{"text":"\/*************************************************************************\n *\n * $RCSfile: YTable.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: oj $ $Date: 2002-11-28 10:27:20 $\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 CONNECTIVITY_MYSQL_TABLE_HXX\n#define CONNECTIVITY_MYSQL_TABLE_HXX\n\n#ifndef CONNECTIVITY_TABLEHELPER_HXX\n#include \"connectivity\/TTableHelper.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_\n#include \n#endif\n#ifndef COMPHELPER_IDPROPERTYARRAYUSAGEHELPER_HXX\n#include \n#endif\n\nnamespace connectivity\n{\n namespace mysql\n {\n\n ::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xColProp);\n\n class OMySQLTable;\n typedef ::comphelper::OIdPropertyArrayUsageHelper< OMySQLTable > OMySQLTable_PROP;\n class OMySQLTable : public OTableHelper\n ,public OMySQLTable_PROP\n {\n sal_Int32 m_nPrivileges; \/\/ we have to set our privileges by our own\n\n \/** executes the statmenmt.\n @param _rStatement\n The statement to execute.\n *\/\n void executeStatement(const ::rtl::OUString& _rStatement );\n protected:\n\n \/** creates the column collection for the table\n @param _rNames\n The column names.\n *\/\n virtual sdbcx::OCollection* createColumns(const TStringVector& _rNames);\n\n \/** creates the key collection for the table\n @param _rNames\n The key names.\n *\/\n virtual sdbcx::OCollection* createKeys(const TStringVector& _rNames);\n\n \/** creates the index collection for the table\n @param _rNames\n The index names.\n *\/\n virtual sdbcx::OCollection* createIndexes(const TStringVector& _rNames);\n\n \/** used to implement the creation of the array helper which is shared amongst all instances of the class.\n This method needs to be implemented in derived classes.\n
\n The method gets called with s_aMutex acquired.\n
\n as long as IPropertyArrayHelper has no virtual destructor, the implementation of ~OPropertyArrayUsageHelper\n assumes that you created an ::cppu::OPropertyArrayHelper when deleting s_pProps.\n @return an pointer to the newly created array helper. Must not be NULL.\n *\/\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper(sal_Int32 nId) const;\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n\n public:\n OMySQLTable( sdbcx::OCollection* _pTables,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection);\n OMySQLTable( sdbcx::OCollection* _pTables,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection,\n const ::rtl::OUString& _Name,\n const ::rtl::OUString& _Type,\n const ::rtl::OUString& _Description = ::rtl::OUString(),\n const ::rtl::OUString& _SchemaName = ::rtl::OUString(),\n const ::rtl::OUString& _CatalogName = ::rtl::OUString(),\n sal_Int32 _nPrivileges = 0\n );\n\n \/\/ ODescriptor\n virtual void construct();\n \/\/ com::sun::star::lang::XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();\n\n \/\/ XAlterTable\n virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& colName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);\n \/**\n returns the ALTER TABLE XXX COLUMN statement\n *\/\n ::rtl::OUString getAlterTableColumnPart(const ::rtl::OUString& _rsColumnName );\n\n \/\/ some methods to alter table structures\n void alterColumnType(sal_Int32 nNewType,const ::rtl::OUString& _rColName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xDescriptor);\n void alterDefaultValue(const ::rtl::OUString& _sNewDefault,const ::rtl::OUString& _rColName);\n void dropDefaultValue(const ::rtl::OUString& _sNewDefault);\n\n };\n }\n}\n#endif \/\/ CONNECTIVITY_MYSQL_TABLE_HXX\n\nINTEGRATION: CWS ooo19126 (1.2.320); FILE MERGED 2005\/09\/05 17:25:43 rt 1.2.320.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: YTable.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 07:33:09 $\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 CONNECTIVITY_MYSQL_TABLE_HXX\n#define CONNECTIVITY_MYSQL_TABLE_HXX\n\n#ifndef CONNECTIVITY_TABLEHELPER_HXX\n#include \"connectivity\/TTableHelper.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_\n#include \n#endif\n#ifndef COMPHELPER_IDPROPERTYARRAYUSAGEHELPER_HXX\n#include \n#endif\n\nnamespace connectivity\n{\n namespace mysql\n {\n\n ::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xColProp);\n\n class OMySQLTable;\n typedef ::comphelper::OIdPropertyArrayUsageHelper< OMySQLTable > OMySQLTable_PROP;\n class OMySQLTable : public OTableHelper\n ,public OMySQLTable_PROP\n {\n sal_Int32 m_nPrivileges; \/\/ we have to set our privileges by our own\n\n \/** executes the statmenmt.\n @param _rStatement\n The statement to execute.\n *\/\n void executeStatement(const ::rtl::OUString& _rStatement );\n protected:\n\n \/** creates the column collection for the table\n @param _rNames\n The column names.\n *\/\n virtual sdbcx::OCollection* createColumns(const TStringVector& _rNames);\n\n \/** creates the key collection for the table\n @param _rNames\n The key names.\n *\/\n virtual sdbcx::OCollection* createKeys(const TStringVector& _rNames);\n\n \/** creates the index collection for the table\n @param _rNames\n The index names.\n *\/\n virtual sdbcx::OCollection* createIndexes(const TStringVector& _rNames);\n\n \/** used to implement the creation of the array helper which is shared amongst all instances of the class.\n This method needs to be implemented in derived classes.\n
\n The method gets called with s_aMutex acquired.\n
\n as long as IPropertyArrayHelper has no virtual destructor, the implementation of ~OPropertyArrayUsageHelper\n assumes that you created an ::cppu::OPropertyArrayHelper when deleting s_pProps.\n @return an pointer to the newly created array helper. Must not be NULL.\n *\/\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper(sal_Int32 nId) const;\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n\n public:\n OMySQLTable( sdbcx::OCollection* _pTables,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection);\n OMySQLTable( sdbcx::OCollection* _pTables,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection,\n const ::rtl::OUString& _Name,\n const ::rtl::OUString& _Type,\n const ::rtl::OUString& _Description = ::rtl::OUString(),\n const ::rtl::OUString& _SchemaName = ::rtl::OUString(),\n const ::rtl::OUString& _CatalogName = ::rtl::OUString(),\n sal_Int32 _nPrivileges = 0\n );\n\n \/\/ ODescriptor\n virtual void construct();\n \/\/ com::sun::star::lang::XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();\n\n \/\/ XAlterTable\n virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& colName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);\n \/**\n returns the ALTER TABLE XXX COLUMN statement\n *\/\n ::rtl::OUString getAlterTableColumnPart(const ::rtl::OUString& _rsColumnName );\n\n \/\/ some methods to alter table structures\n void alterColumnType(sal_Int32 nNewType,const ::rtl::OUString& _rColName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xDescriptor);\n void alterDefaultValue(const ::rtl::OUString& _sNewDefault,const ::rtl::OUString& _rColName);\n void dropDefaultValue(const ::rtl::OUString& _sNewDefault);\n\n };\n }\n}\n#endif \/\/ CONNECTIVITY_MYSQL_TABLE_HXX\n\n<|endoftext|>"} {"text":"#include \"Generator.h\"\n#include \"gtest\/gtest.h\"\n\n#include \n#include \n\n#include \n\nusing namespace Hearthstonepp;\n\nTEST(TaskMeta, TraitConstructors)\n{\n std::random_device rd;\n std::default_random_engine gen(rd());\n\n int sizeTaskID = static_cast(TaskID::_size());\n int sizeMetaData = static_cast(MetaData::GAME_END);\n\n TaskID randID = TaskID::_from_integral(gen() % sizeTaskID);\n MetaData randMeta = static_cast(gen() % sizeMetaData);\n BYTE randUser = gen() % 2;\n\n \/\/ Empty Trait Test\n TaskMetaTrait empty;\n EXPECT_EQ(empty.id, +TaskID::INVALID);\n EXPECT_EQ(empty.status, MetaData::INVALID);\n EXPECT_EQ(empty.userID, TaskMetaTrait::USER_INVALID);\n\n \/\/ TaskID Constructor\n TaskMetaTrait traitID(randID);\n EXPECT_EQ(traitID.id, randID);\n EXPECT_EQ(traitID.status, MetaData::INVALID);\n EXPECT_EQ(traitID.userID, TaskMetaTrait::USER_INVALID);\n\n \/\/ TaskID, Status Constructor\n TaskMetaTrait traitMeta(randID, randMeta);\n EXPECT_EQ(traitMeta.id, randID);\n EXPECT_EQ(traitMeta.status, randMeta);\n EXPECT_EQ(traitMeta.userID, TaskMetaTrait::USER_INVALID);\n\n \/\/ TaskID, Status, User Constructor\n TaskMetaTrait traitUser(randID, randMeta, randUser);\n EXPECT_EQ(traitUser.id, randID);\n EXPECT_EQ(traitUser.status, randMeta);\n EXPECT_EQ(traitUser.userID, randUser);\n\n \/\/ Copy Assignment\n TaskMetaTrait copied(traitUser);\n EXPECT_EQ(copied.id, traitUser.id);\n EXPECT_EQ(copied.status, traitUser.status);\n EXPECT_EQ(copied.userID, traitUser.userID);\n}\n\nTEST(TaskMeta, Constructors)\n{\n constexpr size_t zero = 0;\n std::unique_ptr buffer;\n size_t size = TestUtils::GenerateRandomBuffer(buffer);\n TaskMetaTrait trait = TestUtils::GenerateRandomTrait();\n\n \/\/ Empty Constructor\n TaskMeta meta;\n EXPECT_EQ(meta.id, +TaskID::INVALID);\n EXPECT_EQ(meta.status, MetaData::INVALID);\n EXPECT_EQ(meta.userID, TaskMeta::USER_INVALID);\n EXPECT_EQ(meta.GetBufferSize(), zero);\n EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);\n\n \/\/ Default Constructor\n TaskMeta task(trait, size, buffer.get());\n EXPECT_EQ(trait, task);\n EXPECT_EQ(task.GetBufferSize(), size);\n TestUtils::ExpectBufferEqual(task.GetConstBuffer(), buffer, size);\n\n \/\/ Move Constructor\n TaskMeta moved(trait, size, std::move(buffer));\n EXPECT_EQ(trait, moved);\n EXPECT_EQ(moved.GetBufferSize(), size);\n TestUtils::ExpectBufferEqual(moved.GetConstBuffer(), task.GetConstBuffer(),\n size);\n\n \/\/ Move Assignment\n meta = std::move(moved);\n EXPECT_EQ(trait, meta);\n EXPECT_EQ(meta.GetBufferSize(), size);\n TestUtils::ExpectBufferEqual(meta.GetConstBuffer(), task.GetConstBuffer(),\n size);\n}\n\nTEST(TaskMeta, UniquePtr)\n{\n constexpr size_t zero = 0;\n std::unique_ptr buffer;\n size_t size = TestUtils::GenerateRandomBuffer(buffer);\n\n TaskMetaTrait trait = TestUtils::GenerateRandomTrait();\n TaskMeta meta(trait, size, buffer.get());\n\n \/\/ MoveBuffer\n std::unique_ptr moved = meta.MoveBuffer();\n EXPECT_EQ(meta.GetBufferSize(), zero);\n EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);\n TestUtils::ExpectBufferEqual(buffer, moved, size);\n\n \/\/ reset\n meta = TaskMeta(trait, size, buffer.get());\n meta.reset();\n EXPECT_EQ(meta.GetBufferSize(), zero);\n EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);\n}\n\nTEST(TaskMeta, CopyFrom)\n{\n \/\/ CopyFrom\n TaskMeta meta = TestUtils::GenerateRandomTaskMeta();\n TaskMeta copied = TaskMeta::CopyFrom(meta);\n EXPECT_EQ(meta, copied);\n}\n\nTEST(TaskMeta, ConvertFrom)\n{\n TaskMeta meta = TestUtils::GenerateRandomTaskMeta();\n const auto& buffer = meta.GetConstBuffer();\n size_t size = meta.GetBufferSize();\n\n flatbuffers::FlatBufferBuilder builder(512);\n auto trait = FlatData::TaskMetaTrait(static_cast(meta.id),\n static_cast(meta.status),\n meta.userID);\n\n auto data = builder.CreateVector(buffer.get(), size);\n auto serialized = FlatData::CreateTaskMeta(builder, &trait, data);\n builder.Finish(serialized);\n\n auto deserialized =\n flatbuffers::GetRoot(builder.GetBufferPointer());\n\n \/\/ ConvertFrom\n TaskMeta converted = TaskMeta::ConvertFrom(deserialized);\n EXPECT_EQ(meta, converted);\n}[ci skip] Update TaskMetaTests - Fix header name TestUtils#include \"TestUtils.h\"\n#include \"gtest\/gtest.h\"\n\n#include \n#include \n\n#include \n\nusing namespace Hearthstonepp;\n\nTEST(TaskMeta, TraitConstructors)\n{\n std::random_device rd;\n std::default_random_engine gen(rd());\n\n int sizeTaskID = static_cast(TaskID::_size());\n int sizeMetaData = static_cast(MetaData::GAME_END);\n\n TaskID randID = TaskID::_from_integral(gen() % sizeTaskID);\n MetaData randMeta = static_cast(gen() % sizeMetaData);\n BYTE randUser = gen() % 2;\n\n \/\/ Empty Trait Test\n TaskMetaTrait empty;\n EXPECT_EQ(empty.id, +TaskID::INVALID);\n EXPECT_EQ(empty.status, MetaData::INVALID);\n EXPECT_EQ(empty.userID, TaskMetaTrait::USER_INVALID);\n\n \/\/ TaskID Constructor\n TaskMetaTrait traitID(randID);\n EXPECT_EQ(traitID.id, randID);\n EXPECT_EQ(traitID.status, MetaData::INVALID);\n EXPECT_EQ(traitID.userID, TaskMetaTrait::USER_INVALID);\n\n \/\/ TaskID, Status Constructor\n TaskMetaTrait traitMeta(randID, randMeta);\n EXPECT_EQ(traitMeta.id, randID);\n EXPECT_EQ(traitMeta.status, randMeta);\n EXPECT_EQ(traitMeta.userID, TaskMetaTrait::USER_INVALID);\n\n \/\/ TaskID, Status, User Constructor\n TaskMetaTrait traitUser(randID, randMeta, randUser);\n EXPECT_EQ(traitUser.id, randID);\n EXPECT_EQ(traitUser.status, randMeta);\n EXPECT_EQ(traitUser.userID, randUser);\n\n \/\/ Copy Assignment\n TaskMetaTrait copied(traitUser);\n EXPECT_EQ(copied.id, traitUser.id);\n EXPECT_EQ(copied.status, traitUser.status);\n EXPECT_EQ(copied.userID, traitUser.userID);\n}\n\nTEST(TaskMeta, Constructors)\n{\n constexpr size_t zero = 0;\n std::unique_ptr buffer;\n size_t size = TestUtils::GenerateRandomBuffer(buffer);\n TaskMetaTrait trait = TestUtils::GenerateRandomTrait();\n\n \/\/ Empty Constructor\n TaskMeta meta;\n EXPECT_EQ(meta.id, +TaskID::INVALID);\n EXPECT_EQ(meta.status, MetaData::INVALID);\n EXPECT_EQ(meta.userID, TaskMeta::USER_INVALID);\n EXPECT_EQ(meta.GetBufferSize(), zero);\n EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);\n\n \/\/ Default Constructor\n TaskMeta task(trait, size, buffer.get());\n EXPECT_EQ(trait, task);\n EXPECT_EQ(task.GetBufferSize(), size);\n TestUtils::ExpectBufferEqual(task.GetConstBuffer(), buffer, size);\n\n \/\/ Move Constructor\n TaskMeta moved(trait, size, std::move(buffer));\n EXPECT_EQ(trait, moved);\n EXPECT_EQ(moved.GetBufferSize(), size);\n TestUtils::ExpectBufferEqual(moved.GetConstBuffer(), task.GetConstBuffer(),\n size);\n\n \/\/ Move Assignment\n meta = std::move(moved);\n EXPECT_EQ(trait, meta);\n EXPECT_EQ(meta.GetBufferSize(), size);\n TestUtils::ExpectBufferEqual(meta.GetConstBuffer(), task.GetConstBuffer(),\n size);\n}\n\nTEST(TaskMeta, UniquePtr)\n{\n constexpr size_t zero = 0;\n std::unique_ptr buffer;\n size_t size = TestUtils::GenerateRandomBuffer(buffer);\n\n TaskMetaTrait trait = TestUtils::GenerateRandomTrait();\n TaskMeta meta(trait, size, buffer.get());\n\n \/\/ MoveBuffer\n std::unique_ptr moved = meta.MoveBuffer();\n EXPECT_EQ(meta.GetBufferSize(), zero);\n EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);\n TestUtils::ExpectBufferEqual(buffer, moved, size);\n\n \/\/ reset\n meta = TaskMeta(trait, size, buffer.get());\n meta.reset();\n EXPECT_EQ(meta.GetBufferSize(), zero);\n EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);\n}\n\nTEST(TaskMeta, CopyFrom)\n{\n \/\/ CopyFrom\n TaskMeta meta = TestUtils::GenerateRandomTaskMeta();\n TaskMeta copied = TaskMeta::CopyFrom(meta);\n EXPECT_EQ(meta, copied);\n}\n\nTEST(TaskMeta, ConvertFrom)\n{\n TaskMeta meta = TestUtils::GenerateRandomTaskMeta();\n const auto& buffer = meta.GetConstBuffer();\n size_t size = meta.GetBufferSize();\n\n flatbuffers::FlatBufferBuilder builder(512);\n auto trait = FlatData::TaskMetaTrait(static_cast(meta.id),\n static_cast(meta.status),\n meta.userID);\n\n auto data = builder.CreateVector(buffer.get(), size);\n auto serialized = FlatData::CreateTaskMeta(builder, &trait, data);\n builder.Finish(serialized);\n\n auto deserialized =\n flatbuffers::GetRoot(builder.GetBufferPointer());\n\n \/\/ ConvertFrom\n TaskMeta converted = TaskMeta::ConvertFrom(deserialized);\n EXPECT_EQ(meta, converted);\n}<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ File: thresholder.cpp\n\/\/ Description: Base API for thresholding images in tesseract.\n\/\/ Author: Ray Smith\n\/\/\n\/\/ (C) Copyright 2008, Google Inc.\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\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\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#include \"allheaders.h\"\n\n#include \n\n#include \/\/ for uint32_t\n#include \n\n#include \"otsuthr.h\"\n#include \"tprintf.h\" \/\/ for tprintf\n\n#if defined(USE_OPENCL)\n#include \"openclwrapper.h\" \/\/ for OpenclDevice\n#endif\n\nnamespace tesseract {\n\nImageThresholder::ImageThresholder()\n : pix_(nullptr),\n image_width_(0), image_height_(0),\n pix_channels_(0), pix_wpl_(0),\n scale_(1), yres_(300), estimated_res_(300) {\n SetRectangle(0, 0, 0, 0);\n}\n\nImageThresholder::~ImageThresholder() {\n Clear();\n}\n\n\/\/ Destroy the Pix if there is one, freeing memory.\nvoid ImageThresholder::Clear() {\n pixDestroy(&pix_);\n}\n\n\/\/ Return true if no image has been set.\nbool ImageThresholder::IsEmpty() const {\n return pix_ == nullptr;\n}\n\n\/\/ SetImage makes a copy of all the image data, so it may be deleted\n\/\/ immediately after this call.\n\/\/ Greyscale of 8 and color of 24 or 32 bits per pixel may be given.\n\/\/ Palette color images will not work properly and must be converted to\n\/\/ 24 bit.\n\/\/ Binary images of 1 bit per pixel may also be given but they must be\n\/\/ byte packed with the MSB of the first byte being the first pixel, and a\n\/\/ one pixel is WHITE. For binary images set bytes_per_pixel=0.\nvoid ImageThresholder::SetImage(const unsigned char* imagedata,\n int width, int height,\n int bytes_per_pixel, int bytes_per_line) {\n int bpp = bytes_per_pixel * 8;\n if (bpp == 0) bpp = 1;\n Pix* pix = pixCreate(width, height, bpp == 24 ? 32 : bpp);\n l_uint32* data = pixGetData(pix);\n int wpl = pixGetWpl(pix);\n switch (bpp) {\n case 1:\n for (int y = 0; y < height; ++y, data += wpl, imagedata += bytes_per_line) {\n for (int x = 0; x < width; ++x) {\n if (imagedata[x \/ 8] & (0x80 >> (x % 8)))\n CLEAR_DATA_BIT(data, x);\n else\n SET_DATA_BIT(data, x);\n }\n }\n break;\n\n case 8:\n \/\/ Greyscale just copies the bytes in the right order.\n for (int y = 0; y < height; ++y, data += wpl, imagedata += bytes_per_line) {\n for (int x = 0; x < width; ++x)\n SET_DATA_BYTE(data, x, imagedata[x]);\n }\n break;\n\n case 24:\n \/\/ Put the colors in the correct places in the line buffer.\n for (int y = 0; y < height; ++y, imagedata += bytes_per_line) {\n for (int x = 0; x < width; ++x, ++data) {\n SET_DATA_BYTE(data, COLOR_RED, imagedata[3 * x]);\n SET_DATA_BYTE(data, COLOR_GREEN, imagedata[3 * x + 1]);\n SET_DATA_BYTE(data, COLOR_BLUE, imagedata[3 * x + 2]);\n }\n }\n break;\n\n case 32:\n \/\/ Maintain byte order consistency across different endianness.\n for (int y = 0; y < height; ++y, imagedata += bytes_per_line, data += wpl) {\n for (int x = 0; x < width; ++x) {\n data[x] = (imagedata[x * 4] << 24) | (imagedata[x * 4 + 1] << 16) |\n (imagedata[x * 4 + 2] << 8) | imagedata[x * 4 + 3];\n }\n }\n break;\n\n default:\n tprintf(\"Cannot convert RAW image to Pix with bpp = %d\\n\", bpp);\n }\n SetImage(pix);\n pixDestroy(&pix);\n}\n\n\/\/ Store the coordinates of the rectangle to process for later use.\n\/\/ Doesn't actually do any thresholding.\nvoid ImageThresholder::SetRectangle(int left, int top, int width, int height) {\n rect_left_ = left;\n rect_top_ = top;\n rect_width_ = width;\n rect_height_ = height;\n}\n\n\/\/ Get enough parameters to be able to rebuild bounding boxes in the\n\/\/ original image (not just within the rectangle).\n\/\/ Left and top are enough with top-down coordinates, but\n\/\/ the height of the rectangle and the image are needed for bottom-up.\nvoid ImageThresholder::GetImageSizes(int* left, int* top,\n int* width, int* height,\n int* imagewidth, int* imageheight) {\n *left = rect_left_;\n *top = rect_top_;\n *width = rect_width_;\n *height = rect_height_;\n *imagewidth = image_width_;\n *imageheight = image_height_;\n}\n\n\/\/ Pix vs raw, which to use? Pix is the preferred input for efficiency,\n\/\/ since raw buffers are copied.\n\/\/ SetImage for Pix clones its input, so the source pix may be pixDestroyed\n\/\/ immediately after, but may not go away until after the Thresholder has\n\/\/ finished with it.\nvoid ImageThresholder::SetImage(const Pix* pix) {\n if (pix_ != nullptr)\n pixDestroy(&pix_);\n Pix* src = const_cast(pix);\n int depth;\n pixGetDimensions(src, &image_width_, &image_height_, &depth);\n \/\/ Convert the image as necessary so it is one of binary, plain RGB, or\n \/\/ 8 bit with no colormap. Guarantee that we always end up with our own copy,\n \/\/ not just a clone of the input.\n if (pixGetColormap(src)) {\n Pix* tmp = pixRemoveColormap(src, REMOVE_CMAP_BASED_ON_SRC);\n depth = pixGetDepth(tmp);\n if (depth > 1 && depth < 8) {\n pix_ = pixConvertTo8(tmp, false);\n pixDestroy(&tmp);\n } else {\n pix_ = tmp;\n }\n } else if (depth > 1 && depth < 8) {\n pix_ = pixConvertTo8(src, false);\n } else {\n pix_ = pixCopy(nullptr, src);\n }\n depth = pixGetDepth(pix_);\n pix_channels_ = depth \/ 8;\n pix_wpl_ = pixGetWpl(pix_);\n scale_ = 1;\n estimated_res_ = yres_ = pixGetYRes(pix_);\n Init();\n}\n\n\/\/ Threshold the source image as efficiently as possible to the output Pix.\n\/\/ Creates a Pix and sets pix to point to the resulting pointer.\n\/\/ Caller must use pixDestroy to free the created Pix.\n\/\/\/ Returns false on error.\nbool ImageThresholder::ThresholdToPix(PageSegMode pageseg_mode, Pix** pix) {\n if (image_width_ > INT16_MAX || image_height_ > INT16_MAX) {\n tprintf(\"Image too large: (%d, %d)\\n\", image_width_, image_height_);\n return false;\n }\n if (pix_channels_ == 0) {\n \/\/ We have a binary image, but it still has to be copied, as this API\n \/\/ allows the caller to modify the output.\n Pix* original = GetPixRect();\n *pix = pixCopy(nullptr, original);\n pixDestroy(&original);\n } else {\n OtsuThresholdRectToPix(pix_, pix);\n }\n return true;\n}\n\n\/\/ Gets a pix that contains an 8 bit threshold value at each pixel. The\n\/\/ returned pix may be an integer reduction of the binary image such that\n\/\/ the scale factor may be inferred from the ratio of the sizes, even down\n\/\/ to the extreme of a 1x1 pixel thresholds image.\n\/\/ Ideally the 8 bit threshold should be the exact threshold used to generate\n\/\/ the binary image in ThresholdToPix, but this is not a hard constraint.\n\/\/ Returns nullptr if the input is binary. PixDestroy after use.\nPix* ImageThresholder::GetPixRectThresholds() {\n if (IsBinary()) return nullptr;\n Pix* pix_grey = GetPixRectGrey();\n int width = pixGetWidth(pix_grey);\n int height = pixGetHeight(pix_grey);\n int* thresholds;\n int* hi_values;\n OtsuThreshold(pix_grey, 0, 0, width, height, &thresholds, &hi_values);\n pixDestroy(&pix_grey);\n Pix* pix_thresholds = pixCreate(width, height, 8);\n int threshold = thresholds[0] > 0 ? thresholds[0] : 128;\n pixSetAllArbitrary(pix_thresholds, threshold);\n delete [] thresholds;\n delete [] hi_values;\n return pix_thresholds;\n}\n\n\/\/ Common initialization shared between SetImage methods.\nvoid ImageThresholder::Init() {\n SetRectangle(0, 0, image_width_, image_height_);\n}\n\n\/\/ Get a clone\/copy of the source image rectangle.\n\/\/ The returned Pix must be pixDestroyed.\n\/\/ This function will be used in the future by the page layout analysis, and\n\/\/ the layout analysis that uses it will only be available with Leptonica,\n\/\/ so there is no raw equivalent.\nPix* ImageThresholder::GetPixRect() {\n if (IsFullImage()) {\n \/\/ Just clone the whole thing.\n return pixClone(pix_);\n } else {\n \/\/ Crop to the given rectangle.\n Box* box = boxCreate(rect_left_, rect_top_, rect_width_, rect_height_);\n Pix* cropped = pixClipRectangle(pix_, box, nullptr);\n boxDestroy(&box);\n return cropped;\n }\n}\n\n\/\/ Get a clone\/copy of the source image rectangle, reduced to greyscale,\n\/\/ and at the same resolution as the output binary.\n\/\/ The returned Pix must be pixDestroyed.\n\/\/ Provided to the classifier to extract features from the greyscale image.\nPix* ImageThresholder::GetPixRectGrey() {\n Pix* pix = GetPixRect(); \/\/ May have to be reduced to grey.\n int depth = pixGetDepth(pix);\n if (depth != 8) {\n Pix* result = depth < 8 ? pixConvertTo8(pix, false)\n : pixConvertRGBToLuminance(pix);\n pixDestroy(&pix);\n return result;\n }\n return pix;\n}\n\n\/\/ Otsu thresholds the rectangle, taking the rectangle from *this.\nvoid ImageThresholder::OtsuThresholdRectToPix(Pix* src_pix,\n Pix** out_pix) const {\n int* thresholds;\n int* hi_values;\n\n int num_channels = OtsuThreshold(src_pix, rect_left_, rect_top_, rect_width_,\n rect_height_, &thresholds, &hi_values);\n \/\/ only use opencl if compiled w\/ OpenCL and selected device is opencl\n#ifdef USE_OPENCL\n OpenclDevice od;\n if (num_channels == 4 &&\n od.selectedDeviceIsOpenCL() && rect_top_ == 0 && rect_left_ == 0) {\n od.ThresholdRectToPixOCL((unsigned char*)pixGetData(src_pix), num_channels,\n pixGetWpl(src_pix) * 4, thresholds, hi_values,\n out_pix \/*pix_OCL*\/, rect_height_, rect_width_,\n rect_top_, rect_left_);\n } else {\n#endif\n ThresholdRectToPix(src_pix, num_channels, thresholds, hi_values, out_pix);\n#ifdef USE_OPENCL\n }\n#endif\n delete [] thresholds;\n delete [] hi_values;\n}\n\n\/\/\/ Threshold the rectangle, taking everything except the src_pix\n\/\/\/ from the class, using thresholds\/hi_values to the output pix.\n\/\/\/ NOTE that num_channels is the size of the thresholds and hi_values\n\/\/ arrays and also the bytes per pixel in src_pix.\nvoid ImageThresholder::ThresholdRectToPix(Pix* src_pix,\n int num_channels,\n const int* thresholds,\n const int* hi_values,\n Pix** pix) const {\n *pix = pixCreate(rect_width_, rect_height_, 1);\n uint32_t* pixdata = pixGetData(*pix);\n int wpl = pixGetWpl(*pix);\n int src_wpl = pixGetWpl(src_pix);\n uint32_t* srcdata = pixGetData(src_pix);\n pixSetXRes(*pix, pixGetXRes(src_pix));\n pixSetYRes(*pix, pixGetYRes(src_pix));\n for (int y = 0; y < rect_height_; ++y) {\n const uint32_t* linedata = srcdata + (y + rect_top_) * src_wpl;\n uint32_t* pixline = pixdata + y * wpl;\n for (int x = 0; x < rect_width_; ++x) {\n bool white_result = true;\n for (int ch = 0; ch < num_channels; ++ch) {\n int pixel =\n GET_DATA_BYTE(linedata, (x + rect_left_) * num_channels + ch);\n if (hi_values[ch] >= 0 &&\n (pixel > thresholds[ch]) == (hi_values[ch] == 0)) {\n white_result = false;\n break;\n }\n }\n if (white_result)\n CLEAR_DATA_BIT(pixline, x);\n else\n SET_DATA_BIT(pixline, x);\n }\n }\n}\n\n} \/\/ namespace tesseract.\nFix conversion of images with 16 bpp or 24 bpp to grey\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ File: thresholder.cpp\n\/\/ Description: Base API for thresholding images in tesseract.\n\/\/ Author: Ray Smith\n\/\/\n\/\/ (C) Copyright 2008, Google Inc.\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\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\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#include \"allheaders.h\"\n\n#include \n\n#include \/\/ for uint32_t\n#include \n\n#include \"otsuthr.h\"\n#include \"tprintf.h\" \/\/ for tprintf\n\n#if defined(USE_OPENCL)\n#include \"openclwrapper.h\" \/\/ for OpenclDevice\n#endif\n\nnamespace tesseract {\n\nImageThresholder::ImageThresholder()\n : pix_(nullptr),\n image_width_(0), image_height_(0),\n pix_channels_(0), pix_wpl_(0),\n scale_(1), yres_(300), estimated_res_(300) {\n SetRectangle(0, 0, 0, 0);\n}\n\nImageThresholder::~ImageThresholder() {\n Clear();\n}\n\n\/\/ Destroy the Pix if there is one, freeing memory.\nvoid ImageThresholder::Clear() {\n pixDestroy(&pix_);\n}\n\n\/\/ Return true if no image has been set.\nbool ImageThresholder::IsEmpty() const {\n return pix_ == nullptr;\n}\n\n\/\/ SetImage makes a copy of all the image data, so it may be deleted\n\/\/ immediately after this call.\n\/\/ Greyscale of 8 and color of 24 or 32 bits per pixel may be given.\n\/\/ Palette color images will not work properly and must be converted to\n\/\/ 24 bit.\n\/\/ Binary images of 1 bit per pixel may also be given but they must be\n\/\/ byte packed with the MSB of the first byte being the first pixel, and a\n\/\/ one pixel is WHITE. For binary images set bytes_per_pixel=0.\nvoid ImageThresholder::SetImage(const unsigned char* imagedata,\n int width, int height,\n int bytes_per_pixel, int bytes_per_line) {\n int bpp = bytes_per_pixel * 8;\n if (bpp == 0) bpp = 1;\n Pix* pix = pixCreate(width, height, bpp == 24 ? 32 : bpp);\n l_uint32* data = pixGetData(pix);\n int wpl = pixGetWpl(pix);\n switch (bpp) {\n case 1:\n for (int y = 0; y < height; ++y, data += wpl, imagedata += bytes_per_line) {\n for (int x = 0; x < width; ++x) {\n if (imagedata[x \/ 8] & (0x80 >> (x % 8)))\n CLEAR_DATA_BIT(data, x);\n else\n SET_DATA_BIT(data, x);\n }\n }\n break;\n\n case 8:\n \/\/ Greyscale just copies the bytes in the right order.\n for (int y = 0; y < height; ++y, data += wpl, imagedata += bytes_per_line) {\n for (int x = 0; x < width; ++x)\n SET_DATA_BYTE(data, x, imagedata[x]);\n }\n break;\n\n case 24:\n \/\/ Put the colors in the correct places in the line buffer.\n for (int y = 0; y < height; ++y, imagedata += bytes_per_line) {\n for (int x = 0; x < width; ++x, ++data) {\n SET_DATA_BYTE(data, COLOR_RED, imagedata[3 * x]);\n SET_DATA_BYTE(data, COLOR_GREEN, imagedata[3 * x + 1]);\n SET_DATA_BYTE(data, COLOR_BLUE, imagedata[3 * x + 2]);\n }\n }\n break;\n\n case 32:\n \/\/ Maintain byte order consistency across different endianness.\n for (int y = 0; y < height; ++y, imagedata += bytes_per_line, data += wpl) {\n for (int x = 0; x < width; ++x) {\n data[x] = (imagedata[x * 4] << 24) | (imagedata[x * 4 + 1] << 16) |\n (imagedata[x * 4 + 2] << 8) | imagedata[x * 4 + 3];\n }\n }\n break;\n\n default:\n tprintf(\"Cannot convert RAW image to Pix with bpp = %d\\n\", bpp);\n }\n SetImage(pix);\n pixDestroy(&pix);\n}\n\n\/\/ Store the coordinates of the rectangle to process for later use.\n\/\/ Doesn't actually do any thresholding.\nvoid ImageThresholder::SetRectangle(int left, int top, int width, int height) {\n rect_left_ = left;\n rect_top_ = top;\n rect_width_ = width;\n rect_height_ = height;\n}\n\n\/\/ Get enough parameters to be able to rebuild bounding boxes in the\n\/\/ original image (not just within the rectangle).\n\/\/ Left and top are enough with top-down coordinates, but\n\/\/ the height of the rectangle and the image are needed for bottom-up.\nvoid ImageThresholder::GetImageSizes(int* left, int* top,\n int* width, int* height,\n int* imagewidth, int* imageheight) {\n *left = rect_left_;\n *top = rect_top_;\n *width = rect_width_;\n *height = rect_height_;\n *imagewidth = image_width_;\n *imageheight = image_height_;\n}\n\n\/\/ Pix vs raw, which to use? Pix is the preferred input for efficiency,\n\/\/ since raw buffers are copied.\n\/\/ SetImage for Pix clones its input, so the source pix may be pixDestroyed\n\/\/ immediately after, but may not go away until after the Thresholder has\n\/\/ finished with it.\nvoid ImageThresholder::SetImage(const Pix* pix) {\n if (pix_ != nullptr)\n pixDestroy(&pix_);\n Pix* src = const_cast(pix);\n int depth;\n pixGetDimensions(src, &image_width_, &image_height_, &depth);\n \/\/ Convert the image as necessary so it is one of binary, plain RGB, or\n \/\/ 8 bit with no colormap. Guarantee that we always end up with our own copy,\n \/\/ not just a clone of the input.\n if (pixGetColormap(src)) {\n Pix* tmp = pixRemoveColormap(src, REMOVE_CMAP_BASED_ON_SRC);\n depth = pixGetDepth(tmp);\n if (depth > 1 && depth < 8) {\n pix_ = pixConvertTo8(tmp, false);\n pixDestroy(&tmp);\n } else {\n pix_ = tmp;\n }\n } else if (depth > 1 && depth < 8) {\n pix_ = pixConvertTo8(src, false);\n } else {\n pix_ = pixCopy(nullptr, src);\n }\n depth = pixGetDepth(pix_);\n pix_channels_ = depth \/ 8;\n pix_wpl_ = pixGetWpl(pix_);\n scale_ = 1;\n estimated_res_ = yres_ = pixGetYRes(pix_);\n Init();\n}\n\n\/\/ Threshold the source image as efficiently as possible to the output Pix.\n\/\/ Creates a Pix and sets pix to point to the resulting pointer.\n\/\/ Caller must use pixDestroy to free the created Pix.\n\/\/\/ Returns false on error.\nbool ImageThresholder::ThresholdToPix(PageSegMode pageseg_mode, Pix** pix) {\n if (image_width_ > INT16_MAX || image_height_ > INT16_MAX) {\n tprintf(\"Image too large: (%d, %d)\\n\", image_width_, image_height_);\n return false;\n }\n if (pix_channels_ == 0) {\n \/\/ We have a binary image, but it still has to be copied, as this API\n \/\/ allows the caller to modify the output.\n Pix* original = GetPixRect();\n *pix = pixCopy(nullptr, original);\n pixDestroy(&original);\n } else {\n OtsuThresholdRectToPix(pix_, pix);\n }\n return true;\n}\n\n\/\/ Gets a pix that contains an 8 bit threshold value at each pixel. The\n\/\/ returned pix may be an integer reduction of the binary image such that\n\/\/ the scale factor may be inferred from the ratio of the sizes, even down\n\/\/ to the extreme of a 1x1 pixel thresholds image.\n\/\/ Ideally the 8 bit threshold should be the exact threshold used to generate\n\/\/ the binary image in ThresholdToPix, but this is not a hard constraint.\n\/\/ Returns nullptr if the input is binary. PixDestroy after use.\nPix* ImageThresholder::GetPixRectThresholds() {\n if (IsBinary()) return nullptr;\n Pix* pix_grey = GetPixRectGrey();\n int width = pixGetWidth(pix_grey);\n int height = pixGetHeight(pix_grey);\n int* thresholds;\n int* hi_values;\n OtsuThreshold(pix_grey, 0, 0, width, height, &thresholds, &hi_values);\n pixDestroy(&pix_grey);\n Pix* pix_thresholds = pixCreate(width, height, 8);\n int threshold = thresholds[0] > 0 ? thresholds[0] : 128;\n pixSetAllArbitrary(pix_thresholds, threshold);\n delete [] thresholds;\n delete [] hi_values;\n return pix_thresholds;\n}\n\n\/\/ Common initialization shared between SetImage methods.\nvoid ImageThresholder::Init() {\n SetRectangle(0, 0, image_width_, image_height_);\n}\n\n\/\/ Get a clone\/copy of the source image rectangle.\n\/\/ The returned Pix must be pixDestroyed.\n\/\/ This function will be used in the future by the page layout analysis, and\n\/\/ the layout analysis that uses it will only be available with Leptonica,\n\/\/ so there is no raw equivalent.\nPix* ImageThresholder::GetPixRect() {\n if (IsFullImage()) {\n \/\/ Just clone the whole thing.\n return pixClone(pix_);\n } else {\n \/\/ Crop to the given rectangle.\n Box* box = boxCreate(rect_left_, rect_top_, rect_width_, rect_height_);\n Pix* cropped = pixClipRectangle(pix_, box, nullptr);\n boxDestroy(&box);\n return cropped;\n }\n}\n\n\/\/ Get a clone\/copy of the source image rectangle, reduced to greyscale,\n\/\/ and at the same resolution as the output binary.\n\/\/ The returned Pix must be pixDestroyed.\n\/\/ Provided to the classifier to extract features from the greyscale image.\nPix* ImageThresholder::GetPixRectGrey() {\n auto pix = GetPixRect(); \/\/ May have to be reduced to grey.\n int depth = pixGetDepth(pix);\n if (depth != 8) {\n if (depth == 24) {\n auto tmp = pixConvert24To32(pix);\n pixDestroy(&pix);\n pix = tmp;\n }\n auto result = pixConvertTo8(pix, false);\n pixDestroy(&pix);\n return result;\n }\n return pix;\n}\n\n\/\/ Otsu thresholds the rectangle, taking the rectangle from *this.\nvoid ImageThresholder::OtsuThresholdRectToPix(Pix* src_pix,\n Pix** out_pix) const {\n int* thresholds;\n int* hi_values;\n\n int num_channels = OtsuThreshold(src_pix, rect_left_, rect_top_, rect_width_,\n rect_height_, &thresholds, &hi_values);\n \/\/ only use opencl if compiled w\/ OpenCL and selected device is opencl\n#ifdef USE_OPENCL\n OpenclDevice od;\n if (num_channels == 4 &&\n od.selectedDeviceIsOpenCL() && rect_top_ == 0 && rect_left_ == 0) {\n od.ThresholdRectToPixOCL((unsigned char*)pixGetData(src_pix), num_channels,\n pixGetWpl(src_pix) * 4, thresholds, hi_values,\n out_pix \/*pix_OCL*\/, rect_height_, rect_width_,\n rect_top_, rect_left_);\n } else {\n#endif\n ThresholdRectToPix(src_pix, num_channels, thresholds, hi_values, out_pix);\n#ifdef USE_OPENCL\n }\n#endif\n delete [] thresholds;\n delete [] hi_values;\n}\n\n\/\/\/ Threshold the rectangle, taking everything except the src_pix\n\/\/\/ from the class, using thresholds\/hi_values to the output pix.\n\/\/\/ NOTE that num_channels is the size of the thresholds and hi_values\n\/\/ arrays and also the bytes per pixel in src_pix.\nvoid ImageThresholder::ThresholdRectToPix(Pix* src_pix,\n int num_channels,\n const int* thresholds,\n const int* hi_values,\n Pix** pix) const {\n *pix = pixCreate(rect_width_, rect_height_, 1);\n uint32_t* pixdata = pixGetData(*pix);\n int wpl = pixGetWpl(*pix);\n int src_wpl = pixGetWpl(src_pix);\n uint32_t* srcdata = pixGetData(src_pix);\n pixSetXRes(*pix, pixGetXRes(src_pix));\n pixSetYRes(*pix, pixGetYRes(src_pix));\n for (int y = 0; y < rect_height_; ++y) {\n const uint32_t* linedata = srcdata + (y + rect_top_) * src_wpl;\n uint32_t* pixline = pixdata + y * wpl;\n for (int x = 0; x < rect_width_; ++x) {\n bool white_result = true;\n for (int ch = 0; ch < num_channels; ++ch) {\n int pixel =\n GET_DATA_BYTE(linedata, (x + rect_left_) * num_channels + ch);\n if (hi_values[ch] >= 0 &&\n (pixel > thresholds[ch]) == (hi_values[ch] == 0)) {\n white_result = false;\n break;\n }\n }\n if (white_result)\n CLEAR_DATA_BIT(pixline, x);\n else\n SET_DATA_BIT(pixline, x);\n }\n }\n}\n\n} \/\/ namespace tesseract.\n<|endoftext|>"} {"text":"\/\/#include \r\n#include \"Texture.h\"\r\n\r\n#define STB_IMAGE_IMPLEMENTATION\r\n#include \r\n\r\nconst GLint pixelFormat[5] = { 0, GL_RED, GL_RG, GL_RGB, GL_RGBA };\r\nconst GLint internalFormat[][5] = {\r\n\t{ 0, GL_R8, GL_RG8, GL_RGB8, GL_RGBA8 },\r\n\t{ 0, GL_R16, GL_RG16, GL_RGB16, GL_RGBA16 },\r\n\t{ 0, GL_R16F, GL_RG16F, GL_RGB16F, GL_RGBA16F },\r\n\t{ 0, GL_R32F, GL_RG32F, GL_RGB32F, GL_RGBA32F }\r\n};\r\n\r\nTexture::Texture() {\r\n\twidth = 0;\r\n\theight = 0;\r\n\ttextureID = 0;\r\n}\r\n\r\nTexture::~Texture() {\r\n}\r\n\r\nGLuint Texture::GetTextureID()\r\n{\r\n\treturn textureID;\r\n}\r\n\r\nbool Texture::Load2D(const char* file_name, GLenum wrapping_mode)\r\n{\r\n\tint width, height, chn;\r\n\tunsigned char *data = stbi_load(file_name, &width, &height, &chn, 0);\r\n\r\n\t#ifdef DEBUG_INFO\r\n\t\tcout << width << \" * \" << height << \" channels: \" << chn << endl;\r\n\t#endif\r\n\r\n\tif (data == NULL) {\r\n\t\t#ifdef DEBUG_INFO\r\n\t\tcout << \"Error loading texture: \" << file_name << endl;\r\n\t\t#endif\r\n\t\treturn false;\r\n\t}\r\n\r\n\t#ifdef DEBUG_INFO\r\n\tcout << \"Loaded \" << file_name << endl;\r\n\t#endif\r\n\r\n\tInit2DTexture(width, height);\r\n\r\n\tSetParameters(GL_LINEAR, GL_LINEAR, wrapping_mode);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat[0][chn], width, height, 0, pixelFormat[chn], GL_UNSIGNED_BYTE, (void*)data);\r\n\tglGenerateMipmap(GL_TEXTURE_2D);\r\n\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\r\n\tstbi_image_free(data);\r\n\treturn true;\r\n}\r\n\r\nvoid Texture::Create2DTexture(const unsigned char* img, int width, int height, int chn) {\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat[0][chn], width, height, 0, pixelFormat[chn], GL_UNSIGNED_BYTE, (void*)img);\r\n\tCheckOpenGLError();\r\n\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\nvoid Texture::Create2DTexture(const unsigned short* img, int width, int height, int chn)\r\n{\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat[1][chn], width, height, 0, pixelFormat[chn], GL_UNSIGNED_SHORT, (void*)img);\r\n\tCheckOpenGLError();\r\n\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\nvoid Texture::Create2DTextureFloat(const float* data, int width, int height, int chn, int precision \/*= 16*\/)\r\n{\r\n\tint prec = precision == 32 ? 3 : 2;\r\n\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat[prec][chn], width, height, 0, pixelFormat[chn], GL_FLOAT, (void*)data);\r\n\r\n\tCheckOpenGLError();\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\nvoid Texture::CreateCubeTexture(const float* data, int width, int height, int chn)\r\n{\r\n\tthis->width = width;\r\n\tthis->height = height;\r\n\r\n\tglDeleteTextures(1, &textureID);\r\n\tglGenTextures(1, &textureID);\r\n\tglEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);\r\n\tglBindTexture(GL_TEXTURE_CUBE_MAP, textureID);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\r\n\r\n\t\/\/\tglTexStorage2D(GL_TEXTURE_CUBE_MAP, 1, internalFormat[3][chn], width, height);\r\n\r\n\tfor (int i = 0; i < 6; i++) {\r\n\t\tglTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat[3][chn], width, height, 0, pixelFormat[chn], GL_FLOAT, NULL);\r\n\t}\r\n\r\n\tCheckOpenGLError();\r\n\tglBindTexture(GL_TEXTURE_CUBE_MAP, 0);\r\n}\r\n\r\nvoid Texture::CreateFrameBufferTexture(int width, int height, int targetID)\r\n{\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, 0);\r\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + targetID, GL_TEXTURE_2D, textureID, 0);\r\n\r\n\tCheckOpenGLError();\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\nvoid Texture::CreateDepthBufferTexture(int width, int height)\r\n{\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);\r\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, textureID, 0);\r\n\r\n\tCheckOpenGLError();\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\n\r\nvoid Texture::Bind(GLenum TextureUnit) const\r\n{\r\n\tif (textureID) {\r\n\t\tglActiveTexture(TextureUnit);\r\n\t\tglBindTexture(GL_TEXTURE_2D, textureID);\r\n\t}\r\n}\r\n\r\nvoid Texture::BindForWriting(GLenum textureTarget) const\r\n{\r\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureTarget, textureID, 0);\r\n\tglDrawBuffer(GL_COLOR_ATTACHMENT0);\r\n}\r\n\r\nvoid Texture::SetParameters(GLenum mag_filter, GLenum min_filter, GLenum wrapping_mode)\r\n{\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter); \r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping_mode);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping_mode);\r\n}\r\n\r\nvoid Texture::GetSize(unsigned int &width,unsigned int &height) const\r\n{\r\n\twidth = this->width;\r\n\theight = this->height;\r\n}\r\n\r\nvoid Texture::Init2DTexture(unsigned int width, unsigned int height)\r\n{\r\n\tthis->width = width;\r\n\tthis->height = height;\r\n\r\n\tglDeleteTextures(1, &textureID);\r\n\tglGenTextures(1, &textureID);\r\n\tglBindTexture(GL_TEXTURE_2D, textureID);\r\n\tSetParameters(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE);\r\n}\r\ncode re-factoring\/\/#include \r\n#include \"Texture.h\"\r\n\r\n#define STB_IMAGE_IMPLEMENTATION\r\n#include \r\n\r\nconst GLint pixelFormat[5] = { 0, GL_RED, GL_RG, GL_RGB, GL_RGBA };\r\nconst GLint internalFormat[][5] = {\r\n\t{ 0, GL_R8, GL_RG8, GL_RGB8, GL_RGBA8 },\r\n\t{ 0, GL_R16, GL_RG16, GL_RGB16, GL_RGBA16 },\r\n\t{ 0, GL_R16F, GL_RG16F, GL_RGB16F, GL_RGBA16F },\r\n\t{ 0, GL_R32F, GL_RG32F, GL_RGB32F, GL_RGBA32F }\r\n};\r\n\r\nTexture::Texture() {\r\n\twidth = 0;\r\n\theight = 0;\r\n\ttextureID = 0;\r\n}\r\n\r\nTexture::~Texture() {\r\n}\r\n\r\nGLuint Texture::GetTextureID()\r\n{\r\n\treturn textureID;\r\n}\r\n\r\nbool Texture::Load2D(const char* file_name, GLenum wrapping_mode)\r\n{\r\n\tint width, height, chn;\r\n\tunsigned char *data = stbi_load(file_name, &width, &height, &chn, 0);\r\n\r\n\tif (data == NULL) {\r\n\t\t#ifdef DEBUG_INFO\r\n\t\tcout << \"ERROR loading texture: \" << file_name << endl << endl;\r\n\t\t#endif\r\n\t\treturn false;\r\n\t}\r\n\r\n\t#ifdef DEBUG_INFO\r\n\tcout << \"Loaded \" << file_name << endl;\r\n\tcout << width << \" * \" << height << \" channels: \" << chn << endl << endl;\r\n\t#endif\r\n\r\n\tInit2DTexture(width, height);\r\n\r\n\tSetParameters(GL_LINEAR, GL_LINEAR, wrapping_mode);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat[0][chn], width, height, 0, pixelFormat[chn], GL_UNSIGNED_BYTE, (void*)data);\r\n\tglGenerateMipmap(GL_TEXTURE_2D);\r\n\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\r\n\tstbi_image_free(data);\r\n\treturn true;\r\n}\r\n\r\nvoid Texture::Create2DTexture(const unsigned char* img, int width, int height, int chn) {\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat[0][chn], width, height, 0, pixelFormat[chn], GL_UNSIGNED_BYTE, (void*)img);\r\n\tCheckOpenGLError();\r\n\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\nvoid Texture::Create2DTexture(const unsigned short* img, int width, int height, int chn)\r\n{\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat[1][chn], width, height, 0, pixelFormat[chn], GL_UNSIGNED_SHORT, (void*)img);\r\n\tCheckOpenGLError();\r\n\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\nvoid Texture::Create2DTextureFloat(const float* data, int width, int height, int chn, int precision \/*= 16*\/)\r\n{\r\n\tint prec = precision == 32 ? 3 : 2;\r\n\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat[prec][chn], width, height, 0, pixelFormat[chn], GL_FLOAT, (void*)data);\r\n\r\n\tCheckOpenGLError();\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\nvoid Texture::CreateCubeTexture(const float* data, int width, int height, int chn)\r\n{\r\n\tthis->width = width;\r\n\tthis->height = height;\r\n\r\n\tglDeleteTextures(1, &textureID);\r\n\tglGenTextures(1, &textureID);\r\n\tglEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);\r\n\tglBindTexture(GL_TEXTURE_CUBE_MAP, textureID);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\r\n\r\n\t\/\/\tglTexStorage2D(GL_TEXTURE_CUBE_MAP, 1, internalFormat[3][chn], width, height);\r\n\r\n\tfor (int i = 0; i < 6; i++) {\r\n\t\tglTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat[3][chn], width, height, 0, pixelFormat[chn], GL_FLOAT, NULL);\r\n\t}\r\n\r\n\tCheckOpenGLError();\r\n\tglBindTexture(GL_TEXTURE_CUBE_MAP, 0);\r\n}\r\n\r\nvoid Texture::CreateFrameBufferTexture(int width, int height, int targetID)\r\n{\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, 0);\r\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + targetID, GL_TEXTURE_2D, textureID, 0);\r\n\r\n\tCheckOpenGLError();\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\nvoid Texture::CreateDepthBufferTexture(int width, int height)\r\n{\r\n\tInit2DTexture(width, height);\r\n\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);\r\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, textureID, 0);\r\n\r\n\tCheckOpenGLError();\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n\r\n\r\nvoid Texture::Bind(GLenum TextureUnit) const\r\n{\r\n\tif (textureID) {\r\n\t\tglActiveTexture(TextureUnit);\r\n\t\tglBindTexture(GL_TEXTURE_2D, textureID);\r\n\t}\r\n}\r\n\r\nvoid Texture::BindForWriting(GLenum textureTarget) const\r\n{\r\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureTarget, textureID, 0);\r\n\tglDrawBuffer(GL_COLOR_ATTACHMENT0);\r\n}\r\n\r\nvoid Texture::SetParameters(GLenum mag_filter, GLenum min_filter, GLenum wrapping_mode)\r\n{\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter); \r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping_mode);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping_mode);\r\n}\r\n\r\nvoid Texture::GetSize(unsigned int &width,unsigned int &height) const\r\n{\r\n\twidth = this->width;\r\n\theight = this->height;\r\n}\r\n\r\nvoid Texture::Init2DTexture(unsigned int width, unsigned int height)\r\n{\r\n\tthis->width = width;\r\n\tthis->height = height;\r\n\r\n\tglDeleteTextures(1, &textureID);\r\n\tglGenTextures(1, &textureID);\r\n\tglBindTexture(GL_TEXTURE_2D, textureID);\r\n\tSetParameters(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE);\r\n}\r\n<|endoftext|>"} {"text":"\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * https:\/\/lxqt.org\n *\n * Copyright: 2015 LXQt team\n * Authors:\n * Daniel Drzisga \n *\n * This program or library is free software; you can redistribute it\n * and\/or 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 diinstributed 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\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \n\n#include \"directorymenu.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nDirectoryMenu::DirectoryMenu(const ILXQtPanelPluginStartupInfo &startupInfo) :\n QObject(),\n ILXQtPanelPlugin(startupInfo),\n mMenu(0),\n mDefaultIcon(XdgIcon::fromTheme(\"folder\"))\n{\n mOpenDirectorySignalMapper = new QSignalMapper(this);\n mOpenTerminalSignalMapper = new QSignalMapper(this);\n mMenuSignalMapper = new QSignalMapper(this);\n\n mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n mButton.setAutoRaise(true);\n mButton.setIcon(XdgIcon::fromTheme(\"folder\"));\n\n connect(&mButton, SIGNAL(clicked()), this, SLOT(showMenu()));\n connect(mOpenDirectorySignalMapper, SIGNAL(mapped(QString)), this, SLOT(openDirectory(QString)));\n connect(mOpenTerminalSignalMapper, SIGNAL(mapped(QString)), this, SLOT(openInTerminal(QString)));\n connect(mMenuSignalMapper, SIGNAL(mapped(QString)), this, SLOT(addMenu(QString)));\n\n settingsChanged();\n}\n\nDirectoryMenu::~DirectoryMenu()\n{\n if(mMenu)\n {\n delete mMenu;\n mMenu = 0;\n }\n}\n\nvoid DirectoryMenu::showMenu()\n{\n if(mBaseDirectory.exists())\n {\n buildMenu(mBaseDirectory.absolutePath());\n }\n else\n {\n buildMenu(QDir::homePath());\n }\n\n willShowWindow(mMenu);\n \/\/ Just using Qt`s activateWindow() won't work on some WMs like Kwin.\n \/\/ Solution is to execute menu 1ms later using timer\n mMenu->popup(calculatePopupWindowPos(mMenu->sizeHint()).topLeft());\n}\n\nvoid DirectoryMenu::buildMenu(const QString& path)\n{\n if(mMenu)\n {\n delete mMenu;\n mMenu = 0;\n }\n\n mPathStrings.clear();\n\n mMenu = new QMenu();\n\n addActions(mMenu, path);\n}\n\nvoid DirectoryMenu::openDirectory(const QString& path)\n{\n QDesktopServices::openUrl(QUrl(\"file:\/\/\" + QDir::toNativeSeparators(path)));\n}\n\nvoid DirectoryMenu::openInTerminal(const QString& path)\n{\n QString action = mDefaultTerminal + \" --workdir \" + path;\n QProcess::startDetached(action);\n}\n\nvoid DirectoryMenu::addMenu(QString path)\n{\n QSignalMapper* sender = (QSignalMapper* )QObject::sender();\n QMenu* parentMenu = (QMenu*) sender->mapping(path);\n\n if(parentMenu->isEmpty())\n {\n addActions(parentMenu, path);\n }\n}\n\nvoid DirectoryMenu::addActions(QMenu* menu, const QString& path)\n{\n mPathStrings.push_back(path);\n\n QAction* openDirectoryAction = menu->addAction(XdgIcon::fromTheme(\"folder\"), tr(\"Open\"));\n connect(openDirectoryAction, SIGNAL(triggered()), mOpenDirectorySignalMapper, SLOT(map()));\n mOpenDirectorySignalMapper->setMapping(openDirectoryAction, mPathStrings.back());\n\n QAction* openTerminalAction = menu->addAction(XdgIcon::fromTheme(\"folder\"), tr(\"Open in terminal\"));\n connect(openTerminalAction, SIGNAL(triggered()), mOpenTerminalSignalMapper, SLOT(map()));\n mOpenTerminalSignalMapper->setMapping(openTerminalAction, mPathStrings.back());\n\n menu->addSeparator();\n\n QDir dir(path);\n const QFileInfoList list = dir.entryInfoList();\n\n for (const QFileInfo& entry : list)\n {\n if(entry.isDir() && !entry.isHidden())\n {\n mPathStrings.push_back(entry.fileName());\n\n QMenu* subMenu = menu->addMenu(XdgIcon::fromTheme(\"folder\"), mPathStrings.back());\n\n connect(subMenu, SIGNAL(aboutToShow()), mMenuSignalMapper, SLOT(map()));\n mMenuSignalMapper->setMapping(subMenu, entry.absoluteFilePath());\n }\n }\n}\n\nQDialog* DirectoryMenu::configureDialog()\n{\n return new DirectoryMenuConfiguration(settings());\n}\n\nvoid DirectoryMenu::settingsChanged()\n{\n mBaseDirectory.setPath(settings()->value(\"baseDirectory\", QDir::homePath()).toString());\n\n QString iconPath = settings()->value(\"icon\", QString()).toString();\n QIcon icon = QIcon(iconPath);\n\n if(!icon.isNull())\n {\n QIcon buttonIcon = QIcon(icon);\n if(!buttonIcon.pixmap(QSize(24,24)).isNull())\n {\n mButton.setIcon(buttonIcon);\n return;\n }\n }\n\n mButton.setIcon(mDefaultIcon);\n\n \/\/ Set default terminal\n mDefaultTerminal = settings()->value(\"defaultTerminal\", QString()).toString();\n}\nChanged execution method\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * https:\/\/lxqt.org\n *\n * Copyright: 2015 LXQt team\n * Authors:\n * Daniel Drzisga \n *\n * This program or library is free software; you can redistribute it\n * and\/or 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 diinstributed 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\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \n\n#include \"directorymenu.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nDirectoryMenu::DirectoryMenu(const ILXQtPanelPluginStartupInfo &startupInfo) :\n QObject(),\n ILXQtPanelPlugin(startupInfo),\n mMenu(0),\n mDefaultIcon(XdgIcon::fromTheme(\"folder\"))\n{\n mOpenDirectorySignalMapper = new QSignalMapper(this);\n mOpenTerminalSignalMapper = new QSignalMapper(this);\n mMenuSignalMapper = new QSignalMapper(this);\n\n mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n mButton.setAutoRaise(true);\n mButton.setIcon(XdgIcon::fromTheme(\"folder\"));\n\n connect(&mButton, SIGNAL(clicked()), this, SLOT(showMenu()));\n connect(mOpenDirectorySignalMapper, SIGNAL(mapped(QString)), this, SLOT(openDirectory(QString)));\n connect(mOpenTerminalSignalMapper, SIGNAL(mapped(QString)), this, SLOT(openInTerminal(QString)));\n connect(mMenuSignalMapper, SIGNAL(mapped(QString)), this, SLOT(addMenu(QString)));\n\n settingsChanged();\n}\n\nDirectoryMenu::~DirectoryMenu()\n{\n if(mMenu)\n {\n delete mMenu;\n mMenu = 0;\n }\n}\n\nvoid DirectoryMenu::showMenu()\n{\n if(mBaseDirectory.exists())\n {\n buildMenu(mBaseDirectory.absolutePath());\n }\n else\n {\n buildMenu(QDir::homePath());\n }\n\n willShowWindow(mMenu);\n \/\/ Just using Qt`s activateWindow() won't work on some WMs like Kwin.\n \/\/ Solution is to execute menu 1ms later using timer\n mMenu->popup(calculatePopupWindowPos(mMenu->sizeHint()).topLeft());\n}\n\nvoid DirectoryMenu::buildMenu(const QString& path)\n{\n if(mMenu)\n {\n delete mMenu;\n mMenu = 0;\n }\n\n mPathStrings.clear();\n\n mMenu = new QMenu();\n\n addActions(mMenu, path);\n}\n\nvoid DirectoryMenu::openDirectory(const QString& path)\n{\n QDesktopServices::openUrl(QUrl(\"file:\/\/\" + QDir::toNativeSeparators(path)));\n}\n\nvoid DirectoryMenu::openInTerminal(const QString& path)\n{\n \/\/ Create list of arguments\n QStringList args;\n args << \"--workdir\" << QDir::toNativeSeparators(path);\n \/\/ Execute the default terminal program with arguments\n QProcess::startDetached(mDefaultTerminal, args);\n}\n\nvoid DirectoryMenu::addMenu(QString path)\n{\n QSignalMapper* sender = (QSignalMapper* )QObject::sender();\n QMenu* parentMenu = (QMenu*) sender->mapping(path);\n\n if(parentMenu->isEmpty())\n {\n addActions(parentMenu, path);\n }\n}\n\nvoid DirectoryMenu::addActions(QMenu* menu, const QString& path)\n{\n mPathStrings.push_back(path);\n\n QAction* openDirectoryAction = menu->addAction(XdgIcon::fromTheme(\"folder\"), tr(\"Open\"));\n connect(openDirectoryAction, SIGNAL(triggered()), mOpenDirectorySignalMapper, SLOT(map()));\n mOpenDirectorySignalMapper->setMapping(openDirectoryAction, mPathStrings.back());\n\n QAction* openTerminalAction = menu->addAction(XdgIcon::fromTheme(\"folder\"), tr(\"Open in terminal\"));\n connect(openTerminalAction, SIGNAL(triggered()), mOpenTerminalSignalMapper, SLOT(map()));\n mOpenTerminalSignalMapper->setMapping(openTerminalAction, mPathStrings.back());\n\n menu->addSeparator();\n\n QDir dir(path);\n const QFileInfoList list = dir.entryInfoList();\n\n for (const QFileInfo& entry : list)\n {\n if(entry.isDir() && !entry.isHidden())\n {\n mPathStrings.push_back(entry.fileName());\n\n QMenu* subMenu = menu->addMenu(XdgIcon::fromTheme(\"folder\"), mPathStrings.back());\n\n connect(subMenu, SIGNAL(aboutToShow()), mMenuSignalMapper, SLOT(map()));\n mMenuSignalMapper->setMapping(subMenu, entry.absoluteFilePath());\n }\n }\n}\n\nQDialog* DirectoryMenu::configureDialog()\n{\n return new DirectoryMenuConfiguration(settings());\n}\n\nvoid DirectoryMenu::settingsChanged()\n{\n mBaseDirectory.setPath(settings()->value(\"baseDirectory\", QDir::homePath()).toString());\n\n QString iconPath = settings()->value(\"icon\", QString()).toString();\n QIcon icon = QIcon(iconPath);\n\n if(!icon.isNull())\n {\n QIcon buttonIcon = QIcon(icon);\n if(!buttonIcon.pixmap(QSize(24,24)).isNull())\n {\n mButton.setIcon(buttonIcon);\n return;\n }\n }\n\n mButton.setIcon(mDefaultIcon);\n\n \/\/ Set default terminal\n mDefaultTerminal = settings()->value(\"defaultTerminal\", QString()).toString();\n}\n<|endoftext|>"} {"text":"#ifndef AX_LINEAR_ALGEBRA_H\n#define AX_LINEAR_ALGEBRA_H\n#include \"Vector3.hpp\"\n#include \"Matrix.hpp\"\n\nnamespace ax\n{\n using Realvec = RealVector<3>;\n using Matrix3 = RealMatrix<3,3>;\n using Matrix4 = RealMatrix<4,4>;\n}\n\n#include \"JacobiMethod.hpp\"\n\n#endif \/\/AX_LINEAR_ALGEBRA_H\nadd mat * vec into LinearAlgebra#ifndef AX_LINEAR_ALGEBRA_H\n#define AX_LINEAR_ALGEBRA_H\n#include \"MatrixVectorMultiplication.hpp\"\n\nnamespace ax\n{\n using Realvec = RealVector<3>;\n using Matrix3 = RealMatrix<3,3>;\n using Matrix4 = RealMatrix<4,4>;\n}\n\n#include \"JacobiMethod.hpp\"\n\n#endif \/\/AX_LINEAR_ALGEBRA_H\n<|endoftext|>"} {"text":"#ifndef __CONTROLLER_HH\n#define __CONTROLLER_HH\n\n#include \"calibration.hh\"\n#include \"path.hh\"\n\nconst int BASE = 0;\nconst int SHOULDER = 1;\nconst int ELBOW = 2;\nconst int GRIPPER = 3;\nconst int DRIVES = 4;\n\nclass ControllerBase\n{\npublic:\n ControllerBase(void): m_number(0), m_fraction(0), m_sign(0), m_teachFun(NULL), m_index(0) {\n memset(m_teach, 0, sizeof(m_teach));\n memset(m_configuration, 0, sizeof(m_configuration));\n }\n virtual ~ControllerBase() {}\n Path &curve(int drive) { return m_curve[drive]; }\n int drive(char c) {\n switch (tolower(c)) {\n case 'e':\n return ELBOW;\n case 's':\n return SHOULDER;\n case 'g':\n return GRIPPER;\n default:\n return BASE;\n };\n }\n float target(int drive) {\n return m_curve[drive].target();\n }\n float limit(float value, float lower, float upper) {\n return value < lower ? lower : value > upper ? upper : value;\n }\n float angleToPWM(int drive, float angle) {\n return offset(drive) + angle * resolution(drive);\n }\n float pwmToAngle(int drive, float pwm) {\n return (pwm - offset(drive)) \/ resolution(drive);\n }\n float clipPWM(int drive, float value) {\n return limit(value, lower(drive), upper(drive));\n }\n float clipAngle(int drive, float value) {\n return pwmToAngle(drive, clipPWM(drive, angleToPWM(drive, value)));\n }\n float limitJoint(float value, float other) {\n return limit(value, -45 - other, 45 - other);\n }\n float limitArmAngle(int drive, float value)\n {\n switch (drive) {\n case ELBOW:\n return limitJoint(value, target(SHOULDER));\n case SHOULDER:\n return limitJoint(value, target(ELBOW));\n default:\n return value;\n };\n }\n float limitElbowAngle(int drive, float value, float shoulder)\n {\n return drive == ELBOW ? limitJoint(value, shoulder) : value;\n }\n void saveTeachPoint(int index) {\n for (int i=0; i= 'a' && c <= 'l')\n (this->*m_teachFun)(c - 'a');\n else\n stopDrives();\n resetParser();\n m_teachFun = NULL;\n } else {\n switch (c) {\n case 'r':\n reportReady(drivesReady());\n resetParser();\n break;\n case 't':\n if (hasNumber()) {\n takeConfigurationValue();\n reportRequired(timeRequired(m_configuration));\n } else\n reportTime();\n resetParser();\n break;\n case '.':\n if (m_fraction > 0)\n resetParser();\n else\n m_fraction = 1;\n break;\n case '-':\n m_sign = m_sign == 0 ? -1 : -m_sign;\n m_number = 0;\n m_fraction = 0;\n break;\n case 'b':\n case 'e':\n case 's':\n case 'g':\n case 'B':\n case 'E':\n case 'S':\n case 'G':\n if (hasNumber()) {\n if (isupper(c))\n targetPWM(drive(c), number());\n else\n targetAngle(drive(c), number());\n } else\n if (isupper(c))\n reportPWM(round(angleToPWM(drive(c), m_curve[drive(c)].pos())));\n else\n reportAngle(m_curve[drive(c)].pos());\n resetParser();\n break;\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n m_number = 10 * m_number + (c - '0');\n m_fraction *= 0.1;\n if (m_sign == 0) m_sign = 1;\n break;\n case '\\'':\n m_teachFun = &ControllerBase::loadTeachPoint;\n break;\n case 'm':\n m_teachFun = &ControllerBase::saveTeachPoint;\n break;\n case 'p':\n m_teachFun = &ControllerBase::displayTeachPoint;\n break;\n case ' ':\n takeConfigurationValue();\n break;\n case 'c':\n if (hasNumber()) {\n takeConfigurationValue();\n targetPoint(m_configuration);\n } else\n reportConfiguration(m_curve[0].pos(), m_curve[1].pos(), m_curve[2].pos(), m_curve[3].pos());\n resetParser();\n break;\n case 'l':\n reportLower((lower(0) - offset(0)) \/ resolution(0),\n (lower(1) - offset(1)) \/ resolution(1),\n (lower(2) - offset(2)) \/ resolution(2),\n (lower(3) - offset(3)) \/ resolution(3));\n resetParser();\n break;\n case 'u':\n reportUpper((upper(0) - offset(0)) \/ resolution(0),\n (upper(1) - offset(1)) \/ resolution(1),\n (upper(2) - offset(2)) \/ resolution(2),\n (upper(3) - offset(3)) \/ resolution(3));\n resetParser();\n break;\n default:\n stopDrives();\n };\n };\n }\n virtual int offset(int drive) = 0;\n virtual float resolution(int drive) = 0;\n virtual int lower(int drive) = 0;\n virtual int upper(int drive) = 0;\n virtual void reportReady(bool ready) = 0;\n virtual void reportTime(void) = 0;\n virtual void reportRequired(float time) = 0;\n virtual void reportAngle(float) = 0;\n virtual void reportPWM(int) = 0;\n virtual void reportConfiguration(float, float, float, float) = 0;\n virtual void reportLower(float, float, float, float) = 0;\n virtual void reportUpper(float, float, float, float) = 0;\n virtual void reportTeachPoint(float, float, float, float) = 0;\n virtual void writePWM(int, int) = 0;\nprotected:\n float m_number;\n float m_fraction;\n char m_sign;\n void (ControllerBase::*m_teachFun)(int);\n float m_teach[12][DRIVES];\n int m_index;\n float m_configuration[4];\n Path m_curve[DRIVES];\n};\n\n#endif\nReplace '4' with 'DRIVES'#ifndef __CONTROLLER_HH\n#define __CONTROLLER_HH\n\n#include \"calibration.hh\"\n#include \"path.hh\"\n\nconst int BASE = 0;\nconst int SHOULDER = 1;\nconst int ELBOW = 2;\nconst int GRIPPER = 3;\nconst int DRIVES = 4;\n\nclass ControllerBase\n{\npublic:\n ControllerBase(void): m_number(0), m_fraction(0), m_sign(0), m_teachFun(NULL), m_index(0) {\n memset(m_teach, 0, sizeof(m_teach));\n memset(m_configuration, 0, sizeof(m_configuration));\n }\n virtual ~ControllerBase() {}\n Path &curve(int drive) { return m_curve[drive]; }\n int drive(char c) {\n switch (tolower(c)) {\n case 'e':\n return ELBOW;\n case 's':\n return SHOULDER;\n case 'g':\n return GRIPPER;\n default:\n return BASE;\n };\n }\n float target(int drive) {\n return m_curve[drive].target();\n }\n float limit(float value, float lower, float upper) {\n return value < lower ? lower : value > upper ? upper : value;\n }\n float angleToPWM(int drive, float angle) {\n return offset(drive) + angle * resolution(drive);\n }\n float pwmToAngle(int drive, float pwm) {\n return (pwm - offset(drive)) \/ resolution(drive);\n }\n float clipPWM(int drive, float value) {\n return limit(value, lower(drive), upper(drive));\n }\n float clipAngle(int drive, float value) {\n return pwmToAngle(drive, clipPWM(drive, angleToPWM(drive, value)));\n }\n float limitJoint(float value, float other) {\n return limit(value, -45 - other, 45 - other);\n }\n float limitArmAngle(int drive, float value)\n {\n switch (drive) {\n case ELBOW:\n return limitJoint(value, target(SHOULDER));\n case SHOULDER:\n return limitJoint(value, target(ELBOW));\n default:\n return value;\n };\n }\n float limitElbowAngle(int drive, float value, float shoulder)\n {\n return drive == ELBOW ? limitJoint(value, shoulder) : value;\n }\n void saveTeachPoint(int index) {\n for (int i=0; i= 'a' && c <= 'l')\n (this->*m_teachFun)(c - 'a');\n else\n stopDrives();\n resetParser();\n m_teachFun = NULL;\n } else {\n switch (c) {\n case 'r':\n reportReady(drivesReady());\n resetParser();\n break;\n case 't':\n if (hasNumber()) {\n takeConfigurationValue();\n reportRequired(timeRequired(m_configuration));\n } else\n reportTime();\n resetParser();\n break;\n case '.':\n if (m_fraction > 0)\n resetParser();\n else\n m_fraction = 1;\n break;\n case '-':\n m_sign = m_sign == 0 ? -1 : -m_sign;\n m_number = 0;\n m_fraction = 0;\n break;\n case 'b':\n case 'e':\n case 's':\n case 'g':\n case 'B':\n case 'E':\n case 'S':\n case 'G':\n if (hasNumber()) {\n if (isupper(c))\n targetPWM(drive(c), number());\n else\n targetAngle(drive(c), number());\n } else\n if (isupper(c))\n reportPWM(round(angleToPWM(drive(c), m_curve[drive(c)].pos())));\n else\n reportAngle(m_curve[drive(c)].pos());\n resetParser();\n break;\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n m_number = 10 * m_number + (c - '0');\n m_fraction *= 0.1;\n if (m_sign == 0) m_sign = 1;\n break;\n case '\\'':\n m_teachFun = &ControllerBase::loadTeachPoint;\n break;\n case 'm':\n m_teachFun = &ControllerBase::saveTeachPoint;\n break;\n case 'p':\n m_teachFun = &ControllerBase::displayTeachPoint;\n break;\n case ' ':\n takeConfigurationValue();\n break;\n case 'c':\n if (hasNumber()) {\n takeConfigurationValue();\n targetPoint(m_configuration);\n } else\n reportConfiguration(m_curve[0].pos(), m_curve[1].pos(), m_curve[2].pos(), m_curve[3].pos());\n resetParser();\n break;\n case 'l':\n reportLower((lower(0) - offset(0)) \/ resolution(0),\n (lower(1) - offset(1)) \/ resolution(1),\n (lower(2) - offset(2)) \/ resolution(2),\n (lower(3) - offset(3)) \/ resolution(3));\n resetParser();\n break;\n case 'u':\n reportUpper((upper(0) - offset(0)) \/ resolution(0),\n (upper(1) - offset(1)) \/ resolution(1),\n (upper(2) - offset(2)) \/ resolution(2),\n (upper(3) - offset(3)) \/ resolution(3));\n resetParser();\n break;\n default:\n stopDrives();\n };\n };\n }\n virtual int offset(int drive) = 0;\n virtual float resolution(int drive) = 0;\n virtual int lower(int drive) = 0;\n virtual int upper(int drive) = 0;\n virtual void reportReady(bool ready) = 0;\n virtual void reportTime(void) = 0;\n virtual void reportRequired(float time) = 0;\n virtual void reportAngle(float) = 0;\n virtual void reportPWM(int) = 0;\n virtual void reportConfiguration(float, float, float, float) = 0;\n virtual void reportLower(float, float, float, float) = 0;\n virtual void reportUpper(float, float, float, float) = 0;\n virtual void reportTeachPoint(float, float, float, float) = 0;\n virtual void writePWM(int, int) = 0;\nprotected:\n float m_number;\n float m_fraction;\n char m_sign;\n void (ControllerBase::*m_teachFun)(int);\n float m_teach[12][DRIVES];\n int m_index;\n float m_configuration[DRIVES];\n Path m_curve[DRIVES];\n};\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * @file\n *\n * @brief\n *\n * @copyright BSD License (see doc\/LICENSE.md or http:\/\/www.libelektra.org)\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __GNUC__\n#define TIMER_NOINLINE __attribute__ ((noinline))\n#endif\n\nclass Timer\n{\npublic:\n\t\/\/ options what to do at cleanup\n\tenum option_t\n\t{\n\t\traw_data_cerr, \/\/\/< print name,data\\n (default!)\n\t\tmedian_cerr, \/\/\/< print name,median\\n\n\t\tquiet,\t \/\/\/< print nothing\n\t};\n\n\t\/\/ functions\n\tTIMER_NOINLINE void start ()\n\t{\n\t\tgettimeofday (&begin, nullptr);\n\t}\n\tTIMER_NOINLINE void stop ()\n\t{\n\t\tgettimeofday (&end, nullptr);\n\t\t\/\/ force calculation in long long:\n\t\ttimer_t result = end.tv_sec - begin.tv_sec;\n\t\tresult *= usec_factor;\n\t\tresult += end.tv_usec - begin.tv_usec;\n\t\tresults.push_back (result);\n\t}\n\tstd::string getMedian () const;\n\tTimer (std::string name, option_t option = raw_data_cerr);\n\t~Timer (); \/\/ print csv table at end\n\n\t\/\/ data\n\tstruct timeval begin;\n\tstruct timeval end;\n\ttypedef long long timer_t;\n\ttypedef std::vector results_t;\n\tresults_t results;\n\tstd::string name;\n\toption_t option;\n\tstatic const timer_t usec_factor = 1000000LL;\n};\n\ninline Timer::Timer (std::string name_, option_t option_) : begin (), end (), results (), name (std::move (name_)), option (option_)\n{\n}\n\ninline Timer::~Timer ()\n{\n\tswitch (option)\n\t{\n\tcase raw_data_cerr:\n\t\tfor (auto result : results)\n\t\t{\n\t\t\t\/\/ clang-format off\n\t\t\tstd::cerr << name << \",\"\n\t\t\t\t << result \/ Timer::usec_factor\n\t\t\t\t << \".\"\n\t\t\t\t << std::setw(6)\n\t\t\t\t << std::setfill('0')\n\t\t\t\t << result % Timer::usec_factor\n\t\t\t\t << std::endl;\n\t\t\t\/\/ clang-format on\n\t\t}\n\t\tbreak;\n\tcase median_cerr:\n\t\tstd::cerr << name << \",\" << getMedian () << std::endl;\n\t\tbreak;\n\tcase quiet:\n\t\tbreak;\n\t}\n}\n\nstd::string Timer::getMedian () const\n{\n\tTimer::results_t md = results;\n\tnth_element (md.begin (), md.begin () + md.size () \/ 2, md.end ());\n\tTimer::timer_t r = *(md.begin () + md.size () \/ 2);\n\tstd::ostringstream os;\n\tos << r \/ Timer::usec_factor << \".\" << std::setw (6) << std::setfill ('0') << r % Timer::usec_factor;\n\treturn os.str ();\n}\n\n\ninline std::ostream & operator<< (std::ostream & os, Timer const & t)\n{\n\t\/\/ clang-format off\n\tTimer::timer_t r = t.results.back();\n\tos.width(30);\n\tos.fill(' ');\n\tos << t.name << \"\\t\";\n\tos << r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tr = std::accumulate(t.results.begin(), t.results.end(), 0LL);\n\tos << \"\\t Sum: \"\n\t\t<< r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tr = r \/ t.results.size();\n\tos << \"\\tAvg: \"\n\t\t<< r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tr = *std::min_element(t.results.begin(), t.results.end());\n\tos << \"\\tMin: \"\n\t\t<< r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tr = *std::max_element(t.results.begin(), t.results.end());\n\tos << \"\\tMax: \"\n\t\t<< r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tos << \"\\tMedian: \"\n\t\t<< t.getMedian()\n\t\t<< \" sec\"\n\t\t<< std::endl;\n\t\/\/ clang-format on\n\treturn os;\n}\ncpp: suggestion how to change timer\/**\n * @file\n *\n * @brief\n *\n * @copyright BSD License (see doc\/LICENSE.md or http:\/\/www.libelektra.org)\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __GNUC__\n#define TIMER_NOINLINE __attribute__ ((noinline))\n#endif\n\nclass Timer\n{\npublic:\n\t\/\/ options what to do at cleanup\n\tenum option_t\n\t{\n\t\traw_data_cerr, \/\/\/< print name,data\\n (default!)\n\t\tmedian_cerr, \/\/\/< print name,median\\n\n\t\tquiet,\t \/\/\/< print nothing\n\t};\n\n\t\/\/ functions\n\tTIMER_NOINLINE void start ()\n\t{\n\t\tgettimeofday (&begin, nullptr);\n\t\t\/\/ clock_gettime(CLOCK_MONOTONIC, &begin);\n\t}\n\tTIMER_NOINLINE void stop ()\n\t{\n\t\tgettimeofday (&end, nullptr);\n\t\t\/\/ clock_gettime(CLOCK_MONOTONIC, &end);\n\n\t\t\/\/ force calculation in long long:\n\t\t\/\/ could use timersub here\n\t\ttimer_t result = end.tv_sec - begin.tv_sec;\n\t\tresult *= usec_factor;\n\t\tresult += end.tv_usec - begin.tv_usec;\n\t\tresults.push_back (result);\n\t}\n\tstd::string getMedian () const;\n\tTimer (std::string name, option_t option = raw_data_cerr);\n\t~Timer (); \/\/ print csv table at end\n\n\t\/\/ data\n\tstruct timeval begin;\n\tstruct timeval end;\n\ttypedef long long timer_t;\n\ttypedef std::vector results_t;\n\tresults_t results;\n\tstd::string name;\n\toption_t option;\n\tstatic const timer_t usec_factor = 1000000LL;\n};\n\ninline Timer::Timer (std::string name_, option_t option_) : begin (), end (), results (), name (std::move (name_)), option (option_)\n{\n}\n\ninline Timer::~Timer ()\n{\n\tswitch (option)\n\t{\n\tcase raw_data_cerr:\n\t\tfor (auto result : results)\n\t\t{\n\t\t\t\/\/ clang-format off\n\t\t\tstd::cerr << name << \",\"\n\t\t\t\t << result \/ Timer::usec_factor\n\t\t\t\t << \".\"\n\t\t\t\t << std::setw(6)\n\t\t\t\t << std::setfill('0')\n\t\t\t\t << result % Timer::usec_factor\n\t\t\t\t << std::endl;\n\t\t\t\/\/ clang-format on\n\t\t}\n\t\tbreak;\n\tcase median_cerr:\n\t\tstd::cerr << name << \",\" << getMedian () << std::endl;\n\t\tbreak;\n\tcase quiet:\n\t\tbreak;\n\t}\n}\n\nstd::string Timer::getMedian () const\n{\n\tTimer::results_t md = results;\n\tnth_element (md.begin (), md.begin () + md.size () \/ 2, md.end ());\n\tTimer::timer_t r = *(md.begin () + md.size () \/ 2);\n\tstd::ostringstream os;\n\tos << r \/ Timer::usec_factor << \".\" << std::setw (6) << std::setfill ('0') << r % Timer::usec_factor;\n\treturn os.str ();\n}\n\n\ninline std::ostream & operator<< (std::ostream & os, Timer const & t)\n{\n\t\/\/ clang-format off\n\tTimer::timer_t r = t.results.back();\n\tos.width(30);\n\tos.fill(' ');\n\tos << t.name << \"\\t\";\n\tos << r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tr = std::accumulate(t.results.begin(), t.results.end(), 0LL);\n\tos << \"\\t Sum: \"\n\t\t<< r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tr = r \/ t.results.size();\n\tos << \"\\tAvg: \"\n\t\t<< r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tr = *std::min_element(t.results.begin(), t.results.end());\n\tos << \"\\tMin: \"\n\t\t<< r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tr = *std::max_element(t.results.begin(), t.results.end());\n\tos << \"\\tMax: \"\n\t\t<< r \/ Timer::usec_factor\n\t\t<< \".\"\n\t\t<< std::setw(6)\n\t\t<< std::setfill('0')\n\t\t<< r % Timer::usec_factor\n\t\t<< \" sec\";\n\tos << \"\\tMedian: \"\n\t\t<< t.getMedian()\n\t\t<< \" sec\"\n\t\t<< std::endl;\n\t\/\/ clang-format on\n\treturn os;\n}\n<|endoftext|>"} {"text":"#ifndef K3_UNIQPOLYBUF\n#define K3_UNIQPOLYBUF\n\n#include \n\n#if HAS_LIBDYNAMIC\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \"serialization\/Json.hpp\"\n\n#include \"Common.hpp\"\n#include \"collections\/STLDataspace.hpp\"\n#include \"collections\/Collection.hpp\"\n#include \"collections\/FlatPolyBuffer.hpp\"\n\nnamespace K3 {\nnamespace Libdynamic {\n\ntemplate\nclass UniquePolyBuffer;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Buffer functors.\n\nstruct UPBValueProxy {\n UPBValueProxy(size_t o) : asOffset(true), offset(o) {}\n UPBValueProxy(char* p) : asOffset(false), elem(p) {}\n\n bool asOffset;\n union {\n char* elem;\n size_t offset;\n };\n};\n\ntemplate\nusing UPBKey = std::pair;\n\ntemplate\nstruct UPBEqual : std::binary_function, UPBKey, bool>\n{\n using Container = typename FlatPolyBuffer::Container;\n using UPB = UniquePolyBuffer;\n using ExternalizerT = BufferExternalizer;\n using InternalizerT = BufferInternalizer;\n\n Container* container;\n ExternalizerT etl;\n InternalizerT itl;\n\n UPBEqual(UPB* c)\n : container(c->container.get()),\n etl(container->variable(), ExternalizerT::ExternalizeOp::Reuse),\n itl(container->variable())\n {}\n\n bool operator()(const UPBKey& left, const UPBKey& right) const {\n auto buffer = container->fixed();\n char* lp = left.second.asOffset? buffer_data(buffer) + left.second.offset : left.second.elem;\n char* rp = right.second.asOffset? buffer_data(buffer) + right.second.offset : right.second.elem;\n\n if ( !container->internalized ) {\n if ( left.second.asOffset ) { T::internalize(const_cast(itl), left.first, lp); }\n if ( right.second.asOffset ) { T::internalize(const_cast(itl), right.first, rp); }\n }\n\n bool r = T::equalelem(left.first, lp, right.first, rp);\n\n if ( !container->internalized ) {\n if ( left.second.asOffset ) { T::externalize(const_cast(etl), left.first, lp); }\n if ( right.second.asOffset ) { T::externalize(const_cast(etl), right.first, rp); }\n }\n return r;\n }\n};\n\ntemplate\nstruct UPBHash : std::unary_function, std::size_t>\n{\n using Container = typename FlatPolyBuffer::Container;\n using UPB = UniquePolyBuffer;\n using ExternalizerT = BufferExternalizer;\n using InternalizerT = BufferInternalizer;\n\n Container* container;\n ExternalizerT etl;\n InternalizerT itl;\n\n UPBHash(UPB* c)\n : container(c->container.get()),\n etl(container->variable(), ExternalizerT::ExternalizeOp::Reuse),\n itl(container->variable())\n {}\n\n std::size_t operator()(const UPBKey& k) const {\n std::hash hash;\n size_t h1 = hash(k.first);\n auto buffer = container->fixed();\n char* p = k.second.asOffset? buffer_data(buffer) + k.second.offset : k.second.elem;\n if ( !container->internalized && k.second.asOffset ) {\n T::internalize(const_cast(itl), k.first, p);\n }\n\n boost::hash_combine(h1, T::hashelem(k.first, p));\n\n if ( !container->internalized && k.second.asOffset ) {\n T::externalize(const_cast(etl), k.first, p);\n }\n return h1;\n }\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ UniquePolyBuffer\n\ntemplate\nclass UniquePolyBuffer : public FlatPolyBuffer {\npublic:\n using Super = FlatPolyBuffer;\n using Tag = typename Super::Tag;\n\n using FContainer = typename Super::FContainer;\n using VContainer = typename Super::VContainer;\n using TContainer = typename Super::TContainer;\n\n UniquePolyBuffer()\n : Super(), comparator(this), hasher(this), keys(10, hasher, comparator)\n {}\n\n UniquePolyBuffer(const UniquePolyBuffer& other)\n : Super(other), comparator(this), hasher(this), keys(10, hasher, comparator)\n {\n std::copy(other.keys.begin(), other.keys.end(), std::inserter(keys, keys.begin()));\n }\n\n UniquePolyBuffer(UniquePolyBuffer&& other)\n : Super(std::move(other)),\n comparator(std::move(other.comparator)),\n hasher(std::move(other.hasher)),\n keys(std::move(other.keys))\n {}\n\n UniquePolyBuffer& operator=(const UniquePolyBuffer& other) {\n Super::operator=(other);\n std::copy(other.keys.begin(), other.keys.end(), std::inserter(keys, keys.begin()));\n return *this;\n }\n\n UniquePolyBuffer& operator=(UniquePolyBuffer&& other) {\n comparator = std::move(other.comparator);\n hasher = std::move(other.hasher);\n keys = std::move(other.keys);\n Super::operator=(std::move(other));\n return *this;\n }\n\n ~UniquePolyBuffer() {}\n\n void rebuildKeys() {\n size_t foffset = 0, sz = Super::size(unit_t{});\n for (size_t i = 0; i < sz; ++i) {\n Tag tg = Super::tag_at(i);\n keys.insert(std::make_pair(tg, std::move(UPBValueProxy { foffset })));\n foffset += this->elemsize(tg);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ Tag-specific accessors.\n\n template\n unit_t append(Tag tg, const T& t) {\n UPBValueProxy probe { reinterpret_cast(const_cast(&t)) };\n if ( keys.find(std::make_pair(tg, probe)) == keys.end() ) {\n FContainer* ncf = const_cast(Super::fixedc());\n size_t offset = buffer_size(ncf);\n Super::append(tg, t);\n keys.insert(std::make_pair(tg, std::move(UPBValueProxy { offset })));\n }\n return unit_t{};\n }\n\n \/\/ Clears a container, deleting any backing buffer.\n unit_t clear(unit_t) {\n keys.clear();\n return Super::clear(unit_t{});\n }\n\n unit_t load(const base_string& str) {\n return load(base_string(str));\n }\n\n \/\/ Restores a flat poly buffer from a string.\n unit_t load(base_string&& str) {\n Super::load(std::forward(str));\n rebuildKeys();\n return unit_t{};\n }\n\n template \n void save(archive& a, const unsigned int) const {\n a << boost::serialization::base_object(*this);\n }\n\n template \n void load(archive& a, const unsigned int) {\n a >> boost::serialization::base_object(*this);\n rebuildKeys();\n }\n\n template \n void serialize(archive& a) const {\n Super::serialize(a);\n }\n\n template \n void serialize(archive& a) {\n Super::serialize(a);\n rebuildKeys();\n }\n\n BOOST_SERIALIZATION_SPLIT_MEMBER()\n\nprivate:\n friend class UPBEqual;\n friend class UPBHash;\n UPBEqual comparator;\n UPBHash hasher;\n std::unordered_set, UPBHash, UPBEqual> keys;\n};\n\n}; \/\/ end namespace Libdynamic\n\ntemplate\nusing UniquePolyBuffer = Libdynamic::UniquePolyBuffer;\n\n}; \/\/ end namespace K3\n\n\nnamespace YAML {\ntemplate \nstruct convert> {\n using Tag = typename K3::UniquePolyBuffer::Tag;\n static Node encode(const K3::UniquePolyBuffer& c) {\n Node node;\n bool flag = true;\n c.iterate([&c, &node, &flag](Tag tg, size_t idx, size_t offset){\n if (flag) { flag = false; }\n node.push_back(c.yamlencode(tg, idx, offset));\n });\n if (flag) {\n node = YAML::Load(\"[]\");\n }\n return node;\n }\n\n static bool decode(const Node& node, K3::UniquePolyBuffer& c) {\n for (auto i : node) {\n c.yamldecode(i);\n }\n return true;\n }\n};\n} \/\/ namespace YAML\n\nnamespace JSON {\nusing namespace rapidjson;\ntemplate \nstruct convert> {\n using Tag = typename K3::UniquePolyBuffer::Tag;\n template \n static Value encode(const K3::UniquePolyBuffer& c, Allocator& al) {\n Value v;\n v.SetObject();\n v.AddMember(\"type\", Value(\"UniquePolyBuffer\"), al);\n Value inner;\n inner.SetArray();\n c.iterate([&c, &inner, &al](Tag tg, size_t idx, size_t offset){\n inner.PushBack(c.jsonencode(tg, idx, offset, al), al);\n });\n v.AddMember(\"value\", inner.Move(), al);\n return v;\n }\n};\n} \/\/ namespace JSON\n\n#endif \/\/ HAS_LIBDYNAMIC\n\n#endif\nClearing UPB keys prior to copy assignment#ifndef K3_UNIQPOLYBUF\n#define K3_UNIQPOLYBUF\n\n#include \n\n#if HAS_LIBDYNAMIC\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \"serialization\/Json.hpp\"\n\n#include \"Common.hpp\"\n#include \"collections\/STLDataspace.hpp\"\n#include \"collections\/Collection.hpp\"\n#include \"collections\/FlatPolyBuffer.hpp\"\n\nnamespace K3 {\nnamespace Libdynamic {\n\ntemplate\nclass UniquePolyBuffer;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Buffer functors.\n\nstruct UPBValueProxy {\n UPBValueProxy(size_t o) : asOffset(true), offset(o) {}\n UPBValueProxy(char* p) : asOffset(false), elem(p) {}\n\n bool asOffset;\n union {\n char* elem;\n size_t offset;\n };\n};\n\ntemplate\nusing UPBKey = std::pair;\n\ntemplate\nstruct UPBEqual : std::binary_function, UPBKey, bool>\n{\n using Container = typename FlatPolyBuffer::Container;\n using UPB = UniquePolyBuffer;\n using ExternalizerT = BufferExternalizer;\n using InternalizerT = BufferInternalizer;\n\n Container* container;\n ExternalizerT etl;\n InternalizerT itl;\n\n UPBEqual(UPB* c)\n : container(c->container.get()),\n etl(container->variable(), ExternalizerT::ExternalizeOp::Reuse),\n itl(container->variable())\n {}\n\n bool operator()(const UPBKey& left, const UPBKey& right) const {\n auto buffer = container->fixed();\n char* lp = left.second.asOffset? buffer_data(buffer) + left.second.offset : left.second.elem;\n char* rp = right.second.asOffset? buffer_data(buffer) + right.second.offset : right.second.elem;\n\n if ( !container->internalized ) {\n if ( left.second.asOffset ) { T::internalize(const_cast(itl), left.first, lp); }\n if ( right.second.asOffset ) { T::internalize(const_cast(itl), right.first, rp); }\n }\n\n bool r = T::equalelem(left.first, lp, right.first, rp);\n\n if ( !container->internalized ) {\n if ( left.second.asOffset ) { T::externalize(const_cast(etl), left.first, lp); }\n if ( right.second.asOffset ) { T::externalize(const_cast(etl), right.first, rp); }\n }\n return r;\n }\n};\n\ntemplate\nstruct UPBHash : std::unary_function, std::size_t>\n{\n using Container = typename FlatPolyBuffer::Container;\n using UPB = UniquePolyBuffer;\n using ExternalizerT = BufferExternalizer;\n using InternalizerT = BufferInternalizer;\n\n Container* container;\n ExternalizerT etl;\n InternalizerT itl;\n\n UPBHash(UPB* c)\n : container(c->container.get()),\n etl(container->variable(), ExternalizerT::ExternalizeOp::Reuse),\n itl(container->variable())\n {}\n\n std::size_t operator()(const UPBKey& k) const {\n std::hash hash;\n size_t h1 = hash(k.first);\n auto buffer = container->fixed();\n char* p = k.second.asOffset? buffer_data(buffer) + k.second.offset : k.second.elem;\n if ( !container->internalized && k.second.asOffset ) {\n T::internalize(const_cast(itl), k.first, p);\n }\n\n boost::hash_combine(h1, T::hashelem(k.first, p));\n\n if ( !container->internalized && k.second.asOffset ) {\n T::externalize(const_cast(etl), k.first, p);\n }\n return h1;\n }\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ UniquePolyBuffer\n\ntemplate\nclass UniquePolyBuffer : public FlatPolyBuffer {\npublic:\n using Super = FlatPolyBuffer;\n using Tag = typename Super::Tag;\n\n using FContainer = typename Super::FContainer;\n using VContainer = typename Super::VContainer;\n using TContainer = typename Super::TContainer;\n\n UniquePolyBuffer()\n : Super(), comparator(this), hasher(this), keys(10, hasher, comparator)\n {}\n\n UniquePolyBuffer(const UniquePolyBuffer& other)\n : Super(other), comparator(this), hasher(this), keys(10, hasher, comparator)\n {\n std::copy(other.keys.begin(), other.keys.end(), std::inserter(keys, keys.begin()));\n }\n\n UniquePolyBuffer(UniquePolyBuffer&& other)\n : Super(std::move(other)),\n comparator(std::move(other.comparator)),\n hasher(std::move(other.hasher)),\n keys(std::move(other.keys))\n {}\n\n UniquePolyBuffer& operator=(const UniquePolyBuffer& other) {\n Super::operator=(other);\n keys.clear();\n std::copy(other.keys.begin(), other.keys.end(), std::inserter(keys, keys.begin()));\n return *this;\n }\n\n UniquePolyBuffer& operator=(UniquePolyBuffer&& other) {\n comparator = std::move(other.comparator);\n hasher = std::move(other.hasher);\n keys = std::move(other.keys);\n Super::operator=(std::move(other));\n return *this;\n }\n\n ~UniquePolyBuffer() {}\n\n void rebuildKeys() {\n size_t foffset = 0, sz = Super::size(unit_t{});\n for (size_t i = 0; i < sz; ++i) {\n Tag tg = Super::tag_at(i);\n keys.insert(std::make_pair(tg, std::move(UPBValueProxy { foffset })));\n foffset += this->elemsize(tg);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ Tag-specific accessors.\n\n template\n unit_t append(Tag tg, const T& t) {\n UPBValueProxy probe { reinterpret_cast(const_cast(&t)) };\n if ( keys.find(std::make_pair(tg, probe)) == keys.end() ) {\n FContainer* ncf = const_cast(Super::fixedc());\n size_t offset = buffer_size(ncf);\n Super::append(tg, t);\n keys.insert(std::make_pair(tg, std::move(UPBValueProxy { offset })));\n }\n return unit_t{};\n }\n\n \/\/ Clears a container, deleting any backing buffer.\n unit_t clear(unit_t) {\n keys.clear();\n return Super::clear(unit_t{});\n }\n\n unit_t load(const base_string& str) {\n return load(base_string(str));\n }\n\n \/\/ Restores a flat poly buffer from a string.\n unit_t load(base_string&& str) {\n Super::load(std::forward(str));\n rebuildKeys();\n return unit_t{};\n }\n\n template \n void save(archive& a, const unsigned int) const {\n a << boost::serialization::base_object(*this);\n }\n\n template \n void load(archive& a, const unsigned int) {\n a >> boost::serialization::base_object(*this);\n rebuildKeys();\n }\n\n template \n void serialize(archive& a) const {\n Super::serialize(a);\n }\n\n template \n void serialize(archive& a) {\n Super::serialize(a);\n rebuildKeys();\n }\n\n BOOST_SERIALIZATION_SPLIT_MEMBER()\n\nprivate:\n friend class UPBEqual;\n friend class UPBHash;\n UPBEqual comparator;\n UPBHash hasher;\n std::unordered_set, UPBHash, UPBEqual> keys;\n};\n\n}; \/\/ end namespace Libdynamic\n\ntemplate\nusing UniquePolyBuffer = Libdynamic::UniquePolyBuffer;\n\n}; \/\/ end namespace K3\n\n\nnamespace YAML {\ntemplate \nstruct convert> {\n using Tag = typename K3::UniquePolyBuffer::Tag;\n static Node encode(const K3::UniquePolyBuffer& c) {\n Node node;\n bool flag = true;\n c.iterate([&c, &node, &flag](Tag tg, size_t idx, size_t offset){\n if (flag) { flag = false; }\n node.push_back(c.yamlencode(tg, idx, offset));\n });\n if (flag) {\n node = YAML::Load(\"[]\");\n }\n return node;\n }\n\n static bool decode(const Node& node, K3::UniquePolyBuffer& c) {\n for (auto i : node) {\n c.yamldecode(i);\n }\n return true;\n }\n};\n} \/\/ namespace YAML\n\nnamespace JSON {\nusing namespace rapidjson;\ntemplate \nstruct convert> {\n using Tag = typename K3::UniquePolyBuffer::Tag;\n template \n static Value encode(const K3::UniquePolyBuffer& c, Allocator& al) {\n Value v;\n v.SetObject();\n v.AddMember(\"type\", Value(\"UniquePolyBuffer\"), al);\n Value inner;\n inner.SetArray();\n c.iterate([&c, &inner, &al](Tag tg, size_t idx, size_t offset){\n inner.PushBack(c.jsonencode(tg, idx, offset, al), al);\n });\n v.AddMember(\"value\", inner.Move(), al);\n return v;\n }\n};\n} \/\/ namespace JSON\n\n#endif \/\/ HAS_LIBDYNAMIC\n\n#endif\n<|endoftext|>"} {"text":"#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 \n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pairpii;\ntypedef pairpll;\ntypedef pairpdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<>b;\n\n\treturn ;\n}\n\nvoid Solve(){\n\tint lena;\n\tlena =strlen(a);\n\n\tREP(i,0,lena-1){\n\t\ta[lena+i]=a[i];\n\t}\n\ta[lena*2]=0;\n\n\tcout<>a)\n\tInit(),Solve();\n\treturn 0;\n}update hdu2203#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 \n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pairpii;\ntypedef pairpll;\ntypedef pairpdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<>b;\n\n\treturn ;\n}\n\nvoid Solve(){\n\tint lena;\n\tlena =strlen(a);\n\n\tREP(i,0,lena-1){\n\t\ta[lena+i]=a[i];\n\t}\n\ta[lena*2]=0;\n\n\tcout<>a)\n\tInit(),Solve();\n\treturn 0;\n}<|endoftext|>"} {"text":"#include \"my_application.h\"\n\nint main(int argc, char** argv) {\n g_autoptr(MyApplication) app = my_application_new();\n return g_application_run(G_APPLICATION(app), argc, argv);\n}\nensure taqo runs on x11 backend#include \"my_application.h\"\n\nint main(int argc, char** argv) {\n \/\/ Only X11 is currently supported.\n \/\/ Wayland support is being developed: https:\/\/github.com\/flutter\/flutter\/issues\/57932.\n gdk_set_allowed_backends(\"x11\");\n \n g_autoptr(MyApplication) app = my_application_new();\n return g_application_run(G_APPLICATION(app), argc, argv);\n}\n<|endoftext|>"} {"text":"#include \"hid.h\"\n#include \"base\/debug.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define KEY_LENGTH 255\n\nstatic unsigned short device_id[][2] = {\n {0x046D, 0xC29B} \/* Logitech G27 *\/\n};\n\nstatic unsigned short keys[KEY_LENGTH] = {0};\nstatic unsigned short keys_index = 0;\n\nvoid hid_poll(LPARAM lParam)\n{\n unsigned int buffer_size;\n \n GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &buffer_size,\n sizeof(RAWINPUTHEADER));\n\n RAWINPUT *buffer = (RAWINPUT*)malloc(buffer_size);\n \n GetRawInputData((HRAWINPUT)lParam, RID_INPUT, buffer, &buffer_size,\n sizeof(RAWINPUTHEADER));\n \n GetRawInputDeviceInfo(buffer->header.hDevice, RIDI_PREPARSEDDATA,\n NULL, &buffer_size);\n \n \n PHIDP_PREPARSED_DATA preparsed_data = (PHIDP_PREPARSED_DATA)malloc(buffer_size);\n GetRawInputDeviceInfo(buffer->header.hDevice, RIDI_PREPARSEDDATA,\n preparsed_data, &buffer_size);\n \n PHIDP_CAPS caps = (PHIDP_CAPS)malloc(sizeof(HIDP_CAPS));\n\n HidP_GetCaps(preparsed_data, caps);\n\n GUID device_guid;\n HidD_GetHidGuid(&device_guid);\n \n wchar_t product_string[sizeof(wchar_t) * 128] = {0};\n wchar_t manufacturer_string[sizeof(wchar_t) * 128] = {0};\n wchar_t serial_number[sizeof(wchar_t) * 128] = {0};\n\n GetRawInputDeviceInfo(buffer->header.hDevice, RIDI_DEVICENAME,\n NULL, &buffer_size);\n\n wchar_t *name = (wchar_t*)malloc(sizeof(wchar_t) * (buffer_size+1));\n \n GetRawInputDeviceInfo(buffer->header.hDevice, RIDI_DEVICENAME,\n name, &buffer_size);\n \n HANDLE hid = CreateFile(name, GENERIC_READ | GENERIC_WRITE,\n FILE_SHARE_READ | FILE_SHARE_WRITE,\n NULL, OPEN_EXISTING, NULL, NULL);\n BOOL h = true;\n \n if (hid != INVALID_HANDLE_VALUE) {\n h = HidD_GetProductString(hid, product_string, sizeof(wchar_t)*128);\n h = HidD_GetManufacturerString(hid, manufacturer_string, sizeof(wchar_t)*128);\n h = HidD_GetSerialNumberString(hid, serial_number, sizeof(wchar_t)*128);\n }\n\n unsigned short caps_length = caps->NumberInputButtonCaps;\n \n PHIDP_BUTTON_CAPS button_caps =\n (PHIDP_BUTTON_CAPS)malloc(sizeof(HIDP_BUTTON_CAPS) * caps->NumberInputButtonCaps);\n \n \n HidP_GetButtonCaps(HidP_Input, button_caps, &caps_length, preparsed_data);\n \n unsigned char num_buttons =\n button_caps->Range.UsageMax - button_caps->Range.UsageMin + 1;\n \n PHIDP_VALUE_CAPS value_caps =\n (PHIDP_VALUE_CAPS)malloc(sizeof(HIDP_VALUE_CAPS) * caps->NumberInputValueCaps);\n\n caps_length = caps->NumberInputValueCaps;\n HidP_GetValueCaps(HidP_Input, value_caps, &caps_length, preparsed_data);\n\n unsigned long usage_length = num_buttons;\n PUSAGE usage = (PUSAGE)malloc(sizeof(USAGE) * usage_length);\n long ret;\n ret = HidP_GetUsages(HidP_Input, button_caps->UsagePage, 0, usage, &usage_length,\n preparsed_data, (PCHAR)buffer->data.hid.bRawData,\n buffer->data.hid.dwSizeHid);\n\n \/* This can be improved drastically, iterate over keys first then usage *\/\n for (int i = 0; i < usage_length; i++) {\n \n bool present = false;\n for (int x = 0; x <= keys_index; x++) {\n \n if (keys[x] == usage[i]) {\n present = true;\n break;\n }\n \n }\n\n \/* If not in key array *\/\n if (!present) {\n keys[keys_index] = usage[i];\n LOGF(DEBUG, \"Button %d pressed (%S %S)\",\n usage[i],\n (manufacturer_string[0] == '\\0') ? L\"*\": manufacturer_string,\n (product_string[0] == '\\0') ? L\"*\": product_string);\n keys_index++;\n }\n }\n\n \/* Some key(s) was released *\/\n \/* This block is assuming the smallest button value is 1 *\/\n if (keys_index > usage_length) {\n for (int i = 0; i <= KEY_LENGTH; i++) {\n bool present = false;\n \n for (int x = 0; x <= usage_length; x++) {\n if (keys[i] == usage[x]) {\n present = true;\n break;\n }\n }\n if (!present) {\n LOGF(DEBUG, \"Button %d pressed (%S %S)\",\n keys[i],\n (manufacturer_string[0] == '\\0') ? L\"*\": manufacturer_string,\n (product_string[0] == '\\0') ? L\"*\": product_string);\n keys[i] = 0;\n keys_index--;\n }\n }\n }\n \n unsigned long usage_value;\n for (int i = 0; i < caps->NumberInputValueCaps; i++) {\n \n HidP_GetUsageValue(HidP_Input, value_caps[i].UsagePage, 0,\n value_caps[i].Range.UsageMin, &usage_value,\n preparsed_data, (PCHAR)buffer->data.hid.bRawData,\n buffer->data.hid.dwSizeHid);\n ret++;\n }\n \n free(buffer);\n free(preparsed_data);\n free(button_caps);\n free(usage);\n\n}\n\nvoid enumerate_devices()\n{\n \/* Check if there are recgonized devices plugged in *\/\n unsigned int num_devices = 0;\n LOGF(DEBUG, \"Enumerating system HID devices (manufacturer product vId pId)\");\n GetRawInputDeviceList(NULL, &num_devices, sizeof(RAWINPUTDEVICELIST));\n\n if (num_devices <= 0) {\n DEXIT_PROCESS(L\"Failed to enumerate system devices\", 0);\n }\n\n RAWINPUTDEVICELIST *devices =\n (RAWINPUTDEVICELIST*)malloc(num_devices * sizeof(RAWINPUTDEVICELIST));\n \n if (!GetRawInputDeviceList(devices, &num_devices, sizeof(RAWINPUTDEVICELIST))) {\n DEXIT_PROCESS(L\"Failed to enumerate system devices\", GetLastError());\n }\n\n for (int i = 0; i < num_devices; i++) {\n unsigned int size = 0;\n int ret = 0;\n\n ret = GetRawInputDeviceInfo(devices[i].hDevice, RIDI_DEVICENAME, NULL, &size);\n \n wchar_t *name = (wchar_t*)malloc(sizeof(wchar_t) * (size+1));\n \n ret = GetRawInputDeviceInfo(devices[i].hDevice, RIDI_DEVICENAME, name, &size);\n \n \n ret = GetRawInputDeviceInfo(devices[i].hDevice, RIDI_DEVICEINFO, NULL, &size);\n\n PRID_DEVICE_INFO device_info =\n (PRID_DEVICE_INFO)malloc(size);\n \n ret = GetRawInputDeviceInfo(devices[i].hDevice, RIDI_DEVICEINFO, device_info, &size);\n \n HANDLE hid_handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE,\n FILE_SHARE_READ | FILE_SHARE_WRITE,\n NULL, OPEN_ALWAYS,\n FILE_FLAG_OVERLAPPED, NULL);\n \n wchar_t product_string[sizeof(wchar_t) * 128] = {0};\n wchar_t manufacturer_string[sizeof(wchar_t) * 128] = {0};\n wchar_t serial_number[sizeof(wchar_t) * 128] = {0};\n\n if (hid_handle != INVALID_HANDLE_VALUE) {\n ret = HidD_GetManufacturerString(hid_handle, manufacturer_string, sizeof(wchar_t) * 128);\n ret = HidD_GetProductString(hid_handle, product_string, sizeof(wchar_t) * 128);\n ret = HidD_GetSerialNumberString(hid_handle, serial_number, sizeof(wchar_t) * 128);\n\n LOGF(INFO, \"device %S %S %04x %04x\",\n (manufacturer_string[0] == '\\0') ? L\"*\": manufacturer_string,\n (product_string[0] == '\\0') ? L\"*\": product_string,\n device_info->hid.dwVendorId,\n device_info->hid.dwProductId);\n \n CloseHandle(hid_handle);\n }\n \n free(device_info);\n free(name);\n }\n \n free(devices);\n}\n\nvoid register_devices(HWND hWnd)\n{\n char debug[256];\n wchar_t debug_wide[256];\n \n RAWINPUTDEVICE wheel_input;\n\n LOGF(DEBUG, \"This is a debug log from hid module\");\n\n wheel_input.usUsagePage = 1;\n wheel_input.usUsage = 4;\n wheel_input.dwFlags = RIDEV_INPUTSINK;\n wheel_input.hwndTarget = hWnd;\n\n if (!RegisterRawInputDevices(&wheel_input, 1, sizeof(RAWINPUTDEVICE))) {\n LOGF(FATAL, \"failed to register HID devices\");\n DEXIT_PROCESS(L\"Failed to register HID devices\", GetLastError());\n }\n \n}\nFix string typo#include \"hid.h\"\n#include \"base\/debug.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define KEY_LENGTH 255\n\nstatic unsigned short device_id[][2] = {\n {0x046D, 0xC29B} \/* Logitech G27 *\/\n};\n\nstatic unsigned short keys[KEY_LENGTH] = {0};\nstatic unsigned short keys_index = 0;\n\nvoid hid_poll(LPARAM lParam)\n{\n unsigned int buffer_size;\n \n GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &buffer_size,\n sizeof(RAWINPUTHEADER));\n\n RAWINPUT *buffer = (RAWINPUT*)malloc(buffer_size);\n \n GetRawInputData((HRAWINPUT)lParam, RID_INPUT, buffer, &buffer_size,\n sizeof(RAWINPUTHEADER));\n \n GetRawInputDeviceInfo(buffer->header.hDevice, RIDI_PREPARSEDDATA,\n NULL, &buffer_size);\n \n \n PHIDP_PREPARSED_DATA preparsed_data = (PHIDP_PREPARSED_DATA)malloc(buffer_size);\n GetRawInputDeviceInfo(buffer->header.hDevice, RIDI_PREPARSEDDATA,\n preparsed_data, &buffer_size);\n \n PHIDP_CAPS caps = (PHIDP_CAPS)malloc(sizeof(HIDP_CAPS));\n\n HidP_GetCaps(preparsed_data, caps);\n\n GUID device_guid;\n HidD_GetHidGuid(&device_guid);\n \n wchar_t product_string[sizeof(wchar_t) * 128] = {0};\n wchar_t manufacturer_string[sizeof(wchar_t) * 128] = {0};\n wchar_t serial_number[sizeof(wchar_t) * 128] = {0};\n\n GetRawInputDeviceInfo(buffer->header.hDevice, RIDI_DEVICENAME,\n NULL, &buffer_size);\n\n wchar_t *name = (wchar_t*)malloc(sizeof(wchar_t) * (buffer_size+1));\n \n GetRawInputDeviceInfo(buffer->header.hDevice, RIDI_DEVICENAME,\n name, &buffer_size);\n \n HANDLE hid = CreateFile(name, GENERIC_READ | GENERIC_WRITE,\n FILE_SHARE_READ | FILE_SHARE_WRITE,\n NULL, OPEN_EXISTING, NULL, NULL);\n BOOL h = true;\n \n if (hid != INVALID_HANDLE_VALUE) {\n h = HidD_GetProductString(hid, product_string, sizeof(wchar_t)*128);\n h = HidD_GetManufacturerString(hid, manufacturer_string, sizeof(wchar_t)*128);\n h = HidD_GetSerialNumberString(hid, serial_number, sizeof(wchar_t)*128);\n }\n\n unsigned short caps_length = caps->NumberInputButtonCaps;\n \n PHIDP_BUTTON_CAPS button_caps =\n (PHIDP_BUTTON_CAPS)malloc(sizeof(HIDP_BUTTON_CAPS) * caps->NumberInputButtonCaps);\n \n \n HidP_GetButtonCaps(HidP_Input, button_caps, &caps_length, preparsed_data);\n \n unsigned char num_buttons =\n button_caps->Range.UsageMax - button_caps->Range.UsageMin + 1;\n \n PHIDP_VALUE_CAPS value_caps =\n (PHIDP_VALUE_CAPS)malloc(sizeof(HIDP_VALUE_CAPS) * caps->NumberInputValueCaps);\n\n caps_length = caps->NumberInputValueCaps;\n HidP_GetValueCaps(HidP_Input, value_caps, &caps_length, preparsed_data);\n\n unsigned long usage_length = num_buttons;\n PUSAGE usage = (PUSAGE)malloc(sizeof(USAGE) * usage_length);\n long ret;\n ret = HidP_GetUsages(HidP_Input, button_caps->UsagePage, 0, usage, &usage_length,\n preparsed_data, (PCHAR)buffer->data.hid.bRawData,\n buffer->data.hid.dwSizeHid);\n\n \/* This can be improved drastically, iterate over keys first then usage *\/\n for (int i = 0; i < usage_length; i++) {\n \n bool present = false;\n for (int x = 0; x <= keys_index; x++) {\n \n if (keys[x] == usage[i]) {\n present = true;\n break;\n }\n \n }\n\n \/* If not in key array *\/\n if (!present) {\n keys[keys_index] = usage[i];\n LOGF(DEBUG, \"Button %d pressed (%S %S)\",\n usage[i],\n (manufacturer_string[0] == '\\0') ? L\"*\": manufacturer_string,\n (product_string[0] == '\\0') ? L\"*\": product_string);\n keys_index++;\n }\n }\n\n \/* Some key(s) was released *\/\n \/* This block is assuming the smallest button value is 1 *\/\n if (keys_index > usage_length) {\n for (int i = 0; i <= KEY_LENGTH; i++) {\n bool present = false;\n \n for (int x = 0; x <= usage_length; x++) {\n if (keys[i] == usage[x]) {\n present = true;\n break;\n }\n }\n if (!present) {\n LOGF(DEBUG, \"Button %d released (%S %S)\",\n keys[i],\n (manufacturer_string[0] == '\\0') ? L\"*\": manufacturer_string,\n (product_string[0] == '\\0') ? L\"*\": product_string);\n keys[i] = 0;\n keys_index--;\n }\n }\n }\n \n unsigned long usage_value;\n for (int i = 0; i < caps->NumberInputValueCaps; i++) {\n \n HidP_GetUsageValue(HidP_Input, value_caps[i].UsagePage, 0,\n value_caps[i].Range.UsageMin, &usage_value,\n preparsed_data, (PCHAR)buffer->data.hid.bRawData,\n buffer->data.hid.dwSizeHid);\n ret++;\n }\n \n free(buffer);\n free(preparsed_data);\n free(button_caps);\n free(usage);\n\n}\n\nvoid enumerate_devices()\n{\n \/* Check if there are recgonized devices plugged in *\/\n unsigned int num_devices = 0;\n LOGF(DEBUG, \"Enumerating system HID devices (manufacturer product vId pId)\");\n GetRawInputDeviceList(NULL, &num_devices, sizeof(RAWINPUTDEVICELIST));\n\n if (num_devices <= 0) {\n DEXIT_PROCESS(L\"Failed to enumerate system devices\", 0);\n }\n\n RAWINPUTDEVICELIST *devices =\n (RAWINPUTDEVICELIST*)malloc(num_devices * sizeof(RAWINPUTDEVICELIST));\n \n if (!GetRawInputDeviceList(devices, &num_devices, sizeof(RAWINPUTDEVICELIST))) {\n DEXIT_PROCESS(L\"Failed to enumerate system devices\", GetLastError());\n }\n\n for (int i = 0; i < num_devices; i++) {\n unsigned int size = 0;\n int ret = 0;\n\n ret = GetRawInputDeviceInfo(devices[i].hDevice, RIDI_DEVICENAME, NULL, &size);\n \n wchar_t *name = (wchar_t*)malloc(sizeof(wchar_t) * (size+1));\n \n ret = GetRawInputDeviceInfo(devices[i].hDevice, RIDI_DEVICENAME, name, &size);\n \n \n ret = GetRawInputDeviceInfo(devices[i].hDevice, RIDI_DEVICEINFO, NULL, &size);\n\n PRID_DEVICE_INFO device_info =\n (PRID_DEVICE_INFO)malloc(size);\n \n ret = GetRawInputDeviceInfo(devices[i].hDevice, RIDI_DEVICEINFO, device_info, &size);\n \n HANDLE hid_handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE,\n FILE_SHARE_READ | FILE_SHARE_WRITE,\n NULL, OPEN_ALWAYS,\n FILE_FLAG_OVERLAPPED, NULL);\n \n wchar_t product_string[sizeof(wchar_t) * 128] = {0};\n wchar_t manufacturer_string[sizeof(wchar_t) * 128] = {0};\n wchar_t serial_number[sizeof(wchar_t) * 128] = {0};\n\n if (hid_handle != INVALID_HANDLE_VALUE) {\n ret = HidD_GetManufacturerString(hid_handle, manufacturer_string, sizeof(wchar_t) * 128);\n ret = HidD_GetProductString(hid_handle, product_string, sizeof(wchar_t) * 128);\n ret = HidD_GetSerialNumberString(hid_handle, serial_number, sizeof(wchar_t) * 128);\n\n LOGF(INFO, \"device %S %S %04x %04x\",\n (manufacturer_string[0] == '\\0') ? L\"*\": manufacturer_string,\n (product_string[0] == '\\0') ? L\"*\": product_string,\n device_info->hid.dwVendorId,\n device_info->hid.dwProductId);\n \n CloseHandle(hid_handle);\n }\n \n free(device_info);\n free(name);\n }\n \n free(devices);\n}\n\nvoid register_devices(HWND hWnd)\n{\n char debug[256];\n wchar_t debug_wide[256];\n \n RAWINPUTDEVICE wheel_input;\n\n LOGF(DEBUG, \"This is a debug log from hid module\");\n\n wheel_input.usUsagePage = 1;\n wheel_input.usUsage = 4;\n wheel_input.dwFlags = RIDEV_INPUTSINK;\n wheel_input.hwndTarget = hWnd;\n\n if (!RegisterRawInputDevices(&wheel_input, 1, sizeof(RAWINPUTDEVICE))) {\n LOGF(FATAL, \"failed to register HID devices\");\n DEXIT_PROCESS(L\"Failed to register HID devices\", GetLastError());\n }\n \n}\n<|endoftext|>"} {"text":"#include \n\nclass Moveable\n{\n\tpublic:\n\t\tMoveable()\n\t\t{\n\t\t\tstd::cout << \"Default constructor\" << std::endl;\n\t\t}\n\n\t\tMoveable(const Moveable& m)\n\t\t{\n\t\t\tstd::cout << \"Copy constructor\" << std::endl;\n\t\t}\n\n\t\tMoveable(const Moveable&& m)\n\t\t{\n\t\t\tstd::cout << \"Move constructor\" << std::endl;\n\t\t}\n\n\t\t~Moveable() \n\t\t{\n\t\t\tstd::cout << \"Destructor\" << std::endl;\n\t\t}\n\n\t\tstatic Moveable Instance()\n\t\t{\n\t\t\treturn Moveable();\n\t\t}\n};\n\nint main()\n{\n\tMoveable m;\n\tMoveable c(m);\n Moveable m3(Moveable::Instance());\n}\nMaking progress#include \n\nclass Moveable\n{\n\tpublic:\n\n\t\tint m_iField;\n\t\n\t\tMoveable()\n\t\t{\n\t\t\tm_iField = 0;\n\t\t\tstd::cout << \"Default constructor\" << std::endl;\n\t\t}\n\n\t\tMoveable(const Moveable& m)\n\t\t{\n\t\t\tm_iField = 1;\n\t\t\tstd::cout << \"Copy constructor\" << std::endl;\n\t\t}\n\n\t\tMoveable(const Moveable&& m)\n\t\t{\n\t\t\tm_iField = 2;\n\t\t\tstd::cout << \"Move constructor\" << std::endl;\n\t\t}\n\n Moveable& operator = (const Moveable& m)\n\t\t{\n\t\t\tm_iField = m.m_iField;\n\t\t\tstd::cout << \"normal assignement\" << std::endl;\n\t\t}\n\n Moveable& operator = (const Moveable&& m)\n\t\t{\n\t\t\tm_iField = m.m_iField;\n\t\t\tstd::cout << \"rvalue assignement\" << std::endl;\n\t\t}\n\n\t\tstatic Moveable Instance()\n\t\t{\n\t\t\tstd::cout << \"Instance function\" << std::endl;\n\t\t\treturn Moveable();\n\t\t}\n};\n\nint main()\n{\n\tMoveable m;\n\tMoveable c(m);\n Moveable m3;\n\tm3 = c;\n}\n<|endoftext|>"} {"text":"\/\/===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This family of functions determines the possibility of performing constant\n\/\/ folding.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/ConstantFolding.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Support\/GetElementPtrTypeIterator.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Constant Folding ...\n\/\/\n\n\n\/\/\/ canConstantFoldCallTo - Return true if its even possible to fold a call to\n\/\/\/ the specified function.\nbool\nllvm::canConstantFoldCallTo(Function *F) {\n const std::string &Name = F->getName();\n\n switch (F->getIntrinsicID()) {\n case Intrinsic::isunordered_f32:\n case Intrinsic::isunordered_f64:\n case Intrinsic::sqrt_f32:\n case Intrinsic::sqrt_f64:\n case Intrinsic::bswap_i16:\n case Intrinsic::bswap_i32:\n case Intrinsic::bswap_i64:\n \/\/ FIXME: these should be constant folded as well\n \/\/case Intrinsic::ctpop_i8:\n \/\/case Intrinsic::ctpop_i16:\n \/\/case Intrinsic::ctpop_i32:\n \/\/case Intrinsic::ctpop_i64:\n \/\/case Intrinsic::ctlz_i8:\n \/\/case Intrinsic::ctlz_i16:\n \/\/case Intrinsic::ctlz_i32:\n \/\/case Intrinsic::ctlz_i64:\n \/\/case Intrinsic::cttz_i8:\n \/\/case Intrinsic::cttz_i16:\n \/\/case Intrinsic::cttz_i32:\n \/\/case Intrinsic::cttz_i64:\n return true;\n default: break;\n }\n\n switch (Name[0])\n {\n case 'a':\n return Name == \"acos\" || Name == \"asin\" || Name == \"atan\" ||\n Name == \"atan2\";\n case 'c':\n return Name == \"ceil\" || Name == \"cos\" || Name == \"cosf\" ||\n Name == \"cosh\";\n case 'e':\n return Name == \"exp\";\n case 'f':\n return Name == \"fabs\" || Name == \"fmod\" || Name == \"floor\";\n case 'l':\n return Name == \"log\" || Name == \"log10\";\n case 'p':\n return Name == \"pow\";\n case 's':\n return Name == \"sin\" || Name == \"sinh\" || \n Name == \"sqrt\" || Name == \"sqrtf\";\n case 't':\n return Name == \"tan\" || Name == \"tanh\";\n default:\n return false;\n }\n}\n\nConstant *\nllvm::ConstantFoldFP(double (*NativeFP)(double), double V, const Type *Ty) {\n errno = 0;\n V = NativeFP(V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n return 0;\n}\n\n\/\/\/ ConstantFoldCall - Attempt to constant fold a call to the specified function\n\/\/\/ with the specified arguments, returning null if unsuccessful.\nConstant *\nllvm::ConstantFoldCall(Function *F, const std::vector &Operands) {\n const std::string &Name = F->getName();\n const Type *Ty = F->getReturnType();\n\n if (Operands.size() == 1) {\n if (ConstantFP *Op = dyn_cast(Operands[0])) {\n double V = Op->getValue();\n switch (Name[0])\n {\n case 'a':\n if (Name == \"acos\")\n return ConstantFoldFP(acos, V, Ty);\n else if (Name == \"asin\")\n return ConstantFoldFP(asin, V, Ty);\n else if (Name == \"atan\")\n return ConstantFP::get(Ty, atan(V));\n break;\n case 'c':\n if (Name == \"ceil\")\n return ConstantFoldFP(ceil, V, Ty);\n else if (Name == \"cos\")\n return ConstantFP::get(Ty, cos(V));\n else if (Name == \"cosh\")\n return ConstantFP::get(Ty, cosh(V));\n break;\n case 'e':\n if (Name == \"exp\")\n return ConstantFP::get(Ty, exp(V));\n break;\n case 'f':\n if (Name == \"fabs\")\n return ConstantFP::get(Ty, fabs(V));\n else if (Name == \"floor\")\n return ConstantFoldFP(floor, V, Ty);\n break;\n case 'l':\n if (Name == \"log\" && V > 0)\n return ConstantFP::get(Ty, log(V));\n else if (Name == \"log10\" && V > 0)\n return ConstantFoldFP(log10, V, Ty);\n else if (Name == \"llvm.sqrt.f32\" || Name == \"llvm.sqrt.f64\") {\n if (V >= -0.0)\n return ConstantFP::get(Ty, sqrt(V));\n else \/\/ Undefined\n return ConstantFP::get(Ty, 0.0);\n }\n break;\n case 's':\n if (Name == \"sin\")\n return ConstantFP::get(Ty, sin(V));\n else if (Name == \"sinh\")\n return ConstantFP::get(Ty, sinh(V));\n else if (Name == \"sqrt\" && V >= 0)\n return ConstantFP::get(Ty, sqrt(V));\n else if (Name == \"sqrtf\" && V >= 0)\n return ConstantFP::get(Ty, sqrt((float)V));\n break;\n case 't':\n if (Name == \"tan\")\n return ConstantFP::get(Ty, tan(V));\n else if (Name == \"tanh\")\n return ConstantFP::get(Ty, tanh(V));\n break;\n default:\n break;\n }\n } else if (ConstantInt *Op = dyn_cast(Operands[0])) {\n uint64_t V = Op->getZExtValue();\n if (Name == \"llvm.bswap.i16\")\n return ConstantInt::get(Ty, ByteSwap_16(V));\n else if (Name == \"llvm.bswap.i32\")\n return ConstantInt::get(Ty, ByteSwap_32(V));\n else if (Name == \"llvm.bswap.i64\")\n return ConstantInt::get(Ty, ByteSwap_64(V));\n }\n } else if (Operands.size() == 2) {\n if (ConstantFP *Op1 = dyn_cast(Operands[0])) {\n double Op1V = Op1->getValue();\n if (ConstantFP *Op2 = dyn_cast(Operands[1])) {\n double Op2V = Op2->getValue();\n\n if (Name == \"llvm.isunordered.f32\" || Name == \"llvm.isunordered.f64\")\n return ConstantBool::get(IsNAN(Op1V) || IsNAN(Op2V));\n else\n if (Name == \"pow\") {\n errno = 0;\n double V = pow(Op1V, Op2V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n } else if (Name == \"fmod\") {\n errno = 0;\n double V = fmod(Op1V, Op2V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n } else if (Name == \"atan2\")\n return ConstantFP::get(Ty, atan2(Op1V,Op2V));\n }\n }\n }\n return 0;\n}\n\nremove llvm.isunordered\/\/===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This family of functions determines the possibility of performing constant\n\/\/ folding.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/ConstantFolding.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Support\/GetElementPtrTypeIterator.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Constant Folding ...\n\/\/\n\n\n\/\/\/ canConstantFoldCallTo - Return true if its even possible to fold a call to\n\/\/\/ the specified function.\nbool\nllvm::canConstantFoldCallTo(Function *F) {\n const std::string &Name = F->getName();\n\n switch (F->getIntrinsicID()) {\n case Intrinsic::sqrt_f32:\n case Intrinsic::sqrt_f64:\n case Intrinsic::bswap_i16:\n case Intrinsic::bswap_i32:\n case Intrinsic::bswap_i64:\n \/\/ FIXME: these should be constant folded as well\n \/\/case Intrinsic::ctpop_i8:\n \/\/case Intrinsic::ctpop_i16:\n \/\/case Intrinsic::ctpop_i32:\n \/\/case Intrinsic::ctpop_i64:\n \/\/case Intrinsic::ctlz_i8:\n \/\/case Intrinsic::ctlz_i16:\n \/\/case Intrinsic::ctlz_i32:\n \/\/case Intrinsic::ctlz_i64:\n \/\/case Intrinsic::cttz_i8:\n \/\/case Intrinsic::cttz_i16:\n \/\/case Intrinsic::cttz_i32:\n \/\/case Intrinsic::cttz_i64:\n return true;\n default: break;\n }\n\n switch (Name[0])\n {\n case 'a':\n return Name == \"acos\" || Name == \"asin\" || Name == \"atan\" ||\n Name == \"atan2\";\n case 'c':\n return Name == \"ceil\" || Name == \"cos\" || Name == \"cosf\" ||\n Name == \"cosh\";\n case 'e':\n return Name == \"exp\";\n case 'f':\n return Name == \"fabs\" || Name == \"fmod\" || Name == \"floor\";\n case 'l':\n return Name == \"log\" || Name == \"log10\";\n case 'p':\n return Name == \"pow\";\n case 's':\n return Name == \"sin\" || Name == \"sinh\" || \n Name == \"sqrt\" || Name == \"sqrtf\";\n case 't':\n return Name == \"tan\" || Name == \"tanh\";\n default:\n return false;\n }\n}\n\nConstant *\nllvm::ConstantFoldFP(double (*NativeFP)(double), double V, const Type *Ty) {\n errno = 0;\n V = NativeFP(V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n return 0;\n}\n\n\/\/\/ ConstantFoldCall - Attempt to constant fold a call to the specified function\n\/\/\/ with the specified arguments, returning null if unsuccessful.\nConstant *\nllvm::ConstantFoldCall(Function *F, const std::vector &Operands) {\n const std::string &Name = F->getName();\n const Type *Ty = F->getReturnType();\n\n if (Operands.size() == 1) {\n if (ConstantFP *Op = dyn_cast(Operands[0])) {\n double V = Op->getValue();\n switch (Name[0])\n {\n case 'a':\n if (Name == \"acos\")\n return ConstantFoldFP(acos, V, Ty);\n else if (Name == \"asin\")\n return ConstantFoldFP(asin, V, Ty);\n else if (Name == \"atan\")\n return ConstantFP::get(Ty, atan(V));\n break;\n case 'c':\n if (Name == \"ceil\")\n return ConstantFoldFP(ceil, V, Ty);\n else if (Name == \"cos\")\n return ConstantFP::get(Ty, cos(V));\n else if (Name == \"cosh\")\n return ConstantFP::get(Ty, cosh(V));\n break;\n case 'e':\n if (Name == \"exp\")\n return ConstantFP::get(Ty, exp(V));\n break;\n case 'f':\n if (Name == \"fabs\")\n return ConstantFP::get(Ty, fabs(V));\n else if (Name == \"floor\")\n return ConstantFoldFP(floor, V, Ty);\n break;\n case 'l':\n if (Name == \"log\" && V > 0)\n return ConstantFP::get(Ty, log(V));\n else if (Name == \"log10\" && V > 0)\n return ConstantFoldFP(log10, V, Ty);\n else if (Name == \"llvm.sqrt.f32\" || Name == \"llvm.sqrt.f64\") {\n if (V >= -0.0)\n return ConstantFP::get(Ty, sqrt(V));\n else \/\/ Undefined\n return ConstantFP::get(Ty, 0.0);\n }\n break;\n case 's':\n if (Name == \"sin\")\n return ConstantFP::get(Ty, sin(V));\n else if (Name == \"sinh\")\n return ConstantFP::get(Ty, sinh(V));\n else if (Name == \"sqrt\" && V >= 0)\n return ConstantFP::get(Ty, sqrt(V));\n else if (Name == \"sqrtf\" && V >= 0)\n return ConstantFP::get(Ty, sqrt((float)V));\n break;\n case 't':\n if (Name == \"tan\")\n return ConstantFP::get(Ty, tan(V));\n else if (Name == \"tanh\")\n return ConstantFP::get(Ty, tanh(V));\n break;\n default:\n break;\n }\n } else if (ConstantInt *Op = dyn_cast(Operands[0])) {\n uint64_t V = Op->getZExtValue();\n if (Name == \"llvm.bswap.i16\")\n return ConstantInt::get(Ty, ByteSwap_16(V));\n else if (Name == \"llvm.bswap.i32\")\n return ConstantInt::get(Ty, ByteSwap_32(V));\n else if (Name == \"llvm.bswap.i64\")\n return ConstantInt::get(Ty, ByteSwap_64(V));\n }\n } else if (Operands.size() == 2) {\n if (ConstantFP *Op1 = dyn_cast(Operands[0])) {\n double Op1V = Op1->getValue();\n if (ConstantFP *Op2 = dyn_cast(Operands[1])) {\n double Op2V = Op2->getValue();\n\n if (Name == \"pow\") {\n errno = 0;\n double V = pow(Op1V, Op2V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n } else if (Name == \"fmod\") {\n errno = 0;\n double V = fmod(Op1V, Op2V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n } else if (Name == \"atan2\")\n return ConstantFP::get(Ty, atan2(Op1V,Op2V));\n }\n }\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/===--- FrontendActions.cpp ----------------------------------------------===\/\/\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#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/AST\/ASTConsumer.h\"\n#include \"clang\/Lex\/Pragma.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Frontend\/ASTConsumers.h\"\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/Utils.h\"\n#include \"clang\/Serialization\/ASTWriter.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Custom Actions\n\/\/===----------------------------------------------------------------------===\/\/\n\nASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return new ASTConsumer();\n}\n\nvoid InitOnlyAction::ExecuteAction() {\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ AST Consumer Actions\n\/\/===----------------------------------------------------------------------===\/\/\n\nASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n if (llvm::raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))\n return CreateASTPrinter(OS);\n return 0;\n}\n\nASTConsumer *ASTPrintXMLAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n if (llvm::raw_ostream *OS = CI.createDefaultOutputFile(false, InFile, \"xml\"))\n return CreateASTPrinterXML(OS);\n return 0;\n}\n\nASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return CreateASTDumper();\n}\n\nASTConsumer *ASTDumpXMLAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n llvm::raw_ostream *OS;\n if (CI.getFrontendOpts().OutputFile.empty())\n OS = &llvm::outs();\n else\n OS = CI.createDefaultOutputFile(false, InFile);\n if (!OS) return 0;\n return CreateASTDumperXML(*OS);\n}\n\nASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return CreateASTViewer();\n}\n\nASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return CreateDeclContextPrinter();\n}\n\nASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n std::string Sysroot;\n llvm::raw_ostream *OS = 0;\n bool Chaining;\n if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OS, Chaining))\n return 0;\n\n const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?\n Sysroot.c_str() : 0; \n return new PCHGenerator(CI.getPreprocessor(), Chaining, isysroot, OS);\n}\n\nbool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,\n llvm::StringRef InFile,\n std::string &Sysroot,\n llvm::raw_ostream *&OS,\n bool &Chaining) {\n Sysroot = CI.getHeaderSearchOpts().Sysroot;\n if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {\n CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);\n return true;\n }\n\n OS = CI.createDefaultOutputFile(true, InFile);\n if (!OS)\n return true;\n\n Chaining = CI.getInvocation().getFrontendOpts().ChainedPCH &&\n !CI.getPreprocessorOpts().ImplicitPCHInclude.empty();\n return false;\n}\n\nASTConsumer *InheritanceViewAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return CreateInheritanceViewer(CI.getFrontendOpts().ViewClassInheritance);\n}\n\nASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return new ASTConsumer();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Preprocessor Actions\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid DumpRawTokensAction::ExecuteAction() {\n Preprocessor &PP = getCompilerInstance().getPreprocessor();\n SourceManager &SM = PP.getSourceManager();\n\n \/\/ Start lexing the specified input file.\n const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());\n Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOptions());\n RawLex.SetKeepWhitespaceMode(true);\n\n Token RawTok;\n RawLex.LexFromRawLexer(RawTok);\n while (RawTok.isNot(tok::eof)) {\n PP.DumpToken(RawTok, true);\n llvm::errs() << \"\\n\";\n RawLex.LexFromRawLexer(RawTok);\n }\n}\n\nvoid DumpTokensAction::ExecuteAction() {\n Preprocessor &PP = getCompilerInstance().getPreprocessor();\n \/\/ Start preprocessing the specified input file.\n Token Tok;\n PP.EnterMainSourceFile();\n do {\n PP.Lex(Tok);\n PP.DumpToken(Tok, true);\n llvm::errs() << \"\\n\";\n } while (Tok.isNot(tok::eof));\n}\n\nvoid GeneratePTHAction::ExecuteAction() {\n CompilerInstance &CI = getCompilerInstance();\n if (CI.getFrontendOpts().OutputFile.empty() ||\n CI.getFrontendOpts().OutputFile == \"-\") {\n \/\/ FIXME: Don't fail this way.\n \/\/ FIXME: Verify that we can actually seek in the given file.\n llvm::report_fatal_error(\"PTH requires a seekable file for output!\");\n }\n llvm::raw_fd_ostream *OS =\n CI.createDefaultOutputFile(true, getCurrentFile());\n if (!OS) return;\n\n CacheTokens(CI.getPreprocessor(), OS);\n}\n\nvoid PreprocessOnlyAction::ExecuteAction() {\n Preprocessor &PP = getCompilerInstance().getPreprocessor();\n\n \/\/ Ignore unknown pragmas.\n PP.AddPragmaHandler(new EmptyPragmaHandler());\n\n Token Tok;\n \/\/ Start parsing the specified input file.\n PP.EnterMainSourceFile();\n do {\n PP.Lex(Tok);\n } while (Tok.isNot(tok::eof));\n}\n\nvoid PrintPreprocessedAction::ExecuteAction() {\n CompilerInstance &CI = getCompilerInstance();\n \/\/ Output file needs to be set to 'Binary', to avoid converting Unix style\n \/\/ line feeds () to Microsoft style line feeds ().\n llvm::raw_ostream *OS = CI.createDefaultOutputFile(true, getCurrentFile());\n if (!OS) return;\n\n DoPrintPreprocessedInput(CI.getPreprocessor(), OS,\n CI.getPreprocessorOutputOpts());\n}\n\nvoid PrintPreambleAction::ExecuteAction() {\n switch (getCurrentFileKind()) {\n case IK_C:\n case IK_CXX:\n case IK_ObjC:\n case IK_ObjCXX:\n case IK_OpenCL:\n case IK_CUDA:\n break;\n \n case IK_None:\n case IK_Asm:\n case IK_PreprocessedC:\n case IK_PreprocessedCXX:\n case IK_PreprocessedObjC:\n case IK_PreprocessedObjCXX:\n case IK_AST:\n case IK_LLVM_IR:\n \/\/ We can't do anything with these.\n return;\n }\n \n CompilerInstance &CI = getCompilerInstance();\n llvm::MemoryBuffer *Buffer\n = CI.getFileManager().getBufferForFile(getCurrentFile());\n if (Buffer) {\n unsigned Preamble = Lexer::ComputePreamble(Buffer).first;\n llvm::outs().write(Buffer->getBufferStart(), Preamble);\n delete Buffer;\n }\n}\nlibclang: Don't allow RemoveFileOnSignal to be called via libclang, badness can ensue.\/\/===--- FrontendActions.cpp ----------------------------------------------===\/\/\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#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/AST\/ASTConsumer.h\"\n#include \"clang\/Lex\/Pragma.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Frontend\/ASTConsumers.h\"\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/Utils.h\"\n#include \"clang\/Serialization\/ASTWriter.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Custom Actions\n\/\/===----------------------------------------------------------------------===\/\/\n\nASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return new ASTConsumer();\n}\n\nvoid InitOnlyAction::ExecuteAction() {\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ AST Consumer Actions\n\/\/===----------------------------------------------------------------------===\/\/\n\nASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n if (llvm::raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))\n return CreateASTPrinter(OS);\n return 0;\n}\n\nASTConsumer *ASTPrintXMLAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n if (llvm::raw_ostream *OS = CI.createDefaultOutputFile(false, InFile, \"xml\"))\n return CreateASTPrinterXML(OS);\n return 0;\n}\n\nASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return CreateASTDumper();\n}\n\nASTConsumer *ASTDumpXMLAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n llvm::raw_ostream *OS;\n if (CI.getFrontendOpts().OutputFile.empty())\n OS = &llvm::outs();\n else\n OS = CI.createDefaultOutputFile(false, InFile);\n if (!OS) return 0;\n return CreateASTDumperXML(*OS);\n}\n\nASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return CreateASTViewer();\n}\n\nASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return CreateDeclContextPrinter();\n}\n\nASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n std::string Sysroot;\n llvm::raw_ostream *OS = 0;\n bool Chaining;\n if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OS, Chaining))\n return 0;\n\n const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?\n Sysroot.c_str() : 0; \n return new PCHGenerator(CI.getPreprocessor(), Chaining, isysroot, OS);\n}\n\nbool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,\n llvm::StringRef InFile,\n std::string &Sysroot,\n llvm::raw_ostream *&OS,\n bool &Chaining) {\n Sysroot = CI.getHeaderSearchOpts().Sysroot;\n if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {\n CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);\n return true;\n }\n\n \/\/ We use createOutputFile here because this is exposed via libclang, and we\n \/\/ must disable the RemoveFileOnSignal behavior.\n OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, \/*Binary=*\/true,\n \/*RemoveFileOnSignal=*\/false, InFile);\n if (!OS)\n return true;\n\n Chaining = CI.getInvocation().getFrontendOpts().ChainedPCH &&\n !CI.getPreprocessorOpts().ImplicitPCHInclude.empty();\n return false;\n}\n\nASTConsumer *InheritanceViewAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return CreateInheritanceViewer(CI.getFrontendOpts().ViewClassInheritance);\n}\n\nASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return new ASTConsumer();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Preprocessor Actions\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid DumpRawTokensAction::ExecuteAction() {\n Preprocessor &PP = getCompilerInstance().getPreprocessor();\n SourceManager &SM = PP.getSourceManager();\n\n \/\/ Start lexing the specified input file.\n const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());\n Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOptions());\n RawLex.SetKeepWhitespaceMode(true);\n\n Token RawTok;\n RawLex.LexFromRawLexer(RawTok);\n while (RawTok.isNot(tok::eof)) {\n PP.DumpToken(RawTok, true);\n llvm::errs() << \"\\n\";\n RawLex.LexFromRawLexer(RawTok);\n }\n}\n\nvoid DumpTokensAction::ExecuteAction() {\n Preprocessor &PP = getCompilerInstance().getPreprocessor();\n \/\/ Start preprocessing the specified input file.\n Token Tok;\n PP.EnterMainSourceFile();\n do {\n PP.Lex(Tok);\n PP.DumpToken(Tok, true);\n llvm::errs() << \"\\n\";\n } while (Tok.isNot(tok::eof));\n}\n\nvoid GeneratePTHAction::ExecuteAction() {\n CompilerInstance &CI = getCompilerInstance();\n if (CI.getFrontendOpts().OutputFile.empty() ||\n CI.getFrontendOpts().OutputFile == \"-\") {\n \/\/ FIXME: Don't fail this way.\n \/\/ FIXME: Verify that we can actually seek in the given file.\n llvm::report_fatal_error(\"PTH requires a seekable file for output!\");\n }\n llvm::raw_fd_ostream *OS =\n CI.createDefaultOutputFile(true, getCurrentFile());\n if (!OS) return;\n\n CacheTokens(CI.getPreprocessor(), OS);\n}\n\nvoid PreprocessOnlyAction::ExecuteAction() {\n Preprocessor &PP = getCompilerInstance().getPreprocessor();\n\n \/\/ Ignore unknown pragmas.\n PP.AddPragmaHandler(new EmptyPragmaHandler());\n\n Token Tok;\n \/\/ Start parsing the specified input file.\n PP.EnterMainSourceFile();\n do {\n PP.Lex(Tok);\n } while (Tok.isNot(tok::eof));\n}\n\nvoid PrintPreprocessedAction::ExecuteAction() {\n CompilerInstance &CI = getCompilerInstance();\n \/\/ Output file needs to be set to 'Binary', to avoid converting Unix style\n \/\/ line feeds () to Microsoft style line feeds ().\n llvm::raw_ostream *OS = CI.createDefaultOutputFile(true, getCurrentFile());\n if (!OS) return;\n\n DoPrintPreprocessedInput(CI.getPreprocessor(), OS,\n CI.getPreprocessorOutputOpts());\n}\n\nvoid PrintPreambleAction::ExecuteAction() {\n switch (getCurrentFileKind()) {\n case IK_C:\n case IK_CXX:\n case IK_ObjC:\n case IK_ObjCXX:\n case IK_OpenCL:\n case IK_CUDA:\n break;\n \n case IK_None:\n case IK_Asm:\n case IK_PreprocessedC:\n case IK_PreprocessedCXX:\n case IK_PreprocessedObjC:\n case IK_PreprocessedObjCXX:\n case IK_AST:\n case IK_LLVM_IR:\n \/\/ We can't do anything with these.\n return;\n }\n \n CompilerInstance &CI = getCompilerInstance();\n llvm::MemoryBuffer *Buffer\n = CI.getFileManager().getBufferForFile(getCurrentFile());\n if (Buffer) {\n unsigned Preamble = Lexer::ComputePreamble(Buffer).first;\n llvm::outs().write(Buffer->getBufferStart(), Preamble);\n delete Buffer;\n }\n}\n<|endoftext|>"} {"text":"\/*\topendatacon\n *\n *\tCopyright (c) 2014:\n *\n *\t\tDCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi\n *\t\tyxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==\n *\n *\tLicensed under the Apache License, Version 2.0 (the \"License\");\n *\tyou may not use this file except in compliance with the License.\n *\tYou may obtain a copy of the License at\n *\n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\tUnless required by applicable law or agreed to in writing, software\n *\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n *\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\tSee the License for the specific language governing permissions and\n *\tlimitations under the License.\n *\/\n\/*\n * IOHandler.cpp\n *\n * Created on: 20\/07\/2014\n * Author: Neil Stephens \n *\/\n\n#include \n\nnamespace odc\n{\n\nstd::unordered_map IOHandler::IOHandlers;\n\nstd::unordered_map& IOHandler::GetIOHandlers()\n{\n\treturn IOHandler::IOHandlers;\n}\n\nIOHandler::IOHandler(const std::string& aName):\n\tInitState(InitState_t::ENABLED),\n\tEnableDelayms(0),\n\tName(aName),\n\tpIOS(nullptr),\n\tenabled(false)\n{\n\tIOHandlers[Name]=this;\n}\n\nvoid IOHandler::Subscribe(IOHandler* pIOHandler, std::string aName)\n{\n\tthis->Subscribers[aName] = pIOHandler;\n}\n\nvoid IOHandler::SetIOS(asio::io_service* ios_ptr)\n{\n\tpIOS = ios_ptr;\n}\n\nbool DemandMap::InDemand()\n{\n\tstd::lock_guard lck (mtx);\n\tfor(auto demand : connection_demands)\n\t\tif(demand.second)\n\t\t\treturn true;\n\treturn false;\n}\n\nbool DemandMap::MuxConnectionEvents(ConnectState state, const std::string& SenderName)\n{\n\tif (state == ConnectState::DISCONNECTED)\n\t{\n\t\t{\n\t\t\tstd::lock_guard lck (mtx);\n\t\t\tconnection_demands[SenderName] = false;\n\t\t}\n\t\treturn !InDemand();\n\t}\n\telse if (state == ConnectState::CONNECTED)\n\t{\n\t\tstd::lock_guard lck (mtx);\n\t\tbool new_demand = !connection_demands[SenderName];\n\t\tconnection_demands[SenderName] = true;\n\t\treturn new_demand;\n\t}\n\treturn true;\n}\n\nvoid IOHandler::Event(ConnectState state, const std::string& SenderName)\n{\n\tMuxConnectionEvents(state, SenderName);\n}\n\nSharedStatusCallback_t IOHandler::SyncMultiCallback (const size_t cb_number, SharedStatusCallback_t pStatusCallback)\n{\n\tif(pIOS == nullptr)\n\t{\n\t\tthrow std::runtime_error(\"Uninitialised io_service on enabled IOHandler\");\n\t}\n\tif(cb_number == 1)\n\t\treturn pStatusCallback;\n\n\tauto pCombinedStatus = std::make_shared(CommandStatus::SUCCESS);\n\tauto pExecCount = std::make_shared(0);\n\tauto pCB_sync = std::make_shared(*pIOS);\n\treturn std::make_shared>\n\t\t (pCB_sync->wrap(\n\t\t\t\t [pCB_sync,\n\t\t\t\t pCombinedStatus,\n\t\t\t\t pExecCount,\n\t\t\t\t cb_number,\n\t\t\t\t pStatusCallback](CommandStatus status)\n\t\t\t\t {\n\t\t\t\t\t if(*pCombinedStatus == CommandStatus::UNDEFINED)\n\t\t\t\t\t\t return;\n\n\t\t\t\t\t if(++(*pExecCount) == 1)\n\t\t\t\t\t {\n\t\t\t\t\t *pCombinedStatus = status;\n\t\t\t\t\t if(*pCombinedStatus == CommandStatus::UNDEFINED)\n\t\t\t\t\t {\n\t\t\t\t\t (*pStatusCallback)(*pCombinedStatus);\n\t\t\t\t\t return;\n\t\t\t\t\t\t }\n\t\t\t\t\t }\n\t\t\t\t\t else if(status != *pCombinedStatus)\n\t\t\t\t\t {\n\t\t\t\t\t *pCombinedStatus = CommandStatus::UNDEFINED;\n\t\t\t\t\t (*pStatusCallback)(*pCombinedStatus);\n\t\t\t\t\t return;\n\t\t\t\t\t }\n\n\t\t\t\t\t if(*pExecCount >= cb_number)\n\t\t\t\t\t {\n\t\t\t\t\t (*pStatusCallback)(*pCombinedStatus);\n\t\t\t\t\t }\n\t\t\t\t }));\n}\n\n}\nkeep the io_service active for the life of the SyncMultiCallback strand\/handler\/*\topendatacon\n *\n *\tCopyright (c) 2014:\n *\n *\t\tDCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi\n *\t\tyxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==\n *\n *\tLicensed under the Apache License, Version 2.0 (the \"License\");\n *\tyou may not use this file except in compliance with the License.\n *\tYou may obtain a copy of the License at\n *\n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\tUnless required by applicable law or agreed to in writing, software\n *\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n *\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\tSee the License for the specific language governing permissions and\n *\tlimitations under the License.\n *\/\n\/*\n * IOHandler.cpp\n *\n * Created on: 20\/07\/2014\n * Author: Neil Stephens \n *\/\n\n#include \n\nnamespace odc\n{\n\nstd::unordered_map IOHandler::IOHandlers;\n\nstd::unordered_map& IOHandler::GetIOHandlers()\n{\n\treturn IOHandler::IOHandlers;\n}\n\nIOHandler::IOHandler(const std::string& aName):\n\tInitState(InitState_t::ENABLED),\n\tEnableDelayms(0),\n\tName(aName),\n\tpIOS(nullptr),\n\tenabled(false)\n{\n\tIOHandlers[Name]=this;\n}\n\nvoid IOHandler::Subscribe(IOHandler* pIOHandler, std::string aName)\n{\n\tthis->Subscribers[aName] = pIOHandler;\n}\n\nvoid IOHandler::SetIOS(asio::io_service* ios_ptr)\n{\n\tpIOS = ios_ptr;\n}\n\nbool DemandMap::InDemand()\n{\n\tstd::lock_guard lck (mtx);\n\tfor(auto demand : connection_demands)\n\t\tif(demand.second)\n\t\t\treturn true;\n\treturn false;\n}\n\nbool DemandMap::MuxConnectionEvents(ConnectState state, const std::string& SenderName)\n{\n\tif (state == ConnectState::DISCONNECTED)\n\t{\n\t\t{\n\t\t\tstd::lock_guard lck (mtx);\n\t\t\tconnection_demands[SenderName] = false;\n\t\t}\n\t\treturn !InDemand();\n\t}\n\telse if (state == ConnectState::CONNECTED)\n\t{\n\t\tstd::lock_guard lck (mtx);\n\t\tbool new_demand = !connection_demands[SenderName];\n\t\tconnection_demands[SenderName] = true;\n\t\treturn new_demand;\n\t}\n\treturn true;\n}\n\nvoid IOHandler::Event(ConnectState state, const std::string& SenderName)\n{\n\tMuxConnectionEvents(state, SenderName);\n}\n\nSharedStatusCallback_t IOHandler::SyncMultiCallback (const size_t cb_number, SharedStatusCallback_t pStatusCallback)\n{\n\tif(pIOS == nullptr)\n\t{\n\t\tthrow std::runtime_error(\"Uninitialised io_service on enabled IOHandler\");\n\t}\n\n\tif(cb_number < 2)\n\t\treturn pStatusCallback;\n\n\t\/\/We must keep the io_service active for the life of the strand\/handler we're about to create\n\tauto work = std::make_shared(*pIOS);\n\tauto pCombinedStatus = std::make_shared(CommandStatus::SUCCESS);\n\tauto pExecCount = std::make_shared(0);\n\tauto pCB_sync = std::make_shared(*pIOS);\n\treturn std::make_shared>\n\t\t (pCB_sync->wrap(\n\t\t\t\t [work,\n\t\t\t\t pCB_sync,\n\t\t\t\t pCombinedStatus,\n\t\t\t\t pExecCount,\n\t\t\t\t cb_number,\n\t\t\t\t pStatusCallback](CommandStatus status)\n\t\t\t\t {\n\t\t\t\t\t if(*pCombinedStatus == CommandStatus::UNDEFINED)\n\t\t\t\t\t\t return;\n\n\t\t\t\t\t if(++(*pExecCount) == 1)\n\t\t\t\t\t {\n\t\t\t\t\t *pCombinedStatus = status;\n\t\t\t\t\t if(*pCombinedStatus == CommandStatus::UNDEFINED)\n\t\t\t\t\t {\n\t\t\t\t\t (*pStatusCallback)(*pCombinedStatus);\n\t\t\t\t\t return;\n\t\t\t\t\t\t }\n\t\t\t\t\t }\n\t\t\t\t\t else if(status != *pCombinedStatus)\n\t\t\t\t\t {\n\t\t\t\t\t *pCombinedStatus = CommandStatus::UNDEFINED;\n\t\t\t\t\t (*pStatusCallback)(*pCombinedStatus);\n\t\t\t\t\t return;\n\t\t\t\t\t }\n\n\t\t\t\t\t if(*pExecCount >= cb_number)\n\t\t\t\t\t {\n\t\t\t\t\t (*pStatusCallback)(*pCombinedStatus);\n\t\t\t\t\t }\n\t\t\t\t }));\n}\n\n}\n<|endoftext|>"} {"text":"#include \"GEK\\Math\\Float4x4.h\"\n#include \"GEK\\Shapes\\AlignedBox.h\"\n#include \"GEK\\Shapes\\OrientedBox.h\"\n#include \"GEK\\Utility\\FileSystem.h\"\n#include \"GEK\\Utility\\String.h\"\n#include \"GEK\\Utility\\XML.h\"\n#include \"GEK\\Utility\\Allocator.h\"\n#include \"GEK\\Context\\ContextUser.h\"\n#include \"GEK\\System\\VideoDevice.h\"\n#include \"GEK\\Engine\\Core.h\"\n#include \"GEK\\Engine\\Processor.h\"\n#include \"GEK\\Engine\\ComponentMixin.h\"\n#include \"GEK\\Engine\\Population.h\"\n#include \"GEK\\Engine\\Entity.h\"\n#include \"GEK\\Engine\\Renderer.h\"\n#include \"GEK\\Engine\\Resources.h\"\n#include \"GEK\\Components\\Transform.h\"\n#include \"GEK\\Components\\Color.h\"\n#include \n#include \n#include \n#include \n\nnamespace Gek\n{\n namespace Components\n {\n GEK_COMPONENT(Explosion)\n {\n float strength;\n\n void save(Plugin::Population::ComponentDefinition &componentData) const\n {\n saveParameter(componentData, L\"strength\", strength);\n }\n\n void load(const Plugin::Population::ComponentDefinition &componentData)\n {\n strength = loadParameter(componentData, L\"strength\", 10.0f);\n }\n };\n }; \/\/ namespace Components\n\n namespace Sprites\n {\n GEK_CONTEXT_USER(Explosion)\n , public Plugin::ComponentMixin\n {\n public:\n Explosion(Context *context)\n : ContextRegistration(context)\n {\n }\n\n \/\/ Plugin::Component\n const wchar_t * const getName(void) const\n {\n return L\"explosion\";\n }\n };\n\n GEK_CONTEXT_USER(EmitterProcessor, Plugin::Core *)\n , public Plugin::PopulationListener\n , public Plugin::PopulationStep\n , public Plugin::RendererListener\n , public Plugin::Processor\n {\n public:\n static const uint32_t SpritesBufferCount = 1000000;\n static std::random_device randomDevice;\n static std::mt19937 mersineTwister;\n\n __declspec(align(16))\n struct Sprite\n {\n Math::Float3 position;\n Math::Float3 velocity;\n float angle;\n float torque;\n float halfSize;\n float age;\n float buffer[2];\n\n Sprite(void)\n : halfSize(0.0f)\n {\n }\n };\n\n struct EmitterData\n {\n Shapes::AlignedBox box;\n MaterialHandle material;\n std::vector spritesList;\n\n uint32_t tail;\n std::function update;\n };\n\n private:\n Plugin::Population *population;\n Plugin::Resources *resources;\n Plugin::Renderer *renderer;\n\n VisualHandle visual;\n Video::BufferPtr spritesBuffer;\n\n using EntityEmitterMap = std::unordered_map>;\n EntityEmitterMap entityEmitterMap;\n\n using VisibleMap = concurrency::concurrent_unordered_multimap;\n VisibleMap visibleMap;\n\n public:\n EmitterProcessor(Context *context, Plugin::Core *core)\n : ContextRegistration(context)\n , population(core->getPopulation())\n , resources(core->getResources())\n , renderer(core->getRenderer())\n {\n GEK_REQUIRE(population);\n GEK_REQUIRE(resources);\n GEK_REQUIRE(renderer);\n\n population->addListener(this);\n population->addStep(this, 60);\n renderer->addListener(this);\n\n visual = resources->loadVisual(L\"Sprites\");\n spritesBuffer = renderer->getDevice()->createBuffer(sizeof(Sprite), SpritesBufferCount, Video::BufferType::Structured, Video::BufferFlags::Mappable | Video::BufferFlags::Resource, false);\n }\n\n ~EmitterProcessor(void)\n {\n renderer->removeListener(this);\n population->removeStep(this);\n population->removeListener(this);\n }\n\n \/\/ Plugin::PopulationListener\n void onLoadBegin(void)\n {\n entityEmitterMap.clear();\n }\n\n void onLoadSucceeded(void)\n {\n }\n\n void onLoadFailed(void)\n {\n }\n\n struct combineMinimum\n {\n concurrency::combinable combinable;\n\n combineMinimum(void)\n : combinable([&]\n {\n return Math::Infinity;\n })\n {\n }\n\n void set(float value)\n {\n auto &localValue = combinable.local();\n localValue = std::min(value, localValue);\n }\n\n float get(void)\n {\n return combinable.combine([](float left, float right)\n {\n return std::min(left, right);\n });\n }\n };\n\n struct combineMaximum\n {\n concurrency::combinable combinable;\n\n combineMaximum(void)\n : combinable([&]\n {\n return Math::NegativeInfinity;\n })\n {\n }\n\n void set(float value)\n {\n auto &localValue = combinable.local();\n localValue = std::max(value, localValue);\n }\n\n float get(void)\n {\n return combinable.combine([](float left, float right)\n {\n return std::max(left, right);\n });\n }\n };\n\n void onEntityCreated(Plugin::Entity *entity)\n {\n GEK_REQUIRE(resources);\n GEK_REQUIRE(entity);\n\n if (entity->hasComponent())\n {\n static const Math::Float3 gravity(0.0f, -32.174f, 0.0f);\n static const auto smoke = [this](const Plugin::Entity *entity, EmitterData &emitter) -> void\n {\n static const auto update = [](const Plugin::Entity *entity, EmitterData &emitter, float frameTime) -> void\n {\n auto &sprite = emitter.spritesList.front();\n emitter.spritesList[emitter.tail++] = sprite;\n if (emitter.tail >= emitter.spritesList.size())\n {\n emitter.tail = 1;\n }\n\n sprite.position += (sprite.velocity * frameTime);\n\n combineMinimum minimum[3];\n combineMaximum maximum[3];\n concurrency::parallel_for_each((emitter.spritesList.begin() + 1), emitter.spritesList.end(), [&emitter, frameTime, &minimum, &maximum](Sprite &sprite) -> void\n {\n sprite.age += frameTime;\n sprite.halfSize += frameTime;\n sprite.angle += (sprite.torque * frameTime);\n \/\/sprite.position -= (gravity * frameTime);\n for (uint32_t axis = 0; axis < 3; axis++)\n {\n minimum[axis].set(sprite.position[axis] - sprite.halfSize);\n maximum[axis].set(sprite.position[axis] + sprite.halfSize);\n }\n });\n\n emitter.box.minimum.x = minimum[0].get();\n emitter.box.minimum.y = minimum[1].get();\n emitter.box.minimum.z = minimum[2].get();\n emitter.box.maximum.x = maximum[0].get();\n emitter.box.maximum.y = maximum[1].get();\n emitter.box.maximum.z = maximum[2].get();\n };\n\n const auto &explosionComponent = entity->getComponent();\n const auto &transformComponent = entity->getComponent();\n\n static const std::uniform_real_distribution spawnDirection(-1.0f, 1.0f);\n static const std::uniform_real_distribution spawnAngle(0.0f, (Gek::Math::Pi * 2.0f));\n static const std::uniform_real_distribution spawnTorque(-Gek::Math::Pi + 0.25f, Gek::Math::Pi * 0.25f);\n static const std::uniform_real_distribution spawnStrength(0.5f, 1.0f);\n\n emitter.tail = 1;\n emitter.update = update;\n emitter.material = resources->loadMaterial(L\"Sprites\\\\Smoke\");\n\n emitter.spritesList.resize(1000);\n auto &sprite = emitter.spritesList.front();\n sprite.position = transformComponent.position;\n sprite.velocity.x = spawnDirection(mersineTwister);\n sprite.velocity.y = spawnDirection(mersineTwister);\n sprite.velocity.z = spawnDirection(mersineTwister);\n sprite.velocity *= ((1.0f \/ sprite.velocity.getLength()) * spawnStrength(mersineTwister) * explosionComponent.strength);\n sprite.angle = spawnAngle(mersineTwister);\n sprite.torque = spawnTorque(mersineTwister);\n sprite.halfSize = 0.0f;\n sprite.age = 0.0f;\n };\n\n static const auto spark = [this](const Plugin::Entity *entity, EmitterData &emitter) -> void\n {\n static const auto update = [](const Plugin::Entity *entity, EmitterData &emitter, float frameTime) -> void\n {\n auto &sprite = emitter.spritesList.front();\n emitter.spritesList[emitter.tail++] = sprite;\n if (emitter.tail >= emitter.spritesList.size())\n {\n emitter.tail = 1;\n }\n\n sprite.position += (sprite.velocity * frameTime);\n sprite.velocity += (gravity * frameTime);\n\n combineMinimum minimum[3];\n combineMaximum maximum[3];\n concurrency::parallel_for_each((emitter.spritesList.begin() + 1), emitter.spritesList.end(), [&emitter, frameTime, &minimum, &maximum](Sprite &sprite) -> void\n {\n sprite.age += frameTime;\n sprite.angle += (sprite.torque * frameTime);\n for (uint32_t axis = 0; axis < 3; axis++)\n {\n minimum[axis].set(sprite.position[axis] - sprite.halfSize);\n maximum[axis].set(sprite.position[axis] + sprite.halfSize);\n }\n });\n\n emitter.box.minimum.x = minimum[0].get();\n emitter.box.minimum.y = minimum[1].get();\n emitter.box.minimum.z = minimum[2].get();\n emitter.box.maximum.x = maximum[0].get();\n emitter.box.maximum.y = maximum[1].get();\n emitter.box.maximum.z = maximum[2].get();\n };\n\n const auto &explosionComponent = entity->getComponent();\n const auto &transformComponent = entity->getComponent();\n\n static const std::uniform_real_distribution spawnDirection(-1.0f, 1.0f);\n static const std::uniform_real_distribution spawnAngle(0.0f, (Gek::Math::Pi * 2.0f));\n static const std::uniform_real_distribution spawnTorque(-Gek::Math::Pi, Gek::Math::Pi);\n static const std::uniform_real_distribution spawnStrength(1.0f, 2.0f);\n\n emitter.tail = 1;\n emitter.update = update;\n emitter.material = resources->loadMaterial(L\"Sprites\\\\Spark\");\n\n emitter.spritesList.resize(1000);\n auto &sprite = emitter.spritesList.front();\n sprite.position = transformComponent.position;\n sprite.velocity.x = spawnDirection(mersineTwister);\n sprite.velocity.y = spawnDirection(mersineTwister);\n sprite.velocity.z = spawnDirection(mersineTwister);\n sprite.velocity *= ((1.0f \/ sprite.velocity.getLength()) * spawnStrength(mersineTwister) * explosionComponent.strength);\n sprite.angle = spawnAngle(mersineTwister);\n sprite.torque = spawnTorque(mersineTwister);\n sprite.halfSize = 0.1f;\n sprite.age = 0.0f;\n };\n\n if (entity->hasComponent())\n {\n auto &entityEmitterList = entityEmitterMap[entity];\n\n entityEmitterList.resize(30);\n for (uint32_t index = 0; index < 20; index++)\n {\n smoke(entity, entityEmitterList[index]);\n }\n\n for (uint32_t index = 20; index < 30; index++)\n {\n spark(entity, entityEmitterList[index]);\n }\n }\n }\n }\n\n void onEntityDestroyed(Plugin::Entity *entity)\n {\n GEK_REQUIRE(entity);\n\n auto entitySearch = entityEmitterMap.find(entity);\n if (entitySearch != entityEmitterMap.end())\n {\n entityEmitterMap.erase(entitySearch);\n }\n }\n\n \/\/ Plugin::PopulationStep\n void onUpdate(uint32_t order, State state)\n {\n if (state == State::Active)\n {\n const float frameTime = population->getFrameTime() * 0.1f;\n concurrency::parallel_for_each(entityEmitterMap.begin(), entityEmitterMap.end(), [&](auto &entityEmitterPair) -> void\n {\n const Plugin::Entity *entity = entityEmitterPair.first;\n concurrency::parallel_for_each(entityEmitterPair.second.begin(), entityEmitterPair.second.end(), [&](auto &emitter) -> void\n {\n emitter.update(entity, emitter, frameTime);\n });\n });\n }\n }\n\n \/\/ Plugin::RendererListener\n static void drawCall(Video::Device::Context *deviceContext, Plugin::Resources *resources, const VisibleMap::iterator visibleBegin, const VisibleMap::iterator visibleEnd, Video::Buffer *spritesBuffer)\n {\n GEK_REQUIRE(deviceContext);\n GEK_REQUIRE(resources);\n\n deviceContext->vertexPipeline()->setResource(spritesBuffer, 0);\n\n uint32_t bufferCopied = 0;\n Sprite *bufferData = nullptr;\n deviceContext->getDevice()->mapBuffer(spritesBuffer, (void **)&bufferData);\n for (auto emitterSearch = visibleBegin; emitterSearch != visibleEnd; ++emitterSearch)\n {\n const auto &emitter = *emitterSearch->second;\n\n uint32_t spritesCopied = 0;\n uint32_t spritesCount = emitter.spritesList.size();\n const Sprite *spriteData = emitter.spritesList.data();\n while (spritesCopied < spritesCount)\n {\n uint32_t bufferRemaining = (SpritesBufferCount - bufferCopied);\n uint32_t spritesRemaining = (spritesCount - spritesCopied);\n uint32_t copyCount = std::min(bufferRemaining, spritesRemaining);\n memcpy(&bufferData[bufferCopied], &spriteData[spritesCopied], (sizeof(Sprite) * copyCount));\n\n bufferCopied += copyCount;\n spritesCopied += copyCount;\n if (bufferCopied >= SpritesBufferCount)\n {\n deviceContext->getDevice()->unmapBuffer(spritesBuffer);\n deviceContext->drawPrimitive((SpritesBufferCount * 6), 0);\n deviceContext->getDevice()->mapBuffer(spritesBuffer, (void **)&bufferData);\n bufferCopied = 0;\n }\n };\n }\n\n deviceContext->getDevice()->unmapBuffer(spritesBuffer);\n if (bufferCopied > 0)\n {\n deviceContext->drawPrimitive((bufferCopied * 6), 0);\n }\n }\n\n void onRenderScene(const Plugin::Entity *cameraEntity, const Math::Float4x4 &viewMatrix, const Shapes::Frustum &viewFrustum)\n {\n GEK_REQUIRE(renderer);\n GEK_REQUIRE(cameraEntity);\n\n visibleMap.clear();\n concurrency::parallel_for_each(entityEmitterMap.begin(), entityEmitterMap.end(), [&](auto &entityEmitterPair) -> void\n {\n concurrency::parallel_for_each(entityEmitterPair.second.begin(), entityEmitterPair.second.end(), [&](auto &emitter) -> void\n {\n if (viewFrustum.isVisible(emitter.box))\n {\n visibleMap.insert(std::make_pair(emitter.material, &emitter));\n }\n });\n });\n\n for (auto propertiesSearch = visibleMap.begin(); propertiesSearch != visibleMap.end(); )\n {\n const auto emittersRange = visibleMap.equal_range(propertiesSearch->first);\n renderer->queueDrawCall(visual, propertiesSearch->first, std::bind(drawCall, std::placeholders::_1, resources, emittersRange.first, emittersRange.second, spritesBuffer.get()));\n propertiesSearch = emittersRange.second;\n }\n }\n };\n\n std::random_device EmitterProcessor::randomDevice;\n std::mt19937 EmitterProcessor::mersineTwister(randomDevice());\n\n GEK_REGISTER_CONTEXT_USER(Explosion)\n GEK_REGISTER_CONTEXT_USER(EmitterProcessor)\n }; \/\/ namespace Sprites\n}; \/\/ namespace GekImproving spherical point sampling, but slower. Not a major issue since only the initial point is calculated.#include \"GEK\\Math\\Float4x4.h\"\n#include \"GEK\\Shapes\\AlignedBox.h\"\n#include \"GEK\\Shapes\\OrientedBox.h\"\n#include \"GEK\\Utility\\FileSystem.h\"\n#include \"GEK\\Utility\\String.h\"\n#include \"GEK\\Utility\\XML.h\"\n#include \"GEK\\Utility\\Allocator.h\"\n#include \"GEK\\Context\\ContextUser.h\"\n#include \"GEK\\System\\VideoDevice.h\"\n#include \"GEK\\Engine\\Core.h\"\n#include \"GEK\\Engine\\Processor.h\"\n#include \"GEK\\Engine\\ComponentMixin.h\"\n#include \"GEK\\Engine\\Population.h\"\n#include \"GEK\\Engine\\Entity.h\"\n#include \"GEK\\Engine\\Renderer.h\"\n#include \"GEK\\Engine\\Resources.h\"\n#include \"GEK\\Components\\Transform.h\"\n#include \"GEK\\Components\\Color.h\"\n#include \n#include \n#include \n#include \n\nnamespace Gek\n{\n namespace Components\n {\n GEK_COMPONENT(Explosion)\n {\n float strength;\n\n void save(Plugin::Population::ComponentDefinition &componentData) const\n {\n saveParameter(componentData, L\"strength\", strength);\n }\n\n void load(const Plugin::Population::ComponentDefinition &componentData)\n {\n strength = loadParameter(componentData, L\"strength\", 10.0f);\n }\n };\n }; \/\/ namespace Components\n\n namespace Sprites\n {\n GEK_CONTEXT_USER(Explosion)\n , public Plugin::ComponentMixin\n {\n public:\n Explosion(Context *context)\n : ContextRegistration(context)\n {\n }\n\n \/\/ Plugin::Component\n const wchar_t * const getName(void) const\n {\n return L\"explosion\";\n }\n };\n\n GEK_CONTEXT_USER(EmitterProcessor, Plugin::Core *)\n , public Plugin::PopulationListener\n , public Plugin::PopulationStep\n , public Plugin::RendererListener\n , public Plugin::Processor\n {\n public:\n static const uint32_t SpritesBufferCount = 1000000;\n static std::random_device randomDevice;\n static std::mt19937 mersineTwister;\n\n __declspec(align(16))\n struct Sprite\n {\n Math::Float3 position;\n Math::Float3 velocity;\n float angle;\n float torque;\n float halfSize;\n float age;\n float buffer[2];\n\n Sprite(void)\n : halfSize(0.0f)\n {\n }\n };\n\n struct EmitterData\n {\n Shapes::AlignedBox box;\n MaterialHandle material;\n std::vector spritesList;\n\n uint32_t tail;\n std::function update;\n };\n\n private:\n Plugin::Population *population;\n Plugin::Resources *resources;\n Plugin::Renderer *renderer;\n\n VisualHandle visual;\n Video::BufferPtr spritesBuffer;\n\n using EntityEmitterMap = std::unordered_map>;\n EntityEmitterMap entityEmitterMap;\n\n using VisibleMap = concurrency::concurrent_unordered_multimap;\n VisibleMap visibleMap;\n\n public:\n EmitterProcessor(Context *context, Plugin::Core *core)\n : ContextRegistration(context)\n , population(core->getPopulation())\n , resources(core->getResources())\n , renderer(core->getRenderer())\n {\n GEK_REQUIRE(population);\n GEK_REQUIRE(resources);\n GEK_REQUIRE(renderer);\n\n population->addListener(this);\n population->addStep(this, 60);\n renderer->addListener(this);\n\n visual = resources->loadVisual(L\"Sprites\");\n spritesBuffer = renderer->getDevice()->createBuffer(sizeof(Sprite), SpritesBufferCount, Video::BufferType::Structured, Video::BufferFlags::Mappable | Video::BufferFlags::Resource, false);\n }\n\n ~EmitterProcessor(void)\n {\n renderer->removeListener(this);\n population->removeStep(this);\n population->removeListener(this);\n }\n\n \/\/ Plugin::PopulationListener\n void onLoadBegin(void)\n {\n entityEmitterMap.clear();\n }\n\n void onLoadSucceeded(void)\n {\n }\n\n void onLoadFailed(void)\n {\n }\n\n struct combineMinimum\n {\n concurrency::combinable combinable;\n\n combineMinimum(void)\n : combinable([&]\n {\n return Math::Infinity;\n })\n {\n }\n\n void set(float value)\n {\n auto &localValue = combinable.local();\n localValue = std::min(value, localValue);\n }\n\n float get(void)\n {\n return combinable.combine([](float left, float right)\n {\n return std::min(left, right);\n });\n }\n };\n\n struct combineMaximum\n {\n concurrency::combinable combinable;\n\n combineMaximum(void)\n : combinable([&]\n {\n return Math::NegativeInfinity;\n })\n {\n }\n\n void set(float value)\n {\n auto &localValue = combinable.local();\n localValue = std::max(value, localValue);\n }\n\n float get(void)\n {\n return combinable.combine([](float left, float right)\n {\n return std::max(left, right);\n });\n }\n };\n\n void onEntityCreated(Plugin::Entity *entity)\n {\n GEK_REQUIRE(resources);\n GEK_REQUIRE(entity);\n\n if (entity->hasComponent())\n {\n static const Math::Float3 gravity(0.0f, -32.174f, 0.0f);\n static const auto smoke = [this](const Plugin::Entity *entity, EmitterData &emitter) -> void\n {\n static const auto update = [](const Plugin::Entity *entity, EmitterData &emitter, float frameTime) -> void\n {\n auto &sprite = emitter.spritesList.front();\n emitter.spritesList[emitter.tail++] = sprite;\n if (emitter.tail >= emitter.spritesList.size())\n {\n emitter.tail = 1;\n }\n\n sprite.position += (sprite.velocity * frameTime);\n\n combineMinimum minimum[3];\n combineMaximum maximum[3];\n concurrency::parallel_for_each((emitter.spritesList.begin() + 1), emitter.spritesList.end(), [&emitter, frameTime, &minimum, &maximum](Sprite &sprite) -> void\n {\n sprite.age += frameTime;\n sprite.halfSize += frameTime;\n sprite.angle += (sprite.torque * frameTime);\n \/\/sprite.position -= (gravity * frameTime);\n for (uint32_t axis = 0; axis < 3; axis++)\n {\n minimum[axis].set(sprite.position[axis] - sprite.halfSize);\n maximum[axis].set(sprite.position[axis] + sprite.halfSize);\n }\n });\n\n emitter.box.minimum.x = minimum[0].get();\n emitter.box.minimum.y = minimum[1].get();\n emitter.box.minimum.z = minimum[2].get();\n emitter.box.maximum.x = maximum[0].get();\n emitter.box.maximum.y = maximum[1].get();\n emitter.box.maximum.z = maximum[2].get();\n };\n\n const auto &explosionComponent = entity->getComponent();\n const auto &transformComponent = entity->getComponent();\n\n static const std::uniform_real_distribution spawnDirection(-1.0f, 1.0f);\n static const std::uniform_real_distribution spawnAzimuthal(0.0f, (Gek::Math::Pi * 2.0f));\n static const std::uniform_real_distribution spawnZenith(0.0f, 1.0f);\n static const std::uniform_real_distribution spawnCircle(-Gek::Math::Pi, Gek::Math::Pi);\n static const std::uniform_real_distribution spawnStrength(0.5f, 1.0f);\n\n emitter.tail = 1;\n emitter.update = update;\n emitter.material = resources->loadMaterial(L\"Sprites\\\\Smoke\");\n emitter.spritesList.resize(1000);\n\n float theta = spawnAzimuthal(mersineTwister);\n float phi = acos(spawnDirection(mersineTwister));\n\n auto &sprite = emitter.spritesList.front();\n sprite.position = transformComponent.position;\n sprite.velocity.x = std::sin(phi) * std::sin(theta);\n sprite.velocity.y = -std::sin(phi) * std::cos(theta);\n sprite.velocity.z = std::cos(phi);\n sprite.velocity *= (spawnStrength(mersineTwister) * explosionComponent.strength);\n sprite.angle = spawnCircle(mersineTwister);\n sprite.torque = spawnCircle(mersineTwister);\n sprite.halfSize = 0.1f;\n sprite.age = 0.0f;\n };\n\n static const auto spark = [this](const Plugin::Entity *entity, EmitterData &emitter) -> void\n {\n static const auto update = [](const Plugin::Entity *entity, EmitterData &emitter, float frameTime) -> void\n {\n auto &sprite = emitter.spritesList.front();\n emitter.spritesList[emitter.tail++] = sprite;\n if (emitter.tail >= emitter.spritesList.size())\n {\n emitter.tail = 1;\n }\n\n sprite.position += (sprite.velocity * frameTime);\n sprite.velocity += (gravity * frameTime);\n\n combineMinimum minimum[3];\n combineMaximum maximum[3];\n concurrency::parallel_for_each((emitter.spritesList.begin() + 1), emitter.spritesList.end(), [&emitter, frameTime, &minimum, &maximum](Sprite &sprite) -> void\n {\n sprite.age += frameTime;\n sprite.angle += (sprite.torque * frameTime);\n for (uint32_t axis = 0; axis < 3; axis++)\n {\n minimum[axis].set(sprite.position[axis] - sprite.halfSize);\n maximum[axis].set(sprite.position[axis] + sprite.halfSize);\n }\n });\n\n emitter.box.minimum.x = minimum[0].get();\n emitter.box.minimum.y = minimum[1].get();\n emitter.box.minimum.z = minimum[2].get();\n emitter.box.maximum.x = maximum[0].get();\n emitter.box.maximum.y = maximum[1].get();\n emitter.box.maximum.z = maximum[2].get();\n };\n\n const auto &explosionComponent = entity->getComponent();\n const auto &transformComponent = entity->getComponent();\n\n static const std::uniform_real_distribution spawnDirection(-1.0f, 1.0f);\n static const std::uniform_real_distribution spawnAzimuthal(0.0f, (Gek::Math::Pi * 2.0f));\n static const std::uniform_real_distribution spawnZenith(0.0f, 1.0f);\n static const std::uniform_real_distribution spawnCircle(-Gek::Math::Pi, Gek::Math::Pi);\n static const std::uniform_real_distribution spawnStrength(1.0f, 2.0f);\n\n emitter.tail = 1;\n emitter.update = update;\n emitter.material = resources->loadMaterial(L\"Sprites\\\\Spark\");\n emitter.spritesList.resize(1000);\n\n float theta = spawnAzimuthal(mersineTwister);\n float phi = acos(spawnDirection(mersineTwister));\n\n auto &sprite = emitter.spritesList.front();\n sprite.position = transformComponent.position;\n sprite.velocity.x = std::sin(phi) * std::sin(theta);\n sprite.velocity.y = -std::sin(phi) * std::cos(theta);\n sprite.velocity.z = std::cos(phi);\n sprite.velocity *= (spawnStrength(mersineTwister) * explosionComponent.strength);\n sprite.angle = spawnCircle(mersineTwister);\n sprite.torque = spawnCircle(mersineTwister);\n sprite.halfSize = 0.1f;\n sprite.age = 0.0f;\n };\n\n if (entity->hasComponent())\n {\n auto &entityEmitterList = entityEmitterMap[entity];\n\n entityEmitterList.resize(30);\n for (uint32_t index = 0; index < 20; index++)\n {\n smoke(entity, entityEmitterList[index]);\n }\n\n for (uint32_t index = 20; index < 30; index++)\n {\n spark(entity, entityEmitterList[index]);\n }\n }\n }\n }\n\n void onEntityDestroyed(Plugin::Entity *entity)\n {\n GEK_REQUIRE(entity);\n\n auto entitySearch = entityEmitterMap.find(entity);\n if (entitySearch != entityEmitterMap.end())\n {\n entityEmitterMap.erase(entitySearch);\n }\n }\n\n \/\/ Plugin::PopulationStep\n void onUpdate(uint32_t order, State state)\n {\n if (state == State::Active)\n {\n const float frameTime = population->getFrameTime() * 0.1f;\n concurrency::parallel_for_each(entityEmitterMap.begin(), entityEmitterMap.end(), [&](auto &entityEmitterPair) -> void\n {\n const Plugin::Entity *entity = entityEmitterPair.first;\n concurrency::parallel_for_each(entityEmitterPair.second.begin(), entityEmitterPair.second.end(), [&](auto &emitter) -> void\n {\n emitter.update(entity, emitter, frameTime);\n });\n });\n }\n }\n\n \/\/ Plugin::RendererListener\n static void drawCall(Video::Device::Context *deviceContext, Plugin::Resources *resources, const VisibleMap::iterator visibleBegin, const VisibleMap::iterator visibleEnd, Video::Buffer *spritesBuffer)\n {\n GEK_REQUIRE(deviceContext);\n GEK_REQUIRE(resources);\n\n deviceContext->vertexPipeline()->setResource(spritesBuffer, 0);\n\n uint32_t bufferCopied = 0;\n Sprite *bufferData = nullptr;\n deviceContext->getDevice()->mapBuffer(spritesBuffer, (void **)&bufferData);\n for (auto emitterSearch = visibleBegin; emitterSearch != visibleEnd; ++emitterSearch)\n {\n const auto &emitter = *emitterSearch->second;\n\n uint32_t spritesCopied = 0;\n uint32_t spritesCount = emitter.spritesList.size();\n const Sprite *spriteData = emitter.spritesList.data();\n while (spritesCopied < spritesCount)\n {\n uint32_t bufferRemaining = (SpritesBufferCount - bufferCopied);\n uint32_t spritesRemaining = (spritesCount - spritesCopied);\n uint32_t copyCount = std::min(bufferRemaining, spritesRemaining);\n memcpy(&bufferData[bufferCopied], &spriteData[spritesCopied], (sizeof(Sprite) * copyCount));\n\n bufferCopied += copyCount;\n spritesCopied += copyCount;\n if (bufferCopied >= SpritesBufferCount)\n {\n deviceContext->getDevice()->unmapBuffer(spritesBuffer);\n deviceContext->drawPrimitive((SpritesBufferCount * 6), 0);\n deviceContext->getDevice()->mapBuffer(spritesBuffer, (void **)&bufferData);\n bufferCopied = 0;\n }\n };\n }\n\n deviceContext->getDevice()->unmapBuffer(spritesBuffer);\n if (bufferCopied > 0)\n {\n deviceContext->drawPrimitive((bufferCopied * 6), 0);\n }\n }\n\n void onRenderScene(const Plugin::Entity *cameraEntity, const Math::Float4x4 &viewMatrix, const Shapes::Frustum &viewFrustum)\n {\n GEK_REQUIRE(renderer);\n GEK_REQUIRE(cameraEntity);\n\n visibleMap.clear();\n concurrency::parallel_for_each(entityEmitterMap.begin(), entityEmitterMap.end(), [&](auto &entityEmitterPair) -> void\n {\n concurrency::parallel_for_each(entityEmitterPair.second.begin(), entityEmitterPair.second.end(), [&](auto &emitter) -> void\n {\n if (viewFrustum.isVisible(emitter.box))\n {\n visibleMap.insert(std::make_pair(emitter.material, &emitter));\n }\n });\n });\n\n for (auto propertiesSearch = visibleMap.begin(); propertiesSearch != visibleMap.end(); )\n {\n const auto emittersRange = visibleMap.equal_range(propertiesSearch->first);\n renderer->queueDrawCall(visual, propertiesSearch->first, std::bind(drawCall, std::placeholders::_1, resources, emittersRange.first, emittersRange.second, spritesBuffer.get()));\n propertiesSearch = emittersRange.second;\n }\n }\n };\n\n std::random_device EmitterProcessor::randomDevice;\n std::mt19937 EmitterProcessor::mersineTwister(randomDevice());\n\n GEK_REGISTER_CONTEXT_USER(Explosion)\n GEK_REGISTER_CONTEXT_USER(EmitterProcessor)\n }; \/\/ namespace Sprites\n}; \/\/ namespace Gek<|endoftext|>"} {"text":"\/****************** *****************\n *\n * VR Juggler Portable Runtime\n *\n * Original Authors:\n * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n ****************** ******************\/\n\n\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\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\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************\/\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define XML_OR_LEVEL vprDBG_HEX_LVL\n\n\nnamespace\n{\n\/** Helper to read the data from the current string *\/\n template\n vpr::ReturnStatus readValueStringRep(T& val, std::stringstream* inStream)\n {\n vprASSERT(inStream != NULL);\n\n \/\/ Just to be safe do this again for the heck of it. :)\n \/\/in_stream->exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n vprASSERT(!inStream->bad() && \"Bad stream, BAAADDD stream.\");\n vprASSERT(!inStream->fail() && \"Stream failed.\");\n vprASSERT(!inStream->eof() && \"Stream EOF'd.\");\n vprASSERT(inStream->good());\n\n \/\/stream_content = (*in_stream).str();\n\n (*inStream) >> val;\n\n return vpr::ReturnStatus::Succeed;\n }\n\n}\n\nnamespace vpr\n{\n\nXMLObjectReader::XMLObjectReader(std::vector data)\n : mCurSource(CdataSource)\n{\n initCppDomTree(data);\n \/\/mAttribSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n}\n\nXMLObjectReader::XMLObjectReader(cppdom::NodePtr rootNode)\n : mCurSource(CdataSource)\n{\n mRootNode = rootNode;\n \/\/mAttribSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n}\n\n\n\nXMLObjectReader::NodeState::NodeState(cppdom::Node* cur_node)\n : node(cur_node)\n{\n nextChild_i = node->getChildren().begin(); \/\/ Initialize to the first child\n endChild_i = node->getChildren().end();\n \/\/cdataSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n cdataSource.str(node->getFullCdata());\n}\n\nXMLObjectReader::NodeState::NodeState(const NodeState& rhs)\n{\n node = rhs.node;\n nextChild_i = rhs.nextChild_i;\n endChild_i = rhs.endChild_i;\n \/\/cdataSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n cdataSource.str(rhs.cdataSource.str());\n}\n\nXMLObjectReader::NodeState& XMLObjectReader::NodeState::operator=(const NodeState& rhs)\n{\n node = rhs.node;\n nextChild_i = rhs.nextChild_i;\n endChild_i = rhs.endChild_i;\n cdataSource.str(rhs.cdataSource.str());\n return *this;\n}\n\nvoid XMLObjectReader::NodeState::debugDump(int debug_level)\n{\n vprDEBUG(vprDBG_ALL, debug_level) << \"Node:\" << node->getName() << \" num children:\" << node->getChildren().size()\n << \" distance: nextChild-->endChild:\" << std::distance(nextChild_i,endChild_i) << std::endl << vprDEBUG_FLUSH;\n}\n\n\n\/** Get the current string source we are reading from.\n*\/\nstd::stringstream* XMLObjectReader::getCurSource()\n{\n std::stringstream* in_stream(NULL);\n\n if(AttribSource == mCurSource)\n {\n in_stream = &mAttribSource;\n }\n else\n {\n in_stream = &(mCurNodeStack.back().cdataSource);\n }\n\n return in_stream;\n}\n\n\/** Initialize the members based on a serialized version of something in the data buffer *\/\nvoid XMLObjectReader::initCppDomTree(std::vector data)\n{\n std::string xml_data(data.begin(), data.end());\n std::stringstream xml_stream(xml_data);\n cppdom::ContextPtr cxt(new cppdom::Context);\n cppdom::NodePtr new_node = cppdom::NodePtr(new cppdom::Node(cxt));\n new_node->load(xml_stream, cxt);\n\n mRootNode = new_node;\n\n std::string root_name = mRootNode->getName(); \/\/ Debugging\n\n mCurNodeStack.clear();\n}\n\nvoid XMLObjectReader::debugDumpStack(int debug_level)\n{\n vprDEBUG_OutputGuard(vprDBG_ALL, debug_level, \"mCurNodeStack:\\n\", \"end node stack\\n\");\n\n for(unsigned i=0; igetName()\n << \" num children:\" << mCurNodeStack.back().node->getChildren().size() << std::endl << vprDEBUG_FLUSH;\n\n vprASSERT(mCurNodeStack.back().nextChild_i != mCurNodeStack.back().endChild_i && \"Past last child. No remaining child tags.\");\n\n \/\/ Make sure that we get to child of type node.\n \/\/ While next child is not of type node skip over cdata...\n while( (*(mCurNodeStack.back().nextChild_i))->getType() != cppdom::xml_nt_node)\n {\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \"Skip node: \" << (*(mCurNodeStack.back().nextChild_i))->getName() << \" -- non nt_node type.\\n\" << vprDEBUG_FLUSH;\n mCurNodeStack.back().nextChild_i++;\n vprASSERT(mCurNodeStack.back().nextChild_i != mCurNodeStack.back().endChild_i && \"Skipped past last child. No remaining child tags.\");\n }\n\n cppdom::NodePtr tag_node = *(mCurNodeStack.back().nextChild_i); \/\/ Get the node with the given tag\n mCurNodeStack.back().nextChild_i++; \/\/ Step to the next child for next time\n\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \"Incrementing next child: at end:\" << (mCurNodeStack.back().nextChild_i == mCurNodeStack.back().endChild_i) << std::endl << vprDEBUG_FLUSH;\n\n mCurNodeStack.push_back( NodeState(tag_node.get())); \/\/ Add the child to the stack\n vprASSERT(tag_node.get() == mCurNodeStack.back().node);\n\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \"Found node:\" << tag_node->getName() << std::endl << vprDEBUG_FLUSH;\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \" Node stack size:\" << mCurNodeStack.size() << std::endl << vprDEBUG_FLUSH;\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \" Num children:\" << tag_node->getChildren().size() << std::endl << vprDEBUG_FLUSH;\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \" New node child at end:\" << (mCurNodeStack.back().nextChild_i == mCurNodeStack.back().endChild_i)\n << std::endl << vprDEBUG_FLUSH;\n }\n\n std::string cur_node_name = mCurNodeStack.back().node->getName();\n vprASSERT(tagName == cur_node_name && \"Reading back in incorrect order\");\n return vpr::ReturnStatus::Succeed;\n}\n\n\/** Ends the most recently named tag.\n* Just pop of the cur node state information\n*\/\nvpr::ReturnStatus XMLObjectReader::endTag()\n{\n vprASSERT(!mCurNodeStack.empty());\n mCurNodeStack.pop_back();\n return vpr::ReturnStatus::Succeed;\n}\n\n\/** Starts an attribute of the name attributeName\n* Get the attribute content and set the attribute source with that content\n*\/\nvpr::ReturnStatus XMLObjectReader::beginAttribute(std::string attributeName)\n{\n \/\/std::cout << \"beginAttribute: \" << attributeName << std::endl;\n std::string attrib_content = mCurNodeStack.back().node->getAttribute(attributeName).getString();\n \/\/std::cout << \" attrib content: [\" << attrib_content << \"]\\n\";\n mAttribSource.clear(); \/\/ Clear error states\n mAttribSource.str(attrib_content);\n mAttribSource.seekg(0,std::ios::beg); \/\/ Seek to beginning\n \/\/std::cout << \" mAttribSource.str():[\" << mAttribSource.str() << \"]\" << std::endl;\n mCurSource = AttribSource; \/\/ Get content from attribute now\n return vpr::ReturnStatus::Succeed;\n}\n\n\/** Ends the most recently named attribute *\/\nvpr::ReturnStatus XMLObjectReader::endAttribute()\n{\n mAttribSource.clear();\n mAttribSource.seekg(0,std::ios::beg);\n mAttribSource.str(\"\"); \/\/ Clear the attrib content (not required, but helps point out bugs)\n mCurSource = CdataSource; \/\/ Set back to getting data from cdata\n return vpr::ReturnStatus::Succeed;\n}\n\/\/@}\n\nvoid XMLObjectReader::resetReading()\n{\n mCurSource = CdataSource;\n mCurNodeStack.clear();\n}\n\nvoid XMLObjectReader::pushState()\n{\n ReadState cur_state;\n cur_state.mNodeStack = mCurNodeStack;\n mReadStateStack.push_back(cur_state);\n}\n\nvoid XMLObjectReader::popState()\n{\n ReadState new_state = mReadStateStack.back();\n mReadStateStack.pop_back();\n mCurNodeStack = new_state.mNodeStack;\n}\n\n\n\nvpr::Uint8 XMLObjectReader::readUint8()\n{\n \/\/ Read a uint16 so that it does not treat it as a single char\n vpr::Uint16 temp_data;\n readValueStringRep(temp_data, getCurSource());\n return vpr::Uint8(temp_data);\n}\n\nvpr::Uint16 XMLObjectReader::readUint16()\n{\n vpr::Uint16 val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\nvpr::Uint32 XMLObjectReader::readUint32()\n{\n vpr::Uint32 val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\nvpr::Uint64 XMLObjectReader::readUint64()\n{\n vpr::Uint64 val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\nfloat XMLObjectReader::readFloat()\n{\n float val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\ndouble XMLObjectReader::readDouble()\n{\n double val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\n\nstd::string XMLObjectReader::readString()\n{\n std::string ret_val(\"\"); \n\n if(AttribSource == mCurSource) \/\/ Just return a copy of the attribute source\n {\n ret_val = mAttribSource.str();\n }\n else \/\/ Cdata, extract the \"'s around the string\n {\n char char_buffer[1024]; \/\/ Buffer for writing the final value\n char temp_char('0');\n\n \/\/ Get the first \"\n while('\"' != temp_char)\n {\n mCurNodeStack.back().cdataSource.get(temp_char);\n vprASSERT(('>' != temp_char) && ('<' != temp_char) && \"String delimiter not found\");\n }\n\n \/\/ Get the contents of the string\n char next_char = mCurNodeStack.back().cdataSource.peek();\n bool done_reading(next_char == '\"'); \/\/ If next char is already \", then we are done reading empty string\n \n while(!done_reading)\n {\n mCurNodeStack.back().cdataSource.get(char_buffer,1024, '\"'); \/\/ Copy over to target until we have second \"\n ret_val += char_buffer; \/\/ append onto end\n next_char = mCurNodeStack.back().cdataSource.peek();\n done_reading = (next_char == '\"'); \/\/ Done reading if got to a \"\n }\n mCurNodeStack.back().cdataSource.ignore(1); \/\/ Ignore that \" as well\n }\n\n return ret_val;\n}\n\nbool XMLObjectReader::readBool()\n{\n bool val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\n} \/\/ namespace vpr\n\nUpdate to work with latest version of cppdom.\/****************** *****************\n *\n * VR Juggler Portable Runtime\n *\n * Original Authors:\n * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n ****************** ******************\/\n\n\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\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\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************\/\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define XML_OR_LEVEL vprDBG_HEX_LVL\n\n\nnamespace\n{\n\/** Helper to read the data from the current string *\/\n template\n vpr::ReturnStatus readValueStringRep(T& val, std::stringstream* inStream)\n {\n vprASSERT(inStream != NULL);\n\n \/\/ Just to be safe do this again for the heck of it. :)\n \/\/in_stream->exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n vprASSERT(!inStream->bad() && \"Bad stream, BAAADDD stream.\");\n vprASSERT(!inStream->fail() && \"Stream failed.\");\n vprASSERT(!inStream->eof() && \"Stream EOF'd.\");\n vprASSERT(inStream->good());\n\n \/\/stream_content = (*in_stream).str();\n\n (*inStream) >> val;\n\n return vpr::ReturnStatus::Succeed;\n }\n\n}\n\nnamespace vpr\n{\n\nXMLObjectReader::XMLObjectReader(std::vector data)\n : mCurSource(CdataSource)\n{\n initCppDomTree(data);\n \/\/mAttribSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n}\n\nXMLObjectReader::XMLObjectReader(cppdom::NodePtr rootNode)\n : mCurSource(CdataSource)\n{\n mRootNode = rootNode;\n \/\/mAttribSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n}\n\n\n\nXMLObjectReader::NodeState::NodeState(cppdom::Node* cur_node)\n : node(cur_node)\n{\n nextChild_i = node->getChildren().begin(); \/\/ Initialize to the first child\n endChild_i = node->getChildren().end();\n \/\/cdataSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n cdataSource.str(node->getFullCdata());\n}\n\nXMLObjectReader::NodeState::NodeState(const NodeState& rhs)\n{\n node = rhs.node;\n nextChild_i = rhs.nextChild_i;\n endChild_i = rhs.endChild_i;\n \/\/cdataSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );\n cdataSource.str(rhs.cdataSource.str());\n}\n\nXMLObjectReader::NodeState& XMLObjectReader::NodeState::operator=(const NodeState& rhs)\n{\n node = rhs.node;\n nextChild_i = rhs.nextChild_i;\n endChild_i = rhs.endChild_i;\n cdataSource.str(rhs.cdataSource.str());\n return *this;\n}\n\nvoid XMLObjectReader::NodeState::debugDump(int debug_level)\n{\n vprDEBUG(vprDBG_ALL, debug_level) << \"Node:\" << node->getName() << \" num children:\" << node->getChildren().size()\n << \" distance: nextChild-->endChild:\" << std::distance(nextChild_i,endChild_i) << std::endl << vprDEBUG_FLUSH;\n}\n\n\n\/** Get the current string source we are reading from.\n*\/\nstd::stringstream* XMLObjectReader::getCurSource()\n{\n std::stringstream* in_stream(NULL);\n\n if(AttribSource == mCurSource)\n {\n in_stream = &mAttribSource;\n }\n else\n {\n in_stream = &(mCurNodeStack.back().cdataSource);\n }\n\n return in_stream;\n}\n\n\/** Initialize the members based on a serialized version of something in the data buffer *\/\nvoid XMLObjectReader::initCppDomTree(std::vector data)\n{\n std::string xml_data(data.begin(), data.end());\n std::stringstream xml_stream(xml_data);\n cppdom::ContextPtr cxt(new cppdom::Context);\n cppdom::NodePtr new_node = cppdom::NodePtr(new cppdom::Node(cxt));\n new_node->load(xml_stream, cxt);\n\n mRootNode = new_node;\n\n std::string root_name = mRootNode->getName(); \/\/ Debugging\n\n mCurNodeStack.clear();\n}\n\nvoid XMLObjectReader::debugDumpStack(int debug_level)\n{\n vprDEBUG_OutputGuard(vprDBG_ALL, debug_level, \"mCurNodeStack:\\n\", \"end node stack\\n\");\n\n for(unsigned i=0; igetName()\n << \" num children:\" << mCurNodeStack.back().node->getChildren().size() << std::endl << vprDEBUG_FLUSH;\n\n vprASSERT(mCurNodeStack.back().nextChild_i != mCurNodeStack.back().endChild_i && \"Past last child. No remaining child tags.\");\n\n \/\/ Make sure that we get to child of type node.\n \/\/ While next child is not of type node skip over cdata...\n while( (*(mCurNodeStack.back().nextChild_i))->getType() != cppdom::Node::xml_nt_node)\n {\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \"Skip node: \" << (*(mCurNodeStack.back().nextChild_i))->getName() << \" -- non nt_node type.\\n\" << vprDEBUG_FLUSH;\n mCurNodeStack.back().nextChild_i++;\n vprASSERT(mCurNodeStack.back().nextChild_i != mCurNodeStack.back().endChild_i && \"Skipped past last child. No remaining child tags.\");\n }\n\n cppdom::NodePtr tag_node = *(mCurNodeStack.back().nextChild_i); \/\/ Get the node with the given tag\n mCurNodeStack.back().nextChild_i++; \/\/ Step to the next child for next time\n\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \"Incrementing next child: at end:\" << (mCurNodeStack.back().nextChild_i == mCurNodeStack.back().endChild_i) << std::endl << vprDEBUG_FLUSH;\n\n mCurNodeStack.push_back( NodeState(tag_node.get())); \/\/ Add the child to the stack\n vprASSERT(tag_node.get() == mCurNodeStack.back().node);\n\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \"Found node:\" << tag_node->getName() << std::endl << vprDEBUG_FLUSH;\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \" Node stack size:\" << mCurNodeStack.size() << std::endl << vprDEBUG_FLUSH;\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \" Num children:\" << tag_node->getChildren().size() << std::endl << vprDEBUG_FLUSH;\n vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << \" New node child at end:\" << (mCurNodeStack.back().nextChild_i == mCurNodeStack.back().endChild_i)\n << std::endl << vprDEBUG_FLUSH;\n }\n\n std::string cur_node_name = mCurNodeStack.back().node->getName();\n vprASSERT(tagName == cur_node_name && \"Reading back in incorrect order\");\n return vpr::ReturnStatus::Succeed;\n}\n\n\/** Ends the most recently named tag.\n* Just pop of the cur node state information\n*\/\nvpr::ReturnStatus XMLObjectReader::endTag()\n{\n vprASSERT(!mCurNodeStack.empty());\n mCurNodeStack.pop_back();\n return vpr::ReturnStatus::Succeed;\n}\n\n\/** Starts an attribute of the name attributeName\n* Get the attribute content and set the attribute source with that content\n*\/\nvpr::ReturnStatus XMLObjectReader::beginAttribute(std::string attributeName)\n{\n \/\/std::cout << \"beginAttribute: \" << attributeName << std::endl;\n std::string attrib_content = mCurNodeStack.back().node->getAttribute(attributeName).getString();\n \/\/std::cout << \" attrib content: [\" << attrib_content << \"]\\n\";\n mAttribSource.clear(); \/\/ Clear error states\n mAttribSource.str(attrib_content);\n mAttribSource.seekg(0,std::ios::beg); \/\/ Seek to beginning\n \/\/std::cout << \" mAttribSource.str():[\" << mAttribSource.str() << \"]\" << std::endl;\n mCurSource = AttribSource; \/\/ Get content from attribute now\n return vpr::ReturnStatus::Succeed;\n}\n\n\/** Ends the most recently named attribute *\/\nvpr::ReturnStatus XMLObjectReader::endAttribute()\n{\n mAttribSource.clear();\n mAttribSource.seekg(0,std::ios::beg);\n mAttribSource.str(\"\"); \/\/ Clear the attrib content (not required, but helps point out bugs)\n mCurSource = CdataSource; \/\/ Set back to getting data from cdata\n return vpr::ReturnStatus::Succeed;\n}\n\/\/@}\n\nvoid XMLObjectReader::resetReading()\n{\n mCurSource = CdataSource;\n mCurNodeStack.clear();\n}\n\nvoid XMLObjectReader::pushState()\n{\n ReadState cur_state;\n cur_state.mNodeStack = mCurNodeStack;\n mReadStateStack.push_back(cur_state);\n}\n\nvoid XMLObjectReader::popState()\n{\n ReadState new_state = mReadStateStack.back();\n mReadStateStack.pop_back();\n mCurNodeStack = new_state.mNodeStack;\n}\n\n\n\nvpr::Uint8 XMLObjectReader::readUint8()\n{\n \/\/ Read a uint16 so that it does not treat it as a single char\n vpr::Uint16 temp_data;\n readValueStringRep(temp_data, getCurSource());\n return vpr::Uint8(temp_data);\n}\n\nvpr::Uint16 XMLObjectReader::readUint16()\n{\n vpr::Uint16 val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\nvpr::Uint32 XMLObjectReader::readUint32()\n{\n vpr::Uint32 val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\nvpr::Uint64 XMLObjectReader::readUint64()\n{\n vpr::Uint64 val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\nfloat XMLObjectReader::readFloat()\n{\n float val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\ndouble XMLObjectReader::readDouble()\n{\n double val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\n\nstd::string XMLObjectReader::readString()\n{\n std::string ret_val(\"\"); \n\n if(AttribSource == mCurSource) \/\/ Just return a copy of the attribute source\n {\n ret_val = mAttribSource.str();\n }\n else \/\/ Cdata, extract the \"'s around the string\n {\n char char_buffer[1024]; \/\/ Buffer for writing the final value\n char temp_char('0');\n\n \/\/ Get the first \"\n while('\"' != temp_char)\n {\n mCurNodeStack.back().cdataSource.get(temp_char);\n vprASSERT(('>' != temp_char) && ('<' != temp_char) && \"String delimiter not found\");\n }\n\n \/\/ Get the contents of the string\n char next_char = mCurNodeStack.back().cdataSource.peek();\n bool done_reading(next_char == '\"'); \/\/ If next char is already \", then we are done reading empty string\n \n while(!done_reading)\n {\n mCurNodeStack.back().cdataSource.get(char_buffer,1024, '\"'); \/\/ Copy over to target until we have second \"\n ret_val += char_buffer; \/\/ append onto end\n next_char = mCurNodeStack.back().cdataSource.peek();\n done_reading = (next_char == '\"'); \/\/ Done reading if got to a \"\n }\n mCurNodeStack.back().cdataSource.ignore(1); \/\/ Ignore that \" as well\n }\n\n return ret_val;\n}\n\nbool XMLObjectReader::readBool()\n{\n bool val;\n readValueStringRep(val, getCurSource());\n return val;\n}\n\n} \/\/ namespace vpr\n\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2015 gRPC authors.\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#include \n#include \n#include \n\n#include \"src\/compiler\/config.h\"\n#include \"src\/compiler\/objective_c_generator.h\"\n#include \"src\/compiler\/objective_c_generator_helpers.h\"\n\n#include \n\nusing ::google::protobuf::compiler::objectivec::ClassName;\nusing ::grpc::protobuf::FileDescriptor;\nusing ::grpc::protobuf::FileDescriptor;\nusing ::grpc::protobuf::MethodDescriptor;\nusing ::grpc::protobuf::ServiceDescriptor;\nusing ::grpc::protobuf::io::Printer;\nusing ::std::map;\nusing ::std::set;\n\nnamespace grpc_objective_c_generator {\nnamespace {\n\nvoid PrintProtoRpcDeclarationAsPragma(\n Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n vars[\"client_stream\"] = method->client_streaming() ? \"stream \" : \"\";\n vars[\"server_stream\"] = method->server_streaming() ? \"stream \" : \"\";\n\n printer->Print(vars,\n \"#pragma mark $method_name$($client_stream$$request_type$)\"\n \" returns ($server_stream$$response_type$)\\n\\n\");\n}\n\ntemplate \nstatic void PrintAllComments(const DescriptorType* desc, Printer* printer) {\n std::vector comments;\n grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED,\n &comments);\n grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING,\n &comments);\n grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_TRAILING,\n &comments);\n if (comments.empty()) {\n return;\n }\n printer->Print(\"\/**\\n\");\n for (auto it = comments.begin(); it != comments.end(); ++it) {\n printer->Print(\" * \");\n size_t start_pos = it->find_first_not_of(' ');\n if (start_pos != grpc::string::npos) {\n printer->PrintRaw(it->c_str() + start_pos);\n }\n printer->Print(\"\\n\");\n }\n printer->Print(\" *\/\\n\");\n}\n\nvoid PrintMethodSignature(Printer* printer, const MethodDescriptor* method,\n const map< ::grpc::string, ::grpc::string>& vars) {\n \/\/ Print comment\n PrintAllComments(method, printer);\n\n printer->Print(vars, \"- ($return_type$)$method_name$With\");\n if (method->client_streaming()) {\n printer->Print(\"RequestsWriter:(GRXWriter *)requestWriter\");\n } else {\n printer->Print(vars, \"Request:($request_class$ *)request\");\n }\n\n \/\/ TODO(jcanizales): Put this on a new line and align colons.\n if (method->server_streaming()) {\n printer->Print(vars,\n \" eventHandler:(void(^)(BOOL done, \"\n \"$response_class$ *_Nullable response, NSError *_Nullable \"\n \"error))eventHandler\");\n } else {\n printer->Print(vars,\n \" handler:(void(^)($response_class$ *_Nullable response, \"\n \"NSError *_Nullable error))handler\");\n }\n}\n\nvoid PrintSimpleSignature(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n vars[\"method_name\"] =\n grpc_generator::LowercaseFirstLetter(vars[\"method_name\"]);\n vars[\"return_type\"] = \"void\";\n PrintMethodSignature(printer, method, vars);\n}\n\nvoid PrintAdvancedSignature(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n vars[\"method_name\"] = \"RPCTo\" + vars[\"method_name\"];\n vars[\"return_type\"] = \"GRPCProtoCall *\";\n PrintMethodSignature(printer, method, vars);\n}\n\nvoid PrintV2Signature(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n if (method->client_streaming()) {\n vars[\"return_type\"] = \"GRPCStreamingProtoCall *\";\n } else {\n vars[\"return_type\"] = \"GRPCUnaryProtoCall *\";\n }\n vars[\"method_name\"] =\n grpc_generator::LowercaseFirstLetter(vars[\"method_name\"]);\n\n PrintAllComments(method, printer);\n\n printer->Print(vars, \"- ($return_type$)$method_name$With\");\n if (method->client_streaming()) {\n printer->Print(\"ResponseHandler:(id)handler\");\n } else {\n printer->Print(vars,\n \"Message:($request_class$ *)message \"\n \"responseHandler:(id)handler\");\n }\n printer->Print(\" callOptions:(GRPCCallOptions *_Nullable)callOptions\");\n}\n\ninline map< ::grpc::string, ::grpc::string> GetMethodVars(\n const MethodDescriptor* method) {\n map< ::grpc::string, ::grpc::string> res;\n res[\"method_name\"] = method->name();\n res[\"request_type\"] = method->input_type()->name();\n res[\"response_type\"] = method->output_type()->name();\n res[\"request_class\"] = ClassName(method->input_type());\n res[\"response_class\"] = ClassName(method->output_type());\n return res;\n}\n\nvoid PrintMethodDeclarations(Printer* printer, const MethodDescriptor* method) {\n map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);\n\n PrintProtoRpcDeclarationAsPragma(printer, method, vars);\n\n PrintSimpleSignature(printer, method, vars);\n printer->Print(\";\\n\\n\");\n PrintAdvancedSignature(printer, method, vars);\n printer->Print(\";\\n\\n\\n\");\n}\n\nvoid PrintV2MethodDeclarations(Printer* printer,\n const MethodDescriptor* method) {\n map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);\n\n PrintProtoRpcDeclarationAsPragma(printer, method, vars);\n\n PrintV2Signature(printer, method, vars);\n printer->Print(\";\\n\\n\");\n}\n\nvoid PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n printer->Print(\"{\\n\");\n printer->Print(vars, \" [[self RPCTo$method_name$With\");\n if (method->client_streaming()) {\n printer->Print(\"RequestsWriter:requestWriter\");\n } else {\n printer->Print(\"Request:request\");\n }\n if (method->server_streaming()) {\n printer->Print(\" eventHandler:eventHandler] start];\\n\");\n } else {\n printer->Print(\" handler:handler] start];\\n\");\n }\n printer->Print(\"}\\n\");\n}\n\nvoid PrintAdvancedImplementation(Printer* printer,\n const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n printer->Print(\"{\\n\");\n printer->Print(vars, \" return [self RPCToMethod:@\\\"$method_name$\\\"\\n\");\n\n printer->Print(\" requestsWriter:\");\n if (method->client_streaming()) {\n printer->Print(\"requestWriter\\n\");\n } else {\n printer->Print(\"[GRXWriter writerWithValue:request]\\n\");\n }\n\n printer->Print(vars, \" responseClass:[$response_class$ class]\\n\");\n\n printer->Print(\" responsesWriteable:[GRXWriteable \");\n if (method->server_streaming()) {\n printer->Print(\"writeableWithEventHandler:eventHandler]];\\n\");\n } else {\n printer->Print(\"writeableWithSingleHandler:handler]];\\n\");\n }\n\n printer->Print(\"}\\n\");\n}\n\nvoid PrintV2Implementation(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n printer->Print(\" {\\n\");\n if (method->client_streaming()) {\n printer->Print(vars, \" return [self RPCToMethod:@\\\"$method_name$\\\"\\n\");\n printer->Print(\" responseHandler:handler\\n\");\n printer->Print(\" callOptions:callOptions\\n\");\n printer->Print(\n vars, \" responseClass:[$response_class$ class]];\\n}\\n\\n\");\n } else {\n printer->Print(vars, \" return [self RPCToMethod:@\\\"$method_name$\\\"\\n\");\n printer->Print(\" message:message\\n\");\n printer->Print(\" responseHandler:handler\\n\");\n printer->Print(\" callOptions:callOptions\\n\");\n printer->Print(\n vars, \" responseClass:[$response_class$ class]];\\n}\\n\\n\");\n }\n}\n\nvoid PrintMethodImplementations(Printer* printer,\n const MethodDescriptor* method) {\n map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);\n\n PrintProtoRpcDeclarationAsPragma(printer, method, vars);\n\n \/\/ TODO(jcanizales): Print documentation from the method.\n printer->Print(\"\/\/ Deprecated methods.\\n\");\n PrintSimpleSignature(printer, method, vars);\n PrintSimpleImplementation(printer, method, vars);\n\n printer->Print(\"\/\/ Returns a not-yet-started RPC object.\\n\");\n PrintAdvancedSignature(printer, method, vars);\n PrintAdvancedImplementation(printer, method, vars);\n\n PrintV2Signature(printer, method, vars);\n PrintV2Implementation(printer, method, vars);\n}\n\n} \/\/ namespace\n\n::grpc::string GetAllMessageClasses(const FileDescriptor* file) {\n ::grpc::string output;\n set< ::grpc::string> classes;\n for (int i = 0; i < file->service_count(); i++) {\n const auto service = file->service(i);\n for (int i = 0; i < service->method_count(); i++) {\n const auto method = service->method(i);\n classes.insert(ClassName(method->input_type()));\n classes.insert(ClassName(method->output_type()));\n }\n }\n for (auto one_class : classes) {\n output += \"@class \" + one_class + \";\\n\";\n }\n\n return output;\n}\n\n::grpc::string GetProtocol(const ServiceDescriptor* service) {\n ::grpc::string output;\n\n \/\/ Scope the output stream so it closes and finalizes output to the string.\n grpc::protobuf::io::StringOutputStream output_stream(&output);\n Printer printer(&output_stream, '$');\n\n map< ::grpc::string, ::grpc::string> vars = {\n {\"service_class\", ServiceClassName(service)}};\n\n printer.Print(vars, \"@protocol $service_class$ \\n\\n\");\n for (int i = 0; i < service->method_count(); i++) {\n PrintMethodDeclarations(&printer, service->method(i));\n }\n printer.Print(\"@end\\n\\n\");\n\n return output;\n}\n\n::grpc::string GetV2Protocol(const ServiceDescriptor* service) {\n ::grpc::string output;\n\n \/\/ Scope the output stream so it closes and finalizes output to the string.\n grpc::protobuf::io::StringOutputStream output_stream(&output);\n Printer printer(&output_stream, '$');\n\n map< ::grpc::string, ::grpc::string> vars = {\n {\"service_class\", ServiceClassName(service) + \"2\"}};\n\n printer.Print(vars, \"@protocol $service_class$ \\n\\n\");\n for (int i = 0; i < service->method_count(); i++) {\n PrintV2MethodDeclarations(&printer, service->method(i));\n }\n printer.Print(\"@end\\n\\n\");\n\n return output;\n}\n\n::grpc::string GetInterface(const ServiceDescriptor* service) {\n ::grpc::string output;\n\n \/\/ Scope the output stream so it closes and finalizes output to the string.\n grpc::protobuf::io::StringOutputStream output_stream(&output);\n Printer printer(&output_stream, '$');\n\n map< ::grpc::string, ::grpc::string> vars = {\n {\"service_class\", ServiceClassName(service)}};\n\n printer.Print(vars,\n \"\/**\\n\"\n \" * Basic service implementation, over gRPC, that only does\\n\"\n \" * marshalling and parsing.\\n\"\n \" *\/\\n\");\n printer.Print(vars,\n \"@interface $service_class$ :\"\n \" GRPCProtoService<$service_class$, $service_class$2>\\n\");\n printer.Print(\n \"- (instancetype)initWithHost:(NSString *)host \"\n \"callOptions:(GRPCCallOptions \"\n \"*_Nullable)callOptions\"\n \" NS_DESIGNATED_INITIALIZER;\\n\");\n printer.Print(\"- (instancetype)initWithHost:(NSString *)host;\\n\");\n printer.Print(\n \"+ (instancetype)serviceWithHost:(NSString *)host \"\n \"callOptions:(GRPCCallOptions *_Nullable)callOptions;\\n\");\n printer.Print(\"+ (instancetype)serviceWithHost:(NSString *)host;\\n\");\n printer.Print(\"@end\\n\");\n\n return output;\n}\n\n::grpc::string GetSource(const ServiceDescriptor* service) {\n ::grpc::string output;\n {\n \/\/ Scope the output stream so it closes and finalizes output to the string.\n grpc::protobuf::io::StringOutputStream output_stream(&output);\n Printer printer(&output_stream, '$');\n\n map< ::grpc::string, ::grpc::string> vars = {\n {\"service_name\", service->name()},\n {\"service_class\", ServiceClassName(service)},\n {\"package\", service->file()->package()}};\n\n printer.Print(vars,\n \"@implementation $service_class$\\n\\n\"\n \"#pragma clang diagnostic push\\n\"\n \"#pragma clang diagnostic ignored \"\n \"\\\"-Wobjc-designated-initializers\\\"\\n\\n\"\n \"\/\/ Designated initializer\\n\"\n \"- (instancetype)initWithHost:(NSString *)host \"\n \"callOptions:(GRPCCallOptions *_Nullable)callOptions {\\n\"\n \" return [super initWithHost:host\\n\"\n \" packageName:@\\\"$package$\\\"\\n\"\n \" serviceName:@\\\"$service_name$\\\"\\n\"\n \" callOptions:callOptions];\\n\"\n \"}\\n\\n\"\n \"- (instancetype)initWithHost:(NSString *)host {\\n\"\n \" return [super initWithHost:host\\n\"\n \" packageName:@\\\"$package$\\\"\\n\"\n \" serviceName:@\\\"$service_name$\\\"];\\n\"\n \"}\\n\\n\"\n \"#pragma clang diagnostic pop\\n\\n\");\n\n printer.Print(\n \"\/\/ Override superclass initializer to disallow different\"\n \" package and service names.\\n\"\n \"- (instancetype)initWithHost:(NSString *)host\\n\"\n \" packageName:(NSString *)packageName\\n\"\n \" serviceName:(NSString *)serviceName {\\n\"\n \" return [self initWithHost:host];\\n\"\n \"}\\n\\n\"\n \"- (instancetype)initWithHost:(NSString *)host\\n\"\n \" packageName:(NSString *)packageName\\n\"\n \" serviceName:(NSString *)serviceName\\n\"\n \" callOptions:(GRPCCallOptions *)callOptions {\\n\"\n \" return [self initWithHost:host callOptions:callOptions];\\n\"\n \"}\\n\\n\");\n\n printer.Print(\n \"#pragma mark - Class Methods\\n\\n\"\n \"+ (instancetype)serviceWithHost:(NSString *)host {\\n\"\n \" return [[self alloc] initWithHost:host];\\n\"\n \"}\\n\\n\"\n \"+ (instancetype)serviceWithHost:(NSString *)host \"\n \"callOptions:(GRPCCallOptions *_Nullable)callOptions {\\n\"\n \" return [[self alloc] initWithHost:host callOptions:callOptions];\\n\"\n \"}\\n\\n\");\n\n printer.Print(\"#pragma mark - Method Implementations\\n\\n\");\n\n for (int i = 0; i < service->method_count(); i++) {\n PrintMethodImplementations(&printer, service->method(i));\n }\n\n printer.Print(\"@end\\n\");\n }\n return output;\n}\n\n} \/\/ namespace grpc_objective_c_generator\nAdd API deprecation notice to generated code\/*\n *\n * Copyright 2015 gRPC authors.\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#include \n#include \n#include \n\n#include \"src\/compiler\/config.h\"\n#include \"src\/compiler\/objective_c_generator.h\"\n#include \"src\/compiler\/objective_c_generator_helpers.h\"\n\n#include \n\nusing ::google::protobuf::compiler::objectivec::ClassName;\nusing ::grpc::protobuf::FileDescriptor;\nusing ::grpc::protobuf::FileDescriptor;\nusing ::grpc::protobuf::MethodDescriptor;\nusing ::grpc::protobuf::ServiceDescriptor;\nusing ::grpc::protobuf::io::Printer;\nusing ::std::map;\nusing ::std::set;\n\nnamespace grpc_objective_c_generator {\nnamespace {\n\nvoid PrintProtoRpcDeclarationAsPragma(\n Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n vars[\"client_stream\"] = method->client_streaming() ? \"stream \" : \"\";\n vars[\"server_stream\"] = method->server_streaming() ? \"stream \" : \"\";\n\n printer->Print(vars,\n \"#pragma mark $method_name$($client_stream$$request_type$)\"\n \" returns ($server_stream$$response_type$)\\n\\n\");\n}\n\ntemplate \nstatic void PrintAllComments(const DescriptorType* desc, Printer* printer) {\n std::vector comments;\n grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED,\n &comments);\n grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING,\n &comments);\n grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_TRAILING,\n &comments);\n if (comments.empty()) {\n return;\n }\n printer->Print(\"\/**\\n\");\n for (auto it = comments.begin(); it != comments.end(); ++it) {\n printer->Print(\" * \");\n size_t start_pos = it->find_first_not_of(' ');\n if (start_pos != grpc::string::npos) {\n printer->PrintRaw(it->c_str() + start_pos);\n }\n printer->Print(\"\\n\");\n }\n printer->Print(\" *\\n\");\n printer->Print(\n \" * This method belongs to a set of APIs that have been deprecated. Using\"\n \" the v2 API is recommended.\\n\");\n printer->Print(\" *\/\\n\");\n}\n\nvoid PrintMethodSignature(Printer* printer, const MethodDescriptor* method,\n const map< ::grpc::string, ::grpc::string>& vars) {\n \/\/ Print comment\n PrintAllComments(method, printer);\n\n printer->Print(vars, \"- ($return_type$)$method_name$With\");\n if (method->client_streaming()) {\n printer->Print(\"RequestsWriter:(GRXWriter *)requestWriter\");\n } else {\n printer->Print(vars, \"Request:($request_class$ *)request\");\n }\n\n \/\/ TODO(jcanizales): Put this on a new line and align colons.\n if (method->server_streaming()) {\n printer->Print(vars,\n \" eventHandler:(void(^)(BOOL done, \"\n \"$response_class$ *_Nullable response, NSError *_Nullable \"\n \"error))eventHandler\");\n } else {\n printer->Print(vars,\n \" handler:(void(^)($response_class$ *_Nullable response, \"\n \"NSError *_Nullable error))handler\");\n }\n}\n\nvoid PrintSimpleSignature(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n vars[\"method_name\"] =\n grpc_generator::LowercaseFirstLetter(vars[\"method_name\"]);\n vars[\"return_type\"] = \"void\";\n PrintMethodSignature(printer, method, vars);\n}\n\nvoid PrintAdvancedSignature(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n vars[\"method_name\"] = \"RPCTo\" + vars[\"method_name\"];\n vars[\"return_type\"] = \"GRPCProtoCall *\";\n PrintMethodSignature(printer, method, vars);\n}\n\nvoid PrintV2Signature(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n if (method->client_streaming()) {\n vars[\"return_type\"] = \"GRPCStreamingProtoCall *\";\n } else {\n vars[\"return_type\"] = \"GRPCUnaryProtoCall *\";\n }\n vars[\"method_name\"] =\n grpc_generator::LowercaseFirstLetter(vars[\"method_name\"]);\n\n PrintAllComments(method, printer);\n\n printer->Print(vars, \"- ($return_type$)$method_name$With\");\n if (method->client_streaming()) {\n printer->Print(\"ResponseHandler:(id)handler\");\n } else {\n printer->Print(vars,\n \"Message:($request_class$ *)message \"\n \"responseHandler:(id)handler\");\n }\n printer->Print(\" callOptions:(GRPCCallOptions *_Nullable)callOptions\");\n}\n\ninline map< ::grpc::string, ::grpc::string> GetMethodVars(\n const MethodDescriptor* method) {\n map< ::grpc::string, ::grpc::string> res;\n res[\"method_name\"] = method->name();\n res[\"request_type\"] = method->input_type()->name();\n res[\"response_type\"] = method->output_type()->name();\n res[\"request_class\"] = ClassName(method->input_type());\n res[\"response_class\"] = ClassName(method->output_type());\n return res;\n}\n\nvoid PrintMethodDeclarations(Printer* printer, const MethodDescriptor* method) {\n map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);\n\n PrintProtoRpcDeclarationAsPragma(printer, method, vars);\n\n PrintSimpleSignature(printer, method, vars);\n printer->Print(\";\\n\\n\");\n PrintAdvancedSignature(printer, method, vars);\n printer->Print(\";\\n\\n\\n\");\n}\n\nvoid PrintV2MethodDeclarations(Printer* printer,\n const MethodDescriptor* method) {\n map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);\n\n PrintProtoRpcDeclarationAsPragma(printer, method, vars);\n\n PrintV2Signature(printer, method, vars);\n printer->Print(\";\\n\\n\");\n}\n\nvoid PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n printer->Print(\"{\\n\");\n printer->Print(vars, \" [[self RPCTo$method_name$With\");\n if (method->client_streaming()) {\n printer->Print(\"RequestsWriter:requestWriter\");\n } else {\n printer->Print(\"Request:request\");\n }\n if (method->server_streaming()) {\n printer->Print(\" eventHandler:eventHandler] start];\\n\");\n } else {\n printer->Print(\" handler:handler] start];\\n\");\n }\n printer->Print(\"}\\n\");\n}\n\nvoid PrintAdvancedImplementation(Printer* printer,\n const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n printer->Print(\"{\\n\");\n printer->Print(vars, \" return [self RPCToMethod:@\\\"$method_name$\\\"\\n\");\n\n printer->Print(\" requestsWriter:\");\n if (method->client_streaming()) {\n printer->Print(\"requestWriter\\n\");\n } else {\n printer->Print(\"[GRXWriter writerWithValue:request]\\n\");\n }\n\n printer->Print(vars, \" responseClass:[$response_class$ class]\\n\");\n\n printer->Print(\" responsesWriteable:[GRXWriteable \");\n if (method->server_streaming()) {\n printer->Print(\"writeableWithEventHandler:eventHandler]];\\n\");\n } else {\n printer->Print(\"writeableWithSingleHandler:handler]];\\n\");\n }\n\n printer->Print(\"}\\n\");\n}\n\nvoid PrintV2Implementation(Printer* printer, const MethodDescriptor* method,\n map< ::grpc::string, ::grpc::string> vars) {\n printer->Print(\" {\\n\");\n if (method->client_streaming()) {\n printer->Print(vars, \" return [self RPCToMethod:@\\\"$method_name$\\\"\\n\");\n printer->Print(\" responseHandler:handler\\n\");\n printer->Print(\" callOptions:callOptions\\n\");\n printer->Print(\n vars, \" responseClass:[$response_class$ class]];\\n}\\n\\n\");\n } else {\n printer->Print(vars, \" return [self RPCToMethod:@\\\"$method_name$\\\"\\n\");\n printer->Print(\" message:message\\n\");\n printer->Print(\" responseHandler:handler\\n\");\n printer->Print(\" callOptions:callOptions\\n\");\n printer->Print(\n vars, \" responseClass:[$response_class$ class]];\\n}\\n\\n\");\n }\n}\n\nvoid PrintMethodImplementations(Printer* printer,\n const MethodDescriptor* method) {\n map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);\n\n PrintProtoRpcDeclarationAsPragma(printer, method, vars);\n\n \/\/ TODO(jcanizales): Print documentation from the method.\n printer->Print(\"\/\/ Deprecated methods.\\n\");\n PrintSimpleSignature(printer, method, vars);\n PrintSimpleImplementation(printer, method, vars);\n\n printer->Print(\"\/\/ Returns a not-yet-started RPC object.\\n\");\n PrintAdvancedSignature(printer, method, vars);\n PrintAdvancedImplementation(printer, method, vars);\n\n PrintV2Signature(printer, method, vars);\n PrintV2Implementation(printer, method, vars);\n}\n\n} \/\/ namespace\n\n::grpc::string GetAllMessageClasses(const FileDescriptor* file) {\n ::grpc::string output;\n set< ::grpc::string> classes;\n for (int i = 0; i < file->service_count(); i++) {\n const auto service = file->service(i);\n for (int i = 0; i < service->method_count(); i++) {\n const auto method = service->method(i);\n classes.insert(ClassName(method->input_type()));\n classes.insert(ClassName(method->output_type()));\n }\n }\n for (auto one_class : classes) {\n output += \"@class \" + one_class + \";\\n\";\n }\n\n return output;\n}\n\n::grpc::string GetProtocol(const ServiceDescriptor* service) {\n ::grpc::string output;\n\n \/\/ Scope the output stream so it closes and finalizes output to the string.\n grpc::protobuf::io::StringOutputStream output_stream(&output);\n Printer printer(&output_stream, '$');\n\n map< ::grpc::string, ::grpc::string> vars = {\n {\"service_class\", ServiceClassName(service)}};\n\n printer.Print(vars,\n \"\/**\\n\"\n \" * The methods in this protocol belong to a set of old APIs \"\n \"that have been deprecated. They do not\\n\"\n \" * recognize call options provided in the initializer. Using \"\n \"the v2 protocol is recommended.\\n\"\n \" *\/\\n\");\n printer.Print(vars, \"@protocol $service_class$ \\n\\n\");\n for (int i = 0; i < service->method_count(); i++) {\n PrintMethodDeclarations(&printer, service->method(i));\n }\n printer.Print(\"@end\\n\\n\");\n\n return output;\n}\n\n::grpc::string GetV2Protocol(const ServiceDescriptor* service) {\n ::grpc::string output;\n\n \/\/ Scope the output stream so it closes and finalizes output to the string.\n grpc::protobuf::io::StringOutputStream output_stream(&output);\n Printer printer(&output_stream, '$');\n\n map< ::grpc::string, ::grpc::string> vars = {\n {\"service_class\", ServiceClassName(service) + \"2\"}};\n\n printer.Print(vars, \"@protocol $service_class$ \\n\\n\");\n for (int i = 0; i < service->method_count(); i++) {\n PrintV2MethodDeclarations(&printer, service->method(i));\n }\n printer.Print(\"@end\\n\\n\");\n\n return output;\n}\n\n::grpc::string GetInterface(const ServiceDescriptor* service) {\n ::grpc::string output;\n\n \/\/ Scope the output stream so it closes and finalizes output to the string.\n grpc::protobuf::io::StringOutputStream output_stream(&output);\n Printer printer(&output_stream, '$');\n\n map< ::grpc::string, ::grpc::string> vars = {\n {\"service_class\", ServiceClassName(service)}};\n\n printer.Print(vars,\n \"\/**\\n\"\n \" * Basic service implementation, over gRPC, that only does\\n\"\n \" * marshalling and parsing.\\n\"\n \" *\/\\n\");\n printer.Print(vars,\n \"@interface $service_class$ :\"\n \" GRPCProtoService<$service_class$, $service_class$2>\\n\");\n printer.Print(\n \"- (instancetype)initWithHost:(NSString *)host \"\n \"callOptions:(GRPCCallOptions \"\n \"*_Nullable)callOptions\"\n \" NS_DESIGNATED_INITIALIZER;\\n\");\n printer.Print(\n \"+ (instancetype)serviceWithHost:(NSString *)host \"\n \"callOptions:(GRPCCallOptions *_Nullable)callOptions;\\n\");\n printer.Print(\n \"\/\/ The following methods belong to a set of old APIs that have been \"\n \"deprecated.\\n\");\n printer.Print(\"- (instancetype)initWithHost:(NSString *)host;\\n\");\n printer.Print(\"+ (instancetype)serviceWithHost:(NSString *)host;\\n\");\n printer.Print(\"@end\\n\");\n\n return output;\n}\n\n::grpc::string GetSource(const ServiceDescriptor* service) {\n ::grpc::string output;\n {\n \/\/ Scope the output stream so it closes and finalizes output to the string.\n grpc::protobuf::io::StringOutputStream output_stream(&output);\n Printer printer(&output_stream, '$');\n\n map< ::grpc::string, ::grpc::string> vars = {\n {\"service_name\", service->name()},\n {\"service_class\", ServiceClassName(service)},\n {\"package\", service->file()->package()}};\n\n printer.Print(vars,\n \"@implementation $service_class$\\n\\n\"\n \"#pragma clang diagnostic push\\n\"\n \"#pragma clang diagnostic ignored \"\n \"\\\"-Wobjc-designated-initializers\\\"\\n\\n\"\n \"\/\/ Designated initializer\\n\"\n \"- (instancetype)initWithHost:(NSString *)host \"\n \"callOptions:(GRPCCallOptions *_Nullable)callOptions {\\n\"\n \" return [super initWithHost:host\\n\"\n \" packageName:@\\\"$package$\\\"\\n\"\n \" serviceName:@\\\"$service_name$\\\"\\n\"\n \" callOptions:callOptions];\\n\"\n \"}\\n\\n\"\n \"- (instancetype)initWithHost:(NSString *)host {\\n\"\n \" return [super initWithHost:host\\n\"\n \" packageName:@\\\"$package$\\\"\\n\"\n \" serviceName:@\\\"$service_name$\\\"];\\n\"\n \"}\\n\\n\"\n \"#pragma clang diagnostic pop\\n\\n\");\n\n printer.Print(\n \"\/\/ Override superclass initializer to disallow different\"\n \" package and service names.\\n\"\n \"- (instancetype)initWithHost:(NSString *)host\\n\"\n \" packageName:(NSString *)packageName\\n\"\n \" serviceName:(NSString *)serviceName {\\n\"\n \" return [self initWithHost:host];\\n\"\n \"}\\n\\n\"\n \"- (instancetype)initWithHost:(NSString *)host\\n\"\n \" packageName:(NSString *)packageName\\n\"\n \" serviceName:(NSString *)serviceName\\n\"\n \" callOptions:(GRPCCallOptions *)callOptions {\\n\"\n \" return [self initWithHost:host callOptions:callOptions];\\n\"\n \"}\\n\\n\");\n\n printer.Print(\n \"#pragma mark - Class Methods\\n\\n\"\n \"+ (instancetype)serviceWithHost:(NSString *)host {\\n\"\n \" return [[self alloc] initWithHost:host];\\n\"\n \"}\\n\\n\"\n \"+ (instancetype)serviceWithHost:(NSString *)host \"\n \"callOptions:(GRPCCallOptions *_Nullable)callOptions {\\n\"\n \" return [[self alloc] initWithHost:host callOptions:callOptions];\\n\"\n \"}\\n\\n\");\n\n printer.Print(\"#pragma mark - Method Implementations\\n\\n\");\n\n for (int i = 0; i < service->method_count(); i++) {\n PrintMethodImplementations(&printer, service->method(i));\n }\n\n printer.Print(\"@end\\n\");\n }\n return output;\n}\n\n} \/\/ namespace grpc_objective_c_generator\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud \n\/\/ Copyright (C) 2010 Jitse Niesen \n\/\/\n\/\/ Eigen 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 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n#include \n#include \n\n#ifdef HAS_GSL\n#include \"gsl_helper.h\"\n#endif\n\ntemplate void selfadjointeigensolver(const MatrixType& m)\n{\n \/* this test covers the following files:\n EigenSolver.h, SelfAdjointEigenSolver.h (and indirectly: Tridiagonalization.h)\n *\/\n int rows = m.rows();\n int cols = m.cols();\n\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits::Real RealScalar;\n typedef Matrix VectorType;\n typedef Matrix RealVectorType;\n typedef typename std::complex::Real> Complex;\n\n RealScalar largerEps = 10*test_precision();\n\n MatrixType a = MatrixType::Random(rows,cols);\n MatrixType a1 = MatrixType::Random(rows,cols);\n MatrixType symmA = a.adjoint() * a + a1.adjoint() * a1;\n symmA.template triangularView().setZero();\n\n MatrixType b = MatrixType::Random(rows,cols);\n MatrixType b1 = MatrixType::Random(rows,cols);\n MatrixType symmB = b.adjoint() * b + b1.adjoint() * b1;\n symmB.template triangularView().setZero();\n\n SelfAdjointEigenSolver eiSymm(symmA);\n \/\/ generalized eigen pb\n GeneralizedSelfAdjointEigenSolver eiSymmGen(symmA, symmB);\n\n #ifdef HAS_GSL\n if (ei_is_same_type::ret)\n {\n \/\/ restore symmA and symmB.\n symmA = MatrixType(symmA.template selfadjointView());\n symmB = MatrixType(symmB.template selfadjointView());\n typedef GslTraits Gsl;\n typename Gsl::Matrix gEvec=0, gSymmA=0, gSymmB=0;\n typename GslTraits::Vector gEval=0;\n RealVectorType _eval;\n MatrixType _evec;\n convert(symmA, gSymmA);\n convert(symmB, gSymmB);\n convert(symmA, gEvec);\n gEval = GslTraits::createVector(rows);\n\n Gsl::eigen_symm(gSymmA, gEval, gEvec);\n convert(gEval, _eval);\n convert(gEvec, _evec);\n\n \/\/ test gsl itself !\n VERIFY((symmA * _evec).isApprox(_evec * _eval.asDiagonal(), largerEps));\n\n \/\/ compare with eigen\n VERIFY_IS_APPROX(_eval, eiSymm.eigenvalues());\n VERIFY_IS_APPROX(_evec.cwiseAbs(), eiSymm.eigenvectors().cwiseAbs());\n\n \/\/ generalized pb\n Gsl::eigen_symm_gen(gSymmA, gSymmB, gEval, gEvec);\n convert(gEval, _eval);\n convert(gEvec, _evec);\n \/\/ test GSL itself:\n VERIFY((symmA * _evec).isApprox(symmB * (_evec * _eval.asDiagonal()), largerEps));\n\n \/\/ compare with eigen\n MatrixType normalized_eivec = eiSymmGen.eigenvectors()*eiSymmGen.eigenvectors().colwise().norm().asDiagonal().inverse();\n VERIFY_IS_APPROX(_eval, eiSymmGen.eigenvalues());\n VERIFY_IS_APPROX(_evec.cwiseAbs(), normalized_eivec.cwiseAbs());\n\n Gsl::free(gSymmA);\n Gsl::free(gSymmB);\n GslTraits::free(gEval);\n Gsl::free(gEvec);\n }\n #endif\n\n VERIFY_IS_EQUAL(eiSymm.info(), Success);\n VERIFY((symmA.template selfadjointView() * eiSymm.eigenvectors()).isApprox(\n eiSymm.eigenvectors() * eiSymm.eigenvalues().asDiagonal(), largerEps));\n VERIFY_IS_APPROX(symmA.template selfadjointView().eigenvalues(), eiSymm.eigenvalues());\n\n SelfAdjointEigenSolver eiSymmNoEivecs(symmA, false);\n VERIFY_IS_EQUAL(eiSymmNoEivecs.info(), Success);\n VERIFY_IS_APPROX(eiSymm.eigenvalues(), eiSymmNoEivecs.eigenvalues());\n\n \/\/ generalized eigen problem Ax = lBx\n VERIFY_IS_EQUAL(eiSymmGen.info(), Success);\n VERIFY((symmA.template selfadjointView() * eiSymmGen.eigenvectors()).isApprox(\n symmB.template selfadjointView() * (eiSymmGen.eigenvectors() * eiSymmGen.eigenvalues().asDiagonal()), largerEps));\n\n MatrixType sqrtSymmA = eiSymm.operatorSqrt();\n VERIFY_IS_APPROX(MatrixType(symmA.template selfadjointView()), sqrtSymmA*sqrtSymmA);\n VERIFY_IS_APPROX(sqrtSymmA, symmA.template selfadjointView()*eiSymm.operatorInverseSqrt());\n\n MatrixType id = MatrixType::Identity(rows, cols);\n VERIFY_IS_APPROX(id.template selfadjointView().operatorNorm(), RealScalar(1));\n\n SelfAdjointEigenSolver eiSymmUninitialized;\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.info());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvalues());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt());\n\n eiSymmUninitialized.compute(symmA, false);\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt());\n\n if (rows > 1)\n {\n \/\/ Test matrix with NaN\n symmA(0,0) = std::numeric_limits::quiet_NaN();\n SelfAdjointEigenSolver eiSymmNaN(symmA);\n VERIFY_IS_EQUAL(eiSymmNaN.info(), NoConvergence);\n }\n}\n\nvoid test_eigensolver_selfadjoint()\n{\n for(int i = 0; i < g_repeat; i++) {\n \/\/ very important to test a 3x3 matrix since we provide a special path for it\n CALL_SUBTEST_1( selfadjointeigensolver(Matrix3f()) );\n CALL_SUBTEST_2( selfadjointeigensolver(Matrix4d()) );\n CALL_SUBTEST_3( selfadjointeigensolver(MatrixXf(10,10)) );\n CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(19,19)) );\n CALL_SUBTEST_5( selfadjointeigensolver(MatrixXcd(17,17)) );\n\n \/\/ some trivial but implementation-wise tricky cases\n CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(1,1)) );\n CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(2,2)) );\n CALL_SUBTEST_6( selfadjointeigensolver(Matrix()) );\n CALL_SUBTEST_7( selfadjointeigensolver(Matrix()) );\n }\n\n \/\/ Test problem size constructors\n CALL_SUBTEST_8(SelfAdjointEigenSolver(10));\n CALL_SUBTEST_8(Tridiagonalization(10));\n}\n\nadd unit tests for other generalized variants\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud \n\/\/ Copyright (C) 2010 Jitse Niesen \n\/\/\n\/\/ Eigen 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 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n#include \n#include \n\n#ifdef HAS_GSL\n#include \"gsl_helper.h\"\n#endif\n\ntemplate void selfadjointeigensolver(const MatrixType& m)\n{\n \/* this test covers the following files:\n EigenSolver.h, SelfAdjointEigenSolver.h (and indirectly: Tridiagonalization.h)\n *\/\n int rows = m.rows();\n int cols = m.cols();\n\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits::Real RealScalar;\n typedef Matrix VectorType;\n typedef Matrix RealVectorType;\n typedef typename std::complex::Real> Complex;\n\n RealScalar largerEps = 10*test_precision();\n\n MatrixType a = MatrixType::Random(rows,cols);\n MatrixType a1 = MatrixType::Random(rows,cols);\n MatrixType symmA = a.adjoint() * a + a1.adjoint() * a1;\n symmA.template triangularView().setZero();\n\n MatrixType b = MatrixType::Random(rows,cols);\n MatrixType b1 = MatrixType::Random(rows,cols);\n MatrixType symmB = b.adjoint() * b + b1.adjoint() * b1;\n symmB.template triangularView().setZero();\n\n SelfAdjointEigenSolver eiSymm(symmA);\n \/\/ generalized eigen pb\n GeneralizedSelfAdjointEigenSolver eiSymmGen(symmA, symmB);\n\n #ifdef HAS_GSL\n if (ei_is_same_type::ret)\n {\n \/\/ restore symmA and symmB.\n symmA = MatrixType(symmA.template selfadjointView());\n symmB = MatrixType(symmB.template selfadjointView());\n typedef GslTraits Gsl;\n typename Gsl::Matrix gEvec=0, gSymmA=0, gSymmB=0;\n typename GslTraits::Vector gEval=0;\n RealVectorType _eval;\n MatrixType _evec;\n convert(symmA, gSymmA);\n convert(symmB, gSymmB);\n convert(symmA, gEvec);\n gEval = GslTraits::createVector(rows);\n\n Gsl::eigen_symm(gSymmA, gEval, gEvec);\n convert(gEval, _eval);\n convert(gEvec, _evec);\n\n \/\/ test gsl itself !\n VERIFY((symmA * _evec).isApprox(_evec * _eval.asDiagonal(), largerEps));\n\n \/\/ compare with eigen\n VERIFY_IS_APPROX(_eval, eiSymm.eigenvalues());\n VERIFY_IS_APPROX(_evec.cwiseAbs(), eiSymm.eigenvectors().cwiseAbs());\n\n \/\/ generalized pb\n Gsl::eigen_symm_gen(gSymmA, gSymmB, gEval, gEvec);\n convert(gEval, _eval);\n convert(gEvec, _evec);\n \/\/ test GSL itself:\n VERIFY((symmA * _evec).isApprox(symmB * (_evec * _eval.asDiagonal()), largerEps));\n\n \/\/ compare with eigen\n MatrixType normalized_eivec = eiSymmGen.eigenvectors()*eiSymmGen.eigenvectors().colwise().norm().asDiagonal().inverse();\n VERIFY_IS_APPROX(_eval, eiSymmGen.eigenvalues());\n VERIFY_IS_APPROX(_evec.cwiseAbs(), normalized_eivec.cwiseAbs());\n\n Gsl::free(gSymmA);\n Gsl::free(gSymmB);\n GslTraits::free(gEval);\n Gsl::free(gEvec);\n }\n #endif\n\n VERIFY_IS_EQUAL(eiSymm.info(), Success);\n VERIFY((symmA.template selfadjointView() * eiSymm.eigenvectors()).isApprox(\n eiSymm.eigenvectors() * eiSymm.eigenvalues().asDiagonal(), largerEps));\n VERIFY_IS_APPROX(symmA.template selfadjointView().eigenvalues(), eiSymm.eigenvalues());\n\n SelfAdjointEigenSolver eiSymmNoEivecs(symmA, false);\n VERIFY_IS_EQUAL(eiSymmNoEivecs.info(), Success);\n VERIFY_IS_APPROX(eiSymm.eigenvalues(), eiSymmNoEivecs.eigenvalues());\n\n \/\/ generalized eigen problem Ax = lBx\n eiSymmGen.compute(symmA, symmB,Ax_lBx);\n VERIFY_IS_EQUAL(eiSymmGen.info(), Success);\n VERIFY((symmA.template selfadjointView() * eiSymmGen.eigenvectors()).isApprox(\n symmB.template selfadjointView() * (eiSymmGen.eigenvectors() * eiSymmGen.eigenvalues().asDiagonal()), largerEps));\n\n \/\/ generalized eigen problem BAx = lx\n eiSymmGen.compute(symmA, symmB,BAx_lx);\n VERIFY_IS_EQUAL(eiSymmGen.info(), Success);\n VERIFY((symmB.template selfadjointView() * (symmA.template selfadjointView() * eiSymmGen.eigenvectors())).isApprox(\n (eiSymmGen.eigenvectors() * eiSymmGen.eigenvalues().asDiagonal()), largerEps));\n\n \/\/ generalized eigen problem ABx = lx\n eiSymmGen.compute(symmA, symmB,ABx_lx);\n VERIFY_IS_EQUAL(eiSymmGen.info(), Success);\n VERIFY((symmA.template selfadjointView() * (symmB.template selfadjointView() * eiSymmGen.eigenvectors())).isApprox(\n (eiSymmGen.eigenvectors() * eiSymmGen.eigenvalues().asDiagonal()), largerEps));\n\n\n MatrixType sqrtSymmA = eiSymm.operatorSqrt();\n VERIFY_IS_APPROX(MatrixType(symmA.template selfadjointView()), sqrtSymmA*sqrtSymmA);\n VERIFY_IS_APPROX(sqrtSymmA, symmA.template selfadjointView()*eiSymm.operatorInverseSqrt());\n\n MatrixType id = MatrixType::Identity(rows, cols);\n VERIFY_IS_APPROX(id.template selfadjointView().operatorNorm(), RealScalar(1));\n\n SelfAdjointEigenSolver eiSymmUninitialized;\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.info());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvalues());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt());\n\n eiSymmUninitialized.compute(symmA, false);\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt());\n VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt());\n\n if (rows > 1)\n {\n \/\/ Test matrix with NaN\n symmA(0,0) = std::numeric_limits::quiet_NaN();\n SelfAdjointEigenSolver eiSymmNaN(symmA);\n VERIFY_IS_EQUAL(eiSymmNaN.info(), NoConvergence);\n }\n}\n\nvoid test_eigensolver_selfadjoint()\n{\n for(int i = 0; i < g_repeat; i++) {\n \/\/ very important to test a 3x3 matrix since we provide a special path for it\n CALL_SUBTEST_1( selfadjointeigensolver(Matrix3f()) );\n CALL_SUBTEST_2( selfadjointeigensolver(Matrix4d()) );\n CALL_SUBTEST_3( selfadjointeigensolver(MatrixXf(10,10)) );\n CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(19,19)) );\n CALL_SUBTEST_5( selfadjointeigensolver(MatrixXcd(17,17)) );\n\n \/\/ some trivial but implementation-wise tricky cases\n CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(1,1)) );\n CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(2,2)) );\n CALL_SUBTEST_6( selfadjointeigensolver(Matrix()) );\n CALL_SUBTEST_7( selfadjointeigensolver(Matrix()) );\n }\n\n \/\/ Test problem size constructors\n CALL_SUBTEST_8(SelfAdjointEigenSolver(10));\n CALL_SUBTEST_8(Tridiagonalization(10));\n}\n\n<|endoftext|>"} {"text":"\/\/ @(#)root\/thread:$Id$\n\/\/ Author: Xavier Valls March 2016\n\n\/*************************************************************************\n * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_TThreadExecutor\n#define ROOT_TThreadExecutor\n\n#include \"RConfigure.h\"\n\n\/\/ exclude in case ROOT does not have IMT support\n#ifndef R__USE_IMT\n\/\/ No need to error out for dictionaries.\n# if !defined(__ROOTCLING__) && !defined(G__DICTIONARY)\n# error \"Cannot use ROOT::TThreadExecutor without defining R__USE_IMT.\"\n# endif\n#else\n\n#include \"ROOT\/TExecutor.hxx\"\n#include \n#include \n#include \n\nnamespace tbb { class task_scheduler_init;}\n\nnamespace ROOT {\n\nclass TThreadExecutor: public TExecutor {\ntemplate\nfriend class ParallelReductionResolver;\n\npublic:\n explicit TThreadExecutor();\n\n explicit TThreadExecutor(size_t nThreads);\n\n TThreadExecutor(TThreadExecutor &) = delete;\n TThreadExecutor & operator=(TThreadExecutor &) = delete;\n\n ~TThreadExecutor();\n\n template>\n auto Map(F func, unsigned nTimes) -> std::vector::type>;\n \/\/\/ \\cond\n template>\n auto Map(F func, ROOT::TSeq args) -> std::vector::type>;\n template>\n auto Map(F func, std::vector &args) -> std::vector::type>;\n \/\/ \/ \\endcond\n using TExecutor::Map;\n\n \/\/ \/\/ MapReduce\n \/\/ \/\/ the late return types also check at compile-time whether redfunc is compatible with func,\n \/\/ \/\/ other than checking that func is compatible with the type of arguments.\n \/\/ \/\/ a static_assert check in TThreadExecutor::Reduce is used to check that redfunc is compatible with the type returned by func\n template>\n auto MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of::type;\n template>\n auto MapReduce(F func, ROOT::TSeq args, R redfunc, unsigned nChunks) -> typename std::result_of::type;\n \/\/ \/\/\/ \\cond doxygen should ignore these methods\n template>\n auto MapReduce(F func, std::initializer_list args, R redfunc, unsigned nChunks) -> typename std::result_of::type;\n template>\n auto MapReduce(F func, std::vector &args, R redfunc, unsigned nChunks) -> typename std::result_of::type;\n \/\/ \/\/\/ \\endcond\n using TExecutor::MapReduce;\n\n template auto Reduce(const std::vector &objs, BINARYOP redfunc) -> decltype(redfunc(objs.front(), objs.front()));\n template auto Reduce(const std::vector &objs, R redfunc) -> decltype(redfunc(objs));\n using TExecutor::Reduce;\n\nprotected:\n\n template>\n auto Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector::type>;\n template>\n auto Map(F func, ROOT::TSeq args, R redfunc, unsigned nChunks) -> std::vector::type>;\n template>\n auto Map(F func, std::vector &args, R redfunc, unsigned nChunks) -> std::vector::type>;\n template>\n auto Map(F func, std::initializer_list args, R redfunc, unsigned nChunks) -> std::vector::type>;\n\nprivate:\n void ParallelFor(unsigned start, unsigned end, unsigned step, const std::function &f);\n double ParallelReduce(const std::vector &objs, const std::function &redfunc);\n float ParallelReduce(const std::vector &objs, const std::function &redfunc);\n template\n auto SeqReduce(const std::vector &objs, R redfunc) -> decltype(redfunc(objs));\n\n std::unique_ptr fInitTBB;\n static unsigned fgPoolSize;\n};\n\n\/************ TEMPLATE METHODS IMPLEMENTATION ******************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Execute func (with no arguments) nTimes in parallel.\n\/\/\/ A vector containg executions' results is returned.\n\/\/\/ Functions that take more than zero arguments can be executed (with\n\/\/\/ fixed arguments) by wrapping them in a lambda or with std::bind.\ntemplate\nauto TThreadExecutor::Map(F func, unsigned nTimes) -> std::vector::type>\n{\n using retType = decltype(func());\n std::vector reslist(nTimes);\n auto lambda = [&](unsigned int i){\n reslist[i] = func();\n };\n ParallelFor(0U, nTimes, 1, lambda);\n\n return reslist;\n}\n\ntemplate\nauto TThreadExecutor::Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector::type>\n{\n if(nChunks == 0){\n return Map(func, nTimes);\n }\n\n using retType = decltype(func());\n std::vector reslist(nChunks);\n unsigned step = nChunks==0? 1 : (nTimes+nChunks-1)\/nChunks;\n auto lambda = [&](unsigned int i){\n std::vector partialResults(step);\n for(unsigned j=0; j\nauto TThreadExecutor::Map(F func, ROOT::TSeq args) -> std::vector::type>\n{\n unsigned start = *args.begin();\n unsigned end = *args.end();\n\n using retType = decltype(func(start));\n std::vector reslist(end-start);\n auto lambda = [&](unsigned int i){\n reslist[i] = func(i);\n };\n ParallelFor(start, end, 1, lambda);\n\n return reslist;\n}\n\ntemplate\nauto TThreadExecutor::Map(F func, ROOT::TSeq args, R redfunc, unsigned nChunks) -> std::vector::type>\n{\n if(nChunks == 0){\n return Map(func, args);\n }\n\n unsigned start = *args.begin();\n unsigned end = *args.end();\n unsigned step = nChunks==0? 1 :(end-start+nChunks-1)\/nChunks; \/\/ceiling the division\n\n using retType = decltype(func(start));\n std::vector reslist(nChunks);\n auto lambda = [&](unsigned int i){\n std::vector partialResults(step);\n for(unsigned j=0; j\nauto TThreadExecutor::Map(F func, std::vector &args) -> std::vector::type>\n{\n \/\/ \/\/check whether func is callable\n using retType = decltype(func(args.front()));\n\n unsigned int fNToProcess = args.size();\n std::vector reslist(fNToProcess);\n\n auto lambda = [&](unsigned int i){\n reslist[i] = func(args[i]);\n };\n\n ParallelFor(0U, fNToProcess, 1, lambda);\n\n return reslist;\n}\n\ntemplate\nauto TThreadExecutor::Map(F func, std::vector &args, R redfunc, unsigned nChunks) -> std::vector::type>\n{\n if(nChunks == 0){\n return Map(func, args);\n }\n \/\/ \/\/check whether func is callable\n using retType = decltype(func(args.front()));\n\n unsigned int fNToProcess = args.size();\n std::vector reslist(nChunks);\n unsigned step = (fNToProcess+nChunks-1)\/nChunks; \/\/ceiling the division\n\n auto lambda = [&](unsigned int i){\n std::vector partialResults(step);\n for(unsigned j=0; j\nauto TThreadExecutor::Map(F func, std::initializer_list args, R redfunc, unsigned nChunks) -> std::vector::type>\n{\n std::vector vargs(std::move(args));\n const auto &reslist = Map(func, vargs, redfunc, nChunks);\n return reslist;\n}\n\n\/\/ \/\/ tell doxygen to stop ignoring code\n\/\/ \/\/\/ \\endcond\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\/ This method behaves just like Map, but an additional redfunc function\n\/\/ \/\/\/ must be provided. redfunc is applied to the vector Map would return and\n\/\/ \/\/\/ must return the same type as func. In practice, redfunc can be used to\n\/\/ \/\/\/ \"squash\" the vector returned by Map into a single object by merging,\n\/\/ \/\/\/ adding, mixing the elements of the vector.\ntemplate\nauto TThreadExecutor::MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of::type\n{\n return Reduce(Map(func, nTimes, redfunc, nChunks), redfunc);\n}\n\n\/\/\/ \\cond doxygen should ignore these methods\ntemplate\nauto TThreadExecutor::MapReduce(F func, ROOT::TSeq args, R redfunc, unsigned nChunks) -> typename std::result_of::type\n{\n return Reduce(Map(func, args, redfunc, nChunks), redfunc);\n}\n\ntemplate\nauto TThreadExecutor::MapReduce(F func, std::initializer_list args, R redfunc, unsigned nChunks) -> typename std::result_of::type\n{\n return Reduce(Map(func, args, redfunc, nChunks), redfunc);\n}\n\ntemplate\nauto TThreadExecutor::MapReduce(F func, std::vector &args, R redfunc, unsigned nChunks) -> typename std::result_of::type\n{\n return Reduce(Map(func, args, redfunc, nChunks), redfunc);\n}\n\n\/\/\/ Check that redfunc has the right signature and call it on objs\ntemplate\nauto TThreadExecutor::Reduce(const std::vector &objs, BINARYOP redfunc) -> decltype(redfunc(objs.front(), objs.front()))\n{\n \/\/ check we can apply reduce to objs\n static_assert(std::is_same::value, \"redfunc does not have the correct signature\");\n return ParallelReduce(objs, redfunc);\n}\n\ntemplate\nauto TThreadExecutor::Reduce(const std::vector &objs, R redfunc) -> decltype(redfunc(objs))\n{\n \/\/ check we can apply reduce to objs\n static_assert(std::is_same::value, \"redfunc does not have the correct signature\");\n return SeqReduce(objs, redfunc);\n}\n\ntemplate\nauto TThreadExecutor::SeqReduce(const std::vector &objs, R redfunc) -> decltype(redfunc(objs))\n{\n return redfunc(objs);\n}\n\n} \/\/ namespace ROOT\n\n#endif \/\/ R__USE_IMT\n#endif\nAdd a getter for TThreadExecutor's pool size\/\/ @(#)root\/thread:$Id$\n\/\/ Author: Xavier Valls March 2016\n\n\/*************************************************************************\n * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_TThreadExecutor\n#define ROOT_TThreadExecutor\n\n#include \"RConfigure.h\"\n\n\/\/ exclude in case ROOT does not have IMT support\n#ifndef R__USE_IMT\n\/\/ No need to error out for dictionaries.\n# if !defined(__ROOTCLING__) && !defined(G__DICTIONARY)\n# error \"Cannot use ROOT::TThreadExecutor without defining R__USE_IMT.\"\n# endif\n#else\n\n#include \"ROOT\/TExecutor.hxx\"\n#include \n#include \n#include \n\nnamespace tbb { class task_scheduler_init;}\n\nnamespace ROOT {\n\nclass TThreadExecutor: public TExecutor {\ntemplate\nfriend class ParallelReductionResolver;\n\npublic:\n explicit TThreadExecutor();\n\n explicit TThreadExecutor(size_t nThreads);\n\n TThreadExecutor(TThreadExecutor &) = delete;\n TThreadExecutor & operator=(TThreadExecutor &) = delete;\n\n ~TThreadExecutor();\n\n template>\n auto Map(F func, unsigned nTimes) -> std::vector::type>;\n \/\/\/ \\cond\n template>\n auto Map(F func, ROOT::TSeq args) -> std::vector::type>;\n template>\n auto Map(F func, std::vector &args) -> std::vector::type>;\n \/\/ \/ \\endcond\n using TExecutor::Map;\n\n \/\/ \/\/ MapReduce\n \/\/ \/\/ the late return types also check at compile-time whether redfunc is compatible with func,\n \/\/ \/\/ other than checking that func is compatible with the type of arguments.\n \/\/ \/\/ a static_assert check in TThreadExecutor::Reduce is used to check that redfunc is compatible with the type returned by func\n template>\n auto MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of::type;\n template>\n auto MapReduce(F func, ROOT::TSeq args, R redfunc, unsigned nChunks) -> typename std::result_of::type;\n \/\/ \/\/\/ \\cond doxygen should ignore these methods\n template>\n auto MapReduce(F func, std::initializer_list args, R redfunc, unsigned nChunks) -> typename std::result_of::type;\n template>\n auto MapReduce(F func, std::vector &args, R redfunc, unsigned nChunks) -> typename std::result_of::type;\n \/\/ \/\/\/ \\endcond\n using TExecutor::MapReduce;\n\n template auto Reduce(const std::vector &objs, BINARYOP redfunc) -> decltype(redfunc(objs.front(), objs.front()));\n template auto Reduce(const std::vector &objs, R redfunc) -> decltype(redfunc(objs));\n using TExecutor::Reduce;\n\n \/\/Returns the number of threads set in the scheduler at call time.\n static int GetPoolSize(){return fgPoolSize;}\n\nprotected:\n\n template>\n auto Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector::type>;\n template>\n auto Map(F func, ROOT::TSeq args, R redfunc, unsigned nChunks) -> std::vector::type>;\n template>\n auto Map(F func, std::vector &args, R redfunc, unsigned nChunks) -> std::vector::type>;\n template>\n auto Map(F func, std::initializer_list args, R redfunc, unsigned nChunks) -> std::vector::type>;\n\nprivate:\n void ParallelFor(unsigned start, unsigned end, unsigned step, const std::function &f);\n double ParallelReduce(const std::vector &objs, const std::function &redfunc);\n float ParallelReduce(const std::vector &objs, const std::function &redfunc);\n template\n auto SeqReduce(const std::vector &objs, R redfunc) -> decltype(redfunc(objs));\n\n std::unique_ptr fInitTBB;\n static unsigned fgPoolSize;\n};\n\n\/************ TEMPLATE METHODS IMPLEMENTATION ******************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Execute func (with no arguments) nTimes in parallel.\n\/\/\/ A vector containg executions' results is returned.\n\/\/\/ Functions that take more than zero arguments can be executed (with\n\/\/\/ fixed arguments) by wrapping them in a lambda or with std::bind.\ntemplate\nauto TThreadExecutor::Map(F func, unsigned nTimes) -> std::vector::type>\n{\n using retType = decltype(func());\n std::vector reslist(nTimes);\n auto lambda = [&](unsigned int i){\n reslist[i] = func();\n };\n ParallelFor(0U, nTimes, 1, lambda);\n\n return reslist;\n}\n\ntemplate\nauto TThreadExecutor::Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector::type>\n{\n if(nChunks == 0){\n return Map(func, nTimes);\n }\n\n using retType = decltype(func());\n std::vector reslist(nChunks);\n unsigned step = nChunks==0? 1 : (nTimes+nChunks-1)\/nChunks;\n auto lambda = [&](unsigned int i){\n std::vector partialResults(step);\n for(unsigned j=0; j\nauto TThreadExecutor::Map(F func, ROOT::TSeq args) -> std::vector::type>\n{\n unsigned start = *args.begin();\n unsigned end = *args.end();\n\n using retType = decltype(func(start));\n std::vector reslist(end-start);\n auto lambda = [&](unsigned int i){\n reslist[i] = func(i);\n };\n ParallelFor(start, end, 1, lambda);\n\n return reslist;\n}\n\ntemplate\nauto TThreadExecutor::Map(F func, ROOT::TSeq args, R redfunc, unsigned nChunks) -> std::vector::type>\n{\n if(nChunks == 0){\n return Map(func, args);\n }\n\n unsigned start = *args.begin();\n unsigned end = *args.end();\n unsigned step = nChunks==0? 1 :(end-start+nChunks-1)\/nChunks; \/\/ceiling the division\n\n using retType = decltype(func(start));\n std::vector reslist(nChunks);\n auto lambda = [&](unsigned int i){\n std::vector partialResults(step);\n for(unsigned j=0; j\nauto TThreadExecutor::Map(F func, std::vector &args) -> std::vector::type>\n{\n \/\/ \/\/check whether func is callable\n using retType = decltype(func(args.front()));\n\n unsigned int fNToProcess = args.size();\n std::vector reslist(fNToProcess);\n\n auto lambda = [&](unsigned int i){\n reslist[i] = func(args[i]);\n };\n\n ParallelFor(0U, fNToProcess, 1, lambda);\n\n return reslist;\n}\n\ntemplate\nauto TThreadExecutor::Map(F func, std::vector &args, R redfunc, unsigned nChunks) -> std::vector::type>\n{\n if(nChunks == 0){\n return Map(func, args);\n }\n \/\/ \/\/check whether func is callable\n using retType = decltype(func(args.front()));\n\n unsigned int fNToProcess = args.size();\n std::vector reslist(nChunks);\n unsigned step = (fNToProcess+nChunks-1)\/nChunks; \/\/ceiling the division\n\n auto lambda = [&](unsigned int i){\n std::vector partialResults(step);\n for(unsigned j=0; j\nauto TThreadExecutor::Map(F func, std::initializer_list args, R redfunc, unsigned nChunks) -> std::vector::type>\n{\n std::vector vargs(std::move(args));\n const auto &reslist = Map(func, vargs, redfunc, nChunks);\n return reslist;\n}\n\n\/\/ \/\/ tell doxygen to stop ignoring code\n\/\/ \/\/\/ \\endcond\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\/ This method behaves just like Map, but an additional redfunc function\n\/\/ \/\/\/ must be provided. redfunc is applied to the vector Map would return and\n\/\/ \/\/\/ must return the same type as func. In practice, redfunc can be used to\n\/\/ \/\/\/ \"squash\" the vector returned by Map into a single object by merging,\n\/\/ \/\/\/ adding, mixing the elements of the vector.\ntemplate\nauto TThreadExecutor::MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of::type\n{\n return Reduce(Map(func, nTimes, redfunc, nChunks), redfunc);\n}\n\n\/\/\/ \\cond doxygen should ignore these methods\ntemplate\nauto TThreadExecutor::MapReduce(F func, ROOT::TSeq args, R redfunc, unsigned nChunks) -> typename std::result_of::type\n{\n return Reduce(Map(func, args, redfunc, nChunks), redfunc);\n}\n\ntemplate\nauto TThreadExecutor::MapReduce(F func, std::initializer_list args, R redfunc, unsigned nChunks) -> typename std::result_of::type\n{\n return Reduce(Map(func, args, redfunc, nChunks), redfunc);\n}\n\ntemplate\nauto TThreadExecutor::MapReduce(F func, std::vector &args, R redfunc, unsigned nChunks) -> typename std::result_of::type\n{\n return Reduce(Map(func, args, redfunc, nChunks), redfunc);\n}\n\n\/\/\/ Check that redfunc has the right signature and call it on objs\ntemplate\nauto TThreadExecutor::Reduce(const std::vector &objs, BINARYOP redfunc) -> decltype(redfunc(objs.front(), objs.front()))\n{\n \/\/ check we can apply reduce to objs\n static_assert(std::is_same::value, \"redfunc does not have the correct signature\");\n return ParallelReduce(objs, redfunc);\n}\n\ntemplate\nauto TThreadExecutor::Reduce(const std::vector &objs, R redfunc) -> decltype(redfunc(objs))\n{\n \/\/ check we can apply reduce to objs\n static_assert(std::is_same::value, \"redfunc does not have the correct signature\");\n return SeqReduce(objs, redfunc);\n}\n\ntemplate\nauto TThreadExecutor::SeqReduce(const std::vector &objs, R redfunc) -> decltype(redfunc(objs))\n{\n return redfunc(objs);\n}\n\n} \/\/ namespace ROOT\n\n#endif \/\/ R__USE_IMT\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n\n#include \/\/ _getch()\n\n#include \"Osiris.hpp\"\n\n#include \"Modules\/OsirisModules.hpp\"\n\n#include \n\n#include \n\nOsiris::Osiris()\n{\n wchar_t Buffer[MAX_PATH] = { 0 };\n SHGetSpecialFolderPathW(nullptr, Buffer, CSIDL_PROFILE, false);\n\n std::wstring UserFolder(Buffer);\n UserFolder += L\"\\\\AppData\\\\Local\\\\Packages\\\\Microsoft.Halo5Forge_8wekyb3d8bbwe\\\\LocalState\\\\Log.txt\";\n\n Util::Log::Instance()->SetFile(UserFolder);\n\n LOG << \"Osiris\" << \"---- \";\n LOG << '[' << __DATE__ << \" : \" << __TIME__ << ']' << std::endl;\n LOG << \"\\t-Wunkolo (Wunkolo@gmail.com)\\n\";\n LOG << std::wstring(80, '-') << std::endl;\n\n LOG << std::hex << std::uppercase << std::setfill(L'0');\n LOG << \"Process Base: 0x\" << Util::Process::Base() << std::endl;\n LOG << \"Osiris Thread ID: 0x\" << Util::Thread::GetCurrentThreadId() << std::endl;\n LOG << \"Osiris Base: 0x\" << Util::Process::GetModuleBase(\"Osiris.dll\") << std::endl;\n\n const Ausar::ThreadTable *Table;\n\n Table = Util::Process::GetModuleBase()(0x58CA4B0).Point();\n\n \/\/for( size_t i = 0; i < 64; i++ )\n \/\/{\n \/\/ if( Table->Entries[i].Active == 0 )\n \/\/ {\n \/\/ continue;\n \/\/ }\n \/\/ LOG << \"Thread Name: \" << reinterpret_cast(Table->Entries[i].ThreadName) << std::endl;\n \/\/ LOG << \"Thread ID: \" << Table->Entries[i].ThreadID << std::endl;\n \/\/}\n\n LOG << \"Main Thread ID: \" << Table->GetThreadIDByName(\"MAIN\") << std::endl;\n\n \/\/ Push Commands\n \/\/PushModule(\"research\");\n \/\/PushModule(\"player\");\n}\n\nOsiris::~Osiris()\n{\n}\n\nvoid Osiris::Tick(const std::chrono::high_resolution_clock::duration &DeltaTime)\n{\n for( std::pair> Command : Commands )\n {\n if( Command.second )\n {\n Command.second->Tick(DeltaTime);\n }\n }\n}Tls globals access draft#include \n#include \n\n#include \n#include \n\n#include \/\/ _getch()\n\n#include \"Osiris.hpp\"\n\n#include \"Modules\/OsirisModules.hpp\"\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\nOsiris::Osiris()\n{\n wchar_t Buffer[MAX_PATH] = { 0 };\n SHGetSpecialFolderPathW(nullptr, Buffer, CSIDL_PROFILE, false);\n\n std::wstring UserFolder(Buffer);\n UserFolder += L\"\\\\AppData\\\\Local\\\\Packages\\\\Microsoft.Halo5Forge_8wekyb3d8bbwe\\\\LocalState\\\\Log.txt\";\n\n Util::Log::Instance()->SetFile(UserFolder);\n\n LOG << \"Osiris\" << \"---- \";\n LOG << '[' << __DATE__ << \" : \" << __TIME__ << ']' << std::endl;\n LOG << \"\\t-Wunkolo (Wunkolo@gmail.com)\\n\";\n LOG << std::wstring(80, '-') << std::endl;\n\n LOG << std::hex << std::uppercase << std::setfill(L'0')\n << \"Process Base: 0x\" << Util::Process::Base() << std::endl;\n LOG << \"Osiris Thread ID: 0x\" << Util::Thread::GetCurrentThreadId() << std::endl;\n LOG << \"Osiris Base: 0x\" << Util::Process::GetModuleBase(\"Osiris.dll\") << std::endl;\n\n const Ausar::ThreadTable *Table;\n\n Table = Util::Process::GetModuleBase()(0x58CA4B0).Point();\n\n \/\/for( size_t i = 0; i < 64; i++ )\n \/\/{\n \/\/ if( Table->Entries[i].Active == 0 )\n \/\/ {\n \/\/ continue;\n \/\/ }\n \/\/ LOG << \"Thread Name: \" << reinterpret_cast(Table->Entries[i].ThreadName) << std::endl;\n \/\/ LOG << \"Thread ID: \" << Table->Entries[i].ThreadID << std::endl;\n \/\/}\n\n uint64_t ThreadID = Table->GetThreadIDByName(\"MAIN\");\n\n LOG << \"Main Thread ID: \" << ThreadID << std::endl;\n\n typedef enum _THREADINFOCLASS {\n ThreadBasicInformation = 0,\n } THREADINFOCLASS;\n\n typedef LONG KPRIORITY;\n\n typedef struct _CLIENT_ID {\n HANDLE UniqueProcess;\n HANDLE UniqueThread;\n } CLIENT_ID;\n typedef CLIENT_ID *PCLIENT_ID;\n\n typedef struct _THREAD_BASIC_INFORMATION\n {\n NTSTATUS ExitStatus;\n PVOID TebBaseAddress;\n CLIENT_ID ClientId;\n KAFFINITY AffinityMask;\n KPRIORITY Priority;\n KPRIORITY BasePriority;\n } THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;\n\n typedef NTSTATUS(WINAPI *InfoThreadProc)(HANDLE, LONG, PVOID, ULONG, PULONG);\n\n HANDLE ThreadHandle = OpenThread(\n THREAD_ALL_ACCESS,\n false,\n static_cast(ThreadID)\n );\n\n Util::Pointer TEB(nullptr);\n\n InfoThreadProc NtQueryInformationThread = (InfoThreadProc)GetProcAddress(GetModuleHandleW(L\"ntdll.dll\"), \"NtQueryInformationThread\");\n\n THREAD_BASIC_INFORMATION ThreadInfo = { 0 };\n\n NTSTATUS ntStatus = NtQueryInformationThread(\n ThreadHandle,\n ThreadBasicInformation,\n &ThreadInfo,\n sizeof(THREAD_BASIC_INFORMATION),\n nullptr\n );\n\n LOG << ResumeThread(ThreadHandle) << std::endl;\n\n CloseHandle(ThreadHandle);\n\n TEB = Util::Pointer(ThreadInfo.TebBaseAddress)[0x58][0];\n\n LOG << \"Physics Constants: \" << TEB[0x2D30] << std::endl;\n LOG << \"DOF Globals: \" << TEB[0x49B0] << std::endl;\n LOG << \"DOF Data: \" << TEB[0x1310] << std::endl;\n LOG << \"Director globals: \" << TEB[0x198] << std::endl;\n LOG << \"Hue saturation control: \" << TEB[0x2FF8] << std::endl;\n LOG << \"Game engine globals: \" << TEB[0x13A8] << std::endl;\n LOG << \"Local Game engine globals: \" << TEB[0x13B0] << std::endl;\n LOG << \"Game engine render globals: \" << TEB[0x13B8] << std::endl;\n LOG << \"Game time globals: \" << TEB[0x12A8] << std::endl;\n LOG << \"Composer globals: \" << TEB[0x1C8] << std::endl;\n LOG << \"Fp weapons: \" << TEB[0x1260] << std::endl;\n LOG << \"Player Focus: \" << TEB[0x1320] << std::endl;\n LOG << \"Player Control Globals: \" << TEB[0x1340] << std::endl;\n LOG << \"Player Control Globals Deter.: \" << TEB[0x1348] << std::endl;\n LOG << \"Player Globals: \" << TEB[0x1370] << std::endl;\n\n LOG << \"AI Globals: \" << TEB[0x2E40] << std::endl;\n LOG << \"AI Player state Globals: \" << TEB[0x2E18] << std::endl;\n\n LOG << \"Interaction ripples: \" << TEB[0x4960] << std::endl;\n\n LOG << \"Rasterizer: \" << TEB[0x49A0] << std::endl;\n LOG << \"Render game globals: \" << TEB[0x49A8] << std::endl;\n LOG << \"fp orientations: \" << TEB[0x4A10] << std::endl;\n\n LOG << \"Objects: \" << TEB[0x4B18] << std::endl;\n LOG << \"Object name list: \" << TEB[0x4B20] << std::endl;\n LOG << \"Object placement globals: \" << TEB[0x4B58] << std::endl;\n LOG << \"Object globals: \" << TEB[0x4C08] << std::endl;\n LOG << \"orientations: \" << TEB[0x110] << std::endl;\n\n \/\/ Push Commands\n \/\/PushModule(\"research\");\n \/\/PushModule(\"player\");\n}\n\nOsiris::~Osiris()\n{\n}\n\nvoid Osiris::Tick(const std::chrono::high_resolution_clock::duration &DeltaTime)\n{\n for( std::pair> Command : Commands )\n {\n if( Command.second )\n {\n Command.second->Tick(DeltaTime);\n }\n }\n}<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: customshapeproperties.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2008-01-17 08:05:45 $\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 OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX\n#define OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX\n\n#include \"oox\/helper\/propertymap.hxx\"\n#include \"oox\/drawingml\/color.hxx\"\n#include \n#include \n#include \"tokens.hxx\"\n#include \n#include \n\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEPARAMETERPAIR_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEPARAMETERTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPESEGMENT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEGLUEPOINTTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPESEGMENTCOMMAND_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPETEXTFRAME_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEADJUSTMENTVALUE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPETEXTPATHMODE_HPP_\n#include \n#endif\n#ifndef __com_sun_star_beans_PropertyValues_hpp__\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_PROJECTIONMODE_HPP_\n#include \n#endif\n\nnamespace oox { namespace drawingml {\n\nclass CustomShapeProperties;\n\ntypedef boost::shared_ptr< CustomShapeProperties > CustomShapePropertiesPtr;\n\nstruct CustomShapeGuide\n{\n rtl::OUString maName;\n rtl::OUString maFormula;\n};\n\nclass CustomShapeProperties\n{\npublic:\n\n CustomShapeProperties();\n virtual ~CustomShapeProperties();\n\n void apply( const CustomShapePropertiesPtr& );\n void pushToPropSet( const ::oox::core::XmlFilterBase& rFilterBase,\n const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet > & xPropSet ) const;\n\n void setShapePresetType( const rtl::OUString& rShapePresetType ){ maShapePresetType = rShapePresetType; };\n std::vector< CustomShapeGuide >& getAdjustmentValues(){ return maAdjustmentValues; };\n\n double getValue( const std::vector< CustomShapeGuide >&, sal_uInt32 nIndex ) const;\n\nprivate:\n\n rtl::OUString maShapePresetType;\n std::vector< CustomShapeGuide > maAdjustmentValues;\n};\n\n} }\n\n#endif \/\/ OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX\nINTEGRATION: CWS xmlfilter03_DEV300 (1.2.4); FILE MERGED 2008\/01\/22 16:41:23 hbrinkm 1.2.4.1: pushToPropertySet: new parameter xShape\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: customshapeproperties.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 17:39:22 $\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 OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX\n#define OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX\n\n#include \"oox\/helper\/propertymap.hxx\"\n#include \"oox\/drawingml\/color.hxx\"\n#include \n#include \n#include \"tokens.hxx\"\n#include \n#include \n\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEPARAMETERPAIR_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEPARAMETERTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPESEGMENT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEGLUEPOINTTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPESEGMENTCOMMAND_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPETEXTFRAME_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEADJUSTMENTVALUE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPETEXTPATHMODE_HPP_\n#include \n#endif\n#ifndef __com_sun_star_beans_PropertyValues_hpp__\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_PROJECTIONMODE_HPP_\n#include \n#endif\n#include \n\nnamespace oox { namespace drawingml {\n\nclass CustomShapeProperties;\n\ntypedef boost::shared_ptr< CustomShapeProperties > CustomShapePropertiesPtr;\n\nstruct CustomShapeGuide\n{\n rtl::OUString maName;\n rtl::OUString maFormula;\n};\n\nclass CustomShapeProperties\n{\npublic:\n\n CustomShapeProperties();\n virtual ~CustomShapeProperties();\n\n void apply( const CustomShapePropertiesPtr& );\n void pushToPropSet( const ::oox::core::XmlFilterBase& rFilterBase,\n const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet > & xPropSet,\n const ::com::sun::star::uno::Reference < ::com::sun::star::drawing::XShape > & xShape) const;\n\n void setShapePresetType( const rtl::OUString& rShapePresetType ){ maShapePresetType = rShapePresetType; };\n std::vector< CustomShapeGuide >& getAdjustmentValues(){ return maAdjustmentValues; };\n\n double getValue( const std::vector< CustomShapeGuide >&, sal_uInt32 nIndex ) const;\n\nprivate:\n\n rtl::OUString maShapePresetType;\n std::vector< CustomShapeGuide > maAdjustmentValues;\n};\n\n} }\n\n#endif \/\/ OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX\n<|endoftext|>"} {"text":"#include \"ParticleModel.h\"\n\nParticleModel::ParticleModel(Transform * transform) : _transform(transform)\n{\n\t_transform = transform;\n\n\tgravity = -9.81f;\n\t_mass = 1.0f;\n\n\t_velocity = XMFLOAT3(0.0f, 0.0f, 0.0f);\n\t_acceleration = XMFLOAT3(0.0f, 0.0f, 0.0f);\n\n\t\/\/ Swap between velocity\n\t_useConstAcc = true;\n\tlaminar = true;\n\tslideOn = false;\n\n\tforce = XMFLOAT3(0.0f, 0.0f, 0.0f);\n\tnetForce = XMFLOAT3(0.0f, 0.0f, 0.0f);\n\n\tforceMag = 0.0f;\n\tdragFactor = 1.0f;\n\n\t_radius = 0.5f;\n}\n\nParticleModel::~ParticleModel()\n{\n}\n\nvoid ParticleModel::Move(float xAmount, float yAmount, float zAmount)\n{\n\tXMFLOAT3 position = _transform->GetPosition();\n\n\tposition.x += xAmount;\n\tposition.y += yAmount;\n\tposition.z += zAmount;\n\n\t_transform->SetPosition(position);\n}\n\n\/\/ AI Move\nvoid ParticleModel::Move(XMFLOAT3 move)\n{\n\tXMFLOAT3 position = _transform->GetPosition();\n\tposition.x += move.x;\n\tposition.y += move.y;\n\tposition.z += move.z;\n\t_transform->SetPosition(position);\n}\n\nvoid ParticleModel::MoveConstantVelocity(float t)\n{\n\tt = t \/ 1000;\n\n\tXMFLOAT3 position = _transform->GetPosition();\n\n\tposition.x += _velocity.x * t;\n\tposition.y += _velocity.y * t;\n\tposition.z += _velocity.z * t;\n\n\t_transform->SetPosition(position);\n}\n\nvoid ParticleModel::MoveConstantAcceleration(float t)\n{\n\tt = t \/ 1000;\n\n\tXMFLOAT3 position = _transform->GetPosition();\n\n\t\/\/ S = UT + 0.5AT^2\n\tposition.x += _velocity.x * t + 0.5f * _acceleration.x * t * t;\n\tposition.y += _velocity.y * t + 0.5f * _acceleration.y * t * t;\n\tposition.z += _velocity.z * t + 0.5f * _acceleration.z * t * t;\n\n\t\/\/ V = U + AT\n\t_velocity.x += _acceleration.x * t;\n\t_velocity.y += _acceleration.y * t;\n\t_velocity.z += _acceleration.z * t;\n\n\t_transform->SetPosition(position);\n}\n\nvoid ParticleModel::UpdateNetForce()\n{\n\tnetForce.x = dragForce.x + slidingForce.x;\n\tnetForce.y = dragForce.y + slidingForce.y;\n\tnetForce.z = dragForce.z + slidingForce.z;\n}\n\nvoid ParticleModel::UpdateAccel()\n{\n\t_acceleration.x = netForce.x \/ _mass;\n\t_acceleration.y = netForce.y \/ _mass;\n\t_acceleration.z = netForce.z \/ _mass;\n}\n\nvoid ParticleModel::UpdateState(float t)\n{\n\tUpdateNetForce();\n\n\tUpdateAccel();\n\n\tMoveConstantAcceleration(t);\n}\n\nvoid ParticleModel::Update(float t)\n{\n\tif (_useConstAcc)\n\t{\n\t\tif (slideOn == true)\n\t\t{\n\t\t\tSlidingForce(XMConvertToRadians(90.0f), 10.0f);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tslidingForce.x = 0.0f;\n\t\t\tslidingForce.y = _mass * gravity;\n\t\t\tslidingForce.z = 0.0f;\n\t\t}\n\t\t\n\t\tDragForce();\n\n\t\tUpdateState(t);\n\t}\n\telse\n\t{\n\t\tMoveConstantVelocity(t);\n\t}\n}\n\nvoid ParticleModel::SlidingForce(float theta, float frCoef)\n{\n\t\/\/ Calculate magnitude of force\n\tforceMag = _mass * gravity * (sin(theta) - frCoef * cos(theta));\n\n\t\/\/ Calculate x- and y-components of force (NOTE: x-axis assumed positive rightwards and y-axis positive downwards)\n\tslidingForce.x = forceMag * cos(theta);\n\tslidingForce.y = forceMag * sin(theta);\n\tslidingForce.z = forceMag * cos(theta);\n\n\tif (slidingForce.y > 0.0f)\n\t{\n\t\tslidingForce.x = 0.0f;\n\t\tslidingForce.y = 0.0f;\n\t\t\/\/slidingForce.z = 0.0f;\n\t}\n\n\t\/\/ TODO: Check to ensure that magnitude is not negative\n\t\/\/if (forceMag <= 0.0f)\n\t\/\/\tforceMag = -forceMag;\n}\n\nvoid ParticleModel::SetSlidingForce(bool slideBool)\n{\n\tslideOn = slideBool;\n}\n\nvoid ParticleModel::SlidingMotion(float t)\n{\n\t\/\/SlidingForce(XMConvertToRadians(25.0f), 0.2f);\n\n\tUpdateState(t);\n\n\tMoveConstantAcceleration(t);\n}\n\nvoid ParticleModel::MotionInFluid()\n{\n\tDragForce();\n\n\t\/\/UpdateState();\n\t\/\/\n\t\/\/Move();\n}\n\nvoid ParticleModel::DragForce()\n{\n\tif (laminar)\n\t\t\/\/ Calculate drag force for laminar flow\n\t\tDragLamFlow();\n\telse\n\t\t\/\/ Calculate drag force for turbulent flow\n\t\tDragTurbFlow();\n\n}\n\nvoid ParticleModel::DragLamFlow()\n{\n\t\/\/ Calculate of x- and y-components of drag force\n\tdragForce.x = -dragFactor * _velocity.x;\n\tdragForce.y = -dragFactor * _velocity.y;\n\tdragForce.z = -dragFactor * _velocity.z;\n}\n\nvoid ParticleModel::DragTurbFlow()\n{\n\t\/\/ Calculate magnitude of velocity\n\tfloat velMag;\n\tvelMag = sqrt((_velocity.x * _velocity.x) + (_velocity.y * _velocity.y) + (_velocity.z * _velocity.z));\n\n\t\/\/ Calculate unit vector\/normalised vector of velocity\n\tXMFLOAT3 unitVel;\n\tunitVel.x = (_velocity.x \/ velMag);\n\tunitVel.y = (_velocity.y \/ velMag);\n\tunitVel.z = (_velocity.z \/ velMag);\n\n\t\/\/ Calculate magnitude of drag force\n\tfloat dragMag;\n\tdragMag = dragFactor * velMag * velMag;\n\n\t\/\/ Calculate of x- and y-components of drag force\n\tdragForce.x = -dragMag * unitVel.x;\n\tdragForce.y = -dragMag * unitVel.y;\n\tdragForce.z = -dragMag * unitVel.z;\n\n}\n\nbool ParticleModel::CheckCollision(XMFLOAT3 position2, float radius2)\n{\n\tXMFLOAT3 position = _transform->GetPosition();\n\n\tXMFLOAT3 difference;\n\tdifference.x = position.x - position2.x;\n\tdifference.y = position.y - position2.y;\n\tdifference.z = position.z - position2.z;\n\n\tfloat differenceMag = sqrt((difference.x * difference.x) + (difference.y * difference.y) + (difference.z * difference.z));\n\n\tfloat rDistance = _radius + radius2;\n\n\tif (differenceMag <= rDistance)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\nvoid ParticleModel::CheckFloorCollision(XMFLOAT3 floorPos)\n{\n\tXMFLOAT3 objectPosition = _transform->GetPosition();\n\n\tXMFLOAT3 difference;\n\tdifference.y = objectPosition.y - floorPos.y;\n\n\tfloat differenceMag = sqrt(difference.y * difference.y);\n\n\tif (differenceMag <= _radius)\n\t{\n\t\tslideOn = true;\n\t\t_velocity.y = -_velocity.y;\n\t}\n\telse\n\t{\n\t\tslideOn = false;\n\t}\n}\n\nvoid ParticleModel::ResolveCollision(ParticleModel* particleModel1, ParticleModel* particleModel2)\n{\n\tfloat rCoef = 0.8f;\n\n\tXMFLOAT3 prevPos1 = particleModel1->_transform->GetOldPosition();\n\tXMFLOAT3 prevPos2 = particleModel2->_transform->GetOldPosition();\n\n\tfloat mass1 = particleModel1->GetMass();\n\tfloat mass2 = particleModel2->GetMass();\n\n\tXMFLOAT3 initialVelocity1 = particleModel1->GetVelocity();\n\tXMFLOAT3 initialVelocity2 = particleModel2->GetVelocity();\n\n\tparticleModel1->_transform->SetPosition(prevPos1);\n\tparticleModel2->_transform->SetPosition(prevPos2);\n\n\tXMFLOAT3 velocity1;\n\tXMFLOAT3 velocity2;\n\n\tvelocity1.x = (mass1 * initialVelocity1.x) + (mass2 * initialVelocity2.x) + ((mass2 * rCoef) * (initialVelocity2.x - initialVelocity1.x)) \/ (mass1 + mass2);\n\tvelocity1.y = (mass1 * initialVelocity1.y) + (mass2 * initialVelocity2.y) + ((mass2 * rCoef) * (initialVelocity2.y - initialVelocity1.y)) \/ (mass1 + mass2);\n\tvelocity1.z = (mass1 * initialVelocity1.z) + (mass2 * initialVelocity2.z) + ((mass2 * rCoef) * (initialVelocity2.z - initialVelocity1.z)) \/ (mass1 + mass2);\n\n\tvelocity2.x = (mass1 * initialVelocity1.x) + (mass2 * initialVelocity2.x) + ((mass1 * rCoef) * (initialVelocity1.x - initialVelocity2.x)) \/ (mass1 + mass2);\n\tvelocity2.y = (mass1 * initialVelocity1.y) + (mass2 * initialVelocity2.y) + ((mass1 * rCoef) * (initialVelocity1.y - initialVelocity2.y)) \/ (mass1 + mass2);\n\tvelocity2.z = (mass1 * initialVelocity1.z) + (mass2 * initialVelocity2.z) + ((mass1 * rCoef) * (initialVelocity1.z - initialVelocity2.z)) \/ (mass1 + mass2);\n\t\n\tparticleModel1->SetVelocity(velocity1);\n\tparticleModel2->SetVelocity(velocity2);\n} Updated comments#include \"ParticleModel.h\"\n\nParticleModel::ParticleModel(Transform * transform) : _transform(transform)\n{\n\t_transform = transform;\n\n\tgravity = -9.81f;\n\t_mass = 1.0f;\n\n\t_velocity = XMFLOAT3(0.0f, 0.0f, 0.0f);\n\t_acceleration = XMFLOAT3(0.0f, 0.0f, 0.0f);\n\n\t\/\/ Swap between velocity\n\t_useConstAcc = true;\n\tlaminar = true;\n\tslideOn = false;\n\n\tforce = XMFLOAT3(0.0f, 0.0f, 0.0f);\n\tnetForce = XMFLOAT3(0.0f, 0.0f, 0.0f);\n\n\tforceMag = 0.0f;\n\tdragFactor = 1.0f;\n\n\t_radius = 0.5f;\n}\n\nParticleModel::~ParticleModel()\n{\n}\n\nvoid ParticleModel::Move(float xAmount, float yAmount, float zAmount)\n{\n\tXMFLOAT3 position = _transform->GetPosition();\n\n\tposition.x += xAmount;\n\tposition.y += yAmount;\n\tposition.z += zAmount;\n\n\t_transform->SetPosition(position);\n}\n\n\/\/ AI Move\nvoid ParticleModel::Move(XMFLOAT3 move)\n{\n\tXMFLOAT3 position = _transform->GetPosition();\n\tposition.x += move.x;\n\tposition.y += move.y;\n\tposition.z += move.z;\n\t_transform->SetPosition(position);\n}\n\nvoid ParticleModel::MoveConstantVelocity(float t)\n{\n\tt = t \/ 1000;\n\n\tXMFLOAT3 position = _transform->GetPosition();\n\n\tposition.x += _velocity.x * t;\n\tposition.y += _velocity.y * t;\n\tposition.z += _velocity.z * t;\n\n\t_transform->SetPosition(position);\n}\n\nvoid ParticleModel::MoveConstantAcceleration(float t)\n{\n\tt = t \/ 1000;\n\n\tXMFLOAT3 position = _transform->GetPosition();\n\n\t\/\/ S = UT + 0.5AT^2\n\tposition.x += _velocity.x * t + 0.5f * _acceleration.x * t * t;\n\tposition.y += _velocity.y * t + 0.5f * _acceleration.y * t * t;\n\tposition.z += _velocity.z * t + 0.5f * _acceleration.z * t * t;\n\n\t\/\/ V = U + AT\n\t_velocity.x += _acceleration.x * t;\n\t_velocity.y += _acceleration.y * t;\n\t_velocity.z += _acceleration.z * t;\n\n\t_transform->SetPosition(position);\n}\n\nvoid ParticleModel::UpdateNetForce()\n{\n\tnetForce.x = dragForce.x + slidingForce.x;\n\tnetForce.y = dragForce.y + slidingForce.y;\n\tnetForce.z = dragForce.z + slidingForce.z;\n}\n\nvoid ParticleModel::UpdateAccel()\n{\n\t_acceleration.x = netForce.x \/ _mass;\n\t_acceleration.y = netForce.y \/ _mass;\n\t_acceleration.z = netForce.z \/ _mass;\n}\n\nvoid ParticleModel::UpdateState(float t)\n{\n\tUpdateNetForce();\n\n\tUpdateAccel();\n\n\tMoveConstantAcceleration(t);\n}\n\nvoid ParticleModel::Update(float t)\n{\n\tif (_useConstAcc)\n\t{\n\t\tif (slideOn == true)\n\t\t{\n\t\t\tSlidingForce(XMConvertToRadians(90.0f), 10.0f);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tslidingForce.x = 0.0f;\n\t\t\tslidingForce.y = _mass * gravity;\n\t\t\tslidingForce.z = 0.0f;\n\t\t}\n\t\t\n\t\tDragForce();\n\n\t\tUpdateState(t);\n\t}\n\telse\n\t{\n\t\tMoveConstantVelocity(t);\n\t}\n}\n\nvoid ParticleModel::SlidingForce(float theta, float frCoef)\n{\n\t\/\/ Calculate magnitude of force\n\tforceMag = _mass * gravity * (sin(theta) - frCoef * cos(theta));\n\n\t\/\/ Calculate x- and y-components of force (NOTE: x-axis assumed positive rightwards and y-axis positive downwards)\n\tslidingForce.x = forceMag * cos(theta);\n\tslidingForce.y = forceMag * sin(theta);\n\tslidingForce.z = forceMag * cos(theta);\n\n\tif (slidingForce.y > 0.0f)\n\t{\n\t\tslidingForce.x = 0.0f;\n\t\tslidingForce.y = 0.0f;\n\t\tslidingForce.z = 0.0f;\n\t}\n\n\t\/\/ TODO: Check to ensure that magnitude is not negative\n\t\/\/if (forceMag <= 0.0f)\n\t\/\/\tforceMag = -forceMag;\n}\n\nvoid ParticleModel::SetSlidingForce(bool slideBool)\n{\n\tslideOn = slideBool;\n}\n\nvoid ParticleModel::SlidingMotion(float t)\n{\n\t\/\/SlidingForce(XMConvertToRadians(25.0f), 0.2f);\n\n\tUpdateState(t);\n\n\tMoveConstantAcceleration(t);\n}\n\nvoid ParticleModel::MotionInFluid()\n{\n\tDragForce();\n\n\t\/\/UpdateState();\n\t\/\/Move();\n}\n\nvoid ParticleModel::DragForce()\n{\n\tif (laminar)\n\t\t\/\/ Calculate drag force for laminar flow\n\t\tDragLamFlow();\n\telse\n\t\t\/\/ Calculate drag force for turbulent flow\n\t\tDragTurbFlow();\n\n}\n\nvoid ParticleModel::DragLamFlow()\n{\n\t\/\/ Calculate of x- and y-components of drag force\n\tdragForce.x = -dragFactor * _velocity.x;\n\tdragForce.y = -dragFactor * _velocity.y;\n\tdragForce.z = -dragFactor * _velocity.z;\n}\n\nvoid ParticleModel::DragTurbFlow()\n{\n\t\/\/ Calculate magnitude of velocity\n\tfloat velMag;\n\tvelMag = sqrt((_velocity.x * _velocity.x) + (_velocity.y * _velocity.y) + (_velocity.z * _velocity.z));\n\n\t\/\/ Calculate unit vector\/normalised vector of velocity\n\tXMFLOAT3 unitVel;\n\tunitVel.x = (_velocity.x \/ velMag);\n\tunitVel.y = (_velocity.y \/ velMag);\n\tunitVel.z = (_velocity.z \/ velMag);\n\n\t\/\/ Calculate magnitude of drag force\n\tfloat dragMag;\n\tdragMag = dragFactor * velMag * velMag;\n\n\t\/\/ Calculate of x- and y-components of drag force\n\tdragForce.x = -dragMag * unitVel.x;\n\tdragForce.y = -dragMag * unitVel.y;\n\tdragForce.z = -dragMag * unitVel.z;\n\n}\n\nbool ParticleModel::CheckCollision(XMFLOAT3 position2, float radius2)\n{\n\tXMFLOAT3 position = _transform->GetPosition();\n\n\tXMFLOAT3 difference;\n\tdifference.x = position.x - position2.x;\n\tdifference.y = position.y - position2.y;\n\tdifference.z = position.z - position2.z;\n\n\tfloat differenceMag = sqrt((difference.x * difference.x) + (difference.y * difference.y) + (difference.z * difference.z));\n\n\tfloat rDistance = _radius + radius2;\n\n\tif (differenceMag <= rDistance)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\nvoid ParticleModel::CheckFloorCollision(XMFLOAT3 floorPos)\n{\n\tXMFLOAT3 objectPosition = _transform->GetPosition();\n\n\tXMFLOAT3 difference;\n\tdifference.y = objectPosition.y - floorPos.y;\n\n\tfloat differenceMag = sqrt(difference.y * difference.y);\n\n\tif (differenceMag <= _radius)\n\t{\n\t\tslideOn = true;\n\t\t_velocity.y = -_velocity.y;\n\t}\n\telse\n\t{\n\t\tslideOn = false;\n\t}\n}\n\nvoid ParticleModel::ResolveCollision(ParticleModel* particleModel1, ParticleModel* particleModel2)\n{\n\tfloat rCoef = 0.8f;\n\n\tXMFLOAT3 prevPos1 = particleModel1->_transform->GetOldPosition();\n\tXMFLOAT3 prevPos2 = particleModel2->_transform->GetOldPosition();\n\n\tfloat mass1 = particleModel1->GetMass();\n\tfloat mass2 = particleModel2->GetMass();\n\n\tXMFLOAT3 initialVelocity1 = particleModel1->GetVelocity();\n\tXMFLOAT3 initialVelocity2 = particleModel2->GetVelocity();\n\n\tparticleModel1->_transform->SetPosition(prevPos1);\n\tparticleModel2->_transform->SetPosition(prevPos2);\n\n\tXMFLOAT3 velocity1;\n\tXMFLOAT3 velocity2;\n\n\tvelocity1.x = (mass1 * initialVelocity1.x) + (mass2 * initialVelocity2.x) + ((mass2 * rCoef) * (initialVelocity2.x - initialVelocity1.x)) \/ (mass1 + mass2);\n\tvelocity1.y = (mass1 * initialVelocity1.y) + (mass2 * initialVelocity2.y) + ((mass2 * rCoef) * (initialVelocity2.y - initialVelocity1.y)) \/ (mass1 + mass2);\n\tvelocity1.z = (mass1 * initialVelocity1.z) + (mass2 * initialVelocity2.z) + ((mass2 * rCoef) * (initialVelocity2.z - initialVelocity1.z)) \/ (mass1 + mass2);\n\n\tvelocity2.x = (mass1 * initialVelocity1.x) + (mass2 * initialVelocity2.x) + ((mass1 * rCoef) * (initialVelocity1.x - initialVelocity2.x)) \/ (mass1 + mass2);\n\tvelocity2.y = (mass1 * initialVelocity1.y) + (mass2 * initialVelocity2.y) + ((mass1 * rCoef) * (initialVelocity1.y - initialVelocity2.y)) \/ (mass1 + mass2);\n\tvelocity2.z = (mass1 * initialVelocity1.z) + (mass2 * initialVelocity2.z) + ((mass1 * rCoef) * (initialVelocity1.z - initialVelocity2.z)) \/ (mass1 + mass2);\n\t\n\tparticleModel1->SetVelocity(velocity1);\n\tparticleModel2->SetVelocity(velocity2);\n} <|endoftext|>"} {"text":"#ifndef RESOLVER_PIXEL_SORTER_HPP\n#define RESOLVER_PIXEL_SORTER_HPP\n\n#include \"data_type.hpp\"\n#include \"splitter.hpp\"\n\ntemplate\nclass pixel_sorter\n{\npublic:\n \/\/ 座標(j,i)と座標(l,k)の比較結果としては,compared_type[i][j][k][l]にtuple<上,右,下,左>で入る\n \/\/ compared_typeより,一番距離が近い断片画像をadjacent_typeに整理する\n typedef std::vector>>>> compared_type;\n typedef std::vector>> adjacent_type;\n typedef std::vector> return_type;\n\n pixel_sorter() : split_(){}\n virtual ~pixel_sorter() = default;\n\n return_type operator() (question_raw_data const& raw) const\n {\n auto const& proposed = proposed_answer(raw);\n\n \/\/ TODO: ここで返却されたデータのうち,適しているものを選択してreturn\n \n return proposed[0];\n }\n\n std::vector proposed_answer(question_raw_data const& raw) const\n {\n \/\/\n \/\/ Sub Algorithm\n \/\/ 正しい位置に並べた時に左上から,1~nまでの番号をふり,それが今どこにあるのかという情報をreturn\n \/\/\n\n split_image_type const& splited_image = split_.split_image(raw);\n compared_type const& comp = this->image_comp(splited_image);\n\n Algorithm algo(raw, comp);\n auto const& proposed = algo();\n\n return proposed;\n }\n\nprivate:\n \/\/2つのピクセル間の距離を2乗した値を返却.result = r^2 + g^2 + b^2\n int pixel_comparison(pixel_type const& lhs, pixel_type const& rhs) const\n {\n int s = 0;\n for(int i=0; i<3; ++i) s += static_cast(std::pow(std::abs(lhs[i] - rhs[i]), 2));\n return s;\n }\n\n \/\/2つのピクセル列を比較した値を返す\n int pixel_line_comparison(image_type const& lhs, image_type const& rhs) const\n {\n auto lhs_it = lhs.begin(), lhs_end = lhs.end();\n auto rhs_it = rhs.begin(), rhs_end = rhs.end();\n\n int s = 0;\n for(; lhs_it != lhs_end && rhs_it != rhs_end; ++lhs_it, ++rhs_it)\n {\n s += pixel_comparison(*lhs_it, *rhs_it);\n }\n return s;\n }\n\n \/\/一枚目の右端と二枚目の左端を見る関数, 一致が多いほど低いを返す\n uint64_t rl_comparison(image_type const& lhs, image_type const& rhs) const\n {\n return pixel_line_comparison(lhs.col(lhs.cols - 1), rhs.col(0));\n }\n\n \/\/一枚目の左端と二枚目の右端を見る関数, 一致が多いほど低いを返す\n uint64_t lr_comparison(image_type const& lhs, image_type const& rhs) const\n {\n return pixel_line_comparison(lhs.col(0), rhs.col(rhs.cols - 1));\n }\n\n \/\/一枚目の上端と二枚目の下端を見る関数, 一致が多いほど低いを返す\n uint64_t ud_comparison(image_type const& lhs, image_type const& rhs) const\n {\n return pixel_line_comparison(lhs.row(0), rhs.row(rhs.rows - 1));\n }\n\n \/\/一枚目の下端と二枚目の上端を見る関数, 一致が多いほど低いを返す\n uint64_t du_comparison(image_type const& lhs, image_type const& rhs) const\n {\n return pixel_line_comparison(lhs.row(rhs.rows - 1), rhs.row(0));\n }\n\n compared_type image_comp(split_image_type const& image) const\n {\n \/\/返却用変数\n \/\/\"最大距離が収納されたtuple\"の4次元配列になる\n compared_type comp(\n image.size(),\n std::vector>>>(\n image[0].size(),\n std::vector>>(\n image.size(),\n std::vector>(\n image[0].size(),\n {\n std::numeric_limits::max(),\n std::numeric_limits::max(),\n std::numeric_limits::max(),\n std::numeric_limits::max()\n })\n )\n )\n );\n\n for(int i=0; i i || (k == i && l > j)) \/\/ (j,i)より(l,k)の方が,探索順として後半に或るための条件\n {\n \/\/順序を変えて逆の逆の組み合わせの相対評価は同じであることを使用して探索量を半分にする\n \/\/例えば,Aから見たBは上なら,Bから見たAは下.\n comp[i][j][k][l].up = comp[k][l][i][j].down = ud_comparison(image[i][j], image[k][l]);\n comp[i][j][k][l].right = comp[k][l][i][j].left = rl_comparison(image[i][j], image[k][l]);\n comp[i][j][k][l].down = comp[k][l][i][j].up = du_comparison(image[i][j], image[k][l]);\n comp[i][j][k][l].left = comp[k][l][i][j].right = lr_comparison(image[i][j], image[k][l]);\n }\n }\n }\n return comp;\n }\n\n splitter const split_;\n};\n\n#endif\nyrange2が答え返せなかった時の処理追加 pixcel_sorterとmainに書いたけどyrange2専用#ifndef RESOLVER_PIXEL_SORTER_HPP\n#define RESOLVER_PIXEL_SORTER_HPP\n\n#include \"data_type.hpp\"\n#include \"splitter.hpp\"\n\ntemplate\nclass pixel_sorter\n{\npublic:\n \/\/ 座標(j,i)と座標(l,k)の比較結果としては,compared_type[i][j][k][l]にtuple<上,右,下,左>で入る\n \/\/ compared_typeより,一番距離が近い断片画像をadjacent_typeに整理する\n typedef std::vector>>>> compared_type;\n typedef std::vector>> adjacent_type;\n typedef std::vector> return_type;\n\n pixel_sorter() : split_(){}\n virtual ~pixel_sorter() = default;\n\n return_type operator() (question_raw_data const& raw) const\n {\n auto const& proposed = proposed_answer(raw);\n\n \/\/ TODO: ここで返却されたデータのうち,適しているものを選択してreturn\n\n\t\tif (proposed.size() == 0) return std::vector < std::vector > {};\n\t\telse return proposed[0];\n }\n\n std::vector proposed_answer(question_raw_data const& raw) const\n {\n \/\/\n \/\/ Sub Algorithm\n \/\/ 正しい位置に並べた時に左上から,1~nまでの番号をふり,それが今どこにあるのかという情報をreturn\n \/\/\n\n split_image_type const& splited_image = split_.split_image(raw);\n compared_type const& comp = this->image_comp(raw,splited_image);\n\n Algorithm algo(raw, comp);\n auto const& proposed = algo();\n\n return proposed;\n }\n\nprivate:\n \/\/2つのピクセル間の距離を2乗した値を返却.result = r^2 + g^2 + b^2\n int pixel_comparison(pixel_type const& lhs, pixel_type const& rhs) const\n {\n int s = 0;\n for(int i=0; i<3; ++i) s += static_cast(std::pow(std::abs(lhs[i] - rhs[i]), 2));\n return s;\n }\n\n \/\/2つのピクセル列を比較した値を返す\n int pixel_line_comparison(image_type const& lhs, image_type const& rhs) const\n {\n auto lhs_it = lhs.begin(), lhs_end = lhs.end();\n auto rhs_it = rhs.begin(), rhs_end = rhs.end();\n\n int s = 0;\n for(; lhs_it != lhs_end && rhs_it != rhs_end; ++lhs_it, ++rhs_it)\n {\n s += pixel_comparison(*lhs_it, *rhs_it);\n }\n return s;\n }\n\n \/\/一枚目の右端と二枚目の左端を見る関数, 一致が多いほど低いを返す\n uint64_t rl_comparison(image_type const& lhs, image_type const& rhs) const\n {\n return pixel_line_comparison(lhs.col(lhs.cols - 1), rhs.col(0));\n }\n\n \/\/一枚目の左端と二枚目の右端を見る関数, 一致が多いほど低いを返す\n uint64_t lr_comparison(image_type const& lhs, image_type const& rhs) const\n {\n return pixel_line_comparison(lhs.col(0), rhs.col(rhs.cols - 1));\n }\n\n \/\/一枚目の上端と二枚目の下端を見る関数, 一致が多いほど低いを返す\n uint64_t ud_comparison(image_type const& lhs, image_type const& rhs) const\n {\n return pixel_line_comparison(lhs.row(0), rhs.row(rhs.rows - 1));\n }\n\n \/\/一枚目の下端と二枚目の上端を見る関数, 一致が多いほど低いを返す\n uint64_t du_comparison(image_type const& lhs, image_type const& rhs) const\n {\n return pixel_line_comparison(lhs.row(rhs.rows - 1), rhs.row(0));\n }\n\n\t\/*一枚目の右端と二枚目の左端を見る関数 一致が多いほど低いを返す*\/\n\tuint64_t rl_comparison(cv::Mat file1, cv::Mat file2)\n\t{\n\t\tuint64_t s = 0;\n\t\tfor (int i = 0; i < file1.rows; i++) {\/\/縦ピクセル数ループ\n\t\t\tfor (int c = 0; c < file1.channels(); ++c){\/\/ 画像のチャネル数分だけループ。白黒の場合は1回、カラーの場合は3回\n\t\t\t\ts += abs((file1.data[file1.step * (i + 1) - file1.channels() + c]) - (file2.data[file2.step * i + c]));\n\t\t\t}\n\t\t}\n\t\treturn s;\n\t}\n\n\t\/*一枚目の左端と二枚目の右端を見る関数 一致が多いほど低いを返す*\/\n\tuint64_t lr_comparison(cv::Mat file1, cv::Mat file2)\n\t{\n\t\tuint64_t s = 0;\n\t\tfor (int i = 0; i < file1.rows; i++) {\/\/縦ピクセル数ループ\n\t\t\tfor (int c = 0; c < file1.channels(); ++c){\/\/ 画像のチャネル数分だけループ。白黒の場合は1回、カラーの場合は3回\n\t\t\t\ts += abs((file1.data[file1.step * i + c]) - (file2.data[file2.step * (i + 1) - file1.channels() + c]));\n\n\t\t\t}\n\t\t}\n\t\treturn s;\n\t}\n\n\t\/*一枚目の上端と二枚目の下端を見る関数 一致が多いほど低いを返す*\/\n\tuint64_t ud_comparison(cv::Mat file1, cv::Mat file2)\n\t{\n\t\tuint64_t s = 0;\n\t\tfor (unsigned int i = 0; i < file1.step; i++) {\/\/横ピクセル数ループ\n\t\t\ts += abs((file1.data[i]) - (file2.data[(file2.rows - 1)* file2.step + i]));\n\t\t}\n\t\treturn s;\n\t}\n\n\t\/*一枚目の下端と二枚目の上端を見る関数 一致が多いほど低いを返す*\/\n\tuint64_t du_comparison(cv::Mat file1, cv::Mat file2)\n\t{\n\t\tuint64_t s = 0;\n\t\tfor (unsigned int i = 0; i < file1.step; i++) {\/\/横ピクセル数ループ\n\t\t\ts += abs((file1.data[(file2.rows - 1)*file2.step + i]) - (file2.data[i]));\n\t\t}\n\t\treturn s;\n\t}\n\n compared_type image_comp(question_raw_data const& data_,split_image_type const& image) const\n {\n \/\/返却用変数\n \/\/\"最大距離が収納されたtuple\"の4次元配列になる\n compared_type comp(\n image.size(),\n std::vector>>>(\n image[0].size(),\n std::vector>>(\n image.size(),\n std::vector>(\n image[0].size(),\n {\n std::numeric_limits::max(),\n std::numeric_limits::max(),\n std::numeric_limits::max(),\n std::numeric_limits::max()\n })\n )\n )\n );\n\t\t\n\t\tsplitter sp;\n\t\tsplit_image_type splited = sp.split_image(data_);\n\t\t\t\t\n for(int i=0; i i || (k == i && l > j)) \/\/ (j,i)より(l,k)の方が,探索順として後半に或るための条件\n {\n \/\/順序を変えて逆の逆の組み合わせの相対評価は同じであることを使用して探索量を半分にする\n \/\/例えば,Aから見たBは上なら,Bから見たAは下.\n\t\t\t\t\t\/*\n comp[i][j][k][l].up = comp[k][l][i][j].down = ud_comparison(image[i][j], image[k][l]);\n comp[i][j][k][l].right = comp[k][l][i][j].left = rl_comparison(image[i][j], image[k][l]);\n comp[i][j][k][l].down = comp[k][l][i][j].up = du_comparison(image[i][j], image[k][l]);\n comp[i][j][k][l].left = comp[k][l][i][j].right = lr_comparison(image[i][j], image[k][l]);\n\t\t\t\t\t*\/\n\n\t\t\t\t\tcomp[i][j][k][l].up = comp[k][l][i][j].down = ud_comparison(splited[i][j], splited[k][l]);\n\t\t\t\t\tcomp[i][j][k][l].right = comp[k][l][i][j].left = rl_comparison(splited[i][j], splited[k][l]);\n\t\t\t\t\tcomp[i][j][k][l].down = comp[k][l][i][j].up = du_comparison(splited[i][j], splited[k][l]);\n\t\t\t\t\tcomp[i][j][k][l].left = comp[k][l][i][j].right = lr_comparison(splited[i][j], splited[k][l]);\n\n }\n }\n }\n return comp;\n }\n\n splitter const split_;\n};\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * integer.cpp\n *\/\n#include \"integer.h\"\n\nnamespace c8 {\n \/*\n * Construct an integer using a string.\n *\n * The string can have an optional '-' sign to indicate that it's negative,\n * and then the usual C++-like hex, octal, * or decimal representations.\n *\/\n integer::integer(const std::string &v) {\n negative_ = false;\n\n \/*\n * Does our integer have a '-' sign?\n *\/\n if (v.length()) {\n if (v[0] == '-') {\n negative_ = true;\n }\n }\n\n magnitude_ = natural(negative_ ? v.substr(1) : v);\n }\n\n \/*\n * Add another integer to this one.\n *\/\n auto integer::operator +(const integer &v) const -> integer {\n integer res;\n\n \/*\n * If our two numbers have the same sign then we just add and retain the\n * sign for this number.\n *\/\n if (negative_ == v.negative_) {\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ + v.magnitude_;\n return res;\n }\n\n \/*\n * If we are adding a larger magnitude value then subtract the smaller\n * from the larger, and retain the sign of the larger.\n *\/\n if (magnitude_ < v.magnitude_) {\n res.negative_ = v.negative_;\n res.magnitude_ = v.magnitude_ - magnitude_;\n return res;\n }\n\n \/*\n * We're adding a smaller magnitude value, so subtract the smaller\n * from the larger, and, again, retain the sign of the larger.\n *\/\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ - v.magnitude_;\n return res;\n }\n\n \/*\n * Subtract another integer from this one.\n *\n * Note that there is a subtle difference between the integer subtract operation\n * and the natural number version: We don't have to worry about throwing\n * exceptions for negative results.\n *\/\n auto integer::operator -(const integer &v) const -> integer {\n integer res;\n\n \/*\n * If we're subtracting a negative number from a positive, or a positive from\n * a negative, then we add the magnitudes of both and retain the sign of this one.\n *\/\n if (negative_ != v.negative_) {\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ + v.magnitude_;\n return res;\n }\n\n \/*\n * If we're subtracting a number that has a larger magnitude than this one, then\n * subtract the magnitudes and use the inverse of the sign for the larger.\n *\/\n if (magnitude_ < v.magnitude_) {\n res.negative_ = !v.negative_;\n res.magnitude_ = v.magnitude_ - magnitude_;\n return res;\n }\n\n \/*\n * We're subtracting a number with a smaller magnitude than this one, so subtract\n * the magnitudes and use the sign of this one.\n *\/\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ - v.magnitude_;\n return res;\n }\n\n \/*\n * Left shift this integer by a number of bits.\n *\/\n auto integer::operator <<(unsigned int count) const -> integer {\n integer res;\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ << count;\n return res;\n }\n\n \/*\n * Right shift this integer by a number of bits.\n *\/\n auto integer::operator >>(unsigned int count) const -> integer {\n integer res;\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ >> count;\n return res;\n }\n\n \/*\n * Multiply another integer with this one.\n *\/\n auto integer::operator *(const integer &v) const -> integer {\n integer res;\n res.negative_ = negative_ ^ v.negative_;\n res.magnitude_ = magnitude_ * v.magnitude_;\n return res;\n }\n\n \/*\n * Divide this integer by another one, returning the quotient and remainder.\n *\/\n auto integer::divide_modulus(const integer &v) const -> std::pair {\n std::pair dm = magnitude_.divide_modulus(v.magnitude_);\n\n std::pair res;\n res.first.negative_ = negative_ ^ v.negative_;\n res.first.magnitude_ = std::move(dm.first);\n res.second.magnitude_ = std::move(dm.second);\n\n return res;\n }\n\n \/*\n * Divide this integer by another one, returning the quotient.\n *\/\n auto integer::operator \/(const integer &v) const -> integer {\n integer res;\n res.negative_ = negative_ ^ v.negative_;\n res.magnitude_ = magnitude_ \/ v.magnitude_;\n return res;\n }\n\n \/*\n * Divide this integer by another one, returning the remainder.\n *\/\n auto integer::operator %(const integer &v) const -> integer {\n integer res;\n res.negative_ = negative_ ^ v.negative_;\n res.magnitude_ = magnitude_ % v.magnitude_;\n return res;\n }\n\n \/*\n * Compare a integer with this one.\n *\/\n auto integer::compare(const integer &v) const -> comparison {\n \/*\n * Is this number non-negative?\n *\/\n if (!negative_) {\n \/*\n * If the number we're comparing with is non-negative too then we can\n * just do a simple comparison of the magnitudes.\n *\/\n if (!v.negative_) {\n return magnitude_.compare(v.magnitude_);\n }\n\n \/*\n * The number we're comparing with is negative so we're definitely greater\n * than it.\n *\/\n return comparison::gt;\n }\n\n \/*\n * This integer is negative, so if the number we're comparing with is also\n * negative then we compare magnitudes, but we reverse the result. The most\n * negative value is smaller, not larger.\n *\/\n if (v.negative_) {\n auto ures = magnitude_.compare(v.magnitude_);\n switch (ures) {\n case comparison::lt:\n return comparison::gt;\n\n case comparison::eq:\n return comparison::eq;\n\n case comparison::gt:\n return comparison::lt;\n }\n }\n\n \/*\n * This integer is negative, but the one we're comparing with is not, so we're\n * smaller.\n *\/\n return comparison::lt;\n }\n\n \/*\n * Convert this integer to a long long.\n *\/\n auto integer::to_long_long() const -> long long {\n \/*\n * Will this number fit in a long long? If not then throw an exception.\n *\/\n if (magnitude_.count_bits() > ((8 * sizeof(long long)) - 1)) {\n throw overflow_error();\n }\n\n \/*\n * Convert the result, and, if necessary, flip the sign.\n *\/\n long long res = static_cast(to_unsigned_long_long(magnitude_));\n\n if (negative_) {\n res = -res;\n }\n\n return res;\n }\n\n \/*\n * << operator to print a integer.\n *\/\n auto operator <<(std::ostream &outstr, const integer &v) -> std::ostream & {\n if (v.negative_) {\n outstr << '-';\n }\n\n outstr << v.magnitude_;\n\n return outstr;\n }\n}\n\nFix % operator\/*\n * integer.cpp\n *\/\n#include \"integer.h\"\n\nnamespace c8 {\n \/*\n * Construct an integer using a string.\n *\n * The string can have an optional '-' sign to indicate that it's negative,\n * and then the usual C++-like hex, octal, * or decimal representations.\n *\/\n integer::integer(const std::string &v) {\n negative_ = false;\n\n \/*\n * Does our integer have a '-' sign?\n *\/\n if (v.length()) {\n if (v[0] == '-') {\n negative_ = true;\n }\n }\n\n magnitude_ = natural(negative_ ? v.substr(1) : v);\n }\n\n \/*\n * Add another integer to this one.\n *\/\n auto integer::operator +(const integer &v) const -> integer {\n integer res;\n\n \/*\n * If our two numbers have the same sign then we just add and retain the\n * sign for this number.\n *\/\n if (negative_ == v.negative_) {\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ + v.magnitude_;\n return res;\n }\n\n \/*\n * If we are adding a larger magnitude value then subtract the smaller\n * from the larger, and retain the sign of the larger.\n *\/\n if (magnitude_ < v.magnitude_) {\n res.negative_ = v.negative_;\n res.magnitude_ = v.magnitude_ - magnitude_;\n return res;\n }\n\n \/*\n * We're adding a smaller magnitude value, so subtract the smaller\n * from the larger, and, again, retain the sign of the larger.\n *\/\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ - v.magnitude_;\n return res;\n }\n\n \/*\n * Subtract another integer from this one.\n *\n * Note that there is a subtle difference between the integer subtract operation\n * and the natural number version: We don't have to worry about throwing\n * exceptions for negative results.\n *\/\n auto integer::operator -(const integer &v) const -> integer {\n integer res;\n\n \/*\n * If we're subtracting a negative number from a positive, or a positive from\n * a negative, then we add the magnitudes of both and retain the sign of this one.\n *\/\n if (negative_ != v.negative_) {\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ + v.magnitude_;\n return res;\n }\n\n \/*\n * If we're subtracting a number that has a larger magnitude than this one, then\n * subtract the magnitudes and use the inverse of the sign for the larger.\n *\/\n if (magnitude_ < v.magnitude_) {\n res.negative_ = !v.negative_;\n res.magnitude_ = v.magnitude_ - magnitude_;\n return res;\n }\n\n \/*\n * We're subtracting a number with a smaller magnitude than this one, so subtract\n * the magnitudes and use the sign of this one.\n *\/\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ - v.magnitude_;\n return res;\n }\n\n \/*\n * Left shift this integer by a number of bits.\n *\/\n auto integer::operator <<(unsigned int count) const -> integer {\n integer res;\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ << count;\n return res;\n }\n\n \/*\n * Right shift this integer by a number of bits.\n *\/\n auto integer::operator >>(unsigned int count) const -> integer {\n integer res;\n res.negative_ = negative_;\n res.magnitude_ = magnitude_ >> count;\n return res;\n }\n\n \/*\n * Multiply another integer with this one.\n *\/\n auto integer::operator *(const integer &v) const -> integer {\n integer res;\n res.negative_ = negative_ ^ v.negative_;\n res.magnitude_ = magnitude_ * v.magnitude_;\n return res;\n }\n\n \/*\n * Divide this integer by another one, returning the quotient and remainder.\n *\/\n auto integer::divide_modulus(const integer &v) const -> std::pair {\n std::pair dm = magnitude_.divide_modulus(v.magnitude_);\n\n std::pair res;\n res.first.negative_ = negative_ ^ v.negative_;\n res.first.magnitude_ = std::move(dm.first);\n res.second.magnitude_ = std::move(dm.second);\n\n return res;\n }\n\n \/*\n * Divide this integer by another one, returning the quotient.\n *\/\n auto integer::operator \/(const integer &v) const -> integer {\n integer res;\n res.negative_ = negative_ ^ v.negative_;\n res.magnitude_ = magnitude_ \/ v.magnitude_;\n return res;\n }\n\n \/*\n * Divide this integer by another one, returning the remainder.\n *\/\n auto integer::operator %(const integer &v) const -> integer {\n integer res;\n res.magnitude_ = magnitude_ % v.magnitude_;\n return res;\n }\n\n \/*\n * Compare a integer with this one.\n *\/\n auto integer::compare(const integer &v) const -> comparison {\n \/*\n * Is this number non-negative?\n *\/\n if (!negative_) {\n \/*\n * If the number we're comparing with is non-negative too then we can\n * just do a simple comparison of the magnitudes.\n *\/\n if (!v.negative_) {\n return magnitude_.compare(v.magnitude_);\n }\n\n \/*\n * The number we're comparing with is negative so we're definitely greater\n * than it.\n *\/\n return comparison::gt;\n }\n\n \/*\n * This integer is negative, so if the number we're comparing with is also\n * negative then we compare magnitudes, but we reverse the result. The most\n * negative value is smaller, not larger.\n *\/\n if (v.negative_) {\n auto ures = magnitude_.compare(v.magnitude_);\n switch (ures) {\n case comparison::lt:\n return comparison::gt;\n\n case comparison::eq:\n return comparison::eq;\n\n case comparison::gt:\n return comparison::lt;\n }\n }\n\n \/*\n * This integer is negative, but the one we're comparing with is not, so we're\n * smaller.\n *\/\n return comparison::lt;\n }\n\n \/*\n * Convert this integer to a long long.\n *\/\n auto integer::to_long_long() const -> long long {\n \/*\n * Will this number fit in a long long? If not then throw an exception.\n *\/\n if (magnitude_.count_bits() > ((8 * sizeof(long long)) - 1)) {\n throw overflow_error();\n }\n\n \/*\n * Convert the result, and, if necessary, flip the sign.\n *\/\n long long res = static_cast(to_unsigned_long_long(magnitude_));\n\n if (negative_) {\n res = -res;\n }\n\n return res;\n }\n\n \/*\n * << operator to print a integer.\n *\/\n auto operator <<(std::ostream &outstr, const integer &v) -> std::ostream & {\n if (v.negative_) {\n outstr << '-';\n }\n\n outstr << v.magnitude_;\n\n return outstr;\n }\n}\n\n<|endoftext|>"} {"text":"#include \"kulma\/io\/file.h\"\n\n#include \"kulma\/platform.h\"\n#if KULMA_PLATFORM_WINDOWS\n# ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n# endif\n# include \n#elif KULMA_PLATFORM_LINUX\n\n#endif\n\nnamespace kulma\n{\n FileReader::FileReader()\n#if KULMA_PLATFORM_WINDOWS\n : m_file(INVALID_HANDLE_VALUE)\n#elif KULMA_PLATFORM_LINUX\n : m_file(NULL)\n#endif\n {\n\n }\n\n FileReader::~FileReader()\n {\n\n }\n\n int32_t FileReader::read(void * p_data, int32_t p_size, Error * p_err)\n {\n KULMA_ASSERT(p_err != NULL, \"Reading interface error handler can't be null\");\n\n#if KULMA_PLATFORM_WINDOWS\n DWORD read = 0;\n if (::ReadFile(m_file, p_data, p_size, &read, NULL) == FALSE)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_READ,\n \"FileReader: read failed\");\n }\n else if ((int32_t)read != p_size)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_READ,\n \"FileReader: read failed\");\n }\n return (int32_t)read;\n#elif KULMA_PLATFORM_LINUX\n int32_t size = (int32_t)fread(p_data, 1, p_size, m_file);\n if (size != p_size)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_READ,\n \"FileReader: read failed\");\n return size >= 0 ? size : 0;\n }\n return size;\n#endif\n }\n\n int64_t FileReader::seek(int64_t p_offset, Whence::Enum p_whence)\n {\n#if KULMA_PLATFORM_WINDOWS\n LARGE_INTEGER li;\n\n li.QuadPart = p_offset;\n\n li.LowPart = ::SetFilePointer(m_file,\n li.LowPart,\n &li.HighPart,\n p_whence);\n\n KULMA_ASSERT(li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR,\n \"SetFilePointer failed, GetLastError = %d\",\n GetLastError()\n );\n\n return li.QuadPart;\n\n#elif KULMA_PLATFORM_LINUX\n fseeko64(m_file, p_offset, p_whence);\n return ftello64(m_file);\n#endif\n }\n\n bool FileReader::open(const char * p_filePath, Error * p_err)\n {\n KULMA_ASSERT(p_err != NULL, \"Reading interface error handler can't be null\");\n\n#if KULMA_PLATFORM_WINDOWS\n m_file = ::CreateFile(\n p_filePath,\n GENERIC_READ,\n 0,\n NULL,\n OPEN_ALWAYS,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n\n if (m_file == INVALID_HANDLE_VALUE)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_OPEN,\n \"FileReader: failed to open file\");\n return false;\n }\n#elif KULMA_PLATFORM_LINUX\n m_file = ::fopen(p_filePath, \"rb\");\n\n if (m_file == NULL)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_OPEN,\n \"FileReader: failed to open file\");\n return false;\n }\n#endif\n \n return true;\n }\n\n void FileReader::close()\n {\n#if KULMA_PLATFORM_WINDOWS\n if (m_file != INVALID_HANDLE_VALUE)\n {\n ::CloseHandle(m_file);\n m_file = INVALID_HANDLE_VALUE;\n }\n#elif KULMA_PLATFORM_LINUX\n if (m_file != NULL)\n {\n ::fclose(m_file);\n m_file = NULL;\n }\n#endif\n }\n\n FileWriter::FileWriter()\n#if KULMA_PLATFORM_WINDOWS\n : m_file(INVALID_HANDLE_VALUE)\n#elif KULMA_PLATFORM_LINUX\n : m_file(NULL)\n#endif\n {\n\n }\n\n FileWriter::~FileWriter()\n {\n\n }\n\n int32_t FileWriter::write(const void* p_data, int32_t p_size, Error* p_err)\n {\n KULMA_UNUSED(p_data, p_size, p_err);\n return 0;\n }\n\n int64_t FileWriter::seek(int64_t p_offset, Whence::Enum p_whence)\n {\n KULMA_UNUSED(p_offset, p_whence);\n return 0;\n }\n\n bool FileWriter::open(const char* p_filePath, bool p_append, Error* p_err)\n {\n KULMA_UNUSED(p_filePath, p_append, p_err);\n return false;\n }\n\n void FileWriter::close()\n {\n\n }\n}Open file for writing#include \"kulma\/io\/file.h\"\n\n#include \"kulma\/platform.h\"\n#if KULMA_PLATFORM_WINDOWS\n# ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n# endif\n# include \n#elif KULMA_PLATFORM_LINUX\n\n#endif\n\nnamespace kulma\n{\n FileReader::FileReader()\n#if KULMA_PLATFORM_WINDOWS\n : m_file(INVALID_HANDLE_VALUE)\n#elif KULMA_PLATFORM_LINUX\n : m_file(NULL)\n#endif\n {\n\n }\n\n FileReader::~FileReader()\n {\n\n }\n\n int32_t FileReader::read(void * p_data, int32_t p_size, Error * p_err)\n {\n KULMA_ASSERT(p_err != NULL, \"Reading interface error handler can't be null\");\n\n#if KULMA_PLATFORM_WINDOWS\n DWORD read = 0;\n if (::ReadFile(m_file, p_data, p_size, &read, NULL) == FALSE)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_READ,\n \"FileReader: read failed\");\n }\n else if ((int32_t)read != p_size)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_READ,\n \"FileReader: read failed\");\n }\n return (int32_t)read;\n#elif KULMA_PLATFORM_LINUX\n int32_t size = (int32_t)fread(p_data, 1, p_size, m_file);\n if (size != p_size)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_READ,\n \"FileReader: read failed\");\n return size >= 0 ? size : 0;\n }\n return size;\n#endif\n }\n\n int64_t FileReader::seek(int64_t p_offset, Whence::Enum p_whence)\n {\n#if KULMA_PLATFORM_WINDOWS\n LARGE_INTEGER li;\n\n li.QuadPart = p_offset;\n\n li.LowPart = ::SetFilePointer(m_file,\n li.LowPart,\n &li.HighPart,\n p_whence);\n\n KULMA_ASSERT(li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR,\n \"SetFilePointer failed, GetLastError = %d\",\n GetLastError()\n );\n\n return li.QuadPart;\n\n#elif KULMA_PLATFORM_LINUX\n fseeko64(m_file, p_offset, p_whence);\n return ftello64(m_file);\n#endif\n }\n\n bool FileReader::open(const char * p_filePath, Error * p_err)\n {\n KULMA_ASSERT(p_err != NULL, \"Reading interface error handler can't be null\");\n\n#if KULMA_PLATFORM_WINDOWS\n m_file = ::CreateFileA(\n p_filePath,\n GENERIC_READ,\n 0,\n NULL,\n OPEN_ALWAYS,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n\n if (m_file == INVALID_HANDLE_VALUE)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_OPEN,\n \"FileReader: failed to open file\");\n return false;\n }\n#elif KULMA_PLATFORM_LINUX\n m_file = ::fopen(p_filePath, \"rb\");\n\n if (m_file == NULL)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_OPEN,\n \"FileReader: failed to open file\");\n return false;\n }\n#endif\n \n return true;\n }\n\n void FileReader::close()\n {\n#if KULMA_PLATFORM_WINDOWS\n if (m_file != INVALID_HANDLE_VALUE)\n {\n ::CloseHandle(m_file);\n m_file = INVALID_HANDLE_VALUE;\n }\n#elif KULMA_PLATFORM_LINUX\n if (m_file != NULL)\n {\n ::fclose(m_file);\n m_file = NULL;\n }\n#endif\n }\n\n FileWriter::FileWriter()\n#if KULMA_PLATFORM_WINDOWS\n : m_file(INVALID_HANDLE_VALUE)\n#elif KULMA_PLATFORM_LINUX\n : m_file(NULL)\n#endif\n {\n\n }\n\n FileWriter::~FileWriter()\n {\n\n }\n\n int32_t FileWriter::write(const void* p_data, int32_t p_size, Error* p_err)\n {\n KULMA_UNUSED(p_data, p_size, p_err);\n return 0;\n }\n\n int64_t FileWriter::seek(int64_t p_offset, Whence::Enum p_whence)\n {\n KULMA_UNUSED(p_offset, p_whence);\n return 0;\n }\n\n bool FileWriter::open(const char* p_filePath, bool p_append, Error* p_err)\n {\n#if KULMA_PLATFORM_WINDOWS\n m_file = ::CreateFileA(p_filePath,\n GENERIC_WRITE,\n 0,\n NULL,\n p_append ? OPEN_ALWAYS : CREATE_ALWAYS, \/\/ truncate if necessary\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n\n if (m_file == INVALID_HANDLE_VALUE)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_OPEN,\n \"FileWriter: failed to open file\");\n return false;\n }\n\n if (p_append) \n {\n \/\/ move the cursor to the eof\n DWORD err = ::SetFilePointer(m_file, 0, NULL, FILE_END);\n if (err == INVALID_SET_FILE_POINTER)\n {\n KULMA_ERROR_SET(p_err,\n KULMA_ERROR_IO_OPEN,\n \"FileWriter: faled to open file, SetFilePointer failed\");\n return false;\n }\n }\n#elif KULMA_PLATFORM_LINUX\n#endif\n\n return true;\n }\n\n void FileWriter::close()\n {\n#if KULMA_PLATFORM_WINDOWS\n if (m_file != INVALID_HANDLE_VALUE)\n {\n ::CloseHandle(m_file);\n m_file = INVALID_HANDLE_VALUE;\n }\n#elif KULMA_PLATFORM_LINUX\n if (m_file != NULL)\n {\n ::fclose(m_file);\n m_file = NULL;\n }\n#endif\n }\n}<|endoftext|>"} {"text":"\/*\n * MidiCtrl - Host implementation of a MIDI Uart skeletton (with sysex listener)\n *\n * (c) July 2011 - Manuel Odendahl - wesen@ruinwesen.com\n *\/\n\n#include \n\n#include \"Platform.h\"\n#include \"MidiUartHost.h\"\n\nuint8_t sysexBuf[8192];\nuint8_t sysexBuf2[8192];\n\n#ifndef TEST_SUITE\nMidiClass Midi(NULL, sysexBuf, sizeof(sysexBuf));\nMidiClass Midi2(NULL, sysexBuf2, sizeof(sysexBuf2));\nMidiUartHostClass MidiUart;\n#endif\n\nvoid MidiUartHostSysexListener::end() {\n \/\/ XXX Debug\n \/\/ printf(\"send sysex of %d bytes\\n\", sysex->len);\n\n uint8_t buf[sysex->len +2];\n buf[0] = 0xF0;\n m_memcpy(buf + 1, sysex->data, sysex->len);\n buf[sysex->len + 1] = 0xF7;\n uart->midiSendLong(buf, sysex->len + 2);\n}\n\nvoid handleIncomingMidi() {\n MidiUart.runLoop();\n while (MidiUart.avail()) {\n Midi.handleByte(MidiUart.getc());\n }\n usleep(1000);\n}\n\nvoid MidiUartHostParent::onOutputMessage(uint8_t *msg, uint8_t len) {\n \/\/ printf(\"output message %d bytes\\n\", len);\n \/\/ hexdump(msg, len);\n\n if (len > 3) {\n midiSendLong(msg, len);\n } else {\n switch (len) {\n case 0:\n return;\n case 1:\n midiSendShort(msg[0], 0, 0);\n break;\n case 2:\n midiSendShort(msg[0], msg[1], 0);\n break;\n case 3:\n midiSendShort(msg[0], msg[1], msg[2]);\n break;\n default:\n return;\n }\n }\n}\n\nvoid MidiUartHostParent::init(int _inputDevice, int _outputDevice) {\n inputDevice = _inputDevice;\n outputDevice = _outputDevice;\n \n outputMidi.init();\n outputMidi.addOnMessageCallback(this, (midi_callback_ptr2_t)&MidiUartHostParent::onOutputMessage);\n\n outputMidi.midiSysex.addSysexListener(&sysexListener);\n}\n\nFix method signature for midiuarthost\/*\n * MidiCtrl - Host implementation of a MIDI Uart skeletton (with sysex listener)\n *\n * (c) July 2011 - Manuel Odendahl - wesen@ruinwesen.com\n *\/\n\n#include \n\n#include \"Platform.h\"\n#include \"MidiUartHost.h\"\n\nuint8_t sysexBuf[8192];\nuint8_t sysexBuf2[8192];\n\n#ifndef TEST_SUITE\nMidiClass Midi(NULL, sysexBuf, sizeof(sysexBuf));\nMidiClass Midi2(NULL, sysexBuf2, sizeof(sysexBuf2));\nMidiUartHostClass MidiUart;\n#endif\n\nvoid MidiUartHostSysexListener::end() {\n \/\/ XXX Debug\n \/\/ printf(\"send sysex of %d bytes\\n\", sysex->len);\n\n uint8_t buf[sysex->len +2];\n buf[0] = 0xF0;\n m_memcpy(buf + 1, sysex->data, sysex->len);\n buf[sysex->len + 1] = 0xF7;\n uart->midiSendLong(buf, sysex->len + 2);\n}\n\nvoid handleIncomingMidi() {\n MidiUart.runLoop();\n while (MidiUart.avail()) {\n Midi.handleByte(MidiUart.getc());\n }\n usleep(1000);\n}\n\nvoid MidiUartHostParent::onOutputMessage(uint8_t *msg, uint8_t len) {\n \/\/ printf(\"output message %d bytes\\n\", len);\n \/\/ hexdump(msg, len);\n\n if (len > 3) {\n midiSendLong(msg, len);\n } else {\n switch (len) {\n case 0:\n return;\n case 1:\n midiSendShort(msg[0], 0, 0);\n break;\n case 2:\n midiSendShort(msg[0], msg[1], 0);\n break;\n case 3:\n midiSendShort(msg[0], msg[1], msg[2]);\n break;\n default:\n return;\n }\n }\n}\n\nbool MidiUartHostParent::init(int _inputDevice, int _outputDevice) {\n inputDevice = _inputDevice;\n outputDevice = _outputDevice;\n \n outputMidi.init();\n outputMidi.addOnMessageCallback(this, (midi_callback_ptr2_t)&MidiUartHostParent::onOutputMessage);\n\n outputMidi.midiSysex.addSysexListener(&sysexListener);\n\n return true;\n}\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by permal on 7\/20\/17.\n\/\/\n\n#include \n#include \n#include \n#include \"esp_log.h\"\n\n\nusing namespace smooth::core::ipc;\nusing namespace std::chrono;\n\nnamespace smooth\n{\n namespace application\n {\n namespace network\n {\n namespace mqtt\n {\n MQTT::MQTT(const std::string& mqtt_client_id,\n std::chrono::seconds keep_alive,\n uint32_t stack_depth,\n UBaseType_t priority)\n : Task(mqtt_client_id, stack_depth, priority, std::chrono::milliseconds(100)),\n tx_buffer(),\n rx_buffer(),\n tx_empty(\"TX_empty\", 5, *this, *this),\n data_available(\"data_available\", 5, *this, *this),\n connection_status(\"connection_status\", 5, *this, *this),\n timer_events(\"timer_events\", 5, *this, *this),\n guard(),\n client_id(mqtt_client_id),\n keep_alive(keep_alive),\n mqtt_socket(nullptr),\n receive_timer(\"receive_timer\", MQTT_FSM_RECEIVE_TIMER_ID, timer_events, false,\n std::chrono::seconds(10)),\n reconnect_timer(\"reconnect_timer\", MQTT_FSM_RECONNECT_TIMER_ID, timer_events, false,\n std::chrono::seconds(5)),\n keep_alive_timer(\"keep_alive_timer\", MQTT_FSM_KEEP_ALIVE_TIMER_ID, timer_events, true,\n std::chrono::seconds(1)),\n fsm(*this)\n {\n }\n\n void MQTT::tick()\n {\n fsm.tick();\n }\n\n\n void MQTT::init()\n {\n fsm.set_state(new(fsm) state::IdleState(fsm));\n }\n\n void MQTT::connect_to(std::shared_ptr address, bool auto_reconnect,\n bool use_ssl)\n {\n Mutex::Lock lock(guard);\n\n this->auto_reconnect = auto_reconnect;\n\n if (!mqtt_socket)\n {\n if (use_ssl)\n {\n mqtt_socket.reset(\n new core::network::SSLSocket(tx_buffer,\n rx_buffer,\n tx_empty,\n data_available,\n connection_status));\n }\n else\n {\n mqtt_socket.reset(\n new core::network::Socket(tx_buffer,\n rx_buffer,\n tx_empty,\n data_available,\n connection_status));\n }\n\n mqtt_socket->start(address);\n }\n }\n\n void MQTT::disconnect()\n {\n auto_reconnect = false;\n mqtt_socket->stop();\n mqtt_socket.reset();\n fsm.set_state(new(fsm) state::IdleState(fsm));\n }\n\n void MQTT::send_packet(packet::MQTTPacket& packet, milliseconds timeout)\n {\n receive_timer.start(timeout);\n tx_buffer.put(packet);\n }\n\n const std::string& MQTT::get_client_id() const\n {\n return client_id;\n }\n\n const std::chrono::seconds MQTT::get_keep_alive() const\n {\n return keep_alive;\n }\n\n void MQTT::start_reconnect()\n {\n reconnect_timer.start();\n }\n\n void MQTT::reconnect()\n {\n mqtt_socket->restart();\n }\n\n bool MQTT::get_auto_reconnect() const\n {\n return auto_reconnect;\n }\n\n void MQTT::set_keep_alive_timer(std::chrono::seconds interval)\n {\n if (interval.count() == 0)\n {\n keep_alive_timer.stop();\n }\n else\n {\n std::chrono::milliseconds ms = interval;\n \/\/ Times 0.75 as integer math.\n ms *= 3;\n ms \/= 4;\n ESP_LOGV(\"MQTT\", \"ms: %d\", static_cast(ms.count()));\n keep_alive_timer.start(ms);\n }\n }\n\n void MQTT::message(const core::network::TransmitBufferEmptyEvent& msg)\n {\n fsm.message(msg);\n }\n\n void MQTT::message(const core::network::ConnectionStatusEvent& msg)\n {\n fsm.message(msg);\n }\n\n void MQTT::message(const core::network::DataAvailableEvent& msg)\n {\n receive_timer.stop();\n\n packet::MQTTPacket p;\n if (msg.get(p))\n {\n fsm.packet_received(p);\n }\n }\n\n void MQTT::message(const core::timer::TimerExpiredEvent& msg)\n {\n fsm.message(msg);\n }\n }\n }\n }\n}Changed interval to 0.5 of keep alive interval.\/\/\n\/\/ Created by permal on 7\/20\/17.\n\/\/\n\n#include \n#include \n#include \n#include \"esp_log.h\"\n\n\nusing namespace smooth::core::ipc;\nusing namespace std::chrono;\n\nnamespace smooth\n{\n namespace application\n {\n namespace network\n {\n namespace mqtt\n {\n MQTT::MQTT(const std::string& mqtt_client_id,\n std::chrono::seconds keep_alive,\n uint32_t stack_depth,\n UBaseType_t priority)\n : Task(mqtt_client_id, stack_depth, priority, std::chrono::milliseconds(100)),\n tx_buffer(),\n rx_buffer(),\n tx_empty(\"TX_empty\", 5, *this, *this),\n data_available(\"data_available\", 5, *this, *this),\n connection_status(\"connection_status\", 5, *this, *this),\n timer_events(\"timer_events\", 5, *this, *this),\n guard(),\n client_id(mqtt_client_id),\n keep_alive(keep_alive),\n mqtt_socket(nullptr),\n receive_timer(\"receive_timer\", MQTT_FSM_RECEIVE_TIMER_ID, timer_events, false,\n std::chrono::seconds(10)),\n reconnect_timer(\"reconnect_timer\", MQTT_FSM_RECONNECT_TIMER_ID, timer_events, false,\n std::chrono::seconds(5)),\n keep_alive_timer(\"keep_alive_timer\", MQTT_FSM_KEEP_ALIVE_TIMER_ID, timer_events, true,\n std::chrono::seconds(1)),\n fsm(*this)\n {\n }\n\n void MQTT::tick()\n {\n fsm.tick();\n }\n\n\n void MQTT::init()\n {\n fsm.set_state(new(fsm) state::IdleState(fsm));\n }\n\n void MQTT::connect_to(std::shared_ptr address, bool auto_reconnect,\n bool use_ssl)\n {\n Mutex::Lock lock(guard);\n\n this->auto_reconnect = auto_reconnect;\n\n if (!mqtt_socket)\n {\n if (use_ssl)\n {\n mqtt_socket.reset(\n new core::network::SSLSocket(tx_buffer,\n rx_buffer,\n tx_empty,\n data_available,\n connection_status));\n }\n else\n {\n mqtt_socket.reset(\n new core::network::Socket(tx_buffer,\n rx_buffer,\n tx_empty,\n data_available,\n connection_status));\n }\n\n mqtt_socket->start(address);\n }\n }\n\n void MQTT::disconnect()\n {\n auto_reconnect = false;\n mqtt_socket->stop();\n mqtt_socket.reset();\n fsm.set_state(new(fsm) state::IdleState(fsm));\n }\n\n void MQTT::send_packet(packet::MQTTPacket& packet, milliseconds timeout)\n {\n receive_timer.start(timeout);\n tx_buffer.put(packet);\n }\n\n const std::string& MQTT::get_client_id() const\n {\n return client_id;\n }\n\n const std::chrono::seconds MQTT::get_keep_alive() const\n {\n return keep_alive;\n }\n\n void MQTT::start_reconnect()\n {\n reconnect_timer.start();\n }\n\n void MQTT::reconnect()\n {\n mqtt_socket->restart();\n }\n\n bool MQTT::get_auto_reconnect() const\n {\n return auto_reconnect;\n }\n\n void MQTT::set_keep_alive_timer(std::chrono::seconds interval)\n {\n if (interval.count() == 0)\n {\n keep_alive_timer.stop();\n }\n else\n {\n std::chrono::milliseconds ms = interval;\n ms \/= 2;\n ESP_LOGV(\"MQTT\", \"ms: %d\", static_cast(ms.count()));\n keep_alive_timer.start(ms);\n }\n }\n\n void MQTT::message(const core::network::TransmitBufferEmptyEvent& msg)\n {\n fsm.message(msg);\n }\n\n void MQTT::message(const core::network::ConnectionStatusEvent& msg)\n {\n fsm.message(msg);\n }\n\n void MQTT::message(const core::network::DataAvailableEvent& msg)\n {\n receive_timer.stop();\n\n packet::MQTTPacket p;\n if (msg.get(p))\n {\n fsm.packet_received(p);\n }\n }\n\n void MQTT::message(const core::timer::TimerExpiredEvent& msg)\n {\n fsm.message(msg);\n }\n }\n }\n }\n}<|endoftext|>"} {"text":"\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\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 met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file main.cxx\n *\n * A simple application to demonstrate asynchronous interfaces.\n *\n * @author Balazs Racz\n * @date 7 Dec 2013\n *\/\n\n#include \n#include \n#include \n\n#include \"os\/os.h\"\n#include \"utils\/gc_pipe.hxx\"\n#include \"executor\/Executor.hxx\"\n#include \"nmranet_can.h\"\n#include \"nmranet_config.h\"\n\n#include \"utils\/GcTcpHub.hxx\"\n#include \"nmranet\/AsyncIfCan.hxx\"\n#include \"nmranet\/NMRAnetIf.hxx\"\n#include \"nmranet\/AsyncAliasAllocator.hxx\"\n#include \"nmranet\/GlobalEventHandler.hxx\"\n#include \"nmranet\/EventHandlerTemplates.hxx\"\n#include \"nmranet\/NMRAnetAsyncEventHandler.hxx\"\n#include \"nmranet\/NMRAnetAsyncDefaultNode.hxx\"\n\/\/#include \"freertos_drivers\/nxp\/11cxx_async_can.hxx\"\n\nExecutor<1> g_executor(\"g_executor\", 0, 1024);\nService g_service(&g_executor);\nCanHubFlow can_hub0(&g_service);\n#ifdef __linux__\nGcPacketPrinter packet_printer(&can_hub0);\n#endif\n\nstatic const NMRAnet::NodeID NODE_ID = 0x050101011441ULL;\n\nextern \"C\" {\nextern int GC_GENERATE_NEWLINES;\nint GC_GENERATE_NEWLINES = 1;\n}\n\nextern \"C\" {\nconst size_t WRITE_FLOW_THREAD_STACK_SIZE = 900;\nextern const size_t CAN_TX_BUFFER_SIZE;\nextern const size_t CAN_RX_BUFFER_SIZE;\nconst size_t CAN_RX_BUFFER_SIZE = 1;\nconst size_t CAN_TX_BUFFER_SIZE = 2;\nextern const size_t SERIAL_RX_BUFFER_SIZE;\nextern const size_t SERIAL_TX_BUFFER_SIZE;\nconst size_t SERIAL_RX_BUFFER_SIZE = 16;\nconst size_t SERIAL_TX_BUFFER_SIZE = 16;\n#ifdef BOARD_LAUNCHPAD_EK\nconst size_t main_stack_size = 2500;\n#else\nconst size_t main_stack_size = 900;\n#endif\n}\n\nNMRAnet::AsyncIfCan g_if_can(&g_executor, &can_hub0, 3, 3, 2);\nstatic NMRAnet::AddAliasAllocator _alias_allocator(NODE_ID, &g_if_can);\nNMRAnet::DefaultAsyncNode g_node(&g_if_can, NODE_ID);\nNMRAnet::GlobalEventService g_event_service(&g_if_can);\n\nstatic const uint64_t EVENT_ID = 0x0501010114FF2200ULL;\nconst int main_priority = 0;\n\nclass BlinkerFlow : public StateFlowBase\n{\npublic:\n BlinkerFlow(NMRAnet::AsyncNode* node)\n : StateFlowBase(node->interface()),\n state_(1),\n bit_(node, EVENT_ID, EVENT_ID + 1, &state_, (uint8_t)1),\n producer_(&bit_),\n sleepData_(this)\n {\n start_flow(STATE(blinker));\n }\n\nprivate:\n Action blinker()\n {\n state_ = !state_;\n#ifdef __linux__\n LOG(INFO, \"blink produce %d\", state_);\n#endif\n producer_.Update(&helper_, n_.reset(this));\n return wait_and_call(STATE(handle_sleep));\n }\n\n Action handle_sleep()\n {\n return sleep_and_call(&sleepData_, MSEC_TO_NSEC(1000), STATE(blinker));\n }\n\n uint8_t state_;\n NMRAnet::MemoryBit bit_;\n NMRAnet::BitEventProducer producer_;\n NMRAnet::WriteHelper helper_;\n StateFlowTimer sleepData_;\n BarrierNotifiable n_;\n};\n\nextern \"C\" { void resetblink(uint32_t pattern); }\n\nclass LoggingBit : public NMRAnet::BitEventInterface\n{\npublic:\n LoggingBit(uint64_t event_on, uint64_t event_off, const char* name)\n : BitEventInterface(event_on, event_off), name_(name), state_(false)\n {\n }\n\n virtual bool GetCurrentState()\n {\n return state_;\n }\n virtual void SetState(bool new_value)\n {\n state_ = new_value;\n \/\/HASSERT(0);\n#ifdef __linux__\n LOG(INFO, \"bit %s set to %d\", name_, state_);\n#else\n resetblink(state_ ? 1 : 0);\n#endif\n }\n\n virtual NMRAnet::AsyncNode* node()\n {\n return &g_node;\n }\n\nprivate:\n const char* name_;\n bool state_;\n};\n\n\/** Entry point to application.\n * @param argc number of command line arguments\n * @param argv array of command line arguments\n * @return 0, should never return\n *\/\nint appl_main(int argc, char* argv[])\n{\n#ifdef __linux__\n GcTcpHub hub(&can_hub0, 12021);\n#endif\n#ifdef NNTARGET_LPC11Cxx\n lpc11cxx::CreateCanDriver(&can_pipe);\n#endif\n#ifdef BOARD_LAUNCHPAD_EK\n int fd = ::open(\"\/dev\/ser0\", O_RDWR);\n HASSERT(fd >= 0);\n printf(\"hello, world!\\n\");\n create_gc_port_for_can_hub(&can_hub0, fd);\n#endif\n \/\/ Bootstraps the alias allocation process.\n g_if_can.alias_allocator()->send(g_if_can.alias_allocator()->alloc());\n\n LoggingBit logger(EVENT_ID, EVENT_ID + 1, \"blinker\");\n NMRAnet::BitEventConsumer consumer(&logger);\n \/\/BlinkerFlow blinker(&g_node);\n \/\/ We don't need to support addressed messages.\n \/\/ g_if_can.add_addressed_message_support(1);\n while(1) {\n sleep(1);\n }\n return 0;\n}\nFix main.cxx of async_blink to actually use the physical device.\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\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 met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file main.cxx\n *\n * A simple application to demonstrate asynchronous interfaces.\n *\n * @author Balazs Racz\n * @date 7 Dec 2013\n *\/\n\n#include \n#include \n#include \n\n#include \"os\/os.h\"\n#include \"utils\/gc_pipe.hxx\"\n#include \"executor\/Executor.hxx\"\n#include \"nmranet_can.h\"\n#include \"nmranet_config.h\"\n\n#include \"utils\/GcTcpHub.hxx\"\n#include \"utils\/HubDevice.hxx\"\n#include \"nmranet\/AsyncIfCan.hxx\"\n#include \"nmranet\/NMRAnetIf.hxx\"\n#include \"nmranet\/AsyncAliasAllocator.hxx\"\n#include \"nmranet\/GlobalEventHandler.hxx\"\n#include \"nmranet\/EventHandlerTemplates.hxx\"\n#include \"nmranet\/NMRAnetAsyncEventHandler.hxx\"\n#include \"nmranet\/NMRAnetAsyncDefaultNode.hxx\"\n\/\/#include \"freertos_drivers\/nxp\/11cxx_async_can.hxx\"\n\nExecutor<1> g_executor(\"g_executor\", 0, 1024);\nService g_service(&g_executor);\nCanHubFlow can_hub0(&g_service);\n#ifdef __linux__\nGcPacketPrinter packet_printer(&can_hub0);\n#endif\n\nstatic const NMRAnet::NodeID NODE_ID = 0x050101011441ULL;\n\nextern \"C\" {\nextern int GC_GENERATE_NEWLINES;\nint GC_GENERATE_NEWLINES = 1;\n}\n\nextern \"C\" {\nconst size_t WRITE_FLOW_THREAD_STACK_SIZE = 900;\nextern const size_t CAN_TX_BUFFER_SIZE;\nextern const size_t CAN_RX_BUFFER_SIZE;\nconst size_t CAN_RX_BUFFER_SIZE = 1;\nconst size_t CAN_TX_BUFFER_SIZE = 2;\nextern const size_t SERIAL_RX_BUFFER_SIZE;\nextern const size_t SERIAL_TX_BUFFER_SIZE;\nconst size_t SERIAL_RX_BUFFER_SIZE = 16;\nconst size_t SERIAL_TX_BUFFER_SIZE = 16;\n#ifdef BOARD_LAUNCHPAD_EK\nconst size_t main_stack_size = 2500;\n#else\nconst size_t main_stack_size = 900;\n#endif\n}\n\nNMRAnet::AsyncIfCan g_if_can(&g_executor, &can_hub0, 3, 3, 2);\nstatic NMRAnet::AddAliasAllocator _alias_allocator(NODE_ID, &g_if_can);\nNMRAnet::DefaultAsyncNode g_node(&g_if_can, NODE_ID);\nNMRAnet::GlobalEventService g_event_service(&g_if_can);\n\nstatic const uint64_t EVENT_ID = 0x0501010114FF2200ULL;\nconst int main_priority = 0;\n\nclass BlinkerFlow : public StateFlowBase\n{\npublic:\n BlinkerFlow(NMRAnet::AsyncNode* node)\n : StateFlowBase(node->interface()),\n state_(1),\n bit_(node, EVENT_ID, EVENT_ID + 1, &state_, (uint8_t)1),\n producer_(&bit_),\n sleepData_(this)\n {\n start_flow(STATE(blinker));\n }\n\nprivate:\n Action blinker()\n {\n state_ = !state_;\n#ifdef __linux__\n LOG(INFO, \"blink produce %d\", state_);\n#endif\n producer_.Update(&helper_, n_.reset(this));\n return wait_and_call(STATE(handle_sleep));\n }\n\n Action handle_sleep()\n {\n return sleep_and_call(&sleepData_, MSEC_TO_NSEC(1000), STATE(blinker));\n }\n\n uint8_t state_;\n NMRAnet::MemoryBit bit_;\n NMRAnet::BitEventProducer producer_;\n NMRAnet::WriteHelper helper_;\n StateFlowTimer sleepData_;\n BarrierNotifiable n_;\n};\n\nextern \"C\" { void resetblink(uint32_t pattern); }\n\nclass LoggingBit : public NMRAnet::BitEventInterface\n{\npublic:\n LoggingBit(uint64_t event_on, uint64_t event_off, const char* name)\n : BitEventInterface(event_on, event_off), name_(name), state_(false)\n {\n }\n\n virtual bool GetCurrentState()\n {\n return state_;\n }\n virtual void SetState(bool new_value)\n {\n state_ = new_value;\n \/\/HASSERT(0);\n#ifdef __linux__\n LOG(INFO, \"bit %s set to %d\", name_, state_);\n#else\n resetblink(state_ ? 1 : 0);\n#endif\n }\n\n virtual NMRAnet::AsyncNode* node()\n {\n return &g_node;\n }\n\nprivate:\n const char* name_;\n bool state_;\n};\n\n\/** Entry point to application.\n * @param argc number of command line arguments\n * @param argv array of command line arguments\n * @return 0, should never return\n *\/\nint appl_main(int argc, char* argv[])\n{\n#ifdef __linux__\n GcTcpHub hub(&can_hub0, 12021);\n#else\n#ifdef NNTARGET_LPC11Cxx\n lpc11cxx::CreateCanDriver(&can_pipe);\n#else\n int can_fd = ::open(\"\/dev\/can0\", O_RDWR);\n HASSERT(can_fd >= 0);\n\n FdHubPort can_hub_port(&can_hub0, can_fd, EmptyNotifiable::DefaultInstance());\n#endif \/\/ default target\n#endif \/\/ FreeRTOS\n\n int fd = ::open(\"\/dev\/ser0\", O_RDWR);\n HASSERT(fd >= 0);\n create_gc_port_for_can_hub(&can_hub0, fd);\n\n \/\/ Bootstraps the alias allocation process.\n g_if_can.alias_allocator()->send(g_if_can.alias_allocator()->alloc());\n\n LoggingBit logger(EVENT_ID, EVENT_ID + 1, \"blinker\");\n NMRAnet::BitEventConsumer consumer(&logger);\n \/\/BlinkerFlow blinker(&g_node);\n \/\/ We don't need to support addressed messages.\n \/\/ g_if_can.add_addressed_message_support(1);\n while(1) {\n sleep(1);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * 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\n \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Methods to manipulate and manage daemon names\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_string.h\"\n#include \"get_full_hostname.h\"\n#include \"my_hostname.h\"\n#include \"my_username.h\"\n#include \"condor_uid.h\"\n\nextern \"C\" {\n\n\/\/ Return the host portion of a daemon name string. Either the name\n\/\/ includes an \"@\" sign, in which case we return whatever is after it,\n\/\/ or it doesn't, in which case we just return what we got passed.\nconst char*\nget_host_part( const char* name )\n{\n\tchar const *tmp;\n\tif (name == NULL) return NULL;\n\ttmp = strrchr( name, '@' );\n\tif( tmp ) {\n\t\treturn ++tmp;\n\t} else {\n\t\treturn name;\n\t}\n}\n\n\n\/\/ Return a pointer to a newly allocated string that contains the\n\/\/ valid daemon name that corresponds with the given name. Basically,\n\/\/ see if there's an '@'. If so, resolve everything after it as a\n\/\/ hostname. If not, resolve what we were passed as a hostname.\n\/\/ The string is allocated with strnewp() (or it's equivalent), so you\n\/\/ should deallocate it with delete [].\nchar*\nget_daemon_name( const char* name )\n{\n\tchar *tmp, *fullname, *tmpname, *daemon_name = NULL;\n\tint size;\n\n\tdprintf( D_HOSTNAME, \"Finding proper daemon name for \\\"%s\\\"\\n\",\n\t\t\t name ); \n\n\t\t\/\/ First, check for a '@' in the name. \n\ttmpname = strdup( name );\n\ttmp = strrchr( tmpname, '@' );\n\tif( tmp ) {\n\t\t\t\/\/ There's a '@'.\n\t\t*tmp = '\\0';\n\t\ttmp++;\n\t\tif( *tmp ) {\n\t\t\t\t\/\/ There was something after the @, try to resolve it\n\t\t\t\t\/\/ as a full hostname:\n\t\t\tdprintf( D_HOSTNAME, \"Daemon name has data after the '@', \"\n\t\t\t\t\t \"trying to resolve \\\"%s\\\"\\n\", tmp ); \n\t\t\tfullname = get_full_hostname( tmp );\n\t\t} else {\n\t\t\tdprintf( D_HOSTNAME, \"Daemon name has no data after the '@', \"\n\t\t\t\t\t \"trying to use the local host\\n\" ); \n\t\t\t\t\/\/ There was nothing after the @, use localhost:\n\t\t\tfullname = strnewp( my_full_hostname() );\n\t\t}\n\t\tif( fullname ) {\n\t\t\tsize = strlen(tmpname) + strlen(fullname) + 2;\n\t\t\tdaemon_name = new char[size];\n\t\t\tsprintf( daemon_name, \"%s@%s\", tmpname, fullname );\n\t\t\tdelete [] fullname;\n\t\t} \n\t} else {\n\t\t\t\/\/ There's no '@', just try to resolve the hostname.\n\t\tdprintf( D_HOSTNAME, \"Daemon name contains no '@', treating as a \"\n\t\t\t\t \"regular hostname\\n\" );\n\t\tdaemon_name = get_full_hostname( tmpname );\n\t}\n\tfree( tmpname );\n\n\t\t\/\/ If there was an error, this will still be NULL.\n\tif( daemon_name ) { \n\t\tdprintf( D_HOSTNAME, \"Returning daemon name: \\\"%s\\\"\\n\", daemon_name );\n\t} else {\n\t\tdprintf( D_HOSTNAME, \"Failed to construct daemon name, \"\n\t\t\t\t \"returning NULL\\n\" );\n\t}\n\treturn daemon_name;\n}\n\n\n\/\/ Given some name, create a valid name for ourself with our full\n\/\/ hostname. If the name contains an '@', strip off everything after\n\/\/ it and append my_full_hostname(). If there's no '@', try to\n\/\/ resolve what we have and see if it's my_full_hostname. If so, use\n\/\/ it, otherwise, use name@my_full_hostname(). We return the answer\n\/\/ in a string which should be deallocated w\/ delete [].\nchar*\nbuild_valid_daemon_name( char* name ) \n{\n\tchar *tmp, *tmpname = NULL, *daemon_name = NULL;\n\tint size;\n\n\t\t\/\/ This flag determines if we want to just return a copy of\n\t\t\/\/ my_full_hostname(), or if we want to append\n\t\t\/\/ \"@my_full_hostname\" to the name we were given. The name we\n\t\t\/\/ were given might include an '@', in which case, we trim off\n\t\t\/\/ everything after the '@'.\n\tbool just_host = false;\n\n\tif( name && *name ) {\n\t\ttmpname = strnewp( name );\n\t\ttmp = strrchr( tmpname, '@' );\n\t\tif( tmp ) {\n\t\t\t\t\/\/ name we were passed has an '@', ignore everything\n\t\t\t\t\/\/ after (and including) the '@'. \n\t\t\t*tmp = '\\0';\n\t\t} else {\n\t\t\t\t\/\/ no '@', see if what we have is our hostname\n\t\t\tif( (tmp = get_full_hostname(name)) ) {\n\t\t\t\tif( !strcmp(tmp, my_full_hostname()) ) {\n\t\t\t\t\t\t\/\/ Yup, so just the full hostname.\n\t\t\t\t\tjust_host = true;\n\t\t\t\t}\t\t\t\t\t\n\t\t\t\tdelete [] tmp;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\t\/\/ Passed NULL for the name.\n\t\tjust_host = true;\n\t}\n\n\tif( just_host ) {\n\t\tdaemon_name = strnewp( my_full_hostname() );\n\t} else {\n\t\tsize = strlen(tmpname) + strlen(my_full_hostname()) + 2; \n\t\tdaemon_name = new char[size];\n\t\tsprintf( daemon_name, \"%s@%s\", tmpname, my_full_hostname() ); \n\t}\n\tdelete [] tmpname;\n\treturn daemon_name;\n}\n\n\n\/* \n Return a string on the heap (must be deallocated with delete()) that \n contains the default daemon name for the calling process. If we're\n root (additionally, on UNIX, if we're condor), we default to the\n full hostname. Otherwise, we default to username@full.hostname.\n*\/\nchar*\ndefault_daemon_name( void )\n{\n\tif( is_root() ) {\n\t\treturn strnewp( my_full_hostname() );\n\t}\n#ifndef WIN32\n\tif( getuid() == get_real_condor_uid() ) {\n\t\treturn strnewp( my_full_hostname() );\n\t}\n#endif \/* ! LOSE32 *\/\n\tchar* name = my_username();\n\tif( ! name ) {\n\t\treturn NULL;\n\t}\n\tchar* host = my_full_hostname();\n\tif( ! host ) {\n\t\tfree( name );\n\t\treturn NULL;\n\t}\n\tint size = strlen(name) + strlen(host) + 2;\n\tchar* ans = new char[size];\n\tif( ! ans ) {\n\t\tfree( name );\n\t\treturn NULL;\n\t}\n\tsprintf( ans, \"%s@%s\", name, host );\n\tfree(name);\n\treturn ans;\n}\n\n\n} \/* extern \"C\" *\/\nChange behavior of names ending in an @ sign to allow for multiple Schedds to report the same SCHEDD_NAME. This is critical for transparent Schedd fail-over.\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * 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\n \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Methods to manipulate and manage daemon names\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_string.h\"\n#include \"get_full_hostname.h\"\n#include \"my_hostname.h\"\n#include \"my_username.h\"\n#include \"condor_uid.h\"\n\nextern \"C\" {\n\n\/\/ Return the host portion of a daemon name string. Either the name\n\/\/ includes an \"@\" sign, in which case we return whatever is after it,\n\/\/ or it doesn't, in which case we just return what we got passed.\nconst char*\nget_host_part( const char* name )\n{\n\tchar const *tmp;\n\tif (name == NULL) return NULL;\n\ttmp = strrchr( name, '@' );\n\tif( tmp ) {\n\t\treturn ++tmp;\n\t} else {\n\t\treturn name;\n\t}\n}\n\n\n\/\/ Return a pointer to a newly allocated string that contains the\n\/\/ valid daemon name that corresponds with the given name. Basically,\n\/\/ see if there's an '@'. If so, resolve everything after it as a\n\/\/ hostname. If not, resolve what we were passed as a hostname.\n\/\/ The string is allocated with strnewp() (or it's equivalent), so you\n\/\/ should deallocate it with delete [].\nchar*\nget_daemon_name( const char* name )\n{\n\tchar *tmp, *tmpname, *daemon_name = NULL;\n\tchar *fullname = NULL;\n\tint size;\n\n\tdprintf( D_HOSTNAME, \"Finding proper daemon name for \\\"%s\\\"\\n\",\n\t\t\t name ); \n\n\t\t\/\/ First, check for a '@' in the name. \n\ttmpname = strdup( name );\n\ttmp = strrchr( tmpname, '@' );\n\tif( tmp ) {\n\t\t\t\/\/ There's a '@'.\n\t\t*tmp = '\\0';\n\t\ttmp++;\n\t\tif( *tmp ) {\n\t\t\t\t\/\/ There was something after the @, try to resolve it\n\t\t\t\t\/\/ as a full hostname:\n\t\t\tdprintf( D_HOSTNAME, \"Daemon name has data after the '@', \"\n\t\t\t\t\t \"trying to resolve \\\"%s\\\"\\n\", tmp ); \n\t\t\tfullname = get_full_hostname( tmp );\n\t\t} else {\n\t\t\tdprintf( D_HOSTNAME, \"Daemon name has no data after the '@', \"\n\t\t\t\t\t \"we'll assume that's by design\\n\" ); \n\t\t\tdaemon_name = strnewp( name );\n\t\t}\n\t\tif( fullname ) {\n\t\t\tsize = strlen(tmpname) + strlen(fullname) + 2;\n\t\t\tdaemon_name = new char[size];\n\t\t\tsprintf( daemon_name, \"%s@%s\", tmpname, fullname );\n\t\t\tdelete [] fullname;\n\t\t} \n\t} else {\n\t\t\t\/\/ There's no '@', just try to resolve the hostname.\n\t\tdprintf( D_HOSTNAME, \"Daemon name contains no '@', treating as a \"\n\t\t\t\t \"regular hostname\\n\" );\n\t\tdaemon_name = get_full_hostname( tmpname );\n\t}\n\tfree( tmpname );\n\n\t\t\/\/ If there was an error, this will still be NULL.\n\tif( daemon_name ) { \n\t\tdprintf( D_HOSTNAME, \"Returning daemon name: \\\"%s\\\"\\n\", daemon_name );\n\t} else {\n\t\tdprintf( D_HOSTNAME, \"Failed to construct daemon name, \"\n\t\t\t\t \"returning NULL\\n\" );\n\t}\n\treturn daemon_name;\n}\n\n\n\/\/ Given some name, create a valid name for ourself with our full\n\/\/ hostname. If the name contains an '@', strip off everything after\n\/\/ it and append my_full_hostname(). If there's no '@', try to\n\/\/ resolve what we have and see if it's my_full_hostname. If so, use\n\/\/ it, otherwise, use name@my_full_hostname(). We return the answer\n\/\/ in a string which should be deallocated w\/ delete [].\nchar*\nbuild_valid_daemon_name( char* name ) \n{\n\tchar *tmp, *tmpname = NULL, *daemon_name = NULL;\n\tint size;\n\n\t\t\/\/ This flag determines if we want to just return a copy of\n\t\t\/\/ my_full_hostname(), or if we want to append\n\t\t\/\/ \"@my_full_hostname\" to the name we were given. The name we\n\t\t\/\/ were given might include an '@', in which case, we trim off\n\t\t\/\/ everything after the '@'.\n\tbool just_host = false;\n\n\tbool just_name = false;\n\n\tif( name && *name ) {\n\t\ttmpname = strnewp( name );\n\t\ttmp = strrchr( tmpname, '@' );\n\t\tif( tmp ) {\n\t\t\t\t\/\/ name we were passed has an '@', ignore everything\n\t\t\t\t\/\/ after (and including) the '@'. \n\t\t\t*tmp = '\\0';\n\n\t\t\tjust_name = true;\n\t\t} else {\n\t\t\t\t\/\/ no '@', see if what we have is our hostname\n\t\t\tif( (tmp = get_full_hostname(name)) ) {\n\t\t\t\tif( !strcmp(tmp, my_full_hostname()) ) {\n\t\t\t\t\t\t\/\/ Yup, so just the full hostname.\n\t\t\t\t\tjust_host = true;\n\t\t\t\t}\t\t\t\t\t\n\t\t\t\tdelete [] tmp;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\t\/\/ Passed NULL for the name.\n\t\tjust_host = true;\n\t}\n\n\tif( just_host ) {\n\t\tdaemon_name = strnewp( my_full_hostname() );\n\t} else {\n\t\tif( just_name ) {\n\t\t\tdaemon_name = strnewp( name );\n\t\t} else {\n\t\t\tsize = strlen(tmpname) + strlen(my_full_hostname()) + 2; \n\t\t\tdaemon_name = new char[size];\n\t\t\tsprintf( daemon_name, \"%s@%s\", tmpname, my_full_hostname() ); \n\t\t}\n\t}\n\tdelete [] tmpname;\n\treturn daemon_name;\n}\n\n\n\/* \n Return a string on the heap (must be deallocated with delete()) that \n contains the default daemon name for the calling process. If we're\n root (additionally, on UNIX, if we're condor), we default to the\n full hostname. Otherwise, we default to username@full.hostname.\n*\/\nchar*\ndefault_daemon_name( void )\n{\n\tif( is_root() ) {\n\t\treturn strnewp( my_full_hostname() );\n\t}\n#ifndef WIN32\n\tif( getuid() == get_real_condor_uid() ) {\n\t\treturn strnewp( my_full_hostname() );\n\t}\n#endif \/* ! LOSE32 *\/\n\tchar* name = my_username();\n\tif( ! name ) {\n\t\treturn NULL;\n\t}\n\tchar* host = my_full_hostname();\n\tif( ! host ) {\n\t\tfree( name );\n\t\treturn NULL;\n\t}\n\tint size = strlen(name) + strlen(host) + 2;\n\tchar* ans = new char[size];\n\tif( ! ans ) {\n\t\tfree( name );\n\t\treturn NULL;\n\t}\n\tsprintf( ans, \"%s@%s\", name, host );\n\tfree(name);\n\treturn ans;\n}\n\n\n} \/* extern \"C\" *\/\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * 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\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"user_proc.h\"\n#include \"starter.h\"\n#include \"condor_attributes.h\"\n#include \"classad_helpers.h\"\n#include \"sig_name.h\"\n#include \"stream_handler.h\"\n#include \"subsystem_info.h\"\n\nextern CStarter *Starter;\n\n\n\/* UserProc class implementation *\/\n\nUserProc::~UserProc()\n{\n\tif( name ) {\n\t\tfree( name );\n\t}\n}\n\n\nvoid\nUserProc::initialize( void )\n{\n\tJobPid = -1;\n\texit_status = -1;\n\trequested_exit = false;\n\tm_proc_exited = false;\n\tjob_universe = 0; \/\/ we'll fill in a real value if we can...\n\tif( JobAd ) {\n\t\tinitKillSigs();\n\t\tif( JobAd->LookupInteger( ATTR_JOB_UNIVERSE, job_universe ) < 1 ) {\n\t\t\tjob_universe = 0;\n\t\t}\n\t}\n}\n\n\nvoid\nUserProc::initKillSigs( void )\n{\n\tint sig;\n\n\tsig = findSoftKillSig( JobAd );\n\tif( sig >= 0 ) {\n\t\tsoft_kill_sig = sig;\n\t} else {\n\t\tsoft_kill_sig = SIGTERM;\n\t}\n\n\tsig = findRmKillSig( JobAd );\n\tif( sig >= 0 ) {\n\t\trm_kill_sig = sig;\n\t} else {\n\t\trm_kill_sig = SIGTERM;\n\t}\n\n\tsig = findHoldKillSig( JobAd );\n\tif( sig >= 0 ) {\n\t\thold_kill_sig = sig;\n\t} else {\n\t\thold_kill_sig = SIGTERM;\n\t}\n\n\tconst char* tmp = signalName( soft_kill_sig );\n\tdprintf( D_FULLDEBUG, \"%s KillSignal: %d (%s)\\n\", \n\t\t\t name ? name : \"Main job\", soft_kill_sig, \n\t\t\t tmp ? tmp : \"Unknown\" );\n\n\ttmp = signalName( rm_kill_sig );\n\tdprintf( D_FULLDEBUG, \"%s RmKillSignal: %d (%s)\\n\", \n\t\t\t name ? name : \"Main job\", rm_kill_sig, \n\t\t\t tmp ? tmp : \"Unknown\" );\n\n\ttmp = signalName( hold_kill_sig );\n\tdprintf( D_FULLDEBUG, \"%s HoldKillSignal: %d (%s)\\n\", \n\t\t\t name ? name : \"Main job\", hold_kill_sig, \n\t\t\t tmp ? tmp : \"Unknown\" );\n}\n\n\nbool\nUserProc::JobReaper(int pid, int status)\n{\n\tif (JobPid == pid) {\n\t\tm_proc_exited = true;\n\t\texit_status = status;\n\t\tjob_exit_time.getTime();\n\t}\n\treturn m_proc_exited;\n}\n\n\nbool\nUserProc::PublishUpdateAd( ClassAd* ad )\n{\n\tchar buf[256];\n\n\tif( JobPid >= 0 ) { \n\t\tsprintf( buf, \"%s%s=%d\", name ? name : \"\", ATTR_JOB_PID,\n\t\t\t\t JobPid );\n\t\tad->Insert( buf );\n\t}\n\n\tif( job_start_time.seconds() > 0 ) {\n\t\tsprintf( buf, \"%s%s=%ld\", name ? name : \"\", ATTR_JOB_START_DATE,\n\t\t\t\t job_start_time.seconds() );\n\t\tad->Insert( buf );\n\t}\n\n\tif (m_proc_exited) {\n\n\t\tif( job_exit_time.seconds() > 0 ) {\n\t\t\tsprintf( buf, \"%s%s=%f\", name ? name : \"\", ATTR_JOB_DURATION, \n\t\t\t\t\t job_exit_time.difference(&job_start_time) );\n\t\t\tad->Insert( buf );\n\t\t}\n\n\t\t\t\/*\n\t\t\t If we have the exit status, we want to parse it and set\n\t\t\t some attributes which describe the status in a platform\n\t\t\t independent way. This way, we're sure we're analyzing\n\t\t\t the status integer with the platform-specific macros\n\t\t\t where it came from, instead of assuming that WIFEXITED()\n\t\t\t and friends will work correctly on a status integer we\n\t\t\t got back from a different platform.\n\t\t\t*\/\n\t\tif( WIFSIGNALED(exit_status) ) {\n\t\t\tsprintf( buf, \"%s%s = TRUE\", name ? name : \"\",\n\t\t\t\t\t ATTR_ON_EXIT_BY_SIGNAL );\n\t\t\tad->Insert( buf );\n\t\t\tsprintf( buf, \"%s%s = %d\", name ? name : \"\",\n\t\t\t\t\t ATTR_ON_EXIT_SIGNAL, WTERMSIG(exit_status) );\n\t\t\tad->Insert( buf );\n\t\t\tsprintf( buf, \"%s%s = \\\"died on %s\\\"\",\n\t\t\t\t\t name ? name : \"\", ATTR_EXIT_REASON,\n\t\t\t\t\t daemonCore->GetExceptionString(WTERMSIG(exit_status)) );\n\t\t\tad->Insert( buf );\n\t\t} else {\n\t\t\tsprintf( buf, \"%s%s = FALSE\", name ? name : \"\",\n\t\t\t\t\t ATTR_ON_EXIT_BY_SIGNAL );\n\t\t\tad->Insert( buf );\n\t\t\tsprintf( buf, \"%s%s = %d\", name ? name : \"\",\n\t\t\t\t\t ATTR_ON_EXIT_CODE, WEXITSTATUS(exit_status) );\n\t\t\tad->Insert( buf );\n\t\t}\n\t}\n\treturn true;\n}\n\n\nvoid\nUserProc::PublishToEnv( Env* proc_env )\n{\n\tif (m_proc_exited) {\n\t\t\t\/\/ TODO: what should these really be called? use\n\t\t\t\/\/ myDistro? mySubSystem? hard to say...\n\t\tMyString base;\n\t\tbase = \"_\";\n\t\tbase += myDistro->Get();\n\t\tbase += '_';\n\t\tif( name ) {\n\t\t\tbase += name;\n\t\t} else {\n\t\t\tbase += \"MAINJOB\";\n\t\t}\n\t\tbase += '_';\n\t\tbase.upper_case();\n \n\t\tMyString env_name;\n\n\t\tif( WIFSIGNALED(exit_status) ) {\n\t\t\tenv_name = base.GetCStr();\n\t\t\tenv_name += \"EXIT_SIGNAL\";\n\t\t\tproc_env->SetEnv( env_name.GetCStr(), WTERMSIG(exit_status) );\n\t\t} else {\n\t\t\tenv_name = base.GetCStr();\n\t\t\tenv_name += \"EXIT_CODE\";\n\t\t\tproc_env->SetEnv( env_name.GetCStr(), WEXITSTATUS(exit_status) );\n\t\t}\n\t}\n}\n\nbool\nUserProc::getStdFile( std_file_type type,\n const char* attr,\n bool allow_dash,\n const char* log_header,\n int* out_fd,\n MyString* out_name)\n{\n\t\t\/\/ we're going to return true on success, false on error.\n\t\t\/\/ if we succeed, then if we have an open FD that should\n\t\t\/\/ be passed down to the job, return it in the descriptor\n\t\t\/\/ argument. otherwise, return -1 in the descriptor\n\t\t\/\/ argument and return the name of the file that should\n\t\t\/\/ be opened for the child in the name argument\n\tASSERT(out_fd != NULL);\n\tASSERT(out_name != NULL);\n\t*out_fd = -1;\n\n\tconst char* filename;\n\tbool wants_stream = false;\n\tconst char* stream_name = NULL;\n\tconst char* phrase = NULL;\n\tbool is_output = true;\n\tbool is_null_file = false;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Initialize some settings depending on the type\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tswitch( type ) {\n\tcase SFT_IN:\n\t\tis_output = false;\n\t\tphrase = \"standard input\";\n\t\tstream_name = \"stdin\";\n\t\tbreak;\n\tcase SFT_OUT:\n\t\tis_output = true;\n\t\tphrase = \"standard output\";\n\t\tstream_name = \"stdout\";\n\t\tbreak;\n\tcase SFT_ERR:\n\t\tis_output = true;\n\t\tphrase = \"standard error\";\n\t\tstream_name = \"stderr\";\n\t\tbreak;\n\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Figure out what we're trying to open, if anything\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tif( attr ) {\n\t\tfilename = Starter->jic->getJobStdFile( attr );\n\t\twants_stream = Starter->jic->streamStdFile( attr );\n\t} else {\n\t\tswitch( type ) {\n\t\tcase SFT_IN:\n\t\t\tfilename = Starter->jic->jobInputFilename();\n\t\t\twants_stream = Starter->jic->streamInput();\n\t\t\tbreak;\n\t\tcase SFT_OUT:\n\t\t\tfilename = Starter->jic->jobOutputFilename();\n\t\t\twants_stream = Starter->jic->streamOutput();\n\t\t\tbreak;\n\t\tcase SFT_ERR:\n\t\t\tfilename = Starter->jic->jobErrorFilename();\n\t\t\twants_stream = Starter->jic->streamError();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif( ! filename ) {\n\t\t\t\/\/ If there's nothing specified, we always want to open\n\t\t\t\/\/ the system-appropriate NULL file (\/dev\/null or NUL).\n\t\t\t\/\/ Otherwise, we can mostly treat this as if the job\n\t\t\t\/\/ defined a real local filename. For the few cases were\n\t\t\t\/\/ we have to behave differently, record it in a bool. \n\t\tfilename = NULL_FILE;\n\t\tis_null_file = true;\n\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Deal with special cases\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Use streaming I\/O\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tif( wants_stream && ! is_null_file ) {\n\t\tStreamHandler *handler = new StreamHandler;\n\t\tif( !handler->Init(filename, stream_name, is_output) ) {\n\t\t\tMyString err_msg;\n\t\t\terr_msg.sprintf( \"unable to establish %s stream\", phrase );\n\t\t\tStarter->jic->notifyStarterError( err_msg.Value(), true,\n\t\t\t is_output ? CONDOR_HOLD_CODE_UnableToOpenOutputStream :\n\t\t\t CONDOR_HOLD_CODE_UnableToOpenInputStream, 0 );\n\t\t\treturn false;\n\t\t}\n\t\t*out_fd = handler->GetJobPipe();\n\t\tdprintf( D_ALWAYS, \"%s: streaming from remote file %s\\n\",\n\t\t\t\t log_header, filename );\n\t\treturn true;\n\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Use the starter's equivalent fd\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tif( allow_dash && (filename[0] == '-') && !filename[1] )\n\t{\n\t\t\t\/\/ use the starter's fd\n\t\tswitch( type ) {\n\t\tcase SFT_IN:\n\t\t\t*out_fd = Starter->starterStdinFd();\n\t\t\tdprintf( D_ALWAYS, \"%s: using STDIN of %s\\n\", log_header,\n\t\t\t\t\t mySubSystem->getName() );\n\t\t\tbreak;\n\t\tcase SFT_OUT:\n\t\t\t*out_fd = Starter->starterStdoutFd();\n\t\t\tdprintf( D_ALWAYS, \"%s: using STDOUT of %s\\n\", log_header,\n\t\t\t\t\t mySubSystem->getName() );\n\t\t\tbreak;\n\t\tcase SFT_ERR:\n\t\t\t*out_fd = Starter->starterStderrFd();\n\t\t\tdprintf( D_ALWAYS, \"%s: using STDERR of %s\\n\", log_header,\n\t\t\t\t\t mySubSystem->getName() );\n\t\t\tbreak;\n\t\t}\n\t\treturn true;\n\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ The regular case of a local file \n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t*out_name = filename;\n\treturn true;\n}\n\nint\nUserProc::openStdFile( std_file_type type,\n const char* attr, \n bool allow_dash,\n const char* log_header)\n{\n\t\t\/\/ most of the work gets done by our helper, getStdFile\n\tint fd;\n\tMyString filename;\n\tif (!getStdFile(type,\n\t attr,\n\t allow_dash,\n\t log_header,\n\t &fd,\n\t &filename))\n\t{\n\t\treturn -1;\n\t}\n\n\t\t\/\/ if getStdFile came back with an FD, just return it\n\tif (fd != -1) {\n\t\treturn fd;\n\t}\n\n\t\t\/\/ otherwise, we need to perform an open on the name\n\t\t\/\/ we got back\n\tbool is_output = (type != SFT_IN);\n\tif( is_output ) {\n\t\tint flags = O_WRONLY | O_CREAT | O_TRUNC | O_APPEND;\n\t\tfd = safe_open_wrapper( filename.Value(), flags, 0666 );\n\t\tif( fd < 0 ) {\n\t\t\t\t\/\/ if failed, try again without O_TRUNC\n\t\t\tflags &= ~O_TRUNC;\n\t\t\tfd = safe_open_wrapper( filename.Value(), flags, 0666 );\n\t\t}\n\t} else {\n\t\tfd = safe_open_wrapper( filename.Value(), O_RDONLY );\n\t}\n\tif( fd < 0 ) {\n\t\tint open_errno = errno;\n\t\tchar const *errno_str = strerror( errno );\n\t\tMyString err_msg;\n\t\tconst char* phrase;\n\t\tif (type == SFT_IN) {\n\t\t\tphrase = \"standard input\";\n\t\t}\n\t\telse if (type == SFT_OUT) {\n\t\t\tphrase = \"standard output\";\n\t\t}\n\t\telse {\n\t\t\tphrase = \"standard error\";\n\t\t}\n\t\terr_msg.sprintf( \"Failed to open '%s' as %s: %s (errno %d)\",\n\t\t filename.Value(),\n\t\t phrase,\n\t\t errno_str,\n\t\t errno );\n\t\tdprintf( D_ALWAYS, \"%s\\n\", err_msg.Value() );\n\t\tStarter->jic->notifyStarterError( err_msg.Value(), true,\n\t\t is_output ? CONDOR_HOLD_CODE_UnableToOpenOutput :\n\t\t CONDOR_HOLD_CODE_UnableToOpenInput, open_errno );\n\t\treturn -1;\n\t}\n\tdprintf( (filename == NULL_FILE) ? D_FULLDEBUG : D_ALWAYS,\n\t \"%s: %s\\n\", log_header,\n\t filename.Value() );\n\treturn fd;\n}\n\nAdded support for stdout\/stderr to be >2G\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * 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\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"user_proc.h\"\n#include \"starter.h\"\n#include \"condor_attributes.h\"\n#include \"classad_helpers.h\"\n#include \"sig_name.h\"\n#include \"stream_handler.h\"\n#include \"subsystem_info.h\"\n\nextern CStarter *Starter;\n\n\n\/* UserProc class implementation *\/\n\nUserProc::~UserProc()\n{\n\tif( name ) {\n\t\tfree( name );\n\t}\n}\n\n\nvoid\nUserProc::initialize( void )\n{\n\tJobPid = -1;\n\texit_status = -1;\n\trequested_exit = false;\n\tm_proc_exited = false;\n\tjob_universe = 0; \/\/ we'll fill in a real value if we can...\n\tif( JobAd ) {\n\t\tinitKillSigs();\n\t\tif( JobAd->LookupInteger( ATTR_JOB_UNIVERSE, job_universe ) < 1 ) {\n\t\t\tjob_universe = 0;\n\t\t}\n\t}\n}\n\n\nvoid\nUserProc::initKillSigs( void )\n{\n\tint sig;\n\n\tsig = findSoftKillSig( JobAd );\n\tif( sig >= 0 ) {\n\t\tsoft_kill_sig = sig;\n\t} else {\n\t\tsoft_kill_sig = SIGTERM;\n\t}\n\n\tsig = findRmKillSig( JobAd );\n\tif( sig >= 0 ) {\n\t\trm_kill_sig = sig;\n\t} else {\n\t\trm_kill_sig = SIGTERM;\n\t}\n\n\tsig = findHoldKillSig( JobAd );\n\tif( sig >= 0 ) {\n\t\thold_kill_sig = sig;\n\t} else {\n\t\thold_kill_sig = SIGTERM;\n\t}\n\n\tconst char* tmp = signalName( soft_kill_sig );\n\tdprintf( D_FULLDEBUG, \"%s KillSignal: %d (%s)\\n\", \n\t\t\t name ? name : \"Main job\", soft_kill_sig, \n\t\t\t tmp ? tmp : \"Unknown\" );\n\n\ttmp = signalName( rm_kill_sig );\n\tdprintf( D_FULLDEBUG, \"%s RmKillSignal: %d (%s)\\n\", \n\t\t\t name ? name : \"Main job\", rm_kill_sig, \n\t\t\t tmp ? tmp : \"Unknown\" );\n\n\ttmp = signalName( hold_kill_sig );\n\tdprintf( D_FULLDEBUG, \"%s HoldKillSignal: %d (%s)\\n\", \n\t\t\t name ? name : \"Main job\", hold_kill_sig, \n\t\t\t tmp ? tmp : \"Unknown\" );\n}\n\n\nbool\nUserProc::JobReaper(int pid, int status)\n{\n\tif (JobPid == pid) {\n\t\tm_proc_exited = true;\n\t\texit_status = status;\n\t\tjob_exit_time.getTime();\n\t}\n\treturn m_proc_exited;\n}\n\n\nbool\nUserProc::PublishUpdateAd( ClassAd* ad )\n{\n\tchar buf[256];\n\n\tif( JobPid >= 0 ) { \n\t\tsprintf( buf, \"%s%s=%d\", name ? name : \"\", ATTR_JOB_PID,\n\t\t\t\t JobPid );\n\t\tad->Insert( buf );\n\t}\n\n\tif( job_start_time.seconds() > 0 ) {\n\t\tsprintf( buf, \"%s%s=%ld\", name ? name : \"\", ATTR_JOB_START_DATE,\n\t\t\t\t job_start_time.seconds() );\n\t\tad->Insert( buf );\n\t}\n\n\tif (m_proc_exited) {\n\n\t\tif( job_exit_time.seconds() > 0 ) {\n\t\t\tsprintf( buf, \"%s%s=%f\", name ? name : \"\", ATTR_JOB_DURATION, \n\t\t\t\t\t job_exit_time.difference(&job_start_time) );\n\t\t\tad->Insert( buf );\n\t\t}\n\n\t\t\t\/*\n\t\t\t If we have the exit status, we want to parse it and set\n\t\t\t some attributes which describe the status in a platform\n\t\t\t independent way. This way, we're sure we're analyzing\n\t\t\t the status integer with the platform-specific macros\n\t\t\t where it came from, instead of assuming that WIFEXITED()\n\t\t\t and friends will work correctly on a status integer we\n\t\t\t got back from a different platform.\n\t\t\t*\/\n\t\tif( WIFSIGNALED(exit_status) ) {\n\t\t\tsprintf( buf, \"%s%s = TRUE\", name ? name : \"\",\n\t\t\t\t\t ATTR_ON_EXIT_BY_SIGNAL );\n\t\t\tad->Insert( buf );\n\t\t\tsprintf( buf, \"%s%s = %d\", name ? name : \"\",\n\t\t\t\t\t ATTR_ON_EXIT_SIGNAL, WTERMSIG(exit_status) );\n\t\t\tad->Insert( buf );\n\t\t\tsprintf( buf, \"%s%s = \\\"died on %s\\\"\",\n\t\t\t\t\t name ? name : \"\", ATTR_EXIT_REASON,\n\t\t\t\t\t daemonCore->GetExceptionString(WTERMSIG(exit_status)) );\n\t\t\tad->Insert( buf );\n\t\t} else {\n\t\t\tsprintf( buf, \"%s%s = FALSE\", name ? name : \"\",\n\t\t\t\t\t ATTR_ON_EXIT_BY_SIGNAL );\n\t\t\tad->Insert( buf );\n\t\t\tsprintf( buf, \"%s%s = %d\", name ? name : \"\",\n\t\t\t\t\t ATTR_ON_EXIT_CODE, WEXITSTATUS(exit_status) );\n\t\t\tad->Insert( buf );\n\t\t}\n\t}\n\treturn true;\n}\n\n\nvoid\nUserProc::PublishToEnv( Env* proc_env )\n{\n\tif (m_proc_exited) {\n\t\t\t\/\/ TODO: what should these really be called? use\n\t\t\t\/\/ myDistro? mySubSystem? hard to say...\n\t\tMyString base;\n\t\tbase = \"_\";\n\t\tbase += myDistro->Get();\n\t\tbase += '_';\n\t\tif( name ) {\n\t\t\tbase += name;\n\t\t} else {\n\t\t\tbase += \"MAINJOB\";\n\t\t}\n\t\tbase += '_';\n\t\tbase.upper_case();\n \n\t\tMyString env_name;\n\n\t\tif( WIFSIGNALED(exit_status) ) {\n\t\t\tenv_name = base.GetCStr();\n\t\t\tenv_name += \"EXIT_SIGNAL\";\n\t\t\tproc_env->SetEnv( env_name.GetCStr(), WTERMSIG(exit_status) );\n\t\t} else {\n\t\t\tenv_name = base.GetCStr();\n\t\t\tenv_name += \"EXIT_CODE\";\n\t\t\tproc_env->SetEnv( env_name.GetCStr(), WEXITSTATUS(exit_status) );\n\t\t}\n\t}\n}\n\nbool\nUserProc::getStdFile( std_file_type type,\n const char* attr,\n bool allow_dash,\n const char* log_header,\n int* out_fd,\n MyString* out_name)\n{\n\t\t\/\/ we're going to return true on success, false on error.\n\t\t\/\/ if we succeed, then if we have an open FD that should\n\t\t\/\/ be passed down to the job, return it in the descriptor\n\t\t\/\/ argument. otherwise, return -1 in the descriptor\n\t\t\/\/ argument and return the name of the file that should\n\t\t\/\/ be opened for the child in the name argument\n\tASSERT(out_fd != NULL);\n\tASSERT(out_name != NULL);\n\t*out_fd = -1;\n\n\tconst char* filename;\n\tbool wants_stream = false;\n\tconst char* stream_name = NULL;\n\tconst char* phrase = NULL;\n\tbool is_output = true;\n\tbool is_null_file = false;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Initialize some settings depending on the type\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tswitch( type ) {\n\tcase SFT_IN:\n\t\tis_output = false;\n\t\tphrase = \"standard input\";\n\t\tstream_name = \"stdin\";\n\t\tbreak;\n\tcase SFT_OUT:\n\t\tis_output = true;\n\t\tphrase = \"standard output\";\n\t\tstream_name = \"stdout\";\n\t\tbreak;\n\tcase SFT_ERR:\n\t\tis_output = true;\n\t\tphrase = \"standard error\";\n\t\tstream_name = \"stderr\";\n\t\tbreak;\n\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Figure out what we're trying to open, if anything\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tif( attr ) {\n\t\tfilename = Starter->jic->getJobStdFile( attr );\n\t\twants_stream = Starter->jic->streamStdFile( attr );\n\t} else {\n\t\tswitch( type ) {\n\t\tcase SFT_IN:\n\t\t\tfilename = Starter->jic->jobInputFilename();\n\t\t\twants_stream = Starter->jic->streamInput();\n\t\t\tbreak;\n\t\tcase SFT_OUT:\n\t\t\tfilename = Starter->jic->jobOutputFilename();\n\t\t\twants_stream = Starter->jic->streamOutput();\n\t\t\tbreak;\n\t\tcase SFT_ERR:\n\t\t\tfilename = Starter->jic->jobErrorFilename();\n\t\t\twants_stream = Starter->jic->streamError();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif( ! filename ) {\n\t\t\t\/\/ If there's nothing specified, we always want to open\n\t\t\t\/\/ the system-appropriate NULL file (\/dev\/null or NUL).\n\t\t\t\/\/ Otherwise, we can mostly treat this as if the job\n\t\t\t\/\/ defined a real local filename. For the few cases were\n\t\t\t\/\/ we have to behave differently, record it in a bool. \n\t\tfilename = NULL_FILE;\n\t\tis_null_file = true;\n\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Deal with special cases\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Use streaming I\/O\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tif( wants_stream && ! is_null_file ) {\n\t\tStreamHandler *handler = new StreamHandler;\n\t\tif( !handler->Init(filename, stream_name, is_output) ) {\n\t\t\tMyString err_msg;\n\t\t\terr_msg.sprintf( \"unable to establish %s stream\", phrase );\n\t\t\tStarter->jic->notifyStarterError( err_msg.Value(), true,\n\t\t\t is_output ? CONDOR_HOLD_CODE_UnableToOpenOutputStream :\n\t\t\t CONDOR_HOLD_CODE_UnableToOpenInputStream, 0 );\n\t\t\treturn false;\n\t\t}\n\t\t*out_fd = handler->GetJobPipe();\n\t\tdprintf( D_ALWAYS, \"%s: streaming from remote file %s\\n\",\n\t\t\t\t log_header, filename );\n\t\treturn true;\n\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Use the starter's equivalent fd\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tif( allow_dash && (filename[0] == '-') && !filename[1] )\n\t{\n\t\t\t\/\/ use the starter's fd\n\t\tswitch( type ) {\n\t\tcase SFT_IN:\n\t\t\t*out_fd = Starter->starterStdinFd();\n\t\t\tdprintf( D_ALWAYS, \"%s: using STDIN of %s\\n\", log_header,\n\t\t\t\t\t mySubSystem->getName() );\n\t\t\tbreak;\n\t\tcase SFT_OUT:\n\t\t\t*out_fd = Starter->starterStdoutFd();\n\t\t\tdprintf( D_ALWAYS, \"%s: using STDOUT of %s\\n\", log_header,\n\t\t\t\t\t mySubSystem->getName() );\n\t\t\tbreak;\n\t\tcase SFT_ERR:\n\t\t\t*out_fd = Starter->starterStderrFd();\n\t\t\tdprintf( D_ALWAYS, \"%s: using STDERR of %s\\n\", log_header,\n\t\t\t\t\t mySubSystem->getName() );\n\t\t\tbreak;\n\t\t}\n\t\treturn true;\n\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ The regular case of a local file \n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t*out_name = filename;\n\treturn true;\n}\n\nint\nUserProc::openStdFile( std_file_type type,\n const char* attr, \n bool allow_dash,\n const char* log_header)\n{\n\t\t\/\/ most of the work gets done by our helper, getStdFile\n\tint fd;\n\tMyString filename;\n\tif (!getStdFile(type,\n\t attr,\n\t allow_dash,\n\t log_header,\n\t &fd,\n\t &filename))\n\t{\n\t\treturn -1;\n\t}\n\n\t\t\/\/ if getStdFile came back with an FD, just return it\n\tif (fd != -1) {\n\t\treturn fd;\n\t}\n\n\t\t\/\/ otherwise, we need to perform an open on the name\n\t\t\/\/ we got back\n\tbool is_output = (type != SFT_IN);\n\tif( is_output ) {\n\t\tint flags = O_WRONLY | O_CREAT | O_TRUNC | O_APPEND | O_LARGEFILE;\n\t\tfd = safe_open_wrapper( filename.Value(), flags, 0666 );\n\t\tif( fd < 0 ) {\n\t\t\t\t\/\/ if failed, try again without O_TRUNC\n\t\t\tflags &= ~O_TRUNC;\n\t\t\tfd = safe_open_wrapper( filename.Value(), flags, 0666 );\n\t\t}\n\t} else {\n\t\tfd = safe_open_wrapper( filename.Value(), O_RDONLY | O_LARGEFILE );\n\t}\n\tif( fd < 0 ) {\n\t\tint open_errno = errno;\n\t\tchar const *errno_str = strerror( errno );\n\t\tMyString err_msg;\n\t\tconst char* phrase;\n\t\tif (type == SFT_IN) {\n\t\t\tphrase = \"standard input\";\n\t\t}\n\t\telse if (type == SFT_OUT) {\n\t\t\tphrase = \"standard output\";\n\t\t}\n\t\telse {\n\t\t\tphrase = \"standard error\";\n\t\t}\n\t\terr_msg.sprintf( \"Failed to open '%s' as %s: %s (errno %d)\",\n\t\t filename.Value(),\n\t\t phrase,\n\t\t errno_str,\n\t\t errno );\n\t\tdprintf( D_ALWAYS, \"%s\\n\", err_msg.Value() );\n\t\tStarter->jic->notifyStarterError( err_msg.Value(), true,\n\t\t is_output ? CONDOR_HOLD_CODE_UnableToOpenOutput :\n\t\t CONDOR_HOLD_CODE_UnableToOpenInput, open_errno );\n\t\treturn -1;\n\t}\n\tdprintf( (filename == NULL_FILE) ? D_FULLDEBUG : D_ALWAYS,\n\t \"%s: %s\\n\", log_header,\n\t filename.Value() );\n\treturn fd;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Flutter 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 \"flutter\/lib\/ui\/compositing\/scene_host.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"flutter\/flow\/export_node.h\"\n#include \"flutter\/flow\/view_holder.h\"\n#include \"flutter\/fml\/thread_local.h\"\n#include \"flutter\/lib\/ui\/ui_dart_state.h\"\n\nnamespace {\n\nusing SceneHostBindings = std::unordered_map;\n\nFML_THREAD_LOCAL fml::ThreadLocal tls_scene_host_bindings([](intptr_t value) {\n delete reinterpret_cast(value);\n});\n\nvoid SceneHost_constructor(Dart_NativeArguments args) {\n tonic::DartCallConstructor(&SceneHost::Create, args);\n}\n\nvoid SceneHost_constructorViewHolderToken(Dart_NativeArguments args) {\n \/\/ This UI thread \/ Isolate contains at least 1 SceneHost. Initialize the\n \/\/ per-Isolate bindings.\n if (tls_scene_host_bindings.Get() == 0) {\n tls_scene_host_bindings.Set(\n reinterpret_cast(new SceneHostBindings()));\n }\n\n tonic::DartCallConstructor(&SceneHost::CreateViewHolder, args);\n}\n\nSceneHost* GetSceneHost(scenic::ResourceId id) {\n auto* bindings =\n reinterpret_cast(tls_scene_host_bindings.Get());\n FML_DCHECK(bindings);\n\n auto binding = bindings->find(id);\n if (binding != bindings->end()) {\n return binding->second;\n }\n\n return nullptr;\n}\n\nvoid InvokeDartClosure(tonic::DartPersistentValue* closure) {\n if (closure) {\n std::shared_ptr dart_state = closure->dart_state().lock();\n if (!dart_state) {\n return;\n }\n\n tonic::DartState::Scope scope(dart_state);\n tonic::DartInvoke(closure->value(), {});\n }\n}\n\ntemplate \nvoid InvokeDartFunction(tonic::DartPersistentValue* function, T& arg) {\n if (function) {\n std::shared_ptr dart_state =\n function->dart_state().lock();\n if (!dart_state) {\n return;\n }\n\n tonic::DartState::Scope scope(dart_state);\n tonic::DartInvoke(function->value(), {tonic::ToDart(arg)});\n }\n}\n\n} \/\/ namespace\n\nnamespace flutter {\n\nIMPLEMENT_WRAPPERTYPEINFO(ui, SceneHost);\n\n#define FOR_EACH_BINDING(V) \\\n V(SceneHost, dispose) \\\n V(SceneHost, setProperties)\n\nFOR_EACH_BINDING(DART_NATIVE_CALLBACK)\n\nvoid SceneHost::RegisterNatives(tonic::DartLibraryNatives* natives) {\n natives->Register({{\"SceneHost_constructor\", SceneHost_constructor, 2, true},\n FOR_EACH_BINDING(DART_REGISTER_NATIVE)});\n natives->Register({{\"SceneHost_constructorViewHolderToken\",\n SceneHost_constructorViewHolderToken, 5, true},\n FOR_EACH_BINDING(DART_REGISTER_NATIVE)});\n}\n\nfml::RefPtr SceneHost::Create(\n fml::RefPtr exportTokenHandle) {\n return fml::MakeRefCounted(exportTokenHandle);\n}\n\nfml::RefPtr SceneHost::CreateViewHolder(\n fml::RefPtr viewHolderTokenHandle,\n Dart_Handle viewConnectedCallback,\n Dart_Handle viewDisconnectedCallback,\n Dart_Handle viewStateChangedCallback) {\n return fml::MakeRefCounted(\n viewHolderTokenHandle, viewConnectedCallback, viewDisconnectedCallback,\n viewStateChangedCallback);\n}\n\nSceneHost::SceneHost(fml::RefPtr exportTokenHandle)\n : gpu_task_runner_(\n UIDartState::Current()->GetTaskRunners().GetGPUTaskRunner()),\n id_(fsl::GetKoid(exportTokenHandle->handle())),\n use_view_holder_(false) {\n gpu_task_runner_->PostTask(\n [id = id_, handle = std::move(exportTokenHandle)]() {\n auto export_token = zx::eventpair(handle->ReleaseHandle());\n flow::ExportNode::Create(id, std::move(export_token));\n });\n}\n\nSceneHost::SceneHost(fml::RefPtr viewHolderTokenHandle,\n Dart_Handle viewConnectedCallback,\n Dart_Handle viewDisconnectedCallback,\n Dart_Handle viewStateChangedCallback)\n : gpu_task_runner_(\n UIDartState::Current()->GetTaskRunners().GetGPUTaskRunner()),\n id_(fsl::GetKoid(viewHolderTokenHandle->handle())),\n use_view_holder_(true) {\n if (Dart_IsClosure(viewConnectedCallback)) {\n view_connected_callback_ = std::make_unique(\n UIDartState::Current(), viewConnectedCallback);\n }\n if (Dart_IsClosure(viewDisconnectedCallback)) {\n view_disconnected_callback_ = std::make_unique(\n UIDartState::Current(), viewDisconnectedCallback);\n }\n if (Dart_IsClosure(viewConnectedCallback)) {\n view_state_changed_callback_ = std::make_unique(\n UIDartState::Current(), viewStateChangedCallback);\n }\n\n auto bind_callback = [scene_host = this](scenic::ResourceId id) {\n auto* bindings =\n reinterpret_cast(tls_scene_host_bindings.Get());\n FML_DCHECK(bindings);\n FML_DCHECK(bindings->find(id) == bindings->end());\n\n bindings->emplace(std::make_pair(id, scene_host));\n };\n\n auto ui_task_runner =\n UIDartState::Current()->GetTaskRunners().GetUITaskRunner();\n gpu_task_runner_->PostTask([id = id_,\n ui_task_runner = std::move(ui_task_runner),\n handle = std::move(viewHolderTokenHandle),\n bind_callback = std::move(bind_callback)]() {\n auto view_holder_token =\n scenic::ToViewHolderToken(zx::eventpair(handle->ReleaseHandle()));\n flow::ViewHolder::Create(id, std::move(ui_task_runner),\n std::move(view_holder_token),\n std::move(bind_callback));\n });\n}\n\nSceneHost::~SceneHost() {\n if (use_view_holder_) {\n auto* bindings =\n reinterpret_cast(tls_scene_host_bindings.Get());\n FML_DCHECK(bindings);\n bindings->erase(id_);\n\n gpu_task_runner_->PostTask([id = id_]() { flow::ViewHolder::Destroy(id); });\n } else {\n gpu_task_runner_->PostTask([id = id_]() { flow::ExportNode::Destroy(id); });\n }\n}\n\nvoid SceneHost::OnViewConnected(scenic::ResourceId id) {\n auto* scene_host = GetSceneHost(id);\n\n if (scene_host) {\n InvokeDartClosure(scene_host->view_connected_callback_.get());\n }\n}\n\nvoid SceneHost::OnViewDisconnected(scenic::ResourceId id) {\n auto* scene_host = GetSceneHost(id);\n\n if (scene_host) {\n InvokeDartClosure(scene_host->view_disconnected_callback_.get());\n }\n}\n\nvoid SceneHost::OnViewStateChanged(scenic::ResourceId id, bool state) {\n auto* scene_host = GetSceneHost(id);\n\n if (scene_host) {\n InvokeDartFunction(scene_host->view_state_changed_callback_.get(), state);\n }\n}\n\nvoid SceneHost::setProperties(double width,\n double height,\n double insetTop,\n double insetRight,\n double insetBottom,\n double insetLeft,\n bool focusable) {\n FML_DCHECK(use_view_holder_);\n\n gpu_task_runner_->PostTask([id = id_, width, height, insetTop, insetRight,\n insetBottom, insetLeft, focusable]() {\n auto* view_holder = flow::ViewHolder::FromId(id);\n FML_DCHECK(view_holder);\n\n view_holder->SetProperties(width, height, insetTop, insetRight, insetBottom,\n insetLeft, focusable);\n });\n}\n\nvoid SceneHost::dispose() {\n ClearDartWrapper();\n}\n\n} \/\/ namespace flutter\n[fuchsia] Add flutter:: to scene_host.cc (#8549)\/\/ Copyright 2013 The Flutter 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 \"flutter\/lib\/ui\/compositing\/scene_host.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"flutter\/flow\/export_node.h\"\n#include \"flutter\/flow\/view_holder.h\"\n#include \"flutter\/fml\/thread_local.h\"\n#include \"flutter\/lib\/ui\/ui_dart_state.h\"\n\nnamespace {\n\nusing SceneHostBindings = std::unordered_map;\n\nFML_THREAD_LOCAL fml::ThreadLocal tls_scene_host_bindings([](intptr_t value) {\n delete reinterpret_cast(value);\n});\n\nvoid SceneHost_constructor(Dart_NativeArguments args) {\n tonic::DartCallConstructor(&flutter::SceneHost::Create, args);\n}\n\nvoid SceneHost_constructorViewHolderToken(Dart_NativeArguments args) {\n \/\/ This UI thread \/ Isolate contains at least 1 SceneHost. Initialize the\n \/\/ per-Isolate bindings.\n if (tls_scene_host_bindings.Get() == 0) {\n tls_scene_host_bindings.Set(\n reinterpret_cast(new SceneHostBindings()));\n }\n\n tonic::DartCallConstructor(&flutter::SceneHost::CreateViewHolder, args);\n}\n\nflutter::SceneHost* GetSceneHost(scenic::ResourceId id) {\n auto* bindings =\n reinterpret_cast(tls_scene_host_bindings.Get());\n FML_DCHECK(bindings);\n\n auto binding = bindings->find(id);\n if (binding != bindings->end()) {\n return binding->second;\n }\n\n return nullptr;\n}\n\nvoid InvokeDartClosure(tonic::DartPersistentValue* closure) {\n if (closure) {\n std::shared_ptr dart_state = closure->dart_state().lock();\n if (!dart_state) {\n return;\n }\n\n tonic::DartState::Scope scope(dart_state);\n tonic::DartInvoke(closure->value(), {});\n }\n}\n\ntemplate \nvoid InvokeDartFunction(tonic::DartPersistentValue* function, T& arg) {\n if (function) {\n std::shared_ptr dart_state =\n function->dart_state().lock();\n if (!dart_state) {\n return;\n }\n\n tonic::DartState::Scope scope(dart_state);\n tonic::DartInvoke(function->value(), {tonic::ToDart(arg)});\n }\n}\n\n} \/\/ namespace\n\nnamespace flutter {\n\nIMPLEMENT_WRAPPERTYPEINFO(ui, SceneHost);\n\n#define FOR_EACH_BINDING(V) \\\n V(SceneHost, dispose) \\\n V(SceneHost, setProperties)\n\nFOR_EACH_BINDING(DART_NATIVE_CALLBACK)\n\nvoid SceneHost::RegisterNatives(tonic::DartLibraryNatives* natives) {\n natives->Register({{\"SceneHost_constructor\", SceneHost_constructor, 2, true},\n FOR_EACH_BINDING(DART_REGISTER_NATIVE)});\n natives->Register({{\"SceneHost_constructorViewHolderToken\",\n SceneHost_constructorViewHolderToken, 5, true},\n FOR_EACH_BINDING(DART_REGISTER_NATIVE)});\n}\n\nfml::RefPtr SceneHost::Create(\n fml::RefPtr exportTokenHandle) {\n return fml::MakeRefCounted(exportTokenHandle);\n}\n\nfml::RefPtr SceneHost::CreateViewHolder(\n fml::RefPtr viewHolderTokenHandle,\n Dart_Handle viewConnectedCallback,\n Dart_Handle viewDisconnectedCallback,\n Dart_Handle viewStateChangedCallback) {\n return fml::MakeRefCounted(\n viewHolderTokenHandle, viewConnectedCallback, viewDisconnectedCallback,\n viewStateChangedCallback);\n}\n\nSceneHost::SceneHost(fml::RefPtr exportTokenHandle)\n : gpu_task_runner_(\n UIDartState::Current()->GetTaskRunners().GetGPUTaskRunner()),\n id_(fsl::GetKoid(exportTokenHandle->handle())),\n use_view_holder_(false) {\n gpu_task_runner_->PostTask(\n [id = id_, handle = std::move(exportTokenHandle)]() {\n auto export_token = zx::eventpair(handle->ReleaseHandle());\n flow::ExportNode::Create(id, std::move(export_token));\n });\n}\n\nSceneHost::SceneHost(fml::RefPtr viewHolderTokenHandle,\n Dart_Handle viewConnectedCallback,\n Dart_Handle viewDisconnectedCallback,\n Dart_Handle viewStateChangedCallback)\n : gpu_task_runner_(\n UIDartState::Current()->GetTaskRunners().GetGPUTaskRunner()),\n id_(fsl::GetKoid(viewHolderTokenHandle->handle())),\n use_view_holder_(true) {\n if (Dart_IsClosure(viewConnectedCallback)) {\n view_connected_callback_ = std::make_unique(\n UIDartState::Current(), viewConnectedCallback);\n }\n if (Dart_IsClosure(viewDisconnectedCallback)) {\n view_disconnected_callback_ = std::make_unique(\n UIDartState::Current(), viewDisconnectedCallback);\n }\n if (Dart_IsClosure(viewConnectedCallback)) {\n view_state_changed_callback_ = std::make_unique(\n UIDartState::Current(), viewStateChangedCallback);\n }\n\n auto bind_callback = [scene_host = this](scenic::ResourceId id) {\n auto* bindings =\n reinterpret_cast(tls_scene_host_bindings.Get());\n FML_DCHECK(bindings);\n FML_DCHECK(bindings->find(id) == bindings->end());\n\n bindings->emplace(std::make_pair(id, scene_host));\n };\n\n auto ui_task_runner =\n UIDartState::Current()->GetTaskRunners().GetUITaskRunner();\n gpu_task_runner_->PostTask([id = id_,\n ui_task_runner = std::move(ui_task_runner),\n handle = std::move(viewHolderTokenHandle),\n bind_callback = std::move(bind_callback)]() {\n auto view_holder_token =\n scenic::ToViewHolderToken(zx::eventpair(handle->ReleaseHandle()));\n flow::ViewHolder::Create(id, std::move(ui_task_runner),\n std::move(view_holder_token),\n std::move(bind_callback));\n });\n}\n\nSceneHost::~SceneHost() {\n if (use_view_holder_) {\n auto* bindings =\n reinterpret_cast(tls_scene_host_bindings.Get());\n FML_DCHECK(bindings);\n bindings->erase(id_);\n\n gpu_task_runner_->PostTask([id = id_]() { flow::ViewHolder::Destroy(id); });\n } else {\n gpu_task_runner_->PostTask([id = id_]() { flow::ExportNode::Destroy(id); });\n }\n}\n\nvoid SceneHost::OnViewConnected(scenic::ResourceId id) {\n auto* scene_host = GetSceneHost(id);\n\n if (scene_host) {\n InvokeDartClosure(scene_host->view_connected_callback_.get());\n }\n}\n\nvoid SceneHost::OnViewDisconnected(scenic::ResourceId id) {\n auto* scene_host = GetSceneHost(id);\n\n if (scene_host) {\n InvokeDartClosure(scene_host->view_disconnected_callback_.get());\n }\n}\n\nvoid SceneHost::OnViewStateChanged(scenic::ResourceId id, bool state) {\n auto* scene_host = GetSceneHost(id);\n\n if (scene_host) {\n InvokeDartFunction(scene_host->view_state_changed_callback_.get(), state);\n }\n}\n\nvoid SceneHost::setProperties(double width,\n double height,\n double insetTop,\n double insetRight,\n double insetBottom,\n double insetLeft,\n bool focusable) {\n FML_DCHECK(use_view_holder_);\n\n gpu_task_runner_->PostTask([id = id_, width, height, insetTop, insetRight,\n insetBottom, insetLeft, focusable]() {\n auto* view_holder = flow::ViewHolder::FromId(id);\n FML_DCHECK(view_holder);\n\n view_holder->SetProperties(width, height, insetTop, insetRight, insetBottom,\n insetLeft, focusable);\n });\n}\n\nvoid SceneHost::dispose() {\n ClearDartWrapper();\n}\n\n} \/\/ namespace flutter\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * 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#ifdef _NO_CONDOR_\n#include \/\/ for fstat, struct stat\n#include \/\/ for fstat, struct stat\n#include \/\/ for fstat, struct stat\n#include \/\/ for _POSIX_PATH_MAX\n#include \/\/ for strcpy\n#include \/\/ for atol\n#include \/\/ for assert\n#include \/\/ for errno\n#include \/\/ for syslog, LOG_ERR, LOG_DEBUG\n#else\n#include \"condor_common.h\"\n#endif\n\n#include \"ClassAdLogEntry.h\"\n#include \"ClassAdLogProber.h\"\n#include \"ClassAdLogParser.h\"\n\n\/\/! constructor\nClassAdLogProber::ClassAdLogProber()\n{\n\tlast_mod_time = 0;\n\tlast_size = 0;\n\tlast_seq_num = 0;\n\tlast_creation_time = 0;\n\t\n\tcur_probed_mod_time = 0;\n\tcur_probed_size = 0;\n\tcur_probed_seq_num = 0;\n\tcur_probed_creation_time = 0;\n\tjob_queue_name[0] = '\\0';\n}\n\n\/\/! destructor\nClassAdLogProber::~ClassAdLogProber()\n{}\n\n\/\/**************************************************************************\n\/\/ Accessors\n\/\/**************************************************************************\nvoid\nClassAdLogProber::setJobQueueName(const char* jqn)\n{\n\tassert(jqn);\n\tstrcpy(job_queue_name, jqn);\n}\n\nchar*\nClassAdLogProber::getJobQueueName()\n{\n\treturn job_queue_name;\n}\n\nvoid\nClassAdLogProber::setLastModifiedTime(time_t t)\n{\n\tlast_mod_time = t;\n}\n\n\ntime_t\nClassAdLogProber::getLastModifiedTime()\n{\n\treturn last_mod_time;\n}\n\nvoid\nClassAdLogProber::setLastSize(size_t s)\n{\n\tlast_size = s;\n}\n\n\nsize_t\nClassAdLogProber::getLastSize()\n{\n\treturn last_size;\n}\n\nlong int\nClassAdLogProber::getLastSequenceNumber() \n{\n\treturn last_seq_num;\n}\n\nvoid\nClassAdLogProber::setLastSequenceNumber(long int seq_num) \n{\n\tlast_seq_num = seq_num;\n}\n\ntime_t\nClassAdLogProber::getLastCreationTime() \n{\n\treturn last_creation_time;\n}\n\nvoid\nClassAdLogProber::setLastCreationTime(time_t ctime) \n{\n\tlast_creation_time = ctime;\n}\n\nlong int\nClassAdLogProber::getCurProbedSequenceNumber() {\n\treturn cur_probed_seq_num;\n}\n\nlong int\nClassAdLogProber::getCurProbedCreationTime() {\n\treturn cur_probed_creation_time;\n}\n\n\n\n\/\/! probe job_queue.log file\nProbeResultType\nClassAdLogProber::probe(ClassAdLogEntry *curCALogEntry,\n\t\t\t FILE * job_queue_fd)\nProber::probe(ClassAdLogEntry *curCALogEntry,\n\t\t\t FILE* job_queue_fp)\n{\n\tFileOpErrCode st;\n\tint op_type;\n\tstruct stat filestat;\n\tint job_queue_fd = fileno(job_queue_fp);\n\t\/\/TODO: uncomment and possibly change\n\t\/* \n\tif (job_queue_fd == -1) {\n\t\treturn PROBE_ERROR;\n\t}\n\t*\/\n\n\t\/\/TODO: should use condor's StatInfo instead.\n\tif (fstat(job_queue_fd, &filestat) == -1)\n#ifdef _NO_CONDOR_\n\t\tsyslog(LOG_ERR, \"ERROR: calling stat(): errno=%d (%m)\", errno);\n\t\n\tsyslog(LOG_DEBUG, \"=== Current Probing Information ===\");\n\tsyslog(LOG_DEBUG,\n\t\t \"fsize: %ld\\t\\tmtime: %ld\", \n\t\t (long)filestat.st_size, (long)filestat.st_mtime);\n#else\n\t\tdprintf(D_ALWAYS,\"ERROR: calling stat()\\n\");\n\t\n\tdprintf(D_FULLDEBUG, \"=== Current Probing Information ===\\n\");\n\tdprintf(D_FULLDEBUG, \"fsize: %ld\\t\\tmtime: %ld\\n\", \n\t\t\t\t(long)filestat.st_size, (long)filestat.st_mtime);\n#endif\n\n\t\/\/ get the new state\n\tcur_probed_mod_time = filestat.st_mtime;\n\tcur_probed_size = filestat.st_size;\n\n\tClassAdLogParser caLogParser;\n\t\n\tcaLogParser.setFilePointer(job_queue_fp);\n\tcaLogParser.setNextOffset(0);\n\tst = caLogParser.readLogEntry(op_type);\n\n\tif (FILE_FATAL_ERROR == st) {\n\t\treturn PROBE_FATAL_ERROR;\n\t}\n\tif (st != FILE_READ_SUCCESS) {\n\t\treturn PROBE_ERROR;\n\t}\n\n\tif ( caLogParser.getCurCALogEntry()->op_type !=\n\t\t CondorLogOp_LogHistoricalSequenceNumber )\n\t{\n#ifdef _NO_CONDOR_\n\t\tsyslog(LOG_ERR,\n\t\t\t \"ERROR: prober expects first classad log entry to be \"\n\t\t\t \"type %d, but sees %d instead.\",\n\t\t\t CondorLogOp_LogHistoricalSequenceNumber,\n\t\t\t caLogParser.getCurCALogEntry()->op_type);\n#else\n\t\tdprintf(D_ALWAYS,\n\t\t\t\t\"ERROR: quill prober expects first classad log entry to be \"\n\t\t\t\t\"type %d, but sees %d instead.\",\n\t\t\t\tCondorLogOp_LogHistoricalSequenceNumber,\n\t\t\t\tcaLogParser.getCurCALogEntry()->op_type);\n#endif\n\t\treturn PROBE_FATAL_ERROR;\n\t}\n\n#ifdef _NO_CONDOR_\n\tsyslog(LOG_DEBUG,\n\t\t \"first log entry: %s %s %s\", \n\t\t ((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->key,\n\t\t ((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->name,\n\t\t ((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->value);\n#else\n\tdprintf(D_FULLDEBUG, \"first log entry: %s %s %s\\n\", \n\t\t\t((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->key,\n\t\t\t((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->name,\n\t\t\t((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->value);\n#endif\n\tcur_probed_seq_num = \n\t\tatol(((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->key);\n\tcur_probed_creation_time = \n\t\tatol(((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->value);\n\n\tif (last_size == 0) {\n\t\t\t\/\/ starting phase\n\t\treturn INIT_QUILL;\n\t}\t\n\n\tif(cur_probed_seq_num != last_seq_num) {\n\t\treturn COMPRESSED;\n\t}\n\n\tcaLogParser.setNextOffset(curCALogEntry->offset);\n\tst = caLogParser.readLogEntry(op_type);\n\t\n\tif (FILE_FATAL_ERROR == st) {\n\t\treturn PROBE_FATAL_ERROR;\n\t}\n\tif (st != FILE_READ_EOF && st != FILE_READ_SUCCESS) {\n\t\treturn PROBE_ERROR;\n\t}\n\t\t\n\n\tif((filestat.st_size == last_size) && \n\t caLogParser.getCurCALogEntry()->equal(curCALogEntry)) {\n\t\t\t\/\/ File size and contents stay the same\n\t\treturn NO_CHANGE;\n\t}\n\telse if((filestat.st_size > last_size) &&\n\t\t\tcaLogParser.getCurCALogEntry()->equal(curCALogEntry)) {\n\t\t\t\/\/ File has been increased and new entries have been added\n\t\treturn ADDITION;\n\t}\n\t\t\/\/if it wasn't captured by any of the above cases, \n\t\t\/\/it must have been an error\n\treturn PROBE_ERROR;\t\t\n}\n\nvoid\nClassAdLogProber::incrementProbeInfo() {\n\t\/\/ store the currently probed stat\n\tlast_mod_time = cur_probed_mod_time;\n\tlast_size = cur_probed_size;\n\n\tlast_seq_num = cur_probed_seq_num;\n\tlast_creation_time = cur_probed_creation_time;\n}\nFix bad merge of #1909\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * 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#ifdef _NO_CONDOR_\n#include \/\/ for fstat, struct stat\n#include \/\/ for fstat, struct stat\n#include \/\/ for fstat, struct stat\n#include \/\/ for _POSIX_PATH_MAX\n#include \/\/ for strcpy\n#include \/\/ for atol\n#include \/\/ for assert\n#include \/\/ for errno\n#include \/\/ for syslog, LOG_ERR, LOG_DEBUG\n#else\n#include \"condor_common.h\"\n#endif\n\n#include \"ClassAdLogEntry.h\"\n#include \"ClassAdLogProber.h\"\n#include \"ClassAdLogParser.h\"\n\n\/\/! constructor\nClassAdLogProber::ClassAdLogProber()\n{\n\tlast_mod_time = 0;\n\tlast_size = 0;\n\tlast_seq_num = 0;\n\tlast_creation_time = 0;\n\t\n\tcur_probed_mod_time = 0;\n\tcur_probed_size = 0;\n\tcur_probed_seq_num = 0;\n\tcur_probed_creation_time = 0;\n\tjob_queue_name[0] = '\\0';\n}\n\n\/\/! destructor\nClassAdLogProber::~ClassAdLogProber()\n{}\n\n\/\/**************************************************************************\n\/\/ Accessors\n\/\/**************************************************************************\nvoid\nClassAdLogProber::setJobQueueName(const char* jqn)\n{\n\tassert(jqn);\n\tstrcpy(job_queue_name, jqn);\n}\n\nchar*\nClassAdLogProber::getJobQueueName()\n{\n\treturn job_queue_name;\n}\n\nvoid\nClassAdLogProber::setLastModifiedTime(time_t t)\n{\n\tlast_mod_time = t;\n}\n\n\ntime_t\nClassAdLogProber::getLastModifiedTime()\n{\n\treturn last_mod_time;\n}\n\nvoid\nClassAdLogProber::setLastSize(size_t s)\n{\n\tlast_size = s;\n}\n\n\nsize_t\nClassAdLogProber::getLastSize()\n{\n\treturn last_size;\n}\n\nlong int\nClassAdLogProber::getLastSequenceNumber() \n{\n\treturn last_seq_num;\n}\n\nvoid\nClassAdLogProber::setLastSequenceNumber(long int seq_num) \n{\n\tlast_seq_num = seq_num;\n}\n\ntime_t\nClassAdLogProber::getLastCreationTime() \n{\n\treturn last_creation_time;\n}\n\nvoid\nClassAdLogProber::setLastCreationTime(time_t ctime) \n{\n\tlast_creation_time = ctime;\n}\n\nlong int\nClassAdLogProber::getCurProbedSequenceNumber() {\n\treturn cur_probed_seq_num;\n}\n\nlong int\nClassAdLogProber::getCurProbedCreationTime() {\n\treturn cur_probed_creation_time;\n}\n\n\n\n\/\/! probe job_queue.log file\nProbeResultType\nClassAdLogProber::probe(ClassAdLogEntry *curCALogEntry,\n\t\t\t FILE * job_queue_fp)\n{\n\tFileOpErrCode st;\n\tint op_type;\n\tstruct stat filestat;\n\tint job_queue_fd = fileno(job_queue_fp);\n\t\/\/TODO: uncomment and possibly change\n\t\/* \n\tif (job_queue_fd == -1) {\n\t\treturn PROBE_ERROR;\n\t}\n\t*\/\n\n\t\/\/TODO: should use condor's StatInfo instead.\n\tif (fstat(job_queue_fd, &filestat) == -1)\n#ifdef _NO_CONDOR_\n\t\tsyslog(LOG_ERR, \"ERROR: calling stat(): errno=%d (%m)\", errno);\n\t\n\tsyslog(LOG_DEBUG, \"=== Current Probing Information ===\");\n\tsyslog(LOG_DEBUG,\n\t\t \"fsize: %ld\\t\\tmtime: %ld\", \n\t\t (long)filestat.st_size, (long)filestat.st_mtime);\n#else\n\t\tdprintf(D_ALWAYS,\"ERROR: calling stat()\\n\");\n\t\n\tdprintf(D_FULLDEBUG, \"=== Current Probing Information ===\\n\");\n\tdprintf(D_FULLDEBUG, \"fsize: %ld\\t\\tmtime: %ld\\n\", \n\t\t\t\t(long)filestat.st_size, (long)filestat.st_mtime);\n#endif\n\n\t\/\/ get the new state\n\tcur_probed_mod_time = filestat.st_mtime;\n\tcur_probed_size = filestat.st_size;\n\n\tClassAdLogParser caLogParser;\n\t\n\tcaLogParser.setFilePointer(job_queue_fp);\n\tcaLogParser.setNextOffset(0);\n\tst = caLogParser.readLogEntry(op_type);\n\n\tif (FILE_FATAL_ERROR == st) {\n\t\treturn PROBE_FATAL_ERROR;\n\t}\n\tif (st != FILE_READ_SUCCESS) {\n\t\treturn PROBE_ERROR;\n\t}\n\n\tif ( caLogParser.getCurCALogEntry()->op_type !=\n\t\t CondorLogOp_LogHistoricalSequenceNumber )\n\t{\n#ifdef _NO_CONDOR_\n\t\tsyslog(LOG_ERR,\n\t\t\t \"ERROR: prober expects first classad log entry to be \"\n\t\t\t \"type %d, but sees %d instead.\",\n\t\t\t CondorLogOp_LogHistoricalSequenceNumber,\n\t\t\t caLogParser.getCurCALogEntry()->op_type);\n#else\n\t\tdprintf(D_ALWAYS,\n\t\t\t\t\"ERROR: quill prober expects first classad log entry to be \"\n\t\t\t\t\"type %d, but sees %d instead.\",\n\t\t\t\tCondorLogOp_LogHistoricalSequenceNumber,\n\t\t\t\tcaLogParser.getCurCALogEntry()->op_type);\n#endif\n\t\treturn PROBE_FATAL_ERROR;\n\t}\n\n#ifdef _NO_CONDOR_\n\tsyslog(LOG_DEBUG,\n\t\t \"first log entry: %s %s %s\", \n\t\t ((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->key,\n\t\t ((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->name,\n\t\t ((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->value);\n#else\n\tdprintf(D_FULLDEBUG, \"first log entry: %s %s %s\\n\", \n\t\t\t((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->key,\n\t\t\t((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->name,\n\t\t\t((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->value);\n#endif\n\tcur_probed_seq_num = \n\t\tatol(((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->key);\n\tcur_probed_creation_time = \n\t\tatol(((ClassAdLogEntry *)caLogParser.getCurCALogEntry())->value);\n\n\tif (last_size == 0) {\n\t\t\t\/\/ starting phase\n\t\treturn INIT_QUILL;\n\t}\t\n\n\tif(cur_probed_seq_num != last_seq_num) {\n\t\treturn COMPRESSED;\n\t}\n\n\tcaLogParser.setNextOffset(curCALogEntry->offset);\n\tst = caLogParser.readLogEntry(op_type);\n\t\n\tif (FILE_FATAL_ERROR == st) {\n\t\treturn PROBE_FATAL_ERROR;\n\t}\n\tif (st != FILE_READ_EOF && st != FILE_READ_SUCCESS) {\n\t\treturn PROBE_ERROR;\n\t}\n\t\t\n\n\tif((filestat.st_size == last_size) && \n\t caLogParser.getCurCALogEntry()->equal(curCALogEntry)) {\n\t\t\t\/\/ File size and contents stay the same\n\t\treturn NO_CHANGE;\n\t}\n\telse if((filestat.st_size > last_size) &&\n\t\t\tcaLogParser.getCurCALogEntry()->equal(curCALogEntry)) {\n\t\t\t\/\/ File has been increased and new entries have been added\n\t\treturn ADDITION;\n\t}\n\t\t\/\/if it wasn't captured by any of the above cases, \n\t\t\/\/it must have been an error\n\treturn PROBE_ERROR;\t\t\n}\n\nvoid\nClassAdLogProber::incrementProbeInfo() {\n\t\/\/ store the currently probed stat\n\tlast_mod_time = cur_probed_mod_time;\n\tlast_size = cur_probed_size;\n\n\tlast_seq_num = cur_probed_seq_num;\n\tlast_creation_time = cur_probed_creation_time;\n}\n<|endoftext|>"} {"text":"#include \n#include \"jcl\/cl_include.h\"\n#include \"jcl\/jcl.h\"\n#include \"jcl\/opencl_context.h\"\n\nnamespace jcl {\n\n std::mutex JCL::context_lock_;\n\n JCL::JCL(const CLDevice device, const CLVendor vendor, \n const bool strict_float) {\n context_ = nullptr;\n device_ = device;\n vendor_ = vendor;\n strict_float_ = strict_float;\n\n#if defined(DEBUG) || defined(_DEBUG)\n std::cout << \"\\tCreating OpenCL Context...\" << std::endl\n#endif\n\n \/\/ Aquire lock to prevent multiple initilizations:\n std::lock_guard lock(context_lock_);\n\n context_ .reset(new OpenCLContext());\n context_->createContext(device, vendor);\n context_->InitDevices(device);\n context_->createCommandQueues(); \/\/ For each device\n }\n\n JCL::~JCL() {\n#if defined(DEBUG) || defined(_DEBUG)\n std::cout << \"\\tShutting down OpenCL Context...\" << std::endl;\n#endif\n }\n \n bool JCL::queryDeviceExists(const CLDevice device, const CLVendor vendor) {\n \/\/ Aquire lock to prevent multiple initilizations:\n std::lock_guard lock(context_lock_);\n return OpenCLContext::queryDeviceExists(device, vendor);\n }\n\n uint32_t JCL::getNumDevices() {\n return context_->getNumDevices();\n }\n\n std::string JCL::getDeviceName(const uint32_t device_index) {\n return context_->getDeviceName(device_index);\n }\n\n uint32_t JCL::getMaxWorkgroupSize(const uint32_t device_index) {\n return context_->getMaxWorkgroupSize(device_index);\n }\n\n uint32_t JCL::getMaxWorkitemSize(const uint32_t device_index, const uint32_t dim) {\n return context_->getMaxWorkitemSize(device_index, dim);\n }\n\n CLDevice JCL::getDeviceType(const uint32_t device_index) {\n return context_->getDeviceType(device_index);\n }\n\n JCLBuffer JCL::allocateBuffer(const CLBufferType type, \n const uint32_t nelems) {\n return context_->allocateBuffer(type, nelems);\n }\n\n void JCL::releaseReference(const JCLBuffer buffer) {\n context_->releaseReference(buffer);\n }\n\n void JCL::addReference(const JCLBuffer buffer) {\n context_->addReference(buffer);\n }\n\n void JCL::writeToBuffer(const float* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->writeToBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::readFromBuffer(float* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->readFromBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::writeToBuffer(const int* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->writeToBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::readFromBuffer(int* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->readFromBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::writeToBuffer(const int16_t* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->writeToBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::readFromBuffer(int16_t* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->readFromBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::writeToBuffer(const uint8_t* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->writeToBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::readFromBuffer(uint8_t* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->readFromBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::useKernel(const char* filename, const char* kernel_name) {\n context_->useKernel(filename, kernel_name, strict_float_);\n }\n \n void JCL::useKernelCStr(const char* kernel_c_str, const char* kernel_name) {\n context_->useKernelCStr(kernel_c_str, kernel_name, strict_float_);\n }\n\n void JCL::setArg(const uint32_t index, JCLBuffer buf) {\n context_->setArg(index, buf);\n }\n\n void JCL::setArg(const uint32_t index, int val) {\n context_->setArg(index, val);\n }\n\n void JCL::setArg(const uint32_t index, float val) {\n context_->setArg(index, val);\n }\n\n void JCL::setArg(const uint32_t index, const uint32_t size, void* data) {\n context_->setArg(index, size, data);\n }\n\n void JCL::runKernel(const uint32_t device_index, \n const uint32_t dim, const uint32_t* global_work_size, \n const uint32_t* local_work_size, const bool blocking) {\n context_->runKernel(device_index, dim, global_work_size, \n local_work_size, blocking);\n }\n\n void* JCL::queue(const uint32_t device_index) {\n return context_->queues[device_index]();\n }\n\n void* JCL::getCLMem(const JCLBuffer buffer) {\n return context_->getCLMem(buffer);\n }\n\n std::string JCL::getErrorString(signed int err) {\n switch (err) {\n case 0: return \"CL_SUCCESS\";\n case -1: return \"CL_DEVICE_NOT_FOUND\";\n case -2: return \"CL_DEVICE_NOT_AVAILABLE\";\n case -3: return \"CL_COMPILER_NOT_AVAILABLE\";\n case -4: return \"CL_MEM_OBJECT_ALLOCATION_FAILURE\";\n case -5: return \"CL_OUT_OF_RESOURCES\";\n case -6: return \"CL_OUT_OF_HOST_MEMORY\";\n case -7: return \"CL_PROFILING_INFO_NOT_AVAILABLE\";\n case -8: return \"CL_MEM_COPY_OVERLAP\";\n case -9: return \"CL_IMAGE_FORMAT_MISMATCH\";\n case -10: return \"CL_IMAGE_FORMAT_NOT_SUPPORTED\";\n case -11: return \"CL_BUILD_PROGRAM_FAILURE\";\n case -12: return \"CL_MAP_FAILURE\";\n\n case -30: return \"CL_INVALID_VALUE\";\n case -31: return \"CL_INVALID_DEVICE_TYPE\";\n case -32: return \"CL_INVALID_PLATFORM\";\n case -33: return \"CL_INVALID_DEVICE\";\n case -34: return \"CL_INVALID_CONTEXT\";\n case -35: return \"CL_INVALID_QUEUE_PROPERTIES\";\n case -36: return \"CL_INVALID_COMMAND_QUEUE\";\n case -37: return \"CL_INVALID_HOST_PTR\";\n case -38: return \"CL_INVALID_MEM_OBJECT\";\n case -39: return \"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR\";\n case -40: return \"CL_INVALID_IMAGE_SIZE\";\n case -41: return \"CL_INVALID_SAMPLER\";\n case -42: return \"CL_INVALID_BINARY\";\n case -43: return \"CL_INVALID_BUILD_OPTIONS\";\n case -44: return \"CL_INVALID_PROGRAM\";\n case -45: return \"CL_INVALID_PROGRAM_EXECUTABLE\";\n case -46: return \"CL_INVALID_KERNEL_NAME\";\n case -47: return \"CL_INVALID_KERNEL_DEFINITION\";\n case -48: return \"CL_INVALID_KERNEL\";\n case -49: return \"CL_INVALID_ARG_INDEX\";\n case -50: return \"CL_INVALID_ARG_VALUE\";\n case -51: return \"CL_INVALID_ARG_SIZE\";\n case -52: return \"CL_INVALID_KERNEL_ARGS\";\n case -53: return \"CL_INVALID_WORK_DIMENSION\";\n case -54: return \"CL_INVALID_WORK_GROUP_SIZE\";\n case -55: return \"CL_INVALID_WORK_ITEM_SIZE\";\n case -56: return \"CL_INVALID_GLOBAL_OFFSET\";\n case -57: return \"CL_INVALID_EVENT_WAIT_LIST\";\n case -58: return \"CL_INVALID_EVENT\";\n case -59: return \"CL_INVALID_OPERATION\";\n case -60: return \"CL_INVALID_GL_OBJECT\";\n case -61: return \"CL_INVALID_BUFFER_SIZE\";\n case -62: return \"CL_INVALID_MIP_LEVEL\";\n case -63: return \"CL_INVALID_GLOBAL_WORK_SIZE\";\n default: return \"Unknown OpenCL error\";\n }\n }\n\n void JCL::sync(const uint32_t device_index) {\n context_->sync(device_index);\n }\n\n void JCL::runKernel(const uint32_t device_index, \n const uint32_t dim, const uint32_t* global_work_size, \n const bool blocking) {\n context_->runKernel(device_index, dim, global_work_size, blocking);\n }\n\n uint32_t JCL::queryMaxWorkgroupSizeForCurKernel(const uint32_t device_index) {\n return context_->queryMaxWorkgroupSizeForCurKernel(device_index);\n }\n\n std::string JCL::CLDeviceToString(const CLDevice device) {\n switch (device) {\n case CLDeviceDefault:\n return \"CLDeviceDefault\";\n case CLDeviceAll:\n return \"CLDeviceAll\";\n case CLDeviceCPU:\n return \"CLDeviceCPU\";\n case CLDeviceGPU:\n return \"CLDeviceGPU\";\n case CLDeviceAccelerator:\n return \"CLDeviceDefault\";\n default:\n std::cout << \"Bad CLDevice\" << std::endl;\n RASSERT(false);\n return \"Bad CLDevice\";\n }\n }\n\n std::string JCL::CLVendorToString(const CLVendor vendor) {\n switch (vendor) {\n case CLVendorAny:\n return \"CLVendorAny\";\n case CLDeviceNVidia:\n return \"CLDeviceNVidia\";\n case CLDeviceAMD:\n return \"CLDeviceAMD\";\n case CLDeviceIntel:\n return \"CLDeviceIntel\";\n default:\n std::cout << \"Bad CLVendor\" << std::endl;\n RASSERT(false);\n return \"Bad CLVendor\";\n }\n }\n\n} \/\/ namespace jcl\nfix compiler error#include \n#include \"jcl\/cl_include.h\"\n#include \"jcl\/jcl.h\"\n#include \"jcl\/opencl_context.h\"\n\nnamespace jcl {\n\n std::mutex JCL::context_lock_;\n\n JCL::JCL(const CLDevice device, const CLVendor vendor, \n const bool strict_float) {\n context_ = nullptr;\n device_ = device;\n vendor_ = vendor;\n strict_float_ = strict_float;\n\n#if defined(DEBUG) || defined(_DEBUG)\n std::cout << \"\\tCreating OpenCL Context...\" << std::endl;\n#endif\n\n \/\/ Aquire lock to prevent multiple initilizations:\n std::lock_guard lock(context_lock_);\n\n context_ .reset(new OpenCLContext());\n context_->createContext(device, vendor);\n context_->InitDevices(device);\n context_->createCommandQueues(); \/\/ For each device\n }\n\n JCL::~JCL() {\n#if defined(DEBUG) || defined(_DEBUG)\n std::cout << \"\\tShutting down OpenCL Context...\" << std::endl;\n#endif\n }\n \n bool JCL::queryDeviceExists(const CLDevice device, const CLVendor vendor) {\n \/\/ Aquire lock to prevent multiple initilizations:\n std::lock_guard lock(context_lock_);\n return OpenCLContext::queryDeviceExists(device, vendor);\n }\n\n uint32_t JCL::getNumDevices() {\n return context_->getNumDevices();\n }\n\n std::string JCL::getDeviceName(const uint32_t device_index) {\n return context_->getDeviceName(device_index);\n }\n\n uint32_t JCL::getMaxWorkgroupSize(const uint32_t device_index) {\n return context_->getMaxWorkgroupSize(device_index);\n }\n\n uint32_t JCL::getMaxWorkitemSize(const uint32_t device_index, const uint32_t dim) {\n return context_->getMaxWorkitemSize(device_index, dim);\n }\n\n CLDevice JCL::getDeviceType(const uint32_t device_index) {\n return context_->getDeviceType(device_index);\n }\n\n JCLBuffer JCL::allocateBuffer(const CLBufferType type, \n const uint32_t nelems) {\n return context_->allocateBuffer(type, nelems);\n }\n\n void JCL::releaseReference(const JCLBuffer buffer) {\n context_->releaseReference(buffer);\n }\n\n void JCL::addReference(const JCLBuffer buffer) {\n context_->addReference(buffer);\n }\n\n void JCL::writeToBuffer(const float* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->writeToBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::readFromBuffer(float* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->readFromBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::writeToBuffer(const int* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->writeToBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::readFromBuffer(int* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->readFromBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::writeToBuffer(const int16_t* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->writeToBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::readFromBuffer(int16_t* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->readFromBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::writeToBuffer(const uint8_t* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->writeToBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::readFromBuffer(uint8_t* data, const uint32_t device_index, \n const JCLBuffer buffer, const bool blocking) {\n context_->readFromBuffer(data, device_index, buffer, blocking);\n }\n\n void JCL::useKernel(const char* filename, const char* kernel_name) {\n context_->useKernel(filename, kernel_name, strict_float_);\n }\n \n void JCL::useKernelCStr(const char* kernel_c_str, const char* kernel_name) {\n context_->useKernelCStr(kernel_c_str, kernel_name, strict_float_);\n }\n\n void JCL::setArg(const uint32_t index, JCLBuffer buf) {\n context_->setArg(index, buf);\n }\n\n void JCL::setArg(const uint32_t index, int val) {\n context_->setArg(index, val);\n }\n\n void JCL::setArg(const uint32_t index, float val) {\n context_->setArg(index, val);\n }\n\n void JCL::setArg(const uint32_t index, const uint32_t size, void* data) {\n context_->setArg(index, size, data);\n }\n\n void JCL::runKernel(const uint32_t device_index, \n const uint32_t dim, const uint32_t* global_work_size, \n const uint32_t* local_work_size, const bool blocking) {\n context_->runKernel(device_index, dim, global_work_size, \n local_work_size, blocking);\n }\n\n void* JCL::queue(const uint32_t device_index) {\n return context_->queues[device_index]();\n }\n\n void* JCL::getCLMem(const JCLBuffer buffer) {\n return context_->getCLMem(buffer);\n }\n\n std::string JCL::getErrorString(signed int err) {\n switch (err) {\n case 0: return \"CL_SUCCESS\";\n case -1: return \"CL_DEVICE_NOT_FOUND\";\n case -2: return \"CL_DEVICE_NOT_AVAILABLE\";\n case -3: return \"CL_COMPILER_NOT_AVAILABLE\";\n case -4: return \"CL_MEM_OBJECT_ALLOCATION_FAILURE\";\n case -5: return \"CL_OUT_OF_RESOURCES\";\n case -6: return \"CL_OUT_OF_HOST_MEMORY\";\n case -7: return \"CL_PROFILING_INFO_NOT_AVAILABLE\";\n case -8: return \"CL_MEM_COPY_OVERLAP\";\n case -9: return \"CL_IMAGE_FORMAT_MISMATCH\";\n case -10: return \"CL_IMAGE_FORMAT_NOT_SUPPORTED\";\n case -11: return \"CL_BUILD_PROGRAM_FAILURE\";\n case -12: return \"CL_MAP_FAILURE\";\n\n case -30: return \"CL_INVALID_VALUE\";\n case -31: return \"CL_INVALID_DEVICE_TYPE\";\n case -32: return \"CL_INVALID_PLATFORM\";\n case -33: return \"CL_INVALID_DEVICE\";\n case -34: return \"CL_INVALID_CONTEXT\";\n case -35: return \"CL_INVALID_QUEUE_PROPERTIES\";\n case -36: return \"CL_INVALID_COMMAND_QUEUE\";\n case -37: return \"CL_INVALID_HOST_PTR\";\n case -38: return \"CL_INVALID_MEM_OBJECT\";\n case -39: return \"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR\";\n case -40: return \"CL_INVALID_IMAGE_SIZE\";\n case -41: return \"CL_INVALID_SAMPLER\";\n case -42: return \"CL_INVALID_BINARY\";\n case -43: return \"CL_INVALID_BUILD_OPTIONS\";\n case -44: return \"CL_INVALID_PROGRAM\";\n case -45: return \"CL_INVALID_PROGRAM_EXECUTABLE\";\n case -46: return \"CL_INVALID_KERNEL_NAME\";\n case -47: return \"CL_INVALID_KERNEL_DEFINITION\";\n case -48: return \"CL_INVALID_KERNEL\";\n case -49: return \"CL_INVALID_ARG_INDEX\";\n case -50: return \"CL_INVALID_ARG_VALUE\";\n case -51: return \"CL_INVALID_ARG_SIZE\";\n case -52: return \"CL_INVALID_KERNEL_ARGS\";\n case -53: return \"CL_INVALID_WORK_DIMENSION\";\n case -54: return \"CL_INVALID_WORK_GROUP_SIZE\";\n case -55: return \"CL_INVALID_WORK_ITEM_SIZE\";\n case -56: return \"CL_INVALID_GLOBAL_OFFSET\";\n case -57: return \"CL_INVALID_EVENT_WAIT_LIST\";\n case -58: return \"CL_INVALID_EVENT\";\n case -59: return \"CL_INVALID_OPERATION\";\n case -60: return \"CL_INVALID_GL_OBJECT\";\n case -61: return \"CL_INVALID_BUFFER_SIZE\";\n case -62: return \"CL_INVALID_MIP_LEVEL\";\n case -63: return \"CL_INVALID_GLOBAL_WORK_SIZE\";\n default: return \"Unknown OpenCL error\";\n }\n }\n\n void JCL::sync(const uint32_t device_index) {\n context_->sync(device_index);\n }\n\n void JCL::runKernel(const uint32_t device_index, \n const uint32_t dim, const uint32_t* global_work_size, \n const bool blocking) {\n context_->runKernel(device_index, dim, global_work_size, blocking);\n }\n\n uint32_t JCL::queryMaxWorkgroupSizeForCurKernel(const uint32_t device_index) {\n return context_->queryMaxWorkgroupSizeForCurKernel(device_index);\n }\n\n std::string JCL::CLDeviceToString(const CLDevice device) {\n switch (device) {\n case CLDeviceDefault:\n return \"CLDeviceDefault\";\n case CLDeviceAll:\n return \"CLDeviceAll\";\n case CLDeviceCPU:\n return \"CLDeviceCPU\";\n case CLDeviceGPU:\n return \"CLDeviceGPU\";\n case CLDeviceAccelerator:\n return \"CLDeviceDefault\";\n default:\n std::cout << \"Bad CLDevice\" << std::endl;\n RASSERT(false);\n return \"Bad CLDevice\";\n }\n }\n\n std::string JCL::CLVendorToString(const CLVendor vendor) {\n switch (vendor) {\n case CLVendorAny:\n return \"CLVendorAny\";\n case CLDeviceNVidia:\n return \"CLDeviceNVidia\";\n case CLDeviceAMD:\n return \"CLDeviceAMD\";\n case CLDeviceIntel:\n return \"CLDeviceIntel\";\n default:\n std::cout << \"Bad CLVendor\" << std::endl;\n RASSERT(false);\n return \"Bad CLVendor\";\n }\n }\n\n} \/\/ namespace jcl\n<|endoftext|>"} {"text":"#include \"core\/raytracer.h\"\n\n#include \"core\/image.h\"\n\n#include \"core\/intersection.h\"\n#include \"core\/sphere.h\"\n#include \"core\/random.h\"\n#include \"core\/polarcoord.h\"\n#include \"core\/numeric.h\"\n\n#include \n\nnamespace euphoria::core::raytracer\n{\n HitResult::HitResult\n (\n bool acollided,\n float aray_distance,\n const vec3f& aposition,\n const unit3f& anormal\n )\n : collided(acollided)\n , ray_distance(aray_distance)\n , position(aposition)\n , normal(anormal)\n {\n }\n\n\n HitResult\n NoCollision\n (\n )\n {\n return HitResult\n {\n false,\n 10000.0f,\n vec3f::Zero(),\n unit3f::Up()\n };\n }\n\n\n HitResult\n Collision\n (\n float ray_distance,\n const vec3f& position,\n const unit3f& normal\n )\n {\n return HitResult\n {\n true,\n ray_distance,\n position,\n normal\n };\n }\n\n\n\n struct SphereObject : public Object\n {\n Sphere sphere;\n vec3f position;\n\n SphereObject(const Sphere& asphere, const vec3f& aposition)\n : sphere(asphere)\n , position(aposition)\n {\n }\n\n HitResult\n Hit(const UnitRay3f& ray, const Range& range) const override\n {\n const auto hit_index = GetIntersection\n (\n ray,\n sphere,\n position\n );\n if(IsWithin(range, hit_index))\n {\n const auto hit_position = ray.GetPoint(hit_index);\n const auto hit_normal = vec3f::FromTo(position, hit_position).GetNormalized();\n return Collision\n (\n hit_index,\n hit_position,\n hit_normal\n );\n }\n else\n {\n return NoCollision();\n }\n }\n };\n\n\n std::shared_ptr\n CreateSphere(const Sphere& sphere, const vec3f& position)\n {\n return std::make_shared\n (\n sphere,\n position\n );\n }\n\n\n HitResult\n Scene::Hit(const UnitRay3f& ray, const Range& range) const\n {\n auto r = NoCollision();\n\n for(const auto o: objects)\n {\n const auto h = o->Hit(ray, range);\n if(r.collided == false)\n {\n r = h;\n }\n else\n {\n if(h.collided)\n {\n if(h.ray_distance < r.ray_distance)\n {\n r = h;\n }\n }\n }\n }\n\n return r;\n }\n\n\n Rgb\n rgb(const unit3f& normal)\n {\n return Rgb\n {\n (normal.x + 1)\/2,\n (normal.y + 1)\/2,\n (normal.z + 1)\/2\n };\n }\n\n\n vec3f RandomInUnitSphere(Random* random)\n {\n return RandomUnit3(random) * random->NextFloat01();\n }\n\n\n Rgb\n GetColor(const Scene& scene, const UnitRay3f& ray, Random* random)\n {\n const auto h = scene.Hit\n (\n ray,\n MakeRange(0.0f, std::numeric_limits::max())\n );\n if(h.collided)\n {\n const auto target = h.position + h.normal + RandomInUnitSphere(random);\n const auto reflected_ray = UnitRay3f::FromTo(h.position, target);\n return 0.5f * GetColor(scene, reflected_ray, random);\n \/\/ return rgb(h.normal);\n }\n const auto t = (ray.dir.y+1)\/2.0f;\n return RgbTransform::Transform\n (\n Rgb(1.0f, 1.0f, 1.0f),\n t,\n Rgb(0.5f, 0.7f, 1.0f)\n );\n }\n\n\n struct Camera\n {\n vec3f lower_left_corner = vec3f{-2.0f, -1.0f, -1.0f};\n vec3f horizontal = vec3f{4.0f, 0.0f, 0.0f};\n vec3f vertical = vec3f{0.0f, 2.0f, 0.0f};\n vec3f origin = vec3f{0.0f, 0.0f, 0.0f};\n\n UnitRay3f GetRay(float u, float v) const\n {\n return UnitRay3f::FromTo(origin, lower_left_corner + u*horizontal + v*vertical);\n }\n };\n\n\n Rgb\n Gamma2CorrectColor(Rgb color)\n {\n return {Sqrt(color.r), Sqrt(color.g), Sqrt(color.b)};\n }\n\n void\n Raytrace(Image* aimage, const Scene& scene, int number_of_samples)\n {\n Image& img = *aimage;\n\n auto random = Random{};\n const auto camera = Camera{};\n\n for(int y=0; y(img.GetWidth());\n const auto v = (y + random.NextFloat01()) \/ static_cast(img.GetHeight());\n const auto ray = camera.GetRay(u, v);\n const auto sample_color = GetColor(scene, ray, &random);\n color += sample_color;\n }\n color = color\/number_of_samples;\n color = Gamma2CorrectColor(color);\n img.SetPixel(x,y, rgbi(color));\n }\n }\n}\n\nraytracer step 11: avoiding shadow acne#include \"core\/raytracer.h\"\n\n#include \"core\/image.h\"\n\n#include \"core\/intersection.h\"\n#include \"core\/sphere.h\"\n#include \"core\/random.h\"\n#include \"core\/polarcoord.h\"\n#include \"core\/numeric.h\"\n\n#include \n\nnamespace euphoria::core::raytracer\n{\n HitResult::HitResult\n (\n bool acollided,\n float aray_distance,\n const vec3f& aposition,\n const unit3f& anormal\n )\n : collided(acollided)\n , ray_distance(aray_distance)\n , position(aposition)\n , normal(anormal)\n {\n }\n\n\n HitResult\n NoCollision\n (\n )\n {\n return HitResult\n {\n false,\n 10000.0f,\n vec3f::Zero(),\n unit3f::Up()\n };\n }\n\n\n HitResult\n Collision\n (\n float ray_distance,\n const vec3f& position,\n const unit3f& normal\n )\n {\n return HitResult\n {\n true,\n ray_distance,\n position,\n normal\n };\n }\n\n\n\n struct SphereObject : public Object\n {\n Sphere sphere;\n vec3f position;\n\n SphereObject(const Sphere& asphere, const vec3f& aposition)\n : sphere(asphere)\n , position(aposition)\n {\n }\n\n HitResult\n Hit(const UnitRay3f& ray, const Range& range) const override\n {\n const auto hit_index = GetIntersection\n (\n ray,\n sphere,\n position\n );\n if(IsWithin(range, hit_index))\n {\n const auto hit_position = ray.GetPoint(hit_index);\n const auto hit_normal = vec3f::FromTo(position, hit_position).GetNormalized();\n return Collision\n (\n hit_index,\n hit_position,\n hit_normal\n );\n }\n else\n {\n return NoCollision();\n }\n }\n };\n\n\n std::shared_ptr\n CreateSphere(const Sphere& sphere, const vec3f& position)\n {\n return std::make_shared\n (\n sphere,\n position\n );\n }\n\n\n HitResult\n Scene::Hit(const UnitRay3f& ray, const Range& range) const\n {\n auto r = NoCollision();\n\n for(const auto o: objects)\n {\n const auto h = o->Hit(ray, range);\n if(r.collided == false)\n {\n r = h;\n }\n else\n {\n if(h.collided)\n {\n if(h.ray_distance < r.ray_distance)\n {\n r = h;\n }\n }\n }\n }\n\n return r;\n }\n\n\n Rgb\n rgb(const unit3f& normal)\n {\n return Rgb\n {\n (normal.x + 1)\/2,\n (normal.y + 1)\/2,\n (normal.z + 1)\/2\n };\n }\n\n\n vec3f RandomInUnitSphere(Random* random)\n {\n return RandomUnit3(random) * random->NextFloat01();\n }\n\n\n Rgb\n GetColor(const Scene& scene, const UnitRay3f& ray, Random* random)\n {\n const auto h = scene.Hit\n (\n ray,\n MakeRange(0.001f, std::numeric_limits::max())\n );\n if(h.collided)\n {\n const auto target = h.position + h.normal + RandomInUnitSphere(random);\n const auto reflected_ray = UnitRay3f::FromTo(h.position, target);\n return 0.5f * GetColor(scene, reflected_ray, random);\n \/\/ return rgb(h.normal);\n }\n const auto t = (ray.dir.y+1)\/2.0f;\n return RgbTransform::Transform\n (\n Rgb(1.0f, 1.0f, 1.0f),\n t,\n Rgb(0.5f, 0.7f, 1.0f)\n );\n }\n\n\n struct Camera\n {\n vec3f lower_left_corner = vec3f{-2.0f, -1.0f, -1.0f};\n vec3f horizontal = vec3f{4.0f, 0.0f, 0.0f};\n vec3f vertical = vec3f{0.0f, 2.0f, 0.0f};\n vec3f origin = vec3f{0.0f, 0.0f, 0.0f};\n\n UnitRay3f GetRay(float u, float v) const\n {\n return UnitRay3f::FromTo(origin, lower_left_corner + u*horizontal + v*vertical);\n }\n };\n\n\n Rgb\n Gamma2CorrectColor(Rgb color)\n {\n return {Sqrt(color.r), Sqrt(color.g), Sqrt(color.b)};\n }\n\n void\n Raytrace(Image* aimage, const Scene& scene, int number_of_samples)\n {\n Image& img = *aimage;\n\n auto random = Random{};\n const auto camera = Camera{};\n\n for(int y=0; y(img.GetWidth());\n const auto v = (y + random.NextFloat01()) \/ static_cast(img.GetHeight());\n const auto ray = camera.GetRay(u, v);\n const auto sample_color = GetColor(scene, ray, &random);\n color += sample_color;\n }\n color = color\/number_of_samples;\n color = Gamma2CorrectColor(color);\n img.SetPixel(x,y, rgbi(color));\n }\n }\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"linalg\/util.h\"\n#include \"render\/render_target.h\"\n\n\/*\n * Perform an atomic addition to the float via spin-locking\n * on compare_exchange_weak. Memory ordering is release on write\n * consume on read\n *\/\nstatic float atomic_addf(std::atomic &f, float d){\n\tfloat old = f.load(std::memory_order_consume);\n\tfloat desired = old + d;\n\twhile (!f.compare_exchange_weak(old, desired,\n\t\tstd::memory_order_release, std::memory_order_consume))\n\t{\n\t\tdesired = old + d;\n\t}\n\treturn desired;\n}\n\nPixel::Pixel() : r(0), g(0), b(0), weight(0){}\nPixel::Pixel(const Pixel &p) : r(p.r.load(std::memory_order_consume)), g(p.g.load(std::memory_order_consume)),\n\tb(p.b.load(std::memory_order_consume)), weight(p.weight.load(std::memory_order_consume))\n{}\n\nRenderTarget::RenderTarget(size_t width, size_t height, std::unique_ptr f)\n\t: width(width), height(height), filter(std::move(f)), pixels(width * height),\n\tfloat_buf(width * height, std::numeric_limits::infinity())\n{\n\t\/\/Pre-compute the filter table values\n\tfor (int y = 0; y < FILTER_TABLE_SIZE; ++y){\n\t\tfloat fy = (y + .5f) * filter->h \/ FILTER_TABLE_SIZE;\n\t\tfor (int x = 0; x < FILTER_TABLE_SIZE; ++x){\n\t\t\tfloat fx = (x + .5f) * filter->w \/ FILTER_TABLE_SIZE;\n\t\t\tfilter_table[y * FILTER_TABLE_SIZE + x] = filter->weight(fx, fy);\n\t\t}\n\t}\n}\nvoid RenderTarget::write_pixel(float x, float y, const Colorf &c){\n\t\/\/Compute the discrete pixel coordinates which the sample hits\n\tfloat img_x = x - 0.5f;\n\tfloat img_y = y - 0.5f;\n\tstd::array x_range = {static_cast(std::ceil(img_x - filter->w)),\n\t\tstatic_cast(std::floor(img_x + filter->w))};\n\tstd::array y_range = {static_cast(std::ceil(img_y - filter->h)),\n\t\tstatic_cast(std::floor(img_y + filter->h))};\n\t\/\/Keep pixel coordinates in range and ignore degenerate ranges\n\tx_range[0] = std::max(x_range[0], 0);\n\tx_range[1] = std::min(x_range[1], static_cast(width) - 1);\n\ty_range[0] = std::max(y_range[0], 0);\n\ty_range[1] = std::min(y_range[1], static_cast(height) - 1);\n\tif (x_range[1] - x_range[0] < 0 || y_range[1] - y_range[0] < 0){\n\t\treturn;\n\t}\n\t\/\/Filter this sample to apply it to the pixels in the image affected by it\n\tfor (int iy = y_range[0]; iy <= y_range[1]; ++iy){\n\t\tfloat fy = std::abs(iy - img_y) * filter->inv_h * FILTER_TABLE_SIZE;\n\t\tint fy_idx = std::min(static_cast(fy), FILTER_TABLE_SIZE - 1);\n\t\tfor (int ix = x_range[0]; ix <= x_range[1]; ++ix){\n\t\t\t\/\/Compute location of this sample in the pre-computed filter values\n\t\t\tfloat fx = std::abs(ix - img_x) * filter->inv_w * FILTER_TABLE_SIZE;\n\t\t\tint fx_idx = std::min(static_cast(fx), FILTER_TABLE_SIZE - 1);\n\t\t\tfloat fweight = filter_table[fy_idx * FILTER_TABLE_SIZE + fx_idx];\n\t\t\tPixel &p = pixels[iy * width + ix];\n\t\t\tatomic_addf(p.r, fweight * c.r);\n\t\t\tatomic_addf(p.g, fweight * c.g);\n\t\t\tatomic_addf(p.b, fweight * c.b);\n\t\t\tatomic_addf(p.weight, fweight);\n\t\t}\n\t}\n}\nvoid RenderTarget::write_float(size_t x, size_t y, float d){\n\tfloat_buf[y * width + x] = d;\n}\nbool RenderTarget::save_image(const std::string &file) const {\n\t\/\/Compute the correct image from the saved pixel data\n\tstd::vector img(width * height);\n\tfor (size_t y = 0; y < height; ++y){\n\t\tfor (size_t x = 0; x < width; ++x){\n\t\t\tconst Pixel &p = pixels[y * width + x];\n\t\t\tfloat weight = p.weight.load(std::memory_order_consume);\n\t\t\tif (weight != 0){\n\t\t\t\tColorf c{p.r.load(std::memory_order_consume),\n\t\t\t\t\tp.g.load(std::memory_order_consume),\n\t\t\t\t\tp.b.load(std::memory_order_consume)};\n\t\t\t\tc \/= weight;\n\t\t\t\tc.normalize();\n\t\t\t\timg[y * width + x] = c;\n\t\t\t}\n\t\t}\n\t}\n\treturn save_ppm(file, &img[0].r);\n}\nbool RenderTarget::save_depth(const std::string &file) const {\n\tstd::vector depth_norm = generate_depth_img();\n\treturn save_pgm(file, depth_norm.data());\n}\nbool RenderTarget::save_heat(const std::string &file) const {\n\tstd::vector heat_map = generate_heat_img();\n\treturn save_ppm(file, &heat_map[0].r);\n}\nsize_t RenderTarget::get_width() const {\n\treturn width;\n}\nsize_t RenderTarget::get_height() const {\n\treturn height;\n}\nvoid RenderTarget::get_colorbuf(std::vector &img) const { \n\t\/\/Compute the correct image from the saved pixel data\n\timg.resize(width * height);\n\tfor (size_t y = 0; y < height; ++y){\n\t\tfor (size_t x = 0; x < width; ++x){\n\t\t\tconst Pixel &p = pixels[y * width + x];\n\t\t\tfloat weight = p.weight.load(std::memory_order_consume);\n\t\t\tif (weight != 0){\n\t\t\t\tColorf c{p.r.load(std::memory_order_consume),\n\t\t\t\t\tp.g.load(std::memory_order_consume),\n\t\t\t\t\tp.b.load(std::memory_order_consume)};\n\t\t\t\tc \/= weight;\n\t\t\t\tc.normalize();\n\t\t\t\timg[y * width + x] = c;\n\t\t\t}\n\t\t}\n\t}\n}\nconst std::vector& RenderTarget::get_floatbuf() const {\n\treturn float_buf;\n}\nstd::vector RenderTarget::generate_depth_img() const {\n\tstd::vector depth_norm(width * height);\n\t\/\/Determine the min\/max range of depth values so we can scale\n\t\/\/them into 0-255 range\n\tfloat zmin = std::numeric_limits::infinity();\n\tfloat zmax = std::numeric_limits::min();\n\tfor (const auto &f : float_buf){\n\t\tif (f == std::numeric_limits::infinity()){\n\t\t\tcontinue;\n\t\t}\n\t\tif (f < zmin){\n\t\t\tzmin = f;\n\t\t}\n\t\tif (f > zmax){\n\t\t\tzmax = f;\n\t\t}\n\t}\n\tfor (size_t i = 0; i < float_buf.size(); ++i){\n\t\tif (float_buf[i] == std::numeric_limits::infinity()){\n\t\t\tdepth_norm[i] = 0;\n\t\t}\n\t\telse {\n\t\t\tdepth_norm[i] = static_cast((zmax - float_buf[i]) \/ (zmax - zmin) * 255);\n\t\t\tdepth_norm[i] = clamp(depth_norm[i], uint8_t{0}, uint8_t{255});\n\t\t}\n\t}\n\treturn depth_norm;\n}\nstd::vector RenderTarget::generate_heat_img() const {\n\t\/\/We use HSV to generate the heat map taking H = 240 as our min value (coolest)\n\t\/\/and H = 0 as our max (hottest)\n\tstd::vector heat_map(width * height);\n\tfloat min = std::numeric_limits::infinity();\n\tfloat max = std::numeric_limits::min();\n\tfor (const auto &f : float_buf){\n\t\tif (f == std::numeric_limits::infinity()){\n\t\t\tcontinue;\n\t\t}\n\t\tif (f < min){\n\t\t\tmin = f;\n\t\t}\n\t\tif (f > max){\n\t\t\tmax = f;\n\t\t}\n\t}\n\tfor (size_t i = 0; i < float_buf.size(); ++i){\n\t\tfloat hue = 240;\n\t\tif (float_buf[i] != std::numeric_limits::infinity()){\n\t\t\thue = (float_buf[i] - max) \/ (max - min) * -240.f;\n\t\t\thue = clamp(hue, 0.f, 240.f);\n\t\t}\n\t\thue \/= 60;\n\t\tfloat x = 1 - std::abs(static_cast(hue) % 2 - 1);\n\t\tif (hue >= 0 && hue < 1){\n\t\t\theat_map[i] = Colorf{1, x, 0};\n\t\t}\n\t\telse if (hue < 2){\n\t\t\theat_map[i] = Colorf{x, 1, 0};\n\t\t}\n\t\telse if (hue < 3){\n\t\t\theat_map[i] = Colorf{0, 1, x};\n\t\t}\n\t\telse if (hue < 4){\n\t\t\theat_map[i] = Colorf{0, x, 1};\n\t\t}\n\t\telse if (hue < 5){\n\t\t\theat_map[i] = Colorf{x, 0, 1};\n\t\t}\n\t\telse if (hue < 6){\n\t\t\theat_map[i] = Colorf{1, 0, x};\n\t\t}\n\t}\n\treturn heat_map;\n}\nbool RenderTarget::save_ppm(const std::string &file, const uint8_t *data) const {\n\tFILE *fp = fopen(file.c_str(), \"wb\");\n\tif (!fp){\n\t\tstd::cerr << \"RenderTarget::save_ppm Error: failed to open file \" << file << std::endl;\n\t\treturn false;\n\t}\n\tfprintf(fp, \"P6\\n%d %d\\n255\\n\", static_cast(width), static_cast(height));\n\tfwrite(data, 1, 3 * width * height, fp);\n\tfclose(fp);\n\treturn true;\n}\nbool RenderTarget::save_pgm(const std::string &file, const uint8_t * data) const {\n\tFILE *fp = fopen(file.c_str(), \"wb\");\n\tif (!fp){\n\t\tstd::cerr << \"RenderTarget::save_pgm Error: failed to open file \" << file << std::endl;\n\t\treturn false;\n\t}\n\tfprintf(fp, \"P5\\n%d %d\\n255\\n\", static_cast(width), static_cast(height));\n\tfwrite(data, 1, width * height, fp);\n\tfclose(fp);\n\treturn true;\n}\n\nJust use get_colorbuf to compute the Color24 when writing image#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"linalg\/util.h\"\n#include \"render\/render_target.h\"\n\n\/*\n * Perform an atomic addition to the float via spin-locking\n * on compare_exchange_weak. Memory ordering is release on write\n * consume on read\n *\/\nstatic float atomic_addf(std::atomic &f, float d){\n\tfloat old = f.load(std::memory_order_consume);\n\tfloat desired = old + d;\n\twhile (!f.compare_exchange_weak(old, desired,\n\t\tstd::memory_order_release, std::memory_order_consume))\n\t{\n\t\tdesired = old + d;\n\t}\n\treturn desired;\n}\n\nPixel::Pixel() : r(0), g(0), b(0), weight(0){}\nPixel::Pixel(const Pixel &p) : r(p.r.load(std::memory_order_consume)), g(p.g.load(std::memory_order_consume)),\n\tb(p.b.load(std::memory_order_consume)), weight(p.weight.load(std::memory_order_consume))\n{}\n\nRenderTarget::RenderTarget(size_t width, size_t height, std::unique_ptr f)\n\t: width(width), height(height), filter(std::move(f)), pixels(width * height),\n\tfloat_buf(width * height, std::numeric_limits::infinity())\n{\n\t\/\/Pre-compute the filter table values\n\tfor (int y = 0; y < FILTER_TABLE_SIZE; ++y){\n\t\tfloat fy = (y + .5f) * filter->h \/ FILTER_TABLE_SIZE;\n\t\tfor (int x = 0; x < FILTER_TABLE_SIZE; ++x){\n\t\t\tfloat fx = (x + .5f) * filter->w \/ FILTER_TABLE_SIZE;\n\t\t\tfilter_table[y * FILTER_TABLE_SIZE + x] = filter->weight(fx, fy);\n\t\t}\n\t}\n}\nvoid RenderTarget::write_pixel(float x, float y, const Colorf &c){\n\t\/\/Compute the discrete pixel coordinates which the sample hits\n\tfloat img_x = x - 0.5f;\n\tfloat img_y = y - 0.5f;\n\tstd::array x_range = {static_cast(std::ceil(img_x - filter->w)),\n\t\tstatic_cast(std::floor(img_x + filter->w))};\n\tstd::array y_range = {static_cast(std::ceil(img_y - filter->h)),\n\t\tstatic_cast(std::floor(img_y + filter->h))};\n\t\/\/Keep pixel coordinates in range and ignore degenerate ranges\n\tx_range[0] = std::max(x_range[0], 0);\n\tx_range[1] = std::min(x_range[1], static_cast(width) - 1);\n\ty_range[0] = std::max(y_range[0], 0);\n\ty_range[1] = std::min(y_range[1], static_cast(height) - 1);\n\tif (x_range[1] - x_range[0] < 0 || y_range[1] - y_range[0] < 0){\n\t\treturn;\n\t}\n\t\/\/Filter this sample to apply it to the pixels in the image affected by it\n\tfor (int iy = y_range[0]; iy <= y_range[1]; ++iy){\n\t\tfloat fy = std::abs(iy - img_y) * filter->inv_h * FILTER_TABLE_SIZE;\n\t\tint fy_idx = std::min(static_cast(fy), FILTER_TABLE_SIZE - 1);\n\t\tfor (int ix = x_range[0]; ix <= x_range[1]; ++ix){\n\t\t\t\/\/Compute location of this sample in the pre-computed filter values\n\t\t\tfloat fx = std::abs(ix - img_x) * filter->inv_w * FILTER_TABLE_SIZE;\n\t\t\tint fx_idx = std::min(static_cast(fx), FILTER_TABLE_SIZE - 1);\n\t\t\tfloat fweight = filter_table[fy_idx * FILTER_TABLE_SIZE + fx_idx];\n\t\t\tPixel &p = pixels[iy * width + ix];\n\t\t\tatomic_addf(p.r, fweight * c.r);\n\t\t\tatomic_addf(p.g, fweight * c.g);\n\t\t\tatomic_addf(p.b, fweight * c.b);\n\t\t\tatomic_addf(p.weight, fweight);\n\t\t}\n\t}\n}\nvoid RenderTarget::write_float(size_t x, size_t y, float d){\n\tfloat_buf[y * width + x] = d;\n}\nbool RenderTarget::save_image(const std::string &file) const {\n\t\/\/Compute the correct image from the saved pixel data\n\tstd::vector img(width * height);\n\tget_colorbuf(img);\n\treturn save_ppm(file, &img[0].r);\n}\nbool RenderTarget::save_depth(const std::string &file) const {\n\tstd::vector depth_norm = generate_depth_img();\n\treturn save_pgm(file, depth_norm.data());\n}\nbool RenderTarget::save_heat(const std::string &file) const {\n\tstd::vector heat_map = generate_heat_img();\n\treturn save_ppm(file, &heat_map[0].r);\n}\nsize_t RenderTarget::get_width() const {\n\treturn width;\n}\nsize_t RenderTarget::get_height() const {\n\treturn height;\n}\nvoid RenderTarget::get_colorbuf(std::vector &img) const { \n\t\/\/Compute the correct image from the saved pixel data\n\timg.resize(width * height);\n\tfor (size_t y = 0; y < height; ++y){\n\t\tfor (size_t x = 0; x < width; ++x){\n\t\t\tconst Pixel &p = pixels[y * width + x];\n\t\t\tfloat weight = p.weight.load(std::memory_order_consume);\n\t\t\tif (weight != 0){\n\t\t\t\tColorf c{p.r.load(std::memory_order_consume),\n\t\t\t\t\tp.g.load(std::memory_order_consume),\n\t\t\t\t\tp.b.load(std::memory_order_consume)};\n\t\t\t\tc \/= weight;\n\t\t\t\tc.normalize();\n\t\t\t\timg[y * width + x] = c;\n\t\t\t}\n\t\t}\n\t}\n}\nconst std::vector& RenderTarget::get_floatbuf() const {\n\treturn float_buf;\n}\nstd::vector RenderTarget::generate_depth_img() const {\n\tstd::vector depth_norm(width * height);\n\t\/\/Determine the min\/max range of depth values so we can scale\n\t\/\/them into 0-255 range\n\tfloat zmin = std::numeric_limits::infinity();\n\tfloat zmax = std::numeric_limits::min();\n\tfor (const auto &f : float_buf){\n\t\tif (f == std::numeric_limits::infinity()){\n\t\t\tcontinue;\n\t\t}\n\t\tif (f < zmin){\n\t\t\tzmin = f;\n\t\t}\n\t\tif (f > zmax){\n\t\t\tzmax = f;\n\t\t}\n\t}\n\tfor (size_t i = 0; i < float_buf.size(); ++i){\n\t\tif (float_buf[i] == std::numeric_limits::infinity()){\n\t\t\tdepth_norm[i] = 0;\n\t\t}\n\t\telse {\n\t\t\tdepth_norm[i] = static_cast((zmax - float_buf[i]) \/ (zmax - zmin) * 255);\n\t\t\tdepth_norm[i] = clamp(depth_norm[i], uint8_t{0}, uint8_t{255});\n\t\t}\n\t}\n\treturn depth_norm;\n}\nstd::vector RenderTarget::generate_heat_img() const {\n\t\/\/We use HSV to generate the heat map taking H = 240 as our min value (coolest)\n\t\/\/and H = 0 as our max (hottest)\n\tstd::vector heat_map(width * height);\n\tfloat min = std::numeric_limits::infinity();\n\tfloat max = std::numeric_limits::min();\n\tfor (const auto &f : float_buf){\n\t\tif (f == std::numeric_limits::infinity()){\n\t\t\tcontinue;\n\t\t}\n\t\tif (f < min){\n\t\t\tmin = f;\n\t\t}\n\t\tif (f > max){\n\t\t\tmax = f;\n\t\t}\n\t}\n\tfor (size_t i = 0; i < float_buf.size(); ++i){\n\t\tfloat hue = 240;\n\t\tif (float_buf[i] != std::numeric_limits::infinity()){\n\t\t\thue = (float_buf[i] - max) \/ (max - min) * -240.f;\n\t\t\thue = clamp(hue, 0.f, 240.f);\n\t\t}\n\t\thue \/= 60;\n\t\tfloat x = 1 - std::abs(static_cast(hue) % 2 - 1);\n\t\tif (hue >= 0 && hue < 1){\n\t\t\theat_map[i] = Colorf{1, x, 0};\n\t\t}\n\t\telse if (hue < 2){\n\t\t\theat_map[i] = Colorf{x, 1, 0};\n\t\t}\n\t\telse if (hue < 3){\n\t\t\theat_map[i] = Colorf{0, 1, x};\n\t\t}\n\t\telse if (hue < 4){\n\t\t\theat_map[i] = Colorf{0, x, 1};\n\t\t}\n\t\telse if (hue < 5){\n\t\t\theat_map[i] = Colorf{x, 0, 1};\n\t\t}\n\t\telse if (hue < 6){\n\t\t\theat_map[i] = Colorf{1, 0, x};\n\t\t}\n\t}\n\treturn heat_map;\n}\nbool RenderTarget::save_ppm(const std::string &file, const uint8_t *data) const {\n\tFILE *fp = fopen(file.c_str(), \"wb\");\n\tif (!fp){\n\t\tstd::cerr << \"RenderTarget::save_ppm Error: failed to open file \" << file << std::endl;\n\t\treturn false;\n\t}\n\tfprintf(fp, \"P6\\n%d %d\\n255\\n\", static_cast(width), static_cast(height));\n\tfwrite(data, 1, 3 * width * height, fp);\n\tfclose(fp);\n\treturn true;\n}\nbool RenderTarget::save_pgm(const std::string &file, const uint8_t * data) const {\n\tFILE *fp = fopen(file.c_str(), \"wb\");\n\tif (!fp){\n\t\tstd::cerr << \"RenderTarget::save_pgm Error: failed to open file \" << file << std::endl;\n\t\treturn false;\n\t}\n\tfprintf(fp, \"P5\\n%d %d\\n255\\n\", static_cast(width), static_cast(height));\n\tfwrite(data, 1, width * height, fp);\n\tfclose(fp);\n\treturn true;\n}\n\n<|endoftext|>"} {"text":"\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2020 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace {\n constexpr const char* KeyType = \"Type\";\n constexpr const char* KeyTag = \"Tag\";\n\n constexpr openspace::properties::Property::PropertyInfo EnabledInfo = {\n \"Enabled\",\n \"Is Enabled\",\n \"This setting determines whether this object will be visible or not.\"\n };\n\n constexpr openspace::properties::Property::PropertyInfo OpacityInfo = {\n \"Opacity\",\n \"Transparency\",\n \"This value determines the transparency of this object.\"\n };\n\n constexpr openspace::properties::Property::PropertyInfo RenderableTypeInfo = {\n \"Type\",\n \"Renderable Type\",\n \"This tells the type of the renderable.\",\n openspace::properties::Property::Visibility::Hidden\n };\n\n constexpr openspace::properties::Property::PropertyInfo BoundingSphereInfo = {\n \"BoundingSphere\",\n \"Bounding Sphere\",\n \"The size of the bounding sphere radius.\"\n };\n\n} \/\/ namespace\n\nnamespace openspace {\n\ndocumentation::Documentation Renderable::Documentation() {\n using namespace openspace::documentation;\n\n return {\n \"Renderable\",\n \"renderable\",\n {\n {\n KeyType,\n new StringAnnotationVerifier(\"A valid Renderable created by a factory\"),\n Optional::No,\n \"This key specifies the type of Renderable that gets created. It has to \"\n \"be one of the valid Renderables that are available for creation (see \"\n \"the FactoryDocumentation for a list of possible Renderables), which \"\n \"depends on the configration of the application\"\n },\n {\n EnabledInfo.identifier,\n new BoolVerifier,\n Optional::Yes,\n EnabledInfo.description\n },\n {\n OpacityInfo.identifier,\n new DoubleInRangeVerifier(0.0, 1.0),\n Optional::Yes,\n OpacityInfo.description\n }\n }\n };\n}\n\nstd::unique_ptr Renderable::createFromDictionary(\n const ghoul::Dictionary& dictionary)\n{\n documentation::testSpecificationAndThrow(Documentation(), dictionary, \"Renderable\");\n\n std::string renderableType = dictionary.value(KeyType);\n\n auto factory = FactoryManager::ref().factory();\n ghoul_assert(factory, \"Renderable factory did not exist\");\n std::unique_ptr result = factory->create(renderableType, dictionary);\n return result;\n}\n\n\nRenderable::Renderable(const ghoul::Dictionary& dictionary)\n : properties::PropertyOwner({ \"Renderable\" })\n , _enabled(EnabledInfo, true)\n , _opacity(OpacityInfo, 1.f, 0.f, 1.f)\n , _boundingSphere(BoundingSphereInfo, 0.f, 0.f, 3e10f)\n , _renderableType(RenderableTypeInfo, \"Renderable\")\n{\n ZoneScoped\n\n \/\/ I can't come up with a good reason not to do this for all renderables\n registerUpdateRenderBinFromOpacity();\n\n if (dictionary.hasKeyAndValue(KeyTag)) {\n std::string tagName = dictionary.value(KeyTag);\n if (!tagName.empty()) {\n addTag(std::move(tagName));\n }\n }\n else if (dictionary.hasKeyAndValue(KeyTag)) {\n const ghoul::Dictionary& tagNames = dictionary.value(KeyTag);\n const std::vector& keys = tagNames.keys();\n for (const std::string& key : keys) {\n std::string tagName = tagNames.value(key);\n if (!tagName.empty()) {\n addTag(std::move(tagName));\n }\n }\n }\n\n if (dictionary.hasKey(EnabledInfo.identifier)) {\n _enabled = dictionary.value(EnabledInfo.identifier);\n }\n\n if (dictionary.hasKey(OpacityInfo.identifier)) {\n _opacity = static_cast(dictionary.value(\n OpacityInfo.identifier)\n );\n }\n\n addProperty(_enabled);\n\n \/\/set type for UI\n if (dictionary.hasKey(RenderableTypeInfo.identifier)) {\n _renderableType = dictionary.value(\n RenderableTypeInfo.identifier\n );\n }\n\n if (dictionary.hasKey(BoundingSphereInfo.identifier)) {\n _boundingSphere = static_cast(\n dictionary.value(BoundingSphereInfo.identifier)\n );\n }\n\n addProperty(_renderableType);\n addProperty(_boundingSphere);\n}\n\nvoid Renderable::initialize() {}\n\nvoid Renderable::initializeGL() {}\n\nvoid Renderable::deinitialize() {}\n\nvoid Renderable::deinitializeGL() {}\n\nvoid Renderable::update(const UpdateData&) {}\n\nvoid Renderable::render(const RenderData&, RendererTasks&) {}\n\nvoid Renderable::setBoundingSphere(float boundingSphere) {\n _boundingSphere = boundingSphere;\n}\n\nfloat Renderable::boundingSphere() const {\n return _boundingSphere;\n}\n\nSurfacePositionHandle Renderable::calculateSurfacePositionHandle(\n const glm::dvec3& targetModelSpace) const\n{\n const glm::dvec3 directionFromCenterToTarget = glm::normalize(targetModelSpace);\n return {\n directionFromCenterToTarget * static_cast(boundingSphere()),\n directionFromCenterToTarget,\n 0.0\n };\n}\n\nbool Renderable::renderedWithDesiredData() const {\n return true;\n}\n\nRenderable::RenderBin Renderable::renderBin() const {\n return _renderBin;\n}\n\nvoid Renderable::setRenderBin(RenderBin bin) {\n _renderBin = bin;\n}\n\nbool Renderable::matchesRenderBinMask(int binMask) {\n return binMask & static_cast(renderBin());\n}\n\nbool Renderable::isVisible() const {\n return _enabled;\n}\n\nbool Renderable::isReady() const {\n return true;\n}\n\nbool Renderable::isEnabled() const {\n return _enabled;\n}\n\nvoid Renderable::onEnabledChange(std::function callback) {\n _enabled.onChange([this, c = std::move(callback)]() {\n c(isEnabled());\n });\n}\n\nvoid Renderable::setRenderBinFromOpacity() {\n if (_renderBin != Renderable::RenderBin::PostDeferredTransparent) {\n if (_opacity >= 0.f && _opacity < 1.f) {\n setRenderBin(Renderable::RenderBin::PreDeferredTransparent);\n }\n else {\n setRenderBin(Renderable::RenderBin::Opaque);\n }\n }\n}\n\nvoid Renderable::registerUpdateRenderBinFromOpacity() {\n _opacity.onChange([this](){\n if (_renderBin != Renderable::RenderBin::PostDeferredTransparent) {\n if (_opacity >= 0.f && _opacity < 1.f) {\n setRenderBin(Renderable::RenderBin::PreDeferredTransparent);\n }\n else {\n setRenderBin(Renderable::RenderBin::Opaque);\n }\n }\n });\n}\n\n} \/\/ namespace openspace\nUpdate opacity property description in renderable base class\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2020 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace {\n constexpr const char* KeyType = \"Type\";\n constexpr const char* KeyTag = \"Tag\";\n\n constexpr openspace::properties::Property::PropertyInfo EnabledInfo = {\n \"Enabled\",\n \"Is Enabled\",\n \"This setting determines whether this object will be visible or not.\"\n };\n\n constexpr openspace::properties::Property::PropertyInfo OpacityInfo = {\n \"Opacity\",\n \"Opacity\",\n \"This value determines the opacity of this renderable. A value of 0 means \"\n \"completely transparent.\"\n };\n\n constexpr openspace::properties::Property::PropertyInfo RenderableTypeInfo = {\n \"Type\",\n \"Renderable Type\",\n \"This tells the type of the renderable.\",\n openspace::properties::Property::Visibility::Hidden\n };\n\n constexpr openspace::properties::Property::PropertyInfo BoundingSphereInfo = {\n \"BoundingSphere\",\n \"Bounding Sphere\",\n \"The size of the bounding sphere radius.\"\n };\n\n} \/\/ namespace\n\nnamespace openspace {\n\ndocumentation::Documentation Renderable::Documentation() {\n using namespace openspace::documentation;\n\n return {\n \"Renderable\",\n \"renderable\",\n {\n {\n KeyType,\n new StringAnnotationVerifier(\"A valid Renderable created by a factory\"),\n Optional::No,\n \"This key specifies the type of Renderable that gets created. It has to \"\n \"be one of the valid Renderables that are available for creation (see \"\n \"the FactoryDocumentation for a list of possible Renderables), which \"\n \"depends on the configration of the application\"\n },\n {\n EnabledInfo.identifier,\n new BoolVerifier,\n Optional::Yes,\n EnabledInfo.description\n },\n {\n OpacityInfo.identifier,\n new DoubleInRangeVerifier(0.0, 1.0),\n Optional::Yes,\n OpacityInfo.description\n }\n }\n };\n}\n\nstd::unique_ptr Renderable::createFromDictionary(\n const ghoul::Dictionary& dictionary)\n{\n documentation::testSpecificationAndThrow(Documentation(), dictionary, \"Renderable\");\n\n std::string renderableType = dictionary.value(KeyType);\n\n auto factory = FactoryManager::ref().factory();\n ghoul_assert(factory, \"Renderable factory did not exist\");\n std::unique_ptr result = factory->create(renderableType, dictionary);\n return result;\n}\n\n\nRenderable::Renderable(const ghoul::Dictionary& dictionary)\n : properties::PropertyOwner({ \"Renderable\" })\n , _enabled(EnabledInfo, true)\n , _opacity(OpacityInfo, 1.f, 0.f, 1.f)\n , _boundingSphere(BoundingSphereInfo, 0.f, 0.f, 3e10f)\n , _renderableType(RenderableTypeInfo, \"Renderable\")\n{\n ZoneScoped\n\n \/\/ I can't come up with a good reason not to do this for all renderables\n registerUpdateRenderBinFromOpacity();\n\n if (dictionary.hasKeyAndValue(KeyTag)) {\n std::string tagName = dictionary.value(KeyTag);\n if (!tagName.empty()) {\n addTag(std::move(tagName));\n }\n }\n else if (dictionary.hasKeyAndValue(KeyTag)) {\n const ghoul::Dictionary& tagNames = dictionary.value(KeyTag);\n const std::vector& keys = tagNames.keys();\n for (const std::string& key : keys) {\n std::string tagName = tagNames.value(key);\n if (!tagName.empty()) {\n addTag(std::move(tagName));\n }\n }\n }\n\n if (dictionary.hasKey(EnabledInfo.identifier)) {\n _enabled = dictionary.value(EnabledInfo.identifier);\n }\n\n if (dictionary.hasKey(OpacityInfo.identifier)) {\n _opacity = static_cast(dictionary.value(\n OpacityInfo.identifier)\n );\n }\n\n addProperty(_enabled);\n\n \/\/set type for UI\n if (dictionary.hasKey(RenderableTypeInfo.identifier)) {\n _renderableType = dictionary.value(\n RenderableTypeInfo.identifier\n );\n }\n\n if (dictionary.hasKey(BoundingSphereInfo.identifier)) {\n _boundingSphere = static_cast(\n dictionary.value(BoundingSphereInfo.identifier)\n );\n }\n\n addProperty(_renderableType);\n addProperty(_boundingSphere);\n}\n\nvoid Renderable::initialize() {}\n\nvoid Renderable::initializeGL() {}\n\nvoid Renderable::deinitialize() {}\n\nvoid Renderable::deinitializeGL() {}\n\nvoid Renderable::update(const UpdateData&) {}\n\nvoid Renderable::render(const RenderData&, RendererTasks&) {}\n\nvoid Renderable::setBoundingSphere(float boundingSphere) {\n _boundingSphere = boundingSphere;\n}\n\nfloat Renderable::boundingSphere() const {\n return _boundingSphere;\n}\n\nSurfacePositionHandle Renderable::calculateSurfacePositionHandle(\n const glm::dvec3& targetModelSpace) const\n{\n const glm::dvec3 directionFromCenterToTarget = glm::normalize(targetModelSpace);\n return {\n directionFromCenterToTarget * static_cast(boundingSphere()),\n directionFromCenterToTarget,\n 0.0\n };\n}\n\nbool Renderable::renderedWithDesiredData() const {\n return true;\n}\n\nRenderable::RenderBin Renderable::renderBin() const {\n return _renderBin;\n}\n\nvoid Renderable::setRenderBin(RenderBin bin) {\n _renderBin = bin;\n}\n\nbool Renderable::matchesRenderBinMask(int binMask) {\n return binMask & static_cast(renderBin());\n}\n\nbool Renderable::isVisible() const {\n return _enabled;\n}\n\nbool Renderable::isReady() const {\n return true;\n}\n\nbool Renderable::isEnabled() const {\n return _enabled;\n}\n\nvoid Renderable::onEnabledChange(std::function callback) {\n _enabled.onChange([this, c = std::move(callback)]() {\n c(isEnabled());\n });\n}\n\nvoid Renderable::setRenderBinFromOpacity() {\n if (_renderBin != Renderable::RenderBin::PostDeferredTransparent) {\n if (_opacity >= 0.f && _opacity < 1.f) {\n setRenderBin(Renderable::RenderBin::PreDeferredTransparent);\n }\n else {\n setRenderBin(Renderable::RenderBin::Opaque);\n }\n }\n}\n\nvoid Renderable::registerUpdateRenderBinFromOpacity() {\n _opacity.onChange([this](){\n if (_renderBin != Renderable::RenderBin::PostDeferredTransparent) {\n if (_opacity >= 0.f && _opacity < 1.f) {\n setRenderBin(Renderable::RenderBin::PreDeferredTransparent);\n }\n else {\n setRenderBin(Renderable::RenderBin::Opaque);\n }\n }\n });\n}\n\n} \/\/ namespace openspace\n<|endoftext|>"} {"text":"#include \"list.h\"\n#include \"list.cpp\"\n#include \"queue.h\"\n#include \"queue.cpp\"\n#include \n#include \n#include \n#include \nusing namespace std;\n\n\/\/---------------------------------------------------------------------------\n\/\/ driver to test list\n\/\/---------------------------------------------------------------------------\nint main(void)\n{\n\tusing NP_ADT::CDLL; \/\/ not the same as std::list\n\tusing NP_ADT::Queue;\n\ttry\n\t{\n\t\tCDLL mylist(3, 'X');\n\t\tCDLL mylist2;\n\t\tCDLL mylist3(mylist);\n\t\tCDLL mylist4(mylist.begin(), mylist.end());\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tcout << \"mylist2: \" << mylist2 << endl;\n\t\tcout << \"mylist3: \" << mylist3 << endl;\n\t\tcout << \"mylist4: \" << mylist4 << endl;\n\t\tmylist.push_front('Y');\n\t\tmylist.push_front('Z');\n\t\tcout << mylist.pop_front() << endl;\n\t\tmylist2 = mylist; \/\/ a copy\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\t\/\/ create a new iterator pointing to the beginning of mylist\n\t\tCDLL::iterator listit(mylist.begin());\n\t\tcout << listit++->data << \" \";\n\t\tcout << listit->data << endl;\n\t\tcout << \"mylist: \";\n\t\tfor (unsigned int i = 0; i < mylist.getSize(); i++)\n\t\t\tcout << mylist[i] << \" \";\n\t\tcout << endl;\n\t\tcout << \"mylist[1] = 'N';\" << endl;\n\t\tmylist[1] = 'N';\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tmylist.release();\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tcout << \"mylist2: \" << mylist2 << endl;\n\n\t\t\/\/ Queue Pointer Tests\n\t\t\n\t\tmyqueue = &Queue(3, 'X');\n\t\tCDLL mylist2;\n\t\tCDLL mylist3(mylist);\n\t\tCDLL mylist4(mylist.begin(), mylist.end());\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tcout << \"mylist2: \" << mylist2 << endl;\n\t\tcout << \"mylist3: \" << mylist3 << endl;\n\t\tcout << \"mylist4: \" << mylist4 << endl;\n\t\tmylist.push_front('Y');\n\t\tmylist.push_front('Z');\n\t\tcout << mylist.pop_front() << endl;\n\t\tmylist2 = mylist; \/\/ a copy\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\t\/\/ create a new iterator pointing to the beginning of mylist\n\t\tCDLL::iterator listit(mylist.begin());\n\t\tcout << listit++->data << \" \";\n\t\tcout << listit->data << endl;\n\t\tcout << \"mylist: \";\n\t\tfor (unsigned int i = 0; i < mylist.getSize(); i++)\n\t\t\tcout << mylist[i] << \" \";\n\t\tcout << endl;\n\t\tcout << \"mylist[1] = 'N';\" << endl;\n\t\tmylist[1] = 'N';\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tmylist.release();\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tcout << \"mylist2: \" << mylist2 << endl;\n\t}\n\tcatch (exception e)\n\t{\n\t\tcerr << \"program terminated: \" << e.what() << endl;\n\t\tcin.get();\n\t\treturn EXIT_FAILURE;\n\t}\n\tcin.get(); \/\/ keep window open\n\treturn EXIT_SUCCESS;\n}comment out buggy code#include \"list.h\"\n#include \"list.cpp\"\n#include \"queue.h\"\n#include \"queue.cpp\"\n#include \n#include \n#include \n#include \nusing namespace std;\n\n\/\/---------------------------------------------------------------------------\n\/\/ driver to test list\n\/\/---------------------------------------------------------------------------\nint main(void)\n{\n\tusing NP_ADT::CDLL; \/\/ not the same as std::list\n\tusing NP_ADT::Queue;\n\ttry\n\t{\n\t\tCDLL mylist(3, 'X');\n\t\tCDLL mylist2;\n\t\tCDLL mylist3(mylist);\n\t\tCDLL mylist4(mylist.begin(), mylist.end());\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tcout << \"mylist2: \" << mylist2 << endl;\n\t\tcout << \"mylist3: \" << mylist3 << endl;\n\t\tcout << \"mylist4: \" << mylist4 << endl;\n\t\tmylist.push_front('Y');\n\t\tmylist.push_front('Z');\n\t\tcout << mylist.pop_front() << endl;\n\t\tmylist2 = mylist; \/\/ a copy\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\t\/\/ create a new iterator pointing to the beginning of mylist\n\t\tCDLL::iterator listit(mylist.begin());\n\t\tcout << listit++->data << \" \";\n\t\tcout << listit->data << endl;\n\t\tcout << \"mylist: \";\n\t\tfor (unsigned int i = 0; i < mylist.getSize(); i++)\n\t\t\tcout << mylist[i] << \" \";\n\t\tcout << endl;\n\t\tcout << \"mylist[1] = 'N';\" << endl;\n\t\tmylist[1] = 'N';\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tmylist.release();\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tcout << \"mylist2: \" << mylist2 << endl;\n\n\t\t\/\/ Queue Pointer Tests\n\t\t\/*\n\t\tmyqueue = &Queue(3, 'X');\n\t\tCDLL mylist2;\n\t\tCDLL mylist3(mylist);\n\t\tCDLL mylist4(mylist.begin(), mylist.end());\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tcout << \"mylist2: \" << mylist2 << endl;\n\t\tcout << \"mylist3: \" << mylist3 << endl;\n\t\tcout << \"mylist4: \" << mylist4 << endl;\n\t\tmylist.push_front('Y');\n\t\tmylist.push_front('Z');\n\t\tcout << mylist.pop_front() << endl;\n\t\tmylist2 = mylist; \/\/ a copy\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\t\/\/ create a new iterator pointing to the beginning of mylist\n\t\tCDLL::iterator listit(mylist.begin());\n\t\tcout << listit++->data << \" \";\n\t\tcout << listit->data << endl;\n\t\tcout << \"mylist: \";\n\t\tfor (unsigned int i = 0; i < mylist.getSize(); i++)\n\t\t\tcout << mylist[i] << \" \";\n\t\tcout << endl;\n\t\tcout << \"mylist[1] = 'N';\" << endl;\n\t\tmylist[1] = 'N';\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tmylist.release();\n\t\tcout << \"mylist: \" << mylist << endl;\n\t\tcout << \"mylist2: \" << mylist2 << endl;\n\t\t*\/\n\t}\n\tcatch (exception e)\n\t{\n\t\tcerr << \"program terminated: \" << e.what() << endl;\n\t\tcin.get();\n\t\treturn EXIT_FAILURE;\n\t}\n\tcin.get(); \/\/ keep window open\n\treturn EXIT_SUCCESS;\n}<|endoftext|>"} {"text":"\/*\nTidyEngine\nCopyright (C) 2016 Jakob Sinclair\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this program. If not, see .\nContact the author at: jakob.sinclair99@gmail.com\n*\/\n\n#include \"spriterenderer.hpp\"\n#include \"shader.hpp\"\n#include \"batch.hpp\"\n#include \"camera.hpp\"\n\nSpriteRenderer::SpriteRenderer()\n{\n\t;\t\n}\n\nSpriteRenderer::~SpriteRenderer()\n{\n\tif (m_VAOID != 0)\n\t\tglDeleteVertexArrays(1, &m_VAOID);\n\tif (m_VBOID != 0)\n\t\tglDeleteBuffers(1, &m_VBOID);\n}\n\nvoid SpriteRenderer::Initialise(Shader *shader, Batch *batch)\n{\n\tm_Shader = shader;\n\tm_Batch = batch;\n\n\tif (m_VAOID != 0)\n\t\tglDeleteVertexArrays(1, &m_VAOID);\n\tif (m_VBOID != 0)\n\t\tglDeleteBuffers(1, &m_VBOID);\n\t\n\tglGenVertexArrays(1, &m_VAOID);\n\tglBindVertexArray(m_VAOID);\n\n\tglGenBuffers(1, &m_VBOID);\n\tglBindBuffer(GL_ARRAY_BUFFER, m_VBOID);\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 6000000, NULL, GL_DYNAMIC_DRAW);\n\n\tglEnableVertexAttribArray(0);\n\tglEnableVertexAttribArray(1);\n\tglEnableVertexAttribArray(2);\n\t\n\tglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),\n\t\t\t(void*)offsetof(Vertex, Position));\n\tglVertexAttribPointer(1, 4, GL_FLOAT, GL_TRUE, sizeof(Vertex),\n\t\t\t(void*)offsetof(Vertex, Color));\n\tglVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),\n\t\t\t(void*)offsetof(Vertex, TexUV));\n\n\tglBindVertexArray(0);\n}\n\nvoid SpriteRenderer::Draw(Renderable *object)\n{\n\t\/* Updates the object to prepare for rendering *\/\n\tobject->Render();\n\tm_Batch->Draw(object);\n}\n\nvoid SpriteRenderer::Present(const Camera *camera)\n{\n\tif (camera != nullptr) {\n\t\tm_Shader->SetUniformMat4(\"projection\", camera->GetProj());\n\t\tm_Shader->SetUniformMat4(\"view\", camera->GetView());\n\t\tm_Shader->SetUniformMat4(\"model\", camera->GetModel());\n\t}\n\tm_Batch->Present();\n}libTidyEngine: cleaned up optimasation test\/*\nTidyEngine\nCopyright (C) 2016 Jakob Sinclair\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this program. If not, see .\nContact the author at: jakob.sinclair99@gmail.com\n*\/\n#define SPRITE_COUNT 1000000\n#include \"spriterenderer.hpp\"\n#include \"shader.hpp\"\n#include \"batch.hpp\"\n#include \"camera.hpp\"\n\nSpriteRenderer::SpriteRenderer()\n{\n\t;\t\n}\n\nSpriteRenderer::~SpriteRenderer()\n{\n\tif (m_VAOID != 0)\n\t\tglDeleteVertexArrays(1, &m_VAOID);\n\tif (m_VBOID != 0)\n\t\tglDeleteBuffers(1, &m_VBOID);\n}\n\nvoid SpriteRenderer::Initialise(Shader *shader, Batch *batch)\n{\n\tm_Shader = shader;\n\tm_Batch = batch;\n\n\tif (m_VAOID != 0)\n\t\tglDeleteVertexArrays(1, &m_VAOID);\n\tif (m_VBOID != 0)\n\t\tglDeleteBuffers(1, &m_VBOID);\n\t\n\tglGenVertexArrays(1, &m_VAOID);\n\tglBindVertexArray(m_VAOID);\n\n\tglGenBuffers(1, &m_VBOID);\n\tglBindBuffer(GL_ARRAY_BUFFER, m_VBOID);\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * SPRITE_COUNT * 6, NULL, GL_STREAM_DRAW);\n\n\tglEnableVertexAttribArray(0);\n\tglEnableVertexAttribArray(1);\n\tglEnableVertexAttribArray(2);\n\t\n\tglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),\n\t\t\t(void*)offsetof(Vertex, Position));\n\tglVertexAttribPointer(1, 4, GL_FLOAT, GL_TRUE, sizeof(Vertex),\n\t\t\t(void*)offsetof(Vertex, Color));\n\tglVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),\n\t\t\t(void*)offsetof(Vertex, TexUV));\n\n\tglBindVertexArray(0);\n}\n\nvoid SpriteRenderer::Draw(Renderable *object)\n{\n\t\/* Updates the object to prepare for rendering *\/\n\tobject->Render();\n\tm_Batch->Draw(object);\n}\n\nvoid SpriteRenderer::Present(const Camera *camera)\n{\n\tif (camera != nullptr) {\n\t\tm_Shader->SetUniformMat4(\"projection\", camera->GetProj());\n\t\tm_Shader->SetUniformMat4(\"view\", camera->GetView());\n\t\tm_Shader->SetUniformMat4(\"model\", camera->GetModel());\n\t}\n\tm_Batch->Present();\n}<|endoftext|>"} {"text":"\/**\n * @file\tsrc\/core\/ParameterizedWithSetters.cpp\n * @date\tAug. 2016\n * @author\tPhRG - opticalp.fr\n *\/\n\n\/*\n Copyright (c) 2016 Ph. Renaud-Goud \/ Opticalp\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\n#include \"ParameterizedWithSetters.h\"\n\n#include \"ParameterizedEntityWithWorkers.h\"\n#include \"ExecutionAbortedException.h\"\n\nusing Poco::AutoPtr;\n\nParameterizedWithSetters::~ParameterizedWithSetters()\n{\n\twhile (setters.size())\n\t{\n\t\tconst_cast(setters.begin()->get())->invalidate();\n\t\tsetters.erase(setters.begin());\n\t}\n}\n\nAutoPtr ParameterizedWithSetters::buildParameterSetter(\n\t\tsize_t paramIndex, bool immediateApply)\n{\n\tfor (std::set< Poco::AutoPtr >::iterator it = setters.begin(),\n\t\t\tite = setters.end(); it != ite; it++)\n\t{\n\t\tif (it->get()->getParameterIndex() == paramIndex)\n\t\t\tconst_cast(it->get())->invalidate();\n\t}\n\n\tAutoPtr ptr(new ParameterSetter(self, paramIndex, this, immediateApply));\n\tsetters.insert(ptr);\n\treturn ptr;\n}\n\nPoco::AutoPtr ParameterizedWithSetters::buildParameterSetter(\n\t\tstd::string paramName)\n{\n\treturn buildParameterSetter(self->getParameterIndex(paramName));\n}\n\nPoco::AutoPtr ParameterizedWithSetters::buildParameterSetter(\n\t\tstd::string paramName, bool imm)\n{\n\treturn buildParameterSetter(self->getParameterIndex(paramName), imm);\n}\n\nbool ParameterizedWithSetters::trySetParameter(size_t paramIndex)\n{\n alreadySetLock.lock();\n\n if (paramAlreadySet.count(paramIndex) == 0)\n return true;\n else\n {\n alreadySetLock.unlock();\n return false;\n }\n}\n\nvoid ParameterizedWithSetters::trigSetParameter(size_t paramIndex)\n{\n\n if (paramAlreadySet.insert(paramIndex).second)\n {\n if (paramAlreadySet.size() == setters.size())\n {\n if (preApply)\n self->tryApplyParameters(true);\n\n allSet.set();\n }\n\n alreadySetLock.unlock();\n }\n else\n {\n poco_bugcheck_msg(\"trying to trig a parameter that was not previously locked\");\n }\n}\n\nbool ParameterizedWithSetters::tryAllParametersSet()\n{\n\tif (setters.size())\n\t{\n\t\tif (allSet.tryWait(0))\n\t\t return true;\n\t\telse\n\t\t{\n\t\t for (std::set< Poco::AutoPtr >::iterator it = setters.begin(),\n\t\t ite = setters.end(); it != ite; it++)\n\t\t {\n\t\t alreadySetLock.lock();\n\t\t bool alreadySet = paramAlreadySet.count(const_cast(it->get())->getParameterIndex()) > 0 ;\n\t\t alreadySetLock.unlock();\n\n\t\t if ( !alreadySet && (it->get())->isTargetCancelling() )\n\t\t throw ExecutionAbortedException(\"Apply parameters: \"\n\t\t \"Cancellation upon user request (setter)\");\n\t\t }\n\n\t\t return false;\n\t\t}\n\t}\n\telse\n\t\treturn true;\n}\n\nvoid ParameterizedWithSetters::parametersTreated()\n{\n\tPoco::ScopedLock lock(alreadySetLock);\n\tparamAlreadySet.clear();\n\n\t\/\/ allSet event should be already reset (auto-reset).\n}\nAvoid possible deadlock\/**\n * @file\tsrc\/core\/ParameterizedWithSetters.cpp\n * @date\tAug. 2016\n * @author\tPhRG - opticalp.fr\n *\/\n\n\/*\n Copyright (c) 2016 Ph. Renaud-Goud \/ Opticalp\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\n#include \"ParameterizedWithSetters.h\"\n\n#include \"ParameterizedEntityWithWorkers.h\"\n#include \"ExecutionAbortedException.h\"\n\nusing Poco::AutoPtr;\n\nParameterizedWithSetters::~ParameterizedWithSetters()\n{\n\twhile (setters.size())\n\t{\n\t\tconst_cast(setters.begin()->get())->invalidate();\n\t\tsetters.erase(setters.begin());\n\t}\n}\n\nAutoPtr ParameterizedWithSetters::buildParameterSetter(\n\t\tsize_t paramIndex, bool immediateApply)\n{\n\tfor (std::set< Poco::AutoPtr >::iterator it = setters.begin(),\n\t\t\tite = setters.end(); it != ite; it++)\n\t{\n\t\tif (it->get()->getParameterIndex() == paramIndex)\n\t\t\tconst_cast(it->get())->invalidate();\n\t}\n\n\tAutoPtr ptr(new ParameterSetter(self, paramIndex, this, immediateApply));\n\tsetters.insert(ptr);\n\treturn ptr;\n}\n\nPoco::AutoPtr ParameterizedWithSetters::buildParameterSetter(\n\t\tstd::string paramName)\n{\n\treturn buildParameterSetter(self->getParameterIndex(paramName));\n}\n\nPoco::AutoPtr ParameterizedWithSetters::buildParameterSetter(\n\t\tstd::string paramName, bool imm)\n{\n\treturn buildParameterSetter(self->getParameterIndex(paramName), imm);\n}\n\nbool ParameterizedWithSetters::trySetParameter(size_t paramIndex)\n{\n alreadySetLock.lock();\n\n if (paramAlreadySet.count(paramIndex) == 0)\n return true;\n else\n {\n alreadySetLock.unlock();\n return false;\n }\n}\n\nvoid ParameterizedWithSetters::trigSetParameter(size_t paramIndex)\n{\n\n if (paramAlreadySet.insert(paramIndex).second)\n {\n bool done = (paramAlreadySet.size() == setters.size());\n\n alreadySetLock.unlock();\n if (done)\n {\n if (preApply)\n self->tryApplyParameters(true);\n\n allSet.set();\n }\n }\n else\n {\n poco_bugcheck_msg(\"trying to trig a parameter that was not previously locked\");\n }\n}\n\nbool ParameterizedWithSetters::tryAllParametersSet()\n{\n\tif (setters.size())\n\t{\n\t\tif (allSet.tryWait(0))\n\t\t return true;\n\t\telse\n\t\t{\n\t\t for (std::set< Poco::AutoPtr >::iterator it = setters.begin(),\n\t\t ite = setters.end(); it != ite; it++)\n\t\t {\n\t\t alreadySetLock.lock();\n\t\t bool alreadySet = paramAlreadySet.count(const_cast(it->get())->getParameterIndex()) > 0 ;\n\t\t alreadySetLock.unlock();\n\n\t\t if ( !alreadySet && (it->get())->isTargetCancelling() )\n\t\t throw ExecutionAbortedException(\"Apply parameters: \"\n\t\t \"Cancellation upon user request (setter)\");\n\t\t }\n\n\t\t return false;\n\t\t}\n\t}\n\telse\n\t\treturn true;\n}\n\nvoid ParameterizedWithSetters::parametersTreated()\n{\n\tPoco::ScopedLock lock(alreadySetLock);\n\tparamAlreadySet.clear();\n\n\t\/\/ allSet event should be already reset (auto-reset).\n}\n<|endoftext|>"} {"text":"#include \"i_core.h\"\n\nTargetPlayerController::TargetPlayerController(Actor* player):Controller()\n\t,mCounter(2)\n\t,mHeadingModifier(0)\n\t,mPlayer(player)\n{\n\n}\n\nvoid TargetPlayerController::SetActor(Actor* Obj)\n{\n\tController::SetActor(Obj);\n\tif(!mActor)return;\n\tmActor->SetHeading(0);\n\tmActor->SetSpeed(0.1);\n\tAction const* Act=ActionHolder::Get().GetAction(\"move\");\r\n\tif(Act) Act->Activate(*mActor);\r\n}\n\nvoid TargetPlayerController::Update( double Seconds )\n{\n\tif(!mActor)return;\n\tif(!mPlayer)return;\n\tmCounter+=Seconds;\n\tmCounter=0;\n\tdouble Rot=atan2(mPlayer->GetY()-mActor->GetY(),mPlayer->GetX()-mActor->GetX());\n\tdouble Radians=Rot-mActor->GetHeading();\n\tstatic const double pi=boost::math::constants::pi();\n while (Radians < -pi)\n {\n Radians += pi*2;\n }\n while (Radians > pi)\n {\n Radians -= pi*2;\n }\n\tdouble RotSpd=(Radians>0?1:-1)*0.01;\n\tmActor->SetHeading(mActor->GetHeading()+RotSpd);\n\tmActor->SetOrientation(mActor->GetHeading());\n}\nWhitespace fix#include \"i_core.h\"\n\nTargetPlayerController::TargetPlayerController(Actor* player):Controller()\n\t,mCounter(2)\n\t,mHeadingModifier(0)\n\t,mPlayer(player)\n{\n\n}\n\nvoid TargetPlayerController::SetActor(Actor* Obj)\n{\n\tController::SetActor(Obj);\n\tif(!mActor)return;\n\tmActor->SetHeading(0);\n\tmActor->SetSpeed(0.1);\n\tAction const* Act=ActionHolder::Get().GetAction(\"move\");\n\tif(Act) Act->Activate(*mActor);\n}\n\nvoid TargetPlayerController::Update( double Seconds )\n{\n\tif(!mActor)return;\n\tif(!mPlayer)return;\n\tmCounter+=Seconds;\n\tmCounter=0;\n\tdouble Rot=atan2(mPlayer->GetY()-mActor->GetY(),mPlayer->GetX()-mActor->GetX());\n\tdouble Radians=Rot-mActor->GetHeading();\n\tstatic const double pi=boost::math::constants::pi();\n\twhile (Radians < -pi)\n\t{\n\t\tRadians += pi*2;\n\t}\n\twhile (Radians > pi)\n\t{\n\t\tRadians -= pi*2;\n\t}\n\tdouble RotSpd=(Radians>0?1:-1)*0.01;\n\tmActor->SetHeading(mActor->GetHeading()+RotSpd);\n\tmActor->SetOrientation(mActor->GetHeading());\n}\n<|endoftext|>"} {"text":"\/*-------------------------------------------------------------------------\n *\n * FILE\n *\ttransaction_base.cxx\n *\n * DESCRIPTION\n * common code and definitions for the transaction classes\n * pqxx::transaction_base defines the interface for any abstract class that\n * represents a database transaction\n *\n * Copyright (c) 2001-2004, Jeroen T. Vermeulen \n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/compiler.h\"\n\n#include \n\n#include \"pqxx\/connection_base\"\n#include \"pqxx\/result\"\n#include \"pqxx\/tablestream\"\n#include \"pqxx\/transaction_base\"\n\n\nusing namespace PGSTD;\nusing namespace pqxx::internal;\n\n\npqxx::transaction_base::transaction_base(connection_base &C, \n \t\t\t\t\t const string &TName,\n\t\t\t\t\t const string &CName) :\n namedclass(TName, CName),\n m_Conn(C),\n m_UniqueCursorNum(1),\n m_Focus(),\n m_Status(st_nascent),\n m_Registered(false),\n m_PendingError()\n{\n m_Conn.RegisterTransaction(this);\n m_Registered = true;\n}\n\n\npqxx::transaction_base::~transaction_base()\n{\n try\n {\n if (!m_PendingError.empty())\n process_notice(\"UNPROCESSED ERROR: \" + m_PendingError + \"\\n\");\n\n if (m_Registered)\n {\n m_Conn.process_notice(description() + \" was never closed properly!\\n\");\n m_Conn.UnregisterTransaction(this);\n }\n }\n catch (const exception &e)\n {\n try\n {\n process_notice(string(e.what()) + \"\\n\");\n }\n catch (const exception &)\n {\n process_notice(e.what());\n }\n }\n}\n\n\nvoid pqxx::transaction_base::commit()\n{\n CheckPendingError();\n\n \/\/ Check previous status code. Caller should only call this function if\n \/\/ we're in \"implicit\" state, but multiple commits are silently accepted.\n switch (m_Status)\n {\n case st_nascent:\t\/\/ Empty transaction. No skin off our nose.\n return;\n\n case st_active:\t\/\/ Just fine. This is what we expect.\n break;\n\n case st_aborted:\n throw logic_error(\"Attempt to commit previously aborted \" + description());\n\n case st_committed:\n \/\/ Transaction has been committed already. This is not exactly proper \n \/\/ behaviour, but throwing an exception here would only give the impression\n \/\/ that an abort is needed--which would only confuse things further at this\n \/\/ stage.\n \/\/ Therefore, multiple commits are accepted, though under protest.\n m_Conn.process_notice(description() + \" committed more than once\\n\");\n return;\n\n case st_in_doubt:\n \/\/ Transaction may or may not have been committed. Report the problem but\n \/\/ don't compound our troubles by throwing.\n throw logic_error(description() +\n\t\t \"committed again while in an undetermined state\\n\");\n\n default:\n throw logic_error(\"libpqxx internal error: pqxx::transaction: invalid status code\");\n }\n \n \/\/ Tricky one. If stream is nested in transaction but inside the same scope,\n \/\/ the Commit() will come before the stream is closed. Which means the\n \/\/ commit is premature. Punish this swiftly and without fail to discourage\n \/\/ the habit from forming.\n if (m_Focus.get())\n throw runtime_error(\"Attempt to commit \" + description() + \" \"\n\t\t\t\"with \" + m_Focus.get()->description() + \" \"\n\t\t\t\"still open\");\n\n try\n {\n do_commit();\n m_Status = st_committed;\n }\n catch (const in_doubt_error &)\n {\n m_Status = st_in_doubt;\n throw;\n }\n catch (const exception &)\n {\n m_Status = st_aborted;\n throw;\n }\n\n m_Conn.AddVariables(m_Vars);\n\n End();\n}\n\n\nvoid pqxx::transaction_base::abort()\n{\n \/\/ Check previous status code. Quietly accept multiple aborts to \n \/\/ simplify emergency bailout code.\n switch (m_Status)\n {\n case st_nascent:\t\/\/ Never began transaction. No need to issue rollback.\n break;\n\n case st_active:\n try { do_abort(); } catch (const exception &) { }\n break;\n\n case st_aborted:\n return;\n\n case st_committed:\n throw logic_error(\"Attempt to abort previously committed \" + description());\n\n case st_in_doubt:\n \/\/ Aborting an in-doubt transaction is probably a reasonably sane response\n \/\/ to an insane situation. Log it, but do not complain.\n m_Conn.process_notice(\"Warning: \" + description() + \" \"\n\t\t \"aborted after going into indeterminate state; \"\n\t\t\t \"it may have been executed anyway.\\n\");\n return;\n\n default:\n throw logic_error(\"libpqxx internal error: invalid transaction status\");\n }\n\n m_Status = st_aborted;\n End();\n}\n\n\npqxx::result pqxx::transaction_base::exec(const char Query[],\n \t\t\t\t\t const string &Desc)\n{\n CheckPendingError();\n\n const string N = (Desc.empty() ? \"\" : \"'\" + Desc + \"' \");\n\n if (m_Focus.get())\n throw logic_error(\"Attempt to execute query \" + N + \n\t\t \"on \" + description() + \" \"\n\t\t \"with \" + m_Focus.get()->description() + \" \"\n\t\t \"still open\");\n\n switch (m_Status)\n {\n case st_nascent:\n \/\/ Make sure transaction has begun before executing anything\n Begin();\n break;\n\n case st_active:\n break;\n\n case st_committed:\n throw logic_error(\"Attempt to execute query \" + N +\n\t \"in committed \" + description());\n\n case st_aborted:\n throw logic_error(\"Attempt to execute query \" + N +\n\t \"in aborted \" + description());\n\n case st_in_doubt:\n throw logic_error(\"Attempt to execute query \" + N + \"in \" +\n\t\t description() + \", \"\n\t\t \"which is in indeterminate state\");\n default:\n throw logic_error(\"libpqxx internal error: pqxx::transaction: \"\n\t\t \"invalid status code\");\n }\n\n \/\/ TODO: Pass Desc to do_exec(), and from there on down\n return do_exec(Query);\n}\n\n\nvoid pqxx::transaction_base::set_variable(const string &Var,\n const string &Value)\n{\n \/\/ Before committing to this new value, see what the backend thinks about it\n m_Conn.RawSetVar(Var, Value);\n m_Vars[Var] = Value;\n}\n\n\nstring pqxx::transaction_base::get_variable(const string &Var) const\n{\n const map::const_iterator i = m_Vars.find(Var);\n if (i != m_Vars.end()) return i->second;\n return m_Conn.RawGetVar(Var);\n}\n\n\nvoid pqxx::transaction_base::Begin()\n{\n if (m_Status != st_nascent)\n throw logic_error(\"libpqxx internal error: pqxx::transaction: \"\n\t\t \"Begin() called while not in nascent state\");\n\n try\n {\n \/\/ Better handle any pending notifications before we begin\n m_Conn.get_notifs();\n\n do_begin();\n m_Status = st_active;\n }\n catch (const exception &)\n {\n End();\n throw;\n }\n}\n\n\n\nvoid pqxx::transaction_base::End() throw ()\n{\n if (!m_Registered) return;\n\n try\n {\n m_Conn.UnregisterTransaction(this);\n m_Registered = false;\n\n CheckPendingError();\n\n if (m_Focus.get())\n m_Conn.process_notice(\"Closing \" + description() + \" \"\n\t\t\t \" with \" + m_Focus.get()->description() + \" \"\n\t\t\t \"still open\\n\");\n\n if (m_Status == st_active) abort();\n }\n catch (const exception &e)\n {\n try\n {\n m_Conn.process_notice(string(e.what()) + \"\\n\");\n }\n catch (const exception &)\n {\n m_Conn.process_notice(e.what());\n }\n }\n}\n\n\n\nvoid pqxx::transaction_base::RegisterFocus(transactionfocus *S)\n{\n m_Focus.Register(S);\n}\n\n\nvoid pqxx::transaction_base::UnregisterFocus(transactionfocus *S) throw ()\n{\n try\n {\n m_Focus.Unregister(S);\n }\n catch (const exception &e)\n {\n m_Conn.process_notice(string(e.what()) + \"\\n\");\n }\n}\n\n\npqxx::result pqxx::transaction_base::DirectExec(const char C[], int Retries)\n{\n CheckPendingError();\n return m_Conn.Exec(C, Retries);\n}\n\n\nvoid pqxx::transaction_base::RegisterPendingError(const string &Err) throw ()\n{\n if (m_PendingError.empty() && !Err.empty())\n {\n try\n {\n m_PendingError = Err;\n }\n catch (const exception &e)\n {\n try\n {\n process_notice(\"UNABLE TO PROCESS ERROR\\n\");\n process_notice(e.what());\n process_notice(\"ERROR WAS:\");\n process_notice(Err);\n }\n catch (...)\n {\n }\n }\n }\n}\n\n\nvoid pqxx::transaction_base::CheckPendingError()\n{\n if (!m_PendingError.empty())\n {\n const string Err(m_PendingError);\n#ifdef PQXX_HAVE_STRING_CLEAR\n m_PendingError.clear();\n#else\n m_PendingError.resize(0);\n#endif\n throw runtime_error(m_PendingError);\n }\n}\n\n\nnamespace\n{\nstring MakeCopyString(const string &Table, const string &Columns)\n{\n string Q = \"COPY \" + Table + \" \";\n if (!Columns.empty()) Q += \"(\" + Columns + \") \";\n return Q;\n}\n} \/\/ namespace\n\n\nvoid pqxx::transaction_base::BeginCopyRead(const string &Table, \n const string &Columns)\n{\n exec(MakeCopyString(Table, Columns) + \"TO STDOUT\");\n}\n\n\nvoid pqxx::transaction_base::BeginCopyWrite(const string &Table,\n const string &Columns)\n{\n exec(MakeCopyString(Table, Columns) + \"FROM STDIN\");\n m_Conn.go_async();\n}\n\n\nvoid pqxx::internal::transactionfocus::register_me()\n{\n m_Trans.RegisterFocus(this);\n m_registered = true;\n}\n\n\nvoid pqxx::internal::transactionfocus::unregister_me() throw ()\n{\n m_Trans.UnregisterFocus(this);\n m_registered = false;\n}\n\nvoid pqxx::internal::transactionfocus::reg_pending_error(const string &err) throw ()\n{\n m_Trans.RegisterPendingError(err);\n}\n\n\nBugfix: no longer go async\/*-------------------------------------------------------------------------\n *\n * FILE\n *\ttransaction_base.cxx\n *\n * DESCRIPTION\n * common code and definitions for the transaction classes\n * pqxx::transaction_base defines the interface for any abstract class that\n * represents a database transaction\n *\n * Copyright (c) 2001-2004, Jeroen T. Vermeulen \n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/compiler.h\"\n\n#include \n\n#include \"pqxx\/connection_base\"\n#include \"pqxx\/result\"\n#include \"pqxx\/tablestream\"\n#include \"pqxx\/transaction_base\"\n\n\nusing namespace PGSTD;\nusing namespace pqxx::internal;\n\n\npqxx::transaction_base::transaction_base(connection_base &C, \n \t\t\t\t\t const string &TName,\n\t\t\t\t\t const string &CName) :\n namedclass(TName, CName),\n m_Conn(C),\n m_UniqueCursorNum(1),\n m_Focus(),\n m_Status(st_nascent),\n m_Registered(false),\n m_PendingError()\n{\n m_Conn.RegisterTransaction(this);\n m_Registered = true;\n}\n\n\npqxx::transaction_base::~transaction_base()\n{\n try\n {\n if (!m_PendingError.empty())\n process_notice(\"UNPROCESSED ERROR: \" + m_PendingError + \"\\n\");\n\n if (m_Registered)\n {\n m_Conn.process_notice(description() + \" was never closed properly!\\n\");\n m_Conn.UnregisterTransaction(this);\n }\n }\n catch (const exception &e)\n {\n try\n {\n process_notice(string(e.what()) + \"\\n\");\n }\n catch (const exception &)\n {\n process_notice(e.what());\n }\n }\n}\n\n\nvoid pqxx::transaction_base::commit()\n{\n CheckPendingError();\n\n \/\/ Check previous status code. Caller should only call this function if\n \/\/ we're in \"implicit\" state, but multiple commits are silently accepted.\n switch (m_Status)\n {\n case st_nascent:\t\/\/ Empty transaction. No skin off our nose.\n return;\n\n case st_active:\t\/\/ Just fine. This is what we expect.\n break;\n\n case st_aborted:\n throw logic_error(\"Attempt to commit previously aborted \" + description());\n\n case st_committed:\n \/\/ Transaction has been committed already. This is not exactly proper \n \/\/ behaviour, but throwing an exception here would only give the impression\n \/\/ that an abort is needed--which would only confuse things further at this\n \/\/ stage.\n \/\/ Therefore, multiple commits are accepted, though under protest.\n m_Conn.process_notice(description() + \" committed more than once\\n\");\n return;\n\n case st_in_doubt:\n \/\/ Transaction may or may not have been committed. Report the problem but\n \/\/ don't compound our troubles by throwing.\n throw logic_error(description() +\n\t\t \"committed again while in an undetermined state\\n\");\n\n default:\n throw logic_error(\"libpqxx internal error: pqxx::transaction: invalid status code\");\n }\n \n \/\/ Tricky one. If stream is nested in transaction but inside the same scope,\n \/\/ the Commit() will come before the stream is closed. Which means the\n \/\/ commit is premature. Punish this swiftly and without fail to discourage\n \/\/ the habit from forming.\n if (m_Focus.get())\n throw runtime_error(\"Attempt to commit \" + description() + \" \"\n\t\t\t\"with \" + m_Focus.get()->description() + \" \"\n\t\t\t\"still open\");\n\n try\n {\n do_commit();\n m_Status = st_committed;\n }\n catch (const in_doubt_error &)\n {\n m_Status = st_in_doubt;\n throw;\n }\n catch (const exception &)\n {\n m_Status = st_aborted;\n throw;\n }\n\n m_Conn.AddVariables(m_Vars);\n\n End();\n}\n\n\nvoid pqxx::transaction_base::abort()\n{\n \/\/ Check previous status code. Quietly accept multiple aborts to \n \/\/ simplify emergency bailout code.\n switch (m_Status)\n {\n case st_nascent:\t\/\/ Never began transaction. No need to issue rollback.\n break;\n\n case st_active:\n try { do_abort(); } catch (const exception &) { }\n break;\n\n case st_aborted:\n return;\n\n case st_committed:\n throw logic_error(\"Attempt to abort previously committed \" + description());\n\n case st_in_doubt:\n \/\/ Aborting an in-doubt transaction is probably a reasonably sane response\n \/\/ to an insane situation. Log it, but do not complain.\n m_Conn.process_notice(\"Warning: \" + description() + \" \"\n\t\t \"aborted after going into indeterminate state; \"\n\t\t\t \"it may have been executed anyway.\\n\");\n return;\n\n default:\n throw logic_error(\"libpqxx internal error: invalid transaction status\");\n }\n\n m_Status = st_aborted;\n End();\n}\n\n\npqxx::result pqxx::transaction_base::exec(const char Query[],\n \t\t\t\t\t const string &Desc)\n{\n CheckPendingError();\n\n const string N = (Desc.empty() ? \"\" : \"'\" + Desc + \"' \");\n\n if (m_Focus.get())\n throw logic_error(\"Attempt to execute query \" + N + \n\t\t \"on \" + description() + \" \"\n\t\t \"with \" + m_Focus.get()->description() + \" \"\n\t\t \"still open\");\n\n switch (m_Status)\n {\n case st_nascent:\n \/\/ Make sure transaction has begun before executing anything\n Begin();\n break;\n\n case st_active:\n break;\n\n case st_committed:\n throw logic_error(\"Attempt to execute query \" + N +\n\t \"in committed \" + description());\n\n case st_aborted:\n throw logic_error(\"Attempt to execute query \" + N +\n\t \"in aborted \" + description());\n\n case st_in_doubt:\n throw logic_error(\"Attempt to execute query \" + N + \"in \" +\n\t\t description() + \", \"\n\t\t \"which is in indeterminate state\");\n default:\n throw logic_error(\"libpqxx internal error: pqxx::transaction: \"\n\t\t \"invalid status code\");\n }\n\n \/\/ TODO: Pass Desc to do_exec(), and from there on down\n return do_exec(Query);\n}\n\n\nvoid pqxx::transaction_base::set_variable(const string &Var,\n const string &Value)\n{\n \/\/ Before committing to this new value, see what the backend thinks about it\n m_Conn.RawSetVar(Var, Value);\n m_Vars[Var] = Value;\n}\n\n\nstring pqxx::transaction_base::get_variable(const string &Var) const\n{\n const map::const_iterator i = m_Vars.find(Var);\n if (i != m_Vars.end()) return i->second;\n return m_Conn.RawGetVar(Var);\n}\n\n\nvoid pqxx::transaction_base::Begin()\n{\n if (m_Status != st_nascent)\n throw logic_error(\"libpqxx internal error: pqxx::transaction: \"\n\t\t \"Begin() called while not in nascent state\");\n\n try\n {\n \/\/ Better handle any pending notifications before we begin\n m_Conn.get_notifs();\n\n do_begin();\n m_Status = st_active;\n }\n catch (const exception &)\n {\n End();\n throw;\n }\n}\n\n\n\nvoid pqxx::transaction_base::End() throw ()\n{\n if (!m_Registered) return;\n\n try\n {\n m_Conn.UnregisterTransaction(this);\n m_Registered = false;\n\n CheckPendingError();\n\n if (m_Focus.get())\n m_Conn.process_notice(\"Closing \" + description() + \" \"\n\t\t\t \" with \" + m_Focus.get()->description() + \" \"\n\t\t\t \"still open\\n\");\n\n if (m_Status == st_active) abort();\n }\n catch (const exception &e)\n {\n try\n {\n m_Conn.process_notice(string(e.what()) + \"\\n\");\n }\n catch (const exception &)\n {\n m_Conn.process_notice(e.what());\n }\n }\n}\n\n\n\nvoid pqxx::transaction_base::RegisterFocus(transactionfocus *S)\n{\n m_Focus.Register(S);\n}\n\n\nvoid pqxx::transaction_base::UnregisterFocus(transactionfocus *S) throw ()\n{\n try\n {\n m_Focus.Unregister(S);\n }\n catch (const exception &e)\n {\n m_Conn.process_notice(string(e.what()) + \"\\n\");\n }\n}\n\n\npqxx::result pqxx::transaction_base::DirectExec(const char C[], int Retries)\n{\n CheckPendingError();\n return m_Conn.Exec(C, Retries);\n}\n\n\nvoid pqxx::transaction_base::RegisterPendingError(const string &Err) throw ()\n{\n if (m_PendingError.empty() && !Err.empty())\n {\n try\n {\n m_PendingError = Err;\n }\n catch (const exception &e)\n {\n try\n {\n process_notice(\"UNABLE TO PROCESS ERROR\\n\");\n process_notice(e.what());\n process_notice(\"ERROR WAS:\");\n process_notice(Err);\n }\n catch (...)\n {\n }\n }\n }\n}\n\n\nvoid pqxx::transaction_base::CheckPendingError()\n{\n if (!m_PendingError.empty())\n {\n const string Err(m_PendingError);\n#ifdef PQXX_HAVE_STRING_CLEAR\n m_PendingError.clear();\n#else\n m_PendingError.resize(0);\n#endif\n throw runtime_error(m_PendingError);\n }\n}\n\n\nnamespace\n{\nstring MakeCopyString(const string &Table, const string &Columns)\n{\n string Q = \"COPY \" + Table + \" \";\n if (!Columns.empty()) Q += \"(\" + Columns + \") \";\n return Q;\n}\n} \/\/ namespace\n\n\nvoid pqxx::transaction_base::BeginCopyRead(const string &Table, \n const string &Columns)\n{\n exec(MakeCopyString(Table, Columns) + \"TO STDOUT\");\n}\n\n\nvoid pqxx::transaction_base::BeginCopyWrite(const string &Table,\n const string &Columns)\n{\n exec(MakeCopyString(Table, Columns) + \"FROM STDIN\");\n}\n\n\nvoid pqxx::internal::transactionfocus::register_me()\n{\n m_Trans.RegisterFocus(this);\n m_registered = true;\n}\n\n\nvoid pqxx::internal::transactionfocus::unregister_me() throw ()\n{\n m_Trans.UnregisterFocus(this);\n m_registered = false;\n}\n\nvoid\npqxx::internal::transactionfocus::reg_pending_error(const string &err) throw ()\n{\n m_Trans.RegisterPendingError(err);\n}\n\n\n<|endoftext|>"} {"text":"\/*******************************************************************************\n * pxgsettings - A helper binary to query gsettings\n * Copyright (C) 2006 Nathaniel McCallum \n * Copyright (C) 2011 Dominique Leuenberger \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\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace std;\n\nstatic GMainLoop* loop = NULL;\n\nstatic int print_value(GVariant *value, const char *suffix) {\n\n\tif (!value) return 0;\n\tif (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {\n\t\treturn printf(\"%s%s\", g_variant_get_string(value, NULL), suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) {\n\t\treturn printf(\"%d%s\", g_variant_get_int32(value), suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) {\n\t\tgboolean result;\n\t\tresult = g_variant_get_boolean(value);\n\t\treturn printf(\"%s%s\", result ? \"true\" : \"false\", suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {\n\t\tint count;\n\t\tconst gchar** items;\n\t\titems = g_variant_get_strv(value, NULL);\n\t\tfor (count=0; items[count]; count++) {\n\t\t\tprintf(\"%s%s\", count < 1 ? \"\" : \",\", items[count]);\n\t\t}\n\t\tprintf(\"%s\", suffix);\n\t\treturn count;\n\t}\n\telse {\n\t\tthrow exception();\n\t}\n\n\treturn 0;\n}\n\nstatic void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) {\n\tprintf(\"%s\/%s\\t\", (gchar *)user_data, key);\n\tprint_value(g_settings_get_value(settings, key), \"\\n\");\n}\n\nstatic void on_sig(int \/*signal*\/) {\n\tg_main_loop_quit(loop);\n}\n\nstatic gboolean err(GIOChannel* \/*source*\/, GIOCondition \/*condition*\/, gpointer \/*data*\/) {\n\tg_main_loop_quit(loop);\n\treturn false;\n}\n\nstatic gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) {\n\tgchar *key, *val;\n\tGIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL);\n\n\t\/\/ Remove the trailing '\\n'\n\tfor (int i=0 ; key && key[i] ; i++)\n\t\tif (key[i] == '\\n')\n\t\t\tkey[i] = '\\0';\n\n\t\/\/ If we were successful\n\tif (key && st == G_IO_STATUS_NORMAL) {\n\t\tif (!g_strrstr(key, \"\\t\"))\n\t\t\tgoto exit;\n\n\t\tval = g_strrstr(key, \"\\t\") + 1;\n\t\t*(val-1) = '\\0';\n\n\t\tg_free(key);\n\t\treturn true;\n\t}\n\telse if (key && st == G_IO_STATUS_AGAIN) {\n\t\tg_free(key);\n\t\treturn in(source, condition, data);\n\t}\n\nexit:\n\tg_free(key);\n\treturn err(source, condition, data);\n}\n\nint main(int argc, char **argv) {\n\tif (argc < 2) return 1;\n\n\t\/\/ Register sighup handler\n\tif (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) {\n\t\tfprintf(stderr, \"Unable to trap signals!\");\n\t\treturn 2;\n\t}\n\n\t\/\/ Switch stdout to line buffering\n\tif (setvbuf(stdout, NULL, _IOLBF, 0)) {\n\t\tfprintf(stderr, \"Unable to switch stdout to line buffering!\");\n\t\treturn 3;\n\t}\n\n\t\/\/ Switch stdin to line buffering\n\tif (setvbuf(stdin, NULL, _IOLBF, 0)) {\n\t\tfprintf(stderr, \"Unable to switch stdin to line buffering!\");\n\t\treturn 4;\n\t}\n\n\t\/\/ Init\n#if !GLIB_CHECK_VERSION(2,36,0)\n\tg_type_init();\n#endif\n\n\t\/\/ Get the main loop\n\tloop = g_main_loop_new(NULL, false);\n\n\t\/\/ Setup our GIO Channels\n\tGIOChannel* inchan = g_io_channel_unix_new(fileno(stdin));\n\tGIOChannel* outchan = g_io_channel_unix_new(fileno(stdout));\n\tg_io_add_watch(inchan, G_IO_IN, in, NULL);\n\tg_io_add_watch(inchan, G_IO_PRI, in, NULL);\n\tg_io_add_watch(inchan, G_IO_ERR, err, NULL);\n\tg_io_add_watch(inchan, G_IO_HUP, err, NULL);\n\tg_io_add_watch(outchan, G_IO_ERR, err, NULL);\n\tg_io_add_watch(outchan, G_IO_HUP, err, NULL);\n\n\t\/\/ Get GSettings obkecy\n\tGSettings* settings;\n\n\tfor (int i=1; ipxgsettings: use the correct syntax to connect to the changed signal\/*******************************************************************************\n * pxgsettings - A helper binary to query gsettings\n * Copyright (C) 2006 Nathaniel McCallum \n * Copyright (C) 2011 Dominique Leuenberger \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\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace std;\n\nstatic GMainLoop* loop = NULL;\n\nstatic int print_value(GVariant *value, const char *suffix) {\n\n\tif (!value) return 0;\n\tif (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {\n\t\treturn printf(\"%s%s\", g_variant_get_string(value, NULL), suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) {\n\t\treturn printf(\"%d%s\", g_variant_get_int32(value), suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) {\n\t\tgboolean result;\n\t\tresult = g_variant_get_boolean(value);\n\t\treturn printf(\"%s%s\", result ? \"true\" : \"false\", suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {\n\t\tint count;\n\t\tconst gchar** items;\n\t\titems = g_variant_get_strv(value, NULL);\n\t\tfor (count=0; items[count]; count++) {\n\t\t\tprintf(\"%s%s\", count < 1 ? \"\" : \",\", items[count]);\n\t\t}\n\t\tprintf(\"%s\", suffix);\n\t\treturn count;\n\t}\n\telse {\n\t\tthrow exception();\n\t}\n\n\treturn 0;\n}\n\nstatic void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) {\n\tprintf(\"%s\/%s\\t\", (gchar *)user_data, key);\n\tprint_value(g_settings_get_value(settings, key), \"\\n\");\n}\n\nstatic void on_sig(int \/*signal*\/) {\n\tg_main_loop_quit(loop);\n}\n\nstatic gboolean err(GIOChannel* \/*source*\/, GIOCondition \/*condition*\/, gpointer \/*data*\/) {\n\tg_main_loop_quit(loop);\n\treturn false;\n}\n\nstatic gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) {\n\tgchar *key, *val;\n\tGIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL);\n\n\t\/\/ Remove the trailing '\\n'\n\tfor (int i=0 ; key && key[i] ; i++)\n\t\tif (key[i] == '\\n')\n\t\t\tkey[i] = '\\0';\n\n\t\/\/ If we were successful\n\tif (key && st == G_IO_STATUS_NORMAL) {\n\t\tif (!g_strrstr(key, \"\\t\"))\n\t\t\tgoto exit;\n\n\t\tval = g_strrstr(key, \"\\t\") + 1;\n\t\t*(val-1) = '\\0';\n\n\t\tg_free(key);\n\t\treturn true;\n\t}\n\telse if (key && st == G_IO_STATUS_AGAIN) {\n\t\tg_free(key);\n\t\treturn in(source, condition, data);\n\t}\n\nexit:\n\tg_free(key);\n\treturn err(source, condition, data);\n}\n\nint main(int argc, char **argv) {\n\tif (argc < 2) return 1;\n\n\t\/\/ Register sighup handler\n\tif (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) {\n\t\tfprintf(stderr, \"Unable to trap signals!\");\n\t\treturn 2;\n\t}\n\n\t\/\/ Switch stdout to line buffering\n\tif (setvbuf(stdout, NULL, _IOLBF, 0)) {\n\t\tfprintf(stderr, \"Unable to switch stdout to line buffering!\");\n\t\treturn 3;\n\t}\n\n\t\/\/ Switch stdin to line buffering\n\tif (setvbuf(stdin, NULL, _IOLBF, 0)) {\n\t\tfprintf(stderr, \"Unable to switch stdin to line buffering!\");\n\t\treturn 4;\n\t}\n\n\t\/\/ Init\n#if !GLIB_CHECK_VERSION(2,36,0)\n\tg_type_init();\n#endif\n\n\t\/\/ Get the main loop\n\tloop = g_main_loop_new(NULL, false);\n\n\t\/\/ Setup our GIO Channels\n\tGIOChannel* inchan = g_io_channel_unix_new(fileno(stdin));\n\tGIOChannel* outchan = g_io_channel_unix_new(fileno(stdout));\n\tg_io_add_watch(inchan, G_IO_IN, in, NULL);\n\tg_io_add_watch(inchan, G_IO_PRI, in, NULL);\n\tg_io_add_watch(inchan, G_IO_ERR, err, NULL);\n\tg_io_add_watch(inchan, G_IO_HUP, err, NULL);\n\tg_io_add_watch(outchan, G_IO_ERR, err, NULL);\n\tg_io_add_watch(outchan, G_IO_HUP, err, NULL);\n\n\t\/\/ Get GSettings obkecy\n\tGSettings* settings;\n\n\tfor (int i=1; i"} {"text":"\/*\n * Copyright 2020 The Project Oak Authors\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#include \"absl\/flags\/flag.h\"\n#include \"absl\/flags\/parse.h\"\n#include \"absl\/strings\/numbers.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"absl\/types\/optional.h\"\n#include \"examples\/trusted_information_retrieval\/proto\/trusted_information_retrieval.grpc.pb.h\"\n#include \"examples\/trusted_information_retrieval\/proto\/trusted_information_retrieval.pb.h\"\n#include \"glog\/logging.h\"\n#include \"include\/grpcpp\/grpcpp.h\"\n#include \"oak\/client\/application_client.h\"\n\nABSL_FLAG(std::string, address, \"localhost:8080\", \"Address of the Oak application to connect to\");\nABSL_FLAG(std::vector, location, std::vector{},\n \"Requested location (latitude and longitude separated by comma)\");\nABSL_FLAG(std::string, ca_cert, \"\", \"Path to the PEM-encoded CA root certificate\");\n\nusing ::oak::examples::trusted_information_retrieval::ListPointsOfInterestRequest;\nusing ::oak::examples::trusted_information_retrieval::ListPointsOfInterestResponse;\nusing ::oak::examples::trusted_information_retrieval::Location;\nusing ::oak::examples::trusted_information_retrieval::PointOfInterest;\nusing ::oak::examples::trusted_information_retrieval::TrustedInformationRetrieval;\n\nvoid get_nearest_point_of_interest(TrustedInformationRetrieval::Stub* stub, float latitude,\n float longitude) {\n grpc::ClientContext context;\n LOG(INFO) << \"Getting nearest point of interest:\";\n ListPointsOfInterestRequest request;\n Location* location = request.mutable_location();\n location->set_latitude(latitude);\n location->set_longitude(longitude);\n ListPointsOfInterestResponse response;\n grpc::Status status = stub->ListPointsOfInterest(&context, request, &response);\n if (!status.ok()) {\n LOG(ERROR) << \"Could not get nearest point of interest: \" << status.error_code() << \": \"\n << status.error_message();\n }\n LOG(INFO) << \"Response:\";\n LOG(INFO) << \" - name: \" << response.point_of_interest().name();\n LOG(INFO) << \" - latitude: \" << response.point_of_interest().location().latitude();\n LOG(INFO) << \" - longitude: \" << response.point_of_interest().location().longitude();\n}\n\nint main(int argc, char** argv) {\n absl::ParseCommandLine(argc, argv);\n\n std::string address = absl::GetFlag(FLAGS_address);\n std::string ca_cert = oak::ApplicationClient::LoadRootCert(absl::GetFlag(FLAGS_ca_cert));\n LOG(INFO) << \"Connecting to Oak Application: \" << address;\n\n auto stub = TrustedInformationRetrieval::NewStub(\n oak::ApplicationClient::CreateTlsChannel(address, ca_cert));\n\n \/\/ Parse arguments.\n auto location = absl::GetFlag(FLAGS_location);\n if (location.size() != 2) {\n LOG(FATAL) << \"Incorrect number of coordinates: \" << location.size() << \" (expected 2)\";\n }\n float latitude;\n if (!absl::SimpleAtof(location.front(), &latitude) && latitude >= -90.0 && latitude <= 90.0) {\n LOG(FATAL) << \"Latitude must be a valid floating point number >=-90 and <= 90.\";\n }\n float longitude;\n if (!absl::SimpleAtof(location.back(), &longitude) && longitude >= -180.0 && longitude <= 180.0) {\n LOG(FATAL) << \"Longitude must be a valid floating point number >= -180 and <= 180.\";\n }\n\n \/\/ Get nearest point of interest from the server.\n get_nearest_point_of_interest(stub.get(), latitude, longitude);\n\n return EXIT_SUCCESS;\n}\nUse labels in TIR (#1073)\/*\n * Copyright 2020 The Project Oak Authors\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#include \"absl\/flags\/flag.h\"\n#include \"absl\/flags\/parse.h\"\n#include \"absl\/strings\/numbers.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"absl\/types\/optional.h\"\n#include \"examples\/trusted_information_retrieval\/proto\/trusted_information_retrieval.grpc.pb.h\"\n#include \"examples\/trusted_information_retrieval\/proto\/trusted_information_retrieval.pb.h\"\n#include \"glog\/logging.h\"\n#include \"include\/grpcpp\/grpcpp.h\"\n#include \"oak\/client\/application_client.h\"\n\nABSL_FLAG(std::string, address, \"localhost:8080\", \"Address of the Oak application to connect to\");\nABSL_FLAG(std::vector, location, std::vector{},\n \"Requested location (latitude and longitude separated by comma)\");\nABSL_FLAG(std::string, ca_cert, \"\", \"Path to the PEM-encoded CA root certificate\");\n\nusing ::oak::examples::trusted_information_retrieval::ListPointsOfInterestRequest;\nusing ::oak::examples::trusted_information_retrieval::ListPointsOfInterestResponse;\nusing ::oak::examples::trusted_information_retrieval::Location;\nusing ::oak::examples::trusted_information_retrieval::PointOfInterest;\nusing ::oak::examples::trusted_information_retrieval::TrustedInformationRetrieval;\n\nvoid get_nearest_point_of_interest(TrustedInformationRetrieval::Stub* stub, float latitude,\n float longitude) {\n grpc::ClientContext context;\n LOG(INFO) << \"Getting nearest point of interest:\";\n ListPointsOfInterestRequest request;\n Location* location = request.mutable_location();\n location->set_latitude(latitude);\n location->set_longitude(longitude);\n ListPointsOfInterestResponse response;\n grpc::Status status = stub->ListPointsOfInterest(&context, request, &response);\n if (!status.ok()) {\n LOG(ERROR) << \"Could not get nearest point of interest: \" << status.error_code() << \": \"\n << status.error_message();\n }\n LOG(INFO) << \"Response:\";\n LOG(INFO) << \" - name: \" << response.point_of_interest().name();\n LOG(INFO) << \" - latitude: \" << response.point_of_interest().location().latitude();\n LOG(INFO) << \" - longitude: \" << response.point_of_interest().location().longitude();\n}\n\nint main(int argc, char** argv) {\n absl::ParseCommandLine(argc, argv);\n\n std::string address = absl::GetFlag(FLAGS_address);\n std::string ca_cert = oak::ApplicationClient::LoadRootCert(absl::GetFlag(FLAGS_ca_cert));\n LOG(INFO) << \"Connecting to Oak Application: \" << address;\n\n \/\/ TODO(#1066): Use a more restrictive Label.\n oak::label::Label label = oak::PublicUntrustedLabel();\n \/\/ Connect to the Oak Application.\n auto stub = TrustedInformationRetrieval::NewStub(oak::ApplicationClient::CreateChannel(\n address, oak::ApplicationClient::GetTlsChannelCredentials(ca_cert), label));\n if (stub == nullptr) {\n LOG(FATAL) << \"Failed to create application stub\";\n }\n\n \/\/ Parse arguments.\n auto location = absl::GetFlag(FLAGS_location);\n if (location.size() != 2) {\n LOG(FATAL) << \"Incorrect number of coordinates: \" << location.size() << \" (expected 2)\";\n }\n float latitude;\n if (!absl::SimpleAtof(location.front(), &latitude) && latitude >= -90.0 && latitude <= 90.0) {\n LOG(FATAL) << \"Latitude must be a valid floating point number >=-90 and <= 90.\";\n }\n float longitude;\n if (!absl::SimpleAtof(location.back(), &longitude) && longitude >= -180.0 && longitude <= 180.0) {\n LOG(FATAL) << \"Longitude must be a valid floating point number >= -180 and <= 180.\";\n }\n\n \/\/ Get nearest point of interest from the server.\n get_nearest_point_of_interest(stub.get(), latitude, longitude);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"Skip ExternalWrapTest on Ozone.<|endoftext|>"} {"text":"Fix compiler warnings.<|endoftext|>"} {"text":"\/*\n * Reference: http:\/\/plms.oxfordjournals.org\/content\/s2-42\/1\/230.full.pdf+html\n *\n * Instruction set\n * ===============\n * m-config symbol operations final m-config\n * string char op1,op2,... string\n *\n * op:\n * L - move left one step\n * R - move right one step\n * P - print symbol on tap\n * E - erase symbol from tap\n * symbol:\n * ~ - matches blank cell\n * * - matches any symbol\n * other char matches themselves\n *\n * Lines starting with # are ignored by the interpreter\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstruct Configuration {\n string state;\n char symbol;\n bool operator<(const Configuration &o) const {\n return state < o.state || (state == o.state && symbol < o.symbol);\n }\n};\n\nstruct Action {\n string ops;\n string state;\n};\n\nstring start;\nmap< Configuration, Action > program;\nmap< int, char > tape;\n \nvoid load_program() {\n cin.sync_with_stdio(false);\n string line;\n while (getline(cin, line)) {\n \/\/ skip empty lines\n if (line.length() == 0) {\n continue;\n }\n \n \/\/ lines begining with # are comments\n if (line.at(0) == '#') {\n continue;\n }\n\n istringstream iss(line);\n string state, symbol, ops, fstate;\n iss >> state >> symbol >> ops >> fstate;\n \n if (start.length() == 0) {\n start = state;\n }\n \n Configuration c = {state, symbol.at(0)};\n Action a = {ops, fstate};\n program[c] = a;\n }\n}\n\nvoid print_program() {\n for (auto it=program.begin(); it != program.end(); it++) {\n cout << it->first.state << \" \";\n cout << it->first.symbol << \" \";\n cout << it->second.ops << \" \";\n cout << it->second.state << endl;\n }\n}\n\nvoid print_tape() {\n cout << \"tape: \";\n for (auto it=tape.begin(); it != tape.end(); it++) {\n cout << it->second;\n }\n cout << endl;\n}\n\nvoid print_config(Configuration c) {\n cout << \"conf: \" << c.state << \" \" << c.symbol << endl;\n}\n\nchar read_tape(int tp) {\n if (tape.count(tp)) {\n return tape[tp];\n } else {\n return '~';\n }\n}\n\nint perform_ops(int tp, string ops) {\n for (int i = 0; i < ops.length(); i++) {\n char op = ops.at(i);\n switch (op) {\n case 'R':\n tp++;\n break;\n case 'L':\n tp--;\n break;\n case 'E':\n tape[tp] = '~';\n break;\n case 'P':\n i++;\n tape[tp] = ops.at(i);\n case ',':\n break;\n default:\n cout << \"unknown op: \" << op << endl;\n exit(1);\n }\n }\n return tp;\n}\n\nvoid eval(string curr, int tp, int max) {\n int cnt = 0;\n while (cnt < max) {\n cnt++;\n char s = read_tape(tp);\n Configuration c = {curr, s};\n if (program.count(c) == 0) {\n c = {curr, '*'};\n }\n if (program.count(c) == 0) {\n break;\n }\n Action a = program[c];\n tp = perform_ops(tp, a.ops);\n curr = a.state;\n print_config(c);\n print_tape();\n }\n}\n\nint main(int argc, char *argv[]) {\n load_program();\n print_program();\n eval(start, 0, 1000);\n print_tape();\n return 0;\n}\nmove globals into struct Machine\/*\n * Reference: http:\/\/plms.oxfordjournals.org\/content\/s2-42\/1\/230.full.pdf+html\n *\n * Instruction set\n * ===============\n * m-config symbol operations final m-config\n * string char op1,op2,... string\n *\n * op:\n * L - move left one step\n * R - move right one step\n * P - print symbol on tap\n * E - erase symbol from tap\n * symbol:\n * ~ - matches blank cell\n * * - matches any symbol\n * other char matches themselves\n *\n * Lines starting with # are ignored by the interpreter\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstruct Configuration {\n string state;\n char symbol;\n bool operator<(const Configuration &o) const {\n return state < o.state || (state == o.state && symbol < o.symbol);\n }\n};\n\nstruct Action {\n string ops;\n string state;\n};\n\nstruct Machine {\n int tp = 0;\n string start;\n map< Configuration, Action > program;\n map< int, char > tape;\n};\n \nvoid load_program(Machine &m) {\n cin.sync_with_stdio(false);\n string line;\n while (getline(cin, line)) {\n \/\/ skip empty lines\n if (line.length() == 0) {\n continue;\n }\n \n \/\/ lines begining with # are comments\n if (line.at(0) == '#') {\n continue;\n }\n\n istringstream iss(line);\n string state, symbol, ops, fstate;\n iss >> state >> symbol >> ops >> fstate;\n \n if (m.start.length() == 0) {\n m.start = state;\n }\n \n Configuration c = {state, symbol.at(0)};\n Action a = {ops, fstate};\n m.program[c] = a;\n }\n}\n\nvoid print_program(const Machine &m) {\n for (auto it=m.program.begin(); it != m.program.end(); it++) {\n cout << it->first.state << \" \";\n cout << it->first.symbol << \" \";\n cout << it->second.ops << \" \";\n cout << it->second.state << endl;\n }\n}\n\nvoid print_tape(const Machine &m) {\n cout << \"tape: \";\n for (auto it=m.tape.begin(); it != m.tape.end(); it++) {\n cout << it->second;\n }\n cout << endl;\n}\n\nvoid print_config(Configuration c) {\n cout << \"conf: \" << c.state << \" \" << c.symbol << endl;\n}\n\nchar read_tape(Machine &m, int tp) {\n if (m.tape.count(tp)) {\n return m.tape[tp];\n } else {\n return '~';\n }\n}\n\nint perform_ops(Machine &m, int tp, string ops) {\n for (int i = 0; i < ops.length(); i++) {\n char op = ops.at(i);\n switch (op) {\n case 'R':\n tp++;\n break;\n case 'L':\n tp--;\n break;\n case 'E':\n m.tape[tp] = '~';\n break;\n case 'P':\n i++;\n m.tape[tp] = ops.at(i);\n case ',':\n break;\n default:\n cout << \"unknown op: \" << op << endl;\n exit(1);\n }\n }\n return tp;\n}\n\nvoid eval(Machine &m, int max) {\n string curr = m.start;\n int cnt = 0;\n while (cnt < max) {\n cnt++;\n char s = read_tape(m, m.tp);\n Configuration c = {curr, s};\n if (m.program.count(c) == 0) {\n c = {curr, '*'};\n }\n if (m.program.count(c) == 0) {\n break;\n }\n Action a = m.program[c];\n m.tp = perform_ops(m, m.tp, a.ops);\n curr = a.state;\n print_config(c);\n print_tape(m);\n }\n}\n\nint main(int argc, char *argv[]) {\n Machine m;\n load_program(m);\n print_program(m);\n eval(m, 1000);\n print_tape(m);\n return 0;\n}\n<|endoftext|>"} {"text":"\/* \n * TTBlue Global Object\n * Copyright © 2008, Timothy Place\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"TTFoundation.h\"\n#include \"TTEnvironment.h\"\n#include \"TTClass.h\"\n\n#define thisTTClass TTEnvironment\n\n\n\/\/ The environment object has one instance, which is global in scope.\nTTEnvironment*\tttEnvironment = NULL;\n\n\n\/****************************************************************************************************\/\n\nTTEnvironment::TTEnvironment()\n\t: TTObject(kTTValNONE), debugBasic(false), debugMessaging(false), sr(0)\n{\t\n\tclasses = new TTHash();\n\ttags = new TTHash();\n\n\tregisterAttributeSimple(debugBasic,\t\tkTypeBoolean);\n\tregisterAttributeSimple(debugMessaging,\tkTypeBoolean);\n\tregisterAttributeSimple(sr,\t\t\t\tkTypeUInt32);\n\n\tregisterMessageWithArgument(getVersion);\n\n\tsetAttributeValue(TT(\"sr\"), TTUInt32(44100));\n}\n\n\nTTEnvironment::~TTEnvironment()\n{\n\t\/\/ If on Windows, we need to call FreeLibrary() on all plug-ins loaded with LoadLibrary()\n\t\/\/ On the Mac, we may need to do the equivalent\n\n\tdelete tags;\n\tdelete classes;\n}\n\n\nTTErr TTEnvironment::getVersion(TTValue &value)\n{\n\tvalue = TTFOUNDATION_VERSION_STRING;\n\treturn kTTErrNone;\n}\n\n\nTTErr TTEnvironment::registerClass(const TTSymbolPtr className, const TTString& tagString, const TTObjectInstantiationMethod anInstantiationMethod)\n{\n\tTTValue\t\tv((TTString&)tagString);\t\/\/ The tags to be associated with the class we are registering.\n\tTTValue\t\ttagObjects;\t\t\t\t\t\/\/ Contains a TTList of objects in the environment with the given tag.\n\tTTClassPtr\ttheClass;\n\tTTErr\t\terr;\n\tTTList*\t\tclassNamesForTag;\t\t\t\/\/ The TTList contained by tagObjects\n\tTTUInt16\tsize;\n\tTTSymbolPtr\ttag;\n\tTTValue\t\tresult;\n\n\terr = classes->lookup(className, result);\n\t\n\t\/\/ If a class is already registered with this name, then we do not want to register another class with the same name!\n\tif (err == kTTErrValueNotFound) {\n\t\t\n\t\t\/\/ 1. Turn the string into an array of symbols\n\t\tv.transformCSVStringToSymbolArray();\n\t\t\n\t\t\/\/ 2. Create the class and associate it with its name\n\t\ttheClass = new TTClass(className, v, anInstantiationMethod);\n\t\t\n\t\t\/\/ 3. For each symbol in the TTValue array...\n\t\tsize = v.getSize();\n\t\tfor (TTUInt16 i=0; ilookup(tag, tagObjects);\n\t\t\tif (!err) {\n\t\t\t\tclassNamesForTag = (TTList*)(TTPtr(tagObjects));\n\t\t\t\t\n\t\t\t\t\/\/ TODO: The following code demonstrates so extreme lameness that we need to evaluate.\n\t\t\t\t\/\/\tFirst, we should probably just do this section of code with TTValue instead of TTList (but we needed code to test TTList)\n\t\t\t\t\/\/\tSecond, TTList is taking references but keeping things internally as pointers, which leads to lots of confusion\n\t\t\t\t\/\/\tThird, we have to pass objects that are permanent - so no temporaries are allowed unless we make TTList do a copy\n\t\t\t\t\/\/\tetc.\n\n\t\t\t\t\/\/ TODO: We need to factor out a function to add a tag for a named class (or a given class ptr)\n\t\t\t\t\n\t\t\t\t\/\/classNamesForTag->append(className);\n\t\t\t\tclassNamesForTag->append(*new TTValue(className));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclassNamesForTag = new TTList;\n\t\t\t\ttagObjects = TTPtr(classNamesForTag);\n\t\t\t\ttags->append(tag ,tagObjects);\n\t\t\t\tclassNamesForTag->append(*new TTValue(className));\n\t\t\t}\n\t\t}\t\n\t\t\n\t\t\/\/ 4. Register it\n\t\terr = registerClass(theClass);\n\t}\n\treturn err;\n}\n\n\nTTErr TTEnvironment::registerClass(TTClassPtr theClass)\n{\n\treturn classes->append(theClass->name, TTPtr(theClass));\n}\n\n\nTTErr TTEnvironment::getAllClassNames(TTValue& returnedClassNames)\n{\n\treturn classes->getKeys(returnedClassNames);\n}\n\n\nTTErr TTEnvironment::getClassNamesWithTags(TTValue& classNames, const TTValue& searchTags)\n{\n\t\/\/ TODO: right now we only look for the first tag, we should look for each and then do a union on the results.\n\t\/\/ Well, that's not what's really happening, but the point is that this really only works if we are searching for one tag.\n\t\n\tTTUInt16\tsize = searchTags.getSize();\n\tTTSymbolPtr\ttag;\n\tTTValue\t\ttagObjects;\n\tTTErr\t\terr = kTTErrGeneric;\n\tTTList*\t\tclassNamesForTag;\n\t\n\tfor(TTUInt16 i=0; ilookup(tag, tagObjects);\n\t\tif(!err){\n\t\t\tclassNamesForTag = (TTList*)(TTPtr(tagObjects));\n\t\t\tclassNamesForTag->assignToValue(classNames);\n\t\t}\n\t}\n\n\treturn err;\n}\n\n\nTTErr TTEnvironment::createInstance(const TTSymbolPtr className, TTObjectPtr* anObject, const TTValue& anArgument)\n{\n\treturn createInstance(className, anObject, (TTValue&)anArgument); \/\/ throw away the const (I know, I know...), maybe the non-const constructor shouldn't exist at all?\n}\n\nTTErr TTEnvironment::createInstance(const TTSymbolPtr className, TTObjectPtr* anObject, TTValue& anArgument)\n{\n\tTTValue\t\tv;\n\tTTClassPtr\ttheClass;\n\tTTErr\t\terr;\n\tTTObjectPtr\tnewObject = NULL;\n\tTTObjectPtr\toldObject = NULL;\n\n\terr = classes->lookup(className, v);\n\tif(!err){\n\t\ttheClass = TTClassPtr(TTPtr(v));\n\t\tif(theClass)\n\t\t\terr = theClass->createInstance(&newObject, anArgument);\n\t\telse\n\t\t\terr = kTTErrGeneric;\n\t}\n\t\n\tif(!err && newObject){\n\t\tif(*anObject)\n\t\t\toldObject = *anObject;\n\t\t*anObject = newObject;\n\t\tif(oldObject)\n\t\t\treleaseInstance(&oldObject);\n\n\t\t(*anObject)->classPtr = theClass;\n\t\t(*anObject)->valid = true;\n\t}\n\t\t\n\t\/\/TODO: Add instance tracking. For each instance of a class, we push the instance onto a linked list of instances for that class\n\t\/\/ When the object is freed using deleteInstance(), then we pop it.\n\t\/\/ What would this achieve?\n\t\/\/\t- we could check statistics on them or do other logging\n\t\/\/\t- we could access instances remotely, and perhaps then manipulate them remotely in a shared manner\n\t\/\/\t- if an object is referenced by another object, and thus shared, then we need to reference counting here before freeing.\n\t\/\/ THEREFORE: we should have an addReference() and release() method (instead of a deleteInstance() method).\n\t\/\/\t- the reference counting itself should probably be done inside of TTObject though, yes?\n\treturn err;\n}\n\nTTObjectPtr TTEnvironment::referenceInstance(TTObjectPtr anObject)\n{\n\t\/\/ TODO: make sure that anObject is valid or wrap with an exception?\n\tanObject->referenceCount++;\n\treturn anObject;\n}\n\nTTErr TTEnvironment::releaseInstance(TTObjectPtr* anObject)\n{\n\tTTValue v = **anObject;\n\t\n\t(*anObject)->valid = false;\n\t(*anObject)->observers->iterateObjectsSendingMessage(TT(\"objectFreeing\"), v);\n\t\n\t\/\/ If the object is locked (e.g. in the middle of processing a vector in another thread) \n\t\/\/\tthen we spin until the lock is released\n\t\/\/\tTODO: we should also be able to time-out in the event that we have a dead lock.\n\twhile((*anObject)->getlock())\n\t\t;\n\n\t(*anObject)->referenceCount--;\n\tif((*anObject)->referenceCount < 1){\n\t\tdelete *anObject;\n\t\t*anObject = NULL;\n\t}\n\treturn kTTErrNone;\n}\n\n\n#if 0\n#pragma mark -\n#pragma mark Public Interface\n#endif\n\nTTErr TTObjectInstantiate(const TTSymbolPtr className, TTObjectPtr* returnedObjectPtr, TTValue& arguments)\n{\n\treturn ttEnvironment->createInstance(className, returnedObjectPtr, arguments);\n}\n\n\nTTErr TTObjectInstantiate(const TTSymbolPtr className, TTObjectPtr* returnedObjectPtr, const TTValue& arguments)\n{\n\treturn ttEnvironment->createInstance(className, returnedObjectPtr, arguments);\n}\n\n\nTTErr TTObjectInstantiate(const TTSymbolPtr className, TTObjectPtr* returnedObjectPtr, const TTUInt16 arguments)\n{\n\tTTValue\tv(arguments);\n\treturn ttEnvironment->createInstance(className, returnedObjectPtr, v);\n}\n\n\nTTObjectPtr TTObjectReference(TTObjectPtr anObject)\n{\n\treturn ttEnvironment->referenceInstance(anObject);\n}\n\n\nTTErr TTObjectRelease(TTObjectPtr* anObject)\n{\n\tif(*anObject)\n\t\treturn ttEnvironment->releaseInstance(anObject);\n\telse\n\t\treturn kTTErrNone;\n}\n\n\nTTErr TTClassRegister(const TTSymbolPtr className, const TTString& tagString, const TTObjectInstantiationMethod anInstantiationMethod)\n{\n\treturn ttEnvironment->registerClass(className, tagString, anInstantiationMethod);\n}\n\nTTErr TTClassRegister(const TTSymbolPtr className, TTImmutableCString tagString, const TTObjectInstantiationMethod anInstantiationMethod)\n{\n\treturn ttEnvironment->registerClass(className, TTString(tagString), anInstantiationMethod);\n}\n\n\nTTErr TTGetRegisteredClassNames(TTValue& classNames)\n{\n\treturn ttEnvironment->getAllClassNames(classNames);\n}\n\n\nTTErr TTGetRegisteredClassNamesForTags(TTValue& classNames, const TTValue& searchTags)\n{\n\treturn ttEnvironment->getClassNamesWithTags(classNames, searchTags);\n}\n\n\nTTEnvironment: added an assertion to catch bad TTObject release attempts immediately, rather than waiting for memory corruption to bite us in some undetermined way later on...\/* \n * TTBlue Global Object\n * Copyright © 2008, Timothy Place\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"TTFoundation.h\"\n#include \"TTEnvironment.h\"\n#include \"TTClass.h\"\n\n#define thisTTClass TTEnvironment\n\n\n\/\/ The environment object has one instance, which is global in scope.\nTTEnvironment*\tttEnvironment = NULL;\n\n\n\/****************************************************************************************************\/\n\nTTEnvironment::TTEnvironment()\n\t: TTObject(kTTValNONE), debugBasic(false), debugMessaging(false), sr(0)\n{\t\n\tclasses = new TTHash();\n\ttags = new TTHash();\n\n\tregisterAttributeSimple(debugBasic,\t\tkTypeBoolean);\n\tregisterAttributeSimple(debugMessaging,\tkTypeBoolean);\n\tregisterAttributeSimple(sr,\t\t\t\tkTypeUInt32);\n\n\tregisterMessageWithArgument(getVersion);\n\n\tsetAttributeValue(TT(\"sr\"), TTUInt32(44100));\n}\n\n\nTTEnvironment::~TTEnvironment()\n{\n\t\/\/ If on Windows, we need to call FreeLibrary() on all plug-ins loaded with LoadLibrary()\n\t\/\/ On the Mac, we may need to do the equivalent\n\n\tdelete tags;\n\tdelete classes;\n}\n\n\nTTErr TTEnvironment::getVersion(TTValue &value)\n{\n\tvalue = TTFOUNDATION_VERSION_STRING;\n\treturn kTTErrNone;\n}\n\n\nTTErr TTEnvironment::registerClass(const TTSymbolPtr className, const TTString& tagString, const TTObjectInstantiationMethod anInstantiationMethod)\n{\n\tTTValue\t\tv((TTString&)tagString);\t\/\/ The tags to be associated with the class we are registering.\n\tTTValue\t\ttagObjects;\t\t\t\t\t\/\/ Contains a TTList of objects in the environment with the given tag.\n\tTTClassPtr\ttheClass;\n\tTTErr\t\terr;\n\tTTList*\t\tclassNamesForTag;\t\t\t\/\/ The TTList contained by tagObjects\n\tTTUInt16\tsize;\n\tTTSymbolPtr\ttag;\n\tTTValue\t\tresult;\n\n\terr = classes->lookup(className, result);\n\t\n\t\/\/ If a class is already registered with this name, then we do not want to register another class with the same name!\n\tif (err == kTTErrValueNotFound) {\n\t\t\n\t\t\/\/ 1. Turn the string into an array of symbols\n\t\tv.transformCSVStringToSymbolArray();\n\t\t\n\t\t\/\/ 2. Create the class and associate it with its name\n\t\ttheClass = new TTClass(className, v, anInstantiationMethod);\n\t\t\n\t\t\/\/ 3. For each symbol in the TTValue array...\n\t\tsize = v.getSize();\n\t\tfor (TTUInt16 i=0; ilookup(tag, tagObjects);\n\t\t\tif (!err) {\n\t\t\t\tclassNamesForTag = (TTList*)(TTPtr(tagObjects));\n\t\t\t\t\n\t\t\t\t\/\/ TODO: The following code demonstrates so extreme lameness that we need to evaluate.\n\t\t\t\t\/\/\tFirst, we should probably just do this section of code with TTValue instead of TTList (but we needed code to test TTList)\n\t\t\t\t\/\/\tSecond, TTList is taking references but keeping things internally as pointers, which leads to lots of confusion\n\t\t\t\t\/\/\tThird, we have to pass objects that are permanent - so no temporaries are allowed unless we make TTList do a copy\n\t\t\t\t\/\/\tetc.\n\n\t\t\t\t\/\/ TODO: We need to factor out a function to add a tag for a named class (or a given class ptr)\n\t\t\t\t\n\t\t\t\t\/\/classNamesForTag->append(className);\n\t\t\t\tclassNamesForTag->append(*new TTValue(className));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclassNamesForTag = new TTList;\n\t\t\t\ttagObjects = TTPtr(classNamesForTag);\n\t\t\t\ttags->append(tag ,tagObjects);\n\t\t\t\tclassNamesForTag->append(*new TTValue(className));\n\t\t\t}\n\t\t}\t\n\t\t\n\t\t\/\/ 4. Register it\n\t\terr = registerClass(theClass);\n\t}\n\treturn err;\n}\n\n\nTTErr TTEnvironment::registerClass(TTClassPtr theClass)\n{\n\treturn classes->append(theClass->name, TTPtr(theClass));\n}\n\n\nTTErr TTEnvironment::getAllClassNames(TTValue& returnedClassNames)\n{\n\treturn classes->getKeys(returnedClassNames);\n}\n\n\nTTErr TTEnvironment::getClassNamesWithTags(TTValue& classNames, const TTValue& searchTags)\n{\n\t\/\/ TODO: right now we only look for the first tag, we should look for each and then do a union on the results.\n\t\/\/ Well, that's not what's really happening, but the point is that this really only works if we are searching for one tag.\n\t\n\tTTUInt16\tsize = searchTags.getSize();\n\tTTSymbolPtr\ttag;\n\tTTValue\t\ttagObjects;\n\tTTErr\t\terr = kTTErrGeneric;\n\tTTList*\t\tclassNamesForTag;\n\t\n\tfor(TTUInt16 i=0; ilookup(tag, tagObjects);\n\t\tif(!err){\n\t\t\tclassNamesForTag = (TTList*)(TTPtr(tagObjects));\n\t\t\tclassNamesForTag->assignToValue(classNames);\n\t\t}\n\t}\n\n\treturn err;\n}\n\n\nTTErr TTEnvironment::createInstance(const TTSymbolPtr className, TTObjectPtr* anObject, const TTValue& anArgument)\n{\n\treturn createInstance(className, anObject, (TTValue&)anArgument); \/\/ throw away the const (I know, I know...), maybe the non-const constructor shouldn't exist at all?\n}\n\nTTErr TTEnvironment::createInstance(const TTSymbolPtr className, TTObjectPtr* anObject, TTValue& anArgument)\n{\n\tTTValue\t\tv;\n\tTTClassPtr\ttheClass;\n\tTTErr\t\terr;\n\tTTObjectPtr\tnewObject = NULL;\n\tTTObjectPtr\toldObject = NULL;\n\n\terr = classes->lookup(className, v);\n\tif(!err){\n\t\ttheClass = TTClassPtr(TTPtr(v));\n\t\tif(theClass)\n\t\t\terr = theClass->createInstance(&newObject, anArgument);\n\t\telse\n\t\t\terr = kTTErrGeneric;\n\t}\n\t\n\tif(!err && newObject){\n\t\tif(*anObject)\n\t\t\toldObject = *anObject;\n\t\t*anObject = newObject;\n\t\tif(oldObject)\n\t\t\treleaseInstance(&oldObject);\n\n\t\t(*anObject)->classPtr = theClass;\n\t\t(*anObject)->valid = true;\n\t}\n\t\t\n\t\/\/TODO: Add instance tracking. For each instance of a class, we push the instance onto a linked list of instances for that class\n\t\/\/ When the object is freed using deleteInstance(), then we pop it.\n\t\/\/ What would this achieve?\n\t\/\/\t- we could check statistics on them or do other logging\n\t\/\/\t- we could access instances remotely, and perhaps then manipulate them remotely in a shared manner\n\t\/\/\t- if an object is referenced by another object, and thus shared, then we need to reference counting here before freeing.\n\t\/\/ THEREFORE: we should have an addReference() and release() method (instead of a deleteInstance() method).\n\t\/\/\t- the reference counting itself should probably be done inside of TTObject though, yes?\n\treturn err;\n}\n\nTTObjectPtr TTEnvironment::referenceInstance(TTObjectPtr anObject)\n{\n\t\/\/ TODO: make sure that anObject is valid or wrap with an exception?\n\tanObject->referenceCount++;\n\treturn anObject;\n}\n\nTTErr TTEnvironment::releaseInstance(TTObjectPtr* anObject)\n{\n\tTTValue v = **anObject;\n\t\n\tTT_ASSERT(\"can only release a valid instance\", *anObject && (*anObject)->valid == 1 && (*anObject)->referenceCount);\n\t\n\t(*anObject)->valid = false;\n\t(*anObject)->observers->iterateObjectsSendingMessage(TT(\"objectFreeing\"), v);\n\t\n\t\/\/ If the object is locked (e.g. in the middle of processing a vector in another thread) \n\t\/\/\tthen we spin until the lock is released\n\t\/\/\tTODO: we should also be able to time-out in the event that we have a dead lock.\n\twhile((*anObject)->getlock())\n\t\t;\n\n\t(*anObject)->referenceCount--;\n\tif((*anObject)->referenceCount < 1){\n\t\tdelete *anObject;\n\t\t*anObject = NULL;\n\t}\n\treturn kTTErrNone;\n}\n\n\n#if 0\n#pragma mark -\n#pragma mark Public Interface\n#endif\n\nTTErr TTObjectInstantiate(const TTSymbolPtr className, TTObjectPtr* returnedObjectPtr, TTValue& arguments)\n{\n\treturn ttEnvironment->createInstance(className, returnedObjectPtr, arguments);\n}\n\n\nTTErr TTObjectInstantiate(const TTSymbolPtr className, TTObjectPtr* returnedObjectPtr, const TTValue& arguments)\n{\n\treturn ttEnvironment->createInstance(className, returnedObjectPtr, arguments);\n}\n\n\nTTErr TTObjectInstantiate(const TTSymbolPtr className, TTObjectPtr* returnedObjectPtr, const TTUInt16 arguments)\n{\n\tTTValue\tv(arguments);\n\treturn ttEnvironment->createInstance(className, returnedObjectPtr, v);\n}\n\n\nTTObjectPtr TTObjectReference(TTObjectPtr anObject)\n{\n\treturn ttEnvironment->referenceInstance(anObject);\n}\n\n\nTTErr TTObjectRelease(TTObjectPtr* anObject)\n{\n\tif(*anObject)\n\t\treturn ttEnvironment->releaseInstance(anObject);\n\telse\n\t\treturn kTTErrNone;\n}\n\n\nTTErr TTClassRegister(const TTSymbolPtr className, const TTString& tagString, const TTObjectInstantiationMethod anInstantiationMethod)\n{\n\treturn ttEnvironment->registerClass(className, tagString, anInstantiationMethod);\n}\n\nTTErr TTClassRegister(const TTSymbolPtr className, TTImmutableCString tagString, const TTObjectInstantiationMethod anInstantiationMethod)\n{\n\treturn ttEnvironment->registerClass(className, TTString(tagString), anInstantiationMethod);\n}\n\n\nTTErr TTGetRegisteredClassNames(TTValue& classNames)\n{\n\treturn ttEnvironment->getAllClassNames(classNames);\n}\n\n\nTTErr TTGetRegisteredClassNamesForTags(TTValue& classNames, const TTValue& searchTags)\n{\n\treturn ttEnvironment->getClassNamesWithTags(classNames, searchTags);\n}\n\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2007 Torsten Rahn \"\n\/\/ Copyright 2007 Inge Wallin \"\n\/\/\n\n#include \n#include \n#include \n#include \n\n#include \n \n#include \"KdeMainWindow.h\"\n\n#include \"MarbleTest.h\"\n\n#if STATIC_BUILD\n #include \n Q_IMPORT_PLUGIN(qjpeg)\n Q_IMPORT_PLUGIN(qsvg)\n#endif\n \nint main (int argc, char *argv[])\n{\n KAboutData aboutData( \"marble\", 0, \n ki18n( \"Marble Desktop Globe\" ),\n \"0.3.8\", \n ki18n( \"A World Atlas.\" ),\n KAboutData::License_LGPL, ki18n( \"(c) 2007\" ),\n KLocalizedString(),\n \"http:\/\/edu.kde.org\/marble\" );\n aboutData.addAuthor( ki18n( \"Torsten Rahn\" ),\n ki18n( \"Original author and maintainer\" ),\n \"rahn@kde.org\" );\n aboutData.addAuthor( ki18n( \"Inge Wallin\" ),\n ki18n( \"co-maintainer\" ),\n \"inge@lysator.liu.se\" );\n\n KCmdLineArgs::init( argc, argv, &aboutData );\n\n \n KCmdLineOptions options;\n options.add( \"timedemo\", ki18n( \"Make a time measurement to check performance\" ) );\n options.add( \"gpsdemo\", ki18n( \"Check speed of gps drawing\" ) );\n options.add( \"enableCurrentLocation\", ki18n( \"Enable tab to show the current location\" ) );\n options.add( \"enableFileView\", \n ki18n( \"Enable tab to see gpxFileView\") );\n KCmdLineArgs::addCmdLineOptions( options );\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n KApplication app;\n\n MainWindow *window = new MainWindow();\n window->setAttribute( Qt::WA_DeleteOnClose, true );\n\n MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );\n\n window->show();\n\n if ( args->isSet( \"timedemo\" ) ) {\n window->resize(900, 640);\n marbleTest->timeDemo();\n return 0;\n }\n \n if ( args->isSet( \"gpsdemo\" ) ) {\n window->resize( 900, 640 );\n marbleTest->gpsDemo();\n return 0;\n }\n \n if ( args->isSet( \"enableCurrentLocation\" ) ) {\n window->controlView()->setCurrentLocationTabShown(true);\n }\n \n if ( args->isSet( \"enableFileView\" ) ) {\n window->controlView()->setFileViewTabShown(true);\n }\n\n \/\/ Read the files that are given on the command line.\n \/\/ FIXME: What should the '1' below really be?\n \/\/ Command line arguments, i.e. files to open\n for (int i = 0; i < args->count(); i++) {\n\n \/\/ FIXME: Use openUrl( args->url(i)) instead?\n if ( QFile::exists( args->arg( i ) ) )\n ( window->controlView() )->addPlaceMarkFile( args->arg( i ) );\n }\n\n delete marbleTest;\n\n return app.exec();\n}\n- sync version number \/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2007 Torsten Rahn \"\n\/\/ Copyright 2007 Inge Wallin \"\n\/\/\n\n#include \n#include \n#include \n#include \n\n#include \n \n#include \"KdeMainWindow.h\"\n\n#include \"MarbleTest.h\"\n\n#if STATIC_BUILD\n #include \n Q_IMPORT_PLUGIN(qjpeg)\n Q_IMPORT_PLUGIN(qsvg)\n#endif\n \nint main (int argc, char *argv[])\n{\n KAboutData aboutData( \"marble\", 0, \n ki18n( \"Marble Desktop Globe\" ),\n \"0.3.9\", \n ki18n( \"A World Atlas.\" ),\n KAboutData::License_LGPL, ki18n( \"(c) 2007\" ),\n KLocalizedString(),\n \"http:\/\/edu.kde.org\/marble\" );\n aboutData.addAuthor( ki18n( \"Torsten Rahn\" ),\n ki18n( \"Original author and maintainer\" ),\n \"rahn@kde.org\" );\n aboutData.addAuthor( ki18n( \"Inge Wallin\" ),\n ki18n( \"co-maintainer\" ),\n \"inge@lysator.liu.se\" );\n\n KCmdLineArgs::init( argc, argv, &aboutData );\n\n \n KCmdLineOptions options;\n options.add( \"timedemo\", ki18n( \"Make a time measurement to check performance\" ) );\n options.add( \"gpsdemo\", ki18n( \"Check speed of gps drawing\" ) );\n options.add( \"enableCurrentLocation\", ki18n( \"Enable tab to show the current location\" ) );\n options.add( \"enableFileView\", \n ki18n( \"Enable tab to see gpxFileView\") );\n KCmdLineArgs::addCmdLineOptions( options );\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n KApplication app;\n\n MainWindow *window = new MainWindow();\n window->setAttribute( Qt::WA_DeleteOnClose, true );\n\n MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );\n\n window->show();\n\n if ( args->isSet( \"timedemo\" ) ) {\n window->resize(900, 640);\n marbleTest->timeDemo();\n return 0;\n }\n \n if ( args->isSet( \"gpsdemo\" ) ) {\n window->resize( 900, 640 );\n marbleTest->gpsDemo();\n return 0;\n }\n \n if ( args->isSet( \"enableCurrentLocation\" ) ) {\n window->controlView()->setCurrentLocationTabShown(true);\n }\n \n if ( args->isSet( \"enableFileView\" ) ) {\n window->controlView()->setFileViewTabShown(true);\n }\n\n \/\/ Read the files that are given on the command line.\n \/\/ FIXME: What should the '1' below really be?\n \/\/ Command line arguments, i.e. files to open\n for (int i = 0; i < args->count(); i++) {\n\n \/\/ FIXME: Use openUrl( args->url(i)) instead?\n if ( QFile::exists( args->arg( i ) ) )\n ( window->controlView() )->addPlaceMarkFile( args->arg( i ) );\n }\n\n delete marbleTest;\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\ntemplate \nstd::ifstream& operator>> <> (std::ifstream& infile, Node* root);\n\ntemplate \nstd::ostream& operator<< <> (std::ostream& outfile, Node* root);\n\n\ntemplate \nstruct Node\n{\n\tNode* leftNode;\n\tNode* rightNode;\n\tT value;\n\n\tNode(T value)\n\t{\n\t\tthis->value = value;\n\t\tleftNode = nullptr;\n\t\trightNode = nullptr;\n\t}\n};\n\ntemplate \nclass BinarySearchTree\n{\nprivate:\n\tNode* _root;\n\tvoid destroyTree(Node* node);\n\tvoid insertElement(Node* &node, const T &value);\n\tNode* findPrev(Node* &node, const T& value);\n\tNode* findElement(const T& value) const;\n\npublic:\n\tBinarySearchTree();\n\t~BinarySearchTree();\n\n\tT value_() const;\n\tint count_(const Node* node) const;\n\n\tNode* leftNode_() const;\n\tNode* rightNode_() const;\n\tNode* root() const;\n\n\tvoid insert(const T& value);\n\tbool isFound(const T& value) const;\n\n\tNode* findPrev(const T& value);\n\n\tvoid infile(std::string filename);\n\tvoid outfile(Node* root, std::ostream& outfile) const;\n\tvoid out(std::string filename) const;\n\tvoid paintTree(const Node* node, int level) const;\n\tvoid deleteNode(const T& value);\n\t\n\tfriend std::ifstream& operator>> <> (std::ifstream& infile, Node* root);\n\tfriend std::ostream& operator<< <> (std::ostream& outfile, Node* root);\n};\n\ntemplate \nBinarySearchTree::BinarySearchTree()\n{\n\t_root = nullptr;\n}\n\ntemplate \nBinarySearchTree::~BinarySearchTree()\n{\n\tdestroyTree(_root);\n}\n\ntemplate \nvoid BinarySearchTree::destroyTree(Node* node)\n{\n\tif (!node)\n\t\treturn;\n\n\tdestroyTree(node->leftNode);\n\tdestroyTree(node->rightNode);\n\n\tdelete node;\n}\n\ntemplate \nT BinarySearchTree::value_() const\n{\n\treturn _root->value;\n}\n\ntemplate \nint BinarySearchTree::count_(const Node* node) const\n{\n\tif (!node)\n\t\treturn 0;\n\n\telse\n\t\treturn count_(node->leftNode) + count_(node->rightNode) + 1;\n}\n\ntemplate \nNode* BinarySearchTree::root() const\n{\n\treturn _root;\n}\n\ntemplate \nNode* BinarySearchTree::leftNode_() const\n{\n\treturn _root->leftNode;\n}\n\ntemplate \nNode* BinarySearchTree::rightNode_() const\n{\n\treturn _root->rightNode;\n}\n\ntemplate \nvoid BinarySearchTree::insertElement(Node* &node, const T &value)\n{\n\tif (node)\n\t{\n\t\tif (value == node->value)\n\t\t\tthrow std::logic_error(\"This is current element!\\n\");\n\t\tif (value < node->value)\n\t\t\tinsertElement(node->leftNode, value);\n\t\telse if (value > node->value)\n\t\t\tinsertElement(node->rightNode, value);\n\t}\n\telse node = new Node(value);\n}\n\ntemplate \nvoid BinarySearchTree::insert(const T& value)\n{\n\tinsertElement(_root, value);\n}\n\ntemplate \nNode* BinarySearchTree::findElement(const T& value) const\n{\n\tNode *currNode = _root;\n\n\twhile (currNode)\n\t{\n\t\tif (currNode->value == value)\n\t\t\tbreak;\n\t\telse\n\t\t{\n\t\t\tif (currNode->value < value)\n\t\t\t\tcurrNode = currNode->rightNode;\n\t\t\telse\n\t\t\t\tcurrNode = currNode->leftNode;\n\t\t}\n\t}\n\treturn currNode;\n}\n\ntemplate \nbool BinarySearchTree::isFound(const T& value) const\n{\n\tNode *retNode = findElement(value);\n\tif (retNode)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\ntemplate \nvoid BinarySearchTree::infile(std::string filename)\n{\n\tstd::ifstream infile;\n\tinfile.open(filename);\n\tif (!infile)\n\t\tthrow std::logic_error(\"The file isn't find\");\n\tT value;\n\tint count;\n\tinfile >> count;\n\twhile (count--)\n\t{\n\t\tinfile >> value;\n\t\tinsert(value);\n\t}\n\tinfile.close();\n}\n\ntemplate \nstd::ifstream& operator>> (std::string filename, Node* root)\n{\n\treturn root.infile(filename);\n} \n\ntemplate \nvoid BinarySearchTree::out(std::string filename) const\n{\n\tstd::ofstream ofile(filename);\n\tif (!ofile)\n\t\tthrow std::logic_error(\"The file isn't find\\n\");\n\tint count = count_(_root);\n\tif (count == 0)\n\t\tthrow std::logic_error(\"The tree is empty\\n\");\n\t\tofile << count << \" \";\n\toutfile(_root, ofile);\n\tofile.close();\n}\n\ntemplate \nvoid BinarySearchTree::outfile(Node* root, std::ostream& ofile) const\n{\n\tif (!root)\n\t\treturn;\n\telse\n\t{\n\t\tofile << root->value << \" \";\n\t\toutfile(root->rightNode, ofile);\n\t\toutfile(root->leftNode, ofile);\n\t}\n}\n\ntemplate \nstd::ostream& operator<< (std::ostream& outfile, Node* root)\n{\n\treturn root.outfile(outfile);\n}\n\ntemplate \nvoid BinarySearchTree::paintTree(const Node* node, int level) const\n{\n\tif (node)\n\t{\n\t\tpaintTree(node->rightNode, level++);\n\t\tfor (int i = 0; i < level; i++)\n\t\t{\n\t\t\tstd::cout << \"-\";\n\t\t}\n\t\tstd::cout << node->value << std::endl;\n\t\tpaintTree(node->leftNode, level++);\n\t}\n}\n\ntemplate \nvoid BinarySearchTree::deleteNode(const T& value)\n{\n\tif (isFound(value) == false)\n\t\tthrow std::logic_error(\"This element is not found in BST!\\n\");\n\tNode *currNode = findElement(value);\n\tNode *parentNode = findPrev(value);\n\n\tif (currNode->leftNode == nullptr && currNode->rightNode == nullptr)\n\t{\n\t\tif (parentNode->leftNode == currNode)\n\t\t\tparentNode->leftNode = nullptr;\n\t\tif (parentNode->rightNode == currNode)\n\t\t\tparentNode->rightNode = nullptr;\n\t\tcurrNode = nullptr;\n\t}\n\n\telse if (currNode->rightNode == nullptr)\n\t{\n\t\tif (parentNode->leftNode == currNode)\n\t\t\tparentNode->leftNode = currNode->leftNode;\n\t\tif (parentNode->rightNode == currNode)\n\t\t\tparentNode->rightNode = currNode->leftNode;\n\t\tcurrNode = nullptr;\n\t}\n\n\telse\n\t{\n\t\tNode * minNode = currNode->rightNode;\n\t\twhile (minNode->leftNode)\n\t\t\tminNode = minNode->leftNode;\n\t\tT val = minNode->value;\n\t\tdeleteNode(minNode->value);\n\t\tcurrNode->value = val;\n\t}\n}\n\ntemplate \nNode* BinarySearchTree::findPrev(Node* &node, const T &value)\n{\n\tNode* currNode = node;\n\n\tif (isFound(value))\n\t{\n\t\tif (value < currNode->value)\n\t\t\tif (value == currNode->leftNode->value)\n\t\t\t\treturn currNode;\n\t\t\telse\n\t\t\t\treturn findPrev(currNode->leftNode, value);\n\t\telse if (value > currNode->value)\n\t\t\tif (value == currNode->rightNode->value)\n\t\t\t\treturn currNode;\n\t\t\telse\n\t\t\t\treturn findPrev(currNode->rightNode, value);\n\t\telse return nullptr;\n\t}\n\n\telse return nullptr;\n}\n\ntemplate \nNode* BinarySearchTree::findPrev(const T& value)\n{\n\treturn findPrev(_root, value);\n}\nUpdate binary_search_tree.hpp#include \n#include \n#include \n#include \n\ntemplate \nstd::ifstream& operator>> <> (std::ifstream& infile, Node* root);\n\ntemplate \nstd::ostream& operator<< <> (std::ostream& outfile, Node* root);\n\n\ntemplate \nstruct Node\n{\n\tNode* leftNode;\n\tNode* rightNode;\n\tT value;\n\n\tNode(T value)\n\t{\n\t\tthis->value = value;\n\t\tleftNode = nullptr;\n\t\trightNode = nullptr;\n\t}\n};\n\ntemplate \nclass BinarySearchTree\n{\nprivate:\n\tNode* _root;\n\tvoid destroyTree(Node* node);\n\tvoid insertElement(Node* &node, const T &value);\n\tNode* findPrev(Node* &node, const T& value);\n\tNode* findElement(const T& value) const;\n\npublic:\n\tBinarySearchTree();\n\t~BinarySearchTree();\n\n\tT value_() const;\n\tint count_(const Node* node) const;\n\n\tNode* leftNode_() const;\n\tNode* rightNode_() const;\n\tNode* root() const;\n\n\tvoid insert(const T& value);\n\tbool isFound(const T& value) const;\n\n\tNode* findPrev(const T& value);\n\n\tvoid infile(std::string filename);\n\tvoid outfile(Node* root, std::ostream& outfile) const;\n\tvoid out(std::string filename) const;\n\tvoid paintTree(const Node* node, int level) const;\n\tvoid deleteNode(const T& value);\n\t\n\tfriend std::ifstream& operator>> <> (std::ifstream& infile, BinarySearchTree& node);\n\tfriend std::ostream& operator<< <> (std::ostream& outfile, BinarySearchTree& node);\n};\n\ntemplate \nBinarySearchTree::BinarySearchTree()\n{\n\t_root = nullptr;\n}\n\ntemplate \nBinarySearchTree::~BinarySearchTree()\n{\n\tdestroyTree(_root);\n}\n\ntemplate \nvoid BinarySearchTree::destroyTree(Node* node)\n{\n\tif (!node)\n\t\treturn;\n\n\tdestroyTree(node->leftNode);\n\tdestroyTree(node->rightNode);\n\n\tdelete node;\n}\n\ntemplate \nT BinarySearchTree::value_() const\n{\n\treturn _root->value;\n}\n\ntemplate \nint BinarySearchTree::count_(const Node* node) const\n{\n\tif (!node)\n\t\treturn 0;\n\n\telse\n\t\treturn count_(node->leftNode) + count_(node->rightNode) + 1;\n}\n\ntemplate \nNode* BinarySearchTree::root() const\n{\n\treturn _root;\n}\n\ntemplate \nNode* BinarySearchTree::leftNode_() const\n{\n\treturn _root->leftNode;\n}\n\ntemplate \nNode* BinarySearchTree::rightNode_() const\n{\n\treturn _root->rightNode;\n}\n\ntemplate \nvoid BinarySearchTree::insertElement(Node* &node, const T &value)\n{\n\tif (node)\n\t{\n\t\tif (value == node->value)\n\t\t\tthrow std::logic_error(\"This is current element!\\n\");\n\t\tif (value < node->value)\n\t\t\tinsertElement(node->leftNode, value);\n\t\telse if (value > node->value)\n\t\t\tinsertElement(node->rightNode, value);\n\t}\n\telse node = new Node(value);\n}\n\ntemplate \nvoid BinarySearchTree::insert(const T& value)\n{\n\tinsertElement(_root, value);\n}\n\ntemplate \nNode* BinarySearchTree::findElement(const T& value) const\n{\n\tNode *currNode = _root;\n\n\twhile (currNode)\n\t{\n\t\tif (currNode->value == value)\n\t\t\tbreak;\n\t\telse\n\t\t{\n\t\t\tif (currNode->value < value)\n\t\t\t\tcurrNode = currNode->rightNode;\n\t\t\telse\n\t\t\t\tcurrNode = currNode->leftNode;\n\t\t}\n\t}\n\treturn currNode;\n}\n\ntemplate \nbool BinarySearchTree::isFound(const T& value) const\n{\n\tNode *retNode = findElement(value);\n\tif (retNode)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\ntemplate \nvoid BinarySearchTree::infile(std::string filename)\n{\n\tstd::ifstream infile;\n\tinfile.open(filename);\n\tif (!infile)\n\t\tthrow std::logic_error(\"The file isn't find\");\n\tT value;\n\tint count;\n\tinfile >> count;\n\twhile (count--)\n\t{\n\t\tinfile >> value;\n\t\tinsert(value);\n\t}\n\tinfile.close();\n}\n\ntemplate \nstd::ifstream& operator>> (std::string filename, BinarySearchTree& node)\n{\n\treturn node.infile(filename);\n} \n\ntemplate \nvoid BinarySearchTree::out(std::string filename) const\n{\n\tstd::ofstream ofile(filename);\n\tif (!ofile)\n\t\tthrow std::logic_error(\"The file isn't find\\n\");\n\tint count = count_(_root);\n\tif (count == 0)\n\t\tthrow std::logic_error(\"The tree is empty\\n\");\n\t\tofile << count << \" \";\n\toutfile(_root, ofile);\n\tofile.close();\n}\n\ntemplate \nvoid BinarySearchTree::outfile(Node* root, std::ostream& ofile) const\n{\n\tif (!root)\n\t\treturn;\n\telse\n\t{\n\t\tofile << root->value << \" \";\n\t\toutfile(root->rightNode, ofile);\n\t\toutfile(root->leftNode, ofile);\n\t}\n}\n\ntemplate \nstd::ostream& operator<< (std::ostream& outfile, BinarySearchTree& node)\n{\n\treturn node.outfile(outfile);\n}\n\ntemplate \nvoid BinarySearchTree::paintTree(const Node* node, int level) const\n{\n\tif (node)\n\t{\n\t\tpaintTree(node->rightNode, level++);\n\t\tfor (int i = 0; i < level; i++)\n\t\t{\n\t\t\tstd::cout << \"-\";\n\t\t}\n\t\tstd::cout << node->value << std::endl;\n\t\tpaintTree(node->leftNode, level++);\n\t}\n}\n\ntemplate \nvoid BinarySearchTree::deleteNode(const T& value)\n{\n\tif (isFound(value) == false)\n\t\tthrow std::logic_error(\"This element is not found in BST!\\n\");\n\tNode *currNode = findElement(value);\n\tNode *parentNode = findPrev(value);\n\n\tif (currNode->leftNode == nullptr && currNode->rightNode == nullptr)\n\t{\n\t\tif (parentNode->leftNode == currNode)\n\t\t\tparentNode->leftNode = nullptr;\n\t\tif (parentNode->rightNode == currNode)\n\t\t\tparentNode->rightNode = nullptr;\n\t\tcurrNode = nullptr;\n\t}\n\n\telse if (currNode->rightNode == nullptr)\n\t{\n\t\tif (parentNode->leftNode == currNode)\n\t\t\tparentNode->leftNode = currNode->leftNode;\n\t\tif (parentNode->rightNode == currNode)\n\t\t\tparentNode->rightNode = currNode->leftNode;\n\t\tcurrNode = nullptr;\n\t}\n\n\telse\n\t{\n\t\tNode * minNode = currNode->rightNode;\n\t\twhile (minNode->leftNode)\n\t\t\tminNode = minNode->leftNode;\n\t\tT val = minNode->value;\n\t\tdeleteNode(minNode->value);\n\t\tcurrNode->value = val;\n\t}\n}\n\ntemplate \nNode* BinarySearchTree::findPrev(Node* &node, const T &value)\n{\n\tNode* currNode = node;\n\n\tif (isFound(value))\n\t{\n\t\tif (value < currNode->value)\n\t\t\tif (value == currNode->leftNode->value)\n\t\t\t\treturn currNode;\n\t\t\telse\n\t\t\t\treturn findPrev(currNode->leftNode, value);\n\t\telse if (value > currNode->value)\n\t\t\tif (value == currNode->rightNode->value)\n\t\t\t\treturn currNode;\n\t\t\telse\n\t\t\t\treturn findPrev(currNode->rightNode, value);\n\t\telse return nullptr;\n\t}\n\n\telse return nullptr;\n}\n\ntemplate \nNode* BinarySearchTree::findPrev(const T& value)\n{\n\treturn findPrev(_root, value);\n}\n<|endoftext|>"} {"text":"#include \"libnanocv\/nanocv.h\"\n#include \"libnanocv\/tasks\/task_synthetic_shapes.h\"\n#include \"libnanocv\/util\/thread.h\"\n#include \"libnanocv\/util\/measure.hpp\"\n#include \"libnanocv\/util\/tabulator.h\"\n#include \"libnanocv\/trainers\/batch.h\"\n#include \"libnanocv\/trainers\/minibatch.h\"\n#include \"libnanocv\/trainers\/stochastic.h\"\n\nusing namespace ncv;\n\ntemplate\n<\n typename ttrainer\n>\nvoid test_optimizer(const task_t& task, ttrainer trainer, const string_t& name, tabulator_t& table)\n{\n const size_t cmd_trials = 16;\n\n stats_t tvalues;\n stats_t vvalues;\n stats_t terrors;\n stats_t verrors;\n\n const size_t usec = ncv::measure_robustly_usec([&] ()\n {\n sampler_t tsampler(task);\n tsampler.setup(sampler_t::atype::annotated);\n\n sampler_t vsampler(task);\n tsampler.split(80, vsampler);\n\n const trainer_result_t result = trainer(tsampler, vsampler);\n\n tvalues(result.m_opt_state.m_tvalue);\n vvalues(result.m_opt_state.m_vvalue);\n\n terrors(result.m_opt_state.m_terror_avg);\n verrors(result.m_opt_state.m_verror_avg);\n }, cmd_trials);\n\n table.append(name)\n << tvalues.avg() << terrors.avg() << vvalues.avg() << verrors.avg()\n << (usec \/ 1000);\n}\n\nvoid test_optimizers(\n const task_t& task, const model_t& model, const loss_t& loss, const string_t& criterion,\n const string_t& config_name)\n{\n const size_t cmd_iterations = 32;\n const size_t cmd_epochs = cmd_iterations;\n const scalar_t cmd_epsilon = 1e-4;\n const bool verbose = false;\n\n \/\/ batch optimizers\n const auto batch_optimizers =\n {\n batch_optimizer::GD,\n batch_optimizer::CGD,\n batch_optimizer::LBFGS\n };\n\n \/\/ minibatch optimizers\n const auto minibatch_optimizers =\n {\n batch_optimizer::GD,\n batch_optimizer::CGD,\n batch_optimizer::LBFGS\n };\n\n \/\/ stochastic optimizers\n const auto stochastic_optimizers =\n {\n stochastic_optimizer::SG,\n stochastic_optimizer::SGA,\n stochastic_optimizer::SIA,\n stochastic_optimizer::AG,\n stochastic_optimizer::ADAGRAD,\n stochastic_optimizer::ADADELTA\n };\n\n \/\/ run optimizers and collect results\n tabulator_t table(\"optimizer\\\\\");\n table.header() << \"train loss\" << \"train error\" << \"valid loss\" << \"valid error\" << \"time [msec]\";\n\n for (batch_optimizer optimizer : batch_optimizers)\n {\n test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler)\n {\n return ncv::batch_train(\n model, task, tsampler, vsampler, ncv::n_threads(),\n loss, criterion, optimizer, cmd_iterations, cmd_epsilon, verbose);\n }, \"batch [\" + text::to_string(optimizer) + \"]\", table);\n }\n\n for (batch_optimizer optimizer : minibatch_optimizers)\n {\n test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler)\n {\n return ncv::minibatch_train(\n model, task, tsampler, vsampler, ncv::n_threads(),\n loss, criterion, optimizer, cmd_epochs, cmd_epsilon, verbose);\n }, \"minibatch [\" + text::to_string(optimizer) + \"]\", table);\n }\n\n for (stochastic_optimizer optimizer : stochastic_optimizers)\n {\n test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler)\n {\n return ncv::stochastic_train(\n model, task, tsampler, vsampler, ncv::n_threads(),\n loss, criterion, optimizer, cmd_epochs, verbose);\n }, \"stochastic [\" + text::to_string(optimizer) + \"]\", table);\n }\n\n table.print(std::cout);\n}\n\nint main(int argc, char *argv[])\n{\n ncv::init();\n\n const size_t cmd_samples = 8 * 1024;\n const size_t cmd_rows = 16;\n const size_t cmd_cols = 16;\n const size_t cmd_outputs = 8;\n\n synthetic_shapes_task_t task(\n \"rows=\" + text::to_string(cmd_rows) + \",\" +\n \"cols=\" + text::to_string(cmd_cols) + \",\" +\n \"color=luma\" + \",\" +\n \"dims=\" + text::to_string(cmd_outputs) + \",\" +\n \"size=\" + text::to_string(cmd_samples));\n task.load(\"\");\n\ttask.describe();\n\n const string_t lmodel0;\n const string_t lmodel1 = lmodel0 + \"linear:dims=32;act-snorm;\";\n const string_t lmodel2 = lmodel1 + \"linear:dims=32;act-snorm;\";\n const string_t lmodel3 = lmodel2 + \"linear:dims=32;act-snorm;\";\n\n string_t cmodel;\n cmodel = cmodel + \"conv:dims=8,rows=5,cols=5;pool-max;act-snorm;\";\n cmodel = cmodel + \"conv:dims=8,rows=3,cols=3;act-snorm;\";\n\n const string_t outlayer = \"linear:dims=\" + text::to_string(cmd_outputs) + \";\";\n\n strings_t cmd_networks =\n {\n lmodel0 + outlayer,\n lmodel1 + outlayer,\n lmodel2 + outlayer,\n lmodel3 + outlayer,\n\n cmodel + outlayer\n };\n\n const strings_t cmd_losses = { \"classnll\", \"logistic\" }; \/\/loss_manager_t::instance().ids();\n const strings_t cmd_criteria = { \"avg\" }; \/\/criterion_manager_t::instance().ids();\n\n \/\/ vary the model\n for (const string_t& cmd_network : cmd_networks)\n {\n log_info() << \"<<< running network [\" << cmd_network << \"] ...\";\n\n const rmodel_t model = model_manager_t::instance().get(\"forward-network\", cmd_network);\n assert(model);\n model->resize(task, true);\n\n \/\/ vary the loss\n for (const string_t& cmd_loss : cmd_losses)\n {\n log_info() << \"<<< running loss [\" << cmd_loss << \"] ...\";\n\n const rloss_t loss = loss_manager_t::instance().get(cmd_loss);\n assert(loss);\n\n \/\/ vary the criteria\n for (const string_t& cmd_criterion : cmd_criteria)\n {\n log_info() << \"<<< running criterion [\" << cmd_criterion << \"] ...\";\n\n test_optimizers(task, *model, *loss, cmd_criterion,\n \"loss [\" + cmd_loss + \"], criterion [\" + cmd_criterion + \"]\");\n }\n }\n\n log_info();\n }\n\n \/\/ OK\n log_info() << done;\n return EXIT_SUCCESS;\n}\nfix benchmark#include \"libnanocv\/nanocv.h\"\n#include \"libnanocv\/tasks\/task_synthetic_shapes.h\"\n#include \"libnanocv\/util\/thread.h\"\n#include \"libnanocv\/util\/measure.hpp\"\n#include \"libnanocv\/util\/tabulator.h\"\n#include \"libnanocv\/trainers\/batch.h\"\n#include \"libnanocv\/trainers\/minibatch.h\"\n#include \"libnanocv\/trainers\/stochastic.h\"\n\nusing namespace ncv;\n\ntemplate\n<\n typename ttrainer\n>\nvoid test_optimizer(const task_t& task, ttrainer trainer, const string_t& name, tabulator_t& table)\n{\n const size_t cmd_trials = 16;\n\n stats_t tvalues;\n stats_t vvalues;\n stats_t terrors;\n stats_t verrors;\n\n const size_t usec = ncv::measure_robustly_usec([&] ()\n {\n sampler_t tsampler(task);\n tsampler.setup(sampler_t::atype::annotated);\n\n sampler_t vsampler(task);\n tsampler.split(80, vsampler);\n\n const trainer_result_t result = trainer(tsampler, vsampler);\n\n tvalues(result.m_opt_state.m_tvalue);\n vvalues(result.m_opt_state.m_vvalue);\n\n terrors(result.m_opt_state.m_terror_avg);\n verrors(result.m_opt_state.m_verror_avg);\n }, cmd_trials);\n\n table.append(name)\n << tvalues.avg() << terrors.avg() << vvalues.avg() << verrors.avg()\n << (usec \/ 1000);\n}\n\nvoid test_optimizers(\n const task_t& task, model_t& model, const loss_t& loss, const string_t& criterion,\n const string_t& config_name)\n{\n const size_t cmd_iterations = 32;\n const size_t cmd_epochs = cmd_iterations;\n const scalar_t cmd_epsilon = 1e-4;\n const bool verbose = false;\n\n \/\/ batch optimizers\n const auto batch_optimizers =\n {\n batch_optimizer::GD,\n batch_optimizer::CGD,\n batch_optimizer::LBFGS\n };\n\n \/\/ minibatch optimizers\n const auto minibatch_optimizers =\n {\n batch_optimizer::GD,\n batch_optimizer::CGD,\n batch_optimizer::LBFGS\n };\n\n \/\/ stochastic optimizers\n const auto stochastic_optimizers =\n {\n stochastic_optimizer::SG,\n stochastic_optimizer::SGA,\n stochastic_optimizer::SIA,\n stochastic_optimizer::AG,\n stochastic_optimizer::ADAGRAD,\n stochastic_optimizer::ADADELTA\n };\n\n \/\/ run optimizers and collect results\n tabulator_t table(\"optimizer\\\\\");\n table.header() << \"train loss\" << \"train error\" << \"valid loss\" << \"valid error\" << \"time [msec]\";\n\n for (batch_optimizer optimizer : batch_optimizers)\n {\n test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler)\n {\n model.random_params();\n return ncv::batch_train(\n model, task, tsampler, vsampler, ncv::n_threads(),\n loss, criterion, optimizer, cmd_iterations, cmd_epsilon, verbose);\n }, \"batch [\" + text::to_string(optimizer) + \"]\", table);\n }\n\n for (batch_optimizer optimizer : minibatch_optimizers)\n {\n test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler)\n {\n model.random_params();\n return ncv::minibatch_train(\n model, task, tsampler, vsampler, ncv::n_threads(),\n loss, criterion, optimizer, cmd_epochs, cmd_epsilon, verbose);\n }, \"minibatch [\" + text::to_string(optimizer) + \"]\", table);\n }\n\n for (stochastic_optimizer optimizer : stochastic_optimizers)\n {\n test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler)\n {\n model.random_params();\n return ncv::stochastic_train(\n model, task, tsampler, vsampler, ncv::n_threads(),\n loss, criterion, optimizer, cmd_epochs, verbose);\n }, \"stochastic [\" + text::to_string(optimizer) + \"]\", table);\n }\n\n table.print(std::cout);\n}\n\nint main(int argc, char *argv[])\n{\n ncv::init();\n\n const size_t cmd_samples = 8 * 1024;\n const size_t cmd_rows = 16;\n const size_t cmd_cols = 16;\n const size_t cmd_outputs = 9;\n\n synthetic_shapes_task_t task(\n \"rows=\" + text::to_string(cmd_rows) + \",\" +\n \"cols=\" + text::to_string(cmd_cols) + \",\" +\n \"color=luma\" + \",\" +\n \"dims=\" + text::to_string(cmd_outputs) + \",\" +\n \"size=\" + text::to_string(cmd_samples));\n task.load(\"\");\n\ttask.describe();\n\n const string_t lmodel0;\n const string_t lmodel1 = lmodel0 + \"linear:dims=16;act-snorm;\";\n const string_t lmodel2 = lmodel1 + \"linear:dims=16;act-snorm;\";\n const string_t lmodel3 = lmodel2 + \"linear:dims=16;act-snorm;\";\n\n string_t cmodel;\n cmodel = cmodel + \"conv:dims=8,rows=5,cols=5;pool-max;act-snorm;\";\n cmodel = cmodel + \"conv:dims=8,rows=3,cols=3;act-snorm;\";\n\n const string_t outlayer = \"linear:dims=\" + text::to_string(cmd_outputs) + \";\";\n\n strings_t cmd_networks =\n {\n lmodel0 + outlayer,\n lmodel1 + outlayer,\n lmodel2 + outlayer,\n lmodel3 + outlayer,\n\n cmodel + outlayer\n };\n\n const strings_t cmd_losses = { \"classnll\", \"logistic\" }; \/\/loss_manager_t::instance().ids();\n const strings_t cmd_criteria = { \"avg\" }; \/\/criterion_manager_t::instance().ids();\n\n \/\/ vary the model\n for (const string_t& cmd_network : cmd_networks)\n {\n log_info() << \"<<< running network [\" << cmd_network << \"] ...\";\n\n const rmodel_t model = model_manager_t::instance().get(\"forward-network\", cmd_network);\n assert(model);\n model->resize(task, true);\n\n \/\/ vary the loss\n for (const string_t& cmd_loss : cmd_losses)\n {\n log_info() << \"<<< running loss [\" << cmd_loss << \"] ...\";\n\n const rloss_t loss = loss_manager_t::instance().get(cmd_loss);\n assert(loss);\n\n \/\/ vary the criteria\n for (const string_t& cmd_criterion : cmd_criteria)\n {\n log_info() << \"<<< running criterion [\" << cmd_criterion << \"] ...\";\n\n test_optimizers(task, *model, *loss, cmd_criterion,\n \"loss [\" + cmd_loss + \"], criterion [\" + cmd_criterion + \"]\");\n }\n }\n\n log_info();\n }\n\n \/\/ OK\n log_info() << done;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/* \n * TTBlue Class that maintains a table of symbols\n * Copyright © 2008, Timothy Place\n * \n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSymbolTable.h\"\n#include \"TTMutex.h\"\n#include \"TTValue.h\"\n\n\n#if defined( TT_PLATFORM_MAC ) || defined ( TT_PLATFORM_IPHONE )\n\/\/#include \n\/\/using namespace __gnu_cxx;\n#include \"boost\/unordered_map.hpp\"\nusing namespace boost;\n#elif TT_PLATFORM_LINUX\n#include \n#else\n#include \nusing namespace stdext;\t\/\/ Visual Studio 2008 puts the hash_map in this namespace\n#endif\n\n\n\n\/** A simple helper class used by TTSymbolTable for comparing hash_map keys. *\/\n#if defined( TT_PLATFORM_WIN )\nclass TTStringCompare : public stdext::hash_compare {\npublic:\n\tbool operator()(const TTCString s1, const TTCString s2) const\n\t{\n\t\treturn !strcmp(s1, s2);\n\t}\n\t\n\tstd::size_t operator()(const TTCString s)\n\t{\n\t\treturn stdext::hash_value(s);\n\t}\n};\n#elif defined( TT_PLATFORM_MAC ) || defined ( TT_PLATFORM_IPHONE )\nclass TTStringCompare {\npublic:\n\tbool operator()(const char* s1, const char* s2) const\n\t{\n\t\treturn !strcmp(s1, s2);\n\t}\n};\n#endif\n\n\n\n\/** A type that represents the key as a C-String and the value as a pointer to the matching TTSymbol object. *\/\ntypedef pair\t\t\t\t\t\t\t\t\t\tTTSymbolTablePair;\n\n\n\/** A hash_map type used by TTSymbolTable. *\/\n#ifdef TT_PLATFORM_WIN\ntypedef hash_map\t\t\t\t\t\t\t\t\t\tTTSymbolTableHash;\n#elif TT_PLATFORM_LINUX\ntypedef map\t\t\t\t\t\t\t\t\t\tTTSymbolTableHash;\n#else\ntypedef unordered_map, TTStringCompare>\tTTSymbolTableHash;\n#endif\n\n\/** An iterator for the STL hash_map used by TTSymbolTable. *\/\ntypedef TTSymbolTableHash::const_iterator\t\t\t\t\t\t\t\t\tTTSymbolTableIter;\n\n\n\nstatic TTMutex*\t\t\t\tsMutex = NULL;\nTTFOUNDATION_EXPORT TTSymbolTable*\t\tttSymbolTable = NULL;\n\n\n#define mSYMBOLTABLE ((TTSymbolTableHash*)(mSymbolTable))\n\n\n\/****************************************************************************************************\/\n\nTTSymbolTable::TTSymbolTable()\n{\n\tif (!sMutex)\n\t\tsMutex = new TTMutex(true);\n\tmSymbolTable = (TTPtr) new TTSymbolTableHash;\n\tmSYMBOLTABLE->insert(TTSymbolTablePair(\"\", new TTSymbol(\"\", 0))); \n}\n\n\nTTSymbolTable::~TTSymbolTable()\n{\n\tTTSymbolTableIter\titer;\n\n\tfor (iter = mSYMBOLTABLE->begin(); iter != mSYMBOLTABLE->end(); iter++)\n\t\tdelete TTSymbolPtr(iter->second);\n\tmSYMBOLTABLE->clear();\n\tdelete mSYMBOLTABLE;\n\t\/\/ TODO: we should reference count symbol tables and then free the mutex here, yes?\n}\n\n\nTTSymbol* TTSymbolTable::lookup(const char* aString)\n{\n\tTTSymbolTableIter\titer;\n\n\tsMutex->lock();\n\t\n\titer = mSYMBOLTABLE->find(aString);\n\tif (iter == mSYMBOLTABLE->end()) {\n\t\t\/\/ The symbol wasn't found in the table, so we need to create and add it.\n\t\t\/\/ TTLogMessage(\"Adding symbol: %s With Address: %x\", aString, aString);\n\t\tTTSymbolPtr\tnewSymbol = new TTSymbol(aString, mSYMBOLTABLE->size());\n\t\tmSYMBOLTABLE->insert(TTSymbolTablePair(newSymbol->getCString(), newSymbol)); \n\t\tsMutex->unlock();\n\t\treturn newSymbol; \n\t}\n\telse {\n\t\t\/\/ The symbol was found, so we return it.\n\t\tsMutex->unlock();\n\t\treturn iter->second;\n\t}\n}\n\n\nTTSymbol* TTSymbolTable::lookup(const TTString& aString)\n{\n\treturn lookup(aString.c_str());\n}\n\n\nTTSymbol* TTSymbolTable::lookup(const int& aNumberToBeConvertedToAString)\n{\n\tchar\tcString[16];\n\t\n\tsnprintf(cString, 16, \"%d\", aNumberToBeConvertedToAString);\n\treturn lookup(cString);\n}\n\n\nvoid TTSymbolTable::dump(TTValue& allSymbols)\n{\n\tTTSymbolTableIter\titer;\n\t\n\tTTLogMessage(\"---- DUMPING SYMBOL TABLE -- BEGIN ----\\n\");\n\tallSymbols.clear();\n\tfor (iter = mSYMBOLTABLE->begin(); iter != mSYMBOLTABLE->end(); iter++) {\n\t\tallSymbols.append(TTSymbolPtr(iter->second));\n\t\tTTLogMessage(\"KEY:%s VALUE:%s\\n\", iter->first, TTSymbolPtr(iter->second)->getCString());\n\t}\n\tTTLogMessage(\"---- DUMPING SYMBOL TABLE -- END ----\\n\");\n}\nTTSymbolTable: fixes for the unordered_map not working correctly with the previous C-String to Pointer mapping -- now we do std::string to pointer mapping, which is the common\/optimized case for unordered_map.\/* \n * TTBlue Class that maintains a table of symbols\n * Copyright © 2008, Timothy Place\n * \n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSymbolTable.h\"\n#include \"TTMutex.h\"\n#include \"TTValue.h\"\n\n\n#if defined( TT_PLATFORM_MAC ) || defined ( TT_PLATFORM_IPHONE )\n\/\/#include \n\/\/using namespace __gnu_cxx;\n#include \"boost\/unordered_map.hpp\"\nusing namespace boost;\n#elif TT_PLATFORM_LINUX\n#include \n#else\n#include \nusing namespace stdext;\t\/\/ Visual Studio 2008 puts the hash_map in this namespace\n#endif\n\n\n\n\/** A simple helper class used by TTSymbolTable for comparing hash_map keys. *\/\n#if defined( TT_PLATFORM_WIN )\nclass TTStringCompare : public stdext::hash_compare {\npublic:\n\tbool operator()(const TTCString s1, const TTCString s2) const\n\t{\n\t\treturn !strcmp(s1, s2);\n\t}\n\t\n\tstd::size_t operator()(const TTCString s)\n\t{\n\t\treturn stdext::hash_value(s);\n\t}\n};\n\/\/#elif defined( TT_PLATFORM_MAC ) || defined ( TT_PLATFORM_IPHONE )\n\/\/class TTStringCompare {\n\/\/public:\n\/\/\tbool operator()(const char* s1, const char* s2) const\n\/\/\t{\n\/\/\t\treturn !strcmp(s1, s2);\n\/\/\t}\n\/\/};\n#endif\n\n\n\n\/** A type that represents the key as a C-String and the value as a pointer to the matching TTSymbol object. *\/\ntypedef pair\t\t\t\tTTSymbolTablePair;\n\n\n\/** A hash_map type used by TTSymbolTable. *\/\n#ifdef TT_PLATFORM_WIN\ntypedef hash_map\t\t\t\tTTSymbolTableHash;\n#elif TT_PLATFORM_LINUX\ntypedef map\t\t\t\tTTSymbolTableHash;\n#else\n\/\/typedef unordered_map, TTStringCompare>\tTTSymbolTableHash;\n\/\/typedef unordered_map\t\tTTSymbolTableHash;\ntypedef unordered_map\t\tTTSymbolTableHash;\n#endif\n\n\/** An iterator for the STL hash_map used by TTSymbolTable. *\/\ntypedef TTSymbolTableHash::const_iterator\t\t\tTTSymbolTableIter;\n\n\n\nstatic TTMutex*\t\t\t\tsMutex = NULL;\nTTFOUNDATION_EXPORT TTSymbolTable*\t\tttSymbolTable = NULL;\n\n\n#define mSYMBOLTABLE ((TTSymbolTableHash*)(mSymbolTable))\n\n\n\/****************************************************************************************************\/\n\nTTSymbolTable::TTSymbolTable()\n{\n\tif (!sMutex)\n\t\tsMutex = new TTMutex(true);\n\tmSymbolTable = (TTPtr) new TTSymbolTableHash;\n\tmSYMBOLTABLE->insert(TTSymbolTablePair(\"\", new TTSymbol(\"\", 0))); \n}\n\n\nTTSymbolTable::~TTSymbolTable()\n{\n\tTTSymbolTableIter\titer;\n\n\tfor (iter = mSYMBOLTABLE->begin(); iter != mSYMBOLTABLE->end(); iter++)\n\t\tdelete TTSymbolPtr(iter->second);\n\tmSYMBOLTABLE->clear();\n\tdelete mSYMBOLTABLE;\n\t\/\/ TODO: we should reference count symbol tables and then free the mutex here, yes?\n}\n\n\nTTSymbol* TTSymbolTable::lookup(const char* aString)\n{\n#ifdef TT_PLATFORM_WIN\n\tTTSymbolTableIter\titer;\n\n\tsMutex->lock();\n\t\n\titer = mSYMBOLTABLE->find(aString);\n\tif (iter == mSYMBOLTABLE->end()) {\n\t\t\/\/ The symbol wasn't found in the table, so we need to create and add it.\n\t\t\/\/ TTLogMessage(\"Adding symbol: %s With Address: %x\", aString, aString);\n\t\tTTSymbolPtr\tnewSymbol = new TTSymbol(aString, mSYMBOLTABLE->size());\n\t\tmSYMBOLTABLE->insert(TTSymbolTablePair(newSymbol->getCString(), newSymbol)); \n\t\tsMutex->unlock();\n\t\treturn newSymbol; \n\t}\n\telse {\n\t\t\/\/ The symbol was found, so we return it.\n\t\tsMutex->unlock();\n\t\treturn iter->second;\n\t}\n#else\n\tconst TTString s(aString);\n\treturn lookup(s);\n#endif\t\n}\n\n\nTTSymbol* TTSymbolTable::lookup(const TTString& aString)\n{\n#ifdef TT_PLATFORM_WIN\n\treturn lookup(aString.c_str());\n#else\n\tTTSymbolTableIter\titer;\n\t\n\tsMutex->lock();\n\t\n\titer = mSYMBOLTABLE->find(aString);\n\tif (iter == mSYMBOLTABLE->end()) {\n\t\t\/\/ The symbol wasn't found in the table, so we need to create and add it.\n\t\t\/\/ TTLogMessage(\"Adding symbol: %s With Address: %x\", aString, aString);\n\t\tTTSymbolPtr\tnewSymbol = new TTSymbol(aString, mSYMBOLTABLE->size());\n\t\tmSYMBOLTABLE->insert(TTSymbolTablePair(newSymbol->getCString(), newSymbol)); \n\t\tsMutex->unlock();\n\t\treturn newSymbol; \n\t}\n\telse {\n\t\t\/\/ The symbol was found, so we return it.\n\t\tsMutex->unlock();\n\t\treturn iter->second;\n\t}\n#endif\n}\n\n\nTTSymbol* TTSymbolTable::lookup(const int& aNumberToBeConvertedToAString)\n{\n#ifdef TT_PLATFORM_WIN\n\tchar\tcString[16];\n\t\n\tsnprintf(cString, 16, \"%d\", aNumberToBeConvertedToAString);\n\treturn lookup(cString);\n#else\n\tchar\tcString[16];\n\t\n\tsnprintf(cString, 16, \"%d\", aNumberToBeConvertedToAString);\n\n\tTTString s(cString);\n\treturn lookup(s);\n#endif\n}\n\n\nvoid TTSymbolTable::dump(TTValue& allSymbols)\n{\n\tTTSymbolTableIter\titer;\n\t\n\tTTLogMessage(\"---- DUMPING SYMBOL TABLE -- BEGIN ----\\n\");\n\tallSymbols.clear();\n\tfor (iter = mSYMBOLTABLE->begin(); iter != mSYMBOLTABLE->end(); iter++) {\n\t\tallSymbols.append(TTSymbolPtr(iter->second));\n\t\tTTLogMessage(\"KEY:%s VALUE:%s\\n\", iter->first, TTSymbolPtr(iter->second)->getCString());\n\t}\n\tTTLogMessage(\"---- DUMPING SYMBOL TABLE -- END ----\\n\");\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#pragma once\n\n\/\/Get the implementations\n#include \"etl\/impl\/conv.hpp\"\n\nnamespace etl {\n\n\/*!\n * \\brief A basic configurable convolution expr\n * \\tparam T The value type\n * \\tparam D The dimensions of convolution\n * \\tparam TT The convolution type\n * \\tparam Impl The implementation class\n *\/\ntemplate \nstruct basic_conv_expr : impl_expr> {\n static_assert(D > 0, \"0D convolution is not valid\");\n\n using value_type = T; \/\/\/< The type of value of the expression\n using this_type = basic_conv_expr; \/\/\/< The type of this expression\n\n static constexpr const bool is_gpu = is_cufft_enabled || is_cudnn_enabled; \/\/\/< Indicates if the expression runs on GPU\n\n \/*!\n * \\brief The result type for given sub types\n * \\tparam A The left hand side epxpression type\n * \\tparam B The right hand side epxpression type\n *\/\n template \n using result_type = detail::expr_result_t;\n\n \/*!\n * \\brief Validate the convolutiond dimensions\n * \\param a The input matrix\n * \\þaram b The kernel matrix\n * \\þaram c The output matrix\n *\/\n template ::value)>\n static void check(const A& a, const B& b, const C& c) {\n cpp_unused(a);\n cpp_unused(b);\n cpp_unused(c);\n\n Impl::template check();\n }\n\n \/*!\n * \\brief Validate the convolutiond dimensions\n * \\param a The input matrix\n * \\þaram b The kernel matrix\n * \\þaram c The output matrix\n *\/\n template ::value)>\n static void check(const A& a, const B& b, const C& c) {\n Impl::check(a, b, c);\n }\n\n \/*!\n * \\brief Apply the expression\n * \\param a The left hand side\n * \\param b The right hand side\n * \\param c The expression where to store the results\n *\/\n template \n static void apply(A&& a, B&& b, C&& c) {\n static_assert(all_etl_expr::value, \"Convolution only supported for ETL expressions\");\n\n check(a, b, c);\n\n Impl::apply(\n make_temporary(std::forward(a)),\n make_temporary(std::forward(b)),\n std::forward(c));\n }\n\n \/*!\n * \\brief Returns a textual representation of the operation\n * \\return a textual representation of the operation\n *\/\n static constexpr const char* desc() noexcept {\n return Impl::desc();\n }\n\n \/*!\n * \\brief Returns the DDth dimension of the expression\n * \\return the DDth dimension of the expression\n *\/\n template \n static constexpr std::size_t dim() {\n return Impl::template dim();\n }\n\n \/*!\n * \\brief Returns the dth dimension of the expression\n * \\param a The left hand side\n * \\param b The right hand side\n * \\param d The dimension to get\n * \\return the dth dimension of the expression\n *\/\n template \n static std::size_t dim(const A& a, const B& b, std::size_t d) {\n return Impl::dim(d, a, b);\n }\n\n \/*!\n * \\brief Returns the size of the expression\n * \\param a The left hand side\n * \\param b The right hand side\n * \\return the size of the expression\n *\/\n template \n static std::size_t size(const A& a, const B& b) {\n std::size_t acc = 1;\n for (std::size_t i = 0; i < dimensions(); ++i) {\n acc *= this_type::dim(a, b, i);\n }\n return acc;\n }\n\n \/*!\n * \\brief Returns the multiplicative sum of the dimensions at the given indices\n * \\return the multiplicative sum of the dimensions at the given indices\n *\/\n template \n static constexpr std::size_t size_mul(const std::index_sequence& \/*seq*\/) {\n return mul_all()...>::value;\n }\n\n \/*!\n * \\brief Returns the size of the expression\n * \\return the size of the expression\n *\/\n template \n static constexpr std::size_t size() {\n return size_mul(std::make_index_sequence());\n }\n\n \/*!\n * \\brief Returns the storage order of the expression.\n * \\return the storage order of the expression\n *\/\n template \n static constexpr etl::order order() {\n return etl::order::RowMajor;\n }\n\n \/*!\n * \\brief Returns the number of dimensions of the expression\n * \\return the number of dimensions of the expression\n *\/\n static constexpr std::size_t dimensions() {\n return is_multi(TT) ? D + 1 : D;\n }\n};\n\n\/\/1D convolution\n\n\/*!\n * \\brief Expression for 1D valid convolution\n *\/\ntemplate \nusing conv1_valid_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 1D same convolution\n *\/\ntemplate \nusing conv1_same_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 1D full convolution\n *\/\ntemplate \nusing conv1_full_expr = basic_conv_expr;\n\n\/\/2D convolutions\n\n\/*!\n * \\brief Expression for 2D valid convolution\n *\/\ntemplate\nusing conv2_valid_expr = basic_conv_expr>;\n\n\/*!\n * \\brief Expression for 2D valid convolution\n *\/\ntemplate\nusing conv2_valid_flipped_expr = basic_conv_expr>;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_valid_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_valid_filter_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_valid_filter_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_full_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_valid_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_full_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D valid convolution, with multiple kernels\n *\/\ntemplate \nusing conv2_valid_multi_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D valid convolution, with multiple flipped kernels\n *\/\ntemplate \nusing conv2_valid_multi_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D same convolution, with multiple kernels\n *\/\ntemplate \nusing conv2_same_multi_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D same convolution, with multiple flipped kernels\n *\/\ntemplate \nusing conv2_same_multi_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D full convolution, with multiple kernels\n *\/\ntemplate \nusing conv2_full_multi_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D full convolution, with multiple flipped kernels\n *\/\ntemplate \nusing conv2_full_multi_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D same convolution\n *\/\ntemplate \nusing conv2_same_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D same convolution\n *\/\ntemplate \nusing conv2_same_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D full convolution\n *\/\ntemplate \nusing conv2_full_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D full convolution\n *\/\ntemplate \nusing conv2_full_flipped_expr = basic_conv_expr;\n\n\/\/>2D convolutions\n\n\/*!\n * \\brief Expression for >2D valid convolution\n *\/\ntemplate \nusing conv_deep_valid_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for >2D same convolution\n *\/\ntemplate \nusing conv_deep_same_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for >2D full convolution\n *\/\ntemplate \nusing conv_deep_full_expr = basic_conv_expr;\n\n} \/\/end of namespace etl\nCleanup\/\/=======================================================================\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#pragma once\n\n\/\/Get the implementations\n#include \"etl\/impl\/conv.hpp\"\n\nnamespace etl {\n\n\/*!\n * \\brief A basic configurable convolution expr\n * \\tparam T The value type\n * \\tparam D The dimensions of convolution\n * \\tparam TT The convolution type\n * \\tparam Impl The implementation class\n *\/\ntemplate \nstruct basic_conv_expr : impl_expr> {\n static_assert(D > 0, \"0D convolution is not valid\");\n\n using value_type = T; \/\/\/< The type of value of the expression\n using this_type = basic_conv_expr; \/\/\/< The type of this expression\n\n static constexpr const bool is_gpu = is_cufft_enabled || is_cudnn_enabled; \/\/\/< Indicates if the expression runs on GPU\n\n \/*!\n * \\brief The result type for given sub types\n * \\tparam A The left hand side epxpression type\n * \\tparam B The right hand side epxpression type\n *\/\n template \n using result_type = detail::expr_result_t;\n\n \/*!\n * \\brief Validate the convolutiond dimensions\n * \\param a The input matrix\n * \\þaram b The kernel matrix\n * \\þaram c The output matrix\n *\/\n template ::value)>\n static void check(const A& a, const B& b, const C& c) {\n cpp_unused(a);\n cpp_unused(b);\n cpp_unused(c);\n\n Impl::template check();\n }\n\n \/*!\n * \\brief Validate the convolutiond dimensions\n * \\param a The input matrix\n * \\þaram b The kernel matrix\n * \\þaram c The output matrix\n *\/\n template ::value)>\n static void check(const A& a, const B& b, const C& c) {\n Impl::check(a, b, c);\n }\n\n \/*!\n * \\brief Apply the expression\n * \\param a The left hand side\n * \\param b The right hand side\n * \\param c The expression where to store the results\n *\/\n template \n static void apply(A&& a, B&& b, C&& c) {\n static_assert(all_etl_expr::value, \"Convolution only supported for ETL expressions\");\n\n check(a, b, c);\n\n Impl::apply(\n make_temporary(std::forward(a)),\n make_temporary(std::forward(b)),\n std::forward(c));\n }\n\n \/*!\n * \\brief Returns a textual representation of the operation\n * \\return a textual representation of the operation\n *\/\n static constexpr const char* desc() noexcept {\n return Impl::desc();\n }\n\n \/*!\n * \\brief Returns the DDth dimension of the expression\n * \\return the DDth dimension of the expression\n *\/\n template \n static constexpr std::size_t dim() {\n return Impl::template dim();\n }\n\n \/*!\n * \\brief Returns the dth dimension of the expression\n * \\param a The left hand side\n * \\param b The right hand side\n * \\param d The dimension to get\n * \\return the dth dimension of the expression\n *\/\n template \n static std::size_t dim(const A& a, const B& b, std::size_t d) {\n return Impl::dim(d, a, b);\n }\n\n \/*!\n * \\brief Returns the size of the expression\n * \\param a The left hand side\n * \\param b The right hand side\n * \\return the size of the expression\n *\/\n template \n static std::size_t size(const A& a, const B& b) {\n std::size_t acc = 1;\n for (std::size_t i = 0; i < dimensions(); ++i) {\n acc *= this_type::dim(a, b, i);\n }\n return acc;\n }\n\n \/*!\n * \\brief Returns the multiplicative sum of the dimensions at the given indices\n * \\return the multiplicative sum of the dimensions at the given indices\n *\/\n template \n static constexpr std::size_t size_mul(const std::index_sequence& \/*seq*\/) {\n return mul_all()...>::value;\n }\n\n \/*!\n * \\brief Returns the size of the expression\n * \\return the size of the expression\n *\/\n template \n static constexpr std::size_t size() {\n return size_mul(std::make_index_sequence());\n }\n\n \/*!\n * \\brief Returns the storage order of the expression.\n * \\return the storage order of the expression\n *\/\n template \n static constexpr etl::order order() {\n return etl::order::RowMajor;\n }\n\n \/*!\n * \\brief Returns the number of dimensions of the expression\n * \\return the number of dimensions of the expression\n *\/\n static constexpr std::size_t dimensions() {\n return D;\n }\n};\n\n\/\/1D convolution\n\n\/*!\n * \\brief Expression for 1D valid convolution\n *\/\ntemplate \nusing conv1_valid_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 1D same convolution\n *\/\ntemplate \nusing conv1_same_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 1D full convolution\n *\/\ntemplate \nusing conv1_full_expr = basic_conv_expr;\n\n\/\/2D convolutions\n\n\/*!\n * \\brief Expression for 2D valid convolution\n *\/\ntemplate\nusing conv2_valid_expr = basic_conv_expr>;\n\n\/*!\n * \\brief Expression for 2D valid convolution\n *\/\ntemplate\nusing conv2_valid_flipped_expr = basic_conv_expr>;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_valid_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_valid_filter_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_valid_filter_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_full_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_valid_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 4D valid convolution\n *\/\ntemplate \nusing conv4_full_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D valid convolution, with multiple kernels\n *\/\ntemplate \nusing conv2_valid_multi_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D valid convolution, with multiple flipped kernels\n *\/\ntemplate \nusing conv2_valid_multi_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D same convolution, with multiple kernels\n *\/\ntemplate \nusing conv2_same_multi_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D same convolution, with multiple flipped kernels\n *\/\ntemplate \nusing conv2_same_multi_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D full convolution, with multiple kernels\n *\/\ntemplate \nusing conv2_full_multi_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D full convolution, with multiple flipped kernels\n *\/\ntemplate \nusing conv2_full_multi_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D same convolution\n *\/\ntemplate \nusing conv2_same_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D same convolution\n *\/\ntemplate \nusing conv2_same_flipped_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D full convolution\n *\/\ntemplate \nusing conv2_full_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for 2D full convolution\n *\/\ntemplate \nusing conv2_full_flipped_expr = basic_conv_expr;\n\n\/\/>2D convolutions\n\n\/*!\n * \\brief Expression for >2D valid convolution\n *\/\ntemplate \nusing conv_deep_valid_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for >2D same convolution\n *\/\ntemplate \nusing conv_deep_same_expr = basic_conv_expr;\n\n\/*!\n * \\brief Expression for >2D full convolution\n *\/\ntemplate \nusing conv_deep_full_expr = basic_conv_expr;\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\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\n* conditions 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 copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* 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; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include \"AppSupport.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nstd::string AppSupport::inferReaderDriver(const std::string& filename, pdal::Options& options)\n{\n std::string ext = boost::filesystem::extension(filename);\n\n pdal::Option& fn = options.getOptionByRef(\"filename\");\n fn.setValue(filename);\n\n \/\/ maybe this should live in StageFactory?\n std::map drivers;\n drivers[\"las\"] = \"drivers.las.reader\";\n drivers[\"laz\"] = \"drivers.las.reader\";\n drivers[\"bin\"] = \"drivers.terrasolid.reader\";\n drivers[\"qi\"] = \"drivers.qfit.reader\";\n drivers[\"xml\"] = \"drivers.pipeline.reader\";\n drivers[\"nitf\"] = \"drivers.nitf.reader\";\n drivers[\"ntf\"] = \"drivers.nitf.reader\";\n \n if (boost::algorithm::iequals(filename, \"STDIN\"))\n {\n return drivers[\"xml\"];\n }\n \n if (ext == \"\") return \"\";\n ext = ext.substr(1, ext.length()-1);\n if (ext == \"\") return \"\";\n\n boost::to_lower(ext);\n std::string driver = drivers[ext];\n return driver; \/\/ will be \"\" if not found\n}\n\n\nstd::string AppSupport::inferWriterDriver(const std::string& filename, pdal::Options& options)\n{\n std::string ext = boost::filesystem::extension(filename);\n\n\n boost::to_lower(ext);\n \n if (boost::algorithm::iequals(ext,\".laz\"))\n {\n options.add(\"compression\", true);\n }\n\n options.add(\"filename\", filename);\n\n \/\/ maybe this should live in StageFactory?\n std::map drivers;\n drivers[\"las\"] = \"drivers.las.writer\";\n drivers[\"laz\"] = \"drivers.las.writer\";\n drivers[\"xyz\"] = \"drivers.text.writer\";\n drivers[\"txt\"] = \"drivers.text.writer\";\n drivers[\"pcd\"] = \"drivers.pcd.writer\";\n\n if (boost::algorithm::iequals(filename, \"STDOUT\"))\n {\n return drivers[\"txt\"];\n }\n\n if (ext == \"\") return drivers[\"txt\"];\n ext = ext.substr(1, ext.length()-1);\n if (ext == \"\") return drivers[\"txt\"];\n\n boost::to_lower(ext);\n std::string driver = drivers[ext];\n return driver; \/\/ will be \"\" if not found\n}\n\n\npdal::Stage* AppSupport::makeReader(pdal::Options& options)\n{\n const std::string inputFile = options.getValueOrThrow(\"filename\");\n\n if (!pdal::FileUtils::fileExists(inputFile))\n {\n throw app_runtime_error(\"file not found: \" + inputFile);\n }\n\n pdal::StageFactory factory;\n std::string driver = factory.inferReaderDriver(inputFile, options);\n if (driver == \"\")\n {\n throw app_runtime_error(\"Cannot determine input file type of \" + inputFile);\n }\n\n pdal::Stage* stage = factory.createReader(driver, options);\n if (!stage)\n {\n throw app_runtime_error(\"reader creation failed\");\n }\n\n return stage;\n}\n\n\npdal::Writer* AppSupport::makeWriter(pdal::Options& options, pdal::Stage& stage)\n{\n const std::string outputFile = options.getValueOrThrow(\"filename\");\n\n pdal::StageFactory factory;\n std::string driver = factory.inferWriterDriver(outputFile, options);\n if (driver == \"\")\n {\n throw app_runtime_error(\"Cannot determine output file type of \" + outputFile);\n }\n \n pdal::Writer* writer = factory.createWriter(driver, stage, options);\n if (!writer)\n {\n throw app_runtime_error(\"writer creation failed\");\n }\n\n return writer;\n}\n\n\nPercentageCallback::PercentageCallback(double major, double minor)\n : m_lastMajorPerc(-1 * major)\n , m_lastMinorPerc(-1 * minor)\n , m_done(false)\n{\n return;\n}\n\n\nvoid PercentageCallback::callback()\n{\n if (m_done) return;\n\n double currPerc = getPercentComplete();\n \n if (pdal::Utils::compare_distance(currPerc, 100.0))\n {\n std::cerr << \"100\" << std::endl;\n m_done = true;\n }\n else if (currPerc >= m_lastMajorPerc + 10.0)\n {\n std::cerr << (int)currPerc << std::flush;\n m_lastMajorPerc = currPerc;\n m_lastMinorPerc = currPerc;\n }\n else if (currPerc >= m_lastMinorPerc + 2.0)\n {\n std::cerr << '.' << std::flush;\n m_lastMinorPerc = currPerc;\n }\n\n return;\n}\n\nShellScriptCallback::ShellScriptCallback(std::vector const& command)\n{\n double major(10.0);\n double minor(2.0);\n \n if (!command.size())\n {\n m_command = \"\"; \n }\n else\n {\n m_command = command[0];\n\n if (command.size() == 3)\n {\n major = boost::lexical_cast(command[1]);\n minor = boost::lexical_cast(command[2]);\n } \n else if (command.size() == 2)\n {\n major = boost::lexical_cast(command[1]);\n }\n }\n\n PercentageCallback(major, minor);\n\n return;\n}\n\n\nvoid ShellScriptCallback::callback()\n{\n if (m_done) return;\n\n double currPerc = getPercentComplete();\n \n if (pdal::Utils::compare_distance(currPerc, 100.0))\n {\n m_done = true;\n }\n else if (currPerc >= m_lastMajorPerc + 10.0)\n {\n std::string output;\n int stat = pdal::Utils::run_shell_command(m_command, output);\n }\n else if (currPerc >= m_lastMinorPerc + 2.0)\n {\n m_lastMinorPerc = currPerc;\n }\n\n return;\n}\n\nHeartbeatCallback::HeartbeatCallback()\n{\n return;\n}\n\n\nvoid HeartbeatCallback::callback()\n{\n std::cerr << '.';\n\n return;\n}\nrename variables\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\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\n* conditions 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 copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* 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; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include \"AppSupport.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nstd::string AppSupport::inferReaderDriver(const std::string& filename, pdal::Options& options)\n{\n std::string ext = boost::filesystem::extension(filename);\n\n pdal::Option& fn = options.getOptionByRef(\"filename\");\n fn.setValue(filename);\n\n \/\/ maybe this should live in StageFactory?\n std::map drivers;\n drivers[\"las\"] = \"drivers.las.reader\";\n drivers[\"laz\"] = \"drivers.las.reader\";\n drivers[\"bin\"] = \"drivers.terrasolid.reader\";\n drivers[\"qi\"] = \"drivers.qfit.reader\";\n drivers[\"xml\"] = \"drivers.pipeline.reader\";\n drivers[\"nitf\"] = \"drivers.nitf.reader\";\n drivers[\"ntf\"] = \"drivers.nitf.reader\";\n \n if (boost::algorithm::iequals(filename, \"STDIN\"))\n {\n return drivers[\"xml\"];\n }\n \n if (ext == \"\") return \"\";\n ext = ext.substr(1, ext.length()-1);\n if (ext == \"\") return \"\";\n\n boost::to_lower(ext);\n std::string driver = drivers[ext];\n return driver; \/\/ will be \"\" if not found\n}\n\n\nstd::string AppSupport::inferWriterDriver(const std::string& filename, pdal::Options& options)\n{\n std::string ext = boost::filesystem::extension(filename);\n\n\n boost::to_lower(ext);\n \n if (boost::algorithm::iequals(ext,\".laz\"))\n {\n options.add(\"compression\", true);\n }\n\n options.add(\"filename\", filename);\n\n \/\/ maybe this should live in StageFactory?\n std::map drivers;\n drivers[\"las\"] = \"drivers.las.writer\";\n drivers[\"laz\"] = \"drivers.las.writer\";\n drivers[\"xyz\"] = \"drivers.text.writer\";\n drivers[\"txt\"] = \"drivers.text.writer\";\n drivers[\"pcd\"] = \"drivers.pcd.writer\";\n\n if (boost::algorithm::iequals(filename, \"STDOUT\"))\n {\n return drivers[\"txt\"];\n }\n\n if (ext == \"\") return drivers[\"txt\"];\n ext = ext.substr(1, ext.length()-1);\n if (ext == \"\") return drivers[\"txt\"];\n\n boost::to_lower(ext);\n std::string driver = drivers[ext];\n return driver; \/\/ will be \"\" if not found\n}\n\n\npdal::Stage* AppSupport::makeReader(pdal::Options& options)\n{\n const std::string inputFile = options.getValueOrThrow(\"filename\");\n\n if (!pdal::FileUtils::fileExists(inputFile))\n {\n throw app_runtime_error(\"file not found: \" + inputFile);\n }\n\n pdal::StageFactory factory;\n std::string driver = factory.inferReaderDriver(inputFile, options);\n if (driver == \"\")\n {\n throw app_runtime_error(\"Cannot determine input file type of \" + inputFile);\n }\n\n pdal::Stage* stage = factory.createReader(driver, options);\n if (!stage)\n {\n throw app_runtime_error(\"reader creation failed\");\n }\n\n return stage;\n}\n\n\npdal::Writer* AppSupport::makeWriter(pdal::Options& options, pdal::Stage& stage)\n{\n const std::string outputFile = options.getValueOrThrow(\"filename\");\n\n pdal::StageFactory factory;\n std::string driver = factory.inferWriterDriver(outputFile, options);\n if (driver == \"\")\n {\n throw app_runtime_error(\"Cannot determine output file type of \" + outputFile);\n }\n \n pdal::Writer* writer = factory.createWriter(driver, stage, options);\n if (!writer)\n {\n throw app_runtime_error(\"writer creation failed\");\n }\n\n return writer;\n}\n\n\nPercentageCallback::PercentageCallback(double major, double minor)\n : m_lastMajorPerc(-1 * major)\n , m_lastMinorPerc(-1 * minor)\n , m_done(false)\n{\n return;\n}\n\n\nvoid PercentageCallback::callback()\n{\n if (m_done) return;\n\n double currPerc = getPercentComplete();\n \n if (pdal::Utils::compare_distance(currPerc, 100.0))\n {\n std::cerr << \"100\" << std::endl;\n m_done = true;\n }\n else if (currPerc >= m_lastMajorPerc + 10.0)\n {\n std::cerr << (int)currPerc << std::flush;\n m_lastMajorPerc = currPerc;\n m_lastMinorPerc = currPerc;\n }\n else if (currPerc >= m_lastMinorPerc + 2.0)\n {\n std::cerr << '.' << std::flush;\n m_lastMinorPerc = currPerc;\n }\n\n return;\n}\n\nShellScriptCallback::ShellScriptCallback(std::vector const& command)\n{\n double major_tick(10.0);\n double minor_tick(2.0);\n \n if (!command.size())\n {\n m_command = \"\"; \n }\n else\n {\n m_command = command[0];\n\n if (command.size() == 3)\n {\n major_tick = boost::lexical_cast(command[1]);\n minor_tick = boost::lexical_cast(command[2]);\n } \n else if (command.size() == 2)\n {\n major_tick = boost::lexical_cast(command[1]);\n }\n }\n\n PercentageCallback(major_tick, minor_tick);\n\n return;\n}\n\n\nvoid ShellScriptCallback::callback()\n{\n if (m_done) return;\n\n double currPerc = getPercentComplete();\n \n if (pdal::Utils::compare_distance(currPerc, 100.0))\n {\n m_done = true;\n }\n else if (currPerc >= m_lastMajorPerc + 10.0)\n {\n std::string output;\n int stat = pdal::Utils::run_shell_command(m_command, output);\n }\n else if (currPerc >= m_lastMinorPerc + 2.0)\n {\n m_lastMinorPerc = currPerc;\n }\n\n return;\n}\n\nHeartbeatCallback::HeartbeatCallback()\n{\n return;\n}\n\n\nvoid HeartbeatCallback::callback()\n{\n std::cerr << '.';\n\n return;\n}\n<|endoftext|>"} {"text":"\/*======================================================================\r\n----------------------------------------------------------------------*\/\r\n\/**\r\n * @file\t\tiutest_port_c.inl\r\n * @brief\t\tiris unit portable t@C\r\n *\r\n * @author\t\tt.sirayanagi\r\n * @par\t\t\tcopyright\r\n * Copyright (C) 2012-2014, Takazumi Shirayanagi\\n\r\n * This software is released under the new BSD License,\r\n * see LICENSE\r\n*\/\r\n\/*----------------------------------------------------------------------\r\n======================================================================*\/\r\n#ifndef INCG_IRIS_IUTEST_PORT_C_INL_6D5DBD9D_C830_4415_957D_D38D69AEE35B_\r\n#define INCG_IRIS_IUTEST_PORT_C_INL_6D5DBD9D_C830_4415_957D_D38D69AEE35B_\r\n\r\n\/* include ===========================================================*\/\r\n#include \"..\/internal\/iutest_port_c.h\"\r\n\r\n\/* function ==========================================================*\/\r\n\r\nIUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN()\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ const char * iuTestOS_GetEnv(const char* name)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS_MOBILE) || defined(IUTEST_C_NO_GETENV)\r\n\tIUTEST_UNUSED_VAR(name);\r\n\treturn NULL;\r\n#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)\r\n\tconst char* env = getenv(name);\r\n\treturn (env != NULL && env[0] != '\\0') ? env : NULL;\r\n#else\r\n\treturn getenv(name);\r\n#endif\r\n}\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ int iuTestOS_PutEnv(const char* expr)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS_MOBILE) || defined(IUTEST_C_NO_PUTENV)\r\n\tIUTEST_UNUSED_VAR(expr);\r\n\treturn -1;\r\n#else\r\n\treturn putenv((char*)expr);\r\n#endif\r\n}\r\n\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ iuBOOL iuTestOS_GetEnvironmentVariable(const char* name, char* value, size_t size)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE)\r\n\tif( !GetEnvironmentVariableA(name, value, size) ) return FALSE;\r\n\treturn TRUE;\r\n#else\r\n\tIUTEST_UNUSED_VAR(size);\r\n\tconst char* env = iuTestOS_GetEnv(name);\r\n\tif( env == NULL ) return FALSE;\r\n\tiu_strcpy(value, env);\r\n\treturn TRUE;\r\n#endif\r\n}\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ iuBOOL iuTestOS_GetEnvironmentInt(const char* name, int* value)\r\n{\r\n\tchar buf[128];\r\n\tiu_memset(buf, 0, sizeof(buf));\r\n\tif( value == NULL ) return FALSE;\r\n\tif( iuTestOS_GetEnvironmentVariable(name, buf, sizeof(buf)) )\r\n\t{\r\n\t\t*value = iuString_ToInt(buf);\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ void iuAbort(void)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS_MOBILE)\r\n\tDebugBreak();\r\n\tTerminateProcess(GetCurrentProcess(), 1);\r\n#elif IUTEST_C_HAS_LIBC\r\n\tabort();\r\n#else\r\n\tint* p = NULL;\r\n\t*p = 0;\r\n#endif\r\n}\r\n\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ void iuExit(int exit_code)\r\n{\r\n#if IUTEST_C_HAS_LIBC\r\n\texit(exit_code);\r\n#else\r\n\tIUTEST_UNUSED_VAR(exit_code);\r\n\tint* p = NULL;\r\n\t*p = 0;\r\n#endif\r\n}\r\n\r\nIUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END()\r\n\r\n#if defined(IUTEST_OS_WINDOWS)\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ char* iuTestOS_AllocHResultString(HRESULT hr)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS_MOBILE)\r\n\treturn NULL;\r\n#else\r\n\tLPSTR buf = NULL;\r\n\tFormatMessageA(\r\n\t\tFORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\r\n\t\tNULL,\r\n\t\thr,\r\n\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/* ftHg [U[ *\/\r\n\t\t(LPSTR)&buf,\r\n\t\t0,\r\n\t\tNULL );\r\n\treturn buf;\r\n#endif\r\n}\r\n\r\nstatic IUTEST_ATTRIBUTE_UNUSED_ void iuTestOS_FreeHResultString(char* ptr)\r\n{\r\n\tLocalFree(ptr);\r\n}\r\n\r\n#endif\r\n\r\n#endif\r\nupdate r600\/*======================================================================\r\n----------------------------------------------------------------------*\/\r\n\/**\r\n * @file\t\tiutest_port_c.inl\r\n * @brief\t\tiris unit portable t@C\r\n *\r\n * @author\t\tt.sirayanagi\r\n * @par\t\t\tcopyright\r\n * Copyright (C) 2012-2014, Takazumi Shirayanagi\\n\r\n * This software is released under the new BSD License,\r\n * see LICENSE\r\n*\/\r\n\/*----------------------------------------------------------------------\r\n======================================================================*\/\r\n#ifndef INCG_IRIS_IUTEST_PORT_C_INL_6D5DBD9D_C830_4415_957D_D38D69AEE35B_\r\n#define INCG_IRIS_IUTEST_PORT_C_INL_6D5DBD9D_C830_4415_957D_D38D69AEE35B_\r\n\r\n\/* include ===========================================================*\/\r\n#include \"..\/internal\/iutest_port_c.h\"\r\n\r\n\/* function ==========================================================*\/\r\n\r\nIUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN()\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ const char * iuTestOS_GetEnv(const char* name)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS_MOBILE) || defined(IUTEST_C_NO_GETENV)\r\n\tIUTEST_UNUSED_VAR(name);\r\n\treturn NULL;\r\n#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)\r\n\tconst char* env = getenv(name);\r\n\treturn (env != NULL && env[0] != '\\0') ? env : NULL;\r\n#else\r\n\treturn getenv(name);\r\n#endif\r\n}\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ int iuTestOS_PutEnv(const char* expr)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS_MOBILE) || defined(IUTEST_C_NO_PUTENV)\r\n\tIUTEST_UNUSED_VAR(expr);\r\n\treturn -1;\r\n#else\r\n\treturn putenv((char*)expr);\r\n#endif\r\n}\r\n\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ iuBOOL iuTestOS_GetEnvironmentVariable(const char* name, char* value, size_t size)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE)\r\n\tif( !GetEnvironmentVariableA(name, value, size) ) return FALSE;\r\n\treturn TRUE;\r\n#else\r\n\tIUTEST_UNUSED_VAR(size);\r\n\tconst char* env = iuTestOS_GetEnv(name);\r\n\tif( env == NULL ) return FALSE;\r\n\tiu_strcpy(value, env);\r\n\treturn TRUE;\r\n#endif\r\n}\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ iuBOOL iuTestOS_GetEnvironmentInt(const char* name, int* value)\r\n{\r\n\tchar buf[128];\r\n\tiu_memset(buf, 0, sizeof(buf));\r\n\tif( value == NULL ) return FALSE;\r\n\tif( iuTestOS_GetEnvironmentVariable(name, buf, sizeof(buf)) )\r\n\t{\r\n\t\t*value = iuString_ToInt(buf);\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ void iuAbort(void)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS_MOBILE)\r\n\tDebugBreak();\r\n\tTerminateProcess(GetCurrentProcess(), 1);\r\n#elif IUTEST_C_HAS_LIBC\r\n\tabort();\r\n#else\r\n\tint* p = NULL;\r\n\t*p = 0;\r\n#endif\r\n}\r\n\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ void iuExit(int exit_code)\r\n{\r\n#if IUTEST_C_HAS_LIBC\r\n\texit(exit_code);\r\n#else\r\n\tIUTEST_UNUSED_VAR(exit_code);\r\n\tint* p = NULL;\r\n\t*p = 0;\r\n#endif\r\n}\r\n\r\nIUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END()\r\n\r\n#if defined(IUTEST_OS_WINDOWS)\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ char* iuTestOS_AllocHResultString(HRESULT hr)\r\n{\r\n#if defined(IUTEST_OS_WINDOWS_MOBILE)\r\n\treturn NULL;\r\n#else\r\n\tLPSTR buf = NULL;\r\n\tFormatMessageA(\r\n\t\tFORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\r\n\t\tNULL,\r\n\t\thr,\r\n\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/* ftHg [U[ *\/\r\n\t\t(LPSTR)&buf,\r\n\t\t0,\r\n\t\tNULL );\r\n\treturn buf;\r\n#endif\r\n}\r\n\r\nIUTEST_C_INL_INLINE IUTEST_ATTRIBUTE_UNUSED_ void iuTestOS_FreeHResultString(char* ptr)\r\n{\r\n\tLocalFree(ptr);\r\n}\r\n\r\n#endif\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"Fix some composite matching bugs<|endoftext|>"} {"text":"\/** \\brief Utility for deleting partial or entire MARC records based on an input list.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2015 Universitätsbiblothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (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. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MarcUtil.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"util.h\"\n\n\nstatic void Usage() __attribute__((noreturn));\n\n\nstatic void Usage() {\n std::cerr << \"Usage: \" << progname << \" deletion_list input_marc output_marc\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid ExtractDeletionIds(FILE * const deletion_list, std::unordered_set * const title_deletion_ids,\n\t\t\tstd::unordered_set * const local_deletion_ids)\n{\n char line[100];\n while (std::fgets(line, sizeof(line), deletion_list) != NULL) {\n\tif (std::strlen(line) < 13)\n\t Error(\"short line in deletion list file: \\\"\" + std::string(line) + \"\\\"!\");\n\tif (line[11] == 'A')\n\t title_deletion_ids->insert(line + 12);\n\telse if (line[11] == '9')\n\t local_deletion_ids->insert(line + 12);\n }\n\n std::fclose(deletion_list);\n}\n\n\nint MatchLocalID(const std::unordered_set &local_ids, const std::vector &dir_entries,\n\t\t const std::vector &field_data)\n{\n for (size_t i(0); i < dir_entries.size(); ++i) {\n\tif (dir_entries[i].getTag() != \"LOK\")\n\t continue;\n\n\tconst Subfields subfields(field_data[i]);\n\tif (not subfields.hasSubfield('0'))\n\t continue;\n\n\tconst std::string subfield_contents(subfields.getFirstSubfieldValue('0'));\n\tif (not StringUtil::StartsWith(subfield_contents, \"001 \")\n\t or local_ids.find(subfield_contents.substr(4)) == local_ids.end())\n\t continue;\n\n\treturn i;\n }\n\n return -1;\n}\n\n\nclass MatchTag {\n const std::string tag_to_match_;\npublic:\n explicit MatchTag(const std::string &tag_to_match): tag_to_match_(tag_to_match) { }\n bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; }\n};\n\n\nvoid ProcessRecords(const std::unordered_set &title_deletion_ids,\n\t\t const std::unordered_set &local_deletion_ids, FILE * const input,\n\t\t FILE * const output)\n{\n Leader *raw_leader;\n std::vector dir_entries;\n std::vector field_data;\n std::string err_msg;\n unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0);\n\n while (MarcUtil::ReadNextRecord(input, &raw_leader, &dir_entries, &field_data, &err_msg)) {\n\t++total_record_count;\n\n\tif (dir_entries[0].getTag() != \"001\")\n\t Error(\"First field is not \\\"001\\\"!\");\n\n\tssize_t start_local_match;\n\tif (title_deletion_ids.find(field_data[0]) != title_deletion_ids.end()) {\n\t MarcUtil::ComposeAndWriteRecord(output, dir_entries, field_data, raw_leader);\n\t\n\t bool modified(false);\n\t while ((start_local_match = MatchLocalID(local_deletion_ids, dir_entries, field_data)) != -1) {\n\t\t\/\/ We now expect a field \"000\" before the current \"001\" field:\n\t\t--start_local_match;\n\t\tif (start_local_match <= 0)\n\t\t Error(\"weird data structure (1)!\");\n\t\tconst Subfields subfields(field_data[start_local_match]);\n\t\tif (not subfields.hasSubfield('0')\n\t\t or StringUtil::StartsWith(subfields.getFirstSubfieldValue('0'), \"000 \"))\n\t\t Error(\"missing or empty local field \\\"000\\\"!\");\n\n\t\t\/\/ Now we need to find the index one past the end of the local record. This would\n\t\t\/\/ be either the \"000\" field of the next local record or one past the end of the overall\n\t\t\/\/ MARC record.\n\t\tbool found_next_000(false);\n\t\tsize_t end_local_match(start_local_match + 2);\n\t\twhile (end_local_match < field_data.size()) {\n\t\t const Subfields subfields(field_data[end_local_match]);\n\t\t if (not subfields.hasSubfield('0'))\n\t\t\tError(\"weird data (2)!\");\n\t\t if (StringUtil::StartsWith(subfields.getFirstSubfieldValue('0'), \"000 \")) {\n\t\t\tfound_next_000 = true;\n\t\t\tbreak;\n\t\t }\n\n\t\t ++end_local_match;\n\t\t}\n\t\tif (not found_next_000)\n\t\t ++end_local_match;\n\n\t\t\/\/ Throw away the matched local data set:\n\t\tdir_entries.erase(dir_entries.begin() + start_local_match, dir_entries.begin() + end_local_match);\n\n\t\tmodified = true;\n\t }\n\n\t if (not modified)\n\t\tMarcUtil::ComposeAndWriteRecord(output, dir_entries, field_data, raw_leader);\n\t else {\n\t\t\/\/ Only keep records that still have at least one \"LOK\" tag:\n\t\tif (std::find_if(dir_entries.cbegin(), dir_entries.cend(), MatchTag(\"LOK\")) == dir_entries.cend())\n\t\t ++deleted_record_count;\n\t\telse {\n\t\t ++modified_record_count;\n\t\t MarcUtil::ComposeAndWriteRecord(output, dir_entries, field_data, raw_leader);\n\t\t}\n\t }\n\t} else {\n\t ++deleted_record_count;\n\t std::cout << \"Deleted record with ID \" << field_data[0] << '\\n';\n\t}\n }\n\n if (not err_msg.empty())\n\tError(err_msg);\n std::cerr << \"Read \" << total_record_count << \" records.\\n\";\n std::cerr << \"Deleted \" << deleted_record_count << \" records.\\n\";\n std::cerr << \"Modified \" << modified_record_count << \" records.\\n\";\n\n std::fclose(input);\n std::fclose(output);\n}\n\n\nint main(int argc, char *argv[]) {\n progname = argv[0];\n\n if (argc != 4)\n\tUsage();\n\n const std::string deletion_list_filename(argv[1]);\n FILE *deletion_list = std::fopen(deletion_list_filename.c_str(), \"rb\");\n if (deletion_list == NULL)\n\tError(\"can't open \\\"\" + deletion_list_filename + \"\\\" for reading!\");\n\n std::unordered_set title_deletion_ids, local_deletion_ids;\n ExtractDeletionIds(deletion_list, &title_deletion_ids, &local_deletion_ids);\n\n const std::string marc_input_filename(argv[2]);\n FILE *marc_input = std::fopen(marc_input_filename.c_str(), \"rb\");\n if (marc_input == NULL)\n\tError(\"can't open \\\"\" + marc_input_filename + \"\\\" for reading!\");\n\n const std::string marc_output_filename(argv[3]);\n FILE *marc_output = std::fopen(marc_output_filename.c_str(), \"wb\");\n if (marc_output == NULL)\n\tError(\"can't open \\\"\" + marc_output_filename + \"\\\" for writing!\");\n\n try {\n\tProcessRecords(title_deletion_ids, local_deletion_ids, marc_input, marc_output);\n } catch (const std::exception &e) {\n\tError(\"Caught exception: \" + std::string(e.what()));\n }\n}\nFixed a variety of bugs after I was able to test this with actual data.\/** \\brief Utility for deleting partial or entire MARC records based on an input list.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2015 Universitätsbiblothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (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. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MarcUtil.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"util.h\"\n\n\nstatic void Usage() __attribute__((noreturn));\n\n\nstatic void Usage() {\n std::cerr << \"Usage: \" << progname << \" deletion_list input_marc output_marc\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid ExtractDeletionIds(FILE * const deletion_list, std::unordered_set * const title_deletion_ids,\n\t\t\tstd::unordered_set * const local_deletion_ids)\n{\n unsigned line_no(0);\n char line[100];\n while (std::fgets(line, sizeof(line), deletion_list) != NULL) {\n\t++line_no;\n\tsize_t line_length(std::strlen(line));\n\tif (line_length < 13)\n\t Error(\"short line in deletion list file: \\\"\" + std::string(line) + \"\\\"!\");\n\tif (line[line_length - 1] == '\\n') {\n\t line[line_length - 1] = '\\0';\n\t --line_length;\n\t}\n\tif (line[11] == 'A')\n\t title_deletion_ids->insert(line + 12); \/\/ extract PPN\n\telse if (line[11] == '9') {\n\t if (line_length != 25)\n\t\tError(\"unexpected line length for local entry on line \" + std::to_string(line_no) + \"!\");\n\t local_deletion_ids->insert(std::string(line).substr(12, 9)); \/\/ extract ELN\n\t}\n }\n\n std::fclose(deletion_list);\n}\n\n\nint MatchLocalID(const std::unordered_set &local_ids, const std::vector &dir_entries,\n\t\t const std::vector &field_data)\n{\n for (size_t i(0); i < dir_entries.size(); ++i) {\n\tif (dir_entries[i].getTag() != \"LOK\")\n\t continue;\n\n\tconst Subfields subfields(field_data[i]);\n\tif (not subfields.hasSubfield('0'))\n\t continue;\n\n\tconst std::string subfield_contents(subfields.getFirstSubfieldValue('0'));\n\tif (not StringUtil::StartsWith(subfield_contents, \"001 \")\n\t or local_ids.find(subfield_contents.substr(4)) == local_ids.end())\n\t continue;\n\n\treturn i;\n }\n\n return -1;\n}\n\n\nclass MatchTag {\n const std::string tag_to_match_;\npublic:\n explicit MatchTag(const std::string &tag_to_match): tag_to_match_(tag_to_match) { }\n bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; }\n};\n\n\nvoid ProcessRecords(const std::unordered_set &title_deletion_ids,\n\t\t const std::unordered_set &local_deletion_ids, FILE * const input,\n\t\t FILE * const output)\n{\n Leader *raw_leader;\n std::vector dir_entries;\n std::vector field_data;\n std::string err_msg;\n unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0);\n\n while (MarcUtil::ReadNextRecord(input, &raw_leader, &dir_entries, &field_data, &err_msg)) {\n\t++total_record_count;\n\n\tif (dir_entries[0].getTag() != \"001\")\n\t Error(\"First field is not \\\"001\\\"!\");\n\n\tssize_t start_local_match;\n\tif (title_deletion_ids.find(field_data[0]) != title_deletion_ids.end()) {\n\t ++deleted_record_count;\n\t std::cout << \"Deleted record with ID \" << field_data[0] << '\\n';\n\t} else { \/\/ Look for local data sets that may need to be deleted.\n\t MarcUtil::ComposeAndWriteRecord(output, dir_entries, field_data, raw_leader);\n\t\n\t bool modified(false);\n\t while ((start_local_match = MatchLocalID(local_deletion_ids, dir_entries, field_data)) != -1) {\n\t\t\/\/ We now expect a field \"000\" before the current \"001\" field:\n\t\t--start_local_match;\n\t\tif (start_local_match <= 0)\n\t\t Error(\"weird data structure (1)!\");\n\t\tconst Subfields subfields(field_data[start_local_match]);\n\t\tif (not subfields.hasSubfield('0')\n\t\t or not StringUtil::StartsWith(subfields.getFirstSubfieldValue('0'), \"000 \"))\n\t\t Error(\"missing or empty local field \\\"000\\\"! (EPN: \"\n\t\t\t + field_data[start_local_match + 1].substr(8) + \", PPN: \" + field_data[0] + \")\");\n\n\t\t\/\/ Now we need to find the index one past the end of the local record. This would\n\t\t\/\/ be either the \"000\" field of the next local record or one past the end of the overall\n\t\t\/\/ MARC record.\n\t\tbool found_next_000(false);\n\t\tsize_t end_local_match(start_local_match + 2);\n\t\twhile (end_local_match < field_data.size()) {\n\t\t const Subfields subfields(field_data[end_local_match]);\n\t\t if (not subfields.hasSubfield('0'))\n\t\t\tError(\"weird data (2)!\");\n\t\t if (StringUtil::StartsWith(subfields.getFirstSubfieldValue('0'), \"000 \")) {\n\t\t\tfound_next_000 = true;\n\t\t\tbreak;\n\t\t }\n\n\t\t ++end_local_match;\n\t\t}\n\t\tif (not found_next_000)\n\t\t ++end_local_match;\n\n\t\t\/\/ Throw away the matched local data set:\n\t\tdir_entries.erase(dir_entries.begin() + start_local_match, dir_entries.begin() + end_local_match);\n\n\t\tmodified = true;\n\t }\n\n\t if (not modified)\n\t\tMarcUtil::ComposeAndWriteRecord(output, dir_entries, field_data, raw_leader);\n\t else {\n\t\t\/\/ Only keep records that still have at least one \"LOK\" tag:\n\t\tif (std::find_if(dir_entries.cbegin(), dir_entries.cend(), MatchTag(\"LOK\")) == dir_entries.cend())\n\t\t ++deleted_record_count;\n\t\telse {\n\t\t ++modified_record_count;\n\t\t MarcUtil::ComposeAndWriteRecord(output, dir_entries, field_data, raw_leader);\n\t\t}\n\t }\n\t}\n }\n\n if (not err_msg.empty())\n\tError(err_msg);\n std::cerr << \"Read \" << total_record_count << \" records.\\n\";\n std::cerr << \"Deleted \" << deleted_record_count << \" records.\\n\";\n std::cerr << \"Modified \" << modified_record_count << \" records.\\n\";\n\n std::fclose(input);\n std::fclose(output);\n}\n\n\nint main(int argc, char *argv[]) {\n progname = argv[0];\n\n if (argc != 4)\n\tUsage();\n\n const std::string deletion_list_filename(argv[1]);\n FILE *deletion_list = std::fopen(deletion_list_filename.c_str(), \"rb\");\n if (deletion_list == NULL)\n\tError(\"can't open \\\"\" + deletion_list_filename + \"\\\" for reading!\");\n\n std::unordered_set title_deletion_ids, local_deletion_ids;\n ExtractDeletionIds(deletion_list, &title_deletion_ids, &local_deletion_ids);\n\n const std::string marc_input_filename(argv[2]);\n FILE *marc_input = std::fopen(marc_input_filename.c_str(), \"rb\");\n if (marc_input == NULL)\n\tError(\"can't open \\\"\" + marc_input_filename + \"\\\" for reading!\");\n\n const std::string marc_output_filename(argv[3]);\n FILE *marc_output = std::fopen(marc_output_filename.c_str(), \"wb\");\n if (marc_output == NULL)\n\tError(\"can't open \\\"\" + marc_output_filename + \"\\\" for writing!\");\n\n try {\n\tProcessRecords(title_deletion_ids, local_deletion_ids, marc_input, marc_output);\n } catch (const std::exception &e) {\n\tError(\"Caught exception: \" + std::string(e.what()));\n }\n}\n<|endoftext|>"} {"text":"\/* Copyright 2013 Yahoo! Inc. *\/\n\/* See LICENSE in the root of the distribution for licensing details. *\/\n\n#ifndef DONT_MULTI_INCLUDE_MDBM_UTIL_HH\n#define DONT_MULTI_INCLUDE_MDBM_UTIL_HH\n\n#include \n#include \n#include \n#include \n#include \n\n#include \nextern \"C\" {\n \/* Obtain a backtrace and print it to stdout. *\/\n inline void print_trace(void) {\n void *array[10];\n size_t size = backtrace (array, 10);\n char **strings = backtrace_symbols (array, size);\n printf (\"Obtained %d stack frames.\\n\", (int)size);\n for (size_t i = 0; i < size; i++) { fprintf (stderr, \" @-->%s\\n\", strings[i]); }\n free (strings);\n }\n\n\n \/\/ Intel (and later model AMD) Fetch Time-StampCounter\n \/\/ WANRING: This value may be affected by speedstep and may vary randomly across cores.\n __inline__ uint64_t rdtsc(void) {\n uint32_t lo, hi;\n __asm__ __volatile__ ( \/\/ serialize\n \"xorl %%eax,%%eax \\n cpuid\"\n ::: \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\");\n \/* We cannot use \"=A\", since this would use %rax on x86_64 and return only the lower 32bits of the TSC *\/\n __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n return (uint64_t)hi << 32 | lo;\n }\n}\n\n#include \n#include \n\nclass AccumTSCRecord {\npublic:\n volatile uint64_t total;\n volatile uint64_t count;\n std::string label;\n\n AccumTSCRecord() : total(0), count(0), label(\"\") {}\n};\n\nclass AccumTSC {\npublic:\n typedef std::map AccumulatorMap;\n AccumulatorMap records;\n AccumTSC() { }\n ~AccumTSC() {\n \/\/ G++ seems to be creating and destroying these with great abandon, even though\n \/\/ the macro that makes them declares them (function) static\n AccumulatorMap::iterator iter;\n for (iter = records.begin(); iter != records.end(); ++iter) {\n AccumTSCRecord* rec = iter->second;\n fprintf(stderr, \"TSC pid:%d [%-29s] Time % 12lld for % 9lld avg:% 7lld\\n\", getpid(), rec->label.c_str(), (long long)rec->total, (long long)rec->count, rec->count ? ((long long)rec->total) \/ (long long)rec->count : 0);\n }\n }\n AccumTSCRecord* GetRecord(const char* label) {\n static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\n AccumTSCRecord *rec = NULL;\n \/\/fprintf(stderr, \"Fetching accumulator for [%s]\\n\", label);\n pthread_mutex_lock(&mutex);\n AccumulatorMap::iterator iter = records.find(label);\n if (iter != records.end()) {\n rec = records[label];\n } else {\n rec = new AccumTSCRecord;\n rec->label = label;\n records[label] = rec;\n }\n pthread_mutex_unlock(&mutex);\n return rec;\n }\n static void Increment(AccumTSCRecord *rec, uint64_t time) {\n __sync_fetch_and_add(&rec->count, 1);\n __sync_fetch_and_add(&rec->total, time);\n \/\/fprintf(stderr, \"Time %lld for %lld [%s]\\n\", (long long)total, (long long)count, label);\n }\n};\n\nstatic AccumTSC Accumulators;\n\nclass AutoTSC {\npublic:\n uint64_t start;\n const char *label;\n AccumTSCRecord *rec; \n AutoTSC(const char* lbl, AccumTSCRecord* rec) : rec(rec) {\n label = lbl;\n start = rdtsc();\n }\n ~AutoTSC() {\n uint64_t delta = rdtsc() - start;\n Accumulators.Increment(rec, delta);\n \/\/fprintf(stderr, \"Time %lld for [%s]\\n\", (long long)delta, label);\n }\n};\n\n\n\/\/ profiling via Intel TimeStampCounters, function-static and scoped-automatic variables\n#if 0\n# define AUTO_TSC(desc) \\\n static AccumTSCRecord* record = Accumulators.GetRecord(desc); \\\n AutoTSC TSCAuto(desc, record);\n#else\n# define AUTO_TSC(desc)\n#endif\n\n\/\/ branch hinting macros\n#define likely(x) __builtin_expect(!!(x), 1)\n#define unlikely(x) __builtin_expect(!!(x), 0)\n\n\/\/ cache prefetching macros\n#define prefetch(x) __builtin_prefetch(x)\n\n\n\/\/#define CHECKPOINTV(msg, ...) fprintf(stderr, \"%d %s:%d::%s() \"msg\"\\n\", getpid(), __FILE__, __LINE__, __PRETTY_FUNCTION__,__VA_ARGS__); \n#define CHECKPOINTV(msg, ...) \n\n\/\/#define TRACE_LOCKS\n#define PRINT_LOCK_TRACE(msg) { \\\n char buf[512]; \\\n snprintf(buf, 512, \\\n \"rec:%p pid:%d self:\" OWNER_FMT \" %s count:%u owner:\" OWNER_FMT \" idx:%d\\n\", \\\n rec, getpid(), get_thread_id(), msg, rec->count, \\\n rec->owner, index); \\\n fprintf(stderr, buf); \\\n }\n\n#endif \/* DONT_MULTI_INCLUDE_MDBM_UTIL_HH *\/\nFix a typo: WANRING -> WARNING\/* Copyright 2013 Yahoo! Inc. *\/\n\/* See LICENSE in the root of the distribution for licensing details. *\/\n\n#ifndef DONT_MULTI_INCLUDE_MDBM_UTIL_HH\n#define DONT_MULTI_INCLUDE_MDBM_UTIL_HH\n\n#include \n#include \n#include \n#include \n#include \n\n#include \nextern \"C\" {\n \/* Obtain a backtrace and print it to stdout. *\/\n inline void print_trace(void) {\n void *array[10];\n size_t size = backtrace (array, 10);\n char **strings = backtrace_symbols (array, size);\n printf (\"Obtained %d stack frames.\\n\", (int)size);\n for (size_t i = 0; i < size; i++) { fprintf (stderr, \" @-->%s\\n\", strings[i]); }\n free (strings);\n }\n\n\n \/\/ Intel (and later model AMD) Fetch Time-StampCounter\n \/\/ WARNING: This value may be affected by speedstep and may vary randomly across cores.\n __inline__ uint64_t rdtsc(void) {\n uint32_t lo, hi;\n __asm__ __volatile__ ( \/\/ serialize\n \"xorl %%eax,%%eax \\n cpuid\"\n ::: \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\");\n \/* We cannot use \"=A\", since this would use %rax on x86_64 and return only the lower 32bits of the TSC *\/\n __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n return (uint64_t)hi << 32 | lo;\n }\n}\n\n#include \n#include \n\nclass AccumTSCRecord {\npublic:\n volatile uint64_t total;\n volatile uint64_t count;\n std::string label;\n\n AccumTSCRecord() : total(0), count(0), label(\"\") {}\n};\n\nclass AccumTSC {\npublic:\n typedef std::map AccumulatorMap;\n AccumulatorMap records;\n AccumTSC() { }\n ~AccumTSC() {\n \/\/ G++ seems to be creating and destroying these with great abandon, even though\n \/\/ the macro that makes them declares them (function) static\n AccumulatorMap::iterator iter;\n for (iter = records.begin(); iter != records.end(); ++iter) {\n AccumTSCRecord* rec = iter->second;\n fprintf(stderr, \"TSC pid:%d [%-29s] Time % 12lld for % 9lld avg:% 7lld\\n\", getpid(), rec->label.c_str(), (long long)rec->total, (long long)rec->count, rec->count ? ((long long)rec->total) \/ (long long)rec->count : 0);\n }\n }\n AccumTSCRecord* GetRecord(const char* label) {\n static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\n AccumTSCRecord *rec = NULL;\n \/\/fprintf(stderr, \"Fetching accumulator for [%s]\\n\", label);\n pthread_mutex_lock(&mutex);\n AccumulatorMap::iterator iter = records.find(label);\n if (iter != records.end()) {\n rec = records[label];\n } else {\n rec = new AccumTSCRecord;\n rec->label = label;\n records[label] = rec;\n }\n pthread_mutex_unlock(&mutex);\n return rec;\n }\n static void Increment(AccumTSCRecord *rec, uint64_t time) {\n __sync_fetch_and_add(&rec->count, 1);\n __sync_fetch_and_add(&rec->total, time);\n \/\/fprintf(stderr, \"Time %lld for %lld [%s]\\n\", (long long)total, (long long)count, label);\n }\n};\n\nstatic AccumTSC Accumulators;\n\nclass AutoTSC {\npublic:\n uint64_t start;\n const char *label;\n AccumTSCRecord *rec; \n AutoTSC(const char* lbl, AccumTSCRecord* rec) : rec(rec) {\n label = lbl;\n start = rdtsc();\n }\n ~AutoTSC() {\n uint64_t delta = rdtsc() - start;\n Accumulators.Increment(rec, delta);\n \/\/fprintf(stderr, \"Time %lld for [%s]\\n\", (long long)delta, label);\n }\n};\n\n\n\/\/ profiling via Intel TimeStampCounters, function-static and scoped-automatic variables\n#if 0\n# define AUTO_TSC(desc) \\\n static AccumTSCRecord* record = Accumulators.GetRecord(desc); \\\n AutoTSC TSCAuto(desc, record);\n#else\n# define AUTO_TSC(desc)\n#endif\n\n\/\/ branch hinting macros\n#define likely(x) __builtin_expect(!!(x), 1)\n#define unlikely(x) __builtin_expect(!!(x), 0)\n\n\/\/ cache prefetching macros\n#define prefetch(x) __builtin_prefetch(x)\n\n\n\/\/#define CHECKPOINTV(msg, ...) fprintf(stderr, \"%d %s:%d::%s() \"msg\"\\n\", getpid(), __FILE__, __LINE__, __PRETTY_FUNCTION__,__VA_ARGS__); \n#define CHECKPOINTV(msg, ...) \n\n\/\/#define TRACE_LOCKS\n#define PRINT_LOCK_TRACE(msg) { \\\n char buf[512]; \\\n snprintf(buf, 512, \\\n \"rec:%p pid:%d self:\" OWNER_FMT \" %s count:%u owner:\" OWNER_FMT \" idx:%d\\n\", \\\n rec, getpid(), get_thread_id(), msg, rec->count, \\\n rec->owner, index); \\\n fprintf(stderr, buf); \\\n }\n\n#endif \/* DONT_MULTI_INCLUDE_MDBM_UTIL_HH *\/\n<|endoftext|>"} {"text":"\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2015 BMW Car IT 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 * #L%\n *\/\n#include \"joynr\/ClassDeserializer.h\"\n#include \"joynr\/SerializerRegistry.h\"\n#include \"joynr\/IDeserializer.h\"\nnamespace joynr\n{\n\n\/**\n * @brief deserialize not knowing the type\n * @param object\n * @return Variant\n *\/\nVariant deserialize(IObject& o)\n{\n \/\/ The object must have fields\n if (!o.hasNextField()) {\n throw std::invalid_argument(\"Object contains no fields\");\n }\n\n \/\/ The first field has to contain the typename\n IField& field = o.nextField();\n if (field.name() != \"_typeName\") {\n throw std::invalid_argument(\"First field of object should be _typeName\");\n }\n\n \/\/ Create an object of the correct type\n std::string typeName(field.value());\n std::unique_ptr deserializer =\n SerializerRegistry::getDeserializer(typeName);\n\n \/\/ Deserialize\n return deserializer->deserializeVariant(o);\n}\n\nVariant convertVariant(IValue &value)\n{\n if (value.isObject()) {\n return deserialize(value);\n } else if (value.isArray()) {\n return Variant::make>(\n convertArray(value, convertVariant));\n } else {\n \/\/ This covers all non-object values\n \/\/ i.e values without a _typename entry\n return value.getVariant();\n }\n}\n\nstd::string convertString(IValue &value)\n{\n return static_cast(value);\n}\n\nbool convertBool(IValue &value)\n{\n return value.getBool();\n}\n} \/\/ namespace joynr\n[C++] Use removeEscapeFromSpecialChars in ClassDeserializer\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2015 BMW Car IT 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 * #L%\n *\/\n#include \"joynr\/ClassDeserializer.h\"\n#include \"joynr\/SerializerRegistry.h\"\n#include \"joynr\/IDeserializer.h\"\n#include \"joynr\/Util.h\"\nnamespace joynr\n{\n\n\/**\n * @brief deserialize not knowing the type\n * @param object\n * @return Variant\n *\/\nVariant deserialize(IObject& o)\n{\n \/\/ The object must have fields\n if (!o.hasNextField()) {\n throw std::invalid_argument(\"Object contains no fields\");\n }\n\n \/\/ The first field has to contain the typename\n IField& field = o.nextField();\n if (field.name() != \"_typeName\") {\n throw std::invalid_argument(\"First field of object should be _typeName\");\n }\n\n \/\/ Create an object of the correct type\n std::string typeName(field.value());\n std::unique_ptr deserializer =\n SerializerRegistry::getDeserializer(typeName);\n\n \/\/ Deserialize\n return deserializer->deserializeVariant(o);\n}\n\nVariant convertVariant(IValue &value)\n{\n if (value.isObject()) {\n return deserialize(value);\n } else if (value.isArray()) {\n return Variant::make>(\n convertArray(value, convertVariant));\n } else {\n \/\/ This covers all non-object values\n \/\/ i.e values without a _typename entry\n return value.getVariant();\n }\n}\n\nstd::string convertString(IValue &value)\n{\n return removeEscapeFromSpecialChars(static_cast(value));\n}\n\nbool convertBool(IValue &value)\n{\n return value.getBool();\n}\n} \/\/ namespace joynr\n<|endoftext|>"} {"text":"\/* This software is released under the BSD License.\n |\n | Copyright (c) 2009, Kevin P. Barry [the resourcerver project]\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 met:\n |\n | - Redistributions of source code must retain the above copyright notice, this\n | list of conditions and the following disclaimer.\n |\n | - Redistributions in binary form must reproduce the above copyright notice,\n | this list of conditions and the following disclaimer in the documentation\n | and\/or other materials provided with the distribution.\n |\n | - Neither the name of the Resourcerver Project nor the names of its\n | contributors may be used to endorse or promote products derived from this\n | software without specific prior written permission.\n |\n | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n | POSSIBILITY OF SUCH DAMAGE.\n +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\/\n\nextern \"C\" {\n#include \"api-label-check.h\"\n}\n\nextern \"C\" {\n#include \"param.h\"\n}\n\n#include \/* regular expressions *\/\n\n#include \"protocol\/constants.hpp\"\n\n\nstatic regex_t entity_expression = regex_t(), address_expression = regex_t();\nstatic int entity_initialized = 0, address_initialized = 0;\n\n\nint initialize_label_check()\n{\n\t\/\/TODO: add logging point here\n\n\tif (!entity_initialized)\n\t{\n\tregfree(&entity_expression);\n\tentity_initialized = regcomp(&entity_expression, \"^[\" PARAM_ENTITY_FILTER \"]*$\",\n\t REG_EXTENDED | REG_NOSUB) == 0;\n\t}\n\n\tif (!address_initialized)\n\t{\n\tregfree(&address_expression);\n\taddress_initialized = regcomp(&address_expression, \"^[\" PARAM_ADDRESS_FILTER \"]*$\",\n\t REG_EXTENDED | REG_NOSUB) == 0;\n\t}\n\n\treturn entity_initialized && address_initialized;\n}\n\n\nvoid cleanup_label_check()\n{\n\tregfree(&entity_expression);\n\tregfree(&address_expression);\n\tentity_initialized = false;\n\taddress_initialized = false;\n}\n\n\n\/\/TODO: add logging points for exceeded limits\n\n\nresult check_entity_label(text_info lLabel)\n{\n\tif (!lLabel) return true;\n\tif (strlen(lLabel) > PARAM_ENTITY_LIMIT) return false;\n\treturn (entity_initialized || initialize_label_check()) &&\n\t regexec(&entity_expression, lLabel, 0, NULL, 0x00) == 0;\n}\n\n\nresult check_address_label(text_info lLabel)\n{\n\tif (!lLabel) return true;\n\tif (strlen(lLabel) > PARAM_SCOPE_LIMIT) return false;\n\tif ( !(address_initialized || initialize_label_check()) ||\n\t regexec(&address_expression, lLabel, 0, NULL, 0x00) != 0 )\n\treturn false;\n\n\tint target = -1, address = 0, current_address = 0;\n\tconst char *current = lLabel;\n\tbool checking_address = false;\n\n\tif (current) while (*current)\n\t{\n\tif (*current == client_scope_char)\n\t {\n\tif (target > address) return false;\n\tchecking_address = true;\n\ttarget = current - lLabel;\n\t }\n\n\telse if (*current == address_scope_char)\n\t {\n\tif (address > target) return false;\n\tchecking_address = false;\n\tcurrent_address = 0;\n\taddress = current - lLabel;\n\t }\n\n\telse if (checking_address && ++current_address > PARAM_ADDRESS_LIMIT) return false;\n\n\tcurrent++;\n\t}\n\n\treturn target < 0 || target > address;\n}\n\n\nresult check_next_to_address(text_info lLabel)\n{\n\tif (!lLabel) return false;\n\n\tconst char *current = lLabel;\n\n\tif (current) while (*current)\n\t{\n\tif (*current == client_scope_char) return false;\n\telse if (*current == address_scope_char) return true;\n\tcurrent++;\n\t}\n\n\treturn true;\n}\n\n\nresult check_next_to_client(text_info lLabel)\n{\n\tif (!lLabel) return false;\n\tif (!strlen(lLabel)) return true;\n\n\tconst char *current = lLabel;\n\n\tif (current) while (*current)\n\t{\n\tif (*current == client_scope_char) return true;\n\telse if (*current == address_scope_char) return false;\n\tcurrent++;\n\t}\n\n\treturn false;\n}\ngamma.3 - fixed include in api-label-check\/* This software is released under the BSD License.\n |\n | Copyright (c) 2009, Kevin P. Barry [the resourcerver project]\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 met:\n |\n | - Redistributions of source code must retain the above copyright notice, this\n | list of conditions and the following disclaimer.\n |\n | - Redistributions in binary form must reproduce the above copyright notice,\n | this list of conditions and the following disclaimer in the documentation\n | and\/or other materials provided with the distribution.\n |\n | - Neither the name of the Resourcerver Project nor the names of its\n | contributors may be used to endorse or promote products derived from this\n | software without specific prior written permission.\n |\n | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n | POSSIBILITY OF SUCH DAMAGE.\n +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\/\n\nextern \"C\" {\n#include \"api-label-check.h\"\n}\n\nextern \"C\" {\n#include \"param.h\"\n}\n\n#include \/\/regular expressions\n#include \/\/'strlen', etc.\n\n#include \"protocol\/constants.hpp\"\n\n\nstatic regex_t entity_expression = regex_t(), address_expression = regex_t();\nstatic int entity_initialized = 0, address_initialized = 0;\n\n\nint initialize_label_check()\n{\n\t\/\/TODO: add logging point here\n\n\tif (!entity_initialized)\n\t{\n\tregfree(&entity_expression);\n\tentity_initialized = regcomp(&entity_expression, \"^[\" PARAM_ENTITY_FILTER \"]*$\",\n\t REG_EXTENDED | REG_NOSUB) == 0;\n\t}\n\n\tif (!address_initialized)\n\t{\n\tregfree(&address_expression);\n\taddress_initialized = regcomp(&address_expression, \"^[\" PARAM_ADDRESS_FILTER \"]*$\",\n\t REG_EXTENDED | REG_NOSUB) == 0;\n\t}\n\n\treturn entity_initialized && address_initialized;\n}\n\n\nvoid cleanup_label_check()\n{\n\tregfree(&entity_expression);\n\tregfree(&address_expression);\n\tentity_initialized = false;\n\taddress_initialized = false;\n}\n\n\n\/\/TODO: add logging points for exceeded limits\n\n\nresult check_entity_label(text_info lLabel)\n{\n\tif (!lLabel) return true;\n\tif (strlen(lLabel) > PARAM_ENTITY_LIMIT) return false;\n\treturn (entity_initialized || initialize_label_check()) &&\n\t regexec(&entity_expression, lLabel, 0, NULL, 0x00) == 0;\n}\n\n\nresult check_address_label(text_info lLabel)\n{\n\tif (!lLabel) return true;\n\tif (strlen(lLabel) > PARAM_SCOPE_LIMIT) return false;\n\tif ( !(address_initialized || initialize_label_check()) ||\n\t regexec(&address_expression, lLabel, 0, NULL, 0x00) != 0 )\n\treturn false;\n\n\tint target = -1, address = 0, current_address = 0;\n\tconst char *current = lLabel;\n\tbool checking_address = false;\n\n\tif (current) while (*current)\n\t{\n\tif (*current == client_scope_char)\n\t {\n\tif (target > address) return false;\n\tchecking_address = true;\n\ttarget = current - lLabel;\n\t }\n\n\telse if (*current == address_scope_char)\n\t {\n\tif (address > target) return false;\n\tchecking_address = false;\n\tcurrent_address = 0;\n\taddress = current - lLabel;\n\t }\n\n\telse if (checking_address && ++current_address > PARAM_ADDRESS_LIMIT) return false;\n\n\tcurrent++;\n\t}\n\n\treturn target < 0 || target > address;\n}\n\n\nresult check_next_to_address(text_info lLabel)\n{\n\tif (!lLabel) return false;\n\n\tconst char *current = lLabel;\n\n\tif (current) while (*current)\n\t{\n\tif (*current == client_scope_char) return false;\n\telse if (*current == address_scope_char) return true;\n\tcurrent++;\n\t}\n\n\treturn true;\n}\n\n\nresult check_next_to_client(text_info lLabel)\n{\n\tif (!lLabel) return false;\n\tif (!strlen(lLabel)) return true;\n\n\tconst char *current = lLabel;\n\n\tif (current) while (*current)\n\t{\n\tif (*current == client_scope_char) return true;\n\telse if (*current == address_scope_char) return false;\n\tcurrent++;\n\t}\n\n\treturn false;\n}\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"common.h\"\n#include \"math.h\"\n#include \"PlayerState.h\"\n#include \"Pack.h\"\n#include \"Protocol.h\"\n#include \"StateDatabase.h\"\n\n\/\/ the full scale of a int16_t (less 1.0 for safety)\nconst float smallScale = 32766.0f;\n\n\/\/ 2 cm resolution (range: +\/- 655.34 meters)\nconst float smallMaxDist = 0.02f * smallScale;\n\n\/\/ 1 cm\/sec resolution (range: +\/- 327.66 meters\/sec)\nconst float smallMaxVel = 0.01f * smallScale;\n\n\/\/ 0.001 radians\/sec resolution (range: +\/- 32.766 rads\/sec)\nconst float smallMaxAngVel = 0.001f * smallScale;\n\n\nPlayerState::PlayerState()\n: order(0), status(DeadStatus), azimuth(0.0f), angVel(0.0f)\n{\n pos[0] = pos[1] = pos[2] = 0.0f;\n velocity[0] = velocity[0] = velocity[2] = 0.0f;\n}\n\nvoid*\tPlayerState::pack(void* buf, uint16_t& code)\n{\n order++;\n buf = nboPackInt(buf, int32_t(order));\n buf = nboPackShort(buf, int16_t(status));\n \n if ((BZDB.eval(StateDatabase::BZDB_NOSMALLPACKETS) > 0.0f) ||\n (fabsf (pos[0]) >= smallMaxDist) ||\n (fabsf (pos[1]) >= smallMaxDist) ||\n (fabsf (pos[2]) >= smallMaxDist) ||\n (fabsf (velocity[0]) >= smallMaxVel) ||\n (fabsf (velocity[1]) >= smallMaxVel) ||\n (fabsf (velocity[2]) >= smallMaxVel) ||\n (fabsf (angVel) >= smallMaxAngVel)) {\n\n code = MsgPlayerUpdate;\n \n buf = nboPackVector(buf, pos);\n buf = nboPackVector(buf, velocity);\n buf = nboPackFloat(buf, azimuth);\n buf = nboPackFloat(buf, angVel);\n }\n else {\n\n code = MsgPlayerUpdateSmall;\n \n int16_t posShort[3], velShort[3], aziShort, angVelShort;\n \n for (int i=0; i<3; i++) {\n posShort[i] = (int16_t) ((pos[i] * smallScale) \/ smallMaxDist);\n velShort[i] = (int16_t) ((velocity[i] * smallScale) \/ smallMaxVel);\n }\n\n \/\/ put the angle between -M_PI and +M_PI\n float angle = fmodf (azimuth, M_PI * 2.0f);\n if (angle > M_PI) {\n angle -= (M_PI * 2.0f);\n } \n else if (angle < -M_PI) {\n angle += (M_PI * 2.0f);\n } \n aziShort = (int16_t) ((angle * smallScale) \/ M_PI);\n angVelShort = (int16_t) ((angVel * smallScale) \/ smallMaxAngVel);\n\n buf = nboPackShort(buf, posShort[0]);\n buf = nboPackShort(buf, posShort[1]);\n buf = nboPackShort(buf, posShort[2]);\n buf = nboPackShort(buf, velShort[0]);\n buf = nboPackShort(buf, velShort[1]);\n buf = nboPackShort(buf, velShort[2]);\n buf = nboPackShort(buf, aziShort);\n buf = nboPackShort(buf, angVelShort);\n }\n return buf;\n}\n\nvoid*\tPlayerState::unpack(void* buf, uint16_t code)\n{\n int32_t inOrder;\n int16_t inStatus;\n buf = nboUnpackInt(buf, inOrder);\n buf = nboUnpackShort(buf, inStatus);\n order = int(inOrder);\n status = short(inStatus);\n\n if (code == MsgPlayerUpdate) {\n buf = nboUnpackVector(buf, pos);\n buf = nboUnpackVector(buf, velocity);\n buf = nboUnpackFloat(buf, azimuth);\n buf = nboUnpackFloat(buf, angVel);\n }\n else {\n int16_t posShort[3], velShort[3], aziShort, angVelShort;\n\n buf = nboUnpackShort(buf, posShort[0]);\n buf = nboUnpackShort(buf, posShort[1]);\n buf = nboUnpackShort(buf, posShort[2]);\n buf = nboUnpackShort(buf, velShort[0]);\n buf = nboUnpackShort(buf, velShort[1]);\n buf = nboUnpackShort(buf, velShort[2]);\n buf = nboUnpackShort(buf, aziShort);\n buf = nboUnpackShort(buf, angVelShort);\n \n for (int i=0; i<3; i++) {\n pos[i] = ((float)posShort[i] * smallMaxDist) \/ smallScale;\n velocity[i] = ((float)velShort[i] * smallMaxVel) \/ smallScale;\n }\n azimuth = ((float)aziShort * M_PI) \/ smallScale;\n angVel = ((float)angVelShort * smallMaxAngVel) \/ smallScale;\n }\n return buf;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\ntoday's lesson, multiplication\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"common.h\"\n#include \"math.h\"\n#include \"PlayerState.h\"\n#include \"Pack.h\"\n#include \"Protocol.h\"\n#include \"StateDatabase.h\"\n\n\/\/ the full scale of a int16_t (less 1.0 for safety)\nconst float smallScale = 32766.0f;\n\n\/\/ 2 cm resolution (range: +\/- 655.32 meters)\nconst float smallMaxDist = 0.02f * smallScale;\n\n\/\/ 1 cm\/sec resolution (range: +\/- 327.66 meters\/sec)\nconst float smallMaxVel = 0.01f * smallScale;\n\n\/\/ 0.001 radians\/sec resolution (range: +\/- 32.766 rads\/sec)\nconst float smallMaxAngVel = 0.001f * smallScale;\n\n\nPlayerState::PlayerState()\n: order(0), status(DeadStatus), azimuth(0.0f), angVel(0.0f)\n{\n pos[0] = pos[1] = pos[2] = 0.0f;\n velocity[0] = velocity[0] = velocity[2] = 0.0f;\n}\n\nvoid*\tPlayerState::pack(void* buf, uint16_t& code)\n{\n order++;\n buf = nboPackInt(buf, int32_t(order));\n buf = nboPackShort(buf, int16_t(status));\n \n if ((BZDB.eval(StateDatabase::BZDB_NOSMALLPACKETS) > 0.0f) ||\n (fabsf (pos[0]) >= smallMaxDist) ||\n (fabsf (pos[1]) >= smallMaxDist) ||\n (fabsf (pos[2]) >= smallMaxDist) ||\n (fabsf (velocity[0]) >= smallMaxVel) ||\n (fabsf (velocity[1]) >= smallMaxVel) ||\n (fabsf (velocity[2]) >= smallMaxVel) ||\n (fabsf (angVel) >= smallMaxAngVel)) {\n\n code = MsgPlayerUpdate;\n \n buf = nboPackVector(buf, pos);\n buf = nboPackVector(buf, velocity);\n buf = nboPackFloat(buf, azimuth);\n buf = nboPackFloat(buf, angVel);\n }\n else {\n\n code = MsgPlayerUpdateSmall;\n \n int16_t posShort[3], velShort[3], aziShort, angVelShort;\n \n for (int i=0; i<3; i++) {\n posShort[i] = (int16_t) ((pos[i] * smallScale) \/ smallMaxDist);\n velShort[i] = (int16_t) ((velocity[i] * smallScale) \/ smallMaxVel);\n }\n\n \/\/ put the angle between -M_PI and +M_PI\n float angle = fmodf (azimuth, M_PI * 2.0f);\n if (angle > M_PI) {\n angle -= (M_PI * 2.0f);\n } \n else if (angle < -M_PI) {\n angle += (M_PI * 2.0f);\n } \n aziShort = (int16_t) ((angle * smallScale) \/ M_PI);\n angVelShort = (int16_t) ((angVel * smallScale) \/ smallMaxAngVel);\n\n buf = nboPackShort(buf, posShort[0]);\n buf = nboPackShort(buf, posShort[1]);\n buf = nboPackShort(buf, posShort[2]);\n buf = nboPackShort(buf, velShort[0]);\n buf = nboPackShort(buf, velShort[1]);\n buf = nboPackShort(buf, velShort[2]);\n buf = nboPackShort(buf, aziShort);\n buf = nboPackShort(buf, angVelShort);\n }\n return buf;\n}\n\nvoid*\tPlayerState::unpack(void* buf, uint16_t code)\n{\n int32_t inOrder;\n int16_t inStatus;\n buf = nboUnpackInt(buf, inOrder);\n buf = nboUnpackShort(buf, inStatus);\n order = int(inOrder);\n status = short(inStatus);\n\n if (code == MsgPlayerUpdate) {\n buf = nboUnpackVector(buf, pos);\n buf = nboUnpackVector(buf, velocity);\n buf = nboUnpackFloat(buf, azimuth);\n buf = nboUnpackFloat(buf, angVel);\n }\n else {\n int16_t posShort[3], velShort[3], aziShort, angVelShort;\n\n buf = nboUnpackShort(buf, posShort[0]);\n buf = nboUnpackShort(buf, posShort[1]);\n buf = nboUnpackShort(buf, posShort[2]);\n buf = nboUnpackShort(buf, velShort[0]);\n buf = nboUnpackShort(buf, velShort[1]);\n buf = nboUnpackShort(buf, velShort[2]);\n buf = nboUnpackShort(buf, aziShort);\n buf = nboUnpackShort(buf, angVelShort);\n \n for (int i=0; i<3; i++) {\n pos[i] = ((float)posShort[i] * smallMaxDist) \/ smallScale;\n velocity[i] = ((float)velShort[i] * smallMaxVel) \/ smallScale;\n }\n azimuth = ((float)aziShort * M_PI) \/ smallScale;\n angVel = ((float)angVelShort * smallMaxAngVel) \/ smallScale;\n }\n return buf;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"#include \"Club.h\"\n\nusing namespace std;\n\nClub::Club(): money_(0), installations_() {\n\n for (int i = 0; i < 7; ++i) {\n players_.push_back(new NonFieldPlayer());\n\n team_->setPlayer(*players_.at((unsigned int)i), i);\n\n }\n}\n\n\nClub::Club(JsonValue * json) {\n JsonDict * club = JDICT(json);\n JsonDict * ins;\n\n if (club == NULL) {\n throw ModelUnserializationError(\"Club initialized from non dict\");\n }\n\n JsonInt * money_int = JINT((*club)[\"money\"]);\n if (money_int == NULL) {\n throw ModelUnserializationError(\"Missing int at key 'money' in Club\");\n }\n\n int money = *money_int;\n Installation installations[5];\n\n JsonList * installations_list = JLIST((*club)[\"installations\"]);\n if (installations_list == NULL) {\n throw ModelUnserializationError(\"Missing list at key 'installations' in Club\");\n }\n if (installations_list->size() != 5) {\n throw ModelUnserializationError(\"Bad 'installations' size in Club\");\n }\n\n\n for (int i = 0; i < 5; i++) {\n ins = JDICT((*installations_list)[i]);\n if (ins == NULL) {\n throw ModelUnserializationError(\"Null installation in Club\");\n }\n\n installations[i] = Installation(ins);\n }\n\n Team * team = new Team((*club)[\"team\"]);\n JsonList * player_list = JLIST((*club)[\"players\"]);\n if (player_list == NULL) {\n throw ModelUnserializationError(\"Missing list at key 'players' in Club\");\n }\n\n vector players;\n for (int i = 0; i < player_list->size(); i++) {\n players.push_back(new NonFieldPlayer((*player_list)[i]));\n }\n \/\/TODO uncomment\n \/\/for (int i = 0; i < 7; i++) {\n \/\/ if (team_->getPlayer(i) != NULL) {\n \/\/ players.push_back(team_->getPlayer(i));\n \/\/ }\n \/\/}\n\n new (this)Club(money, installations, team, players);\n}\n\nClub::Club(int money, Installation * installations, Team * team, vector players): money_(money), players_(players) {\n for (int i = 0; i < 5; ++i) {\n installations_[i] = installations[i];\n }\n team_ = team;\n}\n\nClub::~Club() {}\n\nint Club::addMoney(const int deltaMoney) {\n return money_ += deltaMoney;\n}\n\nint Club::getMoney() {\n return money_;\n}\n\nint Club::getLevel() {\n int level = 0;\n for (int i = 0; i < 5; ++i) {\n level += installations_[i].getLevel();\n }\n return level;\n}\n\nTeam * Club::getTeam() {\n return team_;\n}\n\nstd::vector Club::getNonFieldPlayers() {\n return players_;\n}\n\nvoid Club::addNonFieldPlayer(NonFieldPlayer * player) {\n players_.push_back(player);\n}\n\nNonFieldPlayer * Club::removeNonFieldPlayer(unsigned int pos) {\n NonFieldPlayer * tmpPlayer = players_[pos];\n players_.erase(players_.begin() + pos);\n return tmpPlayer;\n}\n\n\nvoid Club::addInstallation(Installation & installation, int pos) {\n installations_[pos] = installation;\n}\n\nInstallation * Club::getInstallations() {\n return installations_;\n}\n\n\nClub::operator JsonDict() const {\n JsonDict r;\n\n r.add(\"money\", new JsonInt(money_));\n\n JsonDict * team = new JsonDict(*team_);\n r.add(\"team\", team);\n\n JsonList * installations = new JsonList();\n for (int i = 0; i < 5; i++) {\n JsonDict * install = new JsonDict(installations_[i]);\n installations->add(install);\n }\n r.add(\"installations\", installations);\n\n JsonList * players = new JsonList();\n for (int i = 0; i < players_.size(); i++) {\n bool present = false;\n for (int j = 0; (j < 7) && (!present); j++) {\n present = players_[i] == team_->getPlayer(j);\n }\n if (!present) {\n JsonDict * player = new JsonDict(*(players_[i]));\n players->add(player);\n }\n }\n r.add(\"players\", players);\n\n return r;\n}\nFix problem when login with an existing username.#include \"Club.h\"\n\nusing namespace std;\n\nClub::Club(): money_(0), installations_() {\n\n for (int i = 0; i < 7; ++i) {\n players_.push_back(new NonFieldPlayer());\n\n team_->setPlayer(*players_.at((unsigned int)i), i);\n\n }\n}\n\n\nClub::Club(JsonValue * json) {\n JsonDict * club = JDICT(json);\n JsonDict * ins;\n\n if (club == NULL) {\n throw ModelUnserializationError(\"Club initialized from non dict\");\n }\n\n JsonInt * money_int = JINT((*club)[\"money\"]);\n if (money_int == NULL) {\n throw ModelUnserializationError(\"Missing int at key 'money' in Club\");\n }\n\n int money = *money_int;\n Installation installations[5];\n\n JsonList * installations_list = JLIST((*club)[\"installations\"]);\n if (installations_list == NULL) {\n throw ModelUnserializationError(\"Missing list at key 'installations' in Club\");\n }\n if (installations_list->size() != 5) {\n throw ModelUnserializationError(\"Bad 'installations' size in Club\");\n }\n\n\n for (int i = 0; i < 5; i++) {\n ins = JDICT((*installations_list)[i]);\n if (ins == NULL) {\n throw ModelUnserializationError(\"Null installation in Club\");\n }\n\n installations[i] = Installation(ins);\n }\n\n Team * team = new Team((*club)[\"team\"]);\n JsonList * player_list = JLIST((*club)[\"players\"]);\n if (player_list == NULL) {\n throw ModelUnserializationError(\"Missing list at key 'players' in Club\");\n }\n\n vector players;\n for (int i = 0; i < player_list->size(); i++) {\n players.push_back(new NonFieldPlayer((*player_list)[i]));\n }\n for (int i = 0; i < 7; i++) {\n if (team->getPlayer(i) != NULL) {\n players.push_back(team->getPlayer(i));\n }\n }\n\n new (this)Club(money, installations, team, players);\n}\n\nClub::Club(int money, Installation * installations, Team * team, vector players): money_(money), players_(players) {\n for (int i = 0; i < 5; ++i) {\n installations_[i] = installations[i];\n }\n team_ = team;\n}\n\nClub::~Club() {}\n\nint Club::addMoney(const int deltaMoney) {\n return money_ += deltaMoney;\n}\n\nint Club::getMoney() {\n return money_;\n}\n\nint Club::getLevel() {\n int level = 0;\n for (int i = 0; i < 5; ++i) {\n level += installations_[i].getLevel();\n }\n return level;\n}\n\nTeam * Club::getTeam() {\n return team_;\n}\n\nstd::vector Club::getNonFieldPlayers() {\n return players_;\n}\n\nvoid Club::addNonFieldPlayer(NonFieldPlayer * player) {\n players_.push_back(player);\n}\n\nNonFieldPlayer * Club::removeNonFieldPlayer(unsigned int pos) {\n NonFieldPlayer * tmpPlayer = players_[pos];\n players_.erase(players_.begin() + pos);\n return tmpPlayer;\n}\n\n\nvoid Club::addInstallation(Installation & installation, int pos) {\n installations_[pos] = installation;\n}\n\nInstallation * Club::getInstallations() {\n return installations_;\n}\n\n\nClub::operator JsonDict() const {\n JsonDict r;\n\n r.add(\"money\", new JsonInt(money_));\n\n JsonDict * team = new JsonDict(*team_);\n r.add(\"team\", team);\n\n JsonList * installations = new JsonList();\n for (int i = 0; i < 5; i++) {\n JsonDict * install = new JsonDict(installations_[i]);\n installations->add(install);\n }\n r.add(\"installations\", installations);\n\n JsonList * players = new JsonList();\n for (int i = 0; i < players_.size(); i++) {\n bool present = false;\n for (int j = 0; (j < 7) && (!present); j++) {\n present = players_[i] == team_->getPlayer(j);\n }\n if (!present) {\n JsonDict * player = new JsonDict(*(players_[i]));\n players->add(player);\n }\n }\n r.add(\"players\", players);\n\n return r;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2002-2010 The ANGLE Project 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\n#include \"compiler\/PoolAlloc.h\"\n\n#ifndef _MSC_VER\n#include \n#endif\n\n#include \"compiler\/InitializeGlobals.h\"\n#include \"compiler\/osinclude.h\"\n\nOS_TLSIndex PoolIndex = OS_INVALID_TLS_INDEX;\n\nvoid InitializeGlobalPools()\n{\n TThreadGlobalPools* globalPools= static_cast(OS_GetTLSValue(PoolIndex)); \n if (globalPools)\n return;\n\n TPoolAllocator *globalPoolAllocator = new TPoolAllocator(true);\n\n TThreadGlobalPools* threadData = new TThreadGlobalPools();\n \n threadData->globalPoolAllocator = globalPoolAllocator;\n \n OS_SetTLSValue(PoolIndex, threadData); \n globalPoolAllocator->push();\n}\n\nvoid FreeGlobalPools()\n{\n \/\/ Release the allocated memory for this thread.\n TThreadGlobalPools* globalPools= static_cast(OS_GetTLSValue(PoolIndex)); \n if (!globalPools)\n return;\n \n GlobalPoolAllocator.popAll();\n delete &GlobalPoolAllocator; \n delete globalPools;\n}\n\nbool InitializePoolIndex()\n{\n \/\/ Allocate a TLS index.\n if ((PoolIndex = OS_AllocTLSIndex()) == OS_INVALID_TLS_INDEX)\n return false;\n\n return true;\n}\n\nvoid FreePoolIndex()\n{\n \/\/ Release the TLS index.\n OS_FreeTLSIndex(PoolIndex);\n}\n\nTPoolAllocator& GetGlobalPoolAllocator()\n{\n TThreadGlobalPools* threadData = static_cast(OS_GetTLSValue(PoolIndex));\n\n return *threadData->globalPoolAllocator;\n}\n\nvoid SetGlobalPoolAllocatorPtr(TPoolAllocator* poolAllocator)\n{\n TThreadGlobalPools* threadData = static_cast(OS_GetTLSValue(PoolIndex));\n\n threadData->globalPoolAllocator = poolAllocator;\n}\n\n\/\/\n\/\/ Implement the functionality of the TPoolAllocator class, which\n\/\/ is documented in PoolAlloc.h.\n\/\/\nTPoolAllocator::TPoolAllocator(bool g, int growthIncrement, int allocationAlignment) : \n global(g),\n pageSize(growthIncrement),\n alignment(allocationAlignment),\n freeList(0),\n inUseList(0),\n numCalls(0)\n{\n \/\/\n \/\/ Don't allow page sizes we know are smaller than all common\n \/\/ OS page sizes.\n \/\/\n if (pageSize < 4*1024)\n pageSize = 4*1024;\n\n \/\/\n \/\/ A large currentPageOffset indicates a new page needs to\n \/\/ be obtained to allocate memory.\n \/\/\n currentPageOffset = pageSize;\n\n \/\/\n \/\/ Adjust alignment to be at least pointer aligned and\n \/\/ power of 2.\n \/\/\n size_t minAlign = sizeof(void*);\n alignment &= ~(minAlign - 1);\n if (alignment < minAlign)\n alignment = minAlign;\n size_t a = 1;\n while (a < alignment)\n a <<= 1;\n alignment = a;\n alignmentMask = a - 1;\n\n \/\/\n \/\/ Align header skip\n \/\/\n headerSkip = minAlign;\n if (headerSkip < sizeof(tHeader)) {\n headerSkip = (sizeof(tHeader) + alignmentMask) & ~alignmentMask;\n }\n}\n\nTPoolAllocator::~TPoolAllocator()\n{\n if (!global) {\n \/\/\n \/\/ Then we know that this object is not being \n \/\/ allocated after other, globally scoped objects\n \/\/ that depend on it. So we can delete the \"in use\" memory.\n \/\/\n while (inUseList) {\n tHeader* next = inUseList->nextPage;\n inUseList->~tHeader();\n delete [] reinterpret_cast(inUseList);\n inUseList = next;\n }\n }\n\n \/\/\n \/\/ Always delete the free list memory - it can't be being\n \/\/ (correctly) referenced, whether the pool allocator was\n \/\/ global or not. We should not check the guard blocks\n \/\/ here, because we did it already when the block was\n \/\/ placed into the free list.\n \/\/\n while (freeList) {\n tHeader* next = freeList->nextPage;\n delete [] reinterpret_cast(freeList);\n freeList = next;\n }\n}\n\n\/\/ Support MSVC++ 6.0\nconst unsigned char TAllocation::guardBlockBeginVal = 0xfb;\nconst unsigned char TAllocation::guardBlockEndVal = 0xfe;\nconst unsigned char TAllocation::userDataFill = 0xcd;\n\n#ifdef GUARD_BLOCKS\n const size_t TAllocation::guardBlockSize = 16;\n#else\n const size_t TAllocation::guardBlockSize = 0;\n#endif\n\n\/\/\n\/\/ Check a single guard block for damage\n\/\/\nvoid TAllocation::checkGuardBlock(unsigned char* blockMem, unsigned char val, const char* locText) const\n{\n for (size_t x = 0; x < guardBlockSize; x++) {\n if (blockMem[x] != val) {\n char assertMsg[80];\n\n \/\/ We don't print the assert message. It's here just to be helpful.\n sprintf(assertMsg, \"PoolAlloc: Damage %s %u byte allocation at 0x%p\\n\",\n locText, size, data());\n assert(0 && \"PoolAlloc: Damage in guard block\");\n }\n }\n}\n\n\nvoid TPoolAllocator::push()\n{\n tAllocState state = { currentPageOffset, inUseList };\n\n stack.push_back(state);\n \n \/\/\n \/\/ Indicate there is no current page to allocate from.\n \/\/\n currentPageOffset = pageSize;\n}\n\n\/\/\n\/\/ Do a mass-deallocation of all the individual allocations\n\/\/ that have occurred since the last push(), or since the\n\/\/ last pop(), or since the object's creation.\n\/\/\n\/\/ The deallocated pages are saved for future allocations.\n\/\/\nvoid TPoolAllocator::pop()\n{\n if (stack.size() < 1)\n return;\n\n tHeader* page = stack.back().page;\n currentPageOffset = stack.back().offset;\n\n while (inUseList != page) {\n \/\/ invoke destructor to free allocation list\n inUseList->~tHeader();\n \n tHeader* nextInUse = inUseList->nextPage;\n if (inUseList->pageCount > 1)\n delete [] reinterpret_cast(inUseList);\n else {\n inUseList->nextPage = freeList;\n freeList = inUseList;\n }\n inUseList = nextInUse;\n }\n\n stack.pop_back();\n}\n\n\/\/\n\/\/ Do a mass-deallocation of all the individual allocations\n\/\/ that have occurred.\n\/\/\nvoid TPoolAllocator::popAll()\n{\n while (stack.size() > 0)\n pop();\n}\n\nvoid* TPoolAllocator::allocate(size_t numBytes)\n{\n \/\/ If we are using guard blocks, all allocations are bracketed by\n \/\/ them: [guardblock][allocation][guardblock]. numBytes is how\n \/\/ much memory the caller asked for. allocationSize is the total\n \/\/ size including guard blocks. In release build,\n \/\/ guardBlockSize=0 and this all gets optimized away.\n size_t allocationSize = TAllocation::allocationSize(numBytes);\n \n \/\/\n \/\/ Just keep some interesting statistics.\n \/\/\n ++numCalls;\n totalBytes += numBytes;\n\n \/\/\n \/\/ Do the allocation, most likely case first, for efficiency.\n \/\/ This step could be moved to be inline sometime.\n \/\/\n if (currentPageOffset + allocationSize <= pageSize) {\n \/\/\n \/\/ Safe to allocate from currentPageOffset.\n \/\/\n unsigned char* memory = reinterpret_cast(inUseList) + currentPageOffset;\n currentPageOffset += allocationSize;\n currentPageOffset = (currentPageOffset + alignmentMask) & ~alignmentMask;\n\n return initializeAllocation(inUseList, memory, numBytes);\n }\n\n if (allocationSize + headerSkip > pageSize) {\n \/\/\n \/\/ Do a multi-page allocation. Don't mix these with the others.\n \/\/ The OS is efficient and allocating and free-ing multiple pages.\n \/\/\n size_t numBytesToAlloc = allocationSize + headerSkip;\n tHeader* memory = reinterpret_cast(::new char[numBytesToAlloc]);\n if (memory == 0)\n return 0;\n\n \/\/ Use placement-new to initialize header\n new(memory) tHeader(inUseList, (numBytesToAlloc + pageSize - 1) \/ pageSize);\n inUseList = memory;\n\n currentPageOffset = pageSize; \/\/ make next allocation come from a new page\n\n \/\/ No guard blocks for multi-page allocations (yet)\n return reinterpret_cast(reinterpret_cast(memory) + headerSkip);\n }\n\n \/\/\n \/\/ Need a simple page to allocate from.\n \/\/\n tHeader* memory;\n if (freeList) {\n memory = freeList;\n freeList = freeList->nextPage;\n } else {\n memory = reinterpret_cast(::new char[pageSize]);\n if (memory == 0)\n return 0;\n }\n\n \/\/ Use placement-new to initialize header\n new(memory) tHeader(inUseList, 1);\n inUseList = memory;\n \n unsigned char* ret = reinterpret_cast(inUseList) + headerSkip;\n currentPageOffset = (headerSkip + allocationSize + alignmentMask) & ~alignmentMask;\n\n return initializeAllocation(inUseList, ret, numBytes);\n}\n\n\n\/\/\n\/\/ Check all allocations in a list for damage by calling check on each.\n\/\/\nvoid TAllocation::checkAllocList() const\n{\n for (const TAllocation* alloc = this; alloc != 0; alloc = alloc->prevAlloc)\n alloc->check();\n}\nFixed compile error with gcc 4.4. TBR=gman@chromium.org Review URL: http:\/\/codereview.appspot.com\/1199047\/\/\n\/\/ Copyright (c) 2002-2010 The ANGLE Project 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\n#include \"compiler\/PoolAlloc.h\"\n\n#ifndef _MSC_VER\n#include \n#endif\n#include \n\n#include \"compiler\/InitializeGlobals.h\"\n#include \"compiler\/osinclude.h\"\n\nOS_TLSIndex PoolIndex = OS_INVALID_TLS_INDEX;\n\nvoid InitializeGlobalPools()\n{\n TThreadGlobalPools* globalPools= static_cast(OS_GetTLSValue(PoolIndex)); \n if (globalPools)\n return;\n\n TPoolAllocator *globalPoolAllocator = new TPoolAllocator(true);\n\n TThreadGlobalPools* threadData = new TThreadGlobalPools();\n \n threadData->globalPoolAllocator = globalPoolAllocator;\n \n OS_SetTLSValue(PoolIndex, threadData); \n globalPoolAllocator->push();\n}\n\nvoid FreeGlobalPools()\n{\n \/\/ Release the allocated memory for this thread.\n TThreadGlobalPools* globalPools= static_cast(OS_GetTLSValue(PoolIndex)); \n if (!globalPools)\n return;\n \n GlobalPoolAllocator.popAll();\n delete &GlobalPoolAllocator; \n delete globalPools;\n}\n\nbool InitializePoolIndex()\n{\n \/\/ Allocate a TLS index.\n if ((PoolIndex = OS_AllocTLSIndex()) == OS_INVALID_TLS_INDEX)\n return false;\n\n return true;\n}\n\nvoid FreePoolIndex()\n{\n \/\/ Release the TLS index.\n OS_FreeTLSIndex(PoolIndex);\n}\n\nTPoolAllocator& GetGlobalPoolAllocator()\n{\n TThreadGlobalPools* threadData = static_cast(OS_GetTLSValue(PoolIndex));\n\n return *threadData->globalPoolAllocator;\n}\n\nvoid SetGlobalPoolAllocatorPtr(TPoolAllocator* poolAllocator)\n{\n TThreadGlobalPools* threadData = static_cast(OS_GetTLSValue(PoolIndex));\n\n threadData->globalPoolAllocator = poolAllocator;\n}\n\n\/\/\n\/\/ Implement the functionality of the TPoolAllocator class, which\n\/\/ is documented in PoolAlloc.h.\n\/\/\nTPoolAllocator::TPoolAllocator(bool g, int growthIncrement, int allocationAlignment) : \n global(g),\n pageSize(growthIncrement),\n alignment(allocationAlignment),\n freeList(0),\n inUseList(0),\n numCalls(0)\n{\n \/\/\n \/\/ Don't allow page sizes we know are smaller than all common\n \/\/ OS page sizes.\n \/\/\n if (pageSize < 4*1024)\n pageSize = 4*1024;\n\n \/\/\n \/\/ A large currentPageOffset indicates a new page needs to\n \/\/ be obtained to allocate memory.\n \/\/\n currentPageOffset = pageSize;\n\n \/\/\n \/\/ Adjust alignment to be at least pointer aligned and\n \/\/ power of 2.\n \/\/\n size_t minAlign = sizeof(void*);\n alignment &= ~(minAlign - 1);\n if (alignment < minAlign)\n alignment = minAlign;\n size_t a = 1;\n while (a < alignment)\n a <<= 1;\n alignment = a;\n alignmentMask = a - 1;\n\n \/\/\n \/\/ Align header skip\n \/\/\n headerSkip = minAlign;\n if (headerSkip < sizeof(tHeader)) {\n headerSkip = (sizeof(tHeader) + alignmentMask) & ~alignmentMask;\n }\n}\n\nTPoolAllocator::~TPoolAllocator()\n{\n if (!global) {\n \/\/\n \/\/ Then we know that this object is not being \n \/\/ allocated after other, globally scoped objects\n \/\/ that depend on it. So we can delete the \"in use\" memory.\n \/\/\n while (inUseList) {\n tHeader* next = inUseList->nextPage;\n inUseList->~tHeader();\n delete [] reinterpret_cast(inUseList);\n inUseList = next;\n }\n }\n\n \/\/\n \/\/ Always delete the free list memory - it can't be being\n \/\/ (correctly) referenced, whether the pool allocator was\n \/\/ global or not. We should not check the guard blocks\n \/\/ here, because we did it already when the block was\n \/\/ placed into the free list.\n \/\/\n while (freeList) {\n tHeader* next = freeList->nextPage;\n delete [] reinterpret_cast(freeList);\n freeList = next;\n }\n}\n\n\/\/ Support MSVC++ 6.0\nconst unsigned char TAllocation::guardBlockBeginVal = 0xfb;\nconst unsigned char TAllocation::guardBlockEndVal = 0xfe;\nconst unsigned char TAllocation::userDataFill = 0xcd;\n\n#ifdef GUARD_BLOCKS\n const size_t TAllocation::guardBlockSize = 16;\n#else\n const size_t TAllocation::guardBlockSize = 0;\n#endif\n\n\/\/\n\/\/ Check a single guard block for damage\n\/\/\nvoid TAllocation::checkGuardBlock(unsigned char* blockMem, unsigned char val, const char* locText) const\n{\n for (size_t x = 0; x < guardBlockSize; x++) {\n if (blockMem[x] != val) {\n char assertMsg[80];\n\n \/\/ We don't print the assert message. It's here just to be helpful.\n sprintf(assertMsg, \"PoolAlloc: Damage %s %u byte allocation at 0x%p\\n\",\n locText, size, data());\n assert(0 && \"PoolAlloc: Damage in guard block\");\n }\n }\n}\n\n\nvoid TPoolAllocator::push()\n{\n tAllocState state = { currentPageOffset, inUseList };\n\n stack.push_back(state);\n \n \/\/\n \/\/ Indicate there is no current page to allocate from.\n \/\/\n currentPageOffset = pageSize;\n}\n\n\/\/\n\/\/ Do a mass-deallocation of all the individual allocations\n\/\/ that have occurred since the last push(), or since the\n\/\/ last pop(), or since the object's creation.\n\/\/\n\/\/ The deallocated pages are saved for future allocations.\n\/\/\nvoid TPoolAllocator::pop()\n{\n if (stack.size() < 1)\n return;\n\n tHeader* page = stack.back().page;\n currentPageOffset = stack.back().offset;\n\n while (inUseList != page) {\n \/\/ invoke destructor to free allocation list\n inUseList->~tHeader();\n \n tHeader* nextInUse = inUseList->nextPage;\n if (inUseList->pageCount > 1)\n delete [] reinterpret_cast(inUseList);\n else {\n inUseList->nextPage = freeList;\n freeList = inUseList;\n }\n inUseList = nextInUse;\n }\n\n stack.pop_back();\n}\n\n\/\/\n\/\/ Do a mass-deallocation of all the individual allocations\n\/\/ that have occurred.\n\/\/\nvoid TPoolAllocator::popAll()\n{\n while (stack.size() > 0)\n pop();\n}\n\nvoid* TPoolAllocator::allocate(size_t numBytes)\n{\n \/\/ If we are using guard blocks, all allocations are bracketed by\n \/\/ them: [guardblock][allocation][guardblock]. numBytes is how\n \/\/ much memory the caller asked for. allocationSize is the total\n \/\/ size including guard blocks. In release build,\n \/\/ guardBlockSize=0 and this all gets optimized away.\n size_t allocationSize = TAllocation::allocationSize(numBytes);\n \n \/\/\n \/\/ Just keep some interesting statistics.\n \/\/\n ++numCalls;\n totalBytes += numBytes;\n\n \/\/\n \/\/ Do the allocation, most likely case first, for efficiency.\n \/\/ This step could be moved to be inline sometime.\n \/\/\n if (currentPageOffset + allocationSize <= pageSize) {\n \/\/\n \/\/ Safe to allocate from currentPageOffset.\n \/\/\n unsigned char* memory = reinterpret_cast(inUseList) + currentPageOffset;\n currentPageOffset += allocationSize;\n currentPageOffset = (currentPageOffset + alignmentMask) & ~alignmentMask;\n\n return initializeAllocation(inUseList, memory, numBytes);\n }\n\n if (allocationSize + headerSkip > pageSize) {\n \/\/\n \/\/ Do a multi-page allocation. Don't mix these with the others.\n \/\/ The OS is efficient and allocating and free-ing multiple pages.\n \/\/\n size_t numBytesToAlloc = allocationSize + headerSkip;\n tHeader* memory = reinterpret_cast(::new char[numBytesToAlloc]);\n if (memory == 0)\n return 0;\n\n \/\/ Use placement-new to initialize header\n new(memory) tHeader(inUseList, (numBytesToAlloc + pageSize - 1) \/ pageSize);\n inUseList = memory;\n\n currentPageOffset = pageSize; \/\/ make next allocation come from a new page\n\n \/\/ No guard blocks for multi-page allocations (yet)\n return reinterpret_cast(reinterpret_cast(memory) + headerSkip);\n }\n\n \/\/\n \/\/ Need a simple page to allocate from.\n \/\/\n tHeader* memory;\n if (freeList) {\n memory = freeList;\n freeList = freeList->nextPage;\n } else {\n memory = reinterpret_cast(::new char[pageSize]);\n if (memory == 0)\n return 0;\n }\n\n \/\/ Use placement-new to initialize header\n new(memory) tHeader(inUseList, 1);\n inUseList = memory;\n \n unsigned char* ret = reinterpret_cast(inUseList) + headerSkip;\n currentPageOffset = (headerSkip + allocationSize + alignmentMask) & ~alignmentMask;\n\n return initializeAllocation(inUseList, ret, numBytes);\n}\n\n\n\/\/\n\/\/ Check all allocations in a list for damage by calling check on each.\n\/\/\nvoid TAllocation::checkAllocList() const\n{\n for (const TAllocation* alloc = this; alloc != 0; alloc = alloc->prevAlloc)\n alloc->check();\n}\n<|endoftext|>"} {"text":"\/************************************************************************\/\n\/* *\/\n\/* Copyright 2002-2003 by Ullrich Koethe *\/\n\/* Cognitive Systems Group, University of Hamburg, Germany *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* You may use, modify, and distribute this software according *\/\n\/* to the terms stated in the LICENSE file included in *\/\n\/* the VIGRA distribution. *\/\n\/* *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/kogs-www.informatik.uni-hamburg.de\/~koethe\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* koethe@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR *\/\n\/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED *\/\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *\/\n\/* *\/\n\/************************************************************************\/\n\n#ifndef VIGRA_ARRAY_VECTOR_HXX\n#define VIGRA_ARRAY_VECTOR_HXX\n\n#include \n#include \n#include \n\nnamespace vigra\n{\n\ntemplate >\nclass ArrayVector\n{\n typedef ArrayVector this_type;\n\npublic:\n typedef T value_type;\n typedef value_type & reference;\n typedef value_type const & const_reference;\n typedef value_type * pointer;\n typedef value_type const * const_pointer;\n typedef value_type * iterator;\n typedef value_type const * const_iterator;\n typedef unsigned int size_type;\n typedef int difference_type;\n typedef Alloc allocator_type;\n\npublic:\n ArrayVector();\n\n explicit ArrayVector(Alloc const & alloc);\n\n explicit ArrayVector( size_type size, Alloc const & alloc = Alloc());\n\n ArrayVector( size_type size, value_type const & initial, Alloc const & alloc = Alloc());\n\n ArrayVector( this_type const & rhs );\n\n template \n ArrayVector(InputIterator i, InputIterator end);\n\n template \n ArrayVector(InputIterator i, InputIterator end, Alloc const & alloc);\n\n this_type & operator=( this_type const & rhs );\n\n ~ArrayVector();\n\n inline const_pointer data() const\n {\n return data_;\n }\n\n inline pointer data()\n {\n return data_;\n }\n\n inline const_iterator begin() const\n {\n return data();\n }\n\n inline iterator begin()\n {\n return data();\n }\n\n inline const_iterator end() const\n {\n return data() + size();\n }\n\n inline iterator end()\n {\n return data() + size();\n }\n\n reference front()\n {\n return *data_;\n }\n\n const_reference front() const\n {\n return *data_;\n }\n\n reference back()\n {\n return data_[size_-1];\n }\n\n const_reference back() const\n {\n return data_[size_-1];\n }\n\n reference operator[]( size_type i )\n {\n return data()[i];\n }\n\n const_reference operator[]( size_type i ) const\n {\n return data()[i];\n }\n\n void pop_back();\n\n void push_back( value_type const & t );\n\n iterator insert(iterator p, value_type const & v);\n\n iterator insert(iterator p, size_type n, value_type const & v);\n\n template \n iterator insert(iterator p, InputIterator i, InputIterator iend);\n\n iterator erase(iterator p);\n\n iterator erase(iterator p, iterator q);\n\n void clear();\n\n void reserve( size_type new_capacity );\n\n void reserve();\n\n void resize( size_type new_size, value_type const & initial );\n\n void resize( size_type new_size )\n {\n resize(new_size, value_type());\n }\n\n bool empty() const\n {\n return size_ == 0;\n }\n\n size_type size() const\n {\n return size_;\n }\n\n size_type capacity() const\n {\n return capacity_;\n }\n\n void swap(this_type & rhs);\n\n private:\n\n void deallocate(pointer data, size_type size);\n\n pointer reserve_raw(size_type capacity);\n\n Alloc alloc_;\n size_type size_, capacity_;\n pointer data_;\n};\n\ntemplate \nArrayVector::ArrayVector()\n: alloc_(Alloc()),\n size_(0),\n capacity_(5),\n data_(reserve_raw(5))\n{}\n\ntemplate \nArrayVector::ArrayVector(Alloc const & alloc)\n: alloc_(alloc),\n size_(0),\n capacity_(5),\n data_(reserve_raw(5))\n{}\n\ntemplate \nArrayVector::ArrayVector( size_type size, Alloc const & alloc)\n: alloc_(alloc),\n size_(size),\n capacity_(size),\n data_(reserve_raw(size))\n{\n if(size_ > 0)\n std::uninitialized_fill(data_, data_+size_, value_type());\n}\n\ntemplate \nArrayVector::ArrayVector( size_type size, \n value_type const & initial, Alloc const & alloc)\n: alloc_(alloc),\n size_(size),\n capacity_(size),\n data_(reserve_raw(size))\n{\n if(size_ > 0)\n std::uninitialized_fill(data_, data_+size_, initial);\n}\n\ntemplate \nArrayVector::ArrayVector( this_type const & rhs )\n: alloc_(rhs.alloc_),\n size_(rhs.size_),\n capacity_(rhs.capacity_),\n data_(reserve_raw(rhs.capacity_))\n{\n if(size_ > 0)\n std::uninitialized_copy(rhs.data_, rhs.data_+size_, data_);\n}\n\ntemplate \ntemplate \nArrayVector::ArrayVector(InputIterator i, InputIterator end)\n: alloc_(),\n size_(std::distance(i, end)),\n capacity_(size_),\n data_(reserve_raw(size_))\n{\n std::uninitialized_copy(i, end, data_);\n}\n\ntemplate \ntemplate \nArrayVector::ArrayVector(InputIterator i, InputIterator end, Alloc const & alloc)\n: alloc_(alloc),\n size_(std::distance(i, end)),\n capacity_(size_),\n data_(reserve_raw(size_))\n{\n std::uninitialized_copy(i, end, data_);\n}\n\n\ntemplate \nArrayVector & ArrayVector::operator=( this_type const & rhs )\n{\n if(this == &rhs)\n return *this;\n ArrayVector new_vector(rhs);\n swap(new_vector);\n return *this;\n}\n\ntemplate \nArrayVector::~ArrayVector()\n{\n deallocate(data_, size_);\n}\n\ntemplate \nvoid ArrayVector::pop_back()\n{\n --size_;\n alloc_.destroy(data_ + size_);\n}\n\ntemplate \nvoid ArrayVector::push_back( value_type const & t )\n{\n reserve();\n alloc_.construct(data_ + size_, t);\n ++size_;\n}\n\ntemplate \nvoid ArrayVector::clear()\n{\n detail::destroy_n(data_, size_);\n size_ = 0;\n}\n\ntemplate \ntypename ArrayVector::iterator\nArrayVector::insert(iterator p, value_type const & v)\n{\n difference_type pos = p - begin();\n if(p == end())\n {\n push_back(v);\n p = begin() + pos;\n }\n else\n {\n push_back(back());\n p = begin() + pos;\n std::copy_backward(p, end() - 2, end() - 1);\n *p = v;\n }\n return p;\n}\n\ntemplate \ntypename ArrayVector::iterator\nArrayVector::insert(iterator p, size_type n, value_type const & v)\n{\n difference_type pos = p - begin();\n size_type new_size = size() + n;\n if(new_size >= capacity_)\n {\n pointer new_data = reserve_raw(new_size);\n std::uninitialized_copy(begin(), p, new_data);\n std::uninitialized_fill(new_data + pos, new_data + pos + n, v);\n std::uninitialized_copy(p, end(), new_data + pos + n);\n deallocate(data_, size_);\n capacity_ = new_size;\n data_ = new_data;\n }\n else if(pos + n >= size_)\n {\n size_type diff = pos + n - size_;\n std::uninitialized_copy(p, end(), end() + diff);\n std::uninitialized_fill(end(), end() + diff, v);\n std::fill(p, end(), v);\n }\n else\n {\n size_type diff = size_ - (pos + n);\n std::uninitialized_copy(end() - n, end(), end());\n std::copy_backward(p, p + diff, end());\n std::fill(p, p + n, v);\n }\n size_ = new_size;\n return begin() + pos;\n}\n\ntemplate \ntemplate \ntypename ArrayVector::iterator\nArrayVector::insert(iterator p, InputIterator i, InputIterator iend)\n{\n difference_type n = iend - i;\n difference_type pos = p - begin();\n size_type new_size = size() + n;\n if(new_size >= capacity_)\n {\n pointer new_data = reserve_raw(new_size);\n std::uninitialized_copy(begin(), p, new_data);\n std::uninitialized_copy(i, iend, new_data + pos);\n std::uninitialized_copy(p, end(), new_data + pos + n);\n std::deallocate(data_, size_);\n capacity_ = new_size;\n data_ = new_data;\n }\n else if(pos + n >= size_)\n {\n size_type diff = pos + n - size_;\n std::uninitialized_copy(p, end(), end() + diff);\n std::uninitialized_copy(iend - diff, iend, end());\n std::copy(i, iend - diff, p);\n }\n else\n {\n size_type diff = size_ - (pos + n);\n std::uninitialized_copy(end() - n, end(), end());\n std::copy_backward(p, p + diff, end());\n std::copy(i, iend, p);\n }\n size_ = new_size;\n return begin() + pos;\n}\n\ntemplate \ntypename ArrayVector::iterator\nArrayVector::erase(iterator p)\n{\n std::copy(p+1, end(), p);\n pop_back();\n return p;\n}\n\ntemplate \ntypename ArrayVector::iterator\nArrayVector::erase(iterator p, iterator q)\n{\n std::copy(q, end(), p);\n size_type eraseCount = q - p;\n detail::destroy_n(end() - eraseCount, eraseCount);\n size_ -= eraseCount;\n return p;\n}\n\ntemplate \nvoid ArrayVector::reserve( size_type new_capacity )\n{\n if(new_capacity <= capacity_)\n return;\n pointer new_data = reserve_raw(new_capacity);\n if(size_ > 0)\n std::uninitialized_copy(data_, data_+size_, new_data);\n deallocate(data_, size_);\n data_ = new_data;\n capacity_ = new_capacity;\n}\n\ntemplate \nvoid ArrayVector::reserve()\n{\n if(size_ == capacity_)\n reserve(2*capacity_);\n}\n\ntemplate \nvoid ArrayVector::resize( size_type new_size, value_type const & initial)\n{\n if(new_size < size_)\n erase(begin() + new_size, end());\n else if(size_ < new_size)\n {\n insert(end(), new_size - size(), initial);\n }\n}\n\ntemplate \nvoid ArrayVector::swap(this_type & rhs)\n{\n std::swap(size_, rhs.size_);\n std::swap(capacity_, rhs.capacity_);\n std::swap(data_, rhs.data_);\n}\n\ntemplate \nvoid ArrayVector::deallocate(pointer data, size_type size)\n{\n if(data)\n {\n detail::destroy_n(data, size);\n alloc_.deallocate(data, size);\n }\n}\n\ntemplate \ntypename ArrayVector::pointer\nArrayVector::reserve_raw(size_type capacity)\n{\n pointer data = 0;\n if(capacity)\n {\n data = alloc_.allocate(capacity);\n }\n return data;\n}\n\n} \/\/ namespace vigra\n\n\n#endif \/* VIGRA_ARRAY_VECTOR_HXX *\/\nadded reverse iterator interface\/************************************************************************\/\n\/* *\/\n\/* Copyright 2002-2003 by Ullrich Koethe *\/\n\/* Cognitive Systems Group, University of Hamburg, Germany *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* You may use, modify, and distribute this software according *\/\n\/* to the terms stated in the LICENSE file included in *\/\n\/* the VIGRA distribution. *\/\n\/* *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/kogs-www.informatik.uni-hamburg.de\/~koethe\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* koethe@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR *\/\n\/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED *\/\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *\/\n\/* *\/\n\/************************************************************************\/\n\n#ifndef VIGRA_ARRAY_VECTOR_HXX\n#define VIGRA_ARRAY_VECTOR_HXX\n\n#include \n#include \n#include \n\nnamespace vigra\n{\n\ntemplate >\nclass ArrayVector\n{\n typedef ArrayVector this_type;\n\npublic:\n typedef T value_type;\n typedef value_type & reference;\n typedef value_type const & const_reference;\n typedef value_type * pointer;\n typedef value_type const * const_pointer;\n typedef value_type * iterator;\n typedef value_type const * const_iterator;\n typedef unsigned int size_type;\n typedef int difference_type;\n typedef Alloc allocator_type;\n typedef std::reverse_iterator reverse_iterator;\n typedef std::reverse_iterator const_reverse_iterator;\n\npublic:\n ArrayVector();\n\n explicit ArrayVector(Alloc const & alloc);\n\n explicit ArrayVector( size_type size, Alloc const & alloc = Alloc());\n\n ArrayVector( size_type size, value_type const & initial, Alloc const & alloc = Alloc());\n\n ArrayVector( this_type const & rhs );\n\n template \n ArrayVector(InputIterator i, InputIterator end);\n\n template \n ArrayVector(InputIterator i, InputIterator end, Alloc const & alloc);\n\n this_type & operator=( this_type const & rhs );\n\n ~ArrayVector();\n\n inline const_pointer data() const\n {\n return data_;\n }\n\n inline pointer data()\n {\n return data_;\n }\n\n inline const_iterator begin() const\n {\n return data();\n }\n\n inline iterator begin()\n {\n return data();\n }\n\n inline const_iterator end() const\n {\n return data() + size();\n }\n\n inline iterator end()\n {\n return data() + size();\n }\n\n inline reverse_iterator rbegin()\r\n {\r\n return (reverse_iterator(end()));\r\n }\r\n\r\n inline const_reverse_iterator rbegin() const\r\n {\r\n return (const_reverse_iterator(end()));\r\n }\r\n\r\n inline reverse_iterator rend()\r\n { \r\n return (reverse_iterator(begin()));\r\n }\r\n\r\n inline const_reverse_iterator rend() const\r\n { \r\n return (const_reverse_iterator(begin()));\r\n }\r\n\r\n reference front()\n {\n return *data_;\n }\n\n const_reference front() const\n {\n return *data_;\n }\n\n reference back()\n {\n return data_[size_-1];\n }\n\n const_reference back() const\n {\n return data_[size_-1];\n }\n\n reference operator[]( size_type i )\n {\n return data()[i];\n }\n\n const_reference operator[]( size_type i ) const\n {\n return data()[i];\n }\n\n void pop_back();\n\n void push_back( value_type const & t );\n\n iterator insert(iterator p, value_type const & v);\n\n iterator insert(iterator p, size_type n, value_type const & v);\n\n template \n iterator insert(iterator p, InputIterator i, InputIterator iend);\n\n iterator erase(iterator p);\n\n iterator erase(iterator p, iterator q);\n\n void clear();\n\n void reserve( size_type new_capacity );\n\n void reserve();\n\n void resize( size_type new_size, value_type const & initial );\n\n void resize( size_type new_size )\n {\n resize(new_size, value_type());\n }\n\n bool empty() const\n {\n return size_ == 0;\n }\n\n size_type size() const\n {\n return size_;\n }\n\n size_type capacity() const\n {\n return capacity_;\n }\n\n void swap(this_type & rhs);\n\n private:\n\n void deallocate(pointer data, size_type size);\n\n pointer reserve_raw(size_type capacity);\n\n Alloc alloc_;\n size_type size_, capacity_;\n pointer data_;\n};\n\ntemplate \nArrayVector::ArrayVector()\n: alloc_(Alloc()),\n size_(0),\n capacity_(5),\n data_(reserve_raw(5))\n{}\n\ntemplate \nArrayVector::ArrayVector(Alloc const & alloc)\n: alloc_(alloc),\n size_(0),\n capacity_(5),\n data_(reserve_raw(5))\n{}\n\ntemplate \nArrayVector::ArrayVector( size_type size, Alloc const & alloc)\n: alloc_(alloc),\n size_(size),\n capacity_(size),\n data_(reserve_raw(size))\n{\n if(size_ > 0)\n std::uninitialized_fill(data_, data_+size_, value_type());\n}\n\ntemplate \nArrayVector::ArrayVector( size_type size, \n value_type const & initial, Alloc const & alloc)\n: alloc_(alloc),\n size_(size),\n capacity_(size),\n data_(reserve_raw(size))\n{\n if(size_ > 0)\n std::uninitialized_fill(data_, data_+size_, initial);\n}\n\ntemplate \nArrayVector::ArrayVector( this_type const & rhs )\n: alloc_(rhs.alloc_),\n size_(rhs.size_),\n capacity_(rhs.capacity_),\n data_(reserve_raw(rhs.capacity_))\n{\n if(size_ > 0)\n std::uninitialized_copy(rhs.data_, rhs.data_+size_, data_);\n}\n\ntemplate \ntemplate \nArrayVector::ArrayVector(InputIterator i, InputIterator end)\n: alloc_(),\n size_(std::distance(i, end)),\n capacity_(size_),\n data_(reserve_raw(size_))\n{\n std::uninitialized_copy(i, end, data_);\n}\n\ntemplate \ntemplate \nArrayVector::ArrayVector(InputIterator i, InputIterator end, Alloc const & alloc)\n: alloc_(alloc),\n size_(std::distance(i, end)),\n capacity_(size_),\n data_(reserve_raw(size_))\n{\n std::uninitialized_copy(i, end, data_);\n}\n\n\ntemplate \nArrayVector & ArrayVector::operator=( this_type const & rhs )\n{\n if(this == &rhs)\n return *this;\n ArrayVector new_vector(rhs);\n swap(new_vector);\n return *this;\n}\n\ntemplate \nArrayVector::~ArrayVector()\n{\n deallocate(data_, size_);\n}\n\ntemplate \nvoid ArrayVector::pop_back()\n{\n --size_;\n alloc_.destroy(data_ + size_);\n}\n\ntemplate \nvoid ArrayVector::push_back( value_type const & t )\n{\n reserve();\n alloc_.construct(data_ + size_, t);\n ++size_;\n}\n\ntemplate \nvoid ArrayVector::clear()\n{\n detail::destroy_n(data_, size_);\n size_ = 0;\n}\n\ntemplate \ntypename ArrayVector::iterator\nArrayVector::insert(iterator p, value_type const & v)\n{\n difference_type pos = p - begin();\n if(p == end())\n {\n push_back(v);\n p = begin() + pos;\n }\n else\n {\n push_back(back());\n p = begin() + pos;\n std::copy_backward(p, end() - 2, end() - 1);\n *p = v;\n }\n return p;\n}\n\ntemplate \ntypename ArrayVector::iterator\nArrayVector::insert(iterator p, size_type n, value_type const & v)\n{\n difference_type pos = p - begin();\n size_type new_size = size() + n;\n if(new_size >= capacity_)\n {\n pointer new_data = reserve_raw(new_size);\n std::uninitialized_copy(begin(), p, new_data);\n std::uninitialized_fill(new_data + pos, new_data + pos + n, v);\n std::uninitialized_copy(p, end(), new_data + pos + n);\n deallocate(data_, size_);\n capacity_ = new_size;\n data_ = new_data;\n }\n else if(pos + n >= size_)\n {\n size_type diff = pos + n - size_;\n std::uninitialized_copy(p, end(), end() + diff);\n std::uninitialized_fill(end(), end() + diff, v);\n std::fill(p, end(), v);\n }\n else\n {\n size_type diff = size_ - (pos + n);\n std::uninitialized_copy(end() - n, end(), end());\n std::copy_backward(p, p + diff, end());\n std::fill(p, p + n, v);\n }\n size_ = new_size;\n return begin() + pos;\n}\n\ntemplate \ntemplate \ntypename ArrayVector::iterator\nArrayVector::insert(iterator p, InputIterator i, InputIterator iend)\n{\n difference_type n = iend - i;\n difference_type pos = p - begin();\n size_type new_size = size() + n;\n if(new_size >= capacity_)\n {\n pointer new_data = reserve_raw(new_size);\n std::uninitialized_copy(begin(), p, new_data);\n std::uninitialized_copy(i, iend, new_data + pos);\n std::uninitialized_copy(p, end(), new_data + pos + n);\n std::deallocate(data_, size_);\n capacity_ = new_size;\n data_ = new_data;\n }\n else if(pos + n >= size_)\n {\n size_type diff = pos + n - size_;\n std::uninitialized_copy(p, end(), end() + diff);\n std::uninitialized_copy(iend - diff, iend, end());\n std::copy(i, iend - diff, p);\n }\n else\n {\n size_type diff = size_ - (pos + n);\n std::uninitialized_copy(end() - n, end(), end());\n std::copy_backward(p, p + diff, end());\n std::copy(i, iend, p);\n }\n size_ = new_size;\n return begin() + pos;\n}\n\ntemplate \ntypename ArrayVector::iterator\nArrayVector::erase(iterator p)\n{\n std::copy(p+1, end(), p);\n pop_back();\n return p;\n}\n\ntemplate \ntypename ArrayVector::iterator\nArrayVector::erase(iterator p, iterator q)\n{\n std::copy(q, end(), p);\n size_type eraseCount = q - p;\n detail::destroy_n(end() - eraseCount, eraseCount);\n size_ -= eraseCount;\n return p;\n}\n\ntemplate \nvoid ArrayVector::reserve( size_type new_capacity )\n{\n if(new_capacity <= capacity_)\n return;\n pointer new_data = reserve_raw(new_capacity);\n if(size_ > 0)\n std::uninitialized_copy(data_, data_+size_, new_data);\n deallocate(data_, size_);\n data_ = new_data;\n capacity_ = new_capacity;\n}\n\ntemplate \nvoid ArrayVector::reserve()\n{\n if(size_ == capacity_)\n reserve(2*capacity_);\n}\n\ntemplate \nvoid ArrayVector::resize( size_type new_size, value_type const & initial)\n{\n if(new_size < size_)\n erase(begin() + new_size, end());\n else if(size_ < new_size)\n {\n insert(end(), new_size - size(), initial);\n }\n}\n\ntemplate \nvoid ArrayVector::swap(this_type & rhs)\n{\n std::swap(size_, rhs.size_);\n std::swap(capacity_, rhs.capacity_);\n std::swap(data_, rhs.data_);\n}\n\ntemplate \nvoid ArrayVector::deallocate(pointer data, size_type size)\n{\n if(data)\n {\n detail::destroy_n(data, size);\n alloc_.deallocate(data, size);\n }\n}\n\ntemplate \ntypename ArrayVector::pointer\nArrayVector::reserve_raw(size_type capacity)\n{\n pointer data = 0;\n if(capacity)\n {\n data = alloc_.allocate(capacity);\n }\n return data;\n}\n\n} \/\/ namespace vigra\n\n\n#endif \/* VIGRA_ARRAY_VECTOR_HXX *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"listize.hpp\"\n#include \"to_string.hpp\"\n#include \"context.hpp\"\n#include \"backtrace.hpp\"\n#include \"error_handling.hpp\"\n\nnamespace Sass {\n\n Listize::Listize(Context& ctx)\n : ctx(ctx)\n { }\n\n Expression* Listize::operator()(Selector_List* sel)\n {\n List* l = SASS_MEMORY_NEW(ctx.mem, List, sel->pstate(), sel->length(), SASS_COMMA);\n for (size_t i = 0, L = sel->length(); i < L; ++i) {\n if (!(*sel)[i]) continue;\n *l << (*sel)[i]->perform(this);\n }\n return l;\n }\n\n Expression* Listize::operator()(Compound_Selector* sel)\n {\n To_String to_string;\n std::string str;\n for (size_t i = 0, L = sel->length(); i < L; ++i) {\n Expression* e = (*sel)[i]->perform(this);\n if (e) str += e->perform(&to_string);\n }\n return SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), str);\n }\n\n Expression* Listize::operator()(Complex_Selector* sel)\n {\n List* l = SASS_MEMORY_NEW(ctx.mem, List, sel->pstate(), 2);\n\n Compound_Selector* head = sel->head();\n if (head && !head->is_empty_reference())\n {\n Expression* hh = head->perform(this);\n if (hh) *l << hh;\n }\n\n To_String to_string;\n std::string reference = ! sel->reference() ? \"\"\n : sel->reference()->perform(&to_string);\n switch(sel->combinator())\n {\n case Complex_Selector::PARENT_OF:\n *l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), \">\");\n break;\n case Complex_Selector::ADJACENT_TO:\n *l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), \"+\");\n break;\n case Complex_Selector::REFERENCE:\n *l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), \"\/\" + reference + \"\/\");\n break;\n case Complex_Selector::PRECEDES:\n *l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), \"~\");\n break;\n case Complex_Selector::ANCESTOR_OF:\n break;\n }\n\n Complex_Selector* tail = sel->tail();\n if (tail)\n {\n Expression* tt = tail->perform(this);\n if (tt && tt->concrete_type() == Expression::LIST)\n { *l += static_cast(tt); }\n else if (tt) *l << static_cast(tt);\n }\n if (l->length() == 0) return 0;\n return l;\n }\n\n Expression* Listize::fallback_impl(AST_Node* n)\n {\n return dynamic_cast(n);\n }\n\n}\nselector-unify should return null instead of an empty list#include \n#include \n#include \n\n#include \"listize.hpp\"\n#include \"to_string.hpp\"\n#include \"context.hpp\"\n#include \"backtrace.hpp\"\n#include \"error_handling.hpp\"\n\nnamespace Sass {\n\n Listize::Listize(Context& ctx)\n : ctx(ctx)\n { }\n\n Expression* Listize::operator()(Selector_List* sel)\n {\n List* l = SASS_MEMORY_NEW(ctx.mem, List, sel->pstate(), sel->length(), SASS_COMMA);\n for (size_t i = 0, L = sel->length(); i < L; ++i) {\n if (!(*sel)[i]) continue;\n *l << (*sel)[i]->perform(this);\n }\n if (l->length()) return l;\n return SASS_MEMORY_NEW(ctx.mem, Null, l->pstate());\n }\n\n Expression* Listize::operator()(Compound_Selector* sel)\n {\n To_String to_string;\n std::string str;\n for (size_t i = 0, L = sel->length(); i < L; ++i) {\n Expression* e = (*sel)[i]->perform(this);\n if (e) str += e->perform(&to_string);\n }\n return SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), str);\n }\n\n Expression* Listize::operator()(Complex_Selector* sel)\n {\n List* l = SASS_MEMORY_NEW(ctx.mem, List, sel->pstate(), 2);\n\n Compound_Selector* head = sel->head();\n if (head && !head->is_empty_reference())\n {\n Expression* hh = head->perform(this);\n if (hh) *l << hh;\n }\n\n To_String to_string;\n std::string reference = ! sel->reference() ? \"\"\n : sel->reference()->perform(&to_string);\n switch(sel->combinator())\n {\n case Complex_Selector::PARENT_OF:\n *l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), \">\");\n break;\n case Complex_Selector::ADJACENT_TO:\n *l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), \"+\");\n break;\n case Complex_Selector::REFERENCE:\n *l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), \"\/\" + reference + \"\/\");\n break;\n case Complex_Selector::PRECEDES:\n *l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, sel->pstate(), \"~\");\n break;\n case Complex_Selector::ANCESTOR_OF:\n break;\n }\n\n Complex_Selector* tail = sel->tail();\n if (tail)\n {\n Expression* tt = tail->perform(this);\n if (tt && tt->concrete_type() == Expression::LIST)\n { *l += static_cast(tt); }\n else if (tt) *l << static_cast(tt);\n }\n if (l->length() == 0) return 0;\n return l;\n }\n\n Expression* Listize::fallback_impl(AST_Node* n)\n {\n return dynamic_cast(n);\n }\n\n}\n<|endoftext|>"} {"text":"\/* This file is part of Zanshin Todo.\n\n Copyright 2011 Kevin Ottens \n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"zanshinrunner.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nZanshinRunner::ZanshinRunner(QObject *parent, const QVariantList &args)\n : Plasma::AbstractRunner(parent, args)\n{\n setObjectName(QLatin1String(\"Zanshin\"));\n setIgnoredTypes(Plasma::RunnerContext::Directory | Plasma::RunnerContext::File |\n Plasma::RunnerContext::NetworkLocation | Plasma::RunnerContext::Help);\n\n connect(this, SIGNAL(prepare()), this, SLOT(prep()));\n connect(this, SIGNAL(teardown()), this, SLOT(down()));\n}\n\nZanshinRunner::~ZanshinRunner()\n{\n}\n\nvoid ZanshinRunner::match(Plasma::RunnerContext &context)\n{\n const QString command = context.query().trimmed();\n\n if (!command.startsWith(\"todo:\", Qt::CaseInsensitive)) {\n return;\n }\n\n const QString summary = command.mid(5).trimmed();\n\n if (summary.isEmpty()) {\n return;\n }\n\n QList matches;\n\n Plasma::QueryMatch match(this);\n match.setData(summary);\n match.setType(Plasma::QueryMatch::ExactMatch);\n match.setIcon(KIcon(\"office-calendar\"));\n match.setText(i18n(\"Add \\\"%1\\\" to your todo list\", summary));\n match.setRelevance(1.0);\n\n matches << match;\n context.addMatches(context.query(), matches);\n}\n\nvoid ZanshinRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)\n{\n Q_UNUSED(context)\n\n Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(Akonadi::Collection::root(),\n Akonadi::CollectionFetchJob::Recursive);\n job->fetchScope().setContentMimeTypes(QStringList() << \"application\/x-vnd.akonadi.calendar.todo\");\n job->exec();\n\n Akonadi::Collection::List cols = job->collections();\n\n if (cols.isEmpty()) {\n return;\n }\n\n Akonadi::Collection collection;\n\n KConfig zanshin(\"zanshinrc\");\n KConfigGroup config(&zanshin, \"General\");\n\n qint64 defaultCollectionId = config.readEntry(\"defaultCollection\", -1);\n\n if (defaultCollectionId > 0) {\n foreach (Akonadi::Collection col, cols) {\n if (col.id() == defaultCollectionId) {\n collection = col;\n break;\n }\n }\n }\n\n if (!collection.isValid()) {\n collection = cols.first();\n }\n\n KCalCore::Todo::Ptr todo(new KCalCore::Todo);\n todo->setSummary(match.data().toString());\n\n Akonadi::Item item;\n item.setMimeType(\"application\/x-vnd.akonadi.calendar.todo\");\n item.setPayload(todo);\n\n new Akonadi::ItemCreateJob(item, collection);\n}\n\n#include \"zanshinrunner.moc\"\nremove some boilerplate\/* This file is part of Zanshin Todo.\n\n Copyright 2011 Kevin Ottens \n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"zanshinrunner.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nZanshinRunner::ZanshinRunner(QObject *parent, const QVariantList &args)\n : Plasma::AbstractRunner(parent, args)\n{\n setObjectName(QLatin1String(\"Zanshin\"));\n setIgnoredTypes(Plasma::RunnerContext::Directory | Plasma::RunnerContext::File |\n Plasma::RunnerContext::NetworkLocation | Plasma::RunnerContext::Help);\n}\n\nZanshinRunner::~ZanshinRunner()\n{\n}\n\nvoid ZanshinRunner::match(Plasma::RunnerContext &context)\n{\n const QString command = context.query().trimmed();\n\n if (!command.startsWith(\"todo:\", Qt::CaseInsensitive)) {\n return;\n }\n\n const QString summary = command.mid(5).trimmed();\n\n if (summary.isEmpty()) {\n return;\n }\n\n QList matches;\n\n Plasma::QueryMatch match(this);\n match.setData(summary);\n match.setType(Plasma::QueryMatch::ExactMatch);\n match.setIcon(KIcon(\"office-calendar\"));\n match.setText(i18n(\"Add \\\"%1\\\" to your todo list\", summary));\n match.setRelevance(1.0);\n\n matches << match;\n context.addMatches(context.query(), matches);\n}\n\nvoid ZanshinRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)\n{\n Q_UNUSED(context)\n\n Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(Akonadi::Collection::root(),\n Akonadi::CollectionFetchJob::Recursive);\n job->fetchScope().setContentMimeTypes(QStringList() << \"application\/x-vnd.akonadi.calendar.todo\");\n job->exec();\n\n Akonadi::Collection::List cols = job->collections();\n\n if (cols.isEmpty()) {\n return;\n }\n\n Akonadi::Collection collection;\n\n KConfig zanshin(\"zanshinrc\");\n KConfigGroup config(&zanshin, \"General\");\n\n qint64 defaultCollectionId = config.readEntry(\"defaultCollection\", -1);\n\n if (defaultCollectionId > 0) {\n foreach (Akonadi::Collection col, cols) {\n if (col.id() == defaultCollectionId) {\n collection = col;\n break;\n }\n }\n }\n\n if (!collection.isValid()) {\n collection = cols.first();\n }\n\n KCalCore::Todo::Ptr todo(new KCalCore::Todo);\n todo->setSummary(match.data().toString());\n\n Akonadi::Item item;\n item.setMimeType(\"application\/x-vnd.akonadi.calendar.todo\");\n item.setPayload(todo);\n\n new Akonadi::ItemCreateJob(item, collection);\n}\n\n#include \"zanshinrunner.moc\"\n<|endoftext|>"} {"text":"\/** \\file\n * Implements a load recorder, useful for simulating loads to test\n * CPU clock daemons and settings.\n *\/\n\n#include \"Options.hpp\"\n\n#include \"types.hpp\"\n#include \"constants.hpp\"\n#include \"errors.hpp\"\n#include \"utility.hpp\"\n#include \"clas.hpp\"\n#include \"version.hpp\"\n\n#include \"sys\/sysctl.hpp\"\n\n#include \/* std::cout, std::cerr *\/\n#include \/* std::ofstream *\/\n#include \/* std::chrono::steady_clock::now() *\/\n#include \/* std::this_thread::sleep_until() *\/\n#include \/* std::unique_ptr *\/\n\n#include \/* CPUSTATES *\/\n\n\/**\n * File local scope.\n *\/\nnamespace {\n\nusing nih::Option;\nusing nih::make_Options;\n\nusing constants::ACLINE;\nusing constants::FREQ;\nusing constants::FREQ_LEVELS;\nusing constants::CP_TIMES;\n\nusing types::ms;\nusing types::coreid_t;\nusing types::cptime_t;\nusing types::mhz_t;\n\nusing errors::Exit;\nusing errors::Exception;\nusing errors::fail;\n\nusing utility::to_value;\nusing utility::sprintf_safe;\nusing namespace utility::literals;\n\nusing clas::ival;\n\nusing sys::ctl::make_Sysctl;\nusing sys::ctl::make_Once;\n\nusing version::LOADREC_FEATURES;\nusing version::flag_t;\nusing namespace version::literals;\n\n\/**\n * The set of supported features.\n *\n * This value is stored in load recordings to allow loadplay to correctly\n * interpret the data.\n *\/\nconstexpr flag_t const FEATURES{\n\t0_FREQ_TRACKING\n};\n\n\/**\n * The global state.\n *\/\nstruct {\n\tbool verbose{false}; \/**< Verbosity flag. *\/\n\tms duration{30000}; \/**< Recording duration in ms. *\/\n\tms interval{25}; \/**< Recording sample interval in ms. *\/\n\n\t\/**\n\t * The output file stream to use if an outfilename is provided\n\t * on the CLI.\n\t *\/\n\tstd::ofstream outfile{};\n\n\t\/**\n\t * A pointer to the stream to use for output, either std::cout\n\t * or outfile.\n\t *\/\n\tstd::ostream * out = &std::cout;\n\n\t\/**\n\t * The user provided output file name.\n\t *\/\n\tchar const * outfilename{nullptr};\n\n\t\/**\n\t * The number of CPU cores\/threads.\n\t *\/\n\tsys::ctl::SysctlOnce const ncpu{1U, {CTL_HW, HW_NCPU}};\n} g;\n\n\/**\n * An enum for command line parsing.\n *\/\nenum class OE {\n\tUSAGE, \/**< Print help *\/\n\tIVAL_DURATION, \/**< Set the duration of the recording *\/\n\tIVAL_POLL, \/**< Set polling interval *\/\n\tFILE_OUTPUT, \/**< Set output file *\/\n\tFILE_PID, \/**< Set PID file *\/\n\tFLAG_VERBOSE, \/**< Verbose output on stderr *\/\n\tOPT_UNKNOWN, \/**< Obligatory *\/\n\tOPT_NOOPT, \/**< Obligatory *\/\n\tOPT_DASH, \/**< Obligatory *\/\n\tOPT_LDASH, \/**< Obligatory *\/\n\tOPT_DONE \/**< Obligatory *\/\n};\n\n\/**\n * The short usage string.\n *\/\nchar const * const USAGE = \"[-hv] [-d ival] [-p ival] [-o file]\";\n\n\/**\n * Definitions of command line options.\n *\/\nOption const OPTIONS[]{\n\t{OE::USAGE, 'h', \"help\", \"\", \"Show usage and exit\"},\n\t{OE::FLAG_VERBOSE, 'v', \"verbose\", \"\", \"Be verbose\"},\n\t{OE::IVAL_DURATION, 'd', \"duration\", \"ival\", \"The duration of the recording\"},\n\t{OE::IVAL_POLL, 'p', \"poll\", \"ival\", \"The polling interval\"},\n\t{OE::FILE_OUTPUT, 'o', \"output\", \"file\", \"Output to file\"},\n\t{OE::FILE_PID, 'P', \"pid\", \"file\", \"Ignored\"},\n};\n\n\/**\n * Outputs the given message on stderr if g.verbose is set.\n *\n * @param msg\n *\tThe message to output\n *\/\ninline void verbose(std::string const & msg) {\n\tif (g.verbose) {\n\t\tstd::cerr << \"loadrec: \" << msg << '\\n';\n\t}\n}\n\n\/**\n * Set up output to the given file.\n *\/\nvoid init() {\n\tif (g.outfilename) {\n\t\tg.outfile.open(g.outfilename);\n\t\tif (!g.outfile.good()) {\n\t\t\tfail(Exit::EWOPEN, errno,\n\t\t\t \"could not open file for writing: \"_s + g.outfilename);\n\t\t}\n\t\tg.out = &g.outfile;\n\t}\n}\n\n\/**\n * Parse command line arguments.\n *\n * @param argc,argv\n *\tThe command line arguments\n *\/\nvoid read_args(int const argc, char const * const argv[]) {\n\tauto getopt = make_Options(argc, argv, USAGE, OPTIONS);\n\n\twhile (true) switch (getopt()) {\n\tcase OE::USAGE:\n\t\tstd::cerr << getopt.usage();\n\t\tthrow Exception{Exit::OK, 0, \"\"};\n\tcase OE::FLAG_VERBOSE:\n\t\tg.verbose = true;\n\t\tbreak;\n\tcase OE::IVAL_DURATION:\n\t\tg.duration = ival(getopt[1]);\n\t\tbreak;\n\tcase OE::IVAL_POLL:\n\t\tg.interval = ival(getopt[1]);\n\t\tbreak;\n\tcase OE::FILE_OUTPUT:\n\t\tg.outfilename = getopt[1];\n\t\tbreak;\n\tcase OE::FILE_PID:\n\t\tbreak;\n\tcase OE::OPT_UNKNOWN:\n\tcase OE::OPT_NOOPT:\n\tcase OE::OPT_DASH:\n\tcase OE::OPT_LDASH:\n\t\tfail(Exit::ECLARG, 0, \"unexpected command line argument: \"_s +\n\t\t getopt[0] + \"\\n\\n\" + getopt.usage());\n\tcase OE::OPT_DONE:\n\t\treturn;\n\t}\n}\n\n\/**\n * Print the sysctls\n *\/\nvoid print_sysctls() {\n\tsys::ctl::Sysctl<> hw_acpi_acline;\n\ttry {\n\t\thw_acpi_acline = {ACLINE};\n\t} catch (sys::sc_error) {\n\t\tverbose(\"cannot read \"_s + ACLINE);\n\t}\n\t*g.out << \"%s=%ld\\n\"_fmt(LOADREC_FEATURES, FEATURES)\n\t << \"hw.machine=\" << make_Sysctl(CTL_HW, HW_MACHINE).get().get() << '\\n'\n\t << \"hw.model=\" << make_Sysctl(CTL_HW, HW_MODEL).get().get() << '\\n'\n\t << \"hw.ncpu=\" << g.ncpu << '\\n'\n\t << ACLINE << '=' << make_Once(1U, hw_acpi_acline) << '\\n';\n\n\tchar mibname[40];\n\tfor (coreid_t i = 0; i < g.ncpu; ++i) {\n\t\tsprintf_safe(mibname, FREQ, i);\n\t\ttry {\n\t\t\tsys::ctl::Sysctl<> ctl{mibname};\n\t\t\t*g.out << mibname << '='\n\t\t\t << make_Once(0, ctl) << '\\n';\n\t\t} catch (sys::sc_error e) {\n\t\t\tverbose(\"cannot access sysctl: \"_s + mibname);\n\t\t\tif (i == 0) {\n\t\t\t\tfail(Exit::ENOFREQ, e,\n\t\t\t\t \"at least the first CPU core must report its clock frequency\");\n\t\t\t}\n\t\t}\n\t\tsprintf_safe(mibname, FREQ_LEVELS, i);\n\t\ttry {\n\t\t\tsys::ctl::Sysctl<> ctl{mibname};\n\t\t\t*g.out << mibname << '='\n\t\t\t << ctl.get().get() << '\\n';\n\t\t} catch (sys::sc_error) {\n\t\t\t\/* do nada *\/\n\t\t}\n\t}\n}\n\n\/**\n * Report the load frames.\n *\n * This prints the time in ms since the last frame and the cp_times\n * growth as a space separated list.\n *\/\nvoid run() try {\n\t\/*\n\t * Setup cptimes buffer for two samples.\n\t *\/\n\tsys::ctl::Sysctl<> const cp_times_ctl = {CP_TIMES};\n\n\tauto const columns = cp_times_ctl.size() \/ sizeof(cptime_t);\n\tauto cp_times = std::unique_ptr(\n\t new cptime_t[2 * columns]{});\n\n\t\/*\n\t * Setup clock frequency sources for each core.\n\t *\/\n\tcoreid_t const cores = columns \/ CPUSTATES;\n\tauto corefreqs = std::unique_ptr>[]>(\n\t new sys::ctl::Sync>[cores]{});\n\n\tfor (coreid_t i = 0; i < cores; ++i) {\n\t\tchar mibname[40];\n\t\tsprintf_safe(mibname, FREQ, i);\n\t\ttry {\n\t\t\tcorefreqs[i] = sys::ctl::Sysctl<>{mibname};\n\t\t} catch (sys::sc_error e) {\n\t\t\tif (i == 0) {\n\t\t\t\tfail(Exit::ENOFREQ, e,\n\t\t\t\t \"at least the first CPU core must report its clock frequency\");\n\t\t\t}\n\t\t\t\/* Fall back to previous clock provider. *\/\n\t\t\tcorefreqs[i] = corefreqs[i - 1];\n\t\t}\n\t}\n\n\t\/*\n\t * Record `cptimes * freq` in order to get an absolute measure of\n\t * the load.\n\t *\/\n\tauto time = std::chrono::steady_clock::now();\n\tauto last = time;\n\tauto const stop = time + g.duration;\n\tsize_t sample = 0;\n\t\/* Takes a sample and prints it, avoids duplicating code\n\t * behind the loop. *\/\n\tauto const takeAndPrintSample = [&]() {\n\t\tcp_times_ctl.get(&cp_times[sample * columns],\n\t\t sizeof(cptime_t) * columns);\n\t\t*g.out << std::chrono::duration_cast(time - last).count();\n\t\tmhz_t freq = 1;\n\t\tfor (int i = 0; i < columns; ++i) {\n\t\t\tif (i % CPUSTATES == 0) {\n\t\t\t\tfreq = corefreqs[i \/ CPUSTATES];\n\t\t\t}\n\t\t\t*g.out << ' '\n\t\t\t << freq * (cp_times[sample * columns + i] -\n\t\t\t cp_times[((sample + 1) % 2) * columns + i]);\n\t\t}\n\t};\n\twhile (time < stop) {\n\t\ttakeAndPrintSample();\n\t\t*g.out << '\\n';\n\t\tsample = (sample + 1) % 2;\n\t\tlast = time;\n\t\tstd::this_thread::sleep_until(time += g.interval);\n\t}\n\ttakeAndPrintSample();\n\t*g.out << std::endl;\n} catch (sys::sc_error e) {\n\tfail(Exit::ESYSCTL, e, \"failed to access sysctl: \"_s + CP_TIMES);\n}\n\n} \/* namespace *\/\n\n\n\/**\n * Main routine, setup and execute daemon, print errors.\n *\n * @param argc,argv\n *\tThe command line arguments\n * @return\n *\tAn exit code\n * @see Exit\n *\/\nint main(int argc, char * argv[]) {\n\ttry {\n\t\tread_args(argc, argv);\n\t\tinit();\n\t\tprint_sysctls();\n\t\trun();\n\t} catch (Exception & e) {\n\t\tif (e.msg != \"\") {\n\t\t\tstd::cerr << \"loadrec: \" << e.msg << '\\n';\n\t\t}\n\t\treturn to_value(e.exitcode);\n\t} catch (sys::sc_error e) {\n\t\tstd::cerr << \"loadrec: untreated sysctl failure: \" << e.c_str() << '\\n';\n\t\tthrow;\n\t} catch (...) {\n\t\tstd::cerr << \"loadrec: untreated failure\\n\";\n\t\tthrow;\n\t}\n}\n\nAdd support for clock frequency recording\/** \\file\n * Implements a load recorder, useful for simulating loads to test\n * CPU clock daemons and settings.\n *\/\n\n#include \"Options.hpp\"\n\n#include \"types.hpp\"\n#include \"constants.hpp\"\n#include \"errors.hpp\"\n#include \"utility.hpp\"\n#include \"clas.hpp\"\n#include \"version.hpp\"\n\n#include \"sys\/sysctl.hpp\"\n\n#include \/* std::cout, std::cerr *\/\n#include \/* std::ofstream *\/\n#include \/* std::chrono::steady_clock::now() *\/\n#include \/* std::this_thread::sleep_until() *\/\n#include \/* std::unique_ptr *\/\n\n#include \/* CPUSTATES *\/\n\n\/**\n * File local scope.\n *\/\nnamespace {\n\nusing nih::Option;\nusing nih::make_Options;\n\nusing constants::ACLINE;\nusing constants::FREQ;\nusing constants::FREQ_LEVELS;\nusing constants::CP_TIMES;\n\nusing types::ms;\nusing types::coreid_t;\nusing types::cptime_t;\nusing types::mhz_t;\n\nusing errors::Exit;\nusing errors::Exception;\nusing errors::fail;\n\nusing utility::to_value;\nusing utility::sprintf_safe;\nusing namespace utility::literals;\n\nusing clas::ival;\n\nusing sys::ctl::make_Sysctl;\nusing sys::ctl::make_Once;\n\nusing version::LOADREC_FEATURES;\nusing version::flag_t;\nusing namespace version::literals;\n\n\/**\n * The set of supported features.\n *\n * This value is stored in load recordings to allow loadplay to correctly\n * interpret the data.\n *\/\nconstexpr flag_t const FEATURES{\n\t1_FREQ_TRACKING\n};\n\n\/**\n * The global state.\n *\/\nstruct {\n\tbool verbose{false}; \/**< Verbosity flag. *\/\n\tms duration{30000}; \/**< Recording duration in ms. *\/\n\tms interval{25}; \/**< Recording sample interval in ms. *\/\n\n\t\/**\n\t * The output file stream to use if an outfilename is provided\n\t * on the CLI.\n\t *\/\n\tstd::ofstream outfile{};\n\n\t\/**\n\t * A pointer to the stream to use for output, either std::cout\n\t * or outfile.\n\t *\/\n\tstd::ostream * out = &std::cout;\n\n\t\/**\n\t * The user provided output file name.\n\t *\/\n\tchar const * outfilename{nullptr};\n\n\t\/**\n\t * The number of CPU cores\/threads.\n\t *\/\n\tsys::ctl::SysctlOnce const ncpu{1U, {CTL_HW, HW_NCPU}};\n} g;\n\n\/**\n * An enum for command line parsing.\n *\/\nenum class OE {\n\tUSAGE, \/**< Print help *\/\n\tIVAL_DURATION, \/**< Set the duration of the recording *\/\n\tIVAL_POLL, \/**< Set polling interval *\/\n\tFILE_OUTPUT, \/**< Set output file *\/\n\tFILE_PID, \/**< Set PID file *\/\n\tFLAG_VERBOSE, \/**< Verbose output on stderr *\/\n\tOPT_UNKNOWN, \/**< Obligatory *\/\n\tOPT_NOOPT, \/**< Obligatory *\/\n\tOPT_DASH, \/**< Obligatory *\/\n\tOPT_LDASH, \/**< Obligatory *\/\n\tOPT_DONE \/**< Obligatory *\/\n};\n\n\/**\n * The short usage string.\n *\/\nchar const * const USAGE = \"[-hv] [-d ival] [-p ival] [-o file]\";\n\n\/**\n * Definitions of command line options.\n *\/\nOption const OPTIONS[]{\n\t{OE::USAGE, 'h', \"help\", \"\", \"Show usage and exit\"},\n\t{OE::FLAG_VERBOSE, 'v', \"verbose\", \"\", \"Be verbose\"},\n\t{OE::IVAL_DURATION, 'd', \"duration\", \"ival\", \"The duration of the recording\"},\n\t{OE::IVAL_POLL, 'p', \"poll\", \"ival\", \"The polling interval\"},\n\t{OE::FILE_OUTPUT, 'o', \"output\", \"file\", \"Output to file\"},\n\t{OE::FILE_PID, 'P', \"pid\", \"file\", \"Ignored\"},\n};\n\n\/**\n * Outputs the given message on stderr if g.verbose is set.\n *\n * @param msg\n *\tThe message to output\n *\/\ninline void verbose(std::string const & msg) {\n\tif (g.verbose) {\n\t\tstd::cerr << \"loadrec: \" << msg << '\\n';\n\t}\n}\n\n\/**\n * Set up output to the given file.\n *\/\nvoid init() {\n\tif (g.outfilename) {\n\t\tg.outfile.open(g.outfilename);\n\t\tif (!g.outfile.good()) {\n\t\t\tfail(Exit::EWOPEN, errno,\n\t\t\t \"could not open file for writing: \"_s + g.outfilename);\n\t\t}\n\t\tg.out = &g.outfile;\n\t}\n}\n\n\/**\n * Parse command line arguments.\n *\n * @param argc,argv\n *\tThe command line arguments\n *\/\nvoid read_args(int const argc, char const * const argv[]) {\n\tauto getopt = make_Options(argc, argv, USAGE, OPTIONS);\n\n\twhile (true) switch (getopt()) {\n\tcase OE::USAGE:\n\t\tstd::cerr << getopt.usage();\n\t\tthrow Exception{Exit::OK, 0, \"\"};\n\tcase OE::FLAG_VERBOSE:\n\t\tg.verbose = true;\n\t\tbreak;\n\tcase OE::IVAL_DURATION:\n\t\tg.duration = ival(getopt[1]);\n\t\tbreak;\n\tcase OE::IVAL_POLL:\n\t\tg.interval = ival(getopt[1]);\n\t\tbreak;\n\tcase OE::FILE_OUTPUT:\n\t\tg.outfilename = getopt[1];\n\t\tbreak;\n\tcase OE::FILE_PID:\n\t\tbreak;\n\tcase OE::OPT_UNKNOWN:\n\tcase OE::OPT_NOOPT:\n\tcase OE::OPT_DASH:\n\tcase OE::OPT_LDASH:\n\t\tfail(Exit::ECLARG, 0, \"unexpected command line argument: \"_s +\n\t\t getopt[0] + \"\\n\\n\" + getopt.usage());\n\tcase OE::OPT_DONE:\n\t\treturn;\n\t}\n}\n\n\/**\n * Print the sysctls\n *\/\nvoid print_sysctls() {\n\tsys::ctl::Sysctl<> hw_acpi_acline;\n\ttry {\n\t\thw_acpi_acline = {ACLINE};\n\t} catch (sys::sc_error) {\n\t\tverbose(\"cannot read \"_s + ACLINE);\n\t}\n\t*g.out << \"%s=%ld\\n\"_fmt(LOADREC_FEATURES, FEATURES)\n\t << \"hw.machine=\" << make_Sysctl(CTL_HW, HW_MACHINE).get().get() << '\\n'\n\t << \"hw.model=\" << make_Sysctl(CTL_HW, HW_MODEL).get().get() << '\\n'\n\t << \"hw.ncpu=\" << g.ncpu << '\\n'\n\t << ACLINE << '=' << make_Once(1U, hw_acpi_acline) << '\\n';\n\n\tfor (coreid_t i = 0; i < g.ncpu; ++i) {\n\t\tchar mibname[40];\n\t\tsprintf_safe(mibname, FREQ, i);\n\t\ttry {\n\t\t\tsys::ctl::Sysctl<> ctl{mibname};\n\t\t\t*g.out << mibname << '='\n\t\t\t << make_Once(0, ctl) << '\\n';\n\t\t} catch (sys::sc_error e) {\n\t\t\tverbose(\"cannot access sysctl: \"_s + mibname);\n\t\t\tif (i == 0) {\n\t\t\t\tfail(Exit::ENOFREQ, e,\n\t\t\t\t \"at least the first CPU core must report its clock frequency\");\n\t\t\t}\n\t\t}\n\t\tsprintf_safe(mibname, FREQ_LEVELS, i);\n\t\ttry {\n\t\t\tsys::ctl::Sysctl<> ctl{mibname};\n\t\t\t*g.out << mibname << '='\n\t\t\t << ctl.get().get() << '\\n';\n\t\t} catch (sys::sc_error) {\n\t\t\t\/* do nada *\/\n\t\t}\n\t}\n}\n\n\/**\n * Report the load frames.\n *\n * This prints the time in ms since the last frame and the cp_times\n * growth as a space separated list.\n *\/\nvoid run() try {\n\t\/*\n\t * Setup cptimes buffer for two samples.\n\t *\/\n\tsys::ctl::Sysctl<> const cp_times_ctl = {CP_TIMES};\n\n\tauto const columns = cp_times_ctl.size() \/ sizeof(cptime_t);\n\tauto cp_times = std::unique_ptr(\n\t new cptime_t[2 * columns]{});\n\n\t\/*\n\t * Setup clock frequency sources for each core.\n\t *\/\n\tcoreid_t const cores = columns \/ CPUSTATES;\n\tauto corefreqs = std::unique_ptr>[]>(\n\t new sys::ctl::Sync>[cores]{});\n\n\tfor (coreid_t i = 0; i < cores; ++i) {\n\t\tchar mibname[40];\n\t\tsprintf_safe(mibname, FREQ, i);\n\t\ttry {\n\t\t\tcorefreqs[i] = sys::ctl::Sysctl<>{mibname};\n\t\t} catch (sys::sc_error e) {\n\t\t\tif (i == 0) {\n\t\t\t\tfail(Exit::ENOFREQ, e,\n\t\t\t\t \"at least the first CPU core must report its clock frequency\");\n\t\t\t}\n\t\t\t\/* Fall back to previous clock provider. *\/\n\t\t\tcorefreqs[i] = corefreqs[i - 1];\n\t\t}\n\t}\n\n\t\/*\n\t * Record freq and cptimes.\n\t *\/\n\tauto time = std::chrono::steady_clock::now();\n\tauto last = time;\n\tauto const stop = time + g.duration;\n\tsize_t sample = 0;\n\t\/* Takes a sample and prints it, avoids duplicating code\n\t * behind the loop. *\/\n\tauto const takeAndPrintSample = [&]() {\n\t\tcp_times_ctl.get(&cp_times[sample * columns],\n\t\t sizeof(cptime_t) * columns);\n\t\t*g.out << std::chrono::duration_cast(time - last).count();\n\t\tfor (coreid_t i = 0; i < cores; ++i) {\n\t\t\t*g.out << ' ' << static_cast(corefreqs[i]);\n\t\t}\n\t\tfor (int i = 0; i < columns; ++i) {\n\t\t\t*g.out << ' '\n\t\t\t << cp_times[sample * columns + i] -\n\t\t\t cp_times[((sample + 1) % 2) * columns + i];\n\t\t}\n\t};\n\twhile (time < stop) {\n\t\ttakeAndPrintSample();\n\t\t*g.out << '\\n';\n\t\tsample = (sample + 1) % 2;\n\t\tlast = time;\n\t\tstd::this_thread::sleep_until(time += g.interval);\n\t}\n\ttakeAndPrintSample();\n\t*g.out << std::endl;\n} catch (sys::sc_error e) {\n\tfail(Exit::ESYSCTL, e, \"failed to access sysctl: \"_s + CP_TIMES);\n}\n\n} \/* namespace *\/\n\n\n\/**\n * Main routine, setup and execute daemon, print errors.\n *\n * @param argc,argv\n *\tThe command line arguments\n * @return\n *\tAn exit code\n * @see Exit\n *\/\nint main(int argc, char * argv[]) {\n\ttry {\n\t\tread_args(argc, argv);\n\t\tinit();\n\t\tprint_sysctls();\n\t\trun();\n\t} catch (Exception & e) {\n\t\tif (e.msg != \"\") {\n\t\t\tstd::cerr << \"loadrec: \" << e.msg << '\\n';\n\t\t}\n\t\treturn to_value(e.exitcode);\n\t} catch (sys::sc_error e) {\n\t\tstd::cerr << \"loadrec: untreated sysctl failure: \" << e.c_str() << '\\n';\n\t\tthrow;\n\t} catch (...) {\n\t\tstd::cerr << \"loadrec: untreated failure\\n\";\n\t\tthrow;\n\t}\n}\n\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/*\n *\n *\/\n\n#include \n#include \"common.h\"\n#include \"SceneNode.h\"\n#include \"ZSceneDatabase.h\"\n#include \"SphereSceneNode.h\"\n#include \"Octree.h\"\n#include \"StateDatabase.h\"\n\nZSceneDatabase::ZSceneDatabase() :\n\t\t\t\tstaticCount(0),\n\t\t\t\tstaticSize(0),\n\t\t\t\tstaticList(NULL),\n\t\t\t\tdynamicCount(0),\n\t\t\t\tdynamicSize(0),\n\t\t\t\tdynamicList(NULL)\n{\n \/\/ do nothing\n}\n\nZSceneDatabase::~ZSceneDatabase()\n{\n \/\/ free static nodes\n for (int i = 0; i < staticCount; i++) {\n delete staticList[i];\n }\n\n \/\/ free lists\n delete[] staticList;\n delete[] dynamicList;\n}\n\nvoid\t\t\tZSceneDatabase::addStaticNode(SceneNode* object)\n{\n if (staticCount == staticSize) {\n if (staticSize == 0) staticSize = 15;\n else staticSize += staticSize + 1;\n SceneNode** newStatic = new SceneNode*[staticSize];\n if (staticList)\n ::memcpy(newStatic, staticList, staticCount * sizeof(SceneNode*));\n delete[] staticList;\n staticList = newStatic;\n }\n staticList[staticCount++] = object;\n}\n\nvoid\t\t\tZSceneDatabase::addDynamicNode(SceneNode* object)\n{\n if (dynamicCount == dynamicSize) {\n if (dynamicSize == 0) dynamicSize = 15;\n else dynamicSize += dynamicSize + 1;\n SceneNode** newDynamic = new SceneNode*[dynamicSize];\n if (dynamicList)\n ::memcpy(newDynamic, dynamicList, dynamicCount * sizeof(SceneNode*));\n delete[] dynamicList;\n dynamicList = newDynamic;\n }\n dynamicList[dynamicCount++] = object;\n}\n\nvoid\t\t\tZSceneDatabase::addDynamicSphere(SphereSceneNode* n)\n{\n \/\/ just add sphere -- don't need to break it up for hidden surfaces\n addDynamicNode(n);\n}\n\nvoid\t\t\tZSceneDatabase::removeDynamicNodes()\n{\n dynamicCount = 0;\n}\n\nvoid\t\t\tZSceneDatabase::removeAllNodes()\n{\n staticCount = 0;\n dynamicCount = 0;\n}\n\nbool\t\t\tZSceneDatabase::isOrdered()\n{\n return false;\n}\n\nSceneIterator*\t\tZSceneDatabase::getRenderIterator()\n{\n return new ZSceneIterator(this);\n}\n\n\n\/\/\n\/\/ ZSceneIterator\n\/\/\n\nZSceneIterator::ZSceneIterator(const ZSceneDatabase* _db) :\n\t\t\t\tSceneIterator(), db(_db)\n{\n cullDepth = BZDB.evalInt(StateDatabase::BZDB_CULLDEPTH);\n cullElements = BZDB.evalInt(StateDatabase::BZDB_CULLELEMENTS);\n octree = NULL;\n culledList = NULL;\n if (cullDepth > 0) {\n makeCuller();\n }\n else {\n culledList = db->staticList;\n culledCount = db->staticCount;\n }\n reset();\n}\n\nZSceneIterator::~ZSceneIterator()\n{\n delete octree;\n if (culledList != db->staticList) {\n delete culledList;\n }\n}\n\nvoid\t\t\tZSceneIterator::makeCuller()\n{\n delete octree;\n octree = new Octree;\n octree->addNodes (db->staticList, db->staticCount, cullDepth, cullElements);\n if (culledList != db->staticList) {\n delete culledList;\n }\n \/\/ make scratch pad for the culler\n culledList = new (SceneNode*)[db->staticCount];\n}\n\nvoid\t\t\tZSceneIterator::resetFrustum(const ViewFrustum* frustum)\n{\n const int currentDepth = BZDB.evalInt(StateDatabase::BZDB_CULLDEPTH);\n const int currentElements = BZDB.evalInt(StateDatabase::BZDB_CULLELEMENTS);\n\n if ((currentDepth != cullDepth) || (currentElements != cullElements)) {\n\n cullDepth = currentDepth;\n cullElements = currentElements;\n\n delete octree;\n octree = NULL;\n\n if (cullDepth > 0) {\n makeCuller();\n }\n else {\n if (culledList != db->staticList) {\n delete culledList;\n }\n culledList = db->staticList;\n culledCount = db->staticCount;\n }\n }\n\n \/\/ cull if we're supposed to\n if (octree) {\n culledCount = octree->getFrustumList (culledList, db->staticCount,\n (const Frustum *) frustum);\n }\n}\n\nvoid\t\t\tZSceneIterator::reset()\n{\n culledIndex = 0;\n culledDone = (culledCount == culledIndex);\n dynamicIndex = 0;\n dynamicDone = (db->dynamicCount == dynamicIndex);\n}\n\nSceneNode*\t\tZSceneIterator::getNext()\n{\n if (!culledDone) {\n SceneNode* node = culledList[culledIndex++];\n culledDone = (culledIndex >= culledCount);\n return node;\n }\n if (!dynamicDone) {\n SceneNode* node = db->dynamicList[dynamicIndex++];\n dynamicDone = (db->dynamicCount == dynamicIndex);\n return node;\n }\n return NULL;\n}\n\n\n\/\/ the callback function from the Culler\nstatic void drawLines (int vertices, const float points[][3], bool partial)\n{\n GLfloat defaultColor[4] = {1.0f, 0.0f, 0.0f, 0.75f};\n GLfloat partialColor[4] = {0.0f, 0.0f, 1.0f, 0.75f};\n \n if (partial) {\n glColor4fv (partialColor);\n } else {\n glColor4fv (defaultColor);\n }\n glBegin (GL_LINE_STRIP);\n for (int i = 0; i < vertices; i++) {\n glVertex3fv (points[i]);\n }\n glEnd ();\n}\n\nvoid \t\tZSceneIterator::drawCuller()\n{\n if (octree) {\n \/\/ setup to draw lines\n glDisable (GL_TEXTURE_2D);\n octree->draw (drawLines);\n glEnable (GL_TEXTURE_2D);\n }\n return;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\ncompile on vc, part 2 - someone make sure that doesn't break gcc\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/*\n *\n *\/\n\n#include \n#include \"common.h\"\n#include \"SceneNode.h\"\n#include \"ZSceneDatabase.h\"\n#include \"SphereSceneNode.h\"\n#include \"Octree.h\"\n#include \"StateDatabase.h\"\n\nZSceneDatabase::ZSceneDatabase() :\n\t\t\t\tstaticCount(0),\n\t\t\t\tstaticSize(0),\n\t\t\t\tstaticList(NULL),\n\t\t\t\tdynamicCount(0),\n\t\t\t\tdynamicSize(0),\n\t\t\t\tdynamicList(NULL)\n{\n \/\/ do nothing\n}\n\nZSceneDatabase::~ZSceneDatabase()\n{\n \/\/ free static nodes\n for (int i = 0; i < staticCount; i++) {\n delete staticList[i];\n }\n\n \/\/ free lists\n delete[] staticList;\n delete[] dynamicList;\n}\n\nvoid\t\t\tZSceneDatabase::addStaticNode(SceneNode* object)\n{\n if (staticCount == staticSize) {\n if (staticSize == 0) staticSize = 15;\n else staticSize += staticSize + 1;\n SceneNode** newStatic = new SceneNode*[staticSize];\n if (staticList)\n ::memcpy(newStatic, staticList, staticCount * sizeof(SceneNode*));\n delete[] staticList;\n staticList = newStatic;\n }\n staticList[staticCount++] = object;\n}\n\nvoid\t\t\tZSceneDatabase::addDynamicNode(SceneNode* object)\n{\n if (dynamicCount == dynamicSize) {\n if (dynamicSize == 0) dynamicSize = 15;\n else dynamicSize += dynamicSize + 1;\n SceneNode** newDynamic = new SceneNode*[dynamicSize];\n if (dynamicList)\n ::memcpy(newDynamic, dynamicList, dynamicCount * sizeof(SceneNode*));\n delete[] dynamicList;\n dynamicList = newDynamic;\n }\n dynamicList[dynamicCount++] = object;\n}\n\nvoid\t\t\tZSceneDatabase::addDynamicSphere(SphereSceneNode* n)\n{\n \/\/ just add sphere -- don't need to break it up for hidden surfaces\n addDynamicNode(n);\n}\n\nvoid\t\t\tZSceneDatabase::removeDynamicNodes()\n{\n dynamicCount = 0;\n}\n\nvoid\t\t\tZSceneDatabase::removeAllNodes()\n{\n staticCount = 0;\n dynamicCount = 0;\n}\n\nbool\t\t\tZSceneDatabase::isOrdered()\n{\n return false;\n}\n\nSceneIterator*\t\tZSceneDatabase::getRenderIterator()\n{\n return new ZSceneIterator(this);\n}\n\n\n\/\/\n\/\/ ZSceneIterator\n\/\/\n\nZSceneIterator::ZSceneIterator(const ZSceneDatabase* _db) :\n\t\t\t\tSceneIterator(), db(_db)\n{\n cullDepth = BZDB.evalInt(StateDatabase::BZDB_CULLDEPTH);\n cullElements = BZDB.evalInt(StateDatabase::BZDB_CULLELEMENTS);\n octree = NULL;\n culledList = NULL;\n if (cullDepth > 0) {\n makeCuller();\n }\n else {\n culledList = db->staticList;\n culledCount = db->staticCount;\n }\n reset();\n}\n\nZSceneIterator::~ZSceneIterator()\n{\n delete octree;\n if (culledList != db->staticList) {\n delete culledList;\n }\n}\n\nvoid\t\t\tZSceneIterator::makeCuller()\n{\n delete octree;\n octree = new Octree;\n octree->addNodes (db->staticList, db->staticCount, cullDepth, cullElements);\n if (culledList != db->staticList) {\n delete culledList;\n }\n \/\/ make scratch pad for the culler\n culledList = new SceneNode*[db->staticCount];\n}\n\nvoid\t\t\tZSceneIterator::resetFrustum(const ViewFrustum* frustum)\n{\n const int currentDepth = BZDB.evalInt(StateDatabase::BZDB_CULLDEPTH);\n const int currentElements = BZDB.evalInt(StateDatabase::BZDB_CULLELEMENTS);\n\n if ((currentDepth != cullDepth) || (currentElements != cullElements)) {\n\n cullDepth = currentDepth;\n cullElements = currentElements;\n\n delete octree;\n octree = NULL;\n\n if (cullDepth > 0) {\n makeCuller();\n }\n else {\n if (culledList != db->staticList) {\n delete culledList;\n }\n culledList = db->staticList;\n culledCount = db->staticCount;\n }\n }\n\n \/\/ cull if we're supposed to\n if (octree) {\n culledCount = octree->getFrustumList (culledList, db->staticCount,\n (const Frustum *) frustum);\n }\n}\n\nvoid\t\t\tZSceneIterator::reset()\n{\n culledIndex = 0;\n culledDone = (culledCount == culledIndex);\n dynamicIndex = 0;\n dynamicDone = (db->dynamicCount == dynamicIndex);\n}\n\nSceneNode*\t\tZSceneIterator::getNext()\n{\n if (!culledDone) {\n SceneNode* node = culledList[culledIndex++];\n culledDone = (culledIndex >= culledCount);\n return node;\n }\n if (!dynamicDone) {\n SceneNode* node = db->dynamicList[dynamicIndex++];\n dynamicDone = (db->dynamicCount == dynamicIndex);\n return node;\n }\n return NULL;\n}\n\n\n\/\/ the callback function from the Culler\nstatic void drawLines (int vertices, const float points[][3], bool partial)\n{\n GLfloat defaultColor[4] = {1.0f, 0.0f, 0.0f, 0.75f};\n GLfloat partialColor[4] = {0.0f, 0.0f, 1.0f, 0.75f};\n \n if (partial) {\n glColor4fv (partialColor);\n } else {\n glColor4fv (defaultColor);\n }\n glBegin (GL_LINE_STRIP);\n for (int i = 0; i < vertices; i++) {\n glVertex3fv (points[i]);\n }\n glEnd ();\n}\n\nvoid \t\tZSceneIterator::drawCuller()\n{\n if (octree) {\n \/\/ setup to draw lines\n glDisable (GL_TEXTURE_2D);\n octree->draw (drawLines);\n glEnable (GL_TEXTURE_2D);\n }\n return;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"#include \"test.h\"\n\nstatic_MTX(mtx3, mtxErrorCheck);\n\nstatic void proc3()\n{\n\tunsigned event;\n\n\tevent = mtx_take(mtx2); assert_timeout(event);\n\tevent = mtx_wait(mtx3); assert_success(event);\n\tevent = mtx_take(mtx3); assert_failure(event);\n\tevent = mtx_give(mtx3); assert_success(event);\n\tevent = mtx_give(mtx3); assert_failure(event);\n\t tsk_stop();\n}\n\nstatic void proc2()\n{\n\tunsigned event;\n\n\tevent = mtx_take(mtx1); assert_timeout(event);\n\tevent = mtx_wait(mtx2); assert_success(event);\n\tevent = mtx_take(mtx2); assert_success(event);\n\t assert_dead(tsk3);\n\t tsk_startFrom(tsk3, proc3); assert_dead(tsk3);\n\tevent = tsk_join(tsk3); assert_success(event);\n\tevent = mtx_give(mtx2); assert_success(event);\n\tevent = mtx_give(mtx2); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc1()\n{\n\tunsigned event;\n\n\tevent = mtx_take(&mtx0); assert_timeout(event);\n\tevent = mtx_wait(mtx1); assert_success(event);\n\tevent = mtx_take(mtx1); assert_failure(event);\n\t assert_dead(tsk2);\n\t tsk_startFrom(tsk2, proc2); assert_dead(tsk2);\n\tevent = tsk_join(tsk2); assert_success(event);\n\tevent = mtx_give(mtx1); assert_success(event);\n\tevent = mtx_give(mtx1); assert_failure(event);\n\t tsk_stop();\n}\n\nstatic void proc0()\n{\n\tunsigned event;\n\n\tevent = mtx_wait(&mtx0); assert_success(event);\n\tevent = mtx_take(&mtx0); assert_timeout(event);\n\t assert_dead(tsk1);\n\t tsk_startFrom(tsk1, proc1); assert_dead(tsk1);\n\tevent = tsk_join(tsk1); assert_success(event);\n\tevent = mtx_give(&mtx0); assert_success(event);\n\tevent = mtx_give(&mtx0); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void test()\n{\n\tunsigned event;\n\t assert_dead(&tsk0);\n\t tsk_startFrom(&tsk0, proc0);\n\tevent = tsk_join(&tsk0); assert_success(event);\n}\n\nextern \"C\"\nvoid test_mutex_4()\n{\n\tTEST_Notify();\n\tmtx_init(&mtx0, mtxNormal, 0);\n\tmtx_init(mtx1, mtxErrorCheck, 0);\n\tmtx_init(mtx2, mtxRecursive, 0);\n\tTEST_Call();\n}\nUpdate test_mutex_4.cpp#include \"test.h\"\n\nstatic_MTX(mtx3, mtxRobust);\n\nstatic void proc5()\n{\n\tunsigned event;\n\n\tevent = mtx_wait(mtx3); assert_owndead(event);\n\tevent = mtx_give(mtx3); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc4()\n{\n\tunsigned event;\n\n\tevent = mtx_wait(mtx3); assert_success(event);\n\t assert_dead(tsk5);\n\t tsk_startFrom(tsk5, proc5); assert_ready(tsk5);\n\tevent = mtx_wait(mtx1); assert(!\"test program cannot be caught here\");\n}\n\nstatic void proc3()\n{\n\tunsigned event;\n\n\tevent = mtx_take(mtx2); assert_timeout(event);\n\tevent = mtx_wait(mtx3); assert_success(event);\n\tevent = mtx_take(mtx3); assert_timeout(event);\n\t assert_dead(tsk4);\n\t tsk_startFrom(tsk4, proc4); assert_ready(tsk4);\n\tevent = mtx_give(mtx3); assert_success(event);\n\tevent = mtx_give(mtx3); assert_failure(event);\n\tevent = tsk_kill(tsk4); assert_success(event);\n\tevent = tsk_join(tsk5); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc2()\n{\n\tunsigned event;\n\n\tevent = mtx_take(mtx1); assert_timeout(event);\n\tevent = mtx_wait(mtx2); assert_success(event);\n\tevent = mtx_take(mtx2); assert_success(event);\n\t assert_dead(tsk3);\n\t tsk_startFrom(tsk3, proc3); assert_dead(tsk3);\n\tevent = tsk_join(tsk3); assert_success(event);\n\tevent = mtx_give(mtx2); assert_success(event);\n\tevent = mtx_give(mtx2); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc1()\n{\n\tunsigned event;\n\n\tevent = mtx_take(&mtx0); assert_timeout(event);\n\tevent = mtx_wait(mtx1); assert_success(event);\n\tevent = mtx_take(mtx1); assert_failure(event);\n\t assert_dead(tsk2);\n\t tsk_startFrom(tsk2, proc2); assert_dead(tsk2);\n\tevent = tsk_join(tsk2); assert_success(event);\n\tevent = mtx_give(mtx1); assert_success(event);\n\tevent = mtx_give(mtx1); assert_failure(event);\n\t tsk_stop();\n}\n\nstatic void proc0()\n{\n\tunsigned event;\n\n\tevent = mtx_wait(&mtx0); assert_success(event);\n\tevent = mtx_take(&mtx0); assert_timeout(event);\n\t assert_dead(tsk1);\n\t tsk_startFrom(tsk1, proc1); assert_dead(tsk1);\n\tevent = tsk_join(tsk1); assert_success(event);\n\tevent = mtx_give(&mtx0); assert_success(event);\n\tevent = mtx_give(&mtx0); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void test()\n{\n\tunsigned event;\n\t assert_dead(&tsk0);\n\t tsk_startFrom(&tsk0, proc0);\n\tevent = tsk_join(&tsk0); assert_success(event);\n}\n\nextern \"C\"\nvoid test_mutex_4()\n{\n\tTEST_Notify();\n\tmtx_init(&mtx0, mtxNormal, 0);\n\tmtx_init(mtx1, mtxErrorCheck, 0);\n\tmtx_init(mtx2, mtxRecursive, 0);\n\tTEST_Call();\n}\n<|endoftext|>"} {"text":"D3D10 render system - A small bug fix for the hlsl shader generator – VET_UBYTE4 is float4 and not char4 (no such thing as char4...).<|endoftext|>"} {"text":"#include \n#include \n\n#include \"acmacs-base\/argc-argv.hh\"\n#include \"acmacs-base\/stream.hh\"\n#include \"seqdb\/seqdb.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"tree.hh\"\n#include \"tree-export.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int argc, const char* argv[])\n{\n using namespace std::string_literals;\n try {\n argc_argv args(argc, argv,\n {\n {\"--db-dir\", \"\"},\n {\"--seqdb\", \"\"},\n {\"--chart\", \"\"},\n {\"--max-leaf-offset\", 80},\n\n {\"-v\", false},\n {\"--verbose\", false},\n {\"-h\", false},\n {\"--help\", false},\n });\n\n if (args[\"-h\"] || args[\"--help\"] || args.number_of_arguments() != 1) {\n throw std::runtime_error(\"Usage: \"s + args.program() + \" [options] \\n\" + args.usage_options());\n }\n const bool verbose = args[\"-v\"] || args[\"--verbose\"];\n seqdb::setup_dbs(args[\"--db-dir\"], verbose ? seqdb::report::yes : seqdb::report::no);\n if (args[\"--seqdb\"])\n seqdb::setup(args[\"--seqdb\"], verbose ? seqdb::report::yes : seqdb::report::no);\n\n Tree tree;\n tree::tree_import(args[0], tree);\n tree.match_seqdb(seqdb::get());\n if (args[\"--chart\"]) {\n auto chart = acmacs::chart::import_from_file(args[\"--chart\"], acmacs::chart::Verify::None, report_time::No);\n const auto matched_names = tree.match(*chart);\n if (matched_names)\n std::cout << \"Tree sequences found in the chart: \" << matched_names << std::endl;\n }\n tree.set_number_strains();\n tree.ladderize(Tree::LadderizeMethod::NumberOfLeaves);\n tree.compute_cumulative_edge_length();\n const auto [min_edge, max_edge] = tree.cumulative_edge_minmax();\n \/\/ std::cout << \"mm: \" << min_edge << ' ' << max_edge << '\\n';\n const auto step = max_edge \/ static_cast(args[\"--max-leaf-offset\"]);\n\n for (const auto* node : tree.leaf_nodes()) {\n const auto edge = node->data.cumulative_edge_length \/ step;\n std::cout << std::string(static_cast(std::lround(edge)), ' ') << node->seq_id;\n if (node->draw.chart_antigen_index)\n std::cout << \" [antigen: \" << *node->draw.chart_antigen_index << ']';\n std::cout << \" [cumul: \" << node->data.cumulative_edge_length\n << ']'\n \/\/ << \" [edge: \" << edge << ']'\n << '\\n';\n }\n\n return 0;\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n return 1;\n }\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\nshowing tree in the text format#include \n#include \n\n#include \"acmacs-base\/argc-argv.hh\"\n#include \"acmacs-base\/stream.hh\"\n#include \"seqdb\/seqdb.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"tree.hh\"\n#include \"tree-export.hh\"\n\nstatic void print_tree_leaves(const Tree& tree, double step);\nstatic void print_tree(const Tree& tree, double step);\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int argc, const char* argv[])\n{\n using namespace std::string_literals;\n try {\n argc_argv args(argc, argv,\n {\n {\"--db-dir\", \"\"},\n {\"--seqdb\", \"\"},\n {\"--chart\", \"\"},\n {\"--max-leaf-offset\", 80},\n\n {\"-v\", false},\n {\"--verbose\", false},\n {\"-h\", false},\n {\"--help\", false},\n });\n\n if (args[\"-h\"] || args[\"--help\"] || args.number_of_arguments() != 1) {\n throw std::runtime_error(\"Usage: \"s + args.program() + \" [options] \\n\" + args.usage_options());\n }\n const bool verbose = args[\"-v\"] || args[\"--verbose\"];\n seqdb::setup_dbs(args[\"--db-dir\"], verbose ? seqdb::report::yes : seqdb::report::no);\n if (args[\"--seqdb\"])\n seqdb::setup(args[\"--seqdb\"], verbose ? seqdb::report::yes : seqdb::report::no);\n\n Tree tree;\n tree::tree_import(args[0], tree);\n tree.match_seqdb(seqdb::get());\n if (args[\"--chart\"]) {\n auto chart = acmacs::chart::import_from_file(args[\"--chart\"], acmacs::chart::Verify::None, report_time::No);\n const auto matched_names = tree.match(*chart);\n if (matched_names)\n std::cout << \"Tree sequences found in the chart: \" << matched_names << std::endl;\n }\n tree.set_number_strains();\n tree.ladderize(Tree::LadderizeMethod::NumberOfLeaves);\n tree.compute_cumulative_edge_length();\n const auto [min_edge, max_edge] = tree.cumulative_edge_minmax();\n \/\/ std::cout << \"mm: \" << min_edge << ' ' << max_edge << '\\n';\n const auto step = max_edge \/ static_cast(args[\"--max-leaf-offset\"]);\n\n print_tree(tree, step);\n \/\/ print_tree_leaves(tree, step);\n\n return 0;\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n return 1;\n }\n}\n\n\/\/ ----------------------------------------------------------------------\n\nvoid print_tree(const Tree& tree, double step)\n{\n auto print_prefix = [step](const Node& node) {\n const auto edge = node.data.cumulative_edge_length \/ step;\n std::cout << std::string(static_cast(std::lround(edge)), ' ');\n };\n\n auto print_cumul = [](const Node& node) { std::cout << \" [cumul: \" << node.data.cumulative_edge_length << ']'; };\n\n auto print_leaf = [&](const Node& node) {\n print_prefix(node);\n std::cout << node.seq_id;\n if (node.draw.chart_antigen_index)\n std::cout << \" [antigen: \" << *node.draw.chart_antigen_index << ']';\n print_cumul(node);\n std::cout << '\\n';\n };\n\n auto print_node = [&](const Node& node) {\n print_prefix(node);\n std::cout << '+';\n \/\/ print_cumul(node);\n std::cout << '\\n';\n };\n\n tree::iterate_leaf_pre(tree, print_leaf, print_node);\n\n} \/\/ print_tree\n\n\/\/ ----------------------------------------------------------------------\n\nvoid print_tree_leaves(const Tree& tree, double step)\n{\n for (const auto* node : tree.leaf_nodes()) {\n const auto edge = node->data.cumulative_edge_length \/ step;\n std::cout << std::string(static_cast(std::lround(edge)), ' ') << node->seq_id;\n if (node->draw.chart_antigen_index)\n std::cout << \" [antigen: \" << *node->draw.chart_antigen_index << ']';\n std::cout << \" [cumul: \" << node->data.cumulative_edge_length\n << ']'\n \/\/ << \" [edge: \" << edge << ']'\n << '\\n';\n }\n\n} \/\/ print_tree_leaves\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AppDetailView.hxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 10:17:31 $\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 DBAUI_APPDETAILVIEW_HXX\n#define DBAUI_APPDETAILVIEW_HXX\n\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_\n#include \n#endif\n#ifndef _SV_SPLIT_HXX\n#include \n#endif\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX\n#include \"IClipBoardTest.hxx\"\n#endif\n#ifndef DBAUI_TITLE_WINDOW_HXX\n#include \"AppTitleWindow.hxx\"\n#endif\n#ifndef DBAUI_APPELEMENTTYPE_HXX\n#include \"AppElementType.hxx\"\n#endif\n#ifndef _SVTREEBOX_HXX\n#include \n#endif\n#ifndef DBAUI_VERTSPLITVIEW_HXX\n#include \"VertSplitView.hxx\"\n#endif\n\n#include \n\nclass SvLBoxEntry;\nnamespace dbaui\n{\n class OApplicationController;\n class OAppBorderWindow;\n class OApplicationDetailView;\n class OAppDetailPageHelper;\n class OTasksWindow;\n\n class OCreationList : public SvTreeListBox\n {\n OTasksWindow* m_pTaskWindow;\n\n \/\/ members related to drawing the currently hovered\/selected entry\n SvLBoxEntry* m_pMouseDownEntry;\n SvLBoxEntry* m_pLastActiveEntry;\n Color m_aOriginalBackgroundColor;\n Font m_aOriginalFont;\n\n public:\n OCreationList(OTasksWindow* _pParent);\n \/\/ window overloads\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void KeyInput( const KeyEvent& rKEvt );\n virtual void Paint( const Rectangle& rRect );\n virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel );\n virtual void GetFocus();\n virtual void LoseFocus();\n\n inline void resetLastActive() { m_pLastActiveEntry = NULL;}\n\n void updateHelpText();\n\n protected:\n virtual void PreparePaint( SvLBoxEntry* _pEntry );\n virtual Rectangle GetFocusRect( SvLBoxEntry* _pEntry, long _nLine );\n virtual void ModelHasCleared();\n\n private:\n void onSelected( SvLBoxEntry* _pEntry ) const;\n \/** sets a new current entry, and invalidates the old and the new one, if necessary\n @return if and only if the \"current entry\" changed\n *\/\n bool setCurrentEntryInvalidate( SvLBoxEntry* _pEntry );\n };\n\n typedef ::std::pair< ::rtl::OUString,USHORT> TResourcePair;\n typedef ::std::vector< ::std::pair > TResourceStruct;\n\n class OTasksWindow : public Window\n {\n ::std::vector< USHORT > m_aHelpTextIds;\n OCreationList m_aCreation;\n FixedText m_aDescription;\n FixedText m_aHelpText;\n FixedLine m_aFL;\n OApplicationDetailView* m_pDetailView;\n\n DECL_LINK( OnEntrySelectHdl, SvTreeListBox* );\n void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );\n protected:\n virtual void DataChanged(const DataChangedEvent& rDCEvt);\n public:\n OTasksWindow(Window* _pParent,OApplicationDetailView* _pDetailView);\n virtual ~OTasksWindow();\n\n \/\/ window overloads\n virtual void Resize();\n\n OApplicationDetailView* getDetailView() const { return m_pDetailView; }\n\n \/** fills the Creation listbox with the necessary strings and images\n @param _rList\n The strings and the id of the images and help texts to add.\n *\/\n void fillCreationNew( const TResourceStruct& _rList );\n\n void Clear();\n void setHelpText(USHORT _nId);\n };\n \/\/==================================================================\n class OApplicationDetailView : public OSplitterView\n , public IClipboardTest\n {\n Splitter m_aHorzSplitter;\n OTitleWindow m_aTasks;\n OTitleWindow m_aContainer;\n OAppBorderWindow& m_rBorderWin; \/\/ my parent\n OAppDetailPageHelper* m_pControlHelper;\n\n void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );\n protected:\n virtual void DataChanged(const DataChangedEvent& rDCEvt);\n public:\n OApplicationDetailView(OAppBorderWindow& _rParent,PreviewMode _ePreviewMode);\n virtual ~OApplicationDetailView();\n \/\/ window overloads\n \/\/ virtual void Resize();\n virtual void GetFocus();\n\n \/** creates the tables page\n @param _xConnection\n The connection to get the table names\n *\/\n void createTablesPage(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection);\n\n \/** creates the page for the specific type.\n @param _eType\n The type which should be created. E_TABLE isn't allowed.\n @param _xContainer\n The container of the elements to be inserted.\n *\/\n void createPage(ElementType _eType,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer);\n\n inline OAppBorderWindow& getBorderWin() const { return m_rBorderWin;}\n sal_Bool isCutAllowed() ;\n sal_Bool isCopyAllowed() ;\n sal_Bool isPasteAllowed();\n virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }\n void copy();\n void cut();\n void paste();\n\n \/** return the qualified name.\n @param _pEntry\n The entry of a table, or query, form, report to get the qualified name.\n If the entry is , the first selected is chosen.\n @return\n the qualified name\n *\/\n ::rtl::OUString getQualifiedName( SvLBoxEntry* _pEntry ) const;\n\n \/** returns if an entry is a leaf\n @param _pEntry\n The entry to check\n @return\n if the entry is a leaf, otherwise \n *\/\n sal_Bool isLeaf(SvLBoxEntry* _pEntry) const;\n\n \/** returns if one of the selected entries is a leaf\n @return\n if the entry is a leaf, otherwise \n *\/\n sal_Bool isALeafSelected() const;\n\n \/** select all entries in the detail page\n *\/\n void selectAll();\n\n \/\/\/ returns if it sorts ascending\n sal_Bool isSortUp() const;\n\n \/\/\/ sort the entries in the detail page down\n void sortDown();\n\n \/\/\/ sort the entries in the detail page up\n void sortUp();\n\n \/\/\/ returns when a detail page was filled\n sal_Bool isFilled() const;\n\n \/\/\/ return the element of currently select entry\n ElementType getElementType() const;\n\n \/** clears the detail pages.\n @param _bTaskAlso\n If the task window will also be cleared.\n *\/\n void clearPages(sal_Bool _bTaskAlso = sal_True);\n\n \/\/\/ returns the count of entries\n sal_Int32 getElementCount();\n\n \/\/\/ returns the count of selected entries\n sal_Int32 getSelectionCount();\n\n \/** returns the element names which are selected\n @param _rNames\n The list will be filled.\n *\/\n void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames ) const;\n\n \/** adds a new object to the detail page.\n @param _eType\n The type where the entry shold be appended.\n @param _rName\n The name of the object to be inserted\n @param _rObject\n The object to add.\n @param _rxConn\n If we insert a table, the connection must be set.\n *\/\n SvLBoxEntry* elementAdded(ElementType eType\n ,const ::rtl::OUString& _rName\n ,const ::com::sun::star::uno::Any& _rObject );\n\n \/** replaces a objects name with a new one\n @param _eType\n The type where the entry shold be appended.\n @param _rOldName\n The old name of the object to be replaced\n @param _rNewName\n The new name of the object to be replaced\n @param _rxConn\n If we insert a table, the connection must be set.\n @param _xObject\n The object which was replaced\n *\/\n void elementReplaced(ElementType eType\n ,const ::rtl::OUString& _rOldName\n ,const ::rtl::OUString& _rNewName );\n\n \/** removes an element from the detail page.\n @param _eType\n The type where the entry shold be appended.\n @param _rName\n The name of the element to be removed.\n @param _rxConn\n If we remove a table, the connection must be set.\n *\/\n void elementRemoved(ElementType _eType\n ,const ::rtl::OUString& _rName );\n\n \/\/\/ returns the preview mode\n PreviewMode getPreviewMode();\n\n \/\/\/ if the preview is enabled\n sal_Bool isPreviewEnabled();\n\n\n \/** switches to the given preview mode\n @param _eMode\n the mode to set for the preview\n *\/\n void switchPreview(PreviewMode _eMode);\n\n \/** shows the Preview of the content when it is enabled.\n @param _xContent\n The content which must support the \"preview\" command.\n *\/\n void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent);\n\n \/** shows the Preview of a table or query\n @param _sDataSourceName\n the name of the data source\n @param _sName\n the name of table or query\n @param _bTable\n if it is a table, otherwise \n @return void\n *\/\n void showPreview( const ::rtl::OUString& _sDataSourceName,\n const ::rtl::OUString& _sName,\n sal_Bool _bTable);\n\n SvLBoxEntry* getEntry( const Point& _aPoint ) const;\n\n \/** a command entry was selected\n @param _sCommand\n The command to be executed.\n *\/\n void onCreationClick( const ::rtl::OUString& _sCommand);\n };\n}\n#endif \/\/ DBAUI_APPDETAILVIEW_HXX\n\nINTEGRATION: CWS dba23ui (1.13.48); FILE MERGED 2007\/05\/19 21:25:35 fs 1.13.48.2: RESYNC: (1.13-1.14); FILE MERGED 2006\/12\/21 08:30:59 fs 1.13.48.1: #i72799# enhanced mnemonics handling, now also for the task pane \/ refactored the task pane initialization\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AppDetailView.hxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: obo $ $Date: 2007-06-12 05:32:49 $\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 DBAUI_APPDETAILVIEW_HXX\n#define DBAUI_APPDETAILVIEW_HXX\n\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_\n#include \n#endif\n#ifndef _SV_SPLIT_HXX\n#include \n#endif\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n#ifndef _SV_MNEMONIC_HXX\n#include \n#endif\n#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX\n#include \"IClipBoardTest.hxx\"\n#endif\n#ifndef DBAUI_TITLE_WINDOW_HXX\n#include \"AppTitleWindow.hxx\"\n#endif\n#ifndef DBAUI_APPELEMENTTYPE_HXX\n#include \"AppElementType.hxx\"\n#endif\n#ifndef _SVTREEBOX_HXX\n#include \n#endif\n#ifndef DBAUI_VERTSPLITVIEW_HXX\n#include \"VertSplitView.hxx\"\n#endif\n\n#include \n\nclass SvLBoxEntry;\n\nnamespace dbaui\n{\n class OApplicationController;\n class OAppBorderWindow;\n class OApplicationDetailView;\n class OAppDetailPageHelper;\n class OTasksWindow;\n\n class OCreationList : public SvTreeListBox\n {\n OTasksWindow& m_rTaskWindow;\n\n \/\/ members related to drawing the currently hovered\/selected entry\n SvLBoxEntry* m_pMouseDownEntry;\n SvLBoxEntry* m_pLastActiveEntry;\n Color m_aOriginalBackgroundColor;\n Font m_aOriginalFont;\n\n public:\n OCreationList( OTasksWindow& _rParent );\n \/\/ window overloads\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void KeyInput( const KeyEvent& rKEvt );\n virtual void Paint( const Rectangle& rRect );\n virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel );\n virtual void GetFocus();\n virtual void LoseFocus();\n\n inline void resetLastActive() { m_pLastActiveEntry = NULL;}\n\n void updateHelpText();\n\n protected:\n virtual void PreparePaint( SvLBoxEntry* _pEntry );\n virtual Rectangle GetFocusRect( SvLBoxEntry* _pEntry, long _nLine );\n virtual void ModelHasCleared();\n\n \/\/ IMnemonicEntryList\n virtual void SelectSearchEntry( const void* _pEntry );\n virtual void ExecuteSearchEntry( const void* _pEntry );\n\n private:\n void onSelected( SvLBoxEntry* _pEntry ) const;\n \/** sets a new current entry, and invalidates the old and the new one, if necessary\n @return if and only if the \"current entry\" changed\n *\/\n bool setCurrentEntryInvalidate( SvLBoxEntry* _pEntry );\n };\n\n struct TaskEntry\n {\n ::rtl::OUString sUNOCommand;\n USHORT nHelpID;\n String sTitle;\n bool bHideWhenDisabled;\n \/\/ TODO: we should be consistent in the task pane and the menus\/toolbars:\n \/\/ If an entry is disabled in the latter, it should also be disabled in the former.\n \/\/ If an entry is *hidden* in the former, it should also be hidden in the latter.\n\n TaskEntry( const sal_Char* _pAsciiUNOCommand, USHORT _nHelpID, USHORT _nTitleResourceID, bool _bHideWhenDisabled = false );\n };\n typedef ::std::vector< TaskEntry > TaskEntryList;\n\n struct TaskPaneData\n {\n \/\/\/ the tasks available in the pane\n TaskEntryList aTasks;\n \/\/\/ the resource ID for the title of the pane\n USHORT nTitleId;\n };\n\n class OTasksWindow : public Window\n {\n OCreationList m_aCreation;\n FixedText m_aDescription;\n FixedText m_aHelpText;\n FixedLine m_aFL;\n OApplicationDetailView* m_pDetailView;\n\n DECL_LINK( OnEntrySelectHdl, SvTreeListBox* );\n void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );\n protected:\n virtual void DataChanged(const DataChangedEvent& rDCEvt);\n public:\n OTasksWindow(Window* _pParent,OApplicationDetailView* _pDetailView);\n virtual ~OTasksWindow();\n\n \/\/ window overloads\n virtual void Resize();\n\n OApplicationDetailView* getDetailView() const { return m_pDetailView; }\n\n \/\/\/ fills the Creation listbox with the necessary strings and images\n void fillTaskEntryList( const TaskEntryList& _rList );\n\n inline bool HandleKeyInput( const KeyEvent& _rKEvt )\n {\n return m_aCreation.HandleKeyInput( _rKEvt );\n }\n\n void Clear();\n void setHelpText(USHORT _nId);\n };\n \/\/==================================================================\n class OApplicationDetailView : public OSplitterView\n , public IClipboardTest\n {\n Splitter m_aHorzSplitter;\n OTitleWindow m_aTasks;\n OTitleWindow m_aContainer;\n OAppBorderWindow& m_rBorderWin; \/\/ my parent\n OAppDetailPageHelper* m_pControlHelper;\n ::std::vector< TaskPaneData > m_aTaskPaneData;\n MnemonicGenerator m_aExternalMnemonics;\n\n void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );\n\n protected:\n virtual void DataChanged(const DataChangedEvent& rDCEvt);\n\n public:\n OApplicationDetailView(OAppBorderWindow& _rParent,PreviewMode _ePreviewMode);\n virtual ~OApplicationDetailView();\n \/\/ window overloads\n \/\/ virtual void Resize();\n virtual void GetFocus();\n\n \/** creates the tables page\n @param _xConnection\n The connection to get the table names\n *\/\n void createTablesPage(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection);\n\n \/** creates the page for the specific type.\n @param _eType\n The type which should be created. E_TABLE isn't allowed.\n @param _xContainer\n The container of the elements to be inserted.\n *\/\n void createPage(ElementType _eType,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer);\n\n void setTaskExternalMnemonics( MnemonicGenerator& _rMnemonics );\n\n \/** called to give the window the chance to intercept key events, while it has not\n the focus\n\n @return if and only if the event has been handled, and should not\n not be further processed\n *\/\n bool interceptKeyInput( const KeyEvent& _rEvent );\n\n inline OAppBorderWindow& getBorderWin() const { return m_rBorderWin; }\n inline OTasksWindow& getTasksWindow() const { return *static_cast< OTasksWindow* >( m_aTasks.getChildWindow() ); }\n\n sal_Bool isCutAllowed() ;\n sal_Bool isCopyAllowed() ;\n sal_Bool isPasteAllowed();\n virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }\n void copy();\n void cut();\n void paste();\n\n \/** return the qualified name.\n @param _pEntry\n The entry of a table, or query, form, report to get the qualified name.\n If the entry is , the first selected is chosen.\n @return\n the qualified name\n *\/\n ::rtl::OUString getQualifiedName( SvLBoxEntry* _pEntry ) const;\n\n \/** returns if an entry is a leaf\n @param _pEntry\n The entry to check\n @return\n if the entry is a leaf, otherwise \n *\/\n sal_Bool isLeaf(SvLBoxEntry* _pEntry) const;\n\n \/** returns if one of the selected entries is a leaf\n @return\n if the entry is a leaf, otherwise \n *\/\n sal_Bool isALeafSelected() const;\n\n \/** select all entries in the detail page\n *\/\n void selectAll();\n\n \/\/\/ returns if it sorts ascending\n sal_Bool isSortUp() const;\n\n \/\/\/ sort the entries in the detail page down\n void sortDown();\n\n \/\/\/ sort the entries in the detail page up\n void sortUp();\n\n \/\/\/ returns when a detail page was filled\n sal_Bool isFilled() const;\n\n \/\/\/ return the element of currently select entry\n ElementType getElementType() const;\n\n \/** clears the detail pages.\n @param _bTaskAlso\n If the task window will also be cleared.\n *\/\n void clearPages(sal_Bool _bTaskAlso = sal_True);\n\n \/\/\/ returns the count of entries\n sal_Int32 getElementCount();\n\n \/\/\/ returns the count of selected entries\n sal_Int32 getSelectionCount();\n\n \/** returns the element names which are selected\n @param _rNames\n The list will be filled.\n *\/\n void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames ) const;\n\n \/** adds a new object to the detail page.\n @param _eType\n The type where the entry shold be appended.\n @param _rName\n The name of the object to be inserted\n @param _rObject\n The object to add.\n @param _rxConn\n If we insert a table, the connection must be set.\n *\/\n SvLBoxEntry* elementAdded(ElementType eType\n ,const ::rtl::OUString& _rName\n ,const ::com::sun::star::uno::Any& _rObject );\n\n \/** replaces a objects name with a new one\n @param _eType\n The type where the entry shold be appended.\n @param _rOldName\n The old name of the object to be replaced\n @param _rNewName\n The new name of the object to be replaced\n @param _rxConn\n If we insert a table, the connection must be set.\n @param _xObject\n The object which was replaced\n *\/\n void elementReplaced(ElementType eType\n ,const ::rtl::OUString& _rOldName\n ,const ::rtl::OUString& _rNewName );\n\n \/** removes an element from the detail page.\n @param _eType\n The type where the entry shold be appended.\n @param _rName\n The name of the element to be removed.\n @param _rxConn\n If we remove a table, the connection must be set.\n *\/\n void elementRemoved(ElementType _eType\n ,const ::rtl::OUString& _rName );\n\n \/\/\/ returns the preview mode\n PreviewMode getPreviewMode();\n\n \/\/\/ if the preview is enabled\n sal_Bool isPreviewEnabled();\n\n\n \/** switches to the given preview mode\n @param _eMode\n the mode to set for the preview\n *\/\n void switchPreview(PreviewMode _eMode);\n\n \/** shows the Preview of the content when it is enabled.\n @param _xContent\n The content which must support the \"preview\" command.\n *\/\n void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent);\n\n \/** shows the Preview of a table or query\n @param _sDataSourceName\n the name of the data source\n @param _sName\n the name of table or query\n @param _bTable\n if it is a table, otherwise \n @return void\n *\/\n void showPreview( const ::rtl::OUString& _sDataSourceName,\n const ::rtl::OUString& _sName,\n sal_Bool _bTable);\n\n SvLBoxEntry* getEntry( const Point& _aPoint ) const;\n\n \/** a command entry was selected\n @param _sCommand\n The command to be executed.\n *\/\n void onCreationClick( const ::rtl::OUString& _sCommand);\n\n private:\n void impl_createPage(\n ElementType _eType,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxNonTableElements\n );\n\n const TaskPaneData& impl_getTaskPaneData( ElementType _eType );\n void impl_fillTaskPaneData( ElementType _eType, TaskPaneData& _rData ) const;\n };\n}\n#endif \/\/ DBAUI_APPDETAILVIEW_HXX\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nclass JsonArray_Parser_Tests : public testing::Test\n{\nprotected:\n StaticJsonBuffer<42> json;\n};\n\nTEST_F(JsonArray_Parser_Tests, EmptyArray)\n{\n JsonArray array = json.parseArray(\"[]\");\n\n EXPECT_TRUE(array.success());\n EXPECT_EQ(0, array.size());\n}\n\nTEST_F(JsonArray_Parser_Tests, ArrayWithNoEnd)\n{\n JsonArray array = json.parseArray(\"[\");\n\n EXPECT_FALSE(array.success());\n EXPECT_EQ(0, array.size());\n}\n\nTEST_F(JsonArray_Parser_Tests, EmptyArrayWithLeadingSpaces)\n{\n JsonArray array = json.parseArray(\" []\");\n\n EXPECT_TRUE(array.success());\n EXPECT_EQ(0, array.size());\n}\n\nTEST_F(JsonArray_Parser_Tests, Garbage)\n{\n JsonArray array = json.parseArray(\"%*$£¤\");\n\n EXPECT_FALSE(array.success());\n EXPECT_EQ(0, array.size());\n}\n\nTEST_F(JsonArray_Parser_Tests, OneInteger)\n{\n JsonArray array = json.parseArray(\"[42]\");\n\n EXPECT_TRUE(array.success());\n EXPECT_EQ(1, array.size());\n EXPECT_EQ(42, static_cast(array[0])); \n}\n\nTEST_F(JsonArray_Parser_Tests, TwoIntegers)\n{\n JsonArray array = json.parseArray(\"[42,84]\");\n\n EXPECT_TRUE(array.success());\n\n EXPECT_EQ(2, array.size());\n EXPECT_EQ(42, static_cast(array[0])); \n EXPECT_EQ(84, static_cast(array[1])); \n}Added test for spaces in arrays#include \n#include \n#include \n\nclass JsonArray_Parser_Tests : public testing::Test\n{\nprotected:\n StaticJsonBuffer<42> json;\n};\n\nTEST_F(JsonArray_Parser_Tests, EmptyArray)\n{\n JsonArray array = json.parseArray(\"[]\");\n\n EXPECT_TRUE(array.success());\n EXPECT_EQ(0, array.size());\n}\n\nTEST_F(JsonArray_Parser_Tests, ArrayWithNoEnd)\n{\n JsonArray array = json.parseArray(\"[\");\n\n EXPECT_FALSE(array.success());\n EXPECT_EQ(0, array.size());\n}\n\nTEST_F(JsonArray_Parser_Tests, EmptyArrayWithLeadingSpaces)\n{\n JsonArray array = json.parseArray(\" []\");\n\n EXPECT_TRUE(array.success());\n EXPECT_EQ(0, array.size());\n}\n\nTEST_F(JsonArray_Parser_Tests, Garbage)\n{\n JsonArray array = json.parseArray(\"%*$£¤\");\n\n EXPECT_FALSE(array.success());\n EXPECT_EQ(0, array.size());\n}\n\nTEST_F(JsonArray_Parser_Tests, OneInteger)\n{\n JsonArray array = json.parseArray(\"[42]\");\n\n EXPECT_TRUE(array.success());\n EXPECT_EQ(1, array.size());\n EXPECT_EQ(42, static_cast(array[0]));\n}\n\nTEST_F(JsonArray_Parser_Tests, OneIntegerWithSpacesBefore)\n{\n JsonArray array = json.parseArray(\"[ \\t\\r\\n42]\");\n\n EXPECT_TRUE(array.success());\n EXPECT_EQ(1, array.size());\n EXPECT_EQ(42, static_cast(array[0]));\n}\n\nTEST_F(JsonArray_Parser_Tests, OneIntegerWithSpaceAfter)\n{\n JsonArray array = json.parseArray(\"[42 \\t\\r\\n]\");\n\n EXPECT_TRUE(array.success());\n EXPECT_EQ(1, array.size());\n EXPECT_EQ(42, static_cast(array[0]));\n}\n\nTEST_F(JsonArray_Parser_Tests, TwoIntegers)\n{\n JsonArray array = json.parseArray(\"[42,84]\");\n\n EXPECT_TRUE(array.success());\n\n EXPECT_EQ(2, array.size());\n EXPECT_EQ(42, static_cast(array[0])); \n EXPECT_EQ(84, static_cast(array[1])); \n}<|endoftext|>"} {"text":"#ifndef ITER_DROPWHILE_H_\n#define ITER_DROPWHILE_H_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n\nnamespace iter {\n\n template \n class DropWhile;\n\n template \n DropWhile dropwhile(FilterFunc, Container&&);\n\n template \n DropWhile> dropwhile(\n FilterFunc, std::initializer_list);\n\n template \n class DropWhile {\n private:\n Container container;\n FilterFunc filter_func;\n\n friend DropWhile dropwhile(FilterFunc, Container&&);\n\n template \n friend DropWhile> dropwhile(\n FF, std::initializer_list);\n\n DropWhile(FilterFunc in_filter_func, Container&& in_container)\n : container(std::forward(in_container)),\n filter_func(in_filter_func) {}\n\n public:\n class Iterator : public std::iterator> {\n private:\n using Holder = DerefHolder>;\n iterator_type sub_iter;\n iterator_type sub_end;\n Holder item;\n FilterFunc* filter_func;\n\n void inc_sub_iter() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n \/\/ skip all values for which the predicate is true\n void skip_passes() {\n while (this->sub_iter != this->sub_end\n && (*this->filter_func)(this->item.get())) {\n this->inc_sub_iter();\n }\n }\n\n public:\n Iterator(iterator_type&& iter, iterator_type&& end,\n FilterFunc& in_filter_func)\n : sub_iter{std::move(iter)},\n sub_end{std::move(end)},\n filter_func(&in_filter_func) {\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n this->skip_passes();\n }\n\n typename Holder::reference operator*() {\n return this->item.get();\n }\n\n typename Holder::pointer operator->() {\n return this->item.get_ptr();\n }\n\n Iterator& operator++() {\n this->inc_sub_iter();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container),\n this->filter_func};\n }\n };\n\n template \n DropWhile dropwhile(\n FilterFunc filter_func, Container&& container) {\n return {filter_func, std::forward(container)};\n }\n\n template \n DropWhile> dropwhile(\n FilterFunc filter_func, std::initializer_list il) {\n return {filter_func, std::move(il)};\n }\n}\n\n#endif\nmoves Dropper into impl{ }#ifndef ITER_DROPWHILE_H_\n#define ITER_DROPWHILE_H_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Dropper;\n }\n\n template \n impl::Dropper dropwhile(FilterFunc, Container&&);\n\n template \n impl::Dropper> dropwhile(\n FilterFunc, std::initializer_list);\n}\n\ntemplate \nclass iter::impl::Dropper {\n private:\n Container container;\n FilterFunc filter_func;\n\n friend Dropper iter::dropwhile(\n FilterFunc, Container&&);\n\n template \n friend Dropper> iter::dropwhile(\n FF, std::initializer_list);\n\n Dropper(FilterFunc in_filter_func, Container&& in_container)\n : container(std::forward(in_container)),\n filter_func(in_filter_func) {}\n\n public:\n class Iterator : public std::iterator> {\n private:\n using Holder = DerefHolder>;\n iterator_type sub_iter;\n iterator_type sub_end;\n Holder item;\n FilterFunc* filter_func;\n\n void inc_sub_iter() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n \/\/ skip all values for which the predicate is true\n void skip_passes() {\n while (this->sub_iter != this->sub_end\n && (*this->filter_func)(this->item.get())) {\n this->inc_sub_iter();\n }\n }\n\n public:\n Iterator(iterator_type&& iter, iterator_type&& end,\n FilterFunc& in_filter_func)\n : sub_iter{std::move(iter)},\n sub_end{std::move(end)},\n filter_func(&in_filter_func) {\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n this->skip_passes();\n }\n\n typename Holder::reference operator*() {\n return this->item.get();\n }\n\n typename Holder::pointer operator->() {\n return this->item.get_ptr();\n }\n\n Iterator& operator++() {\n this->inc_sub_iter();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container),\n this->filter_func};\n }\n};\n\ntemplate \niter::impl::Dropper iter::dropwhile(\n FilterFunc filter_func, Container&& container) {\n return {filter_func, std::forward(container)};\n}\n\ntemplate \niter::impl::Dropper> iter::dropwhile(\n FilterFunc filter_func, std::initializer_list il) {\n return {filter_func, std::move(il)};\n}\n\n#endif\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n * Copyright (C) 2016 Andrew Zonenberg and contributors *\n * *\n * This program is free software; you can redistribute it and\/or modify it under the terms of the GNU Lesser General *\n * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) *\n * any later version. *\n * *\n * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *\n * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for *\n * more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may *\n * find one here: *\n * https:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.txt *\n * or you may search the http:\/\/www.gnu.org website for the version 2.1 license, or you may write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *\n **********************************************************************************************************************\/\n\n#include \n#include \n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction \/ destruction\n\nGreenpak4Comparator::Greenpak4Comparator(\n\t\tGreenpak4Device* device,\n\t\tunsigned int cmpnum,\n\t\tunsigned int matrix,\n\t\tunsigned int ibase,\n\t\tunsigned int oword,\n\t\tunsigned int cbase_isrc,\n\t\tunsigned int cbase_bw,\n\t\tunsigned int cbase_gain,\n\t\tunsigned int cbase_vin,\n\t\tunsigned int cbase_hyst,\n\t\tunsigned int cbase_vref\n\t\t)\n\t\t: Greenpak4BitstreamEntity(device, matrix, ibase, oword, -1)\n\t\t, m_pwren(device->GetGround())\n\t\t, m_vin(device->GetGround())\n\t\t, m_vref(device->GetGround())\n\t\t, m_cmpNum(cmpnum)\n\t\t, m_cbaseIsrc(cbase_isrc)\n\t\t, m_cbaseBw(cbase_bw)\n\t\t, m_cbaseGain(cbase_gain)\n\t\t, m_cbaseVin(cbase_vin)\n\t\t, m_cbaseHyst(cbase_hyst)\n\t\t, m_cbaseVref(cbase_vref)\n\t\t, m_bandwidthHigh(true)\n\t\t, m_vinAtten(1)\n\t\t, m_isrcEn(false)\n\t\t, m_hysteresis(0)\n{\n}\n\nGreenpak4Comparator::~Greenpak4Comparator()\n{\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Accessors\n\nstring Greenpak4Comparator::GetDescription()\n{\n\tchar buf[128];\n\tsnprintf(buf, sizeof(buf), \"ACMP_%u\", m_cmpNum);\n\treturn string(buf);\n}\n\nvector Greenpak4Comparator::GetInputPorts() const\n{\n\tvector r;\n\tr.push_back(\"PWREN\");\n\treturn r;\n}\n\nvoid Greenpak4Comparator::SetInput(string port, Greenpak4EntityOutput src)\n{\n\tif(port == \"PWREN\")\n\t\tm_pwren = src;\n\tif(port == \"VIN\")\n\t\tm_vin = src;\n\tif(port == \"VREF\")\n\t\tm_vref = src;\n\n\t\/\/ignore anything else silently (should not be possible since synthesis would error out)\n}\n\nvector Greenpak4Comparator::GetOutputPorts() const\n{\n\tvector r;\n\tr.push_back(\"OUT\");\n\treturn r;\n}\n\nunsigned int Greenpak4Comparator::GetOutputNetNumber(string port)\n{\n\tif(port == \"OUT\")\n\t\treturn m_outputBaseWord;\n\telse\n\t\treturn -1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Serialization\n\nbool Greenpak4Comparator::CommitChanges()\n{\n\t\/\/Get our cell, or bail if we're unassigned\n\tauto ncell = dynamic_cast(GetNetlistEntity());\n\tif(ncell == NULL)\n\t\treturn true;\n\n\tif(ncell->HasParameter(\"BANDWIDTH\"))\n\t\tm_bandwidthHigh = (ncell->m_parameters[\"BANDWIDTH\"] == \"HIGH\") ? true : false;\n\n\tif(ncell->HasParameter(\"VIN_ATTEN\"))\n\t\tm_vinAtten = (atoi(ncell->m_parameters[\"VIN_ATTEN\"].c_str()));\n\n\tif(ncell->HasParameter(\"VIN_ISRC_EN\"))\n\t\tm_isrcEn = (ncell->m_parameters[\"VIN_ISRC_EN\"] == \"1\") ? true : false;\n\n\tif(ncell->HasParameter(\"HYSTERESIS\"))\n\t\tm_hysteresis = (atoi(ncell->m_parameters[\"HYSTERESIS\"].c_str()));\n\n\treturn true;\n}\n\nbool Greenpak4Comparator::Load(bool* \/*bitstream*\/)\n{\n\t\/\/TODO: Do our inputs\n\tLogError(\"Unimplemented\\n\");\n\treturn false;\n}\n\nbool Greenpak4Comparator::Save(bool* bitstream)\n{\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ INPUT BUS\n\n\tif(!WriteMatrixSelector(bitstream, m_inputBaseWord, m_pwren))\n\t\treturn false;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ CONFIGURATION\n\n\t\/\/Input current source (iff present)\n\tif(m_cbaseIsrc > 0)\n\t\tbitstream[m_cbaseIsrc] = m_isrcEn;\n\n\t\/\/Low bandwidth selector\n\tif(m_cbaseBw > 0)\n\t\tbitstream[m_cbaseBw] = !m_bandwidthHigh;\n\n\t\/\/Gain selector\n\tif(m_cbaseGain > 0)\n\t{\n\t\tswitch(m_vinAtten)\n\t\t{\n\t\t\tcase 1:\n\t\t\t\tbitstream[m_cbaseGain + 1] = false;\n\t\t\t\tbitstream[m_cbaseGain + 0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase 2:\n\t\t\t\tbitstream[m_cbaseGain + 1] = false;\n\t\t\t\tbitstream[m_cbaseGain + 0] = true;\n\t\t\t\tbreak;\n\n\t\t\tcase 3:\n\t\t\t\tbitstream[m_cbaseGain + 1] = true;\n\t\t\t\tbitstream[m_cbaseGain + 0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase 4:\n\t\t\t\tbitstream[m_cbaseGain + 1] = true;\n\t\t\t\tbitstream[m_cbaseGain + 0] = true;\n\t\t\t\tbreak;\n\n\n\t\t\tdefault:\n\t\t\t\tLogError(\"Invalid ACMP attenuation (must be 1\/2\/3\/4)\\n\");\n\t\t\t\treturn false;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(m_vinAtten != 1)\n\t\t{\n\t\t\tLogError(\"Invalid ACMP attenuation (must be 1 for %s)\\n\",\n\t\t\t GetDescription().c_str());\n\t\t}\n\t}\n\n\t\/\/Hysteresis\n\tif(m_cbaseHyst > 0)\n\t{\n\t\tswitch(m_hysteresis)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tbitstream[m_cbaseHyst + 1] = false;\n\t\t\t\tbitstream[m_cbaseHyst + 0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase 25:\n\t\t\t\tbitstream[m_cbaseHyst + 1] = false;\n\t\t\t\tbitstream[m_cbaseHyst + 0] = true;\n\t\t\t\tbreak;\n\n\t\t\tcase 50:\n\t\t\t\tbitstream[m_cbaseHyst + 1] = true;\n\t\t\t\tbitstream[m_cbaseHyst + 0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase 200:\n\t\t\t\tbitstream[m_cbaseHyst + 1] = true;\n\t\t\t\tbitstream[m_cbaseHyst + 0] = true;\n\t\t\t\tbreak;\n\n\n\t\t\tdefault:\n\t\t\t\tLogError(\"Invalid ACMP hysteresis (must be 0\/25\/50\/200)\\n\");\n\t\t\t\treturn false;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(m_hysteresis != 0)\n\t\t{\n\t\t\tLogError(\"Invalid ACMP hysteresis (must be 0 for %s)\\n\",\n\t\t\t GetDescription().c_str());\n\t\t}\n\t}\n\n\t\/\/If input is ground, then don't hook it up (we're not active)\n\tif(m_vin.IsPowerRail() && !m_vin.GetPowerRailValue())\n\t{}\n\n\t\/\/Invalid input\n\telse if(m_muxsels.find(m_vin) == m_muxsels.end())\n\t{\n\t\tLogError(\"Invalid ACMP input (tried to feed %s to %s)\\n\",\n\t\t\tm_vin.GetDescription().c_str(), GetDescription().c_str());\n\t\treturn false;\n\t}\n\n\t\/\/Valid input, hook it up\n\telse\n\t{\n\t\tunsigned int sel = m_muxsels[m_vin];\n\n\t\t\/\/Bitstream is zero-cleared at start of the writing process so high zero bits don't need to be written\n\n\t\t\/\/2-bit mux selector? Write the high bit\n\t\tif(sel & 2)\n\t\t\tbitstream[m_cbaseVin + 1] = true;\n\n\t\t\/\/Write the low bit\n\t\tbitstream[m_cbaseVin] = (sel & 1) ? true : false;\n\t}\n\n\t\/\/Configure the voltage reference cell\n\tunsigned int muxsel = 0;\n\tif(m_vref.IsVoltageReference())\n\t{\n\t\tGreenpak4VoltageReference* vref = dynamic_cast(m_vref.GetRealEntity());\n\t\tmuxsel = vref->GetACMPMuxSel();\n\n\t\tif(muxsel > 0x1F)\n\t\t{\n\t\t\tLogError(\"Invalid mux selector %u (should be 0...31)\\n\", muxsel);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/Unused vrefs can be tied to ground\n\telse if(m_vref.IsPowerRail() && !m_vref.GetPowerRailValue())\n\t{\n\t\t\/\/emulate ground by setting 50 mV, the lowest threshold\n\t\tmuxsel = 0;\n\t}\n\n\t\/\/Vref must be sourced by a GP_VREF cell, complain if it's not\n\telse\n\t{\n\t\tLogError(\n\t\t\t\"Invalid ACMP reference voltage source for %s\\n\"\n\t\t\t\"\t(got %s, must be buffered by a GP_VREF)\\n\",\n\t\t\tGetDescription().c_str(),\n\t\t\tm_vref.GetOutputName().c_str()\n\t\t\t);\n\t}\n\n\tbitstream[m_cbaseVref + 0] = (muxsel & 1) ? true : false;\n\tbitstream[m_cbaseVref + 1] = (muxsel & 2) ? true : false;\n\tbitstream[m_cbaseVref + 2] = (muxsel & 4) ? true : false;\n\tbitstream[m_cbaseVref + 3] = (muxsel & 8) ? true : false;\n\tbitstream[m_cbaseVref + 4] = (muxsel & 16) ? true : false;\n\n\treturn true;\n}\nGreenpak4Comparator: Don't clobber random bitstream addresses when configuring ACMP_5 (which has no input mux)\/***********************************************************************************************************************\n * Copyright (C) 2016 Andrew Zonenberg and contributors *\n * *\n * This program is free software; you can redistribute it and\/or modify it under the terms of the GNU Lesser General *\n * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) *\n * any later version. *\n * *\n * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *\n * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for *\n * more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may *\n * find one here: *\n * https:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.txt *\n * or you may search the http:\/\/www.gnu.org website for the version 2.1 license, or you may write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *\n **********************************************************************************************************************\/\n\n#include \n#include \n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction \/ destruction\n\nGreenpak4Comparator::Greenpak4Comparator(\n\t\tGreenpak4Device* device,\n\t\tunsigned int cmpnum,\n\t\tunsigned int matrix,\n\t\tunsigned int ibase,\n\t\tunsigned int oword,\n\t\tunsigned int cbase_isrc,\n\t\tunsigned int cbase_bw,\n\t\tunsigned int cbase_gain,\n\t\tunsigned int cbase_vin,\n\t\tunsigned int cbase_hyst,\n\t\tunsigned int cbase_vref\n\t\t)\n\t\t: Greenpak4BitstreamEntity(device, matrix, ibase, oword, -1)\n\t\t, m_pwren(device->GetGround())\n\t\t, m_vin(device->GetGround())\n\t\t, m_vref(device->GetGround())\n\t\t, m_cmpNum(cmpnum)\n\t\t, m_cbaseIsrc(cbase_isrc)\n\t\t, m_cbaseBw(cbase_bw)\n\t\t, m_cbaseGain(cbase_gain)\n\t\t, m_cbaseVin(cbase_vin)\n\t\t, m_cbaseHyst(cbase_hyst)\n\t\t, m_cbaseVref(cbase_vref)\n\t\t, m_bandwidthHigh(true)\n\t\t, m_vinAtten(1)\n\t\t, m_isrcEn(false)\n\t\t, m_hysteresis(0)\n{\n}\n\nGreenpak4Comparator::~Greenpak4Comparator()\n{\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Accessors\n\nstring Greenpak4Comparator::GetDescription()\n{\n\tchar buf[128];\n\tsnprintf(buf, sizeof(buf), \"ACMP_%u\", m_cmpNum);\n\treturn string(buf);\n}\n\nvector Greenpak4Comparator::GetInputPorts() const\n{\n\tvector r;\n\tr.push_back(\"PWREN\");\n\treturn r;\n}\n\nvoid Greenpak4Comparator::SetInput(string port, Greenpak4EntityOutput src)\n{\n\tif(port == \"PWREN\")\n\t\tm_pwren = src;\n\tif(port == \"VIN\")\n\t\tm_vin = src;\n\tif(port == \"VREF\")\n\t\tm_vref = src;\n\n\t\/\/ignore anything else silently (should not be possible since synthesis would error out)\n}\n\nvector Greenpak4Comparator::GetOutputPorts() const\n{\n\tvector r;\n\tr.push_back(\"OUT\");\n\treturn r;\n}\n\nunsigned int Greenpak4Comparator::GetOutputNetNumber(string port)\n{\n\tif(port == \"OUT\")\n\t\treturn m_outputBaseWord;\n\telse\n\t\treturn -1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Serialization\n\nbool Greenpak4Comparator::CommitChanges()\n{\n\t\/\/Get our cell, or bail if we're unassigned\n\tauto ncell = dynamic_cast(GetNetlistEntity());\n\tif(ncell == NULL)\n\t\treturn true;\n\n\tif(ncell->HasParameter(\"BANDWIDTH\"))\n\t\tm_bandwidthHigh = (ncell->m_parameters[\"BANDWIDTH\"] == \"HIGH\") ? true : false;\n\n\tif(ncell->HasParameter(\"VIN_ATTEN\"))\n\t\tm_vinAtten = (atoi(ncell->m_parameters[\"VIN_ATTEN\"].c_str()));\n\n\tif(ncell->HasParameter(\"VIN_ISRC_EN\"))\n\t\tm_isrcEn = (ncell->m_parameters[\"VIN_ISRC_EN\"] == \"1\") ? true : false;\n\n\tif(ncell->HasParameter(\"HYSTERESIS\"))\n\t\tm_hysteresis = (atoi(ncell->m_parameters[\"HYSTERESIS\"].c_str()));\n\n\treturn true;\n}\n\nbool Greenpak4Comparator::Load(bool* \/*bitstream*\/)\n{\n\t\/\/TODO: Do our inputs\n\tLogError(\"Unimplemented\\n\");\n\treturn false;\n}\n\nbool Greenpak4Comparator::Save(bool* bitstream)\n{\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ INPUT BUS\n\n\tif(!WriteMatrixSelector(bitstream, m_inputBaseWord, m_pwren))\n\t\treturn false;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ CONFIGURATION\n\n\t\/\/Input current source (iff present)\n\tif(m_cbaseIsrc > 0)\n\t\tbitstream[m_cbaseIsrc] = m_isrcEn;\n\n\t\/\/Low bandwidth selector\n\tif(m_cbaseBw > 0)\n\t\tbitstream[m_cbaseBw] = !m_bandwidthHigh;\n\n\t\/\/Gain selector\n\tif(m_cbaseGain > 0)\n\t{\n\t\tswitch(m_vinAtten)\n\t\t{\n\t\t\tcase 1:\n\t\t\t\tbitstream[m_cbaseGain + 1] = false;\n\t\t\t\tbitstream[m_cbaseGain + 0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase 2:\n\t\t\t\tbitstream[m_cbaseGain + 1] = false;\n\t\t\t\tbitstream[m_cbaseGain + 0] = true;\n\t\t\t\tbreak;\n\n\t\t\tcase 3:\n\t\t\t\tbitstream[m_cbaseGain + 1] = true;\n\t\t\t\tbitstream[m_cbaseGain + 0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase 4:\n\t\t\t\tbitstream[m_cbaseGain + 1] = true;\n\t\t\t\tbitstream[m_cbaseGain + 0] = true;\n\t\t\t\tbreak;\n\n\n\t\t\tdefault:\n\t\t\t\tLogError(\"Invalid ACMP attenuation (must be 1\/2\/3\/4)\\n\");\n\t\t\t\treturn false;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(m_vinAtten != 1)\n\t\t{\n\t\t\tLogError(\"Invalid ACMP attenuation (must be 1 for %s)\\n\",\n\t\t\t GetDescription().c_str());\n\t\t}\n\t}\n\n\t\/\/Hysteresis\n\tif(m_cbaseHyst > 0)\n\t{\n\t\tswitch(m_hysteresis)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tbitstream[m_cbaseHyst + 1] = false;\n\t\t\t\tbitstream[m_cbaseHyst + 0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase 25:\n\t\t\t\tbitstream[m_cbaseHyst + 1] = false;\n\t\t\t\tbitstream[m_cbaseHyst + 0] = true;\n\t\t\t\tbreak;\n\n\t\t\tcase 50:\n\t\t\t\tbitstream[m_cbaseHyst + 1] = true;\n\t\t\t\tbitstream[m_cbaseHyst + 0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase 200:\n\t\t\t\tbitstream[m_cbaseHyst + 1] = true;\n\t\t\t\tbitstream[m_cbaseHyst + 0] = true;\n\t\t\t\tbreak;\n\n\n\t\t\tdefault:\n\t\t\t\tLogError(\"Invalid ACMP hysteresis (must be 0\/25\/50\/200)\\n\");\n\t\t\t\treturn false;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(m_hysteresis != 0)\n\t\t{\n\t\t\tLogError(\"Invalid ACMP hysteresis (must be 0 for %s)\\n\",\n\t\t\t GetDescription().c_str());\n\t\t}\n\t}\n\n\t\/\/If input is ground, then don't hook it up (we're not active)\n\tif(m_vin.IsPowerRail() && !m_vin.GetPowerRailValue())\n\t{}\n\n\t\/\/Invalid input\n\telse if(m_muxsels.find(m_vin) == m_muxsels.end())\n\t{\n\t\tLogError(\"Invalid ACMP input (tried to feed %s to %s)\\n\",\n\t\t\tm_vin.GetDescription().c_str(), GetDescription().c_str());\n\t\treturn false;\n\t}\n\n\t\/\/Valid input, hook it up.\n\t\/\/BUGFIX: If we only have one input there's no vin config bits so don't write to m_cbaseVin\n\telse if(m_muxsels.size() > 1)\n\t{\n\t\tunsigned int sel = m_muxsels[m_vin];\n\n\t\t\/\/Bitstream is zero-cleared at start of the writing process so high zero bits don't need to be written\n\n\t\t\/\/2-bit mux selector? Write the high bit\n\t\tif(sel & 2)\n\t\t\tbitstream[m_cbaseVin + 1] = true;\n\n\t\t\/\/Write the low bit\n\t\tbitstream[m_cbaseVin] = (sel & 1) ? true : false;\n\t}\n\n\t\/\/Configure the voltage reference cell\n\tunsigned int muxsel = 0;\n\tif(m_vref.IsVoltageReference())\n\t{\n\t\tGreenpak4VoltageReference* vref = dynamic_cast(m_vref.GetRealEntity());\n\t\tmuxsel = vref->GetACMPMuxSel();\n\n\t\tif(muxsel > 0x1F)\n\t\t{\n\t\t\tLogError(\"Invalid mux selector %u (should be 0...31)\\n\", muxsel);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/Unused vrefs can be tied to ground\n\telse if(m_vref.IsPowerRail() && !m_vref.GetPowerRailValue())\n\t{\n\t\t\/\/emulate ground by setting 50 mV, the lowest threshold\n\t\tmuxsel = 0;\n\t}\n\n\t\/\/Vref must be sourced by a GP_VREF cell, complain if it's not\n\telse\n\t{\n\t\tLogError(\n\t\t\t\"Invalid ACMP reference voltage source for %s\\n\"\n\t\t\t\"\t(got %s, must be buffered by a GP_VREF)\\n\",\n\t\t\tGetDescription().c_str(),\n\t\t\tm_vref.GetOutputName().c_str()\n\t\t\t);\n\t}\n\n\tbitstream[m_cbaseVref + 0] = (muxsel & 1) ? true : false;\n\tbitstream[m_cbaseVref + 1] = (muxsel & 2) ? true : false;\n\tbitstream[m_cbaseVref + 2] = (muxsel & 4) ? true : false;\n\tbitstream[m_cbaseVref + 3] = (muxsel & 8) ? true : false;\n\tbitstream[m_cbaseVref + 4] = (muxsel & 16) ? true : false;\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"\/*\n* CallADIOSData.cpp\n*\n* Copyright (C) 2018 by Universitaet Stuttgart (VISUS).\n* Alle Rechte vorbehalten.\n*\/\n\n#include \"stdafx.h\"\n#include \"adios_plugin\/CallADIOSData.h\"\n#include \"mmcore\/utility\/log\/Log.h\"\n#include \n\nnamespace megamol {\nnamespace adios {\n \nCallADIOSData::CallADIOSData()\n : dataHash(0)\n , time(0)\n , frameCount(0)\n , dataptr(nullptr) {\n}\n\n\n\/**\n * \\brief \n *\/\nCallADIOSData::~CallADIOSData(void) = default;\n\n\n\/**\n * \\brief CallADIOSData::setTime\n * \\param time \n *\/\nvoid CallADIOSData::setTime(float time) { this->time = time; }\n\n\n\/**\n * \\brief \n * \\return \n *\/\nfloat CallADIOSData::getTime() const { return this->time; }\n\n\n\/**\n * \\brief Sets variable to inquire.\n * \\param varname: The name of the variable.\n * \\return Returns false if variable is not available, true otherwise.\n *\/\nbool CallADIOSData::inquire(const std::string &varname) {\n if (!this->availableVars.empty()) {\n if (std::find(this->availableVars.begin(), this->availableVars.end(), varname) != this->availableVars.end()) {\n this->inqVars.push_back(varname);\n } else {\n megamol::core::utility::log::Log::DefaultLog.WriteError(\"[CallADIOSData] Variable %s is not in available varialbes\", varname.c_str());\n return false;\n }\n } else {\n megamol::core::utility::log::Log::DefaultLog.WriteError(\"[CallADIOSData] No available Vars. Read header first.\");\n return false;\n }\n \/\/ erase non-unique occurrences\n std::sort(this->inqVars.begin(), this->inqVars.end());\n const auto last = std::unique(this->inqVars.begin(), this->inqVars.end());\n this->inqVars.erase(last, this->inqVars.end());\n return true;\n}\n\nstd::vector CallADIOSData::getVarsToInquire() const { return inqVars; }\n\nstd::vector CallADIOSData::getAvailableVars() const { return availableVars; }\n\nvoid CallADIOSData::setAvailableVars(const std::vector &avars) { this->availableVars = avars; }\n\nvoid CallADIOSData::setData(std::shared_ptr _dta) {\n this->dataptr = _dta; }\n\nstd::shared_ptr CallADIOSData::getData(std::string _str) const { return this->dataptr->at(_str); }\n\nbool CallADIOSData::isInVars(std::string var) {\n return std::find(this->availableVars.begin(), this->availableVars.end(), var) != this->availableVars.end();\n}\n\n} \/\/ end namespace adios\n} \/\/ end namespace megamolsetting the data map now also sets the available vars\/*\n* CallADIOSData.cpp\n*\n* Copyright (C) 2018 by Universitaet Stuttgart (VISUS).\n* Alle Rechte vorbehalten.\n*\/\n\n#include \"stdafx.h\"\n#include \"adios_plugin\/CallADIOSData.h\"\n#include \"mmcore\/utility\/log\/Log.h\"\n#include \n\nnamespace megamol {\nnamespace adios {\n \nCallADIOSData::CallADIOSData()\n : dataHash(0)\n , time(0)\n , frameCount(0)\n , dataptr(nullptr) {\n}\n\n\n\/**\n * \\brief \n *\/\nCallADIOSData::~CallADIOSData(void) = default;\n\n\n\/**\n * \\brief CallADIOSData::setTime\n * \\param time \n *\/\nvoid CallADIOSData::setTime(float time) { this->time = time; }\n\n\n\/**\n * \\brief \n * \\return \n *\/\nfloat CallADIOSData::getTime() const { return this->time; }\n\n\n\/**\n * \\brief Sets variable to inquire.\n * \\param varname: The name of the variable.\n * \\return Returns false if variable is not available, true otherwise.\n *\/\nbool CallADIOSData::inquire(const std::string &varname) {\n if (!this->availableVars.empty()) {\n if (std::find(this->availableVars.begin(), this->availableVars.end(), varname) != this->availableVars.end()) {\n this->inqVars.push_back(varname);\n } else {\n megamol::core::utility::log::Log::DefaultLog.WriteError(\"[CallADIOSData] Variable %s is not in available varialbes\", varname.c_str());\n return false;\n }\n } else {\n megamol::core::utility::log::Log::DefaultLog.WriteError(\"[CallADIOSData] No available Vars. Read header first.\");\n return false;\n }\n \/\/ erase non-unique occurrences\n std::sort(this->inqVars.begin(), this->inqVars.end());\n const auto last = std::unique(this->inqVars.begin(), this->inqVars.end());\n this->inqVars.erase(last, this->inqVars.end());\n return true;\n}\n\nstd::vector CallADIOSData::getVarsToInquire() const { return inqVars; }\n\nstd::vector CallADIOSData::getAvailableVars() const { return availableVars; }\n\nvoid CallADIOSData::setAvailableVars(const std::vector &avars) { this->availableVars = avars; }\n\nvoid CallADIOSData::setData(std::shared_ptr _dta) {\n this->dataptr = _dta;\n availableVars.clear();\n availableVars.reserve(dataptr->size());\n for (auto& entry : *dataptr) {\n availableVars.emplace_back(entry.first);\n }\n}\n\nstd::shared_ptr CallADIOSData::getData(std::string _str) const { return this->dataptr->at(_str); }\n\nbool CallADIOSData::isInVars(std::string var) {\n return std::find(this->availableVars.begin(), this->availableVars.end(), var) != this->availableVars.end();\n}\n\n} \/\/ end namespace adios\n} \/\/ end namespace megamol\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: JoinTableView.hxx,v $\n *\n * $Revision: 1.25 $\n *\n * last change: $Author: hr $ $Date: 2007-11-01 15:16:03 $\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 DBAUI_JOINTABLEVIEW_HXX\n#define DBAUI_JOINTABLEVIEW_HXX\n\n#ifndef _SV_WINDOW_HXX\n#include \n#endif\n#ifndef _SV_TIMER_HXX\n#include \n#endif\n#ifndef _SV_SCRBAR_HXX\n#include \n#endif\n#ifndef _RTTI_HXX\n#include \n#endif\n#ifndef _TRANSFER_HXX\n#include \n#endif\n\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _DBACCESS_UI_CALLBACKS_HXX_\n#include \"callbacks.hxx\"\n#endif\n#include \"TableConnectionData.hxx\"\n#include \"TableWindowData.hxx\"\n#include \n#include \n\nstruct AcceptDropEvent;\nstruct ExecuteDropEvent;\nclass SfxUndoAction;\nnamespace dbaui\n{\n class OTableConnection;\n class OTableWindow;\n struct OJoinExchangeData;\n class OJoinDesignView;\n class OTableWindowData;\n class OJoinDesignViewAccess;\n\n \/\/ this class conatins only the scrollbars to avoid that the tablewindows clip the scrollbars\n class OJoinTableView;\n class OScrollWindowHelper : public Window\n {\n ScrollBar m_aHScrollBar;\n ScrollBar m_aVScrollBar;\n Window* m_pCornerWindow;\n OJoinTableView* m_pTableView;\n\n protected:\n virtual void Resize();\n public:\n OScrollWindowHelper( Window* pParent);\n ~OScrollWindowHelper();\n\n void setTableView(OJoinTableView* _pTableView);\n\n void resetRange(const Point& _aSize);\n\n \/\/ own methods\n ScrollBar* GetHScrollBar() { return &m_aHScrollBar; }\n ScrollBar* GetVScrollBar() { return &m_aVScrollBar; }\n };\n\n\n class OJoinTableView : public Window\n ,public IDragTransferableListener\n ,public DropTargetHelper\n {\n friend class OJoinMoveTabWinUndoAct;\n public:\n DECLARE_STL_USTRINGACCESS_MAP(OTableWindow*,OTableWindowMap);\n private:\n OTableWindowMap m_aTableMap;\n ::std::vector m_vTableConnection;\n\n Timer m_aDragScrollTimer;\n Rectangle m_aDragRect;\n Rectangle m_aSizingRect;\n Point m_aDragOffset;\n Point m_aScrollOffset;\n Point m_ptPrevDraggingPos;\n Size m_aOutputSize;\n\n\n OTableWindow* m_pDragWin;\n OTableWindow* m_pSizingWin;\n OTableConnection* m_pSelectedConn;\n\n\n BOOL m_bTrackingInitiallyMoved;\n\n DECL_LINK(OnDragScrollTimer, void*);\n\n protected:\n OTableWindow* m_pLastFocusTabWin;\n OJoinDesignView* m_pView;\n OJoinDesignViewAccess* m_pAccessible;\n\n public:\n OJoinTableView( Window* pParent, OJoinDesignView* pView );\n virtual ~OJoinTableView();\n\n \/\/ window override\n virtual void StateChanged( StateChangedType nStateChange );\n virtual void GetFocus();\n virtual void LoseFocus();\n virtual void KeyInput( const KeyEvent& rEvt );\n \/\/ Accessibility\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();\n\n \/\/ own methods\n ScrollBar* GetHScrollBar() { return static_cast(GetParent())->GetHScrollBar(); }\n ScrollBar* GetVScrollBar() { return static_cast(GetParent())->GetVScrollBar(); }\n DECL_LINK( ScrollHdl, ScrollBar* );\n\n void DrawConnections( const Rectangle& rRect );\n void InvalidateConnections();\n\n void BeginChildMove( OTableWindow* pTabWin, const Point& rMousePos );\n void BeginChildSizing( OTableWindow* pTabWin, const Pointer& rPointer );\n\n void NotifyTitleClicked( OTableWindow* pTabWin, const Point rMousePos );\n\n virtual void AddTabWin(const ::rtl::OUString& _rComposedName, const ::rtl::OUString& rWinName, BOOL bNewTable = FALSE);\n virtual void RemoveTabWin( OTableWindow* pTabWin );\n\n \/\/ alle TabWins verstecken (NICHT loeschen, sie werden in eine Undo-Action gepackt)\n virtual void HideTabWins();\n\n virtual void AddConnection(const OJoinExchangeData& jxdSource, const OJoinExchangeData& jxdDest) = 0;\n\n \/** RemoveConnection allows to remove connections from join table view, it implies that the same as addConnection\n\n @param _pConnection\n the connection which should be removed\n @param _bDelete\n when truie then the connection will be deleted\n\n @return an iterator to next valid connection, so it can be used in any loop\n *\/\n virtual ::std::vector::const_iterator RemoveConnection(OTableConnection* _pConnection,sal_Bool _bDelete);\n\n \/** allows to add new connections to join table view, it implies an invalidation of the features\n ID_BROWSER_ADDTABLE and SID_RELATION_ADD_RELATION also the modified flag will be set to true\n @param _pConnection\n the connection which should be added\n @param _bAddData\n when the data should also be appended\n *\/\n void addConnection(OTableConnection* _pConnection,sal_Bool _bAddData = sal_True);\n\n BOOL ScrollPane( long nDelta, BOOL bHoriz, BOOL bPaintScrollBars );\n ULONG GetTabWinCount();\n Point GetScrollOffset() const { return m_aScrollOffset; }\n\n OJoinDesignView* getDesignView() const { return m_pView; }\n OTableWindow* GetTabWindow( const String& rName );\n\n OTableConnection* GetSelectedConn() { return m_pSelectedConn; }\n void DeselectConn(OTableConnection* pConn); \/\/ NULL ist ausdruecklich zugelassen, dann passiert nichts\n void SelectConn(OTableConnection* pConn);\n\n OTableWindowMap* GetTabWinMap() { return &m_aTableMap; }\n const OTableWindowMap* GetTabWinMap() const { return &m_aTableMap; }\n\n \/** gives a read only access to the connection vector\n *\/\n const ::std::vector* getTableConnections() const { return &m_vTableConnection; }\n\n\n BOOL ExistsAConn(const OTableWindow* pFromWin) const;\n\n \/** getTableConnections searchs for all connections of a table\n @param _pFromWin the table for which connections should be found\n\n @return an iterator which can be used to travel all connections of the table\n *\/\n ::std::vector::const_iterator getTableConnections(const OTableWindow* _pFromWin) const;\n\n \/** getConnectionCount returns how many connection belongs to single table\n @param _pFromWin the table for which connections should be found\n\n @return the count of connections wich belongs to this table\n *\/\n sal_Int32 getConnectionCount(const OTableWindow* _pFromWin) const;\n\n OTableConnection* GetTabConn(const OTableWindow* pLhs,const OTableWindow* pRhs,bool _bSupressCrossOrNaturalJoin = false,const OTableConnection* _rpFirstAfter = NULL) const;\n\n \/\/ clears the window map and connection vector without destroying it\n \/\/ that means teh data of the windows and connection will be untouched\n void clearLayoutInformation();\n\n \/\/ set the focus to that tab win which most recently had it (or to the first available one)\n void GrabTabWinFocus();\n\n \/\/ ReSync ist dazu gedacht, aus dem Dokument alle WinData und ConnData zu holen und entsprechend Wins und Conns anzulegen\n virtual void ReSync() { }\n \/\/ ClearAll implementiert ein hartes Loeschen, es werden alle Conns und alle Wins aus ihren jeweiligen Listen geloescht\n \/\/ sowie die entsprechenden Datas aus dem Dokument ausgetragen\n virtual void ClearAll();\n\n \/\/ wird vom AddTabDlg benutzt, um festzustellen, ob noch Tabellen hinzugefuegt werden duerfen\n virtual BOOL IsAddAllowed();\n virtual long PreNotify(NotifyEvent& rNEvt);\n\n \/\/ DnD stuff\n virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );\n virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );\n virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );\n\n \/**\n can be used in derevied classes to make some special ui handling\n after d&d\n *\/\n virtual void lookForUiActivities();\n\n \/\/ wird nach Verschieben\/Groessenaenderung der TabWins aufgerufen (die Standardimplementation reicht die neuen Daten einfach\n \/\/ an die Daten des Wins weiter)\n virtual void TabWinMoved(OTableWindow* ptWhich, const Point& ptOldPosition);\n \/\/ die Position ist \"virtuell\" : der Container hat sozusagen eine virtuelle Flaeche, von der immer nur ein bestimmter Bereich\n \/\/ - der mittels der Scrollbar veraendert werden kann - zu sehen ist. Insbesondere hat ptOldPosition immer positive Koordinaten,\n \/\/ auch wenn er einen Punkt oberhalb des aktuell sichtbaren Bereichs bezeichnet, dessen physische Ordinate eigentlich\n \/\/ negativ ist.\n virtual void TabWinSized(OTableWindow* ptWhich, const Point& ptOldPosition, const Size& szOldSize);\n\n void modified();\n\n \/** returns if teh given window is visible.\n @param _rPoint\n The Point to check\n @param _rSize\n The Size to be check as well\n @return\n if the area is visible otherwise \n\n *\/\n BOOL isMovementAllowed(const Point& _rPoint,const Size& _rSize);\n\n Size getRealOutputSize() const { return m_aOutputSize; }\n\n\n\n virtual void EnsureVisible(const OTableWindow* _pWin);\n virtual void EnsureVisible(const Point& _rPoint,const Size& _rSize);\n\n TTableWindowData::value_type createTableWindowData(const ::rtl::OUString& _rComposedName\n ,const ::rtl::OUString& _sTableName\n ,const ::rtl::OUString& _rWinName);\n\n protected:\n virtual void MouseButtonUp( const MouseEvent& rEvt );\n virtual void MouseButtonDown( const MouseEvent& rEvt );\n virtual void Tracking( const TrackingEvent& rTEvt );\n virtual void Paint( const Rectangle& rRect );\n virtual void ConnDoubleClicked( OTableConnection* pConnection );\n virtual void SetDefaultTabWinPosSize( OTableWindow* pTabWin );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\n virtual void Resize();\n\n virtual void dragFinished( );\n \/\/ hier ist die Position (die sich waehrend des Sizings aendern kann) physisch, da waehrend des Sizens nicht gescrollt wird\n virtual void Command(const CommandEvent& rEvt);\n\n virtual OTableWindowData* CreateImpl(const ::rtl::OUString& _rComposedName\n ,const ::rtl::OUString& _sTableName\n ,const ::rtl::OUString& _rWinName);\n\n \/** factory method to create table windows\n @param _pData\n The data corresponding to the window.\n @return\n The new TableWindow\n *\/\n virtual OTableWindow* createWindow(const TTableWindowData::value_type& _pData) = 0;\n\n \/** determines whether the classes Init method should accept a query name, or only table names\n *\/\n virtual bool allowQueries() const;\n\n \/** called when init fails at the tablewindowdata because the m_xTable object could not provide columns, but no\n exception was thrown. Expected to throw.\n *\/\n virtual void onNoColumns_throw();\n\n virtual bool supressCrossNaturalJoin(const TTableConnectionData::value_type& _pData) const;\n\n private:\n void InitColors();\n BOOL ScrollWhileDragging();\n\n \/** executePopup opens the context menu to delate a connection\n @param _aPos the position where the popup menu should appear\n @param _pSelConnection the connection which should be deleted\n *\/\n void executePopup(const Point& _aPos,OTableConnection* _pSelConnection);\n\n \/** invalidateAndModify invalidates this window without children and\n set the controller modified\n @param _pAction a possible undo action to add at the controller\n *\/\n void invalidateAndModify(SfxUndoAction *_pAction=NULL);\n\n private:\n using Window::Scroll;\n };\n}\n#endif \/\/ DBAUI_JOINTABLEVIEW_HXX\nINTEGRATION: CWS changefileheader (1.25.96); FILE MERGED 2008\/03\/31 13:27:43 rt 1.25.96.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: JoinTableView.hxx,v $\n * $Revision: 1.26 $\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 DBAUI_JOINTABLEVIEW_HXX\n#define DBAUI_JOINTABLEVIEW_HXX\n\n#ifndef _SV_WINDOW_HXX\n#include \n#endif\n#ifndef _SV_TIMER_HXX\n#include \n#endif\n#ifndef _SV_SCRBAR_HXX\n#include \n#endif\n#ifndef _RTTI_HXX\n#include \n#endif\n#ifndef _TRANSFER_HXX\n#include \n#endif\n\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _DBACCESS_UI_CALLBACKS_HXX_\n#include \"callbacks.hxx\"\n#endif\n#include \"TableConnectionData.hxx\"\n#include \"TableWindowData.hxx\"\n#include \n#include \n\nstruct AcceptDropEvent;\nstruct ExecuteDropEvent;\nclass SfxUndoAction;\nnamespace dbaui\n{\n class OTableConnection;\n class OTableWindow;\n struct OJoinExchangeData;\n class OJoinDesignView;\n class OTableWindowData;\n class OJoinDesignViewAccess;\n\n \/\/ this class conatins only the scrollbars to avoid that the tablewindows clip the scrollbars\n class OJoinTableView;\n class OScrollWindowHelper : public Window\n {\n ScrollBar m_aHScrollBar;\n ScrollBar m_aVScrollBar;\n Window* m_pCornerWindow;\n OJoinTableView* m_pTableView;\n\n protected:\n virtual void Resize();\n public:\n OScrollWindowHelper( Window* pParent);\n ~OScrollWindowHelper();\n\n void setTableView(OJoinTableView* _pTableView);\n\n void resetRange(const Point& _aSize);\n\n \/\/ own methods\n ScrollBar* GetHScrollBar() { return &m_aHScrollBar; }\n ScrollBar* GetVScrollBar() { return &m_aVScrollBar; }\n };\n\n\n class OJoinTableView : public Window\n ,public IDragTransferableListener\n ,public DropTargetHelper\n {\n friend class OJoinMoveTabWinUndoAct;\n public:\n DECLARE_STL_USTRINGACCESS_MAP(OTableWindow*,OTableWindowMap);\n private:\n OTableWindowMap m_aTableMap;\n ::std::vector m_vTableConnection;\n\n Timer m_aDragScrollTimer;\n Rectangle m_aDragRect;\n Rectangle m_aSizingRect;\n Point m_aDragOffset;\n Point m_aScrollOffset;\n Point m_ptPrevDraggingPos;\n Size m_aOutputSize;\n\n\n OTableWindow* m_pDragWin;\n OTableWindow* m_pSizingWin;\n OTableConnection* m_pSelectedConn;\n\n\n BOOL m_bTrackingInitiallyMoved;\n\n DECL_LINK(OnDragScrollTimer, void*);\n\n protected:\n OTableWindow* m_pLastFocusTabWin;\n OJoinDesignView* m_pView;\n OJoinDesignViewAccess* m_pAccessible;\n\n public:\n OJoinTableView( Window* pParent, OJoinDesignView* pView );\n virtual ~OJoinTableView();\n\n \/\/ window override\n virtual void StateChanged( StateChangedType nStateChange );\n virtual void GetFocus();\n virtual void LoseFocus();\n virtual void KeyInput( const KeyEvent& rEvt );\n \/\/ Accessibility\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();\n\n \/\/ own methods\n ScrollBar* GetHScrollBar() { return static_cast(GetParent())->GetHScrollBar(); }\n ScrollBar* GetVScrollBar() { return static_cast(GetParent())->GetVScrollBar(); }\n DECL_LINK( ScrollHdl, ScrollBar* );\n\n void DrawConnections( const Rectangle& rRect );\n void InvalidateConnections();\n\n void BeginChildMove( OTableWindow* pTabWin, const Point& rMousePos );\n void BeginChildSizing( OTableWindow* pTabWin, const Pointer& rPointer );\n\n void NotifyTitleClicked( OTableWindow* pTabWin, const Point rMousePos );\n\n virtual void AddTabWin(const ::rtl::OUString& _rComposedName, const ::rtl::OUString& rWinName, BOOL bNewTable = FALSE);\n virtual void RemoveTabWin( OTableWindow* pTabWin );\n\n \/\/ alle TabWins verstecken (NICHT loeschen, sie werden in eine Undo-Action gepackt)\n virtual void HideTabWins();\n\n virtual void AddConnection(const OJoinExchangeData& jxdSource, const OJoinExchangeData& jxdDest) = 0;\n\n \/** RemoveConnection allows to remove connections from join table view, it implies that the same as addConnection\n\n @param _pConnection\n the connection which should be removed\n @param _bDelete\n when truie then the connection will be deleted\n\n @return an iterator to next valid connection, so it can be used in any loop\n *\/\n virtual ::std::vector::const_iterator RemoveConnection(OTableConnection* _pConnection,sal_Bool _bDelete);\n\n \/** allows to add new connections to join table view, it implies an invalidation of the features\n ID_BROWSER_ADDTABLE and SID_RELATION_ADD_RELATION also the modified flag will be set to true\n @param _pConnection\n the connection which should be added\n @param _bAddData\n when the data should also be appended\n *\/\n void addConnection(OTableConnection* _pConnection,sal_Bool _bAddData = sal_True);\n\n BOOL ScrollPane( long nDelta, BOOL bHoriz, BOOL bPaintScrollBars );\n ULONG GetTabWinCount();\n Point GetScrollOffset() const { return m_aScrollOffset; }\n\n OJoinDesignView* getDesignView() const { return m_pView; }\n OTableWindow* GetTabWindow( const String& rName );\n\n OTableConnection* GetSelectedConn() { return m_pSelectedConn; }\n void DeselectConn(OTableConnection* pConn); \/\/ NULL ist ausdruecklich zugelassen, dann passiert nichts\n void SelectConn(OTableConnection* pConn);\n\n OTableWindowMap* GetTabWinMap() { return &m_aTableMap; }\n const OTableWindowMap* GetTabWinMap() const { return &m_aTableMap; }\n\n \/** gives a read only access to the connection vector\n *\/\n const ::std::vector* getTableConnections() const { return &m_vTableConnection; }\n\n\n BOOL ExistsAConn(const OTableWindow* pFromWin) const;\n\n \/** getTableConnections searchs for all connections of a table\n @param _pFromWin the table for which connections should be found\n\n @return an iterator which can be used to travel all connections of the table\n *\/\n ::std::vector::const_iterator getTableConnections(const OTableWindow* _pFromWin) const;\n\n \/** getConnectionCount returns how many connection belongs to single table\n @param _pFromWin the table for which connections should be found\n\n @return the count of connections wich belongs to this table\n *\/\n sal_Int32 getConnectionCount(const OTableWindow* _pFromWin) const;\n\n OTableConnection* GetTabConn(const OTableWindow* pLhs,const OTableWindow* pRhs,bool _bSupressCrossOrNaturalJoin = false,const OTableConnection* _rpFirstAfter = NULL) const;\n\n \/\/ clears the window map and connection vector without destroying it\n \/\/ that means teh data of the windows and connection will be untouched\n void clearLayoutInformation();\n\n \/\/ set the focus to that tab win which most recently had it (or to the first available one)\n void GrabTabWinFocus();\n\n \/\/ ReSync ist dazu gedacht, aus dem Dokument alle WinData und ConnData zu holen und entsprechend Wins und Conns anzulegen\n virtual void ReSync() { }\n \/\/ ClearAll implementiert ein hartes Loeschen, es werden alle Conns und alle Wins aus ihren jeweiligen Listen geloescht\n \/\/ sowie die entsprechenden Datas aus dem Dokument ausgetragen\n virtual void ClearAll();\n\n \/\/ wird vom AddTabDlg benutzt, um festzustellen, ob noch Tabellen hinzugefuegt werden duerfen\n virtual BOOL IsAddAllowed();\n virtual long PreNotify(NotifyEvent& rNEvt);\n\n \/\/ DnD stuff\n virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );\n virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );\n virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );\n\n \/**\n can be used in derevied classes to make some special ui handling\n after d&d\n *\/\n virtual void lookForUiActivities();\n\n \/\/ wird nach Verschieben\/Groessenaenderung der TabWins aufgerufen (die Standardimplementation reicht die neuen Daten einfach\n \/\/ an die Daten des Wins weiter)\n virtual void TabWinMoved(OTableWindow* ptWhich, const Point& ptOldPosition);\n \/\/ die Position ist \"virtuell\" : der Container hat sozusagen eine virtuelle Flaeche, von der immer nur ein bestimmter Bereich\n \/\/ - der mittels der Scrollbar veraendert werden kann - zu sehen ist. Insbesondere hat ptOldPosition immer positive Koordinaten,\n \/\/ auch wenn er einen Punkt oberhalb des aktuell sichtbaren Bereichs bezeichnet, dessen physische Ordinate eigentlich\n \/\/ negativ ist.\n virtual void TabWinSized(OTableWindow* ptWhich, const Point& ptOldPosition, const Size& szOldSize);\n\n void modified();\n\n \/** returns if teh given window is visible.\n @param _rPoint\n The Point to check\n @param _rSize\n The Size to be check as well\n @return\n if the area is visible otherwise \n\n *\/\n BOOL isMovementAllowed(const Point& _rPoint,const Size& _rSize);\n\n Size getRealOutputSize() const { return m_aOutputSize; }\n\n\n\n virtual void EnsureVisible(const OTableWindow* _pWin);\n virtual void EnsureVisible(const Point& _rPoint,const Size& _rSize);\n\n TTableWindowData::value_type createTableWindowData(const ::rtl::OUString& _rComposedName\n ,const ::rtl::OUString& _sTableName\n ,const ::rtl::OUString& _rWinName);\n\n protected:\n virtual void MouseButtonUp( const MouseEvent& rEvt );\n virtual void MouseButtonDown( const MouseEvent& rEvt );\n virtual void Tracking( const TrackingEvent& rTEvt );\n virtual void Paint( const Rectangle& rRect );\n virtual void ConnDoubleClicked( OTableConnection* pConnection );\n virtual void SetDefaultTabWinPosSize( OTableWindow* pTabWin );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\n virtual void Resize();\n\n virtual void dragFinished( );\n \/\/ hier ist die Position (die sich waehrend des Sizings aendern kann) physisch, da waehrend des Sizens nicht gescrollt wird\n virtual void Command(const CommandEvent& rEvt);\n\n virtual OTableWindowData* CreateImpl(const ::rtl::OUString& _rComposedName\n ,const ::rtl::OUString& _sTableName\n ,const ::rtl::OUString& _rWinName);\n\n \/** factory method to create table windows\n @param _pData\n The data corresponding to the window.\n @return\n The new TableWindow\n *\/\n virtual OTableWindow* createWindow(const TTableWindowData::value_type& _pData) = 0;\n\n \/** determines whether the classes Init method should accept a query name, or only table names\n *\/\n virtual bool allowQueries() const;\n\n \/** called when init fails at the tablewindowdata because the m_xTable object could not provide columns, but no\n exception was thrown. Expected to throw.\n *\/\n virtual void onNoColumns_throw();\n\n virtual bool supressCrossNaturalJoin(const TTableConnectionData::value_type& _pData) const;\n\n private:\n void InitColors();\n BOOL ScrollWhileDragging();\n\n \/** executePopup opens the context menu to delate a connection\n @param _aPos the position where the popup menu should appear\n @param _pSelConnection the connection which should be deleted\n *\/\n void executePopup(const Point& _aPos,OTableConnection* _pSelConnection);\n\n \/** invalidateAndModify invalidates this window without children and\n set the controller modified\n @param _pAction a possible undo action to add at the controller\n *\/\n void invalidateAndModify(SfxUndoAction *_pAction=NULL);\n\n private:\n using Window::Scroll;\n };\n}\n#endif \/\/ DBAUI_JOINTABLEVIEW_HXX\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Debug_AssertExternallySynchronizedMutex_inl_\n#define _Stroika_Foundation_Debug_AssertExternallySynchronizedMutex_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#include \n\n#include \"Sanitizer.h\"\n\nnamespace Stroika::Foundation::Debug {\n\n \/*\n ********************************************************************************\n **************** Debug::AssertExternallySynchronizedMutex **********************\n ********************************************************************************\n *\/\n#if qDebug\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex (const shared_ptr& sharedContext) noexcept\n \/\/ https:\/\/stroika.atlassian.net\/browse\/STK-500\n \/\/ NOTE - this will generate a throw and std::unexpected violation if there is no memory and multiset CTOR\n \/\/ throws. There is no good answer in this case. We declare the constructors noexcept so the footprint of\n \/\/ AssertExternallySynchronizedMutex is as light as possible and the same (API\/constraints) between debug and release\n \/\/ builds. And if we run out of memory here, there isn't much we can do to continue -- LGP 2018-10-02\n : _fSharedContext{sharedContext ? sharedContext : make_shared ()}\n {\n }\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex (const shared_ptr& sharedContext, const AssertExternallySynchronizedMutex& src) noexcept\n : AssertExternallySynchronizedMutex{sharedContext}\n {\n shared_lock critSec1{src}; \/\/ to copy, the src can have shared_locks, but no (write) locks\n }\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex (const AssertExternallySynchronizedMutex& src) noexcept\n : AssertExternallySynchronizedMutex{}\n {\n shared_lock critSec1{src}; \/\/ to copy, the src can have shared_locks, but no (write) locks\n }\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex (const shared_ptr& sharedContext, [[maybe_unused]] AssertExternallySynchronizedMutex&& src) noexcept\n : AssertExternallySynchronizedMutex{sharedContext}\n {\n try {\n Require (src._fSharedContext->fLocks_ == 0 and src._fSharedContext->GetSharedLockEmpty_ ()); \/\/ to move, the src can have no locks of any kind (since we change src)\n }\n catch (...) {\n AssertNotReached ();\n }\n }\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex ([[maybe_unused]] AssertExternallySynchronizedMutex&& src) noexcept\n : AssertExternallySynchronizedMutex{}\n {\n try {\n Require (src._fSharedContext->fLocks_ == 0 and src._fSharedContext->GetSharedLockEmpty_ ()); \/\/ to move, the src can have no locks of any kind (since we change src)\n }\n catch (...) {\n AssertNotReached ();\n }\n }\n#endif\n inline AssertExternallySynchronizedMutex& AssertExternallySynchronizedMutex::operator= ([[maybe_unused]] const AssertExternallySynchronizedMutex& rhs) noexcept\n {\n#if qDebug\n try {\n DISABLE_COMPILER_MSC_WARNING_START (26110); \/\/ to copy, the src can have shared_locks, but no (write) locks\n shared_lock critSec1{rhs}; \/\/ \"\"\n if (this == &rhs) {\n Require (_fSharedContext->fLocks_ == 0 and _fSharedContext->GetSharedLockThreadsCount_ () == 1); \/\/ we locked ourselves above\n }\n else {\n \/\/ @todo This logic SB same as for MOVE, but for some reason this hasn't been triggered yet...\n \/\/ https:\/\/stroika.atlassian.net\/browse\/STK-752\n Require (_fSharedContext->fLocks_ == 0 and _fSharedContext->GetSharedLockEmpty_ ()); \/\/ We must not have any locks going to replace this\n }\n DISABLE_COMPILER_MSC_WARNING_END (26110);\n }\n catch (...) {\n AssertNotReached ();\n }\n#endif\n return *this;\n }\n inline AssertExternallySynchronizedMutex& AssertExternallySynchronizedMutex::operator= ([[maybe_unused]] AssertExternallySynchronizedMutex&& rhs) noexcept\n {\n#if qDebug\n try {\n Require (rhs._fSharedContext->fLocks_ == 0 and rhs._fSharedContext->GetSharedLockEmpty_ ()); \/\/ to move, the rhs can have no locks of any kind (since we change rhs)\n \/\/ NOTE - we also should check if fLocks_ != 0 -= thats OK if WE are the locker.\n \/\/ BUT - I think I need todo work here to TRANSFER the locks (and thats not done here\/yet)\n \/\/\n \/\/Require (_fSharedContext->fLocks_ == 0 and _fSharedContext->GetSharedLockEmpty_ ()); \/\/ ditto for thing being assigned to\n \/\/ https:\/\/stroika.atlassian.net\/browse\/STK-752\n if (_fSharedContext->fLocks_ != 0) {\n \/\/ must do some sanity check and then transfer locks\n Assert (false); \/\/ NYI\n }\n if (not _fSharedContext->GetSharedLockEmpty_ ()) {\n auto tmp = _fSharedContext->CountSharedLockThreads_ ();\n Assert (tmp.second == 0); \/\/ not good enuf - must transer lock to RHS\n \/\/ UNCLEAR if should transfer rhs._fSharedContext making this increment irrelevant\n for (size_t i = 0; i < tmp.second; ++i) {\n \/\/ rhs.lock_shared ();\n }\n }\n \/\/ _fSharedContext = move (rhs._fSharedContext);\n }\n catch (...) {\n AssertNotReached ();\n }\n#endif\n return *this;\n }\n#if qDebug\n inline void AssertExternallySynchronizedMutex::SetAssertExternallySynchronizedMutexContext (const shared_ptr& sharedContext)\n {\n Require (sharedContext != nullptr);\n _fSharedContext = sharedContext;\n }\n#endif\n inline void AssertExternallySynchronizedMutex::lock () const noexcept\n {\n#if qDebug\n lock_ ();\n#endif\n }\n inline void AssertExternallySynchronizedMutex::unlock () const noexcept\n {\n#if qDebug\n unlock_ ();\n#endif\n }\n inline void AssertExternallySynchronizedMutex::lock_shared () const noexcept\n {\n#if qDebug\n lock_shared_ ();\n#endif\n }\n inline void AssertExternallySynchronizedMutex::unlock_shared () const noexcept\n {\n#if qDebug\n unlock_shared_ ();\n#endif\n }\n\n}\n\n#endif \/*_Stroika_Foundation_Debug_AssertExternallySynchronizedMutex_inl_*\/\nslight cleanups of Debug\/AssertExternallySynchronizedMutex.\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Debug_AssertExternallySynchronizedMutex_inl_\n#define _Stroika_Foundation_Debug_AssertExternallySynchronizedMutex_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#include \n\n#include \"Sanitizer.h\"\n\nnamespace Stroika::Foundation::Debug {\n\n \/*\n ********************************************************************************\n **************** Debug::AssertExternallySynchronizedMutex **********************\n ********************************************************************************\n *\/\n#if qDebug\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex (const shared_ptr& sharedContext) noexcept\n \/\/ https:\/\/stroika.atlassian.net\/browse\/STK-500\n \/\/ NOTE - this will generate a throw and std::unexpected violation if there is no memory and multiset CTOR\n \/\/ throws. There is no good answer in this case. We declare the constructors noexcept so the footprint of\n \/\/ AssertExternallySynchronizedMutex is as light as possible and the same (API\/constraints) between debug and release\n \/\/ builds. And if we run out of memory here, there isn't much we can do to continue -- LGP 2018-10-02\n : _fSharedContext{sharedContext ? sharedContext : make_shared ()}\n {\n }\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex (const shared_ptr& sharedContext, const AssertExternallySynchronizedMutex& src) noexcept\n : AssertExternallySynchronizedMutex{sharedContext}\n {\n shared_lock critSec1{src}; \/\/ to copy, the src can have shared_locks, but no (write) locks\n }\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex (const AssertExternallySynchronizedMutex& src) noexcept\n : AssertExternallySynchronizedMutex{}\n {\n shared_lock critSec1{src}; \/\/ to copy, the src can have shared_locks, but no (write) locks\n }\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex (const shared_ptr& sharedContext, [[maybe_unused]] AssertExternallySynchronizedMutex&& src) noexcept\n : AssertExternallySynchronizedMutex{sharedContext}\n {\n try {\n Require (src._fSharedContext->fLocks_ == 0 and src._fSharedContext->GetSharedLockEmpty_ ()); \/\/ to move, the src can have no locks of any kind (since we change src)\n }\n catch (...) {\n AssertNotReached ();\n }\n }\n inline AssertExternallySynchronizedMutex::AssertExternallySynchronizedMutex ([[maybe_unused]] AssertExternallySynchronizedMutex&& src) noexcept\n : AssertExternallySynchronizedMutex{}\n {\n try {\n Require (src._fSharedContext->fLocks_ == 0 and src._fSharedContext->GetSharedLockEmpty_ ()); \/\/ to move, the src can have no locks of any kind (since we change src)\n }\n catch (...) {\n AssertNotReached ();\n }\n }\n#endif\n inline AssertExternallySynchronizedMutex& AssertExternallySynchronizedMutex::operator= ([[maybe_unused]] const AssertExternallySynchronizedMutex& rhs) noexcept\n {\n#if qDebug\n try {\n DISABLE_COMPILER_MSC_WARNING_START (26110); \/\/ to copy, the src can have shared_locks, but no (write) locks\n shared_lock critSec1{rhs}; \/\/ \"\"\n if (this == &rhs) {\n Require (_fSharedContext->fLocks_ == 0 and _fSharedContext->GetSharedLockThreadsCount_ () == 1); \/\/ we locked ourselves above\n }\n else {\n \/\/ @todo This logic SB same as for MOVE, but for some reason this hasn't been triggered yet...\n \/\/ https:\/\/stroika.atlassian.net\/browse\/STK-752\n Require (_fSharedContext->fLocks_ == 0 and _fSharedContext->GetSharedLockEmpty_ ()); \/\/ We must not have any locks going to replace this\n }\n DISABLE_COMPILER_MSC_WARNING_END (26110);\n }\n catch (...) {\n AssertNotReached ();\n }\n#endif\n return *this;\n }\n inline AssertExternallySynchronizedMutex& AssertExternallySynchronizedMutex::operator= ([[maybe_unused]] AssertExternallySynchronizedMutex&& rhs) noexcept\n {\n#if qDebug\n try {\n Require (rhs._fSharedContext->fLocks_ == 0 and rhs._fSharedContext->GetSharedLockEmpty_ ()); \/\/ to move, the rhs can have no locks of any kind (since we change rhs)\n \/\/ https:\/\/stroika.atlassian.net\/browse\/STK-752\n \/\/ review - SB OK to assign over this with locks if the locks are all from this thread\n if (_fSharedContext->fLocks_ != 0) {\n Assert (false); \/\/ NYI\n }\n if (not _fSharedContext->GetSharedLockEmpty_ ()) {\n Assert (_fSharedContext->CountSharedLockThreads_ ().second == 0); \/\/ not good enuf - must transer lock to RHS\n }\n }\n catch (...) {\n AssertNotReached ();\n }\n#endif\n return *this;\n }\n#if qDebug\n inline void AssertExternallySynchronizedMutex::SetAssertExternallySynchronizedMutexContext (const shared_ptr& sharedContext)\n {\n Require (sharedContext != nullptr);\n _fSharedContext = sharedContext;\n }\n#endif\n inline void AssertExternallySynchronizedMutex::lock () const noexcept\n {\n#if qDebug\n lock_ ();\n#endif\n }\n inline void AssertExternallySynchronizedMutex::unlock () const noexcept\n {\n#if qDebug\n unlock_ ();\n#endif\n }\n inline void AssertExternallySynchronizedMutex::lock_shared () const noexcept\n {\n#if qDebug\n lock_shared_ ();\n#endif\n }\n inline void AssertExternallySynchronizedMutex::unlock_shared () const noexcept\n {\n#if qDebug\n unlock_shared_ ();\n#endif\n }\n\n}\n\n#endif \/*_Stroika_Foundation_Debug_AssertExternallySynchronizedMutex_inl_*\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef LUABIND_CALL_FUNCTION_HPP_INCLUDED\n#define LUABIND_CALL_FUNCTION_HPP_INCLUDED\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace luabind\n{\n\tnamespace adl {\n\t\tclass object;\n\t}\n\n\tusing adl::object;\n\n\tnamespace detail {\n\n\t\ttemplate< typename PolicyList, unsigned int pos >\n void push_arguments(lua_State* \/*L*\/) {};\n\n\t\ttemplate< typename PolicyList, unsigned int Pos, typename Arg0, typename... Args >\n\t\tvoid push_arguments(lua_State* L, Arg0&& arg0, Args&&... args)\n\t\t{\n\t\t\tusing converter_type = specialized_converter_policy< fetched_converter_policy, Arg0, cpp_to_lua >;\n\t\t\tconverter_type().to_lua(L, unwrapped::get(std::forward(arg0)));\n push_arguments(L, std::forward(args)...);\n }\n\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\ttemplate\n\t\tvoid call_function_impl(lua_State* L, int m_params, Fn fn, std::true_type \/* void *\/, meta::index_list, Args&&... args)\n\t\t{\n\t\t\tint top = lua_gettop(L);\n\n\t\t\tpush_arguments(L, std::forward(args)...);\n\n\t\t\tif (fn(L, sizeof...(Args), 0)) {\n\t\t\t\tassert(lua_gettop(L) == top - m_params + 1);\n\t\t\t\tcall_error(L);\n\t\t\t}\n\t\t\t\/\/ pops the return values from the function call\n\t\t\tstack_pop pop(L, lua_gettop(L) - top + m_params);\n\t\t}\n\n\t\ttemplate\n\t\tRet call_function_impl(lua_State* L, int m_params, Fn fn, std::false_type \/* void *\/ , meta::index_list, Args&&... args)\n\t\t{\n\t\t\tint top = lua_gettop(L);\n\t\t\t\n\t\t\tpush_arguments(L, std::forward(args)...);\n\n\t\t\tif (fn(L, sizeof...(Args), 1)) {\n\t\t\t\tassert(lua_gettop(L) == top - m_params + 1);\n\t\t\t\tcall_error(L);\n\t\t\t}\n\t\t\t\/\/ pops the return values from the function call\n\t\t\tstack_pop pop(L, lua_gettop(L) - top + m_params);\n\n\t\t\tspecialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;\n\t\t\tif (converter.match(L, decorated_type(), -1) < 0) {\n\t\t\t\tcast_error(L);\n\t\t\t}\n\n\t\t\treturn converter.to_cpp(L, decorated_type(), -1);\n\t\t}\n#else\n\t\ttemplate::value>\n\t\tstruct call_function_struct;\n\n\t\ttemplate\n\t\tstruct call_function_struct< Ret, PolicyList, meta::index_list, NumParams, Function, true \/* void *\/ >\n\t\t{\n\t\t\ttemplate< typename... Args >\n\t\t\tstatic void call(lua_State* L, Args&&... args) {\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\t\n\t\t\t\tpush_arguments(L, std::forward(args)...);\n\n\t\t\t\tif(Function(L, sizeof...(Args), 0)) {\n\t\t\t\t\tassert(lua_gettop(L)==top-NumParams+1);\n\t\t\t\t\tcall_error(L);\n\t\t\t\t}\n\t\t\t\t\/\/ pops the return values from the function call\n\t\t\t\tstack_pop pop(L, lua_gettop(L)-top+NumParams);\n\t\t\t}\n\t\t};\n\n\t\ttemplate\n\t\tstruct call_function_struct< Ret, PolicyList, meta::index_list, NumParams, Function, false \/* void *\/ >\n\t\t{\n\t\t\ttemplate< typename... Args >\n\t\t\tstatic Ret call(lua_State* L, Args&&... args) {\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\t\n\t\t\t\tpush_arguments(L, std::forward(args)...);\n\n\t\t\t\tif(Function(L, sizeof...(Args), 1)) {\n\t\t\t\t\tassert(lua_gettop(L)==top-NumParams+1);\n\t\t\t\t\tcall_error(L);\n\t\t\t\t}\n\t\t\t\t\/\/ pops the return values from the function call\n\t\t\t\tstack_pop pop(L, lua_gettop(L)-top+NumParams);\n\n\t\t\t\tspecialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;\n\t\t\t\tif(converter.match(L, decorated_type(), -1)<0) {\n\t\t\t\t\tcast_error(L);\n\t\t\t\t}\n\n\t\t\t\treturn converter.to_cpp(L, decorated_type(), -1);\n\t\t\t}\n\t\t};\n#endif\n\t}\n\n\ttemplate\n\tR call_pushed_function(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl(L, 1, &detail::pcall, std::is_void(), meta::index_range<1, sizeof...(Args) +1>(), std::forward(args)...);\n#else\n\t\treturn detail::call_function_struct, 1, &detail::pcall >::call(L, std::forward(args)...);\n#endif\n\t}\n\n\ttemplate\n\tR call_function(lua_State* L, const char* name, Args&&... args )\n\t{\n\t\tassert(name && \"luabind::call_function() expects a function name\");\n\t\tlua_getglobal(L, name);\n\t\treturn call_pushed_function(L, std::forward(args)...);\n\t}\n\n\ttemplate\n\tR resume_pushed_function(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl(L, 1, &detail::resume_impl, std::is_void(), meta::index_range<1, sizeof...(Args) +1>(), std::forward(args)...);\n#else\n\t\treturn detail::call_function_struct, 1, &detail::resume_impl >::call(L, std::forward(args)...);\n#endif\n\t}\n\n\ttemplate\n\tR resume_function(lua_State* L, const char* name, Args&&... args)\n\t{\n\t\tassert(name && \"luabind::resume_function() expects a function name\");\n\t\tlua_getglobal(L, name);\n\t\treturn resume_pushed_function(L, std::forward(args)...);\n\t}\n\n\ttemplate\n\tR resume(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl(L, 0, &detail::resume_impl, std::is_void(), meta::index_range<1, sizeof...(Args) +1>(), std::forward(args)...);\n#else\n\t\treturn detail::call_function_struct, 0, &detail::resume_impl >::call(L, std::forward(args)...);\n#endif\n\t}\n\n}\n\n#endif \/\/ LUABIND_CALL_FUNCTION_HPP_INCLUDED\n\nTiny change\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef LUABIND_CALL_FUNCTION_HPP_INCLUDED\n#define LUABIND_CALL_FUNCTION_HPP_INCLUDED\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace luabind\n{\n\tnamespace adl {\n\t\tclass object;\n\t}\n\n\tusing adl::object;\n\n\tnamespace detail {\n\n\t\ttemplate< typename PolicyList, unsigned int pos >\n void push_arguments(lua_State* \/*L*\/) {};\n\n\t\ttemplate< typename PolicyList, unsigned int Pos, typename Arg0, typename... Args >\n\t\tvoid push_arguments(lua_State* L, Arg0&& arg0, Args&&... args)\n\t\t{\n\t\t\tusing converter_type = specialized_converter_policy< fetched_converter_policy, Arg0, cpp_to_lua >;\n\t\t\tconverter_type().to_lua(L, unwrapped::get(std::forward(arg0)));\n push_arguments(L, std::forward(args)...);\n }\n\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\ttemplate\n\t\tvoid call_function_impl(lua_State* L, int m_params, Fn fn, std::true_type \/* void *\/, meta::index_list, Args&&... args)\n\t\t{\n\t\t\tint top = lua_gettop(L);\n\n\t\t\tpush_arguments(L, std::forward(args)...);\n\n\t\t\tif (fn(L, sizeof...(Args), 0)) {\n\t\t\t\tassert(lua_gettop(L) == top - m_params + 1);\n\t\t\t\tcall_error(L);\n\t\t\t}\n\t\t\t\/\/ pops the return values from the function call\n\t\t\tstack_pop pop(L, lua_gettop(L) - top + m_params);\n\t\t}\n\n\t\ttemplate\n\t\tRet call_function_impl(lua_State* L, int m_params, Fn fn, std::false_type \/* void *\/ , meta::index_list, Args&&... args)\n\t\t{\n\t\t\tint top = lua_gettop(L);\n\t\t\t\n\t\t\tpush_arguments(L, std::forward(args)...);\n\n\t\t\tif (fn(L, sizeof...(Args), 1)) {\n\t\t\t\tassert(lua_gettop(L) == top - m_params + 1);\n\t\t\t\tcall_error(L);\n\t\t\t}\n\t\t\t\/\/ pops the return values from the function call\n\t\t\tstack_pop pop(L, lua_gettop(L) - top + m_params);\n\n\t\t\tspecialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;\n\t\t\tif (converter.match(L, decorated_type(), -1) < 0) {\n\t\t\t\tcast_error(L);\n\t\t\t}\n\n\t\t\treturn converter.to_cpp(L, decorated_type(), -1);\n\t\t}\n#else\n\t\ttemplate::value>\n\t\tstruct call_function_struct;\n\n\t\ttemplate\n\t\tstruct call_function_struct< Ret, PolicyList, meta::index_list, NumParams, Function, true \/* void *\/ >\n\t\t{\n\t\t\ttemplate< typename... Args >\n\t\t\tstatic void call(lua_State* L, Args&&... args) {\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\t\n\t\t\t\tpush_arguments(L, std::forward(args)...);\n\n\t\t\t\tif(Function(L, sizeof...(Args), 0)) {\n\t\t\t\t\tassert(lua_gettop(L)==top-NumParams+1);\n\t\t\t\t\tcall_error(L);\n\t\t\t\t}\n\t\t\t\t\/\/ pops the return values from the function call\n\t\t\t\tstack_pop pop(L, lua_gettop(L)-top+NumParams);\n\t\t\t}\n\t\t};\n\n\t\ttemplate\n\t\tstruct call_function_struct< Ret, PolicyList, meta::index_list, NumParams, Function, false \/* void *\/ >\n\t\t{\n\t\t\ttemplate< typename... Args >\n\t\t\tstatic Ret call(lua_State* L, Args&&... args) {\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\t\n\t\t\t\tpush_arguments(L, std::forward(args)...);\n\n\t\t\t\tif(Function(L, sizeof...(Args), 1)) {\n\t\t\t\t\tassert(lua_gettop(L)==top-NumParams+1);\n\t\t\t\t\tcall_error(L);\n\t\t\t\t}\n\t\t\t\t\/\/ pops the return values from the function call\n\t\t\t\tstack_pop pop(L, lua_gettop(L)-top+NumParams);\n\n\t\t\t\tspecialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;\n\t\t\t\tif(converter.match(L, decorated_type(), -1)<0) {\n\t\t\t\t\tcast_error(L);\n\t\t\t\t}\n\n\t\t\t\treturn converter.to_cpp(L, decorated_type(), -1);\n\t\t\t}\n\t\t};\n#endif\n\t}\n\n\ttemplate\n\tR call_pushed_function(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl(L, 1, &detail::pcall, std::is_void(), meta::index_range<1, sizeof...(Args) +1>(), std::forward(args)...);\n#else\n\t\treturn detail::call_function_struct, 1, &detail::pcall >::call(L, std::forward(args)...);\n#endif\n\t}\n\n\ttemplate\n\tR call_function(lua_State* L, const char* name, Args&&... args )\n\t{\n\t\tassert(name && \"luabind::call_function() expects a function name\");\n\t\tlua_getglobal(L, name);\n\t\treturn call_pushed_function(L, std::forward(args)...);\n\t}\n\n\ttemplate\n\tR resume_pushed_function(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl(L, 1, &detail::resume_impl, std::is_void(), meta::index_range<1, sizeof...(Args) +1>(), std::forward(args)...);\n#else\n\t\treturn detail::call_function_struct, 1, &detail::resume_impl >::call(L, std::forward(args)...);\n#endif\n\t}\n\n\ttemplate\n\tR resume_function(lua_State* L, const char* name, Args&&... args)\n\t{\n\t\tassert(name && \"luabind::resume_function() expects a function name\");\n\t\tlua_getglobal(L, name);\n\t\treturn resume_pushed_function(L, std::forward(args)...);\n\t}\n\n\ttemplate\n\tR resume(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl(L, 0, &detail::resume_impl, std::is_void(), meta::index_range<1, sizeof...(Args) +1>(), std::forward(args)...);\n#else\n\t\treturn detail::call_function_struct, 0, &detail::resume_impl >::call(L, std::forward(args)...);\n#endif\n\t}\n\n}\n\n#endif \/\/ LUABIND_CALL_FUNCTION_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"\/*\n spellcheckplugin.cpp\n\n Kopete Spell Checking plugin\n\n Copyright (c) 2003 by Jason Keirstead \n\n Kopete (c) 2002 by the Kopete developers \n\n *************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"kopeteviewmanager.h\"\n#include \"singlespellinstance.h\"\n#include \"spellcheckpreferences.h\"\n\nSingleSpellInstance::SingleSpellInstance( KopeteView *myView, SpellCheckPreferences *mPrefs ) : QObject( 0L )\n{\n\tmView = myView;\n\n\t\/\/If this object was created, we know we have a QTextEdit, so this is safe\n\tt = static_cast( mView->editWidget() );\n\tt->installEventFilter( this );\n\tt->viewport()->installEventFilter( this );\n\n\twords = 0L;\n\tspellCheckerReady = false;\n\n\t\/\/Define our word seperator regexp\n\t\/\/We can't use \\b because QT barfs when trying to split on it\n\tmBound = QRegExp( QString::fromLatin1(\"[\\\\s\\\\W]\") );\n\n\tmSpell = new KSpell(0L, i18n(\"Spellcheck - Kopete\"), this, SLOT( slotSpellCheckerReady( KSpell * )), mPrefs->spellConfig() );\n\tconnect( mSpell, SIGNAL( misspelling( const QString&, const QStringList&, unsigned int ) ), this, SLOT( slotMisspelling( const QString&, const QStringList&, unsigned int ) ) );\n\tconnect( dynamic_cast(mView), SIGNAL( destroyed() ), this, SLOT( slotViewDestroyed() ) );\n}\n\nSingleSpellInstance::~SingleSpellInstance()\n{\n\tkdDebug() << k_funcinfo << \"Destroying single speller instance\" << endl;\n\tspellCheckerReady = false;\n\tmSpell->cleanUp();\n\tdelete mSpell;\n\tdelete words;\n}\n\nvoid SingleSpellInstance::slotViewDestroyed()\n{\n\tdelete this;\n}\n\nvoid SingleSpellInstance::slotSpellCheckerReady( KSpell * )\n{\n\t\/\/kdDebug() << k_funcinfo << \"Single spell checker prepared!\" << endl;\n\tspellCheckerReady = true;\n}\n\nvoid SingleSpellInstance::slotUpdateTextEdit()\n{\n\tQString plainTextContents = t->text();\n\n\t\/\/Save the selection and cursor positions\n\tint parIdx = 1, txtIdx = 1;\n\tint selParFrom = 1, selTxtFrom = 1, selParTo = 1, selTxtTo = 1;\n\tt->getSelection(&selParFrom, &selTxtFrom, &selParTo, &selTxtTo);\n\tt->getCursorPosition(&parIdx, &txtIdx);\n\n\t\/\/Don't use red if the current color is too red\n\tQString highlightColor;\n\tif( t->paletteForegroundColor().red() < 250 )\n\t\thighlightColor = QString::fromLatin1(\"red\");\n\telse\n\t\thighlightColor = QString::fromLatin1(\"blue\");\n\n\tQStringList words = QStringList::split( mBound, plainTextContents );\n\tif( words.count() > 0 )\n\t{\n\t\tfor( QStringList::Iterator it = words.begin(); it != words.end(); ++it )\n\t\t{\n\t\t\tif( mReplacements.contains(*it) )\n\t\t\t{\n\t\t\t\tplainTextContents.replace( QRegExp( QString::fromLatin1(\"\\\\b(%1)\\\\b\").arg( *it ) ),\n\t\t\t\t\tQString::fromLatin1(\"\") + *it +\n\t\t\t\t\tQString::fromLatin1(\"<\/font>\") );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/Update the highlighting\n\tt->setTextFormat( QTextEdit::RichText );\n\tt->setText( plainTextContents );\n\tt->setTextFormat( QTextEdit::PlainText );\n\n\t\/\/Restore the selection and cursor positions\n\tt->setCursorPosition( parIdx, txtIdx );\n\tif( selParFrom > -1 )\n\t\tt->setSelection( selParFrom, selTxtFrom, selParTo, selTxtTo );\n}\n\nvoid SingleSpellInstance::slotMisspelling( const QString &originalword, const QStringList &suggestions, unsigned int )\n{\n\t\/\/kdDebug() << k_funcinfo << originalword << \"IS MISSPELLED!\" << endl;\n\n\tif( !mReplacements.contains( originalword ) )\n\t\tmReplacements[originalword] = suggestions;\n\n\tslotUpdateTextEdit();\n}\n\nbool SingleSpellInstance::eventFilter(QObject *o, QEvent *e)\n{\n\tQWidget *w = static_cast( o );\n\n\tswitch( e->type() )\n\t{\n\t\t\/\/Keypress event, to do the actual checking\n\t\tcase QEvent::KeyPress:\n\t\t{\n\t\t\tif( spellCheckerReady )\n\t\t\t{\n\t\t\t\tQKeyEvent *event = (QKeyEvent*) e;\n\n\t\t\t\t\/\/Only spellcheck when we hit a word delimiter\n\t\t\t\tif( !QChar( event->ascii() ).isLetterOrNumber() )\n\t\t\t\t{\n\t\t\t\t\t\/\/We need to use an actual pointer for this, not just pass in the address of a veriable,\n\t\t\t\t\t\/\/because KSpell is async and the variable will be deleted before KSpell completes\n\t\t\t\t\tdelete words;\n\t\t\t\t\twords = new QStringList( QStringList::split( mBound, t->text() ) );\n\t\t\t\t\tif( words->count() > 0 )\n\t\t\t\t\t\tmSpell->checkList( words, false );\n\t\t\t\t}\n\n\t\t\t\t\/\/Update highlighting\n\t\t\t\tslotUpdateTextEdit();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ContextMenu, to enable right click replace menu\n\t\tcase QEvent::ContextMenu:\n\t\t{\n\t\t\tif ( spellCheckerReady )\n\t\t\t{\n\t\t\t\tQContextMenuEvent *event = (QContextMenuEvent*) e;\n\n\t\t\t\tint para = 0, charPos, firstSpace, lastSpace;\n\n\t\t\t\t\/\/Get the character at the position of the click\n\t\t\t\tQString paraText = t->text( para );\n\t\t\t\tcharPos = t->charAt( event->pos(), ¶ );\n\n\t\t\t\tif( !paraText.at(charPos).isSpace() )\n\t\t\t\t{\n\t\t\t\t\t\/\/Get word right clicked on\n\t\t\t\t\tfirstSpace = paraText.findRev( mBound, charPos ) + 1;\n\t\t\t\t\tlastSpace = paraText.find( mBound, charPos );\n\t\t\t\t\tif( lastSpace == -1 )\n\t\t\t\t\t\tlastSpace = paraText.length();\n\t\t\t\t\tQString word = paraText.mid( firstSpace, lastSpace - firstSpace );\n\n\t\t\t\t\t\/\/Continue if this word was misspelled\n\t\t\t\t\tif( !word.isEmpty() && mReplacements.contains( word ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tKPopupMenu p;\n\t\t\t\t\t\tp.insertTitle( i18n(\"Suggestions\") );\n\n\t\t\t\t\t\t\/\/Add the suggesitons to the popup menu\n\t\t\t\t\t\tQStringList reps = mReplacements[word];\n\t\t\t\t\t\tif( reps.count() > 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint listPos = 0;\n\t\t\t\t\t\t\tfor ( QStringList::Iterator it = reps.begin(); it != reps.end(); ++it ) {\n\t\t\t\t\t\t\t\tp.insertItem( *it, listPos );\n\t\t\t\t\t\t\t\tlistPos++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tp.insertItem( QString::fromLatin1(\"No Suggestions\"), -2 );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/Execute the popup inline\n\t\t\t\t\t\tint id = p.exec( w->mapToGlobal( event->pos() ) );\n\n\t\t\t\t\t\tif( id > -1 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/Save the cursor position\n\t\t\t\t\t\t\tint parIdx = 1, txtIdx = 1;\n\t\t\t\t\t\t\tt->getCursorPosition(&parIdx, &txtIdx);\n\n\t\t\t\t\t\t\t\/\/Put in our replacement\n\t\t\t\t\t\t\tQString txtContents = t->text();\n\t\t\t\t\t\t\tQString newContents = txtContents.left(firstSpace) + mReplacements[word][id] +\n\t\t\t\t\t\t\t\ttxtContents.right( txtContents.length() - lastSpace );\n\t\t\t\t\t\t\tt->setText( newContents );\n\n\t\t\t\t\t\t\t\/\/Restore the cursor position\n\t\t\t\t\t\t\tif( txtIdx > lastSpace )\n\t\t\t\t\t\t\t\ttxtIdx += newContents.length() - txtContents.length();\n\t\t\t\t\t\t\tt->setCursorPosition(parIdx, txtIdx);\n\n\t\t\t\t\t\t\t\/\/Update highlighting\n\t\t\t\t\t\t\tslotUpdateTextEdit();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/Cancel original event\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\t\/\/Return false so events keep propegating\n\treturn false;\n}\n\nFixed a minor bug involving multiple paragraphs\/*\n spellcheckplugin.cpp\n\n Kopete Spell Checking plugin\n\n Copyright (c) 2003 by Jason Keirstead \n\n Kopete (c) 2002 by the Kopete developers \n\n *************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"kopeteviewmanager.h\"\n#include \"singlespellinstance.h\"\n#include \"spellcheckpreferences.h\"\n\nSingleSpellInstance::SingleSpellInstance( KopeteView *myView, SpellCheckPreferences *mPrefs ) : QObject( 0L )\n{\n\tmView = myView;\n\n\t\/\/If this object was created, we know we have a QTextEdit, so this is safe\n\tt = static_cast( mView->editWidget() );\n\tt->installEventFilter( this );\n\tt->viewport()->installEventFilter( this );\n\n\twords = 0L;\n\tspellCheckerReady = false;\n\n\t\/\/Define our word seperator regexp\n\t\/\/We can't use \\b because QT barfs when trying to split on it\n\tmBound = QRegExp( QString::fromLatin1(\"[\\\\s\\\\W]\") );\n\n\tmSpell = new KSpell(0L, i18n(\"Spellcheck - Kopete\"), this, SLOT( slotSpellCheckerReady( KSpell * )), mPrefs->spellConfig() );\n\tconnect( mSpell, SIGNAL( misspelling( const QString&, const QStringList&, unsigned int ) ), this, SLOT( slotMisspelling( const QString&, const QStringList&, unsigned int ) ) );\n\tconnect( dynamic_cast(mView), SIGNAL( destroyed() ), this, SLOT( slotViewDestroyed() ) );\n}\n\nSingleSpellInstance::~SingleSpellInstance()\n{\n\tkdDebug() << k_funcinfo << \"Destroying single speller instance\" << endl;\n\tspellCheckerReady = false;\n\tmSpell->cleanUp();\n\tdelete mSpell;\n\tdelete words;\n}\n\nvoid SingleSpellInstance::slotViewDestroyed()\n{\n\tdelete this;\n}\n\nvoid SingleSpellInstance::slotSpellCheckerReady( KSpell * )\n{\n\t\/\/kdDebug() << k_funcinfo << \"Single spell checker prepared!\" << endl;\n\tspellCheckerReady = true;\n}\n\nvoid SingleSpellInstance::slotUpdateTextEdit()\n{\n\tQString plainTextContents = t->text();\n\n\t\/\/Save the selection and cursor positions\n\tint parIdx = 1, txtIdx = 1;\n\tint selParFrom = 1, selTxtFrom = 1, selParTo = 1, selTxtTo = 1;\n\tt->getSelection(&selParFrom, &selTxtFrom, &selParTo, &selTxtTo);\n\tt->getCursorPosition(&parIdx, &txtIdx);\n\n\t\/\/Don't use red if the current color is too red\n\tQString highlightColor;\n\tif( t->paletteForegroundColor().red() < 250 )\n\t\thighlightColor = QString::fromLatin1(\"red\");\n\telse\n\t\thighlightColor = QString::fromLatin1(\"blue\");\n\n\tQStringList words = QStringList::split( mBound, plainTextContents );\n\tif( words.count() > 0 )\n\t{\n\t\tfor( QStringList::Iterator it = words.begin(); it != words.end(); ++it )\n\t\t{\n\t\t\tif( mReplacements.contains(*it) )\n\t\t\t{\n\t\t\t\tplainTextContents.replace( QRegExp( QString::fromLatin1(\"\\\\b(%1)\\\\b\").arg( *it ) ),\n\t\t\t\t\tQString::fromLatin1(\"\") + *it +\n\t\t\t\t\tQString::fromLatin1(\"<\/font>\") );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/Update the highlighting\n\tt->setTextFormat( QTextEdit::RichText );\n\tt->setText( plainTextContents );\n\tt->setTextFormat( QTextEdit::PlainText );\n\n\t\/\/Restore the selection and cursor positions\n\tt->setCursorPosition( parIdx, txtIdx );\n\tif( selParFrom > -1 )\n\t\tt->setSelection( selParFrom, selTxtFrom, selParTo, selTxtTo );\n}\n\nvoid SingleSpellInstance::slotMisspelling( const QString &originalword, const QStringList &suggestions, unsigned int )\n{\n\t\/\/kdDebug() << k_funcinfo << originalword << \"IS MISSPELLED!\" << endl;\n\n\tif( !mReplacements.contains( originalword ) )\n\t\tmReplacements[originalword] = suggestions;\n\n\tslotUpdateTextEdit();\n}\n\nbool SingleSpellInstance::eventFilter(QObject *o, QEvent *e)\n{\n\tQWidget *w = static_cast( o );\n\n\tswitch( e->type() )\n\t{\n\t\t\/\/Keypress event, to do the actual checking\n\t\tcase QEvent::KeyPress:\n\t\t{\n\t\t\tif( spellCheckerReady )\n\t\t\t{\n\t\t\t\tQKeyEvent *event = (QKeyEvent*) e;\n\n\t\t\t\t\/\/Only spellcheck when we hit a word delimiter\n\t\t\t\tif( !QChar( event->ascii() ).isLetterOrNumber() )\n\t\t\t\t{\n\t\t\t\t\t\/\/We need to use an actual pointer for this, not just pass in the address of a veriable,\n\t\t\t\t\t\/\/because KSpell is async and the variable will be deleted before KSpell completes\n\t\t\t\t\tdelete words;\n\t\t\t\t\twords = new QStringList( QStringList::split( mBound, t->text() ) );\n\t\t\t\t\tif( words->count() > 0 )\n\t\t\t\t\t\tmSpell->checkList( words, false );\n\t\t\t\t}\n\n\t\t\t\t\/\/Update highlighting\n\t\t\t\tslotUpdateTextEdit();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ContextMenu, to enable right click replace menu\n\t\tcase QEvent::ContextMenu:\n\t\t{\n\t\t\tif ( spellCheckerReady )\n\t\t\t{\n\t\t\t\tQContextMenuEvent *event = (QContextMenuEvent*) e;\n\n\t\t\t\tint para = 1, charPos, firstSpace, lastSpace;\n\n\t\t\t\t\/\/Get the character at the position of the click\n\t\t\t\tcharPos = t->charAt( event->pos(), ¶ );\n\t\t\t\tQString paraText = t->text( para );\n\n\t\t\t\tif( !paraText.at(charPos).isSpace() )\n\t\t\t\t{\n\t\t\t\t\t\/\/Get word right clicked on\n\t\t\t\t\tfirstSpace = paraText.findRev( mBound, charPos ) + 1;\n\t\t\t\t\tlastSpace = paraText.find( mBound, charPos );\n\t\t\t\t\tif( lastSpace == -1 )\n\t\t\t\t\t\tlastSpace = paraText.length();\n\t\t\t\t\tQString word = paraText.mid( firstSpace, lastSpace - firstSpace );\n\n\t\t\t\t\t\/\/Continue if this word was misspelled\n\t\t\t\t\tif( !word.isEmpty() && mReplacements.contains( word ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tKPopupMenu p;\n\t\t\t\t\t\tp.insertTitle( i18n(\"Suggestions\") );\n\n\t\t\t\t\t\t\/\/Add the suggestions to the popup menu\n\t\t\t\t\t\tQStringList reps = mReplacements[word];\n\t\t\t\t\t\tif( reps.count() > 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint listPos = 0;\n\t\t\t\t\t\t\tfor ( QStringList::Iterator it = reps.begin(); it != reps.end(); ++it ) {\n\t\t\t\t\t\t\t\tp.insertItem( *it, listPos );\n\t\t\t\t\t\t\t\tlistPos++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tp.insertItem( QString::fromLatin1(\"No Suggestions\"), -2 );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/Execute the popup inline\n\t\t\t\t\t\tint id = p.exec( w->mapToGlobal( event->pos() ) );\n\n\t\t\t\t\t\tif( id > -1 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/Save the cursor position\n\t\t\t\t\t\t\tint parIdx = 1, txtIdx = 1;\n\t\t\t\t\t\t\tt->getCursorPosition(&parIdx, &txtIdx);\n\n\t\t\t\t\t\t\t\/\/Put in our replacement\n\t\t\t\t\t\t\tQString txtContents = t->text();\n\t\t\t\t\t\t\tQString newContents = txtContents.left(firstSpace) + mReplacements[word][id] +\n\t\t\t\t\t\t\t\ttxtContents.right( txtContents.length() - lastSpace );\n\t\t\t\t\t\t\tt->setText( newContents );\n\n\t\t\t\t\t\t\t\/\/Restore the cursor position\n\t\t\t\t\t\t\tif( txtIdx > lastSpace )\n\t\t\t\t\t\t\t\ttxtIdx += newContents.length() - txtContents.length();\n\t\t\t\t\t\t\tt->setCursorPosition(parIdx, txtIdx);\n\n\t\t\t\t\t\t\t\/\/Update highlighting\n\t\t\t\t\t\t\tslotUpdateTextEdit();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/Cancel original event\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\t\/\/Return false so events keep propegating\n\treturn false;\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 \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \"au\/LockDebugger.h\" \/\/ au::LockDebugger\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\/network\/Network2.h\"\n#include \"samson\/network\/Endpoint2.h\"\n#include \"samson\/network\/EndpointManager.h\"\n#include \"samson\/worker\/SamsonWorker.h\"\n#include \"samson\/common\/SamsonSetup.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*\/\nbool noLog;\nbool local;\nchar workingDir[1024];\n\n\n\n#define NOLS _i \"no log server\"\n#define DEF_WD _i SAMSON_DEFAULT_WORKING_DIRECTORY\n\/* ****************************************************************************\n*\n* parse arguments\n*\/\nPaArgument paArgs[] =\n{\n\t{ \"-nolog\", &noLog, \"NO_LOG\", PaBool, PaOpt, false, false, true, \"no logging\" },\n\t{ \"-local\", &local, \"LOCAL\", PaBool, PaOpt, false, false, true, \"local execution\" },\n\t{ \"-working\", workingDir, \"WORKING\", PaString, PaOpt, DEF_WD, PaNL, PaNL, \"working directory\" },\n\n\tPA_END_OF_ARGS\n};\n\n\n\n\/* ****************************************************************************\n*\n* logFd - file descriptor for log file used in all libraries\n*\/\nint logFd = -1;\nsamson::SamsonWorker* worker = NULL;\n\n\n\n\/* ****************************************************************************\n*\n* exitFunction - \n*\/\nvoid exitFunction(void)\n{\n\tif (worker)\n\t\tdelete worker;\n\n\tif (progName)\n\t\tfree(progName);\n}\n\n\n\n\/* ****************************************************************************\n*\n* man texts -\n*\/\nstatic const char* manSynopsis = \" [OPTION]\";\nstatic const char* manShortDescription = \"samsonWorker is the worker process of the samson platform, ...\\n\\n\"\n \"Complete list of options:\\n\";\nstatic const char* manDescription =\n \"samsonWorker is the worker process in the samson cluster,\\n\"\n \"which consists of one or more workers and ONE controller ...\\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-bug-report@tid.es\\nSamson home page: \";\nstatic const char* manCopyright = \"Copyright (C) 2011 Telefonica Investigacion y Desarrollo\";\nstatic const char* manVersion = \"0.6-1\";\n\n\n\nvoid captureSIGPIPE( int s )\n{\n LM_M((\"Capturing SIGPIPE\"));\n}\n\n\n\/* ****************************************************************************\n*\n* main - \n*\/\nint main(int argC, const char *argV[])\n{\n\tpaConfig(\"prefix\", (void*) \"SSW_\");\n\tpaConfig(\"usage and exit on any warning\", (void*) true);\n\tpaConfig(\"log to screen\", (void*) \"only errors\");\n\tpaConfig(\"log file line format\", (void*) \"TYPE:DATE:EXEC-AUX\/FILE[LINE](p.PID) FUNC: TEXT\");\n\tpaConfig(\"screen line format\", (void*) \"TYPE@TIME EXEC: TEXT\");\n\tpaConfig(\"log to file\", (void*) true);\n\n\tpaConfig(\"man synopsis\", (void*) manSynopsis);\n\tpaConfig(\"man shortdescription\", (void*) manShortDescription);\n\tpaConfig(\"man description\", (void*) manDescription);\n\tpaConfig(\"man exitstatus\", (void*) manExitStatus);\n\tpaConfig(\"man author\", (void*) manAuthor);\n\tpaConfig(\"man reportingbugs\", (void*) manReportingBugs);\n\tpaConfig(\"man copyright\", (void*) manCopyright);\n\tpaConfig(\"man version\", (void*) manVersion);\n\n \n\tpaParse(paArgs, argC, (char**) argV, 1, false);\n\n\tlmAux((char*) \"father\");\n\n\tatexit(google::protobuf::ShutdownProtobufLibrary);\n\tatexit(exitFunction);\n\n\tLM_T(LmtInit, (\"Started with arguments:\"));\n\tfor (int ix = 0; ix < argC; ix++)\n\t\tLM_T(LmtInit, (\" %02d: '%s'\", ix, argV[ix]));\n\n\tlogFd = lmFirstDiskFileDescriptor();\n \n \/\/ Capturing SIGPIPE\n if( signal( SIGPIPE , captureSIGPIPE ) == SIG_ERR )\n LM_W((\"SIGPIPE cannot be handled\"));\n \n \/\/ Make sure this singlelton is created just once\n au::LockDebugger::shared();\n \n\tsamson::SamsonSetup::init(); \/\/ Load setup and create default directories\n samson::SamsonSetup::shared()->setWorkingDirectory(workingDir);\n \n\tengine::SharedMemoryManager::init(samson::SamsonSetup::getInt(\"general.num_processess\") , samson::SamsonSetup::getUInt64(\"general.shared_memory_size_per_buffer\"));\n\tengine::Engine::init();\n\tengine::DiskManager::init(1);\n\tengine::ProcessManager::init(samson::SamsonSetup::getInt(\"general.num_processess\"));\n\tengine::MemoryManager::init(samson::SamsonSetup::getUInt64(\"general.memory\"));\n\tsamson::ModulesManager::init();\n samson::stream::BlockManager::init();\n\n \n\t\/\/ Instance of network object and initialization\n\t\/\/ --------------------------------------------------------------------\n\tsamson::EndpointManager* epMgr = new samson::EndpointManager(samson::Endpoint2::Worker);\n\tsamson::Network2* networkP = new samson::Network2(epMgr);\n\n\n\tLM_T(LmtInit, (\"Waiting for network connection ...\"));\n\tnetworkP->runInBackground();\n\n\twhile (!networkP->ready())\n\t\tsleep(1);\n\n\tLM_T(LmtInit, (\"Network Ready\"));\n\t\n\t\/\/ Instance of SamsonWorker object (network contains at least the number of wokers)\n\t\/\/ -----------------------------------------------------------------------------------\n\t\n\tworker = new samson::SamsonWorker(networkP);\n\n\t\/\/ Not necessary anymore. Engine automatically starts with \"init\" call\n\t\/\/ engine::Engine::run();\n \n while( true )\n sleep(10);\n}\nFix broken compilation undex linux\/* ****************************************************************************\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 \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \n\n\n#include \"au\/LockDebugger.h\" \/\/ au::LockDebugger\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\/network\/Network2.h\"\n#include \"samson\/network\/Endpoint2.h\"\n#include \"samson\/network\/EndpointManager.h\"\n#include \"samson\/worker\/SamsonWorker.h\"\n#include \"samson\/common\/SamsonSetup.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*\/\nbool noLog;\nbool local;\nchar workingDir[1024];\n\n\n\n#define NOLS _i \"no log server\"\n#define DEF_WD _i SAMSON_DEFAULT_WORKING_DIRECTORY\n\/* ****************************************************************************\n*\n* parse arguments\n*\/\nPaArgument paArgs[] =\n{\n\t{ \"-nolog\", &noLog, \"NO_LOG\", PaBool, PaOpt, false, false, true, \"no logging\" },\n\t{ \"-local\", &local, \"LOCAL\", PaBool, PaOpt, false, false, true, \"local execution\" },\n\t{ \"-working\", workingDir, \"WORKING\", PaString, PaOpt, DEF_WD, PaNL, PaNL, \"working directory\" },\n\n\tPA_END_OF_ARGS\n};\n\n\n\n\/* ****************************************************************************\n*\n* logFd - file descriptor for log file used in all libraries\n*\/\nint logFd = -1;\nsamson::SamsonWorker* worker = NULL;\n\n\n\n\/* ****************************************************************************\n*\n* exitFunction - \n*\/\nvoid exitFunction(void)\n{\n\tif (worker)\n\t\tdelete worker;\n\n\tif (progName)\n\t\tfree(progName);\n}\n\n\n\n\/* ****************************************************************************\n*\n* man texts -\n*\/\nstatic const char* manSynopsis = \" [OPTION]\";\nstatic const char* manShortDescription = \"samsonWorker is the worker process of the samson platform, ...\\n\\n\"\n \"Complete list of options:\\n\";\nstatic const char* manDescription =\n \"samsonWorker is the worker process in the samson cluster,\\n\"\n \"which consists of one or more workers and ONE controller ...\\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-bug-report@tid.es\\nSamson home page: \";\nstatic const char* manCopyright = \"Copyright (C) 2011 Telefonica Investigacion y Desarrollo\";\nstatic const char* manVersion = \"0.6-1\";\n\n\n\nvoid captureSIGPIPE( int s )\n{\n LM_M((\"Capturing SIGPIPE\"));\n}\n\n\n\/* ****************************************************************************\n*\n* main - \n*\/\nint main(int argC, const char *argV[])\n{\n\tpaConfig(\"prefix\", (void*) \"SSW_\");\n\tpaConfig(\"usage and exit on any warning\", (void*) true);\n\tpaConfig(\"log to screen\", (void*) \"only errors\");\n\tpaConfig(\"log file line format\", (void*) \"TYPE:DATE:EXEC-AUX\/FILE[LINE](p.PID) FUNC: TEXT\");\n\tpaConfig(\"screen line format\", (void*) \"TYPE@TIME EXEC: TEXT\");\n\tpaConfig(\"log to file\", (void*) true);\n\n\tpaConfig(\"man synopsis\", (void*) manSynopsis);\n\tpaConfig(\"man shortdescription\", (void*) manShortDescription);\n\tpaConfig(\"man description\", (void*) manDescription);\n\tpaConfig(\"man exitstatus\", (void*) manExitStatus);\n\tpaConfig(\"man author\", (void*) manAuthor);\n\tpaConfig(\"man reportingbugs\", (void*) manReportingBugs);\n\tpaConfig(\"man copyright\", (void*) manCopyright);\n\tpaConfig(\"man version\", (void*) manVersion);\n\n \n\tpaParse(paArgs, argC, (char**) argV, 1, false);\n\n\tlmAux((char*) \"father\");\n\n\tatexit(google::protobuf::ShutdownProtobufLibrary);\n\tatexit(exitFunction);\n\n\tLM_T(LmtInit, (\"Started with arguments:\"));\n\tfor (int ix = 0; ix < argC; ix++)\n\t\tLM_T(LmtInit, (\" %02d: '%s'\", ix, argV[ix]));\n\n\tlogFd = lmFirstDiskFileDescriptor();\n \n \/\/ Capturing SIGPIPE\n if( signal( SIGPIPE , captureSIGPIPE ) == SIG_ERR )\n LM_W((\"SIGPIPE cannot be handled\"));\n \n \/\/ Make sure this singlelton is created just once\n au::LockDebugger::shared();\n \n\tsamson::SamsonSetup::init(); \/\/ Load setup and create default directories\n samson::SamsonSetup::shared()->setWorkingDirectory(workingDir);\n \n\tengine::SharedMemoryManager::init(samson::SamsonSetup::getInt(\"general.num_processess\") , samson::SamsonSetup::getUInt64(\"general.shared_memory_size_per_buffer\"));\n\tengine::Engine::init();\n\tengine::DiskManager::init(1);\n\tengine::ProcessManager::init(samson::SamsonSetup::getInt(\"general.num_processess\"));\n\tengine::MemoryManager::init(samson::SamsonSetup::getUInt64(\"general.memory\"));\n\tsamson::ModulesManager::init();\n samson::stream::BlockManager::init();\n\n \n\t\/\/ Instance of network object and initialization\n\t\/\/ --------------------------------------------------------------------\n\tsamson::EndpointManager* epMgr = new samson::EndpointManager(samson::Endpoint2::Worker);\n\tsamson::Network2* networkP = new samson::Network2(epMgr);\n\n\n\tLM_T(LmtInit, (\"Waiting for network connection ...\"));\n\tnetworkP->runInBackground();\n\n\twhile (!networkP->ready())\n\t\tsleep(1);\n\n\tLM_T(LmtInit, (\"Network Ready\"));\n\t\n\t\/\/ Instance of SamsonWorker object (network contains at least the number of wokers)\n\t\/\/ -----------------------------------------------------------------------------------\n\t\n\tworker = new samson::SamsonWorker(networkP);\n\n\t\/\/ Not necessary anymore. Engine automatically starts with \"init\" call\n\t\/\/ engine::Engine::run();\n \n while( true )\n sleep(10);\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief document request handler\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2004-2013 triAGENS GmbH, Cologne, Germany\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\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"RestEdgeHandler.h\"\n\n#include \"Basics\/StringUtils.h\"\n#include \"BasicsC\/conversions.h\"\n#include \"BasicsC\/tri-strings.h\"\n#include \"Rest\/HttpRequest.h\"\n#include \"VocBase\/document-collection.h\"\n#include \"VocBase\/edge-collection.h\"\n#include \"Utilities\/ResourceHolder.h\"\n\nusing namespace std;\nusing namespace triagens::basics;\nusing namespace triagens::rest;\nusing namespace triagens::arango;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup ArangoDB\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRestEdgeHandler::RestEdgeHandler (HttpRequest* request, TRI_vocbase_t* vocbase)\n : RestDocumentHandler(request, vocbase) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- protected methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup ArangoDB\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates an edge\n\/\/\/\n\/\/\/ @RESTHEADER{POST \/_api\/edge,creates an edge}\n\/\/\/\n\/\/\/ @REST{POST \/_api\/edge?collection=`collection-name`&from=`from-handle`&to=`to-handle`}\n\/\/\/\n\/\/\/ Creates a new edge in the collection identified by `collection-name`.\n\/\/\/ A JSON representation of the edge document must be passed as the body of\n\/\/\/ the POST request. This JSON object may contain the edge's document key in\n\/\/\/ the `_key` attribute if needed.\n\/\/\/ The document handle of the start point must be passed in `from-handle`.\n\/\/\/ The document handle of the end point must be passed in `to-handle`.\n\/\/\/\n\/\/\/ `from-handle` and `to-handle` are immutable once the edge has been\n\/\/\/ created.\n\/\/\/\n\/\/\/ In all other respects the method works like `POST \/document`, see\n\/\/\/ @ref RestDocument for details.\n\/\/\/\n\/\/\/ @EXAMPLES\n\/\/\/\n\/\/\/ Create an edge:\n\/\/\/\n\/\/\/ @verbinclude rest-edge-create-edge\n\/\/\/\n\/\/\/ Read an edge:\n\/\/\/\n\/\/\/ @verbinclude rest-edge-read-edge\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool RestEdgeHandler::createDocument () {\n vector const& suffix = _request->suffix();\n\n if (suffix.size() != 0) {\n generateError(HttpResponse::BAD,\n TRI_ERROR_HTTP_SUPERFLUOUS_SUFFICES,\n \"superfluous suffix, expecting \" + EDGE_PATH + \"?collection=\");\n return false;\n }\n\n \/\/ edge\n TRI_document_edge_t edge;\n\n \/\/ extract the from\n bool found;\n char const* from = _request->value(\"from\", found);\n\n if (! found || *from == '\\0') {\n generateError(HttpResponse::BAD,\n TRI_ERROR_HTTP_BAD_PARAMETER,\n \"'from' is missing, expecting \" + EDGE_PATH + \"?collection=&from=&to=\");\n return false;\n }\n\n \/\/ extract the to\n char const* to = _request->value(\"to\", found);\n\n if (! found || *to == '\\0') {\n generateError(HttpResponse::BAD,\n TRI_ERROR_HTTP_BAD_PARAMETER,\n \"'to' is missing, expecting \" + EDGE_PATH + \"?collection=&from=&to=\");\n return false;\n }\n\n \/\/ extract the cid\n const string& collection = _request->value(\"collection\", found);\n\n if (! found || collection.empty()) {\n generateError(HttpResponse::BAD,\n TRI_ERROR_ARANGO_COLLECTION_PARAMETER_MISSING,\n \"'collection' is missing, expecting \" + DOCUMENT_PATH + \"?collection=\");\n return false;\n }\n\n const bool waitForSync = extractWaitForSync();\n\n \/\/ auto-ptr that will free JSON data when scope is left\n ResourceHolder holder;\n\n TRI_json_t* json = parseJsonBody();\n if (! holder.registerJson(TRI_UNKNOWN_MEM_ZONE, json)) {\n return false;\n }\n \n if (json->_type != TRI_JSON_ARRAY) {\n generateTransactionError(collection, TRI_ERROR_ARANGO_DOCUMENT_TYPE_INVALID);\n return false;\n }\n\n if (! checkCreateCollection(collection, getCollectionType())) {\n return false;\n }\n\n \/\/ find and load collection given by name or identifier\n SingleCollectionWriteTransaction, 1> trx(_vocbase, _resolver, collection);\n\n \/\/ .............................................................................\n \/\/ inside write transaction\n \/\/ .............................................................................\n\n int res = trx.begin();\n if (res != TRI_ERROR_NO_ERROR) {\n generateTransactionError(collection, res);\n return false;\n }\n\n const TRI_voc_cid_t cid = trx.cid();\n\n edge._fromCid = cid;\n edge._toCid = cid;\n edge._fromKey = 0;\n edge._toKey = 0;\n\n res = parseDocumentId(from, edge._fromCid, edge._fromKey);\n holder.registerString(TRI_CORE_MEM_ZONE, edge._fromKey);\n\n if (res != TRI_ERROR_NO_ERROR) {\n if (res == TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND) {\n generateError(HttpResponse::NOT_FOUND, res, \"'from' does not point to a valid collection\");\n }\n else {\n generateError(HttpResponse::BAD, res, \"'from' is not a document handle\");\n }\n return false;\n }\n\n res = parseDocumentId(to, edge._toCid, edge._toKey);\n holder.registerString(TRI_CORE_MEM_ZONE, edge._toKey);\n\n if (res != TRI_ERROR_NO_ERROR) {\n if (res == TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND) {\n generateError(HttpResponse::NOT_FOUND, res, \"'to' does not point to a valid collection\");\n }\n else {\n generateError(HttpResponse::BAD, res, \"'to' is not a document handle\");\n }\n return false;\n }\n\n \/\/ .............................................................................\n \/\/ inside write transaction\n \/\/ .............................................................................\n\n \/\/ will hold the result\n TRI_doc_mptr_t document;\n res = trx.createEdge(&document, json, waitForSync, &edge);\n const bool wasSynchronous = trx.synchronous();\n res = trx.finish(res);\n\n \/\/ .............................................................................\n \/\/ outside write transaction\n \/\/ .............................................................................\n\n if (res != TRI_ERROR_NO_ERROR) {\n generateTransactionError(collection, res);\n return false;\n }\n\n assert(document._key != 0);\n\n \/\/ generate result\n if (wasSynchronous) {\n generateCreated(cid, document._key, document._rid);\n }\n else {\n generateAccepted(cid, document._key, document._rid);\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\nminor changes\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief document request handler\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2004-2013 triAGENS GmbH, Cologne, Germany\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\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"RestEdgeHandler.h\"\n\n#include \"Basics\/StringUtils.h\"\n#include \"BasicsC\/conversions.h\"\n#include \"BasicsC\/tri-strings.h\"\n#include \"Rest\/HttpRequest.h\"\n#include \"VocBase\/document-collection.h\"\n#include \"VocBase\/edge-collection.h\"\n#include \"Utilities\/ResourceHolder.h\"\n\nusing namespace std;\nusing namespace triagens::basics;\nusing namespace triagens::rest;\nusing namespace triagens::arango;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup ArangoDB\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRestEdgeHandler::RestEdgeHandler (HttpRequest* request, TRI_vocbase_t* vocbase)\n : RestDocumentHandler(request, vocbase) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- protected methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup ArangoDB\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates an edge\n\/\/\/\n\/\/\/ @RESTHEADER{POST \/_api\/edge,creates an edge}\n\/\/\/\n\/\/\/ @RESTQUERYPARAMETERS\n\/\/\/\n\/\/\/ @RESTQUERYPARAM{collection,string,required}\n\/\/\/ Creates a new edge in the collection identified by `collection` name.\n\/\/\/\n\/\/\/ @RESTQUERYPARAM{from,string,required}\n\/\/\/ The document handle of the start point must be passed in `from` handle.\n\/\/\/\n\/\/\/ @RESTQUERYPARAM{to,string,required}\n\/\/\/ The document handle of the end point must be passed in `to` handle.\n\/\/\/\n\/\/\/ @RESTBODYPARAM{edge-document,json,required}\n\/\/\/ A JSON representation of the edge document must be passed as the body of\n\/\/\/ the POST request. This JSON object may contain the edge's document key in\n\/\/\/ the `_key` attribute if needed.\n\/\/\/\n\/\/\/ @RESTDESCRIPTION\n\/\/\/ `from` handle and `to` handle are immutable once the edge has been\n\/\/\/ created.\n\/\/\/\n\/\/\/ In all other respects the method works like `POST \/document`, see\n\/\/\/ @ref RestDocument for details.\n\/\/\/\n\/\/\/ @RESTRETURNCODES\n\/\/\/\n\/\/\/ @RESTRETURNCODE{202}\n\/\/\/ is returned if the edge was created successfully.\n\/\/\/\n\/\/\/ @RESTRETURNCODE{404}\n\/\/\/ is returned if the edge collection was not found.\n\/\/\/\n\/\/\/ @EXAMPLES\n\/\/\/\n\/\/\/ Create an edge and reads it back:\n\/\/\/\n\/\/\/ @EXAMPLE_ARANGOSH_RUN{RestEdgeCreateEdge}\n\/\/\/ db._drop(\"edges\");\n\/\/\/ db._drop(\"vertices\");\n\/\/\/ var Graph = require(\"org\/arangodb\/graph\").Graph;\n\/\/\/ var g = new Graph(\"graph\", \"vertices\", \"edges\");\n\/\/\/ g.addVertex(1);\n\/\/\/ g.addVertex(2);\n\/\/\/ var url = \"\/_api\/edge\/?collection=edges&from=vertices\/1&to=vertices\/2\";\n\/\/\/ \n\/\/\/ var response = logCurlRequest(\"POST\", url, { \"name\": \"Emil\" });\n\/\/\/ \n\/\/\/ assert(response.code === 202);\n\/\/\/\n\/\/\/ logJsonResponse(response);\n\/\/\/ var body = response.body.replace(\/\\\\\/g, '');\n\/\/\/ var edge_id = JSON.parse(body)._id;\n\/\/\/ var response2 = logCurlRequest(\"GET\", \"\/_api\/edge\/\" + edge_id);\n\/\/\/ \n\/\/\/ assert(response2.code === 200);\n\/\/\/\n\/\/\/ logJsonResponse(response2);\n\/\/\/ @END_EXAMPLE_ARANGOSH_RUN\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool RestEdgeHandler::createDocument () {\n vector const& suffix = _request->suffix();\n\n if (suffix.size() != 0) {\n generateError(HttpResponse::BAD,\n TRI_ERROR_HTTP_SUPERFLUOUS_SUFFICES,\n \"superfluous suffix, expecting \" + EDGE_PATH + \"?collection=\");\n return false;\n }\n\n \/\/ edge\n TRI_document_edge_t edge;\n\n \/\/ extract the from\n bool found;\n char const* from = _request->value(\"from\", found);\n\n if (! found || *from == '\\0') {\n generateError(HttpResponse::BAD,\n TRI_ERROR_HTTP_BAD_PARAMETER,\n \"'from' is missing, expecting \" + EDGE_PATH + \"?collection=&from=&to=\");\n return false;\n }\n\n \/\/ extract the to\n char const* to = _request->value(\"to\", found);\n\n if (! found || *to == '\\0') {\n generateError(HttpResponse::BAD,\n TRI_ERROR_HTTP_BAD_PARAMETER,\n \"'to' is missing, expecting \" + EDGE_PATH + \"?collection=&from=&to=\");\n return false;\n }\n\n \/\/ extract the cid\n const string& collection = _request->value(\"collection\", found);\n\n if (! found || collection.empty()) {\n generateError(HttpResponse::BAD,\n TRI_ERROR_ARANGO_COLLECTION_PARAMETER_MISSING,\n \"'collection' is missing, expecting \" + DOCUMENT_PATH + \"?collection=\");\n return false;\n }\n\n const bool waitForSync = extractWaitForSync();\n\n \/\/ auto-ptr that will free JSON data when scope is left\n ResourceHolder holder;\n\n TRI_json_t* json = parseJsonBody();\n if (! holder.registerJson(TRI_UNKNOWN_MEM_ZONE, json)) {\n return false;\n }\n \n if (json->_type != TRI_JSON_ARRAY) {\n generateTransactionError(collection, TRI_ERROR_ARANGO_DOCUMENT_TYPE_INVALID);\n return false;\n }\n\n if (! checkCreateCollection(collection, getCollectionType())) {\n return false;\n }\n\n \/\/ find and load collection given by name or identifier\n SingleCollectionWriteTransaction, 1> trx(_vocbase, _resolver, collection);\n\n \/\/ .............................................................................\n \/\/ inside write transaction\n \/\/ .............................................................................\n\n int res = trx.begin();\n if (res != TRI_ERROR_NO_ERROR) {\n generateTransactionError(collection, res);\n return false;\n }\n\n const TRI_voc_cid_t cid = trx.cid();\n\n edge._fromCid = cid;\n edge._toCid = cid;\n edge._fromKey = 0;\n edge._toKey = 0;\n\n res = parseDocumentId(from, edge._fromCid, edge._fromKey);\n holder.registerString(TRI_CORE_MEM_ZONE, edge._fromKey);\n\n if (res != TRI_ERROR_NO_ERROR) {\n if (res == TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND) {\n generateError(HttpResponse::NOT_FOUND, res, \"'from' does not point to a valid collection\");\n }\n else {\n generateError(HttpResponse::BAD, res, \"'from' is not a document handle\");\n }\n return false;\n }\n\n res = parseDocumentId(to, edge._toCid, edge._toKey);\n holder.registerString(TRI_CORE_MEM_ZONE, edge._toKey);\n\n if (res != TRI_ERROR_NO_ERROR) {\n if (res == TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND) {\n generateError(HttpResponse::NOT_FOUND, res, \"'to' does not point to a valid collection\");\n }\n else {\n generateError(HttpResponse::BAD, res, \"'to' is not a document handle\");\n }\n return false;\n }\n\n \/\/ .............................................................................\n \/\/ inside write transaction\n \/\/ .............................................................................\n\n \/\/ will hold the result\n TRI_doc_mptr_t document;\n res = trx.createEdge(&document, json, waitForSync, &edge);\n const bool wasSynchronous = trx.synchronous();\n res = trx.finish(res);\n\n \/\/ .............................................................................\n \/\/ outside write transaction\n \/\/ .............................................................................\n\n if (res != TRI_ERROR_NO_ERROR) {\n generateTransactionError(collection, res);\n return false;\n }\n\n assert(document._key != 0);\n\n \/\/ generate result\n if (wasSynchronous) {\n generateCreated(cid, document._key, document._rid);\n }\n else {\n generateAccepted(cid, document._key, document._rid);\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\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#ifndef otbScalarImageToHigherOrderTexturesFilter_hxx\n#define otbScalarImageToHigherOrderTexturesFilter_hxx\n\n#include \"otbScalarImageToHigherOrderTexturesFilter.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkProgressReporter.h\"\n\nnamespace otb\n{\ntemplate \nScalarImageToHigherOrderTexturesFilter\n::ScalarImageToHigherOrderTexturesFilter() :\n m_Radius(),\n m_NumberOfBinsPerAxis(8),\n m_InputImageMinimum(0),\n m_InputImageMaximum(255),\n m_FastCalculations(false),\n m_SubsampleFactor(),\n m_SubsampleOffset()\n{\n \/\/ There are 10 outputs corresponding to the 8 textures indices\n this->SetNumberOfRequiredOutputs(10);\n\n \/\/ Create the 11 outputs\n this->SetNthOutput(0, OutputImageType::New());\n this->SetNthOutput(1, OutputImageType::New());\n this->SetNthOutput(2, OutputImageType::New());\n this->SetNthOutput(3, OutputImageType::New());\n this->SetNthOutput(4, OutputImageType::New());\n this->SetNthOutput(5, OutputImageType::New());\n this->SetNthOutput(6, OutputImageType::New());\n this->SetNthOutput(7, OutputImageType::New());\n this->SetNthOutput(8, OutputImageType::New());\n this->SetNthOutput(9, OutputImageType::New());\n\n m_Radius.Fill(10);\n\n \/\/ Set the offset directions to their defaults: half of all the possible\n \/\/ directions 1 pixel away. (The other half is included by symmetry.)\n \/\/ We use a neighborhood iterator to calculate the appropriate offsets.\n typedef itk::Neighborhood NeighborhoodType;\n NeighborhoodType hood;\n hood.SetRadius( 1 );\n\n \/\/ select all \"previous\" neighbors that are face+edge+vertex\n \/\/ connected to the current pixel. do not include the center pixel.\n unsigned int centerIndex = hood.GetCenterNeighborhoodIndex();\n OffsetVectorPointer offsets = OffsetVector::New();\n for( unsigned int d = 0; d < centerIndex; d++ )\n {\n OffsetType offset = hood.GetOffset( d );\n offsets->push_back( offset );\n }\n this->SetOffsets( offsets );\n\n this->m_SubsampleFactor.Fill(1);\n this->m_SubsampleOffset.Fill(0);\n}\n\ntemplate \nScalarImageToHigherOrderTexturesFilter\n::~ScalarImageToHigherOrderTexturesFilter()\n{}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetShortRunEmphasisOutput()\n{\n if (this->GetNumberOfOutputs() < 1)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(0));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetLongRunEmphasisOutput()\n{\n if (this->GetNumberOfOutputs() < 2)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(1));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetGreyLevelNonuniformityOutput()\n{\n if (this->GetNumberOfOutputs() < 3)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(2));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetRunLengthNonuniformityOutput()\n{\n if (this->GetNumberOfOutputs() < 4)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(3));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetLowGreyLevelRunEmphasisOutput()\n{\n if (this->GetNumberOfOutputs() < 5)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(4));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetHighGreyLevelRunEmphasisOutput()\n{\n if (this->GetNumberOfOutputs() < 6)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(5));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetShortRunLowGreyLevelEmphasisOutput()\n{\n if (this->GetNumberOfOutputs() < 7)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(6));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetShortRunHighGreyLevelEmphasisOutput()\n{\n if (this->GetNumberOfOutputs() < 8)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(7));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetLongRunLowGreyLevelEmphasisOutput()\n{\n if (this->GetNumberOfOutputs() < 9)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(8));\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetLongRunHighGreyLevelEmphasisOutput()\n{\n if (this->GetNumberOfOutputs() < 10)\n {\n return nullptr;\n }\n return static_cast(this->GetOutput(9));\n}\n\ntemplate \nvoid\nScalarImageToHigherOrderTexturesFilter\n::SetOffset( const OffsetType offset )\n{\n OffsetVectorPointer offsetVector = OffsetVector::New();\n offsetVector->push_back( offset );\n this->SetOffsets( offsetVector );\n}\n\ntemplate \nvoid\nScalarImageToHigherOrderTexturesFilter\n::GenerateOutputInformation()\n{\n \/\/ First, call superclass implementation\n Superclass::GenerateOutputInformation();\n\n \/\/ Compute output size, origin & spacing\n InputRegionType inputRegion = this->GetInput()->GetLargestPossibleRegion();\n OutputRegionType outputRegion;\n outputRegion.SetIndex(0,0);\n outputRegion.SetIndex(1,0);\n outputRegion.SetSize(0, 1 + (inputRegion.GetSize(0) - 1 - m_SubsampleOffset[0]) \/ m_SubsampleFactor[0]);\n outputRegion.SetSize(1, 1 + (inputRegion.GetSize(1) - 1 - m_SubsampleOffset[1]) \/ m_SubsampleFactor[1]);\n\n typename OutputImageType::SpacingType outSpacing = this->GetInput()->GetSignedSpacing();\n outSpacing[0] *= m_SubsampleFactor[0];\n outSpacing[1] *= m_SubsampleFactor[1];\n\n typename OutputImageType::PointType outOrigin;\n this->GetInput()->TransformIndexToPhysicalPoint(inputRegion.GetIndex()+m_SubsampleOffset,outOrigin);\n\n for (unsigned int i=0 ; i < this->GetNumberOfOutputs() ; i++)\n {\n OutputImagePointerType outputPtr = this->GetOutput(i);\n outputPtr->SetLargestPossibleRegion(outputRegion);\n outputPtr->SetOrigin(outOrigin);\n outputPtr->SetSignedSpacing(outSpacing);\n }\n}\n\n\ntemplate \nvoid\nScalarImageToHigherOrderTexturesFilter\n::GenerateInputRequestedRegion()\n{\n \/\/ First, call superclass implementation\n Superclass::GenerateInputRequestedRegion();\n\n \/\/ Retrieve the input and output pointers\n InputImagePointerType inputPtr = const_cast(this->GetInput());\n OutputImagePointerType outputPtr = this->GetOutput();\n\n if (!inputPtr || !outputPtr)\n {\n return;\n }\n\n \/\/ Retrieve the output requested region\n \/\/ We use only the first output since requested regions for all outputs are enforced to be equal\n \/\/ by the default GenerateOutputRequestedRegiont() implementation\n OutputRegionType outputRequestedRegion = outputPtr->GetRequestedRegion();\n typename OutputRegionType::IndexType outputIndex = outputRequestedRegion.GetIndex();\n typename OutputRegionType::SizeType outputSize = outputRequestedRegion.GetSize();\n InputRegionType inputLargest = inputPtr->GetLargestPossibleRegion();\n\n \/\/ Convert index and size to full grid\n outputIndex[0] = outputIndex[0] * m_SubsampleFactor[0] + m_SubsampleOffset[0] + inputLargest.GetIndex(0);\n outputIndex[1] = outputIndex[1] * m_SubsampleFactor[1] + m_SubsampleOffset[1] + inputLargest.GetIndex(1);\n outputSize[0] = 1 + (outputSize[0] - 1) * m_SubsampleFactor[0];\n outputSize[1] = 1 + (outputSize[1] - 1) * m_SubsampleFactor[1];\n\n InputRegionType inputRequestedRegion(outputIndex,outputSize);\n\n \/\/ Apply the radius\n inputRequestedRegion.PadByRadius(m_Radius);\n\n \/\/ Try to apply the requested region to the input image\n if (inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()))\n {\n inputPtr->SetRequestedRegion(inputRequestedRegion);\n }\n else\n {\n \/\/ Build an exception\n itk::InvalidRequestedRegionError e(__FILE__, __LINE__);\n e.SetLocation(ITK_LOCATION);\n e.SetDescription(\"Requested region is (at least partially) outside the largest possible region.\");\n e.SetDataObject(inputPtr);\n throw e;\n }\n}\n\ntemplate \nvoid\nScalarImageToHigherOrderTexturesFilter\n::ThreadedGenerateData(const OutputRegionType& outputRegionForThread, itk::ThreadIdType threadId)\n{\n \/\/ Retrieve the input and output pointers\n InputImagePointerType inputPtr = const_cast(this->GetInput());\n\n typedef typename itk::ImageRegionIterator IteratorType;\n std::vector outputImagesIterators;\n\n for (unsigned int i = 0; i < this->GetNumberOfOutputs(); ++i)\n {\n outputImagesIterators.push_back( IteratorType(this->GetOutput(i), outputRegionForThread) );\n outputImagesIterators[i].GoToBegin();\n }\n\n \/\/ Compute the max possible run length (in physical unit)\n typename InputImageType::PointType topLeftPoint;\n typename InputImageType::PointType bottomRightPoint;\n inputPtr->TransformIndexToPhysicalPoint( outputImagesIterators[0].GetIndex() - m_Radius, topLeftPoint );\n inputPtr->TransformIndexToPhysicalPoint( outputImagesIterators[0].GetIndex() + m_Radius, bottomRightPoint );\n double maxDistance = topLeftPoint.EuclideanDistanceTo(bottomRightPoint);\n\n InputRegionType inputLargest = inputPtr->GetLargestPossibleRegion();\n\n \/\/ Set-up progress reporting\n itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());\n\n \/\/ Iterate on outputs to compute textures\n while ( !outputImagesIterators[0].IsAtEnd() )\n {\n \/\/ Compute the region on which run-length matrix will be estimated\n typename InputRegionType::IndexType inputIndex;\n typename InputRegionType::SizeType inputSize;\n\n \/\/ Convert index to full grid\n typename OutputImageType::IndexType outIndex;\n\n for (unsigned int dim = 0; dim < InputImageType::ImageDimension; ++dim)\n {\n outIndex[dim] = outputImagesIterators[0].GetIndex()[dim] * m_SubsampleFactor[dim]\n + m_SubsampleOffset[dim] + inputLargest.GetIndex(dim);\n inputIndex[dim] = outIndex[dim] - m_Radius[dim];\n inputSize[dim] = 2 * m_Radius[dim] + 1;\n }\n\n \/\/ Build the input region\n InputRegionType inputRegion;\n inputRegion.SetIndex(inputIndex);\n inputRegion.SetSize(inputSize);\n\n inputRegion.Crop(inputPtr->GetBufferedRegion());\n\n \/\/ Create a local image corresponding to the input region\n InputImagePointerType localInputImage = InputImageType::New();\n localInputImage->SetRegions(inputRegion);\n localInputImage->Allocate();\n typedef itk::ImageRegionIteratorWithIndex ImageRegionIteratorType;\n ImageRegionIteratorType itInputPtr(inputPtr, inputRegion);\n ImageRegionIteratorType itLocalInputImage(localInputImage, inputRegion);\n for (itInputPtr.GoToBegin(), itLocalInputImage.GoToBegin();\n !itInputPtr.IsAtEnd();\n ++itInputPtr, ++itLocalInputImage)\n {\n itLocalInputImage.Set(itInputPtr.Get());\n }\n\n typename ScalarImageToRunLengthFeaturesFilterType::Pointer runLengthFeatureCalculator = ScalarImageToRunLengthFeaturesFilterType::New();\n runLengthFeatureCalculator->SetInput(localInputImage);\n runLengthFeatureCalculator->SetOffsets(m_Offsets);\n runLengthFeatureCalculator->SetNumberOfBinsPerAxis(m_NumberOfBinsPerAxis);\n runLengthFeatureCalculator->SetPixelValueMinMax(m_InputImageMinimum, m_InputImageMaximum);\n runLengthFeatureCalculator->SetDistanceValueMinMax(0, maxDistance);\n\n runLengthFeatureCalculator->Update();\n\n typename ScalarImageToRunLengthFeaturesFilterType::FeatureValueVector&\n featuresMeans = *(runLengthFeatureCalculator->GetFeatureMeans().GetPointer());\n\n \/\/ Fill output\n for (unsigned int i = 0; i < this->GetNumberOfOutputs(); ++i)\n {\n \/\/ Fill output\n outputImagesIterators[i].Set(featuresMeans[i]);\n \/\/ Increment iterators\n ++outputImagesIterators[i];\n }\n \/\/ Update progress\n progress.CompletedPixel();\n }\n}\n\n} \/\/ End namespace otb\n\n#endif\nREFAC: rm cast and change some types\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\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#ifndef otbScalarImageToHigherOrderTexturesFilter_hxx\n#define otbScalarImageToHigherOrderTexturesFilter_hxx\n\n#include \"otbScalarImageToHigherOrderTexturesFilter.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkProgressReporter.h\"\n\nnamespace otb\n{\ntemplate \nScalarImageToHigherOrderTexturesFilter\n::ScalarImageToHigherOrderTexturesFilter() :\n m_Radius(),\n m_NumberOfBinsPerAxis(8),\n m_InputImageMinimum(0),\n m_InputImageMaximum(255),\n m_FastCalculations(false),\n m_SubsampleFactor(),\n m_SubsampleOffset()\n{\n \/\/ There are 10 outputs corresponding to the 8 textures indices\n this->SetNumberOfRequiredOutputs(10);\n\n \/\/ Create the 11 outputs\n this->SetNthOutput(0, OutputImageType::New());\n this->SetNthOutput(1, OutputImageType::New());\n this->SetNthOutput(2, OutputImageType::New());\n this->SetNthOutput(3, OutputImageType::New());\n this->SetNthOutput(4, OutputImageType::New());\n this->SetNthOutput(5, OutputImageType::New());\n this->SetNthOutput(6, OutputImageType::New());\n this->SetNthOutput(7, OutputImageType::New());\n this->SetNthOutput(8, OutputImageType::New());\n this->SetNthOutput(9, OutputImageType::New());\n\n m_Radius.Fill(10);\n\n \/\/ Set the offset directions to their defaults: half of all the possible\n \/\/ directions 1 pixel away. (The other half is included by symmetry.)\n \/\/ We use a neighborhood iterator to calculate the appropriate offsets.\n typedef itk::Neighborhood NeighborhoodType;\n NeighborhoodType hood;\n hood.SetRadius( 1 );\n\n \/\/ select all \"previous\" neighbors that are face+edge+vertex\n \/\/ connected to the current pixel. do not include the center pixel.\n unsigned int centerIndex = hood.GetCenterNeighborhoodIndex();\n OffsetVectorPointer offsets = OffsetVector::New();\n for( unsigned int d = 0; d < centerIndex; d++ )\n {\n OffsetType offset = hood.GetOffset( d );\n offsets->push_back( offset );\n }\n this->SetOffsets( offsets );\n\n this->m_SubsampleFactor.Fill(1);\n this->m_SubsampleOffset.Fill(0);\n}\n\ntemplate \nScalarImageToHigherOrderTexturesFilter\n::~ScalarImageToHigherOrderTexturesFilter()\n{}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetShortRunEmphasisOutput()\n{\n this->GetOutput(0);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetLongRunEmphasisOutput()\n{\n this->GetOutput(1);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetGreyLevelNonuniformityOutput()\n{\n this->GetOutput(2);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetRunLengthNonuniformityOutput()\n{\n this->GetOutput(3);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetLowGreyLevelRunEmphasisOutput()\n{\n this->GetOutput(4);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetHighGreyLevelRunEmphasisOutput()\n{\n this->GetOutput(5);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetShortRunLowGreyLevelEmphasisOutput()\n{\n this->GetOutput(6);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetShortRunHighGreyLevelEmphasisOutput()\n{\n this->GetOutput(7);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetLongRunLowGreyLevelEmphasisOutput()\n{\n this->GetOutput(8);\n}\n\ntemplate \ntypename ScalarImageToHigherOrderTexturesFilter\n::OutputImageType *\nScalarImageToHigherOrderTexturesFilter\n::GetLongRunHighGreyLevelEmphasisOutput()\n{\n this->GetOutput(9);\n}\n\ntemplate \nvoid\nScalarImageToHigherOrderTexturesFilter\n::SetOffset( const OffsetType offset )\n{\n OffsetVectorPointer offsetVector = OffsetVector::New();\n offsetVector->push_back( offset );\n this->SetOffsets( offsetVector );\n}\n\ntemplate \nvoid\nScalarImageToHigherOrderTexturesFilter\n::GenerateOutputInformation()\n{\n \/\/ Compute output size, origin & spacing\n const InputImageType * inputPtr = this->GetInput();\n InputRegionType inputRegion = inputPtr->GetLargestPossibleRegion();\n OutputRegionType outputRegion;\n outputRegion.SetIndex(0,0);\n outputRegion.SetIndex(1,0);\n outputRegion.SetSize(0, 1 + (inputRegion.GetSize(0) - 1 - m_SubsampleOffset[0]) \/ m_SubsampleFactor[0]);\n outputRegion.SetSize(1, 1 + (inputRegion.GetSize(1) - 1 - m_SubsampleOffset[1]) \/ m_SubsampleFactor[1]);\n\n typename OutputImageType::SpacingType outSpacing = inputPtr->GetSignedSpacing();\n outSpacing[0] *= m_SubsampleFactor[0];\n outSpacing[1] *= m_SubsampleFactor[1];\n\n typename OutputImageType::PointType outOrigin;\n inputPtr->TransformIndexToPhysicalPoint(inputRegion.GetIndex()+m_SubsampleOffset,outOrigin);\n\n for (unsigned int i=0 ; i < this->GetNumberOfOutputs() ; i++)\n {\n OutputImagePointerType outputPtr = this->GetOutput(i);\n outputPtr->CopyInformation(inputPtr);\n outputPtr->SetLargestPossibleRegion(outputRegion);\n outputPtr->SetOrigin(outOrigin);\n outputPtr->SetSignedSpacing(outSpacing);\n }\n}\n\n\ntemplate \nvoid\nScalarImageToHigherOrderTexturesFilter\n::GenerateInputRequestedRegion()\n{\n \/\/ First, call superclass implementation\n Superclass::GenerateInputRequestedRegion();\n\n \/\/ Retrieve the input and output pointers\n InputImagePointerType inputPtr = const_cast(this->GetInput());\n OutputImagePointerType outputPtr = this->GetOutput();\n\n if (!inputPtr || !outputPtr)\n {\n return;\n }\n\n \/\/ Retrieve the output requested region\n \/\/ We use only the first output since requested regions for all outputs are enforced to be equal\n \/\/ by the default GenerateOutputRequestedRegiont() implementation\n OutputRegionType outputRequestedRegion = outputPtr->GetRequestedRegion();\n typename OutputRegionType::IndexType outputIndex = outputRequestedRegion.GetIndex();\n typename OutputRegionType::SizeType outputSize = outputRequestedRegion.GetSize();\n InputRegionType inputLargest = inputPtr->GetLargestPossibleRegion();\n\n \/\/ Convert index and size to full grid\n outputIndex[0] = outputIndex[0] * m_SubsampleFactor[0] + m_SubsampleOffset[0] + inputLargest.GetIndex(0);\n outputIndex[1] = outputIndex[1] * m_SubsampleFactor[1] + m_SubsampleOffset[1] + inputLargest.GetIndex(1);\n outputSize[0] = 1 + (outputSize[0] - 1) * m_SubsampleFactor[0];\n outputSize[1] = 1 + (outputSize[1] - 1) * m_SubsampleFactor[1];\n\n InputRegionType inputRequestedRegion(outputIndex,outputSize);\n\n \/\/ Apply the radius\n inputRequestedRegion.PadByRadius(m_Radius);\n\n \/\/ Try to apply the requested region to the input image\n if (inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()))\n {\n inputPtr->SetRequestedRegion(inputRequestedRegion);\n }\n else\n {\n \/\/ Build an exception\n itk::InvalidRequestedRegionError e(__FILE__, __LINE__);\n e.SetLocation(ITK_LOCATION);\n e.SetDescription(\"Requested region is (at least partially) outside the largest possible region.\");\n e.SetDataObject(inputPtr);\n throw e;\n }\n}\n\ntemplate \nvoid\nScalarImageToHigherOrderTexturesFilter\n::ThreadedGenerateData(const OutputRegionType& outputRegionForThread, itk::ThreadIdType threadId)\n{\n \/\/ Retrieve the input and output pointers\n const InputImageType * inputPtr = this->GetInput();\n\n typedef typename itk::ImageRegionIterator IteratorType;\n std::vector outputImagesIterators;\n\n for (unsigned int i = 0; i < this->GetNumberOfOutputs(); ++i)\n {\n outputImagesIterators.push_back( IteratorType(this->GetOutput(i), outputRegionForThread) );\n outputImagesIterators[i].GoToBegin();\n }\n\n \/\/ Compute the max possible run length (in physical unit)\n typename InputImageType::PointType topLeftPoint;\n typename InputImageType::PointType bottomRightPoint;\n inputPtr->TransformIndexToPhysicalPoint( outputImagesIterators[0].GetIndex() - m_Radius, topLeftPoint );\n inputPtr->TransformIndexToPhysicalPoint( outputImagesIterators[0].GetIndex() + m_Radius, bottomRightPoint );\n double maxDistance = topLeftPoint.EuclideanDistanceTo(bottomRightPoint);\n\n InputRegionType inputLargest = inputPtr->GetLargestPossibleRegion();\n\n \/\/ Set-up progress reporting\n itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());\n\n \/\/ Iterate on outputs to compute textures\n while ( !outputImagesIterators[0].IsAtEnd() )\n {\n \/\/ Compute the region on which run-length matrix will be estimated\n typename InputRegionType::IndexType inputIndex;\n typename InputRegionType::SizeType inputSize;\n\n \/\/ Convert index to full grid\n typename OutputImageType::IndexType outIndex;\n\n for (unsigned int dim = 0; dim < InputImageType::ImageDimension; ++dim)\n {\n outIndex[dim] = outputImagesIterators[0].GetIndex()[dim] * m_SubsampleFactor[dim]\n + m_SubsampleOffset[dim] + inputLargest.GetIndex(dim);\n inputIndex[dim] = outIndex[dim] - m_Radius[dim];\n inputSize[dim] = 2 * m_Radius[dim] + 1;\n }\n\n \/\/ Build the input region\n InputRegionType inputRegion;\n inputRegion.SetIndex(inputIndex);\n inputRegion.SetSize(inputSize);\n\n inputRegion.Crop(inputPtr->GetBufferedRegion());\n\n \/\/ Create a local image corresponding to the input region\n InputImagePointerType localInputImage = InputImageType::New();\n localInputImage->SetRegions(inputRegion);\n localInputImage->Allocate();\n typedef itk::ImageRegionIteratorWithIndex ImageRegionIteratorType;\n typedef itk::ImageRegionConstIteratorWithIndex ImageRegionConstIteratorType;\n ImageRegionConstIteratorType itInputPtr(inputPtr, inputRegion);\n ImageRegionIteratorType itLocalInputImage(localInputImage, inputRegion);\n for (itInputPtr.GoToBegin(), itLocalInputImage.GoToBegin();\n !itInputPtr.IsAtEnd();\n ++itInputPtr, ++itLocalInputImage)\n {\n itLocalInputImage.Set(itInputPtr.Get());\n }\n\n typename ScalarImageToRunLengthFeaturesFilterType::Pointer runLengthFeatureCalculator = ScalarImageToRunLengthFeaturesFilterType::New();\n runLengthFeatureCalculator->SetInput(localInputImage);\n runLengthFeatureCalculator->SetOffsets(m_Offsets);\n runLengthFeatureCalculator->SetNumberOfBinsPerAxis(m_NumberOfBinsPerAxis);\n runLengthFeatureCalculator->SetPixelValueMinMax(m_InputImageMinimum, m_InputImageMaximum);\n runLengthFeatureCalculator->SetDistanceValueMinMax(0, maxDistance);\n\n runLengthFeatureCalculator->Update();\n\n typename ScalarImageToRunLengthFeaturesFilterType::FeatureValueVector&\n featuresMeans = *(runLengthFeatureCalculator->GetFeatureMeans().GetPointer());\n\n \/\/ Fill output\n for (unsigned int i = 0; i < this->GetNumberOfOutputs(); ++i)\n {\n \/\/ Fill output\n outputImagesIterators[i].Set(featuresMeans[i]);\n \/\/ Increment iterators\n ++outputImagesIterators[i];\n }\n \/\/ Update progress\n progress.CompletedPixel();\n }\n}\n\n} \/\/ End namespace otb\n\n#endif\n<|endoftext|>"} {"text":"#if defined(__CLING__)\n#include \"AliMultDepSpecAnalysisTask.h\"\n#endif\n\nAliMultDepSpecAnalysisTask* AddTask_mkrueger_MultDepSpec(TString controlstring, Int_t cutModeLow = 100, Int_t cutModeHigh = 121)\n{\n\n \/\/ settings:\n Bool_t includeCrosscheckHistos = kFALSE;\n Bool_t is2013pA = kFALSE;\n UInt_t offlineTriggerMask = AliVEvent::kINT7;\n Bool_t is2015Data = kFALSE;\n Bool_t isPbPbAnalysis = kFALSE;\n\n Int_t maxMultiplicity = 100;\n Float_t etaCut = 0.8;\n if(controlstring.Contains(\"eta03\")) etaCut = 0.3;\n\n Float_t lowerPtCut = 0.15;\n Float_t upperPtCut = 10.;\n\n string colsys = \"pp\";\n\n const Int_t nMultSteps = 3;\n Int_t multSteps[] = {100, 0, 0};\n Int_t multBinWidth[] = {1,1,1};\n\n Int_t nBinsCent = 1;\n Double_t centBinEdgesDummy[2] = {0., 100.};\n Double_t centBinEdgesUsed[9] = {0., 5., 10., 20., 40., 60., 80., 90., 100.};\n Double_t* centBinEdges = centBinEdgesDummy;\n\n if(controlstring.Contains(\"pp\")){\n if(controlstring.Contains(\"performanceHistos\")) includeCrosscheckHistos = kTRUE;\n if(controlstring.Contains(\"5TeV\")) is2015Data = kTRUE;\n if(controlstring.Contains(\"7TeV\")) offlineTriggerMask = AliVEvent::kMB;\n if(controlstring.Contains(\"2TeV\")) offlineTriggerMask = AliVEvent::kMB;\n if(controlstring.Contains(\"09TeV\")) offlineTriggerMask = AliVEvent::kMB;\n }\n if(controlstring.Contains(\"XeXe\")) {\n colsys = \"XeXe\";\n multSteps[0] = 3500; multBinWidth[0] = 1;\n multSteps[1] = 0; multBinWidth[1] = 1;\n multSteps[2] = 0; multBinWidth[2] = 1;\n nBinsCent = 8;\n centBinEdges = centBinEdgesUsed;\n }\n if(controlstring.Contains(\"pPb\")) {\n colsys = \"pPb\";\n multSteps[0] = 200; multBinWidth[0] = 1;\n multSteps[1] = 0; multBinWidth[1] = 1;\n multSteps[2] = 0; multBinWidth[2] = 1;\n is2013pA = kTRUE;\n }\n if(controlstring.Contains(\"PbPb\")) {\n isPbPbAnalysis = kTRUE;\n is2015Data = kTRUE;\n colsys = \"PbPb\";\n multSteps[0] = 4500; multBinWidth[0] = 1;\n multSteps[1] = 0; multBinWidth[1] = 1;\n multSteps[2] = 0; multBinWidth[2] = 1;\n nBinsCent = 8;\n centBinEdges = centBinEdgesUsed;\n if(controlstring.Contains(\"2TeV\")){offlineTriggerMask = AliVEvent::kMB; is2015Data = kFALSE;}\n }\n if(controlstring.Contains(\"oldTrigger\")){offlineTriggerMask = AliVEvent::kMB;}\n\n \/\/ Binning in Multiplicity\n const Int_t nBinsMult = multSteps[0]+ multSteps[1] + multSteps[2] + 1;\n Double_t multBinEdges[nBinsMult+1];\n multBinEdges[0] = -0.5;\n multBinEdges[1] = 0.5;\n Int_t startBin = 1;\n Int_t endBin = 1;\n for(Int_t multStep = 0; multStep < nMultSteps; multStep++){\n endBin += multSteps[multStep];\n for(Int_t multBin = startBin; multBin < endBin; multBin++) {\n multBinEdges[multBin+1] = multBinEdges[multBin] + multBinWidth[multStep];\n }\n startBin = endBin;\n }\n\n\n AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();\n\n if (!mgr) {\n Error(\"AddTask_mkrueger_MultDepSpec\", \"No analysis manager found.\");\n return 0;\n }\n\n \/\/ Switch off all AliInfo (too much output!!!)\n AliLog::SetGlobalLogLevel(AliLog::kError);\n mgr->SetDebugLevel(0);\n\n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n Bool_t hasMC = (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler() != 0x0);\n\n if(controlstring.Contains(\"PbPb\") && hasMC) offlineTriggerMask = AliVEvent::kMB;\n if(controlstring.Contains(\"highMult\")){offlineTriggerMask = AliVEvent::kHighMult;}\n\n AliMultDepSpecAnalysisTask* mainTask = NULL;\n\n char taskName[100] = \"\";\n\n if(controlstring.Contains(\"logBinsPt\")){\n\n Double_t minPt = 0.1;\n Double_t maxPt = 100.;\n Int_t nbinsPt = 30;\n\n Double_t logminPt = TMath::Log10(minPt);\n Double_t logmaxPt = TMath::Log10(maxPt);\n Double_t binwidth = (logmaxPt-logminPt)\/nbinsPt;\n Double_t* binsPt = new Double_t[nbinsPt+1];\n binsPt[0] = minPt;\n for (Int_t i = 1; i <= nbinsPt; i++) {\n binsPt[i] = minPt + TMath::Power(10, logminPt + i*binwidth);\n }\n }\n if(controlstring.Contains(\"noCent\")) {\n nBinsCent = 1;\n centBinEdges = centBinEdgesDummy;\n }\n\n for(Int_t cutMode = cutModeLow; cutMode <= cutModeHigh; cutMode++){\n sprintf(taskName, \"mkrueger_%s_eta_%.2f_cutMode_%d\", colsys.c_str(), etaCut, cutMode);\n\n AliMultDepSpecAnalysisTask* task = new AliMultDepSpecAnalysisTask(taskName);\n\n if(controlstring.Contains(\"fullPt\")){\n upperPtCut = 50;\n lowerPtCut = 0.15;\n\/\/ Double_t pTBinEdgesLarge[69] = {0.,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.5,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,18.0,20.0,22.0,24.0,26.0,28.0,30.0,32.0,34.0,36.0,40.0,45.0,50.0};\n\/\/ Double_t pTBinEdgesLarge[54] = {0.,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.5,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.0,20.0,30.0,40.0,50.0};\n Double_t pTBinEdgesLarge[53] = {0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.5,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.0,20.0,30.0,40.0,50.0,60.0};\n task->SetBinsPt(52, pTBinEdgesLarge);\n }\n\n task->SetIncludeCrosscheckHistos(includeCrosscheckHistos);\n task->Set2013pA(is2013pA);\n\n \/\/ general cuts\n task->SelectCollisionCandidates(offlineTriggerMask);\n task->SetTriggerMask(offlineTriggerMask);\n\n task->SetUseMC(hasMC);\n if(type.Contains(\"ESD\")) task->SetUseESD();\n else task->SetUseAOD();\n task->SetBinsMult(nBinsMult, multBinEdges);\n task->SetBinsCent(nBinsCent, centBinEdges);\n\n \/\/ nominal cut-setting:\n task->SetMinEta(-etaCut);\n task->SetMaxEta(etaCut);\n task->SetMinPt(lowerPtCut);\n task->SetMaxPt(upperPtCut);\n\n task->Set2013pA(kFALSE);\n task->Set2015data(is2015Data);\n\n task->SetMeanXYZv(0.0,0.0,0.0);\n task->SetSigmaMeanXYZv(1.0,1.0,10.0);\n task->SetZvtx(10.);\n\n \/\/ Quality cuts for tracks\n task->SetTPCRefit(kTRUE);\n task->SetITSRefit(kTRUE);\n task->SetKinkDaughters(kFALSE);\n task->SetRatioCrossedRowsOverFindableClustersTPC(0.8);\n task->SetFractionSharedClustersTPC(0.4);\n task->SetMaxchi2perTPCclu(4.);\n task->SetClusterReqITS(kTRUE);\n task->SetMaxchi2perITSclu(36.);\n task->SetDCAtoVertex2D(kFALSE);\n task->SetSigmaToVertex(kFALSE);\n task->SetDCAtoVertexZ(2.0);\n task->SetDCAtoVertexXYPtDep(\"0.0182+0.0350\/pt^1.01\");\n task->SetMaxChi2TPCConstrained(36.); \/\/ was excluded for some reason?\n task->SetMinLenghtInActiveZoneTPC(0);\n task->SetGeometricalCut(kTRUE,3,130,1.5,0.85,0.7); \/\/\/if kTRUE comment CrossedRowsTPC cut\n \/\/ task->SetMinCrossedRowsTPC(120);\n\n\/\/MC1--\n if(cutMode == 100) mainTask = task; \/\/ has no particular use... just to return task with nominal cut setting in macro\n\n \/\/ cut-variation:\n if(cutMode == 101) {task->SetMaxchi2perITSclu(25.);}\n if(cutMode == 102) {task->SetMaxchi2perITSclu(49.);}\n\n if(cutMode == 103) {task->SetMaxchi2perTPCclu(3); }\n if(cutMode == 104) {task->SetMaxchi2perTPCclu(5); }\n\/\/MC2--\n if(cutMode == 105) {task->SetRatioCrossedRowsOverFindableClustersTPC(0.7);}\n if(cutMode == 106) {task->SetRatioCrossedRowsOverFindableClustersTPC(0.9);}\n\n if(cutMode == 107) {task->SetFractionSharedClustersTPC(0.2);}\n if(cutMode == 108) {task->SetFractionSharedClustersTPC(1.0);}\n\/\/MC3--\n if(cutMode == 109) {task->SetMaxChi2TPCConstrained(25.);}\n if(cutMode == 110) {task->SetMaxChi2TPCConstrained(49.);}\n\n if(cutMode == 111) {task->SetDCAtoVertexXYPtDep(\"0.0104+0.0200\/pt^1.01\");}\n if(cutMode == 112) {task->SetDCAtoVertexXYPtDep(\"0.0260+0.0500\/pt^1.01\");}\n\/\/MC4--\n if(cutMode == 113) {task->SetDCAtoVertexZ(1.0);}\n if(cutMode == 114) {task->SetDCAtoVertexZ(5.0);}\n\n if(cutMode == 115) {task->SetClusterReqITS(kFALSE);}\n\/\/MC5--\n if(cutMode == 116) {task->SetGeometricalCut(kTRUE,3,120,1.5,0.85,0.7);}\n if(cutMode == 117) {task->SetGeometricalCut(kTRUE,3,140,1.5,0.85,0.7);}\n\n if(cutMode == 118) {task->SetGeometricalCut(kTRUE,4,130,1.5,0.85,0.7);}\n if(cutMode == 119) {task->SetGeometricalCut(kTRUE,2,130,1.5,0.85,0.7);}\n\n \/\/ event cut varaitions\n if(cutMode == 120) task->SetZvtx(5.);\n if(cutMode == 121) task->SetZvtx(20.);\n\n\n \/\/ hang task in train\n\n mgr->AddTask(task);\n\n AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();\n AliAnalysisDataContainer* coutput = mgr->CreateContainer(taskName,\n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t \"AnalysisResults.root\");\n\n\n\n mgr->ConnectInput(task, 0, cinput);\n mgr->ConnectOutput(task, 1, coutput);\n\n\n }\n\n\n return mainTask;\n\n}\nPWGLF::AliMultDepSpec:: added option to change mult binning#if defined(__CLING__)\n#include \"AliMultDepSpecAnalysisTask.h\"\n#endif\n\nAliMultDepSpecAnalysisTask* AddTask_mkrueger_MultDepSpec(TString controlstring, Int_t cutModeLow = 100, Int_t cutModeHigh = 121)\n{\n\n \/\/ settings:\n Bool_t includeCrosscheckHistos = kFALSE;\n Bool_t is2013pA = kFALSE;\n UInt_t offlineTriggerMask = AliVEvent::kINT7;\n Bool_t is2015Data = kFALSE;\n Bool_t isPbPbAnalysis = kFALSE;\n\n Int_t maxMultiplicity = 100;\n Float_t etaCut = 0.8;\n if(controlstring.Contains(\"eta03\")) etaCut = 0.3;\n\n Float_t lowerPtCut = 0.15;\n Float_t upperPtCut = 10.;\n\n string colsys = \"pp\";\n\n const Int_t nMultSteps = 3;\n Int_t multSteps[] = {100, 0, 0};\n Int_t multBinWidth[] = {1,1,1};\n\n Int_t nBinsCent = 1;\n Double_t centBinEdgesDummy[2] = {0., 100.};\n Double_t centBinEdgesUsed[9] = {0., 5., 10., 20., 40., 60., 80., 90., 100.};\n Double_t* centBinEdges = centBinEdgesDummy;\n\n if(controlstring.Contains(\"pp\")){\n if(controlstring.Contains(\"performanceHistos\")) includeCrosscheckHistos = kTRUE;\n if(controlstring.Contains(\"5TeV\")) is2015Data = kTRUE;\n if(controlstring.Contains(\"7TeV\")) offlineTriggerMask = AliVEvent::kMB;\n if(controlstring.Contains(\"2TeV\")) offlineTriggerMask = AliVEvent::kMB;\n if(controlstring.Contains(\"09TeV\")) offlineTriggerMask = AliVEvent::kMB;\n }\n if(controlstring.Contains(\"XeXe\")) {\n colsys = \"XeXe\";\n multSteps[0] = 3500; multBinWidth[0] = 1;\n multSteps[1] = 0; multBinWidth[1] = 1;\n multSteps[2] = 0; multBinWidth[2] = 1;\n nBinsCent = 8;\n centBinEdges = centBinEdgesUsed;\n }\n if(controlstring.Contains(\"pPb\")) {\n colsys = \"pPb\";\n multSteps[0] = 200; multBinWidth[0] = 1;\n multSteps[1] = 0; multBinWidth[1] = 1;\n multSteps[2] = 0; multBinWidth[2] = 1;\n is2013pA = kTRUE;\n }\n if(controlstring.Contains(\"PbPb\")) {\n isPbPbAnalysis = kTRUE;\n is2015Data = kTRUE;\n colsys = \"PbPb\";\n multSteps[0] = 4500; multBinWidth[0] = 1;\n multSteps[1] = 0; multBinWidth[1] = 1;\n multSteps[2] = 0; multBinWidth[2] = 1;\n nBinsCent = 8;\n centBinEdges = centBinEdgesUsed;\n if(controlstring.Contains(\"2TeV\")){offlineTriggerMask = AliVEvent::kMB; is2015Data = kFALSE;}\n }\n if(controlstring.Contains(\"oldTrigger\")){offlineTriggerMask = AliVEvent::kMB;}\n\n if(controlstring.Contains(\"largeBins\")) {\n multSteps[0] = 450; multBinWidth[0] = 10;\n multSteps[1] = 0; multBinWidth[1] = 1;\n multSteps[2] = 0; multBinWidth[2] = 1;\n }\n\n \/\/ Binning in Multiplicity\n const Int_t nBinsMult = multSteps[0]+ multSteps[1] + multSteps[2] + 1;\n Double_t multBinEdges[nBinsMult+1];\n multBinEdges[0] = -0.5;\n multBinEdges[1] = 0.5;\n Int_t startBin = 1;\n Int_t endBin = 1;\n for(Int_t multStep = 0; multStep < nMultSteps; multStep++){\n endBin += multSteps[multStep];\n for(Int_t multBin = startBin; multBin < endBin; multBin++) {\n multBinEdges[multBin+1] = multBinEdges[multBin] + multBinWidth[multStep];\n }\n startBin = endBin;\n }\n\n\n AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();\n\n if (!mgr) {\n Error(\"AddTask_mkrueger_MultDepSpec\", \"No analysis manager found.\");\n return 0;\n }\n\n \/\/ Switch off all AliInfo (too much output!!!)\n AliLog::SetGlobalLogLevel(AliLog::kError);\n mgr->SetDebugLevel(0);\n\n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n Bool_t hasMC = (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler() != 0x0);\n\n if(controlstring.Contains(\"PbPb\") && hasMC) offlineTriggerMask = AliVEvent::kMB;\n if(controlstring.Contains(\"highMult\")){offlineTriggerMask = AliVEvent::kHighMult;}\n\n AliMultDepSpecAnalysisTask* mainTask = NULL;\n\n char taskName[100] = \"\";\n\n if(controlstring.Contains(\"logBinsPt\")){\n\n Double_t minPt = 0.1;\n Double_t maxPt = 100.;\n Int_t nbinsPt = 30;\n\n Double_t logminPt = TMath::Log10(minPt);\n Double_t logmaxPt = TMath::Log10(maxPt);\n Double_t binwidth = (logmaxPt-logminPt)\/nbinsPt;\n Double_t* binsPt = new Double_t[nbinsPt+1];\n binsPt[0] = minPt;\n for (Int_t i = 1; i <= nbinsPt; i++) {\n binsPt[i] = minPt + TMath::Power(10, logminPt + i*binwidth);\n }\n }\n if(controlstring.Contains(\"noCent\")) {\n nBinsCent = 1;\n centBinEdges = centBinEdgesDummy;\n }\n\n for(Int_t cutMode = cutModeLow; cutMode <= cutModeHigh; cutMode++){\n sprintf(taskName, \"mkrueger_%s_eta_%.2f_cutMode_%d\", colsys.c_str(), etaCut, cutMode);\n\n AliMultDepSpecAnalysisTask* task = new AliMultDepSpecAnalysisTask(taskName);\n\n if(controlstring.Contains(\"fullPt\")){\n upperPtCut = 50;\n lowerPtCut = 0.15;\n\/\/ Double_t pTBinEdgesLarge[69] = {0.,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.5,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,18.0,20.0,22.0,24.0,26.0,28.0,30.0,32.0,34.0,36.0,40.0,45.0,50.0};\n\/\/ Double_t pTBinEdgesLarge[54] = {0.,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.5,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.0,20.0,30.0,40.0,50.0};\n Double_t pTBinEdgesLarge[53] = {0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.5,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.0,20.0,30.0,40.0,50.0,60.0};\n task->SetBinsPt(52, pTBinEdgesLarge);\n }\n\n task->SetIncludeCrosscheckHistos(includeCrosscheckHistos);\n task->Set2013pA(is2013pA);\n\n \/\/ general cuts\n task->SelectCollisionCandidates(offlineTriggerMask);\n task->SetTriggerMask(offlineTriggerMask);\n\n task->SetUseMC(hasMC);\n if(type.Contains(\"ESD\")) task->SetUseESD();\n else task->SetUseAOD();\n task->SetBinsMult(nBinsMult, multBinEdges);\n task->SetBinsCent(nBinsCent, centBinEdges);\n\n \/\/ nominal cut-setting:\n task->SetMinEta(-etaCut);\n task->SetMaxEta(etaCut);\n task->SetMinPt(lowerPtCut);\n task->SetMaxPt(upperPtCut);\n\n task->Set2013pA(kFALSE);\n task->Set2015data(is2015Data);\n\n task->SetMeanXYZv(0.0,0.0,0.0);\n task->SetSigmaMeanXYZv(1.0,1.0,10.0);\n task->SetZvtx(10.);\n\n \/\/ Quality cuts for tracks\n task->SetTPCRefit(kTRUE);\n task->SetITSRefit(kTRUE);\n task->SetKinkDaughters(kFALSE);\n task->SetRatioCrossedRowsOverFindableClustersTPC(0.8);\n task->SetFractionSharedClustersTPC(0.4);\n task->SetMaxchi2perTPCclu(4.);\n task->SetClusterReqITS(kTRUE);\n task->SetMaxchi2perITSclu(36.);\n task->SetDCAtoVertex2D(kFALSE);\n task->SetSigmaToVertex(kFALSE);\n task->SetDCAtoVertexZ(2.0);\n task->SetDCAtoVertexXYPtDep(\"0.0182+0.0350\/pt^1.01\");\n task->SetMaxChi2TPCConstrained(36.); \/\/ was excluded for some reason?\n task->SetMinLenghtInActiveZoneTPC(0);\n task->SetGeometricalCut(kTRUE,3,130,1.5,0.85,0.7); \/\/\/if kTRUE comment CrossedRowsTPC cut\n \/\/ task->SetMinCrossedRowsTPC(120);\n\n\/\/MC1--\n if(cutMode == 100) mainTask = task; \/\/ has no particular use... just to return task with nominal cut setting in macro\n\n \/\/ cut-variation:\n if(cutMode == 101) {task->SetMaxchi2perITSclu(25.);}\n if(cutMode == 102) {task->SetMaxchi2perITSclu(49.);}\n\n if(cutMode == 103) {task->SetMaxchi2perTPCclu(3); }\n if(cutMode == 104) {task->SetMaxchi2perTPCclu(5); }\n\/\/MC2--\n if(cutMode == 105) {task->SetRatioCrossedRowsOverFindableClustersTPC(0.7);}\n if(cutMode == 106) {task->SetRatioCrossedRowsOverFindableClustersTPC(0.9);}\n\n if(cutMode == 107) {task->SetFractionSharedClustersTPC(0.2);}\n if(cutMode == 108) {task->SetFractionSharedClustersTPC(1.0);}\n\/\/MC3--\n if(cutMode == 109) {task->SetMaxChi2TPCConstrained(25.);}\n if(cutMode == 110) {task->SetMaxChi2TPCConstrained(49.);}\n\n if(cutMode == 111) {task->SetDCAtoVertexXYPtDep(\"0.0104+0.0200\/pt^1.01\");}\n if(cutMode == 112) {task->SetDCAtoVertexXYPtDep(\"0.0260+0.0500\/pt^1.01\");}\n\/\/MC4--\n if(cutMode == 113) {task->SetDCAtoVertexZ(1.0);}\n if(cutMode == 114) {task->SetDCAtoVertexZ(5.0);}\n\n if(cutMode == 115) {task->SetClusterReqITS(kFALSE);}\n\/\/MC5--\n if(cutMode == 116) {task->SetGeometricalCut(kTRUE,3,120,1.5,0.85,0.7);}\n if(cutMode == 117) {task->SetGeometricalCut(kTRUE,3,140,1.5,0.85,0.7);}\n\n if(cutMode == 118) {task->SetGeometricalCut(kTRUE,4,130,1.5,0.85,0.7);}\n if(cutMode == 119) {task->SetGeometricalCut(kTRUE,2,130,1.5,0.85,0.7);}\n\n \/\/ event cut varaitions\n if(cutMode == 120) task->SetZvtx(5.);\n if(cutMode == 121) task->SetZvtx(20.);\n\n\n \/\/ hang task in train\n\n mgr->AddTask(task);\n\n AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();\n AliAnalysisDataContainer* coutput = mgr->CreateContainer(taskName,\n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t \"AnalysisResults.root\");\n\n\n\n mgr->ConnectInput(task, 0, cinput);\n mgr->ConnectOutput(task, 1, coutput);\n\n\n }\n\n\n return mainTask;\n\n}\n<|endoftext|>"} {"text":"Added dumping of MirroredX & MirroredY properties<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2016 Intel Corporation \/\/\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\/\/ own\n#include \"Importer.h\"\n\/\/ ospcommon\n#include \"common\/FileName.h\"\n\/\/ tinyxml\n#include \"TinyXML2.h\"\n\/\/ std\n#include \n#include \n\nnamespace ospray {\n namespace importer {\n\n void importVolumeRAW(const FileName &fileName, Volume *volume);\n void importVolumeRM(const FileName &fileName, Volume *volume);\n\n void importVolume(const FileName &fileName, Volume *volume)\n {\n const std::string ext = fileName.ext();\n if (ext == \"raw\" || ext == \"gz\") {\n importVolumeRAW(fileName, volume);\n } else if (ext == \"bob\") {\n importVolumeRM(fileName, volume);\n } else {\n throw std::runtime_error(\"unknown volume format '\"+ext+\"'\");\n }\n\n \/\/ post-checks\n assert(volume->handle != nullptr);\n assert(!volume->bounds.empty());\n }\n\n vec2i parseInt2(const tinyxml2::XMLNode *node)\n {\n vec2i v;\n int rc = sscanf(node->ToElement()->GetText(),\"%i %i\",&v.x,&v.y);\n (void)rc;\n assert(rc == 2);\n return v;\n }\n vec3i parseInt3(const tinyxml2::XMLNode *node)\n {\n vec3i v;\n int rc = sscanf(node->ToElement()->GetText(),\"%i %i %i\",&v.x,&v.y,&v.z);\n (void)rc;\n assert(rc == 3);\n return v;\n }\n\n float parseFloat1(const tinyxml2::XMLNode *node)\n {\n float v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f\",&v);\n (void)rc;\n assert(rc == 1);\n return v;\n }\n vec2f parseFloat2(const tinyxml2::XMLNode *node)\n {\n vec2f v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f %f\",&v.x,&v.y);\n (void)rc;\n assert(rc == 2);\n return v;\n }\n vec3f parseFloat3(const tinyxml2::XMLNode *node)\n {\n vec3f v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f %f %f\",&v.x,&v.y,&v.z);\n (void)rc;\n assert(rc == 3);\n return v;\n }\n\n void importVolume(const FileName &orgFileName,\n Group *group,\n const tinyxml2::XMLNode *root)\n {\n const char *dpFromEnv = getenv(\"OSPRAY_DATA_PARALLEL\");\n \n Volume *volume = new Volume;\n if (dpFromEnv) {\n \/\/ Create the OSPRay object.\n osp::vec3i blockDims;\n int rc = sscanf(dpFromEnv, \"%dx%dx%d\",\n &blockDims.x, &blockDims.y, &blockDims.z);\n if (rc != 3) {\n throw std::runtime_error(\"could not parse OSPRAY_DATA_PARALLEL \"\n \"env-var. Must be of format xx<>Z \"\n \"(e.g., '4x4x4'\");\n }\n volume->handle = ospNewVolume(\"data_distributed_volume\");\n if (volume->handle == nullptr) {\n throw std::runtime_error(\"#loaders.ospObjectFile: could not create \"\n \"volume ...\");\n }\n ospSetVec3i(volume->handle,\"num_dp_blocks\",blockDims);\n } else {\n \/\/ Create the OSPRay object.\n volume->handle = ospNewVolume(\"block_bricked_volume\");\n }\n\n if (volume->handle == nullptr) {\n throw std::runtime_error(\"#loaders.ospObjectFile: could not create \"\n \"volume ...\");\n }\n \n \/\/ Temporary storage for the file name attribute if specified.\n const char *volumeFilename = nullptr;\n \n \/\/ Iterate over object attributes.\n for (const tinyxml2::XMLNode *node = root->FirstChild();\n node;\n node = node->NextSibling()) {\n \n \/\/ Volume size in voxels per dimension.\n if (!strcmp(node->ToElement()->Name(), \"dimensions\")) \n { volume->dimensions = parseInt3(node); continue; }\n \n \/\/ File containing a volume specification and \/ or voxel data.\n if (!strcmp(node->ToElement()->Name(), \"filename\")) \n { volumeFilename = node->ToElement()->GetText(); continue; }\n \n \/\/ Grid origin in world coordinates.\n if (!strcmp(node->ToElement()->Name(), \"gridOrigin\")) \n { volume->gridOrigin = parseFloat3(node); continue; }\n \n \/\/ Grid spacing in each dimension in world coordinates.\n if (!strcmp(node->ToElement()->Name(), \"gridSpacing\"))\n { volume->gridSpacing = parseFloat3(node); continue; }\n \n \/\/ Sampling rate for ray casting based renderers.\n if (!strcmp(node->ToElement()->Name(), \"samplingRate\")) \n { volume->samplingRate = parseFloat1(node); continue; }\n \n \/\/ Subvolume offset from origin within the full volume.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeOffsets\")) \n { volume->subVolumeOffsets = parseInt3(node); continue; }\n \n \/\/ Subvolume dimensions within the full volume.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeDimensions\")) \n { volume->subVolumeDimensions = parseInt3(node); continue; }\n \n \/\/ Subvolume steps in each dimension; can be used to subsample.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeSteps\")) \n { volume->subVolumeSteps = parseInt3(node); continue; }\n \n \/\/ Voxel value range.\n if (!strcmp(node->ToElement()->Name(), \"voxelRange\")) \n { volume->voxelRange = parseFloat2(node); continue; }\n \n \/\/ Voxel type string.\n if (!strcmp(node->ToElement()->Name(), \"voxelType\")) \n { volume->voxelType = node->ToElement()->GetText(); continue; }\n \n \/\/ Error check.\n exitOnCondition(true, \"unrecognized XML element type '\" + \n std::string(node->ToElement()->Name()) + \"'\");\n }\n \n \/\/ Load the contents of the volume file if specified.\n if (volumeFilename != nullptr) {\n \n \/\/ Some implementations of 'dirname()' are destructive.\n char *duplicateFilename = strdup(orgFileName.str().c_str());\n \n \/\/ The volume file path is absolute.\n if (volumeFilename[0] == '\/') \n importVolume(volumeFilename, volume);\n else {\n importVolume((std::string(dirname(duplicateFilename))\n + \"\/\" + volumeFilename).c_str(), volume);\n }\n \n \/\/ Free the temporary character array.\n if (duplicateFilename != nullptr)\n free(duplicateFilename);\n }\n \n group->volume.push_back(volume);\n }\n \n void importTriangleMesh(Group *group, const tinyxml2::XMLNode *node)\n {\n throw std::runtime_error(\"importTriangleMesh: not yet implemented\");\n }\n\n void importLight(Group *group, const tinyxml2::XMLNode *node)\n {\n throw std::runtime_error(\"importLight: not yet implemented\");\n }\n \n void importObject(const FileName &orgFileName,\n Group *group,\n const tinyxml2::XMLNode *node)\n {\n \/\/ OSPRay light object.\n if (!strcmp(node->ToElement()->Name(), \"light\")) \n importLight(group,node);\n \n \/\/ OSPRay triangle mesh object.\n else if (!strcmp(node->ToElement()->Name(), \"triangleMesh\")) \n importTriangleMesh(group,node);\n \n \/\/ OSPRay volume object.\n else if (!strcmp(node->ToElement()->Name(), \"volume\")) \n importVolume(orgFileName,group,node);\n \n \/\/ No other object types are currently supported.\n else \n exitOnCondition(true, \"unrecognized XML element type '\" \n + std::string(node->ToElement()->Name()) + \"'\"); \n }\n\n void importOSP(const FileName &fileName, Group *existingGroupToAddTo)\n {\n \/\/ The XML document container.\n tinyxml2::XMLDocument xml(true, tinyxml2::COLLAPSE_WHITESPACE);\n \n \/\/ Read the XML object file.\n exitOnCondition(xml.LoadFile(fileName.str().c_str()) != tinyxml2::XML_SUCCESS, \n \"unable to read object file '\" + fileName.str() + \"'\");\n \n Group *group = existingGroupToAddTo ? existingGroupToAddTo : new Group;\n\n \/\/ Iterate over the object entries, skip the XML declaration and comments.\n for (const tinyxml2::XMLNode *node = xml.FirstChild();\n node;\n node = node->NextSibling()) {\n if (node->ToElement()) \n importObject(fileName,group,node); \n }\n\n \/\/ post-checks:\n for (size_t i = 0; i < group->volume.size(); i++) {\n assert(group->volume[i]->handle != nullptr);\n assert(!group->volume[i]->bounds.empty());\n }\n }\n }\n}\nCorrectly set the gridOrigin and gridSpacing XML params\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2016 Intel Corporation \/\/\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\/\/ own\n#include \"Importer.h\"\n\/\/ ospcommon\n#include \"common\/FileName.h\"\n\/\/ tinyxml\n#include \"TinyXML2.h\"\n\/\/ std\n#include \n#include \n\nnamespace ospray {\n namespace importer {\n\n void importVolumeRAW(const FileName &fileName, Volume *volume);\n void importVolumeRM(const FileName &fileName, Volume *volume);\n\n void importVolume(const FileName &fileName, Volume *volume)\n {\n const std::string ext = fileName.ext();\n if (ext == \"raw\" || ext == \"gz\") {\n importVolumeRAW(fileName, volume);\n } else if (ext == \"bob\") {\n importVolumeRM(fileName, volume);\n } else {\n throw std::runtime_error(\"unknown volume format '\"+ext+\"'\");\n }\n\n \/\/ post-checks\n assert(volume->handle != nullptr);\n assert(!volume->bounds.empty());\n }\n\n vec2i parseInt2(const tinyxml2::XMLNode *node)\n {\n vec2i v;\n int rc = sscanf(node->ToElement()->GetText(),\"%i %i\",&v.x,&v.y);\n (void)rc;\n assert(rc == 2);\n return v;\n }\n vec3i parseInt3(const tinyxml2::XMLNode *node)\n {\n vec3i v;\n int rc = sscanf(node->ToElement()->GetText(),\"%i %i %i\",&v.x,&v.y,&v.z);\n (void)rc;\n assert(rc == 3);\n return v;\n }\n\n float parseFloat1(const tinyxml2::XMLNode *node)\n {\n float v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f\",&v);\n (void)rc;\n assert(rc == 1);\n return v;\n }\n vec2f parseFloat2(const tinyxml2::XMLNode *node)\n {\n vec2f v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f %f\",&v.x,&v.y);\n (void)rc;\n assert(rc == 2);\n return v;\n }\n vec3f parseFloat3(const tinyxml2::XMLNode *node)\n {\n vec3f v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f %f %f\",&v.x,&v.y,&v.z);\n (void)rc;\n assert(rc == 3);\n return v;\n }\n\n void importVolume(const FileName &orgFileName,\n Group *group,\n const tinyxml2::XMLNode *root)\n {\n const char *dpFromEnv = getenv(\"OSPRAY_DATA_PARALLEL\");\n \n Volume *volume = new Volume;\n if (dpFromEnv) {\n \/\/ Create the OSPRay object.\n osp::vec3i blockDims;\n int rc = sscanf(dpFromEnv, \"%dx%dx%d\",\n &blockDims.x, &blockDims.y, &blockDims.z);\n if (rc != 3) {\n throw std::runtime_error(\"could not parse OSPRAY_DATA_PARALLEL \"\n \"env-var. Must be of format xx<>Z \"\n \"(e.g., '4x4x4'\");\n }\n volume->handle = ospNewVolume(\"data_distributed_volume\");\n if (volume->handle == nullptr) {\n throw std::runtime_error(\"#loaders.ospObjectFile: could not create \"\n \"volume ...\");\n }\n ospSetVec3i(volume->handle,\"num_dp_blocks\",blockDims);\n } else {\n \/\/ Create the OSPRay object.\n volume->handle = ospNewVolume(\"block_bricked_volume\");\n }\n\n if (volume->handle == nullptr) {\n throw std::runtime_error(\"#loaders.ospObjectFile: could not create \"\n \"volume ...\");\n }\n \n \/\/ Temporary storage for the file name attribute if specified.\n const char *volumeFilename = nullptr;\n \n \/\/ Iterate over object attributes.\n for (const tinyxml2::XMLNode *node = root->FirstChild();\n node;\n node = node->NextSibling()) {\n \n \/\/ Volume size in voxels per dimension.\n if (!strcmp(node->ToElement()->Name(), \"dimensions\")) {\n volume->dimensions = parseInt3(node);\n continue;\n }\n \n \/\/ File containing a volume specification and \/ or voxel data.\n if (!strcmp(node->ToElement()->Name(), \"filename\")) {\n volumeFilename = node->ToElement()->GetText();\n continue;\n }\n \n \/\/ Grid origin in world coordinates.\n if (!strcmp(node->ToElement()->Name(), \"gridOrigin\")) {\n volume->gridOrigin = parseFloat3(node);\n ospSetVec3f(volume->handle, \"gridOrigin\", (osp::vec3f&)volume->gridOrigin);\n continue;\n }\n \n \/\/ Grid spacing in each dimension in world coordinates.\n if (!strcmp(node->ToElement()->Name(), \"gridSpacing\")) {\n volume->gridSpacing = parseFloat3(node);\n ospSetVec3f(volume->handle, \"gridSpacing\", (osp::vec3f&)volume->gridSpacing);\n continue;\n }\n \n \/\/ Sampling rate for ray casting based renderers.\n if (!strcmp(node->ToElement()->Name(), \"samplingRate\")) {\n volume->samplingRate = parseFloat1(node);\n ospSet1f(volume->handle, \"samplingRate\", volume->samplingRate);\n continue;\n }\n \n \/\/ Subvolume offset from origin within the full volume.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeOffsets\")) {\n volume->subVolumeOffsets = parseInt3(node);\n continue;\n }\n \n \/\/ Subvolume dimensions within the full volume.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeDimensions\")) {\n volume->subVolumeDimensions = parseInt3(node);\n continue;\n }\n \n \/\/ Subvolume steps in each dimension; can be used to subsample.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeSteps\")) {\n volume->subVolumeSteps = parseInt3(node);\n continue;\n }\n \n \/\/ Voxel value range.\n if (!strcmp(node->ToElement()->Name(), \"voxelRange\")) {\n volume->voxelRange = parseFloat2(node);\n continue;\n }\n \n \/\/ Voxel type string.\n if (!strcmp(node->ToElement()->Name(), \"voxelType\")) {\n volume->voxelType = node->ToElement()->GetText();\n continue;\n }\n \n \/\/ Error check.\n exitOnCondition(true, \"unrecognized XML element type '\" + \n std::string(node->ToElement()->Name()) + \"'\");\n }\n \n \/\/ Load the contents of the volume file if specified.\n if (volumeFilename != nullptr) {\n \n \/\/ Some implementations of 'dirname()' are destructive.\n char *duplicateFilename = strdup(orgFileName.str().c_str());\n \n \/\/ The volume file path is absolute.\n if (volumeFilename[0] == '\/') \n importVolume(volumeFilename, volume);\n else {\n importVolume((std::string(dirname(duplicateFilename))\n + \"\/\" + volumeFilename).c_str(), volume);\n }\n \n \/\/ Free the temporary character array.\n if (duplicateFilename != nullptr)\n free(duplicateFilename);\n }\n \n group->volume.push_back(volume);\n }\n \n void importTriangleMesh(Group *group, const tinyxml2::XMLNode *node)\n {\n throw std::runtime_error(\"importTriangleMesh: not yet implemented\");\n }\n\n void importLight(Group *group, const tinyxml2::XMLNode *node)\n {\n throw std::runtime_error(\"importLight: not yet implemented\");\n }\n \n void importObject(const FileName &orgFileName,\n Group *group,\n const tinyxml2::XMLNode *node)\n {\n \/\/ OSPRay light object.\n if (!strcmp(node->ToElement()->Name(), \"light\")) \n importLight(group,node);\n \n \/\/ OSPRay triangle mesh object.\n else if (!strcmp(node->ToElement()->Name(), \"triangleMesh\")) \n importTriangleMesh(group,node);\n \n \/\/ OSPRay volume object.\n else if (!strcmp(node->ToElement()->Name(), \"volume\")) \n importVolume(orgFileName,group,node);\n \n \/\/ No other object types are currently supported.\n else \n exitOnCondition(true, \"unrecognized XML element type '\" \n + std::string(node->ToElement()->Name()) + \"'\"); \n }\n\n void importOSP(const FileName &fileName, Group *existingGroupToAddTo)\n {\n \/\/ The XML document container.\n tinyxml2::XMLDocument xml(true, tinyxml2::COLLAPSE_WHITESPACE);\n \n \/\/ Read the XML object file.\n exitOnCondition(xml.LoadFile(fileName.str().c_str()) != tinyxml2::XML_SUCCESS, \n \"unable to read object file '\" + fileName.str() + \"'\");\n \n Group *group = existingGroupToAddTo ? existingGroupToAddTo : new Group;\n\n \/\/ Iterate over the object entries, skip the XML declaration and comments.\n for (const tinyxml2::XMLNode *node = xml.FirstChild();\n node;\n node = node->NextSibling()) {\n if (node->ToElement()) \n importObject(fileName,group,node); \n }\n\n \/\/ post-checks:\n for (size_t i = 0; i < group->volume.size(); i++) {\n assert(group->volume[i]->handle != nullptr);\n assert(!group->volume[i]->bounds.empty());\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2004-2006 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: Kevin Lim\n *\/\n\n#include \"base\/intmath.hh\"\n#include \"cpu\/pred\/tournament.hh\"\n\nTournamentBP::TournamentBP(unsigned _localPredictorSize,\n unsigned _localCtrBits,\n unsigned _localHistoryTableSize,\n unsigned _localHistoryBits,\n unsigned _globalPredictorSize,\n unsigned _globalCtrBits,\n unsigned _globalHistoryBits,\n unsigned _choicePredictorSize,\n unsigned _choiceCtrBits,\n unsigned _instShiftAmt)\n : localPredictorSize(_localPredictorSize),\n localCtrBits(_localCtrBits),\n localHistoryTableSize(_localHistoryTableSize),\n localHistoryBits(_localHistoryBits),\n globalPredictorSize(_globalPredictorSize),\n globalCtrBits(_globalCtrBits),\n globalHistoryBits(_globalHistoryBits),\n choicePredictorSize(_globalPredictorSize),\n choiceCtrBits(_choiceCtrBits),\n instShiftAmt(_instShiftAmt)\n{\n if (!isPowerOf2(localPredictorSize)) {\n fatal(\"Invalid local predictor size!\\n\");\n }\n\n \/\/Setup the array of counters for the local predictor\n localCtrs.resize(localPredictorSize);\n\n for (int i = 0; i < localPredictorSize; ++i)\n localCtrs[i].setBits(localCtrBits);\n\n localPredictorMask = floorPow2(localPredictorSize) - 1;\n\n if (!isPowerOf2(localHistoryTableSize)) {\n fatal(\"Invalid local history table size!\\n\");\n }\n\n \/\/Setup the history table for the local table\n localHistoryTable.resize(localHistoryTableSize);\n\n for (int i = 0; i < localHistoryTableSize; ++i)\n localHistoryTable[i] = 0;\n\n \/\/ Setup the local history mask\n localHistoryMask = (1 << localHistoryBits) - 1;\n\n if (!isPowerOf2(globalPredictorSize)) {\n fatal(\"Invalid global predictor size!\\n\");\n }\n\n \/\/Setup the array of counters for the global predictor\n globalCtrs.resize(globalPredictorSize);\n\n for (int i = 0; i < globalPredictorSize; ++i)\n globalCtrs[i].setBits(globalCtrBits);\n\n \/\/Clear the global history\n globalHistory = 0;\n \/\/ Setup the global history mask\n globalHistoryMask = (1 << globalHistoryBits) - 1;\n\n if (!isPowerOf2(choicePredictorSize)) {\n fatal(\"Invalid choice predictor size!\\n\");\n }\n\n \/\/Setup the array of counters for the choice predictor\n choiceCtrs.resize(choicePredictorSize);\n\n for (int i = 0; i < choicePredictorSize; ++i)\n choiceCtrs[i].setBits(choiceCtrBits);\n\n \/\/ @todo: Allow for different thresholds between the predictors.\n threshold = (1 << (localCtrBits - 1)) - 1;\n}\n\ninline\nunsigned\nTournamentBP::calcLocHistIdx(Addr &branch_addr)\n{\n \/\/ Get low order bits after removing instruction offset.\n return (branch_addr >> instShiftAmt) & (localHistoryTableSize - 1);\n}\n\ninline\nvoid\nTournamentBP::updateGlobalHistTaken()\n{\n globalHistory = (globalHistory << 1) | 1;\n globalHistory = globalHistory & globalHistoryMask;\n}\n\ninline\nvoid\nTournamentBP::updateGlobalHistNotTaken()\n{\n globalHistory = (globalHistory << 1);\n globalHistory = globalHistory & globalHistoryMask;\n}\n\ninline\nvoid\nTournamentBP::updateLocalHistTaken(unsigned local_history_idx)\n{\n localHistoryTable[local_history_idx] =\n (localHistoryTable[local_history_idx] << 1) | 1;\n}\n\ninline\nvoid\nTournamentBP::updateLocalHistNotTaken(unsigned local_history_idx)\n{\n localHistoryTable[local_history_idx] =\n (localHistoryTable[local_history_idx] << 1);\n}\n\nbool\nTournamentBP::lookup(Addr &branch_addr, void * &bp_history)\n{\n bool local_prediction;\n unsigned local_history_idx;\n unsigned local_predictor_idx;\n\n bool global_prediction;\n bool choice_prediction;\n\n \/\/Lookup in the local predictor to get its branch prediction\n local_history_idx = calcLocHistIdx(branch_addr);\n local_predictor_idx = localHistoryTable[local_history_idx]\n & localPredictorMask;\n local_prediction = localCtrs[local_predictor_idx].read() > threshold;\n\n \/\/Lookup in the global predictor to get its branch prediction\n global_prediction = globalCtrs[globalHistory].read() > threshold;\n\n \/\/Lookup in the choice predictor to see which one to use\n choice_prediction = choiceCtrs[globalHistory].read() > threshold;\n\n \/\/ Create BPHistory and pass it back to be recorded.\n BPHistory *history = new BPHistory;\n history->globalHistory = globalHistory;\n history->localPredTaken = local_prediction;\n history->globalPredTaken = global_prediction;\n history->globalUsed = choice_prediction;\n bp_history = (void *)history;\n\n assert(globalHistory < globalPredictorSize &&\n local_history_idx < localHistoryTableSize &&\n local_predictor_idx < localPredictorSize);\n\n \/\/ Commented code is for doing speculative update of counters and\n \/\/ all histories.\n if (choice_prediction) {\n if (global_prediction) {\n\/\/ updateHistoriesTaken(local_history_idx);\n\/\/ globalCtrs[globalHistory].increment();\n\/\/ localCtrs[local_history_idx].increment();\n updateGlobalHistTaken();\n return true;\n } else {\n\/\/ updateHistoriesNotTaken(local_history_idx);\n\/\/ globalCtrs[globalHistory].decrement();\n\/\/ localCtrs[local_history_idx].decrement();\n updateGlobalHistNotTaken();\n return false;\n }\n } else {\n if (local_prediction) {\n\/\/ updateHistoriesTaken(local_history_idx);\n\/\/ globalCtrs[globalHistory].increment();\n\/\/ localCtrs[local_history_idx].increment();\n updateGlobalHistTaken();\n return true;\n } else {\n\/\/ updateHistoriesNotTaken(local_history_idx);\n\/\/ globalCtrs[globalHistory].decrement();\n\/\/ localCtrs[local_history_idx].decrement();\n updateGlobalHistNotTaken();\n return false;\n }\n }\n}\n\nvoid\nTournamentBP::uncondBr(void * &bp_history)\n{\n \/\/ Create BPHistory and pass it back to be recorded.\n BPHistory *history = new BPHistory;\n history->globalHistory = globalHistory;\n history->localPredTaken = true;\n history->globalPredTaken = true;\n bp_history = static_cast(history);\n\n updateGlobalHistTaken();\n}\n\nvoid\nTournamentBP::update(Addr &branch_addr, bool taken, void *bp_history)\n{\n unsigned local_history_idx;\n unsigned local_predictor_idx;\n unsigned local_predictor_hist;\n\n \/\/ Get the local predictor's current prediction\n local_history_idx = calcLocHistIdx(branch_addr);\n local_predictor_hist = localHistoryTable[local_history_idx];\n local_predictor_idx = local_predictor_hist & localPredictorMask;\n\n \/\/ Update the choice predictor to tell it which one was correct if\n \/\/ there was a prediction.\n if (bp_history) {\n BPHistory *history = static_cast(bp_history);\n if (history->localPredTaken != history->globalPredTaken) {\n \/\/ If the local prediction matches the actual outcome,\n \/\/ decerement the counter. Otherwise increment the\n \/\/ counter.\n if (history->localPredTaken == taken) {\n choiceCtrs[globalHistory].decrement();\n } else if (history->globalPredTaken == taken){\n choiceCtrs[globalHistory].increment();\n }\n }\n\n \/\/ We're done with this history, now delete it.\n delete history;\n }\n\n assert(globalHistory < globalPredictorSize &&\n local_history_idx < localHistoryTableSize &&\n local_predictor_idx < localPredictorSize);\n\n \/\/ Update the counters and local history with the proper\n \/\/ resolution of the branch. Global history is updated\n \/\/ speculatively and restored upon squash() calls, so it does not\n \/\/ need to be updated.\n if (taken) {\n localCtrs[local_predictor_idx].increment();\n globalCtrs[globalHistory].increment();\n\n updateLocalHistTaken(local_history_idx);\n } else {\n localCtrs[local_predictor_idx].decrement();\n globalCtrs[globalHistory].decrement();\n\n updateLocalHistNotTaken(local_history_idx);\n }\n}\n\nvoid\nTournamentBP::squash(void *bp_history)\n{\n BPHistory *history = static_cast(bp_history);\n\n \/\/ Restore global history to state prior to this branch.\n globalHistory = history->globalHistory;\n\n \/\/ Delete this BPHistory now that we're done with it.\n delete history;\n}\n\n#ifdef DEBUG\nint\nTournamentBP::BPHistory::newCount = 0;\n#endif\nBranch predictor: Fixes the tournament branch predictor.\/*\n * Copyright (c) 2004-2006 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: Kevin Lim\n *\/\n\n#include \"base\/intmath.hh\"\n#include \"cpu\/pred\/tournament.hh\"\n\nTournamentBP::TournamentBP(unsigned _localPredictorSize,\n unsigned _localCtrBits,\n unsigned _localHistoryTableSize,\n unsigned _localHistoryBits,\n unsigned _globalPredictorSize,\n unsigned _globalHistoryBits,\n unsigned _globalCtrBits,\n unsigned _choicePredictorSize,\n unsigned _choiceCtrBits,\n unsigned _instShiftAmt)\n : localPredictorSize(_localPredictorSize),\n localCtrBits(_localCtrBits),\n localHistoryTableSize(_localHistoryTableSize),\n localHistoryBits(_localHistoryBits),\n globalPredictorSize(_globalPredictorSize),\n globalCtrBits(_globalCtrBits),\n globalHistoryBits(_globalHistoryBits),\n choicePredictorSize(_globalPredictorSize),\n choiceCtrBits(_choiceCtrBits),\n instShiftAmt(_instShiftAmt)\n{\n if (!isPowerOf2(localPredictorSize)) {\n fatal(\"Invalid local predictor size!\\n\");\n }\n\n \/\/Setup the array of counters for the local predictor\n localCtrs.resize(localPredictorSize);\n\n for (int i = 0; i < localPredictorSize; ++i)\n localCtrs[i].setBits(localCtrBits);\n\n localPredictorMask = floorPow2(localPredictorSize) - 1;\n\n if (!isPowerOf2(localHistoryTableSize)) {\n fatal(\"Invalid local history table size!\\n\");\n }\n\n \/\/Setup the history table for the local table\n localHistoryTable.resize(localHistoryTableSize);\n\n for (int i = 0; i < localHistoryTableSize; ++i)\n localHistoryTable[i] = 0;\n\n \/\/ Setup the local history mask\n localHistoryMask = (1 << localHistoryBits) - 1;\n\n if (!isPowerOf2(globalPredictorSize)) {\n fatal(\"Invalid global predictor size!\\n\");\n }\n\n \/\/Setup the array of counters for the global predictor\n globalCtrs.resize(globalPredictorSize);\n\n for (int i = 0; i < globalPredictorSize; ++i)\n globalCtrs[i].setBits(globalCtrBits);\n\n \/\/Clear the global history\n globalHistory = 0;\n \/\/ Setup the global history mask\n globalHistoryMask = (1 << globalHistoryBits) - 1;\n\n if (!isPowerOf2(choicePredictorSize)) {\n fatal(\"Invalid choice predictor size!\\n\");\n }\n\n \/\/Setup the array of counters for the choice predictor\n choiceCtrs.resize(choicePredictorSize);\n\n for (int i = 0; i < choicePredictorSize; ++i)\n choiceCtrs[i].setBits(choiceCtrBits);\n\n \/\/ @todo: Allow for different thresholds between the predictors.\n threshold = (1 << (localCtrBits - 1)) - 1;\n}\n\ninline\nunsigned\nTournamentBP::calcLocHistIdx(Addr &branch_addr)\n{\n \/\/ Get low order bits after removing instruction offset.\n return (branch_addr >> instShiftAmt) & (localHistoryTableSize - 1);\n}\n\ninline\nvoid\nTournamentBP::updateGlobalHistTaken()\n{\n globalHistory = (globalHistory << 1) | 1;\n globalHistory = globalHistory & globalHistoryMask;\n}\n\ninline\nvoid\nTournamentBP::updateGlobalHistNotTaken()\n{\n globalHistory = (globalHistory << 1);\n globalHistory = globalHistory & globalHistoryMask;\n}\n\ninline\nvoid\nTournamentBP::updateLocalHistTaken(unsigned local_history_idx)\n{\n localHistoryTable[local_history_idx] =\n (localHistoryTable[local_history_idx] << 1) | 1;\n}\n\ninline\nvoid\nTournamentBP::updateLocalHistNotTaken(unsigned local_history_idx)\n{\n localHistoryTable[local_history_idx] =\n (localHistoryTable[local_history_idx] << 1);\n}\n\nbool\nTournamentBP::lookup(Addr &branch_addr, void * &bp_history)\n{\n bool local_prediction;\n unsigned local_history_idx;\n unsigned local_predictor_idx;\n\n bool global_prediction;\n bool choice_prediction;\n\n \/\/Lookup in the local predictor to get its branch prediction\n local_history_idx = calcLocHistIdx(branch_addr);\n local_predictor_idx = localHistoryTable[local_history_idx]\n & localPredictorMask;\n local_prediction = localCtrs[local_predictor_idx].read() > threshold;\n\n \/\/Lookup in the global predictor to get its branch prediction\n global_prediction = globalCtrs[globalHistory].read() > threshold;\n\n \/\/Lookup in the choice predictor to see which one to use\n choice_prediction = choiceCtrs[globalHistory].read() > threshold;\n\n \/\/ Create BPHistory and pass it back to be recorded.\n BPHistory *history = new BPHistory;\n history->globalHistory = globalHistory;\n history->localPredTaken = local_prediction;\n history->globalPredTaken = global_prediction;\n history->globalUsed = choice_prediction;\n bp_history = (void *)history;\n\n assert(globalHistory < globalPredictorSize &&\n local_history_idx < localHistoryTableSize &&\n local_predictor_idx < localPredictorSize);\n\n \/\/ Commented code is for doing speculative update of counters and\n \/\/ all histories.\n if (choice_prediction) {\n if (global_prediction) {\n\/\/ updateHistoriesTaken(local_history_idx);\n\/\/ globalCtrs[globalHistory].increment();\n\/\/ localCtrs[local_history_idx].increment();\n updateGlobalHistTaken();\n return true;\n } else {\n\/\/ updateHistoriesNotTaken(local_history_idx);\n\/\/ globalCtrs[globalHistory].decrement();\n\/\/ localCtrs[local_history_idx].decrement();\n updateGlobalHistNotTaken();\n return false;\n }\n } else {\n if (local_prediction) {\n\/\/ updateHistoriesTaken(local_history_idx);\n\/\/ globalCtrs[globalHistory].increment();\n\/\/ localCtrs[local_history_idx].increment();\n updateGlobalHistTaken();\n return true;\n } else {\n\/\/ updateHistoriesNotTaken(local_history_idx);\n\/\/ globalCtrs[globalHistory].decrement();\n\/\/ localCtrs[local_history_idx].decrement();\n updateGlobalHistNotTaken();\n return false;\n }\n }\n}\n\nvoid\nTournamentBP::uncondBr(void * &bp_history)\n{\n \/\/ Create BPHistory and pass it back to be recorded.\n BPHistory *history = new BPHistory;\n history->globalHistory = globalHistory;\n history->localPredTaken = true;\n history->globalPredTaken = true;\n bp_history = static_cast(history);\n\n updateGlobalHistTaken();\n}\n\nvoid\nTournamentBP::update(Addr &branch_addr, bool taken, void *bp_history)\n{\n unsigned local_history_idx;\n unsigned local_predictor_idx;\n unsigned local_predictor_hist;\n\n \/\/ Get the local predictor's current prediction\n local_history_idx = calcLocHistIdx(branch_addr);\n local_predictor_hist = localHistoryTable[local_history_idx];\n local_predictor_idx = local_predictor_hist & localPredictorMask;\n\n \/\/ Update the choice predictor to tell it which one was correct if\n \/\/ there was a prediction.\n if (bp_history) {\n BPHistory *history = static_cast(bp_history);\n if (history->localPredTaken != history->globalPredTaken) {\n \/\/ If the local prediction matches the actual outcome,\n \/\/ decerement the counter. Otherwise increment the\n \/\/ counter.\n if (history->localPredTaken == taken) {\n choiceCtrs[history->globalHistory].decrement();\n } else if (history->globalPredTaken == taken){\n choiceCtrs[history->globalHistory].increment();\n }\n\n }\n\n \/\/ Update the counters and local history with the proper\n \/\/ resolution of the branch. Global history is updated\n \/\/ speculatively and restored upon squash() calls, so it does not\n \/\/ need to be updated.\n if (taken) {\n localCtrs[local_predictor_idx].increment();\n globalCtrs[history->globalHistory].increment();\n\n updateLocalHistTaken(local_history_idx);\n } else {\n localCtrs[local_predictor_idx].decrement();\n globalCtrs[history->globalHistory].decrement();\n\n updateLocalHistNotTaken(local_history_idx);\n }\n\n bool mispredict = false;\n\n \/\/global predictor used and mispredicted\n if (history->globalUsed && history->globalPredTaken != taken)\n mispredict = true;\n \/\/local predictor used and mispredicted\n else if (!history->globalUsed && history->localPredTaken != taken)\n mispredict = true;\n\n if (mispredict) {\n if (taken) {\n globalHistory = globalHistory | 1;\n } else {\n unsigned mask = globalHistoryMask - 1;\n globalHistory = globalHistory & mask;\n }\n\n }\n \/\/ We're done with this history, now delete it.\n delete history;\n }\n\n assert(globalHistory < globalPredictorSize &&\n local_history_idx < localHistoryTableSize &&\n local_predictor_idx < localPredictorSize);\n\n\n}\n\nvoid\nTournamentBP::squash(void *bp_history)\n{\n BPHistory *history = static_cast(bp_history);\n\n \/\/ Restore global history to state prior to this branch.\n globalHistory = history->globalHistory;\n\n \/\/ Delete this BPHistory now that we're done with it.\n delete history;\n}\n\n#ifdef DEBUG\nint\nTournamentBP::BPHistory::newCount = 0;\n#endif\n<|endoftext|>"} {"text":"class ExitCounter{\n public:\n static int get();\n static int dec();\n private:\n \/\/ If fastforwarding is turned of the count\n \/\/ needs to be manually changed to 0 here.\n ExitCounter(){ count=1; };\n static ExitCounter * instance;\n int count;\n\n};\nTo run without fast forwarding global_exit_count needs to start at 0class ExitCounter{\n public:\n static int get();\n static int dec();\n private:\n \/\/ If fastforwarding is turned of the count\n \/\/ needs to be manually changed to 0 here.\n ExitCounter(){ count=0; };\n static ExitCounter * instance;\n int count;\n\n};\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 Global Phasing Ltd.\n\/\/\n\/\/ Compare two CIF files with monomer restraints.\n\n#include \n#include \n#include \n#include \/\/ for read_cif_gz\n#include \/\/ for make_chemcomp_from_block\n#define GEMMI_PROG mondiff\n#include \"options.h\"\n\nusing namespace gemmi;\n\nenum OptionIndex { Verbose=3, Bond, BondEsd, Angle, AngleEsd, Relative };\n\nstatic const option::Descriptor Usage[] = {\n { NoOp, 0, \"\", \"\", Arg::None,\n \"Usage:\"\n \"\\n \" EXE_NAME \" [options] FILE1 FILE2\"\n \"\\nOptions:\"},\n CommonUsage[Help],\n CommonUsage[Version],\n { Verbose, 0, \"v\", \"verbose\", Arg::None, \" --verbose \\tVerbose output.\" },\n { NoOp, 0, \"\", \"\", Arg::None, \"\\nMinimal reported differences:\" },\n { Bond, 0, \"\", \"bond\", Arg::Float,\n \" --bond=DELTA \\tdifference in distance value (default: 0.01).\" },\n { BondEsd, 0, \"\", \"bond-esd\", Arg::Float,\n \" --bond-esd=DELTA \\tdifference in distance esd (default: 0.1).\" },\n { Angle, 0, \"\", \"angle\", Arg::Float,\n \" --angle=DELTA \\tdifference in angle value (default: 0.1).\" },\n { AngleEsd, 0, \"\", \"angle-esd\", Arg::Float,\n \" --angle-esd=DELTA \\tdifference in angle esd (default: 1.0).\" },\n { Relative, 0, \"\", \"rel\", Arg::Float,\n \" --rel=SIGMA \\t abs(value difference) \/ esd > SIGMA (default: 0.0).\" },\n { 0, 0, 0, 0, 0, 0 }\n};\n\nstruct MinDelta {\n double bond = 0.01;\n double bond_esd = 0.1;\n double angle = 0.1;\n double angle_esd = 1.0;\n double rel = 0.0;\n};\n\nstatic\nstd::string str(const ChemComp& cc, const Restraints::Bond& b) {\n return gemmi::tostr(\"bond \", b.id1.atom, '-', b.id2.atom,\n \" (\", cc.get_atom(b.id1.atom).chem_type,\n '-', cc.get_atom(b.id2.atom).chem_type, ')');\n}\n\nstatic\nstd::string str(const ChemComp& cc, const Restraints::Angle& a) {\n return gemmi::tostr(\"angle \", a.id1.atom, '-', a.id2.atom, '-', a.id3.atom,\n \" (\", cc.get_atom(a.id1.atom).chem_type,\n '-', cc.get_atom(a.id2.atom).chem_type,\n '-', cc.get_atom(a.id3.atom).chem_type, ')');\n}\n\nstatic\nstd::string str(const ChemComp&, const Restraints::Torsion& a) {\n return \"torsion \" + a.str();\n}\n\nstatic\nstd::string str(const ChemComp&, const Restraints::Chirality& a) {\n return \"chirality \" + a.str();\n}\n\nstatic\nconst char* mark(double delta, double eps) {\n if (delta < eps) return \"\";\n if (delta < 2*eps) return \"*\";\n if (delta < 4*eps) return \"**\";\n if (delta < 8*eps) return \"***\";\n return \"****\";\n}\n\nstatic\nvoid compare_chemcomps(const ChemComp& cc1, const ChemComp& cc2,\n const MinDelta& delta) {\n \/\/ atoms\n for (const ChemComp::Atom& a : cc1.atoms) {\n auto b = cc2.find_atom(a.id);\n if (b == cc2.atoms.end())\n printf(\"- atom %s (%s)\\n\", a.id.c_str(), a.chem_type.c_str());\n else if (a.chem_type != b->chem_type)\n printf(\"! atom %s (%s : %s)\\n\",\n a.id.c_str(), a.chem_type.c_str(), b->chem_type.c_str());\n }\n for (const ChemComp::Atom& a : cc2.atoms)\n if (cc1.find_atom(a.id) == cc1.atoms.end())\n printf(\"+ atom %s (%s)\\n\", a.id.c_str(), a.chem_type.c_str());\n\n \/\/ bonds\n for (const Restraints::Bond& a : cc1.rt.bonds) {\n auto b = cc2.rt.find_bond(a.id1, a.id2);\n if (b == cc2.rt.bonds.end()) {\n printf(\"- %s\\n\", str(cc1, a).c_str());\n } else {\n if (a.type != b->type)\n printf(\"! %-30s %s : %s\\n\", str(cc1, a).c_str(),\n bond_type_to_string(a.type),\n bond_type_to_string(b->type));\n double d = std::fabs(a.value - b->value);\n if ((d > delta.bond || std::fabs(a.esd - b->esd) > delta.bond_esd) &&\n d > delta.rel * std::min(a.esd, b->esd))\n printf(\"! %-30s %4s %.3f : %.3f esd %.3f : %.3f\\n\",\n str(cc1, a).c_str(), mark(d, a.esd),\n a.value, b->value, a.esd, b->esd);\n }\n }\n for (const Restraints::Bond& a : cc2.rt.bonds)\n if (cc1.rt.find_bond(a.id1, a.id2) == cc1.rt.bonds.end())\n printf(\"+ %s\\n\", str(cc2, a).c_str());\n\n \/\/ angles\n for (const Restraints::Angle& a : cc1.rt.angles) {\n auto b = cc2.rt.find_angle(a.id1, a.id2, a.id3);\n if (b == cc2.rt.angles.end()) {\n printf(\"- %s\\n\", str(cc1, a).c_str());\n } else {\n double d = std::fabs(a.value - b->value);\n if ((d > delta.angle || std::fabs(a.esd - b->esd) > delta.angle_esd) &&\n d > delta.rel * std::min(a.esd, b->esd))\n printf(\"! %-30s %4s %6.2f : %6.2f esd %.2f : %.2f\\n\",\n str(cc1, a).c_str(), mark(d, a.esd),\n a.value, b->value, a.esd, b->esd);\n }\n }\n for (const Restraints::Angle& a : cc2.rt.angles)\n if (cc1.rt.find_angle(a.id1, a.id2, a.id3) == cc1.rt.angles.end())\n printf(\"+ %s\\n\", str(cc2, a).c_str());\n\n \/\/ torsion angles\n for (const Restraints::Torsion& a : cc1.rt.torsions) {\n auto b = cc2.rt.find_torsion(a.id1, a.id2, a.id3, a.id4);\n if (b == cc2.rt.torsions.end()) {\n printf(\"- %s\\n\", str(cc1, a).c_str());\n } else {\n double d = std::fabs(a.value - b->value);\n if ((d > delta.angle || std::fabs(a.esd - b->esd) > delta.angle_esd) &&\n d > delta.rel * std::min(a.esd, b->esd))\n printf(\"! %-30s %4s %6.2f : %6.2f esd %.2f : %.2f\\n\",\n str(cc1, a).c_str(), mark(d, a.esd),\n a.value, b->value, a.esd, b->esd);\n }\n }\n for (const Restraints::Torsion& a : cc2.rt.torsions)\n if (cc1.rt.find_torsion(a.id1, a.id2, a.id3,a.id4) == cc1.rt.torsions.end())\n printf(\"+ %s\\n\", str(cc2, a).c_str());\n\n \/\/ chiralities\n std::vector matched_chir(cc2.rt.chirs.size(), false);\n for (const Restraints::Chirality& a : cc1.rt.chirs) {\n if (a.sign == ChiralityType::Both) \/\/ not interesting\n continue;\n auto b = cc2.rt.find_chir(a.id_ctr, a.id1, a.id2, a.id3);\n if (b != cc2.rt.chirs.end()) {\n if (a.sign != b->sign)\n printf(\"! %-30s %s : %s\\n\", str(cc1, a).c_str(),\n chirality_to_string(a.sign), chirality_to_string(b->sign));\n matched_chir[b - cc2.rt.chirs.begin()] = true;\n continue;\n }\n b = cc2.rt.find_chir(a.id_ctr, a.id1, a.id3, a.id2);\n if (b == cc2.rt.chirs.end()) {\n printf(\"- %s %s\\n\", str(cc1, a).c_str(), chirality_to_string(a.sign));\n } else {\n matched_chir[b - cc2.rt.chirs.begin()] = true;\n if (b->sign == ChiralityType::Both || b->sign == a.sign)\n printf(\"! %-30s %s : -%s\\n\", str(cc1, a).c_str(),\n chirality_to_string(a.sign), chirality_to_string(b->sign));\n }\n }\n for (size_t i = 0; i != cc2.rt.chirs.size(); ++i)\n if (!matched_chir[i]) {\n const Restraints::Chirality& a = cc2.rt.chirs[i];\n printf(\"+ %s %s\\n\", str(cc2, a).c_str(), chirality_to_string(a.sign));\n }\n\n \/\/ planes\n std::vector matched_planes(cc2.rt.planes.size(), false);\n std::vector> planes2;\n planes2.reserve(cc2.rt.planes.size());\n for (const Restraints::Plane& b : cc2.rt.planes)\n planes2.emplace_back(b.ids.begin(), b.ids.end());\n for (const Restraints::Plane& a : cc1.rt.planes) {\n std::set plane1(a.ids.begin(), a.ids.end());\n auto b = std::find(planes2.begin(), planes2.end(), plane1);\n if (b == planes2.end()) {\n printf(\"- plane %s\\n\", a.str().c_str());\n continue;\n }\n double b_esd = cc2.rt.planes[b - planes2.begin()].esd;\n if (std::fabs(a.esd - b_esd) > 0.02)\n printf(\"! plane %-53s esd %.2f : %.2f\\n\", a.str().c_str(), a.esd, b_esd);\n b->clear();\n }\n for (size_t i = 0; i != planes2.size(); ++i)\n if (!planes2[i].empty())\n printf(\"+ plane %s\\n\", cc2.rt.planes[i].str().c_str());\n}\n\nint GEMMI_MAIN(int argc, char **argv) {\n OptParser p(EXE_NAME);\n p.simple_parse(argc, argv, Usage);\n p.require_positional_args(2);\n bool verbose = p.options[Verbose];\n const char* path1 = p.nonOption(0);\n const char* path2 = p.nonOption(1);\n\n MinDelta delta;\n if (p.options[Bond])\n delta.bond = std::atof(p.options[Bond].arg);\n if (p.options[BondEsd])\n delta.bond_esd = std::atof(p.options[BondEsd].arg);\n if (p.options[Angle])\n delta.angle = std::atof(p.options[Angle].arg);\n if (p.options[AngleEsd])\n delta.angle_esd = std::atof(p.options[AngleEsd].arg);\n if (p.options[Relative])\n delta.rel = std::atof(p.options[Relative].arg);\n\n try {\n if (verbose)\n fprintf(stderr, \"Reading %s ...\\n\", path1);\n cif::Document doc1 = read_cif_gz(path1);\n const cif::Block* block1 = &doc1.blocks.at(0);\n if (block1->name == \"comp_list\")\n block1 = &doc1.blocks.at(1);\n if (verbose)\n fprintf(stderr, \"Reading %s ...\\n\", path2);\n cif::Document doc2 = read_cif_gz(path2);\n const cif::Block* block2 = doc2.find_block(block1->name);\n if (!block2)\n fail(\"Block \" + block1->name + \" not found in \" + path2);\n ChemComp cc1 = make_chemcomp_from_block(*block1);\n ChemComp cc2 = make_chemcomp_from_block(*block2);\n compare_chemcomps(cc1, cc2, delta);\n } catch (std::runtime_error& e) {\n fprintf(stderr, \"ERROR: %s\\n\", e.what());\n return 1;\n }\n return 0;\n}\n\n\/\/ vim:sw=2:ts=2:et:path^=..\/include,..\/third_party\nmondiff.cpp: catch std::out_of_range\/\/ Copyright 2019 Global Phasing Ltd.\n\/\/\n\/\/ Compare two CIF files with monomer restraints.\n\n#include \n#include \n#include \n#include \/\/ for read_cif_gz\n#include \/\/ for make_chemcomp_from_block\n#define GEMMI_PROG mondiff\n#include \"options.h\"\n\nusing namespace gemmi;\n\nenum OptionIndex { Verbose=3, Bond, BondEsd, Angle, AngleEsd, Relative };\n\nstatic const option::Descriptor Usage[] = {\n { NoOp, 0, \"\", \"\", Arg::None,\n \"Usage:\"\n \"\\n \" EXE_NAME \" [options] FILE1 FILE2\"\n \"\\nOptions:\"},\n CommonUsage[Help],\n CommonUsage[Version],\n { Verbose, 0, \"v\", \"verbose\", Arg::None, \" --verbose \\tVerbose output.\" },\n { NoOp, 0, \"\", \"\", Arg::None, \"\\nMinimal reported differences:\" },\n { Bond, 0, \"\", \"bond\", Arg::Float,\n \" --bond=DELTA \\tdifference in distance value (default: 0.01).\" },\n { BondEsd, 0, \"\", \"bond-esd\", Arg::Float,\n \" --bond-esd=DELTA \\tdifference in distance esd (default: 0.1).\" },\n { Angle, 0, \"\", \"angle\", Arg::Float,\n \" --angle=DELTA \\tdifference in angle value (default: 0.1).\" },\n { AngleEsd, 0, \"\", \"angle-esd\", Arg::Float,\n \" --angle-esd=DELTA \\tdifference in angle esd (default: 1.0).\" },\n { Relative, 0, \"\", \"rel\", Arg::Float,\n \" --rel=SIGMA \\t abs(value difference) \/ esd > SIGMA (default: 0.0).\" },\n { 0, 0, 0, 0, 0, 0 }\n};\n\nstruct MinDelta {\n double bond = 0.01;\n double bond_esd = 0.1;\n double angle = 0.1;\n double angle_esd = 1.0;\n double rel = 0.0;\n};\n\nstatic\nstd::string str(const ChemComp& cc, const Restraints::Bond& b) {\n return gemmi::tostr(\"bond \", b.id1.atom, '-', b.id2.atom,\n \" (\", cc.get_atom(b.id1.atom).chem_type,\n '-', cc.get_atom(b.id2.atom).chem_type, ')');\n}\n\nstatic\nstd::string str(const ChemComp& cc, const Restraints::Angle& a) {\n return gemmi::tostr(\"angle \", a.id1.atom, '-', a.id2.atom, '-', a.id3.atom,\n \" (\", cc.get_atom(a.id1.atom).chem_type,\n '-', cc.get_atom(a.id2.atom).chem_type,\n '-', cc.get_atom(a.id3.atom).chem_type, ')');\n}\n\nstatic\nstd::string str(const ChemComp&, const Restraints::Torsion& a) {\n return \"torsion \" + a.str();\n}\n\nstatic\nstd::string str(const ChemComp&, const Restraints::Chirality& a) {\n return \"chirality \" + a.str();\n}\n\nstatic\nconst char* mark(double delta, double eps) {\n if (delta < eps) return \"\";\n if (delta < 2*eps) return \"*\";\n if (delta < 4*eps) return \"**\";\n if (delta < 8*eps) return \"***\";\n return \"****\";\n}\n\nstatic\nvoid compare_chemcomps(const ChemComp& cc1, const ChemComp& cc2,\n const MinDelta& delta) {\n \/\/ atoms\n for (const ChemComp::Atom& a : cc1.atoms) {\n auto b = cc2.find_atom(a.id);\n if (b == cc2.atoms.end())\n printf(\"- atom %s (%s)\\n\", a.id.c_str(), a.chem_type.c_str());\n else if (a.chem_type != b->chem_type)\n printf(\"! atom %s (%s : %s)\\n\",\n a.id.c_str(), a.chem_type.c_str(), b->chem_type.c_str());\n }\n for (const ChemComp::Atom& a : cc2.atoms)\n if (cc1.find_atom(a.id) == cc1.atoms.end())\n printf(\"+ atom %s (%s)\\n\", a.id.c_str(), a.chem_type.c_str());\n\n \/\/ bonds\n for (const Restraints::Bond& a : cc1.rt.bonds) {\n auto b = cc2.rt.find_bond(a.id1, a.id2);\n if (b == cc2.rt.bonds.end()) {\n printf(\"- %s\\n\", str(cc1, a).c_str());\n } else {\n if (a.type != b->type)\n printf(\"! %-30s %s : %s\\n\", str(cc1, a).c_str(),\n bond_type_to_string(a.type),\n bond_type_to_string(b->type));\n double d = std::fabs(a.value - b->value);\n if ((d > delta.bond || std::fabs(a.esd - b->esd) > delta.bond_esd) &&\n d > delta.rel * std::min(a.esd, b->esd))\n printf(\"! %-30s %4s %.3f : %.3f esd %.3f : %.3f\\n\",\n str(cc1, a).c_str(), mark(d, a.esd),\n a.value, b->value, a.esd, b->esd);\n }\n }\n for (const Restraints::Bond& a : cc2.rt.bonds)\n if (cc1.rt.find_bond(a.id1, a.id2) == cc1.rt.bonds.end())\n printf(\"+ %s\\n\", str(cc2, a).c_str());\n\n \/\/ angles\n for (const Restraints::Angle& a : cc1.rt.angles) {\n auto b = cc2.rt.find_angle(a.id1, a.id2, a.id3);\n if (b == cc2.rt.angles.end()) {\n printf(\"- %s\\n\", str(cc1, a).c_str());\n } else {\n double d = std::fabs(a.value - b->value);\n if ((d > delta.angle || std::fabs(a.esd - b->esd) > delta.angle_esd) &&\n d > delta.rel * std::min(a.esd, b->esd))\n printf(\"! %-30s %4s %6.2f : %6.2f esd %.2f : %.2f\\n\",\n str(cc1, a).c_str(), mark(d, a.esd),\n a.value, b->value, a.esd, b->esd);\n }\n }\n for (const Restraints::Angle& a : cc2.rt.angles)\n if (cc1.rt.find_angle(a.id1, a.id2, a.id3) == cc1.rt.angles.end())\n printf(\"+ %s\\n\", str(cc2, a).c_str());\n\n \/\/ torsion angles\n for (const Restraints::Torsion& a : cc1.rt.torsions) {\n auto b = cc2.rt.find_torsion(a.id1, a.id2, a.id3, a.id4);\n if (b == cc2.rt.torsions.end()) {\n printf(\"- %s\\n\", str(cc1, a).c_str());\n } else {\n double d = std::fabs(a.value - b->value);\n if ((d > delta.angle || std::fabs(a.esd - b->esd) > delta.angle_esd) &&\n d > delta.rel * std::min(a.esd, b->esd))\n printf(\"! %-30s %4s %6.2f : %6.2f esd %.2f : %.2f\\n\",\n str(cc1, a).c_str(), mark(d, a.esd),\n a.value, b->value, a.esd, b->esd);\n }\n }\n for (const Restraints::Torsion& a : cc2.rt.torsions)\n if (cc1.rt.find_torsion(a.id1, a.id2, a.id3,a.id4) == cc1.rt.torsions.end())\n printf(\"+ %s\\n\", str(cc2, a).c_str());\n\n \/\/ chiralities\n std::vector matched_chir(cc2.rt.chirs.size(), false);\n for (const Restraints::Chirality& a : cc1.rt.chirs) {\n if (a.sign == ChiralityType::Both) \/\/ not interesting\n continue;\n auto b = cc2.rt.find_chir(a.id_ctr, a.id1, a.id2, a.id3);\n if (b != cc2.rt.chirs.end()) {\n if (a.sign != b->sign)\n printf(\"! %-30s %s : %s\\n\", str(cc1, a).c_str(),\n chirality_to_string(a.sign), chirality_to_string(b->sign));\n matched_chir[b - cc2.rt.chirs.begin()] = true;\n continue;\n }\n b = cc2.rt.find_chir(a.id_ctr, a.id1, a.id3, a.id2);\n if (b == cc2.rt.chirs.end()) {\n printf(\"- %s %s\\n\", str(cc1, a).c_str(), chirality_to_string(a.sign));\n } else {\n matched_chir[b - cc2.rt.chirs.begin()] = true;\n if (b->sign == ChiralityType::Both || b->sign == a.sign)\n printf(\"! %-30s %s : -%s\\n\", str(cc1, a).c_str(),\n chirality_to_string(a.sign), chirality_to_string(b->sign));\n }\n }\n for (size_t i = 0; i != cc2.rt.chirs.size(); ++i)\n if (!matched_chir[i]) {\n const Restraints::Chirality& a = cc2.rt.chirs[i];\n printf(\"+ %s %s\\n\", str(cc2, a).c_str(), chirality_to_string(a.sign));\n }\n\n \/\/ planes\n std::vector matched_planes(cc2.rt.planes.size(), false);\n std::vector> planes2;\n planes2.reserve(cc2.rt.planes.size());\n for (const Restraints::Plane& b : cc2.rt.planes)\n planes2.emplace_back(b.ids.begin(), b.ids.end());\n for (const Restraints::Plane& a : cc1.rt.planes) {\n std::set plane1(a.ids.begin(), a.ids.end());\n auto b = std::find(planes2.begin(), planes2.end(), plane1);\n if (b == planes2.end()) {\n printf(\"- plane %s\\n\", a.str().c_str());\n continue;\n }\n double b_esd = cc2.rt.planes[b - planes2.begin()].esd;\n if (std::fabs(a.esd - b_esd) > 0.02)\n printf(\"! plane %-53s esd %.2f : %.2f\\n\", a.str().c_str(), a.esd, b_esd);\n b->clear();\n }\n for (size_t i = 0; i != planes2.size(); ++i)\n if (!planes2[i].empty())\n printf(\"+ plane %s\\n\", cc2.rt.planes[i].str().c_str());\n}\n\nint GEMMI_MAIN(int argc, char **argv) {\n OptParser p(EXE_NAME);\n p.simple_parse(argc, argv, Usage);\n p.require_positional_args(2);\n bool verbose = p.options[Verbose];\n const char* path1 = p.nonOption(0);\n const char* path2 = p.nonOption(1);\n\n MinDelta delta;\n if (p.options[Bond])\n delta.bond = std::atof(p.options[Bond].arg);\n if (p.options[BondEsd])\n delta.bond_esd = std::atof(p.options[BondEsd].arg);\n if (p.options[Angle])\n delta.angle = std::atof(p.options[Angle].arg);\n if (p.options[AngleEsd])\n delta.angle_esd = std::atof(p.options[AngleEsd].arg);\n if (p.options[Relative])\n delta.rel = std::atof(p.options[Relative].arg);\n\n try {\n if (verbose)\n fprintf(stderr, \"Reading %s ...\\n\", path1);\n cif::Document doc1 = read_cif_gz(path1);\n const cif::Block* block1 = &doc1.blocks.at(0);\n if (block1->name == \"comp_list\")\n block1 = &doc1.blocks.at(1);\n if (verbose)\n fprintf(stderr, \"Reading %s ...\\n\", path2);\n cif::Document doc2 = read_cif_gz(path2);\n const cif::Block* block2 = doc2.find_block(block1->name);\n if (!block2)\n fail(\"Block \" + block1->name + \" not found in \" + path2);\n ChemComp cc1 = make_chemcomp_from_block(*block1);\n ChemComp cc2 = make_chemcomp_from_block(*block2);\n compare_chemcomps(cc1, cc2, delta);\n } catch (std::runtime_error& e) {\n fprintf(stderr, \"ERROR: %s\\n\", e.what());\n return 1;\n } catch (std::out_of_range& e) {\n fprintf(stderr, \"ERROR: %s\\n\", e.what());\n return 2;\n }\n return 0;\n}\n\n\/\/ vim:sw=2:ts=2:et:path^=..\/include,..\/third_party\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 Global Phasing Ltd.\n\/\/\n\/\/ convert MTZ to SF-mmCIF\n\n\/\/ TODO:\n\/\/ - cell parameters may be different in CELL and DCELL records, check for it\n\/\/ - what to do with _refln.status\n\/\/ - check that the FP column is not from Refmac\n\/\/ - should we allow for repeated column name in MTZ?\n\n#include \n#include \n#include \n#include \/\/ for file_open\n#include \/\/ for read_word\n#include \/\/ for GEMMI_VERSION\n#define GEMMI_PROG mtz2cif\n#include \"options.h\"\n\nenum OptionIndex { Verbose=3, Spec, PrintSpec };\n\nstatic const option::Descriptor Usage[] = {\n { NoOp, 0, \"\", \"\", Arg::None,\n \"Usage:\\n \" EXE_NAME \" [options] MTZ_FILE CIF_FILE\"\n \"\\nOptions:\"},\n { Help, 0, \"h\", \"help\", Arg::None, \" -h, --help \\tPrint usage and exit.\" },\n { Version, 0, \"V\", \"version\", Arg::None,\n \" -V, --version \\tPrint version and exit.\" },\n { Verbose, 0, \"v\", \"verbose\", Arg::None, \" --verbose \\tVerbose output.\" },\n { Spec, 0, \"\", \"spec\", Arg::Required,\n \" --spec=FILE \\tColumn and format specification.\" },\n { PrintSpec, 0, \"\", \"print-spec\", Arg::None,\n \" --print-spec \\tPrint default spec and exit.\" },\n { NoOp, 0, \"\", \"\", Arg::None,\n \"\\nIf CIF_FILE is -, the output is printed to stdout.\"\n \"\\nIf spec is -, it is read from stdin.\"\n \"\\n\\nLines in the spec file have format:\"\n \"\\n [FLAG] COLUMN TYPE TAG [FORMAT]\"\n \"\\nfor example:\"\n \"\\n SIGF_native * SIGF_meas_au 12.5e\"\n \"\\n FREE I pdbx_r_free_flag 3d\"\n \"\\nFLAG (optional) is either ? or &:\"\n \"\\n ? = column is skipped if absent in the MTZ file.\"\n \"\\n & = column is skipped if previous line was skipped. Example:\"\n \"\\n ? I J intensity_meas\"\n \"\\n & SIGI Q intensity_sigma\"\n \"\\nCOLUMN is MTZ column label. Columns H K L are added if not specified.\"\n \"\\n Alternative labels can be separated with | (e.g. FREE|FreeR_flag).\"\n \"\\nTYPE is used for checking the columm type, unless it is '*'.\"\n \"\\nTAG does not include category name, it is only the part after _refln.\"\n \"\\nFORMAT (optional) is printf-like floating-point format:\"\n \"\\n - one of e, f, g with optional flag, width and precision\"\n \"\\n - flag is one of + - # _; '_' stands for ' ', for example '_.4f'\"\n \"\\n - since all numbers in MTZ are stored as float, the integer columns use\"\n \"\\n the same format as float. The format of _refln.status is ignored.\"\n },\n { 0, 0, 0, 0, 0, 0 }\n};\n\nstruct Trans {\n int col_idx;\n bool is_status;\n std::string refln_tag;\n std::string format;\n};\n\nstatic const char* default_spec[] = {\n \"H H index_h\",\n \"K H index_k\",\n \"L H index_l\",\n \"? I J intensity_meas\",\n \"& SIGI Q intensity_sigma\",\n \"? I(+) K pdbx_I_plus\",\n \"& SIGI(+) M pdbx_I_plus_sigma\",\n \"? I(-) K pdbx_I_minus\",\n \"& SIGI(-) M pdbx_I_minus_sigma\",\n \"? FP F F_meas_au\", \/\/ check also if the MTZ is not from refmac\n \"& SIGFP Q F_meas_sigma_au\",\n \"? F(+) G pdbx_F_plus\",\n \"& SIGF(+) L pdbx_F_plus_sigma\",\n \"? F(-) G pdbx_F_minus\",\n \"& SIGF(-) L pdbx_F_minus_sigma\",\n \"? FREE|RFREE|FreeR_flag I status\",\n \"? FWT|2FOFCWT F pdbx_FWT\",\n \"& PHWT|PH2FOFCWT P pdbx_PHWT\",\n \"? DELFWT|FOFCWT F pdbx_DELFWT\",\n \"& DELPHWT|PHFOFCWT P pdbx_DELPHWT\",\n};\n\nstatic int find_column_index(const std::string& column, const gemmi::Mtz& mtz) {\n int idx = -1;\n for (const std::string& label : gemmi::split_str(column, '|')) {\n for (size_t i = 0; i != mtz.columns.size(); ++i) {\n if (mtz.columns[i].label == label) {\n if (idx == -1)\n idx = (int) i;\n else\n fprintf(stderr, \"Warning: duplicate column %s\\n\", label.c_str());\n }\n }\n if (idx != -1)\n break;\n }\n return idx;\n}\n\nvoid check_format(const std::string& fmt) {\n \/\/ expected format: [#_+-]?\\d*(\\.\\d+)?[fFgGeEc]\n if (fmt.find('%') != std::string::npos)\n gemmi::fail(\"Specify format without %. Got: \" + fmt);\n size_t pos = 0;\n if (fmt[0] == '_' || fmt[0] == '+' || fmt[0] == '-' || fmt[0] == '#')\n pos = 1;\n while (gemmi::is_digit(fmt[pos]))\n ++pos;\n if (fmt[pos] == '.' && gemmi::is_digit(fmt[pos+1])) {\n pos += 2;\n while (gemmi::is_digit(fmt[pos]))\n ++pos;\n }\n if (std::isalpha(fmt[pos]))\n ++pos;\n if (fmt[pos] != '\\0')\n gemmi::fail(\"wrong format : \" + fmt + \"\\nCorrect examples: g, .4f, 12.5e\");\n char c = gemmi::alpha_up(fmt.back());\n if (c != 'F' && c != 'G' && c != 'E')\n gemmi::fail(\"expected floating-point format, got: \" + fmt);\n}\n\nstatic std::vector parse_spec(const gemmi::Mtz& mtz,\n const std::vector& lines) {\n std::vector spec;\n size_t prev_size = 0;\n bool discard = false;\n for (const std::string& line : lines) {\n Trans tr;\n const char* p = line.c_str();\n if (*p == '&') {\n if (discard)\n continue;\n } else {\n prev_size = spec.size();\n discard = false;\n }\n bool optional = (*p == '?' || *p == '&');\n if (optional)\n ++p;\n std::string column = gemmi::read_word(p, &p);\n std::string type = gemmi::read_word(p, &p);\n if (type.size() != 1)\n gemmi::fail(\"Spec error: MTZ type '\" + type + \"' is not one character,\"\n \"\\nin line: \" + line);\n tr.refln_tag = gemmi::read_word(p, &p);\n if (tr.refln_tag[0] == '_' || tr.refln_tag.find('.') != std::string::npos)\n gemmi::fail(\"Spec error: expected tag part after _refln., got: \" +\n tr.refln_tag + \"\\nin line: \" + line);\n tr.col_idx = find_column_index(column, mtz);\n if (tr.col_idx == -1) {\n if (!optional)\n gemmi::fail(\"Column not found: \" + column);\n spec.resize(prev_size);\n discard = true;\n continue;\n }\n const gemmi::Mtz::Column& col = mtz.columns[tr.col_idx];\n if (type[0] != '*' && col.type != type[0])\n gemmi::fail(\"Column \" + col.label + \" has type \" +\n std::string(1, col.type) + \" not \" + type);\n tr.is_status = gemmi::iequal(tr.refln_tag, \"status\");\n std::string fmt = gemmi::read_word(p, &p);\n if (fmt.empty()) {\n tr.format = \"%g\";\n } else if (!tr.is_status) {\n check_format(fmt);\n tr.format = \"%\" + fmt;\n if (tr.format[1] == '_')\n tr.format[1] = ' ';\n }\n spec.push_back(tr);\n }\n return spec;\n}\n\n#if defined(__GNUC__)\n# pragma GCC diagnostic ignored \"-Wformat-nonliteral\"\n#endif\n\nstatic void write_cif(const gemmi::Mtz& mtz, const std::vector spec,\n FILE* out) {\n std::string id = \".\";\n fprintf(out, \"# Converted from MTZ by gemmi-mtz2cif \" GEMMI_VERSION \"\\n\");\n fprintf(out, \"# MTZ title: %s\\n\", mtz.title.c_str());\n for (size_t i = 0; i != mtz.history.size(); ++i)\n fprintf(out, \"# MTZ history #%zu: %s\\n\", i, mtz.history[i].c_str());\n fprintf(out, \"data_%s\\n\\n\", \"mtz\");\n fprintf(out, \"_entry.id %s\\n\\n\", id.c_str());\n const gemmi::UnitCell& cell = mtz.get_cell();\n fprintf(out, \"_cell.entry_id %s\\n\", id.c_str());\n fprintf(out, \"_cell.length_a %8.3f\\n\", cell.a);\n fprintf(out, \"_cell.length_b %8.3f\\n\", cell.b);\n fprintf(out, \"_cell.length_c %8.3f\\n\", cell.c);\n fprintf(out, \"_cell.angle_alpha %8.3f\\n\", cell.alpha);\n fprintf(out, \"_cell.angle_beta %8.3f\\n\", cell.beta);\n fprintf(out, \"_cell.angle_gamma %8.3f\\n\\n\", cell.gamma);\n if (const gemmi::SpaceGroup* sg = mtz.spacegroup) {\n fprintf(out, \"_symmetry.entry_id %s\\n\", id.c_str());\n fprintf(out, \"_symmetry.space_group_name_H-M %s\\n\", sg->hm);\n fprintf(out, \"_symmetry.Int_Tables_number %d\\n\\n\", sg->number);\n \/\/ could write _symmetry_equiv.pos_as_xyz, but would it be useful?\n }\n fprintf(out, \"loop_\\n\");\n for (const Trans& tr : spec) {\n const gemmi::Mtz::Column& col = mtz.columns.at(tr.col_idx);\n const gemmi::Mtz::Dataset& ds = mtz.dataset(col.dataset_number);\n fprintf(out, \"_refln.%-24s # %-14s from dataset %s\\n\",\n tr.refln_tag.c_str(), col.label.c_str(), ds.dataset_name.c_str());\n }\n for (int i = 0; i != mtz.nreflections; ++i) {\n const float* row = &mtz.raw_data[i*mtz.ncol];\n bool first = true;\n for (const Trans& tr : spec) {\n if (first)\n first = false;\n else\n fputc(' ', out);\n float v = row[tr.col_idx];\n if (tr.is_status)\n fputc(v ? 'f' : '<', out);\n else\n fprintf(out, tr.format.c_str(), v);\n }\n fputc('\\n', out);\n }\n}\n\nint GEMMI_MAIN(int argc, char **argv) {\n OptParser p(EXE_NAME);\n p.simple_parse(argc, argv, Usage);\n if (p.options[PrintSpec]) {\n for (const char* line : default_spec)\n printf(\"%s\\n\", line);\n return 0;\n }\n p.require_positional_args(2);\n bool verbose = p.options[Verbose];\n const char* mtz_path = p.nonOption(0);\n const char* cif_path = p.nonOption(1);\n gemmi::Mtz mtz;\n if (verbose) {\n fprintf(stderr, \"Reading %s ...\\n\", mtz_path);\n mtz.warnings = stderr;\n }\n try {\n gemmi::fileptr_t f_in = gemmi::file_open(mtz_path, \"rb\");\n mtz.read_all_headers(f_in.get());\n mtz.read_raw_data(f_in.get());\n } catch (std::runtime_error& e) {\n fprintf(stderr, \"ERROR reading %s: %s\\n\", mtz_path, e.what());\n return 1;\n }\n if (verbose)\n fprintf(stderr, \"Writing %s ...\\n\", cif_path);\n std::vector spec;\n try {\n std::vector lines;\n if (p.options[Spec]) {\n char buf[256];\n const char* spec_path = p.options[Spec].arg;\n gemmi::fileptr_t f_spec = gemmi::file_open_or(spec_path, \"r\", stdin);\n while (fgets(buf, sizeof(buf), f_spec.get()) != NULL) {\n const char* start = gemmi::skip_blank(buf);\n if (*start != '\\0' && *start != '#')\n lines.emplace_back(start);\n }\n } else {\n lines.reserve(sizeof(default_spec) \/ sizeof(default_spec[0]));\n for (const char* line : default_spec)\n lines.emplace_back(line);\n }\n spec = parse_spec(mtz, lines);\n if (spec.empty())\n gemmi::fail(\"Empty translation spec\");\n for (size_t i = 0; i != spec.size(); ++i)\n for (size_t j = i + 1; j != spec.size(); ++j)\n if (spec[i].refln_tag == spec[j].refln_tag)\n gemmi::fail(\"duplicated output tag: \" + spec[i].refln_tag);\n \/\/ H, K, L must be the first columns in MTZ and are required in _refln\n for (int i = 2; i != -1; --i)\n if (!gemmi::in_vector_f([&](const Trans& t) { return t.col_idx == i; },\n spec)) {\n spec.insert(spec.begin(), Trans{i, false, \"index_h\", \"%g \"});\n spec.front().refln_tag.back() += i;\n }\n } catch (std::runtime_error& e) {\n fprintf(stderr, \"Problem in translation spec: %s\\n\", e.what());\n return 2;\n }\n try {\n gemmi::fileptr_t f_out = gemmi::file_open_or(cif_path, \"w\", stdout);\n write_cif(mtz, spec, f_out.get());\n } catch (std::runtime_error& e) {\n fprintf(stderr, \"ERROR writing %s: %s\\n\", cif_path, e.what());\n return 3;\n }\n return 0;\n}\n\n\/\/ vim:sw=2:ts=2:et:path^=..\/include,..\/third_party\nmtz2cif: fix _refln.status\/\/ Copyright 2019 Global Phasing Ltd.\n\/\/\n\/\/ convert MTZ to SF-mmCIF\n\n\/\/ TODO:\n\/\/ - cell parameters may be different in CELL and DCELL records, check for it\n\/\/ - what to do with _refln.status\n\/\/ - check that the FP column is not from Refmac\n\/\/ - should we allow for repeated column name in MTZ?\n\n#include \n#include \n#include \n#include \/\/ for file_open\n#include \/\/ for read_word\n#include \/\/ for GEMMI_VERSION\n#define GEMMI_PROG mtz2cif\n#include \"options.h\"\n\nenum OptionIndex { Verbose=3, Spec, PrintSpec };\n\nstatic const option::Descriptor Usage[] = {\n { NoOp, 0, \"\", \"\", Arg::None,\n \"Usage:\\n \" EXE_NAME \" [options] MTZ_FILE CIF_FILE\"\n \"\\nOptions:\"},\n { Help, 0, \"h\", \"help\", Arg::None, \" -h, --help \\tPrint usage and exit.\" },\n { Version, 0, \"V\", \"version\", Arg::None,\n \" -V, --version \\tPrint version and exit.\" },\n { Verbose, 0, \"v\", \"verbose\", Arg::None, \" --verbose \\tVerbose output.\" },\n { Spec, 0, \"\", \"spec\", Arg::Required,\n \" --spec=FILE \\tColumn and format specification.\" },\n { PrintSpec, 0, \"\", \"print-spec\", Arg::None,\n \" --print-spec \\tPrint default spec and exit.\" },\n { NoOp, 0, \"\", \"\", Arg::None,\n \"\\nIf CIF_FILE is -, the output is printed to stdout.\"\n \"\\nIf spec is -, it is read from stdin.\"\n \"\\n\\nLines in the spec file have format:\"\n \"\\n [FLAG] COLUMN TYPE TAG [FORMAT]\"\n \"\\nfor example:\"\n \"\\n SIGF_native * SIGF_meas_au 12.5e\"\n \"\\n FREE I pdbx_r_free_flag 3d\"\n \"\\nFLAG (optional) is either ? or &:\"\n \"\\n ? = column is skipped if absent in the MTZ file.\"\n \"\\n & = column is skipped if previous line was skipped. Example:\"\n \"\\n ? I J intensity_meas\"\n \"\\n & SIGI Q intensity_sigma\"\n \"\\nCOLUMN is MTZ column label. Columns H K L are added if not specified.\"\n \"\\n Alternative labels can be separated with | (e.g. FREE|FreeR_flag).\"\n \"\\nTYPE is used for checking the columm type, unless it is '*'.\"\n \"\\nTAG does not include category name, it is only the part after _refln.\"\n \"\\nFORMAT (optional) is printf-like floating-point format:\"\n \"\\n - one of e, f, g with optional flag, width and precision\"\n \"\\n - flag is one of + - # _; '_' stands for ' ', for example '_.4f'\"\n \"\\n - since all numbers in MTZ are stored as float, the integer columns use\"\n \"\\n the same format as float. The format of _refln.status is ignored.\"\n },\n { 0, 0, 0, 0, 0, 0 }\n};\n\nstruct Trans {\n int col_idx;\n bool is_status;\n std::string refln_tag;\n std::string format;\n};\n\nstatic const char* default_spec[] = {\n \"H H index_h\",\n \"K H index_k\",\n \"L H index_l\",\n \"? I J intensity_meas\",\n \"& SIGI Q intensity_sigma\",\n \"? I(+) K pdbx_I_plus\",\n \"& SIGI(+) M pdbx_I_plus_sigma\",\n \"? I(-) K pdbx_I_minus\",\n \"& SIGI(-) M pdbx_I_minus_sigma\",\n \"? FP F F_meas_au\", \/\/ check also if the MTZ is not from refmac\n \"& SIGFP Q F_meas_sigma_au\",\n \"? F(+) G pdbx_F_plus\",\n \"& SIGF(+) L pdbx_F_plus_sigma\",\n \"? F(-) G pdbx_F_minus\",\n \"& SIGF(-) L pdbx_F_minus_sigma\",\n \"? FREE|RFREE|FreeR_flag I status\",\n \"? FWT|2FOFCWT F pdbx_FWT\",\n \"& PHWT|PH2FOFCWT P pdbx_PHWT\",\n \"? DELFWT|FOFCWT F pdbx_DELFWT\",\n \"& DELPHWT|PHFOFCWT P pdbx_DELPHWT\",\n};\n\nstatic int find_column_index(const std::string& column, const gemmi::Mtz& mtz) {\n int idx = -1;\n for (const std::string& label : gemmi::split_str(column, '|')) {\n for (size_t i = 0; i != mtz.columns.size(); ++i) {\n if (mtz.columns[i].label == label) {\n if (idx == -1)\n idx = (int) i;\n else\n fprintf(stderr, \"Warning: duplicate column %s\\n\", label.c_str());\n }\n }\n if (idx != -1)\n break;\n }\n return idx;\n}\n\nvoid check_format(const std::string& fmt) {\n \/\/ expected format: [#_+-]?\\d*(\\.\\d+)?[fFgGeEc]\n if (fmt.find('%') != std::string::npos)\n gemmi::fail(\"Specify format without %. Got: \" + fmt);\n size_t pos = 0;\n if (fmt[0] == '_' || fmt[0] == '+' || fmt[0] == '-' || fmt[0] == '#')\n pos = 1;\n while (gemmi::is_digit(fmt[pos]))\n ++pos;\n if (fmt[pos] == '.' && gemmi::is_digit(fmt[pos+1])) {\n pos += 2;\n while (gemmi::is_digit(fmt[pos]))\n ++pos;\n }\n if (std::isalpha(fmt[pos]))\n ++pos;\n if (fmt[pos] != '\\0')\n gemmi::fail(\"wrong format : \" + fmt + \"\\nCorrect examples: g, .4f, 12.5e\");\n char c = gemmi::alpha_up(fmt.back());\n if (c != 'F' && c != 'G' && c != 'E')\n gemmi::fail(\"expected floating-point format, got: \" + fmt);\n}\n\nstatic std::vector parse_spec(const gemmi::Mtz& mtz,\n const std::vector& lines) {\n std::vector spec;\n size_t prev_size = 0;\n bool discard = false;\n for (const std::string& line : lines) {\n Trans tr;\n const char* p = line.c_str();\n if (*p == '&') {\n if (discard)\n continue;\n } else {\n prev_size = spec.size();\n discard = false;\n }\n bool optional = (*p == '?' || *p == '&');\n if (optional)\n ++p;\n std::string column = gemmi::read_word(p, &p);\n std::string type = gemmi::read_word(p, &p);\n if (type.size() != 1)\n gemmi::fail(\"Spec error: MTZ type '\" + type + \"' is not one character,\"\n \"\\nin line: \" + line);\n tr.refln_tag = gemmi::read_word(p, &p);\n if (tr.refln_tag[0] == '_' || tr.refln_tag.find('.') != std::string::npos)\n gemmi::fail(\"Spec error: expected tag part after _refln., got: \" +\n tr.refln_tag + \"\\nin line: \" + line);\n tr.col_idx = find_column_index(column, mtz);\n if (tr.col_idx == -1) {\n if (!optional)\n gemmi::fail(\"Column not found: \" + column);\n spec.resize(prev_size);\n discard = true;\n continue;\n }\n const gemmi::Mtz::Column& col = mtz.columns[tr.col_idx];\n if (type[0] != '*' && col.type != type[0])\n gemmi::fail(\"Column \" + col.label + \" has type \" +\n std::string(1, col.type) + \" not \" + type);\n tr.is_status = gemmi::iequal(tr.refln_tag, \"status\");\n std::string fmt = gemmi::read_word(p, &p);\n if (fmt.empty()) {\n tr.format = \"%g\";\n } else if (!tr.is_status) {\n check_format(fmt);\n tr.format = \"%\" + fmt;\n if (tr.format[1] == '_')\n tr.format[1] = ' ';\n }\n spec.push_back(tr);\n }\n return spec;\n}\n\n#if defined(__GNUC__)\n# pragma GCC diagnostic ignored \"-Wformat-nonliteral\"\n#endif\n\nstatic void write_cif(const gemmi::Mtz& mtz, const std::vector spec,\n FILE* out) {\n std::string id = \".\";\n fprintf(out, \"# Converted from MTZ by gemmi-mtz2cif \" GEMMI_VERSION \"\\n\");\n fprintf(out, \"# MTZ title: %s\\n\", mtz.title.c_str());\n for (size_t i = 0; i != mtz.history.size(); ++i)\n fprintf(out, \"# MTZ history #%zu: %s\\n\", i, mtz.history[i].c_str());\n fprintf(out, \"data_%s\\n\\n\", \"mtz\");\n fprintf(out, \"_entry.id %s\\n\\n\", id.c_str());\n const gemmi::UnitCell& cell = mtz.get_cell();\n fprintf(out, \"_cell.entry_id %s\\n\", id.c_str());\n fprintf(out, \"_cell.length_a %8.3f\\n\", cell.a);\n fprintf(out, \"_cell.length_b %8.3f\\n\", cell.b);\n fprintf(out, \"_cell.length_c %8.3f\\n\", cell.c);\n fprintf(out, \"_cell.angle_alpha %8.3f\\n\", cell.alpha);\n fprintf(out, \"_cell.angle_beta %8.3f\\n\", cell.beta);\n fprintf(out, \"_cell.angle_gamma %8.3f\\n\\n\", cell.gamma);\n if (const gemmi::SpaceGroup* sg = mtz.spacegroup) {\n fprintf(out, \"_symmetry.entry_id %s\\n\", id.c_str());\n fprintf(out, \"_symmetry.space_group_name_H-M %s\\n\", sg->hm);\n fprintf(out, \"_symmetry.Int_Tables_number %d\\n\\n\", sg->number);\n \/\/ could write _symmetry_equiv.pos_as_xyz, but would it be useful?\n }\n fprintf(out, \"loop_\\n\");\n for (const Trans& tr : spec) {\n const gemmi::Mtz::Column& col = mtz.columns.at(tr.col_idx);\n const gemmi::Mtz::Dataset& ds = mtz.dataset(col.dataset_number);\n fprintf(out, \"_refln.%-24s # %-14s from dataset %s\\n\",\n tr.refln_tag.c_str(), col.label.c_str(), ds.dataset_name.c_str());\n }\n for (int i = 0; i != mtz.nreflections; ++i) {\n const float* row = &mtz.raw_data[i*mtz.ncol];\n bool first = true;\n for (const Trans& tr : spec) {\n if (first)\n first = false;\n else\n fputc(' ', out);\n float v = row[tr.col_idx];\n if (tr.is_status)\n fputc(v == 0. ? 'f' : 'o', out);\n else\n fprintf(out, tr.format.c_str(), v);\n }\n fputc('\\n', out);\n }\n}\n\nint GEMMI_MAIN(int argc, char **argv) {\n OptParser p(EXE_NAME);\n p.simple_parse(argc, argv, Usage);\n if (p.options[PrintSpec]) {\n for (const char* line : default_spec)\n printf(\"%s\\n\", line);\n return 0;\n }\n p.require_positional_args(2);\n bool verbose = p.options[Verbose];\n const char* mtz_path = p.nonOption(0);\n const char* cif_path = p.nonOption(1);\n gemmi::Mtz mtz;\n if (verbose) {\n fprintf(stderr, \"Reading %s ...\\n\", mtz_path);\n mtz.warnings = stderr;\n }\n try {\n gemmi::fileptr_t f_in = gemmi::file_open(mtz_path, \"rb\");\n mtz.read_all_headers(f_in.get());\n mtz.read_raw_data(f_in.get());\n } catch (std::runtime_error& e) {\n fprintf(stderr, \"ERROR reading %s: %s\\n\", mtz_path, e.what());\n return 1;\n }\n if (verbose)\n fprintf(stderr, \"Writing %s ...\\n\", cif_path);\n std::vector spec;\n try {\n std::vector lines;\n if (p.options[Spec]) {\n char buf[256];\n const char* spec_path = p.options[Spec].arg;\n gemmi::fileptr_t f_spec = gemmi::file_open_or(spec_path, \"r\", stdin);\n while (fgets(buf, sizeof(buf), f_spec.get()) != NULL) {\n const char* start = gemmi::skip_blank(buf);\n if (*start != '\\0' && *start != '#')\n lines.emplace_back(start);\n }\n } else {\n lines.reserve(sizeof(default_spec) \/ sizeof(default_spec[0]));\n for (const char* line : default_spec)\n lines.emplace_back(line);\n }\n spec = parse_spec(mtz, lines);\n if (spec.empty())\n gemmi::fail(\"Empty translation spec\");\n for (size_t i = 0; i != spec.size(); ++i)\n for (size_t j = i + 1; j != spec.size(); ++j)\n if (spec[i].refln_tag == spec[j].refln_tag)\n gemmi::fail(\"duplicated output tag: \" + spec[i].refln_tag);\n \/\/ H, K, L must be the first columns in MTZ and are required in _refln\n for (int i = 2; i != -1; --i)\n if (!gemmi::in_vector_f([&](const Trans& t) { return t.col_idx == i; },\n spec)) {\n spec.insert(spec.begin(), Trans{i, false, \"index_h\", \"%g \"});\n spec.front().refln_tag.back() += i;\n }\n } catch (std::runtime_error& e) {\n fprintf(stderr, \"Problem in translation spec: %s\\n\", e.what());\n return 2;\n }\n try {\n gemmi::fileptr_t f_out = gemmi::file_open_or(cif_path, \"w\", stdout);\n write_cif(mtz, spec, f_out.get());\n } catch (std::runtime_error& e) {\n fprintf(stderr, \"ERROR writing %s: %s\\n\", cif_path, e.what());\n return 3;\n }\n return 0;\n}\n\n\/\/ vim:sw=2:ts=2:et:path^=..\/include,..\/third_party\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Cloudius Systems\n *\/\n\n#include \"core\/reactor.hh\"\n#include \"core\/sstring.hh\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass char_filter {\n using uchar = unsigned char;\npublic:\n template \n explicit char_filter(Pred pred) {\n for (unsigned i = 0; i <= std::numeric_limits::max(); ++i) {\n _filter.set(i, pred(i));\n }\n }\n bool operator()(char v) const { return _filter.test(uchar(v)); }\nprivate:\n std::bitset<1 << std::numeric_limits::digits> _filter;\n};\n\nchar_filter tchar([](char c) {\n return std::isalnum(c) || std::string(\"-!#$%&'\\\\*\\\\+.^_`|~\").find_first_of(c) != std::string::npos;\n});\nchar_filter op_char([](char c) { return std::isupper(c); });\nchar_filter sp_char([](char c) { return std::isspace(c); });\nchar_filter nsp_char([](char c) { return !std::isspace(c); });\nchar_filter digit_char([](char c) { return std::isdigit(c); });\n\nclass http_server {\n std::vector _listeners;\npublic:\n void listen(ipv4_addr addr) {\n listen_options lo;\n lo.reuse_address = true;\n _listeners.push_back(engine.listen(make_ipv4_address(addr), lo));\n do_accepts(_listeners.size() - 1);\n }\n void do_accepts(int which) {\n _listeners[which].accept().then([this, which] (connected_socket fd, socket_address addr) mutable {\n (new connection(*this, std::move(fd), addr))->read().rescue([this] (auto get_ex) {\n try {\n get_ex();\n } catch (std::exception& ex) {\n std::cout << \"request error \" << ex.what() << \"\\n\";\n }\n });\n do_accepts(which);\n }).rescue([] (auto get_ex) {\n try {\n get_ex();\n } catch (std::exception& ex) {\n std::cout << \"accept failed: \" << ex.what() << \"\\n\";\n }\n });\n }\n class connection {\n connected_socket _fd;\n input_stream _read_buf;\n output_stream _write_buf;\n bool _eof = false;\n static constexpr size_t limit = 4096;\n using tmp_buf = temporary_buffer;\n struct request {\n sstring _method;\n sstring _url;\n sstring _version;\n std::unordered_map _headers;\n };\n sstring _last_header_name;\n struct response {\n sstring _response_line;\n sstring _body;\n std::unordered_map _headers;\n };\n std::unique_ptr _req;\n std::unique_ptr _resp;\n std::queue> _pending_responses;\n public:\n connection(http_server& server, connected_socket&& fd, socket_address addr)\n : _fd(std::move(fd)), _read_buf(_fd.input())\n , _write_buf(_fd.output()) {}\n future<> read() {\n return _read_buf.read_until(limit, '\\n').then([this] (tmp_buf start_line) {\n if (!start_line.size()) {\n _eof = true;\n maybe_done();\n return make_ready_future<>();\n }\n _req = std::make_unique();\n size_t pos = 0;\n size_t end = start_line.size();\n while (pos < end && op_char(start_line[pos])) {\n ++pos;\n }\n if (pos == 0) {\n return bad(std::move(_req));\n }\n _req->_method = sstring(start_line.begin(), pos);\n if (pos == end || start_line[pos++] != ' ') {\n return bad(std::move(_req));\n }\n auto url = pos;\n while (pos < end && nsp_char(start_line[pos])) {\n ++pos;\n }\n _req->_url = sstring(start_line.begin() + url, pos - url);\n if (pos == end || start_line[pos++] != ' ') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != 'H') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != 'T') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != 'T') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != 'P') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != '\/') {\n return bad(std::move(_req));\n }\n auto ver = pos;\n if (pos == end || !digit_char(start_line[pos++])) {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != '.') {\n return bad(std::move(_req));\n }\n if (pos == end || !digit_char(start_line[pos++])) {\n return bad(std::move(_req));\n }\n _req->_version = sstring(start_line.begin() + ver, pos - ver);\n if (pos == end || start_line[pos++] != '\\r') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != '\\n') {\n return bad(std::move(_req));\n }\n if (pos != end) {\n return bad(std::move(_req));\n }\n if (_req->_method != \"GET\") {\n return bad(std::move(_req));\n }\n return _read_buf.read_until(limit, '\\n').then([this] (tmp_buf header) {\n return parse_header(std::move(header));\n });\n });\n }\n future<> parse_header(tmp_buf header) {\n if (header.size() == 2 && header[0] == '\\r' && header[1] == '\\n') {\n generate_response(std::move(_req));\n read().rescue([this] (auto get_ex) mutable {\n try {\n get_ex();\n } catch (std::exception& ex) {\n std::cout << \"read failed with \" << ex.what() << \"\\n\";\n this->maybe_done();\n }\n });\n return make_ready_future<>();\n }\n size_t pos = 0;\n size_t end = header.size();\n if (end < 2 || header[end-2] != '\\r' || header[end-1] != '\\n') {\n return bad(std::move(_req));\n }\n while (tchar(header[pos])) {\n ++pos;\n }\n if (pos) {\n sstring name = sstring(header.begin(), pos);\n while (pos != end && sp_char(header[pos])) {\n ++pos;\n }\n if (pos == end || header[pos++] != ':') {\n return bad(std::move(_req));\n }\n while (pos != end && sp_char(header[pos])) {\n ++pos;\n }\n while (pos != end && sp_char(header[end-1])) {\n --end;\n }\n sstring value = sstring(header.begin() + pos, end - pos);\n _req->_headers[name] = std::move(value);\n _last_header_name = std::move(name);\n } else {\n while (sp_char(header[pos])) {\n ++pos;\n }\n while (pos != end && sp_char(header[end-1])) {\n --end;\n }\n if (!pos || end == pos) {\n return bad(std::move(_req));\n }\n _req->_headers[_last_header_name] += \" \";\n _req->_headers[_last_header_name] += sstring(header.begin() + pos, end - pos);\n }\n return _read_buf.read_until(limit, '\\n').then([this] (tmp_buf header) {\n return parse_header(std::move(header));\n });\n }\n future<> bad(std::unique_ptr req) {\n auto resp = std::make_unique();\n resp->_response_line = \"HTTP\/1.1 400 BAD REQUEST\\r\\n\\r\\n\";\n respond(std::move(resp));\n _eof = true;\n throw std::runtime_error(\"failed to parse request\");\n }\n void respond(std::unique_ptr resp) {\n if (!_resp) {\n _resp = std::move(resp);\n start_response();\n } else {\n _pending_responses.push(std::move(resp));\n }\n }\n void start_response() {\n _resp->_headers[\"Content-Length\"] = to_sstring(_resp->_body.size());\n _write_buf.write(_resp->_response_line.begin(), _resp->_response_line.size()).then(\n [this] (size_t n) mutable {\n return write_response_headers(_resp->_headers.begin());\n }).then([this] (size_t done) {\n return _write_buf.write(\"\\r\\n\", 2);\n }).then([this] (size_t done) mutable {\n return write_body();\n }).then([this] (size_t done) {\n return _write_buf.flush();\n }).then([this] (bool done) {\n _resp.reset();\n if (!_pending_responses.empty()) {\n _resp = std::move(_pending_responses.front());\n _pending_responses.pop();\n start_response();\n } else {\n maybe_done();\n }\n });\n }\n future write_response_headers(std::unordered_map::iterator hi) {\n if (hi == _resp->_headers.end()) {\n return make_ready_future(0);\n }\n return _write_buf.write(hi->first.begin(), hi->first.size()).then(\n [hi, this] (size_t done) mutable {\n return _write_buf.write(\": \", 2);\n }).then([hi, this] (size_t done) mutable {\n return _write_buf.write(hi->second.begin(), hi->second.size());\n }).then([hi, this] (size_t done) mutable {\n return _write_buf.write(\"\\r\\n\", 2);\n }).then([hi, this] (size_t done) mutable {\n return write_response_headers(++hi);\n });\n }\n void generate_response(std::unique_ptr req) {\n auto resp = std::make_unique();\n resp->_response_line = \"HTTP\/1.1 200 OK\\r\\n\";\n resp->_headers[\"Content-Type\"] = \"text\/html\";\n resp->_body = \"this is the future<\/title><\/head><body><p>Future!!<\/p><\/body><\/html>\";\n respond(std::move(resp));\n }\n future<size_t> write_body() {\n return _write_buf.write(_resp->_body.begin(), _resp->_body.size());\n }\n void maybe_done() {\n if (_eof && !_req && !_resp && _pending_responses.empty()) {\n delete this;\n }\n }\n };\n};\n\nint main(int ac, char** av) {\n http_server server;\n namespace bpo = boost::program_options;\n bpo::options_description opts;\n opts.add_options()\n (\"help\", \"show help message\")\n ;\n opts.add(reactor::get_options_description());\n bpo::variables_map configuration;\n bpo::store(bpo::command_line_parser(ac, av).options(opts).run(), configuration);\n bpo::notify(configuration);\n if (configuration.count(\"help\")) {\n std::cout << opts << \"\\n\";\n return 1;\n }\n engine.configure(configuration);\n engine.when_started().then([&server] {\n uint16_t port = 10000;\n std::cout << \"Seastar HTTP server listening on port \" << port << \" ...\\n\";\n server.listen({{}, port});\n });\n engine.run();\n return 0;\n}\n\n\n<commit_msg>Run http with smp<commit_after>\/*\n * Copyright 2014 Cloudius Systems\n *\/\n\n#include \"core\/reactor.hh\"\n#include \"core\/sstring.hh\"\n#include <iostream>\n#include <algorithm>\n#include <unordered_map>\n#include <queue>\n#include <bitset>\n#include <limits>\n#include <cctype>\n\nclass char_filter {\n using uchar = unsigned char;\npublic:\n template <typename Pred>\n explicit char_filter(Pred pred) {\n for (unsigned i = 0; i <= std::numeric_limits<uchar>::max(); ++i) {\n _filter.set(i, pred(i));\n }\n }\n bool operator()(char v) const { return _filter.test(uchar(v)); }\nprivate:\n std::bitset<1 << std::numeric_limits<uchar>::digits> _filter;\n};\n\nchar_filter tchar([](char c) {\n return std::isalnum(c) || std::string(\"-!#$%&'\\\\*\\\\+.^_`|~\").find_first_of(c) != std::string::npos;\n});\nchar_filter op_char([](char c) { return std::isupper(c); });\nchar_filter sp_char([](char c) { return std::isspace(c); });\nchar_filter nsp_char([](char c) { return !std::isspace(c); });\nchar_filter digit_char([](char c) { return std::isdigit(c); });\n\nclass http_server {\n std::vector<server_socket> _listeners;\npublic:\n void listen(ipv4_addr addr) {\n listen_options lo;\n lo.reuse_address = true;\n _listeners.push_back(engine.listen(make_ipv4_address(addr), lo));\n do_accepts(_listeners.size() - 1);\n }\n void do_accepts(int which) {\n _listeners[which].accept().then([this, which] (connected_socket fd, socket_address addr) mutable {\n (new connection(*this, std::move(fd), addr))->read().rescue([this] (auto get_ex) {\n try {\n get_ex();\n } catch (std::exception& ex) {\n std::cout << \"request error \" << ex.what() << \"\\n\";\n }\n });\n do_accepts(which);\n }).rescue([] (auto get_ex) {\n try {\n get_ex();\n } catch (std::exception& ex) {\n std::cout << \"accept failed: \" << ex.what() << \"\\n\";\n }\n });\n }\n class connection {\n connected_socket _fd;\n input_stream<char> _read_buf;\n output_stream<char> _write_buf;\n bool _eof = false;\n static constexpr size_t limit = 4096;\n using tmp_buf = temporary_buffer<char>;\n struct request {\n sstring _method;\n sstring _url;\n sstring _version;\n std::unordered_map<sstring, sstring> _headers;\n };\n sstring _last_header_name;\n struct response {\n sstring _response_line;\n sstring _body;\n std::unordered_map<sstring, sstring> _headers;\n };\n std::unique_ptr<request> _req;\n std::unique_ptr<response> _resp;\n std::queue<std::unique_ptr<response>> _pending_responses;\n public:\n connection(http_server& server, connected_socket&& fd, socket_address addr)\n : _fd(std::move(fd)), _read_buf(_fd.input())\n , _write_buf(_fd.output()) {}\n future<> read() {\n return _read_buf.read_until(limit, '\\n').then([this] (tmp_buf start_line) {\n if (!start_line.size()) {\n _eof = true;\n maybe_done();\n return make_ready_future<>();\n }\n _req = std::make_unique<request>();\n size_t pos = 0;\n size_t end = start_line.size();\n while (pos < end && op_char(start_line[pos])) {\n ++pos;\n }\n if (pos == 0) {\n return bad(std::move(_req));\n }\n _req->_method = sstring(start_line.begin(), pos);\n if (pos == end || start_line[pos++] != ' ') {\n return bad(std::move(_req));\n }\n auto url = pos;\n while (pos < end && nsp_char(start_line[pos])) {\n ++pos;\n }\n _req->_url = sstring(start_line.begin() + url, pos - url);\n if (pos == end || start_line[pos++] != ' ') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != 'H') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != 'T') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != 'T') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != 'P') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != '\/') {\n return bad(std::move(_req));\n }\n auto ver = pos;\n if (pos == end || !digit_char(start_line[pos++])) {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != '.') {\n return bad(std::move(_req));\n }\n if (pos == end || !digit_char(start_line[pos++])) {\n return bad(std::move(_req));\n }\n _req->_version = sstring(start_line.begin() + ver, pos - ver);\n if (pos == end || start_line[pos++] != '\\r') {\n return bad(std::move(_req));\n }\n if (pos == end || start_line[pos++] != '\\n') {\n return bad(std::move(_req));\n }\n if (pos != end) {\n return bad(std::move(_req));\n }\n if (_req->_method != \"GET\") {\n return bad(std::move(_req));\n }\n return _read_buf.read_until(limit, '\\n').then([this] (tmp_buf header) {\n return parse_header(std::move(header));\n });\n });\n }\n future<> parse_header(tmp_buf header) {\n if (header.size() == 2 && header[0] == '\\r' && header[1] == '\\n') {\n generate_response(std::move(_req));\n read().rescue([this] (auto get_ex) mutable {\n try {\n get_ex();\n } catch (std::exception& ex) {\n std::cout << \"read failed with \" << ex.what() << \"\\n\";\n this->maybe_done();\n }\n });\n return make_ready_future<>();\n }\n size_t pos = 0;\n size_t end = header.size();\n if (end < 2 || header[end-2] != '\\r' || header[end-1] != '\\n') {\n return bad(std::move(_req));\n }\n while (tchar(header[pos])) {\n ++pos;\n }\n if (pos) {\n sstring name = sstring(header.begin(), pos);\n while (pos != end && sp_char(header[pos])) {\n ++pos;\n }\n if (pos == end || header[pos++] != ':') {\n return bad(std::move(_req));\n }\n while (pos != end && sp_char(header[pos])) {\n ++pos;\n }\n while (pos != end && sp_char(header[end-1])) {\n --end;\n }\n sstring value = sstring(header.begin() + pos, end - pos);\n _req->_headers[name] = std::move(value);\n _last_header_name = std::move(name);\n } else {\n while (sp_char(header[pos])) {\n ++pos;\n }\n while (pos != end && sp_char(header[end-1])) {\n --end;\n }\n if (!pos || end == pos) {\n return bad(std::move(_req));\n }\n _req->_headers[_last_header_name] += \" \";\n _req->_headers[_last_header_name] += sstring(header.begin() + pos, end - pos);\n }\n return _read_buf.read_until(limit, '\\n').then([this] (tmp_buf header) {\n return parse_header(std::move(header));\n });\n }\n future<> bad(std::unique_ptr<request> req) {\n auto resp = std::make_unique<response>();\n resp->_response_line = \"HTTP\/1.1 400 BAD REQUEST\\r\\n\\r\\n\";\n respond(std::move(resp));\n _eof = true;\n throw std::runtime_error(\"failed to parse request\");\n }\n void respond(std::unique_ptr<response> resp) {\n if (!_resp) {\n _resp = std::move(resp);\n start_response();\n } else {\n _pending_responses.push(std::move(resp));\n }\n }\n void start_response() {\n _resp->_headers[\"Content-Length\"] = to_sstring(_resp->_body.size());\n _write_buf.write(_resp->_response_line.begin(), _resp->_response_line.size()).then(\n [this] (size_t n) mutable {\n return write_response_headers(_resp->_headers.begin());\n }).then([this] (size_t done) {\n return _write_buf.write(\"\\r\\n\", 2);\n }).then([this] (size_t done) mutable {\n return write_body();\n }).then([this] (size_t done) {\n return _write_buf.flush();\n }).then([this] (bool done) {\n _resp.reset();\n if (!_pending_responses.empty()) {\n _resp = std::move(_pending_responses.front());\n _pending_responses.pop();\n start_response();\n } else {\n maybe_done();\n }\n });\n }\n future<size_t> write_response_headers(std::unordered_map<sstring, sstring>::iterator hi) {\n if (hi == _resp->_headers.end()) {\n return make_ready_future<size_t>(0);\n }\n return _write_buf.write(hi->first.begin(), hi->first.size()).then(\n [hi, this] (size_t done) mutable {\n return _write_buf.write(\": \", 2);\n }).then([hi, this] (size_t done) mutable {\n return _write_buf.write(hi->second.begin(), hi->second.size());\n }).then([hi, this] (size_t done) mutable {\n return _write_buf.write(\"\\r\\n\", 2);\n }).then([hi, this] (size_t done) mutable {\n return write_response_headers(++hi);\n });\n }\n void generate_response(std::unique_ptr<request> req) {\n auto resp = std::make_unique<response>();\n resp->_response_line = \"HTTP\/1.1 200 OK\\r\\n\";\n resp->_headers[\"Content-Type\"] = \"text\/html\";\n resp->_body = \"<html><head><title>this is the future<\/title><\/head><body><p>Future!!<\/p><\/body><\/html>\";\n respond(std::move(resp));\n }\n future<size_t> write_body() {\n return _write_buf.write(_resp->_body.begin(), _resp->_body.size());\n }\n void maybe_done() {\n if (_eof && !_req && !_resp && _pending_responses.empty()) {\n delete this;\n }\n }\n };\n};\n\nint main(int ac, char** av) {\n http_server server;\n namespace bpo = boost::program_options;\n bpo::options_description opts;\n opts.add_options()\n (\"help\", \"show help message\")\n ;\n opts.add(reactor::get_options_description());\n opts.add(smp::get_options_description());\n bpo::variables_map configuration;\n bpo::store(bpo::command_line_parser(ac, av).options(opts).run(), configuration);\n bpo::notify(configuration);\n if (configuration.count(\"help\")) {\n std::cout << opts << \"\\n\";\n return 1;\n }\n smp::configure(configuration);\n engine.when_started().then([&server] {\n uint16_t port = 10000;\n std::cout << \"Seastar HTTP server listening on port \" << port << \" ...\\n\";\n server.listen({{}, port});\n });\n engine.run();\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ INTEL CORPORATION PROPRIETARY INFORMATION\r\n\/\/\r\n\/\/ This software is supplied under the terms of a license agreement or\r\n\/\/ nondisclosure agreement with Intel Corporation and may not be copied\r\n\/\/ or disclosed except in accordance with the terms of that agreement.\r\n\/\/ Copyright (C) 2014 Intel Corporation. All Rights Reserved.\r\n\/\/\r\n\r\n#include <algorithm>\r\n#include \"VolumeViewer.h\"\r\n#include \"TransferFunctionEditor.h\"\r\n#include \"LightEditor.h\"\r\n#include \"SliceWidget.h\"\r\n#include \"PLYGeometryFile.h\"\r\n\r\nVolumeViewer::VolumeViewer(const std::vector<std::string> &filenames, bool showFrameRate) : renderer(NULL), transferFunction(NULL), osprayWindow(NULL), autoRotationRate(0.025f) {\r\n\r\n \/\/! Default window size.\r\n resize(1024, 768);\r\n\r\n \/\/! Create an OSPRay renderer.\r\n renderer = ospNewRenderer(\"raycast_volume_renderer\"); exitOnCondition(renderer == NULL, \"could not create OSPRay renderer object\");\r\n\r\n \/\/! Create an OSPRay window and set it as the central widget, but don't let it start rendering until we're done with setup.\r\n osprayWindow = new QOSPRayWindow(this, renderer, showFrameRate); setCentralWidget(osprayWindow);\r\n\r\n \/\/! Set the window bounds based on the OSPRay world bounds (always [(0,0,0), (1,1,1)) for volumes).\r\n osprayWindow->setWorldBounds(osp::box3f(osp::vec3f(0.0f), osp::vec3f(1.0f)));\r\n\r\n \/\/! Create an OSPRay light source.\r\n light = ospNewLight(NULL, \"DirectionalLight\"); ospSet3f(light, \"direction\", 1.0f, -2.0f, -1.0f); ospSet3f(light, \"color\", 1.0f, 1.0f, 1.0f);\r\n\r\n \/\/! Set the light source on the renderer.\r\n ospCommit(light); ospSetData(renderer, \"lights\", ospNewData(1, OSP_OBJECT, &light));\r\n\r\n \/\/! Create an OSPRay transfer function.\r\n transferFunction = ospNewTransferFunction(\"piecewise_linear\"); exitOnCondition(transferFunction == NULL, \"could not create OSPRay transfer function object\");\r\n\r\n \/\/! Configure the user interface widgets and callbacks.\r\n initUserInterfaceWidgets();\r\n\r\n \/\/! Commit the transfer function only after the initial colors and alphas have been set (workaround for Qt signalling issue).\r\n ospCommit(transferFunction);\r\n\r\n \/\/! Create and configure the OSPRay state.\r\n initObjects(filenames);\r\n\r\n \/\/! Show the window.\r\n show();\r\n\r\n}\r\n\r\nvoid VolumeViewer::autoRotate(bool set) {\r\n\r\n if(osprayWindow == NULL)\r\n return;\r\n\r\n if(autoRotateAction != NULL)\r\n autoRotateAction->setChecked(set);\r\n\r\n if(set) {\r\n osprayWindow->setRotationRate(autoRotationRate);\r\n osprayWindow->updateGL();\r\n }\r\n else {\r\n osprayWindow->setRotationRate(0.);\r\n }\r\n}\r\n\r\nvoid VolumeViewer::addSlice(std::string filename) {\r\n\r\n \/\/! Use dynamic geometry model for slices.\r\n std::vector<OSPModel> dynamicModels;\r\n dynamicModels.push_back(dynamicModel);\r\n\r\n \/\/! Create a slice widget and add it to the dock. This widget modifies the slice directly.\r\n SliceWidget * sliceWidget = new SliceWidget(dynamicModels, osp::box3f(osp::vec3f(0.0f), osp::vec3f(1.0f)));\r\n connect(sliceWidget, SIGNAL(sliceChanged()), this, SLOT(render()));\r\n sliceWidgetsLayout.addWidget(sliceWidget);\r\n\r\n \/\/! Load state from file if specified.\r\n if(!filename.empty())\r\n sliceWidget->load(filename);\r\n}\r\n\r\nvoid VolumeViewer::addGeometry(std::string filename) {\r\n\r\n \/\/! For now we assume PLY geometry files. Later we can support other geometry formats.\r\n\r\n \/\/! Get filename if not specified.\r\n if(filename.empty())\r\n filename = QFileDialog::getOpenFileName(this, tr(\"Load geometry\"), \".\", \"PLY files (*.ply)\").toStdString();\r\n\r\n if(filename.empty())\r\n return;\r\n\r\n \/\/! Load the geometry.\r\n PLYGeometryFile geometryFile(filename);\r\n\r\n \/\/! Add the OSPRay triangle mesh to all models.\r\n OSPTriangleMesh triangleMesh = geometryFile.getOSPTriangleMesh();\r\n\r\n for(unsigned int i=0; i<models.size(); i++) {\r\n ospAddGeometry(models[i], triangleMesh);\r\n ospCommit(models[i]);\r\n }\r\n}\r\n\r\nvoid VolumeViewer::importObjectsFromFile(const std::string &filename) {\r\n\r\n \/\/! Create an OSPRay model.\r\n OSPModel model = ospNewModel();\r\n\r\n \/\/! Load OSPRay objects from a file.\r\n OSPObjectCatalog catalog = ospImportObjects(filename.c_str());\r\n\r\n \/\/! For now we set the same transfer function on all volumes.\r\n for (size_t i=0 ; catalog->entries[i] ; i++) if (catalog->entries[i]->type == OSP_VOLUME) ospSetObject(catalog->entries[i]->object, \"transferFunction\", transferFunction);\r\n\r\n \/\/! Add the loaded volume(s) to the model.\r\n for (size_t i=0 ; catalog->entries[i] ; i++) if (catalog->entries[i]->type == OSP_VOLUME) ospAddVolume(model, (OSPVolume) catalog->entries[i]->object);\r\n\r\n \/\/! Keep vector of all loaded volume(s).\r\n for (size_t i=0 ; catalog->entries[i] ; i++) if (catalog->entries[i]->type == OSP_VOLUME) volumes.push_back((OSPVolume) catalog->entries[i]->object);\r\n\r\n \/\/! Commit the OSPRay object state.\r\n ospCommitCatalog(catalog); ospCommit(model); models.push_back(model);\r\n\r\n}\r\n\r\nvoid VolumeViewer::initObjects(const std::vector<std::string> &filenames) {\r\n\r\n \/\/! Create model for dynamic geometry.\r\n dynamicModel = ospNewModel();\r\n ospCommit(dynamicModel);\r\n\r\n \/\/! Set the dynamic model on the renderer.\r\n ospSetObject(renderer, \"dynamic_model\", dynamicModel);\r\n\r\n \/\/! Load OSPRay objects from files.\r\n for (size_t i=0 ; i < filenames.size() ; i++) importObjectsFromFile(filenames[i]);\r\n\r\n}\r\n\r\nvoid VolumeViewer::initUserInterfaceWidgets() {\r\n\r\n \/\/! Add the \"auto rotate\" widget and callback.\r\n QToolBar *toolbar = addToolBar(\"toolbar\");\r\n autoRotateAction = new QAction(\"Auto rotate\", this);\r\n autoRotateAction->setCheckable(true);\r\n connect(autoRotateAction, SIGNAL(toggled(bool)), this, SLOT(autoRotate(bool)));\r\n toolbar->addAction(autoRotateAction);\r\n\r\n \/\/! Add the \"next timestep\" widget and callback.\r\n QAction *nextTimeStepAction = new QAction(\"Next timestep\", this);\r\n connect(nextTimeStepAction, SIGNAL(triggered()), this, SLOT(nextTimeStep()));\r\n toolbar->addAction(nextTimeStepAction);\r\n\r\n \/\/! Add the \"play timesteps\" widget and callback.\r\n QAction *playTimeStepsAction = new QAction(\"Play timesteps\", this);\r\n playTimeStepsAction->setCheckable(true);\r\n connect(playTimeStepsAction, SIGNAL(toggled(bool)), this, SLOT(playTimeSteps(bool)));\r\n toolbar->addAction(playTimeStepsAction);\r\n\r\n \/\/! Connect the \"play timesteps\" timer.\r\n connect(&playTimeStepsTimer, SIGNAL(timeout()), this, SLOT(nextTimeStep()));\r\n\r\n \/\/! Add the \"add slice\" widget and callback.\r\n QAction *addSliceAction = new QAction(\"Add slice\", this);\r\n connect(addSliceAction, SIGNAL(triggered()), this, SLOT(addSlice()));\r\n toolbar->addAction(addSliceAction);\r\n\r\n \/\/! Add the \"add geometry\" widget and callback.\r\n QAction *addGeometryAction = new QAction(\"Add geometry\", this);\r\n connect(addGeometryAction, SIGNAL(triggered()), this, SLOT(addGeometry()));\r\n toolbar->addAction(addGeometryAction);\r\n\r\n \/\/! Create the transfer function editor dock widget, this widget modifies the transfer function directly.\r\n QDockWidget *transferFunctionEditorDockWidget = new QDockWidget(\"Transfer Function Editor\", this);\r\n transferFunctionEditor = new TransferFunctionEditor(transferFunction);\r\n transferFunctionEditorDockWidget->setWidget(transferFunctionEditor);\r\n connect(transferFunctionEditor, SIGNAL(transferFunctionChanged()), this, SLOT(commitVolumes()));\r\n connect(transferFunctionEditor, SIGNAL(transferFunctionChanged()), this, SLOT(render()));\r\n addDockWidget(Qt::LeftDockWidgetArea, transferFunctionEditorDockWidget);\r\n\r\n \/\/! Set the transfer function editor widget to its minimum allowed height, to leave room for other dock widgets.\r\n transferFunctionEditor->setMaximumHeight(transferFunctionEditor->minimumSize().height());\r\n\r\n \/\/! Create the light editor dock widget, this widget modifies the light directly.\r\n QDockWidget *lightEditorDockWidget = new QDockWidget(\"Light Editor\", this);\r\n LightEditor *lightEditor = new LightEditor(light);\r\n lightEditorDockWidget->setWidget(lightEditor);\r\n connect(lightEditor, SIGNAL(lightChanged()), this, SLOT(render()));\r\n addDockWidget(Qt::LeftDockWidgetArea, lightEditorDockWidget);\r\n\r\n \/\/! Create a scrollable dock widget for any added slices.\r\n QDockWidget *slicesDockWidget = new QDockWidget(\"Slices\", this);\r\n QScrollArea *slicesScrollArea = new QScrollArea();\r\n QWidget *slicesWidget = new QWidget();\r\n slicesWidget->setLayout(&sliceWidgetsLayout);\r\n slicesScrollArea->setWidget(slicesWidget);\r\n slicesScrollArea->setWidgetResizable(true);\r\n slicesDockWidget->setWidget(slicesScrollArea);\r\n addDockWidget(Qt::LeftDockWidgetArea, slicesDockWidget);\r\n\r\n}\r\n<commit_msg>disabling light editor widget in volume viewer, pending UI improvements.<commit_after>\/\/\r\n\/\/ INTEL CORPORATION PROPRIETARY INFORMATION\r\n\/\/\r\n\/\/ This software is supplied under the terms of a license agreement or\r\n\/\/ nondisclosure agreement with Intel Corporation and may not be copied\r\n\/\/ or disclosed except in accordance with the terms of that agreement.\r\n\/\/ Copyright (C) 2014 Intel Corporation. All Rights Reserved.\r\n\/\/\r\n\r\n#include <algorithm>\r\n#include \"VolumeViewer.h\"\r\n#include \"TransferFunctionEditor.h\"\r\n#include \"LightEditor.h\"\r\n#include \"SliceWidget.h\"\r\n#include \"PLYGeometryFile.h\"\r\n\r\nVolumeViewer::VolumeViewer(const std::vector<std::string> &filenames, bool showFrameRate) : renderer(NULL), transferFunction(NULL), osprayWindow(NULL), autoRotationRate(0.025f) {\r\n\r\n \/\/! Default window size.\r\n resize(1024, 768);\r\n\r\n \/\/! Create an OSPRay renderer.\r\n renderer = ospNewRenderer(\"raycast_volume_renderer\"); exitOnCondition(renderer == NULL, \"could not create OSPRay renderer object\");\r\n\r\n \/\/! Create an OSPRay window and set it as the central widget, but don't let it start rendering until we're done with setup.\r\n osprayWindow = new QOSPRayWindow(this, renderer, showFrameRate); setCentralWidget(osprayWindow);\r\n\r\n \/\/! Set the window bounds based on the OSPRay world bounds (always [(0,0,0), (1,1,1)) for volumes).\r\n osprayWindow->setWorldBounds(osp::box3f(osp::vec3f(0.0f), osp::vec3f(1.0f)));\r\n\r\n \/\/! Create an OSPRay light source.\r\n light = ospNewLight(NULL, \"DirectionalLight\"); ospSet3f(light, \"direction\", 1.0f, -2.0f, -1.0f); ospSet3f(light, \"color\", 1.0f, 1.0f, 1.0f);\r\n\r\n \/\/! Set the light source on the renderer.\r\n ospCommit(light); ospSetData(renderer, \"lights\", ospNewData(1, OSP_OBJECT, &light));\r\n\r\n \/\/! Create an OSPRay transfer function.\r\n transferFunction = ospNewTransferFunction(\"piecewise_linear\"); exitOnCondition(transferFunction == NULL, \"could not create OSPRay transfer function object\");\r\n\r\n \/\/! Configure the user interface widgets and callbacks.\r\n initUserInterfaceWidgets();\r\n\r\n \/\/! Commit the transfer function only after the initial colors and alphas have been set (workaround for Qt signalling issue).\r\n ospCommit(transferFunction);\r\n\r\n \/\/! Create and configure the OSPRay state.\r\n initObjects(filenames);\r\n\r\n \/\/! Show the window.\r\n show();\r\n\r\n}\r\n\r\nvoid VolumeViewer::autoRotate(bool set) {\r\n\r\n if(osprayWindow == NULL)\r\n return;\r\n\r\n if(autoRotateAction != NULL)\r\n autoRotateAction->setChecked(set);\r\n\r\n if(set) {\r\n osprayWindow->setRotationRate(autoRotationRate);\r\n osprayWindow->updateGL();\r\n }\r\n else {\r\n osprayWindow->setRotationRate(0.);\r\n }\r\n}\r\n\r\nvoid VolumeViewer::addSlice(std::string filename) {\r\n\r\n \/\/! Use dynamic geometry model for slices.\r\n std::vector<OSPModel> dynamicModels;\r\n dynamicModels.push_back(dynamicModel);\r\n\r\n \/\/! Create a slice widget and add it to the dock. This widget modifies the slice directly.\r\n SliceWidget * sliceWidget = new SliceWidget(dynamicModels, osp::box3f(osp::vec3f(0.0f), osp::vec3f(1.0f)));\r\n connect(sliceWidget, SIGNAL(sliceChanged()), this, SLOT(render()));\r\n sliceWidgetsLayout.addWidget(sliceWidget);\r\n\r\n \/\/! Load state from file if specified.\r\n if(!filename.empty())\r\n sliceWidget->load(filename);\r\n}\r\n\r\nvoid VolumeViewer::addGeometry(std::string filename) {\r\n\r\n \/\/! For now we assume PLY geometry files. Later we can support other geometry formats.\r\n\r\n \/\/! Get filename if not specified.\r\n if(filename.empty())\r\n filename = QFileDialog::getOpenFileName(this, tr(\"Load geometry\"), \".\", \"PLY files (*.ply)\").toStdString();\r\n\r\n if(filename.empty())\r\n return;\r\n\r\n \/\/! Load the geometry.\r\n PLYGeometryFile geometryFile(filename);\r\n\r\n \/\/! Add the OSPRay triangle mesh to all models.\r\n OSPTriangleMesh triangleMesh = geometryFile.getOSPTriangleMesh();\r\n\r\n for(unsigned int i=0; i<models.size(); i++) {\r\n ospAddGeometry(models[i], triangleMesh);\r\n ospCommit(models[i]);\r\n }\r\n}\r\n\r\nvoid VolumeViewer::importObjectsFromFile(const std::string &filename) {\r\n\r\n \/\/! Create an OSPRay model.\r\n OSPModel model = ospNewModel();\r\n\r\n \/\/! Load OSPRay objects from a file.\r\n OSPObjectCatalog catalog = ospImportObjects(filename.c_str());\r\n\r\n \/\/! For now we set the same transfer function on all volumes.\r\n for (size_t i=0 ; catalog->entries[i] ; i++) if (catalog->entries[i]->type == OSP_VOLUME) ospSetObject(catalog->entries[i]->object, \"transferFunction\", transferFunction);\r\n\r\n \/\/! Add the loaded volume(s) to the model.\r\n for (size_t i=0 ; catalog->entries[i] ; i++) if (catalog->entries[i]->type == OSP_VOLUME) ospAddVolume(model, (OSPVolume) catalog->entries[i]->object);\r\n\r\n \/\/! Keep vector of all loaded volume(s).\r\n for (size_t i=0 ; catalog->entries[i] ; i++) if (catalog->entries[i]->type == OSP_VOLUME) volumes.push_back((OSPVolume) catalog->entries[i]->object);\r\n\r\n \/\/! Commit the OSPRay object state.\r\n ospCommitCatalog(catalog); ospCommit(model); models.push_back(model);\r\n\r\n}\r\n\r\nvoid VolumeViewer::initObjects(const std::vector<std::string> &filenames) {\r\n\r\n \/\/! Create model for dynamic geometry.\r\n dynamicModel = ospNewModel();\r\n ospCommit(dynamicModel);\r\n\r\n \/\/! Set the dynamic model on the renderer.\r\n ospSetObject(renderer, \"dynamic_model\", dynamicModel);\r\n\r\n \/\/! Load OSPRay objects from files.\r\n for (size_t i=0 ; i < filenames.size() ; i++) importObjectsFromFile(filenames[i]);\r\n\r\n}\r\n\r\nvoid VolumeViewer::initUserInterfaceWidgets() {\r\n\r\n \/\/! Add the \"auto rotate\" widget and callback.\r\n QToolBar *toolbar = addToolBar(\"toolbar\");\r\n autoRotateAction = new QAction(\"Auto rotate\", this);\r\n autoRotateAction->setCheckable(true);\r\n connect(autoRotateAction, SIGNAL(toggled(bool)), this, SLOT(autoRotate(bool)));\r\n toolbar->addAction(autoRotateAction);\r\n\r\n \/\/! Add the \"next timestep\" widget and callback.\r\n QAction *nextTimeStepAction = new QAction(\"Next timestep\", this);\r\n connect(nextTimeStepAction, SIGNAL(triggered()), this, SLOT(nextTimeStep()));\r\n toolbar->addAction(nextTimeStepAction);\r\n\r\n \/\/! Add the \"play timesteps\" widget and callback.\r\n QAction *playTimeStepsAction = new QAction(\"Play timesteps\", this);\r\n playTimeStepsAction->setCheckable(true);\r\n connect(playTimeStepsAction, SIGNAL(toggled(bool)), this, SLOT(playTimeSteps(bool)));\r\n toolbar->addAction(playTimeStepsAction);\r\n\r\n \/\/! Connect the \"play timesteps\" timer.\r\n connect(&playTimeStepsTimer, SIGNAL(timeout()), this, SLOT(nextTimeStep()));\r\n\r\n \/\/! Add the \"add slice\" widget and callback.\r\n QAction *addSliceAction = new QAction(\"Add slice\", this);\r\n connect(addSliceAction, SIGNAL(triggered()), this, SLOT(addSlice()));\r\n toolbar->addAction(addSliceAction);\r\n\r\n \/\/! Add the \"add geometry\" widget and callback.\r\n QAction *addGeometryAction = new QAction(\"Add geometry\", this);\r\n connect(addGeometryAction, SIGNAL(triggered()), this, SLOT(addGeometry()));\r\n toolbar->addAction(addGeometryAction);\r\n\r\n \/\/! Create the transfer function editor dock widget, this widget modifies the transfer function directly.\r\n QDockWidget *transferFunctionEditorDockWidget = new QDockWidget(\"Transfer Function Editor\", this);\r\n transferFunctionEditor = new TransferFunctionEditor(transferFunction);\r\n transferFunctionEditorDockWidget->setWidget(transferFunctionEditor);\r\n connect(transferFunctionEditor, SIGNAL(transferFunctionChanged()), this, SLOT(commitVolumes()));\r\n connect(transferFunctionEditor, SIGNAL(transferFunctionChanged()), this, SLOT(render()));\r\n addDockWidget(Qt::LeftDockWidgetArea, transferFunctionEditorDockWidget);\r\n\r\n \/\/! Set the transfer function editor widget to its minimum allowed height, to leave room for other dock widgets.\r\n transferFunctionEditor->setMaximumHeight(transferFunctionEditor->minimumSize().height());\r\n\r\n \/\/! Create the light editor dock widget, this widget modifies the light directly.\r\n \/\/! Disable for now pending UI improvements...\r\n \/* QDockWidget *lightEditorDockWidget = new QDockWidget(\"Light Editor\", this);\r\n LightEditor *lightEditor = new LightEditor(light);\r\n lightEditorDockWidget->setWidget(lightEditor);\r\n connect(lightEditor, SIGNAL(lightChanged()), this, SLOT(render()));\r\n addDockWidget(Qt::LeftDockWidgetArea, lightEditorDockWidget); *\/\r\n\r\n \/\/! Create a scrollable dock widget for any added slices.\r\n QDockWidget *slicesDockWidget = new QDockWidget(\"Slices\", this);\r\n QScrollArea *slicesScrollArea = new QScrollArea();\r\n QWidget *slicesWidget = new QWidget();\r\n slicesWidget->setLayout(&sliceWidgetsLayout);\r\n slicesScrollArea->setWidget(slicesWidget);\r\n slicesScrollArea->setWidgetResizable(true);\r\n slicesDockWidget->setWidget(slicesScrollArea);\r\n addDockWidget(Qt::LeftDockWidgetArea, slicesDockWidget);\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ik_module.hxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: np $ $Date: 2002-11-01 17:11:59 $\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 ARY_IDL_IK_MODULE_HXX\n#define ARY_IDL_IK_MODULE_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include <ary\/idl\/ik_ce.hxx>\n \/\/ COMPONENTS\n \/\/ PARAMETERS\n\n\nnamespace ary\n{\nnamespace idl\n{\n\nclass CePilot;\n\nnamespace ifc_module\n{\n\nusing ifc_ce::Dyn_CeIterator;\nusing ifc_ce::DocText;\n\n\nstruct attr : public ifc_ce::attr\n{\n \/\/ KORR\n \/\/ This has to be changed that way, that the differencing takes place\n \/\/ within hfi_module.cxx and not here.\n \/\/ So the class CePilot is not needed here, etc.\n \/\/ Too much scope pollution.\n static void Get_AllChildrenSeparated(\n std::vector< const CodeEntity* > & o_nestedModules,\n std::vector< const CodeEntity* > & o_services,\n std::vector< const CodeEntity* > & o_interfaces,\n std::vector< const CodeEntity* > & o_structs,\n std::vector< const CodeEntity* > & o_exceptions,\n std::vector< const CodeEntity* > & o_enums,\n std::vector< const CodeEntity* > & o_typedefs,\n std::vector< const CodeEntity* > & o_constantGroups,\n std::vector< const CodeEntity* > & o_singletons,\n const CePilot & i_pilot,\n const CodeEntity & i_ce );\n\n static void Get_SubModules(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Services(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Interfaces(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Structs(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Exceptions(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Enums(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Typedefs(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_ConstantsGroups(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n};\n\nstruct xref : public ifc_ce::xref\n{\n};\n\nstruct doc : public ifc_ce::doc\n{\n};\n\n} \/\/ namespace ifc_module\n\n} \/\/ namespace idl\n} \/\/ namespace ary\n\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.1.132); FILE MERGED 2005\/09\/05 13:09:26 rt 1.1.132.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ik_module.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 16:16:18 $\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 ARY_IDL_IK_MODULE_HXX\n#define ARY_IDL_IK_MODULE_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include <ary\/idl\/ik_ce.hxx>\n \/\/ COMPONENTS\n \/\/ PARAMETERS\n\n\nnamespace ary\n{\nnamespace idl\n{\n\nclass CePilot;\n\nnamespace ifc_module\n{\n\nusing ifc_ce::Dyn_CeIterator;\nusing ifc_ce::DocText;\n\n\nstruct attr : public ifc_ce::attr\n{\n \/\/ KORR\n \/\/ This has to be changed that way, that the differencing takes place\n \/\/ within hfi_module.cxx and not here.\n \/\/ So the class CePilot is not needed here, etc.\n \/\/ Too much scope pollution.\n static void Get_AllChildrenSeparated(\n std::vector< const CodeEntity* > & o_nestedModules,\n std::vector< const CodeEntity* > & o_services,\n std::vector< const CodeEntity* > & o_interfaces,\n std::vector< const CodeEntity* > & o_structs,\n std::vector< const CodeEntity* > & o_exceptions,\n std::vector< const CodeEntity* > & o_enums,\n std::vector< const CodeEntity* > & o_typedefs,\n std::vector< const CodeEntity* > & o_constantGroups,\n std::vector< const CodeEntity* > & o_singletons,\n const CePilot & i_pilot,\n const CodeEntity & i_ce );\n\n static void Get_SubModules(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Services(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Interfaces(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Structs(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Exceptions(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Enums(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_Typedefs(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n static void Get_ConstantsGroups(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n};\n\nstruct xref : public ifc_ce::xref\n{\n};\n\nstruct doc : public ifc_ce::doc\n{\n};\n\n} \/\/ namespace ifc_module\n\n} \/\/ namespace idl\n} \/\/ namespace ary\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/context.hpp\"\n#include \"flusspferd\/object.hpp\"\n#include \"flusspferd\/exception.hpp\"\n#include \"flusspferd\/local_root_scope.hpp\"\n#include \"flusspferd\/spidermonkey\/context.hpp\"\n#include \"flusspferd\/spidermonkey\/value.hpp\"\n#include \"flusspferd\/spidermonkey\/object.hpp\"\n#include \"flusspferd\/spidermonkey\/runtime.hpp\"\n#include \"flusspferd\/current_context_scope.hpp\"\n#include <boost\/unordered_map.hpp>\n#include <cstring>\n#include <cstdio>\n#include <js\/jsapi.h>\n\n#ifndef FLUSSPFERD_STACKCHUNKSIZE\n#define FLUSSPFERD_STACKCHUNKSIZE 8192\n#endif\n\nusing namespace flusspferd;\n\nnamespace {\n static JSClass global_class = {\n \"global\", JSCLASS_GLOBAL_FLAGS,\n JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,\n JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,\n JSCLASS_NO_OPTIONAL_MEMBERS\n };\n}\n\nstruct context::context_private {\n typedef boost::shared_ptr<root_object> root_object_ptr;\n boost::unordered_map<std::string, root_object_ptr> prototypes;\n boost::unordered_map<std::string, root_object_ptr> constructors;\n};\n\nclass context::impl {\npublic:\n impl()\n : context(JS_NewContext(Impl::get_runtime(),\n FLUSSPFERD_STACKCHUNKSIZE)),\n destroy(true)\n {\n if(!context)\n throw exception(\"Could not create Spidermonkey Context\");\n\n uint32 options = JS_GetOptions(context);\n\n options |= JSOPTION_VAROBJFIX;\n options |= JSOPTION_DONT_REPORT_UNCAUGHT;\n options &= ~JSOPTION_XML;\n\n JS_SetVersion(context, JSVersion(JS_VERSION));\n JS_SetOptions(context, options);\n\n JS_BeginRequest(context);\n\n JSObject *global_ = JS_NewObject(context, &global_class, 0x0, 0x0);\n if(!global_)\n throw exception(\"Could not create Global Object\");\n\n JS_SetGlobalObject(context, global_);\n\n if(!JS_InitStandardClasses(context, global_))\n throw exception(\"Could not initialize Global Object\");\n\n JS_DeleteProperty(context, global_, \"XML\");\n\n JS_SetContextPrivate(context, static_cast<void*>(new context_private));\n }\n\n explicit impl(JSContext *context)\n : context(context), destroy(false)\n { }\n\n ~impl() {\n if (destroy) {\n {\n current_context_scope scope(Impl::wrap_context(context));\n delete get_private();\n JS_DestroyContext(context);\n }\n }\n }\n\n bool is_valid() {\n return context;\n }\n\n context_private *get_private() {\n return static_cast<context_private*>(JS_GetContextPrivate(context));\n }\n\n JSContext *context;\n bool destroy;\n};\n\nstruct context::detail {\n JSContext *c;\n detail(JSContext *ct) : c(ct) { }\n\n static JSContext *get(context &co) {\n return co.p->context;\n }\n};\n\nJSContext *Impl::get_context(context &co) {\n return context::detail::get(co);\n}\n\ncontext Impl::wrap_context(JSContext *c) {\n return context(c);\n}\n\ncontext::context()\n{ }\ncontext::context(context::detail const &d)\n : p(new impl(d.c))\n{\n if (!p->is_valid())\n p.reset();\n}\ncontext::~context() { }\n\ncontext context::create() {\n context c;\n c.p.reset(new impl);\n return c;\n}\n\nbool context::is_valid() const {\n return p;\n}\n\nobject context::global() {\n return Impl::wrap_object(JS_GetGlobalObject(p->context));\n}\n\nobject context::scope_chain() {\n return Impl::wrap_object(JS_GetScopeChain(p->context));\n}\n\nvoid context::add_prototype(std::string const &name, object const &proto) {\n p->get_private()->prototypes[name] =\n context_private::root_object_ptr(new root_object(proto));\n}\n\nobject context::prototype(std::string const &name) const {\n context_private::root_object_ptr ptr = p->get_private()->prototypes[name];\n return ptr ? *ptr : object();\n}\n\nvoid context::add_constructor(std::string const &name, object const &ctor) {\n p->get_private()->constructors[name] =\n context_private::root_object_ptr(new root_object(ctor));\n}\n\nobject context::constructor(std::string const &name) const {\n context_private::root_object_ptr ptr = p->get_private()->constructors[name];\n return ptr ? *ptr : object();\n}\n\nvoid context::gc() {\n JS_GC(p->context);\n}\n<commit_msg>fix bug where flusspferd did not compile if JS_THREADSAFE was not enabled in spidermonkey<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/context.hpp\"\n#include \"flusspferd\/object.hpp\"\n#include \"flusspferd\/exception.hpp\"\n#include \"flusspferd\/local_root_scope.hpp\"\n#include \"flusspferd\/spidermonkey\/context.hpp\"\n#include \"flusspferd\/spidermonkey\/value.hpp\"\n#include \"flusspferd\/spidermonkey\/object.hpp\"\n#include \"flusspferd\/spidermonkey\/runtime.hpp\"\n#include \"flusspferd\/current_context_scope.hpp\"\n#include <boost\/unordered_map.hpp>\n#include <cstring>\n#include <cstdio>\n#include <js\/jsapi.h>\n\n#ifndef FLUSSPFERD_STACKCHUNKSIZE\n#define FLUSSPFERD_STACKCHUNKSIZE 8192\n#endif\n\nusing namespace flusspferd;\n\nnamespace {\n static JSClass global_class = {\n \"global\", JSCLASS_GLOBAL_FLAGS,\n JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,\n JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,\n JSCLASS_NO_OPTIONAL_MEMBERS\n };\n}\n\nstruct context::context_private {\n typedef boost::shared_ptr<root_object> root_object_ptr;\n boost::unordered_map<std::string, root_object_ptr> prototypes;\n boost::unordered_map<std::string, root_object_ptr> constructors;\n};\n\nclass context::impl {\npublic:\n impl()\n : context(JS_NewContext(Impl::get_runtime(),\n FLUSSPFERD_STACKCHUNKSIZE)),\n destroy(true)\n {\n if(!context)\n throw exception(\"Could not create Spidermonkey Context\");\n\n uint32 options = JS_GetOptions(context);\n\n options |= JSOPTION_VAROBJFIX;\n options |= JSOPTION_DONT_REPORT_UNCAUGHT;\n options &= ~JSOPTION_XML;\n\n JS_SetVersion(context, JSVersion(JS_VERSION));\n JS_SetOptions(context, options);\n\n#ifdef JS_THREADSAFE\n JS_BeginRequest(context);\n#endif\n\n JSObject *global_ = JS_NewObject(context, &global_class, 0x0, 0x0);\n if(!global_)\n throw exception(\"Could not create Global Object\");\n\n JS_SetGlobalObject(context, global_);\n\n if(!JS_InitStandardClasses(context, global_))\n throw exception(\"Could not initialize Global Object\");\n\n JS_DeleteProperty(context, global_, \"XML\");\n\n JS_SetContextPrivate(context, static_cast<void*>(new context_private));\n }\n\n explicit impl(JSContext *context)\n : context(context), destroy(false)\n { }\n\n ~impl() {\n if (destroy) {\n {\n current_context_scope scope(Impl::wrap_context(context));\n delete get_private();\n JS_DestroyContext(context);\n }\n }\n }\n\n bool is_valid() {\n return context;\n }\n\n context_private *get_private() {\n return static_cast<context_private*>(JS_GetContextPrivate(context));\n }\n\n JSContext *context;\n bool destroy;\n};\n\nstruct context::detail {\n JSContext *c;\n detail(JSContext *ct) : c(ct) { }\n\n static JSContext *get(context &co) {\n return co.p->context;\n }\n};\n\nJSContext *Impl::get_context(context &co) {\n return context::detail::get(co);\n}\n\ncontext Impl::wrap_context(JSContext *c) {\n return context(c);\n}\n\ncontext::context()\n{ }\ncontext::context(context::detail const &d)\n : p(new impl(d.c))\n{\n if (!p->is_valid())\n p.reset();\n}\ncontext::~context() { }\n\ncontext context::create() {\n context c;\n c.p.reset(new impl);\n return c;\n}\n\nbool context::is_valid() const {\n return p;\n}\n\nobject context::global() {\n return Impl::wrap_object(JS_GetGlobalObject(p->context));\n}\n\nobject context::scope_chain() {\n return Impl::wrap_object(JS_GetScopeChain(p->context));\n}\n\nvoid context::add_prototype(std::string const &name, object const &proto) {\n p->get_private()->prototypes[name] =\n context_private::root_object_ptr(new root_object(proto));\n}\n\nobject context::prototype(std::string const &name) const {\n context_private::root_object_ptr ptr = p->get_private()->prototypes[name];\n return ptr ? *ptr : object();\n}\n\nvoid context::add_constructor(std::string const &name, object const &ctor) {\n p->get_private()->constructors[name] =\n context_private::root_object_ptr(new root_object(ctor));\n}\n\nobject context::constructor(std::string const &name) const {\n context_private::root_object_ptr ptr = p->get_private()->constructors[name];\n return ptr ? *ptr : object();\n}\n\nvoid context::gc() {\n JS_GC(p->context);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ai.h\"\n#include <iostream>\n#include <stdlib.h>\n#include <time.h>\n\nusing namespace BWAPI;\nusing namespace Filter;\n\n\/\/ Global variables.\nbool infantryBuildingNeeded;\nbool supplyNeeded;\nbool supplyProviderTypeIsBuilding;\nint infantryBuildingCheckTimer;\nint savingMinerals;\nint supplyCheckTimer;\nRace playerRace;\nstatic int infantryBuildingChecked;\nstatic int supplyChecked;\nUnitType infantryBuilding;\nUnitType infantryType;\nUnitType supplyProviderType;\n\nvoid ai::onEnd(bool isWinner){\n}\n\nvoid ai::onFrame(){\n int frameCount = Broodwar->getFrameCount();\n\n if(!Broodwar->self()\n || frameCount % Broodwar->getLatencyFrames() != 0\n || Broodwar->isPaused()\n || Broodwar->isReplay()){\n return;\n }\n\n int minerals = Broodwar->self()->minerals();\n int supplyTotal = Broodwar->self()->supplyTotal();\n\n if(supplyTotal < 200\n && supplyTotal - Broodwar->self()->supplyUsed() <= 2){\n savingMinerals = 100;\n supplyNeeded = true;\n\n }else{\n savingMinerals = 0;\n supplyNeeded = false;\n }\n\n if(minerals > 200){\n infantryBuildingNeeded = true;\n savingMinerals = 200;\n }\n\n for(auto &unit : Broodwar->self()->getUnits()){\n if(!unit->exists()\n || !unit->isCompleted()\n || unit->isConstructing()\n || unit->isLoaded()\n || unit->isLockedDown()\n || unit->isMaelstrommed()\n || !unit->isPowered()\n || unit->isStasised()\n || unit->isStuck()){\n continue;\n }\n\n \/\/ Setup unit information variables.\n bool unitIsIdle = unit->isIdle();\n UnitType unitType = unit->getType();\n\n \/\/ Handle workers.\n if(unitType.isWorker()){\n \/\/ Handle insufficient supply by building Pylon, building Supply Depot, or training Overlord.\n if(supplyNeeded\n && minerals >= savingMinerals\n && supplyChecked + supplyCheckTimer < frameCount){\n supplyChecked = frameCount;\n\n if(Broodwar->self()->incompleteUnitCount(supplyProviderType) == 0){\n Unit supplyBuilder = unit->getClosestUnit(GetType == supplyProviderType.whatBuilds().first\n && (IsIdle || IsGatheringMinerals)\n && IsOwned);\n\n if(supplyProviderTypeIsBuilding){\n buildBuilding(\n supplyBuilder,\n supplyProviderType\n );\n\n }else{\n supplyBuilder->train(supplyProviderType);\n }\n }\n\n \/\/ Build Barracks\/Gateway\/Spawning Pool.\n }else if(infantryBuildingNeeded\n && minerals >= savingMinerals\n && infantryBuildingChecked + infantryBuildingCheckTimer < frameCount){\n infantryBuildingChecked = frameCount;\n\n if(buildBuilding(\n unit,\n infantryBuilding\n )){\n infantryBuildingNeeded = false;\n savingMinerals = 0;\n }\n\n }else if(unitIsIdle){\n \/\/ Return resources.\n if(unit->isCarryingMinerals()\n || unit->isCarryingGas()){\n unit->returnCargo();\n\n \/\/ Gather resources.\n }else{\n unit->gather(unit->getClosestUnit(IsMineralField || IsRefinery));\n }\n }\n\n }else if(unitIsIdle){\n \/\/ Handle Command Centers, Hatcheries, and Nexuses.\n if(unitType.isResourceDepot()){\n if(minerals >= savingMinerals + 50){\n \/\/ Train workers.\n unit->train(playerRace.getWorker());\n }\n\n \/\/ Handle Barracks and Gateways.\n }else if(unit->canTrain(infantryType)){\n if(minerals >= savingMinerals + 100){\n \/\/ Train Marines and Zealots.\n unit->train(infantryType);\n }\n\n \/\/ Everything else should attack-move scout.\n }else{\n Position position = unit->getPosition();\n position.x += rand() % 501 - 250;\n position.y += rand() % 501 - 250;\n unit->attack(position);\n }\n }\n }\n}\n\nvoid ai::onNukeDetect(BWAPI::Position target){\n}\n\nvoid ai::onPlayerLeft(BWAPI::Player player){\n}\n\nvoid ai::onReceiveText(BWAPI::Player player, std::string text){\n}\n\nvoid ai::onSaveGame(std::string gameName){\n}\n\nvoid ai::onSendText(std::string text){\n Broodwar->sendText(\"%s\", text.c_str());\n}\n\nvoid ai::onStart(){\n Broodwar->setCommandOptimizationLevel(1);\n srand(time(NULL));\n\n \/\/ Setup global variables.\n infantryBuildingChecked = 0;\n infantryBuildingCheckTimer = 2000;\n infantryBuildingNeeded = false;\n playerRace = Broodwar->self()->getRace();\n savingMinerals = 0;\n supplyChecked = 0;\n supplyCheckTimer = 600;\n supplyNeeded = false;\n supplyProviderType = playerRace.getSupplyProvider();\n\n supplyProviderTypeIsBuilding = supplyProviderType.isBuilding();\n\n \/\/ Handle race-specific stuff.\n if(playerRace == Races::Zerg){\n infantryBuilding = UnitTypes::Zerg_Spawning_Pool;\n infantryType = UnitTypes::Zerg_Zergling;\n\n }else if(playerRace == Races::Terran){\n infantryBuilding = UnitTypes::Terran_Barracks;\n infantryType = UnitTypes::Terran_Marine;\n\n }else{\n infantryBuilding = UnitTypes::Protoss_Gateway;\n infantryType = UnitTypes::Protoss_Zealot;\n }\n\n Broodwar->sendText(\"glhf\");\n}\n\nvoid ai::onUnitComplete(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitCreate(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitDestroy(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitDiscover(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitEvade(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitHide(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitMorph(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitRenegade(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitShow(BWAPI::Unit unit){\n}\n\nbool buildBuilding(Unit builder, UnitType building){\n TilePosition targetBuildLocation = Broodwar->getBuildLocation(\n builing,\n builder->getTilePosition()\n );\n\n if(targetBuildLocation){\n return builder->build(\n building,\n targetBuildLocation\n );\n }\n\n return false;\n}\n\n<commit_msg>moved incomplete supply provider check to supply needed check<commit_after>#include \"ai.h\"\n#include <iostream>\n#include <stdlib.h>\n#include <time.h>\n\nusing namespace BWAPI;\nusing namespace Filter;\n\n\/\/ Global variables.\nbool infantryBuildingNeeded;\nbool supplyNeeded;\nbool supplyProviderTypeIsBuilding;\nint infantryBuildingCheckTimer;\nint savingMinerals;\nint supplyCheckTimer;\nRace playerRace;\nstatic int infantryBuildingChecked;\nstatic int supplyChecked;\nUnitType infantryBuilding;\nUnitType infantryType;\nUnitType supplyProviderType;\n\nvoid ai::onEnd(bool isWinner){\n}\n\nvoid ai::onFrame(){\n int frameCount = Broodwar->getFrameCount();\n\n if(!Broodwar->self()\n || frameCount % Broodwar->getLatencyFrames() != 0\n || Broodwar->isPaused()\n || Broodwar->isReplay()){\n return;\n }\n\n int minerals = Broodwar->self()->minerals();\n int supplyTotal = Broodwar->self()->supplyTotal();\n\n if(supplyTotal < 200\n && supplyTotal - Broodwar->self()->supplyUsed() <= 2\n && Broodwar->self()->incompleteUnitCount(supplyProviderType) == 0){\n savingMinerals = 100;\n supplyNeeded = true;\n\n }else{\n savingMinerals = 0;\n supplyNeeded = false;\n }\n\n if(minerals > 200){\n infantryBuildingNeeded = true;\n savingMinerals = 200;\n }\n\n for(auto &unit : Broodwar->self()->getUnits()){\n if(!unit->exists()\n || !unit->isCompleted()\n || unit->isConstructing()\n || unit->isLoaded()\n || unit->isLockedDown()\n || unit->isMaelstrommed()\n || !unit->isPowered()\n || unit->isStasised()\n || unit->isStuck()){\n continue;\n }\n\n \/\/ Setup unit information variables.\n bool unitIsIdle = unit->isIdle();\n UnitType unitType = unit->getType();\n\n \/\/ Handle workers.\n if(unitType.isWorker()){\n \/\/ Handle insufficient supply by building Pylon, building Supply Depot, or training Overlord.\n if(supplyNeeded\n && minerals >= savingMinerals\n && supplyChecked + supplyCheckTimer < frameCount){\n supplyChecked = frameCount;\n\n Unit supplyBuilder = unit->getClosestUnit(GetType == supplyProviderType.whatBuilds().first\n && (IsIdle || IsGatheringMinerals)\n && IsOwned);\n\n if(supplyProviderTypeIsBuilding){\n buildBuilding(\n supplyBuilder,\n supplyProviderType\n );\n\n }else{\n supplyBuilder->train(supplyProviderType);\n }\n\n \/\/ Build Barracks\/Gateway\/Spawning Pool.\n }else if(infantryBuildingNeeded\n && minerals >= savingMinerals\n && infantryBuildingChecked + infantryBuildingCheckTimer < frameCount){\n infantryBuildingChecked = frameCount;\n\n if(buildBuilding(\n unit,\n infantryBuilding\n )){\n infantryBuildingNeeded = false;\n savingMinerals = 0;\n }\n\n }else if(unitIsIdle){\n \/\/ Return resources.\n if(unit->isCarryingMinerals()\n || unit->isCarryingGas()){\n unit->returnCargo();\n\n \/\/ Gather resources.\n }else{\n unit->gather(unit->getClosestUnit(IsMineralField || IsRefinery));\n }\n }\n\n }else if(unitIsIdle){\n \/\/ Handle Command Centers, Hatcheries, and Nexuses.\n if(unitType.isResourceDepot()){\n if(minerals >= savingMinerals + 50){\n \/\/ Train workers.\n unit->train(playerRace.getWorker());\n }\n\n \/\/ Handle Barracks and Gateways.\n }else if(unit->canTrain(infantryType)){\n if(minerals >= savingMinerals + 100){\n \/\/ Train Marines and Zealots.\n unit->train(infantryType);\n }\n\n \/\/ Everything else should attack-move scout.\n }else{\n Position position = unit->getPosition();\n position.x += rand() % 501 - 250;\n position.y += rand() % 501 - 250;\n unit->attack(position);\n }\n }\n }\n}\n\nvoid ai::onNukeDetect(BWAPI::Position target){\n}\n\nvoid ai::onPlayerLeft(BWAPI::Player player){\n}\n\nvoid ai::onReceiveText(BWAPI::Player player, std::string text){\n}\n\nvoid ai::onSaveGame(std::string gameName){\n}\n\nvoid ai::onSendText(std::string text){\n Broodwar->sendText(\"%s\", text.c_str());\n}\n\nvoid ai::onStart(){\n Broodwar->setCommandOptimizationLevel(1);\n srand(time(NULL));\n\n \/\/ Setup global variables.\n infantryBuildingChecked = 0;\n infantryBuildingCheckTimer = 2000;\n infantryBuildingNeeded = false;\n playerRace = Broodwar->self()->getRace();\n savingMinerals = 0;\n supplyChecked = 0;\n supplyCheckTimer = 600;\n supplyNeeded = false;\n supplyProviderType = playerRace.getSupplyProvider();\n\n supplyProviderTypeIsBuilding = supplyProviderType.isBuilding();\n\n \/\/ Handle race-specific stuff.\n if(playerRace == Races::Zerg){\n infantryBuilding = UnitTypes::Zerg_Spawning_Pool;\n infantryType = UnitTypes::Zerg_Zergling;\n\n }else if(playerRace == Races::Terran){\n infantryBuilding = UnitTypes::Terran_Barracks;\n infantryType = UnitTypes::Terran_Marine;\n\n }else{\n infantryBuilding = UnitTypes::Protoss_Gateway;\n infantryType = UnitTypes::Protoss_Zealot;\n }\n\n Broodwar->sendText(\"glhf\");\n}\n\nvoid ai::onUnitComplete(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitCreate(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitDestroy(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitDiscover(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitEvade(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitHide(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitMorph(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitRenegade(BWAPI::Unit unit){\n}\n\nvoid ai::onUnitShow(BWAPI::Unit unit){\n}\n\nbool buildBuilding(Unit builder, UnitType building){\n TilePosition targetBuildLocation = Broodwar->getBuildLocation(\n builing,\n builder->getTilePosition()\n );\n\n if(targetBuildLocation){\n return builder->build(\n building,\n targetBuildLocation\n );\n }\n\n return false;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n @brief Implementation\n\n @date 2016\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2016 Sensics, Inc.\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\/\/ Internal Includes\n#include \"ConfigParams.h\"\n#include \"IMUStateMeasurements.h\"\n\n\/\/ Library\/third-party includes\n#include <osvr\/Util\/Angles.h>\n\n\/\/ Standard includes\n#include <iostream>\n#include <memory>\n\n#define CATCH_CONFIG_MAIN\n#include \"catch_typelist.h\"\n#include <catch.hpp>\n\nusing std::unique_ptr;\nusing namespace osvr;\nusing namespace vbtracker;\nusing namespace Eigen;\nstruct TestData {\n TestData() {\n \/\/\/ Set up from a default configuration.\n ConfigParams params;\n#if 0\n state.setErrorCovariance(\n kalman::types::DimVector<BodyState>::Constant(100).asDiagonal());\n#endif\n\n \/\/\/ configure the process model\n processModel.setDamping(params.linearVelocityDecayCoefficient,\n params.angularVelocityDecayCoefficient);\n processModel.setNoiseAutocorrelation(\n kalman::types::Vector<6>::Map(params.processNoiseAutocorrelation));\n\n \/\/\/ Save the IMU measurement parameters.\n imuVariance = Eigen::Vector3d::Constant(params.imu.orientationVariance);\n }\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n \/\/\/ Quantity computed from the \"camera pose\" (room calibration output)\n Eigen::Quaterniond roomToCameraRotation = Eigen::Quaterniond::Identity();\n\n \/\/\/ Quantity computed during room calibration output\n util::Angle yawCorrection = 0;\n\n \/\/\/ Transform the IMU-measured quaternion using the calibration output\n \/\/\/ mocked up in this struct.\n Eigen::Quaterniond xform(Eigen::Quaterniond const &quat) {\n return getTransformedOrientation(quat, roomToCameraRotation,\n yawCorrection);\n }\n\n \/\/\/ Default constructor is no translation, identity rotation, 10 along\n \/\/\/ main diagonal as the state covariance matrix.\n BodyState state;\n\n BodyProcessModel processModel;\n Eigen::Vector3d imuVariance;\n};\nnamespace Eigen {\ninline void outputQuat(std::ostream &os, Quaterniond const &q) {\n os << \"[\" << q.w() << \" (\" << q.vec().transpose() << \")]\";\n}\nstd::ostream &operator<<(std::ostream &os, Quaterniond const &q) {\n outputQuat(os, q);\n return os;\n}\n} \/\/ namespace Eigen\n\nnamespace Catch {\ntemplate <> struct TypelistTypeNameTrait<kalman::QFirst> {\n static const char *get() { return \"kalman::QFirst\"; }\n};\ntemplate <> struct TypelistTypeNameTrait<kalman::QLast> {\n static const char *get() { return \"kalman::QLast\"; }\n};\ntemplate <> struct TypelistTypeNameTrait<kalman::SplitQ> {\n static const char *get() { return \"kalman::SplitQ\"; }\n};\n} \/\/ namespace Catch\n\nstatic const double SMALL_VALUE = 0.1;\ntemplate <typename MeasurementType>\ninline void smallPositiveYChecks(TestData *data, MeasurementType &kalmanMeas) {\n using JacobianType = typename MeasurementType::JacobianType;\n Vector3d residual = kalmanMeas.getResidual(data->state);\n AND_THEN(\"residual should be 0, SMALL_VALUE, 0\") {\n CAPTURE(residual.transpose());\n CHECK(residual.isApprox(Vector3d(0, SMALL_VALUE, 0)));\n }\n\n JacobianType jacobian = kalmanMeas.getJacobian(data->state);\n AND_THEN(\"the jacobian should be finite\") {\n INFO(\"jacobian\\n\" << jacobian);\n REQUIRE(jacobian.allFinite());\n AND_THEN(\"the jacobian should not be zero\") {\n REQUIRE_FALSE(jacobian.isApproxToConstant(0));\n }\n }\n\n auto correctionInProgress =\n kalman::beginCorrection(data->state, data->processModel, kalmanMeas);\n AND_THEN(\"computed deltaz should equal residual\") {\n CAPTURE(residual.transpose());\n CAPTURE(correctionInProgress.deltaz.transpose());\n CHECK(residual.isApprox(correctionInProgress.deltaz));\n }\n CAPTURE(correctionInProgress.stateCorrection.transpose());\n AND_THEN(\"state correction should be finite\") {\n REQUIRE(correctionInProgress.stateCorrectionFinite);\n AND_THEN(\"state correction should have a rotation component with small \"\n \"positive y\") {\n REQUIRE(correctionInProgress.stateCorrection[3] == Approx(0.));\n REQUIRE(correctionInProgress.stateCorrection[4] > 0);\n REQUIRE(correctionInProgress.stateCorrection[5] == Approx(0.));\n }\n AND_THEN(\"state correction should have an angular velocity component \"\n \"with zero or small positive y\") {\n REQUIRE(correctionInProgress.stateCorrection[9] == Approx(0.));\n REQUIRE(correctionInProgress.stateCorrection[10] >= 0.);\n REQUIRE(correctionInProgress.stateCorrection[11] == Approx(0.));\n }\n AND_THEN(\"state correction should not contain any translational\/linear \"\n \"velocity components\") {\n REQUIRE(correctionInProgress.stateCorrection.head<3>()\n .isApproxToConstant(0.));\n REQUIRE(correctionInProgress.stateCorrection.segment<3>(6)\n .isApproxToConstant(0.));\n }\n }\n}\n\nCATCH_TYPELIST_TESTCASE(\"identity calibration output\", kalman::QFirst,\n kalman::QLast, kalman::SplitQ) {\n using MeasurementType = OrientationMeasurementUsingPolicy<TypeParam>;\n using JacobianType = typename MeasurementType::JacobianType;\n unique_ptr<TestData> data(new TestData);\n GIVEN(\"an identity state\") {\n WHEN(\"filtering in an identity measurement\") {\n Quaterniond xformedMeas = data->xform(Quaterniond::Identity());\n\n THEN(\"the transformed measurement should equal the measurement\") {\n CAPTURE(xformedMeas);\n REQUIRE(xformedMeas.isApprox(Quaterniond::Identity()));\n\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n AND_THEN(\"residual should be zero\") {\n CAPTURE(kalmanMeas.getResidual(data->state));\n REQUIRE(kalmanMeas.getResidual(data->state)\n .isApproxToConstant(0.));\n }\n\n JacobianType jacobian = kalmanMeas.getJacobian(data->state);\n AND_THEN(\"the jacobian should be finite\") {\n INFO(\"jacobian\\n\" << jacobian);\n REQUIRE(jacobian.allFinite());\n AND_THEN(\"the jacobian should not be zero\") {\n REQUIRE_FALSE(jacobian.isApproxToConstant(0));\n }\n auto correctionInProgress = kalman::beginCorrection(\n data->state, data->processModel, kalmanMeas);\n AND_THEN(\"computed deltaz should be zero\") {\n CAPTURE(correctionInProgress.deltaz.transpose());\n REQUIRE(\n correctionInProgress.deltaz.isApproxToConstant(0.));\n }\n CAPTURE(correctionInProgress.stateCorrection.transpose());\n AND_THEN(\"state correction should be finite\") {\n REQUIRE(correctionInProgress.stateCorrectionFinite);\n AND_THEN(\"state correction should be zero\") {\n REQUIRE(correctionInProgress.stateCorrection\n .isApproxToConstant(0.));\n }\n }\n }\n }\n }\n WHEN(\"filtering in a small positive rotation about y\") {\n Quaterniond smallPositiveRotationAboutY(\n AngleAxisd(SMALL_VALUE, Vector3d::UnitY()));\n CAPTURE(SMALL_VALUE);\n CAPTURE(smallPositiveRotationAboutY);\n Quaterniond xformedMeas = data->xform(smallPositiveRotationAboutY);\n CAPTURE(xformedMeas);\n\n THEN(\"the transformed measurement should equal the measurement\") {\n REQUIRE(xformedMeas.isApprox(smallPositiveRotationAboutY));\n \/\/\/ Do the rest of the checks for a small rotation about y\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n smallPositiveYChecks(data.get(), kalmanMeas);\n }\n }\n }\n GIVEN(\"a state rotated about y\") {\n Quaterniond stateRotation(AngleAxisd(M_PI \/ 4., Vector3d::UnitY()));\n data->state.setQuaternion(stateRotation);\n WHEN(\"filtering in a small positive rotation about y\") {\n Quaterniond smallPositiveRotationAboutY =\n stateRotation *\n Quaterniond(AngleAxisd(SMALL_VALUE, Vector3d::UnitY()));\n CAPTURE(SMALL_VALUE);\n CAPTURE(smallPositiveRotationAboutY);\n Quaterniond xformedMeas = data->xform(smallPositiveRotationAboutY);\n CAPTURE(xformedMeas);\n\n THEN(\"the transformed measurement should equal the measurement\") {\n REQUIRE(xformedMeas.isApprox(smallPositiveRotationAboutY));\n\n \/\/\/ Do the rest of the checks for a small rotation about y\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n smallPositiveYChecks(data.get(), kalmanMeas);\n }\n }\n }\n GIVEN(\"a state rotated about x\") {\n Quaterniond stateRotation(AngleAxisd(M_PI \/ 4., Vector3d::UnitX()));\n data->state.setQuaternion(stateRotation);\n WHEN(\"filtering in a small positive rotation about y\") {\n Quaterniond smallPositiveRotationAboutY =\n stateRotation *\n Quaterniond(AngleAxisd(SMALL_VALUE, Vector3d::UnitY()));\n CAPTURE(SMALL_VALUE);\n CAPTURE(smallPositiveRotationAboutY);\n Quaterniond xformedMeas = data->xform(smallPositiveRotationAboutY);\n CAPTURE(xformedMeas);\n\n THEN(\"the transformed measurement should equal the measurement\") {\n REQUIRE(xformedMeas.isApprox(smallPositiveRotationAboutY));\n\n \/\/\/ Do the rest of the checks for a small rotation about y\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n smallPositiveYChecks(data.get(), kalmanMeas);\n }\n }\n }\n}\n\nTEST_CASE(\"Sigma point reconstruction validity\") {\n using namespace osvr::kalman;\n Matrix3d cov(Vector3d::Constant(10).asDiagonal());\n using Generator = SigmaPointGenerator<3>;\n using Reconstructor = ReconstructedDistributionFromSigmaPoints<3, 3>;\n const auto params = SigmaPointParameters(3);\n WHEN(\"Starting with a zero mean\") {\n Vector3d mean = Vector3d::Zero();\n auto gen = Generator(mean, cov, params);\n auto recon = Reconstructor(gen, gen.getSigmaPoints());\n THEN(\"the reconstructed distribution should be approximately equal to \"\n \"the input\") {\n CAPTURE(gen.getSigmaPoints());\n CAPTURE(recon.getMean());\n REQUIRE(recon.getMean().isApproxToConstant(0));\n CAPTURE(recon.getCov());\n REQUIRE(recon.getCov().isApprox(cov));\n }\n }\n}\n<commit_msg>Unscented implementation in the testIMU file.<commit_after>\/** @file\n @brief Implementation\n\n @date 2016\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2016 Sensics, Inc.\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\/\/ Internal Includes\n#include \"ConfigParams.h\"\n#include \"IMUStateMeasurements.h\"\n\n\/\/ Library\/third-party includes\n#include <osvr\/Util\/Angles.h>\n\n\/\/ Standard includes\n#include <iostream>\n#include <memory>\n\n#define CATCH_CONFIG_MAIN\n#include \"catch_typelist.h\"\n#include <catch.hpp>\n\nusing std::unique_ptr;\nusing namespace osvr;\nusing namespace vbtracker;\nusing namespace Eigen;\nstruct TestData {\n TestData() {\n \/\/\/ Set up from a default configuration.\n ConfigParams params;\n#if 0\n state.setErrorCovariance(\n kalman::types::DimVector<BodyState>::Constant(100).asDiagonal());\n#endif\n\n \/\/\/ configure the process model\n processModel.setDamping(params.linearVelocityDecayCoefficient,\n params.angularVelocityDecayCoefficient);\n processModel.setNoiseAutocorrelation(\n kalman::types::Vector<6>::Map(params.processNoiseAutocorrelation));\n\n \/\/\/ Save the IMU measurement parameters.\n imuVariance = Eigen::Vector3d::Constant(params.imu.orientationVariance);\n }\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n \/\/\/ Quantity computed from the \"camera pose\" (room calibration output)\n Eigen::Quaterniond roomToCameraRotation = Eigen::Quaterniond::Identity();\n\n \/\/\/ Quantity computed during room calibration output\n util::Angle yawCorrection = 0;\n\n \/\/\/ Transform the IMU-measured quaternion using the calibration output\n \/\/\/ mocked up in this struct.\n Eigen::Quaterniond xform(Eigen::Quaterniond const &quat) {\n return getTransformedOrientation(quat, roomToCameraRotation,\n yawCorrection);\n }\n\n \/\/\/ Default constructor is no translation, identity rotation, 10 along\n \/\/\/ main diagonal as the state covariance matrix.\n BodyState state;\n\n BodyProcessModel processModel;\n Eigen::Vector3d imuVariance;\n};\nnamespace Eigen {\ninline void outputQuat(std::ostream &os, Quaterniond const &q) {\n os << \"[\" << q.w() << \" (\" << q.vec().transpose() << \")]\";\n}\nstd::ostream &operator<<(std::ostream &os, Quaterniond const &q) {\n outputQuat(os, q);\n return os;\n}\n} \/\/ namespace Eigen\n\nnamespace Catch {\ntemplate <> struct TypelistTypeNameTrait<kalman::QFirst> {\n static const char *get() { return \"kalman::QFirst\"; }\n};\ntemplate <> struct TypelistTypeNameTrait<kalman::QLast> {\n static const char *get() { return \"kalman::QLast\"; }\n};\ntemplate <> struct TypelistTypeNameTrait<kalman::SplitQ> {\n static const char *get() { return \"kalman::SplitQ\"; }\n};\n} \/\/ namespace Catch\n\nstatic const double SMALL_VALUE = 0.1;\ntemplate <typename MeasurementType>\ninline void smallPositiveYChecks(TestData *data, MeasurementType &kalmanMeas) {\n using JacobianType = typename MeasurementType::JacobianType;\n Vector3d residual = kalmanMeas.getResidual(data->state);\n AND_THEN(\"residual should be 0, SMALL_VALUE, 0\") {\n CAPTURE(residual.transpose());\n CHECK(residual.isApprox(Vector3d(0, SMALL_VALUE, 0)));\n }\n\n JacobianType jacobian = kalmanMeas.getJacobian(data->state);\n AND_THEN(\"the jacobian should be finite\") {\n INFO(\"jacobian\\n\" << jacobian);\n REQUIRE(jacobian.allFinite());\n AND_THEN(\"the jacobian should not be zero\") {\n REQUIRE_FALSE(jacobian.isApproxToConstant(0));\n }\n }\n\n auto correctionInProgress =\n kalman::beginCorrection(data->state, data->processModel, kalmanMeas);\n AND_THEN(\"computed deltaz should equal residual\") {\n CAPTURE(residual.transpose());\n CAPTURE(correctionInProgress.deltaz.transpose());\n CHECK(residual.isApprox(correctionInProgress.deltaz));\n }\n CAPTURE(correctionInProgress.stateCorrection.transpose());\n AND_THEN(\"state correction should be finite\") {\n REQUIRE(correctionInProgress.stateCorrectionFinite);\n AND_THEN(\"state correction should have a rotation component with small \"\n \"positive y\") {\n REQUIRE(correctionInProgress.stateCorrection[3] == Approx(0.));\n REQUIRE(correctionInProgress.stateCorrection[4] > 0);\n REQUIRE(correctionInProgress.stateCorrection[5] == Approx(0.));\n }\n AND_THEN(\"state correction should have an angular velocity component \"\n \"with zero or small positive y\") {\n REQUIRE(correctionInProgress.stateCorrection[9] == Approx(0.));\n REQUIRE(correctionInProgress.stateCorrection[10] >= 0.);\n REQUIRE(correctionInProgress.stateCorrection[11] == Approx(0.));\n }\n AND_THEN(\"state correction should not contain any translational\/linear \"\n \"velocity components\") {\n REQUIRE(correctionInProgress.stateCorrection.head<3>()\n .isApproxToConstant(0.));\n REQUIRE(correctionInProgress.stateCorrection.segment<3>(6)\n .isApproxToConstant(0.));\n }\n }\n}\n\nCATCH_TYPELIST_TESTCASE(\"identity calibration output\", kalman::QFirst,\n kalman::QLast, kalman::SplitQ) {\n using MeasurementType = OrientationMeasurementUsingPolicy<TypeParam>;\n using JacobianType = typename MeasurementType::JacobianType;\n unique_ptr<TestData> data(new TestData);\n GIVEN(\"an identity state\") {\n WHEN(\"filtering in an identity measurement\") {\n Quaterniond xformedMeas = data->xform(Quaterniond::Identity());\n\n THEN(\"the transformed measurement should equal the measurement\") {\n CAPTURE(xformedMeas);\n REQUIRE(xformedMeas.isApprox(Quaterniond::Identity()));\n\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n AND_THEN(\"residual should be zero\") {\n CAPTURE(kalmanMeas.getResidual(data->state));\n REQUIRE(kalmanMeas.getResidual(data->state)\n .isApproxToConstant(0.));\n }\n\n JacobianType jacobian = kalmanMeas.getJacobian(data->state);\n AND_THEN(\"the jacobian should be finite\") {\n INFO(\"jacobian\\n\" << jacobian);\n REQUIRE(jacobian.allFinite());\n AND_THEN(\"the jacobian should not be zero\") {\n REQUIRE_FALSE(jacobian.isApproxToConstant(0));\n }\n auto correctionInProgress = kalman::beginCorrection(\n data->state, data->processModel, kalmanMeas);\n AND_THEN(\"computed deltaz should be zero\") {\n CAPTURE(correctionInProgress.deltaz.transpose());\n REQUIRE(\n correctionInProgress.deltaz.isApproxToConstant(0.));\n }\n CAPTURE(correctionInProgress.stateCorrection.transpose());\n AND_THEN(\"state correction should be finite\") {\n REQUIRE(correctionInProgress.stateCorrectionFinite);\n AND_THEN(\"state correction should be zero\") {\n REQUIRE(correctionInProgress.stateCorrection\n .isApproxToConstant(0.));\n }\n }\n }\n }\n }\n WHEN(\"filtering in a small positive rotation about y\") {\n Quaterniond smallPositiveRotationAboutY(\n AngleAxisd(SMALL_VALUE, Vector3d::UnitY()));\n CAPTURE(SMALL_VALUE);\n CAPTURE(smallPositiveRotationAboutY);\n Quaterniond xformedMeas = data->xform(smallPositiveRotationAboutY);\n CAPTURE(xformedMeas);\n\n THEN(\"the transformed measurement should equal the measurement\") {\n REQUIRE(xformedMeas.isApprox(smallPositiveRotationAboutY));\n \/\/\/ Do the rest of the checks for a small rotation about y\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n smallPositiveYChecks(data.get(), kalmanMeas);\n }\n }\n }\n GIVEN(\"a state rotated about y\") {\n Quaterniond stateRotation(AngleAxisd(M_PI \/ 4., Vector3d::UnitY()));\n data->state.setQuaternion(stateRotation);\n WHEN(\"filtering in a small positive rotation about y\") {\n Quaterniond smallPositiveRotationAboutY =\n stateRotation *\n Quaterniond(AngleAxisd(SMALL_VALUE, Vector3d::UnitY()));\n CAPTURE(SMALL_VALUE);\n CAPTURE(smallPositiveRotationAboutY);\n Quaterniond xformedMeas = data->xform(smallPositiveRotationAboutY);\n CAPTURE(xformedMeas);\n\n THEN(\"the transformed measurement should equal the measurement\") {\n REQUIRE(xformedMeas.isApprox(smallPositiveRotationAboutY));\n\n \/\/\/ Do the rest of the checks for a small rotation about y\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n smallPositiveYChecks(data.get(), kalmanMeas);\n }\n }\n }\n GIVEN(\"a state rotated about x\") {\n Quaterniond stateRotation(AngleAxisd(M_PI \/ 4., Vector3d::UnitX()));\n data->state.setQuaternion(stateRotation);\n WHEN(\"filtering in a small positive rotation about y\") {\n Quaterniond smallPositiveRotationAboutY =\n stateRotation *\n Quaterniond(AngleAxisd(SMALL_VALUE, Vector3d::UnitY()));\n CAPTURE(SMALL_VALUE);\n CAPTURE(smallPositiveRotationAboutY);\n Quaterniond xformedMeas = data->xform(smallPositiveRotationAboutY);\n CAPTURE(xformedMeas);\n\n THEN(\"the transformed measurement should equal the measurement\") {\n REQUIRE(xformedMeas.isApprox(smallPositiveRotationAboutY));\n\n \/\/\/ Do the rest of the checks for a small rotation about y\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n smallPositiveYChecks(data.get(), kalmanMeas);\n }\n }\n }\n}\n\nTEST_CASE(\"Sigma point reconstruction validity\") {\n using namespace osvr::kalman;\n Matrix3d cov(Vector3d::Constant(10).asDiagonal());\n using Generator = SigmaPointGenerator<3>;\n using Reconstructor = ReconstructedDistributionFromSigmaPoints<3, 3>;\n const auto params = SigmaPointParameters(3);\n WHEN(\"Starting with a zero mean\") {\n Vector3d mean = Vector3d::Zero();\n auto gen = Generator(mean, cov, params);\n auto recon = Reconstructor(gen, gen.getSigmaPoints());\n THEN(\"the reconstructed distribution should be approximately equal to \"\n \"the input\") {\n CAPTURE(gen.getSigmaPoints());\n CAPTURE(recon.getMean());\n REQUIRE(recon.getMean().isApproxToConstant(0));\n CAPTURE(recon.getCov());\n REQUIRE(recon.getCov().isApprox(cov));\n }\n }\n\n WHEN(\"Starting with a non-zero mean\") {\n Vector3d mean = Vector3d(1, 2, 3);\n auto gen = Generator(mean, cov, params);\n auto recon = Reconstructor(gen, gen.getSigmaPoints());\n THEN(\"the reconstructed distribution should be approximately equal to \"\n \"the input\") {\n CAPTURE(gen.getSigmaPoints());\n CAPTURE(recon.getMean());\n REQUIRE(recon.getMean().isApprox(mean));\n CAPTURE(recon.getCov());\n REQUIRE(recon.getCov().isApprox(cov));\n }\n }\n}\n\nnamespace osvr {\nnamespace kalman {\n\n template <std::size_t Dim, std::size_t OrigDim = Dim>\n class AugmentedSigmaPointGenerator {\n public:\n static_assert(OrigDim <= Dim, \"Original, non-augmented dimension must \"\n \"be equal or less than the full \"\n \"dimension\");\n static const std::size_t L = Dim;\n static const std::size_t OriginalDimension = OrigDim;\n static const std::size_t NumSigmaPoints = L * 2 + 1;\n using MeanVec = types::Vector<Dim>;\n using CovMatrix = types::SquareMatrix<Dim>;\n using SigmaPointsMat = types::Matrix<Dim, NumSigmaPoints>;\n using SigmaPointWeightVec = types::Vector<NumSigmaPoints>;\n template <std::size_t OutputDimension>\n using TransformedSigmaPointsMat =\n types::Matrix<OutputDimension, NumSigmaPoints>;\n AugmentedSigmaPointGenerator(MeanVec const &mean, CovMatrix const &cov,\n SigmaPointParameters params)\n : mean_(mean), covariance_(cov) {\n weights_ =\n SigmaPointWeightVec::Constant(params.getOtherEltWeights());\n weightsForCov_ = weights_;\n weights_[0] = params.getElt0MeanWeight();\n weightsForCov_[0] = params.getElt0CovWeight();\n scaledMatrixSqrt_ = cov.llt().matrixL();\n scaledMatrixSqrt_ *= params.gamma;\n sigmaPoints_ << mean, scaledMatrixSqrt_.colwise() + mean,\n (-scaledMatrixSqrt_).colwise() + mean;\n }\n\n SigmaPointsMat const &getSigmaPoints() const { return sigmaPoints_; }\n\n using SigmaPointBlock = Eigen::Block<SigmaPointsMat, OrigDim, 1>;\n using ConstSigmaPointBlock =\n Eigen::Block<const SigmaPointsMat, OrigDim, 1>;\n\n ConstSigmaPointBlock getSigmaPoint(std::size_t i) const {\n return sigmaPoints_.block<OrigDim, 1>(0, i);\n }\n\n SigmaPointWeightVec const &getWeightsForMean() const {\n return weights_;\n }\n SigmaPointWeightVec const &getWeightsForCov() const {\n return weightsForCov_;\n }\n\n MeanVec const &getMean() const { return mean_; }\n\n private:\n MeanVec mean_;\n CovMatrix covariance_;\n CovMatrix scaledMatrixSqrt_;\n SigmaPointsMat sigmaPoints_;\n SigmaPointWeightVec weights_;\n SigmaPointWeightVec weightsForCov_;\n };\n\n template <std::size_t XformedDim, typename SigmaPointsGenType>\n class SigmaDistributionReconstruction {\n public:\n static const std::size_t DIMENSION = XformedDim;\n using SigmaPointsGen = SigmaPointsGenType;\n static const std::size_t NumSigmaPoints =\n SigmaPointsGen::NumSigmaPoints;\n\n static const types::DimensionType OriginalDimension =\n SigmaPointsGen::OriginalDimension;\n using TransformedSigmaPointsMat =\n typename SigmaPointsGen::template TransformedSigmaPointsMat<\n XformedDim>;\n\n using CrossCovMatrix = types::Matrix<OriginalDimension, DIMENSION>;\n\n using MeanVec = types::Vector<XformedDim>;\n using CovMat = types::SquareMatrix<XformedDim>;\n SigmaDistributionReconstruction(\n SigmaPointsGen const &sigmaPoints,\n TransformedSigmaPointsMat const &xformedPointsMat)\n : xformedCov_(CovMat::Zero()), crossCov_(CrossCovMatrix::Zero()) {\n \/\/\/ weighted average\n xformedMean_ = xformedPointsMat * sigmaPoints.getWeightsForMean();\n TransformedSigmaPointsMat zeroMeanPoints =\n xformedPointsMat.colwise() - xformedMean_;\n\n for (std::size_t i = 0; i < NumSigmaPoints; ++i) {\n auto weight = sigmaPoints.getWeightsForCov()[i];\n xformedCov_ += weight * zeroMeanPoints.col(i) *\n zeroMeanPoints.col(i).transpose();\n crossCov_ += weight * sigmaPoints.getSigmaPoint(i) *\n zeroMeanPoints.col(i).transpose();\n }\n }\n\n MeanVec const &getMean() const { return xformedMean_; }\n CovMat const &getCov() const { return xformedCov_; }\n \/\/ matrix of cross-covariance between original and transformed (such as\n \/\/ state and measurement)\n CrossCovMatrix const &getCrossCov() const { return crossCov_; }\n\n private:\n MeanVec xformedMean_;\n CovMat xformedCov_;\n CrossCovMatrix crossCov_;\n };\n\n template <typename State, typename Measurement>\n class SigmaPointCorrectionApplication {\n public:\n static const types::DimensionType StateDim =\n types::Dimension<State>::value;\n static const types::DimensionType MeasurementDim =\n types::Dimension<Measurement>::value;\n \/\/\/ state augmented with measurement noise mean\n static const types::DimensionType AugmentedStateDim =\n StateDim + MeasurementDim;\n using StateVec = types::DimVector<State>;\n using StateSquareMatrix = types::DimSquareMatrix<State>;\n using MeasurementSquareMatrix = types::DimSquareMatrix<Measurement>;\n using AugmentedStateVec = types::Vector<AugmentedStateDim>;\n using AugmentedStateCovMatrix = types::SquareMatrix<AugmentedStateDim>;\n using SigmaPointsGen =\n AugmentedSigmaPointGenerator<AugmentedStateDim, StateDim>;\n static const types::DimensionType NumSigmaPoints =\n SigmaPointsGen::NumSigmaPoints;\n\n using TransformedSigmaPointMat =\n types::Matrix<MeasurementDim, NumSigmaPoints>;\n\n using Reconstruction =\n SigmaDistributionReconstruction<MeasurementDim, SigmaPointsGen>;\n\n using GainMatrix = types::Matrix<StateDim, MeasurementDim>;\n\n SigmaPointCorrectionApplication(State &s, Measurement &m,\n SigmaPointParameters params)\n : state(s), measurement(m),\n sigmaPoints(getAugmentedStateVec(s, m),\n getAugmentedStateCov(s, m), params),\n transformedPoints(\n transformSigmaPoints(state, measurement, sigmaPoints)),\n reconstruction(sigmaPoints, transformedPoints),\n innovationCovariance(computeInnovationCovariance(\n state, measurement, reconstruction)),\n K(computeKalmanGain(innovationCovariance, reconstruction)),\n stateCorrection(K * reconstruction.getMean()) {}\n\n static AugmentedStateVec getAugmentedStateVec(State const &s,\n Measurement const &m) {\n AugmentedStateVec ret;\n \/\/\/ assuming measurement noise is zero mean\n ret << s.stateVector(), types::DimVector<Measurement>::Zero();\n return ret;\n }\n\n static AugmentedStateCovMatrix getAugmentedStateCov(State const &s,\n Measurement &m) {\n AugmentedStateCovMatrix ret;\n ret << s.errorCovariance(),\n types::Matrix<StateDim, MeasurementDim>::Zero(),\n types::Matrix<MeasurementDim, StateDim>::Zero(),\n m.getCovariance(s);\n return ret;\n }\n\n \/\/\/ Transforms sigma points by having the measurement compute the\n \/\/\/ residual for a state whose state vector we update to each of the\n \/\/\/ sigma points in turn.\n static TransformedSigmaPointMat\n transformSigmaPoints(State const &s, Measurement &m,\n SigmaPointsGen const &sigmaPoints) {\n TransformedSigmaPointMat ret;\n State tempS = s;\n for (std::size_t i = 0; i < NumSigmaPoints; ++i) {\n tempS.setStateVector(sigmaPoints.getSigmaPoint(i));\n ret.col(i) = m.getResidual(tempS);\n }\n return ret;\n }\n\n static MeasurementSquareMatrix\n computeInnovationCovariance(State const &s, Measurement &m,\n Reconstruction const &recon) {\n return recon.getCov() + m.getCovariance(s);\n }\n\n static GainMatrix computeKalmanGain(MeasurementSquareMatrix const &Pvv,\n Reconstruction const &recon) {\n\n \/\/ Solve for K in K=Pxy Pvv^-1\n \/\/ where the cross-covariance matrix from the reconstruction is\n \/\/ transpose(Pxy) and Pvv is the reconstructed covariance plus the\n \/\/ measurement covariance\n \/\/ (Actually solves with transpose(Pvv) * transpose(K) =\n \/\/ transpose(Pxy) )\n GainMatrix ret = Pvv.transpose().ldlt().solve(recon.getCrossCov());\n return ret;\n }\n\n void finishCorrection() {\n state.setStateVector(state.stateVector() + stateCorrection);\n\n StateSquareMatrix newP = state.errorCovariance() -\n K * innovationCovariance * K.transpose();\n state.setErrorCovariance(newP);\n \/\/ Let the state do any cleanup it has to (like fixing externalized\n \/\/ quaternions)\n state.postCorrect();\n }\n\n State &state;\n Measurement &measurement;\n SigmaPointsGen sigmaPoints;\n TransformedSigmaPointMat transformedPoints;\n Reconstruction reconstruction;\n MeasurementSquareMatrix innovationCovariance;\n GainMatrix K;\n StateVec stateCorrection;\n };\n template <typename State, typename Measurement>\n inline SigmaPointCorrectionApplication<State, Measurement>\n beginUnscentedCorrection(State &s, Measurement &m,\n SigmaPointParameters params) {\n return SigmaPointCorrectionApplication<State, Measurement>(s, m,\n params);\n }\n} \/\/ namespace kalman\n} \/\/ namespace osvr\n#if 0\nCATCH_TYPELIST_TESTCASE(\"unscented with identity calibration output\",\n kalman::IMUOrientationMeasForUnscented) {\n#endif\nTEST_CASE(\"unscented with identity calibration output\") {\n using TypeParam = kalman::IMUOrientationMeasForUnscented;\n\n const auto params = kalman::SigmaPointParameters(3);\n \/\/ using MeasurementType = OrientationMeasurementUsingPolicy<TypeParam>;\n using MeasurementType = TypeParam;\n unique_ptr<TestData> data(new TestData);\n GIVEN(\"an identity state\") {\n WHEN(\"filtering in an identity measurement\") {\n Quaterniond xformedMeas = data->xform(Quaterniond::Identity());\n\n THEN(\"the transformed measurement should equal the measurement\") {\n CAPTURE(xformedMeas);\n REQUIRE(xformedMeas.isApprox(Quaterniond::Identity()));\n\n MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n AND_THEN(\"residual should be zero\") {\n CAPTURE(kalmanMeas.getResidual(data->state));\n REQUIRE(kalmanMeas.getResidual(data->state)\n .isApproxToConstant(0.));\n }\n using StateDim =\n kalman::types::Dimension<decltype(data->state)>;\n using MeasurementDim =\n kalman::types::Dimension<MeasurementType>;\n static const auto m = MeasurementDim::value;\n static const auto n = StateDim::value;\n auto inProgress = kalman::beginUnscentedCorrection(\n data->state, kalmanMeas, params);\n\n AND_THEN(\"transformed sigma points should not all equal 0\") {\n REQUIRE_FALSE(\n inProgress.transformedPoints.isApproxToConstant(0.));\n }\n \/\/ kalman::SigmaDistributionReconstruction<MeasurementDim::value,\n \/\/ typename decltype(inProgress)::SigmaPointsGen>\n auto &recon = inProgress.reconstruction;\n AND_THEN(\"propagated mean residual should be zero\") {\n CAPTURE(recon.getMean().transpose());\n REQUIRE(recon.getMean().isApproxToConstant(0.));\n }\n AND_THEN(\n \"state correction should be finite - specifically, zero\") {\n CAPTURE(inProgress.stateCorrection.transpose());\n REQUIRE(inProgress.stateCorrection.array().allFinite());\n REQUIRE(inProgress.stateCorrection.isApproxToConstant(0));\n }\n }\n }\n }\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>Put back deprecated functions.<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include \"any_value.hpp\"\n\n\/\/ GCC (at least g++ 4.7.2) and Visual Studio 2015 do support\n\/\/ setting default values of a struct using C++11 syntax.\n\/\/ Clang 3.7.0 and Visual Studio 2013 do not support\n\/\/ setting default values of a struct using C++11 syntax.\n\/\/ Visual Studio 2013 fails to compile, whereas Clang-compiled\n\/\/ executable with code with setting default values of a struct\n\/\/ causes Segmentation fault upon execution of the program.\n\/\/ Compilers that don't support setting default values of a struct\n\/\/ are handled by setting the default values in a macro.\n\/\/ http:\/\/stackoverflow.com\/questions\/16782103\/initializing-default-values-in-a-struct\/16783513#16783513\n#ifdef __clang__\n#elif defined(__GNUC__)\n#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED\n#elif defined(_WIN32)\n#if (_MSC_VER >= 1900)\n#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED\n#endif\n#endif\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include <GL\/glew.h> \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include <glfw3.h>\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include <cmath> \/\/ NAN, std::isnan, std::pow\n#include <stdint.h> \/\/ uint32_t etc.\n#include <string> \/\/ std::string\n#include <vector> \/\/ std::vector\n\n#ifndef PI\n#define PI 3.14159265359f\n#endif\n\nnamespace ontology\n{\n class Universe;\n class Scene;\n class Shader;\n class Graph;\n class Material;\n class VectorFont;\n class Species;\n class Glyph;\n class Text3D;\n}\n\ntypedef struct ShaderStruct\n{\n ShaderStruct()\n : parent_pointer(nullptr)\n {\n \/\/ constructor.\n }\n ontology::Scene* parent_pointer; \/\/ pointer to the scene (draw list).\n std::string vertex_shader; \/\/ filename of vertex shader.\n std::string fragment_shader; \/\/ filename of fragment shader.\n} ShaderStruct;\n\ntypedef struct MaterialStruct\n{\n MaterialStruct()\n : parent_pointer(nullptr)\n {\n \/\/ constructor.\n }\n ontology::Shader* parent_pointer; \/\/ pointer to the shader.\n std::string texture_file_format; \/\/ type of the texture file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"dds\"`\/`\"DDS\"`.\n std::string texture_filename; \/\/ filename of the model file.\n std::string image_path;\n} MaterialStruct;\n\ntypedef struct NodeStruct\n{\n NodeStruct()\n : parent_pointer(nullptr)\n {\n \/\/ constructor.\n }\n GLuint nodeID;\n ontology::Graph* parent_pointer;\n glm::vec3 coordinate_vector;\n std::vector<uint32_t> neighbor_nodeIDs;\n} NodeStruct;\n\ntypedef struct ObjectStruct\n{\n ObjectStruct()\n : species_parent_pointer(nullptr), glyph_parent_pointer(nullptr), text3D_parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN), is_character(false)\n {\n \/\/ constructor.\n }\n ontology::Species* species_parent_pointer; \/\/ pointer to the parent `Species`.\n ontology::Glyph* glyph_parent_pointer; \/\/ pointer to the parent `Glyph`.\n ontology::Text3D* text3D_parent_pointer; \/\/ pointer to the parent `Text3D`.\n glm::vec3 original_scale_vector; \/\/ original scale vector.\n GLfloat rotate_angle; \/\/ rotate angle.\n bool is_character; \/\/ The parent of a character object is a Glyph. The parent of a regular object is a Species.\n glm::vec3 coordinate_vector; \/\/ coordinate vector.\n glm::vec3 rotate_vector; \/\/ rotate vector.\n glm::vec3 translate_vector; \/\/ translate vector.\n} ObjectStruct;\n\ntypedef struct SpeciesStruct\n{\n SpeciesStruct()\n : parent_pointer(nullptr), is_world(false), world_radius(NAN), triangulation_type(\"bilinear_interpolation\")\n {\n \/\/ constructor.\n }\n \/\/ used for all files (for all species).\n ontology::Material* parent_pointer; \/\/ pointer to the material object.\n bool is_world; \/\/ worlds currently do not rotate nor translate.\n double world_radius; \/\/ radius of sea level in meters. used only for worlds.\n std::string model_file_format; \/\/ type of the model file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"obj\"`\/`\"OBJ\"`.\n \/\/ TODO: add support for `\"SRTM\"`.\n std::string model_filename; \/\/ filename of the model file.\n \/\/ for `\"bmp\"` model files.\n std::string color_channel; \/\/ color channel to use for altitude data.\n\n glm::vec3 light_position; \/\/ light position.\n std::string coordinate_system; \/\/ used only for worlds (`is_world` == `true`). valid values: `\"cartesian\"`.\n \/\/ TODO: add support for `\"spherical\"`. `\"spherical\"` is used eg. in SRTM heightmaps.\n std::string triangulation_type;\n} SpeciesStruct;\n\n#define DEFAULT_VERTEX_SCALING_FACTOR (0.001f)\n\ntypedef struct VectorFontStruct\n{\n VectorFontStruct()\n : parent_pointer(nullptr), vertex_scaling_factor(DEFAULT_VERTEX_SCALING_FACTOR)\n {\n \/\/ constructor.\n }\n \/\/ used for all files (for all font).\n ontology::Material* parent_pointer; \/\/ pointer to the material object.\n GLfloat vertex_scaling_factor;\n std::string font_file_format; \/\/ type of the font file. supported file formats so far: `\"svg\"`\/`\"SVG\"`.\n std::string font_filename; \/\/ filename of the font file.\n} VectorFontStruct;\n\ntypedef struct Text3DStruct\n{\n Text3DStruct()\n : parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN)\n {\n \/\/ constructor.\n }\n ontology::VectorFont* parent_pointer; \/\/ pointer to the parent `VectorFont`.\n std::string text_string;\n const char* text_string_char;\n glm::vec3 original_scale_vector; \/\/ original scale vector.\n GLfloat rotate_angle; \/\/ rotate angle.\n glm::vec3 coordinate_vector; \/\/ coordinate vector.\n glm::vec3 rotate_vector; \/\/ rotate vector.\n glm::vec3 translate_vector; \/\/ translate vector.\n} Text3DStruct;\n\ntypedef struct GlyphStruct\n{\n GlyphStruct()\n : parent_pointer(nullptr)\n {\n \/\/ constructor.\n }\n \/\/ used for all files (for all glyph).\n std::vector<std::vector<glm::vec2>>* glyph_vertex_data;\n const char* glyph_name_pointer; \/\/ we need only a pointer, because glyphs are always created by the `VectorFont` constructor.\n const char* unicode_char_pointer; \/\/ we need only a pointer, because glyphs are always created by the `VectorFont` constructor.\n ontology::VectorFont* parent_pointer; \/\/ pointer to the font object.\n glm::vec3 light_position; \/\/ light position.\n} GlyphStruct;\n\ntypedef struct\n{\n GLuint screen_width;\n GLuint screen_height;\n GLuint x;\n GLuint y;\n GLuint text_size;\n GLuint font_size;\n std::string text;\n const char* text_char;\n const char* char_font_texture_file_format;\n const char* horizontal_alignment;\n const char* vertical_alignment;\n} PrintingStruct;\n\ntypedef struct\n{\n double rho;\n double theta;\n double phi;\n} SphericalCoordinatesStruct;\n\ntypedef struct SphericalWorldStruct\n{\n SphericalWorldStruct()\n :SRTM_latitude_step_in_degrees(1.0f\/1200.0f), SRTM_longitude_step_in_degrees(1.0f\/1200.0f)\n {\n \/\/ constructor.\n }\n double southern_latitude;\n double northern_latitude;\n double western_longitude;\n double eastern_longitude;\n double SRTM_latitude_step_in_degrees;\n double SRTM_longitude_step_in_degrees;\n} SphericalWorldStruct;\n\ntypedef struct TriangulateQuadsStruct\n{\n TriangulateQuadsStruct()\n : should_ylikuutio_use_real_texture_coordinates(true)\n {\n \/\/ constructor.\n }\n uint32_t image_width;\n uint32_t image_height;\n std::string triangulation_type;\n bool should_ylikuutio_use_real_texture_coordinates;\n double sphere_radius;\n SphericalWorldStruct spherical_world_struct;\n} TriangulateQuadsStruct;\n\ntypedef struct TriangulatePolygonsStruct\n{\n TriangulatePolygonsStruct()\n : should_ylikuutio_use_real_texture_coordinates(true)\n {\n \/\/ constructor.\n }\n std::vector<std::vector<glm::vec2>>* input_vertices;\n bool should_ylikuutio_use_real_texture_coordinates;\n} TriangulatePolygonsStruct;\n\ntypedef struct\n{\n uint32_t image_width;\n uint32_t image_height;\n bool should_ylikuutio_use_real_texture_coordinates;\n} BilinearInterpolationStruct;\n\ntypedef struct\n{\n uint32_t image_width;\n uint32_t image_height;\n double sphere_radius;\n bool is_bilinear_interpolation_in_use;\n SphericalWorldStruct spherical_world_struct;\n} TransformationStruct;\n\nnamespace callback_system\n{\n class CallbackEngine;\n class CallbackObject;\n class CallbackParameter;\n}\ntypedef datatypes::AnyValue* (*InputParametersToAnyValueCallback) (\n callback_system::CallbackEngine*,\n callback_system::CallbackObject*,\n std::vector<callback_system::CallbackParameter*>&);\n\nnamespace console\n{\n class Console;\n}\ntypedef datatypes::AnyValue* (*InputParametersToAnyValueCallbackWithConsole) (\n callback_system::CallbackEngine*,\n callback_system::CallbackObject*,\n std::vector<callback_system::CallbackParameter*>&,\n console::Console*);\n#endif\n<commit_msg>`typedef struct SpeciesStruct`, `world_radius`: `double` -> `float`.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include \"any_value.hpp\"\n\n\/\/ GCC (at least g++ 4.7.2) and Visual Studio 2015 do support\n\/\/ setting default values of a struct using C++11 syntax.\n\/\/ Clang 3.7.0 and Visual Studio 2013 do not support\n\/\/ setting default values of a struct using C++11 syntax.\n\/\/ Visual Studio 2013 fails to compile, whereas Clang-compiled\n\/\/ executable with code with setting default values of a struct\n\/\/ causes Segmentation fault upon execution of the program.\n\/\/ Compilers that don't support setting default values of a struct\n\/\/ are handled by setting the default values in a macro.\n\/\/ http:\/\/stackoverflow.com\/questions\/16782103\/initializing-default-values-in-a-struct\/16783513#16783513\n#ifdef __clang__\n#elif defined(__GNUC__)\n#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED\n#elif defined(_WIN32)\n#if (_MSC_VER >= 1900)\n#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED\n#endif\n#endif\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include <GL\/glew.h> \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include <glfw3.h>\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include <cmath> \/\/ NAN, std::isnan, std::pow\n#include <stdint.h> \/\/ uint32_t etc.\n#include <string> \/\/ std::string\n#include <vector> \/\/ std::vector\n\n#ifndef PI\n#define PI 3.14159265359f\n#endif\n\nnamespace ontology\n{\n class Universe;\n class Scene;\n class Shader;\n class Graph;\n class Material;\n class VectorFont;\n class Species;\n class Glyph;\n class Text3D;\n}\n\ntypedef struct ShaderStruct\n{\n ShaderStruct()\n : parent_pointer(nullptr)\n {\n \/\/ constructor.\n }\n ontology::Scene* parent_pointer; \/\/ pointer to the scene (draw list).\n std::string vertex_shader; \/\/ filename of vertex shader.\n std::string fragment_shader; \/\/ filename of fragment shader.\n} ShaderStruct;\n\ntypedef struct MaterialStruct\n{\n MaterialStruct()\n : parent_pointer(nullptr)\n {\n \/\/ constructor.\n }\n ontology::Shader* parent_pointer; \/\/ pointer to the shader.\n std::string texture_file_format; \/\/ type of the texture file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"dds\"`\/`\"DDS\"`.\n std::string texture_filename; \/\/ filename of the model file.\n std::string image_path;\n} MaterialStruct;\n\ntypedef struct NodeStruct\n{\n NodeStruct()\n : parent_pointer(nullptr)\n {\n \/\/ constructor.\n }\n GLuint nodeID;\n ontology::Graph* parent_pointer;\n glm::vec3 coordinate_vector;\n std::vector<uint32_t> neighbor_nodeIDs;\n} NodeStruct;\n\ntypedef struct ObjectStruct\n{\n ObjectStruct()\n : species_parent_pointer(nullptr), glyph_parent_pointer(nullptr), text3D_parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN), is_character(false)\n {\n \/\/ constructor.\n }\n ontology::Species* species_parent_pointer; \/\/ pointer to the parent `Species`.\n ontology::Glyph* glyph_parent_pointer; \/\/ pointer to the parent `Glyph`.\n ontology::Text3D* text3D_parent_pointer; \/\/ pointer to the parent `Text3D`.\n glm::vec3 original_scale_vector; \/\/ original scale vector.\n GLfloat rotate_angle; \/\/ rotate angle.\n bool is_character; \/\/ The parent of a character object is a Glyph. The parent of a regular object is a Species.\n glm::vec3 coordinate_vector; \/\/ coordinate vector.\n glm::vec3 rotate_vector; \/\/ rotate vector.\n glm::vec3 translate_vector; \/\/ translate vector.\n} ObjectStruct;\n\ntypedef struct SpeciesStruct\n{\n SpeciesStruct()\n : parent_pointer(nullptr), is_world(false), world_radius(NAN), triangulation_type(\"bilinear_interpolation\")\n {\n \/\/ constructor.\n }\n \/\/ used for all files (for all species).\n ontology::Material* parent_pointer; \/\/ pointer to the material object.\n bool is_world; \/\/ worlds currently do not rotate nor translate.\n float world_radius; \/\/ radius of sea level in kilometers. used only for worlds.\n std::string model_file_format; \/\/ type of the model file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"obj\"`\/`\"OBJ\"`.\n \/\/ TODO: add support for `\"SRTM\"`.\n std::string model_filename; \/\/ filename of the model file.\n \/\/ for `\"bmp\"` model files.\n std::string color_channel; \/\/ color channel to use for altitude data.\n\n glm::vec3 light_position; \/\/ light position.\n std::string coordinate_system; \/\/ used only for worlds (`is_world` == `true`). valid values: `\"cartesian\"`.\n \/\/ TODO: add support for `\"spherical\"`. `\"spherical\"` is used eg. in SRTM heightmaps.\n std::string triangulation_type;\n} SpeciesStruct;\n\n#define DEFAULT_VERTEX_SCALING_FACTOR (0.001f)\n\ntypedef struct VectorFontStruct\n{\n VectorFontStruct()\n : parent_pointer(nullptr), vertex_scaling_factor(DEFAULT_VERTEX_SCALING_FACTOR)\n {\n \/\/ constructor.\n }\n \/\/ used for all files (for all font).\n ontology::Material* parent_pointer; \/\/ pointer to the material object.\n GLfloat vertex_scaling_factor;\n std::string font_file_format; \/\/ type of the font file. supported file formats so far: `\"svg\"`\/`\"SVG\"`.\n std::string font_filename; \/\/ filename of the font file.\n} VectorFontStruct;\n\ntypedef struct Text3DStruct\n{\n Text3DStruct()\n : parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN)\n {\n \/\/ constructor.\n }\n ontology::VectorFont* parent_pointer; \/\/ pointer to the parent `VectorFont`.\n std::string text_string;\n const char* text_string_char;\n glm::vec3 original_scale_vector; \/\/ original scale vector.\n GLfloat rotate_angle; \/\/ rotate angle.\n glm::vec3 coordinate_vector; \/\/ coordinate vector.\n glm::vec3 rotate_vector; \/\/ rotate vector.\n glm::vec3 translate_vector; \/\/ translate vector.\n} Text3DStruct;\n\ntypedef struct GlyphStruct\n{\n GlyphStruct()\n : parent_pointer(nullptr)\n {\n \/\/ constructor.\n }\n \/\/ used for all files (for all glyph).\n std::vector<std::vector<glm::vec2>>* glyph_vertex_data;\n const char* glyph_name_pointer; \/\/ we need only a pointer, because glyphs are always created by the `VectorFont` constructor.\n const char* unicode_char_pointer; \/\/ we need only a pointer, because glyphs are always created by the `VectorFont` constructor.\n ontology::VectorFont* parent_pointer; \/\/ pointer to the font object.\n glm::vec3 light_position; \/\/ light position.\n} GlyphStruct;\n\ntypedef struct\n{\n GLuint screen_width;\n GLuint screen_height;\n GLuint x;\n GLuint y;\n GLuint text_size;\n GLuint font_size;\n std::string text;\n const char* text_char;\n const char* char_font_texture_file_format;\n const char* horizontal_alignment;\n const char* vertical_alignment;\n} PrintingStruct;\n\ntypedef struct\n{\n double rho;\n double theta;\n double phi;\n} SphericalCoordinatesStruct;\n\ntypedef struct SphericalWorldStruct\n{\n SphericalWorldStruct()\n :SRTM_latitude_step_in_degrees(1.0f\/1200.0f), SRTM_longitude_step_in_degrees(1.0f\/1200.0f)\n {\n \/\/ constructor.\n }\n double southern_latitude;\n double northern_latitude;\n double western_longitude;\n double eastern_longitude;\n double SRTM_latitude_step_in_degrees;\n double SRTM_longitude_step_in_degrees;\n} SphericalWorldStruct;\n\ntypedef struct TriangulateQuadsStruct\n{\n TriangulateQuadsStruct()\n : should_ylikuutio_use_real_texture_coordinates(true)\n {\n \/\/ constructor.\n }\n uint32_t image_width;\n uint32_t image_height;\n std::string triangulation_type;\n bool should_ylikuutio_use_real_texture_coordinates;\n double sphere_radius;\n SphericalWorldStruct spherical_world_struct;\n} TriangulateQuadsStruct;\n\ntypedef struct TriangulatePolygonsStruct\n{\n TriangulatePolygonsStruct()\n : should_ylikuutio_use_real_texture_coordinates(true)\n {\n \/\/ constructor.\n }\n std::vector<std::vector<glm::vec2>>* input_vertices;\n bool should_ylikuutio_use_real_texture_coordinates;\n} TriangulatePolygonsStruct;\n\ntypedef struct\n{\n uint32_t image_width;\n uint32_t image_height;\n bool should_ylikuutio_use_real_texture_coordinates;\n} BilinearInterpolationStruct;\n\ntypedef struct\n{\n uint32_t image_width;\n uint32_t image_height;\n double sphere_radius;\n bool is_bilinear_interpolation_in_use;\n SphericalWorldStruct spherical_world_struct;\n} TransformationStruct;\n\nnamespace callback_system\n{\n class CallbackEngine;\n class CallbackObject;\n class CallbackParameter;\n}\ntypedef datatypes::AnyValue* (*InputParametersToAnyValueCallback) (\n callback_system::CallbackEngine*,\n callback_system::CallbackObject*,\n std::vector<callback_system::CallbackParameter*>&);\n\nnamespace console\n{\n class Console;\n}\ntypedef datatypes::AnyValue* (*InputParametersToAnyValueCallbackWithConsole) (\n callback_system::CallbackEngine*,\n callback_system::CallbackObject*,\n std::vector<callback_system::CallbackParameter*>&,\n console::Console*);\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: gen_makefile.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2007-03-01 15:59: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_sal.hxx\"\n\n#include \"macro.hxx\"\n#include <stdio.h>\n\nint main()\n{\n printf( \"RTL_OS:=%s\\n\", THIS_OS );\n printf( \"RTL_ARCH:=%s\\n\", THIS_ARCH );\n return 0;\n}\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.160); FILE MERGED 2008\/03\/31 13:24:02 rt 1.2.160.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: gen_makefile.cxx,v $\n * $Revision: 1.3 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_sal.hxx\"\n\n#include \"macro.hxx\"\n#include <stdio.h>\n\nint main()\n{\n printf( \"RTL_OS:=%s\\n\", THIS_OS );\n printf( \"RTL_ARCH:=%s\\n\", THIS_ARCH );\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.3 2000\/02\/06 07:47:31 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.2 2000\/02\/04 01:49:27 aruna1\n * TreeWalker and NodeIterator changes\n *\n * Revision 1.1.1.1 1999\/11\/09 01:09:05 twl\n * Initial checkin\n *\n * Revision 1.3 1999\/11\/08 20:44:22 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n#ifndef DOM_TreeWalker_HEADER_GUARD_\n#define DOM_TreeWalker_HEADER_GUARD_\n\n#include \"DOM_Node.hpp\"\n#include \"DOM_NodeFilter.hpp\"\n\nclass TreeWalkerImpl;\n\n\nclass CDOM_EXPORT DOM_TreeWalker {\n\n public:\n\t\t\t\n\n DOM_TreeWalker ();\n DOM_TreeWalker (TreeWalkerImpl* impl);\n DOM_TreeWalker(const DOM_TreeWalker &other);\n DOM_TreeWalker & operator = (const DOM_TreeWalker &other);\n DOM_TreeWalker & operator = (const DOM_NullPtr *val);\n ~DOM_TreeWalker();\n bool operator == (const DOM_TreeWalker & other)const;\n bool operator == (const DOM_NullPtr *other) const;\n bool operator != (const DOM_TreeWalker & other) const;\n bool operator != (const DOM_NullPtr * other) const;\n\n unsigned long \t\t\t\tgetWhatToShow();\n DOM_NodeFilter*\t\t\t\t\tgetFilter();\n DOM_Node\t\t\t\t\t\tgetCurrentNode();\n void\t\t\t\t\t\t\tsetCurrentNode(DOM_Node currentNode);\n DOM_Node\t\t\t\t\t\tparentNode();\n DOM_Node\t\t\t\t\t\tfirstChild();\n DOM_Node\t\t\t\t\t\tlastChild();\n DOM_Node\t\t\t\t\t\tpreviousSibling();\n DOM_Node\t\t\t\t\t\tnextSibling();\n DOM_Node\t\t\t\t\t\tpreviousNode();\n DOM_Node\t\t\t\t\t\tnextNode();\n\n void\t\t\t\t\t\t\tdetach();\n\n private:\n TreeWalkerImpl* fImpl;\n};\n\n\n#endif\n<commit_msg>Added API docs<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.4 2000\/02\/11 01:05:11 abagchi\n * Added API docs\n *\n * Revision 1.3 2000\/02\/06 07:47:31 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.2 2000\/02\/04 01:49:27 aruna1\n * TreeWalker and NodeIterator changes\n *\n * Revision 1.1.1.1 1999\/11\/09 01:09:05 twl\n * Initial checkin\n *\n * Revision 1.3 1999\/11\/08 20:44:22 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n#ifndef DOM_TreeWalker_HEADER_GUARD_\n#define DOM_TreeWalker_HEADER_GUARD_\n\n#include \"DOM_Node.hpp\"\n#include \"DOM_NodeFilter.hpp\"\n\nclass TreeWalkerImpl;\n\n \/**\n * TreeWalker objects are used to navigate a document tree or subtree using the view of\n * the document defined by its <code>whatToShow<\/code> flags and any filters that are defined for the\n * TreeWalker. Any function which performs navigation using a TreeWalker will\n * automatically support any view defined by a TreeWalker.\n *\n * Omitting nodes from the logical view of a subtree can result in a structure that is\n * substantially different from the same subtree in the complete, unfiltered document. Nodes\n * that are siblings in the TreeWalker view may be children of different, widely separated\n * nodes in the original view. For instance, consider a Filter that skips all nodes except for\n * Text nodes and the root node of a document. In the logical view that results, all text\n * nodes will be siblings and appear as direct children of the root node, no matter how\n * deeply nested the structure of the original document.\n *\/\n\nclass CDOM_EXPORT DOM_TreeWalker {\n\n public:\n\t\t\t\n \/** @name Constructors *\/\n \/\/@{\n\n \/**\n * Default constructor\n *\/\n DOM_TreeWalker ();\n\n \/**\n * Copy constructor\n * @param other The object to be copied\n *\/\n DOM_TreeWalker(const DOM_TreeWalker &other);\n \/\/@}\n\n \/** @name Destructor *\/\n \/\/@{\n \/**\n * Destructor\n *\/\n ~DOM_TreeWalker();\n \/\/@}\n\n \/** @name Assignment operators *\/\n \/\/@{\n \/**\n * Assignment operator\n * @param other The object to be copied through assignment\n *\/\n DOM_TreeWalker & operator = (const DOM_TreeWalker &other);\n\n \/**\n * Assignment operator\n *\n * This overloaded variant is provided for\n * the sole purpose of setting a DOM_Node reference variable to\n * zero. Nulling out a reference variable in this way will decrement\n * the reference count on the underlying Node object that the variable\n * formerly referenced. This effect is normally obtained when reference\n * variable goes out of scope, but zeroing them can be useful for\n * global instances, or for local instances that will remain in scope\n * for an extended time, when the storage belonging to the underlying\n * node needs to be reclaimed.\n * @param val Only a value of 0, or null, is allowed.\n *\/\n DOM_TreeWalker & operator = (const DOM_NullPtr *val);\n \/\/@}\n\n \/** @name Equality operators *\/\n \/\/@{\n \/**\n * Test whether this TreeWalker reference refers to the same underlying\n * tree walker as the other reference object. This does not\n * compare the contents of two different objects.\n *\n * @param other The value to be compared\n * @return Returns true if the underlying tree walker object is same\n *\/\n bool operator == (const DOM_TreeWalker & other)const;\n\n \/**\n * Use this comparison operator to test whether a tree walker reference\n * is null.\n *\n * @param other The value to be compared, which must be 0 or null.\n * @return Returns true if the node iterator is null\n *\/\n bool operator == (const DOM_NullPtr *other) const;\n \/\/@}\n\n \/** @name Inequality operators *\/\n \/\/@{\n\n \/**\n * Test whether this TreeWalker reference refers to the same underlying\n * tree walker as the other reference object. This does not\n * compare the contents of two different objects.\n *\n * @param other The value to be compared\n * @return Returns true if the underlying tree walker is different\n *\/\n bool operator != (const DOM_TreeWalker & other) const;\n\n \/**\n * Use this comparison operator to test whether a tree walker reference\n * is null.\n *\n * @param other The value to be compared, which must be 0 or null.\n * @return Returns true if the node iterator is NOT null\n *\/\n bool operator != (const DOM_NullPtr * other) const;\n \/\/@}\n\n \/** @name Get Functions *\/\n \/\/@{\n \/**\n *\t Returns the value of <code>whatToShow<\/code>\n * This attribute determines which node types are presented via the\n * <code>TreeWalker<\/code>. The available set of constants is defined in the Filters\n * interface.\n *\/\n unsigned long \t\t\t\tgetWhatToShow();\n \/**\n *\tGet the filter used to screen nodes.\n *\/\n DOM_NodeFilter*\t\t\t\t\tgetFilter();\n \/**\n * Gets the node at which the tree walker is currently positioned.\n *\n * The value must not be null. Alterations to the DOM tree may cause the\n * current node to no longer be accepted by the TreeWalker's associated\n * filter. <code>currentNode<\/code> may also be explicitly set to any node, whether or not it\n * is within the subtree specified by the root node or would be accepted by\n * the filter and <code>whatToShow<\/code> flags. Further traversal occurs relative to\n * currentNode even if it is not part of the current view by applying the filters\n * in the requested direction (not changing <code>currentNode<\/code> where no traversal is\n * possible).\n *\/\n DOM_Node\t\t\t\t\t\tgetCurrentNode();\n \/\/@}\n\n \/** @name Set Functions *\/\n \/\/@{\n \/**\n * Sets the current node of the DOM tree in tree walker\n *\n * To know more about the current node see <code>getCurrentNode<\/code> description.\n * @see #getCurrentNode\n *\/\n void\t\t\t\t\t\t\tsetCurrentNode(DOM_Node currentNode);\n \/\/@}\n\n \/** @name Iterator Methods *\/\n \/\/@{\n\n \/**\n * Moves to and returns the closest visible ancestor node of the current node.\n * If the search for parentNode attempts to step upward from the\n * TreeWalker's root node, or if it fails to find a visible ancestor node, this\n * method retains the current position and returns null.\n *\n * @return The new parent node, or null if the current node has no parent in\n * the TreeWalker's logical view.\n *\/\n DOM_Node\t\t\t\t\t\tparentNode();\n\n \/**\n * Moves the TreeWalker to the first child of the current node, and returns the new node.\n * If the current node has no children, returns null, and retains\n * the current node\n * @return The new node, or null if the current node has no children.\n *\/\n DOM_Node\t\t\t\t\t\tfirstChild();\n\n \/**\n * Moves the TreeWalker to the last child of the current node, and returns the new node.\n * If the current node has no children, returns null, and retains\n * the current node.\n *\n * @return The new node, or null if the current node has no children.\n *\/\n DOM_Node\t\t\t\t\t\tlastChild();\n\n \/**\n * Moves the TreeWalker to the previous sibling of the current node, and returns the new node.\n * If the current node has no previous sibling, returns\n * <code>null<\/code>, and retains the current node.\n *\n * @return The new node, or null if the current node has no previous sibling.\n *\/\n DOM_Node\t\t\t\t\t\tpreviousSibling();\n\n \/**\n * Moves the TreeWalker to the next sibling of the current node, and returns the new node.\n * If the current node has no next sibling, returns <code>null<\/code>, and\n * retains the current node.\n *\n * @return The new node, or null if the current node has no next sibling.\n *\/\n DOM_Node\t\t\t\t\t\tnextSibling();\n\n \/**\n * Moves the TreeWalker to the previous visible node in document order relative to the current node, and returns the new node.\n * If the current node\n * has no previous node, or if the search for previousNode attempts to step\n * upward from the TreeWalker's root node, returns <code>null<\/code>, and retains the\n * current node.\n *\n * @return The new node, or null if the current <code>node<\/code> has no previous node.\n *\/\n DOM_Node\t\t\t\t\t\tpreviousNode();\n\n \/**\n * Moves the TreeWalker to the next visible node in document order relative to the current node, and returns the new node.\n * If the current node has no\n * next node, or if the search for nextNode attempts to step upward from the\n * TreeWalker's root node, returns null, and retains the current node.\n * @return The new node, or <code>null<\/code> if the current node has no next node.\n *\/\n DOM_Node\t\t\t\t\t\tnextNode();\n\n \/**\n *\t Detaches the iterator from the set which it iterated over, releasing any computational resources and placing the iterator in the INVALID state.\n * After detach has been invoked, calls to <code>nextNode<\/code> or <code>previousNode<\/code>\n * will raise the exception <code>INVALID_STATE_ERR<\/code>.\n *\/\n void\t\t\t\t\t\t\tdetach();\n \/\/@}\n\n private:\n TreeWalkerImpl* fImpl;\n\n protected:\n DOM_TreeWalker (TreeWalkerImpl* impl);\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/********************************************************************\n* Description: emcops.cc\n* Initialization and other ad hoc functions for NML. This complements\n* the auto-generated emc.cc, which contains all the rote update\n* methods for the message classes.\n*\n* Derived from a work by Fred Proctor & Will Shackleford\n*\n* Author:\n* License: GPL Version 2\n* System: Linux\n* \n* Copyright (c) 2004 All rights reserved.\n*\n* Last change:\n********************************************************************\/\n\n#include \"emc.hh\"\n#include \"emc_nml.hh\"\n\nEMC_AXIS_STAT::EMC_AXIS_STAT():\nEMC_AXIS_STAT_MSG(EMC_AXIS_STAT_TYPE, sizeof(EMC_AXIS_STAT))\n{\n axisType = EMC_AXIS_LINEAR;\n units = 1.0;\n backlash = 0.0;\n maxError = 0.0;\n minPositionLimit = -1.0;\n maxPositionLimit = 1.0;\n maxFerror = 1.0;\n ferrorCurrent = 0.0;\n ferrorHighMark = 0.0;\n output = 0.0;\n input = 0.0;\n inpos = 1;\n homing = 0;\n homed = 0;\n enabled = 0;\n fault = 0;\n minSoftLimit = 0;\n maxSoftLimit = 0;\n minHardLimit = 0;\n maxHardLimit = 0;\n overrideLimits = 0;\n}\n\nEMC_TRAJ_STAT::EMC_TRAJ_STAT():\nEMC_TRAJ_STAT_MSG(EMC_TRAJ_STAT_TYPE, sizeof(EMC_TRAJ_STAT))\n{\n linearUnits = 1.0;\n angularUnits = 1.0;\n cycleTime = 0.0;\n axes = 1;\n axis_mask = 1;\n mode = EMC_TRAJ_MODE_FREE;\n enabled = 0;\n inpos = 1;\n queue = 0;\n activeQueue = 0;\n queueFull = 0;\n id = 0;\n paused = 0;\n scale = 0.0;\n spindle_scale = 0.0;\n\n ZERO_EMC_POSE(position);\n ZERO_EMC_POSE(actualPosition);\n\n velocity = 1.0;\n acceleration = 1.0;\n maxVelocity = 1.0;\n maxAcceleration = 1.0;\n\n ZERO_EMC_POSE(probedPosition);\n probe_tripped = 0;\n probing = 0;\n probeval = 0;\n \n ZERO_EMC_POSE(dtg);\n distance_to_go = 0.0;\n kinematics_type = 0;\n motion_type = 0;\n current_vel = 0.0;\n feed_override_enabled = 0;\n spindle_override_enabled = 0;\n adaptive_feed_enabled = 0;\n feed_hold_enabled = 0;\n delayLeft = 0.0;\n}\n\nEMC_MOTION_STAT::EMC_MOTION_STAT():\nEMC_MOTION_STAT_MSG(EMC_MOTION_STAT_TYPE, sizeof(EMC_MOTION_STAT))\n{\n int i;\n\n for (i = 0; i < EMC_MAX_DIO; i++)\n\tsynch_di[i] = 0;\n\n for (i = 0; i < EMC_MAX_AIO; i++)\n\tanalog_input[i] = 0;\n \n debug = 0;\n};\n\nEMC_TASK_STAT::EMC_TASK_STAT():\nEMC_TASK_STAT_MSG(EMC_TASK_STAT_TYPE, sizeof(EMC_TASK_STAT))\n{\n int t;\n\n mode = EMC_TASK_MODE_MANUAL;\n state = EMC_TASK_STATE_ESTOP;\n execState = EMC_TASK_EXEC_DONE;\n interpState = EMC_TASK_INTERP_IDLE;\n motionLine = 0;\n currentLine = 0;\n readLine = 0;\n optional_stop_state = OFF;\n block_delete_state = OFF;\n input_timeout = OFF;\n file[0] = 0;\n command[0] = 0;\n\n ZERO_EMC_POSE(origin);\n ZERO_EMC_POSE(toolOffset);\n\n rotation_xy = 0.0;\n tloIsAlongW = OFF;\n\n for (t = 0; t < ACTIVE_G_CODES; t++)\n\tactiveGCodes[t] = -1;\n for (t = 0; t < ACTIVE_M_CODES; t++)\n\tactiveMCodes[t] = -1;\n for (t = 0; t < ACTIVE_SETTINGS; t++)\n\tactiveSettings[t] = 0.0;\n\n programUnits = CANON_UNITS_MM;\n interpreter_errcode = 0;\n task_paused = 0;\n}\n\nEMC_TOOL_STAT::EMC_TOOL_STAT():\nEMC_TOOL_STAT_MSG(EMC_TOOL_STAT_TYPE, sizeof(EMC_TOOL_STAT))\n{\n int t;\n\n toolPrepped = 0;\n toolInSpindle = 0;\n\n for (t = 0; t <= CANON_TOOL_MAX; t++) {\n\ttoolTable[t].id = 0;\n\ttoolTable[t].xoffset = 0.0;\n\ttoolTable[t].zoffset = 0.0;\n\ttoolTable[t].diameter = 0.0;\n\ttoolTable[t].orientation = 0;\n\ttoolTable[t].frontangle = 0.0;\n\ttoolTable[t].backangle = 0.0;\n }\n}\n\nEMC_AUX_STAT::EMC_AUX_STAT():\nEMC_AUX_STAT_MSG(EMC_AUX_STAT_TYPE, sizeof(EMC_AUX_STAT))\n{\n int t;\n\n estop = 1;\n\n for (t = 0; t < EMC_AUX_MAX_DOUT; t++) {\n\tdout[t] = 0;\n }\n\n for (t = 0; t < EMC_AUX_MAX_DIN; t++) {\n\tdin[t] = 0;\n }\n\n for (t = 0; t < EMC_AUX_MAX_AOUT; t++) {\n\taout[t] = 0;\n }\n\n for (t = 0; t < EMC_AUX_MAX_AIN; t++) {\n\tain[t] = 0;\n }\n}\n\nEMC_SPINDLE_STAT::EMC_SPINDLE_STAT():\nEMC_SPINDLE_STAT_MSG(EMC_SPINDLE_STAT_TYPE, sizeof(EMC_SPINDLE_STAT))\n{\n speed = 0.0;\n direction = 0;\n brake = 1;\n increasing = 0;\n enabled = 0;\n}\n\nEMC_COOLANT_STAT::EMC_COOLANT_STAT():EMC_COOLANT_STAT_MSG(EMC_COOLANT_STAT_TYPE,\n\t\t sizeof\n\t\t (EMC_COOLANT_STAT))\n{\n mist = 0;\n flood = 0;\n}\n\nEMC_LUBE_STAT::EMC_LUBE_STAT():\nEMC_LUBE_STAT_MSG(EMC_LUBE_STAT_TYPE, sizeof(EMC_LUBE_STAT))\n{\n on = 0;\n level = 1;\n}\n\n\/\/ overload = , since class has array elements\nEMC_TOOL_STAT EMC_TOOL_STAT::operator =(EMC_TOOL_STAT s)\n{\n int t;\n\n toolPrepped = s.toolPrepped;\n toolInSpindle = s.toolInSpindle;\n\n for (t = 0; t <= CANON_TOOL_MAX; t++) {\n\ttoolTable[t].id = s.toolTable[t].id;\n\ttoolTable[t].xoffset = s.toolTable[t].xoffset;\n\ttoolTable[t].zoffset = s.toolTable[t].zoffset;\n\ttoolTable[t].diameter = s.toolTable[t].diameter;\n\ttoolTable[t].frontangle = s.toolTable[t].frontangle;\n\ttoolTable[t].backangle = s.toolTable[t].backangle;\n\ttoolTable[t].orientation = s.toolTable[t].orientation;\n }\n\n return s;\n}\n\n\/\/ overload = , since class has array elements\nEMC_AUX_STAT EMC_AUX_STAT::operator =(EMC_AUX_STAT s)\n{\n int t;\n\n estop = s.estop;\n\n for (t = 0; t < EMC_AUX_MAX_DOUT; t++) {\n\tdout[t] = s.dout[t];\n }\n\n for (t = 0; t < EMC_AUX_MAX_DIN; t++) {\n\tdin[t] = s.din[t];\n }\n\n for (t = 0; t < EMC_AUX_MAX_AOUT; t++) {\n\taout[t] = s.aout[t];\n }\n\n for (t = 0; t < EMC_AUX_MAX_AIN; t++) {\n\tain[t] = s.ain[t];\n }\n\n return s;\n}\n\nEMC_STAT::EMC_STAT():EMC_STAT_MSG(EMC_STAT_TYPE, sizeof(EMC_STAT))\n{\n}\n<commit_msg>Add last missing field of EMC_AXIS_STAT Signed-off-by: Michael Geszkiewicz <micges@wp.pl><commit_after>\/********************************************************************\n* Description: emcops.cc\n* Initialization and other ad hoc functions for NML. This complements\n* the auto-generated emc.cc, which contains all the rote update\n* methods for the message classes.\n*\n* Derived from a work by Fred Proctor & Will Shackleford\n*\n* Author:\n* License: GPL Version 2\n* System: Linux\n* \n* Copyright (c) 2004 All rights reserved.\n*\n* Last change:\n********************************************************************\/\n\n#include \"emc.hh\"\n#include \"emc_nml.hh\"\n\nEMC_AXIS_STAT::EMC_AXIS_STAT():\nEMC_AXIS_STAT_MSG(EMC_AXIS_STAT_TYPE, sizeof(EMC_AXIS_STAT))\n{\n axisType = EMC_AXIS_LINEAR;\n units = 1.0;\n backlash = 0.0;\n maxError = 0.0;\n minPositionLimit = -1.0;\n maxPositionLimit = 1.0;\n minFerror = 1.0;\n maxFerror = 1.0;\n ferrorCurrent = 0.0;\n ferrorHighMark = 0.0;\n output = 0.0;\n input = 0.0;\n inpos = 1;\n homing = 0;\n homed = 0;\n enabled = 0;\n fault = 0;\n minSoftLimit = 0;\n maxSoftLimit = 0;\n minHardLimit = 0;\n maxHardLimit = 0;\n overrideLimits = 0;\n}\n\nEMC_TRAJ_STAT::EMC_TRAJ_STAT():\nEMC_TRAJ_STAT_MSG(EMC_TRAJ_STAT_TYPE, sizeof(EMC_TRAJ_STAT))\n{\n linearUnits = 1.0;\n angularUnits = 1.0;\n cycleTime = 0.0;\n axes = 1;\n axis_mask = 1;\n mode = EMC_TRAJ_MODE_FREE;\n enabled = 0;\n inpos = 1;\n queue = 0;\n activeQueue = 0;\n queueFull = 0;\n id = 0;\n paused = 0;\n scale = 0.0;\n spindle_scale = 0.0;\n\n ZERO_EMC_POSE(position);\n ZERO_EMC_POSE(actualPosition);\n\n velocity = 1.0;\n acceleration = 1.0;\n maxVelocity = 1.0;\n maxAcceleration = 1.0;\n\n ZERO_EMC_POSE(probedPosition);\n probe_tripped = 0;\n probing = 0;\n probeval = 0;\n \n ZERO_EMC_POSE(dtg);\n distance_to_go = 0.0;\n kinematics_type = 0;\n motion_type = 0;\n current_vel = 0.0;\n feed_override_enabled = 0;\n spindle_override_enabled = 0;\n adaptive_feed_enabled = 0;\n feed_hold_enabled = 0;\n delayLeft = 0.0;\n}\n\nEMC_MOTION_STAT::EMC_MOTION_STAT():\nEMC_MOTION_STAT_MSG(EMC_MOTION_STAT_TYPE, sizeof(EMC_MOTION_STAT))\n{\n int i;\n\n for (i = 0; i < EMC_MAX_DIO; i++)\n\tsynch_di[i] = 0;\n\n for (i = 0; i < EMC_MAX_AIO; i++)\n\tanalog_input[i] = 0;\n \n debug = 0;\n};\n\nEMC_TASK_STAT::EMC_TASK_STAT():\nEMC_TASK_STAT_MSG(EMC_TASK_STAT_TYPE, sizeof(EMC_TASK_STAT))\n{\n int t;\n\n mode = EMC_TASK_MODE_MANUAL;\n state = EMC_TASK_STATE_ESTOP;\n execState = EMC_TASK_EXEC_DONE;\n interpState = EMC_TASK_INTERP_IDLE;\n motionLine = 0;\n currentLine = 0;\n readLine = 0;\n optional_stop_state = OFF;\n block_delete_state = OFF;\n input_timeout = OFF;\n file[0] = 0;\n command[0] = 0;\n\n ZERO_EMC_POSE(origin);\n ZERO_EMC_POSE(toolOffset);\n\n rotation_xy = 0.0;\n tloIsAlongW = OFF;\n\n for (t = 0; t < ACTIVE_G_CODES; t++)\n\tactiveGCodes[t] = -1;\n for (t = 0; t < ACTIVE_M_CODES; t++)\n\tactiveMCodes[t] = -1;\n for (t = 0; t < ACTIVE_SETTINGS; t++)\n\tactiveSettings[t] = 0.0;\n\n programUnits = CANON_UNITS_MM;\n interpreter_errcode = 0;\n task_paused = 0;\n}\n\nEMC_TOOL_STAT::EMC_TOOL_STAT():\nEMC_TOOL_STAT_MSG(EMC_TOOL_STAT_TYPE, sizeof(EMC_TOOL_STAT))\n{\n int t;\n\n toolPrepped = 0;\n toolInSpindle = 0;\n\n for (t = 0; t <= CANON_TOOL_MAX; t++) {\n\ttoolTable[t].id = 0;\n\ttoolTable[t].xoffset = 0.0;\n\ttoolTable[t].zoffset = 0.0;\n\ttoolTable[t].diameter = 0.0;\n\ttoolTable[t].orientation = 0;\n\ttoolTable[t].frontangle = 0.0;\n\ttoolTable[t].backangle = 0.0;\n }\n}\n\nEMC_AUX_STAT::EMC_AUX_STAT():\nEMC_AUX_STAT_MSG(EMC_AUX_STAT_TYPE, sizeof(EMC_AUX_STAT))\n{\n int t;\n\n estop = 1;\n\n for (t = 0; t < EMC_AUX_MAX_DOUT; t++) {\n\tdout[t] = 0;\n }\n\n for (t = 0; t < EMC_AUX_MAX_DIN; t++) {\n\tdin[t] = 0;\n }\n\n for (t = 0; t < EMC_AUX_MAX_AOUT; t++) {\n\taout[t] = 0;\n }\n\n for (t = 0; t < EMC_AUX_MAX_AIN; t++) {\n\tain[t] = 0;\n }\n}\n\nEMC_SPINDLE_STAT::EMC_SPINDLE_STAT():\nEMC_SPINDLE_STAT_MSG(EMC_SPINDLE_STAT_TYPE, sizeof(EMC_SPINDLE_STAT))\n{\n speed = 0.0;\n direction = 0;\n brake = 1;\n increasing = 0;\n enabled = 0;\n}\n\nEMC_COOLANT_STAT::EMC_COOLANT_STAT():EMC_COOLANT_STAT_MSG(EMC_COOLANT_STAT_TYPE,\n\t\t sizeof\n\t\t (EMC_COOLANT_STAT))\n{\n mist = 0;\n flood = 0;\n}\n\nEMC_LUBE_STAT::EMC_LUBE_STAT():\nEMC_LUBE_STAT_MSG(EMC_LUBE_STAT_TYPE, sizeof(EMC_LUBE_STAT))\n{\n on = 0;\n level = 1;\n}\n\n\/\/ overload = , since class has array elements\nEMC_TOOL_STAT EMC_TOOL_STAT::operator =(EMC_TOOL_STAT s)\n{\n int t;\n\n toolPrepped = s.toolPrepped;\n toolInSpindle = s.toolInSpindle;\n\n for (t = 0; t <= CANON_TOOL_MAX; t++) {\n\ttoolTable[t].id = s.toolTable[t].id;\n\ttoolTable[t].xoffset = s.toolTable[t].xoffset;\n\ttoolTable[t].zoffset = s.toolTable[t].zoffset;\n\ttoolTable[t].diameter = s.toolTable[t].diameter;\n\ttoolTable[t].frontangle = s.toolTable[t].frontangle;\n\ttoolTable[t].backangle = s.toolTable[t].backangle;\n\ttoolTable[t].orientation = s.toolTable[t].orientation;\n }\n\n return s;\n}\n\n\/\/ overload = , since class has array elements\nEMC_AUX_STAT EMC_AUX_STAT::operator =(EMC_AUX_STAT s)\n{\n int t;\n\n estop = s.estop;\n\n for (t = 0; t < EMC_AUX_MAX_DOUT; t++) {\n\tdout[t] = s.dout[t];\n }\n\n for (t = 0; t < EMC_AUX_MAX_DIN; t++) {\n\tdin[t] = s.din[t];\n }\n\n for (t = 0; t < EMC_AUX_MAX_AOUT; t++) {\n\taout[t] = s.aout[t];\n }\n\n for (t = 0; t < EMC_AUX_MAX_AIN; t++) {\n\tain[t] = s.ain[t];\n }\n\n return s;\n}\n\nEMC_STAT::EMC_STAT():EMC_STAT_MSG(EMC_STAT_TYPE, sizeof(EMC_STAT))\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"palette.hpp\"\n\n\/\/ node\n#include <node_buffer.h>\n\n\/\/ stl\n#include <vector>\n#include <iomanip>\n#include <sstream>\n\n\nusing namespace v8;\n\nrgb::rgb(rgba const& c)\n : r(c.r), g(c.g), b(c.b) {}\n\n\/\/ ordering by mean(a,r,g,b), a, r, g, b\nbool rgba::mean_sort_cmp::operator() (const rgba& x, const rgba& y) const\n{\n int t1 = (int)x.a + x.r + x.g + x.b;\n int t2 = (int)y.a + y.r + y.g + y.b;\n if (t1 != t2) return t1 < t2;\n\n \/\/ https:\/\/github.com\/mapnik\/mapnik\/issues\/1087\n if (x.a != y.a) return x.a < y.a;\n if (x.r != y.r) return x.r < y.r;\n if (x.g != y.g) return x.g < y.g;\n return x.b < y.b;\n}\n\nstd::size_t rgba::hash_func::operator()(rgba const& p) const\n{\n return ((std::size_t)p.r * 33023 + (std::size_t)p.g * 30013 +\n (std::size_t)p.b * 27011 + (std::size_t)p.a * 24007) % 21001;\n}\n\n\nrgba_palette::rgba_palette(std::string const& pal, palette_type type)\n : colors_(0)\n{\n parse(pal, type);\n}\n\nrgba_palette::rgba_palette()\n : colors_(0) {}\n\nconst std::vector<rgb>& rgba_palette::palette() const\n{\n return rgb_pal_;\n}\n\nconst std::vector<unsigned>& rgba_palette::alphaTable() const\n{\n return alpha_pal_;\n}\n\nbool rgba_palette::valid() const\n{\n return colors_ > 0;\n}\n\n\/\/ return color index in returned earlier palette\nunsigned rgba_palette::quantize(rgba const& c) const\n{\n unsigned index = 0;\n if (colors_ == 1) return index;\n\n rgba_hash_table::iterator it = color_hashmap_.find(c);\n if (it != color_hashmap_.end())\n {\n index = it->second;\n }\n else\n {\n int dr, dg, db, da;\n int dist, newdist;\n\n \/\/ find closest match based on mean of r,g,b,a\n std::vector<rgba>::const_iterator pit =\n std::lower_bound(sorted_pal_.begin(), sorted_pal_.end(), c, rgba::mean_sort_cmp());\n index = pit - sorted_pal_.begin();\n if (index == sorted_pal_.size()) index--;\n\n dr = sorted_pal_[index].r - c.r;\n dg = sorted_pal_[index].g - c.g;\n db = sorted_pal_[index].b - c.b;\n da = sorted_pal_[index].a - c.a;\n dist = dr*dr + dg*dg + db*db + da*da;\n int poz = index;\n\n \/\/ search neighbour positions in both directions for better match\n for (int i = poz - 1; i >= 0; i--)\n {\n dr = sorted_pal_[i].r - c.r;\n dg = sorted_pal_[i].g - c.g;\n db = sorted_pal_[i].b - c.b;\n da = sorted_pal_[i].a - c.a;\n \/\/ stop criteria based on properties of used sorting\n if ((dr+db+dg+da) * (dr+db+dg+da) \/ 4 > dist)\n {\n break;\n }\n newdist = dr*dr + dg*dg + db*db + da*da;\n if (newdist < dist)\n {\n index = i;\n dist = newdist;\n }\n }\n\n for (unsigned i = poz + 1; i < sorted_pal_.size(); i++)\n {\n dr = sorted_pal_[i].r - c.r;\n dg = sorted_pal_[i].g - c.g;\n db = sorted_pal_[i].b - c.b;\n da = sorted_pal_[i].a - c.a;\n \/\/ stop criteria based on properties of used sorting\n if ((dr+db+dg+da) * (dr+db+dg+da) \/ 4 > dist)\n {\n break;\n }\n newdist = dr*dr + dg*dg + db*db + da*da;\n if (newdist < dist)\n {\n index = i;\n dist = newdist;\n }\n }\n\n \/\/ Cache found index for the color c into the hashmap.\n color_hashmap_[c] = index;\n }\n\n return index;\n}\n\nvoid rgba_palette::parse(std::string const& pal, palette_type type)\n{\n unsigned length = pal.length();\n\n if ((type == PALETTE_RGBA && length % 4 > 0) ||\n (type == PALETTE_RGB && length % 3 > 0) ||\n (type == PALETTE_ACT && length != 772))\n {\n return;\n }\n\n if (type == PALETTE_ACT)\n {\n length = (pal[768] << 8 | pal[769]) * 3;\n }\n\n sorted_pal_.clear();\n color_hashmap_.clear();\n rgb_pal_.clear();\n alpha_pal_.clear();\n\n if (type == PALETTE_RGBA)\n {\n for (unsigned i = 0; i < length; i += 4)\n {\n sorted_pal_.push_back(rgba(pal[i], pal[i + 1], pal[i + 2], pal[i + 3]));\n }\n }\n else\n {\n for (unsigned i = 0; i < length; i += 3)\n {\n sorted_pal_.push_back(rgba(pal[i], pal[i + 1], pal[i + 2], 0xFF));\n }\n }\n\n \/\/ Make sure we have at least one entry in the palette.\n if (sorted_pal_.size() == 0)\n {\n sorted_pal_.push_back(rgba(0, 0, 0, 0));\n }\n\n colors_ = sorted_pal_.size();\n\n \/\/ Sort palette for binary searching in quantization\n std::sort(sorted_pal_.begin(), sorted_pal_.end(), rgba::mean_sort_cmp());\n\n \/\/ Insert all palette colors into the hashmap and into the palette vectors.\n for (unsigned i = 0; i < colors_; i++)\n {\n rgba c = sorted_pal_[i];\n color_hashmap_[c] = i;\n rgb_pal_.push_back(rgb(c));\n if (c.a < 0xFF)\n {\n alpha_pal_.push_back(c.a);\n }\n }\n}\n\n\/\/ ------- node implementation -------\n\n\nPersistent<FunctionTemplate> Palette::constructor;\n\nvoid Palette::Initialize(Handle<Object> target) {\n HandleScope scope;\n\n constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Palette::New));\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(String::NewSymbol(\"Palette\"));\n\n NODE_SET_PROTOTYPE_METHOD(constructor, \"toString\", ToString);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"toBuffer\", ToBuffer);\n\n target->Set(String::NewSymbol(\"Palette\"), constructor->GetFunction());\n}\n\nPalette::Palette(std::string const& palette, rgba_palette::palette_type type) :\n ObjectWrap(),\n palette_(new rgba_palette(palette, type)) {}\n\nPalette::~Palette() {\n}\n\nHandle<Value> Palette::New(const Arguments& args) {\n HandleScope scope;\n\n if (!args.IsConstructCall()) {\n return ThrowException(String::New(\"Cannot call constructor as function, you need to use 'new' keyword\"));\n }\n\n std::string palette;\n rgba_palette::palette_type type = rgba_palette::PALETTE_RGBA;\n if (args.Length() >= 1) {\n if (args[0]->IsString()) {\n String::AsciiValue obj(args[0]->ToString());\n palette = std::string(*obj, obj.length());\n }\n else if (node::Buffer::HasInstance(args[0])) {\n Local<Object> obj = args[0]->ToObject();\n palette = std::string(node::Buffer::Data(obj), node::Buffer::Length(obj));\n }\n }\n if (args.Length() >= 2) {\n if (args[1]->IsString()) {\n std::string obj = *String::Utf8Value(args[1]->ToString());\n if (obj == \"rgb\") type = rgba_palette::PALETTE_RGB;\n else if (obj == \"act\") type = rgba_palette::PALETTE_ACT;\n }\n }\n\n if (!palette.length()) {\n return ThrowException(Exception::TypeError(\n String::New(\"First parameter must be a palette string\")));\n }\n\n Palette* p = new Palette(palette, type);\n if (!p->palette()->valid()) {\n delete p;\n return ThrowException(Exception::TypeError(String::New(\"Invalid palette length\")));\n } else {\n p->Wrap(args.This());\n return args.This();\n }\n}\n\nHandle<Value> Palette::ToString(const Arguments& args)\n{\n HandleScope scope;\n palette_ptr p = ObjectWrap::Unwrap<Palette>(args.This())->palette_;\n\n const std::vector<rgb>& colors = p->palette();\n unsigned length = colors.size();\n const std::vector<unsigned>& alpha = p->alphaTable();\n unsigned alphaLength = alpha.size();\n\n std::ostringstream str(\"\");\n str << \"[Palette \" << length;\n if (length == 1) str << \" color\";\n else str << \" colors\";\n\n str << std::hex << std::setfill('0');\n\n for (unsigned i = 0; i < length; i++) {\n str << \" #\";\n str << std::setw(2) << (unsigned)colors[i].r;\n str << std::setw(2) << (unsigned)colors[i].g;\n str << std::setw(2) << (unsigned)colors[i].b;\n if (i < alphaLength) str << std::setw(2) << alpha[i];\n }\n\n str << \"]\";\n return scope.Close(String::New(str.str().c_str()));\n}\n\nHandle<Value> Palette::ToBuffer(const Arguments& args)\n{\n HandleScope scope;\n\n palette_ptr p = ObjectWrap::Unwrap<Palette>(args.This())->palette_;\n\n const std::vector<rgb>& colors = p->palette();\n unsigned length = colors.size();\n const std::vector<unsigned>& alpha = p->alphaTable();\n unsigned alphaLength = alpha.size();\n\n char palette[256 * 4];\n for (unsigned i = 0, pos = 0; i < length; i++) {\n palette[pos++] = colors[i].r;\n palette[pos++] = colors[i].g;\n palette[pos++] = colors[i].b;\n palette[pos++] = (i < alphaLength) ? alpha[i] : 0xFF;\n }\n\n node::Buffer *buffer = node::Buffer::New(palette, length * 4);\n return scope.Close(buffer->handle_);\n}\n\n<commit_msg>include algorithm<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"palette.hpp\"\n\n\/\/ node\n#include <node_buffer.h>\n\n\/\/ stl\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <algorithm>\n\n\nusing namespace v8;\n\nrgb::rgb(rgba const& c)\n : r(c.r), g(c.g), b(c.b) {}\n\n\/\/ ordering by mean(a,r,g,b), a, r, g, b\nbool rgba::mean_sort_cmp::operator() (const rgba& x, const rgba& y) const\n{\n int t1 = (int)x.a + x.r + x.g + x.b;\n int t2 = (int)y.a + y.r + y.g + y.b;\n if (t1 != t2) return t1 < t2;\n\n \/\/ https:\/\/github.com\/mapnik\/mapnik\/issues\/1087\n if (x.a != y.a) return x.a < y.a;\n if (x.r != y.r) return x.r < y.r;\n if (x.g != y.g) return x.g < y.g;\n return x.b < y.b;\n}\n\nstd::size_t rgba::hash_func::operator()(rgba const& p) const\n{\n return ((std::size_t)p.r * 33023 + (std::size_t)p.g * 30013 +\n (std::size_t)p.b * 27011 + (std::size_t)p.a * 24007) % 21001;\n}\n\n\nrgba_palette::rgba_palette(std::string const& pal, palette_type type)\n : colors_(0)\n{\n parse(pal, type);\n}\n\nrgba_palette::rgba_palette()\n : colors_(0) {}\n\nconst std::vector<rgb>& rgba_palette::palette() const\n{\n return rgb_pal_;\n}\n\nconst std::vector<unsigned>& rgba_palette::alphaTable() const\n{\n return alpha_pal_;\n}\n\nbool rgba_palette::valid() const\n{\n return colors_ > 0;\n}\n\n\/\/ return color index in returned earlier palette\nunsigned rgba_palette::quantize(rgba const& c) const\n{\n unsigned index = 0;\n if (colors_ == 1) return index;\n\n rgba_hash_table::iterator it = color_hashmap_.find(c);\n if (it != color_hashmap_.end())\n {\n index = it->second;\n }\n else\n {\n int dr, dg, db, da;\n int dist, newdist;\n\n \/\/ find closest match based on mean of r,g,b,a\n std::vector<rgba>::const_iterator pit =\n std::lower_bound(sorted_pal_.begin(), sorted_pal_.end(), c, rgba::mean_sort_cmp());\n index = pit - sorted_pal_.begin();\n if (index == sorted_pal_.size()) index--;\n\n dr = sorted_pal_[index].r - c.r;\n dg = sorted_pal_[index].g - c.g;\n db = sorted_pal_[index].b - c.b;\n da = sorted_pal_[index].a - c.a;\n dist = dr*dr + dg*dg + db*db + da*da;\n int poz = index;\n\n \/\/ search neighbour positions in both directions for better match\n for (int i = poz - 1; i >= 0; i--)\n {\n dr = sorted_pal_[i].r - c.r;\n dg = sorted_pal_[i].g - c.g;\n db = sorted_pal_[i].b - c.b;\n da = sorted_pal_[i].a - c.a;\n \/\/ stop criteria based on properties of used sorting\n if ((dr+db+dg+da) * (dr+db+dg+da) \/ 4 > dist)\n {\n break;\n }\n newdist = dr*dr + dg*dg + db*db + da*da;\n if (newdist < dist)\n {\n index = i;\n dist = newdist;\n }\n }\n\n for (unsigned i = poz + 1; i < sorted_pal_.size(); i++)\n {\n dr = sorted_pal_[i].r - c.r;\n dg = sorted_pal_[i].g - c.g;\n db = sorted_pal_[i].b - c.b;\n da = sorted_pal_[i].a - c.a;\n \/\/ stop criteria based on properties of used sorting\n if ((dr+db+dg+da) * (dr+db+dg+da) \/ 4 > dist)\n {\n break;\n }\n newdist = dr*dr + dg*dg + db*db + da*da;\n if (newdist < dist)\n {\n index = i;\n dist = newdist;\n }\n }\n\n \/\/ Cache found index for the color c into the hashmap.\n color_hashmap_[c] = index;\n }\n\n return index;\n}\n\nvoid rgba_palette::parse(std::string const& pal, palette_type type)\n{\n unsigned length = pal.length();\n\n if ((type == PALETTE_RGBA && length % 4 > 0) ||\n (type == PALETTE_RGB && length % 3 > 0) ||\n (type == PALETTE_ACT && length != 772))\n {\n return;\n }\n\n if (type == PALETTE_ACT)\n {\n length = (pal[768] << 8 | pal[769]) * 3;\n }\n\n sorted_pal_.clear();\n color_hashmap_.clear();\n rgb_pal_.clear();\n alpha_pal_.clear();\n\n if (type == PALETTE_RGBA)\n {\n for (unsigned i = 0; i < length; i += 4)\n {\n sorted_pal_.push_back(rgba(pal[i], pal[i + 1], pal[i + 2], pal[i + 3]));\n }\n }\n else\n {\n for (unsigned i = 0; i < length; i += 3)\n {\n sorted_pal_.push_back(rgba(pal[i], pal[i + 1], pal[i + 2], 0xFF));\n }\n }\n\n \/\/ Make sure we have at least one entry in the palette.\n if (sorted_pal_.size() == 0)\n {\n sorted_pal_.push_back(rgba(0, 0, 0, 0));\n }\n\n colors_ = sorted_pal_.size();\n\n \/\/ Sort palette for binary searching in quantization\n std::sort(sorted_pal_.begin(), sorted_pal_.end(), rgba::mean_sort_cmp());\n\n \/\/ Insert all palette colors into the hashmap and into the palette vectors.\n for (unsigned i = 0; i < colors_; i++)\n {\n rgba c = sorted_pal_[i];\n color_hashmap_[c] = i;\n rgb_pal_.push_back(rgb(c));\n if (c.a < 0xFF)\n {\n alpha_pal_.push_back(c.a);\n }\n }\n}\n\n\/\/ ------- node implementation -------\n\n\nPersistent<FunctionTemplate> Palette::constructor;\n\nvoid Palette::Initialize(Handle<Object> target) {\n HandleScope scope;\n\n constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Palette::New));\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(String::NewSymbol(\"Palette\"));\n\n NODE_SET_PROTOTYPE_METHOD(constructor, \"toString\", ToString);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"toBuffer\", ToBuffer);\n\n target->Set(String::NewSymbol(\"Palette\"), constructor->GetFunction());\n}\n\nPalette::Palette(std::string const& palette, rgba_palette::palette_type type) :\n ObjectWrap(),\n palette_(new rgba_palette(palette, type)) {}\n\nPalette::~Palette() {\n}\n\nHandle<Value> Palette::New(const Arguments& args) {\n HandleScope scope;\n\n if (!args.IsConstructCall()) {\n return ThrowException(String::New(\"Cannot call constructor as function, you need to use 'new' keyword\"));\n }\n\n std::string palette;\n rgba_palette::palette_type type = rgba_palette::PALETTE_RGBA;\n if (args.Length() >= 1) {\n if (args[0]->IsString()) {\n String::AsciiValue obj(args[0]->ToString());\n palette = std::string(*obj, obj.length());\n }\n else if (node::Buffer::HasInstance(args[0])) {\n Local<Object> obj = args[0]->ToObject();\n palette = std::string(node::Buffer::Data(obj), node::Buffer::Length(obj));\n }\n }\n if (args.Length() >= 2) {\n if (args[1]->IsString()) {\n std::string obj = *String::Utf8Value(args[1]->ToString());\n if (obj == \"rgb\") type = rgba_palette::PALETTE_RGB;\n else if (obj == \"act\") type = rgba_palette::PALETTE_ACT;\n }\n }\n\n if (!palette.length()) {\n return ThrowException(Exception::TypeError(\n String::New(\"First parameter must be a palette string\")));\n }\n\n Palette* p = new Palette(palette, type);\n if (!p->palette()->valid()) {\n delete p;\n return ThrowException(Exception::TypeError(String::New(\"Invalid palette length\")));\n } else {\n p->Wrap(args.This());\n return args.This();\n }\n}\n\nHandle<Value> Palette::ToString(const Arguments& args)\n{\n HandleScope scope;\n palette_ptr p = ObjectWrap::Unwrap<Palette>(args.This())->palette_;\n\n const std::vector<rgb>& colors = p->palette();\n unsigned length = colors.size();\n const std::vector<unsigned>& alpha = p->alphaTable();\n unsigned alphaLength = alpha.size();\n\n std::ostringstream str(\"\");\n str << \"[Palette \" << length;\n if (length == 1) str << \" color\";\n else str << \" colors\";\n\n str << std::hex << std::setfill('0');\n\n for (unsigned i = 0; i < length; i++) {\n str << \" #\";\n str << std::setw(2) << (unsigned)colors[i].r;\n str << std::setw(2) << (unsigned)colors[i].g;\n str << std::setw(2) << (unsigned)colors[i].b;\n if (i < alphaLength) str << std::setw(2) << alpha[i];\n }\n\n str << \"]\";\n return scope.Close(String::New(str.str().c_str()));\n}\n\nHandle<Value> Palette::ToBuffer(const Arguments& args)\n{\n HandleScope scope;\n\n palette_ptr p = ObjectWrap::Unwrap<Palette>(args.This())->palette_;\n\n const std::vector<rgb>& colors = p->palette();\n unsigned length = colors.size();\n const std::vector<unsigned>& alpha = p->alphaTable();\n unsigned alphaLength = alpha.size();\n\n char palette[256 * 4];\n for (unsigned i = 0, pos = 0; i < length; i++) {\n palette[pos++] = colors[i].r;\n palette[pos++] = colors[i].g;\n palette[pos++] = colors[i].b;\n palette[pos++] = (i < alphaLength) ? alpha[i] : 0xFF;\n }\n\n node::Buffer *buffer = node::Buffer::New(palette, length * 4);\n return scope.Close(buffer->handle_);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <pb_view.h>\n#include <pb_controller.h>\n#include <poddlthread.h>\n#include <download.h>\n#include <config.h>\n#include <logger.h>\n\n#include <dllist.h>\n#include <help.h>\n#include <utils.h>\n\n#include <sstream>\n#include <iostream>\n#include <cstring>\n\nusing namespace newsbeuter;\n\nnamespace podbeuter {\n\npb_view::pb_view(pb_controller * c) : ctrl(c), dllist_form(dllist_str), help_form(help_str), keys(0) {\n}\n\npb_view::~pb_view() {\n\tstfl::reset();\n}\n\nvoid pb_view::run(bool auto_download) {\n\tbool quit = false;\n\n\tset_dllist_keymap_hint();\n\n\tdo {\n\n\t\tif (ctrl->view_update_necessary()) {\n\n\t\t\tdouble total_kbps = ctrl->get_total_kbps();\n\n\t\t\tchar parbuf[128] = \"\";\n\t\t\tif (ctrl->get_maxdownloads() > 1) {\n\t\t\t\tsnprintf(parbuf, sizeof(parbuf), _(\" - %u parallel downloads\"), ctrl->get_maxdownloads());\n\t\t\t}\n\n\t\t\tchar buf[1024];\n\t\t\tsnprintf(buf, sizeof(buf), _(\"Queue (%u downloads in progress, %u total) - %.2f kb\/s total%s\"),\n\t\t\t static_cast<unsigned int>(ctrl->downloads_in_progress()),\n\t\t\t static_cast<unsigned int>(ctrl->downloads().size()), total_kbps, parbuf);\n\n\t\t\tdllist_form.set(\"head\", buf);\n\n\t\t\tLOG(LOG_DEBUG, \"pb_view::run: updating view... downloads().size() = %u\", ctrl->downloads().size());\n\n\t\t\tif (ctrl->downloads().size() > 0) {\n\t\t\t\tstd::string code = \"{list\";\n\n\t\t\t\tunsigned int i = 0;\n\t\t\t\tfor (auto dl : ctrl->downloads()) {\n\t\t\t\t\tchar lbuf[1024];\n\t\t\t\t\tsnprintf(lbuf, sizeof(lbuf), \" %4u [%6.1fMB\/%6.1fMB] [%5.1f %%] [%7.2f kb\/s] %-20s %s -> %s\", i+1, dl.current_size()\/(1024*1024), dl.total_size()\/(1024*1024), dl.percents_finished(), dl.kbps(), dl.status_text(), dl.url(), dl.filename());\n\t\t\t\t\tcode.append(utils::strprintf(\"{listitem[%u] text:%s}\", i, stfl::quote(lbuf).c_str()));\n\t\t\t\t\ti++;\n\t\t\t\t}\n\n\t\t\t\tcode.append(\"}\");\n\n\t\t\t\tdllist_form.modify(\"dls\", \"replace_inner\", code);\n\t\t\t}\n\n\t\t\tctrl->set_view_update_necessary(false);\n\t\t}\n\n\t\tconst char * event = dllist_form.run(500);\n\n\t\tif (auto_download) {\n\t\t\tif (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) {\n\t\t\t\tctrl->start_downloads();\n\t\t\t}\n\t\t}\n\n\t\tif (!event || strcmp(event,\"TIMEOUT\")==0) continue;\n\n\t\toperation op = keys->get_operation(event, \"podbeuter\");\n\n\t\tif (dllist_form.get(\"msg\").length() > 0) {\n\t\t\tdllist_form.set(\"msg\", \"\");\n\t\t\tctrl->set_view_update_necessary(true);\n\t\t}\n\n\t\tswitch (op) {\n\t\tcase OP_PB_TOGGLE_DLALL:\n\t\t\tauto_download = !auto_download;\n\t\t\tbreak;\n\t\tcase OP_HARDQUIT:\n\t\tcase OP_QUIT:\n\t\t\tif (ctrl->downloads_in_progress() > 0) {\n\t\t\t\tdllist_form.set(\"msg\", _(\"Error: can't quit: download(s) in progress.\"));\n\t\t\t\tctrl->set_view_update_necessary(true);\n\t\t\t} else {\n\t\t\t\tquit = true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OP_PB_MOREDL:\n\t\t\tctrl->increase_parallel_downloads();\n\t\t\tbreak;\n\t\tcase OP_PB_LESSDL:\n\t\t\tctrl->decrease_parallel_downloads();\n\t\t\tbreak;\n\t\tcase OP_PB_DOWNLOAD: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() != DL_DOWNLOADING) {\n\t\t\t\t\tstd::thread t {poddlthread(&ctrl->downloads()[idx], ctrl->get_cfgcont())};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_PLAY: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tdlstatus_t status = ctrl->downloads()[idx].status();\n\t\t\t\tif (status == DL_FINISHED || status == DL_PLAYED || status == DL_READY) {\n\t\t\t\t\tctrl->play_file(ctrl->downloads()[idx].filename());\n\t\t\t\t\tctrl->downloads()[idx].set_status(DL_PLAYED);\n\t\t\t\t} else {\n\t\t\t\t\tdllist_form.set(\"msg\", _(\"Error: download needs to be finished before the file can be played.\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_MARK_FINISHED: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tdlstatus_t status = ctrl->downloads()[idx].status();\n\t\t\t\tif ( status == DL_PLAYED ) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(DL_FINISHED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_CANCEL: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() == DL_DOWNLOADING) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(DL_CANCELLED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_DELETE: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() != DL_DOWNLOADING) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(DL_DELETED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_PURGE:\n\t\t\tif (ctrl->downloads_in_progress() > 0) {\n\t\t\t\tdllist_form.set(\"msg\", _(\"Error: unable to perform operation: download(s) in progress.\"));\n\t\t\t} else {\n\t\t\t\tctrl->reload_queue(true);\n\t\t\t}\n\t\t\tctrl->set_view_update_necessary(true);\n\t\t\tbreak;\n\t\tcase OP_HELP:\n\t\t\trun_help();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t} while (!quit);\n}\n\n\n\nvoid pb_view::set_bindings() {\n\tif (keys) {\n\t\tstd::string upkey(\"** \");\n\t\tupkey.append(keys->getkey(OP_SK_UP, \"podbeuter\"));\n\t\tstd::string downkey(\"** \");\n\t\tdownkey.append(keys->getkey(OP_SK_DOWN, \"podbeuter\"));\n\t\tstd::string pgupkey(\"** \");\n\t\tpgupkey.append(keys->getkey(OP_SK_PGUP, \"podbeuter\"));\n\t\tstd::string pgdownkey(\"** \");\n\t\tpgdownkey.append(keys->getkey(OP_SK_PGDOWN, \"podbeuter\"));\n\t\tstd::string homekey(\"** \");\n\t\thomekey.append(keys->getkey(OP_SK_HOME, \"podbeuter\"));\n\t\tstd::string endkey(\"** \");\n\t\tendkey.append(keys->getkey(OP_SK_END, \"podbeuter\"));\n\n\t\tdllist_form.set(\"bind_up\", upkey);\n\t\tdllist_form.set(\"bind_down\", downkey);\n\t\tdllist_form.set(\"bind_page_up\", pgupkey);\n\t\tdllist_form.set(\"bind_page_down\", pgdownkey);\n\t\tdllist_form.set(\"bind_home\", homekey);\n\t\tdllist_form.set(\"bind_end\", endkey);\n\n\t\thelp_form.set(\"bind_up\", upkey);\n\t\thelp_form.set(\"bind_down\", downkey);\n\t\thelp_form.set(\"bind_page_up\", pgupkey);\n\t\thelp_form.set(\"bind_page_down\", pgdownkey);\n\t\thelp_form.set(\"bind_home\", homekey);\n\t\thelp_form.set(\"bind_end\", endkey);\n\n\t}\n}\n\n\n\n\nvoid pb_view::run_help() {\n\tset_help_keymap_hint();\n\n\thelp_form.set(\"head\",_(\"Help\"));\n\n\tstd::vector<keymap_desc> descs;\n\tkeys->get_keymap_descriptions(descs, KM_PODBEUTER);\n\n\tstd::string code = \"{list\";\n\n\tfor (auto desc : descs) {\n\t\tstd::string line = \"{listitem text:\";\n\n\t\tstd::string descline;\n\t\tdescline.append(desc.key);\n\t\tdescline.append(8-desc.key.length(),' ');\n\t\tdescline.append(desc.cmd);\n\t\tdescline.append(24-desc.cmd.length(),' ');\n\t\tdescline.append(desc.desc);\n\t\tline.append(stfl::quote(descline));\n\n\t\tline.append(\"}\");\n\n\t\tcode.append(line);\n\t}\n\n\tcode.append(\"}\");\n\n\thelp_form.modify(\"helptext\",\"replace_inner\",code);\n\n\tbool quit = false;\n\n\tdo {\n\t\tconst char * event = help_form.run(0);\n\t\tif (!event) continue;\n\n\t\toperation op = keys->get_operation(event, \"help\");\n\n\t\tswitch (op) {\n\t\tcase OP_HARDQUIT:\n\t\tcase OP_QUIT:\n\t\t\tquit = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t} while (!quit);\n}\n\nstd::string pb_view::prepare_keymaphint(keymap_hint_entry * hints) {\n\tstd::string keymap_hint;\n\tfor (int i=0; hints[i].op != OP_NIL; ++i) {\n\t\tkeymap_hint.append(keys->getkey(hints[i].op, \"podbeuter\"));\n\t\tkeymap_hint.append(\":\");\n\t\tkeymap_hint.append(hints[i].text);\n\t\tkeymap_hint.append(\" \");\n\t}\n\treturn keymap_hint;\n}\n\nvoid pb_view::set_help_keymap_hint() {\n\tkeymap_hint_entry hints[] = {\n\t\t{ OP_QUIT, _(\"Quit\") },\n\t\t{ OP_NIL, NULL }\n\t};\n\tstd::string keymap_hint = prepare_keymaphint(hints);\n\thelp_form.set(\"help\", keymap_hint);\n}\n\nvoid pb_view::set_dllist_keymap_hint() {\n\tkeymap_hint_entry hints[] = {\n\t\t{ OP_QUIT, _(\"Quit\") },\n\t\t{ OP_PB_DOWNLOAD, _(\"Download\") },\n\t\t{ OP_PB_CANCEL, _(\"Cancel\") },\n\t\t{ OP_PB_DELETE, _(\"Delete\") },\n\t\t{ OP_PB_PURGE, _(\"Purge Finished\") },\n\t\t{ OP_PB_TOGGLE_DLALL, _(\"Toggle Automatic Download\") },\n\t\t{ OP_PB_PLAY, _(\"Play\") },\n\t\t{ OP_PB_MARK_FINISHED, _(\"Mark as Finished\") },\n\t\t{ OP_HELP, _(\"Help\") },\n\t\t{ OP_NIL, NULL }\n\t};\n\n\tstd::string keymap_hint = prepare_keymaphint(hints);\n\tdllist_form.set(\"help\", keymap_hint);\n}\n\n}\n<commit_msg>Another threa.detach() missing<commit_after>#include <pb_view.h>\n#include <pb_controller.h>\n#include <poddlthread.h>\n#include <download.h>\n#include <config.h>\n#include <logger.h>\n\n#include <dllist.h>\n#include <help.h>\n#include <utils.h>\n\n#include <sstream>\n#include <iostream>\n#include <cstring>\n\nusing namespace newsbeuter;\n\nnamespace podbeuter {\n\npb_view::pb_view(pb_controller * c) : ctrl(c), dllist_form(dllist_str), help_form(help_str), keys(0) {\n}\n\npb_view::~pb_view() {\n\tstfl::reset();\n}\n\nvoid pb_view::run(bool auto_download) {\n\tbool quit = false;\n\n\tset_dllist_keymap_hint();\n\n\tdo {\n\n\t\tif (ctrl->view_update_necessary()) {\n\n\t\t\tdouble total_kbps = ctrl->get_total_kbps();\n\n\t\t\tchar parbuf[128] = \"\";\n\t\t\tif (ctrl->get_maxdownloads() > 1) {\n\t\t\t\tsnprintf(parbuf, sizeof(parbuf), _(\" - %u parallel downloads\"), ctrl->get_maxdownloads());\n\t\t\t}\n\n\t\t\tchar buf[1024];\n\t\t\tsnprintf(buf, sizeof(buf), _(\"Queue (%u downloads in progress, %u total) - %.2f kb\/s total%s\"),\n\t\t\t static_cast<unsigned int>(ctrl->downloads_in_progress()),\n\t\t\t static_cast<unsigned int>(ctrl->downloads().size()), total_kbps, parbuf);\n\n\t\t\tdllist_form.set(\"head\", buf);\n\n\t\t\tLOG(LOG_DEBUG, \"pb_view::run: updating view... downloads().size() = %u\", ctrl->downloads().size());\n\n\t\t\tif (ctrl->downloads().size() > 0) {\n\t\t\t\tstd::string code = \"{list\";\n\n\t\t\t\tunsigned int i = 0;\n\t\t\t\tfor (auto dl : ctrl->downloads()) {\n\t\t\t\t\tchar lbuf[1024];\n\t\t\t\t\tsnprintf(lbuf, sizeof(lbuf), \" %4u [%6.1fMB\/%6.1fMB] [%5.1f %%] [%7.2f kb\/s] %-20s %s -> %s\", i+1, dl.current_size()\/(1024*1024), dl.total_size()\/(1024*1024), dl.percents_finished(), dl.kbps(), dl.status_text(), dl.url(), dl.filename());\n\t\t\t\t\tcode.append(utils::strprintf(\"{listitem[%u] text:%s}\", i, stfl::quote(lbuf).c_str()));\n\t\t\t\t\ti++;\n\t\t\t\t}\n\n\t\t\t\tcode.append(\"}\");\n\n\t\t\t\tdllist_form.modify(\"dls\", \"replace_inner\", code);\n\t\t\t}\n\n\t\t\tctrl->set_view_update_necessary(false);\n\t\t}\n\n\t\tconst char * event = dllist_form.run(500);\n\n\t\tif (auto_download) {\n\t\t\tif (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) {\n\t\t\t\tctrl->start_downloads();\n\t\t\t}\n\t\t}\n\n\t\tif (!event || strcmp(event,\"TIMEOUT\")==0) continue;\n\n\t\toperation op = keys->get_operation(event, \"podbeuter\");\n\n\t\tif (dllist_form.get(\"msg\").length() > 0) {\n\t\t\tdllist_form.set(\"msg\", \"\");\n\t\t\tctrl->set_view_update_necessary(true);\n\t\t}\n\n\t\tswitch (op) {\n\t\tcase OP_PB_TOGGLE_DLALL:\n\t\t\tauto_download = !auto_download;\n\t\t\tbreak;\n\t\tcase OP_HARDQUIT:\n\t\tcase OP_QUIT:\n\t\t\tif (ctrl->downloads_in_progress() > 0) {\n\t\t\t\tdllist_form.set(\"msg\", _(\"Error: can't quit: download(s) in progress.\"));\n\t\t\t\tctrl->set_view_update_necessary(true);\n\t\t\t} else {\n\t\t\t\tquit = true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OP_PB_MOREDL:\n\t\t\tctrl->increase_parallel_downloads();\n\t\t\tbreak;\n\t\tcase OP_PB_LESSDL:\n\t\t\tctrl->decrease_parallel_downloads();\n\t\t\tbreak;\n\t\tcase OP_PB_DOWNLOAD: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() != DL_DOWNLOADING) {\n\t\t\t\t\tstd::thread t {poddlthread(&ctrl->downloads()[idx], ctrl->get_cfgcont())};\n\t\t\t\t\tt.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_PLAY: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tdlstatus_t status = ctrl->downloads()[idx].status();\n\t\t\t\tif (status == DL_FINISHED || status == DL_PLAYED || status == DL_READY) {\n\t\t\t\t\tctrl->play_file(ctrl->downloads()[idx].filename());\n\t\t\t\t\tctrl->downloads()[idx].set_status(DL_PLAYED);\n\t\t\t\t} else {\n\t\t\t\t\tdllist_form.set(\"msg\", _(\"Error: download needs to be finished before the file can be played.\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_MARK_FINISHED: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tdlstatus_t status = ctrl->downloads()[idx].status();\n\t\t\t\tif ( status == DL_PLAYED ) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(DL_FINISHED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_CANCEL: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() == DL_DOWNLOADING) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(DL_CANCELLED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_DELETE: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() != DL_DOWNLOADING) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(DL_DELETED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_PURGE:\n\t\t\tif (ctrl->downloads_in_progress() > 0) {\n\t\t\t\tdllist_form.set(\"msg\", _(\"Error: unable to perform operation: download(s) in progress.\"));\n\t\t\t} else {\n\t\t\t\tctrl->reload_queue(true);\n\t\t\t}\n\t\t\tctrl->set_view_update_necessary(true);\n\t\t\tbreak;\n\t\tcase OP_HELP:\n\t\t\trun_help();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t} while (!quit);\n}\n\n\n\nvoid pb_view::set_bindings() {\n\tif (keys) {\n\t\tstd::string upkey(\"** \");\n\t\tupkey.append(keys->getkey(OP_SK_UP, \"podbeuter\"));\n\t\tstd::string downkey(\"** \");\n\t\tdownkey.append(keys->getkey(OP_SK_DOWN, \"podbeuter\"));\n\t\tstd::string pgupkey(\"** \");\n\t\tpgupkey.append(keys->getkey(OP_SK_PGUP, \"podbeuter\"));\n\t\tstd::string pgdownkey(\"** \");\n\t\tpgdownkey.append(keys->getkey(OP_SK_PGDOWN, \"podbeuter\"));\n\t\tstd::string homekey(\"** \");\n\t\thomekey.append(keys->getkey(OP_SK_HOME, \"podbeuter\"));\n\t\tstd::string endkey(\"** \");\n\t\tendkey.append(keys->getkey(OP_SK_END, \"podbeuter\"));\n\n\t\tdllist_form.set(\"bind_up\", upkey);\n\t\tdllist_form.set(\"bind_down\", downkey);\n\t\tdllist_form.set(\"bind_page_up\", pgupkey);\n\t\tdllist_form.set(\"bind_page_down\", pgdownkey);\n\t\tdllist_form.set(\"bind_home\", homekey);\n\t\tdllist_form.set(\"bind_end\", endkey);\n\n\t\thelp_form.set(\"bind_up\", upkey);\n\t\thelp_form.set(\"bind_down\", downkey);\n\t\thelp_form.set(\"bind_page_up\", pgupkey);\n\t\thelp_form.set(\"bind_page_down\", pgdownkey);\n\t\thelp_form.set(\"bind_home\", homekey);\n\t\thelp_form.set(\"bind_end\", endkey);\n\n\t}\n}\n\n\n\n\nvoid pb_view::run_help() {\n\tset_help_keymap_hint();\n\n\thelp_form.set(\"head\",_(\"Help\"));\n\n\tstd::vector<keymap_desc> descs;\n\tkeys->get_keymap_descriptions(descs, KM_PODBEUTER);\n\n\tstd::string code = \"{list\";\n\n\tfor (auto desc : descs) {\n\t\tstd::string line = \"{listitem text:\";\n\n\t\tstd::string descline;\n\t\tdescline.append(desc.key);\n\t\tdescline.append(8-desc.key.length(),' ');\n\t\tdescline.append(desc.cmd);\n\t\tdescline.append(24-desc.cmd.length(),' ');\n\t\tdescline.append(desc.desc);\n\t\tline.append(stfl::quote(descline));\n\n\t\tline.append(\"}\");\n\n\t\tcode.append(line);\n\t}\n\n\tcode.append(\"}\");\n\n\thelp_form.modify(\"helptext\",\"replace_inner\",code);\n\n\tbool quit = false;\n\n\tdo {\n\t\tconst char * event = help_form.run(0);\n\t\tif (!event) continue;\n\n\t\toperation op = keys->get_operation(event, \"help\");\n\n\t\tswitch (op) {\n\t\tcase OP_HARDQUIT:\n\t\tcase OP_QUIT:\n\t\t\tquit = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t} while (!quit);\n}\n\nstd::string pb_view::prepare_keymaphint(keymap_hint_entry * hints) {\n\tstd::string keymap_hint;\n\tfor (int i=0; hints[i].op != OP_NIL; ++i) {\n\t\tkeymap_hint.append(keys->getkey(hints[i].op, \"podbeuter\"));\n\t\tkeymap_hint.append(\":\");\n\t\tkeymap_hint.append(hints[i].text);\n\t\tkeymap_hint.append(\" \");\n\t}\n\treturn keymap_hint;\n}\n\nvoid pb_view::set_help_keymap_hint() {\n\tkeymap_hint_entry hints[] = {\n\t\t{ OP_QUIT, _(\"Quit\") },\n\t\t{ OP_NIL, NULL }\n\t};\n\tstd::string keymap_hint = prepare_keymaphint(hints);\n\thelp_form.set(\"help\", keymap_hint);\n}\n\nvoid pb_view::set_dllist_keymap_hint() {\n\tkeymap_hint_entry hints[] = {\n\t\t{ OP_QUIT, _(\"Quit\") },\n\t\t{ OP_PB_DOWNLOAD, _(\"Download\") },\n\t\t{ OP_PB_CANCEL, _(\"Cancel\") },\n\t\t{ OP_PB_DELETE, _(\"Delete\") },\n\t\t{ OP_PB_PURGE, _(\"Purge Finished\") },\n\t\t{ OP_PB_TOGGLE_DLALL, _(\"Toggle Automatic Download\") },\n\t\t{ OP_PB_PLAY, _(\"Play\") },\n\t\t{ OP_PB_MARK_FINISHED, _(\"Mark as Finished\") },\n\t\t{ OP_HELP, _(\"Help\") },\n\t\t{ OP_NIL, NULL }\n\t};\n\n\tstd::string keymap_hint = prepare_keymaphint(hints);\n\tdllist_form.set(\"help\", keymap_hint);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Revert \"Add back ctrl+shift+delete for bringing up the \"Clear browsing data\"\"<commit_after><|endoftext|>"} {"text":"<commit_before>#include <luabind\/luabind.hpp>\n#include \"..\/externals\/json\/json.h\"\n#include \"math.h\"\n#include \"motionstate.h\"\n#include \"physics.h\"\n\nPhysics::Physics(){\n\tmKinematic.Vel\t = Vector2f(0, 0);\n\tmKinematic.Accel = Vector2f(0, 0);\n\tmHorizDir = MOVE::STOP;\n\tmVertDir = MOVE::STOP;\n}\nPhysics::~Physics(){}\nvoid Physics::Move(float deltaT){\n\t\/\/Update the velocity\n\tUpdateVelocity(deltaT);\n\t\/\/test if the move is ok before applying changes\n\tVector2f testPos;\n\ttestPos = mBox.Pos() + (mKinematic.Vel * deltaT);\n\n\t\/\/Clamp the test position x & y\n\t\/\/TODO: Change these clamp ranges to be the map range, ie. map.x min map.x + map.w max\n\t\/\/map.y min map.y + map.h max\n\ttestPos.x = Math::Clamp(testPos.x, 0.0, 320.0);\n\ttestPos.y = Math::Clamp(testPos.y, 0.0, 320.0);\n\n\t\/\/x axis collision checks\n\tif (CheckCollision(Rectf(testPos.x, mBox.Y(), mBox.W(), mBox.H()))){\n\t}\n\telse \n\t\tmBox.Set(testPos.x, mBox.Y());\n\t\/\/y axis collision checks\n\tif (CheckCollision(Rectf(mBox.X(), testPos.y, mBox.W(), mBox.H()))){\n\t}\n\telse\n\t\tmBox.Set(mBox.X(), testPos.y);\n\n\t\/\/mMotionState.UpdateState(mKinematic);\n}\nvoid Physics::UpdateVelocity(float deltaT){\n\tApplyAcceleration();\n\tApplyFriction();\n\t\/\/if applying the friction would cause the velocity to flip signs, set velocity to 0\n\tif (mHorizDir == MOVE::STOP && ((mKinematic.Vel.x + mKinematic.Accel.x * deltaT > 0.0 && mKinematic.Vel.x < 0.0)\n\t\t|| (mKinematic.Vel.x + mKinematic.Accel.x * deltaT < 0.0 && mKinematic.Vel.x > 0.0)))\n\t\t\tmKinematic.Vel.x = 0.0;\n\telse \n\t\tmKinematic.Vel.x += mKinematic.Accel.x * deltaT;\n\t\/\/same for y\n\tif (mVertDir == MOVE::STOP && ((mKinematic.Vel.y + mKinematic.Accel.y * deltaT > 0.0 && mKinematic.Vel.y < 0.0)\n\t\t|| (mKinematic.Vel.y + mKinematic.Accel.y * deltaT < 0.0 && mKinematic.Vel.y > 0.0)))\n\t\t\tmKinematic.Vel.y = 0.0;\n\telse \n\t\tmKinematic.Vel.y += mKinematic.Accel.y * deltaT;\n\n\t\/\/limit velocity\n\tif ((mKinematic.Vel.x > mPhysConstants.hSpeed) || (mKinematic.Vel.x < -mPhysConstants.hSpeed))\n\t\tmKinematic.Vel.x = mPhysConstants.hSpeed * (mKinematic.Vel.x \/ abs(mKinematic.Vel.x));\n\t\/\/for y as well\n\tif ((mKinematic.Vel.y > mPhysConstants.hSpeed) || (mKinematic.Vel.y < -mPhysConstants.hSpeed))\n\t\tmKinematic.Vel.y = mPhysConstants.hSpeed * (mKinematic.Vel.y \/ abs(mKinematic.Vel.y));\n}\nvoid Physics::ApplyAcceleration(){\n\tif (mHorizDir == Math::RIGHT)\n\t\tmKinematic.Accel.x = mPhysConstants.hAccel;\n\telse if (mHorizDir == Math::LEFT)\n\t\tmKinematic.Accel.x = -mPhysConstants.hAccel;\n\telse\n\t\tmKinematic.Accel.x = 0;\n\tif (mVertDir == Math::UP)\n\t\tmKinematic.Accel.y = -mPhysConstants.hAccel;\n\telse if (mVertDir == Math::DOWN)\n\t\tmKinematic.Accel.y = mPhysConstants.hAccel;\n\telse\n\t\tmKinematic.Accel.y = 0;\n}\nvoid Physics::ApplyFriction(){\n\tif (mHorizDir == MOVE::STOP && mKinematic.Vel.x != 0.0){\n\t\tmKinematic.Accel.x += GROUND_FRICTION * (-mKinematic.Vel.x \/ abs(mKinematic.Vel.x));\n\t}\n\tif (mVertDir == MOVE::STOP && mKinematic.Vel.y != 0.0){\n\t\tmKinematic.Accel.y += GROUND_FRICTION * (-mKinematic.Vel.y \/ abs(mKinematic.Vel.y));\n\t}\n}\nbool Physics::CheckCollision(Rectf box){\n\t\/\/We wait to exit the loop until we've found the collision direction and\n\t\/\/checked it against our movement direction to set v to 0 if moving in direction of \n\t\/\/the collision\n\tbool colliding = false;\n\tfor (Recti i : mCollisionMap){\n\t\tif (Math::CheckCollision(box, i)){\n\t\t\tcolliding = true;\n\t\t\t\/\/Check collision direction against movement directions\n\t\t\tint colDir = Math::RectNearRect(box, i, 15);\n\t\t\tif (mHorizDir == colDir){\n\t\t\t\tmKinematic.Vel.x = 0;\n\t\t\t\treturn colliding;\n\t\t\t}\n\t\t\tif (mVertDir == colDir){\n\t\t\t\tmKinematic.Vel.y = 0;\n\t\t\t\treturn colliding;\n\t\t\t}\n\t\t}\n\t}\n\treturn colliding;\n}\n\nVector2f Physics::Position() const{\n\treturn mBox.Pos();\n}\nVector2f Physics::Velocity() const{\n\treturn mKinematic.Vel;\n}\nVector2f Physics::Acceleration() const{\n\treturn mKinematic.Accel;\n}\nRectf Physics::Box() const{\n\treturn mBox;\n}\nint Physics::MotionState() const{\n\/\/\treturn mMotionState.GetMotionState();\n\treturn 0;\n}\nvoid Physics::SetPosition(Vector2f pos){\n\tmBox.Set(pos);\n}\nvoid Physics::SetVelocity(Vector2f vel){\n\tmKinematic.Vel = vel;\n}\nvoid Physics::SetAcceleration(Vector2f accel){\n\tmKinematic.Accel = accel;\n}\nvoid Physics::SetHorizDir(int moveDir){\n\tif (moveDir == Math::UP || moveDir == Math::DOWN)\n\t\tthrow std::runtime_error(\"Bad Horizontal Direction\");\n\tmHorizDir = moveDir;\n}\nvoid Physics::SetVertDir(int moveDir){\n\tif (moveDir == Math::LEFT || moveDir == Math::RIGHT)\n\t\tthrow std::runtime_error(\"Bad Vertical Direction\");\n\tmVertDir = moveDir;\n}\nvoid Physics::SetPhysConstants(PhysicalConstants physConstants){\n\tmPhysConstants = physConstants;\n}\nvoid Physics::SetBox(Rectf box){\n\tmBox = box;\n}\nvoid Physics::SetMap(CollisionMap map){\n\tmCollisionMap = map;\n}\nJson::Value Physics::Save(){\n\t\/\/Save the object's physical constants and box\n\tJson::Value val;\n\tval[\"box\"] \t = mBox.Save();\n\tval[\"hSpeed\"] = mPhysConstants.hSpeed;\n\tval[\"hAccel\"] = mPhysConstants.hAccel;\n\treturn val;\n}\nvoid Physics::Load(Json::Value val){\n\tmBox.Load(val[\"box\"]);\n\tmPhysConstants.hAccel = val[\"hAccel\"].asInt();\n\tmPhysConstants.hSpeed = val[\"hSpeed\"].asInt();\n\n\t\/\/Setup motion values\n\tmKinematic.Vel\t = Vector2f(0, 0);\n\tmKinematic.Accel = Vector2f(0, 0);\n\tmHorizDir = MOVE::STOP;\n\tmVertDir = MOVE::STOP;\n}\nvoid Physics::RegisterLua(lua_State *l){\n\tusing namespace luabind;\n\n\tmodule(l, \"LPC\")[\n\t\tclass_<Physics>(\"Physics\")\n\t\t\t.def(constructor<>())\n\t\t\t.def(\"Move\", &Physics::Move)\n\t\t\t.def(\"Position\", &Physics::Position)\n\t\t\t.def(\"Velocity\", &Physics::Velocity)\n\t\t\t.def(\"Acceleration\", &Physics::Acceleration)\n\t];\n}<commit_msg>uncommented MotionState usage in Physics<commit_after>#include <luabind\/luabind.hpp>\n#include \"..\/externals\/json\/json.h\"\n#include \"math.h\"\n#include \"motionstate.h\"\n#include \"physics.h\"\n\nPhysics::Physics(){\n\tmKinematic.Vel\t = Vector2f(0, 0);\n\tmKinematic.Accel = Vector2f(0, 0);\n\tmHorizDir = MOVE::STOP;\n\tmVertDir = MOVE::STOP;\n}\nPhysics::~Physics(){}\nvoid Physics::Move(float deltaT){\n\t\/\/Update the velocity\n\tUpdateVelocity(deltaT);\n\t\/\/test if the move is ok before applying changes\n\tVector2f testPos;\n\ttestPos = mBox.Pos() + (mKinematic.Vel * deltaT);\n\n\t\/\/Clamp the test position x & y\n\t\/\/TODO: Change these clamp ranges to be the map range, ie. map.x min map.x + map.w max\n\t\/\/map.y min map.y + map.h max\n\ttestPos.x = Math::Clamp(testPos.x, 0.0, 320.0);\n\ttestPos.y = Math::Clamp(testPos.y, 0.0, 320.0);\n\n\t\/\/x axis collision checks\n\tif (CheckCollision(Rectf(testPos.x, mBox.Y(), mBox.W(), mBox.H()))){\n\t}\n\telse \n\t\tmBox.Set(testPos.x, mBox.Y());\n\t\/\/y axis collision checks\n\tif (CheckCollision(Rectf(mBox.X(), testPos.y, mBox.W(), mBox.H()))){\n\t}\n\telse\n\t\tmBox.Set(mBox.X(), testPos.y);\n\n\tmMotionState.UpdateState(mKinematic);\n}\nvoid Physics::UpdateVelocity(float deltaT){\n\tApplyAcceleration();\n\tApplyFriction();\n\t\/\/if applying the friction would cause the velocity to flip signs, set velocity to 0\n\tif (mHorizDir == MOVE::STOP && ((mKinematic.Vel.x + mKinematic.Accel.x * deltaT > 0.0 && mKinematic.Vel.x < 0.0)\n\t\t|| (mKinematic.Vel.x + mKinematic.Accel.x * deltaT < 0.0 && mKinematic.Vel.x > 0.0)))\n\t\t\tmKinematic.Vel.x = 0.0;\n\telse \n\t\tmKinematic.Vel.x += mKinematic.Accel.x * deltaT;\n\t\/\/same for y\n\tif (mVertDir == MOVE::STOP && ((mKinematic.Vel.y + mKinematic.Accel.y * deltaT > 0.0 && mKinematic.Vel.y < 0.0)\n\t\t|| (mKinematic.Vel.y + mKinematic.Accel.y * deltaT < 0.0 && mKinematic.Vel.y > 0.0)))\n\t\t\tmKinematic.Vel.y = 0.0;\n\telse \n\t\tmKinematic.Vel.y += mKinematic.Accel.y * deltaT;\n\n\t\/\/limit velocity\n\tif ((mKinematic.Vel.x > mPhysConstants.hSpeed) || (mKinematic.Vel.x < -mPhysConstants.hSpeed))\n\t\tmKinematic.Vel.x = mPhysConstants.hSpeed * (mKinematic.Vel.x \/ abs(mKinematic.Vel.x));\n\t\/\/for y as well\n\tif ((mKinematic.Vel.y > mPhysConstants.hSpeed) || (mKinematic.Vel.y < -mPhysConstants.hSpeed))\n\t\tmKinematic.Vel.y = mPhysConstants.hSpeed * (mKinematic.Vel.y \/ abs(mKinematic.Vel.y));\n}\nvoid Physics::ApplyAcceleration(){\n\tif (mHorizDir == Math::RIGHT)\n\t\tmKinematic.Accel.x = mPhysConstants.hAccel;\n\telse if (mHorizDir == Math::LEFT)\n\t\tmKinematic.Accel.x = -mPhysConstants.hAccel;\n\telse\n\t\tmKinematic.Accel.x = 0;\n\tif (mVertDir == Math::UP)\n\t\tmKinematic.Accel.y = -mPhysConstants.hAccel;\n\telse if (mVertDir == Math::DOWN)\n\t\tmKinematic.Accel.y = mPhysConstants.hAccel;\n\telse\n\t\tmKinematic.Accel.y = 0;\n}\nvoid Physics::ApplyFriction(){\n\tif (mHorizDir == MOVE::STOP && mKinematic.Vel.x != 0.0){\n\t\tmKinematic.Accel.x += GROUND_FRICTION * (-mKinematic.Vel.x \/ abs(mKinematic.Vel.x));\n\t}\n\tif (mVertDir == MOVE::STOP && mKinematic.Vel.y != 0.0){\n\t\tmKinematic.Accel.y += GROUND_FRICTION * (-mKinematic.Vel.y \/ abs(mKinematic.Vel.y));\n\t}\n}\nbool Physics::CheckCollision(Rectf box){\n\t\/\/We wait to exit the loop until we've found the collision direction and\n\t\/\/checked it against our movement direction to set v to 0 if moving in direction of \n\t\/\/the collision\n\tbool colliding = false;\n\tfor (Recti i : mCollisionMap){\n\t\tif (Math::CheckCollision(box, i)){\n\t\t\tcolliding = true;\n\t\t\t\/\/Check collision direction against movement directions\n\t\t\tint colDir = Math::RectNearRect(box, i, 15);\n\t\t\tif (mHorizDir == colDir){\n\t\t\t\tmKinematic.Vel.x = 0;\n\t\t\t\treturn colliding;\n\t\t\t}\n\t\t\tif (mVertDir == colDir){\n\t\t\t\tmKinematic.Vel.y = 0;\n\t\t\t\treturn colliding;\n\t\t\t}\n\t\t}\n\t}\n\treturn colliding;\n}\n\nVector2f Physics::Position() const{\n\treturn mBox.Pos();\n}\nVector2f Physics::Velocity() const{\n\treturn mKinematic.Vel;\n}\nVector2f Physics::Acceleration() const{\n\treturn mKinematic.Accel;\n}\nRectf Physics::Box() const{\n\treturn mBox;\n}\nint Physics::MotionState() const{\n\treturn mMotionState.GetMotionState();\n}\nvoid Physics::SetPosition(Vector2f pos){\n\tmBox.Set(pos);\n}\nvoid Physics::SetVelocity(Vector2f vel){\n\tmKinematic.Vel = vel;\n}\nvoid Physics::SetAcceleration(Vector2f accel){\n\tmKinematic.Accel = accel;\n}\nvoid Physics::SetHorizDir(int moveDir){\n\tif (moveDir == Math::UP || moveDir == Math::DOWN)\n\t\tthrow std::runtime_error(\"Bad Horizontal Direction\");\n\tmHorizDir = moveDir;\n}\nvoid Physics::SetVertDir(int moveDir){\n\tif (moveDir == Math::LEFT || moveDir == Math::RIGHT)\n\t\tthrow std::runtime_error(\"Bad Vertical Direction\");\n\tmVertDir = moveDir;\n}\nvoid Physics::SetPhysConstants(PhysicalConstants physConstants){\n\tmPhysConstants = physConstants;\n}\nvoid Physics::SetBox(Rectf box){\n\tmBox = box;\n}\nvoid Physics::SetMap(CollisionMap map){\n\tmCollisionMap = map;\n}\nJson::Value Physics::Save(){\n\t\/\/Save the object's physical constants and box\n\tJson::Value val;\n\tval[\"box\"] \t = mBox.Save();\n\tval[\"hSpeed\"] = mPhysConstants.hSpeed;\n\tval[\"hAccel\"] = mPhysConstants.hAccel;\n\treturn val;\n}\nvoid Physics::Load(Json::Value val){\n\tmBox.Load(val[\"box\"]);\n\tmPhysConstants.hAccel = val[\"hAccel\"].asInt();\n\tmPhysConstants.hSpeed = val[\"hSpeed\"].asInt();\n\n\t\/\/Setup motion values\n\tmKinematic.Vel\t = Vector2f(0, 0);\n\tmKinematic.Accel = Vector2f(0, 0);\n\tmHorizDir = MOVE::STOP;\n\tmVertDir = MOVE::STOP;\n}\nvoid Physics::RegisterLua(lua_State *l){\n\tusing namespace luabind;\n\n\tmodule(l, \"LPC\")[\n\t\tclass_<Physics>(\"Physics\")\n\t\t\t.def(constructor<>())\n\t\t\t.def(\"Move\", &Physics::Move)\n\t\t\t.def(\"Position\", &Physics::Position)\n\t\t\t.def(\"Velocity\", &Physics::Velocity)\n\t\t\t.def(\"Acceleration\", &Physics::Acceleration)\n\t\t\t.def(\"Box\", &Physics::Box)\n\t\t\t.def(\"MotionState\", &Physics::MotionState)\n\t\t\t.def(\"SetPosition\", &Physics::SetPosition)\n\t\t\t.def(\"SetVelocity\", &Physics::SetVelocity)\n\t];\n}<|endoftext|>"} {"text":"<commit_before>\/*\n The MIT License (MIT)\n\n Copyright (c) [2016] [BTC.COM]\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\n#include \"gtest\/gtest.h\"\n#include \"Common.h\"\n#include \"Utils.h\"\n\n#include \"StratumServer.h\"\n\n\/\/ #include \"Kafka.h\"\n\n#ifndef WORK_WITH_STRATUM_SWITCHER\n\nTEST(StratumServer, SessionIDManager24Bits) {\n \/\/ KafkaProducer a(\"\", \"\", 0);\n \/\/ a.produce(\"\", 0);\n\n\n SessionIDManagerT<24> m(0xFFu);\n uint32_t j, sessionID;\n\n \/\/ fill all session ids\n for (uint32_t i = 0; i <= 0x00FFFFFFu; i++) {\n uint32_t id = (0xFFu << 24) | i;\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, id);\n }\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the fisrt one\n j = 0xFF000000u;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the last one\n j = 0xFFFFFFFFu;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n}\n\nTEST(StratumServer, SessionIDManager16Bits) {\n SessionIDManagerT<16> m(0x99u);\n uint32_t j, sessionID;\n\n \/\/ fill all session ids\n for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {\n uint32_t id = (0x99u << 16) | i;\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, id);\n }\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the fisrt one\n j = 0x00990000u;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the last one\n j = 0x0099FFFFu;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n}\n\nTEST(StratumServer, SessionIDManager16BitsWithInterval) {\n SessionIDManagerT<16> m(0x99u);\n m.setAllocInterval(256);\n\n uint32_t j, sessionID;\n\n \/\/ fill all session ids\n \/\/ Use std::vector<bool> because the compile time of \n \/\/ std::bitset<0x100000000ull> is too long.\n {\n std::vector<bool> ids(0x100000000ull);\n for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(ids[sessionID], false);\n ids[sessionID] = true;\n }\n ASSERT_EQ(m.ifFull(), true);\n }\n\n \/\/ free the fisrt one\n {\n j = 0x00990000u;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n }\n\n \/\/ free the last one\n {\n j = 0x0099FFFFu;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n }\n\n \/\/ free all\n for (uint32_t i = 0x00990000u; i <= 0x0099FFFFu; i++) {\n m.freeSessionId(i);\n }\n\n \/\/ fill all again\n {\n std::vector<bool> ids(0x100000000ull);\n for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(ids[sessionID], false);\n ids[sessionID] = true;\n }\n ASSERT_EQ(m.ifFull(), true);\n }\n}\n\nTEST(StratumServer, SessionIDManager8Bits) {\n SessionIDManagerT<8> m(0x68u);\n uint32_t j, sessionID;\n\n \/\/ fill all session ids\n for (uint32_t i = 0; i <= 0x000000FFu; i++) {\n uint32_t id = (0x68u << 8) | i;\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, id);\n }\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the fisrt one\n j = 0x00006800u;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the last one\n j = 0x000068FFu;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n}\n\n#endif \/\/ #ifndef WORK_WITH_STRATUM_SWITCHER\n<commit_msg>add a testcase for StratumServerBitcoin::checkShare()<commit_after>\/*\n The MIT License (MIT)\n\n Copyright (c) [2016] [BTC.COM]\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\n#include \"gtest\/gtest.h\"\n#include \"Common.h\"\n#include \"Utils.h\"\n\n#include \"StratumServer.h\"\n#include \"bitcoin\/BitcoinUtils.h\"\n#include \"bitcoin\/StratumBitcoin.h\"\n#include \"bitcoin\/StratumServerBitcoin.h\"\n\n\/\/ #include \"Kafka.h\"\n\n#ifndef WORK_WITH_STRATUM_SWITCHER\n\nTEST(StratumServer, SessionIDManager24Bits) {\n \/\/ KafkaProducer a(\"\", \"\", 0);\n \/\/ a.produce(\"\", 0);\n\n\n SessionIDManagerT<24> m(0xFFu);\n uint32_t j, sessionID;\n\n \/\/ fill all session ids\n for (uint32_t i = 0; i <= 0x00FFFFFFu; i++) {\n uint32_t id = (0xFFu << 24) | i;\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, id);\n }\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the fisrt one\n j = 0xFF000000u;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the last one\n j = 0xFFFFFFFFu;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n}\n\nTEST(StratumServer, SessionIDManager16Bits) {\n SessionIDManagerT<16> m(0x99u);\n uint32_t j, sessionID;\n\n \/\/ fill all session ids\n for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {\n uint32_t id = (0x99u << 16) | i;\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, id);\n }\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the fisrt one\n j = 0x00990000u;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the last one\n j = 0x0099FFFFu;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n}\n\nTEST(StratumServer, SessionIDManager16BitsWithInterval) {\n SessionIDManagerT<16> m(0x99u);\n m.setAllocInterval(256);\n\n uint32_t j, sessionID;\n\n \/\/ fill all session ids\n \/\/ Use std::vector<bool> because the compile time of \n \/\/ std::bitset<0x100000000ull> is too long.\n {\n std::vector<bool> ids(0x100000000ull);\n for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(ids[sessionID], false);\n ids[sessionID] = true;\n }\n ASSERT_EQ(m.ifFull(), true);\n }\n\n \/\/ free the fisrt one\n {\n j = 0x00990000u;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n }\n\n \/\/ free the last one\n {\n j = 0x0099FFFFu;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n }\n\n \/\/ free all\n for (uint32_t i = 0x00990000u; i <= 0x0099FFFFu; i++) {\n m.freeSessionId(i);\n }\n\n \/\/ fill all again\n {\n std::vector<bool> ids(0x100000000ull);\n for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(ids[sessionID], false);\n ids[sessionID] = true;\n }\n ASSERT_EQ(m.ifFull(), true);\n }\n}\n\nTEST(StratumServer, SessionIDManager8Bits) {\n SessionIDManagerT<8> m(0x68u);\n uint32_t j, sessionID;\n\n \/\/ fill all session ids\n for (uint32_t i = 0; i <= 0x000000FFu; i++) {\n uint32_t id = (0x68u << 8) | i;\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, id);\n }\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the fisrt one\n j = 0x00006800u;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n\n \/\/ free the last one\n j = 0x000068FFu;\n m.freeSessionId(j);\n ASSERT_EQ(m.ifFull(), false);\n ASSERT_EQ(m.allocSessionId(&sessionID), true);\n ASSERT_EQ(sessionID, j);\n ASSERT_EQ(m.ifFull(), true);\n}\n\n#endif \/\/ #ifndef WORK_WITH_STRATUM_SWITCHER\n\nTEST(StratumServerBitcoin, CheckShare) {\n string sjobJson = \"{\\\"jobId\\\":6645522065066147329,\\\"gbtHash\\\":\\\"d349be274f007c2e1ee773b33bd21ef43d2615c089b7c5460b66584881a10683\\\",\"\n \"\\\"prevHash\\\":\\\"00000000000000000019d1d9c84df0ecc23e549b86644ad47cb92570a26b12a5\\\",\\\"prevHashBeStr\\\":\\\"a26b12a57cb9257086644ad4c23e\"\n \"549bc84df0ec0019d1d90000000000000000\\\",\\\"height\\\":558201,\\\"coinbase1\\\":\\\"020000000100000000000000000000000000000000000000000000000\"\n \"00000000000000000ffffffff4b03798408041ba3395c612f4254432e434f4d2ffabe6d6dc807e51bd76025d65ccad2ba8ba1e9fba5f09118b6b55a348638cc17b\"\n \"14e3909080000005fb54ad0\\\",\\\"coinbase2\\\":\\\"ffffffff036734ec4a0000000016001497cfc76442fe717f2a3f0cc9c175f7561b6619970000000000000000\"\n \"266a24aa21a9ed40cbdaa98da815640f815b938df95bffe0775d8078771bc47ed4f43ac4e30b0600000000000000002952534b424c4f434b3a9ad45fdcc194d788\"\n \"895f3ad389b583ea327f826353f7edf6b168db038372cb2700000000\\\",\\\"merkleBranch\\\":\\\"53146311555e15816f4549a893ff2eb50e60741ecccb2996bafd\"\n \"dcf4ee008d5ac504967e375b2522af2be8411b1b032dda0e700c2e8913d869533256ff30caccea4ba404b68e625cfd3237e07e8deddb342690b08314d2638b5272\"\n \"b74ab12fa3b3812908cd6bef999dea979875ba2730615be08b480e4b6f7b878000510a778c557f44bc3f21813d138d25530df85a89a38e2d2827f758ebc68a62e8\"\n \"225933a5af086e72d9a65fd9be526648e8bcf74271308d9d273425b47bd12db075e841ba703f4c8a20be62d036958278b16f214d7fcd35c46a9f9fb1910618fa9e\"\n \"029d3f96518aae34efbdabfbfbc055bffe891d93edbc7539ae9c0a22a35e87d5ccb033b89976cbb624af024b53c6a02309cb838eb285ecf675b801f1dd7f2d5c92\"\n \"4cb1491731c28bea800b12b94bb4f70502a40559c8edb5f73b906ba8e814f10e852ef87365a49346c4b7361b75e38f1d9b96f028880227b7186a0b114e170b170b\"\n \"47\\\",\\\"nVersion\\\":536870912,\\\"nBits\\\":389159077,\\\"nTime\\\":1547281171,\\\"minTime\\\":1547277926,\\\"coinbaseValue\\\":1256993895,\\\"witness\"\n \"Commitment\\\":\\\"6a24aa21a9ed40cbdaa98da815640f815b938df95bffe0775d8078771bc47ed4f43ac4e30b06\\\",\\\"nmcBlockHash\\\":\\\"c807e51bd76025d65\"\n \"ccad2ba8ba1e9fba5f09118b6b55a348638cc17b14e3909\\\",\\\"nmcBits\\\":402868319,\\\"nmcHeight\\\":433937,\\\"nmcRpcAddr\\\":\\\"http:\/\/127.0.0.1:899\"\n \"9\\\",\\\"nmcRpcUserpass\\\":\\\"user:pass\\\",\\\"rskBlockHashForMergedMining\\\":\\\"0x9ad45fdcc194d788895f3ad389b583ea327f826353f7edf6b168db038\"\n \"372cb27\\\",\\\"rskNetworkTarget\\\":\\\"0x00000000000000001386e3444eba74f8a750a71a75ed0b7fecdfd282a8cef091\\\",\\\"rskFeesForMiner\\\":\\\"0\\\",\\\"\"\n \"rskdRpcAddress\\\":\\\"http:\/\/127.0.0.1:4444\\\",\\\"rskdRpcUserPwd\\\":\\\"user:pass\\\",\\\"isRskCleanJob\\\":true}\";\n \n StratumJobBitcoin *sjob = new StratumJobBitcoin();\n sjob->unserializeFromJson(sjobJson.c_str(), sjobJson.size());\n\n StratumJobExBitcoin exjob(sjob, true);\n \n CBlockHeader header;\n std::vector<char> coinbaseBin;\n\n exjob.generateBlockHeader(\n &header, &coinbaseBin,\n 0xfe0000c3u, \"260103fe60004690\",\n sjob->merkleBranch_, sjob->prevHash_,\n sjob->nBits_, sjob->nVersion_,\n 0x5c39a313u, 0x07ba7929u,\n 0x00013f00u\n );\n \n uint256 blkHash = uint256S(\"1028e53e8145994a9ebe4f39eb6a7e3fd4036f2f21a05a5a696e8ac6d0829ef4\");\n ASSERT_EQ(blkHash, header.GetHash());\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef XPATHIC_MATCH_TEST_HPP\n#define XPATHIC_MATCH_TEST_HPP\n\n#include \"..\/CppUnit\/framework\/TestCase.h\"\n#include \"..\/CppUnit\/framework\/TestSuite.h\"\n#include \"..\/CppUnit\/framework\/TestCaller.h\"\n\n#include <XPath\/XPath.hpp>\n#include <DOM\/Simple\/DOMImplementation.h>\n\n\ntemplate<class string_type, class string_adaptor>\nclass MatchTest : public TestCase\n{\n Arabica::XPath::XPath<string_type> parser;\n typedef string_adaptor SA;\n\npublic:\n MatchTest(std::string name) : TestCase(name)\n {\n } \/\/ MatchTest\n\n void setUp()\n {\n } \/\/ setUp\n\n void testParse()\n {\n using namespace Arabica::XPath;\n assertTrue(compileThis(\"\/\"));\n assertTrue(compileThis(\"\/element\"));\n assertTrue(compileThis(\"\/\/element\"));\n assertTrue(compileThis(\"node()\"));\n assertTrue(compileThis(\"text()\"));\n assertTrue(compileThis(\"element\"));\n assertTrue(compileThis(\"element\/child\"));\n assertTrue(compileThis(\"\/element\/child\"));\n assertTrue(compileThis(\"\/\/element\/child\"));\n assertTrue(compileThis(\"\/element\/\/child\"));\n assertTrue(compileThis(\"\/\/element\/\/child\"));\n assertTrue(compileThis(\"element\/child\/child\"));\n assertTrue(compileThis(\"\/element\/child\/child\"));\n assertTrue(compileThis(\"\/\/element\/child\/child\"));\n assertTrue(compileThis(\"\/element\/\/child\/child\"));\n assertTrue(compileThis(\"\/\/element\/\/child\/child\"));\n assertTrue(compileThis(\"\/\/element\/\/child\/\/child\"));\n assertTrue(compileThis(\"element[@ref]\"));\n assertTrue(compileThis(\"element[@type]|element[complexType]|attribute\"));\n assertTrue(compileThis(\"node()|@*\"));\n assertTrue(compileThis(\"hello\"));\n assertTrue(compileThis(\"@hello\"));\n assertTrue(compileThis(\"child::hello\"));\n assertTrue(compileThis(\"attribute::hello\"));\n assertTrue(compileThis(\"hello[@ref]\"));\n assertTrue(compileThis(\"@hello[..\/poop]\"));\n assertTrue(compileThis(\"child::hello[..\/poop]\"));\n assertTrue(compileThis(\"attribute::hello[..\/poop]\"));\n assertTrue(compileThis(\"node()|attribute::*\"));\n } \/\/ testParse\n\n void testParseFails()\n {\n using namespace Arabica::XPath;\n assertTrue(dontCompileThis(\"boolean(..\/hello)\"));\n assertTrue(dontCompileThis(\"..\/hello\"));\n assertTrue(dontCompileThis(\"following-sibling::hello\"));\n assertTrue(dontCompileThis(\"descendant::hello\"));\n assertTrue(dontCompileThis(\"ancestor-or-self::hello\"));\n assertTrue(dontCompileThis(\"\/\/\/\"));\n assertTrue(dontCompileThis(\"test\/\/\/test\"));\n assertTrue(dontCompileThis(\"descendant-or-self::element\"));\n assertTrue(dontCompileThis(\"\/\/element\/following-sibling::trousers\"));\n } \/\/ testParseFails\n\n bool dontCompileThis(const char* path)\n {\n try {\n parser.compile_match(SA::construct_from_utf8(path));\n return false;\n }\n catch(const Arabica::XPath::SyntaxException& ex) {\n std::cerr << ex.what() << std::endl;\n }\n return true;\n } \/\/ dontCompileThis\n\n bool compileThis(const char* path)\n {\n try {\n std::cout << \"\\n-----\\n\" << path << \"\\n\";\n parser.compile_match(SA::construct_from_utf8(path));\n return true;\n }\n catch(const Arabica::XPath::UnsupportedException&) {\n return true;\n }\n catch(const Arabica::XPath::SyntaxException& ex) {\n std::cerr << ex.what() << std::endl;\n }\n return false;\n } \/\/ compileThis\n\n}; \/\/ class MatchTest\n\ntemplate<class string_type, class string_adaptor>\nTestSuite* MatchTest_suite() \n{\n TestSuite *suiteOfTests = new TestSuite;\n\n suiteOfTests->addTest(new TestCaller<MatchTest<string_type, string_adaptor> >(\"testParse\", &MatchTest<string_type, string_adaptor>::testParse));\n suiteOfTests->addTest(new TestCaller<MatchTest<string_type, string_adaptor> >(\"testParseFail\", &MatchTest<string_type, string_adaptor>::testParseFails));\n \n return suiteOfTests;\n} \/\/ MatchTest_suite\n\n#endif\n\n<commit_msg>started evaluating matches<commit_after>#ifndef XPATHIC_MATCH_TEST_HPP\n#define XPATHIC_MATCH_TEST_HPP\n\n#include \"..\/CppUnit\/framework\/TestCase.h\"\n#include \"..\/CppUnit\/framework\/TestSuite.h\"\n#include \"..\/CppUnit\/framework\/TestCaller.h\"\n\n#include <XPath\/XPath.hpp>\n#include <DOM\/SAX2DOM\/SAX2DOM.h>\n#include <SAX\/helpers\/CatchErrorHandler.h>\n\n\ntemplate<class string_type, class string_adaptor>\nclass MatchTest : public TestCase\n{\n Arabica::XPath::XPath<string_type> parser;\n typedef string_adaptor SA;\n\npublic:\n MatchTest(std::string name) : TestCase(name)\n {\n } \/\/ MatchTest\n\n void setUp()\n {\n } \/\/ setUp\n\n void testParse()\n {\n using namespace Arabica::XPath;\n assertTrue(compileThis(\"\/\"));\n assertTrue(compileThis(\"\/element\"));\n assertTrue(compileThis(\"\/\/element\"));\n assertTrue(compileThis(\"node()\"));\n assertTrue(compileThis(\"text()\"));\n assertTrue(compileThis(\"element\"));\n assertTrue(compileThis(\"element\/child\"));\n assertTrue(compileThis(\"\/element\/child\"));\n assertTrue(compileThis(\"\/\/element\/child\"));\n assertTrue(compileThis(\"\/element\/\/child\"));\n assertTrue(compileThis(\"\/\/element\/\/child\"));\n assertTrue(compileThis(\"element\/child\/child\"));\n assertTrue(compileThis(\"\/element\/child\/child\"));\n assertTrue(compileThis(\"\/\/element\/child\/child\"));\n assertTrue(compileThis(\"\/element\/\/child\/child\"));\n assertTrue(compileThis(\"\/\/element\/\/child\/child\"));\n assertTrue(compileThis(\"\/\/element\/\/child\/\/child\"));\n assertTrue(compileThis(\"element[@ref]\"));\n assertTrue(compileThis(\"element[@type]|element[complexType]|attribute\"));\n assertTrue(compileThis(\"node()|@*\"));\n assertTrue(compileThis(\"hello\"));\n assertTrue(compileThis(\"doc\"));\n assertTrue(compileThis(\"@hello\"));\n assertTrue(compileThis(\"child::hello\"));\n assertTrue(compileThis(\"attribute::hello\"));\n assertTrue(compileThis(\"hello[@ref]\"));\n assertTrue(compileThis(\"@hello[..\/poop]\"));\n assertTrue(compileThis(\"child::hello[..\/poop]\"));\n assertTrue(compileThis(\"attribute::hello[..\/poop]\"));\n assertTrue(compileThis(\"node()|attribute::*\"));\n } \/\/ testParse\n\n void testParseFails()\n {\n using namespace Arabica::XPath;\n assertTrue(dontCompileThis(\"boolean(..\/hello)\"));\n assertTrue(dontCompileThis(\"..\/hello\"));\n assertTrue(dontCompileThis(\"following-sibling::hello\"));\n assertTrue(dontCompileThis(\"descendant::hello\"));\n assertTrue(dontCompileThis(\"ancestor-or-self::hello\"));\n assertTrue(dontCompileThis(\"\/\/\/\"));\n assertTrue(dontCompileThis(\"test\/\/\/test\"));\n assertTrue(dontCompileThis(\"descendant-or-self::element\"));\n assertTrue(dontCompileThis(\"\/\/element\/following-sibling::trousers\"));\n } \/\/ testParseFails\n\n void testEvaluateDocMatch()\n {\n DOM::Document<string_type> doc = parseXML(\"<doc><para>hello<\/para><\/doc>\");\n assertTrue(compileMatch(\"\/\")->evaluateAsBool(doc));\n } \/\/ testEvaluateDocMatch\n\n void testDocElementMatch()\n {\n DOM::Document<string_type> doc = parseXML(\"<doc><para>hello<\/para><\/doc>\");\n\n assertTrue(compileMatch(\"doc\")->evaluateAsBool(doc.getDocumentElement()));\n assertTrue(compileMatch(\"doc[para]\")->evaluateAsBool(doc.getDocumentElement()));\n assertTrue(compileMatch(\"*\")->evaluateAsBool(doc.getDocumentElement()));\n assertTrue(compileMatch(\"node()\")->evaluateAsBool(doc.getDocumentElement()));\n assertTrue(compileMatch(\"\/doc\")->evaluateAsBool(doc.getDocumentElement()));\n assertTrue(compileMatch(\"\/\/doc\")->evaluateAsBool(doc.getDocumentElement()));\n } \/\/ testDocElementMatch\n\n void testDocElementNotMatch()\n {\n DOM::Document<string_type> doc = parseXML(\"<doc><para>hello<\/para><\/doc>\");\n\n assertFalse(compileMatch(\"para\")->evaluateAsBool(doc.getDocumentElement()));\n assertFalse(compileMatch(\"text()\")->evaluateAsBool(doc.getDocumentElement()));\n assertFalse(compileMatch(\"comment()\")->evaluateAsBool(doc.getDocumentElement()));\n assertFalse(compileMatch(\"processing-instruction()\")->evaluateAsBool(doc.getDocumentElement()));\n assertFalse(compileMatch(\"\/para\")->evaluateAsBool(doc.getDocumentElement()));\n assertFalse(compileMatch(\"\/\/para\")->evaluateAsBool(doc.getDocumentElement()));\n } \/\/ testDocElementNotMatch\n\n\n bool dontCompileThis(const char* path)\n {\n try {\n compileMatch(path);\n return false;\n }\n catch(const Arabica::XPath::SyntaxException& ex) {\n std::cerr << ex.what() << std::endl;\n }\n return true;\n } \/\/ dontCompileThis\n\n bool compileThis(const char* path)\n {\n try {\n std::cout << \"\\n-----\\n\" << path << \"\\n\";\n compileMatch(path);\n return true;\n }\n catch(const Arabica::XPath::UnsupportedException&) {\n return true;\n }\n catch(const Arabica::XPath::SyntaxException& ex) {\n std::cerr << ex.what() << std::endl;\n }\n return false;\n } \/\/ compileThis\n\n Arabica::XPath::XPathExpressionPtr<string_type, string_adaptor> compileMatch(const char* match)\n {\n return parser.compile_match(SA::construct_from_utf8(match));\n } \/\/ compileMatch\n\n DOM::Document<string_type> parseXML(const char* match)\n {\n std::stringstream ss;\n ss << match;\n\n SAX::basic_InputSource<string_type> is(ss);\n SAX::CatchErrorHandler<string_type> eh;\n SAX2DOM::Parser<string_type, string_adaptor> parser;\n parser.setErrorHandler(eh);\n parser.parse(is); \n\n if(eh.errorsReported())\n throw std::runtime_error(eh.errors());\n\n return parser.getDocument();\n } \/\/ parse\n}; \/\/ class MatchTest\n\ntemplate<class string_type, class string_adaptor>\nTestSuite* MatchTest_suite() \n{\n TestSuite *suiteOfTests = new TestSuite;\n\n suiteOfTests->addTest(new TestCaller<MatchTest<string_type, string_adaptor> >(\"testParse\", &MatchTest<string_type, string_adaptor>::testParse));\n suiteOfTests->addTest(new TestCaller<MatchTest<string_type, string_adaptor> >(\"testParseFail\", &MatchTest<string_type, string_adaptor>::testParseFails));\n suiteOfTests->addTest(new TestCaller<MatchTest<string_type, string_adaptor> >(\"testEvaluateDocMatch\", &MatchTest<string_type, string_adaptor>::testEvaluateDocMatch));\n suiteOfTests->addTest(new TestCaller<MatchTest<string_type, string_adaptor> >(\"testDocElementMatch\", &MatchTest<string_type, string_adaptor>::testDocElementMatch));\n suiteOfTests->addTest(new TestCaller<MatchTest<string_type, string_adaptor> >(\"testDocElementNotMatch\", &MatchTest<string_type, string_adaptor>::testDocElementNotMatch));\n \n return suiteOfTests;\n} \/\/ MatchTest_suite\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra\n *\n * This file is part of Essentia\n *\n * Essentia is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License as published by the Free\n * Software Foundation (FSF), either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the Affero GNU General Public License\n * version 3 along with this program. If not, see http:\/\/www.gnu.org\/licenses\/\n *\/\n\n#include \"debugging.h\"\n#include <iostream>\n\n#ifndef _WIN32\n#include <unistd.h>\n#endif\n\nusing namespace std;\n\nnamespace essentia {\n\nbool infoLevelActive = true;\nbool warningLevelActive = true;\nbool errorLevelActive = true;\n\nint activatedDebugLevels = 0;\nint debugIndentLevel = 0;\n\nLogger loggerInstance;\n\nconst char* debugModuleDescription(DebuggingModule module) {\n switch (module) {\n case EAlgorithm: return \"[Algorithm ] \";\n case EConnectors: return \"[Connectors] \";\n case EFactory: return \"[Factory ] \";\n case ENetwork: return \"[Network ] \";\n case EGraph: return \"[Graph ] \";\n case EExecution: return \"[Execution ] \";\n case EMemory: return \"[Memory ] \";\n case EScheduler: return \"[Scheduler ] \";\n\n case EPython: return \"[ PYTHON ] \";\n case EPyBindings: return \"[ PYBIND ] \";\n case EUnittest: return \"[ UNITTEST ] \";\n\n case EUser1: return \"[ USER1 ] \";\n case EUser2: return \"[ USER2 ] \";\n\n case ENone: return \"[ ] \";\n case EAll: return \"[ ALL ] \";\n default: return \"[ Mixed ] \";\n }\n}\n\n\nvoid setDebugLevel(int levels) {\n activatedDebugLevels |= levels;\n}\n\nvoid unsetDebugLevel(int levels) {\n activatedDebugLevels &= ~levels;\n}\n\n\nDebuggingScheduleVector _schedule;\n\nint _savedDebugLevels = ENone;\n\nvoid scheduleDebug(const DebuggingScheduleVector& schedule) {\n _schedule = schedule;\n}\n\nvoid scheduleDebug(DebuggingSchedule schedule, int nentries) {\n _schedule.resize(nentries);\n for (int i=0; i<nentries; i++) {\n _schedule[i].first.first = schedule[i][0];\n _schedule[i].first.second = schedule[i][1];\n _schedule[i].second = schedule[i][2];\n }\n}\n\nvoid restoreDebugLevels() {\n activatedDebugLevels = _savedDebugLevels;\n}\n\nvoid saveDebugLevels() {\n _savedDebugLevels = activatedDebugLevels;\n}\n\nvoid setDebugLevelForTimeIndex(int index) {\n restoreDebugLevels();\n for (int i=0; i<(int)_schedule.size(); i++) {\n if (_schedule[i].first.first <= index && index <= _schedule[i].first.second) {\n setDebugLevel(_schedule[i].second);\n }\n }\n}\n\n\n\/\/ NOTE: in a thread-safe implementation, the msg queue would be thread-safe and\n\/\/ the flushing would need to happen in a separate thread\n\/\/ This can be achieved using tbb::concurrent_queue\n\nvoid Logger::flush() {\n while (!_msgQueue.empty()) {\n std::cerr << _msgQueue.front();\n \/\/std::cout << _msgQueue.front() << std::flush;\n _msgQueue.pop_front();\n }\n}\n\nvoid Logger::debug(DebuggingModule module, const string& msg, bool resetHeader) {\n if (module & activatedDebugLevels) {\n if (_addHeader) {\n _msgQueue.push_back(E_STRINGIFY(debugModuleDescription(module) \/\/ module name\n + string(debugIndentLevel * 8, ' ') \/\/ indentation\n + msg)); \/\/ msg\n }\n else {\n _msgQueue.push_back(msg);\n }\n\n _addHeader = resetHeader;\n flush();\n }\n}\n\nvoid Logger::info(const string& msg) {\n if (!infoLevelActive) return;\n static string GREEN_FONT = \"\\x1B[0;32m\";\n static string RESET_FONT = \"\\x1B[0m\";\n\n#ifndef _WIN32\n if(!isatty(2)) { \/\/ no colors if stderr is not a terminal\n GREEN_FONT.clear();\n RESET_FONT .clear();\n }\n#endif\n\n _msgQueue.push_back(E_STRINGIFY(GREEN_FONT << \"[ INFO ] \" << RESET_FONT << msg << '\\n'));\n flush();\n}\n\nvoid Logger::warning(const string& msg) {\n if (!warningLevelActive) return;\n static string YELLOW_FONT = \"\\x1B[0;33m\";\n static string RESET_FONT = \"\\x1B[0m\";\n\n#ifndef _WIN32\n if(!isatty(2)) {\n YELLOW_FONT.clear();\n RESET_FONT.clear();\n }\n#endif\n\n _msgQueue.push_back(E_STRINGIFY(YELLOW_FONT << \"[ WARNING ] \" << RESET_FONT << msg << '\\n'));\n flush();\n}\n\nvoid Logger::error(const string& msg) {\n if (!errorLevelActive) return;\n static string RED_FONT = \"\\x1B[0;31m\";\n static string RESET_FONT = \"\\x1B[0m\";\n\n#ifndef _WIN32\n if(!isatty(2)) {\n RED_FONT.clear();\n RESET_FONT.clear();\n }\n#endif\n\n _msgQueue.push_back(E_STRINGIFY(RED_FONT << \"[ ERROR ] \" << RESET_FONT << msg << '\\n'));\n flush();\n}\n\n} \/\/ namespace essentia\n<commit_msg>Remove space<commit_after>\/*\n * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra\n *\n * This file is part of Essentia\n *\n * Essentia is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License as published by the Free\n * Software Foundation (FSF), either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the Affero GNU General Public License\n * version 3 along with this program. If not, see http:\/\/www.gnu.org\/licenses\/\n *\/\n\n#include \"debugging.h\"\n#include <iostream>\n\n#ifndef _WIN32\n#include <unistd.h>\n#endif\n\nusing namespace std;\n\nnamespace essentia {\n\nbool infoLevelActive = true;\nbool warningLevelActive = true;\nbool errorLevelActive = true;\n\nint activatedDebugLevels = 0;\nint debugIndentLevel = 0;\n\nLogger loggerInstance;\n\nconst char* debugModuleDescription(DebuggingModule module) {\n switch (module) {\n case EAlgorithm: return \"[Algorithm ] \";\n case EConnectors: return \"[Connectors] \";\n case EFactory: return \"[Factory ] \";\n case ENetwork: return \"[Network ] \";\n case EGraph: return \"[Graph ] \";\n case EExecution: return \"[Execution ] \";\n case EMemory: return \"[Memory ] \";\n case EScheduler: return \"[Scheduler ] \";\n\n case EPython: return \"[ PYTHON ] \";\n case EPyBindings: return \"[ PYBIND ] \";\n case EUnittest: return \"[ UNITTEST ] \";\n\n case EUser1: return \"[ USER1 ] \";\n case EUser2: return \"[ USER2 ] \";\n\n case ENone: return \"[ ] \";\n case EAll: return \"[ ALL ] \";\n default: return \"[ Mixed ] \";\n }\n}\n\n\nvoid setDebugLevel(int levels) {\n activatedDebugLevels |= levels;\n}\n\nvoid unsetDebugLevel(int levels) {\n activatedDebugLevels &= ~levels;\n}\n\n\nDebuggingScheduleVector _schedule;\n\nint _savedDebugLevels = ENone;\n\nvoid scheduleDebug(const DebuggingScheduleVector& schedule) {\n _schedule = schedule;\n}\n\nvoid scheduleDebug(DebuggingSchedule schedule, int nentries) {\n _schedule.resize(nentries);\n for (int i=0; i<nentries; i++) {\n _schedule[i].first.first = schedule[i][0];\n _schedule[i].first.second = schedule[i][1];\n _schedule[i].second = schedule[i][2];\n }\n}\n\nvoid restoreDebugLevels() {\n activatedDebugLevels = _savedDebugLevels;\n}\n\nvoid saveDebugLevels() {\n _savedDebugLevels = activatedDebugLevels;\n}\n\nvoid setDebugLevelForTimeIndex(int index) {\n restoreDebugLevels();\n for (int i=0; i<(int)_schedule.size(); i++) {\n if (_schedule[i].first.first <= index && index <= _schedule[i].first.second) {\n setDebugLevel(_schedule[i].second);\n }\n }\n}\n\n\n\/\/ NOTE: in a thread-safe implementation, the msg queue would be thread-safe and\n\/\/ the flushing would need to happen in a separate thread\n\/\/ This can be achieved using tbb::concurrent_queue\n\nvoid Logger::flush() {\n while (!_msgQueue.empty()) {\n std::cerr << _msgQueue.front();\n \/\/std::cout << _msgQueue.front() << std::flush;\n _msgQueue.pop_front();\n }\n}\n\nvoid Logger::debug(DebuggingModule module, const string& msg, bool resetHeader) {\n if (module & activatedDebugLevels) {\n if (_addHeader) {\n _msgQueue.push_back(E_STRINGIFY(debugModuleDescription(module) \/\/ module name\n + string(debugIndentLevel * 8, ' ') \/\/ indentation\n + msg)); \/\/ msg\n }\n else {\n _msgQueue.push_back(msg);\n }\n\n _addHeader = resetHeader;\n flush();\n }\n}\n\nvoid Logger::info(const string& msg) {\n if (!infoLevelActive) return;\n static string GREEN_FONT = \"\\x1B[0;32m\";\n static string RESET_FONT = \"\\x1B[0m\";\n\n#ifndef _WIN32\n if(!isatty(2)) { \/\/ no colors if stderr is not a terminal\n GREEN_FONT.clear();\n RESET_FONT.clear();\n }\n#endif\n\n _msgQueue.push_back(E_STRINGIFY(GREEN_FONT << \"[ INFO ] \" << RESET_FONT << msg << '\\n'));\n flush();\n}\n\nvoid Logger::warning(const string& msg) {\n if (!warningLevelActive) return;\n static string YELLOW_FONT = \"\\x1B[0;33m\";\n static string RESET_FONT = \"\\x1B[0m\";\n\n#ifndef _WIN32\n if(!isatty(2)) {\n YELLOW_FONT.clear();\n RESET_FONT.clear();\n }\n#endif\n\n _msgQueue.push_back(E_STRINGIFY(YELLOW_FONT << \"[ WARNING ] \" << RESET_FONT << msg << '\\n'));\n flush();\n}\n\nvoid Logger::error(const string& msg) {\n if (!errorLevelActive) return;\n static string RED_FONT = \"\\x1B[0;31m\";\n static string RESET_FONT = \"\\x1B[0m\";\n\n#ifndef _WIN32\n if(!isatty(2)) {\n RED_FONT.clear();\n RESET_FONT.clear();\n }\n#endif\n\n _msgQueue.push_back(E_STRINGIFY(RED_FONT << \"[ ERROR ] \" << RESET_FONT << msg << '\\n'));\n flush();\n}\n\n} \/\/ namespace essentia\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/cli\/console.h>\n#include <eventql\/util\/inspect.h>\n#include \"eventql\/util\/logging.h\"\n#include \"eventql\/util\/random.h\"\n#include \"eventql\/util\/util\/Base64.h\"\n#include \"eventql\/util\/thread\/eventloop.h\"\n#include \"eventql\/util\/thread\/threadpool.h\"\n#include \"eventql\/util\/thread\/FixedSizeThreadPool.h\"\n#include \"eventql\/util\/io\/TerminalOutputStream.h\"\n#include \"eventql\/util\/wallclock.h\"\n#include \"eventql\/util\/json\/json.h\"\n#include \"eventql\/util\/json\/jsonrpc.h\"\n#include \"eventql\/util\/http\/httpclient.h\"\n#include \"eventql\/util\/http\/HTTPSSEResponseHandler.h\"\n#include \"eventql\/util\/cli\/CLI.h\"\n#include \"eventql\/util\/cli\/flagparser.h\"\n#include \"eventql\/util\/cli\/term.h\"\n#include \"eventql\/server\/sql\/codec\/binary_codec.h\"\n#include \"eventql\/sql\/result_list.h\"\n#include \"linenoise\/linenoise.h\"\n\nnamespace eventql {\nnamespace cli {\n\nvoid Console::startInteractiveShell() {\n char *p;\n while ((p = linenoise(\"evql> \")) != NULL) {\n String line(p);\n linenoiseFree(p);\n\n if (line == \"quit\") {\n return;\n\n } else {\n runQuery(line);\n }\n }\n}\n\nConsole::Console(const CLIConfig cli_cfg) : cfg_(cli_cfg) {}\n\nStatus Console::runQuery(const String& query) {\n auto stdout_os = OutputStream::getStdout();\n auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());\n bool line_dirty = false;\n bool is_tty = stderr_os->isTTY();\n\n bool error = false;\n csql::BinaryResultParser res_parser;\n csql::ResultList results;\n\n res_parser.onProgress([&stderr_os, &line_dirty, is_tty] (\n const csql::ExecutionStatus& status) {\n auto status_line = StringUtil::format(\n \"Query running: $0%\",\n status.progress * 100);\n\n if (is_tty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\" + status_line);\n line_dirty = true;\n } else {\n stderr_os->print(status_line + \"\\n\");\n }\n\n });\n\n res_parser.onTableHeader([&results] (const Vector<String>& columns) {\n results.addHeader(columns);\n });\n\n res_parser.onRow([&results] (int argc, const csql::SValue* argv) {\n results.addRow(argv, argc);\n });\n\n res_parser.onError([&stderr_os, &error] (const String& error_str) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(StringUtil::format(\" $0\\n\", error_str));\n error = true;\n });\n\n try {\n auto url = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/sql\",\n cfg_.getHost(),\n cfg_.getPort());\n\n auto postdata = StringUtil::format(\n \"format=binary&query=$0&database=$1\",\n URI::urlEncode(query),\n URI::urlEncode(cfg_.getDatabase()));\n\n http::HTTPMessage::HeaderList auth_headers;\n if (!cfg_.getAuthToken().isEmpty()) {\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", cfg_.getAuthToken().get()));\n } else if (!cfg_.getUser().empty()) {\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Basic $0\",\n util::Base64::encode(cfg_.getUser() + \":\" + cfg_.getPassword())));\n }\n\n http::HTTPClient http_client(nullptr);\n auto req = http::HTTPRequest::mkPost(url, postdata, auth_headers);\n auto res = http_client.executeRequest(\n req,\n http::StreamingResponseHandler::getFactory(\n std::bind(\n &csql::BinaryResultParser::parse,\n &res_parser,\n std::placeholders::_1,\n std::placeholders::_2)));\n\n if (!res_parser.eof()) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(\" connection to server lost\");\n return Status(eIOError);\n }\n } catch (const StandardException& e) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(StringUtil::format(\" $0\\n\", e.what()));\n return Status(eIOError);\n }\n\n if (is_tty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\");\n }\n\n if (error) {\n return Status(eIOError);\n }\n\n results.debugPrint();\n\n auto num_rows = results.getNumRows();\n auto status_line = StringUtil::format(\n \"$0 row$1 returned\",\n num_rows,\n num_rows > 1 ? \"s\" : \"\");\n\n if (is_tty) {\n stderr_os->print(\"\\r\" + status_line + \"\\n\");\n } else {\n stderr_os->print(status_line + \"\\n\");\n }\n\n return Status::success();\n}\n\nStatus Console::runJS(const String& program_source) {\n auto stdout_os = OutputStream::getStdout();\n auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());\n\n try {\n\n bool finished = false;\n bool error = false;\n String error_string;\n bool line_dirty = false;\n bool is_tty = stderr_os->isTTY();\n\n auto event_handler = [&] (const http::HTTPSSEEvent& ev) {\n if (ev.name.isEmpty()) {\n return;\n }\n\n if (ev.name.get() == \"status\") {\n auto obj = json::parseJSON(ev.data);\n auto tasks_completed = json::objectGetUInt64(obj, \"num_tasks_completed\");\n auto tasks_total = json::objectGetUInt64(obj, \"num_tasks_total\");\n auto tasks_running = json::objectGetUInt64(obj, \"num_tasks_running\");\n auto progress = json::objectGetFloat(obj, \"progress\");\n\n auto status_line = StringUtil::format(\n \"[$0\/$1] $2 tasks running ($3%)\",\n tasks_completed.isEmpty() ? 0 : tasks_completed.get(),\n tasks_total.isEmpty() ? 0 : tasks_total.get(),\n tasks_running.isEmpty() ? 0 : tasks_running.get(),\n progress.isEmpty() ? 0 : progress.get() * 100);\n\n if (is_tty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\" + status_line);\n line_dirty = true;\n } else {\n stderr_os->print(status_line + \"\\n\");\n }\n\n return;\n }\n\n if (line_dirty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\");\n line_dirty = false;\n }\n\n if (ev.name.get() == \"job_started\") {\n \/\/stderr_os->printYellow(\">> Job started\\n\");\n return;\n }\n\n if (ev.name.get() == \"job_finished\") {\n finished = true;\n return;\n }\n\n if (ev.name.get() == \"error\") {\n error = true;\n error_string = URI::urlDecode(ev.data);\n return;\n }\n\n if (ev.name.get() == \"result\") {\n stdout_os->write(URI::urlDecode(ev.data) + \"\\n\");\n return;\n }\n\n if (ev.name.get() == \"log\") {\n stderr_os->print(URI::urlDecode(ev.data) + \"\\n\");\n return;\n }\n\n };\n\n auto url = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/mapreduce\/execute\",\n cfg_.getHost(),\n cfg_.getPort());\n\n http::HTTPMessage::HeaderList auth_headers;\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", cfg_.getAuthToken().get()));\n\n if (is_tty) {\n stderr_os->print(\"Launching job...\");\n line_dirty = true;\n } else {\n stderr_os->print(\"Launching job...\\n\");\n }\n\n http::HTTPClient http_client(nullptr);\n auto req = http::HTTPRequest::mkPost(url, program_source, auth_headers);\n auto res = http_client.executeRequest(\n req,\n http::HTTPSSEResponseHandler::getFactory(event_handler));\n\n if (line_dirty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\");\n }\n\n if (res.statusCode() != 200) {\n error = true;\n error_string = \"HTTP Error: \" + res.body().toString();\n }\n\n if (!finished && !error) {\n error = true;\n error_string = \"connection to server lost\";\n }\n\n if (error) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(\" \" + error_string + \"\\n\");\n return Status(eIOError);\n } else {\n stderr_os->printGreen(\"Job successfully completed\\n\");\n return Status::success();\n }\n } catch (const StandardException& e) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(StringUtil::format(\" $0\\n\", e.what()));\n return Status(eIOError);\n }\n\n}\n\n\n} \/\/ namespace cli\n} \/\/ namespace eventql\n\n<commit_msg>console: print empty result<commit_after>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/cli\/console.h>\n#include <eventql\/util\/inspect.h>\n#include \"eventql\/util\/logging.h\"\n#include \"eventql\/util\/random.h\"\n#include \"eventql\/util\/util\/Base64.h\"\n#include \"eventql\/util\/thread\/eventloop.h\"\n#include \"eventql\/util\/thread\/threadpool.h\"\n#include \"eventql\/util\/thread\/FixedSizeThreadPool.h\"\n#include \"eventql\/util\/io\/TerminalOutputStream.h\"\n#include \"eventql\/util\/wallclock.h\"\n#include \"eventql\/util\/json\/json.h\"\n#include \"eventql\/util\/json\/jsonrpc.h\"\n#include \"eventql\/util\/http\/httpclient.h\"\n#include \"eventql\/util\/http\/HTTPSSEResponseHandler.h\"\n#include \"eventql\/util\/cli\/CLI.h\"\n#include \"eventql\/util\/cli\/flagparser.h\"\n#include \"eventql\/util\/cli\/term.h\"\n#include \"eventql\/server\/sql\/codec\/binary_codec.h\"\n#include \"eventql\/sql\/result_list.h\"\n#include \"linenoise\/linenoise.h\"\n\nnamespace eventql {\nnamespace cli {\n\nvoid Console::startInteractiveShell() {\n char *p;\n while ((p = linenoise(\"evql> \")) != NULL) {\n String line(p);\n linenoiseFree(p);\n\n if (line == \"quit\") {\n return;\n\n } else {\n runQuery(line);\n }\n }\n}\n\nConsole::Console(const CLIConfig cli_cfg) : cfg_(cli_cfg) {}\n\nStatus Console::runQuery(const String& query) {\n auto stdout_os = OutputStream::getStdout();\n auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());\n bool line_dirty = false;\n bool is_tty = stderr_os->isTTY();\n\n bool error = false;\n csql::BinaryResultParser res_parser;\n csql::ResultList results;\n\n res_parser.onProgress([&stderr_os, &line_dirty, is_tty] (\n const csql::ExecutionStatus& status) {\n auto status_line = StringUtil::format(\n \"Query running: $0%\",\n status.progress * 100);\n\n if (is_tty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\" + status_line);\n line_dirty = true;\n } else {\n stderr_os->print(status_line + \"\\n\");\n }\n\n });\n\n res_parser.onTableHeader([&results] (const Vector<String>& columns) {\n results.addHeader(columns);\n });\n\n res_parser.onRow([&results] (int argc, const csql::SValue* argv) {\n results.addRow(argv, argc);\n });\n\n res_parser.onError([&stderr_os, &error] (const String& error_str) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(StringUtil::format(\" $0\\n\", error_str));\n error = true;\n });\n\n try {\n auto url = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/sql\",\n cfg_.getHost(),\n cfg_.getPort());\n\n auto postdata = StringUtil::format(\n \"format=binary&query=$0&database=$1\",\n URI::urlEncode(query),\n URI::urlEncode(cfg_.getDatabase()));\n\n http::HTTPMessage::HeaderList auth_headers;\n if (!cfg_.getAuthToken().isEmpty()) {\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", cfg_.getAuthToken().get()));\n } else if (!cfg_.getUser().empty()) {\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Basic $0\",\n util::Base64::encode(cfg_.getUser() + \":\" + cfg_.getPassword())));\n }\n\n http::HTTPClient http_client(nullptr);\n auto req = http::HTTPRequest::mkPost(url, postdata, auth_headers);\n auto res = http_client.executeRequest(\n req,\n http::StreamingResponseHandler::getFactory(\n std::bind(\n &csql::BinaryResultParser::parse,\n &res_parser,\n std::placeholders::_1,\n std::placeholders::_2)));\n\n if (!res_parser.eof()) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(\" connection to server lost\");\n return Status(eIOError);\n }\n } catch (const StandardException& e) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(StringUtil::format(\" $0\\n\", e.what()));\n return Status(eIOError);\n }\n\n if (is_tty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\");\n }\n\n if (error) {\n return Status(eIOError);\n }\n\n if (results.getNumRows() == 0) {\n String line;\n if (is_tty) {\n line = \"\\r\";\n }\n\n if (results.getNumColumns() == 0) {\n line += \"Query OK \\n\\n\";\n } else {\n line += \"Empty set \\n\\n\";\n }\n\n stderr_os->print(line);\n return Status::success();\n }\n\n\n results.debugPrint();\n\n auto num_rows = results.getNumRows();\n auto status_line = StringUtil::format(\n \"$0 row$1 returned\",\n num_rows,\n num_rows > 1 ? \"s\" : \"\");\n\n if (is_tty) {\n stderr_os->print(\"\\r\" + status_line + \"\\n\\n\");\n } else {\n stderr_os->print(status_line + \"\\n\\n\");\n }\n\n return Status::success();\n}\n\nStatus Console::runJS(const String& program_source) {\n auto stdout_os = OutputStream::getStdout();\n auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());\n\n try {\n\n bool finished = false;\n bool error = false;\n String error_string;\n bool line_dirty = false;\n bool is_tty = stderr_os->isTTY();\n\n auto event_handler = [&] (const http::HTTPSSEEvent& ev) {\n if (ev.name.isEmpty()) {\n return;\n }\n\n if (ev.name.get() == \"status\") {\n auto obj = json::parseJSON(ev.data);\n auto tasks_completed = json::objectGetUInt64(obj, \"num_tasks_completed\");\n auto tasks_total = json::objectGetUInt64(obj, \"num_tasks_total\");\n auto tasks_running = json::objectGetUInt64(obj, \"num_tasks_running\");\n auto progress = json::objectGetFloat(obj, \"progress\");\n\n auto status_line = StringUtil::format(\n \"[$0\/$1] $2 tasks running ($3%)\",\n tasks_completed.isEmpty() ? 0 : tasks_completed.get(),\n tasks_total.isEmpty() ? 0 : tasks_total.get(),\n tasks_running.isEmpty() ? 0 : tasks_running.get(),\n progress.isEmpty() ? 0 : progress.get() * 100);\n\n if (is_tty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\" + status_line);\n line_dirty = true;\n } else {\n stderr_os->print(status_line + \"\\n\");\n }\n\n return;\n }\n\n if (line_dirty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\");\n line_dirty = false;\n }\n\n if (ev.name.get() == \"job_started\") {\n \/\/stderr_os->printYellow(\">> Job started\\n\");\n return;\n }\n\n if (ev.name.get() == \"job_finished\") {\n finished = true;\n return;\n }\n\n if (ev.name.get() == \"error\") {\n error = true;\n error_string = URI::urlDecode(ev.data);\n return;\n }\n\n if (ev.name.get() == \"result\") {\n stdout_os->write(URI::urlDecode(ev.data) + \"\\n\");\n return;\n }\n\n if (ev.name.get() == \"log\") {\n stderr_os->print(URI::urlDecode(ev.data) + \"\\n\");\n return;\n }\n\n };\n\n auto url = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/mapreduce\/execute\",\n cfg_.getHost(),\n cfg_.getPort());\n\n http::HTTPMessage::HeaderList auth_headers;\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", cfg_.getAuthToken().get()));\n\n if (is_tty) {\n stderr_os->print(\"Launching job...\");\n line_dirty = true;\n } else {\n stderr_os->print(\"Launching job...\\n\");\n }\n\n http::HTTPClient http_client(nullptr);\n auto req = http::HTTPRequest::mkPost(url, program_source, auth_headers);\n auto res = http_client.executeRequest(\n req,\n http::HTTPSSEResponseHandler::getFactory(event_handler));\n\n if (line_dirty) {\n stderr_os->eraseLine();\n stderr_os->print(\"\\r\");\n }\n\n if (res.statusCode() != 200) {\n error = true;\n error_string = \"HTTP Error: \" + res.body().toString();\n }\n\n if (!finished && !error) {\n error = true;\n error_string = \"connection to server lost\";\n }\n\n if (error) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(\" \" + error_string + \"\\n\");\n return Status(eIOError);\n } else {\n stderr_os->printGreen(\"Job successfully completed\\n\");\n return Status::success();\n }\n } catch (const StandardException& e) {\n stderr_os->print(\n \"ERROR:\",\n { TerminalStyle::RED, TerminalStyle::UNDERSCORE });\n\n stderr_os->print(StringUtil::format(\" $0\\n\", e.what()));\n return Status(eIOError);\n }\n\n}\n\n\n} \/\/ namespace cli\n} \/\/ namespace eventql\n\n<|endoftext|>"} {"text":"<commit_before>#include <jni.h>\n#include <errno.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <android\/log.h>\n#include <android\/native_activity.h>\n#include <android_native_app_glue.h>\n#include <android\/asset_manager.h>\n\n#include \"..\/..\/test_all.hpp\"\n#include \"..\/..\/util\/test_path.hpp\"\n\n#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, \"native-activity\", __VA_ARGS__))\n#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, \"native-activity\", __VA_ARGS__))\n\n\nvoid android_main(struct android_app* state) {\n\n\t\/\/ Make sure glue isn't stripped.\n\tapp_dummy();\n\n\tANativeActivity* nativeActivity = state->activity;\n\tconst char* externalDataPath = nativeActivity->externalDataPath;\n\tconst char* internalDataPath = nativeActivity->internalDataPath;\n\tstd::string inDataPath(internalDataPath);\n\tstd::string exDataPath(externalDataPath);\n\n\tLOGI(\"Copying asset files...\");\n\tconst int buffer_size = 255;\n\tAAssetManager* assetManager = state->activity->assetManager;\n\tAAssetDir* assetDir = AAssetManager_openDir(assetManager, \"\");\n const char* filename = (const char*)NULL;\n while ((filename = AAssetDir_getNextFileName(assetDir)) != NULL) {\n \tLOGI(\"Asset file: %s\", filename);\n\t\tAAsset* asset = AAssetManager_open(assetManager, filename, AASSET_MODE_STREAMING);\n\t\tchar buf[buffer_size];\n\t\tint nb_read = 0;\n\t\tstd::string filename_str(filename);\n\t\tstd::string filepath = inDataPath + \"\/\" + filename_str;\n\t\tFILE* out = fopen(filepath.c_str(), \"w\");\n\t\twhile ((nb_read = AAsset_read(asset, buf, buffer_size)) > 0)\n\t\t fwrite(buf, nb_read, 1, out);\n\t\tfclose(out);\n\t\tAAsset_close(asset);\n }\n AAssetDir_close(assetDir);\n LOGI(\"Copying of asset files completed\");\n\t\n\ttightdb::test_util::PlatformConfig* platform_config = tightdb::test_util::PlatformConfig::Instance();\n\tplatform_config->set_path(inDataPath + \"\/\");\n\tplatform_config->set_resource_path(inDataPath + \"\/\");\n\n\tLOGI(\"Starting unit tests...\");\n\n\ttest_all(0,0);\n\n\tLOGI(\"Done running unit tests...\");\n\n\tLOGI(\"Copying the test results in the external storage\");\n\tstd::string source = inDataPath + \"\/unit-test-report.xml\";\n\tstd::string destination = exDataPath + \"\/unit-test-report.xml\";\n\tstd::ifstream src(source.c_str(), std::ios::binary);\n std::ofstream dst(destination.c_str(), std::ios::binary);\n\tdst << src.rdbuf();\n\tLOGI(\"The XML file is located in %s\", destination.c_str());\n\n\tANativeActivity_finish(nativeActivity);\n\n\treturn;\n}\n<commit_msg>Fix indentation<commit_after>#include <jni.h>\n#include <errno.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <android\/log.h>\n#include <android\/native_activity.h>\n#include <android_native_app_glue.h>\n#include <android\/asset_manager.h>\n\n#include \"..\/..\/test_all.hpp\"\n#include \"..\/..\/util\/test_path.hpp\"\n\n#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, \"native-activity\", __VA_ARGS__))\n#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, \"native-activity\", __VA_ARGS__))\n\n\nvoid android_main(struct android_app* state) {\n\n \/\/ Make sure glue isn't stripped.\n app_dummy();\n\n ANativeActivity* nativeActivity = state->activity;\n const char* externalDataPath = nativeActivity->externalDataPath;\n const char* internalDataPath = nativeActivity->internalDataPath;\n std::string inDataPath(internalDataPath);\n std::string exDataPath(externalDataPath);\n\n LOGI(\"Copying asset files...\");\n const int buffer_size = 255;\n AAssetManager* assetManager = state->activity->assetManager;\n AAssetDir* assetDir = AAssetManager_openDir(assetManager, \"\");\n const char* filename = (const char*)NULL;\n while ((filename = AAssetDir_getNextFileName(assetDir)) != NULL) {\n LOGI(\"Asset file: %s\", filename);\n AAsset* asset = AAssetManager_open(assetManager, filename, AASSET_MODE_STREAMING);\n char buf[buffer_size];\n int nb_read = 0;\n std::string filename_str(filename);\n std::string filepath = inDataPath + \"\/\" + filename_str;\n FILE* out = fopen(filepath.c_str(), \"w\");\n while ((nb_read = AAsset_read(asset, buf, buffer_size)) > 0)\n fwrite(buf, nb_read, 1, out);\n fclose(out);\n AAsset_close(asset);\n }\n AAssetDir_close(assetDir);\n LOGI(\"Copying of asset files completed\");\n\n tightdb::test_util::PlatformConfig* platform_config = tightdb::test_util::PlatformConfig::Instance();\n platform_config->set_path(inDataPath + \"\/\");\n platform_config->set_resource_path(inDataPath + \"\/\");\n\n LOGI(\"Starting unit tests...\");\n\n test_all(0,0);\n\n LOGI(\"Done running unit tests...\");\n\n LOGI(\"Copying the test results in the external storage\");\n std::string source = inDataPath + \"\/unit-test-report.xml\";\n std::string destination = exDataPath + \"\/unit-test-report.xml\";\n std::ifstream src(source.c_str(), std::ios::binary);\n std::ofstream dst(destination.c_str(), std::ios::binary);\n dst << src.rdbuf();\n LOGI(\"The XML file is located in %s\", destination.c_str());\n\n ANativeActivity_finish(nativeActivity);\n\n return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -----------------------------------------------------------------------\n\/\/ pion-common: a collection of common libraries used by the Pion Platform\n\/\/ -----------------------------------------------------------------------\n\/\/ Copyright (C) 2007-2008 Atomic Labs, Inc. (http:\/\/www.atomiclabs.com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ See http:\/\/www.boost.org\/LICENSE_1_0.txt\n\/\/\n\n#include <pion\/PionConfig.hpp>\n#include <pion\/PionCounter.hpp>\n#include <pion\/PionUnitTestDefs.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/mpl\/list.hpp>\n\nusing namespace pion;\n\nclass NewPionCounter_F : public PionCounter {\npublic:\n\tNewPionCounter_F() {\n\t}\n\t~NewPionCounter_F() {\n\t}\n\nprivate:\n};\n\nBOOST_AUTO_TEST_SUITE_FIXTURE_TEMPLATE(NewPionCounter_S, boost::mpl::list<NewPionCounter_F>)\n\nBOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueReturnsZero) {\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));\n}\n\nBOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterIncrement) {\n\tincrement();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(1));\n}\n\nBOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterDecrement) {\n\tdecrement();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(-1));\n}\n\nBOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterReset) {\n\treset();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nclass PionCounterSetTo5_F : public PionCounter {\npublic:\n\tPionCounterSetTo5_F() {\n\t\tassign(5);\n\t}\n\t~PionCounterSetTo5_F() {\n\t}\n\nprivate:\n};\n\nBOOST_AUTO_TEST_SUITE_FIXTURE_TEMPLATE(PionCounterSetTo5_S, boost::mpl::list<PionCounterSetTo5_F>)\n\nBOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueReturns5) {\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(5));\n}\n\nBOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterIncrement) {\n\tincrement();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(6));\n}\n\nBOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterDecrement) {\n\tdecrement();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(4));\n}\n\nBOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterReset) {\n\treset();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Reverting the last change to PionCounterTests.cpp, because gcc is complaining, and the changes aren't needed.<commit_after>\/\/ -----------------------------------------------------------------------\n\/\/ pion-common: a collection of common libraries used by the Pion Platform\n\/\/ -----------------------------------------------------------------------\n\/\/ Copyright (C) 2007-2008 Atomic Labs, Inc. (http:\/\/www.atomiclabs.com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ See http:\/\/www.boost.org\/LICENSE_1_0.txt\n\/\/\n\n#include <pion\/PionConfig.hpp>\n#include <pion\/PionCounter.hpp>\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace pion;\n\nclass NewPionCounter_F : public PionCounter {\npublic:\n\tNewPionCounter_F() {\n\t}\n\t~NewPionCounter_F() {\n\t}\n\nprivate:\n};\n\nBOOST_FIXTURE_TEST_SUITE(NewPionCounter_S, NewPionCounter_F)\n\nBOOST_AUTO_TEST_CASE(checkGetValueReturnsZero) {\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));\n}\n\nBOOST_AUTO_TEST_CASE(checkGetValueAfterIncrement) {\n\tincrement();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(1));\n}\n\nBOOST_AUTO_TEST_CASE(checkGetValueAfterDecrement) {\n\tdecrement();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(-1));\n}\n\nBOOST_AUTO_TEST_CASE(checkGetValueAfterReset) {\n\treset();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nclass PionCounterSetTo5_F : public PionCounter {\npublic:\n\tPionCounterSetTo5_F() {\n\t\tassign(5);\n\t}\n\t~PionCounterSetTo5_F() {\n\t}\n\nprivate:\n};\n\nBOOST_FIXTURE_TEST_SUITE(PionCounterSetTo5_S, PionCounterSetTo5_F)\n\nBOOST_AUTO_TEST_CASE(checkGetValueReturns5) {\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(5));\n}\n\nBOOST_AUTO_TEST_CASE(checkGetValueAfterIncrement) {\n\tincrement();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(6));\n}\n\nBOOST_AUTO_TEST_CASE(checkGetValueAfterDecrement) {\n\tdecrement();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(4));\n}\n\nBOOST_AUTO_TEST_CASE(checkGetValueAfterReset) {\n\treset();\n\tBOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include \"rendering.h\"\n#include \"..\/events\/events.h\"\n\nclass Renderer\n{\nprivate:\n\tInt32\t\t\t\tm_bInitComplete;\n\tSDL_Window*\t\t\tm_Window;\n\tEvents::Mailbox*\tm_pMailbox;\n\n\tGLeffect\t\t\tm_eftMesh;\n\tGLbuffer\t\t\tm_bufPerMesh;\n\tGLbuffer\t\t\tm_bufPerFrame;\n\n\tGLmesh\t\t\t\tm_glmArena;\n\n\tGLmesh\t\t\t\tm_glmKart;\n\npublic:\n\tint Init( SDL_Window* win );\n\tint Update( float fElapseSec );\n\tint Render();\n\n\tRenderer();\n\t~Renderer();\n};\n\nRenderer* g_pRenderer = 0;\n\nint InitRendering( SDL_Window* win )\n{\n\tif( g_pRenderer ) return 0;\n\tg_pRenderer = new Renderer();\n\treturn g_pRenderer ? g_pRenderer->Init( win ) : 0;\n}\n\nint UpdateRendering( float fElapseSec )\n{\n\treturn g_pRenderer ? g_pRenderer->Update( fElapseSec ) : 0;\n}\n\nint Render()\n{\n\treturn g_pRenderer ? g_pRenderer->Render() : 0;\n}\n\nint ShutdownRendering()\n{\n\tif( !g_pRenderer ) return 0;\n\tdelete g_pRenderer;\n\treturn 1;\n}\n\nRenderer::Renderer()\n{\n\tm_bInitComplete = 0;\n}\n\nRenderer::~Renderer()\n{\n\tglhDestroyBuffer( m_bufPerMesh );\n\tglhDestroyBuffer( m_bufPerFrame );\n\tglhUnloadEffect( m_eftMesh );\n}\n\nint Renderer::Init( SDL_Window* win )\n{\n\tm_Window = win;\n\tm_pMailbox = new Events::Mailbox();\n\n\tif( glewInit() != GLEW_OK )\n\t\treturn 1;\n\n\t\/\/ OpenGL Test Info\n\tconst GLubyte* strVendor = glGetString( GL_VENDOR );\n\tGLint major, minor;\n\tglGetIntegerv( GL_MAJOR_VERSION, &major );\n\tglGetIntegerv( GL_MINOR_VERSION, &minor );\n\n\t\/\/ OpenGL State Init\n\tglClearDepth( 1.0f );\n\tglEnable( GL_DEPTH_TEST );\n\tglEnable( GL_CULL_FACE );\n\tglCullFace( GL_FRONT );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );\n\tglEnable( GL_MULTISAMPLE );\n\n\t\/\/ Load Standard Effects\n\tconst GLchar* aryHeaders[] = { \"component\/rendering\/ShaderStructs.glsl\" };\n\tm_eftMesh = glhLoadEffect( \"component\/rendering\/VShader.glsl\", NULL, \"component\/rendering\/PShader.glsl\", aryHeaders, 1 );\n\tif( !m_eftMesh.program )\n\t\treturn 0;\n\n\tglhCreateBuffer( m_eftMesh, \"cstPerMesh\", sizeof(cstPerMesh), &m_bufPerMesh );\n\tglhCreateBuffer( m_eftMesh, \"cstPerFrame\", sizeof(cstPerFrame), &m_bufPerFrame );\n\n\t{\n\t\tGLchar* pData;\n\t\tInt32 nSize;\n\t\tif( !glhReadFile( \"assets\/Arena.msh\", pData, nSize ) )\n\t\t\treturn 0;\n\n\t\tSEG::Mesh meshdata;\n\t\tGetMutState()->bttmArena = new btTriangleMesh();\n\t\tif( !meshdata.ReadData( (Byte*)pData, nSize, 0, GetMutState()->bttmArena ) )\n\t\t\treturn 0;\n\n\t\tfree( pData );\n\n\t\tif( !glhCreateMesh( m_glmArena, meshdata ) )\n\t\t\treturn 0;\n\t}\n\n\t{\n\t\tGLchar* pData;\n\t\tInt32 nSize;\n\t\tif( !glhReadFile( \"assets\/RedBox.msh\", pData, nSize ) )\n\t\t\treturn 0;\n\n\t\tSEG::Mesh meshdata;\n\t\tif( !meshdata.ReadData( (Byte*)pData, nSize ) )\n\t\t\treturn 0;\n\n\t\tfree( pData );\n\n\t\tif( !glhCreateMesh( m_glmKart, meshdata ) )\n\t\t\treturn 0;\n\t}\n\n\tm_pMailbox->request( Events::EventType::StateUpdate );\n\n\tm_bInitComplete = 1;\n\n\treturn 1;\n}\n\nint Renderer::Update( float fElapseSec )\n{\n\tif( !m_bInitComplete )\n\t\treturn 0;\n\n\tconst std::vector<Events::Event*> aryEvents = m_pMailbox->checkMail();\n\tfor( int i = 0; i < aryEvents.size(); i++ )\n\t{\n\t\tswitch( aryEvents[i]->type )\n\t\t{\n\t\tcase Events::EventType::StateUpdate:\n\t\t\t{\n\t\t\t\t\/\/DEBUGOUT( \"I GOT HERE!\" );\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tcstPerFrame& perFrame = *(cstPerFrame*)m_bufPerFrame.data;\n\n\tInt32 nWinWidth, nWinHeight;\n\tSDL_GetWindowSize( m_Window, &nWinWidth, &nWinHeight );\n\n\tVector3 vFocus = GetState().Camera.vFocus;\n\tperFrame.vEyePos = GetState().Camera.vPos;\n\tperFrame.vEyeDir = Vector3( vFocus - perFrame.vEyePos.xyz() ).Normalize();\n\tperFrame.matProj.Perspective( DEGTORAD( 60.0f ), (Real)nWinWidth\/nWinHeight, 0.1f, 100.0f );\n\tperFrame.matView.LookAt( perFrame.vEyePos.xyz(), vFocus, Vector3( 0, 1, 0 ) );\n\tperFrame.matViewProj = perFrame.matView * perFrame.matProj;\n\tglhUpdateBuffer( m_eftMesh, m_bufPerFrame );\n\n\treturn 1;\n}\n\nint Renderer::Render()\n{\n\tif( !m_bInitComplete )\n\t\treturn 0;\n\n\tcstPerMesh& perMesh = *(cstPerMesh*)m_bufPerMesh.data;\n\tcstPerFrame& perFrame = *(cstPerFrame*)m_bufPerFrame.data;\n\n\tperMesh.matWorld.Identity();\n\tperMesh.matWorldViewProj = perMesh.matWorld * perFrame.matViewProj;\n\tglhUpdateBuffer( m_eftMesh, m_bufPerMesh );\n\tglhDrawMesh( m_eftMesh, m_glmArena );\n\n\tperMesh.matWorld = Matrix::GetScale( 0.3f, 0.3f, 0.5f ) * \n\t\tMatrix::GetRotateQuaternion( GetState().Karts[0].qOrient ) *\n\t\tMatrix::GetTranslate( GetState().Karts[0].vPos );\n\tperMesh.matWorldViewProj = perMesh.matWorld * perFrame.matViewProj;\n\tglhUpdateBuffer( m_eftMesh, m_bufPerMesh );\n\tglhDrawMesh( m_eftMesh, m_glmKart );\n\n\tSDL_GL_SwapWindow( m_Window );\n\n\treturn 1;\n}\n<commit_msg>Change rendering to receive input<commit_after>#include \"rendering.h\"\n#include \"..\/events\/events.h\"\n\nclass Renderer\n{\nprivate:\n\tInt32\t\t\t\tm_bInitComplete;\n\tSDL_Window*\t\t\tm_Window;\n\tEvents::Mailbox*\tm_pMailbox;\n\n\tGLeffect\t\t\tm_eftMesh;\n\tGLbuffer\t\t\tm_bufPerMesh;\n\tGLbuffer\t\t\tm_bufPerFrame;\n\n\tGLmesh\t\t\t\tm_glmArena;\n\n\tGLmesh\t\t\t\tm_glmKart;\n\npublic:\n\tint Init( SDL_Window* win );\n\tint Update( float fElapseSec );\n\tint Render();\n\n\tRenderer();\n\t~Renderer();\n};\n\nRenderer* g_pRenderer = 0;\n\nint InitRendering( SDL_Window* win )\n{\n\tif( g_pRenderer ) return 0;\n\tg_pRenderer = new Renderer();\n\treturn g_pRenderer ? g_pRenderer->Init( win ) : 0;\n}\n\nint UpdateRendering( float fElapseSec )\n{\n\treturn g_pRenderer ? g_pRenderer->Update( fElapseSec ) : 0;\n}\n\nint Render()\n{\n\treturn g_pRenderer ? g_pRenderer->Render() : 0;\n}\n\nint ShutdownRendering()\n{\n\tif( !g_pRenderer ) return 0;\n\tdelete g_pRenderer;\n\treturn 1;\n}\n\nRenderer::Renderer()\n{\n\tm_bInitComplete = 0;\n}\n\nRenderer::~Renderer()\n{\n\tglhDestroyBuffer( m_bufPerMesh );\n\tglhDestroyBuffer( m_bufPerFrame );\n\tglhUnloadEffect( m_eftMesh );\n}\n\nint Renderer::Init( SDL_Window* win )\n{\n\tm_Window = win;\n\tm_pMailbox = new Events::Mailbox();\n\tm_pMailbox->request(Events::EventType::Input);\n\n\tif( glewInit() != GLEW_OK )\n\t\treturn 1;\n\n\t\/\/ OpenGL Test Info\n\tconst GLubyte* strVendor = glGetString( GL_VENDOR );\n\tGLint major, minor;\n\tglGetIntegerv( GL_MAJOR_VERSION, &major );\n\tglGetIntegerv( GL_MINOR_VERSION, &minor );\n\n\t\/\/ OpenGL State Init\n\tglClearDepth( 1.0f );\n\tglEnable( GL_DEPTH_TEST );\n\tglEnable( GL_CULL_FACE );\n\tglCullFace( GL_FRONT );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );\n\tglEnable( GL_MULTISAMPLE );\n\n\t\/\/ Load Standard Effects\n\tconst GLchar* aryHeaders[] = { \"component\/rendering\/ShaderStructs.glsl\" };\n\tm_eftMesh = glhLoadEffect( \"component\/rendering\/VShader.glsl\", NULL, \"component\/rendering\/PShader.glsl\", aryHeaders, 1 );\n\tif( !m_eftMesh.program )\n\t\treturn 0;\n\n\tglhCreateBuffer( m_eftMesh, \"cstPerMesh\", sizeof(cstPerMesh), &m_bufPerMesh );\n\tglhCreateBuffer( m_eftMesh, \"cstPerFrame\", sizeof(cstPerFrame), &m_bufPerFrame );\n\n\t{\n\t\tGLchar* pData;\n\t\tInt32 nSize;\n\t\tif( !glhReadFile( \"assets\/Arena.msh\", pData, nSize ) )\n\t\t\treturn 0;\n\n\t\tSEG::Mesh meshdata;\n\t\tGetMutState()->bttmArena = new btTriangleMesh();\n\t\tif( !meshdata.ReadData( (Byte*)pData, nSize, 0, GetMutState()->bttmArena ) )\n\t\t\treturn 0;\n\n\t\tfree( pData );\n\n\t\tif( !glhCreateMesh( m_glmArena, meshdata ) )\n\t\t\treturn 0;\n\t}\n\n\t{\n\t\tGLchar* pData;\n\t\tInt32 nSize;\n\t\tif( !glhReadFile( \"assets\/RedBox.msh\", pData, nSize ) )\n\t\t\treturn 0;\n\n\t\tSEG::Mesh meshdata;\n\t\tif( !meshdata.ReadData( (Byte*)pData, nSize ) )\n\t\t\treturn 0;\n\n\t\tfree( pData );\n\n\t\tif( !glhCreateMesh( m_glmKart, meshdata ) )\n\t\t\treturn 0;\n\t}\n\n\tm_pMailbox->request( Events::EventType::StateUpdate );\n\n\tm_bInitComplete = 1;\n\n\treturn 1;\n}\n\nint Renderer::Update( float fElapseSec )\n{\n\tif( !m_bInitComplete )\n\t\treturn 0;\n\n\tconst std::vector<Events::Event*> aryEvents = m_pMailbox->checkMail();\n\tfor( int i = 0; i < aryEvents.size(); i++ )\n\t{\n\t\tswitch( aryEvents[i]->type )\n\t\t{\n\t\tcase Events::EventType::StateUpdate:\n\t\t\t{\n\t\t\t\t\/\/DEBUGOUT( \"I GOT HERE!\" );\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Events::EventType::Input:\n\t\t\t{\n\t\t\t\tEvents::InputEvent* input = (Events::InputEvent*)aryEvents[i];\n\t\t\t\t\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tcstPerFrame& perFrame = *(cstPerFrame*)m_bufPerFrame.data;\n\n\tInt32 nWinWidth, nWinHeight;\n\tSDL_GetWindowSize( m_Window, &nWinWidth, &nWinHeight );\n\n\tVector3 vFocus = GetState().Camera.vFocus;\n\tperFrame.vEyePos = GetState().Camera.vPos;\n\tperFrame.vEyeDir = Vector3( vFocus - perFrame.vEyePos.xyz() ).Normalize();\n\tperFrame.matProj.Perspective( DEGTORAD( 60.0f ), (Real)nWinWidth\/nWinHeight, 0.1f, 100.0f );\n\tperFrame.matView.LookAt( perFrame.vEyePos.xyz(), vFocus, Vector3( 0, 1, 0 ) );\n\tperFrame.matViewProj = perFrame.matView * perFrame.matProj;\n\tglhUpdateBuffer( m_eftMesh, m_bufPerFrame );\n\n\treturn 1;\n}\n\nint Renderer::Render()\n{\n\tif( !m_bInitComplete )\n\t\treturn 0;\n\n\tcstPerMesh& perMesh = *(cstPerMesh*)m_bufPerMesh.data;\n\tcstPerFrame& perFrame = *(cstPerFrame*)m_bufPerFrame.data;\n\n\tperMesh.matWorld.Identity();\n\tperMesh.matWorldViewProj = perMesh.matWorld * perFrame.matViewProj;\n\tglhUpdateBuffer( m_eftMesh, m_bufPerMesh );\n\tglhDrawMesh( m_eftMesh, m_glmArena );\n\n\tperMesh.matWorld = Matrix::GetScale( 0.3f, 0.3f, 0.5f ) * \n\t\tMatrix::GetRotateQuaternion( GetState().Karts[0].qOrient ) *\n\t\tMatrix::GetTranslate( GetState().Karts[0].vPos );\n\tperMesh.matWorldViewProj = perMesh.matWorld * perFrame.matViewProj;\n\tglhUpdateBuffer( m_eftMesh, m_bufPerMesh );\n\tglhDrawMesh( m_eftMesh, m_glmKart );\n\n\tSDL_GL_SwapWindow( m_Window );\n\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <highgui.h>\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/features2d\/features2d.hpp>\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace cv;\n\n\nvoid warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )\n{\n H.create(3, 3, CV_32FC1);\n H.at<float>(0,0) = rng.uniform( 0.8f, 1.2f);\n H.at<float>(0,1) = rng.uniform(-0.1f, 0.1f);\n H.at<float>(0,2) = rng.uniform(-0.1f, 0.1f)*src.cols;\n H.at<float>(1,0) = rng.uniform(-0.1f, 0.1f);\n H.at<float>(1,1) = rng.uniform( 0.8f, 1.2f);\n H.at<float>(1,2) = rng.uniform(-0.1f, 0.1f)*src.rows;\n H.at<float>(2,0) = rng.uniform( -1e-4f, 1e-4f);\n H.at<float>(2,1) = rng.uniform( -1e-4f, 1e-4f);\n H.at<float>(2,2) = rng.uniform( 0.8f, 1.2f);\n\n warpPerspective( src, dst, H, src.size() );\n}\n\nint main( int argc, char **argv )\n{\n #if 0\n if( argc != 4 && argc != 3 )\n {\n cout << \"Format:\" << endl <<\n \" classifier(xml to write) test_image file_with_train_images_filenames(txt)\" <<\n \" or\" << endl <<\n \" classifier(xml to read) test_image\" << endl;\n return -1;\n }\n\n CalonderClassifier classifier;\n if( argc == 4 ) \/\/ Train\n {\n \/\/ Read train images and test image\n ifstream fst( argv[3], ifstream::in );\n vector<Mat> trainImgs;\n while( !fst.eof() )\n {\n string str;\n getline( fst, str );\n if (str.empty()) break;\n Mat img = imread( str, CV_LOAD_IMAGE_GRAYSCALE );\n if( !img.empty() )\n trainImgs.push_back( img );\n }\n if( trainImgs.empty() )\n {\n cout << \"All train images can not be read.\" << endl;\n return -1;\n }\n cout << trainImgs.size() << \" train images were read.\" << endl;\n\n \/\/ Extract keypoints from train images\n SurfFeatureDetector detector;\n vector<vector<Point2f> > trainPoints( trainImgs.size() );\n for( size_t i = 0; i < trainImgs.size(); i++ )\n {\n vector<KeyPoint> kps;\n detector.detect( trainImgs[i], kps );\n KeyPoint::convert( kps, trainPoints[i] );\n }\n\n \/\/ Train Calonder classifier on extracted points\n classifier.setVerbose( true);\n classifier.train( trainPoints, trainImgs );\n\n \/\/ Write Calonder classifier\n FileStorage fs( argv[1], FileStorage::WRITE );\n if( fs.isOpened() ) classifier.write( fs );\n }\n else\n {\n \/\/ Read Calonder classifier\n FileStorage fs( argv[1], FileStorage::READ );\n if( fs.isOpened() ) classifier.read( fs.root() );\n }\n\n if( classifier.empty() )\n {\n cout << \"Calonder classifier is empty\" << endl;\n return -1;\n }\n\n \/\/ Test Calonder classifier on test image and warped one\n Mat testImg1 = imread( argv[2], CV_LOAD_IMAGE_GRAYSCALE ), testImg2, H12;\n if( testImg1.empty() )\n {\n cout << \"Test image can not be read.\" << endl;\n return -1;\n }\n warpPerspectiveRand( testImg1, testImg2, H12, theRNG() );\n\n\n \/\/ Exstract keypoints from test images\n SurfFeatureDetector detector;\n vector<KeyPoint> testKeypoints1; detector.detect( testImg1, testKeypoints1 );\n vector<KeyPoint> testKeypoints2; detector.detect( testImg2, testKeypoints2 );\n vector<Point2f> testPoints1; KeyPoint::convert( testKeypoints1, testPoints1 );\n vector<Point2f> testPoints2; KeyPoint::convert( testKeypoints2, testPoints2 );\n\n \/\/ Calculate Calonder descriptors\n int signatureSize = classifier.getSignatureSize();\n vector<float> r1(testPoints1.size()*signatureSize), r2(testPoints2.size()*signatureSize);\n vector<float>::iterator rit = r1.begin();\n for( size_t i = 0; i < testPoints1.size(); i++ )\n {\n vector<float> s;\n classifier( testImg1, testPoints1[i], s );\n copy( s.begin(), s.end(), rit );\n rit += s.size();\n }\n rit = r2.begin();\n for( size_t i = 0; i < testPoints2.size(); i++ )\n {\n vector<float> s;\n classifier( testImg2, testPoints2[i], s );\n copy( s.begin(), s.end(), rit );\n rit += s.size();\n }\n\n Mat descriptors1(testPoints1.size(), classifier.getSignatureSize(), CV_32FC1, &r1[0] ),\n descriptors2(testPoints2.size(), classifier.getSignatureSize(), CV_32FC1, &r2[0] );\n\n \/\/ Match descriptors\n BruteForceMatcher<L1<float> > matcher;\n matcher.add( descriptors2 );\n vector<int> matches;\n matcher.match( descriptors1, matches );\n\n \/\/ Draw results\n \/\/ Prepare inlier mask\n vector<char> matchesMask( matches.size(), 0 );\n Mat points1t; perspectiveTransform(Mat(testPoints1), points1t, H12);\n vector<int>::const_iterator mit = matches.begin();\n for( size_t mi = 0; mi < matches.size(); mi++ )\n {\n if( norm(testPoints2[matches[mi]] - points1t.at<Point2f>(mi,0)) < 4 ) \/\/ inlier\n matchesMask[mi] = 1;\n }\n \/\/ Draw\n Mat drawImg;\n drawMatches( testImg1, testKeypoints1, testImg2, testKeypoints2, matches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask );\n string winName = \"Matches\";\n namedWindow( winName, WINDOW_AUTOSIZE );\n imshow( winName, drawImg );\n waitKey();\n#endif\n return 0;\n}\n<commit_msg>modified sample find_obj_calonder<commit_after>#include <highgui.h>\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/features2d\/features2d.hpp>\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace cv;\n\n\/*\n * Generates random perspective transform of image\n *\/\nvoid warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )\n{\n H.create(3, 3, CV_32FC1);\n H.at<float>(0,0) = rng.uniform( 0.8f, 1.2f);\n H.at<float>(0,1) = rng.uniform(-0.1f, 0.1f);\n H.at<float>(0,2) = rng.uniform(-0.1f, 0.1f)*src.cols;\n H.at<float>(1,0) = rng.uniform(-0.1f, 0.1f);\n H.at<float>(1,1) = rng.uniform( 0.8f, 1.2f);\n H.at<float>(1,2) = rng.uniform(-0.1f, 0.1f)*src.rows;\n H.at<float>(2,0) = rng.uniform( -1e-4f, 1e-4f);\n H.at<float>(2,1) = rng.uniform( -1e-4f, 1e-4f);\n H.at<float>(2,2) = rng.uniform( 0.8f, 1.2f);\n\n warpPerspective( src, dst, H, src.size() );\n}\n\n\/*\n * Trains Calonder classifier and writes trained classifier in file:\n * imgFilename - name of .txt file which contains list of full filenames of train images,\n * classifierFilename - name of binary file in which classifier will be written.\n *\n * To train Calonder classifier RTreeClassifier class need to be used.\n *\/\nvoid trainCalonderClassifier( const string& classifierFilename, const string& imgFilename )\n{\n \/\/ Reads train images\n ifstream is( imgFilename.c_str(), ifstream::in );\n vector<Mat> trainImgs;\n while( !is.eof() )\n {\n string str;\n getline( is, str );\n if (str.empty()) break;\n Mat img = imread( str, CV_LOAD_IMAGE_GRAYSCALE );\n if( !img.empty() )\n trainImgs.push_back( img );\n }\n if( trainImgs.empty() )\n {\n cout << \"All train images can not be read.\" << endl;\n exit(-1);\n }\n cout << trainImgs.size() << \" train images were read.\" << endl;\n\n \/\/ Extracts keypoints from train images\n SurfFeatureDetector detector;\n vector<BaseKeypoint> trainPoints;\n vector<IplImage> iplTrainImgs(trainImgs.size());\n for( size_t imgIdx = 0; imgIdx < trainImgs.size(); imgIdx++ )\n {\n iplTrainImgs[imgIdx] = trainImgs[imgIdx];\n vector<KeyPoint> kps; detector.detect( trainImgs[imgIdx], kps );\n\n for( size_t pointIdx = 0; pointIdx < kps.size(); pointIdx++ )\n {\n Point2f p = kps[pointIdx].pt;\n trainPoints.push_back( BaseKeypoint(cvRound(p.x), cvRound(p.y), &iplTrainImgs[imgIdx]) );\n }\n }\n\n \/\/ Trains Calonder classifier on extracted points\n RTreeClassifier classifier;\n classifier.train( trainPoints, theRNG(), 48, 9, 100 );\n \/\/ Writes classifier\n classifier.write( classifierFilename.c_str() );\n}\n\n\/*\n * Test Calonder classifier to match keypoints on given image:\n * classifierFilename - name of file from which classifier will be read,\n * imgFilename - test image filename.\n *\n * To calculate keypoint descriptors you may use RTreeClassifier class (as to train),\n * but it is convenient to use CalonderDescriptorExtractor class which is wrapper of\n * RTreeClassifier.\n *\/\nvoid testCalonderClassifier( const string& classifierFilename, const string& imgFilename )\n{\n Mat img1 = imread( imgFilename, CV_LOAD_IMAGE_GRAYSCALE ), img2, H12;\n if( img1.empty() )\n {\n cout << \"Test image can not be read.\" << endl;\n exit(-1);\n }\n warpPerspectiveRand( img1, img2, H12, theRNG() );\n\n \/\/ Exstract keypoints from test images\n SurfFeatureDetector detector;\n vector<KeyPoint> keypoints1; detector.detect( img1, keypoints1 );\n vector<KeyPoint> keypoints2; detector.detect( img2, keypoints2 );\n\n \/\/ Compute descriptors\n CalonderDescriptorExtractor<float> de( classifierFilename );\n Mat descriptors1; de.compute( img1, keypoints1, descriptors1 );\n Mat descriptors2; de.compute( img2, keypoints2, descriptors2 );\n\n \/\/ Match descriptors\n BruteForceMatcher<L1<float> > matcher;\n matcher.add( descriptors2 );\n vector<int> matches;\n matcher.match( descriptors1, matches );\n\n \/\/ Prepare inlier mask\n vector<char> matchesMask( matches.size(), 0 );\n vector<Point2f> points1; KeyPoint::convert( keypoints1, points1 );\n vector<Point2f> points2; KeyPoint::convert( keypoints2, points2 );\n Mat points1t; perspectiveTransform(Mat(points1), points1t, H12);\n vector<int>::const_iterator mit = matches.begin();\n for( size_t mi = 0; mi < matches.size(); mi++ )\n {\n if( norm(points2[matches[mi]] - points1t.at<Point2f>(mi,0)) < 4 ) \/\/ inlier\n matchesMask[mi] = 1;\n }\n\n \/\/ Draw\n Mat drawImg;\n drawMatches( img1, keypoints1, img2, keypoints2, matches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask );\n string winName = \"Matches\";\n namedWindow( winName, WINDOW_AUTOSIZE );\n imshow( winName, drawImg );\n waitKey();\n}\n\n\nint main( int argc, char **argv )\n{\n if( argc != 4 && argc != 3 )\n {\n cout << \"Format:\" << endl <<\n \" classifier_file(to write) test_image file_with_train_images_filenames(txt)\" <<\n \" or\" << endl <<\n \" classifier_file(to read) test_image\" << endl;\n return -1;\n }\n\n if( argc == 4 )\n trainCalonderClassifier( argv[1], argv[3] );\n\n testCalonderClassifier( argv[1], argv[2] );\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 libmv authors.\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\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell 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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include \"libmv\/image\/image.h\"\n#include \"libmv\/image\/image_drawing.h\"\n#include \"libmv\/logging\/logging.h\"\n#include \"testing\/testing.h\"\n\nusing namespace libmv;\n\nnamespace {\n\n\/\/ Horizontal \/ Vertical scanlines\n\/\/ Assert that pixels was drawn at the good place\nTEST(ImageDrawing, Scanlines) {\n\n const int w = 10, h = 10;\n Array3Du image(h,w);\n image.Fill(0);\n\n \/\/ horizontal scanline\n \/\/ __________\n \/\/ | |\n \/\/ |__here___|\n \/\/ | |\n \/\/ |_________|\n const int y = 5;\n DrawLine( 0, y, w-1, y, 255, &image);\n for(int i=0; i < w; ++i)\n EXPECT_EQ( image(y,i), 255);\n\n image.Fill(0);\n\n \/\/ Vertical scanline\n \/\/ __________\n \/\/ | h| |\n \/\/ | e| |\n \/\/ | r| |\n \/\/ |____e|___|\n const int x = 5;\n DrawLine( x, 0, x, h-1, 255, &image);\n for (int i = 0; i < h; ++i)\n EXPECT_EQ(image(i,y), 255);\n}\n\n\/\/ Lines with a given angle +\/-45°\n\/\/ Assert that pixels was drawn at the good place\nTEST(ImageDrawing, Lines45) {\n\n const int w = 10, h = 10;\n Array3Du image(h,w);\n image.Fill(0);\n\n \/\/ _____\n \/\/ |\\ |\n \/\/ | \\ |\n \/\/ |__\\|\n\n DrawLine(0, 0, w-1, h-1, 255, &image);\n for (int i = 0; i < w; ++i)\n EXPECT_EQ(image(i,i), 255);\n\n image.Fill(0);\n\n \/\/ _____\n \/\/ | \/ |\n \/\/ | \/ |\n \/\/ |\/___|_\n DrawLine(0, h-1, w-1, 0, 255, &image);\n for (int i = 0; i < h; ++i)\n EXPECT_EQ(image(h-1-i,i), 255);\n}\n\n\/\/ Draw a circle in an image and assert that all the points are\n\/\/ at a distance equal to the radius.\nTEST(ImageDrawing, Circle) {\n\n Array3Du image(10,10);\n image.Fill(0);\n\n const int radius = 3;\n const int x = 5, y = 5;\n\n DrawCircle(x, y, radius, (unsigned char)255, &image);\n\n \/\/ Distance checking :\n for ( int j = 0; j < image.Height(); ++j)\n for ( int i = 0; i < image.Width(); ++i) {\n if (image(j, i) == 255) {\n const float distance = sqrt((j-y)*(j-y) + (i-x)*(i-x));\n EXPECT_NEAR(radius, distance, 1.0f);\n \/\/ Due to discretisation we cannot expect better precision\n }\n }\n}\n\n}\n<commit_msg>- fix on windows with sqrt (expect float or double or long double but no integer).<commit_after>\/\/ Copyright (c) 2009 libmv authors.\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\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell 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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include \"libmv\/image\/image.h\"\n#include \"libmv\/image\/image_drawing.h\"\n#include \"libmv\/logging\/logging.h\"\n#include \"testing\/testing.h\"\n\nusing namespace libmv;\n\nnamespace {\n\n\/\/ Horizontal \/ Vertical scanlines\n\/\/ Assert that pixels was drawn at the good place\nTEST(ImageDrawing, Scanlines) {\n\n const int w = 10, h = 10;\n Array3Du image(h,w);\n image.Fill(0);\n\n \/\/ horizontal scanline\n \/\/ __________\n \/\/ | |\n \/\/ |__here___|\n \/\/ | |\n \/\/ |_________|\n const int y = 5;\n DrawLine( 0, y, w-1, y, 255, &image);\n for(int i=0; i < w; ++i)\n EXPECT_EQ( image(y,i), 255);\n\n image.Fill(0);\n\n \/\/ Vertical scanline\n \/\/ __________\n \/\/ | h| |\n \/\/ | e| |\n \/\/ | r| |\n \/\/ |____e|___|\n const int x = 5;\n DrawLine( x, 0, x, h-1, 255, &image);\n for (int i = 0; i < h; ++i)\n EXPECT_EQ(image(i,y), 255);\n}\n\n\/\/ Lines with a given angle +\/-45°\n\/\/ Assert that pixels was drawn at the good place\nTEST(ImageDrawing, Lines45) {\n\n const int w = 10, h = 10;\n Array3Du image(h,w);\n image.Fill(0);\n\n \/\/ _____\n \/\/ |\\ |\n \/\/ | \\ |\n \/\/ |__\\|\n\n DrawLine(0, 0, w-1, h-1, 255, &image);\n for (int i = 0; i < w; ++i)\n EXPECT_EQ(image(i,i), 255);\n\n image.Fill(0);\n\n \/\/ _____\n \/\/ | \/ |\n \/\/ | \/ |\n \/\/ |\/___|_\n DrawLine(0, h-1, w-1, 0, 255, &image);\n for (int i = 0; i < h; ++i)\n EXPECT_EQ(image(h-1-i,i), 255);\n}\n\n\/\/ Draw a circle in an image and assert that all the points are\n\/\/ at a distance equal to the radius.\nTEST(ImageDrawing, Circle) {\n\n Array3Du image(10,10);\n image.Fill(0);\n\n const int radius = 3;\n const int x = 5, y = 5;\n\n DrawCircle(x, y, radius, (unsigned char)255, &image);\n\n \/\/ Distance checking :\n for ( int j = 0; j < image.Height(); ++j)\n for ( int i = 0; i < image.Width(); ++i) {\n if (image(j, i) == 255) {\n const float distance = sqrt((float)((j-y)*(j-y) + (i-x)*(i-x)));\n EXPECT_NEAR(radius, distance, 1.0f);\n \/\/ Due to discretisation we cannot expect better precision\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"stx\/SHA1.h\"\n#include \"stx\/protobuf\/msg.h\"\n#include \"logjoin\/stages\/TSDBUploadStage.h\"\n#include \"logjoin\/common.h\"\n#include \"tsdb\/RecordEnvelope.pb.h\"\n#include \"tsdb\/TimeWindowPartitioner.h\"\n\nusing namespace stx;\n\nnamespace cm {\n\nvoid TSDBUploadStage::process(\n RefPtr<TrackedSessionContext> ctx,\n const String& tsdb_addr,\n http::HTTPConnectionPool* http) {\n tsdb::RecordEnvelopeList records;\n\n auto time = ctx->joined_session.last_seen_time();\n auto record_id = SHA1::compute(ctx->tracked_session.uid);\n auto stream_key = \"web.sessions\";\n auto partition_key = tsdb::TimeWindowPartitioner::partitionKeyFor(\n stream_key,\n time,\n 4 * kMicrosPerHour);\n\n auto record_data = msg::encode(ctx->joined_session);\n\n auto r = records.add_records();\n r->set_tsdb_namespace(ctx->tracked_session.customer_key);\n r->set_stream_key(stream_key);\n r->set_partition_key(partition_key.toString());\n r->set_record_id(record_id.toString());\n r->set_record_data(record_data->data(), record_data->size());\n\n URI uri(StringUtil::format(\"http:\/\/$0\/tsdb\/insert\", tsdb_addr));\n http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());\n req.addHeader(\"Host\", uri.hostAndPort());\n req.addHeader(\"Content-Type\", \"application\/fnord-msg\");\n req.addBody(*msg::encode(records));\n\n auto res = http->executeRequest(req);\n res.wait();\n\n if (res.get().statusCode() != 201) {\n RAISEF(\n kRuntimeError,\n \"received non-201 response: $0\",\n res.get().body().toString());\n }\n}\n\n} \/\/ namespace cm\n\n<commit_msg>TSDBUploadStage...<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"stx\/SHA1.h\"\n#include \"stx\/protobuf\/msg.h\"\n#include \"logjoin\/stages\/TSDBUploadStage.h\"\n#include \"logjoin\/common.h\"\n#include \"tsdb\/RecordEnvelope.pb.h\"\n#include \"tsdb\/TimeWindowPartitioner.h\"\n\nusing namespace stx;\n\nnamespace cm {\n\nvoid TSDBUploadStage::process(\n RefPtr<TrackedSessionContext> ctx,\n const String& tsdb_addr,\n http::HTTPConnectionPool* http) {\n tsdb::RecordEnvelopeList records;\n\n auto time = ctx->joined_session.last_seen_time() * kMicrosPerSecond;\n auto record_id = SHA1::compute(ctx->tracked_session.uid);\n auto stream_key = \"web.sessions\";\n auto partition_key = tsdb::TimeWindowPartitioner::partitionKeyFor(\n stream_key,\n time,\n 4 * kMicrosPerHour);\n\n auto record_data = msg::encode(ctx->joined_session);\n\n auto r = records.add_records();\n r->set_tsdb_namespace(ctx->tracked_session.customer_key);\n r->set_stream_key(stream_key);\n r->set_partition_key(partition_key.toString());\n r->set_record_id(record_id.toString());\n r->set_record_data(record_data->data(), record_data->size());\n\n URI uri(StringUtil::format(\"http:\/\/$0\/tsdb\/insert\", tsdb_addr));\n http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());\n req.addHeader(\"Host\", uri.hostAndPort());\n req.addHeader(\"Content-Type\", \"application\/fnord-msg\");\n req.addBody(*msg::encode(records));\n\n auto res = http->executeRequest(req);\n res.wait();\n\n if (res.get().statusCode() != 201) {\n RAISEF(\n kRuntimeError,\n \"received non-201 response: $0\",\n res.get().body().toString());\n }\n}\n\n} \/\/ namespace cm\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2010-2017 Branimir Karadzic. All rights reserved.\n * License: https:\/\/github.com\/bkaradzic\/bx#license-bsd-2-clause\n *\/\n\n#include <bx\/process.h>\n\n#include <stdio.h>\n\n#ifndef BX_CONFIG_CRT_PROCESS\n#\tdefine BX_CONFIG_CRT_PROCESS !(0 \\\n\t\t\t|| BX_CRT_NONE \\\n\t\t\t|| BX_PLATFORM_EMSCRIPTEN \\\n\t\t\t|| BX_PLATFORM_PS4 \\\n\t\t\t|| BX_PLATFORM_WINRT \\\n\t\t\t|| BX_PLATFORM_XBOXONE \\\n\t\t\t)\n#endif \/\/ BX_CONFIG_CRT_PROCESS\n\nnamespace bx\n{\n#if BX_CONFIG_CRT_PROCESS\n\n#if BX_CRT_MSVC\n#\tdefine popen _popen\n#\tdefine pclose _pclose\n#endif \/\/ BX_CRT_MSVC\n\n\tProcessReader::ProcessReader()\n\t\t: m_file(NULL)\n\t{\n\t}\n\n\tProcessReader::~ProcessReader()\n\t{\n\t\tBX_CHECK(NULL == m_file, \"Process not closed!\");\n\t}\n\n\tbool ProcessReader::open(const FilePath& _filePath, const StringView& _args, Error* _err)\n\t{\n\t\tBX_CHECK(NULL != _err, \"Reader\/Writer interface calling functions must handle errors.\");\n\n\t\tif (NULL != m_file)\n\t\t{\n\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, \"ProcessReader: File is already open.\");\n\t\t\treturn false;\n\t\t}\n\n\t\tchar tmp[kMaxFilePath*2];\n\t\tstrCopy(tmp, BX_COUNTOF(tmp), _filePath.get() );\n\t\tstrCat(tmp, BX_COUNTOF(tmp), \" \");\n\t\tstrCat(tmp, BX_COUNTOF(tmp), _args);\n\n\t\tm_file = popen(tmp, \"r\");\n\t\tif (NULL == m_file)\n\t\t{\n\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, \"ProcessReader: Failed to open process.\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvoid ProcessReader::close()\n\t{\n\t\tBX_CHECK(NULL != m_file, \"Process not open!\");\n\t\tFILE* file = (FILE*)m_file;\n\t\tm_exitCode = pclose(file);\n\t\tm_file = NULL;\n\t}\n\n\tint32_t ProcessReader::read(void* _data, int32_t _size, Error* _err)\n\t{\n\t\tBX_CHECK(NULL != _err, \"Reader\/Writer interface calling functions must handle errors.\"); BX_UNUSED(_err);\n\n\t\tFILE* file = (FILE*)m_file;\n\t\tint32_t size = (int32_t)fread(_data, 1, _size, file);\n\t\tif (size != _size)\n\t\t{\n\t\t\tif (0 != feof(file) )\n\t\t\t{\n\t\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_EOF, \"ProcessReader: EOF.\");\n\t\t\t}\n\t\t\telse if (0 != ferror(file) )\n\t\t\t{\n\t\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_READ, \"ProcessReader: read error.\");\n\t\t\t}\n\n\t\t\treturn size >= 0 ? size : 0;\n\t\t}\n\n\t\treturn size;\n\t}\n\n\tint32_t ProcessReader::getExitCode() const\n\t{\n\t\treturn m_exitCode;\n\t}\n\n\tProcessWriter::ProcessWriter()\n\t\t: m_file(NULL)\n\t{\n\t}\n\n\tProcessWriter::~ProcessWriter()\n\t{\n\t\tBX_CHECK(NULL == m_file, \"Process not closed!\");\n\t}\n\n\tbool ProcessWriter::open(const FilePath& _filePath, const StringView& _args, Error* _err)\n\t{\n\t\tBX_CHECK(NULL != _err, \"Reader\/Writer interface calling functions must handle errors.\");\n\n\t\tif (NULL != m_file)\n\t\t{\n\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, \"ProcessWriter: File is already open.\");\n\t\t\treturn false;\n\t\t}\n\n\t\tchar tmp[kMaxFilePath*2];\n\t\tstrCopy(tmp, BX_COUNTOF(tmp), _filePath.get() );\n\t\tstrCat(tmp, BX_COUNTOF(tmp), \" \");\n\t\tstrCat(tmp, BX_COUNTOF(tmp), _args);\n\n\t\tm_file = popen(tmp, \"w\");\n\t\tif (NULL == m_file)\n\t\t{\n\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, \"ProcessWriter: Failed to open process.\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvoid ProcessWriter::close()\n\t{\n\t\tBX_CHECK(NULL != m_file, \"Process not open!\");\n\t\tFILE* file = (FILE*)m_file;\n\t\tm_exitCode = pclose(file);\n\t\tm_file = NULL;\n\t}\n\n\tint32_t ProcessWriter::write(const void* _data, int32_t _size, Error* _err)\n\t{\n\t\tBX_CHECK(NULL != _err, \"Reader\/Writer interface calling functions must handle errors.\"); BX_UNUSED(_err);\n\n\t\tFILE* file = (FILE*)m_file;\n\t\tint32_t size = (int32_t)fwrite(_data, 1, _size, file);\n\t\tif (size != _size)\n\t\t{\n\t\t\tif (0 != ferror(file) )\n\t\t\t{\n\t\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_WRITE, \"ProcessWriter: write error.\");\n\t\t\t}\n\n\t\t\treturn size >= 0 ? size : 0;\n\t\t}\n\n\t\treturn size;\n\t}\n\n\tint32_t ProcessWriter::getExitCode() const\n\t{\n\t\treturn m_exitCode;\n\t}\n#endif \/\/ BX_CONFIG_CRT_PROCESS\n\n} \/\/ namespace bx\n<commit_msg>Quote executable name in case there are spaces.<commit_after>\/*\n * Copyright 2010-2017 Branimir Karadzic. All rights reserved.\n * License: https:\/\/github.com\/bkaradzic\/bx#license-bsd-2-clause\n *\/\n\n#include <bx\/process.h>\n\n#include <stdio.h>\n\n#ifndef BX_CONFIG_CRT_PROCESS\n#\tdefine BX_CONFIG_CRT_PROCESS !(0 \\\n\t\t\t|| BX_CRT_NONE \\\n\t\t\t|| BX_PLATFORM_EMSCRIPTEN \\\n\t\t\t|| BX_PLATFORM_PS4 \\\n\t\t\t|| BX_PLATFORM_WINRT \\\n\t\t\t|| BX_PLATFORM_XBOXONE \\\n\t\t\t)\n#endif \/\/ BX_CONFIG_CRT_PROCESS\n\nnamespace bx\n{\n#if BX_CONFIG_CRT_PROCESS\n\n#if BX_CRT_MSVC\n#\tdefine popen _popen\n#\tdefine pclose _pclose\n#endif \/\/ BX_CRT_MSVC\n\n\tProcessReader::ProcessReader()\n\t\t: m_file(NULL)\n\t{\n\t}\n\n\tProcessReader::~ProcessReader()\n\t{\n\t\tBX_CHECK(NULL == m_file, \"Process not closed!\");\n\t}\n\n\tbool ProcessReader::open(const FilePath& _filePath, const StringView& _args, Error* _err)\n\t{\n\t\tBX_CHECK(NULL != _err, \"Reader\/Writer interface calling functions must handle errors.\");\n\n\t\tif (NULL != m_file)\n\t\t{\n\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, \"ProcessReader: File is already open.\");\n\t\t\treturn false;\n\t\t}\n\n\t\tchar tmp[kMaxFilePath*2] = \"\\\"\";\n\t\tstrCat(tmp, BX_COUNTOF(tmp), _filePath.get() );\n\t\tstrCat(tmp, BX_COUNTOF(tmp), \"\\\" \");\n\t\tstrCat(tmp, BX_COUNTOF(tmp), _args);\n\n\t\tm_file = popen(tmp, \"r\");\n\t\tif (NULL == m_file)\n\t\t{\n\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, \"ProcessReader: Failed to open process.\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvoid ProcessReader::close()\n\t{\n\t\tBX_CHECK(NULL != m_file, \"Process not open!\");\n\t\tFILE* file = (FILE*)m_file;\n\t\tm_exitCode = pclose(file);\n\t\tm_file = NULL;\n\t}\n\n\tint32_t ProcessReader::read(void* _data, int32_t _size, Error* _err)\n\t{\n\t\tBX_CHECK(NULL != _err, \"Reader\/Writer interface calling functions must handle errors.\"); BX_UNUSED(_err);\n\n\t\tFILE* file = (FILE*)m_file;\n\t\tint32_t size = (int32_t)fread(_data, 1, _size, file);\n\t\tif (size != _size)\n\t\t{\n\t\t\tif (0 != feof(file) )\n\t\t\t{\n\t\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_EOF, \"ProcessReader: EOF.\");\n\t\t\t}\n\t\t\telse if (0 != ferror(file) )\n\t\t\t{\n\t\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_READ, \"ProcessReader: read error.\");\n\t\t\t}\n\n\t\t\treturn size >= 0 ? size : 0;\n\t\t}\n\n\t\treturn size;\n\t}\n\n\tint32_t ProcessReader::getExitCode() const\n\t{\n\t\treturn m_exitCode;\n\t}\n\n\tProcessWriter::ProcessWriter()\n\t\t: m_file(NULL)\n\t{\n\t}\n\n\tProcessWriter::~ProcessWriter()\n\t{\n\t\tBX_CHECK(NULL == m_file, \"Process not closed!\");\n\t}\n\n\tbool ProcessWriter::open(const FilePath& _filePath, const StringView& _args, Error* _err)\n\t{\n\t\tBX_CHECK(NULL != _err, \"Reader\/Writer interface calling functions must handle errors.\");\n\n\t\tif (NULL != m_file)\n\t\t{\n\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, \"ProcessWriter: File is already open.\");\n\t\t\treturn false;\n\t\t}\n\n\t\tchar tmp[kMaxFilePath*2] = \"\\\"\";\n\t\tstrCat(tmp, BX_COUNTOF(tmp), _filePath.get() );\n\t\tstrCat(tmp, BX_COUNTOF(tmp), \"\\\" \");\n\t\tstrCat(tmp, BX_COUNTOF(tmp), _args);\n\n\t\tm_file = popen(tmp, \"w\");\n\t\tif (NULL == m_file)\n\t\t{\n\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, \"ProcessWriter: Failed to open process.\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvoid ProcessWriter::close()\n\t{\n\t\tBX_CHECK(NULL != m_file, \"Process not open!\");\n\t\tFILE* file = (FILE*)m_file;\n\t\tm_exitCode = pclose(file);\n\t\tm_file = NULL;\n\t}\n\n\tint32_t ProcessWriter::write(const void* _data, int32_t _size, Error* _err)\n\t{\n\t\tBX_CHECK(NULL != _err, \"Reader\/Writer interface calling functions must handle errors.\"); BX_UNUSED(_err);\n\n\t\tFILE* file = (FILE*)m_file;\n\t\tint32_t size = (int32_t)fwrite(_data, 1, _size, file);\n\t\tif (size != _size)\n\t\t{\n\t\t\tif (0 != ferror(file) )\n\t\t\t{\n\t\t\t\tBX_ERROR_SET(_err, BX_ERROR_READERWRITER_WRITE, \"ProcessWriter: write error.\");\n\t\t\t}\n\n\t\t\treturn size >= 0 ? size : 0;\n\t\t}\n\n\t\treturn size;\n\t}\n\n\tint32_t ProcessWriter::getExitCode() const\n\t{\n\t\treturn m_exitCode;\n\t}\n#endif \/\/ BX_CONFIG_CRT_PROCESS\n\n} \/\/ namespace bx\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/common.h\"\n\n#include <fstream>\n\n#include <FreeImagePlus.h>\n#include <physfs.h>\n\n#include \"fileservice.h\"\n\n#include \"gamefw.h\"\n\nusing namespace gamefw;\n\nFileService::FileService()\n{\n FreeImage_Initialise( 0 );\n if (!PHYSFS_isInit())\n PHYSFS_init(NULL);\n PHYSFS_setSaneConfig(\"config\", PROJECT_NAME, \"ob\", 0, 1);\n\n m_dirseparator.assign(PHYSFS_getDirSeparator());\n\n \/\/ Find the project directory\n string basedir(PHYSFS_getBaseDir());\n\n string project_name(PROJECT_NAME);\n\n int project_path_pos = basedir.find(project_name);\n if (project_path_pos == basedir.npos) {\n LOG(logFATAL) << \"Project \" << project_name <<\n \" root directory not found from \" << basedir;\n }\n basedir.erase(project_path_pos + project_name.length());\n\n PHYSFS_mount(basedir.c_str(), NULL, 0); \/\/ Mount to root.\n\n m_entity_factory = new EntityFactory();\n}\n\nFileService::~FileService()\n{\n delete m_entity_factory;\n PHYSFS_deinit();\n FreeImage_DeInitialise();\n}\n\nconst char* FileNotFoundException::what() const throw()\n{\n return \"File not found.\";\n}\n\nconst char* FileService::fileToBuffer(const string& filename ) const\n{\n const string realpath(getRealPath(filename));\n\n \/\/ Open file at end.\n ifstream file( realpath.c_str(), ios::in | ios::ate );\n\n if ( file.is_open() ) {\n uint size = (uint) file.tellg(); \/\/ Get file size.\n \/\/ The +1 is for '\\0'.\n char* buffer = new char[size + 1];\n file.seekg( 0, ios::beg ); \/\/ Back to start.\n char* c = buffer;\n \/\/ Read the file to buffer.\n while (file.good()) {\n file.get(*c);\n c++;\n }\n\n file.close();\n\n *(c - 1) = '\\0'; \/\/ Delete EOF.\n\n LOG( logINFO ) << filename << \" loaded into buffer.\";\n\n return buffer;\n }\n\n LOG( logERROR ) << filename << \" not found.\";\n throw FileNotFoundException();\n}\n\nGLuint FileService::makeTexture( const string& name ) const\n{\n fipImage* image = readImage( name );\n\n assert( image->isValid() );\n\n int width = image->getWidth();\n int height = image->getHeight();\n void* pixels = (void*) image->accessPixels();\n GLuint texture;\n\n glGenTextures( 1, &texture );\n glBindTexture( GL_TEXTURE_2D, texture );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glTexImage2D(\n GL_TEXTURE_2D, 0, \/\/ target, level\n GL_RGB8, \/\/ internal format\n width, height, 0, \/\/ width, height, border\n GL_BGR, GL_UNSIGNED_BYTE, \/\/ external format, type\n pixels \/\/ pixels\n );\n\n image->clear();\n delete image;\n\n return texture;\n\n}\n\nfipImage* FileService::readImage( const string& name ) const\n{\n string filename = \"assets\/images\/\" + name + \".png\";\n\n string realpath(getRealPath(filename));\n\n fipImage* image = new fipImage;\n\n if ( !image->load( realpath.c_str() ) ) {\n assert(false); \/\/ Shouldn't fail.\n }\n image->convertTo24Bits();\n\n LOG( logINFO ) << filename << \" loaded to texture.\";\n return image;\n}\n\nconst string FileService::getRealPath(const string& path) const\n{\n if (!PHYSFS_exists(path.c_str())) {\n LOG( logERROR ) << path << \" not found.\";\n throw FileNotFoundException();\n }\n string realpath(PHYSFS_getRealDir(path.c_str()));\n realpath += m_dirseparator + path;\n return realpath;\n}\n\nEntity FileService::createEntity(const string& name) const\n{\n string path = \"assets\/entities\/\" + name + \".xml\";\n string realpath(getRealPath(path));\n return m_entity_factory->createEntity(realpath);\n}\n\nconst std::string gamefw::FileService::getDirSeparator() const\n{\n return m_dirseparator;\n}\n<commit_msg>Add fallback base directory name \"obsbul\" in Fileservice.<commit_after>#include \"..\/common.h\"\n\n#include <fstream>\n\n#include <FreeImagePlus.h>\n#include <physfs.h>\n\n#include \"fileservice.h\"\n\n#include \"gamefw.h\"\n\nusing namespace gamefw;\n\nFileService::FileService()\n{\n FreeImage_Initialise( 0 );\n if (!PHYSFS_isInit())\n PHYSFS_init(NULL);\n PHYSFS_setSaneConfig(\"config\", PROJECT_NAME, \"ob\", 0, 1);\n\n m_dirseparator.assign(PHYSFS_getDirSeparator());\n\n \/\/ Find the project directory\n string basedir(PHYSFS_getBaseDir());\n\n string project_name(PROJECT_NAME);\n\n int project_path_pos = basedir.find(project_name);\n int fallback_path_pos = basedir.find(project_name);\n if (project_path_pos == basedir.npos) {\n if (fallback_path_pos == basedir.npos) {\n LOG(logFATAL) << \"Project \" << project_name <<\n \" root directory not found from \" << basedir;\n\t\t}\n\t\tproject_path_pos = fallback_path_pos;\n }\n basedir.erase(project_path_pos + project_name.length());\n\n\n PHYSFS_mount(basedir.c_str(), NULL, 0); \/\/ Mount to root.\n\n m_entity_factory = new EntityFactory();\n}\n\nFileService::~FileService()\n{\n delete m_entity_factory;\n PHYSFS_deinit();\n FreeImage_DeInitialise();\n}\n\nconst char* FileNotFoundException::what() const throw()\n{\n return \"File not found.\";\n}\n\nconst char* FileService::fileToBuffer(const string& filename ) const\n{\n const string realpath(getRealPath(filename));\n\n \/\/ Open file at end.\n ifstream file( realpath.c_str(), ios::in | ios::ate );\n\n if ( file.is_open() ) {\n uint size = (uint) file.tellg(); \/\/ Get file size.\n \/\/ The +1 is for '\\0'.\n char* buffer = new char[size + 1];\n file.seekg( 0, ios::beg ); \/\/ Back to start.\n char* c = buffer;\n \/\/ Read the file to buffer.\n while (file.good()) {\n file.get(*c);\n c++;\n }\n\n file.close();\n\n *(c - 1) = '\\0'; \/\/ Delete EOF.\n\n LOG( logINFO ) << filename << \" loaded into buffer.\";\n\n return buffer;\n }\n\n LOG( logERROR ) << filename << \" not found.\";\n throw FileNotFoundException();\n}\n\nGLuint FileService::makeTexture( const string& name ) const\n{\n fipImage* image = readImage( name );\n\n assert( image->isValid() );\n\n int width = image->getWidth();\n int height = image->getHeight();\n void* pixels = (void*) image->accessPixels();\n GLuint texture;\n\n glGenTextures( 1, &texture );\n glBindTexture( GL_TEXTURE_2D, texture );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glTexImage2D(\n GL_TEXTURE_2D, 0, \/\/ target, level\n GL_RGB8, \/\/ internal format\n width, height, 0, \/\/ width, height, border\n GL_BGR, GL_UNSIGNED_BYTE, \/\/ external format, type\n pixels \/\/ pixels\n );\n\n image->clear();\n delete image;\n\n return texture;\n\n}\n\nfipImage* FileService::readImage( const string& name ) const\n{\n string filename = \"assets\/images\/\" + name + \".png\";\n\n string realpath(getRealPath(filename));\n\n fipImage* image = new fipImage;\n\n if ( !image->load( realpath.c_str() ) ) {\n assert(false); \/\/ Shouldn't fail.\n }\n image->convertTo24Bits();\n\n LOG( logINFO ) << filename << \" loaded to texture.\";\n return image;\n}\n\nconst string FileService::getRealPath(const string& path) const\n{\n if (!PHYSFS_exists(path.c_str())) {\n LOG( logERROR ) << path << \" not found.\";\n throw FileNotFoundException();\n }\n string realpath(PHYSFS_getRealDir(path.c_str()));\n realpath += m_dirseparator + path;\n return realpath;\n}\n\nEntity FileService::createEntity(const string& name) const\n{\n string path = \"assets\/entities\/\" + name + \".xml\";\n string realpath(getRealPath(path));\n return m_entity_factory->createEntity(realpath);\n}\n\nconst std::string gamefw::FileService::getDirSeparator() const\n{\n return m_dirseparator;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hd_docu.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: ihi $ $Date: 2006-08-24 10:44:27 $\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\n#include <precomp.h>\n#include \"hd_docu.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include <ary\/cpp\/c_namesp.hxx>\n#include <ary\/cpp\/c_class.hxx>\n#include <ary\/cpp\/c_enum.hxx>\n#include <ary\/cpp\/c_tydef.hxx>\n#include <ary\/cpp\/c_funct.hxx>\n#include <ary\/cpp\/c_vari.hxx>\n#include <ary\/cpp\/c_enuval.hxx>\n#include <ary\/info\/codeinfo.hxx>\n#include <ary\/info\/all_tags.hxx>\n#include <ary\/info\/all_dts.hxx>\n#include <adc_cl.hxx>\n#include \"html_kit.hxx\"\n\n\n\nusing namespace ary::info;\nusing namespace csi;\n\nusing html::DefList;\nusing html::DefListTerm;\nusing html::DefListDefinition;\nusing html::Headline;\nusing html::Link;\n\n\nconst char *\nC_sTagHeadlines[ ary::info::C_eAtTag_NrOfClasses ] =\n {\n \"ATTENTION!\", \"Author\", \"Changes\", \"Collaborators\",\n \"Contact\", \/\/ Contact may be unused\n \"Copyright\", \"Deprecated\", \"Description\", \"Date of Documentation\",\n \"How to Derive from this Class\",\n \"Heap object - owner is responsible for deletion.\",\n \"Important Instances\",\n \"Interface Only\",\n \"Invariant\", \"Lifecycle\",\n \"Multiplicity\", \"On Error\", \"Persistency\", \"Postcondition\",\n \"Precondition\",\n \"Responsibilities\",\n \"Return\", \"Summary\", \"Todos\", \"Version\",\n \"Base Classes\", \"Exceptions\", \"Implements\", \"Keywords\", \"Parameters\",\n \"See Also\", \"Template Parameters\",\n \"\", \"Since \"\n };\n\n\n\nDocu_Display::Docu_Display( OuputPage_Environment & io_rEnv )\n : HtmlDisplay_Impl(io_rEnv),\n bUseHtmlInDocuTokens(false),\n pCurClassOverwrite(0)\n{\n}\n\nDocu_Display::~Docu_Display()\n{\n}\n\nvoid\nDocu_Display::Assign_Out( csi::xml::Element & o_rOut )\n{\n Easy().Enter(o_rOut);\n}\n\nvoid\nDocu_Display::Unassign_Out()\n{\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Display_Namespace( const ary::cpp::Namespace & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\nvoid\nDocu_Display::Display_Class( const ary::cpp::Class & i_rData )\n{\n pCurClassOverwrite = &i_rData;\n i_rData.Info().StoreAt( *this );\n pCurClassOverwrite = 0;\n}\n\nvoid\nDocu_Display::Display_Enum( const ary::cpp::Enum & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\nvoid\nDocu_Display::Display_Typedef( const ary::cpp::Typedef & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\nvoid\nDocu_Display::Display_Function( const ary::cpp::Function & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\nvoid\nDocu_Display::Display_Variable( const ary::cpp::Variable & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\n\n\/\/ -------------- Interface ary::info::DocuDisplay ------------------ \/\/\n\n\nvoid\nDocu_Display::Display_CodeInfo( const CodeInfo & i_rData )\n{\n Start_DocuBlock();\n\n if ( i_rData.IsObsolete() )\n {\n CurOut()\n >> *new html::DefListTerm\n >> *new html::Strong\n << \"D E P R E C A T E D\";\n\n }\n\n CodeInfo::TagList::const_iterator itEnd = i_rData.Tags().end();\n for ( CodeInfo::TagList::const_iterator it = i_rData.Tags().begin();\n it != itEnd;\n ++it )\n {\n (*it)->StoreAt( *this );\n }\n\n Finish_DocuBlock();\n}\n\nvoid\nDocu_Display::Display_StdTag( const StdTag & i_rData )\n{\n csv_assert( int(i_rData.Std_Id()) < int(ary::info::C_eAtTag_NrOfClasses) );\n\n const ary::info::DocuText::TokenList &\n rText = i_rData.CText().Tokens();\n typedef ary::info::DocuText::TokenList::const_iterator TokenIterator;\n\n if ( rText.empty() )\n return;\n else if ( rText.size() < 3 )\n {\n bool bIsWhite = true;\n for ( TokenIterator it = rText.begin();\n it != rText.end();\n ++it )\n {\n if (bIsWhite)\n bIsWhite = (*it)->IsWhite();\n }\n if (bIsWhite)\n return;\n }\n\n Write_TagTitle( C_sTagHeadlines[i_rData.Std_Id()] );\n Write_TagContents( i_rData.CText() );\n}\n\nvoid\nDocu_Display::Display_BaseTag( const BaseTag & )\n{\n\n}\n\nvoid\nDocu_Display::Display_ExceptionTag( const ExceptionTag & )\n{\n}\n\nvoid\nDocu_Display::Display_ImplementsTag( const ImplementsTag & )\n{\n}\n\nvoid\nDocu_Display::Display_KeywordTag( const KeywordTag & )\n{\n}\n\nvoid\nDocu_Display::Display_ParameterTag( const ParameterTag & i_rData )\n{\n Write_TagTitle( \"Parameters\" );\n\n adcdisp::ExplanationTable\n aParams( CurOut() >> *new DefListDefinition );\n\n for ( const ParameterTag * pParam = &i_rData;\n pParam != 0;\n pParam = pParam->GetNext() ) \/\/ KORR_FUTURE\n {\n aParams.AddEntry( pParam->ParamName().c_str() );\n\n Easy().Enter( aParams.Def() );\n Write_Text( pParam->CText() );\n Easy().Leave();\n } \/\/ end for\n}\n\nvoid\nDocu_Display::Display_SeeTag( const SeeTag & i_rData )\n{\n Write_TagTitle( \"See Also\" );\n\n DefListDefinition * dpDef = new DefListDefinition;\n CurOut() << dpDef;\n Easy().Enter(*dpDef);\n\n for ( std::vector< ary::QualifiedName >::const_iterator\n it = i_rData.References().begin();\n it != i_rData.References().end();\n ++it )\n {\n Write_LinkableText( (*it) );\n CurOut() << new html::LineBreak;\n }\n\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Display_TemplateTag( const TemplateTag & i_rData )\n{\n Write_TagTitle( \"Template Parameters\" );\n\n adcdisp::ExplanationTable\n aTplParams( CurOut() >> *new DefListDefinition );\n\n for ( const TemplateTag * pTplParam = &i_rData;\n pTplParam != 0;\n pTplParam = pTplParam->GetNext() )\n {\n aTplParams.AddEntry( pTplParam->TplParamName().c_str() );\n\n Easy().Enter( aTplParams.Def() );\n Write_Text( pTplParam->CText() );\n Easy().Leave();\n } \/\/ end for\n}\n\nvoid\nDocu_Display::Display_LabelTag( const LabelTag & )\n{\n}\n\nvoid\nDocu_Display::Display_SinceTag( const ary::info::SinceTag & i_rData )\n{\n if ( i_rData.Version().empty() )\n {\n return;\n }\n\n \/\/ Transform the value of the @since tag into the text to be displayed.\n String sDisplay;\n if ( autodoc::CommandLine::Get_().DoesTransform_SinceTag() )\n {\n sDisplay = autodoc::CommandLine::Get_()\n .DisplayOf_SinceTagValue( i_rData.Version() );\n }\n else\n {\n sDisplay = i_rData.Version();\n }\n\n if (sDisplay.empty())\n return;\n\n Write_TagTitle( \"Since \" );\n\n DefListDefinition * dpDef = new DefListDefinition;\n CurOut() << dpDef;\n\n Easy().Enter(*dpDef);\n CurOut() << sDisplay;\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Display_DT_Text( const DT_Text & i_rData )\n{\n Write_TextToken( i_rData.Text() );\n}\n\nvoid\nDocu_Display::Display_DT_MaybeLink( const DT_MaybeLink & i_rData )\n{\n \/\/ KORR_FUTURE\n Write_TextToken( i_rData.Text() );\n}\n\nvoid\nDocu_Display::Display_DT_Whitespace( const DT_Whitespace & i_rData )\n{\n static char sSpace[300] =\n \" \"\n \" \"\n \" \"\n \" \"\n \" \"\n \" \";\n UINT8 nLength = i_rData.Length();\n sSpace[nLength] = NULCH;\n CurOut() << sSpace;\n sSpace[nLength] = ' ';\n}\n\nvoid\nDocu_Display::Display_DT_Eol( const DT_Eol & )\n{\n CurOut() << new html::Sbr;\n}\n\nvoid\nDocu_Display::Display_DT_Xml( const ary::info::DT_Xml & i_rData )\n{\n CurOut() << new xml::XmlCode( i_rData.Text() );\n}\n\n\nvoid\nDocu_Display::Start_DocuBlock()\n{\n DYN DefList * dpDefList = new DefList;\n CurOut() << dpDefList;\n Easy().Enter( *dpDefList );\n}\n\nvoid\nDocu_Display::Finish_DocuBlock()\n{\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Write_TagTitle( const char * i_sText,\n const char * )\n{\n if ( strcmp(i_sText,\"ATTENTION!\") == 0 )\n {\n CurOut()\n >> *new html::DefListTerm\n << new html::ClassAttr(\"attention\")\n << i_sText;\n }\n else\n {\n CurOut()\n >> *new html::DefListTerm\n << i_sText;\n }\n}\n\nvoid\nDocu_Display::Write_TagContents( const DocuText & i_rDocuText )\n{\n DefListDefinition * dpDef = new DefListDefinition;\n CurOut() << dpDef;\n\n Easy().Enter(*dpDef);\n Write_Text(i_rDocuText);\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Write_Text( const ary::info::DocuText & i_rDocuText )\n{\n if ( i_rDocuText.IsNoHtml() )\n {\n CurOut()\n << new xml::XmlCode(\"<pre>\");\n bUseHtmlInDocuTokens = false;\n }\n else\n {\n bUseHtmlInDocuTokens = true;\n }\n i_rDocuText.StoreAt( *this );\n if ( i_rDocuText.IsNoHtml() )\n {\n CurOut()\n << new xml::XmlCode(\"<\/pre>\");\n }\n}\n\nvoid\nDocu_Display::Write_TextToken( const udmstri & i_sText )\n{\n if ( bUseHtmlInDocuTokens )\n CurOut() << new xml::XmlCode(i_sText);\n else\n CurOut() << i_sText;\n}\n\nvoid\nDocu_Display::Write_LinkableText( const ary::QualifiedName & i_sQuName )\n{\n const ary::CodeEntity *\n pCe = FindUnambiguousCe( Env(), i_sQuName, pCurClassOverwrite );\n if ( pCe != 0 )\n {\n csi::xml::Element *\n pLink = new csi::html::Link( Link2Ce(Env(), *pCe) );\n CurOut() << pLink;\n Easy().Enter(*pLink);\n Write_QualifiedName(i_sQuName);\n Easy().Leave();\n }\n else\n {\n Write_QualifiedName(i_sQuName);\n }\n CurOut() << \" \";\n}\n\nvoid\nDocu_Display::Write_QualifiedName( const ary::QualifiedName & i_sQuName )\n{\n if ( i_sQuName.IsAbsolute() )\n CurOut() << \"::\";\n for ( ary::QualifiedName::namespace_iterator it = i_sQuName.first_namespace();\n it != i_sQuName.end_namespace();\n ++it )\n {\n CurOut() << (*it) << \"::\";\n }\n CurOut() << i_sQuName.LocalName();\n if ( i_sQuName.IsFunction() )\n CurOut() << \"()\";\n}\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.7.6); FILE MERGED 2006\/09\/01 17:15:31 kaib 1.7.6.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hd_docu.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 16:41:28 $\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_autodoc.hxx\"\n\n\n#include <precomp.h>\n#include \"hd_docu.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include <ary\/cpp\/c_namesp.hxx>\n#include <ary\/cpp\/c_class.hxx>\n#include <ary\/cpp\/c_enum.hxx>\n#include <ary\/cpp\/c_tydef.hxx>\n#include <ary\/cpp\/c_funct.hxx>\n#include <ary\/cpp\/c_vari.hxx>\n#include <ary\/cpp\/c_enuval.hxx>\n#include <ary\/info\/codeinfo.hxx>\n#include <ary\/info\/all_tags.hxx>\n#include <ary\/info\/all_dts.hxx>\n#include <adc_cl.hxx>\n#include \"html_kit.hxx\"\n\n\n\nusing namespace ary::info;\nusing namespace csi;\n\nusing html::DefList;\nusing html::DefListTerm;\nusing html::DefListDefinition;\nusing html::Headline;\nusing html::Link;\n\n\nconst char *\nC_sTagHeadlines[ ary::info::C_eAtTag_NrOfClasses ] =\n {\n \"ATTENTION!\", \"Author\", \"Changes\", \"Collaborators\",\n \"Contact\", \/\/ Contact may be unused\n \"Copyright\", \"Deprecated\", \"Description\", \"Date of Documentation\",\n \"How to Derive from this Class\",\n \"Heap object - owner is responsible for deletion.\",\n \"Important Instances\",\n \"Interface Only\",\n \"Invariant\", \"Lifecycle\",\n \"Multiplicity\", \"On Error\", \"Persistency\", \"Postcondition\",\n \"Precondition\",\n \"Responsibilities\",\n \"Return\", \"Summary\", \"Todos\", \"Version\",\n \"Base Classes\", \"Exceptions\", \"Implements\", \"Keywords\", \"Parameters\",\n \"See Also\", \"Template Parameters\",\n \"\", \"Since \"\n };\n\n\n\nDocu_Display::Docu_Display( OuputPage_Environment & io_rEnv )\n : HtmlDisplay_Impl(io_rEnv),\n bUseHtmlInDocuTokens(false),\n pCurClassOverwrite(0)\n{\n}\n\nDocu_Display::~Docu_Display()\n{\n}\n\nvoid\nDocu_Display::Assign_Out( csi::xml::Element & o_rOut )\n{\n Easy().Enter(o_rOut);\n}\n\nvoid\nDocu_Display::Unassign_Out()\n{\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Display_Namespace( const ary::cpp::Namespace & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\nvoid\nDocu_Display::Display_Class( const ary::cpp::Class & i_rData )\n{\n pCurClassOverwrite = &i_rData;\n i_rData.Info().StoreAt( *this );\n pCurClassOverwrite = 0;\n}\n\nvoid\nDocu_Display::Display_Enum( const ary::cpp::Enum & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\nvoid\nDocu_Display::Display_Typedef( const ary::cpp::Typedef & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\nvoid\nDocu_Display::Display_Function( const ary::cpp::Function & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\nvoid\nDocu_Display::Display_Variable( const ary::cpp::Variable & i_rData )\n{\n i_rData.Info().StoreAt( *this );\n}\n\n\n\/\/ -------------- Interface ary::info::DocuDisplay ------------------ \/\/\n\n\nvoid\nDocu_Display::Display_CodeInfo( const CodeInfo & i_rData )\n{\n Start_DocuBlock();\n\n if ( i_rData.IsObsolete() )\n {\n CurOut()\n >> *new html::DefListTerm\n >> *new html::Strong\n << \"D E P R E C A T E D\";\n\n }\n\n CodeInfo::TagList::const_iterator itEnd = i_rData.Tags().end();\n for ( CodeInfo::TagList::const_iterator it = i_rData.Tags().begin();\n it != itEnd;\n ++it )\n {\n (*it)->StoreAt( *this );\n }\n\n Finish_DocuBlock();\n}\n\nvoid\nDocu_Display::Display_StdTag( const StdTag & i_rData )\n{\n csv_assert( int(i_rData.Std_Id()) < int(ary::info::C_eAtTag_NrOfClasses) );\n\n const ary::info::DocuText::TokenList &\n rText = i_rData.CText().Tokens();\n typedef ary::info::DocuText::TokenList::const_iterator TokenIterator;\n\n if ( rText.empty() )\n return;\n else if ( rText.size() < 3 )\n {\n bool bIsWhite = true;\n for ( TokenIterator it = rText.begin();\n it != rText.end();\n ++it )\n {\n if (bIsWhite)\n bIsWhite = (*it)->IsWhite();\n }\n if (bIsWhite)\n return;\n }\n\n Write_TagTitle( C_sTagHeadlines[i_rData.Std_Id()] );\n Write_TagContents( i_rData.CText() );\n}\n\nvoid\nDocu_Display::Display_BaseTag( const BaseTag & )\n{\n\n}\n\nvoid\nDocu_Display::Display_ExceptionTag( const ExceptionTag & )\n{\n}\n\nvoid\nDocu_Display::Display_ImplementsTag( const ImplementsTag & )\n{\n}\n\nvoid\nDocu_Display::Display_KeywordTag( const KeywordTag & )\n{\n}\n\nvoid\nDocu_Display::Display_ParameterTag( const ParameterTag & i_rData )\n{\n Write_TagTitle( \"Parameters\" );\n\n adcdisp::ExplanationTable\n aParams( CurOut() >> *new DefListDefinition );\n\n for ( const ParameterTag * pParam = &i_rData;\n pParam != 0;\n pParam = pParam->GetNext() ) \/\/ KORR_FUTURE\n {\n aParams.AddEntry( pParam->ParamName().c_str() );\n\n Easy().Enter( aParams.Def() );\n Write_Text( pParam->CText() );\n Easy().Leave();\n } \/\/ end for\n}\n\nvoid\nDocu_Display::Display_SeeTag( const SeeTag & i_rData )\n{\n Write_TagTitle( \"See Also\" );\n\n DefListDefinition * dpDef = new DefListDefinition;\n CurOut() << dpDef;\n Easy().Enter(*dpDef);\n\n for ( std::vector< ary::QualifiedName >::const_iterator\n it = i_rData.References().begin();\n it != i_rData.References().end();\n ++it )\n {\n Write_LinkableText( (*it) );\n CurOut() << new html::LineBreak;\n }\n\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Display_TemplateTag( const TemplateTag & i_rData )\n{\n Write_TagTitle( \"Template Parameters\" );\n\n adcdisp::ExplanationTable\n aTplParams( CurOut() >> *new DefListDefinition );\n\n for ( const TemplateTag * pTplParam = &i_rData;\n pTplParam != 0;\n pTplParam = pTplParam->GetNext() )\n {\n aTplParams.AddEntry( pTplParam->TplParamName().c_str() );\n\n Easy().Enter( aTplParams.Def() );\n Write_Text( pTplParam->CText() );\n Easy().Leave();\n } \/\/ end for\n}\n\nvoid\nDocu_Display::Display_LabelTag( const LabelTag & )\n{\n}\n\nvoid\nDocu_Display::Display_SinceTag( const ary::info::SinceTag & i_rData )\n{\n if ( i_rData.Version().empty() )\n {\n return;\n }\n\n \/\/ Transform the value of the @since tag into the text to be displayed.\n String sDisplay;\n if ( autodoc::CommandLine::Get_().DoesTransform_SinceTag() )\n {\n sDisplay = autodoc::CommandLine::Get_()\n .DisplayOf_SinceTagValue( i_rData.Version() );\n }\n else\n {\n sDisplay = i_rData.Version();\n }\n\n if (sDisplay.empty())\n return;\n\n Write_TagTitle( \"Since \" );\n\n DefListDefinition * dpDef = new DefListDefinition;\n CurOut() << dpDef;\n\n Easy().Enter(*dpDef);\n CurOut() << sDisplay;\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Display_DT_Text( const DT_Text & i_rData )\n{\n Write_TextToken( i_rData.Text() );\n}\n\nvoid\nDocu_Display::Display_DT_MaybeLink( const DT_MaybeLink & i_rData )\n{\n \/\/ KORR_FUTURE\n Write_TextToken( i_rData.Text() );\n}\n\nvoid\nDocu_Display::Display_DT_Whitespace( const DT_Whitespace & i_rData )\n{\n static char sSpace[300] =\n \" \"\n \" \"\n \" \"\n \" \"\n \" \"\n \" \";\n UINT8 nLength = i_rData.Length();\n sSpace[nLength] = NULCH;\n CurOut() << sSpace;\n sSpace[nLength] = ' ';\n}\n\nvoid\nDocu_Display::Display_DT_Eol( const DT_Eol & )\n{\n CurOut() << new html::Sbr;\n}\n\nvoid\nDocu_Display::Display_DT_Xml( const ary::info::DT_Xml & i_rData )\n{\n CurOut() << new xml::XmlCode( i_rData.Text() );\n}\n\n\nvoid\nDocu_Display::Start_DocuBlock()\n{\n DYN DefList * dpDefList = new DefList;\n CurOut() << dpDefList;\n Easy().Enter( *dpDefList );\n}\n\nvoid\nDocu_Display::Finish_DocuBlock()\n{\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Write_TagTitle( const char * i_sText,\n const char * )\n{\n if ( strcmp(i_sText,\"ATTENTION!\") == 0 )\n {\n CurOut()\n >> *new html::DefListTerm\n << new html::ClassAttr(\"attention\")\n << i_sText;\n }\n else\n {\n CurOut()\n >> *new html::DefListTerm\n << i_sText;\n }\n}\n\nvoid\nDocu_Display::Write_TagContents( const DocuText & i_rDocuText )\n{\n DefListDefinition * dpDef = new DefListDefinition;\n CurOut() << dpDef;\n\n Easy().Enter(*dpDef);\n Write_Text(i_rDocuText);\n Easy().Leave();\n}\n\nvoid\nDocu_Display::Write_Text( const ary::info::DocuText & i_rDocuText )\n{\n if ( i_rDocuText.IsNoHtml() )\n {\n CurOut()\n << new xml::XmlCode(\"<pre>\");\n bUseHtmlInDocuTokens = false;\n }\n else\n {\n bUseHtmlInDocuTokens = true;\n }\n i_rDocuText.StoreAt( *this );\n if ( i_rDocuText.IsNoHtml() )\n {\n CurOut()\n << new xml::XmlCode(\"<\/pre>\");\n }\n}\n\nvoid\nDocu_Display::Write_TextToken( const udmstri & i_sText )\n{\n if ( bUseHtmlInDocuTokens )\n CurOut() << new xml::XmlCode(i_sText);\n else\n CurOut() << i_sText;\n}\n\nvoid\nDocu_Display::Write_LinkableText( const ary::QualifiedName & i_sQuName )\n{\n const ary::CodeEntity *\n pCe = FindUnambiguousCe( Env(), i_sQuName, pCurClassOverwrite );\n if ( pCe != 0 )\n {\n csi::xml::Element *\n pLink = new csi::html::Link( Link2Ce(Env(), *pCe) );\n CurOut() << pLink;\n Easy().Enter(*pLink);\n Write_QualifiedName(i_sQuName);\n Easy().Leave();\n }\n else\n {\n Write_QualifiedName(i_sQuName);\n }\n CurOut() << \" \";\n}\n\nvoid\nDocu_Display::Write_QualifiedName( const ary::QualifiedName & i_sQuName )\n{\n if ( i_sQuName.IsAbsolute() )\n CurOut() << \"::\";\n for ( ary::QualifiedName::namespace_iterator it = i_sQuName.first_namespace();\n it != i_sQuName.end_namespace();\n ++it )\n {\n CurOut() << (*it) << \"::\";\n }\n CurOut() << i_sQuName.LocalName();\n if ( i_sQuName.IsFunction() )\n CurOut() << \"()\";\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tbxctl.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2007-06-26 16:52:41 $\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 _BASIDE_TBXCTL_HXX\n#define _BASIDE_TBXCTL_HXX\n\n#ifndef _SFXTBXCTRL_HXX \/\/autogen\n#include <sfx2\/tbxctrl.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_\n#include <com\/sun\/star\/frame\/XLayoutManager.hpp>\n#endif\n\n\/*\n#ifdef _BASIDE_POPUPWINDOWTBX\n\n\/\/ class PopupWindowTbx --------------------------------------------------\n\nclass PopupWindowTbx : public SfxPopupWindow\n{\nprivate:\n SfxToolBoxManager aTbx;\n Link aSelectLink;\n\n DECL_LINK( SelectHdl, void* );\n\npublic:\n PopupWindowTbx( USHORT nId, WindowAlign eAlign,\n ResId aRIdWin, ResId aRIdTbx, SfxBindings& rBind );\n ~PopupWindowTbx();\n\n void StartSelection()\n { aTbx.GetToolBox().StartSelection(); }\n void Update();\n\n virtual SfxPopupWindow* Clone() const;\n virtual void PopupModeEnd();\n};\n#endif\n*\/\n\/\/-------------------\n\/\/ class TbxControls\n\/\/-------------------\nclass TbxControls : public SfxToolBoxControl\n{\nprivate:\n\n struct StateChangedInfo\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager;\n bool bDisabled;\n };\n\n USHORT nLastSlot;\n\nprotected:\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\npublic:\n SFX_DECL_TOOLBOX_CONTROL();\n\n TbxControls(USHORT nSlotId, USHORT nId, ToolBox& rTbx );\n ~TbxControls() {}\n\n virtual SfxPopupWindowType GetPopupWindowType() const;\n virtual SfxPopupWindow* CreatePopupWindow();\n\n using SfxToolBoxControl::Select;\n void Select( USHORT nModifier );\n};\n\n\n#endif \/\/ _BASIDE_TBXCTL_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.9.62); FILE MERGED 2008\/04\/01 15:00:39 thb 1.9.62.3: #i85898# Stripping all external header guards 2008\/04\/01 10:47:46 thb 1.9.62.2: #i85898# Stripping all external header guards 2008\/03\/28 16:04:50 rt 1.9.62.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: tbxctl.hxx,v $\n * $Revision: 1.10 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _BASIDE_TBXCTL_HXX\n#define _BASIDE_TBXCTL_HXX\n\n#include <sfx2\/tbxctrl.hxx>\n#include <com\/sun\/star\/frame\/XLayoutManager.hpp>\n\n\/*\n#ifdef _BASIDE_POPUPWINDOWTBX\n\n\/\/ class PopupWindowTbx --------------------------------------------------\n\nclass PopupWindowTbx : public SfxPopupWindow\n{\nprivate:\n SfxToolBoxManager aTbx;\n Link aSelectLink;\n\n DECL_LINK( SelectHdl, void* );\n\npublic:\n PopupWindowTbx( USHORT nId, WindowAlign eAlign,\n ResId aRIdWin, ResId aRIdTbx, SfxBindings& rBind );\n ~PopupWindowTbx();\n\n void StartSelection()\n { aTbx.GetToolBox().StartSelection(); }\n void Update();\n\n virtual SfxPopupWindow* Clone() const;\n virtual void PopupModeEnd();\n};\n#endif\n*\/\n\/\/-------------------\n\/\/ class TbxControls\n\/\/-------------------\nclass TbxControls : public SfxToolBoxControl\n{\nprivate:\n\n struct StateChangedInfo\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager;\n bool bDisabled;\n };\n\n USHORT nLastSlot;\n\nprotected:\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\npublic:\n SFX_DECL_TOOLBOX_CONTROL();\n\n TbxControls(USHORT nSlotId, USHORT nId, ToolBox& rTbx );\n ~TbxControls() {}\n\n virtual SfxPopupWindowType GetPopupWindowType() const;\n virtual SfxPopupWindow* CreatePopupWindow();\n\n using SfxToolBoxControl::Select;\n void Select( USHORT nModifier );\n};\n\n\n#endif \/\/ _BASIDE_TBXCTL_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"dlgedpage.hxx\"\n#include \"dlged.hxx\"\n#include \"dlgedmod.hxx\"\n#include \"dlgedobj.hxx\"\n\nnamespace basctl\n{\n\nTYPEINIT1( DlgEdPage, SdrPage );\n\n\/\/----------------------------------------------------------------------------\n\nDlgEdPage::DlgEdPage( DlgEdModel& rModel, bool bMasterPage )\n :SdrPage( rModel, bMasterPage )\n{\n}\n\n\/\/----------------------------------------------------------------------------\n\nDlgEdPage::~DlgEdPage()\n{\n Clear();\n}\n\n\/\/----------------------------------------------------------------------------\n\nSdrPage* DlgEdPage::Clone() const\n{\n return new DlgEdPage( *this );\n}\n\n\/\/----------------------------------------------------------------------------\n\nSdrObject* DlgEdPage::SetObjectOrdNum(sal_uLong nOldObjNum, sal_uLong nNewObjNum)\n{\n SdrObject* pObj = SdrPage::SetObjectOrdNum( nOldObjNum, nNewObjNum );\n\n DlgEdHint aHint( DlgEdHint::OBJORDERCHANGED );\n if ( pDlgEdForm )\n pDlgEdForm->GetDlgEditor().Broadcast( aHint );\n\n return pObj;\n}\n\n\/\/----------------------------------------------------------------------------\n\n} \/\/ namespace basctl\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>CID#738562 uninitialized member<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"dlgedpage.hxx\"\n#include \"dlged.hxx\"\n#include \"dlgedmod.hxx\"\n#include \"dlgedobj.hxx\"\n\nnamespace basctl\n{\n\nTYPEINIT1( DlgEdPage, SdrPage );\n\n\/\/----------------------------------------------------------------------------\n\nDlgEdPage::DlgEdPage(DlgEdModel& rModel, bool bMasterPage)\n : SdrPage(rModel, bMasterPage)\n , pDlgEdForm(0)\n{\n}\n\n\/\/----------------------------------------------------------------------------\n\nDlgEdPage::~DlgEdPage()\n{\n Clear();\n}\n\n\/\/----------------------------------------------------------------------------\n\nSdrPage* DlgEdPage::Clone() const\n{\n return new DlgEdPage( *this );\n}\n\n\/\/----------------------------------------------------------------------------\n\nSdrObject* DlgEdPage::SetObjectOrdNum(sal_uLong nOldObjNum, sal_uLong nNewObjNum)\n{\n SdrObject* pObj = SdrPage::SetObjectOrdNum( nOldObjNum, nNewObjNum );\n\n DlgEdHint aHint( DlgEdHint::OBJORDERCHANGED );\n if ( pDlgEdForm )\n pDlgEdForm->GetDlgEditor().Broadcast( aHint );\n\n return pObj;\n}\n\n\/\/----------------------------------------------------------------------------\n\n} \/\/ namespace basctl\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tcommuni.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:33:40 $\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\n#ifndef _CONFIG_HXX\n#include <tools\/config.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _TOOLS_TIME_HXX \/\/autogen\n#include <tools\/time.hxx>\n#endif\n#ifndef _DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include <vos\/process.hxx>\n#endif\n#include <vcl\/timer.hxx>\n\n#ifndef _BASIC_TTRESHLP_HXX\n#include <basic\/ttstrhlp.hxx>\n#endif\n\n#include \"rcontrol.hxx\"\n#include \"tcommuni.hxx\"\n#include <basic\/testtool.hxx>\n\nCommunicationManagerClientViaSocketTT::CommunicationManagerClientViaSocketTT()\n: CommunicationManagerClientViaSocket( TRUE )\n, aAppPath()\n, aAppParams()\n, pProcess( NULL )\n{\n}\n\n\nBOOL CommunicationManagerClientViaSocketTT::StartCommunication()\n{\n bApplicationStarted = FALSE;\n return CommunicationManagerClientViaSocket::StartCommunication( ByteString( GetHostConfig(), RTL_TEXTENCODING_UTF8 ), GetTTPortConfig() );\n}\n\n\nBOOL CommunicationManagerClientViaSocketTT::StartCommunication( String aApp, String aParams, Environment *pChildEnv )\n{\n aAppPath = aApp;\n aAppParams = aParams;\n aAppEnv = (*pChildEnv);\n return StartCommunication();\n}\n\n\nBOOL CommunicationManagerClientViaSocketTT::RetryConnect()\n{\n if ( !bApplicationStarted )\n {\n \/\/ Die App ist wohl nicht da. Starten wir sie mal.\n if ( aAppPath.Len() )\n {\n delete pProcess;\n\n pProcess = new Process();\n pProcess->SetImage( aAppPath, aAppParams, &aAppEnv );\n\n BOOL bSucc = pProcess->Start();\n bApplicationStarted = TRUE;\n\n if ( bSucc )\n {\n aFirstRetryCall = Time() + Time( 0, 1 ); \/\/ Max eine Minute Zeit\n for ( int i = 10 ; i-- ; )\n GetpApp()->Reschedule();\n }\n return bSucc;\n }\n return FALSE;\n }\n else\n {\n if ( aFirstRetryCall > Time() )\n {\n Timer aWait;\n aWait.SetTimeout( 500 ); \/\/ Max 500 mSec\n aWait.Start();\n while ( aWait.IsActive() )\n GetpApp()->Yield();\n return TRUE;\n }\n else\n return FALSE;\n }\n}\n\nBOOL CommunicationManagerClientViaSocketTT::KillApplication()\n{\n if ( pProcess )\n return pProcess->Terminate();\n return TRUE;\n}\n\n#define GETSET(aVar, KeyName, Dafault) \\\n aVar = aConf.ReadKey(KeyName,\"No Entry\"); \\\n if ( aVar.CompareTo(\"No Entry\") == COMPARE_EQUAL ) \\\n { \\\n aVar = ByteString(Dafault); \\\n aConf.WriteKey(KeyName, aVar); \\\n }\n\n\nString GetHostConfig()\n{\n String aHostToTalk;\n\n for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )\n {\n if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii(\"-host=\") == COMPARE_EQUAL\n#ifndef UNX\n || Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii(\"\/host=\") == COMPARE_EQUAL\n#endif\n )\n return Application::GetCommandLineParam( i ).Copy(6);\n }\n\n ByteString abHostToTalk;\n Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString(\"testtool\") ));\n aConf.SetGroup(\"Communication\");\n\n GETSET( abHostToTalk, \"Host\", DEFAULT_HOST );\n return UniString( abHostToTalk, RTL_TEXTENCODING_UTF8 );\n}\n\n\nULONG GetTTPortConfig()\n{\n String aPortToTalk;\n\n for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )\n {\n if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii(\"-port=\") == COMPARE_EQUAL\n#ifndef UNX\n || Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii(\"\/port=\") == COMPARE_EQUAL\n#endif\n )\n {\n aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);\n return (ULONG)aPortToTalk.ToInt64();\n }\n }\n\n ByteString abPortToTalk;\n Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString(\"testtool\") ));\n aConf.SetGroup(\"Communication\");\n\n GETSET( abPortToTalk, \"TTPort\", ByteString::CreateFromInt32( TESTTOOL_DEFAULT_PORT ) );\n return (ULONG)abPortToTalk.ToInt64();\n}\n\n\nULONG GetUnoPortConfig()\n{\n String aPortToTalk;\n\n for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )\n {\n if ( Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii(\"-unoport=\") == COMPARE_EQUAL\n#ifndef UNX\n || Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii(\"\/unoport=\") == COMPARE_EQUAL\n#endif\n )\n {\n aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);\n return (ULONG)aPortToTalk.ToInt64();\n }\n }\n\n ByteString abPortToTalk;\n Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString(\"testtool\") ));\n aConf.SetGroup(\"Communication\");\n\n GETSET( abPortToTalk, \"UnoPort\", ByteString::CreateFromInt32( UNO_DEFAULT_PORT ) );\n return (ULONG)abPortToTalk.ToInt64();\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.8.56); FILE MERGED 2006\/09\/01 17:16:08 kaib 1.8.56.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tcommuni.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 00:39:39 $\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_automation.hxx\"\n\n\n#ifndef _CONFIG_HXX\n#include <tools\/config.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _TOOLS_TIME_HXX \/\/autogen\n#include <tools\/time.hxx>\n#endif\n#ifndef _DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include <vos\/process.hxx>\n#endif\n#include <vcl\/timer.hxx>\n\n#ifndef _BASIC_TTRESHLP_HXX\n#include <basic\/ttstrhlp.hxx>\n#endif\n\n#include \"rcontrol.hxx\"\n#include \"tcommuni.hxx\"\n#include <basic\/testtool.hxx>\n\nCommunicationManagerClientViaSocketTT::CommunicationManagerClientViaSocketTT()\n: CommunicationManagerClientViaSocket( TRUE )\n, aAppPath()\n, aAppParams()\n, pProcess( NULL )\n{\n}\n\n\nBOOL CommunicationManagerClientViaSocketTT::StartCommunication()\n{\n bApplicationStarted = FALSE;\n return CommunicationManagerClientViaSocket::StartCommunication( ByteString( GetHostConfig(), RTL_TEXTENCODING_UTF8 ), GetTTPortConfig() );\n}\n\n\nBOOL CommunicationManagerClientViaSocketTT::StartCommunication( String aApp, String aParams, Environment *pChildEnv )\n{\n aAppPath = aApp;\n aAppParams = aParams;\n aAppEnv = (*pChildEnv);\n return StartCommunication();\n}\n\n\nBOOL CommunicationManagerClientViaSocketTT::RetryConnect()\n{\n if ( !bApplicationStarted )\n {\n \/\/ Die App ist wohl nicht da. Starten wir sie mal.\n if ( aAppPath.Len() )\n {\n delete pProcess;\n\n pProcess = new Process();\n pProcess->SetImage( aAppPath, aAppParams, &aAppEnv );\n\n BOOL bSucc = pProcess->Start();\n bApplicationStarted = TRUE;\n\n if ( bSucc )\n {\n aFirstRetryCall = Time() + Time( 0, 1 ); \/\/ Max eine Minute Zeit\n for ( int i = 10 ; i-- ; )\n GetpApp()->Reschedule();\n }\n return bSucc;\n }\n return FALSE;\n }\n else\n {\n if ( aFirstRetryCall > Time() )\n {\n Timer aWait;\n aWait.SetTimeout( 500 ); \/\/ Max 500 mSec\n aWait.Start();\n while ( aWait.IsActive() )\n GetpApp()->Yield();\n return TRUE;\n }\n else\n return FALSE;\n }\n}\n\nBOOL CommunicationManagerClientViaSocketTT::KillApplication()\n{\n if ( pProcess )\n return pProcess->Terminate();\n return TRUE;\n}\n\n#define GETSET(aVar, KeyName, Dafault) \\\n aVar = aConf.ReadKey(KeyName,\"No Entry\"); \\\n if ( aVar.CompareTo(\"No Entry\") == COMPARE_EQUAL ) \\\n { \\\n aVar = ByteString(Dafault); \\\n aConf.WriteKey(KeyName, aVar); \\\n }\n\n\nString GetHostConfig()\n{\n String aHostToTalk;\n\n for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )\n {\n if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii(\"-host=\") == COMPARE_EQUAL\n#ifndef UNX\n || Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii(\"\/host=\") == COMPARE_EQUAL\n#endif\n )\n return Application::GetCommandLineParam( i ).Copy(6);\n }\n\n ByteString abHostToTalk;\n Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString(\"testtool\") ));\n aConf.SetGroup(\"Communication\");\n\n GETSET( abHostToTalk, \"Host\", DEFAULT_HOST );\n return UniString( abHostToTalk, RTL_TEXTENCODING_UTF8 );\n}\n\n\nULONG GetTTPortConfig()\n{\n String aPortToTalk;\n\n for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )\n {\n if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii(\"-port=\") == COMPARE_EQUAL\n#ifndef UNX\n || Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii(\"\/port=\") == COMPARE_EQUAL\n#endif\n )\n {\n aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);\n return (ULONG)aPortToTalk.ToInt64();\n }\n }\n\n ByteString abPortToTalk;\n Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString(\"testtool\") ));\n aConf.SetGroup(\"Communication\");\n\n GETSET( abPortToTalk, \"TTPort\", ByteString::CreateFromInt32( TESTTOOL_DEFAULT_PORT ) );\n return (ULONG)abPortToTalk.ToInt64();\n}\n\n\nULONG GetUnoPortConfig()\n{\n String aPortToTalk;\n\n for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )\n {\n if ( Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii(\"-unoport=\") == COMPARE_EQUAL\n#ifndef UNX\n || Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii(\"\/unoport=\") == COMPARE_EQUAL\n#endif\n )\n {\n aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);\n return (ULONG)aPortToTalk.ToInt64();\n }\n }\n\n ByteString abPortToTalk;\n Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString(\"testtool\") ));\n aConf.SetGroup(\"Communication\");\n\n GETSET( abPortToTalk, \"UnoPort\", ByteString::CreateFromInt32( UNO_DEFAULT_PORT ) );\n return (ULONG)abPortToTalk.ToInt64();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 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 \"content\/child\/runtime_features.h\"\n\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"components\/scheduler\/common\/scheduler_switches.h\"\n#include \"content\/common\/content_switches_internal.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"third_party\/WebKit\/public\/web\/WebRuntimeFeatures.h\"\n#include \"ui\/gl\/gl_switches.h\"\n#include \"ui\/native_theme\/native_theme_switches.h\"\n\n#if defined(OS_ANDROID)\n#include <cpu-features.h>\n#include \"base\/android\/build_info.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"media\/base\/android\/media_codec_bridge.h\"\n#elif defined(OS_WIN)\n#include \"base\/win\/windows_version.h\"\n#endif\n\nusing blink::WebRuntimeFeatures;\n\nnamespace content {\n\nstatic void SetRuntimeFeatureDefaultsForPlatform() {\n \/\/ Enable non-standard \"apple-touch-icon\" and \"apple-touch-icon-precomposed\".\n WebRuntimeFeatures::enableTouchIconLoading(true);\n\n#if defined(OS_ANDROID)\n \/\/ MSE\/EME implementation needs Android MediaCodec API.\n if (!media::MediaCodecBridge::IsAvailable()) {\n WebRuntimeFeatures::enableMediaSource(false);\n WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);\n WebRuntimeFeatures::enableEncryptedMedia(false);\n }\n \/\/ WebAudio is enabled by default but only when the MediaCodec API\n \/\/ is available.\n AndroidCpuFamily cpu_family = android_getCpuFamily();\n WebRuntimeFeatures::enableWebAudio(\n media::MediaCodecBridge::IsAvailable() &&\n ((cpu_family == ANDROID_CPU_FAMILY_ARM) ||\n (cpu_family == ANDROID_CPU_FAMILY_ARM64) ||\n (cpu_family == ANDROID_CPU_FAMILY_X86) ||\n (cpu_family == ANDROID_CPU_FAMILY_MIPS)));\n\n \/\/ Android does not have support for PagePopup\n WebRuntimeFeatures::enablePagePopup(false);\n \/\/ Android does not yet support SharedWorker. crbug.com\/154571\n WebRuntimeFeatures::enableSharedWorker(false);\n \/\/ Android does not yet support NavigatorContentUtils.\n WebRuntimeFeatures::enableNavigatorContentUtils(false);\n WebRuntimeFeatures::enableOrientationEvent(true);\n WebRuntimeFeatures::enableFastMobileScrolling(true);\n WebRuntimeFeatures::enableMediaCapture(true);\n WebRuntimeFeatures::enableCompositedSelectionUpdate(true);\n \/\/ Android won't be able to reliably support non-persistent notifications, the\n \/\/ intended behavior for which is in flux by itself.\n WebRuntimeFeatures::enableNotificationConstructor(false);\n#else\n WebRuntimeFeatures::enableNavigatorContentUtils(true);\n#endif \/\/ defined(OS_ANDROID)\n\n#if !(defined OS_ANDROID || defined OS_CHROMEOS || defined OS_IOS)\n \/\/ Only Android, ChromeOS, and IOS support NetInfo right now.\n WebRuntimeFeatures::enableNetworkInformation(false);\n#endif\n\n#if defined(OS_WIN)\n \/\/ Screen Orientation API is currently broken on Windows 8 Metro mode and\n \/\/ until we can find how to disable it only for Blink instances running in a\n \/\/ renderer process in Metro, we need to disable the API altogether for Win8.\n \/\/ See http:\/\/crbug.com\/400846\n if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_WIN8)\n WebRuntimeFeatures::enableScreenOrientation(false);\n#endif \/\/ OS_WIN\n}\n\nvoid SetRuntimeFeaturesDefaultsAndUpdateFromArgs(\n const base::CommandLine& command_line) {\n if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures))\n WebRuntimeFeatures::enableExperimentalFeatures(true);\n\n if (command_line.HasSwitch(switches::kEnableWebBluetooth))\n WebRuntimeFeatures::enableWebBluetooth(true);\n\n SetRuntimeFeatureDefaultsForPlatform();\n\n if (command_line.HasSwitch(switches::kDisableDatabases))\n WebRuntimeFeatures::enableDatabase(false);\n\n if (command_line.HasSwitch(scheduler::switches::kDisableBlinkScheduler))\n WebRuntimeFeatures::enableBlinkScheduler(false);\n\n if (command_line.HasSwitch(switches::kDisableMediaSource))\n WebRuntimeFeatures::enableMediaSource(false);\n\n if (command_line.HasSwitch(switches::kDisableNotifications)) {\n WebRuntimeFeatures::enableNotifications(false);\n\n \/\/ Chrome's Push Messaging implementation relies on Web Notifications.\n WebRuntimeFeatures::enablePushMessaging(false);\n }\n\n if (command_line.HasSwitch(switches::kDisableSharedWorkers))\n WebRuntimeFeatures::enableSharedWorker(false);\n\n#if defined(OS_ANDROID)\n \/\/ WebAudio is enabled by default on ARM and X86, if the MediaCodec\n \/\/ API is available.\n WebRuntimeFeatures::enableWebAudio(\n !command_line.HasSwitch(switches::kDisableWebAudio) &&\n media::MediaCodecBridge::IsAvailable());\n#else\n if (command_line.HasSwitch(switches::kDisableWebAudio))\n WebRuntimeFeatures::enableWebAudio(false);\n#endif\n\n if (command_line.HasSwitch(switches::kDisableSpeechAPI))\n WebRuntimeFeatures::enableScriptedSpeech(false);\n\n if (command_line.HasSwitch(switches::kDisableEncryptedMedia))\n WebRuntimeFeatures::enableEncryptedMedia(false);\n\n if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia))\n WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);\n\n if (command_line.HasSwitch(switches::kDisableFileSystem))\n WebRuntimeFeatures::enableFileSystem(false);\n\n if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))\n WebRuntimeFeatures::enableExperimentalCanvasFeatures(true);\n\n if (!command_line.HasSwitch(switches::kDisableAcceleratedJpegDecoding))\n WebRuntimeFeatures::enableDecodeToYUV(true);\n\n if (command_line.HasSwitch(switches::kEnableDisplayList2dCanvas))\n WebRuntimeFeatures::enableDisplayList2dCanvas(true);\n\n if (command_line.HasSwitch(switches::kDisableDisplayList2dCanvas))\n WebRuntimeFeatures::enableDisplayList2dCanvas(false);\n\n if (command_line.HasSwitch(switches::kForceDisplayList2dCanvas))\n WebRuntimeFeatures::forceDisplayList2dCanvas(true);\n\n if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))\n WebRuntimeFeatures::enableWebGLDraftExtensions(true);\n\n if (command_line.HasSwitch(switches::kEnableWebGLImageChromium))\n WebRuntimeFeatures::enableWebGLImageChromium(true);\n\n if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo))\n WebRuntimeFeatures::enableOverlayFullscreenVideo(true);\n\n if (ui::IsOverlayScrollbarEnabled())\n WebRuntimeFeatures::enableOverlayScrollbars(true);\n\n if (command_line.HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths))\n WebRuntimeFeatures::enableBleedingEdgeFastPaths(true);\n\n if (command_line.HasSwitch(switches::kEnablePreciseMemoryInfo))\n WebRuntimeFeatures::enablePreciseMemoryInfo(true);\n\n if (command_line.HasSwitch(switches::kEnableNetworkInformation) ||\n command_line.HasSwitch(\n switches::kEnableExperimentalWebPlatformFeatures)) {\n WebRuntimeFeatures::enableNetworkInformation(true);\n }\n\n if (command_line.HasSwitch(switches::kEnableCredentialManagerAPI))\n WebRuntimeFeatures::enableCredentialManagerAPI(true);\n\n if (command_line.HasSwitch(switches::kDisableSVG1DOM)) {\n WebRuntimeFeatures::enableSVG1DOM(false);\n }\n\n if (command_line.HasSwitch(switches::kReducedReferrerGranularity))\n WebRuntimeFeatures::enableReducedReferrerGranularity(true);\n\n if (command_line.HasSwitch(switches::kEnablePushMessagePayload))\n WebRuntimeFeatures::enablePushMessagingData(true);\n\n if (command_line.HasSwitch(switches::kDisablePermissionsAPI))\n WebRuntimeFeatures::enablePermissionsAPI(false);\n\n \/\/ Delete \"StaleWhileRevalidate\" line from chrome_browser_field_trials.cc\n \/\/ when this experiment is done.\n if (base::FieldTrialList::FindFullName(\"StaleWhileRevalidate\") == \"Enabled\" ||\n command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))\n WebRuntimeFeatures::enableStaleWhileRevalidateCacheControl(true);\n\n if (command_line.HasSwitch(switches::kDisableV8IdleTasks))\n WebRuntimeFeatures::enableV8IdleTasks(false);\n else\n WebRuntimeFeatures::enableV8IdleTasks(true);\n\n if (command_line.HasSwitch(switches::kEnableUnsafeES3APIs))\n WebRuntimeFeatures::enableUnsafeES3APIs(true);\n\n if (command_line.HasSwitch(switches::kEnableWebVR)) {\n WebRuntimeFeatures::enableWebVR(true);\n WebRuntimeFeatures::enableFeatureFromString(\"GeometryInterfaces\", true);\n }\n\n \/\/ Enable explicitly enabled features, and then disable explicitly disabled\n \/\/ ones.\n if (command_line.HasSwitch(switches::kEnableBlinkFeatures)) {\n std::vector<std::string> enabled_features;\n base::SplitString(\n command_line.GetSwitchValueASCII(switches::kEnableBlinkFeatures), ',',\n &enabled_features);\n for (const std::string& feature : enabled_features) {\n WebRuntimeFeatures::enableFeatureFromString(\n blink::WebString::fromLatin1(feature), true);\n }\n }\n if (command_line.HasSwitch(switches::kDisableBlinkFeatures)) {\n std::vector<std::string> disabled_features;\n base::SplitString(\n command_line.GetSwitchValueASCII(switches::kDisableBlinkFeatures), ',',\n &disabled_features);\n for (const std::string& feature : disabled_features) {\n WebRuntimeFeatures::enableFeatureFromString(\n blink::WebString::fromLatin1(feature), false);\n }\n }\n}\n\n} \/\/ namespace content\n<commit_msg>[Android] Allow constructor of Notifications on Android.<commit_after>\/\/ Copyright 2013 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 \"content\/child\/runtime_features.h\"\n\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"components\/scheduler\/common\/scheduler_switches.h\"\n#include \"content\/common\/content_switches_internal.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"third_party\/WebKit\/public\/web\/WebRuntimeFeatures.h\"\n#include \"ui\/gl\/gl_switches.h\"\n#include \"ui\/native_theme\/native_theme_switches.h\"\n\n#if defined(OS_ANDROID)\n#include <cpu-features.h>\n#include \"base\/android\/build_info.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"media\/base\/android\/media_codec_bridge.h\"\n#elif defined(OS_WIN)\n#include \"base\/win\/windows_version.h\"\n#endif\n\nusing blink::WebRuntimeFeatures;\n\nnamespace content {\n\nstatic void SetRuntimeFeatureDefaultsForPlatform() {\n \/\/ Enable non-standard \"apple-touch-icon\" and \"apple-touch-icon-precomposed\".\n WebRuntimeFeatures::enableTouchIconLoading(true);\n\n#if defined(OS_ANDROID)\n \/\/ MSE\/EME implementation needs Android MediaCodec API.\n if (!media::MediaCodecBridge::IsAvailable()) {\n WebRuntimeFeatures::enableMediaSource(false);\n WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);\n WebRuntimeFeatures::enableEncryptedMedia(false);\n }\n \/\/ WebAudio is enabled by default but only when the MediaCodec API\n \/\/ is available.\n AndroidCpuFamily cpu_family = android_getCpuFamily();\n WebRuntimeFeatures::enableWebAudio(\n media::MediaCodecBridge::IsAvailable() &&\n ((cpu_family == ANDROID_CPU_FAMILY_ARM) ||\n (cpu_family == ANDROID_CPU_FAMILY_ARM64) ||\n (cpu_family == ANDROID_CPU_FAMILY_X86) ||\n (cpu_family == ANDROID_CPU_FAMILY_MIPS)));\n\n \/\/ Android does not have support for PagePopup\n WebRuntimeFeatures::enablePagePopup(false);\n \/\/ Android does not yet support SharedWorker. crbug.com\/154571\n WebRuntimeFeatures::enableSharedWorker(false);\n \/\/ Android does not yet support NavigatorContentUtils.\n WebRuntimeFeatures::enableNavigatorContentUtils(false);\n WebRuntimeFeatures::enableOrientationEvent(true);\n WebRuntimeFeatures::enableFastMobileScrolling(true);\n WebRuntimeFeatures::enableMediaCapture(true);\n WebRuntimeFeatures::enableCompositedSelectionUpdate(true);\n#else\n WebRuntimeFeatures::enableNavigatorContentUtils(true);\n#endif \/\/ defined(OS_ANDROID)\n\n#if !(defined OS_ANDROID || defined OS_CHROMEOS || defined OS_IOS)\n \/\/ Only Android, ChromeOS, and IOS support NetInfo right now.\n WebRuntimeFeatures::enableNetworkInformation(false);\n#endif\n\n#if defined(OS_WIN)\n \/\/ Screen Orientation API is currently broken on Windows 8 Metro mode and\n \/\/ until we can find how to disable it only for Blink instances running in a\n \/\/ renderer process in Metro, we need to disable the API altogether for Win8.\n \/\/ See http:\/\/crbug.com\/400846\n if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_WIN8)\n WebRuntimeFeatures::enableScreenOrientation(false);\n#endif \/\/ OS_WIN\n}\n\nvoid SetRuntimeFeaturesDefaultsAndUpdateFromArgs(\n const base::CommandLine& command_line) {\n if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures))\n WebRuntimeFeatures::enableExperimentalFeatures(true);\n\n if (command_line.HasSwitch(switches::kEnableWebBluetooth))\n WebRuntimeFeatures::enableWebBluetooth(true);\n\n SetRuntimeFeatureDefaultsForPlatform();\n\n if (command_line.HasSwitch(switches::kDisableDatabases))\n WebRuntimeFeatures::enableDatabase(false);\n\n if (command_line.HasSwitch(scheduler::switches::kDisableBlinkScheduler))\n WebRuntimeFeatures::enableBlinkScheduler(false);\n\n if (command_line.HasSwitch(switches::kDisableMediaSource))\n WebRuntimeFeatures::enableMediaSource(false);\n\n if (command_line.HasSwitch(switches::kDisableNotifications)) {\n WebRuntimeFeatures::enableNotifications(false);\n\n \/\/ Chrome's Push Messaging implementation relies on Web Notifications.\n WebRuntimeFeatures::enablePushMessaging(false);\n }\n\n if (command_line.HasSwitch(switches::kDisableSharedWorkers))\n WebRuntimeFeatures::enableSharedWorker(false);\n\n#if defined(OS_ANDROID)\n \/\/ WebAudio is enabled by default on ARM and X86, if the MediaCodec\n \/\/ API is available.\n WebRuntimeFeatures::enableWebAudio(\n !command_line.HasSwitch(switches::kDisableWebAudio) &&\n media::MediaCodecBridge::IsAvailable());\n#else\n if (command_line.HasSwitch(switches::kDisableWebAudio))\n WebRuntimeFeatures::enableWebAudio(false);\n#endif\n\n if (command_line.HasSwitch(switches::kDisableSpeechAPI))\n WebRuntimeFeatures::enableScriptedSpeech(false);\n\n if (command_line.HasSwitch(switches::kDisableEncryptedMedia))\n WebRuntimeFeatures::enableEncryptedMedia(false);\n\n if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia))\n WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);\n\n if (command_line.HasSwitch(switches::kDisableFileSystem))\n WebRuntimeFeatures::enableFileSystem(false);\n\n if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))\n WebRuntimeFeatures::enableExperimentalCanvasFeatures(true);\n\n if (!command_line.HasSwitch(switches::kDisableAcceleratedJpegDecoding))\n WebRuntimeFeatures::enableDecodeToYUV(true);\n\n if (command_line.HasSwitch(switches::kEnableDisplayList2dCanvas))\n WebRuntimeFeatures::enableDisplayList2dCanvas(true);\n\n if (command_line.HasSwitch(switches::kDisableDisplayList2dCanvas))\n WebRuntimeFeatures::enableDisplayList2dCanvas(false);\n\n if (command_line.HasSwitch(switches::kForceDisplayList2dCanvas))\n WebRuntimeFeatures::forceDisplayList2dCanvas(true);\n\n if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))\n WebRuntimeFeatures::enableWebGLDraftExtensions(true);\n\n if (command_line.HasSwitch(switches::kEnableWebGLImageChromium))\n WebRuntimeFeatures::enableWebGLImageChromium(true);\n\n if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo))\n WebRuntimeFeatures::enableOverlayFullscreenVideo(true);\n\n if (ui::IsOverlayScrollbarEnabled())\n WebRuntimeFeatures::enableOverlayScrollbars(true);\n\n if (command_line.HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths))\n WebRuntimeFeatures::enableBleedingEdgeFastPaths(true);\n\n if (command_line.HasSwitch(switches::kEnablePreciseMemoryInfo))\n WebRuntimeFeatures::enablePreciseMemoryInfo(true);\n\n if (command_line.HasSwitch(switches::kEnableNetworkInformation) ||\n command_line.HasSwitch(\n switches::kEnableExperimentalWebPlatformFeatures)) {\n WebRuntimeFeatures::enableNetworkInformation(true);\n }\n\n if (command_line.HasSwitch(switches::kEnableCredentialManagerAPI))\n WebRuntimeFeatures::enableCredentialManagerAPI(true);\n\n if (command_line.HasSwitch(switches::kDisableSVG1DOM)) {\n WebRuntimeFeatures::enableSVG1DOM(false);\n }\n\n if (command_line.HasSwitch(switches::kReducedReferrerGranularity))\n WebRuntimeFeatures::enableReducedReferrerGranularity(true);\n\n if (command_line.HasSwitch(switches::kEnablePushMessagePayload))\n WebRuntimeFeatures::enablePushMessagingData(true);\n\n if (command_line.HasSwitch(switches::kDisablePermissionsAPI))\n WebRuntimeFeatures::enablePermissionsAPI(false);\n\n \/\/ Delete \"StaleWhileRevalidate\" line from chrome_browser_field_trials.cc\n \/\/ when this experiment is done.\n if (base::FieldTrialList::FindFullName(\"StaleWhileRevalidate\") == \"Enabled\" ||\n command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))\n WebRuntimeFeatures::enableStaleWhileRevalidateCacheControl(true);\n\n if (command_line.HasSwitch(switches::kDisableV8IdleTasks))\n WebRuntimeFeatures::enableV8IdleTasks(false);\n else\n WebRuntimeFeatures::enableV8IdleTasks(true);\n\n if (command_line.HasSwitch(switches::kEnableUnsafeES3APIs))\n WebRuntimeFeatures::enableUnsafeES3APIs(true);\n\n if (command_line.HasSwitch(switches::kEnableWebVR)) {\n WebRuntimeFeatures::enableWebVR(true);\n WebRuntimeFeatures::enableFeatureFromString(\"GeometryInterfaces\", true);\n }\n\n \/\/ Enable explicitly enabled features, and then disable explicitly disabled\n \/\/ ones.\n if (command_line.HasSwitch(switches::kEnableBlinkFeatures)) {\n std::vector<std::string> enabled_features;\n base::SplitString(\n command_line.GetSwitchValueASCII(switches::kEnableBlinkFeatures), ',',\n &enabled_features);\n for (const std::string& feature : enabled_features) {\n WebRuntimeFeatures::enableFeatureFromString(\n blink::WebString::fromLatin1(feature), true);\n }\n }\n if (command_line.HasSwitch(switches::kDisableBlinkFeatures)) {\n std::vector<std::string> disabled_features;\n base::SplitString(\n command_line.GetSwitchValueASCII(switches::kDisableBlinkFeatures), ',',\n &disabled_features);\n for (const std::string& feature : disabled_features) {\n WebRuntimeFeatures::enableFeatureFromString(\n blink::WebString::fromLatin1(feature), false);\n }\n }\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2020 The TensorFlow Runtime Authors\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\/\/ Implementation of the MIOpen API forwarding calls to symbols dynamically\n\/\/ loaded from the real library.\n#include \"tfrt\/gpu\/wrapper\/miopen_stub.h\"\n\n#include \"symbol_loader.h\"\n\n\/\/ Memoizes load of the .so for this ROCm library.\nstatic void *LoadSymbol(const char *symbol_name) {\n static SymbolLoader loader(\"libmiopen.so\");\n return loader.GetAddressOfSymbol(symbol_name);\n}\n\ntemplate <typename Func>\nstatic Func *GetFunctionPointer(const char *symbol_name, Func *func = nullptr) {\n return reinterpret_cast<Func *>(LoadSymbol(symbol_name));\n}\n\n\/\/ Calls function 'symbol_name' in shared library with 'args'.\n\/\/ TODO(csigg): Change to 'auto Func' when C++17 is allowed.\ntemplate <typename Func, Func *, typename... Args>\nstatic miopenStatus_t DynamicCall(const char *symbol_name, Args &&...args) {\n static auto func_ptr = GetFunctionPointer<Func>(symbol_name);\n if (!func_ptr) return miopenStatusNotInitialized;\n return func_ptr(std::forward<Args>(args)...);\n}\n\nextern \"C\" {\n#include \"miopen_stub.cc.inc\"\n}\n\n\/\/ The functions below have a different return type and therefore don't fit\n\/\/ the code generator patterns.\n\nconst char *miopenGetErrorString(miopenStatus_t error) {\n static auto func_ptr =\n GetFunctionPointer(\"miopenGetErrorString\", miopenGetErrorString);\n if (!func_ptr) return \"FAILED_TO_LOAD_FUNCTION_SYMBOL\";\n return func_ptr(error);\n}\n<commit_msg>Correct the name of the MIOpen library in miopen_stub.cc<commit_after>\/\/ Copyright 2020 The TensorFlow Runtime Authors\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\/\/ Implementation of the MIOpen API forwarding calls to symbols dynamically\n\/\/ loaded from the real library.\n#include \"tfrt\/gpu\/wrapper\/miopen_stub.h\"\n\n#include \"symbol_loader.h\"\n\n\/\/ Memoizes load of the .so for this ROCm library.\nstatic void *LoadSymbol(const char *symbol_name) {\n static SymbolLoader loader(\"libMIOpen.so\");\n return loader.GetAddressOfSymbol(symbol_name);\n}\n\ntemplate <typename Func>\nstatic Func *GetFunctionPointer(const char *symbol_name, Func *func = nullptr) {\n return reinterpret_cast<Func *>(LoadSymbol(symbol_name));\n}\n\n\/\/ Calls function 'symbol_name' in shared library with 'args'.\n\/\/ TODO(csigg): Change to 'auto Func' when C++17 is allowed.\ntemplate <typename Func, Func *, typename... Args>\nstatic miopenStatus_t DynamicCall(const char *symbol_name, Args &&...args) {\n static auto func_ptr = GetFunctionPointer<Func>(symbol_name);\n if (!func_ptr) return miopenStatusNotInitialized;\n return func_ptr(std::forward<Args>(args)...);\n}\n\nextern \"C\" {\n#include \"miopen_stub.cc.inc\"\n}\n\n\/\/ The functions below have a different return type and therefore don't fit\n\/\/ the code generator patterns.\n\nconst char *miopenGetErrorString(miopenStatus_t error) {\n static auto func_ptr =\n GetFunctionPointer(\"miopenGetErrorString\", miopenGetErrorString);\n if (!func_ptr) return \"FAILED_TO_LOAD_FUNCTION_SYMBOL\";\n return func_ptr(error);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dhash.h\"\n#include \"ddns.h\"\n#include <iostream>\n\n#define nelem(a) (sizeof(a)\/sizeof((a)[0]))\n#define nil 0\n\nptr<ddns> ddns_clnt;\n\nstatic int\nsplitfields(char *s, char **f, int mf, int sep)\n{\n char *p;\n int infield, nf;\n \n infield = 0;\n nf = 0;\n for(p=s; *p; p++){\n if(*p == sep){\n *p = '\\0';\n infield = 0;\n }else if(!infield){\n f[nf++] = p;\n if(nf >= mf)\n return nf;\n infield = 1;\n }\n }\n return nf;\n}\n\nstatic int\nmkaddress(unsigned char *a, char *s)\n{\n char *f[5];\n int i, nf;\n\t\n nf = splitfields(s, f, nelem(f), '.');\n if(nf != 4){\n cerr << \"bad ip address format\";\n return -1;\n }\n for(i=0; i<4; i++)\n a[i] = atoi(f[i]);\n return 0;\n}\n\t\nstatic ptr<ddnsRR>\nmkrr(char *name, dns_type t, int nval, char **val)\n{\n char *f[10];\n int nf, i;\n ptr<ddnsRR> *last, rr, rrlist;\n\n rrlist = nil;\n last = &rrlist;\n\t\n for(i=0; i<nval; i++){\n\trr = New refcounted<ddnsRR>;\n\trr->dname = strdup(name);\n\trr->type = t;\n\tswitch(t){\n\tcase A:\n\t rr->rdlength = 4;\n\t if(mkaddress(rr->rdata.address, val[i]) < 0)\n\t return nil;\n\t break;\n\tcase NS:\n\tcase CNAME:\n\tcase MD:\n\tcase MF:\n\tcase MG:\n\tcase MR:\n\tcase PTR:\n\tdefault:\n\t rr->rdata.hostname = strdup(val[i]);\n\t rr->rdlength = strlen(val[i])+1;\n\t break;\n\tcase SOA:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 7){\n\t cerr << \"soa format: mname;rname;serial;refresh;retry;expire;minttl\";\n\t return nil;\n\t }\n\t rr->rdata.soa.mname = strdup(f[0]);\n\t rr->rdata.soa.rname = strdup(f[1]);\n\t rr->rdata.soa.serial = atoi(f[2]);\n\t rr->rdata.soa.refresh = atoi(f[3]);\n\t rr->rdata.soa.retry = atoi(f[4]);\n\t rr->rdata.soa.expire = atoi(f[5]);\n\t rr->rdata.soa.minttl = atoi(f[6]);\n rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1 + 5*4;\n break;\n case WKS:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 3){\n\t cerr << \"wks format: ipaddress;protocol\";\n\t return nil;\n\t }\n if(mkaddress(rr->rdata.wks.address, f[0]) < 0)\n return nil;\n rr->rdata.wks.protocol = atoi(f[1]);\n rr->rdata.wks.bitmap = (char*)malloc(8);\n strcpy(rr->rdata.wks.bitmap, \"Athicha!\");\n rr->rdlength = 4+4+9;\n break;\n case HINFO:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 2){\n\t cerr << \"hinfo format: cpu;os\";\n\t return nil;\n\t }\n\t rr->rdata.hinfo.cpu = strdup(f[0]);\n\t rr->rdata.hinfo.os = strdup(f[1]);\n\t rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1;\n\t break;\n\tcase MINFO:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 2){\n\t cerr << \"minfo format: rmailbx;emailbx\";\n\t return nil;\n\t }\n\t rr->rdata.minfo.rmailbx = strdup(f[0]);\n\t rr->rdata.minfo.emailbx = strdup(f[1]);\n\t rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1;\n\t break;\n case MX:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 2){\n\t cerr << \"mx format: pref;exchange\";\n\t return nil;\n\t }\n\t rr->rdata.mx.pref = atoi(f[0]);\n\t rr->rdata.mx.exchange = strdup(f[1]);\n\t rr->rdlength = 4 + strlen(f[1])+1;\n\t break;\n\tcase TXT:\n\t rr->rdata.txt_data = strdup(val[i]);\n\t rr->rdlength = strlen(val[i])+1;\n\t break;\n case DNULL:\n break;\n\t}\n\t*last = rr;\n\tlast = &rr->next;\n }\n return rrlist;\n}\n\nstatic char*\ncmdinsert(int argc, char **argv)\n{\n if(argc < 3)\n return \"usage: insert name type val...\";\n\n ptr<ddnsRR> rr = mkrr(strdup(argv[0]), get_dtype(argv[1]), argc-2, &argv[2]);\n if(rr == nil)\n return \"parse error\";\n ddns_clnt->store(strdup(argv[0]), rr);\n return nil;\n}\n\nstatic char*\ncmddelete(int, char**)\n{\n return \"delete not implemented\";\n}\n\nstatic char*\ntypestr(dns_type t)\n{\n static char buf[20];\n \n switch(t){\n case A:\n return \"a\";\n case NS:\n return \"ns\";\n case CNAME:\n return \"cname\";\n case MD:\n return \"md\";\n case MF:\n return \"mf\";\n case MB:\n return \"mb\";\n case MG:\n return \"mg\";\n case MR:\n return \"mr\";\n case PTR:\n return \"ptr\";\n case SOA:\n return \"soa\";\n default:\n snprintf(buf, sizeof buf, \"dnstype%d\", t);\n return buf;\n }\n}\n\nstatic void\nprintrr(ptr<ddnsRR> rr)\n{\n unsigned char *a;\n\n cout << rr->dname << \" \" << typestr(rr->type);\n for(; rr; rr=rr->next){\n cout << \" \";\n switch(rr->type){\n case A:\n a = rr->rdata.address;\n cout << (int)a[0] << \".\" << (int)a[1] << \".\" << (int)a[2] << \".\" << (int)a[3];\n break;\n case NS:\n case CNAME:\n case MD:\n case MF:\n case MB:\n case MG:\n case MR:\n case PTR:\n cout << rr->rdata.hostname;\n break;\n case SOA:\n cout << rr->rdata.soa.mname << \";\";\n cout << rr->rdata.soa.rname << \";\";\n cout << rr->rdata.soa.serial << \";\";\n cout << rr->rdata.soa.refresh << \";\";\n cout << rr->rdata.soa.retry << \";\";\n cout << rr->rdata.soa.expire << \";\";\n cout << rr->rdata.soa.minttl;\n break;\n case WKS:\n a = rr->rdata.wks.address;\n cout << (int)a[0] << \".\" << (int)a[1] << \".\" << (int)a[2] << \".\" << (int)a[3] << \";\";\n cout << rr->rdata.wks.protocol << \";\";\n cout << rr->rdata.wks.bitmap;\n break;\n case HINFO:\n cout << rr->rdata.hinfo.cpu << \";\" << rr->rdata.hinfo.os;\n break;\n case MINFO:\n cout << rr->rdata.minfo.rmailbx << \";\" << rr->rdata.minfo.emailbx;\n break;\n case MX:\n cout << rr->rdata.mx.pref << \";\" << rr->rdata.mx.exchange;\n break;\n case TXT:\n cout << rr->rdata.txt_data;\n break;\n case DNULL:\n break;\n default:\n cout << \"\\tunknown type\\n\";\n break;\n }\n }\n cout << \"\\n\";\n}\n\nstatic char*\ncmdlookup(int argc, char **argv)\n{\n if(argc != 2)\n return \"usage: lookup name type\";\n ddns_clnt->lookup(strdup(argv[0]), get_dtype(argv[1]), wrap(printrr));\n return nil;\n}\n \nstatic struct {\n char *cmd;\n char *(*fn)(int, char**);\n} tab[] = {\n {\"insert\", cmdinsert},\n {\"delete\", cmddelete},\n {\"lookup\", cmdlookup},\n};\n\nstatic void \nusage ()\n{\n warnx << \"usage: ddnscmd\\n\";\n exit (1);\n}\n\nint\nmain (int argc, char **argv)\n{\n char line[256], *err, *f[20];\n int i, nf;\n \n if(argc != 1)\n usage ();\n\t\t\n sfsconst_init ();\n const char *control_socket = \"\/tmp\/chord-sock\";\n ddns_clnt = New refcounted<ddns> (control_socket, 0);\n for(;;){\n cerr << \">>> \";\n cin.getline(line, sizeof line);\n if(cin.eof())\n break;\n nf = splitfields(line, f, nelem(f), ' ');\n if(nf == 0)\n continue;\n for(i=0; i<(int)nelem(tab); i++)\n if(strcmp(tab[i].cmd, f[0]) == 0)\n break;\n if(i==nelem(tab)){\n cerr << \"?unknown command\\n\";\n continue;\n }\n if((err = tab[i].fn(nf-1, f+1)) != nil)\n cerr << \"?\" << err << \"\\n\";\n }\n return 0;\n}\n\n<commit_msg>wks argument count bug fix<commit_after>#include \"dhash.h\"\n#include \"ddns.h\"\n#include <iostream>\n\n#define nelem(a) (sizeof(a)\/sizeof((a)[0]))\n#define nil 0\n\nptr<ddns> ddns_clnt;\n\nstatic int\nsplitfields(char *s, char **f, int mf, int sep)\n{\n char *p;\n int infield, nf;\n \n infield = 0;\n nf = 0;\n for(p=s; *p; p++){\n if(*p == sep){\n *p = '\\0';\n infield = 0;\n }else if(!infield){\n f[nf++] = p;\n if(nf >= mf)\n return nf;\n infield = 1;\n }\n }\n return nf;\n}\n\nstatic int\nmkaddress(unsigned char *a, char *s)\n{\n char *f[5];\n int i, nf;\n\t\n nf = splitfields(s, f, nelem(f), '.');\n if(nf != 4){\n cerr << \"bad ip address format\";\n return -1;\n }\n for(i=0; i<4; i++)\n a[i] = atoi(f[i]);\n return 0;\n}\n\t\nstatic ptr<ddnsRR>\nmkrr(char *name, dns_type t, int nval, char **val)\n{\n char *f[10];\n int nf, i;\n ptr<ddnsRR> *last, rr, rrlist;\n\n rrlist = nil;\n last = &rrlist;\n\t\n for(i=0; i<nval; i++){\n\trr = New refcounted<ddnsRR>;\n\trr->dname = strdup(name);\n\trr->type = t;\n\tswitch(t){\n\tcase A:\n\t rr->rdlength = 4;\n\t if(mkaddress(rr->rdata.address, val[i]) < 0)\n\t return nil;\n\t break;\n\tcase NS:\n\tcase CNAME:\n\tcase MD:\n\tcase MF:\n\tcase MG:\n\tcase MR:\n\tcase PTR:\n\tdefault:\n\t rr->rdata.hostname = strdup(val[i]);\n\t rr->rdlength = strlen(val[i])+1;\n\t break;\n\tcase SOA:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 7){\n\t cerr << \"soa format: mname;rname;serial;refresh;retry;expire;minttl\";\n\t return nil;\n\t }\n\t rr->rdata.soa.mname = strdup(f[0]);\n\t rr->rdata.soa.rname = strdup(f[1]);\n\t rr->rdata.soa.serial = atoi(f[2]);\n\t rr->rdata.soa.refresh = atoi(f[3]);\n\t rr->rdata.soa.retry = atoi(f[4]);\n\t rr->rdata.soa.expire = atoi(f[5]);\n\t rr->rdata.soa.minttl = atoi(f[6]);\n rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1 + 5*4;\n break;\n case WKS:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 2){\n\t cerr << \"wks format: ipaddress;protocol\";\n\t return nil;\n\t }\n if(mkaddress(rr->rdata.wks.address, f[0]) < 0)\n return nil;\n rr->rdata.wks.protocol = atoi(f[1]);\n rr->rdata.wks.bitmap = (char*)malloc(8);\n strcpy(rr->rdata.wks.bitmap, \"Athicha!\");\n rr->rdlength = 4+4+9;\n break;\n case HINFO:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 2){\n\t cerr << \"hinfo format: cpu;os\";\n\t return nil;\n\t }\n\t rr->rdata.hinfo.cpu = strdup(f[0]);\n\t rr->rdata.hinfo.os = strdup(f[1]);\n\t rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1;\n\t break;\n\tcase MINFO:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 2){\n\t cerr << \"minfo format: rmailbx;emailbx\";\n\t return nil;\n\t }\n\t rr->rdata.minfo.rmailbx = strdup(f[0]);\n\t rr->rdata.minfo.emailbx = strdup(f[1]);\n\t rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1;\n\t break;\n case MX:\n\t nf = splitfields(val[i], f, nelem(f), ';');\n\t if(nf != 2){\n\t cerr << \"mx format: pref;exchange\";\n\t return nil;\n\t }\n\t rr->rdata.mx.pref = atoi(f[0]);\n\t rr->rdata.mx.exchange = strdup(f[1]);\n\t rr->rdlength = 4 + strlen(f[1])+1;\n\t break;\n\tcase TXT:\n\t rr->rdata.txt_data = strdup(val[i]);\n\t rr->rdlength = strlen(val[i])+1;\n\t break;\n case DNULL:\n break;\n\t}\n\t*last = rr;\n\tlast = &rr->next;\n }\n return rrlist;\n}\n\nstatic char*\ncmdinsert(int argc, char **argv)\n{\n if(argc < 3)\n return \"usage: insert name type val...\";\n\n ptr<ddnsRR> rr = mkrr(strdup(argv[0]), get_dtype(argv[1]), argc-2, &argv[2]);\n if(rr == nil)\n return \"parse error\";\n ddns_clnt->store(strdup(argv[0]), rr);\n return nil;\n}\n\nstatic char*\ncmddelete(int, char**)\n{\n return \"delete not implemented\";\n}\n\nstatic char*\ntypestr(dns_type t)\n{\n static char buf[20];\n \n switch(t){\n case A:\n return \"a\";\n case NS:\n return \"ns\";\n case CNAME:\n return \"cname\";\n case MD:\n return \"md\";\n case MF:\n return \"mf\";\n case MB:\n return \"mb\";\n case MG:\n return \"mg\";\n case MR:\n return \"mr\";\n case PTR:\n return \"ptr\";\n case SOA:\n return \"soa\";\n default:\n snprintf(buf, sizeof buf, \"dnstype%d\", t);\n return buf;\n }\n}\n\nstatic void\nprintrr(ptr<ddnsRR> rr)\n{\n unsigned char *a;\n\n cout << rr->dname << \" \" << typestr(rr->type);\n for(; rr; rr=rr->next){\n cout << \" \";\n switch(rr->type){\n case A:\n a = rr->rdata.address;\n cout << (int)a[0] << \".\" << (int)a[1] << \".\" << (int)a[2] << \".\" << (int)a[3];\n break;\n case NS:\n case CNAME:\n case MD:\n case MF:\n case MB:\n case MG:\n case MR:\n case PTR:\n cout << rr->rdata.hostname;\n break;\n case SOA:\n cout << rr->rdata.soa.mname << \";\";\n cout << rr->rdata.soa.rname << \";\";\n cout << rr->rdata.soa.serial << \";\";\n cout << rr->rdata.soa.refresh << \";\";\n cout << rr->rdata.soa.retry << \";\";\n cout << rr->rdata.soa.expire << \";\";\n cout << rr->rdata.soa.minttl;\n break;\n case WKS:\n a = rr->rdata.wks.address;\n cout << (int)a[0] << \".\" << (int)a[1] << \".\" << (int)a[2] << \".\" << (int)a[3] << \";\";\n cout << rr->rdata.wks.protocol << \";\";\n cout << rr->rdata.wks.bitmap;\n break;\n case HINFO:\n cout << rr->rdata.hinfo.cpu << \";\" << rr->rdata.hinfo.os;\n break;\n case MINFO:\n cout << rr->rdata.minfo.rmailbx << \";\" << rr->rdata.minfo.emailbx;\n break;\n case MX:\n cout << rr->rdata.mx.pref << \";\" << rr->rdata.mx.exchange;\n break;\n case TXT:\n cout << rr->rdata.txt_data;\n break;\n case DNULL:\n break;\n default:\n cout << \"\\tunknown type\\n\";\n break;\n }\n }\n cout << \"\\n\";\n}\n\nstatic char*\ncmdlookup(int argc, char **argv)\n{\n if(argc != 2)\n return \"usage: lookup name type\";\n ddns_clnt->lookup(strdup(argv[0]), get_dtype(argv[1]), wrap(printrr));\n return nil;\n}\n \nstatic struct {\n char *cmd;\n char *(*fn)(int, char**);\n} tab[] = {\n {\"insert\", cmdinsert},\n {\"delete\", cmddelete},\n {\"lookup\", cmdlookup},\n};\n\nstatic void \nusage ()\n{\n warnx << \"usage: ddnscmd\\n\";\n exit (1);\n}\n\nint\nmain (int argc, char **argv)\n{\n char line[256], *err, *f[20];\n int i, nf;\n \n if(argc != 1)\n usage ();\n\t\t\n sfsconst_init ();\n const char *control_socket = \"\/tmp\/chord-sock\";\n ddns_clnt = New refcounted<ddns> (control_socket, 0);\n for(;;){\n cerr << \">>> \";\n cin.getline(line, sizeof line);\n if(cin.eof())\n break;\n nf = splitfields(line, f, nelem(f), ' ');\n if(nf == 0)\n continue;\n for(i=0; i<(int)nelem(tab); i++)\n if(strcmp(tab[i].cmd, f[0]) == 0)\n break;\n if(i==nelem(tab)){\n cerr << \"?unknown command\\n\";\n continue;\n }\n if((err = tab[i].fn(nf-1, f+1)) != nil)\n cerr << \"?\" << err << \"\\n\";\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n *\/\n#pragma once\n\nnamespace libbirch {\n\/**\n * Shape and layout of an array.\n *\n * @ingroup libbirch\n * \n * @tparam D Number of dimensions.\n *\/\ntemplate<int D>\nclass ArrayShape {\n static_assert(D <= 2, \"arrays support only up to two dimensions\");\n};\n\n\/**\n * Shape and layout of a vector (one-dimensional array).\n *\/\ntemplate<>\nclass ArrayShape<1> {\npublic:\n ArrayShape(const int n = 0, const int inc = 1) :\n n(n),\n inc(inc) {\n \/\/\n }\n\n int64_t size() const {\n return n;\n }\n\n int64_t volume() const {\n return int64_t(inc)*n;\n }\n\n int rows() const {\n return n;\n }\n\n static constexpr int columns() {\n return 1;\n }\n\n int stride() const {\n return inc;\n }\n\n int width() const {\n return 1;\n }\n\n int height() const {\n return n;\n }\n\n bool conforms(const ArrayShape<1>& o) const {\n return n == o.n;\n }\n\n void compact() {\n inc = 1;\n }\n\n template<class T>\n auto slice(T* buffer, const std::pair<int,int>& range) const {\n assert(range.first <= range.second && \"invalid range\");\n assert(1 <= range.first && range.first <= n && \"start of range out of bounds\");\n assert(1 <= range.second && range.second <= n && \"end of range out of bounds\");\n\n using U = typename std::remove_const<T>::type;\n U* buf = const_cast<U*>(buffer);\n\n int i = range.first;\n int len = range.second - range.first + 1;\n\n return Array<U,1>(buf + (i - 1)*int64_t(inc), ArrayShape<1>(len, inc));\n }\n\n template<class T>\n T& slice(T* buffer, const int i) const {\n assert(1 <= i && i <= n && \"index out of bounds\");\n return buffer[(i - 1)*int64_t(inc)];\n }\n\n \/**\n * Compute the 0-based offset to the @p s th element in serial storage\n * order.\n *\n * @param s Serial index, 0-based.\n *\/\n int64_t offset(const int64_t s) const {\n return s*inc;\n }\n\n \/**\n * Compute the 0-based offset to the @p t th element in transpose storage\n * order.\n *\n * @param t Transpose index, 0-based.\n *\/\n int64_t transpose(const int64_t t) const {\n return t*inc;\n }\n\nprivate:\n \/**\n * Number of elements.\n *\/\n int n;\n\n \/**\n * Stride between elements.\n *\/\n int inc;\n};\n\n\/**\n * Shape and layout of a matrix (two-dimensional array) in column-major order.\n *\/\ntemplate<>\nclass ArrayShape<2> {\npublic:\n ArrayShape() :\n m(0),\n n(0),\n ld(0) {\n \/\/\n }\n\n ArrayShape(const int m, const int n) :\n m(m),\n n(n),\n ld(m) {\n \/\/\n }\n\n ArrayShape(const int m, const int n, const int ld) :\n m(m),\n n(n),\n ld(ld) {\n \/\/\n }\n\n int64_t size() const {\n return int64_t(m)*n;\n }\n\n int64_t volume() const {\n return int64_t(ld)*n;\n }\n\n int rows() const {\n return m;\n }\n\n int columns() const {\n return n;\n }\n\n int stride() const {\n return ld;\n }\n\n int width() const {\n return m;\n }\n\n int height() const {\n return n;\n }\n\n bool conforms(const ArrayShape<2>& o) const {\n return m == o.m && n == o.n;\n }\n\n void compact() {\n ld = m;\n }\n\n \/**\n * Compute the 0-based offset to the @p s th element in serial storage\n * order.\n *\n * @param s Serial index, 0-based.\n *\/\n int64_t offset(const int64_t s) const {\n int64_t j = s\/m;\n int64_t i = s - j*m;\n return i + ld*j;\n }\n\n \/**\n * Compute the 0-based offset to the @p t th element in transpose storage\n * order.\n *\n * @param t Transpose index, 0-based.\n *\/\n int64_t transpose(const int64_t t) const {\n int64_t i = t\/n;\n int64_t j = t - i*n;\n return i + ld*j;\n }\n\n template<class T>\n auto slice(T* buffer, const std::pair<int,int>& rows,\n const std::pair<int,int>& cols) const {\n assert(rows.first <= rows.second && \"invalid row range\");\n assert(1 <= rows.first && rows.first <= m && \"start of row range out of bounds\");\n assert(1 <= rows.second && rows.second <= m && \"end of row range out of bounds\");\n\n assert(cols.first <= cols.second && \"invalid column range\");\n assert(1 <= cols.first && cols.first <= n && \"start of column range out of bounds\");\n assert(1 <= cols.second && cols.second <= n && \"end of column range out of bounds\");\n\n using U = typename std::remove_const<T>::type;\n U* buf = const_cast<U*>(buffer);\n\n int i = rows.first;\n int r = rows.second - rows.first + 1;\n int j = cols.first;\n int c = cols.second - cols.first + 1;\n\n return Array<U,2>(buf + (i - 1) + int64_t(ld)*(j - 1),\n ArrayShape<2>(r, c, ld));\n }\n\n template<class T>\n auto slice(T* buffer, const std::pair<int,int>& rows, const int j) const {\n assert(rows.first <= rows.second && \"invalid row range\");\n assert(1 <= rows.first && rows.first <= m && \"start of row range out of bounds\");\n assert(1 <= rows.second && rows.second <= m && \"end of row range out of bounds\");\n\n assert(1 <= j && j <= n && \"column index out of bounds\");\n\n using U = typename std::remove_const<T>::type;\n U* buf = const_cast<U*>(buffer);\n\n int i = rows.first;\n int r = rows.second - rows.first + 1;\n\n return Array<U,1>(buf + (i - 1) + int64_t(ld)*(j - 1),\n ArrayShape<1>(r, 1));\n }\n\n template<class T>\n auto slice(T* buffer, const int i, const std::pair<int,int>& cols) const {\n assert(1 <= i && i <= m && \"row index out of bounds\");\n\n assert(cols.first <= cols.second && \"invalid column range\");\n assert(1 <= cols.first && cols.first <= n && \"start of column range out of bounds\");\n assert(1 <= cols.second && cols.second <= n && \"end of column range out of bounds\");\n\n using U = typename std::remove_const<T>::type;\n U* buf = const_cast<U*>(buffer);\n\n int j = cols.first;\n int c = cols.second - cols.first + 1;\n\n return Array<U,1>(buf + (i - 1) + int64_t(ld)*(j - 1),\n ArrayShape<1>(c, ld));\n }\n\n template<class T>\n T& slice(T* buffer, const int i, const int j) const {\n assert(1 <= i && i <= m && \"row index out of bounds\");\n assert(1 <= j && j <= n && \"column index out of bounds\");\n return buffer[(i - 1) + int64_t(ld)*(j - 1)];\n }\n\nprivate:\n \/**\n * Number of rows.\n *\/\n int m;\n\n \/**\n * Number of columns.\n *\/\n int n;\n\n \/**\n * Stride between columns.\n *\/\n int ld;\n};\n}\n<commit_msg>Updated ranges to permit ending index to be less than starting index, with the interpretation that the range is then of zero length.<commit_after>\/**\n * @file\n *\/\n#pragma once\n\nnamespace libbirch {\n\/**\n * Shape and layout of an array.\n *\n * @ingroup libbirch\n * \n * @tparam D Number of dimensions.\n *\/\ntemplate<int D>\nclass ArrayShape {\n static_assert(D <= 2, \"arrays support only up to two dimensions\");\n};\n\n\/**\n * Shape and layout of a vector (one-dimensional array).\n *\/\ntemplate<>\nclass ArrayShape<1> {\npublic:\n ArrayShape(const int n = 0, const int inc = 1) :\n n(n),\n inc(inc) {\n \/\/\n }\n\n int64_t size() const {\n return n;\n }\n\n int64_t volume() const {\n return int64_t(inc)*n;\n }\n\n int rows() const {\n return n;\n }\n\n static constexpr int columns() {\n return 1;\n }\n\n int stride() const {\n return inc;\n }\n\n int width() const {\n return 1;\n }\n\n int height() const {\n return n;\n }\n\n bool conforms(const ArrayShape<1>& o) const {\n return n == o.n;\n }\n\n void compact() {\n inc = 1;\n }\n\n template<class T>\n auto slice(T* buffer, const std::pair<int,int>& range) const {\n assert(1 <= range.first && range.first <= n && \"start of range out of bounds\");\n assert(range.second <= n && \"end of range out of bounds\");\n\n using U = typename std::remove_const<T>::type;\n U* buf = const_cast<U*>(buffer);\n\n int i = range.first;\n int len = std::max(0, range.second - range.first + 1);\n\n return Array<U,1>(buf + (i - 1)*int64_t(inc), ArrayShape<1>(len, inc));\n }\n\n template<class T>\n T& slice(T* buffer, const int i) const {\n assert(1 <= i && i <= n && \"index out of bounds\");\n return buffer[(i - 1)*int64_t(inc)];\n }\n\n \/**\n * Compute the 0-based offset to the @p s th element in serial storage\n * order.\n *\n * @param s Serial index, 0-based.\n *\/\n int64_t offset(const int64_t s) const {\n return s*inc;\n }\n\n \/**\n * Compute the 0-based offset to the @p t th element in transpose storage\n * order.\n *\n * @param t Transpose index, 0-based.\n *\/\n int64_t transpose(const int64_t t) const {\n return t*inc;\n }\n\nprivate:\n \/**\n * Number of elements.\n *\/\n int n;\n\n \/**\n * Stride between elements.\n *\/\n int inc;\n};\n\n\/**\n * Shape and layout of a matrix (two-dimensional array) in column-major order.\n *\/\ntemplate<>\nclass ArrayShape<2> {\npublic:\n ArrayShape() :\n m(0),\n n(0),\n ld(0) {\n \/\/\n }\n\n ArrayShape(const int m, const int n) :\n m(m),\n n(n),\n ld(m) {\n \/\/\n }\n\n ArrayShape(const int m, const int n, const int ld) :\n m(m),\n n(n),\n ld(ld) {\n \/\/\n }\n\n int64_t size() const {\n return int64_t(m)*n;\n }\n\n int64_t volume() const {\n return int64_t(ld)*n;\n }\n\n int rows() const {\n return m;\n }\n\n int columns() const {\n return n;\n }\n\n int stride() const {\n return ld;\n }\n\n int width() const {\n return m;\n }\n\n int height() const {\n return n;\n }\n\n bool conforms(const ArrayShape<2>& o) const {\n return m == o.m && n == o.n;\n }\n\n void compact() {\n ld = m;\n }\n\n \/**\n * Compute the 0-based offset to the @p s th element in serial storage\n * order.\n *\n * @param s Serial index, 0-based.\n *\/\n int64_t offset(const int64_t s) const {\n int64_t j = s\/m;\n int64_t i = s - j*m;\n return i + ld*j;\n }\n\n \/**\n * Compute the 0-based offset to the @p t th element in transpose storage\n * order.\n *\n * @param t Transpose index, 0-based.\n *\/\n int64_t transpose(const int64_t t) const {\n int64_t i = t\/n;\n int64_t j = t - i*n;\n return i + ld*j;\n }\n\n template<class T>\n auto slice(T* buffer, const std::pair<int,int>& rows,\n const std::pair<int,int>& cols) const {\n assert(1 <= rows.first && rows.first <= m && \"start of row range out of bounds\");\n assert(rows.second <= m && \"end of row range out of bounds\");\n assert(1 <= cols.first && cols.first <= n && \"start of column range out of bounds\");\n assert(cols.second <= n && \"end of column range out of bounds\");\n\n using U = typename std::remove_const<T>::type;\n U* buf = const_cast<U*>(buffer);\n\n int i = rows.first;\n int r = std::max(0, rows.second - rows.first + 1);\n int j = cols.first;\n int c = std::max(0, cols.second - cols.first + 1);\n\n return Array<U,2>(buf + (i - 1) + int64_t(ld)*(j - 1),\n ArrayShape<2>(r, c, ld));\n }\n\n template<class T>\n auto slice(T* buffer, const std::pair<int,int>& rows, const int j) const {\n assert(1 <= rows.first && rows.first <= m && \"start of row range out of bounds\");\n assert(rows.second <= m && \"end of row range out of bounds\");\n assert(1 <= j && j <= n && \"column index out of bounds\");\n\n using U = typename std::remove_const<T>::type;\n U* buf = const_cast<U*>(buffer);\n\n int i = rows.first;\n int r = std::max(0, rows.second - rows.first + 1);\n\n return Array<U,1>(buf + (i - 1) + int64_t(ld)*(j - 1),\n ArrayShape<1>(r, 1));\n }\n\n template<class T>\n auto slice(T* buffer, const int i, const std::pair<int,int>& cols) const {\n assert(1 <= i && i <= m && \"row index out of bounds\");\n assert(1 <= cols.first && cols.first <= n && \"start of column range out of bounds\");\n assert(cols.second <= n && \"end of column range out of bounds\");\n\n using U = typename std::remove_const<T>::type;\n U* buf = const_cast<U*>(buffer);\n\n int j = cols.first;\n int c = std::max(0, cols.second - cols.first + 1);\n\n return Array<U,1>(buf + (i - 1) + int64_t(ld)*(j - 1),\n ArrayShape<1>(c, ld));\n }\n\n template<class T>\n T& slice(T* buffer, const int i, const int j) const {\n assert(1 <= i && i <= m && \"row index out of bounds\");\n assert(1 <= j && j <= n && \"column index out of bounds\");\n return buffer[(i - 1) + int64_t(ld)*(j - 1)];\n }\n\nprivate:\n \/**\n * Number of rows.\n *\/\n int m;\n\n \/**\n * Number of columns.\n *\/\n int n;\n\n \/**\n * Stride between columns.\n *\/\n int ld;\n};\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>0e0d2fc0-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inputbox.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 21:39:07 $\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 _SV_BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_EDIT_HXX \/\/autogen\n#include <vcl\/edit.hxx>\n#endif\n#ifndef _SV_DIALOG_HXX \/\/autogen\n#include <vcl\/dialog.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#include <sbx.hxx>\n#include \"runtime.hxx\"\n#pragma hdrstop\n#include \"stdobj.hxx\"\n#include \"rtlproto.hxx\"\n\nclass SvRTLInputBox : public ModalDialog\n{\n Edit aEdit;\n OKButton aOk;\n CancelButton aCancel;\n FixedText aPromptText;\n String aText;\n\n void PositionDialog( long nXTwips, long nYTwips, const Size& rDlgSize );\n void InitButtons( const Size& rDlgSize );\n void PositionEdit( const Size& rDlgSize );\n void PositionPrompt( const String& rPrompt, const Size& rDlgSize );\n DECL_LINK( OkHdl, Button * );\n DECL_LINK( CancelHdl, Button * );\n\npublic:\n SvRTLInputBox( Window* pParent, const String& rPrompt, const String& rTitle,\n const String& rDefault, long nXTwips = -1, long nYTwips = -1 );\n String GetText() const { return aText; }\n};\n\nSvRTLInputBox::SvRTLInputBox( Window* pParent, const String& rPrompt,\n const String& rTitle, const String& rDefault,\n long nXTwips, long nYTwips ) :\n ModalDialog( pParent,WB_3DLOOK | WB_MOVEABLE | WB_CLOSEABLE ),\n aEdit( this, WB_LEFT | WB_BORDER ),\n aOk( this ), aCancel( this ), aPromptText( this, WB_WORDBREAK )\n{\n SetMapMode( MapMode( MAP_APPFONT ) );\n Size aDlgSizeApp( 280, 80 );\n PositionDialog( nXTwips, nYTwips, aDlgSizeApp );\n InitButtons( aDlgSizeApp );\n PositionEdit( aDlgSizeApp );\n PositionPrompt( rPrompt, aDlgSizeApp );\n aOk.Show();\n aCancel.Show();\n aEdit.Show();\n aPromptText.Show();\n SetText( rTitle );\n Font aFont( GetFont());\n Color aColor( GetBackground().GetColor() );\n aFont.SetFillColor( aColor );\n aEdit.SetFont( aFont );\n aEdit.SetText( rDefault );\n aEdit.SetSelection( Selection( SELECTION_MIN, SELECTION_MAX ) );\n}\n\nvoid SvRTLInputBox::InitButtons( const Size& rDlgSize )\n{\n aOk.SetSizePixel( LogicToPixel( Size( 45, 15) ));\n aCancel.SetSizePixel( LogicToPixel( Size( 45, 15) ));\n Point aPos( rDlgSize.Width()-45-10, 5 );\n aOk.SetPosPixel( LogicToPixel( Point(aPos) ));\n aPos.Y() += 16;\n aCancel.SetPosPixel( LogicToPixel( Point(aPos) ));\n aOk.SetClickHdl(LINK(this,SvRTLInputBox, OkHdl));\n aCancel.SetClickHdl(LINK(this,SvRTLInputBox,CancelHdl));\n}\n\nvoid SvRTLInputBox::PositionDialog(long nXTwips, long nYTwips, const Size& rDlgSize)\n{\n SetSizePixel( LogicToPixel(rDlgSize) );\n if( nXTwips != -1 && nYTwips != -1 )\n {\n Point aDlgPosApp( nXTwips, nYTwips );\n SetPosPixel( LogicToPixel( aDlgPosApp, MAP_TWIP ) );\n }\n}\n\nvoid SvRTLInputBox::PositionEdit( const Size& rDlgSize )\n{\n aEdit.SetPosPixel( LogicToPixel( Point( 5,rDlgSize.Height()-35)));\n aEdit.SetSizePixel( LogicToPixel( Size(rDlgSize.Width()-15,12)));\n}\n\n\nvoid SvRTLInputBox::PositionPrompt(const String& rPrompt,const Size& rDlgSize)\n{\n if ( rPrompt.Len() == 0 )\n return;\n String aText( rPrompt );\n aText.ConvertLineEnd( LINEEND_CR );\n aPromptText.SetPosPixel( LogicToPixel(Point(5,5)));\n aPromptText.SetText( aText );\n Size aSize( rDlgSize );\n aSize.Width() -= 70;\n aSize.Height() -= 50;\n aPromptText.SetSizePixel( LogicToPixel(aSize));\n}\n\n\nIMPL_LINK_INLINE_START( SvRTLInputBox, OkHdl, Button *, pButton )\n{\n aText = aEdit.GetText();\n EndDialog( 1 );\n return 0;\n}\nIMPL_LINK_INLINE_END( SvRTLInputBox, OkHdl, Button *, pButton )\n\nIMPL_LINK_INLINE_START( SvRTLInputBox, CancelHdl, Button *, pButton )\n{\n aText.Erase();\n EndDialog( 0 );\n return 0;\n}\nIMPL_LINK_INLINE_END( SvRTLInputBox, CancelHdl, Button *, pButton )\n\n\n\/\/ *********************************************************************\n\/\/ *********************************************************************\n\/\/ *********************************************************************\n\n\/\/ Syntax: String InputBox( Prompt, [Title], [Default] [, nXpos, nYpos ] )\n\nRTLFUNC(InputBox)\n{\n ULONG nArgCount = rPar.Count();\n if ( nArgCount < 2 )\n StarBASIC::Error( SbERR_BAD_ARGUMENT );\n else\n {\n String aTitle;\n String aDefault;\n INT32 nX = -1, nY = -1; \/\/ zentrieren\n const String& rPrompt = rPar.Get(1)->GetString();\n if ( nArgCount > 2 )\n aTitle = rPar.Get(2)->GetString();\n if ( nArgCount > 3 )\n aDefault = rPar.Get(3)->GetString();\n if ( nArgCount > 4 )\n {\n if ( nArgCount != 6 )\n {\n StarBASIC::Error( SbERR_BAD_ARGUMENT );\n return;\n }\n nX = rPar.Get(4)->GetLong();\n nY = rPar.Get(5)->GetLong();\n }\n SvRTLInputBox *pDlg=new SvRTLInputBox(GetpApp()->GetDefDialogParent(),\n rPrompt,aTitle,aDefault,nX,nY);\n pDlg->Execute();\n rPar.Get(0)->PutString( pDlg->GetText() );\n delete pDlg;\n }\n}\n\n\n\n<commit_msg>INTEGRATION: CWS ab19 (1.5.40); FILE MERGED 2006\/03\/03 10:45:10 ab 1.5.40.2: RESYNC: (1.5-1.6); FILE MERGED 2005\/07\/25 13:18:42 ab 1.5.40.1: #i35478# Check parameter error status for optional parameters<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inputbox.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2006-04-07 14:02:53 $\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 _SV_BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_EDIT_HXX \/\/autogen\n#include <vcl\/edit.hxx>\n#endif\n#ifndef _SV_DIALOG_HXX \/\/autogen\n#include <vcl\/dialog.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#include <sbx.hxx>\n#include \"runtime.hxx\"\n#pragma hdrstop\n#include \"stdobj.hxx\"\n#include \"rtlproto.hxx\"\n\nclass SvRTLInputBox : public ModalDialog\n{\n Edit aEdit;\n OKButton aOk;\n CancelButton aCancel;\n FixedText aPromptText;\n String aText;\n\n void PositionDialog( long nXTwips, long nYTwips, const Size& rDlgSize );\n void InitButtons( const Size& rDlgSize );\n void PositionEdit( const Size& rDlgSize );\n void PositionPrompt( const String& rPrompt, const Size& rDlgSize );\n DECL_LINK( OkHdl, Button * );\n DECL_LINK( CancelHdl, Button * );\n\npublic:\n SvRTLInputBox( Window* pParent, const String& rPrompt, const String& rTitle,\n const String& rDefault, long nXTwips = -1, long nYTwips = -1 );\n String GetText() const { return aText; }\n};\n\nSvRTLInputBox::SvRTLInputBox( Window* pParent, const String& rPrompt,\n const String& rTitle, const String& rDefault,\n long nXTwips, long nYTwips ) :\n ModalDialog( pParent,WB_3DLOOK | WB_MOVEABLE | WB_CLOSEABLE ),\n aEdit( this, WB_LEFT | WB_BORDER ),\n aOk( this ), aCancel( this ), aPromptText( this, WB_WORDBREAK )\n{\n SetMapMode( MapMode( MAP_APPFONT ) );\n Size aDlgSizeApp( 280, 80 );\n PositionDialog( nXTwips, nYTwips, aDlgSizeApp );\n InitButtons( aDlgSizeApp );\n PositionEdit( aDlgSizeApp );\n PositionPrompt( rPrompt, aDlgSizeApp );\n aOk.Show();\n aCancel.Show();\n aEdit.Show();\n aPromptText.Show();\n SetText( rTitle );\n Font aFont( GetFont());\n Color aColor( GetBackground().GetColor() );\n aFont.SetFillColor( aColor );\n aEdit.SetFont( aFont );\n aEdit.SetText( rDefault );\n aEdit.SetSelection( Selection( SELECTION_MIN, SELECTION_MAX ) );\n}\n\nvoid SvRTLInputBox::InitButtons( const Size& rDlgSize )\n{\n aOk.SetSizePixel( LogicToPixel( Size( 45, 15) ));\n aCancel.SetSizePixel( LogicToPixel( Size( 45, 15) ));\n Point aPos( rDlgSize.Width()-45-10, 5 );\n aOk.SetPosPixel( LogicToPixel( Point(aPos) ));\n aPos.Y() += 16;\n aCancel.SetPosPixel( LogicToPixel( Point(aPos) ));\n aOk.SetClickHdl(LINK(this,SvRTLInputBox, OkHdl));\n aCancel.SetClickHdl(LINK(this,SvRTLInputBox,CancelHdl));\n}\n\nvoid SvRTLInputBox::PositionDialog(long nXTwips, long nYTwips, const Size& rDlgSize)\n{\n SetSizePixel( LogicToPixel(rDlgSize) );\n if( nXTwips != -1 && nYTwips != -1 )\n {\n Point aDlgPosApp( nXTwips, nYTwips );\n SetPosPixel( LogicToPixel( aDlgPosApp, MAP_TWIP ) );\n }\n}\n\nvoid SvRTLInputBox::PositionEdit( const Size& rDlgSize )\n{\n aEdit.SetPosPixel( LogicToPixel( Point( 5,rDlgSize.Height()-35)));\n aEdit.SetSizePixel( LogicToPixel( Size(rDlgSize.Width()-15,12)));\n}\n\n\nvoid SvRTLInputBox::PositionPrompt(const String& rPrompt,const Size& rDlgSize)\n{\n if ( rPrompt.Len() == 0 )\n return;\n String aText( rPrompt );\n aText.ConvertLineEnd( LINEEND_CR );\n aPromptText.SetPosPixel( LogicToPixel(Point(5,5)));\n aPromptText.SetText( aText );\n Size aSize( rDlgSize );\n aSize.Width() -= 70;\n aSize.Height() -= 50;\n aPromptText.SetSizePixel( LogicToPixel(aSize));\n}\n\n\nIMPL_LINK_INLINE_START( SvRTLInputBox, OkHdl, Button *, pButton )\n{\n aText = aEdit.GetText();\n EndDialog( 1 );\n return 0;\n}\nIMPL_LINK_INLINE_END( SvRTLInputBox, OkHdl, Button *, pButton )\n\nIMPL_LINK_INLINE_START( SvRTLInputBox, CancelHdl, Button *, pButton )\n{\n aText.Erase();\n EndDialog( 0 );\n return 0;\n}\nIMPL_LINK_INLINE_END( SvRTLInputBox, CancelHdl, Button *, pButton )\n\n\n\/\/ *********************************************************************\n\/\/ *********************************************************************\n\/\/ *********************************************************************\n\n\/\/ Syntax: String InputBox( Prompt, [Title], [Default] [, nXpos, nYpos ] )\n\nRTLFUNC(InputBox)\n{\n ULONG nArgCount = rPar.Count();\n if ( nArgCount < 2 )\n StarBASIC::Error( SbERR_BAD_ARGUMENT );\n else\n {\n String aTitle;\n String aDefault;\n INT32 nX = -1, nY = -1; \/\/ zentrieren\n const String& rPrompt = rPar.Get(1)->GetString();\n if ( nArgCount > 2 && !rPar.Get(2)->IsErr() )\n aTitle = rPar.Get(2)->GetString();\n if ( nArgCount > 3 && !rPar.Get(3)->IsErr() )\n aDefault = rPar.Get(3)->GetString();\n if ( nArgCount > 4 )\n {\n if ( nArgCount != 6 )\n {\n StarBASIC::Error( SbERR_BAD_ARGUMENT );\n return;\n }\n nX = rPar.Get(4)->GetLong();\n nY = rPar.Get(5)->GetLong();\n }\n SvRTLInputBox *pDlg=new SvRTLInputBox(GetpApp()->GetDefDialogParent(),\n rPrompt,aTitle,aDefault,nX,nY);\n pDlg->Execute();\n rPar.Get(0)->PutString( pDlg->GetText() );\n delete pDlg;\n }\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"mrmc.h\"\n#include \"sparfun_util.h\"\n#include \"tsqr_util.h\"\n\nvoid SerialTSQR::collect(typedbytes_opaque& key, std::vector<double>& value) {\n add_row(value);\n if (num_local_rows_ >= num_rows_) {\n hadoop_message(\"about to compress\\n\");\n compress();\n hadoop_message(\"compress appears successful\\n\");\n hadoop_counter(\"compress\", 1);\n }\n}\n\n\/\/ compress the local QR factorization\nvoid SerialTSQR::compress() {\n \/\/ compute a QR factorization\n double t0 = sf_time();\n if (lapack_qr(&local_matrix_[0], num_rows_, num_cols_, num_local_rows_)) {\n double dt = sf_time() - t0;\n hadoop_counter(\"lapack time (millisecs)\", (int) (dt * 1000.));\n } else {\n hadoop_error(\"lapack error\\n\");\n }\n if (num_cols_ < num_local_rows_) {\n num_local_rows_ = num_cols_;\n }\n}\n\n\/\/ Output the matrix with random keys for the rows.\nvoid SerialTSQR::output() {\n compress();\n for (size_t i = 0; i < num_local_rows_; ++i) {\n int rand_int = sf_randint(0, 2000000000);\n out_.write_int(rand_int);\n out_.write_list_start();\n for (size_t j = 0; j < num_cols_; ++j) {\n out_.write_double(local_matrix_[i + j * num_rows_]);\n }\n out_.write_list_end();\n }\n}\n<commit_msg>handle the case where no data is passed to the task<commit_after>#include \"mrmc.h\"\n#include \"sparfun_util.h\"\n#include \"tsqr_util.h\"\n\nvoid SerialTSQR::collect(typedbytes_opaque& key, std::vector<double>& value) {\n add_row(value);\n if (num_local_rows_ >= num_rows_) {\n hadoop_message(\"about to compress\\n\");\n compress();\n hadoop_message(\"compress appears successful\\n\");\n hadoop_counter(\"compress\", 1);\n }\n}\n\n\/\/ compress the local QR factorization\nvoid SerialTSQR::compress() {\n \/\/ compute a QR factorization\n double t0 = sf_time();\n if (lapack_qr(&local_matrix_[0], num_rows_, num_cols_, num_local_rows_)) {\n double dt = sf_time() - t0;\n hadoop_counter(\"lapack time (millisecs)\", (int) (dt * 1000.));\n } else {\n hadoop_error(\"lapack error\\n\");\n }\n if (num_cols_ < num_local_rows_) {\n num_local_rows_ = num_cols_;\n }\n}\n\n\/\/ Output the matrix with random keys for the rows.\nvoid SerialTSQR::output() {\n if (num_cols_ == 0) {\n \/\/ no data was received on this task\n return;\n }\n compress();\n for (size_t i = 0; i < num_local_rows_; ++i) {\n int rand_int = sf_randint(0, 2000000000);\n out_.write_int(rand_int);\n out_.write_list_start();\n for (size_t j = 0; j < num_cols_; ++j) {\n out_.write_double(local_matrix_[i + j * num_rows_]);\n }\n out_.write_list_end();\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>e56e634a-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#include \"randgen.h\"\n\nusing namespace std;\n\ndouble randgen(char rand_type, double para1, double para2)\n{\n switch (rand_type)\n {\n case 'U':\n {\n\tboost::random::uniform_01<boost::mt19937 &> zeroone(rng);\n\treturn zeroone();\n\tbreak;\n }\n case 'N':\n {\n\tdouble mean = para1;\n\tdouble std_dev = para2;\n\tboost::normal_distribution<> nd(mean,std_dev);\n\tboost::variate_generator<boost::mt19937 &,boost::normal_distribution<> > norm_rnd(rng,nd);\n\treturn norm_rnd();\n\tbreak;\n }\n case 'P':\n {\n\tdouble lambda = (para1 == 0? para2:para1);\n\tboost::poisson_distribution<> pd(lambda);\n\tboost::variate_generator<boost::mt19937 &,boost::poisson_distribution<> > poisson_rnd(rng,pd);\n\treturn poisson_rnd();\n\tbreak;\n }\n case 'E':\n {\n\tdouble lambda = (para1 == 0? para2:para1);\n\tboost::exponential_distribution<> expd(lambda);\n\tboost::variate_generator<boost::mt19937 &,boost::exponential_distribution<> > exp_rnd(rng,expd);\n\treturn exp_rnd();\n\tbreak;\n }\n default:\n\t return -9999.0;\n break;\n }\n\t\n\t\/\/ EJF -- return dummy value to avoid warning\n return -9999.0;\n}\n<commit_msg>Remove consecutive `break`s after `return`s<commit_after>#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#include \"randgen.h\"\n\nusing namespace std;\n\ndouble randgen(char rand_type, double para1, double para2)\n{\n switch (rand_type)\n {\n case 'U':\n {\n\tboost::random::uniform_01<boost::mt19937 &> zeroone(rng);\n\treturn zeroone();\n }\n case 'N':\n {\n\tdouble mean = para1;\n\tdouble std_dev = para2;\n\tboost::normal_distribution<> nd(mean,std_dev);\n\tboost::variate_generator<boost::mt19937 &,boost::normal_distribution<> > norm_rnd(rng,nd);\n\treturn norm_rnd();\n }\n case 'P':\n {\n\tdouble lambda = (para1 == 0? para2:para1);\n\tboost::poisson_distribution<> pd(lambda);\n\tboost::variate_generator<boost::mt19937 &,boost::poisson_distribution<> > poisson_rnd(rng,pd);\n\treturn poisson_rnd();\n }\n case 'E':\n {\n\tdouble lambda = (para1 == 0? para2:para1);\n\tboost::exponential_distribution<> expd(lambda);\n\tboost::variate_generator<boost::mt19937 &,boost::exponential_distribution<> > exp_rnd(rng,expd);\n\treturn exp_rnd();\n }\n default:\n\t return -9999.0;\n }\n\t\n\t\/\/ EJF -- return dummy value to avoid warning\n return -9999.0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>8c0a6380-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before>d710556a-2e4d-11e5-9284-b827eb9e62be<commit_msg>d7154d4a-2e4d-11e5-9284-b827eb9e62be<commit_after>d7154d4a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>b3824036-2e4d-11e5-9284-b827eb9e62be<commit_msg>b3873a1e-2e4d-11e5-9284-b827eb9e62be<commit_after>b3873a1e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>#include \"GUI.hpp\"\n#include \"globals.hpp\"\nGUI::GUI()\n{\n\ttimeSprite = new sf::Sprite();\n\ttimeSprite->setTexture(textureManager.timeBarTexture);\n\ttimeSprite->setPosition(10, gridHeight-20);\n\n\tcoinSprite = new sf::Sprite();\n\tcoinSprite->setTexture(textureManager.itemsTexture);\n\tcoinSprite->setTextureRect(sf::IntRect(0,80,16,16));\n\n\tkeySprite = new sf::Sprite();\n\tkeySprite->setTexture(textureManager.itemsTexture);\n\tkeySprite->setTextureRect(sf::IntRect(0,32,16,16));\n\n\ttimeoutClock = sf::Clock();\n\ttimeoutClock.restart();\n\tcoins=0;\n\tkeys=0;\n\tpauseOffset = 0;\n\tloosed = false;\n\tlastEnable = false;\n\tsmallTime = false;\n\tbuffFactor = 20;\n}\nvoid GUI::setTimeout(int seconds)\n{\n\ttimeoutClock.restart();\n\ttimeoutSeconds = seconds;\n\ttimeBuff = 0;\n}\nvoid GUI::setTimebuffFactor(float factor)\n{\n\tbuffFactor = factor;\n}\nvoid GUI::applyTimeBufff(float seconds)\n{\n\ttimeBuff += seconds*buffFactor;\n}\nfloat GUI::timeLeft()\n{\n\tfloat elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff+pauseOffset);\n\tfloat timeLeft = timeoutSeconds - elapsedSeconds;\n\treturn timeLeft < 0 ? 0 : timeLeft;\n}\n\nvoid GUI::update (sf::Time deltaTime) {\n\tif (sceneManager.getCurrentScene().textBox->enabled()){\n\t\tif (!lastEnable)\n\t\t{\n\t\t\tpauseOffset += timeoutClock.getElapsedTime().asSeconds();\n\t\t}\n\t\ttimeoutClock.restart();\n\t\tlastEnable = true;\n\t}\n\telse\n\t{\n\t\tlastEnable = false;\n\t}\n\tsf::Int32 currTime = globalClock.getElapsedTime().asMilliseconds();\n\tfloat elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff+pauseOffset);\n\tfloat progress = 1 - (elapsedSeconds \/ timeoutSeconds);\n\t\/\/TODO: use min, max\n\tif (progress > 1)\n\t{\n\t\tprogress = 1;\n\t}\n\tif (progress <= 0)\n\t{\n\t\tprogress = 0;\n\t\tif (!loosed){\n\t\t\tsceneManager.getCurrentScene().textBox->triggerText(\"loose\");\n\t\t}\n\t\tloosed = true;\n\t\tif (!sceneManager.getCurrentScene().textBox->enabled())\n\t\t{\n\t\t\tsceneManager.restartLevel();\n\t\t}\n\t}\n\tif (progress < 0.3)\n\t{\n\t\tif (!smallTime)\n\t\t{\n\t\t\tsceneManager.getCurrentScene().textBox->triggerText(\"smalltime\");\n\t\t}\n\t\tsmallTime = true;\n\t}\n\tint height = (1 - progress) * (gridHeight);\n\ttimeSprite->setPosition(-15 , height);\n\ttimeSprite->setTextureRect(sf::IntRect(0, int(elapsedSeconds) % 45 + 2 * height, 10, gridHeight - height));\n\twindow.draw(*timeSprite);\n\n\tfor (int i = 0;i < coins;i++)\n\t{\n\t\t\/\/TODO: Draw coins\n\t\tcoinSprite->setPosition(gridWidth, - i * 16);\n\t\twindow.draw(*coinSprite);\n\t}\n\n\tfor (int i = 0;i < keys;i++)\n\t{\n\t\t\/\/TODO: Draw coins\n\t\tkeySprite->setPosition(gridWidth, gridHeight - 42 + i*16);\n\t\twindow.draw(*keySprite);\n\t}\n}\n\nvoid GUI::resetCoins()\n{\n\tcoins = 0;\n}\n\nvoid GUI::addCoins(int amount)\n{\n\tcoins += amount;\n}\n\nvoid GUI::resetKeys()\n{\n\tkeys = 0;\n}\n\nvoid GUI::addKeys(int amount)\n{\n\tkeys += amount;\n}\n<commit_msg>sound wenn Zeit knapp<commit_after>#include \"GUI.hpp\"\n#include \"globals.hpp\"\nGUI::GUI()\n{\n\ttimeSprite = new sf::Sprite();\n\ttimeSprite->setTexture(textureManager.timeBarTexture);\n\ttimeSprite->setPosition(10, gridHeight-20);\n\n\tcoinSprite = new sf::Sprite();\n\tcoinSprite->setTexture(textureManager.itemsTexture);\n\tcoinSprite->setTextureRect(sf::IntRect(0,80,16,16));\n\n\tkeySprite = new sf::Sprite();\n\tkeySprite->setTexture(textureManager.itemsTexture);\n\tkeySprite->setTextureRect(sf::IntRect(0,32,16,16));\n\n\ttimeoutClock = sf::Clock();\n\ttimeoutClock.restart();\n\tcoins=0;\n\tkeys=0;\n\tpauseOffset = 0;\n\tloosed = false;\n\tlastEnable = false;\n\tsmallTime = false;\n\tbuffFactor = 20;\n}\nvoid GUI::setTimeout(int seconds)\n{\n\ttimeoutClock.restart();\n\ttimeoutSeconds = seconds;\n\ttimeBuff = 0;\n}\nvoid GUI::setTimebuffFactor(float factor)\n{\n\tbuffFactor = factor;\n}\nvoid GUI::applyTimeBufff(float seconds)\n{\n\ttimeBuff += seconds*buffFactor;\n}\nfloat GUI::timeLeft()\n{\n\tfloat elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff+pauseOffset);\n\tfloat timeLeft = timeoutSeconds - elapsedSeconds;\n\treturn timeLeft < 0 ? 0 : timeLeft;\n}\n\nvoid GUI::update (sf::Time deltaTime) {\n\tif (sceneManager.getCurrentScene().textBox->enabled()){\n\t\tif (!lastEnable)\n\t\t{\n\t\t\tpauseOffset += timeoutClock.getElapsedTime().asSeconds();\n\t\t}\n\t\ttimeoutClock.restart();\n\t\tlastEnable = true;\n\t}\n\telse\n\t{\n\t\tlastEnable = false;\n\t}\n\tsf::Int32 currTime = globalClock.getElapsedTime().asMilliseconds();\n\tfloat elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff+pauseOffset);\n\tfloat progress = 1 - (elapsedSeconds \/ timeoutSeconds);\n\tif (progress < 0.3 && progress > 0.28) {\n\t\tsoundManager.playSound(\"sound\/timeShort.ogg\");\n\t}\n\t\/\/TODO: use min, max\n\tif (progress > 1)\n\t{\n\t\tprogress = 1;\n\t}\n\tif (progress <= 0)\n\t{\n\t\tprogress = 0;\n\t\tif (!loosed){\n\t\t\tsceneManager.getCurrentScene().textBox->triggerText(\"loose\");\n\t\t}\n\t\tloosed = true;\n\t\tif (!sceneManager.getCurrentScene().textBox->enabled())\n\t\t{\n\t\t\tsceneManager.restartLevel();\n\t\t}\n\t}\n\tif (progress < 0.3)\n\t{\n\t\tif (!smallTime)\n\t\t{\n\t\t\tsceneManager.getCurrentScene().textBox->triggerText(\"smalltime\");\n\t\t}\n\t\tsmallTime = true;\n\t}\n\tint height = (1 - progress) * (gridHeight);\n\ttimeSprite->setPosition(-15 , height);\n\ttimeSprite->setTextureRect(sf::IntRect(0, int(elapsedSeconds) % 45 + 2 * height, 10, gridHeight - height));\n\twindow.draw(*timeSprite);\n\n\tfor (int i = 0;i < coins;i++)\n\t{\n\t\t\/\/TODO: Draw coins\n\t\tcoinSprite->setPosition(gridWidth, - i * 16);\n\t\twindow.draw(*coinSprite);\n\t}\n\n\tfor (int i = 0;i < keys;i++)\n\t{\n\t\t\/\/TODO: Draw coins\n\t\tkeySprite->setPosition(gridWidth, gridHeight - 42 + i*16);\n\t\twindow.draw(*keySprite);\n\t}\n}\n\nvoid GUI::resetCoins()\n{\n\tcoins = 0;\n}\n\nvoid GUI::addCoins(int amount)\n{\n\tcoins += amount;\n}\n\nvoid GUI::resetKeys()\n{\n\tkeys = 0;\n}\n\nvoid GUI::addKeys(int amount)\n{\n\tkeys += amount;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp - Kurento Media Server\n *\n * Copyright (C) 2013 Kurento\n * Contact: Miguel París Díaz <mparisdiaz@gmail.com>\n * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>\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 version 3\n * as published by the Free Software Foundation.\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 <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <signal.h>\n#include <execinfo.h>\n\n#include \"MediaServerServiceHandler.hpp\"\n\n#include <protocol\/TBinaryProtocol.h>\n#include <transport\/TServerSocket.h>\n#include <transport\/TBufferTransports.h>\n#include <server\/TNonblockingServer.h>\n#include <concurrency\/PosixThreadFactory.h>\n#include <concurrency\/ThreadManager.h>\n\n#include \"media_config_loader.hpp\"\n\n#include <glibmm.h>\n#include <fstream>\n\n#include <gst\/gst.h>\n\n#include <version.hpp>\n#include \"log.hpp\"\n\n#define GST_DEFAULT_NAME \"media_server\"\n\nGST_DEBUG_CATEGORY (GST_CAT_DEFAULT);\n\nusing namespace ::apache::thrift;\nusing namespace ::apache::thrift::protocol;\nusing namespace ::apache::thrift::transport;\nusing namespace ::apache::thrift::server;\nusing namespace ::apache::thrift::concurrency;\n\nusing namespace ::kurento;\n\nusing boost::shared_ptr;\nusing ::kurento::MediaServerServiceHandler;\nusing ::Glib::KeyFile;\nusing ::Glib::KeyFileFlags;\n\n#define DEFAULT_CONFIG_FILE \"\/etc\/kurento\/kurento.conf\"\n\n#define MEDIA_SERVER_ADDRESS_KEY \"serverAddress\"\n#define MEDIA_SERVER_SERVICE_PORT_KEY \"serverPort\"\n\nstatic std::string serverAddress;\nstatic gint serverServicePort;\nstatic GstSDPMessage *sdp_message;\nstatic KeyFile configFile;\n\nGlib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (true);\nstatic TNonblockingServer *p_server = NULL;\n\nstatic gchar *conf_file;\n\nstatic GOptionEntry entries[] = {\n {\n \"conf-file\", 'f', 0, G_OPTION_ARG_FILENAME, &conf_file, \"Configuration file\",\n NULL\n },\n {NULL}\n};\n\nstatic void\ncreate_media_server_service ()\n{\n int port;\n port = MEDIA_SERVER_SERVICE_PORT;\n shared_ptr < MediaServerServiceHandler >\n handler (new MediaServerServiceHandler () );\n shared_ptr < TProcessor >\n processor (new MediaServerServiceProcessor (handler) );\n shared_ptr < TProtocolFactory >\n protocolFactory (new TBinaryProtocolFactory () );\n shared_ptr < PosixThreadFactory > threadFactory (new PosixThreadFactory () );\n shared_ptr < ThreadManager > threadManager =\n ThreadManager::newSimpleThreadManager (15);\n threadManager->threadFactory (threadFactory);\n threadManager->start ();\n TNonblockingServer server (processor, protocolFactory, port, threadManager);\n p_server = &server;\n GST_INFO (\"Starting MediaServerService\");\n kill (getppid(), SIGCONT);\n server.serve ();\n GST_INFO (\"MediaServerService stopped finishing thread\");\n throw Glib::Thread::Exit ();\n}\n\nstatic void\ncheck_port (int port)\n{\n if (port <= 0 || port > G_MAXUSHORT)\n throw Glib::KeyFileError (Glib::KeyFileError::PARSE, \"Invalid value\");\n}\n\nstatic void\nset_default_server_config ()\n{\n serverAddress = MEDIA_SERVER_ADDRESS;\n serverServicePort = MEDIA_SERVER_SERVICE_PORT;\n}\n\nstatic void\nload_config (const std::string &file_name)\n{\n gint port;\n GST_INFO (\"Reading configuration from: %s\", file_name.c_str () );\n \/* Try to open de file *\/\n {\n std::ifstream file (file_name);\n\n if (!file) {\n GST_INFO (\"Config file not found, creating a new one\");\n std::ofstream of (file_name);\n }\n }\n\n try {\n if (!configFile.load_from_file (file_name,\n KeyFileFlags::KEY_FILE_KEEP_COMMENTS |\n KeyFileFlags::KEY_FILE_KEEP_TRANSLATIONS) ) {\n GST_WARNING (\"Error loading configuration from %s, loading \"\n \"default server config, but no \"\n \"codecs will be available\", file_name.c_str () );\n set_default_server_config ();\n return;\n }\n } catch (Glib::Error ex) {\n GST_WARNING (\"Error loading configuration: %s\", ex.what ().c_str () );\n GST_WARNING (\"Error loading configuration from %s, loading \"\n \"default server config, but no \"\n \"codecs will be available\", file_name.c_str () );\n set_default_server_config ();\n return;\n }\n\n try {\n serverAddress = configFile.get_string (SERVER_GROUP,\n MEDIA_SERVER_ADDRESS_KEY);\n } catch (Glib::KeyFileError err) {\n GST_INFO (err.what ().c_str () );\n GST_INFO (\"Setting default address\");\n configFile.set_string (SERVER_GROUP, MEDIA_SERVER_ADDRESS_KEY,\n MEDIA_SERVER_ADDRESS);\n serverAddress = MEDIA_SERVER_ADDRESS;\n }\n\n try {\n port = configFile.get_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY);\n check_port (port);\n serverServicePort = port;\n } catch (Glib::KeyFileError err) {\n GST_INFO (err.what ().c_str () );\n GST_INFO (\"Setting default server port\");\n configFile.set_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY,\n MEDIA_SERVER_SERVICE_PORT);\n serverServicePort = MEDIA_SERVER_SERVICE_PORT;\n }\n\n try {\n sdp_message = load_session_descriptor (configFile);\n } catch (Glib::KeyFileError err) {\n GST_WARNING (err.what ().c_str () );\n GST_WARNING (\"Wrong codec configuration, communication won't be possible\");\n }\n\n std::ofstream f (file_name, std::ios::out | std::ios::trunc);\n f << configFile.to_data ();\n f.close ();\n GST_INFO (\"Configuration loaded successfully\");\n GST_DEBUG (\"Final config file:\\n%s\", configFile.to_data ().c_str () );\n}\n\nstatic void\ninitialiseExecutableName (char *exe, int size)\n{\n char link[1024];\n int len;\n snprintf (link, sizeof (link), \"\/proc\/%d\/exe\", getpid () );\n len = readlink (link, exe, size);\n\n if (len == -1) {\n fprintf (stderr, \"ERROR GETTING NAME\\n\");\n exit (1);\n }\n\n exe[len] = '\\0';\n}\n\nstatic const char *\ngetExecutableName ()\n{\n static char *exe = NULL;\n static char aux[1024];\n\n if (exe == NULL) {\n initialiseExecutableName (aux, sizeof (aux) );\n exe = aux;\n }\n\n return exe;\n}\n\nstatic void\nbt_sighandler (int sig, siginfo_t *info, gpointer data)\n{\n void *trace[35];\n char **messages = (char **) NULL;\n int i, trace_size = 0;\n\n\/\/ ucontext_t *uc = (ucontext_t *)data;\n\n \/* Do something useful with siginfo_t *\/\n if (sig == SIGSEGV) {\n printf (\"Got signal %d, faulty address is %p\\n\", sig,\n (gpointer) info->si_addr);\n } else if (sig == SIGKILL || sig == SIGINT) {\n loop->quit ();\n return;\n } else {\n printf (\"Got signal %d\\n\", sig);\n }\n\n trace_size = backtrace (trace, 35);\n \/* overwrite sigaction with caller's address *\/\n \/\/trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP];\n messages = backtrace_symbols (trace, trace_size);\n \/* skip first stack frame (points here) *\/\n g_print (\"\\t[bt] Execution path:\\n\");\n\n for (i = 1; i < trace_size; ++i) {\n g_print (\"\\t[bt] #%d %s\\n\", i, messages[i]);\n char syscom[256];\n gchar **strs;\n const gchar *exe;\n strs = g_strsplit (messages[i], \"(\", 2);\n\n if (strs[1] == NULL)\n exe = getExecutableName ();\n else\n exe = strs[0];\n\n sprintf (syscom, \"echo -n \\\"\\t[bt]\\t\\t\\\"; addr2line %p -s -e %s\",\n trace[i], exe);\n g_strfreev (strs);\n system (syscom);\n }\n\n if (sig == SIGPIPE) {\n GST_DEBUG (\"Ignore sigpipe\");\n } else {\n exit (sig);\n }\n}\n\nint\nmain (int argc, char **argv)\n{\n GError *error = NULL;\n GOptionContext *context;\n struct sigaction sa;\n context = g_option_context_new (\"\");\n g_option_context_add_main_entries (context, entries, NULL);\n g_option_context_add_group (context, gst_init_get_option_group () );\n\n if (!g_option_context_parse (context, &argc, &argv, &error) ) {\n GST_ERROR (\"option parsing failed: %s\\n\", error->message);\n exit (1);\n }\n\n g_option_context_free (context);\n\n gst_init (&argc, &argv);\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n \/* Install our signal handler *\/\n sa.sa_sigaction = \/*(void (*)(int, siginfo*, gpointer)) *\/ bt_sighandler;\n sigemptyset (&sa.sa_mask);\n sa.sa_flags = SA_RESTART | SA_SIGINFO;\n sigaction (SIGSEGV, &sa, NULL);\n sigaction (SIGPIPE, &sa, NULL);\n sigaction (SIGINT, &sa, NULL);\n sigaction (SIGKILL, &sa, NULL);\n Glib::thread_init ();\n GST_INFO (\"Kmsc version: %s\", get_version () );\n\n if (!conf_file)\n load_config (DEFAULT_CONFIG_FILE);\n else\n load_config ( (std::string) conf_file);\n\n sigc::slot < void >ss = sigc::ptr_fun (&create_media_server_service);\n Glib::Thread::create (ss, true); \/* Created thread not used to join\n because of a bug in thrift *\/\n loop->run ();\n\n return 0;\n}\n<commit_msg>Fix bug #552: Exit main loop from main thread's context<commit_after>\/*\n * main.cpp - Kurento Media Server\n *\n * Copyright (C) 2013 Kurento\n * Contact: Miguel París Díaz <mparisdiaz@gmail.com>\n * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>\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 version 3\n * as published by the Free Software Foundation.\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 <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <signal.h>\n#include <execinfo.h>\n\n#include \"MediaServerServiceHandler.hpp\"\n\n#include <protocol\/TBinaryProtocol.h>\n#include <transport\/TServerSocket.h>\n#include <transport\/TBufferTransports.h>\n#include <server\/TNonblockingServer.h>\n#include <concurrency\/PosixThreadFactory.h>\n#include <concurrency\/ThreadManager.h>\n\n#include \"media_config_loader.hpp\"\n\n#include <glibmm.h>\n#include <fstream>\n\n#include <gst\/gst.h>\n\n#include <version.hpp>\n#include \"log.hpp\"\n\n#define GST_DEFAULT_NAME \"media_server\"\n\nGST_DEBUG_CATEGORY (GST_CAT_DEFAULT);\n\nusing namespace ::apache::thrift;\nusing namespace ::apache::thrift::protocol;\nusing namespace ::apache::thrift::transport;\nusing namespace ::apache::thrift::server;\nusing namespace ::apache::thrift::concurrency;\n\nusing namespace ::kurento;\n\nusing boost::shared_ptr;\nusing ::kurento::MediaServerServiceHandler;\nusing ::Glib::KeyFile;\nusing ::Glib::KeyFileFlags;\n\n#define DEFAULT_CONFIG_FILE \"\/etc\/kurento\/kurento.conf\"\n\n#define MEDIA_SERVER_ADDRESS_KEY \"serverAddress\"\n#define MEDIA_SERVER_SERVICE_PORT_KEY \"serverPort\"\n\nstatic std::string serverAddress;\nstatic gint serverServicePort;\nstatic GstSDPMessage *sdp_message;\nstatic KeyFile configFile;\n\nGlib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (true);\nstatic TNonblockingServer *p_server = NULL;\n\nstatic gchar *conf_file;\n\nstatic GOptionEntry entries[] = {\n {\n \"conf-file\", 'f', 0, G_OPTION_ARG_FILENAME, &conf_file, \"Configuration file\",\n NULL\n },\n {NULL}\n};\n\nstatic void\ncreate_media_server_service ()\n{\n int port;\n port = MEDIA_SERVER_SERVICE_PORT;\n shared_ptr < MediaServerServiceHandler >\n handler (new MediaServerServiceHandler () );\n shared_ptr < TProcessor >\n processor (new MediaServerServiceProcessor (handler) );\n shared_ptr < TProtocolFactory >\n protocolFactory (new TBinaryProtocolFactory () );\n shared_ptr < PosixThreadFactory > threadFactory (new PosixThreadFactory () );\n shared_ptr < ThreadManager > threadManager =\n ThreadManager::newSimpleThreadManager (15);\n threadManager->threadFactory (threadFactory);\n threadManager->start ();\n TNonblockingServer server (processor, protocolFactory, port, threadManager);\n p_server = &server;\n GST_INFO (\"Starting MediaServerService\");\n kill (getppid(), SIGCONT);\n server.serve ();\n GST_INFO (\"MediaServerService stopped finishing thread\");\n throw Glib::Thread::Exit ();\n}\n\nstatic void\ncheck_port (int port)\n{\n if (port <= 0 || port > G_MAXUSHORT)\n throw Glib::KeyFileError (Glib::KeyFileError::PARSE, \"Invalid value\");\n}\n\nstatic void\nset_default_server_config ()\n{\n serverAddress = MEDIA_SERVER_ADDRESS;\n serverServicePort = MEDIA_SERVER_SERVICE_PORT;\n}\n\nstatic void\nload_config (const std::string &file_name)\n{\n gint port;\n GST_INFO (\"Reading configuration from: %s\", file_name.c_str () );\n \/* Try to open de file *\/\n {\n std::ifstream file (file_name);\n\n if (!file) {\n GST_INFO (\"Config file not found, creating a new one\");\n std::ofstream of (file_name);\n }\n }\n\n try {\n if (!configFile.load_from_file (file_name,\n KeyFileFlags::KEY_FILE_KEEP_COMMENTS |\n KeyFileFlags::KEY_FILE_KEEP_TRANSLATIONS) ) {\n GST_WARNING (\"Error loading configuration from %s, loading \"\n \"default server config, but no \"\n \"codecs will be available\", file_name.c_str () );\n set_default_server_config ();\n return;\n }\n } catch (Glib::Error ex) {\n GST_WARNING (\"Error loading configuration: %s\", ex.what ().c_str () );\n GST_WARNING (\"Error loading configuration from %s, loading \"\n \"default server config, but no \"\n \"codecs will be available\", file_name.c_str () );\n set_default_server_config ();\n return;\n }\n\n try {\n serverAddress = configFile.get_string (SERVER_GROUP,\n MEDIA_SERVER_ADDRESS_KEY);\n } catch (Glib::KeyFileError err) {\n GST_INFO (err.what ().c_str () );\n GST_INFO (\"Setting default address\");\n configFile.set_string (SERVER_GROUP, MEDIA_SERVER_ADDRESS_KEY,\n MEDIA_SERVER_ADDRESS);\n serverAddress = MEDIA_SERVER_ADDRESS;\n }\n\n try {\n port = configFile.get_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY);\n check_port (port);\n serverServicePort = port;\n } catch (Glib::KeyFileError err) {\n GST_INFO (err.what ().c_str () );\n GST_INFO (\"Setting default server port\");\n configFile.set_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY,\n MEDIA_SERVER_SERVICE_PORT);\n serverServicePort = MEDIA_SERVER_SERVICE_PORT;\n }\n\n try {\n sdp_message = load_session_descriptor (configFile);\n } catch (Glib::KeyFileError err) {\n GST_WARNING (err.what ().c_str () );\n GST_WARNING (\"Wrong codec configuration, communication won't be possible\");\n }\n\n std::ofstream f (file_name, std::ios::out | std::ios::trunc);\n f << configFile.to_data ();\n f.close ();\n GST_INFO (\"Configuration loaded successfully\");\n GST_DEBUG (\"Final config file:\\n%s\", configFile.to_data ().c_str () );\n}\n\nstatic void\ninitialiseExecutableName (char *exe, int size)\n{\n char link[1024];\n int len;\n snprintf (link, sizeof (link), \"\/proc\/%d\/exe\", getpid () );\n len = readlink (link, exe, size);\n\n if (len == -1) {\n fprintf (stderr, \"ERROR GETTING NAME\\n\");\n exit (1);\n }\n\n exe[len] = '\\0';\n}\n\nstatic const char *\ngetExecutableName ()\n{\n static char *exe = NULL;\n static char aux[1024];\n\n if (exe == NULL) {\n initialiseExecutableName (aux, sizeof (aux) );\n exe = aux;\n }\n\n return exe;\n}\n\nstatic bool\nquit_loop ()\n{\n loop->quit ();\n\n return FALSE;\n}\n\nstatic void\nbt_sighandler (int sig, siginfo_t *info, gpointer data)\n{\n void *trace[35];\n char **messages = (char **) NULL;\n int i, trace_size = 0;\n\n\/\/ ucontext_t *uc = (ucontext_t *)data;\n\n \/* Do something useful with siginfo_t *\/\n if (sig == SIGSEGV) {\n printf (\"Got signal %d, faulty address is %p\\n\", sig,\n (gpointer) info->si_addr);\n } else if (sig == SIGKILL || sig == SIGINT) {\n \/* since we connect to a signal handler, asynchronous management might *\/\n \/* might happen so we need to set an idle handler to exit the main loop *\/\n \/* in the mainloop context. *\/\n Glib::RefPtr<Glib::IdleSource> idle_source = Glib::IdleSource::create ();\n idle_source->connect (sigc::ptr_fun (&quit_loop) );\n idle_source->attach (loop->get_context() );\n return;\n } else {\n printf (\"Got signal %d\\n\", sig);\n }\n\n trace_size = backtrace (trace, 35);\n \/* overwrite sigaction with caller's address *\/\n \/\/trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP];\n messages = backtrace_symbols (trace, trace_size);\n \/* skip first stack frame (points here) *\/\n g_print (\"\\t[bt] Execution path:\\n\");\n\n for (i = 1; i < trace_size; ++i) {\n g_print (\"\\t[bt] #%d %s\\n\", i, messages[i]);\n char syscom[256];\n gchar **strs;\n const gchar *exe;\n strs = g_strsplit (messages[i], \"(\", 2);\n\n if (strs[1] == NULL)\n exe = getExecutableName ();\n else\n exe = strs[0];\n\n sprintf (syscom, \"echo -n \\\"\\t[bt]\\t\\t\\\"; addr2line %p -s -e %s\",\n trace[i], exe);\n g_strfreev (strs);\n system (syscom);\n }\n\n if (sig == SIGPIPE) {\n GST_DEBUG (\"Ignore sigpipe\");\n } else {\n exit (sig);\n }\n}\n\nint\nmain (int argc, char **argv)\n{\n GError *error = NULL;\n GOptionContext *context;\n struct sigaction sa;\n context = g_option_context_new (\"\");\n g_option_context_add_main_entries (context, entries, NULL);\n g_option_context_add_group (context, gst_init_get_option_group () );\n\n if (!g_option_context_parse (context, &argc, &argv, &error) ) {\n GST_ERROR (\"option parsing failed: %s\\n\", error->message);\n exit (1);\n }\n\n g_option_context_free (context);\n\n gst_init (&argc, &argv);\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n \/* Install our signal handler *\/\n sa.sa_sigaction = \/*(void (*)(int, siginfo*, gpointer)) *\/ bt_sighandler;\n sigemptyset (&sa.sa_mask);\n sa.sa_flags = SA_RESTART | SA_SIGINFO;\n sigaction (SIGSEGV, &sa, NULL);\n sigaction (SIGPIPE, &sa, NULL);\n sigaction (SIGINT, &sa, NULL);\n sigaction (SIGKILL, &sa, NULL);\n Glib::thread_init ();\n GST_INFO (\"Kmsc version: %s\", get_version () );\n\n if (!conf_file)\n load_config (DEFAULT_CONFIG_FILE);\n else\n load_config ( (std::string) conf_file);\n\n sigc::slot < void >ss = sigc::ptr_fun (&create_media_server_service);\n Glib::Thread::create (ss, true); \/* Created thread not used to join\n because of a bug in thrift *\/\n loop->run ();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"getusername.h\"\n#include <errno.h>\n#include <langinfo.h>\n#include <locale.h>\n#include <unistd.h>\n#include <string>\n\nusing namespace std;\n\nconst string utf8 = \"UTF-8\";\n\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms724432(v=vs.85).aspx\n\/\/ Sets errno to:\n\/\/ ERROR_INVALID_PARAMETER - parameter is not valid\n\/\/ ERROR_BAD_ENVIRONMENT - locale is not UTF-8\n\/\/ ERROR_TOO_MANY_OPEN_FILES - already have the maximum allowed number of open files\n\/\/ ERROR_NO_ASSOCIATION - calling process has no controlling terminal\n\/\/ ERROR_INSUFFICIENT_BUFFER - buffer not large enough to hold username string\n\/\/ ERROR_NO_SUCH_USER - there was no corresponding entry in the utmp-file\n\/\/ ERROR_OUTOFMEMORY - insufficient memory to allocate passwd structure\n\/\/ ERROR_NO_ASSOCIATION - standard input didn't refer to a terminal\n\/\/ ERROR_INVALID_FUNCTION - getlogin_r() returned an unrecognized error code\n\/\/\n\/\/ Returns:\n\/\/ 1 - succeeded\n\/\/ 0 - failed\nBOOL GetUserName(WCHAR_T *lpBuffer, LPDWORD lpnSize)\n{\n\terrno = 0;\n\n\t\/\/ Check parameters\n\tif (!lpBuffer || !lpnSize) {\n\t\terrno = ERROR_INVALID_PARAMETER;\n\t\treturn 0;\n\t}\n\n\t\/\/ Select locale from environment\n\tsetlocale(LC_ALL, \"\");\n\t\/\/ Check that locale is UTF-8\n\tif (nl_langinfo(CODESET) != utf8) {\n\t\terrno = ERROR_BAD_ENVIRONMENT;\n\t\treturn 0;\n\t}\n\n\t\/\/ Get username from system in a thread-safe manner\n\tchar userName[*lpnSize];\n\tint err = getlogin_r(userName, *lpnSize);\n\t\/\/ Map errno to Win32 Error Codes\n\tif (err != 0) {\n\t\tswitch (errno) {\n\t\tcase EMFILE:\n\t\tcase ENFILE:\n\t\t\terrno = ERROR_TOO_MANY_OPEN_FILES;\n\t\t\tbreak;\n\t\tcase ENXIO:\n\t\t\terrno = ERROR_NO_ASSOCIATION;\n\t\t\tbreak;\n\t\tcase ERANGE:\n\t\t\terrno = ERROR_INSUFFICIENT_BUFFER;\n\t\t\tbreak;\n\t\tcase ENOENT:\n\t\t\terrno = ERROR_NO_SUCH_USER;\n\t\t\tbreak;\n\t\tcase ENOMEM:\n\t\t\terrno = ERROR_OUTOFMEMORY;\n\t\t\tbreak;\n\t\tcase ENOTTY:\n\t\t\terrno = ERROR_NO_ASSOCIATION;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terrno = ERROR_INVALID_FUNCTION;\n\t\t}\n\t\treturn 0;\n\t}\n\n\t\/\/ TODO: Convert to char* to wchar* (UTF-8 to UTF-16 LE w\/o BOM)\n\n\t\/\/ Unfortunately codecvt is not yet supported by G++, othwerise:\n\t\/\/ wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> conversion;\n\n\t\/\/ TODO: Use PAL's Unicode converters\n\n\t\/\/ TODO: set the lpnSize to the userName length (see msdn)\n\n\treturn 1;\n}\n\n<commit_msg>Convert get_login_r to UTF-16 and return<commit_after>#include \"getusername.h\"\n#include <errno.h>\n#include <langinfo.h>\n#include <locale.h>\n#include <unistd.h>\n#include <string>\n#include <vector>\n#include <scxcorelib\/scxstrencodingconv.h>\n\nusing std::string;\nusing std::vector;\n\nusing SCXCoreLib::Utf8ToUtf16le;\n\nconst string utf8 = \"UTF-8\";\n\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms724432(v=vs.85).aspx\n\/\/ Sets errno to:\n\/\/ ERROR_INVALID_PARAMETER - parameter is not valid\n\/\/ ERROR_BAD_ENVIRONMENT - locale is not UTF-8\n\/\/ ERROR_TOO_MANY_OPEN_FILES - already have the maximum allowed number of open files\n\/\/ ERROR_NO_ASSOCIATION - calling process has no controlling terminal\n\/\/ ERROR_INSUFFICIENT_BUFFER - buffer not large enough to hold username string\n\/\/ ERROR_NO_SUCH_USER - there was no corresponding entry in the utmp-file\n\/\/ ERROR_OUTOFMEMORY - insufficient memory to allocate passwd structure\n\/\/ ERROR_NO_ASSOCIATION - standard input didn't refer to a terminal\n\/\/ ERROR_INVALID_FUNCTION - getlogin_r() returned an unrecognized error code\n\/\/\n\/\/ Returns:\n\/\/ 1 - succeeded\n\/\/ 0 - failed\nBOOL GetUserName(WCHAR_T *lpBuffer, LPDWORD lpnSize)\n{\n\terrno = 0;\n\n\t\/\/ Check parameters\n\tif (!lpBuffer || !lpnSize) {\n\t\terrno = ERROR_INVALID_PARAMETER;\n\t\treturn 0;\n\t}\n\n\t\/\/ Select locale from environment\n\tsetlocale(LC_ALL, \"\");\n\t\/\/ Check that locale is UTF-8\n\tif (nl_langinfo(CODESET) != utf8) {\n\t\terrno = ERROR_BAD_ENVIRONMENT;\n\t\treturn 0;\n\t}\n\n\t\/\/ Get username from system in a thread-safe manner\n\tchar userName[*lpnSize];\n\tint err = getlogin_r(userName, *lpnSize);\n\t\/\/ Map errno to Win32 Error Codes\n\tif (err != 0) {\n\t\tswitch (errno) {\n\t\tcase EMFILE:\n\t\tcase ENFILE:\n\t\t\terrno = ERROR_TOO_MANY_OPEN_FILES;\n\t\t\tbreak;\n\t\tcase ENXIO:\n\t\t\terrno = ERROR_NO_ASSOCIATION;\n\t\t\tbreak;\n\t\tcase ERANGE:\n\t\t\terrno = ERROR_INSUFFICIENT_BUFFER;\n\t\t\tbreak;\n\t\tcase ENOENT:\n\t\t\terrno = ERROR_NO_SUCH_USER;\n\t\t\tbreak;\n\t\tcase ENOMEM:\n\t\t\terrno = ERROR_OUTOFMEMORY;\n\t\t\tbreak;\n\t\tcase ENOTTY:\n\t\t\terrno = ERROR_NO_ASSOCIATION;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terrno = ERROR_INVALID_FUNCTION;\n\t\t}\n\t\treturn 0;\n\t}\n\n\t\/\/ Convert to char * to WCHAR_T * (UTF-8 to UTF-16 LE w\/o BOM)\n\tstring input = string(userName);\n\tvector<unsigned char> output;\n\tUtf8ToUtf16le(input, output);\n\n\tif (output.size()\/2 + 1 > *lpnSize) {\n\t\terrno = ERROR_INSUFFICIENT_BUFFER;\n\t\treturn 0;\n\t}\n\n\t\/\/ Add two null bytes (because it's UTF-16)\n\toutput.push_back('\\0');\n\toutput.push_back('\\0');\n\n\tmemcpy(lpBuffer, &output[0], output.size());\n\t*lpnSize = output.size()\/2;\n\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>79a79712-2e4d-11e5-9284-b827eb9e62be<commit_msg>79ac8bdc-2e4d-11e5-9284-b827eb9e62be<commit_after>79ac8bdc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>#ifndef JOINT_CPP_STRING_HPP\n#define JOINT_CPP_STRING_HPP\n\n\n#include <algorithm>\n\n#include <joint.cpp\/BytesView.hpp>\n#include <joint.cpp\/detail\/Iterator.hpp>\n\n\nnamespace joint\n{\n\n\tclass Utf32View\n\t{\n\t\ttypedef char Byte;\n\t\ttypedef uint32_t value_type;\n\n\tpublic:\n\t\tclass iterator : public detail::IteratorOps<iterator, value_type, value_type>\n\t\t{\n\t\t\tfriend class Utf32View;\n\t\t\tfriend class detail::IteratorOps<iterator, value_type, value_type>;\n\n\t\tprivate:\n\t\t\tconst Byte* _begin;\n\t\t\tconst Byte* _end;\n\t\t\tconst Byte* _ptr;\n\n\t\tpublic:\n\t\t\titerator() { }\n\n\t\tprotected:\n\t\t\titerator(const Byte* begin, const Byte* end, const Byte* ptr)\n\t\t\t\t: _begin(begin), _end(end), _ptr(ptr)\n\t\t\t{ }\n\n\t\t\tbool Equals(iterator other) const\n\t\t\t{ return _ptr == other._ptr; }\n\n\t\t\tvalue_type Dereference() const\n\t\t\t{\n\t\t\t\tByte firstByte = *_ptr;\n\t\t\t\tvalue_type valueMask = 0x7F;\n\t\t\t\tsize_t len = 0;\n\t\t\t\tfor (; len < 4; ++len)\n\t\t\t\t{\n\t\t\t\t\tif ((firstByte & ~valueMask) != ~valueMask)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tvalueMask >>= 1;\n\t\t\t\t}\n\t\t\t\tlen = std::min(len, size_t(_end - _ptr));\n\n\t\t\t\tvalue_type result = firstByte & valueMask;\n\t\t\t\tfor (size_t i = 1; i < len; ++i)\n\t\t\t\t\tresult = (result << 6) | (*(_ptr + i) & 0x3F);\n\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tvoid Increment()\n\t\t\t{\n\t\t\t\twhile (_ptr < _end && (*(++_ptr) & 0xC0) == 0x80)\n\t\t\t\t{ }\n\t\t\t}\n\n\t\t\tvoid Decrement()\n\t\t\t{\n\t\t\t\twhile (_ptr > _begin && (*(--_ptr) & 0xC0) == 0x80)\n\t\t\t\t{ }\n\t\t\t}\n\t\t};\n\n\t\ttypedef iterator const_iterator;\n\n\tprivate:\n\t\tBytesView _bytes;\n\n\tpublic:\n\t\texplicit Utf32View(BytesView bytes)\n\t\t\t: _bytes(bytes)\n\t\t{ }\n\n\t\tconst_iterator begin() const { return const_iterator(_bytes.begin(), _bytes.end(), _bytes.begin()); }\n\t\tconst_iterator end() const { return const_iterator(_bytes.begin(), _bytes.end(), _bytes.end()); }\n\t};\n\n\tUtf32View::const_iterator begin(const Utf32View& v) { return v.begin(); }\n\tUtf32View::const_iterator end(const Utf32View& v) { return v.end(); }\n\n\n\tnamespace detail\n\t{\n\t\ttemplate < typename String_ >\n\t\tclass StringImpl\n\t\t{\n\t\tpublic:\n\t\t\tBytesView Utf8Bytes() const { return BytesView(Self().Data(), Self().Size()); }\n\t\t\tjoint::Utf32View Utf32View() const { return joint::Utf32View(Utf8Bytes()); }\n\n\t\tprotected:\n\t\t\t~StringImpl() { }\n\n\t\tprivate:\n\t\t\tconst String_& Self() const { return static_cast<const String_&>(*this); }\n\t\t};\n\t}\n\n\n\tclass StringRef : public detail::StringImpl<StringRef>\n\t{\n\t\tfriend class detail::StringImpl<StringRef>;\n\n\tprivate:\n\t\tconst char* _data;\n\t\tsize_t _size;\n\n\tpublic:\n\t\tStringRef(const char* data) \/\/ TODO: is this ok?\n\t\t\t: _data(data), _size(strlen(data) + 1)\n\t\t{ }\n\n\t\tStringRef(const char* data, size_t size)\n\t\t\t: _data(data), _size(size)\n\t\t{ }\n\n\tprotected:\n\t\tconst char* Data() const { return _data; }\n\t\tsize_t Size() const { return _size; }\n\t};\n\n\n\tclass String : public detail::StringImpl<String>\n\t{\n\t\tfriend class detail::StringImpl<String>;\n\n\tprivate:\n\t\tstd::string _storage;\n\n\tpublic:\n\t\tString()\n\t\t{ }\n\n\t\tString(const char* value) \/\/ TODO: is this ok?\n\t\t\t: _storage(value)\n\t\t{ }\n\n\t\texplicit String(StringRef stringRef)\n\t\t\t: _storage(stringRef.Utf8Bytes().data(), stringRef.Utf8Bytes().size())\n\t\t{ }\n\n\t\texplicit String(const std::string& storage)\n\t\t\t: _storage(storage)\n\t\t{ }\n\n\t\tstd::string& Storage() { return _storage; }\n\t\tconst std::string& Storage() const { return _storage; }\n\n\t\toperator StringRef() const\n\t\t{ return StringRef(Utf8Bytes().data(), Utf8Bytes().size()); }\n\n\tprotected:\n\t\tconst char* Data() const { return _storage.c_str(); }\n\t\tsize_t Size() const { return _storage.size() + 1; }\n\t};\n\n\tinline std::ostream& operator<<(std::ostream& s, const String& str)\n\t{ return s << str.Utf8Bytes().data(); }\n\n\ttemplate < typename String1_, typename String2_ >\n\tString operator+(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)\n\t{\n\t\tString result(l.Utf8Bytes().data()); \/\/ TODO: reimplement\n\t\tresult.Storage() += r.Utf8Bytes().data();\n\t\treturn result;\n\t}\n\n\ttemplate < typename String1_, typename String2_ >\n\tbool operator==(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)\n\t{\n\t\tBytesView lb = l.Utf8Bytes();\n\t\tBytesView rb = r.Utf8Bytes();\n\t\treturn strncmp(lb.data(), rb.data(), std::min(lb.size(), rb.size())) == 0;\n\t}\n\n\ttemplate < typename String1_, typename String2_ >\n\tbool operator!=(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)\n\t{ return !(l == r); }\n\n}\n\n#endif\n<commit_msg>Template std::ostream write operator for joint::String<commit_after>#ifndef JOINT_CPP_STRING_HPP\n#define JOINT_CPP_STRING_HPP\n\n\n#include <algorithm>\n\n#include <joint.cpp\/BytesView.hpp>\n#include <joint.cpp\/detail\/Iterator.hpp>\n\n\nnamespace joint\n{\n\n\tclass Utf32View\n\t{\n\t\ttypedef char Byte;\n\t\ttypedef uint32_t value_type;\n\n\tpublic:\n\t\tclass iterator : public detail::IteratorOps<iterator, value_type, value_type>\n\t\t{\n\t\t\tfriend class Utf32View;\n\t\t\tfriend class detail::IteratorOps<iterator, value_type, value_type>;\n\n\t\tprivate:\n\t\t\tconst Byte* _begin;\n\t\t\tconst Byte* _end;\n\t\t\tconst Byte* _ptr;\n\n\t\tpublic:\n\t\t\titerator() { }\n\n\t\tprotected:\n\t\t\titerator(const Byte* begin, const Byte* end, const Byte* ptr)\n\t\t\t\t: _begin(begin), _end(end), _ptr(ptr)\n\t\t\t{ }\n\n\t\t\tbool Equals(iterator other) const\n\t\t\t{ return _ptr == other._ptr; }\n\n\t\t\tvalue_type Dereference() const\n\t\t\t{\n\t\t\t\tByte firstByte = *_ptr;\n\t\t\t\tvalue_type valueMask = 0x7F;\n\t\t\t\tsize_t len = 0;\n\t\t\t\tfor (; len < 4; ++len)\n\t\t\t\t{\n\t\t\t\t\tif ((firstByte & ~valueMask) != ~valueMask)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tvalueMask >>= 1;\n\t\t\t\t}\n\t\t\t\tlen = std::min(len, size_t(_end - _ptr));\n\n\t\t\t\tvalue_type result = firstByte & valueMask;\n\t\t\t\tfor (size_t i = 1; i < len; ++i)\n\t\t\t\t\tresult = (result << 6) | (*(_ptr + i) & 0x3F);\n\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tvoid Increment()\n\t\t\t{\n\t\t\t\twhile (_ptr < _end && (*(++_ptr) & 0xC0) == 0x80)\n\t\t\t\t{ }\n\t\t\t}\n\n\t\t\tvoid Decrement()\n\t\t\t{\n\t\t\t\twhile (_ptr > _begin && (*(--_ptr) & 0xC0) == 0x80)\n\t\t\t\t{ }\n\t\t\t}\n\t\t};\n\n\t\ttypedef iterator const_iterator;\n\n\tprivate:\n\t\tBytesView _bytes;\n\n\tpublic:\n\t\texplicit Utf32View(BytesView bytes)\n\t\t\t: _bytes(bytes)\n\t\t{ }\n\n\t\tconst_iterator begin() const { return const_iterator(_bytes.begin(), _bytes.end(), _bytes.begin()); }\n\t\tconst_iterator end() const { return const_iterator(_bytes.begin(), _bytes.end(), _bytes.end()); }\n\t};\n\n\tUtf32View::const_iterator begin(const Utf32View& v) { return v.begin(); }\n\tUtf32View::const_iterator end(const Utf32View& v) { return v.end(); }\n\n\n\tnamespace detail\n\t{\n\t\ttemplate < typename String_ >\n\t\tclass StringImpl\n\t\t{\n\t\tpublic:\n\t\t\tBytesView Utf8Bytes() const { return BytesView(Self().Data(), Self().Size()); }\n\t\t\tjoint::Utf32View Utf32View() const { return joint::Utf32View(Utf8Bytes()); }\n\n\t\tprotected:\n\t\t\t~StringImpl() { }\n\n\t\tprivate:\n\t\t\tconst String_& Self() const { return static_cast<const String_&>(*this); }\n\t\t};\n\t}\n\n\n\tclass StringRef : public detail::StringImpl<StringRef>\n\t{\n\t\tfriend class detail::StringImpl<StringRef>;\n\n\tprivate:\n\t\tconst char* _data;\n\t\tsize_t _size;\n\n\tpublic:\n\t\tStringRef(const char* data) \/\/ TODO: is this ok?\n\t\t\t: _data(data), _size(strlen(data) + 1)\n\t\t{ }\n\n\t\tStringRef(const char* data, size_t size)\n\t\t\t: _data(data), _size(size)\n\t\t{ }\n\n\tprotected:\n\t\tconst char* Data() const { return _data; }\n\t\tsize_t Size() const { return _size; }\n\t};\n\n\n\tclass String : public detail::StringImpl<String>\n\t{\n\t\tfriend class detail::StringImpl<String>;\n\n\tprivate:\n\t\tstd::string _storage;\n\n\tpublic:\n\t\tString()\n\t\t{ }\n\n\t\tString(const char* value) \/\/ TODO: is this ok?\n\t\t\t: _storage(value)\n\t\t{ }\n\n\t\texplicit String(StringRef stringRef)\n\t\t\t: _storage(stringRef.Utf8Bytes().data(), stringRef.Utf8Bytes().size())\n\t\t{ }\n\n\t\texplicit String(const std::string& storage)\n\t\t\t: _storage(storage)\n\t\t{ }\n\n\t\tstd::string& Storage() { return _storage; }\n\t\tconst std::string& Storage() const { return _storage; }\n\n\t\toperator StringRef() const\n\t\t{ return StringRef(Utf8Bytes().data(), Utf8Bytes().size()); }\n\n\tprotected:\n\t\tconst char* Data() const { return _storage.c_str(); }\n\t\tsize_t Size() const { return _storage.size() + 1; }\n\t};\n\n\ttemplate < typename String_ >\n\tstd::ostream& operator<<(std::ostream& s, const detail::StringImpl<String_>& str)\n\t{ return s << str.Utf8Bytes().data(); }\n\n\ttemplate < typename String1_, typename String2_ >\n\tString operator+(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)\n\t{\n\t\tString result(l.Utf8Bytes().data()); \/\/ TODO: reimplement\n\t\tresult.Storage() += r.Utf8Bytes().data();\n\t\treturn result;\n\t}\n\n\ttemplate < typename String1_, typename String2_ >\n\tbool operator==(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)\n\t{\n\t\tBytesView lb = l.Utf8Bytes();\n\t\tBytesView rb = r.Utf8Bytes();\n\t\treturn strncmp(lb.data(), rb.data(), std::min(lb.size(), rb.size())) == 0;\n\t}\n\n\ttemplate < typename String1_, typename String2_ >\n\tbool operator!=(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)\n\t{ return !(l == r); }\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 BVLC and contributors.\n\/\/\n\/\/ This is a simple script that allows one to quickly test a network whose\n\/\/ structure is specified by text format protocol buffers, and whose parameter\n\/\/ are loaded from a pre-trained network.\n\/\/ Usage:\n\/\/ test_net net_proto pretrained_net_proto iterations [CPU\/GPU]\n\n#include <cuda_runtime.h>\n\n#include <cstring>\n#include <cstdlib>\n#include <vector>\n\n#include \"caffe\/caffe.hpp\"\n\nusing namespace caffe; \/\/ NOLINT(build\/namespaces)\n\nint main(int argc, char** argv) {\n if (argc < 4 || argc > 6) {\n LOG(ERROR) << \"test_net net_proto pretrained_net_proto iterations \"\n << \"[CPU\/GPU] [Device ID]\";\n return 1;\n }\n\n Caffe::set_phase(Caffe::TEST);\n\n if (argc >= 5 && strcmp(argv[4], \"GPU\") == 0) {\n Caffe::set_mode(Caffe::GPU);\n int device_id = 0;\n if (argc == 6) {\n device_id = atoi(argv[5]);\n }\n Caffe::SetDevice(device_id);\n LOG(ERROR) << \"Using GPU #\" << device_id;\n } else {\n LOG(ERROR) << \"Using CPU\";\n Caffe::set_mode(Caffe::CPU);\n }\n\n Net<float> caffe_test_net(argv[1]);\n NetParameter trained_net_param;\n ReadProtoFromBinaryFile(argv[2], &trained_net_param);\n caffe_test_net.CopyTrainedLayersFrom(trained_net_param);\n\n int total_iter = atoi(argv[3]);\n LOG(ERROR) << \"Running \" << total_iter << \" iterations.\";\n\n double test_accuracy = 0;\n for (int i = 0; i < total_iter; ++i) {\n const vector<Blob<float>*>& result = caffe_test_net.ForwardPrefilled();\n test_accuracy += result[0]->cpu_data()[0];\n LOG(ERROR) << \"Batch \" << i << \", accuracy: \" << result[0]->cpu_data()[0];\n }\n test_accuracy \/= total_iter;\n LOG(ERROR) << \"Test accuracy: \" << test_accuracy;\n\n return 0;\n}\n<commit_msg>fix test_net to upgrade params from v0 if needed<commit_after>\/\/ Copyright 2014 BVLC and contributors.\n\/\/\n\/\/ This is a simple script that allows one to quickly test a network whose\n\/\/ structure is specified by text format protocol buffers, and whose parameter\n\/\/ are loaded from a pre-trained network.\n\/\/ Usage:\n\/\/ test_net net_proto pretrained_net_proto iterations [CPU\/GPU]\n\n#include <cuda_runtime.h>\n\n#include <cstring>\n#include <cstdlib>\n#include <vector>\n\n#include \"caffe\/caffe.hpp\"\n\nusing namespace caffe; \/\/ NOLINT(build\/namespaces)\n\nint main(int argc, char** argv) {\n if (argc < 4 || argc > 6) {\n LOG(ERROR) << \"test_net net_proto pretrained_net_proto iterations \"\n << \"[CPU\/GPU] [Device ID]\";\n return 1;\n }\n\n Caffe::set_phase(Caffe::TEST);\n\n if (argc >= 5 && strcmp(argv[4], \"GPU\") == 0) {\n Caffe::set_mode(Caffe::GPU);\n int device_id = 0;\n if (argc == 6) {\n device_id = atoi(argv[5]);\n }\n Caffe::SetDevice(device_id);\n LOG(ERROR) << \"Using GPU #\" << device_id;\n } else {\n LOG(ERROR) << \"Using CPU\";\n Caffe::set_mode(Caffe::CPU);\n }\n\n Net<float> caffe_test_net(argv[1]);\n caffe_test_net.CopyTrainedLayersFrom(argv[2]);\n\n int total_iter = atoi(argv[3]);\n LOG(ERROR) << \"Running \" << total_iter << \" iterations.\";\n\n double test_accuracy = 0;\n for (int i = 0; i < total_iter; ++i) {\n const vector<Blob<float>*>& result = caffe_test_net.ForwardPrefilled();\n test_accuracy += result[0]->cpu_data()[0];\n LOG(ERROR) << \"Batch \" << i << \", accuracy: \" << result[0]->cpu_data()[0];\n }\n test_accuracy \/= total_iter;\n LOG(ERROR) << \"Test accuracy: \" << test_accuracy;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>b28c0158-2e4d-11e5-9284-b827eb9e62be<commit_msg>b290f58c-2e4d-11e5-9284-b827eb9e62be<commit_after>b290f58c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>7a152872-2e4d-11e5-9284-b827eb9e62be<commit_msg>7a1a21f6-2e4d-11e5-9284-b827eb9e62be<commit_after>7a1a21f6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>\/\/ A command-line tool for exercising the CCTZ library.\n\n#include <getopt.h>\n#include <algorithm>\n#include <cctype>\n#include <chrono>\n#include <cstring>\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include \"src\/cctz.h\"\n\n\/\/ Parse() specifiers for command-line time arguments.\nconst char* const kFormats[] = {\n \"%Y %m %d %H %M %E*S\",\n \"%Y - %m - %d T %H : %M : %E*S\",\n \"%Y - %m - %d %H : %M : %E*S\",\n \"%Y - %m - %d T %H : %M\",\n \"%Y - %m - %d %H : %M\",\n \"%Y - %m - %d\",\n \"%a %b %d %H : %M : %E*S %Z %Y\",\n \"%a %e %b %Y %H : %M : %E*S\",\n \"%a %b %e %Y %H : %M : %E*S\",\n \"%e %b %Y %H : %M : %E*S\",\n \"%b %e %Y %H : %M : %E*S\",\n \"%a %e %b %Y %H : %M\",\n \"%a %b %e %Y %H : %M\",\n \"%e %b %Y %H : %M\",\n \"%b %e %Y %H : %M\",\n \"%a %e %b %Y\",\n \"%a %b %e %Y\",\n \"%e %b %Y\",\n \"%b %e %Y\",\n nullptr\n};\n\nbool ParseTimeSpec(const std::string& args, cctz::TimeZone zone,\n cctz::time_point* when) {\n for (const char* const* fmt = kFormats; *fmt != NULL; ++fmt) {\n const std::string format = std::string(*fmt) + \" %Ez\";\n cctz::time_point tp;\n if (cctz::Parse(format, args, zone, &tp)) {\n *when = tp;\n return true;\n }\n }\n return false;\n}\n\nbool ParseBreakdownSpec(const std::string& args, cctz::TimeZone zone,\n cctz::Breakdown* when) {\n const cctz::TimeZone utc = cctz::UTCTimeZone();\n for (const char* const* fmt = kFormats; *fmt != NULL; ++fmt) {\n cctz::time_point tp;\n if (cctz::Parse(*fmt, args, utc, &tp)) {\n *when = cctz::BreakTime(tp, utc);\n return true;\n }\n }\n return false;\n}\n\n\/\/ The FormatTime() specifier for output.\nconst char* const kFormat = \"%Y-%m-%d %H:%M:%S %Ez (%Z)\";\n\nconst char* const kWeekDayNames[] = {\n \"Unused\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"\n};\n\nstd::string FormatTimeInZone(cctz::time_point when, cctz::TimeZone zone) {\n std::ostringstream oss;\n oss << std::setw(33) << std::left << cctz::Format(kFormat, when, zone);\n cctz::Breakdown bd = cctz::BreakTime(when, zone);\n oss << \" [wd=\" << kWeekDayNames[bd.weekday]\n << \" yd=\" << std::setw(3) << std::setfill('0') << bd.yearday\n << \" dst=\" << (bd.is_dst ? 'T' : 'F')\n << \" off=\" << std::showpos << bd.offset << std::noshowpos << \"]\";\n return oss.str();\n}\n\nvoid InstantInfo(const std::string& label, cctz::time_point when,\n cctz::TimeZone zone) {\n const cctz::TimeZone utc = cctz::UTCTimeZone(); \/\/ might == zone\n const std::string time_label = \"time_t\";\n const std::string utc_label = \"UTC\";\n const std::string zone_label = \"in-tz\";\n std::size_t width =\n 2 + std::max(std::max(time_label.size(), utc_label.size()),\n zone_label.size());\n std::cout << label << \" {\\n\";\n std::cout << std::setw(width) << std::right << time_label << \": \";\n std::time_t seconds = std::chrono::system_clock::to_time_t(when);\n std::cout << std::setw(10) << seconds;\n if (seconds >= (1LL << 31)) std::cout << \" [>31b]\";\n std::cout << \"\\n\";\n std::cout << std::setw(width) << std::right << utc_label << \": \";\n std::cout << FormatTimeInZone(when, utc) << \"\\n\";\n std::cout << std::setw(width) << std::right << zone_label << \": \";\n std::cout << FormatTimeInZone(when, zone) << \"\\n\";\n std::cout << \"}\\n\";\n}\n\n\/\/ Report everything we know about a Breakdown (YMDHMS).\nint BreakdownInfo(const cctz::Breakdown& when, cctz::TimeZone zone) {\n cctz::TimeInfo ti =\n cctz::MakeTimeInfo(when.year, when.month, when.day,\n when.hour, when.minute, when.second, zone);\n switch (ti.kind) {\n case cctz::TimeInfo::Kind::UNIQUE: {\n std::cout << \"kind: UNIQUE\\n\";\n InstantInfo(\"when\", ti.pre, zone);\n break;\n }\n case cctz::TimeInfo::Kind::SKIPPED: {\n std::cout << \"kind: SKIPPED\\n\";\n InstantInfo(\"post\", ti.post, zone); \/\/ might == trans-1\n InstantInfo(\"trans-1\", ti.trans - std::chrono::seconds(1), zone);\n InstantInfo(\"trans\", ti.trans, zone);\n InstantInfo(\"pre\", ti.pre, zone); \/\/ might == trans\n break;\n }\n case cctz::TimeInfo::Kind::REPEATED: {\n std::cout << \"kind: REPEATED\\n\";\n InstantInfo(\"pre\", ti.pre, zone); \/\/ might == trans-1\n InstantInfo(\"trans-1\", ti.trans - std::chrono::seconds(1), zone);\n InstantInfo(\"trans\", ti.trans, zone);\n InstantInfo(\"post\", ti.post, zone); \/\/ might == trans\n break;\n }\n }\n return 0;\n}\n\n\/\/ Report everything we know about a time_point.\nint TimeInfo(cctz::time_point when, cctz::TimeZone zone) {\n std::cout << \"kind: UNIQUE\\n\";\n InstantInfo(\"when\", when, zone);\n return 0;\n}\n\nconst char* Basename(const char* p) {\n if (const char* b = strrchr(p, '\/')) return ++b;\n return p;\n}\n\n\/\/ std::regex doesn't work before gcc 4.9.\nbool LooksLikeNegOffset(const char* s) {\n if (s[0] == '-' && std::isdigit(s[1]) && std::isdigit(s[2])) {\n int i = (s[3] == ':') ? 4 : 3;\n if (std::isdigit(s[i]) && std::isdigit(s[i + 1])) {\n return s[i + 2] == '\\0';\n }\n }\n return false;\n}\n\nint main(int argc, char** argv) {\n std::string prog = argv[0] ? Basename(argv[0]) : \"time_tool\";\n\n \/\/ Escape arguments that look like negative offsets so that they\n \/\/ don't look like flags.\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i], \"--\") == 0) break;\n if (LooksLikeNegOffset(argv[i])) {\n char* buf = new char[strlen(argv[i] + 2)];\n buf[0] = ' '; \/\/ will later be ignorned\n strcpy(buf + 1, argv[i]);\n argv[i] = buf;\n }\n }\n\n \/\/ Determine the time zone.\n cctz::TimeZone zone = cctz::LocalTimeZone();\n for (;;) {\n static option opts[] = {\n {\"zone\", required_argument, nullptr, 'z'},\n {nullptr, 0, nullptr, 0},\n };\n int c = getopt_long(argc, argv, \"z:\", opts, nullptr);\n if (c == -1) break;\n switch (c) {\n case 'z':\n if (!cctz::LoadTimeZone(optarg, &zone)) {\n std::cerr << optarg << \": Unrecognized time zone\\n\";\n return 1;\n }\n break;\n default:\n std::cerr << \"Usage: \" << prog << \" [--zone=<zone>] [<time-spec>]\\n\";\n return 1;\n }\n }\n\n \/\/ Determine the time point.\n cctz::time_point tp = std::chrono::system_clock::now();\n std::string args;\n for (int i = optind; i < argc; ++i) {\n if (i != optind) args += \" \";\n args += argv[i];\n }\n std::replace(args.begin(), args.end(), ',', ' ');\n std::replace(args.begin(), args.end(), '\/', '-');\n bool have_time = ParseTimeSpec(args, zone, &tp);\n if (!have_time && !args.empty()) {\n std::string spec = args.substr((args[0] == '@') ? 1 : 0);\n if ((spec.size() > 0 && std::isdigit(spec[0])) ||\n (spec.size() > 1 && spec[0] == '-' && std::isdigit(spec[1]))) {\n std::size_t end;\n const time_t t = std::stoll(spec, &end);\n if (end == spec.size()) {\n tp = std::chrono::system_clock::from_time_t(t);\n have_time = true;\n }\n }\n }\n cctz::Breakdown when = cctz::BreakTime(tp, zone);\n bool have_break_down = !have_time && ParseBreakdownSpec(args, zone, &when);\n\n \/\/ Show results.\n if (have_break_down) return BreakdownInfo(when, zone);\n if (have_time || args.empty()) return TimeInfo(tp, zone);\n\n std::cerr << args << \": Malformed time spec\\n\";\n return 1;\n}\n<commit_msg>Use Format(\"%s\") to display the \"time_t\" value for a time_point.<commit_after>\/\/ A command-line tool for exercising the CCTZ library.\n\n#include <getopt.h>\n#include <algorithm>\n#include <cctype>\n#include <chrono>\n#include <cstring>\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include \"src\/cctz.h\"\n\n\/\/ Parse() specifiers for command-line time arguments.\nconst char* const kFormats[] = {\n \"%Y %m %d %H %M %E*S\",\n \"%Y - %m - %d T %H : %M : %E*S\",\n \"%Y - %m - %d %H : %M : %E*S\",\n \"%Y - %m - %d T %H : %M\",\n \"%Y - %m - %d %H : %M\",\n \"%Y - %m - %d\",\n \"%a %b %d %H : %M : %E*S %Z %Y\",\n \"%a %e %b %Y %H : %M : %E*S\",\n \"%a %b %e %Y %H : %M : %E*S\",\n \"%e %b %Y %H : %M : %E*S\",\n \"%b %e %Y %H : %M : %E*S\",\n \"%a %e %b %Y %H : %M\",\n \"%a %b %e %Y %H : %M\",\n \"%e %b %Y %H : %M\",\n \"%b %e %Y %H : %M\",\n \"%a %e %b %Y\",\n \"%a %b %e %Y\",\n \"%e %b %Y\",\n \"%b %e %Y\",\n nullptr\n};\n\nbool ParseTimeSpec(const std::string& args, cctz::TimeZone zone,\n cctz::time_point* when) {\n for (const char* const* fmt = kFormats; *fmt != NULL; ++fmt) {\n const std::string format = std::string(*fmt) + \" %Ez\";\n cctz::time_point tp;\n if (cctz::Parse(format, args, zone, &tp)) {\n *when = tp;\n return true;\n }\n }\n return false;\n}\n\nbool ParseBreakdownSpec(const std::string& args, cctz::TimeZone zone,\n cctz::Breakdown* when) {\n const cctz::TimeZone utc = cctz::UTCTimeZone();\n for (const char* const* fmt = kFormats; *fmt != NULL; ++fmt) {\n cctz::time_point tp;\n if (cctz::Parse(*fmt, args, utc, &tp)) {\n *when = cctz::BreakTime(tp, utc);\n return true;\n }\n }\n return false;\n}\n\n\/\/ The FormatTime() specifier for output.\nconst char* const kFormat = \"%Y-%m-%d %H:%M:%S %Ez (%Z)\";\n\nconst char* const kWeekDayNames[] = {\n \"Unused\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"\n};\n\nstd::string FormatTimeInZone(cctz::time_point when, cctz::TimeZone zone) {\n std::ostringstream oss;\n oss << std::setw(33) << std::left << cctz::Format(kFormat, when, zone);\n cctz::Breakdown bd = cctz::BreakTime(when, zone);\n oss << \" [wd=\" << kWeekDayNames[bd.weekday]\n << \" yd=\" << std::setw(3) << std::setfill('0') << bd.yearday\n << \" dst=\" << (bd.is_dst ? 'T' : 'F')\n << \" off=\" << std::showpos << bd.offset << std::noshowpos << \"]\";\n return oss.str();\n}\n\nvoid InstantInfo(const std::string& label, cctz::time_point when,\n cctz::TimeZone zone) {\n const cctz::TimeZone utc = cctz::UTCTimeZone(); \/\/ might == zone\n const std::string time_label = \"time_t\";\n const std::string utc_label = \"UTC\";\n const std::string zone_label = \"in-tz\";\n std::size_t width =\n 2 + std::max(std::max(time_label.size(), utc_label.size()),\n zone_label.size());\n std::cout << label << \" {\\n\";\n std::cout << std::setw(width) << std::right << time_label << \": \";\n std::cout << std::setw(10) << Format(\"%s\", when, utc);\n std::cout << \"\\n\";\n std::cout << std::setw(width) << std::right << utc_label << \": \";\n std::cout << FormatTimeInZone(when, utc) << \"\\n\";\n std::cout << std::setw(width) << std::right << zone_label << \": \";\n std::cout << FormatTimeInZone(when, zone) << \"\\n\";\n std::cout << \"}\\n\";\n}\n\n\/\/ Report everything we know about a Breakdown (YMDHMS).\nint BreakdownInfo(const cctz::Breakdown& when, cctz::TimeZone zone) {\n cctz::TimeInfo ti =\n cctz::MakeTimeInfo(when.year, when.month, when.day,\n when.hour, when.minute, when.second, zone);\n switch (ti.kind) {\n case cctz::TimeInfo::Kind::UNIQUE: {\n std::cout << \"kind: UNIQUE\\n\";\n InstantInfo(\"when\", ti.pre, zone);\n break;\n }\n case cctz::TimeInfo::Kind::SKIPPED: {\n std::cout << \"kind: SKIPPED\\n\";\n InstantInfo(\"post\", ti.post, zone); \/\/ might == trans-1\n InstantInfo(\"trans-1\", ti.trans - std::chrono::seconds(1), zone);\n InstantInfo(\"trans\", ti.trans, zone);\n InstantInfo(\"pre\", ti.pre, zone); \/\/ might == trans\n break;\n }\n case cctz::TimeInfo::Kind::REPEATED: {\n std::cout << \"kind: REPEATED\\n\";\n InstantInfo(\"pre\", ti.pre, zone); \/\/ might == trans-1\n InstantInfo(\"trans-1\", ti.trans - std::chrono::seconds(1), zone);\n InstantInfo(\"trans\", ti.trans, zone);\n InstantInfo(\"post\", ti.post, zone); \/\/ might == trans\n break;\n }\n }\n return 0;\n}\n\n\/\/ Report everything we know about a time_point.\nint TimeInfo(cctz::time_point when, cctz::TimeZone zone) {\n std::cout << \"kind: UNIQUE\\n\";\n InstantInfo(\"when\", when, zone);\n return 0;\n}\n\nconst char* Basename(const char* p) {\n if (const char* b = strrchr(p, '\/')) return ++b;\n return p;\n}\n\n\/\/ std::regex doesn't work before gcc 4.9.\nbool LooksLikeNegOffset(const char* s) {\n if (s[0] == '-' && std::isdigit(s[1]) && std::isdigit(s[2])) {\n int i = (s[3] == ':') ? 4 : 3;\n if (std::isdigit(s[i]) && std::isdigit(s[i + 1])) {\n return s[i + 2] == '\\0';\n }\n }\n return false;\n}\n\nint main(int argc, char** argv) {\n std::string prog = argv[0] ? Basename(argv[0]) : \"time_tool\";\n\n \/\/ Escape arguments that look like negative offsets so that they\n \/\/ don't look like flags.\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i], \"--\") == 0) break;\n if (LooksLikeNegOffset(argv[i])) {\n char* buf = new char[strlen(argv[i] + 2)];\n buf[0] = ' '; \/\/ will later be ignorned\n strcpy(buf + 1, argv[i]);\n argv[i] = buf;\n }\n }\n\n \/\/ Determine the time zone.\n cctz::TimeZone zone = cctz::LocalTimeZone();\n for (;;) {\n static option opts[] = {\n {\"zone\", required_argument, nullptr, 'z'},\n {nullptr, 0, nullptr, 0},\n };\n int c = getopt_long(argc, argv, \"z:\", opts, nullptr);\n if (c == -1) break;\n switch (c) {\n case 'z':\n if (!cctz::LoadTimeZone(optarg, &zone)) {\n std::cerr << optarg << \": Unrecognized time zone\\n\";\n return 1;\n }\n break;\n default:\n std::cerr << \"Usage: \" << prog << \" [--zone=<zone>] [<time-spec>]\\n\";\n return 1;\n }\n }\n\n \/\/ Determine the time point.\n cctz::time_point tp = std::chrono::system_clock::now();\n std::string args;\n for (int i = optind; i < argc; ++i) {\n if (i != optind) args += \" \";\n args += argv[i];\n }\n std::replace(args.begin(), args.end(), ',', ' ');\n std::replace(args.begin(), args.end(), '\/', '-');\n bool have_time = ParseTimeSpec(args, zone, &tp);\n if (!have_time && !args.empty()) {\n std::string spec = args.substr((args[0] == '@') ? 1 : 0);\n if ((spec.size() > 0 && std::isdigit(spec[0])) ||\n (spec.size() > 1 && spec[0] == '-' && std::isdigit(spec[1]))) {\n std::size_t end;\n const time_t t = std::stoll(spec, &end);\n if (end == spec.size()) {\n tp = std::chrono::system_clock::from_time_t(t);\n have_time = true;\n }\n }\n }\n cctz::Breakdown when = cctz::BreakTime(tp, zone);\n bool have_break_down = !have_time && ParseBreakdownSpec(args, zone, &when);\n\n \/\/ Show results.\n if (have_break_down) return BreakdownInfo(when, zone);\n if (have_time || args.empty()) return TimeInfo(tp, zone);\n\n std::cerr << args << \": Malformed time spec\\n\";\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>6bbfd678-2e4d-11e5-9284-b827eb9e62be<commit_msg>6bc4df4c-2e4d-11e5-9284-b827eb9e62be<commit_after>6bc4df4c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>21f1310e-2e4d-11e5-9284-b827eb9e62be<commit_msg>21f62eca-2e4d-11e5-9284-b827eb9e62be<commit_after>21f62eca-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>1e48464a-2e4e-11e5-9284-b827eb9e62be<commit_msg>1e4d555e-2e4e-11e5-9284-b827eb9e62be<commit_after>1e4d555e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>85e71b8c-2e4e-11e5-9284-b827eb9e62be<commit_msg>85ec23fc-2e4e-11e5-9284-b827eb9e62be<commit_after>85ec23fc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 WebAssembly Community Group participants\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#include <cassert>\n#include <cmath>\n#include <limits>\n\n#include \"support\/safe_integer.h\"\n\nusing namespace wasm;\n\nbool wasm::isInteger(double x) { return fmod(x, 1) == 0; }\n\nbool wasm::isUInteger32(double x) {\n return isInteger(x) && x >= 0 && x <= std::numeric_limits<uint32_t>::max();\n}\n\nbool wasm::isSInteger32(double x) {\n return isInteger(x) && x >= std::numeric_limits<int32_t>::min() &&\n x <= std::numeric_limits<int32_t>::max();\n}\n\nuint32_t wasm::toUInteger32(double x) {\n assert(isUInteger32(x));\n return x < std::numeric_limits<uint32_t>::max()\n ? (uint32_t)x\n : std::numeric_limits<uint32_t>::max();\n}\n\nint32_t wasm::toSInteger32(double x) {\n assert(isSInteger32(x));\n return x > std::numeric_limits<int32_t>::min() &&\n x < std::numeric_limits<int32_t>::max()\n ? x\n : (x < 0 ? std::numeric_limits<int32_t>::min()\n : std::numeric_limits<int32_t>::max());\n}\n\nbool wasm::isUInteger64(double x) {\n return isInteger(x) && x >= 0 && x <= std::numeric_limits<uint64_t>::max();\n}\n\nbool wasm::isSInteger64(double x) {\n return isInteger(x) && x >= std::numeric_limits<int64_t>::min() &&\n x <= std::numeric_limits<int64_t>::max();\n}\n\nuint64_t wasm::toUInteger64(double x) {\n assert(isUInteger64(x));\n return x < (double)std::numeric_limits<uint64_t>::max()\n ? (uint64_t)x\n : std::numeric_limits<uint64_t>::max();\n}\n\nint64_t wasm::toSInteger64(double x) {\n assert(isSInteger64(x));\n return x > (double)std::numeric_limits<int64_t>::min() &&\n x < (double)std::numeric_limits<int64_t>::max()\n ? (int64_t)x\n : (x < 0 ? std::numeric_limits<int64_t>::min()\n : std::numeric_limits<int64_t>::max());\n}\n<commit_msg>Also clean up Visual Studio build warning in wasm::toSInteger32 for double->int32_t cast.<commit_after>\/*\n * Copyright 2016 WebAssembly Community Group participants\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#include <cassert>\n#include <cmath>\n#include <limits>\n\n#include \"support\/safe_integer.h\"\n\nusing namespace wasm;\n\nbool wasm::isInteger(double x) { return fmod(x, 1) == 0; }\n\nbool wasm::isUInteger32(double x) {\n return isInteger(x) && x >= 0 && x <= std::numeric_limits<uint32_t>::max();\n}\n\nbool wasm::isSInteger32(double x) {\n return isInteger(x) && x >= std::numeric_limits<int32_t>::min() &&\n x <= std::numeric_limits<int32_t>::max();\n}\n\nuint32_t wasm::toUInteger32(double x) {\n assert(isUInteger32(x));\n return x < std::numeric_limits<uint32_t>::max()\n ? (uint32_t)x\n : std::numeric_limits<uint32_t>::max();\n}\n\nint32_t wasm::toSInteger32(double x) {\n assert(isSInteger32(x));\n return x > std::numeric_limits<int32_t>::min() &&\n x < std::numeric_limits<int32_t>::max()\n ? (int32_t)x\n : (x < 0 ? std::numeric_limits<int32_t>::min()\n : std::numeric_limits<int32_t>::max());\n}\n\nbool wasm::isUInteger64(double x) {\n return isInteger(x) && x >= 0 && x <= std::numeric_limits<uint64_t>::max();\n}\n\nbool wasm::isSInteger64(double x) {\n return isInteger(x) && x >= std::numeric_limits<int64_t>::min() &&\n x <= std::numeric_limits<int64_t>::max();\n}\n\nuint64_t wasm::toUInteger64(double x) {\n assert(isUInteger64(x));\n return x < (double)std::numeric_limits<uint64_t>::max()\n ? (uint64_t)x\n : std::numeric_limits<uint64_t>::max();\n}\n\nint64_t wasm::toSInteger64(double x) {\n assert(isSInteger64(x));\n return x > (double)std::numeric_limits<int64_t>::min() &&\n x < (double)std::numeric_limits<int64_t>::max()\n ? (int64_t)x\n : (x < 0 ? std::numeric_limits<int64_t>::min()\n : std::numeric_limits<int64_t>::max());\n}\n<|endoftext|>"} {"text":"<commit_before>28da1382-2e4d-11e5-9284-b827eb9e62be<commit_msg>28df004a-2e4d-11e5-9284-b827eb9e62be<commit_after>28df004a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>75afc75a-2e4e-11e5-9284-b827eb9e62be<commit_msg>75b4cc00-2e4e-11e5-9284-b827eb9e62be<commit_after>75b4cc00-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>52dbf30c-2e4e-11e5-9284-b827eb9e62be<commit_msg>52e1011c-2e4e-11e5-9284-b827eb9e62be<commit_after>52e1011c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>#include \"ModLED.h\"\n\/\/TODO this is a dummy mod, remove this once the build system is up\nCModLED::CModLED(void)\n{\n \/\/ nothing\n}\n\nvoid CModLED::Begin(void)\n{\n CModTemplate::Begin();\n ModGUID = 10; \/\/ GUID of this specific mod\n\n if (Global.HasUSB)\n {\n\n }\n InitiateLED();\n}\n\nvoid CModLED::InitiateLED(void) \/\/ this should only be called once per boot up\n{\n ledPin = GetData(LED_PIN_MEM);\n if (ledPin != 255) \/\/ if LED pin is initiated\n {\n LEDCount = GetData(LED_COUNT_MEM);\n FastLED.addLeds<NEOPIXEL, LED_PIN>(LEDs, LEDCount);\n RefreshLED();\n }\n}\n\nvoid CModLED::RefreshLED(void)\n{\n for (short i = 0; i < LEDCount; i++)\n {\n LEDs[i] = CHSV (GetData(2 + i * 2), GetData(2 + i * 2 + 1), Global.LEDBrightness);\n }\n FastLED.show();\n}\n\nvoid CModLED::LoadData(void)\n{\n CModTemplate::LoadData();\n\n if (Global.HasUSB)\n {\n\n }\n RefreshLED();\n}\n\nvoid CModLED::Loop(void)\n{\n CModTemplate::Loop();\n if (Animus.AsyncRefreshDelay())\n {\n }\n}\n\nvoid CModLED::PressCoords(byte x, byte y)\n{\n CModTemplate::PressCoords(x, y);\n\n}\n\nvoid CModLED::PrePress(byte val, byte type)\n{\n CModTemplate::PrePress(val, type);\n if (Global.HasUSB)\n {\n\n }\n}\nvoid CModLED::PressKey(byte val, byte type)\n{\n CModTemplate::PressKey(val, type);\n if (type == 38) \/\/ LED brightness adjust\n {\n short adjust = val - 127;\n if (Global.LEDBrightness + adjust < 0)\n {\n Global.LEDBrightness = 0;\n }\n else if (Global.LEDBrightness + adjust > LED_MAX_BRIGHTNESS)\n {\n Global.LEDBrightness = LED_MAX_BRIGHTNESS;\n }\n else\n {\n Global.LEDBrightness = Global.LEDBrightness + adjust;\n }\n RefreshLED;\n }\n\n}\nvoid CModLED::ReleaseKey(byte val, byte type)\n{\n CModTemplate::ReleaseKey(val, type);\n\n}\n\nvoid CModLED::SerialComms(byte mode)\n{\n CModTemplate::SerialComms(mode);\n}\n\n\nCModLED ModLED;\n<commit_msg>add: led changes<commit_after>#include \"ModLED.h\"\n\/\/TODO this is a dummy mod, remove this once the build system is up\nCModLED::CModLED(void)\n{\n \/\/ nothing\n}\n\nvoid CModLED::Begin(void)\n{\n CModTemplate::Begin();\n ModGUID = 10; \/\/ GUID of this specific mod\n\n if (Global.HasUSB)\n {\n\n }\n InitiateLED();\n}\n\nvoid CModLED::InitiateLED(void) \/\/ this should only be called once per boot up\n{\n uint8_t ledPin = GetData(LED_PIN_MEM);\n if (ledPin == 255) \/\/ this be janky due to hardware problems\n {\n LEDCount = GetData(LED_COUNT_MEM);\n FastLED.addLeds<NEOPIXEL, 11>(LEDs, LEDCount);\n RefreshLED();\n }\n else\n {\n LEDCount = GetData(LED_COUNT_MEM);\n FastLED.addLeds<NEOPIXEL, 26>(LEDs, LEDCount);\n RefreshLED();\n }\n}\n\nvoid CModLED::RefreshLED(void)\n{\n for (short i = 0; i < LEDCount; i++)\n {\n LEDs[i] = CHSV (GetData(2 + i * 2), GetData(2 + i * 2 + 1), Global.LEDBrightness);\n }\n FastLED.show();\n}\n\nvoid CModLED::LoadData(void)\n{\n CModTemplate::LoadData();\n\n if (Global.HasUSB)\n {\n\n }\n RefreshLED();\n}\n\nvoid CModLED::Loop(void)\n{\n CModTemplate::Loop();\n if (Animus.AsyncRefreshDelay())\n {\n }\n}\n\nvoid CModLED::PressCoords(byte x, byte y)\n{\n CModTemplate::PressCoords(x, y);\n\n}\n\nvoid CModLED::PrePress(byte val, byte type)\n{\n CModTemplate::PrePress(val, type);\n if (Global.HasUSB)\n {\n\n }\n}\nvoid CModLED::PressKey(byte val, byte type)\n{\n CModTemplate::PressKey(val, type);\n if (type == 38) \/\/ LED brightness adjust\n {\n short adjust = val - 127;\n if (Global.LEDBrightness + adjust < 0)\n {\n Global.LEDBrightness = 0;\n }\n else if (Global.LEDBrightness + adjust > LED_MAX_BRIGHTNESS)\n {\n Global.LEDBrightness = LED_MAX_BRIGHTNESS;\n }\n else\n {\n Global.LEDBrightness = Global.LEDBrightness + adjust;\n }\n RefreshLED();\n }\n\n}\nvoid CModLED::ReleaseKey(byte val, byte type)\n{\n CModTemplate::ReleaseKey(val, type);\n\n}\n\nvoid CModLED::SerialComms(byte mode)\n{\n CModTemplate::SerialComms(mode);\n}\n\n\nCModLED ModLED;\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Shared memory for sharing data between worker processes.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"shm.hxx\"\n#include \"lock.h\"\n#include \"system\/Error.hxx\"\n#include \"util\/RefCount.hxx\"\n\n#include <inline\/poison.h>\n#include <inline\/list.h>\n#include <daemon\/log.h>\n\n#include <assert.h>\n#include <stdint.h>\n#include <sys\/mman.h>\n#include <errno.h>\n#include <string.h>\n\nstruct page {\n struct list_head siblings;\n\n unsigned num_pages;\n uint8_t *data;\n};\n\nstruct shm {\n RefCount ref;\n\n size_t page_size;\n unsigned num_pages;\n\n \/** this lock protects the linked list *\/\n struct lock lock;\n\n struct list_head available;\n struct page pages[1];\n};\n\nstatic inline unsigned\ncalc_header_pages(size_t page_size, unsigned num_pages)\n{\n size_t header_size = sizeof(struct shm) +\n (num_pages - 1) * sizeof(struct page);\n return (header_size + page_size - 1) \/ page_size;\n}\n\ngcc_const\nstatic uint8_t *\nshm_at(struct shm *shm, size_t offset)\n{\n return (uint8_t *)shm + offset;\n}\n\nstatic uint8_t *\nshm_data(struct shm *shm)\n{\n unsigned header_pages = calc_header_pages(shm->page_size, shm->num_pages);\n\n return shm_at(shm, shm->page_size * header_pages);\n}\n\nstruct shm *\nshm_new(size_t page_size, unsigned num_pages)\n{\n assert(page_size >= sizeof(size_t));\n assert(num_pages > 0);\n\n const unsigned header_pages = calc_header_pages(page_size, num_pages);\n void *p = mmap(nullptr, page_size * (header_pages + num_pages),\n PROT_READ|PROT_WRITE,\n MAP_ANONYMOUS|MAP_SHARED,\n -1, 0);\n if (p == (void *)-1)\n throw MakeErrno(\"mmap() failed\");\n\n struct shm *shm = (struct shm *)p;\n shm->ref.Init();\n shm->page_size = page_size;\n shm->num_pages = num_pages;\n\n lock_init(&shm->lock);\n\n list_init(&shm->available);\n list_add(&shm->pages[0].siblings, &shm->available);\n shm->pages[0].num_pages = num_pages;\n shm->pages[0].data = shm_data(shm);\n\n return shm;\n}\n\nvoid\nshm_ref(struct shm *shm)\n{\n assert(shm != nullptr);\n\n shm->ref.Get();\n}\n\nvoid\nshm_close(struct shm *shm)\n{\n unsigned header_pages;\n int ret;\n\n assert(shm != nullptr);\n\n if (shm->ref.Put())\n lock_destroy(&shm->lock);\n\n header_pages = calc_header_pages(shm->page_size, shm->num_pages);\n ret = munmap(shm, shm->page_size * (header_pages + shm->num_pages));\n if (ret < 0)\n daemon_log(1, \"munmap() failed: %s\\n\", strerror(errno));\n}\n\nsize_t\nshm_page_size(const struct shm *shm)\n{\n return shm->page_size;\n}\n\nstatic struct page *\nshm_find_available(struct shm *shm, unsigned num_pages)\n{\n for (struct page *page = (struct page *)shm->available.next;\n &page->siblings != &shm->available;\n page = (struct page *)page->siblings.next)\n if (page->num_pages >= num_pages)\n return page;\n\n return nullptr;\n}\n\nstatic struct page *\nshm_split_page(const struct shm *shm, struct page *page, unsigned num_pages)\n{\n assert(page->num_pages > num_pages);\n\n page->num_pages -= num_pages;\n\n page[page->num_pages].data = page->data + shm->page_size * page->num_pages;\n page += page->num_pages;\n page->num_pages = num_pages;\n\n return page;\n}\n\nvoid *\nshm_alloc(struct shm *shm, unsigned num_pages)\n{\n assert(num_pages > 0);\n\n lock_lock(&shm->lock);\n\n struct page *page = shm_find_available(shm, num_pages);\n if (page == nullptr) {\n lock_unlock(&shm->lock);\n return nullptr;\n }\n\n assert(page->num_pages >= num_pages);\n\n page = (struct page *)shm->available.next;\n if (page->num_pages == num_pages) {\n list_remove(&page->siblings);\n lock_unlock(&shm->lock);\n\n poison_undefined(page->data, shm->page_size * num_pages);\n return page->data;\n } else {\n page = shm_split_page(shm, page, num_pages);\n\n lock_unlock(&shm->lock);\n\n poison_undefined(page->data, shm->page_size * num_pages);\n return page->data;\n }\n}\n\nstatic unsigned\nshm_page_number(struct shm *shm, const void *p)\n{\n ptrdiff_t difference = (const uint8_t *)p - shm_data(shm);\n unsigned page_number = difference \/ shm->page_size;\n assert(difference % shm->page_size == 0);\n\n assert(page_number < shm->num_pages);\n\n return page_number;\n}\n\n\/** merge this page with its adjacent pages if possible, to create\n bigger \"available\" areas *\/\nstatic void\nshm_merge(struct shm *shm, struct page *page)\n{\n unsigned page_number = shm_page_number(shm, page->data);\n\n \/* merge with previous page? *\/\n\n struct page *other = (struct page *)page->siblings.prev;\n if (&other->siblings != &shm->available &&\n shm_page_number(shm, other->data) + other->num_pages == page_number) {\n other->num_pages += page->num_pages;\n list_remove(&page->siblings);\n page = other;\n }\n\n \/* merge with next page? *\/\n\n other = (struct page *)page->siblings.next;\n if (&other->siblings != &shm->available &&\n page_number + page->num_pages == shm_page_number(shm, other->data)) {\n page->num_pages += other->num_pages;\n list_remove(&other->siblings);\n }\n}\n\nvoid\nshm_free(struct shm *shm, const void *p)\n{\n unsigned page_number = shm_page_number(shm, p);\n struct page *page = &shm->pages[page_number];\n struct page *prev;\n\n poison_noaccess(page->data, shm->page_size * page->num_pages);\n\n lock_lock(&shm->lock);\n\n for (prev = (struct page *)&shm->available;\n prev->siblings.next != &shm->available;\n prev = (struct page *)prev->siblings.next) {\n }\n\n list_add(&page->siblings, &prev->siblings);\n\n shm_merge(shm, page);\n\n lock_unlock(&shm->lock);\n}\n<commit_msg>shm\/shm: move functions into the struct<commit_after>\/*\n * Shared memory for sharing data between worker processes.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"shm.hxx\"\n#include \"lock.h\"\n#include \"system\/Error.hxx\"\n#include \"util\/RefCount.hxx\"\n\n#include <inline\/poison.h>\n#include <inline\/list.h>\n#include <daemon\/log.h>\n\n#include <assert.h>\n#include <stdint.h>\n#include <sys\/mman.h>\n#include <errno.h>\n#include <string.h>\n\nstruct page {\n struct list_head siblings;\n\n unsigned num_pages;\n uint8_t *data;\n};\n\nstruct shm {\n RefCount ref;\n\n size_t page_size;\n unsigned num_pages;\n\n \/** this lock protects the linked list *\/\n struct lock lock;\n\n struct list_head available;\n struct page pages[1];\n\n static unsigned CalcHeaderPages(size_t page_size, unsigned num_pages) {\n size_t header_size = sizeof(struct shm) +\n (num_pages - 1) * sizeof(struct page);\n return (header_size + page_size - 1) \/ page_size;\n }\n\n unsigned CalcHeaderPages() const {\n return CalcHeaderPages(page_size, num_pages);\n }\n\n uint8_t *At(size_t offset) {\n return (uint8_t *)this + offset;\n }\n\n uint8_t *GetData() {\n return At(page_size * CalcHeaderPages());\n }\n};\n\nstruct shm *\nshm_new(size_t page_size, unsigned num_pages)\n{\n assert(page_size >= sizeof(size_t));\n assert(num_pages > 0);\n\n const unsigned header_pages = shm::CalcHeaderPages(page_size, num_pages);\n void *p = mmap(nullptr, page_size * (header_pages + num_pages),\n PROT_READ|PROT_WRITE,\n MAP_ANONYMOUS|MAP_SHARED,\n -1, 0);\n if (p == (void *)-1)\n throw MakeErrno(\"mmap() failed\");\n\n struct shm *shm = (struct shm *)p;\n shm->ref.Init();\n shm->page_size = page_size;\n shm->num_pages = num_pages;\n\n lock_init(&shm->lock);\n\n list_init(&shm->available);\n list_add(&shm->pages[0].siblings, &shm->available);\n shm->pages[0].num_pages = num_pages;\n shm->pages[0].data = shm->GetData();\n\n return shm;\n}\n\nvoid\nshm_ref(struct shm *shm)\n{\n assert(shm != nullptr);\n\n shm->ref.Get();\n}\n\nvoid\nshm_close(struct shm *shm)\n{\n unsigned header_pages;\n int ret;\n\n assert(shm != nullptr);\n\n if (shm->ref.Put())\n lock_destroy(&shm->lock);\n\n header_pages = shm->CalcHeaderPages();\n ret = munmap(shm, shm->page_size * (header_pages + shm->num_pages));\n if (ret < 0)\n daemon_log(1, \"munmap() failed: %s\\n\", strerror(errno));\n}\n\nsize_t\nshm_page_size(const struct shm *shm)\n{\n return shm->page_size;\n}\n\nstatic struct page *\nshm_find_available(struct shm *shm, unsigned num_pages)\n{\n for (struct page *page = (struct page *)shm->available.next;\n &page->siblings != &shm->available;\n page = (struct page *)page->siblings.next)\n if (page->num_pages >= num_pages)\n return page;\n\n return nullptr;\n}\n\nstatic struct page *\nshm_split_page(const struct shm *shm, struct page *page, unsigned num_pages)\n{\n assert(page->num_pages > num_pages);\n\n page->num_pages -= num_pages;\n\n page[page->num_pages].data = page->data + shm->page_size * page->num_pages;\n page += page->num_pages;\n page->num_pages = num_pages;\n\n return page;\n}\n\nvoid *\nshm_alloc(struct shm *shm, unsigned num_pages)\n{\n assert(num_pages > 0);\n\n lock_lock(&shm->lock);\n\n struct page *page = shm_find_available(shm, num_pages);\n if (page == nullptr) {\n lock_unlock(&shm->lock);\n return nullptr;\n }\n\n assert(page->num_pages >= num_pages);\n\n page = (struct page *)shm->available.next;\n if (page->num_pages == num_pages) {\n list_remove(&page->siblings);\n lock_unlock(&shm->lock);\n\n poison_undefined(page->data, shm->page_size * num_pages);\n return page->data;\n } else {\n page = shm_split_page(shm, page, num_pages);\n\n lock_unlock(&shm->lock);\n\n poison_undefined(page->data, shm->page_size * num_pages);\n return page->data;\n }\n}\n\nstatic unsigned\nshm_page_number(struct shm *shm, const void *p)\n{\n ptrdiff_t difference = (const uint8_t *)p - shm->GetData();\n unsigned page_number = difference \/ shm->page_size;\n assert(difference % shm->page_size == 0);\n\n assert(page_number < shm->num_pages);\n\n return page_number;\n}\n\n\/** merge this page with its adjacent pages if possible, to create\n bigger \"available\" areas *\/\nstatic void\nshm_merge(struct shm *shm, struct page *page)\n{\n unsigned page_number = shm_page_number(shm, page->data);\n\n \/* merge with previous page? *\/\n\n struct page *other = (struct page *)page->siblings.prev;\n if (&other->siblings != &shm->available &&\n shm_page_number(shm, other->data) + other->num_pages == page_number) {\n other->num_pages += page->num_pages;\n list_remove(&page->siblings);\n page = other;\n }\n\n \/* merge with next page? *\/\n\n other = (struct page *)page->siblings.next;\n if (&other->siblings != &shm->available &&\n page_number + page->num_pages == shm_page_number(shm, other->data)) {\n page->num_pages += other->num_pages;\n list_remove(&other->siblings);\n }\n}\n\nvoid\nshm_free(struct shm *shm, const void *p)\n{\n unsigned page_number = shm_page_number(shm, p);\n struct page *page = &shm->pages[page_number];\n struct page *prev;\n\n poison_noaccess(page->data, shm->page_size * page->num_pages);\n\n lock_lock(&shm->lock);\n\n for (prev = (struct page *)&shm->available;\n prev->siblings.next != &shm->available;\n prev = (struct page *)prev->siblings.next) {\n }\n\n list_add(&page->siblings, &prev->siblings);\n\n shm_merge(shm, page);\n\n lock_unlock(&shm->lock);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2017, Matt Godbolt\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 met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include \"seasocks\/ToString.h\"\n\n#include <catch2\/catch.hpp>\n\nusing namespace seasocks;\n\nTEST_CASE(\"withIntegralTypes\", \"[toStringTests]\") {\n CHECK(toString(static_cast<short>(1234)) == \"1234\");\n CHECK(toString(static_cast<unsigned short>(1234)) == \"1234\");\n\n CHECK(toString(static_cast<int>(1234)) == \"1234\");\n CHECK(toString(static_cast<unsigned int>(1234)) == \"1234\");\n\n CHECK(toString(static_cast<long>(1234)) == \"1234\");\n CHECK(toString(static_cast<unsigned long>(1234)) == \"1234\");\n\n CHECK(toString(static_cast<long long>(1234)) == \"1234\");\n CHECK(toString(static_cast<unsigned long long>(1234)) == \"1234\");\n}\n\nTEST_CASE(\"withFloatTypes\", \"[toStringTests]\") {\n CHECK(toString(123.4) == \"123.4\");\n CHECK(toString(123.4f) == \"123.4\");\n}\n\nTEST_CASE(\"withCharType\" \"[toStringTests]\") {\n CHECK(toString('c') == \"c\");\n}\n<commit_msg>Typo in the test case fixed.<commit_after>\/\/ Copyright (c) 2013-2017, Matt Godbolt\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 met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include \"seasocks\/ToString.h\"\n\n#include <catch2\/catch.hpp>\n\nusing namespace seasocks;\n\nTEST_CASE(\"withIntegralTypes\", \"[toStringTests]\") {\n CHECK(toString(static_cast<short>(1234)) == \"1234\");\n CHECK(toString(static_cast<unsigned short>(1234)) == \"1234\");\n\n CHECK(toString(static_cast<int>(1234)) == \"1234\");\n CHECK(toString(static_cast<unsigned int>(1234)) == \"1234\");\n\n CHECK(toString(static_cast<long>(1234)) == \"1234\");\n CHECK(toString(static_cast<unsigned long>(1234)) == \"1234\");\n\n CHECK(toString(static_cast<long long>(1234)) == \"1234\");\n CHECK(toString(static_cast<unsigned long long>(1234)) == \"1234\");\n}\n\nTEST_CASE(\"withFloatTypes\", \"[toStringTests]\") {\n CHECK(toString(123.4) == \"123.4\");\n CHECK(toString(123.4f) == \"123.4\");\n}\n\nTEST_CASE(\"withCharType\", \"[toStringTests]\") {\n CHECK(toString('c') == \"c\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2021 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <core_io.h>\n#include <hash.h>\n#include <key.h>\n#include <script\/miniscript.h>\n#include <script\/script.h>\n#include <test\/fuzz\/FuzzedDataProvider.h>\n#include <test\/fuzz\/fuzz.h>\n#include <test\/fuzz\/util.h>\n#include <util\/strencodings.h>\n\nnamespace {\n\n\/\/! Context that implements naive conversion from\/to script only, for roundtrip testing.\nstruct ScriptParserContext {\n \/\/! For Script roundtrip we never need the key from a key hash.\n struct Key {\n bool is_hash;\n std::vector<unsigned char> data;\n };\n\n const std::vector<unsigned char>& ToPKBytes(const Key& key) const\n {\n assert(!key.is_hash);\n return key.data;\n }\n\n const std::vector<unsigned char> ToPKHBytes(const Key& key) const\n {\n if (key.is_hash) return key.data;\n const auto h = Hash160(key.data);\n return {h.begin(), h.end()};\n }\n\n template<typename I>\n std::optional<Key> FromPKBytes(I first, I last) const\n {\n Key key;\n key.data.assign(first, last);\n key.is_hash = false;\n return key;\n }\n\n template<typename I>\n std::optional<Key> FromPKHBytes(I first, I last) const\n {\n Key key;\n key.data.assign(first, last);\n key.is_hash = true;\n return key;\n }\n} SCRIPT_PARSER_CONTEXT;\n\n}\n\n\/* Fuzz tests that test parsing from a script, and roundtripping via script. *\/\nFUZZ_TARGET(miniscript_script)\n{\n FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());\n const std::optional<CScript> script = ConsumeDeserializable<CScript>(fuzzed_data_provider);\n if (!script) return;\n\n const auto ms = miniscript::FromScript(*script, SCRIPT_PARSER_CONTEXT);\n if (!ms) return;\n\n assert(ms->ToScript(SCRIPT_PARSER_CONTEXT) == *script);\n}\n<commit_msg>fuzz: add a Miniscript target for string representation roundtripping<commit_after>\/\/ Copyright (c) 2021 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <core_io.h>\n#include <hash.h>\n#include <key.h>\n#include <script\/miniscript.h>\n#include <script\/script.h>\n#include <test\/fuzz\/FuzzedDataProvider.h>\n#include <test\/fuzz\/fuzz.h>\n#include <test\/fuzz\/util.h>\n#include <util\/strencodings.h>\n\nnamespace {\n\n\/\/! Some pre-computed data for more efficient string roundtrips.\nstruct TestData {\n typedef CPubKey Key;\n\n \/\/ Precomputed public keys.\n std::vector<Key> dummy_keys;\n std::map<Key, int> dummy_key_idx_map;\n std::map<CKeyID, Key> dummy_keys_map;\n\n \/\/! Set the precomputed data.\n void Init() {\n unsigned char keydata[32] = {1};\n for (size_t i = 0; i < 256; i++) {\n keydata[31] = i;\n CKey privkey;\n privkey.Set(keydata, keydata + 32, true);\n const Key pubkey = privkey.GetPubKey();\n\n dummy_keys.push_back(pubkey);\n dummy_key_idx_map.emplace(pubkey, i);\n dummy_keys_map.insert({pubkey.GetID(), pubkey});\n }\n }\n} TEST_DATA;\n\n\/**\n * Context to parse a Miniscript node to and from Script or text representation.\n * Uses an integer (an index in the dummy keys array from the test data) as keys in order\n * to focus on fuzzing the Miniscript nodes' test representation, not the key representation.\n *\/\nstruct ParserContext {\n typedef CPubKey Key;\n\n std::optional<std::string> ToString(const Key& key) const\n {\n auto it = TEST_DATA.dummy_key_idx_map.find(key);\n if (it == TEST_DATA.dummy_key_idx_map.end()) return {};\n uint8_t idx = it->second;\n return HexStr(Span{&idx, 1});\n }\n\n template<typename I>\n std::optional<Key> FromString(I first, I last) const {\n if (last - first != 2) return {};\n auto idx = ParseHex(std::string(first, last));\n if (idx.size() != 1) return {};\n return TEST_DATA.dummy_keys[idx[0]];\n }\n\n template<typename I>\n std::optional<Key> FromPKBytes(I first, I last) const {\n Key key;\n key.Set(first, last);\n if (!key.IsValid()) return {};\n return key;\n }\n\n template<typename I>\n std::optional<Key> FromPKHBytes(I first, I last) const {\n assert(last - first == 20);\n CKeyID keyid;\n std::copy(first, last, keyid.begin());\n const auto it = TEST_DATA.dummy_keys_map.find(keyid);\n if (it == TEST_DATA.dummy_keys_map.end()) return {};\n return it->second;\n }\n} PARSER_CTX;\n\n\/\/! Context that implements naive conversion from\/to script only, for roundtrip testing.\nstruct ScriptParserContext {\n \/\/! For Script roundtrip we never need the key from a key hash.\n struct Key {\n bool is_hash;\n std::vector<unsigned char> data;\n };\n\n const std::vector<unsigned char>& ToPKBytes(const Key& key) const\n {\n assert(!key.is_hash);\n return key.data;\n }\n\n const std::vector<unsigned char> ToPKHBytes(const Key& key) const\n {\n if (key.is_hash) return key.data;\n const auto h = Hash160(key.data);\n return {h.begin(), h.end()};\n }\n\n template<typename I>\n std::optional<Key> FromPKBytes(I first, I last) const\n {\n Key key;\n key.data.assign(first, last);\n key.is_hash = false;\n return key;\n }\n\n template<typename I>\n std::optional<Key> FromPKHBytes(I first, I last) const\n {\n Key key;\n key.data.assign(first, last);\n key.is_hash = true;\n return key;\n }\n} SCRIPT_PARSER_CONTEXT;\n\n} \/\/ namespace\n\nvoid FuzzInit()\n{\n ECC_Start();\n TEST_DATA.Init();\n}\n\n\/* Fuzz tests that test parsing from a string, and roundtripping via string. *\/\nFUZZ_TARGET_INIT(miniscript_string, FuzzInit)\n{\n FuzzedDataProvider provider(buffer.data(), buffer.size());\n auto str = provider.ConsumeRemainingBytesAsString();\n auto parsed = miniscript::FromString(str, PARSER_CTX);\n if (!parsed) return;\n\n const auto str2 = parsed->ToString(PARSER_CTX);\n assert(str2);\n auto parsed2 = miniscript::FromString(*str2, PARSER_CTX);\n assert(parsed2);\n assert(*parsed == *parsed2);\n}\n\n\/* Fuzz tests that test parsing from a script, and roundtripping via script. *\/\nFUZZ_TARGET(miniscript_script)\n{\n FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());\n const std::optional<CScript> script = ConsumeDeserializable<CScript>(fuzzed_data_provider);\n if (!script) return;\n\n const auto ms = miniscript::FromScript(*script, SCRIPT_PARSER_CONTEXT);\n if (!ms) return;\n\n assert(ms->ToScript(SCRIPT_PARSER_CONTEXT) == *script);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * benchmarks\/benchmark-dense-solve.C\n *\n * Copyright (C) 2019 The LinBox group\n * Author: J-G Dumas\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * 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 * ========LICENCE========\n *\/\n\n\/**\\file benchmarks\/benchmark-dense-solve.C\n\\brief Solving dense linear system over Q or Zp.\n\\ingroup benchmarks\n*\/\n\n#include \"linbox\/linbox-config.h\"\n#include <iostream>\n\n#include <givaro\/modular.h>\n#include \"linbox\/util\/args-parser.h\"\n#include \"linbox\/matrix\/sparse-matrix.h\"\n#include \"linbox\/solutions\/solve.h\"\n#include \"linbox\/util\/matrix-stream.h\"\n#include \"linbox\/solutions\/methods.h\"\n\n#ifdef _DEBUG\n#define _BENCHMARKS_DEBUG_\n#endif\n\nusing namespace LinBox;\ntypedef Givaro::ZRing<Givaro::Integer> Ints;\n\nint main (int argc, char **argv)\n{\n Givaro::Integer q = -1 ;\n size_t n = 500 ;\n size_t bits = 10;\n\/\/ size_t p = 0;\n\n Argument as[] = {\n { 'q', \"-q Q\", \"Set the field characteristic (-1 for rationals).\", TYPE_INTEGER , &q },\n { 'n', \"-n N\", \"Set the matrix dimension.\", TYPE_INT , &n },\n { 'b', \"-b B\", \"bit size\", TYPE_INT , &bits },\n\/\/ { 'p', \"-p P\", \"0 for sequential, 1 for 2D iterative, 2 for 2D rec, 3 for 2D rec adaptive, 4 for 3D rec in-place, 5 for 3D rec, 6 for 3D rec adaptive.\", TYPE_INT , &p },\n END_OF_ARGUMENTS\n };\n\n LinBox::parseArguments(argc,argv,as);\n\n bool ModComp = false;\n if (q > 0) ModComp = true;\n\n \n Timer chrono;\n\n if (ModComp) {\n \n typedef Givaro::Modular<double> Field;\n Field F(q);\n\tField::RandIter G(F);\n\t\n#ifdef _BENCHMARKS_DEBUG_\n\tstd::clog << \"Setting A ... \" << std::endl;\n#endif\n chrono.start();\t\t\n DenseMatrix<Field> A(F,n,n);\n\tPAR_BLOCK { FFLAS::pfrand(F,G, n,n,A.getPointer(),n); } \n chrono.stop();\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"... A is \" << A.rowdim() << \" by \" << A.coldim() << \", \" << chrono << std::endl;\n\tif (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::clog <<\"A:=\",Tag::FileFormat::Maple) << ';' << std::endl;\n#endif \n DenseVector<Field> X(F, A.coldim()),B(F, A.rowdim());\n\tfor(auto it=B.begin(); it != B.end(); ++it)\n\t\tif (drand48() <0.5)\n\t\t\tF.assign(*it,F.mOne);\n else\n\t\t\tF.assign(*it,F.one);\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"B is [\";\n\tfor(const auto& it: B)\n F.write(std::clog, it) << ' ';\n std::clog << ']' << std::endl;\n#endif\n\n \/\/ DenseElimination\n chrono.start();\t\t\n PAR_BLOCK { solve (X, A, B, Method::DenseElimination()); }\n chrono.stop();\n\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"(DenseElimination) Solution is [\";\n for(const auto& it: X)\n F.write(std::clog, it) << ' ';\n std::clog << ']' << std::endl;\t\t\n#endif\n std::cout << \"Time: \" << chrono.usertime()\n\t\t << \" Bitsize: \" << Givaro::logtwo(GIVMAX(X.front(), 1));\n\tFFLAS::writeCommandString(std::cout, as) << std::endl;\n } else { \n\n typedef Ints Integers;\n Integers ZZ;\n\tIntegers::RandIter G(ZZ,bits);\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"Reading A ... \" << std::endl;\n chrono.start();\t\t\n#endif\n DenseMatrix<Integers> A(ZZ, n, n);\n\tPAR_BLOCK { FFLAS::pfrand(ZZ,G, n,n,A.getPointer(),n); } \n#ifdef _BENCHMARKS_DEBUG_\n\tchrono.stop();\n std::clog << \"... A is \" << A.rowdim() << \" by \" << A.coldim() << \", \" << chrono << std::endl;\n\tif (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::clog <<\"A:=\",Tag::FileFormat::Maple) << ';' << std::endl;\n#endif \n Givaro::IntegerDom::Element d;\n\n DenseVector<Integers> X(ZZ, A.coldim()),B(ZZ, A.rowdim());\n\n\tfor(auto it=B.begin(); it != B.end(); ++it)\n\t\tif (drand48() <0.5)\n\t\t\tZZ.assign(*it,ZZ.mOne);\n else\n\t\t\tZZ.assign(*it,ZZ.one);\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"B is [\";\n\tfor(const auto& it: B)\n ZZ.write(std::clog, it) << ' ';\n std::clog << ']' << std::endl;\n#endif\n\t\n \/\/ DenseElimination\n chrono.start();\n solve (X, d, A, B, RingCategories::IntegerTag(), Method::DenseElimination());\n chrono.stop();\n\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"(DenseElimination) Solution is [\";\n for(const auto& it: X) ZZ.write(std::clog, it) << ' ';\n ZZ.write(std::clog << \"] \/ \", d)<< std::endl;\n#endif\n\n std::cout << \"Time: \" << chrono.usertime()\n\t\t << \" Bitsize: \" << Givaro::logtwo(d);\n\tFFLAS::writeCommandString(std::cout, as) << std::endl;\n }\n\n return 0;\n}\n<commit_msg>no par yet<commit_after>\/*\n * benchmarks\/benchmark-dense-solve.C\n *\n * Copyright (C) 2019 The LinBox group\n * Author: J-G Dumas\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * 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 * ========LICENCE========\n *\/\n\n\/**\\file benchmarks\/benchmark-dense-solve.C\n\\brief Solving dense linear system over Q or Zp.\n\\ingroup benchmarks\n*\/\n\n#include \"linbox\/linbox-config.h\"\n#include <iostream>\n\n#include <givaro\/modular.h>\n#include \"linbox\/util\/args-parser.h\"\n#include \"linbox\/matrix\/sparse-matrix.h\"\n#include \"linbox\/solutions\/solve.h\"\n#include \"linbox\/util\/matrix-stream.h\"\n#include \"linbox\/solutions\/methods.h\"\n\n#ifdef _DEBUG\n#define _BENCHMARKS_DEBUG_\n#endif\n\nusing namespace LinBox;\ntypedef Givaro::ZRing<Givaro::Integer> Ints;\n\nint main (int argc, char **argv)\n{\n Givaro::Integer q = -1 ;\n size_t n = 500 ;\n size_t bits = 10;\n\/\/ size_t p = 0;\n\n Argument as[] = {\n { 'q', \"-q Q\", \"Set the field characteristic (-1 for rationals).\", TYPE_INTEGER , &q },\n { 'n', \"-n N\", \"Set the matrix dimension.\", TYPE_INT , &n },\n { 'b', \"-b B\", \"bit size\", TYPE_INT , &bits },\n\/\/ { 'p', \"-p P\", \"0 for sequential, 1 for 2D iterative, 2 for 2D rec, 3 for 2D rec adaptive, 4 for 3D rec in-place, 5 for 3D rec, 6 for 3D rec adaptive.\", TYPE_INT , &p },\n END_OF_ARGUMENTS\n };\n\n LinBox::parseArguments(argc,argv,as);\n\n bool ModComp = false;\n if (q > 0) ModComp = true;\n\n \n Timer chrono;\n\n if (ModComp) {\n \n typedef Givaro::Modular<double> Field;\n Field F(q);\n\tField::RandIter G(F);\n\t\n#ifdef _BENCHMARKS_DEBUG_\n\tstd::clog << \"Setting A ... \" << std::endl;\n#endif\n chrono.start();\t\t\n DenseMatrix<Field> A(F,n,n);\n\tPAR_BLOCK { FFLAS::pfrand(F,G, n,n,A.getPointer(),n); } \n chrono.stop();\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"... A is \" << A.rowdim() << \" by \" << A.coldim() << \", \" << chrono << std::endl;\n\tif (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::clog <<\"A:=\",Tag::FileFormat::Maple) << ';' << std::endl;\n#endif \n DenseVector<Field> X(F, A.coldim()),B(F, A.rowdim());\n\tfor(auto it=B.begin(); it != B.end(); ++it)\n\t\tif (drand48() <0.5)\n\t\t\tF.assign(*it,F.mOne);\n else\n\t\t\tF.assign(*it,F.one);\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"B is [\";\n\tfor(const auto& it: B)\n F.write(std::clog, it) << ' ';\n std::clog << ']' << std::endl;\n#endif\n\n \/\/ DenseElimination\n chrono.start();\t\t\n solve (X, A, B, Method::DenseElimination());\n chrono.stop();\n\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"(DenseElimination) Solution is [\";\n for(const auto& it: X)\n F.write(std::clog, it) << ' ';\n std::clog << ']' << std::endl;\t\t\n#endif\n std::cout << \"Time: \" << chrono.usertime()\n\t\t << \" Bitsize: \" << Givaro::logtwo(GIVMAX(X.front(), 1));\n\tFFLAS::writeCommandString(std::cout, as) << std::endl;\n } else { \n\n typedef Ints Integers;\n Integers ZZ;\n\tIntegers::RandIter G(ZZ,bits);\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"Reading A ... \" << std::endl;\n chrono.start();\t\t\n#endif\n DenseMatrix<Integers> A(ZZ, n, n);\n\tPAR_BLOCK { FFLAS::pfrand(ZZ,G, n,n,A.getPointer(),n); } \n#ifdef _BENCHMARKS_DEBUG_\n\tchrono.stop();\n std::clog << \"... A is \" << A.rowdim() << \" by \" << A.coldim() << \", \" << chrono << std::endl;\n\tif (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::clog <<\"A:=\",Tag::FileFormat::Maple) << ';' << std::endl;\n#endif \n Givaro::IntegerDom::Element d;\n\n DenseVector<Integers> X(ZZ, A.coldim()),B(ZZ, A.rowdim());\n\n\tfor(auto it=B.begin(); it != B.end(); ++it)\n\t\tif (drand48() <0.5)\n\t\t\tZZ.assign(*it,ZZ.mOne);\n else\n\t\t\tZZ.assign(*it,ZZ.one);\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"B is [\";\n\tfor(const auto& it: B)\n ZZ.write(std::clog, it) << ' ';\n std::clog << ']' << std::endl;\n#endif\n\t\n \/\/ DenseElimination\n chrono.start();\n solve (X, d, A, B, RingCategories::IntegerTag(), Method::DenseElimination());\n chrono.stop();\n\n#ifdef _BENCHMARKS_DEBUG_\n std::clog << \"(DenseElimination) Solution is [\";\n for(const auto& it: X) ZZ.write(std::clog, it) << ' ';\n ZZ.write(std::clog << \"] \/ \", d)<< std::endl;\n#endif\n\n std::cout << \"Time: \" << chrono.usertime()\n\t\t << \" Bitsize: \" << Givaro::logtwo(d);\n\tFFLAS::writeCommandString(std::cout, as) << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_DEFAULT_TRAITS\n#define MJOLNIR_DEFAULT_TRAITS\n#include <mjolnir\/math\/Vector.hpp>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT, template<typename, typename> class boundaryT>\nstruct SimulatorTraits\n{\n using real_type = realT;\n using coordinate_type = math::Vector<real_type, 3>;\n template<std::size_t N, std::size_t M>\n using matrix_type = math::Matrix<real_type, N, M>;\n\n using boundary_type = boundaryT<real_type, coordinate_type>;\n};\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_DEFAULT_TRAITS *\/\n<commit_msg>refactor: restrict matrix_type to 3x3 or 4x4<commit_after>#ifndef MJOLNIR_DEFAULT_TRAITS\n#define MJOLNIR_DEFAULT_TRAITS\n#include <mjolnir\/math\/Vector.hpp>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT, template<typename, typename> class boundaryT>\nstruct SimulatorTraits\n{\n using real_type = realT;\n using coordinate_type = math::Vector<real_type, 3>;\n\n using matrix33_type = math::Matrix<real_type, 3, 3>;\n using matrix44_type = math::Matrix<real_type, 4, 4>;\n\n using boundary_type = boundaryT<real_type, coordinate_type>;\n};\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_DEFAULT_TRAITS *\/\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>\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 notice,\n this list of conditions and the following disclaimer.\n - Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n - Neither the name of the Mumble Developers nor the names of its\n contributors may be used to endorse or promote products derived from this\n 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 FOUNDATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"murmur_pch.h\"\n\n#include \"SSL.h\"\n\n#include \"Version.h\"\n\nQString MumbleSSL::defaultOpenSSLCipherString() {\n\treturn QLatin1String(\"EECDH+AESGCM:AES256-SHA:AES128-SHA\");\n}\n\nQList<QSslCipher> MumbleSSL::ciphersFromOpenSSLCipherString(QString cipherString) {\n\tQList<QSslCipher> chosenCiphers;\n\n\tSSL_CTX *ctx = NULL;\n\tSSL *ssl = NULL;\n\tconst SSL_METHOD *meth = NULL;\n\tint i = 0;\n\n\tQByteArray csbuf = cipherString.toLatin1();\n\tconst char *ciphers = csbuf.constData();\n\n\tmeth = SSLv23_server_method();\n\tif (meth == NULL) {\n\t\tqWarning(\"MumbleSSL: unable to get SSL method\");\n\t\tgoto out;\n\t}\n\n\tctx = SSL_CTX_new(meth);\n\tif (ctx == NULL) {\n\t\tqWarning(\"MumbleSSL: unable to allocate SSL_CTX\");\n\t\tgoto out;\n\t}\n\n\tif (!SSL_CTX_set_cipher_list(ctx, ciphers)) {\n\t\tqWarning(\"MumbleSSL: error parsing OpenSSL cipher string in ciphersFromOpenSSLCipherString\");\n\t\tgoto out;\n\t}\n\n\tssl = SSL_new(ctx);\n\tif (ssl == NULL) {\n\t\tqWarning(\"MumbleSSL: unable to create SSL object in ciphersFromOpenSSLCipherString\");\n\t\tgoto out;\n\t}\n\n\twhile (1) {\n\t\tconst char *name = SSL_get_cipher_list(ssl, i);\n\t\tif (name == NULL) {\n\t\t\tbreak;\n\t\t}\n\t\tQSslCipher c = QSslCipher(QString::fromLatin1(name));\n\t\tif (!c.isNull()) {\n\t\t\tchosenCiphers << c;\n\t\t}\n\t\t++i;\n\t}\n\nout:\n\tSSL_CTX_free(ctx);\n\tSSL_free(ssl);\n\treturn chosenCiphers;\n}\n\nvoid MumbleSSL::addSystemCA() {\n#if QT_VERSION < 0x040700 && !defined(NO_SYSTEM_CA_OVERRIDE)\n#if defined(Q_OS_WIN)\n\tQStringList qsl;\n\tqsl << QLatin1String(\"Ca\");\n\tqsl << QLatin1String(\"Root\");\n\tqsl << QLatin1String(\"AuthRoot\");\n\tforeach(const QString &store, qsl) {\n\t\tHCERTSTORE hCertStore;\n\t\tPCCERT_CONTEXT pCertContext = NULL;\n\n\t\tbool found = false;\n\n\t\thCertStore = CertOpenSystemStore(NULL, store.utf16());\n\t\tif (! hCertStore) {\n\t\t\tqWarning(\"SSL: Failed to open CA store %s\", qPrintable(store));\n\t\t\tcontinue;\n\t\t}\n\n\t\twhile (pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext)) {\n\t\t\tQByteArray qba(reinterpret_cast<const char *>(pCertContext->pbCertEncoded), pCertContext->cbCertEncoded);\n\n\t\t\tQList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);\n\t\t\tql += QSslCertificate::fromData(qba, QSsl::Der);\n\t\t\tif (! ql.isEmpty()) {\n\t\t\t\tfound = true;\n\t\t\t\tQSslSocket::addDefaultCaCertificates(ql);\n\t\t\t}\n\t\t}\n\t\tif (found)\n\t\t\tqWarning(\"SSL: Added CA certificates from system store '%s'\", qPrintable(store));\n\n\t\tCertCloseStore(hCertStore, 0);\n\t}\n\n#elif defined(Q_OS_MAC)\n\tCFArrayRef certs = NULL;\n\tbool found = false;\n\n\tif (SecTrustCopyAnchorCertificates(&certs) == noErr) {\n\t\tint ncerts = CFArrayGetCount(certs);\n\t\tfor (int i = 0; i < ncerts; i++) {\n\t\t\tCFDataRef data = NULL;\n\n\t\t\tSecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));\n\t\t\tif (! cert)\n\t\t\t\tcontinue;\n\n\t\t\tif (SecKeychainItemExport(cert, kSecFormatX509Cert, kSecItemPemArmour, NULL, &data) == noErr) {\n\t\t\t\tconst char *ptr = reinterpret_cast<const char *>(CFDataGetBytePtr(data));\n\t\t\t\tint len = CFDataGetLength(data);\n\t\t\t\tQByteArray qba(ptr, len);\n\n\t\t\t\tQList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);\n\t\t\t\tif (! ql.isEmpty()) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tQSslSocket::addDefaultCaCertificates(ql);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tCFRelease(certs);\n\n\t\tif (found)\n\t\t\tqWarning(\"SSL: Added CA certificates from 'System Roots' store.\");\n\t}\n#elif defined(Q_OS_UNIX)\n\tQStringList qsl;\n\n#ifdef SYSTEM_CA_DIR\n\tQSslSocket::addDefaultCaCertificates(QLatin1String(MUMTEXT(SYSTEM_CA_DIR)));\n#else\n#ifdef SYSTEM_CA_BUNDLE\n\tqsl << QLatin1String(MUMTEXT(SYSTEM_CA_BUNDLE));\n#else\n#ifdef __FreeBSD__\n\tqsl << QLatin1String(\"\/usr\/local\/share\/certs\/ca-root-nss.crt\");\n#else\n\tqsl << QLatin1String(\"\/etc\/pki\/tls\/certs\/ca-bundle.crt\");\n\tqsl << QLatin1String(\"\/etc\/ssl\/certs\/ca-certificates.crt\");\n#endif\n#endif\n\n\tforeach(const QString &filename, qsl) {\n\t\tQFile f(filename);\n\t\tif (f.exists() && f.open(QIODevice::ReadOnly)) {\n\t\t\tQList<QSslCertificate> ql = QSslCertificate::fromDevice(&f, QSsl::Pem);\n\t\t\tql += QSslCertificate::fromDevice(&f, QSsl::Der);\n\t\t\tif (! ql.isEmpty()) {\n\t\t\t\tqWarning(\"SSL: Added CA certificates from '%s'\", qPrintable(filename));\n\t\t\t\tQSslSocket::addDefaultCaCertificates(ql);\n\t\t\t}\n\t\t}\n\t}\n#endif \/\/ SYSTEM_CA_DIR\n#endif \/\/ Q_OS_UNIX\n\n\tQSet<QByteArray> digests;\n\tQList<QSslCertificate> ql;\n\tforeach(const QSslCertificate &crt, QSslSocket::defaultCaCertificates()) {\n\t\tQByteArray digest = crt.digest(QCryptographicHash::Sha1);\n\t\tif (! digests.contains(digest) && crt.isValid()) {\n\t\t\tql << crt;\n\t\t\tdigests.insert(digest);\n\t\t}\n\t}\n\tQSslSocket::setDefaultCaCertificates(ql);\n#endif \/\/ NO_SYSTEM_CA_OVERRIDE\n\n#if QT_VERSION >= 0x040800\n\t\/\/ Don't perform on-demand loading of root certificates\n\tQSslSocket::addDefaultCaCertificates(QSslSocket::systemCaCertificates());\n#endif\n\n#ifdef Q_OS_WIN\n\t\/\/ Work around issue #1271.\n\t\/\/ Skype's click-to-call feature creates an enormous\n\t\/\/ amount of certificates in the Root CA store.\n\t{\n\t\tQSslConfiguration sslCfg = QSslConfiguration::defaultConfiguration();\n\t\tQList<QSslCertificate> caList = sslCfg.caCertificates();\n\n\t\tQList<QSslCertificate> filteredCaList;\n\t\tforeach (QSslCertificate cert, caList) {\n#if QT_VERSION >= 0x050000\n\t\t\tQStringList orgs = cert.subjectInfo(QSslCertificate::Organization);\n\t\t\tbool skip = false;\n\t\t\tforeach (QString ou, orgs) {\n\t\t\t\tif (ou.contains(QLatin1String(\"Skype\"), Qt::CaseInsensitive)) {\n\t\t\t\t\tskip = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (skip) {\n\t\t\t\tcontinue;\n\t\t\t}\n#else\n\t\t\tQString ou = cert.subjectInfo(QSslCertificate::Organization);\n\t\t\tif (ou.contains(QLatin1String(\"Skype\"), Qt::CaseInsensitive)) {\n\t\t\t\tcontinue;\n\t\t\t}\n#endif\n\t\t\tfilteredCaList.append(cert);\n\t\t}\n\n\t\tsslCfg.setCaCertificates(filteredCaList);\n\t\tQSslConfiguration::setDefaultConfiguration(sslCfg);\n\n\t\tqWarning(\"SSL: CA certificate filter applied. Filtered size: %i, original size: %i\", filteredCaList.size(), caList.size());\n\t}\n#endif\n}\n<commit_msg>SSL: fix build for Qt 4.<commit_after>\/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>\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 notice,\n this list of conditions and the following disclaimer.\n - Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n - Neither the name of the Mumble Developers nor the names of its\n contributors may be used to endorse or promote products derived from this\n 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 FOUNDATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"murmur_pch.h\"\n\n#include \"SSL.h\"\n\n#include \"Version.h\"\n\nQString MumbleSSL::defaultOpenSSLCipherString() {\n\treturn QLatin1String(\"EECDH+AESGCM:AES256-SHA:AES128-SHA\");\n}\n\nQList<QSslCipher> MumbleSSL::ciphersFromOpenSSLCipherString(QString cipherString) {\n\tQList<QSslCipher> chosenCiphers;\n\n\tSSL_CTX *ctx = NULL;\n\tSSL *ssl = NULL;\n\tconst SSL_METHOD *meth = NULL;\n\tint i = 0;\n\n\tQByteArray csbuf = cipherString.toLatin1();\n\tconst char *ciphers = csbuf.constData();\n\n\tmeth = SSLv23_server_method();\n\tif (meth == NULL) {\n\t\tqWarning(\"MumbleSSL: unable to get SSL method\");\n\t\tgoto out;\n\t}\n\n\tctx = SSL_CTX_new(meth);\n\tif (ctx == NULL) {\n\t\tqWarning(\"MumbleSSL: unable to allocate SSL_CTX\");\n\t\tgoto out;\n\t}\n\n\tif (!SSL_CTX_set_cipher_list(ctx, ciphers)) {\n\t\tqWarning(\"MumbleSSL: error parsing OpenSSL cipher string in ciphersFromOpenSSLCipherString\");\n\t\tgoto out;\n\t}\n\n\tssl = SSL_new(ctx);\n\tif (ssl == NULL) {\n\t\tqWarning(\"MumbleSSL: unable to create SSL object in ciphersFromOpenSSLCipherString\");\n\t\tgoto out;\n\t}\n\n\twhile (1) {\n\t\tconst char *name = SSL_get_cipher_list(ssl, i);\n\t\tif (name == NULL) {\n\t\t\tbreak;\n\t\t}\n#if QT_VERSION >= 0x050000\n\t\tQSslCipher c = QSslCipher(QString::fromLatin1(name));\n\t\tif (!c.isNull()) {\n\t\t\tchosenCiphers << c;\n\t\t}\n#else\n\t\tforeach (const QSslCipher &c, QSslSocket::supportedCiphers()) {\n\t\t\tif (c.name() == QString::fromLatin1(name)) {\n\t\t\t\tchosenCiphers << c;\n\t\t\t}\n\t\t}\n#endif\n\t\t++i;\n\t}\n\nout:\n\tSSL_CTX_free(ctx);\n\tSSL_free(ssl);\n\treturn chosenCiphers;\n}\n\nvoid MumbleSSL::addSystemCA() {\n#if QT_VERSION < 0x040700 && !defined(NO_SYSTEM_CA_OVERRIDE)\n#if defined(Q_OS_WIN)\n\tQStringList qsl;\n\tqsl << QLatin1String(\"Ca\");\n\tqsl << QLatin1String(\"Root\");\n\tqsl << QLatin1String(\"AuthRoot\");\n\tforeach(const QString &store, qsl) {\n\t\tHCERTSTORE hCertStore;\n\t\tPCCERT_CONTEXT pCertContext = NULL;\n\n\t\tbool found = false;\n\n\t\thCertStore = CertOpenSystemStore(NULL, store.utf16());\n\t\tif (! hCertStore) {\n\t\t\tqWarning(\"SSL: Failed to open CA store %s\", qPrintable(store));\n\t\t\tcontinue;\n\t\t}\n\n\t\twhile (pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext)) {\n\t\t\tQByteArray qba(reinterpret_cast<const char *>(pCertContext->pbCertEncoded), pCertContext->cbCertEncoded);\n\n\t\t\tQList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);\n\t\t\tql += QSslCertificate::fromData(qba, QSsl::Der);\n\t\t\tif (! ql.isEmpty()) {\n\t\t\t\tfound = true;\n\t\t\t\tQSslSocket::addDefaultCaCertificates(ql);\n\t\t\t}\n\t\t}\n\t\tif (found)\n\t\t\tqWarning(\"SSL: Added CA certificates from system store '%s'\", qPrintable(store));\n\n\t\tCertCloseStore(hCertStore, 0);\n\t}\n\n#elif defined(Q_OS_MAC)\n\tCFArrayRef certs = NULL;\n\tbool found = false;\n\n\tif (SecTrustCopyAnchorCertificates(&certs) == noErr) {\n\t\tint ncerts = CFArrayGetCount(certs);\n\t\tfor (int i = 0; i < ncerts; i++) {\n\t\t\tCFDataRef data = NULL;\n\n\t\t\tSecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));\n\t\t\tif (! cert)\n\t\t\t\tcontinue;\n\n\t\t\tif (SecKeychainItemExport(cert, kSecFormatX509Cert, kSecItemPemArmour, NULL, &data) == noErr) {\n\t\t\t\tconst char *ptr = reinterpret_cast<const char *>(CFDataGetBytePtr(data));\n\t\t\t\tint len = CFDataGetLength(data);\n\t\t\t\tQByteArray qba(ptr, len);\n\n\t\t\t\tQList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);\n\t\t\t\tif (! ql.isEmpty()) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tQSslSocket::addDefaultCaCertificates(ql);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tCFRelease(certs);\n\n\t\tif (found)\n\t\t\tqWarning(\"SSL: Added CA certificates from 'System Roots' store.\");\n\t}\n#elif defined(Q_OS_UNIX)\n\tQStringList qsl;\n\n#ifdef SYSTEM_CA_DIR\n\tQSslSocket::addDefaultCaCertificates(QLatin1String(MUMTEXT(SYSTEM_CA_DIR)));\n#else\n#ifdef SYSTEM_CA_BUNDLE\n\tqsl << QLatin1String(MUMTEXT(SYSTEM_CA_BUNDLE));\n#else\n#ifdef __FreeBSD__\n\tqsl << QLatin1String(\"\/usr\/local\/share\/certs\/ca-root-nss.crt\");\n#else\n\tqsl << QLatin1String(\"\/etc\/pki\/tls\/certs\/ca-bundle.crt\");\n\tqsl << QLatin1String(\"\/etc\/ssl\/certs\/ca-certificates.crt\");\n#endif\n#endif\n\n\tforeach(const QString &filename, qsl) {\n\t\tQFile f(filename);\n\t\tif (f.exists() && f.open(QIODevice::ReadOnly)) {\n\t\t\tQList<QSslCertificate> ql = QSslCertificate::fromDevice(&f, QSsl::Pem);\n\t\t\tql += QSslCertificate::fromDevice(&f, QSsl::Der);\n\t\t\tif (! ql.isEmpty()) {\n\t\t\t\tqWarning(\"SSL: Added CA certificates from '%s'\", qPrintable(filename));\n\t\t\t\tQSslSocket::addDefaultCaCertificates(ql);\n\t\t\t}\n\t\t}\n\t}\n#endif \/\/ SYSTEM_CA_DIR\n#endif \/\/ Q_OS_UNIX\n\n\tQSet<QByteArray> digests;\n\tQList<QSslCertificate> ql;\n\tforeach(const QSslCertificate &crt, QSslSocket::defaultCaCertificates()) {\n\t\tQByteArray digest = crt.digest(QCryptographicHash::Sha1);\n\t\tif (! digests.contains(digest) && crt.isValid()) {\n\t\t\tql << crt;\n\t\t\tdigests.insert(digest);\n\t\t}\n\t}\n\tQSslSocket::setDefaultCaCertificates(ql);\n#endif \/\/ NO_SYSTEM_CA_OVERRIDE\n\n#if QT_VERSION >= 0x040800\n\t\/\/ Don't perform on-demand loading of root certificates\n\tQSslSocket::addDefaultCaCertificates(QSslSocket::systemCaCertificates());\n#endif\n\n#ifdef Q_OS_WIN\n\t\/\/ Work around issue #1271.\n\t\/\/ Skype's click-to-call feature creates an enormous\n\t\/\/ amount of certificates in the Root CA store.\n\t{\n\t\tQSslConfiguration sslCfg = QSslConfiguration::defaultConfiguration();\n\t\tQList<QSslCertificate> caList = sslCfg.caCertificates();\n\n\t\tQList<QSslCertificate> filteredCaList;\n\t\tforeach (QSslCertificate cert, caList) {\n#if QT_VERSION >= 0x050000\n\t\t\tQStringList orgs = cert.subjectInfo(QSslCertificate::Organization);\n\t\t\tbool skip = false;\n\t\t\tforeach (QString ou, orgs) {\n\t\t\t\tif (ou.contains(QLatin1String(\"Skype\"), Qt::CaseInsensitive)) {\n\t\t\t\t\tskip = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (skip) {\n\t\t\t\tcontinue;\n\t\t\t}\n#else\n\t\t\tQString ou = cert.subjectInfo(QSslCertificate::Organization);\n\t\t\tif (ou.contains(QLatin1String(\"Skype\"), Qt::CaseInsensitive)) {\n\t\t\t\tcontinue;\n\t\t\t}\n#endif\n\t\t\tfilteredCaList.append(cert);\n\t\t}\n\n\t\tsslCfg.setCaCertificates(filteredCaList);\n\t\tQSslConfiguration::setDefaultConfiguration(sslCfg);\n\n\t\tqWarning(\"SSL: CA certificate filter applied. Filtered size: %i, original size: %i\", filteredCaList.size(), caList.size());\n\t}\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This Source Code Form is licensed MPL-2.0: http:\/\/mozilla.org\/MPL\/2.0\n#include \"paintwidgets.hh\"\n#include \"factory.hh\"\n#include \"painter.hh\"\n\n#define CHECK_CAIRO_STATUS(status) do { \\\n cairo_status_t ___s = (status); \\\n if (___s != CAIRO_STATUS_SUCCESS) \\\n RAPICORN_DIAG (\"%s: %s\", cairo_status_to_string (___s), #status); \\\n } while (0)\n\nnamespace Rapicorn {\n\n\/\/ == ArrowImpl ==\nArrowImpl::ArrowImpl() :\n dir_ (Direction::RIGHT)\n{}\n\nArrowImpl::~ArrowImpl()\n{}\n\nDirection\nArrowImpl::arrow_dir () const\n{\n return dir_;\n}\n\nvoid\nArrowImpl::arrow_dir (Direction dir)\n{\n dir_ = dir;\n expose();\n changed (\"arrow_dir\");\n}\n\nstatic DataKey<SizePolicy> size_policy_key;\n\nSizePolicy\nArrowImpl::size_policy () const\n{\n SizePolicy spol = get_data (&size_policy_key);\n return spol;\n}\n\nvoid\nArrowImpl::size_policy (SizePolicy spol)\n{\n if (spol == 0)\n delete_data (&size_policy_key);\n else\n set_data (&size_policy_key, spol);\n invalidate_size();\n changed (\"size_policy\");\n}\n\nvoid\nArrowImpl::size_request (Requisition &requisition)\n{\n requisition.width = 3;\n requisition.height = 3;\n}\n\nvoid\nArrowImpl::size_allocate (Allocation area, bool changed)\n{\n SizePolicy spol = size_policy();\n if (spol == SizePolicy::WIDTH_FROM_HEIGHT)\n tune_requisition (area.height, -1);\n else if (spol == SizePolicy::HEIGHT_FROM_WIDTH)\n tune_requisition (-1, area.width);\n}\n\nvoid\nArrowImpl::render (RenderContext &rcontext, const IRect &rect)\n{\n IRect ia = allocation();\n int x = ia.x, y = ia.y, width = ia.width, height = ia.height;\n if (width >= 2 && height >= 2)\n {\n cairo_t *cr = cairo_context (rcontext, rect);\n CPainter painter (cr);\n painter.draw_dir_arrow (x, y, width, height, foreground(), dir_);\n }\n}\n\nstatic const WidgetFactory<ArrowImpl> arrow_factory (\"Rapicorn::Arrow\");\n\n\/\/ == DotGrid ==\nDotGridImpl::DotGridImpl() :\n normal_dot_ (DrawFrame::IN),\n active_dot_ (DrawFrame::IN),\n n_hdots_ (1), n_vdots_ (1),\n right_padding_dots_ (0), top_padding_dots_ (0),\n left_padding_dots_ (0), bottom_padding_dots_ (0)\n{}\n\nDotGridImpl::~DotGridImpl()\n{}\n\nDrawFrame\nDotGridImpl::dot_type () const\n{\n RAPICORN_ASSERT_UNREACHED();\n}\n\nvoid\nDotGridImpl::dot_type (DrawFrame ft)\n{\n normal_dot (ft);\n active_dot (ft);\n}\n\nDrawFrame\nDotGridImpl::current_dot ()\n{\n return ancestry_active() ? active_dot() : normal_dot();\n}\n\nstatic inline int\nu31 (int v)\n{\n return CLAMP (v, 0, INT_MAX);\n}\n\nvoid\nDotGridImpl::active_dot (DrawFrame ft)\n{\n active_dot_ = ft;\n expose();\n changed (\"active_dot\");\n}\n\nDrawFrame\nDotGridImpl::active_dot () const\n{\n return active_dot_;\n}\n\nvoid\nDotGridImpl::normal_dot (DrawFrame ft)\n{\n normal_dot_ = ft;\n expose();\n changed (\"normal_dot\");\n}\n\nDrawFrame\nDotGridImpl::normal_dot () const\n{\n return normal_dot_;\n}\n\nvoid\nDotGridImpl::n_hdots (int num)\n{\n n_hdots_ = u31 (num);\n expose();\n changed (\"n_hdots\");\n}\n\nint\nDotGridImpl::n_hdots () const\n{\n return n_hdots_;\n}\n\nvoid\nDotGridImpl::n_vdots (int num)\n{\n n_vdots_ = u31 (num);\n expose();\n changed (\"n_vdots\");\n}\n\nint\nDotGridImpl::n_vdots () const\n{\n return n_vdots_;\n}\n\nint\nDotGridImpl::right_padding_dots () const\n{\n return right_padding_dots_;\n}\n\nvoid\nDotGridImpl::right_padding_dots (int c)\n{\n right_padding_dots_ = u31 (c);\n expose();\n changed (\"right_padding_dots\");\n}\n\nint\nDotGridImpl::top_padding_dots () const\n{\n return top_padding_dots_;\n}\n\nvoid\nDotGridImpl::top_padding_dots (int c)\n{\n top_padding_dots_ = u31 (c);\n expose();\n changed (\"top_padding_dots\");\n}\n\nint\nDotGridImpl::left_padding_dots () const\n{\n return left_padding_dots_;\n}\n\nvoid\nDotGridImpl::left_padding_dots (int c)\n{\n left_padding_dots_ = u31 (c);\n expose();\n changed (\"left_padding_dots\");\n}\n\nint\nDotGridImpl::bottom_padding_dots () const\n{\n return bottom_padding_dots_;\n}\n\nvoid\nDotGridImpl::bottom_padding_dots (int c)\n{\n bottom_padding_dots_ = u31 (c);\n expose();\n changed (\"bottom_padding_dots\");\n}\n\nvoid\nDotGridImpl::size_request (Requisition &requisition)\n{\n const uint ythick = 1, xthick = 1;\n requisition.width = n_hdots_ * (xthick + xthick) + MAX (n_hdots_ - 1, 0) * xthick;\n requisition.height = n_vdots_ * (ythick + ythick) + MAX (n_vdots_ - 1, 0) * ythick;\n requisition.width += (right_padding_dots_ + left_padding_dots_) * 3 * xthick;\n requisition.height += (top_padding_dots_ + bottom_padding_dots_) * 3 * ythick;\n}\n\nvoid\nDotGridImpl::size_allocate (Allocation area, bool changed)\n{}\n\nvoid\nDotGridImpl::render (RenderContext &rcontext, const IRect &rect)\n{\n const int ythick = 1, xthick = 1;\n int n_hdots = n_hdots_, n_vdots = n_vdots_;\n const IRect ia = allocation();\n int x = ia.x, y = ia.y, width = ia.width, height = ia.height;\n const int rq_width = n_hdots_ * (xthick + xthick) + MAX (n_hdots - 1, 0) * xthick;\n const int rq_height = n_vdots_ * (ythick + ythick) + MAX (n_vdots - 1, 0) * ythick;\n \/* split up extra width *\/\n const uint hpadding = right_padding_dots_ + left_padding_dots_;\n const double halign = hpadding ? left_padding_dots_ * 1.0 \/ hpadding : 0.5;\n if (rq_width < width)\n x += ifloor ((width - rq_width) * halign);\n \/* split up extra height *\/\n const uint vpadding = top_padding_dots_ + bottom_padding_dots_;\n const double valign = vpadding ? bottom_padding_dots_ * 1.0 \/ vpadding : 0.5;\n if (rq_height < height)\n y += ifloor ((height - rq_height) * valign);\n \/* draw dots *\/\n if (width >= 2 * xthick && height >= 2 * ythick && n_hdots && n_vdots)\n {\n \/* limit n_hdots *\/\n if (rq_width > width)\n {\n const int w = width - 2 * xthick; \/\/ dot1\n n_hdots = 1 + w \/ (3 * xthick);\n }\n \/* limit n_vdots *\/\n if (rq_height > height)\n {\n const int h = height - 2 * ythick; \/\/ dot1\n n_vdots = 1 + h \/ (3 * ythick);\n }\n cairo_t *cr = cairo_context (rcontext, rect);\n CPainter rp (cr);\n for (int j = 0; j < n_vdots; j++)\n {\n int xtmp = 0;\n for (int i = 0; i < n_hdots; i++)\n {\n rp.draw_shaded_rect (x + xtmp, y + 2 * ythick - 1, dark_shadow(),\n x + xtmp + 2 * xthick - 1, y, light_glint());\n xtmp += 3 * xthick;\n }\n y += 3 * ythick;\n }\n }\n}\n\nstatic const WidgetFactory<DotGridImpl> dot_grid_factory (\"Rapicorn::DotGrid\");\n\n\/\/ == DrawableImpl ==\nDrawableImpl::DrawableImpl() :\n x_ (0), y_ (0)\n{}\n\nvoid\nDrawableImpl::size_request (Requisition &requisition)\n{\n requisition.width = 320;\n requisition.height = 200;\n}\n\nvoid\nDrawableImpl::size_allocate (Allocation area, bool changed)\n{\n if (false) \/\/ clear out, can lead to flicker\n {\n pixbuf_ = Pixbuf();\n x_ = 0;\n y_ = 0;\n }\n sig_redraw.emit (area.x, area.y, area.width, area.height);\n}\n\nvoid\nDrawableImpl::draw_rect (int x, int y, const Pixbuf &pixbuf)\n{\n const Allocation &area = allocation();\n const size_t rowstride = pixbuf.width();\n if (x >= area.x && y >= area.y &&\n x + pixbuf.width() <= area.x + area.width &&\n y + pixbuf.height() <= area.y + area.height &&\n rowstride * pixbuf.height() <= pixbuf.pixels.size())\n {\n x_ = x;\n y_ = y;\n pixbuf_ = pixbuf;\n }\n else if (pixbuf_.width() > 0)\n {\n pixbuf_ = Pixbuf();\n x_ = 0;\n y_ = 0;\n }\n expose();\n}\n\nvoid\nDrawableImpl::render (RenderContext &rcontext, const IRect &rect)\n{\n const uint size = 10;\n const Allocation &area = allocation();\n cairo_t *cr = cairo_context (rcontext, rect);\n \/\/ checkerboard pattern\n if (true)\n {\n cairo_save (cr);\n cairo_surface_t *ps = cairo_surface_create_similar (cairo_get_target (cr), CAIRO_CONTENT_COLOR, 2 * size, 2 * size);\n cairo_t *pc = cairo_create (ps);\n cairo_set_source_rgb (pc, 1.0, 1.0, 1.0);\n cairo_rectangle (pc, 0, 0, size, size);\n cairo_rectangle (pc, size, size, size, size);\n cairo_fill (pc);\n cairo_set_source_rgb (pc, 0.9, 0.9, 0.9);\n cairo_rectangle (pc, 0, size, size, size);\n cairo_rectangle (pc, size, 0, size, size);\n cairo_fill (pc);\n cairo_destroy (pc);\n cairo_pattern_t *pat = cairo_pattern_create_for_surface (ps);\n cairo_surface_destroy (ps);\n cairo_pattern_set_extend (pat, CAIRO_EXTEND_REPEAT);\n \/\/ render pattern\n cairo_rectangle (cr, area.x, area.y, area.width, area.height);\n cairo_clip (cr);\n cairo_translate (cr, area.x, area.y + area.height);\n cairo_set_source (cr, pat);\n cairo_paint (cr);\n cairo_pattern_destroy (pat);\n cairo_restore (cr);\n }\n \/\/ handle user draw\n if (pixbuf_.width() > 0 && pixbuf_.height() > 0)\n {\n const int rowstride = pixbuf_.width();\n cairo_surface_t *surface = cairo_image_surface_create_for_data ((uint8*) pixbuf_.pixels.data(), CAIRO_FORMAT_ARGB32,\n pixbuf_.width(), pixbuf_.height(), rowstride * 4);\n CHECK_CAIRO_STATUS (cairo_surface_status (surface));\n cairo_set_source_surface (cr, surface, x_, y_);\n cairo_paint (cr);\n cairo_surface_destroy (surface);\n }\n}\n\nstatic const WidgetFactory<DrawableImpl> drawable_factory (\"Rapicorn::Drawable\");\n\n} \/\/ Rapicorn\n<commit_msg>UI: DrawableImpl: use invalidate_content() to avoid missing exposes<commit_after>\/\/ This Source Code Form is licensed MPL-2.0: http:\/\/mozilla.org\/MPL\/2.0\n#include \"paintwidgets.hh\"\n#include \"factory.hh\"\n#include \"painter.hh\"\n\n#define CHECK_CAIRO_STATUS(status) do { \\\n cairo_status_t ___s = (status); \\\n if (___s != CAIRO_STATUS_SUCCESS) \\\n RAPICORN_DIAG (\"%s: %s\", cairo_status_to_string (___s), #status); \\\n } while (0)\n\nnamespace Rapicorn {\n\n\/\/ == ArrowImpl ==\nArrowImpl::ArrowImpl() :\n dir_ (Direction::RIGHT)\n{}\n\nArrowImpl::~ArrowImpl()\n{}\n\nDirection\nArrowImpl::arrow_dir () const\n{\n return dir_;\n}\n\nvoid\nArrowImpl::arrow_dir (Direction dir)\n{\n dir_ = dir;\n expose();\n changed (\"arrow_dir\");\n}\n\nstatic DataKey<SizePolicy> size_policy_key;\n\nSizePolicy\nArrowImpl::size_policy () const\n{\n SizePolicy spol = get_data (&size_policy_key);\n return spol;\n}\n\nvoid\nArrowImpl::size_policy (SizePolicy spol)\n{\n if (spol == 0)\n delete_data (&size_policy_key);\n else\n set_data (&size_policy_key, spol);\n invalidate_size();\n changed (\"size_policy\");\n}\n\nvoid\nArrowImpl::size_request (Requisition &requisition)\n{\n requisition.width = 3;\n requisition.height = 3;\n}\n\nvoid\nArrowImpl::size_allocate (Allocation area, bool changed)\n{\n SizePolicy spol = size_policy();\n if (spol == SizePolicy::WIDTH_FROM_HEIGHT)\n tune_requisition (area.height, -1);\n else if (spol == SizePolicy::HEIGHT_FROM_WIDTH)\n tune_requisition (-1, area.width);\n}\n\nvoid\nArrowImpl::render (RenderContext &rcontext, const IRect &rect)\n{\n IRect ia = allocation();\n int x = ia.x, y = ia.y, width = ia.width, height = ia.height;\n if (width >= 2 && height >= 2)\n {\n cairo_t *cr = cairo_context (rcontext, rect);\n CPainter painter (cr);\n painter.draw_dir_arrow (x, y, width, height, foreground(), dir_);\n }\n}\n\nstatic const WidgetFactory<ArrowImpl> arrow_factory (\"Rapicorn::Arrow\");\n\n\/\/ == DotGrid ==\nDotGridImpl::DotGridImpl() :\n normal_dot_ (DrawFrame::IN),\n active_dot_ (DrawFrame::IN),\n n_hdots_ (1), n_vdots_ (1),\n right_padding_dots_ (0), top_padding_dots_ (0),\n left_padding_dots_ (0), bottom_padding_dots_ (0)\n{}\n\nDotGridImpl::~DotGridImpl()\n{}\n\nDrawFrame\nDotGridImpl::dot_type () const\n{\n RAPICORN_ASSERT_UNREACHED();\n}\n\nvoid\nDotGridImpl::dot_type (DrawFrame ft)\n{\n normal_dot (ft);\n active_dot (ft);\n}\n\nDrawFrame\nDotGridImpl::current_dot ()\n{\n return ancestry_active() ? active_dot() : normal_dot();\n}\n\nstatic inline int\nu31 (int v)\n{\n return CLAMP (v, 0, INT_MAX);\n}\n\nvoid\nDotGridImpl::active_dot (DrawFrame ft)\n{\n active_dot_ = ft;\n expose();\n changed (\"active_dot\");\n}\n\nDrawFrame\nDotGridImpl::active_dot () const\n{\n return active_dot_;\n}\n\nvoid\nDotGridImpl::normal_dot (DrawFrame ft)\n{\n normal_dot_ = ft;\n expose();\n changed (\"normal_dot\");\n}\n\nDrawFrame\nDotGridImpl::normal_dot () const\n{\n return normal_dot_;\n}\n\nvoid\nDotGridImpl::n_hdots (int num)\n{\n n_hdots_ = u31 (num);\n expose();\n changed (\"n_hdots\");\n}\n\nint\nDotGridImpl::n_hdots () const\n{\n return n_hdots_;\n}\n\nvoid\nDotGridImpl::n_vdots (int num)\n{\n n_vdots_ = u31 (num);\n expose();\n changed (\"n_vdots\");\n}\n\nint\nDotGridImpl::n_vdots () const\n{\n return n_vdots_;\n}\n\nint\nDotGridImpl::right_padding_dots () const\n{\n return right_padding_dots_;\n}\n\nvoid\nDotGridImpl::right_padding_dots (int c)\n{\n right_padding_dots_ = u31 (c);\n expose();\n changed (\"right_padding_dots\");\n}\n\nint\nDotGridImpl::top_padding_dots () const\n{\n return top_padding_dots_;\n}\n\nvoid\nDotGridImpl::top_padding_dots (int c)\n{\n top_padding_dots_ = u31 (c);\n expose();\n changed (\"top_padding_dots\");\n}\n\nint\nDotGridImpl::left_padding_dots () const\n{\n return left_padding_dots_;\n}\n\nvoid\nDotGridImpl::left_padding_dots (int c)\n{\n left_padding_dots_ = u31 (c);\n expose();\n changed (\"left_padding_dots\");\n}\n\nint\nDotGridImpl::bottom_padding_dots () const\n{\n return bottom_padding_dots_;\n}\n\nvoid\nDotGridImpl::bottom_padding_dots (int c)\n{\n bottom_padding_dots_ = u31 (c);\n expose();\n changed (\"bottom_padding_dots\");\n}\n\nvoid\nDotGridImpl::size_request (Requisition &requisition)\n{\n const uint ythick = 1, xthick = 1;\n requisition.width = n_hdots_ * (xthick + xthick) + MAX (n_hdots_ - 1, 0) * xthick;\n requisition.height = n_vdots_ * (ythick + ythick) + MAX (n_vdots_ - 1, 0) * ythick;\n requisition.width += (right_padding_dots_ + left_padding_dots_) * 3 * xthick;\n requisition.height += (top_padding_dots_ + bottom_padding_dots_) * 3 * ythick;\n}\n\nvoid\nDotGridImpl::size_allocate (Allocation area, bool changed)\n{}\n\nvoid\nDotGridImpl::render (RenderContext &rcontext, const IRect &rect)\n{\n const int ythick = 1, xthick = 1;\n int n_hdots = n_hdots_, n_vdots = n_vdots_;\n const IRect ia = allocation();\n int x = ia.x, y = ia.y, width = ia.width, height = ia.height;\n const int rq_width = n_hdots_ * (xthick + xthick) + MAX (n_hdots - 1, 0) * xthick;\n const int rq_height = n_vdots_ * (ythick + ythick) + MAX (n_vdots - 1, 0) * ythick;\n \/* split up extra width *\/\n const uint hpadding = right_padding_dots_ + left_padding_dots_;\n const double halign = hpadding ? left_padding_dots_ * 1.0 \/ hpadding : 0.5;\n if (rq_width < width)\n x += ifloor ((width - rq_width) * halign);\n \/* split up extra height *\/\n const uint vpadding = top_padding_dots_ + bottom_padding_dots_;\n const double valign = vpadding ? bottom_padding_dots_ * 1.0 \/ vpadding : 0.5;\n if (rq_height < height)\n y += ifloor ((height - rq_height) * valign);\n \/* draw dots *\/\n if (width >= 2 * xthick && height >= 2 * ythick && n_hdots && n_vdots)\n {\n \/* limit n_hdots *\/\n if (rq_width > width)\n {\n const int w = width - 2 * xthick; \/\/ dot1\n n_hdots = 1 + w \/ (3 * xthick);\n }\n \/* limit n_vdots *\/\n if (rq_height > height)\n {\n const int h = height - 2 * ythick; \/\/ dot1\n n_vdots = 1 + h \/ (3 * ythick);\n }\n cairo_t *cr = cairo_context (rcontext, rect);\n CPainter rp (cr);\n for (int j = 0; j < n_vdots; j++)\n {\n int xtmp = 0;\n for (int i = 0; i < n_hdots; i++)\n {\n rp.draw_shaded_rect (x + xtmp, y + 2 * ythick - 1, dark_shadow(),\n x + xtmp + 2 * xthick - 1, y, light_glint());\n xtmp += 3 * xthick;\n }\n y += 3 * ythick;\n }\n }\n}\n\nstatic const WidgetFactory<DotGridImpl> dot_grid_factory (\"Rapicorn::DotGrid\");\n\n\/\/ == DrawableImpl ==\nDrawableImpl::DrawableImpl() :\n x_ (0), y_ (0)\n{}\n\nvoid\nDrawableImpl::size_request (Requisition &requisition)\n{\n requisition.width = 320;\n requisition.height = 200;\n}\n\nvoid\nDrawableImpl::size_allocate (Allocation area, bool changed)\n{\n if (false) \/\/ clear out, can lead to flicker\n {\n pixbuf_ = Pixbuf();\n x_ = 0;\n y_ = 0;\n }\n sig_redraw.emit (area.x, area.y, area.width, area.height);\n}\n\nvoid\nDrawableImpl::draw_rect (int x, int y, const Pixbuf &pixbuf)\n{\n const Allocation &area = allocation();\n const size_t rowstride = pixbuf.width();\n if (x >= area.x && y >= area.y &&\n x + pixbuf.width() <= area.x + area.width &&\n y + pixbuf.height() <= area.y + area.height &&\n rowstride * pixbuf.height() <= pixbuf.pixels.size())\n {\n x_ = x;\n y_ = y;\n pixbuf_ = pixbuf;\n }\n else if (pixbuf_.width() > 0)\n {\n pixbuf_ = Pixbuf();\n x_ = 0;\n y_ = 0;\n }\n invalidate_content();\n}\n\nvoid\nDrawableImpl::render (RenderContext &rcontext, const IRect &rect)\n{\n const uint size = 10;\n const Allocation &area = allocation();\n cairo_t *cr = cairo_context (rcontext, rect);\n \/\/ checkerboard pattern\n if (true)\n {\n cairo_save (cr);\n cairo_surface_t *ps = cairo_surface_create_similar (cairo_get_target (cr), CAIRO_CONTENT_COLOR, 2 * size, 2 * size);\n cairo_t *pc = cairo_create (ps);\n cairo_set_source_rgb (pc, 1.0, 1.0, 1.0);\n cairo_rectangle (pc, 0, 0, size, size);\n cairo_rectangle (pc, size, size, size, size);\n cairo_fill (pc);\n cairo_set_source_rgb (pc, 0.9, 0.9, 0.9);\n cairo_rectangle (pc, 0, size, size, size);\n cairo_rectangle (pc, size, 0, size, size);\n cairo_fill (pc);\n cairo_destroy (pc);\n cairo_pattern_t *pat = cairo_pattern_create_for_surface (ps);\n cairo_surface_destroy (ps);\n cairo_pattern_set_extend (pat, CAIRO_EXTEND_REPEAT);\n \/\/ render pattern\n cairo_rectangle (cr, area.x, area.y, area.width, area.height);\n cairo_clip (cr);\n cairo_translate (cr, area.x, area.y + area.height);\n cairo_set_source (cr, pat);\n cairo_paint (cr);\n cairo_pattern_destroy (pat);\n cairo_restore (cr);\n }\n \/\/ handle user draw\n if (pixbuf_.width() > 0 && pixbuf_.height() > 0)\n {\n const int rowstride = pixbuf_.width();\n cairo_surface_t *surface = cairo_image_surface_create_for_data ((uint8*) pixbuf_.pixels.data(), CAIRO_FORMAT_ARGB32,\n pixbuf_.width(), pixbuf_.height(), rowstride * 4);\n CHECK_CAIRO_STATUS (cairo_surface_status (surface));\n cairo_set_source_surface (cr, surface, x_, y_);\n cairo_paint (cr);\n cairo_surface_destroy (surface);\n }\n}\n\nstatic const WidgetFactory<DrawableImpl> drawable_factory (\"Rapicorn::Drawable\");\n\n} \/\/ Rapicorn\n<|endoftext|>"} {"text":"<commit_before>\/\/ Slit.hh for Fluxbox\n\/\/ Copyright (c) 2002 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/\n\/\/ Slit.hh for Blackbox - an X11 Window manager\n\/\/ Copyright (c) 1997 - 2000 Brad Hughes (bhughes at tcac.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the \n\/\/ Software is 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 \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 \n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n\/\/ DEALINGS IN THE SOFTWARE.\n\t\n\/\/\/ $Id: Slit.hh,v 1.19 2003\/02\/18 15:11:08 rathnor Exp $\n\n#ifndef\t SLIT_HH\n#define\t SLIT_HH\n\n#include \"Menu.hh\"\n#include \"FbWindow.hh\"\n#include \"Timer.hh\"\n#include \"XLayerItem.hh\"\n#include \"LayerMenu.hh\"\n\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n\n#include <list>\n#include <string>\n#include <memory>\nclass BScreen;\nclass SlitClient;\n\n\/\/\/ Handles dock apps\nclass Slit : public FbTk::TimeoutHandler, public FbTk::EventHandler {\npublic:\n \n \/**\n Client alignment\n *\/\n enum Direction { VERTICAL = 1, HORIZONTAL };\n \/**\n Screen placement\n *\/\n enum Placement { TOPLEFT = 1, CENTERLEFT, BOTTOMLEFT, TOPCENTER, BOTTOMCENTER,\n TOPRIGHT, CENTERRIGHT, BOTTOMRIGHT };\n\n explicit Slit(BScreen &screen, FbTk::XLayer &layer, const char *filename = 0);\n virtual ~Slit();\n\n inline bool isHidden() const { return hidden; }\n inline bool doAutoHide() const { return do_auto_hide; }\n inline Direction direction() const { return m_direction; }\n inline Placement placement() const { return m_placement; }\n FbTk::Menu &menu() { return slitmenu; }\n\n inline Window getWindowID() const { return frame.window.window(); }\n\n inline int x() const { return ((hidden) ? frame.x_hidden : frame.x); }\n inline int y() const { return ((hidden) ? frame.y_hidden : frame.y); }\n\n inline unsigned int width() const { return frame.width; }\n inline unsigned int height() const { return frame.height; }\n\n void setDirection(Direction dir);\n void setPlacement(Placement place);\n void setAutoHide(bool val);\n void addClient(Window clientwin);\n void removeClient(Window clientwin, bool = true);\n void reconfigure();\n void reposition();\n void shutdown();\n \/\/\/ save clients name in a file\n void saveClientList();\n \/\/\/ cycle slit clients up one step\n void cycleClientsUp();\n \/\/\/ cycle slit clients down one step\n void cycleClientsDown();\n\n BScreen *screen() { return m_screen; }\n const BScreen *screen() const { return m_screen; }\n \/**\n @name eventhandlers\n *\/\n \/\/@{\n void handleEvent(XEvent &event);\n void buttonPressEvent(XButtonEvent &event);\n void enterNotifyEvent(XCrossingEvent &event);\n void leaveNotifyEvent(XCrossingEvent &event);\n void configureRequestEvent(XConfigureRequestEvent &event);\n \/\/@}\n\t\n void moveToLayer(int layernum) { m_layeritem->moveToLayer(layernum); }\n FbTk::XLayerItem &getLayerItem() { return *m_layeritem; }\n\n virtual void timeout();\n\n\nprivate:\n void setupMenu();\n\t\n void removeClient(SlitClient *client, bool remap, bool destroy);\n void loadClientList(const char *filename);\n void updateClientmenu();\n\n bool hidden, do_auto_hide;\n Direction m_direction;\n Placement m_placement;\n\n BScreen *m_screen;\n FbTk::Timer timer;\n\n typedef std::list<SlitClient *> SlitClients;\n\n SlitClients clientList;\n FbTk::Menu slitmenu, placement_menu, clientlist_menu;\n LayerMenu<Slit> *slit_layermenu;\n std::string clientListPath;\n std::string m_filename;\n\n struct frame {\n Pixmap pixmap;\n FbTk::FbWindow window;\n\n int x, y, x_hidden, y_hidden;\n unsigned int width, height;\n } frame;\n \/\/ for KDE\n Atom kwm1_dockwindow, kwm2_dockwindow;\n\n FbTk::XLayerItem *m_layeritem;\n};\n\n\n#endif \/\/ SLIT_HH\n<commit_msg>minor cleaning<commit_after>\/\/ Slit.hh for Fluxbox\n\/\/ Copyright (c) 2002 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/\n\/\/ Slit.hh for Blackbox - an X11 Window manager\n\/\/ Copyright (c) 1997 - 2000 Brad Hughes (bhughes at tcac.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the \n\/\/ Software is 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 \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 \n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n\/\/ DEALINGS IN THE SOFTWARE.\n\t\n\/\/\/ $Id: Slit.hh,v 1.20 2003\/02\/20 16:38:17 fluxgen Exp $\n\n#ifndef\t SLIT_HH\n#define\t SLIT_HH\n\n#include \"Menu.hh\"\n#include \"FbWindow.hh\"\n#include \"Timer.hh\"\n#include \"XLayerItem.hh\"\n#include \"LayerMenu.hh\"\n\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n\n#include <list>\n#include <string>\n#include <memory>\n\nclass BScreen;\nclass SlitClient;\n\n\/\/\/ Handles dock apps\nclass Slit : public FbTk::TimeoutHandler, public FbTk::EventHandler {\npublic:\n \n \/**\n Client alignment\n *\/\n enum Direction { VERTICAL = 1, HORIZONTAL };\n \/**\n Screen placement\n *\/\n enum Placement { TOPLEFT = 1, CENTERLEFT, BOTTOMLEFT, TOPCENTER, BOTTOMCENTER,\n TOPRIGHT, CENTERRIGHT, BOTTOMRIGHT };\n\n explicit Slit(BScreen &screen, FbTk::XLayer &layer, const char *filename = 0);\n virtual ~Slit();\n\n inline bool isHidden() const { return hidden; }\n inline bool doAutoHide() const { return do_auto_hide; }\n inline Direction direction() const { return m_direction; }\n inline Placement placement() const { return m_placement; }\n FbTk::Menu &menu() { return slitmenu; }\n\n inline Window getWindowID() const { return frame.window.window(); }\n\n inline int x() const { return ((hidden) ? frame.x_hidden : frame.x); }\n inline int y() const { return ((hidden) ? frame.y_hidden : frame.y); }\n\n inline unsigned int width() const { return frame.width; }\n inline unsigned int height() const { return frame.height; }\n\n void setDirection(Direction dir);\n void setPlacement(Placement place);\n void setAutoHide(bool val);\n void addClient(Window clientwin);\n void removeClient(Window clientwin, bool = true);\n void reconfigure();\n void reposition();\n void shutdown();\n \/\/\/ save clients name in a file\n void saveClientList();\n \/\/\/ cycle slit clients up one step\n void cycleClientsUp();\n \/\/\/ cycle slit clients down one step\n void cycleClientsDown();\n\n BScreen &screen() { return m_screen; }\n const BScreen &screen() const { return m_screen; }\n \/**\n @name eventhandlers\n *\/\n \/\/@{\n void handleEvent(XEvent &event);\n void buttonPressEvent(XButtonEvent &event);\n void enterNotifyEvent(XCrossingEvent &event);\n void leaveNotifyEvent(XCrossingEvent &event);\n void configureRequestEvent(XConfigureRequestEvent &event);\n \/\/@}\n\t\n void moveToLayer(int layernum) { m_layeritem->moveToLayer(layernum); }\n FbTk::XLayerItem &getLayerItem() { return *m_layeritem; }\n\n virtual void timeout();\n\n\nprivate:\n void setupMenu();\n\t\n void removeClient(SlitClient *client, bool remap, bool destroy);\n void loadClientList(const char *filename);\n void updateClientmenu();\n\n bool hidden, do_auto_hide;\n Direction m_direction;\n Placement m_placement;\n\n BScreen &m_screen;\n FbTk::Timer timer;\n\n typedef std::list<SlitClient *> SlitClients;\n\n SlitClients clientList;\n FbTk::Menu slitmenu, placement_menu, clientlist_menu;\n std::auto_ptr<LayerMenu<Slit> > slit_layermenu;\n std::string clientListPath;\n std::string m_filename;\n\n struct frame {\n Pixmap pixmap;\n FbTk::FbWindow window;\n\n int x, y, x_hidden, y_hidden;\n unsigned int width, height;\n } frame;\n \/\/ for KDE\n Atom kwm1_dockwindow, kwm2_dockwindow;\n\n std::auto_ptr<FbTk::XLayerItem> m_layeritem;\n};\n\n\n#endif \/\/ SLIT_HH\n<|endoftext|>"} {"text":"<commit_before>#include \"kaynesgameoflife.hpp\"\n#include <MINX\/Graphics\/Color.hpp>\n#include <MINX\/Graphics\/GameWindow.hpp>\n#include <MINX\/Graphics\/TextureBatch.hpp>\n#include <MINX\/Graphics\/ShaderFactory.hpp>\n\nusing namespace KayneGameOfLife;\nusing namespace MINX;\nusing namespace MINX::Graphics;\n\nbool* map;\nTextureBatch* texBatch;\nconst int tileWidth = 32, tileHeight = 32;\n\nGameOfLife::GameOfLife() : Game()\n{\n\t\/\/This is the constructor. Put stuff here that should happen when the Game is created.\n\n\tGame::SetVideoOptions(640, 480, false, \"kaynes-game-of-life\");\n}\n\nvoid GameOfLife::Initialize()\n{\n\t\/\/Put stuff here that should happen when the Game is initialized.\n\t\n\tGameWindow::sizeLocked = true;\n\tint width = GameWindow::GetWidth()\/tileWidth;\n\tint height = GameWindow::GetHeight()\/tileHeight;\n\tmap = (bool*)malloc(width * height);\n\tfor(int y = 0; y < height; ++y)\n\t{\n\t\tfor(int x = 0; x < width; ++x)\n\t\t{\n\t\t\tmap[y * width + x] = Math::random(0, 1, 2);\n\t\t}\n\t}\n\n\tGame::Initialize();\n\n\ttexBatch = new TextureBatch(ShaderFactory::GetInstance()->GetShaderAtIndex(0));\n}\n\nvoid GameOfLife::LoadContent()\n{\n\t\/\/Put stuff here that loads content for your game.\n\tGame::LoadContent();\n}\n\nvoid GameOfLife::UnloadContent()\n{\n\t\/\/Put stuff here that unloads content from your game.\n\n\tfree(map);\n\n\tGame::UnloadContent();\n}\n\nvoid GameOfLife::Update(GameTime * gameTime)\n{\n\t\/\/Put stuff here to update the logic in your game each tick.\n\tGame::Update(gameTime);\n}\n\nvoid GameOfLife::Draw(GameTime * gameTime)\n{\n\tSetRenderTarget(NULL, Graphics::Color::CornflowerBlue);\n\n\tint width = GameWindow::GetWidth()\/tileWidth;\n\tint height = GameWindow::GetHeight()\/tileHeight;\n\t\n\tfor(int y = 0; y < height; ++y)\n\t{\n\t\tfor(int x = 0; x < width; ++x)\n\t\t{\n\t\t\ttexBatch->DrawPrimitiveRectangle(Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight), map[y * width + x] ? Color::Black : Color::Salmon);\n\t\t}\n\t}\n\n\ttexBatch->DrawLoadedTextures();\n\n\t\/\/Put stuff here to draw your game each frame.\n\tGame::Draw(gameTime);\n}<commit_msg>Implemented rules of the game<commit_after>#include \"kaynesgameoflife.hpp\"\n#include <MINX\/Graphics\/Color.hpp>\n#include <MINX\/Graphics\/GameWindow.hpp>\n#include <MINX\/Graphics\/TextureBatch.hpp>\n#include <MINX\/Graphics\/ShaderFactory.hpp>\n\nusing namespace KayneGameOfLife;\nusing namespace MINX;\nusing namespace MINX::Graphics;\n\nbool* map;\nTextureBatch* texBatch;\nconst int tileWidth = 16, tileHeight = 16;\n\ndouble elapsedTime = 0.0;\ndouble timeLimit = 0.5;\n\n\nbool* updateCells(bool* board, int width, int height);\nint calculateLiveNeighbors(bool* board, int x, int y, int width, int height);\n\nGameOfLife::GameOfLife() : Game()\n{\n\t\/\/This is the constructor. Put stuff here that should happen when the Game is created.\n\tsrand(time(NULL));\n\tGame::SetVideoOptions(640, 480, false, \"kaynes-game-of-life\");\n}\n\nvoid GameOfLife::Initialize()\n{\n\t\/\/Put stuff here that should happen when the Game is initialized.\n\t\n\tGameWindow::sizeLocked = true;\n\tint width = GameWindow::GetWidth()\/tileWidth;\n\tint height = GameWindow::GetHeight()\/tileHeight;\n\tmap = (bool*)malloc(width * height);\n\tfor(int y = 0; y < height; ++y)\n\t{\n\t\tfor(int x = 0; x < width; ++x)\n\t\t{\n\t\t\tmap[y * width + x] = Math::random(0, 1, 2);\n\t\t}\n\t}\n\n\tGame::Initialize();\n\n\ttexBatch = new TextureBatch(ShaderFactory::GetInstance()->GetShaderAtIndex(0));\n}\n\nvoid GameOfLife::LoadContent()\n{\n\t\/\/Put stuff here that loads content for your game.\n\tGame::LoadContent();\n}\n\nvoid GameOfLife::UnloadContent()\n{\n\t\/\/Put stuff here that unloads content from your game.\n\n\tfree(map);\n\n\tGame::UnloadContent();\n}\n\nvoid GameOfLife::Update(GameTime * gameTime)\n{\n\telapsedTime += gameTime->GetDeltaTimeSeconds();\n\n\tif(elapsedTime >= timeLimit)\n\t{\n\t\telapsedTime = 0.0;\n\n\t\tmap = updateCells(map, GameWindow::GetWidth()\/tileWidth, GameWindow::GetHeight()\/tileHeight);\n\t}\n\t\/\/Put stuff here to update the logic in your game each tick.\n\tGame::Update(gameTime);\n}\n\nvoid GameOfLife::Draw(GameTime * gameTime)\n{\n\tSetRenderTarget(NULL, Graphics::Color::CornflowerBlue);\n\n\tint width = GameWindow::GetWidth()\/tileWidth;\n\tint height = GameWindow::GetHeight()\/tileHeight;\n\t\n\tfor(int y = 0; y < height; ++y)\n\t{\n\t\tfor(int x = 0; x < width; ++x)\n\t\t{\n\t\t\ttexBatch->DrawPrimitiveRectangle(\n\t\t\t\tRectangle(\n\t\t\t\t\tx * tileWidth,\n\t\t\t\t\ty * tileHeight,\n\t\t\t\t\ttileWidth,\n\t\t\t\t\ttileHeight),\n\t\t\t\tmap[y * width + x] ? Color::Black : Color::Salmon);\n\t\t}\n\t}\n\n\ttexBatch->DrawLoadedTextures();\n\n\t\/\/Put stuff here to draw your game each frame.\n\tGame::Draw(gameTime);\n}\n\nbool* updateCells(bool* board, int width, int height)\n{\n\tbool* newBoard = (bool*)malloc(width * height);\n\tfor(int y = 0; y < height; ++y)\n\t{\n\t\tfor(int x = 0; x < width; ++x)\n\t\t{\n\t\t\tint liveNeighbors = calculateLiveNeighbors(board, x, y, width, height);\n\t\t\tif(board[y * width + x] && (liveNeighbors < 2) || liveNeighbors > 3)\n\t\t\t{\n\t\t\t\tnewBoard[y * width + x] = false;\n\t\t\t}\n\t\t\telse if(board[y * width + x] && liveNeighbors < 4)\n\t\t\t{\n\t\t\t\tnewBoard[y * width + x] = true;\n\t\t\t}\n\t\t\telse if(liveNeighbors == 3)\n\t\t\t{\n\t\t\t\tnewBoard[y * width + x] = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnewBoard[y * width + x] = false;\n\t\t\t}\n\t\t}\n\t}\n\tfree(board);\n\treturn newBoard;\n}\n\nint calculateLiveNeighbors(bool* board, int x, int y, int width, int height)\n{\n\tint liveCount = 0;\n\tif(y > 0)\n\t{\n\t\tif(board[(y - 1) * width + x]) ++liveCount;\n\t}\n\tif(y > 0 && x > 0)\n\t{\n\t\tif(board[(y - 1) * width + (x - 1)]) ++liveCount;\n\t}\n\tif(x > 0)\n\t{\n\t\tif(board[y * width + (x - 1)]) ++liveCount;\n\t}\n\tif(x > 0 && y < height)\n\t{\n\t\tif(board[(y + 1) * width + (x - 1)]) ++liveCount;\n\t}\n\tif(y < height)\n\t{\n\t\tif(board[(y + 1) * width + x]) ++liveCount;\n\t}\n\tif(y < height && x < width)\n\t{\n\t\tif(board[(y + 1) * width + (x + 1)]) ++liveCount;\n\t}\n\tif(x < width)\n\t{\n\t\tif(board[y * width + (x + 1)]) ++liveCount;\n\t}\n\tif(y > 0 && x < width)\n\t{\n\t\tif(board[(y - 1) * width + (x + 1)]) ++liveCount;\n\t}\n\treturn liveCount;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <random.h>\n#include <scheduler.h>\n#include <util\/time.h>\n\n#include <boost\/thread.hpp>\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(scheduler_tests)\n\nstatic void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, std::chrono::system_clock::time_point rescheduleTime)\n{\n {\n boost::unique_lock<boost::mutex> lock(mutex);\n counter += delta;\n }\n std::chrono::system_clock::time_point noTime = std::chrono::system_clock::time_point::min();\n if (rescheduleTime != noTime) {\n CScheduler::Function f = std::bind(µTask, std::ref(s), std::ref(mutex), std::ref(counter), -delta + 1, noTime);\n s.schedule(f, rescheduleTime);\n }\n}\n\nBOOST_AUTO_TEST_CASE(manythreads)\n{\n \/\/ Stress test: hundreds of microsecond-scheduled tasks,\n \/\/ serviced by 10 threads.\n \/\/\n \/\/ So... ten shared counters, which if all the tasks execute\n \/\/ properly will sum to the number of tasks done.\n \/\/ Each task adds or subtracts a random amount from one of the\n \/\/ counters, and then schedules another task 0-1000\n \/\/ microseconds in the future to subtract or add from\n \/\/ the counter -random_amount+1, so in the end the shared\n \/\/ counters should sum to the number of initial tasks performed.\n CScheduler microTasks;\n\n boost::mutex counterMutex[10];\n int counter[10] = { 0 };\n FastRandomContext rng{\/* fDeterministic *\/ true};\n auto zeroToNine = [](FastRandomContext& rc) -> int { return rc.randrange(10); }; \/\/ [0, 9]\n auto randomMsec = [](FastRandomContext& rc) -> int { return -11 + (int)rc.randrange(1012); }; \/\/ [-11, 1000]\n auto randomDelta = [](FastRandomContext& rc) -> int { return -1000 + (int)rc.randrange(2001); }; \/\/ [-1000, 1000]\n\n std::chrono::system_clock::time_point start = std::chrono::system_clock::now();\n std::chrono::system_clock::time_point now = start;\n std::chrono::system_clock::time_point first, last;\n size_t nTasks = microTasks.getQueueInfo(first, last);\n BOOST_CHECK(nTasks == 0);\n\n for (int i = 0; i < 100; ++i) {\n std::chrono::system_clock::time_point t = now + std::chrono::microseconds(randomMsec(rng));\n std::chrono::system_clock::time_point tReschedule = now + std::chrono::microseconds(500 + randomMsec(rng));\n int whichCounter = zeroToNine(rng);\n CScheduler::Function f = std::bind(µTask, std::ref(microTasks),\n std::ref(counterMutex[whichCounter]), std::ref(counter[whichCounter]),\n randomDelta(rng), tReschedule);\n microTasks.schedule(f, t);\n }\n nTasks = microTasks.getQueueInfo(first, last);\n BOOST_CHECK(nTasks == 100);\n BOOST_CHECK(first < last);\n BOOST_CHECK(last > now);\n\n \/\/ As soon as these are created they will start running and servicing the queue\n boost::thread_group microThreads;\n for (int i = 0; i < 5; i++)\n microThreads.create_thread(std::bind(&CScheduler::serviceQueue, µTasks));\n\n UninterruptibleSleep(std::chrono::microseconds{600});\n now = std::chrono::system_clock::now();\n\n \/\/ More threads and more tasks:\n for (int i = 0; i < 5; i++)\n microThreads.create_thread(std::bind(&CScheduler::serviceQueue, µTasks));\n for (int i = 0; i < 100; i++) {\n std::chrono::system_clock::time_point t = now + std::chrono::microseconds(randomMsec(rng));\n std::chrono::system_clock::time_point tReschedule = now + std::chrono::microseconds(500 + randomMsec(rng));\n int whichCounter = zeroToNine(rng);\n CScheduler::Function f = std::bind(µTask, std::ref(microTasks),\n std::ref(counterMutex[whichCounter]), std::ref(counter[whichCounter]),\n randomDelta(rng), tReschedule);\n microTasks.schedule(f, t);\n }\n\n \/\/ Drain the task queue then exit threads\n microTasks.stop(true);\n microThreads.join_all(); \/\/ ... wait until all the threads are done\n\n int counterSum = 0;\n for (int i = 0; i < 10; i++) {\n BOOST_CHECK(counter[i] != 0);\n counterSum += counter[i];\n }\n BOOST_CHECK_EQUAL(counterSum, 200);\n}\n\nBOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered)\n{\n CScheduler scheduler;\n\n \/\/ each queue should be well ordered with respect to itself but not other queues\n SingleThreadedSchedulerClient queue1(&scheduler);\n SingleThreadedSchedulerClient queue2(&scheduler);\n\n \/\/ create more threads than queues\n \/\/ if the queues only permit execution of one task at once then\n \/\/ the extra threads should effectively be doing nothing\n \/\/ if they don't we'll get out of order behaviour\n boost::thread_group threads;\n for (int i = 0; i < 5; ++i) {\n threads.create_thread(std::bind(&CScheduler::serviceQueue, &scheduler));\n }\n\n \/\/ these are not atomic, if SinglethreadedSchedulerClient prevents\n \/\/ parallel execution at the queue level no synchronization should be required here\n int counter1 = 0;\n int counter2 = 0;\n\n \/\/ just simply count up on each queue - if execution is properly ordered then\n \/\/ the callbacks should run in exactly the order in which they were enqueued\n for (int i = 0; i < 100; ++i) {\n queue1.AddToProcessQueue([i, &counter1]() {\n bool expectation = i == counter1++;\n assert(expectation);\n });\n\n queue2.AddToProcessQueue([i, &counter2]() {\n bool expectation = i == counter2++;\n assert(expectation);\n });\n }\n\n \/\/ finish up\n scheduler.stop(true);\n threads.join_all();\n\n BOOST_CHECK_EQUAL(counter1, 100);\n BOOST_CHECK_EQUAL(counter2, 100);\n}\n\n\/* disabled for now. See discussion in https:\/\/github.com\/bitcoin\/bitcoin\/pull\/18174\nBOOST_AUTO_TEST_CASE(mockforward)\n{\n CScheduler scheduler;\n\n int counter{0};\n CScheduler::Function dummy = [&counter]{counter++;};\n\n \/\/ schedule jobs for 2, 5 & 8 minutes into the future\n int64_t min_in_milli = 60*1000;\n scheduler.scheduleFromNow(dummy, 2*min_in_milli);\n scheduler.scheduleFromNow(dummy, 5*min_in_milli);\n scheduler.scheduleFromNow(dummy, 8*min_in_milli);\n\n \/\/ check taskQueue\n std::chrono::system_clock::time_point first, last;\n size_t num_tasks = scheduler.getQueueInfo(first, last);\n BOOST_CHECK_EQUAL(num_tasks, 3ul);\n\n std::thread scheduler_thread([&]() { scheduler.serviceQueue(); });\n\n \/\/ bump the scheduler forward 5 minutes\n scheduler.MockForward(std::chrono::seconds(5*60));\n\n \/\/ ensure scheduler has chance to process all tasks queued for before 1 ms from now.\n scheduler.scheduleFromNow([&scheduler]{ scheduler.stop(false); }, 1);\n scheduler_thread.join();\n\n \/\/ check that the queue only has one job remaining\n num_tasks = scheduler.getQueueInfo(first, last);\n BOOST_CHECK_EQUAL(num_tasks, 1ul);\n\n \/\/ check that the dummy function actually ran\n BOOST_CHECK_EQUAL(counter, 2);\n\n \/\/ check that the time of the remaining job has been updated\n std::chrono::system_clock::time_point now = std::chrono::system_clock::now();\n int delta = std::chrono::duration_cast<std::chrono::seconds>(first - now).count();\n \/\/ should be between 2 & 3 minutes from now\n BOOST_CHECK(delta > 2*60 && delta < 3*60);\n}\n*\/\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>scheduler_tests: re-enable mockforward test<commit_after>\/\/ Copyright (c) 2012-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <random.h>\n#include <scheduler.h>\n#include <util\/time.h>\n\n#include <boost\/thread.hpp>\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(scheduler_tests)\n\nstatic void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, std::chrono::system_clock::time_point rescheduleTime)\n{\n {\n boost::unique_lock<boost::mutex> lock(mutex);\n counter += delta;\n }\n std::chrono::system_clock::time_point noTime = std::chrono::system_clock::time_point::min();\n if (rescheduleTime != noTime) {\n CScheduler::Function f = std::bind(µTask, std::ref(s), std::ref(mutex), std::ref(counter), -delta + 1, noTime);\n s.schedule(f, rescheduleTime);\n }\n}\n\nBOOST_AUTO_TEST_CASE(manythreads)\n{\n \/\/ Stress test: hundreds of microsecond-scheduled tasks,\n \/\/ serviced by 10 threads.\n \/\/\n \/\/ So... ten shared counters, which if all the tasks execute\n \/\/ properly will sum to the number of tasks done.\n \/\/ Each task adds or subtracts a random amount from one of the\n \/\/ counters, and then schedules another task 0-1000\n \/\/ microseconds in the future to subtract or add from\n \/\/ the counter -random_amount+1, so in the end the shared\n \/\/ counters should sum to the number of initial tasks performed.\n CScheduler microTasks;\n\n boost::mutex counterMutex[10];\n int counter[10] = { 0 };\n FastRandomContext rng{\/* fDeterministic *\/ true};\n auto zeroToNine = [](FastRandomContext& rc) -> int { return rc.randrange(10); }; \/\/ [0, 9]\n auto randomMsec = [](FastRandomContext& rc) -> int { return -11 + (int)rc.randrange(1012); }; \/\/ [-11, 1000]\n auto randomDelta = [](FastRandomContext& rc) -> int { return -1000 + (int)rc.randrange(2001); }; \/\/ [-1000, 1000]\n\n std::chrono::system_clock::time_point start = std::chrono::system_clock::now();\n std::chrono::system_clock::time_point now = start;\n std::chrono::system_clock::time_point first, last;\n size_t nTasks = microTasks.getQueueInfo(first, last);\n BOOST_CHECK(nTasks == 0);\n\n for (int i = 0; i < 100; ++i) {\n std::chrono::system_clock::time_point t = now + std::chrono::microseconds(randomMsec(rng));\n std::chrono::system_clock::time_point tReschedule = now + std::chrono::microseconds(500 + randomMsec(rng));\n int whichCounter = zeroToNine(rng);\n CScheduler::Function f = std::bind(µTask, std::ref(microTasks),\n std::ref(counterMutex[whichCounter]), std::ref(counter[whichCounter]),\n randomDelta(rng), tReschedule);\n microTasks.schedule(f, t);\n }\n nTasks = microTasks.getQueueInfo(first, last);\n BOOST_CHECK(nTasks == 100);\n BOOST_CHECK(first < last);\n BOOST_CHECK(last > now);\n\n \/\/ As soon as these are created they will start running and servicing the queue\n boost::thread_group microThreads;\n for (int i = 0; i < 5; i++)\n microThreads.create_thread(std::bind(&CScheduler::serviceQueue, µTasks));\n\n UninterruptibleSleep(std::chrono::microseconds{600});\n now = std::chrono::system_clock::now();\n\n \/\/ More threads and more tasks:\n for (int i = 0; i < 5; i++)\n microThreads.create_thread(std::bind(&CScheduler::serviceQueue, µTasks));\n for (int i = 0; i < 100; i++) {\n std::chrono::system_clock::time_point t = now + std::chrono::microseconds(randomMsec(rng));\n std::chrono::system_clock::time_point tReschedule = now + std::chrono::microseconds(500 + randomMsec(rng));\n int whichCounter = zeroToNine(rng);\n CScheduler::Function f = std::bind(µTask, std::ref(microTasks),\n std::ref(counterMutex[whichCounter]), std::ref(counter[whichCounter]),\n randomDelta(rng), tReschedule);\n microTasks.schedule(f, t);\n }\n\n \/\/ Drain the task queue then exit threads\n microTasks.stop(true);\n microThreads.join_all(); \/\/ ... wait until all the threads are done\n\n int counterSum = 0;\n for (int i = 0; i < 10; i++) {\n BOOST_CHECK(counter[i] != 0);\n counterSum += counter[i];\n }\n BOOST_CHECK_EQUAL(counterSum, 200);\n}\n\nBOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered)\n{\n CScheduler scheduler;\n\n \/\/ each queue should be well ordered with respect to itself but not other queues\n SingleThreadedSchedulerClient queue1(&scheduler);\n SingleThreadedSchedulerClient queue2(&scheduler);\n\n \/\/ create more threads than queues\n \/\/ if the queues only permit execution of one task at once then\n \/\/ the extra threads should effectively be doing nothing\n \/\/ if they don't we'll get out of order behaviour\n boost::thread_group threads;\n for (int i = 0; i < 5; ++i) {\n threads.create_thread(std::bind(&CScheduler::serviceQueue, &scheduler));\n }\n\n \/\/ these are not atomic, if SinglethreadedSchedulerClient prevents\n \/\/ parallel execution at the queue level no synchronization should be required here\n int counter1 = 0;\n int counter2 = 0;\n\n \/\/ just simply count up on each queue - if execution is properly ordered then\n \/\/ the callbacks should run in exactly the order in which they were enqueued\n for (int i = 0; i < 100; ++i) {\n queue1.AddToProcessQueue([i, &counter1]() {\n bool expectation = i == counter1++;\n assert(expectation);\n });\n\n queue2.AddToProcessQueue([i, &counter2]() {\n bool expectation = i == counter2++;\n assert(expectation);\n });\n }\n\n \/\/ finish up\n scheduler.stop(true);\n threads.join_all();\n\n BOOST_CHECK_EQUAL(counter1, 100);\n BOOST_CHECK_EQUAL(counter2, 100);\n}\n\nBOOST_AUTO_TEST_CASE(mockforward)\n{\n CScheduler scheduler;\n\n int counter{0};\n CScheduler::Function dummy = [&counter]{counter++;};\n\n \/\/ schedule jobs for 2, 5 & 8 minutes into the future\n int64_t min_in_milli = 60*1000;\n scheduler.scheduleFromNow(dummy, 2*min_in_milli);\n scheduler.scheduleFromNow(dummy, 5*min_in_milli);\n scheduler.scheduleFromNow(dummy, 8*min_in_milli);\n\n \/\/ check taskQueue\n std::chrono::system_clock::time_point first, last;\n size_t num_tasks = scheduler.getQueueInfo(first, last);\n BOOST_CHECK_EQUAL(num_tasks, 3ul);\n\n std::thread scheduler_thread([&]() { scheduler.serviceQueue(); });\n\n \/\/ bump the scheduler forward 5 minutes\n scheduler.MockForward(std::chrono::seconds(5*60));\n\n \/\/ ensure scheduler has chance to process all tasks queued for before 1 ms from now.\n scheduler.scheduleFromNow([&scheduler]{ scheduler.stop(false); }, 1);\n scheduler_thread.join();\n\n \/\/ check that the queue only has one job remaining\n num_tasks = scheduler.getQueueInfo(first, last);\n BOOST_CHECK_EQUAL(num_tasks, 1ul);\n\n \/\/ check that the dummy function actually ran\n BOOST_CHECK_EQUAL(counter, 2);\n\n \/\/ check that the time of the remaining job has been updated\n std::chrono::system_clock::time_point now = std::chrono::system_clock::now();\n int delta = std::chrono::duration_cast<std::chrono::seconds>(first - now).count();\n \/\/ should be between 2 & 3 minutes from now\n BOOST_CHECK(delta > 2*60 && delta < 3*60);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#include \"precompiled_reportdesign.hxx\"\n#include \"ReportDrawPage.hxx\"\n#include \"RptObject.hxx\"\n#include \"RptModel.hxx\"\n#include \"RptDef.hxx\"\n#include \"corestrings.hrc\"\n#include <comphelper\/mimeconfighelper.hxx>\n#include <comphelper\/classids.hxx>\n#include <comphelper\/embeddedobjectcontainer.hxx>\n#include <comphelper\/documentconstants.hxx>\n\n#include <svx\/svdmodel.hxx>\n#include <com\/sun\/star\/report\/XFixedLine.hpp>\n#include <com\/sun\/star\/beans\/NamedValue.hpp>\n\n#include <tools\/diagnose_ex.h>\n#include <svx\/unoshape.hxx>\n\nnamespace reportdesign\n{\n using namespace ::com::sun::star;\n using namespace rptui;\n\nOReportDrawPage::OReportDrawPage(SdrPage* _pPage\n ,const uno::Reference< report::XSection >& _xSection)\n: SvxDrawPage(_pPage)\n,m_xSection(_xSection)\n{\n}\n\nSdrObject* OReportDrawPage::_CreateSdrObject( const uno::Reference< drawing::XShape > & xDescr ) throw ()\n{\n uno::Reference< report::XReportComponent> xReportComponent(xDescr,uno::UNO_QUERY);\n if ( xReportComponent.is() )\n return OObjectBase::createObject(xReportComponent);\n return SvxDrawPage::_CreateSdrObject( xDescr );\n}\n\nuno::Reference< drawing::XShape > OReportDrawPage::_CreateShape( SdrObject *pObj ) const throw ()\n{\n OObjectBase* pBaseObj = dynamic_cast<OObjectBase*>(pObj);\n if ( !pBaseObj )\n return SvxDrawPage::_CreateShape( pObj );\n\n uno::Reference< report::XSection> xSection = m_xSection;\n uno::Reference< lang::XMultiServiceFactory> xFactory;\n if ( xSection.is() )\n xFactory.set(xSection->getReportDefinition(),uno::UNO_QUERY);\n uno::Reference< drawing::XShape > xRet;\n uno::Reference< drawing::XShape > xShape;\n if ( xFactory.is() )\n {\n bool bChangeOrientation = false;\n ::rtl::OUString sServiceName = pBaseObj->getServiceName();\n OSL_ENSURE(sServiceName.getLength(),\"No Service Name given!\");\n\n if ( pObj->ISA(OUnoObject) )\n {\n OUnoObject* pUnoObj = dynamic_cast<OUnoObject*>(pObj);\n if ( pUnoObj->GetObjIdentifier() == OBJ_DLG_FIXEDTEXT )\n {\n uno::Reference<beans::XPropertySet> xControlModel(pUnoObj->GetUnoControlModel(),uno::UNO_QUERY);\n if ( xControlModel.is() )\n xControlModel->setPropertyValue( PROPERTY_MULTILINE,uno::makeAny(sal_True));\n }\n else\n bChangeOrientation = pUnoObj->GetObjIdentifier() == OBJ_DLG_HFIXEDLINE;\n SvxShapeControl* pShape = new SvxShapeControl( pObj );\n xShape.set(*pShape,uno::UNO_QUERY);\n pShape->setShapeKind(pObj->GetObjIdentifier());\n }\n else if ( pObj->ISA(OCustomShape) )\n {\n SvxCustomShape* pShape = new SvxCustomShape( pObj );\n uno::Reference < drawing::XEnhancedCustomShapeDefaulter > xShape2 = pShape;\n xShape.set(xShape2,uno::UNO_QUERY);\n pShape->setShapeKind(pObj->GetObjIdentifier());\n }\n else if ( pObj->ISA(SdrOle2Obj) )\n {\n SdrOle2Obj* pOle2Obj = dynamic_cast<SdrOle2Obj*>(pObj);\n if ( !pOle2Obj->GetObjRef().is() )\n {\n sal_Int64 nAspect = embed::Aspects::MSOLE_CONTENT;\n uno::Reference < embed::XEmbeddedObject > xObj;\n ::rtl::OUString sName;\n xObj = pObj->GetModel()->GetPersist()->getEmbeddedObjectContainer().CreateEmbeddedObject(\n ::comphelper::MimeConfigurationHelper::GetSequenceClassIDRepresentation(\n ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"80243D39-6741-46C5-926E-069164FF87BB\"))), sName );\n OSL_ENSURE(xObj.is(),\"Embedded Object could not be created!\");\n\n \/**************************************************\n * Das leere OLE-Objekt bekommt ein neues IPObj\n **************************************************\/\n pObj->SetEmptyPresObj(sal_False);\n pOle2Obj->SetOutlinerParaObject(NULL);\n pOle2Obj->SetObjRef(xObj);\n pOle2Obj->SetPersistName(sName);\n pOle2Obj->SetName(sName);\n pOle2Obj->SetAspect(nAspect);\n Rectangle aRect = pOle2Obj->GetLogicRect();\n\n Size aTmp = aRect.GetSize();\n awt::Size aSz( aTmp.Width(), aTmp.Height() );\n xObj->setVisualAreaSize( nAspect, aSz );\n }\n SvxOle2Shape* pShape = new SvxOle2Shape( pObj );\n xShape.set(*pShape,uno::UNO_QUERY);\n pShape->setShapeKind(pObj->GetObjIdentifier());\n }\n\n if ( !xShape.is() )\n xShape.set( SvxDrawPage::_CreateShape( pObj ) );\n\n try\n {\n OReportModel* pRptModel = static_cast<OReportModel*>(pObj->GetModel());\n xRet.set( pRptModel->createShape(sServiceName,xShape,bChangeOrientation ? 0 : 1), uno::UNO_QUERY_THROW );\n }\n catch( const uno::Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n }\n\n return xRet;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Eliminate ambiguous conversion to cppu::OWeakObject<commit_after>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#include \"precompiled_reportdesign.hxx\"\n#include \"ReportDrawPage.hxx\"\n#include \"RptObject.hxx\"\n#include \"RptModel.hxx\"\n#include \"RptDef.hxx\"\n#include \"corestrings.hrc\"\n#include <comphelper\/mimeconfighelper.hxx>\n#include <comphelper\/classids.hxx>\n#include <comphelper\/embeddedobjectcontainer.hxx>\n#include <comphelper\/documentconstants.hxx>\n\n#include <svx\/svdmodel.hxx>\n#include <com\/sun\/star\/report\/XFixedLine.hpp>\n#include <com\/sun\/star\/beans\/NamedValue.hpp>\n\n#include <tools\/diagnose_ex.h>\n#include <svx\/unoshape.hxx>\n\nnamespace reportdesign\n{\n using namespace ::com::sun::star;\n using namespace rptui;\n\nOReportDrawPage::OReportDrawPage(SdrPage* _pPage\n ,const uno::Reference< report::XSection >& _xSection)\n: SvxDrawPage(_pPage)\n,m_xSection(_xSection)\n{\n}\n\nSdrObject* OReportDrawPage::_CreateSdrObject( const uno::Reference< drawing::XShape > & xDescr ) throw ()\n{\n uno::Reference< report::XReportComponent> xReportComponent(xDescr,uno::UNO_QUERY);\n if ( xReportComponent.is() )\n return OObjectBase::createObject(xReportComponent);\n return SvxDrawPage::_CreateSdrObject( xDescr );\n}\n\nuno::Reference< drawing::XShape > OReportDrawPage::_CreateShape( SdrObject *pObj ) const throw ()\n{\n OObjectBase* pBaseObj = dynamic_cast<OObjectBase*>(pObj);\n if ( !pBaseObj )\n return SvxDrawPage::_CreateShape( pObj );\n\n uno::Reference< report::XSection> xSection = m_xSection;\n uno::Reference< lang::XMultiServiceFactory> xFactory;\n if ( xSection.is() )\n xFactory.set(xSection->getReportDefinition(),uno::UNO_QUERY);\n uno::Reference< drawing::XShape > xRet;\n uno::Reference< drawing::XShape > xShape;\n if ( xFactory.is() )\n {\n bool bChangeOrientation = false;\n ::rtl::OUString sServiceName = pBaseObj->getServiceName();\n OSL_ENSURE(sServiceName.getLength(),\"No Service Name given!\");\n\n if ( pObj->ISA(OUnoObject) )\n {\n OUnoObject* pUnoObj = dynamic_cast<OUnoObject*>(pObj);\n if ( pUnoObj->GetObjIdentifier() == OBJ_DLG_FIXEDTEXT )\n {\n uno::Reference<beans::XPropertySet> xControlModel(pUnoObj->GetUnoControlModel(),uno::UNO_QUERY);\n if ( xControlModel.is() )\n xControlModel->setPropertyValue( PROPERTY_MULTILINE,uno::makeAny(sal_True));\n }\n else\n bChangeOrientation = pUnoObj->GetObjIdentifier() == OBJ_DLG_HFIXEDLINE;\n SvxShapeControl* pShape = new SvxShapeControl( pObj );\n xShape.set(static_cast<cppu::OWeakObject*>(static_cast<SvxShape_UnoImplHelper *>(pShape)),uno::UNO_QUERY);\n pShape->setShapeKind(pObj->GetObjIdentifier());\n }\n else if ( pObj->ISA(OCustomShape) )\n {\n SvxCustomShape* pShape = new SvxCustomShape( pObj );\n uno::Reference < drawing::XEnhancedCustomShapeDefaulter > xShape2 = pShape;\n xShape.set(xShape2,uno::UNO_QUERY);\n pShape->setShapeKind(pObj->GetObjIdentifier());\n }\n else if ( pObj->ISA(SdrOle2Obj) )\n {\n SdrOle2Obj* pOle2Obj = dynamic_cast<SdrOle2Obj*>(pObj);\n if ( !pOle2Obj->GetObjRef().is() )\n {\n sal_Int64 nAspect = embed::Aspects::MSOLE_CONTENT;\n uno::Reference < embed::XEmbeddedObject > xObj;\n ::rtl::OUString sName;\n xObj = pObj->GetModel()->GetPersist()->getEmbeddedObjectContainer().CreateEmbeddedObject(\n ::comphelper::MimeConfigurationHelper::GetSequenceClassIDRepresentation(\n ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"80243D39-6741-46C5-926E-069164FF87BB\"))), sName );\n OSL_ENSURE(xObj.is(),\"Embedded Object could not be created!\");\n\n \/**************************************************\n * Das leere OLE-Objekt bekommt ein neues IPObj\n **************************************************\/\n pObj->SetEmptyPresObj(sal_False);\n pOle2Obj->SetOutlinerParaObject(NULL);\n pOle2Obj->SetObjRef(xObj);\n pOle2Obj->SetPersistName(sName);\n pOle2Obj->SetName(sName);\n pOle2Obj->SetAspect(nAspect);\n Rectangle aRect = pOle2Obj->GetLogicRect();\n\n Size aTmp = aRect.GetSize();\n awt::Size aSz( aTmp.Width(), aTmp.Height() );\n xObj->setVisualAreaSize( nAspect, aSz );\n }\n SvxOle2Shape* pShape = new SvxOle2Shape( pObj );\n xShape.set(*pShape,uno::UNO_QUERY);\n pShape->setShapeKind(pObj->GetObjIdentifier());\n }\n\n if ( !xShape.is() )\n xShape.set( SvxDrawPage::_CreateShape( pObj ) );\n\n try\n {\n OReportModel* pRptModel = static_cast<OReportModel*>(pObj->GetModel());\n xRet.set( pRptModel->createShape(sServiceName,xShape,bChangeOrientation ? 0 : 1), uno::UNO_QUERY_THROW );\n }\n catch( const uno::Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n }\n\n return xRet;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KOrganizer.\n\n Copyright (c) 1997, 1998 Preston Brown <pbrown@kde.org>\n Copyright (c) 2000-2003 Cornelius Schumacher <schumacher@kde.org>\n Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com>\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; 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. See the\n 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 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"kojournaleditor.h\"\n#include \"koeditorgeneraljournal.h\"\n#include \"koeditordetails.h\"\n#include \"koeditorattachments.h\"\n#include \"kodialogmanager.h\"\n#include \"koprefs.h\"\n#include \"korganizer\/baseview.h\"\n\n#include <kcal\/journal.h>\n#include <kcal\/calendarlocal.h>\n\n#include <kmessagebox.h>\n#include <klocale.h>\n\n#include <QLayout>\n#include <QVBoxLayout>\n#include <QFrame>\n#include <QBoxLayout>\n\nusing namespace KCal;\n\nKOJournalEditor::KOJournalEditor( Calendar *calendar, QWidget *parent )\n : KOIncidenceEditor( i18n( \"Edit Journal Entry\" ), calendar, parent ),\n mJournal( 0 ), mCalendar( 0 )\n{\n}\n\nKOJournalEditor::~KOJournalEditor()\n{\n emit dialogClose( mJournal );\n}\n\nvoid KOJournalEditor::init()\n{\n setupGeneral();\n setupAttendeesTab();\n}\n\nvoid KOJournalEditor::reload()\n{\n if ( mJournal ) {\n readJournal( mJournal );\n }\n}\n\nvoid KOJournalEditor::setupGeneral()\n{\n mGeneral = new KOEditorGeneralJournal( mCalendar, this );\n\n QFrame *topFrame = new QFrame();\n addPage( topFrame, i18nc( \"@title general journal settings\", \"General\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n if ( KOPrefs::instance()->mCompactDialogs ) {\n topLayout->setMargin( marginHint() );\n }\n topLayout->setSpacing( spacingHint() );\n\n mGeneral->initTitle( topFrame, topLayout );\n mGeneral->initDate( topFrame, topLayout );\n mGeneral->initDescription( topFrame, topLayout );\n mGeneral->initCategories( topFrame, topLayout );\n\n mGeneral->finishSetup();\n}\n\nvoid KOJournalEditor::editIncidence( Incidence *incidence, Calendar * )\n{\n Journal *journal=dynamic_cast<Journal*>( incidence );\n if ( journal ) {\n init();\n\n mJournal = journal;\n readJournal( mJournal );\n }\n}\n\nvoid KOJournalEditor::newJournal()\n{\n init();\n mJournal = 0;\n loadDefaults();\n}\n\nvoid KOJournalEditor::setTexts( const QString &summary,\n const QString &description,\n bool richDescription )\n{\n if ( description.isEmpty() && summary.contains( \"\\n\" ) ) {\n mGeneral->setDescription( summary, false );\n int pos = summary.indexOf( \"\\n\" );\n mGeneral->setSummary( summary.left( pos ) );\n } else {\n mGeneral->setSummary( summary );\n mGeneral->setDescription( description, richDescription );\n }\n}\n\nvoid KOJournalEditor::loadDefaults()\n{\n setDate( QDate::currentDate() );\n setTime( QTime::currentTime() );\n}\n\nbool KOJournalEditor::processInput()\n{\n if ( !validateInput() ) {\n return false;\n }\n\n if ( mJournal ) {\n Journal *oldJournal = mJournal->clone();\n fillJournal( mJournal );\n mChanger->changeIncidence( oldJournal, mJournal );\n delete oldJournal;\n } else {\n mJournal = new Journal;\n mJournal->setOrganizer( Person( KOPrefs::instance()->fullName(),\n KOPrefs::instance()->email() ) );\n\n fillJournal( mJournal );\n\n if ( !mChanger->addIncidence( mJournal, this ) ) {\n delete mJournal;\n mJournal = 0;\n return false;\n }\n }\n\n return true;\n}\n\nvoid KOJournalEditor::deleteJournal()\n{\n if ( mJournal ) {\n emit deleteIncidenceSignal( mJournal );\n }\n\n emit dialogClose( mJournal );\n reject();\n}\n\nvoid KOJournalEditor::setDate( const QDate &date )\n{\n mGeneral->setDate( date );\n}\n\nvoid KOJournalEditor::setTime( const QTime &time )\n{\n mGeneral->setTime( time );\n}\n\nbool KOJournalEditor::incidenceModified() {\n Journal *newJournal = 0;\n\n if ( mJournal ) {\n newJournal = mJournal->clone();\n fillJournal( newJournal );\n }\n return mJournal && !( *newJournal == *mJournal );\n}\n\nvoid KOJournalEditor::readJournal( Journal *journal, bool tmpl )\n{\n \/\/TODO: just tmpl variable\n Q_UNUSED( tmpl );\n\n if ( !journal ) {\n return;\n }\n\n mGeneral->readJournal( journal );\n mDetails->readIncidence( journal );\n}\n\nvoid KOJournalEditor::fillJournal( Journal *journal )\n{\n mGeneral->fillJournal( journal );\n mDetails->fillIncidence( journal );\n}\n\nbool KOJournalEditor::validateInput()\n{\n return mGeneral->validateInput();\n}\n\nint KOJournalEditor::msgItemDelete()\n{\n return KMessageBox::warningContinueCancel(\n this,\n i18n( \"This journal entry will be permanently deleted.\" ),\n i18n( \"KOrganizer Confirmation\" ),\n KGuiItem( i18n( \"Delete\" ), \"edit-delete\" ) );\n}\n\nvoid KOJournalEditor::modified( int \/*modification*\/)\n{\n \/\/ Play dump, just reload the Journal. This dialog has become so complicated that\n \/\/ there is no point in trying to be smart here...\n reload();\n}\n\nvoid KOJournalEditor::loadTemplate( CalendarLocal &cal )\n{\n Journal::List journals = cal.journals();\n if ( journals.count() == 0 ) {\n KMessageBox::error( this, i18n( \"Template does not contain a valid journal.\" ) );\n } else {\n readJournal( journals.first() );\n }\n}\n\nvoid KOJournalEditor::slotSaveTemplate( const QString &templateName )\n{\n Journal *journal = new Journal;\n fillJournal( journal );\n saveAsTemplate( journal, templateName );\n}\n\nQStringList &KOJournalEditor::templates() const\n{\n return KOPrefs::instance()->mJournalTemplates;\n}\n\n#include \"kojournaleditor.moc\"\n<commit_msg>backport SVN commit 956252 by winterz:<commit_after>\/*\n This file is part of KOrganizer.\n\n Copyright (c) 1997, 1998 Preston Brown <pbrown@kde.org>\n Copyright (c) 2000-2003 Cornelius Schumacher <schumacher@kde.org>\n Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com>\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; 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. See the\n 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 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"kojournaleditor.h\"\n#include \"koeditorgeneraljournal.h\"\n#include \"koeditordetails.h\"\n#include \"koeditorattachments.h\"\n#include \"kodialogmanager.h\"\n#include \"koprefs.h\"\n#include \"korganizer\/baseview.h\"\n\n#include <kcal\/journal.h>\n#include <kcal\/calendarlocal.h>\n\n#include <kmessagebox.h>\n#include <klocale.h>\n\n#include <QLayout>\n#include <QVBoxLayout>\n#include <QFrame>\n#include <QBoxLayout>\n\nusing namespace KCal;\n\nKOJournalEditor::KOJournalEditor( Calendar *calendar, QWidget *parent )\n : KOIncidenceEditor( i18n( \"Edit Journal Entry\" ), calendar, parent ),\n mJournal( 0 ), mCalendar( 0 )\n{\n}\n\nKOJournalEditor::~KOJournalEditor()\n{\n emit dialogClose( mJournal );\n}\n\nvoid KOJournalEditor::init()\n{\n setupGeneral();\n setupAttendeesTab();\n\n connect( mGeneral, SIGNAL(openCategoryDialog()),\n SIGNAL(editCategories()) );\n connect( this, SIGNAL(updateCategoryConfig()),\n mGeneral, SIGNAL(updateCategoryConfig()) );\n\n connect( mDetails, SIGNAL(updateAttendeeSummary(int)),\n mGeneral, SLOT(updateAttendeeSummary(int)) );\n}\n\nvoid KOJournalEditor::reload()\n{\n if ( mJournal ) {\n readJournal( mJournal );\n }\n}\n\nvoid KOJournalEditor::setupGeneral()\n{\n mGeneral = new KOEditorGeneralJournal( mCalendar, this );\n\n QFrame *topFrame = new QFrame();\n addPage( topFrame, i18nc( \"@title general journal settings\", \"General\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n if ( KOPrefs::instance()->mCompactDialogs ) {\n topLayout->setMargin( marginHint() );\n }\n topLayout->setSpacing( spacingHint() );\n\n mGeneral->initTitle( topFrame, topLayout );\n mGeneral->initDate( topFrame, topLayout );\n mGeneral->initDescription( topFrame, topLayout );\n mGeneral->initCategories( topFrame, topLayout );\n\n mGeneral->finishSetup();\n}\n\nvoid KOJournalEditor::editIncidence( Incidence *incidence, Calendar * )\n{\n Journal *journal=dynamic_cast<Journal*>( incidence );\n if ( journal ) {\n init();\n\n mJournal = journal;\n readJournal( mJournal );\n }\n}\n\nvoid KOJournalEditor::newJournal()\n{\n init();\n mJournal = 0;\n loadDefaults();\n}\n\nvoid KOJournalEditor::setTexts( const QString &summary,\n const QString &description,\n bool richDescription )\n{\n if ( description.isEmpty() && summary.contains( \"\\n\" ) ) {\n mGeneral->setDescription( summary, false );\n int pos = summary.indexOf( \"\\n\" );\n mGeneral->setSummary( summary.left( pos ) );\n } else {\n mGeneral->setSummary( summary );\n mGeneral->setDescription( description, richDescription );\n }\n}\n\nvoid KOJournalEditor::loadDefaults()\n{\n setDate( QDate::currentDate() );\n setTime( QTime::currentTime() );\n}\n\nbool KOJournalEditor::processInput()\n{\n if ( !validateInput() ) {\n return false;\n }\n\n if ( mJournal ) {\n Journal *oldJournal = mJournal->clone();\n fillJournal( mJournal );\n mChanger->changeIncidence( oldJournal, mJournal );\n delete oldJournal;\n } else {\n mJournal = new Journal;\n mJournal->setOrganizer( Person( KOPrefs::instance()->fullName(),\n KOPrefs::instance()->email() ) );\n\n fillJournal( mJournal );\n\n if ( !mChanger->addIncidence( mJournal, this ) ) {\n delete mJournal;\n mJournal = 0;\n return false;\n }\n }\n\n return true;\n}\n\nvoid KOJournalEditor::deleteJournal()\n{\n if ( mJournal ) {\n emit deleteIncidenceSignal( mJournal );\n }\n\n emit dialogClose( mJournal );\n reject();\n}\n\nvoid KOJournalEditor::setDate( const QDate &date )\n{\n mGeneral->setDate( date );\n}\n\nvoid KOJournalEditor::setTime( const QTime &time )\n{\n mGeneral->setTime( time );\n}\n\nbool KOJournalEditor::incidenceModified() {\n Journal *newJournal = 0;\n\n if ( mJournal ) {\n newJournal = mJournal->clone();\n fillJournal( newJournal );\n }\n return mJournal && !( *newJournal == *mJournal );\n}\n\nvoid KOJournalEditor::readJournal( Journal *journal, bool tmpl )\n{\n \/\/TODO: just tmpl variable\n Q_UNUSED( tmpl );\n\n if ( !journal ) {\n return;\n }\n\n mGeneral->readJournal( journal );\n mDetails->readIncidence( journal );\n}\n\nvoid KOJournalEditor::fillJournal( Journal *journal )\n{\n mGeneral->fillJournal( journal );\n mDetails->fillIncidence( journal );\n}\n\nbool KOJournalEditor::validateInput()\n{\n return mGeneral->validateInput();\n}\n\nint KOJournalEditor::msgItemDelete()\n{\n return KMessageBox::warningContinueCancel(\n this,\n i18n( \"This journal entry will be permanently deleted.\" ),\n i18n( \"KOrganizer Confirmation\" ),\n KGuiItem( i18n( \"Delete\" ), \"edit-delete\" ) );\n}\n\nvoid KOJournalEditor::modified( int \/*modification*\/)\n{\n \/\/ Play dump, just reload the Journal. This dialog has become so complicated that\n \/\/ there is no point in trying to be smart here...\n reload();\n}\n\nvoid KOJournalEditor::loadTemplate( CalendarLocal &cal )\n{\n Journal::List journals = cal.journals();\n if ( journals.count() == 0 ) {\n KMessageBox::error( this, i18n( \"Template does not contain a valid journal.\" ) );\n } else {\n readJournal( journals.first() );\n }\n}\n\nvoid KOJournalEditor::slotSaveTemplate( const QString &templateName )\n{\n Journal *journal = new Journal;\n fillJournal( journal );\n saveAsTemplate( journal, templateName );\n}\n\nQStringList &KOJournalEditor::templates() const\n{\n return KOPrefs::instance()->mJournalTemplates;\n}\n\n#include \"kojournaleditor.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n *The MIT License (MIT)\n *\n * Copyright (c) <2016> <Stephan Gatzka>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE websocket_tests\n\n#include <boost\/test\/unit_test.hpp>\n#include <errno.h>\n\n#include \"socket.h\"\n#include \"websocket.h\"\n\n#define CRLF \"\\r\\n\"\n\n#ifndef ARRAY_SIZE\n #define ARRAY_SIZE(a) (sizeof(a) \/ sizeof((a)[0]))\n#endif\n\nstatic const int FD_CORRECT_UPGRADE = 1;\nstatic bool ws_error = false;\n\nstatic const char *readbuffer;\nstatic const char *readbuffer_ptr;\n\nstatic http_parser response_parser;\nstatic http_parser_settings response_parser_settings;\nstatic bool got_complete_response_header = false;\nstatic bool response_parse_error = false;\n\nextern \"C\" {\n\tssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count)\n\t{\n\t\tswitch (sock) {\n\t\tcase FD_CORRECT_UPGRADE: {\n\t\t\tsize_t complete_length = 0;\n\t\t\tfor (unsigned int i = 0; i < count; i++) {\n\t\t\t\tif (!got_complete_response_header) {\n\t\t\t\t\tsize_t nparsed = http_parser_execute(&response_parser, &response_parser_settings, (const char *)io_vec[i].iov_base, io_vec[i].iov_len);\n\t\t\t\t\tif (nparsed != io_vec[i].iov_len) {\n\t\t\t\t\t\tresponse_parse_error = true;\n\t\t\t\t\t\terrno = EFAULT;\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tcomplete_length += io_vec[i].iov_len;\n\t\t\t}\n\t\t\treturn complete_length;\n\t\t}\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tssize_t socket_send(socket_type sock, const void *buf, size_t len)\n\t{\n\t\t(void)buf;\n\t\t(void)len;\n\n\t\tswitch (sock) {\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tssize_t socket_read(socket_type sock, void *buf, size_t count)\n\t{\n\t\t(void)buf;\n\t\t(void)count;\n\n\t\tswitch (sock) {\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tint socket_close(socket_type sock)\n\t{\n\t\t(void)sock;\n\t\treturn 0;\n\t}\n}\n\nstatic enum callback_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev)\n{\n\t(void)this_ptr;\n\t(void)ev;\n\treturn CONTINUE_LOOP;\n}\n\nstatic void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev)\n{\n\t(void)this_ptr;\n\t(void)ev;\n}\n\nstatic void ws_on_error(struct websocket *ws)\n{\n\t(void)ws;\n\tws_error = true;\n}\n\nstatic int on_headers_complete(http_parser *parser)\n{\n\t(void)parser;\n\tgot_complete_response_header = true;\n\treturn 0;\n}\n\nstruct F {\n\tF()\n\t{\n\t\tloop.init = NULL;\n\t\tloop.destroy = NULL;\n\t\tloop.run = NULL;\n\t\tloop.add = eventloop_fake_add;\n\t\tloop.remove = eventloop_fake_remove;\n\t\t\n\t\treadbuffer_ptr = readbuffer;\n\t\tgot_complete_response_header = false;\n\t\tresponse_parse_error = false;\n\n\t\thttp_parser_settings_init(&parser_settings);\n\t\thttp_parser_init(&parser, HTTP_REQUEST);\n\n\t\thttp_parser_settings_init(&response_parser_settings);\n\t\thttp_parser_init(&response_parser, HTTP_RESPONSE);\n\t\tresponse_parser_settings.on_headers_complete = on_headers_complete;\n\n\t\thandler[0].request_target = \"\/\";\n\t\thandler[0].create = NULL;\n\t\t\n\t\thandler[0].on_header_field = websocket_upgrade_on_header_field,\n\t\thandler[0].on_header_value = websocket_upgrade_on_header_value,\n\t\thandler[0].on_headers_complete = websocket_upgrade_on_headers_complete,\n\t\thandler[0].on_body = NULL;\n\t\thandler[0].on_message_complete = NULL;\n\n\t\thttp_server.handler = handler;\n\t\thttp_server.num_handlers = ARRAY_SIZE(handler);\n\n\t\tws_error = false;\n\t}\n\n\t~F()\n\t{\n\t}\n\n\tstruct eventloop loop;\n\thttp_parser parser;\n\thttp_parser_settings parser_settings;\n\tstruct url_handler handler[1];\n\tstruct http_server http_server;\n};\n\nBOOST_AUTO_TEST_CASE(test_websocket_init)\n{\n\tstruct websocket ws;\n\twebsocket_init(&ws, NULL, true, NULL);\n\twebsocket_free(&ws);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_http_upgrade, F)\n{\n\tchar request[] = \"GET \/ HTTP\/1.1\" CRLF\n\t \"Connection: Upgrade\" CRLF \\\n\t \"Upgrade: websocket\" CRLF \\\n\t \"Sec-WebSocket-Version: 13\" CRLF\\\n\t \"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\" CRLF CRLF;\n\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_CORRECT_UPGRADE);\n\tBOOST_REQUIRE_MESSAGE(connection != NULL, \"Failed to allocate http connection\");\n\n\tstruct websocket ws;\n\twebsocket_init(&ws, connection, true, ws_on_error);\n\tconnection->parser.data = &ws;\n\n\tbs_read_callback_return ret = websocket_read_header_line(&ws, request, ::strlen(request));\n\tBOOST_CHECK_MESSAGE(ret == BS_OK, \"websocket_read_header_line did not return BS_OK\");\n\tBOOST_CHECK_MESSAGE(ws_error == false, \"Error while parsing the http upgrade request\");\n\twebsocket_free(&ws);\n\t\n\tBOOST_CHECK_MESSAGE(response_parser.status_code == 101, \"Expected 101 status code\");\n\tBOOST_CHECK_MESSAGE(response_parser.http_major == 1, \"Expected http major 1\");\n\tBOOST_CHECK_MESSAGE(response_parser.http_minor == 1, \"Expected http minor 1\");\n\tBOOST_CHECK_MESSAGE(response_parse_error == false, \"Invalid upgrade response!\");\n\t\n\t\/\/ TODO: Check for An |Upgrade| header field with value \"websocket\" as per RFC 2616 [RFC2616].\n\t\/\/ TODO: Check for A |Connection| header field with value \"Upgrade\".\n\t\/\/ TODO: Check for A |Sec-WebSocket-Accept| header field with \"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\"\n\t\/\/ TODO: Check that close frame was sent\n}\n<commit_msg>Check that Upgrade and Connection fields are send in websocket upgrade response.<commit_after>\/*\n *The MIT License (MIT)\n *\n * Copyright (c) <2016> <Stephan Gatzka>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE websocket_tests\n\n#include <boost\/test\/unit_test.hpp>\n#include <errno.h>\n\n#include \"jet_string.h\"\n#include \"socket.h\"\n#include \"websocket.h\"\n\n#define CRLF \"\\r\\n\"\n\n#ifndef ARRAY_SIZE\n #define ARRAY_SIZE(a) (sizeof(a) \/ sizeof((a)[0]))\n#endif\n\nstatic const int FD_CORRECT_UPGRADE = 1;\nstatic bool ws_error = false;\n\nstatic const char *readbuffer;\nstatic const char *readbuffer_ptr;\n\nstatic http_parser response_parser;\nstatic http_parser_settings response_parser_settings;\nstatic bool got_complete_response_header = false;\nstatic bool response_parse_error = false;\n\nextern \"C\" {\n\tssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count)\n\t{\n\t\tswitch (sock) {\n\t\tcase FD_CORRECT_UPGRADE: {\n\t\t\tsize_t complete_length = 0;\n\t\t\tfor (unsigned int i = 0; i < count; i++) {\n\t\t\t\tif (!got_complete_response_header) {\n\t\t\t\t\tsize_t nparsed = http_parser_execute(&response_parser, &response_parser_settings, (const char *)io_vec[i].iov_base, io_vec[i].iov_len);\n\t\t\t\t\tif (nparsed != io_vec[i].iov_len) {\n\t\t\t\t\t\tresponse_parse_error = true;\n\t\t\t\t\t\terrno = EFAULT;\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tcomplete_length += io_vec[i].iov_len;\n\t\t\t}\n\t\t\treturn complete_length;\n\t\t}\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tssize_t socket_send(socket_type sock, const void *buf, size_t len)\n\t{\n\t\t(void)buf;\n\t\t(void)len;\n\n\t\tswitch (sock) {\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tssize_t socket_read(socket_type sock, void *buf, size_t count)\n\t{\n\t\t(void)buf;\n\t\t(void)count;\n\n\t\tswitch (sock) {\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tint socket_close(socket_type sock)\n\t{\n\t\t(void)sock;\n\t\treturn 0;\n\t}\n}\n\nstatic enum callback_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev)\n{\n\t(void)this_ptr;\n\t(void)ev;\n\treturn CONTINUE_LOOP;\n}\n\nstatic void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev)\n{\n\t(void)this_ptr;\n\t(void)ev;\n}\n\nstatic void ws_on_error(struct websocket *ws)\n{\n\t(void)ws;\n\tws_error = true;\n}\n\nstatic int on_headers_complete(http_parser *parser)\n{\n\t(void)parser;\n\tgot_complete_response_header = true;\n\treturn 0;\n}\n\nstruct F {\n\t\n\tenum response_on_header_field {\n\t\tHEADER_UNKNOWN,\n\t\tHEADER_UPGRADE,\n\t\tHEADER_CONNECTION,\n\t};\n\n\tF()\n\t{\n\t\tloop.init = NULL;\n\t\tloop.destroy = NULL;\n\t\tloop.run = NULL;\n\t\tloop.add = eventloop_fake_add;\n\t\tloop.remove = eventloop_fake_remove;\n\t\t\n\t\treadbuffer_ptr = readbuffer;\n\t\tgot_complete_response_header = false;\n\t\tresponse_parse_error = false;\n\n\t\thttp_parser_settings_init(&parser_settings);\n\t\thttp_parser_init(&parser, HTTP_REQUEST);\n\n\t\thttp_parser_settings_init(&response_parser_settings);\n\t\thttp_parser_init(&response_parser, HTTP_RESPONSE);\n\t\tresponse_parser.data = this;\n\t\tresponse_parser_settings.on_header_field = response_on_header_field;\n\t\tresponse_parser_settings.on_header_value = response_on_header_value;\n\t\tresponse_parser_settings.on_headers_complete = on_headers_complete;\n\n\t\thandler[0].request_target = \"\/\";\n\t\thandler[0].create = NULL;\n\t\t\n\t\thandler[0].on_header_field = websocket_upgrade_on_header_field,\n\t\thandler[0].on_header_value = websocket_upgrade_on_header_value,\n\t\thandler[0].on_headers_complete = websocket_upgrade_on_headers_complete,\n\t\thandler[0].on_body = NULL;\n\t\thandler[0].on_message_complete = NULL;\n\n\t\thttp_server.handler = handler;\n\t\thttp_server.num_handlers = ARRAY_SIZE(handler);\n\n\t\tws_error = false;\n\t\tgot_upgrade_response = false;\n\t\tgot_connection_upgrade = false;\n\t\tcurrent_header_field = HEADER_UNKNOWN;\n\t}\n\n\t~F()\n\t{\n\t}\n\n\tstatic int response_on_header_field(http_parser *p, const char *at, size_t length)\n\t{\n\t\tstruct F *f = (struct F *)p->data;\n\n\t\tstatic const char upgrade_key[] = \"Upgrade\";\n\t\tif ((sizeof(upgrade_key) - 1 == length) && (jet_strncasecmp(at, upgrade_key, length) == 0)) {\n\t\t\tf->current_header_field = HEADER_UPGRADE;\n\t\t\treturn 0;\n\t\t}\n\n\t\tstatic const char connection_key[] = \"Connection\";\n\t\tif ((sizeof(connection_key) - 1 == length) && (jet_strncasecmp(at, connection_key, length) == 0)) {\n\t\t\tf->current_header_field = HEADER_CONNECTION;\n\t\t\treturn 0;\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tstatic int response_on_header_value(http_parser *p, const char *at, size_t length)\n\t{\n\t\tint ret = 0;\n\t\tstruct F *f = (struct F *)p->data;\n\t\tswitch(f->current_header_field) {\n\t\tcase HEADER_UPGRADE:\n\t\t\tf->got_upgrade_response = true;\n\t\t\tbreak;\n\n\t\tcase HEADER_CONNECTION:\n\t\t\tif (jet_strncasecmp(at, \"Upgrade\", length) == 0) {\n\t\t\t\tf->got_connection_upgrade = true;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase HEADER_UNKNOWN:\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tf->current_header_field = HEADER_UNKNOWN;\n\t\treturn ret;\n\t}\n\n\tstruct eventloop loop;\n\thttp_parser parser;\n\thttp_parser_settings parser_settings;\n\tstruct url_handler handler[1];\n\tstruct http_server http_server;\n\t\n\tbool got_upgrade_response;\n\tbool got_connection_upgrade;\n\tenum response_on_header_field current_header_field;\n};\n\nBOOST_AUTO_TEST_CASE(test_websocket_init)\n{\n\tstruct websocket ws;\n\twebsocket_init(&ws, NULL, true, NULL);\n\twebsocket_free(&ws);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_http_upgrade, F)\n{\n\tchar request[] = \"GET \/ HTTP\/1.1\" CRLF\n\t \"Connection: Upgrade\" CRLF \\\n\t \"Upgrade: websocket\" CRLF \\\n\t \"Sec-WebSocket-Version: 13\" CRLF\\\n\t \"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\" CRLF CRLF;\n\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_CORRECT_UPGRADE);\n\tBOOST_REQUIRE_MESSAGE(connection != NULL, \"Failed to allocate http connection\");\n\n\tstruct websocket ws;\n\twebsocket_init(&ws, connection, true, ws_on_error);\n\tconnection->parser.data = &ws;\n\n\tbs_read_callback_return ret = websocket_read_header_line(&ws, request, ::strlen(request));\n\tBOOST_CHECK_MESSAGE(ret == BS_OK, \"websocket_read_header_line did not return BS_OK\");\n\tBOOST_CHECK_MESSAGE(ws_error == false, \"Error while parsing the http upgrade request\");\n\twebsocket_free(&ws);\n\t\n\tBOOST_CHECK_MESSAGE(response_parser.status_code == 101, \"Expected 101 status code\");\n\tBOOST_CHECK_MESSAGE(response_parser.http_major == 1, \"Expected http major 1\");\n\tBOOST_CHECK_MESSAGE(response_parser.http_minor == 1, \"Expected http minor 1\");\n\tBOOST_CHECK_MESSAGE(response_parse_error == false, \"Invalid upgrade response!\");\n\tBOOST_CHECK_MESSAGE(got_upgrade_response == true, \"Upgrade header field missing!\");\n\tBOOST_CHECK_MESSAGE(got_connection_upgrade == true, \"Connection header field missing!\");\n\t\n\t\/\/ TODO: Check for A |Sec-WebSocket-Accept| header field with \"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\"\n\t\/\/ TODO: Check that close frame was sent\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include <cstring>\n\n#include <libxml\/tree.h>\n#include <libxml\/parser.h>\n#include <libxml\/xmlmemory.h>\n#include <libxml\/xmlstring.h>\n\n#include \"export.hxx\"\n#include \"common.hxx\"\n#include \"treemerge.hxx\"\n\n\nnamespace\n{\n \/\/Write out an sdf line\n static void lcl_WriteSDF(\n std::ofstream &aSDFStream, const OString& rText, const OString& rPrj,\n const OString& rActFileName, const OString& rID, const OString& rType )\n {\n OString sOutput( rPrj ); sOutput += \"\\t\";\n sOutput += rActFileName;\n sOutput += \"\\t0\\t\";\n sOutput += rType; sOutput += \"\\t\";\n sOutput += rID; sOutput += \"\\t\\t\\t\\t0\\ten-US\\t\";\n sOutput += rText; sOutput += \"\\t\\t\\t\\t\";\n aSDFStream << sOutput.getStr() << std::endl;\n }\n\n \/\/Convert xmlChar* to OString\n static OString lcl_xmlStrToOString( const xmlChar* pString )\n {\n xmlChar* pTemp = xmlStrdup( pString );\n OString sResult =\n static_cast<OString>(reinterpret_cast<sal_Char*>( pTemp ));\n xmlFree( pTemp );\n return sResult;\n }\n\n \/\/Extract strings from nodes on all level recursively\n static void lcl_ExtractLevel(\n const xmlDocPtr pSource, const xmlNodePtr pRoot,\n const xmlChar* pNodeName, std::ofstream& rSDFStream,\n const OString& rPrj, const OString& rRoot )\n {\n if( !pRoot->children )\n {\n return;\n }\n for( xmlNodePtr pCurrent = pRoot->children->next;\n pCurrent; pCurrent = pCurrent->next)\n {\n if (!xmlStrcmp(pCurrent->name, pNodeName))\n {\n xmlChar* pID = xmlGetProp(pCurrent, (const xmlChar*)(\"id\"));\n xmlChar* pText =\n xmlGetProp(pCurrent, (const xmlChar*)(\"title\"));\n lcl_WriteSDF(\n rSDFStream,\n lcl_xmlStrToOString( pText ),\n rPrj,\n common::pathnameToken(\n pSource->name, rRoot.getStr()),\n lcl_xmlStrToOString( pID ),\n lcl_xmlStrToOString( pNodeName ));\n\n xmlFree( pID );\n xmlFree( pText );\n\n lcl_ExtractLevel(\n pSource, pCurrent, (const xmlChar *)(\"node\"),\n rSDFStream, rPrj, rRoot );\n }\n }\n }\n\n \/\/Update id and content of the topic\n static xmlNodePtr lcl_UpdateTopic(\n const xmlNodePtr pCurrent, const OString& rXhpRoot )\n {\n xmlNodePtr pReturn = pCurrent;\n xmlChar* pID = xmlGetProp(pReturn, (const xmlChar*)(\"id\"));\n const OString sID =\n lcl_xmlStrToOString( pID );\n xmlFree( pID );\n\n const sal_Int32 nFirstSlash = sID.indexOf(\"\/\");\n \/\/Update id attribute of topic\n {\n OString sNewID =\n sID.copy( 0, nFirstSlash + 1 ) +\n rXhpRoot.copy( rXhpRoot.lastIndexOf(\"\/\") + 1 ) +\n sID.copy( sID.indexOf( \"\/\", nFirstSlash + 1 ) );\n xmlSetProp(\n pReturn, (const xmlChar*)(\"id\"),\n reinterpret_cast<const xmlChar*>(sNewID.getStr()));\n }\n\n const OString sXhpPath =\n rXhpRoot +\n sID.copy(sID.indexOf(\"\/\", nFirstSlash + 1));\n xmlDocPtr pXhpFile = xmlParseFile( sXhpPath.getStr() );\n \/\/if xhpfile is missing than we put this topic into comment\n if ( !pXhpFile )\n {\n xmlNodePtr pTemp = pReturn;\n xmlChar* sNewID =\n xmlGetProp(pReturn, (const xmlChar*)(\"id\"));\n xmlChar* sComment =\n xmlStrcat( xmlCharStrdup(\"removed \"), sNewID );\n pReturn = xmlNewComment( sComment );\n xmlReplaceNode( pTemp, pReturn );\n xmlFree( pTemp );\n xmlFree( sNewID );\n xmlFree( sComment );\n }\n \/\/update topic's content on the basis of xhpfile's title\n else\n {\n xmlNodePtr pXhpNode = xmlDocGetRootElement( pXhpFile );\n for( pXhpNode = pXhpNode->children;\n pXhpNode; pXhpNode = pXhpNode->children )\n {\n while( pXhpNode->type != XML_ELEMENT_NODE )\n {\n pXhpNode = pXhpNode->next;\n }\n if(!xmlStrcmp(pXhpNode->name, (const xmlChar *)(\"title\")))\n {\n xmlChar* sTitle =\n xmlNodeListGetString(pXhpFile, pXhpNode->children, 1);\n OString sNewTitle =\n lcl_xmlStrToOString( sTitle ).\n replaceAll(\"$[officename]\",\"%PRODUCTNAME\").\n replaceAll(\"$[officeversion]\",\"%PRODUCTVERSION\");\n xmlNodeSetContent(\n pReturn,\n reinterpret_cast<const xmlChar*>( sNewTitle.getStr() ));\n xmlFree( sTitle );\n break;\n }\n }\n if( !pXhpNode )\n {\n std::cerr\n << \"Treex error: Cannot find title in \"\n << sXhpPath.getStr() << std::endl;\n return 0;\n }\n xmlFree( pXhpFile );\n xmlCleanupParser();\n }\n return pReturn;\n }\n \/\/Localize title attribute of help_section and node tags\n static void lcl_MergeLevel(\n xmlDocPtr io_pSource, const xmlNodePtr pRoot,\n const xmlChar * pNodeName, MergeDataFile* pMergeDataFile,\n const OString& rLang, const OString& rXhpRoot )\n {\n if( !pRoot->children )\n {\n return;\n }\n for( xmlNodePtr pCurrent = pRoot->children;\n pCurrent; pCurrent = pCurrent->next)\n {\n if( !xmlStrcmp(pCurrent->name, pNodeName) )\n {\n if( pMergeDataFile )\n {\n xmlChar* pID = xmlGetProp(pCurrent, (const xmlChar*)(\"id\"));\n ResData aResData(\n \"\", lcl_xmlStrToOString( pID ),\n static_cast<OString>(io_pSource->name) );\n xmlFree( pID );\n aResData.sResTyp = lcl_xmlStrToOString( pNodeName );\n PFormEntrys* pEntrys =\n pMergeDataFile->GetPFormEntrys( &aResData );\n if( pEntrys )\n {\n OString sNewText;\n pEntrys->GetText( sNewText, STRING_TYP_TEXT, rLang );\n xmlSetProp(\n pCurrent, (const xmlChar*)(\"title\"),\n (const xmlChar*)(sNewText.getStr()));\n }\n }\n lcl_MergeLevel(\n io_pSource, pCurrent, (const xmlChar *)(\"node\"),\n pMergeDataFile, rLang, rXhpRoot );\n }\n else if( !xmlStrcmp(pCurrent->name, (const xmlChar *)(\"topic\")) )\n {\n pCurrent = lcl_UpdateTopic( pCurrent, rXhpRoot );\n }\n }\n }\n}\n\n\/\/Parse tree file\nTreeParser::TreeParser(\n const OString& rInputFile, const OString& rLang )\n : m_pSource( 0 )\n , m_sLang( rLang )\n , m_bIsInitialized( false )\n{\n m_pSource = xmlParseFile( rInputFile.getStr() );\n if ( !m_pSource ) {\n std::cerr\n << \"Treex error: Cannot open source file: \"\n << rInputFile.getStr() << std::endl;\n return;\n }\n if( !m_pSource->name )\n {\n m_pSource->name = new char[strlen(rInputFile.getStr())+1];\n strcpy( m_pSource->name, rInputFile.getStr() );\n }\n m_bIsInitialized = true;\n}\n\nTreeParser::~TreeParser()\n{\n}\n\n\/\/Extract strings form source file\nvoid TreeParser::Extract(\n const OString& rSDFFile, const OString& rPrj, const OString& rRoot )\n{\n assert( m_bIsInitialized );\n std::ofstream aSDFStream(\n rSDFFile.getStr(), std::ios_base::out | std::ios_base::trunc );\n if( !aSDFStream.is_open() )\n {\n std::cerr\n << \"Treex error: Cannot open sdffile for extract: \"\n << rSDFFile.getStr() << std::endl;\n return;\n }\n\n xmlNodePtr pRootNode = xmlDocGetRootElement( m_pSource );\n lcl_ExtractLevel(\n m_pSource, pRootNode, (const xmlChar *)(\"help_section\"),\n aSDFStream, rPrj, rRoot );\n\n xmlFreeDoc( m_pSource );\n xmlCleanupParser();\n aSDFStream.close();\n m_bIsInitialized = false;\n}\n\n\/\/Merge strings to tree file and update reference to help files(xhp)\nvoid TreeParser::Merge(\n const OString &rMergeSrc, const OString &rDestinationFile,\n const OString &rXhpRoot )\n{\n assert( m_bIsInitialized );\n\n const xmlNodePtr pRootNode = xmlDocGetRootElement( m_pSource );\n if( m_sLang == \"en-US\" )\n {\n lcl_MergeLevel(\n m_pSource, pRootNode, (const xmlChar *)(\"help_section\"),\n 0, m_sLang, rXhpRoot );\n }\n else\n {\n MergeDataFile aMergeDataFile(\n rMergeSrc, static_cast<OString>( m_pSource->name ), false );\n const std::vector<OString> vLanguages = aMergeDataFile.GetLanguages();\n if( !vLanguages.empty() && vLanguages[0] != m_sLang )\n {\n std::cerr\n << \"Treex error: given language conflicts with \"\n << \"language of Mergedata file: \"\n << m_sLang.getStr() << \" - \" << rMergeSrc.getStr() << std::endl;\n return;\n }\n lcl_MergeLevel(\n m_pSource, pRootNode, (const xmlChar *)(\"help_section\"),\n &aMergeDataFile, m_sLang, rXhpRoot );\n }\n\n xmlSaveFile( rDestinationFile.getStr(), m_pSource );\n xmlFreeDoc( m_pSource );\n xmlCleanupParser();\n m_bIsInitialized = false;\n}\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Fix some encoding problem in treemerge<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include <cstring>\n\n#include <libxml\/tree.h>\n#include <libxml\/parser.h>\n#include <libxml\/xmlmemory.h>\n#include <libxml\/xmlstring.h>\n\n#include \"export.hxx\"\n#include \"common.hxx\"\n#include \"treemerge.hxx\"\n\n\nnamespace\n{\n \/\/Write out an sdf line\n static void lcl_WriteSDF(\n std::ofstream &aSDFStream, const OString& rText, const OString& rPrj,\n const OString& rActFileName, const OString& rID, const OString& rType )\n {\n OString sOutput( rPrj ); sOutput += \"\\t\";\n sOutput += rActFileName;\n sOutput += \"\\t0\\t\";\n sOutput += rType; sOutput += \"\\t\";\n sOutput += rID; sOutput += \"\\t\\t\\t\\t0\\ten-US\\t\";\n sOutput += rText; sOutput += \"\\t\\t\\t\\t\";\n aSDFStream << sOutput.getStr() << std::endl;\n }\n\n \/\/Convert xmlChar* to OString\n static OString lcl_xmlStrToOString( const xmlChar* pString )\n {\n xmlChar* pTemp = xmlStrdup( pString );\n OString sResult =\n static_cast<OString>(reinterpret_cast<sal_Char*>( pTemp ));\n xmlFree( pTemp );\n return sResult;\n }\n\n \/\/Extract strings from nodes on all level recursively\n static void lcl_ExtractLevel(\n const xmlDocPtr pSource, const xmlNodePtr pRoot,\n const xmlChar* pNodeName, std::ofstream& rSDFStream,\n const OString& rPrj, const OString& rRoot )\n {\n if( !pRoot->children )\n {\n return;\n }\n for( xmlNodePtr pCurrent = pRoot->children->next;\n pCurrent; pCurrent = pCurrent->next)\n {\n if (!xmlStrcmp(pCurrent->name, pNodeName))\n {\n xmlChar* pID = xmlGetProp(pCurrent, (const xmlChar*)(\"id\"));\n xmlChar* pText =\n xmlGetProp(pCurrent, (const xmlChar*)(\"title\"));\n lcl_WriteSDF(\n rSDFStream,\n lcl_xmlStrToOString( pText ),\n rPrj,\n common::pathnameToken(\n pSource->name, rRoot.getStr()),\n lcl_xmlStrToOString( pID ),\n lcl_xmlStrToOString( pNodeName ));\n\n xmlFree( pID );\n xmlFree( pText );\n\n lcl_ExtractLevel(\n pSource, pCurrent, (const xmlChar *)(\"node\"),\n rSDFStream, rPrj, rRoot );\n }\n }\n }\n\n \/\/Update id and content of the topic\n static xmlNodePtr lcl_UpdateTopic(\n const xmlNodePtr pCurrent, const OString& rXhpRoot )\n {\n xmlNodePtr pReturn = pCurrent;\n xmlChar* pID = xmlGetProp(pReturn, (const xmlChar*)(\"id\"));\n const OString sID =\n lcl_xmlStrToOString( pID );\n xmlFree( pID );\n\n const sal_Int32 nFirstSlash = sID.indexOf(\"\/\");\n \/\/Update id attribute of topic\n {\n OString sNewID =\n sID.copy( 0, nFirstSlash + 1 ) +\n rXhpRoot.copy( rXhpRoot.lastIndexOf(\"\/\") + 1 ) +\n sID.copy( sID.indexOf( \"\/\", nFirstSlash + 1 ) );\n xmlSetProp(\n pReturn, (const xmlChar*)(\"id\"),\n reinterpret_cast<const xmlChar*>(sNewID.getStr()));\n }\n\n const OString sXhpPath =\n rXhpRoot +\n sID.copy(sID.indexOf(\"\/\", nFirstSlash + 1));\n xmlDocPtr pXhpFile = xmlParseFile( sXhpPath.getStr() );\n \/\/if xhpfile is missing than we put this topic into comment\n if ( !pXhpFile )\n {\n xmlNodePtr pTemp = pReturn;\n xmlChar* sNewID =\n xmlGetProp(pReturn, (const xmlChar*)(\"id\"));\n xmlChar* sComment =\n xmlStrcat( xmlCharStrdup(\"removed \"), sNewID );\n pReturn = xmlNewComment( sComment );\n xmlReplaceNode( pTemp, pReturn );\n xmlFree( pTemp );\n xmlFree( sNewID );\n xmlFree( sComment );\n }\n \/\/update topic's content on the basis of xhpfile's title\n else\n {\n xmlNodePtr pXhpNode = xmlDocGetRootElement( pXhpFile );\n for( pXhpNode = pXhpNode->children;\n pXhpNode; pXhpNode = pXhpNode->children )\n {\n while( pXhpNode->type != XML_ELEMENT_NODE )\n {\n pXhpNode = pXhpNode->next;\n }\n if(!xmlStrcmp(pXhpNode->name, (const xmlChar *)(\"title\")))\n {\n xmlChar* sTitle =\n xmlNodeListGetString(pXhpFile, pXhpNode->children, 1);\n OString sNewTitle =\n lcl_xmlStrToOString( sTitle ).\n replaceAll(\"$[officename]\",\"%PRODUCTNAME\").\n replaceAll(\"$[officeversion]\",\"%PRODUCTVERSION\");\n xmlNodeSetContent(\n pReturn,\n xmlEncodeSpecialChars( NULL,\n reinterpret_cast<const xmlChar*>(\n sNewTitle.getStr() )));\n xmlFree( sTitle );\n break;\n }\n }\n if( !pXhpNode )\n {\n std::cerr\n << \"Treex error: Cannot find title in \"\n << sXhpPath.getStr() << std::endl;\n return 0;\n }\n xmlFree( pXhpFile );\n xmlCleanupParser();\n }\n return pReturn;\n }\n \/\/Localize title attribute of help_section and node tags\n static void lcl_MergeLevel(\n xmlDocPtr io_pSource, const xmlNodePtr pRoot,\n const xmlChar * pNodeName, MergeDataFile* pMergeDataFile,\n const OString& rLang, const OString& rXhpRoot )\n {\n if( !pRoot->children )\n {\n return;\n }\n for( xmlNodePtr pCurrent = pRoot->children;\n pCurrent; pCurrent = pCurrent->next)\n {\n if( !xmlStrcmp(pCurrent->name, pNodeName) )\n {\n if( pMergeDataFile )\n {\n xmlChar* pID = xmlGetProp(pCurrent, (const xmlChar*)(\"id\"));\n ResData aResData(\n \"\", lcl_xmlStrToOString( pID ),\n static_cast<OString>(io_pSource->name) );\n xmlFree( pID );\n aResData.sResTyp = lcl_xmlStrToOString( pNodeName );\n PFormEntrys* pEntrys =\n pMergeDataFile->GetPFormEntrys( &aResData );\n if( pEntrys )\n {\n OString sNewText;\n pEntrys->GetText( sNewText, STRING_TYP_TEXT, rLang );\n xmlSetProp(\n pCurrent, (const xmlChar*)(\"title\"),\n (const xmlChar*)(sNewText.getStr()));\n }\n }\n lcl_MergeLevel(\n io_pSource, pCurrent, (const xmlChar *)(\"node\"),\n pMergeDataFile, rLang, rXhpRoot );\n }\n else if( !xmlStrcmp(pCurrent->name, (const xmlChar *)(\"topic\")) )\n {\n pCurrent = lcl_UpdateTopic( pCurrent, rXhpRoot );\n }\n }\n }\n}\n\n\/\/Parse tree file\nTreeParser::TreeParser(\n const OString& rInputFile, const OString& rLang )\n : m_pSource( 0 )\n , m_sLang( rLang )\n , m_bIsInitialized( false )\n{\n m_pSource = xmlParseFile( rInputFile.getStr() );\n if ( !m_pSource ) {\n std::cerr\n << \"Treex error: Cannot open source file: \"\n << rInputFile.getStr() << std::endl;\n return;\n }\n if( !m_pSource->name )\n {\n m_pSource->name = new char[strlen(rInputFile.getStr())+1];\n strcpy( m_pSource->name, rInputFile.getStr() );\n }\n m_bIsInitialized = true;\n}\n\nTreeParser::~TreeParser()\n{\n}\n\n\/\/Extract strings form source file\nvoid TreeParser::Extract(\n const OString& rSDFFile, const OString& rPrj, const OString& rRoot )\n{\n assert( m_bIsInitialized );\n std::ofstream aSDFStream(\n rSDFFile.getStr(), std::ios_base::out | std::ios_base::trunc );\n if( !aSDFStream.is_open() )\n {\n std::cerr\n << \"Treex error: Cannot open sdffile for extract: \"\n << rSDFFile.getStr() << std::endl;\n return;\n }\n\n xmlNodePtr pRootNode = xmlDocGetRootElement( m_pSource );\n lcl_ExtractLevel(\n m_pSource, pRootNode, (const xmlChar *)(\"help_section\"),\n aSDFStream, rPrj, rRoot );\n\n xmlFreeDoc( m_pSource );\n xmlCleanupParser();\n aSDFStream.close();\n m_bIsInitialized = false;\n}\n\n\/\/Merge strings to tree file and update reference to help files(xhp)\nvoid TreeParser::Merge(\n const OString &rMergeSrc, const OString &rDestinationFile,\n const OString &rXhpRoot )\n{\n assert( m_bIsInitialized );\n\n const xmlNodePtr pRootNode = xmlDocGetRootElement( m_pSource );\n if( m_sLang == \"en-US\" )\n {\n lcl_MergeLevel(\n m_pSource, pRootNode, (const xmlChar *)(\"help_section\"),\n 0, m_sLang, rXhpRoot );\n }\n else\n {\n MergeDataFile aMergeDataFile(\n rMergeSrc, static_cast<OString>( m_pSource->name ), false );\n const std::vector<OString> vLanguages = aMergeDataFile.GetLanguages();\n if( !vLanguages.empty() && vLanguages[0] != m_sLang )\n {\n std::cerr\n << \"Treex error: given language conflicts with \"\n << \"language of Mergedata file: \"\n << m_sLang.getStr() << \" - \" << rMergeSrc.getStr() << std::endl;\n return;\n }\n lcl_MergeLevel(\n m_pSource, pRootNode, (const xmlChar *)(\"help_section\"),\n &aMergeDataFile, m_sLang, rXhpRoot );\n }\n\n xmlSaveFile( rDestinationFile.getStr(), m_pSource );\n xmlFreeDoc( m_pSource );\n xmlCleanupParser();\n m_bIsInitialized = false;\n}\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\n#include <math.h>\n#include <iostream>\n#include \"libvideogfx\/libvideogfx.hh\"\n#include <unistd.h>\n\nusing namespace std;\nusing namespace videogfx;\n\n\nint main()\n{\n try\n {\n int16 sine [44100];\n int16 sine2[44100];\n\n for (int i=0;i<44100;i++)\n\t{\n\t sine [i] = (int)(20000*sin(2*M_PI*i* 500\/44100));\n\t sine2[i] = (int)(20000*sin(2*M_PI*i* 750\/44100));\n\t}\n\n AudioSink_LinuxSndCard snd;\n AudioParam param;\n param.n_channels = 2;\n param.rate = 44100;\n snd.SetParam(param);\n param = snd.AskParam();\n\n int16 buf[2*44100];\n for (int i=0;i<44100;i++)\n\t{\n\t buf[2*i ]=sine [i];\n\t buf[2*i+1]=sine2[i];\n\t}\n\n for (int i=0;i<5;i++)\n\t{\n\t snd.SendSamples(buf,2*44100,0);\n\t}\n\n while (snd.PresentationDataPending())\n\t{\n\t snd.PresentData(snd.NextDataPresentationTime());\n\t usleep(100000);\n\t}\n }\n catch (const Excpt_Base& e)\n {\n MessageDisplay::Show(e);\n }\n\n return 0;\n}\n<commit_msg>removed obsolete parameter<commit_after>\n#include <math.h>\n#include <iostream>\n#include \"libvideogfx\/libvideogfx.hh\"\n#include <unistd.h>\n\nusing namespace std;\nusing namespace videogfx;\n\n\nint main()\n{\n try\n {\n int16 sine [44100];\n int16 sine2[44100];\n\n for (int i=0;i<44100;i++)\n\t{\n\t sine [i] = (int)(20000*sin(2*M_PI*i* 500\/44100));\n\t sine2[i] = (int)(20000*sin(2*M_PI*i* 750\/44100));\n\t}\n\n AudioSink_LinuxSndCard snd;\n AudioParam param;\n param.n_channels = 2;\n param.rate = 44100;\n snd.SetParam(param);\n param = snd.AskParam();\n\n int16 buf[2*44100];\n for (int i=0;i<44100;i++)\n\t{\n\t buf[2*i ]=sine [i];\n\t buf[2*i+1]=sine2[i];\n\t}\n\n for (int i=0;i<5;i++)\n\t{\n\t snd.SendSamples(buf,2*44100);\n\t}\n\n while (snd.PresentationDataPending())\n\t{\n\t snd.PresentData(snd.NextDataPresentationTime());\n\t usleep(100000);\n\t}\n }\n catch (const Excpt_Base& e)\n {\n MessageDisplay::Show(e);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <tetris\/TetrisManager.h>\n#include <SFML\/Graphics\/RectangleShape.hpp>\n#include <SFML\/Graphics\/RenderWindow.hpp>\n#include <tetris\/Enums.h>\n\ntetrisGameManager::tetrisGameManager(int windowHeight, int windowWidth) : WINDOW_HEIGHT(windowHeight), WINDOW_WIDTH(windowWidth)\n{\n\n}\n\nvoid tetrisGameManager::checkLines()\n{\n\n\n}\n\nbool tetrisGameManager::checkLoseCondition()\n{\n\n return false;\n}\n\nvoid tetrisGameManager::drawWell(sf::RenderWindow& window)\n{\n \/\/ This could be useful.\n \/*switch(blockGrid[x][y])\n {\n case Empty:\n block.setFillColor(sf::Color::Black);\n block.setOutlineColor(sf::Color::Black);\n break;\n case Cyan:\n block.setFillColor(sf::Color::Cyan);\n block.setOutlineColor(sf::Color(96, 216, 220, 255));\n break;\n case Yellow:\n block.setFillColor(sf::Color::Yellow);\n block.setOutlineColor(sf::Color(222, 222, 79, 255));\n break;\n case Orange:\n block.setFillColor(sf::Color(255, 166, 31, 255));\n block.setOutlineColor(sf::Color(192, 124, 22, 255));\n break;\n case Blue:\n block.setFillColor(sf::Color::Blue);\n block.setOutlineColor(sf::Color(23, 19, 138, 255));\n break;\n case Green:\n block.setFillColor(sf::Color::Green);\n block.setOutlineColor(sf::Color(42, 183, 37, 255));\n break;\n case Red:\n block.setFillColor(sf::Color::Red);\n block.setOutlineColor(sf::Color(195, 25, 30, 255));\n break;\n case Purple:\n block.setFillColor(sf::Color(239, 68, 245, 255));\n block.setOutlineColor(sf::Color(181, 69, 195, 255));\n break;\n }*\/\n}\n\nvoid tetrisGameManager::updateGrid(sf::RenderWindow& window)\n{\n\n\n}\n<commit_msg>Added function for drawing a single tetrimino.<commit_after>#include <tetris\/TetrisManager.h>\n#include <SFML\/Graphics\/RectangleShape.hpp>\n#include <SFML\/Graphics\/RenderWindow.hpp>\n#include <tetris\/Enums.h>\n\ntetrisGameManager::tetrisGameManager(int windowHeight, int windowWidth) : WINDOW_HEIGHT(windowHeight), WINDOW_WIDTH(windowWidth)\n{\n\n}\n\nvoid tetrisGameManager::checkLines()\n{\n\n\n}\n\nbool tetrisGameManager::checkLoseCondition()\n{\n\n return false;\n}\n\nvoid tetrisGameManager::drawWell(sf::RenderWindow& window)\n{\n \/\/ This could be useful.\n \/*switch(blockGrid[x][y])\n {\n case Empty:\n block.setFillColor(sf::Color::Black);\n block.setOutlineColor(sf::Color::Black);\n break;\n case Cyan:\n block.setFillColor(sf::Color::Cyan);\n block.setOutlineColor(sf::Color(96, 216, 220, 255));\n break;\n case Yellow:\n block.setFillColor(sf::Color::Yellow);\n block.setOutlineColor(sf::Color(222, 222, 79, 255));\n break;\n case Orange:\n block.setFillColor(sf::Color(255, 166, 31, 255));\n block.setOutlineColor(sf::Color(192, 124, 22, 255));\n break;\n case Blue:\n block.setFillColor(sf::Color::Blue);\n block.setOutlineColor(sf::Color(23, 19, 138, 255));\n break;\n case Green:\n block.setFillColor(sf::Color::Green);\n block.setOutlineColor(sf::Color(42, 183, 37, 255));\n break;\n case Red:\n block.setFillColor(sf::Color::Red);\n block.setOutlineColor(sf::Color(195, 25, 30, 255));\n break;\n case Purple:\n block.setFillColor(sf::Color(239, 68, 245, 255));\n block.setOutlineColor(sf::Color(181, 69, 195, 255));\n break;\n }*\/\n}\n\nvoid tetrisGameManager::drawTetrimino(sf::RenderWindow& window)\n{\n switch(blockGrid[x][y])\n {\n case Empty:\n block.setFillColor(sf::Color::Black);\n block.setOutlineColor(sf::Color::Black);\n break;\n case Cyan:\n block.setFillColor(sf::Color::Cyan);\n block.setOutlineColor(sf::Color(96, 216, 220, 255));\n break;\n case Yellow:\n block.setFillColor(sf::Color::Yellow);\n block.setOutlineColor(sf::Color(222, 222, 79, 255));\n break;\n case Orange:\n block.setFillColor(sf::Color(255, 166, 31, 255));\n block.setOutlineColor(sf::Color(192, 124, 22, 255));\n break;\n case Blue:\n block.setFillColor(sf::Color::Blue);\n block.setOutlineColor(sf::Color(23, 19, 138, 255));\n break;\n case Green:\n block.setFillColor(sf::Color::Green);\n block.setOutlineColor(sf::Color(42, 183, 37, 255));\n break;\n case Red:\n block.setFillColor(sf::Color::Red);\n block.setOutlineColor(sf::Color(195, 25, 30, 255));\n break;\n case Purple:\n block.setFillColor(sf::Color(239, 68, 245, 255));\n block.setOutlineColor(sf::Color(181, 69, 195, 255));\n break;\n }\n}\n\nvoid tetrisGameManager::updateGrid(sf::RenderWindow& window)\n{\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"generator\/Sawtooth.h\"\n#include \"generator\/Sine.h\"\n#include \"generator\/Silence.h\"\n#include \"generator\/Square.h\"\n#include \"generator\/Triangle.h\"\n#include \"file\/File.h\"\n#include \"util\/StreamBuffer.h\"\n#include \"fx\/Accumulator.h\"\n#include \"fx\/ADSR.h\"\n#include \"fx\/Delay.h\"\n#include \"fx\/Envelope.h\"\n#include \"fx\/Fader.h\"\n#include \"fx\/Highpass.h\"\n#include \"fx\/IIRFilter.h\"\n#include \"fx\/Limiter.h\"\n#include \"fx\/Loop.h\"\n#include \"fx\/Lowpass.h\"\n#include \"fx\/Pitch.h\"\n#include \"fx\/Reverse.h\"\n#include \"fx\/Sum.h\"\n#include \"fx\/Threshold.h\"\n#include \"fx\/Volume.h\"\n#include \"fx\/SoundList.h\"\n#include \"fx\/MutableSound.h\"\n#include \"sequence\/Double.h\"\n#include \"sequence\/Superpose.h\"\n#include \"sequence\/PingPong.h\"\n#include \"respec\/LinearResample.h\"\n#include \"respec\/ChannelMapper.h\"\n#include \"util\/Buffer.h\"\n#include \"Exception.h\"\n\n#include <cassert>\n\nusing namespace aud;\n\n#define AUD_CAPI_IMPLEMENTATION\n#include \"AUD_PlaybackManager.h\"\n\nAUD_API AUD_PlaybackManager* AUD_PlaybackManager_create(AUD_Device* device)\n{\n\tassert(device);\n\n\ttry\n\t{\n\t\treturn new AUD_PlaybackManager(new PlaybackManager(*device));\n\t}\n\tcatch (Exception&)\n\t{\n\t\treturn nullptr;\n\t}\n}\n\nAUD_API void AUD_PlaybackManager_free(AUD_PlaybackManager* manager)\n{\n\tassert(manager);\n\tdelete manager;\n}\n\nAUD_API void AUD_PlaybackManager_play(AUD_PlaybackManager* manager, AUD_Sound* sound, unsigned int catKey)\n{\n\tassert(manager);\n\tassert(sound);\n\n\t(*manager)->play(*sound, catKey);\n}\n\nAUD_API int AUD_PlaybackManager_resume(AUD_PlaybackManager* manager, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->resume(catKey);\n}\n\nAUD_API int AUD_PlaybackManager_pause(AUD_PlaybackManager* manager, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->pause(catKey);\n}\n\nAUD_API float AUD_PlaybackManager_getVolume(AUD_PlaybackManager* manager, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->getVolume(catKey);\n}\n\nAUD_API int AUD_PlaybackManager_setVolume(AUD_PlaybackManager* manager, float volume, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->setVolume(volume, catKey);\n}\n\nAUD_API int AUD_PlaybackManager_stop(AUD_PlaybackManager* manager, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->stop(catKey);\n}\n\nAUD_API void AUD_PlaybackManager_clean(AUD_PlaybackManager* manager)\n{\n\tassert(manager);\n\t(*manager)->clean();\n}<commit_msg>Includes cleaned<commit_after>#include \"Exception.h\"\n\n#include <cassert>\n\nusing namespace aud;\n\n#define AUD_CAPI_IMPLEMENTATION\n#include \"AUD_PlaybackManager.h\"\n\nAUD_API AUD_PlaybackManager* AUD_PlaybackManager_create(AUD_Device* device)\n{\n\tassert(device);\n\n\ttry\n\t{\n\t\treturn new AUD_PlaybackManager(new PlaybackManager(*device));\n\t}\n\tcatch (Exception&)\n\t{\n\t\treturn nullptr;\n\t}\n}\n\nAUD_API void AUD_PlaybackManager_free(AUD_PlaybackManager* manager)\n{\n\tassert(manager);\n\tdelete manager;\n}\n\nAUD_API void AUD_PlaybackManager_play(AUD_PlaybackManager* manager, AUD_Sound* sound, unsigned int catKey)\n{\n\tassert(manager);\n\tassert(sound);\n\n\t(*manager)->play(*sound, catKey);\n}\n\nAUD_API int AUD_PlaybackManager_resume(AUD_PlaybackManager* manager, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->resume(catKey);\n}\n\nAUD_API int AUD_PlaybackManager_pause(AUD_PlaybackManager* manager, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->pause(catKey);\n}\n\nAUD_API float AUD_PlaybackManager_getVolume(AUD_PlaybackManager* manager, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->getVolume(catKey);\n}\n\nAUD_API int AUD_PlaybackManager_setVolume(AUD_PlaybackManager* manager, float volume, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->setVolume(volume, catKey);\n}\n\nAUD_API int AUD_PlaybackManager_stop(AUD_PlaybackManager* manager, unsigned int catKey)\n{\n\tassert(manager);\n\treturn (*manager)->stop(catKey);\n}\n\nAUD_API void AUD_PlaybackManager_clean(AUD_PlaybackManager* manager)\n{\n\tassert(manager);\n\t(*manager)->clean();\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/sha1_hash.hpp>\n#include <boost\/python.hpp>\n\nvoid bind_sha1_hash()\n{\n using namespace boost::python;\n using namespace libtorrent;\n\n class_<sha1_hash>(\"sha1_hash\")\n .def(self == self)\n .def(self != self)\n .def(self < self)\n .def(self_ns::str(self))\n .def(init<char const*>())\n .def(\"clear\", &sha1_hash::clear)\n .def(\"is_all_zeros\", &sha1_hash::is_all_zeros)\n .def(\"to_string\", &sha1_hash::to_string)\n\/\/ .def(\"__getitem__\", &sha1_hash::opreator[])\n ;\n\n scope().attr(\"big_number\") = scope().attr(\"sha1_hash\"); \n scope().attr(\"peer_id\") = scope().attr(\"peer_id\"); \n}\n\n<commit_msg>fix typo in python binding<commit_after>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/sha1_hash.hpp>\n#include <boost\/python.hpp>\n\nvoid bind_sha1_hash()\n{\n using namespace boost::python;\n using namespace libtorrent;\n\n class_<sha1_hash>(\"sha1_hash\")\n .def(self == self)\n .def(self != self)\n .def(self < self)\n .def(self_ns::str(self))\n .def(init<char const*>())\n .def(\"clear\", &sha1_hash::clear)\n .def(\"is_all_zeros\", &sha1_hash::is_all_zeros)\n .def(\"to_string\", &sha1_hash::to_string)\n\/\/ .def(\"__getitem__\", &sha1_hash::opreator[])\n ;\n\n scope().attr(\"big_number\") = scope().attr(\"sha1_hash\"); \n scope().attr(\"peer_id\") = scope().attr(\"sha1_hash\"); \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ * BeginRiceCopyright *****************************************************\n\/\/\n\/\/ $HeadURL$\n\/\/ $Id$\n\/\/\n\/\/ --------------------------------------------------------------------------\n\/\/ Part of HPCToolkit (hpctoolkit.org)\n\/\/\n\/\/ Information about sources of support for research and development of\n\/\/ HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.\n\/\/ --------------------------------------------------------------------------\n\/\/\n\/\/ Copyright ((c)) 2002-2017, Rice University\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Rice University (RICE) 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 RICE and contributors \"as is\" and any\n\/\/ express or implied warranties, including, but not limited to, the\n\/\/ implied warranties of merchantability and fitness for a particular\n\/\/ purpose are disclaimed. In no event shall RICE or contributors be\n\/\/ liable for any direct, indirect, incidental, special, exemplary, or\n\/\/ consequential damages (including, but not limited to, procurement of\n\/\/ substitute goods or services; loss of use, data, or profits; or\n\/\/ business interruption) however caused and on any theory of liability,\n\/\/ whether in contract, strict liability, or tort (including negligence\n\/\/ or otherwise) arising in any way out of the use of this software, even\n\/\/ if advised of the possibility of such damage.\n\/\/\n\/\/ ******************************************************* EndRiceCopyright *\n\n\n\/\/***************************************************************************\n\/\/\n\/\/ File: Fatbin.cpp\n\/\/\n\/\/ Purpose:\n\/\/ unpack cuda fatbin \n\/\/\n\/\/ Description:\n\/\/\n\/\/***************************************************************************\n\n\/\/******************************************************************************\n\/\/ system includes\n\/\/******************************************************************************\n\n#include <string.h>\n\n\n\n\/\/******************************************************************************\n\/\/ local includes\n\/\/******************************************************************************\n\n#include <lib\/support\/StrUtil.hpp>\n#include <include\/hpctoolkit-config.h>\n\n#include \"InputFile.hpp\"\n#include \"ElfHelper.hpp\"\n\n\n\n\n\/\/******************************************************************************\n\/\/ macros\n\/\/******************************************************************************\n\n\n#define CUDA_FATBIN_SECTION \t\".nvFatBinSegment\"\n#define CUDA_FATBIN_DATASECTION \".nv_fatbin\"\n\n#define CUDA_FATBIN_MAGIC \t0x466243b1\n#define CUDA_FATBIN_VERSION \t1\n\n\n\n\/\/******************************************************************************\n\/\/ type definitions\n\/\/******************************************************************************\n\ntypedef struct NvidiaFatBinHeader_s {\n int32_t magicNumber; \n int32_t version; \n const unsigned long long* data; \n void* unused;\n} NvidiaFatBinHeader_t; \n\n\ntypedef std::vector<NvidiaFatBinHeader_t *> FatbinSectionVector;\n\n\n\n\/\/******************************************************************************\n\/\/ local variables\n\/\/******************************************************************************\n\nstatic FatbinSectionVector fatbinSectionVector;\n\n\n\n\/\/******************************************************************************\n\/\/ private functions\n\/\/******************************************************************************\n\nstatic bool\nisCubin(Elf *elf)\n{\n \/\/ open the header of the Elf object\n GElf_Ehdr ehdr_v; \n GElf_Ehdr *obj_ehdr = gelf_getehdr(elf, &ehdr_v);\n\n \/\/ check the header of the Elf object to see if it is a Cubin\n return (obj_ehdr && (obj_ehdr->e_machine == EM_CUDA));\n}\n\n\n#ifdef DYNINST_USE_CUDA\nstatic bool\nrecordIfNvFatbin\n(\n char *obj_ptr,\n Elf *elf,\n GElf_Ehdr *ehdr,\n Elf_Scn *scn,\n GElf_Shdr *shdr\n )\n{\n bool isFatbin = strcmp(elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name),\n\t\t\t CUDA_FATBIN_DATASECTION) == 0;\n if (isFatbin) { \n NvidiaFatBinHeader_t *fatbin =\n (NvidiaFatBinHeader_t *) elfSectionGetData(obj_ptr, shdr);\n std::string empty;\n ElfFile *elfFile = new ElfFile;\n if (elfFile->open((char *) fatbin->data, (size_t) shdr->sh_size, empty)) {\n fatbinSectionVector.push_back(fatbin);\n }\n }\n return isFatbin;\n}\n\n\nstatic bool\nrecordIfCubin\n(\n ElfFile *loadModule,\n char *obj_ptr,\n Elf *elf,\n GElf_Ehdr *ehdr,\n Elf_Scn *scn,\n GElf_Shdr *shdr,\n ElfFileVector *elfFileVector\n )\n{\n char *sectionData = elfSectionGetData(obj_ptr, shdr);\n\n std::string filename = loadModule->getFileName() + \"@\" +\n StrUtil::toStr(shdr->sh_addr, 16);\n\n ElfFile *elfFile = new ElfFile;\n\n \/\/ check if section represents an Elf object\n if (elfFile->open(sectionData, shdr->sh_size, filename)) {\n\n \/\/ if the Elf file is a CUBIN, add it to the vector of load\n \/\/ modules to be analyzed\n if (isCubin(elfFile->getElf())) {\n elfFileVector->push_back(elfFile);\n return true;\n } else {\n delete elfFile;\n }\n }\n return false;\n}\n#endif\n\t\n\n\/\/ cubin text segments all start at offset 0 and are thus overlapping.\n\/\/ relocate each text segment so that it begins at its offset in the\n\/\/ cubin. when this function returns, text segments no longer overlap.\nstatic bool\nfindCubinSections\n(\n ElfFile *elfFile,\n char *obj_ptr,\n Elf *elf,\n ElfSectionVector *sections,\n ElfFileVector *elfFileVector\n )\n{\n int count = 0;\n\n#ifdef DYNINST_USE_CUDA\n GElf_Ehdr ehdr_v;\n GElf_Ehdr *ehdr = gelf_getehdr(elf, &ehdr_v);\n\n if (ehdr) {\n for (auto si = sections->begin(); si != sections->end(); si++) {\n Elf_Scn *scn = *si;\n GElf_Shdr shdr_v;\n GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_v);\n if (!shdr) continue;\n\n if (recordIfNvFatbin(obj_ptr, elf, ehdr, scn, shdr)) {\n\tcount++;\n } else if (recordIfCubin(elfFile, obj_ptr, elf, ehdr, scn,\n\t\t\t shdr, elfFileVector)) {\n\tcount++;\n }\n }\n }\n#endif\n return count > 0;\n}\n\n\n\n\/\/******************************************************************************\n\/\/ interface functions\n\/\/******************************************************************************\n\nbool\nfindCubins\n(\n ElfFile *elfFile,\n ElfFileVector *elfFileVector\n)\n{\n bool success = false;\n Elf *elf = elfFile->getElf();\n\n ElfSectionVector *sections = elfGetSectionVector(elf);\n \n if (sections) {\n success = findCubinSections(elfFile, elfFile->getMemory(), elf,\n\t\t\t sections, elfFileVector);\n }\n return success;\n}\n\n\n\n\/\/******************************************************************************\n\/\/ debugging support\n\/\/******************************************************************************\n\nvoid\nwriteElfFile\n(\n ElfFile *elfFile,\n const char *suffix\n)\n{\n std::string filename = elfFile->getFileName() + suffix;\n FILE *f = fopen(filename.c_str(), \"w\");\n fwrite(elfFile->getMemory(), elfFile->getLength(), 1, f);\n fclose(f);\n}\n\n\nvoid\nwriteCubins(\n ElfFileVector *elfFileVector\n)\n{\n for(unsigned int i = 0; i < elfFileVector->size(); i++) {\n ElfFile *elfFile = (*elfFileVector)[i];\n if (isCubin(elfFile->getElf())) {\n writeElfFile(elfFile, \".cubin\");\n }\n }\n}\n<commit_msg>fix compilation on older systems where EM_CUDA isn't defined in headers<commit_after>\/\/ * BeginRiceCopyright *****************************************************\n\/\/\n\/\/ $HeadURL$\n\/\/ $Id$\n\/\/\n\/\/ --------------------------------------------------------------------------\n\/\/ Part of HPCToolkit (hpctoolkit.org)\n\/\/\n\/\/ Information about sources of support for research and development of\n\/\/ HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.\n\/\/ --------------------------------------------------------------------------\n\/\/\n\/\/ Copyright ((c)) 2002-2017, Rice University\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Rice University (RICE) 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 RICE and contributors \"as is\" and any\n\/\/ express or implied warranties, including, but not limited to, the\n\/\/ implied warranties of merchantability and fitness for a particular\n\/\/ purpose are disclaimed. In no event shall RICE or contributors be\n\/\/ liable for any direct, indirect, incidental, special, exemplary, or\n\/\/ consequential damages (including, but not limited to, procurement of\n\/\/ substitute goods or services; loss of use, data, or profits; or\n\/\/ business interruption) however caused and on any theory of liability,\n\/\/ whether in contract, strict liability, or tort (including negligence\n\/\/ or otherwise) arising in any way out of the use of this software, even\n\/\/ if advised of the possibility of such damage.\n\/\/\n\/\/ ******************************************************* EndRiceCopyright *\n\n\n\/\/***************************************************************************\n\/\/\n\/\/ File: Fatbin.cpp\n\/\/\n\/\/ Purpose:\n\/\/ unpack cuda fatbin \n\/\/\n\/\/ Description:\n\/\/\n\/\/***************************************************************************\n\n\/\/******************************************************************************\n\/\/ system includes\n\/\/******************************************************************************\n\n#include <string.h>\n\n\n\n\/\/******************************************************************************\n\/\/ local includes\n\/\/******************************************************************************\n\n#include <lib\/support\/StrUtil.hpp>\n#include <include\/hpctoolkit-config.h>\n\n#include <Elf_X.h>\n\n#include \"InputFile.hpp\"\n#include \"ElfHelper.hpp\"\n\n\n\n\n\/\/******************************************************************************\n\/\/ macros\n\/\/******************************************************************************\n\n\n#define CUDA_FATBIN_SECTION \t\".nvFatBinSegment\"\n#define CUDA_FATBIN_DATASECTION \".nv_fatbin\"\n\n#define CUDA_FATBIN_MAGIC \t0x466243b1\n#define CUDA_FATBIN_VERSION \t1\n\n\n\n\/\/******************************************************************************\n\/\/ type definitions\n\/\/******************************************************************************\n\ntypedef struct NvidiaFatBinHeader_s {\n int32_t magicNumber; \n int32_t version; \n const unsigned long long* data; \n void* unused;\n} NvidiaFatBinHeader_t; \n\n\ntypedef std::vector<NvidiaFatBinHeader_t *> FatbinSectionVector;\n\n\n\n\/\/******************************************************************************\n\/\/ local variables\n\/\/******************************************************************************\n\nstatic FatbinSectionVector fatbinSectionVector;\n\n\n\n\/\/******************************************************************************\n\/\/ private functions\n\/\/******************************************************************************\n\n#ifdef DYNINST_USE_CUDA\n\nstatic bool\nisCubin(Elf *elf)\n{\n \/\/ open the header of the Elf object\n GElf_Ehdr ehdr_v; \n GElf_Ehdr *obj_ehdr = gelf_getehdr(elf, &ehdr_v);\n\n \/\/ check the header of the Elf object to see if it is a Cubin\n return (obj_ehdr && (obj_ehdr->e_machine == EM_CUDA));\n}\n\n\nstatic bool\nrecordIfNvFatbin\n(\n char *obj_ptr,\n Elf *elf,\n GElf_Ehdr *ehdr,\n Elf_Scn *scn,\n GElf_Shdr *shdr\n )\n{\n bool isFatbin = strcmp(elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name),\n\t\t\t CUDA_FATBIN_DATASECTION) == 0;\n if (isFatbin) { \n NvidiaFatBinHeader_t *fatbin =\n (NvidiaFatBinHeader_t *) elfSectionGetData(obj_ptr, shdr);\n std::string empty;\n ElfFile *elfFile = new ElfFile;\n if (elfFile->open((char *) fatbin->data, (size_t) shdr->sh_size, empty)) {\n fatbinSectionVector.push_back(fatbin);\n }\n }\n return isFatbin;\n}\n\n\nstatic bool\nrecordIfCubin\n(\n ElfFile *loadModule,\n char *obj_ptr,\n Elf *elf,\n GElf_Ehdr *ehdr,\n Elf_Scn *scn,\n GElf_Shdr *shdr,\n ElfFileVector *elfFileVector\n )\n{\n char *sectionData = elfSectionGetData(obj_ptr, shdr);\n\n std::string filename = loadModule->getFileName() + \"@\" +\n StrUtil::toStr(shdr->sh_addr, 16);\n\n ElfFile *elfFile = new ElfFile;\n\n \/\/ check if section represents an Elf object\n if (elfFile->open(sectionData, shdr->sh_size, filename)) {\n\n \/\/ if the Elf file is a CUBIN, add it to the vector of load\n \/\/ modules to be analyzed\n if (isCubin(elfFile->getElf())) {\n elfFileVector->push_back(elfFile);\n return true;\n } else {\n delete elfFile;\n }\n }\n return false;\n}\n#endif\n\t\n\n\/\/ cubin text segments all start at offset 0 and are thus overlapping.\n\/\/ relocate each text segment so that it begins at its offset in the\n\/\/ cubin. when this function returns, text segments no longer overlap.\nstatic bool\nfindCubinSections\n(\n ElfFile *elfFile,\n char *obj_ptr,\n Elf *elf,\n ElfSectionVector *sections,\n ElfFileVector *elfFileVector\n )\n{\n int count = 0;\n\n#ifdef DYNINST_USE_CUDA\n GElf_Ehdr ehdr_v;\n GElf_Ehdr *ehdr = gelf_getehdr(elf, &ehdr_v);\n\n if (ehdr) {\n for (auto si = sections->begin(); si != sections->end(); si++) {\n Elf_Scn *scn = *si;\n GElf_Shdr shdr_v;\n GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_v);\n if (!shdr) continue;\n\n if (recordIfNvFatbin(obj_ptr, elf, ehdr, scn, shdr)) {\n\tcount++;\n } else if (recordIfCubin(elfFile, obj_ptr, elf, ehdr, scn,\n\t\t\t shdr, elfFileVector)) {\n\tcount++;\n }\n }\n }\n#endif\n return count > 0;\n}\n\n\n\n\/\/******************************************************************************\n\/\/ interface functions\n\/\/******************************************************************************\n\nbool\nfindCubins\n(\n ElfFile *elfFile,\n ElfFileVector *elfFileVector\n)\n{\n bool success = false;\n Elf *elf = elfFile->getElf();\n\n ElfSectionVector *sections = elfGetSectionVector(elf);\n \n if (sections) {\n success = findCubinSections(elfFile, elfFile->getMemory(), elf,\n\t\t\t sections, elfFileVector);\n }\n return success;\n}\n\n\n\n\/\/******************************************************************************\n\/\/ debugging support\n\/\/******************************************************************************\n\nvoid\nwriteElfFile\n(\n ElfFile *elfFile,\n const char *suffix\n)\n{\n std::string filename = elfFile->getFileName() + suffix;\n FILE *f = fopen(filename.c_str(), \"w\");\n fwrite(elfFile->getMemory(), elfFile->getLength(), 1, f);\n fclose(f);\n}\n\n\n#ifdef DYNINST_USE_CUDA\nvoid\nwriteCubins(\n ElfFileVector *elfFileVector\n)\n{\n for(unsigned int i = 0; i < elfFileVector->size(); i++) {\n ElfFile *elfFile = (*elfFileVector)[i];\n if (isCubin(elfFile->getElf())) {\n writeElfFile(elfFile, \".cubin\");\n }\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"WProgram.h\"\n#include <SPI.h>\n#include \"TMC262Stepper.h\"\n\n\/\/TMC262 register definitions\n#define DRIVER_CONTROL_REGISTER 0x0ul\n#define CHOPPER_CONFIG_REGISTER 0x80000ul\n#define COOL_STEP_REGISTER 0xA0000ul\n#define STALL_GUARD2_LOAD_MEASURE_REGISTER 0xC0000ul\n#define DRIVER_CONFIG_REGISTER 0xE0000ul\n\n#define REGISTER_BIT_PATTERN 0xFFFFFul\n\n\/\/definitions for the driver control register\n#define MICROSTEPPING_PATTERN 0xFul\n#define STEP_INTERPOLATION 0x200ul\n#define DOUBLE_EDGE_STEP 0x100ul\n\n\/\/definitions for the chopper config register\n#define CHOPPER_MODE_STANDARD 0x0ul\n#define CHOPPER_MODE_T_OFF_FAST_DECAY 0x4000ul\n\n#define RANDOM_TOFF_TIME 0x200ul\n#define BLANK_TIMING_SHIFT 15\n#define HYSTERESIS_DECREMENT_PATTERN 0x1800ul\n#define HYSTERESIS_DECREMENT_SHIFT 11\n#define HYSTERESIS_LOW_VALUE_PATTERN 0x780ul\n#define HYSTERESIS_LOW_SHIFT 7\n#define HYSTERESIS_START_VALUE_PATTERN 0x70ul\n#define HYSTERESIS_START_VALUE_SHIFT 4\n#define T_OFF_TIMING_PATERN 0xFul\n\n\/\/definitions for cool step register\n#define MINIMUM_CURRENT_FOURTH 0x8000ul\n#define CURRENT_DOWN_STEP_SPEED_PATTERN 0x6000ul\n#define SE_MAX_PATTERN 0xF00ul\n#define SE_CURRENT_STEP_WIDTH_PATTERN 0x60ul\n#define SE_MIN_PATTERN 0xful\n\n\/\/definitions for stall guard2 current register\n#define STALL_GUARD_FILTER_ENABLE 0x10000ul\n#define STALL_GUARD_TRESHHOLD_VALUE_PATTERN 0x7F00ul\n#define CURRENT_SCALING_PATTERN 0x1Ful\n\n\/\/default values\n#define INITIAL_MICROSTEPPING 0x3ul \/\/32th microstepping\n\n\n\/\/debuging output\n#define DEBUG\n\nTMC262Stepper::TMC262Stepper(int number_of_steps, int cs_pin, int dir_pin, int step_pin, unsigned int max_current)\n{\n\t\/\/save the pins for later use\n\tthis->cs_pin=cs_pin;\n\tthis->dir_pin=dir_pin;\n\tthis->step_pin = step_pin;\n\t\/\/initialize register values\n\tdriver_control_register_value=DRIVER_CONFIG_REGISTER | INITIAL_MICROSTEPPING;\n\tchopper_config_register=CHOPPER_CONFIG_REGISTER;\n\t\/\/calculate the current scaling from the max current setting (in mA)\n\tfloat mASetting = max_current;\n\t\/\/this is derrived from I=(cs+1)\/32*Vfs\/Rsense*1\/sqrt(2)\n\t\/\/with vfs=5\/16, Rsense=0,15\n\t\/\/giving the formula CS=(ImA*32\/(1000*k)-1 where k=Vfs\/Rsense*1\/sqrt(2) - too lazy to deal with complete formulas\n\tthis->current_scaling = (byte)((mASetting*0.0217223203180507)-0.5); \/\/theoretically - 1.0 for better rounding it is 0.5\n\t\n\t\/\/setting the default register values\n\tdriver_control_register_value=DRIVER_CONTROL_REGISTER|INITIAL_MICROSTEPPING;\n\tchopper_config_register=CHOPPER_CONFIG_REGISTER | (3ul<<BLANK_TIMING_SHIFT) | CHOPPER_MODE_T_OFF_FAST_DECAY | (3ul<<HYSTERESIS_LOW_SHIFT) | (5ul << HYSTERESIS_START_VALUE_SHIFT) | 7;\n\tcool_step_register_value=COOL_STEP_REGISTER;\n\tstall_guard2_current_register_value=STALL_GUARD2_LOAD_MEASURE_REGISTER|current_scaling;\n\tdriver_configuration=DRIVER_CONFIG_REGISTER;\n}\n\nvoid TMC262Stepper::start() {\n\n#ifdef DEBUG\t\n\tSerial.println(\"TMC262 stepper library\");\n\tSerial.print(\"CS pin: \");\n\tSerial.println(cs_pin);\n\tSerial.print(\"DIR pin: \");\n\tSerial.println(dir_pin);\n\tSerial.print(\"STEP pin: \");\n\tSerial.println(step_pin);\n\tSerial.print(\"current scaling: \");\n\tSerial.println(current_scaling,DEC);\n#endif\n\t\/\/set the pins as output & its initial value\n\tpinMode(step_pin, OUTPUT); \n\tpinMode(dir_pin, OUTPUT); \n\tpinMode(cs_pin, OUTPUT); \n\tdigitalWrite(step_pin, LOW); \n\tdigitalWrite(dir_pin, LOW); \n\tdigitalWrite(cs_pin, HIGH); \n\t\n\t\n\tSPI.setBitOrder(MSBFIRST);\n\tSPI.setClockDivider(SPI_CLOCK_DIV8);\n\tSPI.setDataMode(SPI_MODE0);\n\tSPI.begin();\n\t\t\n\tsend262(driver_control_register_value); \n\tsend262(chopper_config_register);\n\tsend262(cool_step_register_value);\n\tsend262(stall_guard2_current_register_value);\n\tsend262(driver_configuration);\n\t\n}\n\n\/*\n Sets the speed in revs per minute\n\n*\/\nvoid TMC262Stepper::setSpeed(long whatSpeed)\n{\n this->step_delay = 60L * 1000L \/ this->number_of_steps \/ whatSpeed;\n}\n\n\/*\n Moves the motor steps_to_move steps. If the number is negative, \n the motor moves in the reverse direction.\n *\/\nvoid TMC262Stepper::step(int steps_to_move)\n{ \n int steps_left = abs(steps_to_move); \/\/ how many steps to take\n \n \/\/ determine direction based on whether steps_to_mode is + or -:\n if (steps_to_move > 0) {this->direction = 1;}\n if (steps_to_move < 0) {this->direction = 0;}\n \n \n \/\/ decrement the number of steps, moving one step each time:\n while(steps_left > 0) {\n \/\/ move only if the appropriate delay has passed:\n if (millis() - this->last_step_time >= this->step_delay) {\n \/\/ get the timeStamp of when you stepped:\n this->last_step_time = millis();\n \/\/ increment or decrement the step number,\n \/\/ depending on direction:\n if (this->direction == 1) {\n\t\t digitalWrite(step_pin, HIGH);\n } \n else { \n\t\t digitalWrite(dir_pin, HIGH);\n\t\t digitalWrite(step_pin, HIGH);\n }\n \/\/ decrement the steps left:\n steps_left--;\n\t \/\/disable sthe step & dir pins\n\t delay(20);\n\t digitalWrite(step_pin, LOW);\n\t digitalWrite(dir_pin, LOW);\n }\n }\n}\n\n\/*\n version() returns the version of the library:\n*\/\nint TMC262Stepper::version(void)\n{\n return 1;\n}\n\nunsigned long TMC262Stepper::send262(unsigned long datagram) {\n\tunsigned long i_datagram;\n\n\t\/\/ensure that only valid bist are set (0-19)\n\t\/\/datagram &=REGISTER_BIT_PATTERN;\n\n#ifdef DEBUG\n\tSerial.print(\"Sending \");\n\tSerial.println(datagram,HEX);\n#endif\n\t\n\t\/\/select the TMC driver\n\tdigitalWrite(cs_pin,LOW);\n\t\n\t\/\/write\/read the values\n\ti_datagram = SPI.transfer((datagram >> 16) & 0xff);\n\ti_datagram <<= 8;\n\ti_datagram |= SPI.transfer((datagram >> 8) & 0xff);\n\ti_datagram <<= 8;\n\ti_datagram |= SPI.transfer((datagram ) & 0xff);\n\ti_datagram >>= 4;\n\t\n\t\/\/deselect the TMC chip\n\tdigitalWrite(cs_pin,HIGH); \n#ifdef DEBUG\n\tSerial.print(\"Received \");\n\tSerial.println(i_datagram,HEX);\n#endif\n\t\n\treturn i_datagram;\n}\n\nvoid TMC262Stepper::setMicrostepping(int setting) {\n\tlong setting_pattern;\n\t\/\/poor mans log\n\tif (setting>=256) {\n\t\tsetting_pattern=0;\n\t} else if (setting>=128) {\n\t\tsetting_pattern=1;\n\t} else if (setting>=64) {\n\t\tsetting_pattern=2;\n\t} else if (setting>=32) {\n\t\tsetting_pattern=3;\n\t} else if (setting>=16) {\n\t\tsetting_pattern=4;\n\t} else if (setting>=8) {\n\t\tsetting_pattern=5;\n\t} else if (setting>=4) {\n\t\tsetting_pattern=6;\n\t} else if (setting>=2) {\n\t\tsetting_pattern=7;\n \/\/1 and 0 lead to full step\n\t} else if (setting<=1) {\n\t\tsetting_pattern=8;\n\t}\n\t\/\/delete the old value\n\tthis->driver_control_register_value &=0xFFFF0ul;\n\t\/\/set the new value\n\tthis->driver_control_register_value |=setting_pattern;\n\tsend262(driver_control_register_value);\n}<commit_msg>the delay can be shortened<commit_after>#include \"WProgram.h\"\n#include <SPI.h>\n#include \"TMC262Stepper.h\"\n\n\/\/TMC262 register definitions\n#define DRIVER_CONTROL_REGISTER 0x0ul\n#define CHOPPER_CONFIG_REGISTER 0x80000ul\n#define COOL_STEP_REGISTER 0xA0000ul\n#define STALL_GUARD2_LOAD_MEASURE_REGISTER 0xC0000ul\n#define DRIVER_CONFIG_REGISTER 0xE0000ul\n\n#define REGISTER_BIT_PATTERN 0xFFFFFul\n\n\/\/definitions for the driver control register\n#define MICROSTEPPING_PATTERN 0xFul\n#define STEP_INTERPOLATION 0x200ul\n#define DOUBLE_EDGE_STEP 0x100ul\n\n\/\/definitions for the chopper config register\n#define CHOPPER_MODE_STANDARD 0x0ul\n#define CHOPPER_MODE_T_OFF_FAST_DECAY 0x4000ul\n\n#define RANDOM_TOFF_TIME 0x200ul\n#define BLANK_TIMING_SHIFT 15\n#define HYSTERESIS_DECREMENT_PATTERN 0x1800ul\n#define HYSTERESIS_DECREMENT_SHIFT 11\n#define HYSTERESIS_LOW_VALUE_PATTERN 0x780ul\n#define HYSTERESIS_LOW_SHIFT 7\n#define HYSTERESIS_START_VALUE_PATTERN 0x70ul\n#define HYSTERESIS_START_VALUE_SHIFT 4\n#define T_OFF_TIMING_PATERN 0xFul\n\n\/\/definitions for cool step register\n#define MINIMUM_CURRENT_FOURTH 0x8000ul\n#define CURRENT_DOWN_STEP_SPEED_PATTERN 0x6000ul\n#define SE_MAX_PATTERN 0xF00ul\n#define SE_CURRENT_STEP_WIDTH_PATTERN 0x60ul\n#define SE_MIN_PATTERN 0xful\n\n\/\/definitions for stall guard2 current register\n#define STALL_GUARD_FILTER_ENABLE 0x10000ul\n#define STALL_GUARD_TRESHHOLD_VALUE_PATTERN 0x7F00ul\n#define CURRENT_SCALING_PATTERN 0x1Ful\n\n\/\/default values\n#define INITIAL_MICROSTEPPING 0x3ul \/\/32th microstepping\n\n\n\/\/debuging output\n#define DEBUG\n\nTMC262Stepper::TMC262Stepper(int number_of_steps, int cs_pin, int dir_pin, int step_pin, unsigned int max_current)\n{\n\t\/\/save the pins for later use\n\tthis->cs_pin=cs_pin;\n\tthis->dir_pin=dir_pin;\n\tthis->step_pin = step_pin;\n\t\/\/initialize register values\n\tdriver_control_register_value=DRIVER_CONFIG_REGISTER | INITIAL_MICROSTEPPING;\n\tchopper_config_register=CHOPPER_CONFIG_REGISTER;\n\t\/\/calculate the current scaling from the max current setting (in mA)\n\tfloat mASetting = max_current;\n\t\/\/this is derrived from I=(cs+1)\/32*Vfs\/Rsense*1\/sqrt(2)\n\t\/\/with vfs=5\/16, Rsense=0,15\n\t\/\/giving the formula CS=(ImA*32\/(1000*k)-1 where k=Vfs\/Rsense*1\/sqrt(2) - too lazy to deal with complete formulas\n\tthis->current_scaling = (byte)((mASetting*0.0217223203180507)-0.5); \/\/theoretically - 1.0 for better rounding it is 0.5\n\t\n\t\/\/setting the default register values\n\tdriver_control_register_value=DRIVER_CONTROL_REGISTER|INITIAL_MICROSTEPPING;\n\tchopper_config_register=CHOPPER_CONFIG_REGISTER | (3ul<<BLANK_TIMING_SHIFT) | CHOPPER_MODE_T_OFF_FAST_DECAY | (3ul<<HYSTERESIS_LOW_SHIFT) | (5ul << HYSTERESIS_START_VALUE_SHIFT) | 7;\n\tcool_step_register_value=COOL_STEP_REGISTER;\n\tstall_guard2_current_register_value=STALL_GUARD2_LOAD_MEASURE_REGISTER|current_scaling;\n\tdriver_configuration=DRIVER_CONFIG_REGISTER;\n}\n\nvoid TMC262Stepper::start() {\n\n#ifdef DEBUG\t\n\tSerial.println(\"TMC262 stepper library\");\n\tSerial.print(\"CS pin: \");\n\tSerial.println(cs_pin);\n\tSerial.print(\"DIR pin: \");\n\tSerial.println(dir_pin);\n\tSerial.print(\"STEP pin: \");\n\tSerial.println(step_pin);\n\tSerial.print(\"current scaling: \");\n\tSerial.println(current_scaling,DEC);\n#endif\n\t\/\/set the pins as output & its initial value\n\tpinMode(step_pin, OUTPUT); \n\tpinMode(dir_pin, OUTPUT); \n\tpinMode(cs_pin, OUTPUT); \n\tdigitalWrite(step_pin, LOW); \n\tdigitalWrite(dir_pin, LOW); \n\tdigitalWrite(cs_pin, HIGH); \n\t\n\t\n\tSPI.setBitOrder(MSBFIRST);\n\tSPI.setClockDivider(SPI_CLOCK_DIV8);\n\tSPI.setDataMode(SPI_MODE0);\n\tSPI.begin();\n\t\t\n\tsend262(driver_control_register_value); \n\tsend262(chopper_config_register);\n\tsend262(cool_step_register_value);\n\tsend262(stall_guard2_current_register_value);\n\tsend262(driver_configuration);\n\t\n}\n\n\/*\n Sets the speed in revs per minute\n\n*\/\nvoid TMC262Stepper::setSpeed(long whatSpeed)\n{\n this->step_delay = 60L * 1000L \/ this->number_of_steps \/ whatSpeed;\n}\n\n\/*\n Moves the motor steps_to_move steps. If the number is negative, \n the motor moves in the reverse direction.\n *\/\nvoid TMC262Stepper::step(int steps_to_move)\n{ \n int steps_left = abs(steps_to_move); \/\/ how many steps to take\n \n \/\/ determine direction based on whether steps_to_mode is + or -:\n if (steps_to_move > 0) {this->direction = 1;}\n if (steps_to_move < 0) {this->direction = 0;}\n \n \n \/\/ decrement the number of steps, moving one step each time:\n while(steps_left > 0) {\n \/\/ move only if the appropriate delay has passed:\n if (millis() - this->last_step_time >= this->step_delay) {\n \/\/ get the timeStamp of when you stepped:\n this->last_step_time = millis();\n \/\/ increment or decrement the step number,\n \/\/ depending on direction:\n if (this->direction == 1) {\n\t\t digitalWrite(step_pin, HIGH);\n } \n else { \n\t\t digitalWrite(dir_pin, HIGH);\n\t\t digitalWrite(step_pin, HIGH);\n }\n \/\/ decrement the steps left:\n steps_left--;\n\t \/\/disable sthe step & dir pins\n\t delay(2);\n\t digitalWrite(step_pin, LOW);\n\t digitalWrite(dir_pin, LOW);\n }\n }\n}\n\n\/*\n version() returns the version of the library:\n*\/\nint TMC262Stepper::version(void)\n{\n return 1;\n}\n\nunsigned long TMC262Stepper::send262(unsigned long datagram) {\n\tunsigned long i_datagram;\n\n\t\/\/ensure that only valid bist are set (0-19)\n\t\/\/datagram &=REGISTER_BIT_PATTERN;\n\n#ifdef DEBUG\n\tSerial.print(\"Sending \");\n\tSerial.println(datagram,HEX);\n#endif\n\t\n\t\/\/select the TMC driver\n\tdigitalWrite(cs_pin,LOW);\n\t\n\t\/\/write\/read the values\n\ti_datagram = SPI.transfer((datagram >> 16) & 0xff);\n\ti_datagram <<= 8;\n\ti_datagram |= SPI.transfer((datagram >> 8) & 0xff);\n\ti_datagram <<= 8;\n\ti_datagram |= SPI.transfer((datagram ) & 0xff);\n\ti_datagram >>= 4;\n\t\n\t\/\/deselect the TMC chip\n\tdigitalWrite(cs_pin,HIGH); \n#ifdef DEBUG\n\tSerial.print(\"Received \");\n\tSerial.println(i_datagram,HEX);\n#endif\n\t\n\treturn i_datagram;\n}\n\nvoid TMC262Stepper::setMicrostepping(int setting) {\n\tlong setting_pattern;\n\t\/\/poor mans log\n\tif (setting>=256) {\n\t\tsetting_pattern=0;\n\t} else if (setting>=128) {\n\t\tsetting_pattern=1;\n\t} else if (setting>=64) {\n\t\tsetting_pattern=2;\n\t} else if (setting>=32) {\n\t\tsetting_pattern=3;\n\t} else if (setting>=16) {\n\t\tsetting_pattern=4;\n\t} else if (setting>=8) {\n\t\tsetting_pattern=5;\n\t} else if (setting>=4) {\n\t\tsetting_pattern=6;\n\t} else if (setting>=2) {\n\t\tsetting_pattern=7;\n \/\/1 and 0 lead to full step\n\t} else if (setting<=1) {\n\t\tsetting_pattern=8;\n\t}\n\t\/\/delete the old value\n\tthis->driver_control_register_value &=0xFFFF0ul;\n\t\/\/set the new value\n\tthis->driver_control_register_value |=setting_pattern;\n\tsend262(driver_control_register_value);\n}<|endoftext|>"} {"text":"<commit_before>#include \"WProgram.h\"\n#include <SPI.h>\n#include \"TMC262Stepper.h\"\n\n#define DEBUG\n# define MRES 0\n\nTMC262Stepper::TMC262Stepper(int number_of_steps, int cs_pin, int dir_pin, int step_pin, unsigned int max_current)\n{\n\t\/\/save the pins for later use\n\tthis->cs_pin=cs_pin;\n\tthis->dir_pin=dir_pin;\n\tthis->step_pin = step_pin;\n\t\/\/calculate the current scaling from the max current setting (in mA)\n\tfloat mASetting = max_current;\n\t\/\/this is derrived from I=(cs+1)\/32*Vfs\/Rsense*1\/sqrt(2)\n\t\/\/with vfs=5\/16, Rsense=0,15\n\t\/\/giving the formula CS=(ImA*32\/(1000*k)-1 where k=Vfs\/Rsense*1\/sqrt(2) - too lazy to deal with complete formulas\n\tthis->current_scaling = (byte)((mASetting*0.0942809041582063)-1.0);\n}\n\nvoid TMC262Stepper::start() {\n\n#ifdef DEBUG\t\n\tSerial.println(\"TMC262 stepper library\");\n\tSerial.print(\"CS pin: \");\n\tSerial.println(cs_pin);\n\tSerial.print(\"DIR pin: \");\n\tSerial.println(dir_pin);\n\tSerial.print(\"STEP pin: \");\n\tSerial.println(step_pin);\n\tSerial.print(\"current scaling: \");\n\tSerial.println(current_scaling,DEC);\n#endif\n\t\/\/set the pins as output & its initial value\n\tpinMode(step_pin, OUTPUT); \n\tpinMode(dir_pin, OUTPUT); \n\tpinMode(cs_pin, OUTPUT); \n\tdigitalWrite(step_pin, LOW); \n\tdigitalWrite(dir_pin, LOW); \n\tdigitalWrite(cs_pin, HIGH); \n\t\n\t\n\tSPI.setBitOrder(MSBFIRST);\n\tSPI.setClockDivider(SPI_CLOCK_DIV8);\n\tSPI.setDataMode(SPI_MODE0);\n\tSPI.begin();\n\t\t\n\tsend262(0x00000|MRES); \n\tsend262(0x941D7);\n\tsend262(0xA0000);\n\tsend262(0xD000F);\n\tsend262(0xEF000);\n\t\n}\n\n\/*\n Sets the speed in revs per minute\n\n*\/\nvoid TMC262Stepper::setSpeed(long whatSpeed)\n{\n this->step_delay = 60L * 1000L \/ this->number_of_steps \/ whatSpeed;\n}\n\n\/*\n Moves the motor steps_to_move steps. If the number is negative, \n the motor moves in the reverse direction.\n *\/\nvoid TMC262Stepper::step(int steps_to_move)\n{ \n int steps_left = abs(steps_to_move); \/\/ how many steps to take\n \n \/\/ determine direction based on whether steps_to_mode is + or -:\n if (steps_to_move > 0) {this->direction = 1;}\n if (steps_to_move < 0) {this->direction = 0;}\n \n \n \/\/ decrement the number of steps, moving one step each time:\n while(steps_left > 0) {\n \/\/ move only if the appropriate delay has passed:\n if (millis() - this->last_step_time >= this->step_delay) {\n \/\/ get the timeStamp of when you stepped:\n this->last_step_time = millis();\n \/\/ increment or decrement the step number,\n \/\/ depending on direction:\n if (this->direction == 1) {\n\t\t digitalWrite(step_pin, HIGH);\n } \n else { \n\t\t digitalWrite(dir_pin, HIGH);\n\t\t digitalWrite(step_pin, HIGH);\n }\n \/\/ decrement the steps left:\n steps_left--;\n\t \/\/disable sthe step & dir pins\n\t delay(20);\n\t digitalWrite(step_pin, LOW);\n\t digitalWrite(dir_pin, LOW);\n }\n }\n}\n\n\/*\n version() returns the version of the library:\n*\/\nint TMC262Stepper::version(void)\n{\n return 1;\n}\n\nunsigned long TMC262Stepper::send262(unsigned long datagram) {\n\tunsigned long i_datagram;\n\t\n#ifdef DEBUG\n\tSerial.print(\"Sending \");\n\tSerial.println(datagram,HEX);\n#endif\n\n\tdigitalWrite(cs_pin,LOW);\n\t\n\ti_datagram = SPI.transfer((datagram >> 16) & 0xff);\n\ti_datagram <<= 8;\n\ti_datagram |= SPI.transfer((datagram >> 8) & 0xff);\n\ti_datagram <<= 8;\n\ti_datagram |= SPI.transfer((datagram ) & 0xff);\n\ti_datagram >>= 4;\n\t\n\tdigitalWrite(cs_pin,HIGH); \n#ifdef DEBUG\n\tSerial.print(\"Received \");\n\tSerial.println(i_datagram,HEX);\n#endif\n\t\n\treturn i_datagram;\n}\n<commit_msg>correcting the current scaling<commit_after>#include \"WProgram.h\"\n#include <SPI.h>\n#include \"TMC262Stepper.h\"\n\n#define DEBUG\n# define MRES 0\n\nTMC262Stepper::TMC262Stepper(int number_of_steps, int cs_pin, int dir_pin, int step_pin, unsigned int max_current)\n{\n\t\/\/save the pins for later use\n\tthis->cs_pin=cs_pin;\n\tthis->dir_pin=dir_pin;\n\tthis->step_pin = step_pin;\n\t\/\/calculate the current scaling from the max current setting (in mA)\n\tfloat mASetting = max_current;\n\t\/\/this is derrived from I=(cs+1)\/32*Vfs\/Rsense*1\/sqrt(2)\n\t\/\/with vfs=5\/16, Rsense=0,15\n\t\/\/giving the formula CS=(ImA*32\/(1000*k)-1 where k=Vfs\/Rsense*1\/sqrt(2) - too lazy to deal with complete formulas\n\tthis->current_scaling = (byte)((mASetting*0.0217223203180507)-0.5); \/\/theoretically - 1.0 for better rounding it is 0.5\n}\n\nvoid TMC262Stepper::start() {\n\n#ifdef DEBUG\t\n\tSerial.println(\"TMC262 stepper library\");\n\tSerial.print(\"CS pin: \");\n\tSerial.println(cs_pin);\n\tSerial.print(\"DIR pin: \");\n\tSerial.println(dir_pin);\n\tSerial.print(\"STEP pin: \");\n\tSerial.println(step_pin);\n\tSerial.print(\"current scaling: \");\n\tSerial.println(current_scaling,DEC);\n#endif\n\t\/\/set the pins as output & its initial value\n\tpinMode(step_pin, OUTPUT); \n\tpinMode(dir_pin, OUTPUT); \n\tpinMode(cs_pin, OUTPUT); \n\tdigitalWrite(step_pin, LOW); \n\tdigitalWrite(dir_pin, LOW); \n\tdigitalWrite(cs_pin, HIGH); \n\t\n\t\n\tSPI.setBitOrder(MSBFIRST);\n\tSPI.setClockDivider(SPI_CLOCK_DIV8);\n\tSPI.setDataMode(SPI_MODE0);\n\tSPI.begin();\n\t\t\n\tsend262(0x00000|MRES); \n\tsend262(0x941D7);\n\tsend262(0xA0000);\n\tsend262(0xD0000|current_scaling);\n\tsend262(0xEF000);\n\t\n}\n\n\/*\n Sets the speed in revs per minute\n\n*\/\nvoid TMC262Stepper::setSpeed(long whatSpeed)\n{\n this->step_delay = 60L * 1000L \/ this->number_of_steps \/ whatSpeed;\n}\n\n\/*\n Moves the motor steps_to_move steps. If the number is negative, \n the motor moves in the reverse direction.\n *\/\nvoid TMC262Stepper::step(int steps_to_move)\n{ \n int steps_left = abs(steps_to_move); \/\/ how many steps to take\n \n \/\/ determine direction based on whether steps_to_mode is + or -:\n if (steps_to_move > 0) {this->direction = 1;}\n if (steps_to_move < 0) {this->direction = 0;}\n \n \n \/\/ decrement the number of steps, moving one step each time:\n while(steps_left > 0) {\n \/\/ move only if the appropriate delay has passed:\n if (millis() - this->last_step_time >= this->step_delay) {\n \/\/ get the timeStamp of when you stepped:\n this->last_step_time = millis();\n \/\/ increment or decrement the step number,\n \/\/ depending on direction:\n if (this->direction == 1) {\n\t\t digitalWrite(step_pin, HIGH);\n } \n else { \n\t\t digitalWrite(dir_pin, HIGH);\n\t\t digitalWrite(step_pin, HIGH);\n }\n \/\/ decrement the steps left:\n steps_left--;\n\t \/\/disable sthe step & dir pins\n\t delay(20);\n\t digitalWrite(step_pin, LOW);\n\t digitalWrite(dir_pin, LOW);\n }\n }\n}\n\n\/*\n version() returns the version of the library:\n*\/\nint TMC262Stepper::version(void)\n{\n return 1;\n}\n\nunsigned long TMC262Stepper::send262(unsigned long datagram) {\n\tunsigned long i_datagram;\n\t\n#ifdef DEBUG\n\tSerial.print(\"Sending \");\n\tSerial.println(datagram,HEX);\n#endif\n\n\tdigitalWrite(cs_pin,LOW);\n\t\n\ti_datagram = SPI.transfer((datagram >> 16) & 0xff);\n\ti_datagram <<= 8;\n\ti_datagram |= SPI.transfer((datagram >> 8) & 0xff);\n\ti_datagram <<= 8;\n\ti_datagram |= SPI.transfer((datagram ) & 0xff);\n\ti_datagram >>= 4;\n\t\n\tdigitalWrite(cs_pin,HIGH); \n#ifdef DEBUG\n\tSerial.print(\"Received \");\n\tSerial.println(i_datagram,HEX);\n#endif\n\t\n\treturn i_datagram;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999, 2000 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file.\n#include \"XalanOutputStreamPrintWriter.hpp\"\n\n\n\n#include <cassert>\n\n\n\n#include <XalanDOM\/XalanDOMString.hpp>\n\n\n\n#include \"DOMStringHelper.hpp\"\n#include \"XalanOutputStream.hpp\"\n\n\n\nXalanOutputStreamPrintWriter::XalanOutputStreamPrintWriter(\n\t\t\tXalanOutputStream&\ttheOutputStream,\n\t\t\tbool\t\t\t\tfAutoFlush) :\n\tPrintWriter(fAutoFlush),\n\tm_OutputStream(theOutputStream)\n{\n}\n\n\n\nXalanOutputStreamPrintWriter::~XalanOutputStreamPrintWriter()\n{\n\tflush();\n}\n\n\n\nbool\nXalanOutputStreamPrintWriter::checkError() const\n{\n\treturn false;\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::close()\n{\n\tflush();\n}\n\n\nvoid\nXalanOutputStreamPrintWriter::flush()\n{\n\tm_OutputStream.flush();\n}\n\n\n\nXalanOutputStream*\nXalanOutputStreamPrintWriter::getStream()\n{\n\treturn &m_OutputStream;\n}\n\n\n\nconst XalanOutputStream*\nXalanOutputStreamPrintWriter::getStream() const\n{\n\treturn &m_OutputStream;\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::write(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheOffset,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\n\tif (theLength == -1)\n\t{\n\t\tif (theOffset == 0)\n\t\t{\n\t\t\tm_OutputStream.write(s);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_OutputStream.write(s + theOffset);\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst long\ttheStopIndex = theOffset + theLength;\n\n\t\tfor (long i = theOffset; i < theStopIndex; i++)\n\t\t{\n\t\t\tm_OutputStream.write(s[i]);\n\t\t}\n\t}\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::write(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheOffset,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\n\tif (theLength == -1)\n\t{\n\t\tif (theOffset == 0)\n\t\t{\n\t\t\tm_OutputStream.write(s);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_OutputStream.write(s + theOffset);\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst long\ttheStopIndex = theOffset + theLength;\n\n\t\tfor (long i = theOffset; i < theStopIndex; i++)\n\t\t{\n\t\t\tm_OutputStream.write(s[i]);\n\t\t}\n\t}\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::write(XMLCh\tc)\n{\n\tm_OutputStream.write(c);\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::write(\n\t\t\tconst DOMString&\ts,\n\t\t\tunsigned int\t\ttheOffset,\n\t\t\tunsigned int\t\ttheLength)\n{\n\twrite(c_wstr(s), theOffset, theLength);\n}\n\n\n\n#if !defined(XALAN_BOOL_AS_INT)\nvoid\nXalanOutputStreamPrintWriter::print(bool\tb)\n{\n\tif (b == true)\n\t{\n\t\tprint(s_trueString);\n\t}\n\telse\n\t{\n\t\tprint(s_falseString);\n\t}\n}\n#endif\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(char\tc)\n{\n\twrite(c);\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\twrite(s,\n\t\t 0,\n\t\t theLength);\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\tassert(theLength >= 0 || theLength == -1);\n\n\twrite(s,\n\t\t 0,\n\t\t theLength);\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(double\td)\n{\n\tm_OutputStream.write(c_wstr(DoubleToDOMString(d)));\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(int\ti)\n{\n\tm_OutputStream.write(c_wstr(LongToDOMString(i)));\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(long\tl)\n{\n\tm_OutputStream.write(c_wstr(LongToDOMString(l)));\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(const DOMString&\ts)\n{\n\tm_OutputStream.write(c_wstr(s));\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println()\n{\n\tm_OutputStream.write(c_wstr(s_newlineString));\n\n\tflush();\n}\n\n\n\n#if !defined(XALAN_BOOL_AS_INT)\nvoid\nXalanOutputStreamPrintWriter::println(bool\tb)\n{\n\tprint(b);\n\n\tprintln();\n}\n#endif\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(char\tc)\n{\n\tprint(c);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tprint(s, theLength);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tprint(s, theLength);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(double\td)\n{\n\tprint(d);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(int\t\ti)\n{\n\tprint(i);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(long\tl)\n{\n\tprint(l);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(const DOMString&\ts)\n{\n\tprint(s);\n\n\tprintln();\n}\n<commit_msg>Write strings more efficiently.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999, 2000 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file.\n#include \"XalanOutputStreamPrintWriter.hpp\"\n\n\n\n#include <cassert>\n\n\n\n#include <XalanDOM\/XalanDOMString.hpp>\n\n\n\n#include \"DOMStringHelper.hpp\"\n#include \"XalanOutputStream.hpp\"\n\n\n\nXalanOutputStreamPrintWriter::XalanOutputStreamPrintWriter(\n\t\t\tXalanOutputStream&\ttheOutputStream,\n\t\t\tbool\t\t\t\tfAutoFlush) :\n\tPrintWriter(fAutoFlush),\n\tm_OutputStream(theOutputStream)\n{\n}\n\n\n\nXalanOutputStreamPrintWriter::~XalanOutputStreamPrintWriter()\n{\n\tflush();\n}\n\n\n\nbool\nXalanOutputStreamPrintWriter::checkError() const\n{\n\treturn false;\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::close()\n{\n\tflush();\n}\n\n\nvoid\nXalanOutputStreamPrintWriter::flush()\n{\n\tm_OutputStream.flush();\n}\n\n\n\nXalanOutputStream*\nXalanOutputStreamPrintWriter::getStream()\n{\n\treturn &m_OutputStream;\n}\n\n\n\nconst XalanOutputStream*\nXalanOutputStreamPrintWriter::getStream() const\n{\n\treturn &m_OutputStream;\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::write(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheOffset,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\n\tif (theLength == -1)\n\t{\n\t\tif (theOffset == 0)\n\t\t{\n\t\t\tm_OutputStream.write(s);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_OutputStream.write(s + theOffset);\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_OutputStream.write(s + theOffset, theLength);\n\t}\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::write(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheOffset,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\n\tif (theLength == -1)\n\t{\n\t\tif (theOffset == 0)\n\t\t{\n\t\t\tm_OutputStream.write(s);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_OutputStream.write(s + theOffset);\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_OutputStream.write(s + theOffset, theLength);\n\t}\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::write(XMLCh\tc)\n{\n\tm_OutputStream.write(c);\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::write(\n\t\t\tconst DOMString&\ts,\n\t\t\tunsigned int\t\ttheOffset,\n\t\t\tunsigned int\t\ttheLength)\n{\n\twrite(c_wstr(s), theOffset, theLength);\n}\n\n\n\n#if !defined(XALAN_BOOL_AS_INT)\nvoid\nXalanOutputStreamPrintWriter::print(bool\tb)\n{\n\tif (b == true)\n\t{\n\t\tprint(s_trueString);\n\t}\n\telse\n\t{\n\t\tprint(s_falseString);\n\t}\n}\n#endif\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(char\tc)\n{\n\twrite(c);\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\twrite(s,\n\t\t 0,\n\t\t theLength);\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\tassert(theLength >= 0 || theLength == -1);\n\n\twrite(s,\n\t\t 0,\n\t\t theLength);\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(double\td)\n{\n\tm_OutputStream.write(c_wstr(DoubleToDOMString(d)));\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(int\ti)\n{\n\tm_OutputStream.write(c_wstr(LongToDOMString(i)));\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(long\tl)\n{\n\tm_OutputStream.write(c_wstr(LongToDOMString(l)));\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::print(const DOMString&\ts)\n{\n\tm_OutputStream.write(c_wstr(s));\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println()\n{\n\tm_OutputStream.write(c_wstr(s_newlineString));\n\n\tflush();\n}\n\n\n\n#if !defined(XALAN_BOOL_AS_INT)\nvoid\nXalanOutputStreamPrintWriter::println(bool\tb)\n{\n\tprint(b);\n\n\tprintln();\n}\n#endif\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(char\tc)\n{\n\tprint(c);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tprint(s, theLength);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tprint(s, theLength);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(double\td)\n{\n\tprint(d);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(int\t\ti)\n{\n\tprint(i);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(long\tl)\n{\n\tprint(l);\n\n\tprintln();\n}\n\n\n\nvoid\nXalanOutputStreamPrintWriter::println(const DOMString&\ts)\n{\n\tprint(s);\n\n\tprintln();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GL.h\"\n#include \"VBO.h\"\n\n#include <cassert>\n#include <iostream>\n\nusing namespace std;\n\nbool VBO::has_vertex_array_objects = false;\n\nstatic GLenum getGLDrawType(VBO::DrawType type) {\n switch (type) {\n case VBO::NONE: break;\n case VBO::POINTS: return GL_POINTS;\n case VBO::LINES: return GL_LINES;\n case VBO::TRIANGLES: return GL_TRIANGLES;\n case VBO::TRIANGLE_STRIP: return GL_TRIANGLE_STRIP;\n case VBO::TRIANGLE_FAN: return GL_TRIANGLE_FAN;\n }\n assert(0);\n return 0;\n}\n\nVBO::~VBO() {\n clear();\n}\n\nvoid\nVBO::clear() {\n if (vao) {\n glDeleteVertexArrays(1, &vao);\n vao = 0;\n }\n if (vbo) {\n glDeleteBuffers(1, &vbo);\n vbo = 0;\n }\n if (indexVbo) {\n glDeleteBuffers(1, &indexVbo);\n indexVbo = 0; \n }\n num_indices = num_elements = 0;\n data_uploaded = indices_uploaded = false;\n}\n\nvoid\nVBO::setPointers() const {\n int n_arrays = 0;\n switch (getDataType()) {\n case T2F_N3F_V3F:\n glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(5 * sizeof(float)));\n n_arrays = 2;\n break;\n case NODE_BILLBOARDS:\n glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0)); \/\/ color\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4)); \/\/ center position\n glVertexAttribPointer(2, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(16)); \/\/ size\n glVertexAttribPointer(3, 2, GL_UNSIGNED_SHORT, GL_FALSE, getStride(), (void *)(20)); \/\/ texture \/ flags\n n_arrays = 4;\n break;\n case BILLBOARDS:\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(3 * sizeof(float)));\n glVertexAttribPointer(2, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));\n glVertexAttribPointer(3, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(5 * sizeof(float)));\n glVertexAttribPointer(4, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(6 * sizeof(float)));\n glVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(7 * sizeof(float)));\n n_arrays = 6;\n break;\n case EDGES:\n glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));\n glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));\n glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(7 * sizeof(float)));\n n_arrays = 4;\n break;\n case ARCS_2D:\n glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));\n n_arrays = 2;\n break;\n case ARCS_3D:\n glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));\n glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));\n n_arrays = 3;\n break;\n }\n for (int i = 0; i < 6; i++) {\n if (i < n_arrays) {\n glEnableVertexAttribArray(i);\n } else if (!hasVertexArrayObjects()) {\n glDisableVertexAttribArray(i);\n }\n }\n}\n\nvoid\nVBO::upload(DataType type, const void * ptr, size_t size) {\n \/\/ assert(size > 0);\n \n data_type = type;\n switch (type) {\n case VBO::T2F_N3F_V3F: stride = 8 * sizeof(float); break;\n case VBO::NODE_BILLBOARDS: stride = sizeof(node_billboard_vbo_s); break; \/\/ ?\n case VBO::BILLBOARDS: stride = sizeof(billboard_data_s); break;\n case VBO::EDGES: stride = sizeof(line_data_s); break;\n case VBO::ARCS_2D: stride = sizeof(arc_data_2d_s); break;\n case VBO::ARCS_3D: stride = sizeof(arc_data_3d_s); break;\n }\n \n num_elements = size \/ stride;\n if (hasVertexArrayObjects()) {\n if (!vao) glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n }\n if (!vbo) glGenBuffers(1, &vbo);\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n glBufferData(GL_ARRAY_BUFFER, size, ptr, is_dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);\n setPointers();\n\n data_uploaded = true;\n}\n\nvoid\nVBO::uploadIndices(const void * ptr, size_t size) {\n assert(size > 0);\n\n if (hasVertexArrayObjects()) {\n if (!vao) glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n }\n if (!indexVbo) glGenBuffers(1, &indexVbo);\n num_indices = size \/ 4;\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVbo);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, ptr, is_dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);\n \n indices_uploaded = true;\n}\n\nvoid\nVBO::draw(DrawType type, const vector<int> & _indices) {\n assert(0);\n const int & first_index = _indices.front();\n glDrawElements(getGLDrawType(type), (GLsizei)_indices.size(), GL_UNSIGNED_INT, &first_index);\n \/\/ glBindVertexArray(0);\n}\n\nvoid\nVBO::draw(DrawType type) {\n if (!type) type = default_draw_type;\n assert(type);\n assert(vbo);\n assert(data_uploaded);\n if (!hasVertexArrayObjects()) {\n setPointers();\n }\n if (!num_indices) {\n \/\/ cerr << \"drawing A: \" << num_elements << endl;\n glDrawArrays(getGLDrawType(type), 0, num_elements);\n } else {\n assert(indices_uploaded);\n \/\/ cerr << \"drawing B: \" << num_indices << endl;\n glDrawElements(getGLDrawType(type), num_indices, GL_UNSIGNED_INT, 0);\n }\n \/\/ glBindVertexArray(0); \n}\n\nvoid\nVBO::quad2d(float x1, float y1,\n\t float x2, float y2,\n\t float x3, float y3,\n\t float x4, float y4) {\n default_draw_type = TRIANGLE_FAN;\n vbo_data_s * data = new vbo_data_s[4];\n unsigned int * indices = new unsigned int[4];\n data[0] = { glm::vec2(0, 0), glm::vec3(0, 0, 1), glm::vec3(x1, y1, 0) };\n data[1] = { glm::vec2(0, 1), glm::vec3(0, 0, 1), glm::vec3(x2, y2, 0) };\n data[2] = { glm::vec2(1, 1), glm::vec3(0, 0, 1), glm::vec3(x3, y3, 0) };\n data[3] = { glm::vec2(1, 0), glm::vec3(0, 0, 1), glm::vec3(x4, y4, 0) };\n upload(T2F_N3F_V3F, data, 4 * sizeof(vbo_data_s));\n indices[0] = 0;\n indices[1] = 1;\n indices[2] = 2;\n indices[3] = 3;\n uploadIndices(indices, 4 * sizeof(unsigned int));\n delete[] indices;\n delete[] data;\n}\n\nvoid\nVBO::quad2d(float x1, float y1, float tx1, float ty1,\n\t float x2, float y2, float tx2, float ty2,\n\t float x3, float y3, float tx3, float ty3,\n\t float x4, float y4, float tx4, float ty4) {\n default_draw_type = TRIANGLE_FAN;\n vbo_data_s * data = new vbo_data_s[4];\n unsigned int * indices = new unsigned int[4];\n data[0] = { glm::vec2(tx1, ty1), glm::vec3(0, 0, 1), glm::vec3(x1, y1, 0) };\n data[1] = { glm::vec2(tx2, ty2), glm::vec3(0, 0, 1), glm::vec3(x2, y2, 0) };\n data[2] = { glm::vec2(tx3, ty3), glm::vec3(0, 0, 1), glm::vec3(x3, y3, 0) };\n data[3] = { glm::vec2(tx4, ty4), glm::vec3(0, 0, 1), glm::vec3(x4, y4, 0) };\n upload(T2F_N3F_V3F, data, 4 * sizeof(vbo_data_s));\n indices[0] = 0;\n indices[1] = 1;\n indices[2] = 2;\n indices[3] = 3;\n uploadIndices(indices, 4 * sizeof(unsigned int));\n delete[] indices;\n delete[] data;\n}\n\nvoid\nVBO::sphere(float radius, unsigned int u, unsigned int v) {\n default_draw_type = TRIANGLES;\n \n vbo_data_s * data = new vbo_data_s[u * v];\n unsigned int * indices = new unsigned int[6 * u * v];\n \n unsigned int in = 0, vn = 0;\n for (unsigned int i = 0; i < u; i++) {\n for (unsigned int j = 0; j < v; j++) {\n float tx = (float)i \/ (u - 1), ty = (float)j \/ (v - 1);\n float i2 = (float)i \/ u * 2 * M_PI, j2 = ((float)j \/ v - 0.5f) * M_PI;\n float x = -radius * cos(j2) * cos(i2);\n float y = -radius * sin(j2);\n float z = radius * cos(j2) * sin(i2);\n \n indices[in++] = i * v + j;\n indices[in++] = i * v + (j + 1) % v;\n indices[in++] = ((i + 1) % u) * v + (j + 1) % v;\n indices[in++] = i * v + j;\n indices[in++] = ((i + 1) % u) * v + (j + 1) % v;\n indices[in++] = ((i + 1) % u) * v + j;\n \n data[vn++] = { glm::vec2(tx, ty), glm::vec3(0, 0, 1), glm::vec3(x, y, z) };\n }\n }\n \n uploadIndices(indices, in * sizeof(unsigned int));\n upload(T2F_N3F_V3F, data, vn * sizeof(vbo_data_s)); \n\n delete[] indices;\n delete[] data;\n}\n\nvoid\nVBO::ring(float outer_radius, float inner_radius, unsigned int n, float dx, float dy) {\n default_draw_type = TRIANGLE_STRIP;\n \n vbo_data_s * data = new vbo_data_s[2 * n];\n unsigned int * indices = new unsigned int[2 * n];\n \n unsigned int vn = 0, in = 0;\n for (unsigned int i = 0; i < n; i++) {\n float a = 2 * M_PI \/ (n - 1);\n float x1 = outer_radius * cos(a) + dx, y1 = outer_radius * sin(a) + dy;\n float x2 = inner_radius * cos(a) + dx, y2 = inner_radius * sin(a) + dy;\n\n if (i % 2 == 0) {\n indices[in++] = vn + 0;\n indices[in++] = vn + 1;\n } else {\n indices[in++] = vn + 1;\n indices[in++] = vn + 0;\n }\n \n data[vn++] = { glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(x1, y1, 0.0f) };\n data[vn++] = { glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(x2, y2, 0.0f) }; \n }\n\n cerr << \"vbo ring vn = \" << vn << \", in = \" << in << endl;\n \n upload(T2F_N3F_V3F, data, vn * sizeof(vbo_data_s)); \n uploadIndices(indices, in * sizeof(unsigned int));\n \n delete[] data;\n delete[] indices;\n}\n<commit_msg>fix VBO configuration error<commit_after>#include \"GL.h\"\n#include \"VBO.h\"\n\n#include <cassert>\n#include <iostream>\n\nusing namespace std;\n\nbool VBO::has_vertex_array_objects = false;\n\nstatic GLenum getGLDrawType(VBO::DrawType type) {\n switch (type) {\n case VBO::NONE: break;\n case VBO::POINTS: return GL_POINTS;\n case VBO::LINES: return GL_LINES;\n case VBO::TRIANGLES: return GL_TRIANGLES;\n case VBO::TRIANGLE_STRIP: return GL_TRIANGLE_STRIP;\n case VBO::TRIANGLE_FAN: return GL_TRIANGLE_FAN;\n }\n assert(0);\n return 0;\n}\n\nVBO::~VBO() {\n clear();\n}\n\nvoid\nVBO::clear() {\n if (vao) {\n glDeleteVertexArrays(1, &vao);\n vao = 0;\n }\n if (vbo) {\n glDeleteBuffers(1, &vbo);\n vbo = 0;\n }\n if (indexVbo) {\n glDeleteBuffers(1, &indexVbo);\n indexVbo = 0; \n }\n num_indices = num_elements = 0;\n data_uploaded = indices_uploaded = false;\n}\n\nvoid\nVBO::setPointers() const {\n int n_arrays = 0;\n switch (getDataType()) {\n case T2F_N3F_V3F:\n glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(5 * sizeof(float)));\n n_arrays = 2;\n break;\n case NODE_BILLBOARDS:\n glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0)); \/\/ color\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4)); \/\/ center position\n glVertexAttribPointer(2, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(16)); \/\/ size\n glVertexAttribPointer(3, 2, GL_UNSIGNED_SHORT, GL_FALSE, getStride(), (void *)(20)); \/\/ texture \/ flags\n n_arrays = 4;\n break;\n case BILLBOARDS:\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(3 * sizeof(float)));\n glVertexAttribPointer(2, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));\n glVertexAttribPointer(3, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(5 * sizeof(float)));\n glVertexAttribPointer(4, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(6 * sizeof(float)));\n glVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(7 * sizeof(float)));\n n_arrays = 6;\n break;\n case EDGES:\n glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));\n glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));\n glVertexAttribPointer(3, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(7 * sizeof(float)));\n n_arrays = 4;\n break;\n case ARCS_2D:\n glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));\n n_arrays = 2;\n break;\n case ARCS_3D:\n glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));\n glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));\n n_arrays = 3;\n break;\n }\n for (int i = 0; i < 6; i++) {\n if (i < n_arrays) {\n glEnableVertexAttribArray(i);\n } else if (!hasVertexArrayObjects()) {\n glDisableVertexAttribArray(i);\n }\n }\n}\n\nvoid\nVBO::upload(DataType type, const void * ptr, size_t size) {\n \/\/ assert(size > 0);\n \n data_type = type;\n switch (type) {\n case VBO::T2F_N3F_V3F: stride = 8 * sizeof(float); break;\n case VBO::NODE_BILLBOARDS: stride = sizeof(node_billboard_vbo_s); break; \/\/ ?\n case VBO::BILLBOARDS: stride = sizeof(billboard_data_s); break;\n case VBO::EDGES: stride = sizeof(line_data_s); break;\n case VBO::ARCS_2D: stride = sizeof(arc_data_2d_s); break;\n case VBO::ARCS_3D: stride = sizeof(arc_data_3d_s); break;\n }\n \n num_elements = size \/ stride;\n if (hasVertexArrayObjects()) {\n if (!vao) glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n }\n if (!vbo) glGenBuffers(1, &vbo);\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n glBufferData(GL_ARRAY_BUFFER, size, ptr, is_dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);\n setPointers();\n\n data_uploaded = true;\n}\n\nvoid\nVBO::uploadIndices(const void * ptr, size_t size) {\n assert(size > 0);\n\n if (hasVertexArrayObjects()) {\n if (!vao) glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n }\n if (!indexVbo) glGenBuffers(1, &indexVbo);\n num_indices = size \/ 4;\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVbo);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, ptr, is_dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);\n \n indices_uploaded = true;\n}\n\nvoid\nVBO::draw(DrawType type, const vector<int> & _indices) {\n assert(0);\n const int & first_index = _indices.front();\n glDrawElements(getGLDrawType(type), (GLsizei)_indices.size(), GL_UNSIGNED_INT, &first_index);\n \/\/ glBindVertexArray(0);\n}\n\nvoid\nVBO::draw(DrawType type) {\n if (!type) type = default_draw_type;\n assert(type);\n assert(vbo);\n assert(data_uploaded);\n if (!hasVertexArrayObjects()) {\n setPointers();\n }\n if (!num_indices) {\n \/\/ cerr << \"drawing A: \" << num_elements << endl;\n glDrawArrays(getGLDrawType(type), 0, num_elements);\n } else {\n assert(indices_uploaded);\n \/\/ cerr << \"drawing B: \" << num_indices << endl;\n glDrawElements(getGLDrawType(type), num_indices, GL_UNSIGNED_INT, 0);\n }\n \/\/ glBindVertexArray(0); \n}\n\nvoid\nVBO::quad2d(float x1, float y1,\n\t float x2, float y2,\n\t float x3, float y3,\n\t float x4, float y4) {\n default_draw_type = TRIANGLE_FAN;\n vbo_data_s * data = new vbo_data_s[4];\n unsigned int * indices = new unsigned int[4];\n data[0] = { glm::vec2(0, 0), glm::vec3(0, 0, 1), glm::vec3(x1, y1, 0) };\n data[1] = { glm::vec2(0, 1), glm::vec3(0, 0, 1), glm::vec3(x2, y2, 0) };\n data[2] = { glm::vec2(1, 1), glm::vec3(0, 0, 1), glm::vec3(x3, y3, 0) };\n data[3] = { glm::vec2(1, 0), glm::vec3(0, 0, 1), glm::vec3(x4, y4, 0) };\n upload(T2F_N3F_V3F, data, 4 * sizeof(vbo_data_s));\n indices[0] = 0;\n indices[1] = 1;\n indices[2] = 2;\n indices[3] = 3;\n uploadIndices(indices, 4 * sizeof(unsigned int));\n delete[] indices;\n delete[] data;\n}\n\nvoid\nVBO::quad2d(float x1, float y1, float tx1, float ty1,\n\t float x2, float y2, float tx2, float ty2,\n\t float x3, float y3, float tx3, float ty3,\n\t float x4, float y4, float tx4, float ty4) {\n default_draw_type = TRIANGLE_FAN;\n vbo_data_s * data = new vbo_data_s[4];\n unsigned int * indices = new unsigned int[4];\n data[0] = { glm::vec2(tx1, ty1), glm::vec3(0, 0, 1), glm::vec3(x1, y1, 0) };\n data[1] = { glm::vec2(tx2, ty2), glm::vec3(0, 0, 1), glm::vec3(x2, y2, 0) };\n data[2] = { glm::vec2(tx3, ty3), glm::vec3(0, 0, 1), glm::vec3(x3, y3, 0) };\n data[3] = { glm::vec2(tx4, ty4), glm::vec3(0, 0, 1), glm::vec3(x4, y4, 0) };\n upload(T2F_N3F_V3F, data, 4 * sizeof(vbo_data_s));\n indices[0] = 0;\n indices[1] = 1;\n indices[2] = 2;\n indices[3] = 3;\n uploadIndices(indices, 4 * sizeof(unsigned int));\n delete[] indices;\n delete[] data;\n}\n\nvoid\nVBO::sphere(float radius, unsigned int u, unsigned int v) {\n default_draw_type = TRIANGLES;\n \n vbo_data_s * data = new vbo_data_s[u * v];\n unsigned int * indices = new unsigned int[6 * u * v];\n \n unsigned int in = 0, vn = 0;\n for (unsigned int i = 0; i < u; i++) {\n for (unsigned int j = 0; j < v; j++) {\n float tx = (float)i \/ (u - 1), ty = (float)j \/ (v - 1);\n float i2 = (float)i \/ u * 2 * M_PI, j2 = ((float)j \/ v - 0.5f) * M_PI;\n float x = -radius * cos(j2) * cos(i2);\n float y = -radius * sin(j2);\n float z = radius * cos(j2) * sin(i2);\n \n indices[in++] = i * v + j;\n indices[in++] = i * v + (j + 1) % v;\n indices[in++] = ((i + 1) % u) * v + (j + 1) % v;\n indices[in++] = i * v + j;\n indices[in++] = ((i + 1) % u) * v + (j + 1) % v;\n indices[in++] = ((i + 1) % u) * v + j;\n \n data[vn++] = { glm::vec2(tx, ty), glm::vec3(0, 0, 1), glm::vec3(x, y, z) };\n }\n }\n \n uploadIndices(indices, in * sizeof(unsigned int));\n upload(T2F_N3F_V3F, data, vn * sizeof(vbo_data_s)); \n\n delete[] indices;\n delete[] data;\n}\n\nvoid\nVBO::ring(float outer_radius, float inner_radius, unsigned int n, float dx, float dy) {\n default_draw_type = TRIANGLE_STRIP;\n \n vbo_data_s * data = new vbo_data_s[2 * n];\n unsigned int * indices = new unsigned int[2 * n];\n \n unsigned int vn = 0, in = 0;\n for (unsigned int i = 0; i < n; i++) {\n float a = 2 * M_PI \/ (n - 1);\n float x1 = outer_radius * cos(a) + dx, y1 = outer_radius * sin(a) + dy;\n float x2 = inner_radius * cos(a) + dx, y2 = inner_radius * sin(a) + dy;\n\n if (i % 2 == 0) {\n indices[in++] = vn + 0;\n indices[in++] = vn + 1;\n } else {\n indices[in++] = vn + 1;\n indices[in++] = vn + 0;\n }\n \n data[vn++] = { glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(x1, y1, 0.0f) };\n data[vn++] = { glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(x2, y2, 0.0f) }; \n }\n\n cerr << \"vbo ring vn = \" << vn << \", in = \" << in << endl;\n \n upload(T2F_N3F_V3F, data, vn * sizeof(vbo_data_s)); \n uploadIndices(indices, in * sizeof(unsigned int));\n \n delete[] data;\n delete[] indices;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file api.cpp\n\/\/\/ @brief primesieve C++ API.\n\/\/\/ Contains the implementations of the functions declared\n\/\/\/ in the primesieve.hpp header file.\n\/\/\/\n\/\/\/ Copyright (C) 2020 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve.hpp>\n#include <primesieve\/CpuInfo.hpp>\n#include <primesieve\/pmath.hpp>\n#include <primesieve\/PrimeSieve.hpp>\n#include <primesieve\/ParallelSieve.hpp>\n\n#include <stdint.h>\n#include <cstddef>\n#include <limits>\n#include <string>\n\nnamespace {\n\nint sieve_size = 0;\n\nint num_threads = 0;\n\n}\n\nnamespace primesieve {\n\nuint64_t nth_prime(int64_t n, uint64_t start)\n{\n ParallelSieve ps;\n return ps.nthPrime(n, start);\n}\n\nuint64_t count_primes(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_PRIMES);\n return ps.getCount(0);\n}\n\nuint64_t count_twins(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_TWINS);\n return ps.getCount(1);\n}\n\nuint64_t count_triplets(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_TRIPLETS);\n return ps.getCount(2);\n}\n\nuint64_t count_quadruplets(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_QUADRUPLETS);\n return ps.getCount(3);\n}\n\nuint64_t count_quintuplets(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_QUINTUPLETS);\n return ps.getCount(4);\n}\n\nuint64_t count_sextuplets(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_SEXTUPLETS);\n return ps.getCount(5);\n}\n\nvoid print_primes(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_PRIMES);\n}\n\nvoid print_twins(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_TWINS);\n}\n\nvoid print_triplets(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_TRIPLETS);\n}\n\nvoid print_quadruplets(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_QUADRUPLETS);\n}\n\nvoid print_quintuplets(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_QUINTUPLETS);\n}\n\nvoid print_sextuplets(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_SEXTUPLETS);\n}\n\nint get_num_threads()\n{\n if (num_threads)\n return num_threads;\n else\n return ParallelSieve::getMaxThreads();\n}\n\nvoid set_num_threads(int threads)\n{\n num_threads = inBetween(1, threads, ParallelSieve::getMaxThreads());\n}\n\nuint64_t get_max_stop()\n{\n return std::numeric_limits<uint64_t>::max();\n}\n\nstd::string primesieve_version()\n{\n return PRIMESIEVE_VERSION;\n}\n\nvoid set_sieve_size(int size)\n{\n sieve_size = inBetween(8, size, 4096);\n sieve_size = floorPow2(sieve_size);\n}\n\nint get_sieve_size()\n{\n \/\/ User specified sieve size\n if (sieve_size)\n return sieve_size;\n\n#if defined(__APPLE__)\n \/\/ On Apple's operating systems (macOS & iOS) we use\n \/\/ the sysctl library to query CPU info. Unfortunately\n \/\/ sysctl returns erroneous L2 & L3 cache information on\n \/\/ Apple silicon CPUs (ARM & ARM64). We can only know\n \/\/ if an L2 cache exists and that it is likely fast. If\n \/\/ this is the case, we make a conservative guess that\n \/\/ the L2 cache per core is at least 8x larger than the\n \/\/ L1 cache as this will likely improve performance.\n if (cpuInfo.sysctlL2CacheWorkaround() &&\n cpuInfo.hasL1Cache() &&\n cpuInfo.l2CacheSize() > cpuInfo.l1CacheSize() * 16)\n {\n \/\/ Convert bytes to KiB\n size_t size = cpuInfo.l1CacheSize() >> 10;\n size = inBetween(8, size * 8, 4096);\n size = floorPow2(size);\n return (int) size;\n }\n#endif\n\n \/\/ Shared CPU caches are usually slow. Hence we only use\n \/\/ the L2 cache for sieving if each physical CPU core\n \/\/ has a private L2 cache. Also we only use half of the\n \/\/ L2 cache. This is a safety measure as some CPUs incur\n \/\/ a significant performance degradation if we fully\n \/\/ utilize the L2 cache.\n if (cpuInfo.hasPrivateL2Cache())\n {\n \/\/ Convert bytes to KiB\n size_t size = cpuInfo.l2CacheSize() >> 10;\n size = inBetween(32, size - 1, 4096);\n size = floorPow2(size);\n return (int) size;\n }\n\n \/\/ TODO: Shared L2 caches can also be fast?!\n \/\/\n \/\/ Up until 2020 shared L2 caches have been slow when\n \/\/ used with multi-threading in primesieve on all\n \/\/ desktop and server CPUs. However in 2020 Apple\n \/\/ released their M1 CPU (ARM64) with an L2 cache that\n \/\/ performs well using multi-threading in primesieve and\n \/\/ media seems to agree that this L2 cache is shared.\n \/\/ I still have some doubts whether this is really the\n \/\/ case, but if it's really true then it is likely that\n \/\/ competitors will eventually catch up and also build\n \/\/ CPUs with fast shared L2 caches.\n \/\/\n \/\/ If the CPU manufacturers move to fast L2 shared\n \/\/ caches then we have to add support for it here. We\n \/\/ should then set the sieve size to e.g.:\n \/\/ total L2 cache size \/ (L2 cache sharing * 2).\n\n if (cpuInfo.hasL1Cache())\n {\n \/\/ Convert bytes to KiB\n size_t size = cpuInfo.l1CacheSize() >> 10;\n size = inBetween(8, size, 4096);\n size = floorPow2(size);\n return (int) size;\n }\n else\n {\n \/\/ Default sieve size in KiB\n size_t size = 32;\n size = inBetween(8, size, 4096);\n size = floorPow2(size);\n return (int) size;\n }\n}\n\n} \/\/ namespace\n<commit_msg>Tune macOS sieve size<commit_after>\/\/\/\n\/\/\/ @file api.cpp\n\/\/\/ @brief primesieve C++ API.\n\/\/\/ Contains the implementations of the functions declared\n\/\/\/ in the primesieve.hpp header file.\n\/\/\/\n\/\/\/ Copyright (C) 2020 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve.hpp>\n#include <primesieve\/CpuInfo.hpp>\n#include <primesieve\/pmath.hpp>\n#include <primesieve\/PrimeSieve.hpp>\n#include <primesieve\/ParallelSieve.hpp>\n\n#include <stdint.h>\n#include <cstddef>\n#include <limits>\n#include <string>\n\nnamespace {\n\nint sieve_size = 0;\n\nint num_threads = 0;\n\n}\n\nnamespace primesieve {\n\nuint64_t nth_prime(int64_t n, uint64_t start)\n{\n ParallelSieve ps;\n return ps.nthPrime(n, start);\n}\n\nuint64_t count_primes(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_PRIMES);\n return ps.getCount(0);\n}\n\nuint64_t count_twins(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_TWINS);\n return ps.getCount(1);\n}\n\nuint64_t count_triplets(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_TRIPLETS);\n return ps.getCount(2);\n}\n\nuint64_t count_quadruplets(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_QUADRUPLETS);\n return ps.getCount(3);\n}\n\nuint64_t count_quintuplets(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_QUINTUPLETS);\n return ps.getCount(4);\n}\n\nuint64_t count_sextuplets(uint64_t start, uint64_t stop)\n{\n ParallelSieve ps;\n ps.sieve(start, stop, COUNT_SEXTUPLETS);\n return ps.getCount(5);\n}\n\nvoid print_primes(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_PRIMES);\n}\n\nvoid print_twins(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_TWINS);\n}\n\nvoid print_triplets(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_TRIPLETS);\n}\n\nvoid print_quadruplets(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_QUADRUPLETS);\n}\n\nvoid print_quintuplets(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_QUINTUPLETS);\n}\n\nvoid print_sextuplets(uint64_t start, uint64_t stop)\n{\n PrimeSieve ps;\n ps.sieve(start, stop, PRINT_SEXTUPLETS);\n}\n\nint get_num_threads()\n{\n if (num_threads)\n return num_threads;\n else\n return ParallelSieve::getMaxThreads();\n}\n\nvoid set_num_threads(int threads)\n{\n num_threads = inBetween(1, threads, ParallelSieve::getMaxThreads());\n}\n\nuint64_t get_max_stop()\n{\n return std::numeric_limits<uint64_t>::max();\n}\n\nstd::string primesieve_version()\n{\n return PRIMESIEVE_VERSION;\n}\n\nvoid set_sieve_size(int size)\n{\n sieve_size = inBetween(8, size, 4096);\n sieve_size = floorPow2(sieve_size);\n}\n\nint get_sieve_size()\n{\n \/\/ User specified sieve size\n if (sieve_size)\n return sieve_size;\n\n#if defined(__APPLE__)\n \/\/ On Apple's operating systems (macOS & iOS) we use\n \/\/ the sysctl library to query CPU info. Unfortunately\n \/\/ sysctl returns erroneous L2 & L3 cache information on\n \/\/ Apple silicon CPUs (ARM & ARM64). We can only know\n \/\/ if an L2 cache exists and that it is likely fast. If\n \/\/ this is the case, we make a conservative guess that\n \/\/ the L2 cache per core is at least 8x larger than the\n \/\/ L1 cache as this will likely improve performance.\n if (cpuInfo.sysctlL2CacheWorkaround() &&\n cpuInfo.hasL1Cache() &&\n cpuInfo.l2CacheSize() > cpuInfo.l1CacheSize() * 8)\n {\n \/\/ Convert bytes to KiB\n size_t size = cpuInfo.l1CacheSize() >> 10;\n size = inBetween(8, size * 8, 4096);\n size = floorPow2(size);\n return (int) size;\n }\n#endif\n\n \/\/ Shared CPU caches are usually slow. Hence we only use\n \/\/ the L2 cache for sieving if each physical CPU core\n \/\/ has a private L2 cache. Also we only use half of the\n \/\/ L2 cache. This is a safety measure as some CPUs incur\n \/\/ a significant performance degradation if we fully\n \/\/ utilize the L2 cache.\n if (cpuInfo.hasPrivateL2Cache())\n {\n \/\/ Convert bytes to KiB\n size_t size = cpuInfo.l2CacheSize() >> 10;\n size = inBetween(32, size - 1, 4096);\n size = floorPow2(size);\n return (int) size;\n }\n\n \/\/ TODO: Shared L2 caches can also be fast?!\n \/\/\n \/\/ Up until 2020 shared L2 caches have been slow when\n \/\/ used with multi-threading in primesieve on all\n \/\/ desktop and server CPUs. However in 2020 Apple\n \/\/ released their M1 CPU (ARM64) with an L2 cache that\n \/\/ performs well using multi-threading in primesieve and\n \/\/ media seems to agree that this L2 cache is shared.\n \/\/ I still have some doubts whether this is really the\n \/\/ case, but if it's really true then it is likely that\n \/\/ competitors will eventually catch up and also build\n \/\/ CPUs with fast shared L2 caches.\n \/\/\n \/\/ If the CPU manufacturers move to fast L2 shared\n \/\/ caches then we have to add support for it here. We\n \/\/ should then set the sieve size to e.g.:\n \/\/ total L2 cache size \/ (L2 cache sharing * 2).\n\n if (cpuInfo.hasL1Cache())\n {\n \/\/ Convert bytes to KiB\n size_t size = cpuInfo.l1CacheSize() >> 10;\n size = inBetween(8, size, 4096);\n size = floorPow2(size);\n return (int) size;\n }\n else\n {\n \/\/ Default sieve size in KiB\n size_t size = 32;\n size = inBetween(8, size, 4096);\n size = floorPow2(size);\n return (int) size;\n }\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Vassil Vassilev 7\/10\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TClingCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Scope.h\"\n\nusing namespace clang;\nusing namespace cling;\n\nclass TObject;\n\n\/\/ Functions used to forward calls from code compiled with no-rtti to code \n\/\/ compiled with rtti.\nextern \"C\" {\n void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&);\n void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&); \n TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx);\n Decl* TCintWithCling__GetObjectDecl(TObject *obj);\n int TCintWithCling__AutoLoadCallback(const char* className);\n}\n\nTClingCallbacks::TClingCallbacks(cling::Interpreter* interp) \n : InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0),\n fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) {\n const Decl* D = 0;\n m_Interpreter->declare(\"namespace __ROOT_SpecialObjects{}\", &D);\n fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D));\n}\n\n\/\/pin the vtable here\nTClingCallbacks::~TClingCallbacks() {}\n\n\/\/ On a failed lookup we have to try to more things before issuing an error.\n\/\/ The symbol might need to be loaded by ROOT's autoloading mechanism or\n\/\/ it might be a ROOT special object. \n\/\/ \n\/\/ Try those first and if still failing issue the diagnostics.\n\/\/\n\/\/ returns true when a declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {\n\n if (tryAutoloadInternal(R, S))\n return true; \/\/ happiness.\n\n \/\/ If the autoload wasn't successful try ROOT specials.\n return tryFindROOTSpecialInternal(R, S);\n}\n\n\/\/ The symbol might be defined in the ROOT class autoloading map so we have to\n\/\/ try to autoload it first and do secondary lookup to try to find it.\n\/\/\n\/\/ returns true when a declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) {\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclarationName Name = R.getLookupName();\n\n \/\/ Try to autoload first if autoloading is enabled\n if (IsAutoloadingEnabled()) {\n \/\/ Avoid tail chasing.\n if (fIsAutoloadingRecursively)\n return false;\n fIsAutoloadingRecursively = true;\n\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n Parser& P = const_cast<Parser&>(m_Interpreter->getParser());\n Parser::ParserCurTokRestoreRAII savedCurToken(P);\n \/\/ After we have saved the token reset the current one to something which \n \/\/ is safe (semi colon usually means empty decl)\n Token& Tok = const_cast<Token&>(P.getCurToken());\n Tok.setKind(tok::semi);\n\n bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics();\n SemaR.getDiagnostics().setSuppressAllDiagnostics();\n \n \/\/ We can't PushDeclContext, because we go up and the routine that pops \n \/\/ the DeclContext assumes that we drill down always.\n \/\/ We have to be on the global context. At that point we are in a \n \/\/ wrapper function so the parent context must be the global.\n Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(), \n SemaR.TUScope);\n\n bool lookupSuccess = false;\n if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) {\n pushedSAndDC.pop();\n cleanupRAII.pop();\n lookupSuccess = SemaR.LookupName(R, S);\n }\n\n SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags);\n\n fIsAutoloadingRecursively = false;\n \n if (lookupSuccess)\n return true;\n }\n\n return false;\n}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {\n\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclContext *CurDC = SemaR.CurContext;\n DeclarationName Name = R.getLookupName();\n\n \/\/ Make sure that the failed lookup comes from the prompt.\n if(!CurDC || !CurDC->isFunctionOrMethod())\n return false;\n if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC))\n if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString()))\n return false;\n\n TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(), \n fLastLookupCtx);\n if (obj) {\n VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, \n Name, \n fROOTSpecialNamespace));\n if (VD) {\n \/\/TODO: Check for same types.\n\n TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD);\n \/\/ Since code was generated already we cannot rely on the initializer \n \/\/ of the decl in the AST, however we will update that init so that it\n \/\/ will be easier while debugging.\n CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());\n Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);\n CStyleCast->setSubExpr(newInit);\n\n \/\/ The actual update happens here, directly in memory.\n *address = obj;\n }\n else {\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n\n const Decl *TD = TCintWithCling__GetObjectDecl(obj);\n \/\/ We will declare the variable as pointer.\n QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));\n \n VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(), \n SourceLocation(), Name.getAsIdentifierInfo(), QT,\n \/*TypeSourceInfo*\/0, SC_None, SC_None\n );\n \/\/ Build an initializer\n Expr* Init \n = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);\n \/\/ Register the decl in our hidden special namespace\n VD->setInit(Init);\n fROOTSpecialNamespace->addDecl(VD);\n\n cling::CompilationOptions CO;\n CO.DeclarationExtraction = 0;\n CO.ValuePrinting = CompilationOptions::VPDisabled;\n CO.ResultEvaluation = 0;\n CO.DynamicScoping = 0;\n CO.Debug = 0;\n CO.CodeGeneration = 1;\n\n cling::Transaction T(CO, \/*llvm::Module=*\/0);\n T.appendUnique(VD);\n T.setCompleted();\n\n m_Interpreter->codegen(&T);\n assert(T.getState() == Transaction::kCommitted\n && \"Compilation should never fail!\");\n }\n assert(VD && \"Cannot be null!\");\n R.addDecl(VD);\n return true;\n }\n\n return false;\n}\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionCommitted(const Transaction &T) {\n if (!T.size())\n return;\n if (fFirstRun) {\n \/\/ Before setting up the callbacks register what cling have seen during init.\n const cling::Transaction* T = m_Interpreter->getFirstTransaction();\n while (T) {\n if (T->getState() == cling::Transaction::kCommitted)\n TCintWithCling__UpdateListsOnCommitted(*T);\n T = T->getNext();\n }\n\n fFirstRun = false;\n }\n\n TCintWithCling__UpdateListsOnCommitted(T);\n}\n\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionUnloaded(const Transaction &T) {\n if (!T.size())\n return;\n\n TCintWithCling__UpdateListsOnUnloaded(T);\n}\n<commit_msg>If I only could spell.<commit_after>\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Vassil Vassilev 7\/10\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TClingCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Scope.h\"\n\nusing namespace clang;\nusing namespace cling;\n\nclass TObject;\n\n\/\/ Functions used to forward calls from code compiled with no-rtti to code \n\/\/ compiled with rtti.\nextern \"C\" {\n void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&);\n void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&); \n TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx);\n Decl* TCintWithCling__GetObjectDecl(TObject *obj);\n int TCintWithCling__AutoLoadCallback(const char* className);\n}\n\nTClingCallbacks::TClingCallbacks(cling::Interpreter* interp) \n : InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0),\n fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) {\n const Decl* D = 0;\n m_Interpreter->declare(\"namespace __ROOT_SpecialObjects{}\", &D);\n fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D));\n}\n\n\/\/pin the vtable here\nTClingCallbacks::~TClingCallbacks() {}\n\n\/\/ On a failed lookup we have to try to more things before issuing an error.\n\/\/ The symbol might need to be loaded by ROOT's autoloading mechanism or\n\/\/ it might be a ROOT special object. \n\/\/ \n\/\/ Try those first and if still failing issue the diagnostics.\n\/\/\n\/\/ returns true when a declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {\n\n if (tryAutoloadInternal(R, S))\n return true; \/\/ happiness.\n\n \/\/ If the autoload wasn't successful try ROOT specials.\n return tryFindROOTSpecialInternal(R, S);\n}\n\n\/\/ The symbol might be defined in the ROOT class autoloading map so we have to\n\/\/ try to autoload it first and do secondary lookup to try to find it.\n\/\/\n\/\/ returns true when a declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) {\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclarationName Name = R.getLookupName();\n\n \/\/ Try to autoload first if autoloading is enabled\n if (IsAutoloadingEnabled()) {\n \/\/ Avoid tail chasing.\n if (fIsAutoloadingRecursively)\n return false;\n fIsAutoloadingRecursively = true;\n\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n Parser& P = const_cast<Parser&>(m_Interpreter->getParser());\n Parser::ParserCurTokRestoreRAII savedCurToken(P);\n \/\/ After we have saved the token reset the current one to something which \n \/\/ is safe (semi colon usually means empty decl)\n Token& Tok = const_cast<Token&>(P.getCurToken());\n Tok.setKind(tok::semi);\n\n bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics();\n SemaR.getDiagnostics().setSuppressAllDiagnostics();\n \n \/\/ We can't PushDeclContext, because we go up and the routine that pops \n \/\/ the DeclContext assumes that we drill down always.\n \/\/ We have to be on the global context. At that point we are in a \n \/\/ wrapper function so the parent context must be the global.\n Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(), \n SemaR.TUScope);\n\n bool lookupSuccess = false;\n if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) {\n pushedDCAndS.pop();\n cleanupRAII.pop();\n lookupSuccess = SemaR.LookupName(R, S);\n }\n\n SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags);\n\n fIsAutoloadingRecursively = false;\n \n if (lookupSuccess)\n return true;\n }\n\n return false;\n}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {\n\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclContext *CurDC = SemaR.CurContext;\n DeclarationName Name = R.getLookupName();\n\n \/\/ Make sure that the failed lookup comes from the prompt.\n if(!CurDC || !CurDC->isFunctionOrMethod())\n return false;\n if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC))\n if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString()))\n return false;\n\n TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(), \n fLastLookupCtx);\n if (obj) {\n VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, \n Name, \n fROOTSpecialNamespace));\n if (VD) {\n \/\/TODO: Check for same types.\n\n TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD);\n \/\/ Since code was generated already we cannot rely on the initializer \n \/\/ of the decl in the AST, however we will update that init so that it\n \/\/ will be easier while debugging.\n CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());\n Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);\n CStyleCast->setSubExpr(newInit);\n\n \/\/ The actual update happens here, directly in memory.\n *address = obj;\n }\n else {\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n\n const Decl *TD = TCintWithCling__GetObjectDecl(obj);\n \/\/ We will declare the variable as pointer.\n QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));\n \n VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(), \n SourceLocation(), Name.getAsIdentifierInfo(), QT,\n \/*TypeSourceInfo*\/0, SC_None, SC_None\n );\n \/\/ Build an initializer\n Expr* Init \n = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);\n \/\/ Register the decl in our hidden special namespace\n VD->setInit(Init);\n fROOTSpecialNamespace->addDecl(VD);\n\n cling::CompilationOptions CO;\n CO.DeclarationExtraction = 0;\n CO.ValuePrinting = CompilationOptions::VPDisabled;\n CO.ResultEvaluation = 0;\n CO.DynamicScoping = 0;\n CO.Debug = 0;\n CO.CodeGeneration = 1;\n\n cling::Transaction T(CO, \/*llvm::Module=*\/0);\n T.appendUnique(VD);\n T.setCompleted();\n\n m_Interpreter->codegen(&T);\n assert(T.getState() == Transaction::kCommitted\n && \"Compilation should never fail!\");\n }\n assert(VD && \"Cannot be null!\");\n R.addDecl(VD);\n return true;\n }\n\n return false;\n}\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionCommitted(const Transaction &T) {\n if (!T.size())\n return;\n if (fFirstRun) {\n \/\/ Before setting up the callbacks register what cling have seen during init.\n const cling::Transaction* T = m_Interpreter->getFirstTransaction();\n while (T) {\n if (T->getState() == cling::Transaction::kCommitted)\n TCintWithCling__UpdateListsOnCommitted(*T);\n T = T->getNext();\n }\n\n fFirstRun = false;\n }\n\n TCintWithCling__UpdateListsOnCommitted(T);\n}\n\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionUnloaded(const Transaction &T) {\n if (!T.size())\n return;\n\n TCintWithCling__UpdateListsOnUnloaded(T);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Vassil Vassilev 7\/10\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TClingCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Scope.h\"\n\nusing namespace clang;\nusing namespace cling;\n\nclass TObject;\n\n\/\/ Functions used to forward calls from code compiled with no-rtti to code \n\/\/ compiled with rtti.\nextern \"C\" {\n void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&);\n void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&); \n TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx);\n Decl* TCintWithCling__GetObjectDecl(TObject *obj);\n int TCintWithCling__AutoLoadCallback(const char* className);\n}\n\nTClingCallbacks::TClingCallbacks(cling::Interpreter* interp) \n : InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0),\n fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) {\n const Decl* D = 0;\n m_Interpreter->declare(\"namespace __ROOT_SpecialObjects{}\", &D);\n fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D));\n}\n\n\/\/pin the vtable here\nTClingCallbacks::~TClingCallbacks() {}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\nbool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {\n\n if (tryAutoloadInternal(R, S))\n return true; \/\/ happiness.\n\n \/\/ If the autoload wasn't successful try ROOT specials.\n return tryFindROOTSpecialInternal(R, S);\n}\n\nbool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) {\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclarationName Name = R.getLookupName();\n\n \/\/ Try to autoload first if autoloading is enabled\n if (IsAutoloadingEnabled()) {\n \/\/ Avoid tail chasing.\n if (fIsAutoloadingRecursively)\n return false;\n fIsAutoloadingRecursively = true;\n\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n Parser& P = const_cast<Parser&>(m_Interpreter->getParser());\n Parser::ParserCurTokRestoreRAII savedCurToken(P);\n\n bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics();\n SemaR.getDiagnostics().setSuppressAllDiagnostics();\n \n \/\/ We can't PushDeclContext, because we go up and the routine that pops \n \/\/ the DeclContext assumes that we drill down always.\n \/\/ We have to be on the global context. At that point we are in a \n \/\/ wrapper function so the parent context must be the global.\n Sema::ContextAndScopeRAII pushedSAndDC(SemaR, C.getTranslationUnitDecl(), \n SemaR.TUScope);\n\n bool lookupSuccess = false;\n if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) {\n pushedSAndDC.pop();\n cleanupRAII.pop();\n lookupSuccess = SemaR.LookupName(R, S);\n }\n\n SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags);\n\n fIsAutoloadingRecursively = false;\n \n if (lookupSuccess)\n return true;\n }\n\n return false;\n}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {\n\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclContext *CurDC = SemaR.CurContext;\n DeclarationName Name = R.getLookupName();\n\n \/\/ Make sure that the failed lookup comes from the prompt.\n if(!CurDC || !CurDC->isFunctionOrMethod())\n return false;\n if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC))\n if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString()))\n return false;\n\n TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(), \n fLastLookupCtx);\n if (obj) {\n VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, \n Name, \n fROOTSpecialNamespace));\n if (VD) {\n \/\/TODO: Check for same types.\n\n TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD);\n \/\/ Since code was generated already we cannot rely on the initializer \n \/\/ of the decl in the AST, however we will update that init so that it\n \/\/ will be easier while debugging.\n CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());\n Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);\n CStyleCast->setSubExpr(newInit);\n\n \/\/ The actual update happens here, directly in memory.\n *address = obj;\n }\n else {\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n\n const Decl *TD = TCintWithCling__GetObjectDecl(obj);\n \/\/ We will declare the variable as pointer.\n QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));\n \n VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(), \n SourceLocation(), Name.getAsIdentifierInfo(), QT,\n \/*TypeSourceInfo*\/0, SC_None, SC_None\n );\n \/\/ Build an initializer\n Expr* Init \n = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);\n \/\/ Register the decl in our hidden special namespace\n VD->setInit(Init);\n fROOTSpecialNamespace->addDecl(VD);\n\n cling::CompilationOptions CO;\n CO.DeclarationExtraction = 0;\n CO.ValuePrinting = CompilationOptions::VPDisabled;\n CO.ResultEvaluation = 0;\n CO.DynamicScoping = 0;\n CO.Debug = 0;\n CO.CodeGeneration = 1;\n\n cling::Transaction T(CO, \/*llvm::Module=*\/0);\n T.appendUnique(VD);\n T.setCompleted();\n\n Interpreter::CompilationResult Result = m_Interpreter->codegen(&T);\n assert(Result == Interpreter::kSuccess \n && \"Compilation should never fail!\");\n }\n assert(VD && \"Cannot be null!\");\n R.addDecl(VD);\n return true;\n }\n\n return false;\n}\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionCommitted(const Transaction &T) {\n if (!T.size())\n return;\n if (fFirstRun) {\n \/\/ Before setting up the callbacks register what cling have seen during init.\n const cling::Transaction* T = m_Interpreter->getFirstTransaction();\n while (T) {\n if (T->getState() == cling::Transaction::kCommitted)\n TCintWithCling__UpdateListsOnCommitted(*T);\n T = T->getNext();\n }\n\n fFirstRun = false;\n }\n\n TCintWithCling__UpdateListsOnCommitted(T);\n}\n\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionUnloaded(const Transaction &T) {\n if (!T.size())\n return;\n\n TCintWithCling__UpdateListsOnUnloaded(T);\n}\n<commit_msg>Documentation.<commit_after>\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Vassil Vassilev 7\/10\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TClingCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Scope.h\"\n\nusing namespace clang;\nusing namespace cling;\n\nclass TObject;\n\n\/\/ Functions used to forward calls from code compiled with no-rtti to code \n\/\/ compiled with rtti.\nextern \"C\" {\n void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&);\n void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&); \n TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx);\n Decl* TCintWithCling__GetObjectDecl(TObject *obj);\n int TCintWithCling__AutoLoadCallback(const char* className);\n}\n\nTClingCallbacks::TClingCallbacks(cling::Interpreter* interp) \n : InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0),\n fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) {\n const Decl* D = 0;\n m_Interpreter->declare(\"namespace __ROOT_SpecialObjects{}\", &D);\n fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D));\n}\n\n\/\/pin the vtable here\nTClingCallbacks::~TClingCallbacks() {}\n\n\/\/ On a failed lookup we have to try to more things before issuing an error.\n\/\/ The symbol might need to be loaded by ROOT's autoloading mechanism or\n\/\/ it might be a ROOT special object. \n\/\/ \n\/\/ Try those first and if still failing issue the diagnostics.\n\/\/\n\/\/ returns true when a declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {\n\n if (tryAutoloadInternal(R, S))\n return true; \/\/ happiness.\n\n \/\/ If the autoload wasn't successful try ROOT specials.\n return tryFindROOTSpecialInternal(R, S);\n}\n\n\/\/ The symbol might be defined in the ROOT class autoloading map so we have to\n\/\/ try to autoload it first and do secondary lookup to try to find it.\n\/\/\n\/\/ returns true when a declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) {\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclarationName Name = R.getLookupName();\n\n \/\/ Try to autoload first if autoloading is enabled\n if (IsAutoloadingEnabled()) {\n \/\/ Avoid tail chasing.\n if (fIsAutoloadingRecursively)\n return false;\n fIsAutoloadingRecursively = true;\n\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n Parser& P = const_cast<Parser&>(m_Interpreter->getParser());\n Parser::ParserCurTokRestoreRAII savedCurToken(P);\n\n bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics();\n SemaR.getDiagnostics().setSuppressAllDiagnostics();\n \n \/\/ We can't PushDeclContext, because we go up and the routine that pops \n \/\/ the DeclContext assumes that we drill down always.\n \/\/ We have to be on the global context. At that point we are in a \n \/\/ wrapper function so the parent context must be the global.\n Sema::ContextAndScopeRAII pushedSAndDC(SemaR, C.getTranslationUnitDecl(), \n SemaR.TUScope);\n\n bool lookupSuccess = false;\n if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) {\n pushedSAndDC.pop();\n cleanupRAII.pop();\n lookupSuccess = SemaR.LookupName(R, S);\n }\n\n SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags);\n\n fIsAutoloadingRecursively = false;\n \n if (lookupSuccess)\n return true;\n }\n\n return false;\n}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {\n\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclContext *CurDC = SemaR.CurContext;\n DeclarationName Name = R.getLookupName();\n\n \/\/ Make sure that the failed lookup comes from the prompt.\n if(!CurDC || !CurDC->isFunctionOrMethod())\n return false;\n if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC))\n if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString()))\n return false;\n\n TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(), \n fLastLookupCtx);\n if (obj) {\n VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, \n Name, \n fROOTSpecialNamespace));\n if (VD) {\n \/\/TODO: Check for same types.\n\n TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD);\n \/\/ Since code was generated already we cannot rely on the initializer \n \/\/ of the decl in the AST, however we will update that init so that it\n \/\/ will be easier while debugging.\n CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());\n Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);\n CStyleCast->setSubExpr(newInit);\n\n \/\/ The actual update happens here, directly in memory.\n *address = obj;\n }\n else {\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n\n const Decl *TD = TCintWithCling__GetObjectDecl(obj);\n \/\/ We will declare the variable as pointer.\n QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));\n \n VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(), \n SourceLocation(), Name.getAsIdentifierInfo(), QT,\n \/*TypeSourceInfo*\/0, SC_None, SC_None\n );\n \/\/ Build an initializer\n Expr* Init \n = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);\n \/\/ Register the decl in our hidden special namespace\n VD->setInit(Init);\n fROOTSpecialNamespace->addDecl(VD);\n\n cling::CompilationOptions CO;\n CO.DeclarationExtraction = 0;\n CO.ValuePrinting = CompilationOptions::VPDisabled;\n CO.ResultEvaluation = 0;\n CO.DynamicScoping = 0;\n CO.Debug = 0;\n CO.CodeGeneration = 1;\n\n cling::Transaction T(CO, \/*llvm::Module=*\/0);\n T.appendUnique(VD);\n T.setCompleted();\n\n Interpreter::CompilationResult Result = m_Interpreter->codegen(&T);\n assert(Result == Interpreter::kSuccess \n && \"Compilation should never fail!\");\n }\n assert(VD && \"Cannot be null!\");\n R.addDecl(VD);\n return true;\n }\n\n return false;\n}\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionCommitted(const Transaction &T) {\n if (!T.size())\n return;\n if (fFirstRun) {\n \/\/ Before setting up the callbacks register what cling have seen during init.\n const cling::Transaction* T = m_Interpreter->getFirstTransaction();\n while (T) {\n if (T->getState() == cling::Transaction::kCommitted)\n TCintWithCling__UpdateListsOnCommitted(*T);\n T = T->getNext();\n }\n\n fFirstRun = false;\n }\n\n TCintWithCling__UpdateListsOnCommitted(T);\n}\n\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionUnloaded(const Transaction &T) {\n if (!T.size())\n return;\n\n TCintWithCling__UpdateListsOnUnloaded(T);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/questions\/local-pipe-32317081\n\/\/ This project is compatible with Qt 4 and Qt 5\n#include <QtTest>\n#include <private\/qiodevice_p.h>\n#include <private\/qringbuffer_p.h>\n#include <algorithm>\n#include <climits>\n\n#ifndef Q_DECL_OVERRIDE\n#define Q_DECL_OVERRIDE\n#endif\n\nclass AppPipePrivate : public QIODevicePrivate {\npublic:\n#if QT_VERSION < QT_VERSION_CHECK(5,7,0)\n QRingBuffer buffer;\n QRingBuffer writeBuffer;\n int writeBufferChunkSize;\n#endif\n const QByteArray *writeData;\n AppPipePrivate() : writeData(0) { writeBufferChunkSize = 4096; }\n};\n\n\/\/\/ A simple point-to-point intra-process pipe. The other endpoint can live in any\n\/\/\/ thread.\nclass AppPipe : public QIODevice {\n Q_OBJECT\n Q_DECLARE_PRIVATE(AppPipe)\n static inline int intLen(qint64 len) { return std::min(len, qint64(INT_MAX)); }\n Q_SLOT void _a_write(const QByteArray &data) {\n Q_D(AppPipe);\n if (!(d->openMode & QIODevice::ReadOnly)) return; \/\/ We must be readable.\n d->buffer.append(data); \/\/ This is a chunk shipped from the source.\n emit hasIncoming(data);\n emit readyRead();\n }\n void hasOutgoingLong(const char *data, qint64 len) {\n while (len) {\n int const size = intLen(len);\n emit hasOutgoing(QByteArray(data, size));\n data += size;\n len -= size;\n }\n }\npublic:\n AppPipe(QIODevice::OpenMode mode, QObject *parent = 0) :\n QIODevice(*new AppPipePrivate, parent) {\n open(mode);\n }\n AppPipe(AppPipe *other, QIODevice::OpenMode mode, QObject *parent = 0) :\n QIODevice(*new AppPipePrivate, parent) {\n open(mode);\n addOther(other);\n }\n AppPipe(AppPipe *other, QObject *parent = 0) :\n QIODevice(*new AppPipePrivate, parent) {\n addOther(other);\n }\n AppPipe(QObject *parent = 0) :\n QIODevice(*new AppPipePrivate, parent) {\n }\n ~AppPipe() Q_DECL_OVERRIDE {}\n void addOther(AppPipe *other) {\n if (other) {\n connect(this, SIGNAL(hasOutgoing(QByteArray)), other, SLOT(_a_write(QByteArray)), Qt::UniqueConnection);\n connect(other, SIGNAL(hasOutgoing(QByteArray)), this, SLOT(_a_write(QByteArray)), Qt::UniqueConnection);\n }\n }\n void removeOther(AppPipe *other) {\n disconnect(this, SIGNAL(hasOutgoing(QByteArray)), other, SLOT(_a_write(QByteArray)));\n disconnect(other, SIGNAL(hasOutgoing(QByteArray)), this, SLOT(_a_write(QByteArray)));\n }\n void flush() {\n Q_D(AppPipe);\n while (!d->writeBuffer.isEmpty()) {\n QByteArray const data = d->writeBuffer.read();\n emit hasOutgoing(data);\n emit bytesWritten(data.size());\n }\n }\n void close() Q_DECL_OVERRIDE {\n Q_D(AppPipe);\n flush();\n QIODevice::close();\n d->buffer.clear();\n }\n qint64 write(const QByteArray &data) { \/\/ This is an optional optimization. The base method works OK.\n Q_D(AppPipe);\n QScopedValueRollback<const QByteArray*> back(d->writeData);\n if (!(d->openMode & Text))\n d->writeData = &data;\n return QIODevice::write(data);\n }\n qint64 writeData(const char *data, qint64 len) Q_DECL_OVERRIDE {\n Q_D(AppPipe);\n bool buffered = !(d->openMode & Unbuffered);\n if (buffered && (d->writeBuffer.size() + len) > d->writeBufferChunkSize)\n flush();\n if (!buffered\n || len > d->writeBufferChunkSize\n || (len == d->writeBufferChunkSize && d->writeBuffer.isEmpty()))\n {\n if (d->writeData && d->writeData->data() == data && d->writeData->size() == len)\n emit hasOutgoing(*d->writeData);\n else\n hasOutgoingLong(data, len);\n }\n else\n memcpy(d->writeBuffer.reserve(len), data, len);\n return len;\n }\n#if QT_VERSION < QT_VERSION_CHECK(5,7,0)\n qint64 readData(char *data, qint64 len) Q_DECL_OVERRIDE {\n Q_D(AppPipe);\n qint64 hadRead = 0;\n while (len && !d->buffer.isEmpty()) {\n int size = d->buffer.read(data, intLen(len));\n hadRead += size;\n data += size;\n len -= size;\n }\n return hadRead;\n }\n bool canReadLine() const Q_DECL_OVERRIDE {\n Q_D(const AppPipe);\n return d->buffer.indexOf('\\n') != -1 || QIODevice::canReadLine();\n }\n qint64 bytesAvailable() const Q_DECL_OVERRIDE {\n Q_D(const AppPipe);\n return QIODevice::bytesAvailable() + d->buffer.size();\n }\n qint64 bytesToWrite() const Q_DECL_OVERRIDE {\n Q_D(const AppPipe);\n return QIODevice::bytesToWrite() + d->writeBuffer.size();\n }\n#else\n \/\/ all the data is in the read buffer already\n qint64 readData(char *, qint64) Q_DECL_OVERRIDE { return 0; }\n#endif\n bool isSequential() const Q_DECL_OVERRIDE { return true; }\n Q_SIGNAL void hasOutgoing(const QByteArray &);\n Q_SIGNAL void hasIncoming(const QByteArray &);\n};\n\nclass TestAppPipe : public QObject {\n Q_OBJECT\n QByteArray data1, data2;\n struct PipePair {\n AppPipe end1, end2;\n PipePair(QIODevice::OpenMode mode = QIODevice::NotOpen) :\n end1(QIODevice::ReadWrite | mode), end2(&end1, QIODevice::ReadWrite | mode) {}\n };\n Q_SLOT void initTestCase() {\n data1 = randomData();\n data2 = randomData();\n }\n Q_SLOT void sizes() {\n QCOMPARE(sizeof(AppPipe), sizeof(QObject));\n }\n Q_SLOT void basic() {\n PipePair p;\n QVERIFY(p.end1.isOpen() && p.end1.isWritable() && p.end1.isReadable());\n QVERIFY(p.end2.isOpen() && p.end2.isWritable() && p.end2.isReadable());\n static const char hello[] = \"Hello There!\";\n p.end1.write(hello);\n p.end1.flush();\n QCOMPARE(p.end2.readAll(), QByteArray(hello));\n }\n static QByteArray randomData(int const size = 1024*1024*32) {\n QByteArray data;\n data.resize(size);\n char *const d = data.data();\n for (char *p = d+data.size()-1; p >= d; --p)\n *p = qrand();\n Q_ASSERT(data.size() == size);\n return data;\n }\n static void randomChunkWrite(AppPipe *dev, const QByteArray &payload) {\n for (int written = 0, left = payload.size(); left; ) {\n int const chunk = std::min(qrand() % 82931, left);\n dev->write(payload.mid(written, chunk));\n left -= chunk; written += chunk;\n }\n dev->flush();\n }\n void runBigData(PipePair &p) {\n Q_ASSERT(!data1.isEmpty() && !data2.isEmpty());\n randomChunkWrite(&p.end1, data1);\n randomChunkWrite(&p.end2, data2);\n QCOMPARE(p.end1.bytesAvailable(), qint64(data2.size()));\n QCOMPARE(p.end2.bytesAvailable(), qint64(data1.size()));\n QCOMPARE(p.end1.readAll(), data2);\n QCOMPARE(p.end2.readAll(), data1);\n }\n Q_SLOT void bigDataBuffered() {\n PipePair p;\n runBigData(p);\n }\n Q_SLOT void bigDataUnbuffered() {\n PipePair p(QIODevice::Unbuffered);\n runBigData(p);\n }\n};\n\nQTEST_MAIN(TestAppPipe)\n\n#include \"main.moc\"\n<commit_msg>Reorder code to put old Qt compatibility code last.<commit_after>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/questions\/local-pipe-32317081\n\/\/ This project is compatible with Qt 4 and Qt 5\n#include <QtTest>\n#include <private\/qiodevice_p.h>\n#include <private\/qringbuffer_p.h>\n#include <algorithm>\n#include <climits>\n\n#ifndef Q_DECL_OVERRIDE\n#define Q_DECL_OVERRIDE\n#endif\n\nclass AppPipePrivate : public QIODevicePrivate {\npublic:\n#if QT_VERSION < QT_VERSION_CHECK(5,7,0)\n QRingBuffer buffer;\n QRingBuffer writeBuffer;\n int writeBufferChunkSize;\n#endif\n const QByteArray *writeData;\n AppPipePrivate() : writeData(0) { writeBufferChunkSize = 4096; }\n};\n\n\/\/\/ A simple point-to-point intra-process pipe. The other endpoint can live in any\n\/\/\/ thread.\nclass AppPipe : public QIODevice {\n Q_OBJECT\n Q_DECLARE_PRIVATE(AppPipe)\n static inline int intLen(qint64 len) { return std::min(len, qint64(INT_MAX)); }\n Q_SLOT void _a_write(const QByteArray &data) {\n Q_D(AppPipe);\n if (!(d->openMode & QIODevice::ReadOnly)) return; \/\/ We must be readable.\n d->buffer.append(data); \/\/ This is a chunk shipped from the source.\n emit hasIncoming(data);\n emit readyRead();\n }\n void hasOutgoingLong(const char *data, qint64 len) {\n while (len) {\n int const size = intLen(len);\n emit hasOutgoing(QByteArray(data, size));\n data += size;\n len -= size;\n }\n }\npublic:\n AppPipe(QIODevice::OpenMode mode, QObject *parent = 0) :\n QIODevice(*new AppPipePrivate, parent) {\n open(mode);\n }\n AppPipe(AppPipe *other, QIODevice::OpenMode mode, QObject *parent = 0) :\n QIODevice(*new AppPipePrivate, parent) {\n open(mode);\n addOther(other);\n }\n AppPipe(AppPipe *other, QObject *parent = 0) :\n QIODevice(*new AppPipePrivate, parent) {\n addOther(other);\n }\n AppPipe(QObject *parent = 0) :\n QIODevice(*new AppPipePrivate, parent) {\n }\n ~AppPipe() Q_DECL_OVERRIDE {}\n void addOther(AppPipe *other) {\n if (other) {\n connect(this, SIGNAL(hasOutgoing(QByteArray)), other, SLOT(_a_write(QByteArray)), Qt::UniqueConnection);\n connect(other, SIGNAL(hasOutgoing(QByteArray)), this, SLOT(_a_write(QByteArray)), Qt::UniqueConnection);\n }\n }\n void removeOther(AppPipe *other) {\n disconnect(this, SIGNAL(hasOutgoing(QByteArray)), other, SLOT(_a_write(QByteArray)));\n disconnect(other, SIGNAL(hasOutgoing(QByteArray)), this, SLOT(_a_write(QByteArray)));\n }\n void flush() {\n Q_D(AppPipe);\n while (!d->writeBuffer.isEmpty()) {\n QByteArray const data = d->writeBuffer.read();\n emit hasOutgoing(data);\n emit bytesWritten(data.size());\n }\n }\n void close() Q_DECL_OVERRIDE {\n Q_D(AppPipe);\n flush();\n QIODevice::close();\n d->buffer.clear();\n }\n qint64 write(const QByteArray &data) { \/\/ This is an optional optimization. The base method works OK.\n Q_D(AppPipe);\n QScopedValueRollback<const QByteArray*> back(d->writeData);\n if (!(d->openMode & Text))\n d->writeData = &data;\n return QIODevice::write(data);\n }\n qint64 writeData(const char *data, qint64 len) Q_DECL_OVERRIDE {\n Q_D(AppPipe);\n bool buffered = !(d->openMode & Unbuffered);\n if (buffered && (d->writeBuffer.size() + len) > d->writeBufferChunkSize)\n flush();\n if (!buffered\n || len > d->writeBufferChunkSize\n || (len == d->writeBufferChunkSize && d->writeBuffer.isEmpty()))\n {\n if (d->writeData && d->writeData->data() == data && d->writeData->size() == len)\n emit hasOutgoing(*d->writeData);\n else\n hasOutgoingLong(data, len);\n }\n else\n memcpy(d->writeBuffer.reserve(len), data, len);\n return len;\n }\n bool isSequential() const Q_DECL_OVERRIDE { return true; }\n Q_SIGNAL void hasOutgoing(const QByteArray &);\n Q_SIGNAL void hasIncoming(const QByteArray &);\n#if QT_VERSION >= QT_VERSION_CHECK(5,7,0)\n \/\/ all the data is in the read buffer already\n qint64 readData(char *, qint64) Q_DECL_OVERRIDE { return 0; }\n#else\n qint64 readData(char *data, qint64 len) Q_DECL_OVERRIDE {\n Q_D(AppPipe);\n qint64 hadRead = 0;\n while (len && !d->buffer.isEmpty()) {\n int size = d->buffer.read(data, intLen(len));\n hadRead += size;\n data += size;\n len -= size;\n }\n return hadRead;\n }\n bool canReadLine() const Q_DECL_OVERRIDE {\n Q_D(const AppPipe);\n return d->buffer.indexOf('\\n') != -1 || QIODevice::canReadLine();\n }\n qint64 bytesAvailable() const Q_DECL_OVERRIDE {\n Q_D(const AppPipe);\n return QIODevice::bytesAvailable() + d->buffer.size();\n }\n qint64 bytesToWrite() const Q_DECL_OVERRIDE {\n Q_D(const AppPipe);\n return QIODevice::bytesToWrite() + d->writeBuffer.size();\n }\n#endif\n};\n\nclass TestAppPipe : public QObject {\n Q_OBJECT\n QByteArray data1, data2;\n struct PipePair {\n AppPipe end1, end2;\n PipePair(QIODevice::OpenMode mode = QIODevice::NotOpen) :\n end1(QIODevice::ReadWrite | mode), end2(&end1, QIODevice::ReadWrite | mode) {}\n };\n Q_SLOT void initTestCase() {\n data1 = randomData();\n data2 = randomData();\n }\n Q_SLOT void sizes() {\n QCOMPARE(sizeof(AppPipe), sizeof(QObject));\n }\n Q_SLOT void basic() {\n PipePair p;\n QVERIFY(p.end1.isOpen() && p.end1.isWritable() && p.end1.isReadable());\n QVERIFY(p.end2.isOpen() && p.end2.isWritable() && p.end2.isReadable());\n static const char hello[] = \"Hello There!\";\n p.end1.write(hello);\n p.end1.flush();\n QCOMPARE(p.end2.readAll(), QByteArray(hello));\n }\n static QByteArray randomData(int const size = 1024*1024*32) {\n QByteArray data;\n data.resize(size);\n char *const d = data.data();\n for (char *p = d+data.size()-1; p >= d; --p)\n *p = qrand();\n Q_ASSERT(data.size() == size);\n return data;\n }\n static void randomChunkWrite(AppPipe *dev, const QByteArray &payload) {\n for (int written = 0, left = payload.size(); left; ) {\n int const chunk = std::min(qrand() % 82931, left);\n dev->write(payload.mid(written, chunk));\n left -= chunk; written += chunk;\n }\n dev->flush();\n }\n void runBigData(PipePair &p) {\n Q_ASSERT(!data1.isEmpty() && !data2.isEmpty());\n randomChunkWrite(&p.end1, data1);\n randomChunkWrite(&p.end2, data2);\n QCOMPARE(p.end1.bytesAvailable(), qint64(data2.size()));\n QCOMPARE(p.end2.bytesAvailable(), qint64(data1.size()));\n QCOMPARE(p.end1.readAll(), data2);\n QCOMPARE(p.end2.readAll(), data1);\n }\n Q_SLOT void bigDataBuffered() {\n PipePair p;\n runBigData(p);\n }\n Q_SLOT void bigDataUnbuffered() {\n PipePair p(QIODevice::Unbuffered);\n runBigData(p);\n }\n Q_SLOT void cleanupTestCase() {\n data1.clear(); data2.clear();\n }\n};\n\nQTEST_MAIN(TestAppPipe)\n\n#include \"main.moc\"\n<|endoftext|>"} {"text":"<commit_before><commit_msg>#101437# Merged in 1.16.14.1<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio\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#include \"ch.h\"\n#include \"hal.h\"\n#include \"chprintf.h\"\n\n#include \"blink.h\"\n#include \"usbconfig.h\"\n\n\/*\n * DAC configuration options (set in halconf.h)\n * DAC_USE_WAIT FALSE\n * DAC_USE_MUTUAL_EXCLUSION FALSE\n *\n * DAC driver system settings (set in mcuconf.h)\n * STM32_DAC_DUAL_MODE FALSE\n * STM32_DAC_USE_DAC1_CH1 TRUE\n * STM32_DAC_USE_DAC1_CH2 FALSE\n *\/\n\n\/*\n * DAC conversion group is not used.\n *\/\n\nnamespace {\n const DACConfig dac1cfg1 = {\n .init = 2047U, \/\/ max value is 4095 (12-bit)\n .datamode = DAC_DHRM_12BIT_RIGHT\n };\n\n const systime_t loop_time = MS2ST(1); \/\/ loop at 1 kHz\n} \/\/ namespace\n\n\/*\n * Application entry point.\n *\/\nint main(void) {\n\n \/*\n * System initializations.\n * - HAL initialization, this also initializes the configured device drivers\n * and performs the board-specific initializations.\n * - Kernel initialization, the main() function becomes a thread and the\n * RTOS is active.\n *\/\n halInit();\n chSysInit();\n\n \/*\n * Start DAC1 driver and set output pin as analog as suggested in Reference Manual.\n *\/\n palSetLineMode(LINE_KOLLM_ACTL_TORQUE, PAL_MODE_INPUT_ANALOG);\n dacStart(&DACD1, &dac1cfg1);\n\n \/*\n * Create the LED blink thread.\n *\/\n chBlinkThreadCreateStatic(NORMALPRIO-1);\n\n \/*\n * Initializes a serial-over-USB CDC driver.\n *\/\n sduObjectInit(&SDU1);\n sduStart(&SDU1, &serusbcfg);\n\n \/*\n * Activates the USB driver and then the USB bus pull-up on D+.\n * Note, a delay is inserted in order to not have to disconnect the cable\n * after a reset.\n *\/\n board_usb_lld_disconnect_bus(); \/\/usbDisconnectBus(serusbcfg.usbp);\n chThdSleepMilliseconds(1500);\n usbStart(serusbcfg.usbp, &usbcfg);\n board_usb_lld_connect_bus(); \/\/usbConnectBus(serusbcfg.usbp);\n\n \/*\n * Normal main() thread activity. Set DAC conversion at roughly 1 kHz.\n *\/\n dacsample_t aout1 = 0;\n while (true) {\n aout1 = (++aout1) % 4095;\n dacPutChannelX(&DACD1, 0, aout1);\n if (SDU1.config->usbp->state == USB_ACTIVE) {\n chprintf((BaseSequentialStream*)&SDU1,\n \"dac: %d\\r\\n\", aout1);\n }\n chThdSleep(loop_time);\n }\n}\n<commit_msg>Change analog output so that changes are easier to see<commit_after>\/*\n ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio\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#include \"ch.h\"\n#include \"hal.h\"\n#include \"chprintf.h\"\n\n#include \"blink.h\"\n#include \"usbconfig.h\"\n\n\/*\n * DAC configuration options (set in halconf.h)\n * DAC_USE_WAIT FALSE\n * DAC_USE_MUTUAL_EXCLUSION FALSE\n *\n * DAC driver system settings (set in mcuconf.h)\n * STM32_DAC_DUAL_MODE FALSE\n * STM32_DAC_USE_DAC1_CH1 TRUE\n * STM32_DAC_USE_DAC1_CH2 FALSE\n *\/\n\n\/*\n * DAC conversion group is not used.\n *\/\n\nnamespace {\n const DACConfig dac1cfg1 = {\n .init = 2047U, \/\/ max value is 4095 (12-bit)\n .datamode = DAC_DHRM_12BIT_RIGHT\n };\n\n const systime_t loop_time = MS2ST(1); \/\/ loop at 1 kHz\n} \/\/ namespace\n\n\/*\n * Application entry point.\n *\/\nint main(void) {\n\n \/*\n * System initializations.\n * - HAL initialization, this also initializes the configured device drivers\n * and performs the board-specific initializations.\n * - Kernel initialization, the main() function becomes a thread and the\n * RTOS is active.\n *\/\n halInit();\n chSysInit();\n\n \/*\n * Start DAC1 driver and set output pin as analog as suggested in Reference Manual.\n *\/\n palSetLineMode(LINE_KOLLM_ACTL_TORQUE, PAL_MODE_INPUT_ANALOG);\n dacStart(&DACD1, &dac1cfg1);\n\n \/*\n * Create the LED blink thread.\n *\/\n chBlinkThreadCreateStatic(NORMALPRIO-1);\n\n \/*\n * Initializes a serial-over-USB CDC driver.\n *\/\n sduObjectInit(&SDU1);\n sduStart(&SDU1, &serusbcfg);\n\n \/*\n * Activates the USB driver and then the USB bus pull-up on D+.\n * Note, a delay is inserted in order to not have to disconnect the cable\n * after a reset.\n *\/\n board_usb_lld_disconnect_bus(); \/\/usbDisconnectBus(serusbcfg.usbp);\n chThdSleepMilliseconds(1500);\n usbStart(serusbcfg.usbp, &usbcfg);\n board_usb_lld_connect_bus(); \/\/usbConnectBus(serusbcfg.usbp);\n\n \/*\n * Normal main() thread activity. Set DAC conversion at roughly 1 kHz.\n *\/\n dacsample_t aout1 = 0;\n while (true) {\n aout1 = (aout1 + 1000) % 4095;\n dacPutChannelX(&DACD1, 0, aout1);\n if (SDU1.config->usbp->state == USB_ACTIVE) {\n chprintf((BaseSequentialStream*)&SDU1,\n \"dac: %d\\r\\n\", aout1);\n }\n chThdSleep(loop_time);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include <dirent.h>\n#include <sys\/types.h>\n#include <pwd.h>\n\n#include <ydsh\/ydsh.h>\n#include <config.h>\n#include \"..\/test_common.h\"\n#include \"..\/..\/src\/constant.h\"\n#include \"..\/..\/src\/misc\/fatal.h\"\n\n\n#ifndef BIN_PATH\n#error require BIN_PATH\n#endif\n\n#ifndef EXTRA_TEST_DIR\n#error require EXTRA_TEST_DIR\n#endif\n\n\/**\n * extra test cases dependent on system directory structure\n * and have side effect on directory structures\n *\/\n\n\nusing namespace ydsh;\n\nclass ModLoadTest : public ExpectOutput {};\n\nstatic ProcBuilder ds(const char *src) {\n return ProcBuilder{BIN_PATH, \"-c\", src}\n .setOut(IOConfig::PIPE)\n .setErr(IOConfig::PIPE)\n .setWorkingDir(EXTRA_TEST_DIR);\n}\n\nTEST_F(ModLoadTest, prepare) {\n auto src = format(\"assert test -f $SCRIPT_DIR\/mod4extra1.ds\\n\"\n \"assert !test -f $SCRIPT_DIR\/mod4extra2.ds\\n\"\n \"assert !test -f $SCRIPT_DIR\/mod4extra3.ds\\n\"\n \"assert test -f ~\/.ydsh\/module\/mod4extra1.ds\\n\"\n \"assert test -f ~\/.ydsh\/module\/mod4extra2.ds\\n\"\n \"assert !test -f ~\/.ydsh\/module\/mod4extra3.ds\\n\"\n \"assert test -f %s\/mod4extra1.ds\\n\"\n \"assert test -f %s\/mod4extra2.ds\\n\"\n \"assert test -f %s\/mod4extra3.ds\\n\"\n \"true\", SYSTEM_MOD_DIR, SYSTEM_MOD_DIR, SYSTEM_MOD_DIR);\n\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src.c_str()), 0));\n}\n\nTEST_F(ModLoadTest, scriptdir) {\n const char *src = R\"(\n source mod4extra1.ds\n assert $OK_LOADING == \"script_dir: mod4extra1.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include1.ds\n assert $mod1.OK_LOADING == \"script_dir: mod4extra1.ds\"\n assert $mod2.OK_LOADING == \"local: mod4extra2.ds\"\n assert $mod3.OK_LOADING == \"system: mod4extra3.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0, \"include from script_dir!!\\n\"));\n}\n\nTEST_F(ModLoadTest, local) {\n const char *src = R\"(\n source mod4extra2.ds\n assert $OK_LOADING == \"local: mod4extra2.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include2.ds\n assert $mod1.OK_LOADING == \"local: mod4extra1.ds\"\n assert $mod2.OK_LOADING == \"local: mod4extra2.ds\"\n assert $mod3.OK_LOADING == \"system: mod4extra3.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include4.ds\n assert $mod.OK_LOADING == \"system: mod4extra4.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n}\n\nTEST_F(ModLoadTest, system) {\n const char *src = R\"(\n source mod4extra3.ds\n assert $OK_LOADING == \"system: mod4extra3.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include3.ds\n assert $mod1.OK_LOADING == \"system: mod4extra1.ds\"\n assert $mod2.OK_LOADING == \"system: mod4extra2.ds\"\n assert $mod3.OK_LOADING == \"system: mod4extra3.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include5.ds\n exit 100\n)\";\n\n auto e = format(\"%s\/include5.ds:2: [semantic error] module not found: `mod4extra5.ds'\\n\"\n \"source mod4extra5.ds as mod\\n\"\n \" ^~~~~~~~~~~~~\\n\"\n \"(string):2: [note] at module import\\n\"\n \" source include5.ds\\n\"\n \" ^~~~~~~~~~~\\n\", SYSTEM_MOD_DIR);\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 1, \"\", e.c_str()));\n}\n\nclass FileFactory {\nprivate:\n std::string name;\n\npublic:\n \/**\n *\n * @param name\n * must be full path\n * @param content\n *\/\n FileFactory(const char *name, const std::string &content) : name(name) {\n FILE *fp = fopen(this->name.c_str(), \"w\");\n fwrite(content.c_str(), sizeof(char), content.size(), fp);\n fflush(fp);\n fclose(fp);\n }\n\n ~FileFactory() {\n remove(this->name.c_str());\n }\n\n const std::string &getFileName() const {\n return this->name;\n }\n};\n\n#define XSTR(v) #v\n#define STR(v) XSTR(v)\n\n#define PROMPT \"ydsh-\" STR(X_INFO_MAJOR_VERSION) \".\" STR(X_INFO_MINOR_VERSION) \"$ \"\n\nstruct RCTest : public InteractiveShellBase {\n RCTest() : InteractiveShellBase(BIN_PATH, \".\") {\n this->setPrompt(PROMPT);\n }\n};\n\nstatic std::string getHOME() {\n std::string str;\n struct passwd *pw = getpwuid(getuid());\n if(pw == nullptr) {\n fatal_perror(\"getpwuid failed\");\n }\n str = pw->pw_dir;\n return str;\n}\n\nTEST_F(RCTest, rcfile1) {\n std::string rcpath = getHOME();\n rcpath += \"\/.ydshrc\";\n FileFactory fileFactory(rcpath.c_str(), \"var RC_VAR = 'rcfile: ~\/.ydshrc'\");\n\n this->invoke(\"--quiet\");\n ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT));\n ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait(\"assert $RC_VAR == 'rcfile: ~\/.ydshrc'; exit 23\", 23, WaitStatus::EXITED));\n}\n\nstruct APITest : public ExpectOutput {\n DSState *state{nullptr};\n\n APITest() {\n this->state = DSState_create();\n }\n\n ~APITest() override {\n DSState_delete(&this->state);\n }\n};\n\nTEST_F(APITest, modFullpath) {\n DSError e;\n int r = DSState_loadModule(this->state, \"edit\", DS_MOD_FULLPATH, &e); \/\/ not load 'edit'\n ASSERT_EQ(1, r);\n ASSERT_EQ(DS_ERROR_KIND_TYPE_ERROR, e.kind);\n ASSERT_STREQ(\"NotFoundMod\", e.name);\n ASSERT_EQ(0, e.lineNum);\n DSError_release(&e);\n}\n\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}<commit_msg>update test case<commit_after>#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include <dirent.h>\n#include <sys\/types.h>\n#include <pwd.h>\n\n#include <ydsh\/ydsh.h>\n#include <config.h>\n#include \"..\/test_common.h\"\n#include \"..\/..\/src\/constant.h\"\n#include \"..\/..\/src\/misc\/fatal.h\"\n\n\n#ifndef BIN_PATH\n#error require BIN_PATH\n#endif\n\n#ifndef EXTRA_TEST_DIR\n#error require EXTRA_TEST_DIR\n#endif\n\n\/**\n * extra test cases dependent on system directory structure\n * and have side effect on directory structures\n *\/\n\n\nusing namespace ydsh;\n\nclass ModLoadTest : public ExpectOutput {};\n\nstatic ProcBuilder ds(const char *src) {\n return ProcBuilder{BIN_PATH, \"-c\", src}\n .setOut(IOConfig::PIPE)\n .setErr(IOConfig::PIPE)\n .setWorkingDir(EXTRA_TEST_DIR);\n}\n\nTEST_F(ModLoadTest, prepare) {\n auto src = format(\"assert test -f $SCRIPT_DIR\/mod4extra1.ds\\n\"\n \"assert !test -f $SCRIPT_DIR\/mod4extra2.ds\\n\"\n \"assert !test -f $SCRIPT_DIR\/mod4extra3.ds\\n\"\n \"assert test -f ~\/.ydsh\/module\/mod4extra1.ds\\n\"\n \"assert test -f ~\/.ydsh\/module\/mod4extra2.ds\\n\"\n \"assert !test -f ~\/.ydsh\/module\/mod4extra3.ds\\n\"\n \"assert test -f %s\/mod4extra1.ds\\n\"\n \"assert test -f %s\/mod4extra2.ds\\n\"\n \"assert test -f %s\/mod4extra3.ds\\n\"\n \"true\", SYSTEM_MOD_DIR, SYSTEM_MOD_DIR, SYSTEM_MOD_DIR);\n\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src.c_str()), 0));\n}\n\nTEST_F(ModLoadTest, scriptdir) {\n const char *src = R\"(\n source mod4extra1.ds\n assert $OK_LOADING == \"script_dir: mod4extra1.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include1.ds\n assert $mod1.OK_LOADING == \"script_dir: mod4extra1.ds\"\n assert $mod2.OK_LOADING == \"local: mod4extra2.ds\"\n assert $mod3.OK_LOADING == \"system: mod4extra3.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0, \"include from script_dir!!\\n\"));\n}\n\nTEST_F(ModLoadTest, local) {\n const char *src = R\"(\n source mod4extra2.ds\n assert $OK_LOADING == \"local: mod4extra2.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include2.ds\n assert $mod1.OK_LOADING == \"local: mod4extra1.ds\"\n assert $mod2.OK_LOADING == \"local: mod4extra2.ds\"\n assert $mod3.OK_LOADING == \"system: mod4extra3.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include4.ds\n assert $mod.OK_LOADING == \"system: mod4extra4.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n}\n\nTEST_F(ModLoadTest, system) {\n const char *src = R\"(\n source mod4extra3.ds\n assert $OK_LOADING == \"system: mod4extra3.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include3.ds\n assert $mod1.OK_LOADING == \"system: mod4extra1.ds\"\n assert $mod2.OK_LOADING == \"system: mod4extra2.ds\"\n assert $mod3.OK_LOADING == \"system: mod4extra3.ds\"\n)\";\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0));\n\n src = R\"(\n source include5.ds\n exit 100\n)\";\n\n auto e = format(\"%s\/include5.ds:2: [semantic error] module not found: `mod4extra5.ds'\\n\"\n \"source mod4extra5.ds as mod\\n\"\n \" ^~~~~~~~~~~~~\\n\"\n \"(string):2: [note] at module import\\n\"\n \" source include5.ds\\n\"\n \" ^~~~~~~~~~~\\n\", SYSTEM_MOD_DIR);\n ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 1, \"\", e.c_str()));\n}\n\nclass FileFactory {\nprivate:\n std::string name;\n\npublic:\n \/**\n *\n * @param name\n * must be full path\n * @param content\n *\/\n FileFactory(const char *name, const std::string &content) : name(name) {\n FILE *fp = fopen(this->name.c_str(), \"w\");\n fwrite(content.c_str(), sizeof(char), content.size(), fp);\n fflush(fp);\n fclose(fp);\n }\n\n ~FileFactory() {\n remove(this->name.c_str());\n }\n\n const std::string &getFileName() const {\n return this->name;\n }\n};\n\n#define XSTR(v) #v\n#define STR(v) XSTR(v)\n\n#define PROMPT \"ydsh-\" STR(X_INFO_MAJOR_VERSION) \".\" STR(X_INFO_MINOR_VERSION) \"$ \"\n\nstruct RCTest : public InteractiveShellBase {\n RCTest() : InteractiveShellBase(BIN_PATH, \".\") {\n this->setPrompt(PROMPT);\n }\n};\n\nstatic std::string getHOME() {\n std::string str;\n struct passwd *pw = getpwuid(getuid());\n if(pw == nullptr) {\n fatal_perror(\"getpwuid failed\");\n }\n str = pw->pw_dir;\n return str;\n}\n\nTEST_F(RCTest, rcfile1) {\n std::string rcpath = getHOME();\n rcpath += \"\/.ydshrc\";\n FileFactory fileFactory(rcpath.c_str(), \"var RC_VAR = 'rcfile: ~\/.ydshrc'\");\n\n this->invoke(\"--quiet\");\n ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT));\n ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait(\"assert $RC_VAR == 'rcfile: ~\/.ydshrc'; exit 23\", 23, WaitStatus::EXITED));\n}\n\nstruct APITest : public ExpectOutput {\n DSState *state{nullptr};\n\n APITest() {\n this->state = DSState_create();\n }\n\n ~APITest() override {\n DSState_delete(&this->state);\n }\n};\n\nTEST_F(APITest, modFullpath) {\n DSError e;\n int r = DSState_loadModule(this->state, \"edit\", DS_MOD_FULLPATH, &e); \/\/ not load 'edit'\n ASSERT_EQ(1, r);\n ASSERT_EQ(DS_ERROR_KIND_TYPE_ERROR, e.kind);\n ASSERT_STREQ(\"NotFoundMod\", e.name);\n ASSERT_EQ(0, e.lineNum);\n DSError_release(&e);\n}\n\nTEST_F(APITest, mod) {\n DSError e;\n int r = DSState_loadModule(this->state, \"edit\", 0, &e);\n ASSERT_EQ(0, r);\n ASSERT_EQ(DS_ERROR_KIND_SUCCESS, e.kind);\n ASSERT_EQ(0, e.lineNum);\n DSError_release(&e);\n}\n\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the Ofi Labs X2 project.\n\n Copyright (C) 2010 Ariya Hidayat <ariya.hidayat@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions 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 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 <organization> nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"kineticmodel.h\"\n\n#include <QtCore\/QTimer>\n#include <QtCore\/QDateTime>\n\nstatic const int KineticModelDefaultUpdateInterval = 15; \/\/ ms\n\nclass KineticModelPrivate\n{\npublic:\n QTimer ticker;\n\n int duration;\n QPointF position;\n QPointF velocity;\n QPointF deacceleration;\n\n QTime timestamp;\n QPointF lastPosition;\n\n KineticModelPrivate();\n};\n\nKineticModelPrivate::KineticModelPrivate()\n : duration(1403)\n , position(0, 0)\n , velocity(0, 0)\n , deacceleration(0, 0)\n , lastPosition(0, 0)\n{\n\n}\n\nKineticModel::KineticModel(QObject *parent)\n : QObject(parent)\n , d_ptr(new KineticModelPrivate)\n{\n connect(&d_ptr->ticker, SIGNAL(timeout()), SLOT(update()));\n d_ptr->ticker.setInterval(KineticModelDefaultUpdateInterval);\n}\n\nKineticModel::~KineticModel()\n{\n\n}\n\nint KineticModel::duration() const\n{\n return d_ptr->duration;\n}\n\nvoid KineticModel::setDuration(int ms)\n{\n d_ptr->duration = ms;\n}\n\nQPointF KineticModel::position() const\n{\n return d_ptr->position;\n}\n\nvoid KineticModel::setPosition(QPointF position)\n{\n setPosition( position.x(), position.y() );\n}\n\nvoid KineticModel::setPosition(qreal posX, qreal posY)\n{\n d_ptr->position.setX( posX );\n d_ptr->position.setY( posY );\n\n int elapsed = d_ptr->timestamp.elapsed();\n\n \/\/ too fast gives less accuracy\n if (elapsed < d_ptr->ticker.interval() \/ 2) {\n return;\n }\n\n qreal delta = static_cast<qreal>( elapsed ) \/ 1000.0;\n\n QPointF lastSpeed = d_ptr->velocity;\n QPointF currentSpeed = ( d_ptr->position - d_ptr->lastPosition ) \/ delta;\n d_ptr->velocity = 0.2 * lastSpeed + 0.8 * currentSpeed;\n d_ptr->lastPosition = d_ptr->position;\n\n d_ptr->timestamp.start();\n}\n\nint KineticModel::updateInterval() const\n{\n return d_ptr->ticker.interval();\n}\n\nvoid KineticModel::setUpdateInterval(int ms)\n{\n d_ptr->ticker.setInterval(ms);\n}\n\nvoid KineticModel::resetSpeed()\n{\n Q_D(KineticModel);\n\n d->ticker.stop();\n d->lastPosition = d->position;\n d->timestamp.start();\n d->velocity = QPointF(0, 0);\n}\n\nvoid KineticModel::release()\n{\n Q_D(KineticModel);\n\n d->deacceleration = d->velocity * 1000 \/ ( 1 + d_ptr->duration );\n if (d->deacceleration.x() < 0) {\n d->deacceleration.setX( -d->deacceleration.x() );\n }\n if (d->deacceleration.y() < 0) {\n d->deacceleration.setY( -d->deacceleration.y() );\n }\n\n if (d->deacceleration.x() > 0.0005 || d->deacceleration.y() > 0.0005) {\n if (!d->ticker.isActive())\n d->ticker.start();\n update();\n } else {\n d->ticker.stop();\n emit finished();\n }\n}\n\nvoid KineticModel::update()\n{\n Q_D(KineticModel);\n\n int elapsed = d->timestamp.elapsed();\n qreal delta = static_cast<qreal>(elapsed) \/ 1000.0;\n\n d->position += d->velocity * delta;\n QPointF vstep = d->deacceleration * delta;\n\n if (d->velocity.x() < vstep.x() && d->velocity.x() >= -vstep.x()) {\n d->velocity.setX( 0 );\n } else {\n if (d->velocity.x() > 0)\n d->velocity.setX( d->velocity.x() - vstep.x() );\n else\n d->velocity.setX( d->velocity.x() + vstep.x() );\n }\n\n if (d->velocity.y() < vstep.y() && d->velocity.y() >= -vstep.y()) {\n d->velocity.setY( 0 );\n } else {\n if (d->velocity.y() > 0)\n d->velocity.setY( d->velocity.y() - vstep.y() );\n else\n d->velocity.setY( d->velocity.y() + vstep.y() );\n }\n\n emit positionChanged( d->position.x(), d->position.y() );\n\n if (d->velocity.isNull()) {\n emit finished();\n d->ticker.stop();\n }\n\n d->timestamp.start();\n}\n\n#include \"kineticmodel.moc\"\n\n<commit_msg>do not start kinetic spinning if the last sample is too long ago<commit_after>\/*\n This file is part of the Ofi Labs X2 project.\n\n Copyright (C) 2010 Ariya Hidayat <ariya.hidayat@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions 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 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 <organization> nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"kineticmodel.h\"\n\n#include <QtCore\/QTimer>\n#include <QtCore\/QDateTime>\n\nstatic const int KineticModelDefaultUpdateInterval = 15; \/\/ ms\n\nclass KineticModelPrivate\n{\npublic:\n QTimer ticker;\n\n int duration;\n QPointF position;\n QPointF velocity;\n QPointF deacceleration;\n\n QTime timestamp;\n QPointF lastPosition;\n\n KineticModelPrivate();\n};\n\nKineticModelPrivate::KineticModelPrivate()\n : duration(1403)\n , position(0, 0)\n , velocity(0, 0)\n , deacceleration(0, 0)\n , lastPosition(0, 0)\n{\n\n}\n\nKineticModel::KineticModel(QObject *parent)\n : QObject(parent)\n , d_ptr(new KineticModelPrivate)\n{\n connect(&d_ptr->ticker, SIGNAL(timeout()), SLOT(update()));\n d_ptr->ticker.setInterval(KineticModelDefaultUpdateInterval);\n}\n\nKineticModel::~KineticModel()\n{\n\n}\n\nint KineticModel::duration() const\n{\n return d_ptr->duration;\n}\n\nvoid KineticModel::setDuration(int ms)\n{\n d_ptr->duration = ms;\n}\n\nQPointF KineticModel::position() const\n{\n return d_ptr->position;\n}\n\nvoid KineticModel::setPosition(QPointF position)\n{\n setPosition( position.x(), position.y() );\n}\n\nvoid KineticModel::setPosition(qreal posX, qreal posY)\n{\n d_ptr->position.setX( posX );\n d_ptr->position.setY( posY );\n\n int elapsed = d_ptr->timestamp.elapsed();\n\n \/\/ too fast gives less accuracy\n if (elapsed < d_ptr->ticker.interval() \/ 2) {\n return;\n }\n\n qreal delta = static_cast<qreal>( elapsed ) \/ 1000.0;\n\n QPointF lastSpeed = d_ptr->velocity;\n QPointF currentSpeed = ( d_ptr->position - d_ptr->lastPosition ) \/ delta;\n d_ptr->velocity = 0.2 * lastSpeed + 0.8 * currentSpeed;\n d_ptr->lastPosition = d_ptr->position;\n\n d_ptr->timestamp.start();\n}\n\nint KineticModel::updateInterval() const\n{\n return d_ptr->ticker.interval();\n}\n\nvoid KineticModel::setUpdateInterval(int ms)\n{\n d_ptr->ticker.setInterval(ms);\n}\n\nvoid KineticModel::resetSpeed()\n{\n Q_D(KineticModel);\n\n d->ticker.stop();\n d->lastPosition = d->position;\n d->timestamp.start();\n d->velocity = QPointF(0, 0);\n}\n\nvoid KineticModel::release()\n{\n Q_D(KineticModel);\n\n \/\/ prevent kinetic spinning if last mouse move is too long ago\n const int elapsed = d->timestamp.elapsed();\n if ( elapsed > 2 * d->ticker.interval() ) {\n d->ticker.stop();\n emit finished();\n return;\n }\n\n d->deacceleration = d->velocity * 1000 \/ ( 1 + d_ptr->duration );\n if (d->deacceleration.x() < 0) {\n d->deacceleration.setX( -d->deacceleration.x() );\n }\n if (d->deacceleration.y() < 0) {\n d->deacceleration.setY( -d->deacceleration.y() );\n }\n\n if (!d->ticker.isActive())\n d->ticker.start();\n}\n\nvoid KineticModel::update()\n{\n Q_D(KineticModel);\n\n int elapsed = d->timestamp.elapsed();\n qreal delta = static_cast<qreal>(elapsed) \/ 1000.0;\n\n d->position += d->velocity * delta;\n QPointF vstep = d->deacceleration * delta;\n\n if (d->velocity.x() < vstep.x() && d->velocity.x() >= -vstep.x()) {\n d->velocity.setX( 0 );\n } else {\n if (d->velocity.x() > 0)\n d->velocity.setX( d->velocity.x() - vstep.x() );\n else\n d->velocity.setX( d->velocity.x() + vstep.x() );\n }\n\n if (d->velocity.y() < vstep.y() && d->velocity.y() >= -vstep.y()) {\n d->velocity.setY( 0 );\n } else {\n if (d->velocity.y() > 0)\n d->velocity.setY( d->velocity.y() - vstep.y() );\n else\n d->velocity.setY( d->velocity.y() + vstep.y() );\n }\n\n emit positionChanged( d->position.x(), d->position.y() );\n\n if (d->velocity.isNull()) {\n emit finished();\n d->ticker.stop();\n }\n\n d->timestamp.start();\n}\n\n#include \"kineticmodel.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/* libcdr\n * Version: MPL 1.1 \/ GPLv2+ \/ LGPLv2+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>\n * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>\n *\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPLv2+\"), or\n * the GNU Lesser General Public License Version 2 or later (the \"LGPLv2+\"),\n * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable\n * instead of those above.\n *\/\n\n#include \"libcdr_utils.h\"\n\n#define CDR_NUM_ELEMENTS(array) sizeof(array)\/sizeof(array[0])\n\nuint8_t libcdr::readU8(WPXInputStream *input, bool \/* bigEndian *\/)\n{\n if (!input || input->atEOS())\n {\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint8_t))\n return *(uint8_t const *)(p);\n throw EndOfStreamException();\n}\n\nuint16_t libcdr::readU16(WPXInputStream *input, bool bigEndian)\n{\n uint16_t p0 = (uint16_t)readU8(input);\n uint16_t p1 = (uint16_t)readU8(input);\n if (bigEndian)\n return (uint16_t)(p1|(p0<<8));\n return (uint16_t)(p0|(p1<<8));\n}\n\nuint32_t libcdr::readU32(WPXInputStream *input, bool bigEndian)\n{\n uint32_t p0 = (uint32_t)readU8(input);\n uint32_t p1 = (uint32_t)readU8(input);\n uint32_t p2 = (uint32_t)readU8(input);\n uint32_t p3 = (uint32_t)readU8(input);\n if (bigEndian)\n return (uint32_t)(p3|(p2<<8)|(p1<<16)|(p0<<24));\n return (uint32_t)(p0|(p1<<8)|(p2<<16)|(p3<<24));\n}\n\nint32_t libcdr::readS32(WPXInputStream *input, bool bigEndian)\n{\n return (int32_t)readU32(input, bigEndian);\n}\n\nuint64_t libcdr::readU64(WPXInputStream *input, bool bigEndian)\n{\n uint64_t p0 = (uint64_t)readU8(input);\n uint64_t p1 = (uint64_t)readU8(input);\n uint64_t p2 = (uint64_t)readU8(input);\n uint64_t p3 = (uint64_t)readU8(input);\n uint64_t p4 = (uint64_t)readU8(input);\n uint64_t p5 = (uint64_t)readU8(input);\n uint64_t p6 = (uint64_t)readU8(input);\n uint64_t p7 = (uint64_t)readU8(input);\n if (bigEndian)\n return (uint64_t)(p7|(p6<<8)|(p5<<16)|(p4<<24)|(p3<<32)|(p2<<40)|(p1<<48)|(p0<<56));\n return (uint64_t)(p0|(p1<<8)|(p2<<16)|(p3<<24)|(p4<<32)|(p5<<40)|(p6<<48)|(p7<<56));\n}\n\ndouble libcdr::readDouble(WPXInputStream *input, bool bigEndian)\n{\n union\n {\n uint64_t u;\n double d;\n } tmpUnion;\n\n tmpUnion.u = readU64(input, bigEndian);\n\n return tmpUnion.d;\n}\n\n#ifdef DEBUG\nconst char *libcdr::toFourCC(unsigned value)\n{\n static char sValue[5] = { 0, 0, 0, 0, 0 };\n sValue[0] = value & 0xff;\n sValue[1] = (value & 0xff00) >> 8;\n sValue[2] = (value & 0xff0000) >> 16;\n sValue[3] = (value & 0xff000000) >> 24;\n return sValue;\n}\n#endif\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<commit_msg>Read longer integers in one run<commit_after>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/* libcdr\n * Version: MPL 1.1 \/ GPLv2+ \/ LGPLv2+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>\n * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>\n *\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPLv2+\"), or\n * the GNU Lesser General Public License Version 2 or later (the \"LGPLv2+\"),\n * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable\n * instead of those above.\n *\/\n\n#include \"libcdr_utils.h\"\n\n#define CDR_NUM_ELEMENTS(array) sizeof(array)\/sizeof(array[0])\n\nuint8_t libcdr::readU8(WPXInputStream *input, bool \/* bigEndian *\/)\n{\n if (!input || input->atEOS())\n {\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint8_t))\n return *(uint8_t const *)(p);\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nuint16_t libcdr::readU16(WPXInputStream *input, bool bigEndian)\n{\n if (!input || input->atEOS())\n {\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint16_t))\n {\n if (bigEndian)\n return (uint16_t)p[1]|((uint16_t)p[0]<<8);\n return (uint16_t)p[0]|((uint16_t)p[1]<<8);\n }\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nuint32_t libcdr::readU32(WPXInputStream *input, bool bigEndian)\n{\n if (!input || input->atEOS())\n {\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint32_t))\n {\n if (bigEndian)\n return (uint32_t)p[3]|((uint32_t)p[2]<<8)|((uint32_t)p[1]<<16)|((uint32_t)p[0]<<24);\n return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);\n }\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nint32_t libcdr::readS32(WPXInputStream *input, bool bigEndian)\n{\n return (int32_t)readU32(input, bigEndian);\n}\n\nuint64_t libcdr::readU64(WPXInputStream *input, bool bigEndian)\n{\n if (!input || input->atEOS())\n {\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint64_t))\n {\n if (bigEndian)\n return (uint64_t)p[7]|((uint64_t)p[6]<<8)|((uint64_t)p[5]<<16)|((uint64_t)p[4]<<24)|((uint64_t)p[3]<<32)|((uint64_t)p[2]<<40)|((uint64_t)p[1]<<48)|((uint64_t)p[0]<<56);\n return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56);\n }\n CDR_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\ndouble libcdr::readDouble(WPXInputStream *input, bool bigEndian)\n{\n union\n {\n uint64_t u;\n double d;\n } tmpUnion;\n\n tmpUnion.u = readU64(input, bigEndian);\n\n return tmpUnion.d;\n}\n\n#ifdef DEBUG\nconst char *libcdr::toFourCC(unsigned value)\n{\n static char sValue[5] = { 0, 0, 0, 0, 0 };\n sValue[0] = value & 0xff;\n sValue[1] = (value & 0xff00) >> 8;\n sValue[2] = (value & 0xff0000) >> 16;\n sValue[3] = (value & 0xff000000) >> 24;\n return sValue;\n}\n#endif\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/** \\file\n * Implements zero-cost abstractions for the getenv(3) facilities.\n *\/\n\n#ifndef _POWERDXX_SYS_ENV_HPP_\n#define _POWERDXX_SYS_ENV_HPP_\n\n#include \"error.hpp\" \/* sys::sc_error *\/\n\n#include <cstdlib> \/* getenv(), setenv() etc. *\/\n\nnamespace sys {\n\n\/**\n * Provides wrappers around the getenv() family of functions.\n *\/\nnamespace env {\n\n\/**\n * The domain error type.\n *\/\nstruct error {};\n\n\/**\n * A reference type refering to an environment variable.\n *\n * To avoid issues with the lifetime of the name string this is not\n * copy constructible or assignable.\n *\/\nclass Var {\n\tprivate:\n\t\/**\n\t * A pointer to the variable name.\n\t *\/\n\tchar const * const name;\n\n\tpublic:\n\t\/**\n\t * Construct an environment variable reference.\n\t *\n\t * @tparam Size\n\t *\tThe size of the name buffer\n\t * @param name\n\t *\tThe name of the environment variable\n\t *\/\n\ttemplate <size_t Size>\n\tVar(char const (& name)[Size]) : name{name} {}\n\n\t\/**\n\t * Do not permit copy construction.\n\t *\/\n\tVar(Var const &) = delete;\n\n\t\/**\n\t * Do not permit copy assignment.\n\t *\/\n\tVar & operator =(Var const &) = delete;\n\n\t\/**\n\t * Retrieve the value of the environment variable.\n\t *\n\t * @return\n\t *\tA pointer to the character array with the variable value\n\t * @retval nullptr\n\t *\tThe variable does not exist\n\t *\/\n\toperator char const *() const {\n\t\treturn getenv(this->name);\n\t}\n\n\t\/**\n\t * Assign a new value to the environment variable.\n\t *\n\t * Deletes the variable if nullptr is assigned.\n\t *\n\t * @param assign\n\t *\tThe new value\n\t * @return\n\t *\tA self-reference\n\t * @throws sc_error<error>{EINVAL}\n\t *\tInvalid variable name\n\t * @throws sc_error<error>{ENOMEM}\n\t *\tFailed to allocate memory when updating the environment\n\t *\/\n\tVar & operator =(char const * const assign) {\n\t\tauto const result =\n\t\t assign\n\t\t ? setenv(this->name, assign, 1)\n\t\t : unsetenv(this->name);\n\t\tif (0 != result) {\n\t\t\tthrow sc_error<error>{errno};\n\t\t}\n\t\treturn *this;\n\t}\n\n\t\/**\n\t * Explicitly deletes the environment variable.\n\t *\n\t * @return\n\t *\tA self-reference\n\t * @throws sc_error<error>{EINVAL}\n\t *\tInvalid variable name\n\t * @throws sc_error<error>{ENOMEM}\n\t *\tFailed to allocate memory when updating the environment\n\t *\/\n\tVar & erase() {\n\t\treturn *this = nullptr;\n\t}\n\n\t\/**\n\t * Explicitly retrieve the value as a character array.\n\t *\n\t * @return\n\t *\tA pointer to the character array with the variable value\n\t * @retval nullptr\n\t *\tThe variable does not exist\n\t *\/\n\tchar const * c_str() const {\n\t\treturn *this;\n\t}\n\n\t\/**\n\t * Explicitly retrieve the value as a std::string.\n\t *\n\t * Returns an empty string if the variable does not exist.\n\t * Use c_str() to distinguish between an empty string and\n\t * an inexistant variable.\n\t *\n\t * @return\n\t *\tA string containing the variable value\n\t *\/\n\tstd::string str() const {\n\t\tauto const result = c_str();\n\t\treturn {result ? result : \"\"};\n\t}\n};\n\n\/**\n * A singleton class providing access to environment variables.\n *\/\nstruct Vars {\n\t\/**\n\t * Access environment variable by name.\n\t *\n\t * @tparam T\n\t *\tThe name argument type\n\t * @param name\n\t *\tThe name of the variable by reference\n\t *\/\n\ttemplate <typename T>\n\tVar const operator [](T const & name) const {\n\t\treturn {name};\n\t}\n\n\t\/**\n\t * Access environment variable by name.\n\t *\n\t * @tparam T\n\t *\tThe name argument type\n\t * @param name\n\t *\tThe name of the variable by reference\n\t *\/\n\ttemplate <typename T>\n\tVar operator [](T const & name) {\n\t\treturn {name};\n\t}\n} vars; \/**< Singleton providing access to environment variables. *\/\n\n} \/* namespace env *\/\n\n} \/* namespace sys *\/\n\n#endif \/* _POWERDXX_SYS_ENV_HPP_ *\/\n<commit_msg>Remove obsolete method<commit_after>\/** \\file\n * Implements zero-cost abstractions for the getenv(3) facilities.\n *\/\n\n#ifndef _POWERDXX_SYS_ENV_HPP_\n#define _POWERDXX_SYS_ENV_HPP_\n\n#include \"error.hpp\" \/* sys::sc_error *\/\n\n#include <cstdlib> \/* getenv(), setenv() etc. *\/\n\nnamespace sys {\n\n\/**\n * Provides wrappers around the getenv() family of functions.\n *\/\nnamespace env {\n\n\/**\n * The domain error type.\n *\/\nstruct error {};\n\n\/**\n * A reference type refering to an environment variable.\n *\n * To avoid issues with the lifetime of the name string this is not\n * copy constructible or assignable.\n *\/\nclass Var {\n\tprivate:\n\t\/**\n\t * A pointer to the variable name.\n\t *\/\n\tchar const * const name;\n\n\tpublic:\n\t\/**\n\t * Construct an environment variable reference.\n\t *\n\t * @tparam Size\n\t *\tThe size of the name buffer\n\t * @param name\n\t *\tThe name of the environment variable\n\t *\/\n\ttemplate <size_t Size>\n\tVar(char const (& name)[Size]) : name{name} {}\n\n\t\/**\n\t * Do not permit copy construction.\n\t *\/\n\tVar(Var const &) = delete;\n\n\t\/**\n\t * Do not permit copy assignment.\n\t *\/\n\tVar & operator =(Var const &) = delete;\n\n\t\/**\n\t * Retrieve the value of the environment variable.\n\t *\n\t * @return\n\t *\tA pointer to the character array with the variable value\n\t * @retval nullptr\n\t *\tThe variable does not exist\n\t *\/\n\toperator char const *() const {\n\t\treturn getenv(this->name);\n\t}\n\n\t\/**\n\t * Assign a new value to the environment variable.\n\t *\n\t * Deletes the variable if nullptr is assigned.\n\t *\n\t * @param assign\n\t *\tThe new value\n\t * @return\n\t *\tA self-reference\n\t * @throws sc_error<error>{EINVAL}\n\t *\tInvalid variable name\n\t * @throws sc_error<error>{ENOMEM}\n\t *\tFailed to allocate memory when updating the environment\n\t *\/\n\tVar & operator =(char const * const assign) {\n\t\tauto const result =\n\t\t assign\n\t\t ? setenv(this->name, assign, 1)\n\t\t : unsetenv(this->name);\n\t\tif (0 != result) {\n\t\t\tthrow sc_error<error>{errno};\n\t\t}\n\t\treturn *this;\n\t}\n\n\t\/**\n\t * Explicitly deletes the environment variable.\n\t *\n\t * @return\n\t *\tA self-reference\n\t * @throws sc_error<error>{EINVAL}\n\t *\tInvalid variable name\n\t * @throws sc_error<error>{ENOMEM}\n\t *\tFailed to allocate memory when updating the environment\n\t *\/\n\tVar & erase() {\n\t\treturn *this = nullptr;\n\t}\n\n\t\/**\n\t * Explicitly retrieve the value as a character array.\n\t *\n\t * @return\n\t *\tA pointer to the character array with the variable value\n\t * @retval nullptr\n\t *\tThe variable does not exist\n\t *\/\n\tchar const * c_str() const {\n\t\treturn *this;\n\t}\n};\n\n\/**\n * A singleton class providing access to environment variables.\n *\/\nstruct Vars {\n\t\/**\n\t * Access environment variable by name.\n\t *\n\t * @tparam T\n\t *\tThe name argument type\n\t * @param name\n\t *\tThe name of the variable by reference\n\t *\/\n\ttemplate <typename T>\n\tVar const operator [](T const & name) const {\n\t\treturn {name};\n\t}\n\n\t\/**\n\t * Access environment variable by name.\n\t *\n\t * @tparam T\n\t *\tThe name argument type\n\t * @param name\n\t *\tThe name of the variable by reference\n\t *\/\n\ttemplate <typename T>\n\tVar operator [](T const & name) {\n\t\treturn {name};\n\t}\n} vars; \/**< Singleton providing access to environment variables. *\/\n\n} \/* namespace env *\/\n\n} \/* namespace sys *\/\n\n#endif \/* _POWERDXX_SYS_ENV_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"attributes.h\"\n#include \"ui_attributes.h\"\n\nAttributes::Attributes(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::Attributes)\n{\n ui->setupUi(this);\n}\n\nAttributes::~Attributes()\n{\n delete ui;\n}\n\nvoid Attributes::setPlayer(Player player) {\n this->player = player;\n ui->nameLabel->setText(this->player.getName());\n}\n<commit_msg>Delete attributes.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fs\/vfs.hpp>\n#include <common.cxx>\n\nusing namespace std::string_literals;\n\nextern lest::tests & specification();\n\nclass Person {\npublic:\n explicit Person(std::string name, int age) : name_ {name}, age_ {age} {};\n bool isBjarne() const { return (name_ == \"Bjarne\") ? true : false; }\nprivate:\n std::string name_;\n int age_;\n};\n\nCASE(\"VFS entries can have names\")\n{\n fs::VFS_entry e(\"entry\", \"description\");\n EXPECT(e.name() == \"entry\");\n}\n\nCASE(\"VFS entries can have descriptions\")\n{\n fs::VFS_entry e(\"entry\", \"description\");\n EXPECT(e.desc() == \"description\");\n}\n\nCASE(\"VFS entries can return type info as string\")\n{\n fs::VFS_entry e(\"entry\", \"description\");\n auto info {e.type_name()};\n EXPECT(info.length() > 0);\n EXPECT(info == \"decltype(nullptr)\");\n}\n\nCASE(\"VFS entries can return their number of children\")\n{\n fs::VFS_entry e(\"entry\", \"description\");\n EXPECT(e.child_count() == 0);\n}\n\nCASE(\"VFS entries can contain arbitrary objects\")\n{\n Person p {\"Bjarne\", 65};\n fs::VFS_entry e(p, \"creator\", \"duh\");\n auto info = e.type_name();\n EXPECT(info != \"decltype(nullptr)\");\n EXPECT(info == \"Person\");\n Person bjarne = e.obj<Person>();\n EXPECT(bjarne.isBjarne() == true);\n EXPECT_THROWS(e.obj<std::string>());\n}\n\nCASE(\"VFS can mount entries in a tree\")\n{\n \/\/ tree is initially empty\n EXPECT(fs::VFS::root().child_count() == 0);\n\n \/\/ mount a char\n char a {'a'};\n fs::mount(\"\/mnt\/chars\/a\", a, \"the letter a\");\n EXPECT(fs::VFS::root().child_count() == 1);\n\n \/\/ cannot mount if already occupied\n char b {'b'};\n EXPECT_THROWS(fs::mount(\"\/mnt\/chars\/a\", b, \"the letter b\"));\n EXPECT_NO_THROW(fs::mount(\"\/mnt\/chars\/b\", b, \"the letter c\"));\n\n \/\/ mount another\n char c {'c'};\n EXPECT_NO_THROW(fs::mount(\"\/mnt\/chars\/c\", c, \"the letter c\"));\n}\n<commit_msg>test: added missing license header to vfs unit test<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\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 <iostream>\n#include <fs\/vfs.hpp>\n#include <common.cxx>\n\nusing namespace std::string_literals;\n\nextern lest::tests & specification();\n\nclass Person {\npublic:\n explicit Person(std::string name, int age) : name_ {name}, age_ {age} {};\n bool isBjarne() const { return (name_ == \"Bjarne\") ? true : false; }\nprivate:\n std::string name_;\n int age_;\n};\n\nCASE(\"VFS entries can have names\")\n{\n fs::VFS_entry e(\"entry\", \"description\");\n EXPECT(e.name() == \"entry\");\n}\n\nCASE(\"VFS entries can have descriptions\")\n{\n fs::VFS_entry e(\"entry\", \"description\");\n EXPECT(e.desc() == \"description\");\n}\n\nCASE(\"VFS entries can return type info as string\")\n{\n fs::VFS_entry e(\"entry\", \"description\");\n auto info {e.type_name()};\n EXPECT(info.length() > 0);\n EXPECT(info == \"decltype(nullptr)\");\n}\n\nCASE(\"VFS entries can return their number of children\")\n{\n fs::VFS_entry e(\"entry\", \"description\");\n EXPECT(e.child_count() == 0);\n}\n\nCASE(\"VFS entries can contain arbitrary objects\")\n{\n Person p {\"Bjarne\", 65};\n fs::VFS_entry e(p, \"creator\", \"duh\");\n auto info = e.type_name();\n EXPECT(info != \"decltype(nullptr)\");\n EXPECT(info == \"Person\");\n Person bjarne = e.obj<Person>();\n EXPECT(bjarne.isBjarne() == true);\n EXPECT_THROWS(e.obj<std::string>());\n}\n\nCASE(\"VFS can mount entries in a tree\")\n{\n \/\/ tree is initially empty\n EXPECT(fs::VFS::root().child_count() == 0);\n\n \/\/ mount a char\n char a {'a'};\n fs::mount(\"\/mnt\/chars\/a\", a, \"the letter a\");\n EXPECT(fs::VFS::root().child_count() == 1);\n\n \/\/ cannot mount if already occupied\n char b {'b'};\n EXPECT_THROWS(fs::mount(\"\/mnt\/chars\/a\", b, \"the letter b\"));\n EXPECT_NO_THROW(fs::mount(\"\/mnt\/chars\/b\", b, \"the letter c\"));\n\n \/\/ mount another\n char c {'c'};\n EXPECT_NO_THROW(fs::mount(\"\/mnt\/chars\/c\", c, \"the letter c\"));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680)\n#define XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include <XercesPlatformSupport\/XercesPlatformSupportDefinitions.hpp>\n\n\n\n#include <cstdio>\n#include <vector>\n\n\n\n\/\/ Base class header file.\n#include <PlatformSupport\/TextOutputStream.hpp>\n\n\n\n#include <XercesPlatformSupport\/XercesPlatformSupportException.hpp>\n\n\n\n\/\/ A base class for all text output streams.\nclass XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStream : public TextOutputStream\n{\npublic :\n\n virtual\n\t~XercesTextOutputStream();\n\n\t\/\/ These interfaces are inherited from TextOutputStream...\n\n virtual void\n\tflush();\n\n virtual void\n\twrite(char\ttheChar);\n\n virtual void\n\twrite(XalanDOMChar\ttheChar);\n\n virtual void\n\twrite(const char*\ttheBuffer);\n\n virtual void\n\twrite(const XalanDOMChar*\ttheBuffer);\n\n virtual void\n\twrite(\n\t\t\tconst char*\t\ttheBuffer,\n\t\t\tunsigned long\ttheBufferLength);\n\n virtual void\n\twrite(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tunsigned long\t\t\ttheBufferLength);\n\n\tenum\n\t{\n\t\teDefaultBufferSize = 512\n\t};\n\n\ttypedef std::vector<XalanDOMChar>\tBufferType;\n\n\tvirtual void\n\tsetBufferSize(BufferType::size_type\t\ttheBufferSize);\n\nprotected:\n\n\texplicit\n XercesTextOutputStream(BufferType::size_type\ttheBufferSize = eDefaultBufferSize);\n\n\tvirtual void\n\twriteData(const char*\t\ttheBuffer,\n\t\t\t unsigned long\t\ttheBufferLength) = 0;\n\n\tvirtual void\n\tdoFlush() = 0;\n\nprivate:\n\n \/\/ These are not implemented...\n XercesTextOutputStream(const XercesTextOutputStream&);\n\n XercesTextOutputStream&\n\toperator=(const XercesTextOutputStream&);\n\n\t\/\/ Utility functions...\n\tvoid\n\tflushBuffer();\n\n\tvoid\n\tdoWrite(const XalanDOMChar*\t\ttheBuffer);\n\n\tBufferType\t\t\t\tm_buffer;\n\n\tBufferType::size_type\tm_bufferSize;\n};\n\n\n\nclass XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStreamException : public XercesPlatformSupportException\n{\npublic:\n\n\tvirtual\n\t~XercesTextOutputStreamException();\n\nprotected:\n\n\tXercesTextOutputStreamException(\n\t\tconst DOMString&\ttheMessage,\n\t\tconst DOMString&\ttheType);\n};\n\n\n\n#endif\t\/\/ TEXTFILEOUTPUTSTREAM_HEADER_GUARD_1357924680\n<commit_msg>Added comment.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680)\n#define XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include <XercesPlatformSupport\/XercesPlatformSupportDefinitions.hpp>\n\n\n\n#include <cstdio>\n#include <vector>\n\n\n\n\/\/ Base class header file.\n#include <PlatformSupport\/TextOutputStream.hpp>\n\n\n\n#include <XercesPlatformSupport\/XercesPlatformSupportException.hpp>\n\n\n\n\/\/ A base class for all text output streams.\nclass XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStream : public TextOutputStream\n{\npublic :\n\n virtual\n\t~XercesTextOutputStream();\n\n\t\/\/ These interfaces are inherited from TextOutputStream...\n\n virtual void\n\tflush();\n\n virtual void\n\twrite(char\ttheChar);\n\n virtual void\n\twrite(XalanDOMChar\ttheChar);\n\n virtual void\n\twrite(const char*\ttheBuffer);\n\n virtual void\n\twrite(const XalanDOMChar*\ttheBuffer);\n\n virtual void\n\twrite(\n\t\t\tconst char*\t\ttheBuffer,\n\t\t\tunsigned long\ttheBufferLength);\n\n virtual void\n\twrite(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tunsigned long\t\t\ttheBufferLength);\n\n\tenum\n\t{\n\t\teDefaultBufferSize = 512\n\t};\n\n\ttypedef std::vector<XalanDOMChar>\tBufferType;\n\n\tvirtual void\n\tsetBufferSize(BufferType::size_type\t\ttheBufferSize);\n\nprotected:\n\n\t\/**\n\t * Constructor.\n\t *\n\t * @param theBufferSize The initial size of the buffer.\n\t *\/\n\texplicit\n XercesTextOutputStream(BufferType::size_type\ttheBufferSize = eDefaultBufferSize);\n\n\tvirtual void\n\twriteData(const char*\t\ttheBuffer,\n\t\t\t unsigned long\t\ttheBufferLength) = 0;\n\n\tvirtual void\n\tdoFlush() = 0;\n\nprivate:\n\n \/\/ These are not implemented...\n XercesTextOutputStream(const XercesTextOutputStream&);\n\n XercesTextOutputStream&\n\toperator=(const XercesTextOutputStream&);\n\n\t\/\/ Utility functions...\n\tvoid\n\tflushBuffer();\n\n\tvoid\n\tdoWrite(const XalanDOMChar*\t\ttheBuffer);\n\n\tBufferType\t\t\t\tm_buffer;\n\n\tBufferType::size_type\tm_bufferSize;\n};\n\n\n\nclass XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStreamException : public XercesPlatformSupportException\n{\npublic:\n\n\tvirtual\n\t~XercesTextOutputStreamException();\n\nprotected:\n\n\tXercesTextOutputStreamException(\n\t\tconst DOMString&\ttheMessage,\n\t\tconst DOMString&\ttheType);\n};\n\n\n\n#endif\t\/\/ TEXTFILEOUTPUTSTREAM_HEADER_GUARD_1357924680\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/vespalib\/testkit\/testapp.h>\n#include <vespa\/searchlib\/bitcompression\/compression.h>\n#include <vespa\/searchlib\/bitcompression\/countcompression.h>\n#include <vespa\/searchlib\/bitcompression\/pagedict4.h>\n#include <vespa\/searchlib\/test\/diskindex\/threelevelcountbuffers.h>\n#include <vespa\/searchlib\/test\/diskindex\/pagedict4_mem_writer.h>\n#include <vespa\/searchlib\/test\/diskindex\/pagedict4_mem_seq_reader.h>\n#include <vespa\/searchlib\/index\/postinglistcounts.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\"pagedict4_hugeword_cornercase_test\");\n\nusing search::index::PostingListCounts;\nusing search::ComprFileWriteContext;\n\nconstexpr uint32_t minChunkDocs = 262144;\nconstexpr uint32_t numWordIds = 65536;\n\nstruct BitBuffer\n{\n using EC = search::bitcompression::PostingListCountFileEncodeContext;\n\n EC e;\n ComprFileWriteContext wc;\n\n BitBuffer()\n : e(),\n wc(e)\n {\n e._minChunkDocs = minChunkDocs;\n e._numWordIds = numWordIds;\n wc.allocComprBuf();\n e.setWriteContext(&wc);\n e.setupWrite(wc);\n assert(e.getWriteOffset() == 0);\n }\n\n void clear() { e.setupWrite(wc); }\n\n uint64_t getSize(const PostingListCounts &counts)\n {\n clear();\n e.writeCounts(counts);\n return e.getWriteOffset();\n }\n\n ~BitBuffer() = default;\n};\n\nvoid addSegment(PostingListCounts &counts)\n{\n PostingListCounts::Segment lastseg = counts._segments.back();\n PostingListCounts::Segment fillseg;\n fillseg._bitLength = 4000000;\n fillseg._numDocs = minChunkDocs;\n fillseg._lastDoc = minChunkDocs;\n counts._bitLength += fillseg._bitLength;\n counts._numDocs += fillseg._numDocs;\n counts._segments.back() = fillseg;\n uint32_t lastDoc = counts._segments.size() * fillseg._numDocs;\n counts._segments.back()._lastDoc = lastDoc;\n counts._segments.push_back(lastseg);\n counts._segments.back()._lastDoc = lastDoc + lastseg._numDocs;\n}\n\nPostingListCounts makeBaseCounts()\n{\n PostingListCounts counts;\n PostingListCounts::Segment lastseg;\n lastseg._bitLength = 100;\n lastseg._numDocs = 10;\n lastseg._lastDoc = 10;\n counts._bitLength = lastseg._bitLength;\n counts._numDocs = lastseg._numDocs;\n counts._segments.push_back(lastseg);\n addSegment(counts);\n return counts;\n}\n\nPostingListCounts makeSegmentedCounts(uint32_t segments)\n{\n PostingListCounts counts = makeBaseCounts();\n while (counts._segments.size() < segments) {\n addSegment(counts);\n }\n return counts;\n}\n\nuint32_t\ncalcSegments(uint32_t maxLen)\n{\n BitBuffer bb;\n PostingListCounts counts = makeBaseCounts();\n uint32_t len = bb.getSize(counts);\n unsigned int i = 0;\n while (len <= maxLen) {\n addSegment(counts);\n ++i;\n len = bb.getSize(counts);\n }\n return counts._segments.size() - 1;\n}\n\nPostingListCounts makeCounts(uint32_t wantLen)\n{\n BitBuffer bb;\n uint32_t segments = calcSegments(wantLen);\n PostingListCounts counts = makeSegmentedCounts(segments);\n PostingListCounts counts2 = makeSegmentedCounts(segments - 1);\n uint32_t len = bb.getSize(counts);\n uint32_t len2 = bb.getSize(counts2);\n for (unsigned int i = 1; i + 2 < counts._segments.size(); ++i) {\n counts._bitLength += counts._segments[0]._bitLength;\n counts._segments[i]._bitLength += counts._segments[0]._bitLength;\n counts2._bitLength += counts2._segments[0]._bitLength;\n counts2._segments[i]._bitLength += counts2._segments[0]._bitLength;\n len = bb.getSize(counts);\n len2 = bb.getSize(counts2);\n if (len == wantLen) {\n return counts;\n }\n if (len2 == wantLen) {\n return counts2;\n }\n }\n LOG(info, \"Could not calculate counts with wanted compressed length\");\n abort();\n}\n\nusing StartOffset = search::bitcompression::PageDict4StartOffset;\nusing Writer = search::diskindex::test::PageDict4MemWriter;\nusing SeqReader = search::diskindex::test::PageDict4MemSeqReader;\n\nvoid testPageSizedCounts()\n{\n uint32_t pageBitSize = 32768;\n uint32_t startBits = 15 * 3 + 12;\n\n uint32_t ssPad = 64;\n uint32_t spPad = 64;\n uint32_t pPad = 64;\n Writer w(minChunkDocs, numWordIds, ssPad, spPad, pPad);\n PostingListCounts baseCounts = makeBaseCounts();\n PostingListCounts largeCounts = makeCounts(pageBitSize - startBits);\n w.addCounts(\"a\", baseCounts);\n w.addCounts(\"b\", baseCounts);\n w.addCounts(\"c\", largeCounts);\n w.addCounts(\"d\", baseCounts);\n w.addCounts(\"e\", baseCounts);\n w.flush();\n\n SeqReader r(minChunkDocs, numWordIds, w._buffers);\n\n uint64_t checkWordNum = 0;\n PostingListCounts counts;\n for (uint64_t wordNum = 1; wordNum < 7; ++wordNum) {\n vespalib::string word;\n counts.clear();\n r.readCounts(word, checkWordNum, counts);\n if (wordNum < 6) {\n EXPECT_EQUAL(checkWordNum, wordNum);\n if (wordNum == 3) {\n EXPECT_TRUE(counts == largeCounts);\n } else {\n EXPECT_TRUE(counts == baseCounts);\n }\n } else {\n EXPECT_GREATER(checkWordNum, 100u);\n }\n }\n}\n\n\n\nTEST(\"require that counts exactly filling dictionary page works\")\n{\n testPageSizedCounts();\n}\n\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<commit_msg>Add comments. Use more descriptive variable names.<commit_after>\/\/ Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/vespalib\/testkit\/testapp.h>\n#include <vespa\/searchlib\/bitcompression\/compression.h>\n#include <vespa\/searchlib\/bitcompression\/countcompression.h>\n#include <vespa\/searchlib\/bitcompression\/pagedict4.h>\n#include <vespa\/searchlib\/test\/diskindex\/threelevelcountbuffers.h>\n#include <vespa\/searchlib\/test\/diskindex\/pagedict4_mem_writer.h>\n#include <vespa\/searchlib\/test\/diskindex\/pagedict4_mem_seq_reader.h>\n#include <vespa\/searchlib\/index\/postinglistcounts.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\"pagedict4_hugeword_cornercase_test\");\n\nusing search::index::PostingListCounts;\nusing search::ComprFileWriteContext;\n\nconstexpr uint32_t minChunkDocs = 262144;\nconstexpr uint32_t numWordIds = 65536;\n\nstruct BitBuffer\n{\n using EC = search::bitcompression::PostingListCountFileEncodeContext;\n\n EC encodeCtx;\n ComprFileWriteContext writeCtx;\n\n BitBuffer()\n : encodeCtx(),\n writeCtx(encodeCtx)\n {\n encodeCtx._minChunkDocs = minChunkDocs;\n encodeCtx._numWordIds = numWordIds;\n writeCtx.allocComprBuf();\n encodeCtx.setWriteContext(&writeCtx);\n encodeCtx.setupWrite(writeCtx);\n assert(encodeCtx.getWriteOffset() == 0);\n }\n\n void clear() { encodeCtx.setupWrite(writeCtx); }\n\n uint64_t getSize(const PostingListCounts &counts)\n {\n clear();\n encodeCtx.writeCounts(counts);\n return encodeCtx.getWriteOffset();\n }\n\n ~BitBuffer() = default;\n};\n\nvoid addSegment(PostingListCounts &counts)\n{\n PostingListCounts::Segment lastseg = counts._segments.back();\n PostingListCounts::Segment fillseg;\n fillseg._bitLength = 4000000;\n fillseg._numDocs = minChunkDocs;\n fillseg._lastDoc = minChunkDocs;\n counts._bitLength += fillseg._bitLength;\n counts._numDocs += fillseg._numDocs;\n counts._segments.back() = fillseg;\n uint32_t lastDoc = counts._segments.size() * fillseg._numDocs;\n counts._segments.back()._lastDoc = lastDoc;\n counts._segments.push_back(lastseg);\n counts._segments.back()._lastDoc = lastDoc + lastseg._numDocs;\n}\n\nPostingListCounts makeBaseCounts()\n{\n PostingListCounts counts;\n PostingListCounts::Segment lastseg;\n lastseg._bitLength = 100;\n lastseg._numDocs = 10;\n lastseg._lastDoc = 10;\n counts._bitLength = lastseg._bitLength;\n counts._numDocs = lastseg._numDocs;\n counts._segments.push_back(lastseg);\n addSegment(counts);\n return counts;\n}\n\nPostingListCounts makeSegmentedCounts(uint32_t segments)\n{\n PostingListCounts counts = makeBaseCounts();\n while (counts._segments.size() < segments) {\n addSegment(counts);\n }\n return counts;\n}\n\nuint32_t\ncalcSegments(uint32_t maxLen)\n{\n BitBuffer bb;\n PostingListCounts counts = makeBaseCounts();\n uint32_t len = bb.getSize(counts);\n unsigned int i = 0;\n while (len <= maxLen) {\n addSegment(counts);\n ++i;\n len = bb.getSize(counts);\n }\n return counts._segments.size() - 1;\n}\n\n\/*\n * Calculate posting list counts that compresses to wantLen bits.\n *\/\nPostingListCounts makeCounts(uint32_t wantLen)\n{\n BitBuffer bb;\n uint32_t segments = calcSegments(wantLen);\n PostingListCounts counts = makeSegmentedCounts(segments);\n PostingListCounts counts2 = makeSegmentedCounts(segments - 1);\n uint32_t len = bb.getSize(counts);\n uint32_t len2 = bb.getSize(counts2);\n for (uint32_t i = 1; i + 2 < counts._segments.size(); ++i) {\n counts._bitLength += counts._segments[0]._bitLength;\n counts._segments[i]._bitLength += counts._segments[0]._bitLength;\n counts2._bitLength += counts2._segments[0]._bitLength;\n counts2._segments[i]._bitLength += counts2._segments[0]._bitLength;\n len = bb.getSize(counts);\n len2 = bb.getSize(counts2);\n if (len == wantLen) {\n return counts;\n }\n if (len2 == wantLen) {\n return counts2;\n }\n }\n LOG(info, \"Could not calculate counts with wanted compressed length\");\n abort();\n}\n\nusing StartOffset = search::bitcompression::PageDict4StartOffset;\nusing Writer = search::diskindex::test::PageDict4MemWriter;\nusing SeqReader = search::diskindex::test::PageDict4MemSeqReader;\n\n\/*\n * Test corner case where a dictionary page has a single word, and the\n * page header and compressed counts completely fills the page.\n *\/\nvoid testPageSizedCounts()\n{\n uint32_t pageBitSize = 32768;\n uint32_t startBits = 15 * 3 + 12;\n\n uint32_t ssPad = 64;\n uint32_t spPad = 64;\n uint32_t pPad = 64;\n Writer w(minChunkDocs, numWordIds, ssPad, spPad, pPad);\n PostingListCounts baseCounts = makeBaseCounts();\n PostingListCounts largeCounts = makeCounts(pageBitSize - startBits);\n w.addCounts(\"a\", baseCounts);\n w.addCounts(\"b\", baseCounts);\n w.addCounts(\"c\", largeCounts);\n w.addCounts(\"d\", baseCounts);\n w.addCounts(\"e\", baseCounts);\n w.flush();\n\n SeqReader r(minChunkDocs, numWordIds, w._buffers);\n\n uint64_t checkWordNum = 0;\n PostingListCounts counts;\n for (uint64_t wordNum = 1; wordNum < 7; ++wordNum) {\n vespalib::string word;\n counts.clear();\n r.readCounts(word, checkWordNum, counts);\n if (wordNum < 6) {\n EXPECT_EQUAL(checkWordNum, wordNum);\n if (wordNum == 3) {\n EXPECT_TRUE(counts == largeCounts);\n } else {\n EXPECT_TRUE(counts == baseCounts);\n }\n } else {\n EXPECT_GREATER(checkWordNum, 100u);\n }\n }\n}\n\n\n\nTEST(\"require that counts exactly filling dictionary page works\")\n{\n testPageSizedCounts();\n}\n\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<|endoftext|>"} {"text":"<commit_before>\/\/ FRAGMENT(main)\n#include <iostream>\n#include <seqan\/align.h>\n\nusing namespace seqan;\n\nint main()\n{\n\ttypedef String<Dna>\t\t\tTSequence;\t\/\/ sequence type\n\ttypedef Align<TSequence,ArrayGaps>\tTAlign;\t\t\/\/ align type\n\ttypedef Row<TAlign>::Type\t\tTRow;\n\ttypedef Iterator<TRow>::Type\t\tTIterator;\n\n\/\/ FRAGMENT(init)\n\tTSequence seq1 = \"acgtacgtact\";\n\tTSequence seq2 = \"actactacgt\";\n\n\tTAlign align;\n\tresize(rows(align), 2); \n\tassignSource(row(align,0),seq1);\n\tassignSource(row(align,1),seq2);\n\n\/\/ FRAGMENT(alignment)\n\tint score = globalAlignment(align,Score<int>(1,-1,-1,-1), Hirschberg());\n\t::std::cout << \"Score = \" << score << ::std::endl;\n\t::std::cout << align;\n\t\n\/\/FRAGMENT(iterate)\n\tfor(unsigned i = 0; i < length(rows(align)); ++i)\n\t{\n\t\tTIterator it = begin(row(align,i));\n\t\tTIterator itEnd = end(row(align,i));\n\t\tunsigned pos = 0;\n\t\tstd::cout << \"Row \" << i << \" contains gaps at positions: \";\n\t\tstd::cout << std::endl;\n\t\twhile (it != itEnd)\n\t\t{\n\t\t\tif(isGap(it))\n \t\t\t\tstd::cout << pos << std::endl;\n\t\t\t++it;\n\t\t\t++pos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n<commit_msg>Fixed for possible leading or trailing gaps.<commit_after>\/\/ FRAGMENT(main)\n#include <iostream>\n#include <seqan\/align.h>\n\nusing namespace seqan;\n\nint main()\n{\n\ttypedef String<Dna>\t\t\tTSequence;\t\/\/ sequence type\n\ttypedef Align<TSequence,ArrayGaps>\tTAlign;\t\t\/\/ align type\n\ttypedef Row<TAlign>::Type\t\tTRow;\n\ttypedef Iterator<TRow>::Type\t\tTIterator;\n\n\/\/ FRAGMENT(init)\n\tTSequence seq1 = \"acgtacgtact\";\n\tTSequence seq2 = \"actactacgt\";\n\n\tTAlign align;\n\tresize(rows(align), 2); \n\tassignSource(row(align,0),seq1);\n\tassignSource(row(align,1),seq2);\n\n\/\/ FRAGMENT(alignment)\n\tint score = globalAlignment(align,Score<int>(1,-1,-1,-1), Hirschberg());\n\t::std::cout << \"Score = \" << score << ::std::endl;\n\t::std::cout << align;\n\t\n\/\/FRAGMENT(iterate)\n\tunsigned aliLength = _max(length(row(align, 0)), length(row(align, 1)));\n\tfor(unsigned i = 0; i < length(rows(align)); ++i)\n\t{\n\t\tTIterator it = iter(row(align,i), 0);\n\t\tTIterator itEnd = iter(row(align,i), aliLength);\n\t\tunsigned pos = 0;\n\t\tstd::cout << \"Row \" << i << \" contains gaps at positions: \";\n\t\tstd::cout << std::endl;\n\t\twhile (it != itEnd)\n\t\t{\n\t\t\tif(isGap(it))\n \t\t\t\tstd::cout << pos << std::endl;\n\t\t\t++it;\n\t\t\t++pos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"cinder\/app\/App.h\"\n#include \"cinder\/app\/RendererGl.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/Shader.h\"\n\nusing namespace ci;\nusing namespace ci::app;\n\nclass BasicApp : public App {\npublic:\n void draw() override;\n};\n\nvoid BasicApp::draw()\n{\n gl::clear();\n\n\tgl::enableDepthRead();\n\tgl::enableDepthWrite();\n\n\tCameraPersp cam;\n\tcam.lookAt(vec3(3, 4.5, 4.5), vec3(0, 1, 0));\n\tgl::setMatrices(cam);\n\n\tauto lambert = gl::ShaderDef().lambert().color();\n\tauto shader = gl::getStockShader(lambert);\n\tshader->bind();\n\n\tint numSpheres = 64;\n\tfloat maxAngle = M_PI * 7;\n\tfloat spiralRadius = 1;\n\tfloat height = 3;\n\tfloat anim = getElapsedFrames() \/ 30.0f;\n\n\tfor (int s = 0; s < numSpheres; ++s)\n\t{\n\t\tfloat rel = s \/ (float)numSpheres;\n\t\tfloat angle = rel * maxAngle;\n\t\tfloat y = fabs(cos(rel * M_PI + anim));\n\t\tfloat r = rel * spiralRadius;\n\t\tvec3 offset(r * cos(angle), y, r * sin(angle));\n\n\t\tgl::pushModelMatrix();\n\t\tgl::translate(offset);\n\t\tgl::scale(vec3(0.05f, y, 0.05f));\n\t\tgl::color(Color(CM_HSV, rel, 1, 1));\n\t\tgl::drawCube(vec3(), vec3(1));\n\t\tgl::popModelMatrix();\n\t}\n}\n\nCINDER_APP( BasicApp, RendererGl )\n<commit_msg>Complete part 3<commit_after>#include \"cinder\/app\/App.h\"\n#include \"cinder\/app\/RendererGl.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/Shader.h\"\n#include \"cinder\/Easing.h\"\n\nusing namespace ci;\nusing namespace ci::app;\n\nclass BasicApp : public App {\npublic:\n\tvoid setup() override;\n void draw() override;\n\n\tstatic const int NUM_SLICES = 4;\n\n\tCameraPersp mCam;\n\tgl::BatchRef mSlices[NUM_SLICES];\n};\n\nvoid BasicApp::setup()\n{\n\tauto lambert = gl::ShaderDef().lambert().color();\n\tgl::GlslProgRef shader = gl::getStockShader(lambert);\n\t\n\tfor (int i = 0; i < NUM_SLICES; ++i)\n\t{\n\t\tfloat rel = i \/ (float)NUM_SLICES;\n\t\tfloat sliceHeight = 1.0f \/ NUM_SLICES;\n\t\tauto slice = geom::Cube().size(1, sliceHeight, 1);\n\t\tauto trans = geom::Translate(0, rel, 0);\n\t\tauto color = geom::Constant(\n\t\t\tgeom::COLOR,\n\t\t\tColor(CM_HSV, rel, 1, 1));\n\t\tmSlices[i] = gl::Batch::create(slice >> trans >> color, shader);\n\t}\n\n\tmCam.lookAt(vec3(2, 3, 2), vec3(0, 0.5f, 0));\n}\n\nvoid BasicApp::draw()\n{\n gl::clear();\n\n\tgl::enableDepthRead();\n\tgl::enableDepthWrite();\n\n\tgl::setMatrices(mCam);\n\n\tconst float delay = 0.25f;\n\tconst float rotationTime = 1.5f;\n\tconst float rotationOffset = 0.1f;\n\tconst float totalTime = delay + rotationTime + NUM_SLICES * rotationOffset;\n\n\t\/\/ loop every `totalTime` seconds\n\tfloat time = fmod(getElapsedFrames() \/ 30.0f, totalTime);\n\n\tfor (int i = 0; i < NUM_SLICES; ++i)\n\t{\n\t\t\/\/ animates from 0 to 1\n\t\tfloat rotation = 0;\n\n\t\t\/\/ when does the slice begin rotating\n\t\tfloat startTime = i * rotationOffset;\n\t\tfloat endTime = startTime + rotationTime;\n\t\tif (time > startTime && time < endTime)\n\t\t{\n\t\t\trotation = (time - startTime) \/ rotationTime;\n\t\t}\n\n\t\tfloat angle = easeInOutQuint(rotation) * M_PI \/ 2.0f;\n\n\t\tgl::ScopedModelMatrix scpModelMtx;\n\t\tgl::rotate(angleAxis(angle, vec3(0, 1, 0)));\n\t\tmSlices[i]->draw();\n\t}\n}\n\nCINDER_APP( BasicApp, RendererGl )\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 ASMlover. 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 ofconditions and the following disclaimer.\n\/\/\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 materialsprovided with the\n\/\/ distribution.\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 HOLDER 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#include <fstream>\n#include <iostream>\n#include <sstream>\n#include \"lexer.h\"\n#include \"lox.h\"\n\nnamespace lox {\n\nvoid Lox::eval(int argc, char* argv[]) {\n if (argc < 2) {\n eval_with_repl();\n }\n else if (argc == 2) {\n eval_with_file(argv[1]);\n }\n else {\n std::cerr << \"USAGE: \" << argv[0] << \" {script}\" << std::endl;\n std::exit(1);\n }\n}\n\nvoid Lox::eval_with_file(const std::string& fname) {\n std::ifstream fp(fname);\n if (fp.is_open()) {\n std::stringstream ss;\n ss << fp.rdbuf();\n\n run(ss.str(), fname);\n }\n}\n\nvoid Lox::eval_with_repl(void) {\n std::string line;\n for (;;) {\n std::cout << \">>> \";\n\n if (!std::getline(std::cin, line) || line == \"exit\") {\n break;\n }\n run(line);\n }\n}\n\nvoid Lox::run(const std::string& sources, const std::string& fname) {\n \/\/ std::cout << sources << std::endl;\n\n lox::Lexer lex(err_report_, sources, fname);\n\n const auto& tokens = lex.parse_tokens();\n if (err_report_.had_error())\n return;\n\n for (auto& tok : tokens)\n std::cout << tok << std::endl;\n}\n\n}\n<commit_msg>:construction: chore(lox): add parser testing<commit_after>\/\/ Copyright (c) 2019 ASMlover. 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 ofconditions and the following disclaimer.\n\/\/\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 materialsprovided with the\n\/\/ distribution.\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 HOLDER 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#include <fstream>\n#include <iostream>\n#include <sstream>\n#include \"lexer.h\"\n#include \"parser.h\"\n#include \"ast_printer.h\"\n#include \"lox.h\"\n\nnamespace lox {\n\nvoid Lox::eval(int argc, char* argv[]) {\n if (argc < 2) {\n eval_with_repl();\n }\n else if (argc == 2) {\n eval_with_file(argv[1]);\n }\n else {\n std::cerr << \"USAGE: \" << argv[0] << \" {script}\" << std::endl;\n std::exit(1);\n }\n}\n\nvoid Lox::eval_with_file(const std::string& fname) {\n std::ifstream fp(fname);\n if (fp.is_open()) {\n std::stringstream ss;\n ss << fp.rdbuf();\n\n run(ss.str(), fname);\n }\n}\n\nvoid Lox::eval_with_repl(void) {\n std::string line;\n for (;;) {\n std::cout << \">>> \";\n\n if (!std::getline(std::cin, line) || line == \"exit\") {\n break;\n }\n run(line);\n }\n}\n\nvoid Lox::run(const std::string& sources, const std::string& fname) {\n Lexer lex(err_report_, sources, fname);\n const auto& tokens = lex.parse_tokens();\n if (err_report_.had_error())\n std::abort();\n\n for (auto& tok : tokens)\n std::cout << tok << std::endl;\n\n Parser parser(err_report_, tokens);\n auto expr = parser.parse();\n auto astp = std::make_shared<AstPrinter>();\n if (err_report_.had_error())\n std::abort();\n\n std::cout << astp->stringify(expr) << std::endl;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008-2009 Gael Guennebaud <g.gael@free.fr>\n\/\/\n\/\/ Eigen 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 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/Geometry>\n#include <Eigen\/LU>\n#include <Eigen\/SVD>\n\n\/* this test covers the following files:\n Geometry\/OrthoMethods.h\n*\/\n\ntemplate<typename Scalar> void orthomethods_3()\n{\n typedef Matrix<Scalar,3,3> Matrix3;\n typedef Matrix<Scalar,3,1> Vector3;\n\n Vector3 v0 = Vector3::Random(),\n v1 = Vector3::Random(),\n v2 = Vector3::Random();\n\n \/\/ cross product\n VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).dot(v1), Scalar(1));\n Matrix3 mat3;\n mat3 << v0.normalized(),\n (v0.cross(v1)).normalized(),\n (v0.cross(v1).cross(v0)).normalized();\n VERIFY(mat3.isUnitary());\n\n\n \/\/ colwise\/rowwise cross product\n mat3.setRandom();\n Vector3 vec3 = Vector3::Random();\n Matrix3 mcross;\n int i = ei_random<int>(0,2);\n mcross = mat3.colwise().cross(vec3);\n VERIFY_IS_APPROX(mcross.col(i), mat3.col(i).cross(vec3));\n mcross = mat3.rowwise().cross(vec3);\n VERIFY_IS_APPROX(mcross.row(i), mat3.row(i).cross(vec3));\n\n}\n\ntemplate<typename Scalar, int Size> void orthomethods(int size=Size)\n{\n typedef Matrix<Scalar,Size,1> VectorType;\n typedef Matrix<Scalar,3,Size> Matrix3N;\n typedef Matrix<Scalar,Size,3> MatrixN3;\n typedef Matrix<Scalar,3,1> Vector3;\n\n VectorType v0 = VectorType::Random(size),\n v1 = VectorType::Random(size),\n v2 = VectorType::Random(size);\n\n \/\/ unitOrthogonal\n VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1));\n VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1));\n\n \/\/ colwise\/rowwise cross product\n Vector3 vec3 = Vector3::Random();\n int i = ei_random<int>(0,size-1);\n\n Matrix3N mat3N(3,size), mcross3N(3,size);\n mat3N.setRandom();\n mcross3N = mat3N.colwise().cross(vec3);\n VERIFY_IS_APPROX(mcross3N.col(i), mat3N.col(i).cross(vec3));\n\n MatrixN3 matN3(size,3), mcrossN3(size,3);\n matN3.setRandom();\n mcrossN3 = matN3.rowwise().cross(vec3);\n VERIFY_IS_APPROX(mcrossN3.row(i), matN3.row(i).cross(vec3));\n\n}\n\nvoid test_geo_orthomethods()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( orthomethods_3<float>() );\n CALL_SUBTEST( orthomethods_3<double>() );\n CALL_SUBTEST( (orthomethods<float,2>()) );\n CALL_SUBTEST( (orthomethods<double,2>()) );\n CALL_SUBTEST( (orthomethods<float,3>()) );\n CALL_SUBTEST( (orthomethods<double,3>()) );\n CALL_SUBTEST( (orthomethods<float,7>()) );\n CALL_SUBTEST( (orthomethods<double,8>()) );\n CALL_SUBTEST( (orthomethods<float,Dynamic>(36)) );\n CALL_SUBTEST( (orthomethods<double,Dynamic>(35)) );\n }\n}\n<commit_msg>add tests showing bug in unitOrthogonal such that we don't forget it!<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008-2009 Gael Guennebaud <g.gael@free.fr>\n\/\/\n\/\/ Eigen 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 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/Geometry>\n#include <Eigen\/LU>\n#include <Eigen\/SVD>\n\n\/* this test covers the following files:\n Geometry\/OrthoMethods.h\n*\/\n\ntemplate<typename Scalar> void orthomethods_3()\n{\n typedef Matrix<Scalar,3,3> Matrix3;\n typedef Matrix<Scalar,3,1> Vector3;\n\n Vector3 v0 = Vector3::Random(),\n v1 = Vector3::Random(),\n v2 = Vector3::Random();\n\n \/\/ cross product\n VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).dot(v1), Scalar(1));\n Matrix3 mat3;\n mat3 << v0.normalized(),\n (v0.cross(v1)).normalized(),\n (v0.cross(v1).cross(v0)).normalized();\n VERIFY(mat3.isUnitary());\n\n\n \/\/ colwise\/rowwise cross product\n mat3.setRandom();\n Vector3 vec3 = Vector3::Random();\n Matrix3 mcross;\n int i = ei_random<int>(0,2);\n mcross = mat3.colwise().cross(vec3);\n VERIFY_IS_APPROX(mcross.col(i), mat3.col(i).cross(vec3));\n mcross = mat3.rowwise().cross(vec3);\n VERIFY_IS_APPROX(mcross.row(i), mat3.row(i).cross(vec3));\n\n}\n\ntemplate<typename Scalar, int Size> void orthomethods(int size=Size)\n{\n typedef Matrix<Scalar,Size,1> VectorType;\n typedef Matrix<Scalar,3,Size> Matrix3N;\n typedef Matrix<Scalar,Size,3> MatrixN3;\n typedef Matrix<Scalar,3,1> Vector3;\n\n VectorType v0 = VectorType::Random(size),\n v1 = VectorType::Random(size),\n v2 = VectorType::Random(size);\n\n \/\/ unitOrthogonal\n VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1));\n VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1));\n\n if (size>3)\n {\n v0.template start<3>().setZero();\n v0.end(size-3).setRandom();\n\n VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1));\n VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1));\n }\n\n \/\/ colwise\/rowwise cross product\n Vector3 vec3 = Vector3::Random();\n int i = ei_random<int>(0,size-1);\n\n Matrix3N mat3N(3,size), mcross3N(3,size);\n mat3N.setRandom();\n mcross3N = mat3N.colwise().cross(vec3);\n VERIFY_IS_APPROX(mcross3N.col(i), mat3N.col(i).cross(vec3));\n\n MatrixN3 matN3(size,3), mcrossN3(size,3);\n matN3.setRandom();\n mcrossN3 = matN3.rowwise().cross(vec3);\n VERIFY_IS_APPROX(mcrossN3.row(i), matN3.row(i).cross(vec3));\n}\n\nvoid test_geo_orthomethods()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( orthomethods_3<float>() );\n CALL_SUBTEST( orthomethods_3<double>() );\n CALL_SUBTEST( (orthomethods<float,2>()) );\n CALL_SUBTEST( (orthomethods<double,2>()) );\n CALL_SUBTEST( (orthomethods<float,3>()) );\n CALL_SUBTEST( (orthomethods<double,3>()) );\n CALL_SUBTEST( (orthomethods<float,7>()) );\n CALL_SUBTEST( (orthomethods<double,8>()) );\n CALL_SUBTEST( (orthomethods<float,Dynamic>(36)) );\n CALL_SUBTEST( (orthomethods<double,Dynamic>(35)) );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DIRICHLET_SHETXCOC\n#define DIRICHLET_SHETXCOC\n\nnamespace Dune {\nnamespace Functionals {\nnamespace Constraints {\n\n\/** @brief Constraints for Dirichlet values on the entire boundary domain\n *\n * This class implements constraints on the degrees of freedom on a @ref\n * Subspace::Linear \"linear subspace\" @endref.\n *\n * Constraints efficiently implement functionals @f$ f_i:\\cal X_H \\to\n * \\mathbb{R}@f$ for each degree of freedom @f$i\\in C \\subset\n * \\{1,\\dots,H\\}@f$, where $H$ is the number of degree of freedoms in the\n * underlying discrete function space @f$\\cal X_H\\@f$. In case of this Dirichlet constraints class, the set\n * @f$\\{1,\\dots,C\\}@f$ includes all\n *\n * @note The Dirichlet constraints only make sense on a finite element space,\n * not on a discontinuous discrete function space.\n *\n * @tparam DiscFuncSpace discrete function space on which constraints shall\n * be applied.\n *\/\ntemplate <class DiscFuncSpace>\nclass Dirichlet\n{\npublic:\n \/\/! Discrete function space on which the Dirichlet constraints are applied\n typedef DiscFuncSpace DiscreteFunctionSpace;\n\n \/\/! Underlying grid part\n typedef typename DiscreteFunctionSpace::GridPartType GridPartType;\n\n \/\/! Dimension of the grid part\n static const int griddim = GridPartType::GridType::dimension;\n\n \/\/! Return type of local() method, implementing the LocalConstraints\n \/\/! interface\n typedef Constraints::LocalDefault<double, griddim, griddim> LocalConstraintsType;\n\npublic:\n \/** Constructor for the Dirichlet constraints\n *\n * @param space discrete function space object on which the Dirichlet\n * constraints are applied\n *\/\n Dirichlet(DiscFuncSpace& space)\n : space_(space)\n , gridPart_(space.gridPart())\n {\n }\n\n\n \/** return a local constraint object for the entity \\a en\n *\n * @param en Entity for which the local constraints shall be compted\n *\n * @returns local constraints object (copyable).\n *\/\n template <class Entity>\n const LocalConstraintsType local(const Entity& en)\n {\n typedef typename DiscFuncSpace::BaseFunctionSet BFS;\n\n const BFS& bfs = space_.baseFunctionSet(en);\n const int numCols = bfs.numBaseFunctions();\n LocalConstraintsType lc(numCols);\n\n typedef typename DFS::Iterator ItType;\n typedef typename Entity::LeafIntersectionIterator IntersectionIterator;\n typedef typename IntersectionIterator::Intersection Intersection;\n\n int numRows = 0;\n ItType it = space_.begin();\n for (; it != space_.end(); it++) {\n const Entity& en = *it;\n\n IntersectionIterator iit = en.ileafbegin();\n for (; iit != en.ileafend(); iit++) {\n const Intersection& ii = *iit;\n if (ii.boundary()) {\n lc.setRowDofs(numRows, space_.mapToGlobal(en, numRows));\n for (unsigned int i = 0; i < numCols; i++) {\n lc.setColumnDofs(i, space_.mapToGlobal(en, i));\n lc.setLocalMatrix(numRows, i) = 0;\n }\n lc.setLocalMatrix(numRows, numRows) = 1;\n ++numRows;\n }\n }\n }\n lc.setRowDofsSize(numRows);\n return lc;\n }\n\nprivate:\n DiscreteFunctionSpace& space_;\n GridPartType& gridPart_;\n}; \/\/ end class Dirichlet\n\n} \/\/ end of namespace Constraints\n} \/\/ end of namespace Functionals\n} \/\/ end of namespace Dune\n\n#endif \/* end of include guard: DIRICHLET_SHETXCOC *\/\n<commit_msg>update documentation in Constraints::Dirichlet<commit_after>#ifndef DIRICHLET_SHETXCOC\n#define DIRICHLET_SHETXCOC\n\nnamespace Dune {\nnamespace Functionals {\nnamespace Constraints {\n\n\/** @brief Constraints for Dirichlet values on the entire boundary domain\n *\n * This class implements constraints on the degrees of freedom on a @link\n * Subspace::Linear \"linear subspace\" @endlink.\n *\n * Constraints efficiently implement functionals @f$ f_i:{\\cal X}_H \\to\n * \\mathbb{R}@f$ for each degree of freedom @f$i\\in {\\cal C} \\subset\n * \\{1,\\dots,H\\}@f$, where @f$ H @f$ is the number of degree of freedoms in the\n * underlying discrete function space @f$ {\\cal X}_H @f$. In case of this\n * Dirichlet constraints class, the set @f$ {\\cal C} @f$ includes all degrees of\n * freedom \"lying\" on boundary edges and @f$ f_i(u) = 0 @f$ for all @f$ i=\\cal\n * C @f$.\n *\n * @note The Dirichlet constraints only make sense on a finite element space,\n * not on a discontinuous discrete function space.\n *\n * @tparam DiscFuncSpace discrete function space on which constraints shall\n * be applied.\n *\/\ntemplate <class DiscFuncSpace>\nclass Dirichlet\n{\npublic:\n \/\/! Discrete function space on which the Dirichlet constraints are applied\n typedef DiscFuncSpace DiscreteFunctionSpace;\n\n \/\/! Underlying grid part\n typedef typename DiscreteFunctionSpace::GridPartType GridPartType;\n\n \/\/! @brief dimension of the grid part\n static const int griddim = GridPartType::GridType::dimension;\n\n \/\/! @brief Return type of local() method, implementing the LocalConstraints\n \/\/! interface\n typedef Constraints::LocalDefault<double, griddim, griddim> LocalConstraintsType;\n\npublic:\n \/** @brief Constructor for the Dirichlet constraints\n *\n * @param space discrete function space object on which the Dirichlet\n * constraints are applied\n *\/\n Dirichlet(DiscFuncSpace& space)\n : space_(space)\n , gridPart_(space.gridPart())\n {\n }\n\n\n \/** @brief returns a local constraint object for the entity \\a en\n *\n * @param en Entity for which the local constraints shall be compted\n *\n * @returns local constraints object (copyable). c.f.\n * Constraints::LocalDefault for more details on the return type\n * implementation.\n *\/\n template <class Entity>\n const LocalConstraintsType local(const Entity& en)\n {\n typedef typename DiscFuncSpace::BaseFunctionSet BFS;\n\n const BFS& bfs = space_.baseFunctionSet(en);\n const int numCols = bfs.numBaseFunctions();\n LocalConstraintsType lc(numCols);\n\n typedef typename DFS::Iterator ItType;\n typedef typename Entity::LeafIntersectionIterator IntersectionIterator;\n typedef typename IntersectionIterator::Intersection Intersection;\n\n int numRows = 0;\n ItType it = space_.begin();\n for (; it != space_.end(); it++) {\n const Entity& en = *it;\n\n IntersectionIterator iit = en.ileafbegin();\n for (; iit != en.ileafend(); iit++) {\n const Intersection& ii = *iit;\n if (ii.boundary()) {\n lc.setRowDofs(numRows, space_.mapToGlobal(en, numRows));\n for (unsigned int i = 0; i < numCols; i++) {\n lc.setColumnDofs(i, space_.mapToGlobal(en, i));\n lc.setLocalMatrix(numRows, i) = 0;\n }\n lc.setLocalMatrix(numRows, numRows) = 1;\n ++numRows;\n }\n }\n }\n lc.setRowDofsSize(numRows);\n return lc;\n }\n\nprivate:\n DiscreteFunctionSpace& space_;\n GridPartType& gridPart_;\n}; \/\/ end class Dirichlet\n\n} \/\/ end of namespace Constraints\n} \/\/ end of namespace Functionals\n} \/\/ end of namespace Dune\n\n#endif \/* end of include guard: DIRICHLET_SHETXCOC *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2009-2011 by Patrick Schaefer, Zuse Institute Berlin\n *\n * Licensed under the BSD License, see LICENSE file for details.\n *\n *\/\n#include \"libxtreemfs\/pbrpc_url.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <string>\n#include <utility>\n\n#include \"libxtreemfs\/xtreemfs_exception.h\"\n\nusing namespace std;\n\nnamespace xtreemfs {\n\nconst std::string PBRPCURL::SCHEME_PBRPC = \"pbrpc\";\nconst std::string PBRPCURL::SCHEME_PBRPCS = \"pbrpcs\";\nconst std::string PBRPCURL::SCHEME_PBRPCG = \"pbrpcg\";\nconst std::string PBRPCURL::SCHEME_PBRPCU = \"pbrpcu\";\n\nPBRPCURL::PBRPCURL(const std::string& scheme,\n const std::string& server, std::string& volume, uint16_t port)\n : scheme_(scheme), server_(server), port_(port), volume_(volume) {\n}\n\nPBRPCURL::PBRPCURL() : scheme_(\"\"), server_(\"\"), port_(0), volume_(\"\") {\n}\n\nbool PBRPCURL::protocolContains(std::string url, std::string scheme) {\n size_t scheme_pos = url.find(\":\/\/\");\n if (scheme_pos != std::string::npos) {\n std::string s = url.substr(0, scheme_pos);\n return scheme == s;\n }\n return false;\n}\n\nvoid PBRPCURL::parseURL(\n const std::string& original_url,\n const std::string& default_scheme,\n const uint16_t default_port) {\n string url(original_url);\n boost::trim(url);\n\n scheme_ = default_scheme;\n size_t scheme_pos = url.find(\":\/\/\");\n size_t address_pos = 0;\n if (scheme_pos != std::string::npos) {\n \/\/ scheme specified\n scheme_ = url.substr(0, scheme_pos);\n if ((scheme_ != SCHEME_PBRPC)\n && (scheme_ != SCHEME_PBRPCS)\n && (scheme_ != SCHEME_PBRPCG)\n && (scheme_ != SCHEME_PBRPCU)) {\n throw InvalidURLException(scheme_ + \" is not a valid scheme\");\n }\n address_pos = scheme_pos + 3;\n }\n port_ = default_port;\n\n size_t last_slash = url.find_last_of(\"\/\");\n size_t last_colon = url.find_last_of(\":\");\n if (last_colon != std::string::npos) {\n \/\/ Port found.\n if (last_colon > address_pos) {\n try {\n if (last_slash != std::string::npos && last_slash > last_colon+1) {\n port_ = boost::lexical_cast<uint16_t>(\n url.substr(last_colon + 1, last_slash-last_colon-1));\n }\n } catch(const boost::bad_lexical_cast&) {\n throw InvalidURLException(\"invalid port: \" +\n url.substr(last_colon + 1, last_slash-last_colon-1));\n }\n } else {\n last_colon = last_slash;\n }\n } else {\n last_colon = last_slash;\n }\n\n \/\/ volume is optional\n if (last_slash > address_pos && last_slash != std::string::npos) {\n volume_ = url.substr(last_slash+1, url.length() - last_slash);\n }\n\n server_ = url.substr(address_pos, last_colon-address_pos);\n}\n\n} \/\/ namespace xtreemfs\n<commit_msg>client: Fixed correct parsing of the port if the volume name is not present.<commit_after>\/*\n * Copyright (c) 2009-2011 by Patrick Schaefer, Zuse Institute Berlin\n *\n * Licensed under the BSD License, see LICENSE file for details.\n *\n *\/\n#include \"libxtreemfs\/pbrpc_url.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <string>\n#include <utility>\n\n#include \"libxtreemfs\/xtreemfs_exception.h\"\n\nusing namespace std;\n\nnamespace xtreemfs {\n\nconst std::string PBRPCURL::SCHEME_PBRPC = \"pbrpc\";\nconst std::string PBRPCURL::SCHEME_PBRPCS = \"pbrpcs\";\nconst std::string PBRPCURL::SCHEME_PBRPCG = \"pbrpcg\";\nconst std::string PBRPCURL::SCHEME_PBRPCU = \"pbrpcu\";\n\nPBRPCURL::PBRPCURL(const std::string& scheme,\n const std::string& server, std::string& volume, uint16_t port)\n : scheme_(scheme), server_(server), port_(port), volume_(volume) {\n}\n\nPBRPCURL::PBRPCURL() : scheme_(\"\"), server_(\"\"), port_(0), volume_(\"\") {\n}\n\nbool PBRPCURL::protocolContains(std::string url, std::string scheme) {\n size_t scheme_pos = url.find(\":\/\/\");\n if (scheme_pos != std::string::npos) {\n std::string s = url.substr(0, scheme_pos);\n return scheme == s;\n }\n return false;\n}\n\nvoid PBRPCURL::parseURL(\n const std::string& original_url,\n const std::string& default_scheme,\n const uint16_t default_port) {\n string url(original_url);\n boost::trim(url);\n\n scheme_ = default_scheme;\n size_t scheme_pos = url.find(\":\/\/\");\n size_t address_pos = 0;\n if (scheme_pos != std::string::npos) {\n \/\/ scheme specified\n scheme_ = url.substr(0, scheme_pos);\n if ((scheme_ != SCHEME_PBRPC)\n && (scheme_ != SCHEME_PBRPCS)\n && (scheme_ != SCHEME_PBRPCG)\n && (scheme_ != SCHEME_PBRPCU)) {\n throw InvalidURLException(scheme_ + \" is not a valid scheme\");\n }\n address_pos = scheme_pos + 3;\n }\n port_ = default_port;\n\n size_t last_slash = url.find_last_of(\"\/\");\n size_t last_colon = url.find_last_of(\":\");\n if (last_colon != std::string::npos) {\n \/\/ Port found.\n if (last_colon > address_pos) {\n try {\n if (last_slash != std::string::npos) {\n if (last_slash > last_colon + 1) {\n port_ = boost::lexical_cast<uint16_t>(\n url.substr(last_colon + 1, last_slash - last_colon - 1));\n }\n } else {\n port_ = boost::lexical_cast<uint16_t>(url.substr(last_colon + 1));\n }\n } catch(const boost::bad_lexical_cast&) {\n throw InvalidURLException(\"invalid port: \" +\n url.substr(last_colon + 1, last_slash - last_colon - 1));\n }\n } else {\n last_colon = last_slash;\n }\n } else {\n last_colon = last_slash;\n }\n\n \/\/ volume is optional\n if (last_slash > address_pos && last_slash != std::string::npos) {\n volume_ = url.substr(last_slash+1, url.length() - last_slash);\n }\n\n server_ = url.substr(address_pos, last_colon-address_pos);\n}\n\n} \/\/ namespace xtreemfs\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2002-2014 The ANGLE Project 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\n\/\/ Texture.cpp: Implements the gl::Texture class. [OpenGL ES 2.0.24] section 3.7 page 63.\n\n#include \"libANGLE\/Texture.h\"\n#include \"libANGLE\/Data.h\"\n#include \"libANGLE\/formatutils.h\"\n\n#include \"libANGLE\/Surface.h\"\n\n#include \"common\/mathutil.h\"\n#include \"common\/utilities.h\"\n\nnamespace gl\n{\n\nbool IsMipmapFiltered(const gl::SamplerState &samplerState)\n{\n switch (samplerState.minFilter)\n {\n case GL_NEAREST:\n case GL_LINEAR:\n return false;\n case GL_NEAREST_MIPMAP_NEAREST:\n case GL_LINEAR_MIPMAP_NEAREST:\n case GL_NEAREST_MIPMAP_LINEAR:\n case GL_LINEAR_MIPMAP_LINEAR:\n return true;\n default: UNREACHABLE();\n return false;\n }\n}\n\nbool IsPointSampled(const gl::SamplerState &samplerState)\n{\n return (samplerState.magFilter == GL_NEAREST && (samplerState.minFilter == GL_NEAREST || samplerState.minFilter == GL_NEAREST_MIPMAP_NEAREST));\n}\n\nunsigned int Texture::mCurrentTextureSerial = 1;\n\nTexture::Texture(rx::TextureImpl *impl, GLuint id, GLenum target)\n : RefCountObject(id),\n mTexture(impl),\n mTextureSerial(issueTextureSerial()),\n mUsage(GL_NONE),\n mImmutableLevelCount(0),\n mTarget(target),\n mBoundSurface(NULL)\n{\n}\n\nTexture::~Texture()\n{\n if (mBoundSurface)\n {\n mBoundSurface->releaseTexImage(EGL_BACK_BUFFER);\n mBoundSurface = NULL;\n }\n SafeDelete(mTexture);\n}\n\nGLenum Texture::getTarget() const\n{\n return mTarget;\n}\n\nvoid Texture::setUsage(GLenum usage)\n{\n mUsage = usage;\n getImplementation()->setUsage(usage);\n}\n\nGLenum Texture::getUsage() const\n{\n return mUsage;\n}\n\nsize_t Texture::getWidth(GLenum target, size_t level) const\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n return getImageDesc(ImageIndex::MakeGeneric(target, level)).size.width;\n}\n\nsize_t Texture::getHeight(GLenum target, size_t level) const\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n return getImageDesc(ImageIndex::MakeGeneric(target, level)).size.height;\n}\n\nsize_t Texture::getDepth(GLenum target, size_t level) const\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n return getImageDesc(ImageIndex::MakeGeneric(target, level)).size.depth;\n}\n\nGLenum Texture::getInternalFormat(GLenum target, size_t level) const\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n return getImageDesc(ImageIndex::MakeGeneric(target, level)).internalFormat;\n}\n\nbool Texture::isSamplerComplete(const SamplerState &samplerState, const Data &data) const\n{\n GLenum baseTarget = getBaseImageTarget();\n size_t width = getWidth(baseTarget, samplerState.baseLevel);\n size_t height = getHeight(baseTarget, samplerState.baseLevel);\n size_t depth = getDepth(baseTarget, samplerState.baseLevel);\n if (width == 0 || height == 0 || depth == 0)\n {\n return false;\n }\n\n if (mTarget == GL_TEXTURE_CUBE_MAP && width != height)\n {\n return false;\n }\n\n GLenum internalFormat = getInternalFormat(baseTarget, samplerState.baseLevel);\n const TextureCaps &textureCaps = data.textureCaps->get(internalFormat);\n if (!textureCaps.filterable && !IsPointSampled(samplerState))\n {\n return false;\n }\n\n bool npotSupport = data.extensions->textureNPOT || data.clientVersion >= 3;\n if (!npotSupport)\n {\n if ((samplerState.wrapS != GL_CLAMP_TO_EDGE && !gl::isPow2(width)) ||\n (samplerState.wrapT != GL_CLAMP_TO_EDGE && !gl::isPow2(height)))\n {\n return false;\n }\n }\n\n if (IsMipmapFiltered(samplerState))\n {\n if (!npotSupport)\n {\n if (!gl::isPow2(width) || !gl::isPow2(height))\n {\n return false;\n }\n }\n\n if (!isMipmapComplete(samplerState))\n {\n return false;\n }\n }\n else\n {\n if (mTarget == GL_TEXTURE_CUBE_MAP && !isCubeComplete())\n {\n return false;\n }\n }\n\n \/\/ OpenGLES 3.0.2 spec section 3.8.13 states that a texture is not mipmap complete if:\n \/\/ The internalformat specified for the texture arrays is a sized internal depth or\n \/\/ depth and stencil format (see table 3.13), the value of TEXTURE_COMPARE_-\n \/\/ MODE is NONE, and either the magnification filter is not NEAREST or the mini-\n \/\/ fication filter is neither NEAREST nor NEAREST_MIPMAP_NEAREST.\n const gl::InternalFormat &formatInfo = gl::GetInternalFormatInfo(internalFormat);\n if (formatInfo.depthBits > 0 && data.clientVersion > 2)\n {\n if (samplerState.compareMode == GL_NONE)\n {\n if ((samplerState.minFilter != GL_NEAREST && samplerState.minFilter != GL_NEAREST_MIPMAP_NEAREST) ||\n samplerState.magFilter != GL_NEAREST)\n {\n return false;\n }\n }\n }\n\n return true;\n}\n\n\/\/ Tests for cube texture completeness. [OpenGL ES 2.0.24] section 3.7.10 page 81.\nbool Texture::isCubeComplete() const\n{\n ASSERT(mTarget == GL_TEXTURE_CUBE_MAP);\n\n GLenum baseTarget = FirstCubeMapTextureTarget;\n size_t width = getWidth(baseTarget, 0);\n size_t height = getWidth(baseTarget, 0);\n if (width == 0 || width != height)\n {\n return false;\n }\n\n GLenum internalFormat = getInternalFormat(baseTarget, 0);\n for (GLenum face = baseTarget + 1; face <= LastCubeMapTextureTarget; face++)\n {\n if (getWidth(face, 0) != width ||\n getHeight(face, 0) != height ||\n getInternalFormat(face, 0) != internalFormat)\n {\n return false;\n }\n }\n\n return true;\n}\n\nunsigned int Texture::getTextureSerial() const\n{\n return mTextureSerial;\n}\n\nunsigned int Texture::issueTextureSerial()\n{\n return mCurrentTextureSerial++;\n}\n\nbool Texture::isImmutable() const\n{\n return (mImmutableLevelCount > 0);\n}\n\nint Texture::immutableLevelCount()\n{\n return mImmutableLevelCount;\n}\n\nError Texture::setImage(GLenum target, size_t level, GLenum internalFormat, const Extents &size, GLenum format, GLenum type,\n const PixelUnpackState &unpack, const uint8_t *pixels)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n Error error = mTexture->setImage(target, level, internalFormat, size, format, type, unpack, pixels);\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n setImageDesc(ImageIndex::MakeGeneric(target, level), ImageDesc(size, GetSizedInternalFormat(internalFormat, type)));\n\n return Error(GL_NO_ERROR);\n}\n\nError Texture::setSubImage(GLenum target, size_t level, const Box &area, GLenum format, GLenum type,\n const PixelUnpackState &unpack, const uint8_t *pixels)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n return mTexture->setSubImage(target, level, area, format, type, unpack, pixels);\n}\n\nError Texture::setCompressedImage(GLenum target, size_t level, GLenum internalFormat, const Extents &size,\n const PixelUnpackState &unpack, const uint8_t *pixels)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n Error error = mTexture->setCompressedImage(target, level, internalFormat, size, unpack, pixels);\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n setImageDesc(ImageIndex::MakeGeneric(target, level), ImageDesc(size, GetSizedInternalFormat(internalFormat, GL_UNSIGNED_BYTE)));\n\n return Error(GL_NO_ERROR);\n}\n\nError Texture::setCompressedSubImage(GLenum target, size_t level, const Box &area, GLenum format,\n const PixelUnpackState &unpack, const uint8_t *pixels)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n return mTexture->setCompressedSubImage(target, level, area, format, unpack, pixels);\n}\n\nError Texture::copyImage(GLenum target, size_t level, const Rectangle &sourceArea, GLenum internalFormat,\n const Framebuffer *source)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n Error error = mTexture->copyImage(target, level, sourceArea, internalFormat, source);\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n setImageDesc(ImageIndex::MakeGeneric(target, level), ImageDesc(Extents(sourceArea.width, sourceArea.height, 1),\n GetSizedInternalFormat(internalFormat, GL_UNSIGNED_BYTE)));\n\n return Error(GL_NO_ERROR);\n}\n\nError Texture::copySubImage(GLenum target, size_t level, const Offset &destOffset, const Rectangle &sourceArea,\n const Framebuffer *source)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n return mTexture->copySubImage(target, level, destOffset, sourceArea, source);\n}\n\nError Texture::setStorage(GLenum target, size_t levels, GLenum internalFormat, const Extents &size)\n{\n ASSERT(target == mTarget);\n\n Error error = mTexture->setStorage(target, levels, internalFormat, size);\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n mImmutableLevelCount = levels;\n clearImageDescs();\n setImageDescChain(levels, size, internalFormat);\n\n return Error(GL_NO_ERROR);\n}\n\n\nError Texture::generateMipmaps()\n{\n Error error = mTexture->generateMipmaps();\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n ImageIndex baseLevel = ImageIndex::MakeGeneric(getBaseImageTarget(), 0);\n const ImageDesc &baseImageInfo = getImageDesc(baseLevel);\n size_t mipLevels = log2(std::max(std::max(baseImageInfo.size.width, baseImageInfo.size.height), baseImageInfo.size.depth)) + 1;\n setImageDescChain(mipLevels, baseImageInfo.size, baseImageInfo.internalFormat);\n\n return Error(GL_NO_ERROR);\n}\n\nvoid Texture::setImageDescChain(size_t levels, Extents baseSize, GLenum sizedInternalFormat)\n{\n for (size_t level = 0; level < levels; level++)\n {\n Extents levelSize(std::max<size_t>(baseSize.width >> level, 1),\n std::max<size_t>(baseSize.height >> level, 1),\n (mTarget == GL_TEXTURE_2D_ARRAY) ? baseSize.depth : std::max<size_t>(baseSize.depth >> level, 1));\n ImageDesc levelInfo(levelSize, sizedInternalFormat);\n\n if (mTarget == GL_TEXTURE_CUBE_MAP)\n {\n for (size_t face = FirstCubeMapTextureTarget; face <= LastCubeMapTextureTarget; face++)\n {\n setImageDesc(ImageIndex::MakeGeneric(face, level), levelInfo);\n }\n }\n else\n {\n setImageDesc(ImageIndex::MakeGeneric(mTarget, level), levelInfo);\n }\n }\n}\n\nTexture::ImageDesc::ImageDesc()\n : ImageDesc(Extents(0, 0, 0), GL_NONE)\n{\n}\n\nTexture::ImageDesc::ImageDesc(const Extents &size, GLenum internalFormat)\n : size(size),\n internalFormat(internalFormat)\n{\n}\n\nconst Texture::ImageDesc &Texture::getImageDesc(const ImageIndex &index) const\n{\n static const Texture::ImageDesc defaultDesc;\n ImageDescMap::const_iterator iter = mImageDescs.find(index);\n return (iter != mImageDescs.end()) ? iter->second : defaultDesc;\n}\n\nvoid Texture::setImageDesc(const ImageIndex &index, const ImageDesc &desc)\n{\n mImageDescs[index] = desc;\n}\n\nvoid Texture::clearImageDescs()\n{\n mImageDescs.clear();\n}\n\nvoid Texture::bindTexImage(egl::Surface *surface)\n{\n releaseTexImage();\n mTexture->bindTexImage(surface);\n mBoundSurface = surface;\n}\n\nvoid Texture::releaseTexImage()\n{\n if (mBoundSurface)\n {\n mBoundSurface = NULL;\n mTexture->releaseTexImage();\n }\n}\n\nGLenum Texture::getBaseImageTarget() const\n{\n return mTarget == GL_TEXTURE_CUBE_MAP ? FirstCubeMapTextureTarget : mTarget;\n}\n\nsize_t Texture::getExpectedMipLevels() const\n{\n GLenum baseTarget = getBaseImageTarget();\n size_t width = getWidth(baseTarget, 0);\n size_t height = getHeight(baseTarget, 0);\n if (mTarget == GL_TEXTURE_3D)\n {\n size_t depth = getDepth(baseTarget, 0);\n return log2(std::max(std::max(width, height), depth)) + 1;\n }\n else\n {\n return log2(std::max(width, height)) + 1;\n }\n}\n\nbool Texture::isMipmapComplete(const gl::SamplerState &samplerState) const\n{\n size_t expectedMipLevels = getExpectedMipLevels();\n\n size_t maxLevel = std::min<size_t>(expectedMipLevels, samplerState.maxLevel + 1);\n\n for (size_t level = samplerState.baseLevel; level < maxLevel; level++)\n {\n if (mTarget == GL_TEXTURE_CUBE_MAP)\n {\n for (GLenum face = FirstCubeMapTextureTarget; face <= LastCubeMapTextureTarget; face++)\n {\n if (!isLevelComplete(face, level, samplerState))\n {\n return false;\n }\n }\n }\n else\n {\n if (!isLevelComplete(mTarget, level, samplerState))\n {\n return false;\n }\n }\n }\n\n return true;\n}\n\n\nbool Texture::isLevelComplete(GLenum target, size_t level,\n const gl::SamplerState &samplerState) const\n{\n ASSERT(level < IMPLEMENTATION_MAX_TEXTURE_LEVELS);\n\n if (isImmutable())\n {\n return true;\n }\n\n size_t width = getWidth(target, samplerState.baseLevel);\n size_t height = getHeight(target, samplerState.baseLevel);\n size_t depth = getHeight(target, samplerState.baseLevel);\n if (width == 0 || height == 0 || depth == 0)\n {\n return false;\n }\n\n \/\/ The base image level is complete if the width and height are positive\n if (level == 0)\n {\n return true;\n }\n\n if (getInternalFormat(target, level) != getInternalFormat(target, samplerState.baseLevel))\n {\n return false;\n }\n\n if (getWidth(target, level) != std::max<size_t>(1, width >> level))\n {\n return false;\n }\n\n if (getHeight(target, level) != std::max<size_t>(1, height >> level))\n {\n return false;\n }\n\n if (mTarget == GL_TEXTURE_3D)\n {\n if (getDepth(target, level) != std::max<size_t>(1, depth >> level))\n {\n return false;\n }\n }\n else if (mTarget == GL_TEXTURE_2D_ARRAY)\n {\n if (getDepth(target, level) != depth)\n {\n return false;\n }\n }\n\n return true;\n}\n\n}\n<commit_msg>Fix 'getDepth' in Texture::isLevelComplete.<commit_after>\/\/\n\/\/ Copyright (c) 2002-2014 The ANGLE Project 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\n\/\/ Texture.cpp: Implements the gl::Texture class. [OpenGL ES 2.0.24] section 3.7 page 63.\n\n#include \"libANGLE\/Texture.h\"\n#include \"libANGLE\/Data.h\"\n#include \"libANGLE\/formatutils.h\"\n\n#include \"libANGLE\/Surface.h\"\n\n#include \"common\/mathutil.h\"\n#include \"common\/utilities.h\"\n\nnamespace gl\n{\n\nbool IsMipmapFiltered(const gl::SamplerState &samplerState)\n{\n switch (samplerState.minFilter)\n {\n case GL_NEAREST:\n case GL_LINEAR:\n return false;\n case GL_NEAREST_MIPMAP_NEAREST:\n case GL_LINEAR_MIPMAP_NEAREST:\n case GL_NEAREST_MIPMAP_LINEAR:\n case GL_LINEAR_MIPMAP_LINEAR:\n return true;\n default: UNREACHABLE();\n return false;\n }\n}\n\nbool IsPointSampled(const gl::SamplerState &samplerState)\n{\n return (samplerState.magFilter == GL_NEAREST && (samplerState.minFilter == GL_NEAREST || samplerState.minFilter == GL_NEAREST_MIPMAP_NEAREST));\n}\n\nunsigned int Texture::mCurrentTextureSerial = 1;\n\nTexture::Texture(rx::TextureImpl *impl, GLuint id, GLenum target)\n : RefCountObject(id),\n mTexture(impl),\n mTextureSerial(issueTextureSerial()),\n mUsage(GL_NONE),\n mImmutableLevelCount(0),\n mTarget(target),\n mBoundSurface(NULL)\n{\n}\n\nTexture::~Texture()\n{\n if (mBoundSurface)\n {\n mBoundSurface->releaseTexImage(EGL_BACK_BUFFER);\n mBoundSurface = NULL;\n }\n SafeDelete(mTexture);\n}\n\nGLenum Texture::getTarget() const\n{\n return mTarget;\n}\n\nvoid Texture::setUsage(GLenum usage)\n{\n mUsage = usage;\n getImplementation()->setUsage(usage);\n}\n\nGLenum Texture::getUsage() const\n{\n return mUsage;\n}\n\nsize_t Texture::getWidth(GLenum target, size_t level) const\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n return getImageDesc(ImageIndex::MakeGeneric(target, level)).size.width;\n}\n\nsize_t Texture::getHeight(GLenum target, size_t level) const\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n return getImageDesc(ImageIndex::MakeGeneric(target, level)).size.height;\n}\n\nsize_t Texture::getDepth(GLenum target, size_t level) const\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n return getImageDesc(ImageIndex::MakeGeneric(target, level)).size.depth;\n}\n\nGLenum Texture::getInternalFormat(GLenum target, size_t level) const\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n return getImageDesc(ImageIndex::MakeGeneric(target, level)).internalFormat;\n}\n\nbool Texture::isSamplerComplete(const SamplerState &samplerState, const Data &data) const\n{\n GLenum baseTarget = getBaseImageTarget();\n size_t width = getWidth(baseTarget, samplerState.baseLevel);\n size_t height = getHeight(baseTarget, samplerState.baseLevel);\n size_t depth = getDepth(baseTarget, samplerState.baseLevel);\n if (width == 0 || height == 0 || depth == 0)\n {\n return false;\n }\n\n if (mTarget == GL_TEXTURE_CUBE_MAP && width != height)\n {\n return false;\n }\n\n GLenum internalFormat = getInternalFormat(baseTarget, samplerState.baseLevel);\n const TextureCaps &textureCaps = data.textureCaps->get(internalFormat);\n if (!textureCaps.filterable && !IsPointSampled(samplerState))\n {\n return false;\n }\n\n bool npotSupport = data.extensions->textureNPOT || data.clientVersion >= 3;\n if (!npotSupport)\n {\n if ((samplerState.wrapS != GL_CLAMP_TO_EDGE && !gl::isPow2(width)) ||\n (samplerState.wrapT != GL_CLAMP_TO_EDGE && !gl::isPow2(height)))\n {\n return false;\n }\n }\n\n if (IsMipmapFiltered(samplerState))\n {\n if (!npotSupport)\n {\n if (!gl::isPow2(width) || !gl::isPow2(height))\n {\n return false;\n }\n }\n\n if (!isMipmapComplete(samplerState))\n {\n return false;\n }\n }\n else\n {\n if (mTarget == GL_TEXTURE_CUBE_MAP && !isCubeComplete())\n {\n return false;\n }\n }\n\n \/\/ OpenGLES 3.0.2 spec section 3.8.13 states that a texture is not mipmap complete if:\n \/\/ The internalformat specified for the texture arrays is a sized internal depth or\n \/\/ depth and stencil format (see table 3.13), the value of TEXTURE_COMPARE_-\n \/\/ MODE is NONE, and either the magnification filter is not NEAREST or the mini-\n \/\/ fication filter is neither NEAREST nor NEAREST_MIPMAP_NEAREST.\n const gl::InternalFormat &formatInfo = gl::GetInternalFormatInfo(internalFormat);\n if (formatInfo.depthBits > 0 && data.clientVersion > 2)\n {\n if (samplerState.compareMode == GL_NONE)\n {\n if ((samplerState.minFilter != GL_NEAREST && samplerState.minFilter != GL_NEAREST_MIPMAP_NEAREST) ||\n samplerState.magFilter != GL_NEAREST)\n {\n return false;\n }\n }\n }\n\n return true;\n}\n\n\/\/ Tests for cube texture completeness. [OpenGL ES 2.0.24] section 3.7.10 page 81.\nbool Texture::isCubeComplete() const\n{\n ASSERT(mTarget == GL_TEXTURE_CUBE_MAP);\n\n GLenum baseTarget = FirstCubeMapTextureTarget;\n size_t width = getWidth(baseTarget, 0);\n size_t height = getWidth(baseTarget, 0);\n if (width == 0 || width != height)\n {\n return false;\n }\n\n GLenum internalFormat = getInternalFormat(baseTarget, 0);\n for (GLenum face = baseTarget + 1; face <= LastCubeMapTextureTarget; face++)\n {\n if (getWidth(face, 0) != width ||\n getHeight(face, 0) != height ||\n getInternalFormat(face, 0) != internalFormat)\n {\n return false;\n }\n }\n\n return true;\n}\n\nunsigned int Texture::getTextureSerial() const\n{\n return mTextureSerial;\n}\n\nunsigned int Texture::issueTextureSerial()\n{\n return mCurrentTextureSerial++;\n}\n\nbool Texture::isImmutable() const\n{\n return (mImmutableLevelCount > 0);\n}\n\nint Texture::immutableLevelCount()\n{\n return mImmutableLevelCount;\n}\n\nError Texture::setImage(GLenum target, size_t level, GLenum internalFormat, const Extents &size, GLenum format, GLenum type,\n const PixelUnpackState &unpack, const uint8_t *pixels)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n Error error = mTexture->setImage(target, level, internalFormat, size, format, type, unpack, pixels);\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n setImageDesc(ImageIndex::MakeGeneric(target, level), ImageDesc(size, GetSizedInternalFormat(internalFormat, type)));\n\n return Error(GL_NO_ERROR);\n}\n\nError Texture::setSubImage(GLenum target, size_t level, const Box &area, GLenum format, GLenum type,\n const PixelUnpackState &unpack, const uint8_t *pixels)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n return mTexture->setSubImage(target, level, area, format, type, unpack, pixels);\n}\n\nError Texture::setCompressedImage(GLenum target, size_t level, GLenum internalFormat, const Extents &size,\n const PixelUnpackState &unpack, const uint8_t *pixels)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n Error error = mTexture->setCompressedImage(target, level, internalFormat, size, unpack, pixels);\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n setImageDesc(ImageIndex::MakeGeneric(target, level), ImageDesc(size, GetSizedInternalFormat(internalFormat, GL_UNSIGNED_BYTE)));\n\n return Error(GL_NO_ERROR);\n}\n\nError Texture::setCompressedSubImage(GLenum target, size_t level, const Box &area, GLenum format,\n const PixelUnpackState &unpack, const uint8_t *pixels)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n return mTexture->setCompressedSubImage(target, level, area, format, unpack, pixels);\n}\n\nError Texture::copyImage(GLenum target, size_t level, const Rectangle &sourceArea, GLenum internalFormat,\n const Framebuffer *source)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n Error error = mTexture->copyImage(target, level, sourceArea, internalFormat, source);\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n setImageDesc(ImageIndex::MakeGeneric(target, level), ImageDesc(Extents(sourceArea.width, sourceArea.height, 1),\n GetSizedInternalFormat(internalFormat, GL_UNSIGNED_BYTE)));\n\n return Error(GL_NO_ERROR);\n}\n\nError Texture::copySubImage(GLenum target, size_t level, const Offset &destOffset, const Rectangle &sourceArea,\n const Framebuffer *source)\n{\n ASSERT(target == mTarget || (mTarget == GL_TEXTURE_CUBE_MAP && IsCubeMapTextureTarget(target)));\n\n return mTexture->copySubImage(target, level, destOffset, sourceArea, source);\n}\n\nError Texture::setStorage(GLenum target, size_t levels, GLenum internalFormat, const Extents &size)\n{\n ASSERT(target == mTarget);\n\n Error error = mTexture->setStorage(target, levels, internalFormat, size);\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n mImmutableLevelCount = levels;\n clearImageDescs();\n setImageDescChain(levels, size, internalFormat);\n\n return Error(GL_NO_ERROR);\n}\n\n\nError Texture::generateMipmaps()\n{\n Error error = mTexture->generateMipmaps();\n if (error.isError())\n {\n return error;\n }\n\n releaseTexImage();\n\n ImageIndex baseLevel = ImageIndex::MakeGeneric(getBaseImageTarget(), 0);\n const ImageDesc &baseImageInfo = getImageDesc(baseLevel);\n size_t mipLevels = log2(std::max(std::max(baseImageInfo.size.width, baseImageInfo.size.height), baseImageInfo.size.depth)) + 1;\n setImageDescChain(mipLevels, baseImageInfo.size, baseImageInfo.internalFormat);\n\n return Error(GL_NO_ERROR);\n}\n\nvoid Texture::setImageDescChain(size_t levels, Extents baseSize, GLenum sizedInternalFormat)\n{\n for (size_t level = 0; level < levels; level++)\n {\n Extents levelSize(std::max<size_t>(baseSize.width >> level, 1),\n std::max<size_t>(baseSize.height >> level, 1),\n (mTarget == GL_TEXTURE_2D_ARRAY) ? baseSize.depth : std::max<size_t>(baseSize.depth >> level, 1));\n ImageDesc levelInfo(levelSize, sizedInternalFormat);\n\n if (mTarget == GL_TEXTURE_CUBE_MAP)\n {\n for (size_t face = FirstCubeMapTextureTarget; face <= LastCubeMapTextureTarget; face++)\n {\n setImageDesc(ImageIndex::MakeGeneric(face, level), levelInfo);\n }\n }\n else\n {\n setImageDesc(ImageIndex::MakeGeneric(mTarget, level), levelInfo);\n }\n }\n}\n\nTexture::ImageDesc::ImageDesc()\n : ImageDesc(Extents(0, 0, 0), GL_NONE)\n{\n}\n\nTexture::ImageDesc::ImageDesc(const Extents &size, GLenum internalFormat)\n : size(size),\n internalFormat(internalFormat)\n{\n}\n\nconst Texture::ImageDesc &Texture::getImageDesc(const ImageIndex &index) const\n{\n static const Texture::ImageDesc defaultDesc;\n ImageDescMap::const_iterator iter = mImageDescs.find(index);\n return (iter != mImageDescs.end()) ? iter->second : defaultDesc;\n}\n\nvoid Texture::setImageDesc(const ImageIndex &index, const ImageDesc &desc)\n{\n mImageDescs[index] = desc;\n}\n\nvoid Texture::clearImageDescs()\n{\n mImageDescs.clear();\n}\n\nvoid Texture::bindTexImage(egl::Surface *surface)\n{\n releaseTexImage();\n mTexture->bindTexImage(surface);\n mBoundSurface = surface;\n}\n\nvoid Texture::releaseTexImage()\n{\n if (mBoundSurface)\n {\n mBoundSurface = NULL;\n mTexture->releaseTexImage();\n }\n}\n\nGLenum Texture::getBaseImageTarget() const\n{\n return mTarget == GL_TEXTURE_CUBE_MAP ? FirstCubeMapTextureTarget : mTarget;\n}\n\nsize_t Texture::getExpectedMipLevels() const\n{\n GLenum baseTarget = getBaseImageTarget();\n size_t width = getWidth(baseTarget, 0);\n size_t height = getHeight(baseTarget, 0);\n if (mTarget == GL_TEXTURE_3D)\n {\n size_t depth = getDepth(baseTarget, 0);\n return log2(std::max(std::max(width, height), depth)) + 1;\n }\n else\n {\n return log2(std::max(width, height)) + 1;\n }\n}\n\nbool Texture::isMipmapComplete(const gl::SamplerState &samplerState) const\n{\n size_t expectedMipLevels = getExpectedMipLevels();\n\n size_t maxLevel = std::min<size_t>(expectedMipLevels, samplerState.maxLevel + 1);\n\n for (size_t level = samplerState.baseLevel; level < maxLevel; level++)\n {\n if (mTarget == GL_TEXTURE_CUBE_MAP)\n {\n for (GLenum face = FirstCubeMapTextureTarget; face <= LastCubeMapTextureTarget; face++)\n {\n if (!isLevelComplete(face, level, samplerState))\n {\n return false;\n }\n }\n }\n else\n {\n if (!isLevelComplete(mTarget, level, samplerState))\n {\n return false;\n }\n }\n }\n\n return true;\n}\n\n\nbool Texture::isLevelComplete(GLenum target, size_t level,\n const gl::SamplerState &samplerState) const\n{\n ASSERT(level < IMPLEMENTATION_MAX_TEXTURE_LEVELS);\n\n if (isImmutable())\n {\n return true;\n }\n\n size_t width = getWidth(target, samplerState.baseLevel);\n size_t height = getHeight(target, samplerState.baseLevel);\n size_t depth = getDepth(target, samplerState.baseLevel);\n if (width == 0 || height == 0 || depth == 0)\n {\n return false;\n }\n\n \/\/ The base image level is complete if the width and height are positive\n if (level == 0)\n {\n return true;\n }\n\n if (getInternalFormat(target, level) != getInternalFormat(target, samplerState.baseLevel))\n {\n return false;\n }\n\n if (getWidth(target, level) != std::max<size_t>(1, width >> level))\n {\n return false;\n }\n\n if (getHeight(target, level) != std::max<size_t>(1, height >> level))\n {\n return false;\n }\n\n if (mTarget == GL_TEXTURE_3D)\n {\n if (getDepth(target, level) != std::max<size_t>(1, depth >> level))\n {\n return false;\n }\n }\n else if (mTarget == GL_TEXTURE_2D_ARRAY)\n {\n if (getDepth(target, level) != depth)\n {\n return false;\n }\n }\n\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* The MIT License (MIT)\r\n * \r\n * Copyright (c) 2014 - 2015, Andreas Merkle\r\n * http:\/\/www.blue-andi.de\r\n * vscp@blue-andi.de\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n * \r\n *\/\r\n\r\n\/*******************************************************************************\r\n DESCRIPTION\r\n*******************************************************************************\/\r\n\/**\r\n@brief VSCP framework class\r\n@file VSCP.cpp\r\n@author Andreas Merkle, http:\/\/www.blue-andi.de\r\n\r\n@section desc Description\r\n@see VSCP.h\r\n\r\n@section svn Subversion\r\n$Author: amerkle $\r\n$Rev: 449 $\r\n$Date: 2015-01-05 20:23:52 +0100 (Mo, 05 Jan 2015) $\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n INCLUDES\r\n*******************************************************************************\/\r\n#include \"VSCP.h\"\r\n#include \"framework\/vscp_core.h\"\r\n#include \"framework\/vscp_portable.h\"\r\n#include \"framework\/vscp_timer.h\"\r\n#include \"framework\/vscp_dev_data.h\"\r\n#include \"framework\/vscp_tp_adapter.h\"\r\n#include \"framework\/vscp_action.h\"\r\n\r\n\/*******************************************************************************\r\n COMPILER SWITCHES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n CONSTANTS\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n MACROS\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n CLASSES, TYPES AND STRUCTURES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n PROTOTYPES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n LOCAL VARIABLES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n GLOBAL VARIABLES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n GLOBAL FUNCTIONS\r\n*******************************************************************************\/\r\n\r\nVSCP::VSCP() :\r\n mIsInitialized(false), \/* Call setup() later *\/\r\n mStatusLampPin(0), \/* Status Lamp pin *\/\r\n mInitButtonPin(0), \/* Segment initialization button pin *\/\r\n mStatusLampState(VSCP_LAMP_STATE_OFF), \/* Status lamp startup state is off *\/\r\n mStatusLampPeriod(200), \/* 200 ms status lamp blinking period *\/\r\n mStatusLampTimer(), \/* Status lamp timer for blinking *\/\r\n mVSCPTimerPeriod(250), \/* 250 ms VSCP timer period *\/\r\n mVSCPTimer() \/* Timer instance used to handle the VSCP framework timers *\/\r\n{\r\n return;\r\n}\r\n\r\nVSCP::~VSCP()\r\n{\r\n return;\r\n}\r\n\r\nvoid VSCP::setup(\r\n int statusLampPin,\r\n int initButtonPin,\r\n const VSCPGuid& guid, \r\n unsigned char zone,\r\n unsigned char subZone,\r\n TpRead tpReadFunc,\r\n TpWrite tpWriteFunc,\r\n ExecuteAction actionExecFunc)\r\n{\r\n unsigned char index = 0;\r\n vscp_dev_data_Container devData;\r\n\r\n \/* Configure the hardware *\/\r\n pinMode(mStatusLampPin, OUTPUT);\r\n pinMode(initButtonPin, INPUT);\r\n \r\n \/* Initialize the VSCP core and the user specific stuff. *\/\r\n (void)vscp_core_init();\r\n \r\n \/* Store device data *\/\r\n for(index = 0; index < VSCP_GUID_SIZE; ++index)\r\n {\r\n devData.guid[index] = guid[index];\r\n }\r\n devData.zone = zone;\r\n devData.subZone = subZone;\r\n vscp_dev_data_set(&devData);\r\n \r\n \/* Setup transport layer *\/\r\n vscp_tp_adapter_set(tpReadFunc, tpWriteFunc);\r\n \r\n \/* Setup action *\/\r\n vscp_action_set(actionExecFunc);\r\n \r\n \/* Start VSCP timer *\/\r\n mVSCPTimer.start(mVSCPTimerPeriod, false);\r\n \r\n \/* Framework is now ready *\/\r\n mIsInitialized = true;\r\n \r\n return;\r\n}\r\n\r\nvoid VSCP::restoreFactoryDefaultSettings(void)\r\n{\r\n if (true == mIsInitialized)\r\n {\r\n vscp_core_restoreFactoryDefaultSettings();\r\n }\r\n \r\n return;\r\n}\r\n\r\nvoid VSCP::process(void)\r\n{\r\n if (true == mIsInitialized)\r\n {\r\n \/* Process the whole framework *\/\r\n vscp_core_process();\r\n \r\n \/* Process all member timers *\/\r\n mStatusLampTimer.process();\r\n mVSCPTimer.process();\r\n \r\n \/* Process all VSCP framework timers *\/\r\n if (true == mVSCPTimer.isTimeout())\r\n {\r\n vscp_timer_process(mVSCPTimerPeriod);\r\n }\r\n \r\n \/* Process the status lamp *\/\r\n processStatusLamp();\r\n \r\n \/* Handle segment initialization button *\/\r\n if (HIGH == digitalRead(mInitButtonPin))\r\n {\r\n vscp_core_startNodeSegmentInit();\r\n }\r\n }\r\n \r\n return;\r\n}\r\n\r\nuint8_t VSCP::readNicknameId(void)\r\n{\r\n unsigned char nicknameId = VSCP_NICKNAME_NOT_INIT;\r\n \r\n if (true == mIsInitialized)\r\n {\r\n nicknameId = vscp_core_readNicknameId();\r\n }\r\n \r\n return nicknameId;\r\n}\r\n\r\nvoid VSCP::startNodeSegmentInit(void)\r\n{\r\n if (true == mIsInitialized)\r\n {\r\n vscp_core_startNodeSegmentInit();\r\n }\r\n \r\n return;\r\n}\r\n\r\nvoid VSCP::setAlarm(unsigned char value)\r\n{\r\n if (true == mIsInitialized)\r\n {\r\n vscp_core_setAlarm(value);\r\n }\r\n \r\n return;\r\n}\r\n\r\nbool VSCP::isActive(void)\r\n{\r\n bool status = false;\r\n\r\n if (TRUE == mIsInitialized)\r\n {\r\n if (FALSE != vscp_core_isActive())\r\n {\r\n status = true;\r\n }\r\n }\r\n \r\n return status;\r\n}\r\n\r\nvoid VSCP::prepareTxMessage(vscp_TxMessage& txMessage, unsigned int vscpClass, unsigned char vscpType, VSCP_PRIORITY priority)\r\n{\r\n vscp_core_prepareTxMessage(&txMessage, vscpClass, vscpType, priority);\r\n return;\r\n}\r\n\r\nbool VSCP::write(const vscp_TxMessage& txMessage)\r\n{\r\n bool status = false;\r\n\r\n if (TRUE == mIsInitialized)\r\n {\r\n status = vscp_core_sendEvent(&txMessage);\r\n }\r\n \r\n return status;\r\n}\r\n\r\nbool VSCP::read(vscp_RxMessage& msg)\r\n{\r\n bool status = false;\r\n\r\n if (TRUE == mIsInitialized)\r\n {\r\n status = vscp_portable_read(&msg);\r\n }\r\n \r\n return status;\r\n}\r\n\r\n\/*******************************************************************************\r\n LOCAL FUNCTIONS\r\n*******************************************************************************\/\r\n\r\nvoid VSCP::processStatusLamp(void)\r\n{\r\n VSCP_LAMP_STATE statusLampState = vscp_portable_getLampState();\r\n \r\n \/* Lamp state changed? *\/\r\n if (mStatusLampState != statusLampState)\r\n {\r\n mStatusLampState = statusLampState;\r\n \r\n switch(mStatusLampState)\r\n {\r\n case VSCP_LAMP_STATE_OFF:\r\n digitalWrite(mStatusLampPin, LOW);\r\n break;\r\n\r\n case VSCP_LAMP_STATE_ON:\r\n digitalWrite(mStatusLampPin, HIGH);\r\n break;\r\n\r\n case VSCP_LAMP_STATE_BLINK:\r\n mStatusLampTimer.start(mStatusLampPeriod, false);\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n }\r\n \/* Shall the lamp blink? *\/\r\n else if (VSCP_LAMP_STATE_BLINK == mStatusLampState)\r\n {\r\n \/* Toggle status lamp? *\/\r\n if (true == mStatusLampTimer.isTimeout())\r\n {\r\n int statusLampPinState = digitalRead(mStatusLampPin);\r\n \r\n if (LOW == statusLampPinState)\r\n {\r\n statusLampPinState = HIGH;\r\n }\r\n else\r\n {\r\n statusLampPinState = LOW;\r\n }\r\n \r\n digitalWrite(mStatusLampPin, statusLampPinState);\r\n }\r\n }\r\n \r\n return;\r\n}\r\n<commit_msg>Hardware configuration fixed.<commit_after>\/* The MIT License (MIT)\r\n * \r\n * Copyright (c) 2014 - 2015, Andreas Merkle\r\n * http:\/\/www.blue-andi.de\r\n * vscp@blue-andi.de\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n * \r\n *\/\r\n\r\n\/*******************************************************************************\r\n DESCRIPTION\r\n*******************************************************************************\/\r\n\/**\r\n@brief VSCP framework class\r\n@file VSCP.cpp\r\n@author Andreas Merkle, http:\/\/www.blue-andi.de\r\n\r\n@section desc Description\r\n@see VSCP.h\r\n\r\n@section svn Subversion\r\n$Author: amerkle $\r\n$Rev: 449 $\r\n$Date: 2015-01-05 20:23:52 +0100 (Mo, 05 Jan 2015) $\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n INCLUDES\r\n*******************************************************************************\/\r\n#include \"VSCP.h\"\r\n#include \"framework\/vscp_core.h\"\r\n#include \"framework\/vscp_portable.h\"\r\n#include \"framework\/vscp_timer.h\"\r\n#include \"framework\/vscp_dev_data.h\"\r\n#include \"framework\/vscp_tp_adapter.h\"\r\n#include \"framework\/vscp_action.h\"\r\n\r\n\/*******************************************************************************\r\n COMPILER SWITCHES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n CONSTANTS\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n MACROS\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n CLASSES, TYPES AND STRUCTURES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n PROTOTYPES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n LOCAL VARIABLES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n GLOBAL VARIABLES\r\n*******************************************************************************\/\r\n\r\n\/*******************************************************************************\r\n GLOBAL FUNCTIONS\r\n*******************************************************************************\/\r\n\r\nVSCP::VSCP() :\r\n mIsInitialized(false), \/* Call setup() later *\/\r\n mStatusLampPin(0), \/* Status Lamp pin *\/\r\n mInitButtonPin(0), \/* Segment initialization button pin *\/\r\n mStatusLampState(VSCP_LAMP_STATE_OFF), \/* Status lamp startup state is off *\/\r\n mStatusLampPeriod(200), \/* 200 ms status lamp blinking period *\/\r\n mStatusLampTimer(), \/* Status lamp timer for blinking *\/\r\n mVSCPTimerPeriod(250), \/* 250 ms VSCP timer period *\/\r\n mVSCPTimer() \/* Timer instance used to handle the VSCP framework timers *\/\r\n{\r\n return;\r\n}\r\n\r\nVSCP::~VSCP()\r\n{\r\n return;\r\n}\r\n\r\nvoid VSCP::setup(\r\n int statusLampPin,\r\n int initButtonPin,\r\n const VSCPGuid& guid, \r\n unsigned char zone,\r\n unsigned char subZone,\r\n TpRead tpReadFunc,\r\n TpWrite tpWriteFunc,\r\n ExecuteAction actionExecFunc)\r\n{\r\n unsigned char index = 0;\r\n vscp_dev_data_Container devData;\r\n\r\n \/* Configure the hardware *\/\r\n pinMode(statusLampPin, OUTPUT);\r\n pinMode(initButtonPin, INPUT_PULLUP);\r\n \r\n mStatusLampPin = statusLampPin;\r\n mInitButtonPin = initButtonPin;\r\n \r\n \/* Initialize the VSCP core and the user specific stuff. *\/\r\n (void)vscp_core_init();\r\n \r\n \/* Store device data *\/\r\n for(index = 0; index < VSCP_GUID_SIZE; ++index)\r\n {\r\n devData.guid[index] = guid[index];\r\n }\r\n devData.zone = zone;\r\n devData.subZone = subZone;\r\n vscp_dev_data_set(&devData);\r\n \r\n \/* Setup transport layer *\/\r\n vscp_tp_adapter_set(tpReadFunc, tpWriteFunc);\r\n \r\n \/* Setup action *\/\r\n vscp_action_set(actionExecFunc);\r\n \r\n \/* Start VSCP timer *\/\r\n mVSCPTimer.start(mVSCPTimerPeriod, false);\r\n \r\n \/* Framework is now ready *\/\r\n mIsInitialized = true;\r\n \r\n return;\r\n}\r\n\r\nvoid VSCP::restoreFactoryDefaultSettings(void)\r\n{\r\n if (true == mIsInitialized)\r\n {\r\n vscp_core_restoreFactoryDefaultSettings();\r\n }\r\n \r\n return;\r\n}\r\n\r\nvoid VSCP::process(void)\r\n{\r\n if (true == mIsInitialized)\r\n {\r\n \/* Process the whole framework *\/\r\n vscp_core_process();\r\n \r\n \/* Process all member timers *\/\r\n mStatusLampTimer.process();\r\n mVSCPTimer.process();\r\n \r\n \/* Process all VSCP framework timers *\/\r\n if (true == mVSCPTimer.isTimeout())\r\n {\r\n vscp_timer_process(mVSCPTimerPeriod);\r\n }\r\n \r\n \/* Process the status lamp *\/\r\n processStatusLamp();\r\n \r\n \/* Handle segment initialization button *\/\r\n if (LOW == digitalRead(mInitButtonPin))\r\n {\r\n vscp_core_startNodeSegmentInit();\r\n }\r\n }\r\n \r\n return;\r\n}\r\n\r\nuint8_t VSCP::readNicknameId(void)\r\n{\r\n unsigned char nicknameId = VSCP_NICKNAME_NOT_INIT;\r\n \r\n if (true == mIsInitialized)\r\n {\r\n nicknameId = vscp_core_readNicknameId();\r\n }\r\n \r\n return nicknameId;\r\n}\r\n\r\nvoid VSCP::startNodeSegmentInit(void)\r\n{\r\n if (true == mIsInitialized)\r\n {\r\n vscp_core_startNodeSegmentInit();\r\n }\r\n \r\n return;\r\n}\r\n\r\nvoid VSCP::setAlarm(unsigned char value)\r\n{\r\n if (true == mIsInitialized)\r\n {\r\n vscp_core_setAlarm(value);\r\n }\r\n \r\n return;\r\n}\r\n\r\nbool VSCP::isActive(void)\r\n{\r\n bool status = false;\r\n\r\n if (TRUE == mIsInitialized)\r\n {\r\n if (FALSE != vscp_core_isActive())\r\n {\r\n status = true;\r\n }\r\n }\r\n \r\n return status;\r\n}\r\n\r\nvoid VSCP::prepareTxMessage(vscp_TxMessage& txMessage, unsigned int vscpClass, unsigned char vscpType, VSCP_PRIORITY priority)\r\n{\r\n vscp_core_prepareTxMessage(&txMessage, vscpClass, vscpType, priority);\r\n return;\r\n}\r\n\r\nbool VSCP::write(const vscp_TxMessage& txMessage)\r\n{\r\n bool status = false;\r\n\r\n if (TRUE == mIsInitialized)\r\n {\r\n status = vscp_core_sendEvent(&txMessage);\r\n }\r\n \r\n return status;\r\n}\r\n\r\nbool VSCP::read(vscp_RxMessage& msg)\r\n{\r\n bool status = false;\r\n\r\n if (TRUE == mIsInitialized)\r\n {\r\n status = vscp_portable_read(&msg);\r\n }\r\n \r\n return status;\r\n}\r\n\r\n\/*******************************************************************************\r\n LOCAL FUNCTIONS\r\n*******************************************************************************\/\r\n\r\nvoid VSCP::processStatusLamp(void)\r\n{\r\n VSCP_LAMP_STATE statusLampState = vscp_portable_getLampState();\r\n \r\n \/* Lamp state changed? *\/\r\n if (mStatusLampState != statusLampState)\r\n {\r\n mStatusLampState = statusLampState;\r\n \r\n switch(mStatusLampState)\r\n {\r\n case VSCP_LAMP_STATE_OFF:\r\n digitalWrite(mStatusLampPin, LOW);\r\n break;\r\n\r\n case VSCP_LAMP_STATE_ON:\r\n digitalWrite(mStatusLampPin, HIGH);\r\n break;\r\n\r\n case VSCP_LAMP_STATE_BLINK:\r\n mStatusLampTimer.start(mStatusLampPeriod, false);\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n }\r\n \/* Shall the lamp blink? *\/\r\n else if (VSCP_LAMP_STATE_BLINK == mStatusLampState)\r\n {\r\n \/* Toggle status lamp? *\/\r\n if (true == mStatusLampTimer.isTimeout())\r\n {\r\n int statusLampPinState = digitalRead(mStatusLampPin);\r\n \r\n if (LOW == statusLampPinState)\r\n {\r\n statusLampPinState = HIGH;\r\n }\r\n else\r\n {\r\n statusLampPinState = LOW;\r\n }\r\n \r\n digitalWrite(mStatusLampPin, statusLampPinState);\r\n }\r\n }\r\n \r\n return;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_OPERATORS_ELLIPTIC_CG_HH\n#define DUNE_GDT_OPERATORS_ELLIPTIC_CG_HH\n\n#include <type_traits>\n\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n#include <dune\/stuff\/functions\/interfaces.hh>\n#include <dune\/stuff\/common\/memory.hh>\n\n#include <dune\/gdt\/spaces\/interface.hh>\n#include <dune\/gdt\/localevaluation\/elliptic.hh>\n#include <dune\/gdt\/localoperator\/codim0.hh>\n#include <dune\/gdt\/assembler\/local\/codim0.hh>\n#include <dune\/gdt\/assembler\/system.hh>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Operators {\n\n\n\/\/ forwards\ntemplate <class DiffusionFactorType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp,\n class GridViewImp = typename SourceSpaceImp::GridViewType, class DiffusionTensorType = void>\nclass EllipticCG;\n\n\nnamespace internal {\n\n\ntemplate <class DiffusionFactorType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp,\n class DiffusionTensorType = void>\nclass EllipticCGTraits\n{\n static_assert(std::is_base_of<Stuff::Tags::LocalizableFunction, DiffusionFactorType>::value,\n \"DiffusionFactorType has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(std::is_base_of<Stuff::Tags::LocalizableFunction, DiffusionTensorType>::value\n || std::is_same<void, DiffusionTensorType>::value,\n \"DiffusionTensorType has to be void or derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(\n std::is_base_of<Stuff::LA::MatrixInterface<typename MatrixImp::Traits, typename MatrixImp::Traits::ScalarType>,\n MatrixImp>::value,\n \"MatrixImp has to be derived from Stuff::LA::MatrixInterface!\");\n static_assert(std::is_base_of<SpaceInterface<typename SourceSpaceImp::Traits>, SourceSpaceImp>::value,\n \"SourceSpaceImp has to be derived from SpaceInterface!\");\n static_assert(std::is_base_of<SpaceInterface<typename RangeSpaceImp::Traits>, RangeSpaceImp>::value,\n \"RangeSpaceImp has to be derived from SpaceInterface!\");\n\npublic:\n typedef EllipticCG<DiffusionFactorType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, DiffusionTensorType>\n derived_type;\n typedef MatrixImp MatrixType;\n typedef SourceSpaceImp SourceSpaceType;\n typedef RangeSpaceImp RangeSpaceType;\n typedef GridViewImp GridViewType;\n}; \/\/ class EllipticCGTraits\n\n} \/\/ namespace internal\n\n\ntemplate <class DiffusionType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp>\nclass EllipticCG<DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void>\n : public Operators::MatrixBased<internal::EllipticCGTraits<DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp,\n GridViewImp, void>>,\n public SystemAssembler<RangeSpaceImp, GridViewImp, SourceSpaceImp>\n{\n typedef SystemAssembler<RangeSpaceImp, GridViewImp, SourceSpaceImp> AssemblerBaseType;\n typedef Operators::MatrixBased<internal::EllipticCGTraits<DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp,\n GridViewImp>> OperatorBaseType;\n typedef LocalOperator::Codim0Integral<LocalEvaluation::Elliptic<DiffusionType>> LocalOperatorType;\n typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType;\n\npublic:\n typedef internal::EllipticCGTraits<DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void> Traits;\n\n typedef typename Traits::MatrixType MatrixType;\n typedef typename Traits::SourceSpaceType SourceSpaceType;\n typedef typename Traits::RangeSpaceType RangeSpaceType;\n typedef typename Traits::GridViewType GridViewType;\n\n using OperatorBaseType::pattern;\n\n static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,\n const SourceSpaceType& source_space, const GridViewType& grid_view)\n {\n return range_space.compute_volume_pattern(grid_view, source_space);\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space,\n const RangeSpaceType& range_space, const GridViewType& grid_view)\n : OperatorBaseType(matrix, source_space, range_space, grid_view)\n , AssemblerBaseType(range_space, grid_view, source_space)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& mtrx, const SourceSpaceType& src_spc,\n const RangeSpaceType& rng_spc)\n : OperatorBaseType(mtrx, src_spc, rng_spc)\n , AssemblerBaseType(rng_spc, src_spc)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& mtrx, const SourceSpaceType& src_spc)\n : OperatorBaseType(mtrx, src_spc)\n , AssemblerBaseType(src_spc)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n virtual ~EllipticCG()\n {\n }\n\n virtual void assemble() override final\n {\n AssemblerBaseType::assemble();\n }\n\nprivate:\n const DiffusionType& diffusion_;\n const LocalOperatorType local_operator_;\n const LocalAssemblerType local_assembler_;\n}; \/\/ class EllipticCG\n\n\n} \/\/ namespace Operators\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_OPERATORS_ELLIPTIC_CG_HH\n<commit_msg>[operators.elliptic-cg] use storage provider<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_OPERATORS_ELLIPTIC_CG_HH\n#define DUNE_GDT_OPERATORS_ELLIPTIC_CG_HH\n\n#include <type_traits>\n\n#include <dune\/stuff\/common\/memory.hh>\n#include <dune\/stuff\/functions\/interfaces.hh>\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n\n#include <dune\/gdt\/spaces\/interface.hh>\n#include <dune\/gdt\/localevaluation\/elliptic.hh>\n#include <dune\/gdt\/localoperator\/codim0.hh>\n#include <dune\/gdt\/assembler\/local\/codim0.hh>\n#include <dune\/gdt\/assembler\/system.hh>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Operators {\n\n\n\/\/ forwards\ntemplate <class DiffusionFactorType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp,\n class GridViewImp = typename SourceSpaceImp::GridViewType, class DiffusionTensorType = void>\nclass EllipticCG;\n\n\nnamespace internal {\n\n\ntemplate <class DiffusionFactorType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp,\n class DiffusionTensorType = void>\nclass EllipticCGTraits\n{\n static_assert(std::is_base_of<Stuff::Tags::LocalizableFunction, DiffusionFactorType>::value,\n \"DiffusionFactorType has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(std::is_base_of<Stuff::Tags::LocalizableFunction, DiffusionTensorType>::value\n || std::is_same<void, DiffusionTensorType>::value,\n \"DiffusionTensorType has to be void or derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(\n std::is_base_of<Stuff::LA::MatrixInterface<typename MatrixImp::Traits, typename MatrixImp::Traits::ScalarType>,\n MatrixImp>::value,\n \"MatrixImp has to be derived from Stuff::LA::MatrixInterface!\");\n static_assert(std::is_base_of<SpaceInterface<typename SourceSpaceImp::Traits>, SourceSpaceImp>::value,\n \"SourceSpaceImp has to be derived from SpaceInterface!\");\n static_assert(std::is_base_of<SpaceInterface<typename RangeSpaceImp::Traits>, RangeSpaceImp>::value,\n \"RangeSpaceImp has to be derived from SpaceInterface!\");\n\npublic:\n typedef EllipticCG<DiffusionFactorType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, DiffusionTensorType>\n derived_type;\n typedef MatrixImp MatrixType;\n typedef SourceSpaceImp SourceSpaceType;\n typedef RangeSpaceImp RangeSpaceType;\n typedef GridViewImp GridViewType;\n}; \/\/ class EllipticCGTraits\n\n} \/\/ namespace internal\n\n\ntemplate <class DiffusionType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp>\nclass EllipticCG<DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void>\n : Stuff::Common::StorageProvider<MatrixImp>,\n public Operators::MatrixBased<internal::EllipticCGTraits<DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp,\n GridViewImp, void>>,\n public SystemAssembler<RangeSpaceImp, GridViewImp, SourceSpaceImp>\n{\n typedef Stuff::Common::StorageProvider<MatrixImp> StorageProvider;\n typedef SystemAssembler<RangeSpaceImp, GridViewImp, SourceSpaceImp> AssemblerBaseType;\n typedef Operators::MatrixBased<internal::EllipticCGTraits<DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp,\n GridViewImp>> OperatorBaseType;\n typedef LocalOperator::Codim0Integral<LocalEvaluation::Elliptic<DiffusionType>> LocalOperatorType;\n typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType;\n\npublic:\n typedef internal::EllipticCGTraits<DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void> Traits;\n\n typedef typename Traits::MatrixType MatrixType;\n typedef typename Traits::SourceSpaceType SourceSpaceType;\n typedef typename Traits::RangeSpaceType RangeSpaceType;\n typedef typename Traits::GridViewType GridViewType;\n\n using OperatorBaseType::pattern;\n\n static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,\n const SourceSpaceType& source_space, const GridViewType& grid_view)\n {\n return range_space.compute_volume_pattern(grid_view, source_space);\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& mtrx, const SourceSpaceType& src_spc,\n const RangeSpaceType& rng_spc, const GridViewType& grid_view)\n : StorageProvider(mtrx)\n , OperatorBaseType(this->storage_access(), src_spc, rng_spc, grid_view)\n , AssemblerBaseType(rng_spc, grid_view, src_spc)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n , assembled_(false)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n EllipticCG(const DiffusionType& diffusion, const SourceSpaceType& src_spc, const RangeSpaceType& rng_spc,\n const GridViewType& grid_view)\n : StorageProvider(\n new MatrixType(rng_spc.mapper().size(), src_spc.mapper().size(), pattern(rng_spc, src_spc, grid_view)))\n , OperatorBaseType(this->storage_access(), src_spc, rng_spc, grid_view)\n , AssemblerBaseType(rng_spc, grid_view, src_spc)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n , assembled_(false)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& mtrx, const SourceSpaceType& src_spc,\n const RangeSpaceType& rng_spc)\n : StorageProvider(mtrx)\n , OperatorBaseType(this->storage_access(), src_spc, rng_spc)\n , AssemblerBaseType(rng_spc, src_spc)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n , assembled_(false)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n EllipticCG(const DiffusionType& diffusion, const SourceSpaceType& src_spc, const RangeSpaceType& rng_spc)\n : StorageProvider(new MatrixType(rng_spc.mapper().size(), src_spc.mapper().size(), pattern(rng_spc, src_spc)))\n , OperatorBaseType(this->storage_access(), src_spc, rng_spc)\n , AssemblerBaseType(rng_spc, src_spc)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n , assembled_(false)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& mtrx, const SourceSpaceType& src_spc)\n : StorageProvider(mtrx)\n , OperatorBaseType(this->storage_access(), src_spc)\n , AssemblerBaseType(src_spc)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n , assembled_(false)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n EllipticCG(const DiffusionType& diffusion, const SourceSpaceType& src_spc)\n : StorageProvider(new MatrixType(src_spc.mapper().size(), src_spc.mapper().size(), pattern(src_spc)))\n , OperatorBaseType(this->storage_access(), src_spc)\n , AssemblerBaseType(src_spc)\n , diffusion_(diffusion)\n , local_operator_(diffusion_)\n , local_assembler_(local_operator_)\n , assembled_(false)\n {\n this->add(local_assembler_, this->matrix());\n }\n\n virtual ~EllipticCG()\n {\n }\n\n virtual void assemble() override final\n {\n if (!assembled_) {\n AssemblerBaseType::assemble(true);\n assembled_ = true;\n }\n } \/\/ ... assemble(...)\n\nprivate:\n const DiffusionType& diffusion_;\n const LocalOperatorType local_operator_;\n const LocalAssemblerType local_assembler_;\n bool assembled_;\n}; \/\/ class EllipticCG\n\n\n} \/\/ namespace Operators\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_OPERATORS_ELLIPTIC_CG_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/===- CallGraph.cpp - Build a Module's call graph ------------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This interface is used to build and manipulate a call graph, which is a very \n\/\/ useful tool for interprocedural optimization.\n\/\/\n\/\/ Every function in a module is represented as a node in the call graph. The\n\/\/ callgraph node keeps track of which functions the are called by the function\n\/\/ corresponding to the node.\n\/\/\n\/\/ A call graph will contain nodes where the function that they correspond to is\n\/\/ null. This 'external' node is used to represent control flow that is not\n\/\/ represented (or analyzable) in the module. As such, the external node will\n\/\/ have edges to functions with the following properties:\n\/\/ 1. All functions in the module without internal linkage, since they could\n\/\/ be called by functions outside of the our analysis capability.\n\/\/ 2. All functions whose address is used for something more than a direct\n\/\/ call, for example being stored into a memory location. Since they may\n\/\/ be called by an unknown caller later, they must be tracked as such.\n\/\/\n\/\/ Similarly, functions have a call edge to the external node iff:\n\/\/ 1. The function is external, reflecting the fact that they could call\n\/\/ anything without internal linkage or that has its address taken.\n\/\/ 2. The function contains an indirect function call.\n\/\/\n\/\/ As an extension in the future, there may be multiple nodes with a null\n\/\/ function. These will be used when we can prove (through pointer analysis)\n\/\/ that an indirect call site can call only a specific set of functions.\n\/\/\n\/\/ Because of these properties, the CallGraph captures a conservative superset\n\/\/ of all of the caller-callee relationships, which is useful for\n\/\/ transformations.\n\/\/\n\/\/ The CallGraph class also attempts to figure out what the root of the\n\/\/ CallGraph is, which is currently does by looking for a function named 'main'.\n\/\/ If no function named 'main' is found, the external node is used as the entry\n\/\/ node, reflecting the fact that any function without internal linkage could\n\/\/ be called into (which is common for libraries).\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Constants.h\" \/\/ Remove when ConstantPointerRefs are gone\n#include \"llvm\/Module.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"Support\/STLExtras.h\"\n\nstatic RegisterAnalysis<CallGraph> X(\"callgraph\", \"Call Graph Construction\");\n\nstatic const char * const KnownExternalFunctions[] = {\n \/\/ Low-level system calls\n \"open\",\n \"read\",\n \"write\",\n \"writev\",\n \"lseek\",\n \"poll\",\n \"ioctl\",\n\n \/\/ Low-level stdc library functions\n \"abort\",\n \"getenv\",\n \"putenv\",\n \n \/\/ Standard IO functions\n \"printf\",\n \"sprintf\",\n \"fopen\",\n \"freopen\",\n \"fclose\",\n \"fwrite\",\n \"puts\",\n \"fputs\",\n \"getc\",\n \"ungetc\",\n \"putc\",\n \"putchar\",\n \"fread\",\n \"fileno\",\n \"ftell\",\n \"fflush\",\n \"fseek\",\n \"fileno\",\n \"ferror\",\n \"feof\",\n \"fdopen\",\n \"__fxstat\",\n \"setbuf\",\n \"setbuffer\",\n \"etlinebuf\",\n \"setvbuf\",\n\n \/\/ Memory functions\n \"malloc\",\n \"free\",\n \"realloc\",\n \"calloc\",\n \"memalign\",\n \n \/\/ String functions\n \"atoi\",\n \"memmove\",\n \"memset\",\n \"memchr\",\n \"memcmp\",\n \"strchr\",\n \"strncpy\",\n \"strncmp\",\n \"strcmp\",\n \"__strcoll_l\",\n \"__strxfrm_l\",\n \"__strftime_l\",\n \"__strtol_l\",\n \"__strtoul_l\",\n \"__strtoll_l\",\n \"__strtoull_l\",\n \"__strtof_l\",\n \"__strtod_l\",\n \"__strtold_l\",\n\n \/\/ Locale functions\n \"__uselocale\",\n \"__newlocale\",\n \"__freelocale\",\n \"__duplocale\",\n \"__nl_langinfo_l\",\n\n \/\/ gettext functions used by libstdc++\n \"gettext\",\n \"dgettext\",\n \"dcgettext\",\n \"textdomain\",\n \"bindtextdomain\",\n \n \/\/ Random stuff\n \"__assert_fail\",\n \"__errno_location\",\n};\n\n\n\/\/\/ ExternalFunctionDoesntCallIntoProgram - This hack is used to indicate to the\n\/\/\/ call graph that the specified external function is _KNOWN_ to not call back\n\/\/\/ into the program. This is important, because otherwise functions which call\n\/\/\/ \"printf\" for example, end up in a great big SCC that goes from the function\n\/\/\/ through main.\n\/\/\/\nstatic bool ExternalFunctionDoesntCallIntoProgram(const std::string &Name) {\n static std::vector<std::string> Funcs;\n\n \/\/ First time this is called?\n if (Funcs.empty()) {\n \/\/ Add a whole bunch of functions which are often used...\n Funcs.insert(Funcs.end(), KnownExternalFunctions,\n KnownExternalFunctions+\n sizeof(KnownExternalFunctions)\/sizeof(KnownExternalFunctions[0]));\n \/\/ Sort the list for efficient access\n std::sort(Funcs.begin(), Funcs.end());\n }\n\n \/\/ Binary search for the function name...\n std::vector<std::string>::iterator I =\n std::lower_bound(Funcs.begin(), Funcs.end(), Name);\n\n \/\/ Found it?\n return I != Funcs.end() && *I == Name;\n}\n\n\n\n\/\/ getNodeFor - Return the node for the specified function or create one if it\n\/\/ does not already exist.\n\/\/\nCallGraphNode *CallGraph::getNodeFor(Function *F) {\n CallGraphNode *&CGN = FunctionMap[F];\n if (CGN) return CGN;\n\n assert((!F || F->getParent() == Mod) && \"Function not in current module!\");\n return CGN = new CallGraphNode(F);\n}\n\nstatic bool isOnlyADirectCall(Function *F, CallSite CS) {\n if (!CS.getInstruction()) return false;\n for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)\n if (*I == F) return false;\n return true;\n}\n\n\/\/ addToCallGraph - Add a function to the call graph, and link the node to all\n\/\/ of the functions that it calls.\n\/\/\nvoid CallGraph::addToCallGraph(Function *F) {\n CallGraphNode *Node = getNodeFor(F);\n\n \/\/ If this function has external linkage, anything could call it...\n if (!F->hasInternalLinkage()) {\n ExternalNode->addCalledFunction(Node);\n\n \/\/ Found the entry point?\n if (F->getName() == \"main\") {\n if (Root)\n Root = ExternalNode; \/\/ Found multiple external mains? Don't pick one.\n else\n Root = Node; \/\/ Found a main, keep track of it!\n }\n }\n \n \/\/ If this function is not defined in this translation unit, it could call\n \/\/ anything.\n if (F->isExternal() && !F->getIntrinsicID() && \n !ExternalFunctionDoesntCallIntoProgram(F->getName()))\n Node->addCalledFunction(ExternalNode);\n\n \/\/ Loop over all of the users of the function... looking for callers...\n \/\/\n bool isUsedExternally = false;\n for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I) {\n if (Instruction *Inst = dyn_cast<Instruction>(*I)) {\n if (isOnlyADirectCall(F, CallSite::get(Inst)))\n getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);\n else\n isUsedExternally = true;\n } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I)) {\n \/\/ THIS IS A DISGUSTING HACK. Brought to you by the power of\n \/\/ ConstantPointerRefs!\n for (Value::use_iterator I = CPR->use_begin(), E = CPR->use_end();\n I != E; ++I)\n if (Instruction *Inst = dyn_cast<Instruction>(*I)) {\n if (isOnlyADirectCall(F, CallSite::get(Inst)))\n getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);\n else\n isUsedExternally = true;\n } else {\n isUsedExternally = true;\n }\n } else { \/\/ Can't classify the user!\n isUsedExternally = true;\n }\n }\n if (isUsedExternally)\n ExternalNode->addCalledFunction(Node);\n\n \/\/ Look for an indirect function call...\n for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)\n for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){\n CallSite CS = CallSite::get(II);\n if (CS.getInstruction() && !CS.getCalledFunction())\n Node->addCalledFunction(ExternalNode);\n }\n}\n\nbool CallGraph::run(Module &M) {\n destroy();\n\n Mod = &M;\n ExternalNode = getNodeFor(0);\n Root = 0;\n\n \/\/ Add every function to the call graph...\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n addToCallGraph(I);\n\n \/\/ If we didn't find a main function, use the external call graph node\n if (Root == 0) Root = ExternalNode;\n \n return false;\n}\n\nvoid CallGraph::destroy() {\n for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();\n I != E; ++I)\n delete I->second;\n FunctionMap.clear();\n}\n\nstatic void WriteToOutput(const CallGraphNode *CGN, std::ostream &o) {\n if (CGN->getFunction())\n o << \"Call graph node for function: '\"\n << CGN->getFunction()->getName() <<\"'\\n\";\n else\n o << \"Call graph node <<null function: 0x\" << CGN << \">>:\\n\";\n\n for (unsigned i = 0; i < CGN->size(); ++i)\n if ((*CGN)[i]->getFunction())\n o << \" Calls function '\" << (*CGN)[i]->getFunction()->getName() << \"'\\n\";\n else\n o << \" Calls external node\\n\";\n o << \"\\n\";\n}\n\nvoid CallGraph::print(std::ostream &o, const Module *M) const {\n o << \"CallGraph Root is: \";\n if (getRoot()->getFunction())\n o << getRoot()->getFunction()->getName() << \"\\n\";\n else\n o << \"<<null function: 0x\" << getRoot() << \">>\\n\";\n \n for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)\n WriteToOutput(I->second, o);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Implementations of public modification methods\n\/\/\n\n\/\/ Functions to keep a call graph up to date with a function that has been\n\/\/ modified\n\/\/\nvoid CallGraph::addFunctionToModule(Function *Meth) {\n assert(0 && \"not implemented\");\n abort();\n}\n\n\/\/ removeFunctionFromModule - Unlink the function from this module, returning\n\/\/ it. Because this removes the function from the module, the call graph node\n\/\/ is destroyed. This is only valid if the function does not call any other\n\/\/ functions (ie, there are no edges in it's CGN). The easiest way to do this\n\/\/ is to dropAllReferences before calling this.\n\/\/\nFunction *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {\n assert(CGN->CalledFunctions.empty() && \"Cannot remove function from call \"\n \"graph if it references other functions!\");\n Function *F = CGN->getFunction(); \/\/ Get the function for the call graph node\n delete CGN; \/\/ Delete the call graph node for this func\n FunctionMap.erase(F); \/\/ Remove the call graph node from the map\n\n Mod->getFunctionList().remove(F);\n return F;\n}\n\nvoid CallGraph::stub() {}\n<commit_msg>None of the __llvm_* functions call into the program. This makes the callgraph MUCH simpler for eh using program.<commit_after>\/\/===- CallGraph.cpp - Build a Module's call graph ------------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This interface is used to build and manipulate a call graph, which is a very \n\/\/ useful tool for interprocedural optimization.\n\/\/\n\/\/ Every function in a module is represented as a node in the call graph. The\n\/\/ callgraph node keeps track of which functions the are called by the function\n\/\/ corresponding to the node.\n\/\/\n\/\/ A call graph will contain nodes where the function that they correspond to is\n\/\/ null. This 'external' node is used to represent control flow that is not\n\/\/ represented (or analyzable) in the module. As such, the external node will\n\/\/ have edges to functions with the following properties:\n\/\/ 1. All functions in the module without internal linkage, since they could\n\/\/ be called by functions outside of the our analysis capability.\n\/\/ 2. All functions whose address is used for something more than a direct\n\/\/ call, for example being stored into a memory location. Since they may\n\/\/ be called by an unknown caller later, they must be tracked as such.\n\/\/\n\/\/ Similarly, functions have a call edge to the external node iff:\n\/\/ 1. The function is external, reflecting the fact that they could call\n\/\/ anything without internal linkage or that has its address taken.\n\/\/ 2. The function contains an indirect function call.\n\/\/\n\/\/ As an extension in the future, there may be multiple nodes with a null\n\/\/ function. These will be used when we can prove (through pointer analysis)\n\/\/ that an indirect call site can call only a specific set of functions.\n\/\/\n\/\/ Because of these properties, the CallGraph captures a conservative superset\n\/\/ of all of the caller-callee relationships, which is useful for\n\/\/ transformations.\n\/\/\n\/\/ The CallGraph class also attempts to figure out what the root of the\n\/\/ CallGraph is, which is currently does by looking for a function named 'main'.\n\/\/ If no function named 'main' is found, the external node is used as the entry\n\/\/ node, reflecting the fact that any function without internal linkage could\n\/\/ be called into (which is common for libraries).\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Constants.h\" \/\/ Remove when ConstantPointerRefs are gone\n#include \"llvm\/Module.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"Support\/STLExtras.h\"\n\nstatic RegisterAnalysis<CallGraph> X(\"callgraph\", \"Call Graph Construction\");\n\nstatic const char * const KnownExternalFunctions[] = {\n \/\/ Low-level system calls\n \"open\",\n \"read\",\n \"write\",\n \"writev\",\n \"lseek\",\n \"poll\",\n \"ioctl\",\n\n \/\/ Low-level stdc library functions\n \"abort\",\n \"getenv\",\n \"putenv\",\n \n \/\/ Standard IO functions\n \"printf\",\n \"sprintf\",\n \"fopen\",\n \"freopen\",\n \"fclose\",\n \"fwrite\",\n \"puts\",\n \"fputs\",\n \"getc\",\n \"ungetc\",\n \"putc\",\n \"putchar\",\n \"fread\",\n \"fileno\",\n \"ftell\",\n \"fflush\",\n \"fseek\",\n \"fileno\",\n \"ferror\",\n \"feof\",\n \"fdopen\",\n \"__fxstat\",\n \"setbuf\",\n \"setbuffer\",\n \"etlinebuf\",\n \"setvbuf\",\n\n \/\/ Memory functions\n \"malloc\",\n \"free\",\n \"realloc\",\n \"calloc\",\n \"memalign\",\n \n \/\/ String functions\n \"atoi\",\n \"memmove\",\n \"memset\",\n \"memchr\",\n \"memcmp\",\n \"strchr\",\n \"strncpy\",\n \"strncmp\",\n \"strcmp\",\n \"__strcoll_l\",\n \"__strxfrm_l\",\n \"__strftime_l\",\n \"__strtol_l\",\n \"__strtoul_l\",\n \"__strtoll_l\",\n \"__strtoull_l\",\n \"__strtof_l\",\n \"__strtod_l\",\n \"__strtold_l\",\n\n \/\/ Locale functions\n \"__uselocale\",\n \"__newlocale\",\n \"__freelocale\",\n \"__duplocale\",\n \"__nl_langinfo_l\",\n\n \/\/ gettext functions used by libstdc++\n \"gettext\",\n \"dgettext\",\n \"dcgettext\",\n \"textdomain\",\n \"bindtextdomain\",\n \n \/\/ Random stuff\n \"__assert_fail\",\n \"__errno_location\",\n};\n\n\n\/\/\/ ExternalFunctionDoesntCallIntoProgram - This hack is used to indicate to the\n\/\/\/ call graph that the specified external function is _KNOWN_ to not call back\n\/\/\/ into the program. This is important, because otherwise functions which call\n\/\/\/ \"printf\" for example, end up in a great big SCC that goes from the function\n\/\/\/ through main.\n\/\/\/\nstatic bool ExternalFunctionDoesntCallIntoProgram(const std::string &Name) {\n static std::vector<std::string> Funcs;\n\n \/\/ First time this is called?\n if (Funcs.empty()) {\n \/\/ Add a whole bunch of functions which are often used...\n Funcs.insert(Funcs.end(), KnownExternalFunctions,\n KnownExternalFunctions+\n sizeof(KnownExternalFunctions)\/sizeof(KnownExternalFunctions[0]));\n \/\/ Sort the list for efficient access\n std::sort(Funcs.begin(), Funcs.end());\n }\n\n if (Name.size() > 7 && !memcmp(\"__llvm_\", Name.c_str(), 7))\n return true;\n\n \/\/ Binary search for the function name...\n std::vector<std::string>::iterator I =\n std::lower_bound(Funcs.begin(), Funcs.end(), Name);\n\n \/\/ Found it?\n return I != Funcs.end() && *I == Name;\n}\n\n\n\n\/\/ getNodeFor - Return the node for the specified function or create one if it\n\/\/ does not already exist.\n\/\/\nCallGraphNode *CallGraph::getNodeFor(Function *F) {\n CallGraphNode *&CGN = FunctionMap[F];\n if (CGN) return CGN;\n\n assert((!F || F->getParent() == Mod) && \"Function not in current module!\");\n return CGN = new CallGraphNode(F);\n}\n\nstatic bool isOnlyADirectCall(Function *F, CallSite CS) {\n if (!CS.getInstruction()) return false;\n for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)\n if (*I == F) return false;\n return true;\n}\n\n\/\/ addToCallGraph - Add a function to the call graph, and link the node to all\n\/\/ of the functions that it calls.\n\/\/\nvoid CallGraph::addToCallGraph(Function *F) {\n CallGraphNode *Node = getNodeFor(F);\n\n \/\/ If this function has external linkage, anything could call it...\n if (!F->hasInternalLinkage()) {\n ExternalNode->addCalledFunction(Node);\n\n \/\/ Found the entry point?\n if (F->getName() == \"main\") {\n if (Root)\n Root = ExternalNode; \/\/ Found multiple external mains? Don't pick one.\n else\n Root = Node; \/\/ Found a main, keep track of it!\n }\n }\n \n \/\/ If this function is not defined in this translation unit, it could call\n \/\/ anything.\n if (F->isExternal() && !F->getIntrinsicID() && \n !ExternalFunctionDoesntCallIntoProgram(F->getName()))\n Node->addCalledFunction(ExternalNode);\n\n \/\/ Loop over all of the users of the function... looking for callers...\n \/\/\n bool isUsedExternally = false;\n for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I) {\n if (Instruction *Inst = dyn_cast<Instruction>(*I)) {\n if (isOnlyADirectCall(F, CallSite::get(Inst)))\n getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);\n else\n isUsedExternally = true;\n } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I)) {\n \/\/ THIS IS A DISGUSTING HACK. Brought to you by the power of\n \/\/ ConstantPointerRefs!\n for (Value::use_iterator I = CPR->use_begin(), E = CPR->use_end();\n I != E; ++I)\n if (Instruction *Inst = dyn_cast<Instruction>(*I)) {\n if (isOnlyADirectCall(F, CallSite::get(Inst)))\n getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);\n else\n isUsedExternally = true;\n } else {\n isUsedExternally = true;\n }\n } else { \/\/ Can't classify the user!\n isUsedExternally = true;\n }\n }\n if (isUsedExternally)\n ExternalNode->addCalledFunction(Node);\n\n \/\/ Look for an indirect function call...\n for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)\n for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){\n CallSite CS = CallSite::get(II);\n if (CS.getInstruction() && !CS.getCalledFunction())\n Node->addCalledFunction(ExternalNode);\n }\n}\n\nbool CallGraph::run(Module &M) {\n destroy();\n\n Mod = &M;\n ExternalNode = getNodeFor(0);\n Root = 0;\n\n \/\/ Add every function to the call graph...\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n addToCallGraph(I);\n\n \/\/ If we didn't find a main function, use the external call graph node\n if (Root == 0) Root = ExternalNode;\n \n return false;\n}\n\nvoid CallGraph::destroy() {\n for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();\n I != E; ++I)\n delete I->second;\n FunctionMap.clear();\n}\n\nstatic void WriteToOutput(const CallGraphNode *CGN, std::ostream &o) {\n if (CGN->getFunction())\n o << \"Call graph node for function: '\"\n << CGN->getFunction()->getName() <<\"'\\n\";\n else\n o << \"Call graph node <<null function: 0x\" << CGN << \">>:\\n\";\n\n for (unsigned i = 0; i < CGN->size(); ++i)\n if ((*CGN)[i]->getFunction())\n o << \" Calls function '\" << (*CGN)[i]->getFunction()->getName() << \"'\\n\";\n else\n o << \" Calls external node\\n\";\n o << \"\\n\";\n}\n\nvoid CallGraph::print(std::ostream &o, const Module *M) const {\n o << \"CallGraph Root is: \";\n if (getRoot()->getFunction())\n o << getRoot()->getFunction()->getName() << \"\\n\";\n else\n o << \"<<null function: 0x\" << getRoot() << \">>\\n\";\n \n for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)\n WriteToOutput(I->second, o);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Implementations of public modification methods\n\/\/\n\n\/\/ Functions to keep a call graph up to date with a function that has been\n\/\/ modified\n\/\/\nvoid CallGraph::addFunctionToModule(Function *Meth) {\n assert(0 && \"not implemented\");\n abort();\n}\n\n\/\/ removeFunctionFromModule - Unlink the function from this module, returning\n\/\/ it. Because this removes the function from the module, the call graph node\n\/\/ is destroyed. This is only valid if the function does not call any other\n\/\/ functions (ie, there are no edges in it's CGN). The easiest way to do this\n\/\/ is to dropAllReferences before calling this.\n\/\/\nFunction *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {\n assert(CGN->CalledFunctions.empty() && \"Cannot remove function from call \"\n \"graph if it references other functions!\");\n Function *F = CGN->getFunction(); \/\/ Get the function for the call graph node\n delete CGN; \/\/ Delete the call graph node for this func\n FunctionMap.erase(F); \/\/ Remove the call graph node from the map\n\n Mod->getFunctionList().remove(F);\n return F;\n}\n\nvoid CallGraph::stub() {}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2011 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\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 *\/\n\n#include <cstdlib>\n#include <iostream>\n\n#include <QCoreApplication>\n#include <QFile>\n#include <QProcess>\n#include <QRegExp>\n#include <QTextStream>\n\n#include \"QXmppGlobal.h\"\n\nstatic void setField(QString &code, const QString &name, const QString &value)\n{\n code.replace(\n QRegExp(QString(\"(%1\\\\s*=)[^\\\\r\\\\n]*\").arg(name)),\n QString(\"\\\\1 %1\").arg(value));\n}\n\nstatic void usage() {\n QTextStream output(stderr);\n output << \"Usage:\" << endl;\n output << \" doxyfilter Generate documentation\" << endl;\n output << \" doxyfilter -g Generate Doxyfile\" << endl;\n output << \" doxyfilter <sourcefile> Filter the given file's code\" << endl;\n}\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n\n if (argc == 1)\n return QProcess::execute(\"doxygen\");\n else if (argc != 2) {\n usage();\n return 1;\n }\n\n if (!strcmp(argv[1], \"-g\")) {\n \/\/ generate default Doxyfile\n QProcess process;\n process.start(\"doxygen\", QStringList() << \"-g\" << \"-\");\n if (!process.waitForFinished()) {\n qWarning(\"Could not run doxygen\");\n return 1;\n }\n QString code = QString::fromUtf8(process.readAll());\n\n \/\/ adjust Doxyfile\n setField(code, \"ALPHABETICAL_INDEX\", \"NO\");\n setField(code, \"EXCLUDE_PATTERNS\", \"*\/moc_* *\/qdnslookup*\");\n setField(code, \"FULL_PATH_NAMES\", \"NO\");\n setField(code, \"HIDE_UNDOC_CLASSES\", \"YES\");\n setField(code, \"GENERATE_LATEX\", \"NO\");\n setField(code, \"HTML_TIMESTAMP\", \"NO\");\n setField(code, \"INPUT\", \"..\/src\");\n setField(code, \"INPUT_FILTER\", QString::fromLocal8Bit(argv[0]));\n setField(code, \"PROJECT_NAME\", \"QXmpp\");\n setField(code, \"PROJECT_NUMBER\", QString(\"Version: %1.%2.%3\").arg(\n QString::number((QXMPP_VERSION >> 16) & 0xff),\n QString::number((QXMPP_VERSION >> 8) & 0xff),\n QString::number(QXMPP_VERSION & 0xff)));\n\n \/\/ write doxyfile\n QFile output(\"Doxyfile\");\n if (!output.open(QIODevice::WriteOnly)) {\n qWarning(\"Could not write to %s\", qPrintable(output.fileName()));\n return 1;\n }\n output.write(code.toUtf8());\n output.close();\n\n } else if (!strcmp(argv[1], \"-h\")) {\n usage();\n return 0;\n } else {\n \/\/ read source code\n QFile source(QString::fromLocal8Bit(argv[1]));\n if (!source.open(QIODevice::ReadOnly)) {\n qWarning(\"Could not open %s\", qPrintable(source.fileName()));\n return 1;\n }\n QString code = QString::fromUtf8(source.readAll());\n source.close();\n\n \/\/ add links for XEPs\n QRegExp regexp(\"(XEP-([0-9]{4})(: [^\\\\s.]+( [A-Z][^\\\\s.]*)*)?)\");\n code.replace(regexp, \"<a href=\\\"http:\/\/xmpp.org\/extensions\/xep-\\\\2.html\\\">\\\\1<\/a>\");\n\n QTextStream output(stdout);\n output << code;\n }\n\n return 0;\n}\n\n<commit_msg>fix doc generation<commit_after>\/*\n * Copyright (C) 2008-2011 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\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 *\/\n\n#include <cstdlib>\n#include <iostream>\n\n#include <QCoreApplication>\n#include <QFile>\n#include <QProcess>\n#include <QRegExp>\n#include <QTextStream>\n\n#include \"QXmppGlobal.h\"\n\nstatic void setField(QString &code, const QString &name, const QString &value)\n{\n code.replace(\n QRegExp(QString(\"(%1\\\\s*=)[^\\\\r\\\\n]*\").arg(name)),\n QString(\"\\\\1 %1\").arg(value));\n}\n\nstatic void usage() {\n QTextStream output(stderr);\n output << \"Usage:\" << endl;\n output << \" doxyfilter Generate documentation\" << endl;\n output << \" doxyfilter -g Generate Doxyfile\" << endl;\n output << \" doxyfilter <sourcefile> Filter the given file's code\" << endl;\n}\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n\n if (argc == 1)\n return QProcess::execute(\"doxygen\");\n else if (argc != 2) {\n usage();\n return 1;\n }\n\n if (!strcmp(argv[1], \"-g\")) {\n \/\/ generate default Doxyfile\n QProcess process;\n process.start(\"doxygen\", QStringList() << \"-g\" << \"-\");\n if (!process.waitForFinished()) {\n qWarning(\"Could not run doxygen\");\n return 1;\n }\n QString code = QString::fromUtf8(process.readAll());\n\n \/\/ adjust Doxyfile\n setField(code, \"ALPHABETICAL_INDEX\", \"NO\");\n setField(code, \"EXCLUDE_PATTERNS\", \"*\/moc_* *\/mod_* *\/qdnslookup*\");\n setField(code, \"FULL_PATH_NAMES\", \"NO\");\n setField(code, \"HIDE_UNDOC_CLASSES\", \"YES\");\n setField(code, \"GENERATE_LATEX\", \"NO\");\n setField(code, \"HTML_TIMESTAMP\", \"NO\");\n setField(code, \"INPUT\", \"..\/src\");\n setField(code, \"INPUT_FILTER\", QString::fromLocal8Bit(argv[0]));\n setField(code, \"PROJECT_NAME\", \"QXmpp\");\n setField(code, \"PROJECT_NUMBER\", QString(\"Version: %1.%2.%3\").arg(\n QString::number((QXMPP_VERSION >> 16) & 0xff),\n QString::number((QXMPP_VERSION >> 8) & 0xff),\n QString::number(QXMPP_VERSION & 0xff)));\n setField(code, \"RECURSIVE\", \"YES\");\n\n \/\/ write doxyfile\n QFile output(\"Doxyfile\");\n if (!output.open(QIODevice::WriteOnly)) {\n qWarning(\"Could not write to %s\", qPrintable(output.fileName()));\n return 1;\n }\n output.write(code.toUtf8());\n output.close();\n\n } else if (!strcmp(argv[1], \"-h\")) {\n usage();\n return 0;\n } else {\n \/\/ read source code\n QFile source(QString::fromLocal8Bit(argv[1]));\n if (!source.open(QIODevice::ReadOnly)) {\n qWarning(\"Could not open %s\", qPrintable(source.fileName()));\n return 1;\n }\n QString code = QString::fromUtf8(source.readAll());\n source.close();\n\n \/\/ add links for XEPs\n QRegExp regexp(\"(XEP-([0-9]{4})(: [^\\\\s.]+( [A-Z][^\\\\s.]*)*)?)\");\n code.replace(regexp, \"<a href=\\\"http:\/\/xmpp.org\/extensions\/xep-\\\\2.html\\\">\\\\1<\/a>\");\n\n QTextStream output(stdout);\n output << code;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\ncreated: 18\/4\/2015\nauthor: Lukas E Meindl\n*************************************************************************\/\n\/***************************************************************************\n* Copyright (C) 2004 - 2015 Paul D Turner & Thce CEGUI Development Team\n*\n* Permission is hereby granted, free of charge, to any person obtaining\n* a copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without limitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and\/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be\n* included in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n***************************************************************************\/\n#include \"LookNFeelOverview.h\"\n\n#include \"CEGUI\/CEGUI.h\"\n\n#include <cmath>\n\n\nusing namespace CEGUI;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*************************************************************************\n\nLookNFeelOverviewSample class\n\n*************************************************************************\/\n\nLookNFeelOverviewSample::LookNFeelOverviewSample()\n{\n Sample::d_name = \"LookNFeelOverviewSample\";\n Sample::d_credits = \"Lukas "Ident" Meindl\";\n Sample::d_description =\n \"This sample gives a quick overview of the available stock LookNFeels (Skins) and their skinned widgets.\"\n \"Most widgets and most skins are shown here and can be directly interacted with.\";\n Sample::d_summary =\n \"The demo uses loads several layouts, each showing a set of widgets from a single skin. \"\n \"A combobox is used for selection. It also shows how font and widget scaling works on different resolutions\";\n Sample::d_priority = 99;\n}\n\n\/*************************************************************************\nSample specific initialisation goes here.\n*************************************************************************\/\nbool LookNFeelOverviewSample::initialise(CEGUI::GUIContext* guiContext)\n{\n using namespace CEGUI;\n\n d_usedFiles = CEGUI::String(__FILE__);\n\n d_guiContext = guiContext;\n WindowManager& winMgr = WindowManager::getSingleton();\n\n \/\/ load scheme and set up defaults\n SchemeManager::getSingleton().createFromFile(\"TaharezLook.scheme\");\n SchemeManager::getSingleton().createFromFile(\"AlfiskoSkin.scheme\");\n SchemeManager::getSingleton().createFromFile(\"WindowsLook.scheme\");\n SchemeManager::getSingleton().createFromFile(\"VanillaSkin.scheme\");\n SchemeManager::getSingleton().createFromFile(\"OgreTray.scheme\");\n guiContext->getCursor().setDefaultImage(\"Vanilla-Images\/MouseArrow\");\n\n \/\/ load all Fonts we are going to use and which are not loaded via scheme\n FontManager::FontList loadedFonts = FontManager::getSingleton().createFromFile(\"Jura-10.font\");\n Font* defaultFont = loadedFonts.empty() ? 0 : loadedFonts.front();\n FontManager::getSingleton().createFromFile(\"DejaVuSans-10.font\");\n\n \/\/ load all layouts we want to use later\n d_taharezOverviewLayout = winMgr.loadLayoutFromFile(\"TaharezLookOverview.layout\");\n d_vanillaOverviewLayout = winMgr.loadLayoutFromFile(\"VanillaLookOverview.layout\");\n\n \/\/ create a root window\n Window* root = winMgr.createWindow(\"DefaultWindow\", \"root\");\n guiContext->setRootWindow(root);\n\n CEGUI::Window* skinSelectionContainer = winMgr.createWindow(\"Vanilla\/StaticText\", \"SkinSelectionContainer\");\n skinSelectionContainer->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.0f)));\n skinSelectionContainer->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f)));\n root->addChild(skinSelectionContainer);\n\n d_loadedLayoutContainer = winMgr.createWindow(\"DefaultWindow\", \"LoadedLayoutContainer\");\n d_loadedLayoutContainer->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.1f)));\n d_loadedLayoutContainer->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(0.9f)));\n skinSelectionContainer->addChild(d_loadedLayoutContainer);\n\n CEGUI::Window* skinSelectionComboboxLabel = winMgr.createWindow(\"Vanilla\/Label\", \"SkinSelectionComboboxLabel\");\n skinSelectionContainer->addChild(skinSelectionComboboxLabel);\n skinSelectionComboboxLabel->setHorizontalAlignment(HA_CENTRE);\n skinSelectionComboboxLabel->setText(\"Choose a Look N' Feel (= a skin) to display\");\n skinSelectionComboboxLabel->setPosition(CEGUI::UVector2(cegui_reldim(-0.18f), cegui_reldim(0.0f)));\n skinSelectionComboboxLabel->setSize(CEGUI::USize(cegui_reldim(0.36f), cegui_reldim(0.04f)));\n skinSelectionComboboxLabel->setProperty(\"HorzFormatting\", \"RightAligned\");\n\n\n CEGUI::Combobox* skinSelectionCombobox = static_cast<CEGUI::Combobox*>(winMgr.createWindow(\"Vanilla\/Combobox\", \"SkinSelectionCombobox\"));\n skinSelectionContainer->addChild(skinSelectionCombobox);\n skinSelectionCombobox->setHorizontalAlignment(HA_CENTRE);\n skinSelectionCombobox->setPosition(CEGUI::UVector2(cegui_reldim(0.08f), cegui_reldim(0.003f)));\n skinSelectionCombobox->setSize(CEGUI::USize(cegui_reldim(0.15f), cegui_reldim(0.3f)));\n skinSelectionCombobox->setReadOnly(true);\n skinSelectionCombobox->setSortingEnabled(false);\n skinSelectionCombobox->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, Event::Subscriber(&LookNFeelOverviewSample::handleSkinSelectionAccepted, this));\n\n d_taharezLookListboxItem = new CEGUI::StandardItem(\"TaharezLook\");\n skinSelectionCombobox->addItem(d_taharezLookListboxItem);\n \/\/d_taharezLookListboxItem->setSelectionBrushImage(\"Vanilla-Images\/GenericBrush\");\n\n d_vanillaLookListboxItem = new CEGUI::StandardItem(\"Vanilla\");\n skinSelectionCombobox->addItem(d_vanillaLookListboxItem);\n \/\/d_vanillaLookListboxItem->setSelectionBrushImage(\"Vanilla-Images\/GenericBrush\");\n\n CEGUI::ListboxTextItem* blaLookListboxItem = new CEGUI::ListboxTextItem(\"TaharezLook\");\n\n \/\/ success!\n return true;\n}\n\n\/*************************************************************************\nCleans up resources allocated in the initialiseSample call.\n*************************************************************************\/\nvoid LookNFeelOverviewSample::deinitialise()\n{\n}\n\n\/*************************************************************************\nAn event handler to handle selections\n*************************************************************************\/\nbool LookNFeelOverviewSample::handleSkinSelectionAccepted(const CEGUI::EventArgs& args)\n{\n const CEGUI::WindowEventArgs& winEventArgs = static_cast<const CEGUI::WindowEventArgs&>(args);\n CEGUI::Combobox* skinSelectionCombobox = static_cast<CEGUI::Combobox*>(winEventArgs.window);\n\n StandardItem* selectedItem = skinSelectionCombobox->getSelectedItem();\n\n while(d_loadedLayoutContainer->getChildCount() > 0)\n d_loadedLayoutContainer->removeChild(d_loadedLayoutContainer->getChildAtIdx(0));\n\n if(selectedItem == d_taharezLookListboxItem)\n {\n d_loadedLayoutContainer->addChild(d_taharezOverviewLayout);\n \n \/\/ Set default font for the gui context\n d_guiContext->setDefaultFont(d_fontForTaharez);\n }\n else if(selectedItem == d_vanillaLookListboxItem)\n {\n d_loadedLayoutContainer->addChild(d_vanillaOverviewLayout);\n d_guiContext->setDefaultFont(d_fontForTaharez); \n }\n\n return false;\n}<commit_msg>MOD: Fixed a bug introduced when adapting the Demos for the FontMgr changes<commit_after>\/***********************************************************************\ncreated: 18\/4\/2015\nauthor: Lukas E Meindl\n*************************************************************************\/\n\/***************************************************************************\n* Copyright (C) 2004 - 2015 Paul D Turner & Thce CEGUI Development Team\n*\n* Permission is hereby granted, free of charge, to any person obtaining\n* a copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without limitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and\/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be\n* included in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n***************************************************************************\/\n#include \"LookNFeelOverview.h\"\n\n#include \"CEGUI\/CEGUI.h\"\n\n#include <cmath>\n\n\nusing namespace CEGUI;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*************************************************************************\n\nLookNFeelOverviewSample class\n\n*************************************************************************\/\n\nLookNFeelOverviewSample::LookNFeelOverviewSample()\n : d_fontForTaharez(0)\n{\n Sample::d_name = \"LookNFeelOverviewSample\";\n Sample::d_credits = \"Lukas "Ident" Meindl\";\n Sample::d_description =\n \"This sample gives a quick overview of the available stock LookNFeels (Skins) and their skinned widgets.\"\n \"Most widgets and most skins are shown here and can be directly interacted with.\";\n Sample::d_summary =\n \"The demo uses loads several layouts, each showing a set of widgets from a single skin. \"\n \"A combobox is used for selection. It also shows how font and widget scaling works on different resolutions\";\n Sample::d_priority = 99;\n}\n\n\/*************************************************************************\nSample specific initialisation goes here.\n*************************************************************************\/\nbool LookNFeelOverviewSample::initialise(CEGUI::GUIContext* guiContext)\n{\n using namespace CEGUI;\n\n d_usedFiles = CEGUI::String(__FILE__);\n\n d_guiContext = guiContext;\n WindowManager& winMgr = WindowManager::getSingleton();\n\n \/\/ load scheme and set up defaults\n SchemeManager::getSingleton().createFromFile(\"TaharezLook.scheme\");\n SchemeManager::getSingleton().createFromFile(\"AlfiskoSkin.scheme\");\n SchemeManager::getSingleton().createFromFile(\"WindowsLook.scheme\");\n SchemeManager::getSingleton().createFromFile(\"VanillaSkin.scheme\");\n SchemeManager::getSingleton().createFromFile(\"OgreTray.scheme\");\n guiContext->getCursor().setDefaultImage(\"Vanilla-Images\/MouseArrow\");\n\n \/\/ load all Fonts we are going to use and which are not loaded via scheme\n FontManager::FontList loadedFonts = FontManager::getSingleton().createFromFile(\"Jura-10.font\");\n d_fontForTaharez = loadedFonts.empty() ? 0 : loadedFonts.front();\n FontManager::getSingleton().createFromFile(\"DejaVuSans-10.font\");\n\n\n \/\/ load all layouts we want to use later\n d_taharezOverviewLayout = winMgr.loadLayoutFromFile(\"TaharezLookOverview.layout\");\n d_vanillaOverviewLayout = winMgr.loadLayoutFromFile(\"VanillaLookOverview.layout\");\n\n \/\/ create a root window\n Window* root = winMgr.createWindow(\"DefaultWindow\", \"root\");\n guiContext->setRootWindow(root);\n\n CEGUI::Window* skinSelectionContainer = winMgr.createWindow(\"Vanilla\/StaticText\", \"SkinSelectionContainer\");\n skinSelectionContainer->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.0f)));\n skinSelectionContainer->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f)));\n root->addChild(skinSelectionContainer);\n\n d_loadedLayoutContainer = winMgr.createWindow(\"DefaultWindow\", \"LoadedLayoutContainer\");\n d_loadedLayoutContainer->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.1f)));\n d_loadedLayoutContainer->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(0.9f)));\n skinSelectionContainer->addChild(d_loadedLayoutContainer);\n\n CEGUI::Window* skinSelectionComboboxLabel = winMgr.createWindow(\"Vanilla\/Label\", \"SkinSelectionComboboxLabel\");\n skinSelectionContainer->addChild(skinSelectionComboboxLabel);\n skinSelectionComboboxLabel->setHorizontalAlignment(HA_CENTRE);\n skinSelectionComboboxLabel->setText(\"Choose a Look N' Feel (= a skin) to display\");\n skinSelectionComboboxLabel->setPosition(CEGUI::UVector2(cegui_reldim(-0.18f), cegui_reldim(0.0f)));\n skinSelectionComboboxLabel->setSize(CEGUI::USize(cegui_reldim(0.36f), cegui_reldim(0.04f)));\n skinSelectionComboboxLabel->setProperty(\"HorzFormatting\", \"RightAligned\");\n\n\n CEGUI::Combobox* skinSelectionCombobox = static_cast<CEGUI::Combobox*>(winMgr.createWindow(\"Vanilla\/Combobox\", \"SkinSelectionCombobox\"));\n skinSelectionContainer->addChild(skinSelectionCombobox);\n skinSelectionCombobox->setHorizontalAlignment(HA_CENTRE);\n skinSelectionCombobox->setPosition(CEGUI::UVector2(cegui_reldim(0.08f), cegui_reldim(0.003f)));\n skinSelectionCombobox->setSize(CEGUI::USize(cegui_reldim(0.15f), cegui_reldim(0.3f)));\n skinSelectionCombobox->setReadOnly(true);\n skinSelectionCombobox->setSortingEnabled(false);\n skinSelectionCombobox->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, Event::Subscriber(&LookNFeelOverviewSample::handleSkinSelectionAccepted, this));\n\n d_taharezLookListboxItem = new CEGUI::StandardItem(\"TaharezLook\");\n skinSelectionCombobox->addItem(d_taharezLookListboxItem);\n \/\/d_taharezLookListboxItem->setSelectionBrushImage(\"Vanilla-Images\/GenericBrush\");\n\n d_vanillaLookListboxItem = new CEGUI::StandardItem(\"Vanilla\");\n skinSelectionCombobox->addItem(d_vanillaLookListboxItem);\n \/\/d_vanillaLookListboxItem->setSelectionBrushImage(\"Vanilla-Images\/GenericBrush\");\n\n CEGUI::ListboxTextItem* blaLookListboxItem = new CEGUI::ListboxTextItem(\"TaharezLook\");\n\n \/\/ success!\n return true;\n}\n\n\/*************************************************************************\nCleans up resources allocated in the initialiseSample call.\n*************************************************************************\/\nvoid LookNFeelOverviewSample::deinitialise()\n{\n}\n\n\/*************************************************************************\nAn event handler to handle selections\n*************************************************************************\/\nbool LookNFeelOverviewSample::handleSkinSelectionAccepted(const CEGUI::EventArgs& args)\n{\n const CEGUI::WindowEventArgs& winEventArgs = static_cast<const CEGUI::WindowEventArgs&>(args);\n CEGUI::Combobox* skinSelectionCombobox = static_cast<CEGUI::Combobox*>(winEventArgs.window);\n\n StandardItem* selectedItem = skinSelectionCombobox->getSelectedItem();\n\n while(d_loadedLayoutContainer->getChildCount() > 0)\n d_loadedLayoutContainer->removeChild(d_loadedLayoutContainer->getChildAtIdx(0));\n\n if(selectedItem == d_taharezLookListboxItem)\n {\n d_loadedLayoutContainer->addChild(d_taharezOverviewLayout);\n \n \/\/ Set default font for the gui context\n d_guiContext->setDefaultFont(d_fontForTaharez);\n }\n else if(selectedItem == d_vanillaLookListboxItem)\n {\n d_loadedLayoutContainer->addChild(d_vanillaOverviewLayout);\n d_guiContext->setDefaultFont(d_fontForTaharez); \n }\n\n return false;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT 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 * #L%\n *\/\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"joynr\/JoynrClusterControllerRuntime.h\"\n#include \"joynr\/Settings.h\"\n#include \"joynr\/SystemServicesSettings.h\"\n#include \"joynr\/system\/ProviderReregistrationControllerProxy.h\"\n\nusing namespace ::testing;\nusing namespace joynr;\n\nTEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime)\n{\n auto integrationSettings = std::make_unique<Settings>(\"test-resources\/MqttSystemIntegrationTest1.settings\");\n joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);\n const std::string domain(systemServiceSettings.getDomain());\n\n auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));\n runtime->init();\n runtime->start();\n\n auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);\n auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();\n\n Semaphore finishedSemaphore;\n providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr);\n finishedSemaphore.waitFor(std::chrono::seconds(2));\n}\n<commit_msg>[C++] Ensure runtime destruction in sys-int-test<commit_after>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT 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 * #L%\n *\/\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"joynr\/JoynrClusterControllerRuntime.h\"\n#include \"joynr\/Settings.h\"\n#include \"joynr\/SystemServicesSettings.h\"\n#include \"joynr\/system\/ProviderReregistrationControllerProxy.h\"\n\nusing namespace ::testing;\nusing namespace joynr;\n\nTEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime)\n{\n auto integrationSettings = std::make_unique<Settings>(\"test-resources\/MqttSystemIntegrationTest1.settings\");\n joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);\n const std::string domain(systemServiceSettings.getDomain());\n\n auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));\n runtime->init();\n runtime->start();\n\n auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);\n auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();\n\n Semaphore finishedSemaphore;\n providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr);\n finishedSemaphore.waitFor(std::chrono::seconds(2));\n\n runtime->stop();\n runtime = nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016-present, Facebook, Inc. All rights reserved.\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#if !defined(ROCKSDB_LITE) && !defined(OS_WIN)\n\n#include \"util\/env_chroot.h\"\n\n#include <unistd.h>\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"rocksdb\/status.h\"\n\nnamespace rocksdb {\n\nclass ChrootEnv : public EnvWrapper {\n public:\n ChrootEnv(Env* base_env, const std::string& chroot_dir)\n : EnvWrapper(base_env), chroot_dir_(chroot_dir) {}\n\n virtual Status NewSequentialFile(const std::string& fname,\n std::unique_ptr<SequentialFile>* result,\n const EnvOptions& options) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewSequentialFile(status_and_enc_path.second, result,\n options);\n }\n\n virtual Status NewRandomAccessFile(const std::string& fname,\n unique_ptr<RandomAccessFile>* result,\n const EnvOptions& options) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewRandomAccessFile(status_and_enc_path.second, result,\n options);\n }\n\n virtual Status NewWritableFile(const std::string& fname,\n unique_ptr<WritableFile>* result,\n const EnvOptions& options) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewWritableFile(status_and_enc_path.second, result,\n options);\n }\n\n virtual Status ReuseWritableFile(const std::string& fname,\n const std::string& old_fname,\n unique_ptr<WritableFile>* result,\n const EnvOptions& options) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n auto status_and_old_enc_path = EncodePath(old_fname);\n if (!status_and_old_enc_path.first.ok()) {\n return status_and_old_enc_path.first;\n }\n return EnvWrapper::ReuseWritableFile(status_and_old_enc_path.second,\n status_and_old_enc_path.second, result,\n options);\n }\n\n virtual Status NewDirectory(const std::string& dir,\n unique_ptr<Directory>* result) override {\n auto status_and_enc_path = EncodePathWithNewBasename(dir);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewDirectory(status_and_enc_path.second, result);\n }\n\n virtual Status FileExists(const std::string& fname) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::FileExists(status_and_enc_path.second);\n }\n\n virtual Status GetChildren(const std::string& dir,\n std::vector<std::string>* result) override {\n auto status_and_enc_path = EncodePath(dir);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetChildren(status_and_enc_path.second, result);\n }\n\n virtual Status GetChildrenFileAttributes(\n const std::string& dir, std::vector<FileAttributes>* result) override {\n auto status_and_enc_path = EncodePath(dir);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetChildrenFileAttributes(status_and_enc_path.second,\n result);\n }\n\n virtual Status DeleteFile(const std::string& fname) override {\n auto status_and_enc_path = EncodePath(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::DeleteFile(status_and_enc_path.second);\n }\n\n virtual Status CreateDir(const std::string& dirname) override {\n auto status_and_enc_path = EncodePathWithNewBasename(dirname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::CreateDir(status_and_enc_path.second);\n }\n\n virtual Status CreateDirIfMissing(const std::string& dirname) override {\n auto status_and_enc_path = EncodePathWithNewBasename(dirname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::CreateDirIfMissing(status_and_enc_path.second);\n }\n\n virtual Status DeleteDir(const std::string& dirname) override {\n auto status_and_enc_path = EncodePath(dirname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::DeleteDir(status_and_enc_path.second);\n }\n\n virtual Status GetFileSize(const std::string& fname,\n uint64_t* file_size) override {\n auto status_and_enc_path = EncodePath(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetFileSize(status_and_enc_path.second, file_size);\n }\n\n virtual Status GetFileModificationTime(const std::string& fname,\n uint64_t* file_mtime) override {\n auto status_and_enc_path = EncodePath(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetFileModificationTime(status_and_enc_path.second,\n file_mtime);\n }\n\n virtual Status RenameFile(const std::string& src,\n const std::string& dest) override {\n auto status_and_src_enc_path = EncodePath(src);\n if (!status_and_src_enc_path.first.ok()) {\n return status_and_src_enc_path.first;\n }\n auto status_and_dest_enc_path = EncodePathWithNewBasename(dest);\n if (!status_and_dest_enc_path.first.ok()) {\n return status_and_dest_enc_path.first;\n }\n return EnvWrapper::RenameFile(status_and_src_enc_path.second,\n status_and_dest_enc_path.second);\n }\n\n virtual Status LinkFile(const std::string& src,\n const std::string& dest) override {\n auto status_and_src_enc_path = EncodePath(src);\n if (!status_and_src_enc_path.first.ok()) {\n return status_and_src_enc_path.first;\n }\n auto status_and_dest_enc_path = EncodePathWithNewBasename(dest);\n if (!status_and_dest_enc_path.first.ok()) {\n return status_and_dest_enc_path.first;\n }\n return EnvWrapper::LinkFile(status_and_src_enc_path.second,\n status_and_dest_enc_path.second);\n }\n\n virtual Status LockFile(const std::string& fname, FileLock** lock) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n \/\/ FileLock subclasses may store path (e.g., PosixFileLock stores it). We\n \/\/ can skip stripping the chroot directory from this path because callers\n \/\/ shouldn't use it.\n return EnvWrapper::LockFile(status_and_enc_path.second, lock);\n }\n\n virtual Status GetTestDirectory(std::string* path) override {\n \/\/ Adapted from PosixEnv's implementation since it doesn't provide a way to\n \/\/ create directory in the chroot.\n char buf[256];\n snprintf(buf, sizeof(buf), \"\/rocksdbtest-%d\", static_cast<int>(geteuid()));\n *path = buf;\n\n \/\/ Directory may already exist, so ignore return\n CreateDir(*path);\n return Status::OK();\n }\n\n virtual Status NewLogger(const std::string& fname,\n shared_ptr<Logger>* result) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewLogger(status_and_enc_path.second, result);\n }\n\n virtual Status GetAbsolutePath(const std::string& db_path,\n std::string* output_path) override {\n auto status_and_enc_path = EncodePath(db_path);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetAbsolutePath(status_and_enc_path.second, output_path);\n }\n\n private:\n \/\/ Returns status and expanded absolute path including the chroot directory.\n \/\/ Checks whether the provided path breaks out of the chroot. If it returns\n \/\/ non-OK status, the returned path should not be used.\n std::pair<Status, std::string> EncodePath(const std::string& path) {\n if (path.empty() || path[0] != '\/') {\n return {Status::InvalidArgument(path, \"Not an absolute path\"), \"\"};\n }\n std::pair<Status, std::string> res;\n res.second = chroot_dir_ + path;\n char* normalized_path = realpath(res.second.c_str(), nullptr);\n if (normalized_path == nullptr) {\n res.first = Status::NotFound(res.second, strerror(errno));\n } else if (strlen(normalized_path) < chroot_dir_.size() ||\n strncmp(normalized_path, chroot_dir_.c_str(),\n chroot_dir_.size()) != 0) {\n res.first = Status::IOError(res.second,\n \"Attempted to access path outside chroot\");\n } else {\n res.first = Status::OK();\n }\n free(normalized_path);\n return res;\n }\n\n \/\/ Similar to EncodePath() except assumes the basename in the path hasn't been\n \/\/ created yet.\n std::pair<Status, std::string> EncodePathWithNewBasename(\n const std::string& path) {\n if (path.empty() || path[0] != '\/') {\n return {Status::InvalidArgument(path, \"Not an absolute path\"), \"\"};\n }\n \/\/ Basename may be followed by trailing slashes\n size_t final_idx = path.find_last_not_of('\/');\n if (final_idx == std::string::npos) {\n \/\/ It's only slashes so no basename to extract\n return EncodePath(path);\n }\n\n \/\/ Pull off the basename temporarily since realname(3) (used by\n \/\/ EncodePath()) requires a path that exists\n size_t base_sep = path.rfind('\/', final_idx);\n auto status_and_enc_path = EncodePath(path.substr(0, base_sep + 1));\n status_and_enc_path.second.append(path.substr(base_sep + 1));\n return status_and_enc_path;\n }\n\n const std::string chroot_dir_;\n};\n\nEnv* NewChrootEnv(Env* base_env, const std::string& chroot_dir) {\n if (!base_env->FileExists(chroot_dir).ok()) {\n return nullptr;\n }\n return new ChrootEnv(base_env, chroot_dir);\n}\n\n} \/\/ namespace rocksdb\n\n#endif \/\/ !defined(ROCKSDB_LITE) && !defined(OS_WIN)\n<commit_msg>Fix includes for clang on OS X<commit_after>\/\/ Copyright (c) 2016-present, Facebook, Inc. All rights reserved.\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#if !defined(ROCKSDB_LITE) && !defined(OS_WIN)\n\n#include \"util\/env_chroot.h\"\n\n#include <errno.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"rocksdb\/status.h\"\n\nnamespace rocksdb {\n\nclass ChrootEnv : public EnvWrapper {\n public:\n ChrootEnv(Env* base_env, const std::string& chroot_dir)\n : EnvWrapper(base_env), chroot_dir_(chroot_dir) {}\n\n virtual Status NewSequentialFile(const std::string& fname,\n std::unique_ptr<SequentialFile>* result,\n const EnvOptions& options) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewSequentialFile(status_and_enc_path.second, result,\n options);\n }\n\n virtual Status NewRandomAccessFile(const std::string& fname,\n unique_ptr<RandomAccessFile>* result,\n const EnvOptions& options) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewRandomAccessFile(status_and_enc_path.second, result,\n options);\n }\n\n virtual Status NewWritableFile(const std::string& fname,\n unique_ptr<WritableFile>* result,\n const EnvOptions& options) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewWritableFile(status_and_enc_path.second, result,\n options);\n }\n\n virtual Status ReuseWritableFile(const std::string& fname,\n const std::string& old_fname,\n unique_ptr<WritableFile>* result,\n const EnvOptions& options) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n auto status_and_old_enc_path = EncodePath(old_fname);\n if (!status_and_old_enc_path.first.ok()) {\n return status_and_old_enc_path.first;\n }\n return EnvWrapper::ReuseWritableFile(status_and_old_enc_path.second,\n status_and_old_enc_path.second, result,\n options);\n }\n\n virtual Status NewDirectory(const std::string& dir,\n unique_ptr<Directory>* result) override {\n auto status_and_enc_path = EncodePathWithNewBasename(dir);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewDirectory(status_and_enc_path.second, result);\n }\n\n virtual Status FileExists(const std::string& fname) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::FileExists(status_and_enc_path.second);\n }\n\n virtual Status GetChildren(const std::string& dir,\n std::vector<std::string>* result) override {\n auto status_and_enc_path = EncodePath(dir);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetChildren(status_and_enc_path.second, result);\n }\n\n virtual Status GetChildrenFileAttributes(\n const std::string& dir, std::vector<FileAttributes>* result) override {\n auto status_and_enc_path = EncodePath(dir);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetChildrenFileAttributes(status_and_enc_path.second,\n result);\n }\n\n virtual Status DeleteFile(const std::string& fname) override {\n auto status_and_enc_path = EncodePath(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::DeleteFile(status_and_enc_path.second);\n }\n\n virtual Status CreateDir(const std::string& dirname) override {\n auto status_and_enc_path = EncodePathWithNewBasename(dirname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::CreateDir(status_and_enc_path.second);\n }\n\n virtual Status CreateDirIfMissing(const std::string& dirname) override {\n auto status_and_enc_path = EncodePathWithNewBasename(dirname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::CreateDirIfMissing(status_and_enc_path.second);\n }\n\n virtual Status DeleteDir(const std::string& dirname) override {\n auto status_and_enc_path = EncodePath(dirname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::DeleteDir(status_and_enc_path.second);\n }\n\n virtual Status GetFileSize(const std::string& fname,\n uint64_t* file_size) override {\n auto status_and_enc_path = EncodePath(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetFileSize(status_and_enc_path.second, file_size);\n }\n\n virtual Status GetFileModificationTime(const std::string& fname,\n uint64_t* file_mtime) override {\n auto status_and_enc_path = EncodePath(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetFileModificationTime(status_and_enc_path.second,\n file_mtime);\n }\n\n virtual Status RenameFile(const std::string& src,\n const std::string& dest) override {\n auto status_and_src_enc_path = EncodePath(src);\n if (!status_and_src_enc_path.first.ok()) {\n return status_and_src_enc_path.first;\n }\n auto status_and_dest_enc_path = EncodePathWithNewBasename(dest);\n if (!status_and_dest_enc_path.first.ok()) {\n return status_and_dest_enc_path.first;\n }\n return EnvWrapper::RenameFile(status_and_src_enc_path.second,\n status_and_dest_enc_path.second);\n }\n\n virtual Status LinkFile(const std::string& src,\n const std::string& dest) override {\n auto status_and_src_enc_path = EncodePath(src);\n if (!status_and_src_enc_path.first.ok()) {\n return status_and_src_enc_path.first;\n }\n auto status_and_dest_enc_path = EncodePathWithNewBasename(dest);\n if (!status_and_dest_enc_path.first.ok()) {\n return status_and_dest_enc_path.first;\n }\n return EnvWrapper::LinkFile(status_and_src_enc_path.second,\n status_and_dest_enc_path.second);\n }\n\n virtual Status LockFile(const std::string& fname, FileLock** lock) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n \/\/ FileLock subclasses may store path (e.g., PosixFileLock stores it). We\n \/\/ can skip stripping the chroot directory from this path because callers\n \/\/ shouldn't use it.\n return EnvWrapper::LockFile(status_and_enc_path.second, lock);\n }\n\n virtual Status GetTestDirectory(std::string* path) override {\n \/\/ Adapted from PosixEnv's implementation since it doesn't provide a way to\n \/\/ create directory in the chroot.\n char buf[256];\n snprintf(buf, sizeof(buf), \"\/rocksdbtest-%d\", static_cast<int>(geteuid()));\n *path = buf;\n\n \/\/ Directory may already exist, so ignore return\n CreateDir(*path);\n return Status::OK();\n }\n\n virtual Status NewLogger(const std::string& fname,\n shared_ptr<Logger>* result) override {\n auto status_and_enc_path = EncodePathWithNewBasename(fname);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::NewLogger(status_and_enc_path.second, result);\n }\n\n virtual Status GetAbsolutePath(const std::string& db_path,\n std::string* output_path) override {\n auto status_and_enc_path = EncodePath(db_path);\n if (!status_and_enc_path.first.ok()) {\n return status_and_enc_path.first;\n }\n return EnvWrapper::GetAbsolutePath(status_and_enc_path.second, output_path);\n }\n\n private:\n \/\/ Returns status and expanded absolute path including the chroot directory.\n \/\/ Checks whether the provided path breaks out of the chroot. If it returns\n \/\/ non-OK status, the returned path should not be used.\n std::pair<Status, std::string> EncodePath(const std::string& path) {\n if (path.empty() || path[0] != '\/') {\n return {Status::InvalidArgument(path, \"Not an absolute path\"), \"\"};\n }\n std::pair<Status, std::string> res;\n res.second = chroot_dir_ + path;\n char* normalized_path = realpath(res.second.c_str(), nullptr);\n if (normalized_path == nullptr) {\n res.first = Status::NotFound(res.second, strerror(errno));\n } else if (strlen(normalized_path) < chroot_dir_.size() ||\n strncmp(normalized_path, chroot_dir_.c_str(),\n chroot_dir_.size()) != 0) {\n res.first = Status::IOError(res.second,\n \"Attempted to access path outside chroot\");\n } else {\n res.first = Status::OK();\n }\n free(normalized_path);\n return res;\n }\n\n \/\/ Similar to EncodePath() except assumes the basename in the path hasn't been\n \/\/ created yet.\n std::pair<Status, std::string> EncodePathWithNewBasename(\n const std::string& path) {\n if (path.empty() || path[0] != '\/') {\n return {Status::InvalidArgument(path, \"Not an absolute path\"), \"\"};\n }\n \/\/ Basename may be followed by trailing slashes\n size_t final_idx = path.find_last_not_of('\/');\n if (final_idx == std::string::npos) {\n \/\/ It's only slashes so no basename to extract\n return EncodePath(path);\n }\n\n \/\/ Pull off the basename temporarily since realname(3) (used by\n \/\/ EncodePath()) requires a path that exists\n size_t base_sep = path.rfind('\/', final_idx);\n auto status_and_enc_path = EncodePath(path.substr(0, base_sep + 1));\n status_and_enc_path.second.append(path.substr(base_sep + 1));\n return status_and_enc_path;\n }\n\n const std::string chroot_dir_;\n};\n\nEnv* NewChrootEnv(Env* base_env, const std::string& chroot_dir) {\n if (!base_env->FileExists(chroot_dir).ok()) {\n return nullptr;\n }\n return new ChrootEnv(base_env, chroot_dir);\n}\n\n} \/\/ namespace rocksdb\n\n#endif \/\/ !defined(ROCKSDB_LITE) && !defined(OS_WIN)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2012 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * 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\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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n * Authors:\n * Eric Anholt <eric@anholt.net>\n *\n *\/\n\n#include \"brw_cfg.h\"\n\n\/** @file brw_cfg.cpp\n *\n * Walks the shader instructions generated and creates a set of basic\n * blocks with successor\/predecessor edges connecting them.\n *\/\n\nstatic bblock_t *\npop_stack(exec_list *list)\n{\n bblock_link *link = (bblock_link *)list->get_tail();\n bblock_t *block = link->block;\n link->link.remove();\n\n return block;\n}\n\nstatic exec_node *\nlink(void *mem_ctx, bblock_t *block)\n{\n bblock_link *l = new(mem_ctx) bblock_link(block);\n return &l->link;\n}\n\nbblock_t::bblock_t() :\n start_ip(0), end_ip(0), block_num(0)\n{\n start = NULL;\n end = NULL;\n\n parents.make_empty();\n children.make_empty();\n\n if_inst = NULL;\n else_inst = NULL;\n endif_inst = NULL;\n}\n\nvoid\nbblock_t::add_successor(void *mem_ctx, bblock_t *successor)\n{\n successor->parents.push_tail(link(mem_ctx, this));\n children.push_tail(link(mem_ctx, successor));\n}\n\nvoid\nbblock_t::dump(backend_visitor *v)\n{\n int ip = this->start_ip;\n for (backend_instruction *inst = (backend_instruction *)this->start;\n\tinst != this->end->next;\n\tinst = (backend_instruction *) inst->next) {\n fprintf(stderr, \"%5d: \", ip);\n v->dump_instruction(inst);\n ip++;\n }\n}\n\ncfg_t::cfg_t(exec_list *instructions)\n{\n mem_ctx = ralloc_context(NULL);\n block_list.make_empty();\n blocks = NULL;\n num_blocks = 0;\n\n bblock_t *cur = NULL;\n int ip = 0;\n\n bblock_t *entry = new_block();\n bblock_t *cur_if = NULL; \/**< BB ending with IF. *\/\n bblock_t *cur_else = NULL; \/**< BB ending with ELSE. *\/\n bblock_t *cur_endif = NULL; \/**< BB starting with ENDIF. *\/\n bblock_t *cur_do = NULL; \/**< BB ending with DO. *\/\n bblock_t *cur_while = NULL; \/**< BB immediately following WHILE. *\/\n exec_list if_stack, else_stack, do_stack, while_stack;\n bblock_t *next;\n\n set_next_block(&cur, entry, ip);\n\n entry->start = (backend_instruction *) instructions->get_head();\n\n foreach_list(node, instructions) {\n backend_instruction *inst = (backend_instruction *)node;\n\n cur->end = inst;\n\n \/* set_next_block wants the post-incremented ip *\/\n ip++;\n\n switch (inst->opcode) {\n case BRW_OPCODE_IF:\n\t \/* Push our information onto a stack so we can recover from\n\t * nested ifs.\n\t *\/\n\t if_stack.push_tail(link(mem_ctx, cur_if));\n\t else_stack.push_tail(link(mem_ctx, cur_else));\n\n\t cur_if = cur;\n\t cur_else = NULL;\n cur_endif = NULL;\n\n\t \/* Set up our immediately following block, full of \"then\"\n\t * instructions.\n\t *\/\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t cur_if->add_successor(mem_ctx, next);\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_ELSE:\n cur_else = cur;\n\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t cur_if->add_successor(mem_ctx, next);\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_ENDIF: {\n if (cur->start == inst) {\n \/* New block was just created; use it. *\/\n cur_endif = cur;\n } else {\n cur_endif = new_block();\n cur_endif->start = inst;\n\n cur->end = (backend_instruction *)inst->prev;\n cur->add_successor(mem_ctx, cur_endif);\n\n set_next_block(&cur, cur_endif, ip - 1);\n }\n\n backend_instruction *else_inst = NULL;\n if (cur_else) {\n else_inst = (backend_instruction *)cur_else->end;\n\n cur_else->add_successor(mem_ctx, cur_endif);\n } else {\n cur_if->add_successor(mem_ctx, cur_endif);\n }\n\n assert(cur_if->end->opcode == BRW_OPCODE_IF);\n assert(!else_inst || else_inst->opcode == BRW_OPCODE_ELSE);\n assert(inst->opcode == BRW_OPCODE_ENDIF);\n\n cur_if->if_inst = cur_if->end;\n cur_if->else_inst = else_inst;\n cur_if->endif_inst = inst;\n\n\t if (cur_else) {\n cur_else->if_inst = cur_if->end;\n cur_else->else_inst = else_inst;\n cur_else->endif_inst = inst;\n }\n\n cur->if_inst = cur_if->end;\n cur->else_inst = else_inst;\n cur->endif_inst = inst;\n\n\t \/* Pop the stack so we're in the previous if\/else\/endif *\/\n\t cur_if = pop_stack(&if_stack);\n\t cur_else = pop_stack(&else_stack);\n\t break;\n }\n case BRW_OPCODE_DO:\n\t \/* Push our information onto a stack so we can recover from\n\t * nested loops.\n\t *\/\n\t do_stack.push_tail(link(mem_ctx, cur_do));\n\t while_stack.push_tail(link(mem_ctx, cur_while));\n\n\t \/* Set up the block just after the while. Don't know when exactly\n\t * it will start, yet.\n\t *\/\n\t cur_while = new_block();\n\n\t \/* Set up our immediately following block, full of \"then\"\n\t * instructions.\n\t *\/\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t cur->add_successor(mem_ctx, next);\n\t cur_do = next;\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_CONTINUE:\n\t cur->add_successor(mem_ctx, cur_do);\n\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t if (inst->predicate)\n\t cur->add_successor(mem_ctx, next);\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_BREAK:\n\t cur->add_successor(mem_ctx, cur_while);\n\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t if (inst->predicate)\n\t cur->add_successor(mem_ctx, next);\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_WHILE:\n\t cur_while->start = (backend_instruction *)inst->next;\n\n\t cur->add_successor(mem_ctx, cur_do);\n\t set_next_block(&cur, cur_while, ip);\n\n\t \/* Pop the stack so we're in the previous loop *\/\n\t cur_do = pop_stack(&do_stack);\n\t cur_while = pop_stack(&while_stack);\n\t break;\n\n default:\n\t break;\n }\n }\n\n cur->end_ip = ip;\n\n make_block_array();\n}\n\ncfg_t::~cfg_t()\n{\n ralloc_free(mem_ctx);\n}\n\nbblock_t *\ncfg_t::new_block()\n{\n bblock_t *block = new(mem_ctx) bblock_t();\n\n return block;\n}\n\nvoid\ncfg_t::set_next_block(bblock_t **cur, bblock_t *block, int ip)\n{\n if (*cur) {\n assert((*cur)->end->next == block->start);\n (*cur)->end_ip = ip - 1;\n }\n\n block->start_ip = ip;\n block->block_num = num_blocks++;\n block_list.push_tail(link(mem_ctx, block));\n *cur = block;\n}\n\nvoid\ncfg_t::make_block_array()\n{\n blocks = ralloc_array(mem_ctx, bblock_t *, num_blocks);\n\n int i = 0;\n foreach_list_typed(bblock_link, link, link, &block_list) {\n blocks[i++] = link->block;\n }\n assert(i == num_blocks);\n}\n\nvoid\ncfg_t::dump(backend_visitor *v)\n{\n for (int b = 0; b < this->num_blocks; b++) {\n bblock_t *block = this->blocks[b];\n fprintf(stderr, \"START B%d\", b);\n foreach_list_typed(bblock_link, link, link, &block->parents) {\n fprintf(stderr, \" <-B%d\",\n link->block->block_num);\n }\n fprintf(stderr, \"\\n\");\n block->dump(v);\n fprintf(stderr, \"END B%d\", b);\n foreach_list_typed(bblock_link, link, link, &block->children) {\n fprintf(stderr, \" ->B%d\",\n link->block->block_num);\n }\n fprintf(stderr, \"\\n\");\n }\n}\n<commit_msg>i965\/cfg: Make DO instruction begin a basic block.<commit_after>\/*\n * Copyright © 2012 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * 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\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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n * Authors:\n * Eric Anholt <eric@anholt.net>\n *\n *\/\n\n#include \"brw_cfg.h\"\n\n\/** @file brw_cfg.cpp\n *\n * Walks the shader instructions generated and creates a set of basic\n * blocks with successor\/predecessor edges connecting them.\n *\/\n\nstatic bblock_t *\npop_stack(exec_list *list)\n{\n bblock_link *link = (bblock_link *)list->get_tail();\n bblock_t *block = link->block;\n link->link.remove();\n\n return block;\n}\n\nstatic exec_node *\nlink(void *mem_ctx, bblock_t *block)\n{\n bblock_link *l = new(mem_ctx) bblock_link(block);\n return &l->link;\n}\n\nbblock_t::bblock_t() :\n start_ip(0), end_ip(0), block_num(0)\n{\n start = NULL;\n end = NULL;\n\n parents.make_empty();\n children.make_empty();\n\n if_inst = NULL;\n else_inst = NULL;\n endif_inst = NULL;\n}\n\nvoid\nbblock_t::add_successor(void *mem_ctx, bblock_t *successor)\n{\n successor->parents.push_tail(link(mem_ctx, this));\n children.push_tail(link(mem_ctx, successor));\n}\n\nvoid\nbblock_t::dump(backend_visitor *v)\n{\n int ip = this->start_ip;\n for (backend_instruction *inst = (backend_instruction *)this->start;\n\tinst != this->end->next;\n\tinst = (backend_instruction *) inst->next) {\n fprintf(stderr, \"%5d: \", ip);\n v->dump_instruction(inst);\n ip++;\n }\n}\n\ncfg_t::cfg_t(exec_list *instructions)\n{\n mem_ctx = ralloc_context(NULL);\n block_list.make_empty();\n blocks = NULL;\n num_blocks = 0;\n\n bblock_t *cur = NULL;\n int ip = 0;\n\n bblock_t *entry = new_block();\n bblock_t *cur_if = NULL; \/**< BB ending with IF. *\/\n bblock_t *cur_else = NULL; \/**< BB ending with ELSE. *\/\n bblock_t *cur_endif = NULL; \/**< BB starting with ENDIF. *\/\n bblock_t *cur_do = NULL; \/**< BB starting with DO. *\/\n bblock_t *cur_while = NULL; \/**< BB immediately following WHILE. *\/\n exec_list if_stack, else_stack, do_stack, while_stack;\n bblock_t *next;\n\n set_next_block(&cur, entry, ip);\n\n entry->start = (backend_instruction *) instructions->get_head();\n\n foreach_list(node, instructions) {\n backend_instruction *inst = (backend_instruction *)node;\n\n cur->end = inst;\n\n \/* set_next_block wants the post-incremented ip *\/\n ip++;\n\n switch (inst->opcode) {\n case BRW_OPCODE_IF:\n\t \/* Push our information onto a stack so we can recover from\n\t * nested ifs.\n\t *\/\n\t if_stack.push_tail(link(mem_ctx, cur_if));\n\t else_stack.push_tail(link(mem_ctx, cur_else));\n\n\t cur_if = cur;\n\t cur_else = NULL;\n cur_endif = NULL;\n\n\t \/* Set up our immediately following block, full of \"then\"\n\t * instructions.\n\t *\/\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t cur_if->add_successor(mem_ctx, next);\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_ELSE:\n cur_else = cur;\n\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t cur_if->add_successor(mem_ctx, next);\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_ENDIF: {\n if (cur->start == inst) {\n \/* New block was just created; use it. *\/\n cur_endif = cur;\n } else {\n cur_endif = new_block();\n cur_endif->start = inst;\n\n cur->end = (backend_instruction *)inst->prev;\n cur->add_successor(mem_ctx, cur_endif);\n\n set_next_block(&cur, cur_endif, ip - 1);\n }\n\n backend_instruction *else_inst = NULL;\n if (cur_else) {\n else_inst = (backend_instruction *)cur_else->end;\n\n cur_else->add_successor(mem_ctx, cur_endif);\n } else {\n cur_if->add_successor(mem_ctx, cur_endif);\n }\n\n assert(cur_if->end->opcode == BRW_OPCODE_IF);\n assert(!else_inst || else_inst->opcode == BRW_OPCODE_ELSE);\n assert(inst->opcode == BRW_OPCODE_ENDIF);\n\n cur_if->if_inst = cur_if->end;\n cur_if->else_inst = else_inst;\n cur_if->endif_inst = inst;\n\n\t if (cur_else) {\n cur_else->if_inst = cur_if->end;\n cur_else->else_inst = else_inst;\n cur_else->endif_inst = inst;\n }\n\n cur->if_inst = cur_if->end;\n cur->else_inst = else_inst;\n cur->endif_inst = inst;\n\n\t \/* Pop the stack so we're in the previous if\/else\/endif *\/\n\t cur_if = pop_stack(&if_stack);\n\t cur_else = pop_stack(&else_stack);\n\t break;\n }\n case BRW_OPCODE_DO:\n\t \/* Push our information onto a stack so we can recover from\n\t * nested loops.\n\t *\/\n\t do_stack.push_tail(link(mem_ctx, cur_do));\n\t while_stack.push_tail(link(mem_ctx, cur_while));\n\n\t \/* Set up the block just after the while. Don't know when exactly\n\t * it will start, yet.\n\t *\/\n\t cur_while = new_block();\n\n if (cur->start == inst) {\n \/* New block was just created; use it. *\/\n cur_do = cur;\n } else {\n cur_do = new_block();\n cur_do->start = inst;\n\n cur->end = (backend_instruction *)inst->prev;\n cur->add_successor(mem_ctx, cur_do);\n\n set_next_block(&cur, cur_do, ip - 1);\n }\n\t break;\n\n case BRW_OPCODE_CONTINUE:\n\t cur->add_successor(mem_ctx, cur_do);\n\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t if (inst->predicate)\n\t cur->add_successor(mem_ctx, next);\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_BREAK:\n\t cur->add_successor(mem_ctx, cur_while);\n\n\t next = new_block();\n\t next->start = (backend_instruction *)inst->next;\n\t if (inst->predicate)\n\t cur->add_successor(mem_ctx, next);\n\n\t set_next_block(&cur, next, ip);\n\t break;\n\n case BRW_OPCODE_WHILE:\n\t cur_while->start = (backend_instruction *)inst->next;\n\n\t cur->add_successor(mem_ctx, cur_do);\n\t set_next_block(&cur, cur_while, ip);\n\n\t \/* Pop the stack so we're in the previous loop *\/\n\t cur_do = pop_stack(&do_stack);\n\t cur_while = pop_stack(&while_stack);\n\t break;\n\n default:\n\t break;\n }\n }\n\n cur->end_ip = ip;\n\n make_block_array();\n}\n\ncfg_t::~cfg_t()\n{\n ralloc_free(mem_ctx);\n}\n\nbblock_t *\ncfg_t::new_block()\n{\n bblock_t *block = new(mem_ctx) bblock_t();\n\n return block;\n}\n\nvoid\ncfg_t::set_next_block(bblock_t **cur, bblock_t *block, int ip)\n{\n if (*cur) {\n assert((*cur)->end->next == block->start);\n (*cur)->end_ip = ip - 1;\n }\n\n block->start_ip = ip;\n block->block_num = num_blocks++;\n block_list.push_tail(link(mem_ctx, block));\n *cur = block;\n}\n\nvoid\ncfg_t::make_block_array()\n{\n blocks = ralloc_array(mem_ctx, bblock_t *, num_blocks);\n\n int i = 0;\n foreach_list_typed(bblock_link, link, link, &block_list) {\n blocks[i++] = link->block;\n }\n assert(i == num_blocks);\n}\n\nvoid\ncfg_t::dump(backend_visitor *v)\n{\n for (int b = 0; b < this->num_blocks; b++) {\n bblock_t *block = this->blocks[b];\n fprintf(stderr, \"START B%d\", b);\n foreach_list_typed(bblock_link, link, link, &block->parents) {\n fprintf(stderr, \" <-B%d\",\n link->block->block_num);\n }\n fprintf(stderr, \"\\n\");\n block->dump(v);\n fprintf(stderr, \"END B%d\", b);\n foreach_list_typed(bblock_link, link, link, &block->children) {\n fprintf(stderr, \" ->B%d\",\n link->block->block_num);\n }\n fprintf(stderr, \"\\n\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\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#include \"combined_matrix_store.h\"\n#include \"dense_matrix.h\"\n#include \"local_matrix_store.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\nstruct mat_info\n{\n\tsize_t nrow;\n\tsize_t ncol;\n\tbool in_mem;\n};\n\nstatic mat_info get_matrix_info(const std::vector<matrix_store::const_ptr> &mats)\n{\n\tmat_info info;\n\tbool is_wide = mats.front()->is_wide();\n\tinfo.nrow = mats.front()->get_num_rows();\n\tinfo.ncol = mats.front()->get_num_cols();\n\tinfo.in_mem = mats.front()->is_in_mem();\n\n\tfor (size_t i = 1; i < mats.size(); i++) {\n\t\tif (is_wide)\n\t\t\tinfo.nrow += mats[i]->get_num_rows();\n\t\telse\n\t\t\tinfo.ncol += mats[i]->get_num_cols();\n\t\tinfo.in_mem = info.in_mem && mats[i]->is_in_mem();\n\t}\n\treturn info;\n}\n\ncombined_matrix_store::ptr combined_matrix_store::create(\n\t\tconst std::vector<matrix_store::const_ptr> &mats, matrix_layout_t layout)\n{\n\tif (mats.empty()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"can't combine 0 matrices\";\n\t\treturn combined_matrix_store::ptr();\n\t}\n\tconst scalar_type &type = mats.front()->get_type();\n\tbool is_wide = mats.front()->is_wide();\n\tfor (size_t i = 1; i < mats.size(); i++) {\n\t\tif (mats[i]->get_type() != type) {\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t<< \"can't combine matrices of different element types\";\n\t\t\treturn combined_matrix_store::ptr();\n\t\t}\n\t\tif (mats[i]->is_wide() != is_wide) {\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t<< \"can't combine matrices of different row\/col length\";\n\t\t\treturn combined_matrix_store::ptr();\n\t\t}\n\t}\n\tif (is_wide) {\n\t\tsize_t num_cols = mats.front()->get_num_cols();\n\t\tfor (size_t i = 1; i < mats.size(); i++) {\n\t\t\tif (mats[i]->get_num_cols() != num_cols) {\n\t\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t\t<< \"can't combine matrices with different row lengths\";\n\t\t\t\treturn combined_matrix_store::ptr();\n\t\t\t}\n\t\t}\n\t\treturn ptr(new combined_matrix_store(mats, layout));\n\t}\n\telse {\n\t\tsize_t num_rows = mats.front()->get_num_rows();\n\t\tfor (size_t i = 1; i < mats.size(); i++) {\n\t\t\tif (mats[i]->get_num_rows() != num_rows) {\n\t\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t\t<< \"can't combine matrices with different col lengths\";\n\t\t\t\treturn combined_matrix_store::ptr();\n\t\t\t}\n\t\t}\n\t\treturn ptr(new combined_matrix_store(mats, layout));\n\t}\n}\n\nnamespace\n{\n\nclass combine_tall_op: public portion_mapply_op\n{\npublic:\n\tcombine_tall_op(size_t num_rows, size_t num_cols,\n\t\t\tconst scalar_type &t): portion_mapply_op(num_rows, num_cols, t) {\n\t}\n\n\tvirtual portion_mapply_op::const_ptr transpose() const;\n\tvirtual void run(const std::vector<local_matrix_store::const_ptr> &ins,\n\t\t\tlocal_matrix_store &out) const;\n\tvirtual std::string to_string(\n\t\t\tconst std::vector<matrix_store::const_ptr> &mats) const {\n\t\t\/\/ TODO\n\t\treturn \"\";\n\t}\n};\n\nclass combine_wide_op: public portion_mapply_op\n{\npublic:\n\tcombine_wide_op(size_t num_rows, size_t num_cols,\n\t\t\tconst scalar_type &t): portion_mapply_op(num_rows, num_cols, t) {\n\t}\n\n\tvirtual portion_mapply_op::const_ptr transpose() const;\n\tvirtual void run(const std::vector<local_matrix_store::const_ptr> &ins,\n\t\t\tlocal_matrix_store &out) const;\n\tvirtual std::string to_string(\n\t\t\tconst std::vector<matrix_store::const_ptr> &mats) const {\n\t\t\/\/ TODO\n\t\treturn \"\";\n\t}\n};\n\nportion_mapply_op::const_ptr combine_tall_op::transpose() const\n{\n\treturn portion_mapply_op::const_ptr(new combine_wide_op(get_out_num_cols(),\n\t\t\t\tget_out_num_rows(), get_output_type()));\n}\n\nvoid combine_tall_op::run(const std::vector<local_matrix_store::const_ptr> &ins,\n\t\tlocal_matrix_store &out) const\n{\n\tsize_t col_idx = 0;\n\tlocal_matrix_store::exposed_area area = out.get_exposed_area();\n\toff_t local_start_row = out.get_local_start_row();\n\toff_t local_start_col = out.get_local_start_col();\n\tfor (size_t i = 0; i < ins.size(); i++) {\n\t\tout.resize(local_start_row, local_start_col + col_idx,\n\t\t\t\tout.get_num_rows(), ins[i]->get_num_cols());\n\t\tout.copy_from(*ins[i]);\n\t\tcol_idx += ins[i]->get_num_cols();\n\t}\n\tout.restore_size(area);\n\tassert(col_idx == out.get_num_cols());\n}\n\nportion_mapply_op::const_ptr combine_wide_op::transpose() const\n{\n\treturn portion_mapply_op::const_ptr(new combine_tall_op(get_out_num_cols(),\n\t\t\t\tget_out_num_rows(), get_output_type()));\n}\n\nvoid combine_wide_op::run(const std::vector<local_matrix_store::const_ptr> &ins,\n\t\tlocal_matrix_store &out) const\n{\n\tsize_t row_idx = 0;\n\tlocal_matrix_store::exposed_area area = out.get_exposed_area();\n\toff_t local_start_row = out.get_local_start_row();\n\toff_t local_start_col = out.get_local_start_col();\n\tfor (size_t i = 0; i < ins.size(); i++) {\n\t\tout.resize(local_start_row + row_idx, local_start_col,\n\t\t\t\tins[i]->get_num_rows(), out.get_num_cols());\n\t\t\/\/ TODO I need to test the performance of memory copy\n\t\t\/\/ It might be slow.\n\t\tout.copy_from(*ins[i]);\n\t\trow_idx += ins[i]->get_num_rows();\n\t}\n\tout.restore_size(area);\n\tassert(row_idx == out.get_num_rows());\n}\n\n}\n\nstatic portion_mapply_op::const_ptr get_combine_op(\n\t\tconst std::vector<matrix_store::const_ptr> &mats)\n{\n\tmat_info info = get_matrix_info(mats);\n\tconst scalar_type &type = mats.front()->get_type();\n\tif (mats.front()->is_wide())\n\t\treturn portion_mapply_op::const_ptr(new combine_wide_op(info.nrow,\n\t\t\t\t\tinfo.ncol, type));\n\telse\n\t\treturn portion_mapply_op::const_ptr(new combine_tall_op(info.nrow,\n\t\t\t\t\tinfo.ncol, type));\n}\n\ncombined_matrix_store::combined_matrix_store(\n\t\tconst std::vector<matrix_store::const_ptr> &mats,\n\t\tmatrix_layout_t layout): mapply_matrix_store(mats,\n\t\t\tget_combine_op(mats), layout)\n{\n\tthis->mats = mats;\n}\n\nstd::string combined_matrix_store::get_name() const\n{\n\tstd::string name = std::string(\"combine(\") + mats[0]->get_name();\n\tfor (size_t i = 1; mats.size(); i++)\n\t\tname += std::string(\", \") + mats[i]->get_name();\n\tname += \")\";\n\treturn name;\n}\n\nmatrix_store::const_ptr combined_matrix_store::transpose() const\n{\n\tstd::vector<matrix_store::const_ptr> tmp(mats.size());\n\tfor (size_t i = 0; i < tmp.size(); i++)\n\t\ttmp[i] = mats[i]->transpose();\n\tmatrix_layout_t layout;\n\tif (store_layout() == matrix_layout_t::L_ROW)\n\t\tlayout = matrix_layout_t::L_COL;\n\telse\n\t\tlayout = matrix_layout_t::L_ROW;\n\treturn matrix_store::const_ptr(new combined_matrix_store(tmp, layout));\n}\n\nmatrix_store::const_ptr combined_matrix_store::get_rows(\n\t\tconst std::vector<off_t> &idxs) const\n{\n\tif (!is_wide()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"Cannot get rows from a tall matrix\";\n\t\treturn matrix_store::const_ptr();\n\t}\n\n\toff_t start_row = 0;\n\tmatrix_store::const_ptr mat;\n\t\/\/ Find the right matrix.\n\tfor (size_t i = 0; i < mats.size(); i++) {\n\t\t\/\/ We assume all required rows are from the same matrix.\n\t\tif (idxs[0] >= start_row\n\t\t\t\t&& (size_t) idxs[0] < start_row + mats[i]->get_num_rows()) {\n\t\t\tmat = mats[i];\n\t\t\tbreak;\n\t\t}\n\t\tstart_row += mats[i]->get_num_rows();\n\t}\n\tif (mat == NULL) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"row idxs are out of bounds\";\n\t\treturn matrix_store::const_ptr();\n\t}\n\n\tassert((size_t) start_row < get_num_rows()\n\t\t\t&& start_row + mat->get_num_rows() <= get_num_rows());\n\tstd::vector<off_t> local_idxs(idxs.size());\n\tfor (size_t i = 0; i < idxs.size(); i++) {\n\t\tif (idxs[i] < start_row\n\t\t\t\t|| (size_t) idxs[i] >= start_row + mat->get_num_rows()) {\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t<< \"Not all rows are in the same physical matrix.\";\n\t\t\treturn matrix_store::const_ptr();\n\t\t}\n\t\tlocal_idxs[i] = idxs[i] - start_row;\n\t}\n\t\/\/ If we want to access all rows of the matrix, we can return\n\t\/\/ the entire matrix directly.\n\tif (local_idxs.size() == mat->get_num_rows()\n\t\t\t&& std::is_sorted(local_idxs.begin(), local_idxs.end()))\n\t\treturn mat;\n\telse\n\t\treturn mat->get_rows(local_idxs);\n}\n\n}\n\n}\n<commit_msg>[Matrix]: fix a bug in get_name of combined_matrix_store.<commit_after>\/*\n * Copyright 2016 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\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#include \"combined_matrix_store.h\"\n#include \"dense_matrix.h\"\n#include \"local_matrix_store.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\nstruct mat_info\n{\n\tsize_t nrow;\n\tsize_t ncol;\n\tbool in_mem;\n};\n\nstatic mat_info get_matrix_info(const std::vector<matrix_store::const_ptr> &mats)\n{\n\tmat_info info;\n\tbool is_wide = mats.front()->is_wide();\n\tinfo.nrow = mats.front()->get_num_rows();\n\tinfo.ncol = mats.front()->get_num_cols();\n\tinfo.in_mem = mats.front()->is_in_mem();\n\n\tfor (size_t i = 1; i < mats.size(); i++) {\n\t\tif (is_wide)\n\t\t\tinfo.nrow += mats[i]->get_num_rows();\n\t\telse\n\t\t\tinfo.ncol += mats[i]->get_num_cols();\n\t\tinfo.in_mem = info.in_mem && mats[i]->is_in_mem();\n\t}\n\treturn info;\n}\n\ncombined_matrix_store::ptr combined_matrix_store::create(\n\t\tconst std::vector<matrix_store::const_ptr> &mats, matrix_layout_t layout)\n{\n\tif (mats.empty()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"can't combine 0 matrices\";\n\t\treturn combined_matrix_store::ptr();\n\t}\n\tconst scalar_type &type = mats.front()->get_type();\n\tbool is_wide = mats.front()->is_wide();\n\tfor (size_t i = 1; i < mats.size(); i++) {\n\t\tif (mats[i]->get_type() != type) {\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t<< \"can't combine matrices of different element types\";\n\t\t\treturn combined_matrix_store::ptr();\n\t\t}\n\t\tif (mats[i]->is_wide() != is_wide) {\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t<< \"can't combine matrices of different row\/col length\";\n\t\t\treturn combined_matrix_store::ptr();\n\t\t}\n\t}\n\tif (is_wide) {\n\t\tsize_t num_cols = mats.front()->get_num_cols();\n\t\tfor (size_t i = 1; i < mats.size(); i++) {\n\t\t\tif (mats[i]->get_num_cols() != num_cols) {\n\t\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t\t<< \"can't combine matrices with different row lengths\";\n\t\t\t\treturn combined_matrix_store::ptr();\n\t\t\t}\n\t\t}\n\t\treturn ptr(new combined_matrix_store(mats, layout));\n\t}\n\telse {\n\t\tsize_t num_rows = mats.front()->get_num_rows();\n\t\tfor (size_t i = 1; i < mats.size(); i++) {\n\t\t\tif (mats[i]->get_num_rows() != num_rows) {\n\t\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t\t<< \"can't combine matrices with different col lengths\";\n\t\t\t\treturn combined_matrix_store::ptr();\n\t\t\t}\n\t\t}\n\t\treturn ptr(new combined_matrix_store(mats, layout));\n\t}\n}\n\nnamespace\n{\n\nclass combine_tall_op: public portion_mapply_op\n{\npublic:\n\tcombine_tall_op(size_t num_rows, size_t num_cols,\n\t\t\tconst scalar_type &t): portion_mapply_op(num_rows, num_cols, t) {\n\t}\n\n\tvirtual portion_mapply_op::const_ptr transpose() const;\n\tvirtual void run(const std::vector<local_matrix_store::const_ptr> &ins,\n\t\t\tlocal_matrix_store &out) const;\n\tvirtual std::string to_string(\n\t\t\tconst std::vector<matrix_store::const_ptr> &mats) const {\n\t\t\/\/ TODO\n\t\treturn \"\";\n\t}\n};\n\nclass combine_wide_op: public portion_mapply_op\n{\npublic:\n\tcombine_wide_op(size_t num_rows, size_t num_cols,\n\t\t\tconst scalar_type &t): portion_mapply_op(num_rows, num_cols, t) {\n\t}\n\n\tvirtual portion_mapply_op::const_ptr transpose() const;\n\tvirtual void run(const std::vector<local_matrix_store::const_ptr> &ins,\n\t\t\tlocal_matrix_store &out) const;\n\tvirtual std::string to_string(\n\t\t\tconst std::vector<matrix_store::const_ptr> &mats) const {\n\t\t\/\/ TODO\n\t\treturn \"\";\n\t}\n};\n\nportion_mapply_op::const_ptr combine_tall_op::transpose() const\n{\n\treturn portion_mapply_op::const_ptr(new combine_wide_op(get_out_num_cols(),\n\t\t\t\tget_out_num_rows(), get_output_type()));\n}\n\nvoid combine_tall_op::run(const std::vector<local_matrix_store::const_ptr> &ins,\n\t\tlocal_matrix_store &out) const\n{\n\tsize_t col_idx = 0;\n\tlocal_matrix_store::exposed_area area = out.get_exposed_area();\n\toff_t local_start_row = out.get_local_start_row();\n\toff_t local_start_col = out.get_local_start_col();\n\tfor (size_t i = 0; i < ins.size(); i++) {\n\t\tout.resize(local_start_row, local_start_col + col_idx,\n\t\t\t\tout.get_num_rows(), ins[i]->get_num_cols());\n\t\tout.copy_from(*ins[i]);\n\t\tcol_idx += ins[i]->get_num_cols();\n\t}\n\tout.restore_size(area);\n\tassert(col_idx == out.get_num_cols());\n}\n\nportion_mapply_op::const_ptr combine_wide_op::transpose() const\n{\n\treturn portion_mapply_op::const_ptr(new combine_tall_op(get_out_num_cols(),\n\t\t\t\tget_out_num_rows(), get_output_type()));\n}\n\nvoid combine_wide_op::run(const std::vector<local_matrix_store::const_ptr> &ins,\n\t\tlocal_matrix_store &out) const\n{\n\tsize_t row_idx = 0;\n\tlocal_matrix_store::exposed_area area = out.get_exposed_area();\n\toff_t local_start_row = out.get_local_start_row();\n\toff_t local_start_col = out.get_local_start_col();\n\tfor (size_t i = 0; i < ins.size(); i++) {\n\t\tout.resize(local_start_row + row_idx, local_start_col,\n\t\t\t\tins[i]->get_num_rows(), out.get_num_cols());\n\t\t\/\/ TODO I need to test the performance of memory copy\n\t\t\/\/ It might be slow.\n\t\tout.copy_from(*ins[i]);\n\t\trow_idx += ins[i]->get_num_rows();\n\t}\n\tout.restore_size(area);\n\tassert(row_idx == out.get_num_rows());\n}\n\n}\n\nstatic portion_mapply_op::const_ptr get_combine_op(\n\t\tconst std::vector<matrix_store::const_ptr> &mats)\n{\n\tmat_info info = get_matrix_info(mats);\n\tconst scalar_type &type = mats.front()->get_type();\n\tif (mats.front()->is_wide())\n\t\treturn portion_mapply_op::const_ptr(new combine_wide_op(info.nrow,\n\t\t\t\t\tinfo.ncol, type));\n\telse\n\t\treturn portion_mapply_op::const_ptr(new combine_tall_op(info.nrow,\n\t\t\t\t\tinfo.ncol, type));\n}\n\ncombined_matrix_store::combined_matrix_store(\n\t\tconst std::vector<matrix_store::const_ptr> &mats,\n\t\tmatrix_layout_t layout): mapply_matrix_store(mats,\n\t\t\tget_combine_op(mats), layout)\n{\n\tthis->mats = mats;\n}\n\nstd::string combined_matrix_store::get_name() const\n{\n\tstd::string name = std::string(\"combine(\") + mats[0]->get_name();\n\tfor (size_t i = 1; i < mats.size(); i++)\n\t\tname += std::string(\", \") + mats[i]->get_name();\n\tname += \")\";\n\treturn name;\n}\n\nmatrix_store::const_ptr combined_matrix_store::transpose() const\n{\n\tstd::vector<matrix_store::const_ptr> tmp(mats.size());\n\tfor (size_t i = 0; i < tmp.size(); i++)\n\t\ttmp[i] = mats[i]->transpose();\n\tmatrix_layout_t layout;\n\tif (store_layout() == matrix_layout_t::L_ROW)\n\t\tlayout = matrix_layout_t::L_COL;\n\telse\n\t\tlayout = matrix_layout_t::L_ROW;\n\treturn matrix_store::const_ptr(new combined_matrix_store(tmp, layout));\n}\n\nmatrix_store::const_ptr combined_matrix_store::get_rows(\n\t\tconst std::vector<off_t> &idxs) const\n{\n\tif (!is_wide()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"Cannot get rows from a tall matrix\";\n\t\treturn matrix_store::const_ptr();\n\t}\n\n\toff_t start_row = 0;\n\tmatrix_store::const_ptr mat;\n\t\/\/ Find the right matrix.\n\tfor (size_t i = 0; i < mats.size(); i++) {\n\t\t\/\/ We assume all required rows are from the same matrix.\n\t\tif (idxs[0] >= start_row\n\t\t\t\t&& (size_t) idxs[0] < start_row + mats[i]->get_num_rows()) {\n\t\t\tmat = mats[i];\n\t\t\tbreak;\n\t\t}\n\t\tstart_row += mats[i]->get_num_rows();\n\t}\n\tif (mat == NULL) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"row idxs are out of bounds\";\n\t\treturn matrix_store::const_ptr();\n\t}\n\n\tassert((size_t) start_row < get_num_rows()\n\t\t\t&& start_row + mat->get_num_rows() <= get_num_rows());\n\tstd::vector<off_t> local_idxs(idxs.size());\n\tfor (size_t i = 0; i < idxs.size(); i++) {\n\t\tif (idxs[i] < start_row\n\t\t\t\t|| (size_t) idxs[i] >= start_row + mat->get_num_rows()) {\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t<< \"Not all rows are in the same physical matrix.\";\n\t\t\treturn matrix_store::const_ptr();\n\t\t}\n\t\tlocal_idxs[i] = idxs[i] - start_row;\n\t}\n\t\/\/ If we want to access all rows of the matrix, we can return\n\t\/\/ the entire matrix directly.\n\tif (local_idxs.size() == mat->get_num_rows()\n\t\t\t&& std::is_sorted(local_idxs.begin(), local_idxs.end()))\n\t\treturn mat;\n\telse\n\t\treturn mat->get_rows(local_idxs);\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PresentationViewShellBase.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 19:06:40 $\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_sd.hxx\"\n\n#include \"PresentationViewShellBase.hxx\"\n\n#ifndef SD_RESID_HXX\n#include \"sdresid.hxx\"\n#endif\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"DrawDocShell.hxx\"\n#endif\n#include \"strings.hrc\"\n#include \"ViewTabBar.hxx\"\n#include \"UpdateLockManager.hxx\"\n\n#include <sfx2\/viewfrm.hxx>\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_\n#include <com\/sun\/star\/frame\/XLayoutManager.hpp>\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nnamespace sd {\n\nclass DrawDocShell;\n\nTYPEINIT1(PresentationViewShellBase, ViewShellBase);\n\n\/\/ We have to expand the SFX_IMPL_VIEWFACTORY macro to call LateInit() after a\n\/\/ new PresentationViewShellBase object has been constructed.\n\n\/*\nSFX_IMPL_VIEWFACTORY(PresentationViewShellBase, SdResId(STR_DEFAULTVIEW))\n{\n SFX_VIEW_REGISTRATION(DrawDocShell);\n}\n*\/\nSfxViewFactory* PresentationViewShellBase::pFactory;\nSfxViewShell* __EXPORT PresentationViewShellBase::CreateInstance (\n SfxViewFrame *_pFrame, SfxViewShell *pOldView)\n{\n PresentationViewShellBase* pBase =\n new PresentationViewShellBase(_pFrame, pOldView);\n pBase->LateInit();\n return pBase;\n}\nvoid PresentationViewShellBase::RegisterFactory( USHORT nPrio )\n{\n pFactory = new SfxViewFactory(\n &CreateInstance,&InitFactory,nPrio,SdResId(STR_DEFAULTVIEW));\n InitFactory();\n}\nvoid PresentationViewShellBase::InitFactory()\n{\n SFX_VIEW_REGISTRATION(DrawDocShell);\n}\n\n\n\n\nPresentationViewShellBase::PresentationViewShellBase (\n SfxViewFrame* _pFrame,\n SfxViewShell* pOldShell)\n : ViewShellBase (_pFrame, pOldShell, ViewShell::ST_PRESENTATION)\n{\n GetUpdateLockManager().Disable();\n\n \/\/ Hide the automatic (non-context sensitive) tool bars.\n if (_pFrame!=NULL && _pFrame->GetFrame()!=NULL)\n {\n Reference<beans::XPropertySet> xFrameSet (\n _pFrame->GetFrame()->GetFrameInterface(),\n UNO_QUERY);\n if (xFrameSet.is())\n {\n Reference<beans::XPropertySet> xLayouterSet (\n xFrameSet->getPropertyValue(::rtl::OUString::createFromAscii(\"LayoutManager\")),\n UNO_QUERY);\n if (xLayouterSet.is())\n {\n xLayouterSet->setPropertyValue(\n ::rtl::OUString::createFromAscii(\"AutomaticToolbars\"),\n makeAny(sal_False));\n }\n }\n }\n}\n\n\n\n\nViewTabBar* PresentationViewShellBase::CreateViewTabBar (void)\n{\n \/\/ The ViewTabBar is not supported.\n return NULL;\n}\n\n\n\n\nPresentationViewShellBase::~PresentationViewShellBase (void)\n{\n}\n\n\n\n} \/\/ end of namespace sd\n\n<commit_msg>INTEGRATION: CWS components1 (1.6.96); FILE MERGED 2007\/01\/31 13:52:53 af 1.6.96.6: #i68075# UpdateLockManager stored as shared_ptr. 2007\/01\/25 15:34:34 af 1.6.96.5: RESYNC: (1.8-1.9); FILE MERGED 2006\/09\/25 17:41:08 af 1.6.96.4: RESYNC: (1.6-1.8); FILE MERGED 2006\/09\/07 14:51:55 af 1.6.96.3: #i68075# Transition from URL to ResourceId. 2006\/08\/28 14:32:33 af 1.6.96.2: #i68075# Fixed compiler problems. 2006\/08\/22 12:43:11 af 1.6.96.1: #i68075# Transition to new drawing framework.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PresentationViewShellBase.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2007-04-03 16:27:25 $\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_sd.hxx\"\n\n#include \"PresentationViewShellBase.hxx\"\n\n#ifndef SD_RESID_HXX\n#include \"sdresid.hxx\"\n#endif\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"DrawDocShell.hxx\"\n#endif\n#include \"strings.hrc\"\n#include \"UpdateLockManager.hxx\"\n#include \"framework\/FrameworkHelper.hxx\"\n#include \"framework\/PresentationModule.hxx\"\n\n#include <sfx2\/viewfrm.hxx>\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_\n#include <com\/sun\/star\/frame\/XLayoutManager.hpp>\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nnamespace sd {\n\nclass DrawDocShell;\n\nTYPEINIT1(PresentationViewShellBase, ViewShellBase);\n\n\/\/ We have to expand the SFX_IMPL_VIEWFACTORY macro to call LateInit() after a\n\/\/ new PresentationViewShellBase object has been constructed.\n\n\/*\nSFX_IMPL_VIEWFACTORY(PresentationViewShellBase, SdResId(STR_DEFAULTVIEW))\n{\n SFX_VIEW_REGISTRATION(DrawDocShell);\n}\n*\/\nSfxViewFactory* PresentationViewShellBase::pFactory;\nSfxViewShell* __EXPORT PresentationViewShellBase::CreateInstance (\n SfxViewFrame *_pFrame, SfxViewShell *pOldView)\n{\n PresentationViewShellBase* pBase =\n new PresentationViewShellBase(_pFrame, pOldView);\n pBase->LateInit(framework::FrameworkHelper::msPresentationViewURL);\n return pBase;\n}\nvoid PresentationViewShellBase::RegisterFactory( USHORT nPrio )\n{\n pFactory = new SfxViewFactory(\n &CreateInstance,&InitFactory,nPrio,SdResId(STR_DEFAULTVIEW));\n InitFactory();\n}\nvoid PresentationViewShellBase::InitFactory()\n{\n SFX_VIEW_REGISTRATION(DrawDocShell);\n}\n\n\n\n\nPresentationViewShellBase::PresentationViewShellBase (\n SfxViewFrame* _pFrame,\n SfxViewShell* pOldShell)\n : ViewShellBase (_pFrame, pOldShell)\n{\n GetUpdateLockManager()->Disable();\n\n \/\/ Hide the automatic (non-context sensitive) tool bars.\n if (_pFrame!=NULL && _pFrame->GetFrame()!=NULL)\n {\n Reference<beans::XPropertySet> xFrameSet (\n _pFrame->GetFrame()->GetFrameInterface(),\n UNO_QUERY);\n if (xFrameSet.is())\n {\n Reference<beans::XPropertySet> xLayouterSet (\n xFrameSet->getPropertyValue(::rtl::OUString::createFromAscii(\"LayoutManager\")),\n UNO_QUERY);\n if (xLayouterSet.is())\n {\n xLayouterSet->setPropertyValue(\n ::rtl::OUString::createFromAscii(\"AutomaticToolbars\"),\n makeAny(sal_False));\n }\n }\n }\n}\n\n\n\n\nPresentationViewShellBase::~PresentationViewShellBase (void)\n{\n}\n\n\n\n\nvoid PresentationViewShellBase::InitializeFramework (void)\n{\n com::sun::star::uno::Reference<com::sun::star::frame::XController>\n xController (GetController());\n sd::framework::PresentationModule::Initialize(xController);\n}\n\n} \/\/ end of namespace sd\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: types.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2004-02-03 12:52:17 $\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#include \"bridges\/cpp_uno\/shared\/types.hxx\"\n#define INCLUDED_BRIDGES_CPP_UNO_SHARED_VTABLES_HXX\n\n#include \"typelib\/typeclass.h\"\n#include \"typelib\/typedescription.h\"\n\nnamespace {\n\nbool isSimpleTypeClass(typelib_TypeClass typeClass) {\n return typeClass <= typelib_TypeClass_DOUBLE\n || typeClass == typelib_TypeClass_ENUM;\n}\n\n}\n\nnamespace bridges { namespace cpp_uno { namespace shared {\n\nbool isSimpleType(typelib_TypeDescriptionReference const * type) {\n return isSimpleTypeClass(type->eTypeClass);\n}\n\nbool isSimpleType(typelib_TypeDescription const * type) {\n return isSimpleTypeClass(type->eTypeClass);\n}\n\nbool relatesToInterfaceType(typelib_TypeDescription const * type) {\n switch (type->eTypeClass) {\n case typelib_TypeClass_ANY:\n case typelib_TypeClass_INTERFACE:\n return true;\n\n case typelib_TypeClass_STRUCT:\n case typelib_TypeClass_EXCEPTION:\n {\n typelib_CompoundTypeDescription const * p\n = reinterpret_cast< typelib_CompoundTypeDescription const * >(\n type);\n for (sal_Int32 i = 0; i < p->nMembers; ++i) {\n switch (p->ppTypeRefs[i]->eTypeClass) {\n case typelib_TypeClass_ANY:\n case typelib_TypeClass_INTERFACE:\n return true;\n\n case typelib_TypeClass_STRUCT:\n case typelib_TypeClass_EXCEPTION:\n case typelib_TypeClass_SEQUENCE:\n {\n typelib_TypeDescription * t = 0;\n TYPELIB_DANGER_GET(&t, p->ppTypeRefs[i]);\n bool b = relatesToInterfaceType(t);\n TYPELIB_DANGER_RELEASE(t);\n if (b) {\n return true;\n }\n }\n break;\n }\n }\n if (p->pBaseTypeDescription != 0) {\n return relatesToInterfaceType(&p->pBaseTypeDescription->aBase);\n }\n }\n break;\n\n case typelib_TypeClass_SEQUENCE:\n switch (reinterpret_cast< typelib_IndirectTypeDescription const * >(\n type)->pType->eTypeClass) {\n case typelib_TypeClass_ANY:\n case typelib_TypeClass_INTERFACE:\n return true;\n\n case typelib_TypeClass_STRUCT:\n case typelib_TypeClass_EXCEPTION:\n case typelib_TypeClass_SEQUENCE:\n {\n typelib_TypeDescription * t = 0;\n TYPELIB_DANGER_GET(\n &t,\n reinterpret_cast< typelib_IndirectTypeDescription const * >(\n type)->pType);\n bool b = relatesToInterfaceType(t);\n TYPELIB_DANGER_RELEASE(t);\n return b;\n }\n }\n break;\n }\n return false;\n}\n\n} } }\n<commit_msg>INTEGRATION: CWS sb29 (1.2.68); FILE MERGED 2005\/01\/31 13:32:04 sb 1.2.68.1: #i41344# Adapted Solaris Intel cpp_uno bridge to multiple-inheritance UNO interface types.<commit_after>\/*************************************************************************\n *\n * $RCSfile: types.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2005-02-21 12:15: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#include \"bridges\/cpp_uno\/shared\/types.hxx\"\n#define INCLUDED_BRIDGES_CPP_UNO_SHARED_VTABLES_HXX\n\n#include \"typelib\/typeclass.h\"\n#include \"typelib\/typedescription.h\"\n\nnamespace bridges { namespace cpp_uno { namespace shared {\n\nbool isSimpleType(typelib_TypeClass typeClass) {\n return typeClass <= typelib_TypeClass_DOUBLE\n || typeClass == typelib_TypeClass_ENUM;\n}\n\nbool isSimpleType(typelib_TypeDescriptionReference const * type) {\n return isSimpleType(type->eTypeClass);\n}\n\nbool isSimpleType(typelib_TypeDescription const * type) {\n return isSimpleType(type->eTypeClass);\n}\n\nbool relatesToInterfaceType(typelib_TypeDescription const * type) {\n switch (type->eTypeClass) {\n case typelib_TypeClass_ANY:\n case typelib_TypeClass_INTERFACE:\n return true;\n\n case typelib_TypeClass_STRUCT:\n case typelib_TypeClass_EXCEPTION:\n {\n typelib_CompoundTypeDescription const * p\n = reinterpret_cast< typelib_CompoundTypeDescription const * >(\n type);\n for (sal_Int32 i = 0; i < p->nMembers; ++i) {\n switch (p->ppTypeRefs[i]->eTypeClass) {\n case typelib_TypeClass_ANY:\n case typelib_TypeClass_INTERFACE:\n return true;\n\n case typelib_TypeClass_STRUCT:\n case typelib_TypeClass_EXCEPTION:\n case typelib_TypeClass_SEQUENCE:\n {\n typelib_TypeDescription * t = 0;\n TYPELIB_DANGER_GET(&t, p->ppTypeRefs[i]);\n bool b = relatesToInterfaceType(t);\n TYPELIB_DANGER_RELEASE(t);\n if (b) {\n return true;\n }\n }\n break;\n }\n }\n if (p->pBaseTypeDescription != 0) {\n return relatesToInterfaceType(&p->pBaseTypeDescription->aBase);\n }\n }\n break;\n\n case typelib_TypeClass_SEQUENCE:\n switch (reinterpret_cast< typelib_IndirectTypeDescription const * >(\n type)->pType->eTypeClass) {\n case typelib_TypeClass_ANY:\n case typelib_TypeClass_INTERFACE:\n return true;\n\n case typelib_TypeClass_STRUCT:\n case typelib_TypeClass_EXCEPTION:\n case typelib_TypeClass_SEQUENCE:\n {\n typelib_TypeDescription * t = 0;\n TYPELIB_DANGER_GET(\n &t,\n reinterpret_cast< typelib_IndirectTypeDescription const * >(\n type)->pType);\n bool b = relatesToInterfaceType(t);\n TYPELIB_DANGER_RELEASE(t);\n return b;\n }\n }\n break;\n }\n return false;\n}\n\n} } }\n<|endoftext|>"} {"text":"<commit_before>#include <build-bot\/bot.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#include <boost\/filesystem.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/ini_parser.hpp>\n\nnamespace fs = boost::filesystem;\nusing namespace dsn::build_bot;\n\nnamespace dsn {\nnamespace build_bot {\n namespace priv {\n class Bot : public dsn::log::Base<Bot> {\n protected:\n boost::property_tree::ptree m_settings;\n\n bool loadConfig(const std::string& config_file)\n {\n BOOST_LOG_SEV(log, severity::info) << \"Loading configuration from \" << config_file;\n\n fs::path path(config_file);\n if (!fs::exists(path)) {\n BOOST_LOG_SEV(log, severity::error) << \"Config file \" << config_file << \" doesn't exist!\";\n return false;\n }\n\n if (!fs::is_regular_file(path)) {\n BOOST_LOG_SEV(log, severity::error) << \"Config file \" << config_file << \" isn't a regular file!\";\n return false;\n }\n\n try {\n boost::property_tree::read_ini(config_file, m_settings);\n }\n\n catch (boost::property_tree::ini_parser_error& ex) {\n BOOST_LOG_SEV(log, severity::error) << \"Failed to parse config file \" << config_file << \": \" << ex.what();\n return false;\n }\n\n return true;\n }\n\n bool initFifo()\n {\n std::string fifoName;\n try {\n fifoName = m_settings.get<std::string>(\"fifo.name\");\n }\n\n catch (boost::property_tree::ptree_error& ex) {\n BOOST_LOG_SEV(log, severity::error) << \"Failed to get FIFO settings from configuration: \" << ex.what();\n return false;\n }\n\n fs::path path(fifoName);\n if (!fs::exists(path)) {\n BOOST_LOG_SEV(log, severity::warning) << \"FIFO \" << fifoName << \" doesn't exist; trying to create it!\";\n if (mkfifo(fifoName.c_str(), 0666) == -1) {\n BOOST_LOG_SEV(log, severity::error) << \"Failed to create FIFO \" << fifoName << \": \" << strerror(errno);\n return false;\n }\n }\n\n return true;\n }\n\n public:\n bool init(const std::string& config_file)\n {\n if (!loadConfig(config_file))\n return false;\n\n if (!initFifo())\n return false;\n\n return true;\n }\n };\n }\n}\n}\n\nconst std::string dsn::build_bot::Bot::DEFAULT_CONFIG_FILE{ \"etc\/build-bot\/bot.conf\" };\n\nBot::Bot()\n : m_impl(new priv::Bot())\n{\n}\n\nBot::~Bot()\n{\n}\n\nbool Bot::init(const std::string& config_file)\n{\n return m_impl->init(config_file);\n}\n<commit_msg>Add boost::asio::io_service to Bot<commit_after>#include <build-bot\/bot.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#include <boost\/asio.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/ini_parser.hpp>\n\nnamespace fs = boost::filesystem;\nusing namespace dsn::build_bot;\n\nnamespace dsn {\nnamespace build_bot {\n namespace priv {\n class Bot : public dsn::log::Base<Bot> {\n protected:\n boost::property_tree::ptree m_settings;\n\n bool loadConfig(const std::string& config_file)\n {\n BOOST_LOG_SEV(log, severity::info) << \"Loading configuration from \" << config_file;\n\n fs::path path(config_file);\n if (!fs::exists(path)) {\n BOOST_LOG_SEV(log, severity::error) << \"Config file \" << config_file << \" doesn't exist!\";\n return false;\n }\n\n if (!fs::is_regular_file(path)) {\n BOOST_LOG_SEV(log, severity::error) << \"Config file \" << config_file << \" isn't a regular file!\";\n return false;\n }\n\n try {\n boost::property_tree::read_ini(config_file, m_settings);\n }\n\n catch (boost::property_tree::ini_parser_error& ex) {\n BOOST_LOG_SEV(log, severity::error) << \"Failed to parse config file \" << config_file << \": \" << ex.what();\n return false;\n }\n\n return true;\n }\n\n bool initFifo()\n {\n std::string fifoName;\n try {\n fifoName = m_settings.get<std::string>(\"fifo.name\");\n }\n\n catch (boost::property_tree::ptree_error& ex) {\n BOOST_LOG_SEV(log, severity::error) << \"Failed to get FIFO settings from configuration: \" << ex.what();\n return false;\n }\n\n fs::path path(fifoName);\n if (!fs::exists(path)) {\n BOOST_LOG_SEV(log, severity::warning) << \"FIFO \" << fifoName << \" doesn't exist; trying to create it!\";\n if (mkfifo(fifoName.c_str(), 0666) == -1) {\n BOOST_LOG_SEV(log, severity::error) << \"Failed to create FIFO \" << fifoName << \": \" << strerror(errno);\n return false;\n }\n }\n\n return true;\n }\n\n boost::asio::io_service m_io;\n boost::asio::strand m_strand;\n\n public:\n Bot()\n : m_io()\n , m_strand(m_io)\n {\n }\n\n bool init(const std::string& config_file)\n {\n if (!loadConfig(config_file))\n return false;\n\n if (!initFifo())\n return false;\n\n return true;\n }\n };\n }\n}\n}\n\nconst std::string dsn::build_bot::Bot::DEFAULT_CONFIG_FILE{ \"etc\/build-bot\/bot.conf\" };\n\nBot::Bot()\n : m_impl(new priv::Bot())\n{\n}\n\nBot::~Bot()\n{\n}\n\nbool Bot::init(const std::string& config_file)\n{\n return m_impl->init(config_file);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=- LiveVariables.cpp - Live Variable Analysis for Source CFGs -*- C++ --*-==\/\/\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\/\/ This file implements Live Variables analysis for source-level CFGs.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/Analyses\/LiveVariables.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/CFG.h\"\n#include \"clang\/Analysis\/Visitors\/CFGRecStmtDeclVisitor.h\"\n#include \"clang\/Analysis\/FlowSensitive\/DataflowSolver.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/Compiler.h\"\n\n#include <string.h>\n#include <stdio.h>\n\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Useful constants.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nstatic const bool Alive = true;\nstatic const bool Dead = false; \n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Dataflow initialization logic.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\nclass VISIBILITY_HIDDEN RegisterDecls \n : public CFGRecStmtDeclVisitor<RegisterDecls> {\n \n LiveVariables::AnalysisDataTy& AD;\n \n typedef llvm::SmallVector<VarDecl*, 20> AlwaysLiveTy;\n AlwaysLiveTy AlwaysLive;\n\n \npublic:\n RegisterDecls(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}\n\n ~RegisterDecls() {\n\n AD.AlwaysLive.resetValues(AD);\n \n for (AlwaysLiveTy::iterator I = AlwaysLive.begin(), E = AlwaysLive.end();\n I != E; ++ I) \n AD.AlwaysLive(*I, AD) = Alive; \n }\n\n void VisitImplicitParamDecl(ImplicitParamDecl* IPD) {\n \/\/ Register the VarDecl for tracking.\n AD.Register(IPD);\n }\n\n void VisitVarDecl(VarDecl* VD) {\n \/\/ Register the VarDecl for tracking.\n AD.Register(VD);\n \n \/\/ Does the variable have global storage? If so, it is always live.\n if (VD->hasGlobalStorage())\n AlwaysLive.push_back(VD); \n }\n \n void VisitUnaryOperator(UnaryOperator* U) {\n \/\/ Check for '&'. Any VarDecl whose value has its address-taken we\n \/\/ treat as always being live (flow-insensitive).\n\n Expr* E = U->getSubExpr()->IgnoreParenCasts();\n \n if (U->getOpcode() == UnaryOperator::AddrOf)\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))\n if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) {\n AD.Register(VD);\n AlwaysLive.push_back(VD);\n return;\n }\n \n Visit(E);\n }\n \n CFG& getCFG() { return AD.getCFG(); }\n};\n} \/\/ end anonymous namespace\n\n\nLiveVariables::LiveVariables(CFG& cfg) {\n \/\/ Register all referenced VarDecls.\n getAnalysisData().setCFG(&cfg);\n RegisterDecls R(getAnalysisData());\n cfg.VisitBlockStmts(R);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Transfer functions.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\n\nclass VISIBILITY_HIDDEN TransferFuncs : public CFGRecStmtVisitor<TransferFuncs>{\n LiveVariables::AnalysisDataTy& AD;\n LiveVariables::ValTy LiveState;\npublic:\n TransferFuncs(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}\n\n LiveVariables::ValTy& getVal() { return LiveState; }\n CFG& getCFG() { return AD.getCFG(); }\n \n void VisitDeclRefExpr(DeclRefExpr* DR);\n void VisitBinaryOperator(BinaryOperator* B);\n void VisitAssign(BinaryOperator* B);\n void VisitDeclStmt(DeclStmt* DS);\n void BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S);\n void VisitUnaryOperator(UnaryOperator* U);\n void Visit(Stmt *S); \n void VisitTerminator(CFGBlock* B); \n \n void SetTopValue(LiveVariables::ValTy& V) {\n V = AD.AlwaysLive; \n }\n \n};\n \nvoid TransferFuncs::Visit(Stmt *S) {\n \n if (S == getCurrentBlkStmt()) {\n \n if (AD.Observer)\n AD.Observer->ObserveStmt(S,AD,LiveState);\n \n if (getCFG().isBlkExpr(S)) LiveState(S,AD) = Dead;\n StmtVisitor<TransferFuncs,void>::Visit(S);\n }\n else if (!getCFG().isBlkExpr(S)) {\n \n if (AD.Observer)\n AD.Observer->ObserveStmt(S,AD,LiveState);\n \n StmtVisitor<TransferFuncs,void>::Visit(S);\n \n }\n else\n \/\/ For block-level expressions, mark that they are live.\n LiveState(S,AD) = Alive;\n}\n \nvoid TransferFuncs::VisitTerminator(CFGBlock* B) {\n \n const Stmt* E = B->getTerminatorCondition();\n\n if (!E)\n return;\n \n assert (getCFG().isBlkExpr(E));\n LiveState(E, AD) = Alive;\n}\n\nvoid TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {\n if (VarDecl* V = dyn_cast<VarDecl>(DR->getDecl())) \n LiveState(V,AD) = Alive;\n}\n \nvoid TransferFuncs::VisitBinaryOperator(BinaryOperator* B) { \n if (B->isAssignmentOp()) VisitAssign(B);\n else VisitStmt(B);\n}\n\nvoid\nTransferFuncs::BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {\n \n \/\/ This represents a 'use' of the collection.\n Visit(S->getCollection());\n \n \/\/ This represents a 'kill' for the variable.\n Stmt* Element = S->getElement();\n DeclRefExpr *DR = 0;\n VarDecl* VD = 0;\n \n if (DeclStmt* DS = dyn_cast<DeclStmt>(Element))\n VD = cast<VarDecl>(DS->getSolitaryDecl());\n else {\n DR = cast<DeclRefExpr>(Element);\n VD = cast<VarDecl>(DR->getDecl());\n }\n\n LiveState(VD, AD) = Dead;\n if (AD.Observer && DR) { AD.Observer->ObserverKill(DR); }\n}\n\n \nvoid TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {\n Expr *E = U->getSubExpr();\n \n switch (U->getOpcode()) {\n case UnaryOperator::PostInc:\n case UnaryOperator::PostDec:\n case UnaryOperator::PreInc:\n case UnaryOperator::PreDec:\n \/\/ Walk through the subexpressions, blasting through ParenExprs\n \/\/ until we either find a DeclRefExpr or some non-DeclRefExpr\n \/\/ expression.\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E->IgnoreParens())) \n if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) {\n \/\/ Treat the --\/++ operator as a kill.\n if (AD.Observer) { AD.Observer->ObserverKill(DR); }\n LiveState(VD, AD) = Alive;\n return VisitDeclRefExpr(DR);\n }\n\n \/\/ Fall-through.\n \n default:\n return Visit(E);\n }\n}\n \nvoid TransferFuncs::VisitAssign(BinaryOperator* B) { \n Expr* LHS = B->getLHS();\n\n \/\/ Assigning to a variable?\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParens())) {\n \n \/\/ Update liveness inforamtion.\n unsigned bit = AD.getIdx(DR->getDecl());\n LiveState.getDeclBit(bit) = Dead | AD.AlwaysLive.getDeclBit(bit);\n \n if (AD.Observer) { AD.Observer->ObserverKill(DR); }\n \n \/\/ Handle things like +=, etc., which also generate \"uses\"\n \/\/ of a variable. Do this just by visiting the subexpression.\n if (B->getOpcode() != BinaryOperator::Assign)\n VisitDeclRefExpr(DR);\n }\n else \/\/ Not assigning to a variable. Process LHS as usual.\n Visit(LHS);\n \n Visit(B->getRHS());\n}\n\nvoid TransferFuncs::VisitDeclStmt(DeclStmt* DS) {\n \/\/ Declarations effectively \"kill\" a variable since they cannot\n \/\/ possibly be live before they are declared.\n for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end();\n DI != DE; ++DI)\n if (VarDecl* VD = dyn_cast<VarDecl>(*DI)) {\n \/\/ The initializer is evaluated after the variable comes into scope.\n \/\/ Since this is a reverse dataflow analysis, we must evaluate the\n \/\/ transfer function for this expression first.\n if (Expr* Init = VD->getInit())\n Visit(Init);\n \n \/\/ Update liveness information by killing the VarDecl.\n unsigned bit = AD.getIdx(VD);\n LiveState.getDeclBit(bit) = Dead | AD.AlwaysLive.getDeclBit(bit);\n }\n}\n \n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Merge operator: if something is live on any successor block, it is live\n\/\/ in the current block (a set union).\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\n\nstruct Merge {\n typedef StmtDeclBitVector_Types::ValTy ValTy; \n \n void operator()(ValTy& Dst, const ValTy& Src) {\n Dst.OrDeclBits(Src);\n Dst.AndBlkExprBits(Src);\n }\n};\n \ntypedef DataflowSolver<LiveVariables, TransferFuncs, Merge> Solver;\n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ External interface to run Liveness analysis.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nvoid LiveVariables::runOnCFG(CFG& cfg) {\n Solver S(*this);\n S.runOnCFG(cfg);\n}\n\nvoid LiveVariables::runOnAllBlocks(const CFG& cfg,\n LiveVariables::ObserverTy* Obs,\n bool recordStmtValues) {\n Solver S(*this);\n ObserverTy* OldObserver = getAnalysisData().Observer;\n getAnalysisData().Observer = Obs;\n S.runOnAllBlocks(cfg, recordStmtValues);\n getAnalysisData().Observer = OldObserver;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ liveness queries\n\/\/\n\nbool LiveVariables::isLive(const CFGBlock* B, const VarDecl* D) const {\n DeclBitVector_Types::Idx i = getAnalysisData().getIdx(D);\n return i.isValid() ? getBlockData(B).getBit(i) : false;\n}\n\nbool LiveVariables::isLive(const ValTy& Live, const VarDecl* D) const {\n DeclBitVector_Types::Idx i = getAnalysisData().getIdx(D);\n return i.isValid() ? Live.getBit(i) : false;\n}\n\nbool LiveVariables::isLive(const Stmt* Loc, const Stmt* StmtVal) const {\n return getStmtData(Loc)(StmtVal,getAnalysisData());\n}\n\nbool LiveVariables::isLive(const Stmt* Loc, const VarDecl* D) const {\n return getStmtData(Loc)(D,getAnalysisData());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ printing liveness state for debugging\n\/\/\n\nvoid LiveVariables::dumpLiveness(const ValTy& V, SourceManager& SM) const {\n const AnalysisDataTy& AD = getAnalysisData();\n \n for (AnalysisDataTy::decl_iterator I = AD.begin_decl(),\n E = AD.end_decl(); I!=E; ++I)\n if (V.getDeclBit(I->second)) { \n SourceLocation PhysLoc = SM.getPhysicalLoc(I->first->getLocation());\n \n fprintf(stderr, \" %s <%s:%u:%u>\\n\", \n I->first->getIdentifier()->getName(),\n SM.getSourceName(PhysLoc),\n SM.getLineNumber(PhysLoc),\n SM.getColumnNumber(PhysLoc));\n }\n} \n\nvoid LiveVariables::dumpBlockLiveness(SourceManager& M) const {\n for (BlockDataMapTy::iterator I = getBlockDataMap().begin(),\n E = getBlockDataMap().end(); I!=E; ++I) {\n fprintf(stderr, \"\\n[ B%d (live variables at block exit) ]\\n\",\n I->first->getBlockID());\n \n dumpLiveness(I->second,M);\n }\n\n fprintf(stderr,\"\\n\");\n}\n<commit_msg>Handle the case where 'element' in ObjCforCollectionstmt is not a DeclStmt or DeclRefExpr.<commit_after>\/\/=- LiveVariables.cpp - Live Variable Analysis for Source CFGs -*- C++ --*-==\/\/\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\/\/ This file implements Live Variables analysis for source-level CFGs.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/Analyses\/LiveVariables.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/CFG.h\"\n#include \"clang\/Analysis\/Visitors\/CFGRecStmtDeclVisitor.h\"\n#include \"clang\/Analysis\/FlowSensitive\/DataflowSolver.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/Compiler.h\"\n\n#include <string.h>\n#include <stdio.h>\n\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Useful constants.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nstatic const bool Alive = true;\nstatic const bool Dead = false; \n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Dataflow initialization logic.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\nclass VISIBILITY_HIDDEN RegisterDecls \n : public CFGRecStmtDeclVisitor<RegisterDecls> {\n \n LiveVariables::AnalysisDataTy& AD;\n \n typedef llvm::SmallVector<VarDecl*, 20> AlwaysLiveTy;\n AlwaysLiveTy AlwaysLive;\n\n \npublic:\n RegisterDecls(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}\n\n ~RegisterDecls() {\n\n AD.AlwaysLive.resetValues(AD);\n \n for (AlwaysLiveTy::iterator I = AlwaysLive.begin(), E = AlwaysLive.end();\n I != E; ++ I) \n AD.AlwaysLive(*I, AD) = Alive; \n }\n\n void VisitImplicitParamDecl(ImplicitParamDecl* IPD) {\n \/\/ Register the VarDecl for tracking.\n AD.Register(IPD);\n }\n\n void VisitVarDecl(VarDecl* VD) {\n \/\/ Register the VarDecl for tracking.\n AD.Register(VD);\n \n \/\/ Does the variable have global storage? If so, it is always live.\n if (VD->hasGlobalStorage())\n AlwaysLive.push_back(VD); \n }\n \n void VisitUnaryOperator(UnaryOperator* U) {\n \/\/ Check for '&'. Any VarDecl whose value has its address-taken we\n \/\/ treat as always being live (flow-insensitive).\n\n Expr* E = U->getSubExpr()->IgnoreParenCasts();\n \n if (U->getOpcode() == UnaryOperator::AddrOf)\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))\n if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) {\n AD.Register(VD);\n AlwaysLive.push_back(VD);\n return;\n }\n \n Visit(E);\n }\n \n CFG& getCFG() { return AD.getCFG(); }\n};\n} \/\/ end anonymous namespace\n\n\nLiveVariables::LiveVariables(CFG& cfg) {\n \/\/ Register all referenced VarDecls.\n getAnalysisData().setCFG(&cfg);\n RegisterDecls R(getAnalysisData());\n cfg.VisitBlockStmts(R);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Transfer functions.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\n\nclass VISIBILITY_HIDDEN TransferFuncs : public CFGRecStmtVisitor<TransferFuncs>{\n LiveVariables::AnalysisDataTy& AD;\n LiveVariables::ValTy LiveState;\npublic:\n TransferFuncs(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}\n\n LiveVariables::ValTy& getVal() { return LiveState; }\n CFG& getCFG() { return AD.getCFG(); }\n \n void VisitDeclRefExpr(DeclRefExpr* DR);\n void VisitBinaryOperator(BinaryOperator* B);\n void VisitAssign(BinaryOperator* B);\n void VisitDeclStmt(DeclStmt* DS);\n void BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S);\n void VisitUnaryOperator(UnaryOperator* U);\n void Visit(Stmt *S); \n void VisitTerminator(CFGBlock* B); \n \n void SetTopValue(LiveVariables::ValTy& V) {\n V = AD.AlwaysLive; \n }\n \n};\n \nvoid TransferFuncs::Visit(Stmt *S) {\n \n if (S == getCurrentBlkStmt()) {\n \n if (AD.Observer)\n AD.Observer->ObserveStmt(S,AD,LiveState);\n \n if (getCFG().isBlkExpr(S)) LiveState(S,AD) = Dead;\n StmtVisitor<TransferFuncs,void>::Visit(S);\n }\n else if (!getCFG().isBlkExpr(S)) {\n \n if (AD.Observer)\n AD.Observer->ObserveStmt(S,AD,LiveState);\n \n StmtVisitor<TransferFuncs,void>::Visit(S);\n \n }\n else\n \/\/ For block-level expressions, mark that they are live.\n LiveState(S,AD) = Alive;\n}\n \nvoid TransferFuncs::VisitTerminator(CFGBlock* B) {\n \n const Stmt* E = B->getTerminatorCondition();\n\n if (!E)\n return;\n \n assert (getCFG().isBlkExpr(E));\n LiveState(E, AD) = Alive;\n}\n\nvoid TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {\n if (VarDecl* V = dyn_cast<VarDecl>(DR->getDecl())) \n LiveState(V,AD) = Alive;\n}\n \nvoid TransferFuncs::VisitBinaryOperator(BinaryOperator* B) { \n if (B->isAssignmentOp()) VisitAssign(B);\n else VisitStmt(B);\n}\n\nvoid\nTransferFuncs::BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {\n \n \/\/ This represents a 'use' of the collection.\n Visit(S->getCollection());\n \n \/\/ This represents a 'kill' for the variable.\n Stmt* Element = S->getElement();\n DeclRefExpr* DR = 0;\n VarDecl* VD = 0;\n \n if (DeclStmt* DS = dyn_cast<DeclStmt>(Element))\n VD = cast<VarDecl>(DS->getSolitaryDecl());\n else {\n Expr* ElemExpr = cast<Expr>(Element)->IgnoreParens(); \n if ((DR = dyn_cast<DeclRefExpr>(ElemExpr)))\n VD = cast<VarDecl>(DR->getDecl());\n }\n\n if (VD) {\n LiveState(VD, AD) = Dead;\n if (AD.Observer && DR) { AD.Observer->ObserverKill(DR); }\n }\n}\n\n \nvoid TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {\n Expr *E = U->getSubExpr();\n \n switch (U->getOpcode()) {\n case UnaryOperator::PostInc:\n case UnaryOperator::PostDec:\n case UnaryOperator::PreInc:\n case UnaryOperator::PreDec:\n \/\/ Walk through the subexpressions, blasting through ParenExprs\n \/\/ until we either find a DeclRefExpr or some non-DeclRefExpr\n \/\/ expression.\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E->IgnoreParens())) \n if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) {\n \/\/ Treat the --\/++ operator as a kill.\n if (AD.Observer) { AD.Observer->ObserverKill(DR); }\n LiveState(VD, AD) = Alive;\n return VisitDeclRefExpr(DR);\n }\n\n \/\/ Fall-through.\n \n default:\n return Visit(E);\n }\n}\n \nvoid TransferFuncs::VisitAssign(BinaryOperator* B) { \n Expr* LHS = B->getLHS();\n\n \/\/ Assigning to a variable?\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParens())) {\n \n \/\/ Update liveness inforamtion.\n unsigned bit = AD.getIdx(DR->getDecl());\n LiveState.getDeclBit(bit) = Dead | AD.AlwaysLive.getDeclBit(bit);\n \n if (AD.Observer) { AD.Observer->ObserverKill(DR); }\n \n \/\/ Handle things like +=, etc., which also generate \"uses\"\n \/\/ of a variable. Do this just by visiting the subexpression.\n if (B->getOpcode() != BinaryOperator::Assign)\n VisitDeclRefExpr(DR);\n }\n else \/\/ Not assigning to a variable. Process LHS as usual.\n Visit(LHS);\n \n Visit(B->getRHS());\n}\n\nvoid TransferFuncs::VisitDeclStmt(DeclStmt* DS) {\n \/\/ Declarations effectively \"kill\" a variable since they cannot\n \/\/ possibly be live before they are declared.\n for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end();\n DI != DE; ++DI)\n if (VarDecl* VD = dyn_cast<VarDecl>(*DI)) {\n \/\/ The initializer is evaluated after the variable comes into scope.\n \/\/ Since this is a reverse dataflow analysis, we must evaluate the\n \/\/ transfer function for this expression first.\n if (Expr* Init = VD->getInit())\n Visit(Init);\n \n \/\/ Update liveness information by killing the VarDecl.\n unsigned bit = AD.getIdx(VD);\n LiveState.getDeclBit(bit) = Dead | AD.AlwaysLive.getDeclBit(bit);\n }\n}\n \n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Merge operator: if something is live on any successor block, it is live\n\/\/ in the current block (a set union).\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\n\nstruct Merge {\n typedef StmtDeclBitVector_Types::ValTy ValTy; \n \n void operator()(ValTy& Dst, const ValTy& Src) {\n Dst.OrDeclBits(Src);\n Dst.AndBlkExprBits(Src);\n }\n};\n \ntypedef DataflowSolver<LiveVariables, TransferFuncs, Merge> Solver;\n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ External interface to run Liveness analysis.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nvoid LiveVariables::runOnCFG(CFG& cfg) {\n Solver S(*this);\n S.runOnCFG(cfg);\n}\n\nvoid LiveVariables::runOnAllBlocks(const CFG& cfg,\n LiveVariables::ObserverTy* Obs,\n bool recordStmtValues) {\n Solver S(*this);\n ObserverTy* OldObserver = getAnalysisData().Observer;\n getAnalysisData().Observer = Obs;\n S.runOnAllBlocks(cfg, recordStmtValues);\n getAnalysisData().Observer = OldObserver;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ liveness queries\n\/\/\n\nbool LiveVariables::isLive(const CFGBlock* B, const VarDecl* D) const {\n DeclBitVector_Types::Idx i = getAnalysisData().getIdx(D);\n return i.isValid() ? getBlockData(B).getBit(i) : false;\n}\n\nbool LiveVariables::isLive(const ValTy& Live, const VarDecl* D) const {\n DeclBitVector_Types::Idx i = getAnalysisData().getIdx(D);\n return i.isValid() ? Live.getBit(i) : false;\n}\n\nbool LiveVariables::isLive(const Stmt* Loc, const Stmt* StmtVal) const {\n return getStmtData(Loc)(StmtVal,getAnalysisData());\n}\n\nbool LiveVariables::isLive(const Stmt* Loc, const VarDecl* D) const {\n return getStmtData(Loc)(D,getAnalysisData());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ printing liveness state for debugging\n\/\/\n\nvoid LiveVariables::dumpLiveness(const ValTy& V, SourceManager& SM) const {\n const AnalysisDataTy& AD = getAnalysisData();\n \n for (AnalysisDataTy::decl_iterator I = AD.begin_decl(),\n E = AD.end_decl(); I!=E; ++I)\n if (V.getDeclBit(I->second)) { \n SourceLocation PhysLoc = SM.getPhysicalLoc(I->first->getLocation());\n \n fprintf(stderr, \" %s <%s:%u:%u>\\n\", \n I->first->getIdentifier()->getName(),\n SM.getSourceName(PhysLoc),\n SM.getLineNumber(PhysLoc),\n SM.getColumnNumber(PhysLoc));\n }\n} \n\nvoid LiveVariables::dumpBlockLiveness(SourceManager& M) const {\n for (BlockDataMapTy::iterator I = getBlockDataMap().begin(),\n E = getBlockDataMap().end(); I!=E; ++I) {\n fprintf(stderr, \"\\n[ B%d (live variables at block exit) ]\\n\",\n I->first->getBlockID());\n \n dumpLiveness(I->second,M);\n }\n\n fprintf(stderr,\"\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"playlistcontainermodel.h\"\n\nnamespace sp = Spotinetta;\n\nnamespace Sonetta {\n\nPlaylistContainerModel::PlaylistContainerModel(const Spotinetta::Session *session, QObject *parent)\n : QAbstractListModel(parent), m_session(session)\n{\n m_watcher = new sp::PlaylistContainerWatcher(session, this);\n\n connect(m_watcher, &sp::PlaylistContainerWatcher::loaded,\n this, &PlaylistContainerModel::onLoaded);\n connect(m_watcher, &sp::PlaylistContainerWatcher::playlistAdded,\n this, &PlaylistContainerModel::onPlaylistAdded);\n connect(m_watcher, &sp::PlaylistContainerWatcher::playlistMoved,\n this, &PlaylistContainerModel::onPlaylistMoved);\n connect(m_watcher, &sp::PlaylistContainerWatcher::playlistRemoved,\n this, &PlaylistContainerModel::onPlaylistRemoved);\n\n m_stateChangedMapper = new QSignalMapper(this);\n m_renamedMapper = new QSignalMapper(this);\n m_imageChangedMapper = new QSignalMapper(this);\n m_descriptionChangedMapper = new QSignalMapper(this);\n\n connect(m_stateChangedMapper, SIGNAL(mapped(int)),\n this, SLOT(onPlaylistStateChanged(int)));\n connect(m_renamedMapper, SIGNAL(mapped(int)),\n this, SLOT(onPlaylistRenamed(int)));\n connect(m_imageChangedMapper, SIGNAL(mapped(int)),\n this, SLOT(onPlaylistImageChanged(int)));\n connect(m_descriptionChangedMapper, SIGNAL(mapped(int)),\n this, SLOT(onPlaylistDescriptionChanged(int)));\n}\n\nint PlaylistContainerModel::rowCount(const QModelIndex &parent) const\n{\n return parent.isValid() ? 0 : m_playlists.count();\n}\n\nQVariant PlaylistContainerModel::data(const QModelIndex &index, int role) const\n{\n const sp::Playlist & playlist = m_playlists.at(index.row())->watched();\n\n switch (role)\n {\n case PlaylistRole:\n return QVariant::fromValue(playlist);\n case IsLoadedRole:\n return playlist.isLoaded();\n case IsValidRole:\n return playlist.isValid();\n case NameRole:\n return playlist.name();\n case DescriptionRole:\n return QString(); \/\/ Fix\n case ImageUriRole:\n return QString(); \/\/ Fix\n\n default:\n return QVariant();\n }\n}\n\nQHash<int, QByteArray> PlaylistContainerModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles.insert(PlaylistRole, \"playlist\");\n roles.insert(IsLoadedRole, \"isLoaded\");\n roles.insert(IsValidRole, \"isValid\");\n roles.insert(NameRole, \"name\");\n roles.insert(DescriptionRole, \"description\");\n roles.insert(ImageUriRole, \"imageUri\");\n return roles;\n}\n\nsp::PlaylistContainer PlaylistContainerModel::playlistContainer() const\n{\n return m_watcher->watched();\n}\n\nvoid PlaylistContainerModel::setPlaylistContainer(const Spotinetta::PlaylistContainer &container)\n{\n if (container != playlistContainer())\n {\n beginResetModel();\n m_playlists.clear();\n m_watcher->watch(container);\n\n \/\/ It seems, though I'm not sure, that we get onPlaylistAdded callbacks\n \/\/ whether the container is loaded or not, so it looks like we don't need\n \/\/ to add any playlists to our list at this point (if we do it messes up the model with duplicate\n \/\/ playlists and too low count)\n\/\/ if (container.isLoaded())\n\/\/ {\n\/\/ onLoaded();\n\/\/ }\n\n endResetModel();\n\n emit playlistContainerChanged();\n }\n}\n\nvoid PlaylistContainerModel::updateWatcherIndices(int first, int last)\n{\n if (last >= first)\n {\n \/\/ last may be < first if a playlist is inserted into an empty container,\n \/\/ in which case we do not need to do anything in particular\n\n for (int i = first; i <= last; ++i)\n {\n auto watcher = m_playlists.at(i);\n updateMappings(watcher.data(), i);\n }\n }\n}\n\nQSharedPointer<Spotinetta::PlaylistWatcher> PlaylistContainerModel::createWatcher(int index)\n{\n const sp::Playlist playlist = playlistContainer().playlistAt(index);\n\n QSharedPointer<sp::PlaylistWatcher> watcher(\n new sp::PlaylistWatcher(m_session, this),\n &sp::PlaylistWatcher::deleteLater);\n\n connect(watcher.data(), SIGNAL(stateChanged()),\n m_stateChangedMapper, SLOT(map()));\n connect(watcher.data(), SIGNAL(renamed()),\n m_renamedMapper, SLOT(map()));\n connect(watcher.data(), SIGNAL(imageChanged()),\n m_imageChangedMapper, SLOT(map()));\n connect(watcher.data(), SIGNAL(descriptionChanged()),\n m_descriptionChangedMapper, SLOT(map()));\n\n updateMappings(watcher.data(), index);\n\n watcher->watch(playlist);\n return watcher;\n}\n\nvoid PlaylistContainerModel::updateMappings(Spotinetta::PlaylistWatcher *watcher, int index)\n{\n m_stateChangedMapper->setMapping(watcher, index);\n m_renamedMapper->setMapping(watcher, index);\n m_imageChangedMapper->setMapping(watcher, index);\n m_descriptionChangedMapper->setMapping(watcher, index);\n}\n\nvoid PlaylistContainerModel::onLoaded()\n{\n Q_ASSERT(!m_session.isNull());\n const sp::PlaylistContainer container = m_watcher->watched();\n\n if (container.playlistCount() > 0)\n {\n beginInsertRows(QModelIndex(), 0, container.playlistCount() - 1);\n m_playlists.reserve(container.playlistCount());\n\n for (int i = 0; i < container.playlistCount(); ++i)\n {\n m_playlists.append(createWatcher(i));\n }\n endInsertRows();\n }\n}\n\n\n\nvoid PlaylistContainerModel::onPlaylistAdded(int position)\n{\n beginInsertRows(QModelIndex(), position, position);\n\n m_playlists.insert(position, createWatcher(position));\n updateWatcherIndices(position + 1, m_playlists.count() - 1);\n\n endInsertRows();\n}\n\nvoid PlaylistContainerModel::onPlaylistRemoved(int position)\n{\n beginRemoveRows(QModelIndex(), position, position);\n\n m_playlists.remove(position);\n updateWatcherIndices(position, m_playlists.count() - 1);\n\n endRemoveRows();\n}\n\nvoid PlaylistContainerModel::onPlaylistMoved(int oldPosition, int newPosition)\n{\n beginMoveRows(QModelIndex(), oldPosition, oldPosition, QModelIndex(), newPosition);\n QSharedPointer<sp::PlaylistWatcher> watcher = m_playlists.at(oldPosition);\n m_playlists.remove(oldPosition);\n m_playlists.insert(newPosition, watcher);\n\n updateWatcherIndices(oldPosition, newPosition);\n\n endMoveRows();\n}\n\nvoid PlaylistContainerModel::onPlaylistStateChanged(int position)\n{\n \/\/ Update all roles for simplicity\n QModelIndex mi = index(position);\n emit dataChanged(mi, mi);\n}\n\nvoid PlaylistContainerModel::onPlaylistRenamed(int position)\n{\n QModelIndex mi = index(position);\n emit dataChanged(mi, mi, QVector<int>(1, NameRole));\n}\n\nvoid PlaylistContainerModel::onPlaylistDescriptionChanged(int position)\n{\n QModelIndex mi = index(position);\n emit dataChanged(mi, mi, QVector<int>(1, DescriptionRole));\n}\n\nvoid PlaylistContainerModel::onPlaylistImageChanged(int position)\n{\n QModelIndex mi = index(position);\n emit dataChanged(mi, mi, QVector<int>(1, ImageUriRole));\n}\n\n\n}\n<commit_msg>Some minor changes to playlistcontainermodel.cpp that hopefully fixes some rare bug that seems to appear once in a blue moon<commit_after>#include \"playlistcontainermodel.h\"\n\n#include <QDebug>\n\nnamespace sp = Spotinetta;\n\nnamespace Sonetta {\n\nPlaylistContainerModel::PlaylistContainerModel(const Spotinetta::Session *session, QObject *parent)\n : QAbstractListModel(parent), m_session(session)\n{\n m_watcher = new sp::PlaylistContainerWatcher(session, this);\n\n connect(m_watcher, &sp::PlaylistContainerWatcher::loaded,\n this, &PlaylistContainerModel::onLoaded);\n connect(m_watcher, &sp::PlaylistContainerWatcher::playlistAdded,\n this, &PlaylistContainerModel::onPlaylistAdded);\n connect(m_watcher, &sp::PlaylistContainerWatcher::playlistMoved,\n this, &PlaylistContainerModel::onPlaylistMoved);\n connect(m_watcher, &sp::PlaylistContainerWatcher::playlistRemoved,\n this, &PlaylistContainerModel::onPlaylistRemoved);\n\n m_stateChangedMapper = new QSignalMapper(this);\n m_renamedMapper = new QSignalMapper(this);\n m_imageChangedMapper = new QSignalMapper(this);\n m_descriptionChangedMapper = new QSignalMapper(this);\n\n connect(m_stateChangedMapper, SIGNAL(mapped(int)),\n this, SLOT(onPlaylistStateChanged(int)));\n connect(m_renamedMapper, SIGNAL(mapped(int)),\n this, SLOT(onPlaylistRenamed(int)));\n connect(m_imageChangedMapper, SIGNAL(mapped(int)),\n this, SLOT(onPlaylistImageChanged(int)));\n connect(m_descriptionChangedMapper, SIGNAL(mapped(int)),\n this, SLOT(onPlaylistDescriptionChanged(int)));\n}\n\nint PlaylistContainerModel::rowCount(const QModelIndex &parent) const\n{\n return parent.isValid() ? 0 : m_playlists.count();\n}\n\nQVariant PlaylistContainerModel::data(const QModelIndex &index, int role) const\n{\n const sp::Playlist & playlist = m_playlists.at(index.row())->watched();\n\n switch (role)\n {\n case PlaylistRole:\n return QVariant::fromValue(playlist);\n case IsLoadedRole:\n return playlist.isLoaded();\n case IsValidRole:\n return playlist.isValid();\n case NameRole:\n return playlist.name();\n case DescriptionRole:\n return QString(); \/\/ Fix\n case ImageUriRole:\n return QString(); \/\/ Fix\n\n default:\n return QVariant();\n }\n}\n\nQHash<int, QByteArray> PlaylistContainerModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles.insert(PlaylistRole, \"playlist\");\n roles.insert(IsLoadedRole, \"isLoaded\");\n roles.insert(IsValidRole, \"isValid\");\n roles.insert(NameRole, \"name\");\n roles.insert(DescriptionRole, \"description\");\n roles.insert(ImageUriRole, \"imageUri\");\n return roles;\n}\n\nsp::PlaylistContainer PlaylistContainerModel::playlistContainer() const\n{\n return m_watcher->watched();\n}\n\nvoid PlaylistContainerModel::setPlaylistContainer(const Spotinetta::PlaylistContainer &container)\n{\n if (container != playlistContainer())\n {\n beginResetModel();\n m_playlists.clear();\n endResetModel();\n m_watcher->watch(container);\n\n emit playlistContainerChanged();\n }\n}\n\nvoid PlaylistContainerModel::updateWatcherIndices(int first, int last)\n{\n if (last >= first)\n {\n \/\/ last may be < first if a playlist is inserted into an empty container,\n \/\/ in which case we do not need to do anything in particular\n\n for (int i = first; i <= last; ++i)\n {\n auto watcher = m_playlists.at(i);\n updateMappings(watcher.data(), i);\n }\n }\n}\n\nQSharedPointer<Spotinetta::PlaylistWatcher> PlaylistContainerModel::createWatcher(int index)\n{\n const sp::Playlist playlist = playlistContainer().playlistAt(index);\n\n QSharedPointer<sp::PlaylistWatcher> watcher(\n new sp::PlaylistWatcher(m_session, this),\n &sp::PlaylistWatcher::deleteLater);\n\n connect(watcher.data(), SIGNAL(stateChanged()),\n m_stateChangedMapper, SLOT(map()));\n connect(watcher.data(), SIGNAL(renamed()),\n m_renamedMapper, SLOT(map()));\n connect(watcher.data(), SIGNAL(imageChanged()),\n m_imageChangedMapper, SLOT(map()));\n connect(watcher.data(), SIGNAL(descriptionChanged()),\n m_descriptionChangedMapper, SLOT(map()));\n\n updateMappings(watcher.data(), index);\n\n watcher->watch(playlist);\n return watcher;\n}\n\nvoid PlaylistContainerModel::updateMappings(Spotinetta::PlaylistWatcher *watcher, int index)\n{\n m_stateChangedMapper->setMapping(watcher, index);\n m_renamedMapper->setMapping(watcher, index);\n m_imageChangedMapper->setMapping(watcher, index);\n m_descriptionChangedMapper->setMapping(watcher, index);\n}\n\nvoid PlaylistContainerModel::onLoaded()\n{\n Q_ASSERT(!m_session.isNull());\n const sp::PlaylistContainer container = m_watcher->watched();\n\n if (container.playlistCount() > 0)\n {\n beginResetModel();\n m_playlists.reserve(container.playlistCount());\n\n for (int i = 0; i < container.playlistCount(); ++i)\n {\n m_playlists.append(createWatcher(i));\n }\n endResetModel();\n }\n}\n\nvoid PlaylistContainerModel::onPlaylistAdded(int position)\n{\n beginInsertRows(QModelIndex(), position, position);\n\n m_playlists.insert(position, createWatcher(position));\n updateWatcherIndices(position + 1, m_playlists.count() - 1);\n\n endInsertRows();\n}\n\nvoid PlaylistContainerModel::onPlaylistRemoved(int position)\n{\n beginRemoveRows(QModelIndex(), position, position);\n\n m_playlists.remove(position);\n updateWatcherIndices(position, m_playlists.count() - 1);\n\n endRemoveRows();\n}\n\nvoid PlaylistContainerModel::onPlaylistMoved(int oldPosition, int newPosition)\n{\n beginMoveRows(QModelIndex(), oldPosition, oldPosition, QModelIndex(), newPosition);\n QSharedPointer<sp::PlaylistWatcher> watcher = m_playlists.at(oldPosition);\n m_playlists.remove(oldPosition);\n m_playlists.insert(newPosition, watcher);\n\n updateWatcherIndices(oldPosition, newPosition);\n\n endMoveRows();\n}\n\nvoid PlaylistContainerModel::onPlaylistStateChanged(int position)\n{\n \/\/ Update all roles for simplicity\n QModelIndex mi = index(position);\n emit dataChanged(mi, mi);\n}\n\nvoid PlaylistContainerModel::onPlaylistRenamed(int position)\n{\n QModelIndex mi = index(position);\n emit dataChanged(mi, mi, QVector<int>(1, NameRole));\n}\n\nvoid PlaylistContainerModel::onPlaylistDescriptionChanged(int position)\n{\n QModelIndex mi = index(position);\n emit dataChanged(mi, mi, QVector<int>(1, DescriptionRole));\n}\n\nvoid PlaylistContainerModel::onPlaylistImageChanged(int position)\n{\n QModelIndex mi = index(position);\n emit dataChanged(mi, mi, QVector<int>(1, ImageUriRole));\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>:art: Initialize elements of vectors with constructor<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"dispatch_queue.h\"\n\n#include <thread>\n#include <queue>\n\nstruct dispatch_queue_t::impl\n{\n impl();\n static void dispatch_thread_proc(impl *self);\n\n std::queue< std::function< void() > > queue;\n std::mutex queue_mtx;\n std::condition_variable queue_cond;\n std::atomic< bool > quit;\n std::thread queue_thread;\n\n using queue_lock_t = std::unique_lock< decltype(queue_mtx) >;\n};\n\nvoid dispatch_queue_t::impl::dispatch_thread_proc(dispatch_queue_t::impl *self)\n{\n using queue_size_t = decltype(self->queue)::size_type;\n\n while (self->quit == false)\n {\n queue_lock_t queue_lock(self->queue_mtx);\n self->queue_cond.wait(queue_lock, [&] { return self->queue.size() > 0; });\n\n while (self->queue.size()) {\n auto dispatch_func = self->queue.front();\n self->queue.pop();\n\n queue_lock.unlock();\n dispatch_func();\n queue_lock.lock();\n }\n }\n}\n\ndispatch_queue_t::impl::impl()\n : quit(false)\n , queue_thread(&dispatch_thread_proc, this)\n{\n}\n\ndispatch_queue_t::dispatch_queue_t()\n : m(new impl)\n{\n}\n\ndispatch_queue_t::~dispatch_queue_t()\n{\n dispatch_async([this] { m->quit = true; });\n m->queue_thread.join();\n}\n\nvoid dispatch_queue_t::dispatch_async(std::function< void() > func)\n{\n impl::queue_lock_t queue_lock(m->queue_mtx);\n m->queue.push(func);\n m->queue_cond.notify_one();\n}\n\nvoid dispatch_queue_t::dispatch_sync(std::function< void() > func)\n{\n std::mutex sync_mtx;\n impl::queue_lock_t sync_lock(sync_mtx);\n std::condition_variable sync_cond;\n std::atomic< bool > completed(false);\n\n {\n impl::queue_lock_t queue_lock(m->queue_mtx);\n m->queue.push(func);\n m->queue.push([&] {\n std::unique_lock< decltype(sync_mtx) > sync_cb_lock(sync_mtx);\n completed = true;\n sync_cond.notify_one();\n });\n\n m->queue_cond.notify_one();\n }\n\n sync_cond.wait(sync_lock, [&] { return completed.load(); });\n}\n\nvoid dispatch_queue_t::dispatch_flush()\n{\n dispatch_sync([]{});\n}\n\n<commit_msg>size() => empty()<commit_after>#include \"dispatch_queue.h\"\n\n#include <thread>\n#include <queue>\n\nstruct dispatch_queue_t::impl\n{\n impl();\n static void dispatch_thread_proc(impl *self);\n\n std::queue< std::function< void() > > queue;\n std::mutex queue_mtx;\n std::condition_variable queue_cond;\n std::atomic< bool > quit;\n std::thread queue_thread;\n\n using queue_lock_t = std::unique_lock< decltype(queue_mtx) >;\n};\n\nvoid dispatch_queue_t::impl::dispatch_thread_proc(dispatch_queue_t::impl *self)\n{\n using queue_size_t = decltype(self->queue)::size_type;\n\n while (self->quit == false)\n {\n queue_lock_t queue_lock(self->queue_mtx);\n self->queue_cond.wait(queue_lock, [&] { return !self->queue.empty(); });\n\n while (!self->queue.empty()) {\n auto dispatch_func = self->queue.front();\n self->queue.pop();\n\n queue_lock.unlock();\n dispatch_func();\n queue_lock.lock();\n }\n }\n}\n\ndispatch_queue_t::impl::impl()\n : quit(false)\n , queue_thread(&dispatch_thread_proc, this)\n{\n}\n\ndispatch_queue_t::dispatch_queue_t()\n : m(new impl)\n{\n}\n\ndispatch_queue_t::~dispatch_queue_t()\n{\n dispatch_async([this] { m->quit = true; });\n m->queue_thread.join();\n}\n\nvoid dispatch_queue_t::dispatch_async(std::function< void() > func)\n{\n impl::queue_lock_t queue_lock(m->queue_mtx);\n m->queue.push(func);\n m->queue_cond.notify_one();\n}\n\nvoid dispatch_queue_t::dispatch_sync(std::function< void() > func)\n{\n std::mutex sync_mtx;\n impl::queue_lock_t sync_lock(sync_mtx);\n std::condition_variable sync_cond;\n std::atomic< bool > completed(false);\n\n {\n impl::queue_lock_t queue_lock(m->queue_mtx);\n m->queue.push(func);\n m->queue.push([&] {\n std::unique_lock< decltype(sync_mtx) > sync_cb_lock(sync_mtx);\n completed = true;\n sync_cond.notify_one();\n });\n\n m->queue_cond.notify_one();\n }\n\n sync_cond.wait(sync_lock, [&] { return completed.load(); });\n}\n\nvoid dispatch_queue_t::dispatch_flush()\n{\n dispatch_sync([]{});\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkGraph.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\/*----------------------------------------------------------------------------\n Copyright (c) Sandia Corporation\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n----------------------------------------------------------------------------*\/\n\n#include \"vtkGraph.h\"\n\n#include \"vtkAdjacentVertexIterator.h\"\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkEdgeListIterator.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInEdgeIterator.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkOutEdgeIterator.h\"\n#include \"vtkPoints.h\"\n#include \"vtkVertexListIterator.h\"\n\n#include <vtksys\/stl\/vector>\n#include <vtksys\/stl\/utility>\n\nusing vtksys_stl::pair;\nusing vtksys_stl::make_pair;\nusing vtksys_stl::vector;\n\ndouble vtkGraph::DefaultPoint[3] = {0, 0, 0};\n\n\/\/----------------------------------------------------------------------------\n\/\/ private class vtkVertexAdjacencyList\n\/\/----------------------------------------------------------------------------\nclass vtkVertexAdjacencyList\n{\npublic:\n vector<vtkInEdgeType> InEdges;\n vector<vtkOutEdgeType> OutEdges;\n};\n\n\/\/----------------------------------------------------------------------------\n\/\/ private class vtkGraphInternals\n\/\/----------------------------------------------------------------------------\nclass vtkGraphInternals : public vtkObject\n{\npublic:\n static vtkGraphInternals *New();\n vtkTypeRevisionMacro(vtkGraphInternals, vtkObject);\n vector<vtkVertexAdjacencyList> Adjacency;\n vtkIdType NumberOfEdges;\n\nprotected:\n vtkGraphInternals()\n { this->NumberOfEdges = 0; }\n ~vtkGraphInternals()\n { }\n\nprivate:\n vtkGraphInternals(const vtkGraphInternals&); \/\/ Not implemented.\n void operator=(const vtkGraphInternals&); \/\/ Not implemented.\n};\n\nvtkStandardNewMacro(vtkGraphInternals);\nvtkCxxRevisionMacro(vtkGraphInternals, \"1.8\");\n\n\/\/----------------------------------------------------------------------------\n\/\/ class vtkGraph\n\/\/----------------------------------------------------------------------------\nvtkCxxSetObjectMacro(vtkGraph, Points, vtkPoints);\nvtkCxxSetObjectMacro(vtkGraph, Internals, vtkGraphInternals);\nvtkCxxRevisionMacro(vtkGraph, \"1.8\");\n\/\/----------------------------------------------------------------------------\nvtkGraph::vtkGraph()\n{\n this->VertexData = vtkDataSetAttributes::New();\n this->EdgeData = vtkDataSetAttributes::New();\n this->Points = 0;\n vtkMath::UninitializeBounds(this->Bounds);\n\n this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_PIECES_EXTENT);\n this->Information->Set(vtkDataObject::DATA_PIECE_NUMBER(), -1);\n this->Information->Set(vtkDataObject::DATA_NUMBER_OF_PIECES(), 1);\n this->Information->Set(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS(), 0);\n\n this->Internals = vtkGraphInternals::New();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkGraph::~vtkGraph()\n{\n this->VertexData->Delete();\n this->EdgeData->Delete();\n if (this->Points)\n {\n this->Points->Delete();\n }\n this->Internals->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\ndouble *vtkGraph::GetPoint(vtkIdType ptId)\n{\n if (this->Points)\n {\n return this->Points->GetPoint(ptId);\n }\n return this->DefaultPoint;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetPoint(vtkIdType ptId, double x[3])\n{\n if (this->Points)\n {\n this->Points->GetPoint(ptId, x);\n }\n else\n {\n for (int i = 0; i < 3; i++)\n {\n x[i] = this->DefaultPoint[i];\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkPoints *vtkGraph::GetPoints()\n{\n if (!this->Points)\n {\n this->Points = vtkPoints::New();\n }\n if (this->Points->GetNumberOfPoints() != this->GetNumberOfVertices())\n {\n this->Points->SetNumberOfPoints(this->GetNumberOfVertices());\n for (vtkIdType i = 0; i < this->GetNumberOfVertices(); i++)\n {\n this->Points->SetPoint(i, 0, 0, 0);\n }\n }\n return this->Points;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::ComputeBounds()\n{\n double *bounds;\n\n if ( this->Points )\n {\n bounds = this->Points->GetBounds();\n for (int i=0; i<6; i++)\n {\n this->Bounds[i] = bounds[i];\n }\n this->ComputeTime.Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\ndouble *vtkGraph::GetBounds()\n{\n this->ComputeBounds();\n return this->Bounds;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetBounds(double bounds[6])\n{\n this->ComputeBounds();\n for (int i=0; i<6; i++)\n {\n bounds[i] = this->Bounds[i];\n }\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned long int vtkGraph::GetMTime()\n{\n unsigned long int doTime = vtkDataObject::GetMTime();\n\n if ( this->VertexData->GetMTime() > doTime )\n {\n doTime = this->VertexData->GetMTime();\n }\n if ( this->EdgeData->GetMTime() > doTime )\n {\n doTime = this->EdgeData->GetMTime();\n }\n if ( this->Points ) \n {\n if ( this->Points->GetMTime() > doTime )\n {\n doTime = this->Points->GetMTime();\n }\n }\n\n return doTime;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::Initialize()\n{\n this->ForceOwnership();\n Superclass::Initialize();\n this->EdgeData->Initialize();\n this->VertexData->Initialize();\n this->Internals->NumberOfEdges = 0;\n this->Internals->Adjacency.clear();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetOutEdges(vtkIdType v, vtkOutEdgeIterator *it)\n{\n if (it)\n {\n it->Initialize(this, v);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetOutEdges(vtkIdType v, const vtkOutEdgeType *& edges, vtkIdType & nedges)\n{\n nedges = this->Internals->Adjacency[v].OutEdges.size();\n if (nedges > 0)\n {\n edges = &(this->Internals->Adjacency[v].OutEdges[0]);\n }\n else\n {\n edges = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetOutDegree(vtkIdType v)\n{\n return this->Internals->Adjacency[v].OutEdges.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetDegree(vtkIdType v)\n{\n return this->Internals->Adjacency[v].InEdges.size() +\n this->Internals->Adjacency[v].OutEdges.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetInEdges(vtkIdType v, vtkInEdgeIterator *it)\n{\n if (it)\n {\n it->Initialize(this, v);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetInEdges(vtkIdType v, const vtkInEdgeType *& edges, vtkIdType & nedges)\n{\n nedges = this->Internals->Adjacency[v].InEdges.size();\n if (nedges > 0)\n {\n edges = &(this->Internals->Adjacency[v].InEdges[0]);\n }\n else\n {\n edges = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetInDegree(vtkIdType v)\n{\n return this->Internals->Adjacency[v].InEdges.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetAdjacentVertices(vtkIdType v, vtkAdjacentVertexIterator *it)\n{\n if (it)\n {\n it->Initialize(this, v);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetEdges(vtkEdgeListIterator *it)\n{\n if (it)\n {\n it->SetGraph(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetNumberOfEdges()\n{\n return this->Internals->NumberOfEdges;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetVertices(vtkVertexListIterator *it)\n{\n if (it)\n {\n it->SetGraph(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetNumberOfVertices()\n{\n return this->Internals->Adjacency.size();\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkGraph::CheckedShallowCopy(vtkGraph *g)\n{\n if (!g)\n {\n return false;\n }\n bool valid = this->IsStructureValid(g);\n if (valid)\n {\n this->CopyInternal(g, false);\n }\n return valid;\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkGraph::CheckedDeepCopy(vtkGraph *g)\n{\n if (!g)\n {\n return false;\n }\n bool valid = this->IsStructureValid(g);\n if (valid)\n {\n this->CopyInternal(g, true);\n }\n return valid;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::ShallowCopy(vtkDataObject *obj)\n{\n vtkGraph *g = vtkGraph::SafeDownCast(obj);\n if (!g)\n {\n vtkErrorMacro(\"Can only shallow copy from vtkGraph subclass.\");\n return;\n }\n bool valid = this->IsStructureValid(g);\n if (valid)\n {\n this->CopyInternal(g, false);\n }\n else\n {\n vtkErrorMacro(\"Invalid graph structure for this type of graph.\");\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::DeepCopy(vtkDataObject *obj)\n{\n vtkGraph *g = vtkGraph::SafeDownCast(obj);\n if (!g)\n {\n vtkErrorMacro(\"Can only shallow copy from vtkGraph subclass.\");\n return;\n }\n bool valid = this->IsStructureValid(g);\n if (valid)\n {\n this->CopyInternal(g, true);\n }\n else\n {\n vtkErrorMacro(\"Invalid graph structure for this type of graph.\");\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::CopyInternal(vtkGraph *g, bool deep)\n{\n if (deep)\n {\n vtkDataObject::DeepCopy(g);\n }\n else\n {\n vtkDataObject::ShallowCopy(g);\n }\n \/\/ Copy on write.\n this->SetInternals(g->Internals);\n if (deep)\n {\n this->EdgeData->DeepCopy(g->EdgeData);\n this->VertexData->DeepCopy(g->VertexData);\n }\n else\n {\n this->EdgeData->ShallowCopy(g->EdgeData);\n this->VertexData->ShallowCopy(g->VertexData);\n }\n if (g->Points)\n {\n if (!this->Points)\n {\n this->Points = vtkPoints::New();\n }\n if (deep)\n {\n this->Points->DeepCopy(g->Points);\n }\n else\n {\n this->Points->ShallowCopy(g->Points);\n }\n }\n else if (this->Points)\n {\n this->Points->Delete();\n this->Points = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::Squeeze()\n{\n if ( this->Points )\n {\n this->Points->Squeeze();\n }\n this->EdgeData->Squeeze();\n this->VertexData->Squeeze();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkGraph *vtkGraph::GetData(vtkInformation *info)\n{\n return info? vtkGraph::SafeDownCast(info->Get(DATA_OBJECT())) : 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkGraph *vtkGraph::GetData(vtkInformationVector *v, int i)\n{\n return vtkGraph::GetData(v->GetInformationObject(i));\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::AddVertexInternal()\n{\n this->ForceOwnership();\n this->Internals->Adjacency.push_back(vtkVertexAdjacencyList());\n return this->Internals->Adjacency.size() - 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkEdgeType vtkGraph::AddEdgeInternal(vtkIdType u, vtkIdType v, bool directed)\n{\n this->ForceOwnership();\n vtkIdType edgeId = this->Internals->NumberOfEdges;\n this->Internals->NumberOfEdges++;\n this->Internals->Adjacency[u].OutEdges.push_back(vtkOutEdgeType(v, edgeId));\n if (directed)\n {\n this->Internals->Adjacency[v].InEdges.push_back(vtkInEdgeType(u, edgeId));\n }\n else if (u != v)\n {\n \/\/ Avoid storing self-loops twice in undirected graphs.\n this->Internals->Adjacency[v].OutEdges.push_back(vtkOutEdgeType(u, edgeId));\n }\n return vtkEdgeType(u, v, edgeId);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::ReorderOutVertices(vtkIdType v, vtkIdTypeArray *vertices)\n{\n this->ForceOwnership();\n vector<vtkOutEdgeType> outEdges;\n vector<vtkOutEdgeType>::iterator it, itEnd;\n itEnd = this->Internals->Adjacency[v].OutEdges.end();\n for (vtkIdType i = 0; i < vertices->GetNumberOfTuples(); ++i)\n {\n vtkIdType vert = vertices->GetValue(i);\n \/\/ Find the matching edge\n for (it = this->Internals->Adjacency[v].OutEdges.begin(); it != itEnd; ++it)\n {\n if (it->Target == vert)\n {\n outEdges.push_back(*it);\n break;\n }\n }\n }\n if (outEdges.size() != this->Internals->Adjacency[v].OutEdges.size())\n {\n vtkErrorMacro(\"Invalid reorder list.\");\n return;\n }\n this->Internals->Adjacency[v].OutEdges = outEdges;\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkGraph::IsSameStructure(vtkGraph *other)\n{\n return (this->Internals == other->Internals);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::ForceOwnership()\n{\n \/\/ If the reference count == 1, we own it and can change it.\n \/\/ If the reference count > 1, we must make a copy to avoid\n \/\/ changing the structure of other graphs.\n if (this->Internals->GetReferenceCount() > 1)\n {\n vtkGraphInternals *internals = vtkGraphInternals::New();\n internals->Adjacency = this->Internals->Adjacency;\n internals->NumberOfEdges = this->Internals->NumberOfEdges;\n this->SetInternals(internals);\n internals->Delete();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Supporting operators\n\/\/----------------------------------------------------------------------------\n\n\/\/----------------------------------------------------------------------------\nbool operator==(vtkEdgeBase e1, vtkEdgeBase e2)\n{\n return e1.Id == e2.Id;\n}\n\n\/\/----------------------------------------------------------------------------\nbool operator!=(vtkEdgeBase e1, vtkEdgeBase e2)\n{\n return e1.Id != e2.Id;\n}\n\n\/\/----------------------------------------------------------------------------\nostream& operator<<(ostream& out, vtkEdgeBase e)\n{\n return out << e.Id;\n}\n<commit_msg>COMP: Attempting to fix VC6.0 error by explicitly using namespace.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkGraph.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\/*----------------------------------------------------------------------------\n Copyright (c) Sandia Corporation\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n----------------------------------------------------------------------------*\/\n\n#include \"vtkGraph.h\"\n\n#include \"vtkAdjacentVertexIterator.h\"\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkEdgeListIterator.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInEdgeIterator.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkOutEdgeIterator.h\"\n#include \"vtkPoints.h\"\n#include \"vtkVertexListIterator.h\"\n\n#include <vtksys\/stl\/vector>\n#include <vtksys\/stl\/utility>\n\nusing vtksys_stl::pair;\nusing vtksys_stl::make_pair;\nusing vtksys_stl::vector;\n\ndouble vtkGraph::DefaultPoint[3] = {0, 0, 0};\n\n\/\/----------------------------------------------------------------------------\n\/\/ private class vtkVertexAdjacencyList\n\/\/----------------------------------------------------------------------------\nclass vtkVertexAdjacencyList\n{\npublic:\n vector<vtkInEdgeType> InEdges;\n vector<vtkOutEdgeType> OutEdges;\n};\n\n\/\/----------------------------------------------------------------------------\n\/\/ private class vtkGraphInternals\n\/\/----------------------------------------------------------------------------\nclass vtkGraphInternals : public vtkObject\n{\npublic:\n static vtkGraphInternals *New();\n vtkTypeRevisionMacro(vtkGraphInternals, vtkObject);\n vector<vtkVertexAdjacencyList> Adjacency;\n vtkIdType NumberOfEdges;\n\nprotected:\n vtkGraphInternals()\n { this->NumberOfEdges = 0; }\n ~vtkGraphInternals()\n { }\n\nprivate:\n vtkGraphInternals(const vtkGraphInternals&); \/\/ Not implemented.\n void operator=(const vtkGraphInternals&); \/\/ Not implemented.\n};\n\nvtkStandardNewMacro(vtkGraphInternals);\nvtkCxxRevisionMacro(vtkGraphInternals, \"1.9\");\n\n\/\/----------------------------------------------------------------------------\n\/\/ class vtkGraph\n\/\/----------------------------------------------------------------------------\nvtkCxxSetObjectMacro(vtkGraph, Points, vtkPoints);\nvtkCxxSetObjectMacro(vtkGraph, Internals, vtkGraphInternals);\nvtkCxxRevisionMacro(vtkGraph, \"1.9\");\n\/\/----------------------------------------------------------------------------\nvtkGraph::vtkGraph()\n{\n this->VertexData = vtkDataSetAttributes::New();\n this->EdgeData = vtkDataSetAttributes::New();\n this->Points = 0;\n vtkMath::UninitializeBounds(this->Bounds);\n\n this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_PIECES_EXTENT);\n this->Information->Set(vtkDataObject::DATA_PIECE_NUMBER(), -1);\n this->Information->Set(vtkDataObject::DATA_NUMBER_OF_PIECES(), 1);\n this->Information->Set(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS(), 0);\n\n this->Internals = vtkGraphInternals::New();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkGraph::~vtkGraph()\n{\n this->VertexData->Delete();\n this->EdgeData->Delete();\n if (this->Points)\n {\n this->Points->Delete();\n }\n this->Internals->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\ndouble *vtkGraph::GetPoint(vtkIdType ptId)\n{\n if (this->Points)\n {\n return this->Points->GetPoint(ptId);\n }\n return this->DefaultPoint;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetPoint(vtkIdType ptId, double x[3])\n{\n if (this->Points)\n {\n this->Points->GetPoint(ptId, x);\n }\n else\n {\n for (int i = 0; i < 3; i++)\n {\n x[i] = this->DefaultPoint[i];\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkPoints *vtkGraph::GetPoints()\n{\n if (!this->Points)\n {\n this->Points = vtkPoints::New();\n }\n if (this->Points->GetNumberOfPoints() != this->GetNumberOfVertices())\n {\n this->Points->SetNumberOfPoints(this->GetNumberOfVertices());\n for (vtkIdType i = 0; i < this->GetNumberOfVertices(); i++)\n {\n this->Points->SetPoint(i, 0, 0, 0);\n }\n }\n return this->Points;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::ComputeBounds()\n{\n double *bounds;\n\n if ( this->Points )\n {\n bounds = this->Points->GetBounds();\n for (int i=0; i<6; i++)\n {\n this->Bounds[i] = bounds[i];\n }\n this->ComputeTime.Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\ndouble *vtkGraph::GetBounds()\n{\n this->ComputeBounds();\n return this->Bounds;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetBounds(double bounds[6])\n{\n this->ComputeBounds();\n for (int i=0; i<6; i++)\n {\n bounds[i] = this->Bounds[i];\n }\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned long int vtkGraph::GetMTime()\n{\n unsigned long int doTime = vtkDataObject::GetMTime();\n\n if ( this->VertexData->GetMTime() > doTime )\n {\n doTime = this->VertexData->GetMTime();\n }\n if ( this->EdgeData->GetMTime() > doTime )\n {\n doTime = this->EdgeData->GetMTime();\n }\n if ( this->Points ) \n {\n if ( this->Points->GetMTime() > doTime )\n {\n doTime = this->Points->GetMTime();\n }\n }\n\n return doTime;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::Initialize()\n{\n this->ForceOwnership();\n Superclass::Initialize();\n this->EdgeData->Initialize();\n this->VertexData->Initialize();\n this->Internals->NumberOfEdges = 0;\n this->Internals->Adjacency.clear();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetOutEdges(vtkIdType v, vtkOutEdgeIterator *it)\n{\n if (it)\n {\n it->Initialize(this, v);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetOutEdges(vtkIdType v, const vtkOutEdgeType *& edges, vtkIdType & nedges)\n{\n nedges = this->Internals->Adjacency[v].OutEdges.size();\n if (nedges > 0)\n {\n edges = &(this->Internals->Adjacency[v].OutEdges[0]);\n }\n else\n {\n edges = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetOutDegree(vtkIdType v)\n{\n return this->Internals->Adjacency[v].OutEdges.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetDegree(vtkIdType v)\n{\n return this->Internals->Adjacency[v].InEdges.size() +\n this->Internals->Adjacency[v].OutEdges.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetInEdges(vtkIdType v, vtkInEdgeIterator *it)\n{\n if (it)\n {\n it->Initialize(this, v);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetInEdges(vtkIdType v, const vtkInEdgeType *& edges, vtkIdType & nedges)\n{\n nedges = this->Internals->Adjacency[v].InEdges.size();\n if (nedges > 0)\n {\n edges = &(this->Internals->Adjacency[v].InEdges[0]);\n }\n else\n {\n edges = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetInDegree(vtkIdType v)\n{\n return this->Internals->Adjacency[v].InEdges.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetAdjacentVertices(vtkIdType v, vtkAdjacentVertexIterator *it)\n{\n if (it)\n {\n it->Initialize(this, v);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetEdges(vtkEdgeListIterator *it)\n{\n if (it)\n {\n it->SetGraph(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetNumberOfEdges()\n{\n return this->Internals->NumberOfEdges;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::GetVertices(vtkVertexListIterator *it)\n{\n if (it)\n {\n it->SetGraph(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::GetNumberOfVertices()\n{\n return this->Internals->Adjacency.size();\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkGraph::CheckedShallowCopy(vtkGraph *g)\n{\n if (!g)\n {\n return false;\n }\n bool valid = this->IsStructureValid(g);\n if (valid)\n {\n this->CopyInternal(g, false);\n }\n return valid;\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkGraph::CheckedDeepCopy(vtkGraph *g)\n{\n if (!g)\n {\n return false;\n }\n bool valid = this->IsStructureValid(g);\n if (valid)\n {\n this->CopyInternal(g, true);\n }\n return valid;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::ShallowCopy(vtkDataObject *obj)\n{\n vtkGraph *g = vtkGraph::SafeDownCast(obj);\n if (!g)\n {\n vtkErrorMacro(\"Can only shallow copy from vtkGraph subclass.\");\n return;\n }\n bool valid = this->IsStructureValid(g);\n if (valid)\n {\n this->CopyInternal(g, false);\n }\n else\n {\n vtkErrorMacro(\"Invalid graph structure for this type of graph.\");\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::DeepCopy(vtkDataObject *obj)\n{\n vtkGraph *g = vtkGraph::SafeDownCast(obj);\n if (!g)\n {\n vtkErrorMacro(\"Can only shallow copy from vtkGraph subclass.\");\n return;\n }\n bool valid = this->IsStructureValid(g);\n if (valid)\n {\n this->CopyInternal(g, true);\n }\n else\n {\n vtkErrorMacro(\"Invalid graph structure for this type of graph.\");\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::CopyInternal(vtkGraph *g, bool deep)\n{\n if (deep)\n {\n vtkDataObject::DeepCopy(g);\n }\n else\n {\n vtkDataObject::ShallowCopy(g);\n }\n \/\/ Copy on write.\n this->SetInternals(g->Internals);\n if (deep)\n {\n this->EdgeData->DeepCopy(g->EdgeData);\n this->VertexData->DeepCopy(g->VertexData);\n }\n else\n {\n this->EdgeData->ShallowCopy(g->EdgeData);\n this->VertexData->ShallowCopy(g->VertexData);\n }\n if (g->Points)\n {\n if (!this->Points)\n {\n this->Points = vtkPoints::New();\n }\n if (deep)\n {\n this->Points->DeepCopy(g->Points);\n }\n else\n {\n this->Points->ShallowCopy(g->Points);\n }\n }\n else if (this->Points)\n {\n this->Points->Delete();\n this->Points = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::Squeeze()\n{\n if ( this->Points )\n {\n this->Points->Squeeze();\n }\n this->EdgeData->Squeeze();\n this->VertexData->Squeeze();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkGraph *vtkGraph::GetData(vtkInformation *info)\n{\n return info? vtkGraph::SafeDownCast(info->Get(DATA_OBJECT())) : 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkGraph *vtkGraph::GetData(vtkInformationVector *v, int i)\n{\n return vtkGraph::GetData(v->GetInformationObject(i));\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkGraph::AddVertexInternal()\n{\n this->ForceOwnership();\n this->Internals->Adjacency.push_back(vtkVertexAdjacencyList());\n return this->Internals->Adjacency.size() - 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkEdgeType vtkGraph::AddEdgeInternal(vtkIdType u, vtkIdType v, bool directed)\n{\n this->ForceOwnership();\n vtkIdType edgeId = this->Internals->NumberOfEdges;\n this->Internals->NumberOfEdges++;\n this->Internals->Adjacency[u].OutEdges.push_back(vtkOutEdgeType(v, edgeId));\n if (directed)\n {\n this->Internals->Adjacency[v].InEdges.push_back(vtkInEdgeType(u, edgeId));\n }\n else if (u != v)\n {\n \/\/ Avoid storing self-loops twice in undirected graphs.\n this->Internals->Adjacency[v].OutEdges.push_back(vtkOutEdgeType(u, edgeId));\n }\n return vtkEdgeType(u, v, edgeId);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::ReorderOutVertices(vtkIdType v, vtkIdTypeArray *vertices)\n{\n this->ForceOwnership();\n vtksys_stl::vector<vtkOutEdgeType> outEdges;\n vtksys_stl::vector<vtkOutEdgeType>::iterator it, itEnd;\n itEnd = this->Internals->Adjacency[v].OutEdges.end();\n for (vtkIdType i = 0; i < vertices->GetNumberOfTuples(); ++i)\n {\n vtkIdType vert = vertices->GetValue(i);\n \/\/ Find the matching edge\n for (it = this->Internals->Adjacency[v].OutEdges.begin(); it != itEnd; ++it)\n {\n if (it->Target == vert)\n {\n outEdges.push_back(*it);\n break;\n }\n }\n }\n if (outEdges.size() != this->Internals->Adjacency[v].OutEdges.size())\n {\n vtkErrorMacro(\"Invalid reorder list.\");\n return;\n }\n this->Internals->Adjacency[v].OutEdges = outEdges;\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkGraph::IsSameStructure(vtkGraph *other)\n{\n return (this->Internals == other->Internals);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::ForceOwnership()\n{\n \/\/ If the reference count == 1, we own it and can change it.\n \/\/ If the reference count > 1, we must make a copy to avoid\n \/\/ changing the structure of other graphs.\n if (this->Internals->GetReferenceCount() > 1)\n {\n vtkGraphInternals *internals = vtkGraphInternals::New();\n internals->Adjacency = this->Internals->Adjacency;\n internals->NumberOfEdges = this->Internals->NumberOfEdges;\n this->SetInternals(internals);\n internals->Delete();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGraph::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Supporting operators\n\/\/----------------------------------------------------------------------------\n\n\/\/----------------------------------------------------------------------------\nbool operator==(vtkEdgeBase e1, vtkEdgeBase e2)\n{\n return e1.Id == e2.Id;\n}\n\n\/\/----------------------------------------------------------------------------\nbool operator!=(vtkEdgeBase e1, vtkEdgeBase e2)\n{\n return e1.Id != e2.Id;\n}\n\n\/\/----------------------------------------------------------------------------\nostream& operator<<(ostream& out, vtkEdgeBase e)\n{\n return out << e.Id;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>iox-#25: Use more auto<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n AdPlug - Replayer for many OPL2\/OPL3 audio file formats.\n Copyright (C) 1999 - 2002 Simon Peter <dn.tlp@gmx.net>, et al.\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n cff.cpp - BoomTracker loader by Riven the Mage <riven@ok.ru>\n*\/\n\/*\n NOTE: Volume slides in the original player have effect on carrier volume\n only. So my volume slides slightly different from them.\n*\/\n\n#include <stdlib.h>\n\n#include \"cff.h\"\n\n\/* -------- Public Methods -------------------------------- *\/\n\nCPlayer *CcffLoader::factory(Copl *newopl)\n{\n CcffLoader *p = new CcffLoader(newopl);\n return p;\n}\n\nbool CcffLoader::load(istream &f, const char *filename)\n{\n\tcff_unpacker unpacker;\n\n\tconst unsigned char conv_inst[11] = { 2,1,10,9,4,3,6,5,0,8,7 };\n\tconst unsigned short conv_note[12] = { 0x16B, 0x181, 0x198, 0x1B0, 0x1CA, 0x1E5, 0x202, 0x220, 0x241, 0x263, 0x287, 0x2AE };\n\n\tint i,j,k,t=0;\n\n\tunsigned char old_event_byte2[9] = {0};\n\n\t\/\/ read header\n\tf.read((char *)&header,sizeof(header));\n\n\t\/\/ '<CUD-FM-File>' - signed ?\n\tif (memcmp(header.id,\"<CUD-FM-File>\"\"\\x1A\\xDE\\xE0\",16))\n\t\treturn false;\n\n\tunsigned char *module = new unsigned char [0x10000];\n\n\t\/\/ packed ?\n\tif (header.packed)\n\t{\n\t\tunsigned char *packed_module = new unsigned char [header.size + 4];\n\n\t\tmemset(packed_module,0,header.size + 4);\n\n\t\tf.read((char *)packed_module,header.size);\n\n\t\tif (!unpacker.unpack(packed_module,module))\n\t\t{\n\t\t\tdelete packed_module;\n\t\t\tdelete module;\n\t\t\treturn false;\n\t\t}\n\n\t\tdelete packed_module;\n\t}\n\telse\n\t{\n\t\tf.read((char *)module,header.size);\n\t}\n\n\t\/\/ init CmodPlayer\n\trealloc_instruments(47);\n\trealloc_order(64);\n\trealloc_patterns(36,64,9);\n\n\tinit_notetable(conv_note);\n\tinit_trackord();\n\n\t\/\/ load instruments\n\tfor (i=0;i<47;i++)\n\t{\n\t\tmemcpy(&instruments[i],&module[i*32],sizeof(cff_instrument));\n\n\t\tfor(j=0;j<11;j++)\n\t\t\tinst[i].data[conv_inst[j]] = instruments[i].data[j];\n\n\t\tinstruments[i].name[20] = 0;\n\t}\n\n\t\/\/ number of patterns\n\tnop = module[0x5E0];\n\n\t\/\/ load title & author\n\tmemcpy(song_title,&module[0x614],20);\n\tmemcpy(song_author,&module[0x600],20);\n\n\t\/\/ load order\n\tmemcpy(order,&module[0x628],64);\n\n\t\/\/ load tracks\n\tfor (i=0;i<nop;i++)\n\t{\n\t\tfor (j=0;j<9;j++)\n\t\t{\n\t\t\tfor (k=0;k<64;k++)\n\t\t\t{\n\t\t\t\tcff_event *event = (cff_event *)&module[0x669 + ((i*64+k)*9+j)*3];\n\n\t\t\t\t\/\/ convert note\n\t\t\t\tif (event->byte0 == 0x6D)\n\t\t\t\t\ttracks[t][k].note = 127;\n\t\t\t\telse\n\t\t\t\t\tif (event->byte0)\n\t\t\t\t\t\ttracks[t][k].note = event->byte0;\n\n\t\t\t\tif (event->byte2)\n\t\t\t\t\told_event_byte2[j] = event->byte2;\n\n\t\t\t\t\/\/ convert effect\n\t\t\t\tswitch (event->byte1)\n\t\t\t\t{\n\t\t\t\t\tcase 'I': \/\/ set instrument\n\t\t\t\t\t\ttracks[t][k].inst = event->byte2 + 1;\n\t\t\t\t\t\ttracks[t][k].param1 = tracks[t][k].param2 = 0;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'H': \/\/ set tempo\n\t\t\t\t\t\ttracks[t][k].command = 7;\n\t\t\t\t\t\tif (event->byte2 < 16)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttracks[t][k].param1 = 0x07;\n\t \t\t\t\t\t\ttracks[t][k].param2 = 0x0D;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'A': \/\/ set speed\n\t\t\t\t\t\ttracks[t][k].command = 19;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2 >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = event->byte2 & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'L': \/\/ pattern break\n\t\t\t\t\t\ttracks[t][k].command = 13;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2 >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = event->byte2 & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'K': \/\/ order jump\n\t\t\t\t\t\ttracks[t][k].command = 11;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2 >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = event->byte2 & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'M': \/\/ set vibrato\/tremolo\n\t\t\t\t\t\ttracks[t][k].command = 27;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2 >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = event->byte2 & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'C': \/\/ set modulator volume\n\t\t\t\t\t\ttracks[t][k].command = 21;\n\t\t\t\t\t\ttracks[t][k].param1 = (0x3F - event->byte2) >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = (0x3F - event->byte2) & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'G': \/\/ set carrier volume\n\t\t\t\t\t\ttracks[t][k].command = 22;\n\t\t\t\t\t\ttracks[t][k].param1 = (0x3F - event->byte2) >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = (0x3F - event->byte2) & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'B': \/\/ set carrier waveform\n\t\t\t\t\t\ttracks[t][k].command = 25;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2;\n\t\t\t\t\t\ttracks[t][k].param2 = 0x0F;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'E': \/\/ fine frequency slide down\n\t\t\t\t\t\ttracks[t][k].command = 24;\n\t\t\t\t\t\ttracks[t][k].param1 = old_event_byte2[j] >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'F': \/\/ fine frequency slide up\n\t\t\t\t\t\ttracks[t][k].command = 23;\n\t\t\t\t\t\ttracks[t][k].param1 = old_event_byte2[j] >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'D': \/\/ fine volume slide\n\t\t\t\t\t\ttracks[t][k].command = 14;\n\t\t\t\t\t\tif (old_event_byte2[j] & 15)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ slide down\n\t\t\t\t\t\t\ttracks[t][k].param1 = 5;\n\t\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] & 15;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ slide up\n\t\t\t\t\t\t\ttracks[t][k].param1 = 4;\n\t\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] >> 4;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'J': \/\/ arpeggio\n\t\t\t\t\t\ttracks[t][k].param1 = old_event_byte2[j] >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] & 15;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tt++;\n\t\t}\n\t}\n\n\tdelete module;\n\n\t\/\/ default instruments\n\tfor (i=0;i<9;i++)\n\t{\n\t\tif (!tracks[i][0].inst)\n\t\t\ttracks[i][0].inst = i + 1;\n\t}\n\n\t\/\/ order loop\n\trestartpos = 0;\n\n\t\/\/ order length\n\tfor (i=0;i<64;i++)\n\t{\n\t\tif (order[i] >= 0x80)\n\t\t{\n\t\t\tlength = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ default tempo\n\tbpm = 0x7D;\n\n\trewind(0);\n\n\treturn true;\t\n}\n\nstd::string CcffLoader::gettype()\n{\n\tstd::string xstr = \"BoomTracker 4\";\n\n\tif (header.packed)\n\t\txstr += \", packed\";\n\n\treturn std::string(xstr);\n}\n\nstd::string CcffLoader::gettitle()\n{\n\treturn std::string(song_title,20);\n}\n\nstd::string CcffLoader::getauthor()\n{\n\treturn std::string(song_author,20);\n}\n\nstd::string CcffLoader::getinstrument(unsigned int n)\n{\n\treturn std::string(instruments[n].name);\n}\n\nunsigned int CcffLoader::getinstruments()\n{\n\treturn 47;\n}\n\n\/* -------- Private Methods ------------------------------- *\/\n\n#ifdef _WIN32\n#pragma warning(disable:4244)\n#pragma warning(disable:4018)\n#endif\n\n\/*\n Lempel-Ziv-Tyr ;-)\n*\/\nunsigned int CcffLoader::cff_unpacker::unpack(unsigned char *ibuf, unsigned char *obuf)\n{\n\tif (memcmp(ibuf,\"YsComp\"\"\\x07\"\"CUD1997\"\"\\x1A\\x04\",16))\n\t\treturn 0;\n\n\tinput = ibuf + 16;\n\toutput = obuf;\n\n\toutput_length = 0;\n\n\theap = (unsigned char *)malloc(0x10000);\n\tdictionary = (unsigned char **)malloc(sizeof(unsigned char *)*0x8000);\n\n\tmemset(heap,0,0x10000);\n\tmemset(dictionary,0,0x8000);\n\n\tcleanup();\n\tstartup();\n\n\t\/\/ LZW\n\twhile (1)\n\t{\n\t\tnew_code = get_code();\n\n\t\t\/\/ 0x00: end of data\n\t\tif (new_code == 0)\n\t\t\tbreak;\n\n\t\t\/\/ 0x01: end of block\n\t\tif (new_code == 1)\n\t\t{\n\t\t\tcleanup();\n\t\t\tstartup();\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ 0x02: expand code length\n\t\tif (new_code == 2)\n\t\t{\n\t\t\tcode_length++;\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ 0x03: RLE\n\t\tif (new_code == 3)\n\t\t{\n\t\t\tunsigned char old_code_length = code_length;\n\n\t\t\tcode_length = 2;\n\n\t\t\tunsigned char repeat_length = get_code() + 1;\n\n\t\t\tcode_length = 4 << get_code();\n\n\t\t\tunsigned long repeat_counter = get_code();\n\n\t\t\tfor (int i=0;i<repeat_counter*repeat_length;i++)\n\t\t\t\toutput[output_length++] = output[output_length - repeat_length];\n\n\t\t\tcode_length = old_code_length;\n\n\t\t\tstartup();\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (new_code >= (0x104 + dictionary_length))\n\t\t{\n\t\t\t\/\/ dictionary <- old.code.string + old.code.char\n\t\t\tthe_string[++the_string[0]] = the_string[1];\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ dictionary <- old.code.string + new.code.char\n\t\t\tunsigned char temp_string[256];\n\n\t\t\ttranslate_code(new_code,temp_string);\n\n\t\t\tthe_string[++the_string[0]] = temp_string[1];\n\t\t}\n\n\t\texpand_dictionary(the_string);\n\n\t\t\/\/ output <- new.code.string\n\t\ttranslate_code(new_code,the_string);\n\n\t\tfor (int i=0;i<the_string[0];i++)\n\t\t\toutput[output_length++] = the_string[i+1];\n\n\t\told_code = new_code;\n\t}\n\n\tfree(heap);\n\tfree(dictionary);\n\n\tif (memcmp(output + 0x5E1,\"CUD-FM-File - SEND A POSTCARD -\",31))\n\t\treturn 0;\n\n\treturn output_length;\n}\n\nunsigned long CcffLoader::cff_unpacker::get_code()\n{\n\tunsigned long code;\n\n\twhile (bits_left <= 24)\n\t{\n\t\tbits_buffer |= ((*input++) << bits_left);\n\t\tbits_left += 8;\n\t}\n\n\tcode = bits_buffer & ((1 << code_length) - 1);\n\n\tbits_buffer >>= code_length;\n\tbits_left -= code_length;\n\n\treturn code;\n}\n\nvoid CcffLoader::cff_unpacker::translate_code(unsigned long code, unsigned char *string)\n{\n\tunsigned char translated_string[256];\n\n\tif (code >= 0x104)\n\t{\n\t\tmemcpy(translated_string,dictionary[code - 0x104],(*(dictionary[code - 0x104])) + 1);\n\t}\n\telse\n\t{\n\t\ttranslated_string[0] = 1;\n\t\ttranslated_string[1] = (code - 4) & 0xFF;\n\t}\n\n\tmemcpy(string,translated_string,256);\n}\n\nvoid CcffLoader::cff_unpacker::cleanup()\n{\n\tcode_length = 9;\n\n\tbits_buffer = 0;\n\tbits_left = 0;\n\n\theap_length = 0;\n\tdictionary_length = 0;\n}\n\nvoid CcffLoader::cff_unpacker::startup()\n{\n\told_code = get_code();\n\n\ttranslate_code(old_code,the_string);\n\n\tfor (int i=0;i<the_string[0];i++)\n\t\toutput[output_length++] = the_string[i+1];\n}\n\nvoid CcffLoader::cff_unpacker::expand_dictionary(unsigned char *string)\n{\n\tmemcpy(&heap[heap_length],string,string[0] + 1);\n\n\tdictionary[dictionary_length] = &heap[heap_length];\n\n\tdictionary_length++;\n\n\theap_length += (string[0] + 1);\n}\n\n#ifdef _WIN32\n#pragma warning(default:4244)\n#pragma warning(default:4018)\n#endif\n<commit_msg>comment changes<commit_after>\/*\n AdPlug - Replayer for many OPL2\/OPL3 audio file formats.\n Copyright (C) 1999 - 2002 Simon Peter <dn.tlp@gmx.net>, et al.\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n cff.cpp - BoomTracker loader by Riven the Mage <riven@ok.ru>\n*\/\n\/*\n NOTE: Conversion of slides is not 100% accurate. Original volume slides\n have effect on carrier volume only. Also, original frequency & volume\n slides use previous effect data instead of current.\n*\/\n\n#include <stdlib.h>\n\n#include \"cff.h\"\n\n\/* -------- Public Methods -------------------------------- *\/\n\nCPlayer *CcffLoader::factory(Copl *newopl)\n{\n CcffLoader *p = new CcffLoader(newopl);\n return p;\n}\n\nbool CcffLoader::load(istream &f, const char *filename)\n{\n\tcff_unpacker unpacker;\n\n\tconst unsigned char conv_inst[11] = { 2,1,10,9,4,3,6,5,0,8,7 };\n\tconst unsigned short conv_note[12] = { 0x16B, 0x181, 0x198, 0x1B0, 0x1CA, 0x1E5, 0x202, 0x220, 0x241, 0x263, 0x287, 0x2AE };\n\n\tint i,j,k,t=0;\n\n\tunsigned char old_event_byte2[9] = {0};\n\n\t\/\/ read header\n\tf.read((char *)&header,sizeof(header));\n\n\t\/\/ '<CUD-FM-File>' - signed ?\n\tif (memcmp(header.id,\"<CUD-FM-File>\"\"\\x1A\\xDE\\xE0\",16))\n\t\treturn false;\n\n\tunsigned char *module = new unsigned char [0x10000];\n\n\t\/\/ packed ?\n\tif (header.packed)\n\t{\n\t\tunsigned char *packed_module = new unsigned char [header.size + 4];\n\n\t\tmemset(packed_module,0,header.size + 4);\n\n\t\tf.read((char *)packed_module,header.size);\n\n\t\tif (!unpacker.unpack(packed_module,module))\n\t\t{\n\t\t\tdelete packed_module;\n\t\t\tdelete module;\n\t\t\treturn false;\n\t\t}\n\n\t\tdelete packed_module;\n\t}\n\telse\n\t{\n\t\tf.read((char *)module,header.size);\n\t}\n\n\t\/\/ init CmodPlayer\n\trealloc_instruments(47);\n\trealloc_order(64);\n\trealloc_patterns(36,64,9);\n\n\tinit_notetable(conv_note);\n\tinit_trackord();\n\n\t\/\/ load instruments\n\tfor (i=0;i<47;i++)\n\t{\n\t\tmemcpy(&instruments[i],&module[i*32],sizeof(cff_instrument));\n\n\t\tfor(j=0;j<11;j++)\n\t\t\tinst[i].data[conv_inst[j]] = instruments[i].data[j];\n\n\t\tinstruments[i].name[20] = 0;\n\t}\n\n\t\/\/ number of patterns\n\tnop = module[0x5E0];\n\n\t\/\/ load title & author\n\tmemcpy(song_title,&module[0x614],20);\n\tmemcpy(song_author,&module[0x600],20);\n\n\t\/\/ load order\n\tmemcpy(order,&module[0x628],64);\n\n\t\/\/ load tracks\n\tfor (i=0;i<nop;i++)\n\t{\n\t\tfor (j=0;j<9;j++)\n\t\t{\n\t\t\tfor (k=0;k<64;k++)\n\t\t\t{\n\t\t\t\tcff_event *event = (cff_event *)&module[0x669 + ((i*64+k)*9+j)*3];\n\n\t\t\t\t\/\/ convert note\n\t\t\t\tif (event->byte0 == 0x6D)\n\t\t\t\t\ttracks[t][k].note = 127;\n\t\t\t\telse\n\t\t\t\t\tif (event->byte0)\n\t\t\t\t\t\ttracks[t][k].note = event->byte0;\n\n\t\t\t\tif (event->byte2)\n\t\t\t\t\told_event_byte2[j] = event->byte2;\n\n\t\t\t\t\/\/ convert effect\n\t\t\t\tswitch (event->byte1)\n\t\t\t\t{\n\t\t\t\t\tcase 'I': \/\/ set instrument\n\t\t\t\t\t\ttracks[t][k].inst = event->byte2 + 1;\n\t\t\t\t\t\ttracks[t][k].param1 = tracks[t][k].param2 = 0;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'H': \/\/ set tempo\n\t\t\t\t\t\ttracks[t][k].command = 7;\n\t\t\t\t\t\tif (event->byte2 < 16)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttracks[t][k].param1 = 0x07;\n\t \t\t\t\t\t\ttracks[t][k].param2 = 0x0D;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'A': \/\/ set speed\n\t\t\t\t\t\ttracks[t][k].command = 19;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2 >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = event->byte2 & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'L': \/\/ pattern break\n\t\t\t\t\t\ttracks[t][k].command = 13;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2 >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = event->byte2 & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'K': \/\/ order jump\n\t\t\t\t\t\ttracks[t][k].command = 11;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2 >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = event->byte2 & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'M': \/\/ set vibrato\/tremolo\n\t\t\t\t\t\ttracks[t][k].command = 27;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2 >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = event->byte2 & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'C': \/\/ set modulator volume\n\t\t\t\t\t\ttracks[t][k].command = 21;\n\t\t\t\t\t\ttracks[t][k].param1 = (0x3F - event->byte2) >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = (0x3F - event->byte2) & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'G': \/\/ set carrier volume\n\t\t\t\t\t\ttracks[t][k].command = 22;\n\t\t\t\t\t\ttracks[t][k].param1 = (0x3F - event->byte2) >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = (0x3F - event->byte2) & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'B': \/\/ set carrier waveform\n\t\t\t\t\t\ttracks[t][k].command = 25;\n\t\t\t\t\t\ttracks[t][k].param1 = event->byte2;\n\t\t\t\t\t\ttracks[t][k].param2 = 0x0F;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'E': \/\/ fine frequency slide down\n\t\t\t\t\t\ttracks[t][k].command = 24;\n\t\t\t\t\t\ttracks[t][k].param1 = old_event_byte2[j] >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'F': \/\/ fine frequency slide up\n\t\t\t\t\t\ttracks[t][k].command = 23;\n\t\t\t\t\t\ttracks[t][k].param1 = old_event_byte2[j] >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] & 15;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'D': \/\/ fine volume slide\n\t\t\t\t\t\ttracks[t][k].command = 14;\n\t\t\t\t\t\tif (old_event_byte2[j] & 15)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ slide down\n\t\t\t\t\t\t\ttracks[t][k].param1 = 5;\n\t\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] & 15;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ slide up\n\t\t\t\t\t\t\ttracks[t][k].param1 = 4;\n\t\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] >> 4;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'J': \/\/ arpeggio\n\t\t\t\t\t\ttracks[t][k].param1 = old_event_byte2[j] >> 4;\n\t\t\t\t\t\ttracks[t][k].param2 = old_event_byte2[j] & 15;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tt++;\n\t\t}\n\t}\n\n\tdelete module;\n\n\t\/\/ default instruments\n\tfor (i=0;i<9;i++)\n\t{\n\t\tif (!tracks[i][0].inst)\n\t\t\ttracks[i][0].inst = i + 1;\n\t}\n\n\t\/\/ order loop\n\trestartpos = 0;\n\n\t\/\/ order length\n\tfor (i=0;i<64;i++)\n\t{\n\t\tif (order[i] >= 0x80)\n\t\t{\n\t\t\tlength = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ default tempo\n\tbpm = 0x7D;\n\n\trewind(0);\n\n\treturn true;\t\n}\n\nstd::string CcffLoader::gettype()\n{\n\tstd::string xstr = \"BoomTracker 4\";\n\n\tif (header.packed)\n\t\txstr += \", packed\";\n\n\treturn std::string(xstr);\n}\n\nstd::string CcffLoader::gettitle()\n{\n\treturn std::string(song_title,20);\n}\n\nstd::string CcffLoader::getauthor()\n{\n\treturn std::string(song_author,20);\n}\n\nstd::string CcffLoader::getinstrument(unsigned int n)\n{\n\treturn std::string(instruments[n].name);\n}\n\nunsigned int CcffLoader::getinstruments()\n{\n\treturn 47;\n}\n\n\/* -------- Private Methods ------------------------------- *\/\n\n#ifdef _WIN32\n#pragma warning(disable:4244)\n#pragma warning(disable:4018)\n#endif\n\n\/*\n Lempel-Ziv-Tyr ;-)\n*\/\nunsigned int CcffLoader::cff_unpacker::unpack(unsigned char *ibuf, unsigned char *obuf)\n{\n\tif (memcmp(ibuf,\"YsComp\"\"\\x07\"\"CUD1997\"\"\\x1A\\x04\",16))\n\t\treturn 0;\n\n\tinput = ibuf + 16;\n\toutput = obuf;\n\n\toutput_length = 0;\n\n\theap = (unsigned char *)malloc(0x10000);\n\tdictionary = (unsigned char **)malloc(sizeof(unsigned char *)*0x8000);\n\n\tmemset(heap,0,0x10000);\n\tmemset(dictionary,0,0x8000);\n\n\tcleanup();\n\tstartup();\n\n\t\/\/ LZW\n\twhile (1)\n\t{\n\t\tnew_code = get_code();\n\n\t\t\/\/ 0x00: end of data\n\t\tif (new_code == 0)\n\t\t\tbreak;\n\n\t\t\/\/ 0x01: end of block\n\t\tif (new_code == 1)\n\t\t{\n\t\t\tcleanup();\n\t\t\tstartup();\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ 0x02: expand code length\n\t\tif (new_code == 2)\n\t\t{\n\t\t\tcode_length++;\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ 0x03: RLE\n\t\tif (new_code == 3)\n\t\t{\n\t\t\tunsigned char old_code_length = code_length;\n\n\t\t\tcode_length = 2;\n\n\t\t\tunsigned char repeat_length = get_code() + 1;\n\n\t\t\tcode_length = 4 << get_code();\n\n\t\t\tunsigned long repeat_counter = get_code();\n\n\t\t\tfor (int i=0;i<repeat_counter*repeat_length;i++)\n\t\t\t\toutput[output_length++] = output[output_length - repeat_length];\n\n\t\t\tcode_length = old_code_length;\n\n\t\t\tstartup();\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (new_code >= (0x104 + dictionary_length))\n\t\t{\n\t\t\t\/\/ dictionary <- old.code.string + old.code.char\n\t\t\tthe_string[++the_string[0]] = the_string[1];\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ dictionary <- old.code.string + new.code.char\n\t\t\tunsigned char temp_string[256];\n\n\t\t\ttranslate_code(new_code,temp_string);\n\n\t\t\tthe_string[++the_string[0]] = temp_string[1];\n\t\t}\n\n\t\texpand_dictionary(the_string);\n\n\t\t\/\/ output <- new.code.string\n\t\ttranslate_code(new_code,the_string);\n\n\t\tfor (int i=0;i<the_string[0];i++)\n\t\t\toutput[output_length++] = the_string[i+1];\n\n\t\told_code = new_code;\n\t}\n\n\tfree(heap);\n\tfree(dictionary);\n\n\tif (memcmp(output + 0x5E1,\"CUD-FM-File - SEND A POSTCARD -\",31))\n\t\treturn 0;\n\n\treturn output_length;\n}\n\nunsigned long CcffLoader::cff_unpacker::get_code()\n{\n\tunsigned long code;\n\n\twhile (bits_left <= 24)\n\t{\n\t\tbits_buffer |= ((*input++) << bits_left);\n\t\tbits_left += 8;\n\t}\n\n\tcode = bits_buffer & ((1 << code_length) - 1);\n\n\tbits_buffer >>= code_length;\n\tbits_left -= code_length;\n\n\treturn code;\n}\n\nvoid CcffLoader::cff_unpacker::translate_code(unsigned long code, unsigned char *string)\n{\n\tunsigned char translated_string[256];\n\n\tif (code >= 0x104)\n\t{\n\t\tmemcpy(translated_string,dictionary[code - 0x104],(*(dictionary[code - 0x104])) + 1);\n\t}\n\telse\n\t{\n\t\ttranslated_string[0] = 1;\n\t\ttranslated_string[1] = (code - 4) & 0xFF;\n\t}\n\n\tmemcpy(string,translated_string,256);\n}\n\nvoid CcffLoader::cff_unpacker::cleanup()\n{\n\tcode_length = 9;\n\n\tbits_buffer = 0;\n\tbits_left = 0;\n\n\theap_length = 0;\n\tdictionary_length = 0;\n}\n\nvoid CcffLoader::cff_unpacker::startup()\n{\n\told_code = get_code();\n\n\ttranslate_code(old_code,the_string);\n\n\tfor (int i=0;i<the_string[0];i++)\n\t\toutput[output_length++] = the_string[i+1];\n}\n\nvoid CcffLoader::cff_unpacker::expand_dictionary(unsigned char *string)\n{\n\tmemcpy(&heap[heap_length],string,string[0] + 1);\n\n\tdictionary[dictionary_length] = &heap[heap_length];\n\n\tdictionary_length++;\n\n\theap_length += (string[0] + 1);\n}\n\n#ifdef _WIN32\n#pragma warning(default:4244)\n#pragma warning(default:4018)\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (C) 2012 PX4 Development Team. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 * @file mixer.cpp\n *\n * Programmable multi-channel mixer library.\n *\/\n\n#include <nuttx\/config.h>\n\n#include <sys\/types.h>\n#include <stdint.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <errno.h>\n#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <systemlib\/err.h>\n\n#include \"mixer.h\"\n\nMixer::Mixer(ControlCallback control_cb, uintptr_t cb_handle) :\n\t_next(nullptr),\n\t_control_cb(control_cb),\n\t_cb_handle(cb_handle)\n{\n}\n\nfloat\nMixer::get_control(uint8_t group, uint8_t index)\n{\n\tfloat\tvalue;\n\n\t_control_cb(_cb_handle, group, index, value);\n\n\treturn value;\n}\n\n\nfloat\nMixer::scale(const mixer_scaler_s &scaler, float input)\n{\n\tfloat output;\n\n\tif (input < 0.0f) {\n\t\toutput = (input * scaler.negative_scale) + scaler.offset;\n\n\t} else {\n\t\toutput = (input * scaler.positive_scale) + scaler.offset;\n\t}\n\n\tif (output > scaler.max_output) {\n\t\toutput = scaler.max_output;\n\n\t} else if (output < scaler.min_output) {\n\t\toutput = scaler.min_output;\n\t}\n\n\treturn output;\n}\n\nint\nMixer::scale_check(struct mixer_scaler_s &scaler)\n{\n\tif (scaler.offset > 1.001f)\n\t\treturn 1;\n\n\tif (scaler.offset < -1.001f)\n\t\treturn 2;\n\n\tif (scaler.min_output > scaler.max_output)\n\t\treturn 3;\n\n\tif (scaler.min_output < -1.001f)\n\t\treturn 4;\n\n\tif (scaler.max_output > 1.001f)\n\t\treturn 5;\n\n\treturn 0;\n}\n\nconst char *\nMixer::findtag(const char *buf, unsigned &buflen, char tag)\n{\n\twhile (buflen >= 2) {\n\t\tif ((buf[0] == tag) && (buf[1] == ':'))\n\t\t\treturn buf;\n\t\tbuf++;\n\t\tbuflen--;\n\t}\n\treturn nullptr;\n}\n\nconst char *\nMixer::skipline(const char *buf, unsigned &buflen)\n{\n\tconst char *p;\n\n\t\/* if we can find a CR or NL in the buffer, skip up to it *\/\n\tif ((p = (const char *)memchr(buf, '\\r', buflen)) || (p = (const char *)memchr(buf, '\\n', buflen))) {\n\t\t\/* skip up to it AND one beyond - could be on the NUL symbol now *\/\n\t\tbuflen -= (p - buf) + 1;\n\t\treturn p + 1;\n\t}\n\n\treturn nullptr;\n}\n\n\/****************************************************************************\/\n\nNullMixer::NullMixer() :\n\tMixer(nullptr, 0)\n{\n}\n\nunsigned\nNullMixer::mix(float *outputs, unsigned space)\n{\n\tif (space > 0) {\n\t\t*outputs = 0.0f;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nvoid\nNullMixer::groups_required(uint32_t &groups)\n{\n\n}\n\nNullMixer *\nNullMixer::from_text(const char *buf, unsigned &buflen)\n{\n\tNullMixer *nm = nullptr;\n\tconst char *end = buf + buflen;\n\n\t\/* enforce that the mixer ends with space or a new line *\/\n\tfor (int i = buflen - 1; i >= 0; i--) {\n\t\tif (buf[i] == '\\0')\n\t\t\tcontinue;\n\n\t\t\/* require a space or newline at the end of the buffer, fail on printable chars *\/\n\t\tif (buf[i] == ' ' || buf[i] == '\\n' || buf[i] == '\\r') {\n\t\t\t\/* found a line ending or space, so no split symbols \/ numbers. good. *\/\n\t\t\tbreak;\n\t\t} else {\n\t\t\treturn nm;\n\t\t}\n\n\t}\n\n\tif ((buflen >= 2) && (buf[0] == 'Z') && (buf[1] == ':')) {\n\t\tnm = new NullMixer;\n\t\tbuflen -= 2;\n\t}\n\n\treturn nm;\n}\n<commit_msg>Remove unused variable<commit_after>\/****************************************************************************\n *\n * Copyright (C) 2012 PX4 Development Team. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 * @file mixer.cpp\n *\n * Programmable multi-channel mixer library.\n *\/\n\n#include <nuttx\/config.h>\n\n#include <sys\/types.h>\n#include <stdint.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <errno.h>\n#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <systemlib\/err.h>\n\n#include \"mixer.h\"\n\nMixer::Mixer(ControlCallback control_cb, uintptr_t cb_handle) :\n\t_next(nullptr),\n\t_control_cb(control_cb),\n\t_cb_handle(cb_handle)\n{\n}\n\nfloat\nMixer::get_control(uint8_t group, uint8_t index)\n{\n\tfloat\tvalue;\n\n\t_control_cb(_cb_handle, group, index, value);\n\n\treturn value;\n}\n\n\nfloat\nMixer::scale(const mixer_scaler_s &scaler, float input)\n{\n\tfloat output;\n\n\tif (input < 0.0f) {\n\t\toutput = (input * scaler.negative_scale) + scaler.offset;\n\n\t} else {\n\t\toutput = (input * scaler.positive_scale) + scaler.offset;\n\t}\n\n\tif (output > scaler.max_output) {\n\t\toutput = scaler.max_output;\n\n\t} else if (output < scaler.min_output) {\n\t\toutput = scaler.min_output;\n\t}\n\n\treturn output;\n}\n\nint\nMixer::scale_check(struct mixer_scaler_s &scaler)\n{\n\tif (scaler.offset > 1.001f)\n\t\treturn 1;\n\n\tif (scaler.offset < -1.001f)\n\t\treturn 2;\n\n\tif (scaler.min_output > scaler.max_output)\n\t\treturn 3;\n\n\tif (scaler.min_output < -1.001f)\n\t\treturn 4;\n\n\tif (scaler.max_output > 1.001f)\n\t\treturn 5;\n\n\treturn 0;\n}\n\nconst char *\nMixer::findtag(const char *buf, unsigned &buflen, char tag)\n{\n\twhile (buflen >= 2) {\n\t\tif ((buf[0] == tag) && (buf[1] == ':'))\n\t\t\treturn buf;\n\t\tbuf++;\n\t\tbuflen--;\n\t}\n\treturn nullptr;\n}\n\nconst char *\nMixer::skipline(const char *buf, unsigned &buflen)\n{\n\tconst char *p;\n\n\t\/* if we can find a CR or NL in the buffer, skip up to it *\/\n\tif ((p = (const char *)memchr(buf, '\\r', buflen)) || (p = (const char *)memchr(buf, '\\n', buflen))) {\n\t\t\/* skip up to it AND one beyond - could be on the NUL symbol now *\/\n\t\tbuflen -= (p - buf) + 1;\n\t\treturn p + 1;\n\t}\n\n\treturn nullptr;\n}\n\n\/****************************************************************************\/\n\nNullMixer::NullMixer() :\n\tMixer(nullptr, 0)\n{\n}\n\nunsigned\nNullMixer::mix(float *outputs, unsigned space)\n{\n\tif (space > 0) {\n\t\t*outputs = 0.0f;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nvoid\nNullMixer::groups_required(uint32_t &groups)\n{\n\n}\n\nNullMixer *\nNullMixer::from_text(const char *buf, unsigned &buflen)\n{\n\tNullMixer *nm = nullptr;\n\n\t\/* enforce that the mixer ends with space or a new line *\/\n\tfor (int i = buflen - 1; i >= 0; i--) {\n\t\tif (buf[i] == '\\0')\n\t\t\tcontinue;\n\n\t\t\/* require a space or newline at the end of the buffer, fail on printable chars *\/\n\t\tif (buf[i] == ' ' || buf[i] == '\\n' || buf[i] == '\\r') {\n\t\t\t\/* found a line ending or space, so no split symbols \/ numbers. good. *\/\n\t\t\tbreak;\n\t\t} else {\n\t\t\treturn nm;\n\t\t}\n\n\t}\n\n\tif ((buflen >= 2) && (buf[0] == 'Z') && (buf[1] == ':')) {\n\t\tnm = new NullMixer;\n\t\tbuflen -= 2;\n\t}\n\n\treturn nm;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- SpillPlacement.cpp - Optimal Spill Code Placement -----------------===\/\/\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\/\/ This file implements the spill code placement analysis.\n\/\/\n\/\/ Each edge bundle corresponds to a node in a Hopfield network. Constraints on\n\/\/ basic blocks are weighted by the block frequency and added to become the node\n\/\/ bias.\n\/\/\n\/\/ Transparent basic blocks have the variable live through, but don't care if it\n\/\/ is spilled or in a register. These blocks become connections in the Hopfield\n\/\/ network, again weighted by block frequency.\n\/\/\n\/\/ The Hopfield network minimizes (possibly locally) its energy function:\n\/\/\n\/\/ E = -sum_n V_n * ( B_n + sum_{n, m linked by b} V_m * F_b )\n\/\/\n\/\/ The energy function represents the expected spill code execution frequency,\n\/\/ or the cost of spilling. This is a Lyapunov function which never increases\n\/\/ when a node is updated. It is guaranteed to converge to a local minimum.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"spillplacement\"\n#include \"SpillPlacement.h\"\n#include \"llvm\/CodeGen\/EdgeBundles.h\"\n#include \"llvm\/CodeGen\/LiveIntervalAnalysis.h\"\n#include \"llvm\/CodeGen\/MachineBasicBlock.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineLoopInfo.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n\nusing namespace llvm;\n\nchar SpillPlacement::ID = 0;\nINITIALIZE_PASS_BEGIN(SpillPlacement, \"spill-code-placement\",\n \"Spill Code Placement Analysis\", true, true)\nINITIALIZE_PASS_DEPENDENCY(EdgeBundles)\nINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\nINITIALIZE_PASS_END(SpillPlacement, \"spill-code-placement\",\n \"Spill Code Placement Analysis\", true, true)\n\nchar &llvm::SpillPlacementID = SpillPlacement::ID;\n\nvoid SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n AU.addRequiredTransitive<EdgeBundles>();\n AU.addRequiredTransitive<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n}\n\n\/\/\/ Node - Each edge bundle corresponds to a Hopfield node.\n\/\/\/\n\/\/\/ The node contains precomputed frequency data that only depends on the CFG,\n\/\/\/ but Bias and Links are computed each time placeSpills is called.\n\/\/\/\n\/\/\/ The node Value is positive when the variable should be in a register. The\n\/\/\/ value can change when linked nodes change, but convergence is very fast\n\/\/\/ because all weights are positive.\n\/\/\/\nstruct SpillPlacement::Node {\n \/\/\/ Frequency - Total block frequency feeding into[0] or out of[1] the bundle.\n \/\/\/ Ideally, these two numbers should be identical, but inaccuracies in the\n \/\/\/ block frequency estimates means that we need to normalize ingoing and\n \/\/\/ outgoing frequencies separately so they are commensurate.\n float Frequency[2];\n\n \/\/\/ Bias - Normalized contributions from non-transparent blocks.\n \/\/\/ A bundle connected to a MustSpill block has a huge negative bias,\n \/\/\/ otherwise it is a number in the range [-2;2].\n float Bias;\n\n \/\/\/ Value - Output value of this node computed from the Bias and links.\n \/\/\/ This is always in the range [-1;1]. A positive number means the variable\n \/\/\/ should go in a register through this bundle.\n float Value;\n\n typedef SmallVector<std::pair<float, unsigned>, 4> LinkVector;\n\n \/\/\/ Links - (Weight, BundleNo) for all transparent blocks connecting to other\n \/\/\/ bundles. The weights are all positive and add up to at most 2, weights\n \/\/\/ from ingoing and outgoing nodes separately add up to a most 1. The weight\n \/\/\/ sum can be less than 2 when the variable is not live into \/ out of some\n \/\/\/ connected basic blocks.\n LinkVector Links;\n\n \/\/\/ preferReg - Return true when this node prefers to be in a register.\n bool preferReg() const {\n \/\/ Undecided nodes (Value==0) go on the stack.\n return Value > 0;\n }\n\n \/\/\/ mustSpill - Return True if this node is so biased that it must spill.\n bool mustSpill() const {\n \/\/ Actually, we must spill if Bias < sum(weights).\n \/\/ It may be worth it to compute the weight sum here?\n return Bias < -2.0f;\n }\n\n \/\/\/ Node - Create a blank Node.\n Node() {\n Frequency[0] = Frequency[1] = 0;\n }\n\n \/\/\/ clear - Reset per-query data, but preserve frequencies that only depend on\n \/\/ the CFG.\n void clear() {\n Bias = Value = 0;\n Links.clear();\n }\n\n \/\/\/ addLink - Add a link to bundle b with weight w.\n \/\/\/ out=0 for an ingoing link, and 1 for an outgoing link.\n void addLink(unsigned b, float w, bool out) {\n \/\/ Normalize w relative to all connected blocks from that direction.\n w \/= Frequency[out];\n\n \/\/ There can be multiple links to the same bundle, add them up.\n for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)\n if (I->second == b) {\n I->first += w;\n return;\n }\n \/\/ This must be the first link to b.\n Links.push_back(std::make_pair(w, b));\n }\n\n \/\/\/ addBias - Bias this node from an ingoing[0] or outgoing[1] link.\n \/\/\/ Return the change to the total number of positive biases.\n int addBias(float w, bool out) {\n \/\/ Normalize w relative to all connected blocks from that direction.\n w \/= Frequency[out];\n int Before = Bias > 0;\n Bias += w;\n int After = Bias > 0;\n return After - Before;\n }\n\n \/\/\/ update - Recompute Value from Bias and Links. Return true when node\n \/\/\/ preference changes.\n bool update(const Node nodes[]) {\n \/\/ Compute the weighted sum of inputs.\n float Sum = Bias;\n for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)\n Sum += I->first * nodes[I->second].Value;\n\n \/\/ The weighted sum is going to be in the range [-2;2]. Ideally, we should\n \/\/ simply set Value = sign(Sum), but we will add a dead zone around 0 for\n \/\/ two reasons:\n \/\/ 1. It avoids arbitrary bias when all links are 0 as is possible during\n \/\/ initial iterations.\n \/\/ 2. It helps tame rounding errors when the links nominally sum to 0.\n const float Thres = 1e-4f;\n bool Before = preferReg();\n if (Sum < -Thres)\n Value = -1;\n else if (Sum > Thres)\n Value = 1;\n else\n Value = 0;\n return Before != preferReg();\n }\n};\n\nbool SpillPlacement::runOnMachineFunction(MachineFunction &mf) {\n MF = &mf;\n bundles = &getAnalysis<EdgeBundles>();\n loops = &getAnalysis<MachineLoopInfo>();\n\n assert(!nodes && \"Leaking node array\");\n nodes = new Node[bundles->getNumBundles()];\n\n \/\/ Compute total ingoing and outgoing block frequencies for all bundles.\n BlockFrequency.resize(mf.getNumBlockIDs());\n for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {\n float Freq = LiveIntervals::getSpillWeight(true, false,\n loops->getLoopDepth(I));\n unsigned Num = I->getNumber();\n BlockFrequency[Num] = Freq;\n nodes[bundles->getBundle(Num, 1)].Frequency[0] += Freq;\n nodes[bundles->getBundle(Num, 0)].Frequency[1] += Freq;\n }\n\n \/\/ We never change the function.\n return false;\n}\n\nvoid SpillPlacement::releaseMemory() {\n delete[] nodes;\n nodes = 0;\n}\n\n\/\/\/ activate - mark node n as active if it wasn't already.\nvoid SpillPlacement::activate(unsigned n) {\n if (ActiveNodes->test(n))\n return;\n ActiveNodes->set(n);\n nodes[n].clear();\n}\n\n\n\/\/\/ addConstraints - Compute node biases and weights from a set of constraints.\n\/\/\/ Set a bit in NodeMask for each active node.\nvoid SpillPlacement::addConstraints(ArrayRef<BlockConstraint> LiveBlocks) {\n for (ArrayRef<BlockConstraint>::iterator I = LiveBlocks.begin(),\n E = LiveBlocks.end(); I != E; ++I) {\n float Freq = getBlockFrequency(I->Number);\n const float Bias[] = {\n 0, \/\/ DontCare,\n 1, \/\/ PrefReg,\n -1, \/\/ PrefSpill\n -HUGE_VALF \/\/ MustSpill\n };\n\n \/\/ Live-in to block?\n if (I->Entry != DontCare) {\n unsigned ib = bundles->getBundle(I->Number, 0);\n activate(ib);\n PositiveNodes += nodes[ib].addBias(Freq * Bias[I->Entry], 1);\n }\n\n \/\/ Live-out from block?\n if (I->Exit != DontCare) {\n unsigned ob = bundles->getBundle(I->Number, 1);\n activate(ob);\n PositiveNodes += nodes[ob].addBias(Freq * Bias[I->Exit], 0);\n }\n }\n}\n\nvoid SpillPlacement::addLinks(ArrayRef<unsigned> Links) {\n for (ArrayRef<unsigned>::iterator I = Links.begin(), E = Links.end(); I != E;\n ++I) {\n unsigned Number = *I;\n unsigned ib = bundles->getBundle(Number, 0);\n unsigned ob = bundles->getBundle(Number, 1);\n\n \/\/ Ignore self-loops.\n if (ib == ob)\n continue;\n activate(ib);\n activate(ob);\n float Freq = getBlockFrequency(Number);\n nodes[ib].addLink(ob, Freq, 1);\n nodes[ob].addLink(ib, Freq, 0);\n }\n}\n\n\/\/\/ iterate - Repeatedly update the Hopfield nodes until stability or the\n\/\/\/ maximum number of iterations is reached.\n\/\/\/ @param Linked - Numbers of linked nodes that need updating.\nvoid SpillPlacement::iterate(const SmallVectorImpl<unsigned> &Linked) {\n if (Linked.empty())\n return;\n\n \/\/ Run up to 10 iterations. The edge bundle numbering is closely related to\n \/\/ basic block numbering, so there is a strong tendency towards chains of\n \/\/ linked nodes with sequential numbers. By scanning the linked nodes\n \/\/ backwards and forwards, we make it very likely that a single node can\n \/\/ affect the entire network in a single iteration. That means very fast\n \/\/ convergence, usually in a single iteration.\n for (unsigned iteration = 0; iteration != 10; ++iteration) {\n \/\/ Scan backwards, skipping the last node which was just updated.\n bool Changed = false;\n for (SmallVectorImpl<unsigned>::const_reverse_iterator I =\n llvm::next(Linked.rbegin()), E = Linked.rend(); I != E; ++I) {\n unsigned n = *I;\n bool C = nodes[n].update(nodes);\n Changed |= C;\n }\n if (!Changed)\n return;\n\n \/\/ Scan forwards, skipping the first node which was just updated.\n Changed = false;\n for (SmallVectorImpl<unsigned>::const_iterator I =\n llvm::next(Linked.begin()), E = Linked.end(); I != E; ++I) {\n unsigned n = *I;\n bool C = nodes[n].update(nodes);\n Changed |= C;\n }\n if (!Changed)\n return;\n }\n}\n\nvoid SpillPlacement::prepare(BitVector &RegBundles) {\n \/\/ Reuse RegBundles as our ActiveNodes vector.\n ActiveNodes = &RegBundles;\n ActiveNodes->clear();\n ActiveNodes->resize(bundles->getNumBundles());\n PositiveNodes = 0;\n}\n\nbool\nSpillPlacement::finish() {\n assert(ActiveNodes && \"Call prepare() first\");\n \/\/ Update all active nodes, and find the ones that are actually linked to\n \/\/ something so their value may change when iterating.\n SmallVector<unsigned, 8> Linked;\n for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n)) {\n nodes[n].update(nodes);\n \/\/ A node that must spill, or a node without any links is not going to\n \/\/ change its value ever again, so exclude it from iterations.\n if (!nodes[n].Links.empty() && !nodes[n].mustSpill())\n Linked.push_back(n);\n }\n\n \/\/ Iterate the network to convergence.\n iterate(Linked);\n\n \/\/ Write preferences back to ActiveNodes.\n bool Perfect = true;\n for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n))\n if (!nodes[n].preferReg()) {\n ActiveNodes->reset(n);\n Perfect = false;\n }\n ActiveNodes = 0;\n return Perfect;\n}\n<commit_msg>Prefer multiplications to divisions.<commit_after>\/\/===-- SpillPlacement.cpp - Optimal Spill Code Placement -----------------===\/\/\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\/\/ This file implements the spill code placement analysis.\n\/\/\n\/\/ Each edge bundle corresponds to a node in a Hopfield network. Constraints on\n\/\/ basic blocks are weighted by the block frequency and added to become the node\n\/\/ bias.\n\/\/\n\/\/ Transparent basic blocks have the variable live through, but don't care if it\n\/\/ is spilled or in a register. These blocks become connections in the Hopfield\n\/\/ network, again weighted by block frequency.\n\/\/\n\/\/ The Hopfield network minimizes (possibly locally) its energy function:\n\/\/\n\/\/ E = -sum_n V_n * ( B_n + sum_{n, m linked by b} V_m * F_b )\n\/\/\n\/\/ The energy function represents the expected spill code execution frequency,\n\/\/ or the cost of spilling. This is a Lyapunov function which never increases\n\/\/ when a node is updated. It is guaranteed to converge to a local minimum.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"spillplacement\"\n#include \"SpillPlacement.h\"\n#include \"llvm\/CodeGen\/EdgeBundles.h\"\n#include \"llvm\/CodeGen\/LiveIntervalAnalysis.h\"\n#include \"llvm\/CodeGen\/MachineBasicBlock.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineLoopInfo.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n\nusing namespace llvm;\n\nchar SpillPlacement::ID = 0;\nINITIALIZE_PASS_BEGIN(SpillPlacement, \"spill-code-placement\",\n \"Spill Code Placement Analysis\", true, true)\nINITIALIZE_PASS_DEPENDENCY(EdgeBundles)\nINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\nINITIALIZE_PASS_END(SpillPlacement, \"spill-code-placement\",\n \"Spill Code Placement Analysis\", true, true)\n\nchar &llvm::SpillPlacementID = SpillPlacement::ID;\n\nvoid SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n AU.addRequiredTransitive<EdgeBundles>();\n AU.addRequiredTransitive<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n}\n\n\/\/\/ Node - Each edge bundle corresponds to a Hopfield node.\n\/\/\/\n\/\/\/ The node contains precomputed frequency data that only depends on the CFG,\n\/\/\/ but Bias and Links are computed each time placeSpills is called.\n\/\/\/\n\/\/\/ The node Value is positive when the variable should be in a register. The\n\/\/\/ value can change when linked nodes change, but convergence is very fast\n\/\/\/ because all weights are positive.\n\/\/\/\nstruct SpillPlacement::Node {\n \/\/\/ Scale - Inverse block frequency feeding into[0] or out of[1] the bundle.\n \/\/\/ Ideally, these two numbers should be identical, but inaccuracies in the\n \/\/\/ block frequency estimates means that we need to normalize ingoing and\n \/\/\/ outgoing frequencies separately so they are commensurate.\n float Scale[2];\n\n \/\/\/ Bias - Normalized contributions from non-transparent blocks.\n \/\/\/ A bundle connected to a MustSpill block has a huge negative bias,\n \/\/\/ otherwise it is a number in the range [-2;2].\n float Bias;\n\n \/\/\/ Value - Output value of this node computed from the Bias and links.\n \/\/\/ This is always in the range [-1;1]. A positive number means the variable\n \/\/\/ should go in a register through this bundle.\n float Value;\n\n typedef SmallVector<std::pair<float, unsigned>, 4> LinkVector;\n\n \/\/\/ Links - (Weight, BundleNo) for all transparent blocks connecting to other\n \/\/\/ bundles. The weights are all positive and add up to at most 2, weights\n \/\/\/ from ingoing and outgoing nodes separately add up to a most 1. The weight\n \/\/\/ sum can be less than 2 when the variable is not live into \/ out of some\n \/\/\/ connected basic blocks.\n LinkVector Links;\n\n \/\/\/ preferReg - Return true when this node prefers to be in a register.\n bool preferReg() const {\n \/\/ Undecided nodes (Value==0) go on the stack.\n return Value > 0;\n }\n\n \/\/\/ mustSpill - Return True if this node is so biased that it must spill.\n bool mustSpill() const {\n \/\/ Actually, we must spill if Bias < sum(weights).\n \/\/ It may be worth it to compute the weight sum here?\n return Bias < -2.0f;\n }\n\n \/\/\/ Node - Create a blank Node.\n Node() {\n Scale[0] = Scale[1] = 0;\n }\n\n \/\/\/ clear - Reset per-query data, but preserve frequencies that only depend on\n \/\/ the CFG.\n void clear() {\n Bias = Value = 0;\n Links.clear();\n }\n\n \/\/\/ addLink - Add a link to bundle b with weight w.\n \/\/\/ out=0 for an ingoing link, and 1 for an outgoing link.\n void addLink(unsigned b, float w, bool out) {\n \/\/ Normalize w relative to all connected blocks from that direction.\n w *= Scale[out];\n\n \/\/ There can be multiple links to the same bundle, add them up.\n for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)\n if (I->second == b) {\n I->first += w;\n return;\n }\n \/\/ This must be the first link to b.\n Links.push_back(std::make_pair(w, b));\n }\n\n \/\/\/ addBias - Bias this node from an ingoing[0] or outgoing[1] link.\n \/\/\/ Return the change to the total number of positive biases.\n int addBias(float w, bool out) {\n \/\/ Normalize w relative to all connected blocks from that direction.\n w *= Scale[out];\n int Before = Bias > 0;\n Bias += w;\n int After = Bias > 0;\n return After - Before;\n }\n\n \/\/\/ update - Recompute Value from Bias and Links. Return true when node\n \/\/\/ preference changes.\n bool update(const Node nodes[]) {\n \/\/ Compute the weighted sum of inputs.\n float Sum = Bias;\n for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)\n Sum += I->first * nodes[I->second].Value;\n\n \/\/ The weighted sum is going to be in the range [-2;2]. Ideally, we should\n \/\/ simply set Value = sign(Sum), but we will add a dead zone around 0 for\n \/\/ two reasons:\n \/\/ 1. It avoids arbitrary bias when all links are 0 as is possible during\n \/\/ initial iterations.\n \/\/ 2. It helps tame rounding errors when the links nominally sum to 0.\n const float Thres = 1e-4f;\n bool Before = preferReg();\n if (Sum < -Thres)\n Value = -1;\n else if (Sum > Thres)\n Value = 1;\n else\n Value = 0;\n return Before != preferReg();\n }\n};\n\nbool SpillPlacement::runOnMachineFunction(MachineFunction &mf) {\n MF = &mf;\n bundles = &getAnalysis<EdgeBundles>();\n loops = &getAnalysis<MachineLoopInfo>();\n\n assert(!nodes && \"Leaking node array\");\n nodes = new Node[bundles->getNumBundles()];\n\n \/\/ Compute total ingoing and outgoing block frequencies for all bundles.\n BlockFrequency.resize(mf.getNumBlockIDs());\n for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {\n float Freq = LiveIntervals::getSpillWeight(true, false,\n loops->getLoopDepth(I));\n unsigned Num = I->getNumber();\n BlockFrequency[Num] = Freq;\n nodes[bundles->getBundle(Num, 1)].Scale[0] += Freq;\n nodes[bundles->getBundle(Num, 0)].Scale[1] += Freq;\n }\n\n \/\/ Scales are reciprocal frequencies.\n for (unsigned i = 0, e = bundles->getNumBundles(); i != e; ++i)\n for (unsigned d = 0; d != 2; ++d)\n if (nodes[i].Scale[d] > 0)\n nodes[i].Scale[d] = 1 \/ nodes[i].Scale[d];\n\n \/\/ We never change the function.\n return false;\n}\n\nvoid SpillPlacement::releaseMemory() {\n delete[] nodes;\n nodes = 0;\n}\n\n\/\/\/ activate - mark node n as active if it wasn't already.\nvoid SpillPlacement::activate(unsigned n) {\n if (ActiveNodes->test(n))\n return;\n ActiveNodes->set(n);\n nodes[n].clear();\n}\n\n\n\/\/\/ addConstraints - Compute node biases and weights from a set of constraints.\n\/\/\/ Set a bit in NodeMask for each active node.\nvoid SpillPlacement::addConstraints(ArrayRef<BlockConstraint> LiveBlocks) {\n for (ArrayRef<BlockConstraint>::iterator I = LiveBlocks.begin(),\n E = LiveBlocks.end(); I != E; ++I) {\n float Freq = getBlockFrequency(I->Number);\n const float Bias[] = {\n 0, \/\/ DontCare,\n 1, \/\/ PrefReg,\n -1, \/\/ PrefSpill\n -HUGE_VALF \/\/ MustSpill\n };\n\n \/\/ Live-in to block?\n if (I->Entry != DontCare) {\n unsigned ib = bundles->getBundle(I->Number, 0);\n activate(ib);\n PositiveNodes += nodes[ib].addBias(Freq * Bias[I->Entry], 1);\n }\n\n \/\/ Live-out from block?\n if (I->Exit != DontCare) {\n unsigned ob = bundles->getBundle(I->Number, 1);\n activate(ob);\n PositiveNodes += nodes[ob].addBias(Freq * Bias[I->Exit], 0);\n }\n }\n}\n\nvoid SpillPlacement::addLinks(ArrayRef<unsigned> Links) {\n for (ArrayRef<unsigned>::iterator I = Links.begin(), E = Links.end(); I != E;\n ++I) {\n unsigned Number = *I;\n unsigned ib = bundles->getBundle(Number, 0);\n unsigned ob = bundles->getBundle(Number, 1);\n\n \/\/ Ignore self-loops.\n if (ib == ob)\n continue;\n activate(ib);\n activate(ob);\n float Freq = getBlockFrequency(Number);\n nodes[ib].addLink(ob, Freq, 1);\n nodes[ob].addLink(ib, Freq, 0);\n }\n}\n\n\/\/\/ iterate - Repeatedly update the Hopfield nodes until stability or the\n\/\/\/ maximum number of iterations is reached.\n\/\/\/ @param Linked - Numbers of linked nodes that need updating.\nvoid SpillPlacement::iterate(const SmallVectorImpl<unsigned> &Linked) {\n if (Linked.empty())\n return;\n\n \/\/ Run up to 10 iterations. The edge bundle numbering is closely related to\n \/\/ basic block numbering, so there is a strong tendency towards chains of\n \/\/ linked nodes with sequential numbers. By scanning the linked nodes\n \/\/ backwards and forwards, we make it very likely that a single node can\n \/\/ affect the entire network in a single iteration. That means very fast\n \/\/ convergence, usually in a single iteration.\n for (unsigned iteration = 0; iteration != 10; ++iteration) {\n \/\/ Scan backwards, skipping the last node which was just updated.\n bool Changed = false;\n for (SmallVectorImpl<unsigned>::const_reverse_iterator I =\n llvm::next(Linked.rbegin()), E = Linked.rend(); I != E; ++I) {\n unsigned n = *I;\n bool C = nodes[n].update(nodes);\n Changed |= C;\n }\n if (!Changed)\n return;\n\n \/\/ Scan forwards, skipping the first node which was just updated.\n Changed = false;\n for (SmallVectorImpl<unsigned>::const_iterator I =\n llvm::next(Linked.begin()), E = Linked.end(); I != E; ++I) {\n unsigned n = *I;\n bool C = nodes[n].update(nodes);\n Changed |= C;\n }\n if (!Changed)\n return;\n }\n}\n\nvoid SpillPlacement::prepare(BitVector &RegBundles) {\n \/\/ Reuse RegBundles as our ActiveNodes vector.\n ActiveNodes = &RegBundles;\n ActiveNodes->clear();\n ActiveNodes->resize(bundles->getNumBundles());\n PositiveNodes = 0;\n}\n\nbool\nSpillPlacement::finish() {\n assert(ActiveNodes && \"Call prepare() first\");\n \/\/ Update all active nodes, and find the ones that are actually linked to\n \/\/ something so their value may change when iterating.\n SmallVector<unsigned, 8> Linked;\n for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n)) {\n nodes[n].update(nodes);\n \/\/ A node that must spill, or a node without any links is not going to\n \/\/ change its value ever again, so exclude it from iterations.\n if (!nodes[n].Links.empty() && !nodes[n].mustSpill())\n Linked.push_back(n);\n }\n\n \/\/ Iterate the network to convergence.\n iterate(Linked);\n\n \/\/ Write preferences back to ActiveNodes.\n bool Perfect = true;\n for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n))\n if (!nodes[n].preferReg()) {\n ActiveNodes->reset(n);\n Perfect = false;\n }\n ActiveNodes = 0;\n return Perfect;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"HomogenizationConstraint.h\"\n\n#include \"Function.h\"\n\nregisterMooseObject(\"TensorMechanicsApp\", HomogenizationConstraint);\n\nInputParameters\nHomogenizationConstraint::validParams()\n{\n InputParameters params = ElementUserObject::validParams();\n params.addRequiredParam<MultiMooseEnum>(\n \"constraint_types\",\n Homogenization::constraintType,\n \"Type of each constraint: strain, stress, or none. The types are specified in the \"\n \"column-major order, and there must be 9 entries in total.\");\n params.addRequiredParam<std::vector<FunctionName>>(\n \"targets\", \"Functions giving the targets to hit for constraint types that are not none.\");\n params.addParam<bool>(\"large_kinematics\", false, \"Using large displacements?\");\n params.addParam<std::string>(\"base_name\", \"Material property base name\");\n return params;\n}\n\nHomogenizationConstraint::HomogenizationConstraint(const InputParameters & parameters)\n : ElementUserObject(parameters),\n _large_kinematics(getParam<bool>(\"large_kinematics\")),\n _base_name(isParamValid(\"base_name\") ? getParam<std::string>(\"base_name\") + \"_\" : \"\"),\n _F(getMaterialPropertyByName<RankTwoTensor>(_base_name + \"deformation_gradient\")),\n _pk1_stress(getMaterialPropertyByName<RankTwoTensor>(_base_name + \"pk1_stress\")),\n _pk1_jacobian(getMaterialPropertyByName<RankFourTensor>(_base_name + \"pk1_jacobian\"))\n{\n \/\/ Constraint types\n auto types = getParam<MultiMooseEnum>(\"constraint_types\");\n if (types.size() != Moose::dim * Moose::dim)\n mooseError(\"Number of constraint types must equal dim * dim. \", types.size(), \" are provided.\");\n\n \/\/ Targets to hit\n const std::vector<FunctionName> & fnames = getParam<std::vector<FunctionName>>(\"targets\");\n\n \/\/ Prepare the constraint map\n unsigned int fcount = 0;\n for (const auto j : make_range(Moose::dim))\n for (const auto i : make_range(Moose::dim))\n {\n const auto idx = i + Moose::dim * j;\n const auto ctype = static_cast<Homogenization::ConstraintType>(types.get(idx));\n if (ctype != Homogenization::ConstraintType::None)\n {\n const Function * const f = &getFunctionByName(fnames[fcount++]);\n _cmap[{i, j}] = {ctype, f};\n }\n }\n}\n\nvoid\nHomogenizationConstraint::initialize()\n{\n _residual.zero();\n _jacobian.zero();\n}\n\nvoid\nHomogenizationConstraint::execute()\n{\n for (_qp = 0; _qp < _qrule->n_points(); _qp++)\n {\n Real dV = _JxW[_qp] * _coord[_qp];\n _residual += computeResidual() * dV;\n _jacobian += computeJacobian() * dV;\n }\n}\n\nvoid\nHomogenizationConstraint::threadJoin(const UserObject & y)\n{\n const HomogenizationConstraint & other = static_cast<const HomogenizationConstraint &>(y);\n _residual += other._residual;\n _jacobian += other._jacobian;\n}\n\nvoid\nHomogenizationConstraint::finalize()\n{\n std::vector<Real> residual(&_residual(0, 0), &_residual(0, 0) + RankTwoTensor::N2);\n std::vector<Real> jacobian(&_jacobian(0, 0, 0, 0), &_jacobian(0, 0, 0, 0) + RankFourTensor::N4);\n\n gatherSum(residual);\n gatherSum(jacobian);\n\n std::copy(residual.begin(), residual.end(), &_residual(0, 0));\n std::copy(jacobian.begin(), jacobian.end(), &_jacobian(0, 0, 0, 0));\n}\n\nRankTwoTensor\nHomogenizationConstraint::computeResidual()\n{\n RankTwoTensor res;\n\n for (auto && [indices, constraint] : _cmap)\n {\n auto && [i, j] = indices;\n auto && [ctype, ctarget] = constraint;\n\n if (_large_kinematics)\n {\n if (ctype == Homogenization::ConstraintType::Stress)\n res(i, j) = _pk1_stress[_qp](i, j) - ctarget->value(_t, _q_point[_qp]);\n else if (ctype == Homogenization::ConstraintType::Strain)\n res(i, j) = _F[_qp](i, j) - (Real(i == j) + ctarget->value(_t, _q_point[_qp]));\n else\n mooseError(\"Unknown constraint type in the integral!\");\n }\n else\n {\n if (ctype == Homogenization::ConstraintType::Stress)\n res(i, j) = _pk1_stress[_qp](i, j) - ctarget->value(_t, _q_point[_qp]);\n else if (ctype == Homogenization::ConstraintType::Strain)\n res(i, j) = 0.5 * (_F[_qp](i, j) + _F[_qp](j, i)) -\n (Real(i == j) + ctarget->value(_t, _q_point[_qp]));\n else\n mooseError(\"Unknown constraint type in the integral!\");\n }\n }\n\n return res;\n}\n\nRankFourTensor\nHomogenizationConstraint::computeJacobian()\n{\n RankFourTensor res;\n\n for (auto && [indices1, constraint1] : _cmap)\n {\n auto && [i, j] = indices1;\n auto && [ctype, ctarget] = constraint1;\n for (auto && indices2 : _cmap)\n {\n auto && [a, b] = indices2.first;\n if (ctype == Homogenization::ConstraintType::Stress)\n res(i, j, a, b) = _pk1_jacobian[_qp](i, j, a, b);\n else if (ctype == Homogenization::ConstraintType::Strain)\n {\n if (_large_kinematics)\n res(i, j, a, b) = Real(i == a && j == b);\n else\n res(i, j, a, b) = 0.5 * Real(i == a && j == b) + 0.5 * Real(i == b && j == a);\n }\n else\n mooseError(\"Unknown constraint type in Jacobian calculator!\");\n }\n }\n\n return res;\n}\n<commit_msg>fix min gcc unused var error<commit_after>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"HomogenizationConstraint.h\"\n\n#include \"Function.h\"\n\nregisterMooseObject(\"TensorMechanicsApp\", HomogenizationConstraint);\n\nInputParameters\nHomogenizationConstraint::validParams()\n{\n InputParameters params = ElementUserObject::validParams();\n params.addRequiredParam<MultiMooseEnum>(\n \"constraint_types\",\n Homogenization::constraintType,\n \"Type of each constraint: strain, stress, or none. The types are specified in the \"\n \"column-major order, and there must be 9 entries in total.\");\n params.addRequiredParam<std::vector<FunctionName>>(\n \"targets\", \"Functions giving the targets to hit for constraint types that are not none.\");\n params.addParam<bool>(\"large_kinematics\", false, \"Using large displacements?\");\n params.addParam<std::string>(\"base_name\", \"Material property base name\");\n return params;\n}\n\nHomogenizationConstraint::HomogenizationConstraint(const InputParameters & parameters)\n : ElementUserObject(parameters),\n _large_kinematics(getParam<bool>(\"large_kinematics\")),\n _base_name(isParamValid(\"base_name\") ? getParam<std::string>(\"base_name\") + \"_\" : \"\"),\n _F(getMaterialPropertyByName<RankTwoTensor>(_base_name + \"deformation_gradient\")),\n _pk1_stress(getMaterialPropertyByName<RankTwoTensor>(_base_name + \"pk1_stress\")),\n _pk1_jacobian(getMaterialPropertyByName<RankFourTensor>(_base_name + \"pk1_jacobian\"))\n{\n \/\/ Constraint types\n auto types = getParam<MultiMooseEnum>(\"constraint_types\");\n if (types.size() != Moose::dim * Moose::dim)\n mooseError(\"Number of constraint types must equal dim * dim. \", types.size(), \" are provided.\");\n\n \/\/ Targets to hit\n const std::vector<FunctionName> & fnames = getParam<std::vector<FunctionName>>(\"targets\");\n\n \/\/ Prepare the constraint map\n unsigned int fcount = 0;\n for (const auto j : make_range(Moose::dim))\n for (const auto i : make_range(Moose::dim))\n {\n const auto idx = i + Moose::dim * j;\n const auto ctype = static_cast<Homogenization::ConstraintType>(types.get(idx));\n if (ctype != Homogenization::ConstraintType::None)\n {\n const Function * const f = &getFunctionByName(fnames[fcount++]);\n _cmap[{i, j}] = {ctype, f};\n }\n }\n}\n\nvoid\nHomogenizationConstraint::initialize()\n{\n _residual.zero();\n _jacobian.zero();\n}\n\nvoid\nHomogenizationConstraint::execute()\n{\n for (_qp = 0; _qp < _qrule->n_points(); _qp++)\n {\n Real dV = _JxW[_qp] * _coord[_qp];\n _residual += computeResidual() * dV;\n _jacobian += computeJacobian() * dV;\n }\n}\n\nvoid\nHomogenizationConstraint::threadJoin(const UserObject & y)\n{\n const HomogenizationConstraint & other = static_cast<const HomogenizationConstraint &>(y);\n _residual += other._residual;\n _jacobian += other._jacobian;\n}\n\nvoid\nHomogenizationConstraint::finalize()\n{\n std::vector<Real> residual(&_residual(0, 0), &_residual(0, 0) + RankTwoTensor::N2);\n std::vector<Real> jacobian(&_jacobian(0, 0, 0, 0), &_jacobian(0, 0, 0, 0) + RankFourTensor::N4);\n\n gatherSum(residual);\n gatherSum(jacobian);\n\n std::copy(residual.begin(), residual.end(), &_residual(0, 0));\n std::copy(jacobian.begin(), jacobian.end(), &_jacobian(0, 0, 0, 0));\n}\n\nRankTwoTensor\nHomogenizationConstraint::computeResidual()\n{\n RankTwoTensor res;\n\n for (auto && [indices, constraint] : _cmap)\n {\n auto && [i, j] = indices;\n auto && [ctype, ctarget] = constraint;\n\n if (_large_kinematics)\n {\n if (ctype == Homogenization::ConstraintType::Stress)\n res(i, j) = _pk1_stress[_qp](i, j) - ctarget->value(_t, _q_point[_qp]);\n else if (ctype == Homogenization::ConstraintType::Strain)\n res(i, j) = _F[_qp](i, j) - (Real(i == j) + ctarget->value(_t, _q_point[_qp]));\n else\n mooseError(\"Unknown constraint type in the integral!\");\n }\n else\n {\n if (ctype == Homogenization::ConstraintType::Stress)\n res(i, j) = _pk1_stress[_qp](i, j) - ctarget->value(_t, _q_point[_qp]);\n else if (ctype == Homogenization::ConstraintType::Strain)\n res(i, j) = 0.5 * (_F[_qp](i, j) + _F[_qp](j, i)) -\n (Real(i == j) + ctarget->value(_t, _q_point[_qp]));\n else\n mooseError(\"Unknown constraint type in the integral!\");\n }\n }\n\n return res;\n}\n\nRankFourTensor\nHomogenizationConstraint::computeJacobian()\n{\n RankFourTensor res;\n\n for (auto && [indices1, constraint1] : _cmap)\n {\n auto && [i, j] = indices1;\n auto && ctype = constraint1.first;\n for (auto && indices2 : _cmap)\n {\n auto && [a, b] = indices2.first;\n if (ctype == Homogenization::ConstraintType::Stress)\n res(i, j, a, b) = _pk1_jacobian[_qp](i, j, a, b);\n else if (ctype == Homogenization::ConstraintType::Strain)\n {\n if (_large_kinematics)\n res(i, j, a, b) = Real(i == a && j == b);\n else\n res(i, j, a, b) = 0.5 * Real(i == a && j == b) + 0.5 * Real(i == b && j == a);\n }\n else\n mooseError(\"Unknown constraint type in Jacobian calculator!\");\n }\n }\n\n return res;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project.\n\nCopyright (C) 2008 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n\n#include \"videorenderer_vmr9.h\"\n\n#ifndef QT_NO_PHONON_VIDEO\n\n#include <QtGui\/QWidget>\n#include <QtGui\/QPainter>\n#include <QtCore\/QTimerEvent>\n\n#ifndef Q_OS_WINCE\n#include <d3d9.h>\n#include <vmr9.h>\n#else\n#include <uuids.h>\n#endif\n\nQT_BEGIN_NAMESPACE\n\n\nnamespace Phonon\n{\n namespace DS9\n {\n VideoRendererVMR9::~VideoRendererVMR9()\n {\n }\n\n bool VideoRendererVMR9::isNative() const\n {\n return true;\n }\n\n\n#ifdef Q_OS_WINCE\n VideoRendererVMR9::VideoRendererVMR9(QWidget *target) : m_target(target)\n {\n m_target->setAttribute(Qt::WA_PaintOnScreen, true);\n m_filter = Filter(CLSID_VideoRenderer, IID_IBaseFilter);\n }\n\n QSize VideoRendererVMR9::videoSize() const\n {\n LONG w = 0,\n h = 0;\n ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);\n if (basic) {\n basic->GetVideoSize( &w, &h);\n }\n return QSize(w, h);\n }\n\n void VideoRendererVMR9::repaintCurrentFrame(QWidget * \/*target*\/, const QRect & \/*rect*\/)\n {\n \/\/nothing to do here: the renderer paints everything\n }\n\n void VideoRendererVMR9::notifyResize(const QRect &rect, Phonon::VideoWidget::AspectRatio aspectRatio,\n Phonon::VideoWidget::ScaleMode scaleMode)\n {\n ComPointer<IVideoWindow> video(m_filter, IID_IVideoWindow);\n\n OAHWND owner;\n HRESULT hr = video->get_Owner(&owner);\n if (FAILED(hr)) {\n return;\n }\n\n const OAHWND newOwner = reinterpret_cast<OAHWND>(m_target->winId());\n if (owner != newOwner) {\n video->put_Owner(newOwner);\n video->put_MessageDrain(newOwner);\n video->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);\n }\n\n \/\/make sure the widget takes the whole size of the parent\n video->SetWindowPosition(0, 0, rect.width(), rect.height());\n\n const QSize vsize = videoSize();\n internalNotifyResize(rect.size(), vsize, aspectRatio, scaleMode);\n\n ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);\n if (basic) {\n basic->SetDestinationPosition(m_dstX, m_dstY, m_dstWidth, m_dstHeight);\n }\n }\n\n void VideoRendererVMR9::applyMixerSettings(qreal \/*brightness*\/, qreal \/*contrast*\/, qreal \/*m_hue*\/, qreal \/*saturation*\/)\n {\n \/\/this can't be supported for WinCE\n }\n\n void VideoRendererVMR9::setActive(bool b)\n {\n if (b) {\n } else {\n ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);\n if (basic) {\n basic->SetDestinationPosition(0, 0, 0, 0);\n }\n }\n }\n\n QImage VideoRendererVMR9::snapshot() const\n {\n ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);\n if (basic) {\n LONG bufferSize = 0;\n \/\/1st we get the buffer size\n basic->GetCurrentImage(&bufferSize, 0);\n\n QByteArray buffer;\n buffer.resize(bufferSize);\n HRESULT hr = basic->GetCurrentImage(&bufferSize, reinterpret_cast<long*>(buffer.data()));\n\n if (SUCCEEDED(hr)) {\n\n const BITMAPINFOHEADER *bmi = reinterpret_cast<const BITMAPINFOHEADER*>(buffer.constData());\n\n const int w = bmi->biWidth,\n h = bmi->biHeight;\n\n \/\/ Create image and copy data into image.\n QImage ret(w, h, QImage::Format_RGB32);\n\n if (!ret.isNull()) {\n const char *data = buffer.constData() + bmi->biSize;\n const int bytes_per_line = w * sizeof(QRgb);\n for (int y = h - 1; y >= 0; --y) {\n qMemCopy(ret.scanLine(y), \/\/destination\n data, \/\/source\n bytes_per_line);\n data += bytes_per_line;\n }\n }\n return ret;\n }\n }\n return QImage();\n }\n\n#else\n VideoRendererVMR9::VideoRendererVMR9(QWidget *target) : m_target(target)\n {\n m_target->setAttribute(Qt::WA_PaintOnScreen, true);\n m_filter = Filter(CLSID_VideoMixingRenderer9, IID_IBaseFilter);\n if (!m_filter) {\n qWarning(\"the video widget could not be initialized correctly\");\n return;\n }\n\n ComPointer<IVMRFilterConfig9> config(m_filter, IID_IVMRFilterConfig9);\n Q_ASSERT(config);\n HRESULT hr = config->SetRenderingMode(VMR9Mode_Windowless);\n Q_ASSERT(SUCCEEDED(hr));\n hr = config->SetNumberOfStreams(1); \/\/for now we limit it to 1 input stream\n Q_ASSERT(SUCCEEDED(hr));\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n windowlessControl->SetVideoClippingWindow(reinterpret_cast<HWND>(target->winId()));\n }\n\n QImage VideoRendererVMR9::snapshot() const\n {\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n if (windowlessControl) {\n BYTE *buffer = 0;\n HRESULT hr = windowlessControl->GetCurrentImage(&buffer);\n if (SUCCEEDED(hr)) {\n\n const BITMAPINFOHEADER *bmi = reinterpret_cast<BITMAPINFOHEADER*>(buffer);\n\n\n const int w = bmi->biWidth,\n h = bmi->biHeight;\n\n \/\/ Create image and copy data into image.\n QImage ret(w, h, QImage::Format_RGB32);\n\n if (!ret.isNull()) {\n uchar *data = buffer + bmi->biSize;\n const int bytes_per_line = w * sizeof(QRgb);\n for (int y = h - 1; y >= 0; --y) {\n qMemCopy(ret.scanLine(y), \/\/destination\n data, \/\/source\n bytes_per_line);\n data += bytes_per_line;\n }\n }\n ::CoTaskMemFree(buffer);\n return ret;\n }\n }\n return QImage();\n }\n\n QSize VideoRendererVMR9::videoSize() const\n {\n LONG w = 0,\n h = 0;\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n if (windowlessControl) {\n windowlessControl->GetNativeVideoSize( &w, &h, 0, 0);\n }\n return QSize(w, h);\n }\n \n void VideoRendererVMR9::repaintCurrentFrame(QWidget *target, const QRect &)\n {\n HDC hDC = target->getDC();\n \/\/ repaint the video\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n\n HRESULT hr = windowlessControl ? windowlessControl->RepaintVideo(target->winId(), hDC) : E_POINTER;\n if (FAILED(hr) || m_dstY > 0 || m_dstX > 0 || true) {\n const QColor c = target->palette().color(target->backgroundRole());\n COLORREF color = RGB(c.red(), c.green(), c.blue());\n HPEN hPen = ::CreatePen(PS_SOLID, 1, color);\n HBRUSH hBrush = ::CreateSolidBrush(color);\n ::SelectObject(hDC, hPen);\n ::SelectObject(hDC, hBrush);\n \/\/ repaint the video\n if (FAILED(hr)) {\n \/\/black background : we use the Win32 API to avoid the ghost effect of the backing store\n ::Rectangle(hDC, 0, 0, target->width(), target->height());\n } else {\n if (m_dstY > 0) {\n ::Rectangle(hDC, 0, 0, target->width(), m_dstY); \/\/top\n ::Rectangle(hDC, 0, target->height() - m_dstY, target->width(), target->height()); \/\/bottom\n }\n if (m_dstX > 0) {\n ::Rectangle(hDC, 0, m_dstY, m_dstX, m_dstHeight + m_dstY); \/\/left\n ::Rectangle(hDC, m_dstWidth + m_dstX, m_dstY, target->width(), m_dstHeight + m_dstY); \/\/right\n }\n }\n ::DeleteObject(hPen);\n ::DeleteObject(hBrush);\n }\n target->releaseDC(hDC);\n\n }\n\n void VideoRendererVMR9::notifyResize(const QRect &rect, Phonon::VideoWidget::AspectRatio aspectRatio,\n Phonon::VideoWidget::ScaleMode scaleMode)\n {\n const QSize vsize = videoSize();\n internalNotifyResize(rect.size(), vsize, aspectRatio, scaleMode);\n\n RECT dstRectWin = { m_dstX, m_dstY, m_dstWidth + m_dstX, m_dstHeight + m_dstY};\n RECT srcRectWin = { 0, 0, vsize.width(), vsize.height()};\n\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n if (windowlessControl) {\n windowlessControl->SetVideoPosition(&srcRectWin, &dstRectWin);\n }\n }\n\n void VideoRendererVMR9::setActive(bool b)\n {\n if (b) {\n } else {\n RECT dummyRect = { 0, 0, 0, 0};\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n windowlessControl->SetVideoPosition(&dummyRect, &dummyRect);\n }\n }\n\n\n void VideoRendererVMR9::applyMixerSettings(qreal brightness, qreal contrast, qreal hue, qreal saturation)\n {\n InputPin sink = BackendNode::pins(m_filter, PINDIR_INPUT).first();\n OutputPin source;\n if (FAILED(sink->ConnectedTo(source.pparam()))) {\n return; \/\/it must be connected to work\n }\n\n \/\/get the mixer (used for brightness\/contrast\/saturation\/hue)\n ComPointer<IVMRMixerControl9> mixer(m_filter, IID_IVMRMixerControl9);\n Q_ASSERT(mixer);\n\n VMR9ProcAmpControl ctrl;\n ctrl.dwSize = sizeof(ctrl);\n ctrl.dwFlags = ProcAmpControl9_Contrast | ProcAmpControl9_Brightness | ProcAmpControl9_Saturation | ProcAmpControl9_Hue;\n VMR9ProcAmpControlRange range;\n range.dwSize = sizeof(range);\n\n range.dwProperty = ProcAmpControl9_Contrast;\n HRESULT hr = mixer->GetProcAmpControlRange(0, &range);\n if (FAILED(hr)) {\n return;\n }\n ctrl.Contrast = ((contrast < 0 ? range.MinValue : range.MaxValue) - range.DefaultValue) * qAbs(contrast) + range.DefaultValue;\n\n \/\/brightness\n range.dwProperty = ProcAmpControl9_Brightness;\n hr = mixer->GetProcAmpControlRange(0, &range);\n if (FAILED(hr)) {\n return;\n }\n ctrl.Brightness = ((brightness < 0 ? range.MinValue : range.MaxValue) - range.DefaultValue) * qAbs(brightness) + range.DefaultValue;\n\n \/\/saturation\n range.dwProperty = ProcAmpControl9_Saturation;\n hr = mixer->GetProcAmpControlRange(0, &range);\n if (FAILED(hr)) {\n return;\n }\n ctrl.Saturation = ((saturation < 0 ? range.MinValue : range.MaxValue) - range.DefaultValue) * qAbs(saturation) + range.DefaultValue;\n\n \/\/hue\n range.dwProperty = ProcAmpControl9_Hue;\n hr = mixer->GetProcAmpControlRange(0, &range);\n if (FAILED(hr)) {\n return;\n }\n ctrl.Hue = ((hue < 0 ? range.MinValue : range.MaxValue) - range.DefaultValue) * qAbs(hue) + range.DefaultValue;\n\n \/\/finally set the settings\n mixer->SetProcAmpControl(0, &ctrl);\n }\n#endif\n }\n}\n\nQT_END_NAMESPACE\n\n#endif \/\/QT_NO_PHONON_VIDEO\n<commit_msg>make the video widget compatible with Qt 4.5 new paint engine<commit_after>\/* This file is part of the KDE project.\n\nCopyright (C) 2008 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n\n#include \"videorenderer_vmr9.h\"\n\n#ifndef QT_NO_PHONON_VIDEO\n\n#include <QtGui\/QWidget>\n#include <QtGui\/QPainter>\n#include <QtCore\/QTimerEvent>\n\n#ifndef Q_OS_WINCE\n#include <d3d9.h>\n#include <vmr9.h>\n#else\n#include <uuids.h>\n#endif\n\nQT_BEGIN_NAMESPACE\n\n\nnamespace Phonon\n{\n namespace DS9\n {\n VideoRendererVMR9::~VideoRendererVMR9()\n {\n }\n\n bool VideoRendererVMR9::isNative() const\n {\n return true;\n }\n\n\n#ifdef Q_OS_WINCE\n VideoRendererVMR9::VideoRendererVMR9(QWidget *target) : m_target(target)\n {\n m_target->setAttribute(Qt::WA_PaintOnScreen, true);\n m_filter = Filter(CLSID_VideoRenderer, IID_IBaseFilter);\n }\n\n QSize VideoRendererVMR9::videoSize() const\n {\n LONG w = 0,\n h = 0;\n ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);\n if (basic) {\n basic->GetVideoSize( &w, &h);\n }\n return QSize(w, h);\n }\n\n void VideoRendererVMR9::repaintCurrentFrame(QWidget * \/*target*\/, const QRect & \/*rect*\/)\n {\n \/\/nothing to do here: the renderer paints everything\n }\n\n void VideoRendererVMR9::notifyResize(const QRect &rect, Phonon::VideoWidget::AspectRatio aspectRatio,\n Phonon::VideoWidget::ScaleMode scaleMode)\n {\n ComPointer<IVideoWindow> video(m_filter, IID_IVideoWindow);\n\n OAHWND owner;\n HRESULT hr = video->get_Owner(&owner);\n if (FAILED(hr)) {\n return;\n }\n\n const OAHWND newOwner = reinterpret_cast<OAHWND>(m_target->winId());\n if (owner != newOwner) {\n video->put_Owner(newOwner);\n video->put_MessageDrain(newOwner);\n video->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);\n }\n\n \/\/make sure the widget takes the whole size of the parent\n video->SetWindowPosition(0, 0, rect.width(), rect.height());\n\n const QSize vsize = videoSize();\n internalNotifyResize(rect.size(), vsize, aspectRatio, scaleMode);\n\n ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);\n if (basic) {\n basic->SetDestinationPosition(m_dstX, m_dstY, m_dstWidth, m_dstHeight);\n }\n }\n\n void VideoRendererVMR9::applyMixerSettings(qreal \/*brightness*\/, qreal \/*contrast*\/, qreal \/*m_hue*\/, qreal \/*saturation*\/)\n {\n \/\/this can't be supported for WinCE\n }\n\n void VideoRendererVMR9::setActive(bool b)\n {\n if (b) {\n } else {\n ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);\n if (basic) {\n basic->SetDestinationPosition(0, 0, 0, 0);\n }\n }\n }\n\n QImage VideoRendererVMR9::snapshot() const\n {\n ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);\n if (basic) {\n LONG bufferSize = 0;\n \/\/1st we get the buffer size\n basic->GetCurrentImage(&bufferSize, 0);\n\n QByteArray buffer;\n buffer.resize(bufferSize);\n HRESULT hr = basic->GetCurrentImage(&bufferSize, reinterpret_cast<long*>(buffer.data()));\n\n if (SUCCEEDED(hr)) {\n\n const BITMAPINFOHEADER *bmi = reinterpret_cast<const BITMAPINFOHEADER*>(buffer.constData());\n\n const int w = bmi->biWidth,\n h = bmi->biHeight;\n\n \/\/ Create image and copy data into image.\n QImage ret(w, h, QImage::Format_RGB32);\n\n if (!ret.isNull()) {\n const char *data = buffer.constData() + bmi->biSize;\n const int bytes_per_line = w * sizeof(QRgb);\n for (int y = h - 1; y >= 0; --y) {\n qMemCopy(ret.scanLine(y), \/\/destination\n data, \/\/source\n bytes_per_line);\n data += bytes_per_line;\n }\n }\n return ret;\n }\n }\n return QImage();\n }\n\n#else\n VideoRendererVMR9::VideoRendererVMR9(QWidget *target) : m_target(target)\n {\n m_target->setAttribute(Qt::WA_PaintOnScreen, true);\n m_filter = Filter(CLSID_VideoMixingRenderer9, IID_IBaseFilter);\n if (!m_filter) {\n qWarning(\"the video widget could not be initialized correctly\");\n return;\n }\n\n ComPointer<IVMRFilterConfig9> config(m_filter, IID_IVMRFilterConfig9);\n Q_ASSERT(config);\n HRESULT hr = config->SetRenderingMode(VMR9Mode_Windowless);\n Q_ASSERT(SUCCEEDED(hr));\n hr = config->SetNumberOfStreams(1); \/\/for now we limit it to 1 input stream\n Q_ASSERT(SUCCEEDED(hr));\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n windowlessControl->SetVideoClippingWindow(reinterpret_cast<HWND>(target->winId()));\n }\n\n QImage VideoRendererVMR9::snapshot() const\n {\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n if (windowlessControl) {\n BYTE *buffer = 0;\n HRESULT hr = windowlessControl->GetCurrentImage(&buffer);\n if (SUCCEEDED(hr)) {\n\n const BITMAPINFOHEADER *bmi = reinterpret_cast<BITMAPINFOHEADER*>(buffer);\n\n\n const int w = bmi->biWidth,\n h = bmi->biHeight;\n\n \/\/ Create image and copy data into image.\n QImage ret(w, h, QImage::Format_RGB32);\n\n if (!ret.isNull()) {\n uchar *data = buffer + bmi->biSize;\n const int bytes_per_line = w * sizeof(QRgb);\n for (int y = h - 1; y >= 0; --y) {\n qMemCopy(ret.scanLine(y), \/\/destination\n data, \/\/source\n bytes_per_line);\n data += bytes_per_line;\n }\n }\n ::CoTaskMemFree(buffer);\n return ret;\n }\n }\n return QImage();\n }\n\n QSize VideoRendererVMR9::videoSize() const\n {\n LONG w = 0,\n h = 0;\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n if (windowlessControl) {\n windowlessControl->GetNativeVideoSize( &w, &h, 0, 0);\n }\n return QSize(w, h);\n }\n \n void VideoRendererVMR9::repaintCurrentFrame(QWidget *target, const QRect &)\n {\n HDC hDC = target->getDC();\n \/\/ repaint the video\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n\n HRESULT hr = windowlessControl ? windowlessControl->RepaintVideo(target->winId(), hDC) : E_POINTER;\n if (FAILED(hr) || m_dstY > 0 || m_dstX > 0) {\n const QColor c = target->palette().color(target->backgroundRole());\n COLORREF color = RGB(c.red(), c.green(), c.blue());\n HPEN hPen = ::CreatePen(PS_SOLID, 1, color);\n HBRUSH hBrush = ::CreateSolidBrush(color);\n ::SelectObject(hDC, hPen);\n ::SelectObject(hDC, hBrush);\n \/\/ repaint the video\n if (FAILED(hr)) {\n \/\/black background : we use the Win32 API to avoid the ghost effect of the backing store\n ::Rectangle(hDC, 0, 0, target->width(), target->height());\n } else {\n if (m_dstY > 0) {\n ::Rectangle(hDC, 0, 0, target->width(), m_dstY); \/\/top\n ::Rectangle(hDC, 0, target->height() - m_dstY, target->width(), target->height()); \/\/bottom\n }\n if (m_dstX > 0) {\n ::Rectangle(hDC, 0, m_dstY, m_dstX, m_dstHeight + m_dstY); \/\/left\n ::Rectangle(hDC, m_dstWidth + m_dstX, m_dstY, target->width(), m_dstHeight + m_dstY); \/\/right\n }\n }\n ::DeleteObject(hPen);\n ::DeleteObject(hBrush);\n }\n target->releaseDC(hDC);\n\n }\n\n void VideoRendererVMR9::notifyResize(const QRect &rect, Phonon::VideoWidget::AspectRatio aspectRatio,\n Phonon::VideoWidget::ScaleMode scaleMode)\n {\n const QSize vsize = videoSize();\n internalNotifyResize(rect.size(), vsize, aspectRatio, scaleMode);\n\n RECT dstRectWin = { m_dstX, m_dstY, m_dstWidth + m_dstX, m_dstHeight + m_dstY};\n RECT srcRectWin = { 0, 0, vsize.width(), vsize.height()};\n\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n if (windowlessControl) {\n windowlessControl->SetVideoPosition(&srcRectWin, &dstRectWin);\n }\n }\n\n void VideoRendererVMR9::setActive(bool b)\n {\n if (b) {\n } else {\n RECT dummyRect = { 0, 0, 0, 0};\n ComPointer<IVMRWindowlessControl9> windowlessControl(m_filter, IID_IVMRWindowlessControl9);\n windowlessControl->SetVideoPosition(&dummyRect, &dummyRect);\n }\n }\n\n\n void VideoRendererVMR9::applyMixerSettings(qreal brightness, qreal contrast, qreal hue, qreal saturation)\n {\n InputPin sink = BackendNode::pins(m_filter, PINDIR_INPUT).first();\n OutputPin source;\n if (FAILED(sink->ConnectedTo(source.pparam()))) {\n return; \/\/it must be connected to work\n }\n\n \/\/get the mixer (used for brightness\/contrast\/saturation\/hue)\n ComPointer<IVMRMixerControl9> mixer(m_filter, IID_IVMRMixerControl9);\n Q_ASSERT(mixer);\n\n VMR9ProcAmpControl ctrl;\n ctrl.dwSize = sizeof(ctrl);\n ctrl.dwFlags = ProcAmpControl9_Contrast | ProcAmpControl9_Brightness | ProcAmpControl9_Saturation | ProcAmpControl9_Hue;\n VMR9ProcAmpControlRange range;\n range.dwSize = sizeof(range);\n\n range.dwProperty = ProcAmpControl9_Contrast;\n HRESULT hr = mixer->GetProcAmpControlRange(0, &range);\n if (FAILED(hr)) {\n return;\n }\n ctrl.Contrast = ((contrast < 0 ? range.MinValue : range.MaxValue) - range.DefaultValue) * qAbs(contrast) + range.DefaultValue;\n\n \/\/brightness\n range.dwProperty = ProcAmpControl9_Brightness;\n hr = mixer->GetProcAmpControlRange(0, &range);\n if (FAILED(hr)) {\n return;\n }\n ctrl.Brightness = ((brightness < 0 ? range.MinValue : range.MaxValue) - range.DefaultValue) * qAbs(brightness) + range.DefaultValue;\n\n \/\/saturation\n range.dwProperty = ProcAmpControl9_Saturation;\n hr = mixer->GetProcAmpControlRange(0, &range);\n if (FAILED(hr)) {\n return;\n }\n ctrl.Saturation = ((saturation < 0 ? range.MinValue : range.MaxValue) - range.DefaultValue) * qAbs(saturation) + range.DefaultValue;\n\n \/\/hue\n range.dwProperty = ProcAmpControl9_Hue;\n hr = mixer->GetProcAmpControlRange(0, &range);\n if (FAILED(hr)) {\n return;\n }\n ctrl.Hue = ((hue < 0 ? range.MinValue : range.MaxValue) - range.DefaultValue) * qAbs(hue) + range.DefaultValue;\n\n \/\/finally set the settings\n mixer->SetProcAmpControl(0, &ctrl);\n }\n#endif\n }\n}\n\nQT_END_NAMESPACE\n\n#endif \/\/QT_NO_PHONON_VIDEO\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- StackProtector.cpp - Stack Protector Insertion --------------------===\/\/\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\/\/ This pass inserts stack protectors into functions which need them. A variable\n\/\/ with a random value in it is stored onto the stack before the local variables\n\/\/ are allocated. Upon exiting the block, the stored value is checked. If it's\n\/\/ changed, then there was some sort of violation and the program aborts.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"stack-protector\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Analysis\/Dominators.h\"\n#include \"llvm\/Attributes.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetLowering.h\"\nusing namespace llvm;\n\n\/\/ SSPBufferSize - The lower bound for a buffer to be considered for stack\n\/\/ smashing protection.\nstatic cl::opt<unsigned>\nSSPBufferSize(\"stack-protector-buffer-size\", cl::init(8),\n cl::desc(\"Lower bound for a buffer to be considered for \"\n \"stack protection\"));\n\nnamespace {\n class StackProtector : public FunctionPass {\n \/\/\/ TLI - Keep a pointer of a TargetLowering to consult for determining\n \/\/\/ target type sizes.\n const TargetLowering *TLI;\n\n Function *F;\n Module *M;\n\n DominatorTree* DT;\n\n \/\/\/ InsertStackProtectors - Insert code into the prologue and epilogue of\n \/\/\/ the function.\n \/\/\/\n \/\/\/ - The prologue code loads and stores the stack guard onto the stack.\n \/\/\/ - The epilogue checks the value stored in the prologue against the\n \/\/\/ original value. It calls __stack_chk_fail if they differ.\n bool InsertStackProtectors();\n\n \/\/\/ CreateFailBB - Create a basic block to jump to when the stack protector\n \/\/\/ check fails.\n BasicBlock *CreateFailBB();\n\n \/\/\/ RequiresStackProtector - Check whether or not this function needs a\n \/\/\/ stack protector based upon the stack protector level.\n bool RequiresStackProtector() const;\n public:\n static char ID; \/\/ Pass identification, replacement for typeid.\n StackProtector() : FunctionPass(ID), TLI(0) {\n initializeStackProtectorPass(*PassRegistry::getPassRegistry());\n }\n StackProtector(const TargetLowering *tli)\n : FunctionPass(ID), TLI(tli) {\n initializeStackProtectorPass(*PassRegistry::getPassRegistry());\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addPreserved<DominatorTree>();\n }\n\n virtual bool runOnFunction(Function &Fn);\n };\n} \/\/ end anonymous namespace\n\nchar StackProtector::ID = 0;\nINITIALIZE_PASS(StackProtector, \"stack-protector\",\n \"Insert stack protectors\", false, false)\n\nFunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {\n return new StackProtector(tli);\n}\n\nbool StackProtector::runOnFunction(Function &Fn) {\n F = &Fn;\n M = F->getParent();\n DT = getAnalysisIfAvailable<DominatorTree>();\n\n if (!RequiresStackProtector()) return false;\n \n return InsertStackProtectors();\n}\n\n\/\/\/ RequiresStackProtector - Check whether or not this function needs a stack\n\/\/\/ protector based upon the stack protector level. The heuristic we use is to\n\/\/\/ add a guard variable to functions that call alloca, and functions with\n\/\/\/ buffers larger than SSPBufferSize bytes.\nbool StackProtector::RequiresStackProtector() const {\n if (F->hasFnAttr(Attribute::StackProtectReq))\n return true;\n\n if (!F->hasFnAttr(Attribute::StackProtect))\n return false;\n\n const TargetData *TD = TLI->getTargetData();\n\n for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {\n BasicBlock *BB = I;\n\n for (BasicBlock::iterator\n II = BB->begin(), IE = BB->end(); II != IE; ++II)\n if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {\n if (AI->isArrayAllocation())\n \/\/ This is a call to alloca with a variable size. Emit stack\n \/\/ protectors.\n return true;\n\n if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) {\n \/\/ We apparently only care about character arrays.\n if (!AT->getElementType()->isIntegerTy(8))\n continue;\n\n \/\/ If an array has more than SSPBufferSize bytes of allocated space,\n \/\/ then we emit stack protectors.\n if (SSPBufferSize <= TD->getTypeAllocSize(AT))\n return true;\n }\n }\n }\n\n return false;\n}\n\n\/\/\/ InsertStackProtectors - Insert code into the prologue and epilogue of the\n\/\/\/ function.\n\/\/\/\n\/\/\/ - The prologue code loads and stores the stack guard onto the stack.\n\/\/\/ - The epilogue checks the value stored in the prologue against the original\n\/\/\/ value. It calls __stack_chk_fail if they differ.\nbool StackProtector::InsertStackProtectors() {\n BasicBlock *FailBB = 0; \/\/ The basic block to jump to if check fails.\n BasicBlock *FailBBDom = 0; \/\/ FailBB's dominator.\n AllocaInst *AI = 0; \/\/ Place on stack that stores the stack guard.\n Value *StackGuardVar = 0; \/\/ The stack guard variable.\n\n for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {\n BasicBlock *BB = I++;\n ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());\n if (!RI) continue;\n\n if (!FailBB) {\n \/\/ Insert code into the entry block that stores the __stack_chk_guard\n \/\/ variable onto the stack:\n \/\/\n \/\/ entry:\n \/\/ StackGuardSlot = alloca i8*\n \/\/ StackGuard = load __stack_chk_guard\n \/\/ call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)\n \/\/ \n const PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());\n unsigned AddressSpace, Offset;\n if (TLI->getStackCookieLocation(AddressSpace, Offset)) {\n Constant *OffsetVal =\n ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);\n \n StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,\n PointerType::get(PtrTy, AddressSpace));\n } else {\n StackGuardVar = M->getOrInsertGlobal(\"__stack_chk_guard\", PtrTy); \n }\n\n BasicBlock &Entry = F->getEntryBlock();\n Instruction *InsPt = &Entry.front();\n\n AI = new AllocaInst(PtrTy, \"StackGuardSlot\", InsPt);\n LoadInst *LI = new LoadInst(StackGuardVar, \"StackGuard\", false, InsPt);\n\n Value *Args[] = { LI, AI };\n CallInst::\n Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),\n &Args[0], array_endof(Args), \"\", InsPt);\n\n \/\/ Create the basic block to jump to when the guard check fails.\n FailBB = CreateFailBB();\n }\n\n \/\/ For each block with a return instruction, convert this:\n \/\/\n \/\/ return:\n \/\/ ...\n \/\/ ret ...\n \/\/\n \/\/ into this:\n \/\/\n \/\/ return:\n \/\/ ...\n \/\/ %1 = load __stack_chk_guard\n \/\/ %2 = load StackGuardSlot\n \/\/ %3 = cmp i1 %1, %2\n \/\/ br i1 %3, label %SP_return, label %CallStackCheckFailBlk\n \/\/\n \/\/ SP_return:\n \/\/ ret ...\n \/\/\n \/\/ CallStackCheckFailBlk:\n \/\/ call void @__stack_chk_fail()\n \/\/ unreachable\n\n \/\/ Split the basic block before the return instruction.\n bool BBIsReachable = (DT && DT->isReachableFromEntry(BB));\n BasicBlock *NewBB = BB->splitBasicBlock(RI, \"SP_return\");\n\n if (BBIsReachable) {\n DT->addNewBlock(NewBB, BB);\n FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;\n }\n\n \/\/ Remove default branch instruction to the new BB.\n BB->getTerminator()->eraseFromParent();\n\n \/\/ Move the newly created basic block to the point right after the old basic\n \/\/ block so that it's in the \"fall through\" position.\n NewBB->moveAfter(BB);\n\n \/\/ Generate the stack protector instructions in the old basic block.\n LoadInst *LI1 = new LoadInst(StackGuardVar, \"\", false, BB);\n LoadInst *LI2 = new LoadInst(AI, \"\", true, BB);\n ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, \"\");\n BranchInst::Create(NewBB, FailBB, Cmp, BB);\n }\n\n \/\/ Return if we didn't modify any basic blocks. I.e., there are no return\n \/\/ statements in the function.\n if (!FailBB) return false;\n\n if (DT && FailBBDom)\n DT->addNewBlock(FailBB, FailBBDom);\n\n return true;\n}\n\n\/\/\/ CreateFailBB - Create a basic block to jump to when the stack protector\n\/\/\/ check fails.\nBasicBlock *StackProtector::CreateFailBB() {\n BasicBlock *FailBB = BasicBlock::Create(F->getContext(),\n \"CallStackCheckFailBlk\", F);\n Constant *StackChkFail =\n M->getOrInsertFunction(\"__stack_chk_fail\",\n Type::getVoidTy(F->getContext()), NULL);\n CallInst::Create(StackChkFail, \"\", FailBB);\n new UnreachableInst(F->getContext(), FailBB);\n return FailBB;\n}\n<commit_msg>Inline check that's used only once.<commit_after>\/\/===-- StackProtector.cpp - Stack Protector Insertion --------------------===\/\/\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\/\/ This pass inserts stack protectors into functions which need them. A variable\n\/\/ with a random value in it is stored onto the stack before the local variables\n\/\/ are allocated. Upon exiting the block, the stored value is checked. If it's\n\/\/ changed, then there was some sort of violation and the program aborts.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"stack-protector\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Analysis\/Dominators.h\"\n#include \"llvm\/Attributes.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetLowering.h\"\nusing namespace llvm;\n\n\/\/ SSPBufferSize - The lower bound for a buffer to be considered for stack\n\/\/ smashing protection.\nstatic cl::opt<unsigned>\nSSPBufferSize(\"stack-protector-buffer-size\", cl::init(8),\n cl::desc(\"Lower bound for a buffer to be considered for \"\n \"stack protection\"));\n\nnamespace {\n class StackProtector : public FunctionPass {\n \/\/\/ TLI - Keep a pointer of a TargetLowering to consult for determining\n \/\/\/ target type sizes.\n const TargetLowering *TLI;\n\n Function *F;\n Module *M;\n\n DominatorTree* DT;\n\n \/\/\/ InsertStackProtectors - Insert code into the prologue and epilogue of\n \/\/\/ the function.\n \/\/\/\n \/\/\/ - The prologue code loads and stores the stack guard onto the stack.\n \/\/\/ - The epilogue checks the value stored in the prologue against the\n \/\/\/ original value. It calls __stack_chk_fail if they differ.\n bool InsertStackProtectors();\n\n \/\/\/ CreateFailBB - Create a basic block to jump to when the stack protector\n \/\/\/ check fails.\n BasicBlock *CreateFailBB();\n\n \/\/\/ RequiresStackProtector - Check whether or not this function needs a\n \/\/\/ stack protector based upon the stack protector level.\n bool RequiresStackProtector() const;\n public:\n static char ID; \/\/ Pass identification, replacement for typeid.\n StackProtector() : FunctionPass(ID), TLI(0) {\n initializeStackProtectorPass(*PassRegistry::getPassRegistry());\n }\n StackProtector(const TargetLowering *tli)\n : FunctionPass(ID), TLI(tli) {\n initializeStackProtectorPass(*PassRegistry::getPassRegistry());\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addPreserved<DominatorTree>();\n }\n\n virtual bool runOnFunction(Function &Fn);\n };\n} \/\/ end anonymous namespace\n\nchar StackProtector::ID = 0;\nINITIALIZE_PASS(StackProtector, \"stack-protector\",\n \"Insert stack protectors\", false, false)\n\nFunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {\n return new StackProtector(tli);\n}\n\nbool StackProtector::runOnFunction(Function &Fn) {\n F = &Fn;\n M = F->getParent();\n DT = getAnalysisIfAvailable<DominatorTree>();\n\n if (!RequiresStackProtector()) return false;\n \n return InsertStackProtectors();\n}\n\n\/\/\/ RequiresStackProtector - Check whether or not this function needs a stack\n\/\/\/ protector based upon the stack protector level. The heuristic we use is to\n\/\/\/ add a guard variable to functions that call alloca, and functions with\n\/\/\/ buffers larger than SSPBufferSize bytes.\nbool StackProtector::RequiresStackProtector() const {\n if (F->hasFnAttr(Attribute::StackProtectReq))\n return true;\n\n if (!F->hasFnAttr(Attribute::StackProtect))\n return false;\n\n const TargetData *TD = TLI->getTargetData();\n\n for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {\n BasicBlock *BB = I;\n\n for (BasicBlock::iterator\n II = BB->begin(), IE = BB->end(); II != IE; ++II)\n if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {\n if (AI->isArrayAllocation())\n \/\/ This is a call to alloca with a variable size. Emit stack\n \/\/ protectors.\n return true;\n\n if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) {\n \/\/ We apparently only care about character arrays.\n if (!AT->getElementType()->isIntegerTy(8))\n continue;\n\n \/\/ If an array has more than SSPBufferSize bytes of allocated space,\n \/\/ then we emit stack protectors.\n if (SSPBufferSize <= TD->getTypeAllocSize(AT))\n return true;\n }\n }\n }\n\n return false;\n}\n\n\/\/\/ InsertStackProtectors - Insert code into the prologue and epilogue of the\n\/\/\/ function.\n\/\/\/\n\/\/\/ - The prologue code loads and stores the stack guard onto the stack.\n\/\/\/ - The epilogue checks the value stored in the prologue against the original\n\/\/\/ value. It calls __stack_chk_fail if they differ.\nbool StackProtector::InsertStackProtectors() {\n BasicBlock *FailBB = 0; \/\/ The basic block to jump to if check fails.\n BasicBlock *FailBBDom = 0; \/\/ FailBB's dominator.\n AllocaInst *AI = 0; \/\/ Place on stack that stores the stack guard.\n Value *StackGuardVar = 0; \/\/ The stack guard variable.\n\n for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {\n BasicBlock *BB = I++;\n ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());\n if (!RI) continue;\n\n if (!FailBB) {\n \/\/ Insert code into the entry block that stores the __stack_chk_guard\n \/\/ variable onto the stack:\n \/\/\n \/\/ entry:\n \/\/ StackGuardSlot = alloca i8*\n \/\/ StackGuard = load __stack_chk_guard\n \/\/ call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)\n \/\/ \n const PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());\n unsigned AddressSpace, Offset;\n if (TLI->getStackCookieLocation(AddressSpace, Offset)) {\n Constant *OffsetVal =\n ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);\n \n StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,\n PointerType::get(PtrTy, AddressSpace));\n } else {\n StackGuardVar = M->getOrInsertGlobal(\"__stack_chk_guard\", PtrTy); \n }\n\n BasicBlock &Entry = F->getEntryBlock();\n Instruction *InsPt = &Entry.front();\n\n AI = new AllocaInst(PtrTy, \"StackGuardSlot\", InsPt);\n LoadInst *LI = new LoadInst(StackGuardVar, \"StackGuard\", false, InsPt);\n\n Value *Args[] = { LI, AI };\n CallInst::\n Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),\n &Args[0], array_endof(Args), \"\", InsPt);\n\n \/\/ Create the basic block to jump to when the guard check fails.\n FailBB = CreateFailBB();\n }\n\n \/\/ For each block with a return instruction, convert this:\n \/\/\n \/\/ return:\n \/\/ ...\n \/\/ ret ...\n \/\/\n \/\/ into this:\n \/\/\n \/\/ return:\n \/\/ ...\n \/\/ %1 = load __stack_chk_guard\n \/\/ %2 = load StackGuardSlot\n \/\/ %3 = cmp i1 %1, %2\n \/\/ br i1 %3, label %SP_return, label %CallStackCheckFailBlk\n \/\/\n \/\/ SP_return:\n \/\/ ret ...\n \/\/\n \/\/ CallStackCheckFailBlk:\n \/\/ call void @__stack_chk_fail()\n \/\/ unreachable\n\n \/\/ Split the basic block before the return instruction.\n BasicBlock *NewBB = BB->splitBasicBlock(RI, \"SP_return\");\n\n if (DT && DT->isReachableFromEntry(BB)) {\n DT->addNewBlock(NewBB, BB);\n FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;\n }\n\n \/\/ Remove default branch instruction to the new BB.\n BB->getTerminator()->eraseFromParent();\n\n \/\/ Move the newly created basic block to the point right after the old basic\n \/\/ block so that it's in the \"fall through\" position.\n NewBB->moveAfter(BB);\n\n \/\/ Generate the stack protector instructions in the old basic block.\n LoadInst *LI1 = new LoadInst(StackGuardVar, \"\", false, BB);\n LoadInst *LI2 = new LoadInst(AI, \"\", true, BB);\n ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, \"\");\n BranchInst::Create(NewBB, FailBB, Cmp, BB);\n }\n\n \/\/ Return if we didn't modify any basic blocks. I.e., there are no return\n \/\/ statements in the function.\n if (!FailBB) return false;\n\n if (DT && FailBBDom)\n DT->addNewBlock(FailBB, FailBBDom);\n\n return true;\n}\n\n\/\/\/ CreateFailBB - Create a basic block to jump to when the stack protector\n\/\/\/ check fails.\nBasicBlock *StackProtector::CreateFailBB() {\n BasicBlock *FailBB = BasicBlock::Create(F->getContext(),\n \"CallStackCheckFailBlk\", F);\n Constant *StackChkFail =\n M->getOrInsertFunction(\"__stack_chk_fail\",\n Type::getVoidTy(F->getContext()), NULL);\n CallInst::Create(StackChkFail, \"\", FailBB);\n new UnreachableInst(F->getContext(), FailBB);\n return FailBB;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* vim:set ts=4 sw=4 sts=4 et: *\/\n\n#include <memory>\n#include <sstream>\n#include <igraph\/cpp\/graph.h>\n#include <igraph\/cpp\/edge.h>\n#include <igraph\/cpp\/vertex.h>\n#include <igraph\/cpp\/vertex_selector.h>\n#include <igraph\/cpp\/generators\/degree_sequence.h>\n#include <igraph\/cpp\/generators\/erdos_renyi.h>\n#include <netctrl\/model.h>\n\n#include \"cmd_arguments.h\"\n#include \"graph_util.h\"\n#include \"logging.h\"\n\nusing namespace igraph;\nusing namespace netctrl;\n\n\n\/\/\/ Helper function to split a string around a delimiter character\nstd::vector<std::string> &split(const std::string& s, char delim,\n std::vector<std::string>& elems) {\n std::stringstream ss(s);\n std::string item;\n while (std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n}\n\n\/\/\/ Helper function to split a string around a delimiter character\nstd::vector<std::string> split(const std::string& s, char delim) {\n std::vector<std::string> elems;\n return split(s, delim, elems);\n}\n\nclass NetworkControllabilityApp {\nprivate:\n \/\/\/ Parsed command line arguments\n CommandLineArguments m_args;\n\n \/\/\/ Graph being analyzed by the UI\n std::auto_ptr<Graph> m_pGraph;\n\n \/\/\/ Controllability model being calculated on the graph\n std::auto_ptr<ControllabilityModel> m_pModel;\n\npublic:\n LOGGING_FUNCTION(debug, 2);\n LOGGING_FUNCTION(info, 1);\n LOGGING_FUNCTION(error, 0);\n\n \/\/\/ Constructor\n NetworkControllabilityApp() : m_pGraph(0), m_pModel(0) {}\n\n \/\/\/ Returns whether we are running in quiet mode\n bool isQuiet() {\n return m_args.verbosity < 1;\n }\n\n \/\/\/ Returns whether we are running in verbose mode\n bool isVerbose() {\n return m_args.verbosity > 1;\n }\n\n \/\/\/ Loads a graph from the given file\n \/**\n * If the name of the file is \"-\", the file is assumed to be the\n * standard input.\n *\/\n std::auto_ptr<Graph> loadGraph(const std::string& filename, GraphFormat format) {\n std::auto_ptr<Graph> result;\n\n if (filename == \"-\") {\n \/\/ Loading graph from standard input\n if (format == GRAPH_FORMAT_AUTO)\n format = GRAPH_FORMAT_EDGELIST;\n result.reset(new Graph(GraphUtil::readGraph(stdin, format)));\n } else if (filename.find(\":\/\/\") != filename.npos) {\n \/\/ Generating graph from model\n size_t pos = filename.find(\":\/\/\");\n std::string model = filename.substr(0, pos);\n std::vector<std::string> params = split(filename.substr(pos+3), ',');\n\n if (model == \"er\") {\n \/\/ Erdos-Renyi network\n if (params.size() < 2) {\n error(\"ER generator requires two or three arguments: number of nodes, \"\n \"average degree and directedness (optional)\");\n return result; \/\/ points to null\n }\n\n long int n = atoi(params[0].c_str());\n float k = atof(params[1].c_str());\n bool directed = true;\n if (params.size() >= 3) {\n directed = atoi(params[2].c_str()) != 0;\n }\n return erdos_renyi_game_gnm(n, directed ? n*k : n*k\/2.0,\n directed, false);\n } else {\n error(\"Unknown graph generator: %s\", model.c_str());\n return result; \/\/ points to null\n }\n } else {\n \/\/ Loading graph from file\n result.reset(new Graph(GraphUtil::readGraph(filename, format)));\n result->setAttribute(\"filename\", filename);\n }\n\n return result;\n }\n\n \/\/\/ Runs the user interface\n int run(int argc, char** argv) {\n m_args.parse(argc, argv);\n\n info(\">> loading graph: %s\", m_args.inputFile.c_str());\n m_pGraph = loadGraph(m_args.inputFile, m_args.inputFormat);\n if (m_pGraph.get() == NULL)\n return 2;\n\n info(\">> graph is %s and has %ld vertices and %ld edges\",\n m_pGraph->isDirected() ? \"directed\" : \"undirected\",\n (long)m_pGraph->vcount(), (long)m_pGraph->ecount());\n\n switch (m_args.modelType) {\n case LIU_MODEL:\n m_pModel.reset(new LiuControllabilityModel(m_pGraph.get()));\n break;\n case SWITCHBOARD_MODEL:\n {\n SwitchboardControllabilityModel* sbdModel;\n sbdModel = new SwitchboardControllabilityModel(m_pGraph.get());\n sbdModel->setControllabilityMeasure(\n m_args.useEdgeMeasure ?\n SwitchboardControllabilityModel::EDGE_MEASURE :\n SwitchboardControllabilityModel::NODE_MEASURE\n );\n m_pModel.reset(sbdModel);\n }\n break;\n }\n\n switch (m_args.operationMode) {\n case MODE_CONTROL_PATHS:\n return runControlPaths();\n\n case MODE_DRIVER_NODES:\n return runDriverNodes();\n\n case MODE_GRAPH:\n return runGraph();\n\n case MODE_STATISTICS:\n return runStatistics();\n\n case MODE_SIGNIFICANCE:\n return runSignificance();\n\n default:\n return 1;\n }\n }\n\n \/\/\/ Runs the control path calculation mode\n int runControlPaths() {\n info(\">> calculating control paths\");\n m_pModel->calculate();\n\n std::vector<ControlPath*> paths = m_pModel->controlPaths();\n info(\">> found %d control path(s)\", paths.size());\n for (std::vector<ControlPath*>::const_iterator it = paths.begin();\n it != paths.end(); it++) {\n std::cout << (*it)->toString() << '\\n';\n }\n\n return 0;\n }\n\n \/\/\/ Runs the driver node calculation mode\n int runDriverNodes() {\n info(\">> calculating control paths and driver nodes\");\n m_pModel->calculate();\n\n Vector driver_nodes = m_pModel->driverNodes();\n info(\">> found %d driver node(s)\", driver_nodes.size());\n for (Vector::const_iterator it = driver_nodes.begin(); it != driver_nodes.end(); it++) {\n any name(m_pGraph->vertex(*it).getAttribute(\"name\", (long int)*it));\n if (name.type() == typeid(std::string)) {\n std::cout << name.as<std::string>() << '\\n';\n } else {\n std::cout << name.as<long int>() << '\\n';\n }\n }\n\n return 0;\n }\n\n \/\/\/ Runs the annotated graph output mode\n int runGraph() {\n long int i, j, n;\n\n info(\">> calculating control paths and driver nodes\");\n m_pModel->calculate();\n\n Vector driver_nodes = m_pModel->driverNodes();\n std::vector<ControlPath*> paths = m_pModel->controlPaths();\n info(\">> found %d driver node(s) and %d control path(s)\",\n driver_nodes.size(), paths.size());\n\n info(\">> classifying edges\");\n std::vector<EdgeClass> edge_classes = m_pModel->edgeClasses();\n\n \/\/ Mark the driver nodes\n for (Vector::const_iterator it = driver_nodes.begin(); it != driver_nodes.end(); it++) {\n m_pGraph->vertex(*it).setAttribute(\"is_driver\", true);\n }\n\n \/\/ Mark the edge types and path indices\n j = 0;\n for (std::vector<ControlPath*>::const_iterator it = paths.begin();\n it != paths.end(); it++, j++) {\n const igraph::Vector& vec = (*it)->edges(*m_pGraph.get());\n n = vec.size();\n for (i = 0; i < n; i++) {\n igraph::Edge edge = m_pGraph->edge(vec[i]);\n edge.setAttribute(\"path_type\", (*it)->name());\n edge.setAttribute(\"path_indices\", j);\n edge.setAttribute(\"path_order\", i);\n }\n }\n\n \/\/ Mark the edge classes\n n = m_pGraph->ecount();\n for (i = 0; i < n; i++) {\n igraph::Edge edge = m_pGraph->edge(i);\n edge.setAttribute(\"edge_class\", edgeClassToString(edge_classes[i]));\n }\n\n \/\/ Print the graph\n GraphUtil::writeGraph(stdout, (*m_pGraph.get()), m_args.outputFormat);\n return 0;\n }\n\n \/\/\/ Runs the signficance calculation mode\n int runSignificance() {\n size_t observedDriverNodeCount;\n size_t numTrials = 100, i;\n float numNodes = m_pGraph->vcount();\n float controllability;\n Vector counts;\n \n info(\">> calculating control paths and driver nodes\");\n m_pModel->calculate();\n\n observedDriverNodeCount = m_pModel->driverNodes().size();\n controllability = m_pModel->controllability();\n\n info(\">> found %d driver node(s)\", observedDriverNodeCount);\n std::cout << \"Observed\\t\" << controllability << '\\n';\n\n \/\/ Testing Erdos-Renyi null model\n info(\">> testing Erdos-Renyi null model\");\n counts.clear();\n for (i = 0; i < numTrials; i++) {\n std::auto_ptr<Graph> graph = igraph::erdos_renyi_game_gnm(\n numNodes, m_pGraph->ecount(),\n m_pGraph->isDirected(), false);\n\n std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());\n pModel->setGraph(graph.get());\n pModel->calculate();\n\n counts.push_back(pModel->controllability());\n }\n counts.sort();\n std::cout << \"ER\\t\" << counts.sum() \/ counts.size() << '\\n';\n\n \/\/ Testing configuration model\n Vector inDegrees, outDegrees;\n m_pGraph->degree(&outDegrees, V(m_pGraph.get()), IGRAPH_OUT, true);\n m_pGraph->degree(&inDegrees, V(m_pGraph.get()), IGRAPH_IN, true);\n\n info(\">> testing configuration model (preserving joint degree distribution)\");\n counts.clear();\n for (i = 0; i < numTrials; i++) {\n std::auto_ptr<Graph> graph =\n igraph::degree_sequence_game(outDegrees, inDegrees,\n IGRAPH_DEGSEQ_SIMPLE);\n\n std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());\n pModel->setGraph(graph.get());\n pModel->calculate();\n\n counts.push_back(pModel->controllability());\n }\n counts.sort();\n std::cout << \"Configuration\\t\" << counts.sum() \/ counts.size() << '\\n';\n\n \/\/ Testing configuration model\n info(\">> testing configuration model (destroying joint degree distribution)\");\n counts.clear();\n for (i = 0; i < numTrials; i++) {\n inDegrees.shuffle();\n outDegrees.shuffle();\n\n std::auto_ptr<Graph> graph =\n igraph::degree_sequence_game(outDegrees, inDegrees,\n IGRAPH_DEGSEQ_SIMPLE);\n\n std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());\n pModel->setGraph(graph.get());\n pModel->calculate();\n\n counts.push_back(pModel->controllability());\n }\n counts.sort();\n std::cout << \"Configuration_no_joint\\t\" << counts.sum() \/ counts.size() << '\\n';\n\n return 0;\n }\n\n \/\/\/ Runs the general statistics calculation mode\n int runStatistics() {\n float n = m_pGraph->vcount();\n float m = m_pGraph->ecount();\n long int num_driver;\n long int num_redundant = 0, num_ordinary = 0, num_critical = 0, num_distinguished = 0;\n\n info(\">> calculating control paths and driver nodes\");\n m_pModel->calculate();\n num_driver = m_pModel->driverNodes().size();\n\n info(\">> classifying edges\");\n std::vector<EdgeClass> edge_classes = m_pModel->edgeClasses();\n if (edge_classes.size() == m && !edge_classes.empty()) {\n for (long int i = 0; i < m; i++) {\n if (edge_classes[i] == EDGE_REDUNDANT)\n num_redundant++;\n else if (edge_classes[i] == EDGE_ORDINARY)\n num_ordinary++;\n else if (edge_classes[i] == EDGE_DISTINGUISHED)\n num_distinguished++;\n else\n num_critical++;\n }\n }\n\n info(\">> order is as follows:\");\n info(\">> driver nodes; distinguished, redundant, ordinary, critical edges\");\n\n std::cout << num_driver << ' '\n << num_distinguished << ' '\n << num_redundant << ' '\n << num_ordinary << ' '\n << num_critical << '\\n';\n std::cout << num_driver \/ n << ' '\n << num_distinguished \/ m << ' '\n << num_redundant \/ m << ' '\n << num_ordinary \/ m << ' '\n << num_critical \/ m << '\\n';\n\n return 0;\n }\n\n};\n\nint main(int argc, char** argv) {\n NetworkControllabilityApp app;\n\n igraph::AttributeHandler::attach();\n return app.run(argc, argv);\n}\n\n<commit_msg>added proper handling of \"-o\" option<commit_after>\/* vim:set ts=4 sw=4 sts=4 et: *\/\n\n#include <cstdio>\n#include <fstream>\n#include <memory>\n#include <sstream>\n#include <igraph\/cpp\/graph.h>\n#include <igraph\/cpp\/edge.h>\n#include <igraph\/cpp\/vertex.h>\n#include <igraph\/cpp\/vertex_selector.h>\n#include <igraph\/cpp\/generators\/degree_sequence.h>\n#include <igraph\/cpp\/generators\/erdos_renyi.h>\n#include <netctrl\/model.h>\n\n#include \"cmd_arguments.h\"\n#include \"graph_util.h\"\n#include \"logging.h\"\n\nusing namespace igraph;\nusing namespace netctrl;\n\n\n\/\/\/ Helper function to split a string around a delimiter character\nstd::vector<std::string> &split(const std::string& s, char delim,\n std::vector<std::string>& elems) {\n std::stringstream ss(s);\n std::string item;\n while (std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n}\n\n\/\/\/ Helper function to split a string around a delimiter character\nstd::vector<std::string> split(const std::string& s, char delim) {\n std::vector<std::string> elems;\n return split(s, delim, elems);\n}\n\nclass NetworkControllabilityApp {\nprivate:\n \/\/\/ Parsed command line arguments\n CommandLineArguments m_args;\n\n \/\/\/ The C-style output file object where the results will be written\n FILE* m_outputFileObject;\n\n \/\/\/ Graph being analyzed by the UI\n std::auto_ptr<Graph> m_pGraph;\n\n \/\/\/ Controllability model being calculated on the graph\n std::auto_ptr<ControllabilityModel> m_pModel;\n\n \/\/\/ The C++-style output stream where the results will be written\n std::ostream* m_pOutputStream;\n\npublic:\n LOGGING_FUNCTION(debug, 2);\n LOGGING_FUNCTION(info, 1);\n LOGGING_FUNCTION(error, 0);\n\n \/\/\/ Constructor\n NetworkControllabilityApp() : m_outputFileObject(0),\n m_pGraph(0), m_pModel(0), m_pOutputStream(0) {}\n\n \/\/\/ Destructor\n ~NetworkControllabilityApp() {\n if (m_outputFileObject != 0 && m_outputFileObject != stdout) {\n fclose(m_outputFileObject);\n }\n\n if (m_pOutputStream != 0 && m_pOutputStream != &std::cout) {\n delete m_pOutputStream;\n }\n }\n\n \/\/\/ Returns the C-style output file object where the results should be written\n FILE* getOutputFileObject() {\n if (m_outputFileObject == 0) {\n if (isWritingToStandardOutput()) {\n m_outputFileObject = stdout;\n } else {\n m_outputFileObject = fopen(m_args.outputFile.c_str(), \"w\");\n if (m_outputFileObject == 0) {\n error(\"cannot open output file for writing: %s\",\n m_args.outputFile.c_str());\n exit(3);\n }\n }\n }\n return m_outputFileObject;\n }\n\n \/\/\/ Returns the C++-style output stream where the results should be written\n std::ostream& getOutputStream() {\n if (m_pOutputStream == 0) {\n if (isWritingToStandardOutput()) {\n m_pOutputStream = &std::cout;\n } else {\n m_pOutputStream = new std::ofstream(m_args.outputFile.c_str());\n if (m_pOutputStream->fail()) {\n error(\"cannot open output file for writing: %s\",\n m_args.outputFile.c_str());\n exit(3);\n }\n }\n }\n return *m_pOutputStream;\n }\n\n \/\/\/ Returns whether we are writing to the standard output\n bool isWritingToStandardOutput() {\n return m_args.outputFile.empty() || m_args.outputFile == \"-\";\n }\n\n \/\/\/ Returns whether we are running in quiet mode\n bool isQuiet() {\n return m_args.verbosity < 1;\n }\n\n \/\/\/ Returns whether we are running in verbose mode\n bool isVerbose() {\n return m_args.verbosity > 1;\n }\n\n \/\/\/ Loads a graph from the given file\n \/**\n * If the name of the file is \"-\", the file is assumed to be the\n * standard input.\n *\/\n std::auto_ptr<Graph> loadGraph(const std::string& filename, GraphFormat format) {\n std::auto_ptr<Graph> result;\n\n if (filename == \"-\") {\n \/\/ Loading graph from standard input\n if (format == GRAPH_FORMAT_AUTO)\n format = GRAPH_FORMAT_EDGELIST;\n result.reset(new Graph(GraphUtil::readGraph(stdin, format)));\n } else if (filename.find(\":\/\/\") != filename.npos) {\n \/\/ Generating graph from model\n size_t pos = filename.find(\":\/\/\");\n std::string model = filename.substr(0, pos);\n std::vector<std::string> params = split(filename.substr(pos+3), ',');\n\n if (model == \"er\") {\n \/\/ Erdos-Renyi network\n if (params.size() < 2) {\n error(\"ER generator requires two or three arguments: number of nodes, \"\n \"average degree and directedness (optional)\");\n return result; \/\/ points to null\n }\n\n long int n = atoi(params[0].c_str());\n float k = atof(params[1].c_str());\n bool directed = true;\n if (params.size() >= 3) {\n directed = atoi(params[2].c_str()) != 0;\n }\n return erdos_renyi_game_gnm(n, directed ? n*k : n*k\/2.0,\n directed, false);\n } else {\n error(\"Unknown graph generator: %s\", model.c_str());\n return result; \/\/ points to null\n }\n } else {\n \/\/ Loading graph from file\n result.reset(new Graph(GraphUtil::readGraph(filename, format)));\n result->setAttribute(\"filename\", filename);\n }\n\n return result;\n }\n\n \/\/\/ Runs the user interface\n int run(int argc, char** argv) {\n int retval;\n\n m_args.parse(argc, argv);\n\n info(\">> loading graph: %s\", m_args.inputFile.c_str());\n m_pGraph = loadGraph(m_args.inputFile, m_args.inputFormat);\n if (m_pGraph.get() == NULL)\n return 2;\n\n info(\">> graph is %s and has %ld vertices and %ld edges\",\n m_pGraph->isDirected() ? \"directed\" : \"undirected\",\n (long)m_pGraph->vcount(), (long)m_pGraph->ecount());\n\n switch (m_args.modelType) {\n case LIU_MODEL:\n m_pModel.reset(new LiuControllabilityModel(m_pGraph.get()));\n break;\n case SWITCHBOARD_MODEL:\n {\n SwitchboardControllabilityModel* sbdModel;\n sbdModel = new SwitchboardControllabilityModel(m_pGraph.get());\n sbdModel->setControllabilityMeasure(\n m_args.useEdgeMeasure ?\n SwitchboardControllabilityModel::EDGE_MEASURE :\n SwitchboardControllabilityModel::NODE_MEASURE\n );\n m_pModel.reset(sbdModel);\n }\n break;\n }\n\n switch (m_args.operationMode) {\n case MODE_CONTROL_PATHS:\n retval = runControlPaths();\n break;\n\n case MODE_DRIVER_NODES:\n retval = runDriverNodes();\n break;\n\n case MODE_GRAPH:\n retval = runGraph();\n break;\n\n case MODE_STATISTICS:\n retval = runStatistics();\n break;\n\n case MODE_SIGNIFICANCE:\n retval = runSignificance();\n break;\n\n default:\n retval = 1;\n }\n\n if (!retval && !isWritingToStandardOutput()) {\n info(\">> results were written to %s\", m_args.outputFile.c_str());\n }\n\n return retval;\n }\n\n \/\/\/ Runs the control path calculation mode\n int runControlPaths() {\n info(\">> calculating control paths\");\n m_pModel->calculate();\n\n std::vector<ControlPath*> paths = m_pModel->controlPaths();\n std::ostream& out = getOutputStream();\n\n info(\">> found %d control path(s)\", paths.size());\n for (std::vector<ControlPath*>::const_iterator it = paths.begin();\n it != paths.end(); it++) {\n out << (*it)->toString() << '\\n';\n }\n\n return 0;\n }\n\n \/\/\/ Runs the driver node calculation mode\n int runDriverNodes() {\n info(\">> calculating control paths and driver nodes\");\n m_pModel->calculate();\n\n Vector driver_nodes = m_pModel->driverNodes();\n std::ostream& out = getOutputStream();\n\n info(\">> found %d driver node(s)\", driver_nodes.size());\n for (Vector::const_iterator it = driver_nodes.begin(); it != driver_nodes.end(); it++) {\n any name(m_pGraph->vertex(*it).getAttribute(\"name\", (long int)*it));\n if (name.type() == typeid(std::string)) {\n out << name.as<std::string>() << '\\n';\n } else {\n out << name.as<long int>() << '\\n';\n }\n }\n\n return 0;\n }\n\n \/\/\/ Runs the annotated graph output mode\n int runGraph() {\n long int i, j, n;\n\n info(\">> calculating control paths and driver nodes\");\n m_pModel->calculate();\n\n Vector driver_nodes = m_pModel->driverNodes();\n std::vector<ControlPath*> paths = m_pModel->controlPaths();\n info(\">> found %d driver node(s) and %d control path(s)\",\n driver_nodes.size(), paths.size());\n\n info(\">> classifying edges\");\n std::vector<EdgeClass> edge_classes = m_pModel->edgeClasses();\n\n \/\/ Mark the driver nodes\n for (Vector::const_iterator it = driver_nodes.begin(); it != driver_nodes.end(); it++) {\n m_pGraph->vertex(*it).setAttribute(\"is_driver\", true);\n }\n\n \/\/ Mark the edge types and path indices\n j = 0;\n for (std::vector<ControlPath*>::const_iterator it = paths.begin();\n it != paths.end(); it++, j++) {\n const igraph::Vector& vec = (*it)->edges(*m_pGraph.get());\n n = vec.size();\n for (i = 0; i < n; i++) {\n igraph::Edge edge = m_pGraph->edge(vec[i]);\n edge.setAttribute(\"path_type\", (*it)->name());\n edge.setAttribute(\"path_indices\", j);\n edge.setAttribute(\"path_order\", i);\n }\n }\n\n \/\/ Mark the edge classes\n n = m_pGraph->ecount();\n for (i = 0; i < n; i++) {\n igraph::Edge edge = m_pGraph->edge(i);\n edge.setAttribute(\"edge_class\", edgeClassToString(edge_classes[i]));\n }\n\n \/\/ Print the graph\n GraphUtil::writeGraph(getOutputFileObject(), (*m_pGraph.get()), m_args.outputFormat);\n\n return 0;\n }\n\n \/\/\/ Runs the signficance calculation mode\n int runSignificance() {\n size_t observedDriverNodeCount;\n size_t numTrials = 100, i;\n float numNodes = m_pGraph->vcount();\n float controllability;\n Vector counts;\n std::ostream& out = getOutputStream();\n \n info(\">> calculating control paths and driver nodes\");\n m_pModel->calculate();\n\n observedDriverNodeCount = m_pModel->driverNodes().size();\n controllability = m_pModel->controllability();\n\n info(\">> found %d driver node(s)\", observedDriverNodeCount);\n out << \"Observed\\t\" << controllability << '\\n';\n\n \/\/ Testing Erdos-Renyi null model\n info(\">> testing Erdos-Renyi null model\");\n counts.clear();\n for (i = 0; i < numTrials; i++) {\n std::auto_ptr<Graph> graph = igraph::erdos_renyi_game_gnm(\n numNodes, m_pGraph->ecount(),\n m_pGraph->isDirected(), false);\n\n std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());\n pModel->setGraph(graph.get());\n pModel->calculate();\n\n counts.push_back(pModel->controllability());\n }\n counts.sort();\n out << \"ER\\t\" << counts.sum() \/ counts.size() << '\\n';\n\n \/\/ Testing configuration model\n Vector inDegrees, outDegrees;\n m_pGraph->degree(&outDegrees, V(m_pGraph.get()), IGRAPH_OUT, true);\n m_pGraph->degree(&inDegrees, V(m_pGraph.get()), IGRAPH_IN, true);\n\n info(\">> testing configuration model (preserving joint degree distribution)\");\n counts.clear();\n for (i = 0; i < numTrials; i++) {\n std::auto_ptr<Graph> graph =\n igraph::degree_sequence_game(outDegrees, inDegrees,\n IGRAPH_DEGSEQ_SIMPLE);\n\n std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());\n pModel->setGraph(graph.get());\n pModel->calculate();\n\n counts.push_back(pModel->controllability());\n }\n counts.sort();\n out << \"Configuration\\t\" << counts.sum() \/ counts.size() << '\\n';\n\n \/\/ Testing configuration model\n info(\">> testing configuration model (destroying joint degree distribution)\");\n counts.clear();\n for (i = 0; i < numTrials; i++) {\n inDegrees.shuffle();\n outDegrees.shuffle();\n\n std::auto_ptr<Graph> graph =\n igraph::degree_sequence_game(outDegrees, inDegrees,\n IGRAPH_DEGSEQ_SIMPLE);\n\n std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());\n pModel->setGraph(graph.get());\n pModel->calculate();\n\n counts.push_back(pModel->controllability());\n }\n counts.sort();\n out << \"Configuration_no_joint\\t\" << counts.sum() \/ counts.size() << '\\n';\n\n return 0;\n }\n\n \/\/\/ Runs the general statistics calculation mode\n int runStatistics() {\n float n = m_pGraph->vcount();\n float m = m_pGraph->ecount();\n long int num_driver;\n long int num_redundant = 0, num_ordinary = 0, num_critical = 0, num_distinguished = 0;\n std::ostream& out = getOutputStream();\n \n info(\">> calculating control paths and driver nodes\");\n m_pModel->calculate();\n num_driver = m_pModel->driverNodes().size();\n\n info(\">> classifying edges\");\n std::vector<EdgeClass> edge_classes = m_pModel->edgeClasses();\n if (edge_classes.size() == m && !edge_classes.empty()) {\n for (long int i = 0; i < m; i++) {\n if (edge_classes[i] == EDGE_REDUNDANT)\n num_redundant++;\n else if (edge_classes[i] == EDGE_ORDINARY)\n num_ordinary++;\n else if (edge_classes[i] == EDGE_DISTINGUISHED)\n num_distinguished++;\n else\n num_critical++;\n }\n }\n\n info(\">> order is as follows:\");\n info(\">> driver nodes; distinguished, redundant, ordinary, critical edges\");\n\n out << num_driver << ' '\n << num_distinguished << ' '\n << num_redundant << ' '\n << num_ordinary << ' '\n << num_critical << '\\n';\n out << num_driver \/ n << ' '\n << num_distinguished \/ m << ' '\n << num_redundant \/ m << ' '\n << num_ordinary \/ m << ' '\n << num_critical \/ m << '\\n';\n\n return 0;\n }\n\n};\n\nint main(int argc, char** argv) {\n NetworkControllabilityApp app;\n\n igraph::AttributeHandler::attach();\n return app.run(argc, argv);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ M113 suspension subsystem.\n\/\/\n\/\/ =============================================================================\n\n#include \"chrono_models\/vehicle\/m113a\/M113a_RoadWheel.h\"\n#include \"chrono_models\/vehicle\/m113a\/M113a_Suspension.h\"\n\nnamespace chrono {\nnamespace vehicle {\nnamespace m113 {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Static variables\n\/\/ -----------------------------------------------------------------------------\nconst double M113a_Suspension::m_arm_mass = 16.513;\nconst ChVector<> M113a_Suspension::m_arm_inertia(3.8, 0.08, 3.8);\nconst double M113a_Suspension::m_arm_radius = 0.019;\n\nconst double M113a_Suspension::m_torsion_a0 = 0;\nconst double M113a_Suspension::m_torsion_k = 9557;\nconst double M113a_Suspension::m_torsion_c = 191;\nconst double M113a_Suspension::m_torsion_t = 0;\nconst double M113a_Suspension::m_torsion_kstop = 350800;\nconst double M113a_Suspension::m_torsion_lowerstop = -7.0 \/ 180.0 * CH_C_PI;\nconst double M113a_Suspension::m_torsion_upperstop = 47.59 \/ 180.0 * CH_C_PI;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ M113 spring functor class - implements a (non)linear rotational spring\n\/\/ -----------------------------------------------------------------------------\nclass M113a_SpringTorque : public ChLinkRSDA::TorqueFunctor {\npublic:\n M113a_SpringTorque(double k, double c, double t, double kstop, double lowerstop, double upperstop) \n : m_k(k), m_c(c), m_t(t), m_kstop(kstop), m_lowerstop(lowerstop), m_upperstop(upperstop) {}\n\n virtual double evaluate(double time, double angle, double vel, ChLinkRSDA* link) override {\n double force = m_t - m_k * angle - m_c * vel;\n\n \/\/Apply bump stop spring rates if needed\n if (angle < m_lowerstop) {\n force -= m_kstop*(angle - m_lowerstop);\n }\n else if (angle > m_upperstop) {\n force -= m_kstop*(angle - m_upperstop);\n }\n\n return force;\n }\n\nprivate:\n double m_k;\n double m_c;\n double m_t;\n double m_kstop;\n double m_lowerstop;\n double m_upperstop;\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ M113 shock functor class - implements a (non)linear translational damper\n\/\/ -----------------------------------------------------------------------------\nclass M113a_ShockForce : public ChLinkTSDA::ForceFunctor {\n public:\n M113a_ShockForce(){}\n\n virtual double evaluate(double time, double rest_length, double length, double vel, ChLinkTSDA* link) override {\n \/\/ Clip the velocity to within +\/- 0.254 m\/s [10 in\/s]\n ChClampValue(vel, -0.254, 0.254);\n\n \/\/ Velocity is positive in extension.\n \/\/ Linear interpolate between 500lbf in extension at 10 in\/s and\n \/\/ -2000lbf at -10in\/s (converted to N)\n return vel >= 0 ? (-8756.341762 * vel) : (-35025.36705 * vel);\n }\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nM113a_Suspension::M113a_Suspension(const std::string& name, VehicleSide side, int index, bool has_shock)\n : ChLinearDamperRWAssembly(name, has_shock), m_side(side) {\n \/\/ Instantiate the force callback for the shock (damper).\n m_shock_forceCB = chrono_types::make_shared<M113a_ShockForce>();\n\n \/\/ Instantiate the torque callback for the spring.\n m_spring_torqueCB = chrono_types::make_shared<M113a_SpringTorque>(\n m_torsion_k, m_torsion_c, m_torsion_t, m_torsion_kstop, m_torsion_lowerstop, m_torsion_upperstop);\n\n \/\/ Create the associated road wheel.\n if (side == LEFT)\n m_road_wheel = chrono_types::make_shared<M113a_RoadWheelLeft>(index);\n else\n m_road_wheel = chrono_types::make_shared<M113a_RoadWheelRight>(index);\n}\n\nM113a_Suspension::~M113a_Suspension() {}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nconst ChVector<> M113a_Suspension::GetLocation(PointId which) {\n ChVector<> point;\n\n switch (which) {\n case ARM:\n point = ChVector<>(0.213, -0.12, 0.199);\n break;\n case ARM_WHEEL:\n point = ChVector<>(0, -0.12, 0);\n break;\n case ARM_CHASSIS:\n point = ChVector<>(0.232, -0.12, 0.217);\n break;\n case SHOCK_A:\n point = ChVector<>(0, -0.12, 0);\n break;\n case SHOCK_C:\n point = ChVector<>(0, -0.12, 1);\n break;\n default:\n point = ChVector<>(0, 0, 0);\n break;\n }\n\n if (m_side == RIGHT)\n point.y() *= -1;\n\n return point;\n}\n\n} \/\/ end namespace m113\n} \/\/ end namespace vehicle\n} \/\/ end namespace chrono\n<commit_msg>Update M113a model to reflect RSDA functor change<commit_after>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ M113 suspension subsystem.\n\/\/\n\/\/ =============================================================================\n\n#include \"chrono_models\/vehicle\/m113a\/M113a_RoadWheel.h\"\n#include \"chrono_models\/vehicle\/m113a\/M113a_Suspension.h\"\n\nnamespace chrono {\nnamespace vehicle {\nnamespace m113 {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Static variables\n\/\/ -----------------------------------------------------------------------------\nconst double M113a_Suspension::m_arm_mass = 16.513;\nconst ChVector<> M113a_Suspension::m_arm_inertia(3.8, 0.08, 3.8);\nconst double M113a_Suspension::m_arm_radius = 0.019;\n\nconst double M113a_Suspension::m_torsion_a0 = 0;\nconst double M113a_Suspension::m_torsion_k = 9557;\nconst double M113a_Suspension::m_torsion_c = 191;\nconst double M113a_Suspension::m_torsion_t = 0;\nconst double M113a_Suspension::m_torsion_kstop = 350800;\nconst double M113a_Suspension::m_torsion_lowerstop = -7.0 \/ 180.0 * CH_C_PI;\nconst double M113a_Suspension::m_torsion_upperstop = 47.59 \/ 180.0 * CH_C_PI;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ M113 spring functor class - implements a (non)linear rotational spring\n\/\/ -----------------------------------------------------------------------------\nclass M113a_SpringTorque : public ChLinkRSDA::TorqueFunctor {\npublic:\n M113a_SpringTorque(double k, double c, double t, double kstop, double lowerstop, double upperstop) \n : m_k(k), m_c(c), m_t(t), m_kstop(kstop), m_lowerstop(lowerstop), m_upperstop(upperstop) {}\n\n virtual double evaluate(double time, double angle, double vel, const ChLinkRSDA& link) override {\n double force = m_t - m_k * angle - m_c * vel;\n\n \/\/Apply bump stop spring rates if needed\n if (angle < m_lowerstop) {\n force -= m_kstop*(angle - m_lowerstop);\n }\n else if (angle > m_upperstop) {\n force -= m_kstop*(angle - m_upperstop);\n }\n\n return force;\n }\n\nprivate:\n double m_k;\n double m_c;\n double m_t;\n double m_kstop;\n double m_lowerstop;\n double m_upperstop;\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ M113 shock functor class - implements a (non)linear translational damper\n\/\/ -----------------------------------------------------------------------------\nclass M113a_ShockForce : public ChLinkTSDA::ForceFunctor {\n public:\n M113a_ShockForce(){}\n\n virtual double evaluate(double time, double rest_length, double length, double vel, ChLinkTSDA* link) override {\n \/\/ Clip the velocity to within +\/- 0.254 m\/s [10 in\/s]\n ChClampValue(vel, -0.254, 0.254);\n\n \/\/ Velocity is positive in extension.\n \/\/ Linear interpolate between 500lbf in extension at 10 in\/s and\n \/\/ -2000lbf at -10in\/s (converted to N)\n return vel >= 0 ? (-8756.341762 * vel) : (-35025.36705 * vel);\n }\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nM113a_Suspension::M113a_Suspension(const std::string& name, VehicleSide side, int index, bool has_shock)\n : ChLinearDamperRWAssembly(name, has_shock), m_side(side) {\n \/\/ Instantiate the force callback for the shock (damper).\n m_shock_forceCB = chrono_types::make_shared<M113a_ShockForce>();\n\n \/\/ Instantiate the torque callback for the spring.\n m_spring_torqueCB = chrono_types::make_shared<M113a_SpringTorque>(\n m_torsion_k, m_torsion_c, m_torsion_t, m_torsion_kstop, m_torsion_lowerstop, m_torsion_upperstop);\n\n \/\/ Create the associated road wheel.\n if (side == LEFT)\n m_road_wheel = chrono_types::make_shared<M113a_RoadWheelLeft>(index);\n else\n m_road_wheel = chrono_types::make_shared<M113a_RoadWheelRight>(index);\n}\n\nM113a_Suspension::~M113a_Suspension() {}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nconst ChVector<> M113a_Suspension::GetLocation(PointId which) {\n ChVector<> point;\n\n switch (which) {\n case ARM:\n point = ChVector<>(0.213, -0.12, 0.199);\n break;\n case ARM_WHEEL:\n point = ChVector<>(0, -0.12, 0);\n break;\n case ARM_CHASSIS:\n point = ChVector<>(0.232, -0.12, 0.217);\n break;\n case SHOCK_A:\n point = ChVector<>(0, -0.12, 0);\n break;\n case SHOCK_C:\n point = ChVector<>(0, -0.12, 1);\n break;\n default:\n point = ChVector<>(0, 0, 0);\n break;\n }\n\n if (m_side == RIGHT)\n point.y() *= -1;\n\n return point;\n}\n\n} \/\/ end namespace m113\n} \/\/ end namespace vehicle\n} \/\/ end namespace chrono\n<|endoftext|>"} {"text":"<commit_before>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/questions\/lineedit-frame-37831979\n#include <QtWidgets>\n#include <QtUiTools>\n\nconst char ui[] = R\"EOF(\n <ui version=\"4.0\">\n <class>Form<\/class>\n <widget class=\"QWidget\" name=\"Form\">\n <layout class=\"QFormLayout\" name=\"formLayout\">\n <item row=\"0\" column=\"0\">\n <widget class=\"QLabel\" name=\"label\">\n <property name=\"text\">\n <string>TextLabel<\/string>\n <\/property>\n <\/widget>\n <\/item>\n <item row=\"0\" column=\"1\">\n <widget class=\"QLineEdit\" name=\"lineEdit\"\/>\n <\/item>\n <\/layout>\n <\/widget>\n <resources\/>\n <connections\/>\n <\/ui>)EOF\";\n\nint main(int argc, char ** argv) {\n QApplication app{argc, argv};\n QBuffer buf;\n buf.setData(ui, sizeof(ui));\n auto w = QUiLoader().load(&buf);\n auto & layout = *static_cast<QFormLayout*>(w->layout());\n QLineEdit edit;\n layout.itemAt(0)->widget()->setMinimumHeight(50);\n layout.addRow(\"Edit here\", &edit);\n edit.setMinimumHeight(100);\n layout.activate();\n w->show();\n return app.exec();\n}\n<commit_msg>Follow the updated question.<commit_after>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/questions\/lineedit-frame-37831979\n#include <QtWidgets>\n#include <QtUiTools>\n\nconst char ui[] = R\"EOF(\n <ui version=\"4.0\">\n <class>DatasetWidget<\/class>\n <widget class=\"QWidget\" name=\"DatasetWidget\">\n <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n <item>\n <widget class=\"QLabel\" name=\"lblCaptionDatensatz\">\n <property name=\"text\">\n <string>Datensatz:<\/string>\n <\/property>\n <\/widget>\n <\/item>\n <item>\n <widget class=\"QLabel\" name=\"lblDatensatz\">\n <property name=\"text\">\n <string>C-XXXX-XXX<\/string>\n <\/property>\n <\/widget>\n <\/item>\n <item>\n <widget class=\"QLineEdit\" name=\"leDescriptor\">\n <property name=\"maxLength\">\n <number>7<\/number>\n <\/property>\n <\/widget>\n <\/item>\n <item>\n <layout class=\"QFormLayout\" name=\"formDisp\"><\/layout>\n <\/item>\n <\/layout>\n <\/widget>\n <connections\/>\n <\/ui>)EOF\";\n\nint main(int argc, char ** argv) {\n QApplication app{argc, argv};\n QBuffer buf;\n buf.setData(ui, sizeof(ui));\n auto w = QUiLoader().load(&buf);\n auto & layout = *w->findChild<QFormLayout*>(\"formDisp\");\n QLineEdit edit1, edit2;\n layout.addRow(\"Edit1\", &edit1);\n layout.addRow(\"Edit2\", &edit2);\n edit1.setMinimumHeight(50);\n edit2.setMinimumHeight(100);\n w->show();\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is a part of the open source stm32plus library.\n * Copyright (c) 2011,2012,2013,2014 Andy Brown <www.andybrown.me.uk>\n * Please see website for licensing terms.\n *\/\n\n#include \"config\/stm32plus.h\"\n#include \"config\/timing.h\"\n#include \"config\/timer.h\"\n#include \"config\/usart.h\"\n#include \"config\/string.h\"\n\n\nusing namespace stm32plus;\n\n\n\/**\n * This timer example demonstrates the use of the encoder feature. The STM32's timers understand\n * the phase relationship between two signals output by a rotary encoder and can translate those\n * rising and falling edges into up\/down movements of a counter. All you need to do is to connect\n * up the two encoder output pins to channels 1 and 2 of a timer and then configure the timer to\n * operate in encoder mode. The timer's counter will then tick up and down as the encoder is operated.\n *\n * We will use timer 1 to receive the encoder inputs. We will subscribe to capture\/compare interrupts\n * so that we get notified when the encoder is moved rather than having to poll for it. We will light\n * different LEDs depending on the direction that the encoder is turned and we will output the value\n * of the counter to the USART.\n *\n * We will also cater for the optional \"index pin\" that resets the counter to a known value when\n * its triggered. This should be connected to PA0. If you're simulating the encoder then you can\n * press the blue USER button on the F4 discovery board to trigger this.\n *\n * Some wiring is obviously required.\n *\n * If you have an encoder then wire the outputs to PA8, PA9 and remove the call to simulateSignals()\n * in the code. simulateSignals() allows you to validate your code before attaching your hardware.\n * To run in simulation mode you must wire PA2 => PA8 and PA3 => PA9. The simulator will pretend to\n * be an encoder and stimulate the encoder TI1 and TI2 inputs according to a known pattern. See the\n * file simulation_waveform.png for a logic-analyser capture of the simulation waveform.\n *\n * F4 Discovery board:\n * This example will work out-of-the-box on the F4 discovery board. LEDs are on PD12, PD13. The\n * USART TX\/RX is on PB6\/PB7 except on the F4 when it's on PD8\/PD9 due to pin availability on\n * the F4 discovery board.\n *\n * Compatible MCU:\n * STM32F0\n * STM32F1\n * STM32F4\n *\n * Tested on devices:\n * STM32F051R8T6\n * STM32F100RBT6\n * -STM32F103ZET6\n * STM32F407VGT6\n *\/\n\nclass TimerEncoderTest {\n\n protected:\n\n \/*\n * LED pins on port D\n *\/\n\n enum {\n LED1_PIN = 12,\n LED2_PIN = 13\n };\n\n \/*\n * Set up the two LEDs that will show the direction of the counter (up\/down)\n *\/\n\n GpioD<DefaultDigitalOutputFeature<LED1_PIN,LED2_PIN>> _leds;\n\n \/*\n * Set up the timer that will be used to receive input from the encoder\n *\/\n\n Timer1<\n Timer1GpioFeature< \/\/ TI1\/TI2 are CH1_IN and CH2_IN, set them up\n TIMER_REMAP_NONE, \/\/ the GPIO input will not be remapped\n TIM1_CH1_IN, \/\/ channel 1 = TI1\n TIM1_CH2_IN \/\/ channel 2 = TI2\n >,\n TimerEncoderFeature< \/\/ we're using the quadrature encoder feature\n EncoderCounterEdge::Input1, \/\/ count on TI1 edges with direction according to TI2\n EncoderPolarity::Rising, \/\/ TI1 polarity\n EncoderPolarity::Rising \/\/ TI2 polarity\n >,\n TimerChannel1Feature, \/\/ we'll use channel 1 for CC interrupts\n Timer1InterruptFeature \/\/ that means we need the interrupt feature\n > _timer;\n\n \/*\n * Declare a USART to write out the counter value. TX\/RX = PD8\/PD9 for Usart3_Remap1 and\n * PB6\/PB7 for Usart1_Remap1. The differences are down to which pins are available on the\n * F4 and F0 discovery boards.\n *\/\n\n#if defined(STM32PLUS_F4)\n Usart3_Remap1<> _usart;\n#else\n Usart1_Remap1<> _usart;\n#endif\n\n UsartPollingOutputStream _outputStream;\n\n \/*\n * Declare the EXTI input (PA0) that should be connected to the encoder's index\n * pin if it has one. A rising edge on this pin resets the counter to a known value\n *\/\n\n GpioA<DefaultDigitalInputFeature<0> > _indexPin;\n Exti0 _exti;\n\n \/*\n * The last value received from the counter\n *\/\n\n uint16_t _lastValue;\n\n public:\n\n \/*\n * Constructor, call the member variable constructors where needed\n *\/\n\n TimerEncoderTest() :\n _usart(57600),\n _outputStream(_usart),\n _exti(EXTI_Mode_Interrupt,EXTI_Trigger_Rising,_indexPin[0]) {\n }\n\n \/*\n * Run the test\n *\/\n\n void run() {\n\n \/*\n * Set ourselves up as a subscriber for interrupts raised by the timer class.\n *\/\n\n _timer.TimerInterruptEventSender.insertSubscriber(\n TimerInterruptEventSourceSlot::bind(this,&TimerEncoderTest::onInterrupt)\n );\n\n \/*\n * Initialise the counter for the encoder to have a range of 0..65535 and arrange\n * for automatic management of the index pin (resets to 30000)\n *\/\n\n _timer.initialiseEncoderCounter(65535);\n _timer.manageEncoderReset(_exti,30000);\n\n \/*\n * Initialise the capture and subscribe to the interrupts\n *\/\n\n _timer.initCapture();\n _timer.enableInterrupts(TIM_IT_CC1);\n\n \/*\n * Initialise the starting value for the counter to 30000\n *\/\n\n _timer.setCounter(_lastValue=30000);\n\n \/*\n * Enable the timer\n *\/\n\n _timer.enablePeripheral();\n\n \/*\n * Go into an infinite loop simulating the encoder signals. If you've got a real\n * encoder then delete the simulateSignals() and delay() calls and just go into\n * an infinite loop.\n *\/\n\n for(;;) {\n simulateSignals();\n MillisecondTimer::delay(1000);\n }\n }\n\n\n \/*\n * Simulate the signals that an encoder might make. This requires you to make the following\n * wiring: PA2 => PA8. PA3 => PA9. TI1 and TI2 will be generated on PA0\/PA1 following the\n * pattern in AN4013 Figure 8. This will simulate 4 up counts and then 4 down counts.\n *\/\n\n void simulateSignals() {\n\n static const bool ti[][2]={\n { false, false },\n { true, false }, \/\/ +1\n { true, true },\n { false, true }, \/\/ +1\n { false, false },\n { true, false }, \/\/ +1\n { true, true },\n { false, true }, \/\/ +1\n { false, false },\n { true, false }, \/\/ reversal\n { false, false },\n { true, false },\n { false, false }, \/\/ -1\n { false, true },\n { true, true }, \/\/ -1\n { true, false },\n { false, false }, \/\/ -1\n { false, true },\n { true, true }, \/\/ -1\n { true, false },\n { false, false },\n { false, true }, \/\/ reversal\n { false, false },\n { false, true },\n { false, false },\n { false, true },\n { false, false }\n };\n\n enum { TI1 = 2, TI2 = 3 };\n GpioA<DefaultDigitalOutputFeature<TI1,TI2> > simpins;\n\n uint8_t i;\n\n \/\/ run through the steps allowing 10ms between each one\n\n for(i=0;i<sizeof(ti)\/sizeof(ti[0]);i++) {\n\n simpins[TI1].setState(ti[i][0]);\n simpins[TI2].setState(ti[i][1]);\n\n MillisecondTimer::delay(10);\n }\n }\n\n\n \/*\n * Subscriber callback function. This is called when the CC1 interrupt that we've\n * enabled is fired. Don't do much in here and be aware of re-entrancy issues.\n *\/\n\n void onInterrupt(TimerEventType tet,uint8_t \/* timerNumber *\/) {\n\n uint16_t currentValue;\n\n \/*\n * Not likely to be anything else but anyway...\n *\/\n\n if(tet!=TimerEventType::EVENT_COMPARE1)\n return;\n\n \/*\n * A positive change will light LED1, a negative change will light LED2\n *\/\n\n currentValue=_timer.getCounter();\n if(currentValue>_lastValue || _lastValue-currentValue>30000) {\n\n \/\/ current > last or there's been a wrap (i.e. silly difference between last and current)\n\n _leds[LED1_PIN].set();\n _leds[LED2_PIN].reset();\n }\n else {\n _leds[LED1_PIN].reset();\n _leds[LED2_PIN].set();\n }\n\n \/*\n * Write out the current value to the USART if it's connected\n *\/\n\n _outputStream << StringUtil::Ascii(currentValue) << \"\\r\\n\";\n _lastValue=currentValue;\n }\n};\n\n\n\/*\n * Main entry point\n *\/\n\nint main() {\n\n MillisecondTimer::initialise();\n\n TimerEncoderTest test;\n test.run();\n\n \/\/ not reached\n return 0;\n}\n<commit_msg>tested on f1hd<commit_after>\/*\n * This file is a part of the open source stm32plus library.\n * Copyright (c) 2011,2012,2013,2014 Andy Brown <www.andybrown.me.uk>\n * Please see website for licensing terms.\n *\/\n\n#include \"config\/stm32plus.h\"\n#include \"config\/timing.h\"\n#include \"config\/timer.h\"\n#include \"config\/usart.h\"\n#include \"config\/string.h\"\n\n\nusing namespace stm32plus;\n\n\n\/**\n * This timer example demonstrates the use of the encoder feature. The STM32's timers understand\n * the phase relationship between two signals output by a rotary encoder and can translate those\n * rising and falling edges into up\/down movements of a counter. All you need to do is to connect\n * up the two encoder output pins to channels 1 and 2 of a timer and then configure the timer to\n * operate in encoder mode. The timer's counter will then tick up and down as the encoder is operated.\n *\n * We will use timer 1 to receive the encoder inputs. We will subscribe to capture\/compare interrupts\n * so that we get notified when the encoder is moved rather than having to poll for it. We will light\n * different LEDs depending on the direction that the encoder is turned and we will output the value\n * of the counter to the USART.\n *\n * We will also cater for the optional \"index pin\" that resets the counter to a known value when\n * its triggered. This should be connected to PA0. If you're simulating the encoder then you can\n * press the blue USER button on the F4 discovery board to trigger this.\n *\n * Some wiring is obviously required.\n *\n * If you have an encoder then wire the outputs to PA8, PA9 and remove the call to simulateSignals()\n * in the code. simulateSignals() allows you to validate your code before attaching your hardware.\n * To run in simulation mode you must wire PA2 => PA8 and PA3 => PA9. The simulator will pretend to\n * be an encoder and stimulate the encoder TI1 and TI2 inputs according to a known pattern. See the\n * file simulation_waveform.png for a logic-analyser capture of the simulation waveform.\n *\n * F4 Discovery board:\n * This example will work out-of-the-box on the F4 discovery board. LEDs are on PD12, PD13. The\n * USART TX\/RX is on PB6\/PB7 except on the F4 when it's on PD8\/PD9 due to pin availability on\n * the F4 discovery board.\n *\n * Compatible MCU:\n * STM32F0\n * STM32F1\n * STM32F4\n *\n * Tested on devices:\n * STM32F051R8T6\n * STM32F100RBT6\n * STM32F103ZET6\n * STM32F407VGT6\n *\/\n\nclass TimerEncoderTest {\n\n protected:\n\n \/*\n * LED pins on port D\n *\/\n\n enum {\n LED1_PIN = 12,\n LED2_PIN = 13\n };\n\n \/*\n * Set up the two LEDs that will show the direction of the counter (up\/down)\n *\/\n\n GpioD<DefaultDigitalOutputFeature<LED1_PIN,LED2_PIN>> _leds;\n\n \/*\n * Set up the timer that will be used to receive input from the encoder\n *\/\n\n Timer1<\n Timer1GpioFeature< \/\/ TI1\/TI2 are CH1_IN and CH2_IN, set them up\n TIMER_REMAP_NONE, \/\/ the GPIO input will not be remapped\n TIM1_CH1_IN, \/\/ channel 1 = TI1\n TIM1_CH2_IN \/\/ channel 2 = TI2\n >,\n TimerEncoderFeature< \/\/ we're using the quadrature encoder feature\n EncoderCounterEdge::Input1, \/\/ count on TI1 edges with direction according to TI2\n EncoderPolarity::Rising, \/\/ TI1 polarity\n EncoderPolarity::Rising \/\/ TI2 polarity\n >,\n TimerChannel1Feature, \/\/ we'll use channel 1 for CC interrupts\n Timer1InterruptFeature \/\/ that means we need the interrupt feature\n > _timer;\n\n \/*\n * Declare a USART to write out the counter value. TX\/RX = PD8\/PD9 for Usart3_Remap1 and\n * PB6\/PB7 for Usart1_Remap1. The differences are down to which pins are available on the\n * F4 and F0 discovery boards.\n *\/\n\n#if defined(STM32PLUS_F4)\n Usart3_Remap1<> _usart;\n#else\n Usart1_Remap1<> _usart;\n#endif\n\n UsartPollingOutputStream _outputStream;\n\n \/*\n * Declare the EXTI input (PA0) that should be connected to the encoder's index\n * pin if it has one. A rising edge on this pin resets the counter to a known value\n *\/\n\n GpioA<DefaultDigitalInputFeature<0> > _indexPin;\n Exti0 _exti;\n\n \/*\n * The last value received from the counter\n *\/\n\n uint16_t _lastValue;\n\n public:\n\n \/*\n * Constructor, call the member variable constructors where needed\n *\/\n\n TimerEncoderTest() :\n _usart(57600),\n _outputStream(_usart),\n _exti(EXTI_Mode_Interrupt,EXTI_Trigger_Rising,_indexPin[0]) {\n }\n\n \/*\n * Run the test\n *\/\n\n void run() {\n\n \/*\n * Set ourselves up as a subscriber for interrupts raised by the timer class.\n *\/\n\n _timer.TimerInterruptEventSender.insertSubscriber(\n TimerInterruptEventSourceSlot::bind(this,&TimerEncoderTest::onInterrupt)\n );\n\n \/*\n * Initialise the counter for the encoder to have a range of 0..65535 and arrange\n * for automatic management of the index pin (resets to 30000)\n *\/\n\n _timer.initialiseEncoderCounter(65535);\n _timer.manageEncoderReset(_exti,30000);\n\n \/*\n * Initialise the capture and subscribe to the interrupts\n *\/\n\n _timer.initCapture();\n _timer.enableInterrupts(TIM_IT_CC1);\n\n \/*\n * Initialise the starting value for the counter to 30000\n *\/\n\n _timer.setCounter(_lastValue=30000);\n\n \/*\n * Enable the timer\n *\/\n\n _timer.enablePeripheral();\n\n \/*\n * Go into an infinite loop simulating the encoder signals. If you've got a real\n * encoder then delete the simulateSignals() and delay() calls and just go into\n * an infinite loop.\n *\/\n\n for(;;) {\n simulateSignals();\n MillisecondTimer::delay(1000);\n }\n }\n\n\n \/*\n * Simulate the signals that an encoder might make. This requires you to make the following\n * wiring: PA2 => PA8. PA3 => PA9. TI1 and TI2 will be generated on PA0\/PA1 following the\n * pattern in AN4013 Figure 8. This will simulate 4 up counts and then 4 down counts.\n *\/\n\n void simulateSignals() {\n\n static const bool ti[][2]={\n { false, false },\n { true, false }, \/\/ +1\n { true, true },\n { false, true }, \/\/ +1\n { false, false },\n { true, false }, \/\/ +1\n { true, true },\n { false, true }, \/\/ +1\n { false, false },\n { true, false }, \/\/ reversal\n { false, false },\n { true, false },\n { false, false }, \/\/ -1\n { false, true },\n { true, true }, \/\/ -1\n { true, false },\n { false, false }, \/\/ -1\n { false, true },\n { true, true }, \/\/ -1\n { true, false },\n { false, false },\n { false, true }, \/\/ reversal\n { false, false },\n { false, true },\n { false, false },\n { false, true },\n { false, false }\n };\n\n enum { TI1 = 2, TI2 = 3 };\n GpioA<DefaultDigitalOutputFeature<TI1,TI2> > simpins;\n\n uint8_t i;\n\n \/\/ run through the steps allowing 10ms between each one\n\n for(i=0;i<sizeof(ti)\/sizeof(ti[0]);i++) {\n\n simpins[TI1].setState(ti[i][0]);\n simpins[TI2].setState(ti[i][1]);\n\n MillisecondTimer::delay(10);\n }\n }\n\n\n \/*\n * Subscriber callback function. This is called when the CC1 interrupt that we've\n * enabled is fired. Don't do much in here and be aware of re-entrancy issues.\n *\/\n\n void onInterrupt(TimerEventType tet,uint8_t \/* timerNumber *\/) {\n\n uint16_t currentValue;\n\n \/*\n * Not likely to be anything else but anyway...\n *\/\n\n if(tet!=TimerEventType::EVENT_COMPARE1)\n return;\n\n \/*\n * A positive change will light LED1, a negative change will light LED2\n *\/\n\n currentValue=_timer.getCounter();\n if(currentValue>_lastValue || _lastValue-currentValue>30000) {\n\n \/\/ current > last or there's been a wrap (i.e. silly difference between last and current)\n\n _leds[LED1_PIN].set();\n _leds[LED2_PIN].reset();\n }\n else {\n _leds[LED1_PIN].reset();\n _leds[LED2_PIN].set();\n }\n\n \/*\n * Write out the current value to the USART if it's connected\n *\/\n\n _outputStream << StringUtil::Ascii(currentValue) << \"\\r\\n\";\n _lastValue=currentValue;\n }\n};\n\n\n\/*\n * Main entry point\n *\/\n\nint main() {\n\n MillisecondTimer::initialise();\n\n TimerEncoderTest test;\n test.run();\n\n \/\/ not reached\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3343\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>SWDEV-2 - Change OpenCL version number from 3343 to 3344<commit_after>\/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3344\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3132\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>SWDEV-2 - Change OpenCL version number from 3132 to 3133<commit_after>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3133\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3102\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>SWDEV-2 - Change OpenCL version number from 3102 to 3103<commit_after>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3103\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"rotation_copying_system.h\"\n#include <Box2D\\Dynamics\\b2Body.h>\n\n#include \"game\/transcendental\/entity_id.h\"\n#include \"augs\/graphics\/renderer.h\"\n\n#include \"game\/components\/physics_component.h\"\n#include \"game\/components\/special_physics_component.h\"\n#include \"game\/components\/gun_component.h\"\n#include \"game\/detail\/inventory_slot_id.h\"\n#include \"game\/detail\/inventory_slot.h\"\n#include \"game\/detail\/inventory_utils.h\"\n\n#include \"augs\/ensure.h\"\n\n#include \"game\/components\/rotation_copying_component.h\"\n#include \"game\/components\/transform_component.h\"\n\n#include \"augs\/misc\/timer.h\"\n\n#include \"game\/transcendental\/entity_handle.h\"\n#include \"game\/transcendental\/step.h\"\n#include \"game\/transcendental\/cosmos.h\"\n\nusing namespace augs;\n\nfloat colinearize_AB(const vec2 O_center_of_rotation, vec2 A_rifle_center, vec2 B_barrel, vec2 C_crosshair) {\n\tauto crosshair_vector = C_crosshair - O_center_of_rotation;\n\tauto barrel_vector = B_barrel - O_center_of_rotation;\n\t\n\tif (crosshair_vector.is_epsilon(1.f))\n\t\tcrosshair_vector.set(1, 0);\n\n\tif (crosshair_vector.length() < barrel_vector.length() + 1.f)\n\t\treturn crosshair_vector.degrees();\n\t\n\tC_crosshair = O_center_of_rotation + crosshair_vector;\n\n\tconst float oc_radius = crosshair_vector.length();\n\t\n\tconst auto intersection = circle_ray_intersection(B_barrel, A_rifle_center, O_center_of_rotation, oc_radius);\n\tconst bool has_intersection = intersection.first;\n\t\n\tensure(has_intersection);\n\n\tconst auto G = intersection.second;\n\tconst auto CG = C_crosshair - G;\n\tconst auto AG = A_rifle_center - G;\n\n\tconst auto final_angle = 2 * (CG.degrees() - AG.degrees());\n\t\n\tif (augs::renderer::get_current().debug_draw_colinearization) {\n\t\tauto& ln = augs::renderer::get_current().logic_lines;\n\n\t\tln.draw_cyan(O_center_of_rotation, C_crosshair);\n\t\tln.draw_red(O_center_of_rotation, A_rifle_center);\n\t\tln.draw_red(O_center_of_rotation, B_barrel);\n\t\tln.draw_yellow(O_center_of_rotation, G);\n\t\t\n\t\tln.draw_green(G, A_rifle_center);\n\t\tln.draw_green(G, C_crosshair);\n\n\t\tA_rifle_center.rotate(final_angle, O_center_of_rotation);\n\t\tB_barrel.rotate(final_angle, O_center_of_rotation);\n\n\t\tln.draw_red(O_center_of_rotation, A_rifle_center);\n\t\tln.draw_red(O_center_of_rotation, B_barrel);\n\n\t\tln.draw(A_rifle_center - (B_barrel - A_rifle_center) * 100, B_barrel + (B_barrel - A_rifle_center)*100);\n\t}\n\n\treturn final_angle;\n}\n\nfloat rotation_copying_system::resolve_rotation_copying_value(const const_entity_handle it) const {\n\tauto& rotation_copying = it.get<components::rotation_copying>();\n\tauto& cosmos = it.get_cosmos();\n\tconst auto target = cosmos[rotation_copying.target];\n\n\tif (target.dead())\n\t\treturn 0.f;\n\n\tfloat new_angle = 0.f;\n\n\tif (rotation_copying.look_mode == components::rotation_copying::look_type::ROTATION) {\n\t\tnew_angle = target.logic_transform().rotation;\n\t}\n\telse if (rotation_copying.look_mode == components::rotation_copying::look_type::POSITION) {\n\t\tconst auto& target_transform = target.logic_transform();\n\t\t\n\t\tconst auto diff = target_transform.pos - position(it);\n\n\t\tif (diff.is_epsilon(1.f))\n\t\t\tnew_angle = 0.f;\n\t\telse\n\t\t\tnew_angle = diff.degrees();\n\n\t\tif (rotation_copying.colinearize_item_in_hand) {\n\t\t\tauto hand = it.map_primary_action_to_secondary_hand_if_primary_empty(0);\n\n\t\t\tif (hand.has_items()) {\n\t\t\t\tconst auto subject_item = hand.get_items_inside()[0];\n\n\t\t\t\tconst auto* maybe_gun = subject_item.find<components::gun>();\n\n\t\t\t\tif (maybe_gun) {\n\t\t\t\t\tconst auto rifle_transform = subject_item.logic_transform();\n\t\t\t\t\tauto rifle_center = rifle_transform.pos;\n\t\t\t\t\tauto barrel = maybe_gun->calculate_barrel_transform(rifle_transform).pos;\n\t\t\t\t\tconst auto mc = position(it);\n\n\t\t\t\t\trifle_center.rotate(-rotation(it), mc);\n\t\t\t\t\tbarrel.rotate(-rotation(it), mc);\n\n\t\t\t\t\tauto crosshair_vector = target_transform.pos - mc;\n\n\t\t\t\t\tnew_angle = colinearize_AB(mc, rifle_center, barrel, target_transform.pos);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tif (target.has<components::physics>()) {\n\t\t\tconst auto target_physics = target.get<components::physics>();\n\n\t\t\tvec2 direction;\n\n\t\t\tif (rotation_copying.look_mode == components::rotation_copying::look_type::VELOCITY)\n\t\t\t\tdirection = vec2(target_physics.velocity());\n\n\t\t\tif (direction.non_zero())\n\t\t\t\tnew_angle = direction.degrees();\n\t\t}\n\t}\n\n\tif (rotation_copying.easing_mode == components::rotation_copying::easing_type::EXPONENTIAL) {\n\t\tensure(0);\n\t\t\/\/float averaging_constant = static_cast<float>(\n\t\t\/\/\tpow(rotation_copying.smoothing_average_factor, rotation_copying.averages_per_sec * delta_seconds())\n\t\t\/\/\t);\n\t\t\/\/\n\t\t\/\/rotation_copying.last_rotation_interpolant = (rotation_copying.last_rotation_interpolant * averaging_constant + new_rotation * (1.0f - averaging_constant)).normalize();\n\t\t\/\/rotation_copying.last_value = rotation_copying.last_rotation_interpolant.degrees();\n\t}\n\telse if (rotation_copying.easing_mode == components::rotation_copying::easing_type::NONE) {\n\t\n\t}\n\n\treturn new_angle;\n}\n\nvoid rotation_copying_system::update_rotations(cosmos& cosmos) const {\n\tfor (const auto it : cosmos.get(processing_subjects::WITH_ROTATION_COPYING)) {\n\t\tconst auto& rotation_copying = it.get<components::rotation_copying>();\n\n\t\tif (rotation_copying.update_value) {\n\t\t\tif (it.has<components::physics>()) {\n\t\t\t\tauto target_angle = resolve_rotation_copying_value(it);\n\t\t\t\tauto& phys = it.get<components::physics>();\n\n\t\t\t\tphys.set_transform({ phys.get_position(), target_angle });\n\t\t\t\tphys.set_angular_velocity(0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tit.get<components::transform>().rotation = resolve_rotation_copying_value(it);\n\t\t\t}\n\t\t}\n\t}\n}<commit_msg>usage of guns_wielded<commit_after>#include \"rotation_copying_system.h\"\n#include <Box2D\\Dynamics\\b2Body.h>\n\n#include \"game\/transcendental\/entity_id.h\"\n#include \"augs\/graphics\/renderer.h\"\n\n#include \"game\/components\/physics_component.h\"\n#include \"game\/components\/special_physics_component.h\"\n#include \"game\/components\/gun_component.h\"\n#include \"game\/detail\/inventory_slot_id.h\"\n#include \"game\/detail\/inventory_slot.h\"\n#include \"game\/detail\/inventory_utils.h\"\n\n#include \"augs\/ensure.h\"\n\n#include \"game\/components\/rotation_copying_component.h\"\n#include \"game\/components\/transform_component.h\"\n\n#include \"augs\/misc\/timer.h\"\n\n#include \"game\/transcendental\/entity_handle.h\"\n#include \"game\/transcendental\/step.h\"\n#include \"game\/transcendental\/cosmos.h\"\n\nusing namespace augs;\n\nfloat colinearize_AB(const vec2 O_center_of_rotation, vec2 A_rifle_center, vec2 B_barrel, vec2 C_crosshair) {\n\tauto crosshair_vector = C_crosshair - O_center_of_rotation;\n\tauto barrel_vector = B_barrel - O_center_of_rotation;\n\t\n\tif (crosshair_vector.is_epsilon(1.f))\n\t\tcrosshair_vector.set(1, 0);\n\n\tif (crosshair_vector.length() < barrel_vector.length() + 1.f)\n\t\treturn crosshair_vector.degrees();\n\t\n\tC_crosshair = O_center_of_rotation + crosshair_vector;\n\n\tconst float oc_radius = crosshair_vector.length();\n\t\n\tconst auto intersection = circle_ray_intersection(B_barrel, A_rifle_center, O_center_of_rotation, oc_radius);\n\tconst bool has_intersection = intersection.first;\n\t\n\tensure(has_intersection);\n\n\tconst auto G = intersection.second;\n\tconst auto CG = C_crosshair - G;\n\tconst auto AG = A_rifle_center - G;\n\n\tconst auto final_angle = 2 * (CG.degrees() - AG.degrees());\n\t\n\tif (augs::renderer::get_current().debug_draw_colinearization) {\n\t\tauto& ln = augs::renderer::get_current().logic_lines;\n\n\t\tln.draw_cyan(O_center_of_rotation, C_crosshair);\n\t\tln.draw_red(O_center_of_rotation, A_rifle_center);\n\t\tln.draw_red(O_center_of_rotation, B_barrel);\n\t\tln.draw_yellow(O_center_of_rotation, G);\n\t\t\n\t\tln.draw_green(G, A_rifle_center);\n\t\tln.draw_green(G, C_crosshair);\n\n\t\tA_rifle_center.rotate(final_angle, O_center_of_rotation);\n\t\tB_barrel.rotate(final_angle, O_center_of_rotation);\n\n\t\tln.draw_red(O_center_of_rotation, A_rifle_center);\n\t\tln.draw_red(O_center_of_rotation, B_barrel);\n\n\t\tln.draw(A_rifle_center - (B_barrel - A_rifle_center) * 100, B_barrel + (B_barrel - A_rifle_center)*100);\n\t}\n\n\treturn final_angle;\n}\n\nfloat rotation_copying_system::resolve_rotation_copying_value(const const_entity_handle it) const {\n\tauto& rotation_copying = it.get<components::rotation_copying>();\n\tauto& cosmos = it.get_cosmos();\n\tconst auto target = cosmos[rotation_copying.target];\n\n\tif (target.dead())\n\t\treturn 0.f;\n\n\tfloat new_angle = 0.f;\n\n\tif (rotation_copying.look_mode == components::rotation_copying::look_type::ROTATION) {\n\t\tnew_angle = target.logic_transform().rotation;\n\t}\n\telse if (rotation_copying.look_mode == components::rotation_copying::look_type::POSITION) {\n\t\tconst auto& target_transform = target.logic_transform();\n\t\t\n\t\tconst auto diff = target_transform.pos - position(it);\n\n\t\tif (diff.is_epsilon(1.f))\n\t\t\tnew_angle = 0.f;\n\t\telse\n\t\t\tnew_angle = diff.degrees();\n\n\t\tif (rotation_copying.colinearize_item_in_hand) {\n\t\t\tauto guns = it.guns_wielded();\n\n\t\t\tif (guns.size() > 0) {\n\t\t\t\tconst auto subject_item = guns[0];\n\n\t\t\t\tconst auto& gun = subject_item.get<components::gun>();\n\n\t\t\t\tconst auto rifle_transform = subject_item.logic_transform();\n\t\t\t\tauto rifle_center = rifle_transform.pos;\n\t\t\t\tauto barrel = gun.calculate_barrel_transform(rifle_transform).pos;\n\t\t\t\tconst auto mc = position(it);\n\n\t\t\t\trifle_center.rotate(-rotation(it), mc);\n\t\t\t\tbarrel.rotate(-rotation(it), mc);\n\n\t\t\t\tauto crosshair_vector = target_transform.pos - mc;\n\n\t\t\t\tnew_angle = colinearize_AB(mc, rifle_center, barrel, target_transform.pos);\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tif (target.has<components::physics>()) {\n\t\t\tconst auto target_physics = target.get<components::physics>();\n\n\t\t\tvec2 direction;\n\n\t\t\tif (rotation_copying.look_mode == components::rotation_copying::look_type::VELOCITY)\n\t\t\t\tdirection = vec2(target_physics.velocity());\n\n\t\t\tif (direction.non_zero())\n\t\t\t\tnew_angle = direction.degrees();\n\t\t}\n\t}\n\n\tif (rotation_copying.easing_mode == components::rotation_copying::easing_type::EXPONENTIAL) {\n\t\tensure(0);\n\t\t\/\/float averaging_constant = static_cast<float>(\n\t\t\/\/\tpow(rotation_copying.smoothing_average_factor, rotation_copying.averages_per_sec * delta_seconds())\n\t\t\/\/\t);\n\t\t\/\/\n\t\t\/\/rotation_copying.last_rotation_interpolant = (rotation_copying.last_rotation_interpolant * averaging_constant + new_rotation * (1.0f - averaging_constant)).normalize();\n\t\t\/\/rotation_copying.last_value = rotation_copying.last_rotation_interpolant.degrees();\n\t}\n\telse if (rotation_copying.easing_mode == components::rotation_copying::easing_type::NONE) {\n\t\n\t}\n\n\treturn new_angle;\n}\n\nvoid rotation_copying_system::update_rotations(cosmos& cosmos) const {\n\tfor (const auto it : cosmos.get(processing_subjects::WITH_ROTATION_COPYING)) {\n\t\tconst auto& rotation_copying = it.get<components::rotation_copying>();\n\n\t\tif (rotation_copying.update_value) {\n\t\t\tif (it.has<components::physics>()) {\n\t\t\t\tauto target_angle = resolve_rotation_copying_value(it);\n\t\t\t\tauto& phys = it.get<components::physics>();\n\n\t\t\t\tphys.set_transform({ phys.get_position(), target_angle });\n\t\t\t\tphys.set_angular_velocity(0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tit.get<components::transform>().rotation = resolve_rotation_copying_value(it);\n\t\t\t}\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix bug & optimize completion<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the KDE PIM project.\n\n Copyright (C) 2009 Martin Koller <kollix@aon.at>\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 version 2 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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include <qtest_kde.h>\n#include \"testdateparser.h\"\n\n#include <mimelib\/datetime.h>\n\n#include <QList>\n#include <QByteArray>\n\n\/\/---------------------------------------------------------------------\n\nQTEST_KDEMAIN( TestDateParser, NoGUI )\n\n\/\/---------------------------------------------------------------------\n\nvoid TestDateParser::testParsing()\n{\n QList<QByteArray> dates;\n\n \/\/ first of a pair is string to parse (local time),\n \/\/ second is the same in ISO-8601 format (YYYY-MM-DDTHH:MM:SS) UTC\n \/\/ non-RFC2822 dates\n dates << \"Mon Dec 15 11:04:05 PST 2003\" << \"2003-12-15T19:04:05\";\n dates << \"Tue, Feb 04, 2003 00:01:20 +0000\" << \"2003-02-04T00:01:20\";\n dates << \"Tue, Feb 04, 2003 10:01:20 -0220\" << \"2003-02-04T12:21:20\";\n dates << \"Tue Feb 04, 2003 00:01:20 +0000\" << \"2003-02-04T00:01:20\";\n dates << \"Fri Oct 14 09:21:49 CEST 2005\" << \"2005-10-14T07:21:49\";\n dates << \"Tue Mar 23 18:00:02 2004\" << \"2004-03-23T18:00:02\";\n\n QByteArray date;\n for (int i = 0; i < dates.count(); i += 2)\n {\n DwDateTime dwt(dates[i].constData());\n dwt.Parse();\n\n QDateTime test;\n test.setTime_t(dwt.AsUnixTime());\n\n QDateTime iso;\n iso = QDateTime::fromString(dates[i+1], Qt::ISODate);\n iso.setTimeSpec(Qt::UTC);\n \/\/qDebug() << test << iso;\n QVERIFY2(test == iso, dates[i]);\n }\n}\n\n\/\/---------------------------------------------------------------------\n<commit_msg>Add unit test for bug 207766, but it doesn't fail.<commit_after>\/*\n This file is part of the KDE PIM project.\n\n Copyright (C) 2009 Martin Koller <kollix@aon.at>\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 version 2 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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include <qtest_kde.h>\n#include \"testdateparser.h\"\n\n#include <mimelib\/datetime.h>\n\n#include <QList>\n#include <QByteArray>\n\n\/\/---------------------------------------------------------------------\n\nQTEST_KDEMAIN( TestDateParser, NoGUI )\n\n\/\/---------------------------------------------------------------------\n\nvoid TestDateParser::testParsing()\n{\n QList<QByteArray> dates;\n\n \/\/ first of a pair is string to parse (local time),\n \/\/ second is the same in ISO-8601 format (YYYY-MM-DDTHH:MM:SS) UTC\n \/\/ non-RFC2822 dates\n dates << \"Mon Dec 15 11:04:05 PST 2003\" << \"2003-12-15T19:04:05\";\n dates << \"Tue, Feb 04, 2003 00:01:20 +0000\" << \"2003-02-04T00:01:20\";\n dates << \"Tue, Feb 04, 2003 10:01:20 -0220\" << \"2003-02-04T12:21:20\";\n dates << \"Fri, 18 Sep 2009 04:44:55 -0400\" << \"2009-09-18T08:44:55\";\n dates << \"Tue Feb 04, 2003 00:01:20 +0000\" << \"2003-02-04T00:01:20\";\n dates << \"Fri Oct 14 09:21:49 CEST 2005\" << \"2005-10-14T07:21:49\";\n dates << \"Tue Mar 23 18:00:02 2004\" << \"2004-03-23T18:00:02\";\n\n QByteArray date;\n for (int i = 0; i < dates.count(); i += 2)\n {\n DwDateTime dwt(dates[i].constData());\n dwt.Parse();\n\n QDateTime test;\n test.setTime_t(dwt.AsUnixTime());\n\n QDateTime iso;\n iso = QDateTime::fromString(dates[i+1], Qt::ISODate);\n iso.setTimeSpec(Qt::UTC);\n \/\/qDebug() << test << iso;\n QVERIFY2(test == iso, dates[i]);\n }\n}\n\n\/\/---------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <vector>\n#define OK 1 \n#define ERROR 0\n#define LIST_INIT_SIZE 100\n#define LISTINCREMENT 10\n#define ElemType int\n\nint main()\n{\n\tstd::vector<ElemType> v;\n\tint a, i;\n\tElemType e, x;\n\tif(v) \/\/ 判断顺序表是否创建成功\n\t{\n\t\tprintf(\"A Sequence List Has Created.\\n\");\n\t}\n\twhile(1)\n\t{\n\t\tprintf(\"1:Insert element\\n2:Delete element\\n3:Load all elements\\n0:Exit\\nPlease choose:\\n\");\n\t\tscanf(\"%d\",&a);\n\t\tswitch(a)\n\t\t{\n\t\t\tcase 1: scanf(\"%d%d\",&i,&x);\n\t\t\t\t\tvector<ElemType>::iterator I = v.begin();\n\t\t\t\t\tif(v.insert(I,i,x)) printf(\"Insert Error!\\n\"); \/\/ 判断i值是否合法,请填空\n\t\t\t\t\telse printf(\"The Element %d is Successfully Inserted!\\n\", x); \n\t\t\t\t\tbreak;\n\t\t\tcase 2: scanf(\"%d\",&i);\n\t\t\t\t\tvector<ElemType>::iterator I = v.begin();\n\t\t\t\t\tI=I+i;\n\n\t\t\t\t\tif(v.erase(I)) printf(\"Delete Error!\\n\"); \/\/ 判断i值是否合法,请填空\n\t\t\t\t\telse printf(\"The Element %d is Successfully Deleted!\\n\", e);\n\t\t\t\t\tbreak;\n\t\t\tcase 3: \n\t\t\tvector<ElemType>::iterator tempIterator;\n\t\t\tfor( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ )\n \t\t\t\tcout << *tempIterator;\n \t\tcout << endl;\n\t\t\t\t\tbreak;\n\t\t\tcase 0: return 1;\n\t\t}\n\t}\n}<commit_msg>update uoj8576<commit_after>#include <stdio.h>\n#include <vector>\n#define OK 1 \n#define ERROR 0\n#define LIST_INIT_SIZE 100\n#define LISTINCREMENT 10\n#define ElemType int\n\nint main()\n{\n\tstd::vector<ElemType> v;\n\tint a, i;\n\tElemType e, x;\n\tif(v.empty()) \/\/ 判断顺序表是否创建成功\n\t{\n\t\tprintf(\"A Sequence List Has Created.\\n\");\n\t}\n\twhile(1)\n\t{\n\t\tprintf(\"1:Insert element\\n2:Delete element\\n3:Load all elements\\n0:Exit\\nPlease choose:\\n\");\n\t\tscanf(\"%d\",&a);\n\t\tswitch(a)\n\t\t{\n\t\t\tcase 1: scanf(\"%d%d\",&i,&x);\n\t\t\t\t\tvector<ElemType>::iterator I = v.begin();\n\t\t\t\t\tif(v.insert(I,i,x)) printf(\"Insert Error!\\n\"); \/\/ 判断i值是否合法,请填空\n\t\t\t\t\telse printf(\"The Element %d is Successfully Inserted!\\n\", x); \n\t\t\t\t\tbreak;\n\t\t\tcase 2: scanf(\"%d\",&i);\n\t\t\t\t\tvector<ElemType>::iterator I = v.begin();\n\t\t\t\t\tI=I+i;\n\n\t\t\t\t\tif(v.erase(I)) printf(\"Delete Error!\\n\"); \/\/ 判断i值是否合法,请填空\n\t\t\t\t\telse printf(\"The Element %d is Successfully Deleted!\\n\", e);\n\t\t\t\t\tbreak;\n\t\t\tcase 3: \n\t\t\tvector<ElemType>::iterator tempIterator;\n\t\t\tfor( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ )\n \t\t\t\tcout << *tempIterator;\n \t\tcout << endl;\n\t\t\t\t\tbreak;\n\t\t\tcase 0: return 1;\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n#if defined(_MSC_VER)\n\/\/ turn off bogus `this used in base member initialization list'\n# pragma warning(disable: 4786)\n#endif\n\n#include \"global.h\"\n\n\nconst struct GlobalDBItem globalDBItems[] = {\n { \"_agilityAdVel\",\t\t\"2.25\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_agilityTimeWindow\",\t\"1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_agilityVelDelta\",\t \"0.3\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_angleTolerance\",\t\t\"0.01\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_angularAd\",\t\t\"1.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_avenueSize\",\t\t\"2.0*_boxBase\",\t\t\tfalse, StateDatabase::Locked},\n { \"_baseSize\",\t\t\"60.0\", false, StateDatabase::Locked},\n { \"_boxBase\",\t\t\t\"30.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_boxHeight\",\t\t\"6.0*_muzzleHeight\",\t\tfalse, StateDatabase::Locked},\n { \"_burrowAngularAd\",\t\t\"0.55\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_burrowDepth\",\t\t\"-1.32\",\t\t\tfalse, StateDatabase::Locked},\n { \"_burrowSpeedAd\",\t\t\"0.80\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_deadUnder\",\t\t\"-1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_explodeTime\",\t\t\"5.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_fakeLag\",\t\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_flagAltitude\",\t\t\"11.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_flagHeight\",\t\t\"10.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_flagPoleWidth\",\t\t\"0.025\", false, StateDatabase::Locked},\n { \"_flagPoleSize\",\t\t\"0.8\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_flagRadius\",\t\t\"2.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_friction\",\t\t\"0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_gMissileAng\",\t\t\"0.628319\",\t\t\tfalse, StateDatabase::Locked},\n { \"_gMissileAdLife\",\t\t\"0.95\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_gravity\",\t\t\t\"-9.8\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_identifyRange\",\t\t\"50.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_jumpVelocity\",\t\t\"19.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_laserAdLife\",\t\t\"0.1\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_laserAdRate\",\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_laserAdVel\",\t\t\"1000.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_lockOnAngle\",\t\t\"0.15\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_lRAdRate\",\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_maxBumpHeight\",\t\t\"0.33\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_maxFlagGrabs\",\t\t\"4.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_maxLOD\",\t\t\t\"32767.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_momentumAngAcc\",\t\t\"1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_momentumLinAcc\",\t\t\"1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_momentumFriction\",\t\"0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_mGunAdLife\",\t\t\"1.0 \/ _mGunAdRate\",\t\tfalse, StateDatabase::Locked},\n { \"_mGunAdRate\",\t\t\"10.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_mGunAdVel\",\t\t\"1.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_muzzleFront\",\t\t\"_tankRadius + 0.1\",\t\tfalse, StateDatabase::Locked},\n { \"_muzzleHeight\",\t\t\"1.57\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_notRespondingTime\",\t\"5.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_obeseFactor\",\t\t\"2.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_pauseDropTime\",\t\t\"15.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_positionTolerance\",\t\"0.01\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_pyrBase\",\t\t\t\"4.0*_tankHeight\",\t\tfalse, StateDatabase::Locked},\n { \"_pyrHeight\",\t\t\"5.0*_tankHeight\",\t\tfalse, StateDatabase::Locked},\n { \"_rejoinTime\",\t\t\"10.0\",\t false, StateDatabase::Locked},\n { \"_reloadTime\",\t\t\"_shotRange \/ _shotSpeed\",\tfalse, StateDatabase::Locked},\n { \"_rFireAdLife\",\t\t\"1.0 \/ _rFireAdRate\",\t\tfalse, StateDatabase::Locked},\n { \"_rFireAdRate\",\t\t\"2.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_rFireAdVel\",\t\t\"1.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shieldFlight\",\t\t\"2.7\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shockAdLife\",\t\t\"0.2\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shockInRadius\",\t\t\"_tankLength\",\t\t\tfalse, StateDatabase::Locked},\n { \"_shockOutRadius\",\t\t\"60.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shotTailLength\",\t\t\"4.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shotRadius\",\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shotRange\",\t\t\"350.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_shotSpeed\",\t\t\"100.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_shotsKeepVerticalVelocity\",\t\"0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_srRadiusMult\",\t\t\"2.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_syncTime\",\t\t\"0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_tankExplosionSize\",\t\"3.5 * _tankLength\", \t\tfalse, StateDatabase::Locked},\n { \"_tankAngVel\",\t\t\"0.785398\", \t\t\tfalse, StateDatabase::Locked},\n { \"_tankHeight\",\t\t\"2.05\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_tankLength\",\t\t\"6.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_tankRadius\",\t\t\"0.72 * _tankLength\",\t\tfalse, StateDatabase::Locked},\n { \"_tankSpeed\",\t\t\"25.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_tankWidth\",\t\t\"2.8\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_targetingAngle\",\t\t\"0.3\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_teleportBreadth\",\t\t\"4.48\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_teleportHeight\",\t\t\"10.08\",\t\t\tfalse, StateDatabase::Locked},\n { \"_teleportTime\",\t\t\"1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_teleportWidth\",\t\t\"1.12\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefAdLife\",\t\t\"0.05\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefAdRate\",\t\t\"12.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefAdShotVel\",\t\t\"8.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefTinyFactor\",\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefVelAd\",\t\t\"1.67\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefDropTime\",\t\t\"_reloadTime * 0.5\",\t\tfalse, StateDatabase::Locked},\n { \"_tinyFactor\",\t\t\"0.4\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_updateThrottleRate\",\t\"30.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_velocityAd\",\t\t\"1.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_wallHeight\",\t\t\"3.0*_tankHeight\",\t\tfalse, StateDatabase::Locked},\n { \"_wideAngleAng\",\t\t\"1.745329\", \t\t\tfalse, StateDatabase::Locked},\n { \"_wingsGravity\",\t\t\"_gravity\",\t\t\tfalse, StateDatabase::Locked},\n { \"_wingsJumpCount\",\t\t\"1\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_wingsJumpVelocity\",\t\"_jumpVelocity\",\t\tfalse, StateDatabase::Locked},\n { \"_worldSize\",\t\t\"800.0\",\t\t\tfalse, StateDatabase::Locked}\n};\nconst unsigned int\tnumGlobalDBItems = countof(globalDBItems);\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>default deadUnder should be near -Inf so that it's disabled -- -32767 is close (-1 kills burrow)<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n#if defined(_MSC_VER)\n\/\/ turn off bogus `this used in base member initialization list'\n# pragma warning(disable: 4786)\n#endif\n\n#include \"global.h\"\n\n\nconst struct GlobalDBItem globalDBItems[] = {\n { \"_agilityAdVel\",\t\t\"2.25\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_agilityTimeWindow\",\t\"1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_agilityVelDelta\",\t \"0.3\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_angleTolerance\",\t\t\"0.01\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_angularAd\",\t\t\"1.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_avenueSize\",\t\t\"2.0*_boxBase\",\t\t\tfalse, StateDatabase::Locked},\n { \"_baseSize\",\t\t\"60.0\", false, StateDatabase::Locked},\n { \"_boxBase\",\t\t\t\"30.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_boxHeight\",\t\t\"6.0*_muzzleHeight\",\t\tfalse, StateDatabase::Locked},\n { \"_burrowAngularAd\",\t\t\"0.55\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_burrowDepth\",\t\t\"-1.32\",\t\t\tfalse, StateDatabase::Locked},\n { \"_burrowSpeedAd\",\t\t\"0.80\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_deadUnder\",\t\t\"-32767.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_explodeTime\",\t\t\"5.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_fakeLag\",\t\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_flagAltitude\",\t\t\"11.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_flagHeight\",\t\t\"10.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_flagPoleWidth\",\t\t\"0.025\", false, StateDatabase::Locked},\n { \"_flagPoleSize\",\t\t\"0.8\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_flagRadius\",\t\t\"2.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_friction\",\t\t\"0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_gMissileAng\",\t\t\"0.628319\",\t\t\tfalse, StateDatabase::Locked},\n { \"_gMissileAdLife\",\t\t\"0.95\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_gravity\",\t\t\t\"-9.8\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_identifyRange\",\t\t\"50.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_jumpVelocity\",\t\t\"19.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_laserAdLife\",\t\t\"0.1\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_laserAdRate\",\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_laserAdVel\",\t\t\"1000.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_lockOnAngle\",\t\t\"0.15\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_lRAdRate\",\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_maxBumpHeight\",\t\t\"0.33\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_maxFlagGrabs\",\t\t\"4.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_maxLOD\",\t\t\t\"32767.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_momentumAngAcc\",\t\t\"1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_momentumLinAcc\",\t\t\"1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_momentumFriction\",\t\"0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_mGunAdLife\",\t\t\"1.0 \/ _mGunAdRate\",\t\tfalse, StateDatabase::Locked},\n { \"_mGunAdRate\",\t\t\"10.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_mGunAdVel\",\t\t\"1.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_muzzleFront\",\t\t\"_tankRadius + 0.1\",\t\tfalse, StateDatabase::Locked},\n { \"_muzzleHeight\",\t\t\"1.57\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_notRespondingTime\",\t\"5.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_obeseFactor\",\t\t\"2.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_pauseDropTime\",\t\t\"15.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_positionTolerance\",\t\"0.01\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_pyrBase\",\t\t\t\"4.0*_tankHeight\",\t\tfalse, StateDatabase::Locked},\n { \"_pyrHeight\",\t\t\"5.0*_tankHeight\",\t\tfalse, StateDatabase::Locked},\n { \"_rejoinTime\",\t\t\"10.0\",\t false, StateDatabase::Locked},\n { \"_reloadTime\",\t\t\"_shotRange \/ _shotSpeed\",\tfalse, StateDatabase::Locked},\n { \"_rFireAdLife\",\t\t\"1.0 \/ _rFireAdRate\",\t\tfalse, StateDatabase::Locked},\n { \"_rFireAdRate\",\t\t\"2.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_rFireAdVel\",\t\t\"1.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shieldFlight\",\t\t\"2.7\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shockAdLife\",\t\t\"0.2\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shockInRadius\",\t\t\"_tankLength\",\t\t\tfalse, StateDatabase::Locked},\n { \"_shockOutRadius\",\t\t\"60.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shotTailLength\",\t\t\"4.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shotRadius\",\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_shotRange\",\t\t\"350.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_shotSpeed\",\t\t\"100.0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_shotsKeepVerticalVelocity\",\t\"0\",\t\t\tfalse, StateDatabase::Locked},\n { \"_srRadiusMult\",\t\t\"2.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_syncTime\",\t\t\"0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_tankExplosionSize\",\t\"3.5 * _tankLength\", \t\tfalse, StateDatabase::Locked},\n { \"_tankAngVel\",\t\t\"0.785398\", \t\t\tfalse, StateDatabase::Locked},\n { \"_tankHeight\",\t\t\"2.05\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_tankLength\",\t\t\"6.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_tankRadius\",\t\t\"0.72 * _tankLength\",\t\tfalse, StateDatabase::Locked},\n { \"_tankSpeed\",\t\t\"25.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_tankWidth\",\t\t\"2.8\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_targetingAngle\",\t\t\"0.3\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_teleportBreadth\",\t\t\"4.48\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_teleportHeight\",\t\t\"10.08\",\t\t\tfalse, StateDatabase::Locked},\n { \"_teleportTime\",\t\t\"1.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_teleportWidth\",\t\t\"1.12\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefAdLife\",\t\t\"0.05\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefAdRate\",\t\t\"12.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefAdShotVel\",\t\t\"8.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefTinyFactor\",\t\t\"0.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefVelAd\",\t\t\"1.67\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_thiefDropTime\",\t\t\"_reloadTime * 0.5\",\t\tfalse, StateDatabase::Locked},\n { \"_tinyFactor\",\t\t\"0.4\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_updateThrottleRate\",\t\"30.0\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_velocityAd\",\t\t\"1.5\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_wallHeight\",\t\t\"3.0*_tankHeight\",\t\tfalse, StateDatabase::Locked},\n { \"_wideAngleAng\",\t\t\"1.745329\", \t\t\tfalse, StateDatabase::Locked},\n { \"_wingsGravity\",\t\t\"_gravity\",\t\t\tfalse, StateDatabase::Locked},\n { \"_wingsJumpCount\",\t\t\"1\",\t\t\t\tfalse, StateDatabase::Locked},\n { \"_wingsJumpVelocity\",\t\"_jumpVelocity\",\t\tfalse, StateDatabase::Locked},\n { \"_worldSize\",\t\t\"800.0\",\t\t\tfalse, StateDatabase::Locked}\n};\nconst unsigned int\tnumGlobalDBItems = countof(globalDBItems);\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>#include \"utils\/mempool.hpp\"\n\n#include <new>\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n\n#define MOVE_BYTES(base, offset) \\\n reinterpret_cast<decltype(base)>(reinterpret_cast<uint8_t*>(base) + offset)\n\n#define CONTAINER_OF(containerType, memberName, memberAddress) \\\n reinterpret_cast<containerType*>(MOVE_BYTES(memberAddress, -offsetof(containerType, memberName)))\n\nnamespace impl = Compiler::Utils;\n\nusing namespace Compiler::Utils;\n\nstatic constexpr auto BLOCK_SIZE = 1 << 12; \/\/ 4KB\nstatic constexpr auto SIZES = 8; \/\/ difference size of memory, 8, 16, 24, 32, 40, 48, 56, 64\nstatic constexpr auto MAX_SIZE = 8 * SIZES;\n\nstruct ListBlock {\n ListBlock *next;\n};\n\n\/**\n * StandardLayout and layout-compatible with ListBlock,\n * and both have a next field which are semantically equal.\n * so DoubleLinkedBlock* can be safely casted to ListBlock*,\n * so we do not need a freeList(DoubleLinkedBlock*) version\n *\/\nstruct DoubleLinkedBlock {\n DoubleLinkedBlock *next;\n DoubleLinkedBlock *prev;\n uint8_t data[0];\n};\n\nstruct PoolBlock {\n \/**< first node of free list *\/\n ListBlock *freeList;\n \/**< points to first node of chunk list *\/\n ListBlock *chunk;\n};\n\ntemplate <class T>\nstatic inline T* managedMalloc(std::size_t additional = 0) noexcept(false) {\n auto ret = malloc(additional + sizeof(T));\n if(!ret)\n throw std::bad_alloc{};\n return static_cast<T*>(ret);\n}\n\nstatic inline void* managedRealloc(void *src, std::size_t newsize) noexcept(false) {\n auto ret = realloc(src, newsize);\n if(!ret)\n throw std::bad_alloc{};\n return ret;\n}\n\nstatic inline void managedFree(void *mem) noexcept {\n free(mem);\n}\n\n\/**\n * See if lowest 3 bit of pointer address is not 0\n * @param ptr pointer address\n *\/\nstatic inline bool lowest3bitSet(void *ptr) noexcept {\n return (reinterpret_cast<uintptr_t>(ptr) & 7);\n}\n\n\/**\n * Make address 8-byte aligned\n * @param ptr pointer address\n * @return aligned address\n *\/\nstatic inline void* align8Pointer(void *ptr) noexcept {\n if(lowest3bitSet(ptr)) {\n auto &&uintptr = reinterpret_cast<uintptr_t&>(ptr);\n uintptr &= ~7U;\n uintptr += 8;\n }\n return ptr;\n}\n\n\/**\n * Calculate size of memory block\n * @param size requested size\n * @return actual size of memory block\n *\/\nstatic inline unsigned sizeOf(unsigned size) noexcept {\n assert(size != 0);\n return size < MAX_SIZE ? (size + 7) & ~7U : size;\n}\n\n\/**\n * Calculate index of MemBlock in whole MemPool\n * @param size requested size\n * @return index to chunks array\n *\/\nstatic inline unsigned indexOf(unsigned size) noexcept {\n assert(size != 0);\n return size < MAX_SIZE ? ((size + 7) >> 3) - 1 : SIZES;\n}\n\nstatic inline PoolBlock* chunkAt(void *base, unsigned index) noexcept {\n return static_cast<PoolBlock*>(base) + index;\n}\n\n\/**\n * Allocate a memory block used as chunk, then attach to a PoolBlock\n * @param owner owner of this chunk\n * @param blockSize size of small block\n * @return first available memory block of this new chunk\n *\/\nstatic ListBlock* addChunk(PoolBlock *owner, unsigned blockSize) {\n auto count = BLOCK_SIZE \/ blockSize;\n auto chunk = managedMalloc<ListBlock>(BLOCK_SIZE);\n \n auto mem = chunk + 1;\n while(count--) {\n auto next = MOVE_BYTES(mem, blockSize);\n mem->next = next;\n mem = next;\n }\n \n chunk->next = owner->chunk;\n owner->chunk = chunk;\n \n mem->next = owner->freeList;\n owner->freeList = chunk + 1;\n \n return chunk + 1;\n}\n\n\/**\n * Allocate an arbitary size of memory, then attach it to PoolBlock\n * @param owner owner of this memory\n * @param blockSize size of this memory\n * @return available memory of this memory block\n *\/\nstatic void* arbitarySizedBlock(PoolBlock *owner, unsigned blockSize) {\n auto block = managedMalloc<DoubleLinkedBlock>(blockSize);\n \n auto first = reinterpret_cast<DoubleLinkedBlock*>(owner->chunk);\n if(first)\n first->prev = block;\n block->next = first;\n block->prev = nullptr;\n \n owner->chunk = reinterpret_cast<ListBlock*>(block);\n return block->data;\n}\n\nMemPool impl::pool{};\n\nclass MemPool::AlignedTag {};\n\nMemPool::AlignedTag MemPool::aligned{};\n\nMemPool::MemPool() {\n auto chunks = managedMalloc<PoolBlock>(SIZES * sizeof(PoolBlock));\n for(auto i=0; i<SIZES+1; ++i) {\n chunks[i].chunk = nullptr;\n chunks[i].freeList = nullptr;\n }\n}\n\nMemPool::~MemPool() noexcept {\n clear();\n managedFree(m_chunks);\n}\n\nvoid* MemPool::allocate(unsigned size) {\n auto index = indexOf(size);\n auto chunk = chunkAt(m_chunks, index);\n \n if(index == SIZES) \n return arbitarySizedBlock(chunk, size);\n \n auto block = chunk->freeList;\n if(!block) \n block = addChunk(chunk, sizeOf(size));\n \n chunk->freeList = block->next;\n return block;\n}\n\nvoid* MemPool::align8Allocate(unsigned size) {\n auto index = indexOf(size);\n assert(index < SIZES);\n \n auto chunk = chunkAt(m_chunks, index);\n ListBlock *first = chunk->freeList, *prev = nullptr;\n while(first) {\n if(lowest3bitSet(first)) {\n if(!prev)\n chunk->freeList = first->next;\n else\n prev->next = first->next;\n return first;\n }\n prev = first;\n first = first->next;\n }\n \n return align8Pointer(allocate(size + 8));\n}\n\nvoid* MemPool::reallocate(void *current, unsigned oldSize, unsigned newSize) {\n if(oldSize >= newSize || sizeOf(oldSize) == sizeOf(newSize))\n return current;\n if(indexOf(oldSize) == SIZES) \n return managedRealloc(current, newSize);\n \n auto ret = memcpy(allocate(newSize), current, oldSize);\n deallocate(current, oldSize);\n return ret;\n}\n\nvoid MemPool::deallocate(void *mem, unsigned size) noexcept {\n if(!mem)\n return;\n auto index = indexOf(size);\n auto chunk = chunkAt(m_chunks, index);\n \n if(index == SIZES) {\n auto block = CONTAINER_OF(DoubleLinkedBlock, data, mem);\n auto prev = block->prev;\n auto next = block->next;\n if(prev)\n prev->next = next;\n if(next)\n next->prev = prev;\n managedFree(block);\n return;\n }\n \n auto block = static_cast<ListBlock*>(mem);\n block->next = chunk->freeList;\n chunk->freeList = block;\n}\n\nvoid MemPool::clear() noexcept {\n auto chunks = static_cast<PoolBlock*>(m_chunks);\n for(auto i=0; i<SIZES; ++i, ++chunks) {\n auto head = chunks->chunk;\n while(head) {\n auto save = head->next;\n managedFree(head);\n head = save;\n }\n chunks->chunk = nullptr;\n chunks->freeList = nullptr;\n }\n}\n\nvoid* operator new(std::size_t size, MemPool &pool) {\n return pool.allocate(size);\n}\n\nvoid* operator new(std::size_t size, MemPool &pool, const MemPool::AlignedTag &) {\n return pool.align8Allocate(size);\n}\n\nvoid operator delete(void* mem, std::size_t size, Compiler::Utils::MemPool& pool) noexcept {\n pool.deallocate(mem, size);\n}\n<commit_msg>fix mempool<commit_after>#include \"utils\/mempool.hpp\"\n\n#include <new>\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n\n#define MOVE_BYTES(base, offset) \\\n reinterpret_cast<decltype(base)>(reinterpret_cast<uint8_t*>(base) + offset)\n\n#define CONTAINER_OF(containerType, memberName, memberAddress) \\\n reinterpret_cast<containerType*>(MOVE_BYTES(memberAddress, -offsetof(containerType, memberName)))\n\nnamespace impl = Compiler::Utils;\n\nusing namespace Compiler::Utils;\n\nstatic constexpr auto BLOCK_SIZE = 1 << 12; \/\/ 4KB\nstatic constexpr auto SIZES = 8; \/\/ difference size of memory, 8, 16, 24, 32, 40, 48, 56, 64\nstatic constexpr auto MAX_SIZE = 8 * SIZES;\n\nstruct ListBlock {\n ListBlock *next;\n};\n\n\/**\n * StandardLayout and layout-compatible with ListBlock,\n * and both have a next field that are semantically equal.\n * So DualLinkedBlock* can be safely casted to ListBlock*,\n * and can share a same deallcation function.\n *\/\nstruct DualLinkedBlock {\n DualLinkedBlock *next;\n DualLinkedBlock *prev;\n uint8_t data[0];\n \n \/**\n * Fix pointer linkage after reallocation.\n *\/\n inline void fixLinkage() noexcept {\n if(prev)\n prev->next = this;\n if(next)\n next->prev = this;\n }\n \n \/**\n * Remove this block from a doubly-linked list\n *\/\n inline void removeThis() noexcept {\n if(prev)\n prev->next = next;\n if(next)\n next->prev = prev;\n }\n};\n\nstruct PoolBlock {\n \/**< first node of free list *\/\n ListBlock *freeList;\n \/**< points to first node of chunk list *\/\n ListBlock *chunk;\n};\n\ntemplate <class T>\nstatic inline T* managedMalloc(std::size_t additional = 0) noexcept(false) {\n auto ret = malloc(additional + sizeof(T));\n if(!ret)\n throw std::bad_alloc{};\n return static_cast<T*>(ret);\n}\n\ntemplate <class T>\nstatic inline T* managedRealloc(T *src, std::size_t newsize) noexcept(false) {\n auto ret = realloc(src, newsize + sizeof(T));\n if(!ret)\n throw std::bad_alloc{};\n return static_cast<T*>(ret);\n}\n\nstatic inline void managedFree(void *mem) noexcept {\n free(mem);\n}\n\n\/**\n * See if lowest 3 bit of pointer address is not 0\n * @param ptr pointer address\n *\/\nstatic inline bool lowest3bitSet(void *ptr) noexcept {\n return (reinterpret_cast<uintptr_t>(ptr) & 7);\n}\n\n\/**\n * Make address 8-byte aligned\n * @param ptr pointer address\n * @return aligned address\n *\/\nstatic inline void* align8Pointer(void *ptr) noexcept {\n if(lowest3bitSet(ptr)) {\n auto &&uintptr = reinterpret_cast<uintptr_t&>(ptr);\n uintptr &= ~7U;\n uintptr += 8;\n }\n return ptr;\n}\n\n\/**\n * Calculate size of memory block\n * @param size requested size\n * @return actual size of memory block\n *\/\nstatic inline unsigned sizeOf(unsigned size) noexcept {\n assert(size != 0);\n return size < MAX_SIZE ? (size + 7) & ~7U : size;\n}\n\n\/**\n * Calculate index of MemBlock in whole MemPool\n * @param size requested size\n * @return index to chunks array\n *\/\nstatic inline unsigned indexOf(unsigned size) noexcept {\n assert(size != 0);\n return size < MAX_SIZE ? ((size + 7) >> 3) - 1 : SIZES;\n}\n\nstatic inline PoolBlock* chunkAt(void *base, unsigned index) noexcept {\n return static_cast<PoolBlock*>(base) + index;\n}\n\n\/**\n * Allocate a memory block used as chunk, then attach to a PoolBlock\n * @param owner owner of this chunk\n * @param blockSize size of small block\n * @return first available memory block of this new chunk\n *\/\nstatic ListBlock* addChunk(PoolBlock *owner, unsigned blockSize) {\n auto count = BLOCK_SIZE \/ blockSize;\n auto chunk = managedMalloc<ListBlock>(BLOCK_SIZE);\n \n auto mem = chunk + 1;\n while(count--) {\n auto next = MOVE_BYTES(mem, blockSize);\n mem->next = next;\n mem = next;\n }\n \n chunk->next = owner->chunk;\n owner->chunk = chunk;\n \n mem->next = owner->freeList;\n owner->freeList = chunk + 1;\n \n return chunk + 1;\n}\n\n\/**\n * Allocate an arbitary size of memory, then attach it to PoolBlock\n * @param owner owner of this memory\n * @param blockSize size of this memory\n * @return available memory of this memory block\n *\/\nstatic void* arbitarySizedBlock(PoolBlock *owner, unsigned blockSize) {\n auto block = managedMalloc<DualLinkedBlock>(blockSize);\n \n auto first = reinterpret_cast<DualLinkedBlock *>(owner->chunk);\n if(first)\n first->prev = block;\n block->next = first;\n block->prev = nullptr;\n \n owner->chunk = reinterpret_cast<ListBlock*>(block);\n return block->data;\n}\n\nMemPool impl::pool{};\n\nclass MemPool::AlignedTag {};\n\nMemPool::AlignedTag MemPool::aligned{};\n\nMemPool::MemPool() {\n auto chunks = managedMalloc<PoolBlock>(SIZES * sizeof(PoolBlock));\n for(auto i=0; i<SIZES+1; ++i) {\n chunks[i].chunk = nullptr;\n chunks[i].freeList = nullptr;\n }\n}\n\nMemPool::~MemPool() noexcept {\n clear();\n managedFree(m_chunks);\n}\n\nvoid* MemPool::allocate(unsigned size) {\n auto index = indexOf(size);\n auto chunk = chunkAt(m_chunks, index);\n \n if(index == SIZES) \n return arbitarySizedBlock(chunk, size);\n \n auto block = chunk->freeList;\n if(!block) \n block = addChunk(chunk, sizeOf(size));\n \n chunk->freeList = block->next;\n return block;\n}\n\nvoid* MemPool::align8Allocate(unsigned size) {\n auto index = indexOf(size);\n assert(index < SIZES);\n \n auto chunk = chunkAt(m_chunks, index);\n ListBlock *first = chunk->freeList, *prev = nullptr;\n while(first) {\n if(!lowest3bitSet(first)) {\n if(!prev)\n chunk->freeList = first->next;\n else\n prev->next = first->next;\n return first;\n }\n prev = first;\n first = first->next;\n }\n \n return align8Pointer(allocate(size + 8));\n}\n\nvoid* MemPool::reallocate(void *current, unsigned oldSize, unsigned newSize) {\n if(oldSize >= newSize || sizeOf(oldSize) == sizeOf(newSize))\n return current;\n if(indexOf(oldSize) == SIZES) {\n auto block = CONTAINER_OF(DualLinkedBlock, data, current);\n auto newblock = managedRealloc(block, newSize);\n newblock->fixLinkage();\n return newblock->data;\n }\n auto ret = memcpy(allocate(newSize), current, oldSize);\n deallocate(current, oldSize);\n return ret;\n}\n\nvoid MemPool::deallocate(void *mem, unsigned size) noexcept {\n if(!mem)\n return;\n auto index = indexOf(size);\n auto chunk = chunkAt(m_chunks, index);\n \n if(index == SIZES) {\n auto block = CONTAINER_OF(DualLinkedBlock, data, mem);\n block->removeThis();\n managedFree(block);\n return;\n }\n \n auto block = static_cast<ListBlock*>(mem);\n block->next = chunk->freeList;\n chunk->freeList = block;\n}\n\nvoid MemPool::clear() noexcept {\n auto chunks = static_cast<PoolBlock*>(m_chunks);\n for(auto i=0; i<SIZES; ++i, ++chunks) {\n auto head = chunks->chunk;\n while(head) {\n auto save = head->next;\n managedFree(head);\n head = save;\n }\n chunks->chunk = nullptr;\n chunks->freeList = nullptr;\n }\n}\n\nvoid* operator new(std::size_t size, MemPool &pool) {\n return pool.allocate(size);\n}\n\nvoid* operator new(std::size_t size, MemPool &pool, const MemPool::AlignedTag &) {\n return pool.align8Allocate(size);\n}\n\nvoid operator delete(void* mem, std::size_t size, Compiler::Utils::MemPool& pool) noexcept {\n pool.deallocate(mem, size);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Stuff stolen from the Internet.<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * studentCollection_class.cpp\n *\n * Author: Patrick Rummage <patrickbrummage@gmail.com>\n *\n * Objective:\n *\n *\/\n#include <iostream>\nusing std::cin;\nusing std::cout;\n\nstruct studentRecord {\n int studentID;\n int grade;\n char* name;\n};\n\nclass studentCollection {\n private:\n struct studentNode {\n studentRecord studentData;\n studentNode* next;\n };\n\n public:\n studentCollection();\n ~studentCollection();\n void addRecord(studentRecord newStudent);\n studentRecord recordWithNumber(int idNum);\n double averageRecord();\n studentCollection recordsWithinRange(int low, int high);\n void removeRecord(int idNum);\n studentNode* copiedList(const studentNode* original);\n studentCollection& operator=(const studentCollection& rhs);\n\n private:\n studentNode* _listHead;\n void deleteList(studentNode* &listPtr);\n};\n\nstudentCollection::studentCollection() {\n _listHead = NULL;\n}\n\nvoid studentCollection::addRecord(studentRecord newStudent) {\n studentNode* newNode = new studentNode;\n newNode->studentData = newStudent;\n newNode->next = _listHead; \/\/ Previous first item\n _listHead = newNode;\n}\n\nstudentRecord studentCollection::recordWithNumber(int idNum) {\n studentNode* loopPtr = _listHead;\n while (loopPtr != NULL && loopPtr->studentData.studentID != idNum) {\n loopPtr = loopPtr->next;\n }\n if (loopPtr == NULL) {\n studentRecord dummyRecord{-1,-1,\"VOID\"};\n return dummyRecord;\n } else {\n return loopPtr->studentData;\n }\n}\n\ndouble studentCollection::averageRecord() {\n if (_listHead == NULL) { \/\/ Handle empty list\n return 0;\n }\n int count = 0;\n int sum = 0;\n studentNode* listPtr = _listHead;\n while (listPtr != NULL) {\n sum += listPtr->studentData.grade;\n count++;\n listPtr = listPtr->next;\n }\n double average = sum \/ count; \n return average;\n}\n\nvoid studentCollection::removeRecord(int idNum) {\n studentNode* loopPtr = _listHead;\n studentNode* previous = NULL;\n while (loopPtr != NULL && loopPtr->studentData.studentID != idNum) {\n previous = loopPtr;\n loopPtr = loopPtr->next;\n }\n if (loopPtr == NULL) { \/\/ Not found\n return;\n }\n if (previous == NULL) { \/\/ Removing first node\n _listHead = _listHead->next;\n } else { \/\/ Join nodes before and after one to be deleted\n previous->next = loopPtr->next;\n }\n delete loopPtr;\n}\n\nvoid studentCollection::deleteList(studentNode* &listPtr) {\n while (listPtr != NULL) {\n studentNode* temp = listPtr;\n listPtr = listPtr->next;\n delete temp;\n }\n}\n\nstudentCollection studentCollection::recordsWithinRange(int low, int high) {\n studentCollection newCollection;\n studentNode* listPtr = _listHead;\n int studentGrade;\n while (listPtr != NULL) {\n studentGrade = listPtr->studentData.grade; \n if (studentGrade >= low && studentGrade <= high) {\n newCollection.addRecord(listPtr->studentData); \n }\n listPtr = listPtr->next;\n }\n return newCollection;\n}\n\nstudentCollection::studentNode*\nstudentCollection::copiedList(const studentNode* original) {\n if (original == NULL) {\n return NULL;\n }\n studentNode* newList = new studentNode;\n newList->studentData = original->studentData;\n studentNode* oldLoopPtr = original->next;\n studentNode* newLoopPtr = newList;\n while(oldLoopPtr != NULL) {\n newLoopPtr->next = new studentNode;\n newLoopPtr = newLoopPtr->next;\n newLoopPtr->studentData = oldLoopPtr->studentData;\n oldLoopPtr = oldLoopPtr->next;\n }\n newLoopPtr->next = NULL;\n return newList;\n}\n\nstudentCollection::~studentCollection() {\n deleteList(_listHead);\n}\n\nstudentCollection& studentCollection::operator=(const studentCollection& rhs) {\n if (this != &rhs) {\n deleteList(_listHead);\n _listHead = copiedList(rhs._listHead);\n }\n return *this;\n}\n\nint main (int argc, char* argv[]) {\n studentCollection collection1;\n collection1.addRecord(studentRecord{0,100,\"Peace\"});\n collection1.addRecord(studentRecord{1,50,\"Scrimbles\"});\n\n studentCollection collection2 = collection1;\n collection2.addRecord(studentRecord{2,25,\"Grizzabella\"});\n\n double average = collection1.averageRecord();\n double average2 = collection2.averageRecord();\n cout << average << '\\n';\n cout << average2 << '\\n';\n\n return 0;\n}\n<commit_msg>added print method<commit_after>\/**\n * studentCollection_class.cpp\n *\n * Author: Patrick Rummage <patrickbrummage@gmail.com>\n *\n * Objective:\n *\n *\/\n#include <iostream>\nusing std::cin;\nusing std::cout;\n\nstruct studentRecord {\n int studentID;\n int grade;\n char* name;\n};\n\nclass studentCollection {\n private:\n struct studentNode {\n studentRecord studentData;\n studentNode* next;\n };\n\n public:\n studentCollection();\n ~studentCollection();\n void printList() const;\n void addRecord(studentRecord newStudent);\n studentRecord recordWithNumber(int idNum);\n double averageRecord();\n studentCollection recordsWithinRange(int low, int high);\n void removeRecord(int idNum);\n studentNode* copiedList(const studentNode* original);\n studentCollection& operator=(const studentCollection& rhs);\n\n private:\n studentNode* _listHead;\n void deleteList(studentNode* &listPtr);\n};\n\nstudentCollection::studentCollection() {\n _listHead = NULL;\n}\n\nvoid studentCollection::printList() const {\n studentNode* listPtr = _listHead;\n while (listPtr != NULL) {\n cout << listPtr->studentData.studentID << \", \" << listPtr->studentData.grade <<\n \", \" << listPtr->studentData.name << '\\n';\n listPtr = listPtr->next;\n }\n}\n\nvoid studentCollection::addRecord(studentRecord newStudent) {\n studentNode* newNode = new studentNode;\n newNode->studentData = newStudent;\n newNode->next = _listHead; \/\/ Previous first item\n _listHead = newNode;\n}\n\nstudentRecord studentCollection::recordWithNumber(int idNum) {\n studentNode* loopPtr = _listHead;\n while (loopPtr != NULL && loopPtr->studentData.studentID != idNum) {\n loopPtr = loopPtr->next;\n }\n if (loopPtr == NULL) {\n studentRecord dummyRecord{-1,-1,\"VOID\"};\n return dummyRecord;\n } else {\n return loopPtr->studentData;\n }\n}\n\ndouble studentCollection::averageRecord() {\n if (_listHead == NULL) { \/\/ Handle empty list\n return 0;\n }\n int count = 0;\n int sum = 0;\n studentNode* listPtr = _listHead;\n while (listPtr != NULL) {\n sum += listPtr->studentData.grade;\n count++;\n listPtr = listPtr->next;\n }\n double average = sum \/ count; \n return average;\n}\n\nvoid studentCollection::removeRecord(int idNum) {\n studentNode* loopPtr = _listHead;\n studentNode* previous = NULL;\n while (loopPtr != NULL && loopPtr->studentData.studentID != idNum) {\n previous = loopPtr;\n loopPtr = loopPtr->next;\n }\n if (loopPtr == NULL) { \/\/ Not found\n return;\n }\n if (previous == NULL) { \/\/ Removing first node\n _listHead = _listHead->next;\n } else { \/\/ Join nodes before and after one to be deleted\n previous->next = loopPtr->next;\n }\n delete loopPtr;\n}\n\nvoid studentCollection::deleteList(studentNode* &listPtr) {\n while (listPtr != NULL) {\n studentNode* temp = listPtr;\n listPtr = listPtr->next;\n delete temp;\n }\n}\n\nstudentCollection studentCollection::recordsWithinRange(int low, int high) {\n studentCollection newCollection;\n studentNode* listPtr = _listHead;\n int studentGrade;\n while (listPtr != NULL) {\n studentGrade = listPtr->studentData.grade; \n if (studentGrade >= low && studentGrade <= high) {\n newCollection.addRecord(listPtr->studentData); \n }\n listPtr = listPtr->next;\n }\n return newCollection;\n}\n\nstudentCollection::studentNode*\nstudentCollection::copiedList(const studentNode* original) {\n if (original == NULL) {\n return NULL;\n }\n studentNode* newList = new studentNode;\n newList->studentData = original->studentData;\n studentNode* oldLoopPtr = original->next;\n studentNode* newLoopPtr = newList;\n while(oldLoopPtr != NULL) {\n newLoopPtr->next = new studentNode;\n newLoopPtr = newLoopPtr->next;\n newLoopPtr->studentData = oldLoopPtr->studentData;\n oldLoopPtr = oldLoopPtr->next;\n }\n newLoopPtr->next = NULL;\n return newList;\n}\n\nstudentCollection::~studentCollection() {\n deleteList(_listHead);\n}\n\nstudentCollection& studentCollection::operator=(const studentCollection& rhs) {\n if (this != &rhs) {\n deleteList(_listHead);\n _listHead = copiedList(rhs._listHead);\n }\n return *this;\n}\n\n\/\/-----------------------------------------------------------------------------\nstd::ostream& operator<<(std::ostream& ost, const studentCollection& sc) {\n sc.printList();\n \n return ost;\n}\n\nint main (int argc, char* argv[]) {\n studentCollection collection1;\n collection1.addRecord(studentRecord{0,100,\"Peace\"});\n collection1.addRecord(studentRecord{1,50,\"Scrimbles\"});\n\n studentCollection collection2 = collection1;\n collection2.addRecord(studentRecord{2,25,\"Grizzabella\"});\n\n double average = collection1.averageRecord();\n double average2 = collection2.averageRecord();\n cout << average << '\\n';\n cout << average2 << '\\n';\n\n cout << collection2 << '\\n';\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.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 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\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n#include <cppunit\/TextTestRunner.h>\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#ifndef TM_IN_SYS_TIME\n#include <time.h>\n#else\n#include <sys\/time.h>\n#endif\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h> \/\/ for stat\n\n#include <string>\n#include <sstream>\n\n#include \"Ancillary.h\"\n#include \"DDS.h\"\n#include \"debug.h\"\n\n#include \"run_tests_cppunit.h\"\n#include \"run_tests_cppunit.h\"\n#include \"test_config.h\"\n\n\nusing namespace CppUnit;\nusing namespace std;\nusing namespace libdap;\n\nclass ancT: public TestFixture {\nprivate:\n\nprotected:\n\npublic:\n ancT() = default;\n ~ancT() = default;\n\n CPPUNIT_TEST_SUITE (ancT);\n\n CPPUNIT_TEST (find_ancillary_file_test);\n CPPUNIT_TEST (find_group_ancillary_file_test);\n CPPUNIT_TEST (read_ancillary_das_file_test);\n\n CPPUNIT_TEST_SUITE_END();\n\n void find_ancillary_file_test()\n {\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/test.1\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/special.test.hdf\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/special.test.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/test.2\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.gz\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/test.3.Z\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test.3.Z.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testste\/test_1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testsuite\/\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test_1.das\");\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/te1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testite\/\", \"\"); \n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/te1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testite\/\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testste\/test1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testsuite\/\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testste\/test1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testsuite\/\", \"test.1\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testste\/test1\", \"ds\", (string) TEST_SRC_DIR + \"\/das-testsuite\/\", \"\")\n == \"\");\n }\n\n void find_group_ancillary_file_test()\n {\n CPPUNIT_ASSERT(\n Ancillary::find_group_ancillary_file((string) TEST_SRC_DIR + \"\/cgi-util-tests\/02group.hdf\", \".htm\")\n == (string) TEST_SRC_DIR + \"\/cgi-util-tests\/group.htm\");\n CPPUNIT_ASSERT(\n Ancillary::find_group_ancillary_file((string) TEST_SRC_DIR + \"\/cgi-util-tests\/group01.hdf\", \".htm\")\n == (string) TEST_SRC_DIR + \"\/cgi-util-tests\/group.htm\");\n CPPUNIT_ASSERT(\n Ancillary::find_group_ancillary_file((string) TEST_SRC_DIR + \"\/cgi-util-tests\/group.hdf\", \".htm\") == \"\");\n }\n\n void read_ancillary_das_file_test()\n {\n DAS das;\n string dir = \"\";\n string file = \"\";\n Ancillary::read_ancillary_das(das, (string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.das\", dir, file);\n CPPUNIT_ASSERT(das.get_size() == 1);\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION (ancT);\n\nint main(int argc, char *argv[])\n{\n return run_tests<ancT>(argc, argv) ? 0: 1;\n}\n<commit_msg>Removed extra header (#189)<commit_after>\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.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 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\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n#include <cppunit\/TextTestRunner.h>\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#ifndef TM_IN_SYS_TIME\n#include <time.h>\n#else\n#include <sys\/time.h>\n#endif\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h> \/\/ for stat\n\n#include <string>\n#include <sstream>\n\n#include \"Ancillary.h\"\n#include \"DDS.h\"\n#include \"debug.h\"\n\n#include \"run_tests_cppunit.h\"\n#include \"test_config.h\"\n\nusing namespace CppUnit;\nusing namespace std;\nusing namespace libdap;\n\nclass ancT: public TestFixture {\nprivate:\n\nprotected:\n\npublic:\n ancT() = default;\n ~ancT() = default;\n\n CPPUNIT_TEST_SUITE (ancT);\n\n CPPUNIT_TEST (find_ancillary_file_test);\n CPPUNIT_TEST (find_group_ancillary_file_test);\n CPPUNIT_TEST (read_ancillary_das_file_test);\n\n CPPUNIT_TEST_SUITE_END();\n\n void find_ancillary_file_test()\n {\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/test.1\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/special.test.hdf\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/special.test.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/test.2\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.gz\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/test.3.Z\", \"das\", \"\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test.3.Z.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testste\/test_1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testsuite\/\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test_1.das\");\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/te1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testite\/\", \"\"); \n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testsuite\/te1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testite\/\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testste\/test1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testsuite\/\", \"\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testste\/test1\", \"das\", (string) TEST_SRC_DIR + \"\/das-testsuite\/\", \"test.1\")\n == (string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.das\");\n CPPUNIT_ASSERT(\n Ancillary::find_ancillary_file((string) TEST_SRC_DIR + \"\/das-testste\/test1\", \"ds\", (string) TEST_SRC_DIR + \"\/das-testsuite\/\", \"\")\n == \"\");\n }\n\n void find_group_ancillary_file_test()\n {\n CPPUNIT_ASSERT(\n Ancillary::find_group_ancillary_file((string) TEST_SRC_DIR + \"\/cgi-util-tests\/02group.hdf\", \".htm\")\n == (string) TEST_SRC_DIR + \"\/cgi-util-tests\/group.htm\");\n CPPUNIT_ASSERT(\n Ancillary::find_group_ancillary_file((string) TEST_SRC_DIR + \"\/cgi-util-tests\/group01.hdf\", \".htm\")\n == (string) TEST_SRC_DIR + \"\/cgi-util-tests\/group.htm\");\n CPPUNIT_ASSERT(\n Ancillary::find_group_ancillary_file((string) TEST_SRC_DIR + \"\/cgi-util-tests\/group.hdf\", \".htm\") == \"\");\n }\n\n void read_ancillary_das_file_test()\n {\n DAS das;\n string dir = \"\";\n string file = \"\";\n Ancillary::read_ancillary_das(das, (string) TEST_SRC_DIR + \"\/das-testsuite\/test.1.das\", dir, file);\n CPPUNIT_ASSERT(das.get_size() == 1);\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION (ancT);\n\nint main(int argc, char *argv[])\n{\n return run_tests<ancT>(argc, argv) ? 0: 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n * This file is distributed under the terms in the attached LICENSE file.\n * If you do not find this file, copies can be found by writing to:\n * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,\n * Berkeley, CA, 94704. Attention: Intel License Inquiry.\n * Or\n * UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776, \n * Berkeley, CA, 94707. Attention: P2 Group.\n *\/\n\n#include \"boost\/test\/unit_test.hpp\"\nusing boost::unit_test_framework::test_suite; \n\n#include \"testPel.h\"\n#include \"testTable2.h\"\n#include \"testMarshal.h\"\n#include \"testBasicElementPlumbing.h\"\n#include \"testFdbufs.h\"\n#include \"testValues.h\"\n#include \"testCsv.h\"\n#include \"testTables.h\"\n#include \"testIDs.h\"\n\n#include \"testLists.C\"\n\ntest_suite* init_unit_test_suite(int, char**)\n{\n test_suite *top = BOOST_TEST_SUITE(\"P2 Unit Test Suite\");\n \n top->add(new testPel_testSuite());\n top->add(new testTable2_testSuite());\n top->add(new testMarshal_testSuite());\n top->add(new testBasicElementPlumbing_testSuite());\n top->add(new testFdbufs_testSuite());\n top->add(new testValues_testSuite());\n top->add(new testCsv_testSuite());\n\n top->add(new testTables_testSuite());\n top->add(new testIDs_testSuite());\n top->add(new testLists_testSuite());\n return top;\n}\n<commit_msg>Fixed p2Test to only include .h's<commit_after>\/* \n * This file is distributed under the terms in the attached LICENSE file.\n * If you do not find this file, copies can be found by writing to:\n * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,\n * Berkeley, CA, 94704. Attention: Intel License Inquiry.\n * Or\n * UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776, \n * Berkeley, CA, 94707. Attention: P2 Group.\n *\/\n\n#include \"boost\/test\/unit_test.hpp\"\nusing boost::unit_test_framework::test_suite; \n\n#include \"testPel.h\"\n#include \"testTable2.h\"\n#include \"testMarshal.h\"\n#include \"testBasicElementPlumbing.h\"\n#include \"testFdbufs.h\"\n#include \"testValues.h\"\n#include \"testCsv.h\"\n#include \"testTables.h\"\n#include \"testIDs.h\"\n#include \"testLists.h\"\n\ntest_suite* init_unit_test_suite(int, char**)\n{\n test_suite *top = BOOST_TEST_SUITE(\"P2 Unit Test Suite\");\n \n top->add(new testPel_testSuite());\n top->add(new testTable2_testSuite());\n top->add(new testMarshal_testSuite());\n top->add(new testBasicElementPlumbing_testSuite());\n top->add(new testFdbufs_testSuite());\n top->add(new testValues_testSuite());\n top->add(new testCsv_testSuite());\n top->add(new testTables_testSuite());\n top->add(new testIDs_testSuite());\n top->add(new testLists_testSuite());\n return top;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef EQ_SOLVER_HPP\n#define EQ_SOLVER_HPP\n\n#include \"expr.hpp\"\n#include \"util.hpp\"\n\n#if defined(__DEPRECATED)\n#define EQ_DEPRECATED\n#undef __DEPRECATED \/\/ Hack to silence gcc\n#endif\n\n\/\/ or-tools\n#include <constraint_solver\/constraint_solver.h>\n\n\/\/ Restore\n#if defined(EQ_DEPRECATED)\n#undef EQ_DEPRECATED\n#define __DEPRECATED\n#endif\n\nnamespace eq {\nnamespace op= operations_research;\n\nclass Solver {\npublic:\n\n\tvoid addVar(int& ref)\n\t{\n\t\tintVars.emplace_back(&ref, solver.MakeIntVar(minInt, maxInt));\n\t}\n\n\ttemplate <typename T>\n\tvoid addRelation(Expr<T> rel)\n\t{\n\t\tmakeRel(*this, rel);\n\t}\n\n\tvoid apply()\n\t{\n\t\tstd::vector<op::IntVar*> ints;\n\t\tfor (auto&& m : intVars) {\n\t\t\tints.push_back(m.model);\n\t\t}\n\t\tauto db= solver.MakePhase(ints, op::Solver::CHOOSE_FIRST_UNBOUND, op::Solver::ASSIGN_MIN_VALUE);\n\t\tsolver.NewSearch(db);\n\n\t\tif (solver.NextSolution()) {\n\t\t\tfor (auto&& var : intVars) {\n\t\t\t\tassert(var.actual && var.model);\n\t\t\t\t*var.actual= var.model->Value();\n\t\t\t}\n\t\t} else {\n\t\t\tstd::cout << \"Solving error, failure count: \" << solver.failures() << std::endl;\n\t\t}\n\t\t\n\t\tsolver.EndSearch();\n\t}\n\nprivate:\n\ttemplate <typename T>\n\tstruct VarInfo {\n\t\tVarInfo()= default;\n\t\tVarInfo(T* actual, op::IntVar* model)\n\t\t\t: actual(actual)\n\t\t\t, model(model)\n\t\t{ }\n\t\tVarInfo(const VarInfo&)= default;\n\t\tVarInfo(VarInfo&& other) : VarInfo(other) {}\n\n\t\tVarInfo& operator=(const VarInfo&)= default;\n\t\tVarInfo& operator=(VarInfo&& other){\n\t\t\t\/\/ std::vector insists using move assign even when its deleted... (gcc 4.8.1)\n\t\t\treturn operator=(other); \n\t\t}\n\n\t\tT* actual= nullptr;\n\t\top::IntVar* model= nullptr;\n\t};\n\n\ttemplate <typename T>\n\tstruct MakeRel {\n\t\tstatic_assert(!sizeof(T), \"Solving for particular expr not implemented\");\n\t};\n\n\t\/\/\/ @todo Simplify expression trees so that unsupported operations vanish\n\t\/\/\/ @todo Check if IntExpr::Var() calls could be omitted\n\t\/\/\/ Creates solver constraints matching to expression\n\ttemplate <typename E>\n\tstatic auto makeRel(Solver& self, E&& t)\n\t-> Return<decltype(&MakeRel<RemoveRef<E>>::eval)>\n\t{\n\t\treturn MakeRel<RemoveRef<E>>::eval(self, t);\n\t}\n\t\n\t\/\/ Expressions to constraints -conversions\n\n\ttemplate <typename T>\n\tstruct MakeRel<Expr<T>> {\n\t\tstatic auto eval(Solver& self, Expr<T> e)\n\t\t-> decltype(makeRel(self, e.get()))\n\t\t{\n\t\t\treturn makeRel(self, e.get());\n\t\t}\n\t};\n\n\ttemplate <typename T>\n\tstruct MakeRel<Var<T>> {\n\t\tstatic op::IntVar* eval(Solver& self, Var<T>& v)\n\t\t{\n\t\t\treturn self.getVarInfo(v.get()).model;\n\t\t}\n\t};\n\n\ttemplate <typename T>\n\tstruct MakeRel<Constant<T>> {\n\t\tstatic op::IntVar* eval(Solver& self, Constant<T> v)\n\t\t{\n\t\t\t\/\/\/ @todo Not sure if leaks\n\t\t\treturn self.solver.MakeIntConst(v.get());\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Add>> {\n\t\tstatic op::IntVar* eval(Solver& self, BiOp<T1, T2, Add> e)\n\t\t{\n\t\t\treturn self.solver.MakeSum(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs))->Var();\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Sub>> {\n\t\tstatic op::IntVar* eval(Solver& self, BiOp<T1, T2, Sub> e)\n\t\t{\n\t\t\treturn self.solver.MakeDifference(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs))->Var();\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Mul>> {\n\t\tstatic op::IntVar* eval(Solver& self, BiOp<T1, T2, Mul> e)\n\t\t{\n\t\t\treturn self.solver.MakeProd(makeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs))->Var();\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Div>> {\n\t\tstatic op::IntVar* eval(Solver& self, BiOp<T1, T2, Div> e)\n\t\t{\n\t\t\treturn self.solver.MakeDiv(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs))->Var();\n\t\t}\n\t};\n\n\ttemplate <typename T>\n\tstruct MakeRel<UOp<T, Pos>> {\n\t\tstatic op::IntVar* eval(Solver& self, UOp<T, Pos> op)\n\t\t{\n\t\t\treturn makeRel(self, op.e);\n\t\t}\n\t};\n\t\n\ttemplate <typename T>\n\tstruct MakeRel<UOp<T, Neg>> {\n\t\tstatic op::IntVar* eval(Solver& self, UOp<T, Neg> op)\n\t\t{\n\t\t\treturn self.solver.MakeOpposite(makeRel(self, op.e))->Var();\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Eq>> {\n\t\tstatic void eval(Solver& self, BiOp<T1, T2, Eq> e)\n\t\t{\n\t\t\tauto constraint= self.solver.MakeEquality(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\t\tself.solver.AddConstraint(constraint);\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Neq>> {\n\t\tstatic void eval(Solver& self, BiOp<T1, T2, Neq> e)\n\t\t{\n\t\t\tauto constraint= self.solver.MakeNonEquality(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\t\tself.solver.AddConstraint(constraint);\n\t\t}\n\t};\n\t\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Gr>> {\n\t\tstatic void eval(Solver& self, BiOp<T1, T2, Gr> e)\n\t\t{\n\t\t\tauto constraint= self.solver.MakeGreater(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\t\tself.solver.AddConstraint(constraint);\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Ls>> {\n\t\tstatic void eval(Solver& self, BiOp<T1, T2, Ls> e)\n\t\t{\n\t\t\tauto constraint= self.solver.MakeLess(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\t\tself.solver.AddConstraint(constraint);\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Geq>> {\n\t\tstatic void eval(Solver& self, BiOp<T1, T2, Geq> e)\n\t\t{\n\t\t\tauto constraint= self.solver.MakeGreaterOrEqual(makeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\t\tself.solver.AddConstraint(constraint);\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Leq>> {\n\t\tstatic void eval(Solver& self, BiOp<T1, T2, Leq> e)\n\t\t{\n\t\t\tauto constraint= self.solver.MakeLessOrEqual(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\t\tself.solver.AddConstraint(constraint);\n\t\t}\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, And>> {\n\t\tstatic void eval(Solver& self, BiOp<T1, T2, And> e)\n\t\t{\n\t\t\tstatic_assert(isRelation<T1>() && isRelation<T2>(),\n\t\t\t\t\t\"Invalid exprs for && operator\");\n\t\t\tMakeRel<T1>::eval(self, e.lhs);\n\t\t\tMakeRel<T2>::eval(self, e.rhs);\n\t\t}\n\t};\n\t\n\ttemplate <typename T1, typename T2>\n\tstruct MakeRel<BiOp<T1, T2, Or>> {\n\t\tstatic void eval(Solver& self, BiOp<T1, T2, Or> e)\n\t\t{\n\t\t\tstatic_assert(!sizeof(T1), \"@todo ||\");\n\t\t}\n\t};\n\n\ttemplate <typename T>\n\tstruct MakeRel<UOp<T, Not>> {\n\t\tstatic op::IntVar* eval(Solver& self, UOp<T, Not> e)\n\t\t{\n\t\t\tstatic_assert(!sizeof(T), \"@todo Negation\");\n\t\t}\n\t};\n\n\tVarInfo<int>& getVarInfo(const int& ref)\n\t{\n\t\tfor (auto&& m : intVars) {\n\t\t\tif (m.actual == &ref)\n\t\t\t\treturn m;\n\t\t}\n\n\t\tassert(0 && \"var not found\");\n\t\tthrow \"var not found\";\n\t}\n\n\t\/\/ Completely arbitrary\n\tstatic constexpr int minInt= -9999;\n\tstatic constexpr int maxInt= 9999;\n\n\top::Solver solver{\"solver\"};\n\tDynArray<VarInfo<int>> intVars;\n};\n\n} \/\/ eq\n\n#endif \/\/ EQ_SOLVER_HPP\n<commit_msg>Moved MakeRel struct outside Solver<commit_after>#ifndef EQ_SOLVER_HPP\n#define EQ_SOLVER_HPP\n\n#include \"expr.hpp\"\n#include \"util.hpp\"\n\n#include <stdexcept>\n\n#if defined(__DEPRECATED)\n#define EQ_DEPRECATED\n#undef __DEPRECATED \/\/ Hack to silence gcc\n#endif\n\n\/\/ or-tools\n#include <constraint_solver\/constraint_solver.h>\n\n\/\/ Restore\n#if defined(EQ_DEPRECATED)\n#undef EQ_DEPRECATED\n#define __DEPRECATED\n#endif\n\nnamespace eq {\nnamespace op= operations_research;\nclass Solver;\n\nnamespace detail {\n\ntemplate <typename T>\nstruct MakeRel {\n\tstatic_assert(!sizeof(T), \"Solving for particular expr not implemented\");\n};\n\n\/\/\/ @todo Simplify expression trees so that unsupported operations vanish\n\/\/\/ @todo Check if IntExpr::Var() calls could be omitted\n\/\/\/ Creates solver constraints matching to expression\ntemplate <typename E>\nstatic auto makeRel(Solver& self, E&& t)\n-> Return<decltype(&MakeRel<RemoveRef<E>>::eval)>\n{\n\treturn detail::MakeRel<RemoveRef<E>>::eval(self, t);\n}\n\n} \/\/ detail\n\nclass Solver {\npublic:\n\n\tvoid addVar(int& ref)\n\t{\n\t\tintVars.emplace_back(&ref, solver.MakeIntVar(minInt, maxInt));\n\t}\n\n\ttemplate <typename T>\n\tvoid addRelation(Expr<T> rel)\n\t{\n\t\tdetail::makeRel(*this, rel);\n\t}\n\n\t\/\/\/ Solve and apply results\n\tvoid apply()\n\t{\n\t\tstd::vector<op::IntVar*> ints;\n\t\tfor (auto&& m : intVars) {\n\t\t\tints.push_back(m.model);\n\t\t}\n\t\tauto db= solver.MakePhase(ints, op::Solver::CHOOSE_FIRST_UNBOUND, op::Solver::ASSIGN_MIN_VALUE);\n\t\tsolver.NewSearch(db);\n\n\t\tif (solver.NextSolution()) {\n\t\t\tfor (auto&& var : intVars) {\n\t\t\t\tassert(var.actual && var.model);\n\t\t\t\t*var.actual= var.model->Value();\n\t\t\t}\n\t\t} else {\n\t\t\tstd::cout << \"Solving error, failure count: \" << solver.failures() << std::endl;\n\t\t}\n\t\t\n\t\tsolver.EndSearch();\n\t}\n\nprivate:\n\ttemplate <typename T>\n\tfriend class detail::MakeRel;\n\t\n\ttemplate <typename T>\n\tstruct VarInfo {\n\t\tVarInfo()= default;\n\t\tVarInfo(T* actual, op::IntVar* model)\n\t\t\t: actual(actual)\n\t\t\t, model(model)\n\t\t{ }\n\t\tVarInfo(const VarInfo&)= default;\n\t\tVarInfo(VarInfo&& other) : VarInfo(other) {}\n\n\t\tVarInfo& operator=(const VarInfo&)= default;\n\t\tVarInfo& operator=(VarInfo&& other){\n\t\t\t\/\/ std::vector insists using move assign even when its deleted... (gcc 4.8.1)\n\t\t\treturn operator=(other); \n\t\t}\n\n\t\tT* actual= nullptr;\n\t\top::IntVar* model= nullptr;\n\t};\n\n\tVarInfo<int>& getVarInfo(const int& ref)\n\t{\n\t\tfor (auto&& m : intVars) {\n\t\t\tif (m.actual == &ref)\n\t\t\t\treturn m;\n\t\t}\n\n\t\tthrow std::runtime_error{\"var not found\"};\n\t}\n\n\t\/\/ Completely arbitrary\n\t\/\/\/ @todo Remove limits\n\tstatic constexpr int minInt= -9999;\n\tstatic constexpr int maxInt= 9999;\n\n\top::Solver solver{\"solver\"};\n\tDynArray<VarInfo<int>> intVars;\n};\n\n\nnamespace detail {\n\n\/\/ Expressions to constraints -conversions\n\ntemplate <typename T>\nstruct MakeRel<Expr<T>> {\n\tstatic auto eval(Solver& self, Expr<T> e)\n\t-> decltype(makeRel(self, e.get()))\n\t{\n\t\treturn makeRel(self, e.get());\n\t}\n};\n\ntemplate <typename T>\nstruct MakeRel<Var<T>> {\n\tstatic op::IntVar* eval(Solver& self, Var<T>& v)\n\t{\n\t\treturn self.getVarInfo(v.get()).model;\n\t}\n};\n\ntemplate <typename T>\nstruct MakeRel<Constant<T>> {\n\tstatic op::IntVar* eval(Solver& self, Constant<T> v)\n\t{\n\t\t\/\/\/ @todo Not sure if leaks\n\t\treturn self.solver.MakeIntConst(v.get());\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Add>> {\n\tstatic op::IntVar* eval(Solver& self, BiOp<T1, T2, Add> e)\n\t{\n\t\treturn self.solver.MakeSum(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs))->Var();\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Sub>> {\n\tstatic op::IntVar* eval(Solver& self, BiOp<T1, T2, Sub> e)\n\t{\n\t\treturn self.solver.MakeDifference(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs))->Var();\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Mul>> {\n\tstatic op::IntVar* eval(Solver& self, BiOp<T1, T2, Mul> e)\n\t{\n\t\treturn self.solver.MakeProd(makeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs))->Var();\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Div>> {\n\tstatic op::IntVar* eval(Solver& self, BiOp<T1, T2, Div> e)\n\t{\n\t\treturn self.solver.MakeDiv(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs))->Var();\n\t}\n};\n\ntemplate <typename T>\nstruct MakeRel<UOp<T, Pos>> {\n\tstatic op::IntVar* eval(Solver& self, UOp<T, Pos> op)\n\t{\n\t\treturn makeRel(self, op.e);\n\t}\n};\n\ntemplate <typename T>\nstruct MakeRel<UOp<T, Neg>> {\n\tstatic op::IntVar* eval(Solver& self, UOp<T, Neg> op)\n\t{\n\t\treturn self.solver.MakeOpposite(makeRel(self, op.e))->Var();\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Eq>> {\n\tstatic void eval(Solver& self, BiOp<T1, T2, Eq> e)\n\t{\n\t\tauto constraint= self.solver.MakeEquality(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\tself.solver.AddConstraint(constraint);\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Neq>> {\n\tstatic void eval(Solver& self, BiOp<T1, T2, Neq> e)\n\t{\n\t\tauto constraint= self.solver.MakeNonEquality(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\tself.solver.AddConstraint(constraint);\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Gr>> {\n\tstatic void eval(Solver& self, BiOp<T1, T2, Gr> e)\n\t{\n\t\tauto constraint= self.solver.MakeGreater(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\tself.solver.AddConstraint(constraint);\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Ls>> {\n\tstatic void eval(Solver& self, BiOp<T1, T2, Ls> e)\n\t{\n\t\tauto constraint= self.solver.MakeLess(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\tself.solver.AddConstraint(constraint);\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Geq>> {\n\tstatic void eval(Solver& self, BiOp<T1, T2, Geq> e)\n\t{\n\t\tauto constraint= self.solver.MakeGreaterOrEqual(makeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\tself.solver.AddConstraint(constraint);\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Leq>> {\n\tstatic void eval(Solver& self, BiOp<T1, T2, Leq> e)\n\t{\n\t\tauto constraint= self.solver.MakeLessOrEqual(\tmakeRel(self, e.lhs),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmakeRel(self, e.rhs));\n\t\tself.solver.AddConstraint(constraint);\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, And>> {\n\tstatic void eval(Solver& self, BiOp<T1, T2, And> e)\n\t{\n\t\tstatic_assert(isRelation<T1>() && isRelation<T2>(),\n\t\t\t\t\"Invalid exprs for && operator\");\n\t\tMakeRel<T1>::eval(self, e.lhs);\n\t\tMakeRel<T2>::eval(self, e.rhs);\n\t}\n};\n\ntemplate <typename T1, typename T2>\nstruct MakeRel<BiOp<T1, T2, Or>> {\n\tstatic void eval(Solver& self, BiOp<T1, T2, Or> e)\n\t{\n\t\tstatic_assert(!sizeof(T1), \"@todo ||\");\n\t}\n};\n\ntemplate <typename T>\nstruct MakeRel<UOp<T, Not>> {\n\tstatic op::IntVar* eval(Solver& self, UOp<T, Not> e)\n\t{\n\t\tstatic_assert(!sizeof(T), \"@todo Negation\");\n\t}\n};\n\n} \/\/ detail\n} \/\/ eq\n\n#endif \/\/ EQ_SOLVER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- NEONMoveFix.cpp - Convert vfp reg-reg moves into neon ---*- C++ -*-===\/\/\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#define DEBUG_TYPE \"neon-mov-fix\"\n#include \"ARM.h\"\n#include \"ARMMachineFunctionInfo.h\"\n#include \"ARMInstrInfo.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\nSTATISTIC(NumVMovs, \"Number of reg-reg moves converted\");\n\nnamespace {\n struct NEONMoveFixPass : public MachineFunctionPass {\n static char ID;\n NEONMoveFixPass() : MachineFunctionPass(&ID) {}\n\n virtual bool runOnMachineFunction(MachineFunction &Fn);\n\n virtual const char *getPassName() const {\n return \"NEON reg-reg move conversion\";\n }\n\n private:\n const TargetRegisterInfo *TRI;\n const ARMBaseInstrInfo *TII;\n\n typedef DenseMap<unsigned, const MachineInstr*> RegMap;\n\n bool InsertMoves(MachineBasicBlock &MBB);\n };\n char NEONMoveFixPass::ID = 0;\n}\n\nbool NEONMoveFixPass::InsertMoves(MachineBasicBlock &MBB) {\n RegMap Defs;\n bool Modified = false;\n\n \/\/ Walk over MBB tracking the def points of the registers.\n MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();\n MachineBasicBlock::iterator NextMII;\n for (; MII != E; MII = NextMII) {\n NextMII = llvm::next(MII);\n MachineInstr *MI = &*MII;\n\n if (MI->getOpcode() == ARM::VMOVD &&\n !TII->isPredicated(MI)) {\n unsigned SrcReg = MI->getOperand(1).getReg();\n \/\/ If we do not find an instruction defining the reg, this means the\n \/\/ register should be live-in for this BB. It's always to better to use\n \/\/ NEON reg-reg moves.\n unsigned Domain = ARMII::DomainNEON;\n RegMap::iterator DefMI = Defs.find(SrcReg);\n if (DefMI != Defs.end()) {\n Domain = DefMI->second->getDesc().TSFlags & ARMII::DomainMask;\n \/\/ Instructions in general domain are subreg accesses.\n \/\/ Map them to NEON reg-reg moves.\n if (Domain == ARMII::DomainGeneral)\n Domain = ARMII::DomainNEON;\n }\n\n if (Domain & ARMII::DomainNEON) {\n \/\/ Convert VMOVD to VMOVDneon\n unsigned DestReg = MI->getOperand(0).getReg();\n\n DEBUG({errs() << \"vmov convert: \"; MI->dump();});\n\n \/\/ It's safe to ignore imp-defs \/ imp-uses here, since:\n \/\/ - We're running late, no intelligent condegen passes should be run\n \/\/ afterwards\n \/\/ - The imp-defs \/ imp-uses are superregs only, we don't care about\n \/\/ them.\n AddDefaultPred(BuildMI(MBB, *MI, MI->getDebugLoc(),\n TII->get(ARM::VMOVDneon), DestReg).addReg(SrcReg));\n MBB.erase(MI);\n MachineBasicBlock::iterator I = prior(NextMII);\n MI = &*I;\n\n DEBUG({errs() << \" into: \"; MI->dump();});\n\n Modified = true;\n ++NumVMovs;\n } else {\n assert((Domain & ARMII::DomainVFP) && \"Invalid domain!\");\n \/\/ Do nothing.\n }\n }\n\n \/\/ Update def information.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand& MO = MI->getOperand(i);\n if (!MO.isReg() || !MO.isDef())\n continue;\n unsigned MOReg = MO.getReg();\n\n Defs[MOReg] = MI;\n \/\/ Catch subregs as well.\n for (const unsigned *R = TRI->getSubRegisters(MOReg); *R; ++R)\n Defs[*R] = MI;\n }\n }\n\n return Modified;\n}\n\nbool NEONMoveFixPass::runOnMachineFunction(MachineFunction &Fn) {\n ARMFunctionInfo *AFI = Fn.getInfo<ARMFunctionInfo>();\n const TargetMachine &TM = Fn.getTarget();\n\n if (AFI->isThumb1OnlyFunction())\n return false;\n\n TRI = TM.getRegisterInfo();\n TII = static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());\n\n bool Modified = false;\n for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;\n ++MFI) {\n MachineBasicBlock &MBB = *MFI;\n Modified |= InsertMoves(MBB);\n }\n\n return Modified;\n}\n\n\/\/\/ createNEONMoveFixPass - Returns an instance of the NEON reg-reg moves fix\n\/\/\/ pass.\nFunctionPass *llvm::createNEONMoveFixPass() {\n return new NEONMoveFixPass();\n}\n<commit_msg>Track defs for all aliases in NEONMoveFix.<commit_after>\/\/===-- NEONMoveFix.cpp - Convert vfp reg-reg moves into neon ---*- C++ -*-===\/\/\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#define DEBUG_TYPE \"neon-mov-fix\"\n#include \"ARM.h\"\n#include \"ARMMachineFunctionInfo.h\"\n#include \"ARMInstrInfo.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\nSTATISTIC(NumVMovs, \"Number of reg-reg moves converted\");\n\nnamespace {\n struct NEONMoveFixPass : public MachineFunctionPass {\n static char ID;\n NEONMoveFixPass() : MachineFunctionPass(&ID) {}\n\n virtual bool runOnMachineFunction(MachineFunction &Fn);\n\n virtual const char *getPassName() const {\n return \"NEON reg-reg move conversion\";\n }\n\n private:\n const TargetRegisterInfo *TRI;\n const ARMBaseInstrInfo *TII;\n\n typedef DenseMap<unsigned, const MachineInstr*> RegMap;\n\n bool InsertMoves(MachineBasicBlock &MBB);\n };\n char NEONMoveFixPass::ID = 0;\n}\n\nbool NEONMoveFixPass::InsertMoves(MachineBasicBlock &MBB) {\n RegMap Defs;\n bool Modified = false;\n\n \/\/ Walk over MBB tracking the def points of the registers.\n MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();\n MachineBasicBlock::iterator NextMII;\n for (; MII != E; MII = NextMII) {\n NextMII = llvm::next(MII);\n MachineInstr *MI = &*MII;\n\n if (MI->getOpcode() == ARM::VMOVD &&\n !TII->isPredicated(MI)) {\n unsigned SrcReg = MI->getOperand(1).getReg();\n \/\/ If we do not find an instruction defining the reg, this means the\n \/\/ register should be live-in for this BB. It's always to better to use\n \/\/ NEON reg-reg moves.\n unsigned Domain = ARMII::DomainNEON;\n RegMap::iterator DefMI = Defs.find(SrcReg);\n if (DefMI != Defs.end()) {\n Domain = DefMI->second->getDesc().TSFlags & ARMII::DomainMask;\n \/\/ Instructions in general domain are subreg accesses.\n \/\/ Map them to NEON reg-reg moves.\n if (Domain == ARMII::DomainGeneral)\n Domain = ARMII::DomainNEON;\n }\n\n if (Domain & ARMII::DomainNEON) {\n \/\/ Convert VMOVD to VMOVDneon\n unsigned DestReg = MI->getOperand(0).getReg();\n\n DEBUG({errs() << \"vmov convert: \"; MI->dump();});\n\n \/\/ It's safe to ignore imp-defs \/ imp-uses here, since:\n \/\/ - We're running late, no intelligent condegen passes should be run\n \/\/ afterwards\n \/\/ - The imp-defs \/ imp-uses are superregs only, we don't care about\n \/\/ them.\n AddDefaultPred(BuildMI(MBB, *MI, MI->getDebugLoc(),\n TII->get(ARM::VMOVDneon), DestReg).addReg(SrcReg));\n MBB.erase(MI);\n MachineBasicBlock::iterator I = prior(NextMII);\n MI = &*I;\n\n DEBUG({errs() << \" into: \"; MI->dump();});\n\n Modified = true;\n ++NumVMovs;\n } else {\n assert((Domain & ARMII::DomainVFP) && \"Invalid domain!\");\n \/\/ Do nothing.\n }\n }\n\n \/\/ Update def information.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand& MO = MI->getOperand(i);\n if (!MO.isReg() || !MO.isDef())\n continue;\n unsigned MOReg = MO.getReg();\n\n Defs[MOReg] = MI;\n \/\/ Catch aliases as well.\n for (const unsigned *R = TRI->getAliasSet(MOReg); *R; ++R)\n Defs[*R] = MI;\n }\n }\n\n return Modified;\n}\n\nbool NEONMoveFixPass::runOnMachineFunction(MachineFunction &Fn) {\n ARMFunctionInfo *AFI = Fn.getInfo<ARMFunctionInfo>();\n const TargetMachine &TM = Fn.getTarget();\n\n if (AFI->isThumb1OnlyFunction())\n return false;\n\n TRI = TM.getRegisterInfo();\n TII = static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());\n\n bool Modified = false;\n for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;\n ++MFI) {\n MachineBasicBlock &MBB = *MFI;\n Modified |= InsertMoves(MBB);\n }\n\n return Modified;\n}\n\n\/\/\/ createNEONMoveFixPass - Returns an instance of the NEON reg-reg moves fix\n\/\/\/ pass.\nFunctionPass *llvm::createNEONMoveFixPass() {\n return new NEONMoveFixPass();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- Inliner.cpp - Code common to all inliners --------------------------===\/\/\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\/\/ This file implements the mechanics required to implement inlining without\n\/\/ missing any calls and updating the call graph. The decisions of which calls\n\/\/ are profitable to inline are implemented elsewhere.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"inline\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/IPO\/InlinerPass.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include <set>\nusing namespace llvm;\n\nSTATISTIC(NumInlined, \"Number of functions inlined\");\nSTATISTIC(NumDeleted, \"Number of functions deleted because all callers found\");\n\nstatic cl::opt<int>\nInlineLimit(\"inline-threshold\", cl::Hidden, cl::init(200),\n cl::desc(\"Control the amount of inlining to perform (default = 200)\"));\n\nInliner::Inliner(void *ID) \n : CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}\n\nInliner::Inliner(void *ID, int Threshold) \n : CallGraphSCCPass(ID), InlineThreshold(Threshold) {}\n\n\/\/\/ getAnalysisUsage - For this class, we declare that we require and preserve\n\/\/\/ the call graph. If the derived class implements this method, it should\n\/\/\/ always explicitly call the implementation here.\nvoid Inliner::getAnalysisUsage(AnalysisUsage &Info) const {\n Info.addRequired<TargetData>();\n CallGraphSCCPass::getAnalysisUsage(Info);\n}\n\n\/\/ InlineCallIfPossible - If it is possible to inline the specified call site,\n\/\/ do so and update the CallGraph for this operation.\nbool Inliner::InlineCallIfPossible(CallSite CS, CallGraph &CG,\n const SmallPtrSet<Function*, 8> &SCCFunctions,\n const TargetData &TD) {\n Function *Callee = CS.getCalledFunction();\n Function *Caller = CS.getCaller();\n\n if (!InlineFunction(CS, &CG, &TD)) return false;\n\n \/\/ If the inlined function had a higher stack protection level than the\n \/\/ calling function, then bump up the caller's stack protection level.\n if (Callee->hasFnAttr(Attribute::StackProtectReq))\n Caller->addFnAttr(Attribute::StackProtectReq);\n else if (Callee->hasFnAttr(Attribute::StackProtect) &&\n !Caller->hasFnAttr(Attribute::StackProtectReq))\n Caller->addFnAttr(Attribute::StackProtect);\n\n \/\/ If we inlined the last possible call site to the function, delete the\n \/\/ function body now.\n if (Callee->use_empty() && (Callee->hasLocalLinkage() ||\n Callee->hasAvailableExternallyLinkage()) &&\n !SCCFunctions.count(Callee)) {\n DOUT << \" -> Deleting dead function: \" << Callee->getName() << \"\\n\";\n CallGraphNode *CalleeNode = CG[Callee];\n\n \/\/ Remove any call graph edges from the callee to its callees.\n CalleeNode->removeAllCalledFunctions();\n\n resetCachedCostInfo(CalleeNode->getFunction());\n\n \/\/ Removing the node for callee from the call graph and delete it.\n delete CG.removeFunctionFromModule(CalleeNode);\n ++NumDeleted;\n }\n return true;\n}\n \n\/\/\/ shouldInline - Return true if the inliner should attempt to inline\n\/\/\/ at the given CallSite.\nbool Inliner::shouldInline(CallSite CS) {\n InlineCost IC = getInlineCost(CS);\n float FudgeFactor = getInlineFudgeFactor(CS);\n \n if (IC.isAlways()) {\n DOUT << \" Inlining: cost=always\"\n << \", Call: \" << *CS.getInstruction();\n return true;\n }\n \n if (IC.isNever()) {\n DOUT << \" NOT Inlining: cost=never\"\n << \", Call: \" << *CS.getInstruction();\n return false;\n }\n \n int Cost = IC.getValue();\n int CurrentThreshold = InlineThreshold;\n Function *Fn = CS.getCaller();\n if (Fn && !Fn->isDeclaration() \n && Fn->hasFnAttr(Attribute::OptimizeForSize)\n && InlineThreshold != 50) {\n CurrentThreshold = 50;\n }\n \n if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {\n DOUT << \" NOT Inlining: cost=\" << Cost\n << \", Call: \" << *CS.getInstruction();\n return false;\n } else {\n DOUT << \" Inlining: cost=\" << Cost\n << \", Call: \" << *CS.getInstruction();\n return true;\n }\n}\n\nbool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {\n CallGraph &CG = getAnalysis<CallGraph>();\n TargetData &TD = getAnalysis<TargetData>();\n\n SmallPtrSet<Function*, 8> SCCFunctions;\n DOUT << \"Inliner visiting SCC:\";\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n if (F) SCCFunctions.insert(F);\n DOUT << \" \" << (F ? F->getName() : \"INDIRECTNODE\");\n }\n\n \/\/ Scan through and identify all call sites ahead of time so that we only\n \/\/ inline call sites in the original functions, not call sites that result\n \/\/ from inlining other functions.\n std::vector<CallSite> CallSites;\n\n for (unsigned i = 0, e = SCC.size(); i != e; ++i)\n if (Function *F = SCC[i]->getFunction())\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {\n CallSite CS = CallSite::get(I);\n if (CS.getInstruction() && !isa<DbgInfoIntrinsic>(I) &&\n (!CS.getCalledFunction() ||\n !CS.getCalledFunction()->isDeclaration()))\n CallSites.push_back(CS);\n }\n\n DOUT << \": \" << CallSites.size() << \" call sites.\\n\";\n\n \/\/ Now that we have all of the call sites, move the ones to functions in the\n \/\/ current SCC to the end of the list.\n unsigned FirstCallInSCC = CallSites.size();\n for (unsigned i = 0; i < FirstCallInSCC; ++i)\n if (Function *F = CallSites[i].getCalledFunction())\n if (SCCFunctions.count(F))\n std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);\n\n \/\/ Now that we have all of the call sites, loop over them and inline them if\n \/\/ it looks profitable to do so.\n bool Changed = false;\n bool LocalChange;\n do {\n LocalChange = false;\n \/\/ Iterate over the outer loop because inlining functions can cause indirect\n \/\/ calls to become direct calls.\n for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)\n if (Function *Callee = CallSites[CSi].getCalledFunction()) {\n \/\/ Calls to external functions are never inlinable.\n if (Callee->isDeclaration()) {\n if (SCC.size() == 1) {\n std::swap(CallSites[CSi], CallSites.back());\n CallSites.pop_back();\n } else {\n \/\/ Keep the 'in SCC \/ not in SCC' boundary correct.\n CallSites.erase(CallSites.begin()+CSi);\n }\n --CSi;\n continue;\n }\n\n \/\/ If the policy determines that we should inline this function,\n \/\/ try to do so.\n CallSite CS = CallSites[CSi];\n if (shouldInline(CS)) {\n Function *Caller = CS.getCaller();\n \/\/ Attempt to inline the function...\n if (InlineCallIfPossible(CS, CG, SCCFunctions, TD)) {\n \/\/ Remove any cached cost info for this caller, as inlining the\n \/\/ callee has increased the size of the caller (which may be the\n \/\/ same as the callee).\n resetCachedCostInfo(Caller);\n\n \/\/ Remove this call site from the list. If possible, use \n \/\/ swap\/pop_back for efficiency, but do not use it if doing so would\n \/\/ move a call site to a function in this SCC before the\n \/\/ 'FirstCallInSCC' barrier.\n if (SCC.size() == 1) {\n std::swap(CallSites[CSi], CallSites.back());\n CallSites.pop_back();\n } else {\n CallSites.erase(CallSites.begin()+CSi);\n }\n --CSi;\n\n ++NumInlined;\n Changed = true;\n LocalChange = true;\n }\n }\n }\n } while (LocalChange);\n\n return Changed;\n}\n\n\/\/ doFinalization - Remove now-dead linkonce functions at the end of\n\/\/ processing to avoid breaking the SCC traversal.\nbool Inliner::doFinalization(CallGraph &CG) {\n return removeDeadFunctions(CG);\n}\n\n \/\/\/ removeDeadFunctions - Remove dead functions that are not included in\n \/\/\/ DNR (Do Not Remove) list.\nbool Inliner::removeDeadFunctions(CallGraph &CG, \n SmallPtrSet<const Function *, 16> *DNR) {\n std::set<CallGraphNode*> FunctionsToRemove;\n\n \/\/ Scan for all of the functions, looking for ones that should now be removed\n \/\/ from the program. Insert the dead ones in the FunctionsToRemove set.\n for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {\n CallGraphNode *CGN = I->second;\n if (Function *F = CGN ? CGN->getFunction() : 0) {\n \/\/ If the only remaining users of the function are dead constants, remove\n \/\/ them.\n F->removeDeadConstantUsers();\n\n if (DNR && DNR->count(F))\n continue;\n\n if ((F->hasLinkOnceLinkage() || F->hasLocalLinkage()) &&\n F->use_empty()) {\n\n \/\/ Remove any call graph edges from the function to its callees.\n CGN->removeAllCalledFunctions();\n\n \/\/ Remove any edges from the external node to the function's call graph\n \/\/ node. These edges might have been made irrelegant due to\n \/\/ optimization of the program.\n CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);\n\n \/\/ Removing the node for callee from the call graph and delete it.\n FunctionsToRemove.insert(CGN);\n }\n }\n }\n\n \/\/ Now that we know which functions to delete, do so. We didn't want to do\n \/\/ this inline, because that would invalidate our CallGraph::iterator\n \/\/ objects. :(\n bool Changed = false;\n for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),\n E = FunctionsToRemove.end(); I != E; ++I) {\n resetCachedCostInfo((*I)->getFunction());\n delete CG.removeFunctionFromModule(*I);\n ++NumDeleted;\n Changed = true;\n }\n\n return Changed;\n}\n<commit_msg>Add line breaks to make the debug output a bit more readable.<commit_after>\/\/===- Inliner.cpp - Code common to all inliners --------------------------===\/\/\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\/\/ This file implements the mechanics required to implement inlining without\n\/\/ missing any calls and updating the call graph. The decisions of which calls\n\/\/ are profitable to inline are implemented elsewhere.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"inline\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/IPO\/InlinerPass.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include <set>\nusing namespace llvm;\n\nSTATISTIC(NumInlined, \"Number of functions inlined\");\nSTATISTIC(NumDeleted, \"Number of functions deleted because all callers found\");\n\nstatic cl::opt<int>\nInlineLimit(\"inline-threshold\", cl::Hidden, cl::init(200),\n cl::desc(\"Control the amount of inlining to perform (default = 200)\"));\n\nInliner::Inliner(void *ID) \n : CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}\n\nInliner::Inliner(void *ID, int Threshold) \n : CallGraphSCCPass(ID), InlineThreshold(Threshold) {}\n\n\/\/\/ getAnalysisUsage - For this class, we declare that we require and preserve\n\/\/\/ the call graph. If the derived class implements this method, it should\n\/\/\/ always explicitly call the implementation here.\nvoid Inliner::getAnalysisUsage(AnalysisUsage &Info) const {\n Info.addRequired<TargetData>();\n CallGraphSCCPass::getAnalysisUsage(Info);\n}\n\n\/\/ InlineCallIfPossible - If it is possible to inline the specified call site,\n\/\/ do so and update the CallGraph for this operation.\nbool Inliner::InlineCallIfPossible(CallSite CS, CallGraph &CG,\n const SmallPtrSet<Function*, 8> &SCCFunctions,\n const TargetData &TD) {\n Function *Callee = CS.getCalledFunction();\n Function *Caller = CS.getCaller();\n\n if (!InlineFunction(CS, &CG, &TD)) return false;\n\n \/\/ If the inlined function had a higher stack protection level than the\n \/\/ calling function, then bump up the caller's stack protection level.\n if (Callee->hasFnAttr(Attribute::StackProtectReq))\n Caller->addFnAttr(Attribute::StackProtectReq);\n else if (Callee->hasFnAttr(Attribute::StackProtect) &&\n !Caller->hasFnAttr(Attribute::StackProtectReq))\n Caller->addFnAttr(Attribute::StackProtect);\n\n \/\/ If we inlined the last possible call site to the function, delete the\n \/\/ function body now.\n if (Callee->use_empty() && (Callee->hasLocalLinkage() ||\n Callee->hasAvailableExternallyLinkage()) &&\n !SCCFunctions.count(Callee)) {\n DOUT << \" -> Deleting dead function: \" << Callee->getName() << \"\\n\";\n CallGraphNode *CalleeNode = CG[Callee];\n\n \/\/ Remove any call graph edges from the callee to its callees.\n CalleeNode->removeAllCalledFunctions();\n\n resetCachedCostInfo(CalleeNode->getFunction());\n\n \/\/ Removing the node for callee from the call graph and delete it.\n delete CG.removeFunctionFromModule(CalleeNode);\n ++NumDeleted;\n }\n return true;\n}\n \n\/\/\/ shouldInline - Return true if the inliner should attempt to inline\n\/\/\/ at the given CallSite.\nbool Inliner::shouldInline(CallSite CS) {\n InlineCost IC = getInlineCost(CS);\n float FudgeFactor = getInlineFudgeFactor(CS);\n \n if (IC.isAlways()) {\n DOUT << \" Inlining: cost=always\"\n << \", Call: \" << *CS.getInstruction() << \"\\n\";\n return true;\n }\n \n if (IC.isNever()) {\n DOUT << \" NOT Inlining: cost=never\"\n << \", Call: \" << *CS.getInstruction() << \"\\n\";\n return false;\n }\n \n int Cost = IC.getValue();\n int CurrentThreshold = InlineThreshold;\n Function *Fn = CS.getCaller();\n if (Fn && !Fn->isDeclaration() \n && Fn->hasFnAttr(Attribute::OptimizeForSize)\n && InlineThreshold != 50) {\n CurrentThreshold = 50;\n }\n \n if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {\n DOUT << \" NOT Inlining: cost=\" << Cost\n << \", Call: \" << *CS.getInstruction() << \"\\n\";\n return false;\n } else {\n DOUT << \" Inlining: cost=\" << Cost\n << \", Call: \" << *CS.getInstruction() << \"\\n\";\n return true;\n }\n}\n\nbool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {\n CallGraph &CG = getAnalysis<CallGraph>();\n TargetData &TD = getAnalysis<TargetData>();\n\n SmallPtrSet<Function*, 8> SCCFunctions;\n DOUT << \"Inliner visiting SCC:\";\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n if (F) SCCFunctions.insert(F);\n DOUT << \" \" << (F ? F->getName() : \"INDIRECTNODE\");\n }\n\n \/\/ Scan through and identify all call sites ahead of time so that we only\n \/\/ inline call sites in the original functions, not call sites that result\n \/\/ from inlining other functions.\n std::vector<CallSite> CallSites;\n\n for (unsigned i = 0, e = SCC.size(); i != e; ++i)\n if (Function *F = SCC[i]->getFunction())\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {\n CallSite CS = CallSite::get(I);\n if (CS.getInstruction() && !isa<DbgInfoIntrinsic>(I) &&\n (!CS.getCalledFunction() ||\n !CS.getCalledFunction()->isDeclaration()))\n CallSites.push_back(CS);\n }\n\n DOUT << \": \" << CallSites.size() << \" call sites.\\n\";\n\n \/\/ Now that we have all of the call sites, move the ones to functions in the\n \/\/ current SCC to the end of the list.\n unsigned FirstCallInSCC = CallSites.size();\n for (unsigned i = 0; i < FirstCallInSCC; ++i)\n if (Function *F = CallSites[i].getCalledFunction())\n if (SCCFunctions.count(F))\n std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);\n\n \/\/ Now that we have all of the call sites, loop over them and inline them if\n \/\/ it looks profitable to do so.\n bool Changed = false;\n bool LocalChange;\n do {\n LocalChange = false;\n \/\/ Iterate over the outer loop because inlining functions can cause indirect\n \/\/ calls to become direct calls.\n for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)\n if (Function *Callee = CallSites[CSi].getCalledFunction()) {\n \/\/ Calls to external functions are never inlinable.\n if (Callee->isDeclaration()) {\n if (SCC.size() == 1) {\n std::swap(CallSites[CSi], CallSites.back());\n CallSites.pop_back();\n } else {\n \/\/ Keep the 'in SCC \/ not in SCC' boundary correct.\n CallSites.erase(CallSites.begin()+CSi);\n }\n --CSi;\n continue;\n }\n\n \/\/ If the policy determines that we should inline this function,\n \/\/ try to do so.\n CallSite CS = CallSites[CSi];\n if (shouldInline(CS)) {\n Function *Caller = CS.getCaller();\n \/\/ Attempt to inline the function...\n if (InlineCallIfPossible(CS, CG, SCCFunctions, TD)) {\n \/\/ Remove any cached cost info for this caller, as inlining the\n \/\/ callee has increased the size of the caller (which may be the\n \/\/ same as the callee).\n resetCachedCostInfo(Caller);\n\n \/\/ Remove this call site from the list. If possible, use \n \/\/ swap\/pop_back for efficiency, but do not use it if doing so would\n \/\/ move a call site to a function in this SCC before the\n \/\/ 'FirstCallInSCC' barrier.\n if (SCC.size() == 1) {\n std::swap(CallSites[CSi], CallSites.back());\n CallSites.pop_back();\n } else {\n CallSites.erase(CallSites.begin()+CSi);\n }\n --CSi;\n\n ++NumInlined;\n Changed = true;\n LocalChange = true;\n }\n }\n }\n } while (LocalChange);\n\n return Changed;\n}\n\n\/\/ doFinalization - Remove now-dead linkonce functions at the end of\n\/\/ processing to avoid breaking the SCC traversal.\nbool Inliner::doFinalization(CallGraph &CG) {\n return removeDeadFunctions(CG);\n}\n\n \/\/\/ removeDeadFunctions - Remove dead functions that are not included in\n \/\/\/ DNR (Do Not Remove) list.\nbool Inliner::removeDeadFunctions(CallGraph &CG, \n SmallPtrSet<const Function *, 16> *DNR) {\n std::set<CallGraphNode*> FunctionsToRemove;\n\n \/\/ Scan for all of the functions, looking for ones that should now be removed\n \/\/ from the program. Insert the dead ones in the FunctionsToRemove set.\n for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {\n CallGraphNode *CGN = I->second;\n if (Function *F = CGN ? CGN->getFunction() : 0) {\n \/\/ If the only remaining users of the function are dead constants, remove\n \/\/ them.\n F->removeDeadConstantUsers();\n\n if (DNR && DNR->count(F))\n continue;\n\n if ((F->hasLinkOnceLinkage() || F->hasLocalLinkage()) &&\n F->use_empty()) {\n\n \/\/ Remove any call graph edges from the function to its callees.\n CGN->removeAllCalledFunctions();\n\n \/\/ Remove any edges from the external node to the function's call graph\n \/\/ node. These edges might have been made irrelegant due to\n \/\/ optimization of the program.\n CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);\n\n \/\/ Removing the node for callee from the call graph and delete it.\n FunctionsToRemove.insert(CGN);\n }\n }\n }\n\n \/\/ Now that we know which functions to delete, do so. We didn't want to do\n \/\/ this inline, because that would invalidate our CallGraph::iterator\n \/\/ objects. :(\n bool Changed = false;\n for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),\n E = FunctionsToRemove.end(); I != E; ++I) {\n resetCachedCostInfo((*I)->getFunction());\n delete CG.removeFunctionFromModule(*I);\n ++NumDeleted;\n Changed = true;\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 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\/browser\/browser_main_qt.h\"\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/debug\/debugger.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_main_win.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"content\/browser\/renderer_host\/render_sandbox_host_linux.h\"\n#include \"content\/browser\/zygote_host_linux.h\"\n#include \"content\/common\/result_codes.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/base\/x\/x11_util_internal.h\"\n\n#if defined(USE_NSS)\n#include \"base\/nss_util.h\"\n#endif\n\n#if defined(USE_LINUX_BREAKPAD)\n#include \"chrome\/app\/breakpad_linux.h\"\n#endif\n\nnamespace {\n\n\/\/ Indicates that we're currently responding to an IO error (by shutting down).\nbool g_in_x11_io_error_handler = false;\n\nint BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {\n if (!g_in_x11_io_error_handler)\n MessageLoop::current()->PostTask(\n FROM_HERE,\n NewRunnableFunction(ui::LogErrorEventDescription, d, *error));\n return 0;\n}\n\nint BrowserX11IOErrorHandler(Display* d) {\n \/\/ If there's an IO error it likely means the X server has gone away\n if (!g_in_x11_io_error_handler) {\n g_in_x11_io_error_handler = true;\n LOG(ERROR) << \"X IO Error detected\";\n BrowserList::SessionEnding();\n }\n\n return 0;\n}\n\n} \/\/ namespace\n\nvoid BrowserMainPartsQt::PreEarlyInitialization() {\n DetectRunningAsRoot();\n\n BrowserMainPartsPosix::PreEarlyInitialization();\n\n SetupSandbox();\n\n#if defined(USE_NSS)\n \/\/ We want to be sure to init NSPR on the main thread.\n base::EnsureNSPRInit();\n#endif\n}\n\nvoid BrowserMainPartsQt::DetectRunningAsRoot() {\n if (geteuid() == 0) {\n exit(EXIT_FAILURE);\n }\n}\n\nvoid BrowserMainPartsQt::SetupSandbox() {\n \/\/ TODO(evanm): move this into SandboxWrapper; I'm just trying to move this\n \/\/ code en masse out of chrome_main for now.\n const char* sandbox_binary = NULL;\n struct stat st;\n\n \/\/ In Chromium branded builds, developers can set an environment variable to\n \/\/ use the development sandbox. See\n \/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSUIDSandboxDevelopment\n if (stat(\"\/proc\/self\/exe\", &st) == 0 && st.st_uid == getuid())\n sandbox_binary = getenv(\"CHROME_DEVEL_SANDBOX\");\n\n#if defined(LINUX_SANDBOX_PATH)\n if (!sandbox_binary)\n sandbox_binary = LINUX_SANDBOX_PATH;\n#endif\n\n std::string sandbox_cmd;\n if (sandbox_binary && !parsed_command_line().HasSwitch(switches::kNoSandbox))\n sandbox_cmd = sandbox_binary;\n\n \/\/ Tickle the sandbox host and zygote host so they fork now.\n RenderSandboxHostLinux* shost = RenderSandboxHostLinux::GetInstance();\n shost->Init(sandbox_cmd);\n ZygoteHost* zhost = ZygoteHost::GetInstance();\n zhost->Init(sandbox_cmd);\n}\n\nvoid DidEndMainMessageLoop() {\n}\n\nvoid RecordBreakpadStatusUMA(MetricsService* metrics) {\n#if defined(USE_LINUX_BREAKPAD)\n metrics->RecordBreakpadRegistration(IsCrashReporterEnabled());\n#else\n metrics->RecordBreakpadRegistration(false);\n#endif\n metrics->RecordBreakpadHasDebugger(base::debug::BeingDebugged());\n}\n\nvoid WarnAboutMinimumSystemRequirements() {\n \/\/ Nothing to warn about on GTK right now.\n}\n\n\/\/ From browser_main_win.h, stubs until we figure out the right thing...\n\nint DoUninstallTasks(bool chrome_still_running) {\n return ResultCodes::NORMAL_EXIT;\n}\n\nint HandleIconsCommands(const CommandLine &parsed_command_line) {\n return 0;\n}\n\nbool CheckMachineLevelInstall() {\n return false;\n}\n\nvoid PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) {\n}\n\nvoid SetBrowserX11ErrorHandlers() {\n \/\/ Set up error handlers to make sure profile gets written if X server\n \/\/ goes away.\n ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);\n}\n\n#if !defined(OS_CHROMEOS)\n\/\/ static\nBrowserMainParts* BrowserMainParts::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n return new BrowserMainPartsQt(parameters);\n}\n#endif\n<commit_msg>Allow run as root for chroot environment<commit_after>\/\/ Copyright (c) 2008 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\/browser\/browser_main_qt.h\"\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/debug\/debugger.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_main_win.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"content\/browser\/renderer_host\/render_sandbox_host_linux.h\"\n#include \"content\/browser\/zygote_host_linux.h\"\n#include \"content\/common\/result_codes.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/base\/x\/x11_util_internal.h\"\n\n#if defined(USE_NSS)\n#include \"base\/nss_util.h\"\n#endif\n\n#if defined(USE_LINUX_BREAKPAD)\n#include \"chrome\/app\/breakpad_linux.h\"\n#endif\n\nnamespace {\n\n\/\/ Indicates that we're currently responding to an IO error (by shutting down).\nbool g_in_x11_io_error_handler = false;\n\nint BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {\n if (!g_in_x11_io_error_handler)\n MessageLoop::current()->PostTask(\n FROM_HERE,\n NewRunnableFunction(ui::LogErrorEventDescription, d, *error));\n return 0;\n}\n\nint BrowserX11IOErrorHandler(Display* d) {\n \/\/ If there's an IO error it likely means the X server has gone away\n if (!g_in_x11_io_error_handler) {\n g_in_x11_io_error_handler = true;\n LOG(ERROR) << \"X IO Error detected\";\n BrowserList::SessionEnding();\n }\n\n return 0;\n}\n\n} \/\/ namespace\n\nvoid BrowserMainPartsQt::PreEarlyInitialization() {\n DetectRunningAsRoot();\n\n BrowserMainPartsPosix::PreEarlyInitialization();\n\n SetupSandbox();\n\n#if defined(USE_NSS)\n \/\/ We want to be sure to init NSPR on the main thread.\n base::EnsureNSPRInit();\n#endif\n}\n\nvoid BrowserMainPartsQt::DetectRunningAsRoot() {\n \/* TODO: To allow run under chroot envrionment, we allow process run as root *\/\n \/\/if (geteuid() == 0) {\n \/\/ exit(EXIT_FAILURE);\n \/\/}\n}\n\nvoid BrowserMainPartsQt::SetupSandbox() {\n \/\/ TODO(evanm): move this into SandboxWrapper; I'm just trying to move this\n \/\/ code en masse out of chrome_main for now.\n const char* sandbox_binary = NULL;\n struct stat st;\n\n \/\/ In Chromium branded builds, developers can set an environment variable to\n \/\/ use the development sandbox. See\n \/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSUIDSandboxDevelopment\n if (stat(\"\/proc\/self\/exe\", &st) == 0 && st.st_uid == getuid())\n sandbox_binary = getenv(\"CHROME_DEVEL_SANDBOX\");\n\n#if defined(LINUX_SANDBOX_PATH)\n if (!sandbox_binary)\n sandbox_binary = LINUX_SANDBOX_PATH;\n#endif\n\n std::string sandbox_cmd;\n if (sandbox_binary && !parsed_command_line().HasSwitch(switches::kNoSandbox))\n sandbox_cmd = sandbox_binary;\n\n \/\/ Tickle the sandbox host and zygote host so they fork now.\n RenderSandboxHostLinux* shost = RenderSandboxHostLinux::GetInstance();\n shost->Init(sandbox_cmd);\n ZygoteHost* zhost = ZygoteHost::GetInstance();\n zhost->Init(sandbox_cmd);\n}\n\nvoid DidEndMainMessageLoop() {\n}\n\nvoid RecordBreakpadStatusUMA(MetricsService* metrics) {\n#if defined(USE_LINUX_BREAKPAD)\n metrics->RecordBreakpadRegistration(IsCrashReporterEnabled());\n#else\n metrics->RecordBreakpadRegistration(false);\n#endif\n metrics->RecordBreakpadHasDebugger(base::debug::BeingDebugged());\n}\n\nvoid WarnAboutMinimumSystemRequirements() {\n \/\/ Nothing to warn about on GTK right now.\n}\n\n\/\/ From browser_main_win.h, stubs until we figure out the right thing...\n\nint DoUninstallTasks(bool chrome_still_running) {\n return ResultCodes::NORMAL_EXIT;\n}\n\nint HandleIconsCommands(const CommandLine &parsed_command_line) {\n return 0;\n}\n\nbool CheckMachineLevelInstall() {\n return false;\n}\n\nvoid PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) {\n}\n\nvoid SetBrowserX11ErrorHandlers() {\n \/\/ Set up error handlers to make sure profile gets written if X server\n \/\/ goes away.\n ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);\n}\n\n#if !defined(OS_CHROMEOS)\n\/\/ static\nBrowserMainParts* BrowserMainParts::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n return new BrowserMainPartsQt(parameters);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"pyclast.h\"\n#include <pybind11\/stl.h>\n#include <clang\/AST\/AST.h>\n#include <clang\/AST\/ASTTypeTraits.h>\n#include <clang\/ASTMatchers\/ASTMatchers.h>\n#include <clang\/ASTMatchers\/ASTMatchersInternal.h>\n#include <clang\/ASTMatchers\/ASTMatchFinder.h>\n#include \"clang\/ASTMatchers\/Dynamic\/Parser.h\"\n#include <cassert>\n\nnamespace py = pybind11;\nusing namespace clang::ast_matchers;\nusing namespace clang::ast_matchers::internal;\nusing namespace clang::ast_matchers::dynamic;\n\n\n\/\/ FIXME: This is a temporary placeholder until a better solution can be found\nDynTypedMatcher parseMatcherExpression(const std::string& code)\n{\n Diagnostics Err;\n auto val = Parser::parseMatcherExpression(code, &Err);\n if(false == val.hasValue()) {\n throw std::logic_error(\"parse failed\");\n }\n return val.getValue();\n}\n\nvoid install_wrappers(pybind11::module& m)\n{\n m.def(\"parseMatcherExpression\", parseMatcherExpression);\n}\n\n<commit_msg>added string matching infrastructure in preparation for testing<commit_after>#include \"pyclast.h\"\n#include <pybind11\/stl.h>\n#include <clang\/AST\/AST.h>\n#include <clang\/AST\/ASTTypeTraits.h>\n#include <clang\/ASTMatchers\/ASTMatchers.h>\n#include <clang\/ASTMatchers\/ASTMatchersInternal.h>\n#include <clang\/ASTMatchers\/ASTMatchFinder.h>\n#include \"clang\/ASTMatchers\/Dynamic\/Parser.h\"\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n\nnamespace py = pybind11;\nusing namespace clang::ast_matchers;\nusing namespace clang::ast_matchers::internal;\nusing namespace clang::ast_matchers::dynamic;\nusing namespace clang::tooling;\n\n\n\/\/ FIXME: This is a temporary placeholder until a better solution can be found\nDynTypedMatcher parseMatcherExpression(const std::string& code)\n{\n Diagnostics Err;\n auto val = Parser::parseMatcherExpression(code, &Err);\n if(false == val.hasValue()) {\n throw std::logic_error(\"parse failed\");\n }\n return val.getValue();\n}\n\nvoid matchString(const std::string& code, MatchFinder& finder, \n const std::string& compileArgs = \"-std=c++11\", \n const std::string& filename = \"input.cpp\")\n{\n const FileContentMappings &VirtualMappedFiles = FileContentMappings();\n std::unique_ptr<FrontendActionFactory> Factory(\n newFrontendActionFactory(&finder));\n std::vector<std::string> args = {compileArgs, \"-frtti\", \"-fexceptions\",\n \"-target\", \"i386-unknown-unknown\"};\n runToolOnCodeWithArgs(\n Factory->create(), code, args, filename, \"clang-tool\",\n std::make_shared<clang::PCHContainerOperations>(), \n VirtualMappedFiles);\n}\n\nvoid install_wrappers(pybind11::module& m)\n{\n m.def(\"parseMatcherExpression\", parseMatcherExpression);\n m.def(\"matchString\", matchString);\n}\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- InlineCommon.cpp - Code common to all inliners ---------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the mechanics required to implement inlining without\n\/\/ missing any calls and updating the call graph. The decisions of which calls\n\/\/ are profitable to inline are implemented elsewhere.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Inliner.h\"\n#include \"llvm\/Constants.h\" \/\/ ConstantPointerRef should die\n#include \"llvm\/Module.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Debug.h\"\n#include \"Support\/Statistic.h\"\n#include <set>\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumInlined(\"inline\", \"Number of functions inlined\");\n Statistic<> NumDeleted(\"inline\", \"Number of functions deleted because all callers found\");\n cl::opt<unsigned> \/\/ FIXME: 200 is VERY conservative\n InlineLimit(\"inline-threshold\", cl::Hidden, cl::init(200),\n cl::desc(\"Control the amount of inlining to perform (default = 200)\"));\n}\n\nInliner::Inliner() : InlineThreshold(InlineLimit) {}\n\n\/\/ InlineCallIfPossible - If it is possible to inline the specified call site,\n\/\/ do so and update the CallGraph for this operation.\nstatic bool InlineCallIfPossible(CallSite CS, CallGraph &CG,\n const std::set<Function*> &SCCFunctions) {\n Function *Caller = CS.getInstruction()->getParent()->getParent();\n Function *Callee = CS.getCalledFunction();\n if (!InlineFunction(CS)) return false;\n\n \/\/ Update the call graph by deleting the edge from Callee to Caller\n CallGraphNode *CalleeNode = CG[Callee];\n CallGraphNode *CallerNode = CG[Caller];\n CallerNode->removeCallEdgeTo(CalleeNode);\n\n \/\/ Since we inlined all uninlined call sites in the callee into the caller,\n \/\/ add edges from the caller to all of the callees of the callee.\n for (CallGraphNode::iterator I = CalleeNode->begin(),\n E = CalleeNode->end(); I != E; ++I)\n CallerNode->addCalledFunction(*I);\n \n \/\/ If we inlined the last possible call site to the function,\n \/\/ delete the function body now.\n if (Callee->use_empty() && Callee->hasInternalLinkage() &&\n !SCCFunctions.count(Callee)) {\n DEBUG(std::cerr << \" -> Deleting dead function: \"\n << Callee->getName() << \"\\n\");\n \n \/\/ Remove any call graph edges from the callee to its callees.\n while (CalleeNode->begin() != CalleeNode->end())\n CalleeNode->removeCallEdgeTo(*(CalleeNode->end()-1));\n \n \/\/ Removing the node for callee from the call graph and delete it.\n delete CG.removeFunctionFromModule(CalleeNode);\n ++NumDeleted;\n }\n return true;\n}\n\nbool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {\n CallGraph &CG = getAnalysis<CallGraph>();\n\n std::set<Function*> SCCFunctions;\n DEBUG(std::cerr << \"Inliner visiting SCC:\");\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n if (F) SCCFunctions.insert(F);\n DEBUG(std::cerr << \" \" << (F ? F->getName() : \"INDIRECTNODE\"));\n }\n\n \/\/ Scan through and identify all call sites ahead of time so that we only\n \/\/ inline call sites in the original functions, not call sites that result\n \/\/ from inlining other functions.\n std::vector<CallSite> CallSites;\n\n for (std::set<Function*>::iterator SCCI = SCCFunctions.begin(),\n E = SCCFunctions.end(); SCCI != E; ++SCCI)\n if (Function *F = *SCCI)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {\n CallSite CS = CallSite::get(I);\n if (CS.getInstruction() && (!CS.getCalledFunction() ||\n !CS.getCalledFunction()->isExternal()))\n CallSites.push_back(CS);\n }\n\n DEBUG(std::cerr << \": \" << CallSites.size() << \" call sites.\\n\");\n \n \/\/ Now that we have all of the call sites, move the ones to functions in the\n \/\/ current SCC to the end of the list.\n unsigned FirstCallInSCC = CallSites.size();\n for (unsigned i = 0; i < FirstCallInSCC; ++i)\n if (Function *F = CallSites[i].getCalledFunction())\n if (SCCFunctions.count(F))\n std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);\n \n \/\/ Now that we have all of the call sites, loop over them and inline them if\n \/\/ it looks profitable to do so.\n bool Changed = false;\n bool LocalChange;\n do {\n LocalChange = false;\n \/\/ Iterate over the outer loop because inlining functions can cause indirect\n \/\/ calls to become direct calls.\n for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)\n if (Function *Callee = CallSites[CSi].getCalledFunction()) {\n \/\/ Calls to external functions are never inlinable.\n if (Callee->isExternal() ||\n CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){\n std::swap(CallSites[CSi], CallSites.back());\n --CSi;\n continue;\n }\n\n \/\/ If the policy determines that we should inline this function,\n \/\/ try to do so.\n CallSite CS = CallSites[CSi];\n int InlineCost = getInlineCost(CS);\n if (InlineCost >= (int)InlineThreshold) {\n DEBUG(std::cerr << \" NOT Inlining: cost=\" << InlineCost\n << \", Call: \" << *CS.getInstruction());\n } else {\n DEBUG(std::cerr << \" Inlining: cost=\" << InlineCost\n << \", Call: \" << *CS.getInstruction());\n \n Function *Caller = CS.getInstruction()->getParent()->getParent();\n\n \/\/ Attempt to inline the function...\n if (InlineCallIfPossible(CS, CG, SCCFunctions)) {\n \/\/ Remove this call site from the list.\n std::swap(CallSites[CSi], CallSites.back());\n CallSites.pop_back();\n --CSi;\n\n ++NumInlined;\n Changed = true;\n LocalChange = true;\n }\n }\n }\n } while (LocalChange);\n\n return Changed;\n}\n\n\/\/ doFinalization - Remove now-dead linkonce functions at the end of\n\/\/ processing to avoid breaking the SCC traversal.\nbool Inliner::doFinalization(CallGraph &CG) {\n std::set<CallGraphNode*> FunctionsToRemove;\n\n \/\/ Scan for all of the functions, looking for ones that should now be removed\n \/\/ from the program. Insert the dead ones in the FunctionsToRemove set.\n for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {\n CallGraphNode *CGN = I->second;\n Function *F = CGN ? CGN->getFunction() : 0;\n\n \/\/ If the only remaining use of the function is a dead constant\n \/\/ pointer ref, remove it.\n if (F && F->hasOneUse())\n if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(F->use_back()))\n if (CPR->use_empty()) {\n CPR->destroyConstant();\n if (F->hasInternalLinkage()) {\n \/\/ There *MAY* be an edge from the external call node to this\n \/\/ function. If so, remove it.\n CallGraphNode *EN = CG.getExternalCallingNode();\n CallGraphNode::iterator I = std::find(EN->begin(), EN->end(), CGN);\n if (I != EN->end()) EN->removeCallEdgeTo(CGN);\n }\n }\n\n if (F && (F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&\n F->use_empty()) {\n \/\/ Remove any call graph edges from the function to its callees.\n while (CGN->begin() != CGN->end())\n CGN->removeCallEdgeTo(*(CGN->end()-1));\n \n \/\/ If the function has external linkage (basically if it's a linkonce\n \/\/ function) remove the edge from the external node to the callee node.\n if (!F->hasInternalLinkage())\n CG.getExternalCallingNode()->removeCallEdgeTo(CGN);\n \n \/\/ Removing the node for callee from the call graph and delete it.\n FunctionsToRemove.insert(CGN);\n }\n }\n\n \/\/ Now that we know which functions to delete, do so. We didn't want to do\n \/\/ this inline, because that would invalidate our CallGraph::iterator\n \/\/ objects. :(\n bool Changed = false;\n for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),\n E = FunctionsToRemove.end(); I != E; ++I) {\n delete CG.removeFunctionFromModule(*I);\n ++NumDeleted;\n Changed = true;\n }\n\n return Changed;\n}\n<commit_msg>Fix a bug in my previous checkin<commit_after>\/\/===- InlineCommon.cpp - Code common to all inliners ---------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the mechanics required to implement inlining without\n\/\/ missing any calls and updating the call graph. The decisions of which calls\n\/\/ are profitable to inline are implemented elsewhere.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Inliner.h\"\n#include \"llvm\/Constants.h\" \/\/ ConstantPointerRef should die\n#include \"llvm\/Module.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Debug.h\"\n#include \"Support\/Statistic.h\"\n#include <set>\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumInlined(\"inline\", \"Number of functions inlined\");\n Statistic<> NumDeleted(\"inline\", \"Number of functions deleted because all callers found\");\n cl::opt<unsigned> \/\/ FIXME: 200 is VERY conservative\n InlineLimit(\"inline-threshold\", cl::Hidden, cl::init(200),\n cl::desc(\"Control the amount of inlining to perform (default = 200)\"));\n}\n\nInliner::Inliner() : InlineThreshold(InlineLimit) {}\n\n\/\/ InlineCallIfPossible - If it is possible to inline the specified call site,\n\/\/ do so and update the CallGraph for this operation.\nstatic bool InlineCallIfPossible(CallSite CS, CallGraph &CG,\n const std::set<Function*> &SCCFunctions) {\n Function *Caller = CS.getInstruction()->getParent()->getParent();\n Function *Callee = CS.getCalledFunction();\n if (!InlineFunction(CS)) return false;\n\n \/\/ Update the call graph by deleting the edge from Callee to Caller\n CallGraphNode *CalleeNode = CG[Callee];\n CallGraphNode *CallerNode = CG[Caller];\n CallerNode->removeCallEdgeTo(CalleeNode);\n\n \/\/ Since we inlined all uninlined call sites in the callee into the caller,\n \/\/ add edges from the caller to all of the callees of the callee.\n for (CallGraphNode::iterator I = CalleeNode->begin(),\n E = CalleeNode->end(); I != E; ++I)\n CallerNode->addCalledFunction(*I);\n \n \/\/ If we inlined the last possible call site to the function,\n \/\/ delete the function body now.\n if (Callee->use_empty() && Callee->hasInternalLinkage() &&\n !SCCFunctions.count(Callee)) {\n DEBUG(std::cerr << \" -> Deleting dead function: \"\n << Callee->getName() << \"\\n\");\n \n \/\/ Remove any call graph edges from the callee to its callees.\n while (CalleeNode->begin() != CalleeNode->end())\n CalleeNode->removeCallEdgeTo(*(CalleeNode->end()-1));\n \n \/\/ Removing the node for callee from the call graph and delete it.\n delete CG.removeFunctionFromModule(CalleeNode);\n ++NumDeleted;\n }\n return true;\n}\n\nbool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {\n CallGraph &CG = getAnalysis<CallGraph>();\n\n std::set<Function*> SCCFunctions;\n DEBUG(std::cerr << \"Inliner visiting SCC:\");\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n if (F) SCCFunctions.insert(F);\n DEBUG(std::cerr << \" \" << (F ? F->getName() : \"INDIRECTNODE\"));\n }\n\n \/\/ Scan through and identify all call sites ahead of time so that we only\n \/\/ inline call sites in the original functions, not call sites that result\n \/\/ from inlining other functions.\n std::vector<CallSite> CallSites;\n\n for (std::set<Function*>::iterator SCCI = SCCFunctions.begin(),\n E = SCCFunctions.end(); SCCI != E; ++SCCI)\n if (Function *F = *SCCI)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {\n CallSite CS = CallSite::get(I);\n if (CS.getInstruction() && (!CS.getCalledFunction() ||\n !CS.getCalledFunction()->isExternal()))\n CallSites.push_back(CS);\n }\n\n DEBUG(std::cerr << \": \" << CallSites.size() << \" call sites.\\n\");\n \n \/\/ Now that we have all of the call sites, move the ones to functions in the\n \/\/ current SCC to the end of the list.\n unsigned FirstCallInSCC = CallSites.size();\n for (unsigned i = 0; i < FirstCallInSCC; ++i)\n if (Function *F = CallSites[i].getCalledFunction())\n if (SCCFunctions.count(F))\n std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);\n \n \/\/ Now that we have all of the call sites, loop over them and inline them if\n \/\/ it looks profitable to do so.\n bool Changed = false;\n bool LocalChange;\n do {\n LocalChange = false;\n \/\/ Iterate over the outer loop because inlining functions can cause indirect\n \/\/ calls to become direct calls.\n for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)\n if (Function *Callee = CallSites[CSi].getCalledFunction()) {\n \/\/ Calls to external functions are never inlinable.\n if (Callee->isExternal() ||\n CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){\n std::swap(CallSites[CSi], CallSites.back());\n CallSites.pop_back();\n --CSi;\n continue;\n }\n\n \/\/ If the policy determines that we should inline this function,\n \/\/ try to do so.\n CallSite CS = CallSites[CSi];\n int InlineCost = getInlineCost(CS);\n if (InlineCost >= (int)InlineThreshold) {\n DEBUG(std::cerr << \" NOT Inlining: cost=\" << InlineCost\n << \", Call: \" << *CS.getInstruction());\n } else {\n DEBUG(std::cerr << \" Inlining: cost=\" << InlineCost\n << \", Call: \" << *CS.getInstruction());\n \n Function *Caller = CS.getInstruction()->getParent()->getParent();\n\n \/\/ Attempt to inline the function...\n if (InlineCallIfPossible(CS, CG, SCCFunctions)) {\n \/\/ Remove this call site from the list.\n std::swap(CallSites[CSi], CallSites.back());\n CallSites.pop_back();\n --CSi;\n\n ++NumInlined;\n Changed = true;\n LocalChange = true;\n }\n }\n }\n } while (LocalChange);\n\n return Changed;\n}\n\n\/\/ doFinalization - Remove now-dead linkonce functions at the end of\n\/\/ processing to avoid breaking the SCC traversal.\nbool Inliner::doFinalization(CallGraph &CG) {\n std::set<CallGraphNode*> FunctionsToRemove;\n\n \/\/ Scan for all of the functions, looking for ones that should now be removed\n \/\/ from the program. Insert the dead ones in the FunctionsToRemove set.\n for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {\n CallGraphNode *CGN = I->second;\n Function *F = CGN ? CGN->getFunction() : 0;\n\n \/\/ If the only remaining use of the function is a dead constant\n \/\/ pointer ref, remove it.\n if (F && F->hasOneUse())\n if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(F->use_back()))\n if (CPR->use_empty()) {\n CPR->destroyConstant();\n if (F->hasInternalLinkage()) {\n \/\/ There *MAY* be an edge from the external call node to this\n \/\/ function. If so, remove it.\n CallGraphNode *EN = CG.getExternalCallingNode();\n CallGraphNode::iterator I = std::find(EN->begin(), EN->end(), CGN);\n if (I != EN->end()) EN->removeCallEdgeTo(CGN);\n }\n }\n\n if (F && (F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&\n F->use_empty()) {\n \/\/ Remove any call graph edges from the function to its callees.\n while (CGN->begin() != CGN->end())\n CGN->removeCallEdgeTo(*(CGN->end()-1));\n \n \/\/ If the function has external linkage (basically if it's a linkonce\n \/\/ function) remove the edge from the external node to the callee node.\n if (!F->hasInternalLinkage())\n CG.getExternalCallingNode()->removeCallEdgeTo(CGN);\n \n \/\/ Removing the node for callee from the call graph and delete it.\n FunctionsToRemove.insert(CGN);\n }\n }\n\n \/\/ Now that we know which functions to delete, do so. We didn't want to do\n \/\/ this inline, because that would invalidate our CallGraph::iterator\n \/\/ objects. :(\n bool Changed = false;\n for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),\n E = FunctionsToRemove.end(); I != E; ++I) {\n delete CG.removeFunctionFromModule(*I);\n ++NumDeleted;\n Changed = true;\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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\/browser\/plugin_observer.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/content_settings\/host_content_settings_map.h\"\n#include \"chrome\/browser\/google\/google_util.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"chrome\/browser\/plugin_installer_infobar_delegate.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/confirm_infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/simple_alert_infobar_delegate.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/view_messages.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/plugins\/npapi\/default_plugin_shared.h\"\n#include \"webkit\/plugins\/npapi\/plugin_group.h\"\n#include \"webkit\/plugins\/npapi\/plugin_list.h\"\n#include \"webkit\/plugins\/npapi\/webplugininfo.h\"\n\nnamespace {\n\n\/\/ PluginInfoBarDelegate ------------------------------------------------------\n\nclass PluginInfoBarDelegate : public ConfirmInfoBarDelegate {\n public:\n PluginInfoBarDelegate(TabContents* tab_contents, const string16& name);\n\n protected:\n virtual ~PluginInfoBarDelegate();\n\n \/\/ ConfirmInfoBarDelegate:\n virtual void InfoBarClosed();\n virtual bool Cancel();\n virtual bool LinkClicked(WindowOpenDisposition disposition);\n\n string16 name_;\n TabContents* tab_contents_;\n\n private:\n \/\/ ConfirmInfoBarDelegate:\n virtual SkBitmap* GetIcon() const;\n virtual string16 GetLinkText();\n\n DISALLOW_COPY_AND_ASSIGN(PluginInfoBarDelegate);\n};\n\nPluginInfoBarDelegate::PluginInfoBarDelegate(TabContents* tab_contents,\n const string16& name)\n : ConfirmInfoBarDelegate(tab_contents),\n name_(name),\n tab_contents_(tab_contents) {\n}\n\nPluginInfoBarDelegate::~PluginInfoBarDelegate() {\n}\n\nvoid PluginInfoBarDelegate::InfoBarClosed() {\n delete this;\n}\n\nbool PluginInfoBarDelegate::Cancel() {\n tab_contents_->render_view_host()->LoadBlockedPlugins();\n return true;\n}\n\nbool PluginInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {\n GURL url = google_util::AppendGoogleLocaleParam(\n GURL(chrome::kOutdatedPluginLearnMoreURL));\n tab_contents_->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);\n return false;\n}\n\nSkBitmap* PluginInfoBarDelegate::GetIcon() const {\n return ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_PLUGIN_INSTALL);\n}\n\nstring16 PluginInfoBarDelegate::GetLinkText() {\n return l10n_util::GetStringUTF16(IDS_LEARN_MORE);\n}\n\n\n\/\/ BlockedPluginInfoBarDelegate -----------------------------------------------\n\nclass BlockedPluginInfoBarDelegate : public PluginInfoBarDelegate {\n public:\n BlockedPluginInfoBarDelegate(TabContents* tab_contents,\n const string16& name);\n\n private:\n virtual ~BlockedPluginInfoBarDelegate();\n\n \/\/ PluginInfoBarDelegate:\n virtual string16 GetMessageText() const;\n virtual string16 GetButtonLabel(InfoBarButton button) const;\n virtual bool Accept();\n virtual bool Cancel();\n virtual void InfoBarClosed();\n virtual void InfoBarDismissed();\n virtual bool LinkClicked(WindowOpenDisposition disposition);\n\n DISALLOW_COPY_AND_ASSIGN(BlockedPluginInfoBarDelegate);\n};\n\nBlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(\n TabContents* tab_contents,\n const string16& utf16_name)\n : PluginInfoBarDelegate(tab_contents, utf16_name) {\n UserMetrics::RecordAction(UserMetricsAction(\"BlockedPluginInfobar.Shown\"));\n std::string name = UTF16ToUTF8(utf16_name);\n if (name == webkit::npapi::PluginGroup::kJavaGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Shown.Java\"));\n else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Shown.QuickTime\"));\n else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Shown.Shockwave\"));\n else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Shown.RealPlayer\"));\n}\n\nBlockedPluginInfoBarDelegate::~BlockedPluginInfoBarDelegate() {\n}\n\nstring16 BlockedPluginInfoBarDelegate::GetMessageText() const {\n return l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, name_);\n}\n\nstring16 BlockedPluginInfoBarDelegate::GetButtonLabel(\n InfoBarButton button) const {\n return l10n_util::GetStringUTF16((button == BUTTON_OK) ?\n IDS_PLUGIN_ENABLE_ALWAYS : IDS_PLUGIN_ENABLE_TEMPORARILY);\n}\n\nbool BlockedPluginInfoBarDelegate::Accept() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.AlwaysAllow\"));\n tab_contents_->profile()->GetHostContentSettingsMap()->AddExceptionForURL(\n tab_contents_->GetURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(),\n CONTENT_SETTING_ALLOW);\n tab_contents_->render_view_host()->LoadBlockedPlugins();\n return true;\n}\n\nbool BlockedPluginInfoBarDelegate::Cancel() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.AllowThisTime\"));\n return PluginInfoBarDelegate::Cancel();\n}\n\nvoid BlockedPluginInfoBarDelegate::InfoBarDismissed() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Dismissed\"));\n}\n\nvoid BlockedPluginInfoBarDelegate::InfoBarClosed() {\n UserMetrics::RecordAction(UserMetricsAction(\"BlockedPluginInfobar.Closed\"));\n PluginInfoBarDelegate::InfoBarClosed();\n}\n\nbool BlockedPluginInfoBarDelegate::LinkClicked(\n WindowOpenDisposition disposition) {\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.LearnMore\"));\n return PluginInfoBarDelegate::LinkClicked(disposition);\n}\n\n\/\/ OutdatedPluginInfoBarDelegate ----------------------------------------------\n\nclass OutdatedPluginInfoBarDelegate : public PluginInfoBarDelegate {\n public:\n OutdatedPluginInfoBarDelegate(TabContents* tab_contents,\n const string16& name,\n const GURL& update_url);\n\n private:\n virtual ~OutdatedPluginInfoBarDelegate();\n\n \/\/ PluginInfoBarDelegate:\n virtual string16 GetMessageText() const;\n virtual string16 GetButtonLabel(InfoBarButton button) const;\n virtual bool Accept();\n virtual bool Cancel();\n virtual void InfoBarClosed();\n virtual void InfoBarDismissed();\n virtual bool LinkClicked(WindowOpenDisposition disposition);\n\n GURL update_url_;\n\n DISALLOW_COPY_AND_ASSIGN(OutdatedPluginInfoBarDelegate);\n};\n\nOutdatedPluginInfoBarDelegate::OutdatedPluginInfoBarDelegate(\n TabContents* tab_contents,\n const string16& utf16_name,\n const GURL& update_url)\n : PluginInfoBarDelegate(tab_contents, utf16_name),\n update_url_(update_url) {\n UserMetrics::RecordAction(UserMetricsAction(\"OutdatedPluginInfobar.Shown\"));\n std::string name = UTF16ToUTF8(utf16_name);\n if (name == webkit::npapi::PluginGroup::kJavaGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.Java\"));\n else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.QuickTime\"));\n else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.Shockwave\"));\n else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.RealPlayer\"));\n else if (name == webkit::npapi::PluginGroup::kSilverlightGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.Silverlight\"));\n else if (name == webkit::npapi::PluginGroup::kAdobeReaderGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.Reader\"));\n}\n\nOutdatedPluginInfoBarDelegate::~OutdatedPluginInfoBarDelegate() {\n}\n\nstring16 OutdatedPluginInfoBarDelegate::GetMessageText() const {\n return l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED_PROMPT, name_);\n}\n\nstring16 OutdatedPluginInfoBarDelegate::GetButtonLabel(\n InfoBarButton button) const {\n return l10n_util::GetStringUTF16((button == BUTTON_OK) ?\n IDS_PLUGIN_UPDATE : IDS_PLUGIN_ENABLE_TEMPORARILY);\n}\n\nbool OutdatedPluginInfoBarDelegate::Accept() {\n UserMetrics::RecordAction(UserMetricsAction(\"OutdatedPluginInfobar.Update\"));\n tab_contents_->OpenURL(update_url_, GURL(), NEW_FOREGROUND_TAB,\n PageTransition::LINK);\n return false;\n}\n\nbool OutdatedPluginInfoBarDelegate::Cancel() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.AllowThisTime\"));\n return PluginInfoBarDelegate::Cancel();\n}\n\nvoid OutdatedPluginInfoBarDelegate::InfoBarDismissed() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Dismissed\"));\n}\n\nvoid OutdatedPluginInfoBarDelegate::InfoBarClosed() {\n UserMetrics::RecordAction(UserMetricsAction(\"OutdatedPluginInfobar.Closed\"));\n PluginInfoBarDelegate::InfoBarClosed();\n}\n\nbool OutdatedPluginInfoBarDelegate::LinkClicked(\n WindowOpenDisposition disposition) {\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.LearnMore\"));\n return PluginInfoBarDelegate::LinkClicked(disposition);\n}\n\n} \/\/ namespace\n\n\n\/\/ PluginObserver -------------------------------------------------------------\n\nPluginObserver::PluginObserver(TabContents* tab_contents)\n : TabContentsObserver(tab_contents) {\n}\n\nPluginObserver::~PluginObserver() {\n}\n\nbool PluginObserver::OnMessageReceived(const IPC::Message& message) {\n IPC_BEGIN_MESSAGE_MAP(PluginObserver, message)\n IPC_MESSAGE_HANDLER(ViewHostMsg_MissingPluginStatus, OnMissingPluginStatus)\n IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)\n IPC_MESSAGE_HANDLER(ViewHostMsg_BlockedOutdatedPlugin,\n OnBlockedOutdatedPlugin)\n IPC_MESSAGE_UNHANDLED(return false)\n IPC_END_MESSAGE_MAP()\n\n return true;\n}\n\nPluginInstallerInfoBarDelegate* PluginObserver::GetPluginInstaller() {\n if (plugin_installer_ == NULL)\n plugin_installer_.reset(new PluginInstallerInfoBarDelegate(tab_contents()));\n return plugin_installer_->AsPluginInstallerInfoBarDelegate();\n}\n\nvoid PluginObserver::OnMissingPluginStatus(int status) {\n \/\/ TODO(PORT): pull in when plug-ins work\n#if defined(OS_WIN)\n if (status == webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE) {\n tab_contents()->AddInfoBar(\n new PluginInstallerInfoBarDelegate(tab_contents()));\n return;\n }\n\n DCHECK_EQ(webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD,\n status);\n for (size_t i = 0; i < tab_contents()->infobar_count(); ++i) {\n InfoBarDelegate* delegate = tab_contents()->GetInfoBarDelegateAt(i);\n if (delegate->AsPluginInstallerInfoBarDelegate() != NULL) {\n tab_contents()->RemoveInfoBar(delegate);\n return;\n }\n }\n#endif\n}\n\nvoid PluginObserver::OnCrashedPlugin(const FilePath& plugin_path) {\n DCHECK(!plugin_path.value().empty());\n\n string16 plugin_name = plugin_path.LossyDisplayName();\n webkit::npapi::WebPluginInfo plugin_info;\n if (webkit::npapi::PluginList::Singleton()->GetPluginInfoByPath(\n plugin_path, &plugin_info) &&\n !plugin_info.name.empty()) {\n plugin_name = plugin_info.name;\n#if defined(OS_MACOSX)\n \/\/ Many plugins on the Mac have .plugin in the actual name, which looks\n \/\/ terrible, so look for that and strip it off if present.\n const std::string kPluginExtension = \".plugin\";\n if (EndsWith(plugin_name, ASCIIToUTF16(kPluginExtension), true))\n plugin_name.erase(plugin_name.length() - kPluginExtension.length());\n#endif \/\/ OS_MACOSX\n }\n SkBitmap* crash_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_PLUGIN_CRASHED);\n tab_contents()->AddInfoBar(new SimpleAlertInfoBarDelegate(tab_contents(),\n crash_icon,\n l10n_util::GetStringFUTF16(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),\n true));\n}\n\nvoid PluginObserver::OnBlockedOutdatedPlugin(const string16& name,\n const GURL& update_url) {\n tab_contents()->AddInfoBar(update_url.is_empty() ?\n static_cast<InfoBarDelegate*>(new BlockedPluginInfoBarDelegate(\n tab_contents(), name)) :\n new OutdatedPluginInfoBarDelegate(tab_contents(), name, update_url));\n}\n\n<commit_msg>Re-order the \"Run this time\" and \"Update...\" buttons as additional attempt to try and put users in the right direction.<commit_after>\/\/ Copyright (c) 2011 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\/browser\/plugin_observer.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/content_settings\/host_content_settings_map.h\"\n#include \"chrome\/browser\/google\/google_util.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"chrome\/browser\/plugin_installer_infobar_delegate.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/confirm_infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/simple_alert_infobar_delegate.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/view_messages.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/plugins\/npapi\/default_plugin_shared.h\"\n#include \"webkit\/plugins\/npapi\/plugin_group.h\"\n#include \"webkit\/plugins\/npapi\/plugin_list.h\"\n#include \"webkit\/plugins\/npapi\/webplugininfo.h\"\n\nnamespace {\n\n\/\/ PluginInfoBarDelegate ------------------------------------------------------\n\nclass PluginInfoBarDelegate : public ConfirmInfoBarDelegate {\n public:\n PluginInfoBarDelegate(TabContents* tab_contents, const string16& name);\n\n protected:\n virtual ~PluginInfoBarDelegate();\n\n \/\/ ConfirmInfoBarDelegate:\n virtual void InfoBarClosed();\n virtual bool Cancel();\n virtual bool LinkClicked(WindowOpenDisposition disposition);\n\n string16 name_;\n TabContents* tab_contents_;\n\n private:\n \/\/ ConfirmInfoBarDelegate:\n virtual SkBitmap* GetIcon() const;\n virtual string16 GetLinkText();\n\n DISALLOW_COPY_AND_ASSIGN(PluginInfoBarDelegate);\n};\n\nPluginInfoBarDelegate::PluginInfoBarDelegate(TabContents* tab_contents,\n const string16& name)\n : ConfirmInfoBarDelegate(tab_contents),\n name_(name),\n tab_contents_(tab_contents) {\n}\n\nPluginInfoBarDelegate::~PluginInfoBarDelegate() {\n}\n\nvoid PluginInfoBarDelegate::InfoBarClosed() {\n delete this;\n}\n\nbool PluginInfoBarDelegate::Cancel() {\n tab_contents_->render_view_host()->LoadBlockedPlugins();\n return true;\n}\n\nbool PluginInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {\n GURL url = google_util::AppendGoogleLocaleParam(\n GURL(chrome::kOutdatedPluginLearnMoreURL));\n tab_contents_->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);\n return false;\n}\n\nSkBitmap* PluginInfoBarDelegate::GetIcon() const {\n return ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_PLUGIN_INSTALL);\n}\n\nstring16 PluginInfoBarDelegate::GetLinkText() {\n return l10n_util::GetStringUTF16(IDS_LEARN_MORE);\n}\n\n\n\/\/ BlockedPluginInfoBarDelegate -----------------------------------------------\n\nclass BlockedPluginInfoBarDelegate : public PluginInfoBarDelegate {\n public:\n BlockedPluginInfoBarDelegate(TabContents* tab_contents,\n const string16& name);\n\n private:\n virtual ~BlockedPluginInfoBarDelegate();\n\n \/\/ PluginInfoBarDelegate:\n virtual string16 GetMessageText() const;\n virtual string16 GetButtonLabel(InfoBarButton button) const;\n virtual bool Accept();\n virtual bool Cancel();\n virtual void InfoBarClosed();\n virtual void InfoBarDismissed();\n virtual bool LinkClicked(WindowOpenDisposition disposition);\n\n DISALLOW_COPY_AND_ASSIGN(BlockedPluginInfoBarDelegate);\n};\n\nBlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(\n TabContents* tab_contents,\n const string16& utf16_name)\n : PluginInfoBarDelegate(tab_contents, utf16_name) {\n UserMetrics::RecordAction(UserMetricsAction(\"BlockedPluginInfobar.Shown\"));\n std::string name = UTF16ToUTF8(utf16_name);\n if (name == webkit::npapi::PluginGroup::kJavaGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Shown.Java\"));\n else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Shown.QuickTime\"));\n else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Shown.Shockwave\"));\n else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Shown.RealPlayer\"));\n}\n\nBlockedPluginInfoBarDelegate::~BlockedPluginInfoBarDelegate() {\n}\n\nstring16 BlockedPluginInfoBarDelegate::GetMessageText() const {\n return l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, name_);\n}\n\nstring16 BlockedPluginInfoBarDelegate::GetButtonLabel(\n InfoBarButton button) const {\n return l10n_util::GetStringUTF16((button == BUTTON_OK) ?\n IDS_PLUGIN_ENABLE_ALWAYS : IDS_PLUGIN_ENABLE_TEMPORARILY);\n}\n\nbool BlockedPluginInfoBarDelegate::Accept() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.AlwaysAllow\"));\n tab_contents_->profile()->GetHostContentSettingsMap()->AddExceptionForURL(\n tab_contents_->GetURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(),\n CONTENT_SETTING_ALLOW);\n tab_contents_->render_view_host()->LoadBlockedPlugins();\n return true;\n}\n\nbool BlockedPluginInfoBarDelegate::Cancel() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.AllowThisTime\"));\n return PluginInfoBarDelegate::Cancel();\n}\n\nvoid BlockedPluginInfoBarDelegate::InfoBarDismissed() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.Dismissed\"));\n}\n\nvoid BlockedPluginInfoBarDelegate::InfoBarClosed() {\n UserMetrics::RecordAction(UserMetricsAction(\"BlockedPluginInfobar.Closed\"));\n PluginInfoBarDelegate::InfoBarClosed();\n}\n\nbool BlockedPluginInfoBarDelegate::LinkClicked(\n WindowOpenDisposition disposition) {\n UserMetrics::RecordAction(\n UserMetricsAction(\"BlockedPluginInfobar.LearnMore\"));\n return PluginInfoBarDelegate::LinkClicked(disposition);\n}\n\n\/\/ OutdatedPluginInfoBarDelegate ----------------------------------------------\n\nclass OutdatedPluginInfoBarDelegate : public PluginInfoBarDelegate {\n public:\n OutdatedPluginInfoBarDelegate(TabContents* tab_contents,\n const string16& name,\n const GURL& update_url);\n\n private:\n virtual ~OutdatedPluginInfoBarDelegate();\n\n \/\/ PluginInfoBarDelegate:\n virtual string16 GetMessageText() const;\n virtual string16 GetButtonLabel(InfoBarButton button) const;\n virtual bool Accept();\n virtual bool Cancel();\n virtual void InfoBarClosed();\n virtual void InfoBarDismissed();\n virtual bool LinkClicked(WindowOpenDisposition disposition);\n\n GURL update_url_;\n\n DISALLOW_COPY_AND_ASSIGN(OutdatedPluginInfoBarDelegate);\n};\n\nOutdatedPluginInfoBarDelegate::OutdatedPluginInfoBarDelegate(\n TabContents* tab_contents,\n const string16& utf16_name,\n const GURL& update_url)\n : PluginInfoBarDelegate(tab_contents, utf16_name),\n update_url_(update_url) {\n UserMetrics::RecordAction(UserMetricsAction(\"OutdatedPluginInfobar.Shown\"));\n std::string name = UTF16ToUTF8(utf16_name);\n if (name == webkit::npapi::PluginGroup::kJavaGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.Java\"));\n else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.QuickTime\"));\n else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.Shockwave\"));\n else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.RealPlayer\"));\n else if (name == webkit::npapi::PluginGroup::kSilverlightGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.Silverlight\"));\n else if (name == webkit::npapi::PluginGroup::kAdobeReaderGroupName)\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Shown.Reader\"));\n}\n\nOutdatedPluginInfoBarDelegate::~OutdatedPluginInfoBarDelegate() {\n}\n\nstring16 OutdatedPluginInfoBarDelegate::GetMessageText() const {\n return l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED_PROMPT, name_);\n}\n\nstring16 OutdatedPluginInfoBarDelegate::GetButtonLabel(\n InfoBarButton button) const {\n return l10n_util::GetStringUTF16((button == BUTTON_OK) ?\n IDS_PLUGIN_ENABLE_TEMPORARILY : IDS_PLUGIN_UPDATE);\n}\n\nbool OutdatedPluginInfoBarDelegate::Accept() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.AllowThisTime\"));\n \/\/ This is intentional; the base class cancel is mapped to running all\n \/\/ plug-ins and closing the infobar. We've rewired Accept() and Cancel() in\n \/\/ the \"outdated\" case so that the first button is \"Update...\"\n return PluginInfoBarDelegate::Cancel();\n}\n\nbool OutdatedPluginInfoBarDelegate::Cancel() {\n UserMetrics::RecordAction(UserMetricsAction(\"OutdatedPluginInfobar.Update\"));\n tab_contents_->OpenURL(update_url_, GURL(), NEW_FOREGROUND_TAB,\n PageTransition::LINK);\n return false;\n}\n\nvoid OutdatedPluginInfoBarDelegate::InfoBarDismissed() {\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.Dismissed\"));\n}\n\nvoid OutdatedPluginInfoBarDelegate::InfoBarClosed() {\n UserMetrics::RecordAction(UserMetricsAction(\"OutdatedPluginInfobar.Closed\"));\n PluginInfoBarDelegate::InfoBarClosed();\n}\n\nbool OutdatedPluginInfoBarDelegate::LinkClicked(\n WindowOpenDisposition disposition) {\n UserMetrics::RecordAction(\n UserMetricsAction(\"OutdatedPluginInfobar.LearnMore\"));\n return PluginInfoBarDelegate::LinkClicked(disposition);\n}\n\n} \/\/ namespace\n\n\n\/\/ PluginObserver -------------------------------------------------------------\n\nPluginObserver::PluginObserver(TabContents* tab_contents)\n : TabContentsObserver(tab_contents) {\n}\n\nPluginObserver::~PluginObserver() {\n}\n\nbool PluginObserver::OnMessageReceived(const IPC::Message& message) {\n IPC_BEGIN_MESSAGE_MAP(PluginObserver, message)\n IPC_MESSAGE_HANDLER(ViewHostMsg_MissingPluginStatus, OnMissingPluginStatus)\n IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)\n IPC_MESSAGE_HANDLER(ViewHostMsg_BlockedOutdatedPlugin,\n OnBlockedOutdatedPlugin)\n IPC_MESSAGE_UNHANDLED(return false)\n IPC_END_MESSAGE_MAP()\n\n return true;\n}\n\nPluginInstallerInfoBarDelegate* PluginObserver::GetPluginInstaller() {\n if (plugin_installer_ == NULL)\n plugin_installer_.reset(new PluginInstallerInfoBarDelegate(tab_contents()));\n return plugin_installer_->AsPluginInstallerInfoBarDelegate();\n}\n\nvoid PluginObserver::OnMissingPluginStatus(int status) {\n \/\/ TODO(PORT): pull in when plug-ins work\n#if defined(OS_WIN)\n if (status == webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE) {\n tab_contents()->AddInfoBar(\n new PluginInstallerInfoBarDelegate(tab_contents()));\n return;\n }\n\n DCHECK_EQ(webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD,\n status);\n for (size_t i = 0; i < tab_contents()->infobar_count(); ++i) {\n InfoBarDelegate* delegate = tab_contents()->GetInfoBarDelegateAt(i);\n if (delegate->AsPluginInstallerInfoBarDelegate() != NULL) {\n tab_contents()->RemoveInfoBar(delegate);\n return;\n }\n }\n#endif\n}\n\nvoid PluginObserver::OnCrashedPlugin(const FilePath& plugin_path) {\n DCHECK(!plugin_path.value().empty());\n\n string16 plugin_name = plugin_path.LossyDisplayName();\n webkit::npapi::WebPluginInfo plugin_info;\n if (webkit::npapi::PluginList::Singleton()->GetPluginInfoByPath(\n plugin_path, &plugin_info) &&\n !plugin_info.name.empty()) {\n plugin_name = plugin_info.name;\n#if defined(OS_MACOSX)\n \/\/ Many plugins on the Mac have .plugin in the actual name, which looks\n \/\/ terrible, so look for that and strip it off if present.\n const std::string kPluginExtension = \".plugin\";\n if (EndsWith(plugin_name, ASCIIToUTF16(kPluginExtension), true))\n plugin_name.erase(plugin_name.length() - kPluginExtension.length());\n#endif \/\/ OS_MACOSX\n }\n SkBitmap* crash_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_PLUGIN_CRASHED);\n tab_contents()->AddInfoBar(new SimpleAlertInfoBarDelegate(tab_contents(),\n crash_icon,\n l10n_util::GetStringFUTF16(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),\n true));\n}\n\nvoid PluginObserver::OnBlockedOutdatedPlugin(const string16& name,\n const GURL& update_url) {\n tab_contents()->AddInfoBar(update_url.is_empty() ?\n static_cast<InfoBarDelegate*>(new BlockedPluginInfoBarDelegate(\n tab_contents(), name)) :\n new OutdatedPluginInfoBarDelegate(tab_contents(), name, update_url));\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fixup for r172828: use InternalScopedBuffer in favor of large stack buffers<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===\/\/\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\/\/ This pass transforms loops by placing phi nodes at the end of the loops for\n\/\/ all values that are live across the loop boundary. For example, it turns\n\/\/ the left into the right code:\n\/\/ \n\/\/ for (...) for (...)\n\/\/ if (c) if (c)\n\/\/ X1 = ... X1 = ...\n\/\/ else else\n\/\/ X2 = ... X2 = ...\n\/\/ X3 = phi(X1, X2) X3 = phi(X1, X2)\n\/\/ ... = X3 + 4 X4 = phi(X3)\n\/\/ ... = X4 + 4\n\/\/\n\/\/ This is still valid LLVM; the extra phi nodes are purely redundant, and will\n\/\/ be trivially eliminated by InstCombine. The major benefit of this \n\/\/ transformation is that it makes many other loop optimizations, such as \n\/\/ LoopUnswitching, simpler.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"lcssa\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/Dominators.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Analysis\/ScalarEvolution.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Utils\/SSAUpdater.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Support\/PredIteratorCache.h\"\nusing namespace llvm;\n\nSTATISTIC(NumLCSSA, \"Number of live out of a loop variables\");\n\nnamespace {\n struct LCSSA : public LoopPass {\n static char ID; \/\/ Pass identification, replacement for typeid\n LCSSA() : LoopPass(ID) {\n initializeLCSSAPass(*PassRegistry::getPassRegistry());\n }\n\n \/\/ Cached analysis information for the current function.\n DominatorTree *DT;\n std::vector<BasicBlock*> LoopBlocks;\n PredIteratorCache PredCache;\n Loop *L;\n \n virtual bool runOnLoop(Loop *L, LPPassManager &LPM);\n\n \/\/\/ This transformation requires natural loop information & requires that\n \/\/\/ loop preheaders be inserted into the CFG. It maintains both of these,\n \/\/\/ as well as the CFG. It also requires dominator information.\n \/\/\/\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n\n AU.addRequired<DominatorTree>();\n AU.addRequired<LoopInfo>();\n AU.addPreservedID(LoopSimplifyID);\n AU.addPreserved<ScalarEvolution>();\n }\n private:\n bool ProcessInstruction(Instruction *Inst,\n const SmallVectorImpl<BasicBlock*> &ExitBlocks);\n \n \/\/\/ verifyAnalysis() - Verify loop nest.\n virtual void verifyAnalysis() const {\n \/\/ Check the special guarantees that LCSSA makes.\n assert(L->isLCSSAForm(*DT) && \"LCSSA form not preserved!\");\n }\n\n \/\/\/ inLoop - returns true if the given block is within the current loop\n bool inLoop(BasicBlock *B) const {\n return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);\n }\n };\n}\n \nchar LCSSA::ID = 0;\nINITIALIZE_PASS_BEGIN(LCSSA, \"lcssa\", \"Loop-Closed SSA Form Pass\", false, false)\nINITIALIZE_PASS_DEPENDENCY(DominatorTree)\nINITIALIZE_PASS_DEPENDENCY(LoopInfo)\nINITIALIZE_PASS_END(LCSSA, \"lcssa\", \"Loop-Closed SSA Form Pass\", false, false)\n\nPass *llvm::createLCSSAPass() { return new LCSSA(); }\nchar &llvm::LCSSAID = LCSSA::ID;\n\n\n\/\/\/ BlockDominatesAnExit - Return true if the specified block dominates at least\n\/\/\/ one of the blocks in the specified list.\nstatic bool BlockDominatesAnExit(BasicBlock *BB,\n const SmallVectorImpl<BasicBlock*> &ExitBlocks,\n DominatorTree *DT) {\n DomTreeNode *DomNode = DT->getNode(BB);\n for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)\n if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))\n return true;\n\n return false;\n}\n\n\n\/\/\/ runOnFunction - Process all loops in the function, inner-most out.\nbool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {\n L = TheLoop;\n \n DT = &getAnalysis<DominatorTree>();\n\n \/\/ Get the set of exiting blocks.\n SmallVector<BasicBlock*, 8> ExitBlocks;\n L->getExitBlocks(ExitBlocks);\n \n if (ExitBlocks.empty())\n return false;\n \n \/\/ Speed up queries by creating a sorted vector of blocks.\n LoopBlocks.clear();\n LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());\n array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());\n \n \/\/ Look at all the instructions in the loop, checking to see if they have uses\n \/\/ outside the loop. If so, rewrite those uses.\n bool MadeChange = false;\n \n for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();\n BBI != E; ++BBI) {\n BasicBlock *BB = *BBI;\n \n \/\/ For large loops, avoid use-scanning by using dominance information: In\n \/\/ particular, if a block does not dominate any of the loop exits, then none\n \/\/ of the values defined in the block could be used outside the loop.\n if (!BlockDominatesAnExit(BB, ExitBlocks, DT))\n continue;\n \n for (BasicBlock::iterator I = BB->begin(), E = BB->end();\n I != E; ++I) {\n \/\/ Reject two common cases fast: instructions with no uses (like stores)\n \/\/ and instructions with one use that is in the same block as this.\n if (I->use_empty() ||\n (I->hasOneUse() && I->use_back()->getParent() == BB &&\n !isa<PHINode>(I->use_back())))\n continue;\n \n MadeChange |= ProcessInstruction(I, ExitBlocks);\n }\n }\n \n assert(L->isLCSSAForm(*DT));\n PredCache.clear();\n\n return MadeChange;\n}\n\n\/\/\/ isExitBlock - Return true if the specified block is in the list.\nstatic bool isExitBlock(BasicBlock *BB,\n const SmallVectorImpl<BasicBlock*> &ExitBlocks) {\n for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)\n if (ExitBlocks[i] == BB)\n return true;\n return false;\n}\n\n\/\/\/ ProcessInstruction - Given an instruction in the loop, check to see if it\n\/\/\/ has any uses that are outside the current loop. If so, insert LCSSA PHI\n\/\/\/ nodes and rewrite the uses.\nbool LCSSA::ProcessInstruction(Instruction *Inst,\n const SmallVectorImpl<BasicBlock*> &ExitBlocks) {\n SmallVector<Use*, 16> UsesToRewrite;\n \n BasicBlock *InstBB = Inst->getParent();\n \n for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();\n UI != E; ++UI) {\n User *U = *UI;\n BasicBlock *UserBB = cast<Instruction>(U)->getParent();\n if (PHINode *PN = dyn_cast<PHINode>(U))\n UserBB = PN->getIncomingBlock(UI);\n \n if (InstBB != UserBB && !inLoop(UserBB))\n UsesToRewrite.push_back(&UI.getUse());\n }\n\n \/\/ If there are no uses outside the loop, exit with no change.\n if (UsesToRewrite.empty()) return false;\n \n ++NumLCSSA; \/\/ We are applying the transformation\n\n \/\/ Invoke instructions are special in that their result value is not available\n \/\/ along their unwind edge. The code below tests to see whether DomBB dominates\n \/\/ the value, so adjust DomBB to the normal destination block, which is\n \/\/ effectively where the value is first usable.\n BasicBlock *DomBB = Inst->getParent();\n if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))\n DomBB = Inv->getNormalDest();\n\n DomTreeNode *DomNode = DT->getNode(DomBB);\n\n SmallVector<PHINode*, 16> AddedPHIs;\n\n SSAUpdater SSAUpdate;\n SSAUpdate.Initialize(Inst->getType(), Inst->getName());\n \n \/\/ Insert the LCSSA phi's into all of the exit blocks dominated by the\n \/\/ value, and add them to the Phi's map.\n for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),\n BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {\n BasicBlock *ExitBB = *BBI;\n if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;\n \n \/\/ If we already inserted something for this BB, don't reprocess it.\n if (SSAUpdate.HasValueForBlock(ExitBB)) continue;\n \n PHINode *PN = PHINode::Create(Inst->getType(),\n PredCache.GetNumPreds(ExitBB),\n Inst->getName()+\".lcssa\",\n ExitBB->begin());\n PN->setDebugLoc(GetFirstDebugLocInBasicBlock(ExitBB));\n\n \/\/ Add inputs from inside the loop for this PHI.\n for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {\n PN->addIncoming(Inst, *PI);\n\n \/\/ If the exit block has a predecessor not within the loop, arrange for\n \/\/ the incoming value use corresponding to that predecessor to be\n \/\/ rewritten in terms of a different LCSSA PHI.\n if (!inLoop(*PI))\n UsesToRewrite.push_back(\n &PN->getOperandUse(\n PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));\n }\n\n AddedPHIs.push_back(PN);\n \n \/\/ Remember that this phi makes the value alive in this block.\n SSAUpdate.AddAvailableValue(ExitBB, PN);\n }\n \n \/\/ Rewrite all uses outside the loop in terms of the new PHIs we just\n \/\/ inserted.\n for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {\n \/\/ If this use is in an exit block, rewrite to use the newly inserted PHI.\n \/\/ This is required for correctness because SSAUpdate doesn't handle uses in\n \/\/ the same block. It assumes the PHI we inserted is at the end of the\n \/\/ block.\n Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());\n BasicBlock *UserBB = User->getParent();\n if (PHINode *PN = dyn_cast<PHINode>(User))\n UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);\n\n if (isa<PHINode>(UserBB->begin()) &&\n isExitBlock(UserBB, ExitBlocks)) {\n UsesToRewrite[i]->set(UserBB->begin());\n continue;\n }\n \n \/\/ Otherwise, do full PHI insertion.\n SSAUpdate.RewriteUse(*UsesToRewrite[i]);\n }\n\n \/\/ Remove PHI nodes that did not have any uses rewritten.\n for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {\n if (AddedPHIs[i]->use_empty())\n AddedPHIs[i]->eraseFromParent();\n }\n \n return true;\n}\n\n<commit_msg>There is no need to force DebugLoc on a PHI at this point.<commit_after>\/\/===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===\/\/\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\/\/ This pass transforms loops by placing phi nodes at the end of the loops for\n\/\/ all values that are live across the loop boundary. For example, it turns\n\/\/ the left into the right code:\n\/\/ \n\/\/ for (...) for (...)\n\/\/ if (c) if (c)\n\/\/ X1 = ... X1 = ...\n\/\/ else else\n\/\/ X2 = ... X2 = ...\n\/\/ X3 = phi(X1, X2) X3 = phi(X1, X2)\n\/\/ ... = X3 + 4 X4 = phi(X3)\n\/\/ ... = X4 + 4\n\/\/\n\/\/ This is still valid LLVM; the extra phi nodes are purely redundant, and will\n\/\/ be trivially eliminated by InstCombine. The major benefit of this \n\/\/ transformation is that it makes many other loop optimizations, such as \n\/\/ LoopUnswitching, simpler.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"lcssa\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/Dominators.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Analysis\/ScalarEvolution.h\"\n#include \"llvm\/Transforms\/Utils\/SSAUpdater.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Support\/PredIteratorCache.h\"\nusing namespace llvm;\n\nSTATISTIC(NumLCSSA, \"Number of live out of a loop variables\");\n\nnamespace {\n struct LCSSA : public LoopPass {\n static char ID; \/\/ Pass identification, replacement for typeid\n LCSSA() : LoopPass(ID) {\n initializeLCSSAPass(*PassRegistry::getPassRegistry());\n }\n\n \/\/ Cached analysis information for the current function.\n DominatorTree *DT;\n std::vector<BasicBlock*> LoopBlocks;\n PredIteratorCache PredCache;\n Loop *L;\n \n virtual bool runOnLoop(Loop *L, LPPassManager &LPM);\n\n \/\/\/ This transformation requires natural loop information & requires that\n \/\/\/ loop preheaders be inserted into the CFG. It maintains both of these,\n \/\/\/ as well as the CFG. It also requires dominator information.\n \/\/\/\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n\n AU.addRequired<DominatorTree>();\n AU.addRequired<LoopInfo>();\n AU.addPreservedID(LoopSimplifyID);\n AU.addPreserved<ScalarEvolution>();\n }\n private:\n bool ProcessInstruction(Instruction *Inst,\n const SmallVectorImpl<BasicBlock*> &ExitBlocks);\n \n \/\/\/ verifyAnalysis() - Verify loop nest.\n virtual void verifyAnalysis() const {\n \/\/ Check the special guarantees that LCSSA makes.\n assert(L->isLCSSAForm(*DT) && \"LCSSA form not preserved!\");\n }\n\n \/\/\/ inLoop - returns true if the given block is within the current loop\n bool inLoop(BasicBlock *B) const {\n return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);\n }\n };\n}\n \nchar LCSSA::ID = 0;\nINITIALIZE_PASS_BEGIN(LCSSA, \"lcssa\", \"Loop-Closed SSA Form Pass\", false, false)\nINITIALIZE_PASS_DEPENDENCY(DominatorTree)\nINITIALIZE_PASS_DEPENDENCY(LoopInfo)\nINITIALIZE_PASS_END(LCSSA, \"lcssa\", \"Loop-Closed SSA Form Pass\", false, false)\n\nPass *llvm::createLCSSAPass() { return new LCSSA(); }\nchar &llvm::LCSSAID = LCSSA::ID;\n\n\n\/\/\/ BlockDominatesAnExit - Return true if the specified block dominates at least\n\/\/\/ one of the blocks in the specified list.\nstatic bool BlockDominatesAnExit(BasicBlock *BB,\n const SmallVectorImpl<BasicBlock*> &ExitBlocks,\n DominatorTree *DT) {\n DomTreeNode *DomNode = DT->getNode(BB);\n for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)\n if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))\n return true;\n\n return false;\n}\n\n\n\/\/\/ runOnFunction - Process all loops in the function, inner-most out.\nbool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {\n L = TheLoop;\n \n DT = &getAnalysis<DominatorTree>();\n\n \/\/ Get the set of exiting blocks.\n SmallVector<BasicBlock*, 8> ExitBlocks;\n L->getExitBlocks(ExitBlocks);\n \n if (ExitBlocks.empty())\n return false;\n \n \/\/ Speed up queries by creating a sorted vector of blocks.\n LoopBlocks.clear();\n LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());\n array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());\n \n \/\/ Look at all the instructions in the loop, checking to see if they have uses\n \/\/ outside the loop. If so, rewrite those uses.\n bool MadeChange = false;\n \n for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();\n BBI != E; ++BBI) {\n BasicBlock *BB = *BBI;\n \n \/\/ For large loops, avoid use-scanning by using dominance information: In\n \/\/ particular, if a block does not dominate any of the loop exits, then none\n \/\/ of the values defined in the block could be used outside the loop.\n if (!BlockDominatesAnExit(BB, ExitBlocks, DT))\n continue;\n \n for (BasicBlock::iterator I = BB->begin(), E = BB->end();\n I != E; ++I) {\n \/\/ Reject two common cases fast: instructions with no uses (like stores)\n \/\/ and instructions with one use that is in the same block as this.\n if (I->use_empty() ||\n (I->hasOneUse() && I->use_back()->getParent() == BB &&\n !isa<PHINode>(I->use_back())))\n continue;\n \n MadeChange |= ProcessInstruction(I, ExitBlocks);\n }\n }\n \n assert(L->isLCSSAForm(*DT));\n PredCache.clear();\n\n return MadeChange;\n}\n\n\/\/\/ isExitBlock - Return true if the specified block is in the list.\nstatic bool isExitBlock(BasicBlock *BB,\n const SmallVectorImpl<BasicBlock*> &ExitBlocks) {\n for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)\n if (ExitBlocks[i] == BB)\n return true;\n return false;\n}\n\n\/\/\/ ProcessInstruction - Given an instruction in the loop, check to see if it\n\/\/\/ has any uses that are outside the current loop. If so, insert LCSSA PHI\n\/\/\/ nodes and rewrite the uses.\nbool LCSSA::ProcessInstruction(Instruction *Inst,\n const SmallVectorImpl<BasicBlock*> &ExitBlocks) {\n SmallVector<Use*, 16> UsesToRewrite;\n \n BasicBlock *InstBB = Inst->getParent();\n \n for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();\n UI != E; ++UI) {\n User *U = *UI;\n BasicBlock *UserBB = cast<Instruction>(U)->getParent();\n if (PHINode *PN = dyn_cast<PHINode>(U))\n UserBB = PN->getIncomingBlock(UI);\n \n if (InstBB != UserBB && !inLoop(UserBB))\n UsesToRewrite.push_back(&UI.getUse());\n }\n\n \/\/ If there are no uses outside the loop, exit with no change.\n if (UsesToRewrite.empty()) return false;\n \n ++NumLCSSA; \/\/ We are applying the transformation\n\n \/\/ Invoke instructions are special in that their result value is not available\n \/\/ along their unwind edge. The code below tests to see whether DomBB dominates\n \/\/ the value, so adjust DomBB to the normal destination block, which is\n \/\/ effectively where the value is first usable.\n BasicBlock *DomBB = Inst->getParent();\n if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))\n DomBB = Inv->getNormalDest();\n\n DomTreeNode *DomNode = DT->getNode(DomBB);\n\n SmallVector<PHINode*, 16> AddedPHIs;\n\n SSAUpdater SSAUpdate;\n SSAUpdate.Initialize(Inst->getType(), Inst->getName());\n \n \/\/ Insert the LCSSA phi's into all of the exit blocks dominated by the\n \/\/ value, and add them to the Phi's map.\n for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),\n BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {\n BasicBlock *ExitBB = *BBI;\n if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;\n \n \/\/ If we already inserted something for this BB, don't reprocess it.\n if (SSAUpdate.HasValueForBlock(ExitBB)) continue;\n \n PHINode *PN = PHINode::Create(Inst->getType(),\n PredCache.GetNumPreds(ExitBB),\n Inst->getName()+\".lcssa\",\n ExitBB->begin());\n\n \/\/ Add inputs from inside the loop for this PHI.\n for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {\n PN->addIncoming(Inst, *PI);\n\n \/\/ If the exit block has a predecessor not within the loop, arrange for\n \/\/ the incoming value use corresponding to that predecessor to be\n \/\/ rewritten in terms of a different LCSSA PHI.\n if (!inLoop(*PI))\n UsesToRewrite.push_back(\n &PN->getOperandUse(\n PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));\n }\n\n AddedPHIs.push_back(PN);\n \n \/\/ Remember that this phi makes the value alive in this block.\n SSAUpdate.AddAvailableValue(ExitBB, PN);\n }\n \n \/\/ Rewrite all uses outside the loop in terms of the new PHIs we just\n \/\/ inserted.\n for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {\n \/\/ If this use is in an exit block, rewrite to use the newly inserted PHI.\n \/\/ This is required for correctness because SSAUpdate doesn't handle uses in\n \/\/ the same block. It assumes the PHI we inserted is at the end of the\n \/\/ block.\n Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());\n BasicBlock *UserBB = User->getParent();\n if (PHINode *PN = dyn_cast<PHINode>(User))\n UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);\n\n if (isa<PHINode>(UserBB->begin()) &&\n isExitBlock(UserBB, ExitBlocks)) {\n UsesToRewrite[i]->set(UserBB->begin());\n continue;\n }\n \n \/\/ Otherwise, do full PHI insertion.\n SSAUpdate.RewriteUse(*UsesToRewrite[i]);\n }\n\n \/\/ Remove PHI nodes that did not have any uses rewritten.\n for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {\n if (AddedPHIs[i]->use_empty())\n AddedPHIs[i]->eraseFromParent();\n }\n \n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: openCherry Platform\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) German Cancer Research Center, Division of Medical and\n Biological Informatics. All rights reserved.\n See MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\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 \"cherryDetachedWindow.h\"\n\n#include \"..\/cherryIWorkbenchPartConstants.h\"\n#include \"..\/cherryISaveablePart.h\"\n\n#include \"..\/cherryWorkbenchWindow.h\"\n\n#include \"..\/tweaklets\/cherryGuiWidgetsTweaklet.h\"\n\n#include \"cherryWorkbenchConstants.h\"\n#include \"cherryEditorManager.h\"\n#include \"cherryDragUtil.h\"\n\nnamespace cherry\n{\n\nDetachedWindow::ShellListener::ShellListener(DetachedWindow* wnd) :\n window(wnd)\n{\n\n}\n\nvoid DetachedWindow::ShellListener::ShellClosed(ShellEvent::Pointer e)\n{\n \/\/ only continue to close if the handleClose\n \/\/ wasn't canceled\n e->doit = window->HandleClose();\n}\n\nDetachedWindow::ShellControlListener::ShellControlListener(DetachedWindow* wnd) :\n window(wnd)\n{\n\n}\n\nGuiTk::IControlListener::Events::Types DetachedWindow::ShellControlListener::GetEventTypes() const\n{\n return Events::RESIZED;\n}\n\nvoid DetachedWindow::ShellControlListener::ControlResized(\n GuiTk::ControlEvent::Pointer e)\n{\n window->folder->SetBounds(\n Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(e->item));\n}\n\nDetachedWindow::DetachedWindow(WorkbenchPage::Pointer workbenchPage)\n{\n shellListener = new ShellListener(this);\n resizeListener = new ShellControlListener(this);\n\n this->page = workbenchPage;\n hideViewsOnClose = true;\n\n folder = new PartStack(page, false);\n}\n\nvoid DetachedWindow::PropertyChange(Object::Pointer \/*source*\/, int propId)\n{\n if (propId == IWorkbenchPartConstants::PROP_TITLE)\n {\n this->UpdateTitle();\n }\n else if (propId == PartStack::PROP_SELECTION)\n {\n this->ActivePartChanged(this->GetPartReference(folder->GetSelection()));\n }\n}\n\nShell::Pointer DetachedWindow::GetShell()\n{\n return windowShell;\n}\n\nvoid DetachedWindow::Create()\n{\n folder->AddListener(IPropertyChangeListener::Pointer(this));\n\n windowShell\n = page->GetWorkbenchWindow().Cast<WorkbenchWindow> () ->GetDetachedWindowPool()->AllocateShell(\n shellListener);\n windowShell->SetData(Object::Pointer(this));\n windowShell->SetText(\"\"); \/\/$NON-NLS-1$\n\n DragUtil::AddDragTarget(windowShell->GetControl(),\n IDragOverListener::Pointer(this));\n hideViewsOnClose = true;\n if (bounds.IsEmpty())\n {\n Rectangle windowRect = page->GetWorkbenchWindow()->GetShell()->GetBounds();\n Point center(windowRect.x + windowRect.width \/ 2, windowRect.y\n - windowRect.height \/ 2);\n bounds = Rectangle(center.x - 150, center.y + 100, 300, 200);\n }\n\n \/\/ Force the rect into the current display\n Rectangle dispBounds =\n Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetScreenSize();\n if (bounds.width > dispBounds.width)\n bounds.width = dispBounds.width;\n if (bounds.height > dispBounds.height)\n bounds.height = dispBounds.height;\n if (bounds.x + bounds.width > dispBounds.width)\n bounds.x = dispBounds.width - bounds.width;\n if (bounds.y + bounds.height > dispBounds.height)\n bounds.y = dispBounds.height - bounds.height;\n\n this->GetShell()->SetBounds(bounds);\n\n this->ConfigureShell(windowShell);\n\n this->CreateContents(windowShell->GetControl());\n \/\/windowShell->Layout(true);\n \/\/folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(windowShell->GetControl()));\n}\n\nvoid DetachedWindow::Add(StackablePart::Pointer part)\n{\n\n Shell::Pointer shell = this->GetShell();\n if (shell != 0)\n {\n part->Reparent(shell->GetControl());\n }\n folder->Add(part);\n this->UpdateMinimumSize();\n}\n\nbool DetachedWindow::BelongsToWorkbenchPage(\n IWorkbenchPage::Pointer workbenchPage)\n{\n return (this->page == workbenchPage);\n}\n\nbool DetachedWindow::Close()\n{\n hideViewsOnClose = false;\n Shell::Pointer shell = this->GetShell();\n if (shell != 0)\n {\n shell->Close();\n }\n return true;\n}\n\nIDropTarget::Pointer DetachedWindow::Drag(void* \/*currentControl*\/,\n Object::Pointer draggedObject, const Point& position, const Rectangle& \/*dragRectangle*\/)\n{\n\n if (draggedObject.Cast<PartPane> () == 0)\n {\n return IDropTarget::Pointer(0);\n }\n\n PartPane::Pointer sourcePart = draggedObject.Cast<PartPane> ();\n\n if (sourcePart->GetWorkbenchWindow() != page->GetWorkbenchWindow())\n {\n return IDropTarget::Pointer(0);\n }\n\n \/\/ Only handle the event if the source part is acceptable to the particular PartStack\n IDropTarget::Pointer target;\n if (folder->AllowsDrop(sourcePart))\n {\n target = folder->GetDropTarget(draggedObject, position);\n\n if (target == 0)\n {\n Rectangle displayBounds =\n DragUtil::GetDisplayBounds(folder->GetControl());\n if (displayBounds.Contains(position))\n {\n StackDropResult::Pointer stackDropResult(new StackDropResult(\n displayBounds, Object::Pointer(0)));\n target = folder->CreateDropTarget(sourcePart, stackDropResult);\n }\n else\n {\n return IDropTarget::Pointer(0);\n }\n }\n }\n\n return target;\n}\n\nIStackableContainer::ChildrenType DetachedWindow::GetChildren() const\n{\n return folder->GetChildren();\n}\n\nWorkbenchPage::Pointer DetachedWindow::GetWorkbenchPage()\n{\n return this->page;\n}\n\nvoid DetachedWindow::RestoreState(IMemento::Pointer memento)\n{\n \/\/ Read the bounds.\n int x = 0;\n memento->GetInteger(WorkbenchConstants::TAG_X, x);\n int y = 0;\n memento->GetInteger(WorkbenchConstants::TAG_Y, y);\n int width = 0;\n memento->GetInteger(WorkbenchConstants::TAG_WIDTH, width);\n int height = 0;\n memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, height);\n\n \/\/ memento->GetInteger(WorkbenchConstants::TAG_FLOAT);\n\n \/\/ Set the bounds.\n bounds = Rectangle(x, y, width, height);\n if (GetShell())\n {\n GetShell()->SetBounds(bounds);\n }\n\n \/\/ Create the folder.\n IMemento::Pointer childMem =\n memento->GetChild(WorkbenchConstants::TAG_FOLDER);\n if (childMem)\n {\n folder->RestoreState(childMem);\n }\n}\n\nvoid DetachedWindow::SaveState(IMemento::Pointer memento)\n{\n if (GetShell())\n {\n bounds = GetShell()->GetBounds();\n }\n\n \/\/ Save the bounds.\n memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x);\n memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y);\n memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width);\n memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height);\n\n \/\/ Save the views.\n IMemento::Pointer childMem = memento->CreateChild(\n WorkbenchConstants::TAG_FOLDER);\n folder->SaveState(childMem);\n}\n\nvoid* DetachedWindow::GetControl()\n{\n return folder->GetControl();\n}\n\nint DetachedWindow::Open()\n{\n\n if (this->GetShell() == 0)\n {\n this->Create();\n }\n\n Rectangle bounds = this->GetShell()->GetBounds();\n\n if (!(bounds == this->GetShell()->GetBounds()))\n {\n this->GetShell()->SetBounds(bounds);\n }\n\n this->GetShell()->SetVisible(true);\n\n folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(this->GetShell()->GetControl()));\n\n return 0;\n}\n\nvoid DetachedWindow::ActivePartChanged(\n IWorkbenchPartReference::Pointer partReference)\n{\n if (activePart == partReference)\n {\n return;\n }\n\n if (activePart != 0)\n {\n activePart->RemovePropertyListener(IPropertyChangeListener::Pointer(this));\n }\n activePart = partReference;\n if (partReference != 0)\n {\n partReference->AddPropertyListener(IPropertyChangeListener::Pointer(this));\n }\n this->UpdateTitle();\n}\n\nvoid DetachedWindow::ConfigureShell(Shell::Pointer shell)\n{\n this->UpdateTitle();\n\n Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(\n shell->GetControl(), resizeListener);\n \/\/shell.addListener(SWT.Activate, activationListener);\n \/\/shell.addListener(SWT.Deactivate, activationListener);\n\n \/\/TODO DetachedWindow key bindings\n \/\/ \/\/ Register this detached view as a window (for key bindings).\n \/\/ IContextService contextService = (IContextService) getWorkbenchPage()\n \/\/ .getWorkbenchWindow().getWorkbench().getService(IContextService.class);\n \/\/ contextService.registerShell(shell, IContextService.TYPE_WINDOW);\n \/\/\n \/\/ page.getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp(shell,\n \/\/ IWorkbenchHelpContextIds.DETACHED_WINDOW);\n}\n\nvoid* DetachedWindow::CreateContents(void* parent)\n{\n \/\/ Create the tab folder.\n folder->CreateControl(parent);\n\n \/\/ Reparent each view in the tab folder.\n std::list<PartPane::Pointer> detachedChildren;\n this->CollectViewPanes(detachedChildren, this->GetChildren());\n for (std::list<PartPane::Pointer>::iterator itr = detachedChildren.begin(); itr\n != detachedChildren.end(); ++itr)\n {\n PartPane::Pointer part = *itr;\n part->Reparent(parent);\n }\n\n \/\/TODO DetachedWindow listen to folder events (update size?)\n \/\/ if (folder->GetPresentation()\n \/\/ instanceof TabbedStackPresentation)\n \/\/ {\n \/\/ TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation();\n \/\/ AbstractTabFolder tabFolder = stack.getTabFolder();\n \/\/ tabFolder.addListener(new TabFolderListener()\n \/\/ {\n \/\/ public void handleEvent(TabFolderEvent e)\n \/\/ {\n \/\/ switch (e.type)\n \/\/ {\n \/\/ case TabFolderEvent.EVENT_CLOSE:\n \/\/ {\n \/\/ updateMinimumSize();\n \/\/ break;\n \/\/ }\n \/\/ case TabFolderEvent.EVENT_PREFERRED_SIZE:\n \/\/ {\n \/\/ updateMinimumSize();\n \/\/ break;\n \/\/ }\n \/\/ }\n \/\/ }\n \/\/ });\n \/\/ }\n\n \/\/ Return tab folder control.\n return folder->GetControl();\n}\n\nvoid DetachedWindow::UpdateTitle()\n{\n if (activePart != 0)\n {\n \/\/ Uncomment to set the shell title to match the title of the active part\n \/\/ String text = activePart.getTitle();\n \/\/\n \/\/ if (!text.equals(s.getText())) {\n \/\/ s.setText(text);\n \/\/ }\n }\n}\n\nvoid DetachedWindow::UpdateMinimumSize()\n{\n \/\/ \/\/ We can only do this for 'Tabbed' stacked presentations.\n \/\/ if (folder.getPresentation().Cast<TabbedStackPresentation>() != 0)\n \/\/ {\n \/\/ TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation();\n \/\/\n \/\/ if (stack->GetPartList().size() == 1)\n \/\/ {\n \/\/ \/\/ Get the minimum space required for the part\n \/\/ int width = stack->ComputePreferredSize(true, Constants::INF, Constants::INF, 0);\n \/\/ int height = stack->ComputePreferredSize(false, Constants::INF, Constants::INF, 0);\n \/\/\n \/\/ \/\/ Take the current shell 'trim' into account\n \/\/ int shellHeight = windowShell->GetBounds().height - windowShell->GetClientArea().height;\n \/\/ int shellWidth = windowShell->GetBounds().width - windowShell->GetClientArea().width;\n \/\/\n \/\/ windowShell->SetMinimumSize(width + shellWidth, height + shellHeight);\n \/\/ }\n \/\/ }\n}\n\nIWorkbenchPartReference::Pointer DetachedWindow::GetPartReference(\n StackablePart::Pointer pane)\n{\n\n if (pane == 0 || pane.Cast<PartPane> () == 0)\n {\n return IWorkbenchPartReference::Pointer(0);\n }\n\n return pane.Cast<PartPane> ()->GetPartReference();\n}\n\nbool DetachedWindow::HandleClose()\n{\n\n if (hideViewsOnClose)\n {\n std::list<PartPane::Pointer> views;\n this->CollectViewPanes(views, this->GetChildren());\n\n \/\/ Save any drty views\n if (!this->HandleSaves(views))\n {\n return false; \/\/ User canceled the save\n }\n\n \/\/ OK, go on with the closing\n for (std::list<PartPane::Pointer>::iterator itr = views.begin(); itr\n != views.end(); ++itr)\n {\n PartPane::Pointer child = *itr;\n\n \/\/ Only close if closable...\n if (child->IsCloseable())\n {\n page->HideView(child->GetPartReference().Cast<IViewReference> ());\n\n \/\/ Was the close cancelled?\n if (child->GetContainer() != 0)\n return false;\n }\n else\n {\n page->AttachView(child->GetPartReference().Cast<IViewReference> ());\n }\n }\n }\n\n if (folder != 0)\n {\n folder->Dispose();\n }\n\n if (windowShell != 0)\n {\n Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(\n windowShell->GetControl(), resizeListener);\n \/\/ windowShell.removeListener(SWT.Activate, activationListener);\n \/\/ windowShell.removeListener(SWT.Deactivate, activationListener);\n\n DragUtil::RemoveDragTarget(windowShell->GetControl(),\n IDragOverListener::Pointer(this));\n bounds = windowShell->GetBounds();\n\n \/\/TODO DetachedWindow unregister key bindings\n \/\/ \/\/ Unregister this detached view as a window (for key bindings).\n \/\/ final IContextService contextService = (IContextService) getWorkbenchPage().getWorkbenchWindow().getWorkbench().getService(IContextService.class);\n \/\/ contextService.unregisterShell(windowShell);\n\n windowShell->SetData(Object::Pointer(0));\n windowShell = 0;\n }\n\n return true;\n}\n\nbool DetachedWindow::HandleSaves(std::list<PartPane::Pointer> views)\n{\n std::vector<IWorkbenchPart::Pointer> dirtyViews;\n for (std::list<PartPane::Pointer>::iterator iterator = views.begin(); iterator\n != views.end(); ++iterator)\n {\n PartPane::Pointer pane = *iterator;\n IViewReference::Pointer ref =\n pane->GetPartReference().Cast<IViewReference> ();\n IViewPart::Pointer part = ref->GetView(false);\n if (part.Cast<ISaveablePart> () != 0)\n {\n ISaveablePart::Pointer saveable = part.Cast<ISaveablePart> ();\n if (saveable->IsDirty() && saveable->IsSaveOnCloseNeeded())\n {\n dirtyViews.push_back(part);\n }\n }\n }\n\n \/\/ If there are any prompt to save -before- any closing happens\n \/\/ FIXME: This code will result in a double prompt if the user\n \/\/ decides not to save a particular view at this stage they'll\n \/\/ get a second one from the 'hideView' call...\n if (dirtyViews.size() > 0)\n {\n IWorkbenchWindow::Pointer window = page->GetWorkbenchWindow();\n bool success =\n EditorManager::SaveAll(dirtyViews, true, true, false, window);\n if (!success)\n {\n return false; \/\/ the user canceled.\n }\n }\n\n return true;\n}\n\nvoid DetachedWindow::CollectViewPanes(std::list<PartPane::Pointer>& result,\n const std::list<StackablePart::Pointer>& parts)\n{\n for (std::list<StackablePart::Pointer>::const_iterator iter = parts.begin(); iter\n != parts.end(); ++iter)\n {\n StackablePart::Pointer part = *iter;\n if (part.Cast<PartPane> () != 0)\n {\n result.push_back(part.Cast<PartPane> ());\n }\n }\n}\n\n}\n<commit_msg>FIX (#2031): added a temporary smartpointer which holds the detachted window alive as long as necessary<commit_after>\/*=========================================================================\n\n Program: openCherry Platform\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) German Cancer Research Center, Division of Medical and\n Biological Informatics. All rights reserved.\n See MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\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 \"cherryDetachedWindow.h\"\n\n#include \"..\/cherryIWorkbenchPartConstants.h\"\n#include \"..\/cherryISaveablePart.h\"\n\n#include \"..\/cherryWorkbenchWindow.h\"\n\n#include \"..\/tweaklets\/cherryGuiWidgetsTweaklet.h\"\n\n#include \"cherryWorkbenchConstants.h\"\n#include \"cherryEditorManager.h\"\n#include \"cherryDragUtil.h\"\n\nnamespace cherry\n{\n\nDetachedWindow::ShellListener::ShellListener(DetachedWindow* wnd) :\n window(wnd)\n{\n\n}\n\nvoid DetachedWindow::ShellListener::ShellClosed(ShellEvent::Pointer e)\n{\n \/\/ hold on to a reference of the DetachedWindow instance\n \/\/ (otherwise, wnd->HandleClose() woulde delete the DetachedWindow\n \/\/ instance too early, trying to write to members afterwards)\n DetachedWindow::Pointer wnd(window);\n\n \/\/ only continue to close if the handleClose\n \/\/ wasn't canceled\n e->doit = wnd->HandleClose();\n}\n\nDetachedWindow::ShellControlListener::ShellControlListener(DetachedWindow* wnd) :\n window(wnd)\n{\n\n}\n\nGuiTk::IControlListener::Events::Types DetachedWindow::ShellControlListener::GetEventTypes() const\n{\n return Events::RESIZED;\n}\n\nvoid DetachedWindow::ShellControlListener::ControlResized(\n GuiTk::ControlEvent::Pointer e)\n{\n window->folder->SetBounds(\n Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(e->item));\n}\n\nDetachedWindow::DetachedWindow(WorkbenchPage::Pointer workbenchPage)\n{\n shellListener = new ShellListener(this);\n resizeListener = new ShellControlListener(this);\n\n this->page = workbenchPage;\n hideViewsOnClose = true;\n\n folder = new PartStack(page, false);\n}\n\nvoid DetachedWindow::PropertyChange(Object::Pointer \/*source*\/, int propId)\n{\n if (propId == IWorkbenchPartConstants::PROP_TITLE)\n {\n this->UpdateTitle();\n }\n else if (propId == PartStack::PROP_SELECTION)\n {\n this->ActivePartChanged(this->GetPartReference(folder->GetSelection()));\n }\n}\n\nShell::Pointer DetachedWindow::GetShell()\n{\n return windowShell;\n}\n\nvoid DetachedWindow::Create()\n{\n folder->AddListener(IPropertyChangeListener::Pointer(this));\n\n windowShell\n = page->GetWorkbenchWindow().Cast<WorkbenchWindow> () ->GetDetachedWindowPool()->AllocateShell(\n shellListener);\n windowShell->SetData(Object::Pointer(this));\n windowShell->SetText(\"\"); \/\/$NON-NLS-1$\n\n DragUtil::AddDragTarget(windowShell->GetControl(),\n IDragOverListener::Pointer(this));\n hideViewsOnClose = true;\n if (bounds.IsEmpty())\n {\n Rectangle windowRect = page->GetWorkbenchWindow()->GetShell()->GetBounds();\n Point center(windowRect.x + windowRect.width \/ 2, windowRect.y\n - windowRect.height \/ 2);\n bounds = Rectangle(center.x - 150, center.y + 100, 300, 200);\n }\n\n \/\/ Force the rect into the current display\n Rectangle dispBounds =\n Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetScreenSize();\n if (bounds.width > dispBounds.width)\n bounds.width = dispBounds.width;\n if (bounds.height > dispBounds.height)\n bounds.height = dispBounds.height;\n if (bounds.x + bounds.width > dispBounds.width)\n bounds.x = dispBounds.width - bounds.width;\n if (bounds.y + bounds.height > dispBounds.height)\n bounds.y = dispBounds.height - bounds.height;\n\n this->GetShell()->SetBounds(bounds);\n\n this->ConfigureShell(windowShell);\n\n this->CreateContents(windowShell->GetControl());\n \/\/windowShell->Layout(true);\n \/\/folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(windowShell->GetControl()));\n}\n\nvoid DetachedWindow::Add(StackablePart::Pointer part)\n{\n\n Shell::Pointer shell = this->GetShell();\n if (shell != 0)\n {\n part->Reparent(shell->GetControl());\n }\n folder->Add(part);\n this->UpdateMinimumSize();\n}\n\nbool DetachedWindow::BelongsToWorkbenchPage(\n IWorkbenchPage::Pointer workbenchPage)\n{\n return (this->page == workbenchPage);\n}\n\nbool DetachedWindow::Close()\n{\n hideViewsOnClose = false;\n Shell::Pointer shell = this->GetShell();\n if (shell != 0)\n {\n shell->Close();\n }\n return true;\n}\n\nIDropTarget::Pointer DetachedWindow::Drag(void* \/*currentControl*\/,\n Object::Pointer draggedObject, const Point& position, const Rectangle& \/*dragRectangle*\/)\n{\n\n if (draggedObject.Cast<PartPane> () == 0)\n {\n return IDropTarget::Pointer(0);\n }\n\n PartPane::Pointer sourcePart = draggedObject.Cast<PartPane> ();\n\n if (sourcePart->GetWorkbenchWindow() != page->GetWorkbenchWindow())\n {\n return IDropTarget::Pointer(0);\n }\n\n \/\/ Only handle the event if the source part is acceptable to the particular PartStack\n IDropTarget::Pointer target;\n if (folder->AllowsDrop(sourcePart))\n {\n target = folder->GetDropTarget(draggedObject, position);\n\n if (target == 0)\n {\n Rectangle displayBounds =\n DragUtil::GetDisplayBounds(folder->GetControl());\n if (displayBounds.Contains(position))\n {\n StackDropResult::Pointer stackDropResult(new StackDropResult(\n displayBounds, Object::Pointer(0)));\n target = folder->CreateDropTarget(sourcePart, stackDropResult);\n }\n else\n {\n return IDropTarget::Pointer(0);\n }\n }\n }\n\n return target;\n}\n\nIStackableContainer::ChildrenType DetachedWindow::GetChildren() const\n{\n return folder->GetChildren();\n}\n\nWorkbenchPage::Pointer DetachedWindow::GetWorkbenchPage()\n{\n return this->page;\n}\n\nvoid DetachedWindow::RestoreState(IMemento::Pointer memento)\n{\n \/\/ Read the bounds.\n int x = 0;\n memento->GetInteger(WorkbenchConstants::TAG_X, x);\n int y = 0;\n memento->GetInteger(WorkbenchConstants::TAG_Y, y);\n int width = 0;\n memento->GetInteger(WorkbenchConstants::TAG_WIDTH, width);\n int height = 0;\n memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, height);\n\n \/\/ memento->GetInteger(WorkbenchConstants::TAG_FLOAT);\n\n \/\/ Set the bounds.\n bounds = Rectangle(x, y, width, height);\n if (GetShell())\n {\n GetShell()->SetBounds(bounds);\n }\n\n \/\/ Create the folder.\n IMemento::Pointer childMem =\n memento->GetChild(WorkbenchConstants::TAG_FOLDER);\n if (childMem)\n {\n folder->RestoreState(childMem);\n }\n}\n\nvoid DetachedWindow::SaveState(IMemento::Pointer memento)\n{\n if (GetShell())\n {\n bounds = GetShell()->GetBounds();\n }\n\n \/\/ Save the bounds.\n memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x);\n memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y);\n memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width);\n memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height);\n\n \/\/ Save the views.\n IMemento::Pointer childMem = memento->CreateChild(\n WorkbenchConstants::TAG_FOLDER);\n folder->SaveState(childMem);\n}\n\nvoid* DetachedWindow::GetControl()\n{\n return folder->GetControl();\n}\n\nint DetachedWindow::Open()\n{\n\n if (this->GetShell() == 0)\n {\n this->Create();\n }\n\n Rectangle bounds = this->GetShell()->GetBounds();\n\n if (!(bounds == this->GetShell()->GetBounds()))\n {\n this->GetShell()->SetBounds(bounds);\n }\n\n this->GetShell()->SetVisible(true);\n\n folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(this->GetShell()->GetControl()));\n\n return 0;\n}\n\nvoid DetachedWindow::ActivePartChanged(\n IWorkbenchPartReference::Pointer partReference)\n{\n if (activePart == partReference)\n {\n return;\n }\n\n if (activePart != 0)\n {\n activePart->RemovePropertyListener(IPropertyChangeListener::Pointer(this));\n }\n activePart = partReference;\n if (partReference != 0)\n {\n partReference->AddPropertyListener(IPropertyChangeListener::Pointer(this));\n }\n this->UpdateTitle();\n}\n\nvoid DetachedWindow::ConfigureShell(Shell::Pointer shell)\n{\n this->UpdateTitle();\n\n Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(\n shell->GetControl(), resizeListener);\n \/\/shell.addListener(SWT.Activate, activationListener);\n \/\/shell.addListener(SWT.Deactivate, activationListener);\n\n \/\/TODO DetachedWindow key bindings\n \/\/ \/\/ Register this detached view as a window (for key bindings).\n \/\/ IContextService contextService = (IContextService) getWorkbenchPage()\n \/\/ .getWorkbenchWindow().getWorkbench().getService(IContextService.class);\n \/\/ contextService.registerShell(shell, IContextService.TYPE_WINDOW);\n \/\/\n \/\/ page.getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp(shell,\n \/\/ IWorkbenchHelpContextIds.DETACHED_WINDOW);\n}\n\nvoid* DetachedWindow::CreateContents(void* parent)\n{\n \/\/ Create the tab folder.\n folder->CreateControl(parent);\n\n \/\/ Reparent each view in the tab folder.\n std::list<PartPane::Pointer> detachedChildren;\n this->CollectViewPanes(detachedChildren, this->GetChildren());\n for (std::list<PartPane::Pointer>::iterator itr = detachedChildren.begin(); itr\n != detachedChildren.end(); ++itr)\n {\n PartPane::Pointer part = *itr;\n part->Reparent(parent);\n }\n\n \/\/TODO DetachedWindow listen to folder events (update size?)\n \/\/ if (folder->GetPresentation()\n \/\/ instanceof TabbedStackPresentation)\n \/\/ {\n \/\/ TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation();\n \/\/ AbstractTabFolder tabFolder = stack.getTabFolder();\n \/\/ tabFolder.addListener(new TabFolderListener()\n \/\/ {\n \/\/ public void handleEvent(TabFolderEvent e)\n \/\/ {\n \/\/ switch (e.type)\n \/\/ {\n \/\/ case TabFolderEvent.EVENT_CLOSE:\n \/\/ {\n \/\/ updateMinimumSize();\n \/\/ break;\n \/\/ }\n \/\/ case TabFolderEvent.EVENT_PREFERRED_SIZE:\n \/\/ {\n \/\/ updateMinimumSize();\n \/\/ break;\n \/\/ }\n \/\/ }\n \/\/ }\n \/\/ });\n \/\/ }\n\n \/\/ Return tab folder control.\n return folder->GetControl();\n}\n\nvoid DetachedWindow::UpdateTitle()\n{\n if (activePart != 0)\n {\n \/\/ Uncomment to set the shell title to match the title of the active part\n \/\/ String text = activePart.getTitle();\n \/\/\n \/\/ if (!text.equals(s.getText())) {\n \/\/ s.setText(text);\n \/\/ }\n }\n}\n\nvoid DetachedWindow::UpdateMinimumSize()\n{\n \/\/ \/\/ We can only do this for 'Tabbed' stacked presentations.\n \/\/ if (folder.getPresentation().Cast<TabbedStackPresentation>() != 0)\n \/\/ {\n \/\/ TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation();\n \/\/\n \/\/ if (stack->GetPartList().size() == 1)\n \/\/ {\n \/\/ \/\/ Get the minimum space required for the part\n \/\/ int width = stack->ComputePreferredSize(true, Constants::INF, Constants::INF, 0);\n \/\/ int height = stack->ComputePreferredSize(false, Constants::INF, Constants::INF, 0);\n \/\/\n \/\/ \/\/ Take the current shell 'trim' into account\n \/\/ int shellHeight = windowShell->GetBounds().height - windowShell->GetClientArea().height;\n \/\/ int shellWidth = windowShell->GetBounds().width - windowShell->GetClientArea().width;\n \/\/\n \/\/ windowShell->SetMinimumSize(width + shellWidth, height + shellHeight);\n \/\/ }\n \/\/ }\n}\n\nIWorkbenchPartReference::Pointer DetachedWindow::GetPartReference(\n StackablePart::Pointer pane)\n{\n\n if (pane == 0 || pane.Cast<PartPane> () == 0)\n {\n return IWorkbenchPartReference::Pointer(0);\n }\n\n return pane.Cast<PartPane> ()->GetPartReference();\n}\n\nbool DetachedWindow::HandleClose()\n{\n\n if (hideViewsOnClose)\n {\n std::list<PartPane::Pointer> views;\n this->CollectViewPanes(views, this->GetChildren());\n\n \/\/ Save any dirty views\n if (!this->HandleSaves(views))\n {\n return false; \/\/ User canceled the save\n }\n\n \/\/ OK, go on with the closing\n for (std::list<PartPane::Pointer>::iterator itr = views.begin(); itr\n != views.end(); ++itr)\n {\n PartPane::Pointer child = *itr;\n\n \/\/ Only close if closable...\n if (child->IsCloseable())\n {\n page->HideView(child->GetPartReference().Cast<IViewReference> ());\n\n \/\/ Was the close cancelled?\n if (child->GetContainer() != 0)\n return false;\n }\n else\n {\n page->AttachView(child->GetPartReference().Cast<IViewReference> ());\n }\n }\n }\n\n if (folder != 0)\n {\n folder->Dispose();\n }\n\n if (windowShell != 0)\n {\n Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(\n windowShell->GetControl(), resizeListener);\n \/\/ windowShell.removeListener(SWT.Activate, activationListener);\n \/\/ windowShell.removeListener(SWT.Deactivate, activationListener);\n\n DragUtil::RemoveDragTarget(windowShell->GetControl(),\n IDragOverListener::Pointer(this));\n bounds = windowShell->GetBounds();\n\n \/\/TODO DetachedWindow unregister key bindings\n \/\/ \/\/ Unregister this detached view as a window (for key bindings).\n \/\/ final IContextService contextService = (IContextService) getWorkbenchPage().getWorkbenchWindow().getWorkbench().getService(IContextService.class);\n \/\/ contextService.unregisterShell(windowShell);\n\n windowShell->SetData(Object::Pointer(0));\n windowShell = 0;\n }\n\n return true;\n}\n\nbool DetachedWindow::HandleSaves(std::list<PartPane::Pointer> views)\n{\n std::vector<IWorkbenchPart::Pointer> dirtyViews;\n for (std::list<PartPane::Pointer>::iterator iterator = views.begin(); iterator\n != views.end(); ++iterator)\n {\n PartPane::Pointer pane = *iterator;\n IViewReference::Pointer ref =\n pane->GetPartReference().Cast<IViewReference> ();\n IViewPart::Pointer part = ref->GetView(false);\n if (part.Cast<ISaveablePart> () != 0)\n {\n ISaveablePart::Pointer saveable = part.Cast<ISaveablePart> ();\n if (saveable->IsDirty() && saveable->IsSaveOnCloseNeeded())\n {\n dirtyViews.push_back(part);\n }\n }\n }\n\n \/\/ If there are any prompt to save -before- any closing happens\n \/\/ FIXME: This code will result in a double prompt if the user\n \/\/ decides not to save a particular view at this stage they'll\n \/\/ get a second one from the 'hideView' call...\n if (dirtyViews.size() > 0)\n {\n IWorkbenchWindow::Pointer window = page->GetWorkbenchWindow();\n bool success =\n EditorManager::SaveAll(dirtyViews, true, true, false, window);\n if (!success)\n {\n return false; \/\/ the user canceled.\n }\n }\n\n return true;\n}\n\nvoid DetachedWindow::CollectViewPanes(std::list<PartPane::Pointer>& result,\n const std::list<StackablePart::Pointer>& parts)\n{\n for (std::list<StackablePart::Pointer>::const_iterator iter = parts.begin(); iter\n != parts.end(); ++iter)\n {\n StackablePart::Pointer part = *iter;\n if (part.Cast<PartPane> () != 0)\n {\n result.push_back(part.Cast<PartPane> ());\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2005-2008 by the FIFE team *\n * http:\/\/www.fifengine.de *\n * This file is part of FIFE. *\n * *\n * FIFE 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 *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***************************************************************************\/\n\n\/\/ Standard C++ library includes\n#include <iostream>\n\n\/\/ 3rd party library includes\n#include <SDL.h>\n#include <SDL_ttf.h>\n\n\/\/ FIFE includes\n\/\/ These includes are split up in two parts, separated by one empty line\n\/\/ First block: files included from the FIFE root src directory\n\/\/ Second block: files included from the same folder\n#include \"util\/base\/exception.h\"\n#include \"util\/log\/logger.h\"\n#include \"util\/time\/timemanager.h\"\n#include \"audio\/soundmanager.h\"\n#include \"gui\/console\/console.h\"\n#include \"gui\/guimanager.h\"\n#include \"vfs\/vfs.h\"\n#include \"vfs\/vfsdirectory.h\"\n#include \"vfs\/directoryprovider.h\"\n#ifdef HAVE_ZIP\n#include \"vfs\/zip\/zipprovider.h\"\n#endif\n#include \"eventchannel\/eventmanager.h\"\n#include \"video\/imagepool.h\"\n#include \"video\/animationpool.h\"\n#include \"audio\/soundclippool.h\"\n#include \"video\/renderbackend.h\"\n#include \"video\/cursor.h\"\n#ifdef HAVE_OPENGL\n#include \"video\/opengl\/renderbackendopengl.h\"\n#include \"gui\/base\/opengl\/opengl_gui_graphics.h\"\n#endif\n#include \"gui\/base\/sdl\/sdl_gui_graphics.h\"\n#include \"gui\/base\/gui_font.h\"\n#include \"video\/sdl\/renderbackendsdl.h\"\n#include \"video\/fonts\/abstractfont.h\"\n#include \"loaders\/native\/video_loaders\/subimage_loader.h\"\n#include \"loaders\/native\/video_loaders\/image_loader.h\"\n#include \"loaders\/native\/audio_loaders\/ogg_loader.h\"\n#include \"model\/model.h\"\n#include \"pathfinder\/linearpather\/linearpather.h\"\n#include \"pathfinder\/routepather\/routepather.h\"\n#include \"model\/metamodel\/grids\/hexgrid.h\"\n#include \"model\/metamodel\/grids\/squaregrid.h\"\n#include \"view\/view.h\"\n#include \"view\/renderers\/camerazonerenderer.h\"\n#include \"view\/renderers\/quadtreerenderer.h\"\n#include \"view\/renderers\/gridrenderer.h\"\n#include \"view\/renderers\/instancerenderer.h\"\n#include \"view\/renderers\/coordinaterenderer.h\"\n#include \"view\/renderers\/floatingtextrenderer.h\"\n#include \"view\/renderers\/cellselectionrenderer.h\"\n#include \"view\/renderers\/blockinginforenderer.h\"\n#include \"view\/renderers\/genericrenderer.h\"\n#include \"engine.h\"\n\n#ifdef USE_COCOA\n#include <dlfcn.h>\n\nint main(int argc, char **argv)\n{\n return 0;\n}\n#endif\n\nnamespace FIFE {\n\tstatic Logger _log(LM_CONTROLLER);\n\n\tEngine::Engine():\n\t\tm_renderbackend(0),\n\t\tm_guimanager(0),\n\t\tm_eventmanager(0),\n\t\tm_soundmanager(0),\n\t\tm_timemanager(0),\n\t\tm_imagepool(0),\n\t\tm_animpool(0),\n\t\tm_soundclippool(0),\n\t\tm_vfs(0),\n\t\tm_model(0),\n\t\tm_gui_graphics(0),\n\t\tm_view(0),\n\t\tm_logmanager(0),\n\t\tm_cursor(0),\n\t\tm_settings() {\n#ifdef USE_COCOA\n\t\t\/\/ The next lines ensure that Cocoa is initialzed correctly.\n\t\t\/\/ This is needed for SDL to function properly on MAC OS X.\n\t\tvoid* cocoa_lib;\n\t\tcocoa_lib = dlopen( \"\/System\/Library\/Frameworks\/Cocoa.framework\/Cocoa\", RTLD_LAZY );\n\t\tvoid (*nsappload)(void);\n\t\tnsappload = (void(*)()) dlsym( cocoa_lib, \"NSApplicationLoad\");\n\t\tnsappload();\n#endif\n\t\tpreInit();\n\t}\n\n\tEngineSettings& Engine::getSettings() {\n\t\treturn m_settings;\n\t}\n\n\tvoid Engine::preInit() {\n\t\tm_logmanager = LogManager::instance();\n\n\t\tFL_LOG(_log, \"================== Engine pre-init start =================\");\n\t\tm_timemanager = new TimeManager();\n\t\tFL_LOG(_log, \"Time manager created\");\n\n\t\tFL_LOG(_log, \"Creating VFS\");\n\t\tm_vfs = new VFS();\n\n\t\tFL_LOG(_log, \"Adding root directory to VFS\");\n\t\tm_vfs->addSource( new VFSDirectory(m_vfs) );\n\t\tm_vfs->addProvider( new DirectoryProvider() );\n#ifdef HAVE_ZIP\n\t\tFL_LOG(_log, \"Adding zip provider to VFS\");\n\t\tm_vfs->addProvider( new ZipProvider() );\n#endif\n\t\t\/\/m_vfs->addProvider(ProviderDAT2());\n\t\t\/\/m_vfs->addProvider(ProviderDAT1());\n\t\tFL_LOG(_log, \"Engine pre-init done\");\n\t}\n\n\tvoid Engine::init() {\n\t\tFL_LOG(_log, \"Engine initialize start\");\n\t\tm_settings.validate();\n\t\tFL_LOG(_log, \"Engine settings validated\");\n\n\t\t\/\/ If failed to init SDL throw exception.\n\t\tif (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER) < 0) {\n\t\t\tthrow SDLException(SDL_GetError());\n\t\t}\n\n\t\tSDL_EnableUNICODE(1);\n\t\tSDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);\n\t\tTTF_Init();\n\n\t\tFL_LOG(_log, \"Creating event manager\");\n\t\tm_eventmanager = new EventManager();\n\n\t\tFL_LOG(_log, \"Creating pools\");\n\t\tm_imagepool = new ImagePool();\n\t\tm_animpool = new AnimationPool();\n\t\tm_soundclippool = new SoundClipPool();\n\t\tm_imagepool->addResourceLoader(new SubImageLoader());\n\t\tm_imagepool->addResourceLoader(new ImageLoader(m_vfs));\n\t\tm_soundclippool->addResourceLoader(new OggLoader(m_vfs));\n\n\t\tFL_LOG(_log, \"Creating render backend\");\n\t\tstd::string rbackend(m_settings.getRenderBackend());\n\t\tif (rbackend == \"SDL\") {\n\t\t\tm_renderbackend = new RenderBackendSDL();\n\t\t\tFL_LOG(_log, \"SDL Render backend created\");\n\t\t} else {\n#ifdef HAVE_OPENGL\n\t\t\tm_renderbackend = new RenderBackendOpenGL();\n\t\t\tFL_LOG(_log, \"OpenGL Render backend created\");\n#else\n\t\t\tm_renderbackend = new RenderBackendSDL();\n\t\t\t\/\/ Remember the choice so we pick the right graphics class.\n\t\t\trbackend = \"SDL\";\n\t\t\tFL_WARN(_log, \"Tried to select OpenGL, even though it is not compiled into the engine. Falling back to SDL Render backend\");\n#endif\n\t\t}\n\t\tFL_LOG(_log, \"Initializing render backend\");\n\t\tm_renderbackend->setChunkingSize(m_settings.getImageChunkingSize());\n\t\tm_renderbackend->init();\n\n\t\tFL_LOG(_log, \"Creating main screen\");\n\t\tm_renderbackend->createMainScreen(\n\t\t\tm_settings.getScreenWidth(),\n\t\t\tm_settings.getScreenHeight(),\n\t\t\tstatic_cast<unsigned char>(m_settings.getBitsPerPixel()),\n\t\t\tm_settings.isFullScreen(),\n\t\t\tm_settings.getWindowTitle(),\n\t\t\tm_settings.getWindowIcon());\n\t\tFL_LOG(_log, \"Main screen created\");\n\n#ifdef HAVE_OPENGL\n\t\tif( rbackend != \"SDL\" ) {\n\t\t\tm_gui_graphics = new OpenGLGuiGraphics(*m_imagepool);\n\t\t}\n#endif\n\t\tif( rbackend == \"SDL\" ) {\n\t\t\tm_gui_graphics = new SdlGuiGraphics(*m_imagepool);\n\t\t}\n\t\tFL_LOG(_log, \"Constructing GUI manager\");\n\t\tm_guimanager = new GUIManager(m_eventmanager, *m_imagepool);\n\t\tm_eventmanager->addSdlEventListener(m_guimanager);\n\t\t\/\/ keep guimanager as the first key listener so that it can evaluate guichan hits\n\t\tm_eventmanager->addKeyListener(m_guimanager);\n\t\t\/\/ keep guimanager as the first mouse listener so that it can evaluate guichan hits\n\t\tm_eventmanager->addMouseListener(m_guimanager);\n\t\tFL_LOG(_log, \"Events bind to GUI manager\");\n\n\t\tFL_LOG(_log, \"Creating default font\");\n\t\tm_defaultfont = m_guimanager->setDefaultFont(\n\t\t\tm_settings.getDefaultFontPath(),\n\t\t\tm_settings.getDefaultFontSize(),\n\t\t\tm_settings.getDefaultFontGlyphs());\n\t\tFL_LOG(_log, \"Initializing GUI manager\");\n\t\tm_guimanager->init(m_gui_graphics, m_settings.getScreenWidth(), m_settings.getScreenHeight());\n\t\tFL_LOG(_log, \"GUI manager initialized\");\n\t\tSDL_EnableUNICODE(1);\n\n\t\tFL_LOG(_log, \"Creating sound manager\");\n\t\tm_soundmanager = new SoundManager(m_soundclippool);\n\t\tm_soundmanager->setVolume(static_cast<float>(m_settings.getInitialVolume()) \/ 10);\n\n\t\tFL_LOG(_log, \"Creating model\");\n\t\tm_model = new Model();\n\t\tFL_LOG(_log, \"Adding pathers to model\");\n\t\tm_model->adoptPather(new LinearPather());\n\t\tm_model->adoptPather(new RoutePather());\n\t\tFL_LOG(_log, \"Adding grid prototypes to model\");\n\t\tm_model->adoptCellGrid(new SquareGrid());\n\t\tm_model->adoptCellGrid(new HexGrid());\n\n\t\tFL_LOG(_log, \"Creating view\");\n\t\tm_view = new View(m_renderbackend, m_imagepool, m_animpool);\n\t\tFL_LOG(_log, \"Creating renderers to view\");\n\t\tm_view->addRenderer(new CameraZoneRenderer(m_renderbackend, 0, m_imagepool));\n\t\tm_view->addRenderer(new InstanceRenderer(m_renderbackend, 10, m_imagepool, m_animpool));\n\t\tm_view->addRenderer(new GridRenderer(m_renderbackend, 20));\n\t\tm_view->addRenderer(new CellSelectionRenderer(m_renderbackend, 30));\n\t\tm_view->addRenderer(new BlockingInfoRenderer(m_renderbackend, 40));\n\t\tm_view->addRenderer(new FloatingTextRenderer(m_renderbackend, 50, dynamic_cast<AbstractFont*>(m_defaultfont)));\n\t\tm_view->addRenderer(new QuadTreeRenderer(m_renderbackend, 60));\n\t\tm_view->addRenderer(new CoordinateRenderer(m_renderbackend, 70, dynamic_cast<AbstractFont*>(m_defaultfont)));\n\t\tm_view->addRenderer(new GenericRenderer(m_renderbackend, 80, m_imagepool, m_animpool));\n\t\tm_cursor = new Cursor(m_imagepool, m_animpool, m_renderbackend);\n\t\tFL_LOG(_log, \"Engine intialized\");\n\t}\n\n\tEngine::~Engine() {\n\t\tFL_LOG(_log, \"Destructing engine\");\n \t\tdelete m_cursor;\n \t\tdelete m_view;\n\t\tdelete m_model;\n\t\tdelete m_soundmanager;\n\t\tdelete m_guimanager;\n\t\tdelete m_gui_graphics;\n\n\t\tm_renderbackend->deinit();\n\t\tdelete m_renderbackend;\n\n\t\t\/\/ Note the dependancy between image and animation pools\n\t\t\/\/ as animations reference images they have to be deleted\n\t\t\/\/ before clearing the image pool.\n\t\tdelete m_animpool;\n\t\tdelete m_imagepool;\n\t\tdelete m_eventmanager;\n\n\t\tdelete m_vfs;\n\n\t\tdelete m_timemanager;\n\n\t\tTTF_Quit();\n\t\tSDL_Quit();\n\t\tFL_LOG(_log, \"================== Engine destructed ==================\");\n\t\t\/\/delete m_logmanager;\n\t}\n\tvoid Engine::initializePumping() {\n\t\tm_eventmanager->processEvents();\n\t}\n\n\tvoid Engine::pump() {\n\t\tm_renderbackend->startFrame();\n\t\tm_timemanager->update();\n\t\tm_model->update();\n\t\tm_view->update();\n\t\tm_guimanager->turn();\n\t\tm_cursor->draw();\n\t\tm_renderbackend->endFrame();\n\t\tSDL_Delay(1);\n\t\tm_eventmanager->processEvents();\n\t}\n\n\tvoid Engine::finalizePumping() {\n\t\t\/\/ nothing here at the moment..\n\t}\n}\/\/FIFE\n\n\/* vim: set noexpandtab: set shiftwidth=2: set tabstop=2: *\/\n<commit_msg>increased felt responsiveness by first processing events and then drawing the screen<commit_after>\/***************************************************************************\n * Copyright (C) 2005-2008 by the FIFE team *\n * http:\/\/www.fifengine.de *\n * This file is part of FIFE. *\n * *\n * FIFE 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 *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***************************************************************************\/\n\n\/\/ Standard C++ library includes\n#include <iostream>\n\n\/\/ 3rd party library includes\n#include <SDL.h>\n#include <SDL_ttf.h>\n\n\/\/ FIFE includes\n\/\/ These includes are split up in two parts, separated by one empty line\n\/\/ First block: files included from the FIFE root src directory\n\/\/ Second block: files included from the same folder\n#include \"util\/base\/exception.h\"\n#include \"util\/log\/logger.h\"\n#include \"util\/time\/timemanager.h\"\n#include \"audio\/soundmanager.h\"\n#include \"gui\/console\/console.h\"\n#include \"gui\/guimanager.h\"\n#include \"vfs\/vfs.h\"\n#include \"vfs\/vfsdirectory.h\"\n#include \"vfs\/directoryprovider.h\"\n#ifdef HAVE_ZIP\n#include \"vfs\/zip\/zipprovider.h\"\n#endif\n#include \"eventchannel\/eventmanager.h\"\n#include \"video\/imagepool.h\"\n#include \"video\/animationpool.h\"\n#include \"audio\/soundclippool.h\"\n#include \"video\/renderbackend.h\"\n#include \"video\/cursor.h\"\n#ifdef HAVE_OPENGL\n#include \"video\/opengl\/renderbackendopengl.h\"\n#include \"gui\/base\/opengl\/opengl_gui_graphics.h\"\n#endif\n#include \"gui\/base\/sdl\/sdl_gui_graphics.h\"\n#include \"gui\/base\/gui_font.h\"\n#include \"video\/sdl\/renderbackendsdl.h\"\n#include \"video\/fonts\/abstractfont.h\"\n#include \"loaders\/native\/video_loaders\/subimage_loader.h\"\n#include \"loaders\/native\/video_loaders\/image_loader.h\"\n#include \"loaders\/native\/audio_loaders\/ogg_loader.h\"\n#include \"model\/model.h\"\n#include \"pathfinder\/linearpather\/linearpather.h\"\n#include \"pathfinder\/routepather\/routepather.h\"\n#include \"model\/metamodel\/grids\/hexgrid.h\"\n#include \"model\/metamodel\/grids\/squaregrid.h\"\n#include \"view\/view.h\"\n#include \"view\/renderers\/camerazonerenderer.h\"\n#include \"view\/renderers\/quadtreerenderer.h\"\n#include \"view\/renderers\/gridrenderer.h\"\n#include \"view\/renderers\/instancerenderer.h\"\n#include \"view\/renderers\/coordinaterenderer.h\"\n#include \"view\/renderers\/floatingtextrenderer.h\"\n#include \"view\/renderers\/cellselectionrenderer.h\"\n#include \"view\/renderers\/blockinginforenderer.h\"\n#include \"view\/renderers\/genericrenderer.h\"\n#include \"engine.h\"\n\n#ifdef USE_COCOA\n#include <dlfcn.h>\n\nint main(int argc, char **argv)\n{\n return 0;\n}\n#endif\n\nnamespace FIFE {\n\tstatic Logger _log(LM_CONTROLLER);\n\n\tEngine::Engine():\n\t\tm_renderbackend(0),\n\t\tm_guimanager(0),\n\t\tm_eventmanager(0),\n\t\tm_soundmanager(0),\n\t\tm_timemanager(0),\n\t\tm_imagepool(0),\n\t\tm_animpool(0),\n\t\tm_soundclippool(0),\n\t\tm_vfs(0),\n\t\tm_model(0),\n\t\tm_gui_graphics(0),\n\t\tm_view(0),\n\t\tm_logmanager(0),\n\t\tm_cursor(0),\n\t\tm_settings() {\n#ifdef USE_COCOA\n\t\t\/\/ The next lines ensure that Cocoa is initialzed correctly.\n\t\t\/\/ This is needed for SDL to function properly on MAC OS X.\n\t\tvoid* cocoa_lib;\n\t\tcocoa_lib = dlopen( \"\/System\/Library\/Frameworks\/Cocoa.framework\/Cocoa\", RTLD_LAZY );\n\t\tvoid (*nsappload)(void);\n\t\tnsappload = (void(*)()) dlsym( cocoa_lib, \"NSApplicationLoad\");\n\t\tnsappload();\n#endif\n\t\tpreInit();\n\t}\n\n\tEngineSettings& Engine::getSettings() {\n\t\treturn m_settings;\n\t}\n\n\tvoid Engine::preInit() {\n\t\tm_logmanager = LogManager::instance();\n\n\t\tFL_LOG(_log, \"================== Engine pre-init start =================\");\n\t\tm_timemanager = new TimeManager();\n\t\tFL_LOG(_log, \"Time manager created\");\n\n\t\tFL_LOG(_log, \"Creating VFS\");\n\t\tm_vfs = new VFS();\n\n\t\tFL_LOG(_log, \"Adding root directory to VFS\");\n\t\tm_vfs->addSource( new VFSDirectory(m_vfs) );\n\t\tm_vfs->addProvider( new DirectoryProvider() );\n#ifdef HAVE_ZIP\n\t\tFL_LOG(_log, \"Adding zip provider to VFS\");\n\t\tm_vfs->addProvider( new ZipProvider() );\n#endif\n\t\t\/\/m_vfs->addProvider(ProviderDAT2());\n\t\t\/\/m_vfs->addProvider(ProviderDAT1());\n\t\tFL_LOG(_log, \"Engine pre-init done\");\n\t}\n\n\tvoid Engine::init() {\n\t\tFL_LOG(_log, \"Engine initialize start\");\n\t\tm_settings.validate();\n\t\tFL_LOG(_log, \"Engine settings validated\");\n\n\t\t\/\/ If failed to init SDL throw exception.\n\t\tif (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER) < 0) {\n\t\t\tthrow SDLException(SDL_GetError());\n\t\t}\n\n\t\tSDL_EnableUNICODE(1);\n\t\tSDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);\n\t\tTTF_Init();\n\n\t\tFL_LOG(_log, \"Creating event manager\");\n\t\tm_eventmanager = new EventManager();\n\n\t\tFL_LOG(_log, \"Creating pools\");\n\t\tm_imagepool = new ImagePool();\n\t\tm_animpool = new AnimationPool();\n\t\tm_soundclippool = new SoundClipPool();\n\t\tm_imagepool->addResourceLoader(new SubImageLoader());\n\t\tm_imagepool->addResourceLoader(new ImageLoader(m_vfs));\n\t\tm_soundclippool->addResourceLoader(new OggLoader(m_vfs));\n\n\t\tFL_LOG(_log, \"Creating render backend\");\n\t\tstd::string rbackend(m_settings.getRenderBackend());\n\t\tif (rbackend == \"SDL\") {\n\t\t\tm_renderbackend = new RenderBackendSDL();\n\t\t\tFL_LOG(_log, \"SDL Render backend created\");\n\t\t} else {\n#ifdef HAVE_OPENGL\n\t\t\tm_renderbackend = new RenderBackendOpenGL();\n\t\t\tFL_LOG(_log, \"OpenGL Render backend created\");\n#else\n\t\t\tm_renderbackend = new RenderBackendSDL();\n\t\t\t\/\/ Remember the choice so we pick the right graphics class.\n\t\t\trbackend = \"SDL\";\n\t\t\tFL_WARN(_log, \"Tried to select OpenGL, even though it is not compiled into the engine. Falling back to SDL Render backend\");\n#endif\n\t\t}\n\t\tFL_LOG(_log, \"Initializing render backend\");\n\t\tm_renderbackend->setChunkingSize(m_settings.getImageChunkingSize());\n\t\tm_renderbackend->init();\n\n\t\tFL_LOG(_log, \"Creating main screen\");\n\t\tm_renderbackend->createMainScreen(\n\t\t\tm_settings.getScreenWidth(),\n\t\t\tm_settings.getScreenHeight(),\n\t\t\tstatic_cast<unsigned char>(m_settings.getBitsPerPixel()),\n\t\t\tm_settings.isFullScreen(),\n\t\t\tm_settings.getWindowTitle(),\n\t\t\tm_settings.getWindowIcon());\n\t\tFL_LOG(_log, \"Main screen created\");\n\n#ifdef HAVE_OPENGL\n\t\tif( rbackend != \"SDL\" ) {\n\t\t\tm_gui_graphics = new OpenGLGuiGraphics(*m_imagepool);\n\t\t}\n#endif\n\t\tif( rbackend == \"SDL\" ) {\n\t\t\tm_gui_graphics = new SdlGuiGraphics(*m_imagepool);\n\t\t}\n\t\tFL_LOG(_log, \"Constructing GUI manager\");\n\t\tm_guimanager = new GUIManager(m_eventmanager, *m_imagepool);\n\t\tm_eventmanager->addSdlEventListener(m_guimanager);\n\t\t\/\/ keep guimanager as the first key listener so that it can evaluate guichan hits\n\t\tm_eventmanager->addKeyListener(m_guimanager);\n\t\t\/\/ keep guimanager as the first mouse listener so that it can evaluate guichan hits\n\t\tm_eventmanager->addMouseListener(m_guimanager);\n\t\tFL_LOG(_log, \"Events bind to GUI manager\");\n\n\t\tFL_LOG(_log, \"Creating default font\");\n\t\tm_defaultfont = m_guimanager->setDefaultFont(\n\t\t\tm_settings.getDefaultFontPath(),\n\t\t\tm_settings.getDefaultFontSize(),\n\t\t\tm_settings.getDefaultFontGlyphs());\n\t\tFL_LOG(_log, \"Initializing GUI manager\");\n\t\tm_guimanager->init(m_gui_graphics, m_settings.getScreenWidth(), m_settings.getScreenHeight());\n\t\tFL_LOG(_log, \"GUI manager initialized\");\n\t\tSDL_EnableUNICODE(1);\n\n\t\tFL_LOG(_log, \"Creating sound manager\");\n\t\tm_soundmanager = new SoundManager(m_soundclippool);\n\t\tm_soundmanager->setVolume(static_cast<float>(m_settings.getInitialVolume()) \/ 10);\n\n\t\tFL_LOG(_log, \"Creating model\");\n\t\tm_model = new Model();\n\t\tFL_LOG(_log, \"Adding pathers to model\");\n\t\tm_model->adoptPather(new LinearPather());\n\t\tm_model->adoptPather(new RoutePather());\n\t\tFL_LOG(_log, \"Adding grid prototypes to model\");\n\t\tm_model->adoptCellGrid(new SquareGrid());\n\t\tm_model->adoptCellGrid(new HexGrid());\n\n\t\tFL_LOG(_log, \"Creating view\");\n\t\tm_view = new View(m_renderbackend, m_imagepool, m_animpool);\n\t\tFL_LOG(_log, \"Creating renderers to view\");\n\t\tm_view->addRenderer(new CameraZoneRenderer(m_renderbackend, 0, m_imagepool));\n\t\tm_view->addRenderer(new InstanceRenderer(m_renderbackend, 10, m_imagepool, m_animpool));\n\t\tm_view->addRenderer(new GridRenderer(m_renderbackend, 20));\n\t\tm_view->addRenderer(new CellSelectionRenderer(m_renderbackend, 30));\n\t\tm_view->addRenderer(new BlockingInfoRenderer(m_renderbackend, 40));\n\t\tm_view->addRenderer(new FloatingTextRenderer(m_renderbackend, 50, dynamic_cast<AbstractFont*>(m_defaultfont)));\n\t\tm_view->addRenderer(new QuadTreeRenderer(m_renderbackend, 60));\n\t\tm_view->addRenderer(new CoordinateRenderer(m_renderbackend, 70, dynamic_cast<AbstractFont*>(m_defaultfont)));\n\t\tm_view->addRenderer(new GenericRenderer(m_renderbackend, 80, m_imagepool, m_animpool));\n\t\tm_cursor = new Cursor(m_imagepool, m_animpool, m_renderbackend);\n\t\tFL_LOG(_log, \"Engine intialized\");\n\t}\n\n\tEngine::~Engine() {\n\t\tFL_LOG(_log, \"Destructing engine\");\n \t\tdelete m_cursor;\n \t\tdelete m_view;\n\t\tdelete m_model;\n\t\tdelete m_soundmanager;\n\t\tdelete m_guimanager;\n\t\tdelete m_gui_graphics;\n\n\t\tm_renderbackend->deinit();\n\t\tdelete m_renderbackend;\n\n\t\t\/\/ Note the dependancy between image and animation pools\n\t\t\/\/ as animations reference images they have to be deleted\n\t\t\/\/ before clearing the image pool.\n\t\tdelete m_animpool;\n\t\tdelete m_imagepool;\n\t\tdelete m_eventmanager;\n\n\t\tdelete m_vfs;\n\n\t\tdelete m_timemanager;\n\n\t\tTTF_Quit();\n\t\tSDL_Quit();\n\t\tFL_LOG(_log, \"================== Engine destructed ==================\");\n\t\t\/\/delete m_logmanager;\n\t}\n\tvoid Engine::initializePumping() {\n\t\tm_eventmanager->processEvents();\n\t}\n\n\tvoid Engine::pump() {\n\t\tm_eventmanager->processEvents();\n\t\tm_renderbackend->startFrame();\n\t\tm_timemanager->update();\n\t\tm_model->update();\n\t\tm_view->update();\n\t\tm_guimanager->turn();\n\t\tm_cursor->draw();\n\t\tm_renderbackend->endFrame();\n\t}\n\n\tvoid Engine::finalizePumping() {\n\t\t\/\/ nothing here at the moment..\n\t}\n}\/\/FIFE\n\n\/* vim: set noexpandtab: set shiftwidth=2: set tabstop=2: *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef PK_GRAPHS_SHORTESTPATHSFLOYDWARSHALL_HPP\n#define PK_GRAPHS_SHORTESTPATHSFLOYDWARSHALL_HPP\n\n\n#include <limits>\n\n\nnamespace pk\n{\nnamespace graphs\n{\n\n\ntemplate<const int V, class WeightType>\nclass shortest_paths_floyd_warshall\n{\npublic:\n typedef WeightType weight_type;\n typedef const weight_type (*shortest_paths_matrix)[V];\n\n shortest_paths_floyd_warshall() : infinity(std::numeric_limits<weight_type>::max()) {}\n\n template<class graph_type>\n void run(const graph_type& g)\n {\n const int num_of_vertices = g.get_num_of_vertices();\n\n for(int i = 0; i < num_of_vertices; ++i)\n {\n for(int j = 0; j < num_of_vertices; ++j)\n shortest_paths[i][j] = infinity;\n\n shortest_paths[i][i] = weight_type(0);\n }\n\n for(int v = 0; v < num_of_vertices; ++v)\n {\n const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v);\n for(int i = 0; i < adj_v.size(); ++i)\n {\n const int u = adj_v[i].to;\n shortest_paths[v][u] = adj_v[i].weight;\n }\n }\n\n for(int k = 0; k < num_of_vertices; ++k)\n {\n for(int i = 0; i < num_of_vertices; ++i)\n {\n for(int j = 0; j < num_of_vertices; ++j)\n {\n if((shortest_paths[i][k] == infinity) || (shortest_paths[k][j] == infinity))\n continue;\n\n const weight_type w = shortest_paths[i][k] + shortest_paths[k][j];\n if(w < shortest_paths[i][j])\n shortest_paths[i][j] = w;\n }\n }\n }\n }\n\n shortest_paths_matrix get_shortest_paths_matrix() const\n {\n return shortest_paths;\n }\n\n const weight_type infinity;\n\nprivate:\n weight_type shortest_paths[V][V];\n};\n\n\n} \/\/ namespace graphs\n} \/\/ namespace pk\n\n\n#endif \/\/ PK_GRAPHS_SHORTESTPATHSFLOYDWARSHALL_HPP\n<commit_msg>Cleaner code<commit_after>#ifndef PK_GRAPHS_SHORTESTPATHSFLOYDWARSHALL_HPP\n#define PK_GRAPHS_SHORTESTPATHSFLOYDWARSHALL_HPP\n\n\n#include <limits>\n\n\nnamespace pk\n{\nnamespace graphs\n{\n\n\ntemplate<const int V, class WeightType>\nclass shortest_paths_floyd_warshall\n{\npublic:\n typedef WeightType weight_type;\n typedef const weight_type (*shortest_paths_matrix)[V];\n\n shortest_paths_floyd_warshall() : infinity(std::numeric_limits<weight_type>::max()) {}\n\n template<class graph_type>\n void run(const graph_type& g)\n {\n num_of_vertices = g.get_num_of_vertices();\n\n initialize_all_paths_to_infinity_and_each_vertex_to_zero();\n set_initial_paths_to_neighbours(g);\n compute_shortest_paths();\n }\n\n shortest_paths_matrix get_shortest_paths_matrix() const\n {\n return shortest_paths;\n }\n\n const weight_type infinity;\n\nprivate:\n void initialize_all_paths_to_infinity_and_each_vertex_to_zero()\n {\n for(int i = 0; i < num_of_vertices; ++i)\n {\n for(int j = 0; j < num_of_vertices; ++j)\n shortest_paths[i][j] = infinity;\n\n shortest_paths[i][i] = weight_type(0);\n }\n }\n\n template<class graph_type>\n void set_initial_paths_to_neighbours(const graph_type& g)\n {\n for(int v = 0; v < num_of_vertices; ++v)\n {\n const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v);\n for(int i = 0; i < adj_v.size(); ++i)\n {\n const int u = adj_v[i].to;\n shortest_paths[v][u] = adj_v[i].weight;\n }\n }\n }\n\n void compute_shortest_paths()\n {\n for(int k = 0; k < num_of_vertices; ++k)\n {\n for(int i = 0; i < num_of_vertices; ++i)\n {\n for(int j = 0; j < num_of_vertices; ++j)\n {\n if((shortest_paths[i][k] == infinity) || (shortest_paths[k][j] == infinity))\n continue;\n\n const weight_type w = shortest_paths[i][k] + shortest_paths[k][j];\n if(w < shortest_paths[i][j])\n shortest_paths[i][j] = w;\n }\n }\n }\n }\n\n weight_type shortest_paths[V][V];\n int num_of_vertices;\n};\n\n\n} \/\/ namespace graphs\n} \/\/ namespace pk\n\n\n#endif \/\/ PK_GRAPHS_SHORTESTPATHSFLOYDWARSHALL_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file Sigma.cpp\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <gourdon.hpp>\n#include <primecount-internal.hpp>\n#include <primesieve.hpp>\n#include <int128_t.hpp>\n#include <min.hpp>\n#include <imath.hpp>\n#include <PiTable.hpp>\n#include <print.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\ntemplate <typename T>\nT Sigma0(T x, int64_t y, int threads)\n{\n T a = pi_legendre(y, threads);\n T pi_sqrtx = pi_legendre(isqrt(x), threads);\n\n return a - 1 + (pi_sqrtx * (pi_sqrtx - 1)) \/ 2 - (a * (a - 1)) \/ 2;\n}\n\ntemplate <typename T>\nT Sigma1(T x, int64_t y, int threads)\n{\n T a = pi_legendre(y, threads);\n T b = pi_legendre(iroot<3>(x), threads);\n\n return (a - b) * (a - b - 1) \/ 2;\n}\n\ntemplate <typename T>\nT Sigma2(T x, int64_t y, int threads)\n{\n T a = pi_legendre(y, threads);\n T b = pi_legendre(iroot<3>(x), threads);\n T c = pi_legendre(isqrt(x \/ y), threads);\n T x_star = max(iroot<4>(x), x \/ ((T) y * (T) y));\n T d = pi_legendre(x_star, threads);\n\n return a * (b - c - (c * (c - 3)) \/ 2 + (d * (d - 3)) \/ 2);\n}\n\ntemplate <typename T>\nT Sigma3(T x, int64_t y, int threads)\n{\n T b = pi_legendre(iroot<3>(x), threads);\n T x_star = max(iroot<4>(x), x \/ ((T) y * (T) y));\n T d = pi_legendre(x_star, threads);\n\n return (b * (b - 1) * (2 * b - 1)) \/ 6 - b - (d * (d - 1) * (2 * d - 1)) \/ 6 + d;\n}\n\n\/\/\/ Memory usage: O(x^(1\/3)) or less\ntemplate <typename T>\nT Sigma4(T x, int64_t y, int threads)\n{\n T sum = 0;\n int64_t pi_y = pi_legendre(y, threads);\n int64_t x_star = max(iroot<4>(x), x \/ ((T) y * (T) y));\n int64_t sqrt_xy = isqrt(x \/ y);\n\n PiTable pi(x \/ (x_star * (T) y));\n primesieve::iterator it(x_star, sqrt_xy);\n int64_t prime = it.next_prime();\n\n for (; prime <= sqrt_xy; prime = it.next_prime())\n sum += pi[x \/ (prime * (T) y)];\n\n return pi_y * sum;\n}\n\n\/\/\/ Memory usage: O(y)\ntemplate <typename T>\nT Sigma5(T x, int64_t y, int threads)\n{\n T sum = 0;\n int64_t x13 = iroot<3>(x);\n int64_t sqrt_xy = isqrt(x \/ y);\n\n PiTable pi(y);\n primesieve::iterator it(sqrt_xy, x13);\n int64_t prime = it.next_prime();\n\n for (; prime <= x13; prime = it.next_prime())\n sum += pi[x \/ (prime * (T) prime)];\n\n return sum;\n}\n\n\/\/\/ Memory usage: O(x^(3\/8))\ntemplate <typename T>\nT Sigma6(T x, int64_t y, int threads)\n{\n T sum = 0;\n int64_t sqrtx = isqrt(x);\n int64_t x13 = iroot<3>(x);\n int64_t x_star = max(iroot<4>(x), x \/ ((T) y * (T) y));\n\n PiTable pi(sqrtx \/ isqrt(x_star));\n primesieve::iterator it(x_star, x13);\n int64_t prime = it.next_prime();\n\n for (; prime <= x13; prime = it.next_prime())\n {\n T pix = pi[sqrtx \/ isqrt(prime)]; \n sum += pix * pix;\n }\n\n return -sum;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t Sigma(int64_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== Sigma(x, y) ===\");\n print(x, y, threads);\n\n double time = get_time();\n int64_t sum = Sigma0(x, y, threads) +\n Sigma1(x, y, threads) +\n Sigma2(x, y, threads) +\n Sigma3(x, y, threads) +\n Sigma4(x, y, threads) +\n Sigma5(x, y, threads) +\n Sigma6(x, y, threads);\n \n print(\"Sigma\", sum, time);\n return sum;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t Sigma(int128_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== Sigma(x, y) ===\");\n print(x, y, threads);\n\n double time = get_time();\n int128_t sum = Sigma0(x, y, threads) +\n Sigma1(x, y, threads) +\n Sigma2(x, y, threads) +\n Sigma3(x, y, threads) +\n Sigma4(x, y, threads) +\n Sigma5(x, y, threads) +\n Sigma6(x, y, threads);\n\n print(\"Sigma\", sum, time);\n return sum;\n}\n\n#endif\n\n} \/\/ namespace\n<commit_msg>Fix bug in Sigma6(x, a)<commit_after>\/\/\/\n\/\/\/ @file Sigma.cpp\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <gourdon.hpp>\n#include <primecount-internal.hpp>\n#include <primesieve.hpp>\n#include <int128_t.hpp>\n#include <min.hpp>\n#include <imath.hpp>\n#include <PiTable.hpp>\n#include <print.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\ntemplate <typename T>\nT Sigma0(T x, int64_t y, int threads)\n{\n T a = pi_legendre(y, threads);\n T pi_sqrtx = pi_legendre(isqrt(x), threads);\n\n return a - 1 + (pi_sqrtx * (pi_sqrtx - 1)) \/ 2 - (a * (a - 1)) \/ 2;\n}\n\ntemplate <typename T>\nT Sigma1(T x, int64_t y, int threads)\n{\n T a = pi_legendre(y, threads);\n T b = pi_legendre(iroot<3>(x), threads);\n\n return (a - b) * (a - b - 1) \/ 2;\n}\n\ntemplate <typename T>\nT Sigma2(T x, int64_t y, int threads)\n{\n T a = pi_legendre(y, threads);\n T b = pi_legendre(iroot<3>(x), threads);\n T c = pi_legendre(isqrt(x \/ y), threads);\n T x_star = max(iroot<4>(x), x \/ ((T) y * (T) y));\n T d = pi_legendre(x_star, threads);\n\n return a * (b - c - (c * (c - 3)) \/ 2 + (d * (d - 3)) \/ 2);\n}\n\ntemplate <typename T>\nT Sigma3(T x, int64_t y, int threads)\n{\n T b = pi_legendre(iroot<3>(x), threads);\n T x_star = max(iroot<4>(x), x \/ ((T) y * (T) y));\n T d = pi_legendre(x_star, threads);\n\n return (b * (b - 1) * (2 * b - 1)) \/ 6 - b - (d * (d - 1) * (2 * d - 1)) \/ 6 + d;\n}\n\n\/\/\/ Memory usage: O(x^(1\/3)) or less\ntemplate <typename T>\nT Sigma4(T x, int64_t y, int threads)\n{\n T sum = 0;\n int64_t pi_y = pi_legendre(y, threads);\n int64_t x_star = max(iroot<4>(x), x \/ ((T) y * (T) y));\n int64_t sqrt_xy = isqrt(x \/ y);\n\n PiTable pi(x \/ (x_star * (T) y));\n primesieve::iterator it(x_star, sqrt_xy);\n int64_t prime = it.next_prime();\n\n for (; prime <= sqrt_xy; prime = it.next_prime())\n sum += pi[x \/ (prime * (T) y)];\n\n return pi_y * sum;\n}\n\n\/\/\/ Memory usage: O(y)\ntemplate <typename T>\nT Sigma5(T x, int64_t y)\n{\n T sum = 0;\n int64_t x13 = iroot<3>(x);\n int64_t sqrt_xy = isqrt(x \/ y);\n\n PiTable pi(y);\n primesieve::iterator it(sqrt_xy, x13);\n int64_t prime = it.next_prime();\n\n for (; prime <= x13; prime = it.next_prime())\n sum += pi[x \/ (prime * (T) prime)];\n\n return sum;\n}\n\n\/\/\/ Memory usage: O(x^(3\/8))\ntemplate <typename T>\nT Sigma6(T x, int64_t y)\n{\n T sum = 0;\n int64_t x13 = iroot<3>(x);\n int64_t x_star = max(iroot<4>(x), x \/ ((T) y * (T) y));\n\n PiTable pi(isqrt(x \/ x_star));\n primesieve::iterator it(x_star, x13);\n int64_t prime = it.next_prime();\n\n for (; prime <= x13; prime = it.next_prime())\n {\n \/\/ Note that in Xavier Gourdon's paper the actual\n \/\/ formula for Σ6 is: sum += pi(x^(1\/2) \/ prime^(1\/2))^2.\n \/\/ However when implemented this way using integers\n \/\/ the formula returns erroneous results.\n \/\/ Hence the formula must be implemented as below:\n T pix = pi[isqrt(x \/ prime)]; \n sum += pix * pix;\n }\n \n return -sum;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t Sigma(int64_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== Sigma(x, y) ===\");\n print(x, y, threads);\n\n double time = get_time();\n int64_t sum = Sigma0(x, y, threads) +\n Sigma1(x, y, threads) +\n Sigma2(x, y, threads) +\n Sigma3(x, y, threads) +\n Sigma4(x, y, threads) +\n Sigma5(x, y) +\n Sigma6(x, y);\n \n print(\"Sigma\", sum, time);\n return sum;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t Sigma(int128_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== Sigma(x, y) ===\");\n print(x, y, threads);\n\n double time = get_time();\n int128_t sum = Sigma0(x, y, threads) +\n Sigma1(x, y, threads) +\n Sigma2(x, y, threads) +\n Sigma3(x, y, threads) +\n Sigma4(x, y, threads) +\n Sigma5(x, y) +\n Sigma6(x, y);\n\n print(\"Sigma\", sum, time);\n return sum;\n}\n\n#endif\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE rodb\n#include <boost\/test\/unit_test.hpp>\n\n#include \"rodb.h\"\n\nclass WhatIs\n{\npublic:\n\tWhatIs(char const *what): what_(what)\n\t{\n\t}\n\n\tbool operator ()(std::exception const &e)\n\t{\n\t\treturn what_ == e.what();\n\t}\n\nprivate:\n\tstd::string what_;\n};\n\nclass WhatStartsWith\n{\npublic:\n\tWhatStartsWith(char const *what): what_(what)\n\t{\n\t}\n\n\tbool operator ()(std::exception const &e)\n\t{\n\t\t\/\/ Check that e.what() start with what_. It's needed because e.what() might\n\t\t\/\/ have source file location information appended to it.\n\t\t\/\/ Example: Index is out of bounds in rodb.h, line 118\n\t\treturn what_.compare(0, what_.size(), e.what(), 0, std::min(what_.size(), strlen(e.what()))) == 0;\n\t}\n\nprivate:\n\tstd::string what_;\n};\n\n#define YAML_FILENAME \"unit_test.yaml\"\n#define RODB_FILENAME \"unit_test.rodb\"\n\nchar const *compile_rodb(char const *yaml)\n{\n\t{\n\t\tstd::ofstream out(YAML_FILENAME);\n\t\tout << yaml;\n\t}\n\n\tsystem(\".\/yaml2rodb.rb \" YAML_FILENAME \" \" RODB_FILENAME);\n\n\treturn RODB_FILENAME;\n}\n\n#define DB(db, yaml) rodb::Database db(compile_rodb(yaml))\n\nBOOST_AUTO_TEST_CASE(create_db)\n{\n\tBOOST_CHECK(rodb::Database::load(\"\") == 0);\n\tBOOST_REQUIRE_EXCEPTION(rodb::Database(\"\"), std::runtime_error, WhatIs(\"Cannot open input file\"));\n}\n\nBOOST_AUTO_TEST_CASE(scalar)\n{\n\tDB(db, \"[0]\");\n\n\tBOOST_CHECK(db.root()[0].is_scalar());\n\tBOOST_CHECK(db.root()[0].size() == 1);\n}\n\nBOOST_AUTO_TEST_CASE(access_array)\n{\n\tDB(db, \"[0, 1, 2, 3, 4]\");\n\n\tBOOST_CHECK(db.root().is_array());\n\tBOOST_CHECK(db.root().is_compound());\n\n\tBOOST_CHECK(db.root().size() == 5);\n\n\tBOOST_CHECK(db.root()[0] == 0);\n\tBOOST_CHECK(db.root()[1] == 1);\n\tBOOST_CHECK(db.root()[2] == 2);\n\tBOOST_CHECK(db.root()[3] == 3);\n\tBOOST_CHECK(db.root()[4] == 4);\n\t\n\tBOOST_REQUIRE_EXCEPTION(db.root()[-1], std::runtime_error, WhatStartsWith(\"Index is out of bounds\"));\n\tBOOST_REQUIRE_EXCEPTION(db.root()[5], std::runtime_error, WhatStartsWith(\"Index is out of bounds\"));\n}\n\nBOOST_AUTO_TEST_CASE(access_map)\n{\n\tDB(db, \"{key0: 0, key1: 1, key2: 2, key3: 3, key4: 4}\");\n\n\tBOOST_CHECK(db.root().is_map());\n\tBOOST_CHECK(db.root().is_compound());\n\n\tBOOST_CHECK(db.root().size() == 5);\n\n\tBOOST_CHECK(db.root().keys().is_array());\n\tBOOST_CHECK(db.root().keys().size() == 5);\n\t\n\tBOOST_CHECK(strcmp(db.root().keys()[0], \"key0\") == 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[1], \"key1\") == 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[2], \"key2\") == 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[3], \"key3\") == 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[4], \"key4\") == 0);\n\n\tBOOST_CHECK(db.root().has_key(\"key0\"));\n\tBOOST_CHECK(db.root().has_key(\"key1\"));\n\tBOOST_CHECK(db.root().has_key(\"key2\"));\n\tBOOST_CHECK(db.root().has_key(\"key3\"));\n\tBOOST_CHECK(db.root().has_key(\"key4\"));\n\n\tBOOST_CHECK(!db.root().has_key(\"\"));\n\tBOOST_CHECK(!db.root().has_key(\"key5\"));\n\n\tBOOST_CHECK(db.root().values().is_array());\n\tBOOST_CHECK(db.root().values().size() == 5);\n\n\tBOOST_CHECK(db.root().values()[0] == 0);\n\tBOOST_CHECK(db.root().values()[1] == 1);\n\tBOOST_CHECK(db.root().values()[2] == 2);\n\tBOOST_CHECK(db.root().values()[3] == 3);\n\tBOOST_CHECK(db.root().values()[4] == 4);\n\n\tBOOST_CHECK(db.root()[\"key0\"] == 0);\n\tBOOST_CHECK(db.root()[\"key1\"] == 1);\n\tBOOST_CHECK(db.root()[\"key2\"] == 2);\n\tBOOST_CHECK(db.root()[\"key3\"] == 3);\n\tBOOST_CHECK(db.root()[\"key4\"] == 4);\n\n\tBOOST_REQUIRE_EXCEPTION(db.root()[\"\"], std::runtime_error, WhatStartsWith(\"Key is not in the map\"));\n\tBOOST_REQUIRE_EXCEPTION(db.root()[\"key5\"], std::runtime_error, WhatStartsWith(\"Key is not in the map\"));\n}\n\nBOOST_AUTO_TEST_CASE(map_sorted)\n{\n\tDB(db, \"{key4: 4, key0: 0, key2: 2, key1: 1, key3: 3}\");\n\t\n\tBOOST_CHECK(strcmp(db.root().keys()[0], db.root().keys()[1]) <= 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[1], db.root().keys()[2]) <= 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[2], db.root().keys()[3]) <= 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[3], db.root().keys()[4]) <= 0);\n\n\tBOOST_CHECK(db.root()[\"key0\"] == 0);\n\tBOOST_CHECK(db.root()[\"key1\"] == 1);\n\tBOOST_CHECK(db.root()[\"key2\"] == 2);\n\tBOOST_CHECK(db.root()[\"key3\"] == 3);\n\tBOOST_CHECK(db.root()[\"key4\"] == 4);\n}\n\nBOOST_AUTO_TEST_CASE(map_sorted_equal)\n{\n\tDB(db1, \"{key4: 4, key0: 0, key2: 2, key1: 1, key3: 3}\");\n\tDB(db2, \"{key0: 0, key1: 1, key2: 2, key3: 3, key4: 4}\");\n\n\tBOOST_CHECK(db1.root() == db2.root());\n}\n\nBOOST_AUTO_TEST_CASE(numbers)\n{\n\tDB(db, \"[false, true, 0, 1000, 0x7fffffff, 0xffffffff, 0.0, 100.0, 1000.0, -10000.0]\");\n\n\t\/\/ Bools\n\tBOOST_CHECK(db.root()[0].is_bool());\n\tBOOST_CHECK(db.root()[1].is_bool());\n\n\tBOOST_CHECK(!db.root()[0]);\n\tBOOST_CHECK(db.root()[1]);\n\n\t\/\/ Ints\n\tBOOST_CHECK(db.root()[2].is_int());\n\tBOOST_CHECK(db.root()[3].is_int());\n\tBOOST_CHECK(db.root()[4].is_int());\n\tBOOST_CHECK(db.root()[5].is_int());\n\n\tBOOST_CHECK(db.root()[2] == 0);\n\tBOOST_CHECK(db.root()[3] == 1000);\n\tBOOST_CHECK(db.root()[4] == 0x7fffffff);\n\tBOOST_CHECK(db.root()[5] == 0xffffffffu);\n\n\t\/\/ Floats\n\tBOOST_CHECK(db.root()[6].is_float());\n\tBOOST_CHECK(db.root()[7].is_float());\n\tBOOST_CHECK(db.root()[8].is_float());\n\tBOOST_CHECK(db.root()[9].is_float());\n\t\n\tBOOST_CHECK(db.root()[6] == 0.0f);\n\tBOOST_CHECK(db.root()[7] == 100.0f);\n\tBOOST_CHECK(db.root()[8] == 1000.0f);\n\tBOOST_CHECK(db.root()[9] == -10000.0f);\n}\n\nBOOST_AUTO_TEST_CASE(strings)\n{\n\tDB(db, \"[string0, string1, string2, string3]\");\n\n\tBOOST_CHECK(db.root()[0].is_string());\n\tBOOST_CHECK(db.root()[1].is_string());\n\tBOOST_CHECK(db.root()[2].is_string());\n\n\tBOOST_CHECK(strcmp(db.root()[0], \"string0\") == 0);\n\tBOOST_CHECK(db.root()[0] == \"string0\");\n\tBOOST_CHECK(\"string0\" == db.root()[0]);\n\n\tBOOST_CHECK(strcmp(db.root()[1], \"string1\") == 0);\n\tBOOST_CHECK(db.root()[1] == \"string1\");\n\tBOOST_CHECK(\"string1\" == db.root()[1]);\n\n\tBOOST_CHECK(strcmp(db.root()[2], \"string2\") == 0);\n\tBOOST_CHECK(db.root()[2] == \"string2\");\n\tBOOST_CHECK(\"string2\" == db.root()[2]);\n\n\tBOOST_CHECK(strcmp(db.root()[3], \"string3\") == 0);\n\tBOOST_CHECK(db.root()[3] == \"string3\");\n\tBOOST_CHECK(\"string3\" == db.root()[3]);\n}\n\nBOOST_AUTO_TEST_CASE(nested_arrays)\n{\n\tDB(db, \"[[0], [1, 2], [3, 4, 5], [[0]], [[[0]]]]\");\n\n\tBOOST_CHECK(db.root().is_array());\n\tBOOST_CHECK(db.root().size() == 5);\n\n\tBOOST_CHECK(db.root()[0].is_array());\n\tBOOST_CHECK(db.root()[0].size() == 1);\n\n\tBOOST_CHECK(db.root()[1].is_array());\n\tBOOST_CHECK(db.root()[1].size() == 2);\n\n\tBOOST_CHECK(db.root()[2].is_array());\n\tBOOST_CHECK(db.root()[2].size() == 3);\n\n\tBOOST_CHECK(db.root()[3].is_array());\n\tBOOST_CHECK(db.root()[3][0].is_array());\n\tBOOST_CHECK(db.root()[3][0].size() == 1);\n\n\tBOOST_CHECK(db.root()[4].is_array());\n\tBOOST_CHECK(db.root()[4][0].is_array());\n\tBOOST_CHECK(db.root()[4][0].size() == 1);\n\tBOOST_CHECK(db.root()[4][0][0].size() == 1);\n}\n\nBOOST_AUTO_TEST_CASE(dump_yaml)\n{\n\tDB(db1, \"[[0], [1, 2], [3, 4, 5], [[0]], [[[0]]]]\");\n\n\tstd::ostringstream stream;\n\tdb1.dump_yaml(stream);\n\n\tDB(db2, stream.str().c_str());\n\tBOOST_CHECK(db2.root().size() == 5);\n\tBOOST_CHECK(db2.root()[4][0][0][0] == 0);\n}\n\nBOOST_AUTO_TEST_CASE(comparison)\n{\n\tDB(db, \"[10, 10, [10], [10], [10, 20], [20, 10], {a: b, cc: dd}, {cc: dd, a: b}, {a: dd, cc: b}, {cc: dd, a: b}]\");\n\n\tBOOST_CHECK(db.root()[0] == db.root()[1]);\n\tBOOST_CHECK(db.root()[2] == db.root()[3]);\n\tBOOST_CHECK(db.root()[4] != db.root()[5]);\n\tBOOST_CHECK(db.root()[6] == db.root()[7]);\n\tBOOST_CHECK(db.root()[8] != db.root()[9]);\n\tBOOST_CHECK(db.root()[0] != db.root()[2]);\n\tBOOST_CHECK(db.root()[1] != db.root()[6]);\n\tBOOST_CHECK(db.root()[4] != db.root()[9]);\n}\n\nBOOST_AUTO_TEST_CASE(direct_database_root_array_access)\n{\n\tDB(db, \"[0, 1, 2, 3, 4]\");\n\n\tBOOST_CHECK(db[0] == 0);\n\tBOOST_CHECK(db[1] == 1);\n\tBOOST_CHECK(db[2] == 2);\n\tBOOST_CHECK(db[3] == 3);\n\tBOOST_CHECK(db[4] == 4);\n\n\tBOOST_CHECK(db[0] == db.root()[0]);\n\tBOOST_CHECK(db[1] == db.root()[1]);\n\tBOOST_CHECK(db[2] == db.root()[2]);\n\tBOOST_CHECK(db[3] == db.root()[3]);\n\tBOOST_CHECK(db[4] == db.root()[4]);\n}\n\nBOOST_AUTO_TEST_CASE(direct_database_root_map_access)\n{\n\tDB(db, \"{key0: 0, key1: 1, key2: 2, key3: 3, key4: 4}\");\n\t\n\tBOOST_CHECK(db[\"key0\"] == 0);\n\tBOOST_CHECK(db[\"key1\"] == 1);\n\tBOOST_CHECK(db[\"key2\"] == 2);\n\tBOOST_CHECK(db[\"key3\"] == 3);\n\tBOOST_CHECK(db[\"key4\"] == 4);\n\n\tBOOST_CHECK(db[\"key0\"] == db.root()[\"key0\"]);\n\tBOOST_CHECK(db[\"key1\"] == db.root()[\"key1\"]);\n\tBOOST_CHECK(db[\"key2\"] == db.root()[\"key2\"]);\n\tBOOST_CHECK(db[\"key3\"] == db.root()[\"key3\"]);\n\tBOOST_CHECK(db[\"key4\"] == db.root()[\"key4\"]);\n}\n<commit_msg>Test empty map<commit_after>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE rodb\n#include <boost\/test\/unit_test.hpp>\n\n#include \"rodb.h\"\n\nclass WhatIs\n{\npublic:\n\tWhatIs(char const *what): what_(what)\n\t{\n\t}\n\n\tbool operator ()(std::exception const &e)\n\t{\n\t\treturn what_ == e.what();\n\t}\n\nprivate:\n\tstd::string what_;\n};\n\nclass WhatStartsWith\n{\npublic:\n\tWhatStartsWith(char const *what): what_(what)\n\t{\n\t}\n\n\tbool operator ()(std::exception const &e)\n\t{\n\t\t\/\/ Check that e.what() start with what_. It's needed because e.what() might\n\t\t\/\/ have source file location information appended to it.\n\t\t\/\/ Example: Index is out of bounds in rodb.h, line 118\n\t\treturn what_.compare(0, what_.size(), e.what(), 0, std::min(what_.size(), strlen(e.what()))) == 0;\n\t}\n\nprivate:\n\tstd::string what_;\n};\n\n#define YAML_FILENAME \"unit_test.yaml\"\n#define RODB_FILENAME \"unit_test.rodb\"\n\nchar const *compile_rodb(char const *yaml)\n{\n\t{\n\t\tstd::ofstream out(YAML_FILENAME);\n\t\tout << yaml;\n\t}\n\n\tsystem(\".\/yaml2rodb.rb \" YAML_FILENAME \" \" RODB_FILENAME);\n\n\treturn RODB_FILENAME;\n}\n\n#define DB(db, yaml) rodb::Database db(compile_rodb(yaml))\n\nBOOST_AUTO_TEST_CASE(create_db)\n{\n\tBOOST_CHECK(rodb::Database::load(\"\") == 0);\n\tBOOST_REQUIRE_EXCEPTION(rodb::Database(\"\"), std::runtime_error, WhatIs(\"Cannot open input file\"));\n}\n\nBOOST_AUTO_TEST_CASE(scalar)\n{\n\tDB(db, \"[0]\");\n\n\tBOOST_CHECK(db.root()[0].is_scalar());\n\tBOOST_CHECK(db.root()[0].size() == 1);\n}\n\nBOOST_AUTO_TEST_CASE(access_array)\n{\n\tDB(db, \"[0, 1, 2, 3, 4]\");\n\n\tBOOST_CHECK(db.root().is_array());\n\tBOOST_CHECK(db.root().is_compound());\n\n\tBOOST_CHECK(db.root().size() == 5);\n\n\tBOOST_CHECK(db.root()[0] == 0);\n\tBOOST_CHECK(db.root()[1] == 1);\n\tBOOST_CHECK(db.root()[2] == 2);\n\tBOOST_CHECK(db.root()[3] == 3);\n\tBOOST_CHECK(db.root()[4] == 4);\n\t\n\tBOOST_REQUIRE_EXCEPTION(db.root()[-1], std::runtime_error, WhatStartsWith(\"Index is out of bounds\"));\n\tBOOST_REQUIRE_EXCEPTION(db.root()[5], std::runtime_error, WhatStartsWith(\"Index is out of bounds\"));\n}\n\nBOOST_AUTO_TEST_CASE(access_map)\n{\n\tDB(db, \"{key0: 0, key1: 1, key2: 2, key3: 3, key4: 4}\");\n\n\tBOOST_CHECK(db.root().is_map());\n\tBOOST_CHECK(db.root().is_compound());\n\n\tBOOST_CHECK(db.root().size() == 5);\n\n\tBOOST_CHECK(db.root().keys().is_array());\n\tBOOST_CHECK(db.root().keys().size() == 5);\n\t\n\tBOOST_CHECK(strcmp(db.root().keys()[0], \"key0\") == 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[1], \"key1\") == 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[2], \"key2\") == 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[3], \"key3\") == 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[4], \"key4\") == 0);\n\n\tBOOST_CHECK(db.root().has_key(\"key0\"));\n\tBOOST_CHECK(db.root().has_key(\"key1\"));\n\tBOOST_CHECK(db.root().has_key(\"key2\"));\n\tBOOST_CHECK(db.root().has_key(\"key3\"));\n\tBOOST_CHECK(db.root().has_key(\"key4\"));\n\n\tBOOST_CHECK(!db.root().has_key(\"\"));\n\tBOOST_CHECK(!db.root().has_key(\"key5\"));\n\n\tBOOST_CHECK(db.root().values().is_array());\n\tBOOST_CHECK(db.root().values().size() == 5);\n\n\tBOOST_CHECK(db.root().values()[0] == 0);\n\tBOOST_CHECK(db.root().values()[1] == 1);\n\tBOOST_CHECK(db.root().values()[2] == 2);\n\tBOOST_CHECK(db.root().values()[3] == 3);\n\tBOOST_CHECK(db.root().values()[4] == 4);\n\n\tBOOST_CHECK(db.root()[\"key0\"] == 0);\n\tBOOST_CHECK(db.root()[\"key1\"] == 1);\n\tBOOST_CHECK(db.root()[\"key2\"] == 2);\n\tBOOST_CHECK(db.root()[\"key3\"] == 3);\n\tBOOST_CHECK(db.root()[\"key4\"] == 4);\n\n\tBOOST_REQUIRE_EXCEPTION(db.root()[\"\"], std::runtime_error, WhatStartsWith(\"Key is not in the map\"));\n\tBOOST_REQUIRE_EXCEPTION(db.root()[\"key5\"], std::runtime_error, WhatStartsWith(\"Key is not in the map\"));\n}\n\nBOOST_AUTO_TEST_CASE(empty_map)\n{\n\tDB(db, \"{}\");\n\n\tBOOST_CHECK(db.root().size() == 0);\n\n\tBOOST_CHECK(!db.root().has_key(\"\"));\n\tBOOST_CHECK(!db.root().has_key(\"key0\"));\n\n\tBOOST_REQUIRE_EXCEPTION(db.root()[\"\"], std::runtime_error, WhatStartsWith(\"Key is not in the map\"));\n\tBOOST_REQUIRE_EXCEPTION(db.root()[\"key0\"], std::runtime_error, WhatStartsWith(\"Key is not in the map\"));\n}\n\nBOOST_AUTO_TEST_CASE(map_sorted)\n{\n\tDB(db, \"{key4: 4, key0: 0, key2: 2, key1: 1, key3: 3}\");\n\t\n\tBOOST_CHECK(strcmp(db.root().keys()[0], db.root().keys()[1]) <= 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[1], db.root().keys()[2]) <= 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[2], db.root().keys()[3]) <= 0);\n\tBOOST_CHECK(strcmp(db.root().keys()[3], db.root().keys()[4]) <= 0);\n\n\tBOOST_CHECK(db.root()[\"key0\"] == 0);\n\tBOOST_CHECK(db.root()[\"key1\"] == 1);\n\tBOOST_CHECK(db.root()[\"key2\"] == 2);\n\tBOOST_CHECK(db.root()[\"key3\"] == 3);\n\tBOOST_CHECK(db.root()[\"key4\"] == 4);\n}\n\nBOOST_AUTO_TEST_CASE(map_sorted_equal)\n{\n\tDB(db1, \"{key4: 4, key0: 0, key2: 2, key1: 1, key3: 3}\");\n\tDB(db2, \"{key0: 0, key1: 1, key2: 2, key3: 3, key4: 4}\");\n\n\tBOOST_CHECK(db1.root() == db2.root());\n}\n\nBOOST_AUTO_TEST_CASE(numbers)\n{\n\tDB(db, \"[false, true, 0, 1000, 0x7fffffff, 0xffffffff, 0.0, 100.0, 1000.0, -10000.0]\");\n\n\t\/\/ Bools\n\tBOOST_CHECK(db.root()[0].is_bool());\n\tBOOST_CHECK(db.root()[1].is_bool());\n\n\tBOOST_CHECK(!db.root()[0]);\n\tBOOST_CHECK(db.root()[1]);\n\n\t\/\/ Ints\n\tBOOST_CHECK(db.root()[2].is_int());\n\tBOOST_CHECK(db.root()[3].is_int());\n\tBOOST_CHECK(db.root()[4].is_int());\n\tBOOST_CHECK(db.root()[5].is_int());\n\n\tBOOST_CHECK(db.root()[2] == 0);\n\tBOOST_CHECK(db.root()[3] == 1000);\n\tBOOST_CHECK(db.root()[4] == 0x7fffffff);\n\tBOOST_CHECK(db.root()[5] == 0xffffffffu);\n\n\t\/\/ Floats\n\tBOOST_CHECK(db.root()[6].is_float());\n\tBOOST_CHECK(db.root()[7].is_float());\n\tBOOST_CHECK(db.root()[8].is_float());\n\tBOOST_CHECK(db.root()[9].is_float());\n\t\n\tBOOST_CHECK(db.root()[6] == 0.0f);\n\tBOOST_CHECK(db.root()[7] == 100.0f);\n\tBOOST_CHECK(db.root()[8] == 1000.0f);\n\tBOOST_CHECK(db.root()[9] == -10000.0f);\n}\n\nBOOST_AUTO_TEST_CASE(strings)\n{\n\tDB(db, \"[string0, string1, string2, string3]\");\n\n\tBOOST_CHECK(db.root()[0].is_string());\n\tBOOST_CHECK(db.root()[1].is_string());\n\tBOOST_CHECK(db.root()[2].is_string());\n\n\tBOOST_CHECK(strcmp(db.root()[0], \"string0\") == 0);\n\tBOOST_CHECK(db.root()[0] == \"string0\");\n\tBOOST_CHECK(\"string0\" == db.root()[0]);\n\n\tBOOST_CHECK(strcmp(db.root()[1], \"string1\") == 0);\n\tBOOST_CHECK(db.root()[1] == \"string1\");\n\tBOOST_CHECK(\"string1\" == db.root()[1]);\n\n\tBOOST_CHECK(strcmp(db.root()[2], \"string2\") == 0);\n\tBOOST_CHECK(db.root()[2] == \"string2\");\n\tBOOST_CHECK(\"string2\" == db.root()[2]);\n\n\tBOOST_CHECK(strcmp(db.root()[3], \"string3\") == 0);\n\tBOOST_CHECK(db.root()[3] == \"string3\");\n\tBOOST_CHECK(\"string3\" == db.root()[3]);\n}\n\nBOOST_AUTO_TEST_CASE(nested_arrays)\n{\n\tDB(db, \"[[0], [1, 2], [3, 4, 5], [[0]], [[[0]]]]\");\n\n\tBOOST_CHECK(db.root().is_array());\n\tBOOST_CHECK(db.root().size() == 5);\n\n\tBOOST_CHECK(db.root()[0].is_array());\n\tBOOST_CHECK(db.root()[0].size() == 1);\n\n\tBOOST_CHECK(db.root()[1].is_array());\n\tBOOST_CHECK(db.root()[1].size() == 2);\n\n\tBOOST_CHECK(db.root()[2].is_array());\n\tBOOST_CHECK(db.root()[2].size() == 3);\n\n\tBOOST_CHECK(db.root()[3].is_array());\n\tBOOST_CHECK(db.root()[3][0].is_array());\n\tBOOST_CHECK(db.root()[3][0].size() == 1);\n\n\tBOOST_CHECK(db.root()[4].is_array());\n\tBOOST_CHECK(db.root()[4][0].is_array());\n\tBOOST_CHECK(db.root()[4][0].size() == 1);\n\tBOOST_CHECK(db.root()[4][0][0].size() == 1);\n}\n\nBOOST_AUTO_TEST_CASE(dump_yaml)\n{\n\tDB(db1, \"[[0], [1, 2], [3, 4, 5], [[0]], [[[0]]]]\");\n\n\tstd::ostringstream stream;\n\tdb1.dump_yaml(stream);\n\n\tDB(db2, stream.str().c_str());\n\tBOOST_CHECK(db2.root().size() == 5);\n\tBOOST_CHECK(db2.root()[4][0][0][0] == 0);\n}\n\nBOOST_AUTO_TEST_CASE(comparison)\n{\n\tDB(db, \"[10, 10, [10], [10], [10, 20], [20, 10], {a: b, cc: dd}, {cc: dd, a: b}, {a: dd, cc: b}, {cc: dd, a: b}]\");\n\n\tBOOST_CHECK(db.root()[0] == db.root()[1]);\n\tBOOST_CHECK(db.root()[2] == db.root()[3]);\n\tBOOST_CHECK(db.root()[4] != db.root()[5]);\n\tBOOST_CHECK(db.root()[6] == db.root()[7]);\n\tBOOST_CHECK(db.root()[8] != db.root()[9]);\n\tBOOST_CHECK(db.root()[0] != db.root()[2]);\n\tBOOST_CHECK(db.root()[1] != db.root()[6]);\n\tBOOST_CHECK(db.root()[4] != db.root()[9]);\n}\n\nBOOST_AUTO_TEST_CASE(direct_database_root_array_access)\n{\n\tDB(db, \"[0, 1, 2, 3, 4]\");\n\n\tBOOST_CHECK(db[0] == 0);\n\tBOOST_CHECK(db[1] == 1);\n\tBOOST_CHECK(db[2] == 2);\n\tBOOST_CHECK(db[3] == 3);\n\tBOOST_CHECK(db[4] == 4);\n\n\tBOOST_CHECK(db[0] == db.root()[0]);\n\tBOOST_CHECK(db[1] == db.root()[1]);\n\tBOOST_CHECK(db[2] == db.root()[2]);\n\tBOOST_CHECK(db[3] == db.root()[3]);\n\tBOOST_CHECK(db[4] == db.root()[4]);\n}\n\nBOOST_AUTO_TEST_CASE(direct_database_root_map_access)\n{\n\tDB(db, \"{key0: 0, key1: 1, key2: 2, key3: 3, key4: 4}\");\n\t\n\tBOOST_CHECK(db[\"key0\"] == 0);\n\tBOOST_CHECK(db[\"key1\"] == 1);\n\tBOOST_CHECK(db[\"key2\"] == 2);\n\tBOOST_CHECK(db[\"key3\"] == 3);\n\tBOOST_CHECK(db[\"key4\"] == 4);\n\n\tBOOST_CHECK(db[\"key0\"] == db.root()[\"key0\"]);\n\tBOOST_CHECK(db[\"key1\"] == db.root()[\"key1\"]);\n\tBOOST_CHECK(db[\"key2\"] == db.root()[\"key2\"]);\n\tBOOST_CHECK(db[\"key3\"] == db.root()[\"key3\"]);\n\tBOOST_CHECK(db[\"key4\"] == db.root()[\"key4\"]);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <mlopen\/handle.hpp>\n#include <mlopen\/errors.hpp>\n#include <algorithm>\n\nnamespace mlopen {\n\nstruct HandleImpl\n{\n \/\/ typedef MLOPEN_MANAGE_PTR(hipStream_t, hipStreamDestroy) StreamPtr;\n typedef std::shared_ptr<typename std::remove_pointer<hipStream_t>::type> StreamPtr;\n\n StreamPtr create_stream()\n {\n hipStream_t result;\n auto status = hipStreamCreate(&result);\n if (status != hipSuccess) MLOPEN_THROW(\"Failed to allocate stream\");\n return StreamPtr{result, &hipStreamDestroy};\n }\n\n static StreamPtr reference_stream(hipStream_t s)\n {\n return StreamPtr{s, null_deleter{}};\n }\n\n std::vector<StreamPtr> streams;\n};\n\nHandle::Handle (int numStreams, mlopenAcceleratorQueue_t *streams) \n: impl(new HandleImpl())\n{\n std::transform(streams, streams+numStreams, std::back_inserter(this->impl->streams), [](hipStream_t x) {\n return HandleImpl::reference_stream(x); \n });\n}\n\nHandle::Handle () \n: impl(new HandleImpl())\n{\n this->impl->streams.push_back(impl->create_stream());\n}\n\nHandle::~Handle() {}\n\nmlopenAcceleratorQueue_t Handle::GetStream() const\n{\n return impl->streams.front().get();\n}\n\nvoid Handle::EnableProfiling(bool enable)\n{\n \/\/ TODO\n}\n\nfloat Handle::GetKernelTime() const\n{\n return 0.0;\n}\n\nManageDataPtr Handle::Create(int sz)\n{\n void * result;\n auto status = hipMalloc(&result, sz);\n if (status != hipSuccess) MLOPEN_THROW(\"Hip error creating buffer: \" + std::to_string(status));\n return ManageDataPtr{result};\n}\nManageDataPtr& Handle::WriteTo(const void* data, ManageDataPtr& ddata, int sz)\n{\n auto status = hipMemcpy(ddata.get(), data, sz, hipMemcpyHostToDevice);\n if (status != hipSuccess) MLOPEN_THROW(\"Hip error writing to buffer: \" + std::to_string(status));\n return ddata;\n}\nvoid Handle::ReadTo(void* data, const ManageDataPtr& ddata, int sz)\n{\n auto status = hipMemcpy(data, ddata.get(), sz, hipMemcpyDeviceToHost);\n if (status != hipSuccess) MLOPEN_THROW(\"Hip error reading from buffer: \" + std::to_string(status));\n}\n}\n\n<commit_msg>Add flag for enabling profiling<commit_after>#include <mlopen\/handle.hpp>\n#include <mlopen\/errors.hpp>\n#include <algorithm>\n\nnamespace mlopen {\n\nstruct HandleImpl\n{\n \/\/ typedef MLOPEN_MANAGE_PTR(hipStream_t, hipStreamDestroy) StreamPtr;\n typedef std::shared_ptr<typename std::remove_pointer<hipStream_t>::type> StreamPtr;\n\n StreamPtr create_stream()\n {\n hipStream_t result;\n auto status = hipStreamCreate(&result);\n if (status != hipSuccess) MLOPEN_THROW(\"Failed to allocate stream\");\n return StreamPtr{result, &hipStreamDestroy};\n }\n\n static StreamPtr reference_stream(hipStream_t s)\n {\n return StreamPtr{s, null_deleter{}};\n }\n\n bool enable_profiling = false;\n std::vector<StreamPtr> streams;\n};\n\nHandle::Handle (int numStreams, mlopenAcceleratorQueue_t *streams) \n: impl(new HandleImpl())\n{\n std::transform(streams, streams+numStreams, std::back_inserter(this->impl->streams), [](hipStream_t x) {\n return HandleImpl::reference_stream(x); \n });\n}\n\nHandle::Handle () \n: impl(new HandleImpl())\n{\n this->impl->streams.push_back(impl->create_stream());\n}\n\nHandle::~Handle() {}\n\nmlopenAcceleratorQueue_t Handle::GetStream() const\n{\n return impl->streams.front().get();\n}\n\nvoid Handle::EnableProfiling(bool enable)\n{\n this->impl->enable_profiling = enable;\n}\n\nfloat Handle::GetKernelTime() const\n{\n \/\/ TODO: Temporary hack until the kernels are added\n if (this->impl->enable_profiling) return 1.0;\n else return 0.0;\n}\n\nManageDataPtr Handle::Create(int sz)\n{\n void * result;\n auto status = hipMalloc(&result, sz);\n if (status != hipSuccess) MLOPEN_THROW(\"Hip error creating buffer: \" + std::to_string(status));\n return ManageDataPtr{result};\n}\nManageDataPtr& Handle::WriteTo(const void* data, ManageDataPtr& ddata, int sz)\n{\n auto status = hipMemcpy(ddata.get(), data, sz, hipMemcpyHostToDevice);\n if (status != hipSuccess) MLOPEN_THROW(\"Hip error writing to buffer: \" + std::to_string(status));\n return ddata;\n}\nvoid Handle::ReadTo(void* data, const ManageDataPtr& ddata, int sz)\n{\n auto status = hipMemcpy(data, ddata.get(), sz, hipMemcpyDeviceToHost);\n if (status != hipSuccess) MLOPEN_THROW(\"Hip error reading from buffer: \" + std::to_string(status));\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef UTILITY_H\n#define UTILITY_H\n\n#include <string>\n#include <vector>\n#include <sstream>\n#include <omp.h>\n#include <cstring>\n#include <algorithm>\n#include <unistd.h>\n#include \"vg.pb.h\"\n#include \"sha1.hpp\"\n#include \"Variant.h\"\n\nnamespace vg {\n\nusing namespace std;\n\nchar reverse_complement(const char& c);\nstring reverse_complement(const string& seq);\nint get_thread_count(void);\nstring wrap_text(const string& str, size_t width);\nbool is_number(const string& s);\n\n\/\/ split a string on any character found in the string of delimiters (delims)\nstd::vector<std::string>& split_delims(const std::string &s, const std::string& delims, std::vector<std::string> &elems);\nstd::vector<std::string> split_delims(const std::string &s, const std::string& delims);\n\nconst std::string sha1sum(const std::string& data);\nconst std::string sha1head(const std::string& data, size_t head);\n\nbool allATGC(const string& s);\nstring nonATGCNtoN(const string& s);\nvoid mapping_cigar(const Mapping& mapping, vector<pair<int, char> >& cigar);\nstring cigar_string(vector<pair<int, char> >& cigar);\nstring mapping_string(const string& source, const Mapping& mapping);\ndouble median(std::vector<int> &v);\n\n\/\/ Convert a probability to a natural log probability.\ninline double prob_to_logprob(double prob) {\n return log(prob);\n}\n\/\/ Convert natural log probability to a probability\ninline double logprob_to_prob(double logprob) {\n return exp(logprob);\n}\n\/\/ Add two probabilities (expressed as logprobs) together and return the result\n\/\/ as a logprob.\ninline double logprob_add(double logprob1, double logprob2) {\n \/\/ Pull out the larger one to avoid underflows\n double pulled_out = max(logprob1, logprob2);\n return pulled_out + prob_to_logprob(logprob_to_prob(logprob1 - pulled_out) + logprob_to_prob(logprob2 - pulled_out));\n}\n\/\/ Invert a logprob, and get the probability of its opposite.\ninline double logprob_invert(double logprob) {\n return prob_to_logprob(1.0 - logprob_to_prob(logprob));\n}\n\n\/\/ Convert integer Phred quality score to probability of wrongness.\ninline double phred_to_prob(int phred) {\n return pow(10, -((double)phred) \/ 10);\n}\n\n\/\/ Convert probability of wrongness to integer Phred quality score.\ninline int prob_to_phred(double prob) {\n return round(-10.0 * log10(prob));\n}\n\n\/\/ Convert a Phred quality score directly to a natural log probability of wrongness.\ninline double phred_to_logprob(int phred) {\n return (-((double)phred) \/ 10) \/ log10(exp(1.0));\n}\n\n\/\/ Convert a natural log probability of wrongness directly to a Phred quality score.\ninline int logprob_to_phred(double logprob ) {\n return round(-10.0 * logprob * log10(exp(1.0)));\n}\n\ntemplate<typename T, typename V>\nset<T> map_keys_to_set(const map<T, V>& m) {\n set<T> r;\n for (auto p : m) r.insert(p.first);\n return r;\n}\n\n\/\/ pairwise maximum\ntemplate<typename T>\nvector<T> pmax(const std::vector<T>& a, const std::vector<T>& b) {\n std::vector<T> c;\n assert(a.size() == b.size());\n c.reserve(a.size());\n std::transform(a.begin(), a.end(), b.begin(),\n std::back_inserter(c),\n [](T a, T b) { return std::max<T>(a, b); });\n return c;\n}\n\n\/\/ maximum of all vectors\ntemplate<typename T>\nvector<T> vpmax(const std::vector<std::vector<T>>& vv) {\n std::vector<T> c;\n if (vv.empty()) return c;\n c = vv.front();\n typename std::vector<std::vector<T> >::const_iterator v = vv.begin();\n ++v; \/\/ skip the first element\n for ( ; v != vv.end(); ++v) {\n c = pmax(c, *v);\n }\n return c;\n}\n\n\/**\n * Compute the sum of the values in a collection. Values must be default-\n * constructable (like numbers are).\n *\/\ntemplate<typename Collection>\ntypename Collection::value_type sum(const Collection& collection) {\n \n \/\/ Set up an alias\n using Item = typename Collection::value_type;\n \n \/\/ Make a new zero-valued item to hold the sum\n auto total = Item();\n for(auto& to_sum : collection) {\n total += to_sum;\n }\n \n return total;\n \n}\n\n\/**\n * Compute the sum of the values in a collection, where the values are log\n * probabilities and the result is the log of the total probability. Items must\n * be convertible to\/from doubles for math.\n *\/\ntemplate<typename Collection>\ntypename Collection::value_type logprob_sum(const Collection& collection) {\n \n \/\/ Set up an alias\n using Item = typename Collection::value_type;\n \n \/\/ Pull out the minimum value\n auto min_iterator = min_element(begin(collection), end(collection));\n \n if(min_iterator == end(collection)) {\n \/\/ Nothing there, p = 0\n return Item(prob_to_logprob(0));\n }\n \n auto check_iterator = begin(collection);\n ++check_iterator;\n if(check_iterator == end(collection)) {\n \/\/ We only have a single element anyway. We don't want to subtract it\n \/\/ out because we'll get 0s.\n return *min_iterator;\n }\n \n \/\/ Pull this much out of every logprob.\n Item pulled_out = *min_iterator;\n \n if(logprob_to_prob(pulled_out) == 0) {\n \/\/ Can't divide by 0!\n \/\/ TODO: fix this in selection\n pulled_out = prob_to_logprob(1);\n }\n \n Item total(0);\n for(auto& to_add : collection) {\n \/\/ Sum up all the scaled probabilities.\n total += logprob_to_prob(to_add - pulled_out);\n }\n \n \/\/ Re-log and re-scale\n return pulled_out + prob_to_logprob(total);\n}\n\nstring tmpfilename(const string& base);\n\n\/\/ Code to detect if a variant lacks an ID and give it a unique but repeatable\n\/\/ one.\nstring get_or_make_variant_id(vcflib::Variant variant);\n\n\/\/ Simple little tree\ntemplate<typename T>\nstruct TreeNode {\n T v;\n vector<TreeNode<T>*> children;\n ~TreeNode() { for (auto c : children) { delete c; } }\n void for_each_preorder(function<void(TreeNode<T>*)> lambda) {\n lambda(this);\n for (auto c : children) {\n c->for_each_preorder(lambda);\n }\n }\n void for_each_postorder(function<void(TreeNode<T>*)> lambda) {\n for (auto c : children) {\n c->for_each_preorder(lambda);\n }\n lambda(this);\n }\n};\n\ntemplate<typename T>\nstruct Tree {\n typedef TreeNode<T> Node;\n Node* root;\n Tree(Node* r = 0) : root(r) {}\n ~Tree() { delete root; }\n void for_each_preorder(function<void(Node*)> lambda) {\n if (root) root->for_each_preorder(lambda);\n }\n void for_each_postorder(function<void(Node*)> lambda) {\n if (root) root->for_each_postorder(lambda);\n }\n\n};\n\n\n}\n\n#endif\n<commit_msg>Fix postorder to recurse as postorder and not preorder<commit_after>#ifndef UTILITY_H\n#define UTILITY_H\n\n#include <string>\n#include <vector>\n#include <sstream>\n#include <omp.h>\n#include <cstring>\n#include <algorithm>\n#include <unistd.h>\n#include \"vg.pb.h\"\n#include \"sha1.hpp\"\n#include \"Variant.h\"\n\nnamespace vg {\n\nusing namespace std;\n\nchar reverse_complement(const char& c);\nstring reverse_complement(const string& seq);\nint get_thread_count(void);\nstring wrap_text(const string& str, size_t width);\nbool is_number(const string& s);\n\n\/\/ split a string on any character found in the string of delimiters (delims)\nstd::vector<std::string>& split_delims(const std::string &s, const std::string& delims, std::vector<std::string> &elems);\nstd::vector<std::string> split_delims(const std::string &s, const std::string& delims);\n\nconst std::string sha1sum(const std::string& data);\nconst std::string sha1head(const std::string& data, size_t head);\n\nbool allATGC(const string& s);\nstring nonATGCNtoN(const string& s);\nvoid mapping_cigar(const Mapping& mapping, vector<pair<int, char> >& cigar);\nstring cigar_string(vector<pair<int, char> >& cigar);\nstring mapping_string(const string& source, const Mapping& mapping);\ndouble median(std::vector<int> &v);\n\n\/\/ Convert a probability to a natural log probability.\ninline double prob_to_logprob(double prob) {\n return log(prob);\n}\n\/\/ Convert natural log probability to a probability\ninline double logprob_to_prob(double logprob) {\n return exp(logprob);\n}\n\/\/ Add two probabilities (expressed as logprobs) together and return the result\n\/\/ as a logprob.\ninline double logprob_add(double logprob1, double logprob2) {\n \/\/ Pull out the larger one to avoid underflows\n double pulled_out = max(logprob1, logprob2);\n return pulled_out + prob_to_logprob(logprob_to_prob(logprob1 - pulled_out) + logprob_to_prob(logprob2 - pulled_out));\n}\n\/\/ Invert a logprob, and get the probability of its opposite.\ninline double logprob_invert(double logprob) {\n return prob_to_logprob(1.0 - logprob_to_prob(logprob));\n}\n\n\/\/ Convert integer Phred quality score to probability of wrongness.\ninline double phred_to_prob(int phred) {\n return pow(10, -((double)phred) \/ 10);\n}\n\n\/\/ Convert probability of wrongness to integer Phred quality score.\ninline int prob_to_phred(double prob) {\n return round(-10.0 * log10(prob));\n}\n\n\/\/ Convert a Phred quality score directly to a natural log probability of wrongness.\ninline double phred_to_logprob(int phred) {\n return (-((double)phred) \/ 10) \/ log10(exp(1.0));\n}\n\n\/\/ Convert a natural log probability of wrongness directly to a Phred quality score.\ninline int logprob_to_phred(double logprob ) {\n return round(-10.0 * logprob * log10(exp(1.0)));\n}\n\ntemplate<typename T, typename V>\nset<T> map_keys_to_set(const map<T, V>& m) {\n set<T> r;\n for (auto p : m) r.insert(p.first);\n return r;\n}\n\n\/\/ pairwise maximum\ntemplate<typename T>\nvector<T> pmax(const std::vector<T>& a, const std::vector<T>& b) {\n std::vector<T> c;\n assert(a.size() == b.size());\n c.reserve(a.size());\n std::transform(a.begin(), a.end(), b.begin(),\n std::back_inserter(c),\n [](T a, T b) { return std::max<T>(a, b); });\n return c;\n}\n\n\/\/ maximum of all vectors\ntemplate<typename T>\nvector<T> vpmax(const std::vector<std::vector<T>>& vv) {\n std::vector<T> c;\n if (vv.empty()) return c;\n c = vv.front();\n typename std::vector<std::vector<T> >::const_iterator v = vv.begin();\n ++v; \/\/ skip the first element\n for ( ; v != vv.end(); ++v) {\n c = pmax(c, *v);\n }\n return c;\n}\n\n\/**\n * Compute the sum of the values in a collection. Values must be default-\n * constructable (like numbers are).\n *\/\ntemplate<typename Collection>\ntypename Collection::value_type sum(const Collection& collection) {\n \n \/\/ Set up an alias\n using Item = typename Collection::value_type;\n \n \/\/ Make a new zero-valued item to hold the sum\n auto total = Item();\n for(auto& to_sum : collection) {\n total += to_sum;\n }\n \n return total;\n \n}\n\n\/**\n * Compute the sum of the values in a collection, where the values are log\n * probabilities and the result is the log of the total probability. Items must\n * be convertible to\/from doubles for math.\n *\/\ntemplate<typename Collection>\ntypename Collection::value_type logprob_sum(const Collection& collection) {\n \n \/\/ Set up an alias\n using Item = typename Collection::value_type;\n \n \/\/ Pull out the minimum value\n auto min_iterator = min_element(begin(collection), end(collection));\n \n if(min_iterator == end(collection)) {\n \/\/ Nothing there, p = 0\n return Item(prob_to_logprob(0));\n }\n \n auto check_iterator = begin(collection);\n ++check_iterator;\n if(check_iterator == end(collection)) {\n \/\/ We only have a single element anyway. We don't want to subtract it\n \/\/ out because we'll get 0s.\n return *min_iterator;\n }\n \n \/\/ Pull this much out of every logprob.\n Item pulled_out = *min_iterator;\n \n if(logprob_to_prob(pulled_out) == 0) {\n \/\/ Can't divide by 0!\n \/\/ TODO: fix this in selection\n pulled_out = prob_to_logprob(1);\n }\n \n Item total(0);\n for(auto& to_add : collection) {\n \/\/ Sum up all the scaled probabilities.\n total += logprob_to_prob(to_add - pulled_out);\n }\n \n \/\/ Re-log and re-scale\n return pulled_out + prob_to_logprob(total);\n}\n\nstring tmpfilename(const string& base);\n\n\/\/ Code to detect if a variant lacks an ID and give it a unique but repeatable\n\/\/ one.\nstring get_or_make_variant_id(vcflib::Variant variant);\n\n\/\/ Simple little tree\ntemplate<typename T>\nstruct TreeNode {\n T v;\n vector<TreeNode<T>*> children;\n ~TreeNode() { for (auto c : children) { delete c; } }\n void for_each_preorder(function<void(TreeNode<T>*)> lambda) {\n lambda(this);\n for (auto c : children) {\n c->for_each_preorder(lambda);\n }\n }\n void for_each_postorder(function<void(TreeNode<T>*)> lambda) {\n for (auto c : children) {\n c->for_each_postorder(lambda);\n }\n lambda(this);\n }\n};\n\ntemplate<typename T>\nstruct Tree {\n typedef TreeNode<T> Node;\n Node* root;\n Tree(Node* r = 0) : root(r) {}\n ~Tree() { delete root; }\n void for_each_preorder(function<void(Node*)> lambda) {\n if (root) root->for_each_preorder(lambda);\n }\n void for_each_postorder(function<void(Node*)> lambda) {\n if (root) root->for_each_postorder(lambda);\n }\n\n};\n\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix forwardJacDot calls in QPControllermex<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ 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 <limits>\n#include <set>\n#include <string>\n\n#include \"chrome\/browser\/history\/text_database.h\"\n\n#include \"app\/sql\/connection.h\"\n#include \"app\/sql\/statement.h\"\n#include \"app\/sql\/transaction.h\"\n#include \"base\/file_util.h\"\n#include \"base\/histogram.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/diagnostics\/sqlite_diagnostics.h\"\n\n\/\/ There are two tables in each database, one full-text search (FTS) table which\n\/\/ indexes the contents and title of the pages. The other is a regular SQLITE\n\/\/ table which contains non-indexed information about the page. All columns of\n\/\/ a FTS table are indexed using the text search algorithm, which isn't what we\n\/\/ want for things like times. If this were in the FTS table, there would be\n\/\/ different words in the index for each time number.\n\/\/\n\/\/ \"pages\" FTS table:\n\/\/ url URL of the page so searches will match the URL.\n\/\/ title Title of the page.\n\/\/ body Body of the page.\n\/\/\n\/\/ \"info\" regular table:\n\/\/ time Time the corresponding FTS entry was visited.\n\/\/\n\/\/ We do joins across these two tables by using their internal rowids, which we\n\/\/ keep in sync between the two tables. The internal rowid is the only part of\n\/\/ an FTS table that is indexed like a normal table, and the index over it is\n\/\/ free since sqlite always indexes the internal rowid.\n\nnamespace history {\n\nnamespace {\n\nstatic const int kCurrentVersionNumber = 1;\nstatic const int kCompatibleVersionNumber = 1;\n\n\/\/ Snippet computation relies on the index of the columns in the original\n\/\/ create statement. These are the 0-based indices (as strings) of the\n\/\/ corresponding columns.\nconst char kTitleColumnIndex[] = \"1\";\nconst char kBodyColumnIndex[] = \"2\";\n\n\/\/ The string prepended to the database identifier to generate the filename.\nconst FilePath::CharType kFilePrefix[] = FILE_PATH_LITERAL(\"History Index \");\n\n} \/\/ namespace\n\nTextDatabase::TextDatabase(const FilePath& path,\n DBIdent id,\n bool allow_create)\n : path_(path),\n ident_(id),\n allow_create_(allow_create) {\n \/\/ Compute the file name.\n file_name_ = path_.Append(IDToFileName(ident_));\n}\n\nTextDatabase::~TextDatabase() {\n}\n\n\/\/ static\nconst FilePath::CharType* TextDatabase::file_base() {\n return kFilePrefix;\n}\n\n\/\/ static\nFilePath TextDatabase::IDToFileName(DBIdent id) {\n \/\/ Identifiers are intended to be a combination of the year and month, for\n \/\/ example, 200801 for January 2008. We convert this to\n \/\/ \"History Index 2008-01\". However, we don't make assumptions about this\n \/\/ scheme: the caller should assign IDs as it feels fit with the knowledge\n \/\/ that they will apppear on disk in this form.\n FilePath::StringType filename(file_base());\n StringAppendF(&filename, FILE_PATH_LITERAL(\"%d-%02d\"),\n id \/ 100, id % 100);\n return FilePath(filename);\n}\n\n\/\/ static\nTextDatabase::DBIdent TextDatabase::FileNameToID(const FilePath& file_path) {\n FilePath::StringType file_name = file_path.BaseName().value();\n\n \/\/ We don't actually check the prefix here. Since the file system could\n \/\/ be case insensitive in ways we can't predict (NTFS), checking could\n \/\/ potentially be the wrong thing to do. Instead, we just look for a suffix.\n static const size_t kIDStringLength = 7; \/\/ Room for \"xxxx-xx\".\n if (file_name.length() < kIDStringLength)\n return 0;\n const FilePath::StringType suffix(\n &file_name[file_name.length() - kIDStringLength]);\n\n if (suffix.length() != kIDStringLength ||\n suffix[4] != FILE_PATH_LITERAL('-')) {\n return 0;\n }\n\n int year = StringToInt(suffix.substr(0, 4));\n int month = StringToInt(suffix.substr(5, 2));\n\n return year * 100 + month;\n}\n\nbool TextDatabase::Init() {\n \/\/ Make sure, if we're not allowed to create the file, that it exists.\n if (!allow_create_) {\n if (!file_util::PathExists(file_name_))\n return false;\n }\n\n \/\/ Set the exceptional sqlite error handler.\n db_.set_error_delegate(GetErrorHandlerForTextDb());\n\n \/\/ Set the database page size to something a little larger to give us\n \/\/ better performance (we're typically seek rather than bandwidth limited).\n \/\/ This only has an effect before any tables have been created, otherwise\n \/\/ this is a NOP. Must be a power of 2 and a max of 8192.\n db_.set_page_size(2096);\n\n \/\/ The default cache size is 2000 which give >8MB of data. Since we will often\n \/\/ have 2-3 of these objects, each with their own 8MB, this adds up very fast.\n \/\/ We therefore reduce the size so when there are multiple objects, we're not\n \/\/ too big.\n db_.set_cache_size(512);\n\n \/\/ Run the database in exclusive mode. Nobody else should be accessing the\n \/\/ database while we're running, and this will give somewhat improved perf.\n db_.set_exclusive_locking();\n\n \/\/ Attach the database to our index file.\n if (!db_.Open(file_name_))\n return false;\n\n \/\/ Meta table tracking version information.\n if (!meta_table_.Init(&db_, kCurrentVersionNumber, kCompatibleVersionNumber))\n return false;\n if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {\n \/\/ This version is too new. We don't bother notifying the user on this\n \/\/ error, and just fail to use the file. Normally if they have version skew,\n \/\/ they will get it for the main history file and it won't be necessary\n \/\/ here. If that's not the case, since this is only indexed data, it's\n \/\/ probably better to just not give FTS results than strange errors when\n \/\/ everything else is working OK.\n LOG(WARNING) << \"Text database is too new.\";\n return false;\n }\n\n return CreateTables();\n}\n\nvoid TextDatabase::BeginTransaction() {\n db_.BeginTransaction();\n}\n\nvoid TextDatabase::CommitTransaction() {\n db_.CommitTransaction();\n}\n\nbool TextDatabase::CreateTables() {\n \/\/ FTS table of page contents.\n if (!db_.DoesTableExist(\"pages\")) {\n if (!db_.Execute(\"CREATE VIRTUAL TABLE pages USING fts2(\"\n \"TOKENIZE icu,\"\n \"url LONGVARCHAR,\"\n \"title LONGVARCHAR,\"\n \"body LONGVARCHAR)\"))\n return false;\n }\n\n \/\/ Non-FTS table containing URLs and times so we can efficiently find them\n \/\/ using a regular index (all FTS columns are special and are treated as\n \/\/ full-text-search, which is not what we want when retrieving this data).\n if (!db_.DoesTableExist(\"info\")) {\n \/\/ Note that there is no point in creating an index over time. Since\n \/\/ we must always query the entire FTS table (it can not efficiently do\n \/\/ subsets), we will always end up doing that first, and joining the info\n \/\/ table off of that.\n if (!db_.Execute(\"CREATE TABLE info(time INTEGER NOT NULL)\"))\n return false;\n }\n\n \/\/ Create the index. This will fail when the index already exists, so we just\n \/\/ ignore the error.\n db_.Execute(\"CREATE INDEX info_time ON info(time)\");\n return true;\n}\n\nbool TextDatabase::AddPageData(base::Time time,\n const std::string& url,\n const std::string& title,\n const std::string& contents) {\n sql::Transaction committer(&db_);\n if (!committer.Begin())\n return false;\n\n \/\/ Add to the pages table.\n sql::Statement add_to_pages(db_.GetCachedStatement(SQL_FROM_HERE,\n \"INSERT INTO pages (url, title, body) VALUES (?,?,?)\"));\n if (!add_to_pages) {\n NOTREACHED() << db_.GetErrorMessage();\n return false;\n }\n add_to_pages.BindString(0, url);\n add_to_pages.BindString(1, title);\n add_to_pages.BindString(2, contents);\n if (!add_to_pages.Run()) {\n NOTREACHED() << db_.GetErrorMessage();\n return false;\n }\n\n int64 rowid = db_.GetLastInsertRowId();\n\n \/\/ Add to the info table with the same rowid.\n sql::Statement add_to_info(db_.GetCachedStatement(SQL_FROM_HERE,\n \"INSERT INTO info (rowid, time) VALUES (?,?)\"));\n if (!add_to_info) {\n NOTREACHED() << db_.GetErrorMessage();\n return false;\n }\n add_to_info.BindInt64(0, rowid);\n add_to_info.BindInt64(1, time.ToInternalValue());\n if (!add_to_info.Run()) {\n NOTREACHED() << db_.GetErrorMessage();\n return false;\n }\n\n return committer.Commit();\n}\n\nvoid TextDatabase::DeletePageData(base::Time time, const std::string& url) {\n \/\/ First get all rows that match. Selecing on time (which has an index) allows\n \/\/ us to avoid brute-force searches on the full-text-index table (there will\n \/\/ generally be only one match per time).\n sql::Statement select_ids(db_.GetCachedStatement(SQL_FROM_HERE,\n \"SELECT info.rowid \"\n \"FROM info JOIN pages ON info.rowid = pages.rowid \"\n \"WHERE info.time=? AND pages.url=?\"));\n if (!select_ids)\n return;\n select_ids.BindInt64(0, time.ToInternalValue());\n select_ids.BindString(1, url);\n std::set<int64> rows_to_delete;\n while (select_ids.Step())\n rows_to_delete.insert(select_ids.ColumnInt64(0));\n\n \/\/ Delete from the pages table.\n sql::Statement delete_page(db_.GetCachedStatement(SQL_FROM_HERE,\n \"DELETE FROM pages WHERE rowid=?\"));\n if (!delete_page)\n return;\n for (std::set<int64>::const_iterator i = rows_to_delete.begin();\n i != rows_to_delete.end(); ++i) {\n delete_page.BindInt64(0, *i);\n if (!delete_page.Run()) {\n NOTREACHED();\n return;\n }\n delete_page.Reset();\n }\n\n \/\/ Delete from the info table.\n sql::Statement delete_info(db_.GetCachedStatement(SQL_FROM_HERE,\n \"DELETE FROM info WHERE rowid=?\"));\n if (!delete_info)\n return;\n for (std::set<int64>::const_iterator i = rows_to_delete.begin();\n i != rows_to_delete.end(); ++i) {\n delete_info.BindInt64(0, *i);\n if (!delete_info.Run()) {\n NOTREACHED();\n return;\n }\n delete_info.Reset();\n }\n}\n\nvoid TextDatabase::Optimize() {\n sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,\n \"SELECT OPTIMIZE(pages) FROM pages LIMIT 1\"));\n if (!statement)\n return;\n statement.Run();\n}\n\nvoid TextDatabase::GetTextMatches(const std::string& query,\n const QueryOptions& options,\n std::vector<Match>* results,\n URLSet* found_urls,\n base::Time* first_time_searched) {\n *first_time_searched = options.begin_time;\n\n sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,\n \"SELECT url, title, time, offsets(pages), body \"\n \"FROM pages LEFT OUTER JOIN info ON pages.rowid = info.rowid \"\n \"WHERE pages MATCH ? AND time >= ? AND time < ? \"\n \"ORDER BY time DESC \"\n \"LIMIT ?\"));\n if (!statement)\n return;\n\n \/\/ When their values indicate \"unspecified\", saturate the numbers to the max\n \/\/ or min to get the correct result.\n int64 effective_begin_time = options.begin_time.is_null() ?\n 0 : options.begin_time.ToInternalValue();\n int64 effective_end_time = options.end_time.is_null() ?\n std::numeric_limits<int64>::max() : options.end_time.ToInternalValue();\n int effective_max_count = options.max_count ?\n options.max_count : std::numeric_limits<int>::max();\n\n statement.BindString(0, query);\n statement.BindInt64(1, effective_begin_time);\n statement.BindInt64(2, effective_end_time);\n statement.BindInt(3, effective_max_count);\n\n while (statement.Step()) {\n \/\/ TODO(brettw) allow canceling the query in the middle.\n \/\/ if (canceled_or_something)\n \/\/ break;\n\n GURL url(statement.ColumnString(0));\n URLSet::const_iterator found_url = found_urls->find(url);\n if (found_url != found_urls->end())\n continue; \/\/ Don't add this duplicate.\n\n \/\/ Fill the results into the vector (avoid copying the URL with Swap()).\n results->resize(results->size() + 1);\n Match& match = results->at(results->size() - 1);\n match.url.Swap(&url);\n\n match.title = UTF8ToWide(statement.ColumnString(1));\n match.time = base::Time::FromInternalValue(statement.ColumnInt64(2));\n\n \/\/ Extract any matches in the title.\n std::string offsets_str = statement.ColumnString(3);\n Snippet::ExtractMatchPositions(offsets_str, kTitleColumnIndex,\n &match.title_match_positions);\n Snippet::ConvertMatchPositionsToWide(statement.ColumnString(1),\n &match.title_match_positions);\n\n \/\/ Extract the matches in the body.\n Snippet::MatchPositions match_positions;\n Snippet::ExtractMatchPositions(offsets_str, kBodyColumnIndex,\n &match_positions);\n\n \/\/ Compute the snippet based on those matches.\n std::string body = statement.ColumnString(4);\n match.snippet.ComputeSnippet(match_positions, body);\n }\n\n \/\/ When we have returned all the results possible (or determined that there\n \/\/ are none), then we have searched all the time requested, so we can\n \/\/ set the first_time_searched to that value.\n if (results->size() == 0 ||\n options.max_count == 0 || \/\/ Special case for wanting all the results.\n static_cast<int>(results->size()) < options.max_count) {\n *first_time_searched = options.begin_time;\n } else {\n \/\/ Since we got the results in order, we know the last item is the last\n \/\/ time we considered.\n *first_time_searched = results->back().time;\n }\n\n statement.Reset();\n}\n\n} \/\/ namespace history\n<commit_msg>Make all new history index files use FTS3 instead of FTS2.<commit_after>\/\/ 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 <limits>\n#include <set>\n#include <string>\n\n#include \"chrome\/browser\/history\/text_database.h\"\n\n#include \"app\/sql\/connection.h\"\n#include \"app\/sql\/statement.h\"\n#include \"app\/sql\/transaction.h\"\n#include \"base\/file_util.h\"\n#include \"base\/histogram.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/diagnostics\/sqlite_diagnostics.h\"\n\n\/\/ There are two tables in each database, one full-text search (FTS) table which\n\/\/ indexes the contents and title of the pages. The other is a regular SQLITE\n\/\/ table which contains non-indexed information about the page. All columns of\n\/\/ a FTS table are indexed using the text search algorithm, which isn't what we\n\/\/ want for things like times. If this were in the FTS table, there would be\n\/\/ different words in the index for each time number.\n\/\/\n\/\/ \"pages\" FTS table:\n\/\/ url URL of the page so searches will match the URL.\n\/\/ title Title of the page.\n\/\/ body Body of the page.\n\/\/\n\/\/ \"info\" regular table:\n\/\/ time Time the corresponding FTS entry was visited.\n\/\/\n\/\/ We do joins across these two tables by using their internal rowids, which we\n\/\/ keep in sync between the two tables. The internal rowid is the only part of\n\/\/ an FTS table that is indexed like a normal table, and the index over it is\n\/\/ free since sqlite always indexes the internal rowid.\n\nnamespace history {\n\nnamespace {\n\nstatic const int kCurrentVersionNumber = 1;\nstatic const int kCompatibleVersionNumber = 1;\n\n\/\/ Snippet computation relies on the index of the columns in the original\n\/\/ create statement. These are the 0-based indices (as strings) of the\n\/\/ corresponding columns.\nconst char kTitleColumnIndex[] = \"1\";\nconst char kBodyColumnIndex[] = \"2\";\n\n\/\/ The string prepended to the database identifier to generate the filename.\nconst FilePath::CharType kFilePrefix[] = FILE_PATH_LITERAL(\"History Index \");\n\n} \/\/ namespace\n\nTextDatabase::TextDatabase(const FilePath& path,\n DBIdent id,\n bool allow_create)\n : path_(path),\n ident_(id),\n allow_create_(allow_create) {\n \/\/ Compute the file name.\n file_name_ = path_.Append(IDToFileName(ident_));\n}\n\nTextDatabase::~TextDatabase() {\n}\n\n\/\/ static\nconst FilePath::CharType* TextDatabase::file_base() {\n return kFilePrefix;\n}\n\n\/\/ static\nFilePath TextDatabase::IDToFileName(DBIdent id) {\n \/\/ Identifiers are intended to be a combination of the year and month, for\n \/\/ example, 200801 for January 2008. We convert this to\n \/\/ \"History Index 2008-01\". However, we don't make assumptions about this\n \/\/ scheme: the caller should assign IDs as it feels fit with the knowledge\n \/\/ that they will apppear on disk in this form.\n FilePath::StringType filename(file_base());\n StringAppendF(&filename, FILE_PATH_LITERAL(\"%d-%02d\"),\n id \/ 100, id % 100);\n return FilePath(filename);\n}\n\n\/\/ static\nTextDatabase::DBIdent TextDatabase::FileNameToID(const FilePath& file_path) {\n FilePath::StringType file_name = file_path.BaseName().value();\n\n \/\/ We don't actually check the prefix here. Since the file system could\n \/\/ be case insensitive in ways we can't predict (NTFS), checking could\n \/\/ potentially be the wrong thing to do. Instead, we just look for a suffix.\n static const size_t kIDStringLength = 7; \/\/ Room for \"xxxx-xx\".\n if (file_name.length() < kIDStringLength)\n return 0;\n const FilePath::StringType suffix(\n &file_name[file_name.length() - kIDStringLength]);\n\n if (suffix.length() != kIDStringLength ||\n suffix[4] != FILE_PATH_LITERAL('-')) {\n return 0;\n }\n\n int year = StringToInt(suffix.substr(0, 4));\n int month = StringToInt(suffix.substr(5, 2));\n\n return year * 100 + month;\n}\n\nbool TextDatabase::Init() {\n \/\/ Make sure, if we're not allowed to create the file, that it exists.\n if (!allow_create_) {\n if (!file_util::PathExists(file_name_))\n return false;\n }\n\n \/\/ Set the exceptional sqlite error handler.\n db_.set_error_delegate(GetErrorHandlerForTextDb());\n\n \/\/ Set the database page size to something a little larger to give us\n \/\/ better performance (we're typically seek rather than bandwidth limited).\n \/\/ This only has an effect before any tables have been created, otherwise\n \/\/ this is a NOP. Must be a power of 2 and a max of 8192.\n db_.set_page_size(2096);\n\n \/\/ The default cache size is 2000 which give >8MB of data. Since we will often\n \/\/ have 2-3 of these objects, each with their own 8MB, this adds up very fast.\n \/\/ We therefore reduce the size so when there are multiple objects, we're not\n \/\/ too big.\n db_.set_cache_size(512);\n\n \/\/ Run the database in exclusive mode. Nobody else should be accessing the\n \/\/ database while we're running, and this will give somewhat improved perf.\n db_.set_exclusive_locking();\n\n \/\/ Attach the database to our index file.\n if (!db_.Open(file_name_))\n return false;\n\n \/\/ Meta table tracking version information.\n if (!meta_table_.Init(&db_, kCurrentVersionNumber, kCompatibleVersionNumber))\n return false;\n if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {\n \/\/ This version is too new. We don't bother notifying the user on this\n \/\/ error, and just fail to use the file. Normally if they have version skew,\n \/\/ they will get it for the main history file and it won't be necessary\n \/\/ here. If that's not the case, since this is only indexed data, it's\n \/\/ probably better to just not give FTS results than strange errors when\n \/\/ everything else is working OK.\n LOG(WARNING) << \"Text database is too new.\";\n return false;\n }\n\n return CreateTables();\n}\n\nvoid TextDatabase::BeginTransaction() {\n db_.BeginTransaction();\n}\n\nvoid TextDatabase::CommitTransaction() {\n db_.CommitTransaction();\n}\n\nbool TextDatabase::CreateTables() {\n \/\/ FTS table of page contents.\n if (!db_.DoesTableExist(\"pages\")) {\n if (!db_.Execute(\"CREATE VIRTUAL TABLE pages USING fts3(\"\n \"TOKENIZE icu,\"\n \"url LONGVARCHAR,\"\n \"title LONGVARCHAR,\"\n \"body LONGVARCHAR)\"))\n return false;\n }\n\n \/\/ Non-FTS table containing URLs and times so we can efficiently find them\n \/\/ using a regular index (all FTS columns are special and are treated as\n \/\/ full-text-search, which is not what we want when retrieving this data).\n if (!db_.DoesTableExist(\"info\")) {\n \/\/ Note that there is no point in creating an index over time. Since\n \/\/ we must always query the entire FTS table (it can not efficiently do\n \/\/ subsets), we will always end up doing that first, and joining the info\n \/\/ table off of that.\n if (!db_.Execute(\"CREATE TABLE info(time INTEGER NOT NULL)\"))\n return false;\n }\n\n \/\/ Create the index. This will fail when the index already exists, so we just\n \/\/ ignore the error.\n db_.Execute(\"CREATE INDEX info_time ON info(time)\");\n return true;\n}\n\nbool TextDatabase::AddPageData(base::Time time,\n const std::string& url,\n const std::string& title,\n const std::string& contents) {\n sql::Transaction committer(&db_);\n if (!committer.Begin())\n return false;\n\n \/\/ Add to the pages table.\n sql::Statement add_to_pages(db_.GetCachedStatement(SQL_FROM_HERE,\n \"INSERT INTO pages (url, title, body) VALUES (?,?,?)\"));\n if (!add_to_pages) {\n NOTREACHED() << db_.GetErrorMessage();\n return false;\n }\n add_to_pages.BindString(0, url);\n add_to_pages.BindString(1, title);\n add_to_pages.BindString(2, contents);\n if (!add_to_pages.Run()) {\n NOTREACHED() << db_.GetErrorMessage();\n return false;\n }\n\n int64 rowid = db_.GetLastInsertRowId();\n\n \/\/ Add to the info table with the same rowid.\n sql::Statement add_to_info(db_.GetCachedStatement(SQL_FROM_HERE,\n \"INSERT INTO info (rowid, time) VALUES (?,?)\"));\n if (!add_to_info) {\n NOTREACHED() << db_.GetErrorMessage();\n return false;\n }\n add_to_info.BindInt64(0, rowid);\n add_to_info.BindInt64(1, time.ToInternalValue());\n if (!add_to_info.Run()) {\n NOTREACHED() << db_.GetErrorMessage();\n return false;\n }\n\n return committer.Commit();\n}\n\nvoid TextDatabase::DeletePageData(base::Time time, const std::string& url) {\n \/\/ First get all rows that match. Selecing on time (which has an index) allows\n \/\/ us to avoid brute-force searches on the full-text-index table (there will\n \/\/ generally be only one match per time).\n sql::Statement select_ids(db_.GetCachedStatement(SQL_FROM_HERE,\n \"SELECT info.rowid \"\n \"FROM info JOIN pages ON info.rowid = pages.rowid \"\n \"WHERE info.time=? AND pages.url=?\"));\n if (!select_ids)\n return;\n select_ids.BindInt64(0, time.ToInternalValue());\n select_ids.BindString(1, url);\n std::set<int64> rows_to_delete;\n while (select_ids.Step())\n rows_to_delete.insert(select_ids.ColumnInt64(0));\n\n \/\/ Delete from the pages table.\n sql::Statement delete_page(db_.GetCachedStatement(SQL_FROM_HERE,\n \"DELETE FROM pages WHERE rowid=?\"));\n if (!delete_page)\n return;\n for (std::set<int64>::const_iterator i = rows_to_delete.begin();\n i != rows_to_delete.end(); ++i) {\n delete_page.BindInt64(0, *i);\n if (!delete_page.Run()) {\n NOTREACHED();\n return;\n }\n delete_page.Reset();\n }\n\n \/\/ Delete from the info table.\n sql::Statement delete_info(db_.GetCachedStatement(SQL_FROM_HERE,\n \"DELETE FROM info WHERE rowid=?\"));\n if (!delete_info)\n return;\n for (std::set<int64>::const_iterator i = rows_to_delete.begin();\n i != rows_to_delete.end(); ++i) {\n delete_info.BindInt64(0, *i);\n if (!delete_info.Run()) {\n NOTREACHED();\n return;\n }\n delete_info.Reset();\n }\n}\n\nvoid TextDatabase::Optimize() {\n sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,\n \"SELECT OPTIMIZE(pages) FROM pages LIMIT 1\"));\n if (!statement)\n return;\n statement.Run();\n}\n\nvoid TextDatabase::GetTextMatches(const std::string& query,\n const QueryOptions& options,\n std::vector<Match>* results,\n URLSet* found_urls,\n base::Time* first_time_searched) {\n *first_time_searched = options.begin_time;\n\n sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,\n \"SELECT url, title, time, offsets(pages), body \"\n \"FROM pages LEFT OUTER JOIN info ON pages.rowid = info.rowid \"\n \"WHERE pages MATCH ? AND time >= ? AND time < ? \"\n \"ORDER BY time DESC \"\n \"LIMIT ?\"));\n if (!statement)\n return;\n\n \/\/ When their values indicate \"unspecified\", saturate the numbers to the max\n \/\/ or min to get the correct result.\n int64 effective_begin_time = options.begin_time.is_null() ?\n 0 : options.begin_time.ToInternalValue();\n int64 effective_end_time = options.end_time.is_null() ?\n std::numeric_limits<int64>::max() : options.end_time.ToInternalValue();\n int effective_max_count = options.max_count ?\n options.max_count : std::numeric_limits<int>::max();\n\n statement.BindString(0, query);\n statement.BindInt64(1, effective_begin_time);\n statement.BindInt64(2, effective_end_time);\n statement.BindInt(3, effective_max_count);\n\n while (statement.Step()) {\n \/\/ TODO(brettw) allow canceling the query in the middle.\n \/\/ if (canceled_or_something)\n \/\/ break;\n\n GURL url(statement.ColumnString(0));\n URLSet::const_iterator found_url = found_urls->find(url);\n if (found_url != found_urls->end())\n continue; \/\/ Don't add this duplicate.\n\n \/\/ Fill the results into the vector (avoid copying the URL with Swap()).\n results->resize(results->size() + 1);\n Match& match = results->at(results->size() - 1);\n match.url.Swap(&url);\n\n match.title = UTF8ToWide(statement.ColumnString(1));\n match.time = base::Time::FromInternalValue(statement.ColumnInt64(2));\n\n \/\/ Extract any matches in the title.\n std::string offsets_str = statement.ColumnString(3);\n Snippet::ExtractMatchPositions(offsets_str, kTitleColumnIndex,\n &match.title_match_positions);\n Snippet::ConvertMatchPositionsToWide(statement.ColumnString(1),\n &match.title_match_positions);\n\n \/\/ Extract the matches in the body.\n Snippet::MatchPositions match_positions;\n Snippet::ExtractMatchPositions(offsets_str, kBodyColumnIndex,\n &match_positions);\n\n \/\/ Compute the snippet based on those matches.\n std::string body = statement.ColumnString(4);\n match.snippet.ComputeSnippet(match_positions, body);\n }\n\n \/\/ When we have returned all the results possible (or determined that there\n \/\/ are none), then we have searched all the time requested, so we can\n \/\/ set the first_time_searched to that value.\n if (results->size() == 0 ||\n options.max_count == 0 || \/\/ Special case for wanting all the results.\n static_cast<int>(results->size()) < options.max_count) {\n *first_time_searched = options.begin_time;\n } else {\n \/\/ Since we got the results in order, we know the last item is the last\n \/\/ time we considered.\n *first_time_searched = results->back().time;\n }\n\n statement.Reset();\n}\n\n} \/\/ namespace history\n<|endoftext|>"} {"text":"<commit_before>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot\n \n licence: see nui3\/LICENCE.TXT\n *\/\n\n#include \"nuiPopupValueAttributeEditor.h\"\n#include \"nuiEditLine.h\"\n\n\n\nnuiPopupValueAttributeEditor::nuiPopupValueAttributeEditor(const nuiAttrib<uint32>& rAttribute, const nuiRange& rRange)\n: nuiAttributeEditor(), mAttribute(rAttribute), mRange(rRange), mEventSink(this)\n{\n SetObjectClass(_T(\"nuiPopupValueAttributeEditor\"));\n \n mpEditLine = new nuiEditLine();\n mpEditLine->SetObjectName(_T(\"NameAttributeEditor::EditLine\"));\n \n AddChild(mpEditLine);\n \n nglString str;\n mAttribute.ToString(str);\n mpEditLine->SetText(str);\n \n mpEditLine->Focus();\n mpEditLine->Do(nuiEditLine::eSelectAll,NULL);\n \n mEventSink.Connect(mpEditLine->Activated, &nuiPopupValueAttributeEditor::OnValidated);\n mEventSink.Connect(mpEditLine->Aborted, &nuiPopupValueAttributeEditor::OnCanceled);\n mEventSink.Connect(mAttribute.GetChangedEvent(), &nuiPopupValueAttributeEditor::OnAttributeChanged);\n}\n\n\n\n\nnuiPopupValueAttributeEditor::~nuiPopupValueAttributeEditor()\n{\n \n}\n\nbool nuiPopupValueAttributeEditor::OnValidated(const nuiEvent& rEvent)\n{\n nglString userStrValue = mpEditLine->GetText();\n double value = userStrValue.GetCDouble();\n \n nglString finalStrValue = userStrValue;\n double min = mRange.GetMinimum();\n double max = mRange.GetMaximum();\n if (value < min)\n {\n finalStrValue.SetCDouble(min);\n }\n else if (value > max)\n {\n finalStrValue.SetCDouble(max);\n }\n \n \n \/\/ auto trash\n Trash();\n \n return true;\n}\n\nbool nuiPopupValueAttributeEditor::OnCanceled(const nuiEvent& rEvent)\n{\n \/\/ auto trash\n Trash();\n return true;\n}\n\n\nbool nuiPopupValueAttributeEditor::OnAttributeChanged(const nuiEvent& rEvent)\n{\n nglString str;\n mAttribute.ToString(str);\n mpEditLine->SetText(str);\n return false;\n}\n<commit_msg>fixed the fix<commit_after>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot\n \n licence: see nui3\/LICENCE.TXT\n *\/\n\n#include \"nui.h\"\n#include \"nuiPopupValueAttributeEditor.h\"\n#include \"nuiEditLine.h\"\n\n\n\nnuiPopupValueAttributeEditor::nuiPopupValueAttributeEditor(const nuiAttrib<uint32>& rAttribute, const nuiRange& rRange)\n: nuiAttributeEditor(), mAttribute(rAttribute), mRange(rRange), mEventSink(this)\n{\n SetObjectClass(_T(\"nuiPopupValueAttributeEditor\"));\n \n mpEditLine = new nuiEditLine();\n mpEditLine->SetObjectName(_T(\"NameAttributeEditor::EditLine\"));\n \n AddChild(mpEditLine);\n \n nglString str;\n mAttribute.ToString(str);\n mpEditLine->SetText(str);\n \n mpEditLine->Focus();\n mpEditLine->Do(nuiEditLine::eSelectAll,NULL);\n \n mEventSink.Connect(mpEditLine->Activated, &nuiPopupValueAttributeEditor::OnValidated);\n mEventSink.Connect(mpEditLine->Aborted, &nuiPopupValueAttributeEditor::OnCanceled);\n mEventSink.Connect(mAttribute.GetChangedEvent(), &nuiPopupValueAttributeEditor::OnAttributeChanged);\n}\n\n\n\n\nnuiPopupValueAttributeEditor::~nuiPopupValueAttributeEditor()\n{\n \n}\n\nbool nuiPopupValueAttributeEditor::OnValidated(const nuiEvent& rEvent)\n{\n nglString userStrValue = mpEditLine->GetText();\n double value = userStrValue.GetCDouble();\n \n nglString finalStrValue = userStrValue;\n double min = mRange.GetMinimum();\n double max = mRange.GetMaximum();\n if (value < min)\n {\n finalStrValue.SetCDouble(min);\n }\n else if (value > max)\n {\n finalStrValue.SetCDouble(max);\n }\n \n \n \/\/ auto trash\n Trash();\n \n return true;\n}\n\nbool nuiPopupValueAttributeEditor::OnCanceled(const nuiEvent& rEvent)\n{\n \/\/ auto trash\n Trash();\n return true;\n}\n\n\nbool nuiPopupValueAttributeEditor::OnAttributeChanged(const nuiEvent& rEvent)\n{\n nglString str;\n mAttribute.ToString(str);\n mpEditLine->SetText(str);\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Q Light Controller\n audio.cpp\n\n Copyright (c) Massimo Callegari\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n Version 2 as published by the Free Software Foundation.\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. The license is\n in the file \"COPYING\".\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include <QDomDocument>\n#include <QDomElement>\n#include <QDebug>\n#include <QFile>\n\n#include <QMessageBox>\n\n#ifdef QT_PHONON_LIB\n#include <phonon\/mediaobject.h>\n#include <phonon\/backendcapabilities.h>\n#endif\n\n#include \"audiodecoder.h\"\n#ifdef HAS_LIBSNDFILE\n #include \"audiodecoder_sndfile.h\"\n#endif\n#ifdef HAS_LIBMAD\n #include \"audiodecoder_mad.h\"\n#endif\n\n#include \"audiorenderer.h\"\n\n#if defined(__APPLE__)\n \/\/#include \"audiorenderer_coreaudio.h\"\n #include \"audiorenderer_portaudio.h\"\n#elif defined(WIN32)\n #include \"audiorenderer_waveout.h\"\n#else\n #include \"audiorenderer_alsa.h\"\n#endif\n#include \"audio.h\"\n#include \"doc.h\"\n\n#define KXMLQLCAudioSource \"Source\"\n#define KXMLQLCAudioStartTime \"StartTime\"\n#define KXMLQLCAudioColor \"Color\"\n\n\/*****************************************************************************\n * Initialization\n *****************************************************************************\/\n\nAudio::Audio(Doc* doc)\n : Function(doc, Function::Audio)\n , m_doc(doc)\n#ifdef QT_PHONON_LIB\n , m_object(NULL)\n#endif\n , m_decoder(NULL)\n , m_audio_out(NULL)\n , m_startTime(UINT_MAX)\n , m_color(96, 128, 83)\n , m_sourceFileName(\"\")\n , m_audioDuration(0)\n{\n setName(tr(\"New Audio\"));\n\n \/\/ Listen to member Function removals\n connect(doc, SIGNAL(functionRemoved(quint32)),\n this, SLOT(slotFunctionRemoved(quint32)));\n}\n\nAudio::~Audio()\n{\n if (m_audio_out != NULL)\n {\n m_audio_out->stop();\n delete m_audio_out;\n }\n if (m_decoder != NULL)\n delete m_decoder;\n}\n\n\/*****************************************************************************\n * Copying\n *****************************************************************************\/\n\nFunction* Audio::createCopy(Doc* doc, bool addToDoc)\n{\n Q_ASSERT(doc != NULL);\n\n Function* copy = new Audio(doc);\n if (copy->copyFrom(this) == false)\n {\n delete copy;\n copy = NULL;\n }\n if (addToDoc == true && doc->addFunction(copy) == false)\n {\n delete copy;\n copy = NULL;\n }\n\n return copy;\n}\n\nbool Audio::copyFrom(const Function* function)\n{\n const Audio* aud = qobject_cast<const Audio*> (function);\n if (aud == NULL)\n return false;\n\n setSourceFileName(aud->m_sourceFileName);\n m_audioDuration = aud->m_audioDuration;\n m_color = aud->m_color;\n\n return Function::copyFrom(function);\n}\n\nQStringList Audio::getCapabilities()\n{\n QStringList cap;\n#ifdef QT_PHONON_LIB\n return Phonon::BackendCapabilities::availableMimeTypes();\n#endif\n#ifdef HAS_LIBSNDFILE\n cap << AudioDecoderSndFile::getSupportedFormats();\n#endif\n#ifdef HAS_LIBMAD\n cap << AudioDecoderMAD::getSupportedFormats();\n#endif\n return cap;\n}\n\n\/*********************************************************************\n * Properties\n *********************************************************************\/\nvoid Audio::setStartTime(quint32 time)\n{\n m_startTime = time;\n}\n\nquint32 Audio::getStartTime() const\n{\n return m_startTime;\n}\n\nqint64 Audio::getDuration()\n{\n return m_audioDuration;\n}\n\nvoid Audio::setColor(QColor color)\n{\n m_color = color;\n}\n\nQColor Audio::getColor()\n{\n return m_color;\n}\n\nbool Audio::setSourceFileName(QString filename)\n{\n if (m_sourceFileName.isEmpty() == false)\n {\n \/\/ unload previous source\n if (m_decoder != NULL)\n {\n delete m_decoder;\n m_decoder = NULL;\n }\n }\n\n#ifdef QT_PHONON_LIB\n m_object = Phonon::createPlayer(Phonon::MusicCategory,\n Phonon::MediaSource(filename));\n if (m_object == NULL)\n return false;\n#endif\n m_sourceFileName = filename;\n\n \/\/QMessageBox::warning(0,\"Warning\", QString(\"File complete path: %1\").arg(m_sourceFileName));\n\n if (QFile(m_sourceFileName).exists())\n setName(QFileInfo(m_sourceFileName).fileName());\n else\n {\n setName(tr(\"File not found\"));\n return true;\n }\n\n#ifdef QT_PHONON_LIB\n connect(m_object, SIGNAL(totalTimeChanged(qint64)), this, SLOT(slotTotalTimeChanged(qint64)));\n#endif\n\n#ifdef HAS_LIBSNDFILE\n m_decoder = new AudioDecoderSndFile(m_sourceFileName);\n if (m_decoder->initialize() == false)\n {\n delete m_decoder;\n m_decoder = NULL;\n }\n else\n {\n m_audioDuration = m_decoder->totalTime();\n return true;\n }\n#endif\n#ifdef HAS_LIBMAD\n m_decoder = new AudioDecoderMAD(m_sourceFileName);\n if (m_decoder->initialize() == false)\n {\n delete m_decoder;\n m_decoder = NULL;\n }\n else\n {\n m_audioDuration = m_decoder->totalTime();\n return true;\n }\n#endif\n return false;\n}\n\nQString Audio::getSourceFileName()\n{\n return m_sourceFileName;\n}\n\nAudioDecoder* Audio::getAudioDecoder()\n{\n return m_decoder;\n}\n\nvoid Audio::adjustAttribute(qreal fraction, int)\n{\n if (m_audio_out != NULL)\n m_audio_out->adjustIntensity(fraction);\n Function::adjustAttribute(fraction);\n}\n\nvoid Audio::slotTotalTimeChanged(qint64)\n{\n#ifdef QT_PHONON_LIB\n m_audioDuration = m_object->totalTime();\n#endif\n qDebug() << \"Audio duration: \" << m_audioDuration;\n emit totalTimeChanged(m_audioDuration);\n}\n\nvoid Audio::slotFunctionRemoved(quint32 fid)\n{\n Q_UNUSED(fid)\n}\n\nbool Audio::saveXML(QDomDocument* doc, QDomElement* wksp_root)\n{\n QDomElement root;\n QDomText text;\n\n Q_ASSERT(doc != NULL);\n Q_ASSERT(wksp_root != NULL);\n\n \/* Function tag *\/\n root = doc->createElement(KXMLQLCFunction);\n wksp_root->appendChild(root);\n\n root.setAttribute(KXMLQLCFunctionID, id());\n root.setAttribute(KXMLQLCFunctionType, Function::typeToString(type()));\n root.setAttribute(KXMLQLCFunctionName, name());\n\n QDomElement source = doc->createElement(KXMLQLCAudioSource);\n source.setAttribute(KXMLQLCAudioStartTime, m_startTime);\n source.setAttribute(KXMLQLCAudioColor, m_color.name());\n\n text = doc->createTextNode(m_doc->normalizeComponentPath(m_sourceFileName));\n\n source.appendChild(text);\n root.appendChild(source);\n\n return true;\n}\n\nbool Audio::loadXML(const QDomElement& root)\n{\n if (root.tagName() != KXMLQLCFunction)\n {\n qWarning() << Q_FUNC_INFO << \"Function node not found\";\n return false;\n }\n\n if (root.attribute(KXMLQLCFunctionType) != typeToString(Function::Audio))\n {\n qWarning() << Q_FUNC_INFO << root.attribute(KXMLQLCFunctionType)\n << \"is not Audio\";\n return false;\n }\n\n QDomNode node = root.firstChild();\n while (node.isNull() == false)\n {\n QDomElement tag = node.toElement();\n if (tag.tagName() == KXMLQLCAudioSource)\n {\n if (tag.hasAttribute(KXMLQLCAudioStartTime))\n m_startTime = tag.attribute(KXMLQLCAudioStartTime).toUInt();\n if (tag.hasAttribute(KXMLQLCAudioColor))\n m_color = QColor(tag.attribute(KXMLQLCAudioColor));\n setSourceFileName(m_doc->denormalizeComponentPath(tag.text()));\n }\n node = node.nextSibling();\n }\n\n return true;\n}\n\nvoid Audio::postLoad()\n{\n}\n\n\/*********************************************************************\n * Running\n *********************************************************************\/\nvoid Audio::preRun(MasterTimer* timer)\n{\n#ifdef QT_PHONON_LIB\n if (m_object != NULL)\n {\n m_object->play();\n return;\n }\n#endif\n if (m_decoder != NULL)\n {\n m_decoder->seek(elapsed());\n AudioParameters ap = m_decoder->audioParameters();\n#if defined(__APPLE__)\n \/\/m_audio_out = new AudioRendererCoreAudio();\n m_audio_out = new AudioRendererPortAudio();\n#elif defined(WIN32)\n m_audio_out = new AudioRendererWaveOut();\n#else\n m_audio_out = new AudioRendererAlsa();\n#endif\n m_audio_out->setDecoder(m_decoder);\n m_audio_out->initialize(ap.sampleRate(), ap.channels(), ap.format());\n m_audio_out->start();\n }\n Function::preRun(timer);\n}\n\nvoid Audio::write(MasterTimer* timer, UniverseArray* universes)\n{\n Q_UNUSED(timer)\n Q_UNUSED(universes)\n}\n\nvoid Audio::postRun(MasterTimer* timer, UniverseArray* universes)\n{\n Q_UNUSED(timer)\n Q_UNUSED(universes)\n#ifdef QT_PHONON_LIB\n if (m_object != NULL)\n m_object->stop();\n#endif\n if (m_audio_out != NULL)\n {\n m_audio_out->stop();\n delete m_audio_out;\n m_audio_out = NULL;\n m_decoder->seek(0);\n }\n Function::postRun(timer, universes);\n}\n<commit_msg>Fixed audio volume setting before playback<commit_after>\/*\n Q Light Controller\n audio.cpp\n\n Copyright (c) Massimo Callegari\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n Version 2 as published by the Free Software Foundation.\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. The license is\n in the file \"COPYING\".\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include <QDomDocument>\n#include <QDomElement>\n#include <QDebug>\n#include <QFile>\n\n#include <QMessageBox>\n\n#ifdef QT_PHONON_LIB\n#include <phonon\/mediaobject.h>\n#include <phonon\/backendcapabilities.h>\n#endif\n\n#include \"audiodecoder.h\"\n#ifdef HAS_LIBSNDFILE\n #include \"audiodecoder_sndfile.h\"\n#endif\n#ifdef HAS_LIBMAD\n #include \"audiodecoder_mad.h\"\n#endif\n\n#include \"audiorenderer.h\"\n\n#if defined(__APPLE__)\n \/\/#include \"audiorenderer_coreaudio.h\"\n #include \"audiorenderer_portaudio.h\"\n#elif defined(WIN32)\n #include \"audiorenderer_waveout.h\"\n#else\n #include \"audiorenderer_alsa.h\"\n#endif\n#include \"audio.h\"\n#include \"doc.h\"\n\n#define KXMLQLCAudioSource \"Source\"\n#define KXMLQLCAudioStartTime \"StartTime\"\n#define KXMLQLCAudioColor \"Color\"\n\n\/*****************************************************************************\n * Initialization\n *****************************************************************************\/\n\nAudio::Audio(Doc* doc)\n : Function(doc, Function::Audio)\n , m_doc(doc)\n#ifdef QT_PHONON_LIB\n , m_object(NULL)\n#endif\n , m_decoder(NULL)\n , m_audio_out(NULL)\n , m_startTime(UINT_MAX)\n , m_color(96, 128, 83)\n , m_sourceFileName(\"\")\n , m_audioDuration(0)\n{\n setName(tr(\"New Audio\"));\n\n \/\/ Listen to member Function removals\n connect(doc, SIGNAL(functionRemoved(quint32)),\n this, SLOT(slotFunctionRemoved(quint32)));\n}\n\nAudio::~Audio()\n{\n if (m_audio_out != NULL)\n {\n m_audio_out->stop();\n delete m_audio_out;\n }\n if (m_decoder != NULL)\n delete m_decoder;\n}\n\n\/*****************************************************************************\n * Copying\n *****************************************************************************\/\n\nFunction* Audio::createCopy(Doc* doc, bool addToDoc)\n{\n Q_ASSERT(doc != NULL);\n\n Function* copy = new Audio(doc);\n if (copy->copyFrom(this) == false)\n {\n delete copy;\n copy = NULL;\n }\n if (addToDoc == true && doc->addFunction(copy) == false)\n {\n delete copy;\n copy = NULL;\n }\n\n return copy;\n}\n\nbool Audio::copyFrom(const Function* function)\n{\n const Audio* aud = qobject_cast<const Audio*> (function);\n if (aud == NULL)\n return false;\n\n setSourceFileName(aud->m_sourceFileName);\n m_audioDuration = aud->m_audioDuration;\n m_color = aud->m_color;\n\n return Function::copyFrom(function);\n}\n\nQStringList Audio::getCapabilities()\n{\n QStringList cap;\n#ifdef QT_PHONON_LIB\n return Phonon::BackendCapabilities::availableMimeTypes();\n#endif\n#ifdef HAS_LIBSNDFILE\n cap << AudioDecoderSndFile::getSupportedFormats();\n#endif\n#ifdef HAS_LIBMAD\n cap << AudioDecoderMAD::getSupportedFormats();\n#endif\n return cap;\n}\n\n\/*********************************************************************\n * Properties\n *********************************************************************\/\nvoid Audio::setStartTime(quint32 time)\n{\n m_startTime = time;\n}\n\nquint32 Audio::getStartTime() const\n{\n return m_startTime;\n}\n\nqint64 Audio::getDuration()\n{\n return m_audioDuration;\n}\n\nvoid Audio::setColor(QColor color)\n{\n m_color = color;\n}\n\nQColor Audio::getColor()\n{\n return m_color;\n}\n\nbool Audio::setSourceFileName(QString filename)\n{\n if (m_sourceFileName.isEmpty() == false)\n {\n \/\/ unload previous source\n if (m_decoder != NULL)\n {\n delete m_decoder;\n m_decoder = NULL;\n }\n }\n\n#ifdef QT_PHONON_LIB\n m_object = Phonon::createPlayer(Phonon::MusicCategory,\n Phonon::MediaSource(filename));\n if (m_object == NULL)\n return false;\n#endif\n m_sourceFileName = filename;\n\n \/\/QMessageBox::warning(0,\"Warning\", QString(\"File complete path: %1\").arg(m_sourceFileName));\n\n if (QFile(m_sourceFileName).exists())\n setName(QFileInfo(m_sourceFileName).fileName());\n else\n {\n setName(tr(\"File not found\"));\n return true;\n }\n\n#ifdef QT_PHONON_LIB\n connect(m_object, SIGNAL(totalTimeChanged(qint64)), this, SLOT(slotTotalTimeChanged(qint64)));\n#endif\n\n#ifdef HAS_LIBSNDFILE\n m_decoder = new AudioDecoderSndFile(m_sourceFileName);\n if (m_decoder->initialize() == false)\n {\n delete m_decoder;\n m_decoder = NULL;\n }\n else\n {\n m_audioDuration = m_decoder->totalTime();\n return true;\n }\n#endif\n#ifdef HAS_LIBMAD\n m_decoder = new AudioDecoderMAD(m_sourceFileName);\n if (m_decoder->initialize() == false)\n {\n delete m_decoder;\n m_decoder = NULL;\n }\n else\n {\n m_audioDuration = m_decoder->totalTime();\n return true;\n }\n#endif\n return false;\n}\n\nQString Audio::getSourceFileName()\n{\n return m_sourceFileName;\n}\n\nAudioDecoder* Audio::getAudioDecoder()\n{\n return m_decoder;\n}\n\nvoid Audio::adjustAttribute(qreal fraction, int)\n{\n if (m_audio_out != NULL)\n m_audio_out->adjustIntensity(fraction);\n Function::adjustAttribute(fraction);\n}\n\nvoid Audio::slotTotalTimeChanged(qint64)\n{\n#ifdef QT_PHONON_LIB\n m_audioDuration = m_object->totalTime();\n#endif\n qDebug() << \"Audio duration: \" << m_audioDuration;\n emit totalTimeChanged(m_audioDuration);\n}\n\nvoid Audio::slotFunctionRemoved(quint32 fid)\n{\n Q_UNUSED(fid)\n}\n\nbool Audio::saveXML(QDomDocument* doc, QDomElement* wksp_root)\n{\n QDomElement root;\n QDomText text;\n\n Q_ASSERT(doc != NULL);\n Q_ASSERT(wksp_root != NULL);\n\n \/* Function tag *\/\n root = doc->createElement(KXMLQLCFunction);\n wksp_root->appendChild(root);\n\n root.setAttribute(KXMLQLCFunctionID, id());\n root.setAttribute(KXMLQLCFunctionType, Function::typeToString(type()));\n root.setAttribute(KXMLQLCFunctionName, name());\n\n QDomElement source = doc->createElement(KXMLQLCAudioSource);\n source.setAttribute(KXMLQLCAudioStartTime, m_startTime);\n source.setAttribute(KXMLQLCAudioColor, m_color.name());\n\n text = doc->createTextNode(m_doc->normalizeComponentPath(m_sourceFileName));\n\n source.appendChild(text);\n root.appendChild(source);\n\n return true;\n}\n\nbool Audio::loadXML(const QDomElement& root)\n{\n if (root.tagName() != KXMLQLCFunction)\n {\n qWarning() << Q_FUNC_INFO << \"Function node not found\";\n return false;\n }\n\n if (root.attribute(KXMLQLCFunctionType) != typeToString(Function::Audio))\n {\n qWarning() << Q_FUNC_INFO << root.attribute(KXMLQLCFunctionType)\n << \"is not Audio\";\n return false;\n }\n\n QDomNode node = root.firstChild();\n while (node.isNull() == false)\n {\n QDomElement tag = node.toElement();\n if (tag.tagName() == KXMLQLCAudioSource)\n {\n if (tag.hasAttribute(KXMLQLCAudioStartTime))\n m_startTime = tag.attribute(KXMLQLCAudioStartTime).toUInt();\n if (tag.hasAttribute(KXMLQLCAudioColor))\n m_color = QColor(tag.attribute(KXMLQLCAudioColor));\n setSourceFileName(m_doc->denormalizeComponentPath(tag.text()));\n }\n node = node.nextSibling();\n }\n\n return true;\n}\n\nvoid Audio::postLoad()\n{\n}\n\n\/*********************************************************************\n * Running\n *********************************************************************\/\nvoid Audio::preRun(MasterTimer* timer)\n{\n#ifdef QT_PHONON_LIB\n if (m_object != NULL)\n {\n m_object->play();\n return;\n }\n#endif\n if (m_decoder != NULL)\n {\n m_decoder->seek(elapsed());\n AudioParameters ap = m_decoder->audioParameters();\n#if defined(__APPLE__)\n \/\/m_audio_out = new AudioRendererCoreAudio();\n m_audio_out = new AudioRendererPortAudio();\n#elif defined(WIN32)\n m_audio_out = new AudioRendererWaveOut();\n#else\n m_audio_out = new AudioRendererAlsa();\n#endif\n m_audio_out->setDecoder(m_decoder);\n m_audio_out->initialize(ap.sampleRate(), ap.channels(), ap.format());\n m_audio_out->start();\n m_audio_out->adjustIntensity(getAttributeValue());\n }\n Function::preRun(timer);\n}\n\nvoid Audio::write(MasterTimer* timer, UniverseArray* universes)\n{\n Q_UNUSED(timer)\n Q_UNUSED(universes)\n}\n\nvoid Audio::postRun(MasterTimer* timer, UniverseArray* universes)\n{\n Q_UNUSED(timer)\n Q_UNUSED(universes)\n#ifdef QT_PHONON_LIB\n if (m_object != NULL)\n m_object->stop();\n#endif\n if (m_audio_out != NULL)\n {\n m_audio_out->stop();\n delete m_audio_out;\n m_audio_out = NULL;\n m_decoder->seek(0);\n }\n Function::postRun(timer, universes);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Baldur Karlsson\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\n#include \"amd_isa.h\"\n#include \"driver\/shaders\/dxbc\/dxbc_inspect.h\"\n#include \"official\/RGA\/Common\/AmdDxGsaCompile.h\"\n#include \"official\/RGA\/elf\/elf32.h\"\n#include \"amd_isa_devices.h\"\n\nstatic const char *driverDllErrorMessage = R\"(Error loading atidxx64.dll.\n\nCurrently atidxx64.dll from AMD's driver package is required for GCN disassembly and it cannot be\ndistributed with RenderDoc.\n\nTo see instructions on how to download and configure it on your system, go to:\nhttps:\/\/github.com\/baldurk\/renderdoc\/wiki\/GCN_ISA)\";\n\nnamespace GCNISA\n{\nstd::string LocatePlugin(const std::string &fileName);\n};\n\nstatic HMODULE GetAMDModule()\n{\n \/\/ first try in the plugin locations\n HMODULE module = LoadLibraryA(GCNISA::LocatePlugin(\"atidxx64.dll\").c_str());\n\n \/\/ if that failed then try checking for it just in the default search path\n if(module == NULL)\n module = LoadLibraryA(\"atidxx64.dll\");\n\n return module;\n}\n\nstd::string GCNISA::Disassemble(const DXBC::DXBCFile *dxbc, const std::string &target)\n{\n HMODULE mod = GetAMDModule();\n\n if(mod == NULL)\n return driverDllErrorMessage;\n\n \/\/ if DXBC is NULL we're testing support, so return empty string - indicating no error\n \/\/ initialising\n if(dxbc == NULL || target == \"\")\n return \"\";\n\n PfnAmdDxGsaCompileShader compileShader =\n (PfnAmdDxGsaCompileShader)GetProcAddress(mod, \"AmdDxGsaCompileShader\");\n PfnAmdDxGsaFreeCompiledShader freeShader =\n (PfnAmdDxGsaFreeCompiledShader)GetProcAddress(mod, \"AmdDxGsaFreeCompiledShader\");\n\n AmdDxGsaCompileShaderInput in = {};\n AmdDxGsaCompileShaderOutput out = {};\n\n AmdDxGsaCompileOption opts[1] = {};\n\n in.inputType = GsaInputDxAsmBin;\n in.numCompileOptions = 0;\n in.pCompileOptions = opts;\n\n for(const asic &a : asicInfo)\n {\n if(target == a.name)\n {\n in.chipFamily = a.chipFamily;\n in.chipRevision = a.chipRevision;\n break;\n }\n }\n\n bool amdil = false;\n if(target == \"AMDIL\")\n {\n in.chipFamily = asicInfo[0].chipFamily;\n in.chipRevision = asicInfo[0].chipRevision;\n amdil = true;\n }\n\n if(in.chipFamily == 0)\n return \"; Invalid ISA Target specified\";\n\n in.pShaderByteCode = dxbc->m_HexDump.data();\n in.byteCodeLength = dxbc->m_HexDump.size();\n\n out.size = sizeof(out);\n\n compileShader(&in, &out);\n\n const uint8_t *elf = (const uint8_t *)out.pShaderBinary;\n\n const Elf32_Ehdr *elfHeader = (const Elf32_Ehdr *)elf;\n\n std::string ret;\n\n \/\/ minimal code to extract data from ELF. We assume the ELF we got back is well-formed.\n if(IS_ELF(*elfHeader) && elfHeader->e_ident[EI_CLASS] == ELFCLASS32)\n {\n const Elf32_Shdr *strtab =\n (const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * elfHeader->e_shstrndx);\n\n const uint8_t *strtabData = elf + strtab->sh_offset;\n\n const AmdDxGsaCompileStats *stats = NULL;\n\n for(int section = 1; section < elfHeader->e_shnum; section++)\n {\n if(section == elfHeader->e_shstrndx)\n continue;\n\n const Elf32_Shdr *sectHeader =\n (const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * section);\n\n const char *name = (const char *)(strtabData + sectHeader->sh_name);\n\n const uint8_t *data = elf + sectHeader->sh_offset;\n\n if(!strcmp(name, \".stats\"))\n {\n stats = (const AmdDxGsaCompileStats *)data;\n }\n else if(amdil && !strcmp(name, \".amdil_disassembly\"))\n {\n ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);\n }\n else if(!amdil && !strcmp(name, \".disassembly\"))\n {\n ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);\n }\n }\n\n if(stats && !amdil)\n {\n std::string statStr = StringFormat::Fmt(\n R\"(; -------- Statistics ---------------------\n; SGPRs: %u out of %u used\n; VGPRs: %u out of %u used\n; LDS: %u out of %u bytes used\n; %u bytes scratch space used\n; Instructions: %u ALU, %u Control Flow, %u TFETCH\n\n)\",\n stats->numSgprsUsed, stats->availableSgprs, stats->numVgprsUsed, stats->availableVgprs,\n stats->usedLdsBytes, stats->availableLdsBytes, stats->usedScratchBytes, stats->numAluInst,\n stats->numControlFlowInst, stats->numTfetchInst);\n\n ret.insert(ret.begin(), statStr.begin(), statStr.end());\n }\n\n std::string header = StringFormat::Fmt(\"; Disassembly for %s\\n\\n\", target.c_str());\n\n ret.insert(ret.begin(), header.begin(), header.end());\n }\n else\n {\n ret = \"; Invalid ELF file generated\";\n }\n\n freeShader(out.pShaderBinary);\n\n return ret;\n}\n<commit_msg>Support 32-bit and 64-bit AMD driver DLLs for disassembly<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Baldur Karlsson\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\n#include \"amd_isa.h\"\n#include \"driver\/shaders\/dxbc\/dxbc_inspect.h\"\n#include \"official\/RGA\/Common\/AmdDxGsaCompile.h\"\n#include \"official\/RGA\/elf\/elf32.h\"\n#include \"amd_isa_devices.h\"\n\n#if ENABLED(RDOC_X64)\n#define DLL_NAME \"atidxx64.dll\"\n#else\n#define DLL_NAME \"atidxx32.dll\"\n#endif\n\nstatic const char *driverDllErrorMessage = R\"(Error loading atidxx64.dll.\n\nCurrently atidxx64.dll from AMD's driver package is required for GCN disassembly and it cannot be\ndistributed with RenderDoc.\n\nTo see instructions on how to download and configure it on your system, go to:\nhttps:\/\/github.com\/baldurk\/renderdoc\/wiki\/GCN_ISA)\";\n\nnamespace GCNISA\n{\nstd::string LocatePlugin(const std::string &fileName);\n};\n\nstatic HMODULE GetAMDModule()\n{\n \/\/ first try in the plugin locations\n HMODULE module = LoadLibraryA(GCNISA::LocatePlugin(DLL_NAME).c_str());\n\n \/\/ if that failed then try checking for it just in the default search path\n if(module == NULL)\n module = LoadLibraryA(DLL_NAME);\n\n return module;\n}\n\nstd::string GCNISA::Disassemble(const DXBC::DXBCFile *dxbc, const std::string &target)\n{\n HMODULE mod = GetAMDModule();\n\n if(mod == NULL)\n return \"; Error loading \" DLL_NAME R\"(.\n\n; Currently atidxx64.dll from AMD's driver package is required for GCN disassembly and it cannot be\n; distributed with RenderDoc.\n\n; To see instructions on how to download and configure it on your system, go to:\n; https:\/\/github.com\/baldurk\/renderdoc\/wiki\/GCN_ISA)\";\n\n \/\/ if DXBC is NULL we're testing support, so return empty string - indicating no error\n \/\/ initialising\n if(dxbc == NULL || target == \"\")\n return \"\";\n\n PfnAmdDxGsaCompileShader compileShader =\n (PfnAmdDxGsaCompileShader)GetProcAddress(mod, \"AmdDxGsaCompileShader\");\n PfnAmdDxGsaFreeCompiledShader freeShader =\n (PfnAmdDxGsaFreeCompiledShader)GetProcAddress(mod, \"AmdDxGsaFreeCompiledShader\");\n\n AmdDxGsaCompileShaderInput in = {};\n AmdDxGsaCompileShaderOutput out = {};\n\n AmdDxGsaCompileOption opts[1] = {};\n\n in.inputType = GsaInputDxAsmBin;\n in.numCompileOptions = 0;\n in.pCompileOptions = opts;\n\n for(const asic &a : asicInfo)\n {\n if(target == a.name)\n {\n in.chipFamily = a.chipFamily;\n in.chipRevision = a.chipRevision;\n break;\n }\n }\n\n bool amdil = false;\n if(target == \"AMDIL\")\n {\n in.chipFamily = asicInfo[0].chipFamily;\n in.chipRevision = asicInfo[0].chipRevision;\n amdil = true;\n }\n\n if(in.chipFamily == 0)\n return \"; Invalid ISA Target specified\";\n\n in.pShaderByteCode = dxbc->m_HexDump.data();\n in.byteCodeLength = dxbc->m_HexDump.size();\n\n out.size = sizeof(out);\n\n compileShader(&in, &out);\n\n const uint8_t *elf = (const uint8_t *)out.pShaderBinary;\n\n const Elf32_Ehdr *elfHeader = (const Elf32_Ehdr *)elf;\n\n std::string ret;\n\n \/\/ minimal code to extract data from ELF. We assume the ELF we got back is well-formed.\n if(IS_ELF(*elfHeader) && elfHeader->e_ident[EI_CLASS] == ELFCLASS32)\n {\n const Elf32_Shdr *strtab =\n (const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * elfHeader->e_shstrndx);\n\n const uint8_t *strtabData = elf + strtab->sh_offset;\n\n const AmdDxGsaCompileStats *stats = NULL;\n\n for(int section = 1; section < elfHeader->e_shnum; section++)\n {\n if(section == elfHeader->e_shstrndx)\n continue;\n\n const Elf32_Shdr *sectHeader =\n (const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * section);\n\n const char *name = (const char *)(strtabData + sectHeader->sh_name);\n\n const uint8_t *data = elf + sectHeader->sh_offset;\n\n if(!strcmp(name, \".stats\"))\n {\n stats = (const AmdDxGsaCompileStats *)data;\n }\n else if(amdil && !strcmp(name, \".amdil_disassembly\"))\n {\n ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);\n }\n else if(!amdil && !strcmp(name, \".disassembly\"))\n {\n ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);\n }\n }\n\n if(stats && !amdil)\n {\n std::string statStr = StringFormat::Fmt(\n R\"(; -------- Statistics ---------------------\n; SGPRs: %u out of %u used\n; VGPRs: %u out of %u used\n; LDS: %u out of %u bytes used\n; %u bytes scratch space used\n; Instructions: %u ALU, %u Control Flow, %u TFETCH\n\n)\",\n stats->numSgprsUsed, stats->availableSgprs, stats->numVgprsUsed, stats->availableVgprs,\n stats->usedLdsBytes, stats->availableLdsBytes, stats->usedScratchBytes, stats->numAluInst,\n stats->numControlFlowInst, stats->numTfetchInst);\n\n ret.insert(ret.begin(), statStr.begin(), statStr.end());\n }\n\n std::string header = StringFormat::Fmt(\"; Disassembly for %s\\n\\n\", target.c_str());\n\n ret.insert(ret.begin(), header.begin(), header.end());\n }\n else\n {\n ret = \"; Invalid ELF file generated\";\n }\n\n freeShader(out.pShaderBinary);\n\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2018 The Dash Core developers\n\/\/ Copyright (c) 2018-2019 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n#include \"hash.h\"\n#include \"main.h\" \/\/ For strMessageMagic\n#include \"messagesigner.h\"\n#include \"masternodeman.h\" \/\/ For GetPublicKey (of MN from its vin)\n#include \"tinyformat.h\"\n#include \"utilstrencodings.h\"\n\nbool CMessageSigner::GetKeysFromSecret(const std::string& strSecret, CKey& keyRet, CPubKey& pubkeyRet)\n{\n CBitcoinSecret vchSecret;\n\n if(!vchSecret.SetString(strSecret)) return false;\n\n keyRet = vchSecret.GetKey();\n pubkeyRet = keyRet.GetPubKey();\n\n return true;\n}\n\nuint256 CMessageSigner::GetMessageHash(const std::string& strMessage)\n{\n CHashWriter ss(SER_GETHASH, 0);\n ss << strMessageMagic;\n ss << strMessage;\n return ss.GetHash();\n}\n\nbool CMessageSigner::SignMessage(const std::string& strMessage, std::vector<unsigned char>& vchSigRet, const CKey& key)\n{\n return CHashSigner::SignHash(GetMessageHash(strMessage), key, vchSigRet);\n}\n\nbool CMessageSigner::VerifyMessage(const CPubKey& pubkey, const std::vector<unsigned char>& vchSig, const std::string& strMessage, std::string& strErrorRet)\n{\n return VerifyMessage(pubkey.GetID(), vchSig, strMessage, strErrorRet);\n}\n\nbool CMessageSigner::VerifyMessage(const CKeyID& keyID, const std::vector<unsigned char>& vchSig, const std::string& strMessage, std::string& strErrorRet)\n{\n return CHashSigner::VerifyHash(GetMessageHash(strMessage), keyID, vchSig, strErrorRet);\n}\n\nbool CHashSigner::SignHash(const uint256& hash, const CKey& key, std::vector<unsigned char>& vchSigRet)\n{\n return key.SignCompact(hash, vchSigRet);\n}\n\nbool CHashSigner::VerifyHash(const uint256& hash, const CPubKey& pubkey, const std::vector<unsigned char>& vchSig, std::string& strErrorRet)\n{\n return VerifyHash(hash, pubkey.GetID(), vchSig, strErrorRet);\n}\n\nbool CHashSigner::VerifyHash(const uint256& hash, const CKeyID& keyID, const std::vector<unsigned char>& vchSig, std::string& strErrorRet)\n{\n CPubKey pubkeyFromSig;\n if(!pubkeyFromSig.RecoverCompact(hash, vchSig)) {\n strErrorRet = \"Error recovering public key.\";\n return false;\n }\n\n if(pubkeyFromSig.GetID() != keyID) {\n strErrorRet = strprintf(\"Keys don't match: pubkey=%s, pubkeyFromSig=%s, hash=%s, vchSig=%s\",\n keyID.ToString(), pubkeyFromSig.GetID().ToString(), hash.ToString(),\n EncodeBase64(&vchSig[0], vchSig.size()));\n return false;\n }\n\n return true;\n}\n\n\/** CSignedMessage Class\n * Functions inherited by network signed-messages\n *\/\n\nbool CSignedMessage::Sign(const CKey& key, const CPubKey& pubKey, const bool fNewSigs)\n{\n std::string strError = \"\";\n\n if (fNewSigs) {\n nMessVersion = MessageVersion::MESS_VER_HASH;\n uint256 hash = GetSignatureHash();\n\n if(!CHashSigner::SignHash(hash, key, vchSig)) {\n return error(\"%s : SignHash() failed\", __func__);\n }\n\n if (!CHashSigner::VerifyHash(hash, pubKey, vchSig, strError)) {\n return error(\"%s : VerifyHash() failed, error: %s\", __func__, strError);\n }\n\n } else {\n nMessVersion = MessageVersion::MESS_VER_STRMESS;\n std::string strMessage = GetStrMessage();\n\n if (!CMessageSigner::SignMessage(strMessage, vchSig, key)) {\n return error(\"%s : SignMessage() failed\", __func__);\n }\n\n if (!CMessageSigner::VerifyMessage(pubKey, vchSig, strMessage, strError)) {\n return error(\"%s : VerifyMessage() failed, error: %s\\n\", __func__, strError);\n }\n }\n\n return true;\n}\n\nbool CSignedMessage::Sign(const std::string strSignKey, const bool fNewSigs)\n{\n CKey key;\n CPubKey pubkey;\n\n if (!CMessageSigner::GetKeysFromSecret(strSignKey, key, pubkey)) {\n return error(\"%s : Invalid strSignKey\", __func__);\n }\n\n return Sign(key, pubkey, fNewSigs);\n}\n\nbool CSignedMessage::CheckSignature(const CPubKey& pubKey) const\n{\n std::string strError = \"\";\n\n if (nMessVersion == MessageVersion::MESS_VER_HASH) {\n uint256 hash = GetSignatureHash();\n if(!CHashSigner::VerifyHash(hash, pubKey, vchSig, strError))\n return error(\"%s : VerifyHash failed: %s\", __func__, strError);\n\n } else {\n std::string strMessage = GetStrMessage();\n if(!CMessageSigner::VerifyMessage(pubKey, vchSig, strMessage, strError))\n return error(\"%s : VerifyMessage failed: %s\", __func__, strError);\n }\n\n return true;\n}\n\nbool CSignedMessage::CheckSignature(const bool fSignatureCheck) const\n{\n std::string strError = \"\";\n\n const CPubKey pubkey = GetPublicKey(strError);\n if (pubkey == CPubKey())\n return error(\"%s : ERROR: %s\", __func__, strError);\n\n return !fSignatureCheck || CheckSignature(pubkey);\n}\n\nconst CPubKey CSignedMessage::GetPublicKey(std::string& strErrorRet) const\n{\n const CTxIn vin = GetVin();\n CMasternode* pmn = mnodeman.Find(vin);\n if(pmn) {\n return pmn->pubKeyMasternode;\n }\n strErrorRet = strprintf(\"Unable to find masternode vin %s\", vin.prevout.hash.GetHex());\n return CPubKey();\n}\n\nstd::string CSignedMessage::GetSignatureBase64() const\n{\n return EncodeBase64(&vchSig[0], vchSig.size());\n}\n\nvoid CSignedMessage::swap(CSignedMessage& first, CSignedMessage& second) \/\/ nothrow\n{\n \/\/ enable ADL (not necessary in our case, but good practice)\n using std::swap;\n\n \/\/ by swapping the members of two classes,\n \/\/ the two classes are effectively swapped\n swap(first.vchSig, second.vchSig);\n swap(first.nMessVersion, second.nMessVersion);\n}\n\n<commit_msg>[Trivial] better log for CHashSigner::VerifyHash failures<commit_after>\/\/ Copyright (c) 2014-2018 The Dash Core developers\n\/\/ Copyright (c) 2018-2019 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n#include \"hash.h\"\n#include \"main.h\" \/\/ For strMessageMagic\n#include \"messagesigner.h\"\n#include \"masternodeman.h\" \/\/ For GetPublicKey (of MN from its vin)\n#include \"tinyformat.h\"\n#include \"utilstrencodings.h\"\n\nbool CMessageSigner::GetKeysFromSecret(const std::string& strSecret, CKey& keyRet, CPubKey& pubkeyRet)\n{\n CBitcoinSecret vchSecret;\n\n if(!vchSecret.SetString(strSecret)) return false;\n\n keyRet = vchSecret.GetKey();\n pubkeyRet = keyRet.GetPubKey();\n\n return true;\n}\n\nuint256 CMessageSigner::GetMessageHash(const std::string& strMessage)\n{\n CHashWriter ss(SER_GETHASH, 0);\n ss << strMessageMagic;\n ss << strMessage;\n return ss.GetHash();\n}\n\nbool CMessageSigner::SignMessage(const std::string& strMessage, std::vector<unsigned char>& vchSigRet, const CKey& key)\n{\n return CHashSigner::SignHash(GetMessageHash(strMessage), key, vchSigRet);\n}\n\nbool CMessageSigner::VerifyMessage(const CPubKey& pubkey, const std::vector<unsigned char>& vchSig, const std::string& strMessage, std::string& strErrorRet)\n{\n return VerifyMessage(pubkey.GetID(), vchSig, strMessage, strErrorRet);\n}\n\nbool CMessageSigner::VerifyMessage(const CKeyID& keyID, const std::vector<unsigned char>& vchSig, const std::string& strMessage, std::string& strErrorRet)\n{\n return CHashSigner::VerifyHash(GetMessageHash(strMessage), keyID, vchSig, strErrorRet);\n}\n\nbool CHashSigner::SignHash(const uint256& hash, const CKey& key, std::vector<unsigned char>& vchSigRet)\n{\n return key.SignCompact(hash, vchSigRet);\n}\n\nbool CHashSigner::VerifyHash(const uint256& hash, const CPubKey& pubkey, const std::vector<unsigned char>& vchSig, std::string& strErrorRet)\n{\n return VerifyHash(hash, pubkey.GetID(), vchSig, strErrorRet);\n}\n\nbool CHashSigner::VerifyHash(const uint256& hash, const CKeyID& keyID, const std::vector<unsigned char>& vchSig, std::string& strErrorRet)\n{\n CPubKey pubkeyFromSig;\n if(!pubkeyFromSig.RecoverCompact(hash, vchSig)) {\n strErrorRet = \"Error recovering public key.\";\n return false;\n }\n\n if(pubkeyFromSig.GetID() != keyID) {\n strErrorRet = strprintf(\"Keys don't match: pubkey=%s, pubkeyFromSig=%s, hash=%s, vchSig=%s\",\n CBitcoinAddress(keyID).ToString(), CBitcoinAddress(pubkeyFromSig.GetID()).ToString(),\n hash.ToString(), EncodeBase64(&vchSig[0], vchSig.size()));\n return false;\n }\n\n return true;\n}\n\n\/** CSignedMessage Class\n * Functions inherited by network signed-messages\n *\/\n\nbool CSignedMessage::Sign(const CKey& key, const CPubKey& pubKey, const bool fNewSigs)\n{\n std::string strError = \"\";\n\n if (fNewSigs) {\n nMessVersion = MessageVersion::MESS_VER_HASH;\n uint256 hash = GetSignatureHash();\n\n if(!CHashSigner::SignHash(hash, key, vchSig)) {\n return error(\"%s : SignHash() failed\", __func__);\n }\n\n if (!CHashSigner::VerifyHash(hash, pubKey, vchSig, strError)) {\n return error(\"%s : VerifyHash() failed, error: %s\", __func__, strError);\n }\n\n } else {\n nMessVersion = MessageVersion::MESS_VER_STRMESS;\n std::string strMessage = GetStrMessage();\n\n if (!CMessageSigner::SignMessage(strMessage, vchSig, key)) {\n return error(\"%s : SignMessage() failed\", __func__);\n }\n\n if (!CMessageSigner::VerifyMessage(pubKey, vchSig, strMessage, strError)) {\n return error(\"%s : VerifyMessage() failed, error: %s\\n\", __func__, strError);\n }\n }\n\n return true;\n}\n\nbool CSignedMessage::Sign(const std::string strSignKey, const bool fNewSigs)\n{\n CKey key;\n CPubKey pubkey;\n\n if (!CMessageSigner::GetKeysFromSecret(strSignKey, key, pubkey)) {\n return error(\"%s : Invalid strSignKey\", __func__);\n }\n\n return Sign(key, pubkey, fNewSigs);\n}\n\nbool CSignedMessage::CheckSignature(const CPubKey& pubKey) const\n{\n std::string strError = \"\";\n\n if (nMessVersion == MessageVersion::MESS_VER_HASH) {\n uint256 hash = GetSignatureHash();\n if(!CHashSigner::VerifyHash(hash, pubKey, vchSig, strError))\n return error(\"%s : VerifyHash failed: %s\", __func__, strError);\n\n } else {\n std::string strMessage = GetStrMessage();\n if(!CMessageSigner::VerifyMessage(pubKey, vchSig, strMessage, strError))\n return error(\"%s : VerifyMessage failed: %s\", __func__, strError);\n }\n\n return true;\n}\n\nbool CSignedMessage::CheckSignature(const bool fSignatureCheck) const\n{\n std::string strError = \"\";\n\n const CPubKey pubkey = GetPublicKey(strError);\n if (pubkey == CPubKey())\n return error(\"%s : ERROR: %s\", __func__, strError);\n\n return !fSignatureCheck || CheckSignature(pubkey);\n}\n\nconst CPubKey CSignedMessage::GetPublicKey(std::string& strErrorRet) const\n{\n const CTxIn vin = GetVin();\n CMasternode* pmn = mnodeman.Find(vin);\n if(pmn) {\n return pmn->pubKeyMasternode;\n }\n strErrorRet = strprintf(\"Unable to find masternode vin %s\", vin.prevout.hash.GetHex());\n return CPubKey();\n}\n\nstd::string CSignedMessage::GetSignatureBase64() const\n{\n return EncodeBase64(&vchSig[0], vchSig.size());\n}\n\nvoid CSignedMessage::swap(CSignedMessage& first, CSignedMessage& second) \/\/ nothrow\n{\n \/\/ enable ADL (not necessary in our case, but good practice)\n using std::swap;\n\n \/\/ by swapping the members of two classes,\n \/\/ the two classes are effectively swapped\n swap(first.vchSig, second.vchSig);\n swap(first.nMessVersion, second.nMessVersion);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"sandbox\/win\/src\/process_mitigations.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"sandbox\/win\/src\/nt_internals.h\"\n#include \"sandbox\/win\/src\/sandbox_utils.h\"\n#include \"sandbox\/win\/src\/win_utils.h\"\n\nnamespace {\n\n\/\/ Functions for enabling policies.\ntypedef BOOL (WINAPI *SetProcessDEPPolicyFunction)(DWORD dwFlags);\n\ntypedef BOOL (WINAPI *SetProcessMitigationPolicyFunction)(\n PROCESS_MITIGATION_POLICY mitigation_policy,\n PVOID buffer,\n SIZE_T length);\n\ntypedef BOOL (WINAPI *SetDefaultDllDirectoriesFunction)(\n DWORD DirectoryFlags);\n\n} \/\/ namespace\n\nnamespace sandbox {\n\nbool ApplyProcessMitigationsToCurrentProcess(MitigationFlags flags) {\n if (!CanSetProcessMitigationsPostStartup(flags))\n return false;\n\n \/\/ We can't apply anything before Win XP, so just return cleanly.\n if (!IsXPSP2OrLater())\n return true;\n\n base::win::Version version = base::win::GetVersion();\n HMODULE module = ::GetModuleHandleA(\"kernel32.dll\");\n\n if (version >= base::win::VERSION_VISTA &&\n (flags & MITIGATION_DLL_SEARCH_ORDER)) {\n SetDefaultDllDirectoriesFunction set_default_dll_directories =\n reinterpret_cast<SetDefaultDllDirectoriesFunction>(\n ::GetProcAddress(module, \"SetDefaultDllDirectories\"));\n\n \/\/ Check for SetDefaultDllDirectories since it requires KB2533623.\n if (set_default_dll_directories) {\n if (!set_default_dll_directories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) {\n CHECK_EQ(ERROR_ACCESS_DENIED, static_cast<long>(::GetLastError()));\n }\n }\n }\n\n \/\/ Set the heap to terminate on corruption\n if (version >= base::win::VERSION_VISTA &&\n (flags & MITIGATION_HEAP_TERMINATE)) {\n if (!::HeapSetInformation(NULL, HeapEnableTerminationOnCorruption,\n NULL, 0)) {\n CHECK_EQ(ERROR_ACCESS_DENIED, static_cast<long>(::GetLastError()));\n }\n }\n\n#if !defined(_WIN64) \/\/ DEP is always enabled on 64-bit.\n if (flags & MITIGATION_DEP) {\n DWORD dep_flags = PROCESS_DEP_ENABLE;\n \/\/ DEP support is quirky on XP, so don't force a failure in that case.\n const bool return_on_fail = version >= base::win::VERSION_VISTA;\n\n if (flags & MITIGATION_DEP_NO_ATL_THUNK)\n dep_flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;\n\n SetProcessDEPPolicyFunction set_process_dep_policy =\n reinterpret_cast<SetProcessDEPPolicyFunction>(\n ::GetProcAddress(module, \"SetProcessDEPPolicy\"));\n if (set_process_dep_policy) {\n if (!set_process_dep_policy(dep_flags) && return_on_fail) {\n CHECK_EQ(ERROR_ACCESS_DENIED, static_cast<long>(::GetLastError()));\n }\n } else {\n \/\/ We're on XP sp2, so use the less standard approach.\n \/\/ For reference: http:\/\/www.uninformed.org\/?v=2&a=4\n const int MEM_EXECUTE_OPTION_ENABLE = 1;\n const int MEM_EXECUTE_OPTION_DISABLE = 2;\n const int MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION = 4;\n const int MEM_EXECUTE_OPTION_PERMANENT = 8;\n\n NtSetInformationProcessFunction set_information_process = NULL;\n ResolveNTFunctionPtr(\"NtSetInformationProcess\",\n &set_information_process);\n if (!set_information_process)\n return false;\n ULONG dep = MEM_EXECUTE_OPTION_DISABLE | MEM_EXECUTE_OPTION_PERMANENT;\n if (!(dep_flags & PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION))\n dep |= MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION;\n if (!SUCCEEDED(set_information_process(GetCurrentProcess(),\n ProcessExecuteFlags,\n &dep, sizeof(dep))) &&\n return_on_fail) {\n CHECK_EQ(ERROR_ACCESS_DENIED, static_cast<long>(::GetLastError()));\n }\n }\n }\n#endif\n\n \/\/ This is all we can do in Win7 and below.\n if (version < base::win::VERSION_WIN8)\n return true;\n\n SetProcessMitigationPolicyFunction set_process_mitigation_policy =\n reinterpret_cast<SetProcessMitigationPolicyFunction>(\n ::GetProcAddress(module, \"SetProcessMitigationPolicy\"));\n if (!set_process_mitigation_policy)\n return false;\n\n \/\/ Enable ASLR policies.\n if (flags & MITIGATION_RELOCATE_IMAGE) {\n PROCESS_MITIGATION_ASLR_POLICY policy = { 0 };\n policy.EnableForceRelocateImages = true;\n policy.DisallowStrippedImages = (flags &\n MITIGATION_RELOCATE_IMAGE_REQUIRED) ==\n MITIGATION_RELOCATE_IMAGE_REQUIRED;\n\n if (!set_process_mitigation_policy(ProcessASLRPolicy, &policy,\n sizeof(policy))) {\n CHECK_EQ(ERROR_ACCESS_DENIED, static_cast<long>(::GetLastError()));\n }\n }\n\n \/\/ Enable strict handle policies.\n if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {\n PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY policy = { 0 };\n policy.HandleExceptionsPermanentlyEnabled =\n policy.RaiseExceptionOnInvalidHandleReference = true;\n\n if (!set_process_mitigation_policy(ProcessStrictHandleCheckPolicy, &policy,\n sizeof(policy))) {\n CHECK_EQ(ERROR_ACCESS_DENIED, static_cast<long>(::GetLastError()));\n }\n }\n\n \/\/ Enable system call policies.\n if (flags & MITIGATION_WIN32K_DISABLE) {\n PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy = { 0 };\n policy.DisallowWin32kSystemCalls = true;\n\n if (!set_process_mitigation_policy(ProcessSystemCallDisablePolicy, &policy,\n sizeof(policy))) {\n CHECK_EQ(ERROR_ACCESS_DENIED, static_cast<long>(::GetLastError()));\n }\n }\n\n \/\/ Enable system call policies.\n if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {\n PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY policy = { 0 };\n policy.DisableExtensionPoints = true;\n\n if (!set_process_mitigation_policy(ProcessExtensionPointDisablePolicy,\n &policy, sizeof(policy))) {\n CHECK_EQ(ERROR_ACCESS_DENIED, static_cast<long>(::GetLastError()));\n }\n }\n\n return true;\n}\n\nvoid ConvertProcessMitigationsToPolicy(MitigationFlags flags,\n DWORD64* policy_flags, size_t* size) {\n base::win::Version version = base::win::GetVersion();\n\n *policy_flags = 0;\n#if defined(_WIN64)\n *size = sizeof(*policy_flags);\n#elif defined(_M_IX86)\n \/\/ A 64-bit flags attribute is illegal on 32-bit Win 7 and below.\n if (version < base::win::VERSION_WIN8)\n *size = sizeof(DWORD);\n else\n *size = sizeof(*policy_flags);\n#else\n#error This platform is not supported.\n#endif\n\n \/\/ Nothing for Win XP or Vista.\n if (version <= base::win::VERSION_VISTA)\n return;\n\n if (flags & MITIGATION_DEP) {\n *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE;\n if (!(flags & MITIGATION_DEP_NO_ATL_THUNK))\n *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE;\n }\n\n if (flags & MITIGATION_SEHOP)\n *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE;\n\n \/\/ Win 7\n if (version < base::win::VERSION_WIN8)\n return;\n\n if (flags & MITIGATION_RELOCATE_IMAGE) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON;\n if (flags & MITIGATION_RELOCATE_IMAGE_REQUIRED) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS;\n }\n }\n\n if (flags & MITIGATION_HEAP_TERMINATE) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_BOTTOM_UP_ASLR) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_HIGH_ENTROPY_ASLR) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_WIN32K_DISABLE) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON;\n }\n}\n\nMitigationFlags FilterPostStartupProcessMitigations(MitigationFlags flags) {\n \/\/ Anything prior to XP SP2.\n if (!IsXPSP2OrLater())\n return 0;\n\n base::win::Version version = base::win::GetVersion();\n\n \/\/ Windows XP SP2+.\n if (version < base::win::VERSION_VISTA) {\n return flags & (MITIGATION_DEP |\n MITIGATION_DEP_NO_ATL_THUNK);\n\n \/\/ Windows Vista\n if (version < base::win::VERSION_WIN7) {\n return flags & (MITIGATION_DEP |\n MITIGATION_DEP_NO_ATL_THUNK |\n MITIGATION_BOTTOM_UP_ASLR |\n MITIGATION_DLL_SEARCH_ORDER |\n MITIGATION_HEAP_TERMINATE);\n }\n\n \/\/ Windows 7 and Vista.\n } else if (version < base::win::VERSION_WIN8) {\n return flags & (MITIGATION_BOTTOM_UP_ASLR |\n MITIGATION_DLL_SEARCH_ORDER |\n MITIGATION_HEAP_TERMINATE);\n }\n\n \/\/ Windows 8 and above.\n return flags & (MITIGATION_BOTTOM_UP_ASLR |\n MITIGATION_DLL_SEARCH_ORDER);\n}\n\nbool ApplyProcessMitigationsToSuspendedProcess(HANDLE process,\n MitigationFlags flags) {\n\/\/ This is a hack to fake a weak bottom-up ASLR on 32-bit Windows.\n#if !defined(_WIN64)\n if (flags & MITIGATION_BOTTOM_UP_ASLR) {\n unsigned int limit;\n rand_s(&limit);\n char* ptr = 0;\n const size_t kMask64k = 0xFFFF;\n \/\/ Random range (512k-16.5mb) in 64k steps.\n const char* end = ptr + ((((limit % 16384) + 512) * 1024) & ~kMask64k);\n while (ptr < end) {\n MEMORY_BASIC_INFORMATION memory_info;\n if (!::VirtualQueryEx(process, ptr, &memory_info, sizeof(memory_info)))\n break;\n size_t size = std::min((memory_info.RegionSize + kMask64k) & ~kMask64k,\n static_cast<SIZE_T>(end - ptr));\n if (ptr && memory_info.State == MEM_FREE)\n ::VirtualAllocEx(process, ptr, size, MEM_RESERVE, PAGE_NOACCESS);\n ptr += size;\n }\n }\n#endif\n\n return true;\n}\n\nbool CanSetProcessMitigationsPostStartup(MitigationFlags flags) {\n \/\/ All of these mitigations can be enabled after startup.\n return !(flags & ~(MITIGATION_HEAP_TERMINATE |\n MITIGATION_DEP |\n MITIGATION_DEP_NO_ATL_THUNK |\n MITIGATION_RELOCATE_IMAGE |\n MITIGATION_RELOCATE_IMAGE_REQUIRED |\n MITIGATION_BOTTOM_UP_ASLR |\n MITIGATION_STRICT_HANDLE_CHECKS |\n MITIGATION_WIN32K_DISABLE |\n MITIGATION_EXTENSION_DLL_DISABLE |\n MITIGATION_DLL_SEARCH_ORDER));\n}\n\nbool CanSetProcessMitigationsPreStartup(MitigationFlags flags) {\n \/\/ These mitigations cannot be enabled prior to startup.\n return !(flags & (MITIGATION_STRICT_HANDLE_CHECKS |\n MITIGATION_WIN32K_DISABLE |\n MITIGATION_DLL_SEARCH_ORDER));\n}\n\n} \/\/ namespace sandbox\n\n<commit_msg>Revert 160252 - Make mitigation failures CHECK<commit_after>\/\/ 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 \"sandbox\/win\/src\/process_mitigations.h\"\n\n#include \"base\/win\/windows_version.h\"\n#include \"sandbox\/win\/src\/nt_internals.h\"\n#include \"sandbox\/win\/src\/sandbox_utils.h\"\n#include \"sandbox\/win\/src\/win_utils.h\"\n\nnamespace {\n\n\/\/ Functions for enabling policies.\ntypedef BOOL (WINAPI *SetProcessDEPPolicyFunction)(DWORD dwFlags);\n\ntypedef BOOL (WINAPI *SetProcessMitigationPolicyFunction)(\n PROCESS_MITIGATION_POLICY mitigation_policy,\n PVOID buffer,\n SIZE_T length);\n\ntypedef BOOL (WINAPI *SetDefaultDllDirectoriesFunction)(\n DWORD DirectoryFlags);\n\n} \/\/ namespace\n\nnamespace sandbox {\n\nbool ApplyProcessMitigationsToCurrentProcess(MitigationFlags flags) {\n if (!CanSetProcessMitigationsPostStartup(flags))\n return false;\n\n \/\/ We can't apply anything before Win XP, so just return cleanly.\n if (!IsXPSP2OrLater())\n return true;\n\n base::win::Version version = base::win::GetVersion();\n HMODULE module = ::GetModuleHandleA(\"kernel32.dll\");\n\n if (version >= base::win::VERSION_VISTA &&\n (flags & MITIGATION_DLL_SEARCH_ORDER)) {\n SetDefaultDllDirectoriesFunction set_default_dll_directories =\n reinterpret_cast<SetDefaultDllDirectoriesFunction>(\n ::GetProcAddress(module, \"SetDefaultDllDirectories\"));\n\n \/\/ Check for SetDefaultDllDirectories since it requires KB2533623.\n if (set_default_dll_directories) {\n if (!set_default_dll_directories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS) &&\n ERROR_ACCESS_DENIED != ::GetLastError()) {\n return false;\n }\n }\n }\n\n \/\/ Set the heap to terminate on corruption\n if (version >= base::win::VERSION_VISTA &&\n (flags & MITIGATION_HEAP_TERMINATE)) {\n if (!::HeapSetInformation(NULL, HeapEnableTerminationOnCorruption,\n NULL, 0) &&\n ERROR_ACCESS_DENIED != ::GetLastError()) {\n return false;\n }\n }\n\n#if !defined(_WIN64) \/\/ DEP is always enabled on 64-bit.\n if (flags & MITIGATION_DEP) {\n DWORD dep_flags = PROCESS_DEP_ENABLE;\n \/\/ DEP support is quirky on XP, so don't force a failure in that case.\n const bool return_on_fail = version >= base::win::VERSION_VISTA;\n\n if (flags & MITIGATION_DEP_NO_ATL_THUNK)\n dep_flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;\n\n SetProcessDEPPolicyFunction set_process_dep_policy =\n reinterpret_cast<SetProcessDEPPolicyFunction>(\n ::GetProcAddress(module, \"SetProcessDEPPolicy\"));\n if (set_process_dep_policy) {\n if (!set_process_dep_policy(dep_flags) &&\n ERROR_ACCESS_DENIED != ::GetLastError() && return_on_fail) {\n return false;\n }\n } else {\n \/\/ We're on XP sp2, so use the less standard approach.\n \/\/ For reference: http:\/\/www.uninformed.org\/?v=2&a=4\n const int MEM_EXECUTE_OPTION_ENABLE = 1;\n const int MEM_EXECUTE_OPTION_DISABLE = 2;\n const int MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION = 4;\n const int MEM_EXECUTE_OPTION_PERMANENT = 8;\n\n NtSetInformationProcessFunction set_information_process = NULL;\n ResolveNTFunctionPtr(\"NtSetInformationProcess\",\n &set_information_process);\n if (!set_information_process)\n return false;\n ULONG dep = MEM_EXECUTE_OPTION_DISABLE | MEM_EXECUTE_OPTION_PERMANENT;\n if (!(dep_flags & PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION))\n dep |= MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION;\n if (!SUCCEEDED(set_information_process(GetCurrentProcess(),\n ProcessExecuteFlags,\n &dep, sizeof(dep))) &&\n ERROR_ACCESS_DENIED != ::GetLastError() && return_on_fail) {\n return false;\n }\n }\n }\n#endif\n\n \/\/ This is all we can do in Win7 and below.\n if (version < base::win::VERSION_WIN8)\n return true;\n\n SetProcessMitigationPolicyFunction set_process_mitigation_policy =\n reinterpret_cast<SetProcessMitigationPolicyFunction>(\n ::GetProcAddress(module, \"SetProcessMitigationPolicy\"));\n if (!set_process_mitigation_policy)\n return false;\n\n \/\/ Enable ASLR policies.\n if (flags & MITIGATION_RELOCATE_IMAGE) {\n PROCESS_MITIGATION_ASLR_POLICY policy = { 0 };\n policy.EnableForceRelocateImages = true;\n policy.DisallowStrippedImages = (flags &\n MITIGATION_RELOCATE_IMAGE_REQUIRED) ==\n MITIGATION_RELOCATE_IMAGE_REQUIRED;\n\n if (!set_process_mitigation_policy(ProcessASLRPolicy, &policy,\n sizeof(policy)) &&\n ERROR_ACCESS_DENIED != ::GetLastError()) {\n return false;\n }\n }\n\n \/\/ Enable strict handle policies.\n if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {\n PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY policy = { 0 };\n policy.HandleExceptionsPermanentlyEnabled =\n policy.RaiseExceptionOnInvalidHandleReference = true;\n\n if (!set_process_mitigation_policy(ProcessStrictHandleCheckPolicy, &policy,\n sizeof(policy)) &&\n ERROR_ACCESS_DENIED != ::GetLastError()) {\n return false;\n }\n }\n\n \/\/ Enable system call policies.\n if (flags & MITIGATION_WIN32K_DISABLE) {\n PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy = { 0 };\n policy.DisallowWin32kSystemCalls = true;\n\n if (!set_process_mitigation_policy(ProcessSystemCallDisablePolicy, &policy,\n sizeof(policy)) &&\n ERROR_ACCESS_DENIED != ::GetLastError()) {\n return false;\n }\n }\n\n \/\/ Enable system call policies.\n if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {\n PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY policy = { 0 };\n policy.DisableExtensionPoints = true;\n\n if (!set_process_mitigation_policy(ProcessExtensionPointDisablePolicy,\n &policy, sizeof(policy)) &&\n ERROR_ACCESS_DENIED != ::GetLastError()) {\n return false;\n }\n }\n\n return true;\n}\n\nvoid ConvertProcessMitigationsToPolicy(MitigationFlags flags,\n DWORD64* policy_flags, size_t* size) {\n base::win::Version version = base::win::GetVersion();\n\n *policy_flags = 0;\n#if defined(_WIN64)\n *size = sizeof(*policy_flags);\n#elif defined(_M_IX86)\n \/\/ A 64-bit flags attribute is illegal on 32-bit Win 7 and below.\n if (version < base::win::VERSION_WIN8)\n *size = sizeof(DWORD);\n else\n *size = sizeof(*policy_flags);\n#else\n#error This platform is not supported.\n#endif\n\n \/\/ Nothing for Win XP or Vista.\n if (version <= base::win::VERSION_VISTA)\n return;\n\n if (flags & MITIGATION_DEP) {\n *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE;\n if (!(flags & MITIGATION_DEP_NO_ATL_THUNK))\n *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE;\n }\n\n if (flags & MITIGATION_SEHOP)\n *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE;\n\n \/\/ Win 7\n if (version < base::win::VERSION_WIN8)\n return;\n\n if (flags & MITIGATION_RELOCATE_IMAGE) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON;\n if (flags & MITIGATION_RELOCATE_IMAGE_REQUIRED) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS;\n }\n }\n\n if (flags & MITIGATION_HEAP_TERMINATE) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_BOTTOM_UP_ASLR) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_HIGH_ENTROPY_ASLR) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_WIN32K_DISABLE) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON;\n }\n\n if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {\n *policy_flags |=\n PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON;\n }\n}\n\nMitigationFlags FilterPostStartupProcessMitigations(MitigationFlags flags) {\n \/\/ Anything prior to XP SP2.\n if (!IsXPSP2OrLater())\n return 0;\n\n base::win::Version version = base::win::GetVersion();\n\n \/\/ Windows XP SP2+.\n if (version < base::win::VERSION_VISTA) {\n return flags & (MITIGATION_DEP |\n MITIGATION_DEP_NO_ATL_THUNK);\n\n \/\/ Windows Vista\n if (version < base::win::VERSION_WIN7) {\n return flags & (MITIGATION_DEP |\n MITIGATION_DEP_NO_ATL_THUNK |\n MITIGATION_BOTTOM_UP_ASLR |\n MITIGATION_DLL_SEARCH_ORDER |\n MITIGATION_HEAP_TERMINATE);\n }\n\n \/\/ Windows 7 and Vista.\n } else if (version < base::win::VERSION_WIN8) {\n return flags & (MITIGATION_BOTTOM_UP_ASLR |\n MITIGATION_DLL_SEARCH_ORDER |\n MITIGATION_HEAP_TERMINATE);\n }\n\n \/\/ Windows 8 and above.\n return flags & (MITIGATION_BOTTOM_UP_ASLR |\n MITIGATION_DLL_SEARCH_ORDER);\n}\n\nbool ApplyProcessMitigationsToSuspendedProcess(HANDLE process,\n MitigationFlags flags) {\n\/\/ This is a hack to fake a weak bottom-up ASLR on 32-bit Windows.\n#if !defined(_WIN64)\n if (flags & MITIGATION_BOTTOM_UP_ASLR) {\n unsigned int limit;\n rand_s(&limit);\n char* ptr = 0;\n const size_t kMask64k = 0xFFFF;\n \/\/ Random range (512k-16.5mb) in 64k steps.\n const char* end = ptr + ((((limit % 16384) + 512) * 1024) & ~kMask64k);\n while (ptr < end) {\n MEMORY_BASIC_INFORMATION memory_info;\n if (!::VirtualQueryEx(process, ptr, &memory_info, sizeof(memory_info)))\n break;\n size_t size = std::min((memory_info.RegionSize + kMask64k) & ~kMask64k,\n static_cast<SIZE_T>(end - ptr));\n if (ptr && memory_info.State == MEM_FREE)\n ::VirtualAllocEx(process, ptr, size, MEM_RESERVE, PAGE_NOACCESS);\n ptr += size;\n }\n }\n#endif\n\n return true;\n}\n\nbool CanSetProcessMitigationsPostStartup(MitigationFlags flags) {\n \/\/ All of these mitigations can be enabled after startup.\n return !(flags & ~(MITIGATION_HEAP_TERMINATE |\n MITIGATION_DEP |\n MITIGATION_DEP_NO_ATL_THUNK |\n MITIGATION_RELOCATE_IMAGE |\n MITIGATION_RELOCATE_IMAGE_REQUIRED |\n MITIGATION_BOTTOM_UP_ASLR |\n MITIGATION_STRICT_HANDLE_CHECKS |\n MITIGATION_WIN32K_DISABLE |\n MITIGATION_EXTENSION_DLL_DISABLE |\n MITIGATION_DLL_SEARCH_ORDER));\n}\n\nbool CanSetProcessMitigationsPreStartup(MitigationFlags flags) {\n \/\/ These mitigations cannot be enabled prior to startup.\n return !(flags & (MITIGATION_STRICT_HANDLE_CHECKS |\n MITIGATION_WIN32K_DISABLE |\n MITIGATION_DLL_SEARCH_ORDER));\n}\n\n} \/\/ namespace sandbox\n\n<|endoftext|>"} {"text":"<commit_before>\/* Lantern - A path tracer\n*\n* Lantern is the legal property of Adrian Astley\n* Copyright Adrian Astley 2015\n*\/\n\n#include <GLFW\/glfw3.h>\n\n#include <cstdio>\n#include <exception>\n\n\nstatic void error_callback(int error, const char *description) {\n\tprintf(\"Error %d: %s\\n\", error, description);\n}\n\n\nint main(int argc, const char *argv[]) {\n\t\/\/ Setup window\n\tglfwSetErrorCallback(error_callback);\n\tif (!glfwInit()) {\n\t\tglfwTerminate();\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tGLFWwindow* window = glfwCreateWindow(1280, 720, \"Lantern\", NULL, NULL);\n\tglfwMakeContextCurrent(window);\n\n\n\tglfwSwapInterval(1);\n\twhile (!glfwWindowShouldClose(window)) {\n\t\tfloat ratio;\n\t\tint width, height;\n\n\t\tglfwGetFramebufferSize(window, &width, &height);\n\t\tratio = width \/ (float)height;\n\n\t\tglViewport(0, 0, width, height);\n\t\tglClear(GL_COLOR_BUFFER_BIT);\n\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglLoadIdentity();\n\t\tglOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);\n\t\tglMatrixMode(GL_MODELVIEW);\n\n\t\tglLoadIdentity();\n\t\tglRotatef((float)glfwGetTime() * 50.f, 0.f, 0.f, 1.f);\n\n\t\tglBegin(GL_TRIANGLES);\n\t\tglColor3f(1.f, 0.f, 0.f);\n\t\tglVertex3f(-0.6f, -0.4f, 0.f);\n\t\tglColor3f(0.f, 1.f, 0.f);\n\t\tglVertex3f(0.6f, -0.4f, 0.f);\n\t\tglColor3f(0.f, 0.f, 1.f);\n\t\tglVertex3f(0.f, 0.6f, 0.f);\n\t\tglEnd();\n\n\t\tglfwSwapBuffers(window);\n\t\tglfwPollEvents();\n\t}\n\n\n\tglfwDestroyWindow(window);\n\n\t\/\/ Cleanup\n\tglfwTerminate();\n}\n<commit_msg>Convert main to use Visualizer and Renderer<commit_after>\/* Lantern - A path tracer\n*\n* Lantern is the legal property of Adrian Astley\n* Copyright Adrian Astley 2015 - 2016\n*\/\n\n#include \"common\/atomic_frame_buffer.h\"\n\n#include \"visualizer\/visualizer.h\"\n#include \"renderer\/renderer.h\"\n\n#include <xmmintrin.h>\n#include <pmmintrin.h>\n\n#include <thread>\n\n\nvoid StartRendererWrapper(Lantern::Renderer *renderer) {\n\trenderer->Start();\n}\n\n\nint main(int argc, const char *argv[]) {\n\t_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);\n\t_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);\n\n\tLantern::AtomicFrameBuffer frameBuffer(1280, 720);\n\t\n\tLantern::Renderer renderer(&frameBuffer);\n\tstd::thread renderThread(StartRendererWrapper, &renderer);\n\n\tLantern::Visualizer visualizer(&frameBuffer);\n\tvisualizer.Run();\n\n\trenderThread.join();\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ QtMWidgets include.\r\n#include \"navigationbar.hpp\"\r\n#include \"navigationbutton.hpp\"\r\n#include \"textlabel.hpp\"\r\n#include \"fingergeometry.hpp\"\r\n\r\n\/\/ Qt include.\r\n#include <QStackedWidget>\r\n#include <QVector>\r\n#include <QMap>\r\n#include <QSharedPointer>\r\n#include <QGridLayout>\r\n#include <QVBoxLayout>\r\n#include <QResizeEvent>\r\n#include <QStack>\r\n#include <QHideEvent>\r\n\r\n\r\nnamespace QtMWidgets {\r\n\r\n\/\/\r\n\/\/ NavigationItem\r\n\/\/\r\n\r\nclass NavigationItem {\r\npublic:\r\n\r\n\tNavigationItem()\r\n\t\t:\tindex( -1 )\r\n\t\t,\tparent( 0 )\r\n\t{\r\n\t}\r\n\r\n\tNavigationItem( const NavigationItem & other )\r\n\t\t:\ttitle( other.title )\r\n\t\t,\tindex( other.index )\r\n\t\t,\tchildren( other.children )\r\n\t\t,\tparent( other.parent )\r\n\t{\r\n\t}\r\n\r\n\tNavigationItem & operator = ( const NavigationItem & other )\r\n\t{\r\n\t\tif( this != &other )\r\n\t\t{\r\n\t\t\ttitle = other.title;\r\n\t\t\tindex = other.index;\r\n\t\t\tchildren = other.children;\r\n\t\t\tparent = other.parent;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tQString title;\r\n\tint index;\r\n\tQVector< QSharedPointer< NavigationItem > > children;\r\n\tQVector< int > childrenIndexes;\r\n\tNavigationItem * parent;\r\n}; \/\/ class NavigationItem\r\n\r\n\r\n\/\/\r\n\/\/ NavigationBarPrivate\r\n\/\/\r\n\r\nclass NavigationBarPrivate {\r\npublic:\r\n\tNavigationBarPrivate( NavigationBar * parent )\r\n\t\t:\tq( parent )\r\n\t\t,\tstack( 0 )\r\n\t\t,\tleft( 0 )\r\n\t\t,\tright( 0 )\r\n\t\t,\ttitle( 0 )\r\n\t\t,\tgrid( 0 )\r\n\t{\r\n\t}\r\n\r\n\tvoid init();\r\n\tvoid removeWidget( int index );\r\n\r\n\tNavigationBar * q;\r\n\tQStackedWidget * stack;\r\n\tQList< QSharedPointer< NavigationItem > > rootItems;\r\n\tQMap< int, QSharedPointer< NavigationItem > > itemsMap;\r\n\tNavigationButton * left;\r\n\tNavigationButton * right;\r\n\tTextLabel * title;\r\n\tQGridLayout * grid;\r\n\tQStack< int > backStack;\r\n\tQStack< int > forwardStack;\r\n}; \/\/ class NavigationBarPrivate\r\n\r\nvoid\r\nNavigationBarPrivate::init()\r\n{\r\n\tq->setBackgroundRole( QPalette::Base );\r\n\tq->setAutoFillBackground( true );\r\n\r\n\tstack = new QStackedWidget( q );\r\n\tstack->setFrameStyle( QFrame::NoFrame | QFrame::Plain );\r\n\r\n\tleft = new NavigationButton( NavigationButton::Left, q );\r\n\tright = new NavigationButton( NavigationButton::Right, q );\r\n\ttitle = new TextLabel( q );\r\n\ttitle->setColor( q->palette().color( QPalette::Highlight ) );\r\n\r\n\tQObject::connect( left, &NavigationButton::clicked,\r\n\t\tq, &NavigationBar::showPreviousScreen );\r\n\tQObject::connect( right, &NavigationButton::clicked,\r\n\t\tq, &NavigationBar::showNextScreen );\r\n\r\n\tQTextOption opt = title->textOption();\r\n\topt.setAlignment( Qt::AlignCenter );\r\n\topt.setWrapMode( QTextOption::NoWrap );\r\n\r\n\ttitle->setTextOption( opt );\r\n\r\n\tQFont f = title->font();\r\n\tf.setBold( true );\r\n\tf.setPointSize( f.pointSize() + 1 );\r\n\r\n\ttitle->setFont( f );\r\n\r\n\tQVBoxLayout * layout = new QVBoxLayout( q );\r\n\tlayout->setSpacing( 0 );\r\n\tlayout->setContentsMargins( 3, 3, 3, 3 );\r\n\r\n\tgrid = new QGridLayout;\r\n\tgrid->addWidget( left, 0, 0 );\r\n\tgrid->addWidget( title, 0, 1 );\r\n\tgrid->addWidget( right, 0, 2 );\r\n\tgrid->setRowMinimumHeight( 0, FingerGeometry::height() );\r\n\r\n\tleft->hide();\r\n\tright->hide();\r\n\r\n\tlayout->addLayout( grid );\r\n\tlayout->addWidget( stack );\r\n}\r\n\r\nvoid\r\nNavigationBarPrivate::removeWidget( int index )\r\n{\r\n\tQSharedPointer< NavigationItem > item = itemsMap[ index ];\r\n\r\n\titemsMap.remove( index );\r\n\tstack->removeWidget( stack->widget( index ) );\r\n\r\n\tforeach( int childIndex, item->childrenIndexes )\r\n\t\tremoveWidget( childIndex );\r\n\r\n\tif( item->parent )\r\n\t{\r\n\t\titem->parent->children.removeAt(\r\n\t\t\titem->parent->children.indexOf( item ) );\r\n\t\titem->parent->childrenIndexes.removeAt(\r\n\t\t\titem->parent->childrenIndexes.indexOf( index ) );\r\n\t}\r\n}\r\n\r\n\r\n\/\/\r\n\/\/ NavigationBar\r\n\/\/\r\n\r\nNavigationBar::NavigationBar( QWidget * parent )\r\n\t:\tQWidget( parent )\r\n\t,\td( new NavigationBarPrivate( this ) )\r\n{\r\n\td->init();\r\n}\r\n\r\nNavigationBar::~NavigationBar()\r\n{\r\n}\r\n\r\nint\r\nNavigationBar::setMainWidget( const QString & title,\r\n\tQWidget * widget )\r\n{\r\n\tconst int index = d->stack->addWidget( widget );\r\n\r\n\td->rootItems.append(\r\n\t\tQSharedPointer< NavigationItem > ( new NavigationItem ) );\r\n\td->itemsMap[ index ] = d->rootItems.back();\r\n\r\n\td->rootItems.back()->index = index;\r\n\td->rootItems.back()->title = title;\r\n\r\n\td->stack->setCurrentIndex( index );\r\n\td->title->setText( title );\r\n\r\n\treturn index;\r\n}\r\n\r\nint\r\nNavigationBar::addWidget( int parentIndex, const QString & title,\r\n\tQWidget * widget )\r\n{\r\n\tconst int index = d->stack->addWidget( widget );\r\n\r\n\tif( d->itemsMap.contains( parentIndex ) )\r\n\t{\r\n\t\tQSharedPointer< NavigationItem > parent = d->itemsMap[ parentIndex ];\r\n\r\n\t\tQSharedPointer< NavigationItem > item( new NavigationItem );\r\n\t\titem->index = index;\r\n\t\titem->title = title;\r\n\t\titem->parent = parent.data();\r\n\r\n\t\tparent->children.append( item );\r\n\t\tparent->childrenIndexes.append( index );\r\n\t\td->itemsMap[ index ] = item;\r\n\t}\r\n\r\n\treturn index;\r\n}\r\n\r\nvoid\r\nNavigationBar::removeWidget( QWidget * widget )\r\n{\r\n\tconst int index = d->stack->indexOf( widget );\r\n\r\n\tif( index != -1 )\r\n\t{\r\n\t\td->removeWidget( index );\r\n\r\n\t\td->backStack.clear();\r\n\t\td->forwardStack.clear();\r\n\r\n\t\td->left->hide();\r\n\t\td->right->hide();\r\n\t}\r\n}\r\n\r\nint\r\nNavigationBar::currentIndex() const\r\n{\r\n\treturn d->stack->currentIndex();\r\n}\r\n\r\nQWidget *\r\nNavigationBar::currentWidget() const\r\n{\r\n\treturn d->stack->currentWidget();\r\n}\r\n\r\nint\r\nNavigationBar::indexOf( QWidget * widget ) const\r\n{\r\n\treturn d->stack->indexOf( widget );\r\n}\r\n\r\nQWidget *\r\nNavigationBar::widget( int index ) const\r\n{\r\n\treturn d->stack->widget( index );\r\n}\r\n\r\nQSize\r\nNavigationBar::minimumSizeHint() const\r\n{\r\n\treturn QSize( FingerGeometry::width(), FingerGeometry::height() );\r\n}\r\n\r\nQSize\r\nNavigationBar::sizeHint() const\r\n{\r\n\treturn minimumSizeHint();\r\n}\r\n\r\nvoid\r\nNavigationBar::showScreen( int index )\r\n{\r\n\tif( d->itemsMap.contains( index ) && currentIndex() != -1 )\r\n\t{\r\n\t\tQSharedPointer< NavigationItem > nextItem = d->itemsMap[ index ];\r\n\t\tQSharedPointer< NavigationItem > currentItem = d->itemsMap[ currentIndex() ];\r\n\r\n\t\tif( d->backStack.isEmpty() || d->backStack.back() != currentIndex() )\r\n\t\t{\r\n\t\t\td->backStack.push( currentIndex() );\r\n\r\n\t\t\td->left->setText( currentItem->title );\r\n\t\t\td->left->show();\r\n\t\t}\r\n\r\n\t\td->title->setText( nextItem->title );\r\n\r\n\t\td->stack->setCurrentIndex( index );\r\n\t}\r\n}\r\n\r\nvoid\r\nNavigationBar::showPreviousScreen()\r\n{\r\n\tif( !d->backStack.isEmpty() )\r\n\t{\r\n\t\tconst int prevIndex = d->backStack.pop();\r\n\t\tQSharedPointer< NavigationItem > prevItem = d->itemsMap[ prevIndex ];\r\n\t\tQSharedPointer< NavigationItem > currentItem = d->itemsMap[ currentIndex() ];\r\n\r\n\t\tif( d->forwardStack.isEmpty() || d->forwardStack.back() != currentIndex() )\r\n\t\t{\r\n\t\t\td->forwardStack.push( currentIndex() );\r\n\r\n\t\t\td->right->setText( currentItem->title );\r\n\t\t\td->right->show();\r\n\t\t}\r\n\r\n\t\td->title->setText( prevItem->title );\r\n\r\n\t\td->stack->setCurrentIndex( prevIndex );\r\n\r\n\t\tif( !d->backStack.isEmpty() )\r\n\t\t{\r\n\t\t\tQSharedPointer< NavigationItem > backItem = d->itemsMap[ d->backStack.top() ];\r\n\r\n\t\t\td->left->setText( backItem->title );\r\n\t\t}\r\n\t\telse\r\n\t\t\td->left->hide();\r\n\t}\r\n}\r\n\r\nvoid\r\nNavigationBar::showNextScreen()\r\n{\r\n\tif( !d->forwardStack.isEmpty() )\r\n\t{\r\n\t\tconst int nextIndex = d->forwardStack.pop();\r\n\t\tQSharedPointer< NavigationItem > nextItem = d->itemsMap[ nextIndex ];\r\n\t\tQSharedPointer< NavigationItem > currentItem = d->itemsMap[ currentIndex() ];\r\n\r\n\t\td->backStack.push( currentIndex() );\r\n\r\n\t\td->title->setText( nextItem->title );\r\n\r\n\t\td->left->setText( currentItem->title );\r\n\t\td->left->show();\r\n\r\n\t\td->stack->setCurrentIndex( nextIndex );\r\n\r\n\t\tif( !d->forwardStack.isEmpty() )\r\n\t\t{\r\n\t\t\tQSharedPointer< NavigationItem > item = d->itemsMap[ d->forwardStack.top() ];\r\n\r\n\t\t\td->right->setText( item->title );\r\n\t\t}\r\n\t\telse\r\n\t\t\td->right->hide();\r\n\t}\r\n}\r\n\r\nvoid\r\nNavigationBar::resizeEvent( QResizeEvent * e )\r\n{\r\n\tconst int width = e->size().width() \/ 3;\r\n\r\n\td->grid->setColumnMinimumWidth( 0, width );\r\n\td->grid->setColumnMinimumWidth( 1, width );\r\n\td->grid->setColumnMinimumWidth( 2, width );\r\n\r\n\te->accept();\r\n}\r\n\r\nvoid\r\nNavigationBar::hideEvent( QHideEvent * e )\r\n{\r\n\tif( !isVisible() )\r\n\t{\r\n\t\td->backStack.clear();\r\n\t\td->forwardStack.clear();\r\n\r\n\t\td->left->hide();\r\n\t\td->right->hide();\r\n\t}\r\n\r\n\te->accept();\r\n}\r\n\r\n} \/* namespace QtMWidgets *\/\r\n<commit_msg>Disable forward stack on show screen in navigation bar.<commit_after>\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ QtMWidgets include.\r\n#include \"navigationbar.hpp\"\r\n#include \"navigationbutton.hpp\"\r\n#include \"textlabel.hpp\"\r\n#include \"fingergeometry.hpp\"\r\n\r\n\/\/ Qt include.\r\n#include <QStackedWidget>\r\n#include <QVector>\r\n#include <QMap>\r\n#include <QSharedPointer>\r\n#include <QGridLayout>\r\n#include <QVBoxLayout>\r\n#include <QResizeEvent>\r\n#include <QStack>\r\n#include <QHideEvent>\r\n\r\n\r\nnamespace QtMWidgets {\r\n\r\n\/\/\r\n\/\/ NavigationItem\r\n\/\/\r\n\r\nclass NavigationItem {\r\npublic:\r\n\r\n\tNavigationItem()\r\n\t\t:\tindex( -1 )\r\n\t\t,\tparent( 0 )\r\n\t{\r\n\t}\r\n\r\n\tNavigationItem( const NavigationItem & other )\r\n\t\t:\ttitle( other.title )\r\n\t\t,\tindex( other.index )\r\n\t\t,\tchildren( other.children )\r\n\t\t,\tparent( other.parent )\r\n\t{\r\n\t}\r\n\r\n\tNavigationItem & operator = ( const NavigationItem & other )\r\n\t{\r\n\t\tif( this != &other )\r\n\t\t{\r\n\t\t\ttitle = other.title;\r\n\t\t\tindex = other.index;\r\n\t\t\tchildren = other.children;\r\n\t\t\tparent = other.parent;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tQString title;\r\n\tint index;\r\n\tQVector< QSharedPointer< NavigationItem > > children;\r\n\tQVector< int > childrenIndexes;\r\n\tNavigationItem * parent;\r\n}; \/\/ class NavigationItem\r\n\r\n\r\n\/\/\r\n\/\/ NavigationBarPrivate\r\n\/\/\r\n\r\nclass NavigationBarPrivate {\r\npublic:\r\n\tNavigationBarPrivate( NavigationBar * parent )\r\n\t\t:\tq( parent )\r\n\t\t,\tstack( 0 )\r\n\t\t,\tleft( 0 )\r\n\t\t,\tright( 0 )\r\n\t\t,\ttitle( 0 )\r\n\t\t,\tgrid( 0 )\r\n\t{\r\n\t}\r\n\r\n\tvoid init();\r\n\tvoid removeWidget( int index );\r\n\r\n\tNavigationBar * q;\r\n\tQStackedWidget * stack;\r\n\tQList< QSharedPointer< NavigationItem > > rootItems;\r\n\tQMap< int, QSharedPointer< NavigationItem > > itemsMap;\r\n\tNavigationButton * left;\r\n\tNavigationButton * right;\r\n\tTextLabel * title;\r\n\tQGridLayout * grid;\r\n\tQStack< int > backStack;\r\n\tQStack< int > forwardStack;\r\n}; \/\/ class NavigationBarPrivate\r\n\r\nvoid\r\nNavigationBarPrivate::init()\r\n{\r\n\tq->setBackgroundRole( QPalette::Base );\r\n\tq->setAutoFillBackground( true );\r\n\r\n\tstack = new QStackedWidget( q );\r\n\tstack->setFrameStyle( QFrame::NoFrame | QFrame::Plain );\r\n\r\n\tleft = new NavigationButton( NavigationButton::Left, q );\r\n\tright = new NavigationButton( NavigationButton::Right, q );\r\n\ttitle = new TextLabel( q );\r\n\ttitle->setColor( q->palette().color( QPalette::Highlight ) );\r\n\r\n\tQObject::connect( left, &NavigationButton::clicked,\r\n\t\tq, &NavigationBar::showPreviousScreen );\r\n\tQObject::connect( right, &NavigationButton::clicked,\r\n\t\tq, &NavigationBar::showNextScreen );\r\n\r\n\tQTextOption opt = title->textOption();\r\n\topt.setAlignment( Qt::AlignCenter );\r\n\topt.setWrapMode( QTextOption::NoWrap );\r\n\r\n\ttitle->setTextOption( opt );\r\n\r\n\tQFont f = title->font();\r\n\tf.setBold( true );\r\n\tf.setPointSize( f.pointSize() + 1 );\r\n\r\n\ttitle->setFont( f );\r\n\r\n\tQVBoxLayout * layout = new QVBoxLayout( q );\r\n\tlayout->setSpacing( 0 );\r\n\tlayout->setContentsMargins( 3, 3, 3, 3 );\r\n\r\n\tgrid = new QGridLayout;\r\n\tgrid->addWidget( left, 0, 0 );\r\n\tgrid->addWidget( title, 0, 1 );\r\n\tgrid->addWidget( right, 0, 2 );\r\n\tgrid->setRowMinimumHeight( 0, FingerGeometry::height() );\r\n\r\n\tleft->hide();\r\n\tright->hide();\r\n\r\n\tlayout->addLayout( grid );\r\n\tlayout->addWidget( stack );\r\n}\r\n\r\nvoid\r\nNavigationBarPrivate::removeWidget( int index )\r\n{\r\n\tQSharedPointer< NavigationItem > item = itemsMap[ index ];\r\n\r\n\titemsMap.remove( index );\r\n\tstack->removeWidget( stack->widget( index ) );\r\n\r\n\tforeach( int childIndex, item->childrenIndexes )\r\n\t\tremoveWidget( childIndex );\r\n\r\n\tif( item->parent )\r\n\t{\r\n\t\titem->parent->children.removeAt(\r\n\t\t\titem->parent->children.indexOf( item ) );\r\n\t\titem->parent->childrenIndexes.removeAt(\r\n\t\t\titem->parent->childrenIndexes.indexOf( index ) );\r\n\t}\r\n}\r\n\r\n\r\n\/\/\r\n\/\/ NavigationBar\r\n\/\/\r\n\r\nNavigationBar::NavigationBar( QWidget * parent )\r\n\t:\tQWidget( parent )\r\n\t,\td( new NavigationBarPrivate( this ) )\r\n{\r\n\td->init();\r\n}\r\n\r\nNavigationBar::~NavigationBar()\r\n{\r\n}\r\n\r\nint\r\nNavigationBar::setMainWidget( const QString & title,\r\n\tQWidget * widget )\r\n{\r\n\tconst int index = d->stack->addWidget( widget );\r\n\r\n\td->rootItems.append(\r\n\t\tQSharedPointer< NavigationItem > ( new NavigationItem ) );\r\n\td->itemsMap[ index ] = d->rootItems.back();\r\n\r\n\td->rootItems.back()->index = index;\r\n\td->rootItems.back()->title = title;\r\n\r\n\td->stack->setCurrentIndex( index );\r\n\td->title->setText( title );\r\n\r\n\treturn index;\r\n}\r\n\r\nint\r\nNavigationBar::addWidget( int parentIndex, const QString & title,\r\n\tQWidget * widget )\r\n{\r\n\tconst int index = d->stack->addWidget( widget );\r\n\r\n\tif( d->itemsMap.contains( parentIndex ) )\r\n\t{\r\n\t\tQSharedPointer< NavigationItem > parent = d->itemsMap[ parentIndex ];\r\n\r\n\t\tQSharedPointer< NavigationItem > item( new NavigationItem );\r\n\t\titem->index = index;\r\n\t\titem->title = title;\r\n\t\titem->parent = parent.data();\r\n\r\n\t\tparent->children.append( item );\r\n\t\tparent->childrenIndexes.append( index );\r\n\t\td->itemsMap[ index ] = item;\r\n\t}\r\n\r\n\treturn index;\r\n}\r\n\r\nvoid\r\nNavigationBar::removeWidget( QWidget * widget )\r\n{\r\n\tconst int index = d->stack->indexOf( widget );\r\n\r\n\tif( index != -1 )\r\n\t{\r\n\t\td->removeWidget( index );\r\n\r\n\t\td->backStack.clear();\r\n\t\td->forwardStack.clear();\r\n\r\n\t\td->left->hide();\r\n\t\td->right->hide();\r\n\t}\r\n}\r\n\r\nint\r\nNavigationBar::currentIndex() const\r\n{\r\n\treturn d->stack->currentIndex();\r\n}\r\n\r\nQWidget *\r\nNavigationBar::currentWidget() const\r\n{\r\n\treturn d->stack->currentWidget();\r\n}\r\n\r\nint\r\nNavigationBar::indexOf( QWidget * widget ) const\r\n{\r\n\treturn d->stack->indexOf( widget );\r\n}\r\n\r\nQWidget *\r\nNavigationBar::widget( int index ) const\r\n{\r\n\treturn d->stack->widget( index );\r\n}\r\n\r\nQSize\r\nNavigationBar::minimumSizeHint() const\r\n{\r\n\treturn QSize( FingerGeometry::width(), FingerGeometry::height() );\r\n}\r\n\r\nQSize\r\nNavigationBar::sizeHint() const\r\n{\r\n\treturn minimumSizeHint();\r\n}\r\n\r\nvoid\r\nNavigationBar::showScreen( int index )\r\n{\r\n\tif( d->itemsMap.contains( index ) && currentIndex() != -1 )\r\n\t{\r\n\t\tQSharedPointer< NavigationItem > nextItem = d->itemsMap[ index ];\r\n\t\tQSharedPointer< NavigationItem > currentItem = d->itemsMap[ currentIndex() ];\r\n\r\n\t\tif( d->backStack.isEmpty() || d->backStack.top() != currentIndex() )\r\n\t\t{\r\n\t\t\td->backStack.push( currentIndex() );\r\n\r\n\t\t\td->left->setText( currentItem->title );\r\n\t\t\td->left->show();\r\n\t\t}\r\n\r\n\t\td->forwardStack.clear();\r\n\t\td->right->hide();\r\n\r\n\t\td->title->setText( nextItem->title );\r\n\r\n\t\td->stack->setCurrentIndex( index );\r\n\t}\r\n}\r\n\r\nvoid\r\nNavigationBar::showPreviousScreen()\r\n{\r\n\tif( !d->backStack.isEmpty() )\r\n\t{\r\n\t\tconst int prevIndex = d->backStack.pop();\r\n\t\tQSharedPointer< NavigationItem > prevItem = d->itemsMap[ prevIndex ];\r\n\t\tQSharedPointer< NavigationItem > currentItem = d->itemsMap[ currentIndex() ];\r\n\r\n\t\tif( d->forwardStack.isEmpty() || d->forwardStack.top() != currentIndex() )\r\n\t\t{\r\n\t\t\td->forwardStack.push( currentIndex() );\r\n\r\n\t\t\td->right->setText( currentItem->title );\r\n\t\t\td->right->show();\r\n\t\t}\r\n\r\n\t\td->title->setText( prevItem->title );\r\n\r\n\t\td->stack->setCurrentIndex( prevIndex );\r\n\r\n\t\tif( !d->backStack.isEmpty() )\r\n\t\t{\r\n\t\t\tQSharedPointer< NavigationItem > backItem = d->itemsMap[ d->backStack.top() ];\r\n\r\n\t\t\td->left->setText( backItem->title );\r\n\t\t}\r\n\t\telse\r\n\t\t\td->left->hide();\r\n\t}\r\n}\r\n\r\nvoid\r\nNavigationBar::showNextScreen()\r\n{\r\n\tif( !d->forwardStack.isEmpty() )\r\n\t{\r\n\t\tconst int nextIndex = d->forwardStack.pop();\r\n\t\tQSharedPointer< NavigationItem > nextItem = d->itemsMap[ nextIndex ];\r\n\t\tQSharedPointer< NavigationItem > currentItem = d->itemsMap[ currentIndex() ];\r\n\r\n\t\td->backStack.push( currentIndex() );\r\n\r\n\t\td->title->setText( nextItem->title );\r\n\r\n\t\td->left->setText( currentItem->title );\r\n\t\td->left->show();\r\n\r\n\t\td->stack->setCurrentIndex( nextIndex );\r\n\r\n\t\tif( !d->forwardStack.isEmpty() )\r\n\t\t{\r\n\t\t\tQSharedPointer< NavigationItem > item = d->itemsMap[ d->forwardStack.top() ];\r\n\r\n\t\t\td->right->setText( item->title );\r\n\t\t}\r\n\t\telse\r\n\t\t\td->right->hide();\r\n\t}\r\n}\r\n\r\nvoid\r\nNavigationBar::resizeEvent( QResizeEvent * e )\r\n{\r\n\tconst int width = e->size().width() \/ 3;\r\n\r\n\td->grid->setColumnMinimumWidth( 0, width );\r\n\td->grid->setColumnMinimumWidth( 1, width );\r\n\td->grid->setColumnMinimumWidth( 2, width );\r\n\r\n\te->accept();\r\n}\r\n\r\nvoid\r\nNavigationBar::hideEvent( QHideEvent * e )\r\n{\r\n\tif( !isVisible() )\r\n\t{\r\n\t\td->backStack.clear();\r\n\t\td->forwardStack.clear();\r\n\r\n\t\td->left->hide();\r\n\t\td->right->hide();\r\n\t}\r\n\r\n\te->accept();\r\n}\r\n\r\n} \/* namespace QtMWidgets *\/\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PaneDockingWindow.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:11:45 $\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 SD_PANE_DOCKING_WINDOW_HXX\n#define SD_PANE_DOCKING_WINDOW_HXX\n\n#ifndef _SFXDOCKWIN_HXX\n#include <sfx2\/dockwin.hxx>\n#endif\n#include <sfx2\/viewfrm.hxx>\n#include \"PaneManager.hxx\"\n\nclass ToolBox;\n\nnamespace sd {\n\nclass PaneDockingWindow\n : public SfxDockingWindow\n{\npublic:\n \/** Create a new docking window that will be displayed in the specified\n pane.\n The constructor will determine the ViewShellBase via the given\n bindings and tell its PaneManager about the new window. It will ask\n the PaneManager for a window title.\n @param pBindings\n Used, among others, to determine the ViewShellBase and\n PaneManager that manage the new docking window.\n @param pChildWindow\n This child window is the logical container for the new docking\n window.\n @param pParent\n The parent window of the new docking window.\n @param rResId\n The resource is used to determine initial size and attributes.\n @param ePane\n The pane in which to show the docking window.\n *\/\n PaneDockingWindow (\n SfxBindings *pBindings,\n SfxChildWindow *pChildWindow,\n ::Window* pParent,\n const ResId& rResId,\n PaneManager::PaneType ePane);\n\n virtual ~PaneDockingWindow (void);\n\n virtual void Paint (const Rectangle& rRectangle);\n virtual void Resize (void);\n\n virtual long Notify( NotifyEvent& rNEvt );\n virtual void StateChanged( StateChangedType nType );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\n \/** Initializing the title tool box either creates a new title tool box\n or clears all items from an existing one. A closer is added as only\n item.\n *\/\n void InitializeTitleToolBox (void);\n\n \/** Add a top down menu to the title bar or rather the top-level menu\n entry. The given callback is called when the menu is clicked and it\n is the task of the callback to show the menu.\n @return\n The id of the new menu is returned. It can be compared by the\n callback to the value of GetCurItemId() when called at the given\n tool box.\n *\/\n USHORT AddMenu (const String& rsMenuName, ULONG nHelpId, const Link& rCallback);\n\n \/** Set the title of the docking window to the given string. Use this\n method when the title is not yet known at the time of construction\n or can not be passed to the constructor.\n *\/\n void SetTitle (const String& rsTitle);\n\nprivate:\n \/** The pane which is represented by the docking window.\n *\/\n PaneManager::PaneType mePane;\n\n \/** Title that is shown at the top of the docking window.\n *\/\n String msTitle;\n\n \/** The tool box that is displayed in the window title area contains\n menus and the closer button.\n *\/\n ::std::auto_ptr<ToolBox> mpTitleToolBox;\n\n \/** The border that is painted arround the inner window. The bevel\n shadow lines are part of the border, so where the border is 0 no\n such line is painted.\n *\/\n SvBorder maBorder;\n\n sal_uInt16 mnChildWindowId;\n\n DECL_LINK(ToolboxSelectHandler, ToolBox*);\n DECL_LINK(WindowEventListener, VclSimpleEvent*);\n};\n\n} \/\/ end of namespace ::sd\n\n#endif\n<commit_msg>INTEGRATION: CWS impress66 (1.7.80); FILE MERGED 2005\/10\/10 14:36:24 af 1.7.80.2: RESYNC: (1.7-1.8); FILE MERGED 2005\/08\/08 11:38:19 af 1.7.80.1: #i48402# Added argument for docking window title to constructor.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PaneDockingWindow.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2005-10-24 16:17:35 $\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 SD_PANE_DOCKING_WINDOW_HXX\n#define SD_PANE_DOCKING_WINDOW_HXX\n\n#ifndef _SFXDOCKWIN_HXX\n#include <sfx2\/dockwin.hxx>\n#endif\n#include <sfx2\/viewfrm.hxx>\n#include \"PaneManager.hxx\"\n\nclass ToolBox;\n\nnamespace sd {\n\nclass PaneDockingWindow\n : public SfxDockingWindow\n{\npublic:\n \/** Create a new docking window that will be displayed in the specified\n pane.\n The constructor will determine the ViewShellBase via the given\n bindings and tell its PaneManager about the new window. It will ask\n the PaneManager for a window title.\n @param pBindings\n Used, among others, to determine the ViewShellBase and\n PaneManager that manage the new docking window.\n @param pChildWindow\n This child window is the logical container for the new docking\n window.\n @param pParent\n The parent window of the new docking window.\n @param rResId\n The resource is used to determine initial size and attributes.\n @param ePane\n The pane in which to show the docking window.\n *\/\n PaneDockingWindow (\n SfxBindings *pBindings,\n SfxChildWindow *pChildWindow,\n ::Window* pParent,\n const ResId& rResId,\n PaneManager::PaneType ePane,\n const String& rsTitle);\n\n virtual ~PaneDockingWindow (void);\n\n virtual void Paint (const Rectangle& rRectangle);\n virtual void Resize (void);\n\n virtual long Notify( NotifyEvent& rNEvt );\n virtual void StateChanged( StateChangedType nType );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\n \/** Initializing the title tool box either creates a new title tool box\n or clears all items from an existing one. A closer is added as only\n item.\n *\/\n void InitializeTitleToolBox (void);\n\n \/** Add a top down menu to the title bar or rather the top-level menu\n entry. The given callback is called when the menu is clicked and it\n is the task of the callback to show the menu.\n @return\n The id of the new menu is returned. It can be compared by the\n callback to the value of GetCurItemId() when called at the given\n tool box.\n *\/\n USHORT AddMenu (const String& rsMenuName, ULONG nHelpId, const Link& rCallback);\n\n \/** Set the title of the docking window to the given string. Use this\n method when the title is not yet known at the time of construction\n or can not be passed to the constructor.\n *\/\n void SetTitle (const String& rsTitle);\n\nprivate:\n \/** The pane which is represented by the docking window.\n *\/\n PaneManager::PaneType mePane;\n\n \/** Title that is shown at the top of the docking window.\n *\/\n String msTitle;\n\n \/** The tool box that is displayed in the window title area contains\n menus and the closer button.\n *\/\n ::std::auto_ptr<ToolBox> mpTitleToolBox;\n\n \/** The border that is painted arround the inner window. The bevel\n shadow lines are part of the border, so where the border is 0 no\n such line is painted.\n *\/\n SvBorder maBorder;\n\n sal_uInt16 mnChildWindowId;\n\n DECL_LINK(ToolboxSelectHandler, ToolBox*);\n DECL_LINK(WindowEventListener, VclSimpleEvent*);\n};\n\n} \/\/ end of namespace ::sd\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\n\/*\n Memcached protocol extensions for testapp.\n\n Provides extended protocol commands to enable interesting testcases.\n\n 1. Currently supports shifting the Memcached's timeofday.\n * protocol command can be overridden in config.\n*\/\n\n#include \"config.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <inttypes.h>\n\n#include \"extensions\/protocol_extension.h\"\n#include <memcached\/util.h>\n#include <platform\/platform.h>\n\nstatic uint8_t adjust_timeofday_command = PROTOCOL_BINARY_CMD_ADJUST_TIMEOFDAY;\n\nGET_SERVER_API server_api;\n\nstatic const char *get_name(void);\nstatic void setup(void (*add)(EXTENSION_BINARY_PROTOCOL_DESCRIPTOR *descriptor,\n uint8_t cmd,\n BINARY_COMMAND_CALLBACK new_handler));\n\nstatic ENGINE_ERROR_CODE handle_adjust_time(EXTENSION_BINARY_PROTOCOL_DESCRIPTOR *descriptor,\n ENGINE_HANDLE* handle,\n const void* cookie,\n protocol_binary_request_header *request,\n ADD_RESPONSE response);\n\nstatic EXTENSION_BINARY_PROTOCOL_DESCRIPTOR descriptor;\n\nstatic const char *get_name(void) {\n return \"testapp protocol extension\";\n}\n\nstatic void setup(void (*add)(EXTENSION_BINARY_PROTOCOL_DESCRIPTOR *descriptor,\n uint8_t cmd,\n BINARY_COMMAND_CALLBACK new_handler))\n{\n add(&descriptor, adjust_timeofday_command, handle_adjust_time);\n}\n\n\nstatic ENGINE_ERROR_CODE handle_adjust_time(EXTENSION_BINARY_PROTOCOL_DESCRIPTOR *descriptor,\n ENGINE_HANDLE* handle,\n const void* cookie,\n protocol_binary_request_header *request,\n ADD_RESPONSE response)\n{\n protocol_binary_adjust_time *req = (protocol_binary_adjust_time*)request;\n ENGINE_ERROR_CODE r = ENGINE_SUCCESS;\n uint64_t offset = 0;\n\n offset = ntohll(req->message.body.offset);\n\n if (r == ENGINE_SUCCESS) {\n\n if (r == ENGINE_SUCCESS) {\n if (request->request.opcode == adjust_timeofday_command) {\n cb_set_timeofday_offset(offset);\n\n if (!response(NULL, 0, NULL, 0, NULL, 0,\n PROTOCOL_BINARY_RAW_BYTES,\n PROTOCOL_BINARY_RESPONSE_SUCCESS,\n 0, cookie)) {\n return ENGINE_DISCONNECT;\n }\n } else {\n if (!response(NULL, 0, NULL, 0, NULL, 0,\n PROTOCOL_BINARY_RAW_BYTES,\n PROTOCOL_BINARY_RESPONSE_SUCCESS,\n 0, cookie)) {\n return ENGINE_DISCONNECT;\n }\n }\n\n }\n }\n return r;\n}\n\nMEMCACHED_PUBLIC_API\nEXTENSION_ERROR_CODE memcached_extensions_initialize(const char *config,\n GET_SERVER_API get_server_api) {\n SERVER_HANDLE_V1 *server = get_server_api();\n server_api = get_server_api;\n descriptor.get_name = get_name;\n descriptor.setup = setup;\n\n if (server == NULL) {\n return EXTENSION_FATAL;\n }\n\n if (config != NULL) {\n size_t time_op = 0;\n struct config_item items[2];\n memset(&items, 0, sizeof(items));\n\n items[0].key = \"t\";\n items[0].datatype = DT_SIZE;\n items[0].value.dt_size = &time_op;\n\n if (server->core->parse_config(config, items, stderr) != 0) {\n return EXTENSION_FATAL;\n }\n\n if (items[0].found) {\n adjust_timeofday_command = (uint8_t)(time_op & 0xff);\n }\n }\n\n if (!server->extension->register_extension(EXTENSION_BINARY_PROTOCOL,\n &descriptor)) {\n return EXTENSION_FATAL;\n }\n\n return EXTENSION_SUCCESS;\n}\n<commit_msg>Refactor: Drop dead code<commit_after>\/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\n\/*\n Memcached protocol extensions for testapp.\n\n Provides extended protocol commands to enable interesting testcases.\n\n 1. Currently supports shifting the Memcached's timeofday.\n*\/\n\n#include \"config.h\"\n#include \"extensions\/protocol_extension.h\"\n\nstatic EXTENSION_BINARY_PROTOCOL_DESCRIPTOR descriptor;\n\nstatic const char *get_name(void) {\n return \"testapp protocol extension\";\n}\n\nstatic ENGINE_ERROR_CODE handle_adjust_time(EXTENSION_BINARY_PROTOCOL_DESCRIPTOR*,\n ENGINE_HANDLE*,\n const void* cookie,\n protocol_binary_request_header *request,\n ADD_RESPONSE response) {\n auto *req = reinterpret_cast<protocol_binary_adjust_time*>(request);\n uint64_t offset = ntohll(req->message.body.offset);\n\n if (request->request.opcode == PROTOCOL_BINARY_CMD_ADJUST_TIMEOFDAY) {\n cb_set_timeofday_offset(offset);\n }\n\n if (!response(nullptr, 0, nullptr, 0, nullptr, 0,\n PROTOCOL_BINARY_RAW_BYTES,\n PROTOCOL_BINARY_RESPONSE_SUCCESS,\n 0, cookie)) {\n return ENGINE_DISCONNECT;\n }\n\n return ENGINE_SUCCESS;\n}\n\nstatic void setup(void (*add)(EXTENSION_BINARY_PROTOCOL_DESCRIPTOR *descriptor,\n uint8_t cmd,\n BINARY_COMMAND_CALLBACK new_handler)) {\n add(&descriptor, PROTOCOL_BINARY_CMD_ADJUST_TIMEOFDAY, handle_adjust_time);\n}\n\nMEMCACHED_PUBLIC_API\nEXTENSION_ERROR_CODE memcached_extensions_initialize(const char *config,\n GET_SERVER_API get_server_api) {\n SERVER_HANDLE_V1 *server = get_server_api();\n descriptor.get_name = get_name;\n descriptor.setup = setup;\n\n if (server == nullptr) {\n return EXTENSION_FATAL;\n }\n\n if (config != nullptr && strlen(config) > 0) {\n return EXTENSION_FATAL;\n }\n\n if (!server->extension->register_extension(EXTENSION_BINARY_PROTOCOL,\n &descriptor)) {\n return EXTENSION_FATAL;\n }\n\n return EXTENSION_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2018-2019 Inviwo Foundation\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 met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <inviwo\/core\/interaction\/pickingcontrollermousestate.h>\n\n#include <inviwo\/core\/interaction\/pickingmanager.h>\n#include <inviwo\/core\/interaction\/events\/eventpropagator.h>\n#include <inviwo\/core\/interaction\/events\/mouseevent.h>\n#include <inviwo\/core\/interaction\/events\/pickingevent.h>\n#include <inviwo\/core\/interaction\/pickingaction.h>\n#include <inviwo\/core\/interaction\/pickingcontroller.h>\n\n#include <sml\/sml.hpp>\nnamespace sml = boost::sml;\n\nnamespace inviwo {\n\nnamespace fsm {\n\n\/\/ State\nstruct FsmState {\n size_t active_globalId = 0;\n};\n\nstruct PreviousFsmState {\n size_t globalId = 0;\n dvec3 ndc{0};\n};\n\nstruct PressFsmState {\n size_t globalId = 0;\n dvec3 ndc{0};\n};\n\n\/\/ States\nstruct Idle {};\nstruct HasId {};\nstruct Pressing {};\n\n\/\/ events;\nstruct BaseEvent {\n BaseEvent(const size_t globalId, MouseEvent* event, EventPropagator* propagator)\n : globalId{globalId}, event{event}, propagator{propagator} {}\n const size_t globalId;\n MouseEvent* event;\n EventPropagator* propagator;\n};\nstruct Move : BaseEvent {\n using BaseEvent::BaseEvent;\n};\nstruct Press : BaseEvent {\n using BaseEvent::BaseEvent;\n};\nstruct Release : BaseEvent {\n using BaseEvent::BaseEvent;\n};\nstruct DblClk : BaseEvent {\n using BaseEvent::BaseEvent;\n};\n\nPickingPressItem mouseButtonToPressItem(MouseButton mb) {\n switch (mb) {\n case MouseButton::None:\n return PickingPressItem::None;\n case MouseButton::Left:\n return PickingPressItem::Primary;\n case MouseButton::Middle:\n return PickingPressItem::Tertiary;\n case MouseButton::Right:\n return PickingPressItem::Secondary;\n default:\n return PickingPressItem::None;\n }\n}\nPickingPressItems mouseButtonsToPressItems(MouseButtons mb) {\n PickingPressItems res = PickingPressItem::None;\n if (mb.count(MouseButton::Left)) res |= PickingPressItem::Primary;\n if (mb.count(MouseButton::Middle)) res |= PickingPressItem::Tertiary;\n if (mb.count(MouseButton::Right)) res |= PickingPressItem::Secondary;\n return res;\n}\n\ntemplate <typename E>\nauto send(PickingState state, PickingPressState pressState, PickingHoverState hoverState,\n bool updatePrev = true, bool markAsUsed = true) {\n return [state, pressState, hoverState, updatePrev, markAsUsed](\n const E& fsmEvent, FsmState& fsmState, PreviousFsmState& prev, PressFsmState& press,\n PickingManager* pickingManager) {\n auto res = pickingManager->getPickingActionFromIndex(fsmState.active_globalId);\n if (res.index == 0 || !res.action) return;\n\n auto me = fsmEvent.event;\n const PickingPressItem pressItem = mouseButtonToPressItem(me->button());\n const PickingPressItems pressedState = mouseButtonsToPressItems(me->buttonState());\n\n PickingEvent pe(res.action, me, state, pressState, pressItem, hoverState, pressedState,\n fsmState.active_globalId, fsmEvent.globalId, press.globalId, prev.globalId,\n press.ndc, prev.ndc);\n fsmEvent.propagator->propagateEvent(&pe, nullptr);\n\n if (markAsUsed && pe.hasBeenUsed()) me->markAsUsed();\n if (updatePrev) {\n prev.globalId = fsmState.active_globalId;\n prev.ndc = me->ndc();\n }\n };\n}\n\ntemplate <typename E>\nauto uid() {\n return [](const E& e, FsmState& fsmstate) { fsmstate.active_globalId = e.globalId; };\n}\n\nstruct Fsm {\n auto operator()() const noexcept {\n using namespace sml;\n const auto idle = sml::state<Idle>;\n const auto hasId = sml::state<HasId>;\n const auto pressing = sml::state<Pressing>;\n\n const auto uidm = uid<Move>();\n const auto uidp = uid<Press>();\n const auto uidr = uid<Release>();\n\n using S = PickingState;\n using P = PickingPressState;\n using H = PickingHoverState;\n\n const auto ups = [](const Press& e, PressFsmState& pressState) {\n pressState.globalId = e.globalId;\n pressState.ndc = e.event->ndc();\n };\n const auto rps = [](PressFsmState& pressState) {\n pressState.globalId = 0;\n pressState.ndc = dvec3{0};\n };\n\n \/\/ guards\n const auto sameId = [](const FsmState& state, const auto& e) -> bool {\n return e.globalId == state.active_globalId;\n };\n const auto diffId = [](const FsmState& state, const auto& e) -> bool {\n return e.globalId != state.active_globalId && e.globalId != 0;\n };\n const auto zeroId = [](const auto& e) -> bool { return e.globalId == 0; };\n const auto zeroMB = [](const FsmState&, const auto& e) -> bool {\n return e.event->buttonState().empty();\n };\n\n \/\/ clang-format off\n return sml::make_transition_table(\n *idle + event<Move> [!zeroId && zeroMB] \/ (uidm, send<Move>(S::Started, P::None, H::Enter)) = hasId,\n idle + event<Press> [!zeroId] \/ (uidp, send<Press>(S::Updated, P::Press, H::Enter)) = pressing,\n idle + event<Release> [!zeroId] \/ (uidr, send<Release>(S::Started, P::None, H::Enter)) = hasId,\n idle + sml::on_entry<_> \/ rps,\n \n hasId + event<Move> [sameId] \/ (send<Move>(S::Updated, P::None, H::Move)),\n hasId + event<Move> [zeroId] \/ (send<Move>(S::Finished, P::None, H::Exit), uidm) = idle,\n hasId + event<Move> [diffId] \/ (send<Move>(S::Finished, P::None, H::Exit, false, false), uidm, send<Move>(S::Started, P::None, H::Enter)),\n hasId + event<Press> [sameId] \/ (ups, send<Press>(S::Updated, P::Press, H::None)) = pressing,\n hasId + sml::on_entry<_> \/ rps,\n\n pressing + event<Move> [sameId] \/ (send<Move>(S::Updated, P::Move, H::Move)),\n pressing + event<Move> [diffId] \/ (send<Move>(S::Updated, P::Move, H::Move)),\n pressing + event<Move> [zeroId] \/ (send<Move>(S::Updated, P::Move, H::Move)),\n\n pressing + event<Release> [sameId && zeroMB] \/ (send<Release>(S::Updated, P::Release, H::None)) = hasId,\n pressing + event<Release> [zeroId && zeroMB] \/ (send<Release>(S::Finished, P::Release, H::Exit), uidr) = idle,\n pressing + event<Release> [diffId && zeroMB] \/ (send<Release>(S::Finished, P::Release, H::Exit, true, false), uidr, send<Release>(S::Started, P::None, H::Enter)) = hasId,\n pressing + event<Release> [!zeroMB] \/ (send<Release>(S::Updated, P::Release, H::None)),\n pressing + event<Press> \/ (send<Press> (S::Updated, P::Press, H::None)),\n \n hasId + event<DblClk> [sameId] \/ (send<DblClk>(S::Updated, P::DoubleClick, H::None)),\n pressing + event<DblClk> \/ (send<DblClk>(S::Updated, P::DoubleClick, H::None))\n );\n \/\/ clang-format on\n }\n};\n\n} \/\/ namespace fsm\n\nstruct PickingControllerMouseStateSM {\n PickingControllerMouseStateSM(PickingManager* pickingManager)\n : pickingManager{pickingManager} {}\n PickingManager* pickingManager;\n fsm::FsmState state;\n fsm::PreviousFsmState previousState;\n fsm::PressFsmState pressState;\n sml::sm<fsm::Fsm> sm{state, previousState, pressState, pickingManager};\n};\n\nPickingControllerMouseState::PickingControllerMouseState(PickingManager* pickingManager)\n : msm{std::make_unique<PickingControllerMouseStateSM>(pickingManager)} {}\n\nPickingControllerMouseState::~PickingControllerMouseState() = default;\n\nvoid PickingControllerMouseState::propagateEvent(MouseEvent* e, EventPropagator* propagator,\n size_t globalId) {\n switch (e->state()) {\n case MouseState::Press: {\n msm->sm.process_event(fsm::Press{globalId, e, propagator});\n break;\n }\n case MouseState::Move: {\n msm->sm.process_event(fsm::Move{globalId, e, propagator});\n break;\n }\n case MouseState::Release: {\n msm->sm.process_event(fsm::Release{globalId, e, propagator});\n break;\n }\n case MouseState::DoubleClick: {\n msm->sm.process_event(fsm::DblClk{globalId, e, propagator});\n break;\n }\n }\n}\n\n} \/\/ namespace inviwo\n<commit_msg>Core: picking controller fix for mouse * handle case when the picking ID under the mouse changes without moving the mouse<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2018-2019 Inviwo Foundation\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 met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <inviwo\/core\/interaction\/pickingcontrollermousestate.h>\n\n#include <inviwo\/core\/interaction\/pickingmanager.h>\n#include <inviwo\/core\/interaction\/events\/eventpropagator.h>\n#include <inviwo\/core\/interaction\/events\/mouseevent.h>\n#include <inviwo\/core\/interaction\/events\/pickingevent.h>\n#include <inviwo\/core\/interaction\/pickingaction.h>\n#include <inviwo\/core\/interaction\/pickingcontroller.h>\n\n#include <sml\/sml.hpp>\nnamespace sml = boost::sml;\n\nnamespace inviwo {\n\nnamespace fsm {\n\n\/\/ State\nstruct FsmState {\n size_t active_globalId = 0;\n};\n\nstruct PreviousFsmState {\n size_t globalId = 0;\n dvec3 ndc{0};\n};\n\nstruct PressFsmState {\n size_t globalId = 0;\n dvec3 ndc{0};\n};\n\n\/\/ States\nstruct Idle {};\nstruct HasId {};\nstruct Pressing {};\n\n\/\/ events;\nstruct BaseEvent {\n BaseEvent(const size_t globalId, MouseEvent* event, EventPropagator* propagator)\n : globalId{globalId}, event{event}, propagator{propagator} {}\n const size_t globalId;\n MouseEvent* event;\n EventPropagator* propagator;\n};\nstruct Move : BaseEvent {\n using BaseEvent::BaseEvent;\n};\nstruct Press : BaseEvent {\n using BaseEvent::BaseEvent;\n};\nstruct Release : BaseEvent {\n using BaseEvent::BaseEvent;\n};\nstruct DblClk : BaseEvent {\n using BaseEvent::BaseEvent;\n};\n\nPickingPressItem mouseButtonToPressItem(MouseButton mb) {\n switch (mb) {\n case MouseButton::None:\n return PickingPressItem::None;\n case MouseButton::Left:\n return PickingPressItem::Primary;\n case MouseButton::Middle:\n return PickingPressItem::Tertiary;\n case MouseButton::Right:\n return PickingPressItem::Secondary;\n default:\n return PickingPressItem::None;\n }\n}\nPickingPressItems mouseButtonsToPressItems(MouseButtons mb) {\n PickingPressItems res = PickingPressItem::None;\n if (mb.count(MouseButton::Left)) res |= PickingPressItem::Primary;\n if (mb.count(MouseButton::Middle)) res |= PickingPressItem::Tertiary;\n if (mb.count(MouseButton::Right)) res |= PickingPressItem::Secondary;\n return res;\n}\n\ntemplate <typename E>\nauto send(PickingState state, PickingPressState pressState, PickingHoverState hoverState,\n bool updatePrev = true, bool markAsUsed = true) {\n return [state, pressState, hoverState, updatePrev, markAsUsed](\n const E& fsmEvent, FsmState& fsmState, PreviousFsmState& prev, PressFsmState& press,\n PickingManager* pickingManager) {\n auto res = pickingManager->getPickingActionFromIndex(fsmState.active_globalId);\n if (res.index == 0 || !res.action) return;\n\n auto me = fsmEvent.event;\n const PickingPressItem pressItem = mouseButtonToPressItem(me->button());\n const PickingPressItems pressedState = mouseButtonsToPressItems(me->buttonState());\n\n PickingEvent pe(res.action, me, state, pressState, pressItem, hoverState, pressedState,\n fsmState.active_globalId, fsmEvent.globalId, press.globalId, prev.globalId,\n press.ndc, prev.ndc);\n fsmEvent.propagator->propagateEvent(&pe, nullptr);\n\n if (markAsUsed && pe.hasBeenUsed()) me->markAsUsed();\n if (updatePrev) {\n prev.globalId = fsmState.active_globalId;\n prev.ndc = me->ndc();\n }\n };\n}\n\ntemplate <typename E>\nauto uid() {\n return [](const E& e, FsmState& fsmstate) { fsmstate.active_globalId = e.globalId; };\n}\n\nstruct Fsm {\n auto operator()() const noexcept {\n using namespace sml;\n const auto idle = sml::state<Idle>;\n const auto hasId = sml::state<HasId>;\n const auto pressing = sml::state<Pressing>;\n\n const auto uidm = uid<Move>();\n const auto uidp = uid<Press>();\n const auto uidr = uid<Release>();\n\n using S = PickingState;\n using P = PickingPressState;\n using H = PickingHoverState;\n\n const auto ups = [](const Press& e, PressFsmState& pressState) {\n pressState.globalId = e.globalId;\n pressState.ndc = e.event->ndc();\n };\n const auto rps = [](PressFsmState& pressState) {\n pressState.globalId = 0;\n pressState.ndc = dvec3{0};\n };\n\n \/\/ guards\n const auto sameId = [](const FsmState& state, const auto& e) -> bool {\n return e.globalId == state.active_globalId;\n };\n const auto diffId = [](const FsmState& state, const auto& e) -> bool {\n return e.globalId != state.active_globalId && e.globalId != 0;\n };\n const auto zeroId = [](const auto& e) -> bool { return e.globalId == 0; };\n const auto zeroMB = [](const FsmState&, const auto& e) -> bool {\n return e.event->buttonState().empty();\n };\n\n \/\/ clang-format off\n return sml::make_transition_table(\n *idle + event<Move> [!zeroId && zeroMB] \/ (uidm, send<Move>(S::Started, P::None, H::Enter)) = hasId,\n idle + event<Press> [!zeroId] \/ (uidp, send<Press>(S::Updated, P::Press, H::Enter)) = pressing,\n idle + event<Release> [!zeroId] \/ (uidr, send<Release>(S::Started, P::None, H::Enter)) = hasId,\n idle + sml::on_entry<_> \/ rps,\n \n hasId + event<Move> [sameId] \/ (send<Move>(S::Updated, P::None, H::Move)),\n hasId + event<Move> [zeroId] \/ (send<Move>(S::Finished, P::None, H::Exit), uidm) = idle,\n hasId + event<Move> [diffId] \/ (send<Move>(S::Finished, P::None, H::Exit, false, false), uidm, send<Move>(S::Started, P::None, H::Enter)),\n hasId + event<Press> [sameId] \/ (ups, send<Press>(S::Updated, P::Press, H::None)) = pressing,\n hasId + event<Press> [diffId] \/ (send<Press>(S::Finished, P::None, H::Exit, false, false), ups, uidp, send<Press>(S::Updated, P::Press, H::Enter)) = pressing,\n hasId + sml::on_entry<_> \/ rps,\n\n pressing + event<Move> [sameId] \/ (send<Move>(S::Updated, P::Move, H::Move)),\n pressing + event<Move> [diffId] \/ (send<Move>(S::Updated, P::Move, H::Move)),\n pressing + event<Move> [zeroId] \/ (send<Move>(S::Updated, P::Move, H::Move)),\n\n pressing + event<Release> [sameId && zeroMB] \/ (send<Release>(S::Updated, P::Release, H::None)) = hasId,\n pressing + event<Release> [zeroId && zeroMB] \/ (send<Release>(S::Finished, P::Release, H::Exit), uidr) = idle,\n pressing + event<Release> [diffId && zeroMB] \/ (send<Release>(S::Finished, P::Release, H::Exit, true, false), uidr, send<Release>(S::Started, P::None, H::Enter)) = hasId,\n pressing + event<Release> [!zeroMB] \/ (send<Release>(S::Updated, P::Release, H::None)),\n pressing + event<Press> \/ (send<Press> (S::Updated, P::Press, H::None)),\n \n hasId + event<DblClk> [sameId] \/ (send<DblClk>(S::Updated, P::DoubleClick, H::None)),\n pressing + event<DblClk> \/ (send<DblClk>(S::Updated, P::DoubleClick, H::None))\n );\n \/\/ clang-format on\n }\n};\n\n} \/\/ namespace fsm\n\nstruct PickingControllerMouseStateSM {\n PickingControllerMouseStateSM(PickingManager* pickingManager)\n : pickingManager{pickingManager} {}\n PickingManager* pickingManager;\n fsm::FsmState state;\n fsm::PreviousFsmState previousState;\n fsm::PressFsmState pressState;\n sml::sm<fsm::Fsm> sm{state, previousState, pressState, pickingManager};\n};\n\nPickingControllerMouseState::PickingControllerMouseState(PickingManager* pickingManager)\n : msm{std::make_unique<PickingControllerMouseStateSM>(pickingManager)} {}\n\nPickingControllerMouseState::~PickingControllerMouseState() = default;\n\nvoid PickingControllerMouseState::propagateEvent(MouseEvent* e, EventPropagator* propagator,\n size_t globalId) {\n switch (e->state()) {\n case MouseState::Press: {\n msm->sm.process_event(fsm::Press{globalId, e, propagator});\n break;\n }\n case MouseState::Move: {\n msm->sm.process_event(fsm::Move{globalId, e, propagator});\n break;\n }\n case MouseState::Release: {\n msm->sm.process_event(fsm::Release{globalId, e, propagator});\n break;\n }\n case MouseState::DoubleClick: {\n msm->sm.process_event(fsm::DblClk{globalId, e, propagator});\n break;\n }\n }\n}\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\r\n*\r\n* NAME: smbPitchShift.cpp\r\n* VERSION: 1.2\r\n* HOME URL: http:\/\/blogs.zynaptiq.com\/bernsee\r\n* KNOWN BUGS: none\r\n*\r\n* SYNOPSIS: Routine for doing pitch shifting while maintaining\r\n* duration using the Short Time Fourier Transform.\r\n*\r\n* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5\r\n* (one octave down) and 2. (one octave up). A value of exactly 1 does not change\r\n* the pitch. numSampsToProcess tells the routine how many samples in indata[0...\r\n* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...\r\n* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the\r\n* data in-place). fftFrameSize defines the FFT frame size used for the\r\n* processing. Typical values are 1024, 2048 and 4096. It MUST be a power of 2.\r\n* oversamp is the STFT oversampling factor which also determines the overlap\r\n* between adjacent STFT frames. It should at least be 4 for moderate scaling\r\n* ratios. A value of 32 is recommended for best quality. sampleRate takes the\r\n* sample rate for the signal in unit Hz, ie. 44100 for 44.1 kHz audio. The data\r\n* passed to the routine in indata[] should be in the range [-1.0, 1.0), which is\r\n* also the output range for the data, make sure you scale the data accordingly\r\n* (for 16bit signed integers you would have to divide (and multiply) by 32768).\r\n*\r\n* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>\r\n*\r\n* \t\t\t\t\t\tThe Wide Open License (WOL)\r\n*\r\n* Permission to use, copy, modify, distribute and sell this software and its\r\n* documentation for any purpose is hereby granted without fee, provided that\r\n* the above copyright notice and this license appear in all source copies. \r\n* THIS SOFTWARE IS PROVIDED \"AS IS\" WITHOUT EXPRESS OR IMPLIED WARRANTY OF\r\n* ANY KIND. See http:\/\/www.dspguru.com\/wol.htm for more information.\r\n*\r\n*****************************************************************************\/\r\n\r\n#ifndef SMBPITCHSHIFT_HPP\r\n#define SMBPITCHSHIFT_HPP\r\n\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <cstdint>\r\n\r\nnamespace smb\r\n{\r\n namespace\r\n {\r\n constexpr float pi = 3.14159265358979323846F;\r\n\r\n \/\/ Use own implementation because std::complex has a poor performance\r\n template <class T>\r\n struct Complex final\r\n {\r\n constexpr Complex<T> operator+(const Complex& other) const noexcept\r\n {\r\n return Complex{real + other.real, imag + other.imag};\r\n }\r\n\r\n constexpr Complex<T>& operator+=(const Complex& other)\r\n {\r\n real += other.real;\r\n imag += other.imag;\r\n return *this;\r\n }\r\n\r\n constexpr Complex<T> operator-(const Complex& other) const noexcept\r\n {\r\n return Complex{real - other.real, imag - other.imag};\r\n }\r\n\r\n constexpr Complex<T> operator-() const noexcept\r\n {\r\n return Complex{-real, -imag};\r\n }\r\n\r\n constexpr Complex<T>& operator-=(const Complex& other) noexcept\r\n {\r\n real -= other.real;\r\n imag -= other.imag;\r\n return *this;\r\n }\r\n\r\n constexpr Complex<T> operator*(const Complex& other) const noexcept\r\n {\r\n return Complex{real * other.real - imag * other.imag, real * other.imag + imag * other.real};\r\n }\r\n\r\n constexpr Complex<T>& operator*=(const Complex& other) noexcept\r\n {\r\n float tempReal = real;\r\n real = tempReal * other.real - imag * other.imag;\r\n imag = tempReal * other.imag + imag * other.real;\r\n return *this;\r\n }\r\n\r\n inline T magnitude() const noexcept\r\n {\r\n return sqrt(real * real + imag * imag);\r\n }\r\n\r\n T real;\r\n T imag;\r\n };\r\n\r\n template <int32_t sign, uint32_t fftFrameSize>\r\n void fft(Complex<float>* fftBuffer) noexcept\r\n {\r\n \/\/ Bit-reversal permutation applied to a sequence of fftFrameSize items\r\n for (uint32_t i = 1; i < fftFrameSize - 1; ++i)\r\n {\r\n uint32_t j = 0;\r\n\r\n for (uint32_t bitm = 1; bitm < fftFrameSize; bitm <<= 1)\r\n {\r\n if (i & bitm) ++j;\r\n j <<= 1;\r\n }\r\n j >>= 1;\r\n\r\n if (i < j)\r\n std::swap(fftBuffer[i], fftBuffer[j]);\r\n }\r\n\r\n \/\/ Iterative form of Danielson–-Lanczos lemma\r\n uint32_t step = 2;\r\n for (uint32_t i = 1; i < fftFrameSize; i <<= 1, step <<= 1)\r\n {\r\n const uint32_t step2 = step >> 1;\r\n const float arg = pi \/ step2;\r\n\r\n const Complex<float> w{std::cos(arg), std::sin(arg) * sign};\r\n Complex<float> u{1.0F, 0.0F};\r\n for (uint32_t j = 0; j < step2; ++j)\r\n {\r\n for (uint32_t k = j; k < fftFrameSize; k += step)\r\n {\r\n const Complex<float> temp = fftBuffer[k + step2] * u;\r\n fftBuffer[k + step2] = fftBuffer[k] - temp;\r\n fftBuffer[k] += temp;\r\n }\r\n\r\n u *= w;\r\n }\r\n }\r\n }\r\n }\r\n\r\n template <uint32_t fftFrameSize, uint32_t oversamp>\r\n class PitchShift final\r\n {\r\n public:\r\n PitchShift()\r\n {\r\n \/\/ Hann window\r\n for (uint32_t k = 0; k < fftFrameSize; ++k)\r\n window[k] = 0.5F * (1.0F + std::cos(2.0F * pi * static_cast<float>(k) \/ static_cast<float>(fftFrameSize)));\r\n }\r\n\r\n \/*\r\n Routine process(). See top of file for explanation\r\n Purpose: doing pitch shifting while maintaining duration using the Short\r\n Time Fourier Transform.\r\n Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>\r\n *\/\r\n void process(const float pitchShift, const uint32_t numSampsToProcess,\r\n const uint32_t sampleRate, const float* indata, float* outdata) noexcept\r\n {\r\n \/\/ set up some handy variables\r\n constexpr uint32_t fftFrameSizeHalf = fftFrameSize \/ 2;\r\n constexpr uint32_t stepSize = fftFrameSize \/ oversamp;\r\n constexpr uint32_t inFifoLatency = fftFrameSize - stepSize;\r\n const float freqPerBin = static_cast<float>(sampleRate) \/ static_cast<float>(fftFrameSize);\r\n const float expected = 2.0F * pi * static_cast<float>(stepSize) \/ static_cast<float>(fftFrameSize);\r\n if (rover == 0) rover = inFifoLatency;\r\n\r\n \/\/ main processing loop\r\n for (uint32_t i = 0; i < numSampsToProcess; ++i)\r\n {\r\n \/\/ As long as we have not yet collected enough data just read in\r\n inFifo[rover] = indata[i];\r\n outdata[i] = outFifo[rover - inFifoLatency];\r\n ++rover;\r\n\r\n \/\/ now we have enough data for processing\r\n if (rover >= fftFrameSize)\r\n {\r\n rover = inFifoLatency;\r\n\r\n \/\/ do windowing\r\n for (uint32_t k = 0; k < fftFrameSize; ++k)\r\n fftWorksp[k] = { inFifo[k] * window[k], 0.0F };\r\n\r\n \/\/ ***************** ANALYSIS *******************\r\n \/\/ do transform\r\n fft<-1, fftFrameSize>(fftWorksp);\r\n\r\n \/\/ this is the analysis step\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; ++k)\r\n {\r\n const Complex<float>& current = fftWorksp[k];\r\n\r\n \/\/ compute magnitude and phase\r\n const float magn = 2.0F * current.magnitude();\r\n const float signx = (current.imag > 0.0F) ? 1.0F : -1.0F;\r\n const float phase = (current.imag == 0.0F) ? 0.0F :\r\n (current.real == 0.0F) ? signx * pi \/ 2.0F :\r\n std::atan2(current.imag, current.real);\r\n\r\n \/\/ compute phase difference\r\n float tmp = phase - lastPhase[k];\r\n lastPhase[k] = phase;\r\n\r\n \/\/ subtract expected phase difference\r\n tmp -= static_cast<float>(k) * expected;\r\n\r\n \/\/ map delta phase into +\/- Pi interval\r\n int32_t qpd = static_cast<int32_t>(tmp \/ pi);\r\n if (qpd >= 0) qpd += qpd & 1;\r\n else qpd -= qpd & 1;\r\n tmp -= pi * static_cast<float>(qpd);\r\n\r\n \/\/ get deviation from bin frequency from the +\/- Pi interval\r\n tmp = oversamp * tmp \/ (2.0F * pi);\r\n\r\n \/\/ compute the k-th partials' true frequency\r\n tmp = static_cast<float>(k) * freqPerBin + tmp * freqPerBin;\r\n\r\n \/\/ store magnitude and true frequency in analysis arrays\r\n anaMagn[k] = magn;\r\n anaFreq[k] = tmp;\r\n }\r\n\r\n \/\/ ***************** PROCESSING *******************\r\n \/\/ this does the actual pitch shifting\r\n std::fill(std::begin(synMagn), std::begin(synMagn) + fftFrameSize, 0.0F);\r\n std::fill(std::begin(synFreq), std::begin(synFreq) + fftFrameSize, 0.0F);\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; ++k)\r\n {\r\n const uint32_t index = static_cast<uint32_t>(k * pitchShift);\r\n if (index > fftFrameSizeHalf) break;\r\n synMagn[index] += anaMagn[k];\r\n synFreq[index] = anaFreq[k] * pitchShift;\r\n }\r\n\r\n \/\/ ***************** SYNTHESIS *******************\r\n \/\/ this is the synthesis step\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; ++k)\r\n {\r\n \/\/ get magnitude and true frequency from synthesis arrays\r\n const float magn = synMagn[k];\r\n float tmp = synFreq[k];\r\n\r\n \/\/ subtract bin mid frequency\r\n tmp -= static_cast<float>(k) * freqPerBin;\r\n\r\n \/\/ get bin deviation from freq deviation\r\n tmp \/= freqPerBin;\r\n\r\n \/\/ take oversampling factor into account\r\n tmp = 2.0F * pi * tmp \/ oversamp;\r\n\r\n \/\/ add the overlap phase advance back in\r\n tmp += static_cast<float>(k) * expected;\r\n\r\n \/\/ accumulate delta phase to get bin phase\r\n sumPhase[k] += tmp;\r\n const float phase = sumPhase[k];\r\n\r\n \/\/ get real and imag part and re-interleave\r\n fftWorksp[k] = { magn * std::cos(phase), magn * std::sin(phase) };\r\n }\r\n\r\n \/\/ zero negative frequencies\r\n for (uint32_t k = fftFrameSize + 1; k < fftFrameSize; ++k)\r\n fftWorksp[k] = {0.0F, 0.0F};\r\n\r\n \/\/ do inverse transform\r\n fft<1, fftFrameSize>(fftWorksp);\r\n\r\n \/\/ do windowing and add to output accumulator\r\n for (uint32_t k = 0; k < fftFrameSize; ++k)\r\n outputAccum[k] += 2.0F * window[k] * fftWorksp[k].real \/ (fftFrameSizeHalf * oversamp);\r\n\r\n uint32_t k;\r\n for (k = 0 ; k < stepSize; ++k)\r\n outFifo[k] = outputAccum[k];\r\n \/\/ shift accumulator\r\n uint32_t j;\r\n for (j = 0; k < fftFrameSize; ++k, ++j)\r\n outputAccum[j] = outputAccum[k];\r\n for (; j < fftFrameSize; ++j)\r\n outputAccum[j] = 0.0;\r\n\r\n \/\/ move input FIFO\r\n for (k = 0; k < inFifoLatency; ++k)\r\n inFifo[k] = inFifo[k + stepSize];\r\n }\r\n }\r\n }\r\n\r\n private:\r\n float window[fftFrameSize]; \/\/ the windowing function\r\n float inFifo[fftFrameSize]{0.0F};\r\n float outFifo[fftFrameSize]{0.0F};\r\n Complex<float> fftWorksp[fftFrameSize]{{0.0F, 0.0F}};\r\n float lastPhase[fftFrameSize \/ 2 + 1]{0.0F};\r\n float sumPhase[fftFrameSize \/ 2 + 1]{0.0F};\r\n float outputAccum[2 * fftFrameSize]{0.0F};\r\n float anaFreq[fftFrameSize]{0.0F};\r\n float anaMagn[fftFrameSize]{0.0F};\r\n float synFreq[fftFrameSize]{0.0F};\r\n float synMagn[fftFrameSize]{0.0F};\r\n uint32_t rover = 0;\r\n };\r\n}\r\n\r\n#endif\r\n<commit_msg>Make the constructor of PitchShift noexcept<commit_after>\/****************************************************************************\r\n*\r\n* NAME: smbPitchShift.cpp\r\n* VERSION: 1.2\r\n* HOME URL: http:\/\/blogs.zynaptiq.com\/bernsee\r\n* KNOWN BUGS: none\r\n*\r\n* SYNOPSIS: Routine for doing pitch shifting while maintaining\r\n* duration using the Short Time Fourier Transform.\r\n*\r\n* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5\r\n* (one octave down) and 2. (one octave up). A value of exactly 1 does not change\r\n* the pitch. numSampsToProcess tells the routine how many samples in indata[0...\r\n* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...\r\n* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the\r\n* data in-place). fftFrameSize defines the FFT frame size used for the\r\n* processing. Typical values are 1024, 2048 and 4096. It MUST be a power of 2.\r\n* oversamp is the STFT oversampling factor which also determines the overlap\r\n* between adjacent STFT frames. It should at least be 4 for moderate scaling\r\n* ratios. A value of 32 is recommended for best quality. sampleRate takes the\r\n* sample rate for the signal in unit Hz, ie. 44100 for 44.1 kHz audio. The data\r\n* passed to the routine in indata[] should be in the range [-1.0, 1.0), which is\r\n* also the output range for the data, make sure you scale the data accordingly\r\n* (for 16bit signed integers you would have to divide (and multiply) by 32768).\r\n*\r\n* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>\r\n*\r\n* \t\t\t\t\t\tThe Wide Open License (WOL)\r\n*\r\n* Permission to use, copy, modify, distribute and sell this software and its\r\n* documentation for any purpose is hereby granted without fee, provided that\r\n* the above copyright notice and this license appear in all source copies. \r\n* THIS SOFTWARE IS PROVIDED \"AS IS\" WITHOUT EXPRESS OR IMPLIED WARRANTY OF\r\n* ANY KIND. See http:\/\/www.dspguru.com\/wol.htm for more information.\r\n*\r\n*****************************************************************************\/\r\n\r\n#ifndef SMBPITCHSHIFT_HPP\r\n#define SMBPITCHSHIFT_HPP\r\n\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <cstdint>\r\n\r\nnamespace smb\r\n{\r\n namespace\r\n {\r\n constexpr float pi = 3.14159265358979323846F;\r\n\r\n \/\/ Use own implementation because std::complex has a poor performance\r\n template <class T>\r\n struct Complex final\r\n {\r\n constexpr Complex<T> operator+(const Complex& other) const noexcept\r\n {\r\n return Complex{real + other.real, imag + other.imag};\r\n }\r\n\r\n constexpr Complex<T>& operator+=(const Complex& other)\r\n {\r\n real += other.real;\r\n imag += other.imag;\r\n return *this;\r\n }\r\n\r\n constexpr Complex<T> operator-(const Complex& other) const noexcept\r\n {\r\n return Complex{real - other.real, imag - other.imag};\r\n }\r\n\r\n constexpr Complex<T> operator-() const noexcept\r\n {\r\n return Complex{-real, -imag};\r\n }\r\n\r\n constexpr Complex<T>& operator-=(const Complex& other) noexcept\r\n {\r\n real -= other.real;\r\n imag -= other.imag;\r\n return *this;\r\n }\r\n\r\n constexpr Complex<T> operator*(const Complex& other) const noexcept\r\n {\r\n return Complex{real * other.real - imag * other.imag, real * other.imag + imag * other.real};\r\n }\r\n\r\n constexpr Complex<T>& operator*=(const Complex& other) noexcept\r\n {\r\n float tempReal = real;\r\n real = tempReal * other.real - imag * other.imag;\r\n imag = tempReal * other.imag + imag * other.real;\r\n return *this;\r\n }\r\n\r\n inline T magnitude() const noexcept\r\n {\r\n return sqrt(real * real + imag * imag);\r\n }\r\n\r\n T real;\r\n T imag;\r\n };\r\n\r\n template <int32_t sign, uint32_t fftFrameSize>\r\n void fft(Complex<float>* fftBuffer) noexcept\r\n {\r\n \/\/ Bit-reversal permutation applied to a sequence of fftFrameSize items\r\n for (uint32_t i = 1; i < fftFrameSize - 1; ++i)\r\n {\r\n uint32_t j = 0;\r\n\r\n for (uint32_t bitm = 1; bitm < fftFrameSize; bitm <<= 1)\r\n {\r\n if (i & bitm) ++j;\r\n j <<= 1;\r\n }\r\n j >>= 1;\r\n\r\n if (i < j)\r\n std::swap(fftBuffer[i], fftBuffer[j]);\r\n }\r\n\r\n \/\/ Iterative form of Danielson–-Lanczos lemma\r\n uint32_t step = 2;\r\n for (uint32_t i = 1; i < fftFrameSize; i <<= 1, step <<= 1)\r\n {\r\n const uint32_t step2 = step >> 1;\r\n const float arg = pi \/ step2;\r\n\r\n const Complex<float> w{std::cos(arg), std::sin(arg) * sign};\r\n Complex<float> u{1.0F, 0.0F};\r\n for (uint32_t j = 0; j < step2; ++j)\r\n {\r\n for (uint32_t k = j; k < fftFrameSize; k += step)\r\n {\r\n const Complex<float> temp = fftBuffer[k + step2] * u;\r\n fftBuffer[k + step2] = fftBuffer[k] - temp;\r\n fftBuffer[k] += temp;\r\n }\r\n\r\n u *= w;\r\n }\r\n }\r\n }\r\n }\r\n\r\n template <uint32_t fftFrameSize, uint32_t oversamp>\r\n class PitchShift final\r\n {\r\n public:\r\n PitchShift() noexcept\r\n {\r\n \/\/ Hann window\r\n for (uint32_t k = 0; k < fftFrameSize; ++k)\r\n window[k] = 0.5F * (1.0F + std::cos(2.0F * pi * static_cast<float>(k) \/ static_cast<float>(fftFrameSize)));\r\n }\r\n\r\n \/*\r\n Routine process(). See top of file for explanation\r\n Purpose: doing pitch shifting while maintaining duration using the Short\r\n Time Fourier Transform.\r\n Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>\r\n *\/\r\n void process(const float pitchShift, const uint32_t numSampsToProcess,\r\n const uint32_t sampleRate, const float* indata, float* outdata) noexcept\r\n {\r\n \/\/ set up some handy variables\r\n constexpr uint32_t fftFrameSizeHalf = fftFrameSize \/ 2;\r\n constexpr uint32_t stepSize = fftFrameSize \/ oversamp;\r\n constexpr uint32_t inFifoLatency = fftFrameSize - stepSize;\r\n const float freqPerBin = static_cast<float>(sampleRate) \/ static_cast<float>(fftFrameSize);\r\n const float expected = 2.0F * pi * static_cast<float>(stepSize) \/ static_cast<float>(fftFrameSize);\r\n if (rover == 0) rover = inFifoLatency;\r\n\r\n \/\/ main processing loop\r\n for (uint32_t i = 0; i < numSampsToProcess; ++i)\r\n {\r\n \/\/ As long as we have not yet collected enough data just read in\r\n inFifo[rover] = indata[i];\r\n outdata[i] = outFifo[rover - inFifoLatency];\r\n ++rover;\r\n\r\n \/\/ now we have enough data for processing\r\n if (rover >= fftFrameSize)\r\n {\r\n rover = inFifoLatency;\r\n\r\n \/\/ do windowing\r\n for (uint32_t k = 0; k < fftFrameSize; ++k)\r\n fftWorksp[k] = { inFifo[k] * window[k], 0.0F };\r\n\r\n \/\/ ***************** ANALYSIS *******************\r\n \/\/ do transform\r\n fft<-1, fftFrameSize>(fftWorksp);\r\n\r\n \/\/ this is the analysis step\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; ++k)\r\n {\r\n const Complex<float>& current = fftWorksp[k];\r\n\r\n \/\/ compute magnitude and phase\r\n const float magn = 2.0F * current.magnitude();\r\n const float signx = (current.imag > 0.0F) ? 1.0F : -1.0F;\r\n const float phase = (current.imag == 0.0F) ? 0.0F :\r\n (current.real == 0.0F) ? signx * pi \/ 2.0F :\r\n std::atan2(current.imag, current.real);\r\n\r\n \/\/ compute phase difference\r\n float tmp = phase - lastPhase[k];\r\n lastPhase[k] = phase;\r\n\r\n \/\/ subtract expected phase difference\r\n tmp -= static_cast<float>(k) * expected;\r\n\r\n \/\/ map delta phase into +\/- Pi interval\r\n int32_t qpd = static_cast<int32_t>(tmp \/ pi);\r\n if (qpd >= 0) qpd += qpd & 1;\r\n else qpd -= qpd & 1;\r\n tmp -= pi * static_cast<float>(qpd);\r\n\r\n \/\/ get deviation from bin frequency from the +\/- Pi interval\r\n tmp = oversamp * tmp \/ (2.0F * pi);\r\n\r\n \/\/ compute the k-th partials' true frequency\r\n tmp = static_cast<float>(k) * freqPerBin + tmp * freqPerBin;\r\n\r\n \/\/ store magnitude and true frequency in analysis arrays\r\n anaMagn[k] = magn;\r\n anaFreq[k] = tmp;\r\n }\r\n\r\n \/\/ ***************** PROCESSING *******************\r\n \/\/ this does the actual pitch shifting\r\n std::fill(std::begin(synMagn), std::begin(synMagn) + fftFrameSize, 0.0F);\r\n std::fill(std::begin(synFreq), std::begin(synFreq) + fftFrameSize, 0.0F);\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; ++k)\r\n {\r\n const uint32_t index = static_cast<uint32_t>(k * pitchShift);\r\n if (index > fftFrameSizeHalf) break;\r\n synMagn[index] += anaMagn[k];\r\n synFreq[index] = anaFreq[k] * pitchShift;\r\n }\r\n\r\n \/\/ ***************** SYNTHESIS *******************\r\n \/\/ this is the synthesis step\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; ++k)\r\n {\r\n \/\/ get magnitude and true frequency from synthesis arrays\r\n const float magn = synMagn[k];\r\n float tmp = synFreq[k];\r\n\r\n \/\/ subtract bin mid frequency\r\n tmp -= static_cast<float>(k) * freqPerBin;\r\n\r\n \/\/ get bin deviation from freq deviation\r\n tmp \/= freqPerBin;\r\n\r\n \/\/ take oversampling factor into account\r\n tmp = 2.0F * pi * tmp \/ oversamp;\r\n\r\n \/\/ add the overlap phase advance back in\r\n tmp += static_cast<float>(k) * expected;\r\n\r\n \/\/ accumulate delta phase to get bin phase\r\n sumPhase[k] += tmp;\r\n const float phase = sumPhase[k];\r\n\r\n \/\/ get real and imag part and re-interleave\r\n fftWorksp[k] = { magn * std::cos(phase), magn * std::sin(phase) };\r\n }\r\n\r\n \/\/ zero negative frequencies\r\n for (uint32_t k = fftFrameSize + 1; k < fftFrameSize; ++k)\r\n fftWorksp[k] = {0.0F, 0.0F};\r\n\r\n \/\/ do inverse transform\r\n fft<1, fftFrameSize>(fftWorksp);\r\n\r\n \/\/ do windowing and add to output accumulator\r\n for (uint32_t k = 0; k < fftFrameSize; ++k)\r\n outputAccum[k] += 2.0F * window[k] * fftWorksp[k].real \/ (fftFrameSizeHalf * oversamp);\r\n\r\n uint32_t k;\r\n for (k = 0 ; k < stepSize; ++k)\r\n outFifo[k] = outputAccum[k];\r\n \/\/ shift accumulator\r\n uint32_t j;\r\n for (j = 0; k < fftFrameSize; ++k, ++j)\r\n outputAccum[j] = outputAccum[k];\r\n for (; j < fftFrameSize; ++j)\r\n outputAccum[j] = 0.0;\r\n\r\n \/\/ move input FIFO\r\n for (k = 0; k < inFifoLatency; ++k)\r\n inFifo[k] = inFifo[k + stepSize];\r\n }\r\n }\r\n }\r\n\r\n private:\r\n float window[fftFrameSize]; \/\/ the windowing function\r\n float inFifo[fftFrameSize]{0.0F};\r\n float outFifo[fftFrameSize]{0.0F};\r\n Complex<float> fftWorksp[fftFrameSize]{{0.0F, 0.0F}};\r\n float lastPhase[fftFrameSize \/ 2 + 1]{0.0F};\r\n float sumPhase[fftFrameSize \/ 2 + 1]{0.0F};\r\n float outputAccum[2 * fftFrameSize]{0.0F};\r\n float anaFreq[fftFrameSize]{0.0F};\r\n float anaMagn[fftFrameSize]{0.0F};\r\n float synFreq[fftFrameSize]{0.0F};\r\n float synMagn[fftFrameSize]{0.0F};\r\n uint32_t rover = 0;\r\n };\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>#include <mbed.h>\n#include \"ReceiverIR.h\"\n\nSerial pc(USBTX, USBRX); \/\/ tx, rx\nReceiverIR ir_rx(p3);\nTicker ledTicker;\n\nint receive(RemoteIR::Format *format, uint8_t *buf, int bufsiz, int timeout = 100) {\n int cnt = 0;\n while (ir_rx.getState() != ReceiverIR::Received) {\n cnt++;\n if (timeout < cnt) {\n return -1;\n }\n }\n\t\n return ir_rx.getData(format, buf, bufsiz * 8);\n}\n\nint main(void) {\n\n while (1) {\n uint8_t buf1[32];\n int bitlength1;\n RemoteIR::Format format;\n\n memset(buf1, 0x00, sizeof(buf1));\n\n {\n bitlength1 = receive(&format, buf1, sizeof(buf1));\n if (bitlength1 < 0) {\n continue;\n }\n\t\t \n\t\t\tconst int n = bitlength1 \/ 8 + (((bitlength1 % 8) != 0) ? 1 : 0);\n\t\t for (int i = 0; i < n; i++) {\n\t\t pc.printf(\"%02X\", buf1[i]);\n\t\t }\n }\n }\n}<commit_msg>Display button pressed<commit_after>#include <mbed.h>\n#include \"ReceiverIR.h\"\n#include \"MicroBit.h\"\n\nSerial pc(USBTX, USBRX); \/\/ tx, rx\nReceiverIR ir_rx(p3);\nTicker ledTicker;\n\nint receive(RemoteIR::Format *format, uint8_t *buf, int bufsiz, int timeout = 100) {\n int cnt = 0;\n while (ir_rx.getState() != ReceiverIR::Received) {\n cnt++;\n if (timeout < cnt) {\n return -1;\n }\n }\n\t\n return ir_rx.getData(format, buf, bufsiz * 8);\n}\n\nint main(void) {\n\t\n MicroBitDisplay display;\n\tdisplay.scroll(\"Press a button on the remote :)\");\n\t\n\t\n while (1) {\n uint8_t buf1[32];\n int bitlength1;\n RemoteIR::Format format;\n\n memset(buf1, 0x00, sizeof(buf1));\n {\n bitlength1 = receive(&format, buf1, sizeof(buf1));\n if (bitlength1 < 0) {\n continue;\n }\n\t\t \n\t\t\tconst int n = bitlength1 \/ 8 + (((bitlength1 % 8) != 0) ? 1 : 0);\n\t\t\t\n\t\t\tif (buf1[0] == 0x00 && buf1[1] == 0xBF) {\n\t\t\t\tif (buf1[2] == 0x00 && buf1[3] == 0xFF) {\n\t\t\t\t\tdisplay.printChar('1');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x01 && buf1[3] == 0xFE) {\n\t\t\t\t\tdisplay.printChar('2');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x02 && buf1[3] == 0xFD) {\n\t\t\t\t\tdisplay.printChar('3');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x04 && buf1[3] == 0xFB) {\n\t\t\t\t\tdisplay.printChar('4');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x05 && buf1[3] == 0xFA) {\n\t\t\t\t\tdisplay.printChar('5');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x06 && buf1[3] == 0xF9) {\n\t\t\t\t\tdisplay.printChar('6');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x08 && buf1[3] == 0xF7) {\n\t\t\t\t\tdisplay.printChar('7');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x09 && buf1[3] == 0xF6) {\n\t\t\t\t\tdisplay.printChar('8');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x0A && buf1[3] == 0xF5) {\n\t\t\t\t\tdisplay.printChar('9');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x0D && buf1[3] == 0xF2) {\n\t\t\t\t\tdisplay.printChar('0');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x0C && buf1[3] == 0xF3) {\n\t\t\t\t\tdisplay.printChar('*');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x0E && buf1[3] == 0xF1) {\n\t\t\t\t\tdisplay.printChar('#');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x14 && buf1[3] == 0xEB) {\n\t\t\t\t\tdisplay.printChar('L');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x16 && buf1[3] == 0xE9) {\n\t\t\t\t\tdisplay.printChar('R');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x11 && buf1[3] == 0xEE) {\n\t\t\t\t\tdisplay.printChar('U');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x19 && buf1[3] == 0xE6) {\n\t\t\t\t\tdisplay.printChar('D');\n\t\t\t\t}\n\t\t\t\tif (buf1[2] == 0x15 && buf1[3] == 0xEA) {\n\t\t\t\t\tdisplay.scroll(\"OK!\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ echo to serial port\n\t\t for (int i = 0; i < n; i++) {\n\t\t pc.printf(\"%02X\", buf1[i]);\n\t\t }\n\t\t\t\n\t\t\tpc.printf(\"\\n\\r\");\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ErrorEstimator.h\"\n\n\/\/ from STL\n#include <algorithm>\n\n\/\/ from RooFit\n#include \"RooMultiVarGaussian.h\"\n#include \"TMatrixDSym.h\"\n#include \"RooArgList.h\"\n#include \"RooArgSet.h\"\n#include \"RooAbsArg.h\"\n#include \"RooRealVar.h\"\n#include \"RooDataSet.h\"\n\n\/\/ from DooCore\n#include \"doocore\/io\/MsgStream.h\"\n#include \"doocore\/statistics\/general.h\"\n\ndoocore::statistics::montecarlo::MultiVarGaussianSampleGenerator::MultiVarGaussianSampleGenerator(const RooArgList& values_expected, const TMatrixDSym& covariance)\n: mvg_(NULL),\nvalues_expected_(new RooArgSet(values_expected)),\nvalues_mu_(new RooArgList()),\nnum_generated_(0),\npos_dataset_(0),\ndataset_(NULL) {\n using namespace doocore::io;\n \n\n TIterator* it = values_expected.createIterator();\n RooAbsArg* arg = NULL;\n \n while ((arg = dynamic_cast<RooAbsArg*>(it->Next()))) {\n RooRealVar* var = dynamic_cast<RooRealVar*>(arg);\n if (var != NULL) {\n std::string name_copy(std::string(var->GetName())+\"_mu\");\n RooRealVar* var_copy = new RooRealVar(*var, name_copy.c_str());\n values_mu_->addOwned(*var_copy);\n }\n }\n delete it;\n \n mvg_ = new RooMultiVarGaussian(\"mvg\", \"mvg\", *values_expected_, *values_mu_, covariance);\n}\n\ndoocore::statistics::montecarlo::MultiVarGaussianSampleGenerator::~MultiVarGaussianSampleGenerator() {\n delete mvg_;\n delete values_expected_;\n delete values_mu_;\n if (dataset_ != NULL) {\n delete dataset_;\n }\n}\n\nconst RooArgSet* doocore::statistics::montecarlo::MultiVarGaussianSampleGenerator::Generate() {\n using namespace doocore::io;\n \n const RooArgSet* values;\n pos_dataset_++;\n if (dataset_ == NULL || pos_dataset_ >= dataset_->numEntries()) {\n pos_dataset_ = 0;\n int num_generate = std::max(100, 2*static_cast<int>(num_generated_));\n num_generated_ += num_generate;\n if (dataset_ != NULL) {\n delete dataset_;\n }\n \n \n dataset_ = mvg_->generate(*values_expected_, num_generate);\n }\n \n values = dataset_->get(pos_dataset_);\n return values;\n}<commit_msg>Statistics: bugfix in MultiVarGaussianSampleGenerator<commit_after>#include \"ErrorEstimator.h\"\n\n\/\/ from STL\n#include <algorithm>\n\n\/\/ from RooFit\n#include \"RooMultiVarGaussian.h\"\n#include \"TMatrixDSym.h\"\n#include \"RooArgList.h\"\n#include \"RooArgSet.h\"\n#include \"RooAbsArg.h\"\n#include \"RooRealVar.h\"\n#include \"RooDataSet.h\"\n\n\/\/ from DooCore\n#include \"doocore\/io\/MsgStream.h\"\n#include \"doocore\/statistics\/general.h\"\n\ndoocore::statistics::montecarlo::MultiVarGaussianSampleGenerator::MultiVarGaussianSampleGenerator(const RooArgList& values_expected, const TMatrixDSym& covariance)\n: mvg_(NULL),\nvalues_expected_(new RooArgSet()),\nvalues_mu_(new RooArgList()),\nnum_generated_(0),\npos_dataset_(0),\ndataset_(NULL) {\n using namespace doocore::io;\n \n\n TIterator* it = values_expected.createIterator();\n RooAbsArg* arg = NULL;\n \n while ((arg = dynamic_cast<RooAbsArg*>(it->Next()))) {\n RooRealVar* var = dynamic_cast<RooRealVar*>(arg);\n if (var != NULL) {\n RooRealVar* var_copy = new RooRealVar(*var, var->GetName());\n values_expected_->addOwned(*var_copy);\n\n std::string name_copy(std::string(var->GetName())+\"_mu\");\n RooRealVar* var_copy_mu = new RooRealVar(*var, name_copy.c_str());\n values_mu_->addOwned(*var_copy_mu);\n }\n }\n delete it;\n \n mvg_ = new RooMultiVarGaussian(\"mvg\", \"mvg\", *values_expected_, *values_mu_, covariance);\n}\n\ndoocore::statistics::montecarlo::MultiVarGaussianSampleGenerator::~MultiVarGaussianSampleGenerator() {\n delete mvg_;\n delete values_expected_;\n delete values_mu_;\n if (dataset_ != NULL) {\n delete dataset_;\n }\n}\n\nconst RooArgSet* doocore::statistics::montecarlo::MultiVarGaussianSampleGenerator::Generate() {\n using namespace doocore::io;\n \n const RooArgSet* values;\n pos_dataset_++;\n if (dataset_ == NULL || pos_dataset_ >= dataset_->numEntries()) {\n pos_dataset_ = 0;\n int num_generate = std::max(100, 2*static_cast<int>(num_generated_));\n num_generated_ += num_generate;\n if (dataset_ != NULL) {\n delete dataset_;\n }\n \n\/\/ values_expected_->Print();\n\/\/ values_mu_->Print();\n dataset_ = mvg_->generate(*values_expected_, num_generate);\n }\n \n values = dataset_->get(pos_dataset_);\n return values;\n}<|endoftext|>"} {"text":"<commit_before>\n\n#include <math.h>\n\n#ifdef __APPLE__\n#include <OpenGL\/gl.h>\n#include <OpenGL\/glu.h>\n#include <Glut\/glut.h>\n#else\n #define FREEGLUT_STATIC\n #include <GL\\glut.h>\n#endif\n\n\/\/ Initial size of graphics window.\nconst int WIDTH = 600;\nconst int HEIGHT = 400;\n\n\/\/ Current size of window.\nint width = WIDTH;\nint height = HEIGHT;\n\n\/\/ Bounds of viewing frustum.\ndouble nearPlane = 1.0;\ndouble farPlane = 85.0;\n\n\/\/ Viewing angle.\ndouble fovy = 45.0;\n\nstatic GLint rotX = 0;\nstatic GLint rotY = 0;\n\nstatic int choice = 0;\n\nvoid drawRectangle()\n{\n\t\/\/phaser base\n\tglBegin(GL_TRIANGLE_STRIP);\n\t\tglVertex3f(-1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, -1.0f);\n\t\tglVertex3f(1.0f, 0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, 1.0f);\n\tglEnd();\n\n\tglBegin(GL_TRIANGLES);\n\t\tglVertex3f(1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(1.0f, 0.5f, -1.0f);\n\t\tglVertex3f(1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, -1.0f);\n\tglEnd();\n\n\tglBegin(GL_TRIANGLES);\n\t\tglVertex3f(-1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, -1.0f);\n\tglEnd();\n}\n\nvoid drawCylinder(GLint degrees)\n{\n\tconst GLfloat PI_TO_DEGREE_RATIO = 3.14159265 \/ 180;\n\n\tGLfloat radius = 1.0f;\n\tGLfloat height = 1.5f;\n\tGLint increment = 10;\n\t\n\tglPushMatrix();\n\n\t\tglTranslatef(-radius\/2, -height\/2, -radius\/2);\n\n\t\tglBegin(GL_POLYGON);\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\t\tfor (int i = 0; i <= degrees; i += increment)\n\t\t\t{\n\t\t\t\tGLfloat angle = i;\n\t\t\t\tglVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t}\n\t\tglEnd();\n\t\t\n\t\tglBegin(GL_POLYGON);\n\t\t\tglVertex3f(0.0f, height, 0.0f);\n\t\t\tfor (int i = 0; i <= degrees; i += increment)\n\t\t\t{\n\t\t\t\tGLfloat angle = i;\n\t\t\t\tglVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t}\n\t\tglEnd();\n\t\n\t\tglBegin(GL_TRIANGLES); \/\/ 2 triangles on the Z axis\n\t\t\tglVertex3f(0.0f, 0.0f, radius);\n\t\t\tglVertex3f(0.0f, height, -radius);\n\t\t\tglVertex3f(0.0f, 0.0f, -radius);\n\t\t\tglVertex3f(0.0f, 0.0f, radius);\n\t\t\tglVertex3f(0.0f, height, radius);\n\t\t\tglVertex3f(0.0f, height, -radius);\n\t\t\tglVertex3f(0.0f, height, radius);\n\t\tglEnd();\n\n\t\t\/*\n\t\tglBegin(GL_TRIANGLES); \/\/ 2 triangles on X\n\t\t\tglVertex3f(radius, 0.0f, 0.0f);\n\t\t\tglVertex3f(0.0f, height, 0.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(radius, 0.0f, 0.0f);\n\t\t\tglVertex3f(radius, height, 0.0f);\n\t\t\tglVertex3f(0.0f, height, 0.0f);\n\t\t\tglVertex3f(radius, height, 0.0f);\n\t\tglEnd();\n\t\t*\/\n\n\t\tfor (int i = 0; i < degrees; i += increment) \/\/all the triangles along the perimeter\n\t\t{\n\t\t\tGLint angleNext = i + increment;\n\t\t\tGLfloat angle = i;\n\n\t\t\tglBegin(GL_POLYGON);\n\t\t\t\tglVertex3f(0.0f + sin(angleNext * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angleNext * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t\tglVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t\tglVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t\tglVertex3f(0.0f + sin(angleNext * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angleNext * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t\tglVertex3f(0.0f + sin(angleNext * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angleNext * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t\tglVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t\tglVertex3f(0.0f + sin(angleNext * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angleNext * PI_TO_DEGREE_RATIO) * radius);\n\t\t\tglEnd();\n\t\t}\n\n\tglPopMatrix();\n}\n\n\nvoid drawPhaserCannon()\n{\n\tglEnable(GL_DEPTH_TEST);\n\t\/\/back panel\n\tglPushMatrix();\n\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\tglTranslatef(1.0f, 0.0f, 0.0f);\n\t\tglScalef(1.2f, 1.0f, 1.2f);\n\t\tdrawCylinder(180);\n\tglPopMatrix();\n\n\t\/\/cannon barrel\n\tglPushMatrix();\n\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\tglTranslatef(-0.1f, 0.0f, -0.55f);\n\t\tglScalef(0.5f, 1.1f, 0.4f);\n\t\tdrawRectangle();\n\tglPopMatrix();\n\n\t\/\/cannon base\n\tglPushMatrix();\n\t\tglColor3f(0,1,0);\n\t\tglTranslatef(1.1f, -1.1f, -0.1f);\n\t\tglScalef(0.9f, 0.5f, 0.9f);\n\t\tdrawCylinder(360);\n\tglPopMatrix();\n}\n\n\/\/sets up rendering context\nvoid render()\n{\n\t\/\/clears the buffer\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\t\/\/preps the \n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\n\tglRotatef(rotX * 10, 1, 0, 0);\n\tglRotatef(rotY * 10, 0, 1, 0);\n\t\n\tif (choice == 1) \/\/draw a cylinder\t\n\t\tdrawRectangle();\n\telse if (choice == 0) \/\/draw half a cylinder\n\t\tdrawPhaserCannon();\n\t\n\tglutSwapBuffers();\n\t\n}\n\n\n\n\/\/ Respond to window resizing, preserving proportions.\nvoid reshapeMainWindow (int newWidth, int newHeight)\n{\n\twidth = newWidth;\n\theight = newHeight;\n\tglViewport(0, 0, width, height);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(fovy, GLfloat(width) \/ GLfloat(height), nearPlane, farPlane);\n\tgluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0);\n}\n\nvoid functionKeys(int key, int x, int y)\n{\n\tswitch (key)\n\t{\n\tcase GLUT_KEY_LEFT:\n\t\trotY++;\n\t\tbreak;\n\t\n\tcase GLUT_KEY_RIGHT:\n\t\trotY--;\n\t\tbreak;\n\n\tcase GLUT_KEY_UP:\n\t\trotX++;\n\t\tbreak;\n\n\tcase GLUT_KEY_DOWN:\n\t\trotX--;\n\t\tbreak;\n\t}\n\tglutPostRedisplay();\n}\n\nvoid keyboardKeys(unsigned char key, int x, int y)\n{\n\tswitch (key)\n\t{\n\tcase 'q':\n\t\tchoice = ++choice % 2; \n\t\tbreak;\n\n\tcase 27:\n\t\texit(0);\n\t}\n\n\tglutPostRedisplay();\n}\n\nint main (int argc, char **argv)\n{\n\t\/\/ GLUT initialization.\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);\n\tglutInitWindowSize(width, height);\n\tglutCreateWindow(\"Robot mids\");\n\n\t\/\/callbacks\t\n\tglutReshapeFunc(reshapeMainWindow);\n\tglutDisplayFunc(render);\n\tglutSpecialFunc(functionKeys);\n\tglutKeyboardFunc(keyboardKeys);\n\n\tglutMainLoop();\n\n\treturn 0;\n}<commit_msg>cylinder, rectangle, prisms.<commit_after>\n\n#include <math.h>\n\n#ifdef __APPLE__\n#include <OpenGL\/gl.h>\n#include <OpenGL\/glu.h>\n#include <Glut\/glut.h>\n#else\n #define FREEGLUT_STATIC\n #include <GL\\glut.h>\n#endif\n\n\/\/ Initial size of graphics window.\nconst int WIDTH = 600;\nconst int HEIGHT = 400;\n\n\/\/ Current size of window.\nint width = WIDTH;\nint height = HEIGHT;\n\n\/\/ Bounds of viewing frustum.\ndouble nearPlane = 1.0;\ndouble farPlane = 85.0;\n\n\/\/ Viewing angle.\ndouble fovy = 45.0;\n\nstatic GLint rotX = 0;\nstatic GLint rotY = 0;\n\nstatic int choice = 0;\n\nvoid drawRectangle()\n{\n\t\/\/phaser base\n\tglBegin(GL_TRIANGLE_STRIP);\n\t\tglVertex3f(-1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, -1.0f);\n\t\tglVertex3f(1.0f, 0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, 1.0f);\n\tglEnd();\n\n\tglBegin(GL_TRIANGLES);\n\t\tglVertex3f(1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(1.0f, 0.5f, -1.0f);\n\t\tglVertex3f(1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(1.0f, -0.5f, -1.0f);\n\tglEnd();\n\n\tglBegin(GL_TRIANGLES);\n\t\tglVertex3f(-1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, -1.0f);\n\t\tglVertex3f(-1.0f, 0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, 1.0f);\n\t\tglVertex3f(-1.0f, -0.5f, -1.0f);\n\tglEnd();\n}\n\nvoid drawCylinder(GLint degrees)\n{\n\tconst GLfloat PI_TO_DEGREE_RATIO = 3.14159265 \/ 180;\n\n\tGLfloat radius = 1.0f;\n\tGLfloat height = 1.5f;\n\tGLint increment = 10;\n\t\n\tglPushMatrix();\n\n\t\tglTranslatef(-radius\/2, -height\/2, -radius\/2);\n\n\t\tglBegin(GL_POLYGON);\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\t\tfor (int i = 0; i <= degrees; i += increment)\n\t\t\t{\n\t\t\t\tGLfloat angle = i;\n\t\t\t\tglVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t}\n\t\tglEnd();\n\t\t\n\t\tglBegin(GL_POLYGON);\n\t\t\tglVertex3f(0.0f, height, 0.0f);\n\t\t\tfor (int i = 0; i <= degrees; i += increment)\n\t\t\t{\n\t\t\t\tGLfloat angle = i;\n\t\t\t\tglVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);\n\t\t\t}\n\t\tglEnd();\n\t\n\t\tglBegin(GL_TRIANGLES); \/\/ 2 triangles on the Z axis\n\t\t\tglVertex3f(0.0f, 0.0f, radius);\n\t\t\tglVertex3f(0.0f, height, -radius);\n\t\t\tglVertex3f(0.0f, 0.0f, -radius);\n\t\t\tglVertex3f(0.0f, 0.0f, radius);\n\t\t\tglVertex3f(0.0f, height, radius);\n\t\t\tglVertex3f(0.0f, height, -radius);\n\t\t\tglVertex3f(0.0f, height, radius);\n\t\tglEnd();\n\n\t\t\/*\n\t\tglBegin(GL_TRIANGLES); \/\/ 2 triangles on X\n\t\t\tglVertex3f(radius, 0.0f, 0.0f);\n\t\t\tglVertex3f(0.0f, height, 0.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(radius, 0.0f, 0.0f);\n\t\t\tglVertex3f(radius, height, 0.0f);\n\t\t\tglVertex3f(0.0f, height, 0.0f);\n\t\t\tglVertex3f(radius, height, 0.0f);\n\t\tglEnd();\n\t\t*\/\n\n\t\tfor (int i = 0; i < degrees; i += increment) \/\/all the triangles along the perimeter\n\t\t{\n\t\t\tGLint angleNext = i + increment;\n\t\t\tGLfloat angle = i;\n\n\t\t\tGLfloat x0 = sin(angle * PI_TO_DEGREE_RATIO) * radius;\n\t\t\tGLfloat x1 = sin(angleNext * PI_TO_DEGREE_RATIO) * radius;\n\t\t\tGLfloat z0 = cos(angle * PI_TO_DEGREE_RATIO) * radius;\n\t\t\tGLfloat z1 = cos(angleNext * PI_TO_DEGREE_RATIO) * radius;\n\n\t\t\tglBegin(GL_POLYGON);\n\t\t\t\tglVertex3f(x1, 0.0f, z1);\n\t\t\t\tglVertex3f(x0, height, z0);\n\t\t\t\tglVertex3f(x0, 0.0f, z0);\n\t\t\t\tglVertex3f(x1, 0.0f, z1);\n\t\t\t\tglVertex3f(x1, height, z1);\n\t\t\t\tglVertex3f(x0, height, z0);\n\t\t\t\tglVertex3f(x1, 0.0f, z1);\n\t\t\tglEnd();\n\t\t}\n\n\tglPopMatrix();\n}\n\nvoid drawTriangularPrism()\n{\n\tglPushMatrix();\n\t\tglRotatef(-135.0f, 0.0f, 0.0f, 1.0f);\n\t\tglTranslatef(-0.5f, -0.25f, 0.5f);\n\t\t\n\t\tglBegin(GL_TRIANGLES); \/\/base 1\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\tglEnd();\n\n\t\tglBegin(GL_TRIANGLES); \/\/base 2\n\t\t\tglVertex3f(0.0f, 0.0f, -1.0f);\n\t\t\tglVertex3f(1.0f, 0.0f, -1.0f);\n\t\t\tglVertex3f(0.5f, 0.5f, -1.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, -1.0f);\n\t\tglEnd();\n\n\t\tglBegin(GL_TRIANGLES); \/\/the \"under part\"\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, -1.0f);\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(1.0f, 0.0f, -1.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, -1.0f);\n\t\t\tglVertex3f(1.0f, 0.0f, -1.0f);\n\t\tglEnd();\n\n\t\tglBegin(GL_TRIANGLES); \/\/the \"top left part\"\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, -1.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\n\t\t\tglVertex3f(0.5f, 0.5f, -1.0f);\n\t\t\tglVertex3f(0.0f, 0.0f, -1.0f);\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\n\t\tglEnd();\n\n\t\tglBegin(GL_TRIANGLES); \/\/the \"top right part\"\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\n\t\t\tglVertex3f(0.5f, 0.5f, -1.0f);\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(0.5f, 0.5f, -1.0f);\n\t\t\tglVertex3f(1.0f, 0.0f, -1.0f);\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\n\t\tglEnd();\n\n\tglPopMatrix();\n}\n\nvoid drawTrapezoidalPrism()\n{\n\tglPushMatrix();\n\t\tglTranslatef(-0.5f, 0.25f, 0.0f);\n\t\t\n\t\tglPushMatrix();\n\t\t\tglTranslatef(0.0f, -0.24f, 0.0f);\n\t\t\tglScalef(1.0f, 1.4f, 2.0f);\n\t\t\tdrawTriangularPrism();\n\t\tglPopMatrix();\n\n\t\tglPushMatrix();\n\t\t\tglTranslatef(1.0f, 0.0f, 0.0f);\n\t\t\tglScalef(0.8f, 1.0f, 1.0f);\n\t\t\tdrawRectangle();\n\t\tglPopMatrix();\n\tglPopMatrix();\n}\n\nvoid drawPhaserCannon()\n{\n\tglEnable(GL_DEPTH_TEST);\n\tglTranslatef(-0.9f, 0.9f, 0.5f);\n\n\t\/\/back panel\n\tglPushMatrix();\n\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\tglTranslatef(1.0f, 0.0f, 0.0f);\n\t\tglScalef(1.2f, 1.0f, 1.2f);\n\t\tdrawCylinder(180);\n\tglPopMatrix();\n\n\t\/\/cannon barrel\n\tglPushMatrix();\n\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\tglTranslatef(-0.1f, 0.0f, -0.6f);\n\t\tglScalef(0.5f, 1.1f, 0.4f);\n\t\tdrawRectangle();\n\tglPopMatrix();\n\n\t\/\/cannon base\n\tglPushMatrix();\n\t\tglColor3f(0,1,0);\n\t\tglTranslatef(1.1f, -1.1f, -0.125f);\n\t\tglScalef(0.9f, 0.5f, 0.9f);\n\t\tdrawCylinder(360);\n\tglPopMatrix();\n}\n\nvoid drawMissileLauncher()\n{\n\tglRotatef(-90, 0.0f, 1.0f, 0.0f);\n\n\tglPushMatrix();\n\t\tglColor3f(1.0f, 4.0f, 0.0f);\n\t\tglScalef(1.1f, 0.9f, 0.8f);\n\t\tdrawRectangle();\n\tglPopMatrix();\n\n\tglPushMatrix();\n\t\tglColor3f(0.5f, 0.0f, 0.5f);\n\t\tglPushMatrix();\n\t\t\tglTranslatef(-1.3f, -0.5f, 0.0f);\n\t\t\tglRotatef(90, 1.0f, 0.0f, 0.0f);\n\t\t\tglScalef(0.3f, 1.7f, 0.3f);\n\t\t\tdrawCylinder(360);\n\t\tglPopMatrix();\n\n\t\tglPushMatrix();\n\t\t\tglColor3f(0.5f, 0.0f, 0.5f);\n\t\t\tglTranslatef(1.6f, -0.5f, 0.0f);\n\t\t\tglRotatef(90, 1.0f, 0.0f, 0.0f);\n\t\t\tglScalef(0.3f, 1.7f, 0.3f);\n\t\t\tdrawCylinder(360);\n\t\tglPopMatrix();\n\tglPopMatrix();\n}\n\nvoid drawCannon()\n{\n\tglPushMatrix();\n\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\tdrawTrapezoidalPrism();\n\tglPopMatrix();\n\n\tglPushMatrix();\n\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\tglTranslatef(-0.9f, 0.35f, 0.5f);\n\t\tglRotatef(90, 0.0f, 0.0f, 1.0f);\n\t\tglScalef(0.1f, 0.6, 0.1f);\n\t\tdrawCylinder(360);\n\tglPopMatrix();\n\n\tglPushMatrix();\n\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\tglTranslatef(-0.9f, 0.35f, -0.5f);\n\t\tglRotatef(90, 0.0f, 0.0f, 1.0f);\n\t\tglScalef(0.1f, 0.6, 0.1f);\n\t\tdrawCylinder(360);\n\tglPopMatrix();\n}\n\nvoid render()\n{\n\t\/\/clears the buffer\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\n\tglRotatef(rotX * 10, 1, 0, 0);\n\tglRotatef(rotY * 10, 0, 1, 0);\n\n\tswitch (choice)\n\t{\n\tcase 0:\n\t\tdrawCannon();\n\t\tbreak;\n\tcase 1:\n\t\tdrawMissileLauncher();\n\t\tbreak;\n\tcase 2:\n\t\tdrawPhaserCannon();\n\t\tbreak;\n\t}\n\t\n\tglutSwapBuffers();\n}\n\n\n\n\/\/ Respond to window resizing, preserving proportions.\nvoid reshapeMainWindow (int newWidth, int newHeight)\n{\n\twidth = newWidth;\n\theight = newHeight;\n\tglViewport(0, 0, width, height);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(fovy, GLfloat(width) \/ GLfloat(height), nearPlane, farPlane);\n\tgluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0);\n}\n\nvoid functionKeys(int key, int x, int y)\n{\n\tswitch (key)\n\t{\n\tcase GLUT_KEY_LEFT:\n\t\trotY++;\n\t\tbreak;\n\t\n\tcase GLUT_KEY_RIGHT:\n\t\trotY--;\n\t\tbreak;\n\n\tcase GLUT_KEY_UP:\n\t\trotX++;\n\t\tbreak;\n\n\tcase GLUT_KEY_DOWN:\n\t\trotX--;\n\t\tbreak;\n\t}\n\tglutPostRedisplay();\n}\n\nvoid keyboardKeys(unsigned char key, int x, int y)\n{\n\tswitch (key)\n\t{\n\tcase 'q':\n\t\tchoice = ++choice % 3; \n\t\tbreak;\n\n\tcase 27:\n\t\texit(0);\n\t}\n\n\tglutPostRedisplay();\n}\n\nvoid init()\n{\n\tglEnable(GL_DEPTH_TEST);\n}\n\nint main (int argc, char **argv)\n{\n\t\/\/ GLUT initialization.\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);\n\tglutInitWindowSize(width, height);\n\tglutCreateWindow(\"Robot mids\");\n\n\t\/\/callbacks\t\n\tglutReshapeFunc(reshapeMainWindow);\n\tglutDisplayFunc(render);\n\tglutSpecialFunc(functionKeys);\n\tglutKeyboardFunc(keyboardKeys);\n\n\tinit();\n\n\tglutMainLoop();\n\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010 Chris Williams <chris@iterativedesigns.com>\n#include \"serialport_native.h\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <assert.h>\n#include <string.h>\n#include <errno.h>\n#include <limits.h>\n\n#include <termios.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/signal.h>\n#include <sys\/types.h>\n\n#include <node.h>\n#include <node_events.h>\n#include <node_buffer.h>\n#include <v8.h>\n\nusing namespace v8;\nusing namespace node;\n\n\n\n\/\/ static Persistent<String> encoding_symbol;\n\/\/ static Persistent<String> errno_symbol;\n\n\/\/ #define THROW_BAD_ARGS ThrowException(Exception::TypeError(String::New(\"Bad argument\")))\n\/\/ \n\/\/ static inline Local<Value> errno_exception(int errorno) {\n\/\/ Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));\n\/\/ Local<Object> obj = e->ToObject();\n\/\/ obj->Set(errno_symbol, Integer::New(errorno));\n\/\/ return e;\n\/\/ }\n\n\n\n\n\nstatic Persistent<String> data_symbol;\nstatic Persistent<String> close_symbol;\n\n\n\nclass SerialPort : public EventEmitter {\npublic:\n static void\n Initialize (v8::Handle<v8::Object> target)\n {\n HandleScope scope;\n Local<FunctionTemplate> t = FunctionTemplate::New(New);\n\n t->Inherit(EventEmitter::constructor_template);\n t->InstanceTemplate()->SetInternalFieldCount(1);\n \n data_symbol = NODE_PSYMBOL(\"data\");\n\t close_symbol = NODE_PSYMBOL(\"close\");\n \n NODE_SET_PROTOTYPE_METHOD(t, \"open\", Open);\n NODE_SET_PROTOTYPE_METHOD(t, \"close\", Close);\n NODE_SET_PROTOTYPE_METHOD(t, \"write\", Write);\n target->Set(String::NewSymbol(\"SerialPort\"), t->GetFunction());\n \n }\n \n \n void signal_handler_IO (int status)\n {\n\t\tprintf(\"%i\", status);\n printf(\"received SIGIO signal.\\n\");\n }\n\n\n bool Open(const char* path, int baudrate, int databits, int stopbits, int parity) {\n\t\tif (fd_) return false;\n struct termios newtio; \n\n long BAUD;\n long DATABITS;\n long STOPBITS;\n long PARITYON;\n long PARITY;\n\n\n switch (baudrate)\n {\n case 38400:\n default:\n BAUD = B38400;\n break;\n case 19200:\n BAUD = B19200;\n break;\n case 9600:\n BAUD = B9600;\n break;\n case 4800:\n BAUD = B4800;\n break;\n case 2400:\n BAUD = B2400;\n break;\n case 1800:\n BAUD = B1800;\n break;\n case 1200:\n BAUD = B1200;\n break;\n case 600:\n BAUD = B600;\n break;\n case 300:\n BAUD = B300;\n break;\n case 200:\n BAUD = B200;\n break;\n case 150:\n BAUD = B150;\n break;\n case 134:\n BAUD = B134;\n break;\n case 110:\n BAUD = B110;\n break;\n case 75:\n BAUD = B75;\n break;\n case 50:\n BAUD = B50;\n break;\n }\n\n switch (databits)\n {\n case 8:\n default:\n DATABITS = CS8;\n break;\n case 7:\n DATABITS = CS7;\n break;\n case 6:\n DATABITS = CS6;\n break;\n case 5:\n DATABITS = CS5;\n break;\n }\n switch (stopbits)\n {\n case 1:\n default:\n STOPBITS = 0;\n break;\n case 2:\n STOPBITS = CSTOPB;\n break;\n } \n\n\n switch (parity)\n {\n case 0:\n default: \/\/none\n PARITYON = 0;\n PARITY = 0;\n break;\n case 1: \/\/odd\n PARITYON = PARENB;\n PARITY = PARODD;\n break;\n case 2: \/\/even\n PARITYON = PARENB;\n PARITY = 0;\n break;\n }\n\n int flags = (O_RDWR | O_NOCTTY | O_NONBLOCK);\n\n fd_ = open(path, flags);\n if (fd_ < 0) return false;\n\n struct sigaction saio; \n\n\t\t\/\/ TODO: Hook event emitter to signal handler\n \/\/ saio.sa_handler = signal_handler_IO;\n\t\t\/\/ ENDTODO\n\n sigemptyset(&saio.sa_mask); \/\/saio.sa_mask = 0;\n saio.sa_flags = 0;\n \/\/ saio.sa_restorer = NULL;\n sigaction(SIGIO,&saio,NULL);\n\n \/\/all process to receive SIGIO\n fcntl(fd_, F_SETOWN, getpid());\n fcntl(fd_, F_SETFL, FASYNC);\n\n\n newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;\n newtio.c_iflag = IGNPAR;\n newtio.c_oflag = 0;\n newtio.c_lflag = 0; \/\/ICANON;\n newtio.c_cc[VMIN]=1;\n newtio.c_cc[VTIME]=0;\n tcflush(fd_, TCIFLUSH);\n tcsetattr(fd_,TCSANOW,&newtio);\n\n\t\tRef();\n\t\t\n return true;\n }\n\n int Write(char* buf, size_t length) {\n ssize_t written = write(fd_, buf, length);\n return written;\n }\n\n\tvoid Close (Local<Value> exception = Local<Value>())\n {\n HandleScope scope;\n\t\tif (fd_)\t{\n\t\t\tclose(fd_);\n\t\t\tfd_ = NULL;\n\t\t}\n Emit(close_symbol, 0, NULL);\n Unref();\n }\n\n\n\nprotected:\n\n\tstatic Handle<Value>\n\tNew (const Arguments& args)\n\t{\n\t HandleScope scope;\n\n\t SerialPort *serial_port = new SerialPort();\n\t serial_port->Wrap(args.This());\n\n\t return scope.Close(args.This());\n\t}\n\t\n\tstatic Handle<Value>\n\tWrite (const Arguments& args)\n\t{\n\t HandleScope scope;\n \n\t SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());\n\t\tif (!Buffer::HasInstance(args[0])) {\n\t return ThrowException(Exception::Error(\n\t String::New(\"Second argument needs to be a buffer\")));\n\t }\n\n\t Local<Object> buffer_obj = args[0]->ToObject();\n\t char *buffer_data = Buffer::Data(buffer_obj);\n\t size_t buffer_length = Buffer::Length(buffer_obj);\n\t\n\t\tif (buffer_length < 0) {\n return ThrowException(Exception::TypeError(String::New(\"Bad argument\")));\n }\n\t\tint written = serial_port->Write(buffer_data, buffer_length);\n if (written < 0) return ThrowException(Exception::Error(String::NewSymbol(strerror(errno))));\n\t\treturn scope.Close(Integer::New(written));\n\t}\n\t\n\t\n\t\n\tstatic Handle<Value>\n\tOpen (const Arguments& args)\n\t{\n\t HandleScope scope;\n \n\t SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());\n \n\t long baudrate = 38400;\n\t int databits = 8;\n\t int stopbits = 1;\n\t int parity = 0;\n\n\t if (!args[0]->IsString()) {\n\t return scope.Close(ThrowException(Exception::Error(String::New(\"Must give serial device string as argument\"))));\n\t }\n\n\t String::Utf8Value path(args[0]->ToString());\n\n\t \/\/ Baud Rate Argument\n\t if (args.Length() >= 2 && !args[1]->IsInt32()) {\n\t return scope.Close(ThrowException(Exception::Error(\n\t String::New(\"If giving baud rate, must be a integer value.\"))));\n\t } else {\n\t baudrate = args[1]->Int32Value();\n\t }\n\n\t \/\/ Data Bits Argument\n\t if (args.Length() >= 3 && !args[2]->IsInt32()) {\n\t return scope.Close(ThrowException(Exception::Error(\n\t String::New(\"If giving data bits, must be a integer value.\"))));\n\t } else {\n\t databits = args[2]->Int32Value();\n\t }\n\n\t \/\/ Stop Bits Arguments\n\t if (args.Length() >= 4 && !args[3]->IsInt32()) {\n\t return scope.Close(ThrowException(Exception::Error(\n\t String::New(\"If giving stop bits, must be a integer value.\"))));\n\t } else {\n\t stopbits = args[3]->Int32Value();\n\t }\n\n\t \/\/ parity Arguments\n\t if (args.Length() >= 5 && !args[4]->IsInt32()) {\n\t return scope.Close(ThrowException(Exception::Error(\n\t String::New(\"If giving parity, must be a integer value.\"))));\n\t } else {\n\t parity = args[4]->Int32Value();\n\t }\n \n \n \n\t bool r = serial_port->Open(*path, baudrate, databits, stopbits, parity);\n\t if (!r) {\n\t return ThrowException(Exception::Error(\n\t String::New(\"Could not open serial port.\")));\n\t }\n\n\t return scope.Close(Undefined());\n\t}\n\t\n\t\n\t\n static Handle<Value>\n Close (const Arguments& args)\n {\n SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());\n HandleScope scope;\n serial_port->Close();\n return scope.Close(Undefined());\n }\n\n\n\n\t\/\/ static Handle<Value>\n\t\/\/ Close (const Arguments& args) \n\t\/\/ {\n\t\/\/ HandleScope scope;\n\t\/\/ \tif (fd_) {\n\t\/\/ int ret = close(fd_);\n\t\/\/ if (ret != 0) return scope.Close(ThrowException(ErrnoException(errno)));\n\t\/\/ \t}\n\t\/\/ return scope.Close(Undefined());\n\t\/\/ }\n\t \n\t\/\/ \n\t\/\/ static Handle<Value>\n\t\/\/ Write (const Arguments& args)\n\t\/\/ {\n\t\/\/ \n\t\/\/ }\n\t\/\/ \n\t\/\/ \n\t\/\/ \n\n\tSerialPort () : EventEmitter () \n\t{\n\t fd_ = NULL;\n\t}\n\n\t~SerialPort ()\n\t{\n\t\tif(fd_) { \n\t\t\tclose(fd_); \n\t\t\tfd_ = NULL;\n\t\t}\n\t}\nprivate:\n\tint fd_;\n \/\/ \n \/\/ \n \/\/ \n \/\/ private:\n \/\/ static inline Local<Value> errno_exception(int errorno) {\n \/\/ Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));\n \/\/ Local<Object> obj = e->ToObject();\n \/\/ obj->Set(errno_symbol, Integer::New(errorno));\n \/\/ return e;\n \/\/ }\n \/\/ }\n \n};\n\n\n\nextern \"C\" void\ninit (Handle<Object> target) \n{\n HandleScope scope;\n SerialPort::Initialize(target);\n}\n\n\n\n<commit_msg>Removed influx node 0.3.x faster buffer code for existing 0.2.x buffer code.<commit_after>\/\/ Copyright 2010 Chris Williams <chris@iterativedesigns.com>\n#include \"serialport_native.h\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <assert.h>\n#include <string.h>\n#include <errno.h>\n#include <limits.h>\n\n#include <termios.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/signal.h>\n#include <sys\/types.h>\n\n#include <node.h>\n#include <node_events.h>\n#include <node_buffer.h>\n#include <v8.h>\n\nusing namespace v8;\nusing namespace node;\n\n\n\n\/\/ static Persistent<String> encoding_symbol;\n\/\/ static Persistent<String> errno_symbol;\n\n\/\/ #define THROW_BAD_ARGS ThrowException(Exception::TypeError(String::New(\"Bad argument\")))\n\/\/ \n\/\/ static inline Local<Value> errno_exception(int errorno) {\n\/\/ Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));\n\/\/ Local<Object> obj = e->ToObject();\n\/\/ obj->Set(errno_symbol, Integer::New(errorno));\n\/\/ return e;\n\/\/ }\n\n\n\n\n\nstatic Persistent<String> data_symbol;\nstatic Persistent<String> close_symbol;\n\n\n\nclass SerialPort : public EventEmitter {\npublic:\n static void\n Initialize (v8::Handle<v8::Object> target)\n {\n HandleScope scope;\n Local<FunctionTemplate> t = FunctionTemplate::New(New);\n\n t->Inherit(EventEmitter::constructor_template);\n t->InstanceTemplate()->SetInternalFieldCount(1);\n \n data_symbol = NODE_PSYMBOL(\"data\");\n close_symbol = NODE_PSYMBOL(\"close\");\n \n NODE_SET_PROTOTYPE_METHOD(t, \"open\", Open);\n NODE_SET_PROTOTYPE_METHOD(t, \"close\", Close);\n NODE_SET_PROTOTYPE_METHOD(t, \"write\", Write);\n target->Set(String::NewSymbol(\"SerialPort\"), t->GetFunction());\n \n }\n \n \n void signal_handler_IO (int status)\n {\n printf(\"%i\", status);\n printf(\"received SIGIO signal.\\n\");\n }\n\n\n bool Open(const char* path, int baudrate, int databits, int stopbits, int parity) {\n if (fd_) return false;\n struct termios newtio; \n\n long BAUD;\n long DATABITS;\n long STOPBITS;\n long PARITYON;\n long PARITY;\n\n\n switch (baudrate)\n {\n case 38400:\n default:\n BAUD = B38400;\n break;\n case 19200:\n BAUD = B19200;\n break;\n case 9600:\n BAUD = B9600;\n break;\n case 4800:\n BAUD = B4800;\n break;\n case 2400:\n BAUD = B2400;\n break;\n case 1800:\n BAUD = B1800;\n break;\n case 1200:\n BAUD = B1200;\n break;\n case 600:\n BAUD = B600;\n break;\n case 300:\n BAUD = B300;\n break;\n case 200:\n BAUD = B200;\n break;\n case 150:\n BAUD = B150;\n break;\n case 134:\n BAUD = B134;\n break;\n case 110:\n BAUD = B110;\n break;\n case 75:\n BAUD = B75;\n break;\n case 50:\n BAUD = B50;\n break;\n }\n\n switch (databits)\n {\n case 8:\n default:\n DATABITS = CS8;\n break;\n case 7:\n DATABITS = CS7;\n break;\n case 6:\n DATABITS = CS6;\n break;\n case 5:\n DATABITS = CS5;\n break;\n }\n switch (stopbits)\n {\n case 1:\n default:\n STOPBITS = 0;\n break;\n case 2:\n STOPBITS = CSTOPB;\n break;\n } \n\n\n switch (parity)\n {\n case 0:\n default: \/\/none\n PARITYON = 0;\n PARITY = 0;\n break;\n case 1: \/\/odd\n PARITYON = PARENB;\n PARITY = PARODD;\n break;\n case 2: \/\/even\n PARITYON = PARENB;\n PARITY = 0;\n break;\n }\n\n int flags = (O_RDWR | O_NOCTTY | O_NONBLOCK);\n\n fd_ = open(path, flags);\n if (fd_ < 0) return false;\n\n struct sigaction saio; \n\n \/\/ TODO: Hook event emitter to signal handler\n \/\/ saio.sa_handler = signal_handler_IO;\n \/\/ ENDTODO\n\n sigemptyset(&saio.sa_mask); \/\/saio.sa_mask = 0;\n saio.sa_flags = 0;\n \/\/ saio.sa_restorer = NULL;\n sigaction(SIGIO,&saio,NULL);\n\n \/\/all process to receive SIGIO\n fcntl(fd_, F_SETOWN, getpid());\n fcntl(fd_, F_SETFL, FASYNC);\n\n\n newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;\n newtio.c_iflag = IGNPAR;\n newtio.c_oflag = 0;\n newtio.c_lflag = 0; \/\/ICANON;\n newtio.c_cc[VMIN]=1;\n newtio.c_cc[VTIME]=0;\n tcflush(fd_, TCIFLUSH);\n tcsetattr(fd_,TCSANOW,&newtio);\n\n Ref();\n \n return true;\n }\n\n int Write(char* buf, size_t length) {\n ssize_t written = write(fd_, buf, length);\n return written;\n }\n\n void Close (Local<Value> exception = Local<Value>())\n {\n HandleScope scope;\n if (fd_) {\n close(fd_);\n fd_ = NULL;\n }\n Emit(close_symbol, 0, NULL);\n Unref();\n }\n\n\n\nprotected:\n\n static Handle<Value>\n New (const Arguments& args)\n {\n HandleScope scope;\n\n SerialPort *serial_port = new SerialPort();\n serial_port->Wrap(args.This());\n\n return scope.Close(args.This());\n }\n \n static Handle<Value>\n Write (const Arguments& args)\n {\n HandleScope scope;\n \n SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());\n \n \n \n if (!Buffer::HasInstance(args[0])) {\n return ThrowException(Exception::Error(String::New(\"First argument needs to be a buffer\")));\n }\n\n Buffer * buffer = ObjectWrap::Unwrap<Buffer>(args[1]->ToObject());\n int buffer_length = buffer->length();\n char * buf = (char*)buffer->data();\n if (buffer_length < 0) {\n return ThrowException(Exception::TypeError(String::New(\"Bad argument\")));\n }\n int written = serial_port->Write(buf, buffer_length);\n if (written < 0) return ThrowException(Exception::Error(String::NewSymbol(strerror(errno))));\n return scope.Close(Integer::New(written));\n }\n \n \n \n static Handle<Value>\n Open (const Arguments& args)\n {\n HandleScope scope;\n \n SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());\n \n long baudrate = 38400;\n int databits = 8;\n int stopbits = 1;\n int parity = 0;\n\n if (!args[0]->IsString()) {\n return scope.Close(ThrowException(Exception::Error(String::New(\"Must give serial device string as argument\"))));\n }\n\n String::Utf8Value path(args[0]->ToString());\n\n \/\/ Baud Rate Argument\n if (args.Length() >= 2 && !args[1]->IsInt32()) {\n return scope.Close(ThrowException(Exception::Error(\n String::New(\"If giving baud rate, must be a integer value.\"))));\n } else {\n baudrate = args[1]->Int32Value();\n }\n\n \/\/ Data Bits Argument\n if (args.Length() >= 3 && !args[2]->IsInt32()) {\n return scope.Close(ThrowException(Exception::Error(\n String::New(\"If giving data bits, must be a integer value.\"))));\n } else {\n databits = args[2]->Int32Value();\n }\n\n \/\/ Stop Bits Arguments\n if (args.Length() >= 4 && !args[3]->IsInt32()) {\n return scope.Close(ThrowException(Exception::Error(\n String::New(\"If giving stop bits, must be a integer value.\"))));\n } else {\n stopbits = args[3]->Int32Value();\n }\n\n \/\/ parity Arguments\n if (args.Length() >= 5 && !args[4]->IsInt32()) {\n return scope.Close(ThrowException(Exception::Error(\n String::New(\"If giving parity, must be a integer value.\"))));\n } else {\n parity = args[4]->Int32Value();\n }\n \n \n \n bool r = serial_port->Open(*path, baudrate, databits, stopbits, parity);\n if (!r) {\n return ThrowException(Exception::Error(\n String::New(\"Could not open serial port.\")));\n }\n\n return scope.Close(Undefined());\n }\n \n \n \n static Handle<Value>\n Close (const Arguments& args)\n {\n SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());\n HandleScope scope;\n serial_port->Close();\n return scope.Close(Undefined());\n }\n\n\n\n \/\/ static Handle<Value>\n \/\/ Close (const Arguments& args) \n \/\/ {\n \/\/ HandleScope scope;\n \/\/ if (fd_) {\n \/\/ int ret = close(fd_);\n \/\/ if (ret != 0) return scope.Close(ThrowException(ErrnoException(errno)));\n \/\/ }\n \/\/ return scope.Close(Undefined());\n \/\/ }\n \n \/\/ \n \/\/ static Handle<Value>\n \/\/ Write (const Arguments& args)\n \/\/ {\n \/\/ \n \/\/ }\n \/\/ \n \/\/ \n \/\/ \n\n SerialPort () : EventEmitter () \n {\n fd_ = NULL;\n }\n\n ~SerialPort ()\n {\n if(fd_) { \n close(fd_); \n fd_ = NULL;\n }\n }\nprivate:\n int fd_;\n \/\/ \n \/\/ \n \/\/ \n \/\/ private:\n \/\/ static inline Local<Value> errno_exception(int errorno) {\n \/\/ Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));\n \/\/ Local<Object> obj = e->ToObject();\n \/\/ obj->Set(errno_symbol, Integer::New(errorno));\n \/\/ return e;\n \/\/ }\n \/\/ }\n \n};\n\n\n\nextern \"C\" void\ninit (Handle<Object> target) \n{\n HandleScope scope;\n SerialPort::Initialize(target);\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file remoteSubscriptionHandle.cc\n * @author Krzysztof Trzepla\n * @copyright (C) 2016 ACK CYFRONET AGH\n * @copyright This software is released under the MIT license cited in\n * 'LICENSE.txt'\n *\/\n\n#include \"remoteSubscriptionHandle.h\"\n#include \"helpers\/logging.h\"\n\n#include \"messages.pb.h\"\n\nnamespace one {\nnamespace client {\nnamespace events {\n\nRemoteSubscriptionHandle::RemoteSubscriptionHandle(StreamKey streamKey,\n Streams &streams, std::int64_t subscriptionId, ProtoSubscriptionPtr msg,\n SequencerStream &stream)\n : SubscriptionHandle(streamKey, streams)\n , m_subscriptionId{subscriptionId}\n , m_stream{stream}\n{\n LOG_DBG(2) << \"Sending subscription with ID: '\" << subscriptionId << \"'\";\n\n auto clientMsg = std::make_unique<ProtoClient>();\n msg->set_id(m_subscriptionId);\n clientMsg->mutable_subscription()->Swap(msg.release());\n m_stream.send(std::move(clientMsg));\n}\n\nRemoteSubscriptionHandle::~RemoteSubscriptionHandle()\n{\n LOG_DBG(2) << \"Sending cancellation for subscription with ID: '\"\n << m_subscriptionId << \"'\";\n\n auto clientMsg = std::make_unique<ProtoClient>();\n auto *msg = clientMsg->mutable_subscription_cancellation();\n msg->set_id(m_subscriptionId);\n m_stream.send(std::move(clientMsg));\n}\n\n} \/\/ namespace events\n} \/\/ namespace client\n} \/\/ namespace one\n<commit_msg>VFS-9252 Changed subscriptions to sync mode<commit_after>\/**\n * @file remoteSubscriptionHandle.cc\n * @author Krzysztof Trzepla\n * @copyright (C) 2016 ACK CYFRONET AGH\n * @copyright This software is released under the MIT license cited in\n * 'LICENSE.txt'\n *\/\n\n#include \"remoteSubscriptionHandle.h\"\n#include \"helpers\/logging.h\"\n\n#include \"messages.pb.h\"\n\nnamespace one {\nnamespace client {\nnamespace events {\n\nRemoteSubscriptionHandle::RemoteSubscriptionHandle(StreamKey streamKey,\n Streams &streams, std::int64_t subscriptionId, ProtoSubscriptionPtr msg,\n SequencerStream &stream)\n : SubscriptionHandle(streamKey, streams)\n , m_subscriptionId{subscriptionId}\n , m_stream{stream}\n{\n LOG_DBG(2) << \"Sending subscription with ID: '\" << subscriptionId << \"'\";\n\n auto clientMsg = std::make_unique<ProtoClient>();\n msg->set_id(m_subscriptionId);\n clientMsg->mutable_subscription()->Swap(msg.release());\n m_stream.sendSync(std::move(clientMsg));\n}\n\nRemoteSubscriptionHandle::~RemoteSubscriptionHandle()\n{\n LOG_DBG(2) << \"Sending cancellation for subscription with ID: '\"\n << m_subscriptionId << \"'\";\n\n auto clientMsg = std::make_unique<ProtoClient>();\n auto *msg = clientMsg->mutable_subscription_cancellation();\n msg->set_id(m_subscriptionId);\n m_stream.sendSync(std::move(clientMsg));\n}\n\n} \/\/ namespace events\n} \/\/ namespace client\n} \/\/ namespace one\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012 Cloudera Inc.\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 \"codec.h\"\n\n#include <zlib.h>\n\nusing namespace parquet_cpp;\n\nvoid GZipCodec::Decompress(int input_len, const uint8_t* input,\n int output_len, uint8_t* output_buffer) \n{\n z_stream stream;\n stream.zalloc = (alloc_func)0;\n stream.zfree = (free_func)0;\n stream.next_in = (Bytef *)input;\n stream.avail_in = (uInt)input_len;\n stream.next_out = (Bytef*)output_buffer;\n stream.avail_out = output_len;\n int rc = inflateInit2(&stream, 16+MAX_WBITS);\n if (rc != Z_OK) { \n throw ParquetException(\"zlib internal error.\");\n }\n rc = inflate(&stream, Z_FINISH); \n if (rc == Z_STREAM_END) {\n rc = inflateEnd(&stream);\n }\n if (rc != Z_OK) {\n throw ParquetException(\"Corrupt gzip compressed data.\");\n }\n}\n\nint GZipCodec::MaxCompressedLen(int input_len, const uint8_t* input) {\n return compressBound(input_len);\n}\n\nint GZipCodec::Compress(int input_len, const uint8_t* input,\n int output_buffer_len, uint8_t* output_buffer) {\n uLongf dstLen = output_buffer_len; \n int rc = compress2((Bytef*)output_buffer, &dstLen, (Bytef*)input, input_len, 1);\n return rc == Z_OK ? dstLen : input_len;\n}\n<commit_msg>Fix code style issues<commit_after>\/\/ Copyright 2012 Cloudera Inc.\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 \"parquet\/compression\/codec.h\"\n\n#include <zlib.h>\n\nnamespace parquet_cpp {\n\nvoid GZipCodec::Decompress(int input_len, const uint8_t* input,\n\t\t\t\t\t\t int output_len, uint8_t* output_buffer)\n{\n\tz_stream stream;\n\tstream.zalloc = reinterpret_cast<alloc_func>0;\n\tstream.zfree = reinterpret_cast<free_func>0;\n\tstream.next_in = reinterpret_cast<Bytef *>input;\n\tstream.avail_in = reinterpret_cast<uInt>input_len;\n\tstream.next_out = reinterpret_cast<Bytef*>output_buffer;\n\tstream.avail_out = output_len;\n\tint rc = inflateInit2(&stream, 16+MAX_WBITS);\n\tif (rc != Z_OK) \n\t{\n\t\tthrow ParquetException(\"zlib internal error.\");\n\t}\n\trc = inflate(&stream, Z_FINISH);\n\tif (rc == Z_STREAM_END) \n\t{\n\t\trc = inflateEnd(&stream);\n\t}\n\tif (rc != Z_OK) \n\t{\n\t\tthrow ParquetException(\"Corrupt gzip compressed data.\");\n\t}\n}\n\nint GZipCodec::MaxCompressedLen(int input_len, const uint8_t* input) \n{\n\treturn compressBound(input_len);\n}\n\nint GZipCodec::Compress(int input_len, const uint8_t* input,\n\t\t\t\t\t\tint output_buffer_len, uint8_t* output_buffer) \n{\n\tuLongf dstLen = output_buffer_len;\n\tint rc = compress2(reinterpret_cast<Bytef*>output_buffer, &dstLen, reinterpret_cast<Bytef*>input, input_len, 1);\n\treturn rc == Z_OK ? dstLen : input_len;\n}\n\n} \/\/ namespace parquet_cpp\n<|endoftext|>"} {"text":"<commit_before>#include \"option_manager.hh\"\n\n#include \"assert.hh\"\n\n#include <sstream>\n\nnamespace Kakoune\n{\n\nOptionDesc::OptionDesc(String name, String docstring, OptionFlags flags)\n : m_name(std::move(name)), m_docstring(std::move(docstring)),\n m_flags(flags) {}\n\nOption::Option(const OptionDesc& desc, OptionManager& manager)\n : m_manager(manager), m_desc(desc) {}\n\nOptionManager::OptionManager(OptionManager& parent)\n : m_parent(&parent)\n{\n parent.register_watcher(*this);\n}\n\nOptionManager::~OptionManager()\n{\n if (m_parent)\n m_parent->unregister_watcher(*this);\n\n kak_assert(m_watchers.empty());\n}\n\nvoid OptionManager::register_watcher(OptionManagerWatcher& watcher)\n{\n kak_assert(not contains(m_watchers, &watcher));\n m_watchers.push_back(&watcher);\n}\n\nvoid OptionManager::unregister_watcher(OptionManagerWatcher& watcher)\n{\n auto it = find(m_watchers.begin(), m_watchers.end(), &watcher);\n kak_assert(it != m_watchers.end());\n m_watchers.erase(it);\n}\n\nOption& OptionManager::get_local_option(const String& name)\n{\n auto it = find_option(m_options, name);\n if (it != m_options.end())\n return **it;\n else if (m_parent)\n {\n m_options.emplace_back((*m_parent)[name].clone(*this));\n return *m_options.back();\n }\n else\n throw option_not_found(name);\n\n}\n\nconst Option& OptionManager::operator[](const String& name) const\n{\n auto it = find_option(m_options, name);\n if (it != m_options.end())\n return **it;\n else if (m_parent)\n return (*m_parent)[name];\n else\n throw option_not_found(name);\n}\n\ntemplate<typename MatchingFunc>\nCandidateList OptionManager::get_matching_names(MatchingFunc func)\n{\n CandidateList result;\n if (m_parent)\n result = m_parent->get_matching_names(func);\n for (auto& option : m_options)\n {\n if (option->flags() & OptionFlags::Hidden)\n continue;\n\n const auto& name = option->name();\n if (func(name) and not contains(result, name))\n result.push_back(name);\n }\n return result;\n}\n\nCandidateList OptionManager::complete_option_name(StringView prefix,\n ByteCount cursor_pos)\n{\n using namespace std::placeholders;\n auto real_prefix = prefix.substr(0, cursor_pos);\n auto result = get_matching_names(std::bind(prefix_match, _1, real_prefix));\n if (result.empty())\n result = get_matching_names(std::bind(subsequence_match, _1, real_prefix));\n return result;\n}\n\nOptionManager::OptionList OptionManager::flatten_options() const\n{\n OptionList res = m_parent ? m_parent->flatten_options() : OptionList{};\n for (auto& option : m_options)\n {\n auto it = find_option(res, option->name());\n if (it != res.end())\n *it = option.get();\n else\n res.emplace_back(option.get());\n }\n return res;\n}\n\nvoid OptionManager::on_option_changed(const Option& option)\n{\n \/\/ if parent option changed, but we overrided it, it's like nothing happened\n if (&option.manager() != this and\n find_option(m_options, option.name()) != m_options.end())\n return;\n\n for (auto watcher : m_watchers)\n watcher->on_option_changed(option);\n}\n\nGlobalOptions::GlobalOptions()\n : OptionManager()\n{\n declare_option(\"tabstop\", \"size of a tab character\", 8);\n declare_option(\"indentwidth\", \"indentation width\", 4);\n declare_option(\"scrolloff\",\n \"number of lines to keep visible main cursor when scrolling\",\n 0);\n declare_option(\"eolformat\", \"end of line format: 'crlf' or 'lf'\", \"lf\"_str);\n declare_option(\"BOM\", \"insert a byte order mark when writing buffer\",\n \"no\"_str);\n declare_option(\"complete_prefix\",\n \"complete up to common prefix in tab completion\",\n true);\n declare_option(\"incsearch\",\n \"incrementaly apply search\/select\/split regex\",\n true);\n declare_option(\"autoinfo\",\n \"automatically display contextual help\",\n true);\n declare_option(\"autoshowcompl\",\n \"automatically display possible completions for prompts\",\n true);\n declare_option(\"aligntab\",\n \"use tab characters when possible for alignement\",\n false);\n declare_option(\"ignored_files\",\n \"patterns to ignore when completing filenames\",\n Regex{R\"(^(\\..*|.*\\.(o|so|a))$)\"});\n declare_option(\"filetype\", \"buffer filetype\", \"\"_str);\n declare_option(\"path\", \"path to consider when trying to find a file\",\n std::vector<String>({ \".\/\", \"\/usr\/include\" }));\n declare_option(\"completers\", \"insert mode completers to execute.\",\n std::vector<String>({\"filename\", \"word=buffer\"}),\n OptionFlags::None,\n OptionChecker<std::vector<String>>([](const std::vector<String>& s) {\n static const auto values = {\"word=buffer\", \"word=all\", \"filename\"};\n for (auto& v : s)\n {\n if (v.substr(0_byte, 7_byte) == \"option=\")\n continue;\n if (not contains(values, v))\n throw runtime_error(v + \" is not a recognised value for completers\");\n }\n }));\n declare_option(\"autoreload\",\n \"autoreload buffer when a filesystem modification is detected\",\n Ask);\n}\n\n}\n<commit_msg>use words=all rather than words=buffer for default insert word completion<commit_after>#include \"option_manager.hh\"\n\n#include \"assert.hh\"\n\n#include <sstream>\n\nnamespace Kakoune\n{\n\nOptionDesc::OptionDesc(String name, String docstring, OptionFlags flags)\n : m_name(std::move(name)), m_docstring(std::move(docstring)),\n m_flags(flags) {}\n\nOption::Option(const OptionDesc& desc, OptionManager& manager)\n : m_manager(manager), m_desc(desc) {}\n\nOptionManager::OptionManager(OptionManager& parent)\n : m_parent(&parent)\n{\n parent.register_watcher(*this);\n}\n\nOptionManager::~OptionManager()\n{\n if (m_parent)\n m_parent->unregister_watcher(*this);\n\n kak_assert(m_watchers.empty());\n}\n\nvoid OptionManager::register_watcher(OptionManagerWatcher& watcher)\n{\n kak_assert(not contains(m_watchers, &watcher));\n m_watchers.push_back(&watcher);\n}\n\nvoid OptionManager::unregister_watcher(OptionManagerWatcher& watcher)\n{\n auto it = find(m_watchers.begin(), m_watchers.end(), &watcher);\n kak_assert(it != m_watchers.end());\n m_watchers.erase(it);\n}\n\nOption& OptionManager::get_local_option(const String& name)\n{\n auto it = find_option(m_options, name);\n if (it != m_options.end())\n return **it;\n else if (m_parent)\n {\n m_options.emplace_back((*m_parent)[name].clone(*this));\n return *m_options.back();\n }\n else\n throw option_not_found(name);\n\n}\n\nconst Option& OptionManager::operator[](const String& name) const\n{\n auto it = find_option(m_options, name);\n if (it != m_options.end())\n return **it;\n else if (m_parent)\n return (*m_parent)[name];\n else\n throw option_not_found(name);\n}\n\ntemplate<typename MatchingFunc>\nCandidateList OptionManager::get_matching_names(MatchingFunc func)\n{\n CandidateList result;\n if (m_parent)\n result = m_parent->get_matching_names(func);\n for (auto& option : m_options)\n {\n if (option->flags() & OptionFlags::Hidden)\n continue;\n\n const auto& name = option->name();\n if (func(name) and not contains(result, name))\n result.push_back(name);\n }\n return result;\n}\n\nCandidateList OptionManager::complete_option_name(StringView prefix,\n ByteCount cursor_pos)\n{\n using namespace std::placeholders;\n auto real_prefix = prefix.substr(0, cursor_pos);\n auto result = get_matching_names(std::bind(prefix_match, _1, real_prefix));\n if (result.empty())\n result = get_matching_names(std::bind(subsequence_match, _1, real_prefix));\n return result;\n}\n\nOptionManager::OptionList OptionManager::flatten_options() const\n{\n OptionList res = m_parent ? m_parent->flatten_options() : OptionList{};\n for (auto& option : m_options)\n {\n auto it = find_option(res, option->name());\n if (it != res.end())\n *it = option.get();\n else\n res.emplace_back(option.get());\n }\n return res;\n}\n\nvoid OptionManager::on_option_changed(const Option& option)\n{\n \/\/ if parent option changed, but we overrided it, it's like nothing happened\n if (&option.manager() != this and\n find_option(m_options, option.name()) != m_options.end())\n return;\n\n for (auto watcher : m_watchers)\n watcher->on_option_changed(option);\n}\n\nGlobalOptions::GlobalOptions()\n : OptionManager()\n{\n declare_option(\"tabstop\", \"size of a tab character\", 8);\n declare_option(\"indentwidth\", \"indentation width\", 4);\n declare_option(\"scrolloff\",\n \"number of lines to keep visible main cursor when scrolling\",\n 0);\n declare_option(\"eolformat\", \"end of line format: 'crlf' or 'lf'\", \"lf\"_str);\n declare_option(\"BOM\", \"insert a byte order mark when writing buffer\",\n \"no\"_str);\n declare_option(\"complete_prefix\",\n \"complete up to common prefix in tab completion\",\n true);\n declare_option(\"incsearch\",\n \"incrementaly apply search\/select\/split regex\",\n true);\n declare_option(\"autoinfo\",\n \"automatically display contextual help\",\n true);\n declare_option(\"autoshowcompl\",\n \"automatically display possible completions for prompts\",\n true);\n declare_option(\"aligntab\",\n \"use tab characters when possible for alignement\",\n false);\n declare_option(\"ignored_files\",\n \"patterns to ignore when completing filenames\",\n Regex{R\"(^(\\..*|.*\\.(o|so|a))$)\"});\n declare_option(\"filetype\", \"buffer filetype\", \"\"_str);\n declare_option(\"path\", \"path to consider when trying to find a file\",\n std::vector<String>({ \".\/\", \"\/usr\/include\" }));\n declare_option(\"completers\", \"insert mode completers to execute.\",\n std::vector<String>({\"filename\", \"word=all\"}),\n OptionFlags::None,\n OptionChecker<std::vector<String>>([](const std::vector<String>& s) {\n static const auto values = {\"word=buffer\", \"word=all\", \"filename\"};\n for (auto& v : s)\n {\n if (v.substr(0_byte, 7_byte) == \"option=\")\n continue;\n if (not contains(values, v))\n throw runtime_error(v + \" is not a recognised value for completers\");\n }\n }));\n declare_option(\"autoreload\",\n \"autoreload buffer when a filesystem modification is detected\",\n Ask);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"protagonist.h\"\n#include \"snowcrash.h\"\n\nusing namespace v8;\nusing namespace protagonist;\n\n\/\/static const std::string RenderDescriptionsOptionKey = \"renderDescriptions\";\nstatic const std::string RequireBlueprintNameOptionKey = \"requireBlueprintName\";\nstatic const std::string ExportSourcemapOptionKey = \"exportSourcemap\";\nstatic const std::string TypeOptionKey = \"type\";\n\nstatic const std::string TypeOptionAst = \"ast\";\nstatic const std::string TypeOptionRefract = \"refract\";\n\nOptionsResult* protagonist::ParseOptionsObject(Handle<Object> optionsObject) {\n OptionsResult *optionsResult = (OptionsResult *) malloc(sizeof(OptionsResult));\n\n optionsResult->options = 0;\n optionsResult->astType = drafter::RefractASTType;\n optionsResult->error = NULL;\n\n const Local<Array> properties = optionsObject->GetPropertyNames();\n const uint32_t length = properties->Length();\n\n for (uint32_t i = 0 ; i < length ; ++i) {\n const Local<Value> key = properties->Get(i);\n const Local<Value> value = optionsObject->Get(key);\n\n if (RequireBlueprintNameOptionKey == *String::Utf8Value(key)) {\n \/\/ RequireBlueprintNameOption\n if (value->IsTrue())\n optionsResult->options |= snowcrash::RequireBlueprintNameOption;\n else\n optionsResult->options &= snowcrash::RequireBlueprintNameOption;\n }\n else if (ExportSourcemapOptionKey == *String::Utf8Value(key)) {\n \/\/ ExportSourcemapOption\n if (value->IsTrue())\n optionsResult->options |= snowcrash::ExportSourcemapOption;\n else\n optionsResult->options &= snowcrash::ExportSourcemapOption;\n }\n else if (TypeOptionKey == *String::Utf8Value(key)) {\n \/\/ TypeOption\n if (TypeOptionAst == *String::Utf8Value(value)) {\n optionsResult->astType = drafter::NormalASTType;\n } else if (TypeOptionRefract == *String::Utf8Value(value)) {\n optionsResult->astType = drafter::RefractASTType;\n } else {\n std::stringstream ss;\n ss << \"unrecognized type '\" << *String::Utf8Value(value) << \"', expected '\";\n ss << TypeOptionAst << \"' or '\" << TypeOptionRefract << \"'\";\n\n optionsResult->error = ss.str().c_str();\n return optionsResult;\n }\n }\n else {\n \/\/ Unrecognized option\n std::stringstream ss;\n ss << \"unrecognized option '\" << *String::Utf8Value(key) << \"', expected: \";\n ss << \"'\" << RequireBlueprintNameOptionKey << \"', '\";\n ss << ExportSourcemapOptionKey << \"' or '\" << TypeOptionKey << '\"';\n\n optionsResult->error = ss.str().c_str();\n return optionsResult;\n }\n }\n\n return optionsResult;\n}\n<commit_msg>Code improvement and optimization in options_parser.cc<commit_after>#include \"protagonist.h\"\n#include \"snowcrash.h\"\n\nusing namespace v8;\nusing namespace protagonist;\n\n\/\/static const std::string RenderDescriptionsOptionKey = \"renderDescriptions\";\nstatic const std::string RequireBlueprintNameOptionKey = \"requireBlueprintName\";\nstatic const std::string ExportSourcemapOptionKey = \"exportSourcemap\";\nstatic const std::string TypeOptionKey = \"type\";\n\nstatic const std::string TypeOptionAst = \"ast\";\nstatic const std::string TypeOptionRefract = \"refract\";\n\nOptionsResult* protagonist::ParseOptionsObject(Handle<Object> optionsObject) {\n OptionsResult *optionsResult = (OptionsResult *) malloc(sizeof(OptionsResult));\n\n optionsResult->options = 0;\n optionsResult->astType = drafter::RefractASTType;\n optionsResult->error = NULL;\n\n const Local<Array> properties = optionsObject->GetPropertyNames();\n const uint32_t length = properties->Length();\n\n for (uint32_t i = 0 ; i < length ; ++i) {\n const Local<Value> key = properties->Get(i);\n const Local<Value> value = optionsObject->Get(key);\n\n const String::Utf8Value strKey(key);\n\n if (RequireBlueprintNameOptionKey == *strKey) {\n \/\/ RequireBlueprintNameOption\n if (value->IsTrue())\n optionsResult->options |= snowcrash::RequireBlueprintNameOption;\n else\n optionsResult->options &= snowcrash::RequireBlueprintNameOption;\n }\n else if (ExportSourcemapOptionKey == *strKey) {\n \/\/ ExportSourcemapOption\n if (value->IsTrue())\n optionsResult->options |= snowcrash::ExportSourcemapOption;\n else\n optionsResult->options &= snowcrash::ExportSourcemapOption;\n }\n else if (TypeOptionKey == *strKey) {\n \/\/ TypeOption\n const String::Utf8Value strValue(value);\n\n if (TypeOptionAst == *strValue) {\n optionsResult->astType = drafter::NormalASTType;\n } else if (TypeOptionRefract == *strValue) {\n optionsResult->astType = drafter::RefractASTType;\n } else {\n std::stringstream ss;\n ss << \"unrecognized type '\" << *strValue << \"', expected '\";\n ss << TypeOptionAst << \"' or '\" << TypeOptionRefract << \"'\";\n\n optionsResult->error = ss.str().c_str();\n return optionsResult;\n }\n }\n else {\n \/\/ Unrecognized option\n std::stringstream ss;\n ss << \"unrecognized option '\" << *strKey << \"', expected: \";\n ss << \"'\" << RequireBlueprintNameOptionKey << \"', '\";\n ss << ExportSourcemapOptionKey << \"' or '\" << TypeOptionKey << '\"';\n\n optionsResult->error = ss.str().c_str();\n return optionsResult;\n }\n }\n\n return optionsResult;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\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#ifndef itkConnectedThresholdImageFilter_hxx\n#define itkConnectedThresholdImageFilter_hxx\n\n#include \"itkConnectedThresholdImageFilter.h\"\n#include \"itkBinaryThresholdImageFunction.h\"\n#include \"itkFloodFilledImageFunctionConditionalIterator.h\"\n#include \"itkProgressReporter.h\"\n\n#include \"itkShapedFloodFilledImageFunctionConditionalIterator.h\"\n#include \"itkMath.h\"\n\nnamespace itk\n{\n\ntemplate< typename TInputImage, typename TOutputImage >\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::ConnectedThresholdImageFilter() :\n m_Lower( NumericTraits< InputImagePixelType >::NonpositiveMin() ),\n m_Upper( NumericTraits< InputImagePixelType >::max() ),\n m_ReplaceValue( NumericTraits< OutputImagePixelType >::OneValue() ),\n m_Connectivity( FaceConnectivity )\n{\n typename InputPixelObjectType::Pointer lower = InputPixelObjectType::New();\n lower->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );\n this->ProcessObject::SetNthInput(1, lower);\n\n typename InputPixelObjectType::Pointer upper = InputPixelObjectType::New();\n upper->Set( NumericTraits< InputImagePixelType >::max() );\n this->ProcessObject::SetNthInput(2, upper);\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetSeed(const IndexType & seed)\n{\n this->ClearSeeds();\n this->AddSeed( seed );\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::AddSeed(const IndexType & seed)\n{\n this->m_Seeds.push_back(seed);\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::ClearSeeds()\n{\n if ( m_Seeds.size() > 0 )\n {\n this->m_Seeds.clear();\n this->Modified();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nconst typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::SeedContainerType &\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetSeeds() const\n{\n return this->m_Seeds;\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GenerateInputRequestedRegion()\n{\n Superclass::GenerateInputRequestedRegion();\n if ( this->GetInput() )\n {\n InputImagePointer image =\n const_cast< InputImageType * >( this->GetInput() );\n image->SetRequestedRegionToLargestPossibleRegion();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::EnlargeOutputRequestedRegion(DataObject *output)\n{\n Superclass::EnlargeOutputRequestedRegion(output);\n output->SetRequestedRegionToLargestPossibleRegion();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetLowerInput(const InputPixelObjectType *input)\n{\n if ( input != this->GetLowerInput() )\n {\n this->ProcessObject::SetNthInput( 1,\n const_cast< InputPixelObjectType * >( input ) );\n this->Modified();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetUpperInput(const InputPixelObjectType *input)\n{\n if ( input != this->GetUpperInput() )\n {\n this->ProcessObject::SetNthInput( 2,\n const_cast< InputPixelObjectType * >( input ) );\n this->Modified();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetUpper(const InputImagePixelType threshold)\n{\n \/\/ first check to see if anything changed\n typename InputPixelObjectType::Pointer upper = this->GetUpperInput();\n if ( upper && Math::ExactlyEquals(upper->Get(), threshold) )\n {\n return;\n }\n\n \/\/ Create a data object to use as the input and to store this\n \/\/ threshold. we always create a new data object to use as the input\n \/\/ since we do not want to change the value in any current input\n \/\/ (the current input could be the output of another filter or the\n \/\/ current input could be used as an input to several filters).\n upper = InputPixelObjectType::New();\n this->ProcessObject::SetNthInput(2, upper);\n\n upper->Set(threshold);\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetLower(const InputImagePixelType threshold)\n{\n \/\/ first check to see if anything changed\n typename InputPixelObjectType::Pointer lower = this->GetLowerInput();\n if ( lower && Math::ExactlyEquals(lower->Get(), threshold) )\n {\n return;\n }\n\n \/\/ Create a data object to use as the input and to store this\n \/\/ threshold. we always create a new data object to use as the input\n \/\/ since we do not want to change the value in any current input\n \/\/ (the current input could be the output of another filter or the\n \/\/ current input could be used as an input to several filters).\n lower = InputPixelObjectType::New();\n this->ProcessObject::SetNthInput(1, lower);\n\n lower->Set(threshold);\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\ntypename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputPixelObjectType *\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetLowerInput()\n{\n typename InputPixelObjectType::Pointer lower =\n static_cast< InputPixelObjectType * >( this->ProcessObject::GetInput(1) );\n if ( !lower )\n {\n \/\/ No input object available, create a new one and set it to the\n \/\/ default threshold\n lower = InputPixelObjectType::New();\n lower->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );\n this->ProcessObject::SetNthInput(1, lower);\n }\n\n return lower;\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\ntypename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputPixelObjectType *\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetUpperInput()\n{\n typename InputPixelObjectType::Pointer upper =\n static_cast< InputPixelObjectType * >( this->ProcessObject::GetInput(2) );\n if ( !upper )\n {\n \/\/ No input object available, create a new one and set it to the\n \/\/ default threshold\n upper = InputPixelObjectType::New();\n upper->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );\n this->ProcessObject::SetNthInput(2, upper);\n }\n\n return upper;\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\ntypename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputImagePixelType\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetLower() const\n{\n typename InputPixelObjectType::Pointer lower =\n const_cast< Self * >( this )->GetLowerInput();\n\n return lower->Get();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\ntypename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputImagePixelType\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetUpper() const\n{\n typename InputPixelObjectType::Pointer upper =\n const_cast< Self * >( this )->GetUpperInput();\n\n return upper->Get();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GenerateData()\n{\n InputImageConstPointer inputImage = this->GetInput();\n OutputImagePointer outputImage = this->GetOutput();\n\n typename InputPixelObjectType::Pointer lowerThreshold = this->GetLowerInput();\n typename InputPixelObjectType::Pointer upperThreshold = this->GetUpperInput();\n\n m_Lower = lowerThreshold->Get();\n m_Upper = upperThreshold->Get();\n\n \/\/ Zero the output\n OutputImageRegionType region = outputImage->GetRequestedRegion();\n outputImage->SetBufferedRegion(region);\n outputImage->Allocate();\n outputImage->FillBuffer(NumericTraits< OutputImagePixelType >::ZeroValue());\n\n typedef BinaryThresholdImageFunction< InputImageType, double > FunctionType;\n\n typename FunctionType::Pointer function = FunctionType::New();\n function->SetInputImage( inputImage );\n function->ThresholdBetween( m_Lower, m_Upper );\n\n ProgressReporter progress( this, 0, region.GetNumberOfPixels() );\n\n if ( this->m_Connectivity == FaceConnectivity )\n {\n typedef FloodFilledImageFunctionConditionalIterator< OutputImageType, FunctionType > IteratorType;\n IteratorType it (outputImage, function, m_Seeds);\n it.GoToBegin();\n\n while ( !it.IsAtEnd() )\n {\n it.Set(m_ReplaceValue);\n ++it;\n progress.CompletedPixel(); \/\/ potential exception thrown here\n }\n }\n else if ( this->m_Connectivity == FullConnectivity )\n {\n \/\/ Use the fully connected iterator here. The fully connected iterator\n \/\/ below is a superset of the above. However, it is reported to be 20%\n \/\/ slower. Hence we use this \"if\" block to use the old iterator when\n \/\/ we don't need full connectivity.\n\n typedef ShapedFloodFilledImageFunctionConditionalIterator< OutputImageType, FunctionType > IteratorType;\n IteratorType it (outputImage, function, m_Seeds);\n it.FullyConnectedOn();\n it.GoToBegin();\n\n while ( !it.IsAtEnd() )\n {\n it.Set(m_ReplaceValue);\n ++it;\n progress.CompletedPixel(); \/\/ potential exception thrown here\n }\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Upper: \"\n << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_Upper )\n << std::endl;\n os << indent << \"Lower: \"\n << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_Lower )\n << std::endl;\n os << indent << \"ReplaceValue: \"\n << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_ReplaceValue )\n << std::endl;\n os << indent << \"Connectivity: \" << m_Connectivity << std::endl;\n}\n} \/\/ end namespace itk\n\n#endif\n<commit_msg>BUG: Print missing Seeds parameter and values used for Upper\/Lower<commit_after>\/*=========================================================================\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#ifndef itkConnectedThresholdImageFilter_hxx\n#define itkConnectedThresholdImageFilter_hxx\n\n#include \"itkConnectedThresholdImageFilter.h\"\n#include \"itkBinaryThresholdImageFunction.h\"\n#include \"itkFloodFilledImageFunctionConditionalIterator.h\"\n#include \"itkProgressReporter.h\"\n\n#include \"itkShapedFloodFilledImageFunctionConditionalIterator.h\"\n#include \"itkMath.h\"\n\nnamespace itk\n{\n\ntemplate< typename TInputImage, typename TOutputImage >\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::ConnectedThresholdImageFilter() :\n m_Lower( NumericTraits< InputImagePixelType >::NonpositiveMin() ),\n m_Upper( NumericTraits< InputImagePixelType >::max() ),\n m_ReplaceValue( NumericTraits< OutputImagePixelType >::OneValue() ),\n m_Connectivity( FaceConnectivity )\n{\n typename InputPixelObjectType::Pointer lower = InputPixelObjectType::New();\n lower->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );\n this->ProcessObject::SetNthInput(1, lower);\n\n typename InputPixelObjectType::Pointer upper = InputPixelObjectType::New();\n upper->Set( NumericTraits< InputImagePixelType >::max() );\n this->ProcessObject::SetNthInput(2, upper);\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetSeed(const IndexType & seed)\n{\n this->ClearSeeds();\n this->AddSeed( seed );\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::AddSeed(const IndexType & seed)\n{\n this->m_Seeds.push_back(seed);\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::ClearSeeds()\n{\n if ( m_Seeds.size() > 0 )\n {\n this->m_Seeds.clear();\n this->Modified();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nconst typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::SeedContainerType &\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetSeeds() const\n{\n return this->m_Seeds;\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GenerateInputRequestedRegion()\n{\n Superclass::GenerateInputRequestedRegion();\n if ( this->GetInput() )\n {\n InputImagePointer image =\n const_cast< InputImageType * >( this->GetInput() );\n image->SetRequestedRegionToLargestPossibleRegion();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::EnlargeOutputRequestedRegion(DataObject *output)\n{\n Superclass::EnlargeOutputRequestedRegion(output);\n output->SetRequestedRegionToLargestPossibleRegion();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetLowerInput(const InputPixelObjectType *input)\n{\n if ( input != this->GetLowerInput() )\n {\n this->ProcessObject::SetNthInput( 1,\n const_cast< InputPixelObjectType * >( input ) );\n this->Modified();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetUpperInput(const InputPixelObjectType *input)\n{\n if ( input != this->GetUpperInput() )\n {\n this->ProcessObject::SetNthInput( 2,\n const_cast< InputPixelObjectType * >( input ) );\n this->Modified();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetUpper(const InputImagePixelType threshold)\n{\n \/\/ first check to see if anything changed\n typename InputPixelObjectType::Pointer upper = this->GetUpperInput();\n if ( upper && Math::ExactlyEquals(upper->Get(), threshold) )\n {\n return;\n }\n\n \/\/ Create a data object to use as the input and to store this\n \/\/ threshold. we always create a new data object to use as the input\n \/\/ since we do not want to change the value in any current input\n \/\/ (the current input could be the output of another filter or the\n \/\/ current input could be used as an input to several filters).\n upper = InputPixelObjectType::New();\n this->ProcessObject::SetNthInput(2, upper);\n\n upper->Set(threshold);\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::SetLower(const InputImagePixelType threshold)\n{\n \/\/ first check to see if anything changed\n typename InputPixelObjectType::Pointer lower = this->GetLowerInput();\n if ( lower && Math::ExactlyEquals(lower->Get(), threshold) )\n {\n return;\n }\n\n \/\/ Create a data object to use as the input and to store this\n \/\/ threshold. we always create a new data object to use as the input\n \/\/ since we do not want to change the value in any current input\n \/\/ (the current input could be the output of another filter or the\n \/\/ current input could be used as an input to several filters).\n lower = InputPixelObjectType::New();\n this->ProcessObject::SetNthInput(1, lower);\n\n lower->Set(threshold);\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\ntypename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputPixelObjectType *\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetLowerInput()\n{\n typename InputPixelObjectType::Pointer lower =\n static_cast< InputPixelObjectType * >( this->ProcessObject::GetInput(1) );\n if ( !lower )\n {\n \/\/ No input object available, create a new one and set it to the\n \/\/ default threshold\n lower = InputPixelObjectType::New();\n lower->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );\n this->ProcessObject::SetNthInput(1, lower);\n }\n\n return lower;\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\ntypename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputPixelObjectType *\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetUpperInput()\n{\n typename InputPixelObjectType::Pointer upper =\n static_cast< InputPixelObjectType * >( this->ProcessObject::GetInput(2) );\n if ( !upper )\n {\n \/\/ No input object available, create a new one and set it to the\n \/\/ default threshold\n upper = InputPixelObjectType::New();\n upper->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );\n this->ProcessObject::SetNthInput(2, upper);\n }\n\n return upper;\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\ntypename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputImagePixelType\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetLower() const\n{\n typename InputPixelObjectType::Pointer lower =\n const_cast< Self * >( this )->GetLowerInput();\n\n return lower->Get();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\ntypename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputImagePixelType\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GetUpper() const\n{\n typename InputPixelObjectType::Pointer upper =\n const_cast< Self * >( this )->GetUpperInput();\n\n return upper->Get();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::GenerateData()\n{\n InputImageConstPointer inputImage = this->GetInput();\n OutputImagePointer outputImage = this->GetOutput();\n\n typename InputPixelObjectType::Pointer lowerThreshold = this->GetLowerInput();\n typename InputPixelObjectType::Pointer upperThreshold = this->GetUpperInput();\n\n m_Lower = lowerThreshold->Get();\n m_Upper = upperThreshold->Get();\n\n \/\/ Zero the output\n OutputImageRegionType region = outputImage->GetRequestedRegion();\n outputImage->SetBufferedRegion(region);\n outputImage->Allocate();\n outputImage->FillBuffer(NumericTraits< OutputImagePixelType >::ZeroValue());\n\n typedef BinaryThresholdImageFunction< InputImageType, double > FunctionType;\n\n typename FunctionType::Pointer function = FunctionType::New();\n function->SetInputImage( inputImage );\n function->ThresholdBetween( m_Lower, m_Upper );\n\n ProgressReporter progress( this, 0, region.GetNumberOfPixels() );\n\n if ( this->m_Connectivity == FaceConnectivity )\n {\n typedef FloodFilledImageFunctionConditionalIterator< OutputImageType, FunctionType > IteratorType;\n IteratorType it (outputImage, function, m_Seeds);\n it.GoToBegin();\n\n while ( !it.IsAtEnd() )\n {\n it.Set(m_ReplaceValue);\n ++it;\n progress.CompletedPixel(); \/\/ potential exception thrown here\n }\n }\n else if ( this->m_Connectivity == FullConnectivity )\n {\n \/\/ Use the fully connected iterator here. The fully connected iterator\n \/\/ below is a superset of the above. However, it is reported to be 20%\n \/\/ slower. Hence we use this \"if\" block to use the old iterator when\n \/\/ we don't need full connectivity.\n\n typedef ShapedFloodFilledImageFunctionConditionalIterator< OutputImageType, FunctionType > IteratorType;\n IteratorType it (outputImage, function, m_Seeds);\n it.FullyConnectedOn();\n it.GoToBegin();\n\n while ( !it.IsAtEnd() )\n {\n it.Set(m_ReplaceValue);\n ++it;\n progress.CompletedPixel(); \/\/ potential exception thrown here\n }\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nConnectedThresholdImageFilter< TInputImage, TOutputImage >\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Upper: \"\n << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( this->GetUpper() )\n << std::endl;\n os << indent << \"Lower: \"\n << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( this->GetLower() )\n << std::endl;\n os << indent << \"ReplaceValue: \"\n << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_ReplaceValue )\n << std::endl;\n os << indent << \"Seeds: \";\n for (unsigned int i = 0; i < this->m_Seeds.size(); ++i)\n {\n os << \" \" << this->m_Seeds[i] << std::endl;\n }\n os << std::endl;\n os << indent << \"Connectivity: \" << m_Connectivity << std::endl;\n}\n} \/\/ end namespace itk\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n#include <math.h>\n#include <netdb.h>\n#include <time.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <netinet\/in.h>\n#include \"statsd_client.h\"\n\nusing namespace std;\nnamespace statsd {\n\ninline bool fequal(float a, float b)\n{\n const float epsilon = 0.0001;\n return ( fabs(a - b) < epsilon );\n}\n\ninline bool should_send(float sample_rate)\n{\n if ( fequal(sample_rate, 1.0) )\n {\n return true;\n }\n\n float p = ((float)random() \/ RAND_MAX);\n return sample_rate > p;\n}\n\n\nstruct _StatsdClientData {\n int sock;\n struct sockaddr_in server;\n\n string ns;\n string host;\n short port;\n bool init;\n\n char errmsg[1024];\n};\n\nStatsdClient::StatsdClient(const string& host, int port, const string& ns)\n{\n d = new _StatsdClientData;\n config(host, port, ns);\n srandom(time(NULL));\n}\n\nStatsdClient::~StatsdClient()\n{\n \/\/ close socket\n if (d->sock >= 0) {\n close(d->sock);\n d->sock = -1;\n }\n}\n\nvoid StatsdClient::config(const string& host, int port, const string& ns)\n{\n d->ns = ns;\n d->host = host;\n d->port = port;\n d->init = false;\n if ( d->sock >= 0 ) {\n close(d->sock);\n }\n d->sock = -1;\n}\n\nint StatsdClient::init()\n{\n if ( d->init ) return 0;\n\n d->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);\n if ( d->sock == -1 ) {\n snprintf(d->errmsg, sizeof(d->errmsg), \"could not create socket, err=%m\");\n return -1;\n }\n\n memset(&d->server, 0, sizeof(d->server));\n d->server.sin_family = AF_INET;\n d->server.sin_port = htons(d->port);\n\n int ret = inet_aton(d->host.c_str(), &d->server.sin_addr);\n if ( ret == 0 )\n {\n \/\/ host must be a domain, get it from internet\n struct addrinfo hints, *result = NULL;\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_DGRAM;\n\n ret = getaddrinfo(d->host.c_str(), NULL, &hints, &result);\n if ( ret ) {\n snprintf(d->errmsg, sizeof(d->errmsg),\n \"getaddrinfo fail, error=%d, msg=%s\", ret, gai_strerror(ret) );\n return -2;\n }\n struct sockaddr_in* host_addr = (struct sockaddr_in*)result->ai_addr;\n memcpy(&d->server.sin_addr, &host_addr->sin_addr, sizeof(struct in_addr));\n freeaddrinfo(result);\n }\n\n d->init = true;\n return 0;\n}\n\n\/* will change the original string *\/\nvoid StatsdClient::cleanup(string& key)\n{\n size_t pos = key.find_first_of(\":|@\");\n while ( pos != string::npos )\n {\n key[pos] = '_';\n pos = key.find_first_of(\":|@\");\n }\n}\n\nint StatsdClient::dec(const string& key, float sample_rate)\n{\n return count(key, -1, sample_rate);\n}\n\nint StatsdClient::inc(const string& key, float sample_rate)\n{\n return count(key, 1, sample_rate);\n}\n\nint StatsdClient::count(const string& key, size_t value, float sample_rate)\n{\n return send(key, value, \"c\", sample_rate);\n}\n\nint StatsdClient::gauge(const string& key, size_t value, float sample_rate)\n{\n return send(key, value, \"g\", sample_rate);\n}\n\nint StatsdClient::timing(const string& key, size_t ms, float sample_rate)\n{\n return send(key, ms, \"ms\", sample_rate);\n}\n\nint StatsdClient::send(string key, size_t value, const string &type, float sample_rate)\n{\n if (!should_send(sample_rate)) {\n return 0;\n }\n\n cleanup(key);\n\n char buf[256];\n if ( fequal( sample_rate, 1.0 ) )\n {\n snprintf(buf, sizeof(buf), \"%s%s:%zd|%s\",\n d->ns.c_str(), key.c_str(), value, type.c_str());\n }\n else\n {\n snprintf(buf, sizeof(buf), \"%s%s:%zd|%s|@%.2f\",\n d->ns.c_str(), key.c_str(), value, type.c_str(), sample_rate);\n }\n\n return send(buf);\n}\n\nint StatsdClient::send(const string &message)\n{\n int ret = init();\n if ( ret )\n {\n return ret;\n }\n ret = sendto(d->sock, message.data(), message.size(), 0, (struct sockaddr *) &d->server, sizeof(d->server));\n if ( ret == -1) {\n snprintf(d->errmsg, sizeof(d->errmsg),\n \"sendto server fail, host=%s:%d, err=%m\", d->host.c_str(), d->port);\n return -1;\n }\n return 0;\n}\n\nconst char* StatsdClient::errmsg()\n{\n return d->errmsg;\n}\n\n}\n\n<commit_msg>add delete d<commit_after>\n#include <math.h>\n#include <netdb.h>\n#include <time.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <netinet\/in.h>\n#include \"statsd_client.h\"\n\nusing namespace std;\nnamespace statsd {\n\ninline bool fequal(float a, float b)\n{\n const float epsilon = 0.0001;\n return ( fabs(a - b) < epsilon );\n}\n\ninline bool should_send(float sample_rate)\n{\n if ( fequal(sample_rate, 1.0) )\n {\n return true;\n }\n\n float p = ((float)random() \/ RAND_MAX);\n return sample_rate > p;\n}\n\n\nstruct _StatsdClientData {\n int sock;\n struct sockaddr_in server;\n\n string ns;\n string host;\n short port;\n bool init;\n\n char errmsg[1024];\n};\n\nStatsdClient::StatsdClient(const string& host, int port, const string& ns)\n{\n d = new _StatsdClientData;\n config(host, port, ns);\n srandom(time(NULL));\n}\n\nStatsdClient::~StatsdClient()\n{\n \/\/ close socket\n if (d->sock >= 0) {\n close(d->sock);\n d->sock = -1;\n delete d;\n d = NULL;\n }\n}\n\nvoid StatsdClient::config(const string& host, int port, const string& ns)\n{\n d->ns = ns;\n d->host = host;\n d->port = port;\n d->init = false;\n if ( d->sock >= 0 ) {\n close(d->sock);\n }\n d->sock = -1;\n}\n\nint StatsdClient::init()\n{\n if ( d->init ) return 0;\n\n d->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);\n if ( d->sock == -1 ) {\n snprintf(d->errmsg, sizeof(d->errmsg), \"could not create socket, err=%m\");\n return -1;\n }\n\n memset(&d->server, 0, sizeof(d->server));\n d->server.sin_family = AF_INET;\n d->server.sin_port = htons(d->port);\n\n int ret = inet_aton(d->host.c_str(), &d->server.sin_addr);\n if ( ret == 0 )\n {\n \/\/ host must be a domain, get it from internet\n struct addrinfo hints, *result = NULL;\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_DGRAM;\n\n ret = getaddrinfo(d->host.c_str(), NULL, &hints, &result);\n if ( ret ) {\n snprintf(d->errmsg, sizeof(d->errmsg),\n \"getaddrinfo fail, error=%d, msg=%s\", ret, gai_strerror(ret) );\n return -2;\n }\n struct sockaddr_in* host_addr = (struct sockaddr_in*)result->ai_addr;\n memcpy(&d->server.sin_addr, &host_addr->sin_addr, sizeof(struct in_addr));\n freeaddrinfo(result);\n }\n\n d->init = true;\n return 0;\n}\n\n\/* will change the original string *\/\nvoid StatsdClient::cleanup(string& key)\n{\n size_t pos = key.find_first_of(\":|@\");\n while ( pos != string::npos )\n {\n key[pos] = '_';\n pos = key.find_first_of(\":|@\");\n }\n}\n\nint StatsdClient::dec(const string& key, float sample_rate)\n{\n return count(key, -1, sample_rate);\n}\n\nint StatsdClient::inc(const string& key, float sample_rate)\n{\n return count(key, 1, sample_rate);\n}\n\nint StatsdClient::count(const string& key, size_t value, float sample_rate)\n{\n return send(key, value, \"c\", sample_rate);\n}\n\nint StatsdClient::gauge(const string& key, size_t value, float sample_rate)\n{\n return send(key, value, \"g\", sample_rate);\n}\n\nint StatsdClient::timing(const string& key, size_t ms, float sample_rate)\n{\n return send(key, ms, \"ms\", sample_rate);\n}\n\nint StatsdClient::send(string key, size_t value, const string &type, float sample_rate)\n{\n if (!should_send(sample_rate)) {\n return 0;\n }\n\n cleanup(key);\n\n char buf[256];\n if ( fequal( sample_rate, 1.0 ) )\n {\n snprintf(buf, sizeof(buf), \"%s%s:%zd|%s\",\n d->ns.c_str(), key.c_str(), value, type.c_str());\n }\n else\n {\n snprintf(buf, sizeof(buf), \"%s%s:%zd|%s|@%.2f\",\n d->ns.c_str(), key.c_str(), value, type.c_str(), sample_rate);\n }\n\n return send(buf);\n}\n\nint StatsdClient::send(const string &message)\n{\n int ret = init();\n if ( ret )\n {\n return ret;\n }\n ret = sendto(d->sock, message.data(), message.size(), 0, (struct sockaddr *) &d->server, sizeof(d->server));\n if ( ret == -1) {\n snprintf(d->errmsg, sizeof(d->errmsg),\n \"sendto server fail, host=%s:%d, err=%m\", d->host.c_str(), d->port);\n return -1;\n }\n return 0;\n}\n\nconst char* StatsdClient::errmsg()\n{\n return d->errmsg;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Flutter 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 <iomanip>\n#include <iostream>\n#include <string>\n\n#include \"flutter\/flow\/layers\/performance_overlay_layer.h\"\n\nnamespace flow {\nnamespace {\n\nvoid DrawStatisticsText(SkCanvas& canvas,\n const std::string& string,\n int x,\n int y) {\n SkPaint paint;\n paint.setTextSize(15);\n paint.setLinearText(false);\n paint.setColor(SK_ColorGRAY);\n paint.setAntiAlias(true);\n canvas.drawText(string.c_str(), string.size(), x, y, paint);\n}\n\nvoid VisualizeStopWatch(SkCanvas& canvas,\n const Stopwatch& stopwatch,\n SkScalar x,\n SkScalar y,\n SkScalar width,\n SkScalar height,\n bool show_graph,\n bool show_labels,\n const std::string& label_prefix) {\n const int label_x = 8; \/\/ distance from x\n const int label_y = -10; \/\/ distance from y+height\n\n if (show_graph) {\n SkRect visualization_rect = SkRect::MakeXYWH(x, y, width, height);\n stopwatch.Visualize(canvas, visualization_rect);\n }\n\n if (show_labels) {\n double ms_per_frame = stopwatch.MaxDelta().ToMillisecondsF();\n double fps;\n if (ms_per_frame < kOneFrameMS) {\n fps = 1e3 \/ kOneFrameMS;\n } else {\n fps = 1e3 \/ ms_per_frame;\n }\n\n std::stringstream stream;\n stream.setf(std::ios::fixed | std::ios::showpoint);\n stream << std::setprecision(1);\n stream << label_prefix << \" \" << fps << \" fps \" << ms_per_frame\n << \"ms\/frame\";\n DrawStatisticsText(canvas, stream.str(), x + label_x, y + height + label_y);\n }\n}\n\n} \/\/ namespace\n\nPerformanceOverlayLayer::PerformanceOverlayLayer(uint64_t options)\n : options_(options) {}\n\nvoid PerformanceOverlayLayer::Paint(PaintContext& context) const {\n const int padding = 8;\n\n if (!options_)\n return;\n\n TRACE_EVENT0(\"flutter\", \"PerformanceOverlayLayer::Paint\");\n SkScalar x = paint_bounds().x() + padding;\n SkScalar y = paint_bounds().y() + padding;\n SkScalar width = paint_bounds().width() - (padding * 2);\n SkScalar height = paint_bounds().height() \/ 2;\n SkAutoCanvasRestore save(context.leaf_nodes_canvas, true);\n\n VisualizeStopWatch(*context.leaf_nodes_canvas, context.frame_time, x, y,\n width, height - padding,\n options_ & kVisualizeRasterizerStatistics,\n options_ & kDisplayRasterizerStatistics, \"GPU\");\n\n VisualizeStopWatch(*context.leaf_nodes_canvas, context.engine_time, x,\n y + height, width, height - padding,\n options_ & kVisualizeEngineStatistics,\n options_ & kDisplayEngineStatistics, \"UI\");\n}\n\n} \/\/ namespace flow\n<commit_msg>update site to use SkFont for text fields (#7464)<commit_after>\/\/ Copyright 2013 The Flutter 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 <iomanip>\n#include <iostream>\n#include <string>\n\n#include \"flutter\/flow\/layers\/performance_overlay_layer.h\"\n#include \"third_party\/skia\/include\/core\/SkFont.h\"\n\nnamespace flow {\nnamespace {\n\nvoid DrawStatisticsText(SkCanvas& canvas,\n const std::string& string,\n int x,\n int y) {\n SkFont font;\n font.setSize(15);\n font.setLinearMetrics(false);\n SkPaint paint;\n paint.setColor(SK_ColorGRAY);\n canvas.drawSimpleText(string.c_str(), string.size(), kUTF8_SkTextEncoding, x,\n y, font, paint);\n}\n\nvoid VisualizeStopWatch(SkCanvas& canvas,\n const Stopwatch& stopwatch,\n SkScalar x,\n SkScalar y,\n SkScalar width,\n SkScalar height,\n bool show_graph,\n bool show_labels,\n const std::string& label_prefix) {\n const int label_x = 8; \/\/ distance from x\n const int label_y = -10; \/\/ distance from y+height\n\n if (show_graph) {\n SkRect visualization_rect = SkRect::MakeXYWH(x, y, width, height);\n stopwatch.Visualize(canvas, visualization_rect);\n }\n\n if (show_labels) {\n double ms_per_frame = stopwatch.MaxDelta().ToMillisecondsF();\n double fps;\n if (ms_per_frame < kOneFrameMS) {\n fps = 1e3 \/ kOneFrameMS;\n } else {\n fps = 1e3 \/ ms_per_frame;\n }\n\n std::stringstream stream;\n stream.setf(std::ios::fixed | std::ios::showpoint);\n stream << std::setprecision(1);\n stream << label_prefix << \" \" << fps << \" fps \" << ms_per_frame\n << \"ms\/frame\";\n DrawStatisticsText(canvas, stream.str(), x + label_x, y + height + label_y);\n }\n}\n\n} \/\/ namespace\n\nPerformanceOverlayLayer::PerformanceOverlayLayer(uint64_t options)\n : options_(options) {}\n\nvoid PerformanceOverlayLayer::Paint(PaintContext& context) const {\n const int padding = 8;\n\n if (!options_)\n return;\n\n TRACE_EVENT0(\"flutter\", \"PerformanceOverlayLayer::Paint\");\n SkScalar x = paint_bounds().x() + padding;\n SkScalar y = paint_bounds().y() + padding;\n SkScalar width = paint_bounds().width() - (padding * 2);\n SkScalar height = paint_bounds().height() \/ 2;\n SkAutoCanvasRestore save(context.leaf_nodes_canvas, true);\n\n VisualizeStopWatch(*context.leaf_nodes_canvas, context.frame_time, x, y,\n width, height - padding,\n options_ & kVisualizeRasterizerStatistics,\n options_ & kDisplayRasterizerStatistics, \"GPU\");\n\n VisualizeStopWatch(*context.leaf_nodes_canvas, context.engine_time, x,\n y + height, width, height - padding,\n options_ & kVisualizeEngineStatistics,\n options_ & kDisplayEngineStatistics, \"UI\");\n}\n\n} \/\/ namespace flow\n<|endoftext|>"} {"text":"<commit_before>\n#include \"cpu.h\"\n\n#if defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)\n# include <sys\/param.h>\n# include <sys\/sysctl.h>\n#endif\n#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_CYGWIN)\n# include <unistd.h>\n#endif\n#include \"windows.hdr.h\"\n\n\n\n\nnamespace Yuni\n{\nnamespace System\n{\nnamespace CPU\n{\n\n\n\t#if defined(YUNI_OS_WINDOWS) || defined(YUNI_OS_CYGWIN)\n\t# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION\n\tuint Count()\n\t{\n\t\tSYSTEM_INFO si;\n\t\tGetSystemInfo(&si);\n\t\treturn si.dwNumberOfProcessors;\n\t}\n\t#endif\n\n\n\t#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)\n\t# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION\n\tuint Count()\n\t{\n\t\t\/\/ The number of processors online (capable of running processes)\n\t\tlong cpus = sysconf(_SC_NPROCESSORS_ONLN);\n\t\treturn (cpus < 1) ? 1 : (uint) cpus;\n\t}\n\t#endif\n\n\n\n\n\t#ifndef YUNI_CPU_COUNT_HAS_IMPLEMENTATION\n\t# warning \"The method Yuni::System::CPU::Count() has not been implemented for the current platform\"\n\tuint Count()\n\t{\n\t\treturn 1; \/\/ Default value\n\t}\n\t#endif\n\n\n\n\n\n} \/\/ namespace CPU\n} \/\/ namespace System\n} \/\/ namespace Yuni\n\n<commit_msg>CPU::Count: fixed compilation on MacOS<commit_after>\n#include \"cpu.h\"\n#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)\n#include <unistd.h>\n#endif\n#include \"windows.hdr.h\"\n\n\n\n\nnamespace Yuni\n{\nnamespace System\n{\nnamespace CPU\n{\n\n\n\t#if defined(YUNI_OS_WINDOWS) || defined(YUNI_OS_CYGWIN)\n\t# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION\n\tuint Count()\n\t{\n\t\tSYSTEM_INFO si;\n\t\tGetSystemInfo(&si);\n\t\treturn si.dwNumberOfProcessors;\n\t}\n\t#endif\n\n\n\t#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)\n\t# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION\n\tuint Count()\n\t{\n\t\t\/\/ The number of processors online (capable of running processes)\n\t\tlong cpus = sysconf(_SC_NPROCESSORS_ONLN);\n\t\treturn (cpus < 1) ? 1 : (uint) cpus;\n\t}\n\t#endif\n\n\n\n\n\t#ifndef YUNI_CPU_COUNT_HAS_IMPLEMENTATION\n\t# warning \"The method Yuni::System::CPU::Count() has not been implemented for the current platform\"\n\tuint Count()\n\t{\n\t\treturn 1; \/\/ Default value\n\t}\n\t#endif\n\n\n\n\n\n} \/\/ namespace CPU\n} \/\/ namespace System\n} \/\/ namespace Yuni\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 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#include \"base\/platform_thread.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/test\/mini_installer_test\/mini_installer_test_constants.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#include \"chrome_mini_installer.h\"\n\nnamespace {\nclass MiniInstallTest : public testing::Test {\n protected:\n void CleanTheSystem() {\n ChromeMiniInstaller userinstall(mini_installer_constants::kUserInstall);\n userinstall.UnInstall();\n if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) {\n ChromeMiniInstaller systeminstall(\n mini_installer_constants::kSystemInstall);\n systeminstall.UnInstall();\n }\n }\n virtual void SetUp() {\n CleanTheSystem();\n }\n\n virtual void TearDown() {\n PlatformThread::Sleep(2000);\n CleanTheSystem();\n }\n };\n};\n\nTEST_F(MiniInstallTest, FullInstallerTest) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.InstallFullInstaller();\n}\n\n\/\/ Will enable this test after bug#9593 gets fixed.\nTEST_F(MiniInstallTest, DISABLED_DifferentialInstallerTest) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.InstallDifferentialInstaller();\n}\n\nTEST_F(MiniInstallTest, DISABLED_StandaloneInstallerTest) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.InstallStandaloneIntaller();\n}\n\nTEST_F(MiniInstallTest, MiniInstallerOverChromeMetaInstallerTest) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.OverInstall();\n}\n\nTEST_F(MiniInstallTest, DISABLED_MiniInstallerSystemInstallTest) {\n if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) {\n ChromeMiniInstaller installer(mini_installer_constants::kSystemInstall);\n installer.Install();\n }\n}\n\nTEST_F(MiniInstallTest, MiniInstallerUserInstallTest) {\n if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.Install();\n }\n}\n\nTEST(InstallUtilTests, MiniInstallTestValidWindowsVersion) {\n \/\/ We run the tests on all supported OSes.\n \/\/ Make sure the code agrees.\n EXPECT_TRUE(InstallUtil::IsOSSupported());\n}\n<commit_msg>Disabling the test again. This time the test doesn't fail at mulitple places. It fails at only one place. investigating... Review URL: http:\/\/codereview.chromium.org\/102003<commit_after>\/\/ Copyright (c) 2006-2008 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#include \"base\/platform_thread.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/test\/mini_installer_test\/mini_installer_test_constants.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#include \"chrome_mini_installer.h\"\n\nnamespace {\nclass MiniInstallTest : public testing::Test {\n protected:\n void CleanTheSystem() {\n ChromeMiniInstaller userinstall(mini_installer_constants::kUserInstall);\n userinstall.UnInstall();\n if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) {\n ChromeMiniInstaller systeminstall(\n mini_installer_constants::kSystemInstall);\n systeminstall.UnInstall();\n }\n }\n virtual void SetUp() {\n CleanTheSystem();\n }\n\n virtual void TearDown() {\n PlatformThread::Sleep(2000);\n CleanTheSystem();\n }\n };\n};\n\nTEST_F(MiniInstallTest, FullInstallerTest) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.InstallFullInstaller();\n}\n\n\/\/ Will enable this test after bug#9593 gets fixed.\nTEST_F(MiniInstallTest, DISABLED_DifferentialInstallerTest) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.InstallDifferentialInstaller();\n}\n\nTEST_F(MiniInstallTest, DISABLED_StandaloneInstallerTest) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.InstallStandaloneIntaller();\n}\n\nTEST_F(MiniInstallTest, MiniInstallerOverChromeMetaInstallerTest) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.OverInstall();\n}\n\nTEST_F(MiniInstallTest, DISABLED_MiniInstallerSystemInstallTest) {\n if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) {\n ChromeMiniInstaller installer(mini_installer_constants::kSystemInstall);\n installer.Install();\n }\n}\n\nTEST_F(MiniInstallTest, DISABLED_MiniInstallerUserInstallTest) {\n if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) {\n ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);\n installer.Install();\n }\n}\n\nTEST(InstallUtilTests, MiniInstallTestValidWindowsVersion) {\n \/\/ We run the tests on all supported OSes.\n \/\/ Make sure the code agrees.\n EXPECT_TRUE(InstallUtil::IsOSSupported());\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef INCLUDED_SROOK_DIGITS_VALUES\n#define INCLUDED_SROOK_DIGITS_VALUES\n\n#include<utility>\n#include<memory>\n#include<vector>\n#include<cmath>\n#include<algorithm>\n\n#if __has_include(<boost\/utility.hpp>)\n#if __has_include(<boost\/mpl\/if.hpp>)\n#include<boost\/utility.hpp>\n#include<boost\/mpl\/if.hpp>\nusing boost::noncopyable;\nusing boost::mpl::if_c;\n#else\n\/\/ self made boost noncopyable\nnamespace srook{\n\tclass noncopyable{\n\tnoncopyable(const noncopyable&)=delete;\n\tnoncopyable& operator=(const noncopyable&)=delete;\nprotected:\n\tnoncopyable()=default;\n\t~noncopyable()=default;\n};\n\n\/\/ self made boost.mpl.if_c\ntemplate<bool Condition,typename T1,typename T2>\nstruct if_c{\n\tusing type=T2;\n};\ntemplate<typename T1,typename T2>\nstruct if_c<true,T1,T2>{\n\tusing type=T1;\n};\n} \/\/ namespace srook\nusing srook::noncopyable;\nusing srook::if_c;\n#endif\n#endif\n\nnamespace srook{\nnamespace srook_adl{ \/\/ protection from unintended ADL\ninline namespace v1{\n\ntemplate<bool Condition,typename T1,typename T2>\nusing if_c_t=typename if_c<Condition,T1,T2>::type;\n\n\ntemplate<typename _Tp,class Not>\nconstexpr bool not_truely_type_v=!std::is_same<typename std::decay<_Tp>::type,Not>::value;\n\n\ntemplate<typename ResultType>\nstruct digits_values final:private noncopyable{\n\tusing result_type=ResultType;\n\t\n\tdigits_values()=default;\n\n\ttemplate<class _Tp>\n\tusing Check_t=typename std::enable_if<not_truely_type_v<_Tp,digits_values>&&\n\t\t!std::is_class<typename std::decay<_Tp>::type>::value&&\n\t\tnot_truely_type_v<_Tp,float>&&\n\t\tnot_truely_type_v<_Tp,double>>::type;\n\n\ttemplate<class _Tp,class=Check_t<_Tp>>\n\tdigits_values(_Tp x)\n\t\t:v(digit_calculation(x)?digit_calculation(x):1,digit_calculation(x)<=1?x:0)\n\t{\n\t\tconst auto digit_=digit_calculation(x);\n\t\tif(!(digit_<=1)){\n\t\t\tauto ten_v=static_cast<std::size_t>(std::pow(10,digit_-1));\n\t\t\tfor(std::size_t i=0; i<v.size(); ++i){\n\t\t\t\tv[i]=x\/ten_v;\n\t\t\t\tx%=ten_v;\n\t\t\t\tten_v\/=10;\n\t\t\t}\n\t\t}\n\t}\n\n\tdigits_values(digits_values&& oth)\n\t{\n\t\tv=std::move(oth.v);\n\t}\n\n\tdigits_values& operator=(digits_values&&)=default;\n\t\n\ttemplate<class _Tp,class=Check_t<_Tp>>\n\tdigits_values& operator=(_Tp x)\n\t{\n\t\tauto digit_=digit_calculation(x);\n\t\tv.resize(digit_);\n\t\tif(!(digit_<=1)){\n\t\t\tauto ten_v=static_cast<std::size_t>(std::pow(10,digit_-1));\n\t\t\tfor(std::size_t i=0; i<v.size(); ++i){\n\t\t\t\tv[i]=x\/ten_v;\n\t\t\t\tx%=ten_v;\n\t\t\t\tten_v\/=10;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tresult_type operator[](const std::size_t& index)const\n\t{return v.at(index);}\n\t\n\tdigits_values operator+(digits_values& oth)\n\t{\n\t\tconst auto this_size=digit();\n\t\tconst auto oth_size=oth.digit();\t\n\t\tconst auto max_v=std::max(this_size,oth_size);\n\t\t\n\t\tdigits_values result;\n\t\tresult.v.reserve(max_v);\n\t\tstd::copy(max_v==this_size?cbegin():oth.cbegin(),max_v==this_size?cend():oth.cend(),std::back_inserter(result.v));\n\n\t\tusing bigger_type=\n\t\t\tif_c_t<\n\t\t\tsizeof(typename std::remove_reference<decltype(oth)>::type::result_type) < sizeof(result_type),\n\t\t\tresult_type,\n\t\t\ttypename std::remove_reference<decltype(oth)>::type::result_type\n\t\t\t>;\n\t\t\n\t\tif(max_v==this_size){\n\t\t\tstd::size_t counter=0;\n\t\t\tfor(auto& i:oth)\n\t\t\t\tresult.v[counter++]+=i;\n\t\t}else{\n\t\t\tstd::size_t counter=0;\n\t\t\tfor(auto& i:v)\n\t\t\t\tresult.v[counter++]+=i;\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\n\n\ttypename std::vector<result_type>::const_iterator cbegin()const{return v.cbegin();}\n\ttypename std::vector<result_type>::const_iterator cend()const{return v.cend();}\n\ttypename std::vector<result_type>::iterator begin(){return v.begin();}\n\ttypename std::vector<result_type>::iterator end(){return v.end();}\n\ttypename std::vector<result_type>::reverse_iterator rbegin(){return v.rbegin();}\n\ttypename std::vector<result_type>::reverse_iterator rend(){return v.rend();}\n\n\tinline std::size_t digit()const{return v.size();}\n\t\n\tauto real_value()\n\t{\n\t\tauto digit_=digit();\n\t\tauto ten_v=static_cast<std::size_t>(std::pow(10,digit_-1));\n\t\tunsigned long long int result=0;\n\n\t\tfor(std::size_t i=0; i<digit_; ++i){\n\t\t\tresult+=v[i]*ten_v;\n\t\t\tten_v\/=10;\n\t\t}\n\t\treturn result;\n\t}\nprivate:\n\tstd::size_t digit_calculation(unsigned long long int x)const\n\t{return std::log10(x)+1;}\n\n\ttemplate<typename Pointed_type>\n\tstd::size_t digit_calculation(Pointed_type x)const\n\t{\n\t\tstd::size_t result=0;\n\t\tfor(; x!=0; ++result)x\/=10;\n\t\treturn result;\n\t}\n\n\tstd::vector<result_type> v;\n};\n\n} \/\/ inline namespace v1\n} \/\/ namespace srook_adl\n\ntemplate<class _Tp=unsigned short int>\nusing digits_values=srook_adl::digits_values<_Tp>;\n\n} \/\/ namespace srook\n#endif \/\/ include guard\n<commit_msg>small fix<commit_after>#ifndef INCLUDED_SROOK_DIGITS_VALUES\n#define INCLUDED_SROOK_DIGITS_VALUES\n\n#include<utility>\n#include<memory>\n#include<vector>\n#include<cmath>\n#include<algorithm>\n\n#if __has_include(<boost\/utility.hpp>)\n#if __has_include(<boost\/mpl\/if.hpp>)\n#include<boost\/utility.hpp>\n#include<boost\/mpl\/if.hpp>\nusing boost::noncopyable;\nusing boost::mpl::if_c;\n#else\n\/\/ self made boost noncopyable\nnamespace srook{\n\tclass noncopyable{\n\tnoncopyable(const noncopyable&)=delete;\n\tnoncopyable& operator=(const noncopyable&)=delete;\nprotected:\n\tnoncopyable()=default;\n\t~noncopyable()=default;\n};\n\n\/\/ self made boost.mpl.if_c\ntemplate<bool Condition,typename T1,typename T2>\nstruct if_c{\n\tusing type=T2;\n};\ntemplate<typename T1,typename T2>\nstruct if_c<true,T1,T2>{\n\tusing type=T1;\n};\n} \/\/ namespace srook\nusing srook::noncopyable;\nusing srook::if_c;\n#endif\n#endif\n\nnamespace srook{\nnamespace srook_adl{ \/\/ protection from unintended ADL\ninline namespace v1{\n\ntemplate<bool Condition,typename T1,typename T2>\nusing if_c_t=typename if_c<Condition,T1,T2>::type;\n\n\ntemplate<typename _Tp,class Not>\nconstexpr bool not_truely_type_v=!std::is_same<typename std::decay<_Tp>::type,Not>::value;\n\n\ntemplate<typename ResultType>\nstruct digits_values final:private noncopyable{\n\tusing result_type=ResultType;\n\t\n\tdigits_values()=default;\n\n\ttemplate<class _Tp>\n\tusing Check_t=typename std::enable_if<not_truely_type_v<_Tp,digits_values>&&\n\t\t!std::is_class<typename std::decay<_Tp>::type>::value&&\n\t\tnot_truely_type_v<_Tp,float>&&\n\t\tnot_truely_type_v<_Tp,double>>::type;\n\n\ttemplate<class _Tp,class=Check_t<_Tp>>\n\tdigits_values(_Tp x)\n\t\t:v(digit_calculation(x)?digit_calculation(x):1,digit_calculation(x)<=1?x:0)\n\t{\n\t\tconst auto digit_=digit_calculation(x);\n\t\tif(!(digit_<=1)){\n\t\t\tauto ten_v=static_cast<std::size_t>(std::pow(10,digit_-1));\n\t\t\tfor(std::size_t i=0; i<v.size(); ++i){\n\t\t\t\tv[i]=x\/ten_v;\n\t\t\t\tx%=ten_v;\n\t\t\t\tten_v\/=10;\n\t\t\t}\n\t\t}\n\t}\n\n\tdigits_values(digits_values&& oth)\n\t{\n\t\tv=std::move(oth.v);\n\t}\n\n\tdigits_values& operator=(digits_values&&)=default;\n\t\n\ttemplate<class _Tp,class=Check_t<_Tp>>\n\tdigits_values& operator=(_Tp x)\n\t{\n\t\tauto digit_=digit_calculation(x);\n\t\tv.resize(digit_);\n\t\tif(!(digit_<=1)){\n\t\t\tauto ten_v=static_cast<std::size_t>(std::pow(10,digit_-1));\n\t\t\tfor(std::size_t i=0; i<v.size(); ++i){\n\t\t\t\tv[i]=x\/ten_v;\n\t\t\t\tx%=ten_v;\n\t\t\t\tten_v\/=10;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tresult_type operator[](const std::size_t& index)const\n\t{return v.at(index);}\n\t\n\ttemplate<typename _ResultType>\n\tdigits_values operator+(const digits_values<_ResultType>& oth)\n\t{\n\t\tconst auto this_size=digit();\n\t\tconst auto oth_size=oth.digit();\t\n\t\tconst auto max_v=std::max(this_size,oth_size);\n\t\t\n\t\tusing bigger_type=if_c_t<sizeof(_ResultType) < sizeof(result_type),result_type,_ResultType>;\n\n\t\tdigits_values<bigger_type> result;\n\t\tresult.v.reserve(max_v);\n\n\t\tif(max_v==this_size){\n\t\t\tstd::copy(cbegin(),cend(),std::back_inserter(result.v));\n\t\t\tstd::size_t counter=0;\n\t\t\tfor(auto i=oth.cbegin(); i!=oth.cend(); ++i)result.v[counter++]+=*i;\n\t\t}else{\n\t\t\tstd::copy(oth.cbegin(),oth.cend(),std::back_inserter(result.v));\n\t\t\tstd::size_t counter=0;\n\t\t\tfor(auto i=cbegin(); i!=cend(); ++i)result.v[counter++]+=*i;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate<typename _ResultType>\n\tdigits_values diff(const digits_values<_ResultType>& oth)\n\t{}\n\n\ttypename std::vector<result_type>::const_iterator cbegin()const{return v.cbegin();}\n\ttypename std::vector<result_type>::const_iterator cend()const{return v.cend();}\n\ttypename std::vector<result_type>::iterator begin(){return v.begin();}\n\ttypename std::vector<result_type>::iterator end(){return v.end();}\n\ttypename std::vector<result_type>::reverse_iterator rbegin(){return v.rbegin();}\n\ttypename std::vector<result_type>::reverse_iterator rend(){return v.rend();}\n\n\tinline std::size_t digit()const{return v.size();}\n\t\n\tauto real_value()\n\t{\n\t\tauto digit_=digit();\n\t\tauto ten_v=static_cast<std::size_t>(std::pow(10,digit_-1));\n\t\tunsigned long long int result=0;\n\n\t\tfor(std::size_t i=0; i<digit_; ++i){\n\t\t\tresult+=v[i]*ten_v;\n\t\t\tten_v\/=10;\n\t\t}\n\t\treturn result;\n\t}\nprivate:\n\tstd::size_t digit_calculation(unsigned long long int x)const\n\t{return std::log10(x)+1;}\n\n\ttemplate<typename Pointed_type>\n\tstd::size_t digit_calculation(Pointed_type x)const\n\t{\n\t\tstd::size_t result=0;\n\t\tfor(; x!=0; ++result)x\/=10;\n\t\treturn result;\n\t}\n\n\tstd::vector<result_type> v;\n};\n\n} \/\/ inline namespace v1\n} \/\/ namespace srook_adl\n\ntemplate<class _Tp=unsigned short int>\nusing digits_values=srook_adl::digits_values<_Tp>;\n\n} \/\/ namespace srook\n#endif \/\/ include guard\n<|endoftext|>"} {"text":"<commit_before>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n #ifndef MATHTYPE_HXX\n#define MATHTYPE_HXX\n\n#include \"node.hxx\"\n#include \"eqnolefilehdr.hxx\"\n\n#include <sot\/storage.hxx>\n\n#include <set>\n\nclass SfxMedium;\n\nclass MathTypeFont\n{\npublic:\n sal_uInt8 nTface;\n sal_uInt8 nStyle;\n MathTypeFont() : nTface(0),nStyle(0) {}\n MathTypeFont(sal_uInt8 nFace) : nTface(nFace),nStyle(0) {}\n void AppendStyleToText(String &rS);\n};\n\nstruct LessMathTypeFont\n{\n sal_Bool operator() (const MathTypeFont &rValue1,\n const MathTypeFont &rValue2) const\n {\n return rValue1.nTface < rValue2.nTface;\n }\n};\n\ntypedef ::std::set< MathTypeFont, LessMathTypeFont > MathTypeFontSet;\n\nclass MathType\n{\npublic:\n MathType(String &rIn) :\n rRet(rIn), nHAlign(0), nVAlign(0), nDefaultSize(12),\n nLSize(0), nDSize(0), nCurSize(0), nLastSize(0), bIsSilent(sal_False)\n {\n Init();\n }\n\n MathType(String &rIn,SmNode *pIn) :\n rRet(rIn), pTree(pIn), nHAlign(2), nVAlign(0), nInsertion(0), nDefaultSize(12),\n nLSize(0), nDSize(0), nCurSize(0), nLastSize(0), nSpec(0), bIsSilent(sal_False)\n {\n Init();\n }\n\n int Parse( SotStorage* pStor );\n int ConvertFromStarMath( SfxMedium& rMedium );\n\nprivate:\n\/*Ver 2 Header*\/\n sal_uInt8 nVersion;\n sal_uInt8 nPlatform;\n sal_uInt8 nProduct;\n sal_uInt8 nProdVersion;\n sal_uInt8 nProdSubVersion;\n\n SvStorageStream *pS;\n\n void Init();\n\n int HandleRecords(int nLevel=0,sal_uInt8 nSelector=0xFF,\n sal_uInt8 nVariation=0xFF,int nRows=0,int nCols=0);\n sal_Bool HandleSize(sal_Int16 nLSize,sal_Int16 nDSize, int &rSetSize);\n void HandleAlign(sal_uInt8 nHAlign,sal_uInt8 nVAlign, int &rSetAlign);\n int HandlePile(int &rSetAlign,int nLevel,sal_uInt8 nSelector,\n sal_uInt8 nVariation);\n int HandleMatrix(int nLevel,sal_uInt8 nSelector,sal_uInt8 nVariarion);\n void HandleMatrixSeperator(int nMatrixRows,int nMatrixCols,int &rCurCol,\n int &rCurRow);\n int HandleTemplate(int nLevel,sal_uInt8 &rSelector,sal_uInt8 &rVariation,\n xub_StrLen &rLastTemplateBracket);\n void HandleEmblishments();\n void HandleSetSize();\n int HandleChar(xub_StrLen &rTextStart,int &rSetSize,int nLevel,\n sal_uInt8 nTag,sal_uInt8 nSelector,sal_uInt8 nVariation,\n sal_Bool bSilent);\n void HandleNudge();\n int xfLMOVE(sal_uInt8 nTest) const {return nTest&0x80;}\n int xfAUTO(sal_uInt8 nTest) const {return nTest&0x10;}\n int xfEMBELL(sal_uInt8 nTest) const {return nTest&0x20;}\n int xfNULL(sal_uInt8 nTest) const {return nTest&0x10;}\n int xfLSPACE(sal_uInt8 nTest) const {return nTest&0x40;}\n int xfRULER(sal_uInt8 nTest) const {return nTest&0x20;}\n\n sal_uInt8 HandleNodes(SmNode *pNode,int nLevel=0);\n int StartTemplate(sal_uInt16 nSelector,sal_uInt16 nVariation=0);\n void EndTemplate(int nOldPendingAttributes);\n void HandleSmMatrix(SmMatrixNode *pMatrix,int nLevel);\n void HandleTable(SmNode *pNode,int nLevel);\n void HandleRoot(SmNode *pNode,int nLevel);\n void HandleSubSupScript(SmNode *pNode,int nLevel);\n sal_uInt8 HandleCScript(SmNode *pNode,SmNode *pContent,int nLevel,\n sal_uLong *pPos=NULL,sal_Bool bTest=sal_True);\n void HandleFractions(SmNode *pNode,int nLevel);\n void HandleBrace(SmNode *pNode,int nLevel);\n void HandleVerticalBrace(SmNode *pNode,int nLevel);\n void HandleOperator(SmNode *pNode,int nLevel);\n sal_Bool HandleLim(SmNode *pNode,int nLevel);\n void HandleMAlign(SmNode *pNode,int nLevel);\n void HandleMath(SmNode *pNode,int nLevel);\n void HandleText(SmNode *pNode,int nLevel);\n void HandleAttributes(SmNode *pNode,int nLevel);\n void TypeFaceToString(String &rRet,sal_uInt8 nFace);\n\n String &rRet;\n SmNode *pTree;\n\n sal_uInt8 nHAlign;\n sal_uInt8 nVAlign;\n\n int nPendingAttributes;\n sal_uLong nInsertion;\n\n sal_Int16 aSizeTable[7];\n sal_Int16 nDefaultSize;\n sal_Int16 nLSize;\n sal_Int16 nDSize;\n sal_Int16 nCurSize;\n sal_Int16 nLastSize;\n sal_uInt8 nSpec;\n sal_Bool bIsSilent, bIsReInterpBrace;\n String sPost;\n xub_StrLen nPostSup;\n xub_StrLen nPostlSup;\n sal_uInt8 nTypeFace;\n MathTypeFontSet aUserStyles;\n\n enum MTOKENS {END,LINE,CHAR,TMPL,PILE,MATRIX,EMBEL,RULER,FONT,SIZE};\n enum MTEMPLATES\n {\n tmANGLE,tmPAREN,tmBRACE,tmBRACK,tmBAR,tmDBAR,tmFLOOR,tmCEILING,\n tmLBLB,tmRBRB,tmRBLB,tmLBRP,tmLPRB,tmROOT,tmFRACT,tmSCRIPT,tmUBAR,\n tmOBAR,tmLARROW,tmRARROW,tmBARROW,tmSINT,tmDINT,tmTINT,tmSSINT,\n tmDSINT,tmTSINT,tmUHBRACE,tmLHBRACE,tmSUM\n };\npublic:\n static sal_Bool LookupChar(sal_Unicode nChar,String &rRet,\n sal_uInt8 nVersion=3,sal_uInt8 nTypeFace=0);\n};\n\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>valgrind: init nTypeFace<commit_after>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n #ifndef MATHTYPE_HXX\n#define MATHTYPE_HXX\n\n#include \"node.hxx\"\n#include \"eqnolefilehdr.hxx\"\n\n#include <sot\/storage.hxx>\n\n#include <set>\n\nclass SfxMedium;\n\nclass MathTypeFont\n{\npublic:\n sal_uInt8 nTface;\n sal_uInt8 nStyle;\n MathTypeFont() : nTface(0),nStyle(0) {}\n MathTypeFont(sal_uInt8 nFace) : nTface(nFace),nStyle(0) {}\n void AppendStyleToText(String &rS);\n};\n\nstruct LessMathTypeFont\n{\n sal_Bool operator() (const MathTypeFont &rValue1,\n const MathTypeFont &rValue2) const\n {\n return rValue1.nTface < rValue2.nTface;\n }\n};\n\ntypedef ::std::set< MathTypeFont, LessMathTypeFont > MathTypeFontSet;\n\nclass MathType\n{\npublic:\n MathType(String &rIn) :\n rRet(rIn), nHAlign(0), nVAlign(0), nDefaultSize(12),\n nLSize(0), nDSize(0), nCurSize(0), nLastSize(0), bIsSilent(sal_False),\n nTypeFace(0)\n {\n Init();\n }\n\n MathType(String &rIn,SmNode *pIn) :\n rRet(rIn), pTree(pIn), nHAlign(2), nVAlign(0), nInsertion(0), nDefaultSize(12),\n nLSize(0), nDSize(0), nCurSize(0), nLastSize(0), nSpec(0), bIsSilent(sal_False),\n nTypeFace(0)\n {\n Init();\n }\n\n int Parse( SotStorage* pStor );\n int ConvertFromStarMath( SfxMedium& rMedium );\n\nprivate:\n\/*Ver 2 Header*\/\n sal_uInt8 nVersion;\n sal_uInt8 nPlatform;\n sal_uInt8 nProduct;\n sal_uInt8 nProdVersion;\n sal_uInt8 nProdSubVersion;\n\n SvStorageStream *pS;\n\n void Init();\n\n int HandleRecords(int nLevel=0,sal_uInt8 nSelector=0xFF,\n sal_uInt8 nVariation=0xFF,int nRows=0,int nCols=0);\n sal_Bool HandleSize(sal_Int16 nLSize,sal_Int16 nDSize, int &rSetSize);\n void HandleAlign(sal_uInt8 nHAlign,sal_uInt8 nVAlign, int &rSetAlign);\n int HandlePile(int &rSetAlign,int nLevel,sal_uInt8 nSelector,\n sal_uInt8 nVariation);\n int HandleMatrix(int nLevel,sal_uInt8 nSelector,sal_uInt8 nVariarion);\n void HandleMatrixSeperator(int nMatrixRows,int nMatrixCols,int &rCurCol,\n int &rCurRow);\n int HandleTemplate(int nLevel,sal_uInt8 &rSelector,sal_uInt8 &rVariation,\n xub_StrLen &rLastTemplateBracket);\n void HandleEmblishments();\n void HandleSetSize();\n int HandleChar(xub_StrLen &rTextStart,int &rSetSize,int nLevel,\n sal_uInt8 nTag,sal_uInt8 nSelector,sal_uInt8 nVariation,\n sal_Bool bSilent);\n void HandleNudge();\n int xfLMOVE(sal_uInt8 nTest) const {return nTest&0x80;}\n int xfAUTO(sal_uInt8 nTest) const {return nTest&0x10;}\n int xfEMBELL(sal_uInt8 nTest) const {return nTest&0x20;}\n int xfNULL(sal_uInt8 nTest) const {return nTest&0x10;}\n int xfLSPACE(sal_uInt8 nTest) const {return nTest&0x40;}\n int xfRULER(sal_uInt8 nTest) const {return nTest&0x20;}\n\n sal_uInt8 HandleNodes(SmNode *pNode,int nLevel=0);\n int StartTemplate(sal_uInt16 nSelector,sal_uInt16 nVariation=0);\n void EndTemplate(int nOldPendingAttributes);\n void HandleSmMatrix(SmMatrixNode *pMatrix,int nLevel);\n void HandleTable(SmNode *pNode,int nLevel);\n void HandleRoot(SmNode *pNode,int nLevel);\n void HandleSubSupScript(SmNode *pNode,int nLevel);\n sal_uInt8 HandleCScript(SmNode *pNode,SmNode *pContent,int nLevel,\n sal_uLong *pPos=NULL,sal_Bool bTest=sal_True);\n void HandleFractions(SmNode *pNode,int nLevel);\n void HandleBrace(SmNode *pNode,int nLevel);\n void HandleVerticalBrace(SmNode *pNode,int nLevel);\n void HandleOperator(SmNode *pNode,int nLevel);\n sal_Bool HandleLim(SmNode *pNode,int nLevel);\n void HandleMAlign(SmNode *pNode,int nLevel);\n void HandleMath(SmNode *pNode,int nLevel);\n void HandleText(SmNode *pNode,int nLevel);\n void HandleAttributes(SmNode *pNode,int nLevel);\n void TypeFaceToString(String &rRet,sal_uInt8 nFace);\n\n String &rRet;\n SmNode *pTree;\n\n sal_uInt8 nHAlign;\n sal_uInt8 nVAlign;\n\n int nPendingAttributes;\n sal_uLong nInsertion;\n\n sal_Int16 aSizeTable[7];\n sal_Int16 nDefaultSize;\n sal_Int16 nLSize;\n sal_Int16 nDSize;\n sal_Int16 nCurSize;\n sal_Int16 nLastSize;\n sal_uInt8 nSpec;\n sal_Bool bIsSilent, bIsReInterpBrace;\n String sPost;\n xub_StrLen nPostSup;\n xub_StrLen nPostlSup;\n sal_uInt8 nTypeFace;\n MathTypeFontSet aUserStyles;\n\n enum MTOKENS {END,LINE,CHAR,TMPL,PILE,MATRIX,EMBEL,RULER,FONT,SIZE};\n enum MTEMPLATES\n {\n tmANGLE,tmPAREN,tmBRACE,tmBRACK,tmBAR,tmDBAR,tmFLOOR,tmCEILING,\n tmLBLB,tmRBRB,tmRBLB,tmLBRP,tmLPRB,tmROOT,tmFRACT,tmSCRIPT,tmUBAR,\n tmOBAR,tmLARROW,tmRARROW,tmBARROW,tmSINT,tmDINT,tmTINT,tmSSINT,\n tmDSINT,tmTSINT,tmUHBRACE,tmLHBRACE,tmSUM\n };\npublic:\n static sal_Bool LookupChar(sal_Unicode nChar,String &rRet,\n sal_uInt8 nVersion=3,sal_uInt8 nTypeFace=0);\n};\n\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nGenerate all strings of n bits\n==============================\n\nRef - ADS 2.12\n\n--------------------------------------------------------------------------------\n\nProblem\n=======\nGenerate all strings of n bits. Assume A[0...n-1] is an array of size n.\n\n--------------------------------------------------------------------------------\n\nAlgorithm\n=========\n1) Every bit can take two values, 0s and 1s.\n2) Start from end of string and set current bit as 0 and 1.\n3) Call recursively.\n\n--------------------------------------------------------------------------------\n\nTime Complexity\n===============\nO(2^n)\n\n--------------------------------------------------------------------------------\n\nOutput\n======\n000\n100\n010\n110\n001\n101\n011\n111\n\n*******************************************************************************\/\n\n#include <stdio.h>\n\nchar A[3];\n\nvoid genString(int n) {\n if (n == 0) {\n printf(\"%s\\n\", A);\n }\n else {\n A[n - 1] = '0';\n genString(n - 1);\n A[n - 1] = '1';\n genString(n - 1);\n }\n}\n\nint main() {\n genString(3);\n return 0;\n}\n<commit_msg>Add K-ary strings<commit_after>\/*******************************************************************************\n\nGenerate all strings of n bits\n==============================\n\nRef - ADS 2.12\n\n--------------------------------------------------------------------------------\n\nProblem\n=======\nGenerate all strings of n bits. Assume A[0...n-1] is an array of size n.\n\n--------------------------------------------------------------------------------\n\nAlgorithm\n=========\n1) Every bit can take two values, 0s and 1s.\n2) Start from end of string and set current bit as 0 and 1.\n3) Call recursively.\n\n--------------------------------------------------------------------------------\n\nTime Complexity\n===============\nO(2^n)\nO(k^n)\n\n--------------------------------------------------------------------------------\n\nOutput\n======\nBinary strings:\n000\n100\n010\n110\n001\n101\n011\n111\n\nK-ary strings:\n000\n100\n200\n010\n110\n210\n020\n120\n220\n001\n101\n201\n011\n111\n211\n021\n121\n221\n002\n102\n202\n012\n112\n212\n022\n122\n222\n\n*******************************************************************************\/\n\n#include <stdio.h>\n\nchar A[3];\n\nvoid genString(int n) {\n if (n == 0) {\n printf(\"%s\\n\", A);\n }\n else {\n A[n - 1] = '0';\n genString(n - 1);\n A[n - 1] = '1';\n genString(n - 1);\n }\n}\n\nvoid genKString(int n, int k) {\n if (n == 0) {\n printf(\"%s\\n\", A);\n }\n else {\n for (int j = 0; j < k; j++) {\n A[n - 1] = '0' + j;\n genKString(n - 1, k);\n }\n }\n}\n\nint main() {\n printf(\"Binary strings:\\n\");\n genString(3);\n printf(\"\\nK-ary strings:\\n\");\n genKString(3, 3);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: zipexcptn.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2007-03-26 13:48:35 $\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_shell.hxx\"\n\n#ifndef GLOBAL_HXX_INCLUDED\n#include \"internal\/global.hxx\"\n#endif\n\n#ifndef ZIPEXCPTN_HXX_INCLUDED\n#include \"zipexcptn.hxx\"\n#endif\n\n\/\/------------------------------------------\n\/**\n*\/\nRuntimeException::RuntimeException(int Error) :\n m_Error(Error)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nRuntimeException::~RuntimeException() throw()\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nint RuntimeException::GetErrorCode() const\n{\n return m_Error;\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nZipException::ZipException(int Error) :\n RuntimeException(Error)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nconst char* ZipException::what() const throw()\n{\n return 0;\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nWin32Exception::Win32Exception(int Error) :\n RuntimeException(Error),\n m_MsgBuff(0)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nWin32Exception::~Win32Exception() throw()\n{\n if (m_MsgBuff)\n LocalFree(m_MsgBuff);\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nconst char* Win32Exception::what() const throw()\n{\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER |\n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n GetErrorCode(),\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/\/ Default language\n (LPTSTR) &m_MsgBuff,\n 0,\n NULL);\n\n return reinterpret_cast<char*>(m_MsgBuff);\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nZipContentMissException::ZipContentMissException(int Error) :\n ZipException(Error)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nAccessViolationException::AccessViolationException(int Error) :\n Win32Exception(Error)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nIOException::IOException(int Error) :\n Win32Exception(Error)\n{\n}\n<commit_msg>INTEGRATION: CWS os2port02 (1.6.40); FILE MERGED 2007\/10\/04 19:45:58 ydario 1.6.40.1: Issue number: i82034 Submitted by: ydario Reviewed by: ydario Commit of changes for OS\/2 CWS source code integration.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: zipexcptn.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 13:11:26 $\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_shell.hxx\"\n\n#ifndef GLOBAL_HXX_INCLUDED\n#include \"internal\/global.hxx\"\n#endif\n\n#ifndef ZIPEXCPTN_HXX_INCLUDED\n#include \"zipexcptn.hxx\"\n#endif\n\n\/\/------------------------------------------\n\/**\n*\/\nRuntimeException::RuntimeException(int Error) :\n m_Error(Error)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nRuntimeException::~RuntimeException() throw()\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nint RuntimeException::GetErrorCode() const\n{\n return m_Error;\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nZipException::ZipException(int Error) :\n RuntimeException(Error)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nconst char* ZipException::what() const throw()\n{\n return 0;\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nWin32Exception::Win32Exception(int Error) :\n RuntimeException(Error),\n m_MsgBuff(0)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nWin32Exception::~Win32Exception() throw()\n{\n#ifndef OS2\n if (m_MsgBuff)\n LocalFree(m_MsgBuff);\n#endif\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nconst char* Win32Exception::what() const throw()\n{\n#ifdef OS2\n return \"Win32Exception!\";\n#else\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER |\n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n GetErrorCode(),\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/\/ Default language\n (LPTSTR) &m_MsgBuff,\n 0,\n NULL);\n\n return reinterpret_cast<char*>(m_MsgBuff);\n#endif\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nZipContentMissException::ZipContentMissException(int Error) :\n ZipException(Error)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nAccessViolationException::AccessViolationException(int Error) :\n Win32Exception(Error)\n{\n}\n\n\/\/------------------------------------------\n\/**\n*\/\nIOException::IOException(int Error) :\n Win32Exception(Error)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef _DEBUG\n#include <iostream>\n#include <boost\/format.hpp>\n#endif\n\n#include <vector>\n#include <algorithm>\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include <data_type.hpp>\n#include <sort_algorithm\/compare.hpp>\n#include <sort_algorithm\/adjacent.hpp>\n#include <sort_algorithm\/compare.hpp>\n#include <sort_algorithm\/yrange2.hpp>\n#include <gui.hpp>\n\n\/\/ 2値座標系式から1値座標系式に変えながら和\n\/\/ 指定した範囲の配列の和を返す\nint yrange2::array_sum(return_type const& array_, int const x, int const y, int const height, int const width) const\n{\n int sum = 0;\n for(int i=0; i<height; ++i)\n {\n for(int j=0; j<width; ++j)\n {\n auto const& target_point = array_[y + i][x + j];\n\t\t\tif (target_point.x == std::numeric_limits<int>::max() && target_point.y == std::numeric_limits<int>::max()) return -1;\n\t\t\telse\n {\n auto const point = target_point.y * width + target_point.x;\n sum += (point > 1000) ? 777 : point;\n }\n }\n }\n return sum;\n}\n\n\/*縦列単位で入れ替え*\/\nvoid yrange2::column_replacement(answer_type_y & answer)\n{\n\tint const sepx = data_.split_num.first;\n\tint const sepy = data_.split_num.second;\n\tuint_fast64_t good_val;\n\tstd::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));\n\tgood_matrix = answer.points;\n\tgood_val = form_evaluate(comp_,good_matrix);\n\n\tfor (int i = 0; i < sepx; ++i){\n\t\tfor (int j = 0; j < sepy; ++j){\n\t\t\tanswer.points[j].insert(answer.points[j].begin(), answer.points[j][sepx - 1]);\n\t\t\tanswer.points[j].pop_back();\n\t\t}\n\t\tauto const temp_score = form_evaluate(comp_, answer.points);\n\t\tif (good_val>temp_score){\n\t\t\tgood_val = temp_score;\n\t\t\tgood_matrix = answer.points;\n\t\t}\n\t}\n\tanswer.points = good_matrix;\n\tanswer.score = good_val;\n}\n\n\/*横列単位で入れ替え*\/\nvoid yrange2::row_replacement(answer_type_y& answer)\n{\n\tint const sepx = data_.split_num.first;\n\tint const sepy = data_.split_num.second;\n\tuint_fast64_t good_val;\n\tstd::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));\n\tstd::vector<point_type> temp_vec;\n\tgood_matrix = answer.points;\n\tgood_val = form_evaluate(comp_,answer.points);\n\tfor (int i = 0; i < sepy; ++i){\n\t\tanswer.points.insert(answer.points.begin(), answer.points[sepy - 1]);\n\t\tanswer.points.pop_back();\n\t\tauto const temp_score = form_evaluate(comp_, answer.points);\n\t\tif (good_val>temp_score){\n\t\t\tgood_val = temp_score;\n\t\t\tgood_matrix = answer.points;\n\t\t}\n\t}\n\tanswer.points = good_matrix;\n\tanswer.score = good_val;\n}\n\n\/\/cv::matの塊にする\ncv::Mat yrange2::combine_image(answer_type_y const& answer)\n{\n\tint const one_picx = data_.size.first \/ data_.split_num.first;\n\tint const one_picy = data_.size.second \/ data_.split_num.second;\n\n\tsplitter sp;\/\/どこからか持ってきてたsplitter\n\tsplit_image_type splitted = sp.split_image(data_);\n\tcv::Mat comb_pic(cv::Size(data_.size.first, data_.size.second), CV_8UC3);\n\tfor (int i = 0; i < data_.split_num.second; ++i){\n\t\tfor (int j = 0; j < data_.split_num.first; ++j){\n\t\t\tcv::Rect roi_rect(j*one_picx, i*one_picy, one_picx, one_picy);\n\t\t\tcv::Mat roi_mat(comb_pic, roi_rect);\n\t\t\tsplitted[answer.points[i][j].y][answer.points[i][j].x].copyTo(roi_mat);\n\t\t}\n\t}\n\treturn std::move(comb_pic.clone());\n}\n\nyrange2::yrange2(question_raw_data const& data, compared_type const& comp)\n : data_(data), comp_(comp), adjacent_data_(select_minimum(comp))\n{\n}\n\nstd::vector<std::vector<std::vector<point_type>>> yrange2::operator() ()\n{\n\tauto const width = data_.split_num.first;\n\tauto const height = data_.split_num.second;\n\n\tauto const exists = [height, width](point_type const& p)\n\t{\n\t\treturn 0 <= p.x && p.x < width && 0 <= p.y && p.y < height;\n\t};\n\n\tstd::vector<std::vector<point_type>> sorted_matrix(\n\t\theight * 2 - 1,\n\t\tstd::vector<point_type>(\n\t\twidth * 2 - 1,\n\t\t{ std::numeric_limits<int>::max(), std::numeric_limits<int>::max() }\n\t\t)\n\t\t);\n\n\tstd::vector<answer_type_y> answer;\n\tsplitter sp;\n\n\n\t\/\/すべてのピースから並べ始めるためのループ\n\tfor (int c_y = 0; c_y < height; ++c_y) for (int c_x = 0; c_x < width; ++c_x)\n\t{\n\t\tsorted_matrix[height - 1][width - 1] = point_type{ c_x, c_y };\n\n\t\t\/\/上に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i)\n\t\t{\n\t\t\tauto const& adjacent = sorted_matrix[height - 1 - i][width - 1];\n\t\t\tsorted_matrix[height - 2 - i][width - 1] = adjacent_data_[adjacent.y][adjacent.x].up;\n\t\t\tif (sorted_matrix[height - 2 - i][width - 1].y < 0 || sorted_matrix[height - 2 - i][width - 1].y >= height) break;\n\t\t}\n\t\t\/\/下に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i)\n\t\t{\n\t\t\tauto const& adjacent = sorted_matrix[height - 1 + i][width - 1];\n\t\t\tsorted_matrix[height + i][width - 1] = adjacent_data_[adjacent.y][adjacent.x].down;\n\t\t\tif (sorted_matrix[height + i][width - 1].y < 0 || sorted_matrix[height + i][width - 1].y >= height) break;\n\t\t}\n\t\t\/\/右に見ていく\n\t\tfor (int i = 0; i < width - 1; ++i)\n\t\t{\n\t\t\tauto const& adjacent = sorted_matrix[height - 1][width - 1 + i];\n\t\t\tsorted_matrix[height - 1][width + i] = adjacent_data_[adjacent.y][adjacent.x].right;\n\t\t\tif (sorted_matrix[height - 1][width + i].x < 0 || sorted_matrix[height - 1][width + i].x >= width) break;\n\t\t}\n\t\t\/\/左に見ていく\n\t\tfor (int i = 0; i < width - 1; ++i)\n\t\t{\n\t\t\tauto const& adjacent = sorted_matrix[height - 1][width - 1 - i];\n\t\t\tsorted_matrix[height - 1][width - 2 - i] = adjacent_data_[adjacent.y][adjacent.x].left;\n\t\t\tif (sorted_matrix[height - 1][width - 2 - i].x < 0 || sorted_matrix[height - 1][width - 2 - i].x >= width) break;\n\t\t}\n\n\t\t\/\/中心を除き上に向かってループ,右に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)\n\t\t{\n\t\t\tauto const& center = sorted_matrix[height - i - 1][width + j - 1];\n\t\t\tauto const& upper = sorted_matrix[height - i - 2][width + j - 1];\n\t\t\tauto const& right = sorted_matrix[height - i - 1][width + j];\n\n\t\t\tif (exists(center) && exists(upper) && exists(right))\n\t\t\t\tsorted_matrix[height - i - 2][width + j] = ur_choose(comp_, upper, center, right);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\t\/\/中心を除き上に向かってループ,左に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)\n\t\t{\n\t\t\tauto const& center = sorted_matrix[height - i - 1][width - j - 1];\n\t\t\tauto const& upper = sorted_matrix[height - i - 2][width - j - 1];\n\t\t\tauto const& left = sorted_matrix[height - i - 1][width - j - 2];\n\n\t\t\tif (exists(center) && exists(upper) && exists(left))\n\t\t\t\tsorted_matrix[height - i - 2][width - j - 2] = ul_choose(comp_, upper, left, center);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\t\/\/中心を除き下に向かってループ,右に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)\n\t\t{\n\t\t\tauto const& center = sorted_matrix[height + i - 1][width + j - 1];\n\t\t\tauto const& lower = sorted_matrix[height + i][width + j - 1];\n\t\t\tauto const& right = sorted_matrix[height + i - 1][width + j];\n\n\t\t\tif (exists(center) && exists(lower) && exists(right))\n\t\t\t\tsorted_matrix[height + i][width + j] = dr_choose(comp_, center, right, lower);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\t\/\/中心を除き下に向かってループ,左に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)\n\t\t{\n\t\t\tauto const& center = sorted_matrix[height + i - 1][width - j - 1];\n\t\t\tauto const& lower = sorted_matrix[height + i][width - j - 1];\n\t\t\tauto const& left = sorted_matrix[height + i - 1][width - j - 2];\n\n\t\t\tif (exists(center) && exists(lower) && exists(left))\n\t\t\t\tsorted_matrix[height + i][width - j - 2] = dl_choose(comp_, left, center, lower);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\tfor (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x)\n\t\t{\n\t\t\tif (array_sum(sorted_matrix, x, y, height, width) == ((width*height - 1)*(width*height) \/ 2) && get_kind_num(data_, sorted_matrix, x, y) == width*height)\n\t\t\t{\n\t\t\t\tstd::vector<std::vector<point_type>> one_answer(height, std::vector<point_type>(width));\n\t\t\t\tfor (int i = 0; i < height; i++) for (int j = 0; j < width; j++)\n\t\t\t\t{\n\t\t\t\t\tone_answer[i][j] = sorted_matrix[y + i][x + j];\n\t\t\t\t}\n\t\t\t\tanswer_type_y temp;\n\t\t\t\ttemp.points = one_answer;\n\t\t\t\tanswer.push_back(std::move(temp));\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/現段階で重複しているものは1つに絞る\n\t\/\/ unique()を使う準備としてソートが必要\n\tstd::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });\n\t\/\/ unique()をしただけでは後ろにゴミが残るので、eraseで削除する\n\tanswer.erase(std::unique(answer.begin(), answer.end()), answer.end());\n\n\t\/\/#########################################################yrange2.5#########################################################\/\/\n\n\t\/\/縦入れ替え,横入れ替え\n\tfor (auto &matrix : answer){\n\t\trow_replacement(matrix);\n\t\tcolumn_replacement(matrix);\n\t\trow_replacement(matrix);\n\t}\n\n\t\/\/もっかいやっとく\n\tstd::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });\n\tanswer.erase(std::unique(answer.begin(), answer.end()), answer.end());\n\n\t\/\/無駄に多く返してもしょうがないので枝抜き\n\tstd::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.score < b.score; });\n\tif (answer.size() >= 3) answer.resize(3);\n\n\t\/\/一枚のcv::Matにする\n\tfor (auto& one_answer : answer)\n\t{\n\t\tone_answer.mat_image = std::move(combine_image(one_answer));\n\t}\n\t\n#ifdef _DEBUG\n std::cout << \"There are \" << answer.size() << \" solutions\" << std::endl;\n\tfor (auto const& one_answer : answer)\n\t{\n\t\tfor (int i = 0; i < one_answer.points.size(); ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < one_answer.points.at(0).size(); ++j)\n\t\t\t{\n\t\t\t\tauto const& data = one_answer.points[i][j];\n\t\t\t\tstd::cout << boost::format(\"(%2d,%2d) \") % data.x % data.y;\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n\t\tstd::cout << \"score = \" << one_answer.score << std::endl;\n\t}\n\tgui::show_image(data_, comp_, answer);\n#endif\n\n\t\/\/TODO:ここどうにかしよう\n\tstd::vector<return_type> return_vec;\n\tfor (auto const& one_answer : answer)\n\t{\n\t\treturn_vec.push_back(std::move(one_answer.points));\n\t}\n\treturn return_vec;\n}\n<commit_msg>パラメータ調整に対応<commit_after>#ifdef _DEBUG\n#include <iostream>\n#include <boost\/format.hpp>\n#endif\n\n#include <vector>\n#include <algorithm>\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include <data_type.hpp>\n#include <sort_algorithm\/compare.hpp>\n#include <sort_algorithm\/adjacent.hpp>\n#include <sort_algorithm\/compare.hpp>\n#include <sort_algorithm\/yrange2.hpp>\n#include <gui.hpp>\n\n\/\/ 2値座標系式から1値座標系式に変えながら和\n\/\/ 指定した範囲の配列の和を返す\nint yrange2::array_sum(return_type const& array_, int const x, int const y, int const height, int const width) const\n{\n int sum = 0;\n for(int i=0; i<height; ++i)\n {\n for(int j=0; j<width; ++j)\n {\n auto const& target_point = array_[y + i][x + j];\n\t\t\tif (target_point.x == std::numeric_limits<int>::max() && target_point.y == std::numeric_limits<int>::max()) return -1;\n\t\t\telse\n {\n auto const point = target_point.y * width + target_point.x;\n sum += (point > 1000) ? 777 : point;\n }\n }\n }\n return sum;\n}\n\n\/*縦列単位で入れ替え*\/\nvoid yrange2::column_replacement(answer_type_y & answer)\n{\n\tint const sepx = data_.split_num.first;\n\tint const sepy = data_.split_num.second;\n\tuint_fast64_t good_val;\n\tstd::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));\n\tgood_matrix = answer.points;\n\tgood_val = form_evaluate(comp_,good_matrix);\n\n\tfor (int i = 0; i < sepx; ++i){\n\t\tfor (int j = 0; j < sepy; ++j){\n\t\t\tanswer.points[j].insert(answer.points[j].begin(), answer.points[j][sepx - 1]);\n\t\t\tanswer.points[j].pop_back();\n\t\t}\n\t\tauto const temp_score = form_evaluate(comp_, answer.points);\n\t\tif (good_val>temp_score){\n\t\t\tgood_val = temp_score;\n\t\t\tgood_matrix = answer.points;\n\t\t}\n\t}\n\tanswer.points = good_matrix;\n\tanswer.score = good_val;\n}\n\n\/*横列単位で入れ替え*\/\nvoid yrange2::row_replacement(answer_type_y& answer)\n{\n\tint const sepx = data_.split_num.first;\n\tint const sepy = data_.split_num.second;\n\tuint_fast64_t good_val;\n\tstd::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));\n\tstd::vector<point_type> temp_vec;\n\tgood_matrix = answer.points;\n\tgood_val = form_evaluate(comp_,answer.points);\n\tfor (int i = 0; i < sepy; ++i){\n\t\tanswer.points.insert(answer.points.begin(), answer.points[sepy - 1]);\n\t\tanswer.points.pop_back();\n\t\tauto const temp_score = form_evaluate(comp_, answer.points);\n\t\tif (good_val>temp_score){\n\t\t\tgood_val = temp_score;\n\t\t\tgood_matrix = answer.points;\n\t\t}\n\t}\n\tanswer.points = good_matrix;\n\tanswer.score = good_val;\n}\n\n\/\/cv::matの塊にする\ncv::Mat yrange2::combine_image(answer_type_y const& answer)\n{\n\tint const one_picx = data_.size.first \/ data_.split_num.first;\n\tint const one_picy = data_.size.second \/ data_.split_num.second;\n\n\tsplitter sp;\/\/どこからか持ってきてたsplitter\n\tsplit_image_type splitted = sp.split_image(data_);\n\tcv::Mat comb_pic(cv::Size(data_.size.first, data_.size.second), CV_8UC3);\n\tfor (int i = 0; i < data_.split_num.second; ++i){\n\t\tfor (int j = 0; j < data_.split_num.first; ++j){\n\t\t\tcv::Rect roi_rect(j*one_picx, i*one_picy, one_picx, one_picy);\n\t\t\tcv::Mat roi_mat(comb_pic, roi_rect);\n\t\t\tsplitted[answer.points[i][j].y][answer.points[i][j].x].copyTo(roi_mat);\n\t\t}\n\t}\n\treturn std::move(comb_pic.clone());\n}\n\nyrange2::yrange2(question_raw_data const& data, compared_type const& comp)\n : data_(data), comp_(comp), adjacent_data_(select_minimum(comp))\n{\n}\n\nstd::vector<std::vector<std::vector<point_type>>> yrange2::operator() ()\n{\n\tauto const width = data_.split_num.first;\n\tauto const height = data_.split_num.second;\n\tint constexpr yrange2_show_ans = 8;\n\n\tauto const exists = [height, width](point_type const& p)\n\t{\n\t\treturn 0 <= p.x && p.x < width && 0 <= p.y && p.y < height;\n\t};\n\n\tstd::vector<std::vector<point_type>> sorted_matrix(\n\t\theight * 2 - 1,\n\t\tstd::vector<point_type>(\n\t\twidth * 2 - 1,\n\t\t{ std::numeric_limits<int>::max(), std::numeric_limits<int>::max() }\n\t\t)\n\t\t);\n\n\tstd::vector<answer_type_y> answer;\n\tsplitter sp;\n\n\n\t\/\/すべてのピースから並べ始めるためのループ\n\tfor (int c_y = 0; c_y < height; ++c_y) for (int c_x = 0; c_x < width; ++c_x)\n\t{\n\t\tsorted_matrix[height - 1][width - 1] = point_type{ c_x, c_y };\n\n\t\t\/\/上に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i)\n\t\t{\n\t\t\tauto const& adjacent = sorted_matrix[height - 1 - i][width - 1];\n\t\t\tsorted_matrix[height - 2 - i][width - 1] = adjacent_data_[adjacent.y][adjacent.x].up;\n\t\t\tif (sorted_matrix[height - 2 - i][width - 1].y < 0 || sorted_matrix[height - 2 - i][width - 1].y >= height) break;\n\t\t}\n\t\t\/\/下に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i)\n\t\t{\n\t\t\tauto const& adjacent = sorted_matrix[height - 1 + i][width - 1];\n\t\t\tsorted_matrix[height + i][width - 1] = adjacent_data_[adjacent.y][adjacent.x].down;\n\t\t\tif (sorted_matrix[height + i][width - 1].y < 0 || sorted_matrix[height + i][width - 1].y >= height) break;\n\t\t}\n\t\t\/\/右に見ていく\n\t\tfor (int i = 0; i < width - 1; ++i)\n\t\t{\n\t\t\tauto const& adjacent = sorted_matrix[height - 1][width - 1 + i];\n\t\t\tsorted_matrix[height - 1][width + i] = adjacent_data_[adjacent.y][adjacent.x].right;\n\t\t\tif (sorted_matrix[height - 1][width + i].x < 0 || sorted_matrix[height - 1][width + i].x >= width) break;\n\t\t}\n\t\t\/\/左に見ていく\n\t\tfor (int i = 0; i < width - 1; ++i)\n\t\t{\n\t\t\tauto const& adjacent = sorted_matrix[height - 1][width - 1 - i];\n\t\t\tsorted_matrix[height - 1][width - 2 - i] = adjacent_data_[adjacent.y][adjacent.x].left;\n\t\t\tif (sorted_matrix[height - 1][width - 2 - i].x < 0 || sorted_matrix[height - 1][width - 2 - i].x >= width) break;\n\t\t}\n\n\t\t\/\/中心を除き上に向かってループ,右に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)\n\t\t{\n\t\t\tauto const& center = sorted_matrix[height - i - 1][width + j - 1];\n\t\t\tauto const& upper = sorted_matrix[height - i - 2][width + j - 1];\n\t\t\tauto const& right = sorted_matrix[height - i - 1][width + j];\n\n\t\t\tif (exists(center) && exists(upper) && exists(right))\n\t\t\t\tsorted_matrix[height - i - 2][width + j] = ur_choose(comp_, upper, center, right);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\t\/\/中心を除き上に向かってループ,左に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)\n\t\t{\n\t\t\tauto const& center = sorted_matrix[height - i - 1][width - j - 1];\n\t\t\tauto const& upper = sorted_matrix[height - i - 2][width - j - 1];\n\t\t\tauto const& left = sorted_matrix[height - i - 1][width - j - 2];\n\n\t\t\tif (exists(center) && exists(upper) && exists(left))\n\t\t\t\tsorted_matrix[height - i - 2][width - j - 2] = ul_choose(comp_, upper, left, center);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\t\/\/中心を除き下に向かってループ,右に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)\n\t\t{\n\t\t\tauto const& center = sorted_matrix[height + i - 1][width + j - 1];\n\t\t\tauto const& lower = sorted_matrix[height + i][width + j - 1];\n\t\t\tauto const& right = sorted_matrix[height + i - 1][width + j];\n\n\t\t\tif (exists(center) && exists(lower) && exists(right))\n\t\t\t\tsorted_matrix[height + i][width + j] = dr_choose(comp_, center, right, lower);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\t\/\/中心を除き下に向かってループ,左に見ていく\n\t\tfor (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)\n\t\t{\n\t\t\tauto const& center = sorted_matrix[height + i - 1][width - j - 1];\n\t\t\tauto const& lower = sorted_matrix[height + i][width - j - 1];\n\t\t\tauto const& left = sorted_matrix[height + i - 1][width - j - 2];\n\n\t\t\tif (exists(center) && exists(lower) && exists(left))\n\t\t\t\tsorted_matrix[height + i][width - j - 2] = dl_choose(comp_, left, center, lower);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\tfor (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x)\n\t\t{\n\t\t\tif (array_sum(sorted_matrix, x, y, height, width) == ((width*height - 1)*(width*height) \/ 2) && get_kind_num(data_, sorted_matrix, x, y) == width*height)\n\t\t\t{\n\t\t\t\tstd::vector<std::vector<point_type>> one_answer(height, std::vector<point_type>(width));\n\t\t\t\tfor (int i = 0; i < height; i++) for (int j = 0; j < width; j++)\n\t\t\t\t{\n\t\t\t\t\tone_answer[i][j] = sorted_matrix[y + i][x + j];\n\t\t\t\t}\n\t\t\t\tanswer_type_y temp;\n\t\t\t\ttemp.points = one_answer;\n\t\t\t\tanswer.push_back(std::move(temp));\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/現段階で重複しているものは1つに絞る\n\t\/\/ unique()を使う準備としてソートが必要\n\tstd::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });\n\t\/\/ unique()をしただけでは後ろにゴミが残るので、eraseで削除する\n\tanswer.erase(std::unique(answer.begin(), answer.end()), answer.end());\n\n\t\/\/#########################################################yrange2.5#########################################################\/\/\n\n\t\/\/縦入れ替え,横入れ替え\n\tfor (auto &matrix : answer){\n\t\trow_replacement(matrix);\n\t\tcolumn_replacement(matrix);\n\t\trow_replacement(matrix);\n\t}\n\n\t\/\/もっかいやっとく\n\tstd::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });\n\tanswer.erase(std::unique(answer.begin(), answer.end()), answer.end());\n\n\t\/\/無駄に多く返してもしょうがないので枝抜き\n\tint const yrange2_ans = answer.size();\n\tstd::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.score < b.score; });\n\tif (answer.size() >= yrange2_show_ans) answer.resize(yrange2_show_ans);\n\n\t\/\/一枚のcv::Matにする\n\tfor (auto& one_answer : answer)\n\t{\n\t\tone_answer.mat_image = std::move(combine_image(one_answer));\n\t}\n\t\n#ifdef _DEBUG\n std::cout << \"There are \" << yrange2_ans << \" solutions\" << std::endl;\n\tfor (auto const& one_answer : answer)\n\t{\n\t\tfor (int i = 0; i < one_answer.points.size(); ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < one_answer.points.at(0).size(); ++j)\n\t\t\t{\n\t\t\t\tauto const& data = one_answer.points[i][j];\n\t\t\t\tstd::cout << boost::format(\"(%2d,%2d) \") % data.x % data.y;\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n\t\tstd::cout << \"score = \" << one_answer.score << std::endl;\n\t}\n\tgui::show_image(data_, comp_, answer);\n#endif\n\n\t\/\/TODO:ここどうにかしよう\n\tstd::vector<return_type> return_vec;\n\tfor (auto const& one_answer : answer)\n\t{\n\t\treturn_vec.push_back(std::move(one_answer.points));\n\t}\n\treturn return_vec;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file. Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.3, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"cpasterplugin.h\"\n\n#include \"ui_pasteselect.h\"\n\n#include \"splitter.h\"\n#include \"view.h\"\n\n#include <coreplugin\/actionmanager\/actionmanager.h>\n#include <coreplugin\/coreconstants.h>\n#include <coreplugin\/editormanager\/editormanager.h>\n#include <coreplugin\/filemanager.h>\n#include <coreplugin\/icore.h>\n#include <coreplugin\/messagemanager.h>\n#include <coreplugin\/messageoutputwindow.h>\n#include <coreplugin\/uniqueidmanager.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <texteditor\/itexteditor.h>\n\n#include <QtCore\/QtPlugin>\n#include <QtCore\/QDebug>\n#include <QtGui\/QAction>\n#include <QtGui\/QApplication>\n#include <QtGui\/QClipboard>\n#include <QtGui\/QMenu>\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QMainWindow>\n#include <QtGui\/QListWidget>\n\nusing namespace CodePaster;\nusing namespace Core;\nusing namespace TextEditor;\n\nCodepasterPlugin::CodepasterPlugin()\n : m_settingsPage(0), m_fetcher(0), m_poster(0)\n{\n}\n\nCodepasterPlugin::~CodepasterPlugin()\n{\n if (m_settingsPage) {\n removeObject(m_settingsPage);\n delete m_settingsPage;\n m_settingsPage = 0;\n }\n}\n\nbool CodepasterPlugin::initialize(const QStringList &arguments, QString *error_message)\n{\n Q_UNUSED(arguments);\n Q_UNUSED(error_message);\n\n \/\/ Create the globalcontext list to register actions accordingly\n QList<int> globalcontext;\n globalcontext << UniqueIDManager::instance()->uniqueIdentifier(Core::Constants::C_GLOBAL);\n\n \/\/ Create the settings Page\n m_settingsPage = new SettingsPage();\n addObject(m_settingsPage);\n\n \/\/register actions\n Core::ActionManager *actionManager = ICore::instance()->actionManager();\n\n Core::ActionContainer *toolsContainer =\n actionManager->actionContainer(Core::Constants::M_TOOLS);\n\n Core::ActionContainer *cpContainer =\n actionManager->createMenu(QLatin1String(\"CodePaster\"));\n cpContainer->menu()->setTitle(tr(\"&CodePaster\"));\n toolsContainer->addMenu(cpContainer);\n\n Core::Command *command;\n\n m_postAction = new QAction(tr(\"Paste snippet...\"), this);\n command = actionManager->registerAction(m_postAction, \"CodePaster.post\", globalcontext);\n command->setDefaultKeySequence(QKeySequence(tr(\"Alt+C,Alt+P\")));\n connect(m_postAction, SIGNAL(triggered()), this, SLOT(post()));\n cpContainer->addAction(command);\n\n m_fetchAction = new QAction(tr(\"Fetch snippet...\"), this);\n command = actionManager->registerAction(m_fetchAction, \"CodePaster.fetch\", globalcontext);\n command->setDefaultKeySequence(QKeySequence(tr(\"Alt+C,Alt+F\")));\n connect(m_fetchAction, SIGNAL(triggered()), this, SLOT(fetch()));\n cpContainer->addAction(command);\n\n return true;\n}\n\nvoid CodepasterPlugin::extensionsInitialized()\n{\n m_projectExplorer = ExtensionSystem::PluginManager::instance()\n ->getObject<ProjectExplorer::ProjectExplorerPlugin>();\n}\n\nQString CodepasterPlugin::serverUrl() const\n{\n QString url = m_settingsPage->serverUrl().toString();\n if (url.startsWith(\"http:\/\/\"))\n url = url.mid(7);\n if (url.endsWith('\/'))\n url.chop(1);\n return url;\n}\n\nvoid CodepasterPlugin::post()\n{\n if (m_poster)\n delete m_poster;\n IEditor* editor = EditorManager::instance()->currentEditor();\n ITextEditor* textEditor = qobject_cast<ITextEditor*>(editor);\n if (!textEditor)\n return;\n\n QString data = textEditor->selectedText();\n if (!data.isEmpty()) {\n QChar *uc = data.data();\n QChar *e = uc + data.size();\n\n for (; uc != e; ++uc) {\n switch (uc->unicode()) {\n case 0xfdd0: \/\/ QTextBeginningOfFrame\n case 0xfdd1: \/\/ QTextEndOfFrame\n case QChar::ParagraphSeparator:\n case QChar::LineSeparator:\n *uc = QLatin1Char('\\n');\n break;\n case QChar::Nbsp:\n *uc = QLatin1Char(' ');\n break;\n default:\n ;\n }\n }\n } else\n data = textEditor->contents();\n\n FileDataList lst = splitDiffToFiles(data.toLatin1());\n QString username = m_settingsPage->username();\n QString description;\n QString comment;\n\n View view(0);\n if (!view.show(username, description, comment, lst))\n return; \/\/ User canceled post\n\n username = view.getUser();\n description = view.getDescription();\n comment = view.getComment();\n data = view.getContent();\n\n \/\/ Submit to codepaster\n\n m_poster = new CustomPoster(serverUrl());\n\n \/\/ Copied from cpaster. Otherwise lineendings will screw up\n if (!data.contains(\"\\r\\n\")) {\n if (data.contains('\\n'))\n data.replace('\\n', \"\\r\\n\");\n else if (data.contains('\\r'))\n data.replace('\\r', \"\\r\\n\");\n }\n m_poster->post(description, comment, data, username);\n}\n\nvoid CodepasterPlugin::fetch()\n{\n if (m_fetcher)\n delete m_fetcher;\n m_fetcher = new CustomFetcher(serverUrl());\n\n QDialog dialog;\n Ui_PasteSelectDialog ui;\n ui.setupUi(&dialog);\n\n ui.listWidget->addItems(QStringList() << \"Waiting for items\");\n ui.listWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);\n ui.listWidget->setFrameStyle(QFrame::NoFrame);\n m_fetcher->list(ui.listWidget);\n\n int result = dialog.exec();\n if (!result)\n return;\n bool ok;\n QStringList list = ui.pasteEdit->text().split(QLatin1Char(' '));\n int pasteID = !list.isEmpty() ? list.first().toInt(&ok) : -1;\n if (!ok || pasteID <= 0)\n return;\n\n delete m_fetcher;\n m_fetcher = new CustomFetcher(serverUrl());\n m_fetcher->fetch(pasteID);\n}\n\nCustomFetcher::CustomFetcher(const QString &host)\n : Fetcher(host)\n , m_host(host)\n , m_listWidget(0)\n , m_id(-1)\n , m_customError(false)\n{\n \/\/ cpaster calls QCoreApplication::exit which we want to avoid here\n disconnect(this, SIGNAL(requestFinished(int,bool))\n ,this, SLOT(gotRequestFinished(int,bool)));\n connect(this, SIGNAL(requestFinished(int,bool))\n , SLOT(customRequestFinished(int,bool)));\n}\n\nvoid CustomFetcher::customRequestFinished(int, bool error)\n{\n m_customError = error;\n if (m_customError || hadError()) {\n QMessageBox::warning(0, QLatin1String(\"CodePaster Error\")\n , QLatin1String(\"Could not fetch code\")\n , QMessageBox::Ok);\n return;\n }\n\n QByteArray data = body();\n if (!m_listWidget) {\n QString title = QString::fromLatin1(\"Code Paster: %1\").arg(m_id);\n EditorManager::instance()->newFile(Core::Constants::K_DEFAULT_TEXT_EDITOR, &title, data);\n } else {\n m_listWidget->clear();\n QStringList lines = QString(data).split(QLatin1Char('\\n'));\n m_listWidget->addItems(lines);\n m_listWidget = 0;\n }\n}\n\nint CustomFetcher::fetch(int pasteID)\n{\n m_id = pasteID;\n return Fetcher::fetch(pasteID);\n}\n\nvoid CustomFetcher::list(QListWidget* list)\n{\n m_listWidget = list;\n QString url = QLatin1String(\"http:\/\/\");\n url += m_host;\n url += QLatin1String(\"\/?command=browse&format=raw\");\n Fetcher::fetch(url);\n}\n\nCustomPoster::CustomPoster(const QString &host, bool copyToClipboard, bool displayOutput)\n : Poster(host), m_copy(copyToClipboard), m_output(displayOutput)\n{\n \/\/ cpaster calls QCoreApplication::exit which we want to avoid here\n disconnect(this, SIGNAL(requestFinished(int,bool)),\n this, SLOT(gotRequestFinished(int,bool)));\n connect(this, SIGNAL(requestFinished(int,bool)),\n SLOT(customRequestFinished(int,bool)));\n}\n\nvoid CustomPoster::customRequestFinished(int, bool error)\n{\n if (!error) {\n if (m_copy)\n QApplication::clipboard()->setText(pastedUrl());\n ICore::instance()->messageManager()->printToOutputPane(pastedUrl(), m_output);\n } else\n QMessageBox::warning(0, \"Code Paster Error\", \"Some error occured while posting\", QMessageBox::Ok);\n#if 0 \/\/ Figure out how to access\n Core::Internal::MessageOutputWindow* messageWindow =\n ExtensionSystem::PluginManager::instance()->getObject<Core::Internal::MessageOutputWindow>();\n if (!messageWindow)\n qDebug() << \"Pasted at:\" << pastedUrl();\n\n messageWindow->append(pastedUrl());\n messageWindow->setFocus();\n#endif\n}\n\nQ_EXPORT_PLUGIN(CodepasterPlugin)\n<commit_msg> Fixes: cpaster: fix potential double deletion test<commit_after>\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file. Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.3, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"cpasterplugin.h\"\n\n#include \"ui_pasteselect.h\"\n\n#include \"splitter.h\"\n#include \"view.h\"\n\n#include <coreplugin\/actionmanager\/actionmanager.h>\n#include <coreplugin\/coreconstants.h>\n#include <coreplugin\/editormanager\/editormanager.h>\n#include <coreplugin\/filemanager.h>\n#include <coreplugin\/icore.h>\n#include <coreplugin\/messagemanager.h>\n#include <coreplugin\/messageoutputwindow.h>\n#include <coreplugin\/uniqueidmanager.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <texteditor\/itexteditor.h>\n\n#include <QtCore\/QtPlugin>\n#include <QtCore\/QDebug>\n#include <QtGui\/QAction>\n#include <QtGui\/QApplication>\n#include <QtGui\/QClipboard>\n#include <QtGui\/QMenu>\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QMainWindow>\n#include <QtGui\/QListWidget>\n\nusing namespace CodePaster;\nusing namespace Core;\nusing namespace TextEditor;\n\nCodepasterPlugin::CodepasterPlugin()\n : m_settingsPage(0), m_fetcher(0), m_poster(0)\n{\n}\n\nCodepasterPlugin::~CodepasterPlugin()\n{\n if (m_settingsPage) {\n removeObject(m_settingsPage);\n delete m_settingsPage;\n m_settingsPage = 0;\n }\n}\n\nbool CodepasterPlugin::initialize(const QStringList &arguments, QString *error_message)\n{\n Q_UNUSED(arguments);\n Q_UNUSED(error_message);\n\n \/\/ Create the globalcontext list to register actions accordingly\n QList<int> globalcontext;\n globalcontext << UniqueIDManager::instance()->uniqueIdentifier(Core::Constants::C_GLOBAL);\n\n \/\/ Create the settings Page\n m_settingsPage = new SettingsPage();\n addObject(m_settingsPage);\n\n \/\/register actions\n Core::ActionManager *actionManager = ICore::instance()->actionManager();\n\n Core::ActionContainer *toolsContainer =\n actionManager->actionContainer(Core::Constants::M_TOOLS);\n\n Core::ActionContainer *cpContainer =\n actionManager->createMenu(QLatin1String(\"CodePaster\"));\n cpContainer->menu()->setTitle(tr(\"&CodePaster\"));\n toolsContainer->addMenu(cpContainer);\n\n Core::Command *command;\n\n m_postAction = new QAction(tr(\"Paste snippet...\"), this);\n command = actionManager->registerAction(m_postAction, \"CodePaster.post\", globalcontext);\n command->setDefaultKeySequence(QKeySequence(tr(\"Alt+C,Alt+P\")));\n connect(m_postAction, SIGNAL(triggered()), this, SLOT(post()));\n cpContainer->addAction(command);\n\n m_fetchAction = new QAction(tr(\"Fetch snippet...\"), this);\n command = actionManager->registerAction(m_fetchAction, \"CodePaster.fetch\", globalcontext);\n command->setDefaultKeySequence(QKeySequence(tr(\"Alt+C,Alt+F\")));\n connect(m_fetchAction, SIGNAL(triggered()), this, SLOT(fetch()));\n cpContainer->addAction(command);\n\n return true;\n}\n\nvoid CodepasterPlugin::extensionsInitialized()\n{\n m_projectExplorer = ExtensionSystem::PluginManager::instance()\n ->getObject<ProjectExplorer::ProjectExplorerPlugin>();\n}\n\nQString CodepasterPlugin::serverUrl() const\n{\n QString url = m_settingsPage->serverUrl().toString();\n if (url.startsWith(\"http:\/\/\"))\n url = url.mid(7);\n if (url.endsWith('\/'))\n url.chop(1);\n return url;\n}\n\nvoid CodepasterPlugin::post()\n{\n \/\/ FIXME: The whole m_poster thing is de facto a simple function call.\n if (m_poster) {\n delete m_poster;\n m_poster = 0; \n }\n IEditor* editor = EditorManager::instance()->currentEditor();\n ITextEditor* textEditor = qobject_cast<ITextEditor*>(editor);\n if (!textEditor)\n return;\n\n QString data = textEditor->selectedText();\n if (!data.isEmpty()) {\n QChar *uc = data.data();\n QChar *e = uc + data.size();\n\n for (; uc != e; ++uc) {\n switch (uc->unicode()) {\n case 0xfdd0: \/\/ QTextBeginningOfFrame\n case 0xfdd1: \/\/ QTextEndOfFrame\n case QChar::ParagraphSeparator:\n case QChar::LineSeparator:\n *uc = QLatin1Char('\\n');\n break;\n case QChar::Nbsp:\n *uc = QLatin1Char(' ');\n break;\n default:\n ;\n }\n }\n } else\n data = textEditor->contents();\n\n FileDataList lst = splitDiffToFiles(data.toLatin1());\n QString username = m_settingsPage->username();\n QString description;\n QString comment;\n\n View view(0);\n if (!view.show(username, description, comment, lst))\n return; \/\/ User canceled post\n\n username = view.getUser();\n description = view.getDescription();\n comment = view.getComment();\n data = view.getContent();\n\n \/\/ Submit to codepaster\n\n m_poster = new CustomPoster(serverUrl());\n\n \/\/ Copied from cpaster. Otherwise lineendings will screw up\n if (!data.contains(\"\\r\\n\")) {\n if (data.contains('\\n'))\n data.replace('\\n', \"\\r\\n\");\n else if (data.contains('\\r'))\n data.replace('\\r', \"\\r\\n\");\n }\n m_poster->post(description, comment, data, username);\n}\n\nvoid CodepasterPlugin::fetch()\n{\n if (m_fetcher) {\n delete m_fetcher;\n m_fetcher = 0;\n }\n m_fetcher = new CustomFetcher(serverUrl());\n\n QDialog dialog;\n Ui_PasteSelectDialog ui;\n ui.setupUi(&dialog);\n\n ui.listWidget->addItems(QStringList() << \"Waiting for items\");\n ui.listWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);\n ui.listWidget->setFrameStyle(QFrame::NoFrame);\n m_fetcher->list(ui.listWidget);\n\n int result = dialog.exec();\n if (!result)\n return;\n bool ok;\n QStringList list = ui.pasteEdit->text().split(QLatin1Char(' '));\n int pasteID = !list.isEmpty() ? list.first().toInt(&ok) : -1;\n if (!ok || pasteID <= 0)\n return;\n\n delete m_fetcher;\n m_fetcher = new CustomFetcher(serverUrl());\n m_fetcher->fetch(pasteID);\n}\n\nCustomFetcher::CustomFetcher(const QString &host)\n : Fetcher(host)\n , m_host(host)\n , m_listWidget(0)\n , m_id(-1)\n , m_customError(false)\n{\n \/\/ cpaster calls QCoreApplication::exit which we want to avoid here\n disconnect(this, SIGNAL(requestFinished(int,bool))\n ,this, SLOT(gotRequestFinished(int,bool)));\n connect(this, SIGNAL(requestFinished(int,bool))\n , SLOT(customRequestFinished(int,bool)));\n}\n\nvoid CustomFetcher::customRequestFinished(int, bool error)\n{\n m_customError = error;\n if (m_customError || hadError()) {\n QMessageBox::warning(0, QLatin1String(\"CodePaster Error\")\n , QLatin1String(\"Could not fetch code\")\n , QMessageBox::Ok);\n return;\n }\n\n QByteArray data = body();\n if (!m_listWidget) {\n QString title = QString::fromLatin1(\"Code Paster: %1\").arg(m_id);\n EditorManager::instance()->newFile(Core::Constants::K_DEFAULT_TEXT_EDITOR, &title, data);\n } else {\n m_listWidget->clear();\n QStringList lines = QString(data).split(QLatin1Char('\\n'));\n m_listWidget->addItems(lines);\n m_listWidget = 0;\n }\n}\n\nint CustomFetcher::fetch(int pasteID)\n{\n m_id = pasteID;\n return Fetcher::fetch(pasteID);\n}\n\nvoid CustomFetcher::list(QListWidget* list)\n{\n m_listWidget = list;\n QString url = QLatin1String(\"http:\/\/\");\n url += m_host;\n url += QLatin1String(\"\/?command=browse&format=raw\");\n Fetcher::fetch(url);\n}\n\nCustomPoster::CustomPoster(const QString &host, bool copyToClipboard, bool displayOutput)\n : Poster(host), m_copy(copyToClipboard), m_output(displayOutput)\n{\n \/\/ cpaster calls QCoreApplication::exit which we want to avoid here\n disconnect(this, SIGNAL(requestFinished(int,bool)),\n this, SLOT(gotRequestFinished(int,bool)));\n connect(this, SIGNAL(requestFinished(int,bool)),\n SLOT(customRequestFinished(int,bool)));\n}\n\nvoid CustomPoster::customRequestFinished(int, bool error)\n{\n if (!error) {\n if (m_copy)\n QApplication::clipboard()->setText(pastedUrl());\n ICore::instance()->messageManager()->printToOutputPane(pastedUrl(), m_output);\n } else\n QMessageBox::warning(0, \"Code Paster Error\", \"Some error occured while posting\", QMessageBox::Ok);\n#if 0 \/\/ Figure out how to access\n Core::Internal::MessageOutputWindow* messageWindow =\n ExtensionSystem::PluginManager::instance()->getObject<Core::Internal::MessageOutputWindow>();\n if (!messageWindow)\n qDebug() << \"Pasted at:\" << pastedUrl();\n\n messageWindow->append(pastedUrl());\n messageWindow->setFocus();\n#endif\n}\n\nQ_EXPORT_PLUGIN(CodepasterPlugin)\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2013-2018 Igor Zinken - http:\/\/www.igorski.nl\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * 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, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include \"sequencer.h\"\n#include \"audioengine.h\"\n#include <utilities\/utils.h>\n#include <vector>\n\nnamespace MWEngine {\n\n\/* static member intialization *\/\n\nbool Sequencer::playing = false;\nBulkCacher* Sequencer::bulkCacher = new BulkCacher( true );\nstd::vector<BaseInstrument*> Sequencer::instruments;\n\n\/* public methods *\/\n\nint Sequencer::registerInstrument( BaseInstrument* instrument )\n{\n int index = -1;\n bool wasPresent = false; \/\/ prevent double addition\n\n for ( int i = 0; i < instruments.size(); i++ )\n {\n if ( instruments.at( i ) == instrument )\n wasPresent = true;\n }\n\n if ( !wasPresent ) {\n instruments.push_back( instrument );\n index = instruments.size() - 1;\n }\n return index; \/\/ the index this instrument is registered at\n}\n\nbool Sequencer::unregisterInstrument( BaseInstrument* instrument )\n{\n for ( int i = 0; i < instruments.size(); i++ )\n {\n if ( instruments.at( i ) == instrument )\n {\n instruments.erase( instruments.begin() + i );\n return true;\n }\n }\n return false;\n}\n\nbool Sequencer::getAudioEvents( std::vector<AudioChannel*>* channels, int bufferPosition,\n int bufferSize, bool addLiveInstruments, bool flushChannels )\n{\n channels->clear();\n\n int bufferEnd = bufferPosition + ( bufferSize - 1 ); \/\/ the highest SampleEnd value we'll query\n bool loopStarted = bufferEnd > AudioEngine::max_buffer_position; \/\/ whether this request exceeds the min_buffer_position - max_buffer_position range\n\n int i, l;\n\n \/\/ note we update the channels mix properties here as they might change during playback\n\n for ( i = 0, l = ( int ) instruments.size(); i < l; ++i )\n {\n BaseInstrument* instrument = instruments.at( i );\n AudioChannel* instrumentChannel = instrument->audioChannel;\n\n \/\/ clear previous channel contents when requested\n if ( flushChannels )\n instrumentChannel->reset();\n\n if ( !instrumentChannel->muted )\n {\n if ( playing )\n collectSequencedEvents( instrument, bufferPosition, bufferEnd );\n\n if ( addLiveInstruments && instrument->hasLiveEvents() )\n collectLiveEvents( instrument );\n\n channels->push_back( instrumentChannel );\n }\n }\n return loopStarted;\n}\n\nvoid Sequencer::updateEvents()\n{\n for ( int i = 0, l = ( int ) instruments.size(); i < l; ++i )\n instruments.at( i )->updateEvents();\n}\n\nvoid Sequencer::clearEvents()\n{\n for ( int i = 0, l = ( int ) instruments.size(); i < l; ++i )\n instruments.at( i )->clearEvents();\n}\n\n\/**\n * used by the getAudioEvents-method of the sequencer, this validates\n * the present AudioEvents against the requested position\n * and updates and flushes the removal queue\n *\n * @param instrument {BaseInstrument*} instrument to gather events from\n * @param bufferPosition {int} the current buffers start pointer\n * @param bufferEnd {int} the current buffers end pointer\n *\/\nvoid Sequencer::collectSequencedEvents( BaseInstrument* instrument, int bufferPosition, int bufferEnd )\n{\n if ( !instrument->hasEvents() )\n return;\n\n AudioChannel* channel = instrument->audioChannel;\n std::vector<BaseAudioEvent*>* audioEvents = instrument->getEvents();\n\n \/\/ removal queue\n std::vector<BaseAudioEvent*> removes;\n\n \/\/ channel has an internal loop (e.g. drum machine) ? recalculate requested\n \/\/ buffer position by subtracting all measures above the first\n \n if ( channel->maxBufferPosition > 0 )\n {\n int samplesPerBar = AudioEngine::samples_per_bar;\n\n while ( bufferPosition >= channel->maxBufferPosition )\n {\n bufferPosition -= samplesPerBar;\n bufferEnd -= samplesPerBar;\n }\n }\n\n int i = 0, amount = ( int ) audioEvents->size();\n for ( ; i < amount; i++ )\n {\n BaseAudioEvent* audioEvent = audioEvents->at( i );\n\n if ( audioEvent->isEnabled() )\n {\n int eventStart = audioEvent->getEventStart();\n int eventEnd = audioEvent->getEventEnd();\n\n if (( eventStart >= bufferPosition && eventStart <= bufferEnd ) ||\n ( eventStart < bufferPosition && eventEnd >= bufferPosition ))\n {\n if ( !audioEvent->isDeletable())\n channel->addEvent( audioEvent );\n else\n removes.push_back( audioEvent );\n }\n }\n }\n \/\/ removal queue filled ? process it so we can safely\n \/\/ remove \"deleted\" AudioEvents without errors occurring\n if ( removes.size() > 0 )\n {\n for ( i = 0; i < removes.size(); i++ )\n {\n BaseAudioEvent* audioEvent = removes[ i ];\n instrument->removeEvent( audioEvent, false );\n }\n }\n}\n\nvoid Sequencer::collectLiveEvents( BaseInstrument* instrument )\n{\n AudioChannel* channel = instrument->audioChannel;\n std::vector<BaseAudioEvent*>* liveEvents = instrument->getLiveEvents();\n\n \/\/ removal queue\n std::vector<BaseAudioEvent*> removes;\n\n for ( int i = 0; i < liveEvents->size(); i++ )\n {\n BaseAudioEvent* audioEvent = liveEvents->at( i );\n\n if ( !audioEvent->isDeletable())\n channel->addLiveEvent( audioEvent );\n else\n removes.push_back( audioEvent );\n }\n \/\/ removal queue filled ? process it so we can safely\n \/\/ remove \"deleted\" AudioEvents without errors occurring\n if ( removes.size() > 0 )\n {\n for ( int i = 0; i < removes.size(); i++ )\n {\n BaseAudioEvent* audioEvent = removes[ i ];\n instrument->removeEvent( audioEvent, true );\n }\n }\n}\n\n\/**\n * used by the cacheAudioEventsForMeasure-method, this collects\n * all AudioEvents in the requested measure for entry into the BulkCacher\n *\n * @param bufferPosition {int} the desired measures buffers start pointer\n * @param bufferEnd {int} the desired measures buffers end pointer\n *\n * @return {std::vector<BaseCacheableAudioEvent*>}\n *\/\nstd::vector<BaseCacheableAudioEvent*>* Sequencer::collectCacheableSequencerEvents( int bufferPosition, int bufferEnd )\n{\n std::vector<BaseCacheableAudioEvent*>* events = new std::vector<BaseCacheableAudioEvent*>();\n\n for ( int i = 0, l = ( int ) instruments.size(); i < l; ++i )\n {\n std::vector<BaseAudioEvent*>* audioEvents = instruments.at( i )->getEvents();\n int amount = ( int ) audioEvents->size();\n\n for ( int j = 0; j < amount; j++ )\n {\n BaseAudioEvent* audioEvent = audioEvents->at( j );\n\n \/\/ if event is an instance of BaseCacheableAudioEvent add it to the list\n if ( dynamic_cast<BaseCacheableAudioEvent*>( audioEvent ) != nullptr )\n {\n int eventStart = audioEvent->getEventStart();\n int eventEnd = audioEvent->getEventEnd();\n\n if (( eventStart >= bufferPosition && eventStart <= bufferEnd ) ||\n ( eventStart < bufferPosition && eventEnd >= bufferPosition ))\n {\n if ( !audioEvent->isDeletable())\n events->push_back(( BaseCacheableAudioEvent* ) audioEvent );\n }\n }\n }\n }\n return events;\n}\n\n} \/\/ E.O namespace MWEngine\n<commit_msg>Fixed issue where sequencer could crash when disposing of events in outside thread<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2013-2019 Igor Zinken - http:\/\/www.igorski.nl\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * 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, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include \"sequencer.h\"\n#include \"audioengine.h\"\n#include <utilities\/utils.h>\n#include <vector>\n\nnamespace MWEngine {\n\n\/* static member intialization *\/\n\nbool Sequencer::playing = false;\nBulkCacher* Sequencer::bulkCacher = new BulkCacher( true );\nstd::vector<BaseInstrument*> Sequencer::instruments;\n\n\/* public methods *\/\n\nint Sequencer::registerInstrument( BaseInstrument* instrument )\n{\n int index = -1;\n bool wasPresent = false; \/\/ prevent double addition\n\n for ( int i = 0; i < instruments.size(); i++ )\n {\n if ( instruments.at( i ) == instrument )\n wasPresent = true;\n }\n\n if ( !wasPresent ) {\n instruments.push_back( instrument );\n index = instruments.size() - 1;\n }\n return index; \/\/ the index this instrument is registered at\n}\n\nbool Sequencer::unregisterInstrument( BaseInstrument* instrument )\n{\n for ( int i = 0; i < instruments.size(); i++ )\n {\n if ( instruments.at( i ) == instrument )\n {\n instruments.erase( instruments.begin() + i );\n return true;\n }\n }\n return false;\n}\n\nbool Sequencer::getAudioEvents( std::vector<AudioChannel*>* channels, int bufferPosition,\n int bufferSize, bool addLiveInstruments, bool flushChannels )\n{\n channels->clear();\n\n int bufferEnd = bufferPosition + ( bufferSize - 1 ); \/\/ the highest SampleEnd value we'll query\n bool loopStarted = bufferEnd > AudioEngine::max_buffer_position; \/\/ whether this request exceeds the min_buffer_position - max_buffer_position range\n\n int i, l;\n\n \/\/ note we update the channels mix properties here as they might change during playback\n\n for ( i = 0, l = ( int ) instruments.size(); i < l; ++i )\n {\n BaseInstrument* instrument = instruments.at( i );\n AudioChannel* instrumentChannel = instrument->audioChannel;\n\n \/\/ clear previous channel contents when requested\n if ( flushChannels )\n instrumentChannel->reset();\n\n if ( !instrumentChannel->muted )\n {\n if ( playing )\n collectSequencedEvents( instrument, bufferPosition, bufferEnd );\n\n if ( addLiveInstruments && instrument->hasLiveEvents() )\n collectLiveEvents( instrument );\n\n channels->push_back( instrumentChannel );\n }\n }\n return loopStarted;\n}\n\nvoid Sequencer::updateEvents()\n{\n for ( int i = 0, l = ( int ) instruments.size(); i < l; ++i )\n instruments.at( i )->updateEvents();\n}\n\nvoid Sequencer::clearEvents()\n{\n for ( int i = 0, l = ( int ) instruments.size(); i < l; ++i )\n instruments.at( i )->clearEvents();\n}\n\n\/**\n * used by the getAudioEvents-method of the sequencer, this validates\n * the present AudioEvents against the requested position\n * and updates and flushes the removal queue\n *\n * @param instrument {BaseInstrument*} instrument to gather events from\n * @param bufferPosition {int} the current buffers start pointer\n * @param bufferEnd {int} the current buffers end pointer\n *\/\nvoid Sequencer::collectSequencedEvents( BaseInstrument* instrument, int bufferPosition, int bufferEnd )\n{\n if ( !instrument->hasEvents() )\n return;\n\n AudioChannel* channel = instrument->audioChannel;\n std::vector<BaseAudioEvent*>* audioEvents = instrument->getEvents();\n\n \/\/ removal queue\n std::vector<BaseAudioEvent*> removes;\n\n \/\/ channel has an internal loop (e.g. drum machine) ? recalculate requested\n \/\/ buffer position by subtracting all measures above the first\n \n if ( channel->maxBufferPosition > 0 )\n {\n int samplesPerBar = AudioEngine::samples_per_bar;\n\n while ( bufferPosition >= channel->maxBufferPosition )\n {\n bufferPosition -= samplesPerBar;\n bufferEnd -= samplesPerBar;\n }\n }\n\n int i = 0;\n for ( ; i < audioEvents->size(); i++ )\n {\n BaseAudioEvent* audioEvent = audioEvents->at( i );\n\n if ( audioEvent->isEnabled() )\n {\n int eventStart = audioEvent->getEventStart();\n int eventEnd = audioEvent->getEventEnd();\n\n if (( eventStart >= bufferPosition && eventStart <= bufferEnd ) ||\n ( eventStart < bufferPosition && eventEnd >= bufferPosition ))\n {\n if ( !audioEvent->isDeletable())\n channel->addEvent( audioEvent );\n else\n removes.push_back( audioEvent );\n }\n }\n }\n \/\/ removal queue filled ? process it so we can safely\n \/\/ remove \"deleted\" AudioEvents without errors occurring\n if ( removes.size() > 0 )\n {\n for ( i = 0; i < removes.size(); i++ )\n {\n BaseAudioEvent* audioEvent = removes[ i ];\n instrument->removeEvent( audioEvent, false );\n }\n }\n}\n\nvoid Sequencer::collectLiveEvents( BaseInstrument* instrument )\n{\n AudioChannel* channel = instrument->audioChannel;\n std::vector<BaseAudioEvent*>* liveEvents = instrument->getLiveEvents();\n\n \/\/ removal queue\n std::vector<BaseAudioEvent*> removes;\n\n for ( int i = 0; i < liveEvents->size(); i++ )\n {\n BaseAudioEvent* audioEvent = liveEvents->at( i );\n\n if ( !audioEvent->isDeletable())\n channel->addLiveEvent( audioEvent );\n else\n removes.push_back( audioEvent );\n }\n \/\/ removal queue filled ? process it so we can safely\n \/\/ remove \"deleted\" AudioEvents without errors occurring\n if ( removes.size() > 0 )\n {\n for ( int i = 0; i < removes.size(); i++ )\n {\n BaseAudioEvent* audioEvent = removes[ i ];\n instrument->removeEvent( audioEvent, true );\n }\n }\n}\n\n\/**\n * used by the cacheAudioEventsForMeasure-method, this collects\n * all AudioEvents in the requested measure for entry into the BulkCacher\n *\n * @param bufferPosition {int} the desired measures buffers start pointer\n * @param bufferEnd {int} the desired measures buffers end pointer\n *\n * @return {std::vector<BaseCacheableAudioEvent*>}\n *\/\nstd::vector<BaseCacheableAudioEvent*>* Sequencer::collectCacheableSequencerEvents( int bufferPosition, int bufferEnd )\n{\n std::vector<BaseCacheableAudioEvent*>* events = new std::vector<BaseCacheableAudioEvent*>();\n\n for ( int i = 0, l = ( int ) instruments.size(); i < l; ++i )\n {\n std::vector<BaseAudioEvent*>* audioEvents = instruments.at( i )->getEvents();\n for ( int j = 0; j < audioEvents->size(); j++ )\n {\n BaseAudioEvent* audioEvent = audioEvents->at( j );\n\n \/\/ if event is an instance of BaseCacheableAudioEvent add it to the list\n if ( dynamic_cast<BaseCacheableAudioEvent*>( audioEvent ) != nullptr )\n {\n int eventStart = audioEvent->getEventStart();\n int eventEnd = audioEvent->getEventEnd();\n\n if (( eventStart >= bufferPosition && eventStart <= bufferEnd ) ||\n ( eventStart < bufferPosition && eventEnd >= bufferPosition ))\n {\n if ( !audioEvent->isDeletable())\n events->push_back(( BaseCacheableAudioEvent* ) audioEvent );\n }\n }\n }\n }\n return events;\n}\n\n} \/\/ E.O namespace MWEngine\n<|endoftext|>"} {"text":"<commit_before>\/*\n * smartBlockWorld.cpp\n *\n * Created on: 12 avril 2013\n * Author: ben\n *\/\n\n#include <iostream>\n#include <stdlib.h>\n#include <string>\n\n#include \"smartBlocksWorld.h\"\n#include \"smartBlocksBlock.h\"\n#include \"scheduler.h\"\n#include \"configExporter.h\"\n\nusing namespace std;\n\nnamespace SmartBlocks {\n\nSmartBlocksWorld::SmartBlocksWorld(const Cell3DPosition &gridSize, const Vector3D &gridScale,\n int argc, char *argv[]):World(argc, argv) {\n cout << \"\\033[1;31mSmartBlocksWorld constructor\\033[0m\" << endl;\n\n if (GlutContext::GUIisEnabled) {\n objBlock = new ObjLoader::ObjLoader(\"..\/..\/simulatorCore\/resources\/textures\/smartBlocksTextures\",\n \"smartBlockSimple.obj\");\n objBlockForPicking = new ObjLoader::ObjLoader(\"..\/..\/simulatorCore\/resources\/textures\/smartBlocksTextures\",\n \"smartBlockPicking.obj\");\n objRepere = new ObjLoader::ObjLoader(\"..\/..\/simulatorCore\/resources\/textures\/latticeTextures\",\n \"repere25.obj\");\n }\n\n lattice = new SLattice(gridSize, gridScale.hasZero() ? defaultBlockSize : gridScale);\n}\n\nSmartBlocksWorld::~SmartBlocksWorld() {\n cout << \"\\033[1;31mSmartBlocksWorld destructor\\033[0m\" << endl;\n}\n\nvoid SmartBlocksWorld::deleteWorld() {\n delete((SmartBlocksWorld*)world);\n world=NULL;\n}\n\nvoid SmartBlocksWorld::addBlock(bID blockId, BlockCodeBuilder bcb,\n const Cell3DPosition &pos, const Color &col,\n short orientation, bool master) {\n\tif (blockId > maxBlockId)\n\t\tmaxBlockId = blockId;\n\telse if (blockId == 0)\n\t\tblockId = incrementBlockId();\n\n SmartBlocksBlock *smartBlock = new SmartBlocksBlock(blockId, bcb);\n buildingBlocksMap.insert(std::pair<int,BaseSimulator::BuildingBlock*>\n (smartBlock->blockId, (BaseSimulator::BuildingBlock*)smartBlock) );\n getScheduler()->schedule(new CodeStartEvent(getScheduler()->now(), smartBlock));\n\n SmartBlocksGlBlock *glBlock = new SmartBlocksGlBlock(blockId);\n tabGlBlocks.push_back(glBlock);\n smartBlock->setGlBlock(glBlock);\n smartBlock->setPosition(pos);\n smartBlock->setColor(col);\n\n if (lattice->isInGrid(pos)) {\n lattice->insert(smartBlock, pos);\n } else {\n cerr << \"ERROR : BLOCK #\" << blockId << \" out of the grid !!!!!\" << endl;\n exit(1);\n }\n}\n\nvoid SmartBlocksWorld::linkBlock(const Cell3DPosition &pos) {\n SmartBlocksBlock *ptrNeighbor;\n SmartBlocksBlock *ptrBlock = (SmartBlocksBlock*)lattice->getBlock(pos);\n vector<Cell3DPosition> nRelCells = lattice->getRelativeConnectivity(pos);\n Cell3DPosition nPos;\n\n \/\/ Check neighbors for each interface\n for (int i = 0; i < 4; i++) {\n nPos = pos + nRelCells[i];\n ptrNeighbor = (SmartBlocksBlock*)lattice->getBlock(nPos);\n if (ptrNeighbor) {\n (ptrBlock)->getInterface(SLattice::Direction(i))->\n connect(ptrNeighbor->getInterface(SLattice::Direction(\n lattice->getOppositeDirection(i))));\n\n OUTPUT << \"connection #\" << (ptrBlock)->blockId <<\n \" to #\" << ptrNeighbor->blockId << endl;\n } else {\n (ptrBlock)->getInterface(SLattice::Direction(i))->connect(NULL);\n }\n }\n}\n\nvoid SmartBlocksWorld::glDraw() {\n static const GLfloat white[]={1.0,1.0,1.0,1.0},\n gray[]={0.2,0.2,0.2,1.0};\n\n glMaterialfv(GL_FRONT,GL_AMBIENT,gray);\n glMaterialfv(GL_FRONT,GL_DIFFUSE,white);\n glMaterialfv(GL_FRONT,GL_SPECULAR,gray);\n glMaterialf(GL_FRONT,GL_SHININESS,40.0);\n glPushMatrix();\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D,idTextureFloor);\n glNormal3f(0,0,1.0f);\n glScalef(lattice->gridSize[0]*lattice->gridScale[0],\n lattice->gridSize[1]*lattice->gridScale[1],1.0f);\n glBegin(GL_QUADS);\n glTexCoord2f(0,0);\n glVertex3f(0.0f,0.0f,0.0f);\n glTexCoord2f(lattice->gridSize[0],0);\n glVertex3f(1.0f,0.0f,0.0f);\n glTexCoord2f(lattice->gridSize[0],lattice->gridSize[1]);\n glVertex3f(1.0,1.0,0.0f);\n glTexCoord2f(0,lattice->gridSize[1]);\n glVertex3f(0.0,1.0,0.0f);\n glEnd();\n glPopMatrix();\n \/\/ draw the axes\n objRepere->glDraw();\n\n glPushMatrix();\n \/*glTranslatef(-lattice->gridSize[0]\/2.0f*lattice->gridScale[0],\n -lattice->gridSize[1]\/2.0f*lattice->gridScale[1],0); *\/\n glDisable(GL_TEXTURE_2D);\n vector <GlBlock*>::iterator ic=tabGlBlocks.begin();\n lock();\n while (ic!=tabGlBlocks.end()) {\n ((SmartBlocksGlBlock*)(*ic))->glDraw(objBlock);\n ic++;\n }\n unlock();\n\n \/*\/\/ drawing the mobiles\n Physics::glDraw();\n *\/\n glPopMatrix();\n}\n\nvoid SmartBlocksWorld::glDrawIdByMaterial() {\n glPushMatrix();\n glDisable(GL_TEXTURE_2D);\n\n vector <GlBlock*>::iterator ic=tabGlBlocks.begin();\n int n=1;\n lock();\n while (ic!=tabGlBlocks.end()) {\n ((SmartBlocksGlBlock*)(*ic))->glDrawIdByMaterial(objBlockForPicking, n);\n ic++;\n }\n unlock();\n glPopMatrix();\n}\n\nvoid SmartBlocksWorld::glDrawId() {\n glPushMatrix();\n glDisable(GL_TEXTURE_2D);\n\n vector <GlBlock*>::iterator ic=tabGlBlocks.begin();\n int n=1;\n lock();\n while (ic!=tabGlBlocks.end()) {\n ((SmartBlocksGlBlock*)(*ic))->glDrawId(objBlock,n);\n ic++;\n }\n unlock();\n glPopMatrix();\n}\n\nvoid SmartBlocksWorld::loadTextures(const string &str) {\n if (GlutContext::GUIisEnabled) {\n \/\/string path = str+\"\/circuit.tga\";\n string path = str+\"\/bois.tga\";\n int lx,ly;\n idTextureFloor = GlutWindow::loadTexture(path.c_str(),lx,ly);\n\n path=str+\"\/..\/smartBlocksTextures\/digits.tga\";\n idTextureDigits = GlutWindow::loadTexture(path.c_str(),lx,ly);\n }\n}\n\nvoid SmartBlocksWorld::setSelectedFace(int n) {\n numSelectedGlBlock = n \/ 5;\n string name = objBlockForPicking->getObjMtlName(n % 5);\n\n if (name == \"Material__72\") numSelectedFace = SLattice::South;\n else if (name == \"Material__66\") numSelectedFace = SLattice::East;\n else if (name == \"Material__71\") numSelectedFace = SLattice::West;\n else if (name == \"Material__68\") numSelectedFace = SLattice::North;\n else {\n\t\tcerr << \"warning: Unrecognized picking face\" << endl;\n\t\tnumSelectedFace = 4;\t\/\/ UNDEFINED\n }\n\n cerr << \"SET \" << name << \" = \" << numSelectedFace << \" = \"\n << lattice->getDirectionString(numSelectedFace) << endl;\n}\n\nvoid SmartBlocksWorld::exportConfiguration() {\n\tSmartBlocksConfigExporter exporter = SmartBlocksConfigExporter(this);\n\texporter.exportConfiguration();\n}\n\n\n} \/\/ SmartBlocks namespace\n<commit_msg>Suppress unnecessary trace when picking, and fix potential invalid read<commit_after>\/*\n * smartBlockWorld.cpp\n *\n * Created on: 12 avril 2013\n * Author: ben\n *\/\n\n#include <iostream>\n#include <stdlib.h>\n#include <string>\n\n#include \"smartBlocksWorld.h\"\n#include \"smartBlocksBlock.h\"\n#include \"scheduler.h\"\n#include \"configExporter.h\"\n\nusing namespace std;\n\nnamespace SmartBlocks {\n\nSmartBlocksWorld::SmartBlocksWorld(const Cell3DPosition &gridSize, const Vector3D &gridScale,\n int argc, char *argv[]):World(argc, argv) {\n cout << \"\\033[1;31mSmartBlocksWorld constructor\\033[0m\" << endl;\n\n if (GlutContext::GUIisEnabled) {\n objBlock = new ObjLoader::ObjLoader(\"..\/..\/simulatorCore\/resources\/textures\/smartBlocksTextures\",\n \"smartBlockSimple.obj\");\n objBlockForPicking = new ObjLoader::ObjLoader(\"..\/..\/simulatorCore\/resources\/textures\/smartBlocksTextures\",\n \"smartBlockPicking.obj\");\n objRepere = new ObjLoader::ObjLoader(\"..\/..\/simulatorCore\/resources\/textures\/latticeTextures\",\n \"repere25.obj\");\n }\n\n lattice = new SLattice(gridSize, gridScale.hasZero() ? defaultBlockSize : gridScale);\n}\n\nSmartBlocksWorld::~SmartBlocksWorld() {\n cout << \"\\033[1;31mSmartBlocksWorld destructor\\033[0m\" << endl;\n}\n\nvoid SmartBlocksWorld::deleteWorld() {\n delete((SmartBlocksWorld*)world);\n world=NULL;\n}\n\nvoid SmartBlocksWorld::addBlock(bID blockId, BlockCodeBuilder bcb,\n const Cell3DPosition &pos, const Color &col,\n short orientation, bool master) {\n\tif (blockId > maxBlockId)\n\t\tmaxBlockId = blockId;\n\telse if (blockId == 0)\n\t\tblockId = incrementBlockId();\n\n SmartBlocksBlock *smartBlock = new SmartBlocksBlock(blockId, bcb);\n buildingBlocksMap.insert(std::pair<int,BaseSimulator::BuildingBlock*>\n (smartBlock->blockId, (BaseSimulator::BuildingBlock*)smartBlock) );\n getScheduler()->schedule(new CodeStartEvent(getScheduler()->now(), smartBlock));\n\n SmartBlocksGlBlock *glBlock = new SmartBlocksGlBlock(blockId);\n tabGlBlocks.push_back(glBlock);\n smartBlock->setGlBlock(glBlock);\n smartBlock->setPosition(pos);\n smartBlock->setColor(col);\n\n if (lattice->isInGrid(pos)) {\n lattice->insert(smartBlock, pos);\n } else {\n cerr << \"ERROR : BLOCK #\" << blockId << \" out of the grid !!!!!\" << endl;\n exit(1);\n }\n}\n\nvoid SmartBlocksWorld::linkBlock(const Cell3DPosition &pos) {\n SmartBlocksBlock *ptrNeighbor;\n SmartBlocksBlock *ptrBlock = (SmartBlocksBlock*)lattice->getBlock(pos);\n vector<Cell3DPosition> nRelCells = lattice->getRelativeConnectivity(pos);\n Cell3DPosition nPos;\n\n \/\/ Check neighbors for each interface\n for (int i = 0; i < 4; i++) {\n nPos = pos + nRelCells[i];\n ptrNeighbor = (SmartBlocksBlock*)lattice->getBlock(nPos);\n if (ptrNeighbor) {\n (ptrBlock)->getInterface(SLattice::Direction(i))->\n connect(ptrNeighbor->getInterface(SLattice::Direction(\n lattice->getOppositeDirection(i))));\n\n OUTPUT << \"connection #\" << (ptrBlock)->blockId <<\n \" to #\" << ptrNeighbor->blockId << endl;\n } else {\n (ptrBlock)->getInterface(SLattice::Direction(i))->connect(NULL);\n }\n }\n}\n\nvoid SmartBlocksWorld::glDraw() {\n static const GLfloat white[]={1.0,1.0,1.0,1.0},\n gray[]={0.2,0.2,0.2,1.0};\n\n glMaterialfv(GL_FRONT,GL_AMBIENT,gray);\n glMaterialfv(GL_FRONT,GL_DIFFUSE,white);\n glMaterialfv(GL_FRONT,GL_SPECULAR,gray);\n glMaterialf(GL_FRONT,GL_SHININESS,40.0);\n glPushMatrix();\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D,idTextureFloor);\n glNormal3f(0,0,1.0f);\n glScalef(lattice->gridSize[0]*lattice->gridScale[0],\n lattice->gridSize[1]*lattice->gridScale[1],1.0f);\n glBegin(GL_QUADS);\n glTexCoord2f(0,0);\n glVertex3f(0.0f,0.0f,0.0f);\n glTexCoord2f(lattice->gridSize[0],0);\n glVertex3f(1.0f,0.0f,0.0f);\n glTexCoord2f(lattice->gridSize[0],lattice->gridSize[1]);\n glVertex3f(1.0,1.0,0.0f);\n glTexCoord2f(0,lattice->gridSize[1]);\n glVertex3f(0.0,1.0,0.0f);\n glEnd();\n glPopMatrix();\n \/\/ draw the axes\n objRepere->glDraw();\n\n glPushMatrix();\n \/*glTranslatef(-lattice->gridSize[0]\/2.0f*lattice->gridScale[0],\n -lattice->gridSize[1]\/2.0f*lattice->gridScale[1],0); *\/\n glDisable(GL_TEXTURE_2D);\n vector <GlBlock*>::iterator ic=tabGlBlocks.begin();\n lock();\n while (ic!=tabGlBlocks.end()) {\n ((SmartBlocksGlBlock*)(*ic))->glDraw(objBlock);\n ic++;\n }\n unlock();\n\n \/*\/\/ drawing the mobiles\n Physics::glDraw();\n *\/\n glPopMatrix();\n}\n\nvoid SmartBlocksWorld::glDrawIdByMaterial() {\n glPushMatrix();\n glDisable(GL_TEXTURE_2D);\n\n vector <GlBlock*>::iterator ic=tabGlBlocks.begin();\n int n=1;\n lock();\n while (ic!=tabGlBlocks.end()) {\n ((SmartBlocksGlBlock*)(*ic))->glDrawIdByMaterial(objBlockForPicking, n);\n ic++;\n }\n unlock();\n glPopMatrix();\n}\n\nvoid SmartBlocksWorld::glDrawId() {\n glPushMatrix();\n glDisable(GL_TEXTURE_2D);\n\n vector <GlBlock*>::iterator ic=tabGlBlocks.begin();\n int n=1;\n lock();\n while (ic!=tabGlBlocks.end()) {\n ((SmartBlocksGlBlock*)(*ic))->glDrawId(objBlock,n);\n ic++;\n }\n unlock();\n glPopMatrix();\n}\n\nvoid SmartBlocksWorld::loadTextures(const string &str) {\n if (GlutContext::GUIisEnabled) {\n \/\/string path = str+\"\/circuit.tga\";\n string path = str+\"\/bois.tga\";\n int lx,ly;\n idTextureFloor = GlutWindow::loadTexture(path.c_str(),lx,ly);\n\n path=str+\"\/..\/smartBlocksTextures\/digits.tga\";\n idTextureDigits = GlutWindow::loadTexture(path.c_str(),lx,ly);\n }\n}\n\nvoid SmartBlocksWorld::setSelectedFace(int n) {\n numSelectedGlBlock = n \/ 5;\n string name = objBlockForPicking->getObjMtlName(n % 5);\n\n if (name == \"Material__72\") numSelectedFace = SLattice::South;\n else if (name == \"Material__66\") numSelectedFace = SLattice::East;\n else if (name == \"Material__71\") numSelectedFace = SLattice::West;\n else if (name == \"Material__68\") numSelectedFace = SLattice::North;\n else {\n\t\tnumSelectedFace = 4;\t\/\/ Top\n return;\n }\n\n \/\/ cerr << \"SET \" << name << \" = \" << numSelectedFace << \" = \"\n \/\/ << lattice->getDirectionString(numSelectedFace) << endl;\n}\n\nvoid SmartBlocksWorld::exportConfiguration() {\n\tSmartBlocksConfigExporter exporter = SmartBlocksConfigExporter(this);\n\texporter.exportConfiguration();\n}\n\n\n} \/\/ SmartBlocks namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 The Hivemind Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\nextern \"C\" {\n#include \"linalg\/src\/tc_mat.h\"\n}\n#include \"resolvevotedialog.h\"\n#include \"resolvevoteinputtablemodel.h\"\n#include <iostream>\n\nResolveVoteInputTableModel::ResolveVoteInputTableModel()\n : QAbstractTableModel(0),\n resolveVoteDialog(0),\n voteptr(0)\n{\n\n}\n\nResolveVoteInputTableModel::~ResolveVoteInputTableModel()\n{\n\n}\n\nint ResolveVoteInputTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return 3 + ((voteptr && *voteptr)? (*voteptr)->nr: 0);\n}\n\nint ResolveVoteInputTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return 1 + ((voteptr && *voteptr)? (*voteptr)->nc: 0);\n}\n\nQVariant ResolveVoteInputTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n if (role == Qt::DisplayRole)\n {\n if (!voteptr || !*voteptr)\n return QVariant();\n\n uint32_t row = index.row();\n uint32_t col = index.column();\n if ((row < 3+(*voteptr)->nr)\n && (col < 1+(*voteptr)->nc))\n {\n\n double value = 0.0;\n\n if (col == 0) { \/* Starting Reputations *\/\n if (row >= 3)\n value = (*voteptr)->rvecs[TC_VOTE_OLD_REP]->a[row-3][0];\n else\n return QVariant();\n }\n else\n if (row == 0) \/* Binary\/Scalar *\/\n value = (*voteptr)->cvecs[TC_VOTE_IS_BINARY]->a[0][col-1];\n else\n if (row == 1) \/* Minimum *\/\n value = 0.0;\n else\n if (row == 2) \/* Maximum *\/\n value = 1.0;\n else\n value = (*voteptr)->M->a[row-3][col-1];\n\n if (value != (*voteptr)->NA) {\n char tmp[32];\n snprintf(tmp, sizeof(tmp), \"%.8f\", value);\n return QVariant(QString(tmp));\n }\n return QVariant(QString(\"NA\"));\n }\n }\n else\n if (role == Qt::TextAlignmentRole)\n return (int)(Qt::AlignRight|Qt::AlignVCenter);\n\n return QVariant();\n}\n\nQVariant ResolveVoteInputTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole)\n {\n char tmp[32];\n if (section == 0)\n snprintf(tmp, sizeof(tmp), \"Old Rep\");\n else\n snprintf(tmp, sizeof(tmp), \"Decision %u\", section+1);\n return QVariant(QString(tmp));\n }\n else\n if (role == Qt::TextAlignmentRole)\n return (int)(Qt::AlignLeft|Qt::AlignVCenter);\n else\n if (role == Qt::ToolTipRole)\n {\n }\n }\n\n if(orientation == Qt::Vertical)\n {\n if (role == Qt::DisplayRole) {\n if (section == 0) return QVariant(tr(\"Binary\/Scalar\"));\n if (section == 1) return QVariant(tr(\"Minumum\"));\n if (section == 2) return QVariant(tr(\"Maximum\"));\n char tmp[32];\n snprintf(tmp, sizeof(tmp), \"Voter %u\", section - 2);\n return QVariant(QString(tmp));\n }\n else\n if (role == Qt::TextAlignmentRole)\n return (int)(Qt::AlignLeft|Qt::AlignVCenter);\n else\n if (role == Qt::ToolTipRole)\n {\n }\n }\n\n return QVariant();\n}\n\nQt::ItemFlags ResolveVoteInputTableModel::flags(const QModelIndex &index) const\n{\n if (!index.isValid())\n return Qt::ItemIsEnabled;\n return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;\n}\n\nvoid ResolveVoteInputTableModel::onDataChange()\n{\n uint32_t nr = 3 + ((voteptr && *voteptr)? (*voteptr)->nr: 0);\n uint32_t nc = (voteptr && *voteptr)? (*voteptr)->nc: 0;\n if (nc) {\n QModelIndex topLeft = index(0, 0, QModelIndex());\n QModelIndex bottomRight = index(nr-1, nc-1, QModelIndex());\n emit dataChanged(topLeft, bottomRight);\n }\n}\n\nbool ResolveVoteInputTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if (role != Qt::EditRole)\n return false;\n\n if (!index.isValid())\n return false;\n\n const char *str;\n\n if(value.isNull()) {\n std::cout << \"FALSE\\n\\n\";\n return false;\n } else {\n str = value.toString().toStdString().c_str();\n }\n\n bool isNA = (strstr(str, \"NA\"))? true: false;\n double dvalue = atof(str);\n\n int row = index.row();\n int col = index.column();\n if ((row < 3+(int)(*voteptr)->nr)\n && (col < 1 + (int)(*voteptr)->nc))\n {\n if (col == 0) {\n if (row >= 3)\n (*voteptr)->rvecs[TC_VOTE_OLD_REP]->a[row-3][0] = dvalue;\n }\n else\n if (row == 0)\n (*voteptr)->cvecs[TC_VOTE_IS_BINARY]->a[0][col-1] = (dvalue > 0.5)? 1.0: 0.0;\n else\n if (row == 1)\n ;\n else\n if (row == 2)\n ;\n else\n (*voteptr)->M->a[row-3][col-1] = (isNA)? (*voteptr)->NA: dvalue;\n\n emit dataChanged(index, index);\n\n if (resolveVoteDialog)\n resolveVoteDialog->onInputChange();\n }\n return false;\n}\n\n<commit_msg>Revert \"Fixed invalid read bug. Found while testing my code with valgrind to find my own bug\"<commit_after>\/\/ Copyright (c) 2015 The Hivemind Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\nextern \"C\" {\n#include \"linalg\/src\/tc_mat.h\"\n}\n#include \"resolvevotedialog.h\"\n#include \"resolvevoteinputtablemodel.h\"\n\n\nResolveVoteInputTableModel::ResolveVoteInputTableModel()\n : QAbstractTableModel(0),\n resolveVoteDialog(0),\n voteptr(0)\n{\n\n}\n\nResolveVoteInputTableModel::~ResolveVoteInputTableModel()\n{\n\n}\n\nint ResolveVoteInputTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return 3 + ((voteptr && *voteptr)? (*voteptr)->nr: 0);\n}\n\nint ResolveVoteInputTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return 1 + ((voteptr && *voteptr)? (*voteptr)->nc: 0);\n}\n\nQVariant ResolveVoteInputTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n if (role == Qt::DisplayRole)\n {\n if (!voteptr || !*voteptr)\n return QVariant();\n\n uint32_t row = index.row();\n uint32_t col = index.column();\n if ((row < 3+(*voteptr)->nr)\n && (col < 1+(*voteptr)->nc))\n {\n\n double value = 0.0;\n\n if (col == 0) { \/* Starting Reputations *\/\n if (row >= 3)\n value = (*voteptr)->rvecs[TC_VOTE_OLD_REP]->a[row-3][0];\n else\n return QVariant();\n }\n else\n if (row == 0) \/* Binary\/Scalar *\/\n value = (*voteptr)->cvecs[TC_VOTE_IS_BINARY]->a[0][col-1];\n else\n if (row == 1) \/* Minimum *\/\n value = 0.0;\n else\n if (row == 2) \/* Maximum *\/\n value = 1.0;\n else\n value = (*voteptr)->M->a[row-3][col-1];\n\n if (value != (*voteptr)->NA) {\n char tmp[32];\n snprintf(tmp, sizeof(tmp), \"%.8f\", value);\n return QVariant(QString(tmp));\n }\n return QVariant(QString(\"NA\"));\n }\n }\n else\n if (role == Qt::TextAlignmentRole)\n return (int)(Qt::AlignRight|Qt::AlignVCenter);\n\n return QVariant();\n}\n\nQVariant ResolveVoteInputTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole)\n {\n char tmp[32];\n if (section == 0)\n snprintf(tmp, sizeof(tmp), \"Old Rep\");\n else\n snprintf(tmp, sizeof(tmp), \"Decision %u\", section+1);\n return QVariant(QString(tmp));\n }\n else\n if (role == Qt::TextAlignmentRole)\n return (int)(Qt::AlignLeft|Qt::AlignVCenter);\n else\n if (role == Qt::ToolTipRole)\n {\n }\n }\n\n if(orientation == Qt::Vertical)\n {\n if (role == Qt::DisplayRole) {\n if (section == 0) return QVariant(tr(\"Binary\/Scalar\"));\n if (section == 1) return QVariant(tr(\"Minumum\"));\n if (section == 2) return QVariant(tr(\"Maximum\"));\n char tmp[32];\n snprintf(tmp, sizeof(tmp), \"Voter %u\", section - 2);\n return QVariant(QString(tmp));\n }\n else\n if (role == Qt::TextAlignmentRole)\n return (int)(Qt::AlignLeft|Qt::AlignVCenter);\n else\n if (role == Qt::ToolTipRole)\n {\n }\n }\n\n return QVariant();\n}\n\nQt::ItemFlags ResolveVoteInputTableModel::flags(const QModelIndex &index) const\n{\n if (!index.isValid())\n return Qt::ItemIsEnabled;\n return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;\n}\n\nvoid ResolveVoteInputTableModel::onDataChange()\n{\n uint32_t nr = 3 + ((voteptr && *voteptr)? (*voteptr)->nr: 0);\n uint32_t nc = (voteptr && *voteptr)? (*voteptr)->nc: 0;\n if (nc) {\n QModelIndex topLeft = index(0, 0, QModelIndex());\n QModelIndex bottomRight = index(nr-1, nc-1, QModelIndex());\n emit dataChanged(topLeft, bottomRight);\n }\n}\n\nbool ResolveVoteInputTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if (role != Qt::EditRole)\n return false;\n\n if (!index.isValid())\n return false;\n\n const char *str = value.toString().toStdString().c_str();\n if (!str)\n return false;\n\n bool isNA = (strstr(str, \"NA\"))? true: false;\n double dvalue = atof(str);\n\n int row = index.row();\n int col = index.column();\n if ((row < 3+(int)(*voteptr)->nr)\n && (col < 1 + (int)(*voteptr)->nc))\n {\n if (col == 0) {\n if (row >= 3)\n (*voteptr)->rvecs[TC_VOTE_OLD_REP]->a[row-3][0] = dvalue;\n }\n else\n if (row == 0)\n (*voteptr)->cvecs[TC_VOTE_IS_BINARY]->a[0][col-1] = (dvalue > 0.5)? 1.0: 0.0;\n else\n if (row == 1)\n ;\n else\n if (row == 2)\n ;\n else\n (*voteptr)->M->a[row-3][col-1] = (isNA)? (*voteptr)->NA: dvalue;\n\n emit dataChanged(index, index);\n\n if (resolveVoteDialog)\n resolveVoteDialog->onInputChange();\n }\n return false;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2016 Colin Girling\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#ifndef OCL_GUARD_TEST_TDIOTESTLOG_HPP\n#define OCL_GUARD_TEST_TDIOTESTLOG_HPP\n\n#include \"TestLog.hpp\"\n#include <iostream>\n\nnamespace ocl\n{\n\nclass StdioTestLog : public TestLog\n{\npublic:\n virtual void Write(TestString const& str)\n {\n std::cout << str.Ptr();\n }\n\n virtual void WriteEOL()\n {\n std::cout << std::endl;\n }\n};\n\n}\n\n#endif \/\/ OCL_GUARD_TEST_TDIOTESTLOG_HPP\n<commit_msg>Corrected #define guard for StdioTestLog class.<commit_after>\/*\nCopyright 2016 Colin Girling\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#ifndef OCL_GUARD_TEST_STDIOTESTLOG_HPP\n#define OCL_GUARD_TEST_STDIOTESTLOG_HPP\n\n#include \"TestLog.hpp\"\n#include <iostream>\n\nnamespace ocl\n{\n\nclass StdioTestLog : public TestLog\n{\npublic:\n virtual void Write(TestString const& str)\n {\n std::cout << str.Ptr();\n }\n\n virtual void WriteEOL()\n {\n std::cout << std::endl;\n }\n};\n\n}\n\n#endif \/\/ OCL_GUARD_TEST_STDIOTESTLOG_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"Overlap.h\"\n#include \"BaseVecVec.h\"\n#include \"AnyStringGraph.h\"\n#include \"util.h\"\n\nDEFINE_USAGE(\n\"Usage: map-contained-reads ORIG_READS_FILE ORIG_OVERLAPS_FILE\\n\"\n\" OLD_TO_NEW_INDICES_FILE GRAPH_FILE OUT_GRAPH_FILE\\n\"\n\"\\n\"\n\"Map contained reads back into a graph.\\n\"\n\"\\n\"\n\"Input:\\n\"\n\" READS_FILE: The set of reads from which the overlaps were found.\\n\"\n\" OVERLAPS_FILE: The set of overlaps, computed from the reads in\\n\"\n\" READS_FILE.\\n\"\n\" OLD_TO_NEW_INDICES_FILE: A map from the old read indices to the new\\n\"\n\" read indices.\\n\"\n\" GRAPH_FILE: The graph to map the contained reads into.\\n\"\n\"\\n\"\n\"Output:\\n\"\n\" OUT_GRAPH_FILE: The output graph into which the contained reads have.\\n\"\n\" been mapped.\\n\"\n);\n\nint main(int argc, char **argv)\n{\n\tUSAGE_IF(argc != 6);\n\tconst char * const orig_reads_file = argv[1];\n\tconst char * const orig_overlaps_file = argv[2];\n\tconst char * const old_to_new_indices_file = argv[3];\n\tconst char * const graph_file = argv[4];\n\tconst char * const out_graph_file = argv[5];\n\n\tinfo(\"Loading original reads from \\\"%s\\\"\", orig_reads_file);\n\tBaseVecVec orig_reads(orig_reads_file);\n\n\tinfo(\"Loading original overlaps from \\\"%s\\\"\", orig_overlaps_file);\n\tOverlapVecVec orig_overlaps(orig_overlaps_file);\n\n\tinfo(\"Loading map from old to new read indices from \\\"%s\\\"\", old_to_new_indices_file);\n\tstd::vector<size_t> old_to_new_indices;\n\t{\n\t\tstd::ifstream is(old_to_new_indices_file);\n\t\tboost::archive::binary_iarchive ar(is);\n\t\tar >> old_to_new_indices;\n\t}\n\n\tsize_t num_orig_reads = orig_reads.size();\n\n\tassert(old_to_new_indices.size() == num_orig_reads);\n\tassert(orig_overlaps.size() == num_orig_reads);\n\n\t\/\/ Count the number of contained reads.\n\tsize_t num_contained_reads = 0;\n\tfor (size_t i = 0; i < num_orig_reads; i++)\n\t\tif (old_to_new_indices[i] == ~size_t(0))\n\t\t\tnum_contained_reads++;\n\n\t\/\/ The number of uncontained reads is the number of original reads minus\n\t\/\/ the number of contained reads.\n\tsize_t num_uncontained_reads = num_orig_reads - num_contained_reads;\n\n\tinfo(\"%zu of %zu original reads were contained (%.2f%%)\",\n\t num_contained_reads, num_orig_reads,\n\t TO_PERCENT(num_contained_reads, num_orig_reads));\n\n\t\/\/ Use the old to new indices map to build the reverse map from the new\n\t\/\/ to old read indices. At the same time, construct a sequential\n\t\/\/ numbering of the contained reads, and build a map from the original\n\t\/\/ read indices to contained read indices and a reverse map from the\n\t\/\/ contained read indices to the original read indices.\n\tstd::vector<size_t> contained_to_old_indices(num_contained_reads, ~size_t(0));\n\tstd::vector<size_t> new_to_old_indices(num_uncontained_reads, ~size_t(0));\n\tstd::vector<size_t> old_to_contained_indices(num_orig_reads, ~size_t(0));\n\tsize_t j = 0;\n\tfor (size_t i = 0; i < orig_reads.size(); i++) {\n\t\tif (old_to_new_indices[i] == ~size_t(0)) {\n\t\t\t\/\/ The read exists in the original reads but not in the\n\t\t\t\/\/ new reads, so it is a contained read.\n\t\t\told_to_contained_indices[i] = j;\n\t\t\tcontained_to_old_indices[j++] = i;\n\t\t} else {\n\t\t\t\/\/ The read exists in both the original and new reads,\n\t\t\t\/\/ so it is not a contained read. It may have been\n\t\t\t\/\/ renumbered.\n\t\t\tassert(old_to_new_indices[i] < num_uncontained_reads);\n\t\t\tassert(new_to_old_indices[old_to_new_indices[i]] == ~size_t(0));\n\t\t\tnew_to_old_indices[old_to_new_indices[i]] = i;\n\t\t}\n\t}\n\tassert(j == num_contained_reads);\n\n\t\/\/ Find the shortest overhanging overlap for each contained read\n\tinfo(\"Finding the shortest overhanging overlap for each contained read\");\n\n\tstd::vector<const Overlap *>\n\t\tshortest_overhang_overlaps(num_contained_reads, NULL);\n\n\tstd::vector<Overlap::read_pos_t>\n\t\tshortest_overhang_lens(num_contained_reads,\n\t\t\t\t std::numeric_limits<Overlap::read_pos_t>::max());\n\n\tforeach (const OverlapVecVec::OverlapSet & overlap_set, orig_overlaps) {\n\t\tforeach(const Overlap & o, overlap_set) {\n\t\t\tOverlap::read_idx_t f_idx;\n\t\t\tOverlap::read_pos_t f_beg;\n\t\t\tOverlap::read_pos_t f_end;\n\t\t\tOverlap::read_idx_t g_idx;\n\t\t\tOverlap::read_pos_t g_beg;\n\t\t\tOverlap::read_pos_t g_end;\n\t\t\tbool rc;\n\n\t\t\tOverlap::read_idx_t uncontained_read_orig_idx;\n\t\t\tOverlap::read_pos_t uncontained_read_overlap_beg;\n\t\t\tOverlap::read_pos_t uncontained_read_overlap_end;\n\n\t\t\tassert_overlap_valid(o, orig_reads, 1, 0);\n\n\t\t\to.get(f_idx, f_beg, f_end, g_idx, g_beg, g_end, rc);\n\t\t\tconst BaseVec & f = orig_reads[f_idx];\n\t\t\tconst BaseVec & g = orig_reads[g_idx];\n\t\t\tconst BaseVec * uncontained_read;\n\n\t\t\tassert(f_idx < num_orig_reads);\n\t\t\tassert(g_idx < num_orig_reads);\n\n\t\t\tsize_t contained_read_orig_idx = ~size_t(0);\n\t\t\tif (f_beg == 0 && f_end == f.size() - 1) {\n\t\t\t\t\/\/ Read f is contained\n\t\t\t\t\/\/ ... but only count this overlap if g is NOT\n\t\t\t\t\/\/ contained\n\t\t\t\tif (old_to_new_indices[g_idx] != ~size_t(0)) {\n\t\t\t\t\tcontained_read_orig_idx = f_idx;\n\t\t\t\t\tuncontained_read = &g;\n\t\t\t\t\tuncontained_read_orig_idx = g_idx;\n\t\t\t\t\tuncontained_read_overlap_beg = g_beg;\n\t\t\t\t\tuncontained_read_overlap_end = g_end;\n\t\t\t\t}\n\t\t\t} else if (g_beg == 0 && g_end == g.size() - 1) {\n\t\t\t\t\/\/ Read g is contained\n\t\t\t\t\/\/ ... but only count this overlap is f is NOT\n\t\t\t\t\/\/ contained\n\t\t\t\tif (old_to_new_indices[f_idx] != ~size_t(0)) {\n\t\t\t\t\tcontained_read_orig_idx = g_idx;\n\t\t\t\t\tuncontained_read = &f;\n\t\t\t\t\tuncontained_read_orig_idx = f_idx;\n\t\t\t\t\tuncontained_read_overlap_beg = f_beg;\n\t\t\t\t\tuncontained_read_overlap_end = f_end;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (contained_read_orig_idx != ~size_t(0)) {\n\t\t\t\tassert(old_to_new_indices[contained_read_orig_idx] ==\n\t\t\t\t ~size_t(0));\n\t\t\t\tassert(old_to_contained_indices[contained_read_orig_idx] !=\n\t\t\t\t ~size_t(0));\n\t\t\t\t\/\/ This is a containing overlap, and the read\n\t\t\t\t\/\/ with original index @contained_read_orig_idx\n\t\t\t\t\/\/ is contained. Compute the overhang length.\n\t\t\t\tOverlap::read_pos_t overhang_len;\n\t\t\t\tif (rc) {\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ ---------->\n\t\t\t\t\t\/\/ <------------------------\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ |overhang|\n\t\t\t\t\toverhang_len = uncontained_read_overlap_beg;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ ---------->\n\t\t\t\t\t\/\/ ------------------------>\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ |overhang|\n\t\t\t\t\tassert(uncontained_read->length() >=\n\t\t\t\t\t uncontained_read_overlap_end + 1);\n\t\t\t\t\toverhang_len = uncontained_read->length() -\n\t\t\t\t\t\t (uncontained_read_overlap_end + 1);\n\t\t\t\t}\n\n\t\t\t\t\/\/ Index of this contained read in the\n\t\t\t\t\/\/ sequential numbering of the contained reads\n\t\t\t\tsize_t contained_idx =\n\t\t\t\t\told_to_contained_indices[contained_read_orig_idx];\n\n\t\t\t\t\/\/ Update the shortest overhang if this overhang\n\t\t\t\t\/\/ is shorter than the previous shortest one.\n\t\t\t\tif (overhang_len < shortest_overhang_lens[contained_idx]) {\n\t\t\t\t\tshortest_overhang_overlaps[contained_idx] = &o;\n\t\t\t\t\tshortest_overhang_lens[contained_idx] = overhang_len;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tinfo(\"Reading string graph from \\\"%s\\\"\", graph_file);\n\tAnyStringGraph graph(graph_file);\n\n\tinfo(\"Mapping %zu contained reads into the string graph\", num_contained_reads);\n\n\t\/\/ Map the contained reads into the graph, given the overlap to use to\n\t\/\/ map each contained read.\n\tfor (size_t i = 0; i < num_contained_reads; i++) {\n\n\t\t\/\/ Original index of this contained read\n\t\tsize_t contained_read_orig_idx = contained_to_old_indices[i];\n\n\t\t\/\/ The overlap in which the overhang from the end of this\n\t\t\/\/ contained read to its containing read is the shortest\n\t\tconst Overlap *o = shortest_overhang_overlaps[i];\n\n\t\t\/\/ Original read index must be valid, the read must be\n\t\t\/\/ contained, and it must have at least 1 overlap with an\n\t\t\/\/ uncontained read.\n\t\tassert(contained_read_orig_idx < num_orig_reads);\n\t\tassert(old_to_new_indices[contained_read_orig_idx] == ~size_t(0));\n\t\tassert(o != NULL);\n\n\t\tOverlap::read_idx_t f_idx, g_idx;\n\t\tOverlap::read_idx_t uncontained_read_dir;\n\t\tOverlap::read_idx_t uncontained_read_new_idx;\n\n\t\to->get_indices(f_idx, g_idx);\n\n\t\tif (f_idx == contained_read_orig_idx) {\n\t\t\tuncontained_read_new_idx = old_to_new_indices[g_idx];\n\t\t} else {\n\t\t\tassert(g_idx == contained_read_orig_idx);\n\t\t\tuncontained_read_new_idx = old_to_new_indices[f_idx];\n\t\t}\n\n\t\tassert(uncontained_read_new_idx < num_uncontained_reads);\n\n\t\tuncontained_read_dir = (o->is_rc() ? 1 : 0);\n\n\t\tgraph.map_contained_read(uncontained_read_new_idx,\n\t\t\t\t\t uncontained_read_dir,\n\t\t\t\t\t shortest_overhang_lens[i]);\n\t}\n\n\tinfo(\"Writing string graph to \\\"%s\\\"\", out_graph_file);\n\tgraph.write(out_graph_file);\n\treturn 0;\n}\n<commit_msg>Map underhangs as well as overhangs<commit_after>#include \"Overlap.h\"\n#include \"BaseVecVec.h\"\n#include \"AnyStringGraph.h\"\n#include \"util.h\"\n\nDEFINE_USAGE(\n\"Usage: map-contained-reads ORIG_READS_FILE ORIG_OVERLAPS_FILE\\n\"\n\" OLD_TO_NEW_INDICES_FILE GRAPH_FILE OUT_GRAPH_FILE\\n\"\n\"\\n\"\n\"Map contained reads back into a graph.\\n\"\n\"\\n\"\n\"Input:\\n\"\n\" READS_FILE: The set of reads from which the overlaps were found.\\n\"\n\" OVERLAPS_FILE: The set of overlaps, computed from the reads in\\n\"\n\" READS_FILE.\\n\"\n\" OLD_TO_NEW_INDICES_FILE: A map from the old read indices to the new\\n\"\n\" read indices.\\n\"\n\" GRAPH_FILE: The graph to map the contained reads into.\\n\"\n\"\\n\"\n\"Output:\\n\"\n\" OUT_GRAPH_FILE: The output graph into which the contained reads have.\\n\"\n\" been mapped.\\n\"\n);\n\nint main(int argc, char **argv)\n{\n\tUSAGE_IF(argc != 6);\n\tconst char * const orig_reads_file = argv[1];\n\tconst char * const orig_overlaps_file = argv[2];\n\tconst char * const old_to_new_indices_file = argv[3];\n\tconst char * const graph_file = argv[4];\n\tconst char * const out_graph_file = argv[5];\n\n\tinfo(\"Loading original reads from \\\"%s\\\"\", orig_reads_file);\n\tBaseVecVec orig_reads(orig_reads_file);\n\n\tinfo(\"Loading original overlaps from \\\"%s\\\"\", orig_overlaps_file);\n\tOverlapVecVec orig_overlaps(orig_overlaps_file);\n\n\tinfo(\"Loading map from old to new read indices from \\\"%s\\\"\", old_to_new_indices_file);\n\tstd::vector<size_t> old_to_new_indices;\n\t{\n\t\tstd::ifstream is(old_to_new_indices_file);\n\t\tboost::archive::binary_iarchive ar(is);\n\t\tar >> old_to_new_indices;\n\t}\n\n\tsize_t num_orig_reads = orig_reads.size();\n\n\tassert(old_to_new_indices.size() == num_orig_reads);\n\tassert(orig_overlaps.size() == num_orig_reads);\n\n\t\/\/ Count the number of contained reads.\n\tsize_t num_contained_reads = 0;\n\tfor (size_t i = 0; i < num_orig_reads; i++)\n\t\tif (old_to_new_indices[i] == ~size_t(0))\n\t\t\tnum_contained_reads++;\n\n\t\/\/ The number of uncontained reads is the number of original reads minus\n\t\/\/ the number of contained reads.\n\tsize_t num_uncontained_reads = num_orig_reads - num_contained_reads;\n\n\tinfo(\"%zu of %zu original reads were contained (%.2f%%)\",\n\t num_contained_reads, num_orig_reads,\n\t TO_PERCENT(num_contained_reads, num_orig_reads));\n\n\t\/\/ Use the old to new indices map to build the reverse map from the new\n\t\/\/ to old read indices. At the same time, construct a sequential\n\t\/\/ numbering of the contained reads, and build a map from the original\n\t\/\/ read indices to contained read indices and a reverse map from the\n\t\/\/ contained read indices to the original read indices.\n\tstd::vector<size_t> contained_to_old_indices(num_contained_reads, ~size_t(0));\n\tstd::vector<size_t> new_to_old_indices(num_uncontained_reads, ~size_t(0));\n\tstd::vector<size_t> old_to_contained_indices(num_orig_reads, ~size_t(0));\n\tsize_t j = 0;\n\tfor (size_t i = 0; i < orig_reads.size(); i++) {\n\t\tif (old_to_new_indices[i] == ~size_t(0)) {\n\t\t\t\/\/ The read exists in the original reads but not in the\n\t\t\t\/\/ new reads, so it is a contained read.\n\t\t\told_to_contained_indices[i] = j;\n\t\t\tcontained_to_old_indices[j++] = i;\n\t\t} else {\n\t\t\t\/\/ The read exists in both the original and new reads,\n\t\t\t\/\/ so it is not a contained read. It may have been\n\t\t\t\/\/ renumbered.\n\t\t\tassert(old_to_new_indices[i] < num_uncontained_reads);\n\t\t\tassert(new_to_old_indices[old_to_new_indices[i]] == ~size_t(0));\n\t\t\tnew_to_old_indices[old_to_new_indices[i]] = i;\n\t\t}\n\t}\n\tassert(j == num_contained_reads);\n\n\t\/\/ Find the shortest overhanging overlap for each contained read\n\tinfo(\"Finding the shortest overhanging overlap for each contained read\");\n\n\tstd::vector<const Overlap *>\n\t\tshortest_overhang_overlaps(num_contained_reads, NULL);\n\n\tstd::vector<const Overlap *>\n\t\tshortest_underhang_overlaps(num_contained_reads, NULL);\n\n\tstd::vector<Overlap::read_pos_t>\n\t\tshortest_overhang_lens(num_contained_reads,\n\t\t\t\t std::numeric_limits<Overlap::read_pos_t>::max());\n\n\tstd::vector<Overlap::read_pos_t>\n\t\tshortest_underhang_lens(num_contained_reads,\n\t\t\t\t\tstd::numeric_limits<Overlap::read_pos_t>::max());\n\n\tforeach (const OverlapVecVec::OverlapSet & overlap_set, orig_overlaps) {\n\t\tforeach(const Overlap & o, overlap_set) {\n\t\t\tOverlap::read_idx_t f_idx;\n\t\t\tOverlap::read_pos_t f_beg;\n\t\t\tOverlap::read_pos_t f_end;\n\t\t\tOverlap::read_idx_t g_idx;\n\t\t\tOverlap::read_pos_t g_beg;\n\t\t\tOverlap::read_pos_t g_end;\n\t\t\tbool rc;\n\n\t\t\tOverlap::read_idx_t uncontained_read_orig_idx;\n\t\t\tOverlap::read_pos_t uncontained_read_overlap_beg;\n\t\t\tOverlap::read_pos_t uncontained_read_overlap_end;\n\n\t\t\tassert_overlap_valid(o, orig_reads, 1, 0);\n\n\t\t\to.get(f_idx, f_beg, f_end, g_idx, g_beg, g_end, rc);\n\t\t\tconst BaseVec & f = orig_reads[f_idx];\n\t\t\tconst BaseVec & g = orig_reads[g_idx];\n\t\t\tconst BaseVec * uncontained_read;\n\n\t\t\tassert(f_idx < num_orig_reads);\n\t\t\tassert(g_idx < num_orig_reads);\n\n\t\t\tsize_t contained_read_orig_idx = ~size_t(0);\n\t\t\tif (f_beg == 0 && f_end == f.size() - 1) {\n\t\t\t\t\/\/ Read f is contained\n\t\t\t\t\/\/ ... but only count this overlap if g is NOT\n\t\t\t\t\/\/ contained\n\t\t\t\tif (old_to_new_indices[g_idx] != ~size_t(0)) {\n\t\t\t\t\tcontained_read_orig_idx = f_idx;\n\t\t\t\t\tuncontained_read = &g;\n\t\t\t\t\tuncontained_read_orig_idx = g_idx;\n\t\t\t\t\tuncontained_read_overlap_beg = g_beg;\n\t\t\t\t\tuncontained_read_overlap_end = g_end;\n\t\t\t\t}\n\t\t\t} else if (g_beg == 0 && g_end == g.size() - 1) {\n\t\t\t\t\/\/ Read g is contained\n\t\t\t\t\/\/ ... but only count this overlap is f is NOT\n\t\t\t\t\/\/ contained\n\t\t\t\tif (old_to_new_indices[f_idx] != ~size_t(0)) {\n\t\t\t\t\tcontained_read_orig_idx = g_idx;\n\t\t\t\t\tuncontained_read = &f;\n\t\t\t\t\tuncontained_read_orig_idx = f_idx;\n\t\t\t\t\tuncontained_read_overlap_beg = f_beg;\n\t\t\t\t\tuncontained_read_overlap_end = f_end;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (contained_read_orig_idx != ~size_t(0)) {\n\t\t\t\tassert(old_to_new_indices[contained_read_orig_idx] ==\n\t\t\t\t ~size_t(0));\n\t\t\t\tassert(old_to_contained_indices[contained_read_orig_idx] !=\n\t\t\t\t ~size_t(0));\n\t\t\t\t\/\/ This is a containing overlap, and the read\n\t\t\t\t\/\/ with original index @contained_read_orig_idx\n\t\t\t\t\/\/ is contained. Compute the overhang length.\n\t\t\t\tOverlap::read_pos_t overhang_len;\n\t\t\t\tOverlap::read_pos_t underhang_len;\n\t\t\t\tif (rc) {\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ ---------->\n\t\t\t\t\t\/\/ <------------------------\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ |overhang|\n\t\t\t\t\toverhang_len = uncontained_read_overlap_beg;\n\t\t\t\t\tunderhang_len = uncontained_read->length() -\n\t\t\t\t\t\t\t(uncontained_read_overlap_end + 1);\n\t\t\t\t} else {\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ ---------->\n\t\t\t\t\t\/\/ ------------------------>\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ |overhang|\n\t\t\t\t\tassert(uncontained_read->length() >=\n\t\t\t\t\t uncontained_read_overlap_end + 1);\n\t\t\t\t\toverhang_len = uncontained_read->length() -\n\t\t\t\t\t\t (uncontained_read_overlap_end + 1);\n\t\t\t\t\tunderhang_len = uncontained_read_overlap_beg;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Index of this contained read in the\n\t\t\t\t\/\/ sequential numbering of the contained reads\n\t\t\t\tsize_t contained_idx =\n\t\t\t\t\told_to_contained_indices[contained_read_orig_idx];\n\n\t\t\t\t\/\/ Update the shortest overhang if this overhang\n\t\t\t\t\/\/ is shorter than the previous shortest one.\n\t\t\t\tif (overhang_len < shortest_overhang_lens[contained_idx]) {\n\t\t\t\t\tshortest_overhang_overlaps[contained_idx] = &o;\n\t\t\t\t\tshortest_overhang_lens[contained_idx] = overhang_len;\n\t\t\t\t}\n\n\t\t\t\tif (underhang_len < shortest_underhang_lens[contained_idx]) {\n\t\t\t\t\tshortest_underhang_overlaps[contained_idx] = &o;\n\t\t\t\t\tshortest_underhang_lens[contained_idx] = underhang_len;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tinfo(\"Reading string graph from \\\"%s\\\"\", graph_file);\n\tAnyStringGraph graph(graph_file);\n\n\tinfo(\"Mapping %zu contained reads into the string graph\", num_contained_reads);\n\n\t\/\/ Map the contained reads into the graph, given the overlap to use to\n\t\/\/ map each contained read.\n\tfor (size_t i = 0; i < num_contained_reads; i++) {\n\n\t\t\/\/ Original index of this contained read\n\t\tsize_t contained_read_orig_idx;\n\n\t\t\/\/ The overlap in which the overhang from the end of this\n\t\t\/\/ contained read to its containing read is the shortest\n\t\tconst Overlap *o;\n\n\t\tOverlap::read_idx_t f_idx, g_idx;\n\t\tOverlap::read_idx_t uncontained_read_dir;\n\t\tOverlap::read_idx_t uncontained_read_new_idx;\n\n\t\t\/\/ Map the overhang\n\t\tcontained_read_orig_idx = contained_to_old_indices[i];\n\t\to = shortest_overhang_overlaps[i];\n\t\t\/\/ Original read index must be valid, the read must be\n\t\t\/\/ contained, and it must have at least 1 overlap with an\n\t\t\/\/ uncontained read.\n\t\tassert(contained_read_orig_idx < num_orig_reads);\n\t\tassert(old_to_new_indices[contained_read_orig_idx] == ~size_t(0));\n\t\tassert(o != NULL);\n\t\to->get_indices(f_idx, g_idx);\n\t\tif (f_idx == contained_read_orig_idx) {\n\t\t\tuncontained_read_new_idx = old_to_new_indices[g_idx];\n\t\t} else {\n\t\t\tassert(g_idx == contained_read_orig_idx);\n\t\t\tuncontained_read_new_idx = old_to_new_indices[f_idx];\n\t\t}\n\t\tassert(uncontained_read_new_idx < num_uncontained_reads);\n\t\tuncontained_read_dir = (o->is_rc() ? 1 : 0);\n\t\tgraph.map_contained_read(uncontained_read_new_idx,\n\t\t\t\t\t uncontained_read_dir,\n\t\t\t\t\t shortest_overhang_lens[i]);\n\n\t\t\/\/ Map the underhang\n\t\to = shortest_underhang_overlaps[i];\n\t\tassert(o != NULL);\n\t\to->get_indices(f_idx, g_idx);\n\t\tif (f_idx == contained_read_orig_idx) {\n\t\t\tuncontained_read_new_idx = old_to_new_indices[g_idx];\n\t\t} else {\n\t\t\tassert(g_idx == contained_read_orig_idx);\n\t\t\tuncontained_read_new_idx = old_to_new_indices[f_idx];\n\t\t}\n\t\tassert(uncontained_read_new_idx < num_uncontained_reads);\n\t\tuncontained_read_dir = (o->is_rc() ? 0 : 1);\n\t\tgraph.map_contained_read(uncontained_read_new_idx,\n\t\t\t\t\t uncontained_read_dir,\n\t\t\t\t\t shortest_overhang_lens[i]);\n\t}\n\n\tinfo(\"Writing string graph to \\\"%s\\\"\", out_graph_file);\n\tgraph.write(out_graph_file);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"libtorrent\/storage.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/session.hpp\"\n\n#include <boost\/utility.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/convenience.hpp>\n#include <boost\/thread\/mutex.hpp>\n\n#include \"test.hpp\"\n\nusing namespace libtorrent;\nusing namespace boost::filesystem;\n\nint test_main()\n{\n\tconst int piece_size = 16;\n\tconst int half = piece_size \/ 2;\n\ttorrent_info info;\n\tinfo.set_piece_size(piece_size);\n\tinfo.add_file(\"temp_storage\/test1.tmp\", 17);\n\tinfo.add_file(\"temp_storage\/test2.tmp\", 612);\n\tinfo.add_file(\"temp_storage\/test3.tmp\", 0);\n\tinfo.add_file(\"temp_storage\/test4.tmp\", 0);\n\tinfo.add_file(\"temp_storage\/test5.tmp\", 1);\n\n\tchar piece0[piece_size] =\n\t{ 6, 6, 6, 6, 6, 6, 6, 6\n\t, 9, 9, 9, 9, 9, 9, 9, 9};\n\n\tchar piece1[piece_size] =\n\t{ 0, 0, 0, 0, 0, 0, 0, 0\n\t, 1, 1, 1, 1, 1, 1, 1, 1};\n\n\tchar piece2[piece_size] =\n\t{ 0, 0, 1, 0, 0, 0, 0, 0\n\t, 1, 1, 1, 1, 1, 1, 1, 1};\n\n\tinfo.set_hash(0, hasher(piece0, piece_size).final());\n\tinfo.set_hash(1, hasher(piece1, piece_size).final());\n\tinfo.set_hash(2, hasher(piece2, piece_size).final());\n\t\n\tinfo.create_torrent();\n\n\tcreate_directory(initial_path() \/ \"temp_storage\");\n\n\tint num_pieces = (1 + 612 + 17 + piece_size - 1) \/ piece_size;\n\tTEST_CHECK(info.num_pieces() == num_pieces);\n\n\tchar piece[piece_size];\n\n\t{ \/\/ avoid having two storages use the same files\t\n\tstorage s(info, initial_path());\n\n\t\/\/ write piece 1 (in slot 0)\n\ts.write(piece1, 0, 0, half);\n\ts.write(piece1 + half, 0, half, half);\n\n\t\/\/ verify piece 1\n\ts.read(piece, 0, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece1));\n\t\n\t\/\/ do the same with piece 0 and 2 (in slot 1 and 2)\n\ts.write(piece0, 1, 0, piece_size);\n\ts.write(piece2, 2, 0, piece_size);\n\n\t\/\/ verify piece 0 and 2\n\ts.read(piece, 1, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece0));\n\n\ts.read(piece, 2, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece2));\n\t\n\t\/\/ make sure the files have the correct size\n\tTEST_CHECK(file_size(initial_path() \/ \"temp_storage\" \/ \"test1.tmp\") == 17);\n\tTEST_CHECK(file_size(initial_path() \/ \"temp_storage\" \/ \"test2.tmp\") == 31);\n\ts.release_files();\n\t}\n\n\t\/\/ make sure the piece_manager can identify the pieces\n\tpiece_manager pm(info, initial_path());\n\tboost::mutex lock;\n\tlibtorrent::detail::piece_checker_data d;\n\n\tstd::vector<bool> pieces;\n\tnum_pieces = 0;\n\tTEST_CHECK(pm.check_fastresume(d, pieces, num_pieces, true) == false);\n\tbool finished = false;\n\tfloat progress;\n\tnum_pieces = 0;\n\twhile (!finished)\n\t\tboost::tie(finished, progress) = pm.check_files(pieces, num_pieces);\n\n\tTEST_CHECK(num_pieces == std::count(pieces.begin(), pieces.end()\n\t\t, true));\n\t\n\tpm.read(piece, 0, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece0));\n\n\tpm.read(piece, 1, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece1));\n\n\tpm.read(piece, 2, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece2));\n\tpm.release_files();\n\n\tremove_all(initial_path() \/ \"temp_storage\");\n\t\n\treturn 0;\n}\n\n<commit_msg>updated storage test<commit_after>#include \"libtorrent\/storage.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/session.hpp\"\n\n#include <boost\/utility.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/convenience.hpp>\n#include <boost\/thread\/mutex.hpp>\n\n#include \"test.hpp\"\n\nusing namespace libtorrent;\nusing namespace boost::filesystem;\n\nint test_main()\n{\n\tconst int piece_size = 16;\n\tconst int half = piece_size \/ 2;\n\ttorrent_info info;\n\tinfo.set_piece_size(piece_size);\n\tinfo.add_file(\"temp_storage\/test1.tmp\", 17);\n\tinfo.add_file(\"temp_storage\/test2.tmp\", 612);\n\tinfo.add_file(\"temp_storage\/test3.tmp\", 0);\n\tinfo.add_file(\"temp_storage\/test4.tmp\", 0);\n\tinfo.add_file(\"temp_storage\/test5.tmp\", 1);\n\n\tchar piece0[piece_size] =\n\t{ 6, 6, 6, 6, 6, 6, 6, 6\n\t, 9, 9, 9, 9, 9, 9, 9, 9};\n\n\tchar piece1[piece_size] =\n\t{ 0, 0, 0, 0, 0, 0, 0, 0\n\t, 1, 1, 1, 1, 1, 1, 1, 1};\n\n\tchar piece2[piece_size] =\n\t{ 0, 0, 1, 0, 0, 0, 0, 0\n\t, 1, 1, 1, 1, 1, 1, 1, 1};\n\n\tinfo.set_hash(0, hasher(piece0, piece_size).final());\n\tinfo.set_hash(1, hasher(piece1, piece_size).final());\n\tinfo.set_hash(2, hasher(piece2, piece_size).final());\n\t\n\tinfo.create_torrent();\n\n\tcreate_directory(initial_path() \/ \"temp_storage\");\n\n\tint num_pieces = (1 + 612 + 17 + piece_size - 1) \/ piece_size;\n\tTEST_CHECK(info.num_pieces() == num_pieces);\n\n\tchar piece[piece_size];\n\n\t{ \/\/ avoid having two storages use the same files\t\n\tstorage s(info, initial_path());\n\n\t\/\/ write piece 1 (in slot 0)\n\ts.write(piece1, 0, 0, half);\n\ts.write(piece1 + half, 0, half, half);\n\n\t\/\/ verify piece 1\n\ts.read(piece, 0, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece1));\n\t\n\t\/\/ do the same with piece 0 and 2 (in slot 1 and 2)\n\ts.write(piece0, 1, 0, piece_size);\n\ts.write(piece2, 2, 0, piece_size);\n\n\t\/\/ verify piece 0 and 2\n\ts.read(piece, 1, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece0));\n\n\ts.read(piece, 2, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece2));\n\t\n\t\/\/ make sure the files have the correct size\n\tTEST_CHECK(file_size(initial_path() \/ \"temp_storage\" \/ \"test1.tmp\") == 17);\n\tTEST_CHECK(file_size(initial_path() \/ \"temp_storage\" \/ \"test2.tmp\") == 31);\n\ts.release_files();\n\t}\n\n\t\/\/ make sure the piece_manager can identify the pieces\n\tpiece_manager pm(info, initial_path());\n\tboost::mutex lock;\n\tlibtorrent::detail::piece_checker_data d;\n\n\tstd::vector<bool> pieces;\n\tnum_pieces = 0;\n\tTEST_CHECK(pm.check_fastresume(d, pieces, num_pieces, true) == false);\n\tbool finished = false;\n\tfloat progress;\n\tnum_pieces = 0;\n\twhile (!finished)\n\t\tboost::tie(finished, progress) = pm.check_files(pieces, num_pieces);\n\n\tTEST_CHECK(num_pieces == std::count(pieces.begin(), pieces.end()\n\t\t, true));\n\t\n\tpm.read(piece, 0, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece0));\n\n\tpm.read(piece, 1, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece1));\n\n\tpm.read(piece, 2, 0, piece_size);\n\tTEST_CHECK(std::equal(piece, piece + piece_size, piece2));\n\tpm.release_files();\n\n\tTEST_CHECK(exists(\"temp_storage\/test3.tmp\"));\n\tTEST_CHECK(exists(\"temp_storage\/test4.tmp\"));\n\t\n\tremove_all(initial_path() \/ \"temp_storage\");\n\t\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <chrono>\n#include <iostream>\n#include <random>\n#include \"..\/includes\/sdr.hpp\"\n\nstd::chrono::system_clock::duration since_epoch()\n{\n return std::chrono::system_clock::now().time_since_epoch();\n}\n\n\nint main()\n{\n constexpr std::size_t Amount = 100000;\n constexpr std::size_t Width = 2048;\n constexpr std::size_t ParallelAmount = 100;\n constexpr float OnPercent = 0.02;\n\n sdr::bank<Width> memory;\n std::vector<std::bitset<Width>> fields;\n\n std::array<double, Width> weights;\n weights.fill(1.1);\n\n std::cout << \"bench\" << std::endl;\n std::cout << \"\\tamount: \" << Amount << std::endl;\n std::cout << \"\\twidth: \" << Width << std::endl;\n std::cout << \"\\tpercent: \" << OnPercent << std::endl;\n std::cout << std::endl;\n\n {\n auto start = since_epoch();\n\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> wdis(0, Width-1);\n\n const std::size_t amount_set = static_cast<std::size_t>(Width * OnPercent);\n\n for(std::size_t i=0; i<Amount; ++i) {\n std::bitset<Width> data;\n\n for(std::size_t j=0; j<amount_set; ++j) {\n data.set(wdis(gen));\n }\n\n fields.push_back(data);\n }\n\n auto end = since_epoch();\n\n std::cout << \"generation took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n }\n\n {\n auto start = since_epoch();\n\n for(auto & field : fields) {\n memory.insert(sdr::concept(field));\n }\n\n auto end = since_epoch();\n\n std::cout << \"insertion took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n }\n\n {\n auto start = since_epoch();\n\n memory.save_to_file(\"test.sdr\");\n\n auto end = since_epoch();\n\n std::cout << \"save to file took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n }\n\n memory.clear();\n\n {\n auto start = since_epoch();\n\n const std::size_t storage_size { memory.load_from_file(\"test.sdr\") };\n\n auto end = since_epoch();\n\n std::cout << \"load from file (\" << storage_size << \" concepts) took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n }\n\n {\n auto start = since_epoch();\n\n std::vector<std::future<std::vector<std::pair<sdr::position_t, std::size_t>>>> futures;\n\n for(sdr::position_t i=0; i < ParallelAmount; ++i) {\n futures.push_back(memory.async_closest(i, 10));\n }\n\n std::vector<std::vector<std::pair<sdr::position_t, std::size_t>>> closests;\n for(sdr::position_t i=0; i < ParallelAmount; ++i) {\n closests.push_back(futures[i].get());\n }\n\n auto end = since_epoch();\n\n std::cout << \"finding closest (parallel => \" << ParallelAmount << \") took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n\n std::size_t counter = 0;\n for(auto & closest : closests) {\n std::cout << \"\\t#\" << counter << std::endl;\n\n for(auto & it : closest) {\n std::cout << \"\\t\\t\" << it.first << \"\\t:: \" << it.second << std::endl;\n }\n\n std::cout << std::endl;\n ++counter;\n }\n }\n\n {\n auto start = since_epoch();\n\n std::array<double, Width> weights;\n std::fill(weights.begin(), weights.end(), 1.1);\n auto closest = memory.weighted_closest(1, 10, weights);\n\n auto end = since_epoch();\n\n std::cout << \"finding weighted closest took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n\n std::cout << \"closest: \" << std::endl;\n for(auto & it : closest) {\n std::cout << \"\\t\" << it.first << \"\\t:: \" << it.second << std::endl;\n }\n }\n\n {\n std::vector<std::size_t> simlist(10);\n std::iota(simlist.begin(), simlist.end(), 1);\n\n auto start = since_epoch();\n\n auto similarity = memory.union_similarity(0, simlist);\n\n auto end = since_epoch();\n\n std::cout << \"finding union similarity took: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << \"ns\" << std::endl;\n\n std::cout << \"similarity: \" << similarity << std::endl;\n }\n\n {\n auto start = since_epoch();\n\n auto matching = memory.matching(sdr::concept({ 0, 10 }));\n\n auto end = since_epoch();\n\n std::cout << \"finding matching took: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << \"ns\" << std::endl;\n std::cout << \"matching.size() => \" << matching.size() << std::endl;\n\n std::cout << \"matching: \" << std::endl;\n for(auto & it : matching) {\n std::cout << it << std::endl;\n }\n }\n\n return 0;\n}\n<commit_msg>fix bench for large dimensions<commit_after>#include <chrono>\n#include <iostream>\n#include <random>\n#include \"..\/includes\/sdr.hpp\"\n\nstd::chrono::system_clock::duration since_epoch()\n{\n return std::chrono::system_clock::now().time_since_epoch();\n}\n\n\nint main()\n{\n constexpr std::size_t Amount = 100000;\n constexpr sdr::width_t Width = 2048;\n constexpr std::size_t ParallelAmount = 100;\n constexpr double OnPercent = 0.02;\n\n sdr::bank<Width> memory;\n std::vector<std::vector<sdr::position_t>> fields;\n\n std::vector<double> weights(Width, 1.1);\n\n std::cout << \"bench\" << std::endl;\n std::cout << \"\\tamount: \" << Amount << std::endl;\n std::cout << \"\\twidth: \" << Width << std::endl;\n std::cout << \"\\tpercent: \" << OnPercent << std::endl;\n std::cout << std::endl;\n\n {\n auto start = since_epoch();\n\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> wdis(0, Width-1);\n\n const std::size_t amount_set = static_cast<std::size_t>(Width * OnPercent);\n\n for(std::size_t i=0; i<Amount; ++i) {\n std::vector<sdr::position_t> data;\n\n for(std::size_t j=0; j<amount_set; ++j) {\n data.push_back(wdis(gen));\n }\n\n fields.push_back(data);\n }\n\n auto end = since_epoch();\n\n std::cout << \"generation took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n }\n\n {\n auto start = since_epoch();\n\n for(auto & field : fields) {\n memory.insert(sdr::concept(field));\n }\n\n auto end = since_epoch();\n\n std::cout << \"insertion took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n }\n\n {\n auto start = since_epoch();\n\n memory.save_to_file(\"test.sdr\");\n\n auto end = since_epoch();\n\n std::cout << \"save to file took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n }\n\n memory.clear();\n\n {\n auto start = since_epoch();\n\n const std::size_t storage_size { memory.load_from_file(\"test.sdr\") };\n\n auto end = since_epoch();\n\n std::cout << \"load from file (\" << storage_size << \" concepts) took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n }\n\n {\n auto start = since_epoch();\n\n std::vector<std::future<std::vector<std::pair<sdr::position_t, std::size_t>>>> futures;\n\n for(sdr::position_t i=0; i < ParallelAmount; ++i) {\n futures.push_back(memory.async_closest(i, 2));\n }\n\n std::vector<std::vector<std::pair<sdr::position_t, std::size_t>>> closests;\n for(sdr::position_t i=0; i < ParallelAmount; ++i) {\n closests.push_back(futures[i].get());\n }\n\n auto end = since_epoch();\n\n std::cout << \"finding closest (parallel => \" << ParallelAmount << \") took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n\n std::size_t counter = 0;\n for(auto & closest : closests) {\n std::cout << \"\\t#\" << counter << std::endl;\n\n for(auto & it : closest) {\n std::cout << \"\\t\\t\" << it.first << \"\\t:: \" << it.second << std::endl;\n }\n\n std::cout << std::endl;\n ++counter;\n }\n }\n\n {\n auto start = since_epoch();\n\n auto closest = memory.weighted_closest(1, 10, weights);\n\n auto end = since_epoch();\n\n std::cout << \"finding weighted closest took: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << \"ms\" << std::endl;\n\n std::cout << \"closest: \" << std::endl;\n for(auto & it : closest) {\n std::cout << \"\\t\" << it.first << \"\\t:: \" << it.second << std::endl;\n }\n }\n\n {\n std::vector<std::size_t> simlist(10);\n std::iota(simlist.begin(), simlist.end(), 1);\n\n auto start = since_epoch();\n\n auto similarity = memory.union_similarity(0, simlist);\n\n auto end = since_epoch();\n\n std::cout << \"finding union similarity took: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << \"ns\" << std::endl;\n\n std::cout << \"similarity: \" << similarity << std::endl;\n }\n\n {\n auto start = since_epoch();\n\n auto matching = memory.matching(sdr::concept({ 0, 10 }));\n\n auto end = since_epoch();\n\n std::cout << \"finding matching took: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << \"ns\" << std::endl;\n std::cout << \"matching.size() => \" << matching.size() << std::endl;\n\n std::cout << \"matching: \" << std::endl;\n for(auto & it : matching) {\n std::cout << it << std::endl;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2007-2012 Christian Stehno\r\n\/\/ This file is part of the \"Irrlicht Engine\".\r\n\/\/ For conditions of distribution and use, see copyright notice in irrlicht.h\r\n\r\n#include \"IrrCompileConfig.h\"\n\r\n#ifdef _IRR_COMPILE_WITH_STL_LOADER_\r\n\r\n#include \"CSTLMeshFileLoader.h\"\r\n#include \"SMesh.h\"\r\n\r\n#include \"IReadFile.h\"\r\n#include \"coreutil.h\"\r\n#include \"os.h\"\r\n#include \"SVertexManipulator.h\"\n\n#include <vector>\n\r\nnamespace irr\r\n{\r\nnamespace scene\r\n{\r\n\r\nasset::IAsset* CSTLMeshFileLoader::loadAsset(io::IReadFile* _file, const asset::IAssetLoader::SAssetLoadParams& _params, asset::IAssetLoader::IAssetLoaderOverride* _override, uint32_t _hierarchyLevel)\r\n{\r\n\tconst long filesize = _file->getSize();\r\n\tif (filesize < 6) \/\/ we need a header\r\n\t\treturn nullptr;\r\n\n bool hasColor = false;\n\n\tSCPUMesh* mesh = new SCPUMesh();\n\tICPUMeshDataFormatDesc* desc = new ICPUMeshDataFormatDesc();\r\n {\r\n\tICPUMeshBuffer* meshbuffer = new ICPUMeshBuffer();\n\tmeshbuffer->setMeshDataAndFormat(desc);\n\tdesc->drop();\n\r\n\tmesh->addMeshBuffer(meshbuffer);\n\tmeshbuffer->drop();\r\n }\r\n\r\n\tbool binary = false;\r\n\tcore::stringc token;\r\n\tif (getNextToken(_file, token) != \"solid\")\r\n\t\tbinary = hasColor = true;\r\n\r\n core::vector<core::vectorSIMDf> positions, normals;\r\n core::vector<uint32_t> colors;\r\n\tif (binary)\r\n\t{\n if (_file->getSize() < 80)\n {\n mesh->drop();\n return nullptr;\n }\n\t\t_file->seek(80); \/\/ skip header\r\n uint32_t vtxCnt = 0u;\r\n\t\t_file->read(&vtxCnt, 4);\n positions.reserve(3*vtxCnt);\r\n normals.reserve(vtxCnt);\r\n colors.reserve(vtxCnt);\r\n\t}\r\n\telse\r\n\t\tgoNextLine(_file); \/\/ skip header\n\r\n\r\n\tuint16_t attrib=0u;\r\n\ttoken.reserve(32);\r\n\twhile (_file->getPos() < filesize)\r\n\t{\r\n\t\tif (!binary)\r\n\t\t{\r\n\t\t\tif (getNextToken(_file, token) != \"facet\")\r\n\t\t\t{\r\n\t\t\t\tif (token==\"endsolid\")\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t\tif (getNextToken(_file, token) != \"normal\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t}\r\n\r\n {\r\n core::vectorSIMDf n;\r\n\t\tgetNextVector(_file, n, binary);\r\n normals.push_back(n);\r\n }\r\n\r\n\t\tif (!binary)\r\n\t\t{\r\n\t\t\tif (getNextToken(_file, token) != \"outer\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t\tif (getNextToken(_file, token) != \"loop\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t}\r\n\r\n {\r\n core::vectorSIMDf p[3];\r\n\t\tfor (uint32_t i = 0u; i < 3u; ++i)\r\n\t\t{\r\n\t\t\tif (!binary)\r\n\t\t\t{\r\n\t\t\t\tif (getNextToken(_file, token) != \"vertex\")\r\n\t\t\t\t{\r\n\t\t\t\t\tmesh->drop();\r\n\t\t\t\t\treturn nullptr;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tgetNextVector(_file, p[i], binary);\r\n\t\t}\r\n for (uint32_t i = 0u; i < 3u; ++i) \/\/ seems like in STL format vertices are ordered in clockwise manner...\r\n positions.push_back(p[2u-i]);\r\n }\r\n\r\n\t\tif (!binary)\r\n\t\t{\r\n\t\t\tif (getNextToken(_file, token) != \"endloop\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t\tif (getNextToken(_file, token) != \"endfacet\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t_file->read(&attrib, 2);\r\n\t\t}\r\n\r\n if (hasColor && (attrib & 0x8000)) \/\/ assuming VisCam\/SolidView non-standard trick to store color in 2 bytes of extra attribute\r\n {\r\n colors.push_back(video::A1R5G5B5toA8R8G8B8(attrib));\r\n }\r\n else\r\n {\r\n hasColor = false;\r\n colors.clear();\r\n }\r\n\r\n\t\tif ((normals.back() == core::vectorSIMDf()).all())\r\n {\r\n\t\t\tnormals.back().set(\n core::plane3df(\n (positions.rbegin()+2)->getAsVector3df(),\n (positions.rbegin()+1)->getAsVector3df(),\n (positions.rbegin()+0)->getAsVector3df()).Normal\n );\n }\r\n\t} \/\/ end while (_file->getPos() < filesize)\n\n const size_t vtxSize = hasColor ? (3 * sizeof(float) + 4 + 4) : (3 * sizeof(float) + 4);\n\tcore::ICPUBuffer* vertexBuf = new core::ICPUBuffer(vtxSize*positions.size());\n\n uint32_t normal{};\n for (size_t i = 0u; i < positions.size(); ++i)\n {\n if (i%3 == 0)\n normal = quantizeNormal2_10_10_10(normals[i\/3]);\n uint8_t* ptr = ((uint8_t*)(vertexBuf->getPointer())) + i*vtxSize;\n memcpy(ptr, positions[i].pointer, 3*4);\n ((uint32_t*)(ptr+12))[0] = normal;\n if (hasColor)\n memcpy(ptr+16, colors.data()+i\/3, 4);\n }\n\n\tdesc->mapVertexAttrBuffer(vertexBuf, EVAI_ATTR0, ECPA_THREE, ECT_FLOAT, vtxSize, 0);\n\tdesc->mapVertexAttrBuffer(vertexBuf, EVAI_ATTR3, ECPA_FOUR, ECT_INT_2_10_10_10_REV, vtxSize, 12);\n if (hasColor)\n\t desc->mapVertexAttrBuffer(vertexBuf, EVAI_ATTR1, ECPA_REVERSED_OR_BGRA, ECT_NORMALIZED_UNSIGNED_BYTE, vtxSize, 16);\n\tvertexBuf->drop();\n\n\tmesh->getMeshBuffer(0)->setIndexCount(positions.size());\r\n \/\/mesh->getMeshBuffer(0)->setPrimitiveType(EPT_POINTS);\r\n\tmesh->recalculateBoundingBox(true);\r\n\r\n\treturn mesh;\r\n}\r\n\r\nbool CSTLMeshFileLoader::isALoadableFileFormat(io::IReadFile * _file) const\r\n{\r\n if (_file->getSize() <= 6u)\r\n return false;\r\n\r\n char header[6];\r\n const size_t prevPos = _file->getPos();\r\n _file->seek(0u);\r\n _file->read(header, 6u);\r\n _file->seek(prevPos);\r\n\r\n if (strncmp(header, \"solid \", 6u) == 0)\r\n return true;\r\n else\r\n return _file->getSize() > 80u; \/\/ some other validation also needed here...\r\n}\r\n\r\n\/\/! Read 3d vector of floats\r\nvoid CSTLMeshFileLoader::getNextVector(io::IReadFile* file, core::vectorSIMDf& vec, bool binary) const\r\n{\r\n\tif (binary)\r\n\t{\r\n\t\tfile->read(&vec.X, 4);\r\n\t\tfile->read(&vec.Y, 4);\r\n\t\tfile->read(&vec.Z, 4);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tgoNextWord(file);\r\n\t\tcore::stringc tmp;\r\n\r\n\t\tgetNextToken(file, tmp);\n\t\tsscanf(tmp.c_str(),\"%f\",&vec.X);\r\n\t\tgetNextToken(file, tmp);\n\t\tsscanf(tmp.c_str(),\"%f\",&vec.Y);\r\n\t\tgetNextToken(file, tmp);\n\t\tsscanf(tmp.c_str(),\"%f\",&vec.Z);\r\n\t}\r\n\tvec.X=-vec.X;\r\n}\r\n\r\n\r\n\/\/! Read next word\r\nconst core::stringc& CSTLMeshFileLoader::getNextToken(io::IReadFile* file, core::stringc& token) const\r\n{\r\n\tgoNextWord(file);\r\n\tuint8_t c;\r\n\ttoken = \"\";\r\n\twhile(file->getPos() != file->getSize())\r\n\t{\r\n\t\tfile->read(&c, 1);\r\n\t\t\/\/ found it, so leave\r\n\t\tif (core::isspace(c))\r\n\t\t\tbreak;\r\n\t\ttoken.append(c);\r\n\t}\r\n\treturn token;\r\n}\r\n\r\n\r\n\/\/! skip to next word\r\nvoid CSTLMeshFileLoader::goNextWord(io::IReadFile* file) const\r\n{\r\n\tuint8_t c;\r\n\twhile(file->getPos() != file->getSize())\r\n\t{\r\n\t\tfile->read(&c, 1);\r\n\t\t\/\/ found it, so leave\r\n\t\tif (!core::isspace(c))\r\n\t\t{\r\n\t\t\tfile->seek(-1, true);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\/\/! Read until line break is reached and stop at the next non-space character\r\nvoid CSTLMeshFileLoader::goNextLine(io::IReadFile* file) const\r\n{\r\n\tuint8_t c;\r\n\t\/\/ look for newline characters\r\n\twhile(file->getPos() != file->getSize())\r\n\t{\r\n\t\tfile->read(&c, 1);\r\n\t\t\/\/ found it, so leave\r\n\t\tif (c=='\\n' || c=='\\r')\r\n\t\t\tbreak;\r\n\t}\r\n}\r\n\r\n} \/\/ end namespace scene\r\n} \/\/ end namespace irr\r\n\r\n\r\n#endif \/\/ _IRR_COMPILE_WITH_STL_LOADER_\r\n<commit_msg>asset-pipeline: STL better validation<commit_after>\/\/ Copyright (C) 2007-2012 Christian Stehno\r\n\/\/ This file is part of the \"Irrlicht Engine\".\r\n\/\/ For conditions of distribution and use, see copyright notice in irrlicht.h\r\n\r\n#include \"IrrCompileConfig.h\"\n\r\n#ifdef _IRR_COMPILE_WITH_STL_LOADER_\r\n\r\n#include \"CSTLMeshFileLoader.h\"\r\n#include \"SMesh.h\"\r\n\r\n#include \"IReadFile.h\"\r\n#include \"coreutil.h\"\r\n#include \"os.h\"\r\n#include \"SVertexManipulator.h\"\n\n#include <vector>\n\r\nnamespace irr\r\n{\r\nnamespace scene\r\n{\r\n\r\nasset::IAsset* CSTLMeshFileLoader::loadAsset(io::IReadFile* _file, const asset::IAssetLoader::SAssetLoadParams& _params, asset::IAssetLoader::IAssetLoaderOverride* _override, uint32_t _hierarchyLevel)\r\n{\r\n\tconst long filesize = _file->getSize();\r\n\tif (filesize < 6) \/\/ we need a header\r\n\t\treturn nullptr;\r\n\n bool hasColor = false;\n\n\tSCPUMesh* mesh = new SCPUMesh();\n\tICPUMeshDataFormatDesc* desc = new ICPUMeshDataFormatDesc();\r\n {\r\n\tICPUMeshBuffer* meshbuffer = new ICPUMeshBuffer();\n\tmeshbuffer->setMeshDataAndFormat(desc);\n\tdesc->drop();\n\r\n\tmesh->addMeshBuffer(meshbuffer);\n\tmeshbuffer->drop();\r\n }\r\n\r\n\tbool binary = false;\r\n\tcore::stringc token;\r\n\tif (getNextToken(_file, token) != \"solid\")\r\n\t\tbinary = hasColor = true;\r\n\r\n core::vector<core::vectorSIMDf> positions, normals;\r\n core::vector<uint32_t> colors;\r\n\tif (binary)\r\n\t{\n if (_file->getSize() < 80)\n {\n mesh->drop();\n return nullptr;\n }\n\t\t_file->seek(80); \/\/ skip header\r\n uint32_t vtxCnt = 0u;\r\n\t\t_file->read(&vtxCnt, 4);\n positions.reserve(3*vtxCnt);\r\n normals.reserve(vtxCnt);\r\n colors.reserve(vtxCnt);\r\n\t}\r\n\telse\r\n\t\tgoNextLine(_file); \/\/ skip header\n\r\n\r\n\tuint16_t attrib=0u;\r\n\ttoken.reserve(32);\r\n\twhile (_file->getPos() < filesize)\r\n\t{\r\n\t\tif (!binary)\r\n\t\t{\r\n\t\t\tif (getNextToken(_file, token) != \"facet\")\r\n\t\t\t{\r\n\t\t\t\tif (token==\"endsolid\")\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t\tif (getNextToken(_file, token) != \"normal\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t}\r\n\r\n {\r\n core::vectorSIMDf n;\r\n\t\tgetNextVector(_file, n, binary);\r\n normals.push_back(n);\r\n }\r\n\r\n\t\tif (!binary)\r\n\t\t{\r\n\t\t\tif (getNextToken(_file, token) != \"outer\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t\tif (getNextToken(_file, token) != \"loop\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t}\r\n\r\n {\r\n core::vectorSIMDf p[3];\r\n\t\tfor (uint32_t i = 0u; i < 3u; ++i)\r\n\t\t{\r\n\t\t\tif (!binary)\r\n\t\t\t{\r\n\t\t\t\tif (getNextToken(_file, token) != \"vertex\")\r\n\t\t\t\t{\r\n\t\t\t\t\tmesh->drop();\r\n\t\t\t\t\treturn nullptr;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tgetNextVector(_file, p[i], binary);\r\n\t\t}\r\n for (uint32_t i = 0u; i < 3u; ++i) \/\/ seems like in STL format vertices are ordered in clockwise manner...\r\n positions.push_back(p[2u-i]);\r\n }\r\n\r\n\t\tif (!binary)\r\n\t\t{\r\n\t\t\tif (getNextToken(_file, token) != \"endloop\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t\tif (getNextToken(_file, token) != \"endfacet\")\r\n\t\t\t{\r\n\t\t\t\tmesh->drop();\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t_file->read(&attrib, 2);\r\n\t\t}\r\n\r\n if (hasColor && (attrib & 0x8000)) \/\/ assuming VisCam\/SolidView non-standard trick to store color in 2 bytes of extra attribute\r\n {\r\n colors.push_back(video::A1R5G5B5toA8R8G8B8(attrib));\r\n }\r\n else\r\n {\r\n hasColor = false;\r\n colors.clear();\r\n }\r\n\r\n\t\tif ((normals.back() == core::vectorSIMDf()).all())\r\n {\r\n\t\t\tnormals.back().set(\n core::plane3df(\n (positions.rbegin()+2)->getAsVector3df(),\n (positions.rbegin()+1)->getAsVector3df(),\n (positions.rbegin()+0)->getAsVector3df()).Normal\n );\n }\r\n\t} \/\/ end while (_file->getPos() < filesize)\n\n const size_t vtxSize = hasColor ? (3 * sizeof(float) + 4 + 4) : (3 * sizeof(float) + 4);\n\tcore::ICPUBuffer* vertexBuf = new core::ICPUBuffer(vtxSize*positions.size());\n\n uint32_t normal{};\n for (size_t i = 0u; i < positions.size(); ++i)\n {\n if (i%3 == 0)\n normal = quantizeNormal2_10_10_10(normals[i\/3]);\n uint8_t* ptr = ((uint8_t*)(vertexBuf->getPointer())) + i*vtxSize;\n memcpy(ptr, positions[i].pointer, 3*4);\n ((uint32_t*)(ptr+12))[0] = normal;\n if (hasColor)\n memcpy(ptr+16, colors.data()+i\/3, 4);\n }\n\n\tdesc->mapVertexAttrBuffer(vertexBuf, EVAI_ATTR0, ECPA_THREE, ECT_FLOAT, vtxSize, 0);\n\tdesc->mapVertexAttrBuffer(vertexBuf, EVAI_ATTR3, ECPA_FOUR, ECT_INT_2_10_10_10_REV, vtxSize, 12);\n if (hasColor)\n\t desc->mapVertexAttrBuffer(vertexBuf, EVAI_ATTR1, ECPA_REVERSED_OR_BGRA, ECT_NORMALIZED_UNSIGNED_BYTE, vtxSize, 16);\n\tvertexBuf->drop();\n\n\tmesh->getMeshBuffer(0)->setIndexCount(positions.size());\r\n \/\/mesh->getMeshBuffer(0)->setPrimitiveType(EPT_POINTS);\r\n\tmesh->recalculateBoundingBox(true);\r\n\r\n\treturn mesh;\r\n}\r\n\r\nbool CSTLMeshFileLoader::isALoadableFileFormat(io::IReadFile* _file) const\r\n{\r\n if (_file->getSize() <= 6u)\r\n return false;\r\n\r\n char header[6];\r\n const size_t prevPos = _file->getPos();\r\n _file->seek(0u);\r\n _file->read(header, 6u);\r\n _file->seek(prevPos);\r\n\r\n if (strncmp(header, \"solid \", 6u) == 0)\r\n return true;\r\n else\r\n {\r\n if (_file->getSize() < 84u)\r\n {\r\n _file->seek(prevPos);\r\n return false;\r\n }\r\n _file->seek(80u);\r\n uint32_t triCnt;\r\n _file->read(&triCnt, 4u);\r\n _file->seek(prevPos);\r\n const size_t STL_TRI_SZ = 50u;\r\n return _file->getSize() == (STL_TRI_SZ*triCnt + 84u);\r\n }\r\n}\r\n\r\n\/\/! Read 3d vector of floats\r\nvoid CSTLMeshFileLoader::getNextVector(io::IReadFile* file, core::vectorSIMDf& vec, bool binary) const\r\n{\r\n\tif (binary)\r\n\t{\r\n\t\tfile->read(&vec.X, 4);\r\n\t\tfile->read(&vec.Y, 4);\r\n\t\tfile->read(&vec.Z, 4);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tgoNextWord(file);\r\n\t\tcore::stringc tmp;\r\n\r\n\t\tgetNextToken(file, tmp);\n\t\tsscanf(tmp.c_str(),\"%f\",&vec.X);\r\n\t\tgetNextToken(file, tmp);\n\t\tsscanf(tmp.c_str(),\"%f\",&vec.Y);\r\n\t\tgetNextToken(file, tmp);\n\t\tsscanf(tmp.c_str(),\"%f\",&vec.Z);\r\n\t}\r\n\tvec.X=-vec.X;\r\n}\r\n\r\n\r\n\/\/! Read next word\r\nconst core::stringc& CSTLMeshFileLoader::getNextToken(io::IReadFile* file, core::stringc& token) const\r\n{\r\n\tgoNextWord(file);\r\n\tuint8_t c;\r\n\ttoken = \"\";\r\n\twhile(file->getPos() != file->getSize())\r\n\t{\r\n\t\tfile->read(&c, 1);\r\n\t\t\/\/ found it, so leave\r\n\t\tif (core::isspace(c))\r\n\t\t\tbreak;\r\n\t\ttoken.append(c);\r\n\t}\r\n\treturn token;\r\n}\r\n\r\n\r\n\/\/! skip to next word\r\nvoid CSTLMeshFileLoader::goNextWord(io::IReadFile* file) const\r\n{\r\n\tuint8_t c;\r\n\twhile(file->getPos() != file->getSize())\r\n\t{\r\n\t\tfile->read(&c, 1);\r\n\t\t\/\/ found it, so leave\r\n\t\tif (!core::isspace(c))\r\n\t\t{\r\n\t\t\tfile->seek(-1, true);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\/\/! Read until line break is reached and stop at the next non-space character\r\nvoid CSTLMeshFileLoader::goNextLine(io::IReadFile* file) const\r\n{\r\n\tuint8_t c;\r\n\t\/\/ look for newline characters\r\n\twhile(file->getPos() != file->getSize())\r\n\t{\r\n\t\tfile->read(&c, 1);\r\n\t\t\/\/ found it, so leave\r\n\t\tif (c=='\\n' || c=='\\r')\r\n\t\t\tbreak;\r\n\t}\r\n}\r\n\r\n} \/\/ end namespace scene\r\n} \/\/ end namespace irr\r\n\r\n\r\n#endif \/\/ _IRR_COMPILE_WITH_STL_LOADER_\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"leveldb\/c.h\"\n\n#include <stdlib.h>\n#include <unistd.h>\n#include \"leveldb\/cache.h\"\n#include \"leveldb\/comparator.h\"\n#include \"leveldb\/db.h\"\n#include \"leveldb\/env.h\"\n#include \"leveldb\/filter_policy.h\"\n#include \"leveldb\/iterator.h\"\n#include \"leveldb\/options.h\"\n#include \"leveldb\/status.h\"\n#include \"leveldb\/write_batch.h\"\n\nusing leveldb::Cache;\nusing leveldb::Comparator;\nusing leveldb::CompressionType;\nusing leveldb::DB;\nusing leveldb::Env;\nusing leveldb::FileLock;\nusing leveldb::FilterPolicy;\nusing leveldb::Iterator;\nusing leveldb::kMajorVersion;\nusing leveldb::kMinorVersion;\nusing leveldb::Logger;\nusing leveldb::NewBloomFilterPolicy;\nusing leveldb::NewLRUCache;\nusing leveldb::Options;\nusing leveldb::RandomAccessFile;\nusing leveldb::Range;\nusing leveldb::ReadOptions;\nusing leveldb::SequentialFile;\nusing leveldb::Slice;\nusing leveldb::Snapshot;\nusing leveldb::Status;\nusing leveldb::WritableFile;\nusing leveldb::WriteBatch;\nusing leveldb::WriteOptions;\n\nextern \"C\" {\n\nstruct leveldb_t { DB* rep; };\nstruct leveldb_iterator_t { Iterator* rep; };\nstruct leveldb_writebatch_t { WriteBatch rep; };\nstruct leveldb_snapshot_t { const Snapshot* rep; };\nstruct leveldb_readoptions_t { ReadOptions rep; };\nstruct leveldb_writeoptions_t { WriteOptions rep; };\nstruct leveldb_options_t { Options rep; };\nstruct leveldb_cache_t { Cache* rep; };\nstruct leveldb_seqfile_t { SequentialFile* rep; };\nstruct leveldb_randomfile_t { RandomAccessFile* rep; };\nstruct leveldb_writablefile_t { WritableFile* rep; };\nstruct leveldb_logger_t { Logger* rep; };\nstruct leveldb_filelock_t { FileLock* rep; };\n\nstruct leveldb_comparator_t : public Comparator {\n void* state_;\n void (*destructor_)(void*);\n int (*compare_)(\n void*,\n const char* a, size_t alen,\n const char* b, size_t blen);\n const char* (*name_)(void*);\n\n virtual ~leveldb_comparator_t() {\n (*destructor_)(state_);\n }\n\n virtual int Compare(const Slice& a, const Slice& b) const {\n return (*compare_)(state_, a.data(), a.size(), b.data(), b.size());\n }\n\n virtual const char* Name() const {\n return (*name_)(state_);\n }\n\n \/\/ No-ops since the C binding does not support key shortening methods.\n virtual void FindShortestSeparator(std::string*, const Slice&) const { }\n virtual void FindShortSuccessor(std::string* key) const { }\n};\n\nstruct leveldb_filterpolicy_t : public FilterPolicy {\n void* state_;\n void (*destructor_)(void*);\n const char* (*name_)(void*);\n char* (*create_)(\n void*,\n const char* const* key_array, const size_t* key_length_array,\n int num_keys,\n size_t* filter_length);\n unsigned char (*key_match_)(\n void*,\n const char* key, size_t length,\n const char* filter, size_t filter_length);\n\n virtual ~leveldb_filterpolicy_t() {\n (*destructor_)(state_);\n }\n\n virtual const char* Name() const {\n return (*name_)(state_);\n }\n\n virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const {\n std::vector<const char*> key_pointers(n);\n std::vector<size_t> key_sizes(n);\n for (int i = 0; i < n; i++) {\n key_pointers[i] = keys[i].data();\n key_sizes[i] = keys[i].size();\n }\n size_t len;\n char* filter = (*create_)(state_, &key_pointers[0], &key_sizes[0], n, &len);\n dst->append(filter, len);\n free(filter);\n }\n\n virtual bool KeyMayMatch(const Slice& key, const Slice& filter) const {\n return (*key_match_)(state_, key.data(), key.size(),\n filter.data(), filter.size());\n }\n};\n\nstruct leveldb_env_t {\n Env* rep;\n bool is_default;\n};\n\nstatic bool SaveError(char** errptr, const Status& s) {\n assert(errptr != NULL);\n if (s.ok()) {\n return false;\n } else if (*errptr == NULL) {\n *errptr = strdup(s.ToString().c_str());\n } else {\n \/\/ TODO(sanjay): Merge with existing error?\n free(*errptr);\n *errptr = strdup(s.ToString().c_str());\n }\n return true;\n}\n\nstatic char* CopyString(const std::string& str) {\n char* result = reinterpret_cast<char*>(malloc(sizeof(char) * str.size()));\n memcpy(result, str.data(), sizeof(char) * str.size());\n return result;\n}\n\nleveldb_t* leveldb_open(\n const leveldb_options_t* options,\n const char* name,\n char** errptr) {\n DB* db;\n if (SaveError(errptr, DB::Open(options->rep, std::string(name), &db))) {\n return NULL;\n }\n leveldb_t* result = new leveldb_t;\n result->rep = db;\n return result;\n}\n\nvoid leveldb_close(leveldb_t* db) {\n delete db->rep;\n delete db;\n}\n\nvoid leveldb_put(\n leveldb_t* db,\n const leveldb_writeoptions_t* options,\n const char* key, size_t keylen,\n const char* val, size_t vallen,\n char** errptr) {\n SaveError(errptr,\n db->rep->Put(options->rep, Slice(key, keylen), Slice(val, vallen)));\n}\n\nvoid leveldb_delete(\n leveldb_t* db,\n const leveldb_writeoptions_t* options,\n const char* key, size_t keylen,\n char** errptr) {\n SaveError(errptr, db->rep->Delete(options->rep, Slice(key, keylen)));\n}\n\n\nvoid leveldb_write(\n leveldb_t* db,\n const leveldb_writeoptions_t* options,\n leveldb_writebatch_t* batch,\n char** errptr) {\n SaveError(errptr, db->rep->Write(options->rep, &batch->rep));\n}\n\nchar* leveldb_get(\n leveldb_t* db,\n const leveldb_readoptions_t* options,\n const char* key, size_t keylen,\n size_t* vallen,\n char** errptr) {\n char* result = NULL;\n std::string tmp;\n Status s = db->rep->Get(options->rep, Slice(key, keylen), &tmp);\n if (s.ok()) {\n *vallen = tmp.size();\n result = CopyString(tmp);\n } else {\n *vallen = 0;\n if (!s.IsNotFound()) {\n SaveError(errptr, s);\n }\n }\n return result;\n}\n\nleveldb_iterator_t* leveldb_create_iterator(\n leveldb_t* db,\n const leveldb_readoptions_t* options) {\n leveldb_iterator_t* result = new leveldb_iterator_t;\n result->rep = db->rep->NewIterator(options->rep);\n return result;\n}\n\nconst leveldb_snapshot_t* leveldb_create_snapshot(\n leveldb_t* db) {\n leveldb_snapshot_t* result = new leveldb_snapshot_t;\n result->rep = db->rep->GetSnapshot();\n return result;\n}\n\nvoid leveldb_release_snapshot(\n leveldb_t* db,\n const leveldb_snapshot_t* snapshot) {\n db->rep->ReleaseSnapshot(snapshot->rep);\n delete snapshot;\n}\n\nchar* leveldb_property_value(\n leveldb_t* db,\n const char* propname) {\n std::string tmp;\n if (db->rep->GetProperty(Slice(propname), &tmp)) {\n \/\/ We use strdup() since we expect human readable output.\n return strdup(tmp.c_str());\n } else {\n return NULL;\n }\n}\n\nvoid leveldb_approximate_sizes(\n leveldb_t* db,\n int num_ranges,\n const char* const* range_start_key, const size_t* range_start_key_len,\n const char* const* range_limit_key, const size_t* range_limit_key_len,\n uint64_t* sizes) {\n Range* ranges = new Range[num_ranges];\n for (int i = 0; i < num_ranges; i++) {\n ranges[i].start = Slice(range_start_key[i], range_start_key_len[i]);\n ranges[i].limit = Slice(range_limit_key[i], range_limit_key_len[i]);\n }\n db->rep->GetApproximateSizes(ranges, num_ranges, sizes);\n delete[] ranges;\n}\n\nvoid leveldb_compact_range(\n leveldb_t* db,\n const char* start_key, size_t start_key_len,\n const char* limit_key, size_t limit_key_len) {\n Slice a, b;\n db->rep->CompactRange(\n \/\/ Pass NULL Slice if corresponding \"const char*\" is NULL\n (start_key ? (a = Slice(start_key, start_key_len), &a) : NULL),\n (limit_key ? (b = Slice(limit_key, limit_key_len), &b) : NULL));\n}\n\nvoid leveldb_destroy_db(\n const leveldb_options_t* options,\n const char* name,\n char** errptr) {\n SaveError(errptr, DestroyDB(name, options->rep));\n}\n\nvoid leveldb_repair_db(\n const leveldb_options_t* options,\n const char* name,\n char** errptr) {\n SaveError(errptr, RepairDB(name, options->rep));\n}\n\nvoid leveldb_iter_destroy(leveldb_iterator_t* iter) {\n delete iter->rep;\n delete iter;\n}\n\nunsigned char leveldb_iter_valid(const leveldb_iterator_t* iter) {\n return iter->rep->Valid();\n}\n\nvoid leveldb_iter_seek_to_first(leveldb_iterator_t* iter) {\n iter->rep->SeekToFirst();\n}\n\nvoid leveldb_iter_seek_to_last(leveldb_iterator_t* iter) {\n iter->rep->SeekToLast();\n}\n\nvoid leveldb_iter_seek(leveldb_iterator_t* iter, const char* k, size_t klen) {\n iter->rep->Seek(Slice(k, klen));\n}\n\nvoid leveldb_iter_next(leveldb_iterator_t* iter) {\n iter->rep->Next();\n}\n\nvoid leveldb_iter_prev(leveldb_iterator_t* iter) {\n iter->rep->Prev();\n}\n\nconst char* leveldb_iter_key(const leveldb_iterator_t* iter, size_t* klen) {\n Slice s = iter->rep->key();\n *klen = s.size();\n return s.data();\n}\n\nconst char* leveldb_iter_value(const leveldb_iterator_t* iter, size_t* vlen) {\n Slice s = iter->rep->value();\n *vlen = s.size();\n return s.data();\n}\n\nvoid leveldb_iter_get_error(const leveldb_iterator_t* iter, char** errptr) {\n SaveError(errptr, iter->rep->status());\n}\n\nleveldb_writebatch_t* leveldb_writebatch_create() {\n return new leveldb_writebatch_t;\n}\n\nvoid leveldb_writebatch_destroy(leveldb_writebatch_t* b) {\n delete b;\n}\n\nvoid leveldb_writebatch_clear(leveldb_writebatch_t* b) {\n b->rep.Clear();\n}\n\nvoid leveldb_writebatch_put(\n leveldb_writebatch_t* b,\n const char* key, size_t klen,\n const char* val, size_t vlen) {\n b->rep.Put(Slice(key, klen), Slice(val, vlen));\n}\n\nvoid leveldb_writebatch_delete(\n leveldb_writebatch_t* b,\n const char* key, size_t klen) {\n b->rep.Delete(Slice(key, klen));\n}\n\nvoid leveldb_writebatch_iterate(\n leveldb_writebatch_t* b,\n void* state,\n void (*put)(void*, const char* k, size_t klen, const char* v, size_t vlen),\n void (*deleted)(void*, const char* k, size_t klen)) {\n class H : public WriteBatch::Handler {\n public:\n void* state_;\n void (*put_)(void*, const char* k, size_t klen, const char* v, size_t vlen);\n void (*deleted_)(void*, const char* k, size_t klen);\n virtual void Put(const Slice& key, const Slice& value) {\n (*put_)(state_, key.data(), key.size(), value.data(), value.size());\n }\n virtual void Delete(const Slice& key) {\n (*deleted_)(state_, key.data(), key.size());\n }\n };\n H handler;\n handler.state_ = state;\n handler.put_ = put;\n handler.deleted_ = deleted;\n b->rep.Iterate(&handler);\n}\n\nleveldb_options_t* leveldb_options_create() {\n return new leveldb_options_t;\n}\n\nvoid leveldb_options_destroy(leveldb_options_t* options) {\n delete options;\n}\n\nvoid leveldb_options_set_comparator(\n leveldb_options_t* opt,\n leveldb_comparator_t* cmp) {\n opt->rep.comparator = cmp;\n}\n\nvoid leveldb_options_set_filter_policy(\n leveldb_options_t* opt,\n leveldb_filterpolicy_t* policy) {\n opt->rep.filter_policy = policy;\n}\n\nvoid leveldb_options_set_create_if_missing(\n leveldb_options_t* opt, unsigned char v) {\n opt->rep.create_if_missing = v;\n}\n\nvoid leveldb_options_set_error_if_exists(\n leveldb_options_t* opt, unsigned char v) {\n opt->rep.error_if_exists = v;\n}\n\nvoid leveldb_options_set_paranoid_checks(\n leveldb_options_t* opt, unsigned char v) {\n opt->rep.paranoid_checks = v;\n}\n\nvoid leveldb_options_set_env(leveldb_options_t* opt, leveldb_env_t* env) {\n opt->rep.env = (env ? env->rep : NULL);\n}\n\nvoid leveldb_options_set_info_log(leveldb_options_t* opt, leveldb_logger_t* l) {\n opt->rep.info_log = (l ? l->rep : NULL);\n}\n\nvoid leveldb_options_set_write_buffer_size(leveldb_options_t* opt, size_t s) {\n opt->rep.write_buffer_size = s;\n}\n\nvoid leveldb_options_set_max_open_files(leveldb_options_t* opt, int n) {\n opt->rep.max_open_files = n;\n}\n\nvoid leveldb_options_set_cache(leveldb_options_t* opt, leveldb_cache_t* c) {\n opt->rep.block_cache = c->rep;\n}\n\nvoid leveldb_options_set_block_size(leveldb_options_t* opt, size_t s) {\n opt->rep.block_size = s;\n}\n\nvoid leveldb_options_set_block_restart_interval(leveldb_options_t* opt, int n) {\n opt->rep.block_restart_interval = n;\n}\n\nvoid leveldb_options_set_compression(leveldb_options_t* opt, int t) {\n opt->rep.compression = static_cast<CompressionType>(t);\n}\n\nleveldb_comparator_t* leveldb_comparator_create(\n void* state,\n void (*destructor)(void*),\n int (*compare)(\n void*,\n const char* a, size_t alen,\n const char* b, size_t blen),\n const char* (*name)(void*)) {\n leveldb_comparator_t* result = new leveldb_comparator_t;\n result->state_ = state;\n result->destructor_ = destructor;\n result->compare_ = compare;\n result->name_ = name;\n return result;\n}\n\nvoid leveldb_comparator_destroy(leveldb_comparator_t* cmp) {\n delete cmp;\n}\n\nleveldb_filterpolicy_t* leveldb_filterpolicy_create(\n void* state,\n void (*destructor)(void*),\n char* (*create_filter)(\n void*,\n const char* const* key_array, const size_t* key_length_array,\n int num_keys,\n size_t* filter_length),\n unsigned char (*key_may_match)(\n void*,\n const char* key, size_t length,\n const char* filter, size_t filter_length),\n const char* (*name)(void*)) {\n leveldb_filterpolicy_t* result = new leveldb_filterpolicy_t;\n result->state_ = state;\n result->destructor_ = destructor;\n result->create_ = create_filter;\n result->key_match_ = key_may_match;\n result->name_ = name;\n return result;\n}\n\nvoid leveldb_filterpolicy_destroy(leveldb_filterpolicy_t* filter) {\n delete filter;\n}\n\nleveldb_filterpolicy_t* leveldb_filterpolicy_create_bloom(int bits_per_key) {\n \/\/ Make a leveldb_filterpolicy_t, but override all of its methods so\n \/\/ they delegate to a NewBloomFilterPolicy() instead of user\n \/\/ supplied C functions.\n struct Wrapper : public leveldb_filterpolicy_t {\n const FilterPolicy* rep_;\n ~Wrapper() { delete rep_; }\n const char* Name() const { return rep_->Name(); }\n void CreateFilter(const Slice* keys, int n, std::string* dst) const {\n return rep_->CreateFilter(keys, n, dst);\n }\n bool KeyMayMatch(const Slice& key, const Slice& filter) const {\n return rep_->KeyMayMatch(key, filter);\n }\n static void DoNothing(void*) { }\n };\n Wrapper* wrapper = new Wrapper;\n wrapper->rep_ = NewBloomFilterPolicy(bits_per_key);\n wrapper->state_ = NULL;\n wrapper->destructor_ = &Wrapper::DoNothing;\n return wrapper;\n}\n\nleveldb_readoptions_t* leveldb_readoptions_create() {\n return new leveldb_readoptions_t;\n}\n\nvoid leveldb_readoptions_destroy(leveldb_readoptions_t* opt) {\n delete opt;\n}\n\nvoid leveldb_readoptions_set_verify_checksums(\n leveldb_readoptions_t* opt,\n unsigned char v) {\n opt->rep.verify_checksums = v;\n}\n\nvoid leveldb_readoptions_set_fill_cache(\n leveldb_readoptions_t* opt, unsigned char v) {\n opt->rep.fill_cache = v;\n}\n\nvoid leveldb_readoptions_set_snapshot(\n leveldb_readoptions_t* opt,\n const leveldb_snapshot_t* snap) {\n opt->rep.snapshot = (snap ? snap->rep : NULL);\n}\n\nleveldb_writeoptions_t* leveldb_writeoptions_create() {\n return new leveldb_writeoptions_t;\n}\n\nvoid leveldb_writeoptions_destroy(leveldb_writeoptions_t* opt) {\n delete opt;\n}\n\nvoid leveldb_writeoptions_set_sync(\n leveldb_writeoptions_t* opt, unsigned char v) {\n opt->rep.sync = v;\n}\n\nleveldb_cache_t* leveldb_cache_create_lru(size_t capacity) {\n leveldb_cache_t* c = new leveldb_cache_t;\n c->rep = NewLRUCache(capacity);\n return c;\n}\n\nvoid leveldb_cache_destroy(leveldb_cache_t* cache) {\n delete cache->rep;\n delete cache;\n}\n\nleveldb_env_t* leveldb_create_default_env() {\n leveldb_env_t* result = new leveldb_env_t;\n result->rep = Env::Default();\n result->is_default = true;\n return result;\n}\n\nvoid leveldb_env_destroy(leveldb_env_t* env) {\n if (!env->is_default) delete env->rep;\n delete env;\n}\n\nvoid leveldb_free(void* ptr) {\n free(ptr);\n}\n\nint leveldb_major_version() {\n return kMajorVersion;\n}\n\nint leveldb_minor_version() {\n return kMinorVersion;\n}\n\n} \/\/ end extern \"C\"\n<commit_msg>Delete c.cc<commit_after><|endoftext|>"} {"text":"<commit_before>#include <yamail\/resource_pool\/async\/pool.hpp>\n\n#include <benchmark\/benchmark.h>\n\n#include <boost\/numeric\/conversion\/cast.hpp>\n\n#include <condition_variable>\n#include <iomanip>\n#include <random>\n#include <thread>\n\nnamespace {\n\nusing namespace yamail::resource_pool;\n\nstruct benchmark_args {\n std::size_t sequences;\n std::size_t threads;\n std::size_t resources;\n std::size_t queue_size;\n};\n\nstruct resource {};\n\nstruct context {\n boost::asio::io_context io_context;\n boost::asio::io_context::work work {io_context};\n std::atomic_bool stop {false};\n time_traits::duration timeout {std::chrono::milliseconds(100)};\n double recycle_probability {0};\n std::vector<std::chrono::steady_clock::duration> durations;\n std::condition_variable get_next;\n std::mutex get_next_mutex;\n std::unique_lock<std::mutex> get_next_lock {get_next_mutex};\n\n void wait_next() {\n get_next.wait(get_next_lock);\n }\n\n void allow_next() {\n get_next.notify_one();\n }\n\n void finish() {\n stop = true;\n io_context.stop();\n }\n};\n\nstruct callback {\n context& ctx;\n async::pool<resource>& pool;\n\n void operator ()(const boost::system::error_code& ec, async::pool<resource>::handle handle) {\n impl(ec, std::move(handle));\n if (!ctx.stop) {\n pool.get_auto_waste(ctx.io_context, *this, ctx.timeout);\n }\n ctx.allow_next();\n }\n\n void impl(const boost::system::error_code& ec, async::pool<resource>::handle handle) {\n static thread_local std::minstd_rand generator(std::hash<std::thread::id>()(std::this_thread::get_id()));\n static std::uniform_real_distribution<> distrubution(0, 1);\n static constexpr const double recycle_probability = 0.5;\n if (!ec) {\n if (handle.empty()) {\n handle.reset(resource {});\n }\n if (distrubution(generator) < recycle_probability) {\n handle.recycle();\n }\n }\n }\n};\n\nstruct io_context_post_callback {\n context& ctx;\n\n void operator ()() {\n if (!ctx.stop) {\n ctx.io_context.post(*this);\n }\n ctx.allow_next();\n }\n};\n\nstatic const std::vector<benchmark_args> benchmarks({\n {1, 1, 1, 0}, \/\/ 0\n {2, 1, 1, 1}, \/\/ 1\n {2, 1, 2, 0}, \/\/ 2\n {10, 1, 10, 0}, \/\/ 3\n {10, 1, 1, 9}, \/\/ 4\n {10, 1, 5, 5}, \/\/ 5\n {10, 1, 9, 1}, \/\/ 6\n {10, 2, 5, 5}, \/\/ 7\n {100, 1, 100, 0}, \/\/ 8\n {100, 1, 10, 90}, \/\/ 9\n {100, 1, 50, 50}, \/\/ 10\n {100, 1, 90, 10}, \/\/ 11\n {100, 2, 50, 50}, \/\/ 12\n {1000, 1, 10, 990}, \/\/ 13\n {1000, 2, 10, 990}, \/\/ 14\n {10000, 1, 10, 9990}, \/\/ 15\n {10000, 2, 10, 9990}, \/\/ 16\n});\n\nvoid get_auto_waste(benchmark::State& state) {\n const auto& args = benchmarks[boost::numeric_cast<std::size_t>(state.range(0))];\n context ctx;\n std::vector<std::thread> workers;\n for (std::size_t i = 0; i < args.threads; ++i) {\n workers.emplace_back(std::thread([&] { return ctx.io_context.run(); }));\n }\n async::pool<resource> pool(args.resources, args.queue_size);\n callback cb {ctx, pool};\n for (std::size_t i = 0; i < args.sequences; ++i) {\n pool.get_auto_waste(ctx.io_context, cb, ctx.timeout);\n }\n while (state.KeepRunning()) {\n ctx.wait_next();\n }\n ctx.finish();\n std::for_each(workers.begin(), workers.end(), std::mem_fn(&std::thread::join));\n}\n\nvoid all_benchmarks(benchmark::internal::Benchmark* b) {\n for (std::size_t n = 0; n < benchmarks.size(); ++n) {\n b->Arg(int(n));\n }\n}\n\n}\n\nBENCHMARK(get_auto_waste)->Apply(all_benchmarks);\n\nBENCHMARK_MAIN();\n<commit_msg>Fix benchmark for multiple threads<commit_after>#include <yamail\/resource_pool\/async\/pool.hpp>\n\n#include <benchmark\/benchmark.h>\n\n#include <boost\/numeric\/conversion\/cast.hpp>\n\n#include <atomic>\n#include <condition_variable>\n#include <iomanip>\n#include <random>\n#include <thread>\n\nnamespace {\n\nusing namespace yamail::resource_pool;\n\nstruct benchmark_args {\n std::size_t sequences;\n std::size_t threads;\n std::size_t resources;\n std::size_t queue_size;\n};\n\nstruct resource {};\n\nstruct context {\n boost::asio::io_context io_context;\n boost::asio::io_context::work work {io_context};\n std::atomic_bool stop {false};\n time_traits::duration timeout {std::chrono::milliseconds(100)};\n double recycle_probability {0};\n std::vector<std::chrono::steady_clock::duration> durations;\n std::condition_variable get_next;\n std::mutex get_next_mutex;\n std::unique_lock<std::mutex> get_next_lock {get_next_mutex};\n std::atomic<std::int64_t> ready_count {0};\n\n void wait_next() {\n if (--ready_count < 0) {\n get_next.wait(get_next_lock);\n }\n }\n\n void allow_next() {\n ++ready_count;\n get_next.notify_one();\n }\n\n void finish() {\n stop = true;\n io_context.stop();\n }\n};\n\nstruct callback {\n context& ctx;\n async::pool<resource>& pool;\n\n void operator ()(const boost::system::error_code& ec, async::pool<resource>::handle handle) {\n impl(ec, std::move(handle));\n if (!ctx.stop) {\n pool.get_auto_waste(ctx.io_context, *this, ctx.timeout);\n }\n ctx.allow_next();\n }\n\n void impl(const boost::system::error_code& ec, async::pool<resource>::handle handle) {\n static thread_local std::minstd_rand generator(std::hash<std::thread::id>()(std::this_thread::get_id()));\n static std::uniform_real_distribution<> distrubution(0, 1);\n static constexpr const double recycle_probability = 0.5;\n if (!ec) {\n if (handle.empty()) {\n handle.reset(resource {});\n }\n if (distrubution(generator) < recycle_probability) {\n handle.recycle();\n }\n }\n }\n};\n\nstruct io_context_post_callback {\n context& ctx;\n\n void operator ()() {\n if (!ctx.stop) {\n ctx.io_context.post(*this);\n }\n ctx.allow_next();\n }\n};\n\nstatic const std::vector<benchmark_args> benchmarks({\n {1, 1, 1, 0}, \/\/ 0\n {2, 1, 1, 1}, \/\/ 1\n {2, 1, 2, 0}, \/\/ 2\n {10, 1, 10, 0}, \/\/ 3\n {10, 1, 1, 9}, \/\/ 4\n {10, 1, 5, 5}, \/\/ 5\n {10, 1, 9, 1}, \/\/ 6\n {10, 2, 5, 5}, \/\/ 7\n {100, 1, 100, 0}, \/\/ 8\n {100, 1, 10, 90}, \/\/ 9\n {100, 1, 50, 50}, \/\/ 10\n {100, 1, 90, 10}, \/\/ 11\n {100, 2, 50, 50}, \/\/ 12\n {1000, 1, 10, 990}, \/\/ 13\n {1000, 2, 10, 990}, \/\/ 14\n {10000, 1, 10, 9990}, \/\/ 15\n {10000, 2, 10, 9990}, \/\/ 16\n});\n\nvoid get_auto_waste(benchmark::State& state) {\n const auto& args = benchmarks[boost::numeric_cast<std::size_t>(state.range(0))];\n context ctx;\n std::vector<std::thread> workers;\n for (std::size_t i = 0; i < args.threads; ++i) {\n workers.emplace_back(std::thread([&] { return ctx.io_context.run(); }));\n }\n async::pool<resource> pool(args.resources, args.queue_size);\n callback cb {ctx, pool};\n for (std::size_t i = 0; i < args.sequences; ++i) {\n pool.get_auto_waste(ctx.io_context, cb, ctx.timeout);\n }\n while (state.KeepRunning()) {\n ctx.wait_next();\n }\n ctx.finish();\n std::for_each(workers.begin(), workers.end(), std::mem_fn(&std::thread::join));\n}\n\nvoid all_benchmarks(benchmark::internal::Benchmark* b) {\n for (std::size_t n = 0; n < benchmarks.size(); ++n) {\n b->Arg(int(n));\n }\n}\n\n}\n\nBENCHMARK(get_auto_waste)->Apply(all_benchmarks);\n\nBENCHMARK_MAIN();\n<|endoftext|>"} {"text":"<commit_before>\/*===========================================================================*\n * This file is part of the BiCePS Linear Integer Solver (BLIS). *\n * *\n * BLIS is distributed under the Eclipse Public License as part of the *\n * COIN-OR repository (http:\/\/www.coin-or.org). *\n * *\n * Authors: *\n * *\n * Yan Xu, Lehigh University *\n * Ted Ralphs, Lehigh University *\n * *\n * Conceptual Design: *\n * *\n * Yan Xu, Lehigh University *\n * Ted Ralphs, Lehigh University *\n * Laszlo Ladanyi, IBM T.J. Watson Research Center *\n * Matthew Saltzman, Clemson University *\n * *\n * *\n * Copyright (C) 2001-2015, Lehigh University, Yan Xu, and Ted Ralphs. *\n * All Rights Reserved. *\n *===========================================================================*\/\n\n#include <iostream>\n\n#include \"CoinError.hpp\"\n#include \"CoinTime.hpp\"\n\n#include \"OsiConicSolverInterface.hpp\"\n#include \"OsiMosekSolverInterface.hpp\"\n#include \"OsiCplexSolverInterface.hpp\"\n#include \"ColaModel.hpp\"\n\/\/#ifdef COIN_HAS_CLP\n#include \"OsiClpSolverInterface.hpp\"\n\/\/#endif\n\n#include \"CglFlowCover.hpp\"\n#include \"CglGomory.hpp\"\n#include \"CglProbing.hpp\"\n#include \"CglKnapsackCover.hpp\"\n#include \"CglOddHole.hpp\"\n\n#include \"DcoConfig.hpp\"\n#include \"DcoModel.hpp\"\n\n#if COIN_HAS_MPI\n#include \"AlpsKnowledgeBrokerMPI.h\"\n#else\n#include \"AlpsKnowledgeBrokerSerial.h\"\n#endif\n\n\/\/ NOTE: gcc compiler doesn't recognize COIN_HAS_CLP, COIN_HAS_MPI\n\n\/\/#############################################################################\n\nint main(int argc, char *argv[])\n{\n\n\ttry{\n\t \/\/Set up lp solver\n\t \/\/ OsiConicSolverInterface * solver = new ColaModel();\n\t \/\/ solver.getModelPtr()->setDualBound(1.0e10);\n\t \/\/ solver.messageHandler()->setLogLevel(0);\n\n\t \/\/ if both mosek and cplex is available, choose mosek.\n\t \/\/ if both not available then choose cola\n#if defined(__OSI_MOSEK__)\n\t OsiConicSolverInterface * solver = new OsiMosekSolverInterface();\n#else\n#if defined(__OSI_CPLEX__)\n\t OsiConicSolverInterface * solver = new OsiCplexSolverInterface();\n#else\n#if defined(__COLA__)\n\t OsiConicSolverInterface * solver = new ColaModel();\n#endif\n#endif\n#endif\n\t \/\/ Create DisCO model\n\t DcoModel model;\n\t model.setSolver(solver);\n\n#ifdef COIN_HAS_MPI\n\t\tAlpsKnowledgeBrokerMPI broker(argc, argv, model);\n#else\n\t\tAlpsKnowledgeBrokerSerial broker(argc, argv, model);\n#endif\n\n\t\t\/\/ Search for best solution\n\t\tbroker.search(&model);\n\n\t\t\/\/ Report the best solution found and its ojective value\n\t\tbroker.printBestSolution();\n }\n\n\tcatch(CoinError& er) {\n \tstd::cerr << \"\\nDISCO ERROR: \\\"\" << er.message()\n\t\t << \"\\\"\"<< std::endl\n\t\t << \" from function \\\"\" << er.methodName()\n\t\t << \"\\\"\"<< std::endl\n\t\t << \" from class \\\"\" << er.className()\n\t\t << \"\\\"\" << std::endl;\n\t}\n catch(...) {\n\t\tstd::cerr << \"Something went wrong!\" << std::endl;\n }\n\n\n return 0;\n}\n\n\/\/#############################################################################\n\n<commit_msg>format update<commit_after>\/*===========================================================================*\n * This file is part of the BiCePS Linear Integer Solver (BLIS). *\n * *\n * BLIS is distributed under the Eclipse Public License as part of the *\n * COIN-OR repository (http:\/\/www.coin-or.org). *\n * *\n * Authors: *\n * *\n * Yan Xu, Lehigh University *\n * Ted Ralphs, Lehigh University *\n * *\n * Conceptual Design: *\n * *\n * Yan Xu, Lehigh University *\n * Ted Ralphs, Lehigh University *\n * Laszlo Ladanyi, IBM T.J. Watson Research Center *\n * Matthew Saltzman, Clemson University *\n * *\n * *\n * Copyright (C) 2001-2015, Lehigh University, Yan Xu, and Ted Ralphs. *\n * All Rights Reserved. *\n *===========================================================================*\/\n\n#include <iostream>\n\n#include \"CoinError.hpp\"\n#include \"CoinTime.hpp\"\n\n#include \"OsiConicSolverInterface.hpp\"\n#include \"OsiMosekSolverInterface.hpp\"\n#include \"OsiCplexSolverInterface.hpp\"\n#include \"ColaModel.hpp\"\n\/\/#ifdef COIN_HAS_CLP\n#include \"OsiClpSolverInterface.hpp\"\n\/\/#endif\n\n#include \"CglFlowCover.hpp\"\n#include \"CglGomory.hpp\"\n#include \"CglProbing.hpp\"\n#include \"CglKnapsackCover.hpp\"\n#include \"CglOddHole.hpp\"\n\n#include \"DcoConfig.hpp\"\n#include \"DcoModel.hpp\"\n\n#if COIN_HAS_MPI\n#include \"AlpsKnowledgeBrokerMPI.h\"\n#else\n#include \"AlpsKnowledgeBrokerSerial.h\"\n#endif\n\n\/\/ NOTE: gcc compiler doesn't recognize COIN_HAS_CLP, COIN_HAS_MPI\n\n\/\/#############################################################################\n\nint main(int argc, char *argv[]) {\n try {\n \/\/Set up lp solver\n \/\/ OsiConicSolverInterface * solver = new ColaModel();\n \/\/ solver.getModelPtr()->setDualBound(1.0e10);\n \/\/ solver.messageHandler()->setLogLevel(0);\n\n \/\/ if both mosek and cplex is available, choose mosek.\n \/\/ if both not available then choose cola\n#if defined(__OSI_MOSEK__)\n OsiConicSolverInterface * solver = new OsiMosekSolverInterface();\n#else\n#if defined(__OSI_CPLEX__)\n OsiConicSolverInterface * solver = new OsiCplexSolverInterface();\n#else\n#if defined(__COLA__)\n OsiConicSolverInterface * solver = new ColaModel();\n#endif\n#endif\n#endif\n \/\/ Create DisCO model\n DcoModel model;\n model.setSolver(solver);\n\n#ifdef COIN_HAS_MPI\n AlpsKnowledgeBrokerMPI broker(argc, argv, model);\n#else\n AlpsKnowledgeBrokerSerial broker(argc, argv, model);\n#endif\n \/\/ Search for best solution\n broker.search(&model);\n \/\/ Report the best solution found and its ojective value\n broker.printBestSolution();\n }\n catch(CoinError& er) {\n std::cerr << \"\\nDISCO ERROR: \\\"\" << er.message()\n\t << \"\\\"\"<< std::endl\n\t << \" from function \\\"\" << er.methodName()\n\t << \"\\\"\"<< std::endl\n\t << \" from class \\\"\" << er.className()\n\t << \"\\\"\" << std::endl;\n }\n catch(...) {\n std::cerr << \"Something went wrong!\" << std::endl;\n }\n return 0;\n}\n\/\/#############################################################################\n<|endoftext|>"} {"text":"<commit_before>\/\/ DepthOp.cpp\n\/*\n * Copyright (c) 2009, Dan Heeks\n * This program is released under the BSD license. See the file COPYING for\n * details.\n *\/\n\n#include \"stdafx.h\"\r\n#include \"DepthOp.h\"\n#include \"CNCConfig.h\"\r\n#include \"ProgramCanvas.h\"\r\n#include \"Program.h\"\r\n#include \"interface\/PropertyInt.h\"\r\n#include \"interface\/PropertyDouble.h\"\r\n#include \"interface\/PropertyLength.h\"\r\n#include \"tinyxml\/tinyxml.h\"\r\n#include \"interface\/Tool.h\"\r\n\nCDepthOpParams::CDepthOpParams()\n{\n\tm_tool_number = 0; \r\n\tm_tool_diameter = 0.0;\r\n\tm_clearance_height = 0.0;\r\n\tm_start_depth = 0.0;\r\n\tm_step_down = 0.0;\r\n\tm_final_depth = 0.0;\r\n\tm_rapid_down_to_height = 0.0;\r\n\tm_horizontal_feed_rate = 0.0;\r\n\tm_vertical_feed_rate = 0.0;\r\n\tm_spindle_speed = 0.0;\r\n}\n\nvoid CDepthOpParams::set_initial_values()\n{\n\tCNCConfig config;\n config.Read(_T(\"DepthFixtureOffset\"), &m_workplane,1);\n\tconfig.Read(_T(\"DepthOpToolNumber\"), &m_tool_number, 1);\r\n\tconfig.Read(_T(\"DepthOpToolDiameter\"), &m_tool_diameter, 3.0);\r\n\tconfig.Read(_T(\"DepthOpClearanceHeight\"), &m_clearance_height, 5.0);\r\n\tconfig.Read(_T(\"DepthOpStartDepth\"), &m_start_depth, 0.0);\r\n\tconfig.Read(_T(\"DepthOpStepDown\"), &m_step_down, 1.0);\r\n\tconfig.Read(_T(\"DepthOpFinalDepth\"), &m_final_depth, -1.0);\r\n\tconfig.Read(_T(\"DepthOpRapidDown\"), &m_rapid_down_to_height, 2.0);\r\n\tconfig.Read(_T(\"DepthOpHorizFeed\"), &m_horizontal_feed_rate, 100.0);\r\n\tconfig.Read(_T(\"DepthOpVertFeed\"), &m_vertical_feed_rate, 100.0);\r\n\tconfig.Read(_T(\"DepthOpSpindleSpeed\"), &m_spindle_speed, 7000);\r}\n\nvoid CDepthOpParams::write_values_to_config()\n{\n\tCNCConfig config;\n\tconfig.Write(_T(\"DepthFixtureOffset\"), m_workplane);\n\tconfig.Write(_T(\"DepthOpToolNumber\"), m_tool_number);\r\n\tconfig.Write(_T(\"DepthOpToolDiameter\"), m_tool_diameter);\r\n\tconfig.Write(_T(\"DepthOpClearanceHeight\"), m_clearance_height);\r\n\tconfig.Write(_T(\"DepthOpStartDepth\"), m_start_depth);\r\n\tconfig.Write(_T(\"DepthOpStepDown\"), m_step_down);\r\n\tconfig.Write(_T(\"DepthOpFinalDepth\"), m_final_depth);\r\n\tconfig.Write(_T(\"DepthOpRapidDown\"), m_rapid_down_to_height);\r\n\tconfig.Write(_T(\"DepthOpHorizFeed\"), m_horizontal_feed_rate);\r\n\tconfig.Write(_T(\"DepthOpVertFeed\"), m_vertical_feed_rate);\r\n\tconfig.Write(_T(\"DepthOpSpindleSpeed\"), m_spindle_speed);\r\n}\n\nstatic void on_set_workplane(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_workplane = value;}\nstatic void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;}\r\nstatic void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;}\r\nstatic void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;}\r\nstatic void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;}\r\nstatic void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;}\r\nstatic void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;}\r\nstatic void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;}\r\nstatic void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;}\r\nstatic void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;}\r\nstatic void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;}\r\n\nvoid CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list)\n{\n\tlist->push_back(new PropertyInt(_(\"fixture offset\"), m_workplane, parent, on_set_workplane));\n\tlist->push_back(new PropertyInt(_(\"tool number\"), m_tool_number, parent, on_set_tool_number));\r\n\tlist->push_back(new PropertyLength(_(\"tool diameter\"), m_tool_diameter, parent, on_set_tool_diameter));\r\n\tlist->push_back(new PropertyLength(_(\"clearance height\"), m_clearance_height, parent, on_set_clearance_height));\r\n\tlist->push_back(new PropertyLength(_(\"step down\"), m_step_down, parent, on_set_step_down));\r\n\tlist->push_back(new PropertyLength(_(\"start depth\"), m_start_depth, parent, on_set_start_depth));\r\n\tlist->push_back(new PropertyLength(_(\"final depth\"), m_final_depth, parent, on_set_final_depth));\r\n\tlist->push_back(new PropertyLength(_(\"rapid down to height\"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height));\r\n\tlist->push_back(new PropertyDouble(_(\"horizontal feed rate\"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate));\r\n\tlist->push_back(new PropertyDouble(_(\"vertical feed rate\"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate));\r\n\tlist->push_back(new PropertyDouble(_(\"spindle speed\"), m_spindle_speed, parent, on_set_spindle_speed));\r\n}\r\n\r\nvoid CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem)\n{\n\tTiXmlElement * element = new TiXmlElement( \"depthop\" );\r\n\tpElem->LinkEndChild( element ); \n\telement->SetAttribute(\"fixture offset\", m_workplane); \r\n\telement->SetAttribute(\"tooln\", m_tool_number);\r\n\telement->SetDoubleAttribute(\"toold\", m_tool_diameter);\r\n\telement->SetDoubleAttribute(\"clear\", m_clearance_height);\r\n\telement->SetDoubleAttribute(\"down\", m_step_down);\r\n\telement->SetDoubleAttribute(\"startdepth\", m_start_depth);\r\n\telement->SetDoubleAttribute(\"depth\", m_final_depth);\r\n\telement->SetDoubleAttribute(\"r\", m_rapid_down_to_height);\r\n\telement->SetDoubleAttribute(\"hfeed\", m_horizontal_feed_rate);\r\n\telement->SetDoubleAttribute(\"vfeed\", m_vertical_feed_rate);\r\n\telement->SetDoubleAttribute(\"spin\", m_spindle_speed);\n}\n\r\nvoid CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem)\n{\n\tTiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement(\"depthop\").Element();\r\n\tif(depthop)\n\t{\n\n\t\tdepthop->Attribute(\"fixture offset\", &m_workplane);\n\t\tdepthop->Attribute(\"tooln\", &m_tool_number);\r\n\t\tdepthop->Attribute(\"toold\", &m_tool_diameter);\r\n\t\tdepthop->Attribute(\"clear\", &m_clearance_height);\r\n\t\tdepthop->Attribute(\"down\", &m_step_down);\r\n\t\tdepthop->Attribute(\"startdepth\", &m_start_depth);\r\n\t\tdepthop->Attribute(\"depth\", &m_final_depth);\r\n\t\tdepthop->Attribute(\"r\", &m_rapid_down_to_height);\r\n\t\tdepthop->Attribute(\"hfeed\", &m_horizontal_feed_rate);\r\n\t\tdepthop->Attribute(\"vfeed\", &m_vertical_feed_rate);\r\n\t\tdepthop->Attribute(\"spin\", &m_spindle_speed);\n\t}\n}\n\nvoid CDepthOp::WriteBaseXML(TiXmlElement *element)\n{\n\tm_depth_op_params.WriteXMLAttributes(element);\r\n\tCOp::WriteBaseXML(element);\r\n}\n\r\nvoid CDepthOp::ReadBaseXML(TiXmlElement* element)\r\n{\n\tm_depth_op_params.ReadFromXMLElement(element);\n\tCOp::ReadBaseXML(element);\r\n}\n\r\nvoid CDepthOp::GetProperties(std::list<Property *> *list)\n{\n\tm_depth_op_params.GetProperties(this, list);\r\n\tCOp::GetProperties(list);\r\n}\r\n\nvoid CDepthOp::AppendTextToProgram()\n{\n\tCOp::AppendTextToProgram();\n\n\ttheApp.m_program_canvas->AppendText(_T(\"clearance = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"rapid_down_to_height = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"start_depth = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"step_down = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"final_depth = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"tool_diameter = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"spindle(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"feedrate_hv(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_horizontal_feed_rate);\n\ttheApp.m_program_canvas->AppendText(_T(\", \"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_vertical_feed_rate);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"tool_change(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"workplane(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_workplane);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"flush_nc()\\n\"));\n\n\n}\n\n<commit_msg>the xml file didn't like 'fixture offset'-changed to 'fixture_offset'<commit_after>\/\/ DepthOp.cpp\n\/*\n * Copyright (c) 2009, Dan Heeks\n * This program is released under the BSD license. See the file COPYING for\n * details.\n *\/\n\n#include \"stdafx.h\"\r\n#include \"DepthOp.h\"\n#include \"CNCConfig.h\"\r\n#include \"ProgramCanvas.h\"\r\n#include \"Program.h\"\r\n#include \"interface\/PropertyInt.h\"\r\n#include \"interface\/PropertyDouble.h\"\r\n#include \"interface\/PropertyLength.h\"\r\n#include \"tinyxml\/tinyxml.h\"\r\n#include \"interface\/Tool.h\"\r\n\nCDepthOpParams::CDepthOpParams()\n{\n\tm_tool_number = 0; \r\n\tm_tool_diameter = 0.0;\r\n\tm_clearance_height = 0.0;\r\n\tm_start_depth = 0.0;\r\n\tm_step_down = 0.0;\r\n\tm_final_depth = 0.0;\r\n\tm_rapid_down_to_height = 0.0;\r\n\tm_horizontal_feed_rate = 0.0;\r\n\tm_vertical_feed_rate = 0.0;\r\n\tm_spindle_speed = 0.0;\r\n}\n\nvoid CDepthOpParams::set_initial_values()\n{\n\tCNCConfig config;\n config.Read(_T(\"DepthFixtureOffset\"), &m_workplane,1);\n\tconfig.Read(_T(\"DepthOpToolNumber\"), &m_tool_number, 1);\r\n\tconfig.Read(_T(\"DepthOpToolDiameter\"), &m_tool_diameter, 3.0);\r\n\tconfig.Read(_T(\"DepthOpClearanceHeight\"), &m_clearance_height, 5.0);\r\n\tconfig.Read(_T(\"DepthOpStartDepth\"), &m_start_depth, 0.0);\r\n\tconfig.Read(_T(\"DepthOpStepDown\"), &m_step_down, 1.0);\r\n\tconfig.Read(_T(\"DepthOpFinalDepth\"), &m_final_depth, -1.0);\r\n\tconfig.Read(_T(\"DepthOpRapidDown\"), &m_rapid_down_to_height, 2.0);\r\n\tconfig.Read(_T(\"DepthOpHorizFeed\"), &m_horizontal_feed_rate, 100.0);\r\n\tconfig.Read(_T(\"DepthOpVertFeed\"), &m_vertical_feed_rate, 100.0);\r\n\tconfig.Read(_T(\"DepthOpSpindleSpeed\"), &m_spindle_speed, 7000);\r}\n\nvoid CDepthOpParams::write_values_to_config()\n{\n\tCNCConfig config;\n\tconfig.Write(_T(\"DepthFixtureOffset\"), m_workplane);\n\tconfig.Write(_T(\"DepthOpToolNumber\"), m_tool_number);\r\n\tconfig.Write(_T(\"DepthOpToolDiameter\"), m_tool_diameter);\r\n\tconfig.Write(_T(\"DepthOpClearanceHeight\"), m_clearance_height);\r\n\tconfig.Write(_T(\"DepthOpStartDepth\"), m_start_depth);\r\n\tconfig.Write(_T(\"DepthOpStepDown\"), m_step_down);\r\n\tconfig.Write(_T(\"DepthOpFinalDepth\"), m_final_depth);\r\n\tconfig.Write(_T(\"DepthOpRapidDown\"), m_rapid_down_to_height);\r\n\tconfig.Write(_T(\"DepthOpHorizFeed\"), m_horizontal_feed_rate);\r\n\tconfig.Write(_T(\"DepthOpVertFeed\"), m_vertical_feed_rate);\r\n\tconfig.Write(_T(\"DepthOpSpindleSpeed\"), m_spindle_speed);\r\n}\n\nstatic void on_set_workplane(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_workplane = value;}\nstatic void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;}\r\nstatic void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;}\r\nstatic void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;}\r\nstatic void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;}\r\nstatic void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;}\r\nstatic void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;}\r\nstatic void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;}\r\nstatic void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;}\r\nstatic void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;}\r\nstatic void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;}\r\n\nvoid CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list)\n{\n\tlist->push_back(new PropertyInt(_(\"fixture offset\"), m_workplane, parent, on_set_workplane));\n\tlist->push_back(new PropertyInt(_(\"tool number\"), m_tool_number, parent, on_set_tool_number));\r\n\tlist->push_back(new PropertyLength(_(\"tool diameter\"), m_tool_diameter, parent, on_set_tool_diameter));\r\n\tlist->push_back(new PropertyLength(_(\"clearance height\"), m_clearance_height, parent, on_set_clearance_height));\r\n\tlist->push_back(new PropertyLength(_(\"step down\"), m_step_down, parent, on_set_step_down));\r\n\tlist->push_back(new PropertyLength(_(\"start depth\"), m_start_depth, parent, on_set_start_depth));\r\n\tlist->push_back(new PropertyLength(_(\"final depth\"), m_final_depth, parent, on_set_final_depth));\r\n\tlist->push_back(new PropertyLength(_(\"rapid down to height\"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height));\r\n\tlist->push_back(new PropertyDouble(_(\"horizontal feed rate\"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate));\r\n\tlist->push_back(new PropertyDouble(_(\"vertical feed rate\"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate));\r\n\tlist->push_back(new PropertyDouble(_(\"spindle speed\"), m_spindle_speed, parent, on_set_spindle_speed));\r\n}\r\n\r\nvoid CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem)\n{\n\tTiXmlElement * element = new TiXmlElement( \"depthop\" );\r\n\tpElem->LinkEndChild( element ); \n\telement->SetAttribute(\"fixture_offset\", m_workplane); \r\n\telement->SetAttribute(\"tooln\", m_tool_number);\r\n\telement->SetDoubleAttribute(\"toold\", m_tool_diameter);\r\n\telement->SetDoubleAttribute(\"clear\", m_clearance_height);\r\n\telement->SetDoubleAttribute(\"down\", m_step_down);\r\n\telement->SetDoubleAttribute(\"startdepth\", m_start_depth);\r\n\telement->SetDoubleAttribute(\"depth\", m_final_depth);\r\n\telement->SetDoubleAttribute(\"r\", m_rapid_down_to_height);\r\n\telement->SetDoubleAttribute(\"hfeed\", m_horizontal_feed_rate);\r\n\telement->SetDoubleAttribute(\"vfeed\", m_vertical_feed_rate);\r\n\telement->SetDoubleAttribute(\"spin\", m_spindle_speed);\n}\n\r\nvoid CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem)\n{\n\tTiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement(\"depthop\").Element();\r\n\tif(depthop)\n\t{\n\n\t\tdepthop->Attribute(\"fixture offset\", &m_workplane);\n\t\tdepthop->Attribute(\"tooln\", &m_tool_number);\r\n\t\tdepthop->Attribute(\"toold\", &m_tool_diameter);\r\n\t\tdepthop->Attribute(\"clear\", &m_clearance_height);\r\n\t\tdepthop->Attribute(\"down\", &m_step_down);\r\n\t\tdepthop->Attribute(\"startdepth\", &m_start_depth);\r\n\t\tdepthop->Attribute(\"depth\", &m_final_depth);\r\n\t\tdepthop->Attribute(\"r\", &m_rapid_down_to_height);\r\n\t\tdepthop->Attribute(\"hfeed\", &m_horizontal_feed_rate);\r\n\t\tdepthop->Attribute(\"vfeed\", &m_vertical_feed_rate);\r\n\t\tdepthop->Attribute(\"spin\", &m_spindle_speed);\n\t}\n}\n\nvoid CDepthOp::WriteBaseXML(TiXmlElement *element)\n{\n\tm_depth_op_params.WriteXMLAttributes(element);\r\n\tCOp::WriteBaseXML(element);\r\n}\n\r\nvoid CDepthOp::ReadBaseXML(TiXmlElement* element)\r\n{\n\tm_depth_op_params.ReadFromXMLElement(element);\n\tCOp::ReadBaseXML(element);\r\n}\n\r\nvoid CDepthOp::GetProperties(std::list<Property *> *list)\n{\n\tm_depth_op_params.GetProperties(this, list);\r\n\tCOp::GetProperties(list);\r\n}\r\n\nvoid CDepthOp::AppendTextToProgram()\n{\n\tCOp::AppendTextToProgram();\n\n\ttheApp.m_program_canvas->AppendText(_T(\"clearance = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"rapid_down_to_height = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"start_depth = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"step_down = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"final_depth = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"tool_diameter = float(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter \/ theApp.m_program->m_units);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"spindle(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"feedrate_hv(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_horizontal_feed_rate);\n\ttheApp.m_program_canvas->AppendText(_T(\", \"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_vertical_feed_rate);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"tool_change(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"workplane(\"));\n\ttheApp.m_program_canvas->AppendText(m_depth_op_params.m_workplane);\n\ttheApp.m_program_canvas->AppendText(_T(\")\\n\"));\n\ttheApp.m_program_canvas->AppendText(_T(\"flush_nc()\\n\"));\n\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Austin on 6\/11\/2015.\n\/\/\n\n#include \"Display.hpp\"\n#include \"Processor.hpp\"\n#include \"MemoryManagementUnit.hpp\"\n\n#include <iostream>\n\nDisplay::Display() {\n Reset();\n}\n\n\/**\n * Initializes references to other Gameboy components\n *\/\nvoid Display::Initialize(Processor* cpu_, MemoryManagementUnit* mmu_) {\n cpu = cpu_;\n mmu = mmu_;\n}\n\nvoid Display::Reset() {\n\tframe = sf::Image();\n frame.create(160, 144);\n\n background = std::vector<sf::Color>(256*256, sf::Color::White);\n show_background = std::vector<bool>(256*256, false);\n\n window = std::vector<sf::Color>(256*256, sf::Color::White);\n show_window = std::vector<bool>(256*256, false);\n\n sprite_map = std::vector<sf::Color>(256*256, sf::Color::White);\n show_sprite = std::vector<bool>(256*256, false);\n}\n\n\/**\n * Returns the current frame for the GameBoy screen.\n *\/\nsf::Image Display::RenderFrame() {\n \/\/ Draw background onto frame, then add window and sprite\n uint8_t scroll_y = mmu->ReadByte(0xFF42);\n uint8_t scroll_x = mmu->ReadByte(0xFF43);\n\n for (int x = 0; x < 160; ++x) {\n int x_offset = scroll_x;\n if (x+x_offset >= 256) {\n x_offset -= 256;\n }\n for (int y = 0; y < 144; ++y) {\n int y_offset = scroll_y;\n if (y+y_offset >= 256) {\n y_offset -= 256;\n }\n if (show_background[(y+y_offset)*256+(x+x_offset)]) {\n frame.setPixel(x, y, background[(y+y_offset)*256+(x+x_offset)]);\n }\n }\n }\n\n \/\/ Draw Window now\n scroll_y = mmu->ReadByte(0xFF4A);\n scroll_x = mmu->ReadByte(0xFF4B);\n\n for (int x = 0; x < 160; ++x) {\n int x_offset = static_cast<int>(scroll_x)-7;\n for (int y = 0; y < 144; ++y) {\n int y_offset = scroll_y;\n if (x+x_offset >= 0 and x+x_offset < 256 and y+y_offset >= 0 and y+y_offset < 256) {\n if (show_window[(y+y_offset)*256+(x+x_offset)]) {\n frame.setPixel(x, y, window[(y+y_offset)*256+(x+x_offset)]);\n }\n }\n }\n }\n\n \/\/ Draw Sprites\n for (int x = 0; x < 160; ++x) {\n for (int y = 0; y < 144; ++y) {\n if (show_sprite[y*256 + x]) {\n frame.setPixel(x, y, sprite_map[y * 256 + x]);\n }\n }\n }\n\n \/\/ Reset frames\n show_background = std::vector<bool>(256*256, false);\n show_window = std::vector<bool>(256*256, false);\n\n return frame;\n}\n\n\/**\n * Renders the current scanline.\n *\/\nvoid Display::RenderScanline(uint8_t line_number) {\n \/\/ First draw background (if enabled)\n uint8_t lcd_control = mmu->zram[0xFF40&0xFF];\n if (lcd_control & 0x01) {\n DrawBackground(lcd_control, line_number);\n }\n\n \/\/ Then draw Window\n if ((lcd_control & 0x20) and (lcd_control & 0x01)) { \/\/ I believe both need to be set to draw Window\n DrawWindow(lcd_control, line_number);\n }\n\n \/\/ Finally draw Sprites\n if (lcd_control & 0x02) {\n DrawSprites(lcd_control, line_number);\n }\n}\n\n\/**\n * Updates Background vector for current scanline of background.\n *\/\nvoid Display::DrawBackground(uint8_t lcd_control, uint8_t line_number) {\n \/\/ Determine if using tile map 0 or 1\n uint16_t tile_map_address;\n if ((lcd_control & 0x08) == 0) {\n tile_map_address = 0x9800; \/\/ tile map #0\n } else {\n tile_map_address = 0x9c00; \/\/ tile map #1\n }\n\n \/\/ Determine if using tile set 0 or 1\n uint16_t tile_set_address;\n int tile_set_offset;\n if ((lcd_control & 0x10) == 0) {\n tile_set_address = 0x8800; \/\/ tile set #0\n tile_set_offset = -128;\n } else {\n tile_set_address = 0x8000; \/\/ tile set #1\n tile_set_offset = 0;\n }\n\n \/\/ Determine which tile row and line of tile to draw\n uint8_t row = static_cast<uint8_t>(std::floor(static_cast<double>(line_number) \/ 8.0));\n uint8_t tile_row = line_number % 8;\n for (std::size_t x = 0; x < 32; ++x) {\n uint8_t tile_number = mmu->ReadByte(tile_map_address + (32*row+x));\n uint16_t tile_address = tile_set_address - tile_set_offset + tile_number*16;\n\n DrawTilePattern(background, show_background, x, row, tile_row, tile_address);\n }\n}\n\n\/**\n * Updates frame buffer for current scanline of Window.\n *\/\nvoid Display::DrawWindow(uint8_t lcd_control, uint8_t line_number) {\n \/\/ Determine if using tile map 0 or 1\n uint16_t tile_map_address;\n if ((lcd_control & 0x40) == 0) {\n tile_map_address = 0x9800; \/\/ tile map #0\n } else {\n tile_map_address = 0x9c00; \/\/ tile map #1\n }\n\n \/\/ Determine if using tile set 0 or 1\n uint16_t tile_set_address;\n int tile_set_offset;\n if ((lcd_control & 0x10) == 0) {\n tile_set_address = 0x8800; \/\/ tile set #0\n tile_set_offset = -128;\n } else {\n tile_set_address = 0x8000; \/\/ tile set #1\n tile_set_offset = 0;\n }\n\n \/\/ Determine which tile row and line of tile to draw\n uint8_t row = static_cast<uint8_t>(std::floor(static_cast<double>(line_number) \/ 8.0));\n uint8_t tile_row = line_number % 8;\n for (std::size_t x = 0; x < 32; ++x) {\n uint8_t tile_number = mmu->ReadByte(tile_map_address + (32*row+x));\n uint16_t tile_address = tile_set_address - tile_set_offset + tile_number*16;\n\n DrawTilePattern(window, show_window, x, row, tile_row, tile_address);\n }\n}\n\nvoid Display::DrawSprites(uint8_t lcd_control, uint8_t line_number) {\n uint16_t oam_table_address = 0xFE00;\n uint16_t sprite_pattern_table = 0x8000; \/\/ Unsigned numbering\n\n uint8_t sprite_height = (lcd_control & 0x04)?16:8; \/\/ Height of each sprite in pixels\n\n \/\/ Iterate through all 40 sprites, drawing the first 10 on the current line_number\n \/\/std::cout << \"New draw\" << std::endl;\n std::vector<Sprite> sprites;\n for (int sprite = 0; sprite < 40; ++sprite) {\n \/\/ TODO: It's far more efficient to only read y_position and read the rest after determining if it's on the scanline\n \/\/ Each sprite is made up of 4 attributes\n uint8_t y_position = mmu->ReadByte(oam_table_address+sprite*4+0);\n uint8_t x_position = mmu->ReadByte(oam_table_address+sprite*4+1);\n uint8_t tile_number = mmu->ReadByte(oam_table_address+sprite*4+2);\n uint8_t attributes = mmu->ReadByte(oam_table_address+sprite*4+3);\n \/\/if (sprite == 0)\n \/\/ std::cout << \"Sprite number and tile number: \" << std::hex << static_cast<unsigned int>(sprite) << \", \" << static_cast<unsigned int>(tile_number) << \", at address: \" << static_cast<unsigned int>(oam_table_address+sprite*4+2) << std::endl;\n\n bool y_flip = (attributes & 0x40)?true:false;\n bool x_flip = (attributes & 0x20)?true:false;\n bool draw_priority = (attributes & 0x80)?true:false; \/\/ If true, don't draw over background\/window colors 1-3\n \/\/ TODO: Might need to create another bool vector for this\n uint8_t palette = (attributes & 0x10)?mmu->ReadByte(0xFF49):mmu->ReadByte(0xFF48); \/\/ Which palette to use\n\n \/\/ If on the scanline, add to sprites vector\n if (y_position >= line_number and y_position < line_number + sprite_height) {\n \/\/ Construct the sprite and add it to sprites\n Sprite new_sprite;\n new_sprite.x = x_position;\n new_sprite.y = y_position;\n new_sprite.tile_number = tile_number;\n new_sprite.attributes = attributes;\n new_sprite.x_flip = x_flip;\n new_sprite.y_flip = y_flip;\n new_sprite.draw_priority = draw_priority;\n new_sprite.palette = palette;\n new_sprite.height = sprite_height;\n\n sprites.push_back(new_sprite);\n }\n }\n\n \/\/ Sort each sprite by its x position (the lowest x position is drawn last)\n std::sort(sprites.begin(), sprites.end(),\n [](Sprite const& first, Sprite const& second) -> bool {\n return first.x < second.x;\n });\n\n \/\/ Draw the last 10 sprites\n \/\/std::cout << \"Start drawing\" << std::endl;\n for (int index = sprites.size()-1; (index > 0) and (index > sprites.size()-11); --index) {\n if (index < 0) break;\n\n uint16_t tile_address = sprite_pattern_table + sprites[index].tile_number*16;\n\n \/\/std::cout << \"Drawing sprites with tile number: \" << index << \", \" << std::hex << static_cast<unsigned int>(sprites[index].tile_number) << std::endl;\n DrawTilePattern(sprite_map, show_sprite, sprites[index].x, sprites[index].y, line_number - sprites[index].x, tile_address, true);\n }\n}\n\nvoid Display::DrawTilePattern(std::vector<sf::Color>& map, std::vector<bool>& show_map, std::size_t x, std::size_t y, std::size_t tile_x, uint16_t tile_address, bool is_sprite) {\n uint16_t line = tile_address + 2*tile_x;\n \/\/ A line is made up of two bytes\n uint8_t line_0 = mmu->ReadByte(line);\n uint8_t line_1 = mmu->ReadByte(line+1);\n for (int bit = 7; bit >= 0; --bit) {\n bool bit_0 = line_0 & (0x1<<bit);\n bool bit_1 = line_1 & (0x1<<bit);\n\n int color;\n if (!bit_1 and !bit_0) {\n color = 0;\n } else if (!bit_1 and bit_0) {\n color = 1;\n } else if (bit_1 and !bit_0) {\n color = 2;\n } else {\n color = 3;\n }\n\n \/\/ Create a palette conversion\n uint8_t palette = mmu->zram[0x47];\n sf::Color white;\n sf::Color light_gray;\n sf::Color dark_gray;\n sf::Color black;\n for (uint8_t bits = 0; bits < 7; bits+=2) {\n uint8_t bit0 = (palette & (1<<bits))>>bits;\n uint8_t bit1 = (palette & (1<<(bits+1)))>>(bits+1);\n uint8_t value = bit0 + (bit1 << 1);\n\n sf::Color new_color;\n if (value == 0x00) {\n new_color = kBlack;\n } else if (value == 0x01) {\n new_color = kDarkGray;\n } else if (value == 0x02) {\n new_color = kLightGray;\n } else if (value == 0x03) {\n new_color = kWhite;\n }\n\n if (bits == 0) {\n black = new_color;\n } else if (bits == 2) {\n dark_gray = new_color;\n } else if (bits == 4) {\n light_gray = new_color;\n } else if (bits == 6) {\n white = new_color;\n }\n }\n\n std::size_t x_pixel = x*8 + 7-bit;\n std::size_t y_pixel = (y*8+tile_x);\n if (color == 0) {\n map[y_pixel*256+x_pixel] = white;\n } else if (color == 1) {\n map[y_pixel*256+x_pixel] = light_gray;\n } else if (color == 2) {\n map[y_pixel*256+x_pixel] = dark_gray;\n } else {\n map[y_pixel*256+x_pixel] = black;\n }\n\n show_map[y_pixel*256+x_pixel] = true;\n }\n}<commit_msg>Add Sprite -8,-16 offset<commit_after>\/\/\n\/\/ Created by Austin on 6\/11\/2015.\n\/\/\n\n#include \"Display.hpp\"\n#include \"Processor.hpp\"\n#include \"MemoryManagementUnit.hpp\"\n\n#include <iostream>\n\nDisplay::Display() {\n Reset();\n}\n\n\/**\n * Initializes references to other Gameboy components\n *\/\nvoid Display::Initialize(Processor* cpu_, MemoryManagementUnit* mmu_) {\n cpu = cpu_;\n mmu = mmu_;\n}\n\nvoid Display::Reset() {\n\tframe = sf::Image();\n frame.create(160, 144);\n\n background = std::vector<sf::Color>(256*256, sf::Color::White);\n show_background = std::vector<bool>(256*256, false);\n\n window = std::vector<sf::Color>(256*256, sf::Color::White);\n show_window = std::vector<bool>(256*256, false);\n\n sprite_map = std::vector<sf::Color>(256*256, sf::Color::White);\n show_sprite = std::vector<bool>(256*256, false);\n}\n\n\/**\n * Returns the current frame for the GameBoy screen.\n *\/\nsf::Image Display::RenderFrame() {\n \/\/ Draw background onto frame, then add window and sprite\n uint8_t scroll_y = mmu->ReadByte(0xFF42);\n uint8_t scroll_x = mmu->ReadByte(0xFF43);\n\n for (int x = 0; x < 160; ++x) {\n int x_offset = scroll_x;\n if (x+x_offset >= 256) {\n x_offset -= 256;\n }\n for (int y = 0; y < 144; ++y) {\n int y_offset = scroll_y;\n if (y+y_offset >= 256) {\n y_offset -= 256;\n }\n if (show_background[(y+y_offset)*256+(x+x_offset)]) {\n frame.setPixel(x, y, background[(y+y_offset)*256+(x+x_offset)]);\n }\n }\n }\n\n \/\/ Draw Window now\n scroll_y = mmu->ReadByte(0xFF4A);\n scroll_x = mmu->ReadByte(0xFF4B);\n\n for (int x = 0; x < 160; ++x) {\n int x_offset = static_cast<int>(scroll_x)-7;\n for (int y = 0; y < 144; ++y) {\n int y_offset = scroll_y;\n if (x+x_offset >= 0 and x+x_offset < 256 and y+y_offset >= 0 and y+y_offset < 256) {\n if (show_window[(y+y_offset)*256+(x+x_offset)]) {\n frame.setPixel(x, y, window[(y+y_offset)*256+(x+x_offset)]);\n }\n }\n }\n }\n\n \/\/ Draw Sprites\n for (int x = 0; x < 160; ++x) {\n for (int y = 0; y < 144; ++y) {\n if (show_sprite[y*256 + x]) {\n frame.setPixel(x, y, sprite_map[y * 256 + x]);\n }\n }\n }\n\n \/\/ Reset frames\n show_background = std::vector<bool>(256*256, false);\n show_window = std::vector<bool>(256*256, false);\n\n return frame;\n}\n\n\/**\n * Renders the current scanline.\n *\/\nvoid Display::RenderScanline(uint8_t line_number) {\n \/\/ First draw background (if enabled)\n uint8_t lcd_control = mmu->zram[0xFF40&0xFF];\n if (lcd_control & 0x01) {\n DrawBackground(lcd_control, line_number);\n }\n\n \/\/ Then draw Window\n if ((lcd_control & 0x20) and (lcd_control & 0x01)) { \/\/ I believe both need to be set to draw Window\n DrawWindow(lcd_control, line_number);\n }\n\n \/\/ Finally draw Sprites\n if (lcd_control & 0x02) {\n DrawSprites(lcd_control, line_number);\n }\n}\n\n\/**\n * Updates Background vector for current scanline of background.\n *\/\nvoid Display::DrawBackground(uint8_t lcd_control, uint8_t line_number) {\n \/\/ Determine if using tile map 0 or 1\n uint16_t tile_map_address;\n if ((lcd_control & 0x08) == 0) {\n tile_map_address = 0x9800; \/\/ tile map #0\n } else {\n tile_map_address = 0x9c00; \/\/ tile map #1\n }\n\n \/\/ Determine if using tile set 0 or 1\n uint16_t tile_set_address;\n int tile_set_offset;\n if ((lcd_control & 0x10) == 0) {\n tile_set_address = 0x8800; \/\/ tile set #0\n tile_set_offset = -128;\n } else {\n tile_set_address = 0x8000; \/\/ tile set #1\n tile_set_offset = 0;\n }\n\n \/\/ Determine which tile row and line of tile to draw\n uint8_t row = static_cast<uint8_t>(std::floor(static_cast<double>(line_number) \/ 8.0));\n uint8_t tile_row = line_number % 8;\n for (std::size_t x = 0; x < 32; ++x) {\n uint8_t tile_number = mmu->ReadByte(tile_map_address + (32*row+x));\n uint16_t tile_address = tile_set_address - tile_set_offset + tile_number*16;\n\n DrawTilePattern(background, show_background, x, row, tile_row, tile_address);\n }\n}\n\n\/**\n * Updates frame buffer for current scanline of Window.\n *\/\nvoid Display::DrawWindow(uint8_t lcd_control, uint8_t line_number) {\n \/\/ Determine if using tile map 0 or 1\n uint16_t tile_map_address;\n if ((lcd_control & 0x40) == 0) {\n tile_map_address = 0x9800; \/\/ tile map #0\n } else {\n tile_map_address = 0x9c00; \/\/ tile map #1\n }\n\n \/\/ Determine if using tile set 0 or 1\n uint16_t tile_set_address;\n int tile_set_offset;\n if ((lcd_control & 0x10) == 0) {\n tile_set_address = 0x8800; \/\/ tile set #0\n tile_set_offset = -128;\n } else {\n tile_set_address = 0x8000; \/\/ tile set #1\n tile_set_offset = 0;\n }\n\n \/\/ Determine which tile row and line of tile to draw\n uint8_t row = static_cast<uint8_t>(std::floor(static_cast<double>(line_number) \/ 8.0));\n uint8_t tile_row = line_number % 8;\n for (std::size_t x = 0; x < 32; ++x) {\n uint8_t tile_number = mmu->ReadByte(tile_map_address + (32*row+x));\n uint16_t tile_address = tile_set_address - tile_set_offset + tile_number*16;\n\n DrawTilePattern(window, show_window, x, row, tile_row, tile_address);\n }\n}\n\nvoid Display::DrawSprites(uint8_t lcd_control, uint8_t line_number) {\n uint16_t oam_table_address = 0xFE00;\n uint16_t sprite_pattern_table = 0x8000; \/\/ Unsigned numbering\n\n uint8_t sprite_height = (lcd_control & 0x04)?16:8; \/\/ Height of each sprite in pixels\n\n \/\/ Iterate through all 40 sprites, drawing the first 10 on the current line_number\n \/\/std::cout << \"New draw\" << std::endl;\n std::vector<Sprite> sprites;\n for (int sprite = 0; sprite < 40; ++sprite) {\n \/\/ TODO: It's far more efficient to only read y_position and read the rest after determining if it's on the scanline\n \/\/ Each sprite is made up of 4 attributes\n uint8_t y_position = mmu->ReadByte(oam_table_address+sprite*4+0);\n uint8_t x_position = mmu->ReadByte(oam_table_address+sprite*4+1);\n uint8_t tile_number = mmu->ReadByte(oam_table_address+sprite*4+2);\n uint8_t attributes = mmu->ReadByte(oam_table_address+sprite*4+3);\n \/\/if (sprite == 0)\n \/\/ std::cout << \"Sprite number and tile number: \" << std::hex << static_cast<unsigned int>(sprite) << \", \" << static_cast<unsigned int>(tile_number) << \", at address: \" << static_cast<unsigned int>(oam_table_address+sprite*4+2) << std::endl;\n\n bool y_flip = (attributes & 0x40)?true:false;\n bool x_flip = (attributes & 0x20)?true:false;\n bool draw_priority = (attributes & 0x80)?true:false; \/\/ If true, don't draw over background\/window colors 1-3\n \/\/ TODO: Might need to create another bool vector for this\n uint8_t palette = (attributes & 0x10)?mmu->ReadByte(0xFF49):mmu->ReadByte(0xFF48); \/\/ Which palette to use\n\n \/\/ If on the scanline, add to sprites vector\n if (y_position <= line_number+16 and y_position+16 + sprite_height >= line_number) {\n \/\/ Construct the sprite and add it to sprites\n Sprite new_sprite;\n new_sprite.x = x_position;\n new_sprite.y = y_position;\n new_sprite.tile_number = tile_number;\n new_sprite.attributes = attributes;\n new_sprite.x_flip = x_flip;\n new_sprite.y_flip = y_flip;\n new_sprite.draw_priority = draw_priority;\n new_sprite.palette = palette;\n new_sprite.height = sprite_height;\n\n sprites.push_back(new_sprite);\n }\n }\n\n \/\/ Sort each sprite by its x position (the lowest x position is drawn last)\n std::sort(sprites.begin(), sprites.end(),\n [](Sprite const& first, Sprite const& second) -> bool {\n return first.x < second.x;\n });\n\n \/\/ Draw the last 10 sprites\n \/\/std::cout << \"Start drawing\" << std::endl;\n for (int index = sprites.size()-1; (index > 0) and (index > sprites.size()-11); --index) {\n if (index < 0) break;\n\n uint16_t tile_address = sprite_pattern_table + sprites[index].tile_number*16;\n\n \/\/std::cout << \"Drawing sprites with tile number: \" << index << \", \" << std::hex << static_cast<unsigned int>(sprites[index].tile_number) << std::endl;\n DrawTilePattern(sprite_map, show_sprite, sprites[index].x, sprites[index].y, line_number - sprites[index].y, tile_address, true);\n }\n}\n\nvoid Display::DrawTilePattern(std::vector<sf::Color>& map, std::vector<bool>& show_map, std::size_t x, std::size_t y, std::size_t tile_x, uint16_t tile_address, bool is_sprite) {\n uint16_t line = tile_address + 2*tile_x;\n \/\/ A line is made up of two bytes\n uint8_t line_0 = mmu->ReadByte(line);\n uint8_t line_1 = mmu->ReadByte(line+1);\n for (int bit = 7; bit >= 0; --bit) {\n bool bit_0 = line_0 & (0x1<<bit);\n bool bit_1 = line_1 & (0x1<<bit);\n\n int color;\n if (!bit_1 and !bit_0) {\n color = 0;\n } else if (!bit_1 and bit_0) {\n color = 1;\n } else if (bit_1 and !bit_0) {\n color = 2;\n } else {\n color = 3;\n }\n\n \/\/ Create a palette conversion\n uint8_t palette = mmu->zram[0x47];\n sf::Color white;\n sf::Color light_gray;\n sf::Color dark_gray;\n sf::Color black;\n for (uint8_t bits = 0; bits < 7; bits+=2) {\n uint8_t bit0 = (palette & (1<<bits))>>bits;\n uint8_t bit1 = (palette & (1<<(bits+1)))>>(bits+1);\n uint8_t value = bit0 + (bit1 << 1);\n\n sf::Color new_color;\n if (value == 0x00) {\n new_color = kBlack;\n } else if (value == 0x01) {\n new_color = kDarkGray;\n } else if (value == 0x02) {\n new_color = kLightGray;\n } else if (value == 0x03) {\n new_color = kWhite;\n }\n\n if (bits == 0) {\n black = new_color;\n } else if (bits == 2) {\n dark_gray = new_color;\n } else if (bits == 4) {\n light_gray = new_color;\n } else if (bits == 6) {\n white = new_color;\n }\n }\n\n \/\/ Todo: For sprites, don't render \"white\" pixels\n int x_pixel;\n int y_pixel;\n int destination;\n if (is_sprite) {\n x_pixel = (static_cast<int>(x)-8)*8 + 7-bit;\n y_pixel = (static_cast<int>(x)-16)*8+tile_x;\n destination = y_pixel*256+x_pixel;\n } else {\n x_pixel = x*8 + 7-bit;\n y_pixel = (y*8+tile_x);\n destination = y_pixel*256+x_pixel;\n }\n\n if (x_pixel >= 0 and x_pixel < 160 and y_pixel >= 0 and y_pixel < 144) {\n if (color == 0) {\n map[destination] = white;\n } else if (color == 1) {\n map[destination] = light_gray;\n } else if (color == 2) {\n map[destination] = dark_gray;\n } else {\n map[destination] = black;\n }\n\n show_map[destination] = true;\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ EigenJS.cpp\n\/\/ ~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#include <cstdlib>\n#include <ctime>\n\n#include \"Complex.hpp\"\n#include \"Matrix.hpp\"\n#include \"CMatrix.hpp\"\n\n#include \"Vector.hpp\"\n#include \"CVector.hpp\"\n\n#include \"RowVector.hpp\"\n#include \"CRowVector.hpp\"\n\nnamespace EigenJS {\n\nvoid Init(v8::Handle<v8::Object> exports) {\n std::srand(static_cast<unsigned int>(std::time(0)));\n std::rand();\n\n Complex<>::Init(exports);\n Matrix<>::Init(exports);\n CMatrix<>::Init(exports);\n\n Vector<>::Init(exports);\n CVector<>::Init(exports);\n\n RowVector<>::Init(exports);\n CRowVector<>::Init(exports);\n}\n\n} \/\/ namespace EigenJS\n\nNODE_MODULE(eigen, EigenJS::Init)\n<commit_msg>src: added 'Block'<commit_after>\/\/\n\/\/ EigenJS.cpp\n\/\/ ~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#include <cstdlib>\n#include <ctime>\n\n#include \"Complex.hpp\"\n#include \"Matrix.hpp\"\n#include \"CMatrix.hpp\"\n\n#include \"Vector.hpp\"\n#include \"CVector.hpp\"\n\n#include \"RowVector.hpp\"\n#include \"CRowVector.hpp\"\n\n#include \"Block.hpp\"\n\nnamespace EigenJS {\n\nvoid Init(v8::Handle<v8::Object> exports) {\n std::srand(static_cast<unsigned int>(std::time(0)));\n std::rand();\n\n Complex<>::Init(exports);\n Matrix<>::Init(exports);\n CMatrix<>::Init(exports);\n\n Vector<>::Init(exports);\n CVector<>::Init(exports);\n\n RowVector<>::Init(exports);\n CRowVector<>::Init(exports);\n\n Block<>::Init(exports);\n}\n\n} \/\/ namespace EigenJS\n\nNODE_MODULE(eigen, EigenJS::Init)\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program 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 General Public License for *\n* 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., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <sofa\/component\/init.h>\n#include <sofa\/core\/ObjectFactory.h>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\nusing std::string;\nusing namespace sofa::core;\nusing namespace sofa::core::objectmodel;\n\nstring make_link(ObjectFactory::Creator::SPtr creator) {\n const BaseClass* Class = creator->getClass();\n string str(Class->namespaceName + \"::\" + Class->className);\n size_t index;\n while ((index = str.find(\"::\", 0)) != string::npos)\n str.replace(index, 2, \"_1_1\");\n for (char c = 'A'; c <= 'Z' ; c++)\n while ((index = str.find(c, 0)) != string::npos)\n str.replace(index, 1, \"_\"+string(1, c-'A'+'a'));\n string link(string(creator->getTarget()) + \"\/class\" + str + \".html\");\n return \"<a href=\\\"..\/\" + link + \"\\\">\" + Class->className +\"<\/a>\";\n}\n\n\nvoid print(const std::string& s) {\n std::cout << s << std::endl;\n}\n\nint main()\n{\n sofa::component::init();\n std::vector<ObjectFactory::ClassEntry::SPtr> entries;\n ObjectFactory::getInstance()->getAllEntries(entries);\n print(\"\/**\");\n print(\" \\\\page component_list Component List\");\n print(\" <ul>\");\n for (size_t i = 0 ; i != entries.size() ; i++)\n if (!entries[i]->creatorMap.empty()) {\n const ObjectFactory::Creator::SPtr creator = entries[i]->creatorMap.begin()->second;\n print(\" <li>\" + make_link(creator) + \"<\/li>\");\n }\n print(\" <\/ul>\");\n print(\"*\/\");\n return 0;\n}\n<commit_msg>doxygen: minor fix<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program 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 General Public License for *\n* 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., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <SofaComponentMain\/init.h>\n#include <sofa\/core\/ObjectFactory.h>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\nusing std::string;\nusing namespace sofa::core;\nusing namespace sofa::core::objectmodel;\n\nstring make_link(ObjectFactory::Creator::SPtr creator) {\n const BaseClass* Class = creator->getClass();\n string str(Class->namespaceName + \"::\" + Class->className);\n size_t index;\n while ((index = str.find(\"::\", 0)) != string::npos)\n str.replace(index, 2, \"_1_1\");\n for (char c = 'A'; c <= 'Z' ; c++)\n while ((index = str.find(c, 0)) != string::npos)\n str.replace(index, 1, \"_\"+string(1, c-'A'+'a'));\n string link(string(creator->getTarget()) + \"\/class\" + str + \".html\");\n return \"<a href=\\\"..\/\" + link + \"\\\">\" + Class->className +\"<\/a>\";\n}\n\n\nvoid print(const std::string& s) {\n std::cout << s << std::endl;\n}\n\nint main()\n{\n sofa::component::init();\n std::vector<ObjectFactory::ClassEntry::SPtr> entries;\n ObjectFactory::getInstance()->getAllEntries(entries);\n print(\"\/**\");\n print(\" \\\\page component_list Component List\");\n print(\" <ul>\");\n for (size_t i = 0 ; i != entries.size() ; i++)\n if (!entries[i]->creatorMap.empty()) {\n const ObjectFactory::Creator::SPtr creator = entries[i]->creatorMap.begin()->second;\n print(\" <li>\" + make_link(creator) + \"<\/li>\");\n }\n print(\" <\/ul>\");\n print(\"*\/\");\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ BOSSA\n\/\/\n\/\/ Copyright (c) 2011-2018, ShumaTech\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 met:\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 the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the <organization> nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY 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\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <string>\n#include <exception>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#include \"Flasher.h\"\n\nusing namespace std;\n\nvoid\nFlasherInfo::print()\n{\n bool first;\n\n printf(\"Device : %s\\n\", name.c_str());\n printf(\"Version : %s\\n\", version.c_str());\n printf(\"Address : 0x%x\\n\", address);\n printf(\"Pages : %d\\n\", numPages);\n printf(\"Page Size : %d bytes\\n\", pageSize);\n printf(\"Total Size : %dKB\\n\", totalSize \/ 1024);\n printf(\"Planes : %d\\n\", numPlanes);\n printf(\"Lock Regions : %zd\\n\", lockRegions.size());\n printf(\"Locked : \");\n first = true;\n for (uint32_t region = 0; region < lockRegions.size(); region++)\n {\n if (lockRegions[region])\n {\n printf(\"%s%d\", first ? \"\" : \",\", region);\n first = false;\n }\n }\n printf(\"%s\\n\", first ? \"none\" : \"\");\n printf(\"Security : %s\\n\", security ? \"true\" : \"false\");\n if (canBootFlash)\n printf(\"Boot Flash : %s\\n\", bootFlash ? \"true\" : \"false\");\n if (canBod)\n printf(\"BOD : %s\\n\", bod ? \"true\" : \"false\");\n if (canBor)\n printf(\"BOR : %s\\n\", bor ? \"true\" : \"false\");\n}\n\nvoid\nFlasher::erase(uint32_t foffset)\n{\n _observer.onStatus(\"Erase flash\\n\");\n _flash->eraseAll(foffset);\n _flash->eraseAuto(false);\n}\n\nvoid\nFlasher::write(const char* filename, uint32_t foffset)\n{\n FILE* infile;\n uint32_t pageSize = _flash->pageSize();\n uint32_t pageNum = 0;\n uint32_t numPages;\n long fsize;\n size_t fbytes;\n\n if (foffset % pageSize != 0 || foffset >= _flash->totalSize())\n throw FlashOffsetError();\n \n infile = fopen(filename, \"rb\");\n if (!infile)\n throw FileOpenError(errno);\n\n try\n {\n if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0)\n throw FileIoError(errno);\n \n rewind(infile);\n\n numPages = (fsize + pageSize - 1) \/ pageSize;\n if (numPages > _flash->numPages())\n throw FileSizeError();\n\n _observer.onStatus(\"Write %ld bytes to flash (%u pages)\\n\", fsize, numPages);\n\n if (_samba.canWriteBuffer())\n {\n uint32_t offset = 0;\n uint32_t bufferSize = _samba.writeBufferSize();\n uint8_t buffer[bufferSize];\n \n while ((fbytes = fread(buffer, 1, bufferSize, infile)) > 0)\n {\n _observer.onProgress(offset \/ pageSize, numPages);\n \n if (fbytes < bufferSize)\n {\n memset(buffer + fbytes, 0, bufferSize - fbytes);\n fbytes = (fbytes + pageSize - 1) \/ pageSize * pageSize;\n }\n \n _flash->loadBuffer(buffer, fbytes);\n _flash->writeBuffer(foffset + offset, fbytes);\n offset += fbytes; \n }\n\n }\n else\n {\n uint8_t buffer[pageSize];\n uint32_t pageOffset = foffset \/ pageSize;\n\n while ((fbytes = fread(buffer, 1, pageSize, infile)) > 0)\n {\n _observer.onProgress(pageNum, numPages);\n\n _flash->loadBuffer(buffer, fbytes);\n _flash->writePage(pageOffset + pageNum);\n\n pageNum++;\n if (pageNum == numPages || fbytes != pageSize)\n break;\n }\n\n }\n }\n catch(...)\n {\n fclose(infile);\n throw;\n }\n \n fclose(infile);\n _observer.onProgress(numPages, numPages);\n}\n\nbool\nFlasher::verify(const char* filename, uint32_t& pageErrors, uint32_t& totalErrors, uint32_t foffset)\n{\n FILE* infile;\n uint32_t pageSize = _flash->pageSize();\n uint8_t bufferA[pageSize];\n uint8_t bufferB[pageSize];\n uint32_t pageNum = 0;\n uint32_t numPages;\n uint32_t pageOffset;\n uint32_t byteErrors = 0;\n uint16_t calcCrc = 0;\n uint16_t flashCrc;\n long fsize;\n size_t fbytes;\n\n pageErrors = 0;\n totalErrors = 0;\n\n if (foffset % pageSize != 0 || foffset >= _flash->totalSize())\n throw FlashOffsetError();\n \n pageOffset = foffset \/ pageSize;\n \n infile = fopen(filename, \"rb\");\n if (!infile)\n throw FileOpenError(errno);\n\n try\n {\n if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0)\n throw FileIoError(errno);\n \n rewind(infile);\n\n numPages = (fsize + pageSize - 1) \/ pageSize;\n if (numPages > _flash->numPages())\n throw FileSizeError();\n\n _observer.onStatus(\"Verify %ld bytes of flash\\n\", fsize);\n\n while ((fbytes = fread(bufferA, 1, pageSize, infile)) > 0)\n {\n byteErrors = 0;\n \n _observer.onProgress(pageNum, numPages);\n\n if (_samba.canChecksumBuffer())\n {\n for (uint32_t i = 0; i < fbytes; i++)\n calcCrc = _samba.checksumCalc(bufferA[i], calcCrc);\n \n flashCrc = _samba.checksumBuffer((pageOffset + pageNum) * pageSize, fbytes);\n \n if (flashCrc != calcCrc)\n {\n _flash->readPage(pageOffset + pageNum, bufferB);\n\n for (uint32_t i = 0; i < fbytes; i++)\n {\n if (bufferA[i] != bufferB[i])\n byteErrors++;\n }\n }\n }\n else\n {\n _flash->readPage(pageOffset + pageNum, bufferB);\n\n for (uint32_t i = 0; i < fbytes; i++)\n {\n if (bufferA[i] != bufferB[i])\n byteErrors++;\n }\n }\n \n if (byteErrors != 0)\n {\n pageErrors++;\n totalErrors += byteErrors;\n }\n\n pageNum++;\n if (pageNum == numPages || fbytes != pageSize)\n break;\n }\n }\n catch(...)\n {\n fclose(infile);\n throw;\n }\n \n fclose(infile);\n\n _observer.onProgress(numPages, numPages);\n \n if (pageErrors != 0)\n return false;\n\n return true;\n}\n\nvoid\nFlasher::read(const char* filename, uint32_t fsize, uint32_t foffset)\n{\n FILE* outfile;\n uint32_t pageSize = _flash->pageSize();\n uint8_t buffer[pageSize];\n uint32_t pageNum = 0;\n uint32_t pageOffset;\n uint32_t numPages;\n size_t fbytes;\n\n if (foffset % pageSize != 0 || foffset >= _flash->totalSize())\n throw FlashOffsetError();\n \n pageOffset = foffset \/ pageSize;\n\n if (fsize == 0)\n fsize = pageSize * (_flash->numPages() - pageOffset);\n\n numPages = (fsize + pageSize - 1) \/ pageSize;\n if (pageOffset + numPages > _flash->numPages())\n throw FileSizeError();\n \n outfile = fopen(filename, \"wb\");\n if (!outfile)\n throw FileOpenError(errno);\n \n _observer.onStatus(\"Read %d bytes from flash\\n\", fsize);\n \n try\n {\n for (pageNum = 0; pageNum < numPages; pageNum++)\n {\n _observer.onProgress(pageNum, numPages);\n\n _flash->readPage(pageOffset + pageNum, buffer);\n\n if (pageNum == numPages - 1 && fsize % pageSize > 0)\n pageSize = fsize % pageSize;\n fbytes = fwrite(buffer, 1, pageSize, outfile);\n if (fbytes != pageSize)\n throw FileShortError();\n }\n }\n catch(...)\n {\n fclose(outfile);\n throw;\n }\n \n _observer.onProgress(numPages, numPages);\n \n fclose(outfile);\n}\n\nvoid\nFlasher::lock(string& regionArg, bool enable)\n{\n if (regionArg.empty())\n {\n _observer.onStatus(\"%s all regions\\n\", enable ? \"Lock\" : \"Unlock\");\n std::vector<bool> regions(_flash->lockRegions(), enable);\n _flash->setLockRegions(regions);\n }\n else\n {\n size_t pos = 0;\n size_t delim;\n uint32_t region;\n string sub;\n std::vector<bool> regions = _flash->getLockRegions();\n\n do\n {\n delim = regionArg.find(',', pos);\n sub = regionArg.substr(pos, delim - pos);\n region = strtol(sub.c_str(), NULL, 0);\n _observer.onStatus(\"%s region %d\\n\", enable ? \"Lock\" : \"Unlock\", region);\n regions[region] = enable;\n pos = delim + 1;\n } while (delim != string::npos);\n\n _flash->setLockRegions(regions);\n }\n}\n\nvoid\nFlasher::info(FlasherInfo& info)\n{\n info.name = _flash->name();\n info.version = _samba.version();\n info.address = _flash->address();\n info.numPages = _flash->numPages();\n info.pageSize = _flash->pageSize();\n info.totalSize = _flash->numPages() * _flash->pageSize();\n info.numPlanes = _flash->numPlanes();\n info.security = _flash->getSecurity();\n info.bootFlash = _flash->getBootFlash();\n info.bod = _flash->getBod();\n info.bor = _flash->getBor();\n\n info.canBootFlash = _flash->canBootFlash();\n info.canBod = _flash->canBod();\n info.canBor = _flash->canBor();\n info.canChipErase = _samba.canChipErase();\n info.canWriteBuffer = _samba.canWriteBuffer();\n info.canChecksumBuffer = _samba.canChecksumBuffer();\n info.lockRegions = _flash->getLockRegions();\n}\n<commit_msg>Fix CRC calculation on verify for crc-capable bootloaders<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ BOSSA\n\/\/\n\/\/ Copyright (c) 2011-2018, ShumaTech\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 met:\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 the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the <organization> nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY 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\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <string>\n#include <exception>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#include \"Flasher.h\"\n\nusing namespace std;\n\nvoid\nFlasherInfo::print()\n{\n bool first;\n\n printf(\"Device : %s\\n\", name.c_str());\n printf(\"Version : %s\\n\", version.c_str());\n printf(\"Address : 0x%x\\n\", address);\n printf(\"Pages : %d\\n\", numPages);\n printf(\"Page Size : %d bytes\\n\", pageSize);\n printf(\"Total Size : %dKB\\n\", totalSize \/ 1024);\n printf(\"Planes : %d\\n\", numPlanes);\n printf(\"Lock Regions : %zd\\n\", lockRegions.size());\n printf(\"Locked : \");\n first = true;\n for (uint32_t region = 0; region < lockRegions.size(); region++)\n {\n if (lockRegions[region])\n {\n printf(\"%s%d\", first ? \"\" : \",\", region);\n first = false;\n }\n }\n printf(\"%s\\n\", first ? \"none\" : \"\");\n printf(\"Security : %s\\n\", security ? \"true\" : \"false\");\n if (canBootFlash)\n printf(\"Boot Flash : %s\\n\", bootFlash ? \"true\" : \"false\");\n if (canBod)\n printf(\"BOD : %s\\n\", bod ? \"true\" : \"false\");\n if (canBor)\n printf(\"BOR : %s\\n\", bor ? \"true\" : \"false\");\n}\n\nvoid\nFlasher::erase(uint32_t foffset)\n{\n _observer.onStatus(\"Erase flash\\n\");\n _flash->eraseAll(foffset);\n _flash->eraseAuto(false);\n}\n\nvoid\nFlasher::write(const char* filename, uint32_t foffset)\n{\n FILE* infile;\n uint32_t pageSize = _flash->pageSize();\n uint32_t pageNum = 0;\n uint32_t numPages;\n long fsize;\n size_t fbytes;\n\n if (foffset % pageSize != 0 || foffset >= _flash->totalSize())\n throw FlashOffsetError();\n \n infile = fopen(filename, \"rb\");\n if (!infile)\n throw FileOpenError(errno);\n\n try\n {\n if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0)\n throw FileIoError(errno);\n \n rewind(infile);\n\n numPages = (fsize + pageSize - 1) \/ pageSize;\n if (numPages > _flash->numPages())\n throw FileSizeError();\n\n _observer.onStatus(\"Write %ld bytes to flash (%u pages)\\n\", fsize, numPages);\n\n if (_samba.canWriteBuffer())\n {\n uint32_t offset = 0;\n uint32_t bufferSize = _samba.writeBufferSize();\n uint8_t buffer[bufferSize];\n \n while ((fbytes = fread(buffer, 1, bufferSize, infile)) > 0)\n {\n _observer.onProgress(offset \/ pageSize, numPages);\n \n if (fbytes < bufferSize)\n {\n memset(buffer + fbytes, 0, bufferSize - fbytes);\n fbytes = (fbytes + pageSize - 1) \/ pageSize * pageSize;\n }\n \n _flash->loadBuffer(buffer, fbytes);\n _flash->writeBuffer(foffset + offset, fbytes);\n offset += fbytes; \n }\n\n }\n else\n {\n uint8_t buffer[pageSize];\n uint32_t pageOffset = foffset \/ pageSize;\n\n while ((fbytes = fread(buffer, 1, pageSize, infile)) > 0)\n {\n _observer.onProgress(pageNum, numPages);\n\n _flash->loadBuffer(buffer, fbytes);\n _flash->writePage(pageOffset + pageNum);\n\n pageNum++;\n if (pageNum == numPages || fbytes != pageSize)\n break;\n }\n\n }\n }\n catch(...)\n {\n fclose(infile);\n throw;\n }\n \n fclose(infile);\n _observer.onProgress(numPages, numPages);\n}\n\nbool\nFlasher::verify(const char* filename, uint32_t& pageErrors, uint32_t& totalErrors, uint32_t foffset)\n{\n FILE* infile;\n uint32_t pageSize = _flash->pageSize();\n uint8_t bufferA[pageSize];\n uint8_t bufferB[pageSize];\n uint32_t pageNum = 0;\n uint32_t numPages;\n uint32_t pageOffset;\n uint32_t byteErrors = 0;\n uint16_t flashCrc;\n long fsize;\n size_t fbytes;\n\n pageErrors = 0;\n totalErrors = 0;\n\n if (foffset % pageSize != 0 || foffset >= _flash->totalSize())\n throw FlashOffsetError();\n \n pageOffset = foffset \/ pageSize;\n \n infile = fopen(filename, \"rb\");\n if (!infile)\n throw FileOpenError(errno);\n\n try\n {\n if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0)\n throw FileIoError(errno);\n \n rewind(infile);\n\n numPages = (fsize + pageSize - 1) \/ pageSize;\n if (numPages > _flash->numPages())\n throw FileSizeError();\n\n _observer.onStatus(\"Verify %ld bytes of flash\\n\", fsize);\n\n while ((fbytes = fread(bufferA, 1, pageSize, infile)) > 0)\n {\n byteErrors = 0;\n \n _observer.onProgress(pageNum, numPages);\n\n if (_samba.canChecksumBuffer())\n {\n uint16_t calcCrc = 0;\n for (uint32_t i = 0; i < fbytes; i++)\n calcCrc = _samba.checksumCalc(bufferA[i], calcCrc);\n \n flashCrc = _samba.checksumBuffer((pageOffset + pageNum) * pageSize, fbytes);\n \n if (flashCrc != calcCrc)\n {\n _flash->readPage(pageOffset + pageNum, bufferB);\n\n for (uint32_t i = 0; i < fbytes; i++)\n {\n if (bufferA[i] != bufferB[i])\n byteErrors++;\n }\n }\n }\n else\n {\n _flash->readPage(pageOffset + pageNum, bufferB);\n\n for (uint32_t i = 0; i < fbytes; i++)\n {\n if (bufferA[i] != bufferB[i])\n byteErrors++;\n }\n }\n \n if (byteErrors != 0)\n {\n pageErrors++;\n totalErrors += byteErrors;\n }\n\n pageNum++;\n if (pageNum == numPages || fbytes != pageSize)\n break;\n }\n }\n catch(...)\n {\n fclose(infile);\n throw;\n }\n \n fclose(infile);\n\n _observer.onProgress(numPages, numPages);\n \n if (pageErrors != 0)\n return false;\n\n return true;\n}\n\nvoid\nFlasher::read(const char* filename, uint32_t fsize, uint32_t foffset)\n{\n FILE* outfile;\n uint32_t pageSize = _flash->pageSize();\n uint8_t buffer[pageSize];\n uint32_t pageNum = 0;\n uint32_t pageOffset;\n uint32_t numPages;\n size_t fbytes;\n\n if (foffset % pageSize != 0 || foffset >= _flash->totalSize())\n throw FlashOffsetError();\n \n pageOffset = foffset \/ pageSize;\n\n if (fsize == 0)\n fsize = pageSize * (_flash->numPages() - pageOffset);\n\n numPages = (fsize + pageSize - 1) \/ pageSize;\n if (pageOffset + numPages > _flash->numPages())\n throw FileSizeError();\n \n outfile = fopen(filename, \"wb\");\n if (!outfile)\n throw FileOpenError(errno);\n \n _observer.onStatus(\"Read %d bytes from flash\\n\", fsize);\n \n try\n {\n for (pageNum = 0; pageNum < numPages; pageNum++)\n {\n _observer.onProgress(pageNum, numPages);\n\n _flash->readPage(pageOffset + pageNum, buffer);\n\n if (pageNum == numPages - 1 && fsize % pageSize > 0)\n pageSize = fsize % pageSize;\n fbytes = fwrite(buffer, 1, pageSize, outfile);\n if (fbytes != pageSize)\n throw FileShortError();\n }\n }\n catch(...)\n {\n fclose(outfile);\n throw;\n }\n \n _observer.onProgress(numPages, numPages);\n \n fclose(outfile);\n}\n\nvoid\nFlasher::lock(string& regionArg, bool enable)\n{\n if (regionArg.empty())\n {\n _observer.onStatus(\"%s all regions\\n\", enable ? \"Lock\" : \"Unlock\");\n std::vector<bool> regions(_flash->lockRegions(), enable);\n _flash->setLockRegions(regions);\n }\n else\n {\n size_t pos = 0;\n size_t delim;\n uint32_t region;\n string sub;\n std::vector<bool> regions = _flash->getLockRegions();\n\n do\n {\n delim = regionArg.find(',', pos);\n sub = regionArg.substr(pos, delim - pos);\n region = strtol(sub.c_str(), NULL, 0);\n _observer.onStatus(\"%s region %d\\n\", enable ? \"Lock\" : \"Unlock\", region);\n regions[region] = enable;\n pos = delim + 1;\n } while (delim != string::npos);\n\n _flash->setLockRegions(regions);\n }\n}\n\nvoid\nFlasher::info(FlasherInfo& info)\n{\n info.name = _flash->name();\n info.version = _samba.version();\n info.address = _flash->address();\n info.numPages = _flash->numPages();\n info.pageSize = _flash->pageSize();\n info.totalSize = _flash->numPages() * _flash->pageSize();\n info.numPlanes = _flash->numPlanes();\n info.security = _flash->getSecurity();\n info.bootFlash = _flash->getBootFlash();\n info.bod = _flash->getBod();\n info.bor = _flash->getBor();\n\n info.canBootFlash = _flash->canBootFlash();\n info.canBod = _flash->canBod();\n info.canBor = _flash->canBor();\n info.canChipErase = _samba.canChipErase();\n info.canWriteBuffer = _samba.canWriteBuffer();\n info.canChecksumBuffer = _samba.canChecksumBuffer();\n info.lockRegions = _flash->getLockRegions();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"common.h\"\n#include <string>\n\n#include <rtosc\/thread-link.h>\n\nvoid verify_msg(rtosc::msg_t read_msg, const char *portname, int value, const char *test_id, int line)\n{\n const std::string test_string = test_id;\n\n assert_str_eq(portname, read_msg, (test_string + \" (portname)\").c_str(), line);\n const char* arg_str = rtosc_argument_string(read_msg);\n assert_str_eq(\"i\", arg_str, (test_string + \" (arg type)\").c_str(), line);\n if(!strcmp(arg_str, \"i\"))\n assert_int_eq(value, rtosc_argument(read_msg, 0).i, (test_string + \" (arg value)\").c_str(), line);\n}\n\nvoid test_contiguous_write()\n{\n \/\/ max 4 messages of each 32 -> 128 bytes size\n rtosc::ThreadLink thread_link(32,4);\n char portname[] = \"abcdefghijklmnop\"; \/\/ length 16, array size 17\n rtosc::msg_t read_msg;\n\n \/\/ always write one message ahead, to check that a second message\n \/\/ does not corrupt the \"message under test\"\n thread_link.write(portname, \"i\", 42);\n\n \/\/ 10 rounds are enough to have 1 discontigous write\n for (int round = 0; round < 10; ++round)\n {\n \/\/ write 17 bytes + 3 bytes padding + 4 bytes argstr + 4 bytes args = 28 bytes\n thread_link.write(portname, \"i\", 42);\n read_msg = thread_link.read();\n\n char test_name [] = \"round 0\";\n test_name[6] += round % 10;\n verify_msg(read_msg, portname, 42, test_name, __LINE__);\n }\n}\n\nint main()\n{\n test_contiguous_write();\n\n return test_summary();\n}\n\n<commit_msg>thread_link_test: Augment contiguous write test<commit_after>#include \"common.h\"\n#include <string>\n\n#include <rtosc\/thread-link.h>\n\nvoid verify_msg(rtosc::msg_t read_msg, const char *portname, int value, const char *test_id, int line)\n{\n const std::string test_string = test_id;\n\n assert_str_eq(portname, read_msg, (test_string + \" (portname)\").c_str(), line);\n const char* arg_str = rtosc_argument_string(read_msg);\n assert_str_eq(\"i\", arg_str, (test_string + \" (arg type)\").c_str(), line);\n if(!strcmp(arg_str, \"i\"))\n assert_int_eq(value, rtosc_argument(read_msg, 0).i, (test_string + \" (arg value)\").c_str(), line);\n}\n\nvoid test_contiguous_write()\n{\n \/\/ max 4 messages of each 32 -> 128 bytes size\n rtosc::ThreadLink thread_link(32,4);\n char portname[] = \"abcdefghijklmnop\"; \/\/ length 16, array size 17\n rtosc::msg_t read_msg;\n\n \/\/ always write one message ahead, to check that a second message\n \/\/ does not corrupt the \"message under test\"\n thread_link.write(portname, \"i\", 42);\n\n \/\/ 10 rounds are enough to have 1 discontigous write\n for (int round = 0; round < 10; ++round)\n {\n \/\/ write 17 bytes + 3 bytes padding + 4 bytes argstr + 4 bytes args = 28 bytes\n thread_link.write(portname, \"i\", 43 + round);\n read_msg = thread_link.read();\n\n char test_name [] = \"round 0\";\n test_name[6] += round % 10;\n verify_msg(read_msg, portname, 42 + round, test_name, __LINE__);\n }\n}\n\nint main()\n{\n test_contiguous_write();\n\n return test_summary();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Petter Strandmark 2012.\n\n#include <cstring>\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <random>\n#include <stdexcept>\n\n#include <Eigen\/Dense>\n#include <Eigen\/Eigenvalues>\n#include <Eigen\/Sparse>\n\nextern \"C\" {\n\t#include \"matrix.h\"\n\t#include \"matrix2.h\"\n\t#undef min\n\t#undef max\n\t#undef catch\n\t#undef SPARSE\n}\n\n#include <spii\/spii.h>\n#include <spii\/solver.h>\n\nnamespace spii {\n\ntemplate<typename EigenMat>\nvoid Eigen_to_Meschach(const EigenMat& eigen_matrix, MAT* A)\n{\n\tint m = eigen_matrix.rows();\n\tint n = eigen_matrix.cols();\n\n\tfor (int i = 0; i < m; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tA->me[i][j] = eigen_matrix(i, j);\n\t\t}\n\t}\n}\n\nstruct FactorizationCacheInternal\n{\n\tPERM* pivot;\n\tPERM* block;\n\tMAT* Hmat;\n\tVEC* x;\n\tVEC* b;\n};\n\nFactorizationCache::FactorizationCache(int n)\n{\n\tauto cache = new FactorizationCacheInternal;\n\tcache->pivot = px_get(n);\n\tcache->block = px_get(n);\n\tcache->Hmat = m_get(n, n);\n\tcache->x = v_get(n);\n\tcache->b = v_get(n);\n\tthis->data = cache;\n}\n\nFactorizationCache::~FactorizationCache()\n{\n\tauto cache = reinterpret_cast<FactorizationCacheInternal*>(this->data);\n\tv_free(cache->b);\n\tv_free(cache->x);\n\tm_free(cache->Hmat);\n\tpx_free(cache->pivot);\n\tpx_free(cache->block);\n\tdelete cache;\n}\n\nvoid Solver::BKP_dense(const Eigen::MatrixXd& H,\n const Eigen::VectorXd& g,\n const FactorizationCache& cache_input,\n Eigen::VectorXd* p,\n SolverResults* results) const\n{\n\tusing namespace Eigen;\n\tdouble start_time = wall_time();\n\n\tauto cache = reinterpret_cast<FactorizationCacheInternal*>(cache_input.data);\n\tint n = H.rows();\n\n\tEigen_to_Meschach(H, cache->Hmat);\n\n\t\/\/m_foutput(stderr, cache->Hmat);\n\n\tBKPfactor(cache->Hmat, cache->pivot, cache->block);\n\n\t\/\/m_foutput(stderr, cache->Hmat);\n\n\tMatrixXd B(n, n);\n\tMatrixXd Q(n, n);\n\tVectorXd tau(n);\n\tVectorXd lambda(n);\n\tB.setZero();\n\tQ.setZero();\n\n\tSelfAdjointEigenSolver<MatrixXd> eigensolver;\n\n\tdouble delta = 1e-12;\n\n\tint onebyone;\n\tfor (int i = 0; i < n; i = onebyone ? i+1 : i+2 ) {\n\t\tonebyone = ( cache->block->pe[i] == i );\n\t\tif ( onebyone ) {\n\t\t B(i, i) = m_entry(cache->Hmat, i, i);\n\t\t\tlambda(i) = B(i, i);\n\t\t\tif (lambda(i) >= delta) {\n\t\t\t\ttau(i) = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttau(i) = delta - (1.0 + delta) * lambda(i);\n\t\t\t}\n\t\t\tQ(i, i) = 1;\n\t\t}\n\t\telse {\n\t\t auto a11 = m_entry(cache->Hmat, i, i);\n\t\t auto a22 = m_entry(cache->Hmat, i+1, i+1);\n\t\t auto a12 = m_entry(cache->Hmat, i+1, i);\n\t\t\tB(i, i) = a11;\n\t\t\tB(i+1, i) = a12;\n\t\t\tB(i, i+1) = a12;\n\t\t\tB(i+1, i+1) = a22;\n\t\t\teigensolver.compute(B.block(i, i, 2, 2));\n\n\t\t\tlambda(i) = eigensolver.eigenvalues()(0);\n\t\t\tlambda(i+1) = eigensolver.eigenvalues()(1);\n\t\t\tfor (int k = i; k <= i + 1; ++k) {\n\t\t\t\tif (lambda(k) >= delta) {\n\t\t\t\t\ttau(k) = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttau(k) = delta - (1.0 + delta) * lambda(k);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tQ.block(i, i, 2, 2) = eigensolver.eigenvectors();\n\t\t}\n\t}\n\n\t\/\/std::cerr << \"B = \\n\" << B << \"\\n\\n\";\n\t\/\/std::cerr << \"F = \\n\" << Q * tau.asDiagonal() * Q.transpose() << \"\\n\\n\";\n\n\tB = B + Q * tau.asDiagonal() * Q.transpose();\n\n\t\/\/std::cerr << \"B = \\n\" << B << \"\\n\\n\";\n\n\tfor (int i = 0; i < n; i = onebyone ? i+1 : i+2 ) {\n\t\tonebyone = ( cache->block->pe[i] == i );\n\t\tif ( onebyone ) {\n\t\t m_entry(cache->Hmat, i, i) = B(i, i);\n\t\t}\n\t\telse {\n\t\t m_entry(cache->Hmat, i, i) = B(i, i);\n\t\t m_entry(cache->Hmat, i+1, i+1) = B(i+1, i+1);\n\t\t m_entry(cache->Hmat, i+1, i) = B(i+1, i);\n\t\t\tm_entry(cache->Hmat, i, i+1) = B(i, i+1);\n\t\t}\n\t}\n\n\tresults->matrix_factorization_time += wall_time() - start_time;\n\tstart_time = wall_time();\n\n\t\/\/m_foutput(stderr, cache->Hmat);\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tcache->b->ve[i] = -g(i);\n\t}\n\tBKPsolve(cache->Hmat, cache->pivot, cache->block, cache->b, cache->x);\n\tfor (int i = 0; i < n; ++i) {\n\t\t(*p)(i) = cache->x->ve[i];\n\t}\n\n\tresults->linear_solver_time += wall_time() - start_time;\n\tstart_time = wall_time();\n\n\tresults->matrix_factorization_time += wall_time() - start_time;\n}\n\n} \/\/ namespace spii\n<commit_msg>FactorizationCache without reinterpret_cast.<commit_after>\/\/ Petter Strandmark 2012.\n\n#include <cstring>\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <random>\n#include <stdexcept>\n\n#include <Eigen\/Dense>\n#include <Eigen\/Eigenvalues>\n#include <Eigen\/Sparse>\n\nextern \"C\" {\n\t#include \"matrix.h\"\n\t#include \"matrix2.h\"\n\t#undef min\n\t#undef max\n\t#undef catch\n\t#undef SPARSE\n}\n\n#include <spii\/spii.h>\n#include <spii\/solver.h>\n\nnamespace spii {\n\ntemplate<typename EigenMat>\nvoid Eigen_to_Meschach(const EigenMat& eigen_matrix, MAT* A)\n{\n\tint m = eigen_matrix.rows();\n\tint n = eigen_matrix.cols();\n\n\tfor (int i = 0; i < m; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tA->me[i][j] = eigen_matrix(i, j);\n\t\t}\n\t}\n}\n\nstruct FactorizationCacheInternal\n{\n\tPERM* pivot;\n\tPERM* block;\n\tMAT* Hmat;\n\tVEC* x;\n\tVEC* b;\n};\n\nFactorizationCache::FactorizationCache(int n)\n{\n\tauto cache = new FactorizationCacheInternal;\n\tcache->pivot = px_get(n);\n\tcache->block = px_get(n);\n\tcache->Hmat = m_get(n, n);\n\tcache->x = v_get(n);\n\tcache->b = v_get(n);\n\tthis->data = cache;\n}\n\nFactorizationCache::~FactorizationCache()\n{\n\tv_free(this->data->b);\n\tv_free(this->data->x);\n\tm_free(this->data->Hmat);\n\tpx_free(this->data->pivot);\n\tpx_free(this->data->block);\n\tdelete this->data;\n}\n\nvoid Solver::BKP_dense(const Eigen::MatrixXd& H,\n const Eigen::VectorXd& g,\n const FactorizationCache& cache_input,\n Eigen::VectorXd* p,\n SolverResults* results) const\n{\n\tusing namespace Eigen;\n\tdouble start_time = wall_time();\n\n\tauto cache = reinterpret_cast<FactorizationCacheInternal*>(cache_input.data);\n\tint n = H.rows();\n\n\tEigen_to_Meschach(H, cache->Hmat);\n\n\t\/\/m_foutput(stderr, cache->Hmat);\n\n\tBKPfactor(cache->Hmat, cache->pivot, cache->block);\n\n\t\/\/m_foutput(stderr, cache->Hmat);\n\n\tMatrixXd B(n, n);\n\tMatrixXd Q(n, n);\n\tVectorXd tau(n);\n\tVectorXd lambda(n);\n\tB.setZero();\n\tQ.setZero();\n\n\tSelfAdjointEigenSolver<MatrixXd> eigensolver;\n\n\tdouble delta = 1e-12;\n\n\tint onebyone;\n\tfor (int i = 0; i < n; i = onebyone ? i+1 : i+2 ) {\n\t\tonebyone = ( cache->block->pe[i] == i );\n\t\tif ( onebyone ) {\n\t\t B(i, i) = m_entry(cache->Hmat, i, i);\n\t\t\tlambda(i) = B(i, i);\n\t\t\tif (lambda(i) >= delta) {\n\t\t\t\ttau(i) = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttau(i) = delta - (1.0 + delta) * lambda(i);\n\t\t\t}\n\t\t\tQ(i, i) = 1;\n\t\t}\n\t\telse {\n\t\t auto a11 = m_entry(cache->Hmat, i, i);\n\t\t auto a22 = m_entry(cache->Hmat, i+1, i+1);\n\t\t auto a12 = m_entry(cache->Hmat, i+1, i);\n\t\t\tB(i, i) = a11;\n\t\t\tB(i+1, i) = a12;\n\t\t\tB(i, i+1) = a12;\n\t\t\tB(i+1, i+1) = a22;\n\t\t\teigensolver.compute(B.block(i, i, 2, 2));\n\n\t\t\tlambda(i) = eigensolver.eigenvalues()(0);\n\t\t\tlambda(i+1) = eigensolver.eigenvalues()(1);\n\t\t\tfor (int k = i; k <= i + 1; ++k) {\n\t\t\t\tif (lambda(k) >= delta) {\n\t\t\t\t\ttau(k) = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttau(k) = delta - (1.0 + delta) * lambda(k);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tQ.block(i, i, 2, 2) = eigensolver.eigenvectors();\n\t\t}\n\t}\n\n\t\/\/std::cerr << \"B = \\n\" << B << \"\\n\\n\";\n\t\/\/std::cerr << \"F = \\n\" << Q * tau.asDiagonal() * Q.transpose() << \"\\n\\n\";\n\n\tB = B + Q * tau.asDiagonal() * Q.transpose();\n\n\t\/\/std::cerr << \"B = \\n\" << B << \"\\n\\n\";\n\n\tfor (int i = 0; i < n; i = onebyone ? i+1 : i+2 ) {\n\t\tonebyone = ( cache->block->pe[i] == i );\n\t\tif ( onebyone ) {\n\t\t m_entry(cache->Hmat, i, i) = B(i, i);\n\t\t}\n\t\telse {\n\t\t m_entry(cache->Hmat, i, i) = B(i, i);\n\t\t m_entry(cache->Hmat, i+1, i+1) = B(i+1, i+1);\n\t\t m_entry(cache->Hmat, i+1, i) = B(i+1, i);\n\t\t\tm_entry(cache->Hmat, i, i+1) = B(i, i+1);\n\t\t}\n\t}\n\n\tresults->matrix_factorization_time += wall_time() - start_time;\n\tstart_time = wall_time();\n\n\t\/\/m_foutput(stderr, cache->Hmat);\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tcache->b->ve[i] = -g(i);\n\t}\n\tBKPsolve(cache->Hmat, cache->pivot, cache->block, cache->b, cache->x);\n\tfor (int i = 0; i < n; ++i) {\n\t\t(*p)(i) = cache->x->ve[i];\n\t}\n\n\tresults->linear_solver_time += wall_time() - start_time;\n\tstart_time = wall_time();\n\n\tresults->matrix_factorization_time += wall_time() - start_time;\n}\n\n} \/\/ namespace spii\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/gtest.h\"\n#include \"common.hpp\"\n\n#include <iostream>\n#include <ostream>\n\/\/ (Pending abstraction of threading interface)\n#include <arbor\/version.hpp>\n\n#include \"threading\/threading.hpp\"\n#include \"threading\/enumerable_thread_specific.hpp\"\n\nusing namespace arb::threading::impl;\nusing namespace arb::threading;\nusing namespace arb;\nnamespace {\n\nstd::atomic<int> nmove{0};\nstd::atomic<int> ncopy{0};\n\nvoid reset() {\n nmove = 0;\n ncopy = 0;\n}\n\nstruct ftor {\n\n ftor() {}\n\n ftor(ftor&& other) {\n ++nmove;\n }\n\n ftor(const ftor& other) {\n ++ncopy;\n }\n\n void operator()() const {}\n};\n\nstruct ftor_wait {\n int duration_us = 100;\n\n ftor_wait() {}\n ftor_wait(int us): duration_us(us) {}\n\n void operator()() const {\n auto duration = std::chrono::microseconds(duration_us);\n std::this_thread::sleep_for(duration);\n }\n};\n\nstruct ftor_parallel_wait {\n\n ftor_parallel_wait(task_system* ts): ts{ts} {}\n\n void operator()() const {\n auto nthreads = ts->get_num_threads();\n auto duration = std::chrono::microseconds(100);\n parallel_for::apply(0, nthreads, ts, [=](int i){ std::this_thread::sleep_for(duration);});\n }\n\n task_system* ts;\n};\n\n}\n\nTEST(task_system, test_copy) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n\n ftor f;\n ts.async(f, 0);\n\n \/\/ Copy into new ftor and move ftor into a task (std::function<void()>)\n EXPECT_EQ(1, nmove);\n EXPECT_EQ(1, ncopy);\n reset();\n }\n}\n\nTEST(task_system, test_move) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n\n ftor f;\n ts.async(std::move(f), 0);\n\n \/\/ Move into new ftor and move ftor into a task (std::function<void()>)\n EXPECT_LE(nmove, 2);\n EXPECT_LE(ncopy, 1);\n reset();\n }\n}\n\nTEST(notification_queue, test_copy) {\n notification_queue q;\n\n ftor f;\n q.push({task(f), 0});\n\n \/\/ Copy into new ftor and move ftor into a task (std::function<void()>)\n EXPECT_EQ(1, nmove);\n EXPECT_EQ(1, ncopy);\n reset();\n}\n\nTEST(notification_queue, test_move) {\n notification_queue q;\n\n ftor f;\n\n \/\/ Move into new ftor and move ftor into a task (std::function<void()>)\n q.push({task(std::move(f)), 1});\n EXPECT_LE(nmove, 2);\n EXPECT_LE(ncopy, 1);\n reset();\n}\n\nTEST(task_group, test_copy) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n task_group g(&ts);\n\n ftor f;\n g.run(f);\n g.wait();\n\n \/\/ Copy into \"wrap\" and move wrap into a task (std::function<void()>)\n EXPECT_EQ(1, nmove);\n EXPECT_EQ(1, ncopy);\n reset();\n }\n}\n\nTEST(task_group, test_move) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n task_group g(&ts);\n\n ftor f;\n g.run(std::move(f));\n g.wait();\n\n \/\/ Move into wrap and move wrap into a task (std::function<void()>)\n EXPECT_LE(nmove, 2);\n EXPECT_LE(ncopy, 1);\n reset();\n }\n}\n\nTEST(task_group, individual_tasks) {\n \/\/ Simple check for deadlock\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n task_group g(&ts);\n\n ftor_wait f;\n for (int i = 0; i < 32 * nthreads; i++) {\n g.run(f);\n }\n g.wait();\n }\n}\n\nTEST(task_group, parallel_for_sleep) {\n \/\/ Simple check for deadlock for nested parallelism\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n task_group g(&ts);\n\n ftor_parallel_wait f(&ts);\n for (int i = 0; i < nthreads; i++) {\n g.run(f);\n }\n g.wait();\n }\n}\n\nTEST(task_group, parallel_for) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n for (int n = 0; n < 10000; n = !n ? 1 : 2 * n) {\n std::vector<int> v(n, -1);\n parallel_for::apply(0, n, &ts, [&](int i) { v[i] = i; });\n for (int i = 0; i < n; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n}\n\n\nTEST(task_group, manual_nested_parallel_for) {\n \/\/ Check for deadlock or stack overflow\n const int ntasks = 100000;\n {\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n std::vector<int> v(ntasks);\n task_system ts(nthreads);\n\n auto nested = [&](int j) {\n task_group g1(&ts);\n g1.run([&](){v[j] = j;});\n g1.wait();\n };\n\n task_group g0(&ts);\n for (int i = 0; i < ntasks; i++) {\n g0.run([=](){nested(i);});\n }\n g0.wait();\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n {\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n std::vector<int> v(ntasks);\n task_system ts(nthreads);\n\n auto double_nested = [&](int i) {\n task_group g2(&ts);\n g2.run([&](){v[i] = i;});\n g2.wait();\n };\n\n auto nested = [&](int i) {\n task_group g1(&ts);\n g1.run([=](){double_nested(i);});\n g1.wait();\n };\n\n task_group g0(&ts);\n for (int i = 0; i < ntasks; i++) {\n g0.run([=](){nested(i);});\n }\n g0.wait();\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n}\n\nTEST(task_group, nested_parallel_for) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n for (int m = 1; m < 512; m *= 2) {\n for (int n = 0; n < 1000; n = !n ? 1 : 2 * n) {\n std::vector<std::vector<int>> v(n, std::vector<int>(m, -1));\n parallel_for::apply(0, n, &ts, [&](int i) {\n auto& w = v[i];\n parallel_for::apply(0, m, &ts, [&](int j) { w[j] = i + j; });\n });\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n EXPECT_EQ(i + j, v[i][j]);\n }\n }\n }\n }\n }\n}\n\nTEST(task_group, multi_nested_parallel_for) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n for (int m = 1; m < 512; m *= 2) {\n for (int n = 0; n < 128; n = !n ? 1 : 2 * n) {\n for (int p = 0; p < 16; p = !p ? 1 : 2 * p) {\n std::vector<std::vector<std::vector<int>>> v(n, std::vector<std::vector<int>>(m, std::vector<int>(p, -1)));\n parallel_for::apply(0, n, &ts, [&](int i) {\n auto& w = v[i];\n parallel_for::apply(0, m, &ts, [&](int j) {\n auto& u = w[j];\n parallel_for::apply(0, p, &ts, [&](int k) {\n u[k] = i + j + k;\n });\n });\n });\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n for (int k = 0; k < p; k++) {\n EXPECT_EQ(i + j + k, v[i][j][k]);\n }\n }\n }\n }\n }\n }\n }\n}\n\nTEST(task_group, nested_parallel_for_unbalanced) {\n \/\/ Top level parallel for has many more tasks than lower level\n const int ntasks = 100000;\n {\n \/\/ Default batching\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, ntasks, &ts, [&](int i) {\n parallel_for::apply(0, 1, &ts, [&](int j) { v[i] = i; });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n \/\/ 128 tasks per batch\n const int batch_size = 128;\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, ntasks, batch_size, &ts, [&](int i) {\n parallel_for::apply(0, 1, batch_size, &ts, [&](int j) { v[i] = i; });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n \/\/ lower level parallel for has many more tasks than top level\n {\n \/\/ Default batching\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, 1, &ts, [&](int i) {\n parallel_for::apply(0, ntasks, &ts, [&](int j) { v[j] = j; });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n \/\/ 128 tasks per batch\n const int batch_size = 128;\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, 1, batch_size, &ts, [&](int i) {\n parallel_for::apply(0, ntasks, batch_size, &ts, [&](int j) { v[j] = j; });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n}\n\nTEST(task_group, multi_nested_parallel_for_unbalanced) {\n \/\/ Top level parallel for has many more tasks than lower level\n const int ntasks = 100000;\n for (int nthreads = 1; nthreads < 20; nthreads*=4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, ntasks, &ts, [&](int i) {\n parallel_for::apply(0, 1, &ts, [&](int j) {\n parallel_for::apply(0, 1, &ts, [&](int k) {\n v[i] = i;\n });\n });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n \/\/ lower level parallel for has many more tasks than top level\n for (int nthreads = 1; nthreads < 20; nthreads*=4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, 1, &ts, [&](int i) {\n parallel_for::apply(0, 1, &ts, [&](int j) {\n parallel_for::apply(0, ntasks, &ts, [&](int k) {\n v[k] = k;\n });\n });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n}\n\nTEST(enumerable_thread_specific, test) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system_handle ts = task_system_handle(new task_system(nthreads));\n enumerable_thread_specific<int> buffers(ts);\n task_group g(ts.get());\n\n for (int i = 0; i < 100000; i++) {\n g.run([&]() {\n auto& buf = buffers.local();\n buf++;\n });\n }\n g.wait();\n\n int sum = 0;\n for (auto b: buffers) {\n sum += b;\n }\n\n EXPECT_EQ(100000, sum);\n }\n}\n<commit_msg>remove checks for move ctor when it could be elided (#1899)<commit_after>#include \"..\/gtest.h\"\n#include \"common.hpp\"\n\n#include <iostream>\n#include <ostream>\n\/\/ (Pending abstraction of threading interface)\n#include <arbor\/version.hpp>\n\n#include \"threading\/threading.hpp\"\n#include \"threading\/enumerable_thread_specific.hpp\"\n\nusing namespace arb::threading::impl;\nusing namespace arb::threading;\nusing namespace arb;\nnamespace {\n\nstd::atomic<int> nmove{0};\nstd::atomic<int> ncopy{0};\n\nvoid reset() {\n nmove = 0;\n ncopy = 0;\n}\n\nstruct ftor {\n\n ftor() {}\n\n ftor(ftor&& other) {\n ++nmove;\n }\n\n ftor(const ftor& other) {\n ++ncopy;\n }\n\n void operator()() const {}\n};\n\nstruct ftor_wait {\n int duration_us = 100;\n\n ftor_wait() {}\n ftor_wait(int us): duration_us(us) {}\n\n void operator()() const {\n auto duration = std::chrono::microseconds(duration_us);\n std::this_thread::sleep_for(duration);\n }\n};\n\nstruct ftor_parallel_wait {\n\n ftor_parallel_wait(task_system* ts): ts{ts} {}\n\n void operator()() const {\n auto nthreads = ts->get_num_threads();\n auto duration = std::chrono::microseconds(100);\n parallel_for::apply(0, nthreads, ts, [=](int i){ std::this_thread::sleep_for(duration);});\n }\n\n task_system* ts;\n};\n\n}\n\nTEST(task_system, test_copy) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n\n ftor f;\n ts.async(f, 0);\n\n \/\/ Copy into new ftor and move ftor into a task (std::function<void()>)\n \/\/ move ctor is elided with some compilers\n \/\/EXPECT_EQ(1, nmove);\n EXPECT_EQ(1, ncopy);\n reset();\n }\n}\n\nTEST(task_system, test_move) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n\n ftor f;\n ts.async(std::move(f), 0);\n\n \/\/ Move into new ftor and move ftor into a task (std::function<void()>)\n EXPECT_LE(nmove, 2);\n EXPECT_LE(ncopy, 1);\n reset();\n }\n}\n\nTEST(notification_queue, test_copy) {\n notification_queue q;\n\n ftor f;\n q.push({task(f), 0});\n\n \/\/ Copy into new ftor and move ftor into a task (std::function<void()>)\n \/\/ move ctor is elided with some compilers\n \/\/EXPECT_EQ(1, nmove);\n EXPECT_EQ(1, ncopy);\n reset();\n}\n\nTEST(notification_queue, test_move) {\n notification_queue q;\n\n ftor f;\n\n \/\/ Move into new ftor and move ftor into a task (std::function<void()>)\n q.push({task(std::move(f)), 1});\n EXPECT_LE(nmove, 2);\n EXPECT_LE(ncopy, 1);\n reset();\n}\n\nTEST(task_group, test_copy) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n task_group g(&ts);\n\n ftor f;\n g.run(f);\n g.wait();\n\n \/\/ Copy into \"wrap\" and move wrap into a task (std::function<void()>)\n EXPECT_EQ(1, nmove);\n EXPECT_EQ(1, ncopy);\n reset();\n }\n}\n\nTEST(task_group, test_move) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n task_group g(&ts);\n\n ftor f;\n g.run(std::move(f));\n g.wait();\n\n \/\/ Move into wrap and move wrap into a task (std::function<void()>)\n EXPECT_LE(nmove, 2);\n EXPECT_LE(ncopy, 1);\n reset();\n }\n}\n\nTEST(task_group, individual_tasks) {\n \/\/ Simple check for deadlock\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n task_group g(&ts);\n\n ftor_wait f;\n for (int i = 0; i < 32 * nthreads; i++) {\n g.run(f);\n }\n g.wait();\n }\n}\n\nTEST(task_group, parallel_for_sleep) {\n \/\/ Simple check for deadlock for nested parallelism\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n task_group g(&ts);\n\n ftor_parallel_wait f(&ts);\n for (int i = 0; i < nthreads; i++) {\n g.run(f);\n }\n g.wait();\n }\n}\n\nTEST(task_group, parallel_for) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n for (int n = 0; n < 10000; n = !n ? 1 : 2 * n) {\n std::vector<int> v(n, -1);\n parallel_for::apply(0, n, &ts, [&](int i) { v[i] = i; });\n for (int i = 0; i < n; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n}\n\n\nTEST(task_group, manual_nested_parallel_for) {\n \/\/ Check for deadlock or stack overflow\n const int ntasks = 100000;\n {\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n std::vector<int> v(ntasks);\n task_system ts(nthreads);\n\n auto nested = [&](int j) {\n task_group g1(&ts);\n g1.run([&](){v[j] = j;});\n g1.wait();\n };\n\n task_group g0(&ts);\n for (int i = 0; i < ntasks; i++) {\n g0.run([=](){nested(i);});\n }\n g0.wait();\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n {\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n std::vector<int> v(ntasks);\n task_system ts(nthreads);\n\n auto double_nested = [&](int i) {\n task_group g2(&ts);\n g2.run([&](){v[i] = i;});\n g2.wait();\n };\n\n auto nested = [&](int i) {\n task_group g1(&ts);\n g1.run([=](){double_nested(i);});\n g1.wait();\n };\n\n task_group g0(&ts);\n for (int i = 0; i < ntasks; i++) {\n g0.run([=](){nested(i);});\n }\n g0.wait();\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n}\n\nTEST(task_group, nested_parallel_for) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n for (int m = 1; m < 512; m *= 2) {\n for (int n = 0; n < 1000; n = !n ? 1 : 2 * n) {\n std::vector<std::vector<int>> v(n, std::vector<int>(m, -1));\n parallel_for::apply(0, n, &ts, [&](int i) {\n auto& w = v[i];\n parallel_for::apply(0, m, &ts, [&](int j) { w[j] = i + j; });\n });\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n EXPECT_EQ(i + j, v[i][j]);\n }\n }\n }\n }\n }\n}\n\nTEST(task_group, multi_nested_parallel_for) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system ts(nthreads);\n for (int m = 1; m < 512; m *= 2) {\n for (int n = 0; n < 128; n = !n ? 1 : 2 * n) {\n for (int p = 0; p < 16; p = !p ? 1 : 2 * p) {\n std::vector<std::vector<std::vector<int>>> v(n, std::vector<std::vector<int>>(m, std::vector<int>(p, -1)));\n parallel_for::apply(0, n, &ts, [&](int i) {\n auto& w = v[i];\n parallel_for::apply(0, m, &ts, [&](int j) {\n auto& u = w[j];\n parallel_for::apply(0, p, &ts, [&](int k) {\n u[k] = i + j + k;\n });\n });\n });\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n for (int k = 0; k < p; k++) {\n EXPECT_EQ(i + j + k, v[i][j][k]);\n }\n }\n }\n }\n }\n }\n }\n}\n\nTEST(task_group, nested_parallel_for_unbalanced) {\n \/\/ Top level parallel for has many more tasks than lower level\n const int ntasks = 100000;\n {\n \/\/ Default batching\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, ntasks, &ts, [&](int i) {\n parallel_for::apply(0, 1, &ts, [&](int j) { v[i] = i; });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n \/\/ 128 tasks per batch\n const int batch_size = 128;\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, ntasks, batch_size, &ts, [&](int i) {\n parallel_for::apply(0, 1, batch_size, &ts, [&](int j) { v[i] = i; });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n \/\/ lower level parallel for has many more tasks than top level\n {\n \/\/ Default batching\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, 1, &ts, [&](int i) {\n parallel_for::apply(0, ntasks, &ts, [&](int j) { v[j] = j; });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n \/\/ 128 tasks per batch\n const int batch_size = 128;\n for (int nthreads = 1; nthreads < 20; nthreads *= 4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, 1, batch_size, &ts, [&](int i) {\n parallel_for::apply(0, ntasks, batch_size, &ts, [&](int j) { v[j] = j; });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n }\n}\n\nTEST(task_group, multi_nested_parallel_for_unbalanced) {\n \/\/ Top level parallel for has many more tasks than lower level\n const int ntasks = 100000;\n for (int nthreads = 1; nthreads < 20; nthreads*=4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, ntasks, &ts, [&](int i) {\n parallel_for::apply(0, 1, &ts, [&](int j) {\n parallel_for::apply(0, 1, &ts, [&](int k) {\n v[i] = i;\n });\n });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n \/\/ lower level parallel for has many more tasks than top level\n for (int nthreads = 1; nthreads < 20; nthreads*=4) {\n task_system ts(nthreads);\n std::vector<int> v(ntasks);\n parallel_for::apply(0, 1, &ts, [&](int i) {\n parallel_for::apply(0, 1, &ts, [&](int j) {\n parallel_for::apply(0, ntasks, &ts, [&](int k) {\n v[k] = k;\n });\n });\n });\n for (int i = 0; i < ntasks; i++) {\n EXPECT_EQ(i, v[i]);\n }\n }\n}\n\nTEST(enumerable_thread_specific, test) {\n for (int nthreads = 1; nthreads < 20; nthreads*=2) {\n task_system_handle ts = task_system_handle(new task_system(nthreads));\n enumerable_thread_specific<int> buffers(ts);\n task_group g(ts.get());\n\n for (int i = 0; i < 100000; i++) {\n g.run([&]() {\n auto& buf = buffers.local();\n buf++;\n });\n }\n g.wait();\n\n int sum = 0;\n for (auto b: buffers) {\n sum += b;\n }\n\n EXPECT_EQ(100000, sum);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <memory>\n#include <cassert>\n\n#include \"eval.hh\"\n#include \"util.hh\"\n#include \"keyword.hh\"\n#include \"symbol.hh\"\n#include \"cons.hh\"\n#include \"function.hh\"\n#include \"printer.hh\"\n\nusing namespace std;\n\nenum class VM_op : int{\n nop = 0,\n if_\n};\n\nnamespace {\n\nvoid funcall(const Function* fun, Lisp_ptr args){\n const auto& argi = fun->arg_info();\n const auto env = fun->closure();\n\n const auto set_arg = [&](Symbol* sym, Lisp_ptr p){\n if(env){\n VM.local_set(sym, p);\n }else{\n VM.stack().push(p);\n }\n };\n \n\n Lisp_ptr arg_name = argi.head;\n\n VM.return_value() = {};\n\n if(env){\n VM.enter_frame(push_frame(env));\n }\n\n \/\/ push args\n int argc = 0;\n\n if(!do_list(args,\n [&](Cons* cell) -> bool{\n assert(argc <= argi.required_args);\n\n if(argc == argi.required_args)\n return false;\n\n VM.code().push(cell->car());\n eval();\n auto evaled = VM.return_value();\n if(!evaled){\n fprintf(stderr, \"eval error: evaluating func's arg failed!!\\n\");\n return false;\n }\n\n auto arg_name_cell = arg_name.get<Cons*>();\n set_arg(arg_name_cell->car().get<Symbol*>(), evaled);\n arg_name = arg_name_cell->cdr();\n ++argc;\n\n return true;\n },\n [&](Lisp_ptr dot_cdr) -> bool{\n assert(argc <= argi.required_args);\n\n if(argc < argi.required_args){\n fprintf(stderr, \"eval error: internal argument counter mismatched!! (read %d args)\\n\",\n argc);\n return false;\n }\n\n if(argi.variadic){\n set_arg(arg_name.get<Symbol*>(), dot_cdr);\n ++argc;\n return true;\n }else{\n if(!nullp(dot_cdr)){\n fprintf(stderr, \"funcall error: argcount mismatch! (more than required %d)\\n\",\n argi.required_args);\n return false;\n }\n \n return true;\n }\n })){\n goto end;\n }\n\n \/\/ real call\n switch(fun->type()){\n case Function::Type::interpreted:\n do_list(fun->get<Lisp_ptr>(),\n [&](Cons* cell) -> bool {\n VM.code().push(cell->car());\n eval();\n return true;\n },\n [&](Lisp_ptr last_cdr){\n if(!nullp(last_cdr)){\n fprintf(stderr, \"eval error: body has dot list!\\n\");\n VM.return_value() = {};\n }\n });\n break;\n case Function::Type::native:\n fun->get<Function::NativeFunc>()();\n if(!VM.return_value())\n fprintf(stderr, \"eval error: native func returned undef!\\n\");\n break;\n default:\n UNEXP_DEFAULT();\n }\n\n end:\n if(env){\n VM.leave_frame();\n }else{\n \/\/ cleaned by native func\n }\n}\n\nvoid eval_lambda(const Cons* rest){\n VM.return_value() = {};\n\n auto args = rest->car();\n if(rest->cdr().tag() != Ptr_tag::cons){\n fprintf(stderr, \"eval error: lambda has invalid body!\\n\");\n return;\n }\n\n auto arg_info = parse_func_arg(args);\n if(!arg_info){\n fprintf(stderr, \"eval error: lambda has invalid args!\\n\");\n return;\n }\n\n auto code = rest->cdr();\n if(!code.get<Cons*>()){\n fprintf(stderr, \"eval error: lambda has no body!\\n\");\n return;\n }\n\n auto fun = new Function(code, arg_info, VM.frame());\n\n VM.return_value() = Lisp_ptr{fun};\n return;\n}\n\nvoid eval_if(Cons* rest){\n VM.return_value() = {};\n\n \/\/ extracting\n Lisp_ptr test, conseq, alt;\n\n int len =\n bind_cons_list(Lisp_ptr(rest),\n [&](Cons* c){\n test = c->car();\n },\n [&](Cons* c){\n conseq = c->car();\n },\n [&](Cons* c){\n alt = c->car();\n });\n\n switch(len){\n case 1:\n fprintf(stderr, \"eval error: informal if expr! (no test expr)\\n\");\n return;\n case 2: case 3: \/\/ successed\n break;\n default:\n fprintf(stderr, \"eval error: informal if expr! (more than %d exprs)\\n\", len);\n return;\n }\n\n \/\/ evaluating\n VM.code().push(Lisp_ptr(VM_op::if_));\n VM.code().push(test);\n\n VM.stack().push(alt);\n VM.stack().push(conseq);\n}\n\nvoid vm_op_if(){\n auto test_result = VM.return_value();\n\n if(test_result.get<bool>()){\n VM.code().push(VM.stack().top());\n VM.stack().pop();\n VM.stack().pop();\n }else{\n VM.stack().pop();\n VM.code().push(VM.stack().top());\n VM.stack().pop();\n }\n}\n\nvoid eval_set(Cons* rest){\n VM.return_value() = {};\n\n \/\/ extracting\n Symbol* var = nullptr;\n Lisp_ptr val;\n\n int len =\n bind_cons_list(Lisp_ptr(rest),\n [&](Cons* c){\n var = c->car().get<Symbol*>();\n },\n [&](Cons* c){\n val = c->car();\n });\n\n if(!var){\n fprintf(stderr, \"eval error: set!'s first element is not symbol!\\n\");\n return;\n }\n\n if(var->to_keyword() != Keyword::not_keyword){\n fprintf(stderr, \"eval error: set!'s first element is Keyword (%s)!\\n\",\n var->name().c_str());\n return;\n }\n\n if(!val){\n fprintf(stderr, \"eval error: no value is supplied for set!\\n\");\n return;\n }\n\n if(len > 2){\n fprintf(stderr, \"eval error: informal set! expr! (more than %d exprs)\\n\", len);\n return;\n }\n\n \/\/ evaluating\n VM.code().push(val);\n eval();\n VM.set(var, VM.return_value());\n return;\n}\n\nvoid eval_define(const Cons* rest){\n static constexpr auto test_varname = [](Symbol* var) -> bool{\n if(!var){\n fprintf(stderr, \"eval error: defined variable name is not a symbol!\\n\");\n return false;\n }\n\n if(var->to_keyword() != Keyword::not_keyword){\n fprintf(stderr, \"eval error: define's first element is Keyword (%s)!\\n\",\n var->name().c_str());\n return false;\n }\n\n return true;\n };\n\n Symbol* var = nullptr;\n Lisp_ptr value;\n unique_ptr<Function> func_value;\n\n VM.return_value() = {};\n\n \/\/ extracting\n auto first = rest->car();\n\n switch(first.tag()){\n case Ptr_tag::symbol: {\n var = first.get<Symbol*>();\n if(!test_varname(var))\n return;\n\n auto val_l = rest->cdr().get<Cons*>();\n if(!val_l){\n fprintf(stderr, \"eval error: definition has empty expr!\\n\");\n return;\n }\n if(val_l->cdr().tag() != Ptr_tag::cons\n || val_l->cdr().get<Cons*>()){\n fprintf(stderr, \"eval error: definition has extra expr!\\n\");\n return;\n }\n\n VM.code().push(val_l->car());\n eval();\n value = VM.return_value();\n break;\n }\n\n case Ptr_tag::cons: {\n auto lis = first.get<Cons*>();\n if(!lis){\n fprintf(stderr, \"eval error: defined variable is not found!\\n\");\n return;\n }\n\n var = lis->car().get<Symbol*>();\n if(!test_varname(var))\n return;\n\n const auto& arg_info = parse_func_arg(lis->cdr());\n if(!arg_info){\n fprintf(stderr, \"eval error: defined function argument is informal!\\n\");\n return;\n }\n \n auto code = rest->cdr();\n if(!code.get<Cons*>()){\n fprintf(stderr, \"eval error: definition has empty body!\\n\");\n return;\n }\n\n func_value = unique_ptr<Function>(new Function(code, arg_info, VM.frame()));\n value = Lisp_ptr(func_value.get());\n break;\n }\n\n default:\n fprintf(stderr, \"eval error: informal define syntax!\\n\");\n return;\n }\n\n \/\/ assignment\n VM.set(var, value);\n func_value.release();\n\n VM.return_value() = value;\n return;\n}\n\n} \/\/ namespace\n\nvoid eval(){\n while(!VM.code().empty()){\n auto p = VM.code().top();\n VM.code().pop();\n\n switch(p.tag()){\n case Ptr_tag::symbol: {\n auto sym = p.get<Symbol*>();\n if(sym->to_keyword() != Keyword::not_keyword){\n fprintf(stderr, \"eval error: symbol '%s' is keyword!!\\n\", sym->name().c_str());\n VM.return_value() = {};\n break;\n }\n \n VM.return_value() = VM.find(sym);\n break;\n }\n \n case Ptr_tag::cons: {\n auto c = p.get<Cons*>();\n auto first = c->car();\n\n \/\/ special operator?\n if(first.tag() == Ptr_tag::symbol){\n auto sym = first.get<Symbol*>();\n auto k = sym->to_keyword();\n\n if(k != Keyword::not_keyword){\n Cons* r = c->cdr().get<Cons*>();\n if(!r){\n fprintf(stderr, \"eval error: expresssion (<KEYWORD>%s) is informal!\\n\",\n (c->cdr().tag() == Ptr_tag::cons) ? \"\" : \". #\");\n VM.return_value() = {};\n break;\n }\n\n switch(k){\n case Keyword::quote: VM.return_value() = r->car(); break;\n case Keyword::lambda: eval_lambda(r); break;\n case Keyword::if_: eval_if(r); break;\n case Keyword::set_: eval_set(r); break;\n case Keyword::define: eval_define(r); break;\n\n case Keyword::cond:\n case Keyword::case_:\n case Keyword::and_:\n case Keyword::or_:\n case Keyword::let:\n case Keyword::let_star:\n case Keyword::letrec:\n case Keyword::begin:\n case Keyword::do_:\n case Keyword::delay:\n case Keyword::quasiquote:\n fprintf(stderr, \"eval error: '%s' is under development...\\n\",\n sym->name().c_str());\n VM.return_value() = {};\n break;\n\n case Keyword::else_:\n case Keyword::r_arrow:\n case Keyword::unquote:\n case Keyword::unquote_splicing:\n fprintf(stderr, \"eval error: '%s' cannot be used as operator!!\\n\",\n sym->name().c_str());\n VM.return_value() = {};\n break;\n\n default:\n UNEXP_DEFAULT();\n }\n break;\n }else{\n \/\/ macro call?\n \/\/ try to find macro-function from symbol\n \/\/ found -> macro expansion\n \/\/ not found -> goto function calling\n ;\n }\n }\n\n \/\/ procedure call?\n VM.code().push(first);\n eval();\n auto proc = VM.return_value();\n if(proc.tag() != Ptr_tag::function){\n fprintf(stderr, \"eval error: (# # ...)'s first element is not procedure (%s)\\n\",\n stringify(proc.tag()));\n VM.return_value() = {};\n break;\n }\n\n funcall(proc.get<Function*>(), c->cdr());\n break;\n }\n\n case Ptr_tag::vm_op:\n switch(p.get<VM_op>()){\n case VM_op::nop:\n break;\n case VM_op::if_:\n vm_op_if();\n break;\n default:\n UNEXP_DEFAULT();\n }\n break;\n \n default: \/\/ almost self-evaluating\n VM.return_value() = p;\n break;\n }\n }\n}\n<commit_msg>nonrecursive set<commit_after>#include <memory>\n#include <cassert>\n\n#include \"eval.hh\"\n#include \"util.hh\"\n#include \"keyword.hh\"\n#include \"symbol.hh\"\n#include \"cons.hh\"\n#include \"function.hh\"\n#include \"printer.hh\"\n\nusing namespace std;\n\nenum class VM_op : int{\n nop = 0,\n if_,\n set_\n};\n\nnamespace {\n\nvoid funcall(const Function* fun, Lisp_ptr args){\n const auto& argi = fun->arg_info();\n const auto env = fun->closure();\n\n const auto set_arg = [&](Symbol* sym, Lisp_ptr p){\n if(env){\n VM.local_set(sym, p);\n }else{\n VM.stack().push(p);\n }\n };\n \n\n Lisp_ptr arg_name = argi.head;\n\n VM.return_value() = {};\n\n if(env){\n VM.enter_frame(push_frame(env));\n }\n\n \/\/ push args\n int argc = 0;\n\n if(!do_list(args,\n [&](Cons* cell) -> bool{\n assert(argc <= argi.required_args);\n\n if(argc == argi.required_args)\n return false;\n\n VM.code().push(cell->car());\n eval();\n auto evaled = VM.return_value();\n if(!evaled){\n fprintf(stderr, \"eval error: evaluating func's arg failed!!\\n\");\n return false;\n }\n\n auto arg_name_cell = arg_name.get<Cons*>();\n set_arg(arg_name_cell->car().get<Symbol*>(), evaled);\n arg_name = arg_name_cell->cdr();\n ++argc;\n\n return true;\n },\n [&](Lisp_ptr dot_cdr) -> bool{\n assert(argc <= argi.required_args);\n\n if(argc < argi.required_args){\n fprintf(stderr, \"eval error: internal argument counter mismatched!! (read %d args)\\n\",\n argc);\n return false;\n }\n\n if(argi.variadic){\n set_arg(arg_name.get<Symbol*>(), dot_cdr);\n ++argc;\n return true;\n }else{\n if(!nullp(dot_cdr)){\n fprintf(stderr, \"funcall error: argcount mismatch! (more than required %d)\\n\",\n argi.required_args);\n return false;\n }\n \n return true;\n }\n })){\n goto end;\n }\n\n \/\/ real call\n switch(fun->type()){\n case Function::Type::interpreted:\n do_list(fun->get<Lisp_ptr>(),\n [&](Cons* cell) -> bool {\n VM.code().push(cell->car());\n eval();\n return true;\n },\n [&](Lisp_ptr last_cdr){\n if(!nullp(last_cdr)){\n fprintf(stderr, \"eval error: body has dot list!\\n\");\n VM.return_value() = {};\n }\n });\n break;\n case Function::Type::native:\n fun->get<Function::NativeFunc>()();\n if(!VM.return_value())\n fprintf(stderr, \"eval error: native func returned undef!\\n\");\n break;\n default:\n UNEXP_DEFAULT();\n }\n\n end:\n if(env){\n VM.leave_frame();\n }else{\n \/\/ cleaned by native func\n }\n}\n\nvoid eval_lambda(const Cons* rest){\n VM.return_value() = {};\n\n auto args = rest->car();\n if(rest->cdr().tag() != Ptr_tag::cons){\n fprintf(stderr, \"eval error: lambda has invalid body!\\n\");\n return;\n }\n\n auto arg_info = parse_func_arg(args);\n if(!arg_info){\n fprintf(stderr, \"eval error: lambda has invalid args!\\n\");\n return;\n }\n\n auto code = rest->cdr();\n if(!code.get<Cons*>()){\n fprintf(stderr, \"eval error: lambda has no body!\\n\");\n return;\n }\n\n auto fun = new Function(code, arg_info, VM.frame());\n\n VM.return_value() = Lisp_ptr{fun};\n return;\n}\n\nvoid eval_if(Cons* rest){\n VM.return_value() = {};\n\n \/\/ extracting\n Lisp_ptr test, conseq, alt;\n\n int len =\n bind_cons_list(Lisp_ptr(rest),\n [&](Cons* c){\n test = c->car();\n },\n [&](Cons* c){\n conseq = c->car();\n },\n [&](Cons* c){\n alt = c->car();\n });\n\n switch(len){\n case 1:\n fprintf(stderr, \"eval error: informal if expr! (no test expr)\\n\");\n return;\n case 2: case 3: \/\/ successed\n break;\n default:\n fprintf(stderr, \"eval error: informal if expr! (more than %d exprs)\\n\", len);\n return;\n }\n\n \/\/ evaluating\n VM.code().push(Lisp_ptr(VM_op::if_));\n VM.code().push(test);\n\n VM.stack().push(alt);\n VM.stack().push(conseq);\n}\n\nvoid vm_op_if(){\n auto test_result = VM.return_value();\n\n if(test_result.get<bool>()){\n VM.code().push(VM.stack().top());\n VM.stack().pop();\n VM.stack().pop();\n }else{\n VM.stack().pop();\n VM.code().push(VM.stack().top());\n VM.stack().pop();\n }\n}\n\nvoid eval_set(Cons* rest){\n VM.return_value() = {};\n\n \/\/ extracting\n Symbol* var = nullptr;\n Lisp_ptr val;\n\n int len =\n bind_cons_list(Lisp_ptr(rest),\n [&](Cons* c){\n var = c->car().get<Symbol*>();\n },\n [&](Cons* c){\n val = c->car();\n });\n\n if(!var){\n fprintf(stderr, \"eval error: set!'s first element is not symbol!\\n\");\n return;\n }\n\n if(var->to_keyword() != Keyword::not_keyword){\n fprintf(stderr, \"eval error: set!'s first element is Keyword (%s)!\\n\",\n var->name().c_str());\n return;\n }\n\n if(!val){\n fprintf(stderr, \"eval error: no value is supplied for set!\\n\");\n return;\n }\n\n if(len > 2){\n fprintf(stderr, \"eval error: informal set! expr! (more than %d exprs)\\n\", len);\n return;\n }\n\n \/\/ evaluating\n VM.code().push(Lisp_ptr{VM_op::set_});\n VM.code().push(val);\n VM.stack().push(Lisp_ptr{var});\n}\n\nvoid vm_op_set(){\n auto var = VM.stack().top().get<Symbol*>();\n VM.stack().pop();\n if(!var){\n fprintf(stderr, \"eval error: internal error occured (set!'s varname is dismissed)\\n\");\n return;\n }\n\n VM.set(var, VM.return_value());\n}\n\nvoid eval_define(const Cons* rest){\n static constexpr auto test_varname = [](Symbol* var) -> bool{\n if(!var){\n fprintf(stderr, \"eval error: defined variable name is not a symbol!\\n\");\n return false;\n }\n\n if(var->to_keyword() != Keyword::not_keyword){\n fprintf(stderr, \"eval error: define's first element is Keyword (%s)!\\n\",\n var->name().c_str());\n return false;\n }\n\n return true;\n };\n\n Symbol* var = nullptr;\n Lisp_ptr value;\n unique_ptr<Function> func_value;\n\n VM.return_value() = {};\n\n \/\/ extracting\n auto first = rest->car();\n\n switch(first.tag()){\n case Ptr_tag::symbol: {\n var = first.get<Symbol*>();\n if(!test_varname(var))\n return;\n\n auto val_l = rest->cdr().get<Cons*>();\n if(!val_l){\n fprintf(stderr, \"eval error: definition has empty expr!\\n\");\n return;\n }\n if(val_l->cdr().tag() != Ptr_tag::cons\n || val_l->cdr().get<Cons*>()){\n fprintf(stderr, \"eval error: definition has extra expr!\\n\");\n return;\n }\n\n VM.code().push(val_l->car());\n eval();\n value = VM.return_value();\n break;\n }\n\n case Ptr_tag::cons: {\n auto lis = first.get<Cons*>();\n if(!lis){\n fprintf(stderr, \"eval error: defined variable is not found!\\n\");\n return;\n }\n\n var = lis->car().get<Symbol*>();\n if(!test_varname(var))\n return;\n\n const auto& arg_info = parse_func_arg(lis->cdr());\n if(!arg_info){\n fprintf(stderr, \"eval error: defined function argument is informal!\\n\");\n return;\n }\n \n auto code = rest->cdr();\n if(!code.get<Cons*>()){\n fprintf(stderr, \"eval error: definition has empty body!\\n\");\n return;\n }\n\n func_value = unique_ptr<Function>(new Function(code, arg_info, VM.frame()));\n value = Lisp_ptr(func_value.get());\n break;\n }\n\n default:\n fprintf(stderr, \"eval error: informal define syntax!\\n\");\n return;\n }\n\n \/\/ assignment\n VM.set(var, value);\n func_value.release();\n\n VM.return_value() = value;\n return;\n}\n\n} \/\/ namespace\n\nvoid eval(){\n while(!VM.code().empty()){\n auto p = VM.code().top();\n VM.code().pop();\n\n switch(p.tag()){\n case Ptr_tag::symbol: {\n auto sym = p.get<Symbol*>();\n if(sym->to_keyword() != Keyword::not_keyword){\n fprintf(stderr, \"eval error: symbol '%s' is keyword!!\\n\", sym->name().c_str());\n VM.return_value() = {};\n break;\n }\n \n VM.return_value() = VM.find(sym);\n break;\n }\n \n case Ptr_tag::cons: {\n auto c = p.get<Cons*>();\n auto first = c->car();\n\n \/\/ special operator?\n if(first.tag() == Ptr_tag::symbol){\n auto sym = first.get<Symbol*>();\n auto k = sym->to_keyword();\n\n if(k != Keyword::not_keyword){\n Cons* r = c->cdr().get<Cons*>();\n if(!r){\n fprintf(stderr, \"eval error: expresssion (<KEYWORD>%s) is informal!\\n\",\n (c->cdr().tag() == Ptr_tag::cons) ? \"\" : \". #\");\n VM.return_value() = {};\n break;\n }\n\n switch(k){\n case Keyword::quote: VM.return_value() = r->car(); break;\n case Keyword::lambda: eval_lambda(r); break;\n case Keyword::if_: eval_if(r); break;\n case Keyword::set_: eval_set(r); break;\n case Keyword::define: eval_define(r); break;\n\n case Keyword::cond:\n case Keyword::case_:\n case Keyword::and_:\n case Keyword::or_:\n case Keyword::let:\n case Keyword::let_star:\n case Keyword::letrec:\n case Keyword::begin:\n case Keyword::do_:\n case Keyword::delay:\n case Keyword::quasiquote:\n fprintf(stderr, \"eval error: '%s' is under development...\\n\",\n sym->name().c_str());\n VM.return_value() = {};\n break;\n\n case Keyword::else_:\n case Keyword::r_arrow:\n case Keyword::unquote:\n case Keyword::unquote_splicing:\n fprintf(stderr, \"eval error: '%s' cannot be used as operator!!\\n\",\n sym->name().c_str());\n VM.return_value() = {};\n break;\n\n default:\n UNEXP_DEFAULT();\n }\n break;\n }else{\n \/\/ macro call?\n \/\/ try to find macro-function from symbol\n \/\/ found -> macro expansion\n \/\/ not found -> goto function calling\n ;\n }\n }\n\n \/\/ procedure call?\n VM.code().push(first);\n eval();\n auto proc = VM.return_value();\n if(proc.tag() != Ptr_tag::function){\n fprintf(stderr, \"eval error: (# # ...)'s first element is not procedure (%s)\\n\",\n stringify(proc.tag()));\n VM.return_value() = {};\n break;\n }\n\n funcall(proc.get<Function*>(), c->cdr());\n break;\n }\n\n case Ptr_tag::vm_op:\n switch(p.get<VM_op>()){\n case VM_op::nop:\n break;\n case VM_op::if_:\n vm_op_if();\n break;\n case VM_op::set_:\n vm_op_set();\n break;\n default:\n UNEXP_DEFAULT();\n }\n break;\n \n default: \/\/ almost self-evaluating\n VM.return_value() = p;\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Gobby - GTK-based collaborative text editor\n * Copyright (C) 2008-2014 Armin Burgmeier <armin@arbur.net>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef _GOBBY_TEXTSESSIONUSERVIEW_HPP_\n#define _GOBBY_TEXTSESSIENUSERVIEW_HPP_\n\n#include \"core\/sessionuserview.hpp\"\n#include \"core\/textsessionview.hpp\"\n#include \"core\/preferences.hpp\"\n#include \"core\/userlist.hpp\"\n\n\/\/ Allows a user in the user list to be double-clicked at, scrolling\n\/\/ the text view to that user's cursor.\nnamespace Gobby\n{\n\nclass TextSessionUserView: public SessionUserView\n{\npublic:\n\tTextSessionUserView(TextSessionView& view, bool show_disconnected,\n\t Preferences::Option<bool>& userlist_view,\n\t Preferences::Option<unsigned int>& w);\n\n\tTextSessionView& get_session_view()\n\t{\n\t\treturn static_cast<TextSessionView&>(\n\t\t\tSessionUserView::get_session_view());\n\t}\n\n\tconst TextSessionView& get_session_view() const\n\t{\n\t\treturn static_cast<const TextSessionView&>(\n\t\t\tSessionUserView::get_session_view());\n\t}\n\nprotected:\n\tvoid on_user_activated(InfUser* user);\n};\n\n}\n\n#endif \/\/ _GOBBY_TEXTSESSIONUSERVIEW_HPP_\n<commit_msg>Fix typo in header guard<commit_after>\/* Gobby - GTK-based collaborative text editor\n * Copyright (C) 2008-2014 Armin Burgmeier <armin@arbur.net>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef _GOBBY_TEXTSESSIONUSERVIEW_HPP_\n#define _GOBBY_TEXTSESSIONUSERVIEW_HPP_\n\n#include \"core\/sessionuserview.hpp\"\n#include \"core\/textsessionview.hpp\"\n#include \"core\/preferences.hpp\"\n#include \"core\/userlist.hpp\"\n\n\/\/ Allows a user in the user list to be double-clicked at, scrolling\n\/\/ the text view to that user's cursor.\nnamespace Gobby\n{\n\nclass TextSessionUserView: public SessionUserView\n{\npublic:\n\tTextSessionUserView(TextSessionView& view, bool show_disconnected,\n\t Preferences::Option<bool>& userlist_view,\n\t Preferences::Option<unsigned int>& w);\n\n\tTextSessionView& get_session_view()\n\t{\n\t\treturn static_cast<TextSessionView&>(\n\t\t\tSessionUserView::get_session_view());\n\t}\n\n\tconst TextSessionView& get_session_view() const\n\t{\n\t\treturn static_cast<const TextSessionView&>(\n\t\t\tSessionUserView::get_session_view());\n\t}\n\nprotected:\n\tvoid on_user_activated(InfUser* user);\n};\n\n}\n\n#endif \/\/ _GOBBY_TEXTSESSIONUSERVIEW_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <v8.h>\n#include <functional>\n#include <bastian.h>\n#include \"test-v8-common.h\"\n\nusing namespace v8;\n\nstatic v8::Isolate* isolate = v8::Isolate::New();\nstatic v8::Isolate::Scope isolatescope(isolate);\nstatic v8::HandleScope handle_scope(isolate);\n\n\nTestContext::TestContext() {\n \/\/ Create a new Isolate and make it the current one.\n global_ = ObjectTemplate::New(v8::Isolate::GetCurrent());\n}\n\nvoid TestContext::AddFunction(const char * export_name, void (*func)(const v8::FunctionCallbackInfo<v8::Value>&)) {\n global_->Set(\n v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), export_name),\n FunctionTemplate::New(v8::Isolate::GetCurrent(), func));\n}\n\nvoid TestContext::RunJS(const char * rawSource) {\n \/\/ Create a new context.\n Local<Context> context = Context::New(v8::Isolate::GetCurrent(), NULL, global_);\n\n \/\/ Enter the context for compiling and running the hello world script.\n Context::Scope context_scope(context);\n\n Local<v8::String> source = v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), rawSource);\n Local<Script> script = Script::Compile(source);\n\n script->Run();\n}\n<commit_msg>remove using namespace v8 in test<commit_after>#include <v8.h>\n#include <functional>\n#include <bastian.h>\n#include \"test-v8-common.h\"\n\n\nTestContext::TestContext() {\n global_ = v8::ObjectTemplate::New(v8::Isolate::GetCurrent());\n}\n\nvoid TestContext::AddFunction(const char * export_name, void (*func)(const v8::FunctionCallbackInfo<v8::Value>&)) {\n global_->Set(\n v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), export_name),\n v8::FunctionTemplate::New(v8::Isolate::GetCurrent(), func));\n}\n\nvoid TestContext::RunJS(const char * rawSource) {\n \/\/ Create a new context.\n v8::Local<v8::Context> context = v8::Context::New(v8::Isolate::GetCurrent(), NULL, global_);\n\n \/\/ Enter the context for compiling and running the hello world script.\n v8::Context::Scope context_scope(context);\n\n v8::Local<v8::String> source = v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), rawSource);\n v8::Local<v8::Script> script = v8::Script::Compile(source);\n\n script->Run();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n* Copyright (c) 2003-2015 Rony Shapiro <ronys@users.sourceforge.net>.\r\n* All rights reserved. Use of the code is allowed under the\r\n* Artistic License 2.0 terms, as specified in the LICENSE file\r\n* distributed with this code, or available from\r\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\r\n*\/\r\n\r\n\/**\r\n * \\file Windows-specific implementation of debug.h\r\n *\/\r\n\r\n\/\/ TRACE replacement\r\n#include \"..\/debug.h\"\r\n#include \"..\/..\/core\/util.h\"\r\n#include <wtypes.h>\r\n\r\n#if defined(_DEBUG) || defined(DEBUG)\r\n\r\n#include <stdio.h>\r\n\r\n\/\/ Debug output - Same usage as MFC TRACE\r\n\/\/ Adds timestamp to start of every piece of debug output\r\nvoid pws_os::Trace(LPCTSTR lpszFormat, ...)\r\n{\r\n va_list args;\r\n va_start(args, lpszFormat);\r\n\r\n stringT sTimeStamp;\r\n PWSUtil::GetTimeStamp(sTimeStamp);\r\n int num_required, num_written;\r\n\r\n num_required = GetStringBufSize(lpszFormat, args);\r\n va_end(args);\/\/after using args we should reset list\r\n va_start(args, lpszFormat);\r\n\r\n TCHAR *szBuffer = new TCHAR[num_required];\r\n num_written = _vsntprintf_s(szBuffer, num_required, num_required - 1, lpszFormat, args);\r\n _ASSERT(num_required == num_written + 1);\r\n szBuffer[num_required - 1] = '\\0';\r\n\r\n const size_t N = num_written + sTimeStamp.length() + 2;\r\n TCHAR *szDebugString = new TCHAR[N];\r\n\r\n _tcscpy_s(szDebugString, N, sTimeStamp.c_str());\r\n _tcscat_s(szDebugString, N, _T(\" \"));\r\n _tcscat_s(szDebugString, N, szBuffer);\r\n\r\n OutputDebugString(szDebugString);\r\n delete[] szDebugString;\r\n delete[] szBuffer;\r\n va_end(args);\r\n}\r\n\r\nvoid pws_os::Trace0(LPCTSTR lpszFormat)\r\n{\r\n stringT sTimeStamp;\r\n PWSUtil::GetTimeStamp(sTimeStamp);\r\n\r\n const size_t N = _tcslen(lpszFormat) + sTimeStamp.length() + 2;\r\n TCHAR *szDebugString = new TCHAR[N];\r\n\r\n _tcscpy_s(szDebugString, N, sTimeStamp.c_str());\r\n _tcscat_s(szDebugString, N, _T(\" \"));\r\n _tcscat_s(szDebugString, N, lpszFormat);\r\n\r\n OutputDebugString(szDebugString);\r\n delete [] szDebugString;\r\n}\r\n#else \/* _DEBUG || DEBUG *\/\r\nvoid pws_os::Trace(LPCTSTR , ...)\r\n{\r\n\/\/ Do nothing in non-Debug mode\r\n}\r\nvoid pws_os::Trace0(LPCTSTR )\r\n{\r\n\/\/ Do nothing in non-Debug mode\r\n}\r\n#endif \/* _DEBUG || DEBUG *\/\r\n\r\n#if defined(_DEBUG) || defined(DEBUG)\r\n#include \"windows.h\"\r\n#include \"..\/debug.h\"\r\n#include \"..\/..\/core\/StringX.h\"\r\n\r\n\/\/ This routine uses Windows functions\r\nDWORD pws_os::IssueError(const stringT &csFunction, bool bMsgBox)\r\n{\r\n LPVOID lpMsgBuf;\r\n LPVOID lpDisplayBuf;\r\n\r\n const DWORD dwLastError = GetLastError();\r\n\r\n FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\r\n NULL,\r\n dwLastError,\r\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\r\n (LPTSTR) &lpMsgBuf,\r\n 0, NULL);\r\n\r\n lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,\r\n (lstrlen((LPCTSTR)lpMsgBuf) + csFunction.length() + 40) * sizeof(TCHAR));\r\n wsprintf((LPTSTR)lpDisplayBuf, TEXT(\"%s failed with error %d: %s\"),\r\n csFunction.c_str(), dwLastError, lpMsgBuf);\r\n if (bMsgBox)\r\n MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT(\"Error\"), MB_OK);\r\n else\r\n OutputDebugString((LPCTSTR)lpDisplayBuf);\r\n\r\n LocalFree(lpMsgBuf);\r\n LocalFree(lpDisplayBuf);\r\n\r\n return dwLastError;\r\n}\r\n\r\nvoid pws_os::HexDump(unsigned char *pmemory, const int &length,\r\n const stringT &cs_prefix, const int &maxnum)\r\n{\r\n TCHAR szBuffer[256];\r\n unsigned char *pmem;\r\n stringT cs_outbuff, cs_hexbuff, cs_charbuff;\r\n int i, j, len(length);\r\n unsigned char c;\r\n\r\n pmem = pmemory;\r\n while (len > 0) {\r\n \/\/ Show offset for this line.\r\n cs_charbuff.clear();\r\n cs_hexbuff.clear();\r\n Format(cs_outbuff, _T(\"%s: %08x *\"), cs_prefix.c_str(), pmem);\r\n\r\n \/\/ Format hex portion of line and save chars for ascii portion\r\n if (len > maxnum)\r\n j = maxnum;\r\n else\r\n j = len;\r\n\r\n for (i = 0; i < j; i++) {\r\n c = *pmem++;\r\n\r\n if ((i % 4) == 0 && i != 0)\r\n cs_outbuff += _T(' ');\r\n\r\n Format(cs_hexbuff, _T(\"%02x\"), c);\r\n cs_outbuff += cs_hexbuff;\r\n\r\n if (c >= 32 && c < 127)\r\n cs_charbuff += (TCHAR)c;\r\n else\r\n cs_charbuff += _T('.');\r\n }\r\n\r\n j = maxnum - j;\r\n\r\n \/\/ Fill out hex portion of short lines.\r\n for (i = j; i > 0; i--) {\r\n if ((i % 4) != 0)\r\n cs_outbuff += _T(\" \");\r\n else\r\n cs_outbuff += _T(\" \");\r\n }\r\n\r\n \/\/ Add ASCII character portion to line.\r\n cs_outbuff += _T(\"* |\");\r\n cs_outbuff += cs_charbuff;\r\n\r\n \/\/ Fill out end of short lines.\r\n for (i = j; i > 0; i--)\r\n cs_outbuff += _T(' ');\r\n\r\n cs_outbuff += _T('|');\r\n\r\n \/\/ Next line\r\n len -= maxnum;\r\n\r\n _stprintf_s(szBuffer, sizeof(szBuffer) \/ sizeof(TCHAR),\r\n _T(\"%s\\n\"), cs_outbuff.c_str());\r\n OutputDebugString(szBuffer);\r\n };\r\n}\r\n#else \/* _DEBUG or DEBUG *\/\r\nDWORD pws_os::IssueError(const stringT &, bool )\r\n{\r\n\/\/ Do nothing in non-Debug mode\r\n return 0;\r\n}\r\n\r\nvoid pws_os::HexDump(unsigned char *, const int &,\r\n const stringT &, const int &)\r\n{\r\n\/\/ Do nothing in non-Debug mode\r\n}\r\n#endif \/* _DEBUG or DEBUG *\/\r\n<commit_msg>Unify ASSERT usage in Windows build<commit_after>\/*\r\n* Copyright (c) 2003-2015 Rony Shapiro <ronys@users.sourceforge.net>.\r\n* All rights reserved. Use of the code is allowed under the\r\n* Artistic License 2.0 terms, as specified in the LICENSE file\r\n* distributed with this code, or available from\r\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\r\n*\/\r\n\r\n\/**\r\n * \\file Windows-specific implementation of debug.h\r\n *\/\r\n\r\n\/\/ TRACE replacement\r\n#include \"..\/debug.h\"\r\n#include \"..\/..\/core\/util.h\"\r\n#include <wtypes.h>\r\n\r\n#if defined(_DEBUG) || defined(DEBUG)\r\n\r\n#include <stdio.h>\r\n\r\n\/\/ Debug output - Same usage as MFC TRACE\r\n\/\/ Adds timestamp to start of every piece of debug output\r\nvoid pws_os::Trace(LPCTSTR lpszFormat, ...)\r\n{\r\n va_list args;\r\n va_start(args, lpszFormat);\r\n\r\n stringT sTimeStamp;\r\n PWSUtil::GetTimeStamp(sTimeStamp);\r\n int num_required, num_written;\r\n\r\n num_required = GetStringBufSize(lpszFormat, args);\r\n va_end(args);\/\/after using args we should reset list\r\n va_start(args, lpszFormat);\r\n\r\n TCHAR *szBuffer = new TCHAR[num_required];\r\n num_written = _vsntprintf_s(szBuffer, num_required, num_required - 1, lpszFormat, args);\r\n ASSERT(num_required == num_written + 1);\r\n szBuffer[num_required - 1] = '\\0';\r\n\r\n const size_t N = num_written + sTimeStamp.length() + 2;\r\n TCHAR *szDebugString = new TCHAR[N];\r\n\r\n _tcscpy_s(szDebugString, N, sTimeStamp.c_str());\r\n _tcscat_s(szDebugString, N, _T(\" \"));\r\n _tcscat_s(szDebugString, N, szBuffer);\r\n\r\n OutputDebugString(szDebugString);\r\n delete[] szDebugString;\r\n delete[] szBuffer;\r\n va_end(args);\r\n}\r\n\r\nvoid pws_os::Trace0(LPCTSTR lpszFormat)\r\n{\r\n stringT sTimeStamp;\r\n PWSUtil::GetTimeStamp(sTimeStamp);\r\n\r\n const size_t N = _tcslen(lpszFormat) + sTimeStamp.length() + 2;\r\n TCHAR *szDebugString = new TCHAR[N];\r\n\r\n _tcscpy_s(szDebugString, N, sTimeStamp.c_str());\r\n _tcscat_s(szDebugString, N, _T(\" \"));\r\n _tcscat_s(szDebugString, N, lpszFormat);\r\n\r\n OutputDebugString(szDebugString);\r\n delete [] szDebugString;\r\n}\r\n#else \/* _DEBUG || DEBUG *\/\r\nvoid pws_os::Trace(LPCTSTR , ...)\r\n{\r\n\/\/ Do nothing in non-Debug mode\r\n}\r\nvoid pws_os::Trace0(LPCTSTR )\r\n{\r\n\/\/ Do nothing in non-Debug mode\r\n}\r\n#endif \/* _DEBUG || DEBUG *\/\r\n\r\n#if defined(_DEBUG) || defined(DEBUG)\r\n#include \"windows.h\"\r\n#include \"..\/debug.h\"\r\n#include \"..\/..\/core\/StringX.h\"\r\n\r\n\/\/ This routine uses Windows functions\r\nDWORD pws_os::IssueError(const stringT &csFunction, bool bMsgBox)\r\n{\r\n LPVOID lpMsgBuf;\r\n LPVOID lpDisplayBuf;\r\n\r\n const DWORD dwLastError = GetLastError();\r\n\r\n FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\r\n NULL,\r\n dwLastError,\r\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\r\n (LPTSTR) &lpMsgBuf,\r\n 0, NULL);\r\n\r\n lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,\r\n (lstrlen((LPCTSTR)lpMsgBuf) + csFunction.length() + 40) * sizeof(TCHAR));\r\n wsprintf((LPTSTR)lpDisplayBuf, TEXT(\"%s failed with error %d: %s\"),\r\n csFunction.c_str(), dwLastError, lpMsgBuf);\r\n if (bMsgBox)\r\n MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT(\"Error\"), MB_OK);\r\n else\r\n OutputDebugString((LPCTSTR)lpDisplayBuf);\r\n\r\n LocalFree(lpMsgBuf);\r\n LocalFree(lpDisplayBuf);\r\n\r\n return dwLastError;\r\n}\r\n\r\nvoid pws_os::HexDump(unsigned char *pmemory, const int &length,\r\n const stringT &cs_prefix, const int &maxnum)\r\n{\r\n TCHAR szBuffer[256];\r\n unsigned char *pmem;\r\n stringT cs_outbuff, cs_hexbuff, cs_charbuff;\r\n int i, j, len(length);\r\n unsigned char c;\r\n\r\n pmem = pmemory;\r\n while (len > 0) {\r\n \/\/ Show offset for this line.\r\n cs_charbuff.clear();\r\n cs_hexbuff.clear();\r\n Format(cs_outbuff, _T(\"%s: %08x *\"), cs_prefix.c_str(), pmem);\r\n\r\n \/\/ Format hex portion of line and save chars for ascii portion\r\n if (len > maxnum)\r\n j = maxnum;\r\n else\r\n j = len;\r\n\r\n for (i = 0; i < j; i++) {\r\n c = *pmem++;\r\n\r\n if ((i % 4) == 0 && i != 0)\r\n cs_outbuff += _T(' ');\r\n\r\n Format(cs_hexbuff, _T(\"%02x\"), c);\r\n cs_outbuff += cs_hexbuff;\r\n\r\n if (c >= 32 && c < 127)\r\n cs_charbuff += (TCHAR)c;\r\n else\r\n cs_charbuff += _T('.');\r\n }\r\n\r\n j = maxnum - j;\r\n\r\n \/\/ Fill out hex portion of short lines.\r\n for (i = j; i > 0; i--) {\r\n if ((i % 4) != 0)\r\n cs_outbuff += _T(\" \");\r\n else\r\n cs_outbuff += _T(\" \");\r\n }\r\n\r\n \/\/ Add ASCII character portion to line.\r\n cs_outbuff += _T(\"* |\");\r\n cs_outbuff += cs_charbuff;\r\n\r\n \/\/ Fill out end of short lines.\r\n for (i = j; i > 0; i--)\r\n cs_outbuff += _T(' ');\r\n\r\n cs_outbuff += _T('|');\r\n\r\n \/\/ Next line\r\n len -= maxnum;\r\n\r\n _stprintf_s(szBuffer, sizeof(szBuffer) \/ sizeof(TCHAR),\r\n _T(\"%s\\n\"), cs_outbuff.c_str());\r\n OutputDebugString(szBuffer);\r\n };\r\n}\r\n#else \/* _DEBUG or DEBUG *\/\r\nDWORD pws_os::IssueError(const stringT &, bool )\r\n{\r\n\/\/ Do nothing in non-Debug mode\r\n return 0;\r\n}\r\n\r\nvoid pws_os::HexDump(unsigned char *, const int &,\r\n const stringT &, const int &)\r\n{\r\n\/\/ Do nothing in non-Debug mode\r\n}\r\n#endif \/* _DEBUG or DEBUG *\/\r\n<|endoftext|>"} {"text":"<commit_before>#include <ros\/ros.h> \n#include <geometry_msgs\/Twist.h> \n#include <math>\n\nstatic const float tol = 0.000000000000001f;\n\nvoid normalize(double &vec[2]){\n float m = sqrt(vec[0]*vec[0] + vec[1]*vec[1]);\n if(tol <= m) m = 1;\n vec[0] \/= m;\n vec[1] \/= m;\n\n if(fabs(vec[0]) < tol) vec[0] = 0.0f;\n if(fabs(vec[1]) < tol) vec[1] = 0.0f;\n}\n\nint main(int argc, char *argv[]){\n ros::NodeHandle node;\n ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10);\n \n ros::Duration(1).sleep();\n geometry_msgs::Twist cmd;\n \n \/\/cmd.linear.z = 1;\n \n double Fs[2];\n double r[2], u[2];\n double obs[2];\n double U = 0;\n \n const double A = 0;\n const double B = 13000;\n const double n = 1;\n const double m = 2.5;\n\n const double force = 0.025;\n \n Fs[0] = Fs[1] = 0;\n obs[0] = 0.5;\n obs[1] = 0;\n\n r[0] -= obs[0];\n r[1] -= obs[1];\n u = r;\n normalize(u);\n \n const double length = 4.0; \/\/TODO: fix param\n const double d = sqrt(r[0]*r[0] + r[1]*r[1]) \/ length;\n U = -A\/pow(d, n) + B\/pow(d, m);\n \n u[0] *= U;\n u[1] *= U;\n \/\/Fs += VRotate2D(-Units[i].fOrientation, U * u);\n \n cmd_pub.publish(cmd);\n\n return 0;\n}\n\n<commit_msg>Implement take off<commit_after>#include <ros\/ros.h> \n#include <geometry_msgs\/Twist.h> \n#include <math>\n\nstatic const float tol = 0.000000000000001f;\n\nvoid normalize(double &vec[2]){\n float m = sqrt(vec[0]*vec[0] + vec[1]*vec[1]);\n if(tol <= m) m = 1;\n vec[0] \/= m;\n vec[1] \/= m;\n\n if(fabs(vec[0]) < tol) vec[0] = 0.0f;\n if(fabs(vec[1]) < tol) vec[1] = 0.0f;\n}\n\nint main(int argc, char *argv[]){\n ros::NodeHandle node;\n ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10);\n \n ros::Duration(1).sleep();\n geometry_msgs::Twist cmd;\n cmd.linear.z = 0.3;\n cmd_pub.publish(cmd);\n ros::Duration(1).sleep();\n \n cmd.linear.z = 0;\n cmd_pub.publish(cmd);\n ros::Duration(1).sleep();\n \n \/*\n double Fs[2];\n double r[2], u[2];\n double obs[2];\n double U = 0;\n \n const double A = 0;\n const double B = 13000;\n const double n = 1;\n const double m = 2.5;\n\n const double force = 0.025;\n \n Fs[0] = Fs[1] = 0;\n obs[0] = 0.5;\n obs[1] = 0;\n\n r[0] -= obs[0];\n r[1] -= obs[1];\n u = r;\n normalize(u);\n \n \/\/const double length = 4.0; \/\/TODO: fix param\n \/\/const double d = sqrt(r[0]*r[0] + r[1]*r[1]) \/ length;\n const double d = sqrt(r[0]*r[0] + r[1]*r[1]);\n U = -A\/pow(d, n) + B\/pow(d, m);\n \n Fs[0] += U * u[0];\n Fs[1] += U * u[1];\n *\/\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef SRC_ONLINE_ADAGRAD_RDA_HPP_\n#define SRC_ONLINE_ADAGRAD_RDA_HPP_\n\n#include <Eigen\/Dense>\n#include <cmath>\n#include \"utility.hpp\"\n\nclass ADAGRAD_RDA {\nprivate :\n const std::size_t kDim;\n const double kEta;\n const double kLambda;\n\nprivate :\n std::size_t _timestep;\n Eigen::VectorXd _w;\n Eigen::VectorXd _h;\n Eigen::VectorXd _g;\n\npublic :\n ADAGRAD_RDA(const std::size_t dim, const double eta, const double lambda)\n : kDim(dim),\n kEta(eta),\n kLambda(lambda),\n _timestep(0),\n _w(Eigen::VectorXd::Zero(kDim)),\n _h(Eigen::VectorXd::Zero(kDim)),\n _g(Eigen::VectorXd::Zero(kDim)) {\n static_assert(std::numeric_limits<decltype(dim)>::max() > 0, \"Dimension Error. (Dimension > 0)\");\n static_assert(std::numeric_limits<decltype(eta)>::max() > 0, \"Hyper Parameter Error. (eta > 0)\");\n static_assert(std::numeric_limits<decltype(lambda)>::max() > 0, \"Hyper Parameter Error. (lambda > 0)\");\n assert(dim > 0);\n assert(eta > 0);\n assert(lambda > 0);\n }\n\n virtual ~ADAGRAD_RDA() { }\n\n double calculate_margin(const Eigen::VectorXd& x) const {\n return _w.dot(x);\n }\n\n double suffer_loss(const Eigen::VectorXd& x, const int y) const {\n return std::max(0.0, 1.0 - y * _w.dot(x));\n }\n\n void update(const Eigen::VectorXd& feature, const int label) {\n if (suffer_loss(feature, label) <= 0.0) { return ; }\n\n _timestep++;\n utility::enumerate(feature.data(), feature.data() + feature.size(), 0,\n [&](const int index, const double value) {\n const auto gradiant = -label * value;\n _g[index] += gradiant;\n _h[index] += gradiant * gradiant;\n\n const auto sign = _g[index] >= 0 ? 1 : -1;\n const auto eta = kEta \/ std::sqrt(_h[index]);\n const auto u = std::abs(_g[index]) \/ _timestep;\n\n _w[index] = (u <= kLambda) ? 0.0 : -sign * eta * _timestep * (u - kLambda);\n });\n\n }\n\n int predict(const Eigen::VectorXd& x) const {\n return calculate_margin(x) > 0.0 ? 1 : -1;\n }\n\n};\n\n#endif \/\/SRC_ONLINE_ADAGRAD_RDA_HPP_\n<commit_msg>bool値を返すようにした<commit_after>#ifndef SRC_ONLINE_ADAGRAD_RDA_HPP_\n#define SRC_ONLINE_ADAGRAD_RDA_HPP_\n\n#include <Eigen\/Dense>\n#include <cmath>\n#include \"utility.hpp\"\n\nclass ADAGRAD_RDA {\nprivate :\n const std::size_t kDim;\n const double kEta;\n const double kLambda;\n\nprivate :\n std::size_t _timestep;\n Eigen::VectorXd _w;\n Eigen::VectorXd _h;\n Eigen::VectorXd _g;\n\npublic :\n ADAGRAD_RDA(const std::size_t dim, const double eta, const double lambda)\n : kDim(dim),\n kEta(eta),\n kLambda(lambda),\n _timestep(0),\n _w(Eigen::VectorXd::Zero(kDim)),\n _h(Eigen::VectorXd::Zero(kDim)),\n _g(Eigen::VectorXd::Zero(kDim)) {\n static_assert(std::numeric_limits<decltype(dim)>::max() > 0, \"Dimension Error. (Dimension > 0)\");\n static_assert(std::numeric_limits<decltype(eta)>::max() > 0, \"Hyper Parameter Error. (eta > 0)\");\n static_assert(std::numeric_limits<decltype(lambda)>::max() > 0, \"Hyper Parameter Error. (lambda > 0)\");\n assert(dim > 0);\n assert(eta > 0);\n assert(lambda > 0);\n }\n\n virtual ~ADAGRAD_RDA() { }\n\n double calculate_margin(const Eigen::VectorXd& x) const {\n return _w.dot(x);\n }\n\n double suffer_loss(const Eigen::VectorXd& x, const int y) const {\n return std::max(0.0, 1.0 - y * _w.dot(x));\n }\n\n bool update(const Eigen::VectorXd& feature, const int label) {\n if (suffer_loss(feature, label) <= 0.0) { return false; }\n\n _timestep++;\n utility::enumerate(feature.data(), feature.data() + feature.size(), 0,\n [&](const int index, const double value) {\n const auto gradiant = -label * value;\n _g[index] += gradiant;\n _h[index] += gradiant * gradiant;\n\n const auto sign = _g[index] >= 0 ? 1 : -1;\n const auto eta = kEta \/ std::sqrt(_h[index]);\n const auto u = std::abs(_g[index]) \/ _timestep;\n\n _w[index] = (u <= kLambda) ? 0.0 : -sign * eta * _timestep * (u - kLambda);\n });\n return true;\n\n }\n\n int predict(const Eigen::VectorXd& x) const {\n return calculate_margin(x) > 0.0 ? 1 : -1;\n }\n\n};\n\n#endif \/\/SRC_ONLINE_ADAGRAD_RDA_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <tansa\/action.h>\n#include <tansa\/control.h>\n#include <tansa\/core.h>\n#include <tansa\/jocsParser.h>\n#include <tansa\/config.h>\n#include <tansa\/jocsPlayer.h>\n#include <tansa\/mocap.h>\n#include <tansa\/gazebo.h>\n#include <tansa\/osc.h>\n\n#ifdef __linux__\n#include <sys\/signal.h>\n#endif\n\/\/TODO check if these work on OSX\n#include <dirent.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace tansa;\n\nstatic bool running;\nstatic bool killmode = false;\nstatic bool pauseMode = false;\nstatic bool stopMode = false;\nstatic bool playMode = false;\nstatic bool prepareMode = false;\nstatic float scale = 1.0;\nstatic JocsPlayer* player = nullptr;\nstatic vector<Vehicle *> vehicles;\nstatic std::vector<vehicle_config> vconfigs;\nstatic vector<unsigned> jocsActiveIds;\n\nvoid signal_sigint(int s) {\n\t\/\/ TODO: Prevent\n\trunning = false;\n}\n\n\/* For sending a system state update to the gui *\/\nvoid send_status_message() {\n\n\tjson j;\n\n\tj[\"type\"] = \"status\";\n\tj[\"time\"] = player->currentTime();\n\n\tjson vehs = json::array();\n\tfor(int i = 0; i < vehicles.size(); i++) {\n\t\tjson v;\n\t\tv[\"id\"] = vconfigs[i].net_id;\n\t\tv[\"role\"] = i <= jocsActiveIds.size() - 1? jocsActiveIds[i] : -1;\n\t\tv[\"connected\"] = vehicles[i]->connected;\n\t\tv[\"armed\"] = vehicles[i]->armed;\n\t\tv[\"tracking\"] = vehicles[i]->tracking;\n\n\t\tjson pos = json::array();\n\t\tpos.push_back(vehicles[i]->state.position.x());\n\t\tpos.push_back(vehicles[i]->state.position.y());\n\t\tpos.push_back(vehicles[i]->state.position.z());\n\t\tv[\"position\"] = pos;\n\n\t\tjson bat = {\n\t\t\t{\"voltage\", vehicles[i]->battery.voltage},\n\t\t\t{\"percent\", vehicles[i]->battery.percent}\n\t\t};\n\t\tv[\"battery\"] = bat;\n\n\t\tvehs.push_back(v);\n\t}\n\tj[\"vehicles\"] = vehs;\n\n\n\tjson global;\n\tglobal[\"playing\"] = player->isPlaying();\n\tglobal[\"ready\"] = player->isReady();\n\tj[\"global\"] = global;\n\n\ttansa::send_message(j);\n}\t\n\nvoid send_file_list() {\n\tjson j;\n\n\tj[\"type\"] = \"list_reply\";\n\tjson files = json::array();\n\tDIR *dir;\n\tstruct dirent *ent;\n\tif ((dir = opendir (\"data\")) != NULL) {\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tif(ent->d_type == DT_REG && std::string(ent->d_name).find(\".jocs\") != std::string::npos)\t\n\t\t\t\tfiles.push_back(std::string(ent->d_name));\n\t\t}\n\t\tclosedir (dir);\n\t} else {\n\t\t\/* could not open directory *\/\n\t\t\/\/TODO Do something intelligent here\n\t}\n\tj[\"files\"] = files;\n\ttansa::send_message(j);\n}\n\nvoid load_jocs_file(const json &data){\n\tif(player == nullptr){\n\t\t\/\/TODO: Send some kinda error code here\n\t\treturn;\n\t}\n\tstd::string file = data[\"filename\"];\n\tint cue = data[\"cue\"];\n\t\/\/TODO: Prepare the jocs file to start at this cue.\n\t\/\/TODO: Need to make sure this gets deleted. Will have to delete inside the JocsPlayer class when we load a new file.\n\t\/\/ In other words, we transfer ownership of the jocs object to the player here.\n\tauto jocs = Jocs::Parse(\"data\/\"+ file, scale);\n\tplayer->loadJocs(jocs);\n\tauto breakpoints = jocs->GetBreakpoints();\n\tjson j;\n\tj[\"type\"] = \"load_reply\";\n\tjson nums = json::array();\n\tfor(auto& b : breakpoints){\n\t\tnums.push_back(b.GetNumber());\n\t}\n\tjson positions = json::array();\n\tfor(auto& b : breakpoints){\n\t\t\/\/TODO: need to fill in the starting positions. Not contained in breakpoints currently\n\t}\n\tj[\"cues\"] = nums;\n\tj[\"target_positions\"] = positions;\n\ttansa::send_message(j);\n\n}\n\nvoid socket_on_message(const json &data) {\n\n\tstring type = data[\"type\"];\n\n\tif(type == \"prepare\") {\n\t\tprintf(\"Preparing...\\n\");\n\t\tprepareMode = true;\n\t} else if(type == \"play\") {\n\t\tprintf(\"Playing...\\n\");\n\t\tplayMode = true;\n\t} else if(type == \"land\") {\n\t\tplayer->land();\n\t} else if (type == \"pause\") {\n\t\tprintf(\"Pausing...\\n\");\n\t\tpauseMode = true;\n\t} else if (type == \"stop\") {\n\t\tprintf(\"Stopping...\\n\");\n\t\tstopMode = true;\n\t} else if (type == \"reset\") {\n\t\tprintf(\"Resetting...\\n\");\n\t} else if (type == \"list\"){\n\t\tprintf(\"Sending file list...\\n\");\n\t\tsend_file_list();\n\t} else if (type == \"load\"){\n\t\tprintf(\"Loading jocs file...\\n\");\n\t\tload_jocs_file(data);\n\t} else if(type == \"kill\") {\n\t\tbool enabled = data[\"enabled\"];\n\t\tprintf(\"Killing...\\n\");\n\t\tkillmode = enabled;\n\t} else {\n\t\t\/\/ TODO: Send an error message back to the browser\n\t\tprintf(\"Unexpected message type recieved!\\n\");\n\t}\n}\n\n\nvoid osc_on_message(OSCMessage &msg) {\n\n\t\/\/ Address will look something like: '\/cue\/0101\/start'\n\tif(msg.address[0] == \"cue\") {\n\n\t\tint num = std::stoi(msg.address[1]);\n\n\t\tif(msg.address[2] == \"load\") {\n\t\t\tplayer->prepare();\n\t\t}\n\t\telse if(msg.address[2] == \"start\") {\n\t\t\tprintf(\"Starting at cue #: %d\\n\", num);\n\n\t\t\t\/\/ Assert that it is already prepared at the given cue\n\n\t\t\tplayer->play();\n\t\t}\n\n\t}\n\n\t\/*\n\tprintf(\"Address:\\n\");\n\tfor(auto str : msg.address)\n\t\tprintf(\"- %s\\n\", str.c_str());\n\n\tprintf(\"\\nArgs:\\n\");\n\tfor(auto str : msg.args)\n\t\tprintf(\"- %s\\n\", str.c_str());\n\t*\/\n\n}\n\npthread_t console_handle;\n\nvoid *console_thread(void *arg) {\n\n\twhile(running) {\n\n\t\t\/\/ Read a command\n\t\tcout << \"> \";\n\t\tstring line;\n\t\tgetline(cin, line);\n\n\t\t\/\/ Split into arguments\n\t\tvector<string> args;\n\t\tistringstream iss(line);\n\t\twhile(!iss.eof()) {\n\t\t\tstring a;\n\t\t\tiss >> a;\n\n\t\t\tif(iss.fail())\n\t\t\t\tbreak;\n\n\t\t\targs.push_back(a);\n\t\t}\n\n\n\t\tif(args.size() == 0)\n\t\t\tcontinue;\n\n\n\n\t\tif (args[0] == \"prepare\") {\n\t\t\tcout << \"Preparing...\" << endl;\n\t\t\tprepareMode = true;\n\t\t} else if (args[0] == \"play\") {\n\t\t\tcout << \"Playing...\" << endl;\n\t\t\tplayMode = true;\n\t\t} else if (args[0] == \"pause\") {\n\t\t\tcout << \"Pausing...\" << endl;\n\t\t\tpauseMode = true;\n\t\t} else if (args[0] == \"stop\") {\n\t\t\tcout << \"Stopping...\" << endl;\n\t\t\tstopMode = true;\n\t\t} else if (args[0] == \"land\") {\n\t\t\tcout << \"Landing...\" << endl;\n\t\t\tplayer->land();\n\t\t} else if (args[0] == \"kill\") {\n\t\t\tkillmode = args.size() <= 1 || !(args[1] == \"off\");\n\t\t}\n\n\n\t}\n\n}\n\nvoid console_start() {\n\tpthread_create(&console_handle, NULL, console_thread, NULL);\n}\n\n\nint main(int argc, char *argv[]) {\n\n\tassert(argc == 2);\n\tstring configPath = argv[1];\n\n\tifstream configStream(configPath);\n\tif (!configStream) throw \"Unable to read config file!\";\n\n\t\/\/\/ Parse the config file\n\tstd::string configData((std::istreambuf_iterator<char>(configStream)), std::istreambuf_iterator<char>());\n\tnlohmann::json rawJson = nlohmann::json::parse(configData);\n\thardware_config config;\n\tstring jocsPath = rawJson[\"jocsPath\"];\n\tvector<unsigned> activeids = rawJson[\"jocsActiveIds\"];\n\tjocsActiveIds = activeids;\n\tbool useMocap = rawJson[\"useMocap\"];\n\tscale = rawJson[\"theaterScale\"];\n\tbool enableMessaging = rawJson[\"enableMessaging\"];\n\tbool enableOSC = rawJson[\"enableOSC\"];\n\n\tif (useMocap) {\n\t\tnlohmann::json hardwareConfig = rawJson[\"hardwareConfig\"];\n\t\tconfig.clientAddress = hardwareConfig[\"clientAddress\"];\n\t\tconfig.serverAddress = hardwareConfig[\"serverAddress\"];\n\t}\n\n\tvconfigs.resize(rawJson[\"vehicles\"].size());\n\tfor(unsigned i = 0; i < rawJson[\"vehicles\"].size(); i++) {\n\t\tvconfigs[i].net_id = rawJson[\"vehicles\"][i][\"net_id\"];\n\t\tif(useMocap) {\n\t\t\tvconfigs[i].lport = 14550 + 10*vconfigs[i].net_id;\n\t\t\tvconfigs[i].rport = 14555;\n\t\t}\n\t\telse { \/\/ The simulated ones are zero-indexed and\n\t\t\tvconfigs[i].lport = 14550 + 10*(vconfigs[i].net_id - 1);\n\t\t\tvconfigs[i].rport = 14555 + 10*(vconfigs[i].net_id - 1);\n\t\t}\n\t}\n\n\tJocs *jocs = Jocs::Parse(jocsPath, scale);\n\n\tauto homes = jocs->GetHomes();\n\n\t\/\/ Only pay attention to homes of active drones\n\tstd::vector<Point> spawns;\n\tfor (int i = 0; i < jocsActiveIds.size(); i++) {\n\t\tint chosenId = jocsActiveIds[i];\n\t\t\/\/ We assume the user only configured for valid IDs..\n\t\tspawns.push_back(homes[chosenId]);\n\t\tspawns[i].z() = 0;\n\t}\n\n\ttansa::init(enableMessaging);\n\n\tif(enableMessaging) {\n\t\ttansa::on_message(socket_on_message);\n\t}\n\n\n\tMocap *mocap = nullptr;\n\tGazeboConnector *gazebo = nullptr;\n\n\t\/\/ Only pay attention to homes of active drones\n\t\/\/ TODO: Have a better check for mocap initialization\/health\n\tif (useMocap) {\n\t\tmocap = new Mocap();\n\t\tmocap->connect(config.clientAddress, config.serverAddress);\n\t} else {\n\t\tgazebo = new GazeboConnector();\n\t\tgazebo->connect();\n\t\tgazebo->spawn(spawns);\n\t}\n\n\tint n = spawns.size();\n\n\tif (n > vconfigs.size()) {\n\t\tprintf(\"Not enough drones on the network\\n\");\n\t\treturn 1;\n\t}\n\n\tvehicles.resize(n);\n\n\tfor(int i = 0; i < n; i++) {\n\t\tconst vehicle_config &v = vconfigs[i];\n\n\t\tvehicles[i] = new Vehicle();\n\n\t\t\/\/ Load default parameters\n\t\tvehicles[i]->readParams(\".\/config\/params\/default.json\");\n\t\t\/\/ TODO: Also read in per-drone ones\n\n\t\tvehicles[i]->connect(v.lport, v.rport);\n\t\tif (useMocap) {\n\t\t\tmocap->track(vehicles[i], i+1);\n\t\t} else {\n\t\t\tgazebo->track(vehicles[i], i);\n\t\t}\n\t}\n\n\tif(enableOSC) {\n\t\tOSC *osc = new OSC();\n\t\tosc->start(53100);\n\t\tosc->set_listener(osc_on_message);\n\t}\n\n\n\n\n\tplayer = new JocsPlayer(vehicles, jocsActiveIds);\n\tplayer->loadJocs(jocs);\n\n\trunning = true;\n\tsignal(SIGINT, signal_sigint);\n\n\tint i = 0;\n\n\t\/*\n\t\/\/ For sample lighting demo\n\tfloat level = 0;\n\tfloat dl = 0.005;\n\t*\/\n\n\tsignal(SIGINT, signal_sigint);\n\tprintf(\"running...\\n\");\n\trunning = true;\n\n\tconsole_start();\n\n\tRate r(100);\n\twhile(running) {\n\n\t\t\/\/ Regular status messages\n\t\tif(enableMessaging && i % 20 == 0) {\n\t\t\tsend_status_message();\n\t\t}\n\n\t\tif (killmode) {\n\t\t\tfor(Vehicle *v : vehicles)\n\t\t\t\tv->terminate();\n\t\t} else if (prepareMode) {\n\t\t\tprepareMode = false;\n\t\t\tplayer->prepare();\n\t\t} else if (playMode) {\n\t\t\tplayMode = false;\n\t\t\tplayer->play();\n\t\t} else if (pauseMode) {\n\t\t\tpauseMode = false;\n\t\t\tplayer->pause();\n\t\t} else if (stopMode) {\n\t\t\tstopMode = false;\n\t\t\tplayer->stop();\n\t\t} else {\n\t\t\tplayer->step();\n\t\t}\n\n\t\tr.sleep();\n\t\ti++;\n\t}\n\n\t\/\/\/ Cleanup\n\tif (useMocap) {\n\t\tmocap->disconnect();\n\t\tdelete mocap;\n\t} else {\n\t\tgazebo->disconnect();\n\t\tdelete gazebo;\n\t}\n\n\t\/\/ Stop all vehicles\n\tfor(int vi = 0; vi < n; vi++) {\n\t\tVehicle *v = vehicles[vi];\n\t\tv->disconnect();\n\t\tdelete v;\n\t}\n\n\tplayer->cleanup();\n\n\tprintf(\"Done!\\n\");\n}\n<commit_msg>Changes to gcs to be able to not segault on file upload<commit_after>#include <tansa\/action.h>\n#include <tansa\/control.h>\n#include <tansa\/core.h>\n#include <tansa\/jocsParser.h>\n#include <tansa\/config.h>\n#include <tansa\/jocsPlayer.h>\n#include <tansa\/mocap.h>\n#include <tansa\/gazebo.h>\n#include <tansa\/osc.h>\n\n#ifdef __linux__\n#include <sys\/signal.h>\n#endif\n\/\/TODO check if these work on OSX\n#include <dirent.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace tansa;\n\nstatic bool running;\nstatic bool killmode = false;\nstatic bool pauseMode = false;\nstatic bool stopMode = false;\nstatic bool playMode = false;\nstatic bool prepareMode = false;\nstatic float scale = 1.0;\nstatic JocsPlayer* player = nullptr;\nstatic vector<Vehicle *> vehicles;\nstatic std::vector<vehicle_config> vconfigs;\nstatic vector<unsigned> jocsActiveIds;\n\nvoid signal_sigint(int s) {\n\t\/\/ TODO: Prevent\n\trunning = false;\n}\n\n\/* For sending a system state update to the gui *\/\nvoid send_status_message() {\n\n\tjson j;\n\n\tj[\"type\"] = \"status\";\n\tj[\"time\"] = player->currentTime();\n\n\tjson vehs = json::array();\n\tfor(int i = 0; i < vehicles.size(); i++) {\n\t\tjson v;\n\t\tv[\"id\"] = vconfigs[i].net_id;\n\t\tv[\"role\"] = i <= jocsActiveIds.size() - 1? jocsActiveIds[i] : -1;\n\t\tv[\"connected\"] = vehicles[i]->connected;\n\t\tv[\"armed\"] = vehicles[i]->armed;\n\t\tv[\"tracking\"] = vehicles[i]->tracking;\n\n\t\tjson pos = json::array();\n\t\tpos.push_back(vehicles[i]->state.position.x());\n\t\tpos.push_back(vehicles[i]->state.position.y());\n\t\tpos.push_back(vehicles[i]->state.position.z());\n\t\tv[\"position\"] = pos;\n\n\t\tjson bat = {\n\t\t\t{\"voltage\", vehicles[i]->battery.voltage},\n\t\t\t{\"percent\", vehicles[i]->battery.percent}\n\t\t};\n\t\tv[\"battery\"] = bat;\n\n\t\tvehs.push_back(v);\n\t}\n\tj[\"vehicles\"] = vehs;\n\n\n\tjson global;\n\tglobal[\"playing\"] = player->isPlaying();\n\tglobal[\"ready\"] = player->isReady();\n\tj[\"global\"] = global;\n\n\ttansa::send_message(j);\n}\t\n\nvoid send_file_list() {\n\tjson j;\n\n\tj[\"type\"] = \"list_reply\";\n\tjson files = json::array();\n\tDIR *dir;\n\tstruct dirent *ent;\n\tif ((dir = opendir (\"data\")) != NULL) {\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tif(ent->d_type == DT_REG && std::string(ent->d_name).find(\".jocs\") != std::string::npos)\t\n\t\t\t\tfiles.push_back(std::string(ent->d_name));\n\t\t}\n\t\tclosedir (dir);\n\t} else {\n\t\t\/* could not open directory *\/\n\t\t\/\/TODO Do something intelligent here\n\t}\n\tj[\"files\"] = files;\n\ttansa::send_message(j);\n}\n\nvoid load_jocs_file(const json &data){\n\tif(player == nullptr){\n\t\t\/\/TODO: Send some kinda error code here\n\t\treturn;\n\t}\n\tstd::string file = data[\"filename\"];\n\t\/\/int cue = data[\"cue\"];\n\t\/\/TODO: Prepare the jocs file to start at this cue.\n\t\/\/TODO: Need to make sure this gets deleted. Will have to delete inside the JocsPlayer class when we load a new file.\n\t\/\/ In other words, we transfer ownership of the jocs object to the player here.\n\tauto jocs = Jocs::Parse(\"data\/\"+ file, scale);\n\tplayer->loadJocs(jocs);\n\tauto breakpoints = jocs->GetBreakpoints();\n\tjson j;\n\tj[\"type\"] = \"load_reply\";\n\tjson nums = json::array();\n\tfor(auto& b : breakpoints){\n\t\tnums.push_back(b.GetNumber());\n\t}\n\tjson positions = json::array();\n\tfor(auto& b : breakpoints){\n\t\t\/\/TODO: need to fill in the starting positions. Not contained in breakpoints currently\n\t}\n\tj[\"cues\"] = nums;\n\tj[\"target_positions\"] = positions;\n\ttansa::send_message(j);\n\n}\n\nvoid socket_on_message(const json &data) {\n\n\tstring type = data[\"type\"];\n\n\tif(type == \"prepare\") {\n\t\tprintf(\"Preparing...\\n\");\n\t\tprepareMode = true;\n\t} else if(type == \"play\") {\n\t\tprintf(\"Playing...\\n\");\n\t\tplayMode = true;\n\t} else if(type == \"land\") {\n\t\tplayer->land();\n\t} else if (type == \"pause\") {\n\t\tprintf(\"Pausing...\\n\");\n\t\tpauseMode = true;\n\t} else if (type == \"stop\") {\n\t\tprintf(\"Stopping...\\n\");\n\t\tstopMode = true;\n\t} else if (type == \"reset\") {\n\t\tprintf(\"Resetting...\\n\");\n\t} else if (type == \"list\"){\n\t\tprintf(\"Sending file list...\\n\");\n\t\tsend_file_list();\n\t} else if (type == \"load\"){\n\t\tprintf(\"Loading jocs file...\\n\");\n\t\tload_jocs_file(data);\n\t} else if(type == \"kill\") {\n\t\tbool enabled = data[\"enabled\"];\n\t\tprintf(\"Killing...\\n\");\n\t\tkillmode = enabled;\n\t} else {\n\t\t\/\/ TODO: Send an error message back to the browser\n\t\tprintf(\"Unexpected message type recieved!\\n\");\n\t}\n}\n\n\nvoid osc_on_message(OSCMessage &msg) {\n\n\t\/\/ Address will look something like: '\/cue\/0101\/start'\n\tif(msg.address[0] == \"cue\") {\n\n\t\tint num = std::stoi(msg.address[1]);\n\n\t\tif(msg.address[2] == \"load\") {\n\t\t\tplayer->prepare();\n\t\t}\n\t\telse if(msg.address[2] == \"start\") {\n\t\t\tprintf(\"Starting at cue #: %d\\n\", num);\n\n\t\t\t\/\/ Assert that it is already prepared at the given cue\n\n\t\t\tplayer->play();\n\t\t}\n\n\t}\n\n\t\/*\n\tprintf(\"Address:\\n\");\n\tfor(auto str : msg.address)\n\t\tprintf(\"- %s\\n\", str.c_str());\n\n\tprintf(\"\\nArgs:\\n\");\n\tfor(auto str : msg.args)\n\t\tprintf(\"- %s\\n\", str.c_str());\n\t*\/\n\n}\n\npthread_t console_handle;\n\nvoid *console_thread(void *arg) {\n\n\twhile(running) {\n\n\t\t\/\/ Read a command\n\t\tcout << \"> \";\n\t\tstring line;\n\t\tgetline(cin, line);\n\n\t\t\/\/ Split into arguments\n\t\tvector<string> args;\n\t\tistringstream iss(line);\n\t\twhile(!iss.eof()) {\n\t\t\tstring a;\n\t\t\tiss >> a;\n\n\t\t\tif(iss.fail())\n\t\t\t\tbreak;\n\n\t\t\targs.push_back(a);\n\t\t}\n\n\n\t\tif(args.size() == 0)\n\t\t\tcontinue;\n\n\n\n\t\tif (args[0] == \"prepare\") {\n\t\t\tcout << \"Preparing...\" << endl;\n\t\t\tprepareMode = true;\n\t\t} else if (args[0] == \"play\") {\n\t\t\tcout << \"Playing...\" << endl;\n\t\t\tplayMode = true;\n\t\t} else if (args[0] == \"pause\") {\n\t\t\tcout << \"Pausing...\" << endl;\n\t\t\tpauseMode = true;\n\t\t} else if (args[0] == \"stop\") {\n\t\t\tcout << \"Stopping...\" << endl;\n\t\t\tstopMode = true;\n\t\t} else if (args[0] == \"land\") {\n\t\t\tcout << \"Landing...\" << endl;\n\t\t\tplayer->land();\n\t\t} else if (args[0] == \"kill\") {\n\t\t\tkillmode = args.size() <= 1 || !(args[1] == \"off\");\n\t\t}\n\n\n\t}\n\n}\n\nvoid console_start() {\n\tpthread_create(&console_handle, NULL, console_thread, NULL);\n}\n\n\nint main(int argc, char *argv[]) {\n\n\tassert(argc == 2);\n\tstring configPath = argv[1];\n\n\tifstream configStream(configPath);\n\tif (!configStream) throw \"Unable to read config file!\";\n\n\t\/\/\/ Parse the config file\n\tstd::string configData((std::istreambuf_iterator<char>(configStream)), std::istreambuf_iterator<char>());\n\tnlohmann::json rawJson = nlohmann::json::parse(configData);\n\thardware_config config;\n\tstring jocsPath = rawJson[\"jocsPath\"];\n\tvector<unsigned> activeids = rawJson[\"jocsActiveIds\"];\n\tjocsActiveIds = activeids;\n\tbool useMocap = rawJson[\"useMocap\"];\n\tscale = rawJson[\"theaterScale\"];\n\tbool enableMessaging = rawJson[\"enableMessaging\"];\n\tbool enableOSC = rawJson[\"enableOSC\"];\n\n\tif (useMocap) {\n\t\tnlohmann::json hardwareConfig = rawJson[\"hardwareConfig\"];\n\t\tconfig.clientAddress = hardwareConfig[\"clientAddress\"];\n\t\tconfig.serverAddress = hardwareConfig[\"serverAddress\"];\n\t}\n\n\tvconfigs.resize(rawJson[\"vehicles\"].size());\n\tfor(unsigned i = 0; i < rawJson[\"vehicles\"].size(); i++) {\n\t\tvconfigs[i].net_id = rawJson[\"vehicles\"][i][\"net_id\"];\n\t\tif(useMocap) {\n\t\t\tvconfigs[i].lport = 14550 + 10*vconfigs[i].net_id;\n\t\t\tvconfigs[i].rport = 14555;\n\t\t}\n\t\telse { \/\/ The simulated ones are zero-indexed and\n\t\t\tvconfigs[i].lport = 14550 + 10*(vconfigs[i].net_id - 1);\n\t\t\tvconfigs[i].rport = 14555 + 10*(vconfigs[i].net_id - 1);\n\t\t}\n\t}\n\n\tJocs *jocs = Jocs::Parse(jocsPath, scale);\n\n\tauto homes = jocs->GetHomes();\n\n\t\/\/ Only pay attention to homes of active drones\n\tstd::vector<Point> spawns;\n\tfor (int i = 0; i < jocsActiveIds.size(); i++) {\n\t\tint chosenId = jocsActiveIds[i];\n\t\t\/\/ We assume the user only configured for valid IDs..\n\t\tspawns.push_back(homes[chosenId]);\n\t\tspawns[i].z() = 0;\n\t}\n\n\ttansa::init(enableMessaging);\n\n\tif(enableMessaging) {\n\t\ttansa::on_message(socket_on_message);\n\t}\n\n\n\tMocap *mocap = nullptr;\n\tGazeboConnector *gazebo = nullptr;\n\n\t\/\/ Only pay attention to homes of active drones\n\t\/\/ TODO: Have a better check for mocap initialization\/health\n\tif (useMocap) {\n\t\tmocap = new Mocap();\n\t\tmocap->connect(config.clientAddress, config.serverAddress);\n\t} else {\n\t\tgazebo = new GazeboConnector();\n\t\tgazebo->connect();\n\t\tgazebo->spawn(spawns);\n\t}\n\n\tint n = spawns.size();\n\n\tif (n > vconfigs.size()) {\n\t\tprintf(\"Not enough drones on the network\\n\");\n\t\treturn 1;\n\t}\n\n\tvehicles.resize(n);\n\n\tfor(int i = 0; i < n; i++) {\n\t\tconst vehicle_config &v = vconfigs[i];\n\n\t\tvehicles[i] = new Vehicle();\n\n\t\t\/\/ Load default parameters\n\t\tvehicles[i]->readParams(\".\/config\/params\/default.json\");\n\t\t\/\/ TODO: Also read in per-drone ones\n\n\t\tvehicles[i]->connect(v.lport, v.rport);\n\t\tif (useMocap) {\n\t\t\tmocap->track(vehicles[i], i+1);\n\t\t} else {\n\t\t\tgazebo->track(vehicles[i], i);\n\t\t}\n\t}\n\n\tif(enableOSC) {\n\t\tOSC *osc = new OSC();\n\t\tosc->start(53100);\n\t\tosc->set_listener(osc_on_message);\n\t}\n\n\n\n\n\tplayer = new JocsPlayer(vehicles, jocsActiveIds);\n\tplayer->loadJocs(jocs);\n\n\trunning = true;\n\tsignal(SIGINT, signal_sigint);\n\n\tint i = 0;\n\n\t\/*\n\t\/\/ For sample lighting demo\n\tfloat level = 0;\n\tfloat dl = 0.005;\n\t*\/\n\n\tsignal(SIGINT, signal_sigint);\n\tprintf(\"running...\\n\");\n\trunning = true;\n\n\tconsole_start();\n\n\tRate r(100);\n\twhile(running) {\n\n\t\t\/\/ Regular status messages\n\t\tif(enableMessaging && i % 20 == 0) {\n\t\t\tsend_status_message();\n\t\t}\n\n\t\tif (killmode) {\n\t\t\tfor(Vehicle *v : vehicles)\n\t\t\t\tv->terminate();\n\t\t} else if (prepareMode) {\n\t\t\tprepareMode = false;\n\t\t\tplayer->prepare();\n\t\t} else if (playMode) {\n\t\t\tplayMode = false;\n\t\t\tplayer->play();\n\t\t} else if (pauseMode) {\n\t\t\tpauseMode = false;\n\t\t\tplayer->pause();\n\t\t} else if (stopMode) {\n\t\t\tstopMode = false;\n\t\t\tplayer->stop();\n\t\t} else {\n\t\t\tplayer->step();\n\t\t}\n\n\t\tr.sleep();\n\t\ti++;\n\t}\n\n\t\/\/\/ Cleanup\n\tif (useMocap) {\n\t\tmocap->disconnect();\n\t\tdelete mocap;\n\t} else {\n\t\tgazebo->disconnect();\n\t\tdelete gazebo;\n\t}\n\n\t\/\/ Stop all vehicles\n\tfor(int vi = 0; vi < n; vi++) {\n\t\tVehicle *v = vehicles[vi];\n\t\tv->disconnect();\n\t\tdelete v;\n\t}\n\n\tplayer->cleanup();\n\n\tprintf(\"Done!\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gui.h\"\n\nextern Adafruit_ILI9341 tft;\nextern Pipeline *pipe;\nTouchScreen screen = TouchScreen(XP, YP, XM, YM);\n\nint freeRam ()\n{\n extern int __heap_start, *__brkval;\n int v;\n return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);\n}\n\n\nvoid Pipeline::segueTo(ViewController *nextController) {\n flush();\n if (_previousController != NULL) {\n delete _previousController;\n _previousController = NULL;\n }\n if (_viewController != NULL) {\n delete _viewController;\n }\n _viewController = nextController;\n _viewController->init();\n}\n\nvoid Pipeline::seguePopover(ViewController *popoverController) {\n flush();\n if (_previousController == NULL) {\n _previousController = _viewController;\n _previousController->deinit();\n }\n _viewController = popoverController;\n _viewController->init();\n}\n\nvoid Pipeline::segueBack() {\n if (_previousController == NULL) {\n \/\/ TODO: Inconsistent api\n#ifdef DEBUGV\n Serial.println(F(\"segue back called, no previous controller\"));\n#endif\n return;\n }\n flush();\n if (_viewController != NULL) {\n delete _viewController;\n }\n _viewController = _previousController;\n _previousController = NULL;\n _viewController->init();\n}\n\nvoid Pipeline::push(tickCallback fn, void *context) {\n if (_draining) {\n#ifdef DEBUGV\n Serial.println(F(\"ignoring push, draining\"));\n#endif\n return;\n }\n _callbacks[_push] = fn;\n _contexts[_push] = context;\n _push++;\n if (_push == SIZE) {\n _push = 0; \/\/ wrap\n }\n#ifdef DEBUG\n if (_push == _pop) {\n Serial.println(F(\"overflowed Pipeline\"));\n }\n#endif\n}\n\nvoid Pipeline::tick() {\n if (_viewController) {\n _viewController->tick();\n }\n if (!_callbacks[_pop]) {\n return;\n }\n int last = _pop;\n _pop++;\n if (_pop == SIZE) {\n _pop = 0; \/\/ wrap\n }\n\n void *context = _contexts[last];\n _callbacks[last](context);\n _callbacks[last] = NULL;\n _contexts[last] = NULL;\n}\n\nvoid Pipeline::flush() {\n _draining = true;\n while (_pop != _push) {\n tick();\n }\n _draining = false;\n}\n\nViewController::~ViewController() {}\n\nControl::~Control() {}\n\nvoid Clickable::tick() {\n if (screen.isTouching(\n _pos.x,\n _pos.y,\n _pos.x+_size.w,\n _pos.y+_size.h\n )) {\n _touching++;\n if (_touching == 1) {\n pipe->push(drawControlForwarder, this);\n }\n } else if (_touching > 0) {\n _touching = 0;\n if (_onClick != NULL) {\n pipe->push(_onClick, _onClickContext);\n }\n pipe->push(drawControlForwarder, this);\n }\n}\n\nvoid Clickable::then(tickCallback cb, void *context) {\n _onClick = cb;\n _onClickContext = context;\n}\n\nvoid Label::tick() {\n Clickable::tick();\n}\n\nvoid Label::draw() {\n int ox = _pos.x;\n int oy = _pos.y;\n if (_touching) {\n ox++;\n oy++;\n }\n tft.setTextColor(fontColor);\n int offset = CURSOR_Y_SMALL;\n if (fontSize == 1) {\n tft.setFont(&Inconsolata_g5pt7b);\n } else {\n tft.setFont(&Inconsolata_g8pt7b);\n offset = CURSOR_Y_LARGE;\n }\n if (centerLabel) {\n uint16_t w, h;\n int16_t x1, y1;\n tft.getTextBounds(_label, 10, 10, &x1, &y1, &w, &h);\n int x = (int) ox + (_size.w \/ 2) - ((int) w \/ 2);\n int y = (int) oy + (_size.h \/ 2) - ((int) h \/ 2);\n tft.setCursor(x, y + offset);\n tft.print(_label);\n } else {\n tft.setCursor(ox, oy+_size.h-2);\n tft.print(_label);\n }\n}\n\nvoid Label::setLabel(const char *label) {\n strcpy(_label, label);\n}\n\nvoid Button::tick() {\n Label::tick();\n}\n\nvoid Button::draw() {\n if (_touching) {\n tft.fillRect(_pos.x, _pos.y, _size.w, _size.h, touchColor);\n } else {\n tft.fillRect(_pos.x-1, _pos.y-1, _size.w, _size.h, bgColor);\n \/\/ TODO: Better drop shadow\n tft.drawFastVLine(_pos.x-1+_size.w, _pos.y-1, _size.h, ILI9341_BLACK);\n tft.drawFastHLine(_pos.x-1, _pos.y-1+_size.h, _size.w, ILI9341_BLACK);\n }\n\n Label::draw();\n}\n\nvoid Textbox::setValueSuffix(const char *suffix) {\n strcpy(_valueSuffixText, suffix);\n}\n\nvoid Textbox::setValue(const char *val) {\n strcpy(_value, val);\n}\n\nvoid Textbox::setValue(long val) {\n ltoa(val, _value, 10);\n}\n\nvoid Textbox::setValue(double val) {\n String str = String(val);\n strcpy(_value, str.c_str());\n}\n\nconst char *Textbox::getValue() {\n return _value;\n}\n\nvoid Textbox::tick() {\n Clickable::tick();\n}\n\nvoid Textbox::draw() {\n if (_fillBackground) {\n tft.fillRect(_pos.x, _pos.y, _size.w, _size.h, bgColor);\n _fillBackground = false;\n }\n if (fontSize == 1) {\n tft.setFont(&Inconsolata_g5pt7b);\n } else {\n tft.setFont(&Inconsolata_g8pt7b);\n }\n\n const char *valStr = _value;\n int valLength = strlen(valStr);\n if (_lastValLength > 0) {\n if (strcmp(_lastVal, valStr) == 0) {\n return;\n }\n\n tft.setCursor(_pos.x, _pos.y +_size.h-2);\n tft.setTextColor(bgColor);\n tft.print(_lastVal);\n\n\/\/ if (valLength != _lastValLength && _valueSuffixText[0] != 0) {\n\/\/ tft.setFont(&Inconsolata_g5pt7b);\n\/\/ tft.print(_valueSuffixText);\n\/\/ }\n }\n\n tft.setCursor(_pos.x, _pos.y +_size.h-2);\n tft.setTextColor(ILI9341_WHITE);\n tft.print(valStr);\n tft.setFont(&Inconsolata_g5pt7b);\n\/\/ if (valLength != _lastValLength) {\n\/\/ tft.setFont(&Inconsolata_g5pt7b);\n\/\/ tft.print(_valueSuffixText);\n\/\/ }\n strcpy(_lastVal, valStr);\n _lastValLength = valLength;\n}\n\nvoid drawControlForwarder(void *context) {\n static_cast<Control*>(context)->draw();\n}\n\nvoid drawViewControllerForwarder(void *context) {\n static_cast<ViewController*>(context)->draw();\n}<commit_msg>Fixed failing handset build.<commit_after>#include \"gui.h\"\n\nextern Adafruit_ILI9341 tft;\nextern Pipeline *pipe;\nTouchScreen screen = TouchScreen(XP, YP, XM, YM);\n\nvoid Pipeline::segueTo(ViewController *nextController) {\n flush();\n if (_previousController != NULL) {\n delete _previousController;\n _previousController = NULL;\n }\n if (_viewController != NULL) {\n delete _viewController;\n }\n _viewController = nextController;\n _viewController->init();\n}\n\nvoid Pipeline::seguePopover(ViewController *popoverController) {\n flush();\n if (_previousController == NULL) {\n _previousController = _viewController;\n _previousController->deinit();\n }\n _viewController = popoverController;\n _viewController->init();\n}\n\nvoid Pipeline::segueBack() {\n if (_previousController == NULL) {\n \/\/ TODO: Inconsistent api\n#ifdef DEBUGV\n Serial.println(F(\"segue back called, no previous controller\"));\n#endif\n return;\n }\n flush();\n if (_viewController != NULL) {\n delete _viewController;\n }\n _viewController = _previousController;\n _previousController = NULL;\n _viewController->init();\n}\n\nvoid Pipeline::push(tickCallback fn, void *context) {\n if (_draining) {\n#ifdef DEBUGV\n Serial.println(F(\"ignoring push, draining\"));\n#endif\n return;\n }\n _callbacks[_push] = fn;\n _contexts[_push] = context;\n _push++;\n if (_push == SIZE) {\n _push = 0; \/\/ wrap\n }\n#ifdef DEBUG\n if (_push == _pop) {\n Serial.println(F(\"overflowed Pipeline\"));\n }\n#endif\n}\n\nvoid Pipeline::tick() {\n if (_viewController) {\n _viewController->tick();\n }\n if (!_callbacks[_pop]) {\n return;\n }\n int last = _pop;\n _pop++;\n if (_pop == SIZE) {\n _pop = 0; \/\/ wrap\n }\n\n void *context = _contexts[last];\n _callbacks[last](context);\n _callbacks[last] = NULL;\n _contexts[last] = NULL;\n}\n\nvoid Pipeline::flush() {\n _draining = true;\n while (_pop != _push) {\n tick();\n }\n _draining = false;\n}\n\nViewController::~ViewController() {}\n\nControl::~Control() {}\n\nvoid Clickable::tick() {\n if (screen.isTouching(\n _pos.x,\n _pos.y,\n _pos.x+_size.w,\n _pos.y+_size.h\n )) {\n _touching++;\n if (_touching == 1) {\n pipe->push(drawControlForwarder, this);\n }\n } else if (_touching > 0) {\n _touching = 0;\n if (_onClick != NULL) {\n pipe->push(_onClick, _onClickContext);\n }\n pipe->push(drawControlForwarder, this);\n }\n}\n\nvoid Clickable::then(tickCallback cb, void *context) {\n _onClick = cb;\n _onClickContext = context;\n}\n\nvoid Label::tick() {\n Clickable::tick();\n}\n\nvoid Label::draw() {\n int ox = _pos.x;\n int oy = _pos.y;\n if (_touching) {\n ox++;\n oy++;\n }\n tft.setTextColor(fontColor);\n int offset = CURSOR_Y_SMALL;\n if (fontSize == 1) {\n tft.setFont(&Inconsolata_g5pt7b);\n } else {\n tft.setFont(&Inconsolata_g8pt7b);\n offset = CURSOR_Y_LARGE;\n }\n if (centerLabel) {\n uint16_t w, h;\n int16_t x1, y1;\n tft.getTextBounds(_label, 10, 10, &x1, &y1, &w, &h);\n int x = (int) ox + (_size.w \/ 2) - ((int) w \/ 2);\n int y = (int) oy + (_size.h \/ 2) - ((int) h \/ 2);\n tft.setCursor(x, y + offset);\n tft.print(_label);\n } else {\n tft.setCursor(ox, oy+_size.h-2);\n tft.print(_label);\n }\n}\n\nvoid Label::setLabel(const char *label) {\n strcpy(_label, label);\n}\n\nvoid Button::tick() {\n Label::tick();\n}\n\nvoid Button::draw() {\n if (_touching) {\n tft.fillRect(_pos.x, _pos.y, _size.w, _size.h, touchColor);\n } else {\n tft.fillRect(_pos.x-1, _pos.y-1, _size.w, _size.h, bgColor);\n \/\/ TODO: Better drop shadow\n tft.drawFastVLine(_pos.x-1+_size.w, _pos.y-1, _size.h, ILI9341_BLACK);\n tft.drawFastHLine(_pos.x-1, _pos.y-1+_size.h, _size.w, ILI9341_BLACK);\n }\n\n Label::draw();\n}\n\nvoid Textbox::setValueSuffix(const char *suffix) {\n strcpy(_valueSuffixText, suffix);\n}\n\nvoid Textbox::setValue(const char *val) {\n strcpy(_value, val);\n}\n\nvoid Textbox::setValue(long val) {\n ltoa(val, _value, 10);\n}\n\nvoid Textbox::setValue(double val) {\n String str = String(val);\n strcpy(_value, str.c_str());\n}\n\nconst char *Textbox::getValue() {\n return _value;\n}\n\nvoid Textbox::tick() {\n Clickable::tick();\n}\n\nvoid Textbox::draw() {\n if (_fillBackground) {\n tft.fillRect(_pos.x, _pos.y, _size.w, _size.h, bgColor);\n _fillBackground = false;\n }\n if (fontSize == 1) {\n tft.setFont(&Inconsolata_g5pt7b);\n } else {\n tft.setFont(&Inconsolata_g8pt7b);\n }\n\n const char *valStr = _value;\n int valLength = strlen(valStr);\n if (_lastValLength > 0) {\n if (strcmp(_lastVal, valStr) == 0) {\n return;\n }\n\n tft.setCursor(_pos.x, _pos.y +_size.h-2);\n tft.setTextColor(bgColor);\n tft.print(_lastVal);\n\n\/\/ if (valLength != _lastValLength && _valueSuffixText[0] != 0) {\n\/\/ tft.setFont(&Inconsolata_g5pt7b);\n\/\/ tft.print(_valueSuffixText);\n\/\/ }\n }\n\n tft.setCursor(_pos.x, _pos.y +_size.h-2);\n tft.setTextColor(ILI9341_WHITE);\n tft.print(valStr);\n tft.setFont(&Inconsolata_g5pt7b);\n\/\/ if (valLength != _lastValLength) {\n\/\/ tft.setFont(&Inconsolata_g5pt7b);\n\/\/ tft.print(_valueSuffixText);\n\/\/ }\n strcpy(_lastVal, valStr);\n _lastValLength = valLength;\n}\n\nvoid drawControlForwarder(void *context) {\n static_cast<Control*>(context)->draw();\n}\n\nvoid drawViewControllerForwarder(void *context) {\n static_cast<ViewController*>(context)->draw();\n}<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\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#include \"parser\/EDDIGrammar.hpp\"\n\nusing namespace eddic;\n\nEddiGrammar::EddiGrammar(const Lexer& lexer) : \n EddiGrammar::base_type(program, \"EDDI Grammar\"), \n value(lexer), \n condition(lexer),\n type(lexer){\n \n else_if_ %= \n lexer.else_ \n >> lexer.if_ \n >> lexer.left_parenth \n >> condition \n >> lexer.right_parenth \n >> lexer.left_brace\n >> *(instruction)\n >> lexer.right_brace;\n\n else_ %= \n lexer.else_ \n >> lexer.left_brace\n >> *(instruction)\n >> lexer.right_brace;\n\n if_ %= \n lexer.if_ \n >> lexer.left_parenth \n >> condition \n >> lexer.right_parenth \n >> lexer.left_brace \n >> *(instruction) \n >> lexer.right_brace\n >> *(else_if_)\n >> -(else_);\n \n for_ %= \n lexer.for_ \n > lexer.left_parenth \n > -declaration \n > lexer.stop \n > -condition \n > lexer.stop \n > -repeatable_instruction \n > lexer.right_parenth \n > lexer.left_brace\n > (*instruction)\n > lexer.right_brace;\n \n foreach_ = \n lexer.foreach_ \n >> lexer.left_parenth \n >> lexer.word \n >> lexer.word \n >> lexer.from_ \n >> lexer.integer \n >> lexer.to_ \n >> lexer.integer \n >> lexer.right_parenth \n >> lexer.left_brace \n >> *(instruction)\n >> lexer.right_brace;\n \n foreachin_ = \n lexer.foreach_ \n >> lexer.left_parenth \n >> lexer.word \n >> lexer.word \n >> lexer.in_ \n >> lexer.word \n >> lexer.right_parenth \n >> lexer.left_brace \n >> *(instruction)\n >> lexer.right_brace;\n \n while_ %=\n lexer.while_ \n > lexer.left_parenth \n > condition \n > lexer.right_parenth \n > lexer.left_brace \n > *(instruction)\n > lexer.right_brace;\n\n declaration %= \n lexer.word \n >> lexer.word \n >> -(lexer.assign >> value);\n \n arrayDeclaration %= \n lexer.word \n >> lexer.word \n >> lexer.left_bracket\n >> lexer.integer\n >> lexer.right_bracket;\n \n assignment %= \n lexer.word \n >> lexer.assign \n >> value;\n\n return_ %=\n lexer.return_\n >> value;\n \n arrayAssignment %= \n lexer.word \n >> lexer.left_bracket\n >> value\n >> lexer.right_bracket\n >> lexer.assign \n >> value;\n \n globalDeclaration %= \n lexer.word \n >> lexer.word \n >> -(lexer.assign >> value.constant)\n >> lexer.stop;\n \n globalArrayDeclaration %= \n lexer.word \n >> lexer.word \n >> lexer.left_bracket\n >> lexer.integer\n >> lexer.right_bracket\n >> lexer.stop;\n\n functionCall %=\n lexer.word\n >> lexer.left_parenth\n >> -( value >> *( lexer.comma > value))\n >> lexer.right_parenth;\n \n swap %= \n lexer.word \n >> lexer.swap \n >> lexer.word;\n \n instruction %= \n (functionCall > lexer.stop)\n | (assignment > lexer.stop)\n | (declaration >> lexer.stop)\n | (arrayDeclaration >> lexer.stop)\n | (arrayAssignment > lexer.stop)\n | (return_ > lexer.stop)\n | if_\n | for_\n | while_\n | foreach_\n | foreachin_\n | (swap > lexer.stop);\n\n repeatable_instruction = assignment | declaration | swap;\n \n arg %= \n type \n >> lexer.word;\n \n function %= \n lexer.word \n >> lexer.word\n >> lexer.left_parenth\n >> -( arg >> *( lexer.comma > arg))\n >> lexer.right_parenth\n >> lexer.left_brace\n >> *(instruction)\n >> lexer.right_brace;\n\n program %=\n qi::eps \n >> *(function | globalDeclaration | globalArrayDeclaration);\n\n \/\/Name the rules\n globalDeclaration.name(\"EDDI global variable\");\n function.name(\"EDDI function declaration\");\n program.name(\"EDDI program\");\n}\n<commit_msg>Fix the grammar for return values<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\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#include \"parser\/EDDIGrammar.hpp\"\n\nusing namespace eddic;\n\nEddiGrammar::EddiGrammar(const Lexer& lexer) : \n EddiGrammar::base_type(program, \"EDDI Grammar\"), \n value(lexer), \n condition(lexer),\n type(lexer){\n \n else_if_ %= \n lexer.else_ \n >> lexer.if_ \n >> lexer.left_parenth \n >> condition \n >> lexer.right_parenth \n >> lexer.left_brace\n >> *(instruction)\n >> lexer.right_brace;\n\n else_ %= \n lexer.else_ \n >> lexer.left_brace\n >> *(instruction)\n >> lexer.right_brace;\n\n if_ %= \n lexer.if_ \n >> lexer.left_parenth \n >> condition \n >> lexer.right_parenth \n >> lexer.left_brace \n >> *(instruction) \n >> lexer.right_brace\n >> *(else_if_)\n >> -(else_);\n \n for_ %= \n lexer.for_ \n > lexer.left_parenth \n > -declaration \n > lexer.stop \n > -condition \n > lexer.stop \n > -repeatable_instruction \n > lexer.right_parenth \n > lexer.left_brace\n > (*instruction)\n > lexer.right_brace;\n \n foreach_ = \n lexer.foreach_ \n >> lexer.left_parenth \n >> lexer.word \n >> lexer.word \n >> lexer.from_ \n >> lexer.integer \n >> lexer.to_ \n >> lexer.integer \n >> lexer.right_parenth \n >> lexer.left_brace \n >> *(instruction)\n >> lexer.right_brace;\n \n foreachin_ = \n lexer.foreach_ \n >> lexer.left_parenth \n >> lexer.word \n >> lexer.word \n >> lexer.in_ \n >> lexer.word \n >> lexer.right_parenth \n >> lexer.left_brace \n >> *(instruction)\n >> lexer.right_brace;\n \n while_ %=\n lexer.while_ \n > lexer.left_parenth \n > condition \n > lexer.right_parenth \n > lexer.left_brace \n > *(instruction)\n > lexer.right_brace;\n\n declaration %= \n lexer.word \n >> lexer.word \n >> -(lexer.assign >> value);\n \n arrayDeclaration %= \n lexer.word \n >> lexer.word \n >> lexer.left_bracket\n >> lexer.integer\n >> lexer.right_bracket;\n \n assignment %= \n lexer.word \n >> lexer.assign \n >> value;\n\n return_ %=\n lexer.return_\n >> value\n >> lexer.stop;\n \n arrayAssignment %= \n lexer.word \n >> lexer.left_bracket\n >> value\n >> lexer.right_bracket\n >> lexer.assign \n >> value;\n \n globalDeclaration %= \n lexer.word \n >> lexer.word \n >> -(lexer.assign >> value.constant)\n >> lexer.stop;\n \n globalArrayDeclaration %= \n lexer.word \n >> lexer.word \n >> lexer.left_bracket\n >> lexer.integer\n >> lexer.right_bracket\n >> lexer.stop;\n\n functionCall %=\n lexer.word\n >> lexer.left_parenth\n >> -( value >> *( lexer.comma > value))\n >> lexer.right_parenth;\n \n swap %= \n lexer.word \n >> lexer.swap \n >> lexer.word;\n \n instruction %= \n (functionCall > lexer.stop)\n | (assignment > lexer.stop)\n | (declaration >> lexer.stop)\n | (arrayDeclaration >> lexer.stop)\n | (arrayAssignment > lexer.stop)\n | if_\n | for_\n | while_\n | foreach_\n | foreachin_\n | return_\n | (swap > lexer.stop);\n\n repeatable_instruction = assignment | declaration | swap;\n \n arg %= \n type \n >> lexer.word;\n \n function %= \n lexer.word \n >> lexer.word\n >> lexer.left_parenth\n >> -( arg >> *( lexer.comma > arg))\n >> lexer.right_parenth\n >> lexer.left_brace\n >> *(instruction)\n >> lexer.right_brace;\n\n program %=\n qi::eps \n >> *(function | globalDeclaration | globalArrayDeclaration);\n\n \/\/Name the rules\n globalDeclaration.name(\"EDDI global variable\");\n function.name(\"EDDI function declaration\");\n program.name(\"EDDI program\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Core developers\n\/\/ Copyright (c) 2017 The UltimateOnlineCash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"primitives\/block.h\"\n\n#include \"hash.h\"\n#include \"tinyformat.h\"\n#include \"utilstrencodings.h\"\n#include \"crypto\/common.h\"\n#include \"crypto\/neoscrypt.h\"\n\nuint256 CBlockHeader::GetHash() const\n{\n return SerializeHash(*this);\n}\n\nuint256 CBlockHeader::GetPoWHash() const\n{\n unsigned int profile = 0x0;\n uint256 hash;\n neoscrypt((unsigned char *) &nVersion, (unsigned char *) &hash, profile);\t\t\t\t\n\treturn(hash);\n}\n\nstd::string CBlock::ToString() const\n{\n std::stringstream s;\n s << strprintf(\"CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\\n\",\n GetHash().ToString(),\n nVersion,\n hashPrevBlock.ToString(),\n hashMerkleRoot.ToString(),\n nTime, nBits, nNonce,\n vtx.size());\n for (const auto& tx : vtx) {\n s << \" \" << tx->ToString() << \"\\n\";\n }\n return s.str();\n}<commit_msg>Update Neoscrypt<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Core developers\n\/\/ Copyright (c) 2017 The UltimateOnlineCash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"primitives\/block.h\"\n\n#include \"hash.h\"\n#include \"tinyformat.h\"\n#include \"utilstrencodings.h\"\n#include \"crypto\/common.h\"\n#include \"crypto\/neoscrypt.h\"\n\nuint256 CBlockHeader::GetHash() const\n{\n return SerializeHash(*this);\n}\n\nuint256 CBlockHeader::GetPoWHash() const\n{\n unsigned int profile = 0x0;\n uint256 thash;\n neoscrypt((unsigned char *) &nVersion, (unsigned char *) &thash, profile);\t\t\t\t\n return thash;\n}\n\nstd::string CBlock::ToString() const\n{\n std::stringstream s;\n s << strprintf(\"CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\\n\",\n GetHash().ToString(),\n nVersion,\n hashPrevBlock.ToString(),\n hashMerkleRoot.ToString(),\n nTime, nBits, nNonce,\n vtx.size());\n for (const auto& tx : vtx) {\n s << \" \" << tx->ToString() << \"\\n\";\n }\n return s.str();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <errno.h>\n#include <assert.h>\n\n#include \"Endian.hh\"\n#include \"TreeGram.hh\"\n#include \"tools.hh\"\n\nstatic std::string format_str(\"cis-binlm2\\n\");\n\nTreeGram::TreeGram()\n : m_type(BACKOFF),\n m_order(0),\n m_last_order(0)\n{\n}\n\nvoid\nTreeGram::reserve_nodes(int nodes)\n{\n m_nodes.clear();\n m_nodes.reserve(nodes);\n m_nodes.push_back(Node(0, -99, 0, -1));\n}\n\nvoid\nTreeGram::set_interpolation(const std::vector<float> &interpolation)\n{\n m_interpolation = interpolation;\n}\n\nvoid\nTreeGram::print_gram(FILE *file, const Gram &gram)\n{\n for (int i = 0; i < gram.size(); i++) {\n fprintf(file, \"%d \", gram[i]);\n }\n fputc('\\n', file);\n}\n\nvoid\nTreeGram::check_order(const Gram &gram)\n{\n \/\/ Order must be the same or the next.\n if (gram.size() < m_last_gram.size() ||\n gram.size() > m_last_gram.size() + 1)\n {\n fprintf(stderr, \"TreeGram::check_order(): \"\n\t \"trying to insert %d-gram after %d-gram\\n\",\n\t gram.size(), m_last_gram.size());\n print_gram(stderr, gram);\n exit(1);\n }\n\n \/\/ Unigrams must be in the correct places\n if (gram.size() == 1) {\n if (gram[0] != m_nodes.size()) {\n fprintf(stderr, \"TreeGram::check_order(): \"\n\t \"trying to insert 1-gram %d to node %d\\n\",\n\t gram[0], m_nodes.size());\n exit(1);\n }\n }\n\n \/\/ With the same order, the grams must inserted in sorted order.\n if (gram.size() == m_last_gram.size()) {\n int i;\n for (i = 0; i < gram.size(); i++) {\n\n \/\/ Skipping grams\n if (gram[i] > m_last_gram[i])\n\tbreak;\n\n \/\/ Not in order\n if (gram[i] < m_last_gram[i]) {\n\tfprintf(stderr, \"TreeGram::check_order(): \"\n\t\t\"gram not in sorted order\\n\");\n\tprint_gram(stderr, gram);\n\texit(1);\n }\n }\n\n \/\/ Duplicate?\n if (i == gram.size()) {\n fprintf(stderr, \"TreeGram::check_order(): \"\n\t \"duplicate gram\\n\");\n print_gram(stderr, gram);\n exit(1);\n }\n }\n}\n\n\/\/ Note that 'last' is not included in the range.\nint\nTreeGram::binary_search(int word, int first, int last)\n{\n int middle;\n int half;\n\n int len = last - first;\n\n while (len > 5) { \/\/ FIXME: magic threshold to do linear search\n half = len \/ 2;\n middle = first + half;\n\n \/\/ Equal\n if (m_nodes[middle].word == word)\n return middle;\n\n \/\/ First half\n if (m_nodes[middle].word > word) {\n last = middle;\n len = last - first;\n }\n\n \/\/ Second half\n else {\n first = middle + 1;\n len = last - first;\n }\n }\n\n while (first < last) {\n if (m_nodes[first].word == word)\n return first;\n first++;\n }\n\n return -1;\n}\n\n\/\/ Returns unigram if node_index < 0\nint\nTreeGram::find_child(int word, int node_index)\n{\n if (word < 0 || word >= m_words.size()) {\n fprintf(stderr, \"TreeGram::find_child(): \"\n\t \"index %d out of vocabulary size %d\\n\", word, m_words.size());\n exit(1);\n }\n\n if (node_index < 0)\n return word;\n\n assert(node_index < m_nodes.size() - 1);\n\n int first = m_nodes[node_index].child_index;\n int last = m_nodes[node_index + 1].child_index; \/\/ not included\n if (first < 0 || last < 0)\n return -1;\n\n return binary_search(word, first, last);\n}\n\n\/\/\/ Finds the path to the current gram.\n\/\/\n\/\/ PRECONDITIONS:\n\/\/ - m_insert_stack contains the indices of 'm_last_gram'\n\/\/\n\/\/ POSTCONDITIONS:\n\/\/ - m_insert_stack contains the indices of 'gram' without the last word\nvoid\nTreeGram::find_path(const Gram &gram)\n{\n int prev = -1;\n int order = 0;\n int index;\n\n assert(gram.size() > 1);\n\n \/\/ The beginning of the path can be found quickly by using the index\n \/\/ stack.\n while (1) {\n assert(order < m_last_gram.size() - 1);\n if (gram[order] != m_last_gram[order])\n break;\n order++;\n }\n m_insert_stack.resize(order);\n\n \/\/ The rest of the path must be searched.\n order--;\n if (order < 0)\n prev = -1;\n else\n prev = m_insert_stack[order];\n\n while (order < m_last_gram.size() - 1) {\n index = find_child(gram[order], prev);\n if (index < 0) {\n fprintf(stderr, \"prefix not found\\n\");\n print_gram(stderr, gram);\n exit(1);\n }\n\n m_insert_stack.push_back(index);\n\n prev = index;\n order++;\n }\n}\n\nvoid\nTreeGram::add_gram(const Gram &gram, float log_prob, float back_off)\n{\n if (m_nodes.empty()) {\n fprintf(stderr, \"TreeGram::add_gram(): \"\n\t \"nodes must be reserved before calling this function\\n\");\n exit(1);\n }\n\n check_order(gram);\n\n \/\/ Update order counts\n if (gram.size() == m_last_gram.size() + 1) {\n m_order_count.push_back(0);\n m_order++;\n }\n assert(m_order_count.size() == gram.size());\n m_order_count[gram.size()]++;\n\n \/\/ Handle unigrams separately\n if (gram.size() == 1) {\n\n \/\/ OOV can be updated anytime.\n if (gram[0] == 0) {\n m_nodes[0].log_prob = log_prob;\n m_nodes[0].back_off = back_off;\n }\n\n \/\/ Unigram which is not OOV\n else\n m_nodes.push_back(Node(gram[0], log_prob, back_off, -1));\n }\n\n \/\/ 2-grams or higher\n else {\n \/\/ Update the path\n find_path(gram);\n\n if (m_nodes[m_insert_stack.back()].child_index < 0)\n m_nodes[m_insert_stack.back()].child_index = m_nodes.size();\n\n m_nodes.push_back(Node(gram.back(), log_prob, back_off, -1));\n m_nodes[m_insert_stack.back() + 1].child_index = m_nodes.size();\n }\n\n m_last_gram = gram;\n assert(m_order == m_last_gram.size());\n}\n\nvoid \nTreeGram::write(FILE *file, bool reflip) \n{\n fputs(format_str.c_str(), file);\n\n \/\/ Write type and interpolation weights\n if (m_type == BACKOFF)\n fputs(\"backoff\\n\", file);\n else if (m_type == INTERPOLATED)\n fputs(\"interpolated\\n\", file);\n\n fprintf(file, \"%d\\n\", num_words());\n for (int i = 0; i < num_words(); i++)\n fprintf(file, \"%s\\n\", word(i).c_str());\n fprintf(file, \"%d %d\\n\", m_order, m_nodes.size());\n\n \/\/ Use correct endianity\n if (Endian::big) \n flip_endian(); \n\n \/\/ Write possible interpolation weights\n if (m_type == INTERPOLATED) {\n assert(m_interpolation.size() == m_order);\n fwrite(&m_interpolation[0], m_order * sizeof(m_interpolation[0]), 1, file);\n }\n\n \/\/ Write nodes\n fwrite(&m_nodes[0], m_nodes.size() * sizeof(TreeGram::Node), 1, file);\n \n if (ferror(file)) {\n fprintf(stderr, \"TreeGram::write(): write error: %s\\n\", strerror(errno));\n exit(1);\n }\n\n \/\/ Restore to original endianess\n if (Endian::big && reflip)\n flip_endian();\n}\n\nvoid \nTreeGram::read(FILE *file) \n{\n std::string line;\n int words;\n bool ret;\n\n \/\/ Read the header\n ret = read_string(&line, format_str.length(), file);\n if (!ret || line != format_str) {\n fprintf(stderr, \"TreeGram::read(): invalid file format\\n\");\n exit(1);\n }\n \n \/\/ Read LM type\n read_line(&line, file);\n chomp(&line);\n if (line == \"backoff\")\n m_type = BACKOFF;\n else if (line == \"interpolated\")\n m_type = INTERPOLATED;\n else {\n fprintf(stderr, \"TreeGram::read(): invalid type: %s\\n\", line.c_str());\n exit(1);\n }\n\n \/\/ Read the number of words\n if (!read_line(&line, file)) {\n fprintf(stderr, \"TreeGram::read(): unexpected end of file\\n\");\n exit(1);\n }\n words = atoi(line.c_str());\n if (words < 1) {\n fprintf(stderr, \"TreeGram::read(): invalid number of words: %s\\n\", \n\t line.c_str());\n exit(1);\n }\n \n \/\/ Read the vocabulary\n for (int i=0; i < words; i++) {\n if (!read_line(&line, file)) {\n fprintf(stderr, \"TreeGram::read(): \"\n\t \"read error while reading vocabulary\\n\");\n exit(1);\n }\n chomp(&line);\n add_word(line);\n }\n\n \/\/ Read the order and the number of nodes\n int m_nodes_size;\n fscanf(file, \"%d %d\\n\", &m_order, &m_nodes_size);\n reserve_nodes(m_nodes_size);\n\n \/\/ Read the possible interpolation weights\n if (m_type == INTERPOLATED) {\n m_interpolation.resize(m_order);\n fread(&m_interpolation[0], sizeof(float) * m_order, 1, file);\n }\n\n \/\/ Read the nodes\n size_t block_size = m_nodes.size() * sizeof(TreeGram::Node);\n size_t blocks_read = fread(&m_nodes[0], block_size, 1, file);\n if (blocks_read != 1) {\n fprintf(stderr, \"TreeGram::read(): \"\n\t \"read error while reading ngrams\\n\");\n exit(1);\n }\n\n if (Endian::big) \n flip_endian();\n}\n\nvoid \nTreeGram::flip_endian() \n{\n assert(sizeof(m_nodes[0].word == 4));\n assert(sizeof(m_nodes[0].log_prob == 4));\n assert(sizeof(m_nodes[0].back_off == 4));\n assert(sizeof(m_nodes[0].child_index == 4));\n\n if (m_type == INTERPOLATED) {\n assert(m_interpolation.size() == m_order);\n Endian::convert(&m_interpolation[0], 4 * m_order);\n }\n\n for (int i = 0; i < m_nodes.size(); i++) {\n Endian::convert(&m_nodes[i].word, 4);\n Endian::convert(&m_nodes[i].log_prob, 4);\n Endian::convert(&m_nodes[i].back_off, 4);\n Endian::convert(&m_nodes[i].child_index, 4);\n }\n}\n\n\/\/ Fetch the node indices of the requested gram to m_fetch_stack as\n\/\/ far as found in the tree structure.\nvoid\nTreeGram::fetch_gram(const Gram &gram, int first)\n{\n int prev = -1;\n m_fetch_stack.clear();\n \n while (m_fetch_stack.size() < gram.size()) {\n int node = find_child(gram[first], prev);\n if (node < 0)\n break;\n m_fetch_stack.push_back(node);\n first++;\n node = prev;\n }\n}\n\nfloat\nTreeGram::log_prob(const Gram &gram)\n{\n assert(gram.size() > 0);\n\n float log_prob = 0;\n \n \/\/ Denote by (w(1) w(2) ... w(N)) the ngram that was requested. The\n \/\/ log-probability of the back-off model is computed as follows:\n\n \/\/ Iterate n = 1..N:\n \/\/ - If (w(n) ... w(N)) not found, add the possible (w(n) ... w(N-1) backoff\n \/\/ - Otherwise, add the log-prob and return.\n int n = 0;\n while (1) {\n assert(n < gram.size());\n fetch_gram(gram, n);\n assert(m_fetch_stack.size() > 0);\n\n \/\/ Full gram found?\n if (m_fetch_stack.size() == gram.size()) {\n log_prob += m_nodes[m_fetch_stack.back()].log_prob;\n m_last_order = gram.size() - n;\n break;\n }\n \n \/\/ Back-off found?\n if (m_fetch_stack.size() == gram.size() - 1)\n log_prob += m_nodes[m_fetch_stack.back()].back_off;\n\n n++;\n }\n\n return log_prob;\n}\n\nTreeGram::Iterator::Iterator(TreeGram *gram)\n : m_gram(gram)\n{\n if (gram)\n reset(gram);\n}\n\nvoid\nTreeGram::Iterator::reset(TreeGram *gram)\n{\n assert(gram);\n m_gram = gram;\n m_index_stack.clear();\n m_index_stack.resize(gram->m_order);\n}\n\nbool\nTreeGram::Iterator::next()\n{\n bool backtrack = false;\n\n \/\/ Start the search\n if (m_index_stack.empty()) {\n m_index_stack.push_back(0);\n return true;\n }\n\n \/\/ Go to the next node. Backtrack if necessary.\n while (1) {\n assert(!m_index_stack.empty());\n int index = m_index_stack.back();\n TreeGram::Node *node = &m_gram->m_nodes[index];\n\n \/\/ End of the structure?\n if (index == m_gram->m_nodes.size() - 1)\n return false;\n\n \/\/ If not backtracking, try diving deeper\n if (!backtrack) {\n \/\/ Do we have children?\n if (node->child_index > 0 && (node+1)->child_index > 0) {\n\tm_index_stack.push_back(node->child_index);\n\treturn true;\n }\n }\n backtrack = false;\n\n \/\/ No children, try siblings \n if (m_index_stack.size() == 1) {\n \/\/ Unigram level: we have always siblings\n index++;\n assert(index < m_gram->m_order_count[0]);\n return true;\n }\n else {\n \/\/ Higher order\n m_index_stack.pop_back();\n TreeGram::Node *parent = &m_gram->m_nodes[m_index_stack.back()];\n\n \/\/ Do we have more siblings?\n index++;\n if (index < (parent+1)->child_index) {\n\tm_index_stack.push_back(index);\n\treturn true;\n }\n\n \/\/ No more siblings, backtrack.\n backtrack = true;\n }\n }\n}\n\nbool\nTreeGram::Iterator::next_order(int order)\n{\n if (order < 1 || order > m_gram->m_order) {\n fprintf(stderr, \"TreeGram::Iterator::next_order(): invalid order %d\\n\", \n\t order);\n exit(1);\n }\n\n while (1) {\n if (!next())\n return false;\n\n if (m_index_stack.size() == order)\n return true;\n }\n}\n\nconst TreeGram::Node&\nTreeGram::Iterator::node()\n{\n assert(m_gram);\n assert(!m_index_stack.empty());\n \n return m_gram->m_nodes[m_index_stack.back()];\n}\n<commit_msg>*** empty log message ***<commit_after>#include <errno.h>\n#include <assert.h>\n\n#include \"Endian.hh\"\n#include \"TreeGram.hh\"\n#include \"tools.hh\"\n\nstatic std::string format_str(\"cis-binlm2\\n\");\n\nTreeGram::TreeGram()\n : m_type(BACKOFF),\n m_order(0),\n m_last_order(0)\n{\n}\n\nvoid\nTreeGram::reserve_nodes(int nodes)\n{\n m_nodes.clear();\n m_nodes.reserve(nodes);\n m_nodes.push_back(Node(0, -99, 0, -1));\n}\n\nvoid\nTreeGram::set_interpolation(const std::vector<float> &interpolation)\n{\n m_interpolation = interpolation;\n}\n\nvoid\nTreeGram::print_gram(FILE *file, const Gram &gram)\n{\n for (int i = 0; i < gram.size(); i++) {\n fprintf(file, \"%d \", gram[i]);\n }\n fputc('\\n', file);\n}\n\nvoid\nTreeGram::check_order(const Gram &gram)\n{\n \/\/ UNK can be updated anytime\n if (gram.size() == 1 && gram[0] == 0)\n return;\n\n \/\/ Order must be the same or the next.\n if (gram.size() < m_last_gram.size() ||\n gram.size() > m_last_gram.size() + 1)\n {\n fprintf(stderr, \"TreeGram::check_order(): \"\n\t \"trying to insert %d-gram after %d-gram\\n\",\n\t gram.size(), m_last_gram.size());\n print_gram(stderr, gram);\n exit(1);\n }\n\n \/\/ Unigrams must be in the correct places\n if (gram.size() == 1) {\n if (gram[0] != m_nodes.size()) {\n fprintf(stderr, \"TreeGram::check_order(): \"\n\t \"trying to insert 1-gram %d to node %d\\n\",\n\t gram[0], m_nodes.size());\n exit(1);\n }\n }\n\n \/\/ With the same order, the grams must inserted in sorted order.\n if (gram.size() == m_last_gram.size()) {\n int i;\n for (i = 0; i < gram.size(); i++) {\n\n \/\/ Skipping grams\n if (gram[i] > m_last_gram[i])\n\tbreak;\n\n \/\/ Not in order\n if (gram[i] < m_last_gram[i]) {\n\tfprintf(stderr, \"TreeGram::check_order(): \"\n\t\t\"gram not in sorted order\\n\");\n\tprint_gram(stderr, gram);\n\texit(1);\n }\n }\n\n \/\/ Duplicate?\n if (i == gram.size()) {\n fprintf(stderr, \"TreeGram::check_order(): \"\n\t \"duplicate gram\\n\");\n print_gram(stderr, gram);\n exit(1);\n }\n }\n}\n\n\/\/ Note that 'last' is not included in the range.\nint\nTreeGram::binary_search(int word, int first, int last)\n{\n int middle;\n int half;\n\n int len = last - first;\n\n while (len > 5) { \/\/ FIXME: magic threshold to do linear search\n half = len \/ 2;\n middle = first + half;\n\n \/\/ Equal\n if (m_nodes[middle].word == word)\n return middle;\n\n \/\/ First half\n if (m_nodes[middle].word > word) {\n last = middle;\n len = last - first;\n }\n\n \/\/ Second half\n else {\n first = middle + 1;\n len = last - first;\n }\n }\n\n while (first < last) {\n if (m_nodes[first].word == word)\n return first;\n first++;\n }\n\n return -1;\n}\n\n\/\/ Returns unigram if node_index < 0\nint\nTreeGram::find_child(int word, int node_index)\n{\n if (word < 0 || word >= m_words.size()) {\n fprintf(stderr, \"TreeGram::find_child(): \"\n\t \"index %d out of vocabulary size %d\\n\", word, m_words.size());\n exit(1);\n }\n\n if (node_index < 0)\n return word;\n\n assert(node_index < m_nodes.size() - 1);\n\n int first = m_nodes[node_index].child_index;\n int last = m_nodes[node_index + 1].child_index; \/\/ not included\n if (first < 0 || last < 0)\n return -1;\n\n return binary_search(word, first, last);\n}\n\n\/\/\/ Finds the path to the current gram.\n\/\/\n\/\/ PRECONDITIONS:\n\/\/ - m_insert_stack contains the indices of 'm_last_gram'\n\/\/\n\/\/ POSTCONDITIONS:\n\/\/ - m_insert_stack contains the indices of 'gram' without the last word\nvoid\nTreeGram::find_path(const Gram &gram)\n{\n int prev = -1;\n int order = 0;\n int index;\n\n assert(gram.size() > 1);\n\n \/\/ The beginning of the path can be found quickly by using the index\n \/\/ stack.\n while (1) {\n assert(order < m_last_gram.size() - 1);\n if (gram[order] != m_last_gram[order])\n break;\n order++;\n }\n m_insert_stack.resize(order);\n\n \/\/ The rest of the path must be searched.\n order--;\n if (order < 0)\n prev = -1;\n else\n prev = m_insert_stack[order];\n\n while (order < m_last_gram.size() - 1) {\n index = find_child(gram[order], prev);\n if (index < 0) {\n fprintf(stderr, \"prefix not found\\n\");\n print_gram(stderr, gram);\n exit(1);\n }\n\n m_insert_stack.push_back(index);\n\n prev = index;\n order++;\n }\n}\n\nvoid\nTreeGram::add_gram(const Gram &gram, float log_prob, float back_off)\n{\n if (m_nodes.empty()) {\n fprintf(stderr, \"TreeGram::add_gram(): \"\n\t \"nodes must be reserved before calling this function\\n\");\n exit(1);\n }\n\n check_order(gram);\n\n \/\/ Update order counts\n if (gram.size() == m_last_gram.size() + 1) {\n m_order_count.push_back(0);\n m_order++;\n }\n assert(m_order_count.size() == gram.size());\n m_order_count[gram.size()]++;\n\n \/\/ Handle unigrams separately\n if (gram.size() == 1) {\n\n \/\/ OOV can be updated anytime.\n if (gram[0] == 0) {\n m_nodes[0].log_prob = log_prob;\n m_nodes[0].back_off = back_off;\n }\n\n \/\/ Unigram which is not OOV\n else\n m_nodes.push_back(Node(gram[0], log_prob, back_off, -1));\n }\n\n \/\/ 2-grams or higher\n else {\n \/\/ Update the path\n find_path(gram);\n\n if (m_nodes[m_insert_stack.back()].child_index < 0)\n m_nodes[m_insert_stack.back()].child_index = m_nodes.size();\n\n m_nodes.push_back(Node(gram.back(), log_prob, back_off, -1));\n m_nodes[m_insert_stack.back() + 1].child_index = m_nodes.size();\n }\n\n m_last_gram = gram;\n assert(m_order == m_last_gram.size());\n}\n\nvoid \nTreeGram::write(FILE *file, bool reflip) \n{\n fputs(format_str.c_str(), file);\n\n \/\/ Write type and interpolation weights\n if (m_type == BACKOFF)\n fputs(\"backoff\\n\", file);\n else if (m_type == INTERPOLATED)\n fputs(\"interpolated\\n\", file);\n\n fprintf(file, \"%d\\n\", num_words());\n for (int i = 0; i < num_words(); i++)\n fprintf(file, \"%s\\n\", word(i).c_str());\n fprintf(file, \"%d %d\\n\", m_order, m_nodes.size());\n\n \/\/ Use correct endianity\n if (Endian::big) \n flip_endian(); \n\n \/\/ Write possible interpolation weights\n if (m_type == INTERPOLATED) {\n assert(m_interpolation.size() == m_order);\n fwrite(&m_interpolation[0], m_order * sizeof(m_interpolation[0]), 1, file);\n }\n\n \/\/ Write nodes\n fwrite(&m_nodes[0], m_nodes.size() * sizeof(TreeGram::Node), 1, file);\n \n if (ferror(file)) {\n fprintf(stderr, \"TreeGram::write(): write error: %s\\n\", strerror(errno));\n exit(1);\n }\n\n \/\/ Restore to original endianess\n if (Endian::big && reflip)\n flip_endian();\n}\n\nvoid \nTreeGram::read(FILE *file) \n{\n std::string line;\n int words;\n bool ret;\n\n \/\/ Read the header\n ret = read_string(&line, format_str.length(), file);\n if (!ret || line != format_str) {\n fprintf(stderr, \"TreeGram::read(): invalid file format\\n\");\n exit(1);\n }\n \n \/\/ Read LM type\n read_line(&line, file);\n chomp(&line);\n if (line == \"backoff\")\n m_type = BACKOFF;\n else if (line == \"interpolated\")\n m_type = INTERPOLATED;\n else {\n fprintf(stderr, \"TreeGram::read(): invalid type: %s\\n\", line.c_str());\n exit(1);\n }\n\n \/\/ Read the number of words\n if (!read_line(&line, file)) {\n fprintf(stderr, \"TreeGram::read(): unexpected end of file\\n\");\n exit(1);\n }\n words = atoi(line.c_str());\n if (words < 1) {\n fprintf(stderr, \"TreeGram::read(): invalid number of words: %s\\n\", \n\t line.c_str());\n exit(1);\n }\n \n \/\/ Read the vocabulary\n for (int i=0; i < words; i++) {\n if (!read_line(&line, file)) {\n fprintf(stderr, \"TreeGram::read(): \"\n\t \"read error while reading vocabulary\\n\");\n exit(1);\n }\n chomp(&line);\n add_word(line);\n }\n\n \/\/ Read the order and the number of nodes\n int m_nodes_size;\n fscanf(file, \"%d %d\\n\", &m_order, &m_nodes_size);\n reserve_nodes(m_nodes_size);\n\n \/\/ Read the possible interpolation weights\n if (m_type == INTERPOLATED) {\n m_interpolation.resize(m_order);\n fread(&m_interpolation[0], sizeof(float) * m_order, 1, file);\n }\n\n \/\/ Read the nodes\n size_t block_size = m_nodes.size() * sizeof(TreeGram::Node);\n size_t blocks_read = fread(&m_nodes[0], block_size, 1, file);\n if (blocks_read != 1) {\n fprintf(stderr, \"TreeGram::read(): \"\n\t \"read error while reading ngrams\\n\");\n exit(1);\n }\n\n if (Endian::big) \n flip_endian();\n}\n\nvoid \nTreeGram::flip_endian() \n{\n assert(sizeof(m_nodes[0].word == 4));\n assert(sizeof(m_nodes[0].log_prob == 4));\n assert(sizeof(m_nodes[0].back_off == 4));\n assert(sizeof(m_nodes[0].child_index == 4));\n\n if (m_type == INTERPOLATED) {\n assert(m_interpolation.size() == m_order);\n Endian::convert(&m_interpolation[0], 4 * m_order);\n }\n\n for (int i = 0; i < m_nodes.size(); i++) {\n Endian::convert(&m_nodes[i].word, 4);\n Endian::convert(&m_nodes[i].log_prob, 4);\n Endian::convert(&m_nodes[i].back_off, 4);\n Endian::convert(&m_nodes[i].child_index, 4);\n }\n}\n\n\/\/ Fetch the node indices of the requested gram to m_fetch_stack as\n\/\/ far as found in the tree structure.\nvoid\nTreeGram::fetch_gram(const Gram &gram, int first)\n{\n int prev = -1;\n m_fetch_stack.clear();\n \n while (m_fetch_stack.size() < gram.size()) {\n int node = find_child(gram[first], prev);\n if (node < 0)\n break;\n m_fetch_stack.push_back(node);\n first++;\n node = prev;\n }\n}\n\nfloat\nTreeGram::log_prob(const Gram &gram)\n{\n assert(gram.size() > 0);\n\n float log_prob = 0;\n \n \/\/ Denote by (w(1) w(2) ... w(N)) the ngram that was requested. The\n \/\/ log-probability of the back-off model is computed as follows:\n\n \/\/ Iterate n = 1..N:\n \/\/ - If (w(n) ... w(N)) not found, add the possible (w(n) ... w(N-1) backoff\n \/\/ - Otherwise, add the log-prob and return.\n int n = 0;\n while (1) {\n assert(n < gram.size());\n fetch_gram(gram, n);\n assert(m_fetch_stack.size() > 0);\n\n \/\/ Full gram found?\n if (m_fetch_stack.size() == gram.size()) {\n log_prob += m_nodes[m_fetch_stack.back()].log_prob;\n m_last_order = gram.size() - n;\n break;\n }\n \n \/\/ Back-off found?\n if (m_fetch_stack.size() == gram.size() - 1)\n log_prob += m_nodes[m_fetch_stack.back()].back_off;\n\n n++;\n }\n\n return log_prob;\n}\n\nTreeGram::Iterator::Iterator(TreeGram *gram)\n : m_gram(gram)\n{\n if (gram)\n reset(gram);\n}\n\nvoid\nTreeGram::Iterator::reset(TreeGram *gram)\n{\n assert(gram);\n m_gram = gram;\n m_index_stack.clear();\n m_index_stack.resize(gram->m_order);\n}\n\nbool\nTreeGram::Iterator::next()\n{\n bool backtrack = false;\n\n \/\/ Start the search\n if (m_index_stack.empty()) {\n m_index_stack.push_back(0);\n return true;\n }\n\n \/\/ Go to the next node. Backtrack if necessary.\n while (1) {\n assert(!m_index_stack.empty());\n int index = m_index_stack.back();\n TreeGram::Node *node = &m_gram->m_nodes[index];\n\n \/\/ End of the structure?\n if (index == m_gram->m_nodes.size() - 1)\n return false;\n\n \/\/ If not backtracking, try diving deeper\n if (!backtrack) {\n \/\/ Do we have children?\n if (node->child_index > 0 && (node+1)->child_index > 0) {\n\tm_index_stack.push_back(node->child_index);\n\treturn true;\n }\n }\n backtrack = false;\n\n \/\/ No children, try siblings \n if (m_index_stack.size() == 1) {\n \/\/ Unigram level: we have always siblings\n index++;\n assert(index < m_gram->m_order_count[0]);\n return true;\n }\n else {\n \/\/ Higher order\n m_index_stack.pop_back();\n TreeGram::Node *parent = &m_gram->m_nodes[m_index_stack.back()];\n\n \/\/ Do we have more siblings?\n index++;\n if (index < (parent+1)->child_index) {\n\tm_index_stack.push_back(index);\n\treturn true;\n }\n\n \/\/ No more siblings, backtrack.\n backtrack = true;\n }\n }\n}\n\nbool\nTreeGram::Iterator::next_order(int order)\n{\n if (order < 1 || order > m_gram->m_order) {\n fprintf(stderr, \"TreeGram::Iterator::next_order(): invalid order %d\\n\", \n\t order);\n exit(1);\n }\n\n while (1) {\n if (!next())\n return false;\n\n if (m_index_stack.size() == order)\n return true;\n }\n}\n\nconst TreeGram::Node&\nTreeGram::Iterator::node()\n{\n assert(m_gram);\n assert(!m_index_stack.empty());\n \n return m_gram->m_nodes[m_index_stack.back()];\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Library\n Module: VoxelMod.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its\ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994\n\n=========================================================================*\/\n#include <math.h>\n#include \"VoxelMod.hh\"\n#include \"BScalars.hh\"\n\nvlVoxelModeller::vlVoxelModeller()\n{\n this->MaximumDistance = 1.0;\n\n this->ModelBounds[0] = 0.0;\n this->ModelBounds[1] = 0.0;\n this->ModelBounds[2] = 0.0;\n this->ModelBounds[3] = 0.0;\n this->ModelBounds[4] = 0.0;\n this->ModelBounds[5] = 0.0;\n\n this->SampleDimensions[0] = 50;\n this->SampleDimensions[1] = 50;\n this->SampleDimensions[2] = 50;\n}\n\nvoid vlVoxelModeller::PrintSelf(ostream& os, vlIndent indent)\n{\n if (this->ShouldIPrint(vlVoxelModeller::GetClassName()))\n {\n vlDataSetToStructuredPointsFilter::PrintSelf(os,indent);\n\n os << indent << \"Maximum Distance: \" << this->MaximumDistance << \"\\n\";\n os << indent << \"Sample Dimensions: (\" << this->SampleDimensions[0] << \", \"\n << this->SampleDimensions[1] << \", \"\n << this->SampleDimensions[2] << \")\\n\";\n os << indent << \"Model Bounds: \\n\";\n os << indent << \" Xmin,Xmax: (\" << this->ModelBounds[0] << \", \" << this->ModelBounds[1] << \")\\n\";\n os << indent << \" Ymin,Ymax: (\" << this->ModelBounds[2] << \", \" << this->ModelBounds[3] << \")\\n\";\n os << indent << \" Zmin,Zmax: (\" << this->ModelBounds[4] << \", \" << this->ModelBounds[5] << \")\\n\";\n }\n}\n\nvoid vlVoxelModeller::SetModelBounds(float *bounds)\n{\n vlVoxelModeller::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);\n}\n\nvoid vlVoxelModeller::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)\n{\n if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax ||\n this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax ||\n this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax )\n {\n float length;\n\n this->Modified();\n this->ModelBounds[0] = xmin;\n this->ModelBounds[1] = xmax;\n this->ModelBounds[2] = ymin;\n this->ModelBounds[3] = ymax;\n this->ModelBounds[4] = zmin;\n this->ModelBounds[5] = zmax;\n\n this->Origin[0] = xmin;\n this->Origin[1] = ymin;\n this->Origin[2] = zmin;\n\n if ( (length = xmin - xmax) == 0.0 ) length = 1.0;\n this->AspectRatio[0] = 1.0;\n this->AspectRatio[1] = (ymax - ymin) \/ length;\n this->AspectRatio[2] = (zmax - zmin) \/ length;\n }\n}\n\nvoid vlVoxelModeller::Execute()\n{\n int cellNum, i, j, k;\n float *bounds, adjBounds[6];\n vlCell *cell;\n float maxDistance, pcoords[3];\n vlBitScalars *newScalars;\n int numPts, idx;\n int subId;\n int min[3], max[3];\n float x[3], prevDistance2, distance2;\n int jkFactor;\n float weights[MAX_CELL_SIZE];\n float closestPoint[3];\n float voxelHalfWidth[3];\n\n vlDebugMacro(<< \"Executing Voxel model\");\n\/\/\n\/\/ Initialize self; create output objects\n\/\/\n this->Initialize();\n\n numPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2];\n newScalars = new vlBitScalars(numPts);\n for (i=0; i<numPts; i++) newScalars->SetScalar(i,0);\n\n this->SetDimensions(this->GetSampleDimensions());\n maxDistance = this->ComputeModelBounds();\n\/\/\n\/\/ Voxel widths are 1\/2 the height, width, length of a voxel\n\/\/\n for (i=0; i < 3; i++) voxelHalfWidth[i] = this->AspectRatio[i] \/ 2.0;\n\/\/\n\/\/ Traverse all cells; computing distance function on volume points.\n\/\/\n for (cellNum=0; cellNum < this->Input->GetNumberOfCells(); cellNum++)\n {\n cell = this->Input->GetCell(cellNum);\n bounds = cell->GetBounds();\n for (i=0; i<3; i++)\n {\n adjBounds[2*i] = bounds[2*i] - maxDistance;\n adjBounds[2*i+1] = bounds[2*i+1] + maxDistance;\n }\n\n \/\/ compute dimensional bounds in data set\n for (i=0; i<3; i++)\n {\n min[i] = (adjBounds[2*i] - this->Origin[i]) \/ this->AspectRatio[i];\n max[i] = (adjBounds[2*i+1] - this->Origin[i]) \/ this->AspectRatio[i];\n if (min[i] < 0) min[i] = 0;\n if (max[i] >= this->SampleDimensions[i]) max[i] = this->SampleDimensions[i] - 1;\n }\n\n jkFactor = this->SampleDimensions[0]*this->SampleDimensions[1];\n for (k = min[2]; k <= max[2]; k++) \n {\n x[2] = this->AspectRatio[2] * k + this->Origin[2];\n for (j = min[1]; j <= max[1]; j++)\n {\n x[1] = this->AspectRatio[1] * j + this->Origin[1];\n for (i = min[0]; i <= max[0]; i++) \n {\n\t idx = jkFactor*k + this->SampleDimensions[0]*j + i;\n\t if (!(newScalars->GetScalar(idx)))\n\t {\n\t x[0] = this->AspectRatio[0] * i + this->Origin[0];\n\t cell->EvaluatePosition(x, closestPoint, subId, pcoords, \n distance2, weights);\n\t if ( closestPoint[0] <= voxelHalfWidth[0] ||\n closestPoint[1] <= voxelHalfWidth[1] ||\n closestPoint[2] <= voxelHalfWidth[2] )\n\t newScalars->SetScalar(idx,1);\n\t }\n\t }\n }\n }\n }\n\/\/\n\/\/ Update self\n\/\/\n this->PointData.SetScalars(newScalars);\n\n}\n\nfloat vlVoxelModeller::ComputeModelBounds()\n{\n float *bounds, maxDist;\n int i, adjustBounds=0;\n\n \/\/ compute model bounds if not set previously\n if ( this->ModelBounds[0] >= this->ModelBounds[1] ||\n this->ModelBounds[2] >= this->ModelBounds[3] ||\n this->ModelBounds[4] >= this->ModelBounds[5] )\n {\n adjustBounds = 1;\n bounds = this->Input->GetBounds();\n }\n else\n {\n bounds = this->ModelBounds;\n }\n\n for (maxDist=0.0, i=0; i<3; i++)\n if ( (bounds[2*i+1] - bounds[2*i]) > maxDist )\n maxDist = bounds[2*i+1] - bounds[2*i];\n\n maxDist *= this->MaximumDistance;\n\n \/\/ adjust bounds so model fits strictly inside (only if not set previously)\n if ( adjustBounds )\n {\n for (i=0; i<3; i++)\n {\n this->ModelBounds[2*i] = bounds[2*i] - maxDist;\n this->ModelBounds[2*i+1] = bounds[2*i+1] + maxDist;\n }\n }\n\n \/\/ Set volume origin and aspect ratio\n for (i=0; i<3; i++)\n {\n this->Origin[i] = this->ModelBounds[2*i];\n this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])\/\n (this->SampleDimensions[i] - 1);\n }\n\n return maxDist; \n}\n\nvoid vlVoxelModeller::SetSampleDimensions(int i, int j, int k)\n{\n int dim[3];\n\n dim[0] = i;\n dim[1] = j;\n dim[2] = k;\n\n this->SetSampleDimensions(dim);\n}\n\nvoid vlVoxelModeller::SetSampleDimensions(int dim[3])\n{\n vlDebugMacro(<< \" setting SampleDimensions to (\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \")\");\n\n if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] ||\n dim[2] != SampleDimensions[2] )\n {\n if ( dim[0]<1 || dim[1]<1 || dim[2]<1 )\n {\n vlErrorMacro (<< \"Bad Sample Dimensions, retaining previous values\");\n return;\n }\n\n for (int dataDim=0, i=0; i<3 ; i++) if (dim[i] > 1) dataDim++;\n\n if ( dataDim < 3 )\n {\n vlErrorMacro(<<\"Sample dimensions must define a volume!\");\n return;\n }\n\n for ( i=0; i<3; i++) this->SampleDimensions[i] = dim[i];\n\n this->Modified();\n }\n}\n<commit_msg>added write method<commit_after>\/*=========================================================================\n\n Program: Visualization Library\n Module: VoxelMod.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its\ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994\n\n=========================================================================*\/\n#include <math.h>\n#include <stdio.h>\n#include \"VoxelMod.hh\"\n#include \"BScalars.hh\"\n\nvlVoxelModeller::vlVoxelModeller()\n{\n this->MaximumDistance = 1.0;\n\n this->ModelBounds[0] = 0.0;\n this->ModelBounds[1] = 0.0;\n this->ModelBounds[2] = 0.0;\n this->ModelBounds[3] = 0.0;\n this->ModelBounds[4] = 0.0;\n this->ModelBounds[5] = 0.0;\n\n this->SampleDimensions[0] = 50;\n this->SampleDimensions[1] = 50;\n this->SampleDimensions[2] = 50;\n}\n\nvoid vlVoxelModeller::PrintSelf(ostream& os, vlIndent indent)\n{\n if (this->ShouldIPrint(vlVoxelModeller::GetClassName()))\n {\n vlDataSetToStructuredPointsFilter::PrintSelf(os,indent);\n\n os << indent << \"Maximum Distance: \" << this->MaximumDistance << \"\\n\";\n os << indent << \"Sample Dimensions: (\" << this->SampleDimensions[0] << \", \"\n << this->SampleDimensions[1] << \", \"\n << this->SampleDimensions[2] << \")\\n\";\n os << indent << \"Model Bounds: \\n\";\n os << indent << \" Xmin,Xmax: (\" << this->ModelBounds[0] << \", \" << this->ModelBounds[1] << \")\\n\";\n os << indent << \" Ymin,Ymax: (\" << this->ModelBounds[2] << \", \" << this->ModelBounds[3] << \")\\n\";\n os << indent << \" Zmin,Zmax: (\" << this->ModelBounds[4] << \", \" << this->ModelBounds[5] << \")\\n\";\n }\n}\n\nvoid vlVoxelModeller::SetModelBounds(float *bounds)\n{\n vlVoxelModeller::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);\n}\n\nvoid vlVoxelModeller::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)\n{\n if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax ||\n this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax ||\n this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax )\n {\n float length;\n\n this->Modified();\n this->ModelBounds[0] = xmin;\n this->ModelBounds[1] = xmax;\n this->ModelBounds[2] = ymin;\n this->ModelBounds[3] = ymax;\n this->ModelBounds[4] = zmin;\n this->ModelBounds[5] = zmax;\n\n this->Origin[0] = xmin;\n this->Origin[1] = ymin;\n this->Origin[2] = zmin;\n\n if ( (length = xmax - xmin) == 0.0 ) length = 1.0;\n this->AspectRatio[0] = 1.0;\n this->AspectRatio[1] = (ymax - ymin) \/ length;\n this->AspectRatio[2] = (zmax - zmin) \/ length;\n }\n}\n\nvoid vlVoxelModeller::Execute()\n{\n int cellNum, i, j, k;\n float *bounds, adjBounds[6];\n vlCell *cell;\n float maxDistance, pcoords[3];\n vlBitScalars *newScalars;\n int numPts, idx;\n int subId;\n int min[3], max[3];\n float x[3], prevDistance2, distance2;\n int jkFactor;\n float weights[MAX_CELL_SIZE];\n float closestPoint[3];\n float voxelHalfWidth[3];\n\n vlDebugMacro(<< \"Executing Voxel model\");\n\/\/\n\/\/ Initialize self; create output objects\n\/\/\n this->Initialize();\n\n numPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2];\n newScalars = new vlBitScalars(numPts);\n for (i=0; i<numPts; i++) newScalars->SetScalar(i,0);\n\n this->SetDimensions(this->GetSampleDimensions());\n maxDistance = this->ComputeModelBounds();\n\/\/\n\/\/ Voxel widths are 1\/2 the height, width, length of a voxel\n\/\/\n for (i=0; i < 3; i++) voxelHalfWidth[i] = this->AspectRatio[i] \/ 2.0;\n\/\/\n\/\/ Traverse all cells; computing distance function on volume points.\n\/\/\n for (cellNum=0; cellNum < this->Input->GetNumberOfCells(); cellNum++)\n {\n cell = this->Input->GetCell(cellNum);\n bounds = cell->GetBounds();\n for (i=0; i<3; i++)\n {\n adjBounds[2*i] = bounds[2*i] - maxDistance;\n adjBounds[2*i+1] = bounds[2*i+1] + maxDistance;\n }\n\n \/\/ compute dimensional bounds in data set\n for (i=0; i<3; i++)\n {\n min[i] = (adjBounds[2*i] - this->Origin[i]) \/ this->AspectRatio[i];\n max[i] = (adjBounds[2*i+1] - this->Origin[i]) \/ this->AspectRatio[i];\n if (min[i] < 0) min[i] = 0;\n if (max[i] >= this->SampleDimensions[i]) max[i] = this->SampleDimensions[i] - 1;\n }\n\n jkFactor = this->SampleDimensions[0]*this->SampleDimensions[1];\n for (k = min[2]; k <= max[2]; k++) \n {\n x[2] = this->AspectRatio[2] * k + this->Origin[2];\n for (j = min[1]; j <= max[1]; j++)\n {\n x[1] = this->AspectRatio[1] * j + this->Origin[1];\n for (i = min[0]; i <= max[0]; i++) \n {\n\t idx = jkFactor*k + this->SampleDimensions[0]*j + i;\n\t if (!(newScalars->GetScalar(idx)))\n\t {\n\t x[0] = this->AspectRatio[0] * i + this->Origin[0];\n\t cell->EvaluatePosition(x, closestPoint, subId, pcoords, \n distance2, weights);\n\t if ((fabs(closestPoint[0] - x[0]) <= voxelHalfWidth[0]) &&\n\t\t(fabs(closestPoint[1] - x[1]) <= voxelHalfWidth[1]) &&\n\t\t(fabs(closestPoint[2] - x[2]) <= voxelHalfWidth[2]))\n\t {\n\t newScalars->SetScalar(idx,1);\n\t }\n\t }\n\t }\n }\n }\n }\n\/\/\n\/\/ Update self\n\/\/\n this->PointData.SetScalars(newScalars);\n\n}\n\nfloat vlVoxelModeller::ComputeModelBounds()\n{\n float *bounds, maxDist;\n int i, adjustBounds=0;\n\n \/\/ compute model bounds if not set previously\n if ( this->ModelBounds[0] >= this->ModelBounds[1] ||\n this->ModelBounds[2] >= this->ModelBounds[3] ||\n this->ModelBounds[4] >= this->ModelBounds[5] )\n {\n adjustBounds = 1;\n bounds = this->Input->GetBounds();\n }\n else\n {\n bounds = this->ModelBounds;\n }\n\n for (maxDist=0.0, i=0; i<3; i++)\n if ( (bounds[2*i+1] - bounds[2*i]) > maxDist )\n maxDist = bounds[2*i+1] - bounds[2*i];\n\n maxDist *= this->MaximumDistance;\n\n \/\/ adjust bounds so model fits strictly inside (only if not set previously)\n if ( adjustBounds )\n {\n for (i=0; i<3; i++)\n {\n this->ModelBounds[2*i] = bounds[2*i] - maxDist;\n this->ModelBounds[2*i+1] = bounds[2*i+1] + maxDist;\n }\n }\n\n \/\/ Set volume origin and aspect ratio\n for (i=0; i<3; i++)\n {\n this->Origin[i] = this->ModelBounds[2*i];\n this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])\/\n (this->SampleDimensions[i] - 1);\n }\n\n return maxDist; \n}\n\nvoid vlVoxelModeller::SetSampleDimensions(int i, int j, int k)\n{\n int dim[3];\n\n dim[0] = i;\n dim[1] = j;\n dim[2] = k;\n\n this->SetSampleDimensions(dim);\n}\n\nvoid vlVoxelModeller::SetSampleDimensions(int dim[3])\n{\n vlDebugMacro(<< \" setting SampleDimensions to (\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \")\");\n\n if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] ||\n dim[2] != SampleDimensions[2] )\n {\n if ( dim[0]<1 || dim[1]<1 || dim[2]<1 )\n {\n vlErrorMacro (<< \"Bad Sample Dimensions, retaining previous values\");\n return;\n }\n\n for (int dataDim=0, i=0; i<3 ; i++) if (dim[i] > 1) dataDim++;\n\n if ( dataDim < 3 )\n {\n vlErrorMacro(<<\"Sample dimensions must define a volume!\");\n return;\n }\n\n for ( i=0; i<3; i++) this->SampleDimensions[i] = dim[i];\n\n this->Modified();\n }\n}\n\nvoid vlVoxelModeller::Write(char *fname)\n{\n FILE *fp;\n int cellNum, i, j, k;\n float *bounds;\n float maxDistance;\n vlBitScalars *newScalars;\n int numPts, idx;\n int bitcount;\n unsigned char uc;\n\n vlDebugMacro(<< \"Writing Voxel model\");\n\n \/\/ update the data\n this->Execute();\n \n numPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2];\n\n newScalars = (vlBitScalars *)this->PointData.GetScalars();\n \n\n this->SetDimensions(this->GetSampleDimensions());\n maxDistance = this->ComputeModelBounds();\n\n fp = fopen(fname,\"w\");\n if (!fp) \n {\n vlErrorMacro(<< \"Couldn't open file: \" << fname << endl);\n return;\n }\n\n fprintf(fp,\"Voxel Data File\\n\");\n fprintf(fp,\"Origin: %f %f %f\\n\",this->Origin[0],\n\t this->Origin[1],this->Origin[2]);\n fprintf(fp,\"Aspect: %f %f %f\\n\",this->AspectRatio[0],\n\t this->AspectRatio[1],this->AspectRatio[2]);\n fprintf(fp,\"Dimensions: %i %i %i\\n\",this->SampleDimensions[0],\n\t this->SampleDimensions[1],this->SampleDimensions[2]);\n\n \/\/ write out the data\n bitcount = 0;\n idx = 0;\n uc = 0x00;\n\n for (k = 0; k < this->SampleDimensions[2]; k++)\n for (j = 0; j < this->SampleDimensions[1]; j++)\n for (i = 0; i < this->SampleDimensions[0]; i++)\n\t{\n\tif (newScalars->GetScalar(idx))\n\t {\n\t uc |= (0x80 >> bitcount);\n\t }\n\tbitcount++;\n\tif (bitcount == 8)\n\t {\n\t fputc(uc,fp);\n\t uc = 0x00;\n\t bitcount = 0;\n\t }\n\tidx++;\n\t}\n if (bitcount)\n {\n fputc(uc,fp);\n }\n\n fclose(fp);\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n Copyright (c) 2015 Sérgio Vieira - sergiosvieira@gmail.com\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 The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\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\n#include \"YObject.h\"\n\n\/** YDA **\/\n#include \"YSprite.h\"\n\n\/** C++ **\/\n#include <cassert>\n\n\/** SDL2 **\/\n#include <SDL.h>\n#include <SDL2_image\/SDL_image.h>\n\n\/** Public Methods **\/\nvoid YObject::render(SDL_Renderer* a_renderer) const\n{\n assert(a_renderer != nullptr);\n assert(m_sprite != nullptr);\n \n SDL_Rect srcRect = m_sprite->rect();\n SDL_Rect dstRect;\n \n dstRect.x = m_position.x();\n dstRect.y = m_position.y();\n dstRect.w = m_sprite->width();\n dstRect.h = m_sprite->height();\n \n SDL_RenderCopy(a_renderer,\n m_sprite->texture(),\n &srcRect,\n &dstRect);\n}\n\nYPoint YObject::position() const\n{\n\treturn m_position;\n}\n\nvoid YObject::position(YPoint a_position)\n{\n\tm_position = a_position;\n}\n\nYPoint YObject::anchor() const\n{\n\treturn m_anchor;\n}\n\nvoid YObject::anchor(YPoint a_anchor)\n{\n\tm_anchor = a_anchor;\n}\n\nvoid YObject::visible(bool a_value)\n{\n\tm_visible = a_value;\n}\n\nbool YObject::isVisible() const\n{\n\treturn m_visible;\n}\n\nYSprite* YObject::sprite() const\n{\n return m_sprite;\n}<commit_msg>Adds algorithm include (visual studio compability)<commit_after>\/****************************************************************************\n Copyright (c) 2015 Sérgio Vieira - sergiosvieira@gmail.com\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 The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\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\n#include \"YObject.h\"\n\n\/** YDA **\/\n#include \"YSprite.h\"\n\n\/** C++ **\/\n#include <cassert>\n\n\/** SDL2 **\/\n#include <SDL.h>\n#ifdef WIN32\n\t#include <SDL_image.h>\t\n#else\n\t#include <SDL2_image\/SDL_image.h>\t\n#endif\n\n\/** Public Methods **\/\nvoid YObject::render(SDL_Renderer* a_renderer) const\n{\n assert(a_renderer != nullptr);\n assert(m_sprite != nullptr);\n \n SDL_Rect srcRect = m_sprite->rect();\n SDL_Rect dstRect;\n \n dstRect.x = m_position.x();\n dstRect.y = m_position.y();\n dstRect.w = m_sprite->width();\n dstRect.h = m_sprite->height();\n \n SDL_RenderCopy(a_renderer,\n m_sprite->texture(),\n &srcRect,\n &dstRect);\n}\n\nYPoint YObject::position() const\n{\n\treturn m_position;\n}\n\nvoid YObject::position(YPoint a_position)\n{\n\tm_position = a_position;\n}\n\nYPoint YObject::anchor() const\n{\n\treturn m_anchor;\n}\n\nvoid YObject::anchor(YPoint a_anchor)\n{\n\tm_anchor = a_anchor;\n}\n\nvoid YObject::visible(bool a_value)\n{\n\tm_visible = a_value;\n}\n\nbool YObject::isVisible() const\n{\n\treturn m_visible;\n}\n\nYSprite* YObject::sprite() const\n{\n return m_sprite;\n}<|endoftext|>"} {"text":"<commit_before>#include <plasp\/utils\/Parser.h>\n\n#include <algorithm>\n\n#include <boost\/assert.hpp>\n\n#include <plasp\/utils\/ParserException.h>\n\nnamespace plasp\n{\nnamespace utils\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Parser\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst std::istreambuf_iterator<char> Parser::EndOfFile = std::istreambuf_iterator<char>();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nParser::Parser(std::istream &istream)\n:\tm_istream(istream),\n\tm_position(m_istream),\n\tm_row{1},\n\tm_column{1},\n\tm_endOfFile{false}\n{\n\tstd::setlocale(LC_NUMERIC, \"C\");\n\n\t\/\/ Don’t skip whitespace\n\tistream.exceptions(std::istream::badbit);\n\n\tcheckStream();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t Parser::row() const\n{\n\treturn m_row;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t Parser::column() const\n{\n\treturn m_column;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nchar Parser::currentCharacter() const\n{\n\tcheckStream();\n\n\treturn *m_position;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Parser::atEndOfFile() const\n{\n\treturn m_position.equal(EndOfFile);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::checkStream() const\n{\n\tif (atEndOfFile())\n\t\tthrow ParserException(m_row, m_column, \"Reading past end of file\");\n\n\tif (m_istream.fail())\n\t\tthrow ParserException(m_row, m_column);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::advance()\n{\n\tcheckStream();\n\n\tconst auto character = currentCharacter();\n\n\tif (character == '\\n')\n\t{\n\t\tm_row++;\n\t\tm_column = 1;\n\t}\n\telse if (std::isblank(character) || std::isprint(character))\n\t\tm_column++;\n\n\tm_position++;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Parser::advanceIf(char expectedCharacter)\n{\n\tcheckStream();\n\n\tif (currentCharacter() != expectedCharacter)\n\t\treturn false;\n\n\tadvance();\n\n\treturn true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::skipWhiteSpace()\n{\n\treturn skipWhiteSpace(\n\t\t[](const auto character)\n\t\t{\n\t\t\treturn std::isspace(character);\n\t\t});\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::skipLine()\n{\n\tcheckStream();\n\n\twhile (currentCharacter() != '\\n')\n\t\tadvance();\n\n\tadvance();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string Parser::getLine()\n{\n\tcheckStream();\n\n\tstd::string value;\n\n\twhile (true)\n\t{\n\t\tconst auto character = currentCharacter();\n\n\t\tadvance();\n\n\t\tif (character == '\\n')\n\t\t\tbreak;\n\t\telse if (character == '\\r')\n\t\t\tcontinue;\n\n\t\tvalue.push_back(character);\n\t}\n\n\treturn value;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nstd::string Parser::parse<std::string>()\n{\n\tskipWhiteSpace();\n\n\tstd::string value;\n\n\twhile (true)\n\t{\n\t\tconst auto character = currentCharacter();\n\n\t\tif (std::isspace(character))\n\t\t\tbreak;\n\n\t\tvalue.push_back(character);\n\t\tadvance();\n\t}\n\n\treturn value;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<std::string>(const std::string &expectedValue)\n{\n\tBOOST_ASSERT(!std::isspace(expectedValue[0]));\n\n\tskipWhiteSpace();\n\n\tstd::for_each(expectedValue.cbegin(), expectedValue.cend(),\n\t\t[&](const auto &expectedCharacter)\n\t\t{\n\t\t\tconst auto character = static_cast<char>(this->currentCharacter());\n\n\t\t\tif (character != expectedCharacter)\n\t\t\t\tthrow ParserException(m_row, m_column, \"Unexpected string, expected \" + expectedValue + \" (expected \" + expectedCharacter + \", got \" + character + \")\");\n\n\t\t\tthis->advance();\n\t\t});\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint64_t Parser::parseIntegerBody()\n{\n\tcheckStream();\n\n\tif (!std::isdigit(currentCharacter()))\n\t\tthrow ParserException(m_row, m_column, \"Could not parse integer value\");\n\n\tuint64_t value = 0;\n\n\twhile (!atEndOfFile())\n\t{\n\t\tconst auto character = currentCharacter();\n\n\t\tif (!std::isdigit(character))\n\t\t\tbreak;\n\n\t\tvalue *= 10;\n\t\tvalue += character - '0';\n\n\t\tadvance();\n\t}\n\n\treturn value;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nint64_t Parser::parse<int64_t>()\n{\n\tskipWhiteSpace();\n\n\tbool positive = advanceIf('+') || !advanceIf('-');\n\n\tconst auto value = parseIntegerBody();\n\n\treturn (positive ? value : -value);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nuint64_t Parser::parse<uint64_t>()\n{\n\tskipWhiteSpace();\n\n\tif (currentCharacter() == '-')\n\t\tthrow ParserException(m_row, m_column, \"Expected unsigned integer, got signed one\");\n\n\treturn parseIntegerBody();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<int64_t>(const int64_t &expectedValue)\n{\n\tconst auto value = parse<int64_t>();\n\n\tif (value != expectedValue)\n\t\tthrow ParserException(m_row, m_column, \"Unexpected value \" + std::to_string(value) + \", expected \" + std::to_string(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<uint64_t>(const uint64_t &expectedValue)\n{\n\tconst auto value = parse<uint64_t>();\n\n\tif (value != expectedValue)\n\t\tthrow ParserException(m_row, m_column, \"Unexpected value \" + std::to_string(value) + \", expected \" + std::to_string(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nint32_t Parser::parse<int32_t>()\n{\n\treturn static_cast<int32_t>(parse<int64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nuint32_t Parser::parse<uint32_t>()\n{\n\treturn static_cast<uint32_t>(parse<uint64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<int32_t>(const int32_t &expectedValue)\n{\n\texpect<int64_t>(static_cast<int64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<uint32_t>(const uint32_t &expectedValue)\n{\n\texpect<uint64_t>(static_cast<uint64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nint16_t Parser::parse<int16_t>()\n{\n\treturn static_cast<int16_t>(parse<int64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nuint16_t Parser::parse<uint16_t>()\n{\n\treturn static_cast<uint16_t>(parse<uint64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<int16_t>(const int16_t &expectedValue)\n{\n\texpect<int64_t>(static_cast<int64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<uint16_t>(const uint16_t &expectedValue)\n{\n\texpect<uint64_t>(static_cast<uint64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nint8_t Parser::parse<int8_t>()\n{\n\treturn static_cast<int8_t>(parse<int64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nuint8_t Parser::parse<uint8_t>()\n{\n\treturn static_cast<uint8_t>(parse<uint64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<int8_t>(const int8_t &expectedValue)\n{\n\texpect<int64_t>(static_cast<int64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<uint8_t>(const uint8_t &expectedValue)\n{\n\texpect<uint64_t>(static_cast<uint64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nbool Parser::parse<bool>()\n{\n\tskipWhiteSpace();\n\n\tif (advanceIf('0'))\n\t return false;\n\n\tif (advanceIf('1'))\n\t\treturn true;\n\n\tthrow ParserException(m_row, m_column, \"Could not parse Boolean value\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<bool>(const bool &expectedValue)\n{\n\tconst auto value = parse<bool>();\n\n\tif (value != expectedValue)\n\t\tthrow ParserException(m_row, m_column, \"Unexpected value \" + std::to_string(value) + \", expected \" + std::to_string(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n}\n<commit_msg>Minor formatting.<commit_after>#include <plasp\/utils\/Parser.h>\n\n#include <algorithm>\n\n#include <boost\/assert.hpp>\n\n#include <plasp\/utils\/ParserException.h>\n\nnamespace plasp\n{\nnamespace utils\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Parser\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst std::istreambuf_iterator<char> Parser::EndOfFile = std::istreambuf_iterator<char>();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nParser::Parser(std::istream &istream)\n:\tm_istream(istream),\n\tm_position(m_istream),\n\tm_row{1},\n\tm_column{1},\n\tm_endOfFile{false}\n{\n\tstd::setlocale(LC_NUMERIC, \"C\");\n\n\t\/\/ Don’t skip whitespace\n\tistream.exceptions(std::istream::badbit);\n\n\tcheckStream();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t Parser::row() const\n{\n\treturn m_row;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t Parser::column() const\n{\n\treturn m_column;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nchar Parser::currentCharacter() const\n{\n\tcheckStream();\n\n\treturn *m_position;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Parser::atEndOfFile() const\n{\n\treturn m_position.equal(EndOfFile);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::checkStream() const\n{\n\tif (atEndOfFile())\n\t\tthrow ParserException(m_row, m_column, \"Reading past end of file\");\n\n\tif (m_istream.fail())\n\t\tthrow ParserException(m_row, m_column);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::advance()\n{\n\tcheckStream();\n\n\tconst auto character = currentCharacter();\n\n\tif (character == '\\n')\n\t{\n\t\tm_row++;\n\t\tm_column = 1;\n\t}\n\telse if (std::isblank(character) || std::isprint(character))\n\t\tm_column++;\n\n\tm_position++;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Parser::advanceIf(char expectedCharacter)\n{\n\tcheckStream();\n\n\tif (currentCharacter() != expectedCharacter)\n\t\treturn false;\n\n\tadvance();\n\n\treturn true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::skipWhiteSpace()\n{\n\treturn skipWhiteSpace(\n\t\t[](const auto character)\n\t\t{\n\t\t\treturn std::isspace(character);\n\t\t});\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::skipLine()\n{\n\tcheckStream();\n\n\twhile (currentCharacter() != '\\n')\n\t\tadvance();\n\n\tadvance();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string Parser::getLine()\n{\n\tcheckStream();\n\n\tstd::string value;\n\n\twhile (true)\n\t{\n\t\tconst auto character = currentCharacter();\n\n\t\tadvance();\n\n\t\tif (character == '\\n')\n\t\t\tbreak;\n\t\telse if (character == '\\r')\n\t\t\tcontinue;\n\n\t\tvalue.push_back(character);\n\t}\n\n\treturn value;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nstd::string Parser::parse<std::string>()\n{\n\tskipWhiteSpace();\n\n\tstd::string value;\n\n\twhile (true)\n\t{\n\t\tconst auto character = currentCharacter();\n\n\t\tif (std::isspace(character))\n\t\t\tbreak;\n\n\t\tvalue.push_back(character);\n\t\tadvance();\n\t}\n\n\treturn value;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<std::string>(const std::string &expectedValue)\n{\n\tBOOST_ASSERT(!std::isspace(expectedValue[0]));\n\n\tskipWhiteSpace();\n\n\tstd::for_each(expectedValue.cbegin(), expectedValue.cend(),\n\t\t[&](const auto &expectedCharacter)\n\t\t{\n\t\t\tconst auto character = static_cast<char>(this->currentCharacter());\n\n\t\t\tif (character != expectedCharacter)\n\t\t\t\tthrow ParserException(m_row, m_column, \"Unexpected string, expected \\\"\" + expectedValue + \"\\\" (expected character '\" + expectedCharacter + \"', got '\" + character + \"')\");\n\n\t\t\tthis->advance();\n\t\t});\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint64_t Parser::parseIntegerBody()\n{\n\tcheckStream();\n\n\tif (!std::isdigit(currentCharacter()))\n\t\tthrow ParserException(m_row, m_column, \"Could not parse integer value\");\n\n\tuint64_t value = 0;\n\n\twhile (!atEndOfFile())\n\t{\n\t\tconst auto character = currentCharacter();\n\n\t\tif (!std::isdigit(character))\n\t\t\tbreak;\n\n\t\tvalue *= 10;\n\t\tvalue += character - '0';\n\n\t\tadvance();\n\t}\n\n\treturn value;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nint64_t Parser::parse<int64_t>()\n{\n\tskipWhiteSpace();\n\n\tbool positive = advanceIf('+') || !advanceIf('-');\n\n\tconst auto value = parseIntegerBody();\n\n\treturn (positive ? value : -value);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nuint64_t Parser::parse<uint64_t>()\n{\n\tskipWhiteSpace();\n\n\tif (currentCharacter() == '-')\n\t\tthrow ParserException(m_row, m_column, \"Expected unsigned integer, got signed one\");\n\n\treturn parseIntegerBody();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<int64_t>(const int64_t &expectedValue)\n{\n\tconst auto value = parse<int64_t>();\n\n\tif (value != expectedValue)\n\t\tthrow ParserException(m_row, m_column, \"Unexpected value \" + std::to_string(value) + \", expected \" + std::to_string(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<uint64_t>(const uint64_t &expectedValue)\n{\n\tconst auto value = parse<uint64_t>();\n\n\tif (value != expectedValue)\n\t\tthrow ParserException(m_row, m_column, \"Unexpected value \" + std::to_string(value) + \", expected \" + std::to_string(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nint32_t Parser::parse<int32_t>()\n{\n\treturn static_cast<int32_t>(parse<int64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nuint32_t Parser::parse<uint32_t>()\n{\n\treturn static_cast<uint32_t>(parse<uint64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<int32_t>(const int32_t &expectedValue)\n{\n\texpect<int64_t>(static_cast<int64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<uint32_t>(const uint32_t &expectedValue)\n{\n\texpect<uint64_t>(static_cast<uint64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nint16_t Parser::parse<int16_t>()\n{\n\treturn static_cast<int16_t>(parse<int64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nuint16_t Parser::parse<uint16_t>()\n{\n\treturn static_cast<uint16_t>(parse<uint64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<int16_t>(const int16_t &expectedValue)\n{\n\texpect<int64_t>(static_cast<int64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<uint16_t>(const uint16_t &expectedValue)\n{\n\texpect<uint64_t>(static_cast<uint64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nint8_t Parser::parse<int8_t>()\n{\n\treturn static_cast<int8_t>(parse<int64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nuint8_t Parser::parse<uint8_t>()\n{\n\treturn static_cast<uint8_t>(parse<uint64_t>());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<int8_t>(const int8_t &expectedValue)\n{\n\texpect<int64_t>(static_cast<int64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<uint8_t>(const uint8_t &expectedValue)\n{\n\texpect<uint64_t>(static_cast<uint64_t>(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nbool Parser::parse<bool>()\n{\n\tskipWhiteSpace();\n\n\tif (advanceIf('0'))\n\t return false;\n\n\tif (advanceIf('1'))\n\t\treturn true;\n\n\tthrow ParserException(m_row, m_column, \"Could not parse Boolean value\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<>\nvoid Parser::expect<bool>(const bool &expectedValue)\n{\n\tconst auto value = parse<bool>();\n\n\tif (value != expectedValue)\n\t\tthrow ParserException(m_row, m_column, \"Unexpected value \" + std::to_string(value) + \", expected \" + std::to_string(expectedValue));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2013-2014 Jeffrey Pfau\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n#include \"GBAApp.h\"\n\n#include \"AudioProcessor.h\"\n#include \"Display.h\"\n#include \"GameController.h\"\n#include \"Window.h\"\n#include \"VFileDevice.h\"\n\n#include <QFileInfo>\n#include <QFileOpenEvent>\n#include <QIcon>\n#include <QTranslator>\n\nextern \"C\" {\n#include \"core\/version.h\"\n#include \"feature\/commandline.h\"\n#include \"util\/nointro.h\"\n#include \"util\/socket.h\"\n}\n\nusing namespace QGBA;\n\nstatic GBAApp* g_app = nullptr;\n\nmLOG_DEFINE_CATEGORY(QT, \"Qt\");\n\nGBAApp::GBAApp(int& argc, char* argv[])\n\t: QApplication(argc, argv)\n\t, m_windows{}\n\t, m_db(nullptr)\n{\n\tg_app = this;\n\n#ifdef BUILD_SDL\n\tSDL_Init(SDL_INIT_NOPARACHUTE);\n#endif\n\n#ifndef Q_OS_MAC\n\tsetWindowIcon(QIcon(\":\/res\/mgba-1024.png\"));\n#endif\n\n\tQTranslator* translator = new QTranslator(this);\n\tif (translator->load(QLocale(\"es\"), QLatin1String(binaryName), QLatin1String(\"-\"), QLatin1String(\":\/translations\"))) {\n\t\tinstallTranslator(translator);\n\t}\n\n\n\tSocketSubsystemInit();\n\tqRegisterMetaType<const uint32_t*>(\"const uint32_t*\");\n\tqRegisterMetaType<mCoreThread*>(\"mCoreThread*\");\n\n\tQApplication::setApplicationName(projectName);\n\tQApplication::setApplicationVersion(projectVersion);\n\n\tif (!m_configController.getQtOption(\"displayDriver\").isNull()) {\n\t\tDisplay::setDriver(static_cast<Display::Driver>(m_configController.getQtOption(\"displayDriver\").toInt()));\n\t}\n\n\tmArguments args;\n\tmGraphicsOpts graphicsOpts;\n\tmSubParser subparser;\n\tinitParserForGraphics(&subparser, &graphicsOpts);\n\tbool loaded = m_configController.parseArguments(&args, argc, argv, &subparser);\n\tif (loaded && args.showHelp) {\n\t\tusage(argv[0], subparser.usage);\n\t\t::exit(0);\n\t\treturn;\n\t}\n\n\treloadGameDB();\n\n\tif (!m_configController.getQtOption(\"audioDriver\").isNull()) {\n\t\tAudioProcessor::setDriver(static_cast<AudioProcessor::Driver>(m_configController.getQtOption(\"audioDriver\").toInt()));\n\t}\n\tWindow* w = new Window(&m_configController);\n\tconnect(w, &Window::destroyed, [this]() {\n\t\tm_windows[0] = nullptr;\n\t});\n\tm_windows[0] = w;\n\n\tif (loaded) {\n\t\tw->argumentsPassed(&args);\n\t} else {\n\t\tw->loadConfig();\n\t}\n\tfreeArguments(&args);\n\n\tif (graphicsOpts.multiplier) {\n\t\tw->resizeFrame(QSize(VIDEO_HORIZONTAL_PIXELS * graphicsOpts.multiplier, VIDEO_VERTICAL_PIXELS * graphicsOpts.multiplier));\n\t}\n\tif (graphicsOpts.fullscreen) {\n\t\tw->enterFullScreen();\n\t}\n\n\tw->show();\n\n\tw->controller()->setMultiplayerController(&m_multiplayer);\n\tw->multiplayerChanged();\n}\n\nbool GBAApp::event(QEvent* event) {\n\tif (event->type() == QEvent::FileOpen) {\n\t\tm_windows[0]->controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file());\n\t\treturn true;\n\t}\n\treturn QApplication::event(event);\n}\n\nWindow* GBAApp::newWindow() {\n\tif (m_multiplayer.attached() >= MAX_GBAS) {\n\t\treturn nullptr;\n\t}\n\tWindow* w = new Window(&m_configController, m_multiplayer.attached());\n\tint windowId = m_multiplayer.attached();\n\tconnect(w, &Window::destroyed, [this, windowId]() {\n\t\tm_windows[windowId] = nullptr;\n\t});\n\tm_windows[windowId] = w;\n\tw->setAttribute(Qt::WA_DeleteOnClose);\n\tw->loadConfig();\n\tw->show();\n\tw->controller()->setMultiplayerController(&m_multiplayer);\n\tw->multiplayerChanged();\n\treturn w;\n}\n\nGBAApp* GBAApp::app() {\n\treturn g_app;\n}\n\nvoid GBAApp::pauseAll(QList<int>* paused) {\n\tfor (int i = 0; i < MAX_GBAS; ++i) {\n\t\tif (!m_windows[i] || !m_windows[i]->controller()->isLoaded() || m_windows[i]->controller()->isPaused()) {\n\t\t\tcontinue;\n\t\t}\n\t\tm_windows[i]->controller()->setPaused(true);\n\t\tpaused->append(i);\n\t}\n}\n\nvoid GBAApp::continueAll(const QList<int>* paused) {\n\tfor (int i : *paused) {\n\t\tm_windows[i]->controller()->setPaused(false);\n\t}\n}\n\nQString GBAApp::getOpenFileName(QWidget* owner, const QString& title, const QString& filter) {\n\tQList<int> paused;\n\tpauseAll(&paused);\n\tQString filename = QFileDialog::getOpenFileName(owner, title, m_configController.getQtOption(\"lastDirectory\").toString(), filter);\n\tcontinueAll(&paused);\n\tif (!filename.isEmpty()) {\n\t\tm_configController.setQtOption(\"lastDirectory\", QFileInfo(filename).dir().path());\n\t}\n\treturn filename;\n}\n\nQString GBAApp::getSaveFileName(QWidget* owner, const QString& title, const QString& filter) {\n\tQList<int> paused;\n\tpauseAll(&paused);\n\tQString filename = QFileDialog::getSaveFileName(owner, title, m_configController.getQtOption(\"lastDirectory\").toString(), filter);\n\tcontinueAll(&paused);\n\tif (!filename.isEmpty()) {\n\t\tm_configController.setQtOption(\"lastDirectory\", QFileInfo(filename).dir().path());\n\t}\n\treturn filename;\n}\n\nQString GBAApp::getOpenDirectoryName(QWidget* owner, const QString& title) {\n\tQList<int> paused;\n\tpauseAll(&paused);\n\tQString filename = QFileDialog::getExistingDirectory(owner, title, m_configController.getQtOption(\"lastDirectory\").toString());\n\tcontinueAll(&paused);\n\tif (!filename.isEmpty()) {\n\t\tm_configController.setQtOption(\"lastDirectory\", QFileInfo(filename).dir().path());\n\t}\n\treturn filename;\n}\n\nQFileDialog* GBAApp::getOpenFileDialog(QWidget* owner, const QString& title, const QString& filter) {\n\tFileDialog* dialog = new FileDialog(this, owner, title, filter);\n\tdialog->setAcceptMode(QFileDialog::AcceptOpen);\n\treturn dialog;\n}\n\nQFileDialog* GBAApp::getSaveFileDialog(QWidget* owner, const QString& title, const QString& filter) {\n\tFileDialog* dialog = new FileDialog(this, owner, title, filter);\n\tdialog->setAcceptMode(QFileDialog::AcceptSave);\n\treturn dialog;\n}\n\nQString GBAApp::dataDir() {\n#ifdef DATADIR\n\tQString path = QString::fromUtf8(DATADIR);\n#else\n\tQString path = QCoreApplication::applicationDirPath();\n#ifdef Q_OS_MAC\n\tpath += QLatin1String(\"\/..\/Resources\");\n#endif\n#endif\n\treturn path;\n}\n\nbool GBAApp::reloadGameDB() {\n\tNoIntroDB* db = nullptr;\n\tVFile* vf = VFileDevice::open(dataDir() + \"\/nointro.dat\", O_RDONLY);\n\tif (vf) {\n\t\tdb = NoIntroDBLoad(vf);\n\t\tvf->close(vf);\n\t}\n\tif (db && m_db) {\n\t\tNoIntroDBDestroy(m_db);\n\t}\n\tif (db) {\n\t\tm_db = db;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nGBAApp::FileDialog::FileDialog(GBAApp* app, QWidget* parent, const QString& caption, const QString& filter)\n\t: QFileDialog(parent, caption, app->m_configController.getQtOption(\"lastDirectory\").toString(), filter)\n\t, m_app(app)\n{\n}\n\nint GBAApp::FileDialog::exec() {\n\tQList<int> paused;\n\tm_app->pauseAll(&paused);\n\tbool didAccept = QFileDialog::exec() == QDialog::Accepted;\n\tQStringList filenames = selectedFiles();\n\tif (!filenames.isEmpty()) {\n\t\tm_app->m_configController.setQtOption(\"lastDirectory\", QFileInfo(filenames[0]).dir().path());\n\t}\n\tm_app->continueAll(&paused);\n\treturn didAccept;\n}\n<commit_msg>Qt: Remove testing code<commit_after>\/* Copyright (c) 2013-2014 Jeffrey Pfau\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n#include \"GBAApp.h\"\n\n#include \"AudioProcessor.h\"\n#include \"Display.h\"\n#include \"GameController.h\"\n#include \"Window.h\"\n#include \"VFileDevice.h\"\n\n#include <QFileInfo>\n#include <QFileOpenEvent>\n#include <QIcon>\n#include <QTranslator>\n\nextern \"C\" {\n#include \"core\/version.h\"\n#include \"feature\/commandline.h\"\n#include \"util\/nointro.h\"\n#include \"util\/socket.h\"\n}\n\nusing namespace QGBA;\n\nstatic GBAApp* g_app = nullptr;\n\nmLOG_DEFINE_CATEGORY(QT, \"Qt\");\n\nGBAApp::GBAApp(int& argc, char* argv[])\n\t: QApplication(argc, argv)\n\t, m_windows{}\n\t, m_db(nullptr)\n{\n\tg_app = this;\n\n#ifdef BUILD_SDL\n\tSDL_Init(SDL_INIT_NOPARACHUTE);\n#endif\n\n#ifndef Q_OS_MAC\n\tsetWindowIcon(QIcon(\":\/res\/mgba-1024.png\"));\n#endif\n\n\tQTranslator* translator = new QTranslator(this);\n\tif (translator->load(QLocale(), QLatin1String(binaryName), QLatin1String(\"-\"), QLatin1String(\":\/translations\"))) {\n\t\tinstallTranslator(translator);\n\t}\n\n\n\tSocketSubsystemInit();\n\tqRegisterMetaType<const uint32_t*>(\"const uint32_t*\");\n\tqRegisterMetaType<mCoreThread*>(\"mCoreThread*\");\n\n\tQApplication::setApplicationName(projectName);\n\tQApplication::setApplicationVersion(projectVersion);\n\n\tif (!m_configController.getQtOption(\"displayDriver\").isNull()) {\n\t\tDisplay::setDriver(static_cast<Display::Driver>(m_configController.getQtOption(\"displayDriver\").toInt()));\n\t}\n\n\tmArguments args;\n\tmGraphicsOpts graphicsOpts;\n\tmSubParser subparser;\n\tinitParserForGraphics(&subparser, &graphicsOpts);\n\tbool loaded = m_configController.parseArguments(&args, argc, argv, &subparser);\n\tif (loaded && args.showHelp) {\n\t\tusage(argv[0], subparser.usage);\n\t\t::exit(0);\n\t\treturn;\n\t}\n\n\treloadGameDB();\n\n\tif (!m_configController.getQtOption(\"audioDriver\").isNull()) {\n\t\tAudioProcessor::setDriver(static_cast<AudioProcessor::Driver>(m_configController.getQtOption(\"audioDriver\").toInt()));\n\t}\n\tWindow* w = new Window(&m_configController);\n\tconnect(w, &Window::destroyed, [this]() {\n\t\tm_windows[0] = nullptr;\n\t});\n\tm_windows[0] = w;\n\n\tif (loaded) {\n\t\tw->argumentsPassed(&args);\n\t} else {\n\t\tw->loadConfig();\n\t}\n\tfreeArguments(&args);\n\n\tif (graphicsOpts.multiplier) {\n\t\tw->resizeFrame(QSize(VIDEO_HORIZONTAL_PIXELS * graphicsOpts.multiplier, VIDEO_VERTICAL_PIXELS * graphicsOpts.multiplier));\n\t}\n\tif (graphicsOpts.fullscreen) {\n\t\tw->enterFullScreen();\n\t}\n\n\tw->show();\n\n\tw->controller()->setMultiplayerController(&m_multiplayer);\n\tw->multiplayerChanged();\n}\n\nbool GBAApp::event(QEvent* event) {\n\tif (event->type() == QEvent::FileOpen) {\n\t\tm_windows[0]->controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file());\n\t\treturn true;\n\t}\n\treturn QApplication::event(event);\n}\n\nWindow* GBAApp::newWindow() {\n\tif (m_multiplayer.attached() >= MAX_GBAS) {\n\t\treturn nullptr;\n\t}\n\tWindow* w = new Window(&m_configController, m_multiplayer.attached());\n\tint windowId = m_multiplayer.attached();\n\tconnect(w, &Window::destroyed, [this, windowId]() {\n\t\tm_windows[windowId] = nullptr;\n\t});\n\tm_windows[windowId] = w;\n\tw->setAttribute(Qt::WA_DeleteOnClose);\n\tw->loadConfig();\n\tw->show();\n\tw->controller()->setMultiplayerController(&m_multiplayer);\n\tw->multiplayerChanged();\n\treturn w;\n}\n\nGBAApp* GBAApp::app() {\n\treturn g_app;\n}\n\nvoid GBAApp::pauseAll(QList<int>* paused) {\n\tfor (int i = 0; i < MAX_GBAS; ++i) {\n\t\tif (!m_windows[i] || !m_windows[i]->controller()->isLoaded() || m_windows[i]->controller()->isPaused()) {\n\t\t\tcontinue;\n\t\t}\n\t\tm_windows[i]->controller()->setPaused(true);\n\t\tpaused->append(i);\n\t}\n}\n\nvoid GBAApp::continueAll(const QList<int>* paused) {\n\tfor (int i : *paused) {\n\t\tm_windows[i]->controller()->setPaused(false);\n\t}\n}\n\nQString GBAApp::getOpenFileName(QWidget* owner, const QString& title, const QString& filter) {\n\tQList<int> paused;\n\tpauseAll(&paused);\n\tQString filename = QFileDialog::getOpenFileName(owner, title, m_configController.getQtOption(\"lastDirectory\").toString(), filter);\n\tcontinueAll(&paused);\n\tif (!filename.isEmpty()) {\n\t\tm_configController.setQtOption(\"lastDirectory\", QFileInfo(filename).dir().path());\n\t}\n\treturn filename;\n}\n\nQString GBAApp::getSaveFileName(QWidget* owner, const QString& title, const QString& filter) {\n\tQList<int> paused;\n\tpauseAll(&paused);\n\tQString filename = QFileDialog::getSaveFileName(owner, title, m_configController.getQtOption(\"lastDirectory\").toString(), filter);\n\tcontinueAll(&paused);\n\tif (!filename.isEmpty()) {\n\t\tm_configController.setQtOption(\"lastDirectory\", QFileInfo(filename).dir().path());\n\t}\n\treturn filename;\n}\n\nQString GBAApp::getOpenDirectoryName(QWidget* owner, const QString& title) {\n\tQList<int> paused;\n\tpauseAll(&paused);\n\tQString filename = QFileDialog::getExistingDirectory(owner, title, m_configController.getQtOption(\"lastDirectory\").toString());\n\tcontinueAll(&paused);\n\tif (!filename.isEmpty()) {\n\t\tm_configController.setQtOption(\"lastDirectory\", QFileInfo(filename).dir().path());\n\t}\n\treturn filename;\n}\n\nQFileDialog* GBAApp::getOpenFileDialog(QWidget* owner, const QString& title, const QString& filter) {\n\tFileDialog* dialog = new FileDialog(this, owner, title, filter);\n\tdialog->setAcceptMode(QFileDialog::AcceptOpen);\n\treturn dialog;\n}\n\nQFileDialog* GBAApp::getSaveFileDialog(QWidget* owner, const QString& title, const QString& filter) {\n\tFileDialog* dialog = new FileDialog(this, owner, title, filter);\n\tdialog->setAcceptMode(QFileDialog::AcceptSave);\n\treturn dialog;\n}\n\nQString GBAApp::dataDir() {\n#ifdef DATADIR\n\tQString path = QString::fromUtf8(DATADIR);\n#else\n\tQString path = QCoreApplication::applicationDirPath();\n#ifdef Q_OS_MAC\n\tpath += QLatin1String(\"\/..\/Resources\");\n#endif\n#endif\n\treturn path;\n}\n\nbool GBAApp::reloadGameDB() {\n\tNoIntroDB* db = nullptr;\n\tVFile* vf = VFileDevice::open(dataDir() + \"\/nointro.dat\", O_RDONLY);\n\tif (vf) {\n\t\tdb = NoIntroDBLoad(vf);\n\t\tvf->close(vf);\n\t}\n\tif (db && m_db) {\n\t\tNoIntroDBDestroy(m_db);\n\t}\n\tif (db) {\n\t\tm_db = db;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nGBAApp::FileDialog::FileDialog(GBAApp* app, QWidget* parent, const QString& caption, const QString& filter)\n\t: QFileDialog(parent, caption, app->m_configController.getQtOption(\"lastDirectory\").toString(), filter)\n\t, m_app(app)\n{\n}\n\nint GBAApp::FileDialog::exec() {\n\tQList<int> paused;\n\tm_app->pauseAll(&paused);\n\tbool didAccept = QFileDialog::exec() == QDialog::Accepted;\n\tQStringList filenames = selectedFiles();\n\tif (!filenames.isEmpty()) {\n\t\tm_app->m_configController.setQtOption(\"lastDirectory\", QFileInfo(filenames[0]).dir().path());\n\t}\n\tm_app->continueAll(&paused);\n\treturn didAccept;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fcntl.h>\n#include <algorithm>\n#include <cstring>\n#include <cstdlib>\n#include <vector>\n\n#include \"common.hpp\"\n#include \"utils\/file.hpp\"\n\nusing namespace polybar;\nusing namespace std;\n\n#ifndef IPC_CHANNEL_PREFIX\n#define IPC_CHANNEL_PREFIX \"\/tmp\/polybar_mqueue.\"\n#endif\n\nvoid log(const string& msg) {\n fprintf(stderr, \"polybar-msg: %s\\n\", msg.c_str());\n}\n\nvoid log(int exit_code, const string& msg) {\n fprintf(stderr, \"polybar-msg: %s\\n\", msg.c_str());\n exit(exit_code);\n}\n\nvoid usage(const string& parameters) {\n fprintf(stderr, \"Usage: polybar-msg [-p pid] %s\\n\", parameters.c_str());\n exit(127);\n}\n\nbool validate_type(const string& type) {\n if (type == \"action\") {\n return true;\n } else if (type == \"cmd\") {\n return true;\n } else if (type == \"hook\") {\n return true;\n } else {\n return false;\n }\n}\n\nint main(int argc, char** argv) {\n const int E_GENERIC{1};\n const int E_NO_CHANNELS{2};\n const int E_MESSAGE_TYPE{3};\n const int E_INVALID_PID{4};\n const int E_INVALID_CHANNEL{5};\n const int E_WRITE{6};\n\n vector<string> args{argv + 1, argv + argc};\n string::size_type p;\n int pid{0};\n\n \/\/ If -p <pid> is passed, check if the process is running and that\n \/\/ a valid channel pipe is available\n if (args.size() >= 2 && args[0].compare(0, 2, \"-p\") == 0) {\n if (!file_util::exists(\"\/proc\/\" + args[1])) {\n log(E_INVALID_PID, \"No process with pid \" + args[1]);\n } else if (!file_util::is_fifo(IPC_CHANNEL_PREFIX + args[1])) {\n log(E_INVALID_CHANNEL, \"No channel available for pid \" + args[1]);\n }\n\n pid = atoi(args[1].c_str());\n args.erase(args.begin());\n args.erase(args.begin());\n }\n\n \/\/ Validate args\n if (args.size() < 2) {\n usage(\"<command=(action|cmd|hook)> <payload> [...]\");\n } else if (!validate_type(args[0])) {\n log(E_MESSAGE_TYPE, \"\\\"\" + args[0] + \"\\\" is not a valid type.\");\n }\n\n string ipc_type{args[0]};\n args.erase(args.begin());\n string ipc_payload{args[0]};\n args.erase(args.begin());\n\n \/\/ Check hook specific args\n if (ipc_type == \"hook\") {\n if (args.size() != 1) {\n usage(\"hook <module-name> <hook-index>\");\n } else if ((p = ipc_payload.find(\"module\/\")) != 0) {\n ipc_payload = \"module\/\" + ipc_payload + args[0];\n args.erase(args.begin());\n } else {\n ipc_payload += args[0];\n args.erase(args.begin());\n }\n }\n\n \/\/ Get availble channel pipes\n auto channels = file_util::glob(IPC_CHANNEL_PREFIX + \"*\"s);\n if (channels.empty()) {\n log(E_NO_CHANNELS, \"There are no active ipc channels\");\n }\n\n \/\/ Write the message to each channel in the list and remove stale\n \/\/ channel pipes that may be left lingering if the owning process got\n \/\/ SIGKILLED or crashed\n for (auto&& channel : channels) {\n string handle{channel};\n int handle_pid{0};\n\n if ((p = handle.rfind('.')) != string::npos) {\n handle_pid = atoi(handle.substr(p + 1).c_str());\n }\n\n if (!file_util::exists(\"\/proc\/\" + to_string(handle_pid))) {\n if (unlink(handle.c_str()) == -1) {\n log(E_GENERIC, \"Could not remove stale ipc channel: \"s + strerror(errno));\n } else {\n log(\"Removed stale ipc channel: \" + handle);\n }\n } else if (!pid || pid == handle_pid) {\n string payload{ipc_type + ':' + ipc_payload};\n file_descriptor fd(handle, O_WRONLY);\n if (write(fd, payload.c_str(), payload.size()) != -1) {\n log(\"Successfully wrote \\\"\" + payload + \"\\\" to \\\"\" + handle + \"\\\"\");\n } else {\n log(E_WRITE, \"Failed to write \\\"\" + payload + \"\\\" to \\\"\" + handle + \"\\\" (err: \" + strerror(errno) + \")\");\n }\n }\n }\n\n return 0;\n}\n<commit_msg>refactor(ipc): More state checks<commit_after>#include <fcntl.h>\n#include <algorithm>\n#include <cstdlib>\n#include <cstring>\n#include <vector>\n\n#include \"common.hpp\"\n#include \"utils\/file.hpp\"\n#include \"utils\/io.hpp\"\n\nusing namespace polybar;\nusing namespace std;\n\n#ifndef IPC_CHANNEL_PREFIX\n#define IPC_CHANNEL_PREFIX \"\/tmp\/polybar_mqueue.\"\n#endif\n\nvoid log(const string& msg) {\n fprintf(stderr, \"polybar-msg: %s\\n\", msg.c_str());\n}\n\nvoid log(int exit_code, const string& msg) {\n fprintf(stderr, \"polybar-msg: %s\\n\", msg.c_str());\n exit(exit_code);\n}\n\nvoid usage(const string& parameters) {\n fprintf(stderr, \"Usage: polybar-msg [-p pid] %s\\n\", parameters.c_str());\n exit(127);\n}\n\nvoid remove_pipe(const string& handle) {\n if (unlink(handle.c_str()) == -1) {\n log(1, \"Could not remove stale ipc channel: \"s + strerror(errno));\n } else {\n log(\"Removed stale ipc channel: \" + handle);\n }\n}\n\nbool validate_type(const string& type) {\n if (type == \"action\") {\n return true;\n } else if (type == \"cmd\") {\n return true;\n } else if (type == \"hook\") {\n return true;\n } else {\n return false;\n }\n}\n\nint main(int argc, char** argv) {\n const int E_NO_CHANNELS{2};\n const int E_MESSAGE_TYPE{3};\n const int E_INVALID_PID{4};\n const int E_INVALID_CHANNEL{5};\n const int E_WRITE{6};\n\n vector<string> args{argv + 1, argv + argc};\n string::size_type p;\n int pid{0};\n\n \/\/ If -p <pid> is passed, check if the process is running and that\n \/\/ a valid channel pipe is available\n if (args.size() >= 2 && args[0].compare(0, 2, \"-p\") == 0) {\n if (!file_util::exists(\"\/proc\/\" + args[1])) {\n log(E_INVALID_PID, \"No process with pid \" + args[1]);\n } else if (!file_util::exists(IPC_CHANNEL_PREFIX + args[1])) {\n log(E_INVALID_CHANNEL, \"No channel available for pid \" + args[1]);\n }\n\n pid = atoi(args[1].c_str());\n args.erase(args.begin());\n args.erase(args.begin());\n }\n\n \/\/ Validate args\n auto help = find_if(args.begin(), args.end(), [](string a) { return a == \"-h\" || a == \"--help\"; }) != args.end();\n if (help || args.size() < 2) {\n usage(\"<command=(action|cmd|hook)> <payload> [...]\");\n } else if (!validate_type(args[0])) {\n log(E_MESSAGE_TYPE, \"\\\"\" + args[0] + \"\\\" is not a valid type.\");\n }\n\n string ipc_type{args[0]};\n args.erase(args.begin());\n string ipc_payload{args[0]};\n args.erase(args.begin());\n\n \/\/ Check hook specific args\n if (ipc_type == \"hook\") {\n if (args.size() != 1) {\n usage(\"hook <module-name> <hook-index>\");\n } else if ((p = ipc_payload.find(\"module\/\")) != 0) {\n ipc_payload = \"module\/\" + ipc_payload + args[0];\n args.erase(args.begin());\n } else {\n ipc_payload += args[0];\n args.erase(args.begin());\n }\n }\n\n \/\/ Get availble channel pipes\n auto pipes = file_util::glob(IPC_CHANNEL_PREFIX + \"*\"s);\n\n \/\/ Remove stale channel files without a running parent process\n for (auto it = pipes.rbegin(); it != pipes.rend(); it++) {\n if ((p = it->rfind('.')) == string::npos) {\n continue;\n } else if (!file_util::exists(\"\/proc\/\" + it->substr(p + 1))) {\n remove_pipe(*it);\n pipes.erase(remove(pipes.begin(), pipes.end(), *it), pipes.end());\n } else if (pid && to_string(pid) != it->substr(p + 1)) {\n pipes.erase(remove(pipes.begin(), pipes.end(), *it), pipes.end());\n }\n }\n\n if (pipes.empty()) {\n log(E_NO_CHANNELS, \"No active ipc channels\");\n }\n\n int exit_status = 127;\n\n \/\/ Write message to each available channel or match\n \/\/ against pid if one was defined\n for (auto&& channel : pipes) {\n try {\n file_descriptor fd(channel, O_WRONLY | O_NONBLOCK);\n string payload{ipc_type + ':' + ipc_payload};\n if (write(fd, payload.c_str(), payload.size()) != -1) {\n log(\"Successfully wrote \\\"\" + payload + \"\\\" to \\\"\" + channel + \"\\\"\");\n exit_status = 0;\n } else {\n log(E_WRITE, \"Failed to write \\\"\" + payload + \"\\\" to \\\"\" + channel + \"\\\" (err: \" + strerror(errno) + \")\");\n }\n } catch (const exception& err) {\n remove_pipe(channel);\n }\n }\n\n return exit_status;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/lelantus.h\"\n#include \"..\/validation.h\"\n#include \"..\/wallet\/wallet.h\"\n\n#include \"automintmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"guiconstants.h\"\n#include \"optionsmodel.h\"\n#include \"lelantusmodel.h\"\n\nIncomingFundNotifier::IncomingFundNotifier(\n CWallet *_wallet, QObject *parent) :\n QObject(parent), wallet(_wallet), timer(0)\n{\n timer = new QTimer(this);\n timer->setSingleShot(true);\n\n connect(timer,\n SIGNAL(timeout()),\n this,\n SLOT(check()),\n Qt::QueuedConnection);\n\n importTransactions();\n subscribeToCoreSignals();\n}\n\nIncomingFundNotifier::~IncomingFundNotifier()\n{\n unsubscribeFromCoreSignals();\n\n delete timer;\n\n timer = nullptr;\n}\n\nvoid IncomingFundNotifier::newBlock()\n{\n LOCK(cs);\n\n if (!txs.empty()) {\n resetTimer();\n }\n}\n\nvoid IncomingFundNotifier::pushTransaction(uint256 const &id)\n{\n LOCK(cs);\n\n txs.push_back(id);\n resetTimer();\n}\n\nvoid IncomingFundNotifier::check()\n{\n LOCK(cs);\n\n if (txs.empty()) {\n return;\n }\n\n CAmount credit = 0;\n std::vector<uint256> immatures;\n\n {\n LOCK2(cs_main, wallet->cs_wallet);\n while (!txs.empty()) {\n auto const &tx = txs.back();\n txs.pop_back();\n\n auto wtx = wallet->mapWallet.find(tx);\n if (wtx == wallet->mapWallet.end()) {\n continue;\n }\n\n credit += std::max(CAmount(0), wtx->second.GetAvailableCredit() - wtx->second.GetDebit(ISMINE_ALL));\n\n if (wtx->second.GetImmatureCredit() > 0) {\n immatures.push_back(tx);\n }\n }\n }\n\n for (auto const &tx : immatures) {\n txs.push_back(tx);\n }\n\n if (credit > 0) {\n Q_EMIT matureFund(credit);\n }\n}\n\nvoid IncomingFundNotifier::importTransactions()\n{\n LOCK(cs);\n LOCK2(cs_main, wallet->cs_wallet);\n\n for (auto const &tx : wallet->mapWallet) {\n if (tx.second.GetAvailableCredit() > 0 || tx.second.GetImmatureCredit() > 0) {\n txs.push_back(tx.first);\n }\n }\n\n resetTimer();\n}\n\nvoid IncomingFundNotifier::resetTimer()\n{\n timer->stop();\n timer->start(1000);\n}\n\n\/\/ Handlers for core signals\nstatic void NotifyTransactionChanged(\n IncomingFundNotifier *model, CWallet *wallet, uint256 const &hash, ChangeType status)\n{\n Q_UNUSED(wallet);\n Q_UNUSED(status);\n if (status == ChangeType::CT_NEW || status == ChangeType::CT_UPDATED) {\n QMetaObject::invokeMethod(\n model,\n \"pushTransaction\",\n Qt::QueuedConnection,\n Q_ARG(uint256, hash));\n }\n}\n\nstatic void IncomingFundNotifyBlockTip(\n IncomingFundNotifier *model, bool initialSync, const CBlockIndex *pIndex)\n{\n Q_UNUSED(initialSync);\n Q_UNUSED(pIndex);\n QMetaObject::invokeMethod(\n model,\n \"newBlock\",\n Qt::QueuedConnection);\n}\n\nvoid IncomingFundNotifier::subscribeToCoreSignals()\n{\n wallet->NotifyTransactionChanged.connect(boost::bind(\n NotifyTransactionChanged, this, _1, _2, _3));\n\n uiInterface.NotifyBlockTip.connect(\n boost::bind(IncomingFundNotifyBlockTip, this, _1, _2));\n}\n\nvoid IncomingFundNotifier::unsubscribeFromCoreSignals()\n{\n wallet->NotifyTransactionChanged.disconnect(boost::bind(\n NotifyTransactionChanged, this, _1, _2, _3));\n\n uiInterface.NotifyBlockTip.disconnect(\n boost::bind(IncomingFundNotifyBlockTip, this, _1, _2));\n}\n\nAutoMintModel::AutoMintModel(\n LelantusModel *_lelantusModel,\n OptionsModel *_optionsModel,\n CWallet *_wallet,\n QObject *parent) :\n QObject(parent),\n lelantusModel(_lelantusModel),\n optionsModel(_optionsModel),\n wallet(_wallet),\n autoMintState(AutoMintState::Disabled),\n resetSyncingTimer(0),\n autoMintCheckTimer(0),\n syncing(false),\n notifier(0)\n{\n resetSyncingTimer = new QTimer(this);\n resetSyncingTimer->setSingleShot(true);\n\n autoMintCheckTimer = new QTimer(this);\n autoMintCheckTimer->setSingleShot(false);\n\n connect(resetSyncingTimer, SIGNAL(timeout()), this, SLOT(resetSyncing()));\n connect(autoMintCheckTimer, SIGNAL(timeout()), this, SLOT(checkAutoMint()));\n\n notifier = new IncomingFundNotifier(wallet, this);\n\n connect(notifier, SIGNAL(matureFund(CAmount)), this, SLOT(startAutoMint()));\n\n connect(optionsModel,\n SIGNAL(autoAnonymizeChanged(bool)),\n this,\n SLOT(updateAutoMintOption(bool)));\n\n subscribeToCoreSignals();\n}\n\nAutoMintModel::~AutoMintModel()\n{\n unsubscribeFromCoreSignals();\n\n delete resetSyncingTimer;\n delete autoMintCheckTimer;\n\n resetSyncingTimer = nullptr;\n autoMintCheckTimer = nullptr;\n}\n\nbool AutoMintModel::askingUser() const\n{\n return autoMintState == AutoMintState::WaitingForUserResponse;\n}\n\nvoid AutoMintModel::userAskToMint()\n{\n autoMintCheckTimer->stop();\n checkAutoMint(true);\n}\n\nvoid AutoMintModel::ackMintAll(AutoMintAck ack, CAmount minted, QString error)\n{\n LOCK(lelantusModel->cs);\n if (ack == AutoMintAck::WaitUserToActive) {\n autoMintState = AutoMintState::WaitingUserToActivate;\n } else {\n autoMintState = AutoMintState::WaitingIncomingFund;\n autoMintCheckTimer->stop();\n }\n\n processAutoMintAck(ack, minted, error);\n}\n\nvoid AutoMintModel::checkAutoMint(bool force)\n{\n \/\/ if lelantus is not allow or client is in initial syncing state then wait\n \/\/ except user force to check\n if (!force) {\n \/\/ check syncing first to reduce main locking\n if (syncing) {\n return;\n }\n\n bool allowed = lelantus::IsLelantusAllowed();\n if (!allowed) {\n return;\n }\n }\n\n {\n LOCK(lelantusModel->cs);\n\n if (fReindex) {\n return;\n }\n\n switch (autoMintState) {\n case AutoMintState::Disabled:\n case AutoMintState::WaitingIncomingFund:\n if (force) {\n break;\n }\n autoMintCheckTimer->stop();\n return;\n case AutoMintState::WaitingUserToActivate:\n break;\n case AutoMintState::WaitingForUserResponse:\n return;\n default:\n throw std::runtime_error(\"Unknown auto mint state\");\n }\n\n autoMintState = AutoMintState::WaitingForUserResponse;\n }\n\n lelantusModel->askUserToMint(force);\n}\n\nvoid AutoMintModel::setSyncing()\n{\n syncing.store(true);\n resetSyncingTimer->stop();\n\n \/\/ wait 2.5 seconds if there are no new signal then reset flag\n resetSyncingTimer->start(2500);\n}\n\nvoid AutoMintModel::resetSyncing()\n{\n syncing.store(false);\n}\n\nvoid AutoMintModel::startAutoMint()\n{\n if (autoMintCheckTimer->isActive()) {\n return;\n }\n\n CAmount mintable = 0;\n {\n LOCK2(cs_main, wallet->cs_wallet);\n mintable = lelantusModel->getMintableAmount();\n }\n\n if (mintable > 0) {\n autoMintState = AutoMintState::WaitingUserToActivate;\n\n autoMintCheckTimer->start(MODEL_UPDATE_DELAY);\n } else {\n autoMintState = AutoMintState::WaitingIncomingFund;\n }\n}\n\nvoid AutoMintModel::updateAutoMintOption(bool enabled)\n{\n LOCK2(cs_main, wallet->cs_wallet);\n LOCK(lelantusModel->cs);\n\n if (enabled) {\n if (autoMintState == AutoMintState::Disabled) {\n startAutoMint();\n }\n } else {\n if (autoMintCheckTimer->isActive()) {\n autoMintCheckTimer->stop();\n }\n\n \/\/ stop mint\n autoMintState = AutoMintState::Disabled;\n }\n}\n\n\/\/ Handlers for core signals\nstatic void NotifyBlockTip(AutoMintModel *model, bool initialSync, const CBlockIndex *pIndex)\n{\n Q_UNUSED(pIndex);\n Q_UNUSED(initialSync);\n QMetaObject::invokeMethod(\n model,\n \"setSyncing\",\n Qt::QueuedConnection);\n}\n\nvoid AutoMintModel::subscribeToCoreSignals()\n{\n uiInterface.NotifyBlockTip.connect(\n boost::bind(NotifyBlockTip, this, _1, _2));\n}\n\nvoid AutoMintModel::unsubscribeFromCoreSignals()\n{\n uiInterface.NotifyBlockTip.disconnect(\n boost::bind(NotifyBlockTip, this, _1, _2));\n}\n\nvoid AutoMintModel::processAutoMintAck(AutoMintAck ack, CAmount minted, QString error)\n{\n QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;\n msgParams.second = CClientUIInterface::MSG_WARNING;\n\n switch (ack)\n {\n case AutoMintAck::Success:\n msgParams.first = tr(\"Success to anonymize, %1\")\n .arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), minted));\n msgParams.second = CClientUIInterface::MSG_INFORMATION;\n break;\n case AutoMintAck::WaitUserToActive:\n case AutoMintAck::NotEnoughFund:\n return;\n case AutoMintAck::FailToMint:\n msgParams.first = tr(\"Fail to mint, %1\").arg(error);\n msgParams.second = CClientUIInterface::MSG_ERROR;\n break;\n case AutoMintAck::FailToUnlock:\n msgParams.first = tr(\"Fail to unlock wallet\");\n msgParams.second = CClientUIInterface::MSG_ERROR;\n break;\n default:\n return;\n };\n\n Q_EMIT message(tr(\"Auto Anonymize\"), msgParams.first, msgParams.second);\n}<commit_msg>Add guard to prevent automint if the flag is not set<commit_after>#include \"..\/lelantus.h\"\n#include \"..\/validation.h\"\n#include \"..\/wallet\/wallet.h\"\n\n#include \"automintmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"guiconstants.h\"\n#include \"optionsmodel.h\"\n#include \"lelantusmodel.h\"\n\nIncomingFundNotifier::IncomingFundNotifier(\n CWallet *_wallet, QObject *parent) :\n QObject(parent), wallet(_wallet), timer(0)\n{\n timer = new QTimer(this);\n timer->setSingleShot(true);\n\n connect(timer,\n SIGNAL(timeout()),\n this,\n SLOT(check()),\n Qt::QueuedConnection);\n\n importTransactions();\n subscribeToCoreSignals();\n}\n\nIncomingFundNotifier::~IncomingFundNotifier()\n{\n unsubscribeFromCoreSignals();\n\n delete timer;\n\n timer = nullptr;\n}\n\nvoid IncomingFundNotifier::newBlock()\n{\n LOCK(cs);\n\n if (!txs.empty()) {\n resetTimer();\n }\n}\n\nvoid IncomingFundNotifier::pushTransaction(uint256 const &id)\n{\n LOCK(cs);\n\n txs.push_back(id);\n resetTimer();\n}\n\nvoid IncomingFundNotifier::check()\n{\n LOCK(cs);\n\n if (txs.empty()) {\n return;\n }\n\n CAmount credit = 0;\n std::vector<uint256> immatures;\n\n {\n LOCK2(cs_main, wallet->cs_wallet);\n while (!txs.empty()) {\n auto const &tx = txs.back();\n txs.pop_back();\n\n auto wtx = wallet->mapWallet.find(tx);\n if (wtx == wallet->mapWallet.end()) {\n continue;\n }\n\n credit += std::max(CAmount(0), wtx->second.GetAvailableCredit() - wtx->second.GetDebit(ISMINE_ALL));\n\n if (wtx->second.GetImmatureCredit() > 0) {\n immatures.push_back(tx);\n }\n }\n }\n\n for (auto const &tx : immatures) {\n txs.push_back(tx);\n }\n\n if (credit > 0) {\n Q_EMIT matureFund(credit);\n }\n}\n\nvoid IncomingFundNotifier::importTransactions()\n{\n LOCK(cs);\n LOCK2(cs_main, wallet->cs_wallet);\n\n for (auto const &tx : wallet->mapWallet) {\n if (tx.second.GetAvailableCredit() > 0 || tx.second.GetImmatureCredit() > 0) {\n txs.push_back(tx.first);\n }\n }\n\n resetTimer();\n}\n\nvoid IncomingFundNotifier::resetTimer()\n{\n timer->stop();\n timer->start(1000);\n}\n\n\/\/ Handlers for core signals\nstatic void NotifyTransactionChanged(\n IncomingFundNotifier *model, CWallet *wallet, uint256 const &hash, ChangeType status)\n{\n Q_UNUSED(wallet);\n Q_UNUSED(status);\n if (status == ChangeType::CT_NEW || status == ChangeType::CT_UPDATED) {\n QMetaObject::invokeMethod(\n model,\n \"pushTransaction\",\n Qt::QueuedConnection,\n Q_ARG(uint256, hash));\n }\n}\n\nstatic void IncomingFundNotifyBlockTip(\n IncomingFundNotifier *model, bool initialSync, const CBlockIndex *pIndex)\n{\n Q_UNUSED(initialSync);\n Q_UNUSED(pIndex);\n QMetaObject::invokeMethod(\n model,\n \"newBlock\",\n Qt::QueuedConnection);\n}\n\nvoid IncomingFundNotifier::subscribeToCoreSignals()\n{\n wallet->NotifyTransactionChanged.connect(boost::bind(\n NotifyTransactionChanged, this, _1, _2, _3));\n\n uiInterface.NotifyBlockTip.connect(\n boost::bind(IncomingFundNotifyBlockTip, this, _1, _2));\n}\n\nvoid IncomingFundNotifier::unsubscribeFromCoreSignals()\n{\n wallet->NotifyTransactionChanged.disconnect(boost::bind(\n NotifyTransactionChanged, this, _1, _2, _3));\n\n uiInterface.NotifyBlockTip.disconnect(\n boost::bind(IncomingFundNotifyBlockTip, this, _1, _2));\n}\n\nAutoMintModel::AutoMintModel(\n LelantusModel *_lelantusModel,\n OptionsModel *_optionsModel,\n CWallet *_wallet,\n QObject *parent) :\n QObject(parent),\n lelantusModel(_lelantusModel),\n optionsModel(_optionsModel),\n wallet(_wallet),\n autoMintState(AutoMintState::Disabled),\n resetSyncingTimer(0),\n autoMintCheckTimer(0),\n syncing(false),\n notifier(0)\n{\n resetSyncingTimer = new QTimer(this);\n resetSyncingTimer->setSingleShot(true);\n\n autoMintCheckTimer = new QTimer(this);\n autoMintCheckTimer->setSingleShot(false);\n\n connect(resetSyncingTimer, SIGNAL(timeout()), this, SLOT(resetSyncing()));\n connect(autoMintCheckTimer, SIGNAL(timeout()), this, SLOT(checkAutoMint()));\n\n notifier = new IncomingFundNotifier(wallet, this);\n\n connect(notifier, SIGNAL(matureFund(CAmount)), this, SLOT(startAutoMint()));\n\n connect(optionsModel,\n SIGNAL(autoAnonymizeChanged(bool)),\n this,\n SLOT(updateAutoMintOption(bool)));\n\n subscribeToCoreSignals();\n}\n\nAutoMintModel::~AutoMintModel()\n{\n unsubscribeFromCoreSignals();\n\n delete resetSyncingTimer;\n delete autoMintCheckTimer;\n\n resetSyncingTimer = nullptr;\n autoMintCheckTimer = nullptr;\n}\n\nbool AutoMintModel::askingUser() const\n{\n return autoMintState == AutoMintState::WaitingForUserResponse;\n}\n\nvoid AutoMintModel::userAskToMint()\n{\n autoMintCheckTimer->stop();\n checkAutoMint(true);\n}\n\nvoid AutoMintModel::ackMintAll(AutoMintAck ack, CAmount minted, QString error)\n{\n LOCK(lelantusModel->cs);\n if (ack == AutoMintAck::WaitUserToActive) {\n autoMintState = AutoMintState::WaitingUserToActivate;\n } else {\n autoMintState = AutoMintState::WaitingIncomingFund;\n autoMintCheckTimer->stop();\n }\n\n processAutoMintAck(ack, minted, error);\n}\n\nvoid AutoMintModel::checkAutoMint(bool force)\n{\n \/\/ if lelantus is not allow or client is in initial syncing state then wait\n \/\/ except user force to check\n if (!force) {\n \/\/ check syncing first to reduce main locking\n if (syncing) {\n return;\n }\n\n bool allowed = lelantus::IsLelantusAllowed();\n if (!allowed) {\n return;\n }\n }\n\n {\n LOCK(lelantusModel->cs);\n\n if (fReindex) {\n return;\n }\n\n switch (autoMintState) {\n case AutoMintState::Disabled:\n case AutoMintState::WaitingIncomingFund:\n if (force) {\n break;\n }\n autoMintCheckTimer->stop();\n return;\n case AutoMintState::WaitingUserToActivate:\n break;\n case AutoMintState::WaitingForUserResponse:\n return;\n default:\n throw std::runtime_error(\"Unknown auto mint state\");\n }\n\n autoMintState = AutoMintState::WaitingForUserResponse;\n }\n\n lelantusModel->askUserToMint(force);\n}\n\nvoid AutoMintModel::setSyncing()\n{\n syncing.store(true);\n resetSyncingTimer->stop();\n\n \/\/ wait 2.5 seconds if there are no new signal then reset flag\n resetSyncingTimer->start(2500);\n}\n\nvoid AutoMintModel::resetSyncing()\n{\n syncing.store(false);\n}\n\nvoid AutoMintModel::startAutoMint()\n{\n if (autoMintCheckTimer->isActive()) {\n return;\n }\n\n if (!optionsModel->getAutoAnonymize()) {\n return;\n }\n\n CAmount mintable = 0;\n {\n LOCK2(cs_main, wallet->cs_wallet);\n mintable = lelantusModel->getMintableAmount();\n }\n\n if (mintable > 0) {\n autoMintState = AutoMintState::WaitingUserToActivate;\n\n autoMintCheckTimer->start(MODEL_UPDATE_DELAY);\n } else {\n autoMintState = AutoMintState::WaitingIncomingFund;\n }\n}\n\nvoid AutoMintModel::updateAutoMintOption(bool enabled)\n{\n LOCK2(cs_main, wallet->cs_wallet);\n LOCK(lelantusModel->cs);\n\n if (enabled) {\n if (autoMintState == AutoMintState::Disabled) {\n startAutoMint();\n }\n } else {\n if (autoMintCheckTimer->isActive()) {\n autoMintCheckTimer->stop();\n }\n\n \/\/ stop mint\n autoMintState = AutoMintState::Disabled;\n }\n}\n\n\/\/ Handlers for core signals\nstatic void NotifyBlockTip(AutoMintModel *model, bool initialSync, const CBlockIndex *pIndex)\n{\n Q_UNUSED(pIndex);\n Q_UNUSED(initialSync);\n QMetaObject::invokeMethod(\n model,\n \"setSyncing\",\n Qt::QueuedConnection);\n}\n\nvoid AutoMintModel::subscribeToCoreSignals()\n{\n uiInterface.NotifyBlockTip.connect(\n boost::bind(NotifyBlockTip, this, _1, _2));\n}\n\nvoid AutoMintModel::unsubscribeFromCoreSignals()\n{\n uiInterface.NotifyBlockTip.disconnect(\n boost::bind(NotifyBlockTip, this, _1, _2));\n}\n\nvoid AutoMintModel::processAutoMintAck(AutoMintAck ack, CAmount minted, QString error)\n{\n QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;\n msgParams.second = CClientUIInterface::MSG_WARNING;\n\n switch (ack)\n {\n case AutoMintAck::Success:\n msgParams.first = tr(\"Success to anonymize, %1\")\n .arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), minted));\n msgParams.second = CClientUIInterface::MSG_INFORMATION;\n break;\n case AutoMintAck::WaitUserToActive:\n case AutoMintAck::NotEnoughFund:\n return;\n case AutoMintAck::FailToMint:\n msgParams.first = tr(\"Fail to mint, %1\").arg(error);\n msgParams.second = CClientUIInterface::MSG_ERROR;\n break;\n case AutoMintAck::FailToUnlock:\n msgParams.first = tr(\"Fail to unlock wallet\");\n msgParams.second = CClientUIInterface::MSG_ERROR;\n break;\n default:\n return;\n };\n\n Q_EMIT message(tr(\"Auto Anonymize\"), msgParams.first, msgParams.second);\n}<|endoftext|>"} {"text":"<commit_before>#include \"Window.h\"\n\n#include <QFileDialog>\n#include <QKeyEvent>\n#include <QKeySequence>\n#include <QMenuBar>\n\n#include \"GameController.h\"\n#include \"GDBWindow.h\"\n#include \"GDBController.h\"\n\nusing namespace QGBA;\n\nWindow::Window(QWidget* parent)\n\t: QMainWindow(parent)\n#ifdef USE_GDB_STUB\n\t, m_gdbController(nullptr)\n#endif\n{\n\tsetSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\tsetMinimumSize(240, 160);\n\n\tm_controller = new GameController(this);\n\tm_display = new Display();\n\tsetCentralWidget(m_display);\n\tconnect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));\n\tconnect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));\n\tconnect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));\n\tconnect(this, SIGNAL(startDrawing(const uint32_t*, GBAThread*)), m_display, SLOT(startDrawing(const uint32_t*, GBAThread*)), Qt::QueuedConnection);\n\tconnect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));\n\tconnect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));\n\n\tsetupMenu(menuBar());\n}\n\nGBAKey Window::mapKey(int qtKey) {\n\tswitch (qtKey) {\n\tcase Qt::Key_Z:\n\t\treturn GBA_KEY_A;\n\t\tbreak;\n\tcase Qt::Key_X:\n\t\treturn GBA_KEY_B;\n\t\tbreak;\n\tcase Qt::Key_A:\n\t\treturn GBA_KEY_L;\n\t\tbreak;\n\tcase Qt::Key_S:\n\t\treturn GBA_KEY_R;\n\t\tbreak;\n\tcase Qt::Key_Return:\n\t\treturn GBA_KEY_START;\n\t\tbreak;\n\tcase Qt::Key_Backspace:\n\t\treturn GBA_KEY_SELECT;\n\t\tbreak;\n\tcase Qt::Key_Up:\n\t\treturn GBA_KEY_UP;\n\t\tbreak;\n\tcase Qt::Key_Down:\n\t\treturn GBA_KEY_DOWN;\n\t\tbreak;\n\tcase Qt::Key_Left:\n\t\treturn GBA_KEY_LEFT;\n\t\tbreak;\n\tcase Qt::Key_Right:\n\t\treturn GBA_KEY_RIGHT;\n\t\tbreak;\n\tdefault:\n\t\treturn GBA_KEY_NONE;\n\t}\n}\n\nvoid Window::selectROM() {\n\tQString filename = QFileDialog::getOpenFileName(this, tr(\"Select ROM\"));\n\tif (!filename.isEmpty()) {\n\t\tm_controller->loadGame(filename);\n\t}\n}\n\n#ifdef USE_GDB_STUB\nvoid Window::gdbOpen() {\n\tif (!m_gdbController) {\n\t\tm_gdbController = new GDBController(m_controller, this);\n\t}\n\tGDBWindow* window = new GDBWindow(m_gdbController);\n\twindow->show();\n}\n#endif\n\nvoid Window::keyPressEvent(QKeyEvent* event) {\n\tif (event->isAutoRepeat()) {\n\t\tQWidget::keyPressEvent(event);\n\t\treturn;\n\t}\n\tGBAKey key = mapKey(event->key());\n\tif (key == GBA_KEY_NONE) {\n\t\tQWidget::keyPressEvent(event);\n\t\treturn;\n\t}\n\tm_controller->keyPressed(key);\n\tevent->accept();\n}\n\nvoid Window::keyReleaseEvent(QKeyEvent* event) {\n\tif (event->isAutoRepeat()) {\n\t\tQWidget::keyReleaseEvent(event);\n\t\treturn;\n\t}\n\tGBAKey key = mapKey(event->key());\n\tif (key == GBA_KEY_NONE) {\n\t\tQWidget::keyPressEvent(event);\n\t\treturn;\n\t}\n\tm_controller->keyReleased(key);\n\tevent->accept();\n}\n\nvoid Window::closeEvent(QCloseEvent* event) {\n\temit shutdown();\n\tQMainWindow::closeEvent(event);\n}\n\nvoid Window::gameStarted(GBAThread* context) {\n\temit startDrawing(m_controller->drawContext(), context);\n\tforeach (QAction* action, m_gameActions) {\n\t\taction->setDisabled(false);\n\t}\n}\n\nvoid Window::gameStopped() {\n\tforeach (QAction* action, m_gameActions) {\n\t\taction->setDisabled(true);\n\t}\n}\n\nvoid Window::setBuffers512() {\n\temit audioBufferSamplesChanged(512);\n}\n\nvoid Window::setBuffers1024() {\n\temit audioBufferSamplesChanged(1024);\n}\n\nvoid Window::setBuffers2048() {\n\temit audioBufferSamplesChanged(2048);\n}\n\nvoid Window::setBuffers4096() {\n\temit audioBufferSamplesChanged(4096);\n}\n\nvoid Window::setupMenu(QMenuBar* menubar) {\n\tmenubar->clear();\n\tQMenu* fileMenu = menubar->addMenu(tr(\"&File\"));\n\tfileMenu->addAction(tr(\"Load &ROM...\"), this, SLOT(selectROM()), QKeySequence::Open);\n\n\tQMenu* emulationMenu = menubar->addMenu(tr(\"&Emulation\"));\n\tQAction* reset = new QAction(tr(\"&Reset\"), nullptr);\n\treset->setShortcut(tr(\"Ctrl+R\"));\n\tconnect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));\n\tm_gameActions.append(reset);\n\temulationMenu->addAction(reset);\n\n\tQAction* shutdown = new QAction(tr(\"Sh&utdown\"), nullptr);\n\tconnect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));\n\tm_gameActions.append(shutdown);\n\temulationMenu->addAction(shutdown);\n\temulationMenu->addSeparator();\n\n\tQAction* pause = new QAction(tr(\"&Pause\"), nullptr);\n\tpause->setChecked(false);\n\tpause->setCheckable(true);\n\tpause->setShortcut(tr(\"Ctrl+P\"));\n\tconnect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));\n\tm_gameActions.append(pause);\n\temulationMenu->addAction(pause);\n\n\tQAction* frameAdvance = new QAction(tr(\"&Next frame\"), nullptr);\n\tframeAdvance->setShortcut(tr(\"Ctrl+N\"));\n\tconnect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));\n\tm_gameActions.append(frameAdvance);\n\temulationMenu->addAction(frameAdvance);\n\n\tQMenu* soundMenu = menubar->addMenu(tr(\"&Sound\"));\n\tQMenu* buffersMenu = soundMenu->addMenu(tr(\"Buffer &size\"));\n\tbuffersMenu->addAction(tr(\"512\"), this, SLOT(setBuffers512()));\n\tbuffersMenu->addAction(tr(\"1024\"), this, SLOT(setBuffers1024()));\n\tbuffersMenu->addAction(tr(\"2048\"), this, SLOT(setBuffers2048()));\n\tbuffersMenu->addAction(tr(\"4096\"), this, SLOT(setBuffers4096()));\n\n\tQMenu* debuggingMenu = menubar->addMenu(tr(\"&Debugging\"));\n#ifdef USE_GDB_STUB\n\tQAction* gdbWindow = new QAction(tr(\"Start &GDB server...\"), nullptr);\n\tconnect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));\n\tdebuggingMenu->addAction(gdbWindow);\n#endif\n\n\tforeach (QAction* action, m_gameActions) {\n\t\taction->setDisabled(true);\n\t}\n}\n<commit_msg>Sync pause setting with the menu properly<commit_after>#include \"Window.h\"\n\n#include <QFileDialog>\n#include <QKeyEvent>\n#include <QKeySequence>\n#include <QMenuBar>\n\n#include \"GameController.h\"\n#include \"GDBWindow.h\"\n#include \"GDBController.h\"\n\nusing namespace QGBA;\n\nWindow::Window(QWidget* parent)\n\t: QMainWindow(parent)\n#ifdef USE_GDB_STUB\n\t, m_gdbController(nullptr)\n#endif\n{\n\tsetSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\tsetMinimumSize(240, 160);\n\n\tm_controller = new GameController(this);\n\tm_display = new Display();\n\tsetCentralWidget(m_display);\n\tconnect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));\n\tconnect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));\n\tconnect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));\n\tconnect(this, SIGNAL(startDrawing(const uint32_t*, GBAThread*)), m_display, SLOT(startDrawing(const uint32_t*, GBAThread*)), Qt::QueuedConnection);\n\tconnect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));\n\tconnect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));\n\n\tsetupMenu(menuBar());\n}\n\nGBAKey Window::mapKey(int qtKey) {\n\tswitch (qtKey) {\n\tcase Qt::Key_Z:\n\t\treturn GBA_KEY_A;\n\t\tbreak;\n\tcase Qt::Key_X:\n\t\treturn GBA_KEY_B;\n\t\tbreak;\n\tcase Qt::Key_A:\n\t\treturn GBA_KEY_L;\n\t\tbreak;\n\tcase Qt::Key_S:\n\t\treturn GBA_KEY_R;\n\t\tbreak;\n\tcase Qt::Key_Return:\n\t\treturn GBA_KEY_START;\n\t\tbreak;\n\tcase Qt::Key_Backspace:\n\t\treturn GBA_KEY_SELECT;\n\t\tbreak;\n\tcase Qt::Key_Up:\n\t\treturn GBA_KEY_UP;\n\t\tbreak;\n\tcase Qt::Key_Down:\n\t\treturn GBA_KEY_DOWN;\n\t\tbreak;\n\tcase Qt::Key_Left:\n\t\treturn GBA_KEY_LEFT;\n\t\tbreak;\n\tcase Qt::Key_Right:\n\t\treturn GBA_KEY_RIGHT;\n\t\tbreak;\n\tdefault:\n\t\treturn GBA_KEY_NONE;\n\t}\n}\n\nvoid Window::selectROM() {\n\tQString filename = QFileDialog::getOpenFileName(this, tr(\"Select ROM\"));\n\tif (!filename.isEmpty()) {\n\t\tm_controller->loadGame(filename);\n\t}\n}\n\n#ifdef USE_GDB_STUB\nvoid Window::gdbOpen() {\n\tif (!m_gdbController) {\n\t\tm_gdbController = new GDBController(m_controller, this);\n\t}\n\tGDBWindow* window = new GDBWindow(m_gdbController);\n\twindow->show();\n}\n#endif\n\nvoid Window::keyPressEvent(QKeyEvent* event) {\n\tif (event->isAutoRepeat()) {\n\t\tQWidget::keyPressEvent(event);\n\t\treturn;\n\t}\n\tGBAKey key = mapKey(event->key());\n\tif (key == GBA_KEY_NONE) {\n\t\tQWidget::keyPressEvent(event);\n\t\treturn;\n\t}\n\tm_controller->keyPressed(key);\n\tevent->accept();\n}\n\nvoid Window::keyReleaseEvent(QKeyEvent* event) {\n\tif (event->isAutoRepeat()) {\n\t\tQWidget::keyReleaseEvent(event);\n\t\treturn;\n\t}\n\tGBAKey key = mapKey(event->key());\n\tif (key == GBA_KEY_NONE) {\n\t\tQWidget::keyPressEvent(event);\n\t\treturn;\n\t}\n\tm_controller->keyReleased(key);\n\tevent->accept();\n}\n\nvoid Window::closeEvent(QCloseEvent* event) {\n\temit shutdown();\n\tQMainWindow::closeEvent(event);\n}\n\nvoid Window::gameStarted(GBAThread* context) {\n\temit startDrawing(m_controller->drawContext(), context);\n\tforeach (QAction* action, m_gameActions) {\n\t\taction->setDisabled(false);\n\t}\n}\n\nvoid Window::gameStopped() {\n\tforeach (QAction* action, m_gameActions) {\n\t\taction->setDisabled(true);\n\t}\n}\n\nvoid Window::setBuffers512() {\n\temit audioBufferSamplesChanged(512);\n}\n\nvoid Window::setBuffers1024() {\n\temit audioBufferSamplesChanged(1024);\n}\n\nvoid Window::setBuffers2048() {\n\temit audioBufferSamplesChanged(2048);\n}\n\nvoid Window::setBuffers4096() {\n\temit audioBufferSamplesChanged(4096);\n}\n\nvoid Window::setupMenu(QMenuBar* menubar) {\n\tmenubar->clear();\n\tQMenu* fileMenu = menubar->addMenu(tr(\"&File\"));\n\tfileMenu->addAction(tr(\"Load &ROM...\"), this, SLOT(selectROM()), QKeySequence::Open);\n\n\tQMenu* emulationMenu = menubar->addMenu(tr(\"&Emulation\"));\n\tQAction* reset = new QAction(tr(\"&Reset\"), nullptr);\n\treset->setShortcut(tr(\"Ctrl+R\"));\n\tconnect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));\n\tm_gameActions.append(reset);\n\temulationMenu->addAction(reset);\n\n\tQAction* shutdown = new QAction(tr(\"Sh&utdown\"), nullptr);\n\tconnect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));\n\tm_gameActions.append(shutdown);\n\temulationMenu->addAction(shutdown);\n\temulationMenu->addSeparator();\n\n\tQAction* pause = new QAction(tr(\"&Pause\"), nullptr);\n\tpause->setChecked(false);\n\tpause->setCheckable(true);\n\tpause->setShortcut(tr(\"Ctrl+P\"));\n\tconnect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));\n\tconnect(m_controller, &GameController::gamePaused, [pause]() { pause->setChecked(true); });\n\tconnect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });\n\tm_gameActions.append(pause);\n\temulationMenu->addAction(pause);\n\n\tQAction* frameAdvance = new QAction(tr(\"&Next frame\"), nullptr);\n\tframeAdvance->setShortcut(tr(\"Ctrl+N\"));\n\tconnect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));\n\tm_gameActions.append(frameAdvance);\n\temulationMenu->addAction(frameAdvance);\n\n\tQMenu* soundMenu = menubar->addMenu(tr(\"&Sound\"));\n\tQMenu* buffersMenu = soundMenu->addMenu(tr(\"Buffer &size\"));\n\tbuffersMenu->addAction(tr(\"512\"), this, SLOT(setBuffers512()));\n\tbuffersMenu->addAction(tr(\"1024\"), this, SLOT(setBuffers1024()));\n\tbuffersMenu->addAction(tr(\"2048\"), this, SLOT(setBuffers2048()));\n\tbuffersMenu->addAction(tr(\"4096\"), this, SLOT(setBuffers4096()));\n\n\tQMenu* debuggingMenu = menubar->addMenu(tr(\"&Debugging\"));\n#ifdef USE_GDB_STUB\n\tQAction* gdbWindow = new QAction(tr(\"Start &GDB server...\"), nullptr);\n\tconnect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));\n\tdebuggingMenu->addAction(gdbWindow);\n#endif\n\n\tforeach (QAction* action, m_gameActions) {\n\t\taction->setDisabled(true);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2006 Ulrich von Zadow\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"VertexArray.h\"\n#include \"..\/base\/Exception.h\"\n\n#include <iostream>\n\nusing namespace std;\n\nnamespace avg {\n\n VertexArray::VertexArray(int NumQuads)\n : m_NumQuads(NumQuads),\n m_bDataChanged(true)\n {\n glproc::GenBuffers(1, &m_VBOArrayID);\n m_pVertexData = new T2V3Vertex[NumQuads*4];\n }\n\n VertexArray::~VertexArray()\n {\n delete[] m_pVertexData;\n glproc::DeleteBuffers(1, &m_VBOArrayID);\n }\n\n void VertexArray::setPos(int QuadIndex, int VertexIndex, const DPoint& Pos, \n const DPoint& TexPos)\n {\n assert(QuadIndex < m_NumQuads);\n T2V3Vertex* pVertex = &(m_pVertexData[QuadIndex*4+VertexIndex]);\n pVertex->m_Pos[0] = Pos.x;\n pVertex->m_Pos[1] = Pos.y;\n pVertex->m_Pos[2] = 0.0;\n pVertex->m_Tex[0] = TexPos.x;\n pVertex->m_Tex[1] = TexPos.y;\n m_bDataChanged = true;\n }\n\n void VertexArray::draw()\n {\n glproc::BindBuffer(GL_ARRAY_BUFFER, m_VBOArrayID);\n if (m_bDataChanged) {\n glproc::BufferData(GL_ARRAY_BUFFER, m_NumQuads*4*sizeof(T2V3Vertex),\n m_pVertexData, GL_STREAM_DRAW);\n }\n glVertexPointer(3, GL_FLOAT, sizeof(T2V3Vertex), (void*)8); \n\/\/ (void *)(offsetof(T2V3Vertex::m_Pos)));\n glTexCoordPointer(2, GL_FLOAT, sizeof(T2V3Vertex),\n 0);\n \n glDrawArrays(GL_QUADS, 0, 4*m_NumQuads);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"VertexArray::draw()\");\n\n m_bDataChanged = false;\n }\n\n}\n\n<commit_msg>Used offsetof instead of fixed offset for VBO data specification.<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2006 Ulrich von Zadow\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"VertexArray.h\"\n#include \"..\/base\/Exception.h\"\n\n#include <iostream>\n#include <stddef.h>\n\nusing namespace std;\n\nnamespace avg {\n\n VertexArray::VertexArray(int NumQuads)\n : m_NumQuads(NumQuads),\n m_bDataChanged(true)\n {\n glproc::GenBuffers(1, &m_VBOArrayID);\n m_pVertexData = new T2V3Vertex[NumQuads*4];\n }\n\n VertexArray::~VertexArray()\n {\n delete[] m_pVertexData;\n glproc::DeleteBuffers(1, &m_VBOArrayID);\n }\n\n void VertexArray::setPos(int QuadIndex, int VertexIndex, const DPoint& Pos, \n const DPoint& TexPos)\n {\n assert(QuadIndex < m_NumQuads);\n T2V3Vertex* pVertex = &(m_pVertexData[QuadIndex*4+VertexIndex]);\n pVertex->m_Pos[0] = Pos.x;\n pVertex->m_Pos[1] = Pos.y;\n pVertex->m_Pos[2] = 0.0;\n pVertex->m_Tex[0] = TexPos.x;\n pVertex->m_Tex[1] = TexPos.y;\n m_bDataChanged = true;\n }\n\n void VertexArray::draw()\n {\n glproc::BindBuffer(GL_ARRAY_BUFFER, m_VBOArrayID);\n if (m_bDataChanged) {\n glproc::BufferData(GL_ARRAY_BUFFER, m_NumQuads*4*sizeof(T2V3Vertex),\n m_pVertexData, GL_STREAM_DRAW);\n }\n glVertexPointer(3, GL_FLOAT, sizeof(T2V3Vertex),\n (void *)(offsetof(T2V3Vertex, m_Pos)));\n glTexCoordPointer(2, GL_FLOAT, sizeof(T2V3Vertex),\n 0);\n \n glDrawArrays(GL_QUADS, 0, 4*m_NumQuads);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"VertexArray::draw()\");\n\n m_bDataChanged = false;\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * fMBT, free Model Based Testing tool\n * Copyright (c) 2011, Intel Corporation.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope 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 License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along with\n * this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\n *\/\n\n\/* Implementations of Bounded Depth-First-Search for models and\n * coverages with push() and pop() *\/\n\n#include \"alg_bdfs.hh\"\n#include \"model.hh\"\n#include \"coverage.hh\"\n#include <algorithm>\n#include <cstdlib>\n#include \"helper.hh\"\n#include \"learn_proxy.hh\"\n\nextern int _g_simulation_depth_hint;\n\nAlgBDFS::AlgBDFS(int searchDepth, Learning* learn):\n m_search_depth(searchDepth), m_learn(learn) {\n if (learn != NULL && ((Learn_proxy*)learn)->lt) \/\/ TODO: learn knows how to learn exec times\n m_learn_exec_times = true;\n else\n m_learn_exec_times = false;\n};\n\ndouble AlgPathToBestCoverage::search(Model& model, Coverage& coverage, std::vector<int>& path)\n{\n m_coverage = &coverage;\n m_model = &model;\n return path_to_best_evaluation(model, path, m_search_depth);\n}\n\ndouble AlgPathToBestCoverage::evaluate()\n{\n return m_coverage->getCoverage();\n}\n\nvoid AlgPathToBestCoverage::doExecute(int action)\n{\n if (!status) {\n return;\n }\n\n m_model->push();\n m_coverage->push();\n\n if (!m_model->execute(action)) { errormsg=\"Model execute error\"; status=false; return;}\n m_coverage->execute(action);\n}\n\nvoid AlgPathToBestCoverage::undoExecute()\n{\n if (!status) {\n return;\n }\n\n m_model->pop();\n m_coverage->pop();\n}\n\ndouble AlgPathToAction::search(Model& model, int find_this_action, std::vector<int> &path)\n{\n m_model = &model;\n m_find_this_action = find_this_action;\n return path_to_best_evaluation(model, path, m_search_depth);\n}\n\ndouble AlgPathToAction::evaluate()\n{\n int *actions;\n int action_count;\n \/* Is action m_find_this_action available in the current state? *\/\n action_count = m_model->getActions(&actions);\n\n if (!status) {\n return 0.0;\n }\n\n for (int i = 0; i < action_count; i++)\n {\n if (actions[i] == m_find_this_action) return 1.0;\n }\n return 0.0;\n}\n\nvoid AlgPathToAction::doExecute(int action)\n{\n m_model->push();\n m_model->execute(action);\n}\n\nvoid AlgPathToAction::undoExecute()\n{\n m_model->pop();\n}\n\ndouble AlgBDFS::path_to_best_evaluation(Model& model, std::vector<int>& path, int depth)\n{\n volatile double current_score = evaluate();\n volatile double best_score = 0;\n std::vector<int> hinted_path;\n\n if (!model.status || !status) {\n if (!model.status)\n\t errormsg = \"Model error: \"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n _g_simulation_depth_hint = depth;\n model.push();\n _g_simulation_depth_hint = 0;\n\n if (path.size() > 0) {\n \/\/ Path includes a hint to look at this path at first before\n \/\/ considering others.\n \/\/\n \/\/ Evaluating the hinted options first has too effects:\n \/\/\n \/\/ - If one path has been chosen earlier, it's preferred to\n \/\/ continue execution that way instead of switching it to\n \/\/ another path that seems to be as good as the\n \/\/ original. This prevents oscillation between equally good\n \/\/ paths.\n \/\/\n \/\/ - If maximal growth rate is known, search starting with a\n \/\/ good \"so far best score\" is able to drop unnecessary\n \/\/ lookups. (Not implemented)\n\n int invalid_step = -1;\n for (unsigned int pos = 0; pos < path.size() && invalid_step == -1; pos++) {\n doExecute(path[pos]);\n if (status == false) {\n invalid_step = pos;\n status = true;\n }\n if (!model.status) {\n status = false;\n\t\terrormsg = \"Model: \" + model.errormsg;\n return 0.0;\n }\n }\n\n if (invalid_step > -1) {\n \/\/ Hinted path is no more valid, throw it away.\n path.resize(0);\n for (int current_step = invalid_step; current_step > -1; current_step--)\n undoExecute();\n } else {\n std::vector<int> additional_path;\n\n best_score = _path_to_best_evaluation(model, additional_path, depth - path.size(), current_score);\n\n if (!model.status || !status) {\n\t if (!model.status)\n\t\terrormsg = \"Model error: \"+model.errormsg;\n\t status=false;\n\t return 0.0;\n }\n\n for (unsigned int i = 0; i < path.size(); i++) undoExecute();\n\n if (!model.status || !status) {\n\t if (!model.status)\n\t\terrormsg = \"Model error: \"+model.errormsg;\n\t status=false;\n\t return 0.0;\n }\n\n if (best_score > current_score) {\n hinted_path = path;\n for (int i = additional_path.size() - 1; i >= 0; i--)\n hinted_path.push_back(additional_path[i]);\n current_score = best_score;\n }\n }\n }\n\n best_score = _path_to_best_evaluation(model, path, depth, current_score);\n model.pop();\n\n if (!model.status || !status) {\n if (!model.status)\n\terrormsg = \"Model error: \"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n if (best_score > current_score || (\n best_score == current_score &&\n path.size() < hinted_path.size())) {\n \/\/ The real algorithm constructs the best path in the opposite\n \/\/ direction to the path vector, this wrapper reverses it.\n std::reverse(path.begin(), path.end());\n } else if (hinted_path.size() > 0) {\n path = hinted_path;\n } else {\n path.resize(0);\n }\n return best_score;\n}\n\nbool AlgBDFS::grows_first(std::vector<int>& first_path, int first_path_start,\n std::vector<int>& second_path, int second_path_start)\n{\n if (first_path.size() != second_path.size()) {\n errormsg=\"first_path.size() != second_path.size()\";\n status=false;\n return false;\n }\n\n volatile double current_score = evaluate();\n\n first_path.push_back(first_path_start);\n second_path.push_back(second_path_start);\n\n int first_difference = first_path.size();\n for (int i = first_path.size() - 1; i >= 0; i--) {\n doExecute(first_path[i]);\n volatile double score = evaluate();\n\n if (!status) {\n return false;\n }\n\n if (score > current_score) {\n first_difference = i;\n break;\n }\n }\n if (first_difference == (int)first_path.size()) {\n errormsg = \"first_difference == (int)first_path.size() \"+to_string(first_difference);\n status=false; return false;\n }\n\n for (int j = first_path.size() - 1; j >= first_difference; j--) undoExecute();\n\n int second_difference = second_path.size();\n for (int i = second_path.size() - 1; i >= 0; i--) {\n doExecute(second_path[i]);\n volatile double score = evaluate();\n if (score > current_score) {\n second_difference = i;\n break;\n }\n }\n if (second_difference == (int)second_path.size()) {\n errormsg = \"second_difference == (int)second_path.size()\";\n status=false; return false;\n }\n\n for (int j = second_path.size() - 1; j >= second_difference; j--) undoExecute();\n\n first_path.pop_back();\n second_path.pop_back();\n\n if (first_difference > second_difference) return true;\n else return false;\n}\n\nbool AlgBDFS::grows_faster(std::vector<int>& first_path, int first_path_start,\n std::vector<int>& second_path, int second_path_start)\n{\n float first_path_time = m_learn->getE(first_path_start);\n float second_path_time = m_learn->getE(second_path_start);\n\n for (int i = first_path.size() - 1; i >= 0; i--) {\n first_path_time += m_learn->getE(first_path[i]);\n }\n for (int i = second_path.size() - 1; i >= 0; i--) {\n second_path_time += m_learn->getE(second_path[i]);\n }\n\n return first_path_time < second_path_time;\n}\n\ndouble AlgPathToAdaptiveCoverage::_path_to_best_evaluation\n (Model& model, std::vector<int>& path, int depth,double best_evaluation)\n{\n int *input_actions = NULL;\n int input_action_count = 0;\n\n if (!status) {\n return 0.0;\n }\n\n volatile double current_state_evaluation = evaluate();\n\n if (current_state_evaluation > best_evaluation)\n best_evaluation = current_state_evaluation;\n\n \/* Can we still continue the search? *\/\n if (depth <= 0)\n return current_state_evaluation;\n\n \/* Recursive search for the best path *\/\n input_action_count = model.getIActions(&input_actions);\n\n if (!model.status) {\n errormsg = \"Model error: \"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n std::vector<int> action_candidates;\n for (int i = 0; i < input_action_count; i++)\n action_candidates.push_back(input_actions[i]);\n\n std::vector<int> best_path;\n unsigned int best_path_length = 0;\n int best_action = -1;\n std::vector<double> pre_evaluation;\n std::vector<double> an_evaluation;\n std::vector<std::vector<int> > a_path;\n\n an_evaluation.resize(input_action_count+1);\n a_path.resize(input_action_count+1);\n pre_evaluation.reserve(input_action_count+1);\n\n for (int i = 0; i < input_action_count; i++)\n {\n doExecute(action_candidates[i]);\n \n a_path[i].resize(0);\n pre_evaluation.push_back(_path_to_best_evaluation(model, a_path[i], depth - 1, best_evaluation));\n undoExecute();\n \n if (!model.status || !status) {\n\tif (!model.status)\n\t errormsg = \"Model error: \"+model.errormsg;\n\tstatus=false;\n\treturn 0.0;\n }\n }\n\n if (m_learn) {\n for (int i = 0; i < input_action_count; i++)\n { \n\tfloat weight_total=0.0;\n\t\n\tfor (int j = 0; j < input_action_count; j++)\n\t {\n\t float weight=m_learn?m_learn->getC(action_candidates[i],action_candidates[j]):0.0;\n\n\t if (i==j) {\n\t weight+=1.0;\n\t }\n\t weight_total+=weight;\n\n\t an_evaluation[i]+=pre_evaluation[j]*weight;\n\t }\n\tif (weight_total>0.0) {\n\t an_evaluation[i]=an_evaluation[i]\/weight_total;\n\t} else {\n\t an_evaluation[i]=0.0;\n\t}\n }\n } else {\n an_evaluation.swap(pre_evaluation);\n }\n \n for (int i = 0; i < input_action_count; i++) { \n if (an_evaluation[i] > current_state_evaluation &&\n (an_evaluation[i] > best_evaluation ||\n (an_evaluation[i] == best_evaluation &&\n (best_action == -1 ||\n (best_action > -1 &&\n ((m_learn_exec_times && grows_faster(a_path[i], action_candidates[i], best_path, best_action)) ||\n (a_path[i].size() < best_path_length ||\n (a_path[i].size() == best_path_length &&\n grows_first(a_path[i], action_candidates[i], best_path, best_action)))))))))\n {\n best_path_length = a_path[i].size();\n best_path = a_path[i];\n best_action = action_candidates[i];\n best_evaluation = an_evaluation[i];\n }\n }\n\n if ((int)best_action > -1) {\n path = best_path;\n path.push_back(best_action);\n return best_evaluation;\n }\n return current_state_evaluation;\n}\n\ndouble AlgBDFS::_path_to_best_evaluation(Model& model, std::vector<int>& path, int depth,\n double best_evaluation)\n{\n int *input_actions = NULL;\n int input_action_count = 0;\n\n if (!status) {\n return 0.0;\n }\n\n volatile double current_state_evaluation = evaluate();\n\n if (current_state_evaluation > best_evaluation)\n best_evaluation = current_state_evaluation;\n\n \/* Can we still continue the search? *\/\n if (depth <= 0)\n return current_state_evaluation;\n\n \/* Recursive search for the best path *\/\n input_action_count = model.getIActions(&input_actions);\n\n if (!model.status) {\n errormsg = \"Model error:\"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n std::vector<int> action_candidates;\n for (int i = 0; i < input_action_count; i++)\n action_candidates.push_back(input_actions[i]);\n std::vector<int> best_path;\n unsigned int best_path_length = 0;\n int best_action = -1;\n for (int i = 0; i < input_action_count; i++)\n {\n std::vector<int> a_path;\n volatile double an_evaluation;\n\n doExecute(action_candidates[i]);\n\n a_path.resize(0);\n an_evaluation = _path_to_best_evaluation(model, a_path, depth - 1, best_evaluation);\n\n undoExecute();\n\n if (!model.status || !status) {\n if (!model.status)\n errormsg = \"Model error:\"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n if (an_evaluation > current_state_evaluation &&\n (an_evaluation > best_evaluation ||\n (an_evaluation == best_evaluation &&\n (best_action == -1 ||\n (best_action > -1 &&\n (a_path.size() < best_path_length ||\n (a_path.size() == best_path_length &&\n grows_first(a_path, action_candidates[i], best_path, best_action))))))))\n {\n best_path_length = a_path.size();\n best_path = a_path;\n best_action = action_candidates[i];\n best_evaluation = an_evaluation;\n }\n }\n\n if ((int)best_action > -1) {\n path = best_path;\n path.push_back(best_action);\n return best_evaluation;\n }\n return current_state_evaluation;\n}\n<commit_msg>fix bugs...<commit_after>\/*\n * fMBT, free Model Based Testing tool\n * Copyright (c) 2011, Intel Corporation.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope 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 License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along with\n * this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\n *\/\n\n\/* Implementations of Bounded Depth-First-Search for models and\n * coverages with push() and pop() *\/\n\n#include \"alg_bdfs.hh\"\n#include \"model.hh\"\n#include \"coverage.hh\"\n#include <algorithm>\n#include <cstdlib>\n#include \"helper.hh\"\n#include \"learn_proxy.hh\"\n\nextern int _g_simulation_depth_hint;\n\nAlgBDFS::AlgBDFS(int searchDepth, Learning* learn):\n m_search_depth(searchDepth), m_learn(learn) {\n if (learn != NULL && ((Learn_proxy*)learn)->lt!=NULL) \/\/ TODO: learn knows how to learn exec times\n m_learn_exec_times = true;\n else\n m_learn_exec_times = false;\n}\n\ndouble AlgPathToBestCoverage::search(Model& model, Coverage& coverage, std::vector<int>& path)\n{\n m_coverage = &coverage;\n m_model = &model;\n return path_to_best_evaluation(model, path, m_search_depth);\n}\n\ndouble AlgPathToBestCoverage::evaluate()\n{\n return m_coverage->getCoverage();\n}\n\nvoid AlgPathToBestCoverage::doExecute(int action)\n{\n if (!status) {\n return;\n }\n\n m_model->push();\n m_coverage->push();\n\n if (!m_model->execute(action)) { errormsg=\"Model execute error\"; status=false; return;}\n m_coverage->execute(action);\n}\n\nvoid AlgPathToBestCoverage::undoExecute()\n{\n if (!status) {\n return;\n }\n\n m_model->pop();\n m_coverage->pop();\n}\n\ndouble AlgPathToAction::search(Model& model, int find_this_action, std::vector<int> &path)\n{\n m_model = &model;\n m_find_this_action = find_this_action;\n return path_to_best_evaluation(model, path, m_search_depth);\n}\n\ndouble AlgPathToAction::evaluate()\n{\n int *actions;\n int action_count;\n \/* Is action m_find_this_action available in the current state? *\/\n action_count = m_model->getActions(&actions);\n\n if (!status) {\n return 0.0;\n }\n\n for (int i = 0; i < action_count; i++)\n {\n if (actions[i] == m_find_this_action) return 1.0;\n }\n return 0.0;\n}\n\nvoid AlgPathToAction::doExecute(int action)\n{\n m_model->push();\n m_model->execute(action);\n}\n\nvoid AlgPathToAction::undoExecute()\n{\n m_model->pop();\n}\n\ndouble AlgBDFS::path_to_best_evaluation(Model& model, std::vector<int>& path, int depth)\n{\n volatile double current_score = evaluate();\n volatile double best_score = 0;\n std::vector<int> hinted_path;\n\n if (!model.status || !status) {\n if (!model.status)\n\t errormsg = \"Model error: \"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n _g_simulation_depth_hint = depth;\n model.push();\n _g_simulation_depth_hint = 0;\n\n if (path.size() > 0) {\n \/\/ Path includes a hint to look at this path at first before\n \/\/ considering others.\n \/\/\n \/\/ Evaluating the hinted options first has too effects:\n \/\/\n \/\/ - If one path has been chosen earlier, it's preferred to\n \/\/ continue execution that way instead of switching it to\n \/\/ another path that seems to be as good as the\n \/\/ original. This prevents oscillation between equally good\n \/\/ paths.\n \/\/\n \/\/ - If maximal growth rate is known, search starting with a\n \/\/ good \"so far best score\" is able to drop unnecessary\n \/\/ lookups. (Not implemented)\n\n int invalid_step = -1;\n for (unsigned int pos = 0; pos < path.size() && invalid_step == -1; pos++) {\n doExecute(path[pos]);\n if (status == false) {\n invalid_step = pos;\n status = true;\n }\n if (!model.status) {\n status = false;\n\t\terrormsg = \"Model: \" + model.errormsg;\n return 0.0;\n }\n }\n\n if (invalid_step > -1) {\n \/\/ Hinted path is no more valid, throw it away.\n path.resize(0);\n for (int current_step = invalid_step; current_step > -1; current_step--)\n undoExecute();\n } else {\n std::vector<int> additional_path;\n\n best_score = _path_to_best_evaluation(model, additional_path, depth - path.size(), current_score);\n\n if (!model.status || !status) {\n\t if (!model.status)\n\t\terrormsg = \"Model error: \"+model.errormsg;\n\t status=false;\n\t return 0.0;\n }\n\n for (unsigned int i = 0; i < path.size(); i++) undoExecute();\n\n if (!model.status || !status) {\n\t if (!model.status)\n\t\terrormsg = \"Model error: \"+model.errormsg;\n\t status=false;\n\t return 0.0;\n }\n\n if (best_score > current_score) {\n hinted_path = path;\n for (int i = additional_path.size() - 1; i >= 0; i--)\n hinted_path.push_back(additional_path[i]);\n current_score = best_score;\n }\n }\n }\n\n best_score = _path_to_best_evaluation(model, path, depth, current_score);\n model.pop();\n\n if (!model.status || !status) {\n if (!model.status)\n\terrormsg = \"Model error: \"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n if (best_score > current_score || (\n best_score == current_score &&\n path.size() < hinted_path.size())) {\n \/\/ The real algorithm constructs the best path in the opposite\n \/\/ direction to the path vector, this wrapper reverses it.\n std::reverse(path.begin(), path.end());\n } else if (hinted_path.size() > 0) {\n path = hinted_path;\n } else {\n path.resize(0);\n }\n return best_score;\n}\n\nbool AlgBDFS::grows_first(std::vector<int>& first_path, int first_path_start,\n std::vector<int>& second_path, int second_path_start)\n{\n if (first_path.size() != second_path.size()) {\n errormsg=\"first_path.size() != second_path.size()\";\n status=false;\n return false;\n }\n\n volatile double current_score = evaluate();\n\n first_path.push_back(first_path_start);\n second_path.push_back(second_path_start);\n\n int first_difference = first_path.size();\n for (int i = first_path.size() - 1; i >= 0; i--) {\n doExecute(first_path[i]);\n volatile double score = evaluate();\n\n if (!status) {\n return false;\n }\n\n if (score > current_score) {\n first_difference = i;\n break;\n }\n }\n if (first_difference == (int)first_path.size()) {\n errormsg = \"first_difference == (int)first_path.size() \"+to_string(first_difference);\n status=false; return false;\n }\n\n for (int j = first_path.size() - 1; j >= first_difference; j--) undoExecute();\n\n int second_difference = second_path.size();\n for (int i = second_path.size() - 1; i >= 0; i--) {\n doExecute(second_path[i]);\n volatile double score = evaluate();\n if (score > current_score) {\n second_difference = i;\n break;\n }\n }\n if (second_difference == (int)second_path.size()) {\n errormsg = \"second_difference == (int)second_path.size()\";\n status=false; return false;\n }\n\n for (int j = second_path.size() - 1; j >= second_difference; j--) undoExecute();\n\n first_path.pop_back();\n second_path.pop_back();\n\n if (first_difference > second_difference) return true;\n else return false;\n}\n\nbool AlgBDFS::grows_faster(std::vector<int>& first_path, int first_path_start,\n std::vector<int>& second_path, int second_path_start)\n{\n float first_path_time = m_learn->getE(first_path_start);\n float second_path_time = m_learn->getE(second_path_start);\n\n for (int i = first_path.size() - 1; i >= 0; i--) {\n first_path_time += m_learn->getE(first_path[i]);\n }\n for (int i = second_path.size() - 1; i >= 0; i--) {\n second_path_time += m_learn->getE(second_path[i]);\n }\n\n return first_path_time < second_path_time;\n}\n\ndouble AlgPathToAdaptiveCoverage::_path_to_best_evaluation\n (Model& model, std::vector<int>& path, int depth,double best_evaluation)\n{\n int *input_actions = NULL;\n int input_action_count = 0;\n\n if (!status) {\n return 0.0;\n }\n\n volatile double current_state_evaluation = evaluate();\n\n if (current_state_evaluation > best_evaluation)\n best_evaluation = current_state_evaluation;\n\n \/* Can we still continue the search? *\/\n if (depth <= 0)\n return current_state_evaluation;\n\n \/* Recursive search for the best path *\/\n input_action_count = model.getIActions(&input_actions);\n\n if (!model.status) {\n errormsg = \"Model error: \"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n std::vector<int> action_candidates;\n for (int i = 0; i < input_action_count; i++)\n action_candidates.push_back(input_actions[i]);\n\n std::vector<int> best_path;\n unsigned int best_path_length = 0;\n int best_action = -1;\n std::vector<double> pre_evaluation;\n std::vector<double> an_evaluation;\n std::vector<std::vector<int> > a_path;\n\n an_evaluation.resize(input_action_count+1);\n a_path.resize(input_action_count+1);\n pre_evaluation.reserve(input_action_count+1);\n\n for (int i = 0; i < input_action_count; i++)\n {\n doExecute(action_candidates[i]);\n \n a_path[i].resize(0);\n pre_evaluation.push_back(_path_to_best_evaluation(model, a_path[i], depth - 1, best_evaluation));\n undoExecute();\n \n if (!model.status || !status) {\n\tif (!model.status)\n\t errormsg = \"Model error: \"+model.errormsg;\n\tstatus=false;\n\treturn 0.0;\n }\n }\n\n if (m_learn) {\n for (int i = 0; i < input_action_count; i++)\n { \n\tfloat weight_total=0.0;\n\t\n\tfor (int j = 0; j < input_action_count; j++)\n\t {\n\t float weight=m_learn?m_learn->getC(action_candidates[i],action_candidates[j]):0.0;\n\n\t if (i==j) {\n\t weight+=1.0;\n\t }\n\t weight_total+=weight;\n\n\t an_evaluation[i]+=pre_evaluation[j]*weight;\n\t }\n\tif (weight_total>0.0) {\n\t an_evaluation[i]=an_evaluation[i]\/weight_total;\n\t} else {\n\t an_evaluation[i]=0.0;\n\t}\n }\n } else {\n an_evaluation.swap(pre_evaluation);\n }\n \n for (int i = 0; i < input_action_count; i++) { \n if (an_evaluation[i] > current_state_evaluation &&\n (an_evaluation[i] > best_evaluation ||\n (an_evaluation[i] == best_evaluation &&\n (best_action == -1 ||\n (best_action > -1 &&\n ((m_learn_exec_times && grows_faster(a_path[i], action_candidates[i], best_path, best_action)) ||\n (a_path[i].size() < best_path_length ||\n (a_path[i].size() == best_path_length &&\n grows_first(a_path[i], action_candidates[i], best_path, best_action)))))))))\n {\n best_path_length = a_path[i].size();\n best_path = a_path[i];\n best_action = action_candidates[i];\n best_evaluation = an_evaluation[i];\n }\n }\n\n if ((int)best_action > -1) {\n path = best_path;\n path.push_back(best_action);\n return best_evaluation;\n }\n return current_state_evaluation;\n}\n\ndouble AlgBDFS::_path_to_best_evaluation(Model& model, std::vector<int>& path, int depth,\n double best_evaluation)\n{\n int *input_actions = NULL;\n int input_action_count = 0;\n\n if (!status) {\n return 0.0;\n }\n\n volatile double current_state_evaluation = evaluate();\n\n if (current_state_evaluation > best_evaluation)\n best_evaluation = current_state_evaluation;\n\n \/* Can we still continue the search? *\/\n if (depth <= 0)\n return current_state_evaluation;\n\n \/* Recursive search for the best path *\/\n input_action_count = model.getIActions(&input_actions);\n\n if (!model.status) {\n errormsg = \"Model error:\"+model.errormsg;\n\tstatus=false;\n\treturn 0.0;\n }\n\n std::vector<int> action_candidates;\n for (int i = 0; i < input_action_count; i++)\n action_candidates.push_back(input_actions[i]);\n std::vector<int> best_path;\n unsigned int best_path_length = 0;\n int best_action = -1;\n for (int i = 0; i < input_action_count; i++)\n {\n std::vector<int> a_path;\n volatile double an_evaluation;\n\n doExecute(action_candidates[i]);\n\n a_path.resize(0);\n an_evaluation = _path_to_best_evaluation(model, a_path, depth - 1, best_evaluation);\n\n undoExecute();\n\n if (!model.status || !status) {\n if (!model.status)\n errormsg = \"Model error:\"+model.errormsg;\n status=false;\n return 0.0;\n }\n\n if (an_evaluation > current_state_evaluation &&\n (an_evaluation > best_evaluation ||\n (an_evaluation == best_evaluation &&\n (best_action == -1 ||\n (best_action > -1 &&\n ((m_learn_exec_times && grows_faster(a_path, action_candidates[i], best_path, best_action)) ||\n\t\t (a_path.size() < best_path_length ||\n\t\t (a_path.size() == best_path_length &&\n\t\t grows_first(a_path, action_candidates[i], best_path, best_action)))))))))\n {\n best_path_length = a_path.size();\n best_path = a_path;\n best_action = action_candidates[i];\n best_evaluation = an_evaluation;\n }\n }\n\n if ((int)best_action > -1) {\n path = best_path;\n path.push_back(best_action);\n return best_evaluation;\n }\n return current_state_evaluation;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <iostream>\n\n#define OPT_TRANSFORM \"-o\"\n#define OPT_PRINT \"-p\"\n#define OPT_STATIC \"-a\"\n#define OPT_EXEC \"-e\"\n\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n bool transformEnabled = false;\n bool printEnabled = false;\n bool staticEnabled = false;\n bool execEnabled = false;\n char* fileName = NULL;\n\n for(int i = 1; i < argc; i++) {\n char* arg = argv[i];\n if(strcmp(arg, OPT_TRANSFORM)) {\n transformEnabled = true;\n } else if(strcmp(arg, OPT_PRINT)) {\n printEnabled = true;\n } else if(strcmp(arg, OPT_STATIC)) {\n staticEnabled = true;\n } else if(strcmp(arg, OPT_EXEC)) {\n execEnabled = true;\n } else {\n fileName = arg;\n }\n }\n\n if(fileName == NULL) {\n cerr << \"No input file provided\";\n return 1;\n }\n\n \/\/ LEXER\n \/\/ PARSER\n if(transformEnabled) {\n \/\/ TRANSFORM\n }\n if(printEnabled) {\n \/\/ PRINT\n }\n if(staticEnabled) {\n \/\/ STATIC\n }\n if(execEnabled) {\n \/\/ EXEC\n }\n\n return 0;\n}\n<commit_msg>Use cpp string<commit_after>#include <iostream>\n#include <string>\n\n#define OPT_TRANSFORM \"-o\"\n#define OPT_PRINT \"-p\"\n#define OPT_STATIC \"-a\"\n#define OPT_EXEC \"-e\"\n\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n bool transformEnabled = false;\n bool printEnabled = false;\n bool staticEnabled = false;\n bool execEnabled = false;\n char* fileName = NULL;\n\n for(int i = 1; i < argc; i++) {\n string* arg = new string(argv[i]);\n if(arg->compare(OPT_TRANSFORM) == 0) {\n transformEnabled = true;\n } else if(arg->compare(OPT_PRINT) == 0) {\n printEnabled = true;\n } else if(arg->compare(OPT_STATIC) == 0) {\n staticEnabled = true;\n } else if(arg->compare(OPT_EXEC) == 0) {\n execEnabled = true;\n } else {\n fileName = argv[i];\n }\n }\n\n if(fileName == NULL) {\n cerr << \"No input file provided\" << endl;\n return 1;\n }\n\n \/\/ LEXER\n \/\/ PARSER\n if(transformEnabled) {\n cout << \"Transform (optimize) input\" << endl;\n \/\/ TRANSFORM\n }\n if(printEnabled) {\n cout << \"Print (transformed?) input\" << endl;\n \/\/ PRINT\n }\n if(staticEnabled) {\n cout << \"Analyze statically\" << endl;\n \/\/ STATIC\n }\n if(execEnabled) {\n cout << \"Execute\" << endl;\n \/\/ EXEC\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"nan.h\"\n#include \"spellchecker.h\"\n\nusing node::ObjectWrap;\nusing namespace spellchecker;\nusing namespace v8;\n\nnamespace {\n\nclass Spellchecker : public ObjectWrap {\n SpellcheckerImplementation* impl;\n\n static NAN_METHOD(New) {\n NanScope();\n Spellchecker* that = new Spellchecker();\n that->Wrap(args.This());\n\n NanReturnValue(args.This());\n }\n\n static NAN_METHOD(SetDictionary) {\n NanScope();\n\n if (args.Length() < 1) {\n return NanThrowError(\"Bad argument\");\n }\n\n Spellchecker* that = ObjectWrap::Unwrap<Spellchecker>(args.Holder());\n\n std::string language = *String::Utf8Value(args[0]);\n std::string directory = \".\";\n if (args.Length() > 1) {\n directory = *String::Utf8Value(args[1]);\n }\n\n bool result = that->impl->SetDictionary(language, directory);\n NanReturnValue(NanNew(result));\n }\n\n static NAN_METHOD(IsMisspelled) {\n NanScope();\n if (args.Length() < 1) {\n return NanThrowError(\"Bad argument\");\n }\n\n Spellchecker* that = ObjectWrap::Unwrap<Spellchecker>(args.Holder());\n std::string word = *String::Utf8Value(args[0]);\n\n NanReturnValue(NanNew(that->impl->IsMisspelled(word)));\n }\n\n static NAN_METHOD(Add) {\n NanScope();\n if (args.Length() < 1) {\n return NanThrowError(\"Bad argument\");\n }\n\n Spellchecker* that = ObjectWrap::Unwrap<Spellchecker>(args.Holder());\n std::string word = *String::Utf8Value(args[0]);\n\n that->impl->Add(word);\n NanReturnUndefined();\n }\n\n static NAN_METHOD(GetAvailableDictionaries) {\n NanScope();\n\n Spellchecker* that = ObjectWrap::Unwrap<Spellchecker>(args.Holder());\n\n std::string path = \".\";\n if (args.Length() > 0) {\n std::string path = *String::Utf8Value(args[0]);\n }\n\n std::vector<std::string> dictionaries =\n that->impl->GetAvailableDictionaries(path);\n\n Local<Array> result = NanNew<Array>(dictionaries.size());\n for (size_t i = 0; i < dictionaries.size(); ++i) {\n const std::string& dict = dictionaries[i];\n result->Set(i, NanNew(dict.data(), dict.size()));\n }\n\n NanReturnValue(result);\n }\n\n static NAN_METHOD(GetCorrectionsForMisspelling) {\n NanScope();\n if (args.Length() < 1) {\n return NanThrowError(\"Bad argument\");\n }\n\n Spellchecker* that = ObjectWrap::Unwrap<Spellchecker>(args.Holder());\n\n std::string word = *String::Utf8Value(args[0]);\n std::vector<std::string> corrections =\n that->impl->GetCorrectionsForMisspelling(word);\n\n Local<Array> result = NanNew<Array>(corrections.size());\n for (size_t i = 0; i < corrections.size(); ++i) {\n const std::string& word = corrections[i];\n result->Set(i, NanNew<String>(word.data(), word.size()));\n }\n\n NanReturnValue(result);\n }\n\n Spellchecker() {\n impl = SpellcheckerFactory::CreateSpellchecker();\n }\n\n \/\/ actual destructor\n virtual ~Spellchecker() {\n delete impl;\n }\n\n public:\n static void Init(Handle<Object> exports) {\n Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(Spellchecker::New);\n\n tpl->SetClassName(NanNew<String>(\"Spellchecker\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n NODE_SET_METHOD(tpl->InstanceTemplate(), \"setDictionary\", Spellchecker::SetDictionary);\n NODE_SET_METHOD(tpl->InstanceTemplate(), \"getAvailableDictionaries\", Spellchecker::GetAvailableDictionaries);\n NODE_SET_METHOD(tpl->InstanceTemplate(), \"getCorrectionsForMisspelling\", Spellchecker::GetCorrectionsForMisspelling);\n NODE_SET_METHOD(tpl->InstanceTemplate(), \"isMisspelled\", Spellchecker::IsMisspelled);\n NODE_SET_METHOD(tpl->InstanceTemplate(), \"add\", Spellchecker::Add);\n\n exports->Set(NanNew(\"Spellchecker\"), tpl->GetFunction());\n }\n};\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n Spellchecker::Init(exports);\n}\n\n} \/\/ namespace\n\nNODE_MODULE(spellchecker, Init)\n<commit_msg>Rewrite to nan 2.0 methods<commit_after>#include \"nan.h\"\n#include \"spellchecker.h\"\n\nusing Nan::ObjectWrap;\nusing namespace spellchecker;\nusing namespace v8;\n\nnamespace {\n\nclass Spellchecker : public Nan::ObjectWrap {\n SpellcheckerImplementation* impl;\n\n static NAN_METHOD(New) {\n Nan::HandleScope scope;\n Spellchecker* that = new Spellchecker();\n that->Wrap(info.This());\n\n info.GetReturnValue().Set(info.This());\n }\n\n static NAN_METHOD(SetDictionary) {\n Nan::HandleScope scope;\n\n if (info.Length() < 1) {\n return Nan::ThrowError(\"Bad argument\");\n }\n\n Spellchecker* that = Nan::ObjectWrap::Unwrap<Spellchecker>(info.Holder());\n\n std::string language = *String::Utf8Value(info[0]);\n std::string directory = \".\";\n if (info.Length() > 1) {\n directory = *String::Utf8Value(info[1]);\n }\n\n bool result = that->impl->SetDictionary(language, directory);\n info.GetReturnValue().Set(Nan::New(result));\n }\n\n static NAN_METHOD(IsMisspelled) {\n Nan::HandleScope scope;\n if (info.Length() < 1) {\n return Nan::ThrowError(\"Bad argument\");\n }\n\n Spellchecker* that = Nan::ObjectWrap::Unwrap<Spellchecker>(info.Holder());\n std::string word = *String::Utf8Value(info[0]);\n\n info.GetReturnValue().Set(Nan::New(that->impl->IsMisspelled(word)));\n }\n\n static NAN_METHOD(Add) {\n Nan::HandleScope scope;\n if (info.Length() < 1) {\n return Nan::ThrowError(\"Bad argument\");\n }\n\n Spellchecker* that = Nan::ObjectWrap::Unwrap<Spellchecker>(info.Holder());\n std::string word = *String::Utf8Value(info[0]);\n\n that->impl->Add(word);\n return;\n }\n\n static NAN_METHOD(GetAvailableDictionaries) {\n Nan::HandleScope scope;\n\n Spellchecker* that = Nan::ObjectWrap::Unwrap<Spellchecker>(info.Holder());\n\n std::string path = \".\";\n if (info.Length() > 0) {\n std::string path = *String::Utf8Value(info[0]);\n }\n\n std::vector<std::string> dictionaries =\n that->impl->GetAvailableDictionaries(path);\n\n Local<Array> result = Nan::New<Array>(dictionaries.size());\n for (size_t i = 0; i < dictionaries.size(); ++i) {\n const std::string& dict = dictionaries[i];\n result->Set(i, Nan::New(dict.data(), dict.size()));\n }\n\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(GetCorrectionsForMisspelling) {\n Nan::HandleScope scope;\n if (info.Length() < 1) {\n return Nan::ThrowError(\"Bad argument\");\n }\n\n Spellchecker* that = Nan::ObjectWrap::Unwrap<Spellchecker>(info.Holder());\n\n std::string word = *String::Utf8Value(info[0]);\n std::vector<std::string> corrections =\n that->impl->GetCorrectionsForMisspelling(word);\n\n Local<Array> result = Nan::New<Array>(corrections.size());\n for (size_t i = 0; i < corrections.size(); ++i) {\n const std::string& word = corrections[i];\n result->Set(i, Nan::New<String>(word.data(), word.size())).ToLocalChecked();\n }\n\n info.GetReturnValue().Set(result);\n }\n\n Spellchecker() {\n impl = SpellcheckerFactory::CreateSpellchecker();\n }\n\n \/\/ actual destructor\n virtual ~Spellchecker() {\n delete impl;\n }\n\n public:\n static void Init(Handle<Object> exports) {\n Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(Spellchecker::New);\n\n tpl->SetClassName(Nan::New<String>(\"Spellchecker\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetMethod(tpl->InstanceTemplate(), \"setDictionary\", Spellchecker::SetDictionary);\n Nan::SetMethod(tpl->InstanceTemplate(), \"getAvailableDictionaries\", Spellchecker::GetAvailableDictionaries);\n Nan::SetMethod(tpl->InstanceTemplate(), \"getCorrectionsForMisspelling\", Spellchecker::GetCorrectionsForMisspelling);\n Nan::SetMethod(tpl->InstanceTemplate(), \"isMisspelled\", Spellchecker::IsMisspelled);\n Nan::SetMethod(tpl->InstanceTemplate(), \"add\", Spellchecker::Add);\n\n exports->Set(Nan::New(\"Spellchecker\").ToLocalChecked(), tpl->GetFunction());\n }\n};\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n Spellchecker::Init(exports);\n}\n\n} \/\/ namespace\n\nNODE_MODULE(spellchecker, Init)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <pow\/daa.h>\n\n#include <chain.h>\n#include <chainparams.h>\n#include <config.h>\n\n#include <test\/util\/setup_common.h>\n\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(daa_tests, BasicTestingSetup)\n\nstatic CBlockIndex GetBlockIndex(CBlockIndex *pindexPrev, int64_t nTimeInterval,\n uint32_t nBits) {\n CBlockIndex block;\n block.pprev = pindexPrev;\n block.nHeight = pindexPrev->nHeight + 1;\n block.nTime = pindexPrev->nTime + nTimeInterval;\n block.nBits = nBits;\n\n block.nChainWork = pindexPrev->nChainWork + GetBlockProof(block);\n return block;\n}\n\nBOOST_AUTO_TEST_CASE(daa_test) {\n DummyConfig config(CBaseChainParams::MAIN);\n\n std::vector<CBlockIndex> blocks(3000);\n\n const Consensus::Params ¶ms = config.GetChainParams().GetConsensus();\n const arith_uint256 powLimit = UintToArith256(params.powLimit);\n uint32_t powLimitBits = powLimit.GetCompact();\n arith_uint256 currentPow = powLimit >> 4;\n uint32_t initialBits = currentPow.GetCompact();\n\n \/\/ Genesis block.\n blocks[0] = CBlockIndex();\n blocks[0].nHeight = 0;\n blocks[0].nTime = 1269211443;\n blocks[0].nBits = initialBits;\n\n blocks[0].nChainWork = GetBlockProof(blocks[0]);\n\n \/\/ Block counter.\n size_t i;\n\n \/\/ Pile up some blocks every 10 mins to establish some history.\n for (i = 1; i < 2050; i++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 600, initialBits);\n }\n\n CBlockHeader blkHeaderDummy;\n uint32_t nBits =\n GetNextDAAWorkRequired(&blocks[2049], &blkHeaderDummy, params);\n\n \/\/ Difficulty stays the same as long as we produce a block every 10 mins.\n for (size_t j = 0; j < 10; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 600, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params), nBits);\n }\n\n \/\/ Make sure we skip over blocks that are out of wack. To do so, we produce\n \/\/ a block that is far in the future, and then produce a block with the\n \/\/ expected timestamp.\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params), nBits);\n blocks[i] = GetBlockIndex(&blocks[i - 1], 2 * 600 - 6000, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params), nBits);\n\n \/\/ The system should continue unaffected by the block with a bogous\n \/\/ timestamps.\n for (size_t j = 0; j < 20; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 600, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params), nBits);\n }\n\n \/\/ We start emitting blocks slightly faster. The first block has no impact.\n blocks[i] = GetBlockIndex(&blocks[i - 1], 550, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params), nBits);\n\n \/\/ Now we should see difficulty increase slowly.\n for (size_t j = 0; j < 10; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 550, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Make sure that difficulty increases very slowly.\n BOOST_CHECK(nextTarget < currentTarget);\n BOOST_CHECK((currentTarget - nextTarget) < (currentTarget >> 10));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c0fe7b1);\n\n \/\/ If we dramatically shorten block production, difficulty increases faster.\n for (size_t j = 0; j < 20; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 10, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Make sure that difficulty increases faster.\n BOOST_CHECK(nextTarget < currentTarget);\n BOOST_CHECK((currentTarget - nextTarget) < (currentTarget >> 4));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c0db19f);\n\n \/\/ We start to emit blocks significantly slower. The first block has no\n \/\/ impact.\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n nBits = GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params);\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c0d9222);\n\n \/\/ If we dramatically slow down block production, difficulty decreases.\n for (size_t j = 0; j < 93; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Check the difficulty decreases.\n BOOST_CHECK(nextTarget <= powLimit);\n BOOST_CHECK(nextTarget > currentTarget);\n BOOST_CHECK((nextTarget - currentTarget) < (currentTarget >> 3));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c2f13b9);\n\n \/\/ Due to the window of time being bounded, next block's difficulty actually\n \/\/ gets harder.\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n nBits = GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params);\n BOOST_CHECK_EQUAL(nBits, 0x1c2ee9bf);\n\n \/\/ And goes down again. It takes a while due to the window being bounded and\n \/\/ the skewed block causes 2 blocks to get out of the window.\n for (size_t j = 0; j < 192; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Check the difficulty decreases.\n BOOST_CHECK(nextTarget <= powLimit);\n BOOST_CHECK(nextTarget > currentTarget);\n BOOST_CHECK((nextTarget - currentTarget) < (currentTarget >> 3));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1d00ffff);\n\n \/\/ Once the difficulty reached the minimum allowed level, it doesn't get any\n \/\/ easier.\n for (size_t j = 0; j < 5; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n \/\/ Check the difficulty stays constant.\n BOOST_CHECK_EQUAL(nextBits, powLimitBits);\n nBits = nextBits;\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Trigger DAA underflow in DAA unit tests<commit_after>\/\/ Copyright (c) 2015-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <pow\/daa.h>\n\n#include <chain.h>\n#include <chainparams.h>\n#include <config.h>\n\n#include <test\/util\/setup_common.h>\n\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(daa_tests, BasicTestingSetup)\n\nstatic CBlockIndex GetBlockIndex(CBlockIndex *pindexPrev, int64_t nTimeInterval,\n uint32_t nBits) {\n CBlockIndex block;\n block.pprev = pindexPrev;\n block.nHeight = pindexPrev->nHeight + 1;\n block.nTime = pindexPrev->nTime + nTimeInterval;\n block.nBits = nBits;\n\n block.nChainWork = pindexPrev->nChainWork + GetBlockProof(block);\n return block;\n}\n\nBOOST_AUTO_TEST_CASE(daa_test) {\n DummyConfig config(CBaseChainParams::MAIN);\n\n std::vector<CBlockIndex> blocks(3000);\n\n const Consensus::Params ¶ms = config.GetChainParams().GetConsensus();\n const arith_uint256 powLimit = UintToArith256(params.powLimit);\n uint32_t powLimitBits = powLimit.GetCompact();\n arith_uint256 currentPow = powLimit >> 4;\n uint32_t initialBits = currentPow.GetCompact();\n\n \/\/ Genesis block.\n blocks[0] = CBlockIndex();\n blocks[0].nHeight = 0;\n blocks[0].nTime = 1269211443;\n blocks[0].nBits = initialBits;\n\n blocks[0].nChainWork = GetBlockProof(blocks[0]);\n\n \/\/ Block counter.\n size_t i;\n\n \/\/ Pile up some blocks every 10 mins to establish some history.\n for (i = 1; i < 2050; i++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 600, initialBits);\n }\n\n CBlockHeader blkHeaderDummy;\n uint32_t nBits =\n GetNextDAAWorkRequired(&blocks[2049], &blkHeaderDummy, params);\n\n \/\/ Difficulty stays the same as long as we produce a block every 10 mins.\n for (size_t j = 0; j < 10; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 600, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params), nBits);\n }\n\n \/\/ Make sure we skip over blocks that are out of wack. To do so, we produce\n \/\/ a block that is far in the future, and then produce a block with the\n \/\/ expected timestamp.\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params), nBits);\n blocks[i] = GetBlockIndex(&blocks[i - 1], 2 * 600 - 6000, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params), nBits);\n\n \/\/ The system should continue unaffected by the block with a bogous\n \/\/ timestamps.\n for (size_t j = 0; j < 20; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 600, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params), nBits);\n }\n\n \/\/ We start emitting blocks slightly faster. The first block has no impact.\n blocks[i] = GetBlockIndex(&blocks[i - 1], 550, nBits);\n BOOST_CHECK_EQUAL(\n GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params), nBits);\n\n \/\/ Now we should see difficulty increase slowly.\n for (size_t j = 0; j < 10; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 550, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Make sure that difficulty increases very slowly.\n BOOST_CHECK(nextTarget < currentTarget);\n BOOST_CHECK((currentTarget - nextTarget) < (currentTarget >> 10));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c0fe7b1);\n\n \/\/ If we dramatically shorten block production, difficulty increases faster.\n for (size_t j = 0; j < 20; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 10, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Make sure that difficulty increases faster.\n BOOST_CHECK(nextTarget < currentTarget);\n BOOST_CHECK((currentTarget - nextTarget) < (currentTarget >> 4));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c0db19f);\n\n \/\/ We start to emit blocks significantly slower. The first block has no\n \/\/ impact.\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n nBits = GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params);\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c0d9222);\n\n \/\/ If we dramatically slow down block production, difficulty decreases.\n for (size_t j = 0; j < 93; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Check the difficulty decreases.\n BOOST_CHECK(nextTarget <= powLimit);\n BOOST_CHECK(nextTarget > currentTarget);\n BOOST_CHECK((nextTarget - currentTarget) < (currentTarget >> 3));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c2f13b9);\n\n \/\/ Due to the window of time being bounded, next block's difficulty actually\n \/\/ gets harder.\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n nBits = GetNextDAAWorkRequired(&blocks[i++], &blkHeaderDummy, params);\n BOOST_CHECK_EQUAL(nBits, 0x1c2ee9bf);\n\n \/\/ And goes down again. It takes a while due to the window being bounded and\n \/\/ the skewed block causes 2 blocks to get out of the window.\n for (size_t j = 0; j < 192; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Check the difficulty decreases.\n BOOST_CHECK(nextTarget <= powLimit);\n BOOST_CHECK(nextTarget > currentTarget);\n BOOST_CHECK((nextTarget - currentTarget) < (currentTarget >> 3));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1d00ffff);\n\n \/\/ Once the difficulty reached the minimum allowed level, it doesn't get any\n \/\/ easier.\n for (size_t j = 0; j < 5; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 6000, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n \/\/ Check the difficulty stays constant.\n BOOST_CHECK_EQUAL(nextBits, powLimitBits);\n nBits = nextBits;\n }\n\n \/\/ We will now mine blocks much faster. For a while, the difficulty will\n \/\/ continue to go down.\n for (size_t j = 0; j < 130; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 10, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Check the difficulty decreases.\n BOOST_CHECK(nextTarget <= powLimit);\n BOOST_CHECK(nextTarget >= currentTarget);\n BOOST_CHECK((nextTarget - currentTarget) < (currentTarget >> 3));\n\n nBits = nextBits;\n }\n\n \/\/ Now the difficulty will go back up, and evetually we will trigger the\n \/\/ cliff code.\n for (size_t j = 0; j < 70; i++, j++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 10, nBits);\n const uint32_t nextBits =\n GetNextDAAWorkRequired(&blocks[i], &blkHeaderDummy, params);\n\n arith_uint256 currentTarget;\n currentTarget.SetCompact(nBits);\n arith_uint256 nextTarget;\n nextTarget.SetCompact(nextBits);\n\n \/\/ Check the difficulty decreases.\n BOOST_CHECK(nextTarget < currentTarget);\n BOOST_CHECK((currentTarget - nextTarget) < (currentTarget >> 3));\n\n nBits = nextBits;\n }\n\n \/\/ Check the actual value.\n BOOST_CHECK_EQUAL(nBits, 0x1c4c068c);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/* \n * Entry point\n *\n * The kernel is \"bootloaded\" by an unconditional branch to start_kernel(). The\n * name is inconsequential, it only needs to be consistent.\n *\n * Authors:\n * Scott Linder\n *\/\n\n#include \"led.hh\"\n#include \"timer.hh\"\n\nextern \"C\"\nvoid start_kernel() {\n LED ok;\n Timer timer;\n while (1) {\n ok.on();\n timer.wait(0x3f0000);\n ok.off();\n timer.wait(0x3f0000);\n }\n}\n<commit_msg>Moved main to use new timer.<commit_after>\/* \n * Entry point\n *\n * The kernel is \"bootloaded\" by an unconditional branch to start_kernel(). The\n * name is inconsequential, it only needs to be consistent.\n *\n * Authors:\n * Scott Linder\n *\/\n\n#include \"ok.hh\"\n#include \"timer.hh\"\n\nextern \"C\"\nvoid start_kernel() {\n OK ok;\n Timer timer;\n const auto kDelay = 40000_usecs;\n while (1) {\n ok.on();\n timer.wait(kDelay);\n ok.off();\n timer.wait(kDelay);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 Steinwurf ApS\n\/\/ All Rights Reserved\n\/\/\n\/\/ Distributed under the \"BSD License\". See the accompanying LICENSE.rst file.\n\n#pragma once\n\n#include <cstdint>\n#include <functional>\n\nnamespace sak\n{\n \/\/\/ Input stream abstraction\n class input_stream\n {\n public:\n\n \/\/\/ Destructor\n virtual ~input_stream()\n {}\n\n \/\/\/ Request a read from the io device\n \/\/\/ @param buffer from where to read\n \/\/\/ @param bytes to read\n virtual void read(uint8_t* buffer, uint32_t bytes) = 0;\n\n \/\/\/ Returns the number of bytes available for reading\n \/\/\/ @return number of bytes available\n virtual uint32_t bytes_available() = 0;\n\n \/\/\/ Indicates if more data will be produced. For a live stream,\n \/\/\/ the function will return true after the stream finishes.\n \/\/\/ For a finite stream (e.g. a file) the function will always\n \/\/\/ return true.\n virtual bool stopped() = 0;\n\n public:\n\n \/\/\/ Signal emitted when data can be read\n typedef std::function<void ()> ready_read_callback;\n\n \/\/\/ Specify callbacks to allow the caller to determine if\n \/\/\/ new data has arrived which is ready to be read.\n \/\/\/ @param slot the slot to connect\n void on_ready_read(const ready_read_callback& callback)\n {\n m_ready_read_callback = callback;\n }\n\n \/\/\/ Signal emitted on error\n typedef std::function<void (const std::string&)> error_callback;\n\n \/\/\/ Connect to the error signal\n \/\/\/ @param slot the function to call\n void on_error(const error_callback& callback)\n {\n m_error_callback = callback;\n }\n\n \/\/\/ Signal emitted when the stream is stopped\n typedef std::function<void ()> stopped_callback;\n\n \/\/\/ Connect to the stopped signal\n \/\/\/ @param slot the function to call\n void on_stopped(const stopped_callback& callback)\n {\n m_stopped_callback = callback;\n }\n\n protected:\n\n \/\/\/ The ready read signal\n ready_read_callback m_ready_read_callback;\n\n \/\/\/ The error signal\n error_callback m_error_callback;\n\n \/\/\/ The stopped signals\n stopped_callback m_stopped_callback;\n };\n}\n<commit_msg>Fix doxygen warnings<commit_after>\/\/ Copyright (c) 2012 Steinwurf ApS\n\/\/ All Rights Reserved\n\/\/\n\/\/ Distributed under the \"BSD License\". See the accompanying LICENSE.rst file.\n\n#pragma once\n\n#include <cstdint>\n#include <functional>\n\nnamespace sak\n{\n \/\/\/ Input stream abstraction\n class input_stream\n {\n public:\n\n \/\/\/ Destructor\n virtual ~input_stream()\n {}\n\n \/\/\/ Request a read from the io device\n \/\/\/ @param buffer from where to read\n \/\/\/ @param bytes to read\n virtual void read(uint8_t* buffer, uint32_t bytes) = 0;\n\n \/\/\/ Returns the number of bytes available for reading\n \/\/\/ @return number of bytes available\n virtual uint32_t bytes_available() = 0;\n\n \/\/\/ Indicates if more data will be produced. For a live stream,\n \/\/\/ the function will return true after the stream finishes.\n \/\/\/ For a finite stream (e.g. a file) the function will always\n \/\/\/ return true.\n virtual bool stopped() = 0;\n\n public:\n\n \/\/\/ Signal emitted when data can be read\n typedef std::function<void ()> ready_read_callback;\n\n \/\/\/ Specify callbacks to allow the caller to determine if\n \/\/\/ new data has arrived which is ready to be read.\n \/\/\/ @param callback the callback function\n void on_ready_read(const ready_read_callback& callback)\n {\n m_ready_read_callback = callback;\n }\n\n \/\/\/ Signal emitted on error\n typedef std::function<void (const std::string&)> error_callback;\n\n \/\/\/ Specify the callback function that is invoked when an error occurs.\n \/\/\/ @param callback the callback function\n void on_error(const error_callback& callback)\n {\n m_error_callback = callback;\n }\n\n \/\/\/ Signal emitted when the stream is stopped\n typedef std::function<void ()> stopped_callback;\n\n \/\/\/ Specify the callback function that is invoked when the stream\n \/\/\/ is stopped.\n \/\/\/ @param callback the callback function\n void on_stopped(const stopped_callback& callback)\n {\n m_stopped_callback = callback;\n }\n\n protected:\n\n \/\/\/ The ready read signal\n ready_read_callback m_ready_read_callback;\n\n \/\/\/ The error signal\n error_callback m_error_callback;\n\n \/\/\/ The stopped signals\n stopped_callback m_stopped_callback;\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file CpuInfo.cpp\n\/\/\/ @brief Get the CPUs cache sizes in bytes.\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/CpuInfo.hpp>\n\n#include <cstddef>\n#include <string>\n#include <vector>\n\n#if defined(_WIN32)\n#include <windows.h>\n#endif\n\n#if !defined(_WIN32)\n\n#include <array>\n#include <cstdio>\n#include <memory>\n\nusing namespace std;\n\nnamespace {\n\n\/\/\/ Execute command and return its stdout.\n\/\/\/ @see https:\/\/stackoverflow.com\/a\/478960\/363778\n\/\/\/\nstring exec(string cmd)\n{\n shared_ptr<FILE> file(popen(cmd.c_str(), \"r\"), pclose);\n string stdout;\n\n if (file)\n {\n array<char, 128> buffer;\n\n while (!feof(file.get()))\n {\n if (fgets(buffer.data(), buffer.size(), file.get()))\n stdout += buffer.data();\n }\n }\n\n return stdout;\n}\n\n\/\/\/ Find cacheId in string and return its size.\n\/\/\/ Example: \"L1_CACHE_SIZE=32768;\"\n\/\/\/\nsize_t getCacheSize(string stdout, string cacheId)\n{\n size_t pos = stdout.find(cacheId);\n size_t cacheSize = 0;\n string cacheStr;\n\n if (pos != string::npos)\n {\n size_t n1 = stdout.find_first_of('=', pos) + 1;\n size_t n2 = stdout.find_first_not_of(\"0123456789\", n1);\n\n if (n1 != string::npos &&\n n2 != string::npos)\n {\n size_t length = n2 - n1;\n cacheStr = stdout.substr(n1, length);\n\n if (!cacheStr.empty())\n cacheSize = stol(cacheStr);\n\n if (cacheStr[n2] == 'K')\n cacheSize *= 1024;\n if (cacheStr[n2] == 'M')\n cacheSize *= 1024 * 1024;\n if (cacheStr[n2] == 'G')\n cacheSize *= 1024 * 1024 * 1024;\n }\n }\n\n return cacheSize;\n}\n\n} \/\/ namespace\n\n#endif\n\nusing namespace std;\n\nnamespace primesieve {\n\nCpuInfo::CpuInfo()\n : l1CacheSize_(0),\n l2CacheSize_(0),\n l3CacheSize_(0)\n{\n initCache();\n}\n\nsize_t CpuInfo::l1CacheSize() const\n{\n return l1CacheSize_;\n}\n\nsize_t CpuInfo::l2CacheSize() const\n{\n return l2CacheSize_;\n}\n\nsize_t CpuInfo::l3CacheSize() const\n{\n return l3CacheSize_;\n}\n\n#if defined(_WIN32)\n\ntypedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);\n\nvoid CpuInfo::initCache()\n{\n LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT(\"kernel32\")), \"GetLogicalProcessorInformation\");\n\n if (glpi)\n {\n DWORD bytes = 0;\n glpi(0, &bytes);\n size_t size = bytes \/ sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);\n vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);\n glpi(info.data(), &bytes);\n\n for (size_t i = 0; i < size; i++)\n {\n if (info[i].Relationship == RelationCache)\n {\n if (info[i].Cache.Level == 1)\n l1CacheSize_ = info[i].Cache.Size;\n if (info[i].Cache.Level == 2)\n l2CacheSize_ = info[i].Cache.Size;\n if (info[i].Cache.Level == 3)\n l3CacheSize_ = info[i].Cache.Size;\n }\n }\n }\n}\n\n#else\n\nvoid CpuInfo::initCache()\n{\n \/\/ Posix shell script for UNIX like OSes\n \/\/ The script tries to get the cache size using 3 different approaches:\n \/\/ 1) getconf LEVEL*_CACHE_SIZE\n \/\/ 2) sysctl hw.l*cachesize\n \/\/ 3) cat \/sys\/devices\/system\/cpu\/cpu0\/cache\/index*\/size\n \/\/\n const string cacheSizeScript = R\"(\n command -v getconf >\/dev\/null 2>\/dev\/null;\n\n if [ $? -eq 0 ];\n then\n L1_CACHE_SIZE=$(getconf LEVEL1_DCACHE_SIZE 2>\/dev\/null);\n L2_CACHE_SIZE=$(getconf LEVEL2_CACHE_SIZE 2>\/dev\/null);\n L3_CACHE_SIZE=$(getconf LEVEL3_CACHE_SIZE 2>\/dev\/null);\n fi;\n\n command -v sysctl >\/dev\/null 2>\/dev\/null;\n\n if [ $? -eq 0 ];\n then\n if [ \"x$L1_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L1_CACHE_SIZE\" = \"0\" ];\n then\n L1_CACHE_SIZE=$(sysctl -n hw.l1dcachesize 2>\/dev\/null);\n fi;\n\n if [ \"x$L2_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L2_CACHE_SIZE\" = \"0\" ];\n then\n L2_CACHE_SIZE=$(sysctl -n hw.l2cachesize 2>\/dev\/null);\n fi;\n\n if [ \"x$L3_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L3_CACHE_SIZE\" = \"0\" ];\n then\n L3_CACHE_SIZE=$(sysctl -n hw.l3cachesize 2>\/dev\/null);\n fi;\n fi;\n\n if [ \"x$L1_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L1_CACHE_SIZE\" = \"0\" ];\n then\n L1_CACHE_SIZE=$(cat \/sys\/devices\/system\/cpu\/cpu0\/cache\/index0\/size 2>\/dev\/null);\n fi;\n\n if [ \"x$L2_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L2_CACHE_SIZE\" = \"0\" ];\n then\n L2_CACHE_SIZE=$(cat \/sys\/devices\/system\/cpu\/cpu0\/cache\/index2\/size 2>\/dev\/null);\n fi;\n\n if [ \"x$L3_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L3_CACHE_SIZE\" = \"0\" ];\n then\n L3_CACHE_SIZE=$(cat \/sys\/devices\/system\/cpu\/cpu0\/cache\/index3\/size 2>\/dev\/null);\n fi;\n\n echo \"L1_CACHE_SIZE=$L1_CACHE_SIZE; \\\n L2_CACHE_SIZE=$L2_CACHE_SIZE; \\\n L3_CACHE_SIZE=$L3_CACHE_SIZE;\"\n )\";\n\n string stdout = exec(cacheSizeScript);\n\n l1CacheSize_ = getCacheSize(stdout, \"L1_CACHE_SIZE\");\n l2CacheSize_ = getCacheSize(stdout, \"L2_CACHE_SIZE\");\n l3CacheSize_ = getCacheSize(stdout, \"L3_CACHE_SIZE\");\n}\n\n#endif\n\n\/\/\/ Singleton\nconst CpuInfo cpuInfo;\n\n} \/\/ namespace\n<commit_msg>Fix last character issue<commit_after>\/\/\/\n\/\/\/ @file CpuInfo.cpp\n\/\/\/ @brief Get the CPUs cache sizes in bytes.\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/CpuInfo.hpp>\n\n#include <cstddef>\n#include <string>\n#include <vector>\n\n#if defined(_WIN32)\n#include <windows.h>\n#endif\n\n#if !defined(_WIN32)\n\n#include <array>\n#include <cstdio>\n#include <memory>\n\nusing namespace std;\n\nnamespace {\n\n\/\/\/ Execute command and return its stdout.\n\/\/\/ @see https:\/\/stackoverflow.com\/a\/478960\/363778\n\/\/\/\nstring exec(string cmd)\n{\n shared_ptr<FILE> file(popen(cmd.c_str(), \"r\"), pclose);\n string stdout;\n\n if (file)\n {\n array<char, 128> buffer;\n\n while (!feof(file.get()))\n {\n if (fgets(buffer.data(), buffer.size(), file.get()))\n stdout += buffer.data();\n }\n }\n\n return stdout;\n}\n\n\/\/\/ Find cacheId in string and return its size.\n\/\/\/ Example: \"L1_CACHE_SIZE=32768;\"\n\/\/\/\nsize_t getCacheSize(string stdout, string cacheId)\n{\n size_t pos = stdout.find(cacheId);\n size_t cacheSize = 0;\n string cacheStr;\n\n if (pos != string::npos)\n {\n size_t n1 = stdout.find_first_of('=', pos) + 1;\n size_t n2 = stdout.find_first_not_of(\"0123456789\", n1);\n\n if (n1 != string::npos &&\n n2 != string::npos)\n {\n size_t length = n2 - n1;\n cacheStr = stdout.substr(n1, length);\n\n if (!cacheStr.empty())\n cacheSize = stol(cacheStr);\n\n if (stdout[n2] == 'K')\n cacheSize *= 1024;\n if (stdout[n2] == 'M')\n cacheSize *= 1024 * 1024;\n if (stdout[n2] == 'G')\n cacheSize *= 1024 * 1024 * 1024;\n }\n }\n\n return cacheSize;\n}\n\n} \/\/ namespace\n\n#endif\n\nusing namespace std;\n\nnamespace primesieve {\n\nCpuInfo::CpuInfo()\n : l1CacheSize_(0),\n l2CacheSize_(0),\n l3CacheSize_(0)\n{\n initCache();\n}\n\nsize_t CpuInfo::l1CacheSize() const\n{\n return l1CacheSize_;\n}\n\nsize_t CpuInfo::l2CacheSize() const\n{\n return l2CacheSize_;\n}\n\nsize_t CpuInfo::l3CacheSize() const\n{\n return l3CacheSize_;\n}\n\n#if defined(_WIN32)\n\ntypedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);\n\nvoid CpuInfo::initCache()\n{\n LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT(\"kernel32\")), \"GetLogicalProcessorInformation\");\n\n if (glpi)\n {\n DWORD bytes = 0;\n glpi(0, &bytes);\n size_t size = bytes \/ sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);\n vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);\n glpi(info.data(), &bytes);\n\n for (size_t i = 0; i < size; i++)\n {\n if (info[i].Relationship == RelationCache)\n {\n if (info[i].Cache.Level == 1)\n l1CacheSize_ = info[i].Cache.Size;\n if (info[i].Cache.Level == 2)\n l2CacheSize_ = info[i].Cache.Size;\n if (info[i].Cache.Level == 3)\n l3CacheSize_ = info[i].Cache.Size;\n }\n }\n }\n}\n\n#else\n\nvoid CpuInfo::initCache()\n{\n \/\/ Posix shell script for UNIX like OSes\n \/\/ The script tries to get the cache size using 3 different approaches:\n \/\/ 1) getconf LEVEL*_CACHE_SIZE\n \/\/ 2) sysctl hw.l*cachesize\n \/\/ 3) cat \/sys\/devices\/system\/cpu\/cpu0\/cache\/index*\/size\n \/\/\n const string cacheSizeScript = R\"(\n command -v getconf >\/dev\/null 2>\/dev\/null;\n\n if [ $? -eq 0 ];\n then\n L1_CACHE_SIZE=$(getconf LEVEL1_DCACHE_SIZE 2>\/dev\/null);\n L2_CACHE_SIZE=$(getconf LEVEL2_CACHE_SIZE 2>\/dev\/null);\n L3_CACHE_SIZE=$(getconf LEVEL3_CACHE_SIZE 2>\/dev\/null);\n fi;\n\n command -v sysctl >\/dev\/null 2>\/dev\/null;\n\n if [ $? -eq 0 ];\n then\n if [ \"x$L1_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L1_CACHE_SIZE\" = \"0\" ];\n then\n L1_CACHE_SIZE=$(sysctl -n hw.l1dcachesize 2>\/dev\/null);\n fi;\n\n if [ \"x$L2_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L2_CACHE_SIZE\" = \"0\" ];\n then\n L2_CACHE_SIZE=$(sysctl -n hw.l2cachesize 2>\/dev\/null);\n fi;\n\n if [ \"x$L3_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L3_CACHE_SIZE\" = \"0\" ];\n then\n L3_CACHE_SIZE=$(sysctl -n hw.l3cachesize 2>\/dev\/null);\n fi;\n fi;\n\n if [ \"x$L1_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L1_CACHE_SIZE\" = \"0\" ];\n then\n L1_CACHE_SIZE=$(cat \/sys\/devices\/system\/cpu\/cpu0\/cache\/index0\/size 2>\/dev\/null);\n fi;\n\n if [ \"x$L2_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L2_CACHE_SIZE\" = \"0\" ];\n then\n L2_CACHE_SIZE=$(cat \/sys\/devices\/system\/cpu\/cpu0\/cache\/index2\/size 2>\/dev\/null);\n fi;\n\n if [ \"x$L3_CACHE_SIZE\" = \"x\" ] || \\\n [ \"$L3_CACHE_SIZE\" = \"0\" ];\n then\n L3_CACHE_SIZE=$(cat \/sys\/devices\/system\/cpu\/cpu0\/cache\/index3\/size 2>\/dev\/null);\n fi;\n\n echo \"L1_CACHE_SIZE=$L1_CACHE_SIZE; \\\n L2_CACHE_SIZE=$L2_CACHE_SIZE; \\\n L3_CACHE_SIZE=$L3_CACHE_SIZE;\"\n )\";\n\n string stdout = exec(cacheSizeScript);\n\n l1CacheSize_ = getCacheSize(stdout, \"L1_CACHE_SIZE\");\n l2CacheSize_ = getCacheSize(stdout, \"L2_CACHE_SIZE\");\n l3CacheSize_ = getCacheSize(stdout, \"L3_CACHE_SIZE\");\n}\n\n#endif\n\n\/\/\/ Singleton\nconst CpuInfo cpuInfo;\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#include \"api\/plugin_instance.h\"\n#include \"core\/core.h\"\n#include \"core\/log.h\"\n#include \"core\/math.h\"\n#include \"core\/plugin_handler.h\"\n#include \"session\/session.h\"\n#include \"settings.h\"\n\/\/#include <imgui.h>\n#include \"ui\/imgui_setup.h\"\n#include \"ui\/menu.h\"\n#include \"ui\/dialogs.h\"\n#include \"ui\/cursor.h\"\n#include \"ui\/ui_render.h\"\n#include \"ui\/ui_statusbar.h\"\n#include \"input\/input_state.h\"\n\n#include <bgfx.h>\n#include <bgfxplatform.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <bx\/timer.h>\n\n#include <remotery.h>\n#include <assert.h>\n\n#include <foundation\/environment.h>\n#include <foundation\/fs.h>\n#include <foundation\/string.h>\n#include <foundation\/path.h>\n\n\/\/ TODO: Fix me\n\nint Window_buildPluginMenu(PluginData** plugins, int count);\nvoid Window_addMenu(const char* name, PDMenuItem* items, uint32_t idOffset);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct Context\n{\n InputState inputState;\n int width;\n int height;\n uint64_t time;\n Session* session; \/\/ one session right now\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic Context s_context;\n\/\/Remotery* s_remotery;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic const char* s_plugins[] =\n{\n \"sourcecode_plugin\",\n \"disassembly_plugin\",\n \"locals_plugin\",\n \"callstack_plugin\",\n \"registers_plugin\",\n \"breakpoints_plugin\",\n \"hex_memory_plugin\",\n \"console_plugin\",\n \"c64_vice_plugin\",\n#ifdef PRODBG_MAC\n \"lldb_plugin\",\n#endif\n#ifdef PRODBG_WIN\n \"dbgeng_plugin\",\n#endif\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid loadLayout(Session* session, float width, float height)\n{\n \/\/ TODO: Fix convesion\n\n if (Session_loadLayout(session, \"data\/current_layout.json\", (int)width, (int)height))\n return;\n\n if (Session_loadLayout(session, \"data\/default_layout.json\", (int)width, (int)height))\n return;\n\n Session_createDockingGrid(session, (int)width, (int)height);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint32_t findMenuIdRange(PDMenu* menu)\n{\n uint32_t idStart = uint32_t(~0);\n uint32_t idEnd = 0;\n\n while (menu->name)\n {\n PDMenuItem* menuItems = menu->items;\n\n while (menuItems->name)\n {\n const uint16_t id = menuItems->id;\n\n if (id > idEnd)\n idEnd = id;\n\n if (id < idStart)\n idStart = id;\n\n menuItems++;\n }\n\n menu++;\n }\n\n return (idEnd << 16) | idStart;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid createMenusForPlugins()\n{\n int count = 0;\n\n PluginData** plugins = PluginHandler_getBackendPlugins(&count);\n\n uint32_t menuIdStart = PRODBG_MENU_PLUGINS_START;\n\n for (int i = 0; i < count; ++i)\n {\n PluginData* pluginData = plugins[i];\n\n PDBackendPlugin* plugin = (PDBackendPlugin*)pluginData->plugin;\n\n if (!plugin)\n continue;\n\n if (!plugin->registerMenu)\n continue;\n\n PDMenu* menus = plugin->registerMenu();\n uint32_t menuRange = findMenuIdRange(menus);\n\n while (menus->name)\n {\n Window_addMenu(menus->name, menus->items, menuIdStart);\n menus++;\n }\n\n pluginData->menuStart = menuIdStart;\n pluginData->menuEnd = menuIdStart + (menuRange >> 16);\n\n menuIdStart += (menuRange >> 16);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool findDataDirectory()\n{\n\t\/\/ check if the data dir is directly here\n\n\tif (fs_is_directory(\"data\"))\n\t\treturn true;\n\n\tconst char* exe_file_path = environment_executable_path();\n\tconst char* exe_path = path_directory_name(exe_file_path );\n\n\tchar* path = string_clone(exe_path);\n\n\t\/\/ search max 10 levels up\n\n\tfor (int i = 0; i < 10; ++i)\n\t{\n\t#if defined(PRODBG_WIN)\n\t\tpath = string_append(path, \"\\\\..\");\n\t#else\n\t\tpath = string_append(path, \"\/..\");\n\t#endif\n\n\t\tenvironment_set_current_working_directory(path);\n\n\t\tif (fs_is_directory(\"data\"))\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_create(void* window, int width, int height)\n{\n Context* context = &s_context;\n \/\/Rect settingsRect;\n \/\/\n\n\tCore_init();\n\n\tfindDataDirectory();\n\n context->session = Session_create();\n context->time = bx::getHPCounter();\n\n#if PRODBG_USING_DOCKING\n loadLayout(context->session, (float)width, (float)(height - g_statusBarSize));\n#endif\n\n \/*\n if (RMT_ERROR_NONE != rmt_CreateGlobalInstance(&s_remotery))\n {\n pd_error(\"Unable to setup Remotery\");\n return;\n }\n *\/\n\n \/\/Settings_getWindowRect(&settingsRect);\n \/\/width = settingsRect.width;\n \/\/height = settingsRect.height;\n\n (void)window;\n\n for (uint32_t i = 0; i < sizeof_array(s_plugins); ++i)\n {\n PluginHandler_addPlugin(OBJECT_DIR, s_plugins[i]);\n }\n\n#if BX_PLATFORM_OSX\n bgfx::osxSetNSWindow(window);\n#elif BX_PLATFORM_WINDOWS\n bgfx::winSetHwnd((HWND)window);\n#else\n \/\/bgfx::winSetHwnd(0);\n#endif\n\n\n bgfx::init();\n bgfx::reset(width, height);\n bgfx::setViewSeq(0, true);\n\n context->width = width;\n context->height = height;\n\n IMGUI_setup(width, height);\n\n Cursor_init();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void updateDock(Context* context)\n{\n UIDockingGrid* grid = Session_getDockingGrid(context->session);\n const InputState* inputState = &context->inputState;\n\n switch (UIDock_getSizingState(grid))\n {\n case UIDockSizerDir_None:\n {\n Cunsor_setType(CursorType_Default);\n break;\n }\n\n case UIDockSizerDir_Horz:\n {\n Cunsor_setType(CursorType_SizeHorizontal);\n break;\n }\n\n case UIDockSizerDir_Vert:\n {\n Cunsor_setType(CursorType_SizeVertical);\n break;\n }\n\n case UIDockSizerDir_Both:\n {\n Cunsor_setType(CursorType_SizeAll);\n break;\n }\n }\n\n UIDock_update(grid, inputState);\n UIDock_renderSizers(grid);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_update()\n{\n Context* context = &s_context;\n\n rmt_ScopedCPUSample(ProDBG_update);\n\n bgfx::setViewRect(0, 0, 0, (uint16_t)context->width, (uint16_t)context->height);\n bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x101010ff, 1.0f, 0);\n bgfx::submit(0);\n\n uint64_t currentTime = bx::getHPCounter();\n uint64_t deltaTick = currentTime - context->time;\n context->time = currentTime;\n\n float deltaTimeMs = (float)(((double)deltaTick) \/ (double)bx::getHPFrequency());\n\n#if PRODBG_USING_DOCKING\n updateDock(context);\n#endif\n {\n rmt_ScopedCPUSample(IMGUI_preUpdate);\n IMGUI_preUpdate(&context->inputState, deltaTimeMs);\n }\n\n \/\/ TODO: Support multiple sessions\n\n {\n rmt_ScopedCPUSample(Session_update);\n Session_update(context->session);\n }\n\n UIStatusBar_render();\n\n \/\/renderTest();\n\n \/*\n\n bool show = true;\n\n ImGui::Begin(\"ImGui Test\", &show, ImVec2(550, 480), true, ImGuiWindowFlags_ShowBorders);\n\n if (ImGui::Button(\"Test0r testing!\"))\n {\n printf(\"test\\n\");\n }\n\n ImGui::End();\n *\/\n\n {\n rmt_ScopedCPUSample(IMGUI_postUpdate);\n IMGUI_postUpdate();\n }\n\n\n {\n rmt_ScopedCPUSample(bgfx_frame);\n bgfx::frame();\n }\n}\n\n\/\/ Temprory test for monkey\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_setWindowSize(int width, int height)\n{\n Context* context = &s_context;\n\n context->width = width;\n context->height = height;\n\n bgfx::reset(width, height);\n IMGUI_updateSize(width, height);\n\n#if PRODBG_USING_DOCKING\n UIDock_updateSize(Session_getDockingGrid(context->session), width, height - (int)g_statusBarSize);\n#endif\n\n ProDBG_update();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_applicationLaunched()\n{\n int pluginCount = 0;\n Window_buildPluginMenu(PluginHandler_getViewPlugins(&pluginCount), pluginCount);\n createMenusForPlugins();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_destroy()\n{\n Context* context = &s_context;\n\n \/\/rmt_DestroyGlobalInstance(s_remotery);\n\n UIDock_saveLayout(Session_getDockingGrid(context->session),\n \"data\/current_layout.json\", (float)context->width, (float)(context->height - g_statusBarSize));\n\n\tSession_destroy(context->session);\n\n Settings_save();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_timedUpdate()\n{\n ProDBG_update();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void onLoadRunExec(Session* session, const char* filename)\n{\n PluginData* pluginData = PluginHandler_findPlugin(0, \"lldb_plugin\", \"LLDB Mac\", true);\n\n if (!pluginData)\n {\n pd_error(\"Unable to find LLDB Mac backend\\n\");\n return;\n }\n\n Session_startLocal(session, (PDBackendPlugin*)pluginData->plugin, filename);\n\n \/\/ Temp test\n \/\/ Session_startLocal(context->session, (PDBackendPlugin*)pluginData->plugin, \"t2-output\/macosx-clang-debug-default\/ProDBG.app\/Contents\/MacOS\/prodbg\");\n \/\/ Session_startLocal(context->session, (PDBackendPlugin*)pluginData->plugin, OBJECT_DIR \"\/crashing_native\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Events\n\nvoid ProDBG_event(int eventId)\n{\n Context* context = &s_context;\n\n int count;\n\n PluginData** pluginsData = PluginHandler_getViewPlugins(&count);\n\n pd_info(\"eventId 0x%x\\n\", eventId);\n\n Vec2 mousePos = context->inputState.mousePos;\n\n#if PRODBG_USING_DOCKING\n if (eventId & PRODBG_MENU_POPUP_SPLIT_HORZ_SHIFT)\n {\n UIDockingGrid* grid = Session_getDockingGrid(context->session);\n UIDock* dockAtMouse = UIDock_getDockAt(grid, (int)mousePos.x, (int)mousePos.y);\n\n eventId &= (PRODBG_MENU_POPUP_SPLIT_HORZ_SHIFT - 1);\n\n ViewPluginInstance* instance = PluginInstance_createViewPlugin(pluginsData[eventId]);\n UIDock_splitHorizontal(Session_getDockingGrid(context->session), dockAtMouse, instance);\n\n Session_addViewPlugin(context->session, instance);\n return;\n }\n\n if (eventId & PRODBG_MENU_POPUP_SPLIT_VERT_SHIFT)\n {\n\n UIDockingGrid* grid = Session_getDockingGrid(context->session);\n UIDock* dockAtMouse = UIDock_getDockAt(grid, (int)mousePos.x, (int)mousePos.y);\n\n eventId &= (PRODBG_MENU_POPUP_SPLIT_VERT_SHIFT - 1);\n\n ViewPluginInstance* instance = PluginInstance_createViewPlugin(pluginsData[eventId]);\n UIDock_splitVertical(Session_getDockingGrid(context->session), dockAtMouse, instance);\n\n Session_addViewPlugin(context->session, instance);\n return;\n }\n\n#endif\n\n \/\/ TODO: This code really needs to be made more robust.\n\n if (eventId >= PRODBG_MENU_PLUGIN_START && eventId < PRODBG_MENU_PLUGIN_START + 9)\n {\n ViewPluginInstance* instance = PluginInstance_createViewPlugin(pluginsData[eventId - PRODBG_MENU_PLUGIN_START]);\n\n UIDockingGrid* grid = Session_getDockingGrid(context->session);\n UIDock* dockAtMouse = UIDock_getDockAt(grid, 0, 0);\n UIDock_splitVertical(Session_getDockingGrid(context->session), dockAtMouse, instance);\n\n Session_addViewPlugin(context->session, instance);\n return;\n }\n\n\n switch (eventId)\n {\n case PRODBG_MENU_FILE_OPEN_AND_RUN_EXE:\n {\n char filename[4096];\n\n if (Dialog_open(filename))\n {\n onLoadRunExec(context->session, filename);\n }\n\n break;\n }\n\n case PRODBG_MENU_FILE_OPEN_SOURCE:\n {\n char filename[4096];\n\n if (Dialog_open(filename))\n {\n Session_loadSourceFile(context->session, filename);\n }\n\n break;\n }\n\n case PRODBG_MENU_DEBUG_START:\n {\n Session_action(context->session, PDAction_run);\n printf(\"run....\\n\");\n break;\n }\n\n case PRODBG_MENU_DEBUG_ATTACH_TO_REMOTE:\n {\n Session_startRemote(context->session, \"127.0.0.1\", 1340);\n break;\n }\n\n case PRODBG_MENU_DEBUG_TOGGLE_BREAKPOINT:\n {\n Session_toggleBreakpointCurrentLine(context->session);\n break;\n }\n\n case PRODBG_MENU_DEBUG_STEP_OVER:\n {\n Session_stepOver(context->session);\n break;\n }\n\n case PRODBG_MENU_DEBUG_STEP_IN:\n {\n Session_stepIn(context->session);\n break;\n }\n }\n\n if (eventId >= PRODBG_MENU_PLUGINS_START)\n {\n Session_onMenu(context->session, eventId);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_scroll(const PDMouseWheelEvent& wheelEvent)\n{\n Context* context = &s_context;\n context->inputState.scrollEvent = wheelEvent;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_setMousePos(float x, float y)\n{\n Context* context = &s_context;\n\n context->inputState.mousePos.x = x;\n context->inputState.mousePos.y = y;\n\n IMGUI_setInputState(&context->inputState);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_setMouseState(int button, int state)\n{\n Context* context = &s_context;\n (void)button;\n\n InputState* inputState = &context->inputState;\n\n \/\/ TODO: Proper mouse support\n\n inputState->mouseDown[0] = !!state;\n\n IMGUI_setInputState(inputState);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_keyDown(int key, int modifier)\n{\n IMGUI_setKeyDown(key, modifier);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_keyUp(int key, int modifier)\n{\n IMGUI_setKeyUp(key, modifier);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_addChar(unsigned short c)\n{\n IMGUI_addInputCharacter(c);\n}\n\n\n\n\n<commit_msg>Replaced bx\/timer with foundation\/time<commit_after>#include \"api\/plugin_instance.h\"\n#include \"core\/core.h\"\n#include \"core\/log.h\"\n#include \"core\/math.h\"\n#include \"core\/plugin_handler.h\"\n#include \"session\/session.h\"\n#include \"settings.h\"\n\/\/#include <imgui.h>\n#include \"ui\/imgui_setup.h\"\n#include \"ui\/menu.h\"\n#include \"ui\/dialogs.h\"\n#include \"ui\/cursor.h\"\n#include \"ui\/ui_render.h\"\n#include \"ui\/ui_statusbar.h\"\n#include \"input\/input_state.h\"\n\n#include <bgfx.h>\n#include <bgfxplatform.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <remotery.h>\n#include <assert.h>\n\n#include <foundation\/environment.h>\n#include <foundation\/fs.h>\n#include <foundation\/string.h>\n#include <foundation\/path.h>\n#include <foundation\/time.h>\n\n\/\/ TODO: Fix me\n\nint Window_buildPluginMenu(PluginData** plugins, int count);\nvoid Window_addMenu(const char* name, PDMenuItem* items, uint32_t idOffset);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct Context\n{\n InputState inputState;\n int width;\n int height;\n uint64_t time;\n Session* session; \/\/ one session right now\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic Context s_context;\n\/\/Remotery* s_remotery;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic const char* s_plugins[] =\n{\n \"sourcecode_plugin\",\n \"disassembly_plugin\",\n \"locals_plugin\",\n \"callstack_plugin\",\n \"registers_plugin\",\n \"breakpoints_plugin\",\n \"hex_memory_plugin\",\n \"console_plugin\",\n \"c64_vice_plugin\",\n#ifdef PRODBG_MAC\n \"lldb_plugin\",\n#endif\n#ifdef PRODBG_WIN\n \"dbgeng_plugin\",\n#endif\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid loadLayout(Session* session, float width, float height)\n{\n \/\/ TODO: Fix convesion\n\n if (Session_loadLayout(session, \"data\/current_layout.json\", (int)width, (int)height))\n return;\n\n if (Session_loadLayout(session, \"data\/default_layout.json\", (int)width, (int)height))\n return;\n\n Session_createDockingGrid(session, (int)width, (int)height);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint32_t findMenuIdRange(PDMenu* menu)\n{\n uint32_t idStart = uint32_t(~0);\n uint32_t idEnd = 0;\n\n while (menu->name)\n {\n PDMenuItem* menuItems = menu->items;\n\n while (menuItems->name)\n {\n const uint16_t id = menuItems->id;\n\n if (id > idEnd)\n idEnd = id;\n\n if (id < idStart)\n idStart = id;\n\n menuItems++;\n }\n\n menu++;\n }\n\n return (idEnd << 16) | idStart;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid createMenusForPlugins()\n{\n int count = 0;\n\n PluginData** plugins = PluginHandler_getBackendPlugins(&count);\n\n uint32_t menuIdStart = PRODBG_MENU_PLUGINS_START;\n\n for (int i = 0; i < count; ++i)\n {\n PluginData* pluginData = plugins[i];\n\n PDBackendPlugin* plugin = (PDBackendPlugin*)pluginData->plugin;\n\n if (!plugin)\n continue;\n\n if (!plugin->registerMenu)\n continue;\n\n PDMenu* menus = plugin->registerMenu();\n uint32_t menuRange = findMenuIdRange(menus);\n\n while (menus->name)\n {\n Window_addMenu(menus->name, menus->items, menuIdStart);\n menus++;\n }\n\n pluginData->menuStart = menuIdStart;\n pluginData->menuEnd = menuIdStart + (menuRange >> 16);\n\n menuIdStart += (menuRange >> 16);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool findDataDirectory()\n{\n\t\/\/ check if the data dir is directly here\n\n\tif (fs_is_directory(\"data\"))\n\t\treturn true;\n\n\tconst char* exe_file_path = environment_executable_path();\n\tconst char* exe_path = path_directory_name(exe_file_path );\n\n\tchar* path = string_clone(exe_path);\n\n\t\/\/ search max 10 levels up\n\n\tfor (int i = 0; i < 10; ++i)\n\t{\n\t#if defined(PRODBG_WIN)\n\t\tpath = string_append(path, \"\\\\..\");\n\t#else\n\t\tpath = string_append(path, \"\/..\");\n\t#endif\n\n\t\tenvironment_set_current_working_directory(path);\n\n\t\tif (fs_is_directory(\"data\"))\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_create(void* window, int width, int height)\n{\n Context* context = &s_context;\n \/\/Rect settingsRect;\n \/\/\n\n\tCore_init();\n\n\tfindDataDirectory();\n\n context->session = Session_create();\n context->time = time_current();\n\n#if PRODBG_USING_DOCKING\n loadLayout(context->session, (float)width, (float)(height - g_statusBarSize));\n#endif\n\n \/*\n if (RMT_ERROR_NONE != rmt_CreateGlobalInstance(&s_remotery))\n {\n pd_error(\"Unable to setup Remotery\");\n return;\n }\n *\/\n\n \/\/Settings_getWindowRect(&settingsRect);\n \/\/width = settingsRect.width;\n \/\/height = settingsRect.height;\n\n (void)window;\n\n for (uint32_t i = 0; i < sizeof_array(s_plugins); ++i)\n {\n PluginHandler_addPlugin(OBJECT_DIR, s_plugins[i]);\n }\n\n#if BX_PLATFORM_OSX\n bgfx::osxSetNSWindow(window);\n#elif BX_PLATFORM_WINDOWS\n bgfx::winSetHwnd((HWND)window);\n#else\n \/\/bgfx::winSetHwnd(0);\n#endif\n\n\n bgfx::init();\n bgfx::reset(width, height);\n bgfx::setViewSeq(0, true);\n\n context->width = width;\n context->height = height;\n\n IMGUI_setup(width, height);\n\n Cursor_init();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void updateDock(Context* context)\n{\n UIDockingGrid* grid = Session_getDockingGrid(context->session);\n const InputState* inputState = &context->inputState;\n\n switch (UIDock_getSizingState(grid))\n {\n case UIDockSizerDir_None:\n {\n Cunsor_setType(CursorType_Default);\n break;\n }\n\n case UIDockSizerDir_Horz:\n {\n Cunsor_setType(CursorType_SizeHorizontal);\n break;\n }\n\n case UIDockSizerDir_Vert:\n {\n Cunsor_setType(CursorType_SizeVertical);\n break;\n }\n\n case UIDockSizerDir_Both:\n {\n Cunsor_setType(CursorType_SizeAll);\n break;\n }\n }\n\n UIDock_update(grid, inputState);\n UIDock_renderSizers(grid);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_update()\n{\n Context* context = &s_context;\n\n rmt_ScopedCPUSample(ProDBG_update);\n\n bgfx::setViewRect(0, 0, 0, (uint16_t)context->width, (uint16_t)context->height);\n bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x101010ff, 1.0f, 0);\n bgfx::submit(0);\n\n uint64_t currentTime = time_current(); \n\n\tfloat dt = time_elapsed(context->time);\n\n context->time = currentTime;\n\n#if PRODBG_USING_DOCKING\n updateDock(context);\n#endif\n {\n rmt_ScopedCPUSample(IMGUI_preUpdate);\n IMGUI_preUpdate(&context->inputState, dt);\n }\n\n \/\/ TODO: Support multiple sessions\n\n {\n rmt_ScopedCPUSample(Session_update);\n Session_update(context->session);\n }\n\n UIStatusBar_render();\n\n \/\/renderTest();\n\n \/*\n\n bool show = true;\n\n ImGui::Begin(\"ImGui Test\", &show, ImVec2(550, 480), true, ImGuiWindowFlags_ShowBorders);\n\n if (ImGui::Button(\"Test0r testing!\"))\n {\n printf(\"test\\n\");\n }\n\n ImGui::End();\n *\/\n\n {\n rmt_ScopedCPUSample(IMGUI_postUpdate);\n IMGUI_postUpdate();\n }\n\n\n {\n rmt_ScopedCPUSample(bgfx_frame);\n bgfx::frame();\n }\n}\n\n\/\/ Temprory test for monkey\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_setWindowSize(int width, int height)\n{\n Context* context = &s_context;\n\n context->width = width;\n context->height = height;\n\n bgfx::reset(width, height);\n IMGUI_updateSize(width, height);\n\n#if PRODBG_USING_DOCKING\n UIDock_updateSize(Session_getDockingGrid(context->session), width, height - (int)g_statusBarSize);\n#endif\n\n ProDBG_update();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_applicationLaunched()\n{\n int pluginCount = 0;\n Window_buildPluginMenu(PluginHandler_getViewPlugins(&pluginCount), pluginCount);\n createMenusForPlugins();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_destroy()\n{\n Context* context = &s_context;\n\n \/\/rmt_DestroyGlobalInstance(s_remotery);\n\n UIDock_saveLayout(Session_getDockingGrid(context->session),\n \"data\/current_layout.json\", (float)context->width, (float)(context->height - g_statusBarSize));\n\n\tSession_destroy(context->session);\n\n Settings_save();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_timedUpdate()\n{\n ProDBG_update();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void onLoadRunExec(Session* session, const char* filename)\n{\n PluginData* pluginData = PluginHandler_findPlugin(0, \"lldb_plugin\", \"LLDB Mac\", true);\n\n if (!pluginData)\n {\n pd_error(\"Unable to find LLDB Mac backend\\n\");\n return;\n }\n\n Session_startLocal(session, (PDBackendPlugin*)pluginData->plugin, filename);\n\n \/\/ Temp test\n \/\/ Session_startLocal(context->session, (PDBackendPlugin*)pluginData->plugin, \"t2-output\/macosx-clang-debug-default\/ProDBG.app\/Contents\/MacOS\/prodbg\");\n \/\/ Session_startLocal(context->session, (PDBackendPlugin*)pluginData->plugin, OBJECT_DIR \"\/crashing_native\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Events\n\nvoid ProDBG_event(int eventId)\n{\n Context* context = &s_context;\n\n int count;\n\n PluginData** pluginsData = PluginHandler_getViewPlugins(&count);\n\n pd_info(\"eventId 0x%x\\n\", eventId);\n\n Vec2 mousePos = context->inputState.mousePos;\n\n#if PRODBG_USING_DOCKING\n if (eventId & PRODBG_MENU_POPUP_SPLIT_HORZ_SHIFT)\n {\n UIDockingGrid* grid = Session_getDockingGrid(context->session);\n UIDock* dockAtMouse = UIDock_getDockAt(grid, (int)mousePos.x, (int)mousePos.y);\n\n eventId &= (PRODBG_MENU_POPUP_SPLIT_HORZ_SHIFT - 1);\n\n ViewPluginInstance* instance = PluginInstance_createViewPlugin(pluginsData[eventId]);\n UIDock_splitHorizontal(Session_getDockingGrid(context->session), dockAtMouse, instance);\n\n Session_addViewPlugin(context->session, instance);\n return;\n }\n\n if (eventId & PRODBG_MENU_POPUP_SPLIT_VERT_SHIFT)\n {\n\n UIDockingGrid* grid = Session_getDockingGrid(context->session);\n UIDock* dockAtMouse = UIDock_getDockAt(grid, (int)mousePos.x, (int)mousePos.y);\n\n eventId &= (PRODBG_MENU_POPUP_SPLIT_VERT_SHIFT - 1);\n\n ViewPluginInstance* instance = PluginInstance_createViewPlugin(pluginsData[eventId]);\n UIDock_splitVertical(Session_getDockingGrid(context->session), dockAtMouse, instance);\n\n Session_addViewPlugin(context->session, instance);\n return;\n }\n\n#endif\n\n \/\/ TODO: This code really needs to be made more robust.\n\n if (eventId >= PRODBG_MENU_PLUGIN_START && eventId < PRODBG_MENU_PLUGIN_START + 9)\n {\n ViewPluginInstance* instance = PluginInstance_createViewPlugin(pluginsData[eventId - PRODBG_MENU_PLUGIN_START]);\n\n UIDockingGrid* grid = Session_getDockingGrid(context->session);\n UIDock* dockAtMouse = UIDock_getDockAt(grid, 0, 0);\n UIDock_splitVertical(Session_getDockingGrid(context->session), dockAtMouse, instance);\n\n Session_addViewPlugin(context->session, instance);\n return;\n }\n\n\n switch (eventId)\n {\n case PRODBG_MENU_FILE_OPEN_AND_RUN_EXE:\n {\n char filename[4096];\n\n if (Dialog_open(filename))\n {\n onLoadRunExec(context->session, filename);\n }\n\n break;\n }\n\n case PRODBG_MENU_FILE_OPEN_SOURCE:\n {\n char filename[4096];\n\n if (Dialog_open(filename))\n {\n Session_loadSourceFile(context->session, filename);\n }\n\n break;\n }\n\n case PRODBG_MENU_DEBUG_START:\n {\n Session_action(context->session, PDAction_run);\n printf(\"run....\\n\");\n break;\n }\n\n case PRODBG_MENU_DEBUG_ATTACH_TO_REMOTE:\n {\n Session_startRemote(context->session, \"127.0.0.1\", 1340);\n break;\n }\n\n case PRODBG_MENU_DEBUG_TOGGLE_BREAKPOINT:\n {\n Session_toggleBreakpointCurrentLine(context->session);\n break;\n }\n\n case PRODBG_MENU_DEBUG_STEP_OVER:\n {\n Session_stepOver(context->session);\n break;\n }\n\n case PRODBG_MENU_DEBUG_STEP_IN:\n {\n Session_stepIn(context->session);\n break;\n }\n }\n\n if (eventId >= PRODBG_MENU_PLUGINS_START)\n {\n Session_onMenu(context->session, eventId);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_scroll(const PDMouseWheelEvent& wheelEvent)\n{\n Context* context = &s_context;\n context->inputState.scrollEvent = wheelEvent;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_setMousePos(float x, float y)\n{\n Context* context = &s_context;\n\n context->inputState.mousePos.x = x;\n context->inputState.mousePos.y = y;\n\n IMGUI_setInputState(&context->inputState);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_setMouseState(int button, int state)\n{\n Context* context = &s_context;\n (void)button;\n\n InputState* inputState = &context->inputState;\n\n \/\/ TODO: Proper mouse support\n\n inputState->mouseDown[0] = !!state;\n\n IMGUI_setInputState(inputState);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_keyDown(int key, int modifier)\n{\n IMGUI_setKeyDown(key, modifier);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_keyUp(int key, int modifier)\n{\n IMGUI_setKeyUp(key, modifier);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProDBG_addChar(unsigned short c)\n{\n IMGUI_addInputCharacter(c);\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"buffers.h\"\n#include \"strutil.h\"\n#include \"log.h\"\n\nvoid processQueue(ByteQueue* queue, bool (*callback)(uint8_t*)) {\n uint8_t snapshot[queue_length(queue)];\n queue_snapshot(queue, snapshot);\n if(callback == NULL) {\n debug(\"Callback is NULL (%p) -- unable to handle queue at %p\\r\\n\",\n callback, queue);\n return;\n }\n\n if(callback(snapshot)) {\n queue_init(queue);\n } else if(queue_full(queue)) {\n debug(\"Incoming write is too long\\r\\n\");\n queue_init(queue);\n } else if(strnchr((char*)snapshot, queue_length(queue) - 1, '\\0') != NULL) {\n debug(\"Incoming buffered write corrupted (%s) -- clearing buffer\\r\\n\",\n snapshot);\n queue_init(queue);\n }\n}\n<commit_msg>Don't walk off the end of a snapshot if interrupt is still adding to queue.<commit_after>#include \"buffers.h\"\n#include \"strutil.h\"\n#include \"log.h\"\n\nvoid processQueue(ByteQueue* queue, bool (*callback)(uint8_t*)) {\n uint8_t snapshot[queue_length(queue)];\n queue_snapshot(queue, snapshot);\n if(callback == NULL) {\n debug(\"Callback is NULL (%p) -- unable to handle queue at %p\\r\\n\",\n callback, queue);\n return;\n }\n\n if(callback(snapshot)) {\n queue_init(queue);\n } else if(queue_full(queue)) {\n debug(\"Incoming write is too long\\r\\n\");\n queue_init(queue);\n } else if(strnchr((char*)snapshot, sizeof(snapshot) - 1, '\\0') != NULL) {\n debug(\"Incoming buffered write corrupted (%s) -- clearing buffer\\r\\n\",\n snapshot);\n queue_init(queue);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"canread.h\"\n#include <stdlib.h>\n#include \"log.h\"\n\n\/* Private: Serialize the root JSON object to a string (ending with a newline)\n * and send it to the listener.\n *\n * root - The JSON object to send.\n * listener - The listener device to send on.\n *\/\nvoid sendJSON(cJSON* root, Listener* listener) {\n char* message = cJSON_PrintUnformatted(root);\n sendMessage(listener, (uint8_t*) message, strlen(message));\n cJSON_Delete(root);\n free(message);\n}\n\n\/* Private: Combine the given name and value into a JSON object (conforming to\n * the OpenXC standard) and send it out to the listener.\n *\n * name - The value for the name field of the OpenXC message.\n * value - The numerical, string or booelan for the value field of the OpenXC\n * message.\n * event - (Optional) The event for the event field of the OpenXC message.\n * listener - The listener device to send on.\n *\/\nvoid sendJSONMessage(const char* name, cJSON* value, cJSON* event,\n Listener* listener) {\n cJSON *root = cJSON_CreateObject();\n cJSON_AddStringToObject(root, NAME_FIELD_NAME, name);\n cJSON_AddItemToObject(root, VALUE_FIELD_NAME, value);\n if(event != NULL) {\n cJSON_AddItemToObject(root, EVENT_FIELD_NAME, event);\n }\n sendJSON(root, listener);\n}\n\n\/* Private: Determine if the received signal should be sent out and update\n * signal metadata.\n *\n * signal - The signal to look for in the CAN message data.\n * data - The data of the CAN message.\n * send - Will be flipped to false if the signal should not be sent (e.g. the\n * signal is on a limited send frequency and the timer is not up yet).\n *\n * Returns the float value of the signal decoded from the data.\n *\/\nfloat preTranslate(CanSignal* signal, uint64_t data, bool* send) {\n float value = decodeCanSignal(signal, data);\n\n if(!signal->received || signal->sendClock == signal->sendFrequency - 1) {\n if(send && (!signal->received || signal->sendSame ||\n value != signal->lastValue)) {\n signal->received = true;\n } else {\n *send = false;\n }\n signal->sendClock = 0;\n } else {\n *send = false;\n ++signal->sendClock;\n }\n return value;\n}\n\n\/* Private: Update signal metadata after translating and sending.\n *\n * We keep track of the last value of each CAN signal (in its raw float form),\n * but we can't update the value until after all translation has happened,\n * in case a custom handler needs to use the value.\n *\/\nvoid postTranslate(CanSignal* signal, float value) {\n signal->lastValue = value;\n}\n\nfloat decodeCanSignal(CanSignal* signal, uint64_t data) {\n uint64_t rawValue = getBitField(data, signal->bitPosition,\n signal->bitSize);\n return rawValue * signal->factor + signal->offset;\n}\n\nfloat passthroughHandler(CanSignal* signal, CanSignal* signals, int signalCount,\n float value, bool* send) {\n return value;\n}\n\nbool booleanHandler(CanSignal* signal, CanSignal* signals, int signalCount,\n float value, bool* send) {\n return value == 0.0 ? false : true;\n}\n\nfloat ignoreHandler(CanSignal* signal, CanSignal* signals, int signalCount,\n float value, bool* send) {\n *send = false;\n return value;\n}\n\nconst char* stateHandler(CanSignal* signal, CanSignal* signals,\n int signalCount, float value, bool* send) {\n CanSignalState* signalState = lookupSignalState(value, signal, signals,\n signalCount);\n if(signalState != NULL) {\n return signalState->name;\n }\n debug(\"No signal state found for value %d\", value);\n *send = false;\n return NULL;\n}\n\nvoid sendNumericalMessage(const char* name, float value, Listener* listener) {\n sendJSONMessage(name, cJSON_CreateNumber(value), NULL, listener);\n}\n\nvoid sendBooleanMessage(const char* name, bool value, Listener* listener) {\n sendJSONMessage(name, cJSON_CreateBool(value), NULL, listener);\n}\n\nvoid sendStringMessage(const char* name, const char* value,\n Listener* listener) {\n sendJSONMessage(name, cJSON_CreateString(value), NULL, listener);\n}\n\nvoid sendEventedBooleanMessage(const char* name, const char* value, bool event,\n Listener* listener) {\n sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateBool(event),\n listener);\n}\n\nvoid sendEventedStringMessage(const char* name, const char* value,\n const char* event, Listener* listener) {\n sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateString(event),\n listener);\n}\n\nvoid passthroughCanMessage(Listener* listener, int id, uint64_t data) {\n cJSON *root = cJSON_CreateObject();\n cJSON_AddNumberToObject(root, ID_FIELD_NAME, id);\n\n char encodedData[67];\n union {\n uint64_t whole;\n uint8_t bytes[8];\n } combined;\n combined.whole = data;\n\n sprintf(encodedData, \"0x%02x%02x%02x%02x%02x%02x%02x%02x\",\n combined.bytes[0],\n combined.bytes[1],\n combined.bytes[2],\n combined.bytes[3],\n combined.bytes[4],\n combined.bytes[5],\n combined.bytes[6],\n combined.bytes[7]);\n cJSON_AddStringToObject(root, DATA_FIELD_NAME, encodedData);\n\n sendJSON(root, listener);\n}\n\nvoid translateCanSignal(Listener* listener, CanSignal* signal,\n uint64_t data,\n float (*handler)(CanSignal*, CanSignal*, int, float, bool*),\n CanSignal* signals, int signalCount) {\n bool send = true;\n float value = preTranslate(signal, data, &send);\n if(send) {\n float processedValue = handler(signal, signals, signalCount, value,\n &send);\n if(send) {\n sendNumericalMessage(signal->genericName, processedValue, listener);\n }\n }\n postTranslate(signal, value);\n}\n\nvoid translateCanSignal(Listener* listener, CanSignal* signal,\n uint64_t data,\n const char* (*handler)(CanSignal*, CanSignal*, int, float, bool*),\n CanSignal* signals, int signalCount) {\n bool send = true;\n float value = preTranslate(signal, data, &send);\n if(send) {\n const char* stringValue = handler(signal, signals, signalCount, value,\n &send);\n if(stringValue == NULL) {\n debug(\"No valid string returned from handler for %s\",\n signal->genericName);\n } else if(send) {\n sendStringMessage(signal->genericName, stringValue, listener);\n }\n }\n postTranslate(signal, value);\n}\n\nvoid translateCanSignal(Listener* listener, CanSignal* signal,\n uint64_t data,\n bool (*handler)(CanSignal*, CanSignal*, int, float, bool*),\n CanSignal* signals, int signalCount) {\n bool send = true;\n float value = preTranslate(signal, data, &send);\n if(send) {\n bool booleanValue = handler(signal, signals, signalCount, value, &send);\n if(send) {\n sendBooleanMessage(signal->genericName, booleanValue, listener);\n }\n }\n postTranslate(signal, value);\n}\n\nvoid translateCanSignal(Listener* listener, CanSignal* signal,\n uint64_t data, CanSignal* signals, int signalCount) {\n translateCanSignal(listener, signal, data, passthroughHandler, signals,\n signalCount);\n}\n<commit_msg>In the float translateCanSignal(), I removed the if(send) check around the handler call. But I left the check around the sendNumericalMessage() call. The change means that now the handler gets called for every message, but a JSON message is only sent as allowed by the send flag.<commit_after>#include \"canread.h\"\n#include <stdlib.h>\n#include \"log.h\"\n\n\/* Private: Serialize the root JSON object to a string (ending with a newline)\n * and send it to the listener.\n *\n * root - The JSON object to send.\n * listener - The listener device to send on.\n *\/\nvoid sendJSON(cJSON* root, Listener* listener) {\n char* message = cJSON_PrintUnformatted(root);\n sendMessage(listener, (uint8_t*) message, strlen(message));\n cJSON_Delete(root);\n free(message);\n}\n\n\/* Private: Combine the given name and value into a JSON object (conforming to\n * the OpenXC standard) and send it out to the listener.\n *\n * name - The value for the name field of the OpenXC message.\n * value - The numerical, string or booelan for the value field of the OpenXC\n * message.\n * event - (Optional) The event for the event field of the OpenXC message.\n * listener - The listener device to send on.\n *\/\nvoid sendJSONMessage(const char* name, cJSON* value, cJSON* event,\n Listener* listener) {\n cJSON *root = cJSON_CreateObject();\n cJSON_AddStringToObject(root, NAME_FIELD_NAME, name);\n cJSON_AddItemToObject(root, VALUE_FIELD_NAME, value);\n if(event != NULL) {\n cJSON_AddItemToObject(root, EVENT_FIELD_NAME, event);\n }\n sendJSON(root, listener);\n}\n\n\/* Private: Determine if the received signal should be sent out and update\n * signal metadata.\n *\n * signal - The signal to look for in the CAN message data.\n * data - The data of the CAN message.\n * send - Will be flipped to false if the signal should not be sent (e.g. the\n * signal is on a limited send frequency and the timer is not up yet).\n *\n * Returns the float value of the signal decoded from the data.\n *\/\nfloat preTranslate(CanSignal* signal, uint64_t data, bool* send) {\n float value = decodeCanSignal(signal, data);\n\n if(!signal->received || signal->sendClock == signal->sendFrequency - 1) {\n if(send && (!signal->received || signal->sendSame ||\n value != signal->lastValue)) {\n signal->received = true;\n } else {\n *send = false;\n }\n signal->sendClock = 0;\n } else {\n *send = false;\n ++signal->sendClock;\n }\n return value;\n}\n\n\/* Private: Update signal metadata after translating and sending.\n *\n * We keep track of the last value of each CAN signal (in its raw float form),\n * but we can't update the value until after all translation has happened,\n * in case a custom handler needs to use the value.\n *\/\nvoid postTranslate(CanSignal* signal, float value) {\n signal->lastValue = value;\n}\n\nfloat decodeCanSignal(CanSignal* signal, uint64_t data) {\n uint64_t rawValue = getBitField(data, signal->bitPosition,\n signal->bitSize);\n return rawValue * signal->factor + signal->offset;\n}\n\nfloat passthroughHandler(CanSignal* signal, CanSignal* signals, int signalCount,\n float value, bool* send) {\n return value;\n}\n\nbool booleanHandler(CanSignal* signal, CanSignal* signals, int signalCount,\n float value, bool* send) {\n return value == 0.0 ? false : true;\n}\n\nfloat ignoreHandler(CanSignal* signal, CanSignal* signals, int signalCount,\n float value, bool* send) {\n *send = false;\n return value;\n}\n\nconst char* stateHandler(CanSignal* signal, CanSignal* signals,\n int signalCount, float value, bool* send) {\n CanSignalState* signalState = lookupSignalState(value, signal, signals,\n signalCount);\n if(signalState != NULL) {\n return signalState->name;\n }\n debug(\"No signal state found for value %d\", value);\n *send = false;\n return NULL;\n}\n\nvoid sendNumericalMessage(const char* name, float value, Listener* listener) {\n sendJSONMessage(name, cJSON_CreateNumber(value), NULL, listener);\n}\n\nvoid sendBooleanMessage(const char* name, bool value, Listener* listener) {\n sendJSONMessage(name, cJSON_CreateBool(value), NULL, listener);\n}\n\nvoid sendStringMessage(const char* name, const char* value,\n Listener* listener) {\n sendJSONMessage(name, cJSON_CreateString(value), NULL, listener);\n}\n\nvoid sendEventedBooleanMessage(const char* name, const char* value, bool event,\n Listener* listener) {\n sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateBool(event),\n listener);\n}\n\nvoid sendEventedStringMessage(const char* name, const char* value,\n const char* event, Listener* listener) {\n sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateString(event),\n listener);\n}\n\nvoid passthroughCanMessage(Listener* listener, int id, uint64_t data) {\n cJSON *root = cJSON_CreateObject();\n cJSON_AddNumberToObject(root, ID_FIELD_NAME, id);\n\n char encodedData[67];\n union {\n uint64_t whole;\n uint8_t bytes[8];\n } combined;\n combined.whole = data;\n\n sprintf(encodedData, \"0x%02x%02x%02x%02x%02x%02x%02x%02x\",\n combined.bytes[0],\n combined.bytes[1],\n combined.bytes[2],\n combined.bytes[3],\n combined.bytes[4],\n combined.bytes[5],\n combined.bytes[6],\n combined.bytes[7]);\n cJSON_AddStringToObject(root, DATA_FIELD_NAME, encodedData);\n\n sendJSON(root, listener);\n}\n\nvoid translateCanSignal(Listener* listener, CanSignal* signal,\n uint64_t data,\n float (*handler)(CanSignal*, CanSignal*, int, float, bool*),\n CanSignal* signals, int signalCount) {\n bool send = true;\n float value = preTranslate(signal, data, &send);\n float processedValue = handler(signal, signals, signalCount, value,\n &send);\n if(send) {\n sendNumericalMessage(signal->genericName, processedValue, listener);\n }\n postTranslate(signal, value);\n}\n\nvoid translateCanSignal(Listener* listener, CanSignal* signal,\n uint64_t data,\n const char* (*handler)(CanSignal*, CanSignal*, int, float, bool*),\n CanSignal* signals, int signalCount) {\n bool send = true;\n float value = preTranslate(signal, data, &send);\n if(send) {\n const char* stringValue = handler(signal, signals, signalCount, value,\n &send);\n if(stringValue == NULL) {\n debug(\"No valid string returned from handler for %s\",\n signal->genericName);\n } else if(send) {\n sendStringMessage(signal->genericName, stringValue, listener);\n }\n }\n postTranslate(signal, value);\n}\n\nvoid translateCanSignal(Listener* listener, CanSignal* signal,\n uint64_t data,\n bool (*handler)(CanSignal*, CanSignal*, int, float, bool*),\n CanSignal* signals, int signalCount) {\n bool send = true;\n float value = preTranslate(signal, data, &send);\n if(send) {\n bool booleanValue = handler(signal, signals, signalCount, value, &send);\n if(send) {\n sendBooleanMessage(signal->genericName, booleanValue, listener);\n }\n }\n postTranslate(signal, value);\n}\n\nvoid translateCanSignal(Listener* listener, CanSignal* signal,\n uint64_t data, CanSignal* signals, int signalCount) {\n translateCanSignal(listener, signal, data, passthroughHandler, signals,\n signalCount);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"bitcoin-config.h\"\n#endif\n\n#include \"addressbookpage.h\"\n#include \"ui_addressbookpage.h\"\n\n#include \"addresstablemodel.h\"\n#include \"bitcoingui.h\"\n#include \"csvmodelwriter.h\"\n#include \"editaddressdialog.h\"\n#include \"guiutil.h\"\n\n#include <QIcon>\n#include <QMenu>\n#include <QMessageBox>\n#include <QSortFilterProxyModel>\n\nAddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::AddressBookPage),\n model(0),\n mode(mode),\n tab(tab)\n{\n ui->setupUi(this);\n\n#ifdef Q_OS_MAC \/\/ Icons on push buttons are very uncommon on Mac\n ui->newAddress->setIcon(QIcon());\n ui->copyAddress->setIcon(QIcon());\n ui->deleteAddress->setIcon(QIcon());\n ui->exportButton->setIcon(QIcon());\n#endif\n\n switch(mode)\n {\n case ForSelection:\n switch(tab)\n {\n case SendingTab: setWindowTitle(tr(\"Choose the address to send coins to\")); break;\n case ReceivingTab: setWindowTitle(tr(\"Choose the address to receive coins with\")); break;\n }\n connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));\n ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);\n ui->tableView->setFocus();\n ui->closeButton->setText(tr(\"C&hoose\"));\n ui->exportButton->hide();\n break;\n case ForEditing:\n switch(tab)\n {\n case SendingTab: setWindowTitle(tr(\"Sending addresses\")); break;\n case ReceivingTab: setWindowTitle(tr(\"Receiving addresses\")); break;\n }\n break;\n }\n switch(tab)\n {\n case SendingTab:\n ui->labelExplanation->setText(tr(\"These are your Dogecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.\"));\n ui->deleteAddress->setVisible(true);\n break;\n case ReceivingTab:\n ui->labelExplanation->setText(tr(\"These are your Dogecoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.\"));\n ui->deleteAddress->setVisible(false);\n break;\n }\n\n \/\/ Context menu actions\n QAction *copyAddressAction = new QAction(tr(\"&Copy Address\"), this);\n QAction *copyLabelAction = new QAction(tr(\"Copy &Label\"), this);\n QAction *editAction = new QAction(tr(\"&Edit\"), this);\n deleteAction = new QAction(ui->deleteAddress->text(), this);\n\n \/\/ Build context menu\n contextMenu = new QMenu();\n contextMenu->addAction(copyAddressAction);\n contextMenu->addAction(copyLabelAction);\n contextMenu->addAction(editAction);\n if(tab == SendingTab)\n contextMenu->addAction(deleteAction);\n contextMenu->addSeparator();\n\n \/\/ Connect signals for context menu actions\n connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));\n connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));\n connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));\n connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));\n\n connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));\n\n connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept()));\n}\n\nAddressBookPage::~AddressBookPage()\n{\n delete ui;\n}\n\nvoid AddressBookPage::setModel(AddressTableModel *model)\n{\n this->model = model;\n if(!model)\n return;\n\n proxyModel = new QSortFilterProxyModel(this);\n proxyModel->setSourceModel(model);\n proxyModel->setDynamicSortFilter(true);\n proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);\n proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);\n switch(tab)\n {\n case ReceivingTab:\n \/\/ Receive filter\n proxyModel->setFilterRole(AddressTableModel::TypeRole);\n proxyModel->setFilterFixedString(AddressTableModel::Receive);\n break;\n case SendingTab:\n \/\/ Send filter\n proxyModel->setFilterRole(AddressTableModel::TypeRole);\n proxyModel->setFilterFixedString(AddressTableModel::Send);\n break;\n }\n ui->tableView->setModel(proxyModel);\n ui->tableView->sortByColumn(0, Qt::AscendingOrder);\n\n \/\/ Set column widths\n#if QT_VERSION < 0x050000\n ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch);\n ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);\n#else\n ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch);\n ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);\n#endif\n\n connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),\n this, SLOT(selectionChanged()));\n\n \/\/ Select row for newly created address\n connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int)));\n\n selectionChanged();\n}\n\nvoid AddressBookPage::on_copyAddress_clicked()\n{\n GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);\n}\n\nvoid AddressBookPage::onCopyLabelAction()\n{\n GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);\n}\n\nvoid AddressBookPage::onEditAction()\n{\n if(!model)\n return;\n\n if(!ui->tableView->selectionModel())\n return;\n QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();\n if(indexes.isEmpty())\n return;\n\n EditAddressDialog dlg(\n tab == SendingTab ?\n EditAddressDialog::EditSendingAddress :\n EditAddressDialog::EditReceivingAddress, this);\n dlg.setModel(model);\n QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));\n dlg.loadRow(origIndex.row());\n dlg.exec();\n}\n\nvoid AddressBookPage::on_newAddress_clicked()\n{\n if(!model)\n return;\n\n EditAddressDialog dlg(\n tab == SendingTab ?\n EditAddressDialog::NewSendingAddress :\n EditAddressDialog::NewReceivingAddress, this);\n dlg.setModel(model);\n if(dlg.exec())\n {\n newAddressToSelect = dlg.getAddress();\n }\n}\n\nvoid AddressBookPage::on_deleteAddress_clicked()\n{\n QTableView *table = ui->tableView;\n if(!table->selectionModel())\n return;\n\n QModelIndexList indexes = table->selectionModel()->selectedRows();\n if(!indexes.isEmpty())\n {\n table->model()->removeRow(indexes.at(0).row());\n }\n}\n\nvoid AddressBookPage::selectionChanged()\n{\n \/\/ Set button states based on selected tab and selection\n QTableView *table = ui->tableView;\n if(!table->selectionModel())\n return;\n\n if(table->selectionModel()->hasSelection())\n {\n switch(tab)\n {\n case SendingTab:\n \/\/ In sending tab, allow deletion of selection\n ui->deleteAddress->setEnabled(true);\n ui->deleteAddress->setVisible(true);\n deleteAction->setEnabled(true);\n break;\n case ReceivingTab:\n \/\/ Deleting receiving addresses, however, is not allowed\n ui->deleteAddress->setEnabled(false);\n ui->deleteAddress->setVisible(false);\n deleteAction->setEnabled(false);\n break;\n }\n ui->copyAddress->setEnabled(true);\n }\n else\n {\n ui->deleteAddress->setEnabled(false);\n ui->copyAddress->setEnabled(false);\n }\n}\n\nvoid AddressBookPage::done(int retval)\n{\n QTableView *table = ui->tableView;\n if(!table->selectionModel() || !table->model())\n return;\n\n \/\/ Figure out which address was selected, and return it\n QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);\n\n foreach (QModelIndex index, indexes)\n {\n QVariant address = table->model()->data(index);\n returnValue = address.toString();\n }\n\n if(returnValue.isEmpty())\n {\n \/\/ If no address entry selected, return rejected\n retval = Rejected;\n }\n\n QDialog::done(retval);\n}\n\nvoid AddressBookPage::on_exportButton_clicked()\n{\n \/\/ CSV is currently the only supported format\n QString filename = GUIUtil::getSaveFileName(this,\n tr(\"Export Address List\"), QString(),\n tr(\"Comma separated file (*.csv)\"), NULL);\n\n if (filename.isNull())\n return;\n\n CSVModelWriter writer(filename);\n\n \/\/ name, column, role\n writer.setModel(proxyModel);\n writer.addColumn(\"Label\", AddressTableModel::Label, Qt::EditRole);\n writer.addColumn(\"Address\", AddressTableModel::Address, Qt::EditRole);\n\n if(!writer.write()) {\n QMessageBox::critical(this, tr(\"Exporting Failed\"),\n tr(\"There was an error trying to save the address list to %1.\").arg(filename));\n }\n}\n\nvoid AddressBookPage::contextualMenu(const QPoint &point)\n{\n QModelIndex index = ui->tableView->indexAt(point);\n if(index.isValid())\n {\n contextMenu->exec(QCursor::pos());\n }\n}\n\nvoid AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int \/*end*\/)\n{\n QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));\n if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))\n {\n \/\/ Select row of newly created address, once\n ui->tableView->setFocus();\n ui->tableView->selectRow(idx.row());\n newAddressToSelect.clear();\n }\n}\n<commit_msg>Update addressbookpage.cpp<commit_after>\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"bitcoin-config.h\"\n#endif\n\n#include \"addressbookpage.h\"\n#include \"ui_addressbookpage.h\"\n\n#include \"addresstablemodel.h\"\n#include \"bitcoingui.h\"\n#include \"csvmodelwriter.h\"\n#include \"editaddressdialog.h\"\n#include \"guiutil.h\"\n\n#include <QIcon>\n#include <QMenu>\n#include <QMessageBox>\n#include <QSortFilterProxyModel>\n\nAddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::AddressBookPage),\n model(0),\n mode(mode),\n tab(tab)\n{\n ui->setupUi(this);\n\n#ifdef Q_OS_MAC \/\/ Icons on push buttons are very uncommon on Mac\n ui->newAddress->setIcon(QIcon());\n ui->copyAddress->setIcon(QIcon());\n ui->deleteAddress->setIcon(QIcon());\n ui->exportButton->setIcon(QIcon());\n#endif\n\n switch(mode)\n {\n case ForSelection:\n switch(tab)\n {\n case SendingTab: setWindowTitle(tr(\"Choose the address to send coins to\")); break;\n case ReceivingTab: setWindowTitle(tr(\"Choose the address to receive coins with\")); break;\n }\n connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));\n ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);\n ui->tableView->setFocus();\n ui->closeButton->setText(tr(\"C&hoose\"));\n ui->exportButton->hide();\n break;\n case ForEditing:\n switch(tab)\n {\n case SendingTab: setWindowTitle(tr(\"Very sending addresses\")); break;\n case ReceivingTab: setWindowTitle(tr(\"Much receiving addresses\")); break;\n }\n break;\n }\n switch(tab)\n {\n case SendingTab:\n ui->labelExplanation->setText(tr(\"These are your Dogecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.\"));\n ui->deleteAddress->setVisible(true);\n break;\n case ReceivingTab:\n ui->labelExplanation->setText(tr(\"These are your Dogecoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.\"));\n ui->deleteAddress->setVisible(false);\n break;\n }\n\n \/\/ Context menu actions\n QAction *copyAddressAction = new QAction(tr(\"&Copy Address\"), this);\n QAction *copyLabelAction = new QAction(tr(\"Copy &Label\"), this);\n QAction *editAction = new QAction(tr(\"&Edit\"), this);\n deleteAction = new QAction(ui->deleteAddress->text(), this);\n\n \/\/ Build context menu\n contextMenu = new QMenu();\n contextMenu->addAction(copyAddressAction);\n contextMenu->addAction(copyLabelAction);\n contextMenu->addAction(editAction);\n if(tab == SendingTab)\n contextMenu->addAction(deleteAction);\n contextMenu->addSeparator();\n\n \/\/ Connect signals for context menu actions\n connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));\n connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));\n connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));\n connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));\n\n connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));\n\n connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept()));\n}\n\nAddressBookPage::~AddressBookPage()\n{\n delete ui;\n}\n\nvoid AddressBookPage::setModel(AddressTableModel *model)\n{\n this->model = model;\n if(!model)\n return;\n\n proxyModel = new QSortFilterProxyModel(this);\n proxyModel->setSourceModel(model);\n proxyModel->setDynamicSortFilter(true);\n proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);\n proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);\n switch(tab)\n {\n case ReceivingTab:\n \/\/ Receive filter\n proxyModel->setFilterRole(AddressTableModel::TypeRole);\n proxyModel->setFilterFixedString(AddressTableModel::Receive);\n break;\n case SendingTab:\n \/\/ Send filter\n proxyModel->setFilterRole(AddressTableModel::TypeRole);\n proxyModel->setFilterFixedString(AddressTableModel::Send);\n break;\n }\n ui->tableView->setModel(proxyModel);\n ui->tableView->sortByColumn(0, Qt::AscendingOrder);\n\n \/\/ Set column widths\n#if QT_VERSION < 0x050000\n ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch);\n ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);\n#else\n ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch);\n ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);\n#endif\n\n connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),\n this, SLOT(selectionChanged()));\n\n \/\/ Select row for newly created address\n connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int)));\n\n selectionChanged();\n}\n\nvoid AddressBookPage::on_copyAddress_clicked()\n{\n GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);\n}\n\nvoid AddressBookPage::onCopyLabelAction()\n{\n GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);\n}\n\nvoid AddressBookPage::onEditAction()\n{\n if(!model)\n return;\n\n if(!ui->tableView->selectionModel())\n return;\n QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();\n if(indexes.isEmpty())\n return;\n\n EditAddressDialog dlg(\n tab == SendingTab ?\n EditAddressDialog::EditSendingAddress :\n EditAddressDialog::EditReceivingAddress, this);\n dlg.setModel(model);\n QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));\n dlg.loadRow(origIndex.row());\n dlg.exec();\n}\n\nvoid AddressBookPage::on_newAddress_clicked()\n{\n if(!model)\n return;\n\n EditAddressDialog dlg(\n tab == SendingTab ?\n EditAddressDialog::NewSendingAddress :\n EditAddressDialog::NewReceivingAddress, this);\n dlg.setModel(model);\n if(dlg.exec())\n {\n newAddressToSelect = dlg.getAddress();\n }\n}\n\nvoid AddressBookPage::on_deleteAddress_clicked()\n{\n QTableView *table = ui->tableView;\n if(!table->selectionModel())\n return;\n\n QModelIndexList indexes = table->selectionModel()->selectedRows();\n if(!indexes.isEmpty())\n {\n table->model()->removeRow(indexes.at(0).row());\n }\n}\n\nvoid AddressBookPage::selectionChanged()\n{\n \/\/ Set button states based on selected tab and selection\n QTableView *table = ui->tableView;\n if(!table->selectionModel())\n return;\n\n if(table->selectionModel()->hasSelection())\n {\n switch(tab)\n {\n case SendingTab:\n \/\/ In sending tab, allow deletion of selection\n ui->deleteAddress->setEnabled(true);\n ui->deleteAddress->setVisible(true);\n deleteAction->setEnabled(true);\n break;\n case ReceivingTab:\n \/\/ Deleting receiving addresses, however, is not allowed\n ui->deleteAddress->setEnabled(false);\n ui->deleteAddress->setVisible(false);\n deleteAction->setEnabled(false);\n break;\n }\n ui->copyAddress->setEnabled(true);\n }\n else\n {\n ui->deleteAddress->setEnabled(false);\n ui->copyAddress->setEnabled(false);\n }\n}\n\nvoid AddressBookPage::done(int retval)\n{\n QTableView *table = ui->tableView;\n if(!table->selectionModel() || !table->model())\n return;\n\n \/\/ Figure out which address was selected, and return it\n QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);\n\n foreach (QModelIndex index, indexes)\n {\n QVariant address = table->model()->data(index);\n returnValue = address.toString();\n }\n\n if(returnValue.isEmpty())\n {\n \/\/ If no address entry selected, return rejected\n retval = Rejected;\n }\n\n QDialog::done(retval);\n}\n\nvoid AddressBookPage::on_exportButton_clicked()\n{\n \/\/ CSV is currently the only supported format\n QString filename = GUIUtil::getSaveFileName(this,\n tr(\"Export Address List\"), QString(),\n tr(\"Comma separated file (*.csv)\"), NULL);\n\n if (filename.isNull())\n return;\n\n CSVModelWriter writer(filename);\n\n \/\/ name, column, role\n writer.setModel(proxyModel);\n writer.addColumn(\"Label\", AddressTableModel::Label, Qt::EditRole);\n writer.addColumn(\"Address\", AddressTableModel::Address, Qt::EditRole);\n\n if(!writer.write()) {\n QMessageBox::critical(this, tr(\"Exporting Failed\"),\n tr(\"There was an error trying to save the address list to %1.\").arg(filename));\n }\n}\n\nvoid AddressBookPage::contextualMenu(const QPoint &point)\n{\n QModelIndex index = ui->tableView->indexAt(point);\n if(index.isValid())\n {\n contextMenu->exec(QCursor::pos());\n }\n}\n\nvoid AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int \/*end*\/)\n{\n QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));\n if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))\n {\n \/\/ Select row of newly created address, once\n ui->tableView->setFocus();\n ui->tableView->selectRow(idx.row());\n newAddressToSelect.clear();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\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 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2009 Soeren Sonnenburg\n * Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society\n *\/\n\n#include <shogun\/base\/init.h>\n#include <shogun\/lib\/memory.h>\n#include <shogun\/mathematics\/Math.h>\n#include <shogun\/mathematics\/Random.h>\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/base\/Parallel.h>\n#include <shogun\/base\/Version.h>\n#include <shogun\/base\/SGRefObject.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef TRACE_MEMORY_ALLOCS\n#include <shogun\/lib\/Map.h>\nshogun::CMap<void*, shogun::MemoryBlock>* sg_mallocs=NULL;\n#endif\n\nnamespace shogun\n{\n\tParallel* sg_parallel=NULL;\n\tSGIO* sg_io=NULL;\n\tVersion* sg_version=NULL;\n\tCMath* sg_math=NULL;\n\tCRandom* sg_rand=NULL;\n\n\t\/\/\/ function called to print normal messages\n\tvoid (*sg_print_message)(FILE* target, const char* str) = NULL;\n\n\t\/\/\/ function called to print warning messages\n\tvoid (*sg_print_warning)(FILE* target, const char* str) = NULL;\n\n\t\/\/\/ function called to print error messages\n\tvoid (*sg_print_error)(FILE* target, const char* str) = NULL;\n\n\t\/\/\/ function called to cancel things\n\tvoid (*sg_cancel_computations)(bool &delayed, bool &immediately)=NULL;\n\n\n\tvoid init_shogun(void (*print_message)(FILE* target, const char* str),\n\t\t\tvoid (*print_warning)(FILE* target, const char* str),\n\t\t\tvoid (*print_error)(FILE* target, const char* str),\n\t\t\tvoid (*cancel_computations)(bool &delayed, bool &immediately))\n\t{\n\t\tif (!sg_io)\n\t\t\tsg_io = new shogun::SGIO();\n\t\tif (!sg_parallel)\n\t\t\tsg_parallel=new shogun::Parallel();\n\t\tif (!sg_version)\n\t\t\tsg_version = new shogun::Version();\n\t\tif (!sg_math)\n\t\t\tsg_math = new shogun::CMath();\n\t\tif (!sg_rand)\n\t\t\tsg_rand = new shogun::CRandom();\n#ifdef TRACE_MEMORY_ALLOCS\n\t\tif (!sg_mallocs)\n\t\t\tsg_mallocs = new shogun::CMap<void*, MemoryBlock>(631, 1024, false);\n\n\t\tSG_REF(sg_mallocs);\n#endif\n\t\tSG_REF(sg_io);\n\t\tSG_REF(sg_parallel);\n\t\tSG_REF(sg_version);\n\t\tSG_REF(sg_math);\n\t\tSG_REF(sg_rand);\n\n\t\tsg_print_message=print_message;\n\t\tsg_print_warning=print_warning;\n\t\tsg_print_error=print_error;\n\t\tsg_cancel_computations=cancel_computations;\n\t\t\n\t\tinit_from_env();\n\t}\n\n\tvoid sg_global_print_default(FILE* target, const char* str)\n\t{\n\t\tfprintf(target, \"%s\", str);\n\t}\n\n\tvoid init_shogun_with_defaults()\n\t{\n\t\tinit_shogun(&sg_global_print_default, &sg_global_print_default,\n\t\t\t\t&sg_global_print_default);\n\t}\n\n\tvoid exit_shogun()\n\t{\n#ifdef TRACE_MEMORY_ALLOCS\n\t\tlist_memory_allocs();\n\t\tshogun::CMap<void*, shogun::MemoryBlock>* mallocs=sg_mallocs;\n\t\tsg_mallocs=NULL;\n\t\tSG_UNREF(mallocs);\n#endif\n\t\tsg_print_message=NULL;\n\t\tsg_print_warning=NULL;\n\t\tsg_print_error=NULL;\n\t\tsg_cancel_computations=NULL;\n\n\t\tSG_UNREF(sg_rand);\n\t\tSG_UNREF(sg_math);\n\t\tSG_UNREF(sg_version);\n\t\tSG_UNREF(sg_parallel);\n\t\tSG_UNREF(sg_io);\n\n\t}\n\n\tvoid set_global_io(SGIO* io)\n\t{\n\t\tSG_REF(io);\n\t\tSG_UNREF(sg_io);\n\t\tsg_io=io;\n\t}\n\n\tSGIO* get_global_io()\n\t{\n\t\tSG_REF(sg_io);\n\t\treturn sg_io;\n\t}\n\n\tvoid set_global_parallel(Parallel* parallel)\n\t{\n\t\tSG_REF(parallel);\n\t\tSG_UNREF(sg_parallel);\n\t\tsg_parallel=parallel;\n\t}\n\n\tParallel* get_global_parallel()\n\t{\n\t\tSG_REF(sg_parallel);\n\t\treturn sg_parallel;\n\t}\n\n\tvoid set_global_version(Version* version)\n\t{\n\t\tSG_REF(version);\n\t\tSG_UNREF(sg_version);\n\t\tsg_version=version;\n\t}\n\n\tVersion* get_global_version()\n\t{\n\t\tSG_REF(sg_version);\n\t\treturn sg_version;\n\t}\n\n\tvoid set_global_math(CMath* math)\n\t{\n\t\tSG_REF(math);\n\t\tSG_UNREF(sg_math);\n\t\tsg_math=math;\n\t}\n\n\tCMath* get_global_math()\n\t{\n\t\tSG_REF(sg_math);\n\t\treturn sg_math;\n\t}\n\n\tvoid set_global_rand(CRandom* rand)\n\t{\n\t\tSG_REF(rand);\n\t\tSG_UNREF(sg_rand);\n\t\tsg_rand=rand;\n\t}\n\n\tCRandom* get_global_rand()\n\t{\n\t\tSG_REF(sg_rand);\n\t\treturn sg_rand;\n\t}\n\t\n\tvoid init_from_env()\n\t{\n\t\tchar* env_log_val = NULL;\n\t\tSGIO* io = get_global_io();\n\t\tenv_log_val = getenv(\"SHOGUN_LOG_LEVEL\");\n\t\tif (env_log_val)\n\t\t{\n\t\t\tif(strncmp(env_log_val, \"DEBUG\", 5) == 0)\n\t\t\t\tio->set_loglevel(MSG_DEBUG);\n\t\t\telse if(strncmp(env_log_val, \"WARN\", 4) == 0)\n\t\t\t\tio->set_loglevel(MSG_WARN);\n\t\t\telse if(strncmp(env_log_val, \"ERROR\", 5) == 0)\n\t\t\t\tio->set_loglevel(MSG_ERROR);\n\t\t}\n\t\tSG_UNREF(io);\n\t}\n}\n<commit_msg>Cleaning up protobuf library in exit_shogun().<commit_after>\/*\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 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2009 Soeren Sonnenburg\n * Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society\n *\/\n\n#include <shogun\/base\/init.h>\n#include <shogun\/lib\/memory.h>\n#include <shogun\/mathematics\/Math.h>\n#include <shogun\/mathematics\/Random.h>\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/base\/Parallel.h>\n#include <shogun\/base\/Version.h>\n#include <shogun\/base\/SGRefObject.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef TRACE_MEMORY_ALLOCS\n#include <shogun\/lib\/Map.h>\nshogun::CMap<void*, shogun::MemoryBlock>* sg_mallocs=NULL;\n#endif\n\n#ifdef HAVE_PROTOBUF\n#include <shogun\/io\/protobuf\/Headers.pb.h>\n#endif\n\nnamespace shogun\n{\n\tParallel* sg_parallel=NULL;\n\tSGIO* sg_io=NULL;\n\tVersion* sg_version=NULL;\n\tCMath* sg_math=NULL;\n\tCRandom* sg_rand=NULL;\n\n\t\/\/\/ function called to print normal messages\n\tvoid (*sg_print_message)(FILE* target, const char* str) = NULL;\n\n\t\/\/\/ function called to print warning messages\n\tvoid (*sg_print_warning)(FILE* target, const char* str) = NULL;\n\n\t\/\/\/ function called to print error messages\n\tvoid (*sg_print_error)(FILE* target, const char* str) = NULL;\n\n\t\/\/\/ function called to cancel things\n\tvoid (*sg_cancel_computations)(bool &delayed, bool &immediately)=NULL;\n\n\n\tvoid init_shogun(void (*print_message)(FILE* target, const char* str),\n\t\t\tvoid (*print_warning)(FILE* target, const char* str),\n\t\t\tvoid (*print_error)(FILE* target, const char* str),\n\t\t\tvoid (*cancel_computations)(bool &delayed, bool &immediately))\n\t{\n\t\tif (!sg_io)\n\t\t\tsg_io = new shogun::SGIO();\n\t\tif (!sg_parallel)\n\t\t\tsg_parallel=new shogun::Parallel();\n\t\tif (!sg_version)\n\t\t\tsg_version = new shogun::Version();\n\t\tif (!sg_math)\n\t\t\tsg_math = new shogun::CMath();\n\t\tif (!sg_rand)\n\t\t\tsg_rand = new shogun::CRandom();\n#ifdef TRACE_MEMORY_ALLOCS\n\t\tif (!sg_mallocs)\n\t\t\tsg_mallocs = new shogun::CMap<void*, MemoryBlock>(631, 1024, false);\n\n\t\tSG_REF(sg_mallocs);\n#endif\n\t\tSG_REF(sg_io);\n\t\tSG_REF(sg_parallel);\n\t\tSG_REF(sg_version);\n\t\tSG_REF(sg_math);\n\t\tSG_REF(sg_rand);\n\n\t\tsg_print_message=print_message;\n\t\tsg_print_warning=print_warning;\n\t\tsg_print_error=print_error;\n\t\tsg_cancel_computations=cancel_computations;\n\t\t\n\t\tinit_from_env();\n\t}\n\n\tvoid sg_global_print_default(FILE* target, const char* str)\n\t{\n\t\tfprintf(target, \"%s\", str);\n\t}\n\n\tvoid init_shogun_with_defaults()\n\t{\n\t\tinit_shogun(&sg_global_print_default, &sg_global_print_default,\n\t\t\t\t&sg_global_print_default);\n\t}\n\n\tvoid exit_shogun()\n\t{\n#ifdef TRACE_MEMORY_ALLOCS\n\t\tlist_memory_allocs();\n\t\tshogun::CMap<void*, shogun::MemoryBlock>* mallocs=sg_mallocs;\n\t\tsg_mallocs=NULL;\n\t\tSG_UNREF(mallocs);\n#endif\n\t\tsg_print_message=NULL;\n\t\tsg_print_warning=NULL;\n\t\tsg_print_error=NULL;\n\t\tsg_cancel_computations=NULL;\n\n\t\tSG_UNREF(sg_rand);\n\t\tSG_UNREF(sg_math);\n\t\tSG_UNREF(sg_version);\n\t\tSG_UNREF(sg_parallel);\n\t\tSG_UNREF(sg_io);\n\n#ifdef HAVE_PROTOBUF\n\t\t::google::protobuf::ShutdownProtobufLibrary();\n#endif\n\t}\n\n\tvoid set_global_io(SGIO* io)\n\t{\n\t\tSG_REF(io);\n\t\tSG_UNREF(sg_io);\n\t\tsg_io=io;\n\t}\n\n\tSGIO* get_global_io()\n\t{\n\t\tSG_REF(sg_io);\n\t\treturn sg_io;\n\t}\n\n\tvoid set_global_parallel(Parallel* parallel)\n\t{\n\t\tSG_REF(parallel);\n\t\tSG_UNREF(sg_parallel);\n\t\tsg_parallel=parallel;\n\t}\n\n\tParallel* get_global_parallel()\n\t{\n\t\tSG_REF(sg_parallel);\n\t\treturn sg_parallel;\n\t}\n\n\tvoid set_global_version(Version* version)\n\t{\n\t\tSG_REF(version);\n\t\tSG_UNREF(sg_version);\n\t\tsg_version=version;\n\t}\n\n\tVersion* get_global_version()\n\t{\n\t\tSG_REF(sg_version);\n\t\treturn sg_version;\n\t}\n\n\tvoid set_global_math(CMath* math)\n\t{\n\t\tSG_REF(math);\n\t\tSG_UNREF(sg_math);\n\t\tsg_math=math;\n\t}\n\n\tCMath* get_global_math()\n\t{\n\t\tSG_REF(sg_math);\n\t\treturn sg_math;\n\t}\n\n\tvoid set_global_rand(CRandom* rand)\n\t{\n\t\tSG_REF(rand);\n\t\tSG_UNREF(sg_rand);\n\t\tsg_rand=rand;\n\t}\n\n\tCRandom* get_global_rand()\n\t{\n\t\tSG_REF(sg_rand);\n\t\treturn sg_rand;\n\t}\n\t\n\tvoid init_from_env()\n\t{\n\t\tchar* env_log_val = NULL;\n\t\tSGIO* io = get_global_io();\n\t\tenv_log_val = getenv(\"SHOGUN_LOG_LEVEL\");\n\t\tif (env_log_val)\n\t\t{\n\t\t\tif(strncmp(env_log_val, \"DEBUG\", 5) == 0)\n\t\t\t\tio->set_loglevel(MSG_DEBUG);\n\t\t\telse if(strncmp(env_log_val, \"WARN\", 4) == 0)\n\t\t\t\tio->set_loglevel(MSG_WARN);\n\t\t\telse if(strncmp(env_log_val, \"ERROR\", 5) == 0)\n\t\t\t\tio->set_loglevel(MSG_ERROR);\n\t\t}\n\t\tSG_UNREF(io);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"world.h\"\n\n#include \"..\/core\/console.h\"\n#include \"..\/core\/content.h\"\n#include \"..\/util\/mathutils.h\"\n#include \"..\/util\/log.h\"\n\n#include \"cell.h\"\n#include \"food.h\"\n#include \"water.h\"\n\n#include <sstream>\n#include <iostream>\n\nNeuralNetwork* World::m_neuralNetwork = 0;\nuint32 World::m_weightCount = 0;\n\n\/\/ 8192.0f\nWorld::World() :\n m_radius(2048.0f),\n m_spatialHash(m_radius),\n m_debug(false)\n{\n std::cout << \"world ctor\" << std::endl;\n\n \/\/ TODO (Tyler): Fine tune the hidden nodes.\n m_neuralNetwork = new NeuralNetwork(11, 8, 4);\n m_weightCount = m_neuralNetwork->getWeightCount();\n}\n\nWorld::~World()\n{\n std::cout << \"world dtor\" << std::endl;\n\n if (m_neuralNetwork)\n delete m_neuralNetwork;\n\n m_neuralNetwork = 0;\n}\n\nbool World::initialize()\n{\n m_border.setRadius(m_radius);\n m_border.setOrigin(m_radius, m_radius);\n m_border.setFillColor(sf::Color(32, 32, 32, 255));\n m_border.setOutlineColor(sf::Color(128, 128, 128, 255));\n m_border.setOutlineThickness(10.0f);\n m_border.setPointCount(100);\n\n m_vertexQuadArray.setPrimitiveType(sf::Quads);\n m_vertexLineArray.setPrimitiveType(sf::Lines);\n\n m_debugText = new sf::Text();\n m_debugText->setFont(*Content::font);\n m_debugText->setPosition(0.0f, 100.0f);\n m_debugText->setCharacterSize(16);\n\n for (int32 i = 0; i < 500; i++) {\n Cell* newCell = new Cell(1, Genome(), randomWorldPoint(), *this);\n newCell->setMass(100.0f);\n m_entities.push_back(newCell);\n }\n\n for (int32 i = 0; i < 200; i++)\n m_entities.push_back(new Food(randomWorldPoint(), *this));\n\n m_spatialHash.buildArray(m_vertexQuadArray, sf::Quads);\n m_spatialHash.buildArray(m_vertexLineArray, sf::Lines);\n\n updateEntityText();\n\n return true;\n}\n\nvoid World::destroy()\n{\n if (m_debugText)\n delete m_debugText;\n\n for (auto& entity : m_entities) {\n delete entity;\n }\n\n m_entities.clear();\n}\n\nvoid World::update(const float dt)\n{\n bool hasChanged = false;\n bool entityDied = false;\n\n for (int32 i = m_entities.size() - 1; i >= 0; i--) {\n Entity* entity = m_entities[i];\n if (entity->isAlive()) {\n\n entity->update(dt);\n\n if (entity->updateHash()) {\n m_spatialHash.update(entity);\n hasChanged = true;\n }\n }\n else {\n\n m_entities.erase(m_entities.begin() + i);\n onDeath(entity);\n\n \/\/ Make sure we remove the entity from the spatialhash and all of the nodes that it exists in.\n \/\/ This can cause problems because a node may contain a null reference to an entity which causesa c crash.\n m_spatialHash.remove(entity);\n\n delete entity;\n entityDied = true;\n }\n }\n\n if (hasChanged && m_debug) {\n m_vertexQuadArray.clear();\n m_vertexLineArray.clear();\n m_spatialHash.buildArray(m_vertexQuadArray, sf::Quads);\n m_spatialHash.buildArray(m_vertexLineArray, sf::Lines);\n }\n\n if (entityDied) {\n updateEntityText();\n }\n}\n\nvoid World::updateEntityText()\n{\n std::stringstream sb;\n sb << \"entity count: \" << m_entities.size() << \", cell count: \" << Cell::m_cellCount;\n m_debugText->setString(sb.str());\n}\n\nvoid World::onDeath(Entity* entity)\n{\n if (entity->getType() == type::Cell) {\n\n Cell* cell = (Cell*)entity;\n if (cell) {\n\n std::stringstream sb;\n sb << \"entity died at generation: \" << cell->getGeneration();\n\n Console::write(sb.str());\n }\n\n }\n else if (entity->getType() == type::Resource) {\n\n Resource* resource = (Resource*)entity;\n if (resource->getResourceType() == type::Food) {\n m_entities.push_back(new Food(randomWorldPoint(), *this));\n }\n else if (resource->getResourceType() == type::Water) {\n m_entities.push_back(new Water(randomWorldPoint(), *this));\n }\n }\n}\n\nvoid World::render(sf::RenderTarget& target, Camera& camera, const sf::View& textView)\n{\n \/\/ Setup the camera view for the world\n camera.render(target);\n\n target.draw(m_border, Content::shader);\n\n if (m_debug) {\n target.draw(m_vertexQuadArray, Content::shader);\n target.draw(m_vertexLineArray, Content::shader);\n }\n\n for (auto& entity : m_entities) {\n\n if (entity->isAlive()) {\n entity->render(target);\n }\n }\n\n target.setView(textView);\n target.draw(*m_debugText);\n}\n\nvec2f World::randomWorldPoint()\n{\n \/\/ Generate a random angle between 0 and 2(Pi).\n const real32 theta = randomFloat(0.0f) * nx::Pi * 2.0f;\n return vec2f(std::cos(theta) * randomFloat(0.0f, m_radius),\n std::sin(theta) * randomFloat(0.0f, m_radius));\n}\n\nvoid World::add(Entity* entity)\n{\n \/\/ Make sure there is never a null entity added.\n if (entity == 0) {\n return;\n }\n\n m_entities.push_back(entity);\n}\n\nbool World::isPointInWorld(vec2f point)\n{\n const vec2f delta = point * point;\n\n return (delta.x + delta.y <= m_radius * m_radius);\n}\n\nbool World::isEntityInWorld(Entity* entity)\n{\n \/\/ Well a null entity can't exist in the world so ya..\n if (entity == 0) {\n return false;\n }\n\n return isPointInWorld(entity->getLocation());\n}\n<commit_msg>Minor formatting in the world class.<commit_after>#include \"world.h\"\n\n#include \"..\/core\/console.h\"\n#include \"..\/core\/content.h\"\n#include \"..\/util\/mathutils.h\"\n#include \"..\/util\/log.h\"\n\n#include \"cell.h\"\n#include \"food.h\"\n#include \"water.h\"\n\n#include <sstream>\n\nNeuralNetwork* World::m_neuralNetwork = 0;\nuint32 World::m_weightCount = 0;\n\n\/\/ 8192.0f\nWorld::World() :\n m_radius(2048.0f),\n m_spatialHash(m_radius),\n m_debug(false)\n{\n \/\/ TODO (Tyler): Fine tune the hidden nodes.\n m_neuralNetwork = new NeuralNetwork(11, 8, 4);\n m_weightCount = m_neuralNetwork->getWeightCount();\n}\n\nWorld::~World()\n{\n if (m_neuralNetwork)\n delete m_neuralNetwork;\n\n m_neuralNetwork = 0;\n}\n\nbool World::initialize()\n{\n m_border.setRadius(m_radius);\n m_border.setOrigin(m_radius, m_radius);\n m_border.setFillColor(sf::Color(32, 32, 32, 255));\n m_border.setOutlineColor(sf::Color(128, 128, 128, 255));\n m_border.setOutlineThickness(10.0f);\n m_border.setPointCount(100);\n\n m_vertexQuadArray.setPrimitiveType(sf::Quads);\n m_vertexLineArray.setPrimitiveType(sf::Lines);\n\n m_debugText = new sf::Text();\n m_debugText->setFont(*Content::font);\n m_debugText->setPosition(0.0f, 100.0f);\n m_debugText->setCharacterSize(16);\n\n for (int32 i = 0; i < 500; i++) {\n Cell* newCell = new Cell(1, Genome(), randomWorldPoint(), *this);\n newCell->setMass(100.0f);\n m_entities.push_back(newCell);\n }\n\n for (int32 i = 0; i < 200; i++)\n m_entities.push_back(new Food(randomWorldPoint(), *this));\n\n m_spatialHash.buildArray(m_vertexQuadArray, sf::Quads);\n m_spatialHash.buildArray(m_vertexLineArray, sf::Lines);\n\n updateEntityText();\n\n return true;\n}\n\nvoid World::destroy()\n{\n if (m_debugText)\n delete m_debugText;\n\n for (auto& entity : m_entities) {\n delete entity;\n }\n\n m_entities.clear();\n}\n\nvoid World::update(const float dt)\n{\n bool hasChanged = false;\n bool entityDied = false;\n\n for (int32 i = m_entities.size() - 1; i >= 0; i--) {\n Entity* entity = m_entities[i];\n if (entity->isAlive()) {\n\n entity->update(dt);\n\n if (entity->updateHash()) {\n m_spatialHash.update(entity);\n hasChanged = true;\n }\n }\n else {\n\n m_entities.erase(m_entities.begin() + i);\n onDeath(entity);\n\n \/\/ Make sure we remove the entity from the spatialhash and all of the nodes that it exists in.\n \/\/ This can cause problems because a node may contain a null reference to an entity which causesa c crash.\n m_spatialHash.remove(entity);\n\n delete entity;\n entityDied = true;\n }\n }\n\n if (hasChanged && m_debug) {\n m_vertexQuadArray.clear();\n m_vertexLineArray.clear();\n m_spatialHash.buildArray(m_vertexQuadArray, sf::Quads);\n m_spatialHash.buildArray(m_vertexLineArray, sf::Lines);\n }\n\n if (entityDied) {\n updateEntityText();\n }\n}\n\nvoid World::updateEntityText()\n{\n std::stringstream sb;\n sb << \"entity count: \" << m_entities.size() << \", cell count: \" << Cell::m_cellCount;\n m_debugText->setString(sb.str());\n}\n\nvoid World::onDeath(Entity* entity)\n{\n if (entity->getType() == type::Cell) {\n\n Cell* cell = (Cell*)entity;\n if (cell) {\n\n std::stringstream sb;\n sb << \"entity died at generation: \" << cell->getGeneration();\n\n Console::write(sb.str());\n }\n\n }\n else if (entity->getType() == type::Resource) {\n\n Resource* resource = (Resource*)entity;\n if (resource->getResourceType() == type::Food) {\n m_entities.push_back(new Food(randomWorldPoint(), *this));\n }\n else if (resource->getResourceType() == type::Water) {\n m_entities.push_back(new Water(randomWorldPoint(), *this));\n }\n }\n}\n\nvoid World::render(sf::RenderTarget& target, Camera& camera, const sf::View& textView)\n{\n \/\/ Setup the camera view for the world\n camera.render(target);\n\n target.draw(m_border, Content::shader);\n\n if (m_debug) {\n target.draw(m_vertexQuadArray, Content::shader);\n target.draw(m_vertexLineArray, Content::shader);\n }\n\n for (auto& entity : m_entities) {\n\n if (entity->isAlive()) {\n entity->render(target);\n }\n }\n\n target.setView(textView);\n target.draw(*m_debugText);\n}\n\nvec2f World::randomWorldPoint()\n{\n \/\/ Generate a random angle between 0 and 2(Pi).\n const real32 theta = randomFloat(0.0f) * nx::Pi * 2.0f;\n return vec2f(std::cos(theta) * randomFloat(0.0f, m_radius),\n std::sin(theta) * randomFloat(0.0f, m_radius));\n}\n\nvoid World::add(Entity* entity)\n{\n \/\/ Make sure there is never a null entity added.\n if (entity == 0) {\n return;\n }\n\n m_entities.push_back(entity);\n}\n\nbool World::isPointInWorld(vec2f point)\n{\n const vec2f delta = point * point;\n\n return (delta.x + delta.y <= m_radius * m_radius);\n}\n\nbool World::isEntityInWorld(Entity* entity)\n{\n \/\/ Well a null entity can't exist in the world so ya..\n if (entity == 0) {\n return false;\n }\n\n return isPointInWorld(entity->getLocation());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"txhistorydialog.h\"\n#include \"ui_txhistorydialog.h\"\n\n#include \"guiutil.h\"\n#include \"optionsmodel.h\"\n#include \"walletmodel.h\"\n#include \"wallet.h\"\n#include \"base58.h\"\n#include \"ui_interface.h\"\n\n#include <boost\/filesystem.hpp>\n\n#include \"leveldb\/db.h\"\n#include \"leveldb\/write_batch.h\"\n\n\/\/ potentially overzealous includes here\n#include \"base58.h\"\n#include \"rpcserver.h\"\n#include \"init.h\"\n#include \"util.h\"\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <utility>\n#include <string>\n#include <boost\/assign\/list_of.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/find.hpp>\n#include <boost\/algorithm\/string\/join.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/format.hpp>\n#include <boost\/filesystem.hpp>\n#include \"json\/json_spirit_utils.h\"\n#include \"json\/json_spirit_value.h\"\n#include \"leveldb\/db.h\"\n#include \"leveldb\/write_batch.h\"\n\/\/ end potentially overzealous includes\n\nusing namespace json_spirit;\n#include \"mastercore.h\"\nusing namespace mastercore;\n\n\/\/ potentially overzealous using here\nusing namespace std;\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace leveldb;\n\/\/ end potentially overzealous using\n\n#include \"mastercore_dex.h\"\n#include \"mastercore_tx.h\"\n#include \"mastercore_sp.h\"\n#include \"mastercore_parse_string.h\"\n\n#include <QDateTime>\n#include <QMessageBox>\n#include <QScrollBar>\n#include <QTextDocument>\n\n#include \"txlistdelegate.h\"\n\nTXHistoryDialog::TXHistoryDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::txHistoryDialog),\n model(0)\n{\n ui->setupUi(this);\n this->model = model;\n ui->txHistoryLW->setItemDelegate(new TXListDelegate(ui->txHistoryLW));\n\n CWallet *wallet = pwalletMain;\n string sAddress = \"\";\n string addressParam = \"\";\n\n int64_t nCount = 10;\n int64_t nFrom = 0;\n int64_t nStartBlock = 0;\n int64_t nEndBlock = 999999;\n\n Array response; \/\/prep an array to hold our output\n\n \/\/ rewrite to use original listtransactions methodology from core\n LOCK(wallet->cs_wallet);\n std::list<CAccountingEntry> acentries;\n CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, \"*\");\n\n \/\/ iterate backwards \n for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)\n {\n CWalletTx *const pwtx = (*it).second.first;\n if (pwtx != 0)\n {\n uint256 hash = pwtx->GetHash();\n CTransaction wtx;\n uint256 blockHash = 0;\n if (!GetTransaction(hash, wtx, blockHash, true)) continue;\n \/\/ get the time of the tx\n int64_t nTime = pwtx->GetTxTime();\n \/\/ get the height of the transaction and check it's within the chosen parameters\n blockHash = pwtx->hashBlock;\n if ((0 == blockHash) || (NULL == mapBlockIndex[blockHash])) continue;\n CBlockIndex* pBlockIndex = mapBlockIndex[blockHash];\n if (NULL == pBlockIndex) continue;\n int blockHeight = pBlockIndex->nHeight;\n if ((blockHeight < nStartBlock) || (blockHeight > nEndBlock)) continue; \/\/ ignore it if not within our range\n \/\/ check if the transaction exists in txlist, and if so is it correct type (21)\n if (p_txlistdb->exists(hash))\n {\n string statusText;\n unsigned int propertyId = 0;\n uint64_t amount = 0;\n string address;\n bool divisible = false;\n bool valid = false;\n string MPTxType;\n\n CMPTransaction mp_obj;\n int parseRC = parseTransaction(true, wtx, blockHeight, 0, &mp_obj);\n if (0 <= parseRC) \/\/negative RC means no MP content\/badly encoded TX, we shouldn't see this if TX in levelDB but check for sanity\n {\n if (0<=mp_obj.step1())\n {\n MPTxType = mp_obj.getTypeString();\n address = mp_obj.getSender();\n\n int tmpblock=0;\n uint32_t tmptype=0;\n uint64_t amountNew=0;\n valid=getValidMPTX(hash, &tmpblock, &tmptype, &amountNew);\n\n if (0 == mp_obj.step2_Value())\n {\n propertyId = mp_obj.getProperty();\n amount = mp_obj.getAmount();\n divisible = isPropertyDivisible(propertyId);\n }\n }\n }\n QListWidgetItem *qItem = new QListWidgetItem();\n qItem->setData(Qt::DisplayRole, QString::fromStdString(hash.GetHex()));\n string displayType = MPTxType;\n string displayAmount;\n string displayToken;\n string displayValid;\n string displayAddress = address;\n if (divisible) { displayAmount = FormatDivisibleMP(amount); } else { displayAmount = FormatIndivisibleMP(amount); }\n if (valid) { displayValid = \"valid\"; } else { displayValid = \"invalid\"; }\n if (propertyId < 3)\n {\n if(propertyId == 1) { displayToken = \" MSC\"; }\n if(propertyId == 2) { displayToken = \" TMSC\"; }\n }\n else\n {\n string s = to_string(propertyId);\n displayToken = \" SPT#\" + s;\n }\n string displayDirection = \"out\";\n QDateTime txTime;\n txTime.setTime_t(nTime);\n QString txTimeStr = txTime.toString(Qt::SystemLocaleShortDate);\n qItem->setData(Qt::UserRole + 1, QString::fromStdString(displayType));\n qItem->setData(Qt::UserRole + 2, QString::fromStdString(displayAmount + \" \" + displayToken));\n qItem->setData(Qt::UserRole + 3, QString::fromStdString(displayDirection));\n qItem->setData(Qt::UserRole + 4, QString::fromStdString(displayAddress));\n qItem->setData(Qt::UserRole + 5, txTimeStr);\n qItem->setData(Qt::UserRole + 6, QString::fromStdString(displayValid));\n ui->txHistoryLW->addItem(qItem);\n }\n }\n }\n \/\/ don't burn time doing more work than we need to\n\/\/ if ((int)response.size() >= (nCount+nFrom)) break;\n \/\/ sort array here and cut on nFrom and nCount\n\/\/ if (nFrom > (int)response.size())\n\/\/ nFrom = response.size();\n\/\/ if ((nFrom + nCount) > (int)response.size())\n\/\/ nCount = response.size() - nFrom;\n\/\/ Array::iterator first = response.begin();\n\/\/ std::advance(first, nFrom);\n\/\/ Array::iterator last = response.begin();\n\/\/ std::advance(last, nFrom+nCount);\n\n\/\/ if (last != response.end()) response.erase(last, response.end());\n\/\/ if (first != response.begin()) response.erase(response.begin(), first);\n\n\/\/ std::reverse(response.begin(), response.end()); \/\/ return oldest to newest?\n \/\/ return response; \/\/ return response array for JSON serialization\n\n}\n\nvoid TXHistoryDialog::setModel(WalletModel *model)\n{\n this->model = model;\n \/\/connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(OrderRefresh()));\n}\n\n<commit_msg>Fix decimals and direction<commit_after>\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"txhistorydialog.h\"\n#include \"ui_txhistorydialog.h\"\n\n#include \"guiutil.h\"\n#include \"optionsmodel.h\"\n#include \"walletmodel.h\"\n#include \"wallet.h\"\n#include \"base58.h\"\n#include \"ui_interface.h\"\n\n#include <boost\/filesystem.hpp>\n\n#include \"leveldb\/db.h\"\n#include \"leveldb\/write_batch.h\"\n\n\/\/ potentially overzealous includes here\n#include \"base58.h\"\n#include \"rpcserver.h\"\n#include \"init.h\"\n#include \"util.h\"\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <utility>\n#include <string>\n#include <boost\/assign\/list_of.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/find.hpp>\n#include <boost\/algorithm\/string\/join.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/format.hpp>\n#include <boost\/filesystem.hpp>\n#include \"json\/json_spirit_utils.h\"\n#include \"json\/json_spirit_value.h\"\n#include \"leveldb\/db.h\"\n#include \"leveldb\/write_batch.h\"\n\/\/ end potentially overzealous includes\n\nusing namespace json_spirit;\n#include \"mastercore.h\"\nusing namespace mastercore;\n\n\/\/ potentially overzealous using here\nusing namespace std;\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace leveldb;\n\/\/ end potentially overzealous using\n\n#include \"mastercore_dex.h\"\n#include \"mastercore_tx.h\"\n#include \"mastercore_sp.h\"\n#include \"mastercore_parse_string.h\"\n\n#include <QDateTime>\n#include <QMessageBox>\n#include <QScrollBar>\n#include <QTextDocument>\n\n#include \"txlistdelegate.h\"\n\nTXHistoryDialog::TXHistoryDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::txHistoryDialog),\n model(0)\n{\n ui->setupUi(this);\n this->model = model;\n ui->txHistoryLW->setItemDelegate(new TXListDelegate(ui->txHistoryLW));\n\n CWallet *wallet = pwalletMain;\n string sAddress = \"\";\n string addressParam = \"\";\n\n int64_t nCount = 10;\n int64_t nFrom = 0;\n int64_t nStartBlock = 0;\n int64_t nEndBlock = 999999;\n\n Array response; \/\/prep an array to hold our output\n\n \/\/ rewrite to use original listtransactions methodology from core\n LOCK(wallet->cs_wallet);\n std::list<CAccountingEntry> acentries;\n CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, \"*\");\n\n \/\/ iterate backwards \n for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)\n {\n CWalletTx *const pwtx = (*it).second.first;\n if (pwtx != 0)\n {\n uint256 hash = pwtx->GetHash();\n CTransaction wtx;\n uint256 blockHash = 0;\n if (!GetTransaction(hash, wtx, blockHash, true)) continue;\n \/\/ get the time of the tx\n int64_t nTime = pwtx->GetTxTime();\n \/\/ get the height of the transaction and check it's within the chosen parameters\n blockHash = pwtx->hashBlock;\n if ((0 == blockHash) || (NULL == mapBlockIndex[blockHash])) continue;\n CBlockIndex* pBlockIndex = mapBlockIndex[blockHash];\n if (NULL == pBlockIndex) continue;\n int blockHeight = pBlockIndex->nHeight;\n if ((blockHeight < nStartBlock) || (blockHeight > nEndBlock)) continue; \/\/ ignore it if not within our range\n \/\/ check if the transaction exists in txlist, and if so is it correct type (21)\n if (p_txlistdb->exists(hash))\n {\n string statusText;\n unsigned int propertyId = 0;\n uint64_t amount = 0;\n string address;\n bool divisible = false;\n bool valid = false;\n string MPTxType;\n\n CMPTransaction mp_obj;\n int parseRC = parseTransaction(true, wtx, blockHeight, 0, &mp_obj);\n if (0 <= parseRC) \/\/negative RC means no MP content\/badly encoded TX, we shouldn't see this if TX in levelDB but check for sanity\n {\n if (0<=mp_obj.step1())\n {\n MPTxType = mp_obj.getTypeString();\n address = mp_obj.getSender();\n\n int tmpblock=0;\n uint32_t tmptype=0;\n uint64_t amountNew=0;\n valid=getValidMPTX(hash, &tmpblock, &tmptype, &amountNew);\n\n if (0 == mp_obj.step2_Value())\n {\n propertyId = mp_obj.getProperty();\n amount = mp_obj.getAmount();\n divisible = isPropertyDivisible(propertyId);\n }\n }\n }\n QListWidgetItem *qItem = new QListWidgetItem();\n qItem->setData(Qt::DisplayRole, QString::fromStdString(hash.GetHex()));\n string displayType = MPTxType;\n string displayAmount;\n string displayToken;\n string displayValid;\n string displayAddress = address;\n if (divisible) { displayAmount = FormatDivisibleMP(amount); } else { displayAmount = FormatIndivisibleMP(amount); }\n \/\/ clean up trailing zeros - good for RPC not so much for UI\n displayAmount.erase ( displayAmount.find_last_not_of('0') + 1, std::string::npos );\n if (displayAmount.length() > 0) { std::string::iterator it = displayAmount.end() - 1; if (*it == '.') { displayAmount.erase(it); } } \/\/get rid of trailing dot if non decimal\n if (valid) { displayValid = \"valid\"; } else { displayValid = \"invalid\"; }\n if (propertyId < 3)\n {\n if(propertyId == 1) { displayToken = \" MSC\"; }\n if(propertyId == 2) { displayToken = \" TMSC\"; }\n }\n else\n {\n string s = to_string(propertyId);\n displayToken = \" SPT#\" + s;\n }\n string displayDirection = \"out\";\n if (!IsMyAddress(displayAddress)) displayDirection = \"in\";\n QDateTime txTime;\n txTime.setTime_t(nTime);\n QString txTimeStr = txTime.toString(Qt::SystemLocaleShortDate);\n qItem->setData(Qt::UserRole + 1, QString::fromStdString(displayType));\n qItem->setData(Qt::UserRole + 2, QString::fromStdString(displayAmount + displayToken));\n qItem->setData(Qt::UserRole + 3, QString::fromStdString(displayDirection));\n qItem->setData(Qt::UserRole + 4, QString::fromStdString(displayAddress));\n qItem->setData(Qt::UserRole + 5, txTimeStr);\n qItem->setData(Qt::UserRole + 6, QString::fromStdString(displayValid));\n ui->txHistoryLW->addItem(qItem);\n }\n }\n }\n \/\/ don't burn time doing more work than we need to\n\/\/ if ((int)response.size() >= (nCount+nFrom)) break;\n \/\/ sort array here and cut on nFrom and nCount\n\/\/ if (nFrom > (int)response.size())\n\/\/ nFrom = response.size();\n\/\/ if ((nFrom + nCount) > (int)response.size())\n\/\/ nCount = response.size() - nFrom;\n\/\/ Array::iterator first = response.begin();\n\/\/ std::advance(first, nFrom);\n\/\/ Array::iterator last = response.begin();\n\/\/ std::advance(last, nFrom+nCount);\n\n\/\/ if (last != response.end()) response.erase(last, response.end());\n\/\/ if (first != response.begin()) response.erase(response.begin(), first);\n\n\/\/ std::reverse(response.begin(), response.end()); \/\/ return oldest to newest?\n \/\/ return response; \/\/ return response array for JSON serialization\n\n}\n\nvoid TXHistoryDialog::setModel(WalletModel *model)\n{\n this->model = model;\n \/\/connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(OrderRefresh()));\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include \"command.h\"\n#include \"..\/CmdHandler.h\"\n#include \"..\/option.h\"\n#include \"..\/stringparse.h\"\n\n\/* full name of the command *\/\nCMDNAME(\"mod\");\n\/* description of the command *\/\nCMDDESCR(\"perform moderation actions\");\n\/* command usage synopsis *\/\nCMDUSAGE(\"$mod <-b|-t> [-l LEN] USER [REASON...]\");\n\n\/* mod: perform moderation commands *\/\nint CmdHandler::mod(char *out, struct command *c)\n{\n\tchar *s;\n\tconst char *t;\n\tint action, lenflag;\n\tint64_t len;\n\tchar reason[MAX_MSG];\n\tchar name[RSN_BUF];\n\n\tint opt;\n\tstatic struct l_option long_opts[] = {\n\t\t{ \"ban\", NO_ARG, 'b' },\n\t\t{ \"help\", NO_ARG, 'h' },\n\t\t{ \"length\", REQ_ARG, 'l' },\n\t\t{ \"timeout\", NO_ARG, 't' },\n\t\t{ 0, 0, 0 }\n\t};\n\n\topt_init();\n\taction = lenflag = 0;\n\tlen = 300;\n\twhile ((opt = l_getopt_long(c->argc, c->argv, \"bl:t\", long_opts))\n\t\t\t!= EOF) {\n\t\tswitch (opt) {\n\t\tcase 'b':\n\t\t\tif (action) {\n\t\t\t\t_sprintf(out, MAX_MSG, \"%s: cannot both timeout\"\n\t\t\t\t\t\t\" and ban\", c->argv[0]);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\taction = BAN;\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\tHELPMSG(out, CMDNAME, CMDUSAGE, CMDDESCR);\n\t\t\treturn EXIT_SUCCESS;\n\t\tcase 'l':\n\t\t\tif (!parsenum(l_optarg, &len)) {\n\t\t\t\t_sprintf(out, MAX_MSG, \"%s: invalid number: %s\",\n\t\t\t\t\t\tc->argv[0], l_optarg);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\tif (len < 0) {\n\t\t\t\t_sprintf(out, MAX_MSG, \"%s: length cannot be \"\n\t\t\t\t\t\t\"negative\", c->argv[0]);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\tlenflag = 1;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tif (action) {\n\t\t\t\t_sprintf(out, MAX_MSG, \"%s: cannot both timeout\"\n\t\t\t\t\t\t\" and ban\", c->argv[0]);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\taction = TIMEOUT;\n\t\t\tbreak;\n\t\tcase '?':\n\t\t\t_sprintf(out, MAX_MSG, \"%s\", l_opterr());\n\t\t\treturn EXIT_FAILURE;\n\t\tdefault:\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\tif (!action || l_optind == c->argc) {\n\t\tUSAGEMSG(out, CMDNAME, CMDUSAGE);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tif (lenflag && action != TIMEOUT) {\n\t\t_sprintf(out, MAX_MSG, \"%s: specifying length doesn't \"\n\t\t\t\t\"make sense for a ban\", c->nick);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/* convert names to lower for lookup *\/\n\ts = name;\n\tt = m_name;\n\twhile ((*s++ = tolower(*t++)))\n\t\t;\n\tfor (s = c->argv[l_optind]; *s; ++s)\n\t\t*s = tolower(*s);\n\n\tif (strcmp(c->argv[l_optind], name) == 0) {\n\t\t_sprintf(out, MAX_MSG, \"@%s, I'd rather not.\", c->nick);\n\t\treturn EXIT_SUCCESS;\n\t}\n\tif (strcmp(c->argv[l_optind], c->nick) == 0) {\n\t\t_sprintf(out, MAX_MSG, \"@%s, don't be silly!\", c->nick);\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\targvcat(reason, c->argc, c->argv, l_optind + 1, 1);\n\t\/* attempt to perform the moderation action *\/\n\tif (!m_modp->mod_action(action, c->argv[l_optind],\n\t\t\t\tc->nick, reason, len)) {\n\t\t_sprintf(out, MAX_MSG, \"%s: user '%s' is not currently in the \"\n\t\t\t\t\"channel\", c->argv[0], c->argv[l_optind]);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t_sprintf(out, MAX_MSG, \"@%s, user '%s' has been %s\",\n\t\t\tc->nick, c->argv[l_optind],\n\t\t\taction == BAN ? \"banned\" : \"timed out\");\n\tif (*reason) {\n\t\tstrcat(out, \" for \");\n\t\tstrcat(out, reason);\n\t}\n\tstrcat(out, \".\");\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>Privilege check for mod command<commit_after>#include <string.h>\n#include \"command.h\"\n#include \"..\/CmdHandler.h\"\n#include \"..\/option.h\"\n#include \"..\/stringparse.h\"\n\n\/* full name of the command *\/\nCMDNAME(\"mod\");\n\/* description of the command *\/\nCMDDESCR(\"perform moderation actions\");\n\/* command usage synopsis *\/\nCMDUSAGE(\"$mod <-b|-t> [-l LEN] USER [REASON...]\");\n\n\/* mod: perform moderation commands *\/\nint CmdHandler::mod(char *out, struct command *c)\n{\n\tchar *s;\n\tconst char *t;\n\tint action, lenflag;\n\tint64_t len;\n\tchar reason[MAX_MSG];\n\tchar name[RSN_BUF];\n\n\tint opt;\n\tstatic struct l_option long_opts[] = {\n\t\t{ \"ban\", NO_ARG, 'b' },\n\t\t{ \"help\", NO_ARG, 'h' },\n\t\t{ \"length\", REQ_ARG, 'l' },\n\t\t{ \"timeout\", NO_ARG, 't' },\n\t\t{ 0, 0, 0 }\n\t};\n\n\tif (!P_ALMOD(c->privileges)) {\n\t\tPERM_DENIED(out, c->nick, c->argv[0]);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\topt_init();\n\taction = lenflag = 0;\n\tlen = 300;\n\twhile ((opt = l_getopt_long(c->argc, c->argv, \"bl:t\", long_opts))\n\t\t\t!= EOF) {\n\t\tswitch (opt) {\n\t\tcase 'b':\n\t\t\tif (action) {\n\t\t\t\t_sprintf(out, MAX_MSG, \"%s: cannot both timeout\"\n\t\t\t\t\t\t\" and ban\", c->argv[0]);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\taction = BAN;\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\tHELPMSG(out, CMDNAME, CMDUSAGE, CMDDESCR);\n\t\t\treturn EXIT_SUCCESS;\n\t\tcase 'l':\n\t\t\tif (!parsenum(l_optarg, &len)) {\n\t\t\t\t_sprintf(out, MAX_MSG, \"%s: invalid number: %s\",\n\t\t\t\t\t\tc->argv[0], l_optarg);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\tif (len < 0) {\n\t\t\t\t_sprintf(out, MAX_MSG, \"%s: length cannot be \"\n\t\t\t\t\t\t\"negative\", c->argv[0]);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\tlenflag = 1;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tif (action) {\n\t\t\t\t_sprintf(out, MAX_MSG, \"%s: cannot both timeout\"\n\t\t\t\t\t\t\" and ban\", c->argv[0]);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\taction = TIMEOUT;\n\t\t\tbreak;\n\t\tcase '?':\n\t\t\t_sprintf(out, MAX_MSG, \"%s\", l_opterr());\n\t\t\treturn EXIT_FAILURE;\n\t\tdefault:\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\tif (!action || l_optind == c->argc) {\n\t\tUSAGEMSG(out, CMDNAME, CMDUSAGE);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tif (lenflag && action != TIMEOUT) {\n\t\t_sprintf(out, MAX_MSG, \"%s: specifying length doesn't \"\n\t\t\t\t\"make sense for a ban\", c->nick);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/* convert names to lower for lookup *\/\n\ts = name;\n\tt = m_name;\n\twhile ((*s++ = tolower(*t++)))\n\t\t;\n\tfor (s = c->argv[l_optind]; *s; ++s)\n\t\t*s = tolower(*s);\n\n\tif (strcmp(c->argv[l_optind], name) == 0) {\n\t\t_sprintf(out, MAX_MSG, \"@%s, I'd rather not.\", c->nick);\n\t\treturn EXIT_SUCCESS;\n\t}\n\tif (strcmp(c->argv[l_optind], c->nick) == 0) {\n\t\t_sprintf(out, MAX_MSG, \"@%s, don't be silly!\", c->nick);\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\targvcat(reason, c->argc, c->argv, l_optind + 1, 1);\n\t\/* attempt to perform the moderation action *\/\n\tif (!m_modp->mod_action(action, c->argv[l_optind],\n\t\t\t\tc->nick, reason, len)) {\n\t\t_sprintf(out, MAX_MSG, \"%s: user '%s' is not currently in the \"\n\t\t\t\t\"channel\", c->argv[0], c->argv[l_optind]);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t_sprintf(out, MAX_MSG, \"@%s, user '%s' has been %s\",\n\t\t\tc->nick, c->argv[l_optind],\n\t\t\taction == BAN ? \"banned\" : \"timed out\");\n\tif (*reason) {\n\t\tstrcat(out, \" for \");\n\t\tstrcat(out, reason);\n\t}\n\tstrcat(out, \".\");\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012, Google Inc.\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:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. 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\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/ Provides an interpreter for assigning primitives and Factory-constructible\n\/\/\/ objects to named variables, as well as vectors thereof.\n\/\/\/ \\author dbikel@google.com (Dan Bikel)\n\n#ifndef RERANKER_INTERPRETER_H_\n#define RERANKER_INTERPRETER_H_\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <tr1\/unordered_map>\n#include <tr1\/unordered_set>\n\n#include \"environment-impl.H\"\n\nnamespace reranker {\n\nusing std::iostream;\nusing std::ifstream;\n\nclass EnvironmentImpl;\n\n\/\/\/ Provides an interpreter for assigning primitives and\n\/\/\/ Factory-constructible objects to named variables, as well as\n\/\/\/ vectors thereof. The interpreter maintains an internal\n\/\/\/ environment whereby previously defined variables may be used in\n\/\/\/ the definition of subsequent ones.\n\/\/\/\n\/\/\/ The syntax of this language extends the syntax\n\/\/\/ of the \\link reranker::Factory Factory \\endlink class, described\n\/\/\/ in the documentation of the \\link reranker::Factory::CreateOrDie\n\/\/\/ Factory::CreateOrDie \\endlink method.\n\/\/\/\n\/\/\/ Statements in this language look like the following:\n\/\/\/ \\code\n\/\/\/ \/\/ This is a comment.\n\/\/\/ b = true; \/\/ assigns the value true to the boolean variable named \"b\"\n\/\/\/ f = 1; \/\/ assigns the int value 1 to the variable \"f\"\n\/\/\/ g = 2.4; \/\/ assigns the double value 2.4 to the variable \"g\"\n\/\/\/ n = \"foo\"; \/\/ assigns the string value \"foo\" to the variable \"n\"\n\/\/\/ b_vec = {true, false, true}; \/\/ assigns a vector of bool to \"b_vec\"\n\/\/\/\n\/\/\/ \/\/ Constructs an object of abstract type Model and assigns it to \"m1\"\n\/\/\/ m1 = PerceptronModel(name(\"foo\"));\n\/\/\/\n\/\/\/ \/\/ Constructs an object of type Model and assigns it to \"m2\", crucially\n\/\/\/ \/\/ using the previously defined string variable \"n\" as the value for\n\/\/\/ \/\/ the PerceptronModel's name parameter.\n\/\/\/ m2 = PerceptronModel(name(n));\n\/\/\/\n\/\/\/ \/\/ Constructs a vector of Model objects and assigns it to \"m_vec\".\n\/\/\/ m_vec = {m2, PerceptronModel(name(\"bar\"))};\n\/\/\/ \\endcode\n\/\/\/\n\/\/\/ More formally, a statement in this language must conform to the\n\/\/\/ following grammar, defined on top of the BNF syntax in the\n\/\/\/ documentation of the \\link reranker::Factory::CreateOrDie\n\/\/\/ Factory::CreateOrDie \\endlink method:\n\/\/\/ <table border=0>\n\/\/\/ <tr>\n\/\/\/ <td><tt>\\<statement_list\\><\/tt><\/td>\n\/\/\/ <td><tt>::=<\/tt><\/td>\n\/\/\/ <td><tt>[ \\<statement\\> ]*<\/tt><\/td>\n\/\/\/ <\/tr>\n\/\/\/ <tr>\n\/\/\/ <td><tt>\\<statement\\><\/tt><\/td>\n\/\/\/ <td><tt>::=<\/tt><\/td>\n\/\/\/ <td><tt>\\<variable_name\\> '=' \\<value\\> ';' <\/tt><\/td>\n\/\/\/ <\/tr>\n\/\/\/ <tr>\n\/\/\/ <td><tt>\\<variable_name\\><\/tt><\/td>\n\/\/\/ <td><tt>::=<\/tt><\/td>\n\/\/\/ <td>any valid C++ identifier<\/td>\n\/\/\/ <\/tr>\n\/\/\/ <tr>\n\/\/\/ <td valign=top><tt>\\<value\\><\/tt><\/td>\n\/\/\/ <td valign=top><tt>::=<\/tt><\/td>\n\/\/\/ <td valign=top><tt>\\<literal\\> | '{' \\<literal_list\\> '}' |<br>\n\/\/\/ \\<spec\\> | '{' \\<spec_list\\> '}'<\/tt>\n\/\/\/ <\/td>\n\/\/\/ <\/tr>\n\/\/\/ <\/table>\n\/\/\/\n\/\/\/ The above grammar doesn’t contain rules covering C++ style\n\/\/\/ line comments, but they have the same behavior in this language as\n\/\/\/ they do in C++, i.e., everything after the <tt>\/\/<\/tt> to the end\n\/\/\/ of the current line is treated as a comment and ignored. There\n\/\/\/ are no C-style comments in this language.\nclass Interpreter {\n public:\n \/\/\/ Constructs a new instance with the specified debug level. The\n \/\/\/ wrapped \\link reranker::Environment Environment \\endlink will\n \/\/\/ also have the specified debug level.\n Interpreter(int debug = 0) : debug_(debug) {\n env_ = new EnvironmentImpl(debug);\n }\n\n \/\/\/ Destroys this interpreter.\n virtual ~Interpreter() {\n delete env_;\n }\n\n \/\/\/ Evaluates the statements in the specified text file.\n void Eval(const string &filename) {\n filename_ = filename;\n ifstream file(filename_.c_str());\n Eval(file);\n }\n\n \/\/\/ Evaluates the statements in the specified string.\n void EvalString(const string& input) {\n StreamTokenizer st(input);\n Eval(st);\n }\n\n \/\/\/ Evaluates the statements in the specified stream.\n void Eval(istream &is) {\n StreamTokenizer st(is);\n Eval(st);\n }\n\n\n void PrintEnv(ostream &os) const {\n env_->Print(os);\n }\n\n \/\/\/ Retrieves the value of the specified variable. It is an error\n \/\/\/ if the type of the specified pointer to a value object is different\n \/\/\/ from the specified variable in this interpreter’s environment.\n \/\/\/\n \/\/\/ \\tparam the type of value object being set by this method\n \/\/\/\n \/\/\/ \\param varname the name of the variable for which to retrieve the value\n \/\/\/ \\param value a pointer to the object whose value to be set by this\n \/\/\/ method\n template<typename T>\n bool Get(const string &varname, T *value) const {\n return env_->Get(varname, value);\n }\n\n \/\/\/ Returns a pointer to the environment of this interpreter.\n \/\/\/ Crucially, this method returns a pointer to the Environment\n \/\/\/ implementation class, \\link reranker::EnvironmentImpl\n \/\/\/ EnvironmentImpl\\endlink, so that its templated \\link\n \/\/\/ reranker::EnvironmentImpl::Get EnvironmentImpl::Get \\endlink\n \/\/\/ method may be invoked.\n EnvironmentImpl *env() { return env_; }\n\n private:\n void Eval(StreamTokenizer &st);\n\n void WrongTokenError(size_t pos,\n const string &expected,\n const string &found,\n StreamTokenizer::TokenType found_type) const;\n\n void WrongTokenTypeError(size_t pos,\n StreamTokenizer::TokenType expected,\n StreamTokenizer::TokenType found,\n const string &token) const;\n\n \/\/\/ The environment of this interpreter.\n EnvironmentImpl *env_;\n\n \/\/\/ The name of the file being interpreted, or the empty string if there\n \/\/\/ is no file associated with the stream being interpreted.\n string filename_;\n\n \/\/\/ The debug level of this interpreter and its associated environment.\n int debug_;\n};\n\n} \/\/ namespace reranker\n\n#endif\n<commit_msg>Another tiny edit to the documentation of the Interpreter class.<commit_after>\/\/ Copyright 2012, Google Inc.\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:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. 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\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/ Provides an interpreter for assigning primitives and Factory-constructible\n\/\/\/ objects to named variables, as well as vectors thereof.\n\/\/\/ \\author dbikel@google.com (Dan Bikel)\n\n#ifndef RERANKER_INTERPRETER_H_\n#define RERANKER_INTERPRETER_H_\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <tr1\/unordered_map>\n#include <tr1\/unordered_set>\n\n#include \"environment-impl.H\"\n\nnamespace reranker {\n\nusing std::iostream;\nusing std::ifstream;\n\nclass EnvironmentImpl;\n\n\/\/\/ Provides an interpreter for assigning primitives and\n\/\/\/ Factory-constructible objects to named variables, as well as\n\/\/\/ vectors thereof. The interpreter maintains an internal\n\/\/\/ environment whereby previously defined variables may be used in\n\/\/\/ the definition of subsequent ones. The syntax of this language\n\/\/\/ extends the syntax of the \\link reranker::Factory Factory \\endlink\n\/\/\/ class, described in the documentation of the \\link\n\/\/\/ reranker::Factory::CreateOrDie Factory::CreateOrDie \\endlink\n\/\/\/ method.\n\/\/\/\n\/\/\/ Statements in this language look like the following:\n\/\/\/ \\code\n\/\/\/ \/\/ This is a comment.\n\/\/\/ b = true; \/\/ assigns the value true to the boolean variable named \"b\"\n\/\/\/ f = 1; \/\/ assigns the int value 1 to the variable \"f\"\n\/\/\/ g = 2.4; \/\/ assigns the double value 2.4 to the variable \"g\"\n\/\/\/ n = \"foo\"; \/\/ assigns the string value \"foo\" to the variable \"n\"\n\/\/\/ b_vec = {true, false, true}; \/\/ assigns a vector of bool to \"b_vec\"\n\/\/\/\n\/\/\/ \/\/ Constructs an object of abstract type Model and assigns it to \"m1\"\n\/\/\/ m1 = PerceptronModel(name(\"foo\"));\n\/\/\/\n\/\/\/ \/\/ Constructs an object of type Model and assigns it to \"m2\", crucially\n\/\/\/ \/\/ using the previously defined string variable \"n\" as the value for\n\/\/\/ \/\/ the PerceptronModel's name parameter.\n\/\/\/ m2 = PerceptronModel(name(n));\n\/\/\/\n\/\/\/ \/\/ Constructs a vector of Model objects and assigns it to \"m_vec\".\n\/\/\/ m_vec = {m2, PerceptronModel(name(\"bar\"))};\n\/\/\/ \\endcode\n\/\/\/\n\/\/\/ More formally, a statement in this language must conform to the\n\/\/\/ following grammar, defined on top of the BNF syntax in the\n\/\/\/ documentation of the \\link reranker::Factory::CreateOrDie\n\/\/\/ Factory::CreateOrDie \\endlink method:\n\/\/\/ <table border=0>\n\/\/\/ <tr>\n\/\/\/ <td><tt>\\<statement_list\\><\/tt><\/td>\n\/\/\/ <td><tt>::=<\/tt><\/td>\n\/\/\/ <td><tt>[ \\<statement\\> ]*<\/tt><\/td>\n\/\/\/ <\/tr>\n\/\/\/ <tr>\n\/\/\/ <td><tt>\\<statement\\><\/tt><\/td>\n\/\/\/ <td><tt>::=<\/tt><\/td>\n\/\/\/ <td><tt>\\<variable_name\\> '=' \\<value\\> ';' <\/tt><\/td>\n\/\/\/ <\/tr>\n\/\/\/ <tr>\n\/\/\/ <td><tt>\\<variable_name\\><\/tt><\/td>\n\/\/\/ <td><tt>::=<\/tt><\/td>\n\/\/\/ <td>any valid C++ identifier<\/td>\n\/\/\/ <\/tr>\n\/\/\/ <tr>\n\/\/\/ <td valign=top><tt>\\<value\\><\/tt><\/td>\n\/\/\/ <td valign=top><tt>::=<\/tt><\/td>\n\/\/\/ <td valign=top><tt>\\<literal\\> | '{' \\<literal_list\\> '}' |<br>\n\/\/\/ \\<spec\\> | '{' \\<spec_list\\> '}'<\/tt>\n\/\/\/ <\/td>\n\/\/\/ <\/tr>\n\/\/\/ <\/table>\n\/\/\/\n\/\/\/ The above grammar doesn’t contain rules covering C++ style\n\/\/\/ line comments, but they have the same behavior in this language as\n\/\/\/ they do in C++, i.e., everything after the <tt>\/\/<\/tt> to the end\n\/\/\/ of the current line is treated as a comment and ignored. There\n\/\/\/ are no C-style comments in this language.\nclass Interpreter {\n public:\n \/\/\/ Constructs a new instance with the specified debug level. The\n \/\/\/ wrapped \\link reranker::Environment Environment \\endlink will\n \/\/\/ also have the specified debug level.\n Interpreter(int debug = 0) : debug_(debug) {\n env_ = new EnvironmentImpl(debug);\n }\n\n \/\/\/ Destroys this interpreter.\n virtual ~Interpreter() {\n delete env_;\n }\n\n \/\/\/ Evaluates the statements in the specified text file.\n void Eval(const string &filename) {\n filename_ = filename;\n ifstream file(filename_.c_str());\n Eval(file);\n }\n\n \/\/\/ Evaluates the statements in the specified string.\n void EvalString(const string& input) {\n StreamTokenizer st(input);\n Eval(st);\n }\n\n \/\/\/ Evaluates the statements in the specified stream.\n void Eval(istream &is) {\n StreamTokenizer st(is);\n Eval(st);\n }\n\n\n void PrintEnv(ostream &os) const {\n env_->Print(os);\n }\n\n \/\/\/ Retrieves the value of the specified variable. It is an error\n \/\/\/ if the type of the specified pointer to a value object is different\n \/\/\/ from the specified variable in this interpreter’s environment.\n \/\/\/\n \/\/\/ \\tparam the type of value object being set by this method\n \/\/\/\n \/\/\/ \\param varname the name of the variable for which to retrieve the value\n \/\/\/ \\param value a pointer to the object whose value to be set by this\n \/\/\/ method\n template<typename T>\n bool Get(const string &varname, T *value) const {\n return env_->Get(varname, value);\n }\n\n \/\/\/ Returns a pointer to the environment of this interpreter.\n \/\/\/ Crucially, this method returns a pointer to the Environment\n \/\/\/ implementation class, \\link reranker::EnvironmentImpl\n \/\/\/ EnvironmentImpl\\endlink, so that its templated \\link\n \/\/\/ reranker::EnvironmentImpl::Get EnvironmentImpl::Get \\endlink\n \/\/\/ method may be invoked.\n EnvironmentImpl *env() { return env_; }\n\n private:\n void Eval(StreamTokenizer &st);\n\n void WrongTokenError(size_t pos,\n const string &expected,\n const string &found,\n StreamTokenizer::TokenType found_type) const;\n\n void WrongTokenTypeError(size_t pos,\n StreamTokenizer::TokenType expected,\n StreamTokenizer::TokenType found,\n const string &token) const;\n\n \/\/\/ The environment of this interpreter.\n EnvironmentImpl *env_;\n\n \/\/\/ The name of the file being interpreted, or the empty string if there\n \/\/\/ is no file associated with the stream being interpreted.\n string filename_;\n\n \/\/\/ The debug level of this interpreter and its associated environment.\n int debug_;\n};\n\n} \/\/ namespace reranker\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n\n#define ELPP_DISABLE_DEFAULT_CRASH_HANDLING 1\n#define ELPP_DEFAULT_LOG_FILE \"logs\/swgchat.log\"\n\n#include \"easylogging++.h\"\n\n#include \"StationChatApp.hpp\"\n\n#include <boost\/program_options.hpp>\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <thread>\n\n#ifdef __GNUC__\n#include <execinfo.h>\n#endif\n\nINITIALIZE_EASYLOGGINGPP\n\nStationChatConfig BuildConfiguration(int argc, const char* argv[]);\n\n#ifdef __GNUC__\nvoid SignalHandler(int sig);\n#endif\n\nint main(int argc, const char* argv[]) {\n#ifdef __GNUC__\n signal(SIGSEGV, SignalHandler);\n#endif\n\n auto config = BuildConfiguration(argc, argv);\n\n el::Loggers::setDefaultConfigurations(config.loggerConfig, true);\n START_EASYLOGGINGPP(argc, argv);\n\n StationChatApp app{config};\n\n while (app.IsRunning()) {\n app.Tick();\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n }\n\n return 0;\n}\n\nStationChatConfig BuildConfiguration(int argc, const char* argv[]) {\n namespace po = boost::program_options;\n StationChatConfig config;\n std::string configFile;\n\n \/\/ Declare a group of options that will be \n \/\/ allowed only on command line\n po::options_description generic(\"Generic options\");\n generic.add_options()\n (\"help,h\", \"produces help message\")\n (\"config,c\", po::value<std::string>(&configFile)->default_value(\"etc\/stationapi\/swgchat.cfg\"),\n \"sets path to the configuration file\")\n (\"logger_config\", po::value<std::string>(&config.loggerConfig)->default_value(\"etc\/stationapi\/logger.cfg\"),\n \"sets path to the logger configuration file\")\n ;\n\n po::options_description options(\"Configuration\");\n options.add_options()\n (\"gateway_address\", po::value<std::string>(&config.gatewayAddress)->default_value(\"127.0.0.1\"),\n \"address for gateway connections\")\n (\"gateway_port\", po::value<uint16_t>(&config.gatewayPort)->default_value(5001),\n \"port for gateway connections\")\n (\"registrar_address\", po::value<std::string>(&config.registrarAddress)->default_value(\"127.0.0.1\"),\n \"address for registrar connections\")\n (\"registrar_port\", po::value<uint16_t>(&config.registrarPort)->default_value(5000),\n \"port for registrar connections\")\n (\"bind_to_ip\", po::value<bool>(&config.bindToIp)->default_value(false),\n \"when set to true, binds to the config address; otherwise, binds on any interface\")\n (\"database_path\", po::value<std::string>(&config.chatDatabasePath)->default_value(\"var\/stationapi\/stationchat.db\"),\n \"path to the sqlite3 database file\")\n ;\n\n po::options_description cmdline_options;\n cmdline_options.add(generic).add(options);\n\n po::options_description config_file_options;\n config_file_options.add(options);\n\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(cmdline_options).allow_unregistered().run(), vm);\n po::notify(vm);\n\n std::ifstream ifs(configFile.c_str());\n if (!ifs) {\n throw std::runtime_error(\"Cannot open configuration file: \" + configFile);\n }\n\n po::store(po::parse_config_file(ifs, config_file_options), vm);\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << cmdline_options << \"\\n\";\n exit(EXIT_SUCCESS);\n }\n\n return config;\n}\n\n#ifdef __GNUC__\nvoid SignalHandler(int sig) {\n const int BACKTRACE_LIMIT = 10;\n void *arr[BACKTRACE_LIMIT];\n auto size = backtrace(arr, BACKTRACE_LIMIT);\n\n fprintf(stderr, \"Error: signal %d:\\n\", sig);\n backtrace_symbols_fd(arr, size, STDERR_FILENO);\n exit(1);\n}\n#endif\n<commit_msg>Disable the default log file<commit_after>\n\n#define ELPP_DISABLE_DEFAULT_CRASH_HANDLING 1\n#define ELPP_NO_DEFAULT_LOG_FILE\n\n#include \"easylogging++.h\"\n\n#include \"StationChatApp.hpp\"\n\n#include <boost\/program_options.hpp>\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <thread>\n\n#ifdef __GNUC__\n#include <execinfo.h>\n#endif\n\nINITIALIZE_EASYLOGGINGPP\n\nStationChatConfig BuildConfiguration(int argc, const char* argv[]);\n\n#ifdef __GNUC__\nvoid SignalHandler(int sig);\n#endif\n\nint main(int argc, const char* argv[]) {\n#ifdef __GNUC__\n signal(SIGSEGV, SignalHandler);\n#endif\n\n auto config = BuildConfiguration(argc, argv);\n\n el::Loggers::setDefaultConfigurations(config.loggerConfig, true);\n START_EASYLOGGINGPP(argc, argv);\n\n StationChatApp app{config};\n\n while (app.IsRunning()) {\n app.Tick();\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n }\n\n return 0;\n}\n\nStationChatConfig BuildConfiguration(int argc, const char* argv[]) {\n namespace po = boost::program_options;\n StationChatConfig config;\n std::string configFile;\n\n \/\/ Declare a group of options that will be \n \/\/ allowed only on command line\n po::options_description generic(\"Generic options\");\n generic.add_options()\n (\"help,h\", \"produces help message\")\n (\"config,c\", po::value<std::string>(&configFile)->default_value(\"etc\/stationapi\/swgchat.cfg\"),\n \"sets path to the configuration file\")\n (\"logger_config\", po::value<std::string>(&config.loggerConfig)->default_value(\"etc\/stationapi\/logger.cfg\"),\n \"sets path to the logger configuration file\")\n ;\n\n po::options_description options(\"Configuration\");\n options.add_options()\n (\"gateway_address\", po::value<std::string>(&config.gatewayAddress)->default_value(\"127.0.0.1\"),\n \"address for gateway connections\")\n (\"gateway_port\", po::value<uint16_t>(&config.gatewayPort)->default_value(5001),\n \"port for gateway connections\")\n (\"registrar_address\", po::value<std::string>(&config.registrarAddress)->default_value(\"127.0.0.1\"),\n \"address for registrar connections\")\n (\"registrar_port\", po::value<uint16_t>(&config.registrarPort)->default_value(5000),\n \"port for registrar connections\")\n (\"bind_to_ip\", po::value<bool>(&config.bindToIp)->default_value(false),\n \"when set to true, binds to the config address; otherwise, binds on any interface\")\n (\"database_path\", po::value<std::string>(&config.chatDatabasePath)->default_value(\"var\/stationapi\/stationchat.db\"),\n \"path to the sqlite3 database file\")\n ;\n\n po::options_description cmdline_options;\n cmdline_options.add(generic).add(options);\n\n po::options_description config_file_options;\n config_file_options.add(options);\n\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(cmdline_options).allow_unregistered().run(), vm);\n po::notify(vm);\n\n std::ifstream ifs(configFile.c_str());\n if (!ifs) {\n throw std::runtime_error(\"Cannot open configuration file: \" + configFile);\n }\n\n po::store(po::parse_config_file(ifs, config_file_options), vm);\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << cmdline_options << \"\\n\";\n exit(EXIT_SUCCESS);\n }\n\n return config;\n}\n\n#ifdef __GNUC__\nvoid SignalHandler(int sig) {\n const int BACKTRACE_LIMIT = 10;\n void *arr[BACKTRACE_LIMIT];\n auto size = backtrace(arr, BACKTRACE_LIMIT);\n\n fprintf(stderr, \"Error: signal %d:\\n\", sig);\n backtrace_symbols_fd(arr, size, STDERR_FILENO);\n exit(1);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The Bitcoin Core developers\n\/\/ Copyright (c) 2019-2020 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"base58.h\"\n#include \"key.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n#include \"test\/test_bitcoin.h\"\n\n#include <string>\n#include <vector>\n\nstruct TestDerivation {\n std::string pub;\n std::string prv;\n unsigned int nChild;\n};\n\nstruct TestVector {\n std::string strHexMaster;\n std::vector<TestDerivation> vDerive;\n\n TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {}\n\n TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) {\n vDerive.emplace_back();\n TestDerivation &der = vDerive.back();\n der.pub = pub;\n der.prv = prv;\n der.nChild = nChild;\n return *this;\n }\n};\n\nTestVector test1 =\n TestVector(\"000102030405060708090a0b0c0d0e0f\")\n (\"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8\",\n \"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi\",\n 0x80000000)\n (\"xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw\",\n \"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7\",\n 1)\n (\"xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ\",\n \"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs\",\n 0x80000002)\n (\"xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5\",\n \"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM\",\n 2)\n (\"xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV\",\n \"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334\",\n 1000000000)\n (\"xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy\",\n \"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76\",\n 0);\n\nTestVector test2 =\n TestVector(\"fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542\")\n (\"xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB\",\n \"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U\",\n 0)\n (\"xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH\",\n \"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt\",\n 0xFFFFFFFF)\n (\"xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a\",\n \"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9\",\n 1)\n (\"xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon\",\n \"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef\",\n 0xFFFFFFFE)\n (\"xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL\",\n \"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc\",\n 2)\n (\"xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt\",\n \"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j\",\n 0);\n\nvoid RunTest(const TestVector &test) {\n std::vector<unsigned char> seed = ParseHex(test.strHexMaster);\n CExtKey key;\n CExtPubKey pubkey;\n key.SetSeed(&seed[0], seed.size());\n pubkey = key.Neuter();\n for (const TestDerivation &derive : test.vDerive) {\n unsigned char data[74];\n key.Encode(data);\n pubkey.Encode(data);\n \/\/ Test private key\n CBitcoinExtKey b58key; b58key.SetKey(key);\n BOOST_CHECK(b58key.ToString() == derive.prv);\n\n CBitcoinExtKey b58keyDecodeCheck(derive.prv);\n CExtKey checkKey = b58keyDecodeCheck.GetKey();\n assert(checkKey == key); \/\/ensure a base58 decoded key also matches\n\n \/\/ Test public key\n CBitcoinExtPubKey b58pubkey; b58pubkey.SetKey(pubkey);\n BOOST_CHECK(b58pubkey.ToString() == derive.pub);\n\n CBitcoinExtPubKey b58PubkeyDecodeCheck(derive.pub);\n CExtPubKey checkPubKey = b58PubkeyDecodeCheck.GetKey();\n assert(checkPubKey == pubkey); \/\/ensure a base58 decoded pubkey also matches\n\n \/\/ Derive new keys\n CExtKey keyNew;\n BOOST_CHECK(key.Derive(keyNew, derive.nChild));\n CExtPubKey pubkeyNew = keyNew.Neuter();\n if (!(derive.nChild & 0x80000000)) {\n \/\/ Compare with public derivation\n CExtPubKey pubkeyNew2;\n BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild));\n BOOST_CHECK(pubkeyNew == pubkeyNew2);\n }\n key = keyNew;\n pubkey = pubkeyNew;\n\n CDataStream ssPub(SER_DISK, CLIENT_VERSION);\n ssPub << pubkeyNew;\n BOOST_CHECK(ssPub.size() == 75);\n\n CDataStream ssPriv(SER_DISK, CLIENT_VERSION);\n ssPriv << keyNew;\n BOOST_CHECK(ssPriv.size() == 75);\n\n CExtPubKey pubCheck;\n CExtKey privCheck;\n ssPub >> pubCheck;\n ssPriv >> privCheck;\n\n BOOST_CHECK(pubCheck == pubkeyNew);\n BOOST_CHECK(privCheck == keyNew);\n }\n}\n\nBOOST_FIXTURE_TEST_SUITE(bip32_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(bip32_test1) {\n RunTest(test1);\n}\n\nBOOST_AUTO_TEST_CASE(bip32_test2) {\n RunTest(test2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>bip32_tests updated to latest upstream changes.<commit_after>\/\/ Copyright (c) 2013 The Bitcoin Core developers\n\/\/ Copyright (c) 2019-2020 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"key.h\"\n#include \"key_io.h\"\n#include \"test\/test_pivx.h\"\n\n#include <string>\n#include <vector>\n\nstruct TestDerivation {\n std::string pub;\n std::string prv;\n unsigned int nChild;\n};\n\nstruct TestVector {\n std::string strHexMaster;\n std::vector<TestDerivation> vDerive;\n\n TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {}\n\n TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) {\n vDerive.emplace_back();\n TestDerivation &der = vDerive.back();\n der.pub = pub;\n der.prv = prv;\n der.nChild = nChild;\n return *this;\n }\n};\n\nTestVector test1 =\n TestVector(\"000102030405060708090a0b0c0d0e0f\")\n (\"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8\",\n \"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi\",\n 0x80000000)\n (\"xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw\",\n \"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7\",\n 1)\n (\"xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ\",\n \"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs\",\n 0x80000002)\n (\"xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5\",\n \"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM\",\n 2)\n (\"xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV\",\n \"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334\",\n 1000000000)\n (\"xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy\",\n \"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76\",\n 0);\n\nTestVector test2 =\n TestVector(\"fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542\")\n (\"xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB\",\n \"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U\",\n 0)\n (\"xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH\",\n \"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt\",\n 0xFFFFFFFF)\n (\"xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a\",\n \"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9\",\n 1)\n (\"xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon\",\n \"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef\",\n 0xFFFFFFFE)\n (\"xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL\",\n \"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc\",\n 2)\n (\"xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt\",\n \"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j\",\n 0);\n\nvoid RunTest(const TestVector &test) {\n std::vector<unsigned char> seed = ParseHex(test.strHexMaster);\n CExtKey key;\n CExtPubKey pubkey;\n key.SetSeed(seed.data(), seed.size());\n pubkey = key.Neuter();\n for (const TestDerivation &derive : test.vDerive) {\n unsigned char data[74];\n key.Encode(data);\n pubkey.Encode(data);\n\n \/\/ Test private key\n BOOST_CHECK(KeyIO::EncodeExtKey(key) == derive.prv);\n BOOST_CHECK(KeyIO::DecodeExtKey(derive.prv) == key); \/\/ensure a base58 decoded key also matches\n\n \/\/ Test public key\n BOOST_CHECK(KeyIO::EncodeExtPubKey(pubkey) == derive.pub);\n BOOST_CHECK(KeyIO::DecodeExtPubKey(derive.pub) == pubkey); \/\/ensure a base58 decoded pubkey also matches\n\n \/\/ Derive new keys\n CExtKey keyNew;\n BOOST_CHECK(key.Derive(keyNew, derive.nChild));\n CExtPubKey pubkeyNew = keyNew.Neuter();\n if (!(derive.nChild & 0x80000000)) {\n \/\/ Compare with public derivation\n CExtPubKey pubkeyNew2;\n BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild));\n BOOST_CHECK(pubkeyNew == pubkeyNew2);\n }\n key = keyNew;\n pubkey = pubkeyNew;\n }\n}\n\nBOOST_FIXTURE_TEST_SUITE(bip32_tests, TestingSetup)\n\nBOOST_AUTO_TEST_CASE(bip32_test1) {\n RunTest(test1);\n}\n\nBOOST_AUTO_TEST_CASE(bip32_test2) {\n RunTest(test2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/common\/init.h\"\n#include \"..\/common\/timer.h\"\n\n#include <iostream>\n#include <vector>\n#include <stdexcept>\n\n#include \"util\/graphics\/bitmap.h\"\n#include \"util\/font.h\"\n#include \"util\/debug.h\"\n#include \"util\/exceptions\/load_exception.h\"\n#include \"util\/token_exception.h\"\n#include \"util\/input\/input.h\"\n#include \"util\/input\/input-manager.h\"\n#include \"util\/sound\/sound.h\"\n#include \"util\/exceptions\/exception.h\"\n#include \"util\/network\/network.h\"\n#include \"util\/network\/irc.h\"\n#include \"util\/thread.h\"\n#include \"util\/pointer.h\"\n#include \"util\/system.h\"\n#include \"util\/timedifference.h\"\n#include \"util\/configuration.h\"\n\n#include <queue>\n#include <map>\n\nstatic std::vector<std::string> split(std::string str, char splitter){\n std::vector<std::string> strings;\n size_t next = str.find(splitter);\n while (next != std::string::npos){\n strings.push_back(str.substr(0, next));\n str = str.substr(next+1);\n next = str.find(splitter);\n }\n if (str != \"\"){\n strings.push_back(str);\n }\n\n return strings;\n}\n\nstatic void setTrue(void * b){\n bool * what = (bool*) b;\n *what = true;\n}\n\nstatic void nextTab(void * i){\n ::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;\n interface->nextChannel();\n}\n\nstatic void previousTab(void * i){\n ::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;\n interface->previousChannel();\n}\n\nclass Game{\npublic:\n Game(const std::string & name, bool host = true):\n name(name),\n host(host){\n }\n ~Game(){\n }\n \n void addClient(const std::string & name, const std::string & ip){\n clients[name] = ip;\n }\n \n std::string clientsAsString(){\n std::string clientlist;\n for (std::map<std::string, std::string>::iterator i = clients.begin(); i != clients.end(); i++){\n clientlist += (*i).first + \", \";\n }\n return clientlist.substr(0, clientlist.size() - 2);\n }\n \n void start(const std::string & hostip) {\n Global::debug(0) << \"Game \" << name << \" is starting.\" << std::endl;\n Global::debug(0) << \"Connecting to \" << hostip << \"....\" << std::endl;\n }\n \n std::map<std::string, std::string> & getClients(){\n return clients;\n }\n \n const std::string & getName() const {\n return name;\n }\n \n bool isHost() const {\n return host;\n }\n \nprivate:\n std::string name;\n bool host;\n std::map<std::string, std::string> clients;\n};\n\nclass InputLogicDraw: public Util::Logic, public Util::Draw, public ::Network::IRC::Message::EventInterface {\npublic:\n InputLogicDraw(int port, const std::string & host, const std::string & username):\n chatInterface(host, port, username),\n escaped(false){\n ircClient = Util::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));\n chatInterface.getInputBox().addHook(Keyboard::Key_ESC, setTrue, &escaped);\n chatInterface.getInputBox().addHook(Keyboard::Key_TAB, nextTab, &chatInterface);\n chatInterface.subscribe(this);\n \/\/ Get IP\n chatInterface.getClient()->sendCommand(::Network::IRC::Command::Userhost, chatInterface.getClient()->getName());\n }\n \n ::Network::IRC::ChatInterface chatInterface;\n Util::ReferenceCount< ::Network::IRC::Client > ircClient;\n \n bool escaped;\n \n std::string ipAddress;\n Util::ReferenceCount<Game> game;\n std::map<std::string, std::string> hosts;\n \n void remoteCommand(const ::Network::IRC::Command & command){\n if (command.getType() == ::Network::IRC::Command::ReplyUserhost){\n const std::vector<std::string> & params = command.getParameters();\n const std::string & extract = params.at(1);\n for (unsigned int i = 0; i < extract.size(); i++){\n if (extract[i] == '@'){\n ipAddress = extract.substr(++i, extract.size()-1);\n Global::debug(0) << \"Your IP Address is: \" << ipAddress << std::endl;\n }\n }\n }\n if (command.hasCtcp()){\n const std::vector<std::string> & ctcp = command.getCtcp();\n if (command.getType() == ::Network::IRC::Command::PrivateMessage){\n try {\n if (ctcp.at(0) == \"game\"){\n const std::string & gameCommand = ctcp.at(1);\n if (gameCommand == \"invite\"){\n const std::string & gameName = ctcp.at(2);\n const std::string & hostName = ctcp.at(3);\n chatInterface.addMessageToTab(\"* \" + hostName + \" has invited you to join the game [\" + gameName + \"]. Type \\\"\/game join \" + gameName + \"\\\".\");\n hosts[gameName] = hostName;\n } else if (gameCommand == \"join\"){\n if (game != NULL && game->isHost()){ \n const std::string & gameName = ctcp.at(2);\n const std::string & clientName = ctcp.at(3);\n const std::string & ip = ctcp.at(4);\n chatInterface.addMessageToTab(\"* \" + clientName + \" has joined \" + gameName + \".\");\n game->addClient(clientName, ip);\n } else {\n chatInterface.addMessageToTab(\"* received a join request with no game pending.\");\n }\n } else if (gameCommand == \"start\"){\n if (game != NULL && !game->isHost()){\n const std::string & gameName = ctcp.at(2);\n const std::string & serverIp = ctcp.at(3);\n chatInterface.addMessageToTab(\"* Host has started game \" + gameName);\n game->start(serverIp);\n }\n }\n } else {\n Global::debug(0) << \"Got ctcp: \" << ctcp.at(0) << std::endl;\n }\n } catch (const std::out_of_range & ex){\n }\n }\n }\n }\n \n void localCommand(const std::vector<std::string> & command){\n if (command.at(0) == \"help\"){\n chatInterface.addMessageToTab(\"* commands: lol, game\");\n } else if (command.at(0) == \"lol\"){\n chatInterface.addMessageToTab(\"* You LOLOLOLOLLOLOLOL yourself.\");\n } else if (command.at(0) == \"game\"){\n \/\/ Game\n if (command.size() > 1){\n if (command.at(1) == \"help\"){\n chatInterface.addMessageToTab(\"* game commands: help, new, start, list-users, list-hosts, invite, join.\");\n } else if (command.at(1) == \"new\"){\n try{\n game = Util::ReferenceCount<Game>(new Game(command.at(2)));\n chatInterface.addMessageToTab(\"* game \\\"\" + command.at(2) + \"\\\" created.\");\n } catch (const std::out_of_range & ex){\n chatInterface.addMessageToTab(\"* \/game new [name]\");\n }\n } else if (command.at(1) == \"start\"){\n if (game != NULL && game->isHost()){\n chatInterface.addMessageToTab(\"* Starting game \" + game->getName());\n for (std::map<std::string, std::string>::iterator i = game->getClients().begin(); i != game->getClients().end(); i++){\n chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,\n (*i).first,\n \":\\001game start \" + game->getName() + \" \" + ipAddress + \"\\001\");\n }\n } else {\n chatInterface.addMessageToTab(\"* Create a game first...\");\n }\n } else if (command.at(1) == \"list-users\"){\n if (game != NULL){\n chatInterface.addMessageToTab(\"* Users who accepted game request: \" + game->clientsAsString());\n } else {\n chatInterface.addMessageToTab(\"* Create a game first...\");\n }\n } else if (command.at(1) == \"list-hosts\"){\n if (!hosts.empty()){\n std::string hostlist;\n for (std::map<std::string, std::string>::iterator i = hosts.begin(); i != hosts.end(); i++){\n hostlist += (*i).first + +\" [\" + (*i).second + \"], \";\n }\n chatInterface.addMessageToTab(\"* Hosts and games you've been invited to: \" + hostlist.substr(0, hostlist.size() - 2));\n } else {\n chatInterface.addMessageToTab(\"* You have no invites.\");\n }\n } else if (command.at(1) == \"invite\"){\n if (game != NULL){\n try {\n chatInterface.addMessageToTab(\"* Sending request to \" + command.at(2));\n chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,\n command.at(2),\n \":\\001game invite \" + game->getName() + \" \" + chatInterface.getClient()->getName() + \"\\001\");\n } catch (const std::out_of_range & ex){\n chatInterface.addMessageToTab(\"* \/game invite [username]\");\n }\n } else {\n chatInterface.addMessageToTab(\"* Create a game first...\");\n }\n } else if (command.at(1) == \"join\"){\n if (!hosts.empty()){\n try {\n const std::string & gameName = command.at(2);\n const std::string & hostName = hosts[gameName];\n chatInterface.addMessageToTab(\"* Joining game at \" + gameName);\n chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,\n hostName,\n \":\\001game join \" + gameName + \" \" + chatInterface.getClient()->getName() + \" \" + ipAddress + \"\\001\");\n game = Util::ReferenceCount<Game>(new Game(gameName, false));\n } catch (const std::out_of_range & ex){\n chatInterface.addMessageToTab(\"* \/game join [name]\");\n }\n } else {\n chatInterface.addMessageToTab(\"* You must be invited to a game first...\");\n }\n }\n }\n } else {\n \/\/chatInterface.addMessageToTab(\"* Uknown command.\");\n }\n }\n \n double ticks(double system){\n return system;\n }\n\n void run(){\n try {\n chatInterface.act();\n } catch (const Exception::Return & ex){\n escaped = true;\n throw ex;\n }\n }\n\n bool done(){\n return escaped;\n }\n \n void draw(const Graphics::Bitmap & screen){\n chatInterface.draw(screen);\n }\n};\n\nstatic void doIrc(const std::string & host, int port, const std::string & username){\n InputLogicDraw client(port, host, username);\n Util::standardLoop(client, client);\n}\n\nstatic void arguments(const std::string & application, int status){\n std::cout << \"Usage: .\/\" << application << \" port host [username]\" << std::endl;\n exit(status);\n}\n\nint main(int argc, char ** argv){\n if (argc >= 2){\n int port = atoi(argv[1]);\n std::string hostname = argv[2];\n std::string username = \"paintown-test\";\n if (argc > 3){\n username = argv[3];\n }\n \n Screen::realInit(Configuration::getScreenWidth(), Configuration::getScreenHeight());\n atexit(Screen::realFinish);\n Common::startTimers();\n \n Sound::initialize();\n \n Global::setDebug(2);\n \n Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, Graphics::getScreenBuffer());\n Keyboard::pushRepeatState(true);\n \n InputManager manager;\n \n Util::Parameter<Util::ReferenceCount<Path::RelativePath> > \n defaultFont(Font::defaultFont, Util::ReferenceCount<Path::RelativePath>(new Path::RelativePath(\"fonts\/arial.ttf\")));\n \n Network::init();\n \n try {\n doIrc(hostname, port, username);\n } catch (const Exception::Return & ex){\n } catch (const Network::NetworkException & ex){\n Global::debug(0) << \"Network Exception: \" << ex.getMessage() << std::endl;\n }\n Network::shutdown();\n } else {\n arguments(argv[0],0);\n }\n return 0;\n}\n#ifdef USE_ALLEGRO\nEND_OF_MAIN()\n#endif\n<commit_msg>[util] Make irc game test clients connect to game server and send hello.<commit_after>#include \"..\/common\/init.h\"\n#include \"..\/common\/timer.h\"\n\n#include <iostream>\n#include <vector>\n#include <stdexcept>\n\n#include \"util\/graphics\/bitmap.h\"\n#include \"util\/font.h\"\n#include \"util\/debug.h\"\n#include \"util\/exceptions\/load_exception.h\"\n#include \"util\/token_exception.h\"\n#include \"util\/input\/input.h\"\n#include \"util\/input\/input-manager.h\"\n#include \"util\/sound\/sound.h\"\n#include \"util\/exceptions\/exception.h\"\n#include \"util\/network\/chat.h\"\n#include \"util\/network\/network.h\"\n#include \"util\/network\/irc.h\"\n#include \"util\/thread.h\"\n#include \"util\/pointer.h\"\n#include \"util\/system.h\"\n#include \"util\/timedifference.h\"\n#include \"util\/configuration.h\"\n\n#include <queue>\n#include <map>\n\nstatic std::vector<std::string> split(std::string str, char splitter){\n std::vector<std::string> strings;\n size_t next = str.find(splitter);\n while (next != std::string::npos){\n strings.push_back(str.substr(0, next));\n str = str.substr(next+1);\n next = str.find(splitter);\n }\n if (str != \"\"){\n strings.push_back(str);\n }\n\n return strings;\n}\n\nstatic void setTrue(void * b){\n bool * what = (bool*) b;\n *what = true;\n}\n\nstatic void nextTab(void * i){\n ::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;\n interface->nextChannel();\n}\n\nstatic void previousTab(void * i){\n ::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;\n interface->previousChannel();\n}\n\nclass Game{\npublic:\n Game(const std::string & name, bool host = true):\n name(name),\n host(host){\n }\n ~Game(){\n }\n \n void addClient(const std::string & name, const std::string & ip){\n clients[name] = ip;\n }\n \n std::string clientsAsString(){\n std::string clientlist;\n for (std::map<std::string, std::string>::iterator i = clients.begin(); i != clients.end(); i++){\n clientlist += (*i).first + \", \";\n }\n return clientlist.substr(0, clientlist.size() - 2);\n }\n \n void start(const std::string & ip, const std::string & hostip) {\n \/\/ TODO move to a thread, otherwise the server is going to hang...\n int port = 9991;\n if (isHost()){\n Global::debug(0) << \"Game \" << name << \" is starting.\" << std::endl;\n Global::debug(0) << \"Starting server on port \" << port << \"....\" << std::endl;\n ::Network::Chat::Server server(port);\n server.start();\n \/\/ Wait for all clients to send a message\n unsigned int allReceived = 0;\n while (allReceived < clients.size()){\n server.poll();\n while (server.hasMessages()){\n ::Network::Chat::Message message = server.nextMessage();\n std::map<std::string, std::string>::iterator check = clients.find(message.getName());\n if (check != clients.end()){\n Global::debug(0) << \"Message Received: \" << message.getMessage() << std::endl;\n allReceived++;\n }\n }\n }\n Global::debug(0) << \"Received all messages. Shutting down.\" << std::endl;\n server.shutdown();\n } else {\n Global::debug(0) << \"Game \" << name << \" is starting.\" << std::endl;\n Global::debug(0) << \"Connecting to \" << hostip << \"....\" << std::endl;\n Network::Socket socket = Network::connectReliable(hostip, port);\n Global::debug(0) << \"Connected\" << std::endl;\n ::Network::Chat::Client client(0, socket);\n client.start();\n ::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, ip, \"Hello from: \" + ip); \n client.sendMessage(ourMessage);\n Global::debug(0) << \"Message sent. Shutting down.\" << std::endl;\n client.shutdown();\n }\n }\n \n std::map<std::string, std::string> & getClients(){\n return clients;\n }\n \n const std::string & getName() const {\n return name;\n }\n \n bool isHost() const {\n return host;\n }\n \nprivate:\n std::string name;\n bool host;\n std::map<std::string, std::string> clients;\n};\n\nclass InputLogicDraw: public Util::Logic, public Util::Draw, public ::Network::IRC::Message::EventInterface {\npublic:\n InputLogicDraw(int port, const std::string & host, const std::string & username):\n chatInterface(host, port, username),\n escaped(false){\n ircClient = Util::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));\n chatInterface.getInputBox().addHook(Keyboard::Key_ESC, setTrue, &escaped);\n chatInterface.getInputBox().addHook(Keyboard::Key_TAB, nextTab, &chatInterface);\n chatInterface.subscribe(this);\n \/\/ Get IP\n chatInterface.getClient()->sendCommand(::Network::IRC::Command::Userhost, chatInterface.getClient()->getName());\n }\n \n ::Network::IRC::ChatInterface chatInterface;\n Util::ReferenceCount< ::Network::IRC::Client > ircClient;\n \n bool escaped;\n \n std::string ipAddress;\n Util::ReferenceCount<Game> game;\n std::map<std::string, std::string> hosts;\n \n void remoteCommand(const ::Network::IRC::Command & command){\n if (command.getType() == ::Network::IRC::Command::ReplyUserhost){\n const std::vector<std::string> & params = command.getParameters();\n const std::string & extract = params.at(1);\n for (unsigned int i = 0; i < extract.size(); i++){\n if (extract[i] == '@'){\n ipAddress = extract.substr(++i, extract.size()-1);\n Global::debug(0) << \"Your IP Address is: \" << ipAddress << std::endl;\n }\n }\n }\n if (command.hasCtcp()){\n const std::vector<std::string> & ctcp = command.getCtcp();\n if (command.getType() == ::Network::IRC::Command::PrivateMessage){\n try {\n if (ctcp.at(0) == \"game\"){\n const std::string & gameCommand = ctcp.at(1);\n if (gameCommand == \"invite\"){\n const std::string & gameName = ctcp.at(2);\n const std::string & hostName = ctcp.at(3);\n chatInterface.addMessageToTab(\"* \" + hostName + \" has invited you to join the game [\" + gameName + \"]. Type \\\"\/game join \" + gameName + \"\\\".\");\n hosts[gameName] = hostName;\n } else if (gameCommand == \"join\"){\n if (game != NULL && game->isHost()){ \n const std::string & gameName = ctcp.at(2);\n const std::string & clientName = ctcp.at(3);\n const std::string & ip = ctcp.at(4);\n chatInterface.addMessageToTab(\"* \" + clientName + \" has joined \" + gameName + \".\");\n game->addClient(clientName, ip);\n } else {\n chatInterface.addMessageToTab(\"* received a join request with no game pending.\");\n }\n } else if (gameCommand == \"start\"){\n if (game != NULL && !game->isHost()){\n const std::string & gameName = ctcp.at(2);\n const std::string & serverIp = ctcp.at(3);\n chatInterface.addMessageToTab(\"* Host has started game \" + gameName);\n game->start(ipAddress, serverIp);\n }\n }\n } else {\n Global::debug(0) << \"Got ctcp: \" << ctcp.at(0) << std::endl;\n }\n } catch (const std::out_of_range & ex){\n }\n }\n }\n }\n \n void localCommand(const std::vector<std::string> & command){\n if (command.at(0) == \"help\"){\n chatInterface.addMessageToTab(\"* commands: lol, game\");\n } else if (command.at(0) == \"lol\"){\n chatInterface.addMessageToTab(\"* You LOLOLOLOLLOLOLOL yourself.\");\n } else if (command.at(0) == \"game\"){\n \/\/ Game\n if (command.size() > 1){\n if (command.at(1) == \"help\"){\n chatInterface.addMessageToTab(\"* game commands: help, new, start, list-users, list-hosts, invite, join.\");\n } else if (command.at(1) == \"new\"){\n try{\n game = Util::ReferenceCount<Game>(new Game(command.at(2)));\n chatInterface.addMessageToTab(\"* game \\\"\" + command.at(2) + \"\\\" created.\");\n } catch (const std::out_of_range & ex){\n chatInterface.addMessageToTab(\"* \/game new [name]\");\n }\n } else if (command.at(1) == \"start\"){\n if (game != NULL && game->isHost()){\n chatInterface.addMessageToTab(\"* Starting game \" + game->getName());\n game->start(ipAddress, ipAddress);\n for (std::map<std::string, std::string>::iterator i = game->getClients().begin(); i != game->getClients().end(); i++){\n chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,\n (*i).first,\n \":\\001game start \" + game->getName() + \" \" + ipAddress + \"\\001\");\n }\n } else {\n chatInterface.addMessageToTab(\"* Create a game first...\");\n }\n } else if (command.at(1) == \"list-users\"){\n if (game != NULL){\n chatInterface.addMessageToTab(\"* Users who accepted game request: \" + game->clientsAsString());\n } else {\n chatInterface.addMessageToTab(\"* Create a game first...\");\n }\n } else if (command.at(1) == \"list-hosts\"){\n if (!hosts.empty()){\n std::string hostlist;\n for (std::map<std::string, std::string>::iterator i = hosts.begin(); i != hosts.end(); i++){\n hostlist += (*i).first + +\" [\" + (*i).second + \"], \";\n }\n chatInterface.addMessageToTab(\"* Hosts and games you've been invited to: \" + hostlist.substr(0, hostlist.size() - 2));\n } else {\n chatInterface.addMessageToTab(\"* You have no invites.\");\n }\n } else if (command.at(1) == \"invite\"){\n if (game != NULL){\n try {\n chatInterface.addMessageToTab(\"* Sending request to \" + command.at(2));\n chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,\n command.at(2),\n \":\\001game invite \" + game->getName() + \" \" + chatInterface.getClient()->getName() + \"\\001\");\n } catch (const std::out_of_range & ex){\n chatInterface.addMessageToTab(\"* \/game invite [username]\");\n }\n } else {\n chatInterface.addMessageToTab(\"* Create a game first...\");\n }\n } else if (command.at(1) == \"join\"){\n if (!hosts.empty()){\n try {\n const std::string & gameName = command.at(2);\n const std::string & hostName = hosts[gameName];\n chatInterface.addMessageToTab(\"* Joining game at \" + gameName);\n chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,\n hostName,\n \":\\001game join \" + gameName + \" \" + chatInterface.getClient()->getName() + \" \" + ipAddress + \"\\001\");\n game = Util::ReferenceCount<Game>(new Game(gameName, false));\n } catch (const std::out_of_range & ex){\n chatInterface.addMessageToTab(\"* \/game join [name]\");\n }\n } else {\n chatInterface.addMessageToTab(\"* You must be invited to a game first...\");\n }\n }\n }\n } else {\n \/\/chatInterface.addMessageToTab(\"* Uknown command.\");\n }\n }\n \n double ticks(double system){\n return system;\n }\n\n void run(){\n try {\n chatInterface.act();\n } catch (const Exception::Return & ex){\n escaped = true;\n throw ex;\n }\n }\n\n bool done(){\n return escaped;\n }\n \n void draw(const Graphics::Bitmap & screen){\n chatInterface.draw(screen);\n }\n};\n\nstatic void doIrc(const std::string & host, int port, const std::string & username){\n InputLogicDraw client(port, host, username);\n Util::standardLoop(client, client);\n}\n\nstatic void arguments(const std::string & application, int status){\n std::cout << \"Usage: .\/\" << application << \" port host [username]\" << std::endl;\n exit(status);\n}\n\nint main(int argc, char ** argv){\n if (argc >= 2){\n int port = atoi(argv[1]);\n std::string hostname = argv[2];\n std::string username = \"paintown-test\";\n if (argc > 3){\n username = argv[3];\n }\n \n Screen::realInit(Configuration::getScreenWidth(), Configuration::getScreenHeight());\n atexit(Screen::realFinish);\n Common::startTimers();\n \n Sound::initialize();\n \n Global::setDebug(2);\n \n Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, Graphics::getScreenBuffer());\n Keyboard::pushRepeatState(true);\n \n InputManager manager;\n \n Util::Parameter<Util::ReferenceCount<Path::RelativePath> > \n defaultFont(Font::defaultFont, Util::ReferenceCount<Path::RelativePath>(new Path::RelativePath(\"fonts\/arial.ttf\")));\n \n Network::init();\n \n try {\n doIrc(hostname, port, username);\n } catch (const Exception::Return & ex){\n } catch (const Network::NetworkException & ex){\n Global::debug(0) << \"Network Exception: \" << ex.getMessage() << std::endl;\n }\n Network::shutdown();\n } else {\n arguments(argv[0],0);\n }\n return 0;\n}\n#ifdef USE_ALLEGRO\nEND_OF_MAIN()\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ The Art of C++ \/ Tuple\n\/\/ Copyright (c) 2015 Daniel Frey\n\n#include <tao\/tuple\/tuple.hpp>\n\n#include <type_traits>\n#include <cassert>\n\nint main()\n{\n using namespace tao;\n\n auto t = tuple< int, double, int >();\n auto t2 = tuple< int, double, int >( 1, 2, 3 );\n auto t3( t2 );\n\n auto t4 = tuple< int, double, int >( 1, 2, 2 );\n auto t5 = tuple< int, double, int >( 1, 2, 4 );\n\n static_assert( tuple_size< decltype( t ) >::value == 3, \"oops\" );\n static_assert( tuple_size< decltype( t2 ) >::value == 3, \"oops\" );\n static_assert( tuple_size< decltype( t3 ) >::value == 3, \"oops\" );\n\n assert( get< 0 >( t2 ) == 1 );\n assert( get< 1 >( t2 ) == 2 );\n assert( get< 2 >( t2 ) == 3 );\n\n assert( get< double >( t2 ) == 2 );\n\n assert( get< 0 >( t3 ) == 1 );\n assert( get< 1 >( t3 ) == 2 );\n assert( get< 2 >( t3 ) == 3 );\n\n assert( get< double >( t3 ) == 2 );\n\n assert( t2 == t3 );\n assert( t2 != t4 );\n assert( t2 > t4 );\n assert( t2 < t5 );\n assert( t2 >= t3 );\n assert( t2 <= t3 );\n assert( t2 >= t4 );\n assert( t2 <= t5 );\n\n assert( tuple<>() == tuple<>() );\n assert( !( tuple<>() < tuple<>() ) );\n\n#if (__cplusplus >= 201402L)\n\n static_assert( tuple<>() == tuple<>(), \"oops\" );\n static_assert( make_tuple() == make_tuple(), \"oops\" );\n static_assert( make_tuple( 0 ) == make_tuple( 0 ), \"oops\" );\n\n static_assert( make_tuple( 1, 2, 3 ) > make_tuple( 1, 2, 2 ), \"oops\" );\n static_assert( make_tuple( 1, 2, 3 ) < make_tuple( 1, 2, 4 ), \"oops\" );\n\n \/\/ TODO: More constexpr checks\n\n#endif\n\n}\n<commit_msg>Added run-time checks<commit_after>\/\/ The Art of C++ \/ Tuple\n\/\/ Copyright (c) 2015 Daniel Frey\n\n#include <tao\/tuple\/tuple.hpp>\n\n#include <type_traits>\n#include <cassert>\n\nint main()\n{\n using namespace tao;\n\n auto t = tuple< int, double, int >();\n auto t2 = tuple< int, double, int >( 1, 2, 3 );\n auto t3( t2 );\n\n auto t4 = tuple< int, double, int >( 1, 2, 2 );\n auto t5 = tuple< int, double, int >( 1, 2, 4 );\n\n static_assert( tuple_size< decltype( t ) >::value == 3, \"oops\" );\n static_assert( tuple_size< decltype( t2 ) >::value == 3, \"oops\" );\n static_assert( tuple_size< decltype( t3 ) >::value == 3, \"oops\" );\n\n assert( get< 0 >( t2 ) == 1 );\n assert( get< 1 >( t2 ) == 2 );\n assert( get< 2 >( t2 ) == 3 );\n\n assert( get< double >( t2 ) == 2 );\n\n assert( get< 0 >( t3 ) == 1 );\n assert( get< 1 >( t3 ) == 2 );\n assert( get< 2 >( t3 ) == 3 );\n\n assert( get< double >( t3 ) == 2 );\n\n assert( t2 == t3 );\n assert( t2 != t4 );\n assert( t2 > t4 );\n assert( t2 < t5 );\n assert( t2 >= t3 );\n assert( t2 <= t3 );\n assert( t2 >= t4 );\n assert( t2 <= t5 );\n\n assert( tuple<>() == tuple<>() );\n assert( !( tuple<>() < tuple<>() ) );\n\n assert( make_tuple( 0 ) == make_tuple( 0 ) );\n\n assert( make_tuple( 1, 2, 3 ) > make_tuple( 1, 2, 2 ) );\n assert( make_tuple( 1, 2, 3 ) < make_tuple( 1, 2, 4 ) );\n\n assert(( tuple< int, int, int >( std::allocator_arg, 5, 1, 2, 3 ) < make_tuple( 1, 2, 4 ) ));\n\n#if (__cplusplus >= 201402L)\n\n static_assert( tuple<>() == tuple<>(), \"oops\" );\n static_assert( make_tuple() == make_tuple(), \"oops\" );\n static_assert( make_tuple( 0 ) == make_tuple( 0 ), \"oops\" );\n\n static_assert( make_tuple( 1, 2, 3 ) > make_tuple( 1, 2, 2 ), \"oops\" );\n static_assert( make_tuple( 1, 2, 3 ) < make_tuple( 1, 2, 4 ), \"oops\" );\n\n \/\/ TODO: More constexpr checks\n\n#endif\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2007-2012, Timothy Stack\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 are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * * Neither the name of Timothy Stack nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _top_status_source_hh\n#define _top_status_source_hh\n\n#include <string>\n\n#include \"logfile_sub_source.hh\"\n#include \"statusview_curses.hh\"\n\nclass top_status_source\n : public status_data_source {\npublic:\n\n typedef listview_curses::action::mem_functor_t<\n top_status_source> lv_functor_t;\n\n typedef enum {\n TSF_TIME,\n TSF_PARTITION_NAME,\n TSF_VIEW_NAME,\n TSF_STITCH_VIEW_FORMAT,\n TSF_FORMAT,\n TSF_STITCH_FORMAT_FILENAME,\n TSF_FILENAME,\n\n TSF__MAX\n } field_t;\n\n top_status_source()\n : filename_wire(*this, &top_status_source::update_filename)\n {\n this->tss_fields[TSF_TIME].set_width(24);\n this->tss_fields[TSF_PARTITION_NAME].set_width(30);\n this->tss_fields[TSF_VIEW_NAME].set_width(6);\n this->tss_fields[TSF_VIEW_NAME].right_justify(true);\n this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_width(2);\n this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_stitch_value(\n view_colors::ansi_color_pair_index(COLOR_CYAN, COLOR_BLUE));\n this->tss_fields[TSF_STITCH_VIEW_FORMAT].right_justify(true);\n this->tss_fields[TSF_FORMAT].set_width(20);\n this->tss_fields[TSF_FORMAT].right_justify(true);\n this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_width(2);\n this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_stitch_value(\n view_colors::ansi_color_pair_index(COLOR_WHITE, COLOR_CYAN));\n this->tss_fields[TSF_STITCH_FORMAT_FILENAME].right_justify(true);\n this->tss_fields[TSF_FILENAME].set_min_width(35); \/* XXX *\/\n this->tss_fields[TSF_FILENAME].set_share(1);\n this->tss_fields[TSF_FILENAME].right_justify(true);\n };\n\n lv_functor_t filename_wire;\n\n size_t statusview_fields(void) { return TSF__MAX; };\n\n status_field &statusview_value_for_field(int field)\n {\n return this->tss_fields[field];\n };\n\n void update_time(void)\n {\n status_field &sf = this->tss_fields[TSF_TIME];\n time_t current_time = time(NULL);\n char buffer[32];\n\n strftime(buffer, sizeof(buffer),\n \"%a %b %d %H:%M:%S %Z\",\n localtime(¤t_time));\n sf.set_value(buffer);\n };\n\n void update_filename(listview_curses *lc)\n {\n status_field & sf_partition = this->tss_fields[TSF_PARTITION_NAME];\n status_field & sf_format = this->tss_fields[TSF_FORMAT];\n status_field & sf_filename = this->tss_fields[TSF_FILENAME];\n struct line_range lr(0);\n\n if (lc->get_inner_height() > 0) {\n string_attrs_t::const_iterator line_attr;\n attr_line_t al;\n\n lc->get_data_source()->\n listview_value_for_row(*lc, lc->get_top(), al);\n string_attrs_t &sa = al.get_attrs();\n line_attr = find_string_attr(sa, &logline::L_FILE);\n if (line_attr != sa.cend()) {\n logfile *lf = (logfile *)line_attr->sa_value.sav_ptr;\n\n if (lf->get_format()) {\n sf_format.set_value(\"% 13s\",\n lf->get_format()->get_name().get());\n }\n else if (!lf->get_filename().empty()) {\n sf_format.set_value(\"% 13s\", \"plain text\");\n }\n else{\n sf_format.clear();\n }\n\n sf_filename.set_value(lf->get_filename());\n }\n else {\n sf_format.clear();\n sf_filename.clear();\n }\n\n line_attr = find_string_attr(sa, &logline::L_PARTITION);\n if (line_attr != sa.end()) {\n bookmark_metadata *bm = (bookmark_metadata *)line_attr->sa_value.sav_ptr;\n\n sf_partition.set_value(bm->bm_name.c_str());\n }\n else {\n sf_partition.clear();\n }\n }\n else {\n sf_format.clear();\n if (lc->get_data_source() != NULL) {\n sf_filename.set_value(lc->get_data_source()->listview_source_name(*lc));\n }\n }\n sf_format.get_value().get_attrs().push_back(\n string_attr(lr, &view_curses::VC_STYLE,\n A_REVERSE | view_colors::ansi_color_pair(COLOR_CYAN, COLOR_BLACK)));\n };\n\nprivate:\n status_field tss_fields[TSF__MAX];\n};\n#endif\n<commit_msg>build fix<commit_after>\/**\n * Copyright (c) 2007-2012, Timothy Stack\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 are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * * Neither the name of Timothy Stack nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _top_status_source_hh\n#define _top_status_source_hh\n\n#include <string>\n\n#include \"logfile_sub_source.hh\"\n#include \"statusview_curses.hh\"\n\nclass top_status_source\n : public status_data_source {\npublic:\n\n typedef listview_curses::action::mem_functor_t<\n top_status_source> lv_functor_t;\n\n typedef enum {\n TSF_TIME,\n TSF_PARTITION_NAME,\n TSF_VIEW_NAME,\n TSF_STITCH_VIEW_FORMAT,\n TSF_FORMAT,\n TSF_STITCH_FORMAT_FILENAME,\n TSF_FILENAME,\n\n TSF__MAX\n } field_t;\n\n top_status_source()\n : filename_wire(*this, &top_status_source::update_filename)\n {\n this->tss_fields[TSF_TIME].set_width(24);\n this->tss_fields[TSF_PARTITION_NAME].set_width(30);\n this->tss_fields[TSF_VIEW_NAME].set_width(6);\n this->tss_fields[TSF_VIEW_NAME].right_justify(true);\n this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_width(2);\n this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_stitch_value(\n view_colors::ansi_color_pair_index(COLOR_CYAN, COLOR_BLUE));\n this->tss_fields[TSF_STITCH_VIEW_FORMAT].right_justify(true);\n this->tss_fields[TSF_FORMAT].set_width(20);\n this->tss_fields[TSF_FORMAT].right_justify(true);\n this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_width(2);\n this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_stitch_value(\n view_colors::ansi_color_pair_index(COLOR_WHITE, COLOR_CYAN));\n this->tss_fields[TSF_STITCH_FORMAT_FILENAME].right_justify(true);\n this->tss_fields[TSF_FILENAME].set_min_width(35); \/* XXX *\/\n this->tss_fields[TSF_FILENAME].set_share(1);\n this->tss_fields[TSF_FILENAME].right_justify(true);\n };\n\n lv_functor_t filename_wire;\n\n size_t statusview_fields(void) { return TSF__MAX; };\n\n status_field &statusview_value_for_field(int field)\n {\n return this->tss_fields[field];\n };\n\n void update_time(void)\n {\n status_field &sf = this->tss_fields[TSF_TIME];\n time_t current_time = time(NULL);\n char buffer[32];\n\n strftime(buffer, sizeof(buffer),\n \"%a %b %d %H:%M:%S %Z\",\n localtime(¤t_time));\n sf.set_value(buffer);\n };\n\n void update_filename(listview_curses *lc)\n {\n status_field & sf_partition = this->tss_fields[TSF_PARTITION_NAME];\n status_field & sf_format = this->tss_fields[TSF_FORMAT];\n status_field & sf_filename = this->tss_fields[TSF_FILENAME];\n struct line_range lr(0);\n\n if (lc->get_inner_height() > 0) {\n string_attrs_t::const_iterator line_attr;\n attr_line_t al;\n\n lc->get_data_source()->\n listview_value_for_row(*lc, lc->get_top(), al);\n string_attrs_t &sa = al.get_attrs();\n line_attr = find_string_attr(sa, &logline::L_FILE);\n if (line_attr != sa.end()) {\n logfile *lf = (logfile *)line_attr->sa_value.sav_ptr;\n\n if (lf->get_format()) {\n sf_format.set_value(\"% 13s\",\n lf->get_format()->get_name().get());\n }\n else if (!lf->get_filename().empty()) {\n sf_format.set_value(\"% 13s\", \"plain text\");\n }\n else{\n sf_format.clear();\n }\n\n sf_filename.set_value(lf->get_filename());\n }\n else {\n sf_format.clear();\n sf_filename.clear();\n }\n\n line_attr = find_string_attr(sa, &logline::L_PARTITION);\n if (line_attr != sa.end()) {\n bookmark_metadata *bm = (bookmark_metadata *)line_attr->sa_value.sav_ptr;\n\n sf_partition.set_value(bm->bm_name.c_str());\n }\n else {\n sf_partition.clear();\n }\n }\n else {\n sf_format.clear();\n if (lc->get_data_source() != NULL) {\n sf_filename.set_value(lc->get_data_source()->listview_source_name(*lc));\n }\n }\n sf_format.get_value().get_attrs().push_back(\n string_attr(lr, &view_curses::VC_STYLE,\n A_REVERSE | view_colors::ansi_color_pair(COLOR_CYAN, COLOR_BLACK)));\n };\n\nprivate:\n status_field tss_fields[TSF__MAX];\n};\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* primitives.tcc -*- C++ -*-\n Rémi Attab (remi.attab@gmail.com), 19 Apr 2014\n FreeBSD-style copyright and disclaimer apply\n\n Reflection utilities for primitives.\n*\/\n\n#pragma once\n\n#include \"reflect.h\"\n#include \"reflect\/basics.h\"\n#include \"reflect\/plumbing.h\"\n\n#include <limits>\n\nnamespace reflect {\n\n\/******************************************************************************\/\n\/* REFLECT LIMIT *\/\n\/******************************************************************************\/\n\n#define reflectLimit(name) \\\n type_->add(#name, [] { return std::numeric_limits<T_>::name(); });\n\n\n\/******************************************************************************\/\n\/* REFLECT NUMBER *\/\n\/******************************************************************************\/\n\ntemplate<typename T_>\nvoid reflectNumberImpl(Type* type_)\n{\n reflectPlumbing();\n\n reflectLimit(min);\n reflectLimit(max);\n\n reflectTrait(primitive);\n\n if (std::numeric_limits<T_>::is_integer) {\n reflectTrait(integer);\n\n if (std::numeric_limits<T_>::is_signed)\n reflectTrait(signed);\n else reflectTrait(unsigned);\n }\n\n else reflectTrait(float);\n}\n\n#define reflectNumber(num) \\\n reflectClassImpl(num) { reflectNumberImpl<T_>(type_); }\n\n} \/\/ reflect\n<commit_msg>Added bool traits.<commit_after>\/* primitives.tcc -*- C++ -*-\n Rémi Attab (remi.attab@gmail.com), 19 Apr 2014\n FreeBSD-style copyright and disclaimer apply\n\n Reflection utilities for primitives.\n*\/\n\n#pragma once\n\n#include \"reflect.h\"\n#include \"reflect\/basics.h\"\n#include \"reflect\/plumbing.h\"\n\n#include <limits>\n\nnamespace reflect {\n\n\/******************************************************************************\/\n\/* REFLECT LIMIT *\/\n\/******************************************************************************\/\n\n#define reflectLimit(name) \\\n type_->add(#name, [] { return std::numeric_limits<T_>::name(); });\n\n\n\/******************************************************************************\/\n\/* REFLECT NUMBER *\/\n\/******************************************************************************\/\n\ntemplate<typename T_>\nvoid reflectNumberImpl(Type* type_)\n{\n reflectPlumbing();\n\n reflectLimit(min);\n reflectLimit(max);\n\n reflectTrait(primitive);\n\n if (std::is_same<T_, bool>::value)\n reflectTrait(bool);\n\n else if (std::numeric_limits<T_>::is_integer) {\n reflectTrait(integer);\n\n if (std::numeric_limits<T_>::is_signed)\n reflectTrait(signed);\n else reflectTrait(unsigned);\n }\n\n else reflectTrait(float);\n}\n\n#define reflectNumber(num) \\\n reflectClassImpl(num) { reflectNumberImpl<T_>(type_); }\n\n} \/\/ reflect\n<|endoftext|>"} {"text":"<commit_before>#include <v8.h>\n#include <node.h>\n#include <objc\/objc.h>\n#include <objc\/message.h>\n#include <objc\/runtime.h>\n#include <ffi\/ffi.h>\n#include \"objc.h\"\n#include \"helpers.h\"\n\n\/\/ Debug\n#import <Foundation\/Foundation.h>\n#include <stdio.h>\n\nusing namespace node;\nusing namespace v8;\n\nnamespace node_objc {\n\n v8::Handle<Value> node_objc_getClass (const Arguments& args) {\n HandleScope scope;\n String::Utf8Value classStr(args[0]->ToString());\n \/\/ get the requested Class\n Class c = objc_getClass(*classStr);\n \/\/ if null was returned, then return JavaScript null\n if (!c) {\n return Null();\n }\n return scope.Close(WrapId(c));\n }\n\n \/\/ For debugging libffi...\n id fake_msgSend (id ref, SEL sel, ...) {\n int j;\n va_list ap;\n va_start(ap, sel); \/\/Requires the last fixed parameter (to get the address)\n for(j=0; j<1; j++) {\n const char * param = va_arg(ap, const char *); \/\/Requires the type to cast to. Increments ap to the next argument.\n NSLog(@\"string: %s\", param);\n }\n va_end(ap);\n return ref;\n }\n\n v8::Handle<Value> node_objc_msgSend (const Arguments& args) {\n HandleScope scope;\n\n ffi_cif cif;\n int argv = args.Length();\n ffi_type **arg_types;\n void **arg_values;\n ffi_status status;\n id result;\n\n arg_types = (ffi_type **) malloc(argv*sizeof(ffi_type *));\n arg_values = (void **) malloc(argv*sizeof(void *));\n\n arg_types[0] = &ffi_type_pointer;\n arg_types[1] = &ffi_type_pointer;\n\n id ref = UnwrapId(args[0]->ToObject());\n SEL sel = UnwrapSel(args[1]->ToObject());\n arg_values[0] = &ref;\n arg_values[1] = &sel;\n\n Local<Value> val;\n for (int i=2; i < argv; i++) {\n val = args[i];\n arg_types[i] = &ffi_type_pointer;\n if (val->IsString()) {\n String::Utf8Value strVal(val->ToObject());\n const char * cStrVal = *strVal;\n arg_values[i] = &cStrVal;\n } else {\n\n }\n }\n\n if ((status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argv, &ffi_type_pointer, arg_types)) != FFI_OK) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\"`ffi_prep_cif` failed!\")));\n }\n\n @try {\n ffi_call(&cif, FFI_FN(objc_msgSend), &result, arg_values);\n }\n @catch (NSException *e) {\n return v8::ThrowException(NSExceptionToV8Error(e));\n }\n\n \/\/NSLog(@\"Length: %d\", [result length]);\n\n v8::Handle<Object> wrap = WrapId(result);\n\n free(arg_types);\n free(arg_values);\n return scope.Close(wrap);\n }\n\n v8::Handle<Value> node_sel_registerName (const Arguments& args) {\n HandleScope scope;\n String::Utf8Value selStr(args[0]->ToString());\n SEL sel = sel_registerName(*selStr);\n if (!sel) {\n return Null();\n }\n return scope.Close(WrapSel(sel));\n }\n\n v8::Handle<Value> node_NSLog (const Arguments& args) {\n HandleScope scope;\n\n id ref = UnwrapId(args[0]->ToObject());\n NSLog(@\"%@\", ref);\n return Undefined();\n }\n\n \/\/ INIT function\n void objcInit (v8::Handle<v8::Object> target) {\n HandleScope scope;\n NODE_SET_METHOD(target, \"objc_getClass\", node_objc_getClass);\n NODE_SET_METHOD(target, \"objc_msgSend\", node_objc_msgSend);\n NODE_SET_METHOD(target, \"sel_registerName\", node_sel_registerName);\n NODE_SET_METHOD(target, \"NSLog\", node_NSLog);\n }\n\n} \/\/ namespace node_objc\n<commit_msg>Pass 'id' values properly as arguments<commit_after>#include <v8.h>\n#include <node.h>\n#include <objc\/objc.h>\n#include <objc\/message.h>\n#include <objc\/runtime.h>\n#include <ffi\/ffi.h>\n#include \"objc.h\"\n#include \"helpers.h\"\n\n\/\/ Debug\n#import <Foundation\/Foundation.h>\n#include <stdio.h>\n\nusing namespace node;\nusing namespace v8;\n\nnamespace node_objc {\n\n v8::Handle<Value> node_objc_getClass (const Arguments& args) {\n HandleScope scope;\n String::Utf8Value classStr(args[0]->ToString());\n \/\/ get the requested Class\n Class c = objc_getClass(*classStr);\n \/\/ if null was returned, then return JavaScript null\n if (!c) {\n return Null();\n }\n return scope.Close(WrapId(c));\n }\n\n \/\/ For debugging libffi...\n id fake_msgSend (id ref, SEL sel, ...) {\n int j;\n va_list ap;\n va_start(ap, sel); \/\/Requires the last fixed parameter (to get the address)\n for(j=0; j<1; j++) {\n const char * param = va_arg(ap, const char *); \/\/Requires the type to cast to. Increments ap to the next argument.\n NSLog(@\"string: %s\", param);\n }\n va_end(ap);\n return ref;\n }\n\n v8::Handle<Value> node_objc_msgSend (const Arguments& args) {\n HandleScope scope;\n\n ffi_cif cif;\n int argv = args.Length();\n ffi_type **arg_types;\n void **arg_values;\n ffi_status status;\n id result;\n\n arg_types = (ffi_type **) malloc(argv*sizeof(ffi_type *));\n arg_values = (void **) malloc(argv*sizeof(void *));\n\n arg_types[0] = &ffi_type_pointer;\n arg_types[1] = &ffi_type_pointer;\n\n id ref = UnwrapId(args[0]->ToObject());\n SEL sel = UnwrapSel(args[1]->ToObject());\n arg_values[0] = &ref;\n arg_values[1] = &sel;\n\n Local<Value> val;\n for (int i=2; i < argv; i++) {\n val = args[i];\n arg_types[i] = &ffi_type_pointer;\n if (val->IsString()) {\n String::Utf8Value strVal(val->ToObject());\n const char * cStrVal = *strVal;\n arg_values[i] = &cStrVal;\n } else {\n id val = UnwrapId(args[i]->ToObject());\n arg_values[i] = &val;\n }\n }\n\n if ((status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argv, &ffi_type_pointer, arg_types)) != FFI_OK) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\"`ffi_prep_cif` failed!\")));\n }\n\n @try {\n ffi_call(&cif, FFI_FN(objc_msgSend), &result, arg_values);\n }\n @catch (NSException *e) {\n return v8::ThrowException(NSExceptionToV8Error(e));\n }\n\n \/\/NSLog(@\"Length: %d\", [result length]);\n\n v8::Handle<Object> wrap = WrapId(result);\n\n free(arg_types);\n free(arg_values);\n return scope.Close(wrap);\n }\n\n v8::Handle<Value> node_sel_registerName (const Arguments& args) {\n HandleScope scope;\n String::Utf8Value selStr(args[0]->ToString());\n SEL sel = sel_registerName(*selStr);\n if (!sel) {\n return Null();\n }\n return scope.Close(WrapSel(sel));\n }\n\n v8::Handle<Value> node_NSLog (const Arguments& args) {\n HandleScope scope;\n\n id ref = UnwrapId(args[0]->ToObject());\n NSLog(@\"%@\", ref);\n return Undefined();\n }\n\n \/\/ INIT function\n void objcInit (v8::Handle<v8::Object> target) {\n HandleScope scope;\n NODE_SET_METHOD(target, \"objc_getClass\", node_objc_getClass);\n NODE_SET_METHOD(target, \"objc_msgSend\", node_objc_msgSend);\n NODE_SET_METHOD(target, \"sel_registerName\", node_sel_registerName);\n NODE_SET_METHOD(target, \"NSLog\", node_NSLog);\n }\n\n} \/\/ namespace node_objc\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n#include \"chainparamsbase.h\"\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n\treturn CalculateNextWorkRequired(pindexLast, params);\n}\n\/\/ SYSCOIN DGW diff algo\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, const Consensus::Params& params)\n{\n\n\t\/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dashpay.io *\/\n \/\/ Genesis block\n\n\tconst arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit);\n if (pindexLast == NULL)\n return nProofOfWorkLimit.GetCompact();\n if (params.fPowNoRetargeting)\n return pindexLast->nBits;\n const CBlockIndex *BlockLastSolved = pindexLast;\n const CBlockIndex *BlockReading = pindexLast;\n int64_t nActualTimespan = 0;\n int64_t LastBlockTime = 0;\n int64_t PastBlocksMin = 24;\n int64_t PastBlocksMax = 24;\n int64_t CountBlocks = 0;\n arith_uint256 PastDifficultyAverage;\n arith_uint256 PastDifficultyAveragePrev;\n\n if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {\n return nProofOfWorkLimit.GetCompact();\n }\n\n for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n CountBlocks++;\n\n if(CountBlocks <= PastBlocksMin) {\n if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }\n else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) \/ (CountBlocks + 1); }\n PastDifficultyAveragePrev = PastDifficultyAverage;\n }\n\n if(LastBlockTime > 0){\n int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());\n nActualTimespan += Diff;\n }\n LastBlockTime = BlockReading->GetBlockTime();\n\n if (BlockReading->pprev == NULL) { assert(BlockReading); break; }\n BlockReading = BlockReading->pprev;\n }\n\n arith_uint256 bnNew(PastDifficultyAverage);\n\n int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing;\n\n if (nActualTimespan < _nTargetTimespan\/3)\n nActualTimespan = _nTargetTimespan\/3;\n if (nActualTimespan > _nTargetTimespan*3)\n nActualTimespan = _nTargetTimespan*3;\n\n \/\/ Retarget\n bnNew *= nActualTimespan;\n bnNew \/= _nTargetTimespan;\n\n if (bnNew > nProofOfWorkLimit){\n bnNew = nProofOfWorkLimit;\n }\n\n return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n bool fNegative;\n bool fOverflow;\n arith_uint256 bnTarget;\n\n bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n \/\/ Check range\n if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n return error(\"CheckProofOfWork(): nBits below minimum work\");\n\n \/\/ Check proof of work matches claimed amount\n\tstd::string chain = ChainNameFromCommandLine();\n if (UintToArith256(hash) > bnTarget)\n return error(\"CheckProofOfWork(): hash doesn't match nBits\");\n\n return true;\n}\n\narith_uint256 GetBlockProof(const CBlockIndex& block)\n{\n arith_uint256 bnTarget;\n bool fNegative;\n bool fOverflow;\n bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);\n if (fNegative || fOverflow || bnTarget == 0)\n return 0;\n \/\/ We need to compute 2**256 \/ (bnTarget+1), but we can't represent 2**256\n \/\/ as it's too large for a arith_uint256. However, as 2**256 is at least as large\n \/\/ as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) \/ (bnTarget+1)) + 1,\n \/\/ or ~bnTarget \/ (nTarget+1) + 1.\n return (~bnTarget \/ (bnTarget + 1)) + 1;\n}\n\nint64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)\n{\n arith_uint256 r;\n int sign = 1;\n if (to.nChainWork > from.nChainWork) {\n r = to.nChainWork - from.nChainWork;\n } else {\n r = from.nChainWork - to.nChainWork;\n sign = -1;\n }\n r = r * arith_uint256(params.nPowTargetSpacing) \/ GetBlockProof(tip);\n if (r.bits() > 63) {\n return sign * std::numeric_limits<int64_t>::max();\n }\n return sign * r.GetLow64();\n}\n<commit_msg>typo<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n#include \"chainparamsbase.h\"\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n\treturn CalculateNextWorkRequired(pindexLast, params);\n}\n\/\/ SYSCOIN DGW diff algo\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n\n\t\/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dashpay.io *\/\n \/\/ Genesis block\n\n\tconst arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit);\n if (pindexLast == NULL)\n return nProofOfWorkLimit.GetCompact();\n if (params.fPowNoRetargeting)\n return pindexLast->nBits;\n const CBlockIndex *BlockLastSolved = pindexLast;\n const CBlockIndex *BlockReading = pindexLast;\n int64_t nActualTimespan = 0;\n int64_t LastBlockTime = 0;\n int64_t PastBlocksMin = 24;\n int64_t PastBlocksMax = 24;\n int64_t CountBlocks = 0;\n arith_uint256 PastDifficultyAverage;\n arith_uint256 PastDifficultyAveragePrev;\n\n if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {\n return nProofOfWorkLimit.GetCompact();\n }\n\n for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n CountBlocks++;\n\n if(CountBlocks <= PastBlocksMin) {\n if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }\n else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) \/ (CountBlocks + 1); }\n PastDifficultyAveragePrev = PastDifficultyAverage;\n }\n\n if(LastBlockTime > 0){\n int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());\n nActualTimespan += Diff;\n }\n LastBlockTime = BlockReading->GetBlockTime();\n\n if (BlockReading->pprev == NULL) { assert(BlockReading); break; }\n BlockReading = BlockReading->pprev;\n }\n\n arith_uint256 bnNew(PastDifficultyAverage);\n\n int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing;\n\n if (nActualTimespan < _nTargetTimespan\/3)\n nActualTimespan = _nTargetTimespan\/3;\n if (nActualTimespan > _nTargetTimespan*3)\n nActualTimespan = _nTargetTimespan*3;\n\n \/\/ Retarget\n bnNew *= nActualTimespan;\n bnNew \/= _nTargetTimespan;\n\n if (bnNew > nProofOfWorkLimit){\n bnNew = nProofOfWorkLimit;\n }\n\n return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n bool fNegative;\n bool fOverflow;\n arith_uint256 bnTarget;\n\n bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n \/\/ Check range\n if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n return error(\"CheckProofOfWork(): nBits below minimum work\");\n\n \/\/ Check proof of work matches claimed amount\n\tstd::string chain = ChainNameFromCommandLine();\n if (UintToArith256(hash) > bnTarget)\n return error(\"CheckProofOfWork(): hash doesn't match nBits\");\n\n return true;\n}\n\narith_uint256 GetBlockProof(const CBlockIndex& block)\n{\n arith_uint256 bnTarget;\n bool fNegative;\n bool fOverflow;\n bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);\n if (fNegative || fOverflow || bnTarget == 0)\n return 0;\n \/\/ We need to compute 2**256 \/ (bnTarget+1), but we can't represent 2**256\n \/\/ as it's too large for a arith_uint256. However, as 2**256 is at least as large\n \/\/ as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) \/ (bnTarget+1)) + 1,\n \/\/ or ~bnTarget \/ (nTarget+1) + 1.\n return (~bnTarget \/ (bnTarget + 1)) + 1;\n}\n\nint64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)\n{\n arith_uint256 r;\n int sign = 1;\n if (to.nChainWork > from.nChainWork) {\n r = to.nChainWork - from.nChainWork;\n } else {\n r = from.nChainWork - to.nChainWork;\n sign = -1;\n }\n r = r * arith_uint256(params.nPowTargetSpacing) \/ GetBlockProof(tip);\n if (r.bits() > 63) {\n return sign * std::numeric_limits<int64_t>::max();\n }\n return sign * r.GetLow64();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ============================================================================\n *\n * Filename: qcpp.hh\n * Description: Global header to include all subheaders\n * License: GPLv3+\n * Author: Kevin Murray, spam@kdmurray.id.au\n *\n * ============================================================================\n *\/\n\n#ifndef QCPP_HH\n#define QCPP_HH\n\n#include \"qc-config.hh\"\n#include \"qc-io.hh\"\n#include \"qc-processor.hh\"\n#include \"qc-length.hh\"\n\n#endif \/* QCPP_HH *\/\n<commit_msg>Add qc-gbs to catch-all header<commit_after>\/*\n * ============================================================================\n *\n * Filename: qcpp.hh\n * Description: Global header to include all subheaders\n * License: GPLv3+\n * Author: Kevin Murray, spam@kdmurray.id.au\n *\n * ============================================================================\n *\/\n\n#ifndef QCPP_HH\n#define QCPP_HH\n\n#include \"qc-config.hh\"\n#include \"qc-io.hh\"\n#include \"qc-gbs.hh\"\n#include \"qc-processor.hh\"\n#include \"qc-length.hh\"\n\n#endif \/* QCPP_HH *\/\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkStructuredGrid.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkStructuredGrid.hh\"\n#include \"vtkVertex.hh\"\n#include \"vtkLine.hh\"\n#include \"vtkQuad.hh\"\n#include \"vtkHexahedron.hh\"\n\nvtkStructuredGrid::vtkStructuredGrid()\n{\n this->Dimensions[0] = 1;\n this->Dimensions[1] = 1;\n this->Dimensions[2] = 1;\n this->DataDescription = VTK_SINGLE_POINT;\n \n this->Blanking = 0;\n this->PointVisibility = NULL;\n}\n\nvtkStructuredGrid::vtkStructuredGrid(const vtkStructuredGrid& sg) :\nvtkPointSet(sg)\n{\n this->Dimensions[0] = sg.Dimensions[0];\n this->Dimensions[1] = sg.Dimensions[1];\n this->Dimensions[2] = sg.Dimensions[2];\n this->DataDescription = sg.DataDescription;\n\n this->Blanking = sg.Blanking;\n if ( sg.PointVisibility != NULL )\n {\n this->PointVisibility->UnRegister((vtkObject *)this);\n this->PointVisibility = sg.PointVisibility;\n this->PointVisibility->Register((vtkObject *)this);\n }\n else\n {\n this->PointVisibility = NULL;\n }\n}\n\nvtkStructuredGrid::~vtkStructuredGrid()\n{\n this->Initialize();\n if (this->PointVisibility) \n {\n this->PointVisibility->UnRegister((vtkObject *)this);\n }\n this->PointVisibility = NULL;\n}\n\n\/\/ Description:\n\/\/ Copy the geometric and topological structure of an input structured grid.\nvoid vtkStructuredGrid::CopyStructure(vtkDataSet *ds)\n{\n vtkStructuredGrid *sg=(vtkStructuredGrid *)ds;\n vtkPointSet::CopyStructure(ds);\n\n for (int i=0; i<3; i++)\n {\n this->Dimensions[i] = sg->Dimensions[i];\n }\n this->DataDescription = sg->DataDescription;\n\n this->Blanking = sg->Blanking;\n if ( sg->PointVisibility != NULL && \n sg->PointVisibility != this->PointVisibility )\n {\n if ( this->PointVisibility ) \n {\n this->PointVisibility->UnRegister((vtkObject *)this);\n }\n this->PointVisibility = sg->PointVisibility;\n this->PointVisibility->Register((vtkObject *)this);\n }\n}\n\nvoid vtkStructuredGrid::Initialize()\n{\n vtkPointSet::Initialize(); \n if ( this->PointVisibility ) \n this->PointVisibility->UnRegister(this);\n this->PointVisibility = NULL;\n this->Blanking = 0;\n}\n\nint vtkStructuredGrid::GetCellType(int vtkNotUsed(cellId))\n{\n switch (this->DataDescription)\n {\n case VTK_SINGLE_POINT: \n return VTK_VERTEX;\n\n case VTK_X_LINE: case VTK_Y_LINE: case VTK_Z_LINE:\n return VTK_LINE;\n\n case VTK_XY_PLANE: case VTK_YZ_PLANE: case VTK_XZ_PLANE:\n return VTK_QUAD;\n\n case VTK_XYZ_GRID:\n return VTK_HEXAHEDRON;\n\n default:\n vtkErrorMacro(<<\"Bad data description!\");\n return VTK_NULL_ELEMENT;\n }\n}\n\nvtkCell *vtkStructuredGrid::GetCell(int cellId)\n{\n static vtkVertex vertex;\n static vtkLine line;\n static vtkQuad quad;\n static vtkHexahedron hexa;\n static vtkCell *cell;\n int idx;\n int i, j, k;\n int d01, offset1, offset2;\n \n \/\/ Make sure data is defined\n if ( ! this->Points )\n {\n vtkErrorMacro (<<\"No data\");\n return NULL;\n }\n \n switch (this->DataDescription)\n {\n case VTK_SINGLE_POINT: \/\/ cellId can only be = 0\n cell = &vertex;\n cell->PointIds.InsertId(0,0);\n break;\n\n case VTK_X_LINE:\n cell = &line;\n cell->PointIds.InsertId(0,cellId);\n cell->PointIds.InsertId(1,cellId+1);\n break;\n\n case VTK_Y_LINE:\n cell = &line;\n cell->PointIds.InsertId(0,cellId);\n cell->PointIds.InsertId(1,cellId+1);\n break;\n\n case VTK_Z_LINE:\n cell = &line;\n cell->PointIds.InsertId(0,cellId);\n cell->PointIds.InsertId(1,cellId+1);\n break;\n\n case VTK_XY_PLANE:\n cell = &quad;\n i = cellId % (this->Dimensions[0]-1);\n j = cellId \/ (this->Dimensions[0]-1);\n idx = i + j*this->Dimensions[0];\n offset1 = 1;\n offset2 = this->Dimensions[0];\n\n cell->PointIds.InsertId(0,idx);\n cell->PointIds.InsertId(1,idx+offset1);\n cell->PointIds.InsertId(2,idx+offset1+offset2);\n cell->PointIds.InsertId(3,idx+offset2);\n break;\n\n case VTK_YZ_PLANE:\n cell = &quad;\n j = cellId % (this->Dimensions[1]-1);\n k = cellId \/ (this->Dimensions[1]-1);\n idx = j + k*this->Dimensions[1];\n offset1 = 1;\n offset2 = this->Dimensions[1];\n\n cell->PointIds.InsertId(0,idx);\n cell->PointIds.InsertId(1,idx+offset1);\n cell->PointIds.InsertId(2,idx+offset1+offset2);\n cell->PointIds.InsertId(3,idx+offset2);\n break;\n\n case VTK_XZ_PLANE:\n cell = &quad;\n i = cellId % (this->Dimensions[0]-1);\n k = cellId \/ (this->Dimensions[0]-1);\n idx = i + k*this->Dimensions[0];\n offset1 = 1;\n offset2 = this->Dimensions[0];\n\n cell->PointIds.InsertId(0,idx);\n cell->PointIds.InsertId(1,idx+offset1);\n cell->PointIds.InsertId(2,idx+offset1+offset2);\n cell->PointIds.InsertId(3,idx+offset2);\n break;\n\n case VTK_XYZ_GRID:\n cell = &hexa;\n d01 = this->Dimensions[0]*this->Dimensions[1];\n i = cellId % (this->Dimensions[0] - 1);\n j = (cellId \/ (this->Dimensions[0] - 1)) % (this->Dimensions[1] - 1);\n k = cellId \/ ((this->Dimensions[0] - 1) * (this->Dimensions[1] - 1));\n idx = i+ j*this->Dimensions[0] + k*d01;\n offset1 = 1;\n offset2 = this->Dimensions[0];\n\n cell->PointIds.InsertId(0,idx);\n cell->PointIds.InsertId(1,idx+offset1);\n cell->PointIds.InsertId(2,idx+offset1+offset2);\n cell->PointIds.InsertId(3,idx+offset2);\n idx += d01;\n cell->PointIds.InsertId(4,idx);\n cell->PointIds.InsertId(5,idx+offset1);\n cell->PointIds.InsertId(6,idx+offset1+offset2);\n cell->PointIds.InsertId(7,idx+offset2);\n break;\n }\n\n \/\/ Extract point coordinates and point ids. NOTE: the ordering of the VlQuad\n \/\/ and vtkHexahedron cells are tricky.\n for (i=0; i<cell->PointIds.GetNumberOfIds(); i++)\n {\n idx = cell->PointIds.GetId(i);\n cell->Points.InsertPoint(i,this->Points->GetPoint(idx));\n }\n\n return cell;\n}\n\n\/\/ Description:\n\/\/ Turn on data blanking. Data blanking is the ability to turn off\n\/\/ portions of the grid when displaying or operating on it. Some data\n\/\/ (like finite difference data) routinely turns off data to simulate\n\/\/ solid obstacles.\nvoid vtkStructuredGrid::BlankingOn()\n{\n if (!this->Blanking)\n {\n this->Blanking = 1;\n this->Modified();\n\n if ( !this->PointVisibility )\n {\n this->AllocatePointVisibility();\n }\n }\n}\n\nvoid vtkStructuredGrid::AllocatePointVisibility()\n{\n if ( !this->PointVisibility )\n {\n this->PointVisibility = \n new vtkBitScalars(this->GetNumberOfPoints(),1000);\n this->PointVisibility->Register((vtkObject *)this);\n for (int i=0; i<this->GetNumberOfPoints(); i++)\n {\n this->PointVisibility->InsertScalar(i,1);\n }\n this->PointVisibility->Delete();\n }\n}\n\n\/\/ Description:\n\/\/ Turn off data blanking.\nvoid vtkStructuredGrid::BlankingOff()\n{\n if (this->Blanking)\n {\n this->Blanking = 0;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Turn off a particular data point.\nvoid vtkStructuredGrid::BlankPoint(int ptId)\n{\n if ( !this->PointVisibility ) this->AllocatePointVisibility();\n this->PointVisibility->InsertScalar(ptId,0);\n}\n\n\/\/ Description:\n\/\/ Turn on a particular data point.\nvoid vtkStructuredGrid::UnBlankPoint(int ptId)\n{\n if ( !this->PointVisibility ) this->AllocatePointVisibility();\n this->PointVisibility->InsertScalar(ptId,1);\n}\n\n\/\/ Description:\n\/\/ Set dimensions of structured grid dataset.\nvoid vtkStructuredGrid::SetDimensions(int i, int j, int k)\n{\n int dim[3];\n\n dim[0] = i;\n dim[1] = j;\n dim[2] = k;\n this->SetDimensions(dim);\n}\n\n\/\/ Description:\n\/\/ Set dimensions of structured grid dataset.\nvoid vtkStructuredGrid::SetDimensions(int dim[3])\n{\n int returnStatus=this->StructuredData.SetDimensions(dim,this->Dimensions);\n\n if ( returnStatus > -1 ) \n {\n this->DataDescription = returnStatus;\n this->Modified();\n }\n}\n\nvoid vtkStructuredGrid::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkPointSet::PrintSelf(os,indent);\n\n os << indent << \"Dimensions: (\" << this->Dimensions[0] << \", \"\n << this->Dimensions[1] << \", \"\n << this->Dimensions[2] << \")\\n\";\n\n os << indent << \"Blanking: \" << (this->Blanking ? \"On\\n\" : \"Off\\n\");\n}\n\n<commit_msg>PERF: Removed NumberOfIds method call from for loop test.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkStructuredGrid.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkStructuredGrid.hh\"\n#include \"vtkVertex.hh\"\n#include \"vtkLine.hh\"\n#include \"vtkQuad.hh\"\n#include \"vtkHexahedron.hh\"\n\nvtkStructuredGrid::vtkStructuredGrid()\n{\n this->Dimensions[0] = 1;\n this->Dimensions[1] = 1;\n this->Dimensions[2] = 1;\n this->DataDescription = VTK_SINGLE_POINT;\n \n this->Blanking = 0;\n this->PointVisibility = NULL;\n}\n\nvtkStructuredGrid::vtkStructuredGrid(const vtkStructuredGrid& sg) :\nvtkPointSet(sg)\n{\n this->Dimensions[0] = sg.Dimensions[0];\n this->Dimensions[1] = sg.Dimensions[1];\n this->Dimensions[2] = sg.Dimensions[2];\n this->DataDescription = sg.DataDescription;\n\n this->Blanking = sg.Blanking;\n if ( sg.PointVisibility != NULL )\n {\n this->PointVisibility->UnRegister((vtkObject *)this);\n this->PointVisibility = sg.PointVisibility;\n this->PointVisibility->Register((vtkObject *)this);\n }\n else\n {\n this->PointVisibility = NULL;\n }\n}\n\nvtkStructuredGrid::~vtkStructuredGrid()\n{\n this->Initialize();\n if (this->PointVisibility) \n {\n this->PointVisibility->UnRegister((vtkObject *)this);\n }\n this->PointVisibility = NULL;\n}\n\n\/\/ Description:\n\/\/ Copy the geometric and topological structure of an input structured grid.\nvoid vtkStructuredGrid::CopyStructure(vtkDataSet *ds)\n{\n vtkStructuredGrid *sg=(vtkStructuredGrid *)ds;\n vtkPointSet::CopyStructure(ds);\n\n for (int i=0; i<3; i++)\n {\n this->Dimensions[i] = sg->Dimensions[i];\n }\n this->DataDescription = sg->DataDescription;\n\n this->Blanking = sg->Blanking;\n if ( sg->PointVisibility != NULL && \n sg->PointVisibility != this->PointVisibility )\n {\n if ( this->PointVisibility ) \n {\n this->PointVisibility->UnRegister((vtkObject *)this);\n }\n this->PointVisibility = sg->PointVisibility;\n this->PointVisibility->Register((vtkObject *)this);\n }\n}\n\nvoid vtkStructuredGrid::Initialize()\n{\n vtkPointSet::Initialize(); \n if ( this->PointVisibility ) \n this->PointVisibility->UnRegister(this);\n this->PointVisibility = NULL;\n this->Blanking = 0;\n}\n\nint vtkStructuredGrid::GetCellType(int vtkNotUsed(cellId))\n{\n switch (this->DataDescription)\n {\n case VTK_SINGLE_POINT: \n return VTK_VERTEX;\n\n case VTK_X_LINE: case VTK_Y_LINE: case VTK_Z_LINE:\n return VTK_LINE;\n\n case VTK_XY_PLANE: case VTK_YZ_PLANE: case VTK_XZ_PLANE:\n return VTK_QUAD;\n\n case VTK_XYZ_GRID:\n return VTK_HEXAHEDRON;\n\n default:\n vtkErrorMacro(<<\"Bad data description!\");\n return VTK_NULL_ELEMENT;\n }\n}\n\nvtkCell *vtkStructuredGrid::GetCell(int cellId)\n{\n static vtkVertex vertex;\n static vtkLine line;\n static vtkQuad quad;\n static vtkHexahedron hexa;\n static vtkCell *cell;\n int idx;\n int i, j, k;\n int d01, offset1, offset2;\n \n \/\/ Make sure data is defined\n if ( ! this->Points )\n {\n vtkErrorMacro (<<\"No data\");\n return NULL;\n }\n \n switch (this->DataDescription)\n {\n case VTK_SINGLE_POINT: \/\/ cellId can only be = 0\n cell = &vertex;\n cell->PointIds.InsertId(0,0);\n break;\n\n case VTK_X_LINE:\n cell = &line;\n cell->PointIds.InsertId(0,cellId);\n cell->PointIds.InsertId(1,cellId+1);\n break;\n\n case VTK_Y_LINE:\n cell = &line;\n cell->PointIds.InsertId(0,cellId);\n cell->PointIds.InsertId(1,cellId+1);\n break;\n\n case VTK_Z_LINE:\n cell = &line;\n cell->PointIds.InsertId(0,cellId);\n cell->PointIds.InsertId(1,cellId+1);\n break;\n\n case VTK_XY_PLANE:\n cell = &quad;\n i = cellId % (this->Dimensions[0]-1);\n j = cellId \/ (this->Dimensions[0]-1);\n idx = i + j*this->Dimensions[0];\n offset1 = 1;\n offset2 = this->Dimensions[0];\n\n cell->PointIds.InsertId(0,idx);\n cell->PointIds.InsertId(1,idx+offset1);\n cell->PointIds.InsertId(2,idx+offset1+offset2);\n cell->PointIds.InsertId(3,idx+offset2);\n break;\n\n case VTK_YZ_PLANE:\n cell = &quad;\n j = cellId % (this->Dimensions[1]-1);\n k = cellId \/ (this->Dimensions[1]-1);\n idx = j + k*this->Dimensions[1];\n offset1 = 1;\n offset2 = this->Dimensions[1];\n\n cell->PointIds.InsertId(0,idx);\n cell->PointIds.InsertId(1,idx+offset1);\n cell->PointIds.InsertId(2,idx+offset1+offset2);\n cell->PointIds.InsertId(3,idx+offset2);\n break;\n\n case VTK_XZ_PLANE:\n cell = &quad;\n i = cellId % (this->Dimensions[0]-1);\n k = cellId \/ (this->Dimensions[0]-1);\n idx = i + k*this->Dimensions[0];\n offset1 = 1;\n offset2 = this->Dimensions[0];\n\n cell->PointIds.InsertId(0,idx);\n cell->PointIds.InsertId(1,idx+offset1);\n cell->PointIds.InsertId(2,idx+offset1+offset2);\n cell->PointIds.InsertId(3,idx+offset2);\n break;\n\n case VTK_XYZ_GRID:\n cell = &hexa;\n d01 = this->Dimensions[0]*this->Dimensions[1];\n i = cellId % (this->Dimensions[0] - 1);\n j = (cellId \/ (this->Dimensions[0] - 1)) % (this->Dimensions[1] - 1);\n k = cellId \/ ((this->Dimensions[0] - 1) * (this->Dimensions[1] - 1));\n idx = i+ j*this->Dimensions[0] + k*d01;\n offset1 = 1;\n offset2 = this->Dimensions[0];\n\n cell->PointIds.InsertId(0,idx);\n cell->PointIds.InsertId(1,idx+offset1);\n cell->PointIds.InsertId(2,idx+offset1+offset2);\n cell->PointIds.InsertId(3,idx+offset2);\n idx += d01;\n cell->PointIds.InsertId(4,idx);\n cell->PointIds.InsertId(5,idx+offset1);\n cell->PointIds.InsertId(6,idx+offset1+offset2);\n cell->PointIds.InsertId(7,idx+offset2);\n break;\n }\n\n \/\/ Extract point coordinates and point ids. NOTE: the ordering of the vtkQuad\n \/\/ and vtkHexahedron cells are tricky.\n int NumberOfIds = cell->PointIds.GetNumberOfIds();\n for (i=0; i<NumberOfIds; i++)\n {\n idx = cell->PointIds.GetId(i);\n cell->Points.InsertPoint(i,this->Points->GetPoint(idx));\n }\n\n return cell;\n}\n\n\/\/ Description:\n\/\/ Turn on data blanking. Data blanking is the ability to turn off\n\/\/ portions of the grid when displaying or operating on it. Some data\n\/\/ (like finite difference data) routinely turns off data to simulate\n\/\/ solid obstacles.\nvoid vtkStructuredGrid::BlankingOn()\n{\n if (!this->Blanking)\n {\n this->Blanking = 1;\n this->Modified();\n\n if ( !this->PointVisibility )\n {\n this->AllocatePointVisibility();\n }\n }\n}\n\nvoid vtkStructuredGrid::AllocatePointVisibility()\n{\n if ( !this->PointVisibility )\n {\n this->PointVisibility = \n new vtkBitScalars(this->GetNumberOfPoints(),1000);\n this->PointVisibility->Register((vtkObject *)this);\n for (int i=0; i<this->GetNumberOfPoints(); i++)\n {\n this->PointVisibility->InsertScalar(i,1);\n }\n this->PointVisibility->Delete();\n }\n}\n\n\/\/ Description:\n\/\/ Turn off data blanking.\nvoid vtkStructuredGrid::BlankingOff()\n{\n if (this->Blanking)\n {\n this->Blanking = 0;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Turn off a particular data point.\nvoid vtkStructuredGrid::BlankPoint(int ptId)\n{\n if ( !this->PointVisibility ) this->AllocatePointVisibility();\n this->PointVisibility->InsertScalar(ptId,0);\n}\n\n\/\/ Description:\n\/\/ Turn on a particular data point.\nvoid vtkStructuredGrid::UnBlankPoint(int ptId)\n{\n if ( !this->PointVisibility ) this->AllocatePointVisibility();\n this->PointVisibility->InsertScalar(ptId,1);\n}\n\n\/\/ Description:\n\/\/ Set dimensions of structured grid dataset.\nvoid vtkStructuredGrid::SetDimensions(int i, int j, int k)\n{\n int dim[3];\n\n dim[0] = i;\n dim[1] = j;\n dim[2] = k;\n this->SetDimensions(dim);\n}\n\n\/\/ Description:\n\/\/ Set dimensions of structured grid dataset.\nvoid vtkStructuredGrid::SetDimensions(int dim[3])\n{\n int returnStatus=this->StructuredData.SetDimensions(dim,this->Dimensions);\n\n if ( returnStatus > -1 ) \n {\n this->DataDescription = returnStatus;\n this->Modified();\n }\n}\n\nvoid vtkStructuredGrid::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkPointSet::PrintSelf(os,indent);\n\n os << indent << \"Dimensions: (\" << this->Dimensions[0] << \", \"\n << this->Dimensions[1] << \", \"\n << this->Dimensions[2] << \")\\n\";\n\n os << indent << \"Blanking: \" << (this->Blanking ? \"On\\n\" : \"Off\\n\");\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <opencv2\/objdetect\/objdetect.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n\n#include <iostream>\n#include <stdio.h>\n\n\/\/ g++ webcam_recognise.cpp `pkg-config --cflags --libs opencv` -I\/usr\/include\/opencv2\/\n\nusing namespace std;\nusing namespace cv;\n\n\/\/ Grab the next camera frame. Waits until the next frame is ready, and\n\/\/ provides direct access to it, so do NOT modify or free the returned image!\n\/\/ Will automatically initialize the camera on the first frame.\nIplImage* getCameraFrame(CvCapture* &camera)\n{\n\tIplImage *frame;\n\tint w, h;\n\n\t\/\/ If the camera hasn't been initialized, then open it.\n\tif (!camera) {\n\t\tprintf(\"Acessing the camera ...\\n\");\n\t\tcamera = cvCreateCameraCapture( 0 );\n\t\tif (!camera) {\n\t\t\tprintf(\"Couldn't access the camera.\\n\");\n\t\t\texit(1);\n\t\t}\n\t\t\/\/ Try to set the camera resolution to 320 x 240.\n\t\tcvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, 320);\n\t\tcvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_HEIGHT, 240);\n\t\t\/\/ Get the first frame, to make sure the camera is initialized.\n\t\tframe = cvQueryFrame( camera );\n\t\tif (frame) {\n\t\t\tw = frame->width;\n\t\t\th = frame->height;\n\t\t\tprintf(\"Got the camera at %dx%d resolution.\\n\", w, h);\n\t\t}\n\t\t\/\/ Wait a little, so that the camera can auto-adjust its brightness.\n\t\tsleep(1000);\t\/\/ (in milliseconds)\n\t}\n\n\t\/\/ Wait until the next camera frame is ready, then grab it.\n\tframe = cvQueryFrame( camera );\n\tif (!frame) {\n\t\tprintf(\"Couldn't grab a camera frame.\\n\");\n\t\texit(1);\n\t}\n\treturn frame;\n}\n<commit_msg>typo lint<commit_after>#include <opencv2\/objdetect\/objdetect.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n\n#include <iostream>\n#include <stdio.h>\n\n\/\/ g++ webcam_recognise.cpp `pkg-config --cflags --libs opencv` -I\/usr\/include\/opencv2\/\n\nusing namespace std;\nusing namespace cv;\n\n\/\/ Grab the next camera frame. Waits until the next frame is ready, and\n\/\/ provides direct access to it, so do NOT modify or free the returned image!\n\/\/ Will automatically initialize the camera on the first frame.\nIplImage* getCameraFrame(CvCapture* &camera) {\n\tIplImage *frame;\n\tint w, h;\n\n\t\/\/ If the camera hasn't been initialized, then open it.\n\tif (!camera) {\n\t\tprintf(\"Acessing the camera ...\\n\");\n\t\tcamera = cvCreateCameraCapture( 0 );\n\t\tif (!camera) {\n\t\t\tprintf(\"Couldn't access the camera.\\n\");\n\t\t\texit(1);\n\t\t}\n\t\t\/\/ Try to set the camera resolution to 320 x 240.\n\t\tcvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, 320);\n\t\tcvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_HEIGHT, 240);\n\t\t\/\/ Get the first frame, to make sure the camera is initialized.\n\t\tframe = cvQueryFrame( camera );\n\t\tif (frame) {\n\t\t\tw = frame->width;\n\t\t\th = frame->height;\n\t\t\tprintf(\"Got the camera at %dx%d resolution.\\n\", w, h);\n\t\t}\n\t\t\/\/ Wait a little, so that the camera can auto-adjust its brightness.\n\t\tsleep(1000);\t\/\/ (in milliseconds)\n\t}\n\n\t\/\/ Wait until the next camera frame is ready, then grab it.\n\tframe = cvQueryFrame( camera );\n\tif (!frame) {\n\t\tprintf(\"Couldn't grab a camera frame.\\n\");\n\t\texit(1);\n\t}\n\treturn frame;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2014 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/ui\/loop_win.h\"\n\n#include \"xenia\/base\/assert.h\"\n\nnamespace xe {\nnamespace ui {\n\nstd::unique_ptr<Loop> Loop::Create() { return std::make_unique<Win32Loop>(); }\n\nWin32Loop::Win32Loop() : thread_id_(0) {\n timer_queue_ = CreateTimerQueue();\n\n xe::threading::Fence init_fence;\n thread_ = std::thread([&init_fence, this]() {\n xe::threading::set_name(\"Win32 Loop\");\n thread_id_ = GetCurrentThreadId();\n\n \/\/ Make a Win32 call to enable the thread queue.\n MSG msg;\n PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);\n\n init_fence.Signal();\n\n ThreadMain();\n\n quit_fence_.Signal();\n });\n init_fence.Wait();\n}\n\nWin32Loop::~Win32Loop() {\n Quit();\n thread_.join();\n\n DeleteTimerQueueEx(timer_queue_, INVALID_HANDLE_VALUE);\n std::lock_guard<std::mutex> lock(pending_timers_mutex_);\n while (!pending_timers_.empty()) {\n auto timer = pending_timers_.back();\n pending_timers_.pop_back();\n delete timer;\n }\n}\n\nvoid Win32Loop::ThreadMain() {\n MSG msg;\n while (!should_exit_) {\n DWORD result =\n MsgWaitForMultipleObjectsEx(0, nullptr, INFINITE, QS_ALLINPUT, 0);\n\n if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n \/\/ Process queued functions.\n std::lock_guard<std::mutex> lock(posted_functions_mutex_);\n for (auto it = posted_functions_.begin(); it != posted_functions_.end();) {\n (*it).Call();\n it = posted_functions_.erase(it);\n }\n }\n\n UIEvent e(nullptr);\n on_quit(&e);\n}\n\nbool Win32Loop::is_on_loop_thread() {\n return thread_id_ == GetCurrentThreadId();\n}\n\nvoid Win32Loop::Post(std::function<void()> fn) {\n assert_true(thread_id_ != 0);\n {\n std::lock_guard<std::mutex> lock(posted_functions_mutex_);\n PostedFn posted_fn(fn);\n posted_functions_.push_back(posted_fn);\n }\n\n while (!PostThreadMessage(thread_id_, WM_NULL, 0, 0)) {\n Sleep(1);\n }\n}\n\nvoid Win32Loop::TimerQueueCallback(void* context, uint8_t) {\n auto timer = reinterpret_cast<PendingTimer*>(context);\n auto loop = timer->loop;\n auto fn = std::move(timer->fn);\n DeleteTimerQueueTimer(timer->timer_queue, timer->timer_handle, NULL);\n {\n std::lock_guard<std::mutex> lock(loop->pending_timers_mutex_);\n loop->pending_timers_.remove(timer);\n }\n delete timer;\n loop->Post(std::move(fn));\n}\n\nvoid Win32Loop::PostDelayed(std::function<void()> fn, uint64_t delay_millis) {\n if (!delay_millis) {\n Post(std::move(fn));\n return;\n }\n auto timer = new PendingTimer();\n timer->loop = this;\n timer->timer_queue = timer_queue_;\n timer->fn = std::move(fn);\n {\n std::lock_guard<std::mutex> lock(pending_timers_mutex_);\n pending_timers_.push_back(timer);\n }\n CreateTimerQueueTimer(&timer->timer_handle, timer_queue_,\n WAITORTIMERCALLBACK(TimerQueueCallback), timer,\n DWORD(delay_millis), 0,\n WT_EXECUTEINTIMERTHREAD | WT_EXECUTEONLYONCE);\n}\n\nvoid Win32Loop::Quit() {\n assert_true(thread_id_ != 0);\n should_exit_ = true;\n while (!PostThreadMessage(thread_id_, WM_NULL, 0, 0)) {\n Sleep(1);\n }\n}\n\nvoid Win32Loop::AwaitQuit() { quit_fence_.Wait(); }\n\n} \/\/ namespace ui\n} \/\/ namespace xe\n<commit_msg>Fix UI thread not waking up from input<commit_after>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2014 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/ui\/loop_win.h\"\n\n#include \"xenia\/base\/assert.h\"\n\nnamespace xe {\nnamespace ui {\n\nstd::unique_ptr<Loop> Loop::Create() { return std::make_unique<Win32Loop>(); }\n\nWin32Loop::Win32Loop() : thread_id_(0) {\n timer_queue_ = CreateTimerQueue();\n\n xe::threading::Fence init_fence;\n thread_ = std::thread([&init_fence, this]() {\n xe::threading::set_name(\"Win32 Loop\");\n thread_id_ = GetCurrentThreadId();\n\n \/\/ Make a Win32 call to enable the thread queue.\n MSG msg;\n PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);\n\n init_fence.Signal();\n\n ThreadMain();\n\n quit_fence_.Signal();\n });\n init_fence.Wait();\n}\n\nWin32Loop::~Win32Loop() {\n Quit();\n thread_.join();\n\n DeleteTimerQueueEx(timer_queue_, INVALID_HANDLE_VALUE);\n std::lock_guard<std::mutex> lock(pending_timers_mutex_);\n while (!pending_timers_.empty()) {\n auto timer = pending_timers_.back();\n pending_timers_.pop_back();\n delete timer;\n }\n}\n\nvoid Win32Loop::ThreadMain() {\n MSG msg;\n while (!should_exit_ && GetMessage(&msg, NULL, 0, 0)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n\n \/\/ Process queued functions.\n std::lock_guard<std::mutex> lock(posted_functions_mutex_);\n for (auto it = posted_functions_.begin(); it != posted_functions_.end();) {\n (*it).Call();\n it = posted_functions_.erase(it);\n }\n }\n\n UIEvent e(nullptr);\n on_quit(&e);\n}\n\nbool Win32Loop::is_on_loop_thread() {\n return thread_id_ == GetCurrentThreadId();\n}\n\nvoid Win32Loop::Post(std::function<void()> fn) {\n assert_true(thread_id_ != 0);\n {\n std::lock_guard<std::mutex> lock(posted_functions_mutex_);\n PostedFn posted_fn(fn);\n posted_functions_.push_back(posted_fn);\n }\n\n while (!PostThreadMessage(thread_id_, WM_NULL, 0, 0)) {\n Sleep(1);\n }\n}\n\nvoid Win32Loop::TimerQueueCallback(void* context, uint8_t) {\n auto timer = reinterpret_cast<PendingTimer*>(context);\n auto loop = timer->loop;\n auto fn = std::move(timer->fn);\n DeleteTimerQueueTimer(timer->timer_queue, timer->timer_handle, NULL);\n {\n std::lock_guard<std::mutex> lock(loop->pending_timers_mutex_);\n loop->pending_timers_.remove(timer);\n }\n delete timer;\n loop->Post(std::move(fn));\n}\n\nvoid Win32Loop::PostDelayed(std::function<void()> fn, uint64_t delay_millis) {\n if (!delay_millis) {\n Post(std::move(fn));\n return;\n }\n auto timer = new PendingTimer();\n timer->loop = this;\n timer->timer_queue = timer_queue_;\n timer->fn = std::move(fn);\n {\n std::lock_guard<std::mutex> lock(pending_timers_mutex_);\n pending_timers_.push_back(timer);\n }\n CreateTimerQueueTimer(&timer->timer_handle, timer_queue_,\n WAITORTIMERCALLBACK(TimerQueueCallback), timer,\n DWORD(delay_millis), 0,\n WT_EXECUTEINTIMERTHREAD | WT_EXECUTEONLYONCE);\n}\n\nvoid Win32Loop::Quit() {\n assert_true(thread_id_ != 0);\n should_exit_ = true;\n while (!PostThreadMessage(thread_id_, WM_NULL, 0, 0)) {\n Sleep(1);\n }\n}\n\nvoid Win32Loop::AwaitQuit() { quit_fence_.Wait(); }\n\n} \/\/ namespace ui\n} \/\/ namespace xe\n<|endoftext|>"} {"text":"<commit_before>\/\/ Experimental sample\n\/\/ Sample using ORC JIT: Work in progress\n#include <memory>\n\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/ExecutionEngine\/RTDyldMemoryManager.h\"\n#include \"llvm\/ExecutionEngine\/Orc\/CompileUtils.h\"\n#include \"llvm\/ExecutionEngine\/Orc\/IRCompileLayer.h\"\n#include \"llvm\/ExecutionEngine\/Orc\/ObjectLinkingLayer.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Mangler.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n\nusing namespace llvm;\n\nclass SimpleOrcJIT {\npublic:\n typedef orc::ObjectLinkingLayer<> ObjLayerT;\n typedef orc::IRCompileLayer<ObjLayerT> CompileLayerT;\n typedef CompileLayerT::ModuleSetHandleT ModuleHandleT;\n\n SimpleOrcJIT()\n : TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),\n CompileLayer(ObjectLayer, orc::SimpleCompiler(*TM)) {\n }\n\n TargetMachine &getTargetMachine() { return *TM; }\n\n struct NoLinkingResolver : public RuntimeDyld::SymbolResolver {\n RuntimeDyld::SymbolInfo findSymbol(const std::string &Name) {\n return nullptr;\n }\n RuntimeDyld::SymbolInfo findSymbolInLogicalDylib(const std::string &Name) {\n return nullptr;\n }\n };\n\n ModuleHandleT addModule(std::unique_ptr<Module> M) {\n std::vector<std::unique_ptr<Module>> MS;\n MS.push_back(std::move(M));\n auto H = CompileLayer.addModuleSet(std::move(MS),\n make_unique<SectionMemoryManager>(),\n make_unique<NoLinkingResolver>());\n\n ModuleHandles.push_back(H);\n return H;\n }\n\n void removeModule(ModuleHandleT H) {\n ModuleHandles.erase(\n std::find(ModuleHandles.begin(), ModuleHandles.end(), H));\n CompileLayer.removeModuleSet(H);\n }\n\n orc::JITSymbol findSymbol(const std::string Name) {\n std::string MangledName;\n {\n raw_string_ostream MangledNameStream(MangledName);\n Mangler::getNameWithPrefix(MangledNameStream, Name, DL);\n }\n\n \/\/ Search modules in reverse order: from last added to first added.\n \/\/ This is the opposite of the usual search order for dlsym, but makes more\n \/\/ sense in a REPL where we want to bind to the newest available definition.\n for (auto H : make_range(ModuleHandles.rbegin(), ModuleHandles.rend()))\n if (auto Sym = CompileLayer.findSymbolIn(H, MangledName, true))\n return Sym;\n\n return nullptr;\n }\n\nprivate:\n std::unique_ptr<TargetMachine> TM;\n const DataLayout DL;\n ObjLayerT ObjectLayer;\n CompileLayerT CompileLayer;\n std::vector<ModuleHandleT> ModuleHandles;\n};\n\ntypedef double (*FooTy)(double, double);\n\nint main(int argc, char **argv) {\n if (argc < 2) {\n errs() << \"Usage: \" << argv[0] << \" <IR file>\\n\";\n return 1;\n }\n\n \/\/ Parse the input LLVM IR file into a module.\n SMDiagnostic Err;\n std::unique_ptr<Module> Mod(parseIRFile(argv[1], Err, getGlobalContext()));\n if (!Mod) {\n Err.print(argv[0], errs());\n return 1;\n }\n\n InitializeNativeTarget();\n InitializeNativeTargetAsmPrinter();\n InitializeNativeTargetAsmParser();\n\n SimpleOrcJIT JIT;\n JIT.addModule(std::move(Mod));\n\n orc::JITSymbol FooSym = JIT.findSymbol(\"foo\");\n if (!FooSym) {\n errs() << \"Unable to find symbol 'foo' in module\";\n return 1;\n }\n\n FooTy FooPtr = reinterpret_cast<FooTy>(FooSym.getAddress());\n outs() << \"foo(2.0, 3.0) = \" << FooPtr(2.0, 3.0) << \"\\n\";\n\n return 0;\n}\n<commit_msg>[experimental jit_orc_run sample] more cleanup<commit_after>\/\/ Experimental sample\n\/\/ Sample using ORC JIT: Work in progress\n#include <memory>\n\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/ExecutionEngine\/RTDyldMemoryManager.h\"\n#include \"llvm\/ExecutionEngine\/Orc\/CompileUtils.h\"\n#include \"llvm\/ExecutionEngine\/Orc\/IRCompileLayer.h\"\n#include \"llvm\/ExecutionEngine\/Orc\/ObjectLinkingLayer.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Mangler.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n\nusing namespace llvm;\n\nclass SimpleOrcJIT {\npublic:\n typedef orc::ObjectLinkingLayer<> ObjLayerT;\n typedef orc::IRCompileLayer<ObjLayerT> CompileLayerT;\n typedef CompileLayerT::ModuleSetHandleT ModuleHandleT;\n\n SimpleOrcJIT()\n : TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),\n CompileLayer(ObjectLayer, orc::SimpleCompiler(*TM)) {}\n\n \/\/ A simple SymbolResolver that doesn't support linking by always returning\n \/\/ nullptr.\n struct NoLinkingResolver : public RuntimeDyld::SymbolResolver {\n RuntimeDyld::SymbolInfo findSymbol(const std::string &Name) {\n return nullptr;\n }\n RuntimeDyld::SymbolInfo findSymbolInLogicalDylib(const std::string &Name) {\n return nullptr;\n }\n };\n\n ModuleHandleT addModule(std::unique_ptr<Module> M) {\n std::vector<std::unique_ptr<Module>> MS;\n MS.push_back(std::move(M));\n auto H = CompileLayer.addModuleSet(std::move(MS),\n make_unique<SectionMemoryManager>(),\n make_unique<NoLinkingResolver>());\n\n ModuleHandles.push_back(H);\n return H;\n }\n\n void removeModule(ModuleHandleT H) {\n ModuleHandles.erase(\n std::find(ModuleHandles.begin(), ModuleHandles.end(), H));\n CompileLayer.removeModuleSet(H);\n }\n\n orc::JITSymbol findSymbol(const std::string Name) {\n std::string MangledName;\n {\n raw_string_ostream MangledNameStream(MangledName);\n Mangler::getNameWithPrefix(MangledNameStream, Name, DL);\n }\n\n for (auto H : make_range(ModuleHandles.rbegin(), ModuleHandles.rend())) {\n if (auto Sym = CompileLayer.findSymbolIn(H, MangledName, true)) {\n return Sym;\n }\n }\n\n return nullptr;\n }\n\nprivate:\n std::unique_ptr<TargetMachine> TM;\n const DataLayout DL;\n ObjLayerT ObjectLayer;\n CompileLayerT CompileLayer;\n std::vector<ModuleHandleT> ModuleHandles;\n};\n\ntypedef double (*FooTy)(double, double);\n\nint main(int argc, char **argv) {\n if (argc < 2) {\n errs() << \"Usage: \" << argv[0] << \" <IR file>\\n\";\n return 1;\n }\n\n \/\/ Parse the input LLVM IR file into a module.\n SMDiagnostic Err;\n std::unique_ptr<Module> Mod(parseIRFile(argv[1], Err, getGlobalContext()));\n if (!Mod) {\n Err.print(argv[0], errs());\n return 1;\n }\n\n InitializeNativeTarget();\n InitializeNativeTargetAsmPrinter();\n InitializeNativeTargetAsmParser();\n\n SimpleOrcJIT JIT;\n JIT.addModule(std::move(Mod));\n\n orc::JITSymbol FooSym = JIT.findSymbol(\"foo\");\n if (!FooSym) {\n errs() << \"Unable to find symbol 'foo' in module\";\n return 1;\n }\n\n FooTy FooPtr = reinterpret_cast<FooTy>(FooSym.getAddress());\n outs() << \"foo(2.0, 3.0) = \" << FooPtr(2.0, 3.0) << \"\\n\";\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"include\/toml.h\"\n\n#include <cstring>\n#include <cstdlib>\n#include <vector>\n\nvoid CToml::error(const char *format, ...) {\n char buffer[1024];\n\n va_list args; va_start(args, format);\n vsnprintf(buffer, 1024, format, args);\n va_end(args);\n\n errors_.push_back(CTomlError(buffer, cur_line));\n\n \/\/ Now we skip to the next line\n while (next_char() != '\\n' && cur()) { }\n next_char();\n}\n\nbool CToml::is_whitespace(char c, bool new_line) {\n return c == '\\t' || c == ' ' || (c == '\\n' && new_line);\n}\n\nbool CToml::is_numeric(char c, bool dot) {\n return (c == dot && dot) || (c >= '0' && c <= '9');\n}\n\nbool CToml::is_integer(char *str) {\n \/\/ An integer must have only numeric digits. It may start with with a '-'.\n if (*str == '\\0') return false;\n if (!is_numeric(str[0]) && str[0] != '-') return false;\n\n for (char *ch = str + 1; *ch; ch++) if (!is_numeric(*ch)) return false;\n return true;\n}\n\nbool CToml::is_float(char *str) {\n \/\/ A decimal may have a decimal point and a sign.\n if (*str == '\\0') return false;\n if (!is_numeric(str[0]) && str[0] != '-') return false;\n\n bool decimal = false;\n for (char *ch = str + 1; *ch; ch++) {\n if (*ch == '.') {\n if (decimal) return false; \/\/ Double decimal point\n decimal = true;\n } else if(!is_numeric(*ch)) return false;\n }\n\n return true;\n}\n\nbool CToml::is_datetime(char *str) {\n \/\/ A datetime has the format YYYY-MM-DDThh:mm:ssZ\n \/\/ GCC still has an incomplete support for regex,\n \/\/ so it is not used here\n if (strlen(str) != 20) return false;\n return str[4] == '-' && str[7] == '-' && str[10] == 'T' &&\n str[13] == ':' && str[16] == ':' && str[19] == 'Z';\n}\n\ntm CToml::to_time(char *str) {\n int year, mon, mday, hour, min, sec;\n sscanf(str, \"%d-%d-%dT%d:%d:%dZ\", &year, &mon, &mday, &hour, &min, &sec);\n\n tm date;\n date.tm_year = year - 1900;\n date.tm_mon = mon - 1;\n date.tm_mday = mday;\n date.tm_hour = hour + 1;\n date.tm_min = min;\n date.tm_sec = sec;\n\n return date;\n}\n\nchar CToml::next_char() {\n if (source_str_) cur() == '\\0' ? '\\0' : *(++cur_);\n else {\n char ch = getc(source_file_);\n *cur_ = (ch == EOF ? '\\0' : ch);\n }\n\n if (cur() == '\\n') cur_line++;\n return cur();\n}\n\nchar CToml::next_skip_whitespace(bool new_lines) {\n while(next_char() && is_whitespace(cur(), new_lines)) { }\n return cur();\n}\n\nvoid CToml::expect(char c) {\n if (cur() != c) error(\"Expected '%c'\", c);\n next_char();\n}\n\nvoid CToml::advance(char c, bool new_line) {\n skip_whitespace(new_line);\n expect(c);\n}\n\nvoid CToml::skip_whitespace(bool new_line) {\n if (is_whitespace(cur(), new_line)) next_skip_whitespace(new_line);\n}\n\nvoid CToml::skip_whitespace_and_comments() {\n while (cur() && (is_whitespace(cur(), true) || cur() == '#')) {\n if (cur() == '#') {\n while (cur() && cur() != '\\n') next_char();\n }\n next_char();\n }\n}\n\nCTomlValue CToml::parse_string() {\n \/\/ A string is a double quoted string literal\n std::vector<char> str_buf;\n\n expect('\"');\n while (cur()) {\n char c = cur(); next_char();\n\n \/\/ Handle special characters\n if (c == '\\\\' && cur()) {\n \/\/ TODO(evilncrazy): support null characters\n if (cur() == 't') c = '\\t';\n else if (cur() == 'n') c = '\\n';\n else if (cur() == 'r') c = '\\r';\n else if (cur() == '\"') c = '\"';\n else if (cur() == '\\\\') c = '\\\\';\n else return error(\"Invalid escape character \\\\%c\", cur()), CTomlValue();\n\n next_char();\n } else if (c == '\"') {\n \/\/ String closed in a double quote\n break;\n }\n\n str_buf.push_back(c);\n }\n\n str_buf.push_back('\\0');\n return CTomlValue(&str_buf[0]);\n}\n\nCTomlValue CToml::parse_number() {\n std::vector<char> str_buf;\n\n while (!is_whitespace(cur(), true) && cur() != ',' && cur() != ']') {\n str_buf.push_back(cur());\n next_char();\n }\n\n str_buf.push_back('\\0');\n\n \/\/ Decide what data type it is\n if (is_integer(&str_buf[0])) return CTomlValue(atoll(&str_buf[0]));\n if (is_float(&str_buf[0])) return CTomlValue(atof(&str_buf[0]));\n if (is_datetime(&str_buf[0])) return CTomlValue(to_time(&str_buf[0]));\n else return error(\"\\\"%s\\\" is not a valid value\",\n std::string(&str_buf[0]).c_str()), CTomlValue();\n}\n\nCTomlValue CToml::parse_boolean() {\n std::string str;\n while (!is_whitespace(cur(), true) && cur()) {\n str += cur();\n next_char();\n }\n\n if (str == \"true\") return CTomlValue(true);\n else if(str == \"false\") return CTomlValue(false);\n else return error(\"\\\"%s\\\" is not a valid value\", str.c_str()), CTomlValue();\n}\n\nCTomlValue CToml::parse_array() {\n \/\/ TODO(evilncrazy): Currently, arrays can be heterogenous\n \/\/ that is, each element can be of any type. There is currently\n \/\/ a discussion on whether to switch to heterogenous arrays.\n \/\/ Shall wait and see.\n expect('[');\n\n std::vector<CTomlValue> array;\n while (cur() && cur() != ']') {\n skip_whitespace_and_comments();\n array.push_back(parse_value());\n\n skip_whitespace_and_comments();\n if (cur() == ']') break;\n advance(',');\n skip_whitespace_and_comments(); \/\/ Need this for trailing commas\n }\n\n advance(']');\n return CTomlValue(&array[0], array.size());\n}\n\nstd::string CToml::parse_key_group() {\n expect('[');\n\n \/\/ Read until close bracket\n std::vector<char> str_buf;\n while (cur() && cur() != ']') {\n str_buf.push_back(cur());\n next_char();\n }\n\n expect(']');\n\n str_buf.push_back('\\0');\n return std::string(&str_buf[0]);\n}\n\nCTomlValue CToml::parse_value() {\n if (cur() == '\"') return parse_string();\n if (is_numeric(cur()) || cur() == '-') return parse_number();\n if (cur() == '[') return parse_array();\n return parse_boolean();\n}\n\nstd::string CToml::parse_key() {\n std::vector<char> str_buf;\n while (!is_whitespace(cur()) && cur() && cur() != '=') {\n str_buf.push_back(cur());\n next_char();\n }\n\n str_buf.push_back('\\0');\n return std::string(&str_buf[0]);\n}\n\nvoid CToml::parse() {\n std::string cur_group;\n\n \/\/ Find next non-whitespace character\n while (skip_whitespace_and_comments(), cur()) {\n if(cur() == '[') {\n \/\/ Key group (it's not an array as an array is always a value)\n cur_group = parse_key_group() + \".\";\n } else {\n std::string key = cur_group + parse_key();\n advance('='); skip_whitespace();\n\n CTomlValue value = parse_value();\n if (value.type() != TOML_NULL) {\n \/\/ We check all the prefix key groups to ensure that they haven't\n \/\/ already been defined previously\n size_t dot_pos = 0;\n while (dot_pos = key.find(\".\", dot_pos + 1), dot_pos != std::string::npos) {\n std::string key_group(key, 0, dot_pos);\n if(get(key_group.c_str()).type() != TOML_NULL) {\n error(\"The key '%s' has already been used\", key_group.c_str());\n break;\n }\n }\n\n \/\/ Now check the whole key\n if (get(key.c_str()).type() == TOML_NULL) {\n if (success())\n values_.insert(std::make_pair(key, value));\n } else {\n error(\"The key '%s' has already been used\", key.c_str());\n }\n }\n }\n }\n}\n\nCTomlValue CToml::get(const char *key) const {\n return get(const_cast<char *>(key));\n}\n\nCTomlValue CToml::get(char *key) const {\n auto it = values_.find(std::string(key));\n return it != values_.end() ? it->second : CTomlValue();\n}\n\n\nbool CToml::from(char *str) {\n if (str == NULL) return false;\n\n source_str_ = new char[strlen(str) + 2];\n strcpy(source_str_ + 1, str);\n\n \/\/ When the parser starts, it will call next_char(), which means that\n \/\/ the first character will be skipped. So we put a dummy character\n \/\/ in the front, so nothing gets skipped.\n source_str_[0] = ' ';\n cur_ = source_str_;\n\n return true;\n}\n\nbool CToml::open(const char *file) {\n source_file_ = fopen(file, \"r\");\n cur_ = new char(' '); \/\/ Dummy value\n\n return source_file_ != NULL;\n}<commit_msg>Fix ambiguous call<commit_after>#include \"include\/toml.h\"\n\n#include <cstring>\n#include <cstdlib>\n#include <vector>\n\nvoid CToml::error(const char *format, ...) {\n char buffer[1024];\n\n va_list args; va_start(args, format);\n vsnprintf(buffer, 1024, format, args);\n va_end(args);\n\n errors_.push_back(CTomlError(buffer, cur_line));\n\n \/\/ Now we skip to the next line\n while (next_char() != '\\n' && cur()) { }\n next_char();\n}\n\nbool CToml::is_whitespace(char c, bool new_line) {\n return c == '\\t' || c == ' ' || (c == '\\n' && new_line);\n}\n\nbool CToml::is_numeric(char c, bool dot) {\n return (c == dot && dot) || (c >= '0' && c <= '9');\n}\n\nbool CToml::is_integer(char *str) {\n \/\/ An integer must have only numeric digits. It may start with with a '-'.\n if (*str == '\\0') return false;\n if (!is_numeric(str[0]) && str[0] != '-') return false;\n\n for (char *ch = str + 1; *ch; ch++) if (!is_numeric(*ch)) return false;\n return true;\n}\n\nbool CToml::is_float(char *str) {\n \/\/ A decimal may have a decimal point and a sign.\n if (*str == '\\0') return false;\n if (!is_numeric(str[0]) && str[0] != '-') return false;\n\n bool decimal = false;\n for (char *ch = str + 1; *ch; ch++) {\n if (*ch == '.') {\n if (decimal) return false; \/\/ Double decimal point\n decimal = true;\n } else if(!is_numeric(*ch)) return false;\n }\n\n return true;\n}\n\nbool CToml::is_datetime(char *str) {\n \/\/ A datetime has the format YYYY-MM-DDThh:mm:ssZ\n \/\/ GCC still has an incomplete support for regex,\n \/\/ so it is not used here\n if (strlen(str) != 20) return false;\n return str[4] == '-' && str[7] == '-' && str[10] == 'T' &&\n str[13] == ':' && str[16] == ':' && str[19] == 'Z';\n}\n\ntm CToml::to_time(char *str) {\n int year, mon, mday, hour, min, sec;\n sscanf(str, \"%d-%d-%dT%d:%d:%dZ\", &year, &mon, &mday, &hour, &min, &sec);\n\n tm date;\n date.tm_year = year - 1900;\n date.tm_mon = mon - 1;\n date.tm_mday = mday;\n date.tm_hour = hour + 1;\n date.tm_min = min;\n date.tm_sec = sec;\n\n return date;\n}\n\nchar CToml::next_char() {\n if (source_str_) cur() == '\\0' ? '\\0' : *(++cur_);\n else {\n char ch = getc(source_file_);\n *cur_ = (ch == EOF ? '\\0' : ch);\n }\n\n if (cur() == '\\n') cur_line++;\n return cur();\n}\n\nchar CToml::next_skip_whitespace(bool new_lines) {\n while(next_char() && is_whitespace(cur(), new_lines)) { }\n return cur();\n}\n\nvoid CToml::expect(char c) {\n if (cur() != c) error(\"Expected '%c'\", c);\n next_char();\n}\n\nvoid CToml::advance(char c, bool new_line) {\n skip_whitespace(new_line);\n expect(c);\n}\n\nvoid CToml::skip_whitespace(bool new_line) {\n if (is_whitespace(cur(), new_line)) next_skip_whitespace(new_line);\n}\n\nvoid CToml::skip_whitespace_and_comments() {\n while (cur() && (is_whitespace(cur(), true) || cur() == '#')) {\n if (cur() == '#') {\n while (cur() && cur() != '\\n') next_char();\n }\n next_char();\n }\n}\n\nCTomlValue CToml::parse_string() {\n \/\/ A string is a double quoted string literal\n std::vector<char> str_buf;\n\n expect('\"');\n while (cur()) {\n char c = cur(); next_char();\n\n \/\/ Handle special characters\n if (c == '\\\\' && cur()) {\n \/\/ TODO(evilncrazy): support null characters\n if (cur() == 't') c = '\\t';\n else if (cur() == 'n') c = '\\n';\n else if (cur() == 'r') c = '\\r';\n else if (cur() == '\"') c = '\"';\n else if (cur() == '\\\\') c = '\\\\';\n else return error(\"Invalid escape character \\\\%c\", cur()), CTomlValue();\n\n next_char();\n } else if (c == '\"') {\n \/\/ String closed in a double quote\n break;\n }\n\n str_buf.push_back(c);\n }\n\n str_buf.push_back('\\0');\n return CTomlValue(&str_buf[0]);\n}\n\nCTomlValue CToml::parse_number() {\n std::vector<char> str_buf;\n\n while (!is_whitespace(cur(), true) && cur() != ',' && cur() != ']') {\n str_buf.push_back(cur());\n next_char();\n }\n\n str_buf.push_back('\\0');\n\n \/\/ Decide what data type it is\n if (is_integer(&str_buf[0])) return CTomlValue(int64_t(atoll(&str_buf[0])));\n if (is_float(&str_buf[0])) return CTomlValue(atof(&str_buf[0]));\n if (is_datetime(&str_buf[0])) return CTomlValue(to_time(&str_buf[0]));\n else return error(\"\\\"%s\\\" is not a valid value\",\n std::string(&str_buf[0]).c_str()), CTomlValue();\n}\n\nCTomlValue CToml::parse_boolean() {\n std::string str;\n while (!is_whitespace(cur(), true) && cur()) {\n str += cur();\n next_char();\n }\n\n if (str == \"true\") return CTomlValue(true);\n else if(str == \"false\") return CTomlValue(false);\n else return error(\"\\\"%s\\\" is not a valid value\", str.c_str()), CTomlValue();\n}\n\nCTomlValue CToml::parse_array() {\n \/\/ TODO(evilncrazy): Currently, arrays can be heterogenous\n \/\/ that is, each element can be of any type. There is currently\n \/\/ a discussion on whether to switch to heterogenous arrays.\n \/\/ Shall wait and see.\n expect('[');\n\n std::vector<CTomlValue> array;\n while (cur() && cur() != ']') {\n skip_whitespace_and_comments();\n array.push_back(parse_value());\n\n skip_whitespace_and_comments();\n if (cur() == ']') break;\n advance(',');\n skip_whitespace_and_comments(); \/\/ Need this for trailing commas\n }\n\n advance(']');\n return CTomlValue(&array[0], array.size());\n}\n\nstd::string CToml::parse_key_group() {\n expect('[');\n\n \/\/ Read until close bracket\n std::vector<char> str_buf;\n while (cur() && cur() != ']') {\n str_buf.push_back(cur());\n next_char();\n }\n\n expect(']');\n\n str_buf.push_back('\\0');\n return std::string(&str_buf[0]);\n}\n\nCTomlValue CToml::parse_value() {\n if (cur() == '\"') return parse_string();\n if (is_numeric(cur()) || cur() == '-') return parse_number();\n if (cur() == '[') return parse_array();\n return parse_boolean();\n}\n\nstd::string CToml::parse_key() {\n std::vector<char> str_buf;\n while (!is_whitespace(cur()) && cur() && cur() != '=') {\n str_buf.push_back(cur());\n next_char();\n }\n\n str_buf.push_back('\\0');\n return std::string(&str_buf[0]);\n}\n\nvoid CToml::parse() {\n std::string cur_group;\n\n \/\/ Find next non-whitespace character\n while (skip_whitespace_and_comments(), cur()) {\n if(cur() == '[') {\n \/\/ Key group (it's not an array as an array is always a value)\n cur_group = parse_key_group() + \".\";\n } else {\n std::string key = cur_group + parse_key();\n advance('='); skip_whitespace();\n\n CTomlValue value = parse_value();\n if (value.type() != TOML_NULL) {\n \/\/ We check all the prefix key groups to ensure that they haven't\n \/\/ already been defined previously\n size_t dot_pos = 0;\n while (dot_pos = key.find(\".\", dot_pos + 1), dot_pos != std::string::npos) {\n std::string key_group(key, 0, dot_pos);\n if(get(key_group.c_str()).type() != TOML_NULL) {\n error(\"The key '%s' has already been used\", key_group.c_str());\n break;\n }\n }\n\n \/\/ Now check the whole key\n if (get(key.c_str()).type() == TOML_NULL) {\n if (success())\n values_.insert(std::make_pair(key, value));\n } else {\n error(\"The key '%s' has already been used\", key.c_str());\n }\n }\n }\n }\n}\n\nCTomlValue CToml::get(const char *key) const {\n return get(const_cast<char *>(key));\n}\n\nCTomlValue CToml::get(char *key) const {\n auto it = values_.find(std::string(key));\n return it != values_.end() ? it->second : CTomlValue();\n}\n\n\nbool CToml::from(char *str) {\n if (str == NULL) return false;\n\n source_str_ = new char[strlen(str) + 2];\n strcpy(source_str_ + 1, str);\n\n \/\/ When the parser starts, it will call next_char(), which means that\n \/\/ the first character will be skipped. So we put a dummy character\n \/\/ in the front, so nothing gets skipped.\n source_str_[0] = ' ';\n cur_ = source_str_;\n\n return true;\n}\n\nbool CToml::open(const char *file) {\n source_file_ = fopen(file, \"r\");\n cur_ = new char(' '); \/\/ Dummy value\n\n return source_file_ != NULL;\n}<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2008, Avian Contributors\n\n Permission to use, copy, modify, and\/or distribute this software\n for any purpose with or without fee is hereby granted, provided\n that the above copyright notice and this permission notice appear\n in all copies.\n\n There is NO WARRANTY for this software. See license.txt for\n details. *\/\n\n#include \"assembler.h\"\n#include \"vector.h\"\n\nusing namespace vm;\n\nnamespace {\n\nenum Register {\n rax = 0,\n rcx = 1,\n rdx = 2,\n rbx = 3,\n rsp = 4,\n rbp = 5,\n rsi = 6,\n rdi = 7,\n r8 = 8,\n r9 = 9,\n r10 = 10,\n r11 = 11,\n r12 = 12,\n r13 = 13,\n r14 = 14,\n r15 = 15,\n};\n\nclass Task {\n public:\n Task(Task* next): next(next) { }\n\n virtual ~Task() { }\n\n virtual void run(uint8_t* code) = 0;\n\n Task* next;\n};\n\nclass MyAssembler: public Assembler {\n public:\n MyAssembler(System* s, Allocator* a): s(s), code(s, a, 1024), tasks(0) { }\n\n virtual unsigned registerCount() {\n return BytesPerWord == 4 ? 8 : 16;\n }\n\n virtual int base() {\n return rbp;\n }\n\n virtual int stack() {\n return rsp;\n }\n\n virtual int thread() {\n return rbx;\n }\n\n virtual int returnLow() {\n return rax;\n }\n\n virtual int returnHigh() {\n return (BytesPerWord == 4 ? rdx : NoRegister);\n }\n\n virtual unsigned argumentRegisterCount() {\n return (BytesPerWord == 4 ? 0 : 6);\n }\n\n virtual int argumentRegister(unsigned index) {\n assert(s, BytesPerWord == 8);\n\n switch (index) {\n case 0:\n return rdi;\n case 1:\n return rsi;\n case 2:\n return rdx;\n case 3:\n return rcx;\n case 4:\n return r8;\n case 5:\n return r9;\n default:\n abort(s);\n }\n }\n\n virtual int stackSyncRegister(unsigned index) {\n switch (index) {\n case 0:\n return rax;\n case 1:\n return rcx;\n case 2:\n return rdx;\n case 3:\n return rsi;\n case 4:\n return rdi;\n default:\n abort(s);\n }\n }\n\n virtual void getTargets(UnaryOperation \/*op*\/, unsigned \/*size*\/,\n Register* r)\n {\n \/\/ todo\n r->low = NoRegister;\n r->high = NoRegister;\n }\n\n virtual void getTargets(BinaryOperation \/*op*\/, unsigned \/*size*\/,\n Register* a, Register* b)\n {\n \/\/ todo\n a->low = NoRegister;\n a->high = NoRegister;\n b->low = NoRegister;\n b->high = NoRegister;\n }\n\n virtual void apply(Operation \/*op*\/) {\n \/\/ todo\n abort(s);\n }\n\n virtual void apply(UnaryOperation \/*op*\/, unsigned \/*size*\/,\n OperandType \/*type*\/, Operand* \/*operand*\/)\n {\n \/\/ todo\n abort(s);\n }\n\n virtual void apply(BinaryOperation \/*op*\/, unsigned \/*size*\/,\n OperandType \/*aType*\/, Operand* \/*a*\/,\n OperandType \/*bType*\/, Operand* \/*b*\/)\n {\n \/\/ todo\n abort(s);\n }\n\n virtual void writeTo(uint8_t* dst) {\n memcpy(dst, code.data, code.length());\n \n for (Task* t = tasks; t; t = t->next) {\n t->run(dst);\n }\n }\n\n virtual unsigned length() {\n return code.length();\n }\n\n virtual void updateCall(void* returnAddress, void* newTarget) {\n uint8_t* instruction = static_cast<uint8_t*>(returnAddress) - 5;\n assert(s, *instruction == 0xE8);\n assert(s, reinterpret_cast<uintptr_t>(instruction + 1) % 4 == 0);\n\n int32_t v = static_cast<uint8_t*>(newTarget)\n - static_cast<uint8_t*>(returnAddress);\n memcpy(instruction + 1, &v, 4);\n }\n\n System* s;\n Vector code;\n Task* tasks;\n};\n\n} \/\/ namespace\n\nnamespace vm {\n\nAssembler*\nmakeAssembler(System* system, Allocator* allocator, Zone* zone)\n{\n return new (zone->allocate(sizeof(MyAssembler)))\n MyAssembler(system, allocator); \n}\n\n} \/\/ namespace vm\n<commit_msg>remove x86.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2010-2011, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ToHoudiniStringAttribConverter.h\"\n\nusing namespace IECore;\n\nnamespace IECoreHoudini\n{\n\nIE_CORE_DEFINERUNTIMETYPED( ToHoudiniStringVectorAttribConverter );\n\nToHoudiniAttribConverter::Description<ToHoudiniStringVectorAttribConverter> ToHoudiniStringVectorAttribConverter::m_description( StringVectorData::staticTypeId() );\n\nToHoudiniStringVectorAttribConverter::ToHoudiniStringVectorAttribConverter( const IECore::Data *data ) :\n\tToHoudiniAttribConverter( data, \"Converts IECore::StringVectorData to a GB_Attribute on the provided GU_Detail.\" )\n{\n\tm_indicesParameter = new IntVectorParameter( \"indices\", \"the indices into the source StringVectorData\", new IntVectorData() );\n\tparameters()->addParameter( m_indicesParameter );\n}\n\nToHoudiniStringVectorAttribConverter::~ToHoudiniStringVectorAttribConverter()\n{\n}\n\nIntVectorParameterPtr ToHoudiniStringVectorAttribConverter::indicesParameter()\n{\n\treturn m_indicesParameter;\n}\n\nConstIntVectorParameterPtr ToHoudiniStringVectorAttribConverter::indicesParameter() const\n{\n\treturn m_indicesParameter;\n}\n\nGA_RWAttributeRef ToHoudiniStringVectorAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const\n{\n\t\/\/\/ \\todo: this used to be supported. why?\n\tthrow IECore::Exception( \"ToHoudiniStringVectorAttribConverter does not support Detail attributes.\" );\n}\n\nGA_RWAttributeRef ToHoudiniStringVectorAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const\n{\n\tassert( data );\n\n\tconst IECore::StringVectorData *stringVectorData = IECore::runTimeCast<const IECore::StringVectorData>( data );\n\tif ( !stringVectorData )\n\t{\n\t\tthrow IECore::Exception( ( boost::format( \"ToHoudiniStringVectorAttribConverter::doConversion: PrimitiveVariable \\\"%s\\\" does not contain IECore::StringVectorData.\" ) % name ).str() );\n\t}\n\t\n\tGA_RWAttributeRef attrRef = geo->addStringTuple( range.getOwner(), name.c_str(), 1 );\n\tif ( attrRef.isInvalid() )\n\t{\n\t\tthrow IECore::Exception( ( boost::format( \"ToHoudiniStringVectorAttribConverter::doConversion: Invalid GA_RWAttributeRef returned for PrimitiveVariable \\\"%s\\\".\" ) % name ).str() );\n\t}\n\t\n\tif ( !range.isValid() || range.empty() )\n\t{\n\t\treturn attrRef;\n\t}\n\t\n\tGA_Attribute *attr = attrRef.getAttribute();\n\t\n\tconst GA_AIFSharedStringTuple *tuple = attr->getAIFSharedStringTuple();\n\t\n\tUT_StringArray strings;\n\tconst std::vector<std::string> &stringVector = stringVectorData->readable();\n\t\n\tconst std::vector<int> &indices = ((const IECore::IntVectorData *)m_indicesParameter->getValidatedValue())->readable();\n\tif ( indices.empty() || stringVector.empty() )\n\t{\n\t\treturn attrRef;\n\t}\n\t\n\tsize_t i = 0;\n\tsize_t numIndices = indices.size();\n\tfor ( GA_Iterator it=range.begin(); !it.atEnd(), i < numIndices; ++it, ++i )\n\t{\n\t\ttuple->setString( attr, it.getOffset(), stringVector[ indices[i] ].c_str(), 0 );\n\t}\n\t\n\treturn attrRef;\n}\n\nIE_CORE_DEFINERUNTIMETYPED( ToHoudiniStringDetailAttribConverter );\n\nToHoudiniAttribConverter::Description<ToHoudiniStringDetailAttribConverter> ToHoudiniStringDetailAttribConverter::m_description( StringData::staticTypeId() );\n\nToHoudiniStringDetailAttribConverter::ToHoudiniStringDetailAttribConverter( const IECore::Data *data ) :\n\tToHoudiniAttribConverter( data, \"Converts IECore::StringData to a GB_Attribute on the provided GU_Detail.\" )\n{\n}\n\nToHoudiniStringDetailAttribConverter::~ToHoudiniStringDetailAttribConverter()\n{\n}\n\nGA_RWAttributeRef ToHoudiniStringDetailAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const\n{\n\tassert( data );\n\n\tconst StringData *stringData = IECore::runTimeCast<const StringData>( data );\n\tif ( !stringData )\n\t{\n\t\tthrow IECore::Exception( ( boost::format( \"ToHoudiniStringDetailAttribConverter::doConversion: PrimitiveVariable \\\"%s\\\" does not contain IECore::StringData.\" ) % name ).str() );\n\t}\n\n\tGA_RWAttributeRef attrRef = geo->addStringTuple( GA_ATTRIB_DETAIL, name.c_str(), 1 );\n\tif ( attrRef.isInvalid() )\n\t{\n\t\tthrow IECore::Exception( ( boost::format( \"ToHoudiniStringDetailAttribConverter::doConversion: Invalid GA_RWAttributeRef returned for PrimitiveVariable \\\"%s\\\".\" ) % name ).str() );\n\t}\n\t\n\tGA_Attribute *attr = attrRef.getAttribute();\n\tattr->getAIFSharedStringTuple()->setString( attr, 0, stringData->readable().c_str(), 0 );\n\t\n\treturn attrRef;\n}\n\nGA_RWAttributeRef ToHoudiniStringDetailAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const\n{\n\tthrow IECore::Exception( \"ToHoudiniStringDetailAttribConverter does not support Element attributes.\" );\n}\n\n} \/\/ namespace IECoreHoudini\n<commit_msg>fixing todo. it was for backwards compatibility with old models, but didnt do the right thing anyways... just giving a warning rather than throwing<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2010-2011, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/MessageHandler.h\"\n\n#include \"ToHoudiniStringAttribConverter.h\"\n\nusing namespace IECore;\n\nnamespace IECoreHoudini\n{\n\nIE_CORE_DEFINERUNTIMETYPED( ToHoudiniStringVectorAttribConverter );\n\nToHoudiniAttribConverter::Description<ToHoudiniStringVectorAttribConverter> ToHoudiniStringVectorAttribConverter::m_description( StringVectorData::staticTypeId() );\n\nToHoudiniStringVectorAttribConverter::ToHoudiniStringVectorAttribConverter( const IECore::Data *data ) :\n\tToHoudiniAttribConverter( data, \"Converts IECore::StringVectorData to a GB_Attribute on the provided GU_Detail.\" )\n{\n\tm_indicesParameter = new IntVectorParameter( \"indices\", \"the indices into the source StringVectorData\", new IntVectorData() );\n\tparameters()->addParameter( m_indicesParameter );\n}\n\nToHoudiniStringVectorAttribConverter::~ToHoudiniStringVectorAttribConverter()\n{\n}\n\nIntVectorParameterPtr ToHoudiniStringVectorAttribConverter::indicesParameter()\n{\n\treturn m_indicesParameter;\n}\n\nConstIntVectorParameterPtr ToHoudiniStringVectorAttribConverter::indicesParameter() const\n{\n\treturn m_indicesParameter;\n}\n\nGA_RWAttributeRef ToHoudiniStringVectorAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const\n{\n\tIECore::msg( IECore::MessageHandler::Error, \"ToHoudiniStringVectorAttribConverter\", \"Does not support Detail attributes.\" );\n\treturn GA_RWAttributeRef();\n}\n\nGA_RWAttributeRef ToHoudiniStringVectorAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const\n{\n\tassert( data );\n\n\tconst IECore::StringVectorData *stringVectorData = IECore::runTimeCast<const IECore::StringVectorData>( data );\n\tif ( !stringVectorData )\n\t{\n\t\tthrow IECore::Exception( ( boost::format( \"ToHoudiniStringVectorAttribConverter::doConversion: PrimitiveVariable \\\"%s\\\" does not contain IECore::StringVectorData.\" ) % name ).str() );\n\t}\n\t\n\tGA_RWAttributeRef attrRef = geo->addStringTuple( range.getOwner(), name.c_str(), 1 );\n\tif ( attrRef.isInvalid() )\n\t{\n\t\tthrow IECore::Exception( ( boost::format( \"ToHoudiniStringVectorAttribConverter::doConversion: Invalid GA_RWAttributeRef returned for PrimitiveVariable \\\"%s\\\".\" ) % name ).str() );\n\t}\n\t\n\tif ( !range.isValid() || range.empty() )\n\t{\n\t\treturn attrRef;\n\t}\n\t\n\tGA_Attribute *attr = attrRef.getAttribute();\n\t\n\tconst GA_AIFSharedStringTuple *tuple = attr->getAIFSharedStringTuple();\n\t\n\tUT_StringArray strings;\n\tconst std::vector<std::string> &stringVector = stringVectorData->readable();\n\t\n\tconst std::vector<int> &indices = ((const IECore::IntVectorData *)m_indicesParameter->getValidatedValue())->readable();\n\tif ( indices.empty() || stringVector.empty() )\n\t{\n\t\treturn attrRef;\n\t}\n\t\n\tsize_t i = 0;\n\tsize_t numIndices = indices.size();\n\tfor ( GA_Iterator it=range.begin(); !it.atEnd(), i < numIndices; ++it, ++i )\n\t{\n\t\ttuple->setString( attr, it.getOffset(), stringVector[ indices[i] ].c_str(), 0 );\n\t}\n\t\n\treturn attrRef;\n}\n\nIE_CORE_DEFINERUNTIMETYPED( ToHoudiniStringDetailAttribConverter );\n\nToHoudiniAttribConverter::Description<ToHoudiniStringDetailAttribConverter> ToHoudiniStringDetailAttribConverter::m_description( StringData::staticTypeId() );\n\nToHoudiniStringDetailAttribConverter::ToHoudiniStringDetailAttribConverter( const IECore::Data *data ) :\n\tToHoudiniAttribConverter( data, \"Converts IECore::StringData to a GB_Attribute on the provided GU_Detail.\" )\n{\n}\n\nToHoudiniStringDetailAttribConverter::~ToHoudiniStringDetailAttribConverter()\n{\n}\n\nGA_RWAttributeRef ToHoudiniStringDetailAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const\n{\n\tassert( data );\n\n\tconst StringData *stringData = IECore::runTimeCast<const StringData>( data );\n\tif ( !stringData )\n\t{\n\t\tthrow IECore::Exception( ( boost::format( \"ToHoudiniStringDetailAttribConverter::doConversion: PrimitiveVariable \\\"%s\\\" does not contain IECore::StringData.\" ) % name ).str() );\n\t}\n\n\tGA_RWAttributeRef attrRef = geo->addStringTuple( GA_ATTRIB_DETAIL, name.c_str(), 1 );\n\tif ( attrRef.isInvalid() )\n\t{\n\t\tthrow IECore::Exception( ( boost::format( \"ToHoudiniStringDetailAttribConverter::doConversion: Invalid GA_RWAttributeRef returned for PrimitiveVariable \\\"%s\\\".\" ) % name ).str() );\n\t}\n\t\n\tGA_Attribute *attr = attrRef.getAttribute();\n\tattr->getAIFSharedStringTuple()->setString( attr, 0, stringData->readable().c_str(), 0 );\n\t\n\treturn attrRef;\n}\n\nGA_RWAttributeRef ToHoudiniStringDetailAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const\n{\n\tthrow IECore::Exception( \"ToHoudiniStringDetailAttribConverter does not support Element attributes.\" );\n}\n\n} \/\/ namespace IECoreHoudini\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2011,2015 Jeff Donner\n\n Permission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation files\n(the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and\/or sell copies of the Software,\nand to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\n The above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <string>\n#include \"tree_parser.h\"\n#include \"tree-kernel.h\"\n#include \"sentence.h\"\n\nusing namespace std;\n\n\/\/ g++ -g .objs\/node.o .objs\/sentence.o .objs\/tree-kernel.o .objs\/test-tree-kernel.o -L..\/tree-parser -ltree_parser -o test-tree-kernel\n\nstring g_real =\n \"(ROOT (S (VP (MD Must) (VP (VB have) (NP (NN java)))) (. .)))\";\n\n\/\/ oversimple parse\nstring g_dog_eat_dog =\n\"(S\"\n\" (NN dog)\"\n\" (VBP eat)\"\n\" (NN dog))\";\n\n\/\/ oversimple parse\nstring g_dog_eat_fish =\n\"(S\"\n\" (NN dog)\"\n\" (VBP eat)\"\n\" (NN fish))\";\n\nstring g_brought_a_cat =\n\" (VP (V brought)\"\n\" (NP (D a)\"\n\" (N cat)))\"\n ;\n\nTree const* make_tree(string const& tree_text)\n{\n TreeLexer lexer(tree_text);\n TreeParser parser(lexer);\n Tree const* t = 0;\n try {\n t = parser.match_and_eat_tree();\n }\n catch (string& ex) {\n cout << \"failed parse: \" << ex << endl;\n }\n\n\/\/ t->pretty_print(cout, 0);\n\n return t;\n}\n\ndouble kernel_value(string one, string two, bool want_sst_not_st)\n{\n Tree const* t1 = make_tree(one);\n Tree const* t2 = make_tree(two);\n\n cout << \"s1\" << endl;\n Sentence s1(t1);\n cout << \"s2\" << endl;\n Sentence s2(t2);\n\n \/\/ sigma == 1 is SSTs (fragments)\n \/\/ sigma == 0 is STs (whole sub-trees, down to leaves)\n int sigma = want_sst_not_st ? 1 : 0;\n double value = kernel_value(s1, s2, sigma);\n return value;\n}\n\nvoid test_sst(string test_name, string one, string two, double expected)\n{\n cout << test_name << endl;\n double value = kernel_value(one, two, true);\n if (value != expected) {\n cout << \"failed - got: \" << value << \" instead of: \" << expected << endl;\n }\n else\n cout << \" ok\" << endl;\n}\n\nvoid test_st(string test_name, string one, string two, double expected)\n{\n cout << test_name << endl;\n double value = kernel_value(one, two, false);\n if (value != expected) {\n cout << \"failed - got: \" << value << \" instead of: \" << expected << endl;\n }\n else\n cout << \" ok\" << endl;\n}\n\n\nint main()\n{\n \/\/ SSTs are like STs, except that you can\n \/\/ 'break a single leg off of' a pre-terminal, and all off of\n \/\/ an ordinary non-terminal (because it's really just acting as\n \/\/ a child of its parent's rule). So if you include a production\n \/\/ you must include it all. Pre-terminals only \/have\/ one 'leg',\n \/\/ so they're included automatically.\n \/\/\n \/\/ '17' is from the paper\n test_sst(\"brought a cat\", g_brought_a_cat, g_brought_a_cat, 17);\n \/\/ hand-counted; number of non-terminal nodes\n test_st(\"brought a cat\", g_brought_a_cat, g_brought_a_cat, 5);\n\n return 0;\n}\n<commit_msg>added pseudocode for the algorithm to generate all subtrees, use of which will allow more thorough testing<commit_after>\/*\nCopyright (c) 2011,2015 Jeff Donner\n\n Permission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation files\n(the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and\/or sell copies of the Software,\nand to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\n The above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <string>\n#include \"tree_parser.h\"\n#include \"tree-kernel.h\"\n#include \"sentence.h\"\n\nusing namespace std;\n\n\/\/ g++ -g .objs\/node.o .objs\/sentence.o .objs\/tree-kernel.o .objs\/test-tree-kernel.o -L..\/tree-parser -ltree_parser -o test-tree-kernel\n\nstring g_real =\n \"(ROOT (S (VP (MD Must) (VP (VB have) (NP (NN java)))) (. .)))\";\n\n\/\/ oversimple parse\nstring g_dog_eat_dog =\n\"(S\"\n\" (NN dog)\"\n\" (VBP eat)\"\n\" (NN dog))\";\n\n\/\/ oversimple parse\nstring g_dog_eat_fish =\n\"(S\"\n\" (NN dog)\"\n\" (VBP eat)\"\n\" (NN fish))\";\n\nstring g_brought_a_cat =\n\" (VP (V brought)\"\n\" (NP (D a)\"\n\" (N cat)))\"\n ;\n\nTree const* make_tree(string const& tree_text)\n{\n TreeLexer lexer(tree_text);\n TreeParser parser(lexer);\n Tree const* t = 0;\n try {\n t = parser.match_and_eat_tree();\n }\n catch (string& ex) {\n cout << \"failed parse: \" << ex << endl;\n }\n\n\/\/ t->pretty_print(cout, 0);\n\n return t;\n}\n\ndouble kernel_value(string one, string two, bool want_sst_not_st)\n{\n Tree const* t1 = make_tree(one);\n Tree const* t2 = make_tree(two);\n\n cout << \"s1\" << endl;\n Sentence s1(t1);\n cout << \"s2\" << endl;\n Sentence s2(t2);\n\n \/\/ sigma == 1 is SSTs (fragments)\n \/\/ sigma == 0 is STs (whole sub-trees, down to leaves)\n int sigma = want_sst_not_st ? 1 : 0;\n double value = kernel_value(s1, s2, sigma);\n return value;\n}\n\nvoid test_sst(string test_name, string one, string two, double expected)\n{\n cout << test_name << endl;\n double value = kernel_value(one, two, true);\n if (value != expected) {\n cout << \"failed - got: \" << value << \" instead of: \" << expected << endl;\n }\n else\n cout << \" ok\" << endl;\n}\n\nvoid test_st(string test_name, string one, string two, double expected)\n{\n cout << test_name << endl;\n double value = kernel_value(one, two, false);\n if (value != expected) {\n cout << \"failed - got: \" << value << \" instead of: \" << expected << endl;\n }\n else\n cout << \" ok\" << endl;\n}\n\n\/* Yo - to test better, we need more sub-tree'd sentences.\n\n def generate_all_connected_subtrees(node, path-so-far):\n generate powerset of all children of node\n with the empty subset, add path-so-far as a complete subtree\n\n generate_all_connected_subtrees(child, path-so-far + child)\n\n def generate all subtrees(root):\n for node in all root:\n generate_all)connected_subtrees(node, null)\n\n *\/\n\nint main()\n{\n \/\/ SSTs are like STs, except that you can\n \/\/ 'break a single leg off of' a pre-terminal, and all off of\n \/\/ an ordinary non-terminal (because it's really just acting as\n \/\/ a child of its parent's rule). So if you include a production\n \/\/ you must include it all. Pre-terminals only \/have\/ one 'leg',\n \/\/ so they're included automatically.\n \/\/\n \/\/ '17' is from the paper\n test_sst(\"brought a cat\", g_brought_a_cat, g_brought_a_cat, 17);\n \/\/ hand-counted; number of non-terminal nodes\n test_st(\"brought a cat\", g_brought_a_cat, g_brought_a_cat, 5);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"roomsreader.h\"\n\nRRNode::RRNode(TiXmlElement *root)\n{\n this->root = root;\n parent = 0;\n gotoRoot();\n}\n\nRRNode::~RRNode()\n{\n\n}\n\nRRNode *RRNode::gotoElement(string name)\n{\n cursor = findElement(root, name);\n if (!isNull())\n parent = cursor->Parent()->ToElement();\n else\n parent = 0;\n return this;\n}\n\nRRNode *RRNode::gotoRoot()\n{\n cursor = root;\n parent = 0;\n return this;\n}\n\nRRNode *RRNode::gotoChild(string name)\n{\n if(!isNull())\n {\n parent = cursor;\n cursor = cursor->FirstChildElement(name.c_str());\n }\n return this;\n}\n\nRRNode *RRNode::gotoParent()\n{\n cursor = parent;\n if(!isNull())\n {\n parent = cursor->Parent()->ToElement();\n }\n return this;\n}\n\nRRNode *RRNode::gotoNext()\n{\n if(!isNull())\n cursor = cursor->NextSiblingElement(cursor->Value());\n return this;\n}\n\nRRNode *RRNode::appendElement(string name)\n{\n if(!isNull())\n {\n TiXmlElement *new_elem = new TiXmlElement(name.c_str());\n cursor->LinkEndChild(new_elem);\n parent = cursor;\n cursor = new_elem;\n }\n return this;\n}\n\nbool RRNode::isNull()\n{\n bool result = cursor;\n return !result;\n}\n\nint RRNode::attrInt(string name)\n{\n int tmp = 0;\n cursor->QueryIntAttribute(name.c_str(), &tmp);\n return tmp;\n}\n\nfloat RRNode::attrFloat(string name)\n{\n float tmp = 0.0;\n cursor->QueryFloatAttribute(name.c_str(), &tmp);\n return tmp;\n}\n\nstring RRNode::attrStr(string name)\n{\n return cursor->Attribute(name.c_str());\n}\n\nvoid RRNode::setAttr(string name, string value)\n{\n cursor->SetAttribute(name.c_str(), value.c_str());\n}\n\nEvent *RRNode::fetchEvent()\n{\n if (isNull()) return 0;\n Event *event = new Event(attrStr(\"id\"));\n for (gotoChild(\"item_req\"); !isNull(); gotoNext())\n event->addItemReq(attrStr(\"id\"), attrStr(\"value\"));\n gotoParent();\n for (gotoChild(\"var_req\"); !isNull(); gotoNext())\n event->addVarReq(attrStr(\"id\"), attrInt(\"value\"));\n gotoParent();\n for (gotoChild(\"action\"); !isNull(); gotoNext())\n {\n Action *act = event->addAction(attrStr(\"id\"));\n for (gotoChild(\"param\"); !isNull(); gotoNext())\n act->pushParam(attrStr(\"value\"));\n gotoParent();\n }\n gotoParent();\n return event;\n}\n\nRoom *RRNode::fetchRoom()\n{\n if (isNull()) return 0;\n Room *room = new Room(attrStr(\"id\"));\n room->bg(attrStr(\"bg\"));\n for (gotoChild(\"area\"); !isNull(); gotoNext())\n {\n Area *area = room->addArea(attrStr(\"id\"));\n area->size(attrFloat(\"x\"), attrFloat(\"y\"), attrFloat(\"width\"), attrFloat(\"height\"));\n area->setEvent(attrStr(\"event\"));\n }\n gotoParent();\n return room;\n}\n\nItem *RRNode::fetchItem()\n{\n if (isNull()) return 0;\n Item *item = new Item(attrStr(\"id\"));\n item->size(attrFloat(\"x\"), attrFloat(\"y\"), attrFloat(\"width\"), attrFloat(\"height\"));\n item->setEvent(attrStr(\"event\"));\n item->setImage(attrStr(\"image\"));\n item->move(attrStr(\"room\"));\n return item;\n}\n\nDialog *RRNode::fetchDialog()\n{\n if (isNull()) return 0;\n Dialog *d = new Dialog(attrStr(\"id\"), attrStr(\"start\"));\n for (gotoChild(\"step\"); !isNull(); gotoNext())\n {\n DialogStep *step = d->addStep(attrStr(\"id\"), attrStr(\"text\"));\n step->event = fetchEvent();\n for (gotoChild(\"link\"); !isNull(); gotoNext())\n d->addLink(step->id, attrStr(\"id\"), attrStr(\"text\"));\n gotoParent();\n }\n gotoParent();\n return d;\n}\n\nTiXmlElement *RRNode::findElement(TiXmlElement *elem, string name)\n{\n if (elem == 0)\n return 0;\n if (string(elem->Value()) == name)\n return elem;\n TiXmlElement *result = findElement(elem->NextSiblingElement(), name);\n if (result != 0)\n return result;\n result = findElement(elem->FirstChildElement(), name);\n if (result != 0)\n return result;\n return 0;\n}\n\n\nstring floatToStr(const float f)\n{\n std::ostringstream os;\n os << f;\n return os.str();\n}\n\nstring upgradeFrom1To2(string content)\n{\n TiXmlDocument doc;\n doc.Parse(content.c_str());\n RRNode node(doc.RootElement());\n node.gotoElement(\"world\");\n int w = node.attrInt(\"width\");\n int h = node.attrInt(\"height\");\n node.setAttr(\"version\", \"2\");\n for (node.gotoElement(\"items\")->gotoChild(\"item\"); !node.isNull(); node.gotoNext())\n {\n node.setAttr(\"x\", floatToStr(node.attrFloat(\"x\") \/ w));\n node.setAttr(\"y\", floatToStr(node.attrFloat(\"y\") \/ h));\n node.setAttr(\"width\", floatToStr(node.attrFloat(\"width\") \/ w));\n node.setAttr(\"height\", floatToStr(node.attrFloat(\"height\") \/ h));\n }\n\n for (node.gotoElement(\"rooms\")->gotoChild(\"room\"); !node.isNull(); node.gotoNext())\n {\n for (node.gotoChild(\"area\"); !node.isNull(); node.gotoNext())\n {\n node.setAttr(\"x\", floatToStr(node.attrFloat(\"x\") \/ w));\n node.setAttr(\"y\", floatToStr(node.attrFloat(\"y\") \/ h));\n node.setAttr(\"width\", floatToStr(node.attrFloat(\"width\") \/ w));\n node.setAttr(\"height\", floatToStr(node.attrFloat(\"height\") \/ h));\n }\n node.gotoParent();\n }\n TiXmlPrinter printer;\n doc.Accept(&printer);\n return printer.CStr();\n}\n\nconst int RoomsReader::VERSION = 2;\n\nRoomsReader::RoomsReader()\n{\n crawler = 0;\n doc = new TiXmlDocument;\n parse_map[\"world\"] = &RoomsReader::parseWorld;\n parse_map[\"room\"] = &RoomsReader::parseRoom;\n parse_map[\"area\"] = &RoomsReader::parseArea;\n parse_map[\"action\"] = &RoomsReader::parseAction;\n parse_map[\"event\"] = &RoomsReader::parseEvent;\n parse_map[\"dialog\"] = &RoomsReader::parseDialog;\n parse_map[\"step\"] = &RoomsReader::parseDialogStep;\n parse_map[\"var\"] = &RoomsReader::parseVar;\n parse_map[\"item\"] = &RoomsReader::parseItem;\n parse_map[\"param\"] = &RoomsReader::parseParam;\n parse_map[\"item_req\"] = &RoomsReader::parseItemReq;\n parse_map[\"var_req\"] = &RoomsReader::parseVarReq;\n parse_map[\"img\"] = &RoomsReader::parseImages;\n}\n\nRoomsReader::~RoomsReader()\n{\n if(crawler)\n delete crawler;\n if (doc)\n delete doc;\n}\n\nRoomsReader::UpgradeFunc RoomsReader::upgrade_funcs[] = {upgradeFrom1To2};\n\nbool RoomsReader::loadFromFile(const string filename)\n{\n std::ifstream xml(filename.c_str(), std::ios::binary);\n if (!xml.good()) return false;\n xml.seekg (0, std::ios::end);\n long length = xml.tellg();\n if (length == 0) return false;\n char *buffer = new char [length];\n xml.seekg (0, std::ios::beg);\n xml.read(buffer, length);\n bool res = loadFromStr(buffer);\n xml.close();\n delete [] buffer;\n return res;\n}\n\nbool RoomsReader::loadFromStr(const string content)\n{\n doc->Parse(content.c_str());\n if (!parse())\n {\n delete doc;\n doc = 0;\n if (file_version < VERSION)\n {\n logger.write(\"Old version detected: \" + floatToStr(file_version) + \". Upgrading...\", Log::WARNING);\n string new_content = upgrade(content);\n return loadFromStr(new_content);\n }\n return false;\n }\n crawler = new RRNode(doc->RootElement());\n return true;\n}\n\nvoid RoomsReader::loadEmptyDoc()\n{\n TiXmlDeclaration *decl = new TiXmlDeclaration(\"1.0\", \"\", \"\");\n TiXmlElement *element = new TiXmlElement(\"world\");\n doc->LinkEndChild(decl);\n doc->LinkEndChild(element);\n crawler = new RRNode(doc->RootElement());\n}\n\nvoid RoomsReader::saveDoc(string filename)\n{\n if (!doc->SaveFile(filename.c_str()))\n logger.write(\"Cannot save to \" + filename, Log::ERROR);\n}\n\nstring RoomsReader::upgrade(string content)\n{\n for (int i = file_version; i < VERSION; ++i)\n {\n content = upgrade_funcs[i - 1](content);\n }\n return content;\n}\n\nbool RoomsReader::parse()\n{\n return parseElement(doc->RootElement());\n}\n\nRRNode *RoomsReader::getCrawler()\n{\n return crawler;\n}\n\nbool RoomsReader::checkUniqueId(std::set<string> &ids, const string id)\n{\n if (ids.count(id) != 0)\n return false;\n ids.insert(id);\n return true;\n}\n\nbool RoomsReader::checkParent(TiXmlElement *elem, string name)\n{\n return (elem->Parent() != 0 &&\n string(elem->Parent()->Value()) == name);\n}\n\nbool RoomsReader::parseElement(TiXmlElement *elem)\n{\n if (elem == 0)\n return true;\n bool value = true;\n if (parse_map.find(elem->Value()) != parse_map.end())\n {\n ParseMethod method = parse_map.find(elem->Value())->second;\n value = (this->*method)(elem);\n }\n return (value && parseElement(elem->FirstChildElement()) && parseElement(elem->NextSiblingElement()));\n}\n\nbool RoomsReader::parseArea(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"x\", ATTR_FLOAT) &&\n parseAttr(elem, \"y\", ATTR_FLOAT) &&\n parseAttr(elem, \"width\", ATTR_FLOAT) &&\n parseAttr(elem, \"height\", ATTR_FLOAT)))\n return false;\n if (!(checkUniqueId(unique_ids_areas, elem->Attribute(\"id\")) &&\n checkParent(elem, \"room\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseItem(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"room\", ATTR_STR) &&\n parseAttr(elem, \"image\", ATTR_STR) &&\n parseAttr(elem, \"x\", ATTR_FLOAT) &&\n parseAttr(elem, \"y\", ATTR_FLOAT) &&\n parseAttr(elem, \"width\", ATTR_FLOAT) &&\n parseAttr(elem, \"height\", ATTR_FLOAT)))\n return false;\n if (!(checkUniqueId(unique_ids_items, elem->Attribute(\"id\")) &&\n checkParent(elem, \"items\") &&\n !checkUniqueId(unique_ids_images, elem->Attribute(\"image\"))))\n return false;\n return true;\n}\n\nbool RoomsReader::parseRoom(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"bg\", ATTR_STR)))\n return false;\n if (!(checkUniqueId(unique_ids_rooms, elem->Attribute(\"id\")) &&\n checkParent(elem, \"rooms\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseAction(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n (checkParent(elem, \"event\") || checkParent(elem, \"step\"))))\n return false;\n return true;\n}\n\nbool RoomsReader::parseWorld(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"version\", ATTR_INT) &&\n parseAttr(elem, \"name\", ATTR_STR) &&\n parseAttr(elem, \"start\", ATTR_STR) &&\n parseAttr(elem, \"width\", ATTR_INT) &&\n parseAttr(elem, \"height\", ATTR_INT)))\n return false;\n elem->QueryIntAttribute(\"version\", &file_version);\n if (file_version != VERSION)\n return false;\n return true;\n}\n\nbool RoomsReader::parseEvent(TiXmlElement *elem)\n{\n if (!parseAttr(elem, \"id\", ATTR_STR))\n return false;\n if (!(checkUniqueId(unique_ids_events, elem->Attribute(\"id\")) &&\n checkParent(elem, \"events\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseVar(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"value\", ATTR_STR) &&\n checkParent(elem, \"vars\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseImages(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"file\", ATTR_STR) &&\n checkParent(elem, \"images\")))\n return false;\n if (!checkUniqueId(unique_ids_images, elem->Attribute(\"file\")))\n return false;\n return true;\n}\n\n\nbool RoomsReader::parseItemReq(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"value\", ATTR_STR)))\n return false;\n if (!(!checkUniqueId(unique_ids_items, elem->Attribute(\"id\")) &&\n (checkParent(elem, \"event\") || checkParent(elem, \"step\"))))\n return false;\n return true;\n}\n\nbool RoomsReader::parseVarReq(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"value\", ATTR_INT)))\n return false;\n if (!(checkParent(elem, \"event\") || checkParent(elem, \"step\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseParam(TiXmlElement *elem)\n{\n if (!parseAttr(elem, \"value\", ATTR_STR))\n return false;\n return true;\n}\n\nbool RoomsReader::parseDialog(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"start\", ATTR_STR)))\n return false;\n if (!(checkUniqueId(unique_ids_dialogs, elem->Attribute(\"id\")) &&\n checkParent(elem, \"dialogs\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseDialogStep(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"text\", ATTR_STR) &&\n checkParent(elem, \"dialog\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseAttr(TiXmlElement *elem, string name, AttributeType type)\n{\n switch (type)\n {\n case ATTR_FLOAT:\n {\n float tmp;\n return (elem->QueryFloatAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);\n break;\n }\n case ATTR_INT:\n {\n int tmp;\n return (elem->QueryIntAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);\n break;\n }\n case ATTR_STR:\n {\n return (elem->Attribute(name.c_str()));\n break;\n }\n default:\n {\n return false;\n break;\n }\n }\n}\n<commit_msg>Added some logs<commit_after>#include \"roomsreader.h\"\n\nRRNode::RRNode(TiXmlElement *root)\n{\n this->root = root;\n parent = 0;\n gotoRoot();\n}\n\nRRNode::~RRNode()\n{\n\n}\n\nRRNode *RRNode::gotoElement(string name)\n{\n cursor = findElement(root, name);\n if (!isNull())\n parent = cursor->Parent()->ToElement();\n else\n parent = 0;\n return this;\n}\n\nRRNode *RRNode::gotoRoot()\n{\n cursor = root;\n parent = 0;\n return this;\n}\n\nRRNode *RRNode::gotoChild(string name)\n{\n if(!isNull())\n {\n parent = cursor;\n cursor = cursor->FirstChildElement(name.c_str());\n }\n return this;\n}\n\nRRNode *RRNode::gotoParent()\n{\n cursor = parent;\n if(!isNull())\n {\n parent = cursor->Parent()->ToElement();\n }\n return this;\n}\n\nRRNode *RRNode::gotoNext()\n{\n if(!isNull())\n cursor = cursor->NextSiblingElement(cursor->Value());\n return this;\n}\n\nRRNode *RRNode::appendElement(string name)\n{\n if(!isNull())\n {\n TiXmlElement *new_elem = new TiXmlElement(name.c_str());\n cursor->LinkEndChild(new_elem);\n parent = cursor;\n cursor = new_elem;\n }\n return this;\n}\n\nbool RRNode::isNull()\n{\n bool result = cursor;\n return !result;\n}\n\nint RRNode::attrInt(string name)\n{\n int tmp = 0;\n cursor->QueryIntAttribute(name.c_str(), &tmp);\n return tmp;\n}\n\nfloat RRNode::attrFloat(string name)\n{\n float tmp = 0.0;\n cursor->QueryFloatAttribute(name.c_str(), &tmp);\n return tmp;\n}\n\nstring RRNode::attrStr(string name)\n{\n return cursor->Attribute(name.c_str());\n}\n\nvoid RRNode::setAttr(string name, string value)\n{\n cursor->SetAttribute(name.c_str(), value.c_str());\n}\n\nEvent *RRNode::fetchEvent()\n{\n if (isNull()) return 0;\n Event *event = new Event(attrStr(\"id\"));\n for (gotoChild(\"item_req\"); !isNull(); gotoNext())\n event->addItemReq(attrStr(\"id\"), attrStr(\"value\"));\n gotoParent();\n for (gotoChild(\"var_req\"); !isNull(); gotoNext())\n event->addVarReq(attrStr(\"id\"), attrInt(\"value\"));\n gotoParent();\n for (gotoChild(\"action\"); !isNull(); gotoNext())\n {\n Action *act = event->addAction(attrStr(\"id\"));\n for (gotoChild(\"param\"); !isNull(); gotoNext())\n act->pushParam(attrStr(\"value\"));\n gotoParent();\n }\n gotoParent();\n return event;\n}\n\nRoom *RRNode::fetchRoom()\n{\n if (isNull()) return 0;\n Room *room = new Room(attrStr(\"id\"));\n room->bg(attrStr(\"bg\"));\n for (gotoChild(\"area\"); !isNull(); gotoNext())\n {\n Area *area = room->addArea(attrStr(\"id\"));\n area->size(attrFloat(\"x\"), attrFloat(\"y\"), attrFloat(\"width\"), attrFloat(\"height\"));\n area->setEvent(attrStr(\"event\"));\n }\n gotoParent();\n return room;\n}\n\nItem *RRNode::fetchItem()\n{\n if (isNull()) return 0;\n Item *item = new Item(attrStr(\"id\"));\n item->size(attrFloat(\"x\"), attrFloat(\"y\"), attrFloat(\"width\"), attrFloat(\"height\"));\n item->setEvent(attrStr(\"event\"));\n item->setImage(attrStr(\"image\"));\n item->move(attrStr(\"room\"));\n return item;\n}\n\nDialog *RRNode::fetchDialog()\n{\n if (isNull()) return 0;\n Dialog *d = new Dialog(attrStr(\"id\"), attrStr(\"start\"));\n for (gotoChild(\"step\"); !isNull(); gotoNext())\n {\n DialogStep *step = d->addStep(attrStr(\"id\"), attrStr(\"text\"));\n step->event = fetchEvent();\n for (gotoChild(\"link\"); !isNull(); gotoNext())\n d->addLink(step->id, attrStr(\"id\"), attrStr(\"text\"));\n gotoParent();\n }\n gotoParent();\n return d;\n}\n\nTiXmlElement *RRNode::findElement(TiXmlElement *elem, string name)\n{\n if (elem == 0)\n return 0;\n if (string(elem->Value()) == name)\n return elem;\n TiXmlElement *result = findElement(elem->NextSiblingElement(), name);\n if (result != 0)\n return result;\n result = findElement(elem->FirstChildElement(), name);\n if (result != 0)\n return result;\n return 0;\n}\n\n\nstring floatToStr(const float f)\n{\n std::ostringstream os;\n os << f;\n return os.str();\n}\n\nstring upgradeFrom1To2(string content)\n{\n TiXmlDocument doc;\n doc.Parse(content.c_str());\n RRNode node(doc.RootElement());\n node.gotoElement(\"world\");\n int w = node.attrInt(\"width\");\n int h = node.attrInt(\"height\");\n node.setAttr(\"version\", \"2\");\n for (node.gotoElement(\"items\")->gotoChild(\"item\"); !node.isNull(); node.gotoNext())\n {\n node.setAttr(\"x\", floatToStr(node.attrFloat(\"x\") \/ w));\n node.setAttr(\"y\", floatToStr(node.attrFloat(\"y\") \/ h));\n node.setAttr(\"width\", floatToStr(node.attrFloat(\"width\") \/ w));\n node.setAttr(\"height\", floatToStr(node.attrFloat(\"height\") \/ h));\n }\n\n for (node.gotoElement(\"rooms\")->gotoChild(\"room\"); !node.isNull(); node.gotoNext())\n {\n for (node.gotoChild(\"area\"); !node.isNull(); node.gotoNext())\n {\n node.setAttr(\"x\", floatToStr(node.attrFloat(\"x\") \/ w));\n node.setAttr(\"y\", floatToStr(node.attrFloat(\"y\") \/ h));\n node.setAttr(\"width\", floatToStr(node.attrFloat(\"width\") \/ w));\n node.setAttr(\"height\", floatToStr(node.attrFloat(\"height\") \/ h));\n }\n node.gotoParent();\n }\n TiXmlPrinter printer;\n doc.Accept(&printer);\n return printer.CStr();\n}\n\nconst int RoomsReader::VERSION = 2;\n\nRoomsReader::RoomsReader()\n{\n crawler = 0;\n doc = new TiXmlDocument;\n parse_map[\"world\"] = &RoomsReader::parseWorld;\n parse_map[\"room\"] = &RoomsReader::parseRoom;\n parse_map[\"area\"] = &RoomsReader::parseArea;\n parse_map[\"action\"] = &RoomsReader::parseAction;\n parse_map[\"event\"] = &RoomsReader::parseEvent;\n parse_map[\"dialog\"] = &RoomsReader::parseDialog;\n parse_map[\"step\"] = &RoomsReader::parseDialogStep;\n parse_map[\"var\"] = &RoomsReader::parseVar;\n parse_map[\"item\"] = &RoomsReader::parseItem;\n parse_map[\"param\"] = &RoomsReader::parseParam;\n parse_map[\"item_req\"] = &RoomsReader::parseItemReq;\n parse_map[\"var_req\"] = &RoomsReader::parseVarReq;\n parse_map[\"img\"] = &RoomsReader::parseImages;\n}\n\nRoomsReader::~RoomsReader()\n{\n if(crawler)\n delete crawler;\n if (doc)\n delete doc;\n}\n\nRoomsReader::UpgradeFunc RoomsReader::upgrade_funcs[] = {upgradeFrom1To2};\n\nbool RoomsReader::loadFromFile(const string filename)\n{\n std::ifstream xml(filename.c_str(), std::ios::binary);\n if (!xml.good()) return false;\n xml.seekg (0, std::ios::end);\n long length = xml.tellg();\n if (length == 0) return false;\n char *buffer = new char [length];\n xml.seekg (0, std::ios::beg);\n xml.read(buffer, length);\n bool res = loadFromStr(buffer);\n xml.close();\n delete [] buffer;\n return res;\n}\n\nbool RoomsReader::loadFromStr(const string content)\n{\n doc->Parse(content.c_str());\n if (!parse())\n {\n delete doc;\n doc = 0;\n if (file_version < VERSION)\n {\n logger.write(\"Old version detected: \" + floatToStr(file_version) + \". Upgrading...\", Log::WARNING);\n string new_content = upgrade(content);\n return loadFromStr(new_content);\n }\n return false;\n }\n crawler = new RRNode(doc->RootElement());\n return true;\n}\n\nvoid RoomsReader::loadEmptyDoc()\n{\n TiXmlDeclaration *decl = new TiXmlDeclaration(\"1.0\", \"\", \"\");\n TiXmlElement *element = new TiXmlElement(\"world\");\n doc->LinkEndChild(decl);\n doc->LinkEndChild(element);\n crawler = new RRNode(doc->RootElement());\n}\n\nvoid RoomsReader::saveDoc(string filename)\n{\n if (!doc->SaveFile(filename.c_str()))\n logger.write(\"Cannot save to \" + filename, Log::ERROR);\n}\n\nstring RoomsReader::upgrade(string content)\n{\n for (int i = file_version; i < VERSION; ++i)\n {\n logger.write(\"Updating from v.\" + floatToStr(i) + \" to v.\" + floatToStr(i + 1), Log::NOTE);\n content = upgrade_funcs[i - 1](content);\n }\n logger.write(\"Upgrade successful!\", Log::WARNING);\n return content;\n}\n\nbool RoomsReader::parse()\n{\n return parseElement(doc->RootElement());\n}\n\nRRNode *RoomsReader::getCrawler()\n{\n return crawler;\n}\n\nbool RoomsReader::checkUniqueId(std::set<string> &ids, const string id)\n{\n if (ids.count(id) != 0)\n return false;\n ids.insert(id);\n return true;\n}\n\nbool RoomsReader::checkParent(TiXmlElement *elem, string name)\n{\n return (elem->Parent() != 0 &&\n string(elem->Parent()->Value()) == name);\n}\n\nbool RoomsReader::parseElement(TiXmlElement *elem)\n{\n if (elem == 0)\n return true;\n bool value = true;\n if (parse_map.find(elem->Value()) != parse_map.end())\n {\n ParseMethod method = parse_map.find(elem->Value())->second;\n value = (this->*method)(elem);\n }\n return (value && parseElement(elem->FirstChildElement()) && parseElement(elem->NextSiblingElement()));\n}\n\nbool RoomsReader::parseArea(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"x\", ATTR_FLOAT) &&\n parseAttr(elem, \"y\", ATTR_FLOAT) &&\n parseAttr(elem, \"width\", ATTR_FLOAT) &&\n parseAttr(elem, \"height\", ATTR_FLOAT)))\n return false;\n if (!(checkUniqueId(unique_ids_areas, elem->Attribute(\"id\")) &&\n checkParent(elem, \"room\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseItem(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"room\", ATTR_STR) &&\n parseAttr(elem, \"image\", ATTR_STR) &&\n parseAttr(elem, \"x\", ATTR_FLOAT) &&\n parseAttr(elem, \"y\", ATTR_FLOAT) &&\n parseAttr(elem, \"width\", ATTR_FLOAT) &&\n parseAttr(elem, \"height\", ATTR_FLOAT)))\n return false;\n if (!(checkUniqueId(unique_ids_items, elem->Attribute(\"id\")) &&\n checkParent(elem, \"items\") &&\n !checkUniqueId(unique_ids_images, elem->Attribute(\"image\"))))\n return false;\n return true;\n}\n\nbool RoomsReader::parseRoom(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"bg\", ATTR_STR)))\n return false;\n if (!(checkUniqueId(unique_ids_rooms, elem->Attribute(\"id\")) &&\n checkParent(elem, \"rooms\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseAction(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n (checkParent(elem, \"event\") || checkParent(elem, \"step\"))))\n return false;\n return true;\n}\n\nbool RoomsReader::parseWorld(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"version\", ATTR_INT) &&\n parseAttr(elem, \"name\", ATTR_STR) &&\n parseAttr(elem, \"start\", ATTR_STR) &&\n parseAttr(elem, \"width\", ATTR_INT) &&\n parseAttr(elem, \"height\", ATTR_INT)))\n return false;\n elem->QueryIntAttribute(\"version\", &file_version);\n if (file_version != VERSION)\n return false;\n return true;\n}\n\nbool RoomsReader::parseEvent(TiXmlElement *elem)\n{\n if (!parseAttr(elem, \"id\", ATTR_STR))\n return false;\n if (!(checkUniqueId(unique_ids_events, elem->Attribute(\"id\")) &&\n checkParent(elem, \"events\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseVar(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"value\", ATTR_STR) &&\n checkParent(elem, \"vars\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseImages(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"file\", ATTR_STR) &&\n checkParent(elem, \"images\")))\n return false;\n if (!checkUniqueId(unique_ids_images, elem->Attribute(\"file\")))\n return false;\n return true;\n}\n\n\nbool RoomsReader::parseItemReq(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"value\", ATTR_STR)))\n return false;\n if (!(!checkUniqueId(unique_ids_items, elem->Attribute(\"id\")) &&\n (checkParent(elem, \"event\") || checkParent(elem, \"step\"))))\n return false;\n return true;\n}\n\nbool RoomsReader::parseVarReq(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"value\", ATTR_INT)))\n return false;\n if (!(checkParent(elem, \"event\") || checkParent(elem, \"step\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseParam(TiXmlElement *elem)\n{\n if (!parseAttr(elem, \"value\", ATTR_STR))\n return false;\n return true;\n}\n\nbool RoomsReader::parseDialog(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"start\", ATTR_STR)))\n return false;\n if (!(checkUniqueId(unique_ids_dialogs, elem->Attribute(\"id\")) &&\n checkParent(elem, \"dialogs\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseDialogStep(TiXmlElement *elem)\n{\n if (!(parseAttr(elem, \"id\", ATTR_STR) &&\n parseAttr(elem, \"text\", ATTR_STR) &&\n checkParent(elem, \"dialog\")))\n return false;\n return true;\n}\n\nbool RoomsReader::parseAttr(TiXmlElement *elem, string name, AttributeType type)\n{\n switch (type)\n {\n case ATTR_FLOAT:\n {\n float tmp;\n return (elem->QueryFloatAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);\n break;\n }\n case ATTR_INT:\n {\n int tmp;\n return (elem->QueryIntAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);\n break;\n }\n case ATTR_STR:\n {\n return (elem->Attribute(name.c_str()));\n break;\n }\n default:\n {\n return false;\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\\\n* File: renderer.cpp\n* Purpose: Implementation of wxExRenderer class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 2007-2008, Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include <wx\/extension\/renderer.h>\n\n#if wxUSE_GUI\n#if wxUSE_GRID\r\n\nwxExRenderer::wxExRenderer(\n long flags,\n const wxPen& pen,\n const wxPen& pen_outer,\n const wxBrush& brush)\n : m_Brush(brush)\n , m_Pen(pen)\n , m_PenOuter(pen_outer)\n , m_Flags(flags)\n{\n}\n\nvoid wxExRenderer::Draw(\n wxGrid& grid,\n wxGridCellAttr& attr,\n wxDC& dc,\n const wxRect& rect,\n int row,\n int col,\n bool isSelected)\n{\n wxGridCellStringRenderer::Draw(grid, attr, dc, rect, row, col, isSelected);\n\n bool left = false;\n bool right = false;\n bool up = false;\n bool down = false;\n\n \/\/ These are drawn using m_PenOuter.\n if (m_PenOuter.GetWidth() > 0)\n {\n dc.SetPen(m_PenOuter);\n\n if (m_Flags & CELL_RECT_OUTER_UP)\n {\n up = true;\n dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());\n }\n\n if (m_Flags & CELL_RECT_OUTER_DOWN)\n {\n down = true;\n dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_RECT_OUTER_LEFT)\n {\n left = true;\n dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());\n }\n\n if (m_Flags & CELL_RECT_OUTER_RIGHT)\n {\n right = true;\n dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_RECT)\n {\n dc.SetBrush(m_Brush);\n dc.DrawRectangle(rect);\n }\n }\n\n \/\/ Rest is drawn using normal pen.\n if (m_Pen.GetWidth() == 0) return;\n\n dc.SetPen(m_Pen);\n\n if (up || down || left || right)\n {\n if (!up) dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());\n if (!down) dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());\n if (!left) dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());\n if (!right) dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_UP)\n {\n dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());\n }\n\n if (m_Flags & CELL_DOWN)\n {\n dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_LEFT)\n {\n dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());\n }\n\n if (m_Flags & CELL_RIGHT)\n {\n dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_CROSS)\n {\n dc.DrawLine(rect.GetTopLeft(), rect.GetBottomRight());\n dc.DrawLine(rect.GetBottomLeft(), rect.GetTopRight());\n }\n}\n\n#endif \/\/ wxUSE_GRID\n#endif \/\/ wxUSE_GUI\n<commit_msg>changed to unix eol<commit_after>\/******************************************************************************\\\n* File: renderer.cpp\n* Purpose: Implementation of wxExRenderer class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 2007-2008, Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include <wx\/extension\/renderer.h>\n\n#if wxUSE_GUI\n#if wxUSE_GRID\n\nwxExRenderer::wxExRenderer(\n long flags,\n const wxPen& pen,\n const wxPen& pen_outer,\n const wxBrush& brush)\n : m_Brush(brush)\n , m_Pen(pen)\n , m_PenOuter(pen_outer)\n , m_Flags(flags)\n{\n}\n\nvoid wxExRenderer::Draw(\n wxGrid& grid,\n wxGridCellAttr& attr,\n wxDC& dc,\n const wxRect& rect,\n int row,\n int col,\n bool isSelected)\n{\n wxGridCellStringRenderer::Draw(grid, attr, dc, rect, row, col, isSelected);\n\n bool left = false;\n bool right = false;\n bool up = false;\n bool down = false;\n\n \/\/ These are drawn using m_PenOuter.\n if (m_PenOuter.GetWidth() > 0)\n {\n dc.SetPen(m_PenOuter);\n\n if (m_Flags & CELL_RECT_OUTER_UP)\n {\n up = true;\n dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());\n }\n\n if (m_Flags & CELL_RECT_OUTER_DOWN)\n {\n down = true;\n dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_RECT_OUTER_LEFT)\n {\n left = true;\n dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());\n }\n\n if (m_Flags & CELL_RECT_OUTER_RIGHT)\n {\n right = true;\n dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_RECT)\n {\n dc.SetBrush(m_Brush);\n dc.DrawRectangle(rect);\n }\n }\n\n \/\/ Rest is drawn using normal pen.\n if (m_Pen.GetWidth() == 0) return;\n\n dc.SetPen(m_Pen);\n\n if (up || down || left || right)\n {\n if (!up) dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());\n if (!down) dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());\n if (!left) dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());\n if (!right) dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_UP)\n {\n dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());\n }\n\n if (m_Flags & CELL_DOWN)\n {\n dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_LEFT)\n {\n dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());\n }\n\n if (m_Flags & CELL_RIGHT)\n {\n dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());\n }\n\n if (m_Flags & CELL_CROSS)\n {\n dc.DrawLine(rect.GetTopLeft(), rect.GetBottomRight());\n dc.DrawLine(rect.GetBottomLeft(), rect.GetTopRight());\n }\n}\n\n#endif \/\/ wxUSE_GRID\n#endif \/\/ wxUSE_GUI\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2015 Inviwo Foundation\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 met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include <modules\/cimg\/cimglayerreader.h>\n#include <modules\/cimg\/cimgutils.h>\n#include <inviwo\/core\/util\/filesystem.h>\n#include <inviwo\/core\/datastructures\/image\/layer.h>\n#include <inviwo\/core\/datastructures\/image\/layerdisk.h>\n\nnamespace inviwo {\n\nCImgLayerReader::CImgLayerReader()\n : DataReaderType<Layer>() {\n addExtension(FileExtension(\"raw\", \"RAW\"));\n#ifdef cimg_use_png\n addExtension(FileExtension(\"png\", \"Portable Network Graphics\"));\n#endif\n#ifdef cimg_use_jpeg\n addExtension(FileExtension(\"jpg\", \"Joint Photographic Experts Group\"));\n addExtension(FileExtension(\"jpeg\", \"Joint Photographic Experts Group\"));\n#endif\n addExtension(FileExtension(\"bmp\", \"Windows bitmap\"));\n#ifdef cimg_use_openexr\n addExtension(FileExtension(\"exr\", \"OpenEXR\"));\n#endif\n addExtension(FileExtension(\"hdr\", \"Analyze 7.5\"));\n}\n\nCImgLayerReader::CImgLayerReader(const CImgLayerReader& rhs)\n : DataReaderType<Layer>(rhs) {};\n\nCImgLayerReader& CImgLayerReader::operator=(const CImgLayerReader& that) {\n if (this != &that) {\n DataReaderType<Layer>::operator=(that);\n }\n\n return *this;\n}\n\nCImgLayerReader* CImgLayerReader::clone() const { return new CImgLayerReader(*this); }\n\nLayer* CImgLayerReader::readMetaData(std::string filePath) {\n if (!filesystem::fileExists(filePath)) {\n std::string newPath = filesystem::addBasePath(filePath);\n\n if (filesystem::fileExists(newPath)) {\n filePath = newPath;\n } else {\n throw DataReaderException(\"Error could not find input file: \" + filePath, IvwContext);\n }\n }\n\n Layer* layer = new Layer();\n\n LayerDisk* layerDisk = new LayerDisk(filePath);\n layerDisk->setDataReader(this->clone());\n\n layer->addRepresentation(layerDisk);\n\n return layer;\n}\n\nvoid CImgLayerReader::readDataInto(void* destination) const {\n LayerDisk* layerDisk = dynamic_cast<LayerDisk*>(owner_);\n if(layerDisk){\n uvec2 dimensions = layerDisk->getDimensions();\n DataFormatEnums::Id formatId = DataFormatEnums::NOT_SPECIALIZED;\n\n std::string filePath = layerDisk->getSourceFile();\n\n if (!filesystem::fileExists(filePath)) {\n std::string newPath = filesystem::addBasePath(filePath);\n\n if (filesystem::fileExists(newPath)) {\n filePath = newPath;\n }\n else {\n throw DataReaderException(\"Error could not find input file: \" + filePath, IvwContext);\n }\n }\n\n if (dimensions != uvec2(0)){\n \/\/ Load and rescale to input dimensions\n CImgUtils::loadLayerData(destination, filePath, dimensions, formatId, true);\n }\n else{\n \/\/ Load to original dimensions\n CImgUtils::loadLayerData(destination, filePath, dimensions, formatId, false);\n layerDisk->setDimensions(dimensions);\n }\n\n layerDisk->updateDataFormat(DataFormatBase::get(formatId));\n }\n}\n\nvoid* CImgLayerReader::readData() const {\n void* data = nullptr;\n\n LayerDisk* layerDisk = dynamic_cast<LayerDisk*>(owner_);\n if(layerDisk){\n uvec2 dimensions = layerDisk->getDimensions();\n DataFormatEnums::Id formatId = DataFormatEnums::NOT_SPECIALIZED;\n\n std::string filePath = layerDisk->getSourceFile();\n\n if (!filesystem::fileExists(filePath)) {\n std::string newPath = filesystem::addBasePath(filePath);\n\n if (filesystem::fileExists(newPath)) {\n filePath = newPath;\n }\n else {\n throw DataReaderException(\"Error could not find input file: \" + filePath, IvwContext);\n }\n }\n\n if (dimensions != uvec2(0)){\n \/\/ Load and rescale to input dimensions\n data = CImgUtils::loadLayerData(nullptr, filePath, dimensions, formatId, true);\n }\n else{\n \/\/ Load to original dimensions\n data = CImgUtils::loadLayerData(nullptr, filePath, dimensions, formatId, false);\n layerDisk->setDimensions(dimensions);\n }\n\n layerDisk->updateDataFormat(DataFormatBase::get(formatId));\n }\n\n return data;\n}\n\n} \/\/ namespace\n<commit_msg>Removed HDR from CimgLayerReader as issue inviwo\/inviwo-dev#366 is not fixed yet.<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2015 Inviwo Foundation\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 met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include <modules\/cimg\/cimglayerreader.h>\n#include <modules\/cimg\/cimgutils.h>\n#include <inviwo\/core\/util\/filesystem.h>\n#include <inviwo\/core\/datastructures\/image\/layer.h>\n#include <inviwo\/core\/datastructures\/image\/layerdisk.h>\n\nnamespace inviwo {\n\nCImgLayerReader::CImgLayerReader()\n : DataReaderType<Layer>() {\n addExtension(FileExtension(\"raw\", \"RAW\"));\n#ifdef cimg_use_png\n addExtension(FileExtension(\"png\", \"Portable Network Graphics\"));\n#endif\n#ifdef cimg_use_jpeg\n addExtension(FileExtension(\"jpg\", \"Joint Photographic Experts Group\"));\n addExtension(FileExtension(\"jpeg\", \"Joint Photographic Experts Group\"));\n#endif\n addExtension(FileExtension(\"bmp\", \"Windows bitmap\"));\n#ifdef cimg_use_openexr\n addExtension(FileExtension(\"exr\", \"OpenEXR\"));\n#endif\n}\n\nCImgLayerReader::CImgLayerReader(const CImgLayerReader& rhs)\n : DataReaderType<Layer>(rhs) {};\n\nCImgLayerReader& CImgLayerReader::operator=(const CImgLayerReader& that) {\n if (this != &that) {\n DataReaderType<Layer>::operator=(that);\n }\n\n return *this;\n}\n\nCImgLayerReader* CImgLayerReader::clone() const { return new CImgLayerReader(*this); }\n\nLayer* CImgLayerReader::readMetaData(std::string filePath) {\n if (!filesystem::fileExists(filePath)) {\n std::string newPath = filesystem::addBasePath(filePath);\n\n if (filesystem::fileExists(newPath)) {\n filePath = newPath;\n } else {\n throw DataReaderException(\"Error could not find input file: \" + filePath, IvwContext);\n }\n }\n\n Layer* layer = new Layer();\n\n LayerDisk* layerDisk = new LayerDisk(filePath);\n layerDisk->setDataReader(this->clone());\n\n layer->addRepresentation(layerDisk);\n\n return layer;\n}\n\nvoid CImgLayerReader::readDataInto(void* destination) const {\n LayerDisk* layerDisk = dynamic_cast<LayerDisk*>(owner_);\n if(layerDisk){\n uvec2 dimensions = layerDisk->getDimensions();\n DataFormatEnums::Id formatId = DataFormatEnums::NOT_SPECIALIZED;\n\n std::string filePath = layerDisk->getSourceFile();\n\n if (!filesystem::fileExists(filePath)) {\n std::string newPath = filesystem::addBasePath(filePath);\n\n if (filesystem::fileExists(newPath)) {\n filePath = newPath;\n }\n else {\n throw DataReaderException(\"Error could not find input file: \" + filePath, IvwContext);\n }\n }\n\n if (dimensions != uvec2(0)){\n \/\/ Load and rescale to input dimensions\n CImgUtils::loadLayerData(destination, filePath, dimensions, formatId, true);\n }\n else{\n \/\/ Load to original dimensions\n CImgUtils::loadLayerData(destination, filePath, dimensions, formatId, false);\n layerDisk->setDimensions(dimensions);\n }\n\n layerDisk->updateDataFormat(DataFormatBase::get(formatId));\n }\n}\n\nvoid* CImgLayerReader::readData() const {\n void* data = nullptr;\n\n LayerDisk* layerDisk = dynamic_cast<LayerDisk*>(owner_);\n if(layerDisk){\n uvec2 dimensions = layerDisk->getDimensions();\n DataFormatEnums::Id formatId = DataFormatEnums::NOT_SPECIALIZED;\n\n std::string filePath = layerDisk->getSourceFile();\n\n if (!filesystem::fileExists(filePath)) {\n std::string newPath = filesystem::addBasePath(filePath);\n\n if (filesystem::fileExists(newPath)) {\n filePath = newPath;\n }\n else {\n throw DataReaderException(\"Error could not find input file: \" + filePath, IvwContext);\n }\n }\n\n if (dimensions != uvec2(0)){\n \/\/ Load and rescale to input dimensions\n data = CImgUtils::loadLayerData(nullptr, filePath, dimensions, formatId, true);\n }\n else{\n \/\/ Load to original dimensions\n data = CImgUtils::loadLayerData(nullptr, filePath, dimensions, formatId, false);\n layerDisk->setDimensions(dimensions);\n }\n\n layerDisk->updateDataFormat(DataFormatBase::get(formatId));\n }\n\n return data;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#ifndef WIGWAG_DETAIL_CREATION_STORAGE_ADAPTER_HPP\n#define WIGWAG_DETAIL_CREATION_STORAGE_ADAPTER_HPP\n\n\n#include <utility>\n\n\nnamespace wigwag {\nnamespace detail\n{\n\n\ttemplate < typename Storage_ >\n\tclass creation_storage_adapter\n\t{\n\tprivate:\n\t\tStorage_\t\t_s;\n\n\tpublic:\n\t\tcreation_storage_adapter()\n\t\t\t: _s()\n\t\t{ }\n\n\t\ttemplate < typename T_, typename... Args_ >\n\t\tvoid create(Args_&&... args)\n\t\t{ _s.template create<T_>(std::forward<Args_>(args)...); }\n\n\t\texplicit operator bool() const\n\t\t{ return _s.constructed(); }\n\n\t\tauto get_ptr() const -> decltype(_s.get_ptr())\n\t\t{ return _s.get_ptr(); }\n\n\t\tauto operator -> () const -> decltype(&*get_ptr())\n\t\t{ return &*get_ptr(); }\n\t};\n\n}}\n\n#endif\n<commit_msg>Added license plate<commit_after>#ifndef WIGWAG_DETAIL_CREATION_STORAGE_ADAPTER_HPP\n#define WIGWAG_DETAIL_CREATION_STORAGE_ADAPTER_HPP\n\n\/\/ Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>\n\/\/\n\/\/ Permission to use, copy, modify, and\/or distribute this software for any purpose with or without fee is hereby granted,\n\/\/ provided that the above copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.\n\/\/ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\n#include <utility>\n\n\nnamespace wigwag {\nnamespace detail\n{\n\n\ttemplate < typename Storage_ >\n\tclass creation_storage_adapter\n\t{\n\tprivate:\n\t\tStorage_\t\t_s;\n\n\tpublic:\n\t\tcreation_storage_adapter()\n\t\t\t: _s()\n\t\t{ }\n\n\t\ttemplate < typename T_, typename... Args_ >\n\t\tvoid create(Args_&&... args)\n\t\t{ _s.template create<T_>(std::forward<Args_>(args)...); }\n\n\t\texplicit operator bool() const\n\t\t{ return _s.constructed(); }\n\n\t\tauto get_ptr() const -> decltype(_s.get_ptr())\n\t\t{ return _s.get_ptr(); }\n\n\t\tauto operator -> () const -> decltype(&*get_ptr())\n\t\t{ return &*get_ptr(); }\n\t};\n\n}}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*--------------------------------------------------------------------------*\\\n | |\n | Copyright (C) 1998 |\n | |\n | , __ , __ |\n | \/|\/ \\ \/|\/ \\ |\n | | __\/ _ ,_ | __\/ _ ,_ | \n | | \\|\/ \/ | | | | \\|\/ \/ | | | |\n | |(__\/|__\/ |_\/ \\_\/|\/|(__\/|__\/ |_\/ \\_\/|\/ |\n | \/| \/| |\n | \\| \\| |\n | |\n | Enrico Bertolazzi |\n | Dipartimento di Ingegneria Industriale |\n | Universita` degli Studi di Trento |\n | email: enrico.bertolazzi@unitn.it |\n | |\n\\*--------------------------------------------------------------------------*\/\n\n#include \"Splines.hh\"\n#include <cmath>\n#include <iomanip>\n\n\/**\n * \n *\/\n\n#ifndef isnan\n#define isnan(A) ((A) != (A))\n#endif\n\n#ifndef isfinite\n#define isfinite(A) ((A*0.0) == 0.0)\n#endif\n\n#ifndef isregular\n#define isregular(A) ( !isnan(A) && isfinite(A) )\n#endif\n\nnamespace Splines {\n\n \/* _ _ _ _ _ _\n \/\/ ___| |__ ___ ___| | _| \\ | | __ _| \\ | |\n \/\/ \/ __| '_ \\ \/ _ \\\/ __| |\/ \/ \\| |\/ _` | \\| |\n \/\/ | (__| | | | __\/ (__| <| |\\ | (_| | |\\ |\n \/\/ \\___|_| |_|\\___|\\___|_|\\_\\_| \\_|\\__,_|_| \\_|\n *\/\n \/\/! check if the vector `pv` os size `DIM` contains only regular floats. If not an error is issued\n void\n checkNaN( valueType const pv[],\n char const v_name[],\n sizeType const DIM ) {\n for ( indexType i = 0 ; i < DIM ; ++i ) {\n if ( isnan(pv[i]) ) {\n std::ostringstream ost ;\n ost << \"\\nfound NaN at \" << v_name << \"[\" << i << \"]\" ;\n throw std::runtime_error(ost.str()) ;\n }\n if ( !isfinite(pv[i]) ) {\n std::ostringstream ost ;\n ost << \"\\nfound Infinity at \" << v_name << \"[\" << i << \"]\" ;\n throw std::runtime_error(ost.str()) ;\n }\n }\n }\n \n void\n Spline::pushBack( valueType x, valueType y ) {\n if ( npts > 0 ) {\n \/\/\/\/ DA RISCRIVERE @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n if ( std::abs(x-X.back()) < 1e-9 ) return ; \/\/ workaround per punti doppi\n SPLINE_ASSERT( x > X.back(),\n \"Spline::pushBack, non monotone insert at insert N. \" << npts <<\n \"\\nX[ \" << npts-1 << \"] = \" << X.back() <<\n \"\\nX[ \" << npts << \"] = \" << x ) ;\n }\n X . push_back( x ) ;\n Y . push_back( y ) ;\n ++npts ;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n void\n Spline::dropBack() {\n if ( npts > 0 ) {\n --npts ;\n X . pop_back() ;\n Y . pop_back() ;\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void\n Spline::setOrigin( valueType x0 ) {\n valueType Tx = x0 - X.front() ;\n for ( VectorOfValues::iterator ix = X.begin() ; ix != X.end() ; ++ix ) *ix += Tx ;\n }\n\n void\n Spline::setRange( valueType xmin, valueType xmax ) {\n SPLINE_ASSERT( xmax > xmin, \"Spline::setRange( \" << xmin << \" , \" << xmax << \" ) bad range \") ;\n valueType S = (xmax - xmin) \/ ( X.back() - X.front() ) ;\n valueType Tx = xmin - S * X.front() ;\n for ( VectorOfValues::iterator ix = X.begin() ; ix != X.end() ; ++ix ) *ix = *ix * S + Tx ;\n }\n\n \/\/! change X-range of the spline\n void\n CubicSplineBase::setRange( valueType xmin, valueType xmax ) {\n Spline::setRange( xmin, xmax ) ;\n valueType recS = ( X.back() - X.front() ) \/ (xmax - xmin) ;\n for ( VectorOfValues::iterator iy = Y.begin() ; iy != Y.end() ; ++iy ) *iy *= recS ;\n }\n\n void\n ConstantsSpline::writeToStream( ostream & s ) const {\n sizeType nseg = sizeType(Y.size()) ;\n for ( sizeType i = 0 ; i < nseg ; ++i )\n s << \"segment N.\" << setw(4) << i\n << \" X:[ \" << X[i] << \", \" << X[i+1] << \" ] Y:\" << Y[i]\n << '\\n' ; \n }\n\n void\n LinearSpline::writeToStream( ostream & s ) const {\n sizeType nseg = sizeType(Y.size()-1) ;\n for ( sizeType i = 0 ; i < nseg ; ++i )\n s << \"segment N.\" << setw(4) << i\n << \" X:[ \" << X[i] << \", \" << X[i+1] << \" ] Y:[ \" << Y[i] << \", \" << Y[i+1] \n << \" ] slope: \" << (Y[i+1]-Y[i])\/(X[i+1]-X[i])\n << '\\n' ; \n }\n\n}\n<commit_msg>Removed a warning<commit_after>\/*--------------------------------------------------------------------------*\\\n | |\n | Copyright (C) 1998 |\n | |\n | , __ , __ |\n | \/|\/ \\ \/|\/ \\ |\n | | __\/ _ ,_ | __\/ _ ,_ | \n | | \\|\/ \/ | | | | \\|\/ \/ | | | |\n | |(__\/|__\/ |_\/ \\_\/|\/|(__\/|__\/ |_\/ \\_\/|\/ |\n | \/| \/| |\n | \\| \\| |\n | |\n | Enrico Bertolazzi |\n | Dipartimento di Ingegneria Industriale |\n | Universita` degli Studi di Trento |\n | email: enrico.bertolazzi@unitn.it |\n | |\n\\*--------------------------------------------------------------------------*\/\n\n#include \"Splines.hh\"\n#include <cmath>\n#include <iomanip>\n\n\/**\n * \n *\/\n\n#ifndef isnan\n#define isnan(A) ((A) != (A))\n#endif\n\n#ifndef isfinite\n#define isfinite(A) ((A*0.0) == 0.0)\n#endif\n\n#ifndef isregular\n#define isregular(A) ( !isnan(A) && isfinite(A) )\n#endif\n\nnamespace Splines {\n\n \/* _ _ _ _ _ _\n \/\/ ___| |__ ___ ___| | _| \\ | | __ _| \\ | |\n \/\/ \/ __| '_ \\ \/ _ \\\/ __| |\/ \/ \\| |\/ _` | \\| |\n \/\/ | (__| | | | __\/ (__| <| |\\ | (_| | |\\ |\n \/\/ \\___|_| |_|\\___|\\___|_|\\_\\_| \\_|\\__,_|_| \\_|\n *\/\n \/\/! check if the vector `pv` os size `DIM` contains only regular floats. If not an error is issued\n void\n checkNaN( valueType const pv[],\n char const v_name[],\n sizeType const DIM ) {\n for ( sizeType i = 0 ; i < DIM ; ++i ) {\n if ( isnan(pv[i]) ) {\n std::ostringstream ost ;\n ost << \"\\nfound NaN at \" << v_name << \"[\" << i << \"]\" ;\n throw std::runtime_error(ost.str()) ;\n }\n if ( !isfinite(pv[i]) ) {\n std::ostringstream ost ;\n ost << \"\\nfound Infinity at \" << v_name << \"[\" << i << \"]\" ;\n throw std::runtime_error(ost.str()) ;\n }\n }\n }\n \n void\n Spline::pushBack( valueType x, valueType y ) {\n if ( npts > 0 ) {\n \/\/\/\/ DA RISCRIVERE @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n if ( std::abs(x-X.back()) < 1e-9 ) return ; \/\/ workaround per punti doppi\n SPLINE_ASSERT( x > X.back(),\n \"Spline::pushBack, non monotone insert at insert N. \" << npts <<\n \"\\nX[ \" << npts-1 << \"] = \" << X.back() <<\n \"\\nX[ \" << npts << \"] = \" << x ) ;\n }\n X . push_back( x ) ;\n Y . push_back( y ) ;\n ++npts ;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n void\n Spline::dropBack() {\n if ( npts > 0 ) {\n --npts ;\n X . pop_back() ;\n Y . pop_back() ;\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void\n Spline::setOrigin( valueType x0 ) {\n valueType Tx = x0 - X.front() ;\n for ( VectorOfValues::iterator ix = X.begin() ; ix != X.end() ; ++ix ) *ix += Tx ;\n }\n\n void\n Spline::setRange( valueType xmin, valueType xmax ) {\n SPLINE_ASSERT( xmax > xmin, \"Spline::setRange( \" << xmin << \" , \" << xmax << \" ) bad range \") ;\n valueType S = (xmax - xmin) \/ ( X.back() - X.front() ) ;\n valueType Tx = xmin - S * X.front() ;\n for ( VectorOfValues::iterator ix = X.begin() ; ix != X.end() ; ++ix ) *ix = *ix * S + Tx ;\n }\n\n \/\/! change X-range of the spline\n void\n CubicSplineBase::setRange( valueType xmin, valueType xmax ) {\n Spline::setRange( xmin, xmax ) ;\n valueType recS = ( X.back() - X.front() ) \/ (xmax - xmin) ;\n for ( VectorOfValues::iterator iy = Y.begin() ; iy != Y.end() ; ++iy ) *iy *= recS ;\n }\n\n void\n ConstantsSpline::writeToStream( ostream & s ) const {\n sizeType nseg = sizeType(Y.size()) ;\n for ( sizeType i = 0 ; i < nseg ; ++i )\n s << \"segment N.\" << setw(4) << i\n << \" X:[ \" << X[i] << \", \" << X[i+1] << \" ] Y:\" << Y[i]\n << '\\n' ; \n }\n\n void\n LinearSpline::writeToStream( ostream & s ) const {\n sizeType nseg = sizeType(Y.size()-1) ;\n for ( sizeType i = 0 ; i < nseg ; ++i )\n s << \"segment N.\" << setw(4) << i\n << \" X:[ \" << X[i] << \", \" << X[i+1] << \" ] Y:[ \" << Y[i] << \", \" << Y[i+1] \n << \" ] slope: \" << (Y[i+1]-Y[i])\/(X[i+1]-X[i])\n << '\\n' ; \n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QApplication>\n#include <QSplashScreen>\n#include <QDebug>\n#include <QFontDatabase>\n\n#include \"app.h\"\n\nvoid messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)\n{\n Q_UNUSED(context)\n\n QString level;\n\n switch (type) {\n case QtDebugMsg:\n level = \"DEBUG\"; break;\n case QtInfoMsg:\n level = \"INFO\"; break;\n case QtWarningMsg:\n level = \"WARNING\"; break;\n case QtCriticalMsg:\n level = \"CRITICAL\"; break;\n case QtFatalMsg:\n level = \"FATAL\"; break;\n default:\n level = \"UNDEFIEND\"; break;\n }\n\n if (type != QtWarningMsg) {\n\n QString text = QString(\"[%1] [%2] %3\")\n .arg(QDateTime::currentDateTime().toString(\"dd-MM-yyyy hh:mm:ss\"))\n .arg(level)\n .arg(message);\n\n static QString logPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);\n\n QFile file(logPath + \"\/stacer.log\");\n\n QIODevice::OpenMode openMode = file.size() > (1L << 20) ? QIODevice::Truncate : QIODevice::Append;\n\n if (file.open(QIODevice::WriteOnly | openMode)) {\n QTextStream stream(&file);\n stream << text << endl;\n\n file.close();\n }\n }\n}\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n\n qApp->setApplicationName(\"stacer\");\n qApp->setApplicationDisplayName(\"Stacer\");\n qApp->setApplicationVersion(\"1.0.9\");\n qApp->setWindowIcon(QIcon(\":\/static\/logo.png\"));\n\n QFontDatabase::addApplicationFont(\":\/static\/font\/Ubuntu-R.ttf\");\n\n QPixmap pixSplash(\":\/static\/splashscreen.png\");\n\n QSplashScreen *splash = new QSplashScreen(pixSplash);\n\n splash->show();\n\n app.processEvents();\n\n\/\/ QThread::sleep(4);\n\n\/\/ qInstallMessageHandler(messageHandler);\n\n App w;\n\n QLatin1String hideOption(\"--hide\");\n\n if (argc < 2 || QString(argv[1]) != hideOption) {\n w.show();\n }\n\n splash->finish(&w);\n\n delete splash;\n\n return app.exec();\n}\n<commit_msg>added message handler<commit_after>#include <QApplication>\n#include <QSplashScreen>\n#include <QDebug>\n#include <QFontDatabase>\n\n#include \"app.h\"\n\nvoid messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)\n{\n Q_UNUSED(context)\n\n QString level;\n\n switch (type) {\n case QtDebugMsg:\n level = \"DEBUG\"; break;\n case QtInfoMsg:\n level = \"INFO\"; break;\n case QtWarningMsg:\n level = \"WARNING\"; break;\n case QtCriticalMsg:\n level = \"CRITICAL\"; break;\n case QtFatalMsg:\n level = \"FATAL\"; break;\n default:\n level = \"UNDEFIEND\"; break;\n }\n\n if (type != QtWarningMsg) {\n\n QString text = QString(\"[%1] [%2] %3\")\n .arg(QDateTime::currentDateTime().toString(\"dd-MM-yyyy hh:mm:ss\"))\n .arg(level)\n .arg(message);\n\n static QString logPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);\n\n QFile file(logPath + \"\/stacer.log\");\n\n QIODevice::OpenMode openMode = file.size() > (1L << 20) ? QIODevice::Truncate : QIODevice::Append;\n\n if (file.open(QIODevice::WriteOnly | openMode)) {\n QTextStream stream(&file);\n stream << text << endl;\n\n file.close();\n }\n }\n}\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n\n qApp->setApplicationName(\"stacer\");\n qApp->setApplicationDisplayName(\"Stacer\");\n qApp->setApplicationVersion(\"1.0.9\");\n qApp->setWindowIcon(QIcon(\":\/static\/logo.png\"));\n\n QFontDatabase::addApplicationFont(\":\/static\/font\/Ubuntu-R.ttf\");\n\n QPixmap pixSplash(\":\/static\/splashscreen.png\");\n\n QSplashScreen *splash = new QSplashScreen(pixSplash);\n\n splash->show();\n\n app.processEvents();\n\n qInstallMessageHandler(messageHandler);\n\n App w;\n\n QLatin1String hideOption(\"--hide\");\n\n if (argc < 2 || QString(argv[1]) != hideOption) {\n w.show();\n }\n\n splash->finish(&w);\n\n delete splash;\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QApplication>\n#include \"pdfview.h\"\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n\n if (argc != 2) {\n fprintf(stderr, \"Usage: runcible-view-pdf <file>\\n\");\n return 1;\n }\n\n PdfView widget;\n widget.setDocument(argv[1]);\n widget.resize(600, 800);\n\n QObject::connect(&widget, SIGNAL(back()), &app, SLOT(quit()));\n\n widget.show();\n return app.exec();\n}\n<commit_msg>Fixed include mistake in view-pdf<commit_after>#include <QApplication>\n#include <stdio.h>\n#include \"pdfview.h\"\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n\n if (argc != 2) {\n fprintf(stderr, \"Usage: runcible-view-pdf <file>\\n\");\n return 1;\n }\n\n PdfView widget;\n widget.setDocument(argv[1]);\n widget.resize(600, 800);\n\n QObject::connect(&widget, SIGNAL(back()), &app, SLOT(quit()));\n\n widget.show();\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n#include <cstring> \/\/ memcpy\n#include <utility> \/\/ swap\n#include <iostream> \/\/ cout, endl\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nVector<T, INIT_CAP, CAP_MULT>::Vector() : items(0), cap(0), data(nullptr) { }\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nVector<T, INIT_CAP, CAP_MULT>::Vector(int size, T val) : Vector() {\n alloc(size);\n for (decltype(size) i = 0; i < size; i++) {\n \/\/ Don't check capacity because we just allocated all. Will speed up a lot.\n _append(val, false);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nVector<T, INIT_CAP, CAP_MULT>::Vector(int size, T *values) : Vector() {\n alloc(size);\n for (decltype(size) i = 0; i < size; i++) {\n _append(values[i], false);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\ntemplate <typename Iterator>\nVector<T, INIT_CAP, CAP_MULT>::Vector(Iterator first, Iterator last) : Vector() {\n for (; first != last; first++) {\n append(*first);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nVector<T, INIT_CAP, CAP_MULT>::~Vector() {\n clear();\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nbool Vector<T, INIT_CAP, CAP_MULT>::isEmpty() const {\n return items == 0;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nint Vector<T, INIT_CAP, CAP_MULT>::size() const {\n return items;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nint Vector<T, INIT_CAP, CAP_MULT>::capacity() const {\n return cap;\n}\n\n\/\/\/ Insert value at the end.\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::append(const T &val) {\n _append(val);\n}\n\n\/\/\/ Insert value at the beginning.\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::prepend(const T &val) {\n insert(0, val);\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::insert(int pos, const T &val) {\n assert(pos >= 0 && pos < cap && \"Position out of bounds!\");\n checkAlloc();\n shiftLeft(pos); \/\/ Effectively moving right.\n data[pos] = val;\n items++;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::print() const {\n using namespace std;\n cout << \"[ \";\n if (isEmpty()) {\n cout << \"empty\";\n }\n for (decltype(cap) i = 0; i < cap; i++) {\n cout << convert(data[i]);\n if (i < cap - 1) {\n cout << \", \";\n }\n }\n cout << \" ]\" << endl;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::clear() {\n if (data) {\n delete[] data;\n data = nullptr;\n }\n items = cap = 0;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::shrinkToFit() {\n if (items == cap) return;\n alloc(items);\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nT Vector<T, INIT_CAP, CAP_MULT>::operator[](int pos) {\n assert(pos >= 0 && pos < cap && \"Position out of bounds!\");\n return data[pos];\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nconst T &Vector<T, INIT_CAP, CAP_MULT>::operator[](int pos) const {\n assert(pos >= 0 && pos < cap && \"Position out of bounds!\");\n return data[pos];\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::remove(const T &val) {\n removeFrom(val);\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::removeAt(int pos) {\n assert(pos >= 0 && pos < cap && \"Position out of bounds!\");\n data[pos] = T();\n items--;\n shiftRight(pos); \/\/ Effectively moving left.\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::fillDefault(T *ptr, int n) {\n for (decltype(n) i = 0; i < n; i++) {\n ptr[i] = T();\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::alloc(int size) {\n auto newCap = size;\n auto *newData = new T[newCap];\n if (newCap > cap) {\n fillDefault(newData, newCap);\n }\n if (items > 0) {\n memcpy(newData, data, items * sizeof(T));\n delete[] data;\n }\n data = newData;\n cap = newCap;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::checkAlloc() {\n if (items != cap) return;\n alloc(cap == 0 ? INIT_CAP : cap * CAP_MULT);\n}\n\n\/\/\/ Appends value but only checks capacity if check is set.\n\/** This saves processing time when appending very many items. *\/\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::_append(const T &val, bool check) {\n if (check) {\n checkAlloc();\n }\n data[items++] = val;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::shiftRight(int pos) {\n for (decltype(pos) i = pos; i < items; i++) {\n std::swap(data[i], data[i+1]);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::shiftLeft(int pos) {\n for (decltype(pos) i = items; i >= pos; i--) {\n std::swap(data[i], data[i+1]);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::removeFrom(const T &val, int pos) {\n for (decltype(pos) i = pos; i < items; i++) {\n auto &item = data[i];\n if (item == val) {\n item = T(); \/\/ Clear.\n items--;\n shiftRight(i); \/\/ Effectively moving left.\n removeFrom(val, i);\n break;\n }\n }\n}\n<commit_msg>Vector: Moved assert() after checkAlloc().<commit_after>#include <cassert>\n#include <cstring> \/\/ memcpy\n#include <utility> \/\/ swap\n#include <iostream> \/\/ cout, endl\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nVector<T, INIT_CAP, CAP_MULT>::Vector() : items(0), cap(0), data(nullptr) { }\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nVector<T, INIT_CAP, CAP_MULT>::Vector(int size, T val) : Vector() {\n alloc(size);\n for (decltype(size) i = 0; i < size; i++) {\n \/\/ Don't check capacity because we just allocated all. Will speed up a lot.\n _append(val, false);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nVector<T, INIT_CAP, CAP_MULT>::Vector(int size, T *values) : Vector() {\n alloc(size);\n for (decltype(size) i = 0; i < size; i++) {\n _append(values[i], false);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\ntemplate <typename Iterator>\nVector<T, INIT_CAP, CAP_MULT>::Vector(Iterator first, Iterator last) : Vector() {\n for (; first != last; first++) {\n append(*first);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nVector<T, INIT_CAP, CAP_MULT>::~Vector() {\n clear();\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nbool Vector<T, INIT_CAP, CAP_MULT>::isEmpty() const {\n return items == 0;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nint Vector<T, INIT_CAP, CAP_MULT>::size() const {\n return items;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nint Vector<T, INIT_CAP, CAP_MULT>::capacity() const {\n return cap;\n}\n\n\/\/\/ Insert value at the end.\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::append(const T &val) {\n _append(val);\n}\n\n\/\/\/ Insert value at the beginning.\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::prepend(const T &val) {\n insert(0, val);\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::insert(int pos, const T &val) {\n checkAlloc();\n assert(pos >= 0 && pos < cap && \"Position out of bounds!\");\n shiftLeft(pos); \/\/ Effectively moving right.\n data[pos] = val;\n items++;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::print() const {\n using namespace std;\n cout << \"[ \";\n if (isEmpty()) {\n cout << \"empty\";\n }\n for (decltype(cap) i = 0; i < cap; i++) {\n cout << convert(data[i]);\n if (i < cap - 1) {\n cout << \", \";\n }\n }\n cout << \" ]\" << endl;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::clear() {\n if (data) {\n delete[] data;\n data = nullptr;\n }\n items = cap = 0;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::shrinkToFit() {\n if (items == cap) return;\n alloc(items);\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nT Vector<T, INIT_CAP, CAP_MULT>::operator[](int pos) {\n assert(pos >= 0 && pos < cap && \"Position out of bounds!\");\n return data[pos];\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nconst T &Vector<T, INIT_CAP, CAP_MULT>::operator[](int pos) const {\n assert(pos >= 0 && pos < cap && \"Position out of bounds!\");\n return data[pos];\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::remove(const T &val) {\n removeFrom(val);\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::removeAt(int pos) {\n assert(pos >= 0 && pos < cap && \"Position out of bounds!\");\n data[pos] = T();\n items--;\n shiftRight(pos); \/\/ Effectively moving left.\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::fillDefault(T *ptr, int n) {\n for (decltype(n) i = 0; i < n; i++) {\n ptr[i] = T();\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::alloc(int size) {\n auto newCap = size;\n auto *newData = new T[newCap];\n if (newCap > cap) {\n fillDefault(newData, newCap);\n }\n if (items > 0) {\n memcpy(newData, data, items * sizeof(T));\n delete[] data;\n }\n data = newData;\n cap = newCap;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::checkAlloc() {\n if (items != cap) return;\n alloc(cap == 0 ? INIT_CAP : cap * CAP_MULT);\n}\n\n\/\/\/ Appends value but only checks capacity if check is set.\n\/** This saves processing time when appending very many items. *\/\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::_append(const T &val, bool check) {\n if (check) {\n checkAlloc();\n }\n data[items++] = val;\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::shiftRight(int pos) {\n for (decltype(pos) i = pos; i < items; i++) {\n std::swap(data[i], data[i+1]);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::shiftLeft(int pos) {\n for (decltype(pos) i = items; i >= pos; i--) {\n std::swap(data[i], data[i+1]);\n }\n}\n\ntemplate <typename T, int INIT_CAP, int CAP_MULT>\nvoid Vector<T, INIT_CAP, CAP_MULT>::removeFrom(const T &val, int pos) {\n for (decltype(pos) i = pos; i < items; i++) {\n auto &item = data[i];\n if (item == val) {\n item = T(); \/\/ Clear.\n items--;\n shiftRight(i); \/\/ Effectively moving left.\n removeFrom(val, i);\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"rosplan_planning_system\/PlanParser.h\"\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nnamespace KCL_rosplan {\n\n\tvoid PlanParser::reset() {\n\t\tfilter_objects.clear();\n\t\tfilter_attributes.clear();\n\t\tknowledge_filter.clear();\n\t\taction_list.clear();\n\t}\n\n\t\/*----------------------*\/\n\t\/* Post processing plan *\/\n\t\/*----------------------*\/\n\n\t\/**\n\t * parses the output of popf, generating a list of action messages.\n\t *\/\n\tvoid PlanParser::preparePlan(std::string &dataPath, PlanningEnvironment &environment, size_t freeActionID) {\n\n\t\t\/\/ trim the end of any existing plan\n\t\twhile(action_list.size() > freeActionID)\n\t\t\taction_list.pop_back();\n\n\t\t\/\/ popf output\n\t\tstd::ifstream planfile;\n\t\tplanfile.open((dataPath + \"plan.pddl\").c_str());\n\t\t\n\t\tint curr, next; \n\t\tstd::string line;\n\t\tstd::vector<rosplan_dispatch_msgs::ActionDispatch> potentialPlan;\n\t\tdouble planDuration;\n\t\tdouble expectedPlanDuration = 0;\n\n\t\twhile(!planfile.eof()) {\n\n\t\t\tgetline(planfile, line);\n\n\t\t\tif (line.substr(0,6).compare(\"; Plan\") == 0) {\n\t\t\t\texpectedPlanDuration = atof(line.substr(25).c_str());\n\t\t\t} else if (line.substr(0,6).compare(\"; Time\")!=0) {\n\t\t\t\t\/\/consume useless lines\n\t\t\t} else {\n\n\t\t\t\tpotentialPlan.clear();\n\t\t\t\tsize_t planFreeActionID = freeActionID;\n\t\t\t\tplanDuration = 0;\n\n\t\t\t\twhile(!planfile.eof() && line.compare(\"\")!=0) {\n\n\t\t\t\t\tgetline(planfile, line);\n\t\t\t\t\tif (line.length()<2)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\trosplan_dispatch_msgs::ActionDispatch msg;\n\n\t\t\t\t\t\/\/ action ID\n\t\t\t\t\tmsg.action_id = planFreeActionID;\n\t\t\t\t\tplanFreeActionID++;\n\n\t\t\t\t\t\/\/ dispatchTime\n\t\t\t\t\tcurr=line.find(\":\");\n\t\t\t\t\tdouble dispatchTime = (double)atof(line.substr(0,curr).c_str());\n\t\t\t\t\tmsg.dispatch_time = dispatchTime;\n\n\t\t\t\t\t\/\/ name\n\t\t\t\t\tcurr=line.find(\"(\")+1;\n\t\t\t\t\tnext=line.find(\" \",curr);\n\t\t\t\t\tstd::string name = line.substr(curr,next-curr).c_str();\n\t\t\t\t\tmsg.name = name;\n\n\t\t\t\t\t\/\/ parameters\n\t\t\t\t\tstd::vector<std::string> params;\n\t\t\t\t\tcurr=next+1;\n\t\t\t\t\tnext=line.find(\")\",curr);\n\t\t\t\t\tint at = curr;\n\t\t\t\t\twhile(at < next) {\n\t\t\t\t\t\tint cc = line.find(\" \",curr);\n\t\t\t\t\t\tint cc1 = line.find(\")\",curr);\n\t\t\t\t\t\tcurr = cc<cc1?cc:cc1;\n\t\t\t\t\t\tstd::string param = environment.name_map[line.substr(at,curr-at)];\n\t\t\t\t\t\tparams.push_back(param);\n\t\t\t\t\t\t++curr;\n\t\t\t\t\t\tat = curr;\n\t\t\t\t\t}\n\t\t\t\t\tprocessPDDLParameters(msg, params, environment);\n\n\t\t\t\t\t\/\/ duration\n\t\t\t\t\tcurr=line.find(\"[\",curr)+1;\n\t\t\t\t\tnext=line.find(\"]\",curr);\n\t\t\t\t\tmsg.duration = (double)atof(line.substr(curr,next-curr).c_str());\n\n\t\t\t\t\tpotentialPlan.push_back(msg);\n\n\t\t\t\t\t\/\/ update plan duration\n\t\t\t\t\tcurr=line.find(\":\");\n\t\t\t\t\tplanDuration = msg.duration + atof(line.substr(0,curr).c_str());\n\t\t\t\t}\n\n\t\t\t\tif(planDuration - expectedPlanDuration < 0.01) {\n\n\t\t\t\t\t\/\/ trim any previously read plan\n\t\t\t\t\twhile(action_list.size() > freeActionID) {\n\t\t\t\t\t\taction_list.pop_back();\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ save better optimised plan\n\t\t\t\t\tfor(size_t i=0;i<potentialPlan.size();i++) {\n\t\t\t\t\t\taction_list.push_back(potentialPlan[i]);\n\t\t\t\t\t\tgenerateFilter(environment);\n\t\t\t\t\t}\n\n\t\t\t\t\ttotal_plan_duration = planDuration;\n\n\t\t\t\t} else {\n\t\t\t\t\tROS_INFO(\"Duration: %f, expected %f; plan discarded\", planDuration, expectedPlanDuration);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tplanfile.close();\n\t}\n\n\t\/**\n\t * processes the parameters of a single PDDL action into an ActionDispatch message\n\t *\/\n\tvoid PlanParser::processPDDLParameters(rosplan_dispatch_msgs::ActionDispatch &msg, std::vector<std::string> ¶ms, PlanningEnvironment &environment) {\n\n\t\t\/\/ find the correct PDDL operator definition\n\t\tstd::map<std::string,std::vector<std::string> >::iterator ait;\n\t\tait = environment.domain_operators.find(msg.name);\n\t\tif(ait != environment.domain_operators.end()) {\n\n\t\t\t\/\/ add the PDDL parameters to the action dispatch\n\t\t\tfor(size_t i=0; i<ait->second.size(); i++) {\n\t\t\t\tdiagnostic_msgs::KeyValue pair;\n\t\t\t\tpair.key = ait->second[i];\n\t\t\t\tpair.value = params[i];\n\t\t\t\tmsg.parameters.push_back(pair);\n\n\t\t\t\t\/\/ prepare object existence for the knowledge filter\n\t\t\t\tbool add = true;\n\t\t\t\tfor(size_t j=0; j<filter_objects.size(); j++)\n\t\t\t\t\tif(0==filter_objects[j].compare(params[i])) add = false;\n\t\t\t\tif(add) filter_objects.push_back(params[i]);\n\t\t\t}\n\n\t\t\t\/\/ prepare object attributes for the knowledge filter\n\t\t\tfor(size_t i=0; i<environment.domain_operator_precondition_map[msg.name].size(); i++) {\n\t\t\t\tstd::vector<std::string> filterAttribute;\n\t\t\t\tstd::vector<std::string> precondition = environment.domain_operator_precondition_map[msg.name][i];\n\t\t\t\tfilterAttribute.push_back(precondition[0]);\n\t\t\t\tfor(size_t j=1; j<precondition.size(); j++) {\n\t\t\t\t\t\/\/ label\n\t\t\t\t\tif(j>1) filterAttribute.push_back(precondition[j]);\n\t\t\t\t\t\/\/ instance name\n\t\t\t\t\tfor(size_t k=0;k<ait->second.size();k++) {\n\t\t\t\t\t\tif(0==ait->second[k].compare(precondition[j]))\n\t\t\t\t\t\t\tfilterAttribute.push_back(params[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfilter_attributes.push_back(filterAttribute);\n\t\t\t}\n\n\t\t\t\/\/ add non-PDDL knowledge items to action dispatch\n\t\t\tstd::map<std::string,std::vector<std::string> >::iterator pit;\n\t\t\tfor(size_t i=0; i<params.size(); i++) {\n\t\t\t\tpit = environment.domain_predicates.find(ait->second[i]);\n\t\t\t\tfor(size_t j=0; j<environment.instance_attributes.size(); j++) {\n\t\t\t\t\t\/\/ TODO have knowledge items be passed more cleanly in dispatch\n\t\t\t\t\tif(0==environment.instance_attributes[j].instance_name.compare(params[i])\n\t\t\t\t\t\t\t&& environment.instance_attributes[j].knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) {\n\t\t\t\t\t\tfor(size_t k=0; k<environment.instance_attributes[j].values.size(); k++) {\n\t\t\t\t\t\t\tdiagnostic_msgs::KeyValue pair;\n\t\t\t\t\t\t\tpair.key = environment.instance_attributes[j].instance_name\n\t\t\t\t\t\t\t\t\t+ \"_\" + environment.instance_attributes[j].attribute_name\n\t\t\t\t\t\t\t\t\t + \"_\" + environment.instance_attributes[j].values[k].key;\n\t\t\t\t\t\t\tpair.value = environment.instance_attributes[j].values[k].value;\n\t\t\t\t\t\t\tmsg.parameters.push_back(pair);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} \/\/ end of operator\n\t}\n\n\t\/*-----------------*\/\n\t\/* Planning filter *\/\n\t\/*-----------------*\/\n\n\t\/**\n\t * populates the knowledge filter messages\n\t *\/\n\tvoid PlanParser::generateFilter(PlanningEnvironment &environment) {\n\n\t\tknowledge_filter.clear();\n\n\t\t\/\/ populate filter message with objects\n\t\tfor(size_t i=0; i<filter_objects.size(); i++) {\n\t\t\trosplan_knowledge_msgs::KnowledgeItem filterItem;\n\t\t\tfilterItem.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;\n\t\t\tfilterItem.instance_type = environment.object_type_map[filter_objects[i]];\n\t\t\tfilterItem.instance_name = filter_objects[i];\n\t\t\tknowledge_filter.push_back(filterItem);\n\t\t}\n\n\t\t\/\/ populate filter message with attributes\n\t\t\/\/ TODO only statics, not all preconditions.\n\t\tfor(size_t i=0; i<filter_attributes.size(); i++) {\n\t\t\trosplan_knowledge_msgs::KnowledgeItem filterItem;\n\t\t\tfilterItem.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;\n\t\t\tfilterItem.attribute_name = filter_attributes[i][0];\n\t\t\tfilterItem.instance_type = environment.object_type_map[filter_attributes[i][1]];\n\t\t\tfilterItem.instance_name = filter_attributes[i][1];\n\t\t\tfor(size_t j=2; j<filter_attributes[i].size()-1; j+=2) {\n\t\t\t\tdiagnostic_msgs::KeyValue pair;\n\t\t\t\tpair.key = filter_attributes[i][j];\n\t\t\t\tpair.value = filter_attributes[i][j+1];\n\t\t\t\tfilterItem.values.push_back(pair);\n\t\t\t}\n\t\t\tknowledge_filter.push_back(filterItem);\n\t\t}\n\t}\n} \/\/ close namespace\n<commit_msg>Fixed bug in parser when action has no parameters<commit_after>#include \"rosplan_planning_system\/PlanParser.h\"\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nnamespace KCL_rosplan {\n\n\tvoid PlanParser::reset() {\n\t\tfilter_objects.clear();\n\t\tfilter_attributes.clear();\n\t\tknowledge_filter.clear();\n\t\taction_list.clear();\n\t}\n\n\t\/*----------------------*\/\n\t\/* Post processing plan *\/\n\t\/*----------------------*\/\n\n\t\/**\n\t * parses the output of popf, generating a list of action messages.\n\t *\/\n\tvoid PlanParser::preparePlan(std::string &dataPath, PlanningEnvironment &environment, size_t freeActionID) {\n\n\t\t\/\/ trim the end of any existing plan\n\t\twhile(action_list.size() > freeActionID)\n\t\t\taction_list.pop_back();\n\n\t\t\/\/ popf output\n\t\tstd::ifstream planfile;\n\t\tplanfile.open((dataPath + \"plan.pddl\").c_str());\n\t\t\n\t\tint curr, next; \n\t\tstd::string line;\n\t\tstd::vector<rosplan_dispatch_msgs::ActionDispatch> potentialPlan;\n\t\tdouble planDuration;\n\t\tdouble expectedPlanDuration = 0;\n\n\t\twhile(!planfile.eof()) {\n\n\t\t\tgetline(planfile, line);\n\n\t\t\tif (line.substr(0,6).compare(\"; Plan\") == 0) {\n\t\t\t\texpectedPlanDuration = atof(line.substr(25).c_str());\n\t\t\t} else if (line.substr(0,6).compare(\"; Time\")!=0) {\n\t\t\t\t\/\/consume useless lines\n\t\t\t} else {\n\n\t\t\t\tpotentialPlan.clear();\n\t\t\t\tsize_t planFreeActionID = freeActionID;\n\t\t\t\tplanDuration = 0;\n\n\t\t\t\twhile(!planfile.eof() && line.compare(\"\")!=0) {\n\n\t\t\t\t\tgetline(planfile, line);\n\t\t\t\t\tif (line.length()<2)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\trosplan_dispatch_msgs::ActionDispatch msg;\n\n\t\t\t\t\t\/\/ action ID\n\t\t\t\t\tmsg.action_id = planFreeActionID;\n\t\t\t\t\tplanFreeActionID++;\n\n\t\t\t\t\t\/\/ dispatchTime\n\t\t\t\t\tcurr=line.find(\":\");\n\t\t\t\t\tdouble dispatchTime = (double)atof(line.substr(0,curr).c_str());\n\t\t\t\t\tmsg.dispatch_time = dispatchTime;\n\n\t\t\t\t\t\/\/ check for parameters\n\t\t\t\t\tcurr=line.find(\"(\")+1;\n\t\t\t\t\tbool paramsExist = (line.find(\" \",curr) > line.find(\")\",curr));\n\t\t\t\t\t\n\t\t\t\t\tif(paramsExist) {\n\n\t\t\t\t\t\t\/\/ name\n\t\t\t\t\t\tnext=line.find(\" \",curr);\n\t\t\t\t\t\tstd::string name = line.substr(curr,next-curr).c_str();\n\t\t\t\t\t\tmsg.name = name;\n\n\t\t\t\t\t\t\/\/ parameters\n\t\t\t\t\t\tstd::vector<std::string> params;\n\t\t\t\t\t\tcurr=next+1;\n\t\t\t\t\t\tnext=line.find(\")\",curr);\n\t\t\t\t\t\tint at = curr;\n\t\t\t\t\t\twhile(at < next) {\n\t\t\t\t\t\t\tint cc = line.find(\" \",curr);\n\t\t\t\t\t\t\tint cc1 = line.find(\")\",curr);\n\t\t\t\t\t\t\tcurr = cc<cc1?cc:cc1;\n\t\t\t\t\t\t\tstd::string param = environment.name_map[line.substr(at,curr-at)];\n\t\t\t\t\t\t\tparams.push_back(param);\n\t\t\t\t\t\t\t++curr;\n\t\t\t\t\t\t\tat = curr;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessPDDLParameters(msg, params, environment);\n\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\/\/ name\n\t\t\t\t\t\tnext=line.find(\")\",curr);\n\t\t\t\t\t\tstd::string name = line.substr(curr,next-curr).c_str();\n\t\t\t\t\t\tmsg.name = name;\n\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ duration\n\t\t\t\t\tcurr=line.find(\"[\",curr)+1;\n\t\t\t\t\tnext=line.find(\"]\",curr);\n\t\t\t\t\tmsg.duration = (double)atof(line.substr(curr,next-curr).c_str());\n\n\t\t\t\t\tpotentialPlan.push_back(msg);\n\n\t\t\t\t\t\/\/ update plan duration\n\t\t\t\t\tcurr=line.find(\":\");\n\t\t\t\t\tplanDuration = msg.duration + atof(line.substr(0,curr).c_str());\n\t\t\t\t}\n\n\t\t\t\tif(planDuration - expectedPlanDuration < 0.01) {\n\n\t\t\t\t\t\/\/ trim any previously read plan\n\t\t\t\t\twhile(action_list.size() > freeActionID) {\n\t\t\t\t\t\taction_list.pop_back();\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ save better optimised plan\n\t\t\t\t\tfor(size_t i=0;i<potentialPlan.size();i++) {\n\t\t\t\t\t\taction_list.push_back(potentialPlan[i]);\n\t\t\t\t\t\tgenerateFilter(environment);\n\t\t\t\t\t}\n\n\t\t\t\t\ttotal_plan_duration = planDuration;\n\n\t\t\t\t} else {\n\t\t\t\t\tROS_INFO(\"Duration: %f, expected %f; plan discarded\", planDuration, expectedPlanDuration);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tplanfile.close();\n\t}\n\n\t\/**\n\t * processes the parameters of a single PDDL action into an ActionDispatch message\n\t *\/\n\tvoid PlanParser::processPDDLParameters(rosplan_dispatch_msgs::ActionDispatch &msg, std::vector<std::string> ¶ms, PlanningEnvironment &environment) {\n\n\t\t\/\/ find the correct PDDL operator definition\n\t\tstd::map<std::string,std::vector<std::string> >::iterator ait;\n\t\tait = environment.domain_operators.find(msg.name);\n\t\tif(ait != environment.domain_operators.end()) {\n\n\t\t\t\/\/ add the PDDL parameters to the action dispatch\n\t\t\tfor(size_t i=0; i<ait->second.size(); i++) {\n\t\t\t\tdiagnostic_msgs::KeyValue pair;\n\t\t\t\tpair.key = ait->second[i];\n\t\t\t\tpair.value = params[i];\n\t\t\t\tmsg.parameters.push_back(pair);\n\n\t\t\t\t\/\/ prepare object existence for the knowledge filter\n\t\t\t\tbool add = true;\n\t\t\t\tfor(size_t j=0; j<filter_objects.size(); j++)\n\t\t\t\t\tif(0==filter_objects[j].compare(params[i])) add = false;\n\t\t\t\tif(add) filter_objects.push_back(params[i]);\n\t\t\t}\n\n\t\t\t\/\/ prepare object attributes for the knowledge filter\n\t\t\tfor(size_t i=0; i<environment.domain_operator_precondition_map[msg.name].size(); i++) {\n\t\t\t\tstd::vector<std::string> filterAttribute;\n\t\t\t\tstd::vector<std::string> precondition = environment.domain_operator_precondition_map[msg.name][i];\n\t\t\t\tfilterAttribute.push_back(precondition[0]);\n\t\t\t\tfor(size_t j=1; j<precondition.size(); j++) {\n\t\t\t\t\t\/\/ label\n\t\t\t\t\tif(j>1) filterAttribute.push_back(precondition[j]);\n\t\t\t\t\t\/\/ instance name\n\t\t\t\t\tfor(size_t k=0;k<ait->second.size();k++) {\n\t\t\t\t\t\tif(0==ait->second[k].compare(precondition[j]))\n\t\t\t\t\t\t\tfilterAttribute.push_back(params[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfilter_attributes.push_back(filterAttribute);\n\t\t\t}\n\n\t\t\t\/\/ add non-PDDL knowledge items to action dispatch\n\t\t\tstd::map<std::string,std::vector<std::string> >::iterator pit;\n\t\t\tfor(size_t i=0; i<params.size(); i++) {\n\t\t\t\tpit = environment.domain_predicates.find(ait->second[i]);\n\t\t\t\tfor(size_t j=0; j<environment.instance_attributes.size(); j++) {\n\t\t\t\t\t\/\/ TODO have knowledge items be passed more cleanly in dispatch\n\t\t\t\t\tif(0==environment.instance_attributes[j].instance_name.compare(params[i])\n\t\t\t\t\t\t\t&& environment.instance_attributes[j].knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) {\n\t\t\t\t\t\tfor(size_t k=0; k<environment.instance_attributes[j].values.size(); k++) {\n\t\t\t\t\t\t\tdiagnostic_msgs::KeyValue pair;\n\t\t\t\t\t\t\tpair.key = environment.instance_attributes[j].instance_name\n\t\t\t\t\t\t\t\t\t+ \"_\" + environment.instance_attributes[j].attribute_name\n\t\t\t\t\t\t\t\t\t + \"_\" + environment.instance_attributes[j].values[k].key;\n\t\t\t\t\t\t\tpair.value = environment.instance_attributes[j].values[k].value;\n\t\t\t\t\t\t\tmsg.parameters.push_back(pair);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} \/\/ end of operator\n\t}\n\n\t\/*-----------------*\/\n\t\/* Planning filter *\/\n\t\/*-----------------*\/\n\n\t\/**\n\t * populates the knowledge filter messages\n\t *\/\n\tvoid PlanParser::generateFilter(PlanningEnvironment &environment) {\n\n\t\tknowledge_filter.clear();\n\n\t\t\/\/ populate filter message with objects\n\t\tfor(size_t i=0; i<filter_objects.size(); i++) {\n\t\t\trosplan_knowledge_msgs::KnowledgeItem filterItem;\n\t\t\tfilterItem.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;\n\t\t\tfilterItem.instance_type = environment.object_type_map[filter_objects[i]];\n\t\t\tfilterItem.instance_name = filter_objects[i];\n\t\t\tknowledge_filter.push_back(filterItem);\n\t\t}\n\n\t\t\/\/ populate filter message with attributes\n\t\t\/\/ TODO only statics, not all preconditions.\n\t\tfor(size_t i=0; i<filter_attributes.size(); i++) {\n\t\t\trosplan_knowledge_msgs::KnowledgeItem filterItem;\n\t\t\tfilterItem.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;\n\t\t\tfilterItem.attribute_name = filter_attributes[i][0];\n\t\t\tfilterItem.instance_type = environment.object_type_map[filter_attributes[i][1]];\n\t\t\tfilterItem.instance_name = filter_attributes[i][1];\n\t\t\tfor(size_t j=2; j<filter_attributes[i].size()-1; j+=2) {\n\t\t\t\tdiagnostic_msgs::KeyValue pair;\n\t\t\t\tpair.key = filter_attributes[i][j];\n\t\t\t\tpair.value = filter_attributes[i][j+1];\n\t\t\t\tfilterItem.values.push_back(pair);\n\t\t\t}\n\t\t\tknowledge_filter.push_back(filterItem);\n\t\t}\n\t}\n} \/\/ close namespace\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include \"Board.h\"\r\n\r\nusing namespace std;\r\n\r\nBoard::Board() {\r\n\tPposition = new char[n];\r\n\tfor (int i = 0; i<n; i++)\r\n\t\tPposition[i] = ' ';\r\n}\r\nBoard::~Board() {\r\n\tdelete[] Pposition;\r\n}\r\nBoard::Board(const Board &obj) {\r\n\tPposition = new char[n];\r\n\tfor (int i = 0; i<n; i++)\r\n\t\tPposition[i] = obj.Pposition[i];\r\n\r\n}\r\nBoard & Board::operator = (const Board & obj)\r\n\/\/ assignment operator\r\n{\r\n\tif (this != &obj)\r\n\t{\r\n\t\tdelete Pposition;\r\n\t\tPposition = new char[n];\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tPposition[i] = obj.Pposition[i];\r\n\t}\r\n\treturn *this;\r\n}\r\nvoid Board::PrintBoard() {\/\/print the board\r\n\tcout << \"+---+---+---+\" << endl;\r\n\tcout << \"|\" << Pposition[0] << \" |\" << Pposition[1] << \" |\" << Pposition[2] << \" |\" << endl;\r\n\tcout << \"+---+---+---+\" << endl;\r\n\tcout << \"|\" << Pposition[3] << \" |\" << Pposition[4] << \" |\" << Pposition[5] << \" |\" << endl;\r\n\tcout << \"+---+---+---+\" << endl;\r\n\tcout << \"|\" << Pposition[6] << \" |\" << Pposition[7] << \" |\" << Pposition[8] << \" |\" << endl;\r\n\tcout << \"+---+---+---+\" << endl;\r\n\r\n}\r\nchar Board::getposition(int p)const {\r\n\treturn Pposition[p];\r\n\r\n}\r\nbool Board::DetermineWinner() {\/\/return true if we have winner function printwinner determine we have winner or not\r\n\tif (Pposition[0] == Pposition[1] && Pposition[0] == Pposition[2] && Pposition[0] != ' ')\r\n\t\treturn true;\r\n\telse if (Pposition[3] == Pposition[4] && Pposition[3] == Pposition[5] && Pposition[3] != ' ')\r\n\t\treturn true;\r\n\telse if (Pposition[6] == Pposition[7] && Pposition[6] == Pposition[8] && Pposition[6] != ' ')\r\n\t\treturn true;\r\n\telse if (Pposition[0] == Pposition[4] && Pposition[0] == Pposition[8] && Pposition[0] != ' ')\r\n\t\treturn true;\r\n\telse if (Pposition[2] == Pposition[4] && Pposition[2] == Pposition[6] && Pposition[2] != ' ')\r\n\t\treturn true;\r\n\telse if (Pposition[0] == Pposition[3] && Pposition[0] == Pposition[6] && Pposition[0] != ' ')\r\n\t\treturn true;\r\n\telse if (Pposition[1] == Pposition[4] && Pposition[1] == Pposition[7] && Pposition[1] != ' ')\r\n\t\treturn true;\r\n\telse if (Pposition[2] == Pposition[5] && Pposition[2] == Pposition[8] && Pposition[2] != ' ')\r\n\t\treturn true;\r\n\r\n\treturn false;\r\n}\r\n\r\nint Board::printwinner(int count, Board *s)\/\/determine we have winner or not\r\n{\r\n\tif (s->DetermineWinner() != true) {\r\n\t\t\/*cout << \"No winner.\" << endl;*\/\r\n\t\treturn 0;\r\n\t}\r\n\telse if (s->DetermineWinner() == true) {\r\n\t\tif (count % 2 == 0)\r\n\t\t\treturn 1;\/* cout << \"winner is:\" << objB->getsymbol() << endl;*\/\r\n\t\telse if (count % 2 != 0)\r\n\t\t\treturn 2; \/*cout << \"winner is:\" << objA->getsymbol() << endl;*\/\r\n\t}\r\n}\r\n\r\nvoid Board::SetPosition(int position,char player) const{\/\/set symbol to the board\r\n\r\n\tif (Pposition[position] == ' ') {\r\n\t\tPposition[position] = player;\r\n\t}\r\n\telse if (Pposition[position] != ' ') {\r\n\t\tcout << \"error\" << endl;\r\n\t}\r\n}\r\n\r\n<commit_msg>Delete Board.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <babylon\/misc\/file_tools.h>\n#include <babylon\/asio\/asio.h>\n\n#define STB_IMAGE_IMPLEMENTATION\n#if defined(__GNUC__) || defined(__MINGW32__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wcast-qual\"\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#if __GNUC__ > 5\n#pragma GCC diagnostic ignored \"-Wmisleading-indentation\"\n#pragma GCC diagnostic ignored \"-Wshift-negative-value\"\n#endif\n#if __GNUC__ > 6\n\/\/ Use of GNU statement expression extension\n#endif\n#pragma GCC diagnostic ignored \"-Wswitch-default\"\n#endif\n#if _MSC_VER && !__INTEL_COMPILER\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n#include <stb_image\/stb_image.h>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n#if defined(__GNUC__) || defined(__MINGW32__)\n#pragma GCC diagnostic pop\n#endif\n\n#include <babylon\/core\/array_buffer_view.h>\n#include <babylon\/core\/filesystem.h>\n#include <babylon\/core\/logging.h>\n#include <babylon\/core\/string.h>\n#include <babylon\/interfaces\/igl_rendering_context.h>\n#include <babylon\/loading\/progress_event.h>\n#include <babylon\/utils\/base64.h>\n\n#include <stdexcept>\n\nnamespace BABYLON {\n\nstd::string FileTools::PreprocessUrl(const std::string& url)\n{\n return url;\n}\n\nstd::string FileTools::_CleanUrl(std::string url)\n{\n String::replaceInPlace(url, \"#\", \"%23\");\n return url;\n}\n\nvoid FileTools::LoadImageFromUrl(\n std::string url, const std::function<void(const Image& img)>& onLoad,\n const std::function<void(const std::string& message, const std::string& exception)>& onError,\n bool flipVertically)\n{\n url = FileTools::_CleanUrl(url);\n url = FileTools::PreprocessUrl(url);\n\n std::string filename = url;\n\n auto onArrayBufferReceived = [=](const ArrayBuffer & buffer) {\n auto image = ArrayBufferToImage(buffer, flipVertically);\n onLoad(image);\n };\n auto onErrorWrapper = [=](const std::string& errorMessage) {\n onError(errorMessage, \"\");\n };\n\n asio::LoadUrlAsync_Binary(url, onArrayBufferReceived, onErrorWrapper);\n}\n\nvoid FileTools::LoadImageFromBuffer(\n const std::variant<std::string, ArrayBuffer, ArrayBufferView, Image>& input, bool invertY,\n const std::function<void(const Image& img)>& onLoad,\n const std::function<void(const std::string& message, const std::string& exception)>& onError)\n{\n if (!onLoad) {\n return;\n }\n\n if (std::holds_alternative<std::string>(input)) {\n onLoad(FileTools::StringToImage(std::get<std::string>(input), invertY));\n }\n else if (std::holds_alternative<ArrayBuffer>(input)) {\n onLoad(FileTools::ArrayBufferToImage(std::get<ArrayBuffer>(input), invertY));\n }\n else if (std::holds_alternative<ArrayBufferView>(input)) {\n onLoad(FileTools::ArrayBufferToImage(std::get<ArrayBufferView>(input).uint8Array, invertY));\n }\n else if (std::holds_alternative<Image>(input)) {\n onLoad(std::get<Image>(input));\n }\n else {\n auto errorMessage = \"Loading image from url not supported\";\n if (onError) {\n onError(errorMessage, \"\");\n }\n else {\n throw std::runtime_error(errorMessage);\n }\n }\n}\n\nImage FileTools::ArrayBufferToImage(const ArrayBuffer& buffer, bool flipVertically)\n{\n if (buffer.empty()) {\n return Image();\n }\n auto bufferSize = static_cast<int>(buffer.size());\n int w = -1, h = -1, n = -1;\n int req_comp = STBI_rgb_alpha;\n\n stbi_set_flip_vertically_on_load(flipVertically);\n unsigned char * ucharBuffer = stbi_load_from_memory(buffer.data(), bufferSize, &w, &h, &n, req_comp);\n stbi_set_flip_vertically_on_load(false);\n\n if (!ucharBuffer)\n return Image();\n\n n = STBI_rgb_alpha;\n Image image (ucharBuffer, w * h * n, w, h, n, (n == 3) ? GL::RGB : GL::RGBA);\n stbi_image_free(ucharBuffer);\n return image;\n}\n\nImage FileTools::StringToImage(const std::string& uri, bool flipVertically)\n{\n const auto IsDataURI = [](const std::string& in) -> bool {\n std::string header = \"data:application\/octet-stream;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:image\/jpeg;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:image\/png;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:image\/bmp;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:image\/gif;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:text\/plain;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:application\/gltf-buffer;base64,\";\n return in.find(header) == 0;\n };\n\n const auto DecodeDataURI = [](std::vector<unsigned char>* out, std::string& mime_type,\n const std::string& in, size_t reqBytes, bool checkSize) -> bool {\n std::string header = \"data:application\/octet-stream;base64,\";\n std::string data;\n if (in.find(header) == 0) {\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n\n if (data.empty()) {\n header = \"data:image\/jpeg;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"image\/jpeg\";\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n }\n\n if (data.empty()) {\n header = \"data:image\/png;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"image\/png\";\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n }\n\n if (data.empty()) {\n header = \"data:image\/bmp;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"image\/bmp\";\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n }\n\n if (data.empty()) {\n header = \"data:image\/gif;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"image\/gif\";\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n }\n\n if (data.empty()) {\n header = \"data:text\/plain;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"text\/plain\";\n data = Base64::decode(in.substr(header.size()));\n }\n }\n\n if (data.empty()) {\n header = \"data:application\/gltf-buffer;base64,\";\n if (in.find(header) == 0) {\n data = Base64::decode(in.substr(header.size()));\n }\n }\n\n if (data.empty()) {\n return false;\n }\n\n if (checkSize) {\n if (data.size() != reqBytes) {\n return false;\n }\n out->resize(reqBytes);\n }\n else {\n out->resize(data.size());\n }\n std::copy(data.begin(), data.end(), out->begin());\n return true;\n };\n\n const auto LoadImageData = [](Image& image, int req_width, int req_height,\n const unsigned char* bytes, int size, bool flipVertically) -> bool {\n int w = 0, h = 0, comp = 0, req_comp = 0;\n\n unsigned char* data = nullptr;\n\n \/\/ force 32-bit textures for common Vulkan compatibility. It appears that\n \/\/ some GPU drivers do not support 24-bit images for Vulkan\n req_comp = 4;\n int bits = 8;\n\n stbi_set_flip_vertically_on_load(flipVertically);\n\n \/\/ It is possible that the image we want to load is a 16bit per channel\n \/\/ image We are going to attempt to load it as 16bit per channel, and if it\n \/\/ worked, set the image data accodingly. We are casting the returned\n \/\/ pointer into unsigned char, because we are representing \"bytes\". But we\n \/\/ are updating the Image metadata to signal that this image uses 2 bytes\n \/\/ (16bits) per channel:\n if (stbi_is_16_bit_from_memory(bytes, size)) {\n data = reinterpret_cast<unsigned char*>(\n stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp));\n if (data) {\n bits = 16;\n }\n }\n\n \/\/ at this point, if data is still NULL, it means that the image wasn't\n \/\/ 16bit per channel, we are going to load it as a normal 8bit per channel\n \/\/ mage as we used to do:\n \/\/ if image cannot be decoded, ignore parsing and keep it by its path\n \/\/ don't break in this case\n \/\/ FIXME we should only enter this function if the image is embedded. If\n \/\/ image->uri references\n \/\/ an image file, it should be left as it is. Image loading should not be\n \/\/ mandatory (to support other formats)\n if (!data)\n data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp);\n if (!data) {\n BABYLON_LOG_WARN(\"StringToImage\",\n \"Unknown image format. STB cannot decode image data for image\")\n return false;\n }\n\n stbi_set_flip_vertically_on_load(false);\n\n if ((w < 1) || (h < 1)) {\n stbi_image_free(data);\n BABYLON_LOG_ERROR(\"StringToImage\", \"Invalid image data for image\")\n return false;\n }\n\n if (req_width > 0) {\n if (req_width != w) {\n stbi_image_free(data);\n BABYLON_LOG_ERROR(\"StringToImage\", \"Image width mismatch for image\")\n return false;\n }\n }\n\n if (req_height > 0) {\n if (req_height != h) {\n stbi_image_free(data);\n BABYLON_LOG_ERROR(\"StringToImage\", \"Image height mismatch. for image\")\n return false;\n }\n }\n\n image.width = w;\n image.height = h;\n image.depth = req_comp;\n image.mode = (req_comp == 3) ? GL::RGB : GL::RGBA;\n image.data.resize(static_cast<size_t>(w * h * req_comp) * size_t(bits \/ 8));\n std::copy(data, data + w * h * req_comp * (bits \/ 8), image.data.begin());\n stbi_image_free(data);\n\n return true;\n };\n\n Image image;\n std::vector<unsigned char> img;\n std::string mimeType;\n if (IsDataURI(uri)) {\n if (!DecodeDataURI(&img, mimeType, uri, 0, false)) {\n BABYLON_LOG_ERROR(\"Failed to decode image from uri: %s\", uri.c_str())\n return Image();\n }\n }\n\n if (LoadImageData(image, 0, 0, &img.at(0), static_cast<int>(img.size()), flipVertically)) {\n return image;\n }\n\n return Image();\n}\n\n\/\/ Superfluous params?\nconstexpr const char* dummyResponseUrl = \"\";\nconstexpr const char* dummyExceptionString = \"\";\nconstexpr const char* dummyProgressType = \"\";\n\nvoid FileTools::LoadFile(\n const std::string& url,\n const std::function<void(const std::variant<std::string, ArrayBuffer>& data,\n const std::string& responseURL)>& onSuccess,\n const std::function<void(const ProgressEvent& event)>& onProgress,\n bool useArrayBuffer,\n const std::function<void(const std::string& message, const std::string& exception)>& onError)\n{\n \/\/ LoadFile's signature is extremely complicated for no good reason\n \/\/ Let's write some wrappers from the simple callbacks of BABYLON::asio\n \/\/ We will need to refactor this later\n\n\n std::string url_clean = FileTools::_CleanUrl(url);\n url_clean = FileTools::PreprocessUrl(url);\n\n auto onErrorWrapper = [onError](const std::string& errorMessage) {\n if (onError)\n onError(errorMessage, dummyExceptionString);\n };\n auto onProgressWrapper = [onProgress](bool lengthComputable, size_t loaded, size_t total) {\n if (onProgress)\n onProgress({dummyProgressType, lengthComputable, loaded, total});\n };\n\n if (useArrayBuffer)\n {\n auto onSuccessWrapper = [onSuccess](const ArrayBuffer& data) {\n if (onSuccess)\n onSuccess(data, dummyResponseUrl);\n };\n asio::LoadUrlAsync_Binary(url_clean, onSuccessWrapper, onErrorWrapper, onProgressWrapper);\n }\n else\n {\n auto onSuccessWrapper = [onSuccess](const std::string& data) {\n if (onSuccess) {\n onSuccess(data, dummyResponseUrl);\n }\n };\n asio::LoadUrlAsync_Text(url_clean, onSuccessWrapper, onErrorWrapper, onProgressWrapper);\n }\n\n asio::Service_WaitAll_Sync();\n \/\/std::cout << \"WaitAll finished\\n\";\n}\n\n} \/\/ end of namespace BABYLON\n<commit_msg>FileTools::LoadFile \/ don't call Service_WaitAll_Sync<commit_after>#include <babylon\/misc\/file_tools.h>\n#include <babylon\/asio\/asio.h>\n\n#define STB_IMAGE_IMPLEMENTATION\n#if defined(__GNUC__) || defined(__MINGW32__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wcast-qual\"\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#if __GNUC__ > 5\n#pragma GCC diagnostic ignored \"-Wmisleading-indentation\"\n#pragma GCC diagnostic ignored \"-Wshift-negative-value\"\n#endif\n#if __GNUC__ > 6\n\/\/ Use of GNU statement expression extension\n#endif\n#pragma GCC diagnostic ignored \"-Wswitch-default\"\n#endif\n#if _MSC_VER && !__INTEL_COMPILER\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n#include <stb_image\/stb_image.h>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n#if defined(__GNUC__) || defined(__MINGW32__)\n#pragma GCC diagnostic pop\n#endif\n\n#include <babylon\/core\/array_buffer_view.h>\n#include <babylon\/core\/filesystem.h>\n#include <babylon\/core\/logging.h>\n#include <babylon\/core\/string.h>\n#include <babylon\/interfaces\/igl_rendering_context.h>\n#include <babylon\/loading\/progress_event.h>\n#include <babylon\/utils\/base64.h>\n\n#include <stdexcept>\n\nnamespace BABYLON {\n\nstd::string FileTools::PreprocessUrl(const std::string& url)\n{\n return url;\n}\n\nstd::string FileTools::_CleanUrl(std::string url)\n{\n String::replaceInPlace(url, \"#\", \"%23\");\n return url;\n}\n\nvoid FileTools::LoadImageFromUrl(\n std::string url, const std::function<void(const Image& img)>& onLoad,\n const std::function<void(const std::string& message, const std::string& exception)>& onError,\n bool flipVertically)\n{\n url = FileTools::_CleanUrl(url);\n url = FileTools::PreprocessUrl(url);\n\n std::string filename = url;\n\n auto onArrayBufferReceived = [=](const ArrayBuffer & buffer) {\n auto image = ArrayBufferToImage(buffer, flipVertically);\n onLoad(image);\n };\n auto onErrorWrapper = [=](const std::string& errorMessage) {\n onError(errorMessage, \"\");\n };\n\n asio::LoadUrlAsync_Binary(url, onArrayBufferReceived, onErrorWrapper);\n}\n\nvoid FileTools::LoadImageFromBuffer(\n const std::variant<std::string, ArrayBuffer, ArrayBufferView, Image>& input, bool invertY,\n const std::function<void(const Image& img)>& onLoad,\n const std::function<void(const std::string& message, const std::string& exception)>& onError)\n{\n if (!onLoad) {\n return;\n }\n\n if (std::holds_alternative<std::string>(input)) {\n onLoad(FileTools::StringToImage(std::get<std::string>(input), invertY));\n }\n else if (std::holds_alternative<ArrayBuffer>(input)) {\n onLoad(FileTools::ArrayBufferToImage(std::get<ArrayBuffer>(input), invertY));\n }\n else if (std::holds_alternative<ArrayBufferView>(input)) {\n onLoad(FileTools::ArrayBufferToImage(std::get<ArrayBufferView>(input).uint8Array, invertY));\n }\n else if (std::holds_alternative<Image>(input)) {\n onLoad(std::get<Image>(input));\n }\n else {\n auto errorMessage = \"Loading image from url not supported\";\n if (onError) {\n onError(errorMessage, \"\");\n }\n else {\n throw std::runtime_error(errorMessage);\n }\n }\n}\n\nImage FileTools::ArrayBufferToImage(const ArrayBuffer& buffer, bool flipVertically)\n{\n if (buffer.empty()) {\n return Image();\n }\n auto bufferSize = static_cast<int>(buffer.size());\n int w = -1, h = -1, n = -1;\n int req_comp = STBI_rgb_alpha;\n\n stbi_set_flip_vertically_on_load(flipVertically);\n unsigned char * ucharBuffer = stbi_load_from_memory(buffer.data(), bufferSize, &w, &h, &n, req_comp);\n stbi_set_flip_vertically_on_load(false);\n\n if (!ucharBuffer)\n return Image();\n\n n = STBI_rgb_alpha;\n Image image (ucharBuffer, w * h * n, w, h, n, (n == 3) ? GL::RGB : GL::RGBA);\n stbi_image_free(ucharBuffer);\n return image;\n}\n\nImage FileTools::StringToImage(const std::string& uri, bool flipVertically)\n{\n const auto IsDataURI = [](const std::string& in) -> bool {\n std::string header = \"data:application\/octet-stream;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:image\/jpeg;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:image\/png;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:image\/bmp;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:image\/gif;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:text\/plain;base64,\";\n if (in.find(header) == 0) {\n return true;\n }\n\n header = \"data:application\/gltf-buffer;base64,\";\n return in.find(header) == 0;\n };\n\n const auto DecodeDataURI = [](std::vector<unsigned char>* out, std::string& mime_type,\n const std::string& in, size_t reqBytes, bool checkSize) -> bool {\n std::string header = \"data:application\/octet-stream;base64,\";\n std::string data;\n if (in.find(header) == 0) {\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n\n if (data.empty()) {\n header = \"data:image\/jpeg;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"image\/jpeg\";\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n }\n\n if (data.empty()) {\n header = \"data:image\/png;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"image\/png\";\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n }\n\n if (data.empty()) {\n header = \"data:image\/bmp;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"image\/bmp\";\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n }\n\n if (data.empty()) {\n header = \"data:image\/gif;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"image\/gif\";\n data = Base64::decode(in.substr(header.size())); \/\/ cut mime string.\n }\n }\n\n if (data.empty()) {\n header = \"data:text\/plain;base64,\";\n if (in.find(header) == 0) {\n mime_type = \"text\/plain\";\n data = Base64::decode(in.substr(header.size()));\n }\n }\n\n if (data.empty()) {\n header = \"data:application\/gltf-buffer;base64,\";\n if (in.find(header) == 0) {\n data = Base64::decode(in.substr(header.size()));\n }\n }\n\n if (data.empty()) {\n return false;\n }\n\n if (checkSize) {\n if (data.size() != reqBytes) {\n return false;\n }\n out->resize(reqBytes);\n }\n else {\n out->resize(data.size());\n }\n std::copy(data.begin(), data.end(), out->begin());\n return true;\n };\n\n const auto LoadImageData = [](Image& image, int req_width, int req_height,\n const unsigned char* bytes, int size, bool flipVertically) -> bool {\n int w = 0, h = 0, comp = 0, req_comp = 0;\n\n unsigned char* data = nullptr;\n\n \/\/ force 32-bit textures for common Vulkan compatibility. It appears that\n \/\/ some GPU drivers do not support 24-bit images for Vulkan\n req_comp = 4;\n int bits = 8;\n\n stbi_set_flip_vertically_on_load(flipVertically);\n\n \/\/ It is possible that the image we want to load is a 16bit per channel\n \/\/ image We are going to attempt to load it as 16bit per channel, and if it\n \/\/ worked, set the image data accodingly. We are casting the returned\n \/\/ pointer into unsigned char, because we are representing \"bytes\". But we\n \/\/ are updating the Image metadata to signal that this image uses 2 bytes\n \/\/ (16bits) per channel:\n if (stbi_is_16_bit_from_memory(bytes, size)) {\n data = reinterpret_cast<unsigned char*>(\n stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp));\n if (data) {\n bits = 16;\n }\n }\n\n \/\/ at this point, if data is still NULL, it means that the image wasn't\n \/\/ 16bit per channel, we are going to load it as a normal 8bit per channel\n \/\/ mage as we used to do:\n \/\/ if image cannot be decoded, ignore parsing and keep it by its path\n \/\/ don't break in this case\n \/\/ FIXME we should only enter this function if the image is embedded. If\n \/\/ image->uri references\n \/\/ an image file, it should be left as it is. Image loading should not be\n \/\/ mandatory (to support other formats)\n if (!data)\n data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp);\n if (!data) {\n BABYLON_LOG_WARN(\"StringToImage\",\n \"Unknown image format. STB cannot decode image data for image\")\n return false;\n }\n\n stbi_set_flip_vertically_on_load(false);\n\n if ((w < 1) || (h < 1)) {\n stbi_image_free(data);\n BABYLON_LOG_ERROR(\"StringToImage\", \"Invalid image data for image\")\n return false;\n }\n\n if (req_width > 0) {\n if (req_width != w) {\n stbi_image_free(data);\n BABYLON_LOG_ERROR(\"StringToImage\", \"Image width mismatch for image\")\n return false;\n }\n }\n\n if (req_height > 0) {\n if (req_height != h) {\n stbi_image_free(data);\n BABYLON_LOG_ERROR(\"StringToImage\", \"Image height mismatch. for image\")\n return false;\n }\n }\n\n image.width = w;\n image.height = h;\n image.depth = req_comp;\n image.mode = (req_comp == 3) ? GL::RGB : GL::RGBA;\n image.data.resize(static_cast<size_t>(w * h * req_comp) * size_t(bits \/ 8));\n std::copy(data, data + w * h * req_comp * (bits \/ 8), image.data.begin());\n stbi_image_free(data);\n\n return true;\n };\n\n Image image;\n std::vector<unsigned char> img;\n std::string mimeType;\n if (IsDataURI(uri)) {\n if (!DecodeDataURI(&img, mimeType, uri, 0, false)) {\n BABYLON_LOG_ERROR(\"Failed to decode image from uri: %s\", uri.c_str())\n return Image();\n }\n }\n\n if (LoadImageData(image, 0, 0, &img.at(0), static_cast<int>(img.size()), flipVertically)) {\n return image;\n }\n\n return Image();\n}\n\n\/\/ Superfluous params?\nconstexpr const char* dummyResponseUrl = \"\";\nconstexpr const char* dummyExceptionString = \"\";\nconstexpr const char* dummyProgressType = \"\";\n\nvoid FileTools::LoadFile(\n const std::string& url,\n const std::function<void(const std::variant<std::string, ArrayBuffer>& data,\n const std::string& responseURL)>& onSuccess,\n const std::function<void(const ProgressEvent& event)>& onProgress,\n bool useArrayBuffer,\n const std::function<void(const std::string& message, const std::string& exception)>& onError)\n{\n \/\/ LoadFile's signature is extremely complicated for no good reason\n \/\/ Let's write some wrappers from the simple callbacks of BABYLON::asio\n \/\/ We will need to refactor this later\n\n\n std::string url_clean = FileTools::_CleanUrl(url);\n url_clean = FileTools::PreprocessUrl(url);\n\n auto onErrorWrapper = [onError](const std::string& errorMessage) {\n if (onError)\n onError(errorMessage, dummyExceptionString);\n };\n auto onProgressWrapper = [onProgress](bool lengthComputable, size_t loaded, size_t total) {\n if (onProgress)\n onProgress({dummyProgressType, lengthComputable, loaded, total});\n };\n\n if (useArrayBuffer)\n {\n auto onSuccessWrapper = [onSuccess](const ArrayBuffer& data) {\n if (onSuccess)\n onSuccess(data, dummyResponseUrl);\n };\n asio::LoadUrlAsync_Binary(url_clean, onSuccessWrapper, onErrorWrapper, onProgressWrapper);\n }\n else\n {\n auto onSuccessWrapper = [onSuccess](const std::string& data) {\n if (onSuccess) {\n onSuccess(data, dummyResponseUrl);\n }\n };\n asio::LoadUrlAsync_Text(url_clean, onSuccessWrapper, onErrorWrapper, onProgressWrapper);\n }\n\n \/\/ asio::Service_WaitAll_Sync();\n \/\/std::cout << \"WaitAll finished\\n\";\n}\n\n} \/\/ end of namespace BABYLON\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Implements View::GetXXXDragThreshold on Linux.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>[SPIR-V] Handle 16\/16, 16\/16\/16\/16 (float and norm) and 32f<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"databaseconnectionstatuslabel.hxx\"\n\n#include <apps\/app\/app.hxx>\n\nPROJECT_NAMESPACE_BEGIN\nWIDGETS_NAMESPACE_BEGIN\n\nDatabaseConnectionStatusLabel::DatabaseConnectionStatusLabel(QWidget* p)\n : StatusLabel(p)\n{\n connect(APP_NAMESPACE::App::get(), &APP_NAMESPACE::App::databaseIsAvailable, this, &DatabaseConnectionStatusLabel::onDatabaseAvailable);\n connect(APP_NAMESPACE::App::get(), &APP_NAMESPACE::App::databaseIsUnavailable, this, &DatabaseConnectionStatusLabel::onDatabaseUnavailable);\n}\n\nvoid DatabaseConnectionStatusLabel::onDatabaseAvailable(const QString &msg)\n{\n setText(msg);\n}\n\nvoid DatabaseConnectionStatusLabel::onDatabaseUnavailable(const QString &msg)\n{\n setText(msg);\n}\n\nWIDGETS_NAMESPACE_END\nPROJECT_NAMESPACE_END\n<commit_msg>set initial status<commit_after>#include \"databaseconnectionstatuslabel.hxx\"\n\n#include <apps\/app\/app.hxx>\n\nPROJECT_NAMESPACE_BEGIN\nWIDGETS_NAMESPACE_BEGIN\n\nDatabaseConnectionStatusLabel::DatabaseConnectionStatusLabel(QWidget* p)\n : StatusLabel(p)\n{\n connect(APP_NAMESPACE::App::get(), &APP_NAMESPACE::App::databaseIsAvailable, this, &DatabaseConnectionStatusLabel::onDatabaseAvailable);\n connect(APP_NAMESPACE::App::get(), &APP_NAMESPACE::App::databaseIsUnavailable, this, &DatabaseConnectionStatusLabel::onDatabaseUnavailable);\n\n onDatabaseUnavailable(tr(\"Database not available\"));\n}\n\nvoid DatabaseConnectionStatusLabel::onDatabaseAvailable(const QString &msg)\n{\n setText(msg);\n}\n\nvoid DatabaseConnectionStatusLabel::onDatabaseUnavailable(const QString &msg)\n{\n setText(msg);\n}\n\nWIDGETS_NAMESPACE_END\nPROJECT_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Stubs.cpp - Swift Language ABI Runtime Stubs ---------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Misc stubs for functions which should be in swift.swift, but are difficult\n\/\/ or impossible to write in swift at the moment.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <mach\/mach_time.h>\n#include <sys\/resource.h>\n#include <sys\/errno.h>\n#include <pthread.h>\n#include <unistd.h>\n#include <cstring>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <sys\/stat.h> \/\/ stat\n#include <fcntl.h> \/\/ open\n#include <unistd.h> \/\/ read, close\n#include <dirent.h>\n#include <limits.h>\n#include \"llvm\/ADT\/StringExtras.h\"\n\n\/\/ FIXME: We shouldn't be writing implemenetations for functions in the swift\n\/\/ module in C, and this isn't really an ideal place to put those\n\/\/ implementations.\nextern \"C\" void _TSs5printFT3valSi_T_(int64_t l) {\n printf(\"%lld\", l);\n}\n\nextern \"C\" void _TSs5printFT3valSu_T_(uint64_t l) {\n printf(\"%llu\", l);\n}\n\nextern \"C\" void _TSs5printFT3valSd_T_(double l) {\n char Buffer[256];\n sprintf(Buffer, \"%g\", l);\n if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr)\n strcat(Buffer, \".0\");\n printf(\"%s\", Buffer);\n}\n\n\/\/ static func String(v : Int128, radix : Int) -> String\nextern \"C\"\nunsigned long long\nprint_int(char* TmpBuffer, __int64_t buf_len, __int128_t X, uint64_t Radix,\n bool uppercase) {\n assert(Radix != 0 && Radix <= 36 && \"Invalid radix for string conversion\");\n char *P = TmpBuffer;\n\n bool WasNeg = X < 0;\n __uint128_t Y = WasNeg ? -X : X;\n\n if (Y == 0) {\n *P++ = '0';\n } else if (Radix == 10) {\n while (Y) {\n *P++ = '0' + char(Y % 10);\n Y \/= 10;\n }\n } else {\n unsigned Radix32 = Radix;\n while (Y) {\n *P++ = llvm::hexdigit(Y % Radix32, !uppercase);\n Y \/= Radix32;\n }\n }\n\n if (WasNeg) *P++ = '-';\n std::reverse(TmpBuffer, P);\n return size_t(P - TmpBuffer);\n}\n\n\/\/ static func String(v : UInt128, radix : Int) -> String\nextern \"C\"\nunsigned long long\nprint_uint(char* TmpBuffer, __int64_t buf_len, __uint128_t Y, uint64_t Radix,\n bool uppercase) {\n assert(Radix != 0 && Radix <= 36 && \"Invalid radix for string conversion\");\n char *P = TmpBuffer;\n\n if (Y == 0) {\n *P++ = '0';\n } else if (Radix == 10) {\n while (Y) {\n *P++ = '0' + char(Y % 10);\n Y \/= 10;\n }\n } else {\n unsigned Radix32 = Radix;\n while (Y) {\n *P++ = llvm::hexdigit(Y % Radix32, !uppercase);\n Y \/= Radix32;\n }\n }\n\n std::reverse(TmpBuffer, P);\n return size_t(P - TmpBuffer);\n}\n\n\/\/ static func String(v : Double) -> String\nextern \"C\"\nunsigned long long\nprint_double(char* Buffer, double X) {\n long long i = sprintf(Buffer, \"%g\", X);\n if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr) {\n Buffer[i++] = '.';\n Buffer[i++] = '0';\n }\n if (i < 0) {\n __builtin_trap();\n }\n return i;\n}\n\nextern \"C\" bool _TSb13getLogicValuefRSbFT_Bi1_(bool* b) {\n return *b;\n}\n\nextern \"C\" bool swift_getBool(bool b) {\n return b;\n}\n\nstatic bool\n_swift_replOutputIsUTF8(void) {\n const char *lang = getenv(\"LANG\");\n return lang && strstr(lang, \"UTF-8\");\n}\n\nextern \"C\"\nuint32_t\nswift_replOutputIsUTF8(void) {\n static auto rval = _swift_replOutputIsUTF8();\n return rval;\n}\n\n#if defined(__i386__) || defined(__x86_64__)\nstatic inline uint64_t\nrdtsc() {\n uint32_t lo, hi;\n asm(\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n return uint64_t(hi) << 32 | lo;\n}\n#else\n#error \"not supported\"\n#endif\n\nstatic double interruptOverhead;\nstatic double loopOverhead;\n\nstatic uint64_t\n_swift_startBenchmark(void) {\n return rdtsc();\n}\n\nextern \"C\"\nvoid\nswift_printBenchmark(uint64_t start, uint64_t laps, char *buffer, int64_t len) {\n double val = rdtsc() - start;\n val \/= laps;\n val \/= interruptOverhead;\n val -= loopOverhead;\n printf(\"%12.2f %*s\\n\", val, (int)len, buffer);\n}\n\nextern \"C\"\n__attribute__((noinline,used))\n__typeof__(&_swift_startBenchmark)\n_swift_initBenchmark() asm(\"_swift_startBenchmark\");\n\n__typeof__(&_swift_startBenchmark)\n_swift_initBenchmark() {\n asm(\".symbol_resolver _swift_startBenchmark\");\n union {\n unsigned reg[4*3];\n char brand[48];\n } u;\n char brand[48];\n char *s2 = u.brand;\n char *s1 = brand;\n unsigned eax, ebx, ecx, edx;\n memset(&u, 0, sizeof(u));\n int r;\n\n \/\/ Let's not have the OS compete with our CPU time if we can avoid it\n r = setvbuf(stdout, 0, _IOFBF, 0);\n assert(r == 0);\n\n \/\/ XXX -- There doesn't seem to be an API to figure out the max value\n sched_param schedParam;\n schedParam.sched_priority = 79;\n r = pthread_setschedparam(pthread_self(), SCHED_FIFO, &schedParam);\n assert(r == 0);\n\n eax = 0x80000002;\n asm(\"cpuid\" : \"+a\" (eax), \"=b\" (ebx), \"=c\" (ecx), \"=d\" (edx));\n u.reg[0] = eax;\n u.reg[1] = ebx;\n u.reg[2] = ecx;\n u.reg[3] = edx;\n\n eax = 0x80000003;\n asm(\"cpuid\" : \"+a\" (eax), \"=b\" (ebx), \"=c\" (ecx), \"=d\" (edx));\n u.reg[4] = eax;\n u.reg[5] = ebx;\n u.reg[6] = ecx;\n u.reg[7] = edx;\n\n eax = 0x80000004;\n asm(\"cpuid\" : \"+a\" (eax), \"=b\" (ebx), \"=c\" (ecx), \"=d\" (edx));\n u.reg[8] = eax;\n u.reg[9] = ebx;\n u.reg[10] = ecx;\n u.reg[11] = edx;\n\n while (*s2 == ' ') {\n s2++;\n }\n do {\n while (s2[0] == ' ' && s2[1] == ' ') {\n s2++;\n }\n } while ((*s1++ = *s2++));\n printf(\"Processor: %s\\n\\n\", brand);\n\n uint64_t start = rdtsc();\n for (unsigned long i = 0; i < 1000000000ull; i++) {\n asm(\"\");\n }\n double delta = (rdtsc() - start) \/ 1000000000.0;\n assert((delta >= 1.0 && delta < 1.05) || (delta >= 2.0 && delta < 2.05));\n if (delta >= 2.0) {\n loopOverhead = 2.0;\n interruptOverhead = delta \/ 2.0;\n } else {\n loopOverhead = 1.0;\n interruptOverhead = delta \/ 1.0;\n }\n assert((interruptOverhead - 1.0) < 0.01);\n\n eax = 6;\n asm(\"cpuid\" : \"+a\" (eax), \"=b\" (ebx), \"=c\" (ecx), \"=d\" (edx));\n\n if (eax & 2) {\n fprintf(stderr, \"WARNING: TurboBoost. Results will be less reliable.\\n\");\n fprintf(stderr, \" Consider: sudo \/usr\/local\/bin\/pstates -D\\n\\n\");\n }\n\n if (geteuid()) {\n fprintf(stderr, \"WARNING: Non-elevated priority. Results will be less reliable.\\n\");\n fprintf(stderr, \" Consider: sudo .\/myBench\\n\\n\");\n }\n\n return _swift_startBenchmark;\n}\n\nextern \"C\"\nint\nswift_file_open(const char* filename)\n{\n return open(filename, O_RDONLY);\n}\n\nextern \"C\"\nint\nswift_file_close(int fd)\n{\n return close(fd);\n}\n\nextern \"C\"\nsize_t\nswift_file_read(int fd, char* buf, size_t nb)\n{\n return read(fd, buf, nb);\n}\n\nextern \"C\"\nsize_t\nswift_fd_size(int fd)\n{\n struct stat buf;\n int err = fstat(fd, &buf);\n assert(err == 0);\n (void) err;\n return buf.st_size;\n}\n\nstruct readdir_tuple_s {\n char *str;\n int64_t len;\n};\n\nextern \"C\"\nstruct readdir_tuple_s\nposix_readdir_hack(DIR *d)\n{\n struct readdir_tuple_s rval = { NULL, 0 };\n struct dirent *dp;\n if ((dp = readdir(d))) {\n rval.str = dp->d_name;\n rval.len = dp->d_namlen;\n }\n return rval;\n}\n\nextern \"C\"\nint64_t\nposix_isDirectory_hack(const char *path)\n{\n struct stat sb;\n int r = stat(path, &sb);\n (void)r;\n assert(r != -1);\n return S_ISDIR(sb.st_mode);\n}\n\nextern \"C\"\nint\nposix_get_errno(void)\n{\n return errno; \/\/ errno is not a global, but a macro\n}\n\nextern \"C\"\nvoid\nposix_set_errno(int value)\n{\n errno = value; \/\/ errno is not a global, but a macro\n}\n<commit_msg>Don't append \".0\" to \"inf\" and \"-inf\".<commit_after>\/\/===--- Stubs.cpp - Swift Language ABI Runtime Stubs ---------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Misc stubs for functions which should be in swift.swift, but are difficult\n\/\/ or impossible to write in swift at the moment.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <mach\/mach_time.h>\n#include <sys\/resource.h>\n#include <sys\/errno.h>\n#include <pthread.h>\n#include <unistd.h>\n#include <cstring>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <sys\/stat.h> \/\/ stat\n#include <fcntl.h> \/\/ open\n#include <unistd.h> \/\/ read, close\n#include <dirent.h>\n#include <limits.h>\n#include \"llvm\/ADT\/StringExtras.h\"\n\n\/\/ static func String(v : Int128, radix : Int) -> String\nextern \"C\"\nunsigned long long\nprint_int(char* TmpBuffer, __int64_t buf_len, __int128_t X, uint64_t Radix,\n bool uppercase) {\n assert(Radix != 0 && Radix <= 36 && \"Invalid radix for string conversion\");\n char *P = TmpBuffer;\n\n bool WasNeg = X < 0;\n __uint128_t Y = WasNeg ? -X : X;\n\n if (Y == 0) {\n *P++ = '0';\n } else if (Radix == 10) {\n while (Y) {\n *P++ = '0' + char(Y % 10);\n Y \/= 10;\n }\n } else {\n unsigned Radix32 = Radix;\n while (Y) {\n *P++ = llvm::hexdigit(Y % Radix32, !uppercase);\n Y \/= Radix32;\n }\n }\n\n if (WasNeg) *P++ = '-';\n std::reverse(TmpBuffer, P);\n return size_t(P - TmpBuffer);\n}\n\n\/\/ static func String(v : UInt128, radix : Int) -> String\nextern \"C\"\nunsigned long long\nprint_uint(char* TmpBuffer, __int64_t buf_len, __uint128_t Y, uint64_t Radix,\n bool uppercase) {\n assert(Radix != 0 && Radix <= 36 && \"Invalid radix for string conversion\");\n char *P = TmpBuffer;\n\n if (Y == 0) {\n *P++ = '0';\n } else if (Radix == 10) {\n while (Y) {\n *P++ = '0' + char(Y % 10);\n Y \/= 10;\n }\n } else {\n unsigned Radix32 = Radix;\n while (Y) {\n *P++ = llvm::hexdigit(Y % Radix32, !uppercase);\n Y \/= Radix32;\n }\n }\n\n std::reverse(TmpBuffer, P);\n return size_t(P - TmpBuffer);\n}\n\n\/\/ static func String(v : Double) -> String\nextern \"C\"\nunsigned long long\nprint_double(char* Buffer, double X) {\n long long i = sprintf(Buffer, \"%g\", X);\n \/\/ Add \".0\" to a float that (a) is not in scientific notation, (b) does not\n \/\/ already have a fractional part, and (c) is not infinite.\n if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr &&\n strchr(Buffer, 'n') == nullptr) {\n Buffer[i++] = '.';\n Buffer[i++] = '0';\n }\n if (i < 0) {\n __builtin_trap();\n }\n return i;\n}\n\n\/\/ FIXME: We shouldn't be writing implemenetations for functions in the swift\n\/\/ module in C, and this isn't really an ideal place to put those\n\/\/ implementations.\nextern \"C\" void _TSs5printFT3valSi_T_(int64_t l) {\n printf(\"%lld\", l);\n}\n\nextern \"C\" void _TSs5printFT3valSu_T_(uint64_t l) {\n printf(\"%llu\", l);\n}\n\nextern \"C\" void _TSs5printFT3valSd_T_(double l) {\n char Buffer[256];\n unsigned long long i = print_double(Buffer, l);\n Buffer[i] = '\\0';\n printf(\"%s\", Buffer);\n}\n\nextern \"C\" bool _TSb13getLogicValuefRSbFT_Bi1_(bool* b) {\n return *b;\n}\n\nextern \"C\" bool swift_getBool(bool b) {\n return b;\n}\n\nstatic bool\n_swift_replOutputIsUTF8(void) {\n const char *lang = getenv(\"LANG\");\n return lang && strstr(lang, \"UTF-8\");\n}\n\nextern \"C\"\nuint32_t\nswift_replOutputIsUTF8(void) {\n static auto rval = _swift_replOutputIsUTF8();\n return rval;\n}\n\n#if defined(__i386__) || defined(__x86_64__)\nstatic inline uint64_t\nrdtsc() {\n uint32_t lo, hi;\n asm(\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n return uint64_t(hi) << 32 | lo;\n}\n#else\n#error \"not supported\"\n#endif\n\nstatic double interruptOverhead;\nstatic double loopOverhead;\n\nstatic uint64_t\n_swift_startBenchmark(void) {\n return rdtsc();\n}\n\nextern \"C\"\nvoid\nswift_printBenchmark(uint64_t start, uint64_t laps, char *buffer, int64_t len) {\n double val = rdtsc() - start;\n val \/= laps;\n val \/= interruptOverhead;\n val -= loopOverhead;\n printf(\"%12.2f %*s\\n\", val, (int)len, buffer);\n}\n\nextern \"C\"\n__attribute__((noinline,used))\n__typeof__(&_swift_startBenchmark)\n_swift_initBenchmark() asm(\"_swift_startBenchmark\");\n\n__typeof__(&_swift_startBenchmark)\n_swift_initBenchmark() {\n asm(\".symbol_resolver _swift_startBenchmark\");\n union {\n unsigned reg[4*3];\n char brand[48];\n } u;\n char brand[48];\n char *s2 = u.brand;\n char *s1 = brand;\n unsigned eax, ebx, ecx, edx;\n memset(&u, 0, sizeof(u));\n int r;\n\n \/\/ Let's not have the OS compete with our CPU time if we can avoid it\n r = setvbuf(stdout, 0, _IOFBF, 0);\n assert(r == 0);\n\n \/\/ XXX -- There doesn't seem to be an API to figure out the max value\n sched_param schedParam;\n schedParam.sched_priority = 79;\n r = pthread_setschedparam(pthread_self(), SCHED_FIFO, &schedParam);\n assert(r == 0);\n\n eax = 0x80000002;\n asm(\"cpuid\" : \"+a\" (eax), \"=b\" (ebx), \"=c\" (ecx), \"=d\" (edx));\n u.reg[0] = eax;\n u.reg[1] = ebx;\n u.reg[2] = ecx;\n u.reg[3] = edx;\n\n eax = 0x80000003;\n asm(\"cpuid\" : \"+a\" (eax), \"=b\" (ebx), \"=c\" (ecx), \"=d\" (edx));\n u.reg[4] = eax;\n u.reg[5] = ebx;\n u.reg[6] = ecx;\n u.reg[7] = edx;\n\n eax = 0x80000004;\n asm(\"cpuid\" : \"+a\" (eax), \"=b\" (ebx), \"=c\" (ecx), \"=d\" (edx));\n u.reg[8] = eax;\n u.reg[9] = ebx;\n u.reg[10] = ecx;\n u.reg[11] = edx;\n\n while (*s2 == ' ') {\n s2++;\n }\n do {\n while (s2[0] == ' ' && s2[1] == ' ') {\n s2++;\n }\n } while ((*s1++ = *s2++));\n printf(\"Processor: %s\\n\\n\", brand);\n\n uint64_t start = rdtsc();\n for (unsigned long i = 0; i < 1000000000ull; i++) {\n asm(\"\");\n }\n double delta = (rdtsc() - start) \/ 1000000000.0;\n assert((delta >= 1.0 && delta < 1.05) || (delta >= 2.0 && delta < 2.05));\n if (delta >= 2.0) {\n loopOverhead = 2.0;\n interruptOverhead = delta \/ 2.0;\n } else {\n loopOverhead = 1.0;\n interruptOverhead = delta \/ 1.0;\n }\n assert((interruptOverhead - 1.0) < 0.01);\n\n eax = 6;\n asm(\"cpuid\" : \"+a\" (eax), \"=b\" (ebx), \"=c\" (ecx), \"=d\" (edx));\n\n if (eax & 2) {\n fprintf(stderr, \"WARNING: TurboBoost. Results will be less reliable.\\n\");\n fprintf(stderr, \" Consider: sudo \/usr\/local\/bin\/pstates -D\\n\\n\");\n }\n\n if (geteuid()) {\n fprintf(stderr, \"WARNING: Non-elevated priority. Results will be less reliable.\\n\");\n fprintf(stderr, \" Consider: sudo .\/myBench\\n\\n\");\n }\n\n return _swift_startBenchmark;\n}\n\nextern \"C\"\nint\nswift_file_open(const char* filename)\n{\n return open(filename, O_RDONLY);\n}\n\nextern \"C\"\nint\nswift_file_close(int fd)\n{\n return close(fd);\n}\n\nextern \"C\"\nsize_t\nswift_file_read(int fd, char* buf, size_t nb)\n{\n return read(fd, buf, nb);\n}\n\nextern \"C\"\nsize_t\nswift_fd_size(int fd)\n{\n struct stat buf;\n int err = fstat(fd, &buf);\n assert(err == 0);\n (void) err;\n return buf.st_size;\n}\n\nstruct readdir_tuple_s {\n char *str;\n int64_t len;\n};\n\nextern \"C\"\nstruct readdir_tuple_s\nposix_readdir_hack(DIR *d)\n{\n struct readdir_tuple_s rval = { NULL, 0 };\n struct dirent *dp;\n if ((dp = readdir(d))) {\n rval.str = dp->d_name;\n rval.len = dp->d_namlen;\n }\n return rval;\n}\n\nextern \"C\"\nint64_t\nposix_isDirectory_hack(const char *path)\n{\n struct stat sb;\n int r = stat(path, &sb);\n (void)r;\n assert(r != -1);\n return S_ISDIR(sb.st_mode);\n}\n\nextern \"C\"\nint\nposix_get_errno(void)\n{\n return errno; \/\/ errno is not a global, but a macro\n}\n\nextern \"C\"\nvoid\nposix_set_errno(int value)\n{\n errno = value; \/\/ errno is not a global, but a macro\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3184\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>SWDEV-2 - Change OpenCL version number from 3184 to 3185<commit_after>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3185\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"hermes1d.h\"\n\n#include \"legendre.h\"\n#include \"quad_std.h\"\n\n\/\/ This test makes sure that Legendre polynomials\n\/\/ are orthonormal.\n\n#define ERROR_SUCCESS 0\n#define ERROR_FAILURE -1\n\nint main(int argc, char* argv[])\n{\n \/\/ maximum poly degree of Legendre polynomials tested\n int max_poly_degree = 29; \/\/FIXME: should be 99\n\n \/\/ maximum allowed error\n double max_allowed_error = 1e-10;\n\n \/\/ loop over polynomial degrees, starting with 1\n double max_actual_error = 0; \n for (int poly_deg_1=0; poly_deg_1<max_poly_degree; poly_deg_1++) {\n for (int poly_deg_2=0; poly_deg_2<max_poly_degree; poly_deg_2++) {\n \/\/ integrating the Legendre polynomial of degree 'poly_deg'\n \/\/ from -1 to 1 using Gauss quadratures of orders 1, 2, ...\n \/\/ MAX_POLYORDER\n for (int quad_order=poly_deg_1 + poly_deg_2; \n quad_order<2*max_poly_degree; quad_order++) {\n int num_pts = g_quad_1d_std.get_num_points(quad_order);\n double2 *quad_tab = g_quad_1d_std.get_points(quad_order);\n double val = 0;\n for (int i=0; i<num_pts; i++) {\n double point_i = quad_tab[i][0];\n double weight_i = quad_tab[i][1];\n val += legendre_fn_tab_1d[poly_deg_1](point_i) * \n legendre_fn_tab_1d[poly_deg_2](point_i) * weight_i;\n }\n if (poly_deg_1 == poly_deg_2) { \/\/ val must be one\n if (fabs(val - 1.) > max_actual_error) \n max_actual_error = fabs(val - 1.);\n if (max_actual_error > max_allowed_error) {\n printf(\"poly_deg_1 = %d, poly_deg_2 = %d, quad_order = %d, val - 1. = %g\\n\", \n poly_deg_1, poly_deg_2, quad_order, val - 1.); \n return ERROR_FAILURE;\n }\n }\n else { \/\/ val must be zero\n if (fabs(val) > max_actual_error) \n max_actual_error = fabs(val);\n if (max_actual_error > max_allowed_error) {\n printf(\"poly_deg_1 = %d, poly_deg_2 = %d, quad_order = %d, val = %g\\n\", \n poly_deg_1, poly_deg_2, quad_order, val); \n return ERROR_FAILURE;\n }\n }\n }\n }\n }\n\n printf(\"Success!\\n\");\n return ERROR_SUCCESS;\n}\n<commit_msg>Example legendre-2 now works for p = 0, 1, ..., 50.<commit_after>#include \"hermes1d.h\"\n\n#include \"legendre.h\"\n#include \"quad_std.h\"\n\n\/\/ This test makes sure that Legendre polynomials\n\/\/ are orthonormal. It takes a lot of time.\n\n#define ERROR_SUCCESS 0\n#define ERROR_FAILURE -1\n\nint main(int argc, char* argv[])\n{\n \/\/ maximum poly degree of Legendre polynomials tested\n int max_test_poly_degree = 50; \n\n \/\/ maximum allowed error\n double max_allowed_error = 1e-12;\n\n \/\/ loop over polynomial degrees, starting with 1\n double max_actual_error = 0; \n for (int poly_deg_1=0; poly_deg_1 < max_test_poly_degree+1; poly_deg_1++) {\n for (int poly_deg_2=0; poly_deg_2<max_test_poly_degree+1; poly_deg_2++) {\n \/\/ integrating the product of Legendre polynomials of degrees \n \/\/ 'poly_deg_1' and 'poly_deg_2'from -1 to 1 using Gauss quadratures \n \/\/ of order poly_deg_1 + poly_deg_2\n for (int quad_order=poly_deg_1 + poly_deg_2; \n quad_order<2*max_test_poly_degree; quad_order++) {\n int num_pts = g_quad_1d_std.get_num_points(quad_order);\n double2 *quad_tab = g_quad_1d_std.get_points(quad_order);\n double val = 0;\n for (int i=0; i<num_pts; i++) {\n double point_i = quad_tab[i][0];\n double weight_i = quad_tab[i][1];\n val += calc_leg_pol_val(point_i, poly_deg_1) * \n calc_leg_pol_val(point_i, poly_deg_2) * weight_i;\n }\n double val_final;\n if (poly_deg_1 == poly_deg_2) val_final = val - 1.0;\n else val_final = val; \n printf(\"poly_deg_1 = %d, poly_deg_2 = %d, quad_order = %d, val_final = %g\\n\", poly_deg_1, poly_deg_2, quad_order, val_final); \n if (fabs(val_final) > max_actual_error) {\n max_actual_error = fabs(val_final);\n if (max_actual_error > max_allowed_error) {\n printf(\"Failure!\\n\");\n return ERROR_FAILURE;\n }\n }\n }\n }\n }\n\n printf(\"Success!\\n\");\n return ERROR_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3530\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>SWDEV-2 - Change OpenCL version number from 3530 to 3531<commit_after>\/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.\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#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3531\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"vision_thread.h\"\n#include \"612.h\"\n#include \"ranges.h\"\n#include \"vision_alt.h\"\n#include \"update.h\"\n#include \"ports.h\"\n#include \"particle_filter.h\"\n#include <Vision\/AxisCamera.h>\n#include <Vision\/Threshold.h>\n#include <Timer.h>\n#include <Task.h>\n#include <cstdio>\n#include <vxWorks.h>\n#include <nivision.h>\n\n#include <algorithm>\n#include <utility>\n#include <fstream>\n\n#if DEBUG_612\nconst int WRITE_IMAGE = 9;\n#endif\n\n\/\/NI function\nIMAQ_FUNC int Priv_SetWriteFileAllowed(UINT32 enable); \n\nvoid update_targets(vision_thread&, ColorImage&);\n\nvision_thread::vision_thread(AxisCamera& c, vision_processor p) : thread_obj(\"vision_processing\", (FUNCPTR)thread_worker), cam(c) {\n callback = p;\n enabled = true;\n \/\/initialize mutex\n target_lock = semBCreate(SEM_Q_PRIORITY, SEM_FULL);\n \/\/make new thread \n if (!thread_obj.Start((uinteger)this)) {\n std::printf(\"Vision: Error creating thread.\\n\");\n }\n}\n\nvision_thread::~vision_thread() {\n \/\/destroy other thread\n std::printf(\"Destroying semaphore\\n\");\n semDelete(target_lock);\n thread_obj.Stop();\n}\n\nint vision_thread::thread_worker(uinteger obj) {\n ((vision_thread*)obj)->process_loop();\n \/\/should never be reached\n return 0;\n}\n\nvoid vision_thread::process_loop() {\n \/\/this the routine puts us in here. Do vision processing\n while (true) {\n \/\/YES, I KNOW GOTOS ARE SUPPOSED TO BE EVIL. I AM USING THEM HERE\n \/\/TO AVOID NEEDLESS SENTINEL VARIABLES.\n if (enabled) {\n \/\/get picture from camera\n#if DEBUG_612\n Timer process_time;\n process_time.Start();\n#endif\n if (!camera().IsFreshImage()) {\n goto processing_footer; \/\/no new image for us to process\n }\n if (!camera().GetImage(&image)) {\n perror_612(\"Cannot Recieve Image From Camera\");\n goto processing_footer;\n }\n \/\/do vision processing\n callback(*this, image);\n#if DEBUG_612\n output_debug_info();\n \/\/std::printf(\"Processing took %f sec\\n\", process_time.Get());\n#endif\n }\n processing_footer:\n {\n Wait(0.05); \/\/should be a trivial wait compared to processing wait\n \/\/wait is here to keep sucking up processing power while polling the\n \/\/camera object\n }\n }\n}\n\nvoid vision_thread::enable() {\n enabled = true;\n}\n\nvoid vision_thread::disable() {\n enabled = false;\n}\n\nvoid vision_thread::lock_targets() {\n semTake(target_lock, WAIT_FOREVER);\n}\n\nvoid vision_thread::release_targets() {\n semGive(target_lock);\n}\n\n\/\/returns if thread is locked\nbool vision_thread::lock_targets_nowait() {\n if (semTake(target_lock, NO_WAIT) == ERROR) {\n \/\/unsuccessful\n return false;\n }\n else {\n \/\/locked\n return true;\n }\n}\n\nvision_targets::vision_targets()\n#ifdef VISION_ALT_HEURISTIC\n : bottom_t(bottom_basket), top_t(top_basket), left_t(midleft_basket), right_t(midright_basket) {\n#else\n{\n target t;\n for (unsigned i = 0; i < numtargets; i++) {\n targets_vec.push_back(t);\n }\n#endif \n registry().register_func(update_helper, (void*)this);\n}\n\nvision_targets::~vision_targets() {\n registry().unregister_func(update_helper, (void*)this);\n}\n\nvoid vision_targets::update_helper(void * obj) {\n ((vision_targets*)obj)->update();\n}\n\nvoid vision_targets::update() {\n if (get_vision_thread().lock_targets_nowait()) {\n#ifdef VISION_ALT_HEURISTIC\n bottom_t = bottom_basket;\n left_t = midleft_basket;\n right_t = midright_basket;\n top_t = top_basket;\n#else\n for (unsigned i = 0; i < numtargets; i++) {\n targets_vec.at(i) = target_arr[i];\n }\n#endif\n get_vision_thread().release_targets();\n }\n}\n\n#ifdef VISION_ALT_HEURISTIC\n\ntarget& vision_targets::bottom() {\n return bottom_t;\n}\n\ntarget& vision_targets::top() {\n return top_t;\n}\n\ntarget& vision_targets::left() {\n return left_t;\n}\n\ntarget& vision_targets::right() {\n return right_t;\n}\n\n#else\n\nstd::vector<target> vision_targets::targets() {\n return targets_vec;\n}\n\n#endif\n\nvision_thread& get_vision_thread() {\n static vision_thread t(camera(), update_targets);\n return t;\n}\n\nvision_targets& get_targets() {\n static vision_targets t;\n return t;\n}\n\n\/\/FORCE INSTANTIATION\nvision_thread& VISION_THREAD_INSTANCE = get_vision_thread();\nvision_targets& VISION_TARGETS_INSTANCE = get_targets();\n\n\/\/MUST DELETE RETURN VALUE IN CALLER\nstd::pair<report_vector*, BinaryImage*> do_threshold(ColorImage& image) {\n \/\/Threshold objects\n static Threshold HSL_THOLD(HSL_HMIN, HSL_HMAX, HSL_SMIN, HSL_SMAX, HSL_LMIN, HSL_LMAX);\n static Threshold HSI_THOLD(HSI_HMIN, HSI_HMAX, HSI_SMIN, HSI_SMAX, HSI_IMIN, HSI_IMAX);\n static Threshold HSV_THOLD(HSV_HMIN, HSV_HMAX, HSV_SMIN, HSV_SMAX, HSV_VMIN, HSV_VMAX);\n BinaryImage * result = NULL;\n if (COLOR_MODE == HSL) {\n result = image.ThresholdHSL(HSL_THOLD);\n }\n else if (COLOR_MODE == HSI) {\n result = image.ThresholdHSI(HSI_THOLD);\n }\n else if (COLOR_MODE == HSV) {\n result = image.ThresholdHSV(HSV_THOLD);\n }\n else {\n \/\/color mode undefined. Fall back to HSL\n result = image.ThresholdHSL(HSL_THOLD);\n perror_612(\"Invalid Color Mode - Falling Back to HSL\");\n }\n if (!result) {\n \/\/we have issues\n perror_612(\"Threshold Unsuccessful\");\n return std::make_pair<report_vector*, BinaryImage*>(NULL, NULL);\n }\n report_vector * ret = result->GetOrderedParticleAnalysisReports();\n \/\/delete result;\/\/TODO: may be more efficient if we can allocate one binary\n \/\/image and call imaqColorThreshold. leaving as is now\n \/\/cause it's prettier this way and POITROAE.\n return std::make_pair<report_vector*, BinaryImage*>(ret, result);\n}\n\nvoid do_particle_filter(report_vector * v, Image * img) {\n \/\/filter particles\n particle_filter filt(img);\n v->erase(std::remove_if(v->begin(), v->end(), filt), v->end());\n if (v->size() > 4) { \/\/more than four elements\n v->resize(4); \/\/drop extra elements - get four biggest\n }\n}\n\nvoid write_particles(const char * fname, const report_vector * v) {\n \/\/write particle analyses\n std::fstream o(fname, std::fstream::out | std::fstream::trunc);\n o << \"#ifndef REPORT_H_INC\\n\"\n \"#define REPORT_H_INC\\n\\n\"\n \"struct Rect {\\n\"\n \"\\tint top;\\n\"\n \"\\tint left;\\n\"\n \"\\tint height;\\n\"\n \"\\tint width;\\n\"\n \"};\\n\\n\"\n \"struct ParticleAnalysisReport {\\n\"\n \"\\tint imageHeight;\\n\"\n \"\\tint imageWidth;\\n\"\n \"\\tdouble imageTimestamp;\\n\"\n \"\\tint particleIndex;\\n\"\n \"\\tint center_mass_x;\\n\"\n \"\\tint center_mass_y;\\n\"\n \"\\tdouble center_mass_x_normalized;\\n\"\n \"\\tdouble cneter_mass_y_normalized;\\n\"\n \"\\tdouble particleArea;\\n\"\n \"\\tRect boundingRect;\\n\"\n \"\\tdouble particleToImagePercent;\\n\"\n \"\\tdouble particleQuality;\\n\"\n \"};\\n\\n\"\n \"ParticleAnalysisReport reports[] = {\\n\";\n if (v->size()) {\n report_vector::const_iterator it;\n for (it = v->begin(); it < v->end(); it++) {\n o << \"\\t{\\n\"\n \"\\t\\t\" << it->imageHeight << \",\\n\"\n \"\\t\\t\" << it->imageWidth << \",\\n\"\n \"\\t\\t\" << it->imageTimestamp << \",\\n\"\n \"\\t\\t\" << it->particleIndex << \",\\n\"\n \"\\t\\t\" << it->center_mass_x << \",\\n\"\n \"\\t\\t\" << it->center_mass_y << \",\\n\"\n \"\\t\\t\" << it->center_mass_x_normalized << \",\\n\"\n \"\\t\\t\" << it->center_mass_y_normalized << \",\\n\"\n \"\\t\\t\" << it->particleArea << \",\\n\"\n \"\\t\\t{\\n\"\n \"\\t\\t\\t\" << it->boundingRect.top << \",\\n\"\n \"\\t\\t\\t\" << it->boundingRect.left << \",\\n\"\n \"\\t\\t\\t\" << it->boundingRect.height << \",\\n\"\n \"\\t\\t\\t\" << it->boundingRect.width << \",\\n\"\n \"\\t\\t},\\n\"\n \"\\t\\t\" << it->particleToImagePercent << \",\\n\"\n \"\\t\\t\" << it->particleQuality << \",\\n\"\n \"\\t}\";\n if (it + 1 != v->end()) {\n o << ',';\n }\n o << std::endl;\n }\n }\n o << \"};\\n\\n\"\n \"#endif\" << std::endl;\n \/\/PHEW.\n o.close();\n}\n\n\nvoid update_targets(vision_thread& thread, ColorImage& image) {\n std::pair<report_vector*, BinaryImage*> ptrs = do_threshold(image);\n report_vector * reports = ptrs.first;\n BinaryImage * img = ptrs.second;\n#if DEBUG_612\n if (left_joystick.GetRawButton(WRITE_IMAGE)) {\n std::printf(\"Writing...\\n\");\n char buffer[64];\n std::sprintf(buffer, \"%f_clr.bmp\", Timer::GetFPGATimestamp());\n image.Write(buffer);\n int x = std::strlen(buffer);\n buffer[x-6] = 'b';\n buffer[x-5] = 'i';\n buffer[x-4] = 'n';\n img->Write(buffer);\n buffer[x-7] = '.';\n buffer[x-6] = 'h';\n buffer[x-5] = '\\0';\n write_particles(buffer, reports);\n }\n#endif\n if (!reports) {\n \/\/particle analysis failed.\n if (img) {\n delete img;\n }\n return;\n }\n do_particle_filter(reports, img->GetImaqImage());\n thread.lock_targets();\n target::id_and_process(reports);\n thread.release_targets();\n delete reports; \/\/free vector\n delete img; \/\/free image\n}\n<commit_msg>added include for cstring and fixed make_pair for c++0x<commit_after>#include \"vision_thread.h\"\n#include \"612.h\"\n#include \"ranges.h\"\n#include \"vision_alt.h\"\n#include \"update.h\"\n#include \"ports.h\"\n#include \"particle_filter.h\"\n#include <Vision\/AxisCamera.h>\n#include <Vision\/Threshold.h>\n#include <Timer.h>\n#include <Task.h>\n#include <cstdio>\n#include <cstring>\n#include <vxWorks.h>\n#include <nivision.h>\n\n#include <algorithm>\n#include <utility>\n#include <fstream>\n\n#if DEBUG_612\nconst int WRITE_IMAGE = 9;\n#endif\n\n\/\/NI function\nIMAQ_FUNC int Priv_SetWriteFileAllowed(UINT32 enable); \n\nvoid update_targets(vision_thread&, ColorImage&);\n\nvision_thread::vision_thread(AxisCamera& c, vision_processor p) : thread_obj(\"vision_processing\", (FUNCPTR)thread_worker), cam(c) {\n callback = p;\n enabled = true;\n \/\/initialize mutex\n target_lock = semBCreate(SEM_Q_PRIORITY, SEM_FULL);\n \/\/make new thread \n if (!thread_obj.Start((uinteger)this)) {\n std::printf(\"Vision: Error creating thread.\\n\");\n }\n}\n\nvision_thread::~vision_thread() {\n \/\/destroy other thread\n std::printf(\"Destroying semaphore\\n\");\n semDelete(target_lock);\n thread_obj.Stop();\n}\n\nint vision_thread::thread_worker(uinteger obj) {\n ((vision_thread*)obj)->process_loop();\n \/\/should never be reached\n return 0;\n}\n\nvoid vision_thread::process_loop() {\n \/\/this the routine puts us in here. Do vision processing\n while (true) {\n \/\/YES, I KNOW GOTOS ARE SUPPOSED TO BE EVIL. I AM USING THEM HERE\n \/\/TO AVOID NEEDLESS SENTINEL VARIABLES.\n if (enabled) {\n \/\/get picture from camera\n#if DEBUG_612\n Timer process_time;\n process_time.Start();\n#endif\n if (!camera().IsFreshImage()) {\n goto processing_footer; \/\/no new image for us to process\n }\n if (!camera().GetImage(&image)) {\n perror_612(\"Cannot Recieve Image From Camera\");\n goto processing_footer;\n }\n \/\/do vision processing\n callback(*this, image);\n#if DEBUG_612\n output_debug_info();\n \/\/std::printf(\"Processing took %f sec\\n\", process_time.Get());\n#endif\n }\n processing_footer:\n {\n Wait(0.05); \/\/should be a trivial wait compared to processing wait\n \/\/wait is here to keep sucking up processing power while polling the\n \/\/camera object\n }\n }\n}\n\nvoid vision_thread::enable() {\n enabled = true;\n}\n\nvoid vision_thread::disable() {\n enabled = false;\n}\n\nvoid vision_thread::lock_targets() {\n semTake(target_lock, WAIT_FOREVER);\n}\n\nvoid vision_thread::release_targets() {\n semGive(target_lock);\n}\n\n\/\/returns if thread is locked\nbool vision_thread::lock_targets_nowait() {\n if (semTake(target_lock, NO_WAIT) == ERROR) {\n \/\/unsuccessful\n return false;\n }\n else {\n \/\/locked\n return true;\n }\n}\n\nvision_targets::vision_targets()\n#ifdef VISION_ALT_HEURISTIC\n : bottom_t(bottom_basket), top_t(top_basket), left_t(midleft_basket), right_t(midright_basket) {\n#else\n{\n target t;\n for (unsigned i = 0; i < numtargets; i++) {\n targets_vec.push_back(t);\n }\n#endif \n registry().register_func(update_helper, (void*)this);\n}\n\nvision_targets::~vision_targets() {\n registry().unregister_func(update_helper, (void*)this);\n}\n\nvoid vision_targets::update_helper(void * obj) {\n ((vision_targets*)obj)->update();\n}\n\nvoid vision_targets::update() {\n if (get_vision_thread().lock_targets_nowait()) {\n#ifdef VISION_ALT_HEURISTIC\n bottom_t = bottom_basket;\n left_t = midleft_basket;\n right_t = midright_basket;\n top_t = top_basket;\n#else\n for (unsigned i = 0; i < numtargets; i++) {\n targets_vec.at(i) = target_arr[i];\n }\n#endif\n get_vision_thread().release_targets();\n }\n}\n\n#ifdef VISION_ALT_HEURISTIC\n\ntarget& vision_targets::bottom() {\n return bottom_t;\n}\n\ntarget& vision_targets::top() {\n return top_t;\n}\n\ntarget& vision_targets::left() {\n return left_t;\n}\n\ntarget& vision_targets::right() {\n return right_t;\n}\n\n#else\n\nstd::vector<target> vision_targets::targets() {\n return targets_vec;\n}\n\n#endif\n\nvision_thread& get_vision_thread() {\n static vision_thread t(camera(), update_targets);\n return t;\n}\n\nvision_targets& get_targets() {\n static vision_targets t;\n return t;\n}\n\n\/\/FORCE INSTANTIATION\nvision_thread& VISION_THREAD_INSTANCE = get_vision_thread();\nvision_targets& VISION_TARGETS_INSTANCE = get_targets();\n\n\/\/MUST DELETE RETURN VALUE IN CALLER\nstd::pair<report_vector*&, BinaryImage*&> do_threshold(ColorImage& image) {\n \/\/Threshold objects\n static Threshold HSL_THOLD(HSL_HMIN, HSL_HMAX, HSL_SMIN, HSL_SMAX, HSL_LMIN, HSL_LMAX);\n static Threshold HSI_THOLD(HSI_HMIN, HSI_HMAX, HSI_SMIN, HSI_SMAX, HSI_IMIN, HSI_IMAX);\n static Threshold HSV_THOLD(HSV_HMIN, HSV_HMAX, HSV_SMIN, HSV_SMAX, HSV_VMIN, HSV_VMAX);\n BinaryImage * result = NULL;\n if (COLOR_MODE == HSL) {\n result = image.ThresholdHSL(HSL_THOLD);\n }\n else if (COLOR_MODE == HSI) {\n result = image.ThresholdHSI(HSI_THOLD);\n }\n else if (COLOR_MODE == HSV) {\n result = image.ThresholdHSV(HSV_THOLD);\n }\n else {\n \/\/color mode undefined. Fall back to HSL\n result = image.ThresholdHSL(HSL_THOLD);\n perror_612(\"Invalid Color Mode - Falling Back to HSL\");\n }\n if (!result) {\n \/\/we have issues\n perror_612(\"Threshold Unsuccessful\");\n return std::make_pair<report_vector*, BinaryImage*>(NULL, NULL);\n }\n report_vector * ret = result->GetOrderedParticleAnalysisReports();\n \/\/delete result;\/\/TODO: may be more efficient if we can allocate one binary\n \/\/image and call imaqColorThreshold. leaving as is now\n \/\/cause it's prettier this way and POITROAE.\n return std::make_pair<report_vector*&, BinaryImage*&>(ret, result);\n}\n\nvoid do_particle_filter(report_vector * v, Image * img) {\n \/\/filter particles\n particle_filter filt(img);\n v->erase(std::remove_if(v->begin(), v->end(), filt), v->end());\n if (v->size() > 4) { \/\/more than four elements\n v->resize(4); \/\/drop extra elements - get four biggest\n }\n}\n\nvoid write_particles(const char * fname, const report_vector * v) {\n \/\/write particle analyses\n std::fstream o(fname, std::fstream::out | std::fstream::trunc);\n o << \"#ifndef REPORT_H_INC\\n\"\n \"#define REPORT_H_INC\\n\\n\"\n \"struct Rect {\\n\"\n \"\\tint top;\\n\"\n \"\\tint left;\\n\"\n \"\\tint height;\\n\"\n \"\\tint width;\\n\"\n \"};\\n\\n\"\n \"struct ParticleAnalysisReport {\\n\"\n \"\\tint imageHeight;\\n\"\n \"\\tint imageWidth;\\n\"\n \"\\tdouble imageTimestamp;\\n\"\n \"\\tint particleIndex;\\n\"\n \"\\tint center_mass_x;\\n\"\n \"\\tint center_mass_y;\\n\"\n \"\\tdouble center_mass_x_normalized;\\n\"\n \"\\tdouble cneter_mass_y_normalized;\\n\"\n \"\\tdouble particleArea;\\n\"\n \"\\tRect boundingRect;\\n\"\n \"\\tdouble particleToImagePercent;\\n\"\n \"\\tdouble particleQuality;\\n\"\n \"};\\n\\n\"\n \"ParticleAnalysisReport reports[] = {\\n\";\n if (v->size()) {\n report_vector::const_iterator it;\n for (it = v->begin(); it < v->end(); it++) {\n o << \"\\t{\\n\"\n \"\\t\\t\" << it->imageHeight << \",\\n\"\n \"\\t\\t\" << it->imageWidth << \",\\n\"\n \"\\t\\t\" << it->imageTimestamp << \",\\n\"\n \"\\t\\t\" << it->particleIndex << \",\\n\"\n \"\\t\\t\" << it->center_mass_x << \",\\n\"\n \"\\t\\t\" << it->center_mass_y << \",\\n\"\n \"\\t\\t\" << it->center_mass_x_normalized << \",\\n\"\n \"\\t\\t\" << it->center_mass_y_normalized << \",\\n\"\n \"\\t\\t\" << it->particleArea << \",\\n\"\n \"\\t\\t{\\n\"\n \"\\t\\t\\t\" << it->boundingRect.top << \",\\n\"\n \"\\t\\t\\t\" << it->boundingRect.left << \",\\n\"\n \"\\t\\t\\t\" << it->boundingRect.height << \",\\n\"\n \"\\t\\t\\t\" << it->boundingRect.width << \",\\n\"\n \"\\t\\t},\\n\"\n \"\\t\\t\" << it->particleToImagePercent << \",\\n\"\n \"\\t\\t\" << it->particleQuality << \",\\n\"\n \"\\t}\";\n if (it + 1 != v->end()) {\n o << ',';\n }\n o << std::endl;\n }\n }\n o << \"};\\n\\n\"\n \"#endif\" << std::endl;\n \/\/PHEW.\n o.close();\n}\n\n\nvoid update_targets(vision_thread& thread, ColorImage& image) {\n std::pair<report_vector*&, BinaryImage*&> ptrs = do_threshold(image);\n report_vector * reports = ptrs.first;\n BinaryImage * img = ptrs.second;\n#if DEBUG_612\n if (left_joystick.GetRawButton(WRITE_IMAGE)) {\n std::printf(\"Writing...\\n\");\n char buffer[64];\n std::sprintf(buffer, \"%f_clr.bmp\", Timer::GetFPGATimestamp());\n image.Write(buffer);\n int x = std::strlen(buffer);\n buffer[x-6] = 'b';\n buffer[x-5] = 'i';\n buffer[x-4] = 'n';\n img->Write(buffer);\n buffer[x-7] = '.';\n buffer[x-6] = 'h';\n buffer[x-5] = '\\0';\n write_particles(buffer, reports);\n }\n#endif\n if (!reports) {\n \/\/particle analysis failed.\n if (img) {\n delete img;\n }\n return;\n }\n do_particle_filter(reports, img->GetImaqImage());\n thread.lock_targets();\n target::id_and_process(reports);\n thread.release_targets();\n delete reports; \/\/free vector\n delete img; \/\/free image\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>make running time of brpc_h2_unsent_message_unittest shorter<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file scheduler\/scheduler.cc\n ** \\brief Implementation of scheduler::Scheduler.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n\n#include <cassert>\n#include <cstdlib>\n\n#include <libport\/compiler.hh>\n#include <libport\/containers.hh>\n#include <libport\/foreach.hh>\n\n#include \"kernel\/userver.hh\"\n\n#include \"object\/urbi-exception.hh\"\n\n#include \"scheduler\/scheduler.hh\"\n#include \"scheduler\/job.hh\"\n\nnamespace scheduler\n{\n\n \/\/ This function is required to start a new job using the libcoroutine.\n \/\/ Its only purpose is to create the context and start the execution\n \/\/ of the new job.\n static void\n run_job (void* job)\n {\n static_cast<Job*>(job)->run();\n }\n\n void\n Scheduler::add_job (Job* job)\n {\n assert (job);\n assert (!libport::has (jobs_, job));\n jobs_.push_back (job);\n jobs_to_start_ = true;\n }\n\n libport::utime_t\n Scheduler::work ()\n {\n ++cycle_;\n ECHO (\"======================================================== cycle \"\n\t << cycle_);\n\n libport::utime_t deadline = execute_round (false);\n\n \/\/ If some jobs need to be stopped, do it as soon as possible.\n deadline = std::min (deadline, check_for_stopped_tags (deadline));\n\n#ifdef ENABLE_DEBUG_TRACES\n if (deadline)\n ECHO (\"Scheduler asking to be woken up in \"\n\t << (deadline - ::urbiserver->getTime ()) \/ 1000000L << \" seconds\");\n else\n ECHO (\"Scheduler asking to be woken up ASAP\");\n#endif\n\n return deadline;\n }\n\n libport::utime_t\n Scheduler::execute_round (bool blocked_only)\n {\n \/\/ Run all the jobs in the run queue once. If any job declares upon entry or\n \/\/ return that it is not side-effect free, we remember that for the next\n \/\/ cycle.\n pending_.clear ();\n std::swap (pending_, jobs_);\n\n \/\/ By default, wake us up after one hour and consider that we have no\n \/\/ new job to start. Also, run waiting jobs only if the previous round\n \/\/ may have add a side effect and reset this indication for the current\n \/\/ job.\n libport::utime_t deadline = ::urbiserver->getTime () + 3600000000LL;\n jobs_to_start_ = false;\n bool start_waiting = possible_side_effect_;\n possible_side_effect_ = false;\n\n ECHO (pending_.size() << \" jobs in the queue for this round\");\n foreach (Job* job, pending_)\n {\n \/\/ Kill a job if needed. See explanation in job.hh.\n to_kill_ = 0;\n\n assert (job);\n assert (!job->terminated ());\n\n \/\/ Should the job be started?\n bool start = false;\n\n ECHO (\"Considering \" << *job << \" in state \" << state_name (job->state_get ()));\n\n switch (job->state_get ())\n {\n case to_start:\n\t\/\/ New job. Start its coroutine but do not start the job as it would be queued\n\t\/\/ twice otherwise. It will start doing real work at the next cycle, so set\n\t\/\/ deadline to 0. Note that we use \"continue\" here to avoid having the job\n\t\/\/ requeued because it hasn't been started by setting \"start\".\n\tECHO (\"Starting job \" << *job);\n\tcurrent_job_ = job;\n\tCoro_startCoro_ (coro_, job->coro_get(), job, run_job);\n\tcurrent_job_ = 0;\n\tECHO (\"Job \" << *job << \" has been started\");\n\tassert (job->state_get () != to_start);\n\tdeadline = 0;\n\tcontinue;\n case zombie:\n\tassert (false);\n\tbreak;\n case running:\n\tstart = !blocked_only || job->blocked ();\n\tbreak;\n case sleeping:\n\t{\n\t libport::utime_t job_deadline = job->deadline_get ();\n\t if (job_deadline <= ::urbiserver->getTime ())\n\t start = true;\n\t else\n\t deadline = std::min (deadline, job_deadline);\n\t}\n\tbreak;\n case waiting:\n\t\/\/ Since jobs keep their orders in the queue, start waiting jobs if\n\t\/\/ previous jobs in the run have had a possible side effect or if\n\t\/\/ the previous run may have had some. Without it, we may miss some\n\t\/\/ changes if the watching job is after the modifying job in the queue\n\t\/\/ and the watched condition gets true for only one cycle.\n\tstart = start_waiting | possible_side_effect_;\n\tbreak;\n case joining:\n\tbreak;\n }\n\n if (start)\n {\n\tECHO (\"will resume job \" << *job\n\t << (job->side_effect_free_get() ? \" (side-effect free)\" : \"\"));\n\tpossible_side_effect_ |= !job->side_effect_free_get ();\n\tassert (!current_job_);\n\tCoro_switchTo_ (coro_, job->coro_get ());\n\tassert (!current_job_);\n\tpossible_side_effect_ |= !job->side_effect_free_get ();\n\tECHO (\"back from job \" << *job\n\t << (job->side_effect_free_get() ? \" (side-effect free)\" : \"\"));\n\tswitch (job->state_get ())\n\t{\n\tcase running:\n\t deadline = 0;\n\t break;\n\tcase sleeping:\n\t deadline = std::min (deadline, job->deadline_get ());\n\t break;\n\tdefault:\n\t break;\n\t}\n }\n else\n\tjobs_.push_back (job); \/\/ Job not started, keep it in queue\n }\n\n \/\/ Kill a job if needed. See explanation in job.hh.\n to_kill_ = 0;\n\n \/\/\/ If during this cycle a new job has been created by an existing job,\n \/\/\/ start it.\n if (jobs_to_start_)\n deadline = 0;\n\n return deadline;\n }\n\n libport::utime_t\n Scheduler::check_for_stopped_tags (libport::utime_t old_deadline)\n {\n bool blocked_job = false;\n\n \/\/ If we have had no stopped tag, return immediately.\n if (stopped_tags_.empty ())\n return old_deadline;\n\n \/\/ If some jobs have been blocked, mark them as running so that they will\n \/\/ handle the condition when they are resumed.\n foreach (Job* job, jobs_)\n if (job->blocked ())\n {\n\tjob->state_set (running);\n\tblocked_job = true;\n }\n\n \/\/ Wake up blocked jobs.\n libport::utime_t deadline = execute_round (true);\n\n \/\/ Reset tags to their real blocked value and reset the list.\n foreach (tag_state_type t, stopped_tags_)\n t.first->set_blocked (t.second);\n stopped_tags_.clear ();\n\n return deadline;\n }\n\n void\n Scheduler::resume_scheduler (Job* job)\n {\n \/\/ If the job has not terminated and is side-effect free, then we\n \/\/ assume it will not take a long time as we are probably evaluating\n \/\/ a condition. In order to reduce the number of cycles spent to evaluate\n \/\/ the condition, continue until it asks to be suspended in another\n \/\/ way or until it is no longer side-effect free.\n\n bool side_effect_free_save = job->side_effect_free_get ();\n\n if (job->state_get () == running && side_effect_free_save)\n return;\n\n \/\/ We may have to suspend the job several time in case it makes no sense\n \/\/ to start it back. Let's do it in a loop and we'll break when we want\n \/\/ to resume the job.\n\n for (;;)\n {\n \/\/ Add the job at the end of the scheduler queue unless the job has\n \/\/ already terminated.\n if (!job->terminated ())\n\tjobs_.push_back (job);\n\n \/\/ Switch back to the scheduler.\n assert (current_job_ == job);\n current_job_ = 0;\n ECHO (*job << \" has \" << (job->terminated () ? \"\" : \"not \") << \"terminated\\n\\t\"\n\t << \"state: \" << state_name (job->state_get ()));\n Coro_switchTo_ (job->coro_get (), coro_);\n\n \/\/ We regained control, we are again in the context of the job.\n assert (!current_job_);\n current_job_ = job;\n ECHO (\"job \" << *job << \" resumed\");\n\n \/\/ Execute a deferred exception if any; this may break out of this loop\n job->check_for_pending_exception ();\n\n \/\/ If we are not frozen, it is time to resume regular execution\n if (!job->frozen ())\n\tbreak;\n\n \/\/ Ok, we are frozen. Let's requeue ourselves after setting\n \/\/ the side_effect_free flag, and we will be in waiting mode.\n job->side_effect_free_set (true);\n job->state_set (waiting);\n }\n\n \/\/ Check that we are not near exhausting the stack space.\n job->check_stack_space ();\n\n \/\/ Restore the side_effect_free flag\n job->side_effect_free_set (side_effect_free_save);\n\n \/\/ Resume job execution\n }\n\n void\n Scheduler::killall_jobs ()\n {\n ECHO (\"killing all jobs!\");\n\n foreach (Job* job, jobs_)\n kill_job (job);\n\n foreach (Job* job, pending_)\n kill_job (job);\n }\n\n void\n Scheduler::unschedule_job (Job* job)\n {\n assert (job);\n assert (job != current_job_);\n\n ECHO (\"unscheduling job \" << *job);\n\n \/\/ Remove the job from the queue.\n jobs_.remove (job);\n\n \/\/ Remove it from live queues as well if the job is destroyed.\n pending_.remove (job);\n }\n\n void\n Scheduler::kill_job (Job* job)\n {\n KillException ke;\n job->async_throw (ke);\n }\n\n void Scheduler::signal_stop (rTag t)\n {\n bool previous_state = t->own_blocked ();\n t->set_blocked (true);\n stopped_tags_.push_back (std::make_pair(t, previous_state));\n }\n\n} \/\/ namespace scheduler\n<commit_msg>Do not wait if there is a possible side effect<commit_after>\/**\n ** \\file scheduler\/scheduler.cc\n ** \\brief Implementation of scheduler::Scheduler.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n\n#include <cassert>\n#include <cstdlib>\n\n#include <libport\/compiler.hh>\n#include <libport\/containers.hh>\n#include <libport\/foreach.hh>\n\n#include \"kernel\/userver.hh\"\n\n#include \"object\/urbi-exception.hh\"\n\n#include \"scheduler\/scheduler.hh\"\n#include \"scheduler\/job.hh\"\n\nnamespace scheduler\n{\n\n \/\/ This function is required to start a new job using the libcoroutine.\n \/\/ Its only purpose is to create the context and start the execution\n \/\/ of the new job.\n static void\n run_job (void* job)\n {\n static_cast<Job*>(job)->run();\n }\n\n void\n Scheduler::add_job (Job* job)\n {\n assert (job);\n assert (!libport::has (jobs_, job));\n jobs_.push_back (job);\n jobs_to_start_ = true;\n }\n\n libport::utime_t\n Scheduler::work ()\n {\n ++cycle_;\n ECHO (\"======================================================== cycle \"\n\t << cycle_);\n\n libport::utime_t deadline = execute_round (false);\n\n \/\/ If some jobs need to be stopped, do it as soon as possible.\n deadline = std::min (deadline, check_for_stopped_tags (deadline));\n\n#ifdef ENABLE_DEBUG_TRACES\n if (deadline)\n ECHO (\"Scheduler asking to be woken up in \"\n\t << (deadline - ::urbiserver->getTime ()) \/ 1000000L << \" seconds\");\n else\n ECHO (\"Scheduler asking to be woken up ASAP\");\n#endif\n\n return deadline;\n }\n\n libport::utime_t\n Scheduler::execute_round (bool blocked_only)\n {\n \/\/ Run all the jobs in the run queue once. If any job declares upon entry or\n \/\/ return that it is not side-effect free, we remember that for the next\n \/\/ cycle.\n pending_.clear ();\n std::swap (pending_, jobs_);\n\n \/\/ By default, wake us up after one hour and consider that we have no\n \/\/ new job to start. Also, run waiting jobs only if the previous round\n \/\/ may have add a side effect and reset this indication for the current\n \/\/ job.\n libport::utime_t deadline = ::urbiserver->getTime () + 3600000000LL;\n jobs_to_start_ = false;\n bool start_waiting = possible_side_effect_;\n possible_side_effect_ = false;\n\n ECHO (pending_.size() << \" jobs in the queue for this round\");\n foreach (Job* job, pending_)\n {\n \/\/ Kill a job if needed. See explanation in job.hh.\n to_kill_ = 0;\n\n assert (job);\n assert (!job->terminated ());\n\n \/\/ Should the job be started?\n bool start = false;\n\n ECHO (\"Considering \" << *job << \" in state \" << state_name (job->state_get ()));\n\n switch (job->state_get ())\n {\n case to_start:\n\t\/\/ New job. Start its coroutine but do not start the job as it would be queued\n\t\/\/ twice otherwise. It will start doing real work at the next cycle, so set\n\t\/\/ deadline to 0. Note that we use \"continue\" here to avoid having the job\n\t\/\/ requeued because it hasn't been started by setting \"start\".\n\tECHO (\"Starting job \" << *job);\n\tcurrent_job_ = job;\n\tCoro_startCoro_ (coro_, job->coro_get(), job, run_job);\n\tcurrent_job_ = 0;\n\tECHO (\"Job \" << *job << \" has been started\");\n\tassert (job->state_get () != to_start);\n\tdeadline = 0;\n\tcontinue;\n case zombie:\n\tassert (false);\n\tbreak;\n case running:\n\tstart = !blocked_only || job->blocked ();\n\tbreak;\n case sleeping:\n\t{\n\t libport::utime_t job_deadline = job->deadline_get ();\n\t if (job_deadline <= ::urbiserver->getTime ())\n\t start = true;\n\t else\n\t deadline = std::min (deadline, job_deadline);\n\t}\n\tbreak;\n case waiting:\n\t\/\/ Since jobs keep their orders in the queue, start waiting jobs if\n\t\/\/ previous jobs in the run have had a possible side effect or if\n\t\/\/ the previous run may have had some. Without it, we may miss some\n\t\/\/ changes if the watching job is after the modifying job in the queue\n\t\/\/ and the watched condition gets true for only one cycle.\n\tstart = start_waiting | possible_side_effect_;\n\tbreak;\n case joining:\n\tbreak;\n }\n\n if (start)\n {\n\tECHO (\"will resume job \" << *job\n\t << (job->side_effect_free_get() ? \" (side-effect free)\" : \"\"));\n\tpossible_side_effect_ |= !job->side_effect_free_get ();\n\tassert (!current_job_);\n\tCoro_switchTo_ (coro_, job->coro_get ());\n\tassert (!current_job_);\n\tpossible_side_effect_ |= !job->side_effect_free_get ();\n\tECHO (\"back from job \" << *job\n\t << (job->side_effect_free_get() ? \" (side-effect free)\" : \"\"));\n\tswitch (job->state_get ())\n\t{\n\tcase running:\n\t deadline = 0;\n\t break;\n\tcase sleeping:\n\t deadline = std::min (deadline, job->deadline_get ());\n\t break;\n\tdefault:\n\t break;\n\t}\n }\n else\n\tjobs_.push_back (job); \/\/ Job not started, keep it in queue\n }\n\n \/\/ Kill a job if needed. See explanation in job.hh.\n to_kill_ = 0;\n\n \/\/\/ If during this cycle a new job has been created by an existing job,\n \/\/\/ start it. Also start if a possible side effect happened, it may have\n \/\/\/ occurred later then the waiting jobs in the cycle.\n if (jobs_to_start_ || possible_side_effect_)\n deadline = 0;\n\n return deadline;\n }\n\n libport::utime_t\n Scheduler::check_for_stopped_tags (libport::utime_t old_deadline)\n {\n bool blocked_job = false;\n\n \/\/ If we have had no stopped tag, return immediately.\n if (stopped_tags_.empty ())\n return old_deadline;\n\n \/\/ If some jobs have been blocked, mark them as running so that they will\n \/\/ handle the condition when they are resumed.\n foreach (Job* job, jobs_)\n if (job->blocked ())\n {\n\tjob->state_set (running);\n\tblocked_job = true;\n }\n\n \/\/ Wake up blocked jobs.\n libport::utime_t deadline = execute_round (true);\n\n \/\/ Reset tags to their real blocked value and reset the list.\n foreach (tag_state_type t, stopped_tags_)\n t.first->set_blocked (t.second);\n stopped_tags_.clear ();\n\n return deadline;\n }\n\n void\n Scheduler::resume_scheduler (Job* job)\n {\n \/\/ If the job has not terminated and is side-effect free, then we\n \/\/ assume it will not take a long time as we are probably evaluating\n \/\/ a condition. In order to reduce the number of cycles spent to evaluate\n \/\/ the condition, continue until it asks to be suspended in another\n \/\/ way or until it is no longer side-effect free.\n\n bool side_effect_free_save = job->side_effect_free_get ();\n\n if (job->state_get () == running && side_effect_free_save)\n return;\n\n \/\/ We may have to suspend the job several time in case it makes no sense\n \/\/ to start it back. Let's do it in a loop and we'll break when we want\n \/\/ to resume the job.\n\n for (;;)\n {\n \/\/ Add the job at the end of the scheduler queue unless the job has\n \/\/ already terminated.\n if (!job->terminated ())\n\tjobs_.push_back (job);\n\n \/\/ Switch back to the scheduler.\n assert (current_job_ == job);\n current_job_ = 0;\n ECHO (*job << \" has \" << (job->terminated () ? \"\" : \"not \") << \"terminated\\n\\t\"\n\t << \"state: \" << state_name (job->state_get ()));\n Coro_switchTo_ (job->coro_get (), coro_);\n\n \/\/ We regained control, we are again in the context of the job.\n assert (!current_job_);\n current_job_ = job;\n ECHO (\"job \" << *job << \" resumed\");\n\n \/\/ Execute a deferred exception if any; this may break out of this loop\n job->check_for_pending_exception ();\n\n \/\/ If we are not frozen, it is time to resume regular execution\n if (!job->frozen ())\n\tbreak;\n\n \/\/ Ok, we are frozen. Let's requeue ourselves after setting\n \/\/ the side_effect_free flag, and we will be in waiting mode.\n job->side_effect_free_set (true);\n job->state_set (waiting);\n }\n\n \/\/ Check that we are not near exhausting the stack space.\n job->check_stack_space ();\n\n \/\/ Restore the side_effect_free flag\n job->side_effect_free_set (side_effect_free_save);\n\n \/\/ Resume job execution\n }\n\n void\n Scheduler::killall_jobs ()\n {\n ECHO (\"killing all jobs!\");\n\n foreach (Job* job, jobs_)\n kill_job (job);\n\n foreach (Job* job, pending_)\n kill_job (job);\n }\n\n void\n Scheduler::unschedule_job (Job* job)\n {\n assert (job);\n assert (job != current_job_);\n\n ECHO (\"unscheduling job \" << *job);\n\n \/\/ Remove the job from the queue.\n jobs_.remove (job);\n\n \/\/ Remove it from live queues as well if the job is destroyed.\n pending_.remove (job);\n }\n\n void\n Scheduler::kill_job (Job* job)\n {\n KillException ke;\n job->async_throw (ke);\n }\n\n void Scheduler::signal_stop (rTag t)\n {\n bool previous_state = t->own_blocked ();\n t->set_blocked (true);\n stopped_tags_.push_back (std::make_pair(t, previous_state));\n }\n\n} \/\/ namespace scheduler\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- TaskFuture.cpp - Unit tests for the task futures API -------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Runtime\/Concurrency.h\"\n#include \"swift\/Runtime\/Metadata.h\"\n#include \"swift\/Demangling\/ManglingMacros.h\"\n#include \"swift\/Basic\/STLExtras.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace swift;\n\nnamespace {\ntemplate <class T> struct FutureContext;\n\ntemplate <class T>\nusing InvokeFunctionRef =\n llvm::function_ref<void(AsyncTask *task,\n ExecutorRef executor,\n FutureContext<T> *context)>;\n\nusing BodyFunctionRef =\n llvm::function_ref<void(AsyncTask *task)>;\n\ntemplate <class Storage> struct PODFutureContext : AsyncContext {\n alignas(Storage) char resultStorage[sizeof(Storage)];\n void *errorStorage;\n};\n\ntemplate <class Storage> struct FutureContext : PODFutureContext<Storage> {\n InvokeFunctionRef<Storage> storedInvokeFn;\n\n Storage& getStorage() {\n return *reinterpret_cast<Storage *>(&this->resultStorage[0]);\n }\n};\n\n\/\/ Disable template argument deduction.\ntemplate <class T>\nusing undeduced =\n typename std::enable_if<std::is_same<T, T>::value, T>::type;\n\ntemplate <class T>\nSWIFT_CC(swift)\nstatic void futureTaskInvokeFunction(AsyncTask *task, ExecutorRef executor,\n AsyncContext *context) {\n auto futureContext = static_cast<FutureContext<T>*>(context);\n futureContext->storedInvokeFn(task, executor, futureContext);\n\n \/\/ Return to finish off the task.\n \/\/ In a normal situation we'd need to free the context, but here\n \/\/ we know we're at the top level.\n futureContext->ResumeParent(task, executor, futureContext);\n}\n\ntemplate <class T>\nstatic void withFutureTask(const Metadata *resultType,\n undeduced<InvokeFunctionRef<T>> invokeFn,\n BodyFunctionRef body) {\n JobFlags flags = JobKind::Task;\n flags.task_setIsFuture(true);\n\n auto taskAndContext =\n swift_task_create_future_f(flags, \/*parent*\/ nullptr, resultType,\n &futureTaskInvokeFunction<T>,\n sizeof(FutureContext<T>),\n offsetof(PODFutureContext<T>, resultStorage),\n offsetof(PODFutureContext<T>, errorStorage));\n\n auto futureContext =\n static_cast<FutureContext<T>*>(taskAndContext.InitialContext);\n futureContext->getStorage() = 42; \/\/ Magic number.\n futureContext->storedInvokeFn = invokeFn;\n\n \/\/ Forward our owning reference to the task into its execution,\n \/\/ causing it to be destroyed when it completes.\n body(taskAndContext.Task);\n}\n\nstatic ExecutorRef createFakeExecutor(uintptr_t value) {\n return {reinterpret_cast<Executor*>(value)};\n}\n}\n\nextern const FullMetadata<OpaqueMetadata> METADATA_SYM(Si);\n\nTEST(TaskFutureTest, intFuture) {\n auto createdExecutor = createFakeExecutor(1234);\n bool hasRun = false;\n\n withFutureTask<intptr_t>(\n reinterpret_cast<const Metadata *>(&METADATA_SYM(Si)),\n [&](AsyncTask *task, ExecutorRef executor,\n FutureContext<intptr_t> *context) {\n \/\/ The storage should be what we initialized it to earlier.\n EXPECT_EQ(42, context->getStorage());\n\n \/\/ The error storage should have been cleared out for us.\n EXPECT_EQ(nullptr, context->errorStorage);\n\n \/\/ Store something in the future.\n context->getStorage() = 17;\n\n hasRun = true;\n }, [&](AsyncTask *task) {\n \/\/ Run the task, which should fill in the future.\n EXPECT_FALSE(hasRun);\n task->run(createdExecutor);\n EXPECT_TRUE(hasRun);\n\n \/\/ \"Wait\" for the future, which must have completed by now.\n auto waitResult = swift_task_future_wait(task, nullptr);\n EXPECT_EQ(TaskFutureWaitResult::Success, waitResult.kind);\n\n \/\/ Make sure we got the result value we expect.\n EXPECT_EQ(17, *reinterpret_cast<intptr_t *>(waitResult.storage));\n });\n}\n\n<commit_msg>[Future] Add a test to make sure we're handling object lifetimes properly.<commit_after>\/\/===--- TaskFuture.cpp - Unit tests for the task futures API -------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Runtime\/Concurrency.h\"\n#include \"swift\/Runtime\/Metadata.h\"\n#include \"swift\/Demangling\/ManglingMacros.h\"\n#include \"swift\/Basic\/STLExtras.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace swift;\n\nnamespace {\ntemplate <class T> struct FutureContext;\n\ntemplate <class T>\nusing InvokeFunctionRef =\n llvm::function_ref<void(AsyncTask *task,\n ExecutorRef executor,\n FutureContext<T> *context)>;\n\nusing BodyFunctionRef =\n llvm::function_ref<void(AsyncTask *task)>;\n\ntemplate <class Storage> struct PODFutureContext : AsyncContext {\n alignas(Storage) char resultStorage[sizeof(Storage)];\n void *errorStorage;\n};\n\ntemplate <class Storage> struct FutureContext : PODFutureContext<Storage> {\n InvokeFunctionRef<Storage> storedInvokeFn;\n\n Storage& getStorage() {\n return *reinterpret_cast<Storage *>(&this->resultStorage[0]);\n }\n};\n\n\/\/ Disable template argument deduction.\ntemplate <class T>\nusing undeduced =\n typename std::enable_if<std::is_same<T, T>::value, T>::type;\n\ntemplate <class T>\nSWIFT_CC(swift)\nstatic void futureTaskInvokeFunction(AsyncTask *task, ExecutorRef executor,\n AsyncContext *context) {\n auto futureContext = static_cast<FutureContext<T>*>(context);\n futureContext->storedInvokeFn(task, executor, futureContext);\n\n \/\/ Return to finish off the task.\n \/\/ In a normal situation we'd need to free the context, but here\n \/\/ we know we're at the top level.\n futureContext->ResumeParent(task, executor, futureContext);\n}\n\ntemplate <class T>\nstatic void withFutureTask(const Metadata *resultType,\n const T& initialValue,\n undeduced<InvokeFunctionRef<T>> invokeFn,\n BodyFunctionRef body) {\n JobFlags flags = JobKind::Task;\n flags.task_setIsFuture(true);\n\n auto taskAndContext =\n swift_task_create_future_f(flags, \/*parent*\/ nullptr, resultType,\n &futureTaskInvokeFunction<T>,\n sizeof(FutureContext<T>),\n offsetof(PODFutureContext<T>, resultStorage),\n offsetof(PODFutureContext<T>, errorStorage));\n\n auto futureContext =\n static_cast<FutureContext<T>*>(taskAndContext.InitialContext);\n futureContext->getStorage() = initialValue; \/\/ Magic number.\n futureContext->storedInvokeFn = invokeFn;\n\n \/\/ Forward our owning reference to the task into its execution,\n \/\/ causing it to be destroyed when it completes.\n body(taskAndContext.Task);\n}\n\nstatic ExecutorRef createFakeExecutor(uintptr_t value) {\n return {reinterpret_cast<Executor*>(value)};\n}\n}\n\nextern const FullMetadata<OpaqueMetadata> METADATA_SYM(Si);\n\nstruct TestObject : HeapObject {\n constexpr TestObject(HeapMetadata const *newMetadata)\n : HeapObject(newMetadata, InlineRefCounts::Immortal)\n , Addr(NULL), Value(0) {}\n\n size_t *Addr;\n size_t Value;\n};\n\nstatic SWIFT_CC(swift) void destroyTestObject(SWIFT_CONTEXT HeapObject *_object) {\n auto object = static_cast<TestObject*>(_object);\n assert(object->Addr && \"object already deallocated\");\n *object->Addr = object->Value;\n object->Addr = nullptr;\n swift_deallocObject(object, sizeof(TestObject), alignof(TestObject) - 1);\n}\n\nstatic const FullMetadata<ClassMetadata> TestClassObjectMetadata = {\n { { &destroyTestObject }, { &VALUE_WITNESS_SYM(Bo) } },\n { { nullptr }, ClassFlags::UsesSwiftRefcounting, 0, 0, 0, 0, 0, 0 }\n};\n\n\/\/\/ Create an object that, when deallocated, stores the given value to\n\/\/\/ the given pointer.\nstatic TestObject *allocTestObject(size_t *addr, size_t value) {\n auto result =\n static_cast<TestObject *>(swift_allocObject(&TestClassObjectMetadata,\n sizeof(TestObject),\n alignof(TestObject) - 1));\n result->Addr = addr;\n result->Value = value;\n return result;\n}\n\nTEST(TaskFutureTest, intFuture) {\n auto createdExecutor = createFakeExecutor(1234);\n bool hasRun = false;\n\n withFutureTask<intptr_t>(\n reinterpret_cast<const Metadata *>(&METADATA_SYM(Si)), 42,\n [&](AsyncTask *task, ExecutorRef executor,\n FutureContext<intptr_t> *context) {\n \/\/ The storage should be what we initialized it to earlier.\n EXPECT_EQ(42, context->getStorage());\n\n \/\/ The error storage should have been cleared out for us.\n EXPECT_EQ(nullptr, context->errorStorage);\n\n \/\/ Store something in the future.\n context->getStorage() = 17;\n\n hasRun = true;\n }, [&](AsyncTask *task) {\n \/\/ Run the task, which should fill in the future.\n EXPECT_FALSE(hasRun);\n task->run(createdExecutor);\n EXPECT_TRUE(hasRun);\n\n \/\/ \"Wait\" for the future, which must have completed by now.\n auto waitResult = swift_task_future_wait(task, nullptr);\n EXPECT_EQ(TaskFutureWaitResult::Success, waitResult.kind);\n\n \/\/ Make sure we got the result value we expect.\n EXPECT_EQ(17, *reinterpret_cast<intptr_t *>(waitResult.storage));\n });\n}\n\nTEST(TaskFutureTest, objectFuture) {\n auto createdExecutor = createFakeExecutor(1234);\n bool hasRun = false;\n\n size_t objectValueOnComplete = 7;\n TestObject *object = nullptr;\n withFutureTask<TestObject *>(\n &TestClassObjectMetadata, nullptr,\n [&](AsyncTask *task, ExecutorRef executor,\n FutureContext<TestObject *> *context) {\n object = allocTestObject(&objectValueOnComplete, 25);\n\n \/\/ The error storage should have been cleared out for us.\n EXPECT_EQ(nullptr, context->errorStorage);\n\n \/\/ Store the object in the future.\n context->getStorage() = object;\n\n hasRun = true;\n }, [&](AsyncTask *task) {\n \/\/ Retain the task, so it won't be destroyed when it is executed.\n swift_retain(task);\n\n \/\/ Run the task, which should fill in the future.\n EXPECT_FALSE(hasRun);\n task->run(createdExecutor);\n EXPECT_TRUE(hasRun);\n\n \/\/ \"Wait\" for the future, which must have completed by now.\n auto waitResult = swift_task_future_wait(task, nullptr);\n EXPECT_EQ(TaskFutureWaitResult::Success, waitResult.kind);\n\n \/\/ Make sure we got the result value we expect.\n EXPECT_EQ(object, *reinterpret_cast<TestObject **>(waitResult.storage));\n\n \/\/ Make sure the object hasn't been destroyed.\n EXPECT_EQ(7, objectValueOnComplete);\n\n \/\/ Okay, release the task. This should destroy the object.\n swift_release(task);\n assert(objectValueOnComplete == 25);\n });\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <GuiBase\/Viewer\/TrackballCamera.hpp>\n\n#include <QApplication>\n#include <QMessageBox>\n#include <iostream>\n\n#include <Core\/Event\/KeyEvent.hpp>\n#include <Core\/Event\/MouseEvent.hpp>\n#include <Core\/Log\/Log.hpp>\n#include <Core\/Math\/Math.hpp>\n#include <Engine\/Renderer\/Camera\/Camera.hpp>\n#include <Engine\/Renderer\/Light\/Light.hpp>\n\n#include <GuiBase\/Utils\/KeyMappingManager.hpp>\n\nnamespace Ra {\nusing Core::Math::Pi;\n\nGui::TrackballCamera::TrackballCamera( uint width, uint height ) :\n CameraInterface( width, height ),\n m_trackballCenter( 0, 0, 0 ),\n m_quickCameraModifier( 1.f ),\n m_wheelSpeedModifier( 0.02f ),\n m_distFromCenter( 1.0f ),\n m_cameraRadius( 1.0f ),\n m_rotateAround( true ),\n m_cameraRotateMode( false ),\n m_cameraPanMode( false ),\n m_cameraZoomMode( false ),\n m_walkingOn( false ),\n m_strafingOn( false ),\n m_climbingOn( false ),\n m_walking( 0 ),\n m_strafing( 0 ),\n m_climbing( 0 ) {\n resetCamera();\n}\n\nGui::TrackballCamera::~TrackballCamera() {}\n\nvoid Gui::TrackballCamera::resetCamera() {\n m_camera->setFrame( Core::Transform::Identity() );\n m_camera->setPosition( Core::Vector3( 0, 0, 1 ) );\n m_trackballCenter = Core::Vector3::Zero();\n updatePhiTheta();\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::setCameraRadius( Scalar rad ) {\n m_cameraRadius = rad;\n}\nScalar Gui::TrackballCamera::getCameraRadius() {\n return m_cameraRadius;\n}\n\nbool Gui::TrackballCamera::handleMousePressEvent( QMouseEvent* event ) {\n bool handled = false;\n m_lastMouseX = event->pos().x();\n m_lastMouseY = event->pos().y();\n\n \/* TODO: Better handling of rotation\/pan\/zoom with KeyMappingManager *\/\n if ( event->modifiers().testFlag( Qt::NoModifier ) )\n {\n m_cameraRotateMode = true;\n handled = true;\n }\n\n if ( event->modifiers().testFlag( Qt::ShiftModifier ) )\n {\n m_cameraPanMode = true;\n handled = true;\n }\n\n if ( event->modifiers().testFlag( Qt::ControlModifier ) )\n {\n m_cameraZoomMode = true;\n handled = true;\n }\n\n return handled;\n}\n\nbool Gui::TrackballCamera::handleMouseMoveEvent( QMouseEvent* event ) {\n Scalar dx = ( event->pos().x() - m_lastMouseX ) \/ m_camera->getWidth();\n Scalar dy = ( event->pos().y() - m_lastMouseY ) \/ m_camera->getHeight();\n\n if ( event->modifiers().testFlag( Qt::AltModifier ) )\n {\n m_quickCameraModifier = 10.0;\n } else\n { m_quickCameraModifier = 2.0; }\n\n if ( m_cameraRotateMode )\n {\n handleCameraRotate( dx, dy );\n }\n\n if ( m_cameraPanMode )\n {\n handleCameraPan( dx, dy );\n }\n\n if ( m_cameraZoomMode )\n {\n handleCameraZoom( dx, dy );\n }\n\n m_lastMouseX = event->pos().x();\n m_lastMouseY = event->pos().y();\n\n if ( m_hasLightAttached )\n {\n m_light->setPosition( m_camera->getPosition() );\n m_light->setDirection( m_camera->getDirection() );\n }\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n\n return true;\n}\n\nbool Gui::TrackballCamera::handleMouseReleaseEvent( QMouseEvent* event ) {\n m_cameraRotateMode = false;\n m_cameraPanMode = false;\n m_cameraZoomMode = false;\n m_quickCameraModifier = 1.0;\n\n return true;\n}\n\nbool Gui::TrackballCamera::handleWheelEvent( QWheelEvent* event ) {\n handleCameraZoom( ( event->angleDelta().y() * 0.01 + event->angleDelta().x() * 0.01 ) *\n m_wheelSpeedModifier );\n\n if ( m_hasLightAttached )\n {\n m_light->setPosition( m_camera->getPosition() );\n m_light->setDirection( m_camera->getDirection() );\n }\n\n emit cameraPositionChanged( m_camera->getPosition() );\n\n return true;\n}\n\nbool Gui::TrackballCamera::handleKeyPressEvent( QKeyEvent* e ) {\n if ( Gui::KeyMappingManager::getInstance()->actionTriggered(\n e, Gui::KeyMappingManager::TRACKBALLCAMERA_ROTATE_AROUND ) )\n {\n m_rotateAround = !m_rotateAround;\n return true;\n }\n\n return false;\n}\n\nbool Gui::TrackballCamera::handleKeyReleaseEvent( QKeyEvent* e ) {\n return false;\n}\n\nvoid Gui::TrackballCamera::save( std::ostream& out ) const {\n out << \"#Radium_trackball_camera_state\" << std::endl;\n out << m_camera->getFrame().matrix() << std::endl;\n out << std::endl;\n out << m_camera->getFOV() << \" \" << m_camera->getZNear() << \" \" << m_camera->getZFar()\n << std::endl;\n out << std::endl;\n out << m_trackballCenter.transpose();\n}\n\nvoid Gui::TrackballCamera::load( std::istream& in ) {\n std::string str;\n Scalar M[16]; \/\/ 4x4 view matrix;\n Scalar fov, znear, zfar, x, y, z;\n\n in >> str;\n bool result = !in.fail();\n for ( uint i = 0; i < 16; ++i )\n {\n in >> M[i];\n result &= !in.fail();\n }\n in >> fov >> znear >> zfar >> x >> y >> z;\n result &= !in.fail();\n\n if ( !result )\n {\n LOG( logWARNING ) << \"Could not load camera file data\";\n return;\n }\n\n Core::Matrix4 frame;\n frame << M[0], M[1], M[2], M[3], M[4], M[5], M[6], M[7], M[8], M[9], M[10], M[11], M[12], M[13],\n M[14], M[15];\n\n Core::Transform T( frame );\n m_camera->setFrame( T );\n m_camera->setFOV( fov );\n m_camera->setZNear( znear );\n m_camera->setZFar( zfar );\n m_trackballCenter = Core::Vector3( x, y, x );\n\n updatePhiTheta();\n\n if ( m_hasLightAttached )\n {\n m_light->setPosition( m_camera->getPosition() );\n m_light->setDirection( m_camera->getDirection() );\n }\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::setCameraPosition( const Core::Vector3& position ) {\n if ( position == m_trackballCenter )\n {\n QMessageBox::warning( nullptr, \"Error\", \"Position cannot be set to target point\" );\n return;\n }\n m_camera->setPosition( position );\n m_camera->setDirection( m_trackballCenter - position );\n\n updatePhiTheta();\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::setCameraTarget( const Core::Vector3& target ) {\n if ( m_camera->getPosition() == m_trackballCenter )\n {\n QMessageBox::warning( nullptr, \"Error\", \"Target cannot be set to current camera position\" );\n return;\n }\n\n m_trackballCenter = target;\n m_camera->setDirection( target - m_camera->getPosition() );\n updatePhiTheta();\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::fitScene( const Core::Aabb& aabb ) {\n resetCamera();\n\n Scalar f = m_camera->getFOV();\n Scalar a = m_camera->getAspect();\n\n const Scalar r = ( aabb.max() - aabb.min() ).norm() \/ 2.0;\n const Scalar x = r \/ std::sin( f \/ 2.0 );\n const Scalar y = r \/ std::sin( f * a \/ 2.0 );\n Scalar d = std::max( std::max( x, y ), Scalar( 0.001 ) );\n\n m_camera->setPosition(\n Core::Vector3( aabb.center().x(), aabb.center().y(), aabb.center().z() + d ) );\n m_camera->setDirection( Core::Vector3( 0, 0, -1 ) );\n m_trackballCenter = aabb.center();\n\n updatePhiTheta();\n\n m_distFromCenter = d;\n m_cameraRadius = d;\n\n Scalar zfar =\n std::max( Scalar( d + ( aabb.max().z() - aabb.min().z() ) * 2.0 ), m_camera->getZFar() );\n m_camera->setZFar( zfar );\n\n if ( m_hasLightAttached )\n {\n m_light->setPosition( m_camera->getPosition() );\n m_light->setDirection( m_camera->getDirection() );\n }\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::handleCameraRotate( Scalar dx, Scalar dy ) {\n Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier;\n Scalar y = -dy * m_cameraSensitivity * m_quickCameraModifier;\n\n Scalar phi = m_phi + x; \/\/ Keep phi between -pi and pi\n Scalar theta = std::min( std::max( m_theta + y, Scalar( 0.0 ) ), Pi );\n\n Scalar dphi = phi - m_phi;\n Scalar dtheta = theta - m_theta;\n\n const Core::Vector3 C = m_trackballCenter;\n const Core::Vector3 P0 = m_camera->getPosition();\n const Scalar r = ( C - P0 ).norm();\n \/\/ Compute new camera position, on the sphere of radius r centered on C\n Scalar px = C.x() + r * std::cos( phi ) * std::sin( theta );\n Scalar py = C.y() + r * std::cos( theta );\n Scalar pz = C.z() + r * std::sin( phi ) * std::sin( theta );\n\n \/\/ Compute the translation from old pos to new pos\n Core::Vector3 P( px, py, pz );\n Core::Vector3 t( P - P0 );\n\n \/\/ Translate the camera given this translation\n Core::Transform T( Core::Transform::Identity() );\n T.translation() = t;\n\n \/\/ Rotate the camera so that it points to the center\n Core::Transform R1( Core::Transform::Identity() );\n Core::Transform R2( Core::Transform::Identity() );\n\n Core::Vector3 U = Core::Vector3( 0, 1, 0 );\n Core::Vector3 R = -m_camera->getRightVector().normalized();\n\n R1 = Core::AngleAxis( -dphi, U );\n R2 = Core::AngleAxis( -dtheta, R );\n\n m_camera->applyTransform( T * R1 * R2 );\n\n m_phi = phi;\n m_theta = theta;\n}\n\nvoid Gui::TrackballCamera::handleCameraPan( Scalar dx, Scalar dy ) {\n Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1;\n Scalar y = dy * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1;\n \/\/ Move camera and trackball center, keep the distance to the center\n Core::Vector3 R = -m_camera->getRightVector();\n Core::Vector3 U = m_camera->getUpVector();\n\n Core::Transform T( Core::Transform::Identity() );\n Core::Vector3 t = x * R + y * U;\n T.translate( t );\n\n m_camera->applyTransform( T );\n m_trackballCenter += t;\n}\n\nvoid Gui::TrackballCamera::handleCameraZoom( Scalar dx, Scalar dy ) {\n handleCameraZoom( Ra::Core::Math::sign( dx ) * ( std::abs( dx ) + std::abs( dy ) ) );\n}\n\nvoid Gui::TrackballCamera::handleCameraZoom( Scalar z ) {\n Scalar y = m_cameraRadius * z * m_cameraSensitivity * m_quickCameraModifier;\n Core::Vector3 F = m_camera->getDirection();\n\n Scalar dist = ( m_trackballCenter - m_camera->getPosition() ).norm();\n\n if ( dist < ( m_camera->getZNear() + y ) )\n {\n y = dist - m_camera->getZNear();\n }\n\n Core::Transform T( Core::Transform::Identity() );\n Core::Vector3 t = y * F;\n T.translate( t );\n\n m_camera->applyTransform( T );\n\n \/\/ m_trackballCenter = m_camera->getPosition() + m_camera->getDirection().normalized();\n\n emit cameraTargetChanged( m_trackballCenter );\n\n \/\/ m_distFromCenter = ( m_trackballCenter - m_camera->getPosition() ).norm();\n}\n\nvoid Gui::TrackballCamera::updatePhiTheta() {\n const Core::Vector3& P = m_camera->getPosition();\n const Core::Vector3& C = m_trackballCenter;\n const Core::Vector3& R = P - C;\n const Scalar r = R.norm();\n\n m_theta = std::acos( R.y() \/ r );\n m_phi = ( R.z() == 0.f && R.x() == 0.f ) ? 0.f : std::atan2( R.z(), R.x() );\n CORE_ASSERT( std::isfinite( m_theta ) && std::isfinite( m_phi ), \"Error in trackball camera\" );\n}\n} \/\/ namespace Ra\n<commit_msg>Fix camera load ;<commit_after>#include <GuiBase\/Viewer\/TrackballCamera.hpp>\n\n#include <QApplication>\n#include <QMessageBox>\n#include <iostream>\n\n#include <Core\/Event\/KeyEvent.hpp>\n#include <Core\/Event\/MouseEvent.hpp>\n#include <Core\/Log\/Log.hpp>\n#include <Core\/Math\/Math.hpp>\n#include <Engine\/Renderer\/Camera\/Camera.hpp>\n#include <Engine\/Renderer\/Light\/Light.hpp>\n\n#include <GuiBase\/Utils\/KeyMappingManager.hpp>\n\nnamespace Ra {\nusing Core::Math::Pi;\n\nGui::TrackballCamera::TrackballCamera( uint width, uint height ) :\n CameraInterface( width, height ),\n m_trackballCenter( 0, 0, 0 ),\n m_quickCameraModifier( 1.f ),\n m_wheelSpeedModifier( 0.02f ),\n m_distFromCenter( 1.0f ),\n m_cameraRadius( 1.0f ),\n m_rotateAround( true ),\n m_cameraRotateMode( false ),\n m_cameraPanMode( false ),\n m_cameraZoomMode( false ),\n m_walkingOn( false ),\n m_strafingOn( false ),\n m_climbingOn( false ),\n m_walking( 0 ),\n m_strafing( 0 ),\n m_climbing( 0 ) {\n resetCamera();\n}\n\nGui::TrackballCamera::~TrackballCamera() {}\n\nvoid Gui::TrackballCamera::resetCamera() {\n m_camera->setFrame( Core::Transform::Identity() );\n m_camera->setPosition( Core::Vector3( 0, 0, 1 ) );\n m_trackballCenter = Core::Vector3::Zero();\n updatePhiTheta();\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::setCameraRadius( Scalar rad ) {\n m_cameraRadius = rad;\n}\nScalar Gui::TrackballCamera::getCameraRadius() {\n return m_cameraRadius;\n}\n\nbool Gui::TrackballCamera::handleMousePressEvent( QMouseEvent* event ) {\n bool handled = false;\n m_lastMouseX = event->pos().x();\n m_lastMouseY = event->pos().y();\n\n \/* TODO: Better handling of rotation\/pan\/zoom with KeyMappingManager *\/\n if ( event->modifiers().testFlag( Qt::NoModifier ) )\n {\n m_cameraRotateMode = true;\n handled = true;\n }\n\n if ( event->modifiers().testFlag( Qt::ShiftModifier ) )\n {\n m_cameraPanMode = true;\n handled = true;\n }\n\n if ( event->modifiers().testFlag( Qt::ControlModifier ) )\n {\n m_cameraZoomMode = true;\n handled = true;\n }\n\n return handled;\n}\n\nbool Gui::TrackballCamera::handleMouseMoveEvent( QMouseEvent* event ) {\n Scalar dx = ( event->pos().x() - m_lastMouseX ) \/ m_camera->getWidth();\n Scalar dy = ( event->pos().y() - m_lastMouseY ) \/ m_camera->getHeight();\n\n if ( event->modifiers().testFlag( Qt::AltModifier ) )\n {\n m_quickCameraModifier = 10.0;\n } else\n { m_quickCameraModifier = 2.0; }\n\n if ( m_cameraRotateMode )\n {\n handleCameraRotate( dx, dy );\n }\n\n if ( m_cameraPanMode )\n {\n handleCameraPan( dx, dy );\n }\n\n if ( m_cameraZoomMode )\n {\n handleCameraZoom( dx, dy );\n }\n\n m_lastMouseX = event->pos().x();\n m_lastMouseY = event->pos().y();\n\n if ( m_hasLightAttached )\n {\n m_light->setPosition( m_camera->getPosition() );\n m_light->setDirection( m_camera->getDirection() );\n }\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n\n return true;\n}\n\nbool Gui::TrackballCamera::handleMouseReleaseEvent( QMouseEvent* event ) {\n m_cameraRotateMode = false;\n m_cameraPanMode = false;\n m_cameraZoomMode = false;\n m_quickCameraModifier = 1.0;\n\n return true;\n}\n\nbool Gui::TrackballCamera::handleWheelEvent( QWheelEvent* event ) {\n handleCameraZoom( ( event->angleDelta().y() * 0.01 + event->angleDelta().x() * 0.01 ) *\n m_wheelSpeedModifier );\n\n if ( m_hasLightAttached )\n {\n m_light->setPosition( m_camera->getPosition() );\n m_light->setDirection( m_camera->getDirection() );\n }\n\n emit cameraPositionChanged( m_camera->getPosition() );\n\n return true;\n}\n\nbool Gui::TrackballCamera::handleKeyPressEvent( QKeyEvent* e ) {\n if ( Gui::KeyMappingManager::getInstance()->actionTriggered(\n e, Gui::KeyMappingManager::TRACKBALLCAMERA_ROTATE_AROUND ) )\n {\n m_rotateAround = !m_rotateAround;\n return true;\n }\n\n return false;\n}\n\nbool Gui::TrackballCamera::handleKeyReleaseEvent( QKeyEvent* e ) {\n return false;\n}\n\nvoid Gui::TrackballCamera::save( std::ostream& out ) const {\n out << \"#Radium_trackball_camera_state\" << std::endl;\n out << m_camera->getFrame().matrix() << std::endl;\n out << std::endl;\n out << m_camera->getFOV() << \" \" << m_camera->getZNear() << \" \" << m_camera->getZFar() << \" \"\n << m_camera->getZoomFactor() << \" \" << m_cameraRadius << \" \" << m_distFromCenter\n << std::endl;\n out << std::endl;\n out << m_trackballCenter.transpose();\n out << std::endl;\n}\n\nvoid Gui::TrackballCamera::load( std::istream& in ) {\n std::string str;\n Scalar M[16]; \/\/ 4x4 view matrix;\n Scalar fov, znear, zfar, Z, r, d, x, y, z;\n\n in >> str;\n bool result = !in.fail();\n for ( uint i = 0; i < 16; ++i )\n {\n in >> M[i];\n result &= !in.fail();\n }\n in >> fov >> znear >> zfar >> Z >> r >> d >> x >> y >> z;\n result &= !in.fail();\n\n if ( !result )\n {\n LOG( logWARNING ) << \"Could not load camera file data\";\n return;\n }\n m_cameraRadius = r;\n m_distFromCenter = d;\n\n Core::Matrix4 frame;\n frame << M[0], M[1], M[2], M[3], M[4], M[5], M[6], M[7], M[8], M[9], M[10], M[11], M[12], M[13],\n M[14], M[15];\n\n Core::Transform T( frame );\n m_camera->setFrame( T );\n m_camera->setFOV( fov );\n m_camera->setZNear( znear );\n m_camera->setZFar( zfar );\n m_camera->setZoomFactor( Z );\n m_trackballCenter = Core::Vector3( x, y, z );\n\n updatePhiTheta();\n\n if ( m_hasLightAttached )\n {\n m_light->setPosition( m_camera->getPosition() );\n m_light->setDirection( m_camera->getDirection() );\n }\n\n save( std::cout );\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::setCameraPosition( const Core::Vector3& position ) {\n if ( position == m_trackballCenter )\n {\n QMessageBox::warning( nullptr, \"Error\", \"Position cannot be set to target point\" );\n return;\n }\n m_camera->setPosition( position );\n m_camera->setDirection( m_trackballCenter - position );\n\n updatePhiTheta();\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::setCameraTarget( const Core::Vector3& target ) {\n if ( m_camera->getPosition() == m_trackballCenter )\n {\n QMessageBox::warning( nullptr, \"Error\", \"Target cannot be set to current camera position\" );\n return;\n }\n\n m_trackballCenter = target;\n m_camera->setDirection( target - m_camera->getPosition() );\n updatePhiTheta();\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::fitScene( const Core::Aabb& aabb ) {\n resetCamera();\n\n Scalar f = m_camera->getFOV();\n Scalar a = m_camera->getAspect();\n\n const Scalar r = ( aabb.max() - aabb.min() ).norm() \/ 2.0;\n const Scalar x = r \/ std::sin( f \/ 2.0 );\n const Scalar y = r \/ std::sin( f * a \/ 2.0 );\n Scalar d = std::max( std::max( x, y ), Scalar( 0.001 ) );\n\n m_camera->setPosition(\n Core::Vector3( aabb.center().x(), aabb.center().y(), aabb.center().z() + d ) );\n m_camera->setDirection( Core::Vector3( 0, 0, -1 ) );\n m_trackballCenter = aabb.center();\n\n updatePhiTheta();\n\n m_distFromCenter = d;\n m_cameraRadius = d;\n\n Scalar zfar =\n std::max( Scalar( d + ( aabb.max().z() - aabb.min().z() ) * 2.0 ), m_camera->getZFar() );\n m_camera->setZFar( zfar );\n\n if ( m_hasLightAttached )\n {\n m_light->setPosition( m_camera->getPosition() );\n m_light->setDirection( m_camera->getDirection() );\n }\n\n emit cameraPositionChanged( m_camera->getPosition() );\n emit cameraTargetChanged( m_trackballCenter );\n}\n\nvoid Gui::TrackballCamera::handleCameraRotate( Scalar dx, Scalar dy ) {\n Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier;\n Scalar y = -dy * m_cameraSensitivity * m_quickCameraModifier;\n\n Scalar phi = m_phi + x; \/\/ Keep phi between -pi and pi\n Scalar theta = std::min( std::max( m_theta + y, Scalar( 0.0 ) ), Pi );\n\n Scalar dphi = phi - m_phi;\n Scalar dtheta = theta - m_theta;\n\n const Core::Vector3 C = m_trackballCenter;\n const Core::Vector3 P0 = m_camera->getPosition();\n const Scalar r = ( C - P0 ).norm();\n \/\/ Compute new camera position, on the sphere of radius r centered on C\n Scalar px = C.x() + r * std::cos( phi ) * std::sin( theta );\n Scalar py = C.y() + r * std::cos( theta );\n Scalar pz = C.z() + r * std::sin( phi ) * std::sin( theta );\n\n \/\/ Compute the translation from old pos to new pos\n Core::Vector3 P( px, py, pz );\n Core::Vector3 t( P - P0 );\n\n \/\/ Translate the camera given this translation\n Core::Transform T( Core::Transform::Identity() );\n T.translation() = t;\n\n \/\/ Rotate the camera so that it points to the center\n Core::Transform R1( Core::Transform::Identity() );\n Core::Transform R2( Core::Transform::Identity() );\n\n Core::Vector3 U = Core::Vector3( 0, 1, 0 );\n Core::Vector3 R = -m_camera->getRightVector().normalized();\n\n R1 = Core::AngleAxis( -dphi, U );\n R2 = Core::AngleAxis( -dtheta, R );\n\n m_camera->applyTransform( T * R1 * R2 );\n\n m_phi = phi;\n m_theta = theta;\n}\n\nvoid Gui::TrackballCamera::handleCameraPan( Scalar dx, Scalar dy ) {\n Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1;\n Scalar y = dy * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1;\n \/\/ Move camera and trackball center, keep the distance to the center\n Core::Vector3 R = -m_camera->getRightVector();\n Core::Vector3 U = m_camera->getUpVector();\n\n Core::Transform T( Core::Transform::Identity() );\n Core::Vector3 t = x * R + y * U;\n T.translate( t );\n\n m_camera->applyTransform( T );\n m_trackballCenter += t;\n}\n\nvoid Gui::TrackballCamera::handleCameraZoom( Scalar dx, Scalar dy ) {\n handleCameraZoom( Ra::Core::Math::sign( dx ) * ( std::abs( dx ) + std::abs( dy ) ) );\n}\n\nvoid Gui::TrackballCamera::handleCameraZoom( Scalar z ) {\n Scalar y = m_cameraRadius * z * m_cameraSensitivity * m_quickCameraModifier;\n Core::Vector3 F = m_camera->getDirection();\n\n Scalar dist = ( m_trackballCenter - m_camera->getPosition() ).norm();\n\n if ( dist < ( m_camera->getZNear() + y ) )\n {\n y = dist - m_camera->getZNear();\n }\n\n Core::Transform T( Core::Transform::Identity() );\n Core::Vector3 t = y * F;\n T.translate( t );\n\n m_camera->applyTransform( T );\n\n \/\/ m_trackballCenter = m_camera->getPosition() + m_camera->getDirection().normalized();\n\n emit cameraTargetChanged( m_trackballCenter );\n\n \/\/ m_distFromCenter = ( m_trackballCenter - m_camera->getPosition() ).norm();\n}\n\nvoid Gui::TrackballCamera::updatePhiTheta() {\n const Core::Vector3& P = m_camera->getPosition();\n const Core::Vector3& C = m_trackballCenter;\n const Core::Vector3& R = P - C;\n const Scalar r = R.norm();\n\n m_theta = std::acos( R.y() \/ r );\n m_phi = ( R.z() == 0.f && R.x() == 0.f ) ? 0.f : std::atan2( R.z(), R.x() );\n CORE_ASSERT( std::isfinite( m_theta ) && std::isfinite( m_phi ), \"Error in trackball camera\" );\n}\n} \/\/ namespace Ra\n<|endoftext|>"} {"text":"<commit_before>\n\n#include \"wsclient.hpp\"\n#include <cossb.hpp>\n#include <algorithm>\n#include <ext\/json.hpp>\n\nUSE_COMPONENT_INTERFACE(wsclient)\n\nvoid handle_message(const std::string & message)\n{\n\tnlohmann::json _json_data = nlohmann::json::parse(message);\n\n\tif(_json_data.find(\"service\")!=_json_data.end()){\n\t\tstring wsdata = _json_data.dump();\n\t\tstring service = _json_data[\"service\"];\n\t\tcossb::message msg(\"wsclient\", base::msg_type::REQUEST);\n\t\tmsg.pack(wsdata);\n\t\tcossb_broker->publish(service.c_str(), msg);\n\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Web socket message : {}\", wsdata));\n\t}\n\n}\n\nwsclient::wsclient()\n:cossb::interface::icomponent(COMPONENT(wsclient)){\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nwsclient::~wsclient() {\n\n}\n\nbool wsclient::setup()\n{\n\tstring uri = get_profile()->get(profile::section::property, \"endpoint\").asString(\"ws:\/\/localhost.9002\");\n\n\tif(!_client){\n\t\t_client = easywsclient::WebSocket::from_url(uri.c_str());\n\t\tif(_client->getReadyState()==easywsclient::WebSocket::OPEN){\n\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Connected to the {} websocket server\",uri));\n\t\t\tif(!_socket_task)\n\t\t\t\t_socket_task = create_task(wsclient::read);\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool wsclient::run()\n{\n\n\treturn true;\n}\n\nbool wsclient::stop()\n{\n\tdestroy_task(_socket_task);\n\n\t_client->close();\n\tdelete _client;\n\n\treturn true;\n}\n\nvoid wsclient::subscribe(cossb::message* const msg)\n{\n\tswitch(msg->get_frame()->type){\n\t\tcase cossb::base::msg_type::REQUEST:{\n\n\t\t\tstring pack = boost::any_cast<string>(*msg->get_data());\n\n\n\t\t} break;\n\t\tcase cossb::base::msg_type::DATA: break;\n\t\tcase cossb::base::msg_type::RESPONSE: break;\n\t\tcase cossb::base::msg_type::EVENT: break;\n\n\t}\n}\n\nvoid wsclient::read()\n{\n\twhile(1) {\n\t\ttry {\n\t\t\tif(_client->getReadyState()!=easywsclient::WebSocket::CLOSED){\n\t\t\t\t_client->poll();\n\t\t\t\t_client->dispatch(handle_message);\n\t\t\t}\n\n\t\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(100));\n\t\t\tif(boost::this_thread::interruption_requested()) break;\n\t\t}\n\t\tcatch(thread_interrupted&) {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<commit_msg>update<commit_after>\n\n#include \"wsclient.hpp\"\n#include <cossb.hpp>\n#include <algorithm>\n#include <ext\/json.hpp>\n\nUSE_COMPONENT_INTERFACE(wsclient)\n\nvoid handle_message(const std::string & message)\n{\n\tnlohmann::json _json_data = nlohmann::json::parse(message);\n\n\tif(_json_data.find(\"service\")!=_json_data.end()){\n\t\tstring wsdata = _json_data.dump();\n\t\tstring service = _json_data[\"service\"];\n\t\tcossb::message msg(\"wsclient\", base::msg_type::REQUEST);\n\t\tmsg.pack(wsdata);\n\t\tcossb_broker->publish(service.c_str(), msg);\n\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Publish WS message : {}\", wsdata));\n\t}\n\n}\n\nwsclient::wsclient()\n:cossb::interface::icomponent(COMPONENT(wsclient)){\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nwsclient::~wsclient() {\n\n}\n\nbool wsclient::setup()\n{\n\tstring uri = get_profile()->get(profile::section::property, \"endpoint\").asString(\"ws:\/\/localhost.9002\");\n\n\tif(!_client){\n\t\t_client = easywsclient::WebSocket::from_url(uri.c_str());\n\t\tif(_client->getReadyState()==easywsclient::WebSocket::OPEN){\n\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Connected to the {} websocket server\",uri));\n\t\t\tif(!_socket_task)\n\t\t\t\t_socket_task = create_task(wsclient::read);\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool wsclient::run()\n{\n\n\treturn true;\n}\n\nbool wsclient::stop()\n{\n\tdestroy_task(_socket_task);\n\n\t_client->close();\n\tdelete _client;\n\n\treturn true;\n}\n\nvoid wsclient::subscribe(cossb::message* const msg)\n{\n\tswitch(msg->get_frame()->type){\n\t\tcase cossb::base::msg_type::REQUEST:{\n\n\t\t\tstring pack = boost::any_cast<string>(*msg->get_data());\n\n\n\t\t} break;\n\t\tcase cossb::base::msg_type::DATA: break;\n\t\tcase cossb::base::msg_type::RESPONSE: break;\n\t\tcase cossb::base::msg_type::EVENT: break;\n\n\t}\n}\n\nvoid wsclient::read()\n{\n\twhile(1) {\n\t\ttry {\n\t\t\tif(_client->getReadyState()!=easywsclient::WebSocket::CLOSED){\n\t\t\t\t_client->poll();\n\t\t\t\t_client->dispatch(handle_message);\n\t\t\t}\n\n\t\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(100));\n\t\t\tif(boost::this_thread::interruption_requested()) break;\n\t\t}\n\t\tcatch(thread_interrupted&) {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file ProcessBus.hpp\n * @author Denis Kotov\n * @date 25 Jun 2017\n * @brief Contains ProcessBus class.\n * It is a broker pattern. Used to control registration\n * and connection of services\n * @copyright Denis Kotov, MIT License. Open source:\n *\/\n\n#ifndef ICC_PROCESSBUS_HPP\n#define ICC_PROCESSBUS_HPP\n\n#include <typeinfo>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <typeinfo>\n#include <typeindex>\n#include <unordered_map>\n#include <IComponent.hpp>\n\ntemplate <typename _Interface>\nclass IClient;\n\ntemplate <typename _Interface>\nclass IService;\n\nclass ProcessBus\n : public IComponent {\n public:\n using tKeyForClientList = std::pair<std::type_index, std::string>;\n using tListOfClients = std::set<void*>;\n using tKeyForServiceList = std::type_index;\n using tListOfServices = std::map<std::string, void*>;\n\n public:\n template <typename _Interface>\n void registerService(IService<_Interface> * _service,\n const std::string & _serviceName) {\n push([=]{\n services_[tKeyForServiceList(typeid(_Interface))].emplace(_serviceName, _service);\n auto clientsKey = tKeyForClientList{typeid(_Interface), _serviceName};\n auto clients = clients_[clientsKey];\n for (auto client : clients) {\n reinterpret_cast<IClient<_Interface>*>(client)->setService(_service);\n }\n });\n }\n\n template <typename _Interface>\n void unregisterService(IService<_Interface> * _service,\n const std::string & _serviceName) {\n push([=]{\n auto clientsKey = tKeyForClientList{typeid(_Interface), _serviceName};\n auto clients = clients_[clientsKey];\n for (auto client : clients) {\n reinterpret_cast<IClient<_Interface>*>(client)->setService(nullptr);\n }\n });\n }\n\n template <typename _Interface>\n void buildClient(IClient<_Interface> * _client,\n const std::string & _serviceName) {\n push([=] {\n auto clientsKey = tKeyForClientList{typeid(_Interface), _serviceName};\n clients_[clientsKey].emplace(_client);\n auto servicesIter = services_.find(std::type_index(typeid(_Interface)));\n if (services_.end() != servicesIter) {\n auto serviceIter = std::find_if(servicesIter->second.begin(),\n servicesIter->second.end(),\n [=](std::pair<std::string, void*> element) {\n return element.first == _serviceName;\n });\n if (servicesIter->second.end() != serviceIter) {\n _client->setService(\n reinterpret_cast<IService<_Interface>*>(serviceIter->second));\n }\n }\n });\n }\n\n template <typename _Interface>\n void disassembleClient(IClient<_Interface> * _client,\n const std::string & _serviceName) {\n push([=] {\n auto clientsKey = tKeyForClientList{typeid(_Interface), _serviceName};\n clients_[clientsKey].erase(_client);\n });\n }\n\n public:\n static ProcessBus & getBus();\n\n private:\n ProcessBus();\n ProcessBus(const ProcessBus &) = delete;\n ProcessBus(ProcessBus &&) = delete;\n virtual ~ProcessBus();\n\n private:\n std::thread thread_;\n std::map<tKeyForClientList, tListOfClients> clients_;\n std::map<tKeyForServiceList, tListOfServices> services_;\n};\n\n#endif \/\/ICC_PROCESSBUS_HPP\n<commit_msg>Removed extra header<commit_after>\/**\n * @file ProcessBus.hpp\n * @author Denis Kotov\n * @date 25 Jun 2017\n * @brief Contains ProcessBus class.\n * It is a broker pattern. Used to control registration\n * and connection of services\n * @copyright Denis Kotov, MIT License. Open source:\n *\/\n\n#ifndef ICC_PROCESSBUS_HPP\n#define ICC_PROCESSBUS_HPP\n\n#include <set>\n#include <map>\n#include <algorithm>\n#include <typeinfo>\n#include <typeindex>\n#include <unordered_map>\n#include <IComponent.hpp>\n\ntemplate <typename _Interface>\nclass IClient;\n\ntemplate <typename _Interface>\nclass IService;\n\nclass ProcessBus\n : public IComponent {\n public:\n using tKeyForClientList = std::pair<std::type_index, std::string>;\n using tListOfClients = std::set<void*>;\n using tKeyForServiceList = std::type_index;\n using tListOfServices = std::map<std::string, void*>;\n\n public:\n template <typename _Interface>\n void registerService(IService<_Interface> * _service,\n const std::string & _serviceName) {\n push([=]{\n services_[tKeyForServiceList(typeid(_Interface))].emplace(_serviceName, _service);\n auto clientsKey = tKeyForClientList{typeid(_Interface), _serviceName};\n auto clients = clients_[clientsKey];\n for (auto client : clients) {\n reinterpret_cast<IClient<_Interface>*>(client)->setService(_service);\n }\n });\n }\n\n template <typename _Interface>\n void unregisterService(IService<_Interface> * _service,\n const std::string & _serviceName) {\n push([=]{\n auto clientsKey = tKeyForClientList{typeid(_Interface), _serviceName};\n auto clients = clients_[clientsKey];\n for (auto client : clients) {\n reinterpret_cast<IClient<_Interface>*>(client)->setService(nullptr);\n }\n });\n }\n\n template <typename _Interface>\n void buildClient(IClient<_Interface> * _client,\n const std::string & _serviceName) {\n push([=] {\n auto clientsKey = tKeyForClientList{typeid(_Interface), _serviceName};\n clients_[clientsKey].emplace(_client);\n auto servicesIter = services_.find(std::type_index(typeid(_Interface)));\n if (services_.end() != servicesIter) {\n auto serviceIter = std::find_if(servicesIter->second.begin(),\n servicesIter->second.end(),\n [=](std::pair<std::string, void*> element) {\n return element.first == _serviceName;\n });\n if (servicesIter->second.end() != serviceIter) {\n _client->setService(\n reinterpret_cast<IService<_Interface>*>(serviceIter->second));\n }\n }\n });\n }\n\n template <typename _Interface>\n void disassembleClient(IClient<_Interface> * _client,\n const std::string & _serviceName) {\n push([=] {\n auto clientsKey = tKeyForClientList{typeid(_Interface), _serviceName};\n clients_[clientsKey].erase(_client);\n });\n }\n\n public:\n static ProcessBus & getBus();\n\n private:\n ProcessBus();\n ProcessBus(const ProcessBus &) = delete;\n ProcessBus(ProcessBus &&) = delete;\n virtual ~ProcessBus();\n\n private:\n std::thread thread_;\n std::map<tKeyForClientList, tListOfClients> clients_;\n std::map<tKeyForServiceList, tListOfServices> services_;\n};\n\n#endif \/\/ICC_PROCESSBUS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"frame_buffer.h\"\n#include \"packet.h\"\n\n#include <cassert>\n#include <string.h>\n\n#if defined(_WIN32)\n \/\/ VS 2005: Don't warn for default initialized arrays. See help for more info.\n #pragma warning(disable:4351)\n#endif\n\nnamespace webrtc {\n\nVCMFrameBuffer::VCMFrameBuffer()\n :\n _state(kStateFree),\n _frameCounted(false),\n _nackCount(0),\n _latestPacketTimeMs(-1) {\n}\n\nVCMFrameBuffer::~VCMFrameBuffer() {\n}\n\nVCMFrameBuffer::VCMFrameBuffer(VCMFrameBuffer& rhs)\n:\nVCMEncodedFrame(rhs),\n_state(rhs._state),\n_frameCounted(rhs._frameCounted),\n_sessionInfo(),\n_nackCount(rhs._nackCount),\n_latestPacketTimeMs(rhs._latestPacketTimeMs)\n{\n _sessionInfo = rhs._sessionInfo;\n}\n\nwebrtc::FrameType\nVCMFrameBuffer::FrameType() const\n{\n return _sessionInfo.FrameType();\n}\n\nvoid\nVCMFrameBuffer::SetPreviousFrameLoss()\n{\n _sessionInfo.SetPreviousFrameLoss();\n}\n\nWebRtc_Word32\nVCMFrameBuffer::GetLowSeqNum() const\n{\n return _sessionInfo.LowSequenceNumber();\n}\n\nWebRtc_Word32\nVCMFrameBuffer::GetHighSeqNum() const\n{\n return _sessionInfo.HighSequenceNumber();\n}\n\nint VCMFrameBuffer::PictureId() const {\n return _sessionInfo.PictureId();\n}\n\nint VCMFrameBuffer::TemporalId() const {\n return _sessionInfo.TemporalId();\n}\n\nbool VCMFrameBuffer::LayerSync() const {\n return _sessionInfo.LayerSync();\n}\n\nint VCMFrameBuffer::Tl0PicId() const {\n return _sessionInfo.Tl0PicId();\n}\n\nbool VCMFrameBuffer::NonReference() const {\n return _sessionInfo.NonReference();\n}\n\nbool\nVCMFrameBuffer::IsSessionComplete() const\n{\n return _sessionInfo.complete();\n}\n\n\/\/ Insert packet\nVCMFrameBufferEnum\nVCMFrameBuffer::InsertPacket(const VCMPacket& packet, WebRtc_Word64 timeInMs,\n bool enableDecodableState, WebRtc_UWord32 rttMS)\n{\n if (_state == kStateDecoding)\n {\n \/\/ Do not insert packet\n return kIncomplete;\n }\n\n \/\/ Sanity to check if the frame has been freed. (Too old for example)\n if (_state == kStateFree)\n {\n return kStateError;\n }\n\n \/\/ is this packet part of this frame\n if (TimeStamp() && (TimeStamp() != packet.timestamp))\n {\n return kTimeStampError;\n }\n\n \/\/ sanity checks\n if (_size + packet.sizeBytes +\n (packet.insertStartCode ? kH264StartCodeLengthBytes : 0 )\n > kMaxJBFrameSizeBytes)\n {\n return kSizeError;\n }\n if (NULL == packet.dataPtr && packet.sizeBytes > 0)\n {\n return kSizeError;\n }\n if (packet.dataPtr != NULL)\n {\n _payloadType = packet.payloadType;\n }\n\n if (kStateEmpty == _state)\n {\n \/\/ First packet (empty and\/or media) inserted into this frame.\n \/\/ store some info and set some initial values.\n _timeStamp = packet.timestamp;\n _codec = packet.codec;\n if (packet.frameType != kFrameEmpty)\n {\n \/\/ first media packet\n SetState(kStateIncomplete);\n }\n }\n\n WebRtc_UWord32 requiredSizeBytes = Length() + packet.sizeBytes +\n (packet.insertStartCode ? kH264StartCodeLengthBytes : 0);\n if (requiredSizeBytes >= _size)\n {\n const WebRtc_UWord8* prevBuffer = _buffer;\n const WebRtc_UWord32 increments = requiredSizeBytes \/\n kBufferIncStepSizeBytes +\n (requiredSizeBytes %\n kBufferIncStepSizeBytes > 0);\n const WebRtc_UWord32 newSize = _size +\n increments * kBufferIncStepSizeBytes;\n if (newSize > kMaxJBFrameSizeBytes)\n {\n return kSizeError;\n }\n if (VerifyAndAllocate(newSize) == -1)\n {\n return kSizeError;\n }\n _sessionInfo.UpdateDataPointers(_buffer - prevBuffer);\n }\n\n CopyCodecSpecific(&packet.codecSpecificHeader);\n\n int retVal = _sessionInfo.InsertPacket(packet, _buffer,\n enableDecodableState,\n rttMS);\n if (retVal == -1)\n {\n return kSizeError;\n }\n else if (retVal == -2)\n {\n return kDuplicatePacket;\n }\n \/\/ update length\n _length = Length() + static_cast<WebRtc_UWord32>(retVal);\n\n _latestPacketTimeMs = timeInMs;\n\n if (_sessionInfo.complete()) {\n return kCompleteSession;\n } else if (_sessionInfo.decodable()) {\n SetState(kStateDecodable);\n return kDecodableSession;\n } else {\n \/\/ this layer is not complete\n if (_state == kStateComplete) {\n \/\/ we already have a complete layer\n \/\/ wait for all independent layers belonging to the same frame\n _state = kStateIncomplete;\n }\n }\n return kIncomplete;\n}\n\nWebRtc_Word64\nVCMFrameBuffer::LatestPacketTimeMs()\n{\n return _latestPacketTimeMs;\n}\n\n\/\/ Zero out all entries in list up to and including the (first)\n\/\/ entry equal to _lowSeqNum\nWebRtc_Word32\nVCMFrameBuffer::ZeroOutSeqNum(WebRtc_Word32* list, WebRtc_Word32 num)\n{\n if (_sessionInfo.ZeroOutSeqNum(list, num) != 0)\n {\n return -1;\n }\n return 0;\n}\n\n\/\/ Zero out all entries in list up to and including the (first) entry equal to\n\/\/ _lowSeqNum. Hybrid mode: 1. Don't NACK FEC packets 2. Make a smart decision\n\/\/ on whether to NACK or not\n\nWebRtc_Word32\nVCMFrameBuffer::ZeroOutSeqNumHybrid(WebRtc_Word32* list,\n WebRtc_Word32 num,\n WebRtc_UWord32 rttMs)\n{\n return _sessionInfo.ZeroOutSeqNumHybrid(list, num, rttMs);\n}\n\nvoid\nVCMFrameBuffer::IncrementNackCount()\n{\n _nackCount++;\n}\n\nWebRtc_Word16\nVCMFrameBuffer::GetNackCount() const\n{\n return _nackCount;\n}\n\nbool\nVCMFrameBuffer::HaveLastPacket() const\n{\n return _sessionInfo.HaveLastPacket();\n}\n\nvoid\nVCMFrameBuffer::Reset()\n{\n _length = 0;\n _timeStamp = 0;\n _sessionInfo.Reset();\n _frameCounted = false;\n _payloadType = 0;\n _nackCount = 0;\n _latestPacketTimeMs = -1;\n _state = kStateFree;\n VCMEncodedFrame::Reset();\n}\n\n\/\/ Makes sure the session contains a decodable stream.\nvoid\nVCMFrameBuffer::MakeSessionDecodable()\n{\n WebRtc_UWord32 retVal;\n#ifdef INDEPENDENT_PARTITIONS\n if (_codec != kVideoCodecVP8) {\n retVal = _sessionInfo.MakeDecodable();\n _length -= retVal;\n }\n#else\n retVal = _sessionInfo.MakeDecodable();\n _length -= retVal;\n#endif\n}\n\n\/\/ Set state of frame\nvoid\nVCMFrameBuffer::SetState(VCMFrameBufferStateEnum state)\n{\n if (_state == state)\n {\n return;\n }\n switch (state)\n {\n case kStateFree:\n \/\/ Reset everything\n \/\/ We can go to this state from all other states.\n \/\/ The one setting the state to free must ensure\n \/\/ that the frame is removed from the timestamp\n \/\/ ordered frame list in the jb.\n Reset();\n break;\n\n case kStateIncomplete:\n \/\/ we can go to this state from state kStateEmpty\n assert(_state == kStateEmpty ||\n _state == kStateDecoding);\n\n \/\/ Do nothing, we received a packet\n break;\n\n case kStateComplete:\n assert(_state == kStateEmpty ||\n _state == kStateIncomplete ||\n _state == kStateDecodable);\n\n break;\n\n case kStateEmpty:\n assert(_state == kStateFree);\n \/\/ Do nothing\n break;\n\n case kStateDecoding:\n \/\/ A frame might have received empty packets, or media packets might\n \/\/ have been removed when making the frame decodable. The frame can\n \/\/ still be set to decodable since it can be used to inform the\n \/\/ decoder of a frame loss.\n assert(_state == kStateComplete || _state == kStateIncomplete ||\n _state == kStateDecodable || _state == kStateEmpty);\n \/\/ Transfer frame information to EncodedFrame and create any codec\n \/\/ specific information\n RestructureFrameInformation();\n break;\n\n case kStateDecodable:\n assert(_state == kStateEmpty ||\n _state == kStateIncomplete);\n break;\n\n default:\n \/\/ Should never happen\n assert(!\"FrameBuffer::SetState Incorrect frame buffer state as input\");\n return;\n }\n _state = state;\n}\n\nvoid\nVCMFrameBuffer::RestructureFrameInformation()\n{\n PrepareForDecode();\n _frameType = ConvertFrameType(_sessionInfo.FrameType());\n _completeFrame = _sessionInfo.complete();\n _missingFrame = _sessionInfo.PreviousFrameLoss();\n}\n\nWebRtc_Word32\nVCMFrameBuffer::ExtractFromStorage(const EncodedVideoData& frameFromStorage)\n{\n _frameType = ConvertFrameType(frameFromStorage.frameType);\n _timeStamp = frameFromStorage.timeStamp;\n _payloadType = frameFromStorage.payloadType;\n _encodedWidth = frameFromStorage.encodedWidth;\n _encodedHeight = frameFromStorage.encodedHeight;\n _missingFrame = frameFromStorage.missingFrame;\n _completeFrame = frameFromStorage.completeFrame;\n _renderTimeMs = frameFromStorage.renderTimeMs;\n _codec = frameFromStorage.codec;\n const WebRtc_UWord8 *prevBuffer = _buffer;\n if (VerifyAndAllocate(frameFromStorage.payloadSize) < 0)\n {\n return VCM_MEMORY;\n }\n _sessionInfo.UpdateDataPointers(_buffer - prevBuffer);\n memcpy(_buffer, frameFromStorage.payloadData, frameFromStorage.payloadSize);\n _length = frameFromStorage.payloadSize;\n return VCM_OK;\n}\n\nint VCMFrameBuffer::NotDecodablePackets() const {\n return _sessionInfo.packets_not_decodable();\n}\n\n\/\/ Set counted status (as counted by JB or not)\nvoid VCMFrameBuffer::SetCountedFrame(bool frameCounted)\n{\n _frameCounted = frameCounted;\n}\n\nbool VCMFrameBuffer::GetCountedFrame() const\n{\n return _frameCounted;\n}\n\n\/\/ Get current state of frame\nVCMFrameBufferStateEnum\nVCMFrameBuffer::GetState() const\n{\n return _state;\n}\n\n\/\/ Get current state of frame\nVCMFrameBufferStateEnum\nVCMFrameBuffer::GetState(WebRtc_UWord32& timeStamp) const\n{\n timeStamp = TimeStamp();\n return GetState();\n}\n\nbool\nVCMFrameBuffer::IsRetransmitted() const\n{\n return _sessionInfo.session_nack();\n}\n\nvoid\nVCMFrameBuffer::PrepareForDecode()\n{\n#ifdef INDEPENDENT_PARTITIONS\n if (_codec == kVideoCodecVP8)\n {\n _length =\n _sessionInfo.BuildVP8FragmentationHeader(_buffer, _length,\n &_fragmentation);\n }\n else\n {\n _length = _sessionInfo.PrepareForDecode(_buffer);\n }\n#else\n _length = _sessionInfo.PrepareForDecode(_buffer);\n#endif\n}\n\n}\n<commit_msg>Updating the frame buffer return value in InsertPacket: Return NoError when a packet is inserted to a frame which is being decoded. Review URL: http:\/\/webrtc-codereview.appspot.com\/330027<commit_after>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"frame_buffer.h\"\n#include \"packet.h\"\n\n#include <cassert>\n#include <string.h>\n\n#if defined(_WIN32)\n \/\/ VS 2005: Don't warn for default initialized arrays. See help for more info.\n #pragma warning(disable:4351)\n#endif\n\nnamespace webrtc {\n\nVCMFrameBuffer::VCMFrameBuffer()\n :\n _state(kStateFree),\n _frameCounted(false),\n _nackCount(0),\n _latestPacketTimeMs(-1) {\n}\n\nVCMFrameBuffer::~VCMFrameBuffer() {\n}\n\nVCMFrameBuffer::VCMFrameBuffer(VCMFrameBuffer& rhs)\n:\nVCMEncodedFrame(rhs),\n_state(rhs._state),\n_frameCounted(rhs._frameCounted),\n_sessionInfo(),\n_nackCount(rhs._nackCount),\n_latestPacketTimeMs(rhs._latestPacketTimeMs)\n{\n _sessionInfo = rhs._sessionInfo;\n}\n\nwebrtc::FrameType\nVCMFrameBuffer::FrameType() const\n{\n return _sessionInfo.FrameType();\n}\n\nvoid\nVCMFrameBuffer::SetPreviousFrameLoss()\n{\n _sessionInfo.SetPreviousFrameLoss();\n}\n\nWebRtc_Word32\nVCMFrameBuffer::GetLowSeqNum() const\n{\n return _sessionInfo.LowSequenceNumber();\n}\n\nWebRtc_Word32\nVCMFrameBuffer::GetHighSeqNum() const\n{\n return _sessionInfo.HighSequenceNumber();\n}\n\nint VCMFrameBuffer::PictureId() const {\n return _sessionInfo.PictureId();\n}\n\nint VCMFrameBuffer::TemporalId() const {\n return _sessionInfo.TemporalId();\n}\n\nbool VCMFrameBuffer::LayerSync() const {\n return _sessionInfo.LayerSync();\n}\n\nint VCMFrameBuffer::Tl0PicId() const {\n return _sessionInfo.Tl0PicId();\n}\n\nbool VCMFrameBuffer::NonReference() const {\n return _sessionInfo.NonReference();\n}\n\nbool\nVCMFrameBuffer::IsSessionComplete() const\n{\n return _sessionInfo.complete();\n}\n\n\/\/ Insert packet\nVCMFrameBufferEnum\nVCMFrameBuffer::InsertPacket(const VCMPacket& packet, WebRtc_Word64 timeInMs,\n bool enableDecodableState, WebRtc_UWord32 rttMS)\n{\n if (_state == kStateDecoding)\n {\n \/\/ Do not insert packet\n return kNoError;\n }\n\n \/\/ Sanity to check if the frame has been freed. (Too old for example)\n if (_state == kStateFree)\n {\n return kStateError;\n }\n\n \/\/ is this packet part of this frame\n if (TimeStamp() && (TimeStamp() != packet.timestamp))\n {\n return kTimeStampError;\n }\n\n \/\/ sanity checks\n if (_size + packet.sizeBytes +\n (packet.insertStartCode ? kH264StartCodeLengthBytes : 0 )\n > kMaxJBFrameSizeBytes)\n {\n return kSizeError;\n }\n if (NULL == packet.dataPtr && packet.sizeBytes > 0)\n {\n return kSizeError;\n }\n if (packet.dataPtr != NULL)\n {\n _payloadType = packet.payloadType;\n }\n\n if (kStateEmpty == _state)\n {\n \/\/ First packet (empty and\/or media) inserted into this frame.\n \/\/ store some info and set some initial values.\n _timeStamp = packet.timestamp;\n _codec = packet.codec;\n if (packet.frameType != kFrameEmpty)\n {\n \/\/ first media packet\n SetState(kStateIncomplete);\n }\n }\n\n WebRtc_UWord32 requiredSizeBytes = Length() + packet.sizeBytes +\n (packet.insertStartCode ? kH264StartCodeLengthBytes : 0);\n if (requiredSizeBytes >= _size)\n {\n const WebRtc_UWord8* prevBuffer = _buffer;\n const WebRtc_UWord32 increments = requiredSizeBytes \/\n kBufferIncStepSizeBytes +\n (requiredSizeBytes %\n kBufferIncStepSizeBytes > 0);\n const WebRtc_UWord32 newSize = _size +\n increments * kBufferIncStepSizeBytes;\n if (newSize > kMaxJBFrameSizeBytes)\n {\n return kSizeError;\n }\n if (VerifyAndAllocate(newSize) == -1)\n {\n return kSizeError;\n }\n _sessionInfo.UpdateDataPointers(_buffer - prevBuffer);\n }\n\n CopyCodecSpecific(&packet.codecSpecificHeader);\n\n int retVal = _sessionInfo.InsertPacket(packet, _buffer,\n enableDecodableState,\n rttMS);\n if (retVal == -1)\n {\n return kSizeError;\n }\n else if (retVal == -2)\n {\n return kDuplicatePacket;\n }\n \/\/ update length\n _length = Length() + static_cast<WebRtc_UWord32>(retVal);\n\n _latestPacketTimeMs = timeInMs;\n\n if (_sessionInfo.complete()) {\n return kCompleteSession;\n } else if (_sessionInfo.decodable()) {\n SetState(kStateDecodable);\n return kDecodableSession;\n } else {\n \/\/ this layer is not complete\n if (_state == kStateComplete) {\n \/\/ we already have a complete layer\n \/\/ wait for all independent layers belonging to the same frame\n _state = kStateIncomplete;\n }\n }\n return kIncomplete;\n}\n\nWebRtc_Word64\nVCMFrameBuffer::LatestPacketTimeMs()\n{\n return _latestPacketTimeMs;\n}\n\n\/\/ Zero out all entries in list up to and including the (first)\n\/\/ entry equal to _lowSeqNum\nWebRtc_Word32\nVCMFrameBuffer::ZeroOutSeqNum(WebRtc_Word32* list, WebRtc_Word32 num)\n{\n if (_sessionInfo.ZeroOutSeqNum(list, num) != 0)\n {\n return -1;\n }\n return 0;\n}\n\n\/\/ Zero out all entries in list up to and including the (first) entry equal to\n\/\/ _lowSeqNum. Hybrid mode: 1. Don't NACK FEC packets 2. Make a smart decision\n\/\/ on whether to NACK or not\n\nWebRtc_Word32\nVCMFrameBuffer::ZeroOutSeqNumHybrid(WebRtc_Word32* list,\n WebRtc_Word32 num,\n WebRtc_UWord32 rttMs)\n{\n return _sessionInfo.ZeroOutSeqNumHybrid(list, num, rttMs);\n}\n\nvoid\nVCMFrameBuffer::IncrementNackCount()\n{\n _nackCount++;\n}\n\nWebRtc_Word16\nVCMFrameBuffer::GetNackCount() const\n{\n return _nackCount;\n}\n\nbool\nVCMFrameBuffer::HaveLastPacket() const\n{\n return _sessionInfo.HaveLastPacket();\n}\n\nvoid\nVCMFrameBuffer::Reset()\n{\n _length = 0;\n _timeStamp = 0;\n _sessionInfo.Reset();\n _frameCounted = false;\n _payloadType = 0;\n _nackCount = 0;\n _latestPacketTimeMs = -1;\n _state = kStateFree;\n VCMEncodedFrame::Reset();\n}\n\n\/\/ Makes sure the session contains a decodable stream.\nvoid\nVCMFrameBuffer::MakeSessionDecodable()\n{\n WebRtc_UWord32 retVal;\n#ifdef INDEPENDENT_PARTITIONS\n if (_codec != kVideoCodecVP8) {\n retVal = _sessionInfo.MakeDecodable();\n _length -= retVal;\n }\n#else\n retVal = _sessionInfo.MakeDecodable();\n _length -= retVal;\n#endif\n}\n\n\/\/ Set state of frame\nvoid\nVCMFrameBuffer::SetState(VCMFrameBufferStateEnum state)\n{\n if (_state == state)\n {\n return;\n }\n switch (state)\n {\n case kStateFree:\n \/\/ Reset everything\n \/\/ We can go to this state from all other states.\n \/\/ The one setting the state to free must ensure\n \/\/ that the frame is removed from the timestamp\n \/\/ ordered frame list in the jb.\n Reset();\n break;\n\n case kStateIncomplete:\n \/\/ we can go to this state from state kStateEmpty\n assert(_state == kStateEmpty ||\n _state == kStateDecoding);\n\n \/\/ Do nothing, we received a packet\n break;\n\n case kStateComplete:\n assert(_state == kStateEmpty ||\n _state == kStateIncomplete ||\n _state == kStateDecodable);\n\n break;\n\n case kStateEmpty:\n assert(_state == kStateFree);\n \/\/ Do nothing\n break;\n\n case kStateDecoding:\n \/\/ A frame might have received empty packets, or media packets might\n \/\/ have been removed when making the frame decodable. The frame can\n \/\/ still be set to decodable since it can be used to inform the\n \/\/ decoder of a frame loss.\n assert(_state == kStateComplete || _state == kStateIncomplete ||\n _state == kStateDecodable || _state == kStateEmpty);\n \/\/ Transfer frame information to EncodedFrame and create any codec\n \/\/ specific information\n RestructureFrameInformation();\n break;\n\n case kStateDecodable:\n assert(_state == kStateEmpty ||\n _state == kStateIncomplete);\n break;\n\n default:\n \/\/ Should never happen\n assert(!\"FrameBuffer::SetState Incorrect frame buffer state as input\");\n return;\n }\n _state = state;\n}\n\nvoid\nVCMFrameBuffer::RestructureFrameInformation()\n{\n PrepareForDecode();\n _frameType = ConvertFrameType(_sessionInfo.FrameType());\n _completeFrame = _sessionInfo.complete();\n _missingFrame = _sessionInfo.PreviousFrameLoss();\n}\n\nWebRtc_Word32\nVCMFrameBuffer::ExtractFromStorage(const EncodedVideoData& frameFromStorage)\n{\n _frameType = ConvertFrameType(frameFromStorage.frameType);\n _timeStamp = frameFromStorage.timeStamp;\n _payloadType = frameFromStorage.payloadType;\n _encodedWidth = frameFromStorage.encodedWidth;\n _encodedHeight = frameFromStorage.encodedHeight;\n _missingFrame = frameFromStorage.missingFrame;\n _completeFrame = frameFromStorage.completeFrame;\n _renderTimeMs = frameFromStorage.renderTimeMs;\n _codec = frameFromStorage.codec;\n const WebRtc_UWord8 *prevBuffer = _buffer;\n if (VerifyAndAllocate(frameFromStorage.payloadSize) < 0)\n {\n return VCM_MEMORY;\n }\n _sessionInfo.UpdateDataPointers(_buffer - prevBuffer);\n memcpy(_buffer, frameFromStorage.payloadData, frameFromStorage.payloadSize);\n _length = frameFromStorage.payloadSize;\n return VCM_OK;\n}\n\nint VCMFrameBuffer::NotDecodablePackets() const {\n return _sessionInfo.packets_not_decodable();\n}\n\n\/\/ Set counted status (as counted by JB or not)\nvoid VCMFrameBuffer::SetCountedFrame(bool frameCounted)\n{\n _frameCounted = frameCounted;\n}\n\nbool VCMFrameBuffer::GetCountedFrame() const\n{\n return _frameCounted;\n}\n\n\/\/ Get current state of frame\nVCMFrameBufferStateEnum\nVCMFrameBuffer::GetState() const\n{\n return _state;\n}\n\n\/\/ Get current state of frame\nVCMFrameBufferStateEnum\nVCMFrameBuffer::GetState(WebRtc_UWord32& timeStamp) const\n{\n timeStamp = TimeStamp();\n return GetState();\n}\n\nbool\nVCMFrameBuffer::IsRetransmitted() const\n{\n return _sessionInfo.session_nack();\n}\n\nvoid\nVCMFrameBuffer::PrepareForDecode()\n{\n#ifdef INDEPENDENT_PARTITIONS\n if (_codec == kVideoCodecVP8)\n {\n _length =\n _sessionInfo.BuildVP8FragmentationHeader(_buffer, _length,\n &_fragmentation);\n }\n else\n {\n _length = _sessionInfo.PrepareForDecode(_buffer);\n }\n#else\n _length = _sessionInfo.PrepareForDecode(_buffer);\n#endif\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.4.10); FILE MERGED 2005\/11\/10 17:15:23 pl 1.4.10.1: #i55991# removed warnings<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\r\n\/\/\r\n\/\/ҪṩSCreateInstanceӿڡӿڶfunSCreateInstance\r\nclass SComLoader\r\n{\r\n typedef BOOL (*funSCreateInstance)(IObjRef **);\r\npublic:\r\n SComLoader():m_hMod(0),m_funCreateInst(NULL){}\r\n ~SComLoader()\r\n {\r\n if(m_hMod) FreeLibrary(m_hMod);\r\n }\r\n\r\n BOOL CreateInstance(LPCTSTR pszDllPath,IObjRef **ppObj,LPCSTR pszFnName = \"SCreateInstance\")\r\n {\r\n if(!m_funCreateInst)\r\n {\r\n m_hMod=LoadLibrary(pszDllPath);\r\n if(!m_hMod) return FALSE;\r\n m_funCreateInst=(funSCreateInstance)GetProcAddress(m_hMod,pszFnName);\r\n if(!m_funCreateInst)\r\n {\r\n FreeLibrary(m_hMod);\r\n return FALSE;\r\n }\r\n }\r\n return m_funCreateInst(ppObj);\r\n }\r\nprotected:\r\n HMODULE m_hMod;\r\n funSCreateInstance m_funCreateInst;\r\n};<commit_msg><commit_after>#pragma once\r\n\r\n\/\/\r\n\/\/ҪṩSCreateInstanceӿڡӿڶfunSCreateInstance\r\nclass SComLoader\r\n{\r\n typedef BOOL (*funSCreateInstance)(IObjRef **);\r\npublic:\r\n SComLoader()\r\n :m_hMod(0)\r\n ,m_funCreateInst(NULL)\r\n {\r\n m_szDllPath[0]=0;\r\n }\r\n ~SComLoader()\r\n {\r\n if(m_hMod) FreeLibrary(m_hMod);\r\n }\r\n\r\n BOOL CreateInstance(LPCTSTR pszDllPath,IObjRef **ppObj,LPCSTR pszFnName = \"SCreateInstance\")\r\n {\r\n if(!m_funCreateInst)\r\n {\r\n m_hMod=LoadLibrary(pszDllPath);\r\n if(!m_hMod) return FALSE;\r\n m_funCreateInst=(funSCreateInstance)GetProcAddress(m_hMod,pszFnName);\r\n if(!m_funCreateInst)\r\n {\r\n FreeLibrary(m_hMod);\r\n return FALSE;\r\n }\r\n _tcscpy(m_szDllPath,pszDllPath);\r\n }\r\n return m_funCreateInst(ppObj);\r\n }\r\nprotected:\r\n HMODULE m_hMod;\r\n funSCreateInstance m_funCreateInst;\r\n TCHAR m_szDllPath[MAX_PATH];\r\n};<|endoftext|>"} {"text":"<commit_before>\/\/ -*- c++ -*- \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This file is part of Miro (The Middleware for Robots)\n\/\/ Copyright (C) 1999-2013\n\/\/ Department of Neural Information Processing, University of Ulm\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2, or (at your option)\n\/\/ 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. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/\n#define QT_ALTERNATE_QTSMANIP\n\n#include \"ConfigFile.h\"\n\n#include \"params\/Parser.h\"\n#include \"params\/Generator.h\"\n#include \"params\/TextErrorHandler.h\"\n\n#include <qfile.h>\n#include <qdom.h>\n#include <qxml.h>\n#include <qmessagebox.h>\n#include <QTextStream>\n\nMiro::Singleton<ConfigFileName> ConfigFileName::instance;\nMiro::Singleton<ConfigFile> ConfigFile::instance;\n\nConfigFileName::ConfigFileName() :\n fileName_(\".MiroConfigFile.xml\")\n{}\n\nConfigFile::ConfigFile() :\n generator_(NULL),\n handler_(NULL)\n{\n char const * const home = getenv(\"HOME\");\n configFile_ = QString(home) + \"\/\" + ConfigFileName::instance()->fileName();\n\n readConfigFile(); \n}\n \nConfigFile::~ConfigFile()\n{\n delete generator_;\n delete handler_;\n}\n\n\nvoid \nConfigFile::setDescriptionFiles(const QStringList& _descriptions)\n{\n descriptionFiles_ = _descriptions;\n\n writeConfigFile();\n} \t\n\n\n\/**\n *if no BehaviourDescriptionFile was loaded (i.e. behaviourFile==\"\") then\n *the function reads the path of the BehaviourDescriptionFile, which is used last, out of the Config-XML-File. \n *else it only returns the Name of the loaded BehaviourDescriptionFile (i. e. behaviourFile);\n *\/\nvoid \nConfigFile::readConfigFile()\n{\n descriptionFiles_.clear();\n\n \/\/ try to open policy editor config file\n QFile file(configFile_);\n if (file.open(QIODevice::ReadOnly)) {\n QDomDocument doc(\"MiroConfigDocument\");\n if (doc.setContent(&file)) {\n\n QDomNode n = doc.documentElement().firstChild();\n while (!n.isNull()) {\n\tQDomElement e = n.toElement();\n\tif (e.tagName() == \"config_item\" &&\n\t e.attribute(\"name\") == \"files\") {\n\t \n\t QDomNode node = n.firstChild();\n\t while (!node.isNull()) {\n\t e = node.toElement();\n\t if (e.tagName() == \"parameter\" &&\n\t\te.attribute(\"name\") == \"file\") {\n\t \/\/add behaviour description file to list\n\t descriptionFiles_.append(node.toElement().attribute(\"value\"));\n\t } \t \n\t node = node.nextSibling();\n\t }\t\n\t}\n\tn = n.nextSibling();\n }\n } \n else {\n QString infoText(\"Error parsing configuration file\\n\" + \n\t\t configFile_ +\n\t\t \"\\nStarting with empty configuration.\");\n QMessageBox::information(0, \"Policy Editor\", infoText);\n }\n file.close();\n }\n else {\n QString infoText(\"Error opening configuration file\\n\" + \n\t\t configFile_ +\n\t\t \"\\nStarting with empty configuration.\");\n QMessageBox::information(0, \"Policy Editor\", infoText);\n \/\/ create a minimal config file for the next run\n writeConfigFile();\n }\n\n parseDescriptionFiles();\n}\n\nvoid \nConfigFile::writeConfigFile()\n{\n parseDescriptionFiles();\n\n QDomDocument doc( \"MiroConfigDocument\" );\n QDomElement root = doc.createElement( \"Configuration\" );\n doc.appendChild( root );\n\n QDomElement tag = doc.createElement( \"config_item\" );\n tag.setAttribute(\"name\", \"files\");\n root.appendChild(tag);\n for (int i = 0; i < descriptionFiles_.count(); ++i) {\n QDomElement f = doc.createElement( \"parameter\" );\n f.setAttribute(\"name\", \"file\");\n f.setAttribute(\"value\", descriptionFiles_[i]);\n tag.appendChild(f);\n }\n\n QFile f(configFile_);\n if (!f.open(QIODevice::WriteOnly)) {\n throw QString(\"PolicyConfig::writeConfigFile: Error: file error!\");\n }\n QTextStream ts(&f);\n doc.save(ts, 0);\n}\n\nvoid \nConfigFile::parseDescriptionFiles()\n{\n bool okay = false;\n while (!okay) {\n delete generator_;\n generator_ = new Miro::CFG::Generator;\n delete handler_;\n handler_ = new Miro::CFG::Parser(*generator_);\n \n QStringList::Iterator first, last = descriptionFiles_.end();\n for (first = descriptionFiles_.begin(); first != last ; ++first) {\n\n \/\/ kill previous namespace nesting\n generator_->clearNamespace();\n\n QString fileName = *first;\n QFile xmlFile( fileName );\n if (!xmlFile.exists()) {\n QString infoText(\"Error parsing behaviour description file: \\n\" +\n\t\t fileName + \"\\n\" +\n\t\t \"File not found.\");\n QMessageBox::information(0, \"Policy Editor\", infoText);\n descriptionFiles_.remove(first);\n break;\n }\n QXmlInputSource source( xmlFile );\n QXmlSimpleReader reader;\n Miro::CFG::TextErrorHandler errorHandler;\n \n reader.setContentHandler( handler_ );\n reader.setErrorHandler( &errorHandler);\n\n if (!reader.parse( source )) {\n\tQString infoText(\"Error parsing behaviour description file:\\n\" +\n\t\t\t fileName + \"\\n\" +\n\t\t\t errorHandler.errorString());\n\tQMessageBox::information(0, \"Policy Editor\", infoText);\n\tdescriptionFiles_.remove(first);\n\tbreak;\n }\n }\n \/\/ parsing successfull\n okay = true;\n\n \/\/ cout << \"parsing complete. known types: \" << endl;\n \/\/ cout << *generator_ << endl;\n }\n}\n<commit_msg>If a Parameter Description File in the load list is not in the file system, query the user for permission to remove it from the load list<commit_after>\/\/ -*- c++ -*- \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This file is part of Miro (The Middleware for Robots)\n\/\/ Copyright (C) 1999-2013\n\/\/ Department of Neural Information Processing, University of Ulm\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2, or (at your option)\n\/\/ 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. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/\n#define QT_ALTERNATE_QTSMANIP\n\n#include \"ConfigFile.h\"\n\n#include \"params\/Parser.h\"\n#include \"params\/Generator.h\"\n#include \"params\/TextErrorHandler.h\"\n\n#include <qfile.h>\n#include <qdom.h>\n#include <qxml.h>\n#include <qmessagebox.h>\n#include <QTextStream>\n\nMiro::Singleton<ConfigFileName> ConfigFileName::instance;\nMiro::Singleton<ConfigFile> ConfigFile::instance;\n\nConfigFileName::ConfigFileName() :\n fileName_(\".MiroConfigFile.xml\")\n{}\n\nConfigFile::ConfigFile() :\n generator_(NULL),\n handler_(NULL)\n{\n char const * const home = getenv(\"HOME\");\n configFile_ = QString(home) + \"\/\" + ConfigFileName::instance()->fileName();\n\n readConfigFile(); \n}\n \nConfigFile::~ConfigFile()\n{\n delete generator_;\n delete handler_;\n}\n\n\nvoid \nConfigFile::setDescriptionFiles(const QStringList& _descriptions)\n{\n descriptionFiles_ = _descriptions;\n\n writeConfigFile();\n} \t\n\n\n\/**\n *if no BehaviourDescriptionFile was loaded (i.e. behaviourFile==\"\") then\n *the function reads the path of the BehaviourDescriptionFile, which is used last, out of the Config-XML-File. \n *else it only returns the Name of the loaded BehaviourDescriptionFile (i. e. behaviourFile);\n *\/\nvoid \nConfigFile::readConfigFile()\n{\n descriptionFiles_.clear();\n\n \/\/ try to open policy editor config file\n QFile file(configFile_);\n if (file.open(QIODevice::ReadOnly)) {\n QDomDocument doc(\"MiroConfigDocument\");\n if (doc.setContent(&file)) {\n\n QDomNode n = doc.documentElement().firstChild();\n while (!n.isNull()) {\n\tQDomElement e = n.toElement();\n\tif (e.tagName() == \"config_item\" &&\n\t e.attribute(\"name\") == \"files\") {\n\t \n\t QDomNode node = n.firstChild();\n\t while (!node.isNull()) {\n\t e = node.toElement();\n\t if (e.tagName() == \"parameter\" &&\n\t\te.attribute(\"name\") == \"file\") {\n\t \/\/add behaviour description file to list\n\t descriptionFiles_.append(node.toElement().attribute(\"value\"));\n\t } \t \n\t node = node.nextSibling();\n\t }\t\n\t}\n\tn = n.nextSibling();\n }\n } \n else {\n QString infoText(\"Error parsing configuration file\\n\" + \n\t\t configFile_ +\n\t\t \"\\nStarting with empty configuration.\");\n QMessageBox::information(0, \"Policy Editor\", infoText);\n }\n file.close();\n }\n else {\n QString infoText(\"Error opening configuration file\\n\" + \n\t\t configFile_ +\n\t\t \"\\nStarting with empty configuration.\");\n QMessageBox::information(0, \"Policy Editor\", infoText);\n \/\/ create a minimal config file for the next run\n writeConfigFile();\n }\n\n parseDescriptionFiles();\n}\n\nvoid \nConfigFile::writeConfigFile()\n{\n parseDescriptionFiles();\n\n QDomDocument doc( \"MiroConfigDocument\" );\n QDomElement root = doc.createElement( \"Configuration\" );\n doc.appendChild( root );\n\n QDomElement tag = doc.createElement( \"config_item\" );\n tag.setAttribute(\"name\", \"files\");\n root.appendChild(tag);\n for (int i = 0; i < descriptionFiles_.count(); ++i) {\n QDomElement f = doc.createElement( \"parameter\" );\n f.setAttribute(\"name\", \"file\");\n f.setAttribute(\"value\", descriptionFiles_[i]);\n tag.appendChild(f);\n }\n\n QFile f(configFile_);\n if (!f.open(QIODevice::WriteOnly)) {\n throw QString(\"PolicyConfig::writeConfigFile: Error: file error!\");\n }\n QTextStream ts(&f);\n doc.save(ts, 0);\n}\n\nvoid \nConfigFile::parseDescriptionFiles()\n{\n bool okay = false;\n while (!okay) {\n delete generator_;\n generator_ = new Miro::CFG::Generator;\n delete handler_;\n handler_ = new Miro::CFG::Parser(*generator_);\n \n QStringList::Iterator first, last = descriptionFiles_.end();\n for (first = descriptionFiles_.begin(); first != last ; ++first) {\n\n \/\/ kill previous namespace nesting\n generator_->clearNamespace();\n\n QString fileName = *first;\n QFile xmlFile( fileName );\n if (!xmlFile.exists()) {\n\t\/\/ Always remove the pathname of the nonexistent file.\n\t\/\/ Do this unconditionally before calling writeConfigFile() and\n\t\/\/ before break;\n\tdescriptionFiles_.remove(first);\n\t\/\/ For why this QMessageBox is built in this way, see\n\t\/\/ http:\/\/qt-project.org\/doc\/qt-4.8\/qmessagebox.html#the-property-based-api\n\t\/\/ where it says: \"Using the property-based API is recommended.\"\n\tQMessageBox msgBox;\n\tmsgBox.setText(\"Parameter Description File not found:\\n\" +\n\t\t fileName + \"\\n\");\n\tmsgBox.setInformativeText(\"Do you want to remove this file from the list?\");\n\tmsgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);\n\tmsgBox.setDefaultButton(QMessageBox::No);\n\tconst int ret = msgBox.exec();\n\tif (ret == QMessageBox::Yes)\n\t{\n\t writeConfigFile();\n\t}\n\tbreak;\n }\n QXmlInputSource source( xmlFile );\n QXmlSimpleReader reader;\n Miro::CFG::TextErrorHandler errorHandler;\n \n reader.setContentHandler( handler_ );\n reader.setErrorHandler( &errorHandler);\n\n if (!reader.parse( source )) {\n\tQString infoText(\"Error parsing behaviour description file:\\n\" +\n\t\t\t fileName + \"\\n\" +\n\t\t\t errorHandler.errorString());\n\tQMessageBox::information(0, \"Policy Editor\", infoText);\n\tdescriptionFiles_.remove(first);\n\tbreak;\n }\n }\n \/\/ parsing successfull\n okay = true;\n\n \/\/ cout << \"parsing complete. known types: \" << endl;\n \/\/ cout << *generator_ << endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- X86ELFObjectWriter.cpp - X86 ELF Writer ---------------------------===\/\/\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#include \"MCTargetDesc\/X86FixupKinds.h\"\n#include \"MCTargetDesc\/X86MCTargetDesc.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCELFObjectWriter.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/MC\/MCValue.h\"\n#include \"llvm\/Support\/ELF.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n\nusing namespace llvm;\n\nnamespace {\n class X86ELFObjectWriter : public MCELFObjectTargetWriter {\n public:\n X86ELFObjectWriter(bool IsELF64, uint8_t OSABI, uint16_t EMachine);\n\n ~X86ELFObjectWriter() override;\n\n protected:\n unsigned getRelocType(MCContext &Ctx, const MCValue &Target,\n const MCFixup &Fixup, bool IsPCRel) const override;\n };\n}\n\nX86ELFObjectWriter::X86ELFObjectWriter(bool IsELF64, uint8_t OSABI,\n uint16_t EMachine)\n : MCELFObjectTargetWriter(IsELF64, OSABI, EMachine,\n \/\/ Only i386 and IAMCU use Rel instead of RelA.\n \/*HasRelocationAddend*\/\n (EMachine != ELF::EM_386) &&\n (EMachine != ELF::EM_IAMCU)) {}\n\nX86ELFObjectWriter::~X86ELFObjectWriter()\n{}\n\nenum X86_64RelType { RT64_64, RT64_32, RT64_32S, RT64_16, RT64_8 };\n\nstatic X86_64RelType getType64(unsigned Kind,\n MCSymbolRefExpr::VariantKind &Modifier,\n bool &IsPCRel) {\n switch (Kind) {\n default:\n llvm_unreachable(\"Unimplemented\");\n case X86::reloc_global_offset_table8:\n Modifier = MCSymbolRefExpr::VK_GOT;\n IsPCRel = true;\n return RT64_64;\n case FK_Data_8:\n return RT64_64;\n case X86::reloc_signed_4byte:\n if (Modifier == MCSymbolRefExpr::VK_None && !IsPCRel)\n return RT64_32S;\n return RT64_32;\n case X86::reloc_global_offset_table:\n Modifier = MCSymbolRefExpr::VK_GOT;\n IsPCRel = true;\n return RT64_32;\n case FK_Data_4:\n case FK_PCRel_4:\n case X86::reloc_riprel_4byte:\n case X86::reloc_riprel_4byte_movq_load:\n return RT64_32;\n case FK_PCRel_2:\n case FK_Data_2:\n return RT64_16;\n case FK_PCRel_1:\n case FK_Data_1:\n return RT64_8;\n }\n}\n\nstatic void checkIs32(MCContext &Ctx, SMLoc Loc, X86_64RelType Type) {\n if (Type != RT64_32)\n Ctx.reportError(Loc,\n \"32 bit reloc applied to a field with a different size\");\n}\n\nstatic unsigned getRelocType64(MCContext &Ctx, SMLoc Loc,\n MCSymbolRefExpr::VariantKind Modifier,\n X86_64RelType Type, bool IsPCRel) {\n switch (Modifier) {\n default:\n llvm_unreachable(\"Unimplemented\");\n case MCSymbolRefExpr::VK_None:\n switch (Type) {\n case RT64_64:\n return IsPCRel ? ELF::R_X86_64_PC64 : ELF::R_X86_64_64;\n case RT64_32:\n return IsPCRel ? ELF::R_X86_64_PC32 : ELF::R_X86_64_32;\n case RT64_32S:\n return ELF::R_X86_64_32S;\n case RT64_16:\n return IsPCRel ? ELF::R_X86_64_PC16 : ELF::R_X86_64_16;\n case RT64_8:\n return IsPCRel ? ELF::R_X86_64_PC8 : ELF::R_X86_64_8;\n }\n case MCSymbolRefExpr::VK_GOT:\n switch (Type) {\n case RT64_64:\n return IsPCRel ? ELF::R_X86_64_GOTPC64 : ELF::R_X86_64_GOT64;\n case RT64_32:\n return IsPCRel ? ELF::R_X86_64_GOTPC32 : ELF::R_X86_64_GOT32;\n case RT64_32S:\n case RT64_16:\n case RT64_8:\n llvm_unreachable(\"Unimplemented\");\n }\n case MCSymbolRefExpr::VK_GOTOFF:\n assert(Type == RT64_64);\n assert(!IsPCRel);\n return ELF::R_X86_64_GOTOFF64;\n case MCSymbolRefExpr::VK_TPOFF:\n assert(!IsPCRel);\n switch (Type) {\n case RT64_64:\n return ELF::R_X86_64_TPOFF64;\n case RT64_32:\n return ELF::R_X86_64_TPOFF32;\n case RT64_32S:\n case RT64_16:\n case RT64_8:\n llvm_unreachable(\"Unimplemented\");\n }\n case MCSymbolRefExpr::VK_DTPOFF:\n assert(!IsPCRel);\n switch (Type) {\n case RT64_64:\n return ELF::R_X86_64_DTPOFF64;\n case RT64_32:\n return ELF::R_X86_64_DTPOFF32;\n case RT64_32S:\n case RT64_16:\n case RT64_8:\n llvm_unreachable(\"Unimplemented\");\n }\n case MCSymbolRefExpr::VK_SIZE:\n assert(!IsPCRel);\n switch (Type) {\n case RT64_64:\n return ELF::R_X86_64_SIZE64;\n case RT64_32:\n return ELF::R_X86_64_SIZE32;\n case RT64_32S:\n case RT64_16:\n case RT64_8:\n llvm_unreachable(\"Unimplemented\");\n }\n case MCSymbolRefExpr::VK_TLSCALL:\n return ELF::R_X86_64_TLSDESC_CALL;\n case MCSymbolRefExpr::VK_TLSDESC:\n return ELF::R_X86_64_GOTPC32_TLSDESC;\n case MCSymbolRefExpr::VK_TLSGD:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_TLSGD;\n case MCSymbolRefExpr::VK_GOTTPOFF:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_GOTTPOFF;\n case MCSymbolRefExpr::VK_TLSLD:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_TLSLD;\n case MCSymbolRefExpr::VK_PLT:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_PLT32;\n case MCSymbolRefExpr::VK_GOTPCREL:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_GOTPCREL;\n }\n}\n\nenum X86_32RelType { RT32_32, RT32_16, RT32_8 };\n\nstatic X86_32RelType getType32(X86_64RelType T) {\n switch (T) {\n case RT64_64:\n llvm_unreachable(\"Unimplemented\");\n case RT64_32:\n case RT64_32S:\n return RT32_32;\n case RT64_16:\n return RT32_16;\n case RT64_8:\n return RT32_8;\n }\n llvm_unreachable(\"unexpected relocation type!\");\n}\n\nstatic unsigned getRelocType32(MCSymbolRefExpr::VariantKind Modifier,\n X86_32RelType Type, bool IsPCRel) {\n switch (Modifier) {\n default:\n llvm_unreachable(\"Unimplemented\");\n case MCSymbolRefExpr::VK_None:\n switch (Type) {\n case RT32_32:\n return IsPCRel ? ELF::R_386_PC32 : ELF::R_386_32;\n case RT32_16:\n return IsPCRel ? ELF::R_386_PC16 : ELF::R_386_16;\n case RT32_8:\n return IsPCRel ? ELF::R_386_PC8 : ELF::R_386_8;\n }\n case MCSymbolRefExpr::VK_GOT:\n assert(Type == RT32_32);\n return IsPCRel ? ELF::R_386_GOTPC : ELF::R_386_GOT32;\n case MCSymbolRefExpr::VK_GOTOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_GOTOFF;\n case MCSymbolRefExpr::VK_TPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_LE_32;\n case MCSymbolRefExpr::VK_DTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_LDO_32;\n case MCSymbolRefExpr::VK_TLSGD:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_GD;\n case MCSymbolRefExpr::VK_GOTTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_IE_32;\n case MCSymbolRefExpr::VK_PLT:\n assert(Type == RT32_32);\n return ELF::R_386_PLT32;\n case MCSymbolRefExpr::VK_INDNTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_IE;\n case MCSymbolRefExpr::VK_NTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_LE;\n case MCSymbolRefExpr::VK_GOTNTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_GOTIE;\n case MCSymbolRefExpr::VK_TLSLDM:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_LDM;\n }\n}\n\nunsigned X86ELFObjectWriter::getRelocType(MCContext &Ctx, const MCValue &Target,\n const MCFixup &Fixup,\n bool IsPCRel) const {\n MCSymbolRefExpr::VariantKind Modifier = Target.getAccessVariant();\n X86_64RelType Type = getType64(Fixup.getKind(), Modifier, IsPCRel);\n if (getEMachine() == ELF::EM_X86_64)\n return getRelocType64(Ctx, Fixup.getLoc(), Modifier, Type, IsPCRel);\n\n assert((getEMachine() == ELF::EM_386 || getEMachine() == ELF::EM_IAMCU) &&\n \"Unsupported ELF machine type.\");\n return getRelocType32(Modifier, getType32(Type), IsPCRel);\n}\n\nMCObjectWriter *llvm::createX86ELFObjectWriter(raw_pwrite_stream &OS,\n bool IsELF64, uint8_t OSABI,\n uint16_t EMachine) {\n MCELFObjectTargetWriter *MOTW =\n new X86ELFObjectWriter(IsELF64, OSABI, EMachine);\n return createELFObjectWriter(MOTW, OS, \/*IsLittleEndian=*\/true);\n}\n<commit_msg>[MC\/ELF] Pass Fixup to getRelocType64.<commit_after>\/\/===-- X86ELFObjectWriter.cpp - X86 ELF Writer ---------------------------===\/\/\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#include \"MCTargetDesc\/X86FixupKinds.h\"\n#include \"MCTargetDesc\/X86MCTargetDesc.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCELFObjectWriter.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/MC\/MCValue.h\"\n#include \"llvm\/Support\/ELF.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n\nusing namespace llvm;\n\nnamespace {\n class X86ELFObjectWriter : public MCELFObjectTargetWriter {\n public:\n X86ELFObjectWriter(bool IsELF64, uint8_t OSABI, uint16_t EMachine);\n\n ~X86ELFObjectWriter() override;\n\n protected:\n unsigned getRelocType(MCContext &Ctx, const MCValue &Target,\n const MCFixup &Fixup, bool IsPCRel) const override;\n };\n}\n\nX86ELFObjectWriter::X86ELFObjectWriter(bool IsELF64, uint8_t OSABI,\n uint16_t EMachine)\n : MCELFObjectTargetWriter(IsELF64, OSABI, EMachine,\n \/\/ Only i386 and IAMCU use Rel instead of RelA.\n \/*HasRelocationAddend*\/\n (EMachine != ELF::EM_386) &&\n (EMachine != ELF::EM_IAMCU)) {}\n\nX86ELFObjectWriter::~X86ELFObjectWriter()\n{}\n\nenum X86_64RelType { RT64_64, RT64_32, RT64_32S, RT64_16, RT64_8 };\n\nstatic X86_64RelType getType64(unsigned Kind,\n MCSymbolRefExpr::VariantKind &Modifier,\n bool &IsPCRel) {\n switch (Kind) {\n default:\n llvm_unreachable(\"Unimplemented\");\n case X86::reloc_global_offset_table8:\n Modifier = MCSymbolRefExpr::VK_GOT;\n IsPCRel = true;\n return RT64_64;\n case FK_Data_8:\n return RT64_64;\n case X86::reloc_signed_4byte:\n if (Modifier == MCSymbolRefExpr::VK_None && !IsPCRel)\n return RT64_32S;\n return RT64_32;\n case X86::reloc_global_offset_table:\n Modifier = MCSymbolRefExpr::VK_GOT;\n IsPCRel = true;\n return RT64_32;\n case FK_Data_4:\n case FK_PCRel_4:\n case X86::reloc_riprel_4byte:\n case X86::reloc_riprel_4byte_movq_load:\n return RT64_32;\n case FK_PCRel_2:\n case FK_Data_2:\n return RT64_16;\n case FK_PCRel_1:\n case FK_Data_1:\n return RT64_8;\n }\n}\n\nstatic void checkIs32(MCContext &Ctx, SMLoc Loc, X86_64RelType Type) {\n if (Type != RT64_32)\n Ctx.reportError(Loc,\n \"32 bit reloc applied to a field with a different size\");\n}\n\nstatic unsigned getRelocType64(MCContext &Ctx, const MCFixup &Fixup,\n MCSymbolRefExpr::VariantKind Modifier,\n X86_64RelType Type, bool IsPCRel) {\n SMLoc Loc = Fixup.getLoc();\n switch (Modifier) {\n default:\n llvm_unreachable(\"Unimplemented\");\n case MCSymbolRefExpr::VK_None:\n switch (Type) {\n case RT64_64:\n return IsPCRel ? ELF::R_X86_64_PC64 : ELF::R_X86_64_64;\n case RT64_32:\n return IsPCRel ? ELF::R_X86_64_PC32 : ELF::R_X86_64_32;\n case RT64_32S:\n return ELF::R_X86_64_32S;\n case RT64_16:\n return IsPCRel ? ELF::R_X86_64_PC16 : ELF::R_X86_64_16;\n case RT64_8:\n return IsPCRel ? ELF::R_X86_64_PC8 : ELF::R_X86_64_8;\n }\n case MCSymbolRefExpr::VK_GOT:\n switch (Type) {\n case RT64_64:\n return IsPCRel ? ELF::R_X86_64_GOTPC64 : ELF::R_X86_64_GOT64;\n case RT64_32:\n return IsPCRel ? ELF::R_X86_64_GOTPC32 : ELF::R_X86_64_GOT32;\n case RT64_32S:\n case RT64_16:\n case RT64_8:\n llvm_unreachable(\"Unimplemented\");\n }\n case MCSymbolRefExpr::VK_GOTOFF:\n assert(Type == RT64_64);\n assert(!IsPCRel);\n return ELF::R_X86_64_GOTOFF64;\n case MCSymbolRefExpr::VK_TPOFF:\n assert(!IsPCRel);\n switch (Type) {\n case RT64_64:\n return ELF::R_X86_64_TPOFF64;\n case RT64_32:\n return ELF::R_X86_64_TPOFF32;\n case RT64_32S:\n case RT64_16:\n case RT64_8:\n llvm_unreachable(\"Unimplemented\");\n }\n case MCSymbolRefExpr::VK_DTPOFF:\n assert(!IsPCRel);\n switch (Type) {\n case RT64_64:\n return ELF::R_X86_64_DTPOFF64;\n case RT64_32:\n return ELF::R_X86_64_DTPOFF32;\n case RT64_32S:\n case RT64_16:\n case RT64_8:\n llvm_unreachable(\"Unimplemented\");\n }\n case MCSymbolRefExpr::VK_SIZE:\n assert(!IsPCRel);\n switch (Type) {\n case RT64_64:\n return ELF::R_X86_64_SIZE64;\n case RT64_32:\n return ELF::R_X86_64_SIZE32;\n case RT64_32S:\n case RT64_16:\n case RT64_8:\n llvm_unreachable(\"Unimplemented\");\n }\n case MCSymbolRefExpr::VK_TLSCALL:\n return ELF::R_X86_64_TLSDESC_CALL;\n case MCSymbolRefExpr::VK_TLSDESC:\n return ELF::R_X86_64_GOTPC32_TLSDESC;\n case MCSymbolRefExpr::VK_TLSGD:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_TLSGD;\n case MCSymbolRefExpr::VK_GOTTPOFF:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_GOTTPOFF;\n case MCSymbolRefExpr::VK_TLSLD:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_TLSLD;\n case MCSymbolRefExpr::VK_PLT:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_PLT32;\n case MCSymbolRefExpr::VK_GOTPCREL:\n checkIs32(Ctx, Loc, Type);\n return ELF::R_X86_64_GOTPCREL;\n }\n}\n\nenum X86_32RelType { RT32_32, RT32_16, RT32_8 };\n\nstatic X86_32RelType getType32(X86_64RelType T) {\n switch (T) {\n case RT64_64:\n llvm_unreachable(\"Unimplemented\");\n case RT64_32:\n case RT64_32S:\n return RT32_32;\n case RT64_16:\n return RT32_16;\n case RT64_8:\n return RT32_8;\n }\n llvm_unreachable(\"unexpected relocation type!\");\n}\n\nstatic unsigned getRelocType32(MCSymbolRefExpr::VariantKind Modifier,\n X86_32RelType Type, bool IsPCRel) {\n switch (Modifier) {\n default:\n llvm_unreachable(\"Unimplemented\");\n case MCSymbolRefExpr::VK_None:\n switch (Type) {\n case RT32_32:\n return IsPCRel ? ELF::R_386_PC32 : ELF::R_386_32;\n case RT32_16:\n return IsPCRel ? ELF::R_386_PC16 : ELF::R_386_16;\n case RT32_8:\n return IsPCRel ? ELF::R_386_PC8 : ELF::R_386_8;\n }\n case MCSymbolRefExpr::VK_GOT:\n assert(Type == RT32_32);\n return IsPCRel ? ELF::R_386_GOTPC : ELF::R_386_GOT32;\n case MCSymbolRefExpr::VK_GOTOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_GOTOFF;\n case MCSymbolRefExpr::VK_TPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_LE_32;\n case MCSymbolRefExpr::VK_DTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_LDO_32;\n case MCSymbolRefExpr::VK_TLSGD:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_GD;\n case MCSymbolRefExpr::VK_GOTTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_IE_32;\n case MCSymbolRefExpr::VK_PLT:\n assert(Type == RT32_32);\n return ELF::R_386_PLT32;\n case MCSymbolRefExpr::VK_INDNTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_IE;\n case MCSymbolRefExpr::VK_NTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_LE;\n case MCSymbolRefExpr::VK_GOTNTPOFF:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_GOTIE;\n case MCSymbolRefExpr::VK_TLSLDM:\n assert(Type == RT32_32);\n assert(!IsPCRel);\n return ELF::R_386_TLS_LDM;\n }\n}\n\nunsigned X86ELFObjectWriter::getRelocType(MCContext &Ctx, const MCValue &Target,\n const MCFixup &Fixup,\n bool IsPCRel) const {\n MCSymbolRefExpr::VariantKind Modifier = Target.getAccessVariant();\n X86_64RelType Type = getType64(Fixup.getKind(), Modifier, IsPCRel);\n if (getEMachine() == ELF::EM_X86_64)\n return getRelocType64(Ctx, Fixup, Modifier, Type, IsPCRel);\n\n assert((getEMachine() == ELF::EM_386 || getEMachine() == ELF::EM_IAMCU) &&\n \"Unsupported ELF machine type.\");\n return getRelocType32(Modifier, getType32(Type), IsPCRel);\n}\n\nMCObjectWriter *llvm::createX86ELFObjectWriter(raw_pwrite_stream &OS,\n bool IsELF64, uint8_t OSABI,\n uint16_t EMachine) {\n MCELFObjectTargetWriter *MOTW =\n new X86ELFObjectWriter(IsELF64, OSABI, EMachine);\n return createELFObjectWriter(MOTW, OS, \/*IsLittleEndian=*\/true);\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n#include <WarpedDebug.h>\r\n#include \"DVFSManagerFactory.h\"\r\n#include \"SharedDVFSManager.h\"\r\n#include \"DistributedDVFSManager.h\"\r\n#include \"TimeWarpSimulationManager.h\"\r\n#include \"SimulationConfiguration.h\"\r\n\r\n#include <string>\r\n\r\nusing std::cout;\r\nusing std::cerr;\r\nusing std::endl;\r\n\r\nDVFSManagerFactory::DVFSManagerFactory(){}\r\n\r\nDVFSManagerFactory::~DVFSManagerFactory(){}\r\n\r\n\/\/ allocate a new manager of the type given in the configuration file\r\nConfigurable *\r\nDVFSManagerFactory::allocate( SimulationConfiguration &configuration,\r\n\t\t\t\tConfigurable *parent ) const {\r\n\r\n TimeWarpSimulationManager *mySimulationManager = \r\n dynamic_cast<TimeWarpSimulationManager *>( parent );\r\n ASSERT(mySimulationManager);\r\n\r\n std::string dvfsManagerType = configuration.get_string({\"TimeWarp\", \"DVFSManager\", \"Type\"},\r\n \"None\");\r\n if(dvfsManagerType == \"None\") {\r\n return NULL;\r\n }\r\n\r\n std::string metric = configuration.get_string({\"TimeWarp\", \"DVFSManager\", \"UsefulWorkMetric\"},\r\n \"Rollbacks\");\r\n std::string al = configuration.get_string({\"TimeWarp\", \"DVFSManager\", \"Algorithm\"},\r\n \"Fixed\");\r\n bool dvfsDebugPrint = configuration.get_bool({\"TimeWarp\", \"DVFSManager\", \"DebugPrint\"}, false);\r\n int p = configuration.get_int({\"TimeWarp\", \"DVFSManager\", \"Period\"}, 1);\r\n int firsize = configuration.get_int({\"TimeWarp\", \"DVFSManager\", \"FIRSize\"}, 16);\r\n double threshold = configuration.get_double({\"TimeWarp\", \"DVFSManager\", \"Threshold\"}, 0.1);\r\n\r\n DVFSManager::UsefulWorkMetric uwm;\r\n if(metric == \"Rollbacks\")\r\n uwm = DVFSManager::ROLLBACKS;\r\n else if(metric == \"RollbackFraction\")\r\n uwm = DVFSManager::ROLLBACK_FRACTION;\r\n else {\r\n stringstream err;\r\n err << \"DVFSManager: UsefulWorkMetric \" << metric << \" is invalid. \"\r\n << \"Valid metrics are Rollbacks | RollbackFraction. Aborting simulation.\"\r\n << endl;\r\n mySimulationManager->shutdown(err.str());\r\n }\r\n\r\n DVFSManager::Algorithm alg;\r\n if(al == \"Fixed\")\r\n alg = DVFSManager::FIXED;\r\n else if(al == \"Performance\")\r\n alg = DVFSManager::PERFORMANCE;\r\n else if(al == \"Power\")\r\n alg = DVFSManager::POWER;\r\n else if(al == \"Hybrid\")\r\n alg = DVFSManager::HYBRID;\r\n else {\r\n stringstream err;\r\n err << \"DVFSManager: Algorithm \" << al << \" is invalid. \"\r\n << \"Valid options are Fixed | Performance | Power | Hybrid. \"\r\n << \"Aborting simulation.\" << endl;\r\n mySimulationManager->shutdown(err.str());\r\n }\r\n\r\n if(dvfsManagerType == \"Shared\" || dvfsManagerType == \"Distributed\") {\r\n cout << \"(\"\r\n << mySimulationManager->getSimulationManagerID()\r\n << \") configured a \" << dvfsManagerType << \" DVFS Manager\" << endl\r\n << \"Algorithm: \" << al << endl\r\n << \"Period: \" << p << endl\r\n << \"FIR Size: \" << firsize << endl\r\n << \"Useful work metric: \" << metric << endl\r\n << \"Threshold: \" << threshold << endl;\r\n if(dvfsDebugPrint)\r\n cout << \"Writing trace to csv\" << endl;\r\n\r\n if(dvfsManagerType == \"Shared\")\r\n return new SharedDVFSManager(mySimulationManager,\r\n p,\r\n firsize,\r\n alg,\r\n dvfsDebugPrint,\r\n uwm,\r\n threshold);\r\n\r\n return new DistributedDVFSManager(mySimulationManager,\r\n p,\r\n firsize,\r\n alg,\r\n dvfsDebugPrint,\r\n uwm,\r\n threshold);\r\n }\r\n else {\r\n stringstream err;\r\n cerr << \"DVFSManager: invalid type '\" << dvfsManagerType << \"'.\" << endl\r\n << \"Valid types are None | Shared | Distributed. Aborting simulation.\";\r\n mySimulationManager->shutdown(err.str());\r\n }\r\n}\r\n\r\nconst DVFSManagerFactory *\r\nDVFSManagerFactory::instance(){\r\n static DVFSManagerFactory *singleton = new DVFSManagerFactory();\r\n return singleton;\r\n}\r\n<commit_msg>Fixed control reaching end of non void function<commit_after>\r\n#include <WarpedDebug.h>\r\n#include \"DVFSManagerFactory.h\"\r\n#include \"SharedDVFSManager.h\"\r\n#include \"DistributedDVFSManager.h\"\r\n#include \"TimeWarpSimulationManager.h\"\r\n#include \"SimulationConfiguration.h\"\r\n\r\n#include <string>\r\n\r\nusing std::cout;\r\nusing std::cerr;\r\nusing std::endl;\r\n\r\nDVFSManagerFactory::DVFSManagerFactory(){}\r\n\r\nDVFSManagerFactory::~DVFSManagerFactory(){}\r\n\r\n\/\/ allocate a new manager of the type given in the configuration file\r\nConfigurable *\r\nDVFSManagerFactory::allocate( SimulationConfiguration &configuration,\r\n\t\t\t\tConfigurable *parent ) const {\r\n\r\n TimeWarpSimulationManager *mySimulationManager = \r\n dynamic_cast<TimeWarpSimulationManager *>( parent );\r\n ASSERT(mySimulationManager);\r\n\r\n std::string dvfsManagerType = configuration.get_string({\"TimeWarp\", \"DVFSManager\", \"Type\"},\r\n \"None\");\r\n if(dvfsManagerType == \"None\") {\r\n return NULL;\r\n }\r\n\r\n std::string metric = configuration.get_string({\"TimeWarp\", \"DVFSManager\", \"UsefulWorkMetric\"},\r\n \"Rollbacks\");\r\n std::string al = configuration.get_string({\"TimeWarp\", \"DVFSManager\", \"Algorithm\"},\r\n \"Fixed\");\r\n bool dvfsDebugPrint = configuration.get_bool({\"TimeWarp\", \"DVFSManager\", \"DebugPrint\"}, false);\r\n int p = configuration.get_int({\"TimeWarp\", \"DVFSManager\", \"Period\"}, 1);\r\n int firsize = configuration.get_int({\"TimeWarp\", \"DVFSManager\", \"FIRSize\"}, 16);\r\n double threshold = configuration.get_double({\"TimeWarp\", \"DVFSManager\", \"Threshold\"}, 0.1);\r\n\r\n DVFSManager::UsefulWorkMetric uwm;\r\n if(metric == \"Rollbacks\")\r\n uwm = DVFSManager::ROLLBACKS;\r\n else if(metric == \"RollbackFraction\")\r\n uwm = DVFSManager::ROLLBACK_FRACTION;\r\n else {\r\n stringstream err;\r\n err << \"DVFSManager: UsefulWorkMetric \" << metric << \" is invalid. \"\r\n << \"Valid metrics are Rollbacks | RollbackFraction. Aborting simulation.\"\r\n << endl;\r\n mySimulationManager->shutdown(err.str());\r\n }\r\n\r\n DVFSManager::Algorithm alg;\r\n if(al == \"Fixed\")\r\n alg = DVFSManager::FIXED;\r\n else if(al == \"Performance\")\r\n alg = DVFSManager::PERFORMANCE;\r\n else if(al == \"Power\")\r\n alg = DVFSManager::POWER;\r\n else if(al == \"Hybrid\")\r\n alg = DVFSManager::HYBRID;\r\n else {\r\n stringstream err;\r\n err << \"DVFSManager: Algorithm \" << al << \" is invalid. \"\r\n << \"Valid options are Fixed | Performance | Power | Hybrid. \"\r\n << \"Aborting simulation.\" << endl;\r\n mySimulationManager->shutdown(err.str());\r\n }\r\n\r\n if(dvfsManagerType == \"Shared\" || dvfsManagerType == \"Distributed\") {\r\n cout << \"(\"\r\n << mySimulationManager->getSimulationManagerID()\r\n << \") configured a \" << dvfsManagerType << \" DVFS Manager\" << endl\r\n << \"Algorithm: \" << al << endl\r\n << \"Period: \" << p << endl\r\n << \"FIR Size: \" << firsize << endl\r\n << \"Useful work metric: \" << metric << endl\r\n << \"Threshold: \" << threshold << endl;\r\n if(dvfsDebugPrint)\r\n cout << \"Writing trace to csv\" << endl;\r\n\r\n if(dvfsManagerType == \"Shared\")\r\n return new SharedDVFSManager(mySimulationManager,\r\n p,\r\n firsize,\r\n alg,\r\n dvfsDebugPrint,\r\n uwm,\r\n threshold);\r\n\r\n return new DistributedDVFSManager(mySimulationManager,\r\n p,\r\n firsize,\r\n alg,\r\n dvfsDebugPrint,\r\n uwm,\r\n threshold);\r\n }\r\n stringstream err;\r\n cerr << \"DVFSManager: invalid type '\" << dvfsManagerType << \"'.\" << endl\r\n << \"Valid types are None | Shared | Distributed. Aborting simulation.\";\r\n mySimulationManager->shutdown(err.str());\r\n}\r\n\r\nconst DVFSManagerFactory *\r\nDVFSManagerFactory::instance(){\r\n static DVFSManagerFactory *singleton = new DVFSManagerFactory();\r\n return singleton;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Helpers for debugging the kernel compiler.\n\/\/ \n\/\/ Copyright (c) 2013 Pekka Jääskeläinen \/ Tampere University of Technology\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 <fstream>\n#include <iostream>\n#include <sstream>\n#include <set>\n\n#include \"CompilerWarnings.h\"\nIGNORE_COMPILER_WARNING(\"-Wunused-parameter\")\n\n#include \"pocl.h\"\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n\n#include \"DebugHelpers.h\"\n#include \"Barrier.h\"\n#include \"Workgroup.h\"\n\nPOP_COMPILER_DIAGS\n\nusing namespace llvm;\n\nnamespace pocl {\n\nstatic std::string getDotBasicBlockID(llvm::BasicBlock* bb) {\n std::ostringstream namess;\n namess << \"BB\" << std::hex << bb;\n return namess.str();\n}\n\nstatic void printBranches(\n llvm::BasicBlock* b, std::ostream& s, bool \/*highlighted*\/) {\n\n llvm::TerminatorInst *term = b->getTerminator();\n for (unsigned i = 0; i < term->getNumSuccessors(); ++i) \n {\n BasicBlock *succ = term->getSuccessor(i);\n s << getDotBasicBlockID(b) << \" -> \" << getDotBasicBlockID(succ) << \";\"\n << std::endl;\n }\n s << std::endl; \n}\n\nstatic void printBasicBlock(\n llvm::BasicBlock* b, std::ostream& s, bool highlighted) {\n \/\/ if (!Barrier::hasBarrier(b)) continue;\n s << getDotBasicBlockID(b);\n s << \"[shape=rect,style=\";\n if (Barrier::hasBarrier(b)) \n s << \"dotted\";\n else \n s << \"solid\";\n \n if (highlighted) {\n s << \",color=red,style=filled\";\n }\n s << \",label=\\\"\" << b->getName().str() << \":\\\\n\";\n\n \/\/ The work-item loop control structures.\n if (b->getName().startswith(\"pregion_for_cond\")) {\n s << \"wi-loop branch\\\\n\";\n } else if (b->getName().startswith(\"pregion_for_inc\")) {\n s << \"local_id_* increment\\\\n\";\n } else if (b->getName().startswith(\"pregion_for_init\")) {\n s << \"wi-loop init\\\\n\";\n } else if (b->getName().startswith(\"pregion_for_end\")) {\n s << \"wi-loop exit\\\\n\";\n } else {\n \/\/ analyze the contents of the BB\n int previousNonBarriers = 0;\n for (llvm::BasicBlock::iterator instr = b->begin();\n instr != b->end(); ++instr) {\n \n if (isa<Barrier>(instr)) {\n s << \"BARRIER\\\\n\";\n previousNonBarriers = 0;\n } else if (isa<BranchInst>(instr)) {\n s << \"branch\\\\n\";\n previousNonBarriers = 0;\n } else if (isa<PHINode>(instr)) {\n s << \"PHI\\\\n\";\n previousNonBarriers = 0;\n } else if (isa<ReturnInst>(instr)) {\n s << \"RETURN\\\\n\";\n previousNonBarriers = 0;\n } else if (isa<UnreachableInst>(instr)) {\n s << \"UNREACHABLE\\\\n\";\n previousNonBarriers = 0;\n } else {\n if (previousNonBarriers == 0) \n s << \"...program instructions...\\\\n\";\n previousNonBarriers++;\n }\n }\n }\n s << \"\\\"\";\n s << \"]\";\n s << \";\" << std::endl << std::endl;\n}\n\n\/**\n * pocl-specific dumping of the LLVM Function as a control flow graph in the\n * Graphviz dot format.\n *\n * @param F the function to dump\n * @param fname the target file name\n * @param regions highlight these parallel regions in the graph\n * @param highlights highlight these basic blocks in the graph\n *\/\nvoid dumpCFG(\n llvm::Function &F, std::string fname, \n ParallelRegion::ParallelRegionVector *regions,\n std::set<llvm::BasicBlock*> *highlights) {\n\n if (fname == \"\")\n fname = std::string(\"pocl_cfg.\") + F.getName().str() + \".dot\";\n\n std::ofstream s;\n s.open(fname.c_str(), std::ios::trunc);\n s << \"digraph \" << F.getName().str() << \" {\" << std::endl;\n\n std::set<BasicBlock*> regionBBs;\n\n if (regions != NULL) {\n\n for (ParallelRegion::ParallelRegionVector::iterator ri = regions->begin(),\n re = regions->end(); ri != re; ++ri) {\n\n ParallelRegion* pr = *ri;\n\n s << \"\\tsubgraph cluster\" << pr->GetID() << \" {\" << std::endl;\n\n for (ParallelRegion::iterator i = pr->begin(), e = pr->end(); \n i != e; ++i) {\n BasicBlock *b = *i;\n printBasicBlock(\n b, s, highlights != NULL && \n highlights->find(b) != highlights->end());\n regionBBs.insert(b);\n }\n s << \"label=\\\"Parallel region #\" << pr->GetID() << \"\\\";\" << std::endl;\n s << \"}\" << std::endl;\n }\n }\n\n for (Function::iterator i = F.begin(), e = F.end(); i != e; ++i) {\n BasicBlock *b = &*i;\n if (regionBBs.find(b) != regionBBs.end()) continue;\n printBasicBlock\n (b, s, highlights != NULL && highlights->find(b) != highlights->end());\n }\n\n for (Function::iterator i = F.begin(), e = F.end(); i != e; ++i) {\n BasicBlock *b = &*i;\n printBranches\n (b, s, highlights != NULL && highlights->find(b) != highlights->end());\n }\n\n s << \"}\" << std::endl;\n s.close();\n std::cout << \"### dumped CFG to \" << fname << std::endl;\n}\n\nbool chopBBs(llvm::Function &F, llvm::Pass &P) {\n bool fchanged = false;\n const int MAX_INSTRUCTIONS_PER_BB = 70;\n do {\n fchanged = false;\n for (Function::iterator i = F.begin(), e = F.end(); i != e; ++i) {\n BasicBlock *b = &*i;\n \n if (b->size() > MAX_INSTRUCTIONS_PER_BB + 1)\n {\n int count = 0;\n BasicBlock::iterator splitPoint = b->begin();\n while (count < MAX_INSTRUCTIONS_PER_BB || isa<PHINode>(splitPoint))\n {\n ++splitPoint;\n ++count;\n }\n#ifdef LLVM_OLDER_THAN_3_7\n SplitBlock(b, splitPoint, &P);\n#else\n SplitBlock(b, &*splitPoint);\n#endif\n fchanged = true;\n break;\n }\n } \n\n } while (fchanged);\n return fchanged;\n}\n \n};\n<commit_msg>debughelpers: Do not overwrite previous dot dumps<commit_after>\/\/ Helpers for debugging the kernel compiler.\n\/\/ \n\/\/ Copyright (c) 2013 Pekka Jääskeläinen \/ Tampere University of Technology\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 <fstream>\n#include <iostream>\n#include <sstream>\n#include <set>\n\n#include \"CompilerWarnings.h\"\nIGNORE_COMPILER_WARNING(\"-Wunused-parameter\")\n\n#include \"pocl.h\"\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n\n#include \"DebugHelpers.h\"\n#include \"Barrier.h\"\n#include \"Workgroup.h\"\n#include \"pocl_file_util.h\"\n\nPOP_COMPILER_DIAGS\n\nusing namespace llvm;\n\nnamespace pocl {\n\nstatic std::string getDotBasicBlockID(llvm::BasicBlock* bb) {\n std::ostringstream namess;\n namess << \"BB\" << std::hex << bb;\n return namess.str();\n}\n\nstatic void printBranches(\n llvm::BasicBlock* b, std::ostream& s, bool \/*highlighted*\/) {\n\n llvm::TerminatorInst *term = b->getTerminator();\n for (unsigned i = 0; i < term->getNumSuccessors(); ++i) \n {\n BasicBlock *succ = term->getSuccessor(i);\n s << getDotBasicBlockID(b) << \" -> \" << getDotBasicBlockID(succ) << \";\"\n << std::endl;\n }\n s << std::endl; \n}\n\nstatic void printBasicBlock(\n llvm::BasicBlock* b, std::ostream& s, bool highlighted) {\n \/\/ if (!Barrier::hasBarrier(b)) continue;\n s << getDotBasicBlockID(b);\n s << \"[shape=rect,style=\";\n if (Barrier::hasBarrier(b)) \n s << \"dotted\";\n else \n s << \"solid\";\n \n if (highlighted) {\n s << \",color=red,style=filled\";\n }\n s << \",label=\\\"\" << b->getName().str() << \":\\\\n\";\n\n \/\/ The work-item loop control structures.\n if (b->getName().startswith(\"pregion_for_cond\")) {\n s << \"wi-loop branch\\\\n\";\n } else if (b->getName().startswith(\"pregion_for_inc\")) {\n s << \"local_id_* increment\\\\n\";\n } else if (b->getName().startswith(\"pregion_for_init\")) {\n s << \"wi-loop init\\\\n\";\n } else if (b->getName().startswith(\"pregion_for_end\")) {\n s << \"wi-loop exit\\\\n\";\n } else {\n \/\/ analyze the contents of the BB\n int previousNonBarriers = 0;\n for (llvm::BasicBlock::iterator instr = b->begin();\n instr != b->end(); ++instr) {\n \n if (isa<Barrier>(instr)) {\n s << \"BARRIER\\\\n\";\n previousNonBarriers = 0;\n } else if (isa<BranchInst>(instr)) {\n s << \"branch\\\\n\";\n previousNonBarriers = 0;\n } else if (isa<PHINode>(instr)) {\n s << \"PHI\\\\n\";\n previousNonBarriers = 0;\n } else if (isa<ReturnInst>(instr)) {\n s << \"RETURN\\\\n\";\n previousNonBarriers = 0;\n } else if (isa<UnreachableInst>(instr)) {\n s << \"UNREACHABLE\\\\n\";\n previousNonBarriers = 0;\n } else {\n if (previousNonBarriers == 0) \n s << \"...program instructions...\\\\n\";\n previousNonBarriers++;\n }\n }\n }\n s << \"\\\"\";\n s << \"]\";\n s << \";\" << std::endl << std::endl;\n}\n\n\/**\n * pocl-specific dumping of the LLVM Function as a control flow graph in the\n * Graphviz dot format.\n *\n * @param F the function to dump\n * @param fname the target file name\n * @param regions highlight these parallel regions in the graph\n * @param highlights highlight these basic blocks in the graph\n *\/\nvoid dumpCFG(\n llvm::Function &F, std::string fname, \n ParallelRegion::ParallelRegionVector *regions,\n std::set<llvm::BasicBlock*> *highlights) {\n\n if (fname == \"\")\n fname = std::string(\"pocl_cfg.\") + F.getName().str() + \".dot\";\n\n std::string origName = fname;\n int counter = 0;\n while (pocl_exists (fname.c_str())) {\n std::ostringstream ss;\n ss << origName << \".\" << counter;\n fname = ss.str();\n ++counter;\n }\n\n std::ofstream s;\n s.open(fname.c_str(), std::ios::trunc);\n s << \"digraph \" << F.getName().str() << \" {\" << std::endl;\n\n std::set<BasicBlock*> regionBBs;\n\n if (regions != NULL) {\n\n for (ParallelRegion::ParallelRegionVector::iterator ri = regions->begin(),\n re = regions->end(); ri != re; ++ri) {\n\n ParallelRegion* pr = *ri;\n\n s << \"\\tsubgraph cluster\" << pr->GetID() << \" {\" << std::endl;\n\n for (ParallelRegion::iterator i = pr->begin(), e = pr->end(); \n i != e; ++i) {\n BasicBlock *b = *i;\n printBasicBlock(\n b, s, highlights != NULL && \n highlights->find(b) != highlights->end());\n regionBBs.insert(b);\n }\n s << \"label=\\\"Parallel region #\" << pr->GetID() << \"\\\";\" << std::endl;\n s << \"}\" << std::endl;\n }\n }\n\n for (Function::iterator i = F.begin(), e = F.end(); i != e; ++i) {\n BasicBlock *b = &*i;\n if (regionBBs.find(b) != regionBBs.end()) continue;\n printBasicBlock\n (b, s, highlights != NULL && highlights->find(b) != highlights->end());\n }\n\n for (Function::iterator i = F.begin(), e = F.end(); i != e; ++i) {\n BasicBlock *b = &*i;\n printBranches\n (b, s, highlights != NULL && highlights->find(b) != highlights->end());\n }\n\n s << \"}\" << std::endl;\n s.close();\n std::cout << \"### dumped CFG to \" << fname << std::endl;\n}\n\nbool chopBBs(llvm::Function &F, llvm::Pass &P) {\n bool fchanged = false;\n const int MAX_INSTRUCTIONS_PER_BB = 70;\n do {\n fchanged = false;\n for (Function::iterator i = F.begin(), e = F.end(); i != e; ++i) {\n BasicBlock *b = &*i;\n \n if (b->size() > MAX_INSTRUCTIONS_PER_BB + 1)\n {\n int count = 0;\n BasicBlock::iterator splitPoint = b->begin();\n while (count < MAX_INSTRUCTIONS_PER_BB || isa<PHINode>(splitPoint))\n {\n ++splitPoint;\n ++count;\n }\n#ifdef LLVM_OLDER_THAN_3_7\n SplitBlock(b, splitPoint, &P);\n#else\n SplitBlock(b, &*splitPoint);\n#endif\n fchanged = true;\n break;\n }\n } \n\n } while (fchanged);\n return fchanged;\n}\n \n};\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- sanitizer_flags_test.cc -------------------------------------------===\/\/\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\/\/ This file is a part of ThreadSanitizer\/AddressSanitizer runtime.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"sanitizer_common\/sanitizer_common.h\"\n#include \"sanitizer_common\/sanitizer_flags.h\"\n#include \"sanitizer_common\/sanitizer_flag_parser.h\"\n#include \"sanitizer_common\/sanitizer_libc.h\"\n#include \"sanitizer_common\/sanitizer_allocator_internal.h\"\n#include \"gtest\/gtest.h\"\n\n#include <string.h>\n\nnamespace __sanitizer {\n\nstatic const char kFlagName[] = \"flag_name\";\nstatic const char kFlagDesc[] = \"flag description\";\n\ntemplate <typename T>\nstatic void TestFlag(T start_value, const char *env, T final_value) {\n T flag = start_value;\n\n FlagParser parser;\n RegisterFlag(&parser, kFlagName, kFlagDesc, &flag);\n\n parser.ParseString(env);\n\n EXPECT_EQ(final_value, flag);\n}\n\ntemplate <>\nvoid TestFlag(const char *start_value, const char *env,\n const char *final_value) {\n const char *flag = start_value;\n\n FlagParser parser;\n RegisterFlag(&parser, kFlagName, kFlagDesc, &flag);\n\n parser.ParseString(env);\n\n EXPECT_EQ(0, internal_strcmp(final_value, flag));\n}\n\nTEST(SanitizerCommon, BooleanFlags) {\n TestFlag(false, \"flag_name=1\", true);\n TestFlag(false, \"flag_name=yes\", true);\n TestFlag(false, \"flag_name=true\", true);\n TestFlag(true, \"flag_name=0\", false);\n TestFlag(true, \"flag_name=no\", false);\n TestFlag(true, \"flag_name=false\", false);\n}\n\nTEST(SanitizerCommon, IntFlags) {\n TestFlag(-11, 0, -11);\n TestFlag(-11, \"flag_name=0\", 0);\n TestFlag(-11, \"flag_name=42\", 42);\n TestFlag(-11, \"flag_name=-42\", -42);\n\n \/\/ Unrecognized flags are ignored.\n TestFlag(-11, \"--flag_name=42\", -11);\n TestFlag(-11, \"zzzzzzz=42\", -11);\n\n EXPECT_DEATH(TestFlag(-11, \"flag_name\", 0), \"expected '='\");\n EXPECT_DEATH(TestFlag(-11, \"flag_name=42U\", 0),\n \"Invalid value for int option\");\n}\n\nTEST(SanitizerCommon, StrFlags) {\n TestFlag(\"zzz\", 0, \"zzz\");\n TestFlag(\"zzz\", \"flag_name=\", \"\");\n TestFlag(\"zzz\", \"flag_name=abc\", \"abc\");\n TestFlag(\"\", \"flag_name=abc\", \"abc\");\n TestFlag(\"\", \"flag_name='abc zxc'\", \"abc zxc\");\n \/\/ TestStrFlag(\"\", \"flag_name=\\\"abc qwe\\\" asd\", \"abc qwe\");\n}\n\nstatic void TestTwoFlags(const char *env, bool expected_flag1,\n const char *expected_flag2,\n const char *name1 = \"flag1\",\n const char *name2 = \"flag2\") {\n bool flag1 = !expected_flag1;\n const char *flag2 = \"\";\n\n FlagParser parser;\n RegisterFlag(&parser, name1, kFlagDesc, &flag1);\n RegisterFlag(&parser, name2, kFlagDesc, &flag2);\n\n parser.ParseString(env);\n\n EXPECT_EQ(expected_flag1, flag1);\n EXPECT_EQ(0, internal_strcmp(flag2, expected_flag2));\n}\n\nTEST(SanitizerCommon, MultipleFlags) {\n TestTwoFlags(\"flag1=1 flag2='zzz'\", true, \"zzz\");\n TestTwoFlags(\"flag2='qxx' flag1=0\", false, \"qxx\");\n TestTwoFlags(\"flag1=false:flag2='zzz'\", false, \"zzz\");\n TestTwoFlags(\"flag2=qxx:flag1=yes\", true, \"qxx\");\n TestTwoFlags(\"flag2=qxx\\nflag1=yes\", true, \"qxx\");\n TestTwoFlags(\"flag2=qxx\\r\\nflag1=yes\", true, \"qxx\");\n TestTwoFlags(\"flag2=qxx\\tflag1=yes\", true, \"qxx\");\n}\n\nTEST(SanitizerCommon, CommonSuffixFlags) {\n TestTwoFlags(\"flag=1 other_flag='zzz'\", true, \"zzz\", \"flag\", \"other_flag\");\n TestTwoFlags(\"other_flag='zzz' flag=1\", true, \"zzz\", \"flag\", \"other_flag\");\n TestTwoFlags(\"other_flag=' flag=0 ' flag=1\", true, \" flag=0 \", \"flag\",\n \"other_flag\");\n TestTwoFlags(\"flag=1 other_flag=' flag=0 '\", true, \" flag=0 \", \"flag\",\n \"other_flag\");\n}\n\nTEST(SanitizerCommon, CommonFlags) {\n CommonFlags cf;\n FlagParser parser;\n RegisterCommonFlags(&parser, &cf);\n\n cf.SetDefaults();\n EXPECT_TRUE(cf.symbolize);\n EXPECT_STREQ(\".\", cf.coverage_dir);\n\n cf.symbolize = false;\n cf.coverage = true;\n cf.coverage_direct = true;\n cf.log_path = \"path\/one\";\n\n parser.ParseString(\"symbolize=1:coverage_direct=false log_path='path\/two'\");\n EXPECT_TRUE(cf.symbolize);\n EXPECT_TRUE(cf.coverage);\n EXPECT_FALSE(cf.coverage_direct);\n EXPECT_STREQ(\"path\/two\", cf.log_path);\n}\n\n} \/\/ namespace __sanitizer\n<commit_msg>[compiler-rt] Fix broken (flaky) unittests based on FlagParser.<commit_after>\/\/===-- sanitizer_flags_test.cc -------------------------------------------===\/\/\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\/\/ This file is a part of ThreadSanitizer\/AddressSanitizer runtime.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"sanitizer_common\/sanitizer_common.h\"\n#include \"sanitizer_common\/sanitizer_flags.h\"\n#include \"sanitizer_common\/sanitizer_flag_parser.h\"\n#include \"sanitizer_common\/sanitizer_libc.h\"\n#include \"sanitizer_common\/sanitizer_allocator_internal.h\"\n#include \"gtest\/gtest.h\"\n\n#include <string.h>\n\nnamespace __sanitizer {\n\nstatic const char kFlagName[] = \"flag_name\";\nstatic const char kFlagDesc[] = \"flag description\";\n\ntemplate <typename T>\nstatic void TestFlag(T start_value, const char *env, T final_value) {\n T flag = start_value;\n\n FlagParser parser;\n RegisterFlag(&parser, kFlagName, kFlagDesc, &flag);\n\n parser.ParseString(env);\n\n EXPECT_EQ(final_value, flag);\n}\n\ntemplate <>\nvoid TestFlag(const char *start_value, const char *env,\n const char *final_value) {\n const char *flag = start_value;\n\n FlagParser parser;\n RegisterFlag(&parser, kFlagName, kFlagDesc, &flag);\n\n parser.ParseString(env);\n\n EXPECT_EQ(0, internal_strcmp(final_value, flag));\n\n \/\/ Reporting unrecognized flags is needed to reset them.\n ReportUnrecognizedFlags();\n}\n\nTEST(SanitizerCommon, BooleanFlags) {\n TestFlag(false, \"flag_name=1\", true);\n TestFlag(false, \"flag_name=yes\", true);\n TestFlag(false, \"flag_name=true\", true);\n TestFlag(true, \"flag_name=0\", false);\n TestFlag(true, \"flag_name=no\", false);\n TestFlag(true, \"flag_name=false\", false);\n}\n\nTEST(SanitizerCommon, IntFlags) {\n TestFlag(-11, 0, -11);\n TestFlag(-11, \"flag_name=0\", 0);\n TestFlag(-11, \"flag_name=42\", 42);\n TestFlag(-11, \"flag_name=-42\", -42);\n\n \/\/ Unrecognized flags are ignored.\n TestFlag(-11, \"--flag_name=42\", -11);\n TestFlag(-11, \"zzzzzzz=42\", -11);\n\n EXPECT_DEATH(TestFlag(-11, \"flag_name\", 0), \"expected '='\");\n EXPECT_DEATH(TestFlag(-11, \"flag_name=42U\", 0),\n \"Invalid value for int option\");\n}\n\nTEST(SanitizerCommon, StrFlags) {\n TestFlag(\"zzz\", 0, \"zzz\");\n TestFlag(\"zzz\", \"flag_name=\", \"\");\n TestFlag(\"zzz\", \"flag_name=abc\", \"abc\");\n TestFlag(\"\", \"flag_name=abc\", \"abc\");\n TestFlag(\"\", \"flag_name='abc zxc'\", \"abc zxc\");\n \/\/ TestStrFlag(\"\", \"flag_name=\\\"abc qwe\\\" asd\", \"abc qwe\");\n}\n\nstatic void TestTwoFlags(const char *env, bool expected_flag1,\n const char *expected_flag2,\n const char *name1 = \"flag1\",\n const char *name2 = \"flag2\") {\n bool flag1 = !expected_flag1;\n const char *flag2 = \"\";\n\n FlagParser parser;\n RegisterFlag(&parser, name1, kFlagDesc, &flag1);\n RegisterFlag(&parser, name2, kFlagDesc, &flag2);\n\n parser.ParseString(env);\n\n EXPECT_EQ(expected_flag1, flag1);\n EXPECT_EQ(0, internal_strcmp(flag2, expected_flag2));\n\n \/\/ Reporting unrecognized flags is needed to reset them.\n ReportUnrecognizedFlags();\n}\n\nTEST(SanitizerCommon, MultipleFlags) {\n TestTwoFlags(\"flag1=1 flag2='zzz'\", true, \"zzz\");\n TestTwoFlags(\"flag2='qxx' flag1=0\", false, \"qxx\");\n TestTwoFlags(\"flag1=false:flag2='zzz'\", false, \"zzz\");\n TestTwoFlags(\"flag2=qxx:flag1=yes\", true, \"qxx\");\n TestTwoFlags(\"flag2=qxx\\nflag1=yes\", true, \"qxx\");\n TestTwoFlags(\"flag2=qxx\\r\\nflag1=yes\", true, \"qxx\");\n TestTwoFlags(\"flag2=qxx\\tflag1=yes\", true, \"qxx\");\n}\n\nTEST(SanitizerCommon, CommonSuffixFlags) {\n TestTwoFlags(\"flag=1 other_flag='zzz'\", true, \"zzz\", \"flag\", \"other_flag\");\n TestTwoFlags(\"other_flag='zzz' flag=1\", true, \"zzz\", \"flag\", \"other_flag\");\n TestTwoFlags(\"other_flag=' flag=0 ' flag=1\", true, \" flag=0 \", \"flag\",\n \"other_flag\");\n TestTwoFlags(\"flag=1 other_flag=' flag=0 '\", true, \" flag=0 \", \"flag\",\n \"other_flag\");\n}\n\nTEST(SanitizerCommon, CommonFlags) {\n CommonFlags cf;\n FlagParser parser;\n RegisterCommonFlags(&parser, &cf);\n\n cf.SetDefaults();\n EXPECT_TRUE(cf.symbolize);\n EXPECT_STREQ(\".\", cf.coverage_dir);\n\n cf.symbolize = false;\n cf.coverage = true;\n cf.coverage_direct = true;\n cf.log_path = \"path\/one\";\n\n parser.ParseString(\"symbolize=1:coverage_direct=false log_path='path\/two'\");\n EXPECT_TRUE(cf.symbolize);\n EXPECT_TRUE(cf.coverage);\n EXPECT_FALSE(cf.coverage_direct);\n EXPECT_STREQ(\"path\/two\", cf.log_path);\n}\n\n} \/\/ namespace __sanitizer\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- sanitizer_ioctl_test.cc -------------------------------------------===\/\/\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\/\/ Tests for ioctl interceptor implementation in sanitizer_common.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_common\/sanitizer_platform.h\"\n#if SANITIZER_LINUX\n\n#include <linux\/input.h>\n#include <vector>\n\n#include \"interception\/interception.h\"\n#include \"sanitizer_test_utils.h\"\n#include \"sanitizer_common\/sanitizer_platform_limits_posix.h\"\n#include \"sanitizer_common\/sanitizer_common.h\"\n#include \"gtest\/gtest.h\"\n\n\nusing namespace __sanitizer;\n\n#define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, sz) \\\n do { \\\n (void) ctx; \\\n (void) ptr; \\\n (void) sz; \\\n } while (0)\n#define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, sz) \\\n do { \\\n (void) ctx; \\\n (void) ptr; \\\n (void) sz; \\\n } while (0)\n\n#include \"sanitizer_common\/sanitizer_common_interceptors_ioctl.inc\"\n\nstatic struct IoctlInit {\n IoctlInit() {\n ioctl_init();\n \/\/ Avoid unused function warnings.\n (void)&ioctl_common_pre;\n (void)&ioctl_common_post;\n }\n} ioctl_static_initializer;\n\nTEST(SanitizerIoctl, Fixup) {\n EXPECT_EQ((unsigned)FIONBIO, ioctl_request_fixup(FIONBIO));\n\n EXPECT_EQ(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(0, 16)));\n EXPECT_EQ(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(1, 16)));\n EXPECT_EQ(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(1, 17)));\n EXPECT_EQ(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(31, 16)));\n EXPECT_NE(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(32, 16)));\n\n EXPECT_EQ(EVIOCGABS(0), ioctl_request_fixup(EVIOCGABS(0)));\n EXPECT_EQ(EVIOCGABS(0), ioctl_request_fixup(EVIOCGABS(5)));\n EXPECT_EQ(EVIOCGABS(0), ioctl_request_fixup(EVIOCGABS(63)));\n EXPECT_NE(EVIOCGABS(0), ioctl_request_fixup(EVIOCGABS(64)));\n\n EXPECT_EQ(EVIOCSABS(0), ioctl_request_fixup(EVIOCSABS(0)));\n EXPECT_EQ(EVIOCSABS(0), ioctl_request_fixup(EVIOCSABS(5)));\n EXPECT_EQ(EVIOCSABS(0), ioctl_request_fixup(EVIOCSABS(63)));\n EXPECT_NE(EVIOCSABS(0), ioctl_request_fixup(EVIOCSABS(64)));\n\n const ioctl_desc *desc = ioctl_lookup(EVIOCGKEY(16));\n EXPECT_NE((void *)0, desc);\n EXPECT_EQ(EVIOCGKEY(0), desc->req);\n}\n\n#endif \/\/ SANITIZER_LINUX\n<commit_msg>[sanitizer] Fix build.<commit_after>\/\/===-- sanitizer_ioctl_test.cc -------------------------------------------===\/\/\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\/\/ Tests for ioctl interceptor implementation in sanitizer_common.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_common\/sanitizer_platform.h\"\n#if SANITIZER_LINUX\n\n#include <linux\/input.h>\n#include <vector>\n\n#include \"interception\/interception.h\"\n#include \"sanitizer_test_utils.h\"\n#include \"sanitizer_common\/sanitizer_platform_limits_posix.h\"\n#include \"sanitizer_common\/sanitizer_common.h\"\n#include \"gtest\/gtest.h\"\n\n\nusing namespace __sanitizer;\n\n#define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, sz) \\\n do { \\\n (void) ctx; \\\n (void) ptr; \\\n (void) sz; \\\n } while (0)\n#define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, sz) \\\n do { \\\n (void) ctx; \\\n (void) ptr; \\\n (void) sz; \\\n } while (0)\n\n#include \"sanitizer_common\/sanitizer_common_interceptors_ioctl.inc\"\n\nstatic struct IoctlInit {\n IoctlInit() {\n ioctl_init();\n \/\/ Avoid unused function warnings.\n (void)&ioctl_common_pre;\n (void)&ioctl_common_post;\n (void)&ioctl_decode;\n }\n} ioctl_static_initializer;\n\nTEST(SanitizerIoctl, Fixup) {\n EXPECT_EQ((unsigned)FIONBIO, ioctl_request_fixup(FIONBIO));\n\n EXPECT_EQ(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(0, 16)));\n EXPECT_EQ(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(1, 16)));\n EXPECT_EQ(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(1, 17)));\n EXPECT_EQ(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(31, 16)));\n EXPECT_NE(EVIOCGBIT(0, 0), ioctl_request_fixup(EVIOCGBIT(32, 16)));\n\n EXPECT_EQ(EVIOCGABS(0), ioctl_request_fixup(EVIOCGABS(0)));\n EXPECT_EQ(EVIOCGABS(0), ioctl_request_fixup(EVIOCGABS(5)));\n EXPECT_EQ(EVIOCGABS(0), ioctl_request_fixup(EVIOCGABS(63)));\n EXPECT_NE(EVIOCGABS(0), ioctl_request_fixup(EVIOCGABS(64)));\n\n EXPECT_EQ(EVIOCSABS(0), ioctl_request_fixup(EVIOCSABS(0)));\n EXPECT_EQ(EVIOCSABS(0), ioctl_request_fixup(EVIOCSABS(5)));\n EXPECT_EQ(EVIOCSABS(0), ioctl_request_fixup(EVIOCSABS(63)));\n EXPECT_NE(EVIOCSABS(0), ioctl_request_fixup(EVIOCSABS(64)));\n\n const ioctl_desc *desc = ioctl_lookup(EVIOCGKEY(16));\n EXPECT_NE((void *)0, desc);\n EXPECT_EQ(EVIOCGKEY(0), desc->req);\n}\n\n#endif \/\/ SANITIZER_LINUX\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Author(s):\n** - Herve Cuche <hcuche@aldebaran-robotics.com>\n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include <iostream>\n#include <cstring>\n#include <map>\n#include <stdint.h>\n\n#include <event2\/util.h>\n#include <event2\/event.h>\n#include <event2\/buffer.h>\n#include <event2\/bufferevent.h>\n#include <boost\/thread.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#include \"src\/transport_socket_p.hpp\"\n#include \"src\/transport_socket_libevent_p.hpp\"\n#include \"src\/network_thread.hpp\"\n#include \"src\/message_p.hpp\"\n#include \"src\/buffer_p.hpp\"\n#include \"src\/session_p.hpp\"\n\n#include <qi\/log.hpp>\n#include <qimessaging\/session.hpp>\n#include <qimessaging\/message.hpp>\n#include <qimessaging\/datastream.hpp>\n#include <qimessaging\/buffer.hpp>\n\n#define MAX_LINE 16384\n\nnamespace qi\n{\n static void readcb(struct bufferevent *bev,\n void *context)\n {\n TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);\n tc->readcb(bev, context);\n }\n\n static void writecb(struct bufferevent* bev,\n void* context)\n {\n TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);\n tc->writecb(bev, context);\n }\n\n\n static void eventcb(struct bufferevent *bev,\n short error,\n void *context)\n {\n TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);\n tc->eventcb(bev, error, context);\n }\n\n\n void TransportSocketLibEvent::readcb(struct bufferevent *bev,\n void *QI_UNUSED(context))\n {\n struct evbuffer *input = bufferevent_get_input(bev);\n\n while (true)\n {\n if (msg == NULL)\n {\n msg = new qi::Message();\n readHdr = true;\n }\n\n if (readHdr)\n {\n if (evbuffer_get_length(input) < sizeof(MessagePrivate::MessageHeader))\n return;\n\n evbuffer_remove(input,\n msg->_p->getHeader(),\n sizeof(MessagePrivate::MessageHeader));\n readHdr = false;\n }\n\n if (evbuffer_get_length(input) <\n static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size)\n return;\n\n \/* we have to let the Buffer know we are going to push some data inside *\/\n qi::Buffer buf;\n buf.reserve(static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size);\n msg->setBuffer(buf);\n\n evbuffer_remove(input,\n buf.data(),\n buf.size());\n assert(msg->isValid());\n\n {\n boost::mutex::scoped_lock l(mtx);\n msgSend[msg->id()] = msg;\n cond.notify_all();\n }\n if (tcd)\n tcd->onSocketReadyRead(self, msg->id());\n\n msg = NULL;\n }\n }\n\n\n void TransportSocketLibEvent::writecb(struct bufferevent *QI_UNUSED(bev),\n void *QI_UNUSED(context))\n {\n if (tcd)\n tcd->onSocketWriteDone(self);\n }\n\n void TransportSocketLibEvent::eventcb(struct bufferevent *bev,\n short events,\n void *QI_UNUSED(context))\n {\n if (events & BEV_EVENT_CONNECTED)\n {\n connected = true;\n if (tcd)\n tcd->onSocketConnected(self);\n }\n else if ((events & BEV_EVENT_EOF) || (events & BEV_EVENT_ERROR))\n {\n bufferevent_free(bev);\n bev = 0;\n bool wasco = connected;\n connected = false;\n \/\/for waitForId\n cond.notify_all();\n\n if (tcd)\n tcd->onSocketConnectionError(self);\n if (wasco && tcd)\n tcd->onSocketDisconnected(self);\n\n \/\/ check errno to see what error occurred\n qiLogVerbose(\"qimessaging.TransportSocketLibevent\") << \"socket terminate (\" << errno << \"): \" << strerror(errno) << std::endl;\n }\n else if (events & BEV_EVENT_TIMEOUT)\n {\n \/\/ must be a timeout event handle, handle it\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"must be a timeout event handle, handle it\" << std::endl;\n }\n }\n\n TransportSocketLibEvent::TransportSocketLibEvent(TransportSocket *socket)\n : TransportSocketPrivate(socket)\n , bev(NULL)\n , fd(-1)\n {\n }\n\n TransportSocketLibEvent::TransportSocketLibEvent(TransportSocket *socket, int fileDesc, void *data)\n : TransportSocketPrivate(socket)\n , bev(NULL)\n , fd(fileDesc)\n {\n struct event_base *base = static_cast<event_base *>(data);\n bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);\n bufferevent_setcb(bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this);\n bufferevent_setwatermark(bev, EV_WRITE, 0, MAX_LINE);\n bufferevent_enable(bev, EV_READ|EV_WRITE);\n connected = true;\n }\n\n TransportSocketLibEvent::~TransportSocketLibEvent()\n {\n if (isConnected())\n disconnect();\n }\n\n void TransportSocketLibEvent::onBufferSent(const void *QI_UNUSED(data),\n size_t QI_UNUSED(datalen),\n void *buffer)\n {\n Buffer *b = static_cast<Buffer *>(buffer);\n delete b;\n }\n\n void TransportSocketLibEvent::onMessageSent(const void *QI_UNUSED(data),\n size_t QI_UNUSED(datalen),\n void *msg)\n {\n Message *m = static_cast<Message *>(msg);\n delete m;\n }\n\n bool TransportSocketLibEvent::connect(qi::Session *session,\n const qi::Url &url)\n {\n const std::string &address = url.host();\n struct evutil_addrinfo *ai = NULL;\n int err;\n struct evutil_addrinfo hint;\n char portbuf[10];\n\n qiLogVerbose(\"qimessaging.transportsocket.connect\") << \"Trying to connect to \" << url.host() << \":\" << url.port();\n if (!isConnected())\n {\n bev = bufferevent_socket_new(session->_p->_networkThread->getEventBase(), -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);\n bufferevent_setcb(bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this);\n bufferevent_setwatermark(bev, EV_WRITE, 0, MAX_LINE);\n bufferevent_enable(bev, EV_READ|EV_WRITE);\n\n evutil_snprintf(portbuf, sizeof(portbuf), \"%d\", url.port());\n memset(&hint, 0, sizeof(hint));\n hint.ai_family = AF_UNSPEC;\n hint.ai_protocol = IPPROTO_TCP;\n hint.ai_socktype = SOCK_STREAM;\n err = evutil_getaddrinfo(address.c_str(), portbuf, &hint, &ai);\n if (err != 0)\n {\n qiLogError(\"qimessaging.TransportSocketLibEvent\") << \"Cannot resolve dns (\" << address << \")\";\n return (false);\n }\n\n int result = bufferevent_socket_connect(bev, ai->ai_addr, ai->ai_addrlen);\n\n if (result == 0)\n return true;\n\n return false;\n }\n else\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"socket is already connected.\";\n }\n\n return false;\n }\n\n void TransportSocketLibEvent::disconnect()\n {\n if (isConnected())\n {\n bufferevent_free(bev);\n bev = NULL;\n connected = false;\n }\n else\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"socket is not connected.\";\n }\n }\n\n bool TransportSocketLibEvent::send(const qi::Message &msg)\n {\n if (!isConnected())\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"socket is not connected.\";\n return false;\n }\n\n qi::Message *m = new qi::Message();\n *m = msg;\n m->_p->complete();\n assert(m->isValid());\n\n struct evbuffer *evb = bufferevent_get_output(bev);\n\n \/\/ m might be deleted.\n qi::Buffer *b = new qi::Buffer(m->buffer());\n\n if (evbuffer_add_reference(evb,\n m->_p->getHeader(),\n sizeof(qi::MessagePrivate::MessageHeader),\n qi::TransportSocketLibEvent::onMessageSent,\n static_cast<void *>(m)) != 0)\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"Add reference fail in header\";\n delete m;\n delete b;\n return false;\n }\n size_t sz = b->size();\n if (sz) {\n if (evbuffer_add_reference(evb,\n b->data(),\n sz,\n qi::TransportSocketLibEvent::onBufferSent,\n static_cast<void *>(b)) != 0)\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"Add reference fail for block of size \" << sz;\n delete b;\n return false;\n }\n }\n else {\n delete b;\n }\n\n if (bufferevent_write_buffer(bev, evb) != 0)\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"Can't add buffer to the send queue\";\n evbuffer_drain(evb, sizeof(qi::MessagePrivate::MessageHeader) + sz);\n return false;\n }\n\n return true;\n }\n}\n\n<commit_msg>Fix invlid read of message id in libevent backend<commit_after>\/*\n** Author(s):\n** - Herve Cuche <hcuche@aldebaran-robotics.com>\n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include <iostream>\n#include <cstring>\n#include <map>\n#include <stdint.h>\n\n#include <event2\/util.h>\n#include <event2\/event.h>\n#include <event2\/buffer.h>\n#include <event2\/bufferevent.h>\n#include <boost\/thread.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#include \"src\/transport_socket_p.hpp\"\n#include \"src\/transport_socket_libevent_p.hpp\"\n#include \"src\/network_thread.hpp\"\n#include \"src\/message_p.hpp\"\n#include \"src\/buffer_p.hpp\"\n#include \"src\/session_p.hpp\"\n\n#include <qi\/log.hpp>\n#include <qimessaging\/session.hpp>\n#include <qimessaging\/message.hpp>\n#include <qimessaging\/datastream.hpp>\n#include <qimessaging\/buffer.hpp>\n\n#define MAX_LINE 16384\n\nnamespace qi\n{\n static void readcb(struct bufferevent *bev,\n void *context)\n {\n TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);\n tc->readcb(bev, context);\n }\n\n static void writecb(struct bufferevent* bev,\n void* context)\n {\n TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);\n tc->writecb(bev, context);\n }\n\n\n static void eventcb(struct bufferevent *bev,\n short error,\n void *context)\n {\n TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);\n tc->eventcb(bev, error, context);\n }\n\n\n void TransportSocketLibEvent::readcb(struct bufferevent *bev,\n void *QI_UNUSED(context))\n {\n struct evbuffer *input = bufferevent_get_input(bev);\n int msgId = 0;\n\n while (true)\n {\n if (msg == NULL)\n {\n msg = new qi::Message();\n readHdr = true;\n }\n\n if (readHdr)\n {\n if (evbuffer_get_length(input) < sizeof(MessagePrivate::MessageHeader))\n return;\n\n evbuffer_remove(input,\n msg->_p->getHeader(),\n sizeof(MessagePrivate::MessageHeader));\n readHdr = false;\n }\n\n if (evbuffer_get_length(input) <\n static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size)\n return;\n\n \/* we have to let the Buffer know we are going to push some data inside *\/\n qi::Buffer buf;\n buf.reserve(static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size);\n msg->setBuffer(buf);\n\n evbuffer_remove(input,\n buf.data(),\n buf.size());\n assert(msg->isValid());\n\n {\n boost::mutex::scoped_lock l(mtx);\n msgSend[msg->id()] = msg;\n msgId = msg->id();\n msg = NULL;\n cond.notify_all();\n }\n if (tcd)\n tcd->onSocketReadyRead(self, msgId);\n\n }\n }\n\n\n void TransportSocketLibEvent::writecb(struct bufferevent *QI_UNUSED(bev),\n void *QI_UNUSED(context))\n {\n if (tcd)\n tcd->onSocketWriteDone(self);\n }\n\n void TransportSocketLibEvent::eventcb(struct bufferevent *bev,\n short events,\n void *QI_UNUSED(context))\n {\n if (events & BEV_EVENT_CONNECTED)\n {\n connected = true;\n if (tcd)\n tcd->onSocketConnected(self);\n }\n else if ((events & BEV_EVENT_EOF) || (events & BEV_EVENT_ERROR))\n {\n bufferevent_free(bev);\n bev = 0;\n bool wasco = connected;\n connected = false;\n \/\/for waitForId\n cond.notify_all();\n\n if (tcd)\n tcd->onSocketConnectionError(self);\n if (wasco && tcd)\n tcd->onSocketDisconnected(self);\n\n \/\/ check errno to see what error occurred\n qiLogVerbose(\"qimessaging.TransportSocketLibevent\") << \"socket terminate (\" << errno << \"): \" << strerror(errno) << std::endl;\n }\n else if (events & BEV_EVENT_TIMEOUT)\n {\n \/\/ must be a timeout event handle, handle it\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"must be a timeout event handle, handle it\" << std::endl;\n }\n }\n\n TransportSocketLibEvent::TransportSocketLibEvent(TransportSocket *socket)\n : TransportSocketPrivate(socket)\n , bev(NULL)\n , fd(-1)\n {\n }\n\n TransportSocketLibEvent::TransportSocketLibEvent(TransportSocket *socket, int fileDesc, void *data)\n : TransportSocketPrivate(socket)\n , bev(NULL)\n , fd(fileDesc)\n {\n struct event_base *base = static_cast<event_base *>(data);\n bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);\n bufferevent_setcb(bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this);\n bufferevent_setwatermark(bev, EV_WRITE, 0, MAX_LINE);\n bufferevent_enable(bev, EV_READ|EV_WRITE);\n connected = true;\n }\n\n TransportSocketLibEvent::~TransportSocketLibEvent()\n {\n if (isConnected())\n disconnect();\n }\n\n void TransportSocketLibEvent::onBufferSent(const void *QI_UNUSED(data),\n size_t QI_UNUSED(datalen),\n void *buffer)\n {\n Buffer *b = static_cast<Buffer *>(buffer);\n delete b;\n }\n\n void TransportSocketLibEvent::onMessageSent(const void *QI_UNUSED(data),\n size_t QI_UNUSED(datalen),\n void *msg)\n {\n Message *m = static_cast<Message *>(msg);\n delete m;\n }\n\n bool TransportSocketLibEvent::connect(qi::Session *session,\n const qi::Url &url)\n {\n const std::string &address = url.host();\n struct evutil_addrinfo *ai = NULL;\n int err;\n struct evutil_addrinfo hint;\n char portbuf[10];\n\n qiLogVerbose(\"qimessaging.transportsocket.connect\") << \"Trying to connect to \" << url.host() << \":\" << url.port();\n if (!isConnected())\n {\n bev = bufferevent_socket_new(session->_p->_networkThread->getEventBase(), -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);\n bufferevent_setcb(bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this);\n bufferevent_setwatermark(bev, EV_WRITE, 0, MAX_LINE);\n bufferevent_enable(bev, EV_READ|EV_WRITE);\n\n evutil_snprintf(portbuf, sizeof(portbuf), \"%d\", url.port());\n memset(&hint, 0, sizeof(hint));\n hint.ai_family = AF_UNSPEC;\n hint.ai_protocol = IPPROTO_TCP;\n hint.ai_socktype = SOCK_STREAM;\n err = evutil_getaddrinfo(address.c_str(), portbuf, &hint, &ai);\n if (err != 0)\n {\n qiLogError(\"qimessaging.TransportSocketLibEvent\") << \"Cannot resolve dns (\" << address << \")\";\n return (false);\n }\n\n int result = bufferevent_socket_connect(bev, ai->ai_addr, ai->ai_addrlen);\n\n if (result == 0)\n return true;\n\n return false;\n }\n else\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"socket is already connected.\";\n }\n\n return false;\n }\n\n void TransportSocketLibEvent::disconnect()\n {\n if (isConnected())\n {\n bufferevent_free(bev);\n bev = NULL;\n connected = false;\n }\n else\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"socket is not connected.\";\n }\n }\n\n bool TransportSocketLibEvent::send(const qi::Message &msg)\n {\n if (!isConnected())\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"socket is not connected.\";\n return false;\n }\n\n qi::Message *m = new qi::Message();\n *m = msg;\n m->_p->complete();\n assert(m->isValid());\n\n struct evbuffer *evb = bufferevent_get_output(bev);\n\n \/\/ m might be deleted.\n qi::Buffer *b = new qi::Buffer(m->buffer());\n\n if (evbuffer_add_reference(evb,\n m->_p->getHeader(),\n sizeof(qi::MessagePrivate::MessageHeader),\n qi::TransportSocketLibEvent::onMessageSent,\n static_cast<void *>(m)) != 0)\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"Add reference fail in header\";\n delete m;\n delete b;\n return false;\n }\n size_t sz = b->size();\n if (sz) {\n if (evbuffer_add_reference(evb,\n b->data(),\n sz,\n qi::TransportSocketLibEvent::onBufferSent,\n static_cast<void *>(b)) != 0)\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"Add reference fail for block of size \" << sz;\n delete b;\n return false;\n }\n }\n else {\n delete b;\n }\n\n if (bufferevent_write_buffer(bev, evb) != 0)\n {\n qiLogError(\"qimessaging.TransportSocketLibevent\") << \"Can't add buffer to the send queue\";\n evbuffer_drain(evb, sizeof(qi::MessagePrivate::MessageHeader) + sz);\n return false;\n }\n\n return true;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"login\/oauth2-login.h\"\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QNetworkAccessManager>\n#include <QNetworkReply>\n#include \"logger.h\"\n#include \"mixed-settings.h\"\n#include \"models\/site.h\"\n\n\ntypedef QPair<QString, QString> QStrP;\n\nOAuth2Login::OAuth2Login(Site *site, QNetworkAccessManager *manager, MixedSettings *settings)\n\t: m_site(site), m_manager(manager), m_settings(settings), m_tokenReply(nullptr)\n{}\n\nbool OAuth2Login::isTestable() const\n{\n\treturn !m_settings->value(\"login\/oauth2\/tokenUrl\").toString().isEmpty();\n}\n\nvoid OAuth2Login::login()\n{\n\tconst QString type = m_settings->value(\"login\/oauth2\/type\", \"password\").toString();\n\tconst QString consumerKey = m_settings->value(\"auth\/consumerKey\").toString();\n\tconst QString consumerSecret = m_settings->value(\"auth\/consumerSecret\").toString();\n\n\tQNetworkRequest request(m_site->fixUrl(m_settings->value(\"login\/oauth2\/tokenUrl\").toString()));\n\trequest.setHeader(QNetworkRequest::ContentTypeHeader, \"application\/x-www-form-urlencoded;charset=UTF-8\");\n\n\tQList<QStrP> body;\n\n\tif (type == \"header_basic\")\n\t{\n\t\tbody << QStrP(\"grant_type\", \"client_credentials\");\n\n\t\tconst QByteArray bearerCredentials = QUrl::toPercentEncoding(consumerKey) + \":\" + QUrl::toPercentEncoding(consumerSecret);\n\t\tconst QByteArray base64BearerCredentials = bearerCredentials.toBase64();\n\t\trequest.setRawHeader(\"Authorization\", \"Basic \" + base64BearerCredentials);\n\t}\n\telse if (type == \"client_credentials\")\n\t{\n\t\tbody << QStrP(\"grant_type\", \"client_credentials\")\n\t\t\t << QStrP(\"client_id\", consumerKey)\n\t\t\t << QStrP(\"client_secret\", consumerSecret);\n\t}\n\telse if (type == \"password\")\n\t{\n\t\tconst QString pseudo = m_settings->value(\"auth\/pseudo\").toString();\n\t\tconst QString password = m_settings->value(\"auth\/password\").toString();\n\n\t\tbody << QStrP(\"grant_type\", \"password\")\n\t\t\t << QStrP(\"username\", pseudo)\n\t\t\t << QStrP(\"password\", password);\n\n\t\tif (!consumerKey.isEmpty())\n\t\t{\n\t\t\tbody << QStrP(\"client_id\", consumerKey);\n\t\t\tif (!consumerSecret.isEmpty())\n\t\t\t{ body << QStrP(\"client_secret\", consumerSecret); }\n\t\t}\n\t}\n\n\t\/\/ Post request and wait for a reply\n\tQString bodyStr;\n\tfor (const QStrP &pair : body)\n\t{ bodyStr += (!bodyStr.isEmpty() ? \"&\" : \"\") + pair.first + \"=\" + pair.second; }\n\tm_tokenReply = m_manager->post(request, bodyStr.toUtf8());\n\tconnect(m_tokenReply, &QNetworkReply::finished, this, &OAuth2Login::loginFinished);\n}\n\nvoid OAuth2Login::loginFinished()\n{\n\tconst QString result = m_tokenReply->readAll();\n\tconst QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toUtf8());\n\tconst QJsonObject jsonObject = jsonDocument.object();\n\n\tconst QJsonValue tokenType = jsonObject.value(\"token_type\");\n\tif (tokenType.isUndefined())\n\t{\n\t\tlog(QStringLiteral(\"[%1] No OAuth2 token type received: %2\").arg(m_site->url(), result), Logger::Warning);\n\t\temit loggedIn(Result::Failure);\n\t\treturn;\n\t}\n\tif (tokenType.toString() != QLatin1String(\"bearer\"))\n\t{\n\t\tlog(QStringLiteral(\"[%1] Wrong OAuth2 token type received (%2).\").arg(m_site->url(), tokenType.toString()), Logger::Warning);\n\t\temit loggedIn(Result::Failure);\n\t\treturn;\n\t}\n\n\tm_token = jsonObject.value(\"access_token\").toString();\n\temit loggedIn(Result::Success);\n}\n\nvoid OAuth2Login::complementRequest(QNetworkRequest *request) const\n{\n\tif (!m_token.isEmpty())\n\t\trequest->setRawHeader(\"Authorization\", \"Bearer \" + m_token.toUtf8());\n}\n<commit_msg>Support OAuth2 API that wrap their responses in 'response' JSON objects<commit_after>#include \"login\/oauth2-login.h\"\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QNetworkAccessManager>\n#include <QNetworkReply>\n#include \"logger.h\"\n#include \"mixed-settings.h\"\n#include \"models\/site.h\"\n\n\ntypedef QPair<QString, QString> QStrP;\n\nOAuth2Login::OAuth2Login(Site *site, QNetworkAccessManager *manager, MixedSettings *settings)\n\t: m_site(site), m_manager(manager), m_settings(settings), m_tokenReply(nullptr)\n{}\n\nbool OAuth2Login::isTestable() const\n{\n\treturn !m_settings->value(\"login\/oauth2\/tokenUrl\").toString().isEmpty();\n}\n\nvoid OAuth2Login::login()\n{\n\tconst QString type = m_settings->value(\"login\/oauth2\/type\", \"password\").toString();\n\tconst QString consumerKey = m_settings->value(\"auth\/consumerKey\").toString();\n\tconst QString consumerSecret = m_settings->value(\"auth\/consumerSecret\").toString();\n\n\tQNetworkRequest request(m_site->fixUrl(m_settings->value(\"login\/oauth2\/tokenUrl\").toString()));\n\trequest.setHeader(QNetworkRequest::ContentTypeHeader, \"application\/x-www-form-urlencoded;charset=UTF-8\");\n\n\tQList<QStrP> body;\n\n\tif (type == \"header_basic\")\n\t{\n\t\tbody << QStrP(\"grant_type\", \"client_credentials\");\n\n\t\tconst QByteArray bearerCredentials = QUrl::toPercentEncoding(consumerKey) + \":\" + QUrl::toPercentEncoding(consumerSecret);\n\t\tconst QByteArray base64BearerCredentials = bearerCredentials.toBase64();\n\t\trequest.setRawHeader(\"Authorization\", \"Basic \" + base64BearerCredentials);\n\t}\n\telse if (type == \"client_credentials\")\n\t{\n\t\tbody << QStrP(\"grant_type\", \"client_credentials\")\n\t\t\t << QStrP(\"client_id\", consumerKey)\n\t\t\t << QStrP(\"client_secret\", consumerSecret);\n\t}\n\telse if (type == \"password\")\n\t{\n\t\tconst QString pseudo = m_settings->value(\"auth\/pseudo\").toString();\n\t\tconst QString password = m_settings->value(\"auth\/password\").toString();\n\n\t\tbody << QStrP(\"grant_type\", \"password\")\n\t\t\t << QStrP(\"username\", pseudo)\n\t\t\t << QStrP(\"password\", password);\n\n\t\tif (!consumerKey.isEmpty())\n\t\t{\n\t\t\tbody << QStrP(\"client_id\", consumerKey);\n\t\t\tif (!consumerSecret.isEmpty())\n\t\t\t{ body << QStrP(\"client_secret\", consumerSecret); }\n\t\t}\n\t}\n\n\t\/\/ Post request and wait for a reply\n\tQString bodyStr;\n\tfor (const QStrP &pair : body)\n\t{ bodyStr += (!bodyStr.isEmpty() ? \"&\" : \"\") + pair.first + \"=\" + pair.second; }\n\tm_tokenReply = m_manager->post(request, bodyStr.toUtf8());\n\tconnect(m_tokenReply, &QNetworkReply::finished, this, &OAuth2Login::loginFinished);\n}\n\nvoid OAuth2Login::loginFinished()\n{\n\tconst QString result = m_tokenReply->readAll();\n\tconst QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toUtf8());\n\n\t\/\/ Some OAuth2 API wrap their responses in 'response' JSON objects\n\tQJsonObject jsonObject = jsonDocument.object();\n\tif (!jsonObject.contains(\"token_type\") && jsonObject.contains(\"response\"))\n\t{ jsonObject = jsonObject.value(\"response\").toObject(); }\n\n\tconst QJsonValue tokenType = jsonObject.value(\"token_type\");\n\tif (tokenType.isUndefined())\n\t{\n\t\tlog(QStringLiteral(\"[%1] No OAuth2 token type received: %2\").arg(m_site->url(), result), Logger::Warning);\n\t\temit loggedIn(Result::Failure);\n\t\treturn;\n\t}\n\tif (tokenType.toString() != QLatin1String(\"bearer\"))\n\t{\n\t\tlog(QStringLiteral(\"[%1] Wrong OAuth2 token type received (%2).\").arg(m_site->url(), tokenType.toString()), Logger::Warning);\n\t\temit loggedIn(Result::Failure);\n\t\treturn;\n\t}\n\n\tm_token = jsonObject.value(\"access_token\").toString();\n\temit loggedIn(Result::Success);\n}\n\nvoid OAuth2Login::complementRequest(QNetworkRequest *request) const\n{\n\tif (!m_token.isEmpty())\n\t\trequest->setRawHeader(\"Authorization\", \"Bearer \" + m_token.toUtf8());\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/time.h>\n\nstatic const char * const succ = \"succ\";\nstatic const char * const fail = \"fail\";\n\nint main (int argc, char *argv[]) {\n (void) argc;\n (void) argv;\n\n char request[255];\n char temp;\n int ret;\n int fd;\n fd_set rset;\n \n FD_ZERO(&rset);\n\n printf(\"great success!\\n\");\n\n for (;;) {\n FD_SET(0, &rset); \n select(1, &rset, NULL, NULL, NULL); \n\n ret = read(0, request, sizeof(request));\n\n if (ret <= 0)\n return 0;\n\n fd = open(request, O_RDONLY);\n \n if (fd < 0)\n ret = write(1, fail, sizeof(fail));\n else\n ret = write(1, succ, sizeof(succ));\n \n if (ret <= 0) {\n close(fd);\n return 0;\n }\n \n ret = read(fd, &temp, sizeof(temp));\n\n close(fd);\n\n if (ret < 0)\n return 0;\n }\n\n}\n<commit_msg>moved anything that may block (fork, open, fstat, read, write) to fdhelper<commit_after>#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/socket.h>\n#include <sys\/sendfile.h>\n#include <sys\/stat.h>\n\n#define FDH_CLONE 100\n#define FDH_KILL 101\n#define FDH_OPEN 102\n#define FDH_STAT 103\n#define FDH_READ 104\n#define FDH_WRITE 105\n\n\/* clone\n * > msg: req\n * < msg: errno | pid; [anc: fd]\n *\n * kill\n * > msg: req\n *\n * open \n * > msg: req | mode | filename\n * < msg: errno; [anc: fd]\n *\n * stat\n * > msg: req, anc: fd\n * < msg: errno | [stat]\n *\n * read\n * > msg: req | size; anc: fd\n * < sendfile: ifd, ofd, NULL, size\n *\n * write\n * > msg: req; anc: fd\n * > write: pipe \n * < read: pipe -> write: fd\n *\/\n\nint send(int fd, int fd_to_send, char * buf, size_t len) {\n struct iovec iov[1];\n struct msghdr msgh;\n struct cmsghdr *cmsg;\n char anc[CMSG_SPACE(sizeof(int))];\n\n iov[0].iov_base = buf;\n iov[0].iov_len = len;\n \n msgh.msg_iov = iov;\n msgh.msg_iovlen = 1;\n \n msgh.msg_name = NULL;\n msgh.msg_namelen = 0;\n\n if (fd < 0) {\n msgh.msg_control = NULL;\n msgh.msg_controllen = 0;\n } else {\n msgh.msg_control = anc;\n msgh.msg_controllen = sizeof(anc);\n\n cmsg = CMSG_FIRSTHDR(&msgh);\n cmsg->cmsg_level = SOL_SOCKET;\n cmsg->cmsg_type = SCM_RIGHTS;\n cmsg->cmsg_len = CMSG_LEN(sizeof(int));\n *(int *)CMSG_DATA(cmsg) = fd_to_send;\n\n msgh.msg_controllen = cmsg->cmsg_len;\n }\n\n msgh.msg_flags = 0;\n\n return sendmsg(fd, &msgh, 0);\n}\n\nint recv(int fd, int * fd_to_recv, char * buf, size_t len) {\n int r;\n int fdt;\n struct iovec iov[1];\n struct msghdr msgh;\n struct cmsghdr *cmsg;\n char anc[CMSG_SPACE(sizeof(int))];\n\n iov[0].iov_base = buf;\n iov[0].iov_len = len;\n \n msgh.msg_iov = iov;\n msgh.msg_iovlen = 1;\n \n msgh.msg_name = NULL;\n msgh.msg_namelen = 0;\n\n msgh.msg_control = anc;\n msgh.msg_controllen = sizeof(anc);\n\n if ((r = recvmsg(fd, &msgh, 0)) < 0)\n return r;\n \n if (msgh.msg_controllen > 0) {\n cmsg = CMSG_FIRSTHDR(&msgh);\n if (cmsg->cmsg_len == sizeof(anc) && cmsg->cmsg_type == SCM_RIGHTS)\n fdt = *(int *)CMSG_DATA(cmsg);\n if (fd_to_recv != NULL)\n *fd_to_recv = fdt;\n else\n close(fdt);\n } else if (fd_to_recv != NULL)\n *fd_to_recv = -1;\n \n return r;\n}\n\nint main (void) {\n char buf[8192];\n int len;\n int fd;\n \n pid_t pid;\n int socks[2], chfd;\n \n mode_t mode;\n char * fname;\n \n struct stat * stat;\n \n size_t size;\n ssize_t ssize;\n\n for (;;) {\n if ((len = recv(0, &fd, buf, sizeof(buf))) < 0) {\n perror(\"recvmsg\");\n goto exit_;\n } else if (len == 0)\n goto exit_;\n \n switch (buf[0]) {\n case FDH_CLONE:\n printf(\"clone %d\\n\", getpid());\n if (socketpair(AF_UNIX, SOCK_STREAM, 0, socks) < 0) {\n chfd = -1;\n *(int *)buf = errno;\n len = sizeof(int);\n goto forkerr;\n }\n \n pid = fork();\n if (pid < 0) {\n chfd = -1;\n *(int *)buf = errno;\n len = sizeof(int);\n goto forkerr;\n } else if (pid == 0) {\n \/\/ child\n printf(\"!child %d\\n\", getpid()); \n close(0);\n close(socks[0]);\n if (dup2(socks[1], 0) < 0) {\n close(socks[1]);\n goto exit_;\n }\n close(socks[1]);\n break;\n }\n \n chfd = socks[0];\n *(int *)buf = 0;\n *(pid_t *)&buf[sizeof(int)] = pid;\n len = sizeof(int) + sizeof(pid_t);\n forkerr:\n close(socks[1]);\n if (send(0, chfd, buf, len) < 0) {\n perror(\"sendmsg\");\n close(socks[0]);\n goto exit_;\n }\n close(socks[0]);\n break;\n case FDH_KILL:\n printf(\"kill %d\\n\", getpid());\n goto exit_;\n break;\n case FDH_OPEN:\n printf(\"open %d\\n\", getpid());\n mode = *(int *)&buf[1];\n fname = &buf[1 + sizeof(mode_t)];\n *(int *)buf = ((fd = open(fname, mode)) < 0) ? errno : 0;\n if (send(0, fd, buf, sizeof(int)) < 0) {\n perror(\"sendmsg\");\n goto exit;\n }\n close(fd);\n break;\n case FDH_STAT:\n printf(\"stat %d\\n\", getpid());\n stat = (struct stat *)&buf[sizeof(int)];\n *(int *)buf = (fstat(fd, stat) < 0) ? errno : 0;\n if (send(0, fd, buf, sizeof(int) + sizeof(struct stat)) < 0) {\n perror(\"sendmsg\");\n goto exit;\n }\n close(fd);\n break;\n case FDH_READ:\n printf(\"read %d\\n\", getpid());\n size = *(size_t *)&buf[1];\n if (sendfile(0, fd, NULL, size) < 0) {\n \/* TODO handle error gracefully *\/\n perror(\"sendfile\");\n goto exit;\n }\n close(fd);\n break;\n case FDH_WRITE:\n printf(\"write %d %d\\n\", fd, getpid());\n do {\n if ((ssize = read(0, buf, sizeof(buf))) < 0) {\n \/* TODO handle error gracefully *\/\n perror(\"read\");\n goto exit;\n }\n if (ssize)\n if (ssize != write(fd, buf, (size_t)ssize)) {\n \/* TODO handle error gracefully *\/\n perror(\"\\nwritex\");\n goto exit;\n }\n } while (ssize > 0);\n close(fd);\n break;\n default:\n fprintf(stderr, \"Unknown request\\n\");\n goto exit;\n break;\n }\n }\n\nexit:\n close(fd);\nexit_:\n printf(\"exit %d\\n\", getpid());\n close(0);\n exit(0);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <b9\/interpreter.hpp>\n#include <b9\/loader.hpp>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/time.h>\n#include <vector>\n\n#include <gtest\/gtest.h>\n\nnamespace b9 {\nnamespace test {\n\nclass InterpreterTestEnvironment : public ::testing::Environment {\n public:\n static const char* moduleName;\n\n virtual void SetUp() {\n moduleName = getenv(\"B9_TEST_MODULE\");\n ASSERT_NE(moduleName, nullptr);\n }\n};\n\nconst char* InterpreterTestEnvironment::moduleName{nullptr};\n\nclass InterpreterTest : public ::testing::TestWithParam<const char*> {\n public:\n static std::shared_ptr<Module> module_;\n\n static void SetUpTestCase() {\n module_ = DlLoader{}.loadModule(InterpreterTestEnvironment::moduleName);\n }\n\n virtual void SetUp() {}\n};\n\nstd::shared_ptr<Module> InterpreterTest::module_{nullptr};\n\nTEST_P(InterpreterTest, run) {\n Config cfg;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\nTEST_P(InterpreterTest, runJit) {\n Config cfg;\n cfg.jit = true;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\nTEST_P(InterpreterTest, runDirectCall) {\n Config cfg;\n cfg.jit = true;\n cfg.directCall = true;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\nTEST_P(InterpreterTest, runPassParam) {\n Config cfg;\n cfg.jit = true;\n cfg.directCall = true;\n cfg.passParam = true;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\nTEST_P(InterpreterTest, runLazyVmState) {\n Config cfg;\n cfg.jit = true;\n cfg.directCall = true;\n cfg.passParam = true;\n cfg.lazyVmState = true;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\n\/\/ clang-format off\n\nINSTANTIATE_TEST_CASE_P(InterpreterTestSuite, InterpreterTest,\n ::testing::Values(\n \"test_return_true\",\n \"test_return_false\",\n \"test_add\",\n \"test_sub\",\n \"test_equal\",\n \"test_equal_1\",\n \"test_greaterThan\",\n \"test_greaterThan_1\",\n \"test_greaterThanOrEqual\",\n \"test_greaterThanOrEqual_1\",\n \"test_greaterThanOrEqual_2\",\n \"test_lessThan\",\n \"test_lessThan_1\",\n \"test_lessThan_2\",\n \"test_lessThan_3\",\n \"test_lessThanOrEqual\",\n \"test_lessThanOrEqual_1\",\n \"test_call\",\n \"test_string_declare_string_var\",\n \"helper_test_string_return_string\",\n \"test_string_return_string\",\n \"test_while\"\n));\n\n\/\/ clang-format on\n\nTEST(MyTest, arguments) {\n b9::VirtualMachine vm{{}};\n auto m = std::make_shared<Module>();\n Instruction i[] = {{ByteCode::PUSH_FROM_VAR, 0},\n {ByteCode::PUSH_FROM_VAR, 1},\n {ByteCode::INT_ADD},\n {ByteCode::FUNCTION_RETURN},\n END_SECTION};\n\n m->functions.push_back(b9::FunctionSpec{\"add_args\", i, 2, 0});\n vm.load(m);\n auto r = vm.run(\"add_args\", {1, 2});\n EXPECT_EQ(r, 3);\n}\n\n} \/\/ namespace test\n} \/\/ namespace b9\n\nextern \"C\" int main(int argc, char** argv) {\n ::testing::InitGoogleTest(&argc, argv);\n AddGlobalTestEnvironment(new b9::test::InterpreterTestEnvironment{});\n return RUN_ALL_TESTS();\n}\n<commit_msg>Add CASCON eye catcher<commit_after>#include <b9\/interpreter.hpp>\n#include <b9\/loader.hpp>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/time.h>\n#include <vector>\n\n#include <gtest\/gtest.h>\n\nnamespace b9 {\nnamespace test {\n\nclass InterpreterTestEnvironment : public ::testing::Environment {\n public:\n static const char* moduleName;\n\n virtual void SetUp() {\n moduleName = getenv(\"B9_TEST_MODULE\");\n ASSERT_NE(moduleName, nullptr);\n }\n};\n\nconst char* InterpreterTestEnvironment::moduleName{nullptr};\n\nclass InterpreterTest : public ::testing::TestWithParam<const char*> {\n public:\n static std::shared_ptr<Module> module_;\n\n static void SetUpTestCase() {\n module_ = DlLoader{}.loadModule(InterpreterTestEnvironment::moduleName);\n }\n\n virtual void SetUp() {}\n};\n\nstd::shared_ptr<Module> InterpreterTest::module_{nullptr};\n\nTEST_P(InterpreterTest, run) {\n Config cfg;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\nTEST_P(InterpreterTest, runJit) {\n Config cfg;\n cfg.jit = true;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\nTEST_P(InterpreterTest, runDirectCall) {\n Config cfg;\n cfg.jit = true;\n cfg.directCall = true;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\nTEST_P(InterpreterTest, runPassParam) {\n Config cfg;\n cfg.jit = true;\n cfg.directCall = true;\n cfg.passParam = true;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\nTEST_P(InterpreterTest, runLazyVmState) {\n Config cfg;\n cfg.jit = true;\n cfg.directCall = true;\n cfg.passParam = true;\n cfg.lazyVmState = true;\n\n VirtualMachine vm{cfg};\n vm.load(module_);\n EXPECT_TRUE(vm.run(GetParam(), {}));\n}\n\n\/\/ clang-format off\n\nINSTANTIATE_TEST_CASE_P(InterpreterTestSuite, InterpreterTest,\n ::testing::Values(\n \"test_return_true\",\n \"test_return_false\",\n \"test_add\",\n \"test_sub\",\n \"test_equal\",\n \"test_equal_1\",\n \"test_greaterThan\",\n \"test_greaterThan_1\",\n \"test_greaterThanOrEqual\",\n \"test_greaterThanOrEqual_1\",\n \"test_greaterThanOrEqual_2\",\n \"test_lessThan\",\n \"test_lessThan_1\",\n \"test_lessThan_2\",\n \"test_lessThan_3\",\n \"test_lessThanOrEqual\",\n \"test_lessThanOrEqual_1\",\n \"test_call\",\n \"test_string_declare_string_var\",\n \"helper_test_string_return_string\",\n \"test_string_return_string\",\n \"test_while\"\n \/\/ CASCON2017 add test_div and test_mul here\n));\n\n\/\/ clang-format on\n\nTEST(MyTest, arguments) {\n b9::VirtualMachine vm{{}};\n auto m = std::make_shared<Module>();\n Instruction i[] = {{ByteCode::PUSH_FROM_VAR, 0},\n {ByteCode::PUSH_FROM_VAR, 1},\n {ByteCode::INT_ADD},\n {ByteCode::FUNCTION_RETURN},\n END_SECTION};\n\n m->functions.push_back(b9::FunctionSpec{\"add_args\", i, 2, 0});\n vm.load(m);\n auto r = vm.run(\"add_args\", {1, 2});\n EXPECT_EQ(r, 3);\n}\n\n} \/\/ namespace test\n} \/\/ namespace b9\n\nextern \"C\" int main(int argc, char** argv) {\n ::testing::InitGoogleTest(&argc, argv);\n AddGlobalTestEnvironment(new b9::test::InterpreterTestEnvironment{});\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Arduino.h>\n#include <unity.h>\n\n#ifdef UNIT_TEST\n\n\/\/ void setUp(void) {\n\/\/ \/\/ set stuff up here\n\/\/ }\n\n\/\/ void tearDown(void) {\n\/\/ \/\/ clean stuff up here\n\/\/ }\n\nvoid test_led_builtin_pin_number(void) {\n TEST_ASSERT_EQUAL(LED_BUILTIN, 13);\n}\n\nvoid test_led_state_high(void) {\n digitalWrite(LED_BUILTIN, HIGH);\n TEST_ASSERT_EQUAL(digitalRead(LED_BUILTIN), LOW);\n}\n\nvoid test_led_state_low(void) {\n digitalWrite(LED_BUILTIN, LOW);\n TEST_ASSERT_EQUAL(digitalRead(LED_BUILTIN), LOW);\n}\n\nvoid setup() {\n \/\/ NOTE!!! Wait for >2 secs\n \/\/ if board doesn't support software reset via Serial.DTR\/RTS\n delay(2000);\n\n UNITY_BEGIN(); \/\/ IMPORTANT LINE!\n RUN_TEST(test_led_builtin_pin_number);\n\n pinMode(LED_BUILTIN, OUTPUT);\n}\n\nuint8_t i = 0;\nuint8_t max_blinks = 5;\n\nvoid loop() {\n if (i < max_blinks)\n {\n RUN_TEST(test_led_state_high);\n delay(500);\n RUN_TEST(test_led_state_low);\n delay(500);\n i++;\n }\n else if (i == max_blinks) {\n UNITY_END(); \/\/ stop unit testing\n }\n}\n\n#endif\n<commit_msg>Fix test<commit_after>#include <Arduino.h>\n#include <unity.h>\n\n#ifdef UNIT_TEST\n\n\/\/ void setUp(void) {\n\/\/ \/\/ set stuff up here\n\/\/ }\n\n\/\/ void tearDown(void) {\n\/\/ \/\/ clean stuff up here\n\/\/ }\n\nvoid test_led_builtin_pin_number(void) {\n TEST_ASSERT_EQUAL(LED_BUILTIN, 13);\n}\n\nvoid test_led_state_high(void) {\n digitalWrite(LED_BUILTIN, HIGH);\n TEST_ASSERT_EQUAL(digitalRead(LED_BUILTIN), HIGH);\n}\n\nvoid test_led_state_low(void) {\n digitalWrite(LED_BUILTIN, LOW);\n TEST_ASSERT_EQUAL(digitalRead(LED_BUILTIN), LOW);\n}\n\nvoid setup() {\n \/\/ NOTE!!! Wait for >2 secs\n \/\/ if board doesn't support software reset via Serial.DTR\/RTS\n delay(2000);\n\n UNITY_BEGIN(); \/\/ IMPORTANT LINE!\n RUN_TEST(test_led_builtin_pin_number);\n\n pinMode(LED_BUILTIN, OUTPUT);\n}\n\nuint8_t i = 0;\nuint8_t max_blinks = 5;\n\nvoid loop() {\n if (i < max_blinks)\n {\n RUN_TEST(test_led_state_high);\n delay(500);\n RUN_TEST(test_led_state_low);\n delay(500);\n i++;\n }\n else if (i == max_blinks) {\n UNITY_END(); \/\/ stop unit testing\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n*\n* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker 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 Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* fermin at tid dot es\n*\n* Author: Ken Zangelin\n*\/\n#include \"gtest\/gtest.h\"\n\n#include \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n#include \"common\/globals.h\"\n\n#include \"convenienceMap\/mapGetContextEntityAttributes.h\"\n#include \"convenience\/RegisterProviderRequest.h\"\n#include \"convenienceMap\/mapPostIndividualContextEntityAttribute.h\"\n#include \"mongoBackend\/mongoRegisterContext.h\"\n#include \"ngsi9\/RegisterContextResponse.h\"\n#include \"ngsi9\/DiscoverContextAvailabilityResponse.h\"\n#include \"testInit.h\"\n\n\n\n\/* ****************************************************************************\n*\n* prepareDatabase -\n*\/\nstatic void prepareDatabase(std::string id, std::string type)\n{\n \/* Set database *\/\n setupDatabase();\n\n DBClientConnection* connection = getMongoConnection();\n\n \/* We create one entity:\n *\n * - 'id', 'type' with four attributes\n * A1: X\n * A1: Y\n * A2: Z\n * A3: W\n *\/\n\n BSONObj en1 = BSON(\"_id\" << BSON(\"id\" << id << \"type\" << type) <<\n \"attrs\" << BSON_ARRAY(\n BSON(\"name\" << \"A1\" << \"type\" << \"TA1\" << \"value\" << \"X\") <<\n BSON(\"name\" << \"A1\" << \"type\" << \"TA1bis\" << \"value\" << \"Y\") <<\n BSON(\"name\" << \"A2\" << \"type\" << \"TA2\" << \"value\" << \"Z\") <<\n BSON(\"name\" << \"A3\" << \"type\" << \"TA3\" << \"value\" << \"W\")\n )\n );\n\n connection->insert(ENTITIES_COLL, en1);\n}\n\n\n\n\/* ****************************************************************************\n*\n* notFoundThenFound - \n*\/\nTEST(mapPostIndividualContextEntityAttribute, notFoundThenFound)\n{\n HttpStatusCode ms;\n UpdateContextAttributeRequest request;\n StatusCode response;\n\n \/* Set timer *\/\n Timer* t = new Timer();\n setTimer(t);\n\n prepareDatabase(\"MPICE\", \"ttt\");\n\n ms = mapPostIndividualContextEntityAttribute(\"MPICE\", \"A1\", &request, &response);\n EXPECT_EQ(SccOk, ms);\n EXPECT_EQ(200, response.code);\n\n ms = mapPostIndividualContextEntityAttribute(\"MPICE2\", \"A9\", &request, &response);\n EXPECT_EQ(SccOk, ms);\n\n \/\/ FIXME P9: Why is there a 200 OK here?\n \/\/ Why not?\n \/\/\n \/\/ POST \/ngsi10\/contextEntities\/*\/attributes\/* :\n \/\/ This operation allows adding new value instances, possibly including metadata, for the attribute represented by the resource.\n \/\/ The request body is an instance of updateContextAttributeRequest; the response body is an instance of StatusCode.\n \/\/\n EXPECT_EQ(200, response.code);\n}\n<commit_msg>changed fixme text<commit_after>\/*\n*\n* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker 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 Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* fermin at tid dot es\n*\n* Author: Ken Zangelin\n*\/\n#include \"gtest\/gtest.h\"\n\n#include \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n#include \"common\/globals.h\"\n\n#include \"convenienceMap\/mapGetContextEntityAttributes.h\"\n#include \"convenience\/RegisterProviderRequest.h\"\n#include \"convenienceMap\/mapPostIndividualContextEntityAttribute.h\"\n#include \"mongoBackend\/mongoRegisterContext.h\"\n#include \"ngsi9\/RegisterContextResponse.h\"\n#include \"ngsi9\/DiscoverContextAvailabilityResponse.h\"\n#include \"testInit.h\"\n\n\n\n\/* ****************************************************************************\n*\n* prepareDatabase -\n*\/\nstatic void prepareDatabase(std::string id, std::string type)\n{\n \/* Set database *\/\n setupDatabase();\n\n DBClientConnection* connection = getMongoConnection();\n\n \/* We create one entity:\n *\n * - 'id', 'type' with four attributes\n * A1: X\n * A1: Y\n * A2: Z\n * A3: W\n *\/\n\n BSONObj en1 = BSON(\"_id\" << BSON(\"id\" << id << \"type\" << type) <<\n \"attrs\" << BSON_ARRAY(\n BSON(\"name\" << \"A1\" << \"type\" << \"TA1\" << \"value\" << \"X\") <<\n BSON(\"name\" << \"A1\" << \"type\" << \"TA1bis\" << \"value\" << \"Y\") <<\n BSON(\"name\" << \"A2\" << \"type\" << \"TA2\" << \"value\" << \"Z\") <<\n BSON(\"name\" << \"A3\" << \"type\" << \"TA3\" << \"value\" << \"W\")\n )\n );\n\n connection->insert(ENTITIES_COLL, en1);\n}\n\n\n\n\/* ****************************************************************************\n*\n* notFoundThenFound - \n*\/\nTEST(mapPostIndividualContextEntityAttribute, notFoundThenFound)\n{\n HttpStatusCode ms;\n UpdateContextAttributeRequest request;\n StatusCode response;\n\n \/* Set timer *\/\n Timer* t = new Timer();\n setTimer(t);\n\n prepareDatabase(\"MPICE\", \"ttt\");\n\n ms = mapPostIndividualContextEntityAttribute(\"MPICE\", \"A1\", &request, &response);\n EXPECT_EQ(SccOk, ms);\n EXPECT_EQ(200, response.code);\n\n ms = mapPostIndividualContextEntityAttribute(\"MPICE2\", \"A9\", &request, &response);\n EXPECT_EQ(SccOk, ms);\n\n \/\/ FIXME P9: Why is there a 200 OK here?\n \/\/ To be removed when the convenienceMap library is removed.\n \/\/ See issue #117\n EXPECT_EQ(200, response.code);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"MooseInit.h\"\n#include \"Moose.h\"\n#include \"MooseTypes.h\"\n#include \"libmesh\/parallel.h\"\n#include \"libmesh\/null_output_iterator.h\"\n\n#include <vector>\n#include <list>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n\n\/\/ Create a performance log\nPerfLog Moose::perf_log(\"Moose Test\");\n\n\ntemplate <typename T>\nstruct string_list_inserter\n : std::iterator<std::output_iterator_tag, T>\n{\n explicit string_list_inserter(std::list<T *> & list) : _list(list) \n {\n }\n \n template <typename T2>\n void operator=(const T2 & value)\n {\n _list.push_back(value);\n }\n\n string_list_inserter& operator++() {\n return *this;\n }\n\n string_list_inserter operator++(int) {\n return string_list_inserter(*this);\n }\n\n \/\/ We don't return a reference-to-T here because we don't want to\n \/\/ construct one or have any of its methods called.\n string_list_inserter& operator*() { return *this; }\n\nprivate:\n std::list<T *> & _list;\n};\n\n\nnamespace libMesh {\nnamespace Parallel {\n\n\/\/ BufferType<> specializations to return a buffer datatype\n\/\/ to handle communication of Elems\ntemplate <>\nstruct BufferType<const std::string *> {\n typedef largest_id_type type;\n};\n\ntemplate<>\nunsigned int packed_size(const std::string *, std::vector<largest_id_type>::const_iterator in)\n{\n \/\/ String is encoded as a length followed by the content (as long long ints)\n return in[0] + 1;;\n}\n\ntemplate<>\nunsigned int packed_size(const std::string * s, std::vector<largest_id_type>::iterator in)\n{\n return packed_size(s, std::vector<largest_id_type>::const_iterator(in));\n}\n\n\ntemplate<>\nunsigned int packable_size(const std::string * s, const void *)\n{\n \/\/ String is encoded as a length followed by the content (as long long ints)\n return s->size() + 1;\n}\n \n \ntemplate <>\nvoid pack (const std::string * b, std::vector<largest_id_type> & data, const void *)\n{\n data.push_back(b->size());\n std::copy(b->begin(), b->end(), std::back_inserter(data));\n}\n \ntemplate <>\nvoid unpack(std::vector<largest_id_type>::const_iterator in, std::string ** out, void *)\n{\n largest_id_type size = in[0];\n\n std::ostringstream oss;\n for (unsigned int i = 0; i < size; ++i)\n oss << static_cast<char>(in[i+1]);\n\n in += size + 1;\n \n (*out) = new std::string(oss.str());\n}\n\n}\n}\n \n\n\nint main(int argc, char *argv[])\n{ \n \/\/ Initialize MPI, solvers and MOOSE\n MooseInit init(argc, argv);\n\n MooseSharedPointer<Parallel::Communicator> comm(new Parallel::Communicator(MPI_COMM_WORLD));\n\n std::string foo;\n switch (comm->rank())\n {\n case 0:\n foo.assign(\"zero\"); break;\n case 1:\n foo.assign(\"one\"); break;\n case 2:\n foo.assign(\"two\"); break;\n case 3:\n foo.assign(\"three\"); break;\n case 4:\n foo.assign(\"four\"); break;\n case 5:\n foo.assign(\"five\"); break;\n case 6:\n foo.assign(\"six\"); break;\n default:\n foo.assign(\"some bigger number\"); break;\n }\n \n std::vector<std::string *> send(1);\n send[0] = &foo;\n\n std::list<std::string *> recv;\n \n comm->allgather_packed_range((void *)(NULL), send.begin(), send.end(),\n string_list_inserter<std::string>(recv));\n\n for (std::list<std::string *>::iterator it = recv.begin(); it != recv.end(); ++it)\n std::cout << **it << '\\n';\n \n \/\/ Vitally important!\n for (std::list<std::string *>::iterator it = recv.begin(); it != recv.end(); ++it)\n delete *it;\n \n return 0;\n}\n<commit_msg>Fooling around with switching largest_id_type to char<commit_after>#include \"MooseInit.h\"\n#include \"Moose.h\"\n#include \"MooseTypes.h\"\n#include \"libmesh\/parallel.h\"\n#include \"libmesh\/null_output_iterator.h\"\n\n#include <vector>\n#include <list>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n\n\/\/ Create a performance log\nPerfLog Moose::perf_log(\"Moose Test\");\n\n\ntemplate <typename T>\nstruct string_list_inserter\n : std::iterator<std::output_iterator_tag, T>\n{\n explicit string_list_inserter(std::list<T *> & list) : _list(list)\n {\n }\n\n template <typename T2>\n void operator=(const T2 & value)\n {\n _list.push_back(value);\n }\n\n string_list_inserter& operator++() {\n return *this;\n }\n\n string_list_inserter operator++(int) {\n return string_list_inserter(*this);\n }\n\n \/\/ We don't return a reference-to-T here because we don't want to\n \/\/ construct one or have any of its methods called.\n string_list_inserter& operator*() { return *this; }\n\nprivate:\n std::list<T *> & _list;\n};\n\n\nnamespace libMesh {\nnamespace Parallel {\n\n\/\/ BufferType<> specializations to return a buffer datatype\n\/\/ to handle communication of Elems\ntemplate <>\nstruct BufferType<const std::string *> {\n typedef unsigned char type;\n};\n\ntemplate<>\nunsigned int packed_size(const std::string *, std::vector<unsigned char>::const_iterator in)\n{\n std::cout << \"packed size: \" << ((in[0] << 24) | (in[1] << 16) | (in[2] << 8) | (in[3] << 0)) << std::endl;\n\n\n \/\/ String is encoded as a 32-bit length followed by the content (unsigned char)\n return (in[0] << 24) | (in[1] << 16) | (in[2] << 8) | (in[3]);\n}\n\ntemplate<>\nunsigned int packed_size(const std::string * s, std::vector<unsigned char>::iterator in)\n{\n return packed_size(s, std::vector<unsigned char>::const_iterator(in));\n}\n\n\ntemplate<>\nunsigned int packable_size(const std::string * s, const void *)\n{\n \/\/ String is encoded as a 32-bit length followed by the content (unsigned char)\n return s->size() + 4;\n}\n\n\ntemplate <>\nvoid pack (const std::string * b, std::vector<unsigned char> & data, const void *)\n{\n uint32_t size = 4 \/* 32-bit int *\/ + b->size();\n\n\/\/ std::cout << \"size: \" << size << std::endl;\n\/\/\n\/\/ const unsigned char* beg = reinterpret_cast<const unsigned char*>(&size);\n\/\/ const unsigned char* end = beg + sizeof(size);\n\/\/ while(beg != end)\n\/\/ std::cout << std::bitset<CHAR_BIT>(*beg++) << ' ';\n\/\/ std::cout << '\\n';\n\n\n data.push_back(size >> 24);\n data.push_back(size >> 16);\n data.push_back(size >> 8);\n data.push_back(size);\n\n\/\/ data.push_back(static_cast<unsigned char>(size & 0x000000FF));\n\/\/ data.reinterpret_cast<\n\n unsigned int packed_size = data.size();\n std::cout << \"byte 0: \" << static_cast<unsigned int>(data[packed_size-4]) << std::endl;\n std::cout << \"byte 1: \" << static_cast<unsigned int>(data[packed_size-3]) << std::endl;\n std::cout << \"byte 2: \" << static_cast<unsigned int>(data[packed_size-2]) << std::endl;\n std::cout << \"byte 3: \" << static_cast<unsigned int>(data[packed_size-1]) << std::endl;\n\n\n std::copy(b->begin(), b->end(), std::back_inserter(data));\n}\n\ntemplate <>\nvoid unpack(std::vector<unsigned char>::const_iterator in, std::string ** out, void *)\n{\n uint32_t size = (in[0] << 24) | (in[1] << 16) | (in[2] << 8) | (in[3] << 0);\n\n std::cout << \"Unpack: \" << size << std::endl;\n\n std::ostringstream oss;\n for (unsigned int i = 4; i < size; ++i)\n oss << in[i];\n\n in += size;\n\n (*out) = new std::string(oss.str());\n}\n\n}\n}\n\n\n\nint main(int argc, char *argv[])\n{\n \/\/ Initialize MPI, solvers and MOOSE\n MooseInit init(argc, argv);\n\n MooseSharedPointer<Parallel::Communicator> comm(new Parallel::Communicator(MPI_COMM_WORLD));\n\n std::string foo;\n switch (comm->rank())\n {\n case 0:\n for (unsigned int i=0; i<260; ++i)\n foo.append(\"0123456789\");\n break;\n\n\/\/ foo.assign(\"zero\"); break;\n case 1:\n foo.assign(\"one\"); break;\n case 2:\n foo.assign(\"two\"); break;\n case 3:\n foo.assign(\"three\"); break;\n case 4:\n foo.assign(\"four\"); break;\n case 5:\n foo.assign(\"five\"); break;\n case 6:\n foo.assign(\"six\"); break;\n default:\n foo.assign(\"some bigger number\"); break;\n }\n\n std::vector<std::string *> send(1);\n send[0] = &foo;\n\n std::list<std::string *> recv;\n\n comm->allgather_packed_range((void *)(NULL), send.begin(), send.end(),\n string_list_inserter<std::string>(recv));\n\n\n for (std::list<std::string *>::iterator it = recv.begin(); it != recv.end(); ++it)\n std::cout << **it << '\\n';\n\n \/\/ Vitally important!\n for (std::list<std::string *>::iterator it = recv.begin(); it != recv.end(); ++it)\n delete *it;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_optimizers\"\n\n#include <boost\/test\/unit_test.hpp>\n#include \"math\/abs.hpp\"\n#include \"core\/logger.h\"\n#include \"core\/minimize.h\"\n#include \"math\/random.hpp\"\n#include \"math\/numeric.hpp\"\n#include \"math\/epsilon.hpp\"\n#include \"text\/to_string.hpp\"\n\n#include \"func\/function_trid.h\"\n#include \"func\/function_beale.h\"\n#include \"func\/function_booth.h\"\n#include \"func\/function_sphere.h\"\n#include \"func\/function_matyas.h\"\n#include \"func\/function_powell.h\"\n#include \"func\/function_mccormick.h\"\n#include \"func\/function_himmelblau.h\"\n#include \"func\/function_rosenbrock.h\"\n#include \"func\/function_3hump_camel.h\"\n#include \"func\/function_sum_squares.h\"\n#include \"func\/function_dixon_price.h\"\n#include \"func\/function_goldstein_price.h\"\n#include \"func\/function_rotated_ellipsoid.h\"\n\nnamespace test\n{\n using namespace ncv;\n\n static void check_solution(const string_t& problem, const string_t& optimizer,\n const vector_t& x0, const opt_state_t& state, const std::vector<std::pair<vector_t, scalar_t>>& solutions)\n {\n \/\/ check convergence\n const scalar_t dg = state.g.lpNorm<Eigen::Infinity>();\n BOOST_CHECK_LE(dg, math::epsilon3<scalar_t>());\n\n \/\/ find the closest solution\n size_t best_index = std::string::npos;\n scalar_t best_distance = std::numeric_limits<scalar_t>::max();\n\n for (size_t index = 0; index < solutions.size(); index ++)\n {\n const scalar_t distance = (state.x - solutions[index].first).lpNorm<Eigen::Infinity>();\n if (distance < best_distance)\n {\n best_distance = distance;\n best_index = index;\n }\n }\n\n \/\/ check accuracy\n BOOST_REQUIRE_LT(best_index, solutions.size());\n\n const scalar_t df = math::abs(state.f - solutions[best_index].second);\n const scalar_t dx = (state.x - solutions[best_index].first).lpNorm<Eigen::Infinity>();\n\n BOOST_CHECK_LE(df, math::epsilon3<scalar_t>());\n BOOST_CHECK_LE(dx, math::epsilon3<scalar_t>());\n\n \/\/ debugging\n BOOST_CHECK_MESSAGE(\n dx < math::epsilon3<scalar_t>(),\n \"failed (x) for <\" << problem << \">, <\" << optimizer << \"> and <\" << x0.transpose() << \">!\");\n BOOST_CHECK_MESSAGE(\n df < math::epsilon3<scalar_t>(),\n \"failed (f) for <\" << problem << \">, <\" << optimizer << \"> and <\" << x0.transpose() << \">!\");\n BOOST_CHECK_MESSAGE(\n dg < math::epsilon3<scalar_t>(),\n \"failed (g) for <\" << problem << \">, <\" << optimizer << \"> and <\" << x0.transpose() << \">!\");\n }\n\n static void check_problem(\n const string_t& problem_name,\n const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,\n const std::vector<std::pair<vector_t, scalar_t>>& solutions)\n {\n const size_t iterations = 1024;\n const scalar_t epsilon = 1e-6;\n const size_t trials = 16 * 1024;\n\n const size_t dims = fn_size();\n\n random_t<scalar_t> rgen(-1.0, +1.0);\n\n \/\/ generate fixed random trials\n vectors_t x0s;\n for (size_t t = 0; t < trials; t ++)\n {\n vector_t x0(dims);\n rgen(x0.data(), x0.data() + x0.size());\n\n x0s.push_back(x0);\n }\n\n \/\/ optimizers to try\n const auto optimizers =\n {\n min::batch_optimizer::GD,\n\n min::batch_optimizer::CGD,\n\/\/ min::batch_optimizer::CGD_CD,\n\/\/ min::batch_optimizer::CGD_DY,\n\/\/ min::batch_optimizer::CGD_FR,\n\/\/ min::batch_optimizer::CGD_HS,\n\/\/ min::batch_optimizer::CGD_LS,\n min::batch_optimizer::CGD_N,\n min::batch_optimizer::CGD_PRP,\n\/\/ min::batch_optimizer::CGD_DYCD,\n min::batch_optimizer::CGD_DYHS,\n\n min::batch_optimizer::LBFGS\n };\n\n for (min::batch_optimizer optimizer : optimizers)\n {\n for (size_t t = 0; t < trials; t ++)\n {\n const vector_t& x0 = x0s[t];\n\n \/\/ optimize\n const opt_state_t state = ncv::minimize(\n fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,\n x0, optimizer, iterations, epsilon);\n\n \/\/ check solution\n check_solution(problem_name, text::to_string(optimizer), x0, state, solutions);\n }\n }\n }\n\n static void check_problems(const std::vector<test::function_t>& funcs)\n {\n for (const test::function_t& func : funcs)\n {\n test::check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(test_optimizers)\n{\n using namespace ncv; \n\n\/\/ test::check_problems(ncv::make_beale_funcs());\n test::check_problems(ncv::make_booth_funcs());\n test::check_problems(ncv::make_matyas_funcs());\n\/\/ test::check_problems(ncv::make_trid_funcs(8));\n test::check_problems(ncv::make_sphere_funcs(8));\n\/\/ test::check_problems(ncv::make_powell_funcs(8));\n\/\/ test::check_problems(ncv::make_mccormick_funcs());\n test::check_problems(ncv::make_himmelblau_funcs());\n\/\/ test::check_problems(ncv::make_rosenbrock_funcs(7));\n\/\/ test::check_problems(ncv::make_3hump_camel_funcs());\n\/\/ test::check_problems(ncv::make_dixon_price_funcs(8));\n test::check_problems(ncv::make_sum_squares_funcs(8));\n\/\/ test::check_problems(ncv::make_goldstein_price_funcs());\n test::check_problems(ncv::make_rotated_ellipsoid_funcs(8));\n}\n\n<commit_msg>exhaustively testing the optimizers (to polish & make it faster)<commit_after>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_optimizers\"\n\n#include <boost\/test\/unit_test.hpp>\n#include \"math\/abs.hpp\"\n#include \"core\/logger.h\"\n#include \"core\/minimize.h\"\n#include \"math\/random.hpp\"\n#include \"math\/numeric.hpp\"\n#include \"math\/epsilon.hpp\"\n#include \"text\/to_string.hpp\"\n\n#include \"func\/function_trid.h\"\n#include \"func\/function_beale.h\"\n#include \"func\/function_booth.h\"\n#include \"func\/function_sphere.h\"\n#include \"func\/function_matyas.h\"\n#include \"func\/function_powell.h\"\n#include \"func\/function_mccormick.h\"\n#include \"func\/function_himmelblau.h\"\n#include \"func\/function_rosenbrock.h\"\n#include \"func\/function_3hump_camel.h\"\n#include \"func\/function_sum_squares.h\"\n#include \"func\/function_dixon_price.h\"\n#include \"func\/function_goldstein_price.h\"\n#include \"func\/function_rotated_ellipsoid.h\"\n\nnamespace test\n{\n using namespace ncv;\n\n static void check_solution(const string_t& problem, const string_t& optimizer,\n const vector_t& x0, const opt_state_t& state, const std::vector<std::pair<vector_t, scalar_t>>& solutions)\n {\n\/\/ \/\/ find the closest solution\n\/\/ size_t best_index = std::string::npos;\n\/\/ scalar_t best_distance = std::numeric_limits<scalar_t>::max();\n\n\/\/ for (size_t index = 0; index < solutions.size(); index ++)\n\/\/ {\n\/\/ const scalar_t distance = (state.x - solutions[index].first).lpNorm<Eigen::Infinity>();\n\/\/ if (distance < best_distance)\n\/\/ {\n\/\/ best_distance = distance;\n\/\/ best_index = index;\n\/\/ }\n\/\/ }\n\n\/\/ \/\/ check accuracy\n\/\/ BOOST_REQUIRE_LT(best_index, solutions.size());\n\n\/\/ const scalar_t df = math::abs(state.f - solutions[best_index].second);\n\/\/ const scalar_t dx = (state.x - solutions[best_index].first).lpNorm<Eigen::Infinity>();\n\n\/\/ BOOST_CHECK_LE(df, math::epsilon3<scalar_t>());\n\/\/ BOOST_CHECK_LE(dx, math::epsilon3<scalar_t>());\n\n\/\/ \/\/ debugging\n\/\/ BOOST_CHECK_MESSAGE(\n\/\/ dx < math::epsilon3<scalar_t>(),\n\/\/ \"failed (x) after \" << state.n_iterations() <<\n\/\/ \" iterations for <\" << problem << \">, <\" << optimizer << \"> and <\" << x0.transpose() << \">!\");\n\/\/ BOOST_CHECK_MESSAGE(\n\/\/ df < math::epsilon3<scalar_t>(),\n\/\/ \"failed (f) after \" << state.n_iterations() <<\n\/\/ \" iterations for <\" << problem << \">, <\" << optimizer << \"> and <\" << x0.transpose() << \">!\");\n }\n\n static void check_convergence(const string_t& problem, const string_t& optimizer,\n const vector_t& x0, const scalar_t epsilon, const opt_state_t& state)\n {\n \/\/ check convergence\n const scalar_t dg = state.convergence_criteria();\n BOOST_CHECK_LE(dg, epsilon);\n\n \/\/ debugging\n BOOST_CHECK_MESSAGE(\n dg < epsilon,\n \"failed (g) for <\" << problem << \", \" << optimizer <<\n \">: x0 = \" << x0.transpose() << \", iters = \" << state.n_iterations() << \"!\");\n }\n\n static void check_problem(\n const string_t& problem_name,\n const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,\n const std::vector<std::pair<vector_t, scalar_t>>& solutions)\n {\n const size_t iterations = 1024 * 1024;\n const scalar_t epsilon = 1e-6;\n const size_t trials = 16 * 1024;\n\n const size_t dims = fn_size();\n\n random_t<scalar_t> rgen(-1.0, +1.0);\n\n \/\/ generate fixed random trials\n vectors_t x0s;\n for (size_t t = 0; t < trials; t ++)\n {\n vector_t x0(dims);\n rgen(x0.data(), x0.data() + x0.size());\n\n x0s.push_back(x0);\n }\n\n \/\/ optimizers to try\n const auto optimizers =\n {\n min::batch_optimizer::GD,\n\n min::batch_optimizer::CGD,\n min::batch_optimizer::CGD_CD,\n min::batch_optimizer::CGD_DY,\n min::batch_optimizer::CGD_FR,\n min::batch_optimizer::CGD_HS,\n min::batch_optimizer::CGD_LS,\n min::batch_optimizer::CGD_N,\n min::batch_optimizer::CGD_PRP,\n min::batch_optimizer::CGD_DYCD,\n min::batch_optimizer::CGD_DYHS,\n\n min::batch_optimizer::LBFGS\n };\n\n for (min::batch_optimizer optimizer : optimizers)\n {\n for (size_t t = 0; t < trials; t ++)\n {\n const vector_t& x0 = x0s[t];\n\n \/\/ optimize\n const opt_state_t state = ncv::minimize(\n fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,\n x0, optimizer, iterations, epsilon);\n\n \/\/ check result\n check_convergence(problem_name, text::to_string(optimizer), x0, epsilon, state);\n check_solution(problem_name, text::to_string(optimizer), x0, state, solutions);\n }\n }\n }\n\n static void check_problems(const std::vector<test::function_t>& funcs)\n {\n for (const test::function_t& func : funcs)\n {\n test::check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(test_optimizers)\n{\n using namespace ncv; \n\n test::check_problems(ncv::make_beale_funcs());\n test::check_problems(ncv::make_booth_funcs());\n test::check_problems(ncv::make_matyas_funcs());\n test::check_problems(ncv::make_trid_funcs(8));\n test::check_problems(ncv::make_sphere_funcs(8));\n test::check_problems(ncv::make_powell_funcs(8));\n test::check_problems(ncv::make_mccormick_funcs());\n test::check_problems(ncv::make_himmelblau_funcs());\n test::check_problems(ncv::make_rosenbrock_funcs(7));\n test::check_problems(ncv::make_3hump_camel_funcs());\n test::check_problems(ncv::make_dixon_price_funcs(8));\n test::check_problems(ncv::make_sum_squares_funcs(8));\n test::check_problems(ncv::make_goldstein_price_funcs());\n test::check_problems(ncv::make_rotated_ellipsoid_funcs(8));\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/Outer_Parameters.hxx\"\n#include \"setup_constraints.hxx\"\n\n#include \"..\/..\/ostream_set.hxx\"\n#include \"..\/..\/ostream_map.hxx\"\n#include \"..\/..\/ostream_vector.hxx\"\n#include \"..\/..\/set_stream_precision.hxx\"\n\nnamespace\n{\n void copy_matrix(const El::Matrix<El::BigFloat> &source,\n El::DistMatrix<El::BigFloat> &destination)\n {\n for(int64_t row(0); row < destination.LocalHeight(); ++row)\n {\n int64_t global_row(destination.GlobalRow(row));\n for(int64_t column(0); column < destination.LocalWidth(); ++column)\n {\n int64_t global_column(destination.GlobalCol(column));\n destination.SetLocal(row, column,\n source(global_row, global_column));\n }\n }\n }\n\n void\n copy_matrix(const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &source,\n El::Matrix<El::BigFloat> &destination)\n {\n destination.Resize(source.LocalHeight(), source.LocalWidth());\n for(int64_t row(0); row < source.LocalHeight(); ++row)\n {\n for(int64_t column(0); column < source.LocalWidth(); ++column)\n {\n destination(row, column) = source.GetLocal(row, column);\n }\n }\n }\n\n void fill_weights(const El::Matrix<El::BigFloat> &y, const size_t &max_index,\n const std::vector<El::BigFloat> &normalization,\n std::vector<El::BigFloat> &weights)\n {\n weights.at(max_index) = 1;\n for(size_t block_row(0); block_row != size_t(y.Height()); ++block_row)\n {\n const size_t index(block_row + (block_row < max_index ? 0 : 1));\n weights.at(index) = y(block_row, 0);\n weights.at(max_index) -= weights.at(index) * normalization.at(index);\n }\n weights.at(max_index) \/= normalization.at(max_index);\n }\n}\n\nvoid compute_y_transform(\n const std::vector<std::vector<std::vector<std::vector<Function>>>>\n &function_blocks,\n const std::vector<std::set<El::BigFloat>> &points,\n const std::vector<El::BigFloat> &objectives,\n const std::vector<El::BigFloat> &normalization,\n const Outer_Parameters ¶meters, const size_t &max_index,\n const El::Grid &global_grid,\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y,\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,\n El::BigFloat &primal_c_scale);\n\nboost::optional<int64_t> load_checkpoint(\n const boost::filesystem::path &checkpoint_directory,\n boost::optional<int64_t> &backup_generation, int64_t ¤t_generation,\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y_star,\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,\n El::Matrix<El::BigFloat> &y, std::vector<std::set<El::BigFloat>> &points,\n El::BigFloat &threshold, El::BigFloat &primal_c_scale);\n\nvoid find_new_points(\n const size_t &num_blocks, const size_t &rank, const size_t &num_procs,\n const El::BigFloat &infinity,\n const std::vector<std::vector<std::vector<std::vector<Function>>>>\n &function_blocks,\n const std::vector<El::BigFloat> &weights,\n const std::vector<std::set<El::BigFloat>> &points,\n std::vector<std::vector<El::BigFloat>> &new_points, bool &has_new_points);\n\nvoid save_checkpoint(\n const boost::filesystem::path &checkpoint_directory,\n const Verbosity &verbosity,\n const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y_star,\n const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,\n const El::Matrix<El::BigFloat> &y,\n const std::vector<std::set<El::BigFloat>> &points,\n const El::BigFloat &infinity, const El::BigFloat &threshold,\n const El::BigFloat &primal_c_scale,\n boost::optional<int64_t> &backup_generation, int64_t ¤t_generation);\n\nstd::vector<El::BigFloat> compute_optimal(\n const std::vector<std::vector<std::vector<std::vector<Function>>>>\n &function_blocks,\n const std::vector<std::vector<El::BigFloat>> &initial_points,\n const std::vector<El::BigFloat> &objectives,\n const std::vector<El::BigFloat> &normalization,\n const Outer_Parameters ¶meters_in)\n{\n if(initial_points.size() != function_blocks.size())\n {\n throw std::runtime_error(\n \"Size are different: Positive_Matrix_With_Prefactor: \"\n + std::to_string(function_blocks.size())\n + \", initial points: \" + std::to_string(initial_points.size()));\n }\n Outer_Parameters parameters(parameters_in);\n\n const size_t rank(El::mpi::Rank()), num_procs(El::mpi::Size()),\n num_weights(normalization.size());\n\n const size_t num_blocks(initial_points.size());\n std::vector<El::BigFloat> weights(num_weights, 0);\n std::vector<std::set<El::BigFloat>> points(num_blocks);\n std::vector<std::vector<El::BigFloat>> new_points(num_blocks);\n\n \/\/ GMP does not have a special infinity value, so we use max double.\n const El::BigFloat infinity(std::numeric_limits<double>::max());\n \/\/ Use the input points and add inifinty\n for(size_t block(0); block < num_blocks; ++block)\n {\n for(auto &point : initial_points.at(block))\n {\n points.at(block).emplace(point);\n }\n points.at(block).emplace(infinity);\n }\n\n \/\/ TODO: This is duplicated from sdp2input\/write_output\/write_output.cxx\n size_t max_index(0);\n El::BigFloat max_normalization(0);\n for(size_t index(0); index != normalization.size(); ++index)\n {\n const El::BigFloat element(Abs(normalization[index]));\n if(element > max_normalization)\n {\n max_normalization = element;\n max_index = index;\n }\n }\n\n const El::Grid global_grid;\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_to_y_star(global_grid),\n dual_objective_b_star(global_grid);\n El::BigFloat primal_c_scale;\n\n \/\/ TODO: Load checkpoint\n parameters.solver.duality_gap_threshold = 1.1;\n El::Matrix<El::BigFloat> yp_saved(yp_to_y_star.Height(), 1);\n El::Zero(yp_saved);\n\n int64_t current_generation(0);\n boost::optional<int64_t> backup_generation;\n load_checkpoint(parameters.solver.checkpoint_in, backup_generation,\n current_generation, yp_to_y_star, dual_objective_b_star,\n yp_saved, points, parameters.solver.duality_gap_threshold,\n primal_c_scale);\n if(backup_generation)\n {\n El::Matrix<El::BigFloat> y(yp_saved.Height(), 1);\n\n El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0),\n yp_to_y_star.LockedMatrix(), yp_saved, El::BigFloat(0.0), y);\n\n if(El::mpi::Rank() == 0 && parameters.verbosity >= Verbosity::regular)\n {\n std::cout << \"Loaded checkpoint \" << backup_generation << \"\\n\";\n }\n fill_weights(y, max_index, normalization, weights);\n }\n else\n {\n compute_y_transform(function_blocks, points, objectives, normalization,\n parameters, max_index, global_grid, yp_to_y_star,\n dual_objective_b_star, primal_c_scale);\n }\n\n while(parameters.solver.duality_gap_threshold\n > parameters_in.solver.duality_gap_threshold)\n {\n std::map<size_t, size_t> new_to_old;\n size_t num_constraints(0), old_index(0);\n std::vector<size_t> matrix_dimensions;\n for(size_t block(0); block != num_blocks; ++block)\n {\n for(size_t offset(0); offset != points.at(block).size(); ++offset)\n {\n new_to_old.emplace(num_constraints + offset, old_index + offset);\n }\n old_index += points.at(block).size();\n for(auto &point : new_points.at(block))\n {\n points.at(block).emplace(point);\n }\n num_constraints += points.at(block).size();\n matrix_dimensions.insert(matrix_dimensions.end(),\n points.at(block).size(),\n function_blocks[block].size());\n if(rank == 0 && parameters.verbosity >= Verbosity::debug)\n {\n std::cout << \"points: \" << block << \" \" << points.at(block)\n << \"\\n\";\n }\n }\n if(rank == 0 && parameters.verbosity >= Verbosity::regular)\n {\n std::cout << \"num_constraints: \" << num_constraints << \"\\n\";\n }\n\n std::vector<std::vector<El::BigFloat>> primal_objective_c;\n primal_objective_c.reserve(num_constraints);\n std::vector<El::Matrix<El::BigFloat>> free_var_matrix;\n free_var_matrix.reserve(num_constraints);\n\n setup_constraints(max_index, num_blocks, infinity, function_blocks,\n normalization, points, primal_objective_c,\n free_var_matrix);\n\n const El::BigFloat objective_const(objectives.at(max_index)\n \/ normalization.at(max_index));\n\n Block_Info block_info(matrix_dimensions, parameters.verbosity);\n\n El::Grid grid(block_info.mpi_comm.value);\n\n SDP sdp(objective_const, primal_objective_c, free_var_matrix,\n yp_to_y_star, dual_objective_b_star, primal_c_scale, block_info,\n grid);\n\n SDP_Solver solver(parameters.solver, parameters.verbosity,\n parameters.require_initial_checkpoint, block_info,\n grid, sdp.dual_objective_b.Height());\n\n for(auto &y_block : solver.y.blocks)\n {\n copy_matrix(yp_saved, y_block);\n }\n\n boost::property_tree::ptree parameter_properties(\n to_property_tree(parameters));\n bool has_new_points(false);\n while(!has_new_points\n && parameters.solver.duality_gap_threshold\n > parameters_in.solver.duality_gap_threshold)\n {\n if(rank == 0 && parameters.verbosity >= Verbosity::regular)\n {\n std::cout << \"Threshold: \"\n << parameters.solver.duality_gap_threshold << \"\\n\";\n }\n\n Timers timers(parameters.verbosity >= Verbosity::debug);\n SDP_Solver_Terminate_Reason reason\n = solver.run(parameters.solver, parameters.verbosity,\n parameter_properties, block_info, sdp, grid, timers);\n\n if(rank == 0 && parameters.verbosity >= Verbosity::regular)\n {\n set_stream_precision(std::cout);\n std::cout << \"-----\" << reason << \"-----\\n\"\n << '\\n'\n << \"primalObjective = \" << solver.primal_objective\n << '\\n'\n << \"dualObjective = \" << solver.dual_objective\n << '\\n'\n << \"dualityGap = \" << solver.duality_gap << '\\n'\n << \"primalError = \" << solver.primal_error()\n << '\\n'\n << \"dualError = \" << solver.dual_error << '\\n'\n << '\\n';\n }\n\n if(reason == SDP_Solver_Terminate_Reason::MaxComplementarityExceeded\n || reason == SDP_Solver_Terminate_Reason::MaxIterationsExceeded\n || reason == SDP_Solver_Terminate_Reason::MaxRuntimeExceeded)\n {\n std::stringstream ss;\n ss << \"Can not find solution: \" << reason;\n throw std::runtime_error(ss.str());\n }\n\n \/\/ y is duplicated among cores, so only need to print out copy on\n \/\/ the root node.\n \/\/ THe weight at max_index is determined by the normalization\n \/\/ condition dot(norm,weights)=1\n El::DistMatrix<El::BigFloat> yp(dual_objective_b_star.Height(), 1,\n yp_to_y_star.Grid());\n El::Zero(yp);\n El::DistMatrix<El::BigFloat> y(yp);\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(\n solver.y.blocks.at(0));\n for(int64_t row(0); row != yp.LocalHeight(); ++row)\n {\n int64_t global_row(yp.GlobalRow(row));\n for(int64_t column(0); column != yp.LocalWidth(); ++column)\n {\n int64_t global_column(yp.GlobalCol(column));\n yp.SetLocal(row, column,\n yp_star.GetLocal(global_row, global_column));\n }\n }\n El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0), yp_to_y_star,\n yp, El::BigFloat(0.0), y);\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> y_star(y);\n\n fill_weights(y_star.LockedMatrix(), max_index, normalization,\n weights);\n if(rank == 0 && parameters.verbosity >= Verbosity::regular)\n {\n set_stream_precision(std::cout);\n std::cout << \"weight: \" << weights << \"\\n\";\n\n El::BigFloat optimal(0);\n for(size_t index(0); index < objectives.size(); ++index)\n {\n optimal += objectives[index] * weights[index];\n }\n std::cout << \"optimal: \" << optimal << \"\\n\";\n }\n find_new_points(num_blocks, rank, num_procs, infinity,\n function_blocks, weights, points, new_points,\n has_new_points);\n if(!has_new_points)\n {\n parameters.solver.duality_gap_threshold\n \/= parameters.duality_gap_reduction;\n }\n }\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(\n solver.y.blocks.front());\n copy_matrix(yp_star, yp_saved);\n save_checkpoint(parameters.solver.checkpoint_out, parameters.verbosity,\n yp_to_y_star, dual_objective_b_star, yp_saved, points,\n infinity, parameters.solver.duality_gap_threshold,\n primal_c_scale, backup_generation, current_generation);\n }\n return weights;\n}\n<commit_msg>Remove lots of redundant copies<commit_after>#include \"..\/Outer_Parameters.hxx\"\n#include \"setup_constraints.hxx\"\n\n#include \"..\/..\/ostream_set.hxx\"\n#include \"..\/..\/ostream_map.hxx\"\n#include \"..\/..\/ostream_vector.hxx\"\n#include \"..\/..\/set_stream_precision.hxx\"\n\nnamespace\n{\n void copy_matrix(const El::Matrix<El::BigFloat> &source,\n El::DistMatrix<El::BigFloat> &destination)\n {\n for(int64_t row(0); row < destination.LocalHeight(); ++row)\n {\n int64_t global_row(destination.GlobalRow(row));\n for(int64_t column(0); column < destination.LocalWidth(); ++column)\n {\n int64_t global_column(destination.GlobalCol(column));\n destination.SetLocal(row, column,\n source(global_row, global_column));\n }\n }\n }\n\n void\n copy_matrix(const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &source,\n El::Matrix<El::BigFloat> &destination)\n {\n destination.Resize(source.LocalHeight(), source.LocalWidth());\n for(int64_t row(0); row < source.LocalHeight(); ++row)\n {\n for(int64_t column(0); column < source.LocalWidth(); ++column)\n {\n destination(row, column) = source.GetLocal(row, column);\n }\n }\n }\n\n void fill_weights(const El::Matrix<El::BigFloat> &y, const size_t &max_index,\n const std::vector<El::BigFloat> &normalization,\n std::vector<El::BigFloat> &weights)\n {\n \/\/ THe weight at max_index is determined by the normalization\n \/\/ condition dot(norm,weights)=1\n weights.at(max_index) = 1;\n for(size_t block_row(0); block_row != size_t(y.Height()); ++block_row)\n {\n const size_t index(block_row + (block_row < max_index ? 0 : 1));\n weights.at(index) = y(block_row, 0);\n weights.at(max_index) -= weights.at(index) * normalization.at(index);\n }\n weights.at(max_index) \/= normalization.at(max_index);\n }\n}\n\nvoid compute_y_transform(\n const std::vector<std::vector<std::vector<std::vector<Function>>>>\n &function_blocks,\n const std::vector<std::set<El::BigFloat>> &points,\n const std::vector<El::BigFloat> &objectives,\n const std::vector<El::BigFloat> &normalization,\n const Outer_Parameters ¶meters, const size_t &max_index,\n const El::Grid &global_grid,\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y,\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,\n El::BigFloat &primal_c_scale);\n\nboost::optional<int64_t> load_checkpoint(\n const boost::filesystem::path &checkpoint_directory,\n boost::optional<int64_t> &backup_generation, int64_t ¤t_generation,\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y_star,\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,\n El::Matrix<El::BigFloat> &y, std::vector<std::set<El::BigFloat>> &points,\n El::BigFloat &threshold, El::BigFloat &primal_c_scale);\n\nvoid find_new_points(\n const size_t &num_blocks, const size_t &rank, const size_t &num_procs,\n const El::BigFloat &infinity,\n const std::vector<std::vector<std::vector<std::vector<Function>>>>\n &function_blocks,\n const std::vector<El::BigFloat> &weights,\n const std::vector<std::set<El::BigFloat>> &points,\n std::vector<std::vector<El::BigFloat>> &new_points, bool &has_new_points);\n\nvoid save_checkpoint(\n const boost::filesystem::path &checkpoint_directory,\n const Verbosity &verbosity,\n const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y_star,\n const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,\n const El::Matrix<El::BigFloat> &y,\n const std::vector<std::set<El::BigFloat>> &points,\n const El::BigFloat &infinity, const El::BigFloat &threshold,\n const El::BigFloat &primal_c_scale,\n boost::optional<int64_t> &backup_generation, int64_t ¤t_generation);\n\nstd::vector<El::BigFloat> compute_optimal(\n const std::vector<std::vector<std::vector<std::vector<Function>>>>\n &function_blocks,\n const std::vector<std::vector<El::BigFloat>> &initial_points,\n const std::vector<El::BigFloat> &objectives,\n const std::vector<El::BigFloat> &normalization,\n const Outer_Parameters ¶meters_in)\n{\n if(initial_points.size() != function_blocks.size())\n {\n throw std::runtime_error(\n \"Size are different: Positive_Matrix_With_Prefactor: \"\n + std::to_string(function_blocks.size())\n + \", initial points: \" + std::to_string(initial_points.size()));\n }\n Outer_Parameters parameters(parameters_in);\n\n const size_t rank(El::mpi::Rank()), num_procs(El::mpi::Size()),\n num_weights(normalization.size());\n\n const size_t num_blocks(initial_points.size());\n std::vector<El::BigFloat> weights(num_weights, 0);\n std::vector<std::set<El::BigFloat>> points(num_blocks);\n std::vector<std::vector<El::BigFloat>> new_points(num_blocks);\n\n \/\/ GMP does not have a special infinity value, so we use max double.\n const El::BigFloat infinity(std::numeric_limits<double>::max());\n \/\/ Use the input points and add inifinty\n for(size_t block(0); block < num_blocks; ++block)\n {\n for(auto &point : initial_points.at(block))\n {\n points.at(block).emplace(point);\n }\n points.at(block).emplace(infinity);\n }\n\n \/\/ TODO: This is duplicated from sdp2input\/write_output\/write_output.cxx\n size_t max_index(0);\n El::BigFloat max_normalization(0);\n for(size_t index(0); index != normalization.size(); ++index)\n {\n const El::BigFloat element(Abs(normalization[index]));\n if(element > max_normalization)\n {\n max_normalization = element;\n max_index = index;\n }\n }\n\n const El::Grid global_grid;\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_to_y_star(global_grid),\n dual_objective_b_star(global_grid);\n El::BigFloat primal_c_scale;\n\n parameters.solver.duality_gap_threshold = 1.1;\n El::Matrix<El::BigFloat> yp_saved(yp_to_y_star.Height(), 1);\n El::Zero(yp_saved);\n\n int64_t current_generation(0);\n boost::optional<int64_t> backup_generation;\n load_checkpoint(parameters.solver.checkpoint_in, backup_generation,\n current_generation, yp_to_y_star, dual_objective_b_star,\n yp_saved, points, parameters.solver.duality_gap_threshold,\n primal_c_scale);\n if(backup_generation)\n {\n El::Matrix<El::BigFloat> y(yp_saved.Height(), 1);\n\n El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0),\n yp_to_y_star.LockedMatrix(), yp_saved, El::BigFloat(0.0), y);\n\n if(El::mpi::Rank() == 0 && parameters.verbosity >= Verbosity::regular)\n {\n std::cout << \"Loaded checkpoint \" << backup_generation << \"\\n\";\n }\n fill_weights(y, max_index, normalization, weights);\n }\n else\n {\n compute_y_transform(function_blocks, points, objectives, normalization,\n parameters, max_index, global_grid, yp_to_y_star,\n dual_objective_b_star, primal_c_scale);\n }\n\n while(parameters.solver.duality_gap_threshold\n > parameters_in.solver.duality_gap_threshold)\n {\n std::map<size_t, size_t> new_to_old;\n size_t num_constraints(0), old_index(0);\n std::vector<size_t> matrix_dimensions;\n for(size_t block(0); block != num_blocks; ++block)\n {\n for(size_t offset(0); offset != points.at(block).size(); ++offset)\n {\n new_to_old.emplace(num_constraints + offset, old_index + offset);\n }\n old_index += points.at(block).size();\n for(auto &point : new_points.at(block))\n {\n points.at(block).emplace(point);\n }\n num_constraints += points.at(block).size();\n matrix_dimensions.insert(matrix_dimensions.end(),\n points.at(block).size(),\n function_blocks[block].size());\n if(rank == 0 && parameters.verbosity >= Verbosity::debug)\n {\n std::cout << \"points: \" << block << \" \" << points.at(block)\n << \"\\n\";\n }\n }\n if(rank == 0 && parameters.verbosity >= Verbosity::regular)\n {\n std::cout << \"num_constraints: \" << num_constraints << \"\\n\";\n }\n\n std::vector<std::vector<El::BigFloat>> primal_objective_c;\n primal_objective_c.reserve(num_constraints);\n std::vector<El::Matrix<El::BigFloat>> free_var_matrix;\n free_var_matrix.reserve(num_constraints);\n\n setup_constraints(max_index, num_blocks, infinity, function_blocks,\n normalization, points, primal_objective_c,\n free_var_matrix);\n\n const El::BigFloat objective_const(objectives.at(max_index)\n \/ normalization.at(max_index));\n\n Block_Info block_info(matrix_dimensions, parameters.verbosity);\n\n El::Grid grid(block_info.mpi_comm.value);\n\n SDP sdp(objective_const, primal_objective_c, free_var_matrix,\n yp_to_y_star, dual_objective_b_star, primal_c_scale, block_info,\n grid);\n\n SDP_Solver solver(parameters.solver, parameters.verbosity,\n parameters.require_initial_checkpoint, block_info,\n grid, sdp.dual_objective_b.Height());\n\n for(auto &y_block : solver.y.blocks)\n {\n copy_matrix(yp_saved, y_block);\n }\n\n boost::property_tree::ptree parameter_properties(\n to_property_tree(parameters));\n bool has_new_points(false);\n while(!has_new_points\n && parameters.solver.duality_gap_threshold\n > parameters_in.solver.duality_gap_threshold)\n {\n if(rank == 0 && parameters.verbosity >= Verbosity::regular)\n {\n std::cout << \"Threshold: \"\n << parameters.solver.duality_gap_threshold << \"\\n\";\n }\n\n Timers timers(parameters.verbosity >= Verbosity::debug);\n SDP_Solver_Terminate_Reason reason\n = solver.run(parameters.solver, parameters.verbosity,\n parameter_properties, block_info, sdp, grid, timers);\n\n if(rank == 0 && parameters.verbosity >= Verbosity::regular)\n {\n set_stream_precision(std::cout);\n std::cout << \"-----\" << reason << \"-----\\n\"\n << '\\n'\n << \"primalObjective = \" << solver.primal_objective\n << '\\n'\n << \"dualObjective = \" << solver.dual_objective\n << '\\n'\n << \"dualityGap = \" << solver.duality_gap << '\\n'\n << \"primalError = \" << solver.primal_error()\n << '\\n'\n << \"dualError = \" << solver.dual_error << '\\n'\n << '\\n';\n }\n\n if(reason == SDP_Solver_Terminate_Reason::MaxComplementarityExceeded\n || reason == SDP_Solver_Terminate_Reason::MaxIterationsExceeded\n || reason == SDP_Solver_Terminate_Reason::MaxRuntimeExceeded)\n {\n std::stringstream ss;\n ss << \"Can not find solution: \" << reason;\n throw std::runtime_error(ss.str());\n }\n\n El::Matrix<El::BigFloat> y(dual_objective_b_star.Height(), 1);\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(\n solver.y.blocks.at(0));\n\n El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0),\n yp_to_y_star.LockedMatrix(), yp_star.LockedMatrix(),\n El::BigFloat(0.0), y);\n\n fill_weights(y, max_index, normalization, weights);\n if(rank == 0 && parameters.verbosity >= Verbosity::regular)\n {\n set_stream_precision(std::cout);\n std::cout << \"weight: \" << weights << \"\\n\";\n\n El::BigFloat optimal(0);\n for(size_t index(0); index < objectives.size(); ++index)\n {\n optimal += objectives[index] * weights[index];\n }\n std::cout << \"optimal: \" << optimal << \"\\n\";\n }\n find_new_points(num_blocks, rank, num_procs, infinity,\n function_blocks, weights, points, new_points,\n has_new_points);\n if(!has_new_points)\n {\n parameters.solver.duality_gap_threshold\n \/= parameters.duality_gap_reduction;\n }\n }\n El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(\n solver.y.blocks.front());\n copy_matrix(yp_star, yp_saved);\n save_checkpoint(parameters.solver.checkpoint_out, parameters.verbosity,\n yp_to_y_star, dual_objective_b_star, yp_saved, points,\n infinity, parameters.solver.duality_gap_threshold,\n primal_c_scale, backup_generation, current_generation);\n }\n return weights;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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 * @file frame.cc\n **\/\n#include \"modules\/planning\/common\/frame.h\"\n\n#include <cmath>\n#include <list>\n#include <string>\n#include <utility>\n\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/vec2d.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/map\/pnc_map\/pnc_map.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/reference_line\/reference_line_smoother.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::adapter::AdapterManager;\n\nconst hdmap::PncMap *Frame::pnc_map_ = nullptr;\n\nvoid Frame::SetMap(hdmap::PncMap *pnc_map) { pnc_map_ = pnc_map; }\n\nFrameHistory::FrameHistory()\n : IndexedQueue<uint32_t, Frame>(FLAGS_max_history_frame_num) {}\n\nFrame::Frame(const uint32_t sequence_num) : sequence_num_(sequence_num) {}\n\nvoid Frame::SetVehicleInitPose(const localization::Pose &pose) {\n init_pose_ = pose;\n}\n\nconst localization::Pose &Frame::VehicleInitPose() const { return init_pose_; }\n\nvoid Frame::SetRoutingResponse(const routing::RoutingResponse &routing) {\n routing_response_ = routing;\n}\n\nvoid Frame::SetPlanningStartPoint(const common::TrajectoryPoint &start_point) {\n planning_start_point_ = start_point;\n}\n\nconst hdmap::PncMap *Frame::PncMap() {\n DCHECK(pnc_map_) << \"map is not setup in frame\";\n return pnc_map_;\n}\n\nconst common::TrajectoryPoint &Frame::PlanningStartPoint() const {\n return planning_start_point_;\n}\n\nvoid Frame::SetPrediction(const prediction::PredictionObstacles &prediction) {\n prediction_ = prediction;\n}\n\nvoid Frame::CreatePredictionObstacles(\n const prediction::PredictionObstacles &prediction) {\n std::list<std::unique_ptr<Obstacle> > obstacles;\n Obstacle::CreateObstacles(prediction, &obstacles);\n for (auto &ptr : obstacles) {\n auto id(ptr->Id());\n obstacles_.Add(id, std::move(ptr));\n }\n}\n\nbool Frame::CreateDestinationObstacle() {\n \/\/ set destination point\n if (!routing_response_.routing_request().has_end()) {\n ADEBUG << \"routing_request has no end\";\n return false;\n }\n common::math::Vec2d destination;\n destination.set_x(routing_response_.routing_request().end().pose().x());\n destination.set_y(routing_response_.routing_request().end().pose().y());\n\n \/\/ check if destination point is in planning range\n common::SLPoint destination_sl;\n reference_line_.get_point_in_frenet_frame(destination, &destination_sl);\n double destination_s = destination_sl.s();\n if (destination_s < 0 || destination_s > reference_line_.length()) {\n AINFO << \"destination(s[:\" << destination_sl.s()\n << \"]) out of planning range. Skip\";\n return true;\n }\n\n \/\/ adjust destination based on adc_front_s\n common::SLPoint adc_sl;\n auto& adc_position = common::VehicleState::instance()->pose().position();\n reference_line_.get_point_in_frenet_frame(\n {adc_position.x(), adc_position.y()}, &adc_sl);\n const auto& vehicle_param =\n common::VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n double adc_front_s = adc_sl.s() + vehicle_param.front_edge_to_center();\n if (destination_sl.s() <= adc_front_s) {\n destination_s = adc_front_s + FLAGS_destination_adjust_distance_buffer;\n }\n\n std::unique_ptr<Obstacle> obstacle_ptr = CreateVirtualObstacle(\n FLAGS_destination_obstacle_id,\n destination_s,\n FLAGS_virtual_stop_wall_length,\n FLAGS_virtual_stop_wall_width,\n FLAGS_virtual_stop_wall_height);\n\n obstacles_.Add(FLAGS_destination_obstacle_id, std::move(obstacle_ptr));\n\n return true;\n}\n\nconst ADCTrajectory &Frame::GetADCTrajectory() const { return trajectory_pb_; }\n\nADCTrajectory *Frame::MutableADCTrajectory() { return &trajectory_pb_; }\n\nPathDecision *Frame::path_decision() { return path_decision_; }\n\nstd::vector<ReferenceLineInfo> &Frame::reference_line_info() {\n return reference_line_info_;\n}\n\nbool Frame::InitReferenceLineInfo(\n const std::vector<ReferenceLine> &reference_lines) {\n reference_line_info_.clear();\n for (const auto &reference_line : reference_lines) {\n reference_line_info_.emplace_back(reference_line);\n auto &info = reference_line_info_.back();\n if (!info.AddObstacles(obstacles_.Items())) {\n AERROR << \"Failed to add obstacles to reference line\";\n return false;\n }\n }\n return true;\n}\n\nbool Frame::Init(const PlanningConfig &config) {\n if (!pnc_map_) {\n AERROR << \"map is null, call SetMap() first\";\n return false;\n }\n const auto &point = init_pose_.position();\n if (std::isnan(point.x()) || std::isnan(point.y())) {\n AERROR << \"init point is not set\";\n return false;\n }\n smoother_config_ = config.reference_line_smoother_config();\n std::vector<ReferenceLine> reference_lines;\n if (!CreateReferenceLineFromRouting(init_pose_.position(), routing_response_,\n &reference_lines)) {\n AERROR << \"Failed to create reference line from position: \"\n << init_pose_.DebugString();\n return false;\n }\n\n if (FLAGS_enable_prediction) {\n CreatePredictionObstacles(prediction_);\n }\n\n CreateDestinationObstacle();\n\n InitReferenceLineInfo(reference_lines);\n reference_line_ = reference_lines.front();\n\n \/\/ FIXME(all) remove path decision from Frame.\n path_decision_ = reference_line_info_[0].path_decision();\n CHECK(path_decision_->path_obstacles().Items().size() > 0);\n\n if (FLAGS_enable_traffic_decision) {\n MakeTrafficDecision(routing_response_, reference_line_);\n }\n\n return true;\n}\n\nuint32_t Frame::sequence_num() const { return sequence_num_; }\n\nconst PlanningData &Frame::planning_data() const { return _planning_data; }\n\nPlanningData *Frame::mutable_planning_data() { return &_planning_data; }\n\nconst ReferenceLine &Frame::reference_line() const { return reference_line_; }\n\nbool Frame::MakeTrafficDecision(const routing::RoutingResponse &routing,\n const ReferenceLine &reference_line) {\n const auto &path_obstacles = path_decision_->path_obstacles();\n for (const auto path_obstacle : path_obstacles.Items()) {\n const auto &obstacle = path_obstacle->Obstacle();\n\n \/\/ destination stop\n if (obstacle->Id() == FLAGS_destination_obstacle_id) {\n \/\/ check stop_posision on reference line\n auto stop_position = obstacle->Perception().position();\n common::SLPoint stop_line_sl;\n reference_line.get_point_in_frenet_frame(\n { stop_position.x(), stop_position.x()}, &stop_line_sl);\n if (!reference_line.is_on_road(stop_line_sl)) {\n continue;\n }\n\n \/\/ check stop_line_s vs adc_s. stop_line_s must be ahead of adc_front_s\n common::SLPoint adc_sl;\n auto& adc_position = common::VehicleState::instance()->pose().position();\n reference_line.get_point_in_frenet_frame(\n {adc_position.x(), adc_position.y()}, &adc_sl);\n const auto& vehicle_param =\n common::VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n double adc_front_s = adc_sl.s() + vehicle_param.front_edge_to_center();\n if (stop_line_sl.s() <= adc_front_s) {\n ADEBUG << \"skip: object:\" << obstacle->Id() << \" fence route_s[\"\n << stop_line_sl.s() << \"] behind adc_front_s[\"\n << adc_front_s << \"]\";\n continue;\n }\n\n ObjectDecisionType object_stop;\n ObjectStop *object_stop_ptr = object_stop.mutable_stop();\n object_stop_ptr->set_distance_s(FLAGS_stop_line_min_distance);\n object_stop_ptr->set_reason_code(\n StopReasonCode::STOP_REASON_DESTINATION);\n\n auto stop_ref_point = reference_line_.get_reference_point(\n stop_position.x(), stop_position.y());\n object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x());\n object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y());\n object_stop_ptr->set_stop_heading(stop_ref_point.heading());\n\n path_decision_->AddLongitudinalDecision(\"TBD\", obstacle->Id(),\n object_stop);\n }\n }\n\n return true;\n}\n\nbool Frame::CreateReferenceLineFromRouting(\n const common::PointENU &position, const routing::RoutingResponse &routing,\n std::vector<ReferenceLine> *reference_lines) {\n CHECK_NOTNULL(reference_lines);\n\n hdmap::Path hdmap_path;\n if (!pnc_map_->CreatePathFromRouting(\n routing, position, FLAGS_look_backward_distance,\n FLAGS_look_forward_distance, &hdmap_path)) {\n AERROR << \"Failed to get path from routing\";\n return false;\n }\n reference_lines->emplace_back(ReferenceLine());\n ReferenceLineSmoother smoother;\n smoother.Init(smoother_config_);\n if (!smoother.smooth(ReferenceLine(hdmap_path), &reference_lines->back())) {\n AERROR << \"Failed to smooth reference line\";\n return false;\n }\n return true;\n}\n\nconst IndexedObstacles &Frame::GetObstacles() const { return obstacles_; }\n\nstd::string Frame::DebugString() const {\n return \"Frame: \" + std::to_string(sequence_num_);\n}\n\nvoid Frame::RecordInputDebug() {\n if (!FLAGS_enable_record_debug) {\n ADEBUG << \"Skip record input into debug\";\n return;\n }\n auto planning_data = trajectory_pb_.mutable_debug()->mutable_planning_data();\n auto adc_position = planning_data->mutable_adc_position();\n const auto &localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n adc_position->CopyFrom(localization);\n\n const auto &chassis = AdapterManager::GetChassis()->GetLatestObserved();\n auto debug_chassis = planning_data->mutable_chassis();\n debug_chassis->CopyFrom(chassis);\n\n const auto &routing_response =\n AdapterManager::GetRoutingResponse()->GetLatestObserved();\n\n auto debug_routing = planning_data->mutable_routing();\n debug_routing->CopyFrom(routing_response);\n}\n\nvoid Frame::AlignPredictionTime(const double trajectory_header_time) {\n double prediction_header_time = prediction_.header().timestamp_sec();\n\n for (int i = 0; i < prediction_.prediction_obstacle_size(); i++) {\n prediction::PredictionObstacle *obstacle =\n prediction_.mutable_prediction_obstacle(i);\n for (int j = 0; j < obstacle->trajectory_size(); j++) {\n prediction::Trajectory *trajectory = obstacle->mutable_trajectory(j);\n for (int k = 0; k < trajectory->trajectory_point_size(); k++) {\n common::TrajectoryPoint *point =\n trajectory->mutable_trajectory_point(k);\n double abs_relative_time = point->relative_time();\n point->set_relative_time(prediction_header_time + abs_relative_time -\n trajectory_header_time);\n }\n }\n }\n}\n\nstd::unique_ptr<Obstacle> Frame::CreateVirtualObstacle(\n const std::string &obstacle_id,\n const double route_s,\n const double length, const double width, const double height) {\n std::unique_ptr<Obstacle> obstacle_ptr(nullptr);\n\n \/\/ create a \"virtual\" perception_obstacle\n perception::PerceptionObstacle perception_obstacle;\n perception_obstacle.set_id(-1); \/\/ simulator needs a valid integer\n auto dest_ref_point =\n reference_line_.get_reference_point(route_s);\n perception_obstacle.mutable_position()->set_x(dest_ref_point.x());\n perception_obstacle.mutable_position()->set_y(dest_ref_point.y());\n perception_obstacle.set_theta(dest_ref_point.heading());\n perception_obstacle.mutable_velocity()->set_x(0);\n perception_obstacle.mutable_velocity()->set_y(0);\n perception_obstacle.set_length(length);\n perception_obstacle.set_width(length);\n perception_obstacle.set_height(length);\n perception_obstacle.set_type(\n perception::PerceptionObstacle::UNKNOWN_UNMOVABLE);\n perception_obstacle.set_tracking_time(1.0);\n\n obstacle_ptr.reset(new Obstacle(obstacle_id, perception_obstacle));\n return obstacle_ptr;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: move destination after reference line. (#955)<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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 * @file frame.cc\n **\/\n#include \"modules\/planning\/common\/frame.h\"\n\n#include <cmath>\n#include <list>\n#include <string>\n#include <utility>\n\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/vec2d.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/map\/pnc_map\/pnc_map.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/reference_line\/reference_line_smoother.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::adapter::AdapterManager;\n\nconst hdmap::PncMap *Frame::pnc_map_ = nullptr;\n\nvoid Frame::SetMap(hdmap::PncMap *pnc_map) { pnc_map_ = pnc_map; }\n\nFrameHistory::FrameHistory()\n : IndexedQueue<uint32_t, Frame>(FLAGS_max_history_frame_num) {}\n\nFrame::Frame(const uint32_t sequence_num) : sequence_num_(sequence_num) {}\n\nvoid Frame::SetVehicleInitPose(const localization::Pose &pose) {\n init_pose_ = pose;\n}\n\nconst localization::Pose &Frame::VehicleInitPose() const { return init_pose_; }\n\nvoid Frame::SetRoutingResponse(const routing::RoutingResponse &routing) {\n routing_response_ = routing;\n}\n\nvoid Frame::SetPlanningStartPoint(const common::TrajectoryPoint &start_point) {\n planning_start_point_ = start_point;\n}\n\nconst hdmap::PncMap *Frame::PncMap() {\n DCHECK(pnc_map_) << \"map is not setup in frame\";\n return pnc_map_;\n}\n\nconst common::TrajectoryPoint &Frame::PlanningStartPoint() const {\n return planning_start_point_;\n}\n\nvoid Frame::SetPrediction(const prediction::PredictionObstacles &prediction) {\n prediction_ = prediction;\n}\n\nvoid Frame::CreatePredictionObstacles(\n const prediction::PredictionObstacles &prediction) {\n std::list<std::unique_ptr<Obstacle> > obstacles;\n Obstacle::CreateObstacles(prediction, &obstacles);\n for (auto &ptr : obstacles) {\n auto id(ptr->Id());\n obstacles_.Add(id, std::move(ptr));\n }\n}\n\nbool Frame::CreateDestinationObstacle() {\n \/\/ set destination point\n if (!routing_response_.routing_request().has_end()) {\n ADEBUG << \"routing_request has no end\";\n return false;\n }\n common::math::Vec2d destination;\n destination.set_x(routing_response_.routing_request().end().pose().x());\n destination.set_y(routing_response_.routing_request().end().pose().y());\n\n \/\/ check if destination point is in planning range\n common::SLPoint destination_sl;\n reference_line_.get_point_in_frenet_frame(destination, &destination_sl);\n double destination_s = destination_sl.s();\n if (destination_s < 0 || destination_s > reference_line_.length()) {\n AINFO << \"destination(s[:\" << destination_sl.s()\n << \"]) out of planning range. Skip\";\n return true;\n }\n\n \/\/ adjust destination based on adc_front_s\n common::SLPoint adc_sl;\n auto& adc_position = common::VehicleState::instance()->pose().position();\n reference_line_.get_point_in_frenet_frame(\n {adc_position.x(), adc_position.y()}, &adc_sl);\n const auto& vehicle_param =\n common::VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n double adc_front_s = adc_sl.s() + vehicle_param.front_edge_to_center();\n if (destination_sl.s() <= adc_front_s) {\n destination_s = adc_front_s + FLAGS_destination_adjust_distance_buffer;\n }\n\n std::unique_ptr<Obstacle> obstacle_ptr = CreateVirtualObstacle(\n FLAGS_destination_obstacle_id,\n destination_s,\n FLAGS_virtual_stop_wall_length,\n FLAGS_virtual_stop_wall_width,\n FLAGS_virtual_stop_wall_height);\n\n obstacles_.Add(FLAGS_destination_obstacle_id, std::move(obstacle_ptr));\n\n return true;\n}\n\nconst ADCTrajectory &Frame::GetADCTrajectory() const { return trajectory_pb_; }\n\nADCTrajectory *Frame::MutableADCTrajectory() { return &trajectory_pb_; }\n\nPathDecision *Frame::path_decision() { return path_decision_; }\n\nstd::vector<ReferenceLineInfo> &Frame::reference_line_info() {\n return reference_line_info_;\n}\n\nbool Frame::InitReferenceLineInfo(\n const std::vector<ReferenceLine> &reference_lines) {\n reference_line_info_.clear();\n for (const auto &reference_line : reference_lines) {\n reference_line_info_.emplace_back(reference_line);\n auto &info = reference_line_info_.back();\n if (!info.AddObstacles(obstacles_.Items())) {\n AERROR << \"Failed to add obstacles to reference line\";\n return false;\n }\n }\n return true;\n}\n\nbool Frame::Init(const PlanningConfig &config) {\n if (!pnc_map_) {\n AERROR << \"map is null, call SetMap() first\";\n return false;\n }\n const auto &point = init_pose_.position();\n if (std::isnan(point.x()) || std::isnan(point.y())) {\n AERROR << \"init point is not set\";\n return false;\n }\n smoother_config_ = config.reference_line_smoother_config();\n std::vector<ReferenceLine> reference_lines;\n if (!CreateReferenceLineFromRouting(init_pose_.position(), routing_response_,\n &reference_lines)) {\n AERROR << \"Failed to create reference line from position: \"\n << init_pose_.DebugString();\n return false;\n }\n\n if (FLAGS_enable_prediction) {\n CreatePredictionObstacles(prediction_);\n }\n\n InitReferenceLineInfo(reference_lines);\n reference_line_ = reference_lines.front();\n\n CreateDestinationObstacle();\n\n \/\/ FIXME(all) remove path decision from Frame.\n path_decision_ = reference_line_info_[0].path_decision();\n CHECK(path_decision_->path_obstacles().Items().size() > 0);\n\n if (FLAGS_enable_traffic_decision) {\n MakeTrafficDecision(routing_response_, reference_line_);\n }\n\n return true;\n}\n\nuint32_t Frame::sequence_num() const { return sequence_num_; }\n\nconst PlanningData &Frame::planning_data() const { return _planning_data; }\n\nPlanningData *Frame::mutable_planning_data() { return &_planning_data; }\n\nconst ReferenceLine &Frame::reference_line() const { return reference_line_; }\n\nbool Frame::MakeTrafficDecision(const routing::RoutingResponse &routing,\n const ReferenceLine &reference_line) {\n const auto &path_obstacles = path_decision_->path_obstacles();\n for (const auto path_obstacle : path_obstacles.Items()) {\n const auto &obstacle = path_obstacle->Obstacle();\n\n \/\/ destination stop\n if (obstacle->Id() == FLAGS_destination_obstacle_id) {\n \/\/ check stop_posision on reference line\n auto stop_position = obstacle->Perception().position();\n common::SLPoint stop_line_sl;\n reference_line.get_point_in_frenet_frame(\n { stop_position.x(), stop_position.x()}, &stop_line_sl);\n if (!reference_line.is_on_road(stop_line_sl)) {\n continue;\n }\n\n \/\/ check stop_line_s vs adc_s. stop_line_s must be ahead of adc_front_s\n common::SLPoint adc_sl;\n auto& adc_position = common::VehicleState::instance()->pose().position();\n reference_line.get_point_in_frenet_frame(\n {adc_position.x(), adc_position.y()}, &adc_sl);\n const auto& vehicle_param =\n common::VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n double adc_front_s = adc_sl.s() + vehicle_param.front_edge_to_center();\n if (stop_line_sl.s() <= adc_front_s) {\n ADEBUG << \"skip: object:\" << obstacle->Id() << \" fence route_s[\"\n << stop_line_sl.s() << \"] behind adc_front_s[\"\n << adc_front_s << \"]\";\n continue;\n }\n\n ObjectDecisionType object_stop;\n ObjectStop *object_stop_ptr = object_stop.mutable_stop();\n object_stop_ptr->set_distance_s(FLAGS_stop_line_min_distance);\n object_stop_ptr->set_reason_code(\n StopReasonCode::STOP_REASON_DESTINATION);\n\n auto stop_ref_point = reference_line_.get_reference_point(\n stop_position.x(), stop_position.y());\n object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x());\n object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y());\n object_stop_ptr->set_stop_heading(stop_ref_point.heading());\n\n path_decision_->AddLongitudinalDecision(\"TBD\", obstacle->Id(),\n object_stop);\n }\n }\n\n return true;\n}\n\nbool Frame::CreateReferenceLineFromRouting(\n const common::PointENU &position, const routing::RoutingResponse &routing,\n std::vector<ReferenceLine> *reference_lines) {\n CHECK_NOTNULL(reference_lines);\n\n hdmap::Path hdmap_path;\n if (!pnc_map_->CreatePathFromRouting(\n routing, position, FLAGS_look_backward_distance,\n FLAGS_look_forward_distance, &hdmap_path)) {\n AERROR << \"Failed to get path from routing\";\n return false;\n }\n reference_lines->emplace_back(ReferenceLine());\n ReferenceLineSmoother smoother;\n smoother.Init(smoother_config_);\n if (!smoother.smooth(ReferenceLine(hdmap_path), &reference_lines->back())) {\n AERROR << \"Failed to smooth reference line\";\n return false;\n }\n return true;\n}\n\nconst IndexedObstacles &Frame::GetObstacles() const { return obstacles_; }\n\nstd::string Frame::DebugString() const {\n return \"Frame: \" + std::to_string(sequence_num_);\n}\n\nvoid Frame::RecordInputDebug() {\n if (!FLAGS_enable_record_debug) {\n ADEBUG << \"Skip record input into debug\";\n return;\n }\n auto planning_data = trajectory_pb_.mutable_debug()->mutable_planning_data();\n auto adc_position = planning_data->mutable_adc_position();\n const auto &localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n adc_position->CopyFrom(localization);\n\n const auto &chassis = AdapterManager::GetChassis()->GetLatestObserved();\n auto debug_chassis = planning_data->mutable_chassis();\n debug_chassis->CopyFrom(chassis);\n\n const auto &routing_response =\n AdapterManager::GetRoutingResponse()->GetLatestObserved();\n\n auto debug_routing = planning_data->mutable_routing();\n debug_routing->CopyFrom(routing_response);\n}\n\nvoid Frame::AlignPredictionTime(const double trajectory_header_time) {\n double prediction_header_time = prediction_.header().timestamp_sec();\n\n for (int i = 0; i < prediction_.prediction_obstacle_size(); i++) {\n prediction::PredictionObstacle *obstacle =\n prediction_.mutable_prediction_obstacle(i);\n for (int j = 0; j < obstacle->trajectory_size(); j++) {\n prediction::Trajectory *trajectory = obstacle->mutable_trajectory(j);\n for (int k = 0; k < trajectory->trajectory_point_size(); k++) {\n common::TrajectoryPoint *point =\n trajectory->mutable_trajectory_point(k);\n double abs_relative_time = point->relative_time();\n point->set_relative_time(prediction_header_time + abs_relative_time -\n trajectory_header_time);\n }\n }\n }\n}\n\nstd::unique_ptr<Obstacle> Frame::CreateVirtualObstacle(\n const std::string &obstacle_id,\n const double route_s,\n const double length, const double width, const double height) {\n std::unique_ptr<Obstacle> obstacle_ptr(nullptr);\n\n \/\/ create a \"virtual\" perception_obstacle\n perception::PerceptionObstacle perception_obstacle;\n perception_obstacle.set_id(-1); \/\/ simulator needs a valid integer\n auto dest_ref_point =\n reference_line_.get_reference_point(route_s);\n perception_obstacle.mutable_position()->set_x(dest_ref_point.x());\n perception_obstacle.mutable_position()->set_y(dest_ref_point.y());\n perception_obstacle.set_theta(dest_ref_point.heading());\n perception_obstacle.mutable_velocity()->set_x(0);\n perception_obstacle.mutable_velocity()->set_y(0);\n perception_obstacle.set_length(length);\n perception_obstacle.set_width(length);\n perception_obstacle.set_height(length);\n perception_obstacle.set_type(\n perception::PerceptionObstacle::UNKNOWN_UNMOVABLE);\n perception_obstacle.set_tracking_time(1.0);\n\n obstacle_ptr.reset(new Obstacle(obstacle_id, perception_obstacle));\n return obstacle_ptr;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include \"dsa_common.h\"\n\n#include <boost\/asio\/strand.hpp>\n#include <boost\/beast\/websocket.hpp>\n\n#include \"http_connection.h\"\n#include \"web_server.h\"\n#include \"network\/connection.h\"\n\nnamespace websocket =\n boost::beast::websocket; \/\/ from <boost\/beast\/websocket.hpp>\n\nnamespace dsa {\n\n\nHttpConnection::HttpConnection(WebServer& web_server)\n : _web_server(web_server), _socket(_web_server.io_service()) {}\n\nvoid HttpConnection::accept() {\n \/\/ Read a request\n boost::beast::http::async_read(\n _socket, _buffer, _req,\n \/\/ TODO: run within the strand?\n [ this, sthis = shared_from_this() ](\n const boost::system::error_code& error, size_t bytes_transferred) {\n\n \/\/ TODO: check error\/termination conditions\n\n if (websocket::is_upgrade(_req)) {\n \/\/ call corresponding server's callback\n _connection = _web_server.ws_handler(_req.target().to_string())(\n _web_server, std::move(_socket), std::move(_req));\n }\n return;\n }); \/\/ async_read\n}\n\nvoid HttpConnection::destroy() {\n\/*\n if(_connection != nullptr) {\n _connection->destroy();\n }\n*\/\n}\n} \/\/ namespace dsa\n<commit_msg>temporary fix for a websocket issue on Windows platform<commit_after>#include \"dsa_common.h\"\n\n#include <boost\/asio\/strand.hpp>\n#include <boost\/beast\/websocket.hpp>\n\n#include \"http_connection.h\"\n#include \"web_server.h\"\n#include \"network\/connection.h\"\n\nnamespace websocket =\n boost::beast::websocket; \/\/ from <boost\/beast\/websocket.hpp>\n\nnamespace dsa {\n\n\nHttpConnection::HttpConnection(WebServer& web_server)\n : _web_server(web_server), _socket(_web_server.io_service()) {}\n\nvoid HttpConnection::accept() {\n \/\/ Read a request\n boost::beast::http::async_read(\n _socket, _buffer, _req,\n \/\/ TODO: run within the strand?\n [ this, sthis = shared_from_this() ](\n const boost::system::error_code& error, size_t bytes_transferred) {\n\n \/\/ TODO: check error\/termination conditions\n\n if (websocket::is_upgrade(_req)) {\n \/\/ call corresponding server's callback\n\/\/ TODO - temporary fix for issue on Windowns platform\n\/\/ _connection = _web_server.ws_handler(_req.target().to_string())(\n _connection = _web_server.ws_handler(\"\/\")(\n _web_server, std::move(_socket), std::move(_req));\n }\n return;\n }); \/\/ async_read\n}\n\nvoid HttpConnection::destroy() {\n\/*\n if(_connection != nullptr) {\n _connection->destroy();\n }\n*\/\n}\n} \/\/ namespace dsa\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#ifndef CLUSTERING_ADMINISTRATION_DATUM_ADAPTER_HPP_\n#define CLUSTERING_ADMINISTRATION_DATUM_ADAPTER_HPP_\n\n#include <set>\n#include <string>\n#include <vector>\n\n#include \"containers\/name_string.hpp\"\n#include \"rdb_protocol\/datum.hpp\"\n\ncounted_t<const ql::datum_t> convert_name_to_datum(\n const name_string_t &value);\nbool convert_name_from_datum(\n counted_t<const ql::datum_t> datum,\n const std::string &what, \/* e.g. \"server name\" or \"table name\" *\/\n name_string_t *value_out,\n std::string *error_out);\n\ncounted_t<const ql::datum_t> convert_db_and_table_to_datum(\n const name_string_t &database, const name_string_t &table);\nbool convert_db_and_table_from_datum(\n counted_t<const ql::datum_t> datum,\n name_string_t *database_out,\n name_string_t *table_out,\n std::string *error_out);\n\ncounted_t<const ql::datum_t> convert_uuid_to_datum(\n const uuid_u &value);\nbool convert_uuid_from_datum(\n counted_t<const ql::datum_t> datum,\n uuid_u *value_out,\n std::string *error_out);\n\ntemplate<class T>\ncounted_t<const ql::datum_t> convert_vector_to_datum(\n const std::function<counted_t<const ql::datum_t>(const T&)> &conv,\n const std::vector<T> &vector) {\n ql::datum_array_builder_t builder((ql::configured_limits_t()));\n builder.reserve(vector.size());\n for (const T &elem : vector) {\n builder.add(conv(elem));\n }\n return std::move(builder).to_counted();\n}\n\ntemplate<class T>\nbool convert_vector_from_datum(\n const std::function<bool(counted_t<const ql::datum_t>, T*, std::string*)> &conv,\n counted_t<const ql::datum_t> datum,\n std::vector<T> *vector_out,\n std::string *error_out) {\n if (datum->get_type() != ql::datum_t::R_ARRAY) {\n *error_out = \"Expected an array, got \" + datum->print();\n return false;\n }\n vector_out->resize(datum->size());\n for (size_t i = 0; i < datum->size(); ++i) {\n if (!conv(datum->get(i), &(*vector_out)[i], error_out)) {\n return false;\n }\n }\n return true;\n}\n\ntemplate<class T>\ncounted_t<const ql::datum_t> convert_set_to_datum(\n const std::function<counted_t<const ql::datum_t>(const T&)> &conv,\n const std::set<T> &set) {\n ql::datum_array_builder_t builder((ql::configured_limits_t()));\n builder.reserve(set.size());\n for (const T &elem : set) {\n builder.add(conv(elem));\n }\n return std::move(builder).to_counted();\n}\n\ntemplate<class T>\nbool convert_set_from_datum(\n const std::function<bool(counted_t<const ql::datum_t>, T*, std::string*)> &conv,\n bool allow_duplicates,\n counted_t<const ql::datum_t> datum,\n std::set<T> *set_out,\n std::string *error_out) {\n if (datum->get_type() != ql::datum_t::R_ARRAY) {\n *error_out = \"Expected an array, got \" + datum->print();\n return false;\n }\n set_out->clear();\n for (size_t i = 0; i < datum->size(); ++i) {\n T value;\n if (!conv(datum->get(i), &value, error_out)) {\n return false;\n }\n if (!allow_duplicates && set_out->count(value) == 1) {\n *error_out = datum->get(i)->print() + \" was specified more than once.\";\n return false;\n }\n set_out->insert(value);\n }\n return true;\n}\n\n\/* `converter_from_datum_object_t` is a helper for converting a `datum_t` to some other\ntype when the type's datum representation is an object with a fixed set of fields.\nConstruct a `converter_from_datum_object_t` and call `init()` with your datum. `init()`\nwill fail if the input isn't an object. Next, call `get()` or `get_optional()` for each\nfield of the object; `get()` will fail if the field isn't present. Finally, call\n`check_no_extra_keys()`, which will fail if the object has any keys that you didn't call\n`get()` or `get_optional()` for. This way, it will produce a nice error message if the\nuser passes an object with an invalid key. *\/\nclass converter_from_datum_object_t {\npublic:\n bool init(counted_t<const ql::datum_t> datum,\n std::string *error_out);\n bool get(const std::string &key,\n counted_t<const ql::datum_t> *value_out,\n std::string *error_out);\n void get_optional(const std::string &key,\n counted_t<const ql::datum_t> *value_out);\n bool check_no_extra_keys(std::string *error_out);\nprivate:\n counted_t<const ql::datum_t> datum;\n std::set<std::string> extra_keys;\n};\n\n#endif \/* CLUSTERING_ADMINISTRATION_DATUM_ADAPTER_HPP_ *\/\n\n<commit_msg>Fix minor style issue in datum_adapter.hpp<commit_after>\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#ifndef CLUSTERING_ADMINISTRATION_DATUM_ADAPTER_HPP_\n#define CLUSTERING_ADMINISTRATION_DATUM_ADAPTER_HPP_\n\n#include <set>\n#include <string>\n#include <vector>\n\n#include \"containers\/name_string.hpp\"\n#include \"rdb_protocol\/datum.hpp\"\n\ncounted_t<const ql::datum_t> convert_name_to_datum(\n const name_string_t &value);\nbool convert_name_from_datum(\n counted_t<const ql::datum_t> datum,\n const std::string &what, \/* e.g. \"server name\" or \"table name\" *\/\n name_string_t *value_out,\n std::string *error_out);\n\ncounted_t<const ql::datum_t> convert_db_and_table_to_datum(\n const name_string_t &database, const name_string_t &table);\nbool convert_db_and_table_from_datum(\n counted_t<const ql::datum_t> datum,\n name_string_t *database_out,\n name_string_t *table_out,\n std::string *error_out);\n\ncounted_t<const ql::datum_t> convert_uuid_to_datum(\n const uuid_u &value);\nbool convert_uuid_from_datum(\n counted_t<const ql::datum_t> datum,\n uuid_u *value_out,\n std::string *error_out);\n\ntemplate<class T>\ncounted_t<const ql::datum_t> convert_vector_to_datum(\n const std::function<counted_t<const ql::datum_t>(const T&)> &conv,\n const std::vector<T> &vector) {\n ql::datum_array_builder_t builder((ql::configured_limits_t()));\n builder.reserve(vector.size());\n for (const T &elem : vector) {\n builder.add(conv(elem));\n }\n return std::move(builder).to_counted();\n}\n\ntemplate<class T>\nbool convert_vector_from_datum(\n const std::function<bool(counted_t<const ql::datum_t>, T*, std::string*)> &conv,\n counted_t<const ql::datum_t> datum,\n std::vector<T> *vector_out,\n std::string *error_out) {\n if (datum->get_type() != ql::datum_t::R_ARRAY) {\n *error_out = \"Expected an array, got \" + datum->print();\n return false;\n }\n vector_out->resize(datum->size());\n for (size_t i = 0; i < datum->size(); ++i) {\n if (!conv(datum->get(i), &(*vector_out)[i], error_out)) {\n return false;\n }\n }\n return true;\n}\n\ntemplate<class T>\ncounted_t<const ql::datum_t> convert_set_to_datum(\n const std::function<counted_t<const ql::datum_t>(const T&)> &conv,\n const std::set<T> &set) {\n ql::datum_array_builder_t builder((ql::configured_limits_t()));\n builder.reserve(set.size());\n for (const T &elem : set) {\n builder.add(conv(elem));\n }\n return std::move(builder).to_counted();\n}\n\ntemplate<class T>\nbool convert_set_from_datum(\n const std::function<bool(counted_t<const ql::datum_t>, T*, std::string*)> &conv,\n bool allow_duplicates,\n counted_t<const ql::datum_t> datum,\n std::set<T> *set_out,\n std::string *error_out) {\n if (datum->get_type() != ql::datum_t::R_ARRAY) {\n *error_out = \"Expected an array, got \" + datum->print();\n return false;\n }\n set_out->clear();\n for (size_t i = 0; i < datum->size(); ++i) {\n T value;\n if (!conv(datum->get(i), &value, error_out)) {\n return false;\n }\n auto res = set_out->insert(value);\n if (!allow_duplicates && !res.second) {\n *error_out = datum->get(i)->print() + \" was specified more than once.\";\n return false;\n }\n }\n return true;\n}\n\n\/* `converter_from_datum_object_t` is a helper for converting a `datum_t` to some other\ntype when the type's datum representation is an object with a fixed set of fields.\nConstruct a `converter_from_datum_object_t` and call `init()` with your datum. `init()`\nwill fail if the input isn't an object. Next, call `get()` or `get_optional()` for each\nfield of the object; `get()` will fail if the field isn't present. Finally, call\n`check_no_extra_keys()`, which will fail if the object has any keys that you didn't call\n`get()` or `get_optional()` for. This way, it will produce a nice error message if the\nuser passes an object with an invalid key. *\/\nclass converter_from_datum_object_t {\npublic:\n bool init(counted_t<const ql::datum_t> datum,\n std::string *error_out);\n bool get(const std::string &key,\n counted_t<const ql::datum_t> *value_out,\n std::string *error_out);\n void get_optional(const std::string &key,\n counted_t<const ql::datum_t> *value_out);\n bool check_no_extra_keys(std::string *error_out);\nprivate:\n counted_t<const ql::datum_t> datum;\n std::set<std::string> extra_keys;\n};\n\n#endif \/* CLUSTERING_ADMINISTRATION_DATUM_ADAPTER_HPP_ *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>\n\n This file is part of the KDE project\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 License\n aint with this library see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"GPXgpxTagHandler.h\"\n\n#include \"MarbleDebug.h\"\n\n#include \"GPXElementDictionary.h\"\n#include \"GeoDataParser.h\"\n\n#include \"GeoDataDocument.h\"\n#include \"GeoDataStyle.h\"\n#include \"GeoDataStyleMap.h\"\n#include \"GeoDataHotSpot.h\"\n#include \"MarbleDirs.h\"\n#include \"global.h\"\n\nnamespace Marble\n{\nnamespace gpx\n{\nGPX_DEFINE_TAG_HANDLER(gpx)\n\nGeoNode* GPXgpxTagHandler::parse(GeoParser& parser) const\n{\n GeoDataDocument* doc = geoDataDoc( parser );\n\n GeoDataStyle style;\n GeoDataLineStyle lineStyle;\n lineStyle.setColor( oxygenForestGreen4 );\n lineStyle.setWidth(2);\n style.setLineStyle(lineStyle);\n style.setStyleId(\"track\");\n\n GeoDataStyleMap styleMap;\n styleMap.setStyleId(\"map-track\");\n styleMap.insert(\"normal\", QString(\"#\").append(style.styleId()));\n doc->addStyleMap(styleMap);\n doc->addStyle(style);\n\n \/\/ create a style for routes\n GeoDataStyle routestyle;\n GeoDataLineStyle routeLineStyle;\n routeLineStyle.setColor( \"blue\" );\n routeLineStyle.setWidth(3);\n routestyle.setLineStyle(routeLineStyle);\n routestyle.setStyleId(\"route\");\n\n GeoDataStyleMap routeStyleMap;\n routeStyleMap.setStyleId(\"map-route\");\n routeStyleMap.insert(\"normal\", QString(\"#\").append(routestyle.styleId()));\n doc->addStyleMap(routeStyleMap);\n doc->addStyle(routestyle);\n \n \/\/ routepoint icon style\n GeoDataStyle routepointStyle;\n routepointStyle.setStyleId(\"routepoint\");\n GeoDataIconStyle routeIconStyle;\n routeIconStyle.setIconPath(MarbleDirs::path(\"bitmaps\/city_4_white.png\"));\n routeIconStyle.setHotSpot(QPointF(0.5,0.5), GeoDataHotSpot::Fraction, GeoDataHotSpot::Fraction);\n routepointStyle.setIconStyle(routeIconStyle);\n\n GeoDataStyleMap routepointStyleMap;\n routepointStyleMap.setStyleId(\"map-routepoint\");\n routepointStyleMap.insert(\"normal\", QString(\"#\").append(routepointStyle.styleId()));\n doc->addStyleMap(routepointStyleMap);\n doc->addStyle(routepointStyle);\n \n \/\/ create a default style for waypoint icons\n GeoDataStyle waypointStyle;\n waypointStyle.setStyleId(\"waypoint\");\n GeoDataIconStyle iconStyle;\n iconStyle.setIconPath(MarbleDirs::path(\"bitmaps\/flag.png\"));\n iconStyle.setHotSpot(QPointF(0.12,0.03), GeoDataHotSpot::Fraction, GeoDataHotSpot::Fraction);\n waypointStyle.setIconStyle(iconStyle);\n\n GeoDataStyleMap wpStyleMap;\n styleMap.setStyleId(\"map-waypoint\");\n styleMap.insert(\"normal\", QString(\"#\").append(waypointStyle.styleId()));\n doc->addStyleMap(wpStyleMap);\n doc->addStyle(waypointStyle);\n \n#ifdef DEBUG_TAGS\n mDebug() << \"Parsed <\" << gpxTag_gpx << \"> document: \" << doc;\n#endif\n return doc;\n}\n\n}\n}\n<commit_msg>get the route\/wpt style correct<commit_after>\/*\n Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>\n\n This file is part of the KDE project\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 License\n aint with this library see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"GPXgpxTagHandler.h\"\n\n#include \"MarbleDebug.h\"\n\n#include \"GPXElementDictionary.h\"\n#include \"GeoDataParser.h\"\n\n#include \"GeoDataDocument.h\"\n#include \"GeoDataStyle.h\"\n#include \"GeoDataStyleMap.h\"\n#include \"GeoDataHotSpot.h\"\n#include \"MarbleDirs.h\"\n#include \"global.h\"\n\nnamespace Marble\n{\nnamespace gpx\n{\nGPX_DEFINE_TAG_HANDLER(gpx)\n\nGeoNode* GPXgpxTagHandler::parse(GeoParser& parser) const\n{\n GeoDataDocument* doc = geoDataDoc( parser );\n\n GeoDataStyle style;\n GeoDataLineStyle lineStyle;\n lineStyle.setColor( oxygenForestGreen4 );\n lineStyle.setWidth(2);\n style.setLineStyle(lineStyle);\n style.setStyleId(\"track\");\n\n GeoDataStyleMap styleMap;\n styleMap.setStyleId(\"map-track\");\n styleMap.insert(\"normal\", QString(\"#\").append(style.styleId()));\n doc->addStyleMap(styleMap);\n doc->addStyle(style);\n\n \/\/ create a style for routes\n GeoDataStyle routestyle;\n GeoDataLineStyle routeLineStyle;\n routeLineStyle.setColor( oxygenSkyBlue4 );\n routeLineStyle.setWidth(2);\n routestyle.setLineStyle(routeLineStyle);\n routestyle.setStyleId(\"route\");\n\n GeoDataStyleMap routeStyleMap;\n routeStyleMap.setStyleId(\"map-route\");\n routeStyleMap.insert(\"normal\", QString(\"#\").append(routestyle.styleId()));\n doc->addStyleMap(routeStyleMap);\n doc->addStyle(routestyle);\n\n \/\/ routepoint style\n GeoDataStyle routepointStyle;\n routepointStyle.setStyleId(\"routepoint\");\n\n GeoDataIconStyle routepointIconStyle;\n routepointIconStyle.setIconPath(MarbleDirs::path(\"bitmaps\/city_4_white.png\"));\n routepointIconStyle.setHotSpot(QPointF(0.5,0.5), GeoDataHotSpot::Fraction, GeoDataHotSpot::Fraction);\n routepointStyle.setIconStyle(routepointIconStyle);\n\n GeoDataLabelStyle routepointLabelStyle;\n routepointLabelStyle.setAlignment(GeoDataLabelStyle::Corner);\n routepointStyle.setLabelStyle(routepointLabelStyle);\n\n GeoDataStyleMap routepointStyleMap;\n routepointStyleMap.setStyleId(\"map-routepoint\");\n routepointStyleMap.insert(\"normal\", QString(\"#\").append(routepointStyle.styleId()));\n doc->addStyleMap(routepointStyleMap);\n doc->addStyle(routepointStyle);\n\n \/\/ create a default style for waypoint icons\n GeoDataStyle waypointStyle;\n waypointStyle.setStyleId(\"waypoint\");\n GeoDataIconStyle iconStyle;\n iconStyle.setIconPath(MarbleDirs::path(\"bitmaps\/flag.png\"));\n iconStyle.setHotSpot(QPointF(0.12,0.03), GeoDataHotSpot::Fraction, GeoDataHotSpot::Fraction);\n waypointStyle.setIconStyle(iconStyle);\n\n GeoDataLabelStyle waypointLabelStyle;\n waypointLabelStyle.setAlignment(GeoDataLabelStyle::Corner);\n waypointStyle.setLabelStyle(waypointLabelStyle);\n\n GeoDataStyleMap waypointStyleMap;\n waypointStyleMap.setStyleId(\"map-waypoint\");\n waypointStyleMap.insert(\"normal\", QString(\"#\").append(waypointStyle.styleId()));\n doc->addStyleMap(waypointStyleMap);\n doc->addStyle(waypointStyle);\n\n#ifdef DEBUG_TAGS\n mDebug() << \"Parsed <\" << gpxTag_gpx << \"> document: \" << doc;\n#endif\n return doc;\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * File : C.cpp\n * Author : Kazune Takahashi\n * Created : 12\/9\/2018, 10:32:26 PM\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\nconst int C = 5000;\n\/\/ const ll M = 1000000007;\n\nint N, A;\nint x[50];\n\nll DP[60][10000];\n\nint main()\n{\n cin >> N >> A;\n for (auto i = 0; i < N; i++)\n {\n cin >> x[i];\n x[i] -= A;\n }\n fill(&DP[0][0], &DP[0][0] + 60 * 10000, 0);\n DP[0][C] = 1;\n for (auto i = 0; i < N; i++)\n {\n for (auto j = 0; j < 10000; j++)\n {\n if (DP[i][j] == 0)\n {\n continue;\n }\n DP[i + 1][j + x[i]] += DP[i][j];\n }\n }\n cout << DP[N][C] << endl;\n}<commit_msg>tried C.cpp to 'C'<commit_after>\/**\n * File : C.cpp\n * Author : Kazune Takahashi\n * Created : 12\/9\/2018, 10:32:26 PM\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\nconst int C = 5000;\n\/\/ const ll M = 1000000007;\n\nint N, A;\nint x[50];\n\nll DP[60][10000];\n\nint main()\n{\n cin >> N >> A;\n for (auto i = 0; i < N; i++)\n {\n cin >> x[i];\n x[i] -= A;\n }\n fill(&DP[0][0], &DP[0][0] + 60 * 10000, 0);\n DP[0][C] = 1;\n for (auto i = 0; i < N; i++)\n {\n for (auto j = 0; j < 10000; j++)\n {\n if (DP[i][j] == 0)\n {\n continue;\n }\n DP[i + 1][j] += DP[i][j];\n DP[i + 1][j + x[i]] += DP[i][j];\n }\n }\n cout << DP[N][C] << endl;\n}<|endoftext|>"} {"text":"<commit_before>#include <experimental\/filesystem>\n#include <time.h>\n\n#include <Util\/Util.h>\n#include <Network\/PacketContainer.h>\n#include <Logging\/Logger.h>\n\n#include \"Network\/GameConnection.h\"\n#include \"Actor\/Player.h\"\n\n#include \"Session.h\"\n#include \"Framework.h\"\n\n\nextern Core::Framework g_fw;\nnamespace fs = std::experimental::filesystem;\n\nCore::Session::Session( uint32_t sessionId ) :\n m_sessionId( sessionId ),\n m_lastDataTime( Util::getTimeSeconds() ),\n m_lastSqlTime( Util::getTimeSeconds() ),\n m_isValid( false )\n{\n}\n\nCore::Session::~Session()\n{\n}\n\nvoid Core::Session::setZoneConnection( Network::GameConnectionPtr pZoneCon )\n{\n pZoneCon->m_conType = Network::ConnectionType::Zone;\n m_pZoneConnection = pZoneCon;\n}\n\nvoid Core::Session::setChatConnection( Network::GameConnectionPtr pChatCon )\n{\n pChatCon->m_conType = Network::ConnectionType::Chat;\n m_pChatConnection = pChatCon;\n}\n\nCore::Network::GameConnectionPtr Core::Session::getZoneConnection() const\n{\n return m_pZoneConnection;\n}\n\nCore::Network::GameConnectionPtr Core::Session::getChatConnection() const\n{\n return m_pChatConnection;\n}\n\n\nbool Core::Session::loadPlayer()\n{\n\n m_pPlayer = Entity::make_Player();\n\n if( !m_pPlayer->load( m_sessionId, shared_from_this() ) )\n {\n m_isValid = false;\n return false;\n }\n\n m_isValid = true;\n\n return true;\n\n}\n\nvoid Core::Session::close()\n{\n if( m_pZoneConnection )\n m_pZoneConnection->Disconnect();\n\n if( m_pChatConnection )\n m_pChatConnection->Disconnect();\n\n \/\/ remove the session from the player\n if( m_pPlayer )\n \/\/ reset the zone, so the zone handler knows to remove the actor\n m_pPlayer->setCurrentZone( nullptr );\n}\n\nuint32_t Core::Session::getId() const\n{\n return m_sessionId;\n}\n\nint64_t Core::Session::getLastDataTime() const\n{\n return m_lastDataTime;\n}\n\nint64_t Core::Session::getLastSqlTime() const\n{\n return m_lastSqlTime;\n}\n\nbool Core::Session::isValid() const\n{\n return m_isValid;\n}\n\nvoid Core::Session::updateLastDataTime()\n{\n m_lastDataTime = Util::getTimeSeconds();\n}\n\nvoid Core::Session::updateLastSqlTime()\n{\n m_lastSqlTime = Util::getTimeSeconds();\n}\n\nvoid Core::Session::startReplay( const std::string& path )\n{\n auto pLog = g_fw.get< Logger >();\n if( !fs::exists( path ) )\n {\n getPlayer()->sendDebug( \"Couldn't find folder.\" );\n return;\n }\n\n m_replayCache.clear();\n\n std::vector< std::tuple< uint64_t, std::string > > loadedSets;\n\n for( auto it = fs::directory_iterator( fs::path( path ) );\n it != fs::directory_iterator(); ++it )\n {\n \/\/ Get the filename of the current element\n auto fileName = it->path().filename().string();\n auto unixTime = std::stoull( fileName.substr( 0, 14 ).c_str() );\n\n if( unixTime > 1000000000 )\n {\n loadedSets.push_back( std::tuple< uint64_t, std::string >( unixTime, it->path().string() ) );\n }\n }\n\n sort( loadedSets.begin(), loadedSets.end(),\n []( const std::tuple< uint64_t, std::string >& left, const std::tuple< uint64_t, std::string >& right )\n {\n return std::get< 0 >( left ) < std::get< 0 >( right );\n } );\n\n uint64_t startTime = std::get< 0 >( loadedSets.at( 0 ) );\n\n for( auto set : loadedSets )\n {\n m_replayCache.push_back( std::tuple< uint64_t, std::string >(\n Util::getTimeMs() + ( std::get< 0 >( set ) - startTime ), std::get< 1 >( set ) ) );\n\n pLog->info( \"Registering \" + std::get< 1 >( set ) + \" for \" + std::to_string( std::get< 0 >( set ) - startTime ) );\n }\n\n getPlayer()->sendDebug( \"Registered \" + std::to_string( m_replayCache.size() ) + \" sets for replay\" );\n m_isReplaying = true;\n}\n\nvoid Core::Session::stopReplay()\n{\n m_isReplaying = false;\n m_replayCache.clear();\n}\n\nvoid Core::Session::processReplay()\n{\n int at = 0;\n for( const auto& set : m_replayCache )\n {\n if( std::get< 0 >( set ) <= Util::getTimeMs() )\n {\n m_pZoneConnection->injectPacket( std::get< 1 >( set ), *getPlayer().get() );\n m_replayCache.erase( m_replayCache.begin() + at );\n \/\/g_framework.getLogger().info( \"Sent for \" + std::to_string( std::get< 0 >( set ) ) + \", left: \" + std::to_string( m_replayCache.size() ) );\n }\n at++;\n }\n\n if( m_replayCache.size() == 0 )\n m_isReplaying = false;\n}\n\nvoid Core::Session::sendReplayInfo()\n{\n std::string message = std::to_string( m_replayCache.size() ) + \" Sets left in cache, \";\n\n if( m_isReplaying )\n message += \" is active\";\n else\n message += \" is idle\";\n\n getPlayer()->sendDebug( message );\n}\n\nvoid Core::Session::update()\n{\n if( m_isReplaying )\n processReplay();\n\n if( m_pZoneConnection )\n {\n m_pZoneConnection->processInQueue();\n\n \/\/ SESSION LOGIC\n m_pPlayer->update( Util::getTimeMs() );\n\n if( ( static_cast< uint32_t >( Util::getTimeSeconds() ) - static_cast< uint32_t >( getLastSqlTime() ) ) > 10 )\n {\n updateLastSqlTime();\n m_pPlayer->updateSql();\n }\n\n m_pZoneConnection->processOutQueue();\n }\n\n if( m_pChatConnection )\n {\n m_pChatConnection->processInQueue();\n m_pChatConnection->processOutQueue();\n }\n\n}\n\nCore::Entity::PlayerPtr Core::Session::getPlayer() const\n{\n return m_pPlayer;\n}\n\n<commit_msg>Sync chardata on session close<commit_after>#include <experimental\/filesystem>\n#include <time.h>\n\n#include <Util\/Util.h>\n#include <Network\/PacketContainer.h>\n#include <Logging\/Logger.h>\n\n#include \"Network\/GameConnection.h\"\n#include \"Actor\/Player.h\"\n\n#include \"Session.h\"\n#include \"Framework.h\"\n\n\nextern Core::Framework g_fw;\nnamespace fs = std::experimental::filesystem;\n\nCore::Session::Session( uint32_t sessionId ) :\n m_sessionId( sessionId ),\n m_lastDataTime( Util::getTimeSeconds() ),\n m_lastSqlTime( Util::getTimeSeconds() ),\n m_isValid( false )\n{\n}\n\nCore::Session::~Session()\n{\n}\n\nvoid Core::Session::setZoneConnection( Network::GameConnectionPtr pZoneCon )\n{\n pZoneCon->m_conType = Network::ConnectionType::Zone;\n m_pZoneConnection = pZoneCon;\n}\n\nvoid Core::Session::setChatConnection( Network::GameConnectionPtr pChatCon )\n{\n pChatCon->m_conType = Network::ConnectionType::Chat;\n m_pChatConnection = pChatCon;\n}\n\nCore::Network::GameConnectionPtr Core::Session::getZoneConnection() const\n{\n return m_pZoneConnection;\n}\n\nCore::Network::GameConnectionPtr Core::Session::getChatConnection() const\n{\n return m_pChatConnection;\n}\n\n\nbool Core::Session::loadPlayer()\n{\n\n m_pPlayer = Entity::make_Player();\n\n if( !m_pPlayer->load( m_sessionId, shared_from_this() ) )\n {\n m_isValid = false;\n return false;\n }\n\n m_isValid = true;\n\n return true;\n\n}\n\nvoid Core::Session::close()\n{\n if( m_pZoneConnection )\n m_pZoneConnection->Disconnect();\n\n if( m_pChatConnection )\n m_pChatConnection->Disconnect();\n\n \/\/ remove the session from the player\n if( m_pPlayer )\n {\n \/\/ do one last update to db\n m_pPlayer->updateSql();\n \/\/ reset the zone, so the zone handler knows to remove the actor\n m_pPlayer->setCurrentZone( nullptr );\n }\n}\n\nuint32_t Core::Session::getId() const\n{\n return m_sessionId;\n}\n\nint64_t Core::Session::getLastDataTime() const\n{\n return m_lastDataTime;\n}\n\nint64_t Core::Session::getLastSqlTime() const\n{\n return m_lastSqlTime;\n}\n\nbool Core::Session::isValid() const\n{\n return m_isValid;\n}\n\nvoid Core::Session::updateLastDataTime()\n{\n m_lastDataTime = Util::getTimeSeconds();\n}\n\nvoid Core::Session::updateLastSqlTime()\n{\n m_lastSqlTime = Util::getTimeSeconds();\n}\n\nvoid Core::Session::startReplay( const std::string& path )\n{\n auto pLog = g_fw.get< Logger >();\n if( !fs::exists( path ) )\n {\n getPlayer()->sendDebug( \"Couldn't find folder.\" );\n return;\n }\n\n m_replayCache.clear();\n\n std::vector< std::tuple< uint64_t, std::string > > loadedSets;\n\n for( auto it = fs::directory_iterator( fs::path( path ) );\n it != fs::directory_iterator(); ++it )\n {\n \/\/ Get the filename of the current element\n auto fileName = it->path().filename().string();\n auto unixTime = std::stoull( fileName.substr( 0, 14 ).c_str() );\n\n if( unixTime > 1000000000 )\n {\n loadedSets.push_back( std::tuple< uint64_t, std::string >( unixTime, it->path().string() ) );\n }\n }\n\n sort( loadedSets.begin(), loadedSets.end(),\n []( const std::tuple< uint64_t, std::string >& left, const std::tuple< uint64_t, std::string >& right )\n {\n return std::get< 0 >( left ) < std::get< 0 >( right );\n } );\n\n uint64_t startTime = std::get< 0 >( loadedSets.at( 0 ) );\n\n for( auto set : loadedSets )\n {\n m_replayCache.push_back( std::tuple< uint64_t, std::string >(\n Util::getTimeMs() + ( std::get< 0 >( set ) - startTime ), std::get< 1 >( set ) ) );\n\n pLog->info( \"Registering \" + std::get< 1 >( set ) + \" for \" + std::to_string( std::get< 0 >( set ) - startTime ) );\n }\n\n getPlayer()->sendDebug( \"Registered \" + std::to_string( m_replayCache.size() ) + \" sets for replay\" );\n m_isReplaying = true;\n}\n\nvoid Core::Session::stopReplay()\n{\n m_isReplaying = false;\n m_replayCache.clear();\n}\n\nvoid Core::Session::processReplay()\n{\n int at = 0;\n for( const auto& set : m_replayCache )\n {\n if( std::get< 0 >( set ) <= Util::getTimeMs() )\n {\n m_pZoneConnection->injectPacket( std::get< 1 >( set ), *getPlayer().get() );\n m_replayCache.erase( m_replayCache.begin() + at );\n \/\/g_framework.getLogger().info( \"Sent for \" + std::to_string( std::get< 0 >( set ) ) + \", left: \" + std::to_string( m_replayCache.size() ) );\n }\n at++;\n }\n\n if( m_replayCache.size() == 0 )\n m_isReplaying = false;\n}\n\nvoid Core::Session::sendReplayInfo()\n{\n std::string message = std::to_string( m_replayCache.size() ) + \" Sets left in cache, \";\n\n if( m_isReplaying )\n message += \" is active\";\n else\n message += \" is idle\";\n\n getPlayer()->sendDebug( message );\n}\n\nvoid Core::Session::update()\n{\n if( m_isReplaying )\n processReplay();\n\n if( m_pZoneConnection )\n {\n m_pZoneConnection->processInQueue();\n\n \/\/ SESSION LOGIC\n m_pPlayer->update( Util::getTimeMs() );\n\n if( ( static_cast< uint32_t >( Util::getTimeSeconds() ) - static_cast< uint32_t >( getLastSqlTime() ) ) > 10 )\n {\n updateLastSqlTime();\n m_pPlayer->updateSql();\n }\n\n m_pZoneConnection->processOutQueue();\n }\n\n if( m_pChatConnection )\n {\n m_pChatConnection->processInQueue();\n m_pChatConnection->processOutQueue();\n }\n\n}\n\nCore::Entity::PlayerPtr Core::Session::getPlayer() const\n{\n return m_pPlayer;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Clever programming language\n * Copyright (c) Clever Team\n *\n * This file is distributed under the MIT license. See LICENSE for details.\n *\/\n\n#include \"core\/clever.h\"\n#include \"core\/value.h\"\n#include \"modules\/std\/concurrent\/module.h\"\n#include \"modules\/std\/concurrent\/thread.h\"\n#include \"modules\/std\/core\/function.h\"\n#include \"types\/type.h\"\n\nnamespace clever { namespace packages { namespace std {\n\nstatic inline void* ThreadHandler(void* ThreadArgument){\n\tThreadData* intern = static_cast<ThreadData*>(ThreadArgument);\n\n\t::std::cout << \"Hello From ThreadHandler\" << ::std::endl;\n\n\treturn intern;\n}\n\nvoid Thread::dump(const void* data) const\n{\n\tdump(data, ::std::cout);\n}\n\nvoid Thread::dump(const void* data, ::std::ostream& out) const\n{\n\tValue::DataValue* dvalue =\n\t\tstatic_cast<Value::DataValue*>(const_cast<void*>(data));\n\tif (dvalue) {\n\n\t}\n}\n\nvoid* Thread::allocData(CLEVER_TYPE_CTOR_ARGS) const\n{\n\tThreadData* intern = new ThreadData;\n\tif (intern) {\n\n\t\tintern->thread = new pthread_t;\n\t\tintern->lock = new pthread_mutex_t;\n\t\tintern->entry = NULL;\n\n\t\tif (intern->lock) {\n\t\t\tif (pthread_mutex_init(intern->lock, NULL) != 0) {\n\t\t\t\tclever_error(\"Thread.new failed to initialize a lock for the Thread\");\n\t\t\t}\n\t\t}\n\n\t\tif (args->size()) {\n\n\t\t\tValue* point = args->at(0);\n\n\t\t\t\/** there's something very wrong here **\/\n\t\t\tif (point->getType() == CLEVER_FUNC_TYPE) {\n\t\t\t\tintern->entry = static_cast<Function*>(point->getObj());\n\t\t\t} else {\n\t\t\t\tclever_error(\"Thread.new was expecting a Function and got something else at %@\", point);\n\t\t\t}\n\t\t} else {\n\t\t\tclever_error(\"Thread.new was expecting a Function entry point and recieved no arguments\");\n\t\t}\n\t}\n\treturn intern;\n}\n\nvoid Thread::deallocData(void* data)\n{\n\tThreadData* intern = static_cast<ThreadData*>(data);\n\tif (intern) {\n\n\t\tif (intern->lock) {\n\t\t\tif (pthread_mutex_destroy(intern->lock) != 0) {\n\t\t\t\tclever_error(\"Thread.delete experienced an error destroying the Thread's lock\");\n\t\t\t}\n\n\t\t\tdelete intern->lock;\n\t\t}\n\n\t\tdelete intern->thread;\n\t\tdelete intern;\n\t}\n}\n\nCLEVER_METHOD(Thread::start)\n{\n\tThreadData* intern = CLEVER_GET_OBJECT(ThreadData*, CLEVER_THIS());\n\n\tif (!intern) {\n\t\t\/\/CLEVER_THROW(eventually)\n\t\treturn;\n\t}\n\n\tif (intern->entry != NULL) {\n\t\t\/** @TODO(krakjoe) pthread attributes **\/\n\n\t\tif (pthread_mutex_lock(intern->lock) == 0) {\n\t\t\tresult->setBool(\n\t\t\t\t(pthread_create(intern->thread, NULL, ThreadHandler, intern) == 0)\n\t\t\t);\n\t\t\tpthread_mutex_unlock(intern->lock);\n\t\t} else {\n\t\t\t\/* report fatality *\/\n\t\t\tresult->setBool(false);\n\t\t}\n\t} else {\n\t\tresult->setBool(false);\n\t}\n}\n\nCLEVER_TYPE_INIT(Thread::init)\n{\n\taddMethod(new Function(\"start\", (MethodPtr)&Thread::start));\n}\n\n}}} \/\/ clever::packages::std\n<commit_msg>- CS, nesting--<commit_after>\/**\n * Clever programming language\n * Copyright (c) Clever Team\n *\n * This file is distributed under the MIT license. See LICENSE for details.\n *\/\n\n#include \"core\/clever.h\"\n#include \"core\/value.h\"\n#include \"modules\/std\/concurrent\/module.h\"\n#include \"modules\/std\/concurrent\/thread.h\"\n#include \"modules\/std\/core\/function.h\"\n#include \"types\/type.h\"\n\nnamespace clever { namespace packages { namespace std {\n\nstatic inline void* ThreadHandler(void* ThreadArgument)\n{\n\tThreadData* intern = static_cast<ThreadData*>(ThreadArgument);\n\n\t::std::cout << \"Hello From ThreadHandler\" << ::std::endl;\n\n\treturn intern;\n}\n\nvoid Thread::dump(const void* data) const\n{\n\tdump(data, ::std::cout);\n}\n\nvoid Thread::dump(const void* data, ::std::ostream& out) const\n{\n\tValue::DataValue* dvalue =\n\t\tstatic_cast<Value::DataValue*>(const_cast<void*>(data));\n\tif (dvalue) {\n\n\t}\n}\n\nvoid* Thread::allocData(CLEVER_TYPE_CTOR_ARGS) const\n{\n\tThreadData* intern = new ThreadData;\n\n\tintern->thread = new pthread_t;\n\tintern->lock = new pthread_mutex_t;\n\tintern->entry = NULL;\n\n\tif (intern->lock) {\n\t\tif (pthread_mutex_init(intern->lock, NULL) != 0) {\n\t\t\tclever_error(\"Thread.new failed to initialize a lock for the Thread\");\n\t\t}\n\t}\n\n\tif (args->size()) {\n\t\tValue* point = args->at(0);\n\n\t\t\/** there's something very wrong here **\/\n\t\tif (point->getType() == CLEVER_FUNC_TYPE) {\n\t\t\tintern->entry = static_cast<Function*>(point->getObj());\n\t\t} else {\n\t\t\tclever_error(\"Thread.new was expecting a Function and got something else at %@\", point);\n\t\t}\n\t} else {\n\t\tclever_error(\"Thread.new was expecting a Function entry point and recieved no arguments\");\n\t}\n\treturn intern;\n}\n\nvoid Thread::deallocData(void* data)\n{\n\tThreadData* intern = static_cast<ThreadData*>(data);\n\n\tif (!intern) {\n\t\treturn;\n\t}\n\n\tif (intern->lock) {\n\t\tif (pthread_mutex_destroy(intern->lock) != 0) {\n\t\t\tclever_error(\"Thread.delete experienced an error destroying the Thread's lock\");\n\t\t}\n\t\tdelete intern->lock;\n\t}\n\n\tdelete intern->thread;\n\tdelete intern;\n}\n\nCLEVER_METHOD(Thread::start)\n{\n\tThreadData* intern = CLEVER_GET_OBJECT(ThreadData*, CLEVER_THIS());\n\n\tif (!intern) {\n\t\t\/\/CLEVER_THROW(eventually)\n\t\treturn;\n\t}\n\n\tif (intern->entry != NULL) {\n\t\t\/** @TODO(krakjoe) pthread attributes **\/\n\n\t\tif (pthread_mutex_lock(intern->lock) == 0) {\n\t\t\tresult->setBool(\n\t\t\t\t(pthread_create(intern->thread, NULL, ThreadHandler, intern) == 0)\n\t\t\t);\n\t\t\tpthread_mutex_unlock(intern->lock);\n\t\t} else {\n\t\t\t\/* report fatality *\/\n\t\t\tresult->setBool(false);\n\t\t}\n\t} else {\n\t\tresult->setBool(false);\n\t}\n}\n\nCLEVER_TYPE_INIT(Thread::init)\n{\n\taddMethod(new Function(\"start\", (MethodPtr)&Thread::start));\n}\n\n}}} \/\/ clever::packages::std\n<|endoftext|>"} {"text":"<commit_before>\/\/================================================================================\r\n\/\/\r\n\/\/\tThe MIT License (MIT)\r\n\/\/\r\n\/\/\tCopyright (c) 2014 Konstantinos Sofokleous\r\n\/\/\r\n\/\/\tPermission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/\tof this software and associated documentation files (the \"Software\"), to deal\r\n\/\/\tin the Software without restriction, including without limitation the rights\r\n\/\/\tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/\tcopies of the Software, and to permit persons to whom the Software is\r\n\/\/\tfurnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/\tThe above copyright notice and this permission notice shall be included in\r\n\/\/\tall copies or substantial portions of the Software.\r\n\/\/\r\n\/\/\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/\tTHE SOFTWARE.\r\n\/\/\r\n\/\/================================================================================\r\n\r\n\/\/#define SLOG_DISABLE 0\r\n\/\/#define SLOG_DISABLE_INFO 0\r\n#include <slog\/slog.h>\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tslog::logconfig::parse(argc, argv);\r\n\r\n\t{\r\n\t\tslog::filelogdevice keep_this_instance_around(\"logoutput.log\", true);\r\n\t\t\r\n\t\tslog::info();\r\n\t\tslog::info() << \"---------------- NEW RUN ----------------\";\r\n\t\tslog::info() << \"slog version \" << slog::getmajorversion() << \".\" << slog::getminorversion() << \".\" << slog::getpatchversion();\r\n\r\n\t\tslog::error() << \"major error: failed to say hello to world\";\r\n\t\tslog::warn() << \"warning: this should be yellow\";\r\n\t\tslog::info() << \"fyi: life is full of meaningless little lines\";\r\n\t\tslog::verbose() << \"verbosity: also known as 'it goes to eleven'\";\r\n\t}\r\n\r\n\tslog::debug() << \"major debug reporting for duty... this log wont make in the log file\";\r\n\t\r\n\treturn 0;\r\n}<commit_msg>added some more tests<commit_after>\/\/================================================================================\r\n\/\/\r\n\/\/\tThe MIT License (MIT)\r\n\/\/\r\n\/\/\tCopyright (c) 2014 Konstantinos Sofokleous\r\n\/\/\r\n\/\/\tPermission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/\tof this software and associated documentation files (the \"Software\"), to deal\r\n\/\/\tin the Software without restriction, including without limitation the rights\r\n\/\/\tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/\tcopies of the Software, and to permit persons to whom the Software is\r\n\/\/\tfurnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/\tThe above copyright notice and this permission notice shall be included in\r\n\/\/\tall copies or substantial portions of the Software.\r\n\/\/\r\n\/\/\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/\tTHE SOFTWARE.\r\n\/\/\r\n\/\/================================================================================\r\n\r\n\/\/#define SLOG_DISABLE 0\r\n\/\/#define SLOG_DISABLE_INFO 0\r\n#include <slog\/slog.h>\r\n\r\nvoid compare_file_contents(const char* filename, std::string contents, std::string errorstring)\r\n{\r\n\tstd::ifstream file(filename);\r\n\tif (file.bad())\r\n\t\tthrow std::runtime_error(strobj() << \"compare_file_contents :: file '\" << filename << \"'\");\r\n\r\n\tstd::string value;\r\n\tfile >> value;\r\n\r\n\tif (value.compare(contents) != 0)\r\n\t\tthrow std::runtime_error(strobj() << errorstring);\r\n}\r\n\r\n\/\/\/ --- tests\r\n\r\nvoid emptylog(int argc, char* argv[])\r\n{\r\n\tconst char logfilename[] = \"emptylog.test.log\";\r\n\tif (_unlink(logfilename) != 0 && (errno != ENOENT))\r\n\t\tthrow std::runtime_error(strobj() << \"emptylog :: failed to delete file '\" << logfilename << \"'\");\r\n\r\n\t{\r\n\t\tslog::filelogdevice logfile(logfilename, true);\r\n\t\tslog::info::type.enabled = false;\r\n\t\tslog::info() << \"test\";\r\n\t\tslog::info::type.enabled = true;\r\n\t}\r\n\r\n\tcompare_file_contents(logfilename, \"\", \"type.enabled = false; failed not to write to log file\");\r\n}\r\n\r\nvoid simple_log_line(int argc, char* argv[])\r\n{\r\n\tconst char thisline[] = \"this simple line\";\r\n\r\n\tauto prevtime = slog::logconfig::timestamps;\r\n\tauto prevprintlogtype = slog::logconfig::print_logtype;\r\n\tslog::logconfig::timestamps = false;\r\n\tslog::logconfig::print_logtype = false;\r\n\r\n\tslog::logconfig::set_default_console_print([&thisline](const slog::logtype& type, const std::string& line)\r\n\t{\r\n\t\tif (line.compare(thisline) != 0)\r\n\t\t\tthrow std::runtime_error(strobj() << \"simple_log_line :: failed compose a simple log line with all prefixes removed\");\r\n\t});\r\n\r\n\tslog::info() << thisline;\r\n\r\n\tslog::logconfig::timestamps = prevtime;\r\n\tslog::logconfig::print_logtype = prevprintlogtype;\r\n\tslog::logconfig::set_default_console_print(nullptr);\r\n}\r\n\r\nvoid default_verbose_debug_off(int argc, char* argv[])\r\n{\r\n\tslog::logconfig::set_default_console_print([](const slog::logtype& type, const std::string& line)\r\n\t{\r\n\t\tif (line.length() > 0)\r\n\t\t\tthrow std::runtime_error(strobj() << \"default_verbose_debug_off :: default state of verbose and debug is not disabled\");\r\n\t});\r\n\r\n\tslog::debug() << \"testing\";\r\n\tslog::verbose() << \"testing again\";\r\n\r\n\tslog::logconfig::set_default_console_print(nullptr);\r\n}\r\n\r\nvoid empty_lines_should_print(int argc, char* argv[])\r\n{\r\n\tslog::logconfig::set_default_console_print([](const slog::logtype& type, const std::string& line)\r\n\t{\r\n\t\tif (line.length() == 0)\r\n\t\t\tthrow std::runtime_error(strobj() << \"empty_lines_should_print :: empty info line printed nothing\");\r\n\t});\r\n\r\n\tslog::info();\r\n\r\n\tslog::logconfig::set_default_console_print(nullptr);\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------------------\r\n\r\n#include <iostream>\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\ttry\r\n\t{\r\n\t\temptylog(argc, argv);\r\n\t\tsimple_log_line(argc, argv);\r\n\t\tdefault_verbose_debug_off(argc, argv);\r\n\t\tempty_lines_should_print(argc, argv);\r\n\r\n\t\tslog::logconfig::parse(argc, argv);\r\n\r\n\t\t{\r\n\t\t\tslog::filelogdevice keep_this_instance_around(\"logoutput.log\", true);\r\n\r\n\t\t\tslog::info();\r\n\t\t\tslog::info() << \"---------------- NEW RUN ----------------\";\r\n\t\t\tslog::info() << \"slog version \" << slog::getmajorversion() << \".\" << slog::getminorversion() << \".\" << slog::getpatchversion();\r\n\r\n\t\t\tslog::error() << \"major error: failed to say hello to world\";\r\n\t\t\tslog::warn() << \"warning: this should be yellow\";\r\n\t\t\tslog::info() << \"fyi: life is full of meaningless little lines\";\r\n\t\t\tslog::verbose() << \"verbosity: also known as 'it goes to eleven'\";\r\n\t\t\tslog::success() << \"success: you only see this when you get lucky\";\r\n\t\t}\r\n\r\n\t\tslog::debug() << \"major debug reporting for duty... this log wont make in the log file\";\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tstd::cerr << \"Test failed: \" << e.what() << std::endl;\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\tstd::cout << \"All tests succeeded\" << std::endl;\r\n\r\n\treturn 0;\r\n}<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Flacon - audio File Encoder\n * https:\/\/github.com\/flacon\/flacon\n *\n * Copyright: 2017\n * Alexander Sokoloff <sokoloff.a@gmail.com>\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 * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"tools.h\"\n\n#include <QTest>\n#include <QDir>\n#include <QFile>\n#include <QTextStream>\n#include <QProcess>\n#include <QCryptographicHash>\n#include <QIODevice>\n#include <QBuffer>\n#include <QDebug>\n#include \"..\/settings.h\"\n#include \"..\/cue.h\"\n#include \"..\/disk.h\"\n#include \"..\/converter\/decoder.h\"\n\nclass HashDevice: public QIODevice {\npublic:\n HashDevice(QCryptographicHash::Algorithm method, QObject *parent = nullptr):\n QIODevice(parent),\n mHash(method),\n mInHeader(true)\n {\n }\n\n QByteArray result() const { return mHash.result(); }\n\n\nprotected:\n qint64 readData(char*, qint64) { return -1; }\n\n qint64 writeData(const char *data, qint64 len)\n {\n if (mInHeader)\n {\n mBuf.append(data, len);\n int n = mBuf.indexOf(\"data\");\n if (n > -1 && n < mBuf.length() - 8)\n {\n mInHeader = false;\n mHash.addData(mBuf.data() + n + 8, mBuf.length() - n - 8);\n }\n return len;\n }\n\n mHash.addData(data, len);\n return len;\n }\n\nprivate:\n QByteArray mBuf;\n QCryptographicHash mHash;\n bool mInHeader;\n};\n\n\n\/************************************************\n *\n ************************************************\/\nQString calcAudioHash(const QString &fileName)\n{\n Decoder decoder;\n try\n {\n decoder.open(fileName);\n }\n catch (FlaconError &err)\n {\n FAIL(QString(\"Can't open input file '%1': %2\").arg(fileName, err.what()).toLocal8Bit());\n return \"\";\n }\n\n if (!decoder.audioFormat())\n {\n FAIL(\"Unknown format\");\n decoder.close();\n return \"\";\n }\n\n HashDevice hash(QCryptographicHash::Md5);\n hash.open(QIODevice::WriteOnly);\n decoder.extract(CueTime(), CueTime(), &hash);\n decoder.close();\n\n return hash.result().toHex();\n}\n\n\n\/************************************************\n *\n ************************************************\/\nTestCueFile::TestCueFile(const QString &fileName):\n mFileName(fileName)\n{\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid TestCueFile::setWavFile(const QString &value)\n{\n mWavFile = value;\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid TestCueFile::addTrack(const QString &index0, const QString &index1)\n{\n mTracks << TestCueTrack(index0, index1);\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid TestCueFile::addTrack(const QString &index1)\n{\n addTrack(\"\", index1);\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid TestCueFile::write()\n{\n QFile f(mFileName);\n if (!f.open(QFile::WriteOnly | QFile::Truncate))\n QFAIL(QString(\"Can't create cue file '%1': %2\").arg(mFileName).arg(f.errorString()).toLocal8Bit());\n\n QTextStream cue(&f);\n\n cue << QString(\"FILE \\\"%1\\\" WAVE\\n\").arg(mWavFile);\n for (int i=0; i < mTracks.count(); ++i)\n {\n TestCueTrack track = mTracks.at(i);\n\n cue << QString(\"\\nTRACK %1 AUDIO\\n\").arg(i + 1);\n if (track.index0 != \"\")\n cue << QString(\" INDEX 00 %1\\n\").arg(track.index0);\n\n if (track.index1 != \"\")\n cue << QString(\" INDEX 01 %1\\n\").arg(track.index1);\n }\n\n f.close();\n}\n\n\n\/************************************************\n *\n ************************************************\/\nbool compareAudioHash(const QString &file1, const QString &expected)\n{\n if (calcAudioHash(file1) != expected)\n {\n FAIL(QString(\"Compared hases are not the same for:\\n\"\n \" [%1] %2\\n\"\n \" [%3] %4\\n\")\n\n .arg(calcAudioHash(file1))\n .arg(file1)\n\n .arg(expected)\n .arg(\"expected\")\n\n .toLocal8Bit());\n return false;\n }\n return true;\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid writeHexString(const QString &str, QIODevice *out)\n{\n for (QString line : str.split('\\n'))\n {\n for (int i=0; i<line.length()-1;)\n {\n \/\/ Skip comments\n if (line.at(i) == '\/')\n break;\n\n if (line.at(i).isSpace())\n {\n ++i;\n continue;\n }\n\n\n union {\n quint16 n16;\n char b;\n };\n\n bool ok;\n n16 = line.mid(i, 2).toShort(&ok, 16);\n if (!ok)\n throw QString(\"Incorrect HEX data at %1:\\n%2\").arg(i).arg(line);\n\n out->write(&b, 1);\n i+=2;\n }\n }\n}\n\n\n\/************************************************\n *\n ************************************************\/\nQByteArray writeHexString(const QString &str)\n{\n QBuffer data;\n data.open(QBuffer::ReadWrite);\n writeHexString(str, &data);\n return data.buffer();\n}\n\n\n\/************************************************\n *\n ************************************************\/\nstatic void writeTestWavData(QIODevice *device, quint64 dataSize)\n{\n static const int BUF_SIZE = 1024 * 1024;\n\n quint32 x=123456789, y=362436069, z=521288629;\n union {\n quint32 t;\n char bytes[4];\n };\n\n QByteArray buf;\n\n buf.reserve(4 * 1024 * 1024);\n buf.reserve(BUF_SIZE);\n for (uint i=0; i<(dataSize\/ sizeof(quint32)); ++i)\n {\n \/\/ xorshf96 ...................\n x ^= x << 16;\n x ^= x >> 5;\n x ^= x << 1;\n\n t = x;\n x = y;\n y = z;\n z = t ^ x ^ y;\n \/\/ xorshf96 ...................\n\n buf.append(bytes, 4);\n if (buf.size() >= BUF_SIZE)\n {\n device->write(buf);\n buf.resize(0);\n }\n }\n\n device->write(buf);\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid createWavFile(const QString &fileName, const QString &header, const int duration)\n{\n QBuffer wavHdr;\n wavHdr.open(QBuffer::ReadWrite);\n writeHexString(header, &wavHdr);\n\n if (duration) {\n quint32 bitsPerSample =\n (quint8(wavHdr.buffer()[28]) << 0) +\n (quint8(wavHdr.buffer()[29]) << 8) +\n (quint8(wavHdr.buffer()[30]) << 16) +\n (quint8(wavHdr.buffer()[31]) << 24);\n\n quint32 ckSize = bitsPerSample * duration + wavHdr.buffer().size() - 8 + 8;\n wavHdr.buffer()[4] = quint8(ckSize >> 0);\n wavHdr.buffer()[5] = quint8(ckSize >> 8);\n wavHdr.buffer()[6] = quint8(ckSize >> 16);\n wavHdr.buffer()[7] = quint8(ckSize >> 24);\n }\n\n\n \/\/ See http:\/\/www-mmsp.ece.mcgill.ca\/Documents\/AudioFormats\/WAVE\/WAVE.html\n quint32 ckSize =\n (quint8(wavHdr.buffer()[4]) << 0) +\n (quint8(wavHdr.buffer()[5]) << 8) +\n (quint8(wavHdr.buffer()[6]) << 16) +\n (quint8(wavHdr.buffer()[7]) << 24);\n\n quint32 dataSize = ckSize - wavHdr.size();\n\n QFile file(fileName);\n\n if (file.exists() && file.size() == ckSize + 8)\n return;\n\n if (!file.open(QFile::WriteOnly | QFile::Truncate))\n QFAIL(QString(\"Can't create file '%1': %2\").arg(fileName, file.errorString()).toLocal8Bit());\n\n file.write(wavHdr.buffer());\n file.write(\"data\", 4);\n char buf[4];\n buf[0] = quint8(dataSize);\n buf[1] = quint8(dataSize >> 8);\n buf[2] = quint8(dataSize >> 16);\n buf[3] = quint8(dataSize >> 24);\n file.write(buf, 4);\n\n writeTestWavData(&file, dataSize);\n file.close();\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid encodeAudioFile(const QString &wavFileName, const QString &outFileName)\n{\n if (QFileInfo(outFileName).exists())\n return;\n\n QString program;\n QStringList args;\n\n QString ext = QFileInfo(outFileName).suffix();\n\n if(ext == \"ape\")\n {\n program = \"mac\";\n args << wavFileName;\n args << outFileName;\n args << \"-c2000\";\n\n }\n\n else if(ext == \"flac\")\n {\n program = \"flac\";\n args << \"--silent\";\n args << \"--force\";\n args << \"-o\" << outFileName;\n args << wavFileName;\n }\n\n else if(ext == \"wv\")\n {\n program = \"wavpack\";\n args << wavFileName;\n args << \"-y\";\n args << \"-q\";\n args << \"-o\" << outFileName;\n }\n\n else if(ext == \"tta\")\n {\n program = \"ttaenc\";\n args << \"-o\" << outFileName;\n args << \"-e\";\n args << wavFileName;\n args << \"\/\";\n }\n\n else\n {\n QFAIL(QString(\"Can't create file '%1': unknown file format\").arg(outFileName).toLocal8Bit());\n }\n\n\n QProcess proc;\n proc.start(program, args);\n proc.waitForFinished(3 * 60 * 10000);\n if (proc.exitStatus() != 0)\n QFAIL(QString(\"Can't encode to file '%1':\").arg(outFileName).toLocal8Bit() + proc.readAllStandardError());\n\n if (!QFileInfo(outFileName).isFile())\n QFAIL(QString(\"Can't encode to file '%1' (file don't exists'):\").arg(outFileName).toLocal8Bit() + proc.readAllStandardError());\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid testFail(const QString &message, const char *file, int line)\n{\n QTest::qFail(message.toLocal8Bit().data(), file, line);\n}\n\n\n\/************************************************\n *\n ************************************************\/\nDisk *loadFromCue(const QString &cueFile)\n{\n try\n {\n QVector<CueDisk> cue = CueReader().load(cueFile);\n Disk *res = new Disk();\n res->loadFromCue(cue.first());\n return res;\n }\n catch (FlaconError &err)\n {\n FAIL(err.what());\n }\n return nullptr;\n}\n\n<commit_msg>Accurate encoder error handling in tests.<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Flacon - audio File Encoder\n * https:\/\/github.com\/flacon\/flacon\n *\n * Copyright: 2017\n * Alexander Sokoloff <sokoloff.a@gmail.com>\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 * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"tools.h\"\n\n#include <QTest>\n#include <QDir>\n#include <QFile>\n#include <QTextStream>\n#include <QProcess>\n#include <QCryptographicHash>\n#include <QIODevice>\n#include <QBuffer>\n#include <QDebug>\n#include \"..\/settings.h\"\n#include \"..\/cue.h\"\n#include \"..\/disk.h\"\n#include \"..\/converter\/decoder.h\"\n\nclass HashDevice: public QIODevice {\npublic:\n HashDevice(QCryptographicHash::Algorithm method, QObject *parent = nullptr):\n QIODevice(parent),\n mHash(method),\n mInHeader(true)\n {\n }\n\n QByteArray result() const { return mHash.result(); }\n\n\nprotected:\n qint64 readData(char*, qint64) { return -1; }\n\n qint64 writeData(const char *data, qint64 len)\n {\n if (mInHeader)\n {\n mBuf.append(data, len);\n int n = mBuf.indexOf(\"data\");\n if (n > -1 && n < mBuf.length() - 8)\n {\n mInHeader = false;\n mHash.addData(mBuf.data() + n + 8, mBuf.length() - n - 8);\n }\n return len;\n }\n\n mHash.addData(data, len);\n return len;\n }\n\nprivate:\n QByteArray mBuf;\n QCryptographicHash mHash;\n bool mInHeader;\n};\n\n\n\/************************************************\n *\n ************************************************\/\nQString calcAudioHash(const QString &fileName)\n{\n Decoder decoder;\n try\n {\n decoder.open(fileName);\n }\n catch (FlaconError &err)\n {\n FAIL(QString(\"Can't open input file '%1': %2\").arg(fileName, err.what()).toLocal8Bit());\n return \"\";\n }\n\n if (!decoder.audioFormat())\n {\n FAIL(\"Unknown format\");\n decoder.close();\n return \"\";\n }\n\n HashDevice hash(QCryptographicHash::Md5);\n hash.open(QIODevice::WriteOnly);\n decoder.extract(CueTime(), CueTime(), &hash);\n decoder.close();\n\n return hash.result().toHex();\n}\n\n\n\/************************************************\n *\n ************************************************\/\nTestCueFile::TestCueFile(const QString &fileName):\n mFileName(fileName)\n{\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid TestCueFile::setWavFile(const QString &value)\n{\n mWavFile = value;\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid TestCueFile::addTrack(const QString &index0, const QString &index1)\n{\n mTracks << TestCueTrack(index0, index1);\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid TestCueFile::addTrack(const QString &index1)\n{\n addTrack(\"\", index1);\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid TestCueFile::write()\n{\n QFile f(mFileName);\n if (!f.open(QFile::WriteOnly | QFile::Truncate))\n QFAIL(QString(\"Can't create cue file '%1': %2\").arg(mFileName).arg(f.errorString()).toLocal8Bit());\n\n QTextStream cue(&f);\n\n cue << QString(\"FILE \\\"%1\\\" WAVE\\n\").arg(mWavFile);\n for (int i=0; i < mTracks.count(); ++i)\n {\n TestCueTrack track = mTracks.at(i);\n\n cue << QString(\"\\nTRACK %1 AUDIO\\n\").arg(i + 1);\n if (track.index0 != \"\")\n cue << QString(\" INDEX 00 %1\\n\").arg(track.index0);\n\n if (track.index1 != \"\")\n cue << QString(\" INDEX 01 %1\\n\").arg(track.index1);\n }\n\n f.close();\n}\n\n\n\/************************************************\n *\n ************************************************\/\nbool compareAudioHash(const QString &file1, const QString &expected)\n{\n if (calcAudioHash(file1) != expected)\n {\n FAIL(QString(\"Compared hases are not the same for:\\n\"\n \" [%1] %2\\n\"\n \" [%3] %4\\n\")\n\n .arg(calcAudioHash(file1))\n .arg(file1)\n\n .arg(expected)\n .arg(\"expected\")\n\n .toLocal8Bit());\n return false;\n }\n return true;\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid writeHexString(const QString &str, QIODevice *out)\n{\n for (QString line : str.split('\\n'))\n {\n for (int i=0; i<line.length()-1;)\n {\n \/\/ Skip comments\n if (line.at(i) == '\/')\n break;\n\n if (line.at(i).isSpace())\n {\n ++i;\n continue;\n }\n\n\n union {\n quint16 n16;\n char b;\n };\n\n bool ok;\n n16 = line.mid(i, 2).toShort(&ok, 16);\n if (!ok)\n throw QString(\"Incorrect HEX data at %1:\\n%2\").arg(i).arg(line);\n\n out->write(&b, 1);\n i+=2;\n }\n }\n}\n\n\n\/************************************************\n *\n ************************************************\/\nQByteArray writeHexString(const QString &str)\n{\n QBuffer data;\n data.open(QBuffer::ReadWrite);\n writeHexString(str, &data);\n return data.buffer();\n}\n\n\n\/************************************************\n *\n ************************************************\/\nstatic void writeTestWavData(QIODevice *device, quint64 dataSize)\n{\n static const int BUF_SIZE = 1024 * 1024;\n\n quint32 x=123456789, y=362436069, z=521288629;\n union {\n quint32 t;\n char bytes[4];\n };\n\n QByteArray buf;\n\n buf.reserve(4 * 1024 * 1024);\n buf.reserve(BUF_SIZE);\n for (uint i=0; i<(dataSize\/ sizeof(quint32)); ++i)\n {\n \/\/ xorshf96 ...................\n x ^= x << 16;\n x ^= x >> 5;\n x ^= x << 1;\n\n t = x;\n x = y;\n y = z;\n z = t ^ x ^ y;\n \/\/ xorshf96 ...................\n\n buf.append(bytes, 4);\n if (buf.size() >= BUF_SIZE)\n {\n device->write(buf);\n buf.resize(0);\n }\n }\n\n device->write(buf);\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid createWavFile(const QString &fileName, const QString &header, const int duration)\n{\n QBuffer wavHdr;\n wavHdr.open(QBuffer::ReadWrite);\n writeHexString(header, &wavHdr);\n\n if (duration) {\n quint32 bitsPerSample =\n (quint8(wavHdr.buffer()[28]) << 0) +\n (quint8(wavHdr.buffer()[29]) << 8) +\n (quint8(wavHdr.buffer()[30]) << 16) +\n (quint8(wavHdr.buffer()[31]) << 24);\n\n quint32 ckSize = bitsPerSample * duration + wavHdr.buffer().size() - 8 + 8;\n wavHdr.buffer()[4] = quint8(ckSize >> 0);\n wavHdr.buffer()[5] = quint8(ckSize >> 8);\n wavHdr.buffer()[6] = quint8(ckSize >> 16);\n wavHdr.buffer()[7] = quint8(ckSize >> 24);\n }\n\n\n \/\/ See http:\/\/www-mmsp.ece.mcgill.ca\/Documents\/AudioFormats\/WAVE\/WAVE.html\n quint32 ckSize =\n (quint8(wavHdr.buffer()[4]) << 0) +\n (quint8(wavHdr.buffer()[5]) << 8) +\n (quint8(wavHdr.buffer()[6]) << 16) +\n (quint8(wavHdr.buffer()[7]) << 24);\n\n quint32 dataSize = ckSize - wavHdr.size();\n\n QFile file(fileName);\n\n if (file.exists() && file.size() == ckSize + 8)\n return;\n\n if (!file.open(QFile::WriteOnly | QFile::Truncate))\n QFAIL(QString(\"Can't create file '%1': %2\").arg(fileName, file.errorString()).toLocal8Bit());\n\n file.write(wavHdr.buffer());\n file.write(\"data\", 4);\n char buf[4];\n buf[0] = quint8(dataSize);\n buf[1] = quint8(dataSize >> 8);\n buf[2] = quint8(dataSize >> 16);\n buf[3] = quint8(dataSize >> 24);\n file.write(buf, 4);\n\n writeTestWavData(&file, dataSize);\n file.close();\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid encodeAudioFile(const QString &wavFileName, const QString &outFileName)\n{\n if (QFileInfo(outFileName).exists() && QFileInfo(outFileName).size() > 1024)\n return;\n\n QString program;\n QStringList args;\n\n QString ext = QFileInfo(outFileName).suffix();\n\n if(ext == \"ape\")\n {\n program = \"mac\";\n args << wavFileName;\n args << outFileName;\n args << \"-c2000\";\n\n }\n\n else if(ext == \"flac\")\n {\n program = \"flac\";\n args << \"--silent\";\n args << \"--force\";\n args << \"-o\" << outFileName;\n args << wavFileName;\n }\n\n else if(ext == \"wv\")\n {\n program = \"wavpack\";\n args << wavFileName;\n args << \"-y\";\n args << \"-q\";\n args << \"-o\" << outFileName;\n }\n\n else if(ext == \"tta\")\n {\n program = \"ttaenc\";\n args << \"-o\" << outFileName;\n args << \"-e\";\n args << wavFileName;\n args << \"\/\";\n }\n\n else\n {\n QFAIL(QString(\"Can't create file '%1': unknown file format\").arg(outFileName).toLocal8Bit());\n }\n\n\n bool ok = true;\n QProcess proc;\n proc.start(program, args);\n ok = proc.waitForStarted(3 * 1000);\n ok = ok && proc.waitForFinished(3 * 60 * 100) ;\n ok = ok && (proc.exitStatus() == 0);\n\n if (!ok)\n {\n QFAIL(QString(\"Can't encode %1 %2:\")\n .arg(program)\n .arg(args.join(\" \"))\n .toLocal8Bit()\n + proc.readAllStandardError());\n }\n\n if (!QFileInfo(outFileName).isFile())\n {\n QFAIL(QString(\"Can't encode to file '%1' (file don't exists'):\")\n .arg(outFileName).toLocal8Bit()\n + proc.readAllStandardError());\n }\n}\n\n\n\/************************************************\n *\n ************************************************\/\nvoid testFail(const QString &message, const char *file, int line)\n{\n QTest::qFail(message.toLocal8Bit().data(), file, line);\n}\n\n\n\/************************************************\n *\n ************************************************\/\nDisk *loadFromCue(const QString &cueFile)\n{\n try\n {\n QVector<CueDisk> cue = CueReader().load(cueFile);\n Disk *res = new Disk();\n res->loadFromCue(cue.first());\n return res;\n }\n catch (FlaconError &err)\n {\n FAIL(err.what());\n }\n return nullptr;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Planning: change FallbackSpeed params<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ game.cpp\n\/\/ tetris\n\/\/\n\/\/ Created by Xhacker Liu on 2\/13\/14.\n\/\/ Copyright (c) 2014 Xhacker. All rights reserved.\n\/\/\n\n#include \"Game.h\"\n#include \"constants.h\"\n#include <sys\/time.h>\n#include <unistd.h>\n\nGame *Game::singleton = NULL;\n\nvoid Game::run(int argc, char **argv)\n{\n singleton = this;\n\n timeval t;\n gettimeofday(&t, NULL);\n srand((unsigned)(t.tv_sec * 1000 + t.tv_usec));\n\n tetromino.game = singleton;\n tetromino.board = &board;\n\n glutInit(&argc, argv);\n#ifdef __APPLE__\n glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_RGBA | GLUT_DOUBLE);\n#else\n glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n#endif\n glutInitWindowSize(340, 600);\n glutCreateWindow(\"Xetris!\");\n\n#ifndef __APPLE__\n glewInit();\n#endif\n\n reset();\n init();\n\n glutDisplayFunc(display);\n glutSpecialFunc(keyboard);\n glutIdleFunc(idle);\n\n glutMainLoop();\n}\n\nvoid Game::init()\n{\n vec2 points[kTotalPoints];\n for (int i = 0; i < kNumOfHLines; ++i) {\n points[i * 2 ] = vec2(-W, -H + BLOCK_H * i);\n points[i * 2 + 1] = vec2( W, -H + BLOCK_H * i);\n }\n for (int i = 0; i < kNumOfVLines; ++i) {\n points[kNumOfHPoints + i * 2 ] = vec2(-W + BLOCK_W * i, -H);\n points[kNumOfHPoints + i * 2 + 1] = vec2(-W + BLOCK_W * i, H);\n }\n\n vec4 colors[kTotalPoints];\n for (int i = 0; i < kNumOfHPoints + kNumOfVPoints; ++i) {\n colors[i] = vec4(0.93, 0.93, 0.93, 1.0);\n }\n\n GLuint vaoID;\n glGenVertexArrays(1, &vaoID);\n glBindVertexArray(vaoID);\n\n GLuint vboID;\n glGenBuffers(1, &vboID);\n glBindBuffer(GL_ARRAY_BUFFER, vboID);\n glBufferData(GL_ARRAY_BUFFER, sizeof(points) + sizeof(colors), points, GL_STATIC_DRAW);\n glBufferSubData(GL_ARRAY_BUFFER, kTotalPoints * sizeof(vec2), sizeof(colors), colors);\n\n GLuint program = InitShader(\"vshader.glsl\", \"fshader.glsl\");\n GLuint vPosition = glGetAttribLocation(program, \"vPosition\");\n glEnableVertexAttribArray(vPosition);\n glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));\n\n GLuint vColor = glGetAttribLocation(program, \"vColor\");\n glEnableVertexAttribArray(vColor);\n glVertexAttribPointer(vColor, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(points)));\n\n glClearColor(1.0, 1.0, 1.0, 1.0);\n}\n\nvoid Game::reset()\n{\n tetromino.interval = kDefaultInterval;\n tetromino.reset();\n board.reset();\n is_game_over = false;\n}\n\nvoid Game::display()\n{\n glClear(GL_COLOR_BUFFER_BIT);\n\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n glEnable(GL_CULL_FACE);\n\n \/\/ draw grids\n glDrawArrays(GL_LINES, 0, kNumOfHPoints + kNumOfVPoints);\n\n \/\/ draw current tetromino\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n glDrawArrays(GL_TRIANGLE_STRIP, kBeginTetrominoPoints, kNumOfTetrominoPoints);\n\n \/\/ draw bottom blocks\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n glDrawArrays(GL_TRIANGLE_STRIP, kBeginBoardPoints, singleton->board.num_of_points);\n\n glutSwapBuffers();\n}\n\nvoid Game::keyboard(int key, int x, int y)\n{\n switch (key) {\n case GLUT_KEY_LEFT:\n singleton->tetromino.left();\n break;\n case GLUT_KEY_RIGHT:\n singleton->tetromino.right();\n break;\n case GLUT_KEY_UP:\n singleton->tetromino.rotate();\n break;\n case GLUT_KEY_DOWN:\n singleton->tetromino.down();\n break;\n case 'w': case 'W':\n singleton->tetromino.up();\n break;\n case 'r': case 'R':\n singleton->reset();\n break;\n case 'q': case 'Q':\n case kKeyCodeESC: case kKeyCodeESC2:\n exit(EXIT_SUCCESS);\n break;\n }\n}\n\nvoid Game::idle()\n{\n if (!singleton->is_game_over) {\n singleton->tetromino.write_buffer();\n singleton->board.write_buffer();\n\n glutPostRedisplay();\n }\n usleep(20);\n}\n\nvoid Game::game_over()\n{\n is_game_over = true;\n}\n<commit_msg>Fix segfault. Remain other issues.<commit_after>\/\/\n\/\/ game.cpp\n\/\/ tetris\n\/\/\n\/\/ Created by Xhacker Liu on 2\/13\/14.\n\/\/ Copyright (c) 2014 Xhacker. All rights reserved.\n\/\/\n\n#include \"Game.h\"\n#include \"constants.h\"\n#include <sys\/time.h>\n#include <unistd.h>\n\nGame *Game::singleton = NULL;\n\nvoid Game::run(int argc, char **argv)\n{\n singleton = this;\n\n timeval t;\n gettimeofday(&t, NULL);\n srand((unsigned)(t.tv_sec * 1000 + t.tv_usec));\n\n tetromino.game = singleton;\n tetromino.board = &board;\n\n glutInit(&argc, argv);\n#ifdef __APPLE__\n glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_RGBA | GLUT_DOUBLE);\n#else\n glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n#endif\n glutInitWindowSize(340, 600);\n glutCreateWindow(\"Xetris!\");\n\n#ifndef __APPLE__\n glewInit();\n#endif\n\n reset();\n init();\n\n glutDisplayFunc(display);\n glutSpecialFunc(keyboard);\n glutIdleFunc(idle);\n\n glutMainLoop();\n}\n\nvoid Game::init()\n{\n vec2 points[kTotalPoints];\n for (int i = 0; i < kNumOfHLines; ++i) {\n points[i * 2 ] = vec2(-W, -H + BLOCK_H * i);\n points[i * 2 + 1] = vec2( W, -H + BLOCK_H * i);\n }\n for (int i = 0; i < kNumOfVLines; ++i) {\n points[kNumOfHPoints + i * 2 ] = vec2(-W + BLOCK_W * i, -H);\n points[kNumOfHPoints + i * 2 + 1] = vec2(-W + BLOCK_W * i, H);\n }\n\n vec4 colors[kTotalPoints];\n for (int i = 0; i < kNumOfHPoints + kNumOfVPoints; ++i) {\n colors[i] = vec4(0.93, 0.93, 0.93, 1.0);\n }\n\n GLuint vaoID;\n glGenVertexArrays(1, &vaoID);\n glBindVertexArray(vaoID);\n\n GLuint vboID;\n glGenBuffers(1, &vboID);\n glBindBuffer(GL_ARRAY_BUFFER, vboID);\n glBufferData(GL_ARRAY_BUFFER, sizeof(points) + sizeof(colors), NULL, GL_STATIC_DRAW);\n glBufferSubData(GL_ARRAY_BUFFER, 0, kTotalPoints * sizeof(vec2), points);\n glBufferSubData(GL_ARRAY_BUFFER, kTotalPoints * sizeof(vec2), sizeof(colors), colors);\n\n GLuint program = InitShader(\"vshader.glsl\", \"fshader.glsl\");\n GLuint vPosition = glGetAttribLocation(program, \"vPosition\");\n glEnableVertexAttribArray(vPosition);\n glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));\n\n GLuint vColor = glGetAttribLocation(program, \"vColor\");\n glEnableVertexAttribArray(vColor);\n glVertexAttribPointer(vColor, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(points)));\n\n glClearColor(1.0, 1.0, 1.0, 1.0);\n}\n\nvoid Game::reset()\n{\n tetromino.interval = kDefaultInterval;\n tetromino.reset();\n board.reset();\n is_game_over = false;\n}\n\nvoid Game::display()\n{\n glClear(GL_COLOR_BUFFER_BIT);\n\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n glEnable(GL_CULL_FACE);\n\n \/\/ draw grids\n glDrawArrays(GL_LINES, 0, kNumOfHPoints + kNumOfVPoints);\n\n \/\/ draw current tetromino\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n glDrawArrays(GL_TRIANGLE_STRIP, kBeginTetrominoPoints, kNumOfTetrominoPoints);\n\n \/\/ draw bottom blocks\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n glDrawArrays(GL_TRIANGLE_STRIP, kBeginBoardPoints, singleton->board.num_of_points);\n\n glutSwapBuffers();\n}\n\nvoid Game::keyboard(int key, int x, int y)\n{\n switch (key) {\n case GLUT_KEY_LEFT:\n singleton->tetromino.left();\n break;\n case GLUT_KEY_RIGHT:\n singleton->tetromino.right();\n break;\n case GLUT_KEY_UP:\n singleton->tetromino.rotate();\n break;\n case GLUT_KEY_DOWN:\n singleton->tetromino.down();\n break;\n case 'w': case 'W':\n singleton->tetromino.up();\n break;\n case 'r': case 'R':\n singleton->reset();\n break;\n case 'q': case 'Q':\n case kKeyCodeESC: case kKeyCodeESC2:\n exit(EXIT_SUCCESS);\n break;\n }\n}\n\nvoid Game::idle()\n{\n if (!singleton->is_game_over) {\n singleton->tetromino.write_buffer();\n singleton->board.write_buffer();\n\n glutPostRedisplay();\n }\n usleep(20);\n}\n\nvoid Game::game_over()\n{\n is_game_over = true;\n}\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE NiftyMulticutTest\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <iostream> \n#include <random>\n\n#include \"nifty\/tools\/runtime_check.hxx\"\n#include \"nifty\/graph\/undirected_list_graph.hxx\"\n#include \"nifty\/graph\/optimization\/multicut\/multicut_objective.hxx\"\n#include \"nifty\/graph\/optimization\/multicut\/multicut_ilp.hxx\"\n\n#ifdef WITH_GUROBI\n#include \"nifty\/ilp_backend\/gurobi.hxx\"\n#endif\n\n#ifdef WITH_CPLEX\n#include \"nifty\/ilp_backend\/cplex.hxx\"\n#endif\n\n#ifdef WITH_GLPK\n#include \"nifty\/ilp_backend\/glpk.hxx\"\n#endif\n\nBOOST_AUTO_TEST_CASE(RandomizedMulticutTest)\n{\n \/\/ rand gen \n \/\/std::random_device rd();\n std::mt19937 gen(42);\/\/rd());\n std::uniform_real_distribution<> dis(-1.0, 1.0); \n\n\n\n typedef double WeightType;\n typedef nifty::graph::UndirectedGraph<> Graph;\n typedef nifty::graph::MulticutObjective<Graph, WeightType> Objective;\n typedef nifty::graph::MulticutVerboseVisitor<Objective> VerboseVisitor;\n\n\n\n \/\/ create a grid graph\n const size_t s = 15;\n Graph g(s*s);\n for(auto y=0; y<s; ++y)\n for(auto x=0; x<s; ++x){\n auto u = x + y*s;\n if(x+1 < s){\n auto v = x + 1 + y * s;\n g.insertEdge(u, v);\n }\n if(y+1 < s){\n auto v = x + (y + 1) * s;\n g.insertEdge(u, v);\n }\n }\n\n\n \/\/ create an objective \n Objective objective(g);\n auto & weights = objective.weights(); \n\n \/\/ fill the objective with values\n for(auto e : g.edges())\n weights[e] = dis(gen);\n\n \/\/ optimize gurobi\n #ifdef WITH_GUROBI\n {\n std::cout<<\"opt gurobi \\n\";\n typedef nifty::ilp_backend::Gurobi IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n \/\/ optimize \n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint8_t> outputEdgeLabels(g,0);\n \n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels); \n }\n #endif\n\n #ifdef WITH_CPLEX\n {\n std::cout<<\"opt cplex \\n\";\n typedef nifty::ilp_backend::Cplex IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n \/\/ optimize \n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint8_t> outputEdgeLabels(g,0);\n \n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels); \n }\n #endif\n\n #ifdef WITH_GLPK\n {\n std::cout<<\"opt glpk \\n\";\n typedef nifty::ilp_backend::Glpk IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n \/\/ optimize \n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint8_t> outputEdgeLabels(g,0);\n \n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels); \n }\n #endif\n}\n\n\nBOOST_AUTO_TEST_CASE(SimpleMulticutTest)\n{\n \/\/ rand gen \n \/\/std::random_device rd();\n std::mt19937 gen(42);\/\/rd());\n std::uniform_real_distribution<> dis(-1.0, 1.0); \n\n\n\n typedef double WeightType;\n typedef nifty::graph::UndirectedGraph<> Graph;\n typedef nifty::graph::MulticutObjective<Graph, WeightType> Objective;\n typedef nifty::graph::MulticutVerboseVisitor<Objective> VerboseVisitor;\n\n\n\n\n \/\/ create a grid graph\n const size_t sx = 8;\n const size_t sy = 13;\n auto node = [&](uint64_t x, uint64_t y){\n return x + y*sx;\n };\n Graph g(sx*sy);\n for(auto y=0; y<sy; ++y)\n for(auto x=0; x<sx; ++x){\n auto u = node(x, y);\n if(x+1 < sx){\n auto v = node(x+1, y);\n g.insertEdge(u, v);\n }\n if(y+1 < sy){\n auto v = node(x, y+1);\n g.insertEdge(u, v);\n }\n }\n\n\n \/\/ create an objective \n Objective objective(g);\n auto & weights = objective.weights(); \n\n \/\/ fill the objective with values\n for(auto e : g.edges())\n weights[e] = 10.0;\n\n auto yPos = std::vector<int>({0, 2, 4, 8, 10,11, 12});\n for(auto y : yPos){\n auto e = g.findEdge( node(3, y), node(4, y) );\n NIFTY_ASSERT_OP(e,!=,-1);\n weights[e] = -10.0;\n }\n\n typename Graph::EdgeMap<uint16_t> shouldSolution(g,0);\n for(size_t y=0; y<sy; ++y){\n auto e = g.findEdge( node(3, y), node(3+1, y) );\n shouldSolution[e] = 1;\n }\n\n\n\n \/\/ optimize gurobi\n #ifdef WITH_GUROBI\n {\n std::cout<<\"opt gurobi \\n\";\n typedef nifty::ilp_backend::Gurobi IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n \n typedef typename Solver::NodeLabels NodeLabels;\n Solver solver(objective);\n\n nifty::graph::graph_maps::EdgeMap<Graph, uint16_t> outputEdgeLabels(g,0);\n\n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels);\n\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels);\n for(auto e : g.edges()){\n NIFTY_TEST_OP(shouldSolution[e],==,outputEdgeLabels[e]);\n }\n }\n #endif\n\n \/\/ optimize cplex\n #ifdef WITH_CPLEX\n {\n std::cout<<\"opt cplex \\n\";\n typedef nifty::ilp_backend::Cplex IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n\n\n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint16_t> outputEdgeLabels(g,0);\n\n\n\n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels);\n \n for(auto e : g.edges()){\n NIFTY_TEST_OP(shouldSolution[e],==,outputEdgeLabels[e]);\n }\n }\n #endif\n\n \/\/ optimize cplex\n #ifdef WITH_GLPK\n {\n std::cout<<\"opt glpk \\n\";\n typedef nifty::ilp_backend::Glpk IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n\n\n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint16_t> outputEdgeLabels(g,0);\n\n\n\n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels);\n \n for(auto e : g.edges()){\n NIFTY_TEST_OP(shouldSolution[e],==,outputEdgeLabels[e]);\n }\n }\n #endif\n}\n<commit_msg>minor fix<commit_after>#define BOOST_TEST_MODULE NiftyMulticutTest\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <iostream> \n#include <random>\n\n#include \"nifty\/tools\/runtime_check.hxx\"\n#include \"nifty\/graph\/undirected_list_graph.hxx\"\n#include \"nifty\/graph\/optimization\/multicut\/multicut_objective.hxx\"\n#include \"nifty\/graph\/optimization\/multicut\/multicut_ilp.hxx\"\n\n#ifdef WITH_GUROBI\n#include \"nifty\/ilp_backend\/gurobi.hxx\"\n#endif\n\n#ifdef WITH_CPLEX\n#include \"nifty\/ilp_backend\/cplex.hxx\"\n#endif\n\n#ifdef WITH_GLPK\n#include \"nifty\/ilp_backend\/glpk.hxx\"\n#endif\n\nBOOST_AUTO_TEST_CASE(RandomizedMulticutTest)\n{\n \/\/ rand gen \n \/\/std::random_device rd();\n std::mt19937 gen(42);\/\/rd());\n std::uniform_real_distribution<> dis(-1.0, 1.0); \n\n\n\n typedef double WeightType;\n typedef nifty::graph::UndirectedGraph<> Graph;\n typedef nifty::graph::optimization::multicut::MulticutObjective<Graph, WeightType> Objective;\n typedef nifty::graph::optimization::multicut::MulticutVerboseVisitor<Objective> VerboseVisitor;\n\n\n\n \/\/ create a grid graph\n const size_t s = 15;\n Graph g(s*s);\n for(auto y=0; y<s; ++y)\n for(auto x=0; x<s; ++x){\n auto u = x + y*s;\n if(x+1 < s){\n auto v = x + 1 + y * s;\n g.insertEdge(u, v);\n }\n if(y+1 < s){\n auto v = x + (y + 1) * s;\n g.insertEdge(u, v);\n }\n }\n\n\n \/\/ create an objective \n Objective objective(g);\n auto & weights = objective.weights(); \n\n \/\/ fill the objective with values\n for(auto e : g.edges())\n weights[e] = dis(gen);\n\n \/\/ optimize gurobi\n #ifdef WITH_GUROBI\n {\n std::cout<<\"opt gurobi \\n\";\n typedef nifty::ilp_backend::Gurobi IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n \/\/ optimize \n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint8_t> outputEdgeLabels(g,0);\n \n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels); \n }\n #endif\n\n #ifdef WITH_CPLEX\n {\n std::cout<<\"opt cplex \\n\";\n typedef nifty::ilp_backend::Cplex IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n \/\/ optimize \n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint8_t> outputEdgeLabels(g,0);\n \n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels); \n }\n #endif\n\n #ifdef WITH_GLPK\n {\n std::cout<<\"opt glpk \\n\";\n typedef nifty::ilp_backend::Glpk IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n \/\/ optimize \n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint8_t> outputEdgeLabels(g,0);\n \n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels); \n }\n #endif\n}\n\n\nBOOST_AUTO_TEST_CASE(SimpleMulticutTest)\n{\n \/\/ rand gen \n \/\/std::random_device rd();\n std::mt19937 gen(42);\/\/rd());\n std::uniform_real_distribution<> dis(-1.0, 1.0); \n\n\n\n typedef double WeightType;\n typedef nifty::graph::UndirectedGraph<> Graph;\n typedef nifty::graph::optimization::multicut::MulticutObjective<Graph, WeightType> Objective;\n typedef nifty::graph::optimization::multicut::MulticutVerboseVisitor<Objective> VerboseVisitor;\n\n\n\n\n \/\/ create a grid graph\n const size_t sx = 8;\n const size_t sy = 13;\n auto node = [&](uint64_t x, uint64_t y){\n return x + y*sx;\n };\n Graph g(sx*sy);\n for(auto y=0; y<sy; ++y)\n for(auto x=0; x<sx; ++x){\n auto u = node(x, y);\n if(x+1 < sx){\n auto v = node(x+1, y);\n g.insertEdge(u, v);\n }\n if(y+1 < sy){\n auto v = node(x, y+1);\n g.insertEdge(u, v);\n }\n }\n\n\n \/\/ create an objective \n Objective objective(g);\n auto & weights = objective.weights(); \n\n \/\/ fill the objective with values\n for(auto e : g.edges())\n weights[e] = 10.0;\n\n auto yPos = std::vector<int>({0, 2, 4, 8, 10,11, 12});\n for(auto y : yPos){\n auto e = g.findEdge( node(3, y), node(4, y) );\n NIFTY_ASSERT_OP(e,!=,-1);\n weights[e] = -10.0;\n }\n\n typename Graph::EdgeMap<uint16_t> shouldSolution(g,0);\n for(size_t y=0; y<sy; ++y){\n auto e = g.findEdge( node(3, y), node(3+1, y) );\n shouldSolution[e] = 1;\n }\n\n\n\n \/\/ optimize gurobi\n #ifdef WITH_GUROBI\n {\n std::cout<<\"opt gurobi \\n\";\n typedef nifty::ilp_backend::Gurobi IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n \n typedef typename Solver::NodeLabels NodeLabels;\n Solver solver(objective);\n\n nifty::graph::graph_maps::EdgeMap<Graph, uint16_t> outputEdgeLabels(g,0);\n\n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels);\n\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels);\n for(auto e : g.edges()){\n NIFTY_TEST_OP(shouldSolution[e],==,outputEdgeLabels[e]);\n }\n }\n #endif\n\n \/\/ optimize cplex\n #ifdef WITH_CPLEX\n {\n std::cout<<\"opt cplex \\n\";\n typedef nifty::ilp_backend::Cplex IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n\n\n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint16_t> outputEdgeLabels(g,0);\n\n\n\n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels);\n \n for(auto e : g.edges()){\n NIFTY_TEST_OP(shouldSolution[e],==,outputEdgeLabels[e]);\n }\n }\n #endif\n\n \/\/ optimize cplex\n #ifdef WITH_GLPK\n {\n std::cout<<\"opt glpk \\n\";\n typedef nifty::ilp_backend::Glpk IlpSolver;\n typedef nifty::graph::optimization::multicut::MulticutIlp<Objective, IlpSolver> Solver;\n typedef typename Solver::NodeLabels NodeLabels;\n\n\n Solver solver(objective);\n nifty::graph::graph_maps::EdgeMap<Graph, uint16_t> outputEdgeLabels(g,0);\n\n\n\n VerboseVisitor visitor; \n NodeLabels nodeLabels(g, 0);\n solver.optimize(nodeLabels, &visitor);\n g.nodeLabelsToEdgeLabels(nodeLabels, outputEdgeLabels);\n \n for(auto e : g.edges()){\n NIFTY_TEST_OP(shouldSolution[e],==,outputEdgeLabels[e]);\n }\n }\n #endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * VHDL code generation for LPM devices.\n *\n * Copyright (C) 2008 Nick Gasson (nick@nickg.me.uk)\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; 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. See the\n * 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"vhdl_target.h\"\n\n#include <iostream>\n#include <cassert>\n\n\/*\n * Return the base of a part select.\n *\/\nstatic vhdl_expr *part_select_base(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_expr *off;\n ivl_nexus_t base = ivl_lpm_data(lpm, 1);\n if (base != NULL)\n off = nexus_to_var_ref(scope, base);\n else\n off = new vhdl_const_int(ivl_lpm_base(lpm));\n\n \/\/ Array indexes must be integers\n vhdl_type integer(VHDL_TYPE_INTEGER);\n return off->cast(&integer);\n}\n\nvhdl_var_ref *lpm_output(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_var_ref *out = nexus_to_var_ref(scope, ivl_lpm_q(lpm, 0));\n if (NULL == out) {\n vhdl_type *type =\n vhdl_type::type_for(ivl_lpm_width(lpm),\n ivl_lpm_signed(lpm) != 0);\n string name(\"LPM\");\n name += ivl_lpm_basename(lpm);\n name += \"_Out\";\n\n if (!scope->have_declared(name)) {\n scope->add_decl\n (new vhdl_signal_decl(name.c_str(), new vhdl_type(*type)));\n }\n \n out = new vhdl_var_ref(name.c_str(), type);\n }\n\n if (ivl_lpm_type(lpm) == IVL_LPM_PART_PV) {\n vhdl_expr *off = part_select_base(scope, lpm);\n assert(off);\n\n out->set_slice(off, ivl_lpm_width(lpm) - 1);\n }\n \n return out;\n}\n\n\nstatic vhdl_expr *concat_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_type *result_type =\n vhdl_type::type_for(ivl_lpm_width(lpm), ivl_lpm_signed(lpm) != 0);\n vhdl_binop_expr *expr =\n new vhdl_binop_expr(VHDL_BINOP_CONCAT, result_type);\n \n for (int i = ivl_lpm_selects(lpm) - 1; i >= 0; i--) {\n vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i));\n if (NULL == e)\n return NULL;\n\n expr->add_expr(e);\n }\n\n return expr;\n}\n\nstatic vhdl_expr *binop_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t op)\n{\n unsigned out_width = ivl_lpm_width(lpm);\n vhdl_type *result_type =\n vhdl_type::type_for(out_width, ivl_lpm_signed(lpm) != 0);\n vhdl_binop_expr *expr = new vhdl_binop_expr(op, result_type);\n \n for (int i = 0; i < 2; i++) {\n vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i));\n if (NULL == e)\n return NULL;\n\n expr->add_expr(e->cast(result_type));\n }\n \n if (op == VHDL_BINOP_MULT) {\n \/\/ Need to resize the output to the desired size,\n \/\/ as this does not happen automatically in VHDL\n \n vhdl_fcall *resize =\n new vhdl_fcall(\"Resize\", vhdl_type::nsigned(out_width));\n resize->add_expr(expr);\n resize->add_expr(new vhdl_const_int(out_width));\n \n return resize;\n }\n else\n return expr;\n}\n\nstatic vhdl_expr *rel_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t op)\n{\n vhdl_binop_expr *expr = new vhdl_binop_expr(op, vhdl_type::boolean());\n \n for (int i = 0; i < 2; i++) {\n vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i));\n if (NULL == e)\n return NULL;\n\n expr->add_expr(e);\n }\n\n return expr;\n}\n\nstatic vhdl_expr *part_select_vp_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_var_ref *selfrom = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n if (NULL == selfrom)\n return NULL;\n \n vhdl_expr *off = part_select_base(scope, lpm);;\n if (NULL == off)\n return NULL;\n\n selfrom->set_slice(off, ivl_lpm_width(lpm) - 1);\n return selfrom;\n}\n\n\nstatic vhdl_expr *part_select_pv_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{ \n return nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n}\n\nstatic vhdl_expr *ufunc_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_fcall *fcall = new vhdl_fcall(ivl_lpm_basename(lpm), NULL);\n\n for (unsigned i = 0; i < ivl_lpm_size(lpm); i++) {\n vhdl_var_ref *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i));\n if (NULL == ref)\n return NULL;\n\n fcall->add_expr(ref);\n }\n\n return fcall;\n}\n\nstatic vhdl_expr *reduction_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm,\n const char *rfunc, bool invert)\n{\n vhdl_fcall *fcall = new vhdl_fcall(rfunc, vhdl_type::std_logic());\n\n vhdl_var_ref *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n if (NULL == ref)\n return NULL;\n \n fcall->add_expr(ref);\n\n if (invert)\n return new vhdl_unaryop_expr\n (VHDL_UNARYOP_NOT, fcall, vhdl_type::std_logic());\n else\n return fcall;\n}\n\nstatic vhdl_expr *sign_extend_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_expr *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n if (ref)\n return ref->resize(ivl_lpm_width(lpm));\n else\n return NULL;\n}\n\nstatic vhdl_expr *array_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n ivl_signal_t array = ivl_lpm_array(lpm);\n if (!seen_signal_before(array))\n return NULL;\n \n const char *renamed = get_renamed_signal(array).c_str();\n\n vhdl_decl *adecl = scope->get_decl(renamed);\n assert(adecl);\n \n vhdl_type *atype = new vhdl_type(*adecl->get_type());\n\n vhdl_expr *select = nexus_to_var_ref(scope, ivl_lpm_select(lpm));\n if (NULL == select)\n return NULL;\n \n vhdl_var_ref *ref = new vhdl_var_ref(renamed, atype);\n vhdl_type integer(VHDL_TYPE_INTEGER);\n ref->set_slice(select->cast(&integer));\n \n return ref;\n}\n\nstatic vhdl_expr *shift_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm,\n vhdl_binop_t shift_op)\n{\n vhdl_expr *lhs = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n vhdl_expr *rhs = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 1));\n if (!lhs || !rhs)\n return NULL; \n \n \/\/ The RHS must be an integer\n vhdl_type integer(VHDL_TYPE_INTEGER);\n vhdl_expr *r_cast = rhs->cast(&integer);\n\n vhdl_type *rtype = new vhdl_type(*lhs->get_type());\n return new vhdl_binop_expr(lhs, shift_op, r_cast, rtype);\n}\n\nstatic vhdl_expr *lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n switch (ivl_lpm_type(lpm)) {\n case IVL_LPM_ADD:\n return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_ADD);\n case IVL_LPM_SUB:\n return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_SUB);\n case IVL_LPM_MULT:\n return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_MULT);\n case IVL_LPM_CONCAT:\n return concat_lpm_to_expr(scope, lpm);\n case IVL_LPM_CMP_GE:\n return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_GEQ);\n case IVL_LPM_CMP_EEQ:\n return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_EQ);\n case IVL_LPM_PART_VP:\n return part_select_vp_lpm_to_expr(scope, lpm);\n case IVL_LPM_PART_PV:\n return part_select_pv_lpm_to_expr(scope, lpm);\n case IVL_LPM_UFUNC:\n return ufunc_lpm_to_expr(scope, lpm);\n case IVL_LPM_RE_AND:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_AND\", false);\n case IVL_LPM_RE_NAND:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_AND\", true);\n case IVL_LPM_RE_NOR:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_OR\", true);\n case IVL_LPM_RE_OR:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_OR\", false);\n case IVL_LPM_RE_XOR:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_XOR\", false);\n case IVL_LPM_RE_XNOR:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_XNOR\", false);\n case IVL_LPM_SIGN_EXT:\n return sign_extend_lpm_to_expr(scope, lpm);\n case IVL_LPM_ARRAY:\n return array_lpm_to_expr(scope, lpm);\n case IVL_LPM_SHIFTL:\n return shift_lpm_to_expr(scope, lpm, VHDL_BINOP_SL);\n case IVL_LPM_SHIFTR:\n return shift_lpm_to_expr(scope, lpm, VHDL_BINOP_SR);\n default:\n error(\"Unsupported LPM type: %d\", ivl_lpm_type(lpm));\n return NULL;\n }\n}\n\nint draw_lpm(vhdl_arch *arch, ivl_lpm_t lpm)\n{\n vhdl_expr *f = lpm_to_expr(arch->get_scope(), lpm);\n if (NULL == f)\n return 0;\n \n vhdl_var_ref *out = lpm_output(arch->get_scope(), lpm);\n arch->add_stmt(new vhdl_cassign_stmt(out, f));\n \n return 0;\n}\n\n<commit_msg>Add IVL_LPM_CMP_EQ<commit_after>\/*\n * VHDL code generation for LPM devices.\n *\n * Copyright (C) 2008 Nick Gasson (nick@nickg.me.uk)\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; 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. See the\n * 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"vhdl_target.h\"\n\n#include <iostream>\n#include <cassert>\n\n\/*\n * Return the base of a part select.\n *\/\nstatic vhdl_expr *part_select_base(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_expr *off;\n ivl_nexus_t base = ivl_lpm_data(lpm, 1);\n if (base != NULL)\n off = nexus_to_var_ref(scope, base);\n else\n off = new vhdl_const_int(ivl_lpm_base(lpm));\n\n \/\/ Array indexes must be integers\n vhdl_type integer(VHDL_TYPE_INTEGER);\n return off->cast(&integer);\n}\n\nvhdl_var_ref *lpm_output(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_var_ref *out = nexus_to_var_ref(scope, ivl_lpm_q(lpm, 0));\n if (NULL == out) {\n vhdl_type *type =\n vhdl_type::type_for(ivl_lpm_width(lpm),\n ivl_lpm_signed(lpm) != 0);\n string name(\"LPM\");\n name += ivl_lpm_basename(lpm);\n name += \"_Out\";\n\n if (!scope->have_declared(name)) {\n scope->add_decl\n (new vhdl_signal_decl(name.c_str(), new vhdl_type(*type)));\n }\n \n out = new vhdl_var_ref(name.c_str(), type);\n }\n\n if (ivl_lpm_type(lpm) == IVL_LPM_PART_PV) {\n vhdl_expr *off = part_select_base(scope, lpm);\n assert(off);\n\n out->set_slice(off, ivl_lpm_width(lpm) - 1);\n }\n \n return out;\n}\n\n\nstatic vhdl_expr *concat_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_type *result_type =\n vhdl_type::type_for(ivl_lpm_width(lpm), ivl_lpm_signed(lpm) != 0);\n vhdl_binop_expr *expr =\n new vhdl_binop_expr(VHDL_BINOP_CONCAT, result_type);\n \n for (int i = ivl_lpm_selects(lpm) - 1; i >= 0; i--) {\n vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i));\n if (NULL == e)\n return NULL;\n\n expr->add_expr(e);\n }\n\n return expr;\n}\n\nstatic vhdl_expr *binop_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t op)\n{\n unsigned out_width = ivl_lpm_width(lpm);\n vhdl_type *result_type =\n vhdl_type::type_for(out_width, ivl_lpm_signed(lpm) != 0);\n vhdl_binop_expr *expr = new vhdl_binop_expr(op, result_type);\n \n for (int i = 0; i < 2; i++) {\n vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i));\n if (NULL == e)\n return NULL;\n\n expr->add_expr(e->cast(result_type));\n }\n \n if (op == VHDL_BINOP_MULT) {\n \/\/ Need to resize the output to the desired size,\n \/\/ as this does not happen automatically in VHDL\n \n vhdl_fcall *resize =\n new vhdl_fcall(\"Resize\", vhdl_type::nsigned(out_width));\n resize->add_expr(expr);\n resize->add_expr(new vhdl_const_int(out_width));\n \n return resize;\n }\n else\n return expr;\n}\n\nstatic vhdl_expr *rel_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t op)\n{\n vhdl_binop_expr *expr = new vhdl_binop_expr(op, vhdl_type::boolean());\n \n for (int i = 0; i < 2; i++) {\n vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i));\n if (NULL == e)\n return NULL;\n\n expr->add_expr(e);\n }\n\n return expr;\n}\n\nstatic vhdl_expr *part_select_vp_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_var_ref *selfrom = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n if (NULL == selfrom)\n return NULL;\n \n vhdl_expr *off = part_select_base(scope, lpm);;\n if (NULL == off)\n return NULL;\n\n selfrom->set_slice(off, ivl_lpm_width(lpm) - 1);\n return selfrom;\n}\n\n\nstatic vhdl_expr *part_select_pv_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{ \n return nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n}\n\nstatic vhdl_expr *ufunc_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_fcall *fcall = new vhdl_fcall(ivl_lpm_basename(lpm), NULL);\n\n for (unsigned i = 0; i < ivl_lpm_size(lpm); i++) {\n vhdl_var_ref *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i));\n if (NULL == ref)\n return NULL;\n\n fcall->add_expr(ref);\n }\n\n return fcall;\n}\n\nstatic vhdl_expr *reduction_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm,\n const char *rfunc, bool invert)\n{\n vhdl_fcall *fcall = new vhdl_fcall(rfunc, vhdl_type::std_logic());\n\n vhdl_var_ref *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n if (NULL == ref)\n return NULL;\n \n fcall->add_expr(ref);\n\n if (invert)\n return new vhdl_unaryop_expr\n (VHDL_UNARYOP_NOT, fcall, vhdl_type::std_logic());\n else\n return fcall;\n}\n\nstatic vhdl_expr *sign_extend_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n vhdl_expr *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n if (ref)\n return ref->resize(ivl_lpm_width(lpm));\n else\n return NULL;\n}\n\nstatic vhdl_expr *array_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n ivl_signal_t array = ivl_lpm_array(lpm);\n if (!seen_signal_before(array))\n return NULL;\n \n const char *renamed = get_renamed_signal(array).c_str();\n\n vhdl_decl *adecl = scope->get_decl(renamed);\n assert(adecl);\n \n vhdl_type *atype = new vhdl_type(*adecl->get_type());\n\n vhdl_expr *select = nexus_to_var_ref(scope, ivl_lpm_select(lpm));\n if (NULL == select)\n return NULL;\n \n vhdl_var_ref *ref = new vhdl_var_ref(renamed, atype);\n vhdl_type integer(VHDL_TYPE_INTEGER);\n ref->set_slice(select->cast(&integer));\n \n return ref;\n}\n\nstatic vhdl_expr *shift_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm,\n vhdl_binop_t shift_op)\n{\n vhdl_expr *lhs = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0));\n vhdl_expr *rhs = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 1));\n if (!lhs || !rhs)\n return NULL; \n \n \/\/ The RHS must be an integer\n vhdl_type integer(VHDL_TYPE_INTEGER);\n vhdl_expr *r_cast = rhs->cast(&integer);\n\n vhdl_type *rtype = new vhdl_type(*lhs->get_type());\n return new vhdl_binop_expr(lhs, shift_op, r_cast, rtype);\n}\n\nstatic vhdl_expr *lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm)\n{\n switch (ivl_lpm_type(lpm)) {\n case IVL_LPM_ADD:\n return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_ADD);\n case IVL_LPM_SUB:\n return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_SUB);\n case IVL_LPM_MULT:\n return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_MULT);\n case IVL_LPM_CONCAT:\n return concat_lpm_to_expr(scope, lpm);\n case IVL_LPM_CMP_GE:\n return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_GEQ);\n case IVL_LPM_CMP_EQ:\n case IVL_LPM_CMP_EEQ:\n return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_EQ);\n case IVL_LPM_PART_VP:\n return part_select_vp_lpm_to_expr(scope, lpm);\n case IVL_LPM_PART_PV:\n return part_select_pv_lpm_to_expr(scope, lpm);\n case IVL_LPM_UFUNC:\n return ufunc_lpm_to_expr(scope, lpm);\n case IVL_LPM_RE_AND:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_AND\", false);\n case IVL_LPM_RE_NAND:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_AND\", true);\n case IVL_LPM_RE_NOR:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_OR\", true);\n case IVL_LPM_RE_OR:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_OR\", false);\n case IVL_LPM_RE_XOR:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_XOR\", false);\n case IVL_LPM_RE_XNOR:\n return reduction_lpm_to_expr(scope, lpm, \"Reduce_XNOR\", false);\n case IVL_LPM_SIGN_EXT:\n return sign_extend_lpm_to_expr(scope, lpm);\n case IVL_LPM_ARRAY:\n return array_lpm_to_expr(scope, lpm);\n case IVL_LPM_SHIFTL:\n return shift_lpm_to_expr(scope, lpm, VHDL_BINOP_SL);\n case IVL_LPM_SHIFTR:\n return shift_lpm_to_expr(scope, lpm, VHDL_BINOP_SR);\n default:\n error(\"Unsupported LPM type: %d\", ivl_lpm_type(lpm));\n return NULL;\n }\n}\n\nint draw_lpm(vhdl_arch *arch, ivl_lpm_t lpm)\n{\n vhdl_expr *f = lpm_to_expr(arch->get_scope(), lpm);\n if (NULL == f)\n return 0;\n \n vhdl_var_ref *out = lpm_output(arch->get_scope(), lpm);\n arch->add_stmt(new vhdl_cassign_stmt(out, f));\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2003 MySQL AB\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; 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. 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, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#include <NDBT.hpp>\n#include <NDBT_Test.hpp>\n#include <HugoTransactions.hpp>\n#include <UtilTransactions.hpp>\n#include <random.h>\n#include <getarg.h>\n\nstruct Parameter {\n const char * name;\n unsigned value;\n unsigned min;\n unsigned max; \n};\n\n#define P_OPER 0\n#define P_RANGE 1\n#define P_ROWS 2\n#define P_LOOPS 3\n#define P_CREATE 4\n#define P_LOAD 5\n\n#define P_MAX 6\n\n\/**\n * operation\n * 0 - serial pk\n * 1 - batch pk\n * 2 - serial uniq \n * 3 - batch uniq\n * 4 - index eq\n * 5 - range scan\n * 6 - ordered range scan\n * 7 - interpreted scan\n *\/ \nstatic const char * g_ops[] = {\n \"serial pk\",\n \"batch pk\",\n \"serial uniq index access\",\n \"batch uniq index access\",\n \"index eq-bound\",\n \"index range\",\n \"index ordered\",\n \"interpreted scan\"\n};\n\n#define P_OP_TYPES 8\nstatic Uint64 g_times[P_OP_TYPES];\n\nstatic \nParameter \ng_paramters[] = {\n { \"operation\", 0, 0, 6 }, \/\/ 0 \n { \"range\", 1000, 1, ~0 },\/\/ 1 no of rows to read\n { \"size\", 1000000, 1, ~0 },\/\/ 2 rows in tables\n { \"iterations\", 3, 1, ~0 },\/\/ 3\n { \"create_drop\", 0, 0, 1 }, \/\/ 4\n { \"data\", 0, 0, 1 } \/\/ 5\n};\n\nstatic Ndb* g_ndb = 0;\nstatic const NdbDictionary::Table * g_tab;\nstatic const NdbDictionary::Index * g_i_unique;\nstatic const NdbDictionary::Index * g_i_ordered;\nstatic char g_table[256];\nstatic char g_unique[256];\nstatic char g_ordered[256];\nstatic char g_buffer[2*1024*1024];\n\nint create_table();\nint load_table();\nint run_read();\nint clear_table();\nint drop_table();\nvoid print_result();\n\nint\nmain(int argc, const char** argv){\n int verbose = 1;\n int optind = 0;\n \n struct getargs args[1+P_MAX] = {\n { \"verbose\", 'v', arg_flag, &verbose, \"Print verbose status\", \"verbose\" }\n };\n const int num_args = 1 + P_MAX;\n for(int i = 0; i<P_MAX; i++){\n args[i+1].long_name = g_paramters[i].name;\n args[i+1].short_name = * g_paramters[i].name;\n args[i+1].type = arg_integer;\n args[i+1].value = &g_paramters[i].value;\n BaseString tmp;\n tmp.assfmt(\"min: %d max: %d\", g_paramters[i].min, g_paramters[i].max);\n args[i+1].help = strdup(tmp.c_str());\n args[i+1].arg_help = 0;\n }\n \n if(getarg(args, num_args, argc, argv, &optind)) {\n arg_printusage(args, num_args, argv[0], \"tabname1 tabname2 ...\");\n return NDBT_WRONGARGS;\n }\n \n myRandom48Init(NdbTick_CurrentMillisecond());\n \n g_ndb = new Ndb(\"TEST_DB\");\n if(g_ndb->init() != 0){\n g_err << \"init() failed\" << endl;\n goto error;\n }\n if(g_ndb->waitUntilReady() != 0){\n g_err << \"Wait until ready failed\" << endl;\n goto error;\n }\n for(int i = optind; i<argc; i++){\n const char * T = argv[i];\n g_info << \"Testing \" << T << endl;\n snprintf(g_table, sizeof(g_table), T);\n snprintf(g_ordered, sizeof(g_ordered), \"IDX_O_%s\", T);\n snprintf(g_unique, sizeof(g_unique), \"IDX_U_%s\", T);\n if(create_table())\n goto error;\n if(load_table())\n goto error;\n for(int l = 0; l<g_paramters[P_LOOPS].value; l++){\n for(int j = 0; j<P_OP_TYPES; j++){\n\tg_paramters[P_OPER].value = j;\n\tif(run_read())\n\t goto error;\n }\n }\n print_result();\n }\n \n if(g_ndb) delete g_ndb;\n return NDBT_OK;\nerror:\n if(g_ndb) delete g_ndb;\n return NDBT_FAILED;\n}\n\nint\ncreate_table(){\n NdbDictionary::Dictionary* dict = g_ndb->getDictionary();\n assert(dict);\n if(g_paramters[P_CREATE].value){\n const NdbDictionary::Table * pTab = NDBT_Tables::getTable(g_table);\n assert(pTab);\n NdbDictionary::Table copy = * pTab;\n copy.setLogging(false);\n if(dict->createTable(copy) != 0){\n g_err << \"Failed to create table: \" << g_table << endl;\n return -1;\n }\n\n NdbDictionary::Index x(g_ordered);\n x.setTable(g_table);\n x.setType(NdbDictionary::Index::OrderedIndex);\n x.setLogging(false);\n for (unsigned k = 0; k < copy.getNoOfColumns(); k++){\n if(copy.getColumn(k)->getPrimaryKey()){\n\tx.addColumn(copy.getColumn(k)->getName());\n }\n }\n\n if(dict->createIndex(x) != 0){\n g_err << \"Failed to create index: \" << endl;\n return -1;\n }\n\n x.setName(g_unique);\n x.setType(NdbDictionary::Index::UniqueHashIndex);\n if(dict->createIndex(x) != 0){\n g_err << \"Failed to create index: \" << endl;\n return -1;\n }\n }\n g_tab = dict->getTable(g_table);\n g_i_unique = dict->getIndex(g_unique, g_table);\n g_i_ordered = dict->getIndex(g_ordered, g_table);\n assert(g_tab);\n assert(g_i_unique);\n assert(g_i_ordered);\n return 0;\n}\n\nint\ndrop_table(){\n if(!g_paramters[P_CREATE].value)\n return 0;\n if(g_ndb->getDictionary()->dropTable(g_tab->getName()) != 0){\n g_err << \"Failed to drop table: \" << g_tab->getName() << endl;\n return -1;\n }\n g_tab = 0;\n return 0;\n}\n\nint\nload_table(){\n if(!g_paramters[P_LOAD].value)\n return 0;\n \n int rows = g_paramters[P_ROWS].value;\n HugoTransactions hugoTrans(* g_tab);\n if (hugoTrans.loadTable(g_ndb, rows)){\n g_err.println(\"Failed to load %s with %d rows\", g_tab->getName(), rows);\n return -1;\n }\n return 0;\n}\n\nint\nclear_table(){\n if(!g_paramters[P_LOAD].value)\n return 0;\n int rows = g_paramters[P_ROWS].value;\n \n UtilTransactions utilTrans(* g_tab);\n if (utilTrans.clearTable(g_ndb, rows) != 0){\n g_err.println(\"Failed to clear table %s\", g_tab->getName());\n return -1;\n }\n return 0;\n}\n\ninline \nvoid err(NdbError e){\n ndbout << e << endl;\n}\n\nstatic \nvoid\ndo_work(){\n int sz = 10 * 1024;\n int pos= rand() % (sizeof(g_buffer) - sz);\n memset(g_buffer+pos, rand(), sz);\n}\n\nint\nrun_read(){\n int iter = g_paramters[P_LOOPS].value;\n NDB_TICKS start1, stop;\n int sum_time= 0;\n \n const Uint32 rows = g_paramters[P_ROWS].value;\n const Uint32 range = g_paramters[P_RANGE].value;\n \n start1 = NdbTick_CurrentMillisecond();\n NdbConnection * pTrans = g_ndb->startTransaction();\n if(!pTrans){\n g_err << \"Failed to start transaction\" << endl;\n err(g_ndb->getNdbError());\n return -1;\n }\n \n NdbOperation * pOp;\n NdbScanOperation * pSp;\n NdbIndexOperation * pUp;\n NdbIndexScanOperation * pIp;\n NdbResultSet * rs = (NdbResultSet*)~0;\n \n Uint32 start_row = rand() % (rows - range);\n Uint32 stop_row = start_row + range;\n\n \/**\n * 0 - serial pk\n * 1 - batch pk\n * 2 - serial uniq \n * 3 - batch uniq\n * 4 - index eq\n * 5 - range scan\n * 6 - interpreted scan\n *\/\n int check = 0;\n void* res = (void*)~0;\n const Uint32 pk = 0;\n Uint32 cnt = 0;\n for(; start_row < stop_row; start_row++){\n switch(g_paramters[P_OPER].value){\n case 0:\n pOp = pTrans->getNdbOperation(g_table);\n check = pOp->readTuple();\n check = pOp->equal(pk, start_row);\n break;\n case 1:\n for(; start_row<stop_row; start_row++){\n\tpOp = pTrans->getNdbOperation(g_table);\n\tcheck = pOp->readTuple();\n\tcheck = pOp->equal(pk, start_row);\n\tfor(int j = 0; j<g_tab->getNoOfColumns(); j++){\n\t res = pOp->getValue(j);\n\t assert(res);\n\t}\n }\n break;\n case 2:\n pOp = pTrans->getNdbIndexOperation(g_unique, g_table);\n check = pOp->readTuple();\n check = pOp->equal(pk, start_row);\n break;\n case 3:\n for(; start_row<stop_row; start_row++){\n\tpOp = pTrans->getNdbIndexOperation(g_unique, g_table);\n\tcheck = pOp->readTuple();\n\tcheck = pOp->equal(pk, start_row);\n\tfor(int j = 0; j<g_tab->getNoOfColumns(); j++){\n\t res = pOp->getValue(j);\n\t assert(res);\n\t}\n }\n break;\n case 4:\n pOp = pIp = pTrans->getNdbIndexScanOperation(g_ordered,g_table);\n rs = pIp->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundEQ, &start_row);\n break;\n case 5:\n pOp = pIp = pTrans->getNdbIndexScanOperation(g_ordered,g_table);\n rs = pIp->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundLE, &start_row);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundGT, &stop_row);\n start_row = stop_row;\n break;\n case 6:\n pOp = pIp = pTrans->getNdbIndexScanOperation(g_ordered,g_table);\n rs = pIp->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0, true);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundLE, &start_row);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundGT, &stop_row);\n start_row = stop_row;\n break;\n case 7:\n pOp = pSp = pTrans->getNdbScanOperation(g_table);\n rs = pSp->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0);\n NdbScanFilter filter(pOp) ; \n filter.begin(NdbScanFilter::AND);\n filter.ge(pk, start_row);\n filter.lt(pk, stop_row);\n filter.end();\n start_row = stop_row;\n break;\n }\n \n assert(res);\n if(check != 0){\n ndbout << pOp->getNdbError() << endl;\n ndbout << pTrans->getNdbError() << endl;\n }\n assert(check == 0);\n assert(rs);\n\n for(int j = 0; j<g_tab->getNoOfColumns(); j++){\n res = pOp->getValue(j);\n assert(res);\n }\n \n check = pTrans->execute(NoCommit);\n if(check != 0){\n ndbout << pTrans->getNdbError() << endl;\n }\n assert(check == 0);\n if(g_paramters[P_OPER].value >= 4){\n while((check = rs->nextResult(true)) == 0){\n\tdo_work();\n\tcnt++;\n }\n\t\n if(check == -1){\n\terr(pTrans->getNdbError());\n\treturn -1;\n }\n assert(check == 1);\n rs->close();\n } else {\n if(start_row != stop_row)\n\tdo_work();\n else\n\tfor(int j = 0; j<range; j++)\n\t do_work();\n }\n }\n assert(g_paramters[P_OPER].value < 4 || (cnt == range));\n \n pTrans->close();\n \n stop = NdbTick_CurrentMillisecond();\n g_times[g_paramters[P_OPER].value] += (stop - start1);\n return 0;\n}\n\nvoid\nprint_result(){\n for(int i = 0; i<P_OP_TYPES; i++){\n g_err.println(\"%s avg: %u us\/row\", g_ops[i],\n\t\t (1000*g_times[i])\/g_paramters[P_RANGE].value);\n }\n}\n<commit_msg>removed faked do_work<commit_after>\/* Copyright (C) 2003 MySQL AB\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; 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. 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, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#include <NDBT.hpp>\n#include <NDBT_Test.hpp>\n#include <HugoTransactions.hpp>\n#include <UtilTransactions.hpp>\n#include <random.h>\n#include <getarg.h>\n\nstruct Parameter {\n const char * name;\n unsigned value;\n unsigned min;\n unsigned max; \n};\n\n#define P_OPER 0\n#define P_RANGE 1\n#define P_ROWS 2\n#define P_LOOPS 3\n#define P_CREATE 4\n#define P_LOAD 5\n\n#define P_MAX 6\n\n\/**\n * operation\n * 0 - serial pk\n * 1 - batch pk\n * 2 - serial uniq \n * 3 - batch uniq\n * 4 - index eq\n * 5 - range scan\n * 6 - ordered range scan\n * 7 - interpreted scan\n *\/ \nstatic const char * g_ops[] = {\n \"serial pk\",\n \"batch pk\",\n \"serial uniq index access\",\n \"batch uniq index access\",\n \"index eq-bound\",\n \"index range\",\n \"index ordered\",\n \"interpreted scan\"\n};\n\n#define P_OP_TYPES 8\nstatic Uint64 g_times[P_OP_TYPES];\n\nstatic \nParameter \ng_paramters[] = {\n { \"operation\", 0, 0, 6 }, \/\/ 0 \n { \"range\", 1000, 1, ~0 },\/\/ 1 no of rows to read\n { \"size\", 1000000, 1, ~0 },\/\/ 2 rows in tables\n { \"iterations\", 3, 1, ~0 },\/\/ 3\n { \"create_drop\", 0, 0, 1 }, \/\/ 4\n { \"data\", 0, 0, 1 } \/\/ 5\n};\n\nstatic Ndb* g_ndb = 0;\nstatic const NdbDictionary::Table * g_tab;\nstatic const NdbDictionary::Index * g_i_unique;\nstatic const NdbDictionary::Index * g_i_ordered;\nstatic char g_table[256];\nstatic char g_unique[256];\nstatic char g_ordered[256];\nstatic char g_buffer[2*1024*1024];\n\nint create_table();\nint load_table();\nint run_read();\nint clear_table();\nint drop_table();\nvoid print_result();\n\nint\nmain(int argc, const char** argv){\n int verbose = 1;\n int optind = 0;\n \n struct getargs args[1+P_MAX] = {\n { \"verbose\", 'v', arg_flag, &verbose, \"Print verbose status\", \"verbose\" }\n };\n const int num_args = 1 + P_MAX;\n for(int i = 0; i<P_MAX; i++){\n args[i+1].long_name = g_paramters[i].name;\n args[i+1].short_name = * g_paramters[i].name;\n args[i+1].type = arg_integer;\n args[i+1].value = &g_paramters[i].value;\n BaseString tmp;\n tmp.assfmt(\"min: %d max: %d\", g_paramters[i].min, g_paramters[i].max);\n args[i+1].help = strdup(tmp.c_str());\n args[i+1].arg_help = 0;\n }\n \n if(getarg(args, num_args, argc, argv, &optind)) {\n arg_printusage(args, num_args, argv[0], \"tabname1 tabname2 ...\");\n return NDBT_WRONGARGS;\n }\n \n myRandom48Init(NdbTick_CurrentMillisecond());\n \n g_ndb = new Ndb(\"TEST_DB\");\n if(g_ndb->init() != 0){\n g_err << \"init() failed\" << endl;\n goto error;\n }\n if(g_ndb->waitUntilReady() != 0){\n g_err << \"Wait until ready failed\" << endl;\n goto error;\n }\n for(int i = optind; i<argc; i++){\n const char * T = argv[i];\n g_info << \"Testing \" << T << endl;\n snprintf(g_table, sizeof(g_table), T);\n snprintf(g_ordered, sizeof(g_ordered), \"IDX_O_%s\", T);\n snprintf(g_unique, sizeof(g_unique), \"IDX_U_%s\", T);\n if(create_table())\n goto error;\n if(load_table())\n goto error;\n for(int l = 0; l<g_paramters[P_LOOPS].value; l++){\n for(int j = 0; j<P_OP_TYPES; j++){\n\tg_paramters[P_OPER].value = j;\n\tif(run_read())\n\t goto error;\n }\n }\n print_result();\n }\n \n if(g_ndb) delete g_ndb;\n return NDBT_OK;\nerror:\n if(g_ndb) delete g_ndb;\n return NDBT_FAILED;\n}\n\nint\ncreate_table(){\n NdbDictionary::Dictionary* dict = g_ndb->getDictionary();\n assert(dict);\n if(g_paramters[P_CREATE].value){\n const NdbDictionary::Table * pTab = NDBT_Tables::getTable(g_table);\n assert(pTab);\n NdbDictionary::Table copy = * pTab;\n copy.setLogging(false);\n if(dict->createTable(copy) != 0){\n g_err << \"Failed to create table: \" << g_table << endl;\n return -1;\n }\n\n NdbDictionary::Index x(g_ordered);\n x.setTable(g_table);\n x.setType(NdbDictionary::Index::OrderedIndex);\n x.setLogging(false);\n for (unsigned k = 0; k < copy.getNoOfColumns(); k++){\n if(copy.getColumn(k)->getPrimaryKey()){\n\tx.addColumn(copy.getColumn(k)->getName());\n }\n }\n\n if(dict->createIndex(x) != 0){\n g_err << \"Failed to create index: \" << endl;\n return -1;\n }\n\n x.setName(g_unique);\n x.setType(NdbDictionary::Index::UniqueHashIndex);\n if(dict->createIndex(x) != 0){\n g_err << \"Failed to create index: \" << endl;\n return -1;\n }\n }\n g_tab = dict->getTable(g_table);\n g_i_unique = dict->getIndex(g_unique, g_table);\n g_i_ordered = dict->getIndex(g_ordered, g_table);\n assert(g_tab);\n assert(g_i_unique);\n assert(g_i_ordered);\n return 0;\n}\n\nint\ndrop_table(){\n if(!g_paramters[P_CREATE].value)\n return 0;\n if(g_ndb->getDictionary()->dropTable(g_tab->getName()) != 0){\n g_err << \"Failed to drop table: \" << g_tab->getName() << endl;\n return -1;\n }\n g_tab = 0;\n return 0;\n}\n\nint\nload_table(){\n if(!g_paramters[P_LOAD].value)\n return 0;\n \n int rows = g_paramters[P_ROWS].value;\n HugoTransactions hugoTrans(* g_tab);\n if (hugoTrans.loadTable(g_ndb, rows)){\n g_err.println(\"Failed to load %s with %d rows\", g_tab->getName(), rows);\n return -1;\n }\n return 0;\n}\n\nint\nclear_table(){\n if(!g_paramters[P_LOAD].value)\n return 0;\n int rows = g_paramters[P_ROWS].value;\n \n UtilTransactions utilTrans(* g_tab);\n if (utilTrans.clearTable(g_ndb, rows) != 0){\n g_err.println(\"Failed to clear table %s\", g_tab->getName());\n return -1;\n }\n return 0;\n}\n\ninline \nvoid err(NdbError e){\n ndbout << e << endl;\n}\n\nint\nrun_read(){\n int iter = g_paramters[P_LOOPS].value;\n NDB_TICKS start1, stop;\n int sum_time= 0;\n \n const Uint32 rows = g_paramters[P_ROWS].value;\n const Uint32 range = g_paramters[P_RANGE].value;\n \n start1 = NdbTick_CurrentMillisecond();\n NdbConnection * pTrans = g_ndb->startTransaction();\n if(!pTrans){\n g_err << \"Failed to start transaction\" << endl;\n err(g_ndb->getNdbError());\n return -1;\n }\n \n NdbOperation * pOp;\n NdbScanOperation * pSp;\n NdbIndexOperation * pUp;\n NdbIndexScanOperation * pIp;\n NdbResultSet * rs = (NdbResultSet*)~0;\n \n Uint32 start_row = rand() % (rows - range);\n Uint32 stop_row = start_row + range;\n\n \/**\n * 0 - serial pk\n * 1 - batch pk\n * 2 - serial uniq \n * 3 - batch uniq\n * 4 - index eq\n * 5 - range scan\n * 6 - interpreted scan\n *\/\n int check = 0;\n void* res = (void*)~0;\n const Uint32 pk = 0;\n Uint32 cnt = 0;\n for(; start_row < stop_row; start_row++){\n switch(g_paramters[P_OPER].value){\n case 0:\n pOp = pTrans->getNdbOperation(g_table);\n check = pOp->readTuple();\n check = pOp->equal(pk, start_row);\n break;\n case 1:\n for(; start_row<stop_row; start_row++){\n\tpOp = pTrans->getNdbOperation(g_table);\n\tcheck = pOp->readTuple();\n\tcheck = pOp->equal(pk, start_row);\n\tfor(int j = 0; j<g_tab->getNoOfColumns(); j++){\n\t res = pOp->getValue(j);\n\t assert(res);\n\t}\n }\n break;\n case 2:\n pOp = pTrans->getNdbIndexOperation(g_unique, g_table);\n check = pOp->readTuple();\n check = pOp->equal(pk, start_row);\n break;\n case 3:\n for(; start_row<stop_row; start_row++){\n\tpOp = pTrans->getNdbIndexOperation(g_unique, g_table);\n\tcheck = pOp->readTuple();\n\tcheck = pOp->equal(pk, start_row);\n\tfor(int j = 0; j<g_tab->getNoOfColumns(); j++){\n\t res = pOp->getValue(j);\n\t assert(res);\n\t}\n }\n break;\n case 4:\n pOp = pIp = pTrans->getNdbIndexScanOperation(g_ordered,g_table);\n rs = pIp->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundEQ, &start_row);\n break;\n case 5:\n pOp = pIp = pTrans->getNdbIndexScanOperation(g_ordered,g_table);\n rs = pIp->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundLE, &start_row);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundGT, &stop_row);\n start_row = stop_row;\n break;\n case 6:\n pOp = pIp = pTrans->getNdbIndexScanOperation(g_ordered,g_table);\n rs = pIp->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0, true);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundLE, &start_row);\n check = pIp->setBound(pk, NdbIndexScanOperation::BoundGT, &stop_row);\n start_row = stop_row;\n break;\n case 7:\n pOp = pSp = pTrans->getNdbScanOperation(g_table);\n rs = pSp->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0);\n NdbScanFilter filter(pOp) ; \n filter.begin(NdbScanFilter::AND);\n filter.ge(pk, start_row);\n filter.lt(pk, stop_row);\n filter.end();\n start_row = stop_row;\n break;\n }\n \n assert(res);\n if(check != 0){\n ndbout << pOp->getNdbError() << endl;\n ndbout << pTrans->getNdbError() << endl;\n }\n assert(check == 0);\n assert(rs);\n\n for(int j = 0; j<g_tab->getNoOfColumns(); j++){\n res = pOp->getValue(j);\n assert(res);\n }\n \n check = pTrans->execute(NoCommit);\n if(check != 0){\n ndbout << pTrans->getNdbError() << endl;\n }\n assert(check == 0);\n if(g_paramters[P_OPER].value >= 4){\n while((check = rs->nextResult(true)) == 0){\n\tcnt++;\n }\n\t\n if(check == -1){\n\terr(pTrans->getNdbError());\n\treturn -1;\n }\n assert(check == 1);\n rs->close();\n }\n }\n assert(g_paramters[P_OPER].value < 4 || (cnt == range));\n \n pTrans->close();\n \n stop = NdbTick_CurrentMillisecond();\n g_times[g_paramters[P_OPER].value] += (stop - start1);\n return 0;\n}\n\nvoid\nprint_result(){\n for(int i = 0; i<P_OP_TYPES; i++){\n g_err.println(\"%s avg: %u us\/row\", g_ops[i],\n\t\t (1000*g_times[i])\/g_paramters[P_RANGE].value);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This software is distributed under BSD 3-clause license (see LICENSE file).\n *\n * Authors: Giovanni De Toni\n *\n *\/\n\n#include <shogun\/io\/visitors\/ToStringVisitor.h>\n#include <shogun\/lib\/observers\/ObservedValueTemplated.h>\n#include <shogun\/lib\/observers\/ParameterObserverLogger.h>\n#include <shogun\/lib\/type_case.h>\n\nusing namespace shogun;\n\nCParameterObserverLogger::CParameterObserverLogger()\n{\n}\n\nCParameterObserverLogger::CParameterObserverLogger(\n std::vector<std::string>& parameters)\n : ParameterObserver(parameters)\n{\n}\n\nCParameterObserverLogger::~CParameterObserverLogger()\n{\n}\n\nvoid CParameterObserverLogger::on_error(std::exception_ptr ptr)\n{\n}\n\nvoid CParameterObserverLogger::on_complete()\n{\n}\n\nvoid CParameterObserverLogger::on_next_impl(const TimedObservedValue& value)\n{\n\n\tauto name = value.first->get<std::string>(\"name\");\n\tauto any_val = value.first->get_any();\n\n\tstd::stringstream stream;\n\tToStringVisitor visitor(&stream);\n\n\tif (any_val.visitable())\n\t{\n\t\tany_val.visit(&visitor);\n\t} else {\n\t\tstream << \"{function}\";\n\t}\n\n\tSG_PRINT(\n\t\t\t\"[%lu] Received a value called \\\"%s\\\" which contains: %s\\n\",\n\t\t\tconvert_to_millis(value.second), name.c_str(),\n\t\t\tstream.str().c_str());\n}\n<commit_msg>Replace ParameterObserverLogger message with a shorter version.<commit_after>\/*\n * This software is distributed under BSD 3-clause license (see LICENSE file).\n *\n * Authors: Giovanni De Toni\n *\n *\/\n\n#include <shogun\/io\/visitors\/ToStringVisitor.h>\n#include <shogun\/lib\/observers\/ObservedValueTemplated.h>\n#include <shogun\/lib\/observers\/ParameterObserverLogger.h>\n#include <shogun\/lib\/type_case.h>\n\nusing namespace shogun;\n\nCParameterObserverLogger::CParameterObserverLogger()\n{\n}\n\nCParameterObserverLogger::CParameterObserverLogger(\n std::vector<std::string>& parameters)\n : ParameterObserver(parameters)\n{\n}\n\nCParameterObserverLogger::~CParameterObserverLogger()\n{\n}\n\nvoid CParameterObserverLogger::on_error(std::exception_ptr ptr)\n{\n}\n\nvoid CParameterObserverLogger::on_complete()\n{\n}\n\nvoid CParameterObserverLogger::on_next_impl(const TimedObservedValue& value)\n{\n\n\tauto name = value.first->get<std::string>(\"name\");\n\tauto any_val = value.first->get_any();\n\n\tstd::stringstream stream;\n\tToStringVisitor visitor(&stream);\n\n\tif (any_val.visitable())\n\t{\n\t\tany_val.visit(&visitor);\n\t} else {\n\t\tstream << \"{function}\";\n\t}\n\n\tSG_PRINT(\n\t\t\t\"[%lu] \\\"%s\\\"=%s\\n\",\n\t\t\tconvert_to_millis(value.second), name.c_str(),\n\t\t\tstream.str().c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Flavio Castelli <flavio.castelli@gmail.com>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n*\/\n#include <stdio.h>\n\n#include \"eventlistenerqueue.h\"\n#include \"event.h\"\n#include \"strigi_thread.h\"\n#include \"strigilogging.h\"\n\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\n\nEventListenerQueue::EventListenerQueue(const char* name)\n : StrigiThread (name)\n{\n STRIGI_MUTEX_INIT (&m_mutex);\n m_toProcessOldCount = 0;\n m_processedOldCount = 0;\n m_waitingOldCount = 0;\n}\n\nEventListenerQueue::~EventListenerQueue()\n{\n clear();\n \n STRIGI_MUTEX_DESTROY (&m_mutex);\n}\n\nvoid EventListenerQueue::clearEvents( map<string, Event*>& events)\n{\n map < string, Event*>:: iterator iter;\n\n for (iter = events.begin(); iter != events.end(); iter++)\n {\n delete iter->second;\n }\n \n events.clear();\n}\n\nvoid EventListenerQueue::clear()\n{\n STRIGI_MUTEX_LOCK (&m_mutex);\n \n clearEvents (m_toProcess);\n clearEvents (m_processed);\n clearEvents (m_waiting);\n \n STRIGI_MUTEX_UNLOCK (&m_mutex);\n}\n\nvoid* EventListenerQueue::run(void*)\n{\n while (getState() != Stopping)\n {\n sleep (5);\n if (STRIGI_MUTEX_TRY_LOCK(&m_mutex) == 0)\n {\n \n if (m_waiting.size() > 0)\n {\n \/\/ search all wainting events that can be promoted to\n \/\/ \"toProcess\" status\n \n map<string,Event*>::iterator iter = m_waiting.begin();\n \n time_t now;\n time (&now);\n double delta = 60;\n \n while (iter != m_waiting.end())\n {\n if (checkElapsedTime(iter->second, now, delta))\n {\n m_toProcess.insert(make_pair(iter->first,iter->second));\n map<string,Event*>::iterator itRm = iter;\n iter++;\n m_waiting.erase(itRm);\n }\n else\n iter++;\n }\n }\n \n if (m_processed.size() > 0)\n purgeProcessedEvents();\n\n \/\/ print stats\n char buff [50];\n\n if (m_processed.size() != m_processedOldCount) {\n snprintf (buff, 50*sizeof(char), \"%lu\", (unsigned long)m_processed.size());\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.run\",\n string(buff) + \" events in \\\"processed\\\" queue\");\n m_processedOldCount = m_processed.size();\n }\n\n if (m_toProcess.size() != m_toProcessOldCount) {\n snprintf (buff, 50*sizeof(char), \"%lu\", (unsigned long)m_toProcess.size());\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.run\",\n string(buff) + \" events in \\\"to process\\\" queue\");\n m_toProcessOldCount = m_toProcess.size();\n }\n\n if (m_waiting.size() != m_waitingOldCount) {\n snprintf (buff, 50*sizeof(char), \"%lu\", (unsigned long)m_waiting.size());\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.run\",\n string(buff) + \" events in \\\"waiting\\\" queue\");\n m_waitingOldCount = m_waiting.size();\n }\n \n STRIGI_MUTEX_UNLOCK (&m_mutex);\n }\n\n if (getState() == Working)\n setState(Idling);\n }\n\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.run\",\n string(\"exit state: \") + getStringState());\n return 0;\n}\n\nbool EventListenerQueue::checkElapsedTime (Event* event,time_t now,double delta)\n{\n double diff = difftime (now, event->getTime());\n \n if (diff > delta)\n return true;\n \n return false;\n}\n\nvoid EventListenerQueue::purgeProcessedEvents()\n{\n unsigned int counter = 0;\n time_t now;\n time (&now);\n \n double delta = 120;\n \n map <string, Event*>::iterator iter = m_processed.begin();\n \n while (iter != m_processed.end())\n {\n if (checkElapsedTime(iter->second, now, delta))\n {\n map <string, Event*>::iterator itRm = iter;\n iter++;\n \n \/\/ we remove this event forever, free-up some memory\n delete itRm->second;\n itRm->second = NULL;\n m_processed.erase (itRm);\n counter++;\n }\n else\n iter++;\n }\n \n if (counter > 0)\n {\n char buff [50];\n snprintf (buff, 50*sizeof (char), \"%i\", counter);\n \n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.purgeProcessedEvents\",\n string(buff) + \" has been removed from processed \" +\n \"events queue\");\n }\n}\n\nEvent* EventListenerQueue::searchInProcessed(Event* event)\n{\n if (event == NULL)\n return NULL;\n\n map<string, Event*>::iterator iter;\n iter = m_processed.find(event->getPath());\n \n if (iter == m_processed.end())\n return NULL;\n else\n return iter->second;\n}\n\nEvent* EventListenerQueue::searchInWaiting (Event* event)\n{\n map<string, Event*>::iterator iter;\n iter = m_waiting.find(event->getPath());\n \n if (iter == m_waiting.end())\n return NULL;\n else\n return iter->second;\n}\n\nEvent* EventListenerQueue::searchInToProcess (Event* event)\n{\n map<string, Event*>::iterator iter;\n iter = m_toProcess.find(event->getPath());\n \n if (iter == m_toProcess.end())\n return NULL;\n else\n return iter->second;\n}\n\nvoid EventListenerQueue::putInWaiting (Event* event)\n{\n Event* waitingEvent = searchInWaiting(event);\n \n if (waitingEvent)\n {\n \/\/ there's already an event regarding this file\/dir\n \/\/ let's update the event type\n updateEventType(waitingEvent, event, m_waiting);\n \n \/\/ we don't need event anymore, free-up some memory\n delete event;\n event = NULL;\n \n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.addEvents\",\n \"updated waiting event status\");\n }\n else\n {\n \/\/ add the new event to the wainting queue\n m_waiting.insert (make_pair(event->getPath(), event));\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.putInWaiting\",\n \"new event added to waiting queue\");\n }\n}\n\nvoid EventListenerQueue::putInProcessed (Event* event)\n{\n Event* processedEvent = searchInProcessed(event);\n \n if (processedEvent)\n {\n \/\/ there's already an event regarding this file\/dir\n \/\/ let's update this one\n processedEvent->setType(event->getType());\n processedEvent->setTime(event->getTime());\n \n \/\/ we don't need event anymore, free-up some memory\n delete event;\n event = NULL;\n \n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.putInProcessed\",\n \"updated processed event\");\n }\n else\n {\n \/\/ add the new event to the wainting queue\n m_processed.insert (make_pair(event->getPath(), event));\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.putInProcessed\",\n \"new event added to processed queue\");\n }\n}\n\nvoid EventListenerQueue::updateEventType (Event* oldEvent, Event* newEvent,\n map <string, Event*>& eventMap)\n{\n \/\/ simplification table\n \/\/ old event | new event | result \n \/\/ C | C | IMPOSSIBLE\n \/\/ C | U | C\n \/\/ C | D | REMOVE\n \/\/ U | U | U\n \/\/ U | C | IMPOSSIBLE\n \/\/ U | D | D\n \/\/ D | D | IMPOSSIBLE\n \/\/ D | U | IMPOSSIBLE\n \/\/ D | C | U\n \n switch (oldEvent->getType())\n {\n case Event::CREATED:\n {\n switch (newEvent->getType())\n {\n case Event::CREATED:\n STRIGI_LOG_INFO(\"strigi.EventListenerQueue.updateEventType\",\n \"Maybe we've lost some filesystem event\");\n \n \/\/ put in update state, it's the safer solution because with\n \/\/ update event we make a delete and a create\n oldEvent->setType( Event::UPDATED);\n break;\n case Event::UPDATED:\n STRIGI_LOG_ERROR(\"strigi.EventListenerQueue.updateEventType\",\n \"CREATED --> UPDATED = leave CREATED\");\n \/\/ leave CREATED state\n break;\n case Event::DELETED:\n \/\/ remove the old event, the new one makes it useless\n eventMap.erase(oldEvent->getPath());\n \n \/\/ deallocate event\n delete oldEvent;\n oldEvent = NULL;\n break;\n }\n break;\n }\n case Event::UPDATED:\n {\n switch (newEvent->getType())\n {\n case Event::CREATED:\n STRIGI_LOG_INFO(\"strigi.EventListenerQueue.updateEventType\",\n \"Maybe we've lost some filesystem event\");\n \/\/ leave UPDATED state, it's the safer solution because with\n \/\/ update event we make a delete and a create\n break;\n case Event::UPDATED:\n \/\/ leave UPDATED state\n STRIGI_LOG_ERROR(\"strigi.EventListenerQueue.updateEventType\",\n \"UPDATED --> UPDATED = leave UPDATED\");\n\n break;\n case Event::DELETED:\n oldEvent->setType( Event::DELETED);\n STRIGI_LOG_ERROR(\"strigi.EventListenerQueue.updateEventType\",\n \"UPDATED --> DELETED = DELETED\");\n break;\n }\n break;\n }\n case Event::DELETED:\n {\n switch (newEvent->getType())\n {\n case Event::CREATED:\n oldEvent->setType( Event::UPDATED);\n STRIGI_LOG_ERROR(\"strigi.EventListenerQueue.updateEventType\",\n \"DELETED --> CREATED = UPDATED\");\n break;\n case Event::UPDATED:\n STRIGI_LOG_INFO(\"strigi.EventListenerQueue.updateEventType\",\n \"Maybe we've lost some filesystem event\");\n \n \/\/ put in update state, it's the safer solution because with\n \/\/ update event we make a delete and a create\n oldEvent->setType( Event::UPDATED);\n break;\n case Event::DELETED:\n STRIGI_LOG_INFO(\"strigi.EventListenerQueue.updateEventType\",\n \"Maybe we've lost some filesystem event\");\n \/\/leave DELETED state\n break;\n }\n break;\n }\n }\n}\n\nvoid EventListenerQueue::addEvents (vector<Event*> events)\n{\n vector<Event*>::iterator iter;\n\n STRIGI_MUTEX_LOCK (&m_mutex);\n \n Event* event = NULL;\n\n for (iter = events.begin(); iter != events.end(); iter++)\n {\n event = searchInProcessed(*iter);\n if (event)\n {\n \/\/ not to much time ago we have processed an event regarding\n \/\/ the same file\/dir, we've to wait a little before processing this\n \/\/ new event\n putInWaiting (*iter);\n continue;\n }\n \n event = searchInWaiting(*iter);\n if (event)\n {\n \/\/ there's another event in the wainting queue that is related with\n \/\/ this file\/dir. Let's update its status\n updateEventType (event, *iter, m_waiting);\n \n \/\/ we don't need this new event anymore, free-up some memory\n delete *iter;\n *iter = NULL;\n \n continue;\n }\n \n event = searchInToProcess(*iter);\n if (event)\n {\n updateEventType (event, *iter, m_toProcess);\n \n \/\/ we don't need this new event anymore, free-up some memory\n delete *iter;\n *iter = NULL;\n \n continue;\n }\n else\n {\n Event* e = *iter;\n string temp;\n\n \/\/ if we're arrived here this new event has to be processed\n m_toProcess.insert (make_pair (e->getPath(), e));\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.addEvents\",\n string(\"event regarding \") + e->getPath() +\n \" has been put in toProcess queue\");\n }\n }\n\n STRIGI_MUTEX_UNLOCK (&m_mutex);\n}\n\nunsigned int EventListenerQueue::size()\n{\n unsigned int i = 0;\n \n if (STRIGI_MUTEX_TRY_LOCK (&m_mutex) == 0)\n {\n i = m_toProcess.size();\n STRIGI_MUTEX_UNLOCK (&m_mutex);\n }\n \n return i;\n}\n\nvector <Event*> EventListenerQueue::getEvents()\n{\n vector <Event*> result;\n\n if (STRIGI_MUTEX_TRY_LOCK (&m_mutex))\n {\n for (map<string, Event*>::iterator iter = m_toProcess.begin();\n iter != m_toProcess.end(); iter++)\n {\n result.push_back (new Event (iter->second));\n \n \/\/ move event to processed queue\n putInProcessed (iter->second);\n }\n\n m_toProcess.clear();\n\n STRIGI_MUTEX_UNLOCK (&m_mutex);\n }\n\n return result;\n}\n<commit_msg>fix testing for success of the call to STRIGI_MUTEX_TRY_LOCK. It return 0 on success.<commit_after>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Flavio Castelli <flavio.castelli@gmail.com>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n*\/\n#include <stdio.h>\n\n#include \"eventlistenerqueue.h\"\n#include \"event.h\"\n#include \"strigi_thread.h\"\n#include \"strigilogging.h\"\n\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\n\nEventListenerQueue::EventListenerQueue(const char* name)\n : StrigiThread (name)\n{\n STRIGI_MUTEX_INIT (&m_mutex);\n m_toProcessOldCount = 0;\n m_processedOldCount = 0;\n m_waitingOldCount = 0;\n}\n\nEventListenerQueue::~EventListenerQueue()\n{\n clear();\n \n STRIGI_MUTEX_DESTROY (&m_mutex);\n}\n\nvoid EventListenerQueue::clearEvents( map<string, Event*>& events)\n{\n map < string, Event*>:: iterator iter;\n\n for (iter = events.begin(); iter != events.end(); iter++)\n {\n delete iter->second;\n }\n \n events.clear();\n}\n\nvoid EventListenerQueue::clear()\n{\n STRIGI_MUTEX_LOCK (&m_mutex);\n \n clearEvents (m_toProcess);\n clearEvents (m_processed);\n clearEvents (m_waiting);\n \n STRIGI_MUTEX_UNLOCK (&m_mutex);\n}\n\nvoid* EventListenerQueue::run(void*)\n{\n while (getState() != Stopping)\n {\n sleep (5);\n if (STRIGI_MUTEX_TRY_LOCK(&m_mutex) == 0)\n {\n \n if (m_waiting.size() > 0)\n {\n \/\/ search all wainting events that can be promoted to\n \/\/ \"toProcess\" status\n \n map<string,Event*>::iterator iter = m_waiting.begin();\n \n time_t now;\n time (&now);\n double delta = 60;\n \n while (iter != m_waiting.end())\n {\n if (checkElapsedTime(iter->second, now, delta))\n {\n m_toProcess.insert(make_pair(iter->first,iter->second));\n map<string,Event*>::iterator itRm = iter;\n iter++;\n m_waiting.erase(itRm);\n }\n else\n iter++;\n }\n }\n \n if (m_processed.size() > 0)\n purgeProcessedEvents();\n\n \/\/ print stats\n char buff [50];\n\n if (m_processed.size() != m_processedOldCount) {\n snprintf (buff, 50*sizeof(char), \"%lu\", (unsigned long)m_processed.size());\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.run\",\n string(buff) + \" events in \\\"processed\\\" queue\");\n m_processedOldCount = m_processed.size();\n }\n\n if (m_toProcess.size() != m_toProcessOldCount) {\n snprintf (buff, 50*sizeof(char), \"%lu\", (unsigned long)m_toProcess.size());\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.run\",\n string(buff) + \" events in \\\"to process\\\" queue\");\n m_toProcessOldCount = m_toProcess.size();\n }\n\n if (m_waiting.size() != m_waitingOldCount) {\n snprintf (buff, 50*sizeof(char), \"%lu\", (unsigned long)m_waiting.size());\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.run\",\n string(buff) + \" events in \\\"waiting\\\" queue\");\n m_waitingOldCount = m_waiting.size();\n }\n \n STRIGI_MUTEX_UNLOCK (&m_mutex);\n }\n\n if (getState() == Working)\n setState(Idling);\n }\n\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.run\",\n string(\"exit state: \") + getStringState());\n return 0;\n}\n\nbool EventListenerQueue::checkElapsedTime (Event* event,time_t now,double delta)\n{\n double diff = difftime (now, event->getTime());\n \n if (diff > delta)\n return true;\n \n return false;\n}\n\nvoid EventListenerQueue::purgeProcessedEvents()\n{\n unsigned int counter = 0;\n time_t now;\n time (&now);\n \n double delta = 120;\n \n map <string, Event*>::iterator iter = m_processed.begin();\n \n while (iter != m_processed.end())\n {\n if (checkElapsedTime(iter->second, now, delta))\n {\n map <string, Event*>::iterator itRm = iter;\n iter++;\n \n \/\/ we remove this event forever, free-up some memory\n delete itRm->second;\n itRm->second = NULL;\n m_processed.erase (itRm);\n counter++;\n }\n else\n iter++;\n }\n \n if (counter > 0)\n {\n char buff [50];\n snprintf (buff, 50*sizeof (char), \"%i\", counter);\n \n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.purgeProcessedEvents\",\n string(buff) + \" has been removed from processed \" +\n \"events queue\");\n }\n}\n\nEvent* EventListenerQueue::searchInProcessed(Event* event)\n{\n if (event == NULL)\n return NULL;\n\n map<string, Event*>::iterator iter;\n iter = m_processed.find(event->getPath());\n \n if (iter == m_processed.end())\n return NULL;\n else\n return iter->second;\n}\n\nEvent* EventListenerQueue::searchInWaiting (Event* event)\n{\n map<string, Event*>::iterator iter;\n iter = m_waiting.find(event->getPath());\n \n if (iter == m_waiting.end())\n return NULL;\n else\n return iter->second;\n}\n\nEvent* EventListenerQueue::searchInToProcess (Event* event)\n{\n map<string, Event*>::iterator iter;\n iter = m_toProcess.find(event->getPath());\n \n if (iter == m_toProcess.end())\n return NULL;\n else\n return iter->second;\n}\n\nvoid EventListenerQueue::putInWaiting (Event* event)\n{\n Event* waitingEvent = searchInWaiting(event);\n \n if (waitingEvent)\n {\n \/\/ there's already an event regarding this file\/dir\n \/\/ let's update the event type\n updateEventType(waitingEvent, event, m_waiting);\n \n \/\/ we don't need event anymore, free-up some memory\n delete event;\n event = NULL;\n \n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.addEvents\",\n \"updated waiting event status\");\n }\n else\n {\n \/\/ add the new event to the wainting queue\n m_waiting.insert (make_pair(event->getPath(), event));\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.putInWaiting\",\n \"new event added to waiting queue\");\n }\n}\n\nvoid EventListenerQueue::putInProcessed (Event* event)\n{\n Event* processedEvent = searchInProcessed(event);\n \n if (processedEvent)\n {\n \/\/ there's already an event regarding this file\/dir\n \/\/ let's update this one\n processedEvent->setType(event->getType());\n processedEvent->setTime(event->getTime());\n \n \/\/ we don't need event anymore, free-up some memory\n delete event;\n event = NULL;\n \n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.putInProcessed\",\n \"updated processed event\");\n }\n else\n {\n \/\/ add the new event to the wainting queue\n m_processed.insert (make_pair(event->getPath(), event));\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.putInProcessed\",\n \"new event added to processed queue\");\n }\n}\n\nvoid EventListenerQueue::updateEventType (Event* oldEvent, Event* newEvent,\n map <string, Event*>& eventMap)\n{\n \/\/ simplification table\n \/\/ old event | new event | result \n \/\/ C | C | IMPOSSIBLE\n \/\/ C | U | C\n \/\/ C | D | REMOVE\n \/\/ U | U | U\n \/\/ U | C | IMPOSSIBLE\n \/\/ U | D | D\n \/\/ D | D | IMPOSSIBLE\n \/\/ D | U | IMPOSSIBLE\n \/\/ D | C | U\n \n switch (oldEvent->getType())\n {\n case Event::CREATED:\n {\n switch (newEvent->getType())\n {\n case Event::CREATED:\n STRIGI_LOG_INFO(\"strigi.EventListenerQueue.updateEventType\",\n \"Maybe we've lost some filesystem event\");\n \n \/\/ put in update state, it's the safer solution because with\n \/\/ update event we make a delete and a create\n oldEvent->setType( Event::UPDATED);\n break;\n case Event::UPDATED:\n STRIGI_LOG_ERROR(\"strigi.EventListenerQueue.updateEventType\",\n \"CREATED --> UPDATED = leave CREATED\");\n \/\/ leave CREATED state\n break;\n case Event::DELETED:\n \/\/ remove the old event, the new one makes it useless\n eventMap.erase(oldEvent->getPath());\n \n \/\/ deallocate event\n delete oldEvent;\n oldEvent = NULL;\n break;\n }\n break;\n }\n case Event::UPDATED:\n {\n switch (newEvent->getType())\n {\n case Event::CREATED:\n STRIGI_LOG_INFO(\"strigi.EventListenerQueue.updateEventType\",\n \"Maybe we've lost some filesystem event\");\n \/\/ leave UPDATED state, it's the safer solution because with\n \/\/ update event we make a delete and a create\n break;\n case Event::UPDATED:\n \/\/ leave UPDATED state\n STRIGI_LOG_ERROR(\"strigi.EventListenerQueue.updateEventType\",\n \"UPDATED --> UPDATED = leave UPDATED\");\n\n break;\n case Event::DELETED:\n oldEvent->setType( Event::DELETED);\n STRIGI_LOG_ERROR(\"strigi.EventListenerQueue.updateEventType\",\n \"UPDATED --> DELETED = DELETED\");\n break;\n }\n break;\n }\n case Event::DELETED:\n {\n switch (newEvent->getType())\n {\n case Event::CREATED:\n oldEvent->setType( Event::UPDATED);\n STRIGI_LOG_ERROR(\"strigi.EventListenerQueue.updateEventType\",\n \"DELETED --> CREATED = UPDATED\");\n break;\n case Event::UPDATED:\n STRIGI_LOG_INFO(\"strigi.EventListenerQueue.updateEventType\",\n \"Maybe we've lost some filesystem event\");\n \n \/\/ put in update state, it's the safer solution because with\n \/\/ update event we make a delete and a create\n oldEvent->setType( Event::UPDATED);\n break;\n case Event::DELETED:\n STRIGI_LOG_INFO(\"strigi.EventListenerQueue.updateEventType\",\n \"Maybe we've lost some filesystem event\");\n \/\/leave DELETED state\n break;\n }\n break;\n }\n }\n}\n\nvoid EventListenerQueue::addEvents (vector<Event*> events)\n{\n vector<Event*>::iterator iter;\n\n STRIGI_MUTEX_LOCK (&m_mutex);\n \n Event* event = NULL;\n\n for (iter = events.begin(); iter != events.end(); iter++)\n {\n event = searchInProcessed(*iter);\n if (event)\n {\n \/\/ not to much time ago we have processed an event regarding\n \/\/ the same file\/dir, we've to wait a little before processing this\n \/\/ new event\n putInWaiting (*iter);\n continue;\n }\n \n event = searchInWaiting(*iter);\n if (event)\n {\n \/\/ there's another event in the wainting queue that is related with\n \/\/ this file\/dir. Let's update its status\n updateEventType (event, *iter, m_waiting);\n \n \/\/ we don't need this new event anymore, free-up some memory\n delete *iter;\n *iter = NULL;\n \n continue;\n }\n \n event = searchInToProcess(*iter);\n if (event)\n {\n updateEventType (event, *iter, m_toProcess);\n \n \/\/ we don't need this new event anymore, free-up some memory\n delete *iter;\n *iter = NULL;\n \n continue;\n }\n else\n {\n Event* e = *iter;\n string temp;\n\n \/\/ if we're arrived here this new event has to be processed\n m_toProcess.insert (make_pair (e->getPath(), e));\n STRIGI_LOG_DEBUG (\"strigi.EventListenerQueue.addEvents\",\n string(\"event regarding \") + e->getPath() +\n \" has been put in toProcess queue\");\n }\n }\n\n STRIGI_MUTEX_UNLOCK (&m_mutex);\n}\n\nunsigned int EventListenerQueue::size()\n{\n unsigned int i = 0;\n \n if (STRIGI_MUTEX_TRY_LOCK (&m_mutex) == 0)\n {\n i = m_toProcess.size();\n STRIGI_MUTEX_UNLOCK (&m_mutex);\n }\n \n return i;\n}\n\nvector <Event*> EventListenerQueue::getEvents()\n{\n vector <Event*> result;\n\n if (STRIGI_MUTEX_TRY_LOCK (&m_mutex) == 0)\n {\n for (map<string, Event*>::iterator iter = m_toProcess.begin();\n iter != m_toProcess.end(); iter++)\n {\n result.push_back (new Event (iter->second));\n \n \/\/ move event to processed queue\n putInProcessed (iter->second);\n }\n\n m_toProcess.clear();\n\n STRIGI_MUTEX_UNLOCK (&m_mutex);\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ruby.h>\n#include <set>\n#include <algorithm>\n\n#include <boost\/tuple\/tuple.hpp>\n\nusing namespace boost;\nusing namespace std;\n\nstatic VALUE cValueSet;\nstatic ID id_new;\nstatic ID id_to_value_set;\n\ntypedef std::set<VALUE> ValueSet;\nstatic ValueSet& get_wrapped_set(VALUE self)\n{\n void* object = 0;\n Data_Get_Struct(self, void, object);\n return *reinterpret_cast<ValueSet*>(object);\n}\nstatic void value_set_mark(ValueSet const* set)\n{ std::for_each(set->begin(), set->end(), rb_gc_mark); }\nstatic void value_set_free(ValueSet const* set)\n{ delete set; }\nstatic VALUE value_set_alloc(VALUE klass)\n{\n ValueSet* cxx_set = new ValueSet;\n return Data_Wrap_Struct(klass, value_set_mark, value_set_free, cxx_set);\n}\nstatic VALUE value_set_each(VALUE self)\n{\n ValueSet& set = get_wrapped_set(self);\n for_each(set.begin(), set.end(), rb_yield);\n return self;\n}\nstatic VALUE value_set_include_p(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n return self.find(vother) == self.end() ? Qfalse : Qtrue;\n}\nstatic VALUE value_set_to_value_set(VALUE self) { return self; }\nstatic VALUE value_set_include_all_p(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n return std::includes(self.begin(), self.end(), other.begin(), other.end()) ? Qtrue : Qfalse;\n}\n\nstatic VALUE value_set_union(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(vother);\n \n VALUE vresult = rb_funcall(cValueSet, id_new, 0);\n ValueSet& result = get_wrapped_set(vresult);\n std::set_union(self.begin(), self.end(), other.begin(), other.end(), \n\t std::inserter(result, result.end()));\n return vresult;\n}\n\n\/* call-seq:\n * set.merge(other)\t\t=> set\n *\n * Merges the elements of +other+ into +self+. If +other+ is a ValueSet, the operation is O(N + M)\n *\/\nstatic VALUE value_set_merge(VALUE vself, VALUE vother)\n{\n ValueSet& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n \n self.insert(other.begin(), other.end());\n return vself;\n}\n\n\/* call-seq:\n * set.intersection(other)\t=> intersection_set\n * set & other\t\t=> intersection_set\n *\n * Computes the intersection of +set+ and +other+\n *\/\nstatic VALUE value_set_intersection(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n \n VALUE vresult = rb_funcall(cValueSet, id_new, 0);\n ValueSet& result = get_wrapped_set(vresult);\n std::set_intersection(self.begin(), self.end(), other.begin(), other.end(), \n\t std::inserter(result, result.end()));\n return vresult;\n}\nstatic VALUE value_set_difference(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n \n VALUE vresult = rb_funcall(cValueSet, id_new, 0);\n ValueSet& result = get_wrapped_set(vresult);\n std::set_difference(self.begin(), self.end(), other.begin(), other.end(), \n\t std::inserter(result, result.end()));\n return vresult;\n}\n\nstatic VALUE value_set_insert(VALUE vself, VALUE v)\n{\n ValueSet& self = get_wrapped_set(vself);\n bool exists;\n tie(tuples::ignore, exists) = self.insert(v);\n return exists ? Qtrue : Qfalse;\n}\nstatic VALUE value_set_delete(VALUE vself, VALUE v)\n{\n ValueSet& self = get_wrapped_set(vself);\n size_t count = self.erase(v);\n return count > 0 ? Qtrue : Qfalse;\n}\n\n\/* call-seq:\n * set == other\t\t=> true or false\n *\n * Equality\n *\/\nstatic VALUE value_set_equal(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n return (self == other) ? Qtrue : Qfalse;\n}\n\n\n\n\n\n\n\n\nstatic VALUE enumerable_to_value_set_i(VALUE i, VALUE* memo)\n{\n ValueSet& result = *reinterpret_cast<ValueSet*>(memo);\n result.insert(i);\n return Qnil;\n}\nstatic VALUE enumerable_to_value_set(VALUE self)\n{\n VALUE vresult = rb_funcall(cValueSet, id_new, 0);\n ValueSet& result = get_wrapped_set(vresult);\n\n rb_iterate(rb_each, self, RUBY_METHOD_FUNC(enumerable_to_value_set_i), reinterpret_cast<VALUE>(&result));\n return vresult;\n}\n\nstatic VALUE enumerable_each_uniq_i(VALUE i, VALUE* memo)\n{ \n set<VALUE>& seen = *reinterpret_cast< set<VALUE>* >(memo); \n if (seen.find(i) == seen.end())\n {\n\tseen.insert(i);\n\treturn rb_yield(i);\n }\n else\n\treturn Qnil;\n\n}\n\nstatic VALUE enumerable_each_uniq(VALUE self)\n{\n set<VALUE> seen;\n rb_iterate(rb_each, self, \n\t RUBY_METHOD_FUNC(enumerable_each_uniq_i), (VALUE)&seen);\n return self;\n}\n\n\nextern \"C\" void Init_faster()\n{\n rb_define_method(rb_mEnumerable, \"each_uniq\", RUBY_METHOD_FUNC(enumerable_each_uniq), 0);\n rb_define_method(rb_mEnumerable, \"to_value_set\", RUBY_METHOD_FUNC(enumerable_to_value_set), 0);\n\n cValueSet = rb_define_class(\"ValueSet\", rb_cObject);\n id_new = rb_intern(\"new\");\n id_to_value_set = rb_intern(\"to_value_set\");\n rb_define_alloc_func(cValueSet, value_set_alloc);\n rb_define_method(cValueSet, \"each\", RUBY_METHOD_FUNC(value_set_each), 0);\n rb_define_method(cValueSet, \"include?\", RUBY_METHOD_FUNC(value_set_include_p), 1);\n rb_define_method(cValueSet, \"include_all?\", RUBY_METHOD_FUNC(value_set_include_all_p), 1);\n rb_define_method(cValueSet, \"union\", RUBY_METHOD_FUNC(value_set_union), 1);\n rb_define_method(cValueSet, \"intersection\", RUBY_METHOD_FUNC(value_set_intersection), 1);\n rb_define_method(cValueSet, \"difference\", RUBY_METHOD_FUNC(value_set_difference), 1);\n rb_define_method(cValueSet, \"insert\", RUBY_METHOD_FUNC(value_set_insert), 1);\n rb_define_method(cValueSet, \"merge\", RUBY_METHOD_FUNC(value_set_merge), 1);\n rb_define_method(cValueSet, \"delete\", RUBY_METHOD_FUNC(value_set_delete), 1);\n rb_define_method(cValueSet, \"==\", RUBY_METHOD_FUNC(value_set_equal), 1);\n rb_define_method(cValueSet, \"to_value_set\", RUBY_METHOD_FUNC(value_set_to_value_set), 0);\n}\n\n<commit_msg>[value_set] documentation<commit_after>#include <ruby.h>\n#include <set>\n#include <algorithm>\n\n#include <boost\/tuple\/tuple.hpp>\n\nusing namespace boost;\nusing namespace std;\n\nstatic VALUE cValueSet;\nstatic ID id_new;\nstatic ID id_to_value_set;\n\ntypedef std::set<VALUE> ValueSet;\nstatic ValueSet& get_wrapped_set(VALUE self)\n{\n void* object = 0;\n Data_Get_Struct(self, void, object);\n return *reinterpret_cast<ValueSet*>(object);\n}\nstatic void value_set_mark(ValueSet const* set)\n{ std::for_each(set->begin(), set->end(), rb_gc_mark); }\nstatic void value_set_free(ValueSet const* set)\n{ delete set; }\nstatic VALUE value_set_alloc(VALUE klass)\n{\n ValueSet* cxx_set = new ValueSet;\n return Data_Wrap_Struct(klass, value_set_mark, value_set_free, cxx_set);\n}\n\/* call-seq:\n * set.each { |obj| ... }\t => set\n *\/\nstatic VALUE value_set_each(VALUE self)\n{\n ValueSet& set = get_wrapped_set(self);\n for_each(set.begin(), set.end(), rb_yield);\n return self;\n}\n\/* call-seq:\n * set.include?(value)\t => true or false\n *\n * Checks if +value+ is in +set+\n *\/\nstatic VALUE value_set_include_p(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n return self.find(vother) == self.end() ? Qfalse : Qtrue;\n}\n\n\/* call-seq:\n * set.to_value_set\t\t => set\n *\/\nstatic VALUE value_set_to_value_set(VALUE self) { return self; }\n\n\/* call-seq:\n * set.include_all?(other)\t\t=> true or false\n *\n * Checks if all elements of +other+ are in +set+\n *\/\nstatic VALUE value_set_include_all_p(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n return std::includes(self.begin(), self.end(), other.begin(), other.end()) ? Qtrue : Qfalse;\n}\n\n\/* call-seq:\n * set.union(other)\t\t=> union_set\n * set | other\t\t\t=> union_set\n *\n * Computes the union of +set+ and +other+\n *\/\nstatic VALUE value_set_union(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(vother);\n \n VALUE vresult = rb_funcall(cValueSet, id_new, 0);\n ValueSet& result = get_wrapped_set(vresult);\n std::set_union(self.begin(), self.end(), other.begin(), other.end(), \n\t std::inserter(result, result.end()));\n return vresult;\n}\n\n\/* call-seq:\n * set.merge(other)\t\t=> set\n *\n * Merges the elements of +other+ into +self+. If +other+ is a ValueSet, the operation is O(N + M)\n *\/\nstatic VALUE value_set_merge(VALUE vself, VALUE vother)\n{\n ValueSet& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n \n self.insert(other.begin(), other.end());\n return vself;\n}\n\n\/* call-seq:\n * set.intersection(other)\t=> intersection_set\n * set & other\t\t=> intersection_set\n *\n * Computes the intersection of +set+ and +other+\n *\/\nstatic VALUE value_set_intersection(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n \n VALUE vresult = rb_funcall(cValueSet, id_new, 0);\n ValueSet& result = get_wrapped_set(vresult);\n std::set_intersection(self.begin(), self.end(), other.begin(), other.end(), \n\t std::inserter(result, result.end()));\n return vresult;\n}\n\/* call-seq:\n * set.difference(other)\t=> intersection_set\n * set - other\t\t=> intersection_set\n *\n * Computes the set of all elements of +set+ not in +other+\n *\/\nstatic VALUE value_set_difference(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n \n VALUE vresult = rb_funcall(cValueSet, id_new, 0);\n ValueSet& result = get_wrapped_set(vresult);\n std::set_difference(self.begin(), self.end(), other.begin(), other.end(), \n\t std::inserter(result, result.end()));\n return vresult;\n}\n\n\/* call-seq:\n * set.insert(value)\t\t=> true or false\n * \n * Inserts +value+ into +set+. Returns true if the value did not exist\n * in the set yet (it has actually been inserted), and false otherwise.\n *\/\nstatic VALUE value_set_insert(VALUE vself, VALUE v)\n{\n ValueSet& self = get_wrapped_set(vself);\n bool exists;\n tie(tuples::ignore, exists) = self.insert(v);\n return exists ? Qtrue : Qfalse;\n}\n\/* call-seq:\n * set.delete(value)\t\t=> true or false\n * \n * Removes +value+ from +set+. Returns true if the value did exist\n * in the set yet (it has actually been removed), and false otherwise.\n *\/\nstatic VALUE value_set_delete(VALUE vself, VALUE v)\n{\n ValueSet& self = get_wrapped_set(vself);\n size_t count = self.erase(v);\n return count > 0 ? Qtrue : Qfalse;\n}\n\n\/* call-seq:\n * set == other\t\t=> true or false\n *\n * Equality\n *\/\nstatic VALUE value_set_equal(VALUE vself, VALUE vother)\n{\n ValueSet const& self = get_wrapped_set(vself);\n ValueSet const& other = get_wrapped_set(rb_funcall(vother, id_to_value_set, 0));\n return (self == other) ? Qtrue : Qfalse;\n}\n\n\n\n\n\n\n\n\nstatic VALUE enumerable_to_value_set_i(VALUE i, VALUE* memo)\n{\n ValueSet& result = *reinterpret_cast<ValueSet*>(memo);\n result.insert(i);\n return Qnil;\n}\n\/* call-seq:\n * enum.to_value_set\t\t=> value_set\n *\n * Builds a value_set object from this enumerable\n *\/\nstatic VALUE enumerable_to_value_set(VALUE self)\n{\n VALUE vresult = rb_funcall(cValueSet, id_new, 0);\n ValueSet& result = get_wrapped_set(vresult);\n\n rb_iterate(rb_each, self, RUBY_METHOD_FUNC(enumerable_to_value_set_i), reinterpret_cast<VALUE>(&result));\n return vresult;\n}\n\nstatic VALUE enumerable_each_uniq_i(VALUE i, VALUE* memo)\n{ \n set<VALUE>& seen = *reinterpret_cast< set<VALUE>* >(memo); \n if (seen.find(i) == seen.end())\n {\n\tseen.insert(i);\n\treturn rb_yield(i);\n }\n else\n\treturn Qnil;\n\n}\n\n\/* call-seq:\n * enum.each_uniq { |obj| ... }\n *\n * Yields all unique values found in +enum+\n *\/\nstatic VALUE enumerable_each_uniq(VALUE self)\n{\n set<VALUE> seen;\n rb_iterate(rb_each, self, \n\t RUBY_METHOD_FUNC(enumerable_each_uniq_i), (VALUE)&seen);\n return self;\n}\n\n\nextern \"C\" void Init_faster()\n{\n rb_define_method(rb_mEnumerable, \"each_uniq\", RUBY_METHOD_FUNC(enumerable_each_uniq), 0);\n rb_define_method(rb_mEnumerable, \"to_value_set\", RUBY_METHOD_FUNC(enumerable_to_value_set), 0);\n\n cValueSet = rb_define_class(\"ValueSet\", rb_cObject);\n id_new = rb_intern(\"new\");\n id_to_value_set = rb_intern(\"to_value_set\");\n rb_define_alloc_func(cValueSet, value_set_alloc);\n rb_define_method(cValueSet, \"each\", RUBY_METHOD_FUNC(value_set_each), 0);\n rb_define_method(cValueSet, \"include?\", RUBY_METHOD_FUNC(value_set_include_p), 1);\n rb_define_method(cValueSet, \"include_all?\", RUBY_METHOD_FUNC(value_set_include_all_p), 1);\n rb_define_method(cValueSet, \"union\", RUBY_METHOD_FUNC(value_set_union), 1);\n rb_define_method(cValueSet, \"intersection\", RUBY_METHOD_FUNC(value_set_intersection), 1);\n rb_define_method(cValueSet, \"difference\", RUBY_METHOD_FUNC(value_set_difference), 1);\n rb_define_method(cValueSet, \"insert\", RUBY_METHOD_FUNC(value_set_insert), 1);\n rb_define_method(cValueSet, \"merge\", RUBY_METHOD_FUNC(value_set_merge), 1);\n rb_define_method(cValueSet, \"delete\", RUBY_METHOD_FUNC(value_set_delete), 1);\n rb_define_method(cValueSet, \"==\", RUBY_METHOD_FUNC(value_set_equal), 1);\n rb_define_method(cValueSet, \"to_value_set\", RUBY_METHOD_FUNC(value_set_to_value_set), 0);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\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 <limits>\nnamespace iox\n{\nnamespace cxx\n{\ntemplate <typename Source>\ninline typename std::enable_if<!std::is_convertible<Source, std::string>::value, std::string>::type\nconvert::toString(const Source& t)\n{\n std::stringstream ss;\n ss << t;\n return ss.str();\n}\n\ntemplate <typename Source>\ninline typename std::enable_if<std::is_convertible<Source, std::string>::value, std::string>::type\nconvert::toString(const Source& t)\n{\n return t;\n}\n\ntemplate <typename Destination>\ninline typename std::enable_if<std::is_convertible<const char*, Destination>::value, bool>::type\nfromString(const char* v, Destination& dest)\n{\n dest = Destination(v);\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<std::string>(const char* v, std::string& dest)\n{\n dest = std::string(v);\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<char>(const char* v, char& dest)\n{\n if (strlen(v) != 1u)\n {\n std::cerr << v << \" is not a char\" << std::endl;\n return false;\n }\n dest = v[0];\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<string<100>>(const char* v, string<100>& dest)\n{\n dest = string<100>(TruncateToCapacity, v);\n return true;\n}\n\ninline bool convert::stringIsNumber(const char* v, const NumberType type)\n{\n if (v[0] == '\\0')\n return false;\n\n bool hasDot = false;\n\n for (uint32_t i = 0u; v[i] != '\\0'; ++i)\n {\n if (v[i] >= 48 && v[i] <= 57) \/\/ 48 == ascii 0, 57 == ascii 9\n {\n continue;\n }\n else if (type != NumberType::UNSIGNED_INTEGER && i == 0u\n && (v[i] == 43 || v[i] == 45)) \/\/ 43 == ascii +, 45 == ascii -\n {\n continue;\n }\n else if (type == NumberType::FLOAT && !hasDot && v[i] == 46) \/\/ 46 == ascii .\n {\n hasDot = true;\n }\n else\n {\n return false;\n }\n }\n\n return true;\n}\n\ninline bool convert::stringIsNumberWithErrorMessage(const char* v, const NumberType type)\n{\n if (!stringIsNumber(v, type))\n {\n std::cerr << v << \" is not \";\n switch (type)\n {\n case NumberType::FLOAT:\n {\n std::cerr << \"a float\";\n break;\n }\n case NumberType::INTEGER:\n {\n std::cerr << \"a signed integer\";\n break;\n }\n case NumberType::UNSIGNED_INTEGER:\n {\n std::cerr << \"an unsigned integer\";\n break;\n }\n }\n std::cerr << std::endl;\n return false;\n }\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<float>(const char* v, float& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))\n {\n return false;\n }\n\n auto call = makeSmartC(strtof, ReturnMode::PRE_DEFINED_ERROR_CODE, {HUGE_VALF, -HUGE_VALF}, {}, v, nullptr);\n\n if (call.hasErrors())\n {\n return false;\n }\n\n dest = call.getReturnValue();\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<double>(const char* v, double& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))\n {\n return false;\n }\n\n auto call = makeSmartC(strtod, ReturnMode::PRE_DEFINED_ERROR_CODE, {HUGE_VAL, -HUGE_VAL}, {}, v, nullptr);\n\n if (call.hasErrors())\n {\n return false;\n }\n\n dest = call.getReturnValue();\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<long double>(const char* v, long double& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))\n {\n return false;\n }\n\n auto call = makeSmartC(strtold, ReturnMode::PRE_DEFINED_ERROR_CODE, {HUGE_VALL, -HUGE_VALL}, {}, v, nullptr);\n\n if (call.hasErrors())\n {\n return false;\n }\n\n dest = call.getReturnValue();\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<uint64_t>(const char* v, uint64_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoull, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULLONG_MAX}, {}, v, nullptr, 10u);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<uint64_t>::max())\n {\n std::cerr << call.getReturnValue() << \" too large, uint64_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<uint64_t>(call.getReturnValue());\n return true;\n}\n\n\/\/\/ introduced for mac os since unsigned long is not uint64_t despite it has the same size\n\/\/\/ who knows why ¯\\_(ツ)_\/¯\ntemplate <>\ninline bool convert::fromString<unsigned long>(const char* v, unsigned long& dest)\n{\n uint64_t temp{0};\n bool retVal = fromString(v, temp);\n dest = temp;\n return retVal;\n}\n\ntemplate <>\ninline bool convert::fromString<uint32_t>(const char* v, uint32_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoull, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULLONG_MAX}, {}, v, nullptr, 10u);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<uint32_t>::max())\n {\n std::cerr << call.getReturnValue() << \" too large, uint32_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<uint32_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<uint16_t>(const char* v, uint16_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoul, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULONG_MAX}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<uint16_t>::max())\n {\n std::cerr << call.getReturnValue() << \" too large, uint16_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<uint16_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<uint8_t>(const char* v, uint8_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoul, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULONG_MAX}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<uint8_t>::max())\n {\n std::cerr << call.getReturnValue() << \" too large, uint8_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<uint8_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<int64_t>(const char* v, int64_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoll, ReturnMode::PRE_DEFINED_ERROR_CODE, {LLONG_MAX, LLONG_MIN}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<int64_t>::max()\n || call.getReturnValue() < std::numeric_limits<int64_t>::min())\n {\n std::cerr << call.getReturnValue() << \" is out of range, int64_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<int64_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<int32_t>(const char* v, int32_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoll, ReturnMode::PRE_DEFINED_ERROR_CODE, {LLONG_MAX, LLONG_MIN}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<int32_t>::max()\n || call.getReturnValue() < std::numeric_limits<int32_t>::min())\n {\n std::cerr << call.getReturnValue() << \" is out of range, int32_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<int32_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<int16_t>(const char* v, int16_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtol, ReturnMode::PRE_DEFINED_ERROR_CODE, {LONG_MAX, LONG_MIN}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<int16_t>::max()\n || call.getReturnValue() < std::numeric_limits<int16_t>::min())\n {\n std::cerr << call.getReturnValue() << \" is out of range, int16_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<int16_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<int8_t>(const char* v, int8_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtol, ReturnMode::PRE_DEFINED_ERROR_CODE, {LONG_MAX, LONG_MIN}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<int8_t>::max()\n || call.getReturnValue() < std::numeric_limits<int8_t>::min())\n {\n std::cerr << call.getReturnValue() << \" is out of range, int8_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<int8_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<bool>(const char* v, bool& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoul, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULONG_MAX}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n dest = static_cast<bool>(call.getReturnValue());\n return true;\n}\n\n} \/\/ namespace cxx\n} \/\/ namespace iox\n<commit_msg>iox-#32 overload for fromString conversion to unsigned long only for mac os<commit_after>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\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 <limits>\nnamespace iox\n{\nnamespace cxx\n{\ntemplate <typename Source>\ninline typename std::enable_if<!std::is_convertible<Source, std::string>::value, std::string>::type\nconvert::toString(const Source& t)\n{\n std::stringstream ss;\n ss << t;\n return ss.str();\n}\n\ntemplate <typename Source>\ninline typename std::enable_if<std::is_convertible<Source, std::string>::value, std::string>::type\nconvert::toString(const Source& t)\n{\n return t;\n}\n\ntemplate <typename Destination>\ninline typename std::enable_if<std::is_convertible<const char*, Destination>::value, bool>::type\nfromString(const char* v, Destination& dest)\n{\n dest = Destination(v);\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<std::string>(const char* v, std::string& dest)\n{\n dest = std::string(v);\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<char>(const char* v, char& dest)\n{\n if (strlen(v) != 1u)\n {\n std::cerr << v << \" is not a char\" << std::endl;\n return false;\n }\n dest = v[0];\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<string<100>>(const char* v, string<100>& dest)\n{\n dest = string<100>(TruncateToCapacity, v);\n return true;\n}\n\ninline bool convert::stringIsNumber(const char* v, const NumberType type)\n{\n if (v[0] == '\\0')\n return false;\n\n bool hasDot = false;\n\n for (uint32_t i = 0u; v[i] != '\\0'; ++i)\n {\n if (v[i] >= 48 && v[i] <= 57) \/\/ 48 == ascii 0, 57 == ascii 9\n {\n continue;\n }\n else if (type != NumberType::UNSIGNED_INTEGER && i == 0u\n && (v[i] == 43 || v[i] == 45)) \/\/ 43 == ascii +, 45 == ascii -\n {\n continue;\n }\n else if (type == NumberType::FLOAT && !hasDot && v[i] == 46) \/\/ 46 == ascii .\n {\n hasDot = true;\n }\n else\n {\n return false;\n }\n }\n\n return true;\n}\n\ninline bool convert::stringIsNumberWithErrorMessage(const char* v, const NumberType type)\n{\n if (!stringIsNumber(v, type))\n {\n std::cerr << v << \" is not \";\n switch (type)\n {\n case NumberType::FLOAT:\n {\n std::cerr << \"a float\";\n break;\n }\n case NumberType::INTEGER:\n {\n std::cerr << \"a signed integer\";\n break;\n }\n case NumberType::UNSIGNED_INTEGER:\n {\n std::cerr << \"an unsigned integer\";\n break;\n }\n }\n std::cerr << std::endl;\n return false;\n }\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<float>(const char* v, float& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))\n {\n return false;\n }\n\n auto call = makeSmartC(strtof, ReturnMode::PRE_DEFINED_ERROR_CODE, {HUGE_VALF, -HUGE_VALF}, {}, v, nullptr);\n\n if (call.hasErrors())\n {\n return false;\n }\n\n dest = call.getReturnValue();\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<double>(const char* v, double& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))\n {\n return false;\n }\n\n auto call = makeSmartC(strtod, ReturnMode::PRE_DEFINED_ERROR_CODE, {HUGE_VAL, -HUGE_VAL}, {}, v, nullptr);\n\n if (call.hasErrors())\n {\n return false;\n }\n\n dest = call.getReturnValue();\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<long double>(const char* v, long double& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::FLOAT))\n {\n return false;\n }\n\n auto call = makeSmartC(strtold, ReturnMode::PRE_DEFINED_ERROR_CODE, {HUGE_VALL, -HUGE_VALL}, {}, v, nullptr);\n\n if (call.hasErrors())\n {\n return false;\n }\n\n dest = call.getReturnValue();\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<uint64_t>(const char* v, uint64_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoull, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULLONG_MAX}, {}, v, nullptr, 10u);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<uint64_t>::max())\n {\n std::cerr << call.getReturnValue() << \" too large, uint64_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<uint64_t>(call.getReturnValue());\n return true;\n}\n\n#ifdef __APPLE__\n\/\/\/ introduced for mac os since unsigned long is not uint64_t despite it has the same size\n\/\/\/ who knows why ¯\\_(ツ)_\/¯\ntemplate <>\ninline bool convert::fromString<unsigned long>(const char* v, unsigned long& dest)\n{\n uint64_t temp{0};\n bool retVal = fromString(v, temp);\n dest = temp;\n return retVal;\n}\n#endif\n\ntemplate <>\ninline bool convert::fromString<uint32_t>(const char* v, uint32_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoull, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULLONG_MAX}, {}, v, nullptr, 10u);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<uint32_t>::max())\n {\n std::cerr << call.getReturnValue() << \" too large, uint32_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<uint32_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<uint16_t>(const char* v, uint16_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoul, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULONG_MAX}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<uint16_t>::max())\n {\n std::cerr << call.getReturnValue() << \" too large, uint16_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<uint16_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<uint8_t>(const char* v, uint8_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoul, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULONG_MAX}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<uint8_t>::max())\n {\n std::cerr << call.getReturnValue() << \" too large, uint8_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<uint8_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<int64_t>(const char* v, int64_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoll, ReturnMode::PRE_DEFINED_ERROR_CODE, {LLONG_MAX, LLONG_MIN}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<int64_t>::max()\n || call.getReturnValue() < std::numeric_limits<int64_t>::min())\n {\n std::cerr << call.getReturnValue() << \" is out of range, int64_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<int64_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<int32_t>(const char* v, int32_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoll, ReturnMode::PRE_DEFINED_ERROR_CODE, {LLONG_MAX, LLONG_MIN}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<int32_t>::max()\n || call.getReturnValue() < std::numeric_limits<int32_t>::min())\n {\n std::cerr << call.getReturnValue() << \" is out of range, int32_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<int32_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<int16_t>(const char* v, int16_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtol, ReturnMode::PRE_DEFINED_ERROR_CODE, {LONG_MAX, LONG_MIN}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<int16_t>::max()\n || call.getReturnValue() < std::numeric_limits<int16_t>::min())\n {\n std::cerr << call.getReturnValue() << \" is out of range, int16_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<int16_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<int8_t>(const char* v, int8_t& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtol, ReturnMode::PRE_DEFINED_ERROR_CODE, {LONG_MAX, LONG_MIN}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n if (call.getReturnValue() > std::numeric_limits<int8_t>::max()\n || call.getReturnValue() < std::numeric_limits<int8_t>::min())\n {\n std::cerr << call.getReturnValue() << \" is out of range, int8_t overflow\" << std::endl;\n return false;\n }\n\n dest = static_cast<int8_t>(call.getReturnValue());\n return true;\n}\n\ntemplate <>\ninline bool convert::fromString<bool>(const char* v, bool& dest)\n{\n if (!stringIsNumberWithErrorMessage(v, NumberType::UNSIGNED_INTEGER))\n {\n return false;\n }\n\n auto call = makeSmartC(strtoul, ReturnMode::PRE_DEFINED_ERROR_CODE, {ULONG_MAX}, {}, v, nullptr, 10);\n if (call.hasErrors())\n {\n return false;\n }\n\n dest = static_cast<bool>(call.getReturnValue());\n return true;\n}\n\n} \/\/ namespace cxx\n} \/\/ namespace iox\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PresentationViewShell.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:12:15 $\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 SD_PRESENTATION_VIEW_SHELL_HXX\n#define SD_PRESENTATION_VIEW_SHELL_HXX\n\n#ifndef SD_DRAW_VIEW_SHELL\n#include \"DrawViewShell.hxx\"\n#endif\n\nnamespace sd {\n\n\/** This view shell is responsible for showing the presentation of an\n Impress document.\n*\/\nclass PresentationViewShell\n : public DrawViewShell\n{\npublic:\n TYPEINFO();\n\n SFX_DECL_VIEWFACTORY(PresViewShell);\n SFX_DECL_INTERFACE( SD_IF_SDPRESVIEWSHELL );\n\n PresentationViewShell (\n SfxViewFrame* pFrame,\n ViewShellBase& rViewShellBase,\n ::Window* pParentWindow,\n FrameView* pFrameView = NULL);\n static void CreateFullScreenShow(ViewShell* pOriginShell, SfxRequest& rReq );\n\n \/** This method is used by a simple class that passes some\n arguments from the creator of the new view shell to the new view\n shell object by waiting for its asynchronous creation.\n @param pFrameView\n The frame view that is typically used by the creating object and\n that shall be shared by the created view shell.\n @param rRequest\n A request from which some arguments are extracted by the\n FuSlideShow object. It usually comes from an Execute() method\n that initiated the creation of the new presentation view shell.\n @param nPageNumber\n The number of the page at which to start the show.\n *\/\n void FinishInitialization (\n FrameView* pFrameView,\n SfxRequest& rRequest,\n USHORT nPageNumber);\n\nprotected:\n virtual SvxRuler* CreateHRuler(::sd::Window* pWin, BOOL bIsFirst);\n virtual SvxRuler* CreateVRuler(::sd::Window* pWin);\n\nprivate:\n Rectangle maOldVisArea;\n sal_Bool mbShowStarted;\n\n PresentationViewShell (\n SfxViewFrame* pFrame,\n ::Window* pParentWindow,\n const DrawViewShell& rShell);\n virtual ~PresentationViewShell (void);\n\n virtual void Activate (BOOL bIsMDIActivate);\n virtual void Paint (const Rectangle& rRect, ::sd::Window* pWin);\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.314); FILE MERGED 2006\/11\/22 12:42:01 cl 1.5.314.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PresentationViewShell.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 17:36:56 $\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 SD_PRESENTATION_VIEW_SHELL_HXX\n#define SD_PRESENTATION_VIEW_SHELL_HXX\n\n#ifndef SD_DRAW_VIEW_SHELL\n#include \"DrawViewShell.hxx\"\n#endif\n\nnamespace sd {\n\n\/** This view shell is responsible for showing the presentation of an\n Impress document.\n*\/\nclass PresentationViewShell\n : public DrawViewShell\n{\npublic:\n TYPEINFO();\n\n SFX_DECL_VIEWFACTORY(PresViewShell);\n SFX_DECL_INTERFACE( SD_IF_SDPRESVIEWSHELL )\n\n PresentationViewShell (\n SfxViewFrame* pFrame,\n ViewShellBase& rViewShellBase,\n ::Window* pParentWindow,\n FrameView* pFrameView = NULL);\n static void CreateFullScreenShow(ViewShell* pOriginShell, SfxRequest& rReq );\n\n \/** This method is used by a simple class that passes some\n arguments from the creator of the new view shell to the new view\n shell object by waiting for its asynchronous creation.\n @param pFrameView\n The frame view that is typically used by the creating object and\n that shall be shared by the created view shell.\n @param rRequest\n A request from which some arguments are extracted by the\n FuSlideShow object. It usually comes from an Execute() method\n that initiated the creation of the new presentation view shell.\n @param nPageNumber\n The number of the page at which to start the show.\n *\/\n void FinishInitialization (\n FrameView* pFrameView,\n SfxRequest& rRequest,\n USHORT nPageNumber);\n\nprotected:\n virtual SvxRuler* CreateHRuler(::sd::Window* pWin, BOOL bIsFirst);\n virtual SvxRuler* CreateVRuler(::sd::Window* pWin);\n\nprivate:\n Rectangle maOldVisArea;\n sal_Bool mbShowStarted;\n\n PresentationViewShell (\n SfxViewFrame* pFrame,\n ::Window* pParentWindow,\n const DrawViewShell& rShell);\n virtual ~PresentationViewShell (void);\n\n virtual void Activate (BOOL bIsMDIActivate);\n virtual void Paint (const Rectangle& rRect, ::sd::Window* pWin);\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: GraphicViewShellBase.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-01-20 12:37:41 $\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#include \"GraphicViewShellBase.hxx\"\n\n#ifndef SD_RESID_HXX\n#include \"sdresid.hxx\"\n#endif\n#ifndef SD_GRAPHIC_DOC_SHELL_HXX\n#include \"GraphicDocShell.hxx\"\n#endif\n#include \"strings.hrc\"\n\nnamespace sd {\n\nclass DrawDocShell;\n\nTYPEINIT1(GraphicViewShellBase, ViewShellBase);\n\nSFX_IMPL_VIEWFACTORY(GraphicViewShellBase, SdResId(STR_DEFAULTVIEW))\n{\n SFX_VIEW_REGISTRATION(GraphicDocShell);\n}\n\n\n\n\nGraphicViewShellBase::GraphicViewShellBase (\n SfxViewFrame* pFrame,\n SfxViewShell* pOldShell)\n : ViewShellBase (pFrame, pOldShell, ViewShell::ST_DRAW)\n{\n}\n\n\n\n\nGraphicViewShellBase::~GraphicViewShellBase (void)\n{\n}\n\n} \/\/ end of namespace sd\n\n<commit_msg>INTEGRATION: CWS impress2 (1.2.26); FILE MERGED 2004\/06\/29 07:09:03 af 1.2.26.1: #i22705# Added LateInit() method where the ViewTabBar is deleted.<commit_after>\/*************************************************************************\n *\n * $RCSfile: GraphicViewShellBase.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 14:50:17 $\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#include \"GraphicViewShellBase.hxx\"\n\n#include \"ViewTabBar.hxx\"\n#ifndef SD_RESID_HXX\n#include \"sdresid.hxx\"\n#endif\n#ifndef SD_GRAPHIC_DOC_SHELL_HXX\n#include \"GraphicDocShell.hxx\"\n#endif\n#include \"strings.hrc\"\n\nnamespace sd {\n\nclass DrawDocShell;\n\nTYPEINIT1(GraphicViewShellBase, ViewShellBase);\n\n\/\/ We have to expand the SFX_IMPL_VIEWFACTORY macro to call LateInit() after a\n\/\/ new GraphicViewShellBase object has been constructed.\n\n\/*\nSFX_IMPL_VIEWFACTORY(GraphicViewShellBase, SdResId(STR_DEFAULTVIEW))\n{\n SFX_VIEW_REGISTRATION(GraphicDocShell);\n}\n*\/\nSfxViewFactory* GraphicViewShellBase::pFactory;\nSfxViewShell* __EXPORT GraphicViewShellBase::CreateInstance (\n SfxViewFrame *pFrame, SfxViewShell *pOldView)\n{\n GraphicViewShellBase* pBase = new GraphicViewShellBase(pFrame, pOldView);\n pBase->LateInit();\n return pBase;\n}\nvoid GraphicViewShellBase::RegisterFactory( USHORT nPrio )\n{\n pFactory = new SfxViewFactory(\n &CreateInstance,&InitFactory,nPrio,SdResId(STR_DEFAULTVIEW));\n InitFactory();\n}\nvoid GraphicViewShellBase::InitFactory()\n{\n SFX_VIEW_REGISTRATION(GraphicDocShell);\n}\n\n\n\n\n\n\n\n\nGraphicViewShellBase::GraphicViewShellBase (\n SfxViewFrame* pFrame,\n SfxViewShell* pOldShell)\n : ViewShellBase (pFrame, pOldShell, ViewShell::ST_DRAW)\n{\n}\n\n\n\n\nvoid GraphicViewShellBase::LateInit (void)\n{\n ViewShellBase::LateInit();\n \/\/ Turn the ViewTabBar off again. It is not needed for Draw.\n mpViewTabBar.reset();\n}\n\n\n\n\nGraphicViewShellBase::~GraphicViewShellBase (void)\n{\n}\n\n} \/\/ end of namespace sd\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2011 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\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 *\/\n\n#include <cstdlib>\n#include <iostream>\n\n#include <QCoreApplication>\n#include <QFile>\n#include <QProcess>\n#include <QRegExp>\n#include <QTextStream>\n\n#include \"QXmppGlobal.h\"\n\nstatic void setField(QString &code, const QString &name, const QString &value)\n{\n code.replace(\n QRegExp(QString(\"(%1\\\\s*=)[^\\\\r\\\\n]*\").arg(name)),\n QString(\"\\\\1 %1\").arg(value));\n}\n\nstatic void usage() {\n QTextStream output(stderr);\n output << \"Usage:\" << endl;\n output << \" doxyfilter Generate documentation\" << endl;\n output << \" doxyfilter -g Generate Doxyfile\" << endl;\n output << \" doxyfilter <sourcefile> Filter the given file's code\" << endl;\n}\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n\n if (argc == 1)\n return QProcess::execute(\"doxygen\");\n else if (argc != 2) {\n usage();\n return 1;\n }\n\n if (!strcmp(argv[1], \"-g\")) {\n \/\/ generate default Doxyfile\n QProcess process;\n process.start(\"doxygen\", QStringList() << \"-g\" << \"-\");\n if (!process.waitForFinished()) {\n qWarning(\"Could not run doxygen\");\n return 1;\n }\n QString code = QString::fromUtf8(process.readAll());\n\n \/\/ adjust Doxyfile\n setField(code, \"ALPHABETICAL_INDEX\", \"NO\");\n setField(code, \"EXCLUDE_PATTERNS\", \"*\/moc_*\");\n setField(code, \"FULL_PATH_NAMES\", \"NO\");\n setField(code, \"HIDE_UNDOC_CLASSES\", \"YES\");\n setField(code, \"GENERATE_LATEX\", \"NO\");\n setField(code, \"HTML_TIMESTAMP\", \"NO\");\n setField(code, \"INPUT\", \"..\/src\");\n setField(code, \"INPUT_FILTER\", QString::fromLocal8Bit(argv[0]));\n setField(code, \"PROJECT_NAME\", \"QXmpp\");\n setField(code, \"PROJECT_NUMBER\", QString(\"%1.%2.%3\").arg(\n QString::number((QXMPP_VERSION >> 16) & 0xff),\n QString::number((QXMPP_VERSION >> 8) & 0xff),\n QString::number(QXMPP_VERSION & 0xff)));\n\n \/\/ write doxyfile\n QFile output(\"Doxyfile\");\n if (!output.open(QIODevice::WriteOnly)) {\n qWarning(\"Could not write to %s\", qPrintable(output.fileName()));\n return 1;\n }\n output.write(code.toUtf8());\n output.close();\n\n } else if (!strcmp(argv[1], \"-h\")) {\n usage();\n return 0;\n } else {\n \/\/ read source code\n QFile source(QString::fromLocal8Bit(argv[1]));\n if (!source.open(QIODevice::ReadOnly)) {\n qWarning(\"Could not open %s\", qPrintable(source.fileName()));\n return 1;\n }\n QString code = QString::fromUtf8(source.readAll());\n source.close();\n\n \/\/ add links for XEPs\n code.replace(QRegExp(\"(XEP-([0-9]{4}))\"), \"<a href=\\\"http:\/\/xmpp.org\/extensions\/xep-\\\\2.html\\\">\\\\1<\/a>\");\n\n QTextStream output(stdout);\n output << code;\n }\n\n return 0;\n}\n\n<commit_msg>change format<commit_after>\/*\n * Copyright (C) 2008-2011 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\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 *\/\n\n#include <cstdlib>\n#include <iostream>\n\n#include <QCoreApplication>\n#include <QFile>\n#include <QProcess>\n#include <QRegExp>\n#include <QTextStream>\n\n#include \"QXmppGlobal.h\"\n\nstatic void setField(QString &code, const QString &name, const QString &value)\n{\n code.replace(\n QRegExp(QString(\"(%1\\\\s*=)[^\\\\r\\\\n]*\").arg(name)),\n QString(\"\\\\1 %1\").arg(value));\n}\n\nstatic void usage() {\n QTextStream output(stderr);\n output << \"Usage:\" << endl;\n output << \" doxyfilter Generate documentation\" << endl;\n output << \" doxyfilter -g Generate Doxyfile\" << endl;\n output << \" doxyfilter <sourcefile> Filter the given file's code\" << endl;\n}\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n\n if (argc == 1)\n return QProcess::execute(\"doxygen\");\n else if (argc != 2) {\n usage();\n return 1;\n }\n\n if (!strcmp(argv[1], \"-g\")) {\n \/\/ generate default Doxyfile\n QProcess process;\n process.start(\"doxygen\", QStringList() << \"-g\" << \"-\");\n if (!process.waitForFinished()) {\n qWarning(\"Could not run doxygen\");\n return 1;\n }\n QString code = QString::fromUtf8(process.readAll());\n\n \/\/ adjust Doxyfile\n setField(code, \"ALPHABETICAL_INDEX\", \"NO\");\n setField(code, \"EXCLUDE_PATTERNS\", \"*\/moc_*\");\n setField(code, \"FULL_PATH_NAMES\", \"NO\");\n setField(code, \"HIDE_UNDOC_CLASSES\", \"YES\");\n setField(code, \"GENERATE_LATEX\", \"NO\");\n setField(code, \"HTML_TIMESTAMP\", \"NO\");\n setField(code, \"INPUT\", \"..\/src\");\n setField(code, \"INPUT_FILTER\", QString::fromLocal8Bit(argv[0]));\n setField(code, \"PROJECT_NAME\", \"QXmpp\");\n setField(code, \"PROJECT_NUMBER\", QString(\"Version: %1.%2.%3\").arg(\n QString::number((QXMPP_VERSION >> 16) & 0xff),\n QString::number((QXMPP_VERSION >> 8) & 0xff),\n QString::number(QXMPP_VERSION & 0xff)));\n\n \/\/ write doxyfile\n QFile output(\"Doxyfile\");\n if (!output.open(QIODevice::WriteOnly)) {\n qWarning(\"Could not write to %s\", qPrintable(output.fileName()));\n return 1;\n }\n output.write(code.toUtf8());\n output.close();\n\n } else if (!strcmp(argv[1], \"-h\")) {\n usage();\n return 0;\n } else {\n \/\/ read source code\n QFile source(QString::fromLocal8Bit(argv[1]));\n if (!source.open(QIODevice::ReadOnly)) {\n qWarning(\"Could not open %s\", qPrintable(source.fileName()));\n return 1;\n }\n QString code = QString::fromUtf8(source.readAll());\n source.close();\n\n \/\/ add links for XEPs\n code.replace(QRegExp(\"(XEP-([0-9]{4}))\"), \"<a href=\\\"http:\/\/xmpp.org\/extensions\/xep-\\\\2.html\\\">\\\\1<\/a>\");\n\n QTextStream output(stdout);\n output << code;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ======================================================================\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n * Licensed under the MIT License.\n * See LICENSE.md in the project root for license information.\n * ======================================================================\n *\/\n\n#ifdef QTFRAMEWORK\n#include <QVariantMap>\n#include <QMap>\n#include <QJsonObject>\n#include <QJsonDocument>\n\n#include \"JsonObjectQt.h\"\n#include \"JsonArrayQt.h\"\n#include \"JsonParserQt.h\"\n\n#include \"..\/..\/ModernAPI\/RMSExceptions.h\"\n#include \"..\/Logger\/Logger.h\"\n\nnamespace rmscore {\nnamespace platform {\nnamespace json {\nstd::shared_ptr<IJsonObject>IJsonObject::Create()\n{\n return std::make_shared<JsonObjectQt>();\n}\n\nbool JsonObjectQt::IsNull(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n return jo.contains(name.c_str())\n ? jo[name.c_str()].isNull()\n : throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::IsNull: Name doesn't exist\");\n}\n\nstd::shared_ptr<IJsonArray>JsonObjectQt::GetArray()\n{\n if (!this->impl_.isArray())\n {\n throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetArray: The object is not an array\");\n }\n\n QJsonArray arr = this->impl_.toArray();\n\n return std::shared_ptr<IJsonArray>(new JsonArrayQt(arr));\n}\n\nbool JsonObjectQt::HasName(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n return jo.contains(name.c_str());\n}\n\nstd::string JsonObjectQt::GetNamedString(const std::string& name,\n const std::string& defaultValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (jo.contains(name.c_str()) && !jo[name.c_str()].isNull()) {\n auto obj = jo[name.c_str()];\n\n if (obj.isString()) {\n return obj.toString().toStdString();\n }\n\n throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedString: convertion error\");\n }\n return defaultValue;\n}\n\nvoid JsonObjectQt::SetNamedString(const std::string& name,\n const std::string& value)\n{\n QJsonObject jo = this->impl_.toObject();\n\n jo.insert(name.c_str(), QJsonValue(QString::fromStdString(value)));\n this->impl_ = QJsonValue(jo);\n}\n\nbool JsonObjectQt::GetNamedBool(const std::string& name, bool bDefaultValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n return jo.contains(name.c_str())\n ? jo[name.c_str()].isBool()\n ? jo[name.c_str()].toBool()\n : throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedBool: convertion error\")\n : bDefaultValue;\n}\n\nvoid JsonObjectQt::SetNamedBool(const std::string& name, bool bValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n jo.insert(name.c_str(), bValue);\n this->impl_ = QJsonValue(jo);\n}\n\ndouble JsonObjectQt::GetNamedNumber(const std::string& name, double fDefaultValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n return jo.contains(name.c_str())\n ? jo[name.c_str()].isDouble()\n ? jo[name.c_str()].toDouble()\n : throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedNumber: convertion error\")\n : fDefaultValue;\n}\n\nvoid JsonObjectQt::SetNamedNumber(const std::string& name, double fValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n jo.insert(name.c_str(), fValue);\n this->impl_ = QJsonValue(jo);\n}\n\nstd::shared_ptr<IJsonObject>JsonObjectQt::GetNamedObject(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (!jo.contains(name.c_str()))\n {\n return nullptr;\n }\n\n QJsonValue val = jo.value(name.data());\n\n if (!val.isObject())\n {\n throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedObject: convertion error\");\n }\n\n return std::make_shared<JsonObjectQt>(val);\n}\n\nvoid JsonObjectQt::SetNamedObject(const std::string& name,\n const IJsonObject& jsonObject)\n{\n QJsonObject jo = this->impl_.toObject();\n auto other = static_cast<const JsonObjectQt&>(jsonObject);\n\n jo.insert(name.c_str(), other.impl());\n this->impl_ = QJsonValue(jo);\n}\n\nstd::shared_ptr<IJsonArray>JsonObjectQt::GetNamedArray(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (!jo.contains(name.c_str()))\n {\n return nullptr;\n }\n\n QJsonValue val = jo.value(name.data());\n\n if (!val.isArray())\n {\n throw exceptions::RMSInvalidArgumentException(\"the value is not an array\");\n }\n\n return std::shared_ptr<JsonArrayQt>(new JsonArrayQt(val.toArray()));\n}\n\nvoid JsonObjectQt::SetNamedArray(const std::string& name,\n const IJsonArray & jsonArray)\n{\n QJsonObject jo = this->impl_.toObject();\n auto other = static_cast<const JsonArrayQt&>(jsonArray);\n\n jo.insert(name.c_str(), QJsonValue(other.impl()));\n this->impl_ = QJsonValue(jo);\n}\n\nvoid JsonObjectQt::SetNamedValue(const std::string & name,\n const common::ByteArray& value) {\n QJsonObject jo = this->impl_.toObject();\n\n QVariant jsonVar(QByteArray(reinterpret_cast<const char *>(value.data()),\n static_cast<int>(value.size())));\n\n jo.insert(name.c_str(), QJsonValue::fromVariant(jsonVar));\n this->impl_ = QJsonValue(jo);\n}\n\ncommon::ByteArray JsonObjectQt::GetNamedValue(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n auto nameStr = name.c_str();\n auto ret = jo.contains(nameStr)\n ? jo[nameStr].isString()\n ? jo[nameStr].toString().toUtf8()\n : throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedValue: convertion error\")\n : QByteArray();\n\n return common::ByteArray(ret.begin(), ret.end());\n}\n\nStringArray JsonObjectQt::GetNamedStringArray(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (!jo.contains(name.c_str()))\n {\n Logger::Warning(\n \"JsonObjectQt::GetNamedStringArray: Can't find the key named '%s'\",\n name.c_str());\n return std::vector<std::string>();\n }\n\n QJsonValue val = jo[name.c_str()];\n\n if (!val.isArray())\n {\n throw exceptions::RMSInvalidArgumentException(\"the value is not an array\");\n }\n\n StringArray list;\n QJsonArray arr = val.toArray();\n\n for (int i = 0; i < arr.size(); ++i)\n {\n QJsonValue val = arr[i];\n list.push_back(val.toString().toStdString());\n }\n\n return list;\n}\n\nmodernapi::AppDataHashMap JsonObjectQt::ToStringDictionary()\n{\n QVariantMap map = this->impl_.toObject().toVariantMap();\n\n modernapi::AppDataHashMap result;\n\n for (QString& key : map.keys())\n {\n result.insert(std::make_pair(key.toStdString(),\n map[key].toString().toStdString()));\n }\n return result;\n}\n\ncommon::ByteArray JsonObjectQt::Stringify()\n{\n QJsonDocument doc(this->impl_.toObject());\n\n auto res = doc.toJson(QJsonDocument::Compact);\n\n return common::ByteArray(res.begin(), res.end());\n}\n}\n}\n} \/\/ namespace rmscore { namespace platform { namespace json {\n#endif \/\/ ifdef QTFRAMEWORK\n<commit_msg>ERROR: UsageRestrictionsClient: Got an invalid json from the REST service. #35<commit_after>\/*\n * ======================================================================\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n * Licensed under the MIT License.\n * See LICENSE.md in the project root for license information.\n * ======================================================================\n *\/\n\n#ifdef QTFRAMEWORK\n#include <QVariantMap>\n#include <QMap>\n#include <QJsonObject>\n#include <QJsonDocument>\n\n#include \"JsonObjectQt.h\"\n#include \"JsonArrayQt.h\"\n#include \"JsonParserQt.h\"\n\n#include \"..\/..\/ModernAPI\/RMSExceptions.h\"\n#include \"..\/Logger\/Logger.h\"\n\nnamespace rmscore {\nnamespace platform {\nnamespace json {\nstd::shared_ptr<IJsonObject>IJsonObject::Create()\n{\n return std::make_shared<JsonObjectQt>();\n}\n\nbool JsonObjectQt::IsNull(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n return jo.contains(name.c_str())\n ? jo[name.c_str()].isNull()\n : throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::IsNull: Name doesn't exist\");\n}\n\nstd::shared_ptr<IJsonArray>JsonObjectQt::GetArray()\n{\n if (!this->impl_.isArray())\n {\n throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetArray: The object is not an array\");\n }\n\n QJsonArray arr = this->impl_.toArray();\n\n return std::shared_ptr<IJsonArray>(new JsonArrayQt(arr));\n}\n\nbool JsonObjectQt::HasName(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n return jo.contains(name.c_str());\n}\n\nstd::string JsonObjectQt::GetNamedString(const std::string& name,\n const std::string& defaultValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (jo.contains(name.c_str()) && !jo[name.c_str()].isNull()) {\n auto obj = jo[name.c_str()];\n\n if (obj.isString()) {\n return obj.toString().toStdString();\n }\n\n throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedString: convertion error\");\n }\n return defaultValue;\n}\n\nvoid JsonObjectQt::SetNamedString(const std::string& name,\n const std::string& value)\n{\n QJsonObject jo = this->impl_.toObject();\n\n jo.insert(name.c_str(), QJsonValue(QString::fromStdString(value)));\n this->impl_ = QJsonValue(jo);\n}\n\nbool JsonObjectQt::GetNamedBool(const std::string& name, bool bDefaultValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n return jo.contains(name.c_str())\n ? jo[name.c_str()].isBool()\n ? jo[name.c_str()].toBool()\n : throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedBool: convertion error\")\n : bDefaultValue;\n}\n\nvoid JsonObjectQt::SetNamedBool(const std::string& name, bool bValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n jo.insert(name.c_str(), bValue);\n this->impl_ = QJsonValue(jo);\n}\n\ndouble JsonObjectQt::GetNamedNumber(const std::string& name, double fDefaultValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (jo.contains(name.c_str())) {\n auto joVal = jo[name.c_str()];\n\n if (!joVal.isNull()) {\n if (jo[name.c_str()].isDouble()) {\n return jo[name.c_str()].toDouble();\n } else {\n throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedNumber: convertion error\");\n }\n }\n }\n return fDefaultValue;\n}\n\nvoid JsonObjectQt::SetNamedNumber(const std::string& name, double fValue)\n{\n QJsonObject jo = this->impl_.toObject();\n\n jo.insert(name.c_str(), fValue);\n this->impl_ = QJsonValue(jo);\n}\n\nstd::shared_ptr<IJsonObject>JsonObjectQt::GetNamedObject(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (!jo.contains(name.c_str()))\n {\n return nullptr;\n }\n\n QJsonValue val = jo.value(name.data());\n\n if (!val.isObject())\n {\n throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedObject: convertion error\");\n }\n\n return std::make_shared<JsonObjectQt>(val);\n}\n\nvoid JsonObjectQt::SetNamedObject(const std::string& name,\n const IJsonObject& jsonObject)\n{\n QJsonObject jo = this->impl_.toObject();\n auto other = static_cast<const JsonObjectQt&>(jsonObject);\n\n jo.insert(name.c_str(), other.impl());\n this->impl_ = QJsonValue(jo);\n}\n\nstd::shared_ptr<IJsonArray>JsonObjectQt::GetNamedArray(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (!jo.contains(name.c_str()))\n {\n return nullptr;\n }\n\n QJsonValue val = jo.value(name.data());\n\n if (!val.isArray())\n {\n throw exceptions::RMSInvalidArgumentException(\"the value is not an array\");\n }\n\n return std::shared_ptr<JsonArrayQt>(new JsonArrayQt(val.toArray()));\n}\n\nvoid JsonObjectQt::SetNamedArray(const std::string& name,\n const IJsonArray & jsonArray)\n{\n QJsonObject jo = this->impl_.toObject();\n auto other = static_cast<const JsonArrayQt&>(jsonArray);\n\n jo.insert(name.c_str(), QJsonValue(other.impl()));\n this->impl_ = QJsonValue(jo);\n}\n\nvoid JsonObjectQt::SetNamedValue(const std::string & name,\n const common::ByteArray& value) {\n QJsonObject jo = this->impl_.toObject();\n\n QVariant jsonVar(QByteArray(reinterpret_cast<const char *>(value.data()),\n static_cast<int>(value.size())));\n\n jo.insert(name.c_str(), QJsonValue::fromVariant(jsonVar));\n this->impl_ = QJsonValue(jo);\n}\n\ncommon::ByteArray JsonObjectQt::GetNamedValue(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n auto nameStr = name.c_str();\n auto ret = jo.contains(nameStr)\n ? jo[nameStr].isString()\n ? jo[nameStr].toString().toUtf8()\n : throw exceptions::RMSInvalidArgumentException(\n \"JsonObjectQt::GetNamedValue: convertion error\")\n : QByteArray();\n\n return common::ByteArray(ret.begin(), ret.end());\n}\n\nStringArray JsonObjectQt::GetNamedStringArray(const std::string& name)\n{\n QJsonObject jo = this->impl_.toObject();\n\n if (!jo.contains(name.c_str()))\n {\n Logger::Warning(\n \"JsonObjectQt::GetNamedStringArray: Can't find the key named '%s'\",\n name.c_str());\n return std::vector<std::string>();\n }\n\n QJsonValue val = jo[name.c_str()];\n\n if (!val.isArray())\n {\n throw exceptions::RMSInvalidArgumentException(\"the value is not an array\");\n }\n\n StringArray list;\n QJsonArray arr = val.toArray();\n\n for (int i = 0; i < arr.size(); ++i)\n {\n QJsonValue val = arr[i];\n list.push_back(val.toString().toStdString());\n }\n\n return list;\n}\n\nmodernapi::AppDataHashMap JsonObjectQt::ToStringDictionary()\n{\n QVariantMap map = this->impl_.toObject().toVariantMap();\n\n modernapi::AppDataHashMap result;\n\n for (QString& key : map.keys())\n {\n result.insert(std::make_pair(key.toStdString(),\n map[key].toString().toStdString()));\n }\n return result;\n}\n\ncommon::ByteArray JsonObjectQt::Stringify()\n{\n QJsonDocument doc(this->impl_.toObject());\n\n auto res = doc.toJson(QJsonDocument::Compact);\n\n return common::ByteArray(res.begin(), res.end());\n}\n}\n}\n} \/\/ namespace rmscore { namespace platform { namespace json {\n#endif \/\/ ifdef QTFRAMEWORK\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fix bug: texblends uninitialized value transported.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * deinvert - a voice inversion descrambler\n * Copyright (c) Oona Räisänen\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n#include \"src\/deinvert.h\"\n\n#include <getopt.h>\n#include <algorithm>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\n#include \"config.h\"\n#include \"src\/liquid_wrappers.h\"\n#include \"src\/wdsp.h\"\n\nnamespace deinvert {\n\nnamespace {\n\nconst float kLowpassFilterLengthSeconds = 0.0018f;\nconst int kMaxFilterLength = 2047;\n\n}\n\nvoid PrintUsage() {\n std::cout <<\n \"deinvert [OPTIONS]\\n\"\n \"\\n\"\n \"-f, --frequency FREQ Frequency of the inversion carrier, in Hertz.\\n\"\n \"\\n\"\n \"-h, --help Display this usage help.\\n\"\n \"\\n\"\n \"-i, --input-file FILE Use an audio file as input. All formats\\n\"\n \" supported by libsndfile should work.\\n\"\n \"\\n\"\n \"-n, --nofilter Disable filtering (faster).\\n\"\n \"\\n\"\n \"-o, --output-file FILE Write output to a WAV file instead of stdout. An\\n\"\n \" existing file will be overwritten.\\n\"\n \"\\n\"\n \"-p, --preset NUM Scrambler frequency preset (1-8), referring to\\n\"\n \" the set of common carrier frequencies used by\\n\"\n \" e.g. the Selectone ST-20B scrambler.\\n\"\n \"\\n\"\n \"-r, --samplerate RATE Sampling rate of raw input audio, in Hertz.\\n\"\n \"\\n\"\n \"-v, --version Display version string.\\n\";\n}\n\nvoid PrintVersion() {\n#ifdef DEBUG\n std::cout << PACKAGE_STRING << \"-debug by OH2EIQ\" << std::endl;\n#else\n std::cout << PACKAGE_STRING << \" by OH2EIQ\" << std::endl;\n#endif\n}\n\nOptions GetOptions(int argc, char** argv) {\n deinvert::Options options;\n\n static struct option long_options[] = {\n { \"frequency\", no_argument, 0, 'f'},\n { \"preset\", 1, 0, 'p'},\n { \"input-file\", 1, 0, 'i'},\n { \"help\", no_argument, 0, 'h'},\n { \"nofilter\", no_argument, 0, 'n'},\n { \"samplerate\", 1, 0, 'r'},\n { \"version\", no_argument, 0, 'v'},\n {0, 0, 0, 0}};\n\n static const std::vector<float> selectone_carriers({\n 2632.f, 2718.f, 2868.f, 3023.f, 3196.f, 3339.f, 3495.f, 3729.f\n });\n\n options.frequency = selectone_carriers.at(0);\n\n int option_index = 0;\n int option_char;\n int selectone_num;\n\n while ((option_char = getopt_long(argc, argv, \"f:hi:no:p:r:v\",\n long_options,\n &option_index)) >= 0) {\n switch (option_char) {\n case 'i':\n#ifdef HAVE_SNDFILE\n options.infilename = std::string(optarg);\n options.input_type = deinvert::INPUT_SNDFILE;\n#else\n std::cerr << \"error: deinvert was compiled without libsndfile\"\n << std::endl;\n options.just_exit = true;\n#endif\n break;\n case 'f':\n options.frequency = std::atoi(optarg);\n break;\n case 'n':\n options.nofilter = true;\n break;\n case 'o':\n#ifdef HAVE_SNDFILE\n options.output_type = deinvert::OUTPUT_WAVFILE;\n options.outfilename = std::string(optarg);\n#else\n std::cerr << \"error: deinvert was compiled without libsndfile\"\n << std::endl;\n options.just_exit = true;\n#endif\n break;\n case 'p':\n selectone_num = std::atoi(optarg);\n if (selectone_num >= 1 &&\n selectone_num <= 8) {\n options.frequency = selectone_carriers.at(selectone_num - 1);\n } else {\n std::cerr << \"error: please specify scrambler group from 1 to 8\"\n << std::endl;\n options.just_exit = true;\n }\n break;\n case 'r':\n options.samplerate = std::atoi(optarg);\n if (options.samplerate < 6000.f) {\n std::cerr << \"error: sample rate must be 6000 Hz or higher\"\n << std::endl;\n options.just_exit = true;\n }\n break;\n case 'v':\n PrintVersion();\n options.just_exit = true;\n break;\n case 'h':\n default:\n PrintUsage();\n options.just_exit = true;\n break;\n }\n if (options.just_exit)\n break;\n }\n\n return options;\n}\n\nAudioReader::~AudioReader() {\n}\n\nbool AudioReader::eof() const {\n return is_eof_;\n}\n\nStdinReader::StdinReader(const Options& options) :\n samplerate_(options.samplerate) {\n is_eof_ = false;\n}\n\nStdinReader::~StdinReader() {\n}\n\nstd::vector<float> StdinReader::ReadBlock() {\n int num_read = fread(buffer_, sizeof(buffer_[0]), bufsize_, stdin);\n\n if (num_read < bufsize_)\n is_eof_ = true;\n\n std::vector<float> result(num_read);\n for (int i = 0; i < num_read; i++)\n result[i] = buffer_[i] * (1.f \/ 32768.f);\n\n return result;\n}\n\nfloat StdinReader::samplerate() const {\n return samplerate_;\n}\n\n#ifdef HAVE_SNDFILE\nSndfileReader::SndfileReader(const Options& options) :\n info_({0, 0, 0, 0, 0, 0}),\n file_(sf_open(options.infilename.c_str(), SFM_READ, &info_)) {\n is_eof_ = false;\n if (info_.frames == 0) {\n std::cerr << \"error: couldn't open \" << options.infilename << std::endl;\n is_eof_ = true;\n }\n if (info_.samplerate < 6000.f) {\n std::cerr << \"error: sample rate must be 6000 Hz or higher\" << std::endl;\n is_eof_ = true;\n }\n}\n\nSndfileReader::~SndfileReader() {\n sf_close(file_);\n}\n\nstd::vector<float> SndfileReader::ReadBlock() {\n std::vector<float> result;\n if (is_eof_)\n return result;\n\n sf_count_t num_read = sf_readf_float(file_, buffer_, bufsize_);\n if (num_read != bufsize_)\n is_eof_ = true;\n\n if (info_.channels == 1) {\n result = std::vector<float>(buffer_, buffer_ + num_read);\n } else {\n result = std::vector<float>(num_read);\n for (size_t i = 0; i < result.size(); i++)\n result[i] = buffer_[i * info_.channels];\n }\n return result;\n}\n\nfloat SndfileReader::samplerate() const {\n return info_.samplerate;\n}\n#endif\n\nAudioWriter::~AudioWriter() {\n}\n\nRawPCMWriter::RawPCMWriter() : ptr_(0) {\n}\n\nbool RawPCMWriter::push(float sample) {\n int16_t outsample = sample * 32767.f;\n buffer_[ptr_] = outsample;\n ptr_++;\n if (ptr_ == bufsize_) {\n fwrite(buffer_, sizeof(buffer_[0]), bufsize_, stdout);\n ptr_ = 0;\n }\n return true;\n}\n\n#ifdef HAVE_SNDFILE\nSndfileWriter::SndfileWriter(const std::string& fname, int rate) :\n info_({0, rate, 1, SF_FORMAT_WAV | SF_FORMAT_PCM_16, 0, 0}),\n file_(sf_open(fname.c_str(), SFM_WRITE, &info_)),\n ptr_(0) {\n}\n\nSndfileWriter::~SndfileWriter() {\n write(ptr_);\n sf_close(file_);\n}\n\nbool SndfileWriter::push(float sample) {\n bool success = true;\n buffer_[ptr_] = sample;\n if (ptr_ == bufsize_ - 1) {\n success = write(ptr_);\n }\n\n ptr_ = (ptr_ + 1) % bufsize_;\n return success;\n}\n\nbool SndfileWriter::write(sf_count_t numsamples) {\n return (file_ != nullptr &&\n sf_write_float(file_, buffer_, numsamples) == numsamples);\n}\n#endif\n\n} \/\/ namespace deinvert\n\nint main(int argc, char** argv) {\n deinvert::Options options = deinvert::GetOptions(argc, argv);\n\n if (options.just_exit)\n return EXIT_FAILURE;\n\n deinvert::AudioReader* reader;\n deinvert::AudioWriter* writer;\n\n#ifdef HAVE_SNDFILE\n if (options.input_type == deinvert::INPUT_SNDFILE)\n reader = new deinvert::SndfileReader(options);\n else\n#endif\n reader = new deinvert::StdinReader(options);\n\n#ifdef HAVE_SNDFILE\n if (options.output_type == deinvert::OUTPUT_WAVFILE)\n writer = new deinvert::SndfileWriter(options.outfilename,\n options.samplerate);\n else\n#endif\n writer = new deinvert::RawPCMWriter();\n\n int filter_length = 2 * std::round(options.samplerate *\n deinvert::kLowpassFilterLengthSeconds) + 1;\n filter_length = std::min(deinvert::kMaxFilterLength, filter_length);\n\n#ifdef HAVE_LIQUID\n liquid::NCO nco(LIQUID_VCO,\n options.frequency * 2.0f * M_PI \/ options.samplerate);\n liquid::FIRFilter prefilter(filter_length,\n options.frequency \/ options.samplerate);\n liquid::FIRFilter postfilter(filter_length,\n (options.frequency - 150.f) \/ options.samplerate);\n#else\n wdsp::NCO nco(options.frequency * 2.0f * M_PI \/ options.samplerate);\n#endif\n\n while (!reader->eof()) {\n for (float insample : reader->ReadBlock()) {\n nco.Step();\n#ifdef HAVE_LIQUID\n if (options.nofilter) {\n writer->push(nco.MixUp({insample, 0.0f}).real() * M_SQRT2);\n } else {\n prefilter.push({insample, 0.0f});\n std::complex<float> mixed = nco.MixUp(prefilter.execute());\n postfilter.push(mixed.real());\n writer->push(postfilter.execute().real() * 2.f);\n }\n#else\n writer->push(nco.MixUp({insample, 0.0f}).real());\n#endif\n }\n }\n\n delete reader;\n delete writer;\n}\n<commit_msg>don't overflow when channels > 1<commit_after>\/*\n * deinvert - a voice inversion descrambler\n * Copyright (c) Oona Räisänen\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n#include \"src\/deinvert.h\"\n\n#include <getopt.h>\n#include <algorithm>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\n#include \"config.h\"\n#include \"src\/liquid_wrappers.h\"\n#include \"src\/wdsp.h\"\n\nnamespace deinvert {\n\nnamespace {\n\nconst float kLowpassFilterLengthSeconds = 0.0018f;\nconst int kMaxFilterLength = 2047;\n\n}\n\nvoid PrintUsage() {\n std::cout <<\n \"deinvert [OPTIONS]\\n\"\n \"\\n\"\n \"-f, --frequency FREQ Frequency of the inversion carrier, in Hertz.\\n\"\n \"\\n\"\n \"-h, --help Display this usage help.\\n\"\n \"\\n\"\n \"-i, --input-file FILE Use an audio file as input. All formats\\n\"\n \" supported by libsndfile should work.\\n\"\n \"\\n\"\n \"-n, --nofilter Disable filtering (faster).\\n\"\n \"\\n\"\n \"-o, --output-file FILE Write output to a WAV file instead of stdout. An\\n\"\n \" existing file will be overwritten.\\n\"\n \"\\n\"\n \"-p, --preset NUM Scrambler frequency preset (1-8), referring to\\n\"\n \" the set of common carrier frequencies used by\\n\"\n \" e.g. the Selectone ST-20B scrambler.\\n\"\n \"\\n\"\n \"-r, --samplerate RATE Sampling rate of raw input audio, in Hertz.\\n\"\n \"\\n\"\n \"-v, --version Display version string.\\n\";\n}\n\nvoid PrintVersion() {\n#ifdef DEBUG\n std::cout << PACKAGE_STRING << \"-debug by OH2EIQ\" << std::endl;\n#else\n std::cout << PACKAGE_STRING << \" by OH2EIQ\" << std::endl;\n#endif\n}\n\nOptions GetOptions(int argc, char** argv) {\n deinvert::Options options;\n\n static struct option long_options[] = {\n { \"frequency\", no_argument, 0, 'f'},\n { \"preset\", 1, 0, 'p'},\n { \"input-file\", 1, 0, 'i'},\n { \"help\", no_argument, 0, 'h'},\n { \"nofilter\", no_argument, 0, 'n'},\n { \"samplerate\", 1, 0, 'r'},\n { \"version\", no_argument, 0, 'v'},\n {0, 0, 0, 0}};\n\n static const std::vector<float> selectone_carriers({\n 2632.f, 2718.f, 2868.f, 3023.f, 3196.f, 3339.f, 3495.f, 3729.f\n });\n\n options.frequency = selectone_carriers.at(0);\n\n int option_index = 0;\n int option_char;\n int selectone_num;\n\n while ((option_char = getopt_long(argc, argv, \"f:hi:no:p:r:v\",\n long_options,\n &option_index)) >= 0) {\n switch (option_char) {\n case 'i':\n#ifdef HAVE_SNDFILE\n options.infilename = std::string(optarg);\n options.input_type = deinvert::INPUT_SNDFILE;\n#else\n std::cerr << \"error: deinvert was compiled without libsndfile\"\n << std::endl;\n options.just_exit = true;\n#endif\n break;\n case 'f':\n options.frequency = std::atoi(optarg);\n break;\n case 'n':\n options.nofilter = true;\n break;\n case 'o':\n#ifdef HAVE_SNDFILE\n options.output_type = deinvert::OUTPUT_WAVFILE;\n options.outfilename = std::string(optarg);\n#else\n std::cerr << \"error: deinvert was compiled without libsndfile\"\n << std::endl;\n options.just_exit = true;\n#endif\n break;\n case 'p':\n selectone_num = std::atoi(optarg);\n if (selectone_num >= 1 &&\n selectone_num <= 8) {\n options.frequency = selectone_carriers.at(selectone_num - 1);\n } else {\n std::cerr << \"error: please specify scrambler group from 1 to 8\"\n << std::endl;\n options.just_exit = true;\n }\n break;\n case 'r':\n options.samplerate = std::atoi(optarg);\n if (options.samplerate < 6000.f) {\n std::cerr << \"error: sample rate must be 6000 Hz or higher\"\n << std::endl;\n options.just_exit = true;\n }\n break;\n case 'v':\n PrintVersion();\n options.just_exit = true;\n break;\n case 'h':\n default:\n PrintUsage();\n options.just_exit = true;\n break;\n }\n if (options.just_exit)\n break;\n }\n\n return options;\n}\n\nAudioReader::~AudioReader() {\n}\n\nbool AudioReader::eof() const {\n return is_eof_;\n}\n\nStdinReader::StdinReader(const Options& options) :\n samplerate_(options.samplerate) {\n is_eof_ = false;\n}\n\nStdinReader::~StdinReader() {\n}\n\nstd::vector<float> StdinReader::ReadBlock() {\n int num_read = fread(buffer_, sizeof(buffer_[0]), bufsize_, stdin);\n\n if (num_read < bufsize_)\n is_eof_ = true;\n\n std::vector<float> result(num_read);\n for (int i = 0; i < num_read; i++)\n result[i] = buffer_[i] * (1.f \/ 32768.f);\n\n return result;\n}\n\nfloat StdinReader::samplerate() const {\n return samplerate_;\n}\n\n#ifdef HAVE_SNDFILE\nSndfileReader::SndfileReader(const Options& options) :\n info_({0, 0, 0, 0, 0, 0}),\n file_(sf_open(options.infilename.c_str(), SFM_READ, &info_)) {\n is_eof_ = false;\n if (info_.frames == 0) {\n std::cerr << \"error: couldn't open \" << options.infilename << std::endl;\n is_eof_ = true;\n }\n if (info_.samplerate < 6000.f) {\n std::cerr << \"error: sample rate must be 6000 Hz or higher\" << std::endl;\n is_eof_ = true;\n }\n}\n\nSndfileReader::~SndfileReader() {\n sf_close(file_);\n}\n\nstd::vector<float> SndfileReader::ReadBlock() {\n std::vector<float> result;\n if (is_eof_)\n return result;\n\n sf_count_t num_read = sf_readf_float(file_, buffer_,\n bufsize_ \/ info_.channels);\n if (num_read != bufsize_)\n is_eof_ = true;\n\n if (info_.channels == 1) {\n result = std::vector<float>(buffer_, buffer_ + num_read);\n } else {\n result = std::vector<float>(num_read);\n for (size_t i = 0; i < result.size(); i++)\n result[i] = buffer_[i * info_.channels];\n }\n return result;\n}\n\nfloat SndfileReader::samplerate() const {\n return info_.samplerate;\n}\n#endif\n\nAudioWriter::~AudioWriter() {\n}\n\nRawPCMWriter::RawPCMWriter() : ptr_(0) {\n}\n\nbool RawPCMWriter::push(float sample) {\n int16_t outsample = sample * 32767.f;\n buffer_[ptr_] = outsample;\n ptr_++;\n if (ptr_ == bufsize_) {\n fwrite(buffer_, sizeof(buffer_[0]), bufsize_, stdout);\n ptr_ = 0;\n }\n return true;\n}\n\n#ifdef HAVE_SNDFILE\nSndfileWriter::SndfileWriter(const std::string& fname, int rate) :\n info_({0, rate, 1, SF_FORMAT_WAV | SF_FORMAT_PCM_16, 0, 0}),\n file_(sf_open(fname.c_str(), SFM_WRITE, &info_)),\n ptr_(0) {\n}\n\nSndfileWriter::~SndfileWriter() {\n write(ptr_);\n sf_close(file_);\n}\n\nbool SndfileWriter::push(float sample) {\n bool success = true;\n buffer_[ptr_] = sample;\n if (ptr_ == bufsize_ - 1) {\n success = write(ptr_);\n }\n\n ptr_ = (ptr_ + 1) % bufsize_;\n return success;\n}\n\nbool SndfileWriter::write(sf_count_t numsamples) {\n return (file_ != nullptr &&\n sf_write_float(file_, buffer_, numsamples) == numsamples);\n}\n#endif\n\n} \/\/ namespace deinvert\n\nint main(int argc, char** argv) {\n deinvert::Options options = deinvert::GetOptions(argc, argv);\n\n if (options.just_exit)\n return EXIT_FAILURE;\n\n deinvert::AudioReader* reader;\n deinvert::AudioWriter* writer;\n\n#ifdef HAVE_SNDFILE\n if (options.input_type == deinvert::INPUT_SNDFILE)\n reader = new deinvert::SndfileReader(options);\n else\n#endif\n reader = new deinvert::StdinReader(options);\n\n#ifdef HAVE_SNDFILE\n if (options.output_type == deinvert::OUTPUT_WAVFILE)\n writer = new deinvert::SndfileWriter(options.outfilename,\n options.samplerate);\n else\n#endif\n writer = new deinvert::RawPCMWriter();\n\n int filter_length = 2 * std::round(options.samplerate *\n deinvert::kLowpassFilterLengthSeconds) + 1;\n filter_length = std::min(deinvert::kMaxFilterLength, filter_length);\n\n#ifdef HAVE_LIQUID\n liquid::NCO nco(LIQUID_VCO,\n options.frequency * 2.0f * M_PI \/ options.samplerate);\n liquid::FIRFilter prefilter(filter_length,\n options.frequency \/ options.samplerate);\n liquid::FIRFilter postfilter(filter_length,\n (options.frequency - 150.f) \/ options.samplerate);\n#else\n wdsp::NCO nco(options.frequency * 2.0f * M_PI \/ options.samplerate);\n#endif\n\n while (!reader->eof()) {\n for (float insample : reader->ReadBlock()) {\n nco.Step();\n#ifdef HAVE_LIQUID\n if (options.nofilter) {\n writer->push(nco.MixUp({insample, 0.0f}).real() * M_SQRT2);\n } else {\n prefilter.push({insample, 0.0f});\n std::complex<float> mixed = nco.MixUp(prefilter.execute());\n postfilter.push(mixed.real());\n writer->push(postfilter.execute().real() * 2.f);\n }\n#else\n writer->push(nco.MixUp({insample, 0.0f}).real());\n#endif\n }\n }\n\n delete reader;\n delete writer;\n}\n<|endoftext|>"} {"text":"<commit_before>#define PY_SSIZE_T_CLEAN\r\n#include <Python.h>\r\n\r\n#if PY_MAJOR_VERSION == 3\r\n#define BO_OUT \"y#\"\r\n#endif\r\n\r\n#if PY_MAJOR_VERSION == 2\r\n#define BO_OUT \"s#\"\r\n#endif\r\n\r\n\r\n\r\n#define BYBYTESOP_FUNC(NAME,OP) \\\r\nstatic PyObject * NAME(PyObject *self, PyObject *args){ \\\r\n\tPy_buffer ab,bb; \\\r\n\tchar * a; \\\r\n\tchar * b; \\\r\n\tchar * out; \\\r\n\tPy_ssize_t out_size; \\\r\n\tif (!PyArg_ParseTuple(args, \"s*s*\", &ab,&bb)) \\\r\n return NULL; \\\r\n\tif (ab.suboffsets!=NULL||ab.strides!=NULL){ \\\r\n\t\tPyBuffer_Release(&ab); \\\r\n\t\tPyBuffer_Release(&bb); \\\r\n\t\tPyErr_SetString(PyExc_ValueError,\"First argument must export buffer as PyBUF_CONTIG_RO\"); \\\r\n\t\treturn NULL; \\\r\n\t} \\\r\n\tif (bb.suboffsets!=NULL||ab.strides!=NULL){ \\\r\n\t\tPyBuffer_Release(&ab); \\\r\n\t\tPyBuffer_Release(&bb); \\\r\n\t\tPyErr_SetString(PyExc_ValueError,\"First argument must export buffer as PyBUF_CONTIG_RO\"); \\\r\n\t\treturn NULL; \\\r\n\t} \\\r\n\tPy_BEGIN_ALLOW_THREADS \\\r\n\tif (bb.len<ab.len){ \\\r\n\t\tout_size=bb.len; \\\r\n\t}else{ \\\r\n\t\tout_size=ab.len; \\\r\n\t} \\\r\n\ta=(char*)ab.buf; \\\r\n\tb=(char*)bb.buf; \\\r\n\tout=(char*)malloc(out_size); \\\r\n\tfor (int i=0;i<out_size;i++){ \\\r\n\t\tout[i]=a[i] OP b[i]; \\\r\n\t} \\\r\n\tPyBuffer_Release(&ab); \\\r\n\tPyBuffer_Release(&bb); \\\r\n\tPy_END_ALLOW_THREADS \\\r\n\treturn Py_BuildValue(BO_OUT,out,out_size); \\\r\n} \\\r\n\r\n\r\n#define BYBYTESOP_N_FUNC(NAME,OP) \\\r\nstatic PyObject * NAME(PyObject *self, PyObject *args){ \\\r\n\tPy_buffer ab,bb; \\\r\n\tchar * a; \\\r\n\tchar * b; \\\r\n\tchar * out; \\\r\n\tPy_ssize_t out_size; \\\r\n\tif (!PyArg_ParseTuple(args, \"s*s*\", &ab,&bb)) \\\r\n return NULL; \\\r\n\tif (ab.suboffsets!=NULL||ab.strides!=NULL){ \\\r\n\t\tPyBuffer_Release(&ab); \\\r\n\t\tPyBuffer_Release(&bb); \\\r\n\t\tPyErr_SetString(PyExc_ValueError,\"First argument must export buffer as PyBUF_CONTIG_RO\"); \\\r\n\t\treturn NULL; \\\r\n\t} \\\r\n\tif (bb.suboffsets!=NULL||ab.strides!=NULL){ \\\r\n\t\tPyBuffer_Release(&ab); \\\r\n\t\tPyBuffer_Release(&bb); \\\r\n\t\tPyErr_SetString(PyExc_ValueError,\"First argument must export buffer as PyBUF_CONTIG_RO\"); \\\r\n\t\treturn NULL; \\\r\n\t} \\\r\n\tPy_BEGIN_ALLOW_THREADS \\\r\n\tif (bb.len<ab.len){ \\\r\n\t\tout_size=bb.len; \\\r\n\t}else{ \\\r\n\t\tout_size=ab.len; \\\r\n\t} \\\r\n\ta=(char*)ab.buf; \\\r\n\tb=(char*)bb.buf; \\\r\n\tout=(char*)malloc(out_size); \\\r\n\tfor (int i=0;i<out_size;i++){ \\\r\n\t\tout[i]=~(a[i] OP b[i]); \\\r\n\t} \\\r\n\tPyBuffer_Release(&ab); \\\r\n\tPyBuffer_Release(&bb); \\\r\n\tPy_END_ALLOW_THREADS \\\r\n\treturn Py_BuildValue(BO_OUT,out,out_size); \\\r\n} \\\r\n\r\n\r\nBYBYTESOP_FUNC(bytesop_op_xor, ^)\r\n\r\nBYBYTESOP_FUNC(bytesop_op_or, | )\r\n\r\nBYBYTESOP_FUNC(bytesop_op_and, &)\r\n\r\nBYBYTESOP_N_FUNC(bytesop_op_xnor, ^)\r\n\r\nBYBYTESOP_N_FUNC(bytesop_op_nor, | )\r\n\r\nBYBYTESOP_N_FUNC(bytesop_op_nand, &)\r\n\r\n\r\nstatic PyObject * bytesop_op_not(PyObject *self, PyObject *args){\r\n\tPy_buffer b;\r\n\tchar * a;\r\n\tchar * out;\r\n\tPy_ssize_t out_size;\r\n\tif (!PyArg_ParseTuple(args, \"s*\", &b))\r\n\t\treturn NULL;\r\n\tif (b.suboffsets!=NULL||b.strides!=NULL){\r\n\t\tPyBuffer_Release(&b);\r\n\t\tPyErr_SetString(PyExc_ValueError,\"Argument must export buffer as PyBUF_CONTIG_RO\");\r\n\t\treturn NULL;\r\n\t}\r\n\tPy_BEGIN_ALLOW_THREADS \r\n\ta=(char*)b.buf;\r\n\tout_size = b.len;\r\n\tout = (char*)malloc(out_size);\r\n\tfor (int i = 0; i < out_size; i++){\r\n\t\tout[i] = ~a[i];\r\n\t}\r\n\tPyBuffer_Release(&b);\r\n\tPy_END_ALLOW_THREADS\r\n\treturn Py_BuildValue(BO_OUT, out, out_size);\r\n}\r\n\r\nstatic PyMethodDef BytesOpMethods[] =\r\n{\r\n\t{ \"op_xor\", bytesop_op_xor, METH_VARARGS,\r\n\t\"XOR two bytes-like objects.\" },\r\n\t{ \"op_or\", bytesop_op_or, METH_VARARGS,\r\n\t\"OR two bytes-like objects.\" },\r\n\t{ \"op_and\", bytesop_op_and, METH_VARARGS,\r\n\t\"AND two bytes-like objects.\" },\r\n\t{ \"op_xnor\", bytesop_op_xnor, METH_VARARGS,\r\n\t\"XNOR (NXOR) two bytes-like objects.\" },\r\n\t{ \"op_nor\", bytesop_op_nor, METH_VARARGS,\r\n\t\"NOR two bytes-like objects.\" },\r\n\t{ \"op_nand\", bytesop_op_nand, METH_VARARGS,\r\n\t\"NAND two bytes-like objects.\" },\r\n\t{ \"op_not\", bytesop_op_not, METH_VARARGS,\r\n\t\"NOT a bytes-like object.\" },\r\n\t{ NULL, NULL, 0, NULL }\r\n};\r\n\r\n#define BO_N \"bytesop\"\r\n#define BO_DOC \"Bitwise operations on bytes-like objects\"\r\n\r\n#if PY_MAJOR_VERSION == 3\r\nstatic struct PyModuleDef bytesopmodule = {\r\n\tPyModuleDef_HEAD_INIT,\r\n\tBO_N, \/* name of module *\/\r\n\tBO_DOC, \/* module documentation, may be NULL *\/\r\n\t-1, \/* size of per-interpreter state of the module,\r\n\t\t\t\t or -1 if the module keeps state in global variables. *\/\r\n\t\t\t\t BytesOpMethods\r\n};\r\n\r\nPyMODINIT_FUNC PyInit_bytesop(void)\r\n{\r\n\treturn PyModule_Create(&bytesopmodule);\r\n}\r\n#endif\r\n\r\n#if PY_MAJOR_VERSION == 2\r\nPyMODINIT_FUNC initbytesop(void)\r\n{\r\n\t(void)Py_InitModule3(BO_N, BytesOpMethods, BO_DOC);\r\n}\r\n\r\n#endif<commit_msg>add function signatures<commit_after>#define PY_SSIZE_T_CLEAN\r\n#include <Python.h>\r\n\r\n#if PY_MAJOR_VERSION == 3\r\n#define BO_OUT \"y#\"\r\n#endif\r\n\r\n#if PY_MAJOR_VERSION == 2\r\n#define BO_OUT \"s#\"\r\n#endif\r\n\r\n\r\n\r\n#define BYBYTESOP_FUNC(NAME,OP) \\\r\nstatic PyObject * NAME(PyObject *self, PyObject *args){ \\\r\n\tPy_buffer ab,bb; \\\r\n\tchar * a; \\\r\n\tchar * b; \\\r\n\tchar * out; \\\r\n\tPy_ssize_t out_size; \\\r\n\tif (!PyArg_ParseTuple(args, \"s*s*\", &ab,&bb)) \\\r\n return NULL; \\\r\n\tif (ab.suboffsets!=NULL||ab.strides!=NULL){ \\\r\n\t\tPyBuffer_Release(&ab); \\\r\n\t\tPyBuffer_Release(&bb); \\\r\n\t\tPyErr_SetString(PyExc_ValueError,\"First argument must export buffer as PyBUF_CONTIG_RO\"); \\\r\n\t\treturn NULL; \\\r\n\t} \\\r\n\tif (bb.suboffsets!=NULL||ab.strides!=NULL){ \\\r\n\t\tPyBuffer_Release(&ab); \\\r\n\t\tPyBuffer_Release(&bb); \\\r\n\t\tPyErr_SetString(PyExc_ValueError,\"First argument must export buffer as PyBUF_CONTIG_RO\"); \\\r\n\t\treturn NULL; \\\r\n\t} \\\r\n\tPy_BEGIN_ALLOW_THREADS \\\r\n\tif (bb.len<ab.len){ \\\r\n\t\tout_size=bb.len; \\\r\n\t}else{ \\\r\n\t\tout_size=ab.len; \\\r\n\t} \\\r\n\ta=(char*)ab.buf; \\\r\n\tb=(char*)bb.buf; \\\r\n\tout=(char*)malloc(out_size); \\\r\n\tfor (int i=0;i<out_size;i++){ \\\r\n\t\tout[i]=a[i] OP b[i]; \\\r\n\t} \\\r\n\tPyBuffer_Release(&ab); \\\r\n\tPyBuffer_Release(&bb); \\\r\n\tPy_END_ALLOW_THREADS \\\r\n\treturn Py_BuildValue(BO_OUT,out,out_size); \\\r\n} \\\r\n\r\n\r\n#define BYBYTESOP_N_FUNC(NAME,OP) \\\r\nstatic PyObject * NAME(PyObject *self, PyObject *args){ \\\r\n\tPy_buffer ab,bb; \\\r\n\tchar * a; \\\r\n\tchar * b; \\\r\n\tchar * out; \\\r\n\tPy_ssize_t out_size; \\\r\n\tif (!PyArg_ParseTuple(args, \"s*s*\", &ab,&bb)) \\\r\n return NULL; \\\r\n\tif (ab.suboffsets!=NULL||ab.strides!=NULL){ \\\r\n\t\tPyBuffer_Release(&ab); \\\r\n\t\tPyBuffer_Release(&bb); \\\r\n\t\tPyErr_SetString(PyExc_ValueError,\"First argument must export buffer as PyBUF_CONTIG_RO\"); \\\r\n\t\treturn NULL; \\\r\n\t} \\\r\n\tif (bb.suboffsets!=NULL||ab.strides!=NULL){ \\\r\n\t\tPyBuffer_Release(&ab); \\\r\n\t\tPyBuffer_Release(&bb); \\\r\n\t\tPyErr_SetString(PyExc_ValueError,\"First argument must export buffer as PyBUF_CONTIG_RO\"); \\\r\n\t\treturn NULL; \\\r\n\t} \\\r\n\tPy_BEGIN_ALLOW_THREADS \\\r\n\tif (bb.len<ab.len){ \\\r\n\t\tout_size=bb.len; \\\r\n\t}else{ \\\r\n\t\tout_size=ab.len; \\\r\n\t} \\\r\n\ta=(char*)ab.buf; \\\r\n\tb=(char*)bb.buf; \\\r\n\tout=(char*)malloc(out_size); \\\r\n\tfor (int i=0;i<out_size;i++){ \\\r\n\t\tout[i]=~(a[i] OP b[i]); \\\r\n\t} \\\r\n\tPyBuffer_Release(&ab); \\\r\n\tPyBuffer_Release(&bb); \\\r\n\tPy_END_ALLOW_THREADS \\\r\n\treturn Py_BuildValue(BO_OUT,out,out_size); \\\r\n} \\\r\n\r\n\r\nBYBYTESOP_FUNC(bytesop_op_xor, ^)\r\n\r\nBYBYTESOP_FUNC(bytesop_op_or, | )\r\n\r\nBYBYTESOP_FUNC(bytesop_op_and, &)\r\n\r\nBYBYTESOP_N_FUNC(bytesop_op_xnor, ^)\r\n\r\nBYBYTESOP_N_FUNC(bytesop_op_nor, | )\r\n\r\nBYBYTESOP_N_FUNC(bytesop_op_nand, &)\r\n\r\n\r\nstatic PyObject * bytesop_op_not(PyObject *self, PyObject *args){\r\n\tPy_buffer b;\r\n\tchar * a;\r\n\tchar * out;\r\n\tPy_ssize_t out_size;\r\n\tif (!PyArg_ParseTuple(args, \"s*\", &b))\r\n\t\treturn NULL;\r\n\tif (b.suboffsets!=NULL||b.strides!=NULL){\r\n\t\tPyBuffer_Release(&b);\r\n\t\tPyErr_SetString(PyExc_ValueError,\"Argument must export buffer as PyBUF_CONTIG_RO\");\r\n\t\treturn NULL;\r\n\t}\r\n\tPy_BEGIN_ALLOW_THREADS \r\n\ta=(char*)b.buf;\r\n\tout_size = b.len;\r\n\tout = (char*)malloc(out_size);\r\n\tfor (int i = 0; i < out_size; i++){\r\n\t\tout[i] = ~a[i];\r\n\t}\r\n\tPyBuffer_Release(&b);\r\n\tPy_END_ALLOW_THREADS\r\n\treturn Py_BuildValue(BO_OUT, out, out_size);\r\n}\r\n\r\nstatic PyMethodDef BytesOpMethods[] =\r\n{\r\n\t{ \"op_xor\", bytesop_op_xor, METH_VARARGS,\r\n\t\"(a, b)\\nXOR two bytes-like objects.\" },\r\n\t{ \"op_or\", bytesop_op_or, METH_VARARGS,\r\n\t\"(a, b)\\nOR two bytes-like objects.\" },\r\n\t{ \"op_and\", bytesop_op_and, METH_VARARGS,\r\n\t\"(a, b)\\nAND two bytes-like objects.\" },\r\n\t{ \"op_xnor\", bytesop_op_xnor, METH_VARARGS,\r\n\t\"(a, b)\\nXNOR (NXOR) two bytes-like objects.\" },\r\n\t{ \"op_nor\", bytesop_op_nor, METH_VARARGS,\r\n\t\"(a, b)\\nNOR two bytes-like objects.\" },\r\n\t{ \"op_nand\", bytesop_op_nand, METH_VARARGS,\r\n\t\"(a, b)\\nNAND two bytes-like objects.\" },\r\n\t{ \"op_not\", bytesop_op_not, METH_VARARGS,\r\n\t\"(b)\\nNOT a bytes-like object.\" },\r\n\t{ NULL, NULL, 0, NULL }\r\n};\r\n\r\n#define BO_N \"bytesop\"\r\n#define BO_DOC \"Bitwise operations on bytes-like objects\"\r\n\r\n#if PY_MAJOR_VERSION == 3\r\nstatic struct PyModuleDef bytesopmodule = {\r\n\tPyModuleDef_HEAD_INIT,\r\n\tBO_N, \/* name of module *\/\r\n\tBO_DOC, \/* module documentation, may be NULL *\/\r\n\t-1, \/* size of per-interpreter state of the module,\r\n\t\t\t\t or -1 if the module keeps state in global variables. *\/\r\n\t\t\t\t BytesOpMethods\r\n};\r\n\r\nPyMODINIT_FUNC PyInit_bytesop(void)\r\n{\r\n\treturn PyModule_Create(&bytesopmodule);\r\n}\r\n#endif\r\n\r\n#if PY_MAJOR_VERSION == 2\r\nPyMODINIT_FUNC initbytesop(void)\r\n{\r\n\t(void)Py_InitModule3(BO_N, BytesOpMethods, BO_DOC);\r\n}\r\n\r\n#endif<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2017, EPL-Vizards\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 met:\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 the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the EPL-Vizards nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\/*!\n * \\file qwtplotmodel.cpp\n *\/\n\n#include \"qwtplotmodel.hpp\"\nusing namespace EPL_Viz;\n\nQWTPlotModel::QWTPlotModel() : BaseModel() {}\n\nQWTPlotModel::init() {\n plot = MainWindow::mainWindow->findChild<QwtPlot *>(\"plotCanvas\");\n log = MainWindow::mainWindow->getCaptureInstance()->getEventLog();\n appid = log->getAppID();\n}\n\nQWTPlotModel::update(EPL_DataCollect::Cycle *cycle) {\n \/\/ TODO Image Event?\n}\n<commit_msg>compile fix<commit_after>\/* Copyright (c) 2017, EPL-Vizards\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 met:\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 the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the EPL-Vizards nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\/*!\n * \\file qwtplotmodel.cpp\n *\/\n\n#include \"qwtplotmodel.hpp\"\nusing namespace EPL_Viz;\n\nQWTPlotModel::QWTPlotModel() : BaseModel() {}\n\nvoid QWTPlotModel::init() {\n plot = MainWindow::mainWindow->findChild<QwtPlot *>(\"plotCanvas\");\n log = MainWindow::mainWindow->getCaptureInstance()->getEventLog();\n appid = log->getAppID();\n}\n\nvoid QWTPlotModel::update(EPL_DataCollect::Cycle *cycle) {\n \/\/ TODO Image Event?\n}\n<|endoftext|>"} {"text":"<commit_before>\n#ifdef HAVE_STD_IOSTREAM\n#include <iostream>\n#include <fstream>\n#else\n#include <iostream.h>\n#include <fstream.h>\n#endif\n#include <vector>\n\n#include <sys\/stat.h>\n\n#include \"dircoll.h\"\n\nnamespace zipios {\n\nusing std::cerr ;\nusing std::endl ;\nusing std::vector ;\n\nDirectoryCollection::DirectoryCollection( const string &path ) {\n \/\/ Check path is actually a directory\n if ( isDir( path ) ) {\n _filename = path ;\n _valid = true ;\n } else {\n _valid = false ;\n }\n}\n\nvoid DirectoryCollection::close() {\n _valid = false ;\n}\n\n\nvector< ConstEntryPointer > DirectoryCollection::entries() const {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n\n cerr << \"DirectoryCollection::entries not implemented yet\" << endl ;\n\n \/\/ FIXME: Return the real thing.\n return vector< ConstEntryPointer >() ; \n}\n\n\nConstEntryPointer\nDirectoryCollection::getEntry( const string &name, \n\t\t\t MatchPath matchpath = MATCH ) const {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n\n if ( matchpath != MATCH ) {\n cerr << \n \"DirectoryCollection::getEntry not implemented for matchpath = IGNORE\" \n\t << endl ;\n return 0 ;\n }\n\n return new DirEntry( name, \"\", _filename ) ;\n}\n\n\nistream *DirectoryCollection::getInputStream( const ConstEntryPointer &entry ) {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n\n return getInputStream( entry->getName() ) ;\n}\n\n\nistream *DirectoryCollection::getInputStream( const string &entry_name, \n\t\t\t\t\t MatchPath matchpath = MATCH ) {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n\n if ( matchpath != MATCH ) {\n cerr << \n \"DirectoryCollection::getInputStream not implemented for matchpath = IGNORE\" \n\t << endl ;\n return 0 ;\n }\n\n string real_path( _filename + entry_name ) ;\n ifstream *ifs = new ifstream( real_path.c_str() ) ;\n if( ! *ifs ) {\n delete ifs ;\n return 0 ;\n } else \n return ifs ; \n}\n\n\nint DirectoryCollection::size() const {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n \/\/ FIXME: implement this method.\n}\n\n\nDirectoryCollection::~DirectoryCollection() {}\n\n\nbool DirectoryCollection::isDir( const string &path ) const {\n struct stat buf ;\n \/\/ If stat fails something is wrong, and we\n \/\/ may as well return false.\n if( stat( path.c_str(), &buf ) != 0 ) \n return false ;\n else\n return S_ISDIR( buf.st_mode ) ;\n}\n\n\n} \/\/ namespace\n\n\/** \\file\n Implementation of DirectoryCollection.\n*\/\n\n\/*\n Zipios++ - a small C++ library that provides easy access to .zip files.\n Copyright (C) 2000 Thomas Sndergaard\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; 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. 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, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\n<commit_msg>DirectoryCollection::getInputStream() now returns a 0 pointer (wrapped in a ConstEntryPointer) if the specified entry is invalid, as it should.<commit_after>\n#ifdef HAVE_STD_IOSTREAM\n#include <iostream>\n#include <fstream>\n#else\n#include <iostream.h>\n#include <fstream.h>\n#endif\n#include <vector>\n\n#include <sys\/stat.h>\n\n#include \"dircoll.h\"\n\nnamespace zipios {\n\nusing std::cerr ;\nusing std::endl ;\nusing std::vector ;\n\nDirectoryCollection::DirectoryCollection( const string &path ) {\n \/\/ Check path is actually a directory\n if ( isDir( path ) ) {\n _filename = path ;\n _valid = true ;\n } else {\n _valid = false ;\n }\n \n \/\/ In order to be able to simply prepend _filename\n \/\/ we need to transform it slightly. If it ends in a\n \/\/ slash thats fine.\n \/\/ if not we have to append a slash, unless the specified path is the\n \/\/ empty string.\n if ( _filename.size() > 0 && _filename[ _filename.size() -1 ] != '\/' )\n _filename.append( 1, '\/' ) ;\n}\n\nvoid DirectoryCollection::close() {\n _valid = false ;\n}\n\n\nvector< ConstEntryPointer > DirectoryCollection::entries() const {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n\n cerr << \"DirectoryCollection::entries not implemented yet\" << endl ;\n\n \/\/ FIXME: Return the real thing.\n return vector< ConstEntryPointer >() ; \n}\n\n\nConstEntryPointer\nDirectoryCollection::getEntry( const string &name, \n\t\t\t MatchPath matchpath = MATCH ) const {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n\n if ( matchpath != MATCH ) {\n cerr << \n \"DirectoryCollection::getEntry not implemented for matchpath = IGNORE\" \n\t << endl ;\n return 0 ;\n }\n ConstEntryPointer ent ( new DirEntry( name, \"\", _filename ) ) ;\n if ( ent->isValid() )\n return ent ;\n else\n return 0 ;\n}\n\n\nistream *DirectoryCollection::getInputStream( const ConstEntryPointer &entry ) {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n\n return getInputStream( entry->getName() ) ;\n}\n\n\nistream *DirectoryCollection::getInputStream( const string &entry_name, \n\t\t\t\t\t MatchPath matchpath = MATCH ) {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n\n if ( matchpath != MATCH ) {\n cerr << \n \"DirectoryCollection::getInputStream not implemented for matchpath = IGNORE\" \n\t << endl ;\n return 0 ;\n }\n\n string real_path( _filename + entry_name ) ;\n ifstream *ifs = new ifstream( real_path.c_str() ) ;\n if( ! *ifs ) {\n delete ifs ;\n return 0 ;\n } else \n return ifs ; \n}\n\n\nint DirectoryCollection::size() const {\n if ( ! _valid )\n throw InvalidStateException( \"Attempt to use an invalid DirectoryCollection\" ) ;\n \/\/ FIXME: implement this method.\n}\n\n\nDirectoryCollection::~DirectoryCollection() {}\n\n\nbool DirectoryCollection::isDir( const string &path ) const {\n struct stat buf ;\n \/\/ If stat fails something is wrong, and we\n \/\/ may as well return false.\n if( stat( path.c_str(), &buf ) != 0 ) \n return false ;\n else\n return S_ISDIR( buf.st_mode ) ;\n}\n\n\n} \/\/ namespace\n\n\/** \\file\n Implementation of DirectoryCollection.\n*\/\n\n\/*\n Zipios++ - a small C++ library that provides easy access to .zip files.\n Copyright (C) 2000 Thomas Sndergaard\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; 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. 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, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"views\/controls\/native_control.h\"\n\n#include <atlbase.h>\n#include <atlapp.h>\n#include <atlcrack.h>\n#include <atlframe.h>\n#include <atlmisc.h>\n\n#include \"app\/keyboard_code_conversion_win.h\"\n#include \"app\/keyboard_codes.h\"\n#include \"app\/l10n_util_win.h\"\n#include \"base\/logging.h\"\n#include \"base\/win_util.h\"\n#include \"gfx\/native_theme_win.h\"\n#include \"views\/background.h\"\n#include \"views\/border.h\"\n#include \"views\/controls\/native\/native_view_host.h\"\n#include \"views\/focus\/focus_manager.h\"\n#include \"views\/widget\/widget.h\"\n\nnamespace views {\n\n\/\/ Maps to the original WNDPROC for the controller window before we subclassed\n\/\/ it.\nstatic const wchar_t* const kHandlerKey =\n L\"__CONTROL_ORIGINAL_MESSAGE_HANDLER__\";\n\n\/\/ Maps to the NativeControl.\nstatic const wchar_t* const kNativeControlKey = L\"__NATIVE_CONTROL__\";\n\nclass NativeControlContainer : public CWindowImpl<NativeControlContainer,\n CWindow,\n CWinTraits<WS_CHILD | WS_CLIPSIBLINGS |\n WS_CLIPCHILDREN>> {\n public:\n\n explicit NativeControlContainer(NativeControl* parent) : parent_(parent),\n control_(NULL) {\n Create(parent->GetWidget()->GetNativeView());\n ::ShowWindow(m_hWnd, SW_SHOW);\n }\n\n virtual ~NativeControlContainer() {\n }\n\n \/\/ NOTE: If you add a new message, be sure and verify parent_ is valid before\n \/\/ calling into parent_.\n DECLARE_FRAME_WND_CLASS(L\"ChromeViewsNativeControlContainer\", NULL);\n BEGIN_MSG_MAP(NativeControlContainer);\n MSG_WM_CREATE(OnCreate);\n MSG_WM_ERASEBKGND(OnEraseBkgnd);\n MSG_WM_PAINT(OnPaint);\n MSG_WM_SIZE(OnSize);\n MSG_WM_NOTIFY(OnNotify);\n MSG_WM_COMMAND(OnCommand);\n MSG_WM_DESTROY(OnDestroy);\n MSG_WM_CONTEXTMENU(OnContextMenu);\n MSG_WM_CTLCOLORBTN(OnCtlColorBtn);\n MSG_WM_CTLCOLORSTATIC(OnCtlColorStatic)\n END_MSG_MAP();\n\n HWND GetControl() {\n return control_;\n }\n\n \/\/ Called when the parent is getting deleted. This control stays around until\n \/\/ it gets the OnFinalMessage call.\n void ResetParent() {\n parent_ = NULL;\n }\n\n void OnFinalMessage(HWND hwnd) {\n if (parent_)\n parent_->NativeControlDestroyed();\n delete this;\n }\n\n private:\n LRESULT OnCreate(LPCREATESTRUCT create_struct) {\n control_ = parent_->CreateNativeControl(m_hWnd);\n\n \/\/ We subclass the control hwnd so we get the WM_KEYDOWN messages.\n WNDPROC original_handler =\n win_util::SetWindowProc(control_,\n &NativeControl::NativeControlWndProc);\n BOOL set_prop_result = SetProp(control_, kHandlerKey, original_handler);\n CHECK(set_prop_result) << \"Failed to SetProp in NativeControlContainer \"\n << win_util::FormatLastWin32Error();\n\n set_prop_result = SetProp(control_, kNativeControlKey, parent_);\n CHECK(set_prop_result) << \"Failed to SetProp in NativeControlContainer \"\n << win_util::FormatLastWin32Error();\n\n ::ShowWindow(control_, SW_SHOW);\n return 1;\n }\n\n LRESULT OnEraseBkgnd(HDC dc) {\n return 1;\n }\n\n void OnPaint(HDC ignore) {\n PAINTSTRUCT ps;\n HDC dc = ::BeginPaint(*this, &ps);\n ::EndPaint(*this, &ps);\n }\n\n void OnSize(int type, const CSize& sz) {\n ::MoveWindow(control_, 0, 0, sz.cx, sz.cy, TRUE);\n }\n\n LRESULT OnCommand(UINT code, int id, HWND source) {\n return parent_ ? parent_->OnCommand(code, id, source) : 0;\n }\n\n LRESULT OnNotify(int w_param, LPNMHDR l_param) {\n if (parent_)\n return parent_->OnNotify(w_param, l_param);\n else\n return 0;\n }\n\n void OnDestroy() {\n if (parent_)\n parent_->OnDestroy();\n }\n\n void OnContextMenu(HWND window, const POINT& location) {\n if (parent_)\n parent_->OnContextMenu(location);\n }\n\n \/\/ We need to find an ancestor with a non-null background, and\n \/\/ ask it for a (solid color) brush that approximates\n \/\/ the background. The caller will use this when drawing\n \/\/ the native control as a background color, particularly\n \/\/ for radiobuttons and XP style pushbuttons.\n LRESULT OnCtlColor(UINT msg, HDC dc, HWND control) {\n const View *ancestor = parent_;\n while (ancestor) {\n const Background *background = ancestor->background();\n if (background) {\n HBRUSH brush = background->GetNativeControlBrush();\n if (brush)\n return reinterpret_cast<LRESULT>(brush);\n }\n ancestor = ancestor->GetParent();\n }\n\n \/\/ COLOR_BTNFACE is the default for dialog box backgrounds.\n return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_BTNFACE));\n }\n\n LRESULT OnCtlColorBtn(HDC dc, HWND control) {\n return OnCtlColor(WM_CTLCOLORBTN, dc, control);\n }\n\n LRESULT OnCtlColorStatic(HDC dc, HWND control) {\n return OnCtlColor(WM_CTLCOLORSTATIC, dc, control);\n }\n\n NativeControl* parent_;\n HWND control_;\n DISALLOW_COPY_AND_ASSIGN(NativeControlContainer);\n};\n\nNativeControl::NativeControl() : hwnd_view_(NULL),\n container_(NULL),\n fixed_width_(-1),\n horizontal_alignment_(CENTER),\n fixed_height_(-1),\n vertical_alignment_(CENTER) {\n enabled_ = true;\n focusable_ = true;\n}\n\nNativeControl::~NativeControl() {\n if (container_) {\n container_->ResetParent();\n ::DestroyWindow(*container_);\n }\n}\n\nvoid NativeControl::ValidateNativeControl() {\n if (hwnd_view_ == NULL) {\n hwnd_view_ = new NativeViewHost;\n AddChildView(hwnd_view_);\n }\n\n if (!container_ && IsVisible()) {\n container_ = new NativeControlContainer(this);\n hwnd_view_->Attach(*container_);\n if (!enabled_)\n EnableWindow(GetNativeControlHWND(), enabled_);\n\n \/\/ This message ensures that the focus border is shown.\n ::SendMessage(container_->GetControl(),\n WM_CHANGEUISTATE,\n MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),\n 0);\n }\n}\n\nvoid NativeControl::ViewHierarchyChanged(bool is_add, View *parent,\n View *child) {\n if (is_add && parent != this && !container_ && GetWidget()) {\n ValidateNativeControl();\n Layout();\n }\n}\n\nvoid NativeControl::Layout() {\n if (!container_ && GetWidget())\n ValidateNativeControl();\n\n if (hwnd_view_) {\n gfx::Rect lb = GetLocalBounds(false);\n\n int x = lb.x();\n int y = lb.y();\n int width = lb.width();\n int height = lb.height();\n if (fixed_width_ > 0) {\n width = std::min(fixed_width_, width);\n switch (horizontal_alignment_) {\n case LEADING:\n \/\/ Nothing to do.\n break;\n case CENTER:\n x += (lb.width() - width) \/ 2;\n break;\n case TRAILING:\n x = x + lb.width() - width;\n break;\n default:\n NOTREACHED();\n }\n }\n\n if (fixed_height_ > 0) {\n height = std::min(fixed_height_, height);\n switch (vertical_alignment_) {\n case LEADING:\n \/\/ Nothing to do.\n break;\n case CENTER:\n y += (lb.height() - height) \/ 2;\n break;\n case TRAILING:\n y = y + lb.height() - height;\n break;\n default:\n NOTREACHED();\n }\n }\n\n hwnd_view_->SetBounds(x, y, width, height);\n }\n}\n\nvoid NativeControl::OnContextMenu(const POINT& location) {\n if (!GetContextMenuController())\n return;\n\n if (location.x == -1 && location.y == -1)\n ShowContextMenu(GetKeyboardContextMenuLocation(), false);\n else\n ShowContextMenu(gfx::Point(location), true);\n}\n\nvoid NativeControl::Focus() {\n if (container_) {\n DCHECK(container_->GetControl());\n ::SetFocus(container_->GetControl());\n NotifyAccessibilityEvent(AccessibilityTypes::EVENT_FOCUS, false);\n }\n}\n\nHWND NativeControl::GetNativeControlHWND() {\n if (container_)\n return container_->GetControl();\n else\n return NULL;\n}\n\nvoid NativeControl::NativeControlDestroyed() {\n if (hwnd_view_)\n hwnd_view_->Detach();\n container_ = NULL;\n}\n\nvoid NativeControl::SetVisible(bool f) {\n if (f != IsVisible()) {\n View::SetVisible(f);\n if (!f && container_) {\n ::DestroyWindow(*container_);\n } else if (f && !container_) {\n ValidateNativeControl();\n }\n }\n}\n\nvoid NativeControl::SetEnabled(bool enabled) {\n if (enabled_ != enabled) {\n View::SetEnabled(enabled);\n if (GetNativeControlHWND()) {\n EnableWindow(GetNativeControlHWND(), enabled_);\n }\n }\n}\n\nvoid NativeControl::Paint(gfx::Canvas* canvas) {\n}\n\nvoid NativeControl::VisibilityChanged(View* starting_from, bool is_visible) {\n SetVisible(is_visible);\n}\n\nvoid NativeControl::SetFixedWidth(int width, Alignment alignment) {\n DCHECK_GT(width, 0);\n fixed_width_ = width;\n horizontal_alignment_ = alignment;\n}\n\nvoid NativeControl::SetFixedHeight(int height, Alignment alignment) {\n DCHECK_GT(height, 0);\n fixed_height_ = height;\n vertical_alignment_ = alignment;\n}\n\nDWORD NativeControl::GetAdditionalExStyle() const {\n \/\/ If the UI for the view is mirrored, we should make sure we add the\n \/\/ extended window style for a right-to-left layout so the subclass creates\n \/\/ a mirrored HWND for the underlying control.\n DWORD ex_style = 0;\n if (base::i18n::IsRTL())\n ex_style |= l10n_util::GetExtendedStyles();\n\n return ex_style;\n}\n\nDWORD NativeControl::GetAdditionalRTLStyle() const {\n \/\/ If the UI for the view is mirrored, we should make sure we add the\n \/\/ extended window style for a right-to-left layout so the subclass creates\n \/\/ a mirrored HWND for the underlying control.\n DWORD ex_style = 0;\n if (base::i18n::IsRTL())\n ex_style |= l10n_util::GetExtendedTooltipStyles();\n\n return ex_style;\n}\n\n\/\/ static\nLRESULT CALLBACK NativeControl::NativeControlWndProc(HWND window, UINT message,\n WPARAM w_param,\n LPARAM l_param) {\n HANDLE original_handler = GetProp(window, kHandlerKey);\n DCHECK(original_handler);\n NativeControl* native_control =\n static_cast<NativeControl*>(GetProp(window, kNativeControlKey));\n DCHECK(native_control);\n\n if (message == WM_KEYDOWN &&\n native_control->OnKeyDown(app::KeyboardCodeForWindowsKeyCode(w_param))) {\n return 0;\n } else if (message == WM_SETFOCUS) {\n \/\/ Let the focus manager know that the focus changed.\n FocusManager* focus_manager = native_control->GetFocusManager();\n if (focus_manager) {\n focus_manager->SetFocusedView(native_control);\n } else {\n NOTREACHED();\n }\n } else if (message == WM_DESTROY) {\n win_util::SetWindowProc(window,\n reinterpret_cast<WNDPROC>(original_handler));\n RemoveProp(window, kHandlerKey);\n RemoveProp(window, kNativeControlKey);\n }\n\n return CallWindowProc(reinterpret_cast<WNDPROC>(original_handler), window,\n message, w_param, l_param);\n}\n\n} \/\/ namespace views\n<commit_msg>Revert 63478 - Adds CHECKs in hopes of figuring out why we're crashing on some test bots.<commit_after>\/\/ Copyright (c) 2010 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 \"views\/controls\/native_control.h\"\n\n#include <atlbase.h>\n#include <atlapp.h>\n#include <atlcrack.h>\n#include <atlframe.h>\n#include <atlmisc.h>\n\n#include \"app\/keyboard_code_conversion_win.h\"\n#include \"app\/keyboard_codes.h\"\n#include \"app\/l10n_util_win.h\"\n#include \"base\/logging.h\"\n#include \"base\/win_util.h\"\n#include \"gfx\/native_theme_win.h\"\n#include \"views\/background.h\"\n#include \"views\/border.h\"\n#include \"views\/controls\/native\/native_view_host.h\"\n#include \"views\/focus\/focus_manager.h\"\n#include \"views\/widget\/widget.h\"\n\nnamespace views {\n\n\/\/ Maps to the original WNDPROC for the controller window before we subclassed\n\/\/ it.\nstatic const wchar_t* const kHandlerKey =\n L\"__CONTROL_ORIGINAL_MESSAGE_HANDLER__\";\n\n\/\/ Maps to the NativeControl.\nstatic const wchar_t* const kNativeControlKey = L\"__NATIVE_CONTROL__\";\n\nclass NativeControlContainer : public CWindowImpl<NativeControlContainer,\n CWindow,\n CWinTraits<WS_CHILD | WS_CLIPSIBLINGS |\n WS_CLIPCHILDREN>> {\n public:\n\n explicit NativeControlContainer(NativeControl* parent) : parent_(parent),\n control_(NULL) {\n Create(parent->GetWidget()->GetNativeView());\n ::ShowWindow(m_hWnd, SW_SHOW);\n }\n\n virtual ~NativeControlContainer() {\n }\n\n \/\/ NOTE: If you add a new message, be sure and verify parent_ is valid before\n \/\/ calling into parent_.\n DECLARE_FRAME_WND_CLASS(L\"ChromeViewsNativeControlContainer\", NULL);\n BEGIN_MSG_MAP(NativeControlContainer);\n MSG_WM_CREATE(OnCreate);\n MSG_WM_ERASEBKGND(OnEraseBkgnd);\n MSG_WM_PAINT(OnPaint);\n MSG_WM_SIZE(OnSize);\n MSG_WM_NOTIFY(OnNotify);\n MSG_WM_COMMAND(OnCommand);\n MSG_WM_DESTROY(OnDestroy);\n MSG_WM_CONTEXTMENU(OnContextMenu);\n MSG_WM_CTLCOLORBTN(OnCtlColorBtn);\n MSG_WM_CTLCOLORSTATIC(OnCtlColorStatic)\n END_MSG_MAP();\n\n HWND GetControl() {\n return control_;\n }\n\n \/\/ Called when the parent is getting deleted. This control stays around until\n \/\/ it gets the OnFinalMessage call.\n void ResetParent() {\n parent_ = NULL;\n }\n\n void OnFinalMessage(HWND hwnd) {\n if (parent_)\n parent_->NativeControlDestroyed();\n delete this;\n }\n private:\n\n LRESULT OnCreate(LPCREATESTRUCT create_struct) {\n control_ = parent_->CreateNativeControl(m_hWnd);\n\n \/\/ We subclass the control hwnd so we get the WM_KEYDOWN messages.\n WNDPROC original_handler =\n win_util::SetWindowProc(control_,\n &NativeControl::NativeControlWndProc);\n SetProp(control_, kHandlerKey, original_handler);\n SetProp(control_, kNativeControlKey , parent_);\n\n ::ShowWindow(control_, SW_SHOW);\n return 1;\n }\n\n LRESULT OnEraseBkgnd(HDC dc) {\n return 1;\n }\n\n void OnPaint(HDC ignore) {\n PAINTSTRUCT ps;\n HDC dc = ::BeginPaint(*this, &ps);\n ::EndPaint(*this, &ps);\n }\n\n void OnSize(int type, const CSize& sz) {\n ::MoveWindow(control_, 0, 0, sz.cx, sz.cy, TRUE);\n }\n\n LRESULT OnCommand(UINT code, int id, HWND source) {\n return parent_ ? parent_->OnCommand(code, id, source) : 0;\n }\n\n LRESULT OnNotify(int w_param, LPNMHDR l_param) {\n if (parent_)\n return parent_->OnNotify(w_param, l_param);\n else\n return 0;\n }\n\n void OnDestroy() {\n if (parent_)\n parent_->OnDestroy();\n }\n\n void OnContextMenu(HWND window, const POINT& location) {\n if (parent_)\n parent_->OnContextMenu(location);\n }\n\n \/\/ We need to find an ancestor with a non-null background, and\n \/\/ ask it for a (solid color) brush that approximates\n \/\/ the background. The caller will use this when drawing\n \/\/ the native control as a background color, particularly\n \/\/ for radiobuttons and XP style pushbuttons.\n LRESULT OnCtlColor(UINT msg, HDC dc, HWND control) {\n const View *ancestor = parent_;\n while (ancestor) {\n const Background *background = ancestor->background();\n if (background) {\n HBRUSH brush = background->GetNativeControlBrush();\n if (brush)\n return reinterpret_cast<LRESULT>(brush);\n }\n ancestor = ancestor->GetParent();\n }\n\n \/\/ COLOR_BTNFACE is the default for dialog box backgrounds.\n return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_BTNFACE));\n }\n\n LRESULT OnCtlColorBtn(HDC dc, HWND control) {\n return OnCtlColor(WM_CTLCOLORBTN, dc, control);\n }\n\n LRESULT OnCtlColorStatic(HDC dc, HWND control) {\n return OnCtlColor(WM_CTLCOLORSTATIC, dc, control);\n }\n\n NativeControl* parent_;\n HWND control_;\n DISALLOW_COPY_AND_ASSIGN(NativeControlContainer);\n};\n\nNativeControl::NativeControl() : hwnd_view_(NULL),\n container_(NULL),\n fixed_width_(-1),\n horizontal_alignment_(CENTER),\n fixed_height_(-1),\n vertical_alignment_(CENTER) {\n enabled_ = true;\n focusable_ = true;\n}\n\nNativeControl::~NativeControl() {\n if (container_) {\n container_->ResetParent();\n ::DestroyWindow(*container_);\n }\n}\n\nvoid NativeControl::ValidateNativeControl() {\n if (hwnd_view_ == NULL) {\n hwnd_view_ = new NativeViewHost;\n AddChildView(hwnd_view_);\n }\n\n if (!container_ && IsVisible()) {\n container_ = new NativeControlContainer(this);\n hwnd_view_->Attach(*container_);\n if (!enabled_)\n EnableWindow(GetNativeControlHWND(), enabled_);\n\n \/\/ This message ensures that the focus border is shown.\n ::SendMessage(container_->GetControl(),\n WM_CHANGEUISTATE,\n MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),\n 0);\n }\n}\n\nvoid NativeControl::ViewHierarchyChanged(bool is_add, View *parent,\n View *child) {\n if (is_add && parent != this && !container_ && GetWidget()) {\n ValidateNativeControl();\n Layout();\n }\n}\n\nvoid NativeControl::Layout() {\n if (!container_ && GetWidget())\n ValidateNativeControl();\n\n if (hwnd_view_) {\n gfx::Rect lb = GetLocalBounds(false);\n\n int x = lb.x();\n int y = lb.y();\n int width = lb.width();\n int height = lb.height();\n if (fixed_width_ > 0) {\n width = std::min(fixed_width_, width);\n switch (horizontal_alignment_) {\n case LEADING:\n \/\/ Nothing to do.\n break;\n case CENTER:\n x += (lb.width() - width) \/ 2;\n break;\n case TRAILING:\n x = x + lb.width() - width;\n break;\n default:\n NOTREACHED();\n }\n }\n\n if (fixed_height_ > 0) {\n height = std::min(fixed_height_, height);\n switch (vertical_alignment_) {\n case LEADING:\n \/\/ Nothing to do.\n break;\n case CENTER:\n y += (lb.height() - height) \/ 2;\n break;\n case TRAILING:\n y = y + lb.height() - height;\n break;\n default:\n NOTREACHED();\n }\n }\n\n hwnd_view_->SetBounds(x, y, width, height);\n }\n}\n\nvoid NativeControl::OnContextMenu(const POINT& location) {\n if (!GetContextMenuController())\n return;\n\n if (location.x == -1 && location.y == -1)\n ShowContextMenu(GetKeyboardContextMenuLocation(), false);\n else\n ShowContextMenu(gfx::Point(location), true);\n}\n\nvoid NativeControl::Focus() {\n if (container_) {\n DCHECK(container_->GetControl());\n ::SetFocus(container_->GetControl());\n NotifyAccessibilityEvent(AccessibilityTypes::EVENT_FOCUS, false);\n }\n}\n\nHWND NativeControl::GetNativeControlHWND() {\n if (container_)\n return container_->GetControl();\n else\n return NULL;\n}\n\nvoid NativeControl::NativeControlDestroyed() {\n if (hwnd_view_)\n hwnd_view_->Detach();\n container_ = NULL;\n}\n\nvoid NativeControl::SetVisible(bool f) {\n if (f != IsVisible()) {\n View::SetVisible(f);\n if (!f && container_) {\n ::DestroyWindow(*container_);\n } else if (f && !container_) {\n ValidateNativeControl();\n }\n }\n}\n\nvoid NativeControl::SetEnabled(bool enabled) {\n if (enabled_ != enabled) {\n View::SetEnabled(enabled);\n if (GetNativeControlHWND()) {\n EnableWindow(GetNativeControlHWND(), enabled_);\n }\n }\n}\n\nvoid NativeControl::Paint(gfx::Canvas* canvas) {\n}\n\nvoid NativeControl::VisibilityChanged(View* starting_from, bool is_visible) {\n SetVisible(is_visible);\n}\n\nvoid NativeControl::SetFixedWidth(int width, Alignment alignment) {\n DCHECK_GT(width, 0);\n fixed_width_ = width;\n horizontal_alignment_ = alignment;\n}\n\nvoid NativeControl::SetFixedHeight(int height, Alignment alignment) {\n DCHECK_GT(height, 0);\n fixed_height_ = height;\n vertical_alignment_ = alignment;\n}\n\nDWORD NativeControl::GetAdditionalExStyle() const {\n \/\/ If the UI for the view is mirrored, we should make sure we add the\n \/\/ extended window style for a right-to-left layout so the subclass creates\n \/\/ a mirrored HWND for the underlying control.\n DWORD ex_style = 0;\n if (base::i18n::IsRTL())\n ex_style |= l10n_util::GetExtendedStyles();\n\n return ex_style;\n}\n\nDWORD NativeControl::GetAdditionalRTLStyle() const {\n \/\/ If the UI for the view is mirrored, we should make sure we add the\n \/\/ extended window style for a right-to-left layout so the subclass creates\n \/\/ a mirrored HWND for the underlying control.\n DWORD ex_style = 0;\n if (base::i18n::IsRTL())\n ex_style |= l10n_util::GetExtendedTooltipStyles();\n\n return ex_style;\n}\n\n\/\/ static\nLRESULT CALLBACK NativeControl::NativeControlWndProc(HWND window, UINT message,\n WPARAM w_param,\n LPARAM l_param) {\n HANDLE original_handler = GetProp(window, kHandlerKey);\n DCHECK(original_handler);\n NativeControl* native_control =\n static_cast<NativeControl*>(GetProp(window, kNativeControlKey));\n DCHECK(native_control);\n\n if (message == WM_KEYDOWN &&\n native_control->OnKeyDown(app::KeyboardCodeForWindowsKeyCode(w_param))) {\n return 0;\n } else if (message == WM_SETFOCUS) {\n \/\/ Let the focus manager know that the focus changed.\n FocusManager* focus_manager = native_control->GetFocusManager();\n if (focus_manager) {\n focus_manager->SetFocusedView(native_control);\n } else {\n NOTREACHED();\n }\n } else if (message == WM_DESTROY) {\n win_util::SetWindowProc(window,\n reinterpret_cast<WNDPROC>(original_handler));\n RemoveProp(window, kHandlerKey);\n RemoveProp(window, kNativeControlKey);\n }\n\n return CallWindowProc(reinterpret_cast<WNDPROC>(original_handler), window,\n message, w_param, l_param);\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2014 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENCE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_TUPLE_CAST_HPP\n#define CAF_TUPLE_CAST_HPP\n\n#include <type_traits>\n\n#include \"caf\/optional.hpp\"\n#include \"caf\/cow_tuple.hpp\"\n\n#include \"caf\/detail\/matches.hpp\"\n#include \"caf\/detail\/type_list.hpp\"\n\nnamespace caf {\n\ntemplate <class... T>\noptional<typename detail::tl_apply<\n typename detail::tl_filter_not<detail::type_list<T...>, is_anything>::type,\n cow_tuple\n>::type>\ntuple_cast(message) {\n return none; \/\/TODO: implement me\n}\n\n} \/\/ namespace caf\n\n#endif \/\/ CAF_TUPLE_CAST_HPP\n<commit_msg>Remove obsolete file<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include \"Grid.hpp\"\n#include <algorithm>\n\nnamespace jakway_antf\n{\n\n\/**\n * the square is a stable shape in the game of life\n * it should never change regardless of how many generations we run\n *\/\nTEST(GenerationTests, testSquare)\n{\n const POS_TYPE width=4, height=4;\n Grid grid(width, height);\n\n ASSERT_TRUE(grid.getSize() == (width * height));\n\n \/**\n * XXX--TODO:\n * check that the grid has 4 live tiles with a 1-cell dead tile buffer around them\n * grid.runGeneration will expand the grid since touchingEdges() is true\n * also change the name of GameRunner.runGeneration because 2 classes with different methods with the same name is confusing\n *\/\n auto checkGrid = [&grid]() {\n \/\/check the top and bottom edges are dead--we expanded the graph\n for(POS_TYPE x = 0; x < width + 1; x++)\n {\n ASSERT_TRUE(grid.getTile(x, 0) == TILE_DEAD);\n ASSERT_TRUE(grid.getTile(x, height + 1) == TILE_DEAD);\n }\n\n \/\/check the left and right edges are dead\n for(POS_TYPE y = 0; y < height + 1; y++)\n {\n ASSERT_TRUE(grid.getTile(y, 0) == TILE_DEAD);\n ASSERT_TRUE(grid.getTile(y, width + 1) == TILE_DEAD);\n }\n\n \/\/the middle of the graph is the square--it should be alive\n ASSERT_TRUE(grid.getTile(1, 1) == TILE_ALIVE);\n ASSERT_TRUE(grid.getTile(2, 1) == TILE_ALIVE);\n ASSERT_TRUE(grid.getTile(1, 2) == TILE_ALIVE);\n ASSERT_TRUE(grid.getTile(2, 2) == TILE_ALIVE);\n };\n\n \/\/set all tiles to alive\n std::for_each(grid.begin(), grid.end(), [](bool& tile) { tile = TILE_ALIVE; });\n\n \/\/check the grid is OK\n std::for_each(grid.begin(), grid.end(), [](bool& tile) { ASSERT_TRUE(tile == TILE_ALIVE); });\n ASSERT_TRUE(grid.getSize() == (width * height));\n\n \/\/after running the first generation the grid will be expanded--this requires a new checking function\n \/\/run generations and assert nothing has changed\n const unsigned int numGenerations = 100;\n for(unsigned int i = 0; i < numGenerations ; i++)\n {\n \/\/after each generation, check the size is still correct and all the tiles are the same\n grid.runGeneration();\n checkGrid();\n ASSERT_TRUE(grid.getSize() == ((width+2) * (height+2)));\n }\n}\n\n}\n<commit_msg>moved tests out of the jakway_antf namespace<commit_after>#include \"gtest\/gtest.h\"\n#include \"Grid.hpp\"\n#include <algorithm>\n\nusing namespace jakway_antf;\n\n\/**\n * the square is a stable shape in the game of life\n * it should never change regardless of how many generations we run\n *\/\nTEST(GenerationTests, testSquare)\n{\n const POS_TYPE width=4, height=4;\n Grid grid(width, height);\n\n ASSERT_TRUE(grid.getSize() == (width * height));\n\n \/**\n * XXX--TODO:\n * check that the grid has 4 live tiles with a 1-cell dead tile buffer around them\n * grid.runGeneration will expand the grid since touchingEdges() is true\n * also change the name of GameRunner.runGeneration because 2 classes with different methods with the same name is confusing\n *\/\n auto checkGrid = [&grid]() {\n \/\/check the top and bottom edges are dead--we expanded the graph\n for(POS_TYPE x = 0; x < width + 1; x++)\n {\n ASSERT_TRUE(grid.getTile(x, 0) == TILE_DEAD);\n ASSERT_TRUE(grid.getTile(x, height + 1) == TILE_DEAD);\n }\n\n \/\/check the left and right edges are dead\n for(POS_TYPE y = 0; y < height + 1; y++)\n {\n ASSERT_TRUE(grid.getTile(y, 0) == TILE_DEAD);\n ASSERT_TRUE(grid.getTile(y, width + 1) == TILE_DEAD);\n }\n\n \/\/the middle of the graph is the square--it should be alive\n ASSERT_TRUE(grid.getTile(1, 1) == TILE_ALIVE);\n ASSERT_TRUE(grid.getTile(2, 1) == TILE_ALIVE);\n ASSERT_TRUE(grid.getTile(1, 2) == TILE_ALIVE);\n ASSERT_TRUE(grid.getTile(2, 2) == TILE_ALIVE);\n };\n\n \/\/set all tiles to alive\n std::for_each(grid.begin(), grid.end(), [](bool& tile) { tile = TILE_ALIVE; });\n\n \/\/check the grid is OK\n std::for_each(grid.begin(), grid.end(), [](bool& tile) { ASSERT_TRUE(tile == TILE_ALIVE); });\n ASSERT_TRUE(grid.getSize() == (width * height));\n\n \/\/after running the first generation the grid will be expanded--this requires a new checking function\n \/\/run generations and assert nothing has changed\n const unsigned int numGenerations = 100;\n for(unsigned int i = 0; i < numGenerations ; i++)\n {\n \/\/after each generation, check the size is still correct and all the tiles are the same\n grid.runGeneration();\n checkGrid();\n ASSERT_TRUE(grid.getSize() == ((width+2) * (height+2)));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2015 mogemimi.\n\/\/ Distributed under the MIT license. See LICENSE.md file for details.\n\n#ifndef POMDOG_EFFECTPASSGL4_5C5F046F_HPP\n#define POMDOG_EFFECTPASSGL4_5C5F046F_HPP\n\n#include \"OpenGLPrerequisites.hpp\"\n#include \"BlendStateGL4.hpp\"\n#include \"DepthStencilStateGL4.hpp\"\n#include \"RasterizerStateGL4.hpp\"\n#include \"TypesafeGL4.hpp\"\n#include \"..\/RenderSystem\/NativeEffectPass.hpp\"\n#include \"Pomdog\/Graphics\/detail\/ForwardDeclarations.hpp\"\n#include \"Pomdog\/Utility\/Optional.hpp\"\n#include <cstdint>\n#include <vector>\n\nnamespace Pomdog {\nnamespace Detail {\nnamespace RenderSystem {\nnamespace GL4 {\n\nclass InputLayoutGL4;\n\nstruct TextureBindingGL4 {\n GLint UniformLocation;\n std::uint16_t SlotIndex;\n};\n\nstruct UniformBlockBindingGL4 {\n std::string Name;\n std::uint16_t SlotIndex;\n};\n\nclass EffectPassGL4 final: public NativeEffectPass {\npublic:\n EffectPassGL4() = delete;\n\n explicit EffectPassGL4(EffectPassDescription const& description);\n\n ~EffectPassGL4();\n\n std::unique_ptr<NativeConstantLayout> CreateConstantLayout() override;\n\n void ApplyShaders();\n\n ShaderProgramGL4 GetShaderProgram() const;\n\n InputLayoutGL4* GetInputLayout() const;\n\nprivate:\n std::vector<TextureBindingGL4> textureBindings;\n std::vector<UniformBlockBindingGL4> uniformBlockBindings;\n Optional<ShaderProgramGL4> shaderProgram;\n std::unique_ptr<InputLayoutGL4> inputLayout;\n BlendStateGL4 blendState;\n RasterizerStateGL4 rasterizerState;\n DepthStencilStateGL4 depthStencilState;\n};\n\n}\/\/ namespace GL4\n}\/\/ namespace RenderSystem\n}\/\/ namespace Detail\n}\/\/ namespace Pomdog\n\n#endif \/\/ POMDOG_EFFECTPASSGL4_5C5F046F_HPP\n<commit_msg>Minor refactor<commit_after>\/\/ Copyright (c) 2013-2015 mogemimi.\n\/\/ Distributed under the MIT license. See LICENSE.md file for details.\n\n#ifndef POMDOG_EFFECTPASSGL4_5C5F046F_HPP\n#define POMDOG_EFFECTPASSGL4_5C5F046F_HPP\n\n#include \"OpenGLPrerequisites.hpp\"\n#include \"BlendStateGL4.hpp\"\n#include \"DepthStencilStateGL4.hpp\"\n#include \"RasterizerStateGL4.hpp\"\n#include \"TypesafeGL4.hpp\"\n#include \"..\/RenderSystem\/NativeEffectPass.hpp\"\n#include \"Pomdog\/Graphics\/detail\/ForwardDeclarations.hpp\"\n#include \"Pomdog\/Utility\/Optional.hpp\"\n#include <cstdint>\n#include <vector>\n\nnamespace Pomdog {\nnamespace Detail {\nnamespace RenderSystem {\nnamespace GL4 {\n\nclass InputLayoutGL4;\n\nstruct TextureBindingGL4 {\n GLint UniformLocation;\n std::uint16_t SlotIndex;\n};\n\nstruct UniformBlockBindingGL4 {\n std::string Name;\n std::uint16_t SlotIndex;\n};\n\nclass EffectPassGL4 final: public NativeEffectPass {\npublic:\n EffectPassGL4() = delete;\n\n explicit EffectPassGL4(EffectPassDescription const& description);\n\n ~EffectPassGL4();\n\n std::unique_ptr<NativeConstantLayout> CreateConstantLayout() override;\n\n void ApplyShaders();\n\n ShaderProgramGL4 GetShaderProgram() const;\n\n InputLayoutGL4* GetInputLayout() const;\n\nprivate:\n std::vector<TextureBindingGL4> textureBindings;\n std::vector<UniformBlockBindingGL4> uniformBlockBindings;\n BlendStateGL4 blendState;\n RasterizerStateGL4 rasterizerState;\n DepthStencilStateGL4 depthStencilState;\n Optional<ShaderProgramGL4> shaderProgram;\n std::unique_ptr<InputLayoutGL4> inputLayout;\n};\n\n}\/\/ namespace GL4\n}\/\/ namespace RenderSystem\n}\/\/ namespace Detail\n}\/\/ namespace Pomdog\n\n#endif \/\/ POMDOG_EFFECTPASSGL4_5C5F046F_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017-present Facebook, Inc.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n#include <thrift\/compiler\/common.h>\n#include <thrift\/compiler\/parse\/parsing_driver.h>\n\n#include <boost\/filesystem.hpp>\n\nnamespace apache {\nnamespace thrift {\nnamespace compiler {\n\n\/**\n * Current compilation stage. One of: arguments, parse, generation\n *\/\nstd::string g_stage;\n\n\/**\n * Directory containing template files\n *\/\nstd::string g_template_dir;\n\n\/**\n * Should C++ include statements use path prefixes for other thrift-generated\n * header files\n *\/\nbool g_cpp_use_include_prefix = false;\n\n\/**\n * Global debug state\n *\/\nint g_debug = 0;\n\n\/**\n * Warning level\n *\/\nint g_warn = 1;\n\n\/**\n * Verbose output\n *\/\nint g_verbose = 0;\n\n\/**\n * The last parsed doctext comment.\n *\/\nchar* g_doctext;\n\n\/**\n * The location of the last parsed doctext comment.\n *\/\nint g_doctext_lineno;\n\nstd::string compute_absolute_path(const std::string& path) {\n boost::filesystem::path abspath{path};\n try {\n abspath = boost::filesystem::canonical(abspath);\n return abspath.string();\n } catch (const boost::filesystem::filesystem_error& e) {\n failure(\"Could not find file: %s. Error: %s\", path.c_str(), e.what());\n }\n}\n\nvoid pdebug(const char* fmt, ...) {\n if (g_debug == 0) {\n return;\n }\n va_list args;\n printf(\"[PARSE] \");\n va_start(args, fmt);\n vprintf(fmt, args);\n va_end(args);\n printf(\"\\n\");\n}\n\nvoid pverbose(const char* fmt, ...) {\n if (g_verbose == 0) {\n return;\n }\n va_list args;\n va_start(args, fmt);\n vprintf(fmt, args);\n va_end(args);\n}\n\nvoid pwarning(int level, const char* fmt, ...) {\n if (g_warn < level) {\n return;\n }\n va_list args;\n fprintf(stderr, \"[WARNING:%s] \", g_stage.c_str());\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n va_end(args);\n fprintf(stderr, \"\\n\");\n}\n\n[[noreturn]] void failure(const char* fmt, ...) {\n va_list args;\n fprintf(stderr, \"[FAILURE:%s] \", g_stage.c_str());\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n va_end(args);\n fprintf(stderr, \"\\n\");\n exit(1);\n}\n\nvoid dump_docstrings(t_program* program) {\n std::string progdoc = program->get_doc();\n if (!progdoc.empty()) {\n printf(\"Whole program doc:\\n%s\\n\", progdoc.c_str());\n }\n const std::vector<t_typedef*>& typedefs = program->get_typedefs();\n std::vector<t_typedef*>::const_iterator t_iter;\n for (t_iter = typedefs.begin(); t_iter != typedefs.end(); ++t_iter) {\n t_typedef* td = *t_iter;\n if (td->has_doc()) {\n printf(\n \"typedef %s:\\n%s\\n\", td->get_name().c_str(), td->get_doc().c_str());\n }\n }\n const std::vector<t_enum*>& enums = program->get_enums();\n std::vector<t_enum*>::const_iterator e_iter;\n for (e_iter = enums.begin(); e_iter != enums.end(); ++e_iter) {\n t_enum* en = *e_iter;\n if (en->has_doc()) {\n printf(\"enum %s:\\n%s\\n\", en->get_name().c_str(), en->get_doc().c_str());\n }\n }\n const std::vector<t_const*>& consts = program->get_consts();\n std::vector<t_const*>::const_iterator c_iter;\n for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {\n t_const* co = *c_iter;\n if (co->has_doc()) {\n printf(\"const %s:\\n%s\\n\", co->get_name().c_str(), co->get_doc().c_str());\n }\n }\n const std::vector<t_struct*>& structs = program->get_structs();\n std::vector<t_struct*>::const_iterator s_iter;\n for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {\n t_struct* st = *s_iter;\n if (st->has_doc()) {\n printf(\"struct %s:\\n%s\\n\", st->get_name().c_str(), st->get_doc().c_str());\n }\n }\n const std::vector<t_struct*>& xceptions = program->get_xceptions();\n std::vector<t_struct*>::const_iterator x_iter;\n for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {\n t_struct* xn = *x_iter;\n if (xn->has_doc()) {\n printf(\n \"xception %s:\\n%s\\n\", xn->get_name().c_str(), xn->get_doc().c_str());\n }\n }\n const std::vector<t_service*>& services = program->get_services();\n std::vector<t_service*>::const_iterator v_iter;\n for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {\n t_service* sv = *v_iter;\n if (sv->has_doc()) {\n printf(\n \"service %s:\\n%s\\n\", sv->get_name().c_str(), sv->get_doc().c_str());\n }\n }\n}\n\n\/**\n * Parse with the given parameters, and dump all the diagnostic messages\n * returned.\n *\n * If the parsing fails, this function will exit(1).\n *\/\nstd::unique_ptr<t_program_bundle> parse_and_dump_diagnostics(\n std::string path,\n apache::thrift::parsing_params params) {\n apache::thrift::parsing_driver driver{path, std::move(params)};\n\n std::vector<apache::thrift::diagnostic_message> diagnostic_messages;\n auto program = driver.parse(diagnostic_messages);\n\n for (auto const& message : diagnostic_messages) {\n switch (message.level) {\n case apache::thrift::diagnostic_level::YY_ERROR:\n fprintf(\n stderr,\n \"[ERROR:%s:%d] (last token was '%s')\\n%s\\n\",\n message.filename.c_str(),\n message.lineno,\n message.last_token.c_str(),\n message.message.c_str());\n break;\n case apache::thrift::diagnostic_level::WARNING:\n fprintf(\n stderr,\n \"[WARNING:%s:%d] %s\\n\",\n message.filename.c_str(),\n message.lineno,\n message.message.c_str());\n break;\n case apache::thrift::diagnostic_level::VERBOSE:\n fprintf(stderr, \"%s\", message.message.c_str());\n break;\n case apache::thrift::diagnostic_level::DEBUG:\n fprintf(\n stderr, \"[PARSE:%d] %s\\n\", message.lineno, message.message.c_str());\n break;\n case apache::thrift::diagnostic_level::FAILURE:\n fprintf(\n stderr,\n \"[FAILURE:%s:%d] %s\\n\",\n message.filename.c_str(),\n message.lineno,\n message.message.c_str());\n break;\n }\n }\n\n if (!program) {\n exit(1);\n }\n\n return program;\n}\n\nvoid mark_file_executable(std::string const& path) {\n namespace fs = boost::filesystem;\n fs::permissions(\n path, fs::add_perms | fs::owner_exe | fs::group_exe | fs::others_exe);\n}\n\n} \/\/ namespace compiler\n} \/\/ namespace thrift\n} \/\/ namespace apache\n<commit_msg>Fix issue of getting absolute path on Windows<commit_after>\/*\n * Copyright 2017-present Facebook, Inc.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n#include <thrift\/compiler\/common.h>\n#include <thrift\/compiler\/parse\/parsing_driver.h>\n\n#include <boost\/filesystem.hpp>\n\nnamespace apache {\nnamespace thrift {\nnamespace compiler {\n\n\/**\n * Current compilation stage. One of: arguments, parse, generation\n *\/\nstd::string g_stage;\n\n\/**\n * Directory containing template files\n *\/\nstd::string g_template_dir;\n\n\/**\n * Should C++ include statements use path prefixes for other thrift-generated\n * header files\n *\/\nbool g_cpp_use_include_prefix = false;\n\n\/**\n * Global debug state\n *\/\nint g_debug = 0;\n\n\/**\n * Warning level\n *\/\nint g_warn = 1;\n\n\/**\n * Verbose output\n *\/\nint g_verbose = 0;\n\n\/**\n * The last parsed doctext comment.\n *\/\nchar* g_doctext;\n\n\/**\n * The location of the last parsed doctext comment.\n *\/\nint g_doctext_lineno;\n\nstd::string compute_absolute_path(const std::string& path) {\n boost::filesystem::path abspath{path};\n try {\n abspath = boost::filesystem::absolute(abspath);\n return abspath.string();\n } catch (const boost::filesystem::filesystem_error& e) {\n failure(\"Could not find file: %s. Error: %s\", path.c_str(), e.what());\n }\n}\n\nvoid pdebug(const char* fmt, ...) {\n if (g_debug == 0) {\n return;\n }\n va_list args;\n printf(\"[PARSE] \");\n va_start(args, fmt);\n vprintf(fmt, args);\n va_end(args);\n printf(\"\\n\");\n}\n\nvoid pverbose(const char* fmt, ...) {\n if (g_verbose == 0) {\n return;\n }\n va_list args;\n va_start(args, fmt);\n vprintf(fmt, args);\n va_end(args);\n}\n\nvoid pwarning(int level, const char* fmt, ...) {\n if (g_warn < level) {\n return;\n }\n va_list args;\n fprintf(stderr, \"[WARNING:%s] \", g_stage.c_str());\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n va_end(args);\n fprintf(stderr, \"\\n\");\n}\n\n[[noreturn]] void failure(const char* fmt, ...) {\n va_list args;\n fprintf(stderr, \"[FAILURE:%s] \", g_stage.c_str());\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n va_end(args);\n fprintf(stderr, \"\\n\");\n exit(1);\n}\n\nvoid dump_docstrings(t_program* program) {\n std::string progdoc = program->get_doc();\n if (!progdoc.empty()) {\n printf(\"Whole program doc:\\n%s\\n\", progdoc.c_str());\n }\n const std::vector<t_typedef*>& typedefs = program->get_typedefs();\n std::vector<t_typedef*>::const_iterator t_iter;\n for (t_iter = typedefs.begin(); t_iter != typedefs.end(); ++t_iter) {\n t_typedef* td = *t_iter;\n if (td->has_doc()) {\n printf(\n \"typedef %s:\\n%s\\n\", td->get_name().c_str(), td->get_doc().c_str());\n }\n }\n const std::vector<t_enum*>& enums = program->get_enums();\n std::vector<t_enum*>::const_iterator e_iter;\n for (e_iter = enums.begin(); e_iter != enums.end(); ++e_iter) {\n t_enum* en = *e_iter;\n if (en->has_doc()) {\n printf(\"enum %s:\\n%s\\n\", en->get_name().c_str(), en->get_doc().c_str());\n }\n }\n const std::vector<t_const*>& consts = program->get_consts();\n std::vector<t_const*>::const_iterator c_iter;\n for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {\n t_const* co = *c_iter;\n if (co->has_doc()) {\n printf(\"const %s:\\n%s\\n\", co->get_name().c_str(), co->get_doc().c_str());\n }\n }\n const std::vector<t_struct*>& structs = program->get_structs();\n std::vector<t_struct*>::const_iterator s_iter;\n for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {\n t_struct* st = *s_iter;\n if (st->has_doc()) {\n printf(\"struct %s:\\n%s\\n\", st->get_name().c_str(), st->get_doc().c_str());\n }\n }\n const std::vector<t_struct*>& xceptions = program->get_xceptions();\n std::vector<t_struct*>::const_iterator x_iter;\n for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {\n t_struct* xn = *x_iter;\n if (xn->has_doc()) {\n printf(\n \"xception %s:\\n%s\\n\", xn->get_name().c_str(), xn->get_doc().c_str());\n }\n }\n const std::vector<t_service*>& services = program->get_services();\n std::vector<t_service*>::const_iterator v_iter;\n for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {\n t_service* sv = *v_iter;\n if (sv->has_doc()) {\n printf(\n \"service %s:\\n%s\\n\", sv->get_name().c_str(), sv->get_doc().c_str());\n }\n }\n}\n\n\/**\n * Parse with the given parameters, and dump all the diagnostic messages\n * returned.\n *\n * If the parsing fails, this function will exit(1).\n *\/\nstd::unique_ptr<t_program_bundle> parse_and_dump_diagnostics(\n std::string path,\n apache::thrift::parsing_params params) {\n apache::thrift::parsing_driver driver{path, std::move(params)};\n\n std::vector<apache::thrift::diagnostic_message> diagnostic_messages;\n auto program = driver.parse(diagnostic_messages);\n\n for (auto const& message : diagnostic_messages) {\n switch (message.level) {\n case apache::thrift::diagnostic_level::YY_ERROR:\n fprintf(\n stderr,\n \"[ERROR:%s:%d] (last token was '%s')\\n%s\\n\",\n message.filename.c_str(),\n message.lineno,\n message.last_token.c_str(),\n message.message.c_str());\n break;\n case apache::thrift::diagnostic_level::WARNING:\n fprintf(\n stderr,\n \"[WARNING:%s:%d] %s\\n\",\n message.filename.c_str(),\n message.lineno,\n message.message.c_str());\n break;\n case apache::thrift::diagnostic_level::VERBOSE:\n fprintf(stderr, \"%s\", message.message.c_str());\n break;\n case apache::thrift::diagnostic_level::DEBUG:\n fprintf(\n stderr, \"[PARSE:%d] %s\\n\", message.lineno, message.message.c_str());\n break;\n case apache::thrift::diagnostic_level::FAILURE:\n fprintf(\n stderr,\n \"[FAILURE:%s:%d] %s\\n\",\n message.filename.c_str(),\n message.lineno,\n message.message.c_str());\n break;\n }\n }\n\n if (!program) {\n exit(1);\n }\n\n return program;\n}\n\nvoid mark_file_executable(std::string const& path) {\n namespace fs = boost::filesystem;\n fs::permissions(\n path, fs::add_perms | fs::owner_exe | fs::group_exe | fs::others_exe);\n}\n\n} \/\/ namespace compiler\n} \/\/ namespace thrift\n} \/\/ namespace apache\n<|endoftext|>"} {"text":"<commit_before>#include<stdlib.h>\n#include<opencv2\/opencv.hpp>\n#include<opencv2\/highgui\/highgui.hpp>\n#include<time.h>\n#pragma comment(lib,\"opencv_world320.lib\")\n\nstatic const int N = 256;\/\/文字列の長さ\nint main(void) {\n\t\/\/TODO 関数の分割\n\tchar full_command[N];\n\tchar front_command[] = \"sudo raspistill -o \";\/\/command\n\tchar full_path[N];\n\tchar directry_path[] = \"\/home\/pi\/object\";\/\/pathの先頭\n\tchar name_path[N];\/\/時間を文字列に変換するときに代入する変数\n\tchar file_extention[] = \".jpg\";\/\/拡張子\n\ttime_t timer;\/\/時刻を受け取る変数\n\tstruct tm *timeptr;\/\/日時を集めた構造体ポインタ\n\ttime(&timer);\/\/現在時刻の取得\n\ttimeptr = localtime(&timer);\/\/ポインタ\n\tstrftime(name_path, N, \"%Y%m%d-%H%M%S\", timeptr);\/\/日時を文字列に変換してsに代入\n\tsprintf(full_path, \"%s%s%s\",directry_path, name_path, file_extention);\n\tsprintf(full_command, \"%s%s\", front_command, full_path);\/\/コマンドの文字列をつなげる。\n\tsystem(full_command);\/\/raspistillで静止画を撮って日時を含むファイル名で保存。\n\n\tcv::Mat src,dst,dst_filtered;\n\tdst_filtered = cv::Scalar(0, 0, 0);\/\/画像の初期化\n\tdouble count = 0; \/\/赤色を認識したピクセルの数\n\tdouble percentage = 0; \/\/割合\n\tsrc =cv::imread(full_path);\n\tcv::cvtColor(src, dst, CV_BGR2HSV);\/\/入力画像(src)をhsv色空間(dst)に変換\n\t\/\/inRange(入力画像,下界画像,上界画像,出力画像)\n\t\/\/「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)\n\tcv::inRange(dst, cv::Scalar(160, 150, 0), cv::Scalar(190, 255, 255), dst_filtered);\n\tcount = cv::countNonZero(dst_filtered);\/\/赤色部分の面積を計算\n\tdouble Area = dst.rows*dst.cols;\/\/全ピクセル数の計算\n\tpercentage = (count \/ Area)*100;\/\/百分率で計算\n\tprintf(\"赤色の面積の割合は%f\\n\", percentage);\n}\n<commit_msg>関数の分割<commit_after>#include<stdlib.h>\n#include<opencv2\/opencv.hpp>\n#include<opencv2\/highgui\/highgui.hpp>\n#include<time.h>\n#pragma comment(lib,\"opencv_world320.lib\")\n\nstatic const int N = 256;\/\/文字列の長さ\n\n\/\/写真をとってそのpathを返す\nchar* takePhoto(void)\n{\n\tchar full_command[N];\n\tchar front_command[] = \"sudo raspistill -o \";\/\/command\n\tchar full_path[N];\n\tchar directry_path[] = \"\/home\/pi\/object\";\/\/pathの先頭\n\tchar name_path[N];\/\/時間を文字列に変換するときに代入する変数\n\tchar file_extention[] = \".jpg\";\/\/拡張子\n\ttime_t timer;\/\/時刻を受け取る変数\n\tstruct tm *timeptr;\/\/日時を集めた構造体ポインタ\n\ttime(&timer);\/\/現在時刻の取得\n\ttimeptr = localtime(&timer);\/\/ポインタ\n\tstrftime(name_path, N, \"%Y%m%d-%H%M%S\", timeptr);\/\/日時を文字列に変換してsに代入\n\tsprintf(full_path, \"%s%s%s\",directry_path, name_path, file_extention);\n\tsprintf(full_command, \"%s%s\", front_command, full_path);\/\/コマンドの文字列をつなげる。\n\tsystem(full_command);\/\/raspistillで静止画を撮って日時を含むファイル名で保存。\n\treturn full_path;\n}\n\nint main(void) {\n\tcv::Mat src,hsv,hsv_filtered;\/\n\thsv_filtered = cv::Scalar(0, 0, 0);\/\/画像の初期化\n\tdouble count = 0; \/\/赤色を認識したピクセルの数\n\tdouble percentage = 0; \/\/割合\n\tsrc =cv::imread(takePhoto());\n\tcv::cvtColor(src, hsv, CV_BGR2HSV);\/\/入力画像(src)をhsv色空間(hsv)に変換\n\t\/\/inRange(入力画像,下界画像,上界画像,出力画像)\n\t\/\/「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)\n\tcv::inRange(hsv, cv::Scalar(160, 150, 0), cv::Scalar(190, 255, 255), hsv_filtered);\n\tcount = cv::countNonZero(hsv_filtered);\/\/赤色部分の面積を計算\n\tdouble Area = hsv.rows*hsv.cols;\/\/全ピクセル数の計算\n\tpercentage = (count \/ Area)*100;\/\/百分率で計算\n\tprintf(\"赤色の面積の割合は%f\\n\", percentage);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2005 by Andrei Alexandrescu\n\/\/ Permission to use, copy, modify, distribute, and sell this software for any\n\/\/ purpose is hereby granted without fee, provided that the above copyright\n\/\/ notice appear in all copies and that both that copyright notice and this\n\/\/ permission notice appear in supporting documentation.\n\/\/ The author makes no representations about the suitability of this software \n\/\/ for any purpose. It is provided \"as is\" without express or implied \n\/\/ warranty.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"loki\/SafeFormat.h\"\n#include <iostream>\n#include <cassert>\n#include <utility>\n\nusing namespace std;\n\ntemplate <class Integral1, class Integral2>\nIntegral2 RandomInt(Integral1 low, Integral2 up)\n{\n \/\/ From ``Accelerated C++'', page 135:\n \/\/ random integer in the range [0, n)\n \/\/ We adjust to generate in the range [0, n]\n const Integral2 \n low2 = low,\n n = up - low;\n \n assert(n > 0);\n\n const unsigned int bucket_size = RAND_MAX \/ n;\n assert(bucket_size > 0);\n \n Integral2 r;\n do r = Integral2(rand() \/ bucket_size);\n while (r > n);\n\n r += low2; \n assert(r >= low2 && r <= up);\n return r;\n}\n\nstring RandomString(unsigned int maxSize)\n{\n string result(RandomInt(0, maxSize), '\\0');\n unsigned int i = 0;\n for (; i != result.size(); ++i) {\n result[i] = RandomInt('a', 'z');\n }\n return result;\n}\n\ntemplate <class T>\nvoid TestCase(const string& fmt, T value) {\n char buf[4096];\n std::string s;\n const int i1 = SPrintf(s, fmt.c_str())(value); \n#ifdef _MSC_VER \n const int i2 = _snprintf(buf, sizeof(buf), fmt.c_str(), value); \n#else\n const int i2 = snprintf(buf, sizeof(buf), fmt.c_str(), value); \n#endif\n \n if (i1 != i2 || s != buf) \n {\n cout << endl\n << \"Reference: \" << i2 << \"; Actual: \" << i1 << \", Difference = \" << i2-i1 << endl\n << \"V: [\" << value << \"]\" << endl\n << \"F: [\" << fmt << \"]\" << endl\n << \"R: [\" << buf << \"]\" << endl\n << \"A: [\" << s.c_str() << \"]\" << endl;\n assert(false); \n }\n}\n\ntemplate <class T, class U>\nvoid TestCase2(const string& fmt, T value, U value2) {\n char buf[4096];\n std::string s;\n const int i1 = SPrintf(s, fmt.c_str())(value)(value2); \n const int i2 = snprintf(buf, sizeof(buf), fmt.c_str(), value, value2); \n assert(i1 == i2); \n assert(s == buf); \n}\n\nint main(int argc, char** argv) {\n if (argc == 3) {\n \/\/ test speed\n int i = atoi(argv[2]);\n switch (argv[1][0]) {\n case 'p':\n for (; i > 0; --i) {\n printf(\"Hey, %u frobnicators and %u twiddlicators\\n\",\n i, i);\n }\n break;\n case 's':\n for (; i > 0; --i) {\n cout << \"Hey, \" << i << \" frobnicators and \" << i << \n \" twiddlicators\\n\";\n }\n break;\n case 'n':\n for (; i > 0; --i) {\n Printf(\"Hey, %u frobnicators and %u twiddlicators\\n\")\n (i)(i);\n }\n break;\n }\n return 0;\n }\n \n \/\/srand(time(0));\n srand(0);\n for (unsigned i = 0; ; ++i) {\n printf(\"%u\\r\", i);\n \n \/\/ Generate a random string for the head\n string lead = RandomString(100);\n \/\/ This string will hold a random format specification\n string formatSpec(lead + \"|%\");\n \/\/ Generate a random set of flags\n static const string flags(\"-+0 #\");\n unsigned int maxFlags = RandomInt(0u, flags.length() - 1);\n for (unsigned int i = 0; i != maxFlags; ++i) {\n formatSpec += flags[RandomInt(0u, flags.length() - 1)];\n }\n \/\/ Generate an optional random width\n if (RandomInt(0, 1)) {\n const unsigned int width = RandomInt(0, 100);\n char buf[4];\n sprintf(buf, \"%u\", width);\n formatSpec += buf;\n }\n \/\/ Generate an optional random precision\n if (RandomInt(0, 1)) {\n const unsigned int prec = RandomInt(0, 100);\n char buf[4];\n sprintf(buf, \"%u\", prec);\n formatSpec += '.';\n formatSpec += buf;\n }\n \/\/ Generate a random type character\n static const string type(\"cdeEfgGinopsuxX\");\n const char typeSpec = type[RandomInt(0, type.size() - 1)];\n \/\/ Generate an optional type prefix\n static const string prefix(\"hl\");\n if (typeSpec != 's' && RandomInt(0, 1)) {\n formatSpec += prefix[RandomInt(0, prefix.size() - 1)];\n }\n formatSpec += typeSpec;\n formatSpec += '|';\n formatSpec += RandomString(100);\n \n switch (typeSpec) {\n case 'c': \n TestCase(formatSpec, RandomInt(1, 127));\n break;\n case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': \n TestCase(formatSpec, RandomInt(-10000, 10000));\n break;\n case 'e': case 'E': case 'f': case 'g': case 'G': \n TestCase(formatSpec, \n RandomInt(-10000, 10000) \/ double(RandomInt(1, 100)));\n break;\n case 'n': \n break;\n case 'p': \n {\n void * p = malloc(RandomInt(1, 1000));\n TestCase(formatSpec, p);\n free(p);\n }\n break;\n case 's': \n TestCase(formatSpec, RandomString(100).c_str());\n break;\n default:\n assert(false);\n break; \n }\n }\n}\n<commit_msg>astyle --style=ansi<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2005 by Andrei Alexandrescu\n\/\/ Permission to use, copy, modify, distribute, and sell this software for any\n\/\/ purpose is hereby granted without fee, provided that the above copyright\n\/\/ notice appear in all copies and that both that copyright notice and this\n\/\/ permission notice appear in supporting documentation.\n\/\/ The author makes no representations about the suitability of this software\n\/\/ for any purpose. It is provided \"as is\" without express or implied\n\/\/ warranty.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"loki\/SafeFormat.h\"\n#include <iostream>\n#include <cassert>\n#include <utility>\n\nusing namespace std;\n\ntemplate <class Integral1, class Integral2>\nIntegral2 RandomInt(Integral1 low, Integral2 up)\n{\n \/\/ From ``Accelerated C++'', page 135:\n \/\/ random integer in the range [0, n)\n \/\/ We adjust to generate in the range [0, n]\n const Integral2\n low2 = low,\n n = up - low;\n\n assert(n > 0);\n\n const unsigned int bucket_size = RAND_MAX \/ n;\n assert(bucket_size > 0);\n\n Integral2 r;\n do\n r = Integral2(rand() \/ bucket_size);\n while (r > n);\n\n r += low2;\n assert(r >= low2 && r <= up);\n return r;\n}\n\nstring RandomString(unsigned int maxSize)\n{\n string result(RandomInt(0, maxSize), '\\0');\n unsigned int i = 0;\n for (; i != result.size(); ++i)\n {\n result[i] = RandomInt('a', 'z');\n }\n return result;\n}\n\ntemplate <class T>\nvoid TestCase(const string& fmt, T value)\n{\n char buf[4096];\n std::string s;\n const int i1 = SPrintf(s, fmt.c_str())(value);\n \n#ifdef _MSC_VER\n const int i2 = _snprintf(buf, sizeof(buf), fmt.c_str(), value);\n#else\n const int i2 = snprintf(buf, sizeof(buf), fmt.c_str(), value);\n#endif\n\n if (i1 != i2 || s != buf)\n {\n cout << endl\n << \"Reference: \" << i2 << \"; Actual: \" << i1 << \", Difference = \" << i2-i1 << endl\n << \"V: [\" << value << \"]\" << endl\n << \"F: [\" << fmt << \"]\" << endl\n << \"R: [\" << buf << \"]\" << endl\n << \"A: [\" << s.c_str() << \"]\" << endl;\n assert(false);\n }\n}\n\ntemplate <class T, class U>\nvoid TestCase2(const string& fmt, T value, U value2)\n{\n char buf[4096];\n std::string s;\n const int i1 = SPrintf(s, fmt.c_str())(value)(value2);\n const int i2 = snprintf(buf, sizeof(buf), fmt.c_str(), value, value2);\n assert(i1 == i2);\n assert(s == buf);\n}\n\nint main(int argc, char** argv)\n{\n if (argc == 3)\n {\n \/\/ test speed\n int i = atoi(argv[2]);\n switch (argv[1][0])\n {\n case 'p':\n for (; i > 0; --i)\n {\n printf(\"Hey, %u frobnicators and %u twiddlicators\\n\",\n i, i);\n }\n break;\n case 's':\n for (; i > 0; --i)\n {\n cout << \"Hey, \" << i << \" frobnicators and \" << i <<\n \" twiddlicators\\n\";\n }\n break;\n case 'n':\n for (; i > 0; --i)\n {\n Printf(\"Hey, %u frobnicators and %u twiddlicators\\n\")\n (i)(i);\n }\n break;\n }\n return 0;\n }\n\n \/\/srand(time(0));\n srand(0);\n for (unsigned i = 0; ; ++i)\n {\n printf(\"%u\\r\", i);\n\n \/\/ Generate a random string for the head\n string lead = RandomString(100);\n \/\/ This string will hold a random format specification\n string formatSpec(lead + \"|%\");\n \/\/ Generate a random set of flags\n static const string flags(\"-+0 #\");\n unsigned int maxFlags = RandomInt(0u, flags.length() - 1);\n for (unsigned int i = 0; i != maxFlags; ++i)\n {\n formatSpec += flags[RandomInt(0u, flags.length() - 1)];\n }\n \/\/ Generate an optional random width\n if (RandomInt(0, 1))\n {\n const unsigned int width = RandomInt(0, 100);\n char buf[4];\n sprintf(buf, \"%u\", width);\n formatSpec += buf;\n }\n \/\/ Generate an optional random precision\n if (RandomInt(0, 1))\n {\n const unsigned int prec = RandomInt(0, 100);\n char buf[4];\n sprintf(buf, \"%u\", prec);\n formatSpec += '.';\n formatSpec += buf;\n }\n \/\/ Generate a random type character\n static const string type(\"cdeEfgGinopsuxX\");\n const char typeSpec = type[RandomInt(0, type.size() - 1)];\n \/\/ Generate an optional type prefix\n static const string prefix(\"hl\");\n if (typeSpec != 's' && RandomInt(0, 1))\n {\n formatSpec += prefix[RandomInt(0, prefix.size() - 1)];\n }\n formatSpec += typeSpec;\n formatSpec += '|';\n formatSpec += RandomString(100);\n\n switch (typeSpec)\n {\n case 'c':\n TestCase(formatSpec, RandomInt(1, 127));\n break;\n case 'd':\n case 'i':\n case 'o':\n case 'u':\n case 'x':\n case 'X':\n TestCase(formatSpec, RandomInt(-10000, 10000));\n break;\n case 'e':\n case 'E':\n case 'f':\n case 'g':\n case 'G':\n TestCase(formatSpec,\n RandomInt(-10000, 10000) \/ double(RandomInt(1, 100)));\n break;\n case 'n':\n break;\n case 'p':\n {\n void * p = malloc(RandomInt(1, 1000));\n TestCase(formatSpec, p);\n free(p);\n }\n break;\n case 's':\n TestCase(formatSpec, RandomString(100).c_str());\n break;\n default:\n assert(false);\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>more fixes to PassTArgByValueType; cleanup redundant obsolete sharedptr copies; and related Container cleanups<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"..\/lib\/catch.hpp\"\n\nextern \"C\"\n{\n#include \"..\/inc\/AvlTree.h\"\n}\n\n\/\/ TODO: test avl tree<commit_msg>Added unit test for AvlTree.<commit_after>#include \"..\/lib\/catch.hpp\"\n\nextern \"C\"\n{\n#include \"..\/inc\/AvlTree.h\"\n}\n\nint compare(const void *a, const void *b)\n{\n\treturn (int)a - (int)b;\n}\n\nTEST_CASE(\"avl tree contains, delete, insert, is empty\", \"[inc\/AvlTree.h\/avlContains, inc\/AvlTree.h\/avlDelete, inc\/AvlTree.h\/avlInsert, inc\/AvlTree.h\/avlIsEmpty]\")\n{\n\tstruct AvlTree tree;\n\n\tavlReset(&tree, &compare);\n\tREQUIRE(avlIsEmpty(&tree));\n\n\tfor (int i = 0; i < 10; i++)\n\t\tREQUIRE(avlInsert(&tree, (void*)i));\n\n\tfor (int i = 0; i < 10; i++)\n\t\tREQUIRE(avlContains(&tree, (void*)i));\n\n\tREQUIRE_FALSE(avlIsEmpty(&tree));\n\tREQUIRE_FALSE(avlInsert(&tree, (void*)2));\n\tREQUIRE_FALSE(avlContains(&tree, (void*)-1));\n\tREQUIRE_FALSE(avlDelete(&tree, (void*)-2));\n\n\tfor (int i = 0; i < 10; i++)\n\t\tREQUIRE(avlDelete(&tree, (void*)i));\n\n\tREQUIRE(avlIsEmpty(&tree));\n\n\tfor (int i = 0; i > -10; i--)\n\t\tavlInsert(&tree, (void*)i);\n\n\tavlReset(&tree, NULL);\n\tREQUIRE(avlIsEmpty(&tree));\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.2.224); FILE MERGED 2005\/09\/05 17:05:37 rt 1.2.224.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>"} {"text":"<commit_before>\/** \\file extract_keywords_for_translation.cc\n * \\brief A tool for extracting keywords that need to be translated. The keywords and any possibly pre-existing\n * translations will be stored in a SQL database.\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2016, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (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. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"DbRow.h\"\n#include \"DirectoryEntry.h\"\n#include \"IniFile.h\"\n#include \"Leader.h\"\n#include \"MarcUtil.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"TranslationUtil.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << progname << \" inferior_title_input superior_title_input norm_data_input\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nstatic std::unordered_set<std::string> *shared_norm_data_control_numbers;\n\n\nbool RecordKeywordControlNumbers(MarcUtil::Record * const record, XmlWriter * const \/*xml_writer*\/,\n\t\t\t\t std::string * const \/* err_msg *\/)\n{\n std::vector<std::string> keyword_tags;\n StringUtil::Split(\"600:610:611:630:650:653:656\", ':', &keyword_tags);\n const std::vector<std::string> &fields(record->getFields());\n const std::vector<DirectoryEntry> &dir_entries(record->getDirEntries());\n for (const auto &keyword_tag : keyword_tags) {\n\tconst ssize_t start_index(record->getFieldIndex(keyword_tag));\n\tif (start_index == -1)\n\t continue;\n\n for (size_t index(start_index); index < dir_entries.size() and dir_entries[index].getTag() == keyword_tag; ++index) {\n const Subfields subfields(fields[index]);\n const auto begin_end(subfields.getIterators('0'));\n for (auto subfield0(begin_end.first); subfield0 != begin_end.second; ++subfield0) {\n if (not StringUtil::StartsWith(subfield0->second, \"(DE-576)\"))\n continue;\n\n const std::string topic_id(subfield0->second.substr(8));\n\t\tshared_norm_data_control_numbers->insert(topic_id);\n }\n }\n }\n\n return true;\n}\n\n\nvoid ExtractKeywordNormdataControlNumbers(File * const marc_input,\n\t\t\t\t\t std::unordered_set<std::string> * const norm_data_control_numbers)\n{\n const size_t orig_size(norm_data_control_numbers->size());\n\n shared_norm_data_control_numbers = norm_data_control_numbers;\n std::string err_msg;\n if (not MarcUtil::ProcessRecords(marc_input, RecordKeywordControlNumbers, nullptr, &err_msg))\n\tError(\"error while extracting keyword control numbers for \\\"\" + marc_input->getPath() + \"\\\": \" + err_msg);\n\n std::cerr << \"Found \" << (norm_data_control_numbers->size() - orig_size) << \" new keyword control numbers in \"\n\t << marc_input->getPath() << '\\n';\n}\n\n\nstatic unsigned keyword_count, translation_count;\nstatic DbConnection *shared_connection;\n\n\nbool ExtractTranslations(MarcUtil::Record * const record, XmlWriter * const \/*xml_writer*\/, std::string * const \/* err_msg *\/) {\n const std::vector<std::string> &fields(record->getFields());\n if (shared_norm_data_control_numbers->find(fields[0]) == shared_norm_data_control_numbers->cend())\n\treturn true; \/\/ Not one of the records w\/ a keyword used in our title data.\n\n const ssize_t _150_index(record->getFieldIndex(\"150\"));\n if (_150_index == -1)\n\treturn true;\n const Subfields _150_subfields(fields[_150_index]);\n const std::string german_text(_150_subfields.getFirstSubfieldValue('a'));\n if (unlikely(german_text.empty()))\n\treturn true;\n ++keyword_count;\n \n std::vector<std::pair<std::string, std::string>> text_and_language_codes;\n text_and_language_codes.emplace_back(std::make_pair(german_text, \"deu\"));\n\n \/\/ Find translations:\n const ssize_t first_750_index(record->getFieldIndex(\"750\"));\n if (first_750_index != -1) {\n\tconst std::vector<DirectoryEntry> &dir_entries(record->getDirEntries());\n for (size_t index(first_750_index); index < dir_entries.size() and dir_entries[index].getTag() == \"750\"; ++index) {\n\t const Subfields _750_subfields(fields[index]);\n\t auto start_end(_750_subfields.getIterators('9'));\n\t if (start_end.first == start_end.second)\n\t\tcontinue;\n\t std::string language_code, association;\n\t for (auto code_and_value(start_end.first); code_and_value != start_end.second; ++code_and_value) {\n\t\tif (StringUtil::StartsWith(code_and_value->second, \"L:\"))\n\t\t language_code = code_and_value->second.substr(2);\n\t\telse if (StringUtil::StartsWith(code_and_value->second, \"Z:\"))\n\t\t association = code_and_value->second.substr(2);\n\t }\n\t if (not language_code.empty()) {\n\t\t++translation_count;\n\t\ttext_and_language_codes.emplace_back(std::make_pair(_750_subfields.getFirstSubfieldValue('a'), language_code));\n\t }\n }\n }\n\n \/\/ Update the database.\n const std::string id(TranslationUtil::GetId(shared_connection, german_text));\n for (const auto &text_and_language_code : text_and_language_codes) {\n\tconst std::string REPLACE_STMT(\"REPLACE INTO translations SET id=\" + id + \", language_code=\\\"\"\n\t\t\t\t + text_and_language_code.second + \"\\\", category=\\\"keywords\\\", preexists=TRUE, \\\", text=\\\"\"\n\t\t\t\t + shared_connection->escapeString(text_and_language_code.first) + \"\\\"\");\n\tif (not shared_connection->query(REPLACE_STMT))\n\t Error(\"Insert failed: \" + REPLACE_STMT + \" (\" + shared_connection->getLastErrorMessage() + \")\");\n }\n\n return true;\n}\n\n\nvoid ExtractTranslationTerms(File * const norm_data_input, DbConnection * const connection) {\n shared_connection = connection;\n\n std::string err_msg;\n if (not MarcUtil::ProcessRecords(norm_data_input, ExtractTranslations, nullptr, &err_msg))\n\tError(\"error while extracting translations from \\\"\" + norm_data_input->getPath() + \"\\\": \" + err_msg);\n\n std::cerr << \"Added \" << keyword_count << \" to the translation database.\\n\";\n std::cerr << \"Found \" << translation_count << \" translations in the norm data.\\n\";\n}\n\n\t\t\t \nconst std::string CONF_FILE_PATH(\"\/var\/lib\/tuelib\/translations.conf\");\n\n\nint main(int argc, char **argv) {\n progname = argv[0];\n\n if (argc != 4)\n Usage();\n\n const std::string inferior_marc_input_filename(argv[1]);\n File inferior_marc_input(inferior_marc_input_filename, \"rm\");\n if (not inferior_marc_input)\n Error(\"can't open \\\"\" + inferior_marc_input_filename + \"\\\" for reading!\");\n\n const std::string superior_marc_input_filename(argv[2]);\n File superior_marc_input(superior_marc_input_filename, \"rm\");\n if (not superior_marc_input)\n Error(\"can't open \\\"\" + superior_marc_input_filename + \"\\\" for reading!\");\n\n const std::string norm_data_marc_input_filename(argv[3]);\n File norm_data_marc_input(norm_data_marc_input_filename, \"rm\");\n if (not norm_data_marc_input)\n Error(\"can't open \\\"\" + norm_data_marc_input_filename + \"\\\" for reading!\");\n\n try {\n\tconst IniFile ini_file(CONF_FILE_PATH);\n\tconst std::string sql_database(ini_file.getString(\"\", \"sql_database\"));\n\tconst std::string sql_username(ini_file.getString(\"\", \"sql_username\"));\n\tconst std::string sql_password(ini_file.getString(\"\", \"sql_password\"));\n\tDbConnection db_connection(sql_database, sql_username, sql_password);\n\n\tstd::unordered_set<std::string> norm_data_control_numbers;\n\tExtractKeywordNormdataControlNumbers(&inferior_marc_input, &norm_data_control_numbers);\n\tExtractKeywordNormdataControlNumbers(&superior_marc_input, &norm_data_control_numbers);\n\tExtractTranslationTerms(&norm_data_marc_input, &db_connection);\n } catch (const std::exception &x) {\n\tError(\"caught exception: \" + std::string(x.what()));\n }\n}\n<commit_msg>More bad SQL.<commit_after>\/** \\file extract_keywords_for_translation.cc\n * \\brief A tool for extracting keywords that need to be translated. The keywords and any possibly pre-existing\n * translations will be stored in a SQL database.\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2016, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (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. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"DbRow.h\"\n#include \"DirectoryEntry.h\"\n#include \"IniFile.h\"\n#include \"Leader.h\"\n#include \"MarcUtil.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"TranslationUtil.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << progname << \" inferior_title_input superior_title_input norm_data_input\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nstatic std::unordered_set<std::string> *shared_norm_data_control_numbers;\n\n\nbool RecordKeywordControlNumbers(MarcUtil::Record * const record, XmlWriter * const \/*xml_writer*\/,\n\t\t\t\t std::string * const \/* err_msg *\/)\n{\n std::vector<std::string> keyword_tags;\n StringUtil::Split(\"600:610:611:630:650:653:656\", ':', &keyword_tags);\n const std::vector<std::string> &fields(record->getFields());\n const std::vector<DirectoryEntry> &dir_entries(record->getDirEntries());\n for (const auto &keyword_tag : keyword_tags) {\n\tconst ssize_t start_index(record->getFieldIndex(keyword_tag));\n\tif (start_index == -1)\n\t continue;\n\n for (size_t index(start_index); index < dir_entries.size() and dir_entries[index].getTag() == keyword_tag; ++index) {\n const Subfields subfields(fields[index]);\n const auto begin_end(subfields.getIterators('0'));\n for (auto subfield0(begin_end.first); subfield0 != begin_end.second; ++subfield0) {\n if (not StringUtil::StartsWith(subfield0->second, \"(DE-576)\"))\n continue;\n\n const std::string topic_id(subfield0->second.substr(8));\n\t\tshared_norm_data_control_numbers->insert(topic_id);\n }\n }\n }\n\n return true;\n}\n\n\nvoid ExtractKeywordNormdataControlNumbers(File * const marc_input,\n\t\t\t\t\t std::unordered_set<std::string> * const norm_data_control_numbers)\n{\n const size_t orig_size(norm_data_control_numbers->size());\n\n shared_norm_data_control_numbers = norm_data_control_numbers;\n std::string err_msg;\n if (not MarcUtil::ProcessRecords(marc_input, RecordKeywordControlNumbers, nullptr, &err_msg))\n\tError(\"error while extracting keyword control numbers for \\\"\" + marc_input->getPath() + \"\\\": \" + err_msg);\n\n std::cerr << \"Found \" << (norm_data_control_numbers->size() - orig_size) << \" new keyword control numbers in \"\n\t << marc_input->getPath() << '\\n';\n}\n\n\nstatic unsigned keyword_count, translation_count;\nstatic DbConnection *shared_connection;\n\n\nbool ExtractTranslations(MarcUtil::Record * const record, XmlWriter * const \/*xml_writer*\/, std::string * const \/* err_msg *\/) {\n const std::vector<std::string> &fields(record->getFields());\n if (shared_norm_data_control_numbers->find(fields[0]) == shared_norm_data_control_numbers->cend())\n\treturn true; \/\/ Not one of the records w\/ a keyword used in our title data.\n\n const ssize_t _150_index(record->getFieldIndex(\"150\"));\n if (_150_index == -1)\n\treturn true;\n const Subfields _150_subfields(fields[_150_index]);\n const std::string german_text(_150_subfields.getFirstSubfieldValue('a'));\n if (unlikely(german_text.empty()))\n\treturn true;\n ++keyword_count;\n \n std::vector<std::pair<std::string, std::string>> text_and_language_codes;\n text_and_language_codes.emplace_back(std::make_pair(german_text, \"deu\"));\n\n \/\/ Find translations:\n const ssize_t first_750_index(record->getFieldIndex(\"750\"));\n if (first_750_index != -1) {\n\tconst std::vector<DirectoryEntry> &dir_entries(record->getDirEntries());\n for (size_t index(first_750_index); index < dir_entries.size() and dir_entries[index].getTag() == \"750\"; ++index) {\n\t const Subfields _750_subfields(fields[index]);\n\t auto start_end(_750_subfields.getIterators('9'));\n\t if (start_end.first == start_end.second)\n\t\tcontinue;\n\t std::string language_code, association;\n\t for (auto code_and_value(start_end.first); code_and_value != start_end.second; ++code_and_value) {\n\t\tif (StringUtil::StartsWith(code_and_value->second, \"L:\"))\n\t\t language_code = code_and_value->second.substr(2);\n\t\telse if (StringUtil::StartsWith(code_and_value->second, \"Z:\"))\n\t\t association = code_and_value->second.substr(2);\n\t }\n\t if (not language_code.empty()) {\n\t\t++translation_count;\n\t\ttext_and_language_codes.emplace_back(std::make_pair(_750_subfields.getFirstSubfieldValue('a'), language_code));\n\t }\n }\n }\n\n \/\/ Update the database.\n const std::string id(TranslationUtil::GetId(shared_connection, german_text));\n for (const auto &text_and_language_code : text_and_language_codes) {\n\tconst std::string REPLACE_STMT(\"REPLACE INTO translations SET id=\" + id + \", language_code=\\\"\"\n\t\t\t\t + text_and_language_code.second + \"\\\", category=\\\"keywords\\\", preexists=TRUE, text=\\\"\"\n\t\t\t\t + shared_connection->escapeString(text_and_language_code.first) + \"\\\"\");\n\tif (not shared_connection->query(REPLACE_STMT))\n\t Error(\"Insert failed: \" + REPLACE_STMT + \" (\" + shared_connection->getLastErrorMessage() + \")\");\n }\n\n return true;\n}\n\n\nvoid ExtractTranslationTerms(File * const norm_data_input, DbConnection * const connection) {\n shared_connection = connection;\n\n std::string err_msg;\n if (not MarcUtil::ProcessRecords(norm_data_input, ExtractTranslations, nullptr, &err_msg))\n\tError(\"error while extracting translations from \\\"\" + norm_data_input->getPath() + \"\\\": \" + err_msg);\n\n std::cerr << \"Added \" << keyword_count << \" to the translation database.\\n\";\n std::cerr << \"Found \" << translation_count << \" translations in the norm data.\\n\";\n}\n\n\t\t\t \nconst std::string CONF_FILE_PATH(\"\/var\/lib\/tuelib\/translations.conf\");\n\n\nint main(int argc, char **argv) {\n progname = argv[0];\n\n if (argc != 4)\n Usage();\n\n const std::string inferior_marc_input_filename(argv[1]);\n File inferior_marc_input(inferior_marc_input_filename, \"rm\");\n if (not inferior_marc_input)\n Error(\"can't open \\\"\" + inferior_marc_input_filename + \"\\\" for reading!\");\n\n const std::string superior_marc_input_filename(argv[2]);\n File superior_marc_input(superior_marc_input_filename, \"rm\");\n if (not superior_marc_input)\n Error(\"can't open \\\"\" + superior_marc_input_filename + \"\\\" for reading!\");\n\n const std::string norm_data_marc_input_filename(argv[3]);\n File norm_data_marc_input(norm_data_marc_input_filename, \"rm\");\n if (not norm_data_marc_input)\n Error(\"can't open \\\"\" + norm_data_marc_input_filename + \"\\\" for reading!\");\n\n try {\n\tconst IniFile ini_file(CONF_FILE_PATH);\n\tconst std::string sql_database(ini_file.getString(\"\", \"sql_database\"));\n\tconst std::string sql_username(ini_file.getString(\"\", \"sql_username\"));\n\tconst std::string sql_password(ini_file.getString(\"\", \"sql_password\"));\n\tDbConnection db_connection(sql_database, sql_username, sql_password);\n\n\tstd::unordered_set<std::string> norm_data_control_numbers;\n\tExtractKeywordNormdataControlNumbers(&inferior_marc_input, &norm_data_control_numbers);\n\tExtractKeywordNormdataControlNumbers(&superior_marc_input, &norm_data_control_numbers);\n\tExtractTranslationTerms(&norm_data_marc_input, &db_connection);\n } catch (const std::exception &x) {\n\tError(\"caught exception: \" + std::string(x.what()));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n * File: main.cpp\n * Author: dayler\n *\n * Created on May 4, 2015, 4:31 PM\n *\/\n\n#include <cstdlib>\n#include <iostream>\n#include <unistd.h>\n#include <time.h>\n#include <pthread.h>\n#include <sys\/time.h>\n#include <string.h>\n#include <string>\n\n#include \"Utils.hpp\"\n#include \"Runnable.hpp\"\n#include \"SimpleRunnable.hpp\"\n#include \"Thread.hpp\"\n#include \"SMutex.hpp\"\n#include \"SSynch.hpp\"\n#include \"cqueue.hpp\"\n#include \"timer.hpp\"\n\nusing namespace std;\n\n\/\/pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;\nint counter = 0;\n\n\/* For safe condition variable usage, must use a boolean predicate and *\/\n\/* a mutex with the condition. *\/\nint workToDo = 0;\n\/\/pthread_cond_t cond = PTHREAD_COND_INITIALIZER;\n\/\/pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;\n\nconst int COUNT = 5;\nint shared = 0;\n\nclass Item\n{\npublic:\n string cstr;\n \n Item(string cstr)\n {\n this->cstr = cstr;\n }\n \n virtual ~Item()\n {\n \/\/ No op\n }\n};\n\nQueue<Item>* items;\n\n#define NTHREADS 100\n#define WAIT_TIME_SECONDS 15\n\nclass SchTask : public Runnable\n{\npublic:\n SchTask(int id)\n {\n this->id = id;\n }\n \n void* run()\n {\n printf(\"Hola!!! ID:%d\\n\", id);\n return reinterpret_cast<void*>(id);\n }\nprivate:\n int id;\n};\n\nint main()\n{\n cout<<\"start...\"<<endl;\n \n Runnable* r1 = new SchTask(10);\n Timer* t1 = new Timer(\"timer-1\");\n \n t1->scheduleAt(r1, 5000);\n long rc = reinterpret_cast<long>(t1->join());\n \n cout<<\"RESP:\"<<rc<<endl;\n \n delete r1;\n delete t1;\n \n cout<<\"end..\"<<endl;\n return 0;\n}\n\n\/**\n * Producer and consumer.\n *\/\n\/\/\/\/ Produccer\n\/\/class TH1 : public Runnable\n\/\/{\n\/\/public:\n\/\/ int id;\n\/\/ \n\/\/ TH1(int id)\n\/\/ {\n\/\/ this->id = id;\n\/\/ }\n\/\/ \n\/\/ ~TH1()\n\/\/ {\n\/\/ \/\/ No op\n\/\/ }\n\/\/ \n\/\/ bool isRunning()\n\/\/ {\n\/\/ return shared < COUNT;\n\/\/ }\n\/\/ \n\/\/ void* run()\n\/\/ {\n\/\/ while (isRunning())\n\/\/ {\n\/\/ printf(\"AAAA 1\\n\");\n\/\/ string sshared = SSTR(shared);\n\/\/ printf(\"AAAA 2\\n\");\n\/\/ sleep(3);\n\/\/ printf(\"AAAA 3\\n\");\n\/\/ items->push(new Item(sshared));\n\/\/ printf(\"THID:%d Pushed %s\\n\", id, sshared.c_str());\n\/\/ shared++;\n\/\/ }\n\/\/ return reinterpret_cast<void*>(id);\n\/\/ }\n\/\/};\n\/\/\n\/\/\/\/ Consummer\n\/\/class TH2 : public Runnable\n\/\/{\n\/\/public:\n\/\/ int id;\n\/\/ \n\/\/ TH2(int id)\n\/\/ {\n\/\/ this->id = id;\n\/\/ }\n\/\/ \n\/\/ ~TH2()\n\/\/ {\n\/\/ \/\/ No op\n\/\/ }\n\/\/ \n\/\/ bool isRunning()\n\/\/ {\n\/\/ \/\/ If shred is less than MAX or items is not empty.\n\/\/ return shared < COUNT || !items->empty();\n\/\/ }\n\/\/ \n\/\/ void* run()\n\/\/ {\n\/\/ while (isRunning())\n\/\/ {\n\/\/ printf(\"BBBB\\n\");\n\/\/ sleep(1);\n\/\/ Item* val = items->waitAndPop();\n\/\/ printf(\"THID:%d q->waitAndPop() = %s\\n\", id, val->cstr.c_str());\n\/\/ delete val;\n\/\/ }\n\/\/ return reinterpret_cast<void*>(id);\n\/\/ }\n\/\/};\n\/\/\n\/\/int main()\n\/\/{\n\/\/ cout<<\"Start main...\"<<endl;\n\/\/ items = new Queue<Item>();\n\/\/ \n\/\/ printf(\"Init runnables.\\n\");\n\/\/ Runnable* r1 = new TH1(111);\n\/\/ Runnable* r2 = new TH2(222);\n\/\/ Runnable* r3 = new TH2(333);\n\/\/ \n\/\/ Thread* t1 = new Thread(r1, false);\n\/\/ Thread* t2 = new Thread(r2, false);\n\/\/ Thread* t3 = new Thread(r3, false);\n\/\/ \n\/\/ \/\/ Start thread\n\/\/ printf(\"Starting threads...\\n\");\n\/\/ t2->start(); \/\/ Consumer\n\/\/ t1->start(); \/\/ Producer\n\/\/ t3->start(); \/\/ Consumer\n\/\/ printf(\"Was started threads joining ...\\n\");\n\/\/ \n\/\/ \/\/ Joining threads\n\/\/ long res1 = reinterpret_cast<long>(t1->join()); \/\/ Producer\n\/\/ cout<<\"Result t1 = \"<<res1<<endl;\n\/\/ long res2 = reinterpret_cast<long>(t2->join()); \/\/ Consumer\n\/\/ cout<<\"Result t2 = \"<<res2<<endl;\n\/\/ long res3 = reinterpret_cast<long>(t3->join()); \/\/ Consumer\n\/\/ cout<<\"Result t2 = \"<<res3<<endl;\n\/\/ \n\/\/ \/\/ delete\n\/\/ delete r1;\n\/\/ delete r2;\n\/\/ delete r3;\n\/\/ delete t1;\n\/\/ delete t2;\n\/\/ delete t3;\n\/\/ delete items;\n\/\/ \n\/\/ cout<<\"Finish well main...\"<<endl;\n\/\/ return 0;\n\/\/}\n\n\/**\n * Threads basic\n *\/\n\/\/void* functionC(void* arg)\n\/\/{\n\/\/ CMutex m(&mutex1);\n\/\/ \/\/ pthread_mutex_lock( &mutex1 );\n\/\/ counter++;\n\/\/ printf(\"Counter value: %d\\n\",counter);\n\/\/ \/\/ pthread_mutex_unlock( &mutex1 );\n\/\/}\n\/\/\n\/\/int main()\n\/\/{\n\/\/ int rc1, rc2;\n\/\/ pthread_t thread1, thread2;\n\/\/\n\/\/ \/\/ Create independent threads each of which will execute functionC \/\n\/\/\n\/\/ if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )\n\/\/ {\n\/\/ printf(\"Thread creation failed: %d\\n\", rc1);\n\/\/ }\n\/\/\n\/\/ if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )\n\/\/ {\n\/\/ printf(\"Thread creation failed: %d\\n\", rc2);\n\/\/ }\n\/\/\n\/\/ \/\/ Wait till threads are complete before main continues. Unless we \/\n\/\/ \/\/ wait we run the risk of executing an exit which will terminate \/\n\/\/ \/\/ the process and all threads before the threads have completed. \/\n\/\/\n\/\/ pthread_join( thread1, NULL);\n\/\/ pthread_join( thread2, NULL); \n\/\/\n\/\/ exit(0);\n\/\/}\n\n\/\/int main() {\n\/\/ cout<<\"Begin main test class...\"<<endl;\n\/\/ \n\/\/ Runnable* r1 = new SimpleRunnable(1, 3);\n\/\/ Runnable* r2 = new SimpleRunnable(2, 8);\n\/\/ \n\/\/ Thread* t1 = new Thread(r1, false);\n\/\/ Thread* t2 = new Thread(r2, false);\n\/\/ \n\/\/ \/\/ Start threads\n\/\/ t1->start();\n\/\/ t2->start();\n\/\/ \n\/\/ \/\/ Join threads\n\/\/ long res1 = reinterpret_cast<long>(t1->join());\n\/\/ long res2 = reinterpret_cast<long>(t2->join());\n\/\/ \n\/\/ cout<<\"Result t1 = \"<<res1<<endl;\n\/\/ cout<<\"Result t2 = \"<<res2<<endl;\n\/\/ \n\/\/ \/\/ Delete objects\n\/\/ delete r1;\n\/\/ delete t1;\n\/\/ \n\/\/ delete r2;\n\/\/ delete t2;\n\/\/ \n\/\/ cout<<\"Finish main test class...\"<<endl;\n\/\/ return 0;\n\/\/}\n\n<commit_msg>Make example for scheduled task.<commit_after>\/* \n * File: main.cpp\n * Author: dayler\n *\n * Created on May 4, 2015, 4:31 PM\n *\/\n\n#include <cstdlib>\n#include <iostream>\n#include <unistd.h>\n#include <time.h>\n#include <pthread.h>\n#include <sys\/time.h>\n#include <string.h>\n#include <string>\n\n#include \"Utils.hpp\"\n#include \"Runnable.hpp\"\n#include \"SimpleRunnable.hpp\"\n#include \"Thread.hpp\"\n#include \"SMutex.hpp\"\n#include \"SSynch.hpp\"\n#include \"cqueue.hpp\"\n#include \"timer.hpp\"\n\nusing namespace std;\n\n\/\/pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;\nint counter = 0;\n\n\/* For safe condition variable usage, must use a boolean predicate and *\/\n\/* a mutex with the condition. *\/\nint workToDo = 0;\n\/\/pthread_cond_t cond = PTHREAD_COND_INITIALIZER;\n\/\/pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;\n\nconst int COUNT = 5;\nint shared = 0;\n\nclass Item\n{\npublic:\n string cstr;\n \n Item(string cstr)\n {\n this->cstr = cstr;\n }\n \n virtual ~Item()\n {\n \/\/ No op\n }\n};\n\nQueue<Item>* items;\n\n#define NTHREADS 100\n#define WAIT_TIME_SECONDS 15\n\nclass SchTask : public Runnable\n{\npublic:\n SchTask(int id)\n {\n this->id = id;\n }\n \n void* run()\n {\n printf(\"Hola!!! ID:%d\\n\", id);\n return reinterpret_cast<void*>(id);\n }\nprivate:\n int id;\n};\n\nint main()\n{\n cout<<\"start...\"<<endl;\n \n Runnable* r1 = new SchTask(10);\n Timer* t1 = new Timer(\"timer-1\");\n \n t1->scheduleAtFixedRate(r1, 5000, 2000);\n long rc = reinterpret_cast<long>(t1->join());\n \n cout<<\"RESP:\"<<rc<<endl;\n \n delete r1;\n delete t1;\n \n cout<<\"end..\"<<endl;\n return 0;\n}\n\n\/**\n * Producer and consumer.\n *\/\n\/\/\/\/ Produccer\n\/\/class TH1 : public Runnable\n\/\/{\n\/\/public:\n\/\/ int id;\n\/\/ \n\/\/ TH1(int id)\n\/\/ {\n\/\/ this->id = id;\n\/\/ }\n\/\/ \n\/\/ ~TH1()\n\/\/ {\n\/\/ \/\/ No op\n\/\/ }\n\/\/ \n\/\/ bool isRunning()\n\/\/ {\n\/\/ return shared < COUNT;\n\/\/ }\n\/\/ \n\/\/ void* run()\n\/\/ {\n\/\/ while (isRunning())\n\/\/ {\n\/\/ printf(\"AAAA 1\\n\");\n\/\/ string sshared = SSTR(shared);\n\/\/ printf(\"AAAA 2\\n\");\n\/\/ sleep(3);\n\/\/ printf(\"AAAA 3\\n\");\n\/\/ items->push(new Item(sshared));\n\/\/ printf(\"THID:%d Pushed %s\\n\", id, sshared.c_str());\n\/\/ shared++;\n\/\/ }\n\/\/ return reinterpret_cast<void*>(id);\n\/\/ }\n\/\/};\n\/\/\n\/\/\/\/ Consummer\n\/\/class TH2 : public Runnable\n\/\/{\n\/\/public:\n\/\/ int id;\n\/\/ \n\/\/ TH2(int id)\n\/\/ {\n\/\/ this->id = id;\n\/\/ }\n\/\/ \n\/\/ ~TH2()\n\/\/ {\n\/\/ \/\/ No op\n\/\/ }\n\/\/ \n\/\/ bool isRunning()\n\/\/ {\n\/\/ \/\/ If shred is less than MAX or items is not empty.\n\/\/ return shared < COUNT || !items->empty();\n\/\/ }\n\/\/ \n\/\/ void* run()\n\/\/ {\n\/\/ while (isRunning())\n\/\/ {\n\/\/ printf(\"BBBB\\n\");\n\/\/ sleep(1);\n\/\/ Item* val = items->waitAndPop();\n\/\/ printf(\"THID:%d q->waitAndPop() = %s\\n\", id, val->cstr.c_str());\n\/\/ delete val;\n\/\/ }\n\/\/ return reinterpret_cast<void*>(id);\n\/\/ }\n\/\/};\n\/\/\n\/\/int main()\n\/\/{\n\/\/ cout<<\"Start main...\"<<endl;\n\/\/ items = new Queue<Item>();\n\/\/ \n\/\/ printf(\"Init runnables.\\n\");\n\/\/ Runnable* r1 = new TH1(111);\n\/\/ Runnable* r2 = new TH2(222);\n\/\/ Runnable* r3 = new TH2(333);\n\/\/ \n\/\/ Thread* t1 = new Thread(r1, false);\n\/\/ Thread* t2 = new Thread(r2, false);\n\/\/ Thread* t3 = new Thread(r3, false);\n\/\/ \n\/\/ \/\/ Start thread\n\/\/ printf(\"Starting threads...\\n\");\n\/\/ t2->start(); \/\/ Consumer\n\/\/ t1->start(); \/\/ Producer\n\/\/ t3->start(); \/\/ Consumer\n\/\/ printf(\"Was started threads joining ...\\n\");\n\/\/ \n\/\/ \/\/ Joining threads\n\/\/ long res1 = reinterpret_cast<long>(t1->join()); \/\/ Producer\n\/\/ cout<<\"Result t1 = \"<<res1<<endl;\n\/\/ long res2 = reinterpret_cast<long>(t2->join()); \/\/ Consumer\n\/\/ cout<<\"Result t2 = \"<<res2<<endl;\n\/\/ long res3 = reinterpret_cast<long>(t3->join()); \/\/ Consumer\n\/\/ cout<<\"Result t2 = \"<<res3<<endl;\n\/\/ \n\/\/ \/\/ delete\n\/\/ delete r1;\n\/\/ delete r2;\n\/\/ delete r3;\n\/\/ delete t1;\n\/\/ delete t2;\n\/\/ delete t3;\n\/\/ delete items;\n\/\/ \n\/\/ cout<<\"Finish well main...\"<<endl;\n\/\/ return 0;\n\/\/}\n\n\/**\n * Threads basic\n *\/\n\/\/void* functionC(void* arg)\n\/\/{\n\/\/ CMutex m(&mutex1);\n\/\/ \/\/ pthread_mutex_lock( &mutex1 );\n\/\/ counter++;\n\/\/ printf(\"Counter value: %d\\n\",counter);\n\/\/ \/\/ pthread_mutex_unlock( &mutex1 );\n\/\/}\n\/\/\n\/\/int main()\n\/\/{\n\/\/ int rc1, rc2;\n\/\/ pthread_t thread1, thread2;\n\/\/\n\/\/ \/\/ Create independent threads each of which will execute functionC \/\n\/\/\n\/\/ if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )\n\/\/ {\n\/\/ printf(\"Thread creation failed: %d\\n\", rc1);\n\/\/ }\n\/\/\n\/\/ if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )\n\/\/ {\n\/\/ printf(\"Thread creation failed: %d\\n\", rc2);\n\/\/ }\n\/\/\n\/\/ \/\/ Wait till threads are complete before main continues. Unless we \/\n\/\/ \/\/ wait we run the risk of executing an exit which will terminate \/\n\/\/ \/\/ the process and all threads before the threads have completed. \/\n\/\/\n\/\/ pthread_join( thread1, NULL);\n\/\/ pthread_join( thread2, NULL); \n\/\/\n\/\/ exit(0);\n\/\/}\n\n\/\/int main() {\n\/\/ cout<<\"Begin main test class...\"<<endl;\n\/\/ \n\/\/ Runnable* r1 = new SimpleRunnable(1, 3);\n\/\/ Runnable* r2 = new SimpleRunnable(2, 8);\n\/\/ \n\/\/ Thread* t1 = new Thread(r1, false);\n\/\/ Thread* t2 = new Thread(r2, false);\n\/\/ \n\/\/ \/\/ Start threads\n\/\/ t1->start();\n\/\/ t2->start();\n\/\/ \n\/\/ \/\/ Join threads\n\/\/ long res1 = reinterpret_cast<long>(t1->join());\n\/\/ long res2 = reinterpret_cast<long>(t2->join());\n\/\/ \n\/\/ cout<<\"Result t1 = \"<<res1<<endl;\n\/\/ cout<<\"Result t2 = \"<<res2<<endl;\n\/\/ \n\/\/ \/\/ Delete objects\n\/\/ delete r1;\n\/\/ delete t1;\n\/\/ \n\/\/ delete r2;\n\/\/ delete t2;\n\/\/ \n\/\/ cout<<\"Finish main test class...\"<<endl;\n\/\/ return 0;\n\/\/}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"doctest.h\"\n\n#include \"header.h\"\n\nDOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN\n#include <string>\n#include <vector>\n#include <list>\n#include <sstream>\nDOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END\n\n\/\/ the standard forbids writing in the std namespace but it works on all compilers\nnamespace std\n{\ntemplate <typename T>\nostream& operator<<(ostream& stream, const vector<T>& in) {\n stream << \"[\";\n for(size_t i = 0; i < in.size(); ++i)\n if(i < in.size() - 1)\n stream << in[i] << \", \";\n else\n stream << in[i];\n stream << \"]\";\n return stream;\n}\n}\n\n\/\/ as an alternative you may write a specialization of doctest::StringMaker\nnamespace doctest\n{\ntemplate <typename T>\nstruct StringMaker<std::list<T> >\n{\n static String convert(const std::list<T>& in) {\n std::ostringstream oss;\n\n oss << \"[\";\n for(typename std::list<T>::const_iterator it = in.begin(); it != in.end(); ++it)\n oss << *it << \", \";\n oss << \"]\";\n\n return oss.str().c_str();\n }\n};\n}\n\ntemplate <typename T, typename K>\nstruct MyType\n{\n T one;\n K two;\n};\n\ntemplate <typename T>\nstruct MyTypeInherited : MyType<T, float>\n{};\n\ntemplate <typename T, typename K>\nbool operator==(const MyType<T, K>& lhs, const MyType<T, K>& rhs) {\n return lhs.one == rhs.one && lhs.two == rhs.two;\n}\n\ntemplate <typename T, typename K>\nstd::ostream& operator<<(std::ostream& stream, const MyType<T, K>& in) {\n stream << \"[\" << in.one << \", \" << in.two << \"]\";\n return stream;\n}\n\nnamespace Bar\n{\nstruct Foo\n{\n friend bool operator==(const Foo&, const Foo&) { return false; }\n};\n\n\/\/ as a third option you may provide an overload of toString()\ninline doctest::String toString(const Foo&) { return \"Foo{}\"; }\n} \/\/ namespace Bar\n\n\/\/ set an exception translator for MyTypeInherited<int>\nREGISTER_EXCEPTION_TRANSLATOR(MyTypeInherited<int>& ex) {\n return doctest::String(\"MyTypeInherited<int>(\") + doctest::toString(ex.one) + \", \" +\n doctest::toString(ex.two) + \")\";\n}\n\nTEST_CASE(\"all asserts should fail and show how the objects get stringified\") {\n MyTypeInherited<int> bla1;\n bla1.one = 5;\n bla1.two = 4.0f;\n MyTypeInherited<int> bla2;\n bla2.one = 5;\n bla2.two = 6.0f;\n\n Bar::Foo f1;\n Bar::Foo f2;\n CHECK(f1 == f2);\n\n \/\/ std::string already has an operator<< working with std::ostream\n std::string dummy1 = \"omg\";\n std::string dummy2 = \"tralala\";\n\n CHECK(dummy1 == dummy2);\n\n std::vector<int> vec1;\n vec1.push_back(1);\n vec1.push_back(2);\n vec1.push_back(3);\n\n std::vector<int> vec2;\n vec2.push_back(1);\n vec2.push_back(2);\n vec2.push_back(4);\n\n CHECK(vec1 == vec2);\n\n std::list<int> lst_1;\n lst_1.push_back(1);\n lst_1.push_back(42);\n lst_1.push_back(3);\n\n std::list<int> lst_2;\n lst_2.push_back(1);\n lst_2.push_back(2);\n lst_2.push_back(666);\n\n CHECK(lst_1 == lst_2);\n\n \/\/ lets see if this exception gets translated\n throw_if(true, bla1);\n}\n\nstatic doctest::String intTranslator(int ex) {\n return doctest::String(\"int: \") + doctest::toString(ex);\n}\n\nTEST_CASE(\"a test case that registers an exception translator for int and then throws one\") {\n \/\/ set an exception translator for int - note that this shouldn't be done in a test case but\n \/\/ in main() or somewhere before executing the tests - but here I'm just lazy...\n doctest::registerExceptionTranslator(intTranslator);\n\n throw_if(true, 5);\n}\n<commit_msg>silencing 1 more warning for VS 2008\/2010 when using \/Wall - that a float was getting stored in memory and not in a register... relates #95<commit_after>#include \"doctest.h\"\n\n#include \"header.h\"\n\nDOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN\n#include <string>\n#include <vector>\n#include <list>\n#include <sstream>\nDOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END\n\n\/\/ the standard forbids writing in the std namespace but it works on all compilers\nnamespace std\n{\ntemplate <typename T>\nostream& operator<<(ostream& stream, const vector<T>& in) {\n stream << \"[\";\n for(size_t i = 0; i < in.size(); ++i)\n if(i < in.size() - 1)\n stream << in[i] << \", \";\n else\n stream << in[i];\n stream << \"]\";\n return stream;\n}\n}\n\n\/\/ as an alternative you may write a specialization of doctest::StringMaker\nnamespace doctest\n{\ntemplate <typename T>\nstruct StringMaker<std::list<T> >\n{\n static String convert(const std::list<T>& in) {\n std::ostringstream oss;\n\n oss << \"[\";\n for(typename std::list<T>::const_iterator it = in.begin(); it != in.end(); ++it)\n oss << *it << \", \";\n oss << \"]\";\n\n return oss.str().c_str();\n }\n};\n}\n\ntemplate <typename T, typename K>\nstruct MyType\n{\n T one;\n K two;\n};\n\ntemplate <typename T>\nstruct MyTypeInherited : MyType<T, unsigned>\n{};\n\ntemplate <typename T, typename K>\nbool operator==(const MyType<T, K>& lhs, const MyType<T, K>& rhs) {\n return lhs.one == rhs.one && lhs.two == rhs.two;\n}\n\ntemplate <typename T, typename K>\nstd::ostream& operator<<(std::ostream& stream, const MyType<T, K>& in) {\n stream << \"[\" << in.one << \", \" << in.two << \"]\";\n return stream;\n}\n\nnamespace Bar\n{\nstruct Foo\n{\n friend bool operator==(const Foo&, const Foo&) { return false; }\n};\n\n\/\/ as a third option you may provide an overload of toString()\ninline doctest::String toString(const Foo&) { return \"Foo{}\"; }\n} \/\/ namespace Bar\n\n\/\/ set an exception translator for MyTypeInherited<int>\nREGISTER_EXCEPTION_TRANSLATOR(MyTypeInherited<int>& ex) {\n return doctest::String(\"MyTypeInherited<int>(\") + doctest::toString(ex.one) + \", \" +\n doctest::toString(ex.two) + \")\";\n}\n\nTEST_CASE(\"all asserts should fail and show how the objects get stringified\") {\n MyTypeInherited<int> bla1;\n bla1.one = 5;\n bla1.two = 4u;\n MyTypeInherited<int> bla2;\n bla2.one = 5;\n bla2.two = 6u;\n\n Bar::Foo f1;\n Bar::Foo f2;\n CHECK(f1 == f2);\n\n \/\/ std::string already has an operator<< working with std::ostream\n std::string dummy1 = \"omg\";\n std::string dummy2 = \"tralala\";\n\n CHECK(dummy1 == dummy2);\n\n std::vector<int> vec1;\n vec1.push_back(1);\n vec1.push_back(2);\n vec1.push_back(3);\n\n std::vector<int> vec2;\n vec2.push_back(1);\n vec2.push_back(2);\n vec2.push_back(4);\n\n CHECK(vec1 == vec2);\n\n std::list<int> lst_1;\n lst_1.push_back(1);\n lst_1.push_back(42);\n lst_1.push_back(3);\n\n std::list<int> lst_2;\n lst_2.push_back(1);\n lst_2.push_back(2);\n lst_2.push_back(666);\n\n CHECK(lst_1 == lst_2);\n\n \/\/ lets see if this exception gets translated\n throw_if(true, bla1);\n}\n\nstatic doctest::String intTranslator(int ex) {\n return doctest::String(\"int: \") + doctest::toString(ex);\n}\n\nTEST_CASE(\"a test case that registers an exception translator for int and then throws one\") {\n \/\/ set an exception translator for int - note that this shouldn't be done in a test case but\n \/\/ in main() or somewhere before executing the tests - but here I'm just lazy...\n doctest::registerExceptionTranslator(intTranslator);\n\n throw_if(true, 5);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"reconfigurable_stateserver.h\"\n#include \"sbenv.h\"\n#include \"remote_check.h\"\n#include <vespa\/vespalib\/util\/host_name.h>\n#include <vespa\/vespalib\/util\/exceptions.h>\n#include <vespa\/vespalib\/stllike\/asciistream.h>\n#include <vespa\/fnet\/frt\/supervisor.h>\n#include <vespa\/fnet\/transport.h>\n#include <vespa\/config\/helper\/configfetcher.h>\n#include <thread>\n#include <sstream>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".slobrok.server.sbenv\");\n\nusing namespace std::chrono_literals;\n\nnamespace slobrok {\n\nnamespace {\n\nstd::string\ncreateSpec(int port)\n{\n if (port == 0) {\n return std::string();\n }\n std::ostringstream str;\n str << \"tcp\/\";\n str << vespalib::HostName::get();\n str << \":\";\n str << port;\n return str.str();\n}\n\nvoid\ndiscard(std::vector<std::string> &vec, const std::string & val)\n{\n uint32_t i = 0;\n uint32_t size = vec.size();\n while (i < size) {\n if (vec[i] == val) {\n std::swap(vec[i], vec[size - 1]);\n vec.pop_back();\n --size;\n } else {\n ++i;\n }\n }\n LOG_ASSERT(size == vec.size());\n}\n\n\nclass ConfigTask : public FNET_Task\n{\nprivate:\n Configurator& _configurator;\n\n ConfigTask(const ConfigTask &);\n ConfigTask &operator=(const ConfigTask &);\npublic:\n ConfigTask(FNET_Scheduler *sched, Configurator& configurator);\n\n ~ConfigTask();\n void PerformTask() override;\n};\n\n\nConfigTask::ConfigTask(FNET_Scheduler *sched, Configurator& configurator)\n : FNET_Task(sched),\n _configurator(configurator)\n{\n Schedule(1.0);\n}\n\n\nConfigTask::~ConfigTask()\n{\n Kill();\n}\n\n\nvoid\nConfigTask::PerformTask()\n{\n Schedule(1.0);\n LOG(spam, \"checking for new config\");\n try {\n _configurator.poll();\n } catch (std::exception &e) {\n LOG(warning, \"ConfigTask: poll failed: %s\", e.what());\n Schedule(10.0);\n }\n}\n\n} \/\/ namespace slobrok::<unnamed>\n\nSBEnv::SBEnv(const ConfigShim &shim)\n : _transport(std::make_unique<FNET_Transport>(TransportConfig().drop_empty_buffers(true))),\n _supervisor(std::make_unique<FRT_Supervisor>(_transport.get())),\n _configShim(shim),\n _configurator(shim.factory().create(*this)),\n _shuttingDown(false),\n _partnerList(),\n _me(createSpec(_configShim.portNumber())),\n _rpcHooks(*this, _rpcsrvmap, _rpcsrvmanager),\n _remotechecktask(std::make_unique<RemoteCheck>(getSupervisor()->GetScheduler(), _rpcsrvmap, _rpcsrvmanager, _exchanger)),\n _health(),\n _metrics(_rpcHooks, *_transport),\n _components(),\n _localRpcMonitorMap(*_supervisor),\n _rpcsrvmanager(*this),\n _exchanger(*this, _rpcsrvmap),\n _rpcsrvmap()\n{\n srandom(time(nullptr) ^ getpid());\n _localMonitorSubscription = MapSubscription::subscribe(_rpcsrvmap.proxy(), _localRpcMonitorMap);\n _consensusSubscription = MapSubscription::subscribe(_localRpcMonitorMap.dispatcher(), _consensusMap);\n \/\/ TODO: use consensus as source here:\n _globalHistorySubscription = MapSubscription::subscribe(_rpcsrvmap.proxy(), _globalVisibleHistory);\n _rpcHooks.initRPC(getSupervisor());\n}\n\n\nSBEnv::~SBEnv() = default;\n\nFNET_Scheduler *\nSBEnv::getScheduler() {\n return _transport->GetScheduler();\n}\n\nvoid\nSBEnv::shutdown()\n{\n _shuttingDown = true;\n getTransport()->ShutDown(false);\n}\n\nvoid\nSBEnv::resume()\n{\n \/\/ nop\n}\n\nnamespace {\n\nvespalib::string\ntoString(const std::vector<std::string> & v) {\n vespalib::asciistream os;\n os << \"[\" << '\\n';\n for (const std::string & partner : v) {\n os << \" \" << partner << '\\n';\n }\n os << ']';\n return os.str();\n}\n\n} \/\/ namespace <unnamed>\n\nint\nSBEnv::MainLoop()\n{\n if (! getSupervisor()->Listen(_configShim.portNumber())) {\n LOG(error, \"unable to listen to port %d\", _configShim.portNumber());\n EV_STOPPING(\"slobrok\", \"could not listen\");\n return 1;\n } else {\n LOG(config, \"listening on port %d\", _configShim.portNumber());\n }\n\n std::unique_ptr<ReconfigurableStateServer> stateServer;\n if (_configShim.enableStateServer()) {\n stateServer = std::make_unique<ReconfigurableStateServer>(_configShim.configId(), _health, _metrics, _components);\n }\n\n try {\n _configurator->poll();\n ConfigTask configTask(getScheduler(), *_configurator);\n LOG(debug, \"slobrok: starting main event loop\");\n EV_STARTED(\"slobrok\");\n getTransport()->Main();\n LOG(debug, \"slobrok: main event loop done\");\n } catch (vespalib::Exception &e) {\n LOG(error, \"invalid config: %s\", e.what());\n EV_STOPPING(\"slobrok\", \"invalid config\");\n return 1;\n } catch (std::exception &e) {\n LOG(error, \"Unexpected std::exception : %s\", e.what());\n EV_STOPPING(\"slobrok\", \"Unexpected std::exception\");\n return 1;\n }\n EV_STOPPING(\"slobrok\", \"clean shutdown\");\n return 0;\n}\n\n\nvoid\nSBEnv::setup(const std::vector<std::string> &cfg)\n{\n _partnerList = cfg;\n std::vector<std::string> oldList = _exchanger.getPartnerList();\n LOG(debug, \"(re-)configuring. oldlist size %d, configuration list size %d\",\n (int)oldList.size(),\n (int)cfg.size());\n for (uint32_t i = 0; i < cfg.size(); ++i) {\n std::string slobrok = cfg[i];\n discard(oldList, slobrok);\n if (slobrok != mySpec()) {\n OkState res = _rpcsrvmanager.addPeer(slobrok, slobrok.c_str());\n if (!res.ok()) {\n LOG(warning, \"could not add peer %s: %s\", slobrok.c_str(), res.errorMsg.c_str());\n } else {\n LOG(config, \"added peer %s\", slobrok.c_str());\n }\n }\n }\n for (uint32_t i = 0; i < oldList.size(); ++i) {\n OkState res = _rpcsrvmanager.removePeer(oldList[i], oldList[i].c_str());\n if (!res.ok()) {\n LOG(warning, \"could not remove peer %s: %s\", oldList[i].c_str(), res.errorMsg.c_str());\n } else {\n LOG(config, \"removed peer %s\", oldList[i].c_str());\n }\n }\n int64_t curGen = _configurator->getGeneration();\n vespalib::ComponentConfigProducer::Config current(\"slobroks\", curGen, \"ok\");\n _components.addConfig(current);\n}\n\nOkState\nSBEnv::addPeer(const std::string &name, const std::string &spec)\n{\n if (spec == mySpec()) {\n return OkState(FRTE_RPC_METHOD_FAILED, \"cannot add my own spec as peer\");\n }\n if (_partnerList.size() != 0) {\n for (const std::string & partner : _partnerList) {\n if (partner == spec) {\n return OkState(0, \"already configured with peer\");\n }\n }\n vespalib::string peers = toString(_partnerList);\n LOG(warning, \"got addPeer with non-configured peer %s, check config consistency. configured peers = %s\",\n spec.c_str(), peers.c_str());\n _partnerList.push_back(spec);\n }\n return _rpcsrvmanager.addPeer(name, spec.c_str());\n}\n\nOkState\nSBEnv::removePeer(const std::string &name, const std::string &spec)\n{\n if (spec == mySpec()) {\n return OkState(FRTE_RPC_METHOD_FAILED, \"cannot remove my own spec as peer\");\n }\n for (const std::string & partner : _partnerList) {\n if (partner == spec) {\n return OkState(FRTE_RPC_METHOD_FAILED, \"configured partner list contains peer, cannot remove\");\n }\n }\n return _rpcsrvmanager.removePeer(name, spec.c_str());\n}\n\n} \/\/ namespace slobrok\n<commit_msg>stop listening to events from the old RpcServerMap, make feedback loop instead<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"reconfigurable_stateserver.h\"\n#include \"sbenv.h\"\n#include \"remote_check.h\"\n#include <vespa\/vespalib\/util\/host_name.h>\n#include <vespa\/vespalib\/util\/exceptions.h>\n#include <vespa\/vespalib\/stllike\/asciistream.h>\n#include <vespa\/fnet\/frt\/supervisor.h>\n#include <vespa\/fnet\/transport.h>\n#include <vespa\/config\/helper\/configfetcher.h>\n#include <thread>\n#include <sstream>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".slobrok.server.sbenv\");\n\nusing namespace std::chrono_literals;\n\nnamespace slobrok {\n\nnamespace {\n\nstd::string\ncreateSpec(int port)\n{\n if (port == 0) {\n return std::string();\n }\n std::ostringstream str;\n str << \"tcp\/\";\n str << vespalib::HostName::get();\n str << \":\";\n str << port;\n return str.str();\n}\n\nvoid\ndiscard(std::vector<std::string> &vec, const std::string & val)\n{\n uint32_t i = 0;\n uint32_t size = vec.size();\n while (i < size) {\n if (vec[i] == val) {\n std::swap(vec[i], vec[size - 1]);\n vec.pop_back();\n --size;\n } else {\n ++i;\n }\n }\n LOG_ASSERT(size == vec.size());\n}\n\n\nclass ConfigTask : public FNET_Task\n{\nprivate:\n Configurator& _configurator;\n\n ConfigTask(const ConfigTask &);\n ConfigTask &operator=(const ConfigTask &);\npublic:\n ConfigTask(FNET_Scheduler *sched, Configurator& configurator);\n\n ~ConfigTask();\n void PerformTask() override;\n};\n\n\nConfigTask::ConfigTask(FNET_Scheduler *sched, Configurator& configurator)\n : FNET_Task(sched),\n _configurator(configurator)\n{\n Schedule(1.0);\n}\n\n\nConfigTask::~ConfigTask()\n{\n Kill();\n}\n\n\nvoid\nConfigTask::PerformTask()\n{\n Schedule(1.0);\n LOG(spam, \"checking for new config\");\n try {\n _configurator.poll();\n } catch (std::exception &e) {\n LOG(warning, \"ConfigTask: poll failed: %s\", e.what());\n Schedule(10.0);\n }\n}\n\n} \/\/ namespace slobrok::<unnamed>\n\nSBEnv::SBEnv(const ConfigShim &shim)\n : _transport(std::make_unique<FNET_Transport>(TransportConfig().drop_empty_buffers(true))),\n _supervisor(std::make_unique<FRT_Supervisor>(_transport.get())),\n _configShim(shim),\n _configurator(shim.factory().create(*this)),\n _shuttingDown(false),\n _partnerList(),\n _me(createSpec(_configShim.portNumber())),\n _rpcHooks(*this, _rpcsrvmap, _rpcsrvmanager),\n _remotechecktask(std::make_unique<RemoteCheck>(getSupervisor()->GetScheduler(), _rpcsrvmap, _rpcsrvmanager, _exchanger)),\n _health(),\n _metrics(_rpcHooks, *_transport),\n _components(),\n _localRpcMonitorMap(*_supervisor),\n _rpcsrvmanager(*this),\n _exchanger(*this, _rpcsrvmap),\n _rpcsrvmap()\n{\n srandom(time(nullptr) ^ getpid());\n \/\/ note: feedback loop between these two:\n _localMonitorSubscription = MapSubscription::subscribe(_consensusMap, _localRpcMonitorMap);\n _consensusSubscription = MapSubscription::subscribe(_localRpcMonitorMap.dispatcher(), _consensusMap);\n \/\/ TODO: use consensus as source here:\n _globalHistorySubscription = MapSubscription::subscribe(_rpcsrvmap.proxy(), _globalVisibleHistory);\n _rpcHooks.initRPC(getSupervisor());\n}\n\n\nSBEnv::~SBEnv() = default;\n\nFNET_Scheduler *\nSBEnv::getScheduler() {\n return _transport->GetScheduler();\n}\n\nvoid\nSBEnv::shutdown()\n{\n _shuttingDown = true;\n getTransport()->ShutDown(false);\n}\n\nvoid\nSBEnv::resume()\n{\n \/\/ nop\n}\n\nnamespace {\n\nvespalib::string\ntoString(const std::vector<std::string> & v) {\n vespalib::asciistream os;\n os << \"[\" << '\\n';\n for (const std::string & partner : v) {\n os << \" \" << partner << '\\n';\n }\n os << ']';\n return os.str();\n}\n\n} \/\/ namespace <unnamed>\n\nint\nSBEnv::MainLoop()\n{\n if (! getSupervisor()->Listen(_configShim.portNumber())) {\n LOG(error, \"unable to listen to port %d\", _configShim.portNumber());\n EV_STOPPING(\"slobrok\", \"could not listen\");\n return 1;\n } else {\n LOG(config, \"listening on port %d\", _configShim.portNumber());\n }\n\n std::unique_ptr<ReconfigurableStateServer> stateServer;\n if (_configShim.enableStateServer()) {\n stateServer = std::make_unique<ReconfigurableStateServer>(_configShim.configId(), _health, _metrics, _components);\n }\n\n try {\n _configurator->poll();\n ConfigTask configTask(getScheduler(), *_configurator);\n LOG(debug, \"slobrok: starting main event loop\");\n EV_STARTED(\"slobrok\");\n getTransport()->Main();\n LOG(debug, \"slobrok: main event loop done\");\n } catch (vespalib::Exception &e) {\n LOG(error, \"invalid config: %s\", e.what());\n EV_STOPPING(\"slobrok\", \"invalid config\");\n return 1;\n } catch (std::exception &e) {\n LOG(error, \"Unexpected std::exception : %s\", e.what());\n EV_STOPPING(\"slobrok\", \"Unexpected std::exception\");\n return 1;\n }\n EV_STOPPING(\"slobrok\", \"clean shutdown\");\n return 0;\n}\n\n\nvoid\nSBEnv::setup(const std::vector<std::string> &cfg)\n{\n _partnerList = cfg;\n std::vector<std::string> oldList = _exchanger.getPartnerList();\n LOG(debug, \"(re-)configuring. oldlist size %d, configuration list size %d\",\n (int)oldList.size(),\n (int)cfg.size());\n for (uint32_t i = 0; i < cfg.size(); ++i) {\n std::string slobrok = cfg[i];\n discard(oldList, slobrok);\n if (slobrok != mySpec()) {\n OkState res = _rpcsrvmanager.addPeer(slobrok, slobrok.c_str());\n if (!res.ok()) {\n LOG(warning, \"could not add peer %s: %s\", slobrok.c_str(), res.errorMsg.c_str());\n } else {\n LOG(config, \"added peer %s\", slobrok.c_str());\n }\n }\n }\n for (uint32_t i = 0; i < oldList.size(); ++i) {\n OkState res = _rpcsrvmanager.removePeer(oldList[i], oldList[i].c_str());\n if (!res.ok()) {\n LOG(warning, \"could not remove peer %s: %s\", oldList[i].c_str(), res.errorMsg.c_str());\n } else {\n LOG(config, \"removed peer %s\", oldList[i].c_str());\n }\n }\n int64_t curGen = _configurator->getGeneration();\n vespalib::ComponentConfigProducer::Config current(\"slobroks\", curGen, \"ok\");\n _components.addConfig(current);\n}\n\nOkState\nSBEnv::addPeer(const std::string &name, const std::string &spec)\n{\n if (spec == mySpec()) {\n return OkState(FRTE_RPC_METHOD_FAILED, \"cannot add my own spec as peer\");\n }\n if (_partnerList.size() != 0) {\n for (const std::string & partner : _partnerList) {\n if (partner == spec) {\n return OkState(0, \"already configured with peer\");\n }\n }\n vespalib::string peers = toString(_partnerList);\n LOG(warning, \"got addPeer with non-configured peer %s, check config consistency. configured peers = %s\",\n spec.c_str(), peers.c_str());\n _partnerList.push_back(spec);\n }\n return _rpcsrvmanager.addPeer(name, spec.c_str());\n}\n\nOkState\nSBEnv::removePeer(const std::string &name, const std::string &spec)\n{\n if (spec == mySpec()) {\n return OkState(FRTE_RPC_METHOD_FAILED, \"cannot remove my own spec as peer\");\n }\n for (const std::string & partner : _partnerList) {\n if (partner == spec) {\n return OkState(FRTE_RPC_METHOD_FAILED, \"configured partner list contains peer, cannot remove\");\n }\n }\n return _rpcsrvmanager.removePeer(name, spec.c_str());\n}\n\n} \/\/ namespace slobrok\n<|endoftext|>"} {"text":"<commit_before>\/* Async FRPC client.\n * The MIT License (MIT)\n * Copyright (c) 2014 Jan Cermak\n *\/\n\n\n#include \"frpcdata.h\"\n#include <frpcmarshaller.h>\n#include <frpcwriter.h>\n#include <frpcunmarshaller.h>\n#include <frpctreefeeder.h>\n#include <frpctreebuilder.h>\n#include <string.h>\n#include <cstdarg>\n\nnamespace {\n\n\nclass StringWriter: public FRPC::Writer_t {\n std::string data;\n public:\n StringWriter() {}\n virtual void write(const char *data, unsigned size) {\n this->data.append(data, size);\n }\n virtual void flush() {}\n\n const std::string &getData() const {\n return data;\n }\n};\n\n\n\/\/\/ va_list RAII.\nstruct VaListHolder {\n va_list &args;\n\n VaListHolder(va_list &args)\n : args(args)\n {}\n ~VaListHolder() {\n va_end(args);\n }\n};\n\n\n} \/\/ anon namespace \n\nnamespace frpcdata {\n\n\nstd::string dumps(const char *methodname, va_list args) {\n \/\/ TODO configurable from outside\n int useBinary = false;\n unsigned char protocolVersionMajor = 2;\n unsigned char protocolVersionMinor = 1;\n\n \/\/ create writer\n StringWriter writer;\n \/\/ create marshaller\n FRPC::Marshaller_t *marshaller = FRPC::Marshaller_t::create((useBinary\n ? FRPC::Marshaller_t::BINARY_RPC\n : FRPC::Marshaller_t::XML_RPC),\n writer, FRPC::ProtocolVersion_t(protocolVersionMajor,\n protocolVersionMinor));\n try {\n FRPC::TreeFeeder_t feeder(*marshaller);\n if (methodname) {\n marshaller->packMethodCall(methodname, strlen(methodname));\n \/\/ process value pointers varargs until nullptr.\n while (const FRPC::Value_t *value = va_arg(args, FRPC::Value_t*)) {\n feeder.feedValue(*value);\n }\n }\n\n marshaller->flush();\n } catch (const std::exception &e) {\n throw;\n }\n\n return writer.getData();\n}\n\n\nstd::string dumps(const char *methodname, ...) {\n va_list args;\n va_start(args, methodname);\n VaListHolder _args(args);\n return std::string();\n}\n\n\n\/\/\/ Read string data (xml) and return it as FRPC Value.\nFRPC::Value_t &loads(FRPC::Pool_t &pool, const std::string &data) {\n FRPC::TreeBuilder_t tree(pool);\n FRPC::UnMarshaller_t *xml = FRPC::UnMarshaller_t::create(\n FRPC::UnMarshaller_t::XML_RPC, tree);\n xml->unMarshall(data.c_str(), data.size(), FRPC::UnMarshaller_t::TYPE_METHOD_RESPONSE);\n return tree.getUnMarshaledData();\n}\n\n\n} \/\/ namespace frpcdata\n\n<commit_msg>fix incomplete dumps function (did not passed var args); unmarhsaller error returned as struct.<commit_after>\/* Async FRPC client.\n * The MIT License (MIT)\n * Copyright (c) 2014 Jan Cermak\n *\/\n\n\n#include \"frpcdata.h\"\n#include <frpcmarshaller.h>\n#include <frpcwriter.h>\n#include <frpcunmarshaller.h>\n#include <frpctreefeeder.h>\n#include <frpctreebuilder.h>\n#include <string.h>\n#include <cstdarg>\n\nnamespace {\n\n\nclass StringWriter: public FRPC::Writer_t {\n std::string data;\n public:\n StringWriter() {}\n virtual void write(const char *data, unsigned size) {\n this->data.append(data, size);\n }\n virtual void flush() {}\n\n const std::string &getData() const {\n return data;\n }\n};\n\n\n\/\/\/ va_list RAII.\nstruct VaListHolder {\n va_list &args;\n\n VaListHolder(va_list &args)\n : args(args)\n {}\n ~VaListHolder() {\n va_end(args);\n }\n};\n\n\n} \/\/ anon namespace \n\nnamespace frpcdata {\n\n\nstd::string dumps(const char *methodname, va_list args) {\n \/\/ TODO configurable from outside\n int useBinary = false;\n unsigned char protocolVersionMajor = 2;\n unsigned char protocolVersionMinor = 1;\n\n \/\/ create writer\n StringWriter writer;\n \/\/ create marshaller\n FRPC::Marshaller_t *marshaller = FRPC::Marshaller_t::create((useBinary\n ? FRPC::Marshaller_t::BINARY_RPC\n : FRPC::Marshaller_t::XML_RPC),\n writer, FRPC::ProtocolVersion_t(protocolVersionMajor,\n protocolVersionMinor));\n try {\n FRPC::TreeFeeder_t feeder(*marshaller);\n if (methodname) {\n marshaller->packMethodCall(methodname, strlen(methodname));\n \/\/ process value pointers varargs until nullptr.\n while (const FRPC::Value_t *value = va_arg(args, FRPC::Value_t*)) {\n feeder.feedValue(*value);\n }\n }\n\n marshaller->flush();\n } catch (const std::exception &e) {\n throw;\n }\n\n return writer.getData();\n}\n\n\nstd::string dumps(const char *methodname, ...) {\n va_list args;\n va_start(args, methodname);\n VaListHolder _args(args);\n return dumps(methodname, args);\n}\n\n\n\/\/\/ Read string data (xml) and return it as FRPC Value.\nFRPC::Value_t &loads(FRPC::Pool_t &pool, const std::string &data) {\n FRPC::TreeBuilder_t tree(pool);\n FRPC::UnMarshaller_t *xml = FRPC::UnMarshaller_t::create(\n FRPC::UnMarshaller_t::XML_RPC, tree);\n xml->unMarshall(data.c_str(), data.size(), FRPC::UnMarshaller_t::TYPE_METHOD_RESPONSE);\n FRPC::Value_t *res = tree.getUnMarshaledDataPtr();\n if (res == 0x0) {\n \/\/TODO exception?\n return pool.Struct(\n \"status\", pool.Int(tree.getUnMarshaledErrorNumber()),\n \"statusMessage\", pool.String(tree.getUnMarshaledErrorMessage()));\n }\n return *res;\n}\n\n\n} \/\/ namespace frpcdata\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2019 Elviss Strazdins. All rights reserved.\n\n#include <cstdlib>\n#include <system_error>\n#pragma push_macro(\"WIN32_LEAN_AND_MEAN\")\n#pragma push_macro(\"NOMINMAX\")\n#ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n#endif\n#ifndef NOMINMAX\n# define NOMINMAX\n#endif\n#include <Windows.h>\n#include <shellapi.h>\n#pragma pop_macro(\"WIN32_LEAN_AND_MEAN\")\n#pragma pop_macro(\"NOMINMAX\")\n\n#include \"EngineWin.hpp\"\n#include \"NativeWindowWin.hpp\"\n#include \"input\/windows\/InputSystemWin.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace\n {\n class ShellExecuteErrorCategory final: public std::error_category\n {\n public:\n const char* name() const noexcept final\n {\n return \"ShellExecute\";\n }\n\n std::string message(int condition) const final\n {\n switch (condition)\n {\n case 0: return \"Out of memory\";\n case ERROR_FILE_NOT_FOUND: return \"ERROR_FILE_NOT_FOUND\";\n case ERROR_PATH_NOT_FOUND: return \"ERROR_PATH_NOT_FOUND\";\n case ERROR_BAD_FORMAT: return \"ERROR_BAD_FORMAT\";\n case SE_ERR_ACCESSDENIED: return \"SE_ERR_ACCESSDENIED\";\n case SE_ERR_ASSOCINCOMPLETE: return \"SE_ERR_ASSOCINCOMPLETE\";\n case SE_ERR_DDEBUSY: return \"SE_ERR_DDEBUSY\";\n case SE_ERR_DDEFAIL: return \"SE_ERR_DDEFAIL\";\n case SE_ERR_DDETIMEOUT: return \"SE_ERR_DDETIMEOUT\";\n case SE_ERR_DLLNOTFOUND: return \"SE_ERR_DLLNOTFOUND\";\n case SE_ERR_NOASSOC: return \"SE_ERR_NOASSOC\";\n case SE_ERR_OOM: return \"SE_ERR_OOM\";\n case SE_ERR_SHARE: return \"SE_ERR_SHARE\";\n default: return \"Unknown error (\" + std::to_string(condition) + \")\";\n }\n }\n };\n\n const ShellExecuteErrorCategory shellExecuteErrorCategory {};\n }\n\n EngineWin::EngineWin(int initArgc, LPWSTR* initArgv)\n {\n if (initArgv)\n {\n int bufferSize;\n std::vector<char> buffer;\n\n for (int i = 0; i < initArgc; ++i)\n {\n bufferSize = WideCharToMultiByte(CP_UTF8, 0, initArgv[i], -1, nullptr, 0, nullptr, nullptr);\n if (bufferSize == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert wide char to UTF-8\");\n\n buffer.resize(bufferSize);\n if (WideCharToMultiByte(CP_UTF8, 0, initArgv[i], -1, buffer.data(), bufferSize, nullptr, nullptr) == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert wide char to UTF-8\");\n\n args.push_back(buffer.data());\n }\n }\n\n HRESULT hr;\n if (FAILED(hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED)))\n throw std::system_error(hr, std::system_category(), \"Failed to initialize COM\");\n\n#ifdef DEBUG\n if (!AllocConsole())\n log(Log::Level::Info) << \"Attached to console\";\n#endif\n }\n\n EngineWin::~EngineWin()\n {\n \/\/CoUninitialize();\n }\n\n static void translateMessage(HWND window, const std::set<HACCEL>& accelerators, MSG& message)\n {\n bool translate = true;\n\n for (HACCEL accelerator : accelerators)\n {\n if (TranslateAccelerator(window, accelerator, &message))\n translate = false;\n }\n\n if (translate)\n {\n TranslateMessage(&message);\n DispatchMessage(&message);\n }\n }\n\n void EngineWin::run()\n {\n init();\n start();\n\n input::InputSystemWin* inputWin = static_cast<input::InputSystemWin*>(inputManager->getInputSystem());\n NativeWindowWin* windowWin = static_cast<NativeWindowWin*>(window->getNativeWindow());\n\n MSG message;\n\n while (active)\n {\n if (!paused)\n {\n if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE))\n {\n translateMessage(windowWin->getNativeWindow(),\n windowWin->accelerators, message);\n\n if (message.message == WM_QUIT)\n {\n exit();\n break;\n }\n }\n }\n else\n {\n BOOL ret;\n if ((ret = GetMessage(&message, nullptr, 0, 0)) == -1)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get message\");\n\n if (ret == 0)\n {\n exit();\n break;\n }\n else\n {\n translateMessage(windowWin->getNativeWindow(),\n windowWin->accelerators, message);\n }\n }\n\n inputWin->update();\n }\n\n exit();\n }\n\n void EngineWin::runOnMainThread(const std::function<void()>& func)\n {\n NativeWindowWin* windowWin = static_cast<NativeWindowWin*>(window->getNativeWindow());\n\n std::unique_lock<std::mutex> lock(executeMutex);\n executeQueue.push(func);\n lock.unlock();\n\n if (!PostMessage(windowWin->getNativeWindow(), WM_USER, 0, 0))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to post message\");\n\n }\n\n void EngineWin::executeAll()\n {\n std::function<void()> func;\n\n for (;;)\n {\n std::unique_lock<std::mutex> lock(executeMutex);\n\n if (executeQueue.empty())\n break;\n\n func = std::move(executeQueue.front());\n executeQueue.pop();\n lock.unlock();\n\n if (func) func();\n }\n }\n\n void EngineWin::openURL(const std::string& url)\n {\n const int buferSize = MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, nullptr, 0);\n if (buferSize == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert UTF-8 to wide char\");\n\n std::vector<WCHAR> buffer(buferSize);\n if (MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, buffer.data(), buferSize) == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert UTF-8 to wide char\");\n\n \/\/ Result of the ShellExecuteW can be cast only to an int (https:\/\/docs.microsoft.com\/en-us\/windows\/desktop\/api\/shellapi\/nf-shellapi-shellexecutew)\n \/\/ Cast to intptr_t and then to int to avoid warnings 4311 and 4302\n auto result = static_cast<int>(reinterpret_cast<intptr_t>(ShellExecuteW(nullptr, L\"open\", buffer.data(), nullptr, nullptr, SW_SHOWNORMAL)));\n if (result <= 32)\n throw std::system_error(result, shellExecuteErrorCategory, \"Failed to execute open\");\n }\n}\n<commit_msg>Use memcpy to cast the result of ShellExecuteW to int<commit_after>\/\/ Copyright 2015-2019 Elviss Strazdins. All rights reserved.\n\n#include <cstdlib>\n#include <system_error>\n#pragma push_macro(\"WIN32_LEAN_AND_MEAN\")\n#pragma push_macro(\"NOMINMAX\")\n#ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n#endif\n#ifndef NOMINMAX\n# define NOMINMAX\n#endif\n#include <Windows.h>\n#include <shellapi.h>\n#pragma pop_macro(\"WIN32_LEAN_AND_MEAN\")\n#pragma pop_macro(\"NOMINMAX\")\n\n#include \"EngineWin.hpp\"\n#include \"NativeWindowWin.hpp\"\n#include \"input\/windows\/InputSystemWin.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace\n {\n class ShellExecuteErrorCategory final: public std::error_category\n {\n public:\n const char* name() const noexcept final\n {\n return \"ShellExecute\";\n }\n\n std::string message(int condition) const final\n {\n switch (condition)\n {\n case 0: return \"Out of memory\";\n case ERROR_FILE_NOT_FOUND: return \"ERROR_FILE_NOT_FOUND\";\n case ERROR_PATH_NOT_FOUND: return \"ERROR_PATH_NOT_FOUND\";\n case ERROR_BAD_FORMAT: return \"ERROR_BAD_FORMAT\";\n case SE_ERR_ACCESSDENIED: return \"SE_ERR_ACCESSDENIED\";\n case SE_ERR_ASSOCINCOMPLETE: return \"SE_ERR_ASSOCINCOMPLETE\";\n case SE_ERR_DDEBUSY: return \"SE_ERR_DDEBUSY\";\n case SE_ERR_DDEFAIL: return \"SE_ERR_DDEFAIL\";\n case SE_ERR_DDETIMEOUT: return \"SE_ERR_DDETIMEOUT\";\n case SE_ERR_DLLNOTFOUND: return \"SE_ERR_DLLNOTFOUND\";\n case SE_ERR_NOASSOC: return \"SE_ERR_NOASSOC\";\n case SE_ERR_OOM: return \"SE_ERR_OOM\";\n case SE_ERR_SHARE: return \"SE_ERR_SHARE\";\n default: return \"Unknown error (\" + std::to_string(condition) + \")\";\n }\n }\n };\n\n const ShellExecuteErrorCategory shellExecuteErrorCategory {};\n }\n\n EngineWin::EngineWin(int initArgc, LPWSTR* initArgv)\n {\n if (initArgv)\n {\n int bufferSize;\n std::vector<char> buffer;\n\n for (int i = 0; i < initArgc; ++i)\n {\n bufferSize = WideCharToMultiByte(CP_UTF8, 0, initArgv[i], -1, nullptr, 0, nullptr, nullptr);\n if (bufferSize == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert wide char to UTF-8\");\n\n buffer.resize(bufferSize);\n if (WideCharToMultiByte(CP_UTF8, 0, initArgv[i], -1, buffer.data(), bufferSize, nullptr, nullptr) == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert wide char to UTF-8\");\n\n args.push_back(buffer.data());\n }\n }\n\n HRESULT hr;\n if (FAILED(hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED)))\n throw std::system_error(hr, std::system_category(), \"Failed to initialize COM\");\n\n#ifdef DEBUG\n if (!AllocConsole())\n log(Log::Level::Info) << \"Attached to console\";\n#endif\n }\n\n EngineWin::~EngineWin()\n {\n \/\/CoUninitialize();\n }\n\n static void translateMessage(HWND window, const std::set<HACCEL>& accelerators, MSG& message)\n {\n bool translate = true;\n\n for (HACCEL accelerator : accelerators)\n {\n if (TranslateAccelerator(window, accelerator, &message))\n translate = false;\n }\n\n if (translate)\n {\n TranslateMessage(&message);\n DispatchMessage(&message);\n }\n }\n\n void EngineWin::run()\n {\n init();\n start();\n\n input::InputSystemWin* inputWin = static_cast<input::InputSystemWin*>(inputManager->getInputSystem());\n NativeWindowWin* windowWin = static_cast<NativeWindowWin*>(window->getNativeWindow());\n\n MSG message;\n\n while (active)\n {\n if (!paused)\n {\n if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE))\n {\n translateMessage(windowWin->getNativeWindow(),\n windowWin->accelerators, message);\n\n if (message.message == WM_QUIT)\n {\n exit();\n break;\n }\n }\n }\n else\n {\n BOOL ret;\n if ((ret = GetMessage(&message, nullptr, 0, 0)) == -1)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get message\");\n\n if (ret == 0)\n {\n exit();\n break;\n }\n else\n {\n translateMessage(windowWin->getNativeWindow(),\n windowWin->accelerators, message);\n }\n }\n\n inputWin->update();\n }\n\n exit();\n }\n\n void EngineWin::runOnMainThread(const std::function<void()>& func)\n {\n NativeWindowWin* windowWin = static_cast<NativeWindowWin*>(window->getNativeWindow());\n\n std::unique_lock<std::mutex> lock(executeMutex);\n executeQueue.push(func);\n lock.unlock();\n\n if (!PostMessage(windowWin->getNativeWindow(), WM_USER, 0, 0))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to post message\");\n\n }\n\n void EngineWin::executeAll()\n {\n std::function<void()> func;\n\n for (;;)\n {\n std::unique_lock<std::mutex> lock(executeMutex);\n\n if (executeQueue.empty())\n break;\n\n func = std::move(executeQueue.front());\n executeQueue.pop();\n lock.unlock();\n\n if (func) func();\n }\n }\n\n void EngineWin::openURL(const std::string& url)\n {\n const int buferSize = MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, nullptr, 0);\n if (buferSize == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert UTF-8 to wide char\");\n\n std::vector<WCHAR> buffer(buferSize);\n if (MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, buffer.data(), buferSize) == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert UTF-8 to wide char\");\n\n \/\/ Result of the ShellExecuteW can be cast only to an int (https:\/\/docs.microsoft.com\/en-us\/windows\/desktop\/api\/shellapi\/nf-shellapi-shellexecutew)\n HINSTANCE result = ShellExecuteW(nullptr, L\"open\", buffer.data(), nullptr, nullptr, SW_SHOWNORMAL);\n int status;\n memcpy(&status, &result, sizeof(status));\n if (status <= 32)\n throw std::system_error(status, shellExecuteErrorCategory, \"Failed to execute open\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <pthread.h>\n#include <stdio.h>\n#include <dlfcn.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/select.h>\n#include <sys\/time.h>\n#include <execinfo.h>\n#include <tern\/hooks.h>\n#include <tern\/space.h>\n#include <tern\/options.h>\n#include <tern\/runtime\/runtime.h>\n\nusing namespace tern;\n\n#define __NEED_INPUT_INSID\n#define __USE_TERN_RUNTIME\n\/\/#define PRINT_DEBUG\n\n\/*\n#ifdef __USE_TERN_RUNTIME\n#define __INSTALL_RUNTIME\n#endif\n\n#ifdef __INSTALL_RUNTIME\n\nstruct preload_static_block\n{\n preload_static_block()\n {\n InstallRuntime();\n }\n};\n\n\/\/ notice, it doesn't work for functions called in static constructors of program \n\nstatic preload_static_block preload_initializer;\n\n#endif\n*\/\n\n#define __SPEC_HOOK___libc_start_main\n\nstatic void print_stack()\n{\n#if 0\n void* tracePtrs[500];\n printf(\"here\");\n fflush(stdout);\n int count = backtrace( tracePtrs, 500 );\n printf(\"here\");\n fflush(stdout);\n char** funcNames = backtrace_symbols( tracePtrs, count );\n \n printf(\"here\");\n fflush(stdout);\n \/\/ Print the stack trace\n for( int ii = 0; ii < count; ii++ )\n printf( \"%s\\n\", funcNames[ii] );\n fflush(stdout);\n\n \/\/ Free the string pointers\n free( funcNames );\n#endif\n}\n\nvoid *get_eip()\n{\n void *tracePtrs[20];\n int i;\n uint64_t ret = 0; \n int count = backtrace(tracePtrs, 20);\n\n if (options::whole_stack_eip_signature)\n {\n ret = 0;\n for (i = 0; i < count; ++i)\n ret = ret * 97 + (uint64_t) tracePtrs[i];\n return (void*) ret;\n \/\/std::cout << std::hex << tracePtrs[2] << std::dec << std::endl;\n \/\/char** funcNames = backtrace_symbols( tracePtrs, count );\n \/\/printf( \"%s\\n\", funcNames[2] );\n \/\/printf(stderr, \"reteip: %p\\n\", tracePtrs[1]);\n } else\n return tracePtrs[3]; \/\/ this is ret_eip of my caller\n}\n\n#define HOOK_MUTEX_COND\n#define HOOK_BARRIER\n#define HOOK_SEMAPHORE\n#define HOOK_BLOCKING_FUNCS\n\n\/\/ notice we have not implemented tern_fork yet. so the\n\/\/ hooking code is disabled. \n\/\/#define __SPEC_HOOK_fork\n\n#ifndef HOOK_MUTEX_COND\n#define __SPEC_HOOK_pthread_mutex_init\n#define __SPEC_HOOK_pthread_mutex_lock\n#define __SPEC_HOOK_pthread_mutex_unlock\n#define __SPEC_HOOK_pthread_mutex_trylock\n#define __SPEC_HOOK_pthread_mutex_timedlock\n#define __SPEC_HOOK_pthread_cond_wait\n#define __SPEC_HOOK_pthread_cond_signal\n#define __SPEC_HOOK_pthread_cond_timedwait\n#define __SPEC_HOOK_pthread_cond_broadcast\n#endif\n\n#ifndef HOOK_BARRIER\n#define __SPEC_HOOK_pthread_barrier_wait\n#define __SPEC_HOOK_pthread_barrier_init\n#define __SPEC_HOOK_pthread_barrier_destroy\n#endif\n\n#ifndef HOOK_SEMAPHORE\n#define __SPEC_HOOK_sem_wait\n#define __SPEC_HOOK_sem_trywait\n#define __SPEC_HOOK_sem_timedwait\n#define __SPEC_HOOK_sem_post\n#endif\n\n#ifndef HOOK_BLOCKING_FUNCS\n#define __SPEC_HOOK_recv\n#define __SPEC_HOOK_connect\n#define __SPEC_HOOK_accept\n#define __SPEC_HOOK_accept4\n#define __SPEC_HOOK_read\n#define __SPEC_HOOK_write\n#define __SPEC_HOOK_sigwait\n#define __SPEC_HOOK_select\n#define __SPEC_HOOK_recvfrom\n#define __SPEC_HOOK_recvmsg\n#define __SPEC_HOOK_sleep\n#define __SPEC_HOOK_usleep\n#define __SPEC_HOOK_nanosleep\n#define __SPEC_HOOK_epoll_wait\n#endif\n\n#include \"spec_hooks.cpp\"\n#include \"template.cpp\"\n\n<commit_msg>Nits, disable sync builtins in libgomp<commit_after>#include <pthread.h>\n#include <stdio.h>\n#include <dlfcn.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/select.h>\n#include <sys\/time.h>\n#include <execinfo.h>\n#include <tern\/hooks.h>\n#include <tern\/space.h>\n#include <tern\/options.h>\n#include <tern\/runtime\/runtime.h>\n\nusing namespace tern;\n\n#define __NEED_INPUT_INSID\n#define __USE_TERN_RUNTIME\n\/\/#define PRINT_DEBUG\n\n\/*\n#ifdef __USE_TERN_RUNTIME\n#define __INSTALL_RUNTIME\n#endif\n\n#ifdef __INSTALL_RUNTIME\n\nstruct preload_static_block\n{\n preload_static_block()\n {\n InstallRuntime();\n }\n};\n\n\/\/ notice, it doesn't work for functions called in static constructors of program \n\nstatic preload_static_block preload_initializer;\n\n#endif\n*\/\n\n#define __SPEC_HOOK___libc_start_main\n\nstatic void print_stack()\n{\n#if 0\n void* tracePtrs[500];\n printf(\"here\");\n fflush(stdout);\n int count = backtrace( tracePtrs, 500 );\n printf(\"here\");\n fflush(stdout);\n char** funcNames = backtrace_symbols( tracePtrs, count );\n \n printf(\"here\");\n fflush(stdout);\n \/\/ Print the stack trace\n for( int ii = 0; ii < count; ii++ )\n printf( \"%s\\n\", funcNames[ii] );\n fflush(stdout);\n\n \/\/ Free the string pointers\n free( funcNames );\n#endif\n}\n\nvoid *get_eip()\n{\n void *tracePtrs[20];\n int i;\n uint64_t ret = 0; \n int count = backtrace(tracePtrs, 20);\n\n if (options::whole_stack_eip_signature)\n {\n ret = 0;\n for (i = 0; i < count; ++i)\n ret = ret * 97 + (uint64_t) tracePtrs[i];\n return (void*) ret;\n \/\/std::cout << std::hex << tracePtrs[2] << std::dec << std::endl;\n \/\/char** funcNames = backtrace_symbols( tracePtrs, count );\n \/\/printf( \"%s\\n\", funcNames[2] );\n \/\/printf(stderr, \"reteip: %p\\n\", tracePtrs[1]);\n } else\n return tracePtrs[2]; \/\/ this is ret_eip of my caller\n}\n\n#define HOOK_MUTEX_COND\n#define HOOK_BARRIER\n#define HOOK_SEMAPHORE\n#define HOOK_BLOCKING_FUNCS\n\n\/\/ notice we have not implemented tern_fork yet. so the\n\/\/ hooking code is disabled. \n\/\/#define __SPEC_HOOK_fork\n\n#ifndef HOOK_MUTEX_COND\n#define __SPEC_HOOK_pthread_mutex_init\n#define __SPEC_HOOK_pthread_mutex_lock\n#define __SPEC_HOOK_pthread_mutex_unlock\n#define __SPEC_HOOK_pthread_mutex_trylock\n#define __SPEC_HOOK_pthread_mutex_timedlock\n#define __SPEC_HOOK_pthread_cond_wait\n#define __SPEC_HOOK_pthread_cond_signal\n#define __SPEC_HOOK_pthread_cond_timedwait\n#define __SPEC_HOOK_pthread_cond_broadcast\n#endif\n\n#ifndef HOOK_BARRIER\n#define __SPEC_HOOK_pthread_barrier_wait\n#define __SPEC_HOOK_pthread_barrier_init\n#define __SPEC_HOOK_pthread_barrier_destroy\n#endif\n\n#ifndef HOOK_SEMAPHORE\n#define __SPEC_HOOK_sem_wait\n#define __SPEC_HOOK_sem_trywait\n#define __SPEC_HOOK_sem_timedwait\n#define __SPEC_HOOK_sem_post\n#endif\n\n#ifndef HOOK_BLOCKING_FUNCS\n#define __SPEC_HOOK_recv\n#define __SPEC_HOOK_connect\n#define __SPEC_HOOK_accept\n#define __SPEC_HOOK_accept4\n#define __SPEC_HOOK_read\n#define __SPEC_HOOK_write\n#define __SPEC_HOOK_sigwait\n#define __SPEC_HOOK_select\n#define __SPEC_HOOK_recvfrom\n#define __SPEC_HOOK_recvmsg\n#define __SPEC_HOOK_sleep\n#define __SPEC_HOOK_usleep\n#define __SPEC_HOOK_nanosleep\n#define __SPEC_HOOK_epoll_wait\n#endif\n\n#include \"spec_hooks.cpp\"\n#include \"template.cpp\"\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix bad change in RenderScriptx86ABIFixups.cpp, forgot to change everything necessary<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/future.hpp>\n#include <agency\/new_executor_traits.hpp>\n#include <agency\/detail\/executor_traits\/check_for_member_functions.hpp>\n#include <agency\/detail\/executor_traits\/ignore_tail_parameters_and_invoke.hpp>\n#include <type_traits>\n#include <utility>\n\n\nnamespace agency\n{\nnamespace detail\n{\nnamespace new_executor_traits_detail\n{\nnamespace multi_agent_then_execute_returning_user_specified_container_implementation_strategies\n{\n\n\nstruct use_multi_agent_then_execute_returning_user_specified_container_member_function {};\n\nstruct use_multi_agent_then_execute_with_shared_inits_returning_user_specified_container {};\n\ntemplate<class Container, class Executor, class Function, class Future>\nusing select_multi_agent_then_execute_returning_user_specified_container_implementation =\n typename std::conditional<\n has_multi_agent_then_execute_returning_user_specified_container<Container,Executor,Function,Future>::value,\n use_multi_agent_then_execute_returning_user_specified_container_member_function,\n use_multi_agent_then_execute_with_shared_inits_returning_user_specified_container\n >::type;\n\n\ntemplate<class Container, class Executor, class Function, class Future>\ntypename new_executor_traits<Executor>::template future<Container>\n multi_agent_then_execute_returning_user_specified_container(use_multi_agent_then_execute_returning_user_specified_container_member_function,\n Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, Future& fut)\n{\n return ex.template then_execute<Container>(f, shape, fut);\n} \/\/ end multi_agent_then_execute_returning_user_specified_container()\n\n\ntemplate<class Function, class T>\nstruct ignore_tail_parameters_and_invoke\n{\n mutable Function f;\n\n template<class Index, class... Args>\n __AGENCY_ANNOTATION\n typename std::result_of<Function(Index,T&)>::type\n operator()(const Index& idx, T& past_arg, Args&&...) const\n {\n \/\/ XXX should use std::invoke\n return f(idx, past_arg);\n }\n};\n\n\ntemplate<class Function>\nstruct ignore_tail_parameters_and_invoke<Function,void>\n{\n mutable Function f;\n\n template<class Index, class... Args>\n __AGENCY_ANNOTATION\n typename std::result_of<Function(Index)>::type\n operator()(const Index& idx, Args&&...) const\n {\n \/\/ XXX should use std::invoke\n return f(idx);\n }\n};\n\n\ntemplate<class Container, size_t... Indices, class Executor, class Function, class Future, class Tuple>\ntypename new_executor_traits<Executor>::template future<Container>\n multi_agent_then_execute_returning_user_specified_container_impl(detail::index_sequence<Indices...>,\n Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, Future& fut,\n const Tuple& tuple_of_ignored_parameters)\n{\n using value_type = typename future_traits<Future>::value_type;\n\n return new_executor_traits<Executor>::template then_execute<Container>(ex, ignore_tail_parameters_and_invoke<Function,value_type>{f}, shape, fut, std::get<Indices>(tuple_of_ignored_parameters)...);\n} \/\/ end multi_agent_then_execute_returning_user_specified_container_impl()\n\n\ntemplate<class Container, class Executor, class Function, class Future>\ntypename new_executor_traits<Executor>::template future<Container>\n multi_agent_then_execute_returning_user_specified_container(use_multi_agent_then_execute_with_shared_inits_returning_user_specified_container,\n Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, Future& fut)\n{\n auto tuple_of_ignored_parameters = new_executor_traits_detail::make_tuple_of_ignored_parameters(ex);\n\n return multi_agent_then_execute_returning_user_specified_container_impl<Container>(detail::make_index_sequence<std::tuple_size<decltype(tuple_of_ignored_parameters)>::value>(), ex, f, shape, fut, tuple_of_ignored_parameters);\n} \/\/ end multi_agent_then_execute_returning_user_specified_container()\n\n\n} \/\/ end multi_agent_then_execute_returning_user_specified_container_implementation_strategies\n} \/\/ end new_executor_traits_detail\n} \/\/ end detail\n\n\ntemplate<class Executor>\n template<class Container, class Function, class Future,\n class Enable1,\n class Enable2,\n class Enable3\n >\ntypename new_executor_traits<Executor>::template future<Container>\n new_executor_traits<Executor>\n ::then_execute(typename new_executor_traits<Executor>::executor_type& ex,\n Function f,\n typename new_executor_traits<Executor>::shape_type shape,\n Future& fut)\n{\n namespace ns = detail::new_executor_traits_detail::multi_agent_then_execute_returning_user_specified_container_implementation_strategies;\n\n using check_for_member_function = ns::select_multi_agent_then_execute_returning_user_specified_container_implementation<Container,Executor,Function,Future>;\n\n return ns::multi_agent_then_execute_returning_user_specified_container<Container>(check_for_member_function(), ex, f, shape, fut);\n} \/\/ end new_executor_traits::then_execute()\n\n\n} \/\/ end agency\n\n<commit_msg>Use agency::invoke() in ignore_tail_parameters_and_invoke<commit_after>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/future.hpp>\n#include <agency\/new_executor_traits.hpp>\n#include <agency\/detail\/executor_traits\/check_for_member_functions.hpp>\n#include <agency\/detail\/executor_traits\/ignore_tail_parameters_and_invoke.hpp>\n#include <agency\/functional.hpp>\n#include <type_traits>\n#include <utility>\n\n\nnamespace agency\n{\nnamespace detail\n{\nnamespace new_executor_traits_detail\n{\nnamespace multi_agent_then_execute_returning_user_specified_container_implementation_strategies\n{\n\n\nstruct use_multi_agent_then_execute_returning_user_specified_container_member_function {};\n\nstruct use_multi_agent_then_execute_with_shared_inits_returning_user_specified_container {};\n\ntemplate<class Container, class Executor, class Function, class Future>\nusing select_multi_agent_then_execute_returning_user_specified_container_implementation =\n typename std::conditional<\n has_multi_agent_then_execute_returning_user_specified_container<Container,Executor,Function,Future>::value,\n use_multi_agent_then_execute_returning_user_specified_container_member_function,\n use_multi_agent_then_execute_with_shared_inits_returning_user_specified_container\n >::type;\n\n\ntemplate<class Container, class Executor, class Function, class Future>\ntypename new_executor_traits<Executor>::template future<Container>\n multi_agent_then_execute_returning_user_specified_container(use_multi_agent_then_execute_returning_user_specified_container_member_function,\n Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, Future& fut)\n{\n return ex.template then_execute<Container>(f, shape, fut);\n} \/\/ end multi_agent_then_execute_returning_user_specified_container()\n\n\ntemplate<class Function, class T>\nstruct ignore_tail_parameters_and_invoke\n{\n mutable Function f;\n\n template<class Index, class... Args>\n __AGENCY_ANNOTATION\n typename std::result_of<Function(Index,T&)>::type\n operator()(const Index& idx, T& past_arg, Args&&...) const\n {\n \/\/ XXX should use std::invoke\n return f(idx, past_arg);\n }\n};\n\n\ntemplate<class Function>\nstruct ignore_tail_parameters_and_invoke<Function,void>\n{\n mutable Function f;\n\n __agency_hd_warning_disable__\n template<class Index, class... Args>\n __AGENCY_ANNOTATION\n typename std::result_of<Function(Index)>::type\n operator()(const Index& idx, Args&&...) const\n {\n return agency::invoke(f, idx);\n }\n};\n\n\ntemplate<class Container, size_t... Indices, class Executor, class Function, class Future, class Tuple>\ntypename new_executor_traits<Executor>::template future<Container>\n multi_agent_then_execute_returning_user_specified_container_impl(detail::index_sequence<Indices...>,\n Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, Future& fut,\n const Tuple& tuple_of_ignored_parameters)\n{\n using value_type = typename future_traits<Future>::value_type;\n\n return new_executor_traits<Executor>::template then_execute<Container>(ex, ignore_tail_parameters_and_invoke<Function,value_type>{f}, shape, fut, std::get<Indices>(tuple_of_ignored_parameters)...);\n} \/\/ end multi_agent_then_execute_returning_user_specified_container_impl()\n\n\ntemplate<class Container, class Executor, class Function, class Future>\ntypename new_executor_traits<Executor>::template future<Container>\n multi_agent_then_execute_returning_user_specified_container(use_multi_agent_then_execute_with_shared_inits_returning_user_specified_container,\n Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, Future& fut)\n{\n auto tuple_of_ignored_parameters = new_executor_traits_detail::make_tuple_of_ignored_parameters(ex);\n\n return multi_agent_then_execute_returning_user_specified_container_impl<Container>(detail::make_index_sequence<std::tuple_size<decltype(tuple_of_ignored_parameters)>::value>(), ex, f, shape, fut, tuple_of_ignored_parameters);\n} \/\/ end multi_agent_then_execute_returning_user_specified_container()\n\n\n} \/\/ end multi_agent_then_execute_returning_user_specified_container_implementation_strategies\n} \/\/ end new_executor_traits_detail\n} \/\/ end detail\n\n\ntemplate<class Executor>\n template<class Container, class Function, class Future,\n class Enable1,\n class Enable2,\n class Enable3\n >\ntypename new_executor_traits<Executor>::template future<Container>\n new_executor_traits<Executor>\n ::then_execute(typename new_executor_traits<Executor>::executor_type& ex,\n Function f,\n typename new_executor_traits<Executor>::shape_type shape,\n Future& fut)\n{\n namespace ns = detail::new_executor_traits_detail::multi_agent_then_execute_returning_user_specified_container_implementation_strategies;\n\n using check_for_member_function = ns::select_multi_agent_then_execute_returning_user_specified_container_implementation<Container,Executor,Function,Future>;\n\n return ns::multi_agent_then_execute_returning_user_specified_container<Container>(check_for_member_function(), ex, f, shape, fut);\n} \/\/ end new_executor_traits::then_execute()\n\n\n} \/\/ end agency\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\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#include \"QUECTEL_BC95_CellularStack.h\"\n#include \"CellularUtil.h\"\n#include \"CellularLog.h\"\n\nusing namespace mbed;\nusing namespace mbed_cellular_util;\n\nQUECTEL_BC95_CellularStack::QUECTEL_BC95_CellularStack(ATHandler &atHandler, int cid, nsapi_ip_stack_t stack_type) : AT_CellularStack(atHandler, cid, stack_type)\n{\n _at.set_urc_handler(\"+NSONMI:\", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsonmi));\n}\n\nQUECTEL_BC95_CellularStack::~QUECTEL_BC95_CellularStack()\n{\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::socket_listen(nsapi_socket_t handle, int backlog)\n{\n return NSAPI_ERROR_UNSUPPORTED;\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr)\n{\n return NSAPI_ERROR_UNSUPPORTED;\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &address)\n{\n CellularSocket *socket = (CellularSocket *)handle;\n\n _at.lock();\n if (!socket->created) {\n const nsapi_error_t error_create = create_socket_impl(socket);\n if (error_create != NSAPI_ERROR_OK) {\n return error_create;\n }\n }\n\n _at.cmd_start(\"AT+NSOCO=\");\n _at.write_int(socket->id);\n _at.write_string(address.get_ip_address(), false);\n _at.write_int(address.get_port());\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n _at.unlock();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n socket->remoteAddress = address;\n socket->connected = true;\n return NSAPI_ERROR_OK;\n }\n\n return NSAPI_ERROR_NO_CONNECTION;\n}\n\nvoid QUECTEL_BC95_CellularStack::urc_nsonmi()\n{\n int sock_id = _at.read_int();\n\n for (int i = 0; i < get_max_socket_count(); i++) {\n CellularSocket *sock = _socket[i];\n if (sock && sock->id == sock_id) {\n if (sock->_cb) {\n sock->_cb(sock->_data);\n }\n break;\n }\n }\n}\n\nint QUECTEL_BC95_CellularStack::get_max_socket_count()\n{\n return BC95_SOCKET_MAX;\n}\n\nbool QUECTEL_BC95_CellularStack::is_protocol_supported(nsapi_protocol_t protocol)\n{\n return (protocol == NSAPI_UDP || protocol == NSAPI_TCP);\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::socket_close_impl(int sock_id)\n{\n _at.cmd_start(\"AT+NSOCL=\");\n _at.write_int(sock_id);\n _at.cmd_stop_read_resp();\n\n tr_info(\"Close socket: %d error: %d\", sock_id, _at.get_last_error());\n\n return _at.get_last_error();\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::create_socket_impl(CellularSocket *socket)\n{\n int sock_id = -1;\n bool socketOpenWorking = false;\n\n if (socket->proto == NSAPI_UDP) {\n _at.cmd_start(\"AT+NSOCR=DGRAM,17,\");\n } else if (socket->proto == NSAPI_TCP) {\n _at.cmd_start(\"AT+NSOCR=STREAM,6,\");\n } else {\n return NSAPI_ERROR_PARAMETER;\n }\n _at.write_int(socket->localAddress.get_port());\n _at.write_int(1);\n _at.cmd_stop();\n _at.resp_start();\n sock_id = _at.read_int();\n _at.resp_stop();\n\n socketOpenWorking = (_at.get_last_error() == NSAPI_ERROR_OK);\n\n if (!socketOpenWorking) {\n _at.cmd_start(\"AT+NSOCL=0\");\n _at.cmd_stop_read_resp();\n\n if (socket->proto == NSAPI_UDP) {\n _at.cmd_start(\"AT+NSOCR=DGRAM,17,\");\n } else if (socket->proto == NSAPI_TCP) {\n _at.cmd_start(\"AT+NSOCR=STREAM,6,\");\n }\n _at.write_int(socket->localAddress.get_port());\n _at.write_int(1);\n _at.cmd_stop();\n _at.resp_start();\n sock_id = _at.read_int();\n _at.resp_stop();\n\n socketOpenWorking = (_at.get_last_error() == NSAPI_ERROR_OK);\n }\n\n if (!socketOpenWorking || (sock_id == -1)) {\n tr_error(\"Socket create failed!\");\n return NSAPI_ERROR_NO_SOCKET;\n }\n\n \/\/ Check for duplicate socket id delivered by modem\n for (int i = 0; i < BC95_SOCKET_MAX; i++) {\n CellularSocket *sock = _socket[i];\n if (sock && sock->created && sock->id == sock_id) {\n tr_error(\"Duplicate socket index: %d created:%d, sock_id: %d\", i, sock->created, sock_id);\n return NSAPI_ERROR_NO_SOCKET;\n }\n }\n\n tr_info(\"Socket create id: %d\", sock_id);\n\n socket->id = sock_id;\n socket->created = true;\n\n return NSAPI_ERROR_OK;\n}\n\nnsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_sendto_impl(CellularSocket *socket, const SocketAddress &address,\n const void *data, nsapi_size_t size)\n{\n int sent_len = 0;\n\n char *hexstr = new char[size * 2 + 1];\n int hexlen = char_str_to_hex_str((const char *)data, size, hexstr);\n \/\/ NULL terminated for write_string\n hexstr[hexlen] = 0;\n\n if (socket->proto == NSAPI_UDP) {\n _at.cmd_start(\"AT+NSOST=\");\n _at.write_int(socket->id);\n _at.write_string(address.get_ip_address(), false);\n _at.write_int(address.get_port());\n _at.write_int(size);\n } else if (socket->proto == NSAPI_TCP) {\n _at.cmd_start(\"AT+NSOSD=\");\n _at.write_int(socket->id);\n _at.write_int(size);\n } else {\n delete [] hexstr;\n return NSAPI_ERROR_PARAMETER;\n }\n\n _at.write_string(hexstr, false);\n _at.cmd_stop();\n _at.resp_start();\n \/\/ skip socket id\n _at.skip_param();\n sent_len = _at.read_int();\n _at.resp_stop();\n\n delete [] hexstr;\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n return sent_len;\n }\n\n return _at.get_last_error();\n}\n\nnsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address,\n void *buffer, nsapi_size_t size)\n{\n nsapi_size_or_error_t recv_len = 0;\n int port;\n char ip_address[NSAPI_IP_SIZE];\n\n _at.cmd_start(\"AT+NSORF=\");\n _at.write_int(socket->id);\n _at.write_int(size);\n _at.cmd_stop();\n _at.resp_start();\n \/\/ receiving socket id\n _at.skip_param();\n _at.read_string(ip_address, sizeof(ip_address));\n port = _at.read_int();\n recv_len = _at.read_int();\n int hexlen = _at.read_hex_string((char *)buffer, size);\n \/\/ remaining length\n _at.skip_param();\n _at.resp_stop();\n\n if (!recv_len || (recv_len == -1) || (_at.get_last_error() != NSAPI_ERROR_OK)) {\n return NSAPI_ERROR_WOULD_BLOCK;\n }\n\n if (address) {\n address->set_ip_address(ip_address);\n address->set_port(port);\n }\n\n if (recv_len != hexlen) {\n tr_error(\"Not received as much data as expected. Should receive: %d bytes, received: %d bytes\", recv_len, hexlen);\n }\n return recv_len;\n}\n<commit_msg>Cellular: Fix max packet size for BC95 driver<commit_after>\/*\n * Copyright (c) 2017, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\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#include \"QUECTEL_BC95_CellularStack.h\"\n#include \"CellularUtil.h\"\n#include \"CellularLog.h\"\n\n#define PACKET_SIZE_MAX 1358\n\nusing namespace mbed;\nusing namespace mbed_cellular_util;\n\nQUECTEL_BC95_CellularStack::QUECTEL_BC95_CellularStack(ATHandler &atHandler, int cid, nsapi_ip_stack_t stack_type) : AT_CellularStack(atHandler, cid, stack_type)\n{\n _at.set_urc_handler(\"+NSONMI:\", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsonmi));\n}\n\nQUECTEL_BC95_CellularStack::~QUECTEL_BC95_CellularStack()\n{\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::socket_listen(nsapi_socket_t handle, int backlog)\n{\n return NSAPI_ERROR_UNSUPPORTED;\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr)\n{\n return NSAPI_ERROR_UNSUPPORTED;\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &address)\n{\n CellularSocket *socket = (CellularSocket *)handle;\n\n _at.lock();\n if (!socket->created) {\n const nsapi_error_t error_create = create_socket_impl(socket);\n if (error_create != NSAPI_ERROR_OK) {\n return error_create;\n }\n }\n\n _at.cmd_start(\"AT+NSOCO=\");\n _at.write_int(socket->id);\n _at.write_string(address.get_ip_address(), false);\n _at.write_int(address.get_port());\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n _at.unlock();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n socket->remoteAddress = address;\n socket->connected = true;\n return NSAPI_ERROR_OK;\n }\n\n return NSAPI_ERROR_NO_CONNECTION;\n}\n\nvoid QUECTEL_BC95_CellularStack::urc_nsonmi()\n{\n int sock_id = _at.read_int();\n\n for (int i = 0; i < get_max_socket_count(); i++) {\n CellularSocket *sock = _socket[i];\n if (sock && sock->id == sock_id) {\n if (sock->_cb) {\n sock->_cb(sock->_data);\n }\n break;\n }\n }\n}\n\nint QUECTEL_BC95_CellularStack::get_max_socket_count()\n{\n return BC95_SOCKET_MAX;\n}\n\nbool QUECTEL_BC95_CellularStack::is_protocol_supported(nsapi_protocol_t protocol)\n{\n return (protocol == NSAPI_UDP || protocol == NSAPI_TCP);\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::socket_close_impl(int sock_id)\n{\n _at.cmd_start(\"AT+NSOCL=\");\n _at.write_int(sock_id);\n _at.cmd_stop_read_resp();\n\n tr_info(\"Close socket: %d error: %d\", sock_id, _at.get_last_error());\n\n return _at.get_last_error();\n}\n\nnsapi_error_t QUECTEL_BC95_CellularStack::create_socket_impl(CellularSocket *socket)\n{\n int sock_id = -1;\n bool socketOpenWorking = false;\n\n if (socket->proto == NSAPI_UDP) {\n _at.cmd_start(\"AT+NSOCR=DGRAM,17,\");\n } else if (socket->proto == NSAPI_TCP) {\n _at.cmd_start(\"AT+NSOCR=STREAM,6,\");\n } else {\n return NSAPI_ERROR_PARAMETER;\n }\n _at.write_int(socket->localAddress.get_port());\n _at.write_int(1);\n _at.cmd_stop();\n _at.resp_start();\n sock_id = _at.read_int();\n _at.resp_stop();\n\n socketOpenWorking = (_at.get_last_error() == NSAPI_ERROR_OK);\n\n if (!socketOpenWorking) {\n _at.cmd_start(\"AT+NSOCL=0\");\n _at.cmd_stop_read_resp();\n\n if (socket->proto == NSAPI_UDP) {\n _at.cmd_start(\"AT+NSOCR=DGRAM,17,\");\n } else if (socket->proto == NSAPI_TCP) {\n _at.cmd_start(\"AT+NSOCR=STREAM,6,\");\n }\n _at.write_int(socket->localAddress.get_port());\n _at.write_int(1);\n _at.cmd_stop();\n _at.resp_start();\n sock_id = _at.read_int();\n _at.resp_stop();\n\n socketOpenWorking = (_at.get_last_error() == NSAPI_ERROR_OK);\n }\n\n if (!socketOpenWorking || (sock_id == -1)) {\n tr_error(\"Socket create failed!\");\n return NSAPI_ERROR_NO_SOCKET;\n }\n\n \/\/ Check for duplicate socket id delivered by modem\n for (int i = 0; i < BC95_SOCKET_MAX; i++) {\n CellularSocket *sock = _socket[i];\n if (sock && sock->created && sock->id == sock_id) {\n tr_error(\"Duplicate socket index: %d created:%d, sock_id: %d\", i, sock->created, sock_id);\n return NSAPI_ERROR_NO_SOCKET;\n }\n }\n\n tr_info(\"Socket create id: %d\", sock_id);\n\n socket->id = sock_id;\n socket->created = true;\n\n return NSAPI_ERROR_OK;\n}\n\nnsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_sendto_impl(CellularSocket *socket, const SocketAddress &address,\n const void *data, nsapi_size_t size)\n{\n int sent_len = 0;\n\n if (size > PACKET_SIZE_MAX) {\n return NSAPI_ERROR_PARAMETER;\n }\n\n char *hexstr = new char[size * 2 + 1];\n int hexlen = char_str_to_hex_str((const char *)data, size, hexstr);\n \/\/ NULL terminated for write_string\n hexstr[hexlen] = 0;\n\n if (socket->proto == NSAPI_UDP) {\n _at.cmd_start(\"AT+NSOST=\");\n _at.write_int(socket->id);\n _at.write_string(address.get_ip_address(), false);\n _at.write_int(address.get_port());\n _at.write_int(size);\n } else if (socket->proto == NSAPI_TCP) {\n _at.cmd_start(\"AT+NSOSD=\");\n _at.write_int(socket->id);\n _at.write_int(size);\n } else {\n delete [] hexstr;\n return NSAPI_ERROR_PARAMETER;\n }\n\n _at.write_string(hexstr, false);\n _at.cmd_stop();\n _at.resp_start();\n \/\/ skip socket id\n _at.skip_param();\n sent_len = _at.read_int();\n _at.resp_stop();\n\n delete [] hexstr;\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n return sent_len;\n }\n\n return _at.get_last_error();\n}\n\nnsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address,\n void *buffer, nsapi_size_t size)\n{\n nsapi_size_or_error_t recv_len = 0;\n int port;\n char ip_address[NSAPI_IP_SIZE];\n\n _at.cmd_start(\"AT+NSORF=\");\n _at.write_int(socket->id);\n _at.write_int(size <= PACKET_SIZE_MAX ? size : PACKET_SIZE_MAX);\n _at.cmd_stop();\n _at.resp_start();\n \/\/ receiving socket id\n _at.skip_param();\n _at.read_string(ip_address, sizeof(ip_address));\n port = _at.read_int();\n recv_len = _at.read_int();\n int hexlen = _at.read_hex_string((char *)buffer, size);\n \/\/ remaining length\n _at.skip_param();\n _at.resp_stop();\n\n if (!recv_len || (recv_len == -1) || (_at.get_last_error() != NSAPI_ERROR_OK)) {\n return NSAPI_ERROR_WOULD_BLOCK;\n }\n\n if (address) {\n address->set_ip_address(ip_address);\n address->set_port(port);\n }\n\n if (recv_len != hexlen) {\n tr_error(\"Not received as much data as expected. Should receive: %d bytes, received: %d bytes\", recv_len, hexlen);\n }\n return recv_len;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2019 The Apollo Authors. All Rights Reserved.\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 * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/stage_intersection_cruise_impl.h\"\n\n#include <string>\n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/map\/pnc_map\/path.h\"\n#include \"modules\/planning\/common\/planning_context.h\"\n#include \"modules\/planning\/common\/util\/util.h\"\n#include \"modules\/planning\/scenarios\/util\/util.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\n\nbool StageIntersectionCruiseImpl::CheckDone(\n const Frame& frame,\n const ScenarioConfig::ScenarioType& scenario_type,\n const ScenarioConfig::StageConfig& config,\n const bool right_of_way_status) {\n const auto& reference_line_info = frame.reference_line_info().front();\n\n \/\/ TODO(all): remove when pnc_junction completely available on map\n \/\/ get traffic sign overlap along reference line\n hdmap::PathOverlap* traffic_sign_overlap = nullptr;\n if (scenario_type == ScenarioConfig::STOP_SIGN_PROTECTED ||\n scenario_type == ScenarioConfig::STOP_SIGN_UNPROTECTED) {\n const auto& stop_sign_status =\n PlanningContext::Planningstatus().stop_sign();\n const std::string traffic_sign_overlap_id =\n stop_sign_status.current_stop_sign_overlap_id();\n traffic_sign_overlap = scenario::util::GetOverlapOnReferenceLine(\n reference_line_info,\n traffic_sign_overlap_id,\n ReferenceLineInfo::STOP_SIGN);\n } else if (scenario_type == ScenarioConfig::TRAFFIC_LIGHT_PROTECTED ||\n scenario_type == ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN ||\n scenario_type == ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN) {\n const auto& traffic_light_status =\n PlanningContext::Planningstatus().traffic_light();\n const std::string traffic_sign_overlap_id =\n traffic_light_status.current_traffic_light_overlap_id_size() > 0 ?\n traffic_light_status.current_traffic_light_overlap_id(0) : \"\";\n traffic_sign_overlap = scenario::util::GetOverlapOnReferenceLine(\n reference_line_info,\n traffic_sign_overlap_id,\n ReferenceLineInfo::SIGNAL);\n }\n if (!traffic_sign_overlap) {\n return true;\n }\n\n const auto& pnc_junction_overlaps =\n reference_line_info.reference_line().map_path().pnc_junction_overlaps();\n if (pnc_junction_overlaps.empty()) {\n \/\/ TODO(all): remove when pnc_junction completely available on map\n \/\/ pnc_junction not exist on map, use current traffic_sign's end_s\n constexpr double kIntersectionPassDist = 20.0; \/\/ unit: m\n const double adc_back_edge_s =\n reference_line_info.AdcSlBoundary().start_s();\n const double distance_adc_pass_traffic_sign =\n adc_back_edge_s - traffic_sign_overlap->end_s;\n ADEBUG << \"distance_adc_pass_traffic_sign[\"\n << distance_adc_pass_traffic_sign\n << \"] traffic_sign_end_s[\" << traffic_sign_overlap->end_s << \"]\";\n\n return distance_adc_pass_traffic_sign >= kIntersectionPassDist;\n }\n\n if (!planning::util::CheckInsidePnCJunction(reference_line_info)) {\n return true;\n }\n\n \/\/ set right_of_way_status\n reference_line_info.SetJunctionRightOfWay(traffic_sign_overlap->start_s,\n right_of_way_status);\n\n return false;\n}\n\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: more updates on StageIntersectionCuiseImpl<commit_after>\/******************************************************************************\n * Copyright 2019 The Apollo Authors. All Rights Reserved.\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 * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/stage_intersection_cruise_impl.h\"\n\n#include <string>\n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/map\/pnc_map\/path.h\"\n#include \"modules\/planning\/common\/planning_context.h\"\n#include \"modules\/planning\/common\/util\/util.h\"\n#include \"modules\/planning\/scenarios\/util\/util.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\n\nbool StageIntersectionCruiseImpl::CheckDone(\n const Frame& frame,\n const ScenarioConfig::ScenarioType& scenario_type,\n const ScenarioConfig::StageConfig& config,\n const bool right_of_way_status) {\n const auto& reference_line_info = frame.reference_line_info().front();\n\n const auto& pnc_junction_overlaps =\n reference_line_info.reference_line().map_path().pnc_junction_overlaps();\n if (pnc_junction_overlaps.empty()) {\n \/\/ TODO(all): remove when pnc_junction completely available on map\n \/\/ pnc_junction not exist on map, use current traffic_sign's end_s\n \/\/ get traffic sign overlap along reference line\n hdmap::PathOverlap* traffic_sign_overlap = nullptr;\n if (scenario_type == ScenarioConfig::STOP_SIGN_PROTECTED ||\n scenario_type == ScenarioConfig::STOP_SIGN_UNPROTECTED) {\n \/\/ stop_sign scenarios\n const auto& stop_sign_status =\n PlanningContext::Planningstatus().stop_sign();\n const std::string traffic_sign_overlap_id =\n stop_sign_status.current_stop_sign_overlap_id();\n traffic_sign_overlap = scenario::util::GetOverlapOnReferenceLine(\n reference_line_info,\n traffic_sign_overlap_id,\n ReferenceLineInfo::STOP_SIGN);\n } else if (scenario_type == ScenarioConfig::TRAFFIC_LIGHT_PROTECTED ||\n scenario_type == ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN ||\n scenario_type == ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN) {\n \/\/ traffic_light scenarios\n const auto& traffic_light_status =\n PlanningContext::Planningstatus().traffic_light();\n const std::string traffic_sign_overlap_id =\n traffic_light_status.current_traffic_light_overlap_id_size() > 0 ?\n traffic_light_status.current_traffic_light_overlap_id(0) : \"\";\n traffic_sign_overlap = scenario::util::GetOverlapOnReferenceLine(\n reference_line_info,\n traffic_sign_overlap_id,\n ReferenceLineInfo::SIGNAL);\n } else {\n \/\/ TODO(all): to be added\n \/\/ yield_sign scenarios\n }\n\n if (!traffic_sign_overlap) {\n return true;\n }\n\n constexpr double kIntersectionPassDist = 20.0; \/\/ unit: m\n const double adc_back_edge_s =\n reference_line_info.AdcSlBoundary().start_s();\n const double distance_adc_pass_traffic_sign =\n adc_back_edge_s - traffic_sign_overlap->end_s;\n ADEBUG << \"distance_adc_pass_traffic_sign[\"\n << distance_adc_pass_traffic_sign\n << \"] traffic_sign_end_s[\" << traffic_sign_overlap->end_s << \"]\";\n\n \/\/ set right_of_way_status\n reference_line_info.SetJunctionRightOfWay(traffic_sign_overlap->start_s,\n right_of_way_status);\n\n return distance_adc_pass_traffic_sign >= kIntersectionPassDist;\n }\n\n if (!planning::util::CheckInsidePnCJunction(reference_line_info)) {\n return true;\n }\n\n \/\/ set right_of_way_status\n hdmap::PathOverlap pnc_junction_overlap;\n const double adc_front_edge_s =\n reference_line_info.AdcSlBoundary().end_s();\n reference_line_info.GetPnCJunction(adc_front_edge_s, &pnc_junction_overlap);\n reference_line_info.SetJunctionRightOfWay(pnc_junction_overlap.start_s,\n right_of_way_status);\n\n return false;\n}\n\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include <v8.h>\n#include <mysql.h>\n#include <stdlib.h>\n\nv8::Handle<v8::FunctionTemplate> rest;\n\nv8::Handle<v8::Value> _mysql(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.This()->InternalFieldCount() == 0) {\n return v8::ThrowException(v8::String::New(\"Invalid call format. Use 'new MySQL()'\"));\n }\n args.This()->SetInternalField(0, v8::Boolean::New(false));\n \n return args.This();\n}\n\nv8::Handle<v8::Value> _connect(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 4) {\n return v8::ThrowException(v8::String::New(\"Invalid call format. Use 'mysql.connect(host, user, pass, db)'\"));\n }\n\n MYSQL *conn;\n \n v8::String::Utf8Value host(args[0]);\n v8::String::Utf8Value user(args[1]);\n v8::String::Utf8Value pass(args[2]);\n v8::String::Utf8Value db(args[3]);\n\t \n conn = mysql_init(NULL);\n\n if (!mysql_real_connect(conn, *host, *user, *pass, *db, 0, NULL, 0)){\n return v8::Boolean::New(false);\n } else {\n mysql_query(conn, \"SET NAMES 'utf8'\");\t\t\t\t \n args.This()->SetInternalField(0, v8::External::New((void *)conn));\n return args.This();\n } \n}\n\nv8::Handle<v8::Value> _query(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\t\t\n if (args.Length() < 1) {\n return v8::ThrowException(v8::String::New(\"No query specified\"));\n }\n v8::String::Utf8Value q(args[0]);\n \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n MYSQL_RES *res;\n mysql_query(conn, *q);\n res = mysql_store_result(conn);\n \n if (res) {\n v8::Handle<v8::Value> resargs[] = { v8::External::New((void *) res) };\n return rest->GetFunction()->NewInstance(1, resargs);\n } else {\n return v8::Boolean::New(false);\n }\n}\n\nv8::Handle<v8::Value> _error(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n\t \t \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n return v8::String::New(mysql_error(conn));\n}\n\nv8::Handle<v8::Value> _errno(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n return v8::Integer::New(mysql_errno(conn));\n}\n\nv8::Handle<v8::Value> _affectedrows(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n\t \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n return v8::Integer::New(mysql_affected_rows(conn));\n}\n\nv8::Handle<v8::Value> _insertid(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n\n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n return v8::Integer::New(mysql_insert_id(conn));\n}\n\nv8::Handle<v8::Value> _escape(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n if (args.Length() < 1) {\n return v8::ThrowException(v8::String::New(\"Nothing to escape\"));\n }\n v8::String::Utf8Value str(args[0]);\n \n int len = args[0]->ToString()->Utf8Length();\n char * result = (char *) malloc((2*len+1) * sizeof(char));\n \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n int length = mysql_real_escape_string(conn, result, *str, len);\n\n return v8::String::New(result, length);\n}\n\nv8::Handle<v8::Value> _result(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n args.This()->SetInternalField(0, args[0]);\n return args.This();\n}\n\nv8::Handle<v8::Value> _numrows(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n\n return v8::Integer::New(mysql_num_rows(res));\n}\n\nv8::Handle<v8::Value> _numfields(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n\n return v8::Integer::New(mysql_num_fields(res));\n}\n\nv8::Handle<v8::Value> _fetchnames(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n\n int cnt = mysql_num_fields(res);\n MYSQL_FIELD * fields = mysql_fetch_fields(res);\n v8::Handle<v8::Array> result = v8::Array::New(cnt);\n \n for(int i = 0; i < cnt; i++) {\n result->Set(v8::Integer::New(i), v8::String::New(fields[i].name));\n }\n \n return result;\n}\n\nv8::Handle<v8::Value> _fetcharrays(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n mysql_data_seek(res, 0);\n\n int x = mysql_num_fields(res);\n int y = mysql_num_rows(res);\n MYSQL_ROW row;\n v8::Handle<v8::Array> result = v8::Array::New(y);\n \n for (int i = 0; i < y; i++) {\n row = mysql_fetch_row(res);\n v8::Handle<v8::Array> item = v8::Array::New(x);\n result->Set(v8::Integer::New(i), item);\n for (int j=0; j<x; j++) {\n if (row[j] == NULL) {\n item->Set(v8::Integer::New(j), v8::Null());\n } else {\n item->Set(v8::Integer::New(j), v8::String::New(row[j]));\n }\n }\n }\n \n return result;\n}\n\nv8::Handle<v8::Value> _fetchobjects(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n mysql_data_seek(res, 0);\n\n int x = mysql_num_fields(res);\n int y = mysql_num_rows(res);\n MYSQL_FIELD * fields = mysql_fetch_fields(res);\n MYSQL_ROW row;\n v8::Handle<v8::Array> result = v8::Array::New(y);\n \n for (int i = 0; i < y; i++) {\n row = mysql_fetch_row(res);\n v8::Handle<v8::Object> item = v8::Object::New();\n result->Set(v8::Integer::New(i), item);\n for (int j=0; j<x; j++) {\n if (row[j] == NULL) {\n item->Set(v8::String::New(fields[j].name), v8::Null());\n } else {\n item->Set(v8::String::New(fields[j].name), v8::String::New(row[j]));\n }\n }\n }\n \n return result;\n}\n\nvoid setup_mysql(v8::Handle<v8::Object> target) {\n\/\/ v8::HandleScope handle_scope;\n\n v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_mysql);\n ft->SetClassName(v8::String::New(\"MySQL\"));\n\n v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();\n ot->SetInternalFieldCount(1); \/* connection *\/\n \n v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();\n pt->Set(v8::String::New(\"connect\"), v8::FunctionTemplate::New(_connect));\n pt->Set(v8::String::New(\"query\"), v8::FunctionTemplate::New(_query));\n pt->Set(v8::String::New(\"error\"), v8::FunctionTemplate::New(_error));\n pt->Set(v8::String::New(\"errno\"), v8::FunctionTemplate::New(_errno));\n pt->Set(v8::String::New(\"affectedRows\"), v8::FunctionTemplate::New(_affectedrows));\n pt->Set(v8::String::New(\"escape\"), v8::FunctionTemplate::New(_escape));\n pt->Set(v8::String::New(\"insertId\"), v8::FunctionTemplate::New(_insertid));\n \n rest = v8::FunctionTemplate::New(_result);\n rest->SetClassName(v8::String::New(\"Result\"));\n \n v8::Handle<v8::ObjectTemplate> resinst = rest->InstanceTemplate();\n resinst->SetInternalFieldCount(1);\n \n v8::Handle<v8::ObjectTemplate> resproto = rest->PrototypeTemplate();\n resproto->Set(v8::String::New(\"numRows\"), v8::FunctionTemplate::New(_numrows));\n resproto->Set(v8::String::New(\"numFields\"), v8::FunctionTemplate::New(_numfields));\n resproto->Set(v8::String::New(\"fetchNames\"), v8::FunctionTemplate::New(_fetchnames));\n resproto->Set(v8::String::New(\"fetchArrays\"), v8::FunctionTemplate::New(_fetcharrays));\n resproto->Set(v8::String::New(\"fetchObjects\"), v8::FunctionTemplate::New(_fetchobjects));\n\n target->Set(v8::String::New(\"MySQL\"), ft->GetFunction());\n}\n<commit_msg>mysql on windows<commit_after>#include <v8.h>\n\n#ifdef windows\n# include <my_global.h>\n#endif\n\n#include <mysql.h>\n#include <stdlib.h>\n\nv8::Handle<v8::FunctionTemplate> rest;\n\nv8::Handle<v8::Value> _mysql(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.This()->InternalFieldCount() == 0) {\n return v8::ThrowException(v8::String::New(\"Invalid call format. Use 'new MySQL()'\"));\n }\n args.This()->SetInternalField(0, v8::Boolean::New(false));\n \n return args.This();\n}\n\nv8::Handle<v8::Value> _connect(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 4) {\n return v8::ThrowException(v8::String::New(\"Invalid call format. Use 'mysql.connect(host, user, pass, db)'\"));\n }\n\n MYSQL *conn;\n \n v8::String::Utf8Value host(args[0]);\n v8::String::Utf8Value user(args[1]);\n v8::String::Utf8Value pass(args[2]);\n v8::String::Utf8Value db(args[3]);\n\t \n conn = mysql_init(NULL);\n\n if (!mysql_real_connect(conn, *host, *user, *pass, *db, 0, NULL, 0)){\n return v8::Boolean::New(false);\n } else {\n mysql_query(conn, \"SET NAMES 'utf8'\");\t\t\t\t \n args.This()->SetInternalField(0, v8::External::New((void *)conn));\n return args.This();\n } \n}\n\nv8::Handle<v8::Value> _query(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\t\t\n if (args.Length() < 1) {\n return v8::ThrowException(v8::String::New(\"No query specified\"));\n }\n v8::String::Utf8Value q(args[0]);\n \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n MYSQL_RES *res;\n mysql_query(conn, *q);\n res = mysql_store_result(conn);\n \n if (res) {\n v8::Handle<v8::Value> resargs[] = { v8::External::New((void *) res) };\n return rest->GetFunction()->NewInstance(1, resargs);\n } else {\n return v8::Boolean::New(false);\n }\n}\n\nv8::Handle<v8::Value> _error(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n\t \t \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n return v8::String::New(mysql_error(conn));\n}\n\nv8::Handle<v8::Value> _errno(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n return v8::Integer::New(mysql_errno(conn));\n}\n\nv8::Handle<v8::Value> _affectedrows(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n\t \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n return v8::Integer::New(mysql_affected_rows(conn));\n}\n\nv8::Handle<v8::Value> _insertid(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n\n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n return v8::Integer::New(mysql_insert_id(conn));\n}\n\nv8::Handle<v8::Value> _escape(const v8::Arguments &args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> c = args.This()->GetInternalField(0);\n if (c->IsFalse()) {\n return v8::ThrowException(v8::String::New(\"No connection established\"));\n }\n if (args.Length() < 1) {\n return v8::ThrowException(v8::String::New(\"Nothing to escape\"));\n }\n v8::String::Utf8Value str(args[0]);\n \n int len = args[0]->ToString()->Utf8Length();\n char * result = (char *) malloc((2*len+1) * sizeof(char));\n \n MYSQL * conn = reinterpret_cast<MYSQL *>(v8::Handle<v8::External>::Cast(c)->Value());\n\n int length = mysql_real_escape_string(conn, result, *str, len);\n\n return v8::String::New(result, length);\n}\n\nv8::Handle<v8::Value> _result(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n args.This()->SetInternalField(0, args[0]);\n return args.This();\n}\n\nv8::Handle<v8::Value> _numrows(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n\n return v8::Integer::New(mysql_num_rows(res));\n}\n\nv8::Handle<v8::Value> _numfields(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n\n return v8::Integer::New(mysql_num_fields(res));\n}\n\nv8::Handle<v8::Value> _fetchnames(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n\n int cnt = mysql_num_fields(res);\n MYSQL_FIELD * fields = mysql_fetch_fields(res);\n v8::Handle<v8::Array> result = v8::Array::New(cnt);\n \n for(int i = 0; i < cnt; i++) {\n result->Set(v8::Integer::New(i), v8::String::New(fields[i].name));\n }\n \n return result;\n}\n\nv8::Handle<v8::Value> _fetcharrays(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n mysql_data_seek(res, 0);\n\n int x = mysql_num_fields(res);\n int y = mysql_num_rows(res);\n MYSQL_ROW row;\n v8::Handle<v8::Array> result = v8::Array::New(y);\n \n for (int i = 0; i < y; i++) {\n row = mysql_fetch_row(res);\n v8::Handle<v8::Array> item = v8::Array::New(x);\n result->Set(v8::Integer::New(i), item);\n for (int j=0; j<x; j++) {\n if (row[j] == NULL) {\n item->Set(v8::Integer::New(j), v8::Null());\n } else {\n item->Set(v8::Integer::New(j), v8::String::New(row[j]));\n }\n }\n }\n \n return result;\n}\n\nv8::Handle<v8::Value> _fetchobjects(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> r = args.This()->GetInternalField(0);\n MYSQL_RES * res = reinterpret_cast<MYSQL_RES *>(v8::Handle<v8::External>::Cast(r)->Value());\n mysql_data_seek(res, 0);\n\n int x = mysql_num_fields(res);\n int y = mysql_num_rows(res);\n MYSQL_FIELD * fields = mysql_fetch_fields(res);\n MYSQL_ROW row;\n v8::Handle<v8::Array> result = v8::Array::New(y);\n \n for (int i = 0; i < y; i++) {\n row = mysql_fetch_row(res);\n v8::Handle<v8::Object> item = v8::Object::New();\n result->Set(v8::Integer::New(i), item);\n for (int j=0; j<x; j++) {\n if (row[j] == NULL) {\n item->Set(v8::String::New(fields[j].name), v8::Null());\n } else {\n item->Set(v8::String::New(fields[j].name), v8::String::New(row[j]));\n }\n }\n }\n \n return result;\n}\n\nvoid setup_mysql(v8::Handle<v8::Object> target) {\n\/\/ v8::HandleScope handle_scope;\n\n v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_mysql);\n ft->SetClassName(v8::String::New(\"MySQL\"));\n\n v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();\n ot->SetInternalFieldCount(1); \/* connection *\/\n \n v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();\n pt->Set(v8::String::New(\"connect\"), v8::FunctionTemplate::New(_connect));\n pt->Set(v8::String::New(\"query\"), v8::FunctionTemplate::New(_query));\n pt->Set(v8::String::New(\"error\"), v8::FunctionTemplate::New(_error));\n pt->Set(v8::String::New(\"errno\"), v8::FunctionTemplate::New(_errno));\n pt->Set(v8::String::New(\"affectedRows\"), v8::FunctionTemplate::New(_affectedrows));\n pt->Set(v8::String::New(\"escape\"), v8::FunctionTemplate::New(_escape));\n pt->Set(v8::String::New(\"insertId\"), v8::FunctionTemplate::New(_insertid));\n \n rest = v8::FunctionTemplate::New(_result);\n rest->SetClassName(v8::String::New(\"Result\"));\n \n v8::Handle<v8::ObjectTemplate> resinst = rest->InstanceTemplate();\n resinst->SetInternalFieldCount(1);\n \n v8::Handle<v8::ObjectTemplate> resproto = rest->PrototypeTemplate();\n resproto->Set(v8::String::New(\"numRows\"), v8::FunctionTemplate::New(_numrows));\n resproto->Set(v8::String::New(\"numFields\"), v8::FunctionTemplate::New(_numfields));\n resproto->Set(v8::String::New(\"fetchNames\"), v8::FunctionTemplate::New(_fetchnames));\n resproto->Set(v8::String::New(\"fetchArrays\"), v8::FunctionTemplate::New(_fetcharrays));\n resproto->Set(v8::String::New(\"fetchObjects\"), v8::FunctionTemplate::New(_fetchobjects));\n\n target->Set(v8::String::New(\"MySQL\"), ft->GetFunction());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 Pavel Shramov <shramov@mexmat.net>\n *\n * json2pb is free software; you can redistribute it and\/or modify\n * it under the terms of the MIT license. See LICENSE for details.\n *\/\n\n#include <errno.h>\n#include <jansson.h>\n\n\/\/ Backport json_boolean if needed (for jansson <2.4)\n\/\/ This macro comes from the Jansson docs, and is thus\n\/\/ Copyright (c) 2009-2014 Petri Lehtinen <petri@digip.org>, distributed under\n\/\/ the MIT license.\n#ifndef json_boolean\n#define json_boolean(val) ((val) ? json_true() : json_false())\n#endif\n\n#include <google\/protobuf\/message.h>\n#include <google\/protobuf\/descriptor.h>\n\n#include <json2pb.h>\n\n#include <stdexcept>\n#include <cstdio>\n\nnamespace {\n#include \"bin2ascii.h\"\n}\n\nusing google::protobuf::Message;\nusing google::protobuf::MessageFactory;\nusing google::protobuf::Descriptor;\nusing google::protobuf::FieldDescriptor;\nusing google::protobuf::EnumDescriptor;\nusing google::protobuf::EnumValueDescriptor;\nusing google::protobuf::Reflection;\n\nstruct json_autoptr {\n\tjson_t * ptr;\n\tjson_autoptr(json_t *json) : ptr(json) {}\n\t~json_autoptr() { if (ptr) json_decref(ptr); }\n\tjson_t * release() { json_t *tmp = ptr; ptr = 0; return tmp; }\n};\n\nclass j2pb_error : public std::exception {\n\tstd::string _error;\npublic:\n\tj2pb_error(const std::string &e) : _error(e) {}\n\tj2pb_error(const FieldDescriptor *field, const std::string &e) : _error(field->name() + \": \" + e) {}\n\tvirtual ~j2pb_error() throw() {};\n\n\tvirtual const char *what() const throw () { return _error.c_str(); };\n};\n\nstatic json_t * _pb2json(const Message& msg);\nstatic json_t * _field2json(const Message& msg, const FieldDescriptor *field, size_t index)\n{\n\tconst Reflection *ref = msg.GetReflection();\n\tconst bool repeated = field->is_repeated();\n\tjson_t *jf = 0;\n\tswitch (field->cpp_type())\n\t{\n#define _CONVERT(type, ctype, fmt, sfunc, afunc)\t\t\\\n\t\tcase FieldDescriptor::type: {\t\t\t\\\n\t\t\tconst ctype value = (repeated)?\t\t\\\n\t\t\t\tref->afunc(msg, field, index):\t\\\n\t\t\t\tref->sfunc(msg, field);\t\t\\\n\t\t\tjf = fmt(value);\t\t\t\\\n\t\t\tbreak;\t\t\t\t\t\\\n\t\t}\n\n\t\t_CONVERT(CPPTYPE_DOUBLE, double, json_real, GetDouble, GetRepeatedDouble);\n\t\t_CONVERT(CPPTYPE_FLOAT, double, json_real, GetFloat, GetRepeatedFloat);\n\t\t_CONVERT(CPPTYPE_INT64, json_int_t, json_integer, GetInt64, GetRepeatedInt64);\n\t\t_CONVERT(CPPTYPE_UINT64, json_int_t, json_integer, GetUInt64, GetRepeatedUInt64);\n\t\t_CONVERT(CPPTYPE_INT32, json_int_t, json_integer, GetInt32, GetRepeatedInt32);\n\t\t_CONVERT(CPPTYPE_UINT32, json_int_t, json_integer, GetUInt32, GetRepeatedUInt32);\n\t\t_CONVERT(CPPTYPE_BOOL, bool, json_boolean, GetBool, GetRepeatedBool);\n#undef _CONVERT\n\t\tcase FieldDescriptor::CPPTYPE_STRING: {\n\t\t\tstd::string scratch;\n\t\t\tconst std::string &value = (repeated)?\n\t\t\t\tref->GetRepeatedStringReference(msg, field, index, &scratch):\n\t\t\t\tref->GetStringReference(msg, field, &scratch);\n\t\t\tif (field->type() == FieldDescriptor::TYPE_BYTES)\n\t\t\t\tjf = json_string(b64_encode(value).c_str());\n\t\t\telse\n\t\t\t\tjf = json_string(value.c_str());\n\t\t\tbreak;\n\t\t}\n\t\tcase FieldDescriptor::CPPTYPE_MESSAGE: {\n\t\t\tconst Message& mf = (repeated)?\n\t\t\t\tref->GetRepeatedMessage(msg, field, index):\n\t\t\t\tref->GetMessage(msg, field);\n\t\t\tjf = _pb2json(mf);\n\t\t\tbreak;\n\t\t}\n\t\tcase FieldDescriptor::CPPTYPE_ENUM: {\n\t\t\tconst EnumValueDescriptor* ef = (repeated)?\n\t\t\t\tref->GetRepeatedEnum(msg, field, index):\n\t\t\t\tref->GetEnum(msg, field);\n\n\t\t\tjf = json_integer(ef->number());\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\tif (!jf) throw j2pb_error(field, \"Fail to convert to json\");\n\treturn jf;\n}\n\nstatic json_t * _pb2json(const Message& msg)\n{\n\tconst Descriptor *d = msg.GetDescriptor();\n\tconst Reflection *ref = msg.GetReflection();\n\tif (!d || !ref) return 0;\n\n\tjson_t *root = json_object();\n\tjson_autoptr _auto(root);\n\n \/\/std::cerr << msg.DebugString() << std::endl;\n\n\tstd::vector<const FieldDescriptor *> fields;\n\tref->ListFields(msg, &fields);\n\n\tfor (size_t i = 0; i != fields.size(); i++)\n\t{\n\t\tconst FieldDescriptor *field = fields[i];\n\t\tjson_t *jf = 0;\n\t\tif(field->is_repeated()) {\n\t\t\tsize_t count = ref->FieldSize(msg, field);\n\t\t\tif (!count) continue;\n\n\t\t\tjson_autoptr array(json_array());\n\t\t\tfor (size_t j = 0; j < count; j++)\n\t\t\t\tjson_array_append_new(array.ptr, _field2json(msg, field, j));\n\t\t\tjf = array.release();\n\t\t} else if (ref->HasField(msg, field))\n\t\t\tjf = _field2json(msg, field, 0);\n\t\telse\n\t\t\tcontinue;\n\n\t\tconst std::string &name = (field->is_extension())?field->full_name():field->name();\n\t\tjson_object_set_new(root, name.c_str(), jf);\n\t}\n\treturn _auto.release();\n}\n\nstatic bool string2bool(const char* str) {\n \/\/ If the string is empty, *str == 0.\n return (*str == 't' || *str == 'T' || *str == 'y' || *str == 'Y' || (*str >= '1' && *str <= '9')); \n}\n\nstatic void _json2pb(Message& msg, json_t *root);\nstatic void _json2field(Message &msg, const FieldDescriptor *field, json_t *jf)\n{\n\tconst Reflection *ref = msg.GetReflection();\n\tconst bool repeated = field->is_repeated();\n\tjson_error_t error;\n\n\tswitch (field->cpp_type())\n\t{\n#define _SET_OR_ADD(sfunc, afunc, value)\t\t\t\\\n\t\tdo {\t\t\t\t\t\t\\\n\t\t\tif (repeated)\t\t\t\t\\\n\t\t\t\tref->afunc(&msg, field, value);\t\\\n\t\t\telse\t\t\t\t\t\\\n\t\t\t\tref->sfunc(&msg, field, value);\t\\\n\t\t} while (0)\n\n#define _CONVERT_WITH_STRING(type, ctype, fmt, fromstringfunc, sfunc, afunc) \t\t\\\n\t\tcase FieldDescriptor::type: {\t\t\t\\\n\t\t\tctype value;\t\t\t\t\\\n\t\t\tint r = json_unpack_ex(jf, &error, JSON_STRICT, fmt, &value); \\\n if (r) { \\\n if (!json_is_string(jf)) throw j2pb_error(field, std::string(\"Failed to unpack or view as string: \") + error.text); \\\n\t\t\t const char * string_value = json_string_value(jf); \\\n value = fromstringfunc(string_value); \\\n } \\\n\t\t\t_SET_OR_ADD(sfunc, afunc, value);\t\\\n\t\t\tbreak;\t\t\t\t\t\\\n\t\t}\n\n\t\t_CONVERT_WITH_STRING(CPPTYPE_DOUBLE, double, \"F\", atof, SetDouble, AddDouble);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_FLOAT, double, \"F\", atof, SetFloat, AddFloat);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_INT64, json_int_t, \"I\", std::stoll, SetInt64, AddInt64);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_UINT64, json_int_t, \"I\", std::stoull, SetUInt64, AddUInt64);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_INT32, json_int_t, \"I\", atoi, SetInt32, AddInt32);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_UINT32, json_int_t, \"I\", std::stoul, SetUInt32, AddUInt32);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_BOOL, int, \"b\", string2bool, SetBool, AddBool);\n\n\t\tcase FieldDescriptor::CPPTYPE_STRING: {\n\t\t\tif (!json_is_string(jf))\n\t\t\t\tthrow j2pb_error(field, \"Not a string\");\n\t\t\tconst char * value = json_string_value(jf);\n\t\t\tif(field->type() == FieldDescriptor::TYPE_BYTES)\n\t\t\t\t_SET_OR_ADD(SetString, AddString, b64_decode(value));\n\t\t\telse\n\t\t\t\t_SET_OR_ADD(SetString, AddString, value);\n\t\t\tbreak;\n\t\t}\n\t\tcase FieldDescriptor::CPPTYPE_MESSAGE: {\n\t\t\tMessage *mf = (repeated)?\n\t\t\t\tref->AddMessage(&msg, field):\n\t\t\t\tref->MutableMessage(&msg, field);\n\t\t\t_json2pb(*mf, jf);\n\t\t\tbreak;\n\t\t}\n\t\tcase FieldDescriptor::CPPTYPE_ENUM: {\n\t\t\tconst EnumDescriptor *ed = field->enum_type();\n\t\t\tconst EnumValueDescriptor *ev = 0;\n\t\t\tif (json_is_integer(jf)) {\n\t\t\t\tev = ed->FindValueByNumber(json_integer_value(jf));\n\t\t\t} else if (json_is_string(jf)) {\n\t\t\t\tev = ed->FindValueByName(json_string_value(jf));\n\t\t\t} else\n\t\t\t\tthrow j2pb_error(field, \"Not an integer or string\");\n\t\t\tif (!ev)\n\t\t\t\tthrow j2pb_error(field, \"Enum value not found\");\n\t\t\t_SET_OR_ADD(SetEnum, AddEnum, ev);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n \n#undef _CONVERT_WITH_STRING\n#undef _SET_OR_ADD\n\t}\n}\n\nstatic void _json2pb(Message& msg, json_t *root)\n{\n\tconst Descriptor *d = msg.GetDescriptor();\n\tconst Reflection *ref = msg.GetReflection();\n\tif (!d || !ref) throw j2pb_error(\"No descriptor or reflection\");\n\n\tfor (void *i = json_object_iter(root); i; i = json_object_iter_next(root, i))\n\t{\n\t\tconst char *name = json_object_iter_key(i);\n\t\tjson_t *jf = json_object_iter_value(i);\n\n\t\tconst FieldDescriptor *field = d->FindFieldByName(name);\n\t\tif (!field)\n\t\t\tfield = ref->FindKnownExtensionByName(name);\n\t\t\t\/\/field = d->file()->FindExtensionByName(name);\n\n\t\tif (!field) throw j2pb_error(\"Unknown field: \" + std::string(name));\n\n\t\tint r = 0;\n\t\tif (field->is_repeated()) {\n\t\t\tif (!json_is_array(jf))\n\t\t\t\tthrow j2pb_error(field, \"Not array\");\n\t\t\tfor (size_t j = 0; j < json_array_size(jf); j++)\n\t\t\t\t_json2field(msg, field, json_array_get(jf, j));\n\t\t} else\n\t\t\t_json2field(msg, field, jf);\n\t}\n}\n\nvoid json2pb(Message &msg, const char *buf, size_t size)\n{\n\tjson_t *root;\n\tjson_error_t error;\n\n\troot = json_loadb(buf, size, 0, &error);\n\n\tif (!root)\n\t\tthrow j2pb_error(std::string(\"Load failed: \") + error.text);\n\n\tjson_autoptr _auto(root);\n\n\tif (!json_is_object(root))\n\t\tthrow j2pb_error(\"Malformed JSON: not an object\");\n\n\t_json2pb(msg, root);\n}\n\nvoid json2pb(Message &msg, FILE *fp)\n{\n json_t *root;\n\tjson_error_t error;\n\n\troot = json_loadf(fp, JSON_DISABLE_EOF_CHECK, &error);\n\n\tif (!root)\n\t\tthrow j2pb_error(std::string(\"Load failed: \") + error.text);\n\n\tjson_autoptr _auto(root);\n\n\tif (!json_is_object(root))\n\t\tthrow j2pb_error(\"Malformed JSON: not an object\");\n\n\t_json2pb(msg, root);\n}\n\nvoid json2pb(Message &msg, const std::string& data)\n{\n json2pb(msg, data.c_str(), data.size());\n}\n\nint json_dump_std_string(const char *buf, size_t size, void *data)\n{\n\tstd::string *s = (std::string *) data;\n\ts->append(buf, size);\n\treturn 0;\n}\n\nstd::string pb2json(const Message &msg)\n{\n\tstd::string r;\n\n\tjson_t *root = _pb2json(msg);\n\tjson_autoptr _auto(root);\n\tjson_dump_callback(root, json_dump_std_string, &r, 0);\n\treturn r;\n}\n<commit_msg>Quote all 64-bit integers like Protobuf does<commit_after>\/*\n * Copyright (c) 2013 Pavel Shramov <shramov@mexmat.net>\n *\n * json2pb is free software; you can redistribute it and\/or modify\n * it under the terms of the MIT license. See LICENSE for details.\n *\/\n\n#include <errno.h>\n#include <jansson.h>\n\n\/\/ Backport json_boolean if needed (for jansson <2.4)\n\/\/ This macro comes from the Jansson docs, and is thus\n\/\/ Copyright (c) 2009-2014 Petri Lehtinen <petri@digip.org>, distributed under\n\/\/ the MIT license.\n#ifndef json_boolean\n#define json_boolean(val) ((val) ? json_true() : json_false())\n#endif\n\n#include <google\/protobuf\/message.h>\n#include <google\/protobuf\/descriptor.h>\n\n#include <json2pb.h>\n\n#include <stdexcept>\n#include <cstdio>\n\nnamespace {\n#include \"bin2ascii.h\"\n}\n\nusing google::protobuf::Message;\nusing google::protobuf::MessageFactory;\nusing google::protobuf::Descriptor;\nusing google::protobuf::FieldDescriptor;\nusing google::protobuf::EnumDescriptor;\nusing google::protobuf::EnumValueDescriptor;\nusing google::protobuf::Reflection;\n\nstruct json_autoptr {\n\tjson_t * ptr;\n\tjson_autoptr(json_t *json) : ptr(json) {}\n\t~json_autoptr() { if (ptr) json_decref(ptr); }\n\tjson_t * release() { json_t *tmp = ptr; ptr = 0; return tmp; }\n};\n\nclass j2pb_error : public std::exception {\n\tstd::string _error;\npublic:\n\tj2pb_error(const std::string &e) : _error(e) {}\n\tj2pb_error(const FieldDescriptor *field, const std::string &e) : _error(field->name() + \": \" + e) {}\n\tvirtual ~j2pb_error() throw() {};\n\n\tvirtual const char *what() const throw () { return _error.c_str(); };\n};\n\nstatic json_t * _pb2json(const Message& msg);\nstatic json_t * _field2json(const Message& msg, const FieldDescriptor *field, size_t index)\n{\n\tconst Reflection *ref = msg.GetReflection();\n\tconst bool repeated = field->is_repeated();\n\tjson_t *jf = 0;\n\tswitch (field->cpp_type())\n\t{\n#define _CONVERT(type, ctype, fmt, sfunc, afunc)\t\t\\\n\t\tcase FieldDescriptor::type: {\t\t\t\\\n\t\t\tconst ctype value = (repeated)?\t\t\\\n\t\t\t\tref->afunc(msg, field, index):\t\\\n\t\t\t\tref->sfunc(msg, field);\t\t\\\n\t\t\tjf = fmt(value);\t\t\t\\\n\t\t\tbreak;\t\t\t\t\t\\\n\t\t}\n \n#define _CONVERT_AS_STRING(type, ctype, sfunc, afunc)\t\t\\\n\t\tcase FieldDescriptor::type: {\t\t\t\\\n\t\t\tconst ctype value = (repeated)?\t\t\\\n\t\t\t\tref->afunc(msg, field, index):\t\\\n\t\t\t\tref->sfunc(msg, field);\t\t\\\n std::string quoted = std::to_string(value); \\\n\t\t\tjf = json_string(quoted.c_str());\t\t\t\\\n\t\t\tbreak;\t\t\t\t\t\\\n\t\t}\n\n\t\t_CONVERT(CPPTYPE_DOUBLE, double, json_real, GetDouble, GetRepeatedDouble);\n\t\t_CONVERT(CPPTYPE_FLOAT, double, json_real, GetFloat, GetRepeatedFloat);\n\t\t_CONVERT_AS_STRING(CPPTYPE_INT64, json_int_t, GetInt64, GetRepeatedInt64);\n\t\t_CONVERT_AS_STRING(CPPTYPE_UINT64, json_int_t, GetUInt64, GetRepeatedUInt64);\n\t\t_CONVERT(CPPTYPE_INT32, json_int_t, json_integer, GetInt32, GetRepeatedInt32);\n\t\t_CONVERT(CPPTYPE_UINT32, json_int_t, json_integer, GetUInt32, GetRepeatedUInt32);\n\t\t_CONVERT(CPPTYPE_BOOL, bool, json_boolean, GetBool, GetRepeatedBool);\n#undef _CONVERT_AS_STRING\n#undef _CONVERT\n\t\tcase FieldDescriptor::CPPTYPE_STRING: {\n\t\t\tstd::string scratch;\n\t\t\tconst std::string &value = (repeated)?\n\t\t\t\tref->GetRepeatedStringReference(msg, field, index, &scratch):\n\t\t\t\tref->GetStringReference(msg, field, &scratch);\n\t\t\tif (field->type() == FieldDescriptor::TYPE_BYTES)\n\t\t\t\tjf = json_string(b64_encode(value).c_str());\n\t\t\telse\n\t\t\t\tjf = json_string(value.c_str());\n\t\t\tbreak;\n\t\t}\n\t\tcase FieldDescriptor::CPPTYPE_MESSAGE: {\n\t\t\tconst Message& mf = (repeated)?\n\t\t\t\tref->GetRepeatedMessage(msg, field, index):\n\t\t\t\tref->GetMessage(msg, field);\n\t\t\tjf = _pb2json(mf);\n\t\t\tbreak;\n\t\t}\n\t\tcase FieldDescriptor::CPPTYPE_ENUM: {\n\t\t\tconst EnumValueDescriptor* ef = (repeated)?\n\t\t\t\tref->GetRepeatedEnum(msg, field, index):\n\t\t\t\tref->GetEnum(msg, field);\n\n\t\t\tjf = json_integer(ef->number());\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\tif (!jf) throw j2pb_error(field, \"Fail to convert to json\");\n\treturn jf;\n}\n\nstatic json_t * _pb2json(const Message& msg)\n{\n\tconst Descriptor *d = msg.GetDescriptor();\n\tconst Reflection *ref = msg.GetReflection();\n\tif (!d || !ref) return 0;\n\n\tjson_t *root = json_object();\n\tjson_autoptr _auto(root);\n\n \/\/std::cerr << msg.DebugString() << std::endl;\n\n\tstd::vector<const FieldDescriptor *> fields;\n\tref->ListFields(msg, &fields);\n\n\tfor (size_t i = 0; i != fields.size(); i++)\n\t{\n\t\tconst FieldDescriptor *field = fields[i];\n\t\tjson_t *jf = 0;\n\t\tif(field->is_repeated()) {\n\t\t\tsize_t count = ref->FieldSize(msg, field);\n\t\t\tif (!count) continue;\n\n\t\t\tjson_autoptr array(json_array());\n\t\t\tfor (size_t j = 0; j < count; j++)\n\t\t\t\tjson_array_append_new(array.ptr, _field2json(msg, field, j));\n\t\t\tjf = array.release();\n\t\t} else if (ref->HasField(msg, field))\n\t\t\tjf = _field2json(msg, field, 0);\n\t\telse\n\t\t\tcontinue;\n\n\t\tconst std::string &name = (field->is_extension())?field->full_name():field->name();\n\t\tjson_object_set_new(root, name.c_str(), jf);\n\t}\n\treturn _auto.release();\n}\n\nstatic bool string2bool(const char* str) {\n \/\/ If the string is empty, *str == 0.\n return (*str == 't' || *str == 'T' || *str == 'y' || *str == 'Y' || (*str >= '1' && *str <= '9')); \n}\n\nstatic void _json2pb(Message& msg, json_t *root);\nstatic void _json2field(Message &msg, const FieldDescriptor *field, json_t *jf)\n{\n\tconst Reflection *ref = msg.GetReflection();\n\tconst bool repeated = field->is_repeated();\n\tjson_error_t error;\n\n\tswitch (field->cpp_type())\n\t{\n#define _SET_OR_ADD(sfunc, afunc, value)\t\t\t\\\n\t\tdo {\t\t\t\t\t\t\\\n\t\t\tif (repeated)\t\t\t\t\\\n\t\t\t\tref->afunc(&msg, field, value);\t\\\n\t\t\telse\t\t\t\t\t\\\n\t\t\t\tref->sfunc(&msg, field, value);\t\\\n\t\t} while (0)\n\n#define _CONVERT_WITH_STRING(type, ctype, fmt, fromstringfunc, sfunc, afunc) \t\t\\\n\t\tcase FieldDescriptor::type: {\t\t\t\\\n\t\t\tctype value;\t\t\t\t\\\n\t\t\tint r = json_unpack_ex(jf, &error, JSON_STRICT, fmt, &value); \\\n if (r) { \\\n if (!json_is_string(jf)) throw j2pb_error(field, std::string(\"Failed to unpack or view as string: \") + error.text); \\\n\t\t\t const char * string_value = json_string_value(jf); \\\n value = fromstringfunc(string_value); \\\n } \\\n\t\t\t_SET_OR_ADD(sfunc, afunc, value);\t\\\n\t\t\tbreak;\t\t\t\t\t\\\n\t\t}\n\n\t\t_CONVERT_WITH_STRING(CPPTYPE_DOUBLE, double, \"F\", atof, SetDouble, AddDouble);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_FLOAT, double, \"F\", atof, SetFloat, AddFloat);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_INT64, json_int_t, \"I\", std::stoll, SetInt64, AddInt64);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_UINT64, json_int_t, \"I\", std::stoull, SetUInt64, AddUInt64);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_INT32, json_int_t, \"I\", atoi, SetInt32, AddInt32);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_UINT32, json_int_t, \"I\", std::stoul, SetUInt32, AddUInt32);\n\t\t_CONVERT_WITH_STRING(CPPTYPE_BOOL, int, \"b\", string2bool, SetBool, AddBool);\n\n\t\tcase FieldDescriptor::CPPTYPE_STRING: {\n\t\t\tif (!json_is_string(jf))\n\t\t\t\tthrow j2pb_error(field, \"Not a string\");\n\t\t\tconst char * value = json_string_value(jf);\n\t\t\tif(field->type() == FieldDescriptor::TYPE_BYTES)\n\t\t\t\t_SET_OR_ADD(SetString, AddString, b64_decode(value));\n\t\t\telse\n\t\t\t\t_SET_OR_ADD(SetString, AddString, value);\n\t\t\tbreak;\n\t\t}\n\t\tcase FieldDescriptor::CPPTYPE_MESSAGE: {\n\t\t\tMessage *mf = (repeated)?\n\t\t\t\tref->AddMessage(&msg, field):\n\t\t\t\tref->MutableMessage(&msg, field);\n\t\t\t_json2pb(*mf, jf);\n\t\t\tbreak;\n\t\t}\n\t\tcase FieldDescriptor::CPPTYPE_ENUM: {\n\t\t\tconst EnumDescriptor *ed = field->enum_type();\n\t\t\tconst EnumValueDescriptor *ev = 0;\n\t\t\tif (json_is_integer(jf)) {\n\t\t\t\tev = ed->FindValueByNumber(json_integer_value(jf));\n\t\t\t} else if (json_is_string(jf)) {\n\t\t\t\tev = ed->FindValueByName(json_string_value(jf));\n\t\t\t} else\n\t\t\t\tthrow j2pb_error(field, \"Not an integer or string\");\n\t\t\tif (!ev)\n\t\t\t\tthrow j2pb_error(field, \"Enum value not found\");\n\t\t\t_SET_OR_ADD(SetEnum, AddEnum, ev);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n \n#undef _CONVERT_WITH_STRING\n#undef _SET_OR_ADD\n\t}\n}\n\nstatic void _json2pb(Message& msg, json_t *root)\n{\n\tconst Descriptor *d = msg.GetDescriptor();\n\tconst Reflection *ref = msg.GetReflection();\n\tif (!d || !ref) throw j2pb_error(\"No descriptor or reflection\");\n\n\tfor (void *i = json_object_iter(root); i; i = json_object_iter_next(root, i))\n\t{\n\t\tconst char *name = json_object_iter_key(i);\n\t\tjson_t *jf = json_object_iter_value(i);\n\n\t\tconst FieldDescriptor *field = d->FindFieldByName(name);\n\t\tif (!field)\n\t\t\tfield = ref->FindKnownExtensionByName(name);\n\t\t\t\/\/field = d->file()->FindExtensionByName(name);\n\n\t\tif (!field) throw j2pb_error(\"Unknown field: \" + std::string(name));\n\n\t\tint r = 0;\n\t\tif (field->is_repeated()) {\n\t\t\tif (!json_is_array(jf))\n\t\t\t\tthrow j2pb_error(field, \"Not array\");\n\t\t\tfor (size_t j = 0; j < json_array_size(jf); j++)\n\t\t\t\t_json2field(msg, field, json_array_get(jf, j));\n\t\t} else\n\t\t\t_json2field(msg, field, jf);\n\t}\n}\n\nvoid json2pb(Message &msg, const char *buf, size_t size)\n{\n\tjson_t *root;\n\tjson_error_t error;\n\n\troot = json_loadb(buf, size, 0, &error);\n\n\tif (!root)\n\t\tthrow j2pb_error(std::string(\"Load failed: \") + error.text);\n\n\tjson_autoptr _auto(root);\n\n\tif (!json_is_object(root))\n\t\tthrow j2pb_error(\"Malformed JSON: not an object\");\n\n\t_json2pb(msg, root);\n}\n\nvoid json2pb(Message &msg, FILE *fp)\n{\n json_t *root;\n\tjson_error_t error;\n\n\troot = json_loadf(fp, JSON_DISABLE_EOF_CHECK, &error);\n\n\tif (!root)\n\t\tthrow j2pb_error(std::string(\"Load failed: \") + error.text);\n\n\tjson_autoptr _auto(root);\n\n\tif (!json_is_object(root))\n\t\tthrow j2pb_error(\"Malformed JSON: not an object\");\n\n\t_json2pb(msg, root);\n}\n\nvoid json2pb(Message &msg, const std::string& data)\n{\n json2pb(msg, data.c_str(), data.size());\n}\n\nint json_dump_std_string(const char *buf, size_t size, void *data)\n{\n\tstd::string *s = (std::string *) data;\n\ts->append(buf, size);\n\treturn 0;\n}\n\nstd::string pb2json(const Message &msg)\n{\n\tstd::string r;\n\n\tjson_t *root = _pb2json(msg);\n\tjson_autoptr _auto(root);\n\tjson_dump_callback(root, json_dump_std_string, &r, 0);\n\treturn r;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <iostream>\n#include <utility>\n#include <cstdio>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/ptrace.h>\n#include <sys\/wait.h>\n#include <sys\/user.h>\n\n#include \"dwarf\/dwarf++.hh\"\n#include \"elf\/elf++.hh\"\n\n#include \"linenoise.h\"\n\nclass debugger {\npublic:\n debugger (std::string prog_name, pid_t pid)\n : m_prog_name{std::move(prog_name)}, m_pid{pid} {}\n\n void run();\nprivate:\n void handle_command(const std::string& line);\n\n std::string m_prog_name;\n pid_t m_pid;\n};\n\nvoid debugger::run() {\n char* line = nullptr;\n while((line = linenoise(\"minidbg> \")) != NULL) {\n handle_command(line);\n linenoiseHistoryAdd(line);\n linenoiseFree(line);\n }\n}\n\nvoid debugger::handle_command(const std::string& line) {\n if (line == \"cont\") {\n ptrace(PTRACE_CONT, m_pid, NULL, NULL);\n }\n else {\n std::cerr << \"Unknown command\\n\";\n }\n}\n\nvoid execute_debugger (const std::string& prog_name, pid_t pid) {\n int wait_status;\n wait(&wait_status);\n\n auto fd = open(prog_name.c_str(), O_RDONLY);\n\n elf::elf ef(elf::create_mmap_loader(fd));\n dwarf::dwarf dw(dwarf::elf::create_loader(ef));\n\n debugger dbg{prog_name, pid};\n dbg.run();\n}\n\nvoid execute_debugee (const std::string& prog_name) {\n if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) {\n std::cerr << \"Error in ptrace\\n\";\n return;\n }\n execl(prog_name.c_str(), prog_name.c_str(), NULL);\n}\n\nint main(int argc, char* argv[]) {\n auto prog = argv[1];\n\n auto pid = fork();\n if (pid == 0) {\n \/\/child\n execute_debugee(prog);\n\n }\n else if (pid >= 1) {\n \/\/parent\n execute_debugger(prog, pid);\n }\n else {\n std::cerr << \"Error forking\";\n }\n}\n<commit_msg>Early line and pc work<commit_after>#include <string>\n#include <iostream>\n#include <utility>\n#include <cstdio>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/ptrace.h>\n#include <sys\/wait.h>\n#include <sys\/user.h>\n\n#include \"dwarf\/dwarf++.hh\"\n#include \"elf\/elf++.hh\"\n\n#include \"linenoise.h\"\n\nclass debugger {\npublic:\n debugger (std::string prog_name, pid_t pid)\n : m_prog_name{std::move(prog_name)}, m_pid{pid} {\n auto fd = open(m_prog_name.c_str(), O_RDONLY);\n\n m_elf = elf::elf{elf::create_mmap_loader(fd)};\n m_dwarf = dwarf::dwarf{dwarf::elf::create_loader(m_elf)};\n }\n\n void run();\nprivate:\n void handle_command(const std::string& line);\n uint64_t get_pc();\n std::string get_current_line_entry();\n\n std::string m_prog_name;\n pid_t m_pid;\n dwarf::dwarf m_dwarf;\n elf::elf m_elf;\n};\n\nuint64_t debugger::get_pc() {\n struct user_regs_struct regs;\n std::cout << ptrace(PTRACE_GETREGS, m_pid, NULL, ®s) << std::endl;\n return regs.rip;\n}\n\nstd::string debugger::get_current_line_entry() {\n auto pc = get_pc();\n\n for (auto &cu : m_dwarf.compilation_units()) {\n if (die_pc_range(cu.root()).contains(pc)) {\n return \"\";\/\/at_name(cu.root());\n \/\/ Map PC to a line\n auto < = cu.get_line_table();\n auto it = lt.find_address(pc);\n if (it == lt.end()) {\n return \"\";\n }\n else {\n return it->get_description();\n }\n }\n }\n\n return \"\";\n}\n\nvoid debugger::run() {\n char* line = nullptr;\n while((line = linenoise(\"minidbg> \")) != NULL) {\n handle_command(line);\n linenoiseHistoryAdd(line);\n linenoiseFree(line);\n }\n}\n\nvoid debugger::handle_command(const std::string& line) {\n if (line == \"cont\") {\n ptrace(PTRACE_CONT, m_pid, NULL, NULL);\n }\n else if (line == \"line\") {\n std::cout << get_current_line_entry() << std::endl;\n }\n else if (line == \"pc\") {\n std::cout << std::hex << get_pc() << std::endl;\n }\n else {\n std::cerr << \"Unknown command\\n\";\n }\n}\n\nvoid execute_debugger (const std::string& prog_name, pid_t pid) {\n int wait_status;\n wait(&wait_status);\n\n debugger dbg{prog_name, pid};\n dbg.run();\n}\n\nvoid execute_debugee (const std::string& prog_name) {\n if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) {\n std::cerr << \"Error in ptrace\\n\";\n return;\n }\n execl(prog_name.c_str(), prog_name.c_str(), NULL);\n}\n\nint main(int argc, char* argv[]) {\n auto prog = argv[1];\n\n auto pid = fork();\n if (pid == 0) {\n \/\/child\n execute_debugee(prog);\n\n }\n else if (pid >= 1) {\n \/\/parent\n execute_debugger(prog, pid);\n }\n else {\n std::cerr << \"Error forking\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/point_types.h>\n\n#include <pcl\/registration\/ndt.h>\n#include <pcl\/filters\/approximate_voxel_grid.h>\n\n#include <pcl\/visualization\/pcl_visualizer.h>\n#include <boost\/thread\/thread.hpp>\n\nint\nmain (int argc, char** argv)\n{\n \/\/ Loading first scan of room.\n pcl::PointCloud<pcl::PointXYZ>::Ptr target_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n if (pcl::io::loadPCDFile<pcl::PointXYZ> (\"room_scan1.pcd\", *target_cloud) == -1)\n {\n PCL_ERROR (\"Couldn't read file room_scan1.pcd \\n\");\n return (-1);\n }\n std::cout << \"Loaded \" << target_cloud->size () << \" data points from room_scan1.pcd\" << std::endl;\n\n \/\/ Loading second scan of room from new perspective.\n pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n if (pcl::io::loadPCDFile<pcl::PointXYZ> (\"room_scan2.pcd\", *input_cloud) == -1)\n {\n PCL_ERROR (\"Couldn't read file room_scan2.pcd \\n\");\n return (-1);\n }\n std::cout << \"Loaded \" << input_cloud->size () << \" data points from room_scan2.pcd\" << std::endl;\n\n \/\/ Filtering input scan to roughly 10% of original size to increase speed of registration.\n pcl::PointCloud<pcl::PointXYZ>::Ptr filtered_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n pcl::ApproximateVoxelGrid<pcl::PointXYZ> approximate_voxel_filter;\n approximate_voxel_filter.setLeafSize (0.2, 0.2, 0.2);\n approximate_voxel_filter.setInputCloud (input_cloud);\n approximate_voxel_filter.filter (*filtered_cloud);\n std::cout << \"Filtered cloud contains \" << filtered_cloud->size ()\n << \" data points from room_scan2.pcd\" << std::endl;\n\n \/\/ Initializing Normal Distributions Transform (NDT).\n pcl::NormalDistributionsTransform<pcl::PointXYZ, pcl::PointXYZ> ndt;\n\n \/\/ Setting scale dependent NDT parameters\n \/\/ Setting minimum transformation difference for termination condition.\n ndt.setTransformationEpsilon (0.01);\n \/\/ Setting maximum step size for More-Thuente line search.\n ndt.setStepSize (0.1);\n \/\/Setting Resolution of NDT grid structure (VoxelGridCovariance).\n ndt.setResolution (1.0);\n\n \/\/ Setting max number of registration iterations.\n ndt.setMaximumIterations (35);\n\n \/\/ Setting point cloud to be aligned.\n ndt.setInputCloud (filtered_cloud);\n \/\/ Setting point cloud to be aligned to.\n ndt.setInputTarget (target_cloud);\n\n \/\/ Set initial alignment estimate found using robot odometry.\n Eigen::AngleAxisf init_rotation (0.6931, Eigen::Vector3f::UnitZ ());\n Eigen::Translation3f init_translation (1.79387, 0.720047, 0);\n Eigen::Matrix4f init_guess = (init_translation * init_rotation).matrix ();\n\n \/\/ Calculating required rigid transform to align the input cloud to the target cloud.\n pcl::PointCloud<pcl::PointXYZ>::Ptr output_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n ndt.align (*output_cloud, init_guess);\n\n std::cout << \"Normal Distributions Transform has converged:\" << ndt.hasConverged ()\n << \" score: \" << ndt.getFitnessScore () << std::endl;\n\n \/\/ Transforming unfiltered, input cloud using found transform.\n pcl::transformPointCloud (*input_cloud, *output_cloud, ndt.getFinalTransformation ());\n\n \/\/ Saving transformed input cloud.\n pcl::io::savePCDFileASCII (\"room_scan2_transformed.pcd\", *output_cloud);\n\n \/\/ Initializing point cloud visualizer\n boost::shared_ptr<pcl::visualization::PCLVisualizer>\n viewer_final (new pcl::visualization::PCLVisualizer (\"3D Viewer\"));\n viewer_final->setBackgroundColor (0, 0, 0);\n\n \/\/ Coloring and visualizing target cloud (red).\n pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>\n target_color (target_cloud, 255, 0, 0);\n viewer_final->addPointCloud<pcl::PointXYZ> (target_cloud, target_color, \"target cloud\");\n viewer_final->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE,\n 1, \"target cloud\");\n\n \/\/ Coloring and visualizing transformed input cloud (green).\n pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>\n output_color (output_cloud, 0, 255, 0);\n viewer_final->addPointCloud<pcl::PointXYZ> (output_cloud, output_color, \"output cloud\");\n viewer_final->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE,\n 1, \"output cloud\");\n\n \/\/ Starting visualizer\n viewer_final->addCoordinateSystem (1.0);\n viewer_final->initCameraParameters ();\n\n \/\/ Wait until visualizer window is closed.\n while (!viewer_final->wasStopped ())\n {\n viewer_final->spinOnce (100);\n boost::this_thread::sleep (boost::posix_time::microseconds (100000));\n }\n\n return (0);\n}\n<commit_msg>got rid of a deprecated API warning<commit_after>#include <iostream>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/point_types.h>\n\n#include <pcl\/registration\/ndt.h>\n#include <pcl\/filters\/approximate_voxel_grid.h>\n\n#include <pcl\/visualization\/pcl_visualizer.h>\n#include <boost\/thread\/thread.hpp>\n\nint\nmain (int argc, char** argv)\n{\n \/\/ Loading first scan of room.\n pcl::PointCloud<pcl::PointXYZ>::Ptr target_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n if (pcl::io::loadPCDFile<pcl::PointXYZ> (\"room_scan1.pcd\", *target_cloud) == -1)\n {\n PCL_ERROR (\"Couldn't read file room_scan1.pcd \\n\");\n return (-1);\n }\n std::cout << \"Loaded \" << target_cloud->size () << \" data points from room_scan1.pcd\" << std::endl;\n\n \/\/ Loading second scan of room from new perspective.\n pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n if (pcl::io::loadPCDFile<pcl::PointXYZ> (\"room_scan2.pcd\", *input_cloud) == -1)\n {\n PCL_ERROR (\"Couldn't read file room_scan2.pcd \\n\");\n return (-1);\n }\n std::cout << \"Loaded \" << input_cloud->size () << \" data points from room_scan2.pcd\" << std::endl;\n\n \/\/ Filtering input scan to roughly 10% of original size to increase speed of registration.\n pcl::PointCloud<pcl::PointXYZ>::Ptr filtered_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n pcl::ApproximateVoxelGrid<pcl::PointXYZ> approximate_voxel_filter;\n approximate_voxel_filter.setLeafSize (0.2, 0.2, 0.2);\n approximate_voxel_filter.setInputCloud (input_cloud);\n approximate_voxel_filter.filter (*filtered_cloud);\n std::cout << \"Filtered cloud contains \" << filtered_cloud->size ()\n << \" data points from room_scan2.pcd\" << std::endl;\n\n \/\/ Initializing Normal Distributions Transform (NDT).\n pcl::NormalDistributionsTransform<pcl::PointXYZ, pcl::PointXYZ> ndt;\n\n \/\/ Setting scale dependent NDT parameters\n \/\/ Setting minimum transformation difference for termination condition.\n ndt.setTransformationEpsilon (0.01);\n \/\/ Setting maximum step size for More-Thuente line search.\n ndt.setStepSize (0.1);\n \/\/Setting Resolution of NDT grid structure (VoxelGridCovariance).\n ndt.setResolution (1.0);\n\n \/\/ Setting max number of registration iterations.\n ndt.setMaximumIterations (35);\n\n \/\/ Setting point cloud to be aligned.\n ndt.setInputSource (filtered_cloud);\n \/\/ Setting point cloud to be aligned to.\n ndt.setInputTarget (target_cloud);\n\n \/\/ Set initial alignment estimate found using robot odometry.\n Eigen::AngleAxisf init_rotation (0.6931, Eigen::Vector3f::UnitZ ());\n Eigen::Translation3f init_translation (1.79387, 0.720047, 0);\n Eigen::Matrix4f init_guess = (init_translation * init_rotation).matrix ();\n\n \/\/ Calculating required rigid transform to align the input cloud to the target cloud.\n pcl::PointCloud<pcl::PointXYZ>::Ptr output_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n ndt.align (*output_cloud, init_guess);\n\n std::cout << \"Normal Distributions Transform has converged:\" << ndt.hasConverged ()\n << \" score: \" << ndt.getFitnessScore () << std::endl;\n\n \/\/ Transforming unfiltered, input cloud using found transform.\n pcl::transformPointCloud (*input_cloud, *output_cloud, ndt.getFinalTransformation ());\n\n \/\/ Saving transformed input cloud.\n pcl::io::savePCDFileASCII (\"room_scan2_transformed.pcd\", *output_cloud);\n\n \/\/ Initializing point cloud visualizer\n boost::shared_ptr<pcl::visualization::PCLVisualizer>\n viewer_final (new pcl::visualization::PCLVisualizer (\"3D Viewer\"));\n viewer_final->setBackgroundColor (0, 0, 0);\n\n \/\/ Coloring and visualizing target cloud (red).\n pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>\n target_color (target_cloud, 255, 0, 0);\n viewer_final->addPointCloud<pcl::PointXYZ> (target_cloud, target_color, \"target cloud\");\n viewer_final->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE,\n 1, \"target cloud\");\n\n \/\/ Coloring and visualizing transformed input cloud (green).\n pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>\n output_color (output_cloud, 0, 255, 0);\n viewer_final->addPointCloud<pcl::PointXYZ> (output_cloud, output_color, \"output cloud\");\n viewer_final->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE,\n 1, \"output cloud\");\n\n \/\/ Starting visualizer\n viewer_final->addCoordinateSystem (1.0);\n viewer_final->initCameraParameters ();\n\n \/\/ Wait until visualizer window is closed.\n while (!viewer_final->wasStopped ())\n {\n viewer_final->spinOnce (100);\n boost::this_thread::sleep (boost::posix_time::microseconds (100000));\n }\n\n return (0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\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 10\/21\/2014\n * \\author Jan Issac (jan.issac@gmail.com)\n * \\author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * Max-Planck-Institute for Intelligent Systems,\n * University of Southern California\n *\/\n\n#ifndef FL__FILTER__GAUSSIAN__POINT_SET_GAUSSIAN_HPP\n#define FL__FILTER__GAUSSIAN__POINT_SET_GAUSSIAN_HPP\n\n#include <map>\n\n#include <Eigen\/Dense>\n\n#include <fast_filtering\/distributions\/gaussian.hpp>\n#include <fast_filtering\/filtering_library\/exception\/exception.hpp>\n#include <fast_filtering\/filtering_library\/filter\/filter_interface.hpp>\n\nnamespace fl\n{\n\n\/\/ Forward declaration\ntemplate <typename Point, int POINT_COUNT> class PointSetGaussian;\n\n\/**\n * Trait struct of a PointSetGaussian\n *\/\ntemplate <typename Point_, int POINT_COUNT>\nstruct Traits<PointSetGaussian<Point_, POINT_COUNT>>\n{\n \/**\n * @brief Gaussian sample type\n *\/\n typedef Point_ Point;\n\n \/**\n * \\brief Weight harbors the weights of a point. For each of the first two\n * moments there is a separate weight.\n *\n * Generally a single weight suffices. However, some transforms utilize\n * different weights for each moment to select a set of points representing\n * the underlying moments.\n *\/\n struct Weight\n {\n \/**\n * First moment (mean) point weight\n *\/\n double w_mean;\n\n \/**\n * Second centered moment (covariance) point weight\n *\/\n double w_cov;\n };\n\n \/**\n * \\typedef PointMatrix\n *\n * \\brief Point container type\n *\n * \\details\n * The point container type has a fixed-size dimension of a point\n * and the number of the points is statically known.\n *\/\n typedef Eigen::Matrix<\n typename Point::Scalar,\n Point::SizeAtCompileTime,\n POINT_COUNT\n > PointMatrix;\n\n \/**\n * \\typedef Weight\n *\n * Weight list of all points\n *\/\n typedef std::vector<Weight> WeightVector;\n\n \/**\n * \\typedef Base\n *\n * Base class type\n *\/\n typedef ff::Gaussian<Point> Base;\n};\n\n\/**\n * \\class PointSetGaussian\n *\n * PointSetGaussian is Gaussian distribution represented by a set of points\n * (a statistic)\n *\n * \\tparam Point Gaussian variable type\n * \\tparam POINT_COUNT Number of points representing the gaussian\n *\/\ntemplate <typename Point_, int POINT_COUNT = Eigen::Dynamic>\nclass PointSetGaussian:\n public ff::Gaussian<Point_>\n{\npublic:\n typedef PointSetGaussian<Point_, POINT_COUNT> This;\n\n typedef typename Traits<This>::Base Base;\n typedef typename Traits<This>::Point Point;\n typedef typename Traits<This>::PointMatrix PointMatrix;\n typedef typename Traits<This>::Weight Weight;\n typedef typename Traits<This>::WeightVector WeightVector;\n\n using Base::Mean;\n using Base::Covariance;\n using Base::Precision;\n using Base::SquareRoot;\n using Base::DiagonalCovariance;\n using Base::DiagonalSquareRoot;\n using Base::DiagonalPrecision;\n using Base::SetStandard;\n using Base::Probability;\n using Base::LogProbability;\n using Base::Dimension;\n using Base::NoiseDimension;\n\npublic:\n \/**\n * Creates a PointSetGaussian\n *\n * \\param dimension Sample space dimension\n * \\param point_count Number of points representing the Gaussian\n *\/\n PointSetGaussian(size_t point_count = POINT_COUNT > 0 ? POINT_COUNT : 0,\n size_t dimension = Point::SizeAtCompileTime)\n : Base(dimension),\n points_(Dimension(), point_count),\n weights_(point_count)\n {\n points_.setZero();\n\n double weight = (point_count > 0) ? 1.\/double(point_count) : 0;\n std::fill(weights_.begin(), weights_.end(), Weight{weight, weight});\n }\n\n \/**\n * \\brief Overridable default constructor\n *\/\n virtual ~PointSetGaussian() { }\n\n \/**\n * \\return i-th point\n *\n * \\param i Index of requested point\n *\n * \\throw OutOfBoundsException\n *\/\n Point point(size_t i) const\n {\n if (is_out_of_bounds(i))\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, points_.cols()));\n }\n\n return points_.col(i);\n }\n\n \/**\n * \\return weight of i-th point assuming both weights are the same\n *\n * \\param i Index of requested point\n *\n * \\throw OutOfBoundsException\n *\/\n double weight(size_t i)\n {\n if (is_out_of_bounds(i))\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, weights_.size()));\n }\n\n return weights_[i].m_mean;\n }\n\n \/**\n * \\return weight of i-th point\n *\n * \\param i Index of requested point\n *\n * \\throw OutOfBoundsException\n *\/\n const Weight& weight(size_t i) const\n {\n if (is_out_of_bounds(i))\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, points_.cols()));\n }\n\n return weights_[i];\n }\n\n \/**\n * \\return Point matrix\n *\/\n const PointMatrix& points() const noexcept\n {\n return points_;\n }\n\n \/**\n * \\return point weights vector\n *\/\n const WeightVector& weights() const noexcept\n {\n return weights_;\n }\n\n \/**\n * Sets a given point at position i\n *\n * \\param i Index of point\n * \\param p The new point\n *\n * \\throw OutOfBoundsException\n *\/\n void point(size_t i, Point p)\n {\n if (is_out_of_bounds(i))\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, points_.cols()));\n }\n\n points_.col(i) = p;\n }\n\n \/**\n * Sets a given point at position i along with its weights\n *\n * \\param i Index of point\n * \\param p The new point\n * \\param w Point weights. The weights determinaing the first two\n * moments are the same\n *\n * \\throw OutOfBoundsException\n *\/\n void point(size_t i, Point p, double w)\n {\n point(i, p, Weight{w, w});\n }\n\n \/**\n * Sets a given point at position i along with its weights\n *\n * \\param i Index of point\n * \\param p The new point\n * \\param w_mean point weight used to compute the first moment\n * \\param w_cov point weight used to compute the second centered moment\n *\n * \\throw OutOfBoundsException\n *\/\n void point(size_t i, Point p, double w_mean , double w_cov)\n {\n point(i, p, Weight{w_mean, w_cov});\n }\n\n \/**\n * Sets a given point at given position i along with its weights\n *\n * \\param i Index of point\n * \\param p The new point\n * \\param weights point weights\n *\n * \\throw OutOfBoundsException\n *\/\n void point(size_t i, Point p, Weight weights)\n {\n if (is_out_of_bounds(i))\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, points_.cols()));\n }\n\n points_.col(i) = p;\n weights_[i] = weights;\n }\n\n \/**\n * Sets a given weight of a point at position i\n *\n * \\param i Index of point\n * \\param w Point weights. The weights determinaing the first two\n * moments are the same\n *\n * \\throw OutOfBoundsException\n *\/\n void weight(size_t i, double w)\n {\n if (is_out_of_bounds(i))\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, weights_.size()));\n }\n\n weights_[i] = Weight{w, w};\n }\n\n \/**\n * Sets given weights of a point at position i\n *\n * \\param i Index of point\n * \\param w_mean point weight used to compute the first moment\n * \\param w_cov point weight used to compute the second centered moment\n *\n * \\throw OutOfBoundsException\n *\/\n void weight(size_t i, Point p, double w_mean , double w_cov)\n {\n if (is_out_of_bounds(i))\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, weights_.size()));\n }\n\n weights_[i] = Weight{w_mean, w_cov};\n }\n\n \/**\n * Sets given weights of a point at position i\n *\n * \\param i Index of point\n * \\param weights point weights\n *\n * \\throw OutOfBoundsException\n *\/\n void weight(size_t i, Weight weights)\n {\n if (is_out_of_bounds(i))\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, weights_.size()));\n }\n\n weights_[i] = weights;\n }\n\n \/**\n * @return Centered points matrix.\n *\n * Creates a PointMatrix populated with zero mean points\n *\/\n PointMatrix centered_points() const noexcept\n {\n PointMatrix centered(points_.rows(), points_.cols);\n\n const size_t point_count = points_.cols();\n for (size_t i = 0; i < point_count; ++i)\n {\n centered.col(i) = points_.col(i) - Mean();\n }\n\n return centered;\n }\n\nprotected:\n \/**\n * \\return True of index i is out of bounds\n *\n * \\param i Point index\n *\n * \\internal asserts size equallity of points and weights\n *\/\n bool is_out_of_bounds(size_t i) const noexcept\n {\n assert(points_.cols() == weights_.size());\n\n return !(i < weights_.size());\n }\n\nprotected:\n \/**\n * \\brief point container\n *\/\n PointMatrix points_;\n\n \/**\n * \\brief weight container\n *\/\n WeightVector weights_;\n};\n\n}\n\n#endif\n<commit_msg>Extended point set gaussian<commit_after>\/*\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 10\/21\/2014\n * \\author Jan Issac (jan.issac@gmail.com)\n * Max-Planck-Institute for Intelligent Systems,\n * University of Southern California\n *\/\n\n#ifndef FL__FILTER__GAUSSIAN__POINT_SET_GAUSSIAN_HPP\n#define FL__FILTER__GAUSSIAN__POINT_SET_GAUSSIAN_HPP\n\n#include <map>\n#include <cmath>\n#include <type_traits>\n\n#include <Eigen\/Dense>\n\n#include <fast_filtering\/distributions\/gaussian.hpp>\n#include <fast_filtering\/filtering_library\/exception\/exception.hpp>\n#include <fast_filtering\/filtering_library\/filter\/filter_interface.hpp>\n\nnamespace fl\n{\n\n\/\/ Forward declaration\ntemplate <typename Point, int Points_> class PointSetGaussian;\n\n\/**\n * Trait struct of a PointSetGaussian\n *\/\ntemplate <typename Point_, int Points_>\nstruct Traits<PointSetGaussian<Point_, Points_>>\n{ \n \/**\n * \\brief Gaussian sample type\n *\/\n typedef Point_ Point;\n\n \/**\n * \\brief Base class type\n *\/\n typedef ff::Gaussian<Point> Base;\n\n \/* Gaussian Base types *\/\n typedef typename ff::Traits<Base>::Vector Vector;\n typedef typename ff::Traits<Base>::Scalar Scalar;\n typedef typename ff::Traits<Base>::Noise Noise;\n typedef typename ff::Traits<Base>::Operator Operator;\n\n \/**\n * \\brief Number of points for fixed-size set\n *\/\n enum\n {\n \/**\n * \\brief Gaussian dimension\n *\n * For fixed-size Point type and hence a fixed-size Gaussian, the\n * \\c Dimension value is greater zero. Dynamic-size Gaussians have the\n * dymension Eigen::Dynamic.\n *\/\n Dimension = ff::Traits<Base>::Dimension,\n\n \/**\n * \\brief Number of points which provided by the PointSetGaussian.\n *\n * If the number of points is unknown and there for dynamic, then\n * NumberOfPoints is set to Eigen::Dynamic\n *\/\n NumberOfPoints = IsFixed<Points_>() ? Points_ : Eigen::Dynamic\n };\n\n \/**\n * \\brief Weight harbors the weights of a point. For each of the first two\n * moments there is a separate weight.\n *\n *\n * Generally a single weight suffices. However, some transforms utilize\n * different weights for each moment to select a set of points representing\n * the underlying moments.\n *\/\n struct Weight\n {\n \/**\n * First moment (mean) point weight\n *\/\n double w_mean;\n\n \/**\n * Second centered moment (covariance) point weight\n *\/\n double w_cov;\n };\n\n \/**\n * \\brief Point container type\n *\n * \\details\n * The point container type has a fixed-size dimension of a point\n * and the number of the points is statically known.\n *\/\n typedef Eigen::Matrix<Scalar, Dimension, Points_ > PointMatrix;\n\n \/**\n * @brief WeightVector\n *\/\n typedef Eigen::Matrix<\n typename Point::Scalar,\n Points_,\n 1\n > WeightVector;\n\n \/**\n * \\brief Weight list of all points\n *\/\n typedef std::vector<Weight> Weights;\n\n\n};\n\n\/**\n * \\class PointSetGaussian\n *\n * PointSetGaussian is Gaussian distribution represented by a set of points\n * (a statistic)\n *\n * \\tparam Point Gaussian variable type\n * \\tparam Points_ Number of points representing the gaussian\n *\/\ntemplate <typename Point_, int Points_ = Eigen::Dynamic>\nclass PointSetGaussian:\n public ff::Gaussian<Point_>\n{\npublic:\n typedef PointSetGaussian<Point_, Points_> This;\n\n typedef typename Traits<This>::Base Base;\n typedef typename Traits<This>::Scalar Scalar;\n typedef typename Traits<This>::Operator Operator;\n typedef typename Traits<This>::Noise Noise;\n typedef typename Traits<This>::Point Point;\n typedef typename Traits<This>::PointMatrix PointMatrix;\n typedef typename Traits<This>::Weight Weight;\n typedef typename Traits<This>::Weights Weights;\n typedef typename Traits<This>::WeightVector WeightVector; \n\n using Base::Mean;\n using Base::Covariance;\n using Base::Precision;\n using Base::SquareRoot;\n using Base::DiagonalCovariance;\n using Base::DiagonalSquareRoot;\n using Base::DiagonalPrecision;\n using Base::SetStandard;\n using Base::Probability;\n using Base::LogProbability;\n using Base::Dimension;\n using Base::NoiseDimension;\n\npublic:\n \/**\n * Creates a PointSetGaussian\n *\n * \\param points_count Number of points representing the Gaussian\n * \\param dimension Sample space dimension\n *\/\n PointSetGaussian(size_t points_count = (Points_ > 0) ? Points_ : 0,\n size_t dimension = Point::RowsAtCompileTime)\n : Base(dimension),\n points_(Dimension(), points_count),\n weights_(points_count),\n changes_staged_(false)\n {\n assert(points_count >= 0);\n static_assert(Points_ >= Eigen::Dynamic, \"Invalid point count\");\n\n points_.setZero();\n\n double weight = (points_count > 0) ? 1.\/double(points_count) : 0;\n std::fill(weights_.begin(), weights_.end(), Weight{weight, weight});\n }\n\n \/**\n * \\brief Overridable default constructor\n *\/\n virtual ~PointSetGaussian() { }\n\n \/**\n * Resizes a dynamic-size PointSetGaussian to a desired. For\n *\n * \\param Points_ Number of points\n *\n * \\throws ResizingFixedSizeEntityException\n *\/\n void resize(size_t points_count)\n {\n if (weights_.size() == points_count) return;\n\n if (IsFixed<Points_>())\n {\n BOOST_THROW_EXCEPTION(\n fl::ResizingFixedSizeEntityException(weights_.size(),\n points_count,\n \"poit set Gaussian\"));\n }\n\n points_.setZero(Dimension(), points_count);\n\n weights_.resize(points_count);\n const double weight = (points_count > 0)? 1. \/ double(points_count) : 0;\n std::fill(weights_.begin(), weights_.end(), Weight{weight, weight});\n }\n\n \/**\n * Sets the new Gaussian dimension for dynamic-size Gaussian (not to confuse\n * with the number of points)\n *\n * @param new_dimension New Gaussian dimension\n *\/\n virtual void Dimension(size_t new_dimension)\n {\n Base::Dimension(new_dimension);\n points_.resize(Dimension(), count_points());\n }\n\n \/**\n * @return The number of points\n *\/\n size_t count_points() const\n {\n return points_.cols();\n }\n\n \/**\n * \\return i-th point\n *\n * \\param i Index of requested point\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n Point point(size_t i) const\n {\n assert_bounds(i);\n\n return points_.col(i);\n }\n\n \/**\n * \\return weight of i-th point assuming both weights are the same\n *\n * \\param i Index of requested point\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n double weight(size_t i)\n {\n assert_bounds(i);\n\n return weights_[i].w_mean;\n }\n\n \/**\n * \\return weights of i-th point\n *\n * \\param i Index of requested point\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n const Weight& weights(size_t i) const\n {\n assert_bounds(i);\n\n return weights_[i];\n }\n\n \/**\n * \\return Point matrix\n *\/\n const PointMatrix& points() const noexcept\n {\n return points_;\n }\n\n \/**\n * \\return point weights vector\n *\/\n const Weights& weights() const noexcept\n {\n return weights_;\n }\n\n \/**\n * @return Returns the weights for the mean of the points as a vector\n *\/\n WeightVector mean_weights_vector() const noexcept\n {\n const size_t point_count = count_points();\n\n WeightVector weight_vec(point_count);\n\n for (size_t i = 0; i < point_count; ++i)\n {\n weight_vec(i) = weights_[i].w_mean;\n }\n\n return weight_vec;\n }\n\n \/**\n * @return Returns the weights for the covariance of the points as a vector\n *\/\n WeightVector covariance_weights_vector() const noexcept\n {\n const size_t point_count = count_points();\n\n WeightVector weight_vec(point_count);\n\n for (size_t i = 0; i < point_count; ++i)\n {\n weight_vec(i) = weights_[i].w_cov;\n }\n\n return weight_vec;\n }\n\n \/**\n * Sets a given point at position i\n *\n * \\param i Index of point\n * \\param p The new point\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n void point(size_t i, Point p)\n {\n assert_bounds(i);\n\n points_.col(i) = p;\n stage_point_changes();\n }\n\n \/**\n * Sets a given point at position i along with its weights\n *\n * \\param i Index of point\n * \\param p The new point\n * \\param w Point weights. The weights determinaing the first two\n * moments are the same\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n void point(size_t i, Point p, double w)\n {\n point(i, p, Weight{w, w}); \n }\n\n \/**\n * Sets a given point at position i along with its weights\n *\n * \\param i Index of point\n * \\param p The new point\n * \\param w_mean point weight used to compute the first moment\n * \\param w_cov point weight used to compute the second centered moment\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n void point(size_t i, Point p, double w_mean , double w_cov)\n {\n point(i, p, Weight{w_mean, w_cov});\n }\n\n \/**\n * Sets a given point at given position i along with its weights\n *\n * \\param i Index of point\n * \\param p The new point\n * \\param weights point weights\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n void point(size_t i, Point p, Weight weights)\n {\n assert_bounds(i);\n\n points_.col(i) = p;\n weights_[i] = weights;\n stage_point_changes();\n }\n\n \/**\n * Sets a given weight of a point at position i\n *\n * \\param i Index of point\n * \\param w Point weights. The weights determinaing the first two\n * moments are the same\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n void weight(size_t i, double w)\n {\n weight(i, Weight{w, w});\n }\n\n \/**\n * Sets given weights of a point at position i\n *\n * \\param i Index of point\n * \\param w_mean point weight used to compute the first moment\n * \\param w_cov point weight used to compute the second centered moment\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n void weight(size_t i, double w_mean , double w_cov)\n {\n weight(i, Weight{w_mean, w_cov});\n }\n\n \/**\n * Sets given weights of a point at position i\n *\n * \\param i Index of point\n * \\param weights point weights\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n void weight(size_t i, Weight weights)\n {\n assert_bounds(i);\n\n weights_[i] = weights;\n stage_point_changes();\n }\n\n void commit_point_changes()\n {\n changes_staged_ = false;\n\n if (moments_dirty_)\n {\n PointMatrix P = weighted_centered_points();\n Covariance(P * P.transpose());\n Mean(weighted_mean());\n\n moments_dirty_ = false;\n }\n }\n\n \/**\n * @return Centered points matrix.\n *\n * Creates a PointMatrix populated with zero mean points\n *\/\n PointMatrix centered_points() const noexcept\n {\n PointMatrix centered(points_.rows(), points_.cols());\n\n const Point weighted_mean = weighted_mean();\n const size_t point_count = points_.cols();\n for (size_t i = 0; i < point_count; ++i)\n {\n centered.col(i) = points_.col(i) - weighted_mean;\n }\n\n return centered;\n }\n\n \/**\n * @return Weighted centered points matrix.\n *\n * Creates a PointMatrix populated with weighted zero mean points\n *\/\n PointMatrix weighted_centered_points() const noexcept\n {\n PointMatrix centered(points_.rows(), points_.cols());\n\n const Point mean = weighted_mean();\n const size_t point_count = points_.cols();\n for (size_t i = 0; i < point_count; ++i)\n {\n centered.col(i) =\n weights_[i].w_cov * (points_.col(i) - mean);\n }\n\n return centered;\n }\n\n \/**\n * @return The weighted mean of all points\n *\/\n Point weighted_mean() const\n {\n Point weighted_mean;\n weighted_mean.setZero(Dimension());\n\n const size_t point_count = points_.cols();\n for (size_t i = 0; i < point_count; ++i)\n {\n weighted_mean += weights_[i].w_mean * points_.col(i);\n }\n\n return weighted_mean;\n }\n\n \/**\n * The point set becomes dirty once one of moment representations has been\n * changed.\n *\n * @return point set dirty status\n *\/\n bool is_point_set_dirty() const noexcept\n {\n return point_set_dirty_;\n }\n\n \/* Gaussian interface *\/\n\n virtual Vector Mean() const\n {\n if (moments_dirty_)\n {\n\n }\n\n return mean_;\n }\n\n virtual void Mean(const Vector& mean) noexcept\n {\n point_set_dirty_ = true;\n Base::Mean(mean);\n }\n\n virtual void Covariance(const Operator& covariance) noexcept\n {\n point_set_dirty_ = true;\n Covariance(covariance);\n }\n\n virtual void SquareRoot(const Operator& square_root) noexcept\n {\n point_set_dirty_ = true;\n SquareRoot(square_root);\n }\n\n virtual void Precision(const Operator& precision) noexcept\n {\n point_set_dirty_ = true;\n Precision(precision);\n }\n\n virtual void DiagonalCovariance(const Operator& diag_covariance) noexcept\n {\n point_set_dirty_ = true;\n DiagonalCovariance(diag_covariance);\n }\n\n virtual void DiagonalSquareRoot(const Operator& diag_square_root) noexcept\n {\n point_set_dirty_ = true;\n DiagonalSquareRoot(diag_square_root);\n }\n\n virtual void DiagonalPrecision(const Operator& diag_precision) noexcept\n {\n point_set_dirty_ = true;\n DiagonalPrecision(diag_precision);\n }\n\nprotected:\n \/**\n * Asserts that the specified index is within bounds and that the dimension\n * is greater zero.\n *\n * \\param i Point index\n *\n * \\internal asserts size equallity of points and weights\n *\n * \\throws OutOfBoundsException\n * \\throws ZeroDimensionException\n *\/\n void assert_bounds(size_t i) const\n {\n assert(points_.cols() == weights_.size());\n\n if (i >= weights_.size())\n {\n BOOST_THROW_EXCEPTION(OutOfBoundsException(i, weights_.size()));\n }\n\n if (Dimension() == 0)\n {\n BOOST_THROW_EXCEPTION(ZeroDimensionException(\"PointSetGaussian\"));\n }\n }\n\n\n void stage_point_changes()\n {\n moments_dirty_ = true;\n changes_staged_ = true;\n }\n\nprotected:\n \/**\n * \\brief point container\n *\/\n mutable PointMatrix points_;\n\n \/**\n * \\brief weight container\n *\/\n mutable Weights weights_;\n\n bool changes_staged_;\n bool moments_dirty_;\n bool point_set_dirty_;\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* $Id$ *\/\n\n\n#include <base\/exceptions.h>\n#include <string>\n#include <strstream>\n\n\n\nExceptionBase::ExceptionBase () :\n\t\tfile(\"\"), line(0), function(\"\"), cond(\"\"), exc(\"\")\n{};\n\n\n\nExceptionBase::ExceptionBase (const char* f, const int l, const char *func,\n\t\t\t const char* c, const char *e) :\n\t\tfile(f), line(l), function(func), cond(c), exc(e)\n{};\n\n\n\nvoid ExceptionBase::SetFields (const char* f,\n\t\t\t const int l,\n\t\t\t const char *func,\n\t\t\t const char *c,\n\t\t\t const char *e) {\n file = f;\n line = l;\n function = func;\n cond = c;\n exc = e;\n};\n\n\n\nvoid ExceptionBase::PrintExcData (ostream &out) const {\n out << \"An error occurred in line <\" << line\n << \"> of file <\" << file\n << \"> in function\" << endl\n << \" \" << function << endl\n << \"The violated condition was: \"<< endl\n << \" \" << cond << endl\n << \"The name and call sequence of the exception was:\" << endl\n << \" \" << exc << endl\n << \"Additional Information: \" << endl;\n};\n\n\n\n\nvoid ExceptionBase::PrintInfo (ostream &out) const {\n out << \"(none)\" << endl;\n};\n\n\n\nconst char * ExceptionBase::what () const {\n\t\t\t\t \/\/ have a place where to store the\n\t\t\t\t \/\/ description of the exception as a char *\n\t\t\t\t \/\/\n\t\t\t\t \/\/ this thing obviously is not multi-threading\n\t\t\t\t \/\/ safe, but we don't care about that for now\n\t\t\t\t \/\/\n\t\t\t\t \/\/ we need to make this object static, since\n\t\t\t\t \/\/ we want to return the data stored in it\n\t\t\t\t \/\/ and therefore need a liftime which is\n\t\t\t\t \/\/ longer than the execution time of this\n\t\t\t\t \/\/ function\n static string description;\n\t\t\t\t \/\/ convert the messages printed by the\n\t\t\t\t \/\/ exceptions into a string\n ostrstream converter;\n\n converter << \"--------------------------------------------------------\"\n\t << endl;\n\t\t\t\t \/\/ put general info into the string\n PrintExcData (converter);\n\t\t\t\t \/\/ put in exception specific data\n PrintInfo (converter);\n \n converter << \"--------------------------------------------------------\"\n\t << endl;\n\n description = converter.str();\n\n return description.c_str();\n};\n\n<commit_msg>Fix a point I was not really aware about previously: strstreams need <<ends!.<commit_after>\/* $Id$ *\/\n\n\n#include <base\/exceptions.h>\n#include <string>\n#include <strstream>\n\n\n\nExceptionBase::ExceptionBase () :\n\t\tfile(\"\"), line(0), function(\"\"), cond(\"\"), exc(\"\")\n{};\n\n\n\nExceptionBase::ExceptionBase (const char* f, const int l, const char *func,\n\t\t\t const char* c, const char *e) :\n\t\tfile(f), line(l), function(func), cond(c), exc(e)\n{};\n\n\n\nvoid ExceptionBase::SetFields (const char* f,\n\t\t\t const int l,\n\t\t\t const char *func,\n\t\t\t const char *c,\n\t\t\t const char *e) {\n file = f;\n line = l;\n function = func;\n cond = c;\n exc = e;\n};\n\n\n\nvoid ExceptionBase::PrintExcData (ostream &out) const {\n out << \"An error occurred in line <\" << line\n << \"> of file <\" << file\n << \"> in function\" << endl\n << \" \" << function << endl\n << \"The violated condition was: \"<< endl\n << \" \" << cond << endl\n << \"The name and call sequence of the exception was:\" << endl\n << \" \" << exc << endl\n << \"Additional Information: \" << endl;\n};\n\n\n\n\nvoid ExceptionBase::PrintInfo (ostream &out) const {\n out << \"(none)\" << endl;\n};\n\n\n\nconst char * ExceptionBase::what () const {\n\t\t\t\t \/\/ have a place where to store the\n\t\t\t\t \/\/ description of the exception as a char *\n\t\t\t\t \/\/\n\t\t\t\t \/\/ this thing obviously is not multi-threading\n\t\t\t\t \/\/ safe, but we don't care about that for now\n\t\t\t\t \/\/\n\t\t\t\t \/\/ we need to make this object static, since\n\t\t\t\t \/\/ we want to return the data stored in it\n\t\t\t\t \/\/ and therefore need a liftime which is\n\t\t\t\t \/\/ longer than the execution time of this\n\t\t\t\t \/\/ function\n static string description;\n\t\t\t\t \/\/ convert the messages printed by the\n\t\t\t\t \/\/ exceptions into a string\n ostrstream converter;\n\n converter << \"--------------------------------------------------------\"\n\t << endl;\n\t\t\t\t \/\/ put general info into the string\n PrintExcData (converter);\n\t\t\t\t \/\/ put in exception specific data\n PrintInfo (converter);\n \n converter << \"--------------------------------------------------------\"\n\t << endl\n\t << ends;\n\n description = converter.str();\n\n return description.c_str();\n};\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Contributors to the OpenVDB Project\n\/\/ SPDX-License-Identifier: MPL-2.0\n\/\/\n\/\/\/ @file SOP_OpenVDB_LOD.cc\n\/\/\/\n\/\/\/ @author FX R&D OpenVDB team\n\/\/\/\n\/\/\/ @brief Generate one or more levels of a volume mipmap.\n\n#include <houdini_utils\/ParmFactory.h>\n#include <openvdb_houdini\/SOP_NodeVDB.h>\n#include <openvdb_houdini\/Utils.h>\n#include <openvdb\/tools\/MultiResGrid.h>\n\n#include <hboost\/algorithm\/string\/join.hpp>\n\n#include <string>\n#include <vector>\n\n\nnamespace hvdb = openvdb_houdini;\nnamespace hutil = houdini_utils;\n\n\nclass SOP_OpenVDB_LOD: public hvdb::SOP_NodeVDB\n{\npublic:\n SOP_OpenVDB_LOD(OP_Network*, const char* name, OP_Operator*);\n ~SOP_OpenVDB_LOD() override {}\n\n static OP_Node* factory(OP_Network*, const char* name, OP_Operator*);\n\n int isRefInput(unsigned input) const override { return (input > 0); }\n\n class Cache: public SOP_VDBCacheOptions { OP_ERROR cookVDBSop(OP_Context&) override; };\n\nprotected:\n bool updateParmsFlags() override;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nvoid\nnewSopOperator(OP_OperatorTable* table)\n{\n if (table == nullptr) return;\n\n hutil::ParmList parms;\n\n parms.add(hutil::ParmFactory(PRM_STRING, \"group\", \"Group\")\n .setChoiceList(&hutil::PrimGroupMenuInput1)\n .setTooltip(\"Specify a subset of the input VDB grids to be processed.\")\n .setDocumentation(\n \"A subset of the input VDB grids to be processed\"\n \" (see [specifying volumes|\/model\/volumes#group])\"));\n\n parms.add(hutil::ParmFactory(PRM_ORD, \"lod\", \"LOD Mode\")\n .setDefault(PRMzeroDefaults)\n .setChoiceListItems(PRM_CHOICELIST_SINGLE, {\n \"single\", \"Single Level\",\n \"range\", \"Level Range\",\n \"mipmaps\",\"LOD Pyramid\"\n })\n .setDocumentation(\n \"How to build the LOD pyramid\\n\\n\"\n \"Single Level:\\n\"\n \" Build a single, filtered VDB.\\n\\n\"\n \"Level Range:\\n\"\n \" Build a series of VDBs of progressively lower resolution\\n\"\n \" within a given range of scales.\\n\\n\"\n \"LOD Pyramid:\\n\"\n \" Build a standard pyramid of VDBs of decreasing resolution.\\n\"\n \" Each level of the pyramid is half the resolution in each\\n\"\n \" dimension of the previous level, starting with the input VDB.\\n\"));\n\n parms.add(hutil::ParmFactory(PRM_FLT_J, \"level\", \"Level\")\n .setDefault(PRMoneDefaults)\n .setRange(PRM_RANGE_RESTRICTED, 0.0, PRM_RANGE_UI, 10.0)\n .setTooltip(\"Specify which single level to produce.\\n\"\n \"Level 0, the highest-resolution level, is the input VDB.\"));\n\n {\n const std::vector<fpreal> defaultRange{\n fpreal(0.0), \/\/ start\n fpreal(2.0), \/\/ end\n fpreal(1.0) \/\/ step\n };\n\n parms.add(hutil::ParmFactory(PRM_FLT_J, \"range\", \"Range\")\n .setDefault(defaultRange)\n .setVectorSize(3)\n .setRange(PRM_RANGE_RESTRICTED, 0.0, PRM_RANGE_UI, 10.0)\n .setTooltip(\n \"In Level Range mode, specify the (inclusive) starting and ending levels\"\n \" and the level step. Level 0, the highest-resolution level, is the input VDB;\"\n \" fractional levels are allowed.\"));\n }\n\n parms.add(hutil::ParmFactory(PRM_INT_J, \"count\", \"Count\")\n .setDefault(PRMtwoDefaults)\n .setRange(PRM_RANGE_RESTRICTED, 2, PRM_RANGE_UI, 10)\n .setTooltip(\n \"In LOD Pyramid mode, specify the number of pyramid levels to generate.\"\n \" Each level is half the resolution of the previous level.\"));\n\n parms.add(hutil::ParmFactory(PRM_TOGGLE, \"reuse\", \"Preserve Grid Names\")\n .setDefault(PRMzeroDefaults)\n .setTooltip(\n \"In Single Level mode, give the output VDB the same name as the input VDB.\"));\n\n hvdb::OpenVDBOpFactory(\"VDB LOD\", SOP_OpenVDB_LOD::factory, parms, *table)\n .addInput(\"VDBs\")\n .setVerb(SOP_NodeVerb::COOK_INPLACE, []() { return new SOP_OpenVDB_LOD::Cache; })\n .setDocumentation(\"\\\n#icon: COMMON\/openvdb\\n\\\n#tags: vdb\\n\\\n\\n\\\n\\\"\\\"\\\"Build an LOD pyramid from a VDB volume.\\\"\\\"\\\"\\n\\\n\\n\\\n@overview\\n\\\n\\n\\\nThis node creates filtered versions of a VDB volume at multiple resolutions,\\n\\\nproviding mipmap-like levels of detail.\\n\\\nThe low-resolution versions can be used both as thumbnails for fast processing\\n\\\nand for constant-time, filtered lookups over large areas of a volume.\\n\\\n\\n\\\n@related\\n\\\n- [OpenVDB Resample|Node:sop\/DW_OpenVDBResample]\\n\\\n\\n\\\n@examples\\n\\\n\\n\\\nSee [openvdb.org|http:\/\/www.openvdb.org\/download\/] for source code\\n\\\nand usage examples.\\n\");\n}\n\n\nbool\nSOP_OpenVDB_LOD::updateParmsFlags()\n{\n bool changed = false;\n\n const auto lodMode = evalInt(\"lod\", 0, 0);\n\n changed |= enableParm(\"level\", lodMode == 0);\n changed |= enableParm(\"reuse\", lodMode == 0);\n changed |= enableParm(\"range\", lodMode == 1);\n changed |= enableParm(\"count\", lodMode == 2);\n\n return changed;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nOP_Node*\nSOP_OpenVDB_LOD::factory(OP_Network* net,\n const char* name, OP_Operator* op)\n{\n return new SOP_OpenVDB_LOD(net, name, op);\n}\n\n\nSOP_OpenVDB_LOD::SOP_OpenVDB_LOD(OP_Network* net,\n const char* name, OP_Operator* op):\n hvdb::SOP_NodeVDB(net, name, op)\n{\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace {\n\ntemplate<openvdb::Index Order>\nstruct MultiResGridFractionalOp\n{\n MultiResGridFractionalOp(float f) : level(f) {}\n template<typename GridType>\n void operator()(const GridType& grid)\n {\n if ( level <= 0.0f ) {\n outputGrid = typename GridType::Ptr( new GridType(grid) );\n } else {\n const size_t levels = openvdb::math::Ceil(level) + 1;\n using TreeT = typename GridType::TreeType;\n openvdb::tools::MultiResGrid<TreeT> mrg( levels, grid );\n outputGrid = mrg.template createGrid<Order>( level );\n }\n }\n const float level;\n hvdb::GridPtr outputGrid;\n};\n\ntemplate<openvdb::Index Order>\nstruct MultiResGridRangeOp\n{\n MultiResGridRangeOp(float start_, float end_, float step_, hvdb::Interrupter& boss_)\n : start(start_), end(end_), step(step_), outputGrids(), boss(&boss_)\n {}\n\n template<typename GridType>\n void operator()(const GridType& grid)\n {\n if ( end > 0.0f ) {\n const size_t levels = openvdb::math::Ceil(end) + 1;\n using TreeT = typename GridType::TreeType;\n openvdb::tools::MultiResGrid<TreeT> mrg( levels, grid );\n\n \/\/ inclusive range\n for (float level = start; !(level > end); level += step) {\n\n if (boss->wasInterrupted()) break;\n\n outputGrids.push_back( mrg.template createGrid<Order>( level ) );\n }\n }\n }\n const float start, end, step;\n std::vector<hvdb::GridPtr> outputGrids;\n hvdb::Interrupter * const boss;\n};\n\nstruct MultiResGridIntegerOp\n{\n MultiResGridIntegerOp(size_t n) : levels(n) {}\n template<typename GridType>\n void operator()(const GridType& grid)\n {\n using TreeT = typename GridType::TreeType;\n openvdb::tools::MultiResGrid<TreeT> mrg( levels, grid );\n outputGrids = mrg.grids();\n }\n const size_t levels;\n openvdb::GridPtrVecPtr outputGrids;\n};\n\n\ninline bool\nisValidRange(float start, float end, float step)\n{\n if (start < 0.0f || !(step > 0.0f) || end < 0.0f) {\n return false;\n }\n\n return !(start > end);\n}\n\n}\/\/unnamed namespace\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nOP_ERROR\nSOP_OpenVDB_LOD::Cache::cookVDBSop(OP_Context& context)\n{\n try {\n const fpreal time = context.getTime();\n\n \/\/ Get the group of grids to process.\n const GA_PrimitiveGroup* group = matchGroup(*gdp, evalStdString(\"group\", time));\n\n std::vector<std::string> skipped;\n\n hvdb::Interrupter boss(\"Creating VDB LoD pyramid\");\n GA_RWHandleS name_h(gdp, GA_ATTRIB_PRIMITIVE, \"name\");\n\n const auto lodMode = evalInt(\"lod\", 0, 0);\n if (lodMode == 0) {\n\n const bool reuseName = evalInt(\"reuse\", 0, 0) > 0;\n MultiResGridFractionalOp<1> op( float(evalFloat(\"level\", 0, time)) );\n for (hvdb::VdbPrimIterator it(gdp, group); it; ++it) {\n\n if (boss.wasInterrupted()) return error();\n\n if (name_h.isValid())\n it->getGrid().setName(static_cast<const char *>(name_h.get(it->getMapOffset())));\n\n if (!it->getGrid().transform().isLinear()) {\n skipped.push_back(it->getGrid().getName());\n continue;\n }\n\n hvdb::GEOvdbApply<hvdb::VolumeGridTypes>(**it, op);\n\n if (boss.wasInterrupted()) return error();\n\n if (reuseName) op.outputGrid->setName( it->getGrid().getName() );\n\n hvdb::createVdbPrimitive(*gdp, op.outputGrid);\n\n gdp->destroyPrimitiveOffset(it->getMapOffset(), \/*and_points=*\/true);\n }\n\n } else if (lodMode == 1) {\n\n const float start = float(evalFloat(\"range\", 0, time));\n const float end = float(evalFloat(\"range\", 1, time));\n const float step = float(evalFloat(\"range\", 2, time));\n\n if (!isValidRange(start, end, step)) {\n addError(SOP_MESSAGE, \"Invalid range, make sure that \"\n \"start <= end and the step size is a positive number.\");\n return error();\n }\n\n MultiResGridRangeOp<1> op( start, end, step, boss );\n for (hvdb::VdbPrimIterator it(gdp, group); it; ++it) {\n\n if (boss.wasInterrupted()) return error();\n\n if (name_h.isValid())\n it->getGrid().setName(static_cast<const char *>(name_h.get(it->getMapOffset())));\n\n if (!it->getGrid().transform().isLinear()) {\n skipped.push_back(it->getGrid().getName());\n continue;\n }\n\n hvdb::GEOvdbApply<hvdb::VolumeGridTypes>(**it, op);\n\n if (boss.wasInterrupted()) return error();\n\n for (size_t i=0; i< op.outputGrids.size(); ++i) {\n hvdb::createVdbPrimitive(*gdp, op.outputGrids[i]);\n }\n\n gdp->destroyPrimitiveOffset(it->getMapOffset(), \/*and_points=*\/true);\n }\n } else if (lodMode == 2) {\n\n MultiResGridIntegerOp op( evalInt(\"count\", 0, time) );\n for (hvdb::VdbPrimIterator it(gdp, group); it; ++it) {\n\n if (boss.wasInterrupted()) return error();\n\n if (name_h.isValid())\n it->getGrid().setName(static_cast<const char *>(name_h.get(it->getMapOffset())));\n\n if (!it->getGrid().transform().isLinear()) {\n skipped.push_back(it->getGrid().getName());\n continue;\n }\n\n hvdb::GEOvdbApply<hvdb::VolumeGridTypes>(**it, op);\n\n if (boss.wasInterrupted()) return error();\n\n for (size_t i=0; i< op.outputGrids->size(); ++i) {\n hvdb::createVdbPrimitive(*gdp, op.outputGrids->at(i));\n }\n\n gdp->destroyPrimitiveOffset(it->getMapOffset(), \/*and_points=*\/true);\n }\n\n } else {\n addError(SOP_MESSAGE, \"Invalid LOD option.\");\n }\n\n if (!skipped.empty()) {\n addWarning(SOP_MESSAGE, (\"Unable to process grid(s): \" +\n hboost::algorithm::join(skipped, \", \")).c_str());\n }\n\n } catch (std::exception& e) {\n addError(SOP_MESSAGE, e.what());\n }\n\n return error();\n}\n<commit_msg>Drop incompatible MultiResGrid data<commit_after>\/\/ Copyright Contributors to the OpenVDB Project\n\/\/ SPDX-License-Identifier: MPL-2.0\n\/\/\n\/\/\/ @file SOP_OpenVDB_LOD.cc\n\/\/\/\n\/\/\/ @author FX R&D OpenVDB team\n\/\/\/\n\/\/\/ @brief Generate one or more levels of a volume mipmap.\n\n#include <houdini_utils\/ParmFactory.h>\n#include <openvdb_houdini\/SOP_NodeVDB.h>\n#include <openvdb_houdini\/Utils.h>\n#include <openvdb\/tools\/MultiResGrid.h>\n\n#include <hboost\/algorithm\/string\/join.hpp>\n\n#include <string>\n#include <vector>\n\n\nnamespace hvdb = openvdb_houdini;\nnamespace hutil = houdini_utils;\n\n\nclass SOP_OpenVDB_LOD: public hvdb::SOP_NodeVDB\n{\npublic:\n SOP_OpenVDB_LOD(OP_Network*, const char* name, OP_Operator*);\n ~SOP_OpenVDB_LOD() override {}\n\n static OP_Node* factory(OP_Network*, const char* name, OP_Operator*);\n\n int isRefInput(unsigned input) const override { return (input > 0); }\n\n class Cache: public SOP_VDBCacheOptions { OP_ERROR cookVDBSop(OP_Context&) override; };\n\nprotected:\n bool updateParmsFlags() override;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nvoid\nnewSopOperator(OP_OperatorTable* table)\n{\n if (table == nullptr) return;\n\n hutil::ParmList parms;\n\n parms.add(hutil::ParmFactory(PRM_STRING, \"group\", \"Group\")\n .setChoiceList(&hutil::PrimGroupMenuInput1)\n .setTooltip(\"Specify a subset of the input VDB grids to be processed.\")\n .setDocumentation(\n \"A subset of the input VDB grids to be processed\"\n \" (see [specifying volumes|\/model\/volumes#group])\"));\n\n parms.add(hutil::ParmFactory(PRM_ORD, \"lod\", \"LOD Mode\")\n .setDefault(PRMzeroDefaults)\n .setChoiceListItems(PRM_CHOICELIST_SINGLE, {\n \"single\", \"Single Level\",\n \"range\", \"Level Range\",\n \"mipmaps\",\"LOD Pyramid\"\n })\n .setDocumentation(\n \"How to build the LOD pyramid\\n\\n\"\n \"Single Level:\\n\"\n \" Build a single, filtered VDB.\\n\\n\"\n \"Level Range:\\n\"\n \" Build a series of VDBs of progressively lower resolution\\n\"\n \" within a given range of scales.\\n\\n\"\n \"LOD Pyramid:\\n\"\n \" Build a standard pyramid of VDBs of decreasing resolution.\\n\"\n \" Each level of the pyramid is half the resolution in each\\n\"\n \" dimension of the previous level, starting with the input VDB.\\n\"));\n\n parms.add(hutil::ParmFactory(PRM_FLT_J, \"level\", \"Level\")\n .setDefault(PRMoneDefaults)\n .setRange(PRM_RANGE_RESTRICTED, 0.0, PRM_RANGE_UI, 10.0)\n .setTooltip(\"Specify which single level to produce.\\n\"\n \"Level 0, the highest-resolution level, is the input VDB.\"));\n\n {\n const std::vector<fpreal> defaultRange{\n fpreal(0.0), \/\/ start\n fpreal(2.0), \/\/ end\n fpreal(1.0) \/\/ step\n };\n\n parms.add(hutil::ParmFactory(PRM_FLT_J, \"range\", \"Range\")\n .setDefault(defaultRange)\n .setVectorSize(3)\n .setRange(PRM_RANGE_RESTRICTED, 0.0, PRM_RANGE_UI, 10.0)\n .setTooltip(\n \"In Level Range mode, specify the (inclusive) starting and ending levels\"\n \" and the level step. Level 0, the highest-resolution level, is the input VDB;\"\n \" fractional levels are allowed.\"));\n }\n\n parms.add(hutil::ParmFactory(PRM_INT_J, \"count\", \"Count\")\n .setDefault(PRMtwoDefaults)\n .setRange(PRM_RANGE_RESTRICTED, 2, PRM_RANGE_UI, 10)\n .setTooltip(\n \"In LOD Pyramid mode, specify the number of pyramid levels to generate.\"\n \" Each level is half the resolution of the previous level.\"));\n\n parms.add(hutil::ParmFactory(PRM_TOGGLE, \"reuse\", \"Preserve Grid Names\")\n .setDefault(PRMzeroDefaults)\n .setTooltip(\n \"In Single Level mode, give the output VDB the same name as the input VDB.\"));\n\n hvdb::OpenVDBOpFactory(\"VDB LOD\", SOP_OpenVDB_LOD::factory, parms, *table)\n .addInput(\"VDBs\")\n .setVerb(SOP_NodeVerb::COOK_INPLACE, []() { return new SOP_OpenVDB_LOD::Cache; })\n .setDocumentation(\"\\\n#icon: COMMON\/openvdb\\n\\\n#tags: vdb\\n\\\n\\n\\\n\\\"\\\"\\\"Build an LOD pyramid from a VDB volume.\\\"\\\"\\\"\\n\\\n\\n\\\n@overview\\n\\\n\\n\\\nThis node creates filtered versions of a VDB volume at multiple resolutions,\\n\\\nproviding mipmap-like levels of detail.\\n\\\nThe low-resolution versions can be used both as thumbnails for fast processing\\n\\\nand for constant-time, filtered lookups over large areas of a volume.\\n\\\n\\n\\\n@related\\n\\\n- [OpenVDB Resample|Node:sop\/DW_OpenVDBResample]\\n\\\n\\n\\\n@examples\\n\\\n\\n\\\nSee [openvdb.org|http:\/\/www.openvdb.org\/download\/] for source code\\n\\\nand usage examples.\\n\");\n}\n\n\nbool\nSOP_OpenVDB_LOD::updateParmsFlags()\n{\n bool changed = false;\n\n const auto lodMode = evalInt(\"lod\", 0, 0);\n\n changed |= enableParm(\"level\", lodMode == 0);\n changed |= enableParm(\"reuse\", lodMode == 0);\n changed |= enableParm(\"range\", lodMode == 1);\n changed |= enableParm(\"count\", lodMode == 2);\n\n return changed;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nOP_Node*\nSOP_OpenVDB_LOD::factory(OP_Network* net,\n const char* name, OP_Operator* op)\n{\n return new SOP_OpenVDB_LOD(net, name, op);\n}\n\n\nSOP_OpenVDB_LOD::SOP_OpenVDB_LOD(OP_Network* net,\n const char* name, OP_Operator* op):\n hvdb::SOP_NodeVDB(net, name, op)\n{\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace {\n\ntemplate<openvdb::Index Order>\nstruct MultiResGridFractionalOp\n{\n MultiResGridFractionalOp(float f) : level(f) {}\n template<typename GridType>\n void operator()(const GridType& grid)\n {\n using TreeT = typename GridType::TreeType;\n if ( level <= 0.0f ) {\n outputGrid = typename GridType::Ptr( new GridType(grid) );\n } else {\n const size_t levels = openvdb::math::Ceil(level) + 1;\n const GridType* gridPtr = &grid;\n#if OPENVDB_ABI_VERSION_NUMBER >= 7 \/\/ Grid::copyReplacingMetadata() only available in ABI>=7\n \/\/ if grid already has MultiResGrid_Level metadata with type int64, remove it\n typename GridType::ConstPtr newGridPtr;\n auto meta = grid.template getMetadata<openvdb::Int64Metadata>(\"MultiResGrid_Level\");\n if (meta) {\n \/\/ deep copy meta map and remove element\n openvdb::MetaMap metaMap(static_cast<const openvdb::MetaMap&>(grid));\n metaMap.removeMeta(\"MultiResGrid_Level\");\n \/\/ the tree and transform are shared with the input grid, but meta map is different\n newGridPtr = grid.copyReplacingMetadata(metaMap);\n gridPtr = newGridPtr.get();\n }\n#endif\n openvdb::tools::MultiResGrid<TreeT> mrg( levels, *gridPtr );\n outputGrid = mrg.template createGrid<Order>( level );\n }\n }\n const float level;\n hvdb::GridPtr outputGrid;\n};\n\ntemplate<openvdb::Index Order>\nstruct MultiResGridRangeOp\n{\n MultiResGridRangeOp(float start_, float end_, float step_, hvdb::Interrupter& boss_)\n : start(start_), end(end_), step(step_), outputGrids(), boss(&boss_)\n {}\n\n template<typename GridType>\n void operator()(const GridType& grid)\n {\n using TreeT = typename GridType::TreeType;\n if ( end > 0.0f ) {\n const size_t levels = openvdb::math::Ceil(end) + 1;\n const GridType* gridPtr = &grid;\n#if OPENVDB_ABI_VERSION_NUMBER >= 7 \/\/ Grid::copyReplacingMetadata() only available in ABI>=7\n \/\/ if grid already has MultiResGrid_Level metadata with type int64, remove it\n typename GridType::ConstPtr newGridPtr;\n auto meta = grid.template getMetadata<openvdb::Int64Metadata>(\"MultiResGrid_Level\");\n if (meta) {\n \/\/ deep copy meta map and remove element\n openvdb::MetaMap metaMap(static_cast<const openvdb::MetaMap&>(grid));\n metaMap.removeMeta(\"MultiResGrid_Level\");\n \/\/ the tree and transform are shared with the input grid, but meta map is different\n newGridPtr = grid.copyReplacingMetadata(metaMap);\n gridPtr = newGridPtr.get();\n }\n#endif\n openvdb::tools::MultiResGrid<TreeT> mrg( levels, *gridPtr );\n\n \/\/ inclusive range\n for (float level = start; !(level > end); level += step) {\n\n if (boss->wasInterrupted()) break;\n\n outputGrids.push_back( mrg.template createGrid<Order>( level ) );\n }\n }\n }\n const float start, end, step;\n std::vector<hvdb::GridPtr> outputGrids;\n hvdb::Interrupter * const boss;\n};\n\nstruct MultiResGridIntegerOp\n{\n MultiResGridIntegerOp(size_t n) : levels(n) {}\n template<typename GridType>\n void operator()(const GridType& grid)\n {\n using TreeT = typename GridType::TreeType;\n const GridType* gridPtr = &grid;\n#if OPENVDB_ABI_VERSION_NUMBER >= 7 \/\/ Grid::copyReplacingMetadata() only available in ABI>=7\n \/\/ if grid already has MultiResGrid_Level metadata with type float, remove it\n typename GridType::ConstPtr newGridPtr;\n auto meta = grid.template getMetadata<openvdb::FloatMetadata>(\"MultiResGrid_Level\");\n if (meta) {\n \/\/ deep copy meta map and remove element\n openvdb::MetaMap metaMap(static_cast<const openvdb::MetaMap&>(grid));\n metaMap.removeMeta(\"MultiResGrid_Level\");\n \/\/ the tree and transform are shared with the input grid, but meta map is different\n newGridPtr = grid.copyReplacingMetadata(metaMap);\n gridPtr = newGridPtr.get();\n }\n#endif\n openvdb::tools::MultiResGrid<TreeT> mrg( levels, *gridPtr );\n outputGrids = mrg.grids();\n }\n const size_t levels;\n openvdb::GridPtrVecPtr outputGrids;\n};\n\n\ninline bool\nisValidRange(float start, float end, float step)\n{\n if (start < 0.0f || !(step > 0.0f) || end < 0.0f) {\n return false;\n }\n\n return !(start > end);\n}\n\n}\/\/unnamed namespace\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nOP_ERROR\nSOP_OpenVDB_LOD::Cache::cookVDBSop(OP_Context& context)\n{\n try {\n const fpreal time = context.getTime();\n\n \/\/ Get the group of grids to process.\n const GA_PrimitiveGroup* group = matchGroup(*gdp, evalStdString(\"group\", time));\n\n std::vector<std::string> skipped;\n\n hvdb::Interrupter boss(\"Creating VDB LoD pyramid\");\n GA_RWHandleS name_h(gdp, GA_ATTRIB_PRIMITIVE, \"name\");\n\n const auto lodMode = evalInt(\"lod\", 0, 0);\n if (lodMode == 0) {\n\n const bool reuseName = evalInt(\"reuse\", 0, 0) > 0;\n MultiResGridFractionalOp<1> op( float(evalFloat(\"level\", 0, time)) );\n for (hvdb::VdbPrimIterator it(gdp, group); it; ++it) {\n\n if (boss.wasInterrupted()) return error();\n\n if (name_h.isValid())\n it->getGrid().setName(static_cast<const char *>(name_h.get(it->getMapOffset())));\n\n if (!it->getGrid().transform().isLinear()) {\n skipped.push_back(it->getGrid().getName());\n continue;\n }\n\n hvdb::GEOvdbApply<hvdb::VolumeGridTypes>(**it, op);\n\n if (boss.wasInterrupted()) return error();\n\n if (reuseName) op.outputGrid->setName( it->getGrid().getName() );\n\n hvdb::createVdbPrimitive(*gdp, op.outputGrid);\n\n gdp->destroyPrimitiveOffset(it->getMapOffset(), \/*and_points=*\/true);\n }\n\n } else if (lodMode == 1) {\n\n const float start = float(evalFloat(\"range\", 0, time));\n const float end = float(evalFloat(\"range\", 1, time));\n const float step = float(evalFloat(\"range\", 2, time));\n\n if (!isValidRange(start, end, step)) {\n addError(SOP_MESSAGE, \"Invalid range, make sure that \"\n \"start <= end and the step size is a positive number.\");\n return error();\n }\n\n MultiResGridRangeOp<1> op( start, end, step, boss );\n for (hvdb::VdbPrimIterator it(gdp, group); it; ++it) {\n\n if (boss.wasInterrupted()) return error();\n\n if (name_h.isValid())\n it->getGrid().setName(static_cast<const char *>(name_h.get(it->getMapOffset())));\n\n if (!it->getGrid().transform().isLinear()) {\n skipped.push_back(it->getGrid().getName());\n continue;\n }\n\n hvdb::GEOvdbApply<hvdb::VolumeGridTypes>(**it, op);\n\n if (boss.wasInterrupted()) return error();\n\n for (size_t i=0; i< op.outputGrids.size(); ++i) {\n hvdb::createVdbPrimitive(*gdp, op.outputGrids[i]);\n }\n\n gdp->destroyPrimitiveOffset(it->getMapOffset(), \/*and_points=*\/true);\n }\n } else if (lodMode == 2) {\n\n MultiResGridIntegerOp op( evalInt(\"count\", 0, time) );\n for (hvdb::VdbPrimIterator it(gdp, group); it; ++it) {\n\n if (boss.wasInterrupted()) return error();\n\n if (name_h.isValid())\n it->getGrid().setName(static_cast<const char *>(name_h.get(it->getMapOffset())));\n\n if (!it->getGrid().transform().isLinear()) {\n skipped.push_back(it->getGrid().getName());\n continue;\n }\n\n hvdb::GEOvdbApply<hvdb::VolumeGridTypes>(**it, op);\n\n if (boss.wasInterrupted()) return error();\n\n for (size_t i=0; i< op.outputGrids->size(); ++i) {\n hvdb::createVdbPrimitive(*gdp, op.outputGrids->at(i));\n }\n\n gdp->destroyPrimitiveOffset(it->getMapOffset(), \/*and_points=*\/true);\n }\n\n } else {\n addError(SOP_MESSAGE, \"Invalid LOD option.\");\n }\n\n if (!skipped.empty()) {\n addWarning(SOP_MESSAGE, (\"Unable to process grid(s): \" +\n hboost::algorithm::join(skipped, \", \")).c_str());\n }\n\n } catch (std::exception& e) {\n addError(SOP_MESSAGE, e.what());\n }\n\n return error();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <iostream>\n#include <opencv2\/opencv.hpp>\n#include \"ros\/ros.h\"\n#include \"ram_msgs\/Buoys.h\"\n#include <vector>\n\nusing namespace cv;\nusing namespace std;\n\nMat frame;\nMat hsv_frame, gray;\nvector<Mat> hsv_channels;\nint thresh = 100;\nint max_thresh = 255;\nRNG rng(12345);\nMat drawing;\n\n\/** @function thresh_callback *\/\nvoid thresh_callback(int, void*) {\n Mat canny_output;\n vector<vector<Point> > contours;\n vector<Vec4i> hierarchy;\n vector<Vec3f> circles;\n Mat blurred;\n \n \/\/ Detect edges using canny\n Canny(hsv_frame, canny_output, thresh, thresh*2, 3);\n\n \/* GaussianBlur( hsv_channels[2], blurred, Size(9, 9), 0, 0 );\n HoughCircles( blurred, circles, CV_HOUGH_GRADIENT, 2, blurred.rows\/4, 400, 50, 0, 0 );\n printf(\"%d\", circles.size());\n *\/\n \/\/ Find contours\n findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));\n \n \/\/ Draw contours\n drawing = Mat::zeros(canny_output.size(), CV_8UC3);\n for(int i = 0; i < contours.size(); i++) {\n Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));\n drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());\n }\n\n \/\/ Show in a window\n namedWindow(\"Contours\", CV_WINDOW_AUTOSIZE);\n imshow(\"Contours\", drawing);\n}\n\n\nint main(int argc, char*argv[]) {\n \n if(argc != 2){\n cout << \"wrong number of arguments dummy, call \\\"a.out test_video\\\"\" << endl;\n return 0;\n }\n\n\n \/\/Publisher for circle locations\n ros::init(argc,argv,\"circle_centers\");\n ros::NodeHandle n;\n \n ros::Publisher circ_pub = n.advertise<ram_msgs::Buoys>(\"circle_locations\", 1000);\n\n \n \/\/ Read image\n VideoCapture cap = VideoCapture( argv[1] );\n cap >> frame;\n\n Mat im_with_keypoints;\n std::vector<KeyPoint> keypoints;\n \n while(!frame.empty()) {\n\t\/\/ Convert the frame into hsv, then split it into channels\n\tcvtColor(frame, hsv_frame, CV_BGR2HSV);\n\thsv_channels.clear();\n\tsplit(hsv_frame, hsv_channels);\n\n\t\n\tnamedWindow(\"HSV\", CV_WINDOW_AUTOSIZE);\t\n\timshow(\"HSV\",hsv_frame);\n \t\/\/ GaussianBlur(hsv, hsv, Size(15, 15), 2, 2 );\n \n \/\/\/ Create Window\n char* source_window = \"Source\";\n namedWindow(source_window, CV_WINDOW_AUTOSIZE);\n imshow(source_window, frame);\n \n createTrackbar(\" Canny thresh:\", \"Source\", &thresh, max_thresh, thresh_callback);\n thresh_callback(0, 0);\n\n\tcvtColor(drawing, gray, CV_BGR2GRAY);\n\tGaussianBlur(gray, gray, Size(15,15), 2, 2);\n\tnamedWindow(\"drawings,gray\", CV_WINDOW_AUTOSIZE);\n\timshow(\"drawings,gray\",gray);\n\n\n\t\/\/Finds the locations of the circles and drwas them on the original image\n vector<Vec3f> circles;\n HoughCircles(gray, circles, CV_HOUGH_GRADIENT,2, gray.rows\/4, thresh * 2, 82 );\n\t\n\n\tram_msgs::Buoys buoy;\n\t\/\/Hopefully there arent more than 10 circles the HoughCircles picks up\n\tstd::vector<double> xs;\n\tstd::vector<double> ys;\n\tstd::vector<double> zs;\n\t\/\/circ_pub.publish();\n\t \n waitKey(0);\n for(size_t i = 0; i < circles.size(); i++) {\n Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));\n int radius = cvRound(circles[i][2]);\n \/\/ draw the circle center\n circle(frame, center, 3, Scalar(0,255,0), -1, 8, 0 );\n \/\/ draw the circle outline\n circle(frame, center, radius, Scalar(0,0,255), 3, 8, 0 );\n\n\t\t xs.push_back(circles[i][0]);\n\t\t ys.push_back(circles[i][1]);\n\t\t zs.push_back(circles[i][2]);\n }\n\n\tbuoy.x = xs;\n\tbuoy.y = ys;\n\tbuoy.z = zs;\n\n\tcirc_pub.publish(buoy);\n\t\n\tnamedWindow(\"circles\", 1);\n\timshow(\"circles\", frame); \n \n waitKey(0);\n cap >> frame;\n }\n}\n<commit_msg>cleaned up a little updated canny_tuner (not much)<commit_after>#include <stdio.h>\n#include <iostream>\n#include <opencv2\/opencv.hpp>\n#include \"ros\/ros.h\"\n#include \"ram_msgs\/Buoys.h\"\n#include <vector>\n\nusing namespace cv;\nusing namespace std;\n\nMat frame;\nMat hsv_frame, gray;\nvector<Mat> hsv_channels;\nint thresh = 100;\nint max_thresh = 255;\nRNG rng(12345);\nMat drawing;\n\n\/** @function thresh_callback *\/\nvoid thresh_callback(int, void*) {\n Mat canny_output;\n vector<vector<Point> > contours;\n vector<Vec4i> hierarchy;\n vector<Vec3f> circles;\n Mat blurred;\n \n \/\/ Detect edges using canny\n Canny(hsv_frame, canny_output, thresh, thresh*2, 3);\n\n \/* GaussianBlur( hsv_channels[2], blurred, Size(9, 9), 0, 0 );\n HoughCircles( blurred, circles, CV_HOUGH_GRADIENT, 2, blurred.rows\/4, 400, 50, 0, 0 );\n printf(\"%d\", circles.size());\n *\/\n \/\/ Find contours\n findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));\n \n \/\/ Draw contours\n drawing = Mat::zeros(canny_output.size(), CV_8UC3);\n for(int i = 0; i < contours.size(); i++) {\n Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));\n drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());\n }\n\n \/\/ Show in a window\n namedWindow(\"Contours\", CV_WINDOW_AUTOSIZE);\n imshow(\"Contours\", drawing);\n}\n\n\nint main(int argc, char*argv[]) {\n \n if(argc != 2){\n cout << \"wrong number of arguments dummy, call \\\"a.out test_video\\\"\" << endl;\n return 0;\n }\n\n\n \/\/Publisher for circle locations\n ros::init(argc,argv,\"circle_centers\");\n ros::NodeHandle n;\n \n ros::Publisher circ_pub = n.advertise<ram_msgs::Buoys>(\"circle_locations\", 1000);\n\n \n \/\/ Read image\n VideoCapture cap = VideoCapture( argv[1] );\n cap >> frame;\n\n Mat im_with_keypoints;\n std::vector<KeyPoint> keypoints;\n \n while(!frame.empty()) {\n\t\/\/ Convert the frame into hsv, then split it into channels\n\tcvtColor(frame, hsv_frame, CV_BGR2HSV);\n\thsv_channels.clear();\n\tsplit(hsv_frame, hsv_channels);\n\n\t\n\tnamedWindow(\"HSV\", CV_WINDOW_AUTOSIZE);\t\n\timshow(\"HSV\",hsv_frame);\n \t\/\/ GaussianBlur(hsv, hsv, Size(15, 15), 2, 2 );\n \n \/\/\/ Create Window\n char* source_window = \"Source\";\n namedWindow(source_window, CV_WINDOW_AUTOSIZE);\n imshow(source_window, frame);\n \n createTrackbar(\" Canny thresh:\", \"Source\", &thresh, max_thresh, thresh_callback);\n thresh_callback(0, 0);\n\n\tcvtColor(drawing, gray, CV_BGR2GRAY);\n\tGaussianBlur(gray, gray, Size(15,15), 2, 2);\n\tnamedWindow(\"drawings,gray\", CV_WINDOW_AUTOSIZE);\n\timshow(\"drawings,gray\",gray);\n\n\n\t\/\/Finds the locations of the circles and drwas them on the original image\n vector<Vec3f> circles;\n HoughCircles(gray, circles, CV_HOUGH_GRADIENT,2, gray.rows\/4, thresh * 2, 82 );\n\t\n\n\tram_msgs::Buoys buoy;\n\t\/\/Hopefully there arent more than 10 circles the HoughCircles picks up\n\tstd::vector<double> xs;\n\tstd::vector<double> ys;\n\tstd::vector<double> zs;\n\t \n waitKey(0);\n for(size_t i = 0; i < circles.size(); i++) {\n Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));\n int radius = cvRound(circles[i][2]);\n \/\/ draw the circle center\n circle(frame, center, 3, Scalar(0,255,0), -1, 8, 0 );\n \/\/ draw the circle outline\n circle(frame, center, radius, Scalar(0,0,255), 3, 8, 0 );\n\n\t\t xs.push_back(circles[i][0]);\n\t\t ys.push_back(circles[i][1]);\n\t\t zs.push_back(circles[i][2]);\n }\n\n\tbuoy.x = xs;\n\tbuoy.y = ys;\n\tbuoy.z = zs;\n\n\tcirc_pub.publish(buoy);\n\t\n\tnamedWindow(\"circles\", 1);\n\timshow(\"circles\", frame); \n \n waitKey(0);\n cap >> frame;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Zanshin\n\n Copyright 2014 Kevin Ottens <ervin@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n\n#include \"applicationcomponents.h\"\n\n#include <QBoxLayout>\n#include <QLabel>\n#include <QVariant>\n#include <QWidget>\n#include <QWidgetAction>\n\n#include \"availablepagesview.h\"\n#include \"availablesourcesview.h\"\n#include \"datasourcecombobox.h\"\n#include \"editorview.h\"\n#include \"pageview.h\"\n\n#include \"presentation\/applicationmodel.h\"\n\nusing namespace Widgets;\n\nApplicationComponents::ApplicationComponents(QWidget *parent, ApplicationMode mode)\n : QObject(parent),\n m_model(0),\n m_parent(parent),\n m_availableSourcesView(0),\n m_availablePagesView(0),\n m_pageView(0),\n m_editorView(0),\n m_noteCombo(0),\n m_taskCombo(0),\n m_mode(mode)\n{\n}\n\nQObject *ApplicationComponents::model() const\n{\n return m_model;\n}\n\nAvailableSourcesView *ApplicationComponents::availableSourcesView() const\n{\n if (!m_availableSourcesView) {\n auto availableSourcesView = new AvailableSourcesView(m_parent);\n if (m_model) {\n availableSourcesView->setModel(m_model->property(\"availableSources\").value<QObject*>());\n if (m_mode == NotesOnly) {\n availableSourcesView->setDefaultSourceProperty(m_model, \"defaultNoteDataSource\");\n connect(m_model, SIGNAL(defaultNoteDataSourceChanged(Domain::DataSource::Ptr)),\n availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n connect(availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n } else if (m_mode == TasksOnly) {\n availableSourcesView->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(m_model, SIGNAL(defaultTaskDataSourceChanged(Domain::DataSource::Ptr)),\n availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n connect(availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n } else {\n availableSourcesView->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(m_model, SIGNAL(defaultTaskDataSourceChanged(Domain::DataSource::Ptr)),\n availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n \/\/TODO decide wether to set task or note source depending on source type?\n connect(availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n connect(availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n }\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_availableSourcesView = availableSourcesView;\n }\n\n return m_availableSourcesView;\n}\n\nAvailablePagesView *ApplicationComponents::availablePagesView() const\n{\n if (!m_availablePagesView) {\n auto availablePagesView = new AvailablePagesView(m_parent);\n if (m_model) {\n availablePagesView->setModel(m_model->property(\"availablePages\").value<QObject*>());\n availablePagesView->setProjectSourcesModel(m_model->property(\"taskSourcesModel\").value<QAbstractItemModel*>());\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_availablePagesView = availablePagesView;\n\n connect(self->m_availablePagesView, SIGNAL(currentPageChanged(QObject*)),\n self, SLOT(onCurrentPageChanged(QObject*)));\n }\n\n return m_availablePagesView;\n}\n\nPageView *ApplicationComponents::pageView() const\n{\n if (!m_pageView) {\n auto pageView = new PageView(m_parent, m_mode == NotesOnly ? PageView::NotesOnly : PageView::TasksOnly);\n if (m_model) {\n pageView->setModel(m_model->property(\"currentPage\").value<QObject*>());\n connect(m_model, SIGNAL(currentPageChanged(QObject*)),\n pageView, SLOT(setModel(QObject*)));\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_pageView = pageView;\n\n connect(self->m_pageView, SIGNAL(currentArtifactChanged(Domain::Artifact::Ptr)),\n self, SLOT(onCurrentArtifactChanged(Domain::Artifact::Ptr)));\n }\n\n return m_pageView;\n}\n\nEditorView *ApplicationComponents::editorView() const\n{\n if (!m_editorView) {\n auto editorView = new EditorView(m_parent);\n if (m_model) {\n editorView->setModel(m_model->property(\"editor\").value<QObject*>());\n }\n\n auto self = const_cast<ApplicationComponents*>(this);\n self->m_editorView = editorView;\n }\n\n return m_editorView;\n}\n\nQList<QAction *> ApplicationComponents::configureActions() const\n{\n if (m_configureActions.isEmpty()) {\n QList<QAction*> actions;\n\n if (m_mode == TasksAndNotes) {\n auto widget = new QWidget;\n widget->setLayout(new QHBoxLayout);\n widget->layout()->addWidget(new QLabel(tr(\"Default task source\")));\n widget->layout()->addWidget(defaultTaskSourceCombo());\n\n auto comboAction = new QWidgetAction(m_parent);\n comboAction->setObjectName(\"zanshin_settings_task_sources\");\n comboAction->setDefaultWidget(widget);\n actions << comboAction;\n\n widget = new QWidget;\n widget->setLayout(new QHBoxLayout);\n widget->layout()->addWidget(new QLabel(tr(\"Default note source\")));\n widget->layout()->addWidget(defaultNoteSourceCombo());\n\n comboAction = new QWidgetAction(m_parent);\n comboAction->setObjectName(\"zanshin_settings_note_sources\");\n comboAction->setDefaultWidget(widget);\n actions << comboAction;\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_configureActions = actions;\n }\n\n return m_configureActions;\n}\n\nDataSourceComboBox *ApplicationComponents::defaultNoteSourceCombo() const\n{\n if (!m_noteCombo) {\n auto combo = new DataSourceComboBox(m_parent);\n combo->setObjectName(\"noteSourceCombo\");\n combo->setFixedWidth(300);\n if (m_model) {\n combo->setModel(m_model->property(\"noteSourcesModel\").value<QAbstractItemModel*>());\n combo->setDefaultSourceProperty(m_model, \"defaultNoteDataSource\");\n connect(combo, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_noteCombo = combo;\n }\n\n return m_noteCombo;\n}\n\nDataSourceComboBox *ApplicationComponents::defaultTaskSourceCombo() const\n{\n if (!m_taskCombo) {\n auto combo = new DataSourceComboBox(m_parent);\n combo->setObjectName(\"taskSourceCombo\");\n combo->setFixedWidth(300);\n if (m_model) {\n combo->setModel(m_model->property(\"taskSourcesModel\").value<QAbstractItemModel*>());\n combo->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(combo, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_taskCombo = combo;\n }\n\n return m_taskCombo;\n}\n\nvoid ApplicationComponents::setModel(QObject *model)\n{\n if (m_model == model)\n return;\n\n m_model = model;\n\n if (m_availableSourcesView) {\n m_availableSourcesView->setModel(m_model->property(\"availableSources\").value<QObject*>());\n m_availableSourcesView->setDefaultSourceProperty(m_model, \"defaultNoteDataSource\");\n }\n\n if (m_availablePagesView) {\n m_availablePagesView->setModel(m_model->property(\"availablePages\").value<QObject*>());\n m_availablePagesView->setProjectSourcesModel(m_model->property(\"taskSourcesModel\").value<QAbstractItemModel*>());\n }\n\n if (m_pageView) {\n m_pageView->setModel(m_model->property(\"currentPage\").value<QObject*>());\n connect(m_model, SIGNAL(currentPageChanged(QObject*)),\n m_pageView, SLOT(setModel(QObject*)));\n }\n\n if (m_editorView)\n m_editorView->setModel(m_model->property(\"editor\").value<QObject*>());\n\n if (m_noteCombo) {\n m_noteCombo->setModel(m_model->property(\"noteSourcesModel\").value<QAbstractItemModel*>());\n m_noteCombo->setDefaultSourceProperty(m_model, \"defaultNoteDataSource\");\n connect(m_noteCombo, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n }\n\n if (m_taskCombo) {\n m_taskCombo->setModel(m_model->property(\"taskSourcesModel\").value<QAbstractItemModel*>());\n m_taskCombo->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(m_noteCombo, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n }\n}\n\nvoid ApplicationComponents::onCurrentPageChanged(QObject *page)\n{\n m_model->setProperty(\"currentPage\", QVariant::fromValue(page));\n\n QObject *editorModel = m_model->property(\"editor\").value<QObject*>();\n if (editorModel)\n editorModel->setProperty(\"artifact\", QVariant::fromValue(Domain::Artifact::Ptr()));\n}\n\nvoid ApplicationComponents::onCurrentArtifactChanged(const Domain::Artifact::Ptr &artifact)\n{\n auto editorModel = m_model->property(\"editor\").value<QObject*>();\n editorModel->setProperty(\"artifact\", QVariant::fromValue(artifact));\n}\n<commit_msg>Depending on what comes first we may have to reconnect<commit_after>\/* This file is part of Zanshin\n\n Copyright 2014 Kevin Ottens <ervin@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n\n#include \"applicationcomponents.h\"\n\n#include <QBoxLayout>\n#include <QLabel>\n#include <QVariant>\n#include <QWidget>\n#include <QWidgetAction>\n\n#include \"availablepagesview.h\"\n#include \"availablesourcesview.h\"\n#include \"datasourcecombobox.h\"\n#include \"editorview.h\"\n#include \"pageview.h\"\n\n#include \"presentation\/applicationmodel.h\"\n\nusing namespace Widgets;\n\nApplicationComponents::ApplicationComponents(QWidget *parent, ApplicationMode mode)\n : QObject(parent),\n m_model(0),\n m_parent(parent),\n m_availableSourcesView(0),\n m_availablePagesView(0),\n m_pageView(0),\n m_editorView(0),\n m_noteCombo(0),\n m_taskCombo(0),\n m_mode(mode)\n{\n}\n\nQObject *ApplicationComponents::model() const\n{\n return m_model;\n}\n\nAvailableSourcesView *ApplicationComponents::availableSourcesView() const\n{\n if (!m_availableSourcesView) {\n auto availableSourcesView = new AvailableSourcesView(m_parent);\n if (m_model) {\n availableSourcesView->setModel(m_model->property(\"availableSources\").value<QObject*>());\n if (m_mode == NotesOnly) {\n availableSourcesView->setDefaultSourceProperty(m_model, \"defaultNoteDataSource\");\n connect(m_model, SIGNAL(defaultNoteDataSourceChanged(Domain::DataSource::Ptr)),\n availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n connect(availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n } else if (m_mode == TasksOnly) {\n availableSourcesView->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(m_model, SIGNAL(defaultTaskDataSourceChanged(Domain::DataSource::Ptr)),\n availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n connect(availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n } else {\n availableSourcesView->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(m_model, SIGNAL(defaultTaskDataSourceChanged(Domain::DataSource::Ptr)),\n availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n \/\/TODO decide wether to set task or note source depending on source type?\n connect(availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n connect(availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n }\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_availableSourcesView = availableSourcesView;\n }\n\n return m_availableSourcesView;\n}\n\nAvailablePagesView *ApplicationComponents::availablePagesView() const\n{\n if (!m_availablePagesView) {\n auto availablePagesView = new AvailablePagesView(m_parent);\n if (m_model) {\n availablePagesView->setModel(m_model->property(\"availablePages\").value<QObject*>());\n availablePagesView->setProjectSourcesModel(m_model->property(\"taskSourcesModel\").value<QAbstractItemModel*>());\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_availablePagesView = availablePagesView;\n\n connect(self->m_availablePagesView, SIGNAL(currentPageChanged(QObject*)),\n self, SLOT(onCurrentPageChanged(QObject*)));\n }\n\n return m_availablePagesView;\n}\n\nPageView *ApplicationComponents::pageView() const\n{\n if (!m_pageView) {\n auto pageView = new PageView(m_parent, m_mode == NotesOnly ? PageView::NotesOnly : PageView::TasksOnly);\n if (m_model) {\n pageView->setModel(m_model->property(\"currentPage\").value<QObject*>());\n connect(m_model, SIGNAL(currentPageChanged(QObject*)),\n pageView, SLOT(setModel(QObject*)));\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_pageView = pageView;\n\n connect(self->m_pageView, SIGNAL(currentArtifactChanged(Domain::Artifact::Ptr)),\n self, SLOT(onCurrentArtifactChanged(Domain::Artifact::Ptr)));\n }\n\n return m_pageView;\n}\n\nEditorView *ApplicationComponents::editorView() const\n{\n if (!m_editorView) {\n auto editorView = new EditorView(m_parent);\n if (m_model) {\n editorView->setModel(m_model->property(\"editor\").value<QObject*>());\n }\n\n auto self = const_cast<ApplicationComponents*>(this);\n self->m_editorView = editorView;\n }\n\n return m_editorView;\n}\n\nQList<QAction *> ApplicationComponents::configureActions() const\n{\n if (m_configureActions.isEmpty()) {\n QList<QAction*> actions;\n\n if (m_mode == TasksAndNotes) {\n auto widget = new QWidget;\n widget->setLayout(new QHBoxLayout);\n widget->layout()->addWidget(new QLabel(tr(\"Default task source\")));\n widget->layout()->addWidget(defaultTaskSourceCombo());\n\n auto comboAction = new QWidgetAction(m_parent);\n comboAction->setObjectName(\"zanshin_settings_task_sources\");\n comboAction->setDefaultWidget(widget);\n actions << comboAction;\n\n widget = new QWidget;\n widget->setLayout(new QHBoxLayout);\n widget->layout()->addWidget(new QLabel(tr(\"Default note source\")));\n widget->layout()->addWidget(defaultNoteSourceCombo());\n\n comboAction = new QWidgetAction(m_parent);\n comboAction->setObjectName(\"zanshin_settings_note_sources\");\n comboAction->setDefaultWidget(widget);\n actions << comboAction;\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_configureActions = actions;\n }\n\n return m_configureActions;\n}\n\nDataSourceComboBox *ApplicationComponents::defaultNoteSourceCombo() const\n{\n if (!m_noteCombo) {\n auto combo = new DataSourceComboBox(m_parent);\n combo->setObjectName(\"noteSourceCombo\");\n combo->setFixedWidth(300);\n if (m_model) {\n combo->setModel(m_model->property(\"noteSourcesModel\").value<QAbstractItemModel*>());\n combo->setDefaultSourceProperty(m_model, \"defaultNoteDataSource\");\n connect(combo, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_noteCombo = combo;\n }\n\n return m_noteCombo;\n}\n\nDataSourceComboBox *ApplicationComponents::defaultTaskSourceCombo() const\n{\n if (!m_taskCombo) {\n auto combo = new DataSourceComboBox(m_parent);\n combo->setObjectName(\"taskSourceCombo\");\n combo->setFixedWidth(300);\n if (m_model) {\n combo->setModel(m_model->property(\"taskSourcesModel\").value<QAbstractItemModel*>());\n combo->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(combo, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n }\n\n ApplicationComponents *self = const_cast<ApplicationComponents*>(this);\n self->m_taskCombo = combo;\n }\n\n return m_taskCombo;\n}\n\nvoid ApplicationComponents::setModel(QObject *model)\n{\n if (m_model == model)\n return;\n\n m_model = model;\n\n if (m_availableSourcesView) {\n m_availableSourcesView->setModel(m_model->property(\"availableSources\").value<QObject*>());\n if (m_mode == NotesOnly) {\n m_availableSourcesView->setDefaultSourceProperty(m_model, \"defaultNoteDataSource\");\n connect(m_model, SIGNAL(defaultNoteDataSourceChanged(Domain::DataSource::Ptr)),\n m_availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n connect(m_availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n } else if (m_mode == TasksOnly) {\n m_availableSourcesView->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(m_model, SIGNAL(defaultTaskDataSourceChanged(Domain::DataSource::Ptr)),\n m_availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n connect(m_availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n } else {\n m_availableSourcesView->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(m_model, SIGNAL(defaultTaskDataSourceChanged(Domain::DataSource::Ptr)),\n m_availableSourcesView, SLOT(setDefaultSource(Domain::DataSource::Ptr)));\n \/\/TODO decide wether to set task or note source depending on source type?\n connect(m_availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n connect(m_availableSourcesView, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n }\n }\n\n if (m_availablePagesView) {\n m_availablePagesView->setModel(m_model->property(\"availablePages\").value<QObject*>());\n m_availablePagesView->setProjectSourcesModel(m_model->property(\"taskSourcesModel\").value<QAbstractItemModel*>());\n }\n\n if (m_pageView) {\n m_pageView->setModel(m_model->property(\"currentPage\").value<QObject*>());\n connect(m_model, SIGNAL(currentPageChanged(QObject*)),\n m_pageView, SLOT(setModel(QObject*)));\n }\n\n if (m_editorView)\n m_editorView->setModel(m_model->property(\"editor\").value<QObject*>());\n\n if (m_noteCombo) {\n m_noteCombo->setModel(m_model->property(\"noteSourcesModel\").value<QAbstractItemModel*>());\n m_noteCombo->setDefaultSourceProperty(m_model, \"defaultNoteDataSource\");\n connect(m_noteCombo, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultNoteDataSource(Domain::DataSource::Ptr)));\n }\n\n if (m_taskCombo) {\n m_taskCombo->setModel(m_model->property(\"taskSourcesModel\").value<QAbstractItemModel*>());\n m_taskCombo->setDefaultSourceProperty(m_model, \"defaultTaskDataSource\");\n connect(m_noteCombo, SIGNAL(sourceActivated(Domain::DataSource::Ptr)),\n m_model, SLOT(setDefaultTaskDataSource(Domain::DataSource::Ptr)));\n }\n}\n\nvoid ApplicationComponents::onCurrentPageChanged(QObject *page)\n{\n m_model->setProperty(\"currentPage\", QVariant::fromValue(page));\n\n QObject *editorModel = m_model->property(\"editor\").value<QObject*>();\n if (editorModel)\n editorModel->setProperty(\"artifact\", QVariant::fromValue(Domain::Artifact::Ptr()));\n}\n\nvoid ApplicationComponents::onCurrentArtifactChanged(const Domain::Artifact::Ptr &artifact)\n{\n auto editorModel = m_model->property(\"editor\").value<QObject*>();\n editorModel->setProperty(\"artifact\", QVariant::fromValue(artifact));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <os>\n#include <net\/inet4>\n#include <math.h>\n#include <iostream>\n#include <sstream>\n#include <net\/dhcp\/dh4client.hpp>\n\nusing namespace std::chrono;\n\n\/\/ An IP-stack object\nstd::unique_ptr<net::Inet4<VirtioNet> > inet;\n\nvoid Service::start() {\n \n \/\/ Assign a driver (VirtioNet) to a network interface (eth0)\n \/\/ @note: We could determine the appropirate driver dynamically, but then we'd\n \/\/ have to include all the drivers into the image, which we want to avoid.\n Nic<VirtioNet>& eth0 = Dev::eth<0,VirtioNet>();\n \n \/\/ Bring up a network stack, attached to the nic\n inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);\n \n printf(\"Size of IP-stack: %i bytes \\n\",sizeof(inet));\n printf(\"Service IP address: %s \\n\", inet->ip_addr().str().c_str());\n \n \/\/ Set up a TCP server on port 80\n net::TCP::Socket& sock = inet->tcp().bind(80);\n \n printf(\"SERVICE: %i open ports in TCP @ %p \\n\",\n inet->tcp().openPorts(), &(inet->tcp()));\n\n srand(OS::cycles_since_boot());\n \n sock.onConnect([](net::TCP::Socket& conn){\n printf(\"SERVICE got data: %s \\n\",conn.read(1024).c_str());\n \n int color = rand();\n std::stringstream stream;\n \n \/* HTML Fonts *\/\n std::string ubuntu_medium = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 500; \";\n std::string ubuntu_normal = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 400; \";\n std::string ubuntu_light = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 300; \";\n \n \/* HTML *\/\n stream << \"<html><head>\"\n\t << \"<link href='https:\/\/fonts.googleapis.com\/css?family=Ubuntu:500,300' rel='stylesheet' type='text\/css'>\"\n\t << \"<\/head><body>\"\n\t << \"<h1 style= \\\"color: \" << \"#\" << std::hex << (color >> 8) << \"\\\">\"\t\n\t << \"<span style=\\\"\"+ubuntu_medium+\"\\\">Include<\/span><span style=\\\"\"+ubuntu_light+\"\\\">OS<\/span> <\/h1>\"\n\t << \"<h2>Now speaks TCP!<\/h2>\"\n\t\/\/ .... generate more dynamic content \n\t << \"<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far <\/p>\"\n\t << \"<footer><hr \/> © 2015, Oslo and Akershus University College of Applied Sciences <\/footer>\"\n\t << \"<\/body><\/html>\\n\";\n \n \/* HTTP-header *\/\n std::string html = stream.str();\n std::string header=\"HTTP\/1.1 200 OK \\n \"\t\t\t\t\\\n\t\"Date: Mon, 01 Jan 1970 00:00:01 GMT \\n\"\t\t\t\\\n\t\"Server: IncludeOS prototype 4.0 \\n\"\t\t\t\t\\\n\t\"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \\n\"\t\t\\\n\t\"Content-Type: text\/html; charset=UTF-8 \\n\"\t\t\t\\\n\t\"Content-Length: \"+std::to_string(html.size())+\"\\n\"\t\t\\\n\t\"Accept-Ranges: bytes\\n\"\t\t\t\t\t\\\n\t\"Connection: close\\n\\n\";\n \n conn.write(header);\n conn.write(html);\n \n \/\/ We don't have to actively close when the http-header says \"Connection: close\"\n \/\/conn.close();\n \n });\n \n printf(\"*** TEST SERVICE STARTED *** \\n\"); \n\n}\n<commit_msg>Demo service has static IP + DHCP<commit_after>#include <os>\n#include <net\/inet4>\n#include <math.h>\n#include <iostream>\n#include <sstream>\n#include <net\/dhcp\/dh4client.hpp>\n\nusing namespace std::chrono;\n\n\/\/ An IP-stack object\nstd::unique_ptr<net::Inet4<VirtioNet> > inet;\n\nvoid Service::start() {\n \n \/\/ Assign a driver (VirtioNet) to a network interface (eth0)\n \/\/ @note: We could determine the appropirate driver dynamically, but then we'd\n \/\/ have to include all the drivers into the image, which we want to avoid.\n Nic<VirtioNet>& eth0 = Dev::eth<0,VirtioNet>();\n \n \/\/ Bring up a network stack, attached to the nic\n inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);\n \n \/\/ Static configuration, until we (possibly) get DHCP\n inet->network_config( {{ 10,0,0,42 }}, \/\/ IP\n\t\t\t{{ 255,255,255,0 }}, \/\/ Netmask\n\t\t\t{{ 10,0,0,1 }}, \/\/ Gateway\n\t\t\t{{ 8,8,8,8 }} ); \/\/ DNS\n \n printf(\"Size of IP-stack: %i b \\n\",sizeof(inet));\n printf(\"Service IP address: %s \\n\", inet->ip_addr().str().c_str());\n \n \/\/ Set up a TCP server on port 80\n net::TCP::Socket& sock = inet->tcp().bind(80);\n \n printf(\"SERVICE: %i open ports in TCP @ %p \\n\",\n inet->tcp().openPorts(), &(inet->tcp()));\n\n srand(OS::cycles_since_boot());\n \n sock.onConnect([](net::TCP::Socket& conn){\n printf(\"SERVICE got data: %s \\n\",conn.read(1024).c_str());\n \n int color = rand();\n std::stringstream stream;\n \n \/* HTML Fonts *\/\n std::string ubuntu_medium = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 500; \";\n std::string ubuntu_normal = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 400; \";\n std::string ubuntu_light = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 300; \";\n \n \/* HTML *\/\n stream << \"<html><head>\"\n\t << \"<link href='https:\/\/fonts.googleapis.com\/css?family=Ubuntu:500,300' rel='stylesheet' type='text\/css'>\"\n\t << \"<\/head><body>\"\n\t << \"<h1 style= \\\"color: \" << \"#\" << std::hex << (color >> 8) << \"\\\">\"\t\n\t << \"<span style=\\\"\"+ubuntu_medium+\"\\\">Include<\/span><span style=\\\"\"+ubuntu_light+\"\\\">OS<\/span> <\/h1>\"\n\t << \"<h2>Now speaks TCP!<\/h2>\"\n\t\/\/ .... generate more dynamic content \n\t << \"<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far <\/p>\"\n\t << \"<footer><hr \/> © 2015, Oslo and Akershus University College of Applied Sciences <\/footer>\"\n\t << \"<\/body><\/html>\\n\";\n \n \/* HTTP-header *\/\n std::string html = stream.str();\n std::string header=\"HTTP\/1.1 200 OK \\n \"\t\t\t\t\\\n\t\"Date: Mon, 01 Jan 1970 00:00:01 GMT \\n\"\t\t\t\\\n\t\"Server: IncludeOS prototype 4.0 \\n\"\t\t\t\t\\\n\t\"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \\n\"\t\t\\\n\t\"Content-Type: text\/html; charset=UTF-8 \\n\"\t\t\t\\\n\t\"Content-Length: \"+std::to_string(html.size())+\"\\n\"\t\t\\\n\t\"Accept-Ranges: bytes\\n\"\t\t\t\t\t\\\n\t\"Connection: close\\n\\n\";\n \n conn.write(header);\n conn.write(html);\n \n \/\/ We don't have to actively close when the http-header says \"Connection: close\"\n \/\/conn.close();\n \n });\n \n printf(\"*** TEST SERVICE STARTED *** \\n\"); \n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016, The Bifrost Authors. 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 * * 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 Bifrost Authors 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 ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * 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\n#include <bifrost\/proclog.h>\n#include \"trace.hpp\"\n#include \"proclog.hpp\"\n\n#include <fstream>\n#include <cstdlib> \/\/ For system\n#include <cstdarg> \/\/ For va_start, va_list, va_end\n#include <sys\/file.h> \/\/ For flock\n#include <sys\/stat.h> \/\/ For fstat\n#include <sys\/types.h> \/\/ For getpid\n#include <dirent.h> \/\/ For opendir, readdir, closedir\n#include <unistd.h> \/\/ For getpid\n#include <system_error>\n#include <set>\n#include <mutex>\n\nvoid make_dir(std::string path, int perms=775) {\n\tif( std::system((\"mkdir -p \"+path+\" -m \"+std::to_string(perms)).c_str()) ) {\n\t\tthrow std::runtime_error(\"Failed to create path: \"+path);\n\t}\n}\nvoid remove_all(std::string path) {\n\tif( std::system((\"rm -rf \"+path).c_str()) ) {\n\t\tthrow std::runtime_error(\"Failed to remove all: \"+path);\n\t}\n}\nvoid remove_dir(std::string path) {\n\tif( std::system((\"rmdir \"+path+\" 2> \/dev\/null\").c_str()) ) {\n\t\tthrow std::runtime_error(\"Failed to remove dir: \"+path);\n\t}\n}\nvoid remove_file(std::string path) {\n\tif( std::system((\"rm -f \"+path).c_str()) ) {\n\t\tthrow std::runtime_error(\"Failed to remove file: \"+path);\n\t}\n}\nbool process_exists(pid_t pid) {\n\tstruct stat s;\n\treturn !(stat((\"\/proc\/\"+std::to_string(pid)).c_str(), &s) == -1\n\t && errno == ENOENT);\n}\n\nstd::string get_dirname(std::string filename) {\n\t\/\/ TODO: This is crude, but works for our proclog use-case\n\treturn filename.substr(0, filename.find_last_of(\"\/\"));\n}\n\nclass LockFile {\n\tstd::string _lockfile;\n\tint _fd;\npublic:\n\tLockFile(LockFile const& ) = delete;\n\tLockFile& operator=(LockFile const& ) = delete;\n\tLockFile(std::string lockfile) : _lockfile(lockfile) {\n\t\twhile( true ) {\n\t\t\t_fd = open(_lockfile.c_str(), O_CREAT, 600);\n\t\t\tflock(_fd, LOCK_EX);\n\t\t\tstruct stat fd_stat, lockfile_stat;\n\t\t\tfstat(_fd, &fd_stat);\n\t\t\tstat(_lockfile.c_str(), &lockfile_stat);\n\t\t\t\/\/ Compare inodes\n\t\t\tif( fd_stat.st_ino == lockfile_stat.st_ino ) {\n\t\t\t\t\/\/ Got the lock\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tclose(_fd);\n\t\t}\n\t}\n\t~LockFile() {\n\t\tunlink(_lockfile.c_str());\n\t\tflock(_fd, LOCK_UN);\n\t}\n};\n\nclass ProcLogMgr {\n\tstatic constexpr const char* base_logdir = \"\/dev\/shm\/bifrost\";\n\tstd::string _logdir;\n\tstd::set<std::string> _logs;\n\tstd::set<std::string> _created_dirs;\n\tmutable std::mutex _mutex;\n\tvoid try_base_logdir_cleanup() {\n\t\t\/\/ Do this with a file lock to avoid interference from other processes\n\t\tLockFile lock(std::string(base_logdir) + \".lock\");\n\t\tDIR* dp;\n\t\t\/\/ Remove pid dirs for which a corresponding process does not exist\n\t\tif( (dp = opendir(base_logdir)) ) {\n\t\t\tstruct dirent* ep;\n\t\t\twhile( (ep = readdir(dp)) ) {\n\t\t\t\tpid_t pid = atoi(ep->d_name);\n\t\t\t\tif( pid && !process_exists(pid) ) {\n\t\t\t\t\tremove_all(std::string(base_logdir) + \"\/\" +\n\t\t\t\t\t std::to_string(pid));\n\t\t\t\t}\n\t\t\t}\n\t\t\tclosedir(dp);\n\t\t}\n\t\t\/\/ Remove the base_logdir if it's empty\n\t\ttry { remove_dir(base_logdir); }\n\t\tcatch( std::exception ) {}\n\t}\n\tProcLogMgr()\n\t\t: _logdir(std::string(base_logdir) + \"\/\" + std::to_string(getpid())) {\n\t\tthis->try_base_logdir_cleanup();\n\t\tmake_dir(base_logdir, 777);\n\t\tmake_dir(_logdir);\n\t}\n\t~ProcLogMgr() {\n\t\ttry {\n\t\t\tremove_all(_logdir);\n\t\t\tthis->try_base_logdir_cleanup();\n\t\t} catch( std::exception ) {}\n\t}\n\tFILE* open_file(std::string filename) {\n\t\t\/\/ Note: Individual log dirs and files are only created if they are\n\t\t\/\/ actually updated with data.\n\t\t\/\/ Note: name may contain subdirs, so we must ensure they exist first\n\t\tthis->ensure_dir_exists(filename);\n\t\tFILE* logfile = (FILE*)fopen(filename.c_str(), \"w\");\n\t\tif( !logfile ) {\n\t\t\tthrow std::runtime_error(\"fopen(\\\"\"+filename+\"\\\", \\\"w\\\") failed\");\n\t\t}\n\t\treturn logfile;\n\t}\npublic:\n\tProcLogMgr(ProcLogMgr& ) = delete;\n\tProcLogMgr& operator=(ProcLogMgr& ) = delete;\n\tstatic ProcLogMgr& get() {\n\t\tstatic ProcLogMgr proclog;\n\t\treturn proclog;\n\t}\n\tvoid ensure_dir_exists(std::string filename) {\n\t\tstd::string dirname = get_dirname(filename);\n\t\tif( !_created_dirs.count(dirname) ) {\n\t\t\t\/\/ Note: make_dir is really slow, so we ensure we call it only once\n\t\t\tmake_dir(dirname);\n\t\t\t_created_dirs.insert(dirname);\n\t\t}\n\t}\n\tstd::string create_log(std::string name) {\n\t\tstd::lock_guard<std::mutex> lock(_mutex);\n\t\tstd::string origname = name;\n\t\tint i = 1;\n\t\twhile( _logs.count(name) ) {\n\t\t\t\/\/ Disambiguate by adding suffix to name\n\t\t\tname = origname + \"_\" + std::to_string(++i);\n\t\t}\n\t\tstd::string filename = _logdir + \"\/\" + name;\n\t\t_logs.insert(filename);\n\t\treturn filename;\n\t}\n\tvoid destroy_log(std::string filename) {\n\t\tstd::lock_guard<std::mutex> lock(_mutex);\n\t\tremove_file(filename);\n\t\t_logs.erase(filename);\n\t}\n\tvoid update_log_s(std::string filename, const char* str) {\n\t\tstd::lock_guard<std::mutex> lock(_mutex);\n\t\tFILE* logfile = this->open_file(filename);\n\t\tfputs(str, logfile);\n\t\tfclose(logfile);\n\t}\n\tvoid update_log_v(std::string filename, const char* fmt, va_list args) {\n\t\tstd::lock_guard<std::mutex> lock(_mutex);\n\t\tFILE* logfile = this->open_file(filename);\n\t\tvfprintf(logfile, fmt, args);\n\t\tfclose(logfile);\n\t}\n};\n\nBFproclog_impl::BFproclog_impl(std::string name)\n\t: _filename(ProcLogMgr::get().create_log(name)) {}\nBFproclog_impl::~BFproclog_impl() {\n\tProcLogMgr::get().destroy_log(_filename);\n}\nvoid BFproclog_impl::update_s(const char* str) {\n\tProcLogMgr::get().update_log_s(_filename, str);\n}\nvoid BFproclog_impl::update_v(const char* fmt, va_list args) {\n\tProcLogMgr::get().update_log_v(_filename, fmt, args);\n}\nvoid BFproclog_impl::update(const char* fmt, ...) {\n\tva_list args;\n\tva_start(args, fmt);\n\tthis->update_v(fmt, args);\n\tva_end(args);\n}\nmovable_ofstream_WAR BFproclog_impl::update() {\n\tProcLogMgr::get().ensure_dir_exists(_filename);\n\t\/\/ TODO: gcc < 5 has a bug where std streams are not movable\n\t\/\/return std::ofstream(_filename);\n\treturn movable_ofstream_WAR(_filename);\n}\n\nBFstatus bfProcLogCreate(BFproclog* log_ptr, const char* name) {\n\tBF_ASSERT(log_ptr, BF_STATUS_INVALID_POINTER);\n\tBF_ASSERT(name, BF_STATUS_INVALID_POINTER);\n\tBF_TRY_RETURN_ELSE(*log_ptr = new BFproclog_impl(name),\n\t *log_ptr = 0);\n}\nBFstatus bfProcLogDestroy(BFproclog log) {\n\tBF_ASSERT(log, BF_STATUS_INVALID_HANDLE);\n\tdelete log;\n\treturn BF_STATUS_SUCCESS;\n}\nBFstatus bfProcLogUpdate(BFproclog log, const char* str) {\n\tBF_ASSERT(log, BF_STATUS_INVALID_HANDLE);\n\tBF_ASSERT(str, BF_STATUS_INVALID_POINTER);\n\tBF_TRY_RETURN(log->update_s(str));\n}\n<commit_msg>Cleaned up proclog.cpp to better deal with pipelines using multiple version of the same block. This is done by looking for a '\/' in the logname and splitting on that character to get the block name for de-duplication purposes.<commit_after>\/*\n * Copyright (c) 2016, The Bifrost Authors. 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 * * 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 Bifrost Authors 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 ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * 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\n#include <bifrost\/proclog.h>\n#include \"trace.hpp\"\n#include \"proclog.hpp\"\n\n#include <fstream>\n#include <cstdlib> \/\/ For system\n#include <cstdarg> \/\/ For va_start, va_list, va_end\n#include <sys\/file.h> \/\/ For flock\n#include <sys\/stat.h> \/\/ For fstat\n#include <sys\/types.h> \/\/ For getpid\n#include <dirent.h> \/\/ For opendir, readdir, closedir\n#include <unistd.h> \/\/ For getpid\n#include <system_error>\n#include <set>\n#include <mutex>\n\nvoid make_dir(std::string path, int perms=775) {\n\tif( std::system((\"mkdir -p \"+path+\" -m \"+std::to_string(perms)).c_str()) ) {\n\t\tthrow std::runtime_error(\"Failed to create path: \"+path);\n\t}\n}\nvoid remove_all(std::string path) {\n\tif( std::system((\"rm -rf \"+path).c_str()) ) {\n\t\tthrow std::runtime_error(\"Failed to remove all: \"+path);\n\t}\n}\nvoid remove_dir(std::string path) {\n\tif( std::system((\"rmdir \"+path+\" 2> \/dev\/null\").c_str()) ) {\n\t\tthrow std::runtime_error(\"Failed to remove dir: \"+path);\n\t}\n}\nvoid remove_file(std::string path) {\n\tif( std::system((\"rm -f \"+path).c_str()) ) {\n\t\tthrow std::runtime_error(\"Failed to remove file: \"+path);\n\t}\n}\nbool process_exists(pid_t pid) {\n\tstruct stat s;\n\treturn !(stat((\"\/proc\/\"+std::to_string(pid)).c_str(), &s) == -1\n\t && errno == ENOENT);\n}\n\nstd::string get_dirname(std::string filename) {\n\t\/\/ TODO: This is crude, but works for our proclog use-case\n\treturn filename.substr(0, filename.find_last_of(\"\/\"));\n}\n\nclass LockFile {\n\tstd::string _lockfile;\n\tint _fd;\npublic:\n\tLockFile(LockFile const& ) = delete;\n\tLockFile& operator=(LockFile const& ) = delete;\n\tLockFile(std::string lockfile) : _lockfile(lockfile) {\n\t\twhile( true ) {\n\t\t\t_fd = open(_lockfile.c_str(), O_CREAT, 600);\n\t\t\tflock(_fd, LOCK_EX);\n\t\t\tstruct stat fd_stat, lockfile_stat;\n\t\t\tfstat(_fd, &fd_stat);\n\t\t\tstat(_lockfile.c_str(), &lockfile_stat);\n\t\t\t\/\/ Compare inodes\n\t\t\tif( fd_stat.st_ino == lockfile_stat.st_ino ) {\n\t\t\t\t\/\/ Got the lock\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tclose(_fd);\n\t\t}\n\t}\n\t~LockFile() {\n\t\tunlink(_lockfile.c_str());\n\t\tflock(_fd, LOCK_UN);\n\t}\n};\n\nclass ProcLogMgr {\n\tstatic constexpr const char* base_logdir = \"\/dev\/shm\/bifrost\";\n\tstd::string _logdir;\n\tstd::set<std::string> _logs;\n\tstd::set<std::string> _created_dirs;\n\tmutable std::mutex _mutex;\n\tvoid try_base_logdir_cleanup() {\n\t\t\/\/ Do this with a file lock to avoid interference from other processes\n\t\tLockFile lock(std::string(base_logdir) + \".lock\");\n\t\tDIR* dp;\n\t\t\/\/ Remove pid dirs for which a corresponding process does not exist\n\t\tif( (dp = opendir(base_logdir)) ) {\n\t\t\tstruct dirent* ep;\n\t\t\twhile( (ep = readdir(dp)) ) {\n\t\t\t\tpid_t pid = atoi(ep->d_name);\n\t\t\t\tif( pid && !process_exists(pid) ) {\n\t\t\t\t\tremove_all(std::string(base_logdir) + \"\/\" +\n\t\t\t\t\t std::to_string(pid));\n\t\t\t\t}\n\t\t\t}\n\t\t\tclosedir(dp);\n\t\t}\n\t\t\/\/ Remove the base_logdir if it's empty\n\t\ttry { remove_dir(base_logdir); }\n\t\tcatch( std::exception ) {}\n\t}\n\tProcLogMgr()\n\t\t: _logdir(std::string(base_logdir) + \"\/\" + std::to_string(getpid())) {\n\t\tthis->try_base_logdir_cleanup();\n\t\tmake_dir(base_logdir, 777);\n\t\tmake_dir(_logdir);\n\t}\n\t~ProcLogMgr() {\n\t\ttry {\n\t\t\tremove_all(_logdir);\n\t\t\tthis->try_base_logdir_cleanup();\n\t\t} catch( std::exception ) {}\n\t}\n\tFILE* open_file(std::string filename) {\n\t\t\/\/ Note: Individual log dirs and files are only created if they are\n\t\t\/\/ actually updated with data.\n\t\t\/\/ Note: name may contain subdirs, so we must ensure they exist first\n\t\tthis->ensure_dir_exists(filename);\n\t\tFILE* logfile = (FILE*)fopen(filename.c_str(), \"w\");\n\t\tif( !logfile ) {\n\t\t\tthrow std::runtime_error(\"fopen(\\\"\"+filename+\"\\\", \\\"w\\\") failed\");\n\t\t}\n\t\treturn logfile;\n\t}\npublic:\n\tProcLogMgr(ProcLogMgr& ) = delete;\n\tProcLogMgr& operator=(ProcLogMgr& ) = delete;\n\tstatic ProcLogMgr& get() {\n\t\tstatic ProcLogMgr proclog;\n\t\treturn proclog;\n\t}\n\tvoid ensure_dir_exists(std::string filename) {\n\t\tstd::string dirname = get_dirname(filename);\n\t\tif( !_created_dirs.count(dirname) ) {\n\t\t\t\/\/ Note: make_dir is really slow, so we ensure we call it only once\n\t\t\tmake_dir(dirname);\n\t\t\t_created_dirs.insert(dirname);\n\t\t}\n\t}\n\tstd::string create_log(std::string name) {\n\t\tstd::lock_guard<std::mutex> lock(_mutex);\n\t\tstd::string origname = name;\n\t\tstd::string modname = name.substr(0, name.find(\"\/\"));\n\t\tstd::string logname = name.substr(name.find(\"\/\"), name.length());\n\t\tstd::string filename = _logdir + \"\/\" + name;\n\t\t\n\t\tint i = 1;\n\t\twhile( _logs.count(filename) ) {\n\t\t\t\/\/ Disambiguate by adding suffix to name\n\t\t\tname = modname + \"_\" + std::to_string(++i);\n\t\t\tif( logname.length() > 0 ) {\n\t\t\t\tname = name + \"\/\" + logname;\n\t\t\t}\n\t\t\tfilename = _logdir + \"\/\" + name;\n\t\t}\n\t\t_logs.insert(filename);\n\t\treturn filename;\n\t}\n\tvoid destroy_log(std::string filename) {\n\t\tstd::lock_guard<std::mutex> lock(_mutex);\n\t\tremove_file(filename);\n\t\t_logs.erase(filename);\n\t}\n\tvoid update_log_s(std::string filename, const char* str) {\n\t\tstd::lock_guard<std::mutex> lock(_mutex);\n\t\tFILE* logfile = this->open_file(filename);\n\t\tfputs(str, logfile);\n\t\tfclose(logfile);\n\t}\n\tvoid update_log_v(std::string filename, const char* fmt, va_list args) {\n\t\tstd::lock_guard<std::mutex> lock(_mutex);\n\t\tFILE* logfile = this->open_file(filename);\n\t\tvfprintf(logfile, fmt, args);\n\t\tfclose(logfile);\n\t}\n};\n\nBFproclog_impl::BFproclog_impl(std::string name)\n\t: _filename(ProcLogMgr::get().create_log(name)) {}\nBFproclog_impl::~BFproclog_impl() {\n\tProcLogMgr::get().destroy_log(_filename);\n}\nvoid BFproclog_impl::update_s(const char* str) {\n\tProcLogMgr::get().update_log_s(_filename, str);\n}\nvoid BFproclog_impl::update_v(const char* fmt, va_list args) {\n\tProcLogMgr::get().update_log_v(_filename, fmt, args);\n}\nvoid BFproclog_impl::update(const char* fmt, ...) {\n\tva_list args;\n\tva_start(args, fmt);\n\tthis->update_v(fmt, args);\n\tva_end(args);\n}\nmovable_ofstream_WAR BFproclog_impl::update() {\n\tProcLogMgr::get().ensure_dir_exists(_filename);\n\t\/\/ TODO: gcc < 5 has a bug where std streams are not movable\n\t\/\/return std::ofstream(_filename);\n\treturn movable_ofstream_WAR(_filename);\n}\n\nBFstatus bfProcLogCreate(BFproclog* log_ptr, const char* name) {\n\tBF_ASSERT(log_ptr, BF_STATUS_INVALID_POINTER);\n\tBF_ASSERT(name, BF_STATUS_INVALID_POINTER);\n\tBF_TRY_RETURN_ELSE(*log_ptr = new BFproclog_impl(name),\n\t *log_ptr = 0);\n}\nBFstatus bfProcLogDestroy(BFproclog log) {\n\tBF_ASSERT(log, BF_STATUS_INVALID_HANDLE);\n\tdelete log;\n\treturn BF_STATUS_SUCCESS;\n}\nBFstatus bfProcLogUpdate(BFproclog log, const char* str) {\n\tBF_ASSERT(log, BF_STATUS_INVALID_HANDLE);\n\tBF_ASSERT(str, BF_STATUS_INVALID_POINTER);\n\tBF_TRY_RETURN(log->update_s(str));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2014, Alberto Corona <alberto@0x1a.us>\n\/\/ All rights reserved. This file is part of yabs, distributed under the BSD\n\/\/ 3-Clause license. For full terms please see the LICENSE file.\n\n#include <regex.h>\n#include <string.h>\n#include <yaml.h>\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n#include \"profile.h\"\n\nProfile::Profile()\n{\n\tDocNum = 0;\n}\n\nvoid Profile::IncDocNum()\n{\n\tDocNum++;\n}\n\nint Profile::AssertConfig(unsigned char *value)\n{\n\tif (CompValid(value) != 1) {\n\t\tprintf(\"Error: invalid configuration option: %s\\n\", value);\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nconst char *Profile::ConvValue(unsigned char *conv_value)\n{\n\tstd::string temp_value;\n\ttemp_value.append(reinterpret_cast<const char *>(conv_value));\n\treturn temp_value.c_str();\n}\n\nint Profile::CompValid(unsigned char *comp_value)\n{\n\tfor (int i = 0; i <= MAX_OPT - 1; i++) {\n\t\tif (strcasecmp(STDValues[i], ConvValue(comp_value)) == 0) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nconst char *Profile::PrependLink(const char *string, const char *pre)\n{\n\tstd::string temp_string = string;\n\tstd::string temp_pre = pre;\n\tstd::string n_pre = \" \";\n\tsize_t start_pos = 0;\n\twhile ((start_pos = temp_string.find(n_pre, start_pos)) != std::string::npos) {\n\t\ttemp_string.replace(start_pos, n_pre.length(), temp_pre);\n\t\tstart_pos += temp_pre.length();\n\t}\n\treturn temp_string.c_str();\n}\n\nvoid Profile::OpenInclude(const char *file)\n{\n\tinc_conf = fopen(file, \"r\");\n\tif (inc_conf == NULL) {\n\t\tprintf(\"Error: Couldn't open included file: %s\\n\", file);\n\t}\n}\n\nvoid Profile::PopValidValue(std::string &k_value, const char *v_value)\n{\n\tif (strcasecmp(\"os\", k_value.c_str()) == 0) {\n\t\tOSList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"arch\", k_value.c_str()) == 0) {\n\t\tArchList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"cc\", k_value.c_str()) == 0) {\n\t\tCCList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"cxx\", k_value.c_str()) == 0) {\n\t\tCXXList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"include\", k_value.c_str()) == 0) {\n\t\tConfIncList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"lang\", k_value.c_str()) == 0) {\n\t\tLangList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"dist\", k_value.c_str()) == 0) {\n\t\tDistList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"before-script\", k_value.c_str()) == 0) {\n\t\tBeforeScriptList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"after-script\", k_value.c_str()) == 0) {\n\t\tAfterScriptList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"libs\", k_value.c_str()) == 0) {\n\t\tLibsList.push_back(PrependLink(v_value, \" -l\"));\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"incdir\", k_value.c_str()) == 0) {\n\t\tIncDirList.push_back(PrependLink(v_value, \" -I\"));\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"libdir\", k_value.c_str()) == 0) {\n\t\tLibDirList.push_back(PrependLink(v_value, \" -L\"));\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"target\", k_value.c_str()) == 0) {\n\t\tTargetList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"remote\", k_value.c_str()) == 0) {\n\t\tRemoteList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"defines\", k_value.c_str()) == 0) {\n\t\tDefinesList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n}\n<commit_msg>profile: remove unused headers<commit_after>\/\/ Copyright (c) 2013-2014, Alberto Corona <alberto@0x1a.us>\n\/\/ All rights reserved. This file is part of yabs, distributed under the BSD\n\/\/ 3-Clause license. For full terms please see the LICENSE file.\n\n#include <string.h>\n#include <yaml.h>\n#include <iostream>\n#include <string>\n#include <vector>\n#include \"profile.h\"\n\nProfile::Profile()\n{\n\tDocNum = 0;\n}\n\nvoid Profile::IncDocNum()\n{\n\tDocNum++;\n}\n\nint Profile::AssertConfig(unsigned char *value)\n{\n\tif (CompValid(value) != 1) {\n\t\tprintf(\"Error: invalid configuration option: %s\\n\", value);\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nconst char *Profile::ConvValue(unsigned char *conv_value)\n{\n\tstd::string temp_value;\n\ttemp_value.append(reinterpret_cast<const char *>(conv_value));\n\treturn temp_value.c_str();\n}\n\nint Profile::CompValid(unsigned char *comp_value)\n{\n\tfor (int i = 0; i <= MAX_OPT - 1; i++) {\n\t\tif (strcasecmp(STDValues[i], ConvValue(comp_value)) == 0) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nconst char *Profile::PrependLink(const char *string, const char *pre)\n{\n\tstd::string temp_string = string;\n\tstd::string temp_pre = pre;\n\tstd::string n_pre = \" \";\n\tsize_t start_pos = 0;\n\twhile ((start_pos = temp_string.find(n_pre, start_pos)) != std::string::npos) {\n\t\ttemp_string.replace(start_pos, n_pre.length(), temp_pre);\n\t\tstart_pos += temp_pre.length();\n\t}\n\treturn temp_string.c_str();\n}\n\nvoid Profile::OpenInclude(const char *file)\n{\n\tinc_conf = fopen(file, \"r\");\n\tif (inc_conf == NULL) {\n\t\tprintf(\"Error: Couldn't open included file: %s\\n\", file);\n\t}\n}\n\nvoid Profile::PopValidValue(std::string &k_value, const char *v_value)\n{\n\tif (strcasecmp(\"os\", k_value.c_str()) == 0) {\n\t\tOSList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"arch\", k_value.c_str()) == 0) {\n\t\tArchList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"cc\", k_value.c_str()) == 0) {\n\t\tCCList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"cxx\", k_value.c_str()) == 0) {\n\t\tCXXList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"include\", k_value.c_str()) == 0) {\n\t\tConfIncList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"lang\", k_value.c_str()) == 0) {\n\t\tLangList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"dist\", k_value.c_str()) == 0) {\n\t\tDistList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"before-script\", k_value.c_str()) == 0) {\n\t\tBeforeScriptList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"after-script\", k_value.c_str()) == 0) {\n\t\tAfterScriptList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"libs\", k_value.c_str()) == 0) {\n\t\tLibsList.push_back(PrependLink(v_value, \" -l\"));\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"incdir\", k_value.c_str()) == 0) {\n\t\tIncDirList.push_back(PrependLink(v_value, \" -I\"));\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"libdir\", k_value.c_str()) == 0) {\n\t\tLibDirList.push_back(PrependLink(v_value, \" -L\"));\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"target\", k_value.c_str()) == 0) {\n\t\tTargetList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"remote\", k_value.c_str()) == 0) {\n\t\tRemoteList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n\tif (strcasecmp(\"defines\", k_value.c_str()) == 0) {\n\t\tDefinesList.push_back(v_value);\n\t\tprintf(\"Adding value: %s to key: %s\\n\", v_value, k_value.c_str());\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <agency\/execution_policy.hpp>\n#include <mutex>\n#include <iostream>\n#include <thread>\n#include <cassert>\n\n\/\/ this is just like std::mutex, except it has a move constructor\n\/\/ the move constructor just acts like the default constructor\nclass movable_mutex\n{\n public:\n constexpr movable_mutex() = default;\n\n movable_mutex(const movable_mutex&) = delete;\n\n movable_mutex(movable_mutex&&)\n : mut_()\n {}\n\n void lock()\n {\n mut_.lock();\n }\n\n void unlock()\n {\n mut_.unlock();\n }\n\n private:\n std::mutex mut_;\n};\n\n\n\/\/ this function implements a single concurrent ping pong match\nsize_t ping_pong_match(agency::concurrent_agent& self, const std::vector<std::string>& names, int num_volleys, movable_mutex& mut, int& ball)\n{\n \/\/ agent 0 initializes the ball\n if(self.index() == 0)\n {\n ball = 0;\n }\n\n self.wait();\n\n auto name = names[self.index()];\n \n for(int next_state = self.index();\n (next_state < num_volleys) && (ball >= 0);\n next_state += 2)\n {\n \/\/ wait for the next volley\n while(ball >= 0 && ball != next_state)\n {\n mut.lock();\n std::cout << name << \" waiting for return\" << std::endl;\n mut.unlock();\n \n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n \n mut.lock();\n if(ball == -1)\n {\n std::cout << name << \" wins!\" << std::endl;\n }\n else\n {\n \/\/ try to return the ball\n if(std::rand() % 10 == 0)\n {\n \/\/ whiff -- declare outself the loser\n ball = -self.index() - 1;\n std::cout << \"whiff... \" << name << \" loses!\" << std::endl;\n }\n else\n {\n \/\/ successful return\n ball += 1;\n std::cout << name << \"! ball is now \" << ball << std::endl;\n }\n }\n mut.unlock();\n \n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n\n \/\/ decode who lost the match\n int loser = (ball > 0) ? 1 : -(ball + 1);\n\n \/\/ return the winner\n return loser ^ 1;\n}\n\n\n\/\/ this function implements a two concurrent semifinals ping pong matches\n\/\/ followed by a single final ping pong match\nvoid ping_pong_tournament(agency::concurrent_group<agency::concurrent_agent>& self,\n const std::vector<std::vector<std::string>>& semifinalists,\n int num_volleys,\n movable_mutex& mut,\n std::vector<std::string>& finalists,\n int& ball)\n{\n if(self.inner().index() == 0)\n {\n if(self.outer().index() == 0)\n {\n std::cout << \"Starting semifinal matches...\" << std::endl;\n }\n\n self.outer().wait();\n }\n\n self.inner().wait();\n\n \/\/ play the semifinals matches\n auto semifinal_winner_idx = ping_pong_match(self.inner(), semifinalists[self.outer().index()], num_volleys, mut, ball);\n\n if(self.inner().index() == 0)\n {\n \/\/ the first agent of each group reports who won the semifinal match\n auto semifinal_winner = semifinalists[self.outer().index()][semifinal_winner_idx];\n finalists[self.outer().index()] = semifinal_winner;\n\n \/\/ have the first player of each group wait for the other group\n self.outer().wait();\n }\n\n \/\/ have each inner group wait for each other\n self.inner().wait();\n\n \/\/ group 0 plays the final match while group 1 sits it out\n if(self.outer().index() == 0)\n {\n \/\/ agent 0 initializes the contestant names for the final match\n if(self.inner().index() == 0)\n {\n std::cout << std::endl << finalists[0] << \" and \" << finalists[1] << \" starting the final match...\" << std::endl;\n }\n\n \/\/ wait until agent 0 initializes the contestant names before starting the final match\n self.inner().wait();\n\n \/\/ play the final match\n auto final_winner_idx = ping_pong_match(self.inner(), finalists, num_volleys, mut, ball);\n\n \/\/ have agent 0 of group 0 report the winner\n if(self.inner().index() == 0)\n {\n std::cout << std::endl << finalists[final_winner_idx] << \" is the tournament champion!\" << std::endl;\n }\n }\n}\n\n\nint main()\n{\n using namespace agency;\n using namespace std;\n\n size_t num_volleys = 20;\n vector<vector<string>> semifinalists = {{\"ping\", \"pong\"}, {\"foo\", \"bar\"}};\n\n bulk_invoke(con(2, con(2)), ping_pong_tournament, semifinalists, num_volleys, share<0,movable_mutex>(), share<0,vector<string>>(2), share<1,int>());\n\n return 0;\n}\n\n<commit_msg>Use the newer share syntax<commit_after>#include <agency\/execution_policy.hpp>\n#include <mutex>\n#include <iostream>\n#include <thread>\n#include <cassert>\n\n\/\/ this is just like std::mutex, except it has a move constructor\n\/\/ the move constructor just acts like the default constructor\nclass movable_mutex\n{\n public:\n constexpr movable_mutex() = default;\n\n movable_mutex(const movable_mutex&) = delete;\n\n movable_mutex(movable_mutex&&)\n : mut_()\n {}\n\n void lock()\n {\n mut_.lock();\n }\n\n void unlock()\n {\n mut_.unlock();\n }\n\n private:\n std::mutex mut_;\n};\n\n\n\/\/ this function implements a single concurrent ping pong match\nsize_t ping_pong_match(agency::concurrent_agent& self, const std::vector<std::string>& names, int num_volleys, movable_mutex& mut, int& ball)\n{\n \/\/ agent 0 initializes the ball\n if(self.index() == 0)\n {\n ball = 0;\n }\n\n self.wait();\n\n auto name = names[self.index()];\n \n for(int next_state = self.index();\n (next_state < num_volleys) && (ball >= 0);\n next_state += 2)\n {\n \/\/ wait for the next volley\n while(ball >= 0 && ball != next_state)\n {\n mut.lock();\n std::cout << name << \" waiting for return\" << std::endl;\n mut.unlock();\n \n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n \n mut.lock();\n if(ball == -1)\n {\n std::cout << name << \" wins!\" << std::endl;\n }\n else\n {\n \/\/ try to return the ball\n if(std::rand() % 10 == 0)\n {\n \/\/ whiff -- declare outself the loser\n ball = -self.index() - 1;\n std::cout << \"whiff... \" << name << \" loses!\" << std::endl;\n }\n else\n {\n \/\/ successful return\n ball += 1;\n std::cout << name << \"! ball is now \" << ball << std::endl;\n }\n }\n mut.unlock();\n \n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n\n \/\/ decode who lost the match\n int loser = (ball > 0) ? 1 : -(ball + 1);\n\n \/\/ return the winner\n return loser ^ 1;\n}\n\n\n\/\/ this function implements a two concurrent semifinals ping pong matches\n\/\/ followed by a single final ping pong match\nvoid ping_pong_tournament(agency::concurrent_group<agency::concurrent_agent>& self,\n const std::vector<std::vector<std::string>>& semifinalists,\n int num_volleys,\n movable_mutex& mut,\n std::vector<std::string>& finalists,\n int& ball)\n{\n if(self.inner().index() == 0)\n {\n if(self.outer().index() == 0)\n {\n std::cout << \"Starting semifinal matches...\" << std::endl;\n }\n\n self.outer().wait();\n }\n\n self.inner().wait();\n\n \/\/ play the semifinals matches\n auto semifinal_winner_idx = ping_pong_match(self.inner(), semifinalists[self.outer().index()], num_volleys, mut, ball);\n\n if(self.inner().index() == 0)\n {\n \/\/ the first agent of each group reports who won the semifinal match\n auto semifinal_winner = semifinalists[self.outer().index()][semifinal_winner_idx];\n finalists[self.outer().index()] = semifinal_winner;\n\n \/\/ have the first player of each group wait for the other group\n self.outer().wait();\n }\n\n \/\/ have each inner group wait for each other\n self.inner().wait();\n\n \/\/ group 0 plays the final match while group 1 sits it out\n if(self.outer().index() == 0)\n {\n \/\/ agent 0 initializes the contestant names for the final match\n if(self.inner().index() == 0)\n {\n std::cout << std::endl << finalists[0] << \" and \" << finalists[1] << \" starting the final match...\" << std::endl;\n }\n\n \/\/ wait until agent 0 initializes the contestant names before starting the final match\n self.inner().wait();\n\n \/\/ play the final match\n auto final_winner_idx = ping_pong_match(self.inner(), finalists, num_volleys, mut, ball);\n\n \/\/ have agent 0 of group 0 report the winner\n if(self.inner().index() == 0)\n {\n std::cout << std::endl << finalists[final_winner_idx] << \" is the tournament champion!\" << std::endl;\n }\n }\n}\n\n\nint main()\n{\n using namespace agency;\n using namespace std;\n\n size_t num_volleys = 20;\n vector<vector<string>> semifinalists = {{\"ping\", \"pong\"}, {\"foo\", \"bar\"}};\n\n bulk_invoke(con(2, con(2)), ping_pong_tournament, semifinalists, num_volleys, share<movable_mutex>(), share<vector<string>>(2), share_at_scope<1,int>());\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Open Source Robotics 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#include <iostream>\n#include <string>\n#include <ignition\/transport.hh>\n#include \"msg\/stringmsg.pb.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Service response callback.\nvoid responseCb(const std::string &_topic,\n const example::mymsgs::StringMsg &_rep, bool _result)\n{\n if (_result)\n std::cout << \"Response: [\" << _rep.data() << \"]\" << std::endl;\n else\n std::cerr << \"Service call failed\" << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(int argc, char **argv)\n{\n \/\/ Create a transport node.\n ignition::transport::Node node;\n\n \/\/ Prepare the input parameters.\n example::mymsgs::StringMsg req;\n req.set_data(\"HELLO\");\n\n \/\/ Request the \"\/echo\" service.\n node.Request(\"\/echo\", req, responseCb);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(300));\n\n \/\/ Request the \"\/echo\" service.\n node.Request(\"\/echo\", req, responseCb);\n\n \/\/ Wait for the response.\n std::cout << \"Press <ENTER> to exit\" << std::endl;\n getchar();\n}\n<commit_msg>Restoring examples.<commit_after>\/*\n * Copyright (C) 2014 Open Source Robotics 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#include <iostream>\n#include <string>\n#include <ignition\/transport.hh>\n#include \"msg\/stringmsg.pb.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Service response callback.\nvoid responseCb(const std::string &_topic,\n const example::mymsgs::StringMsg &_rep, bool _result)\n{\n if (_result)\n std::cout << \"Response: [\" << _rep.data() << \"]\" << std::endl;\n else\n std::cerr << \"Service call failed\" << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(int argc, char **argv)\n{\n \/\/ Create a transport node.\n ignition::transport::Node node;\n\n \/\/ Prepare the input parameters.\n example::mymsgs::StringMsg req;\n req.set_data(\"HELLO\");\n\n \/\/ Request the \"\/echo\" service.\n node.Request(\"\/echo\", req, responseCb);\n\n \/\/ Wait for the response.\n std::cout << \"Press <ENTER> to exit\" << std::endl;\n getchar();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/python.hpp>\n#include \"ModelInterface.h\"\n#include \"pyToCppModelInterfaceCache.h\"\n\n#include <boost\/python\/stl_iterator.hpp>\n#include <iostream>\n#include <stdexcept>\n#include <boost\/python\/numeric.hpp>\n#include <boost\/python\/tuple.hpp>\n#include <boost\/python\/module.hpp>\n#include <boost\/python\/def.hpp>\n#include <numpy\/noprefix.h>\n\n\nnamespace threeML {\n\ntemplate<typename T>\ninline\nstd::vector<T> to_std_vector(const boost::python::object &iterable) {\n return std::vector<T>(boost::python::stl_input_iterator<T>(iterable),\n boost::python::stl_input_iterator<T>());\n}\n\nvoid pyToCppModelInterfaceCache::setExtSourceBoundaries(const int id, const float lon_min, const float lon_max,\n const float lat_min, const float lat_max)\n{\n\n BoundingBox this_boundingBox;\n\n this_boundingBox.lon_min = lon_min;\n this_boundingBox.lon_max = lon_max;\n this_boundingBox.lat_min = lat_min;\n this_boundingBox.lat_max = lat_max;\n\n m_boundingBoxes[id] = this_boundingBox;\n\n}\n\nvoid pyToCppModelInterfaceCache::setExtSourceCube(const int id, const numeric::array &cube,\n const numeric::array &lon, const numeric::array &lat)\n{\n\n \/\/ Add an extended source to the cache (a map)\n\n PyArrayObject* cube__ = (PyArrayObject*) cube.ptr();\n\n unsigned int n_points = (unsigned int) *(cube__->dimensions);\n unsigned int n_energies = (unsigned int) *(cube__->dimensions+1);\n\n \/\/ This is n_points * n_energies in size\n\n double* cube_ = (double *) cube__->data;\n\n \/\/ These are both n_points in size\n\n double* lon_ = (double *) ((PyArrayObject*) lon.ptr())->data;\n double* lat_ = (double *) ((PyArrayObject*) lat.ptr())->data;\n\n ExtSrcCube this_srcCube;\n\n for(unsigned int i=0; i < n_points; ++i)\n {\n\n float this_lon = (float) lon_[i];\n float this_lat = (float) lat_[i];\n\n SkyCoord this_coord(this_lon, this_lat);\n\n \/\/ A little of pointer algebra\n\n int this_data_start = i * n_energies;\n int this_data_stop = this_data_start + n_energies;\n\n \/\/ Note how this construct avoid the double copy which would\n \/\/ occur if we were to first create a vector and then\n \/\/ copy it into a standard map. Here instead the operator\n \/\/ [] creates an empty vector, which is then filled with\n \/\/ the assign method\n\n this_srcCube[this_coord].assign(cube_ + this_data_start, cube_ + this_data_stop);\n\n }\n\n \/\/ Finally add to the map\n\n m_extSources[id] = this_srcCube;\n\n}\n\nbool pyToCppModelInterfaceCache::isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const {\n return true;\n}\n\nint pyToCppModelInterfaceCache::getNumberOfPointSources() const {\n\n return m_nPtSources;\n\n}\n\nvoid pyToCppModelInterfaceCache::getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const {\n\n throw std::runtime_error(\"ModelInterfaceCache: point source not yet implemented\");\n}\n\n\nvoid pyToCppModelInterfaceCache::reset() {\n\n \/\/Empty the cache\n \/*\n m_extSources.clear();\n m_boundingBoxes.clear();\n m_nExtSources = 0;\n m_nPtSources = 0;*\/\n\n}\n\nstd::vector<double>\npyToCppModelInterfaceCache::getPointSourceFluxes(int srcid, std::vector<double> energies) const {\n\n throw std::runtime_error(\"ModelInterfaceCache: point source not yet implemented\");\n\n}\n\nint pyToCppModelInterfaceCache::getNumberOfExtendedSources() const {\n\n \/\/ We use the size of bounding boxes and not of m_extSources because the latter\n \/\/ could get filled in a second moment\n return m_boundingBoxes.size();\n\n}\n\nstd::vector<double>\npyToCppModelInterfaceCache::getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec,\n std::vector<double> energies) const {\n\n SkyCoord sky_pos(j2000_ra, j2000_dec);\n\n try {\n\n return m_extSources.at(srcid).at(sky_pos);\n\n } catch (...) {\n\n std::cerr << \"Cache failure\" << std::endl;\n\n std::cerr << \"Requested id \" << srcid << \" at position \" << j2000_ra << \", \" << j2000_dec << std::endl;\n\n }\n}\n\nstd::vector<double>\npyToCppModelInterfaceCache::getExtendedSourceFluxes_test(int srcid, double j2000_ra, double j2000_dec) const {\n\n SkyCoord sky_pos(j2000_ra, j2000_dec);\n\n try {\n\n return m_extSources.at(srcid).at(sky_pos);\n\n } catch (...) {\n\n std::cerr << \"Cache failure\" << std::endl;\n\n std::cerr << \"Requested id \" << srcid << \" at position \" << j2000_ra << \", \" << j2000_dec << std::endl;\n\n }\n\n}\n\nstd::string pyToCppModelInterfaceCache::getPointSourceName(int srcid) const {\n\n \/\/TODO: implement a mechanism to actually keep the true name\n\n std::stringstream name;\n\n name << \"Point source \" << srcid;\n\n return name.str();\n}\n\nstd::string pyToCppModelInterfaceCache::getExtendedSourceName(int srcid) const {\n\n \/\/TODO: implement a mechanism to actually keep the true name\n\n std::stringstream name;\n\n name << \"Extended source \" << srcid;\n\n return name.str();\n}\n\nvoid pyToCppModelInterfaceCache::getExtendedSourceBoundaries(int srcid, double *j2000_ra_min,\n double *j2000_ra_max,\n double *j2000_dec_min,\n double *j2000_dec_max) const {\n\n const BoundingBox *this_boundingBox = &m_boundingBoxes.at(srcid);\n\n *j2000_ra_min = this_boundingBox->lon_min;\n *j2000_ra_max = this_boundingBox->lon_max;\n *j2000_dec_min = this_boundingBox->lat_min;\n *j2000_dec_max = this_boundingBox->lat_max;\n\n}\n\n}\n\nusing namespace threeML;\nusing namespace boost::python;\n\n\/\/This is needed to wrap the interface (i.e., all methods are virtual)\n\/\/contained in ModelInterface.h\nstruct ModelInterfaceCacheWrap: ModelInterface, wrapper<ModelInterface> {\n int getNumberOfPointSources() const { return this->get_override(\"getNumberOfPointSources\")(); }\n\n void getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const {\n this->get_override(\"getPointSourcePosition\")();\n }\n\n std::vector<double> getPointSourceFluxes(int srcid, std::vector<double> energies) const {\n return this->get_override(\"getPointSourceFluxes\")();\n }\n\n std::string getPointSourceName(int srcid) const { return this->get_override(\"getPointSourceName\")(); }\n\n int getNumberOfExtendedSources() const { return this->get_override(\"getNumberOfExtendedSources\")(); }\n\n std::vector<double> getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec,\n std::vector<double> energies) const {\n return this->get_override(\"getExtendedSourceFluxes\")();\n }\n\n std::string getExtendedSourceName(int srcid) const { return this->get_override(\"getExtendedSourceName\")(); }\n\n bool isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const {\n return this->get_override(\"isInsideAnyExtendedSource\")();\n }\n\n void getExtendedSourceBoundaries(int srcid, double *j2000_ra_min,\n double *j2000_ra_max,\n double *j2000_dec_min,\n double *j2000_dec_max) const { this->get_override(\"getExtendedSourceBoundaries\")(); }\n};\n\ntemplate<class T>\nstruct VecToList {\n static PyObject *convert(const std::vector<T> &vec) {\n boost::python::list *l = new boost::python::list();\n\n for (size_t i = 0; i < vec.size(); i++)\n (*l).append(vec[i]);\n\n return l->ptr();\n }\n};\n\n\nBOOST_PYTHON_MODULE (pyModelInterfaceCache) {\n \/\/hello\n to_python_converter<std::vector<double, std::allocator<double> >, VecToList<double> >();\n\n class_<ModelInterfaceCacheWrap, boost::noncopyable>(\"ModelInterface\")\n .def(\"getNumberOfPointSources\", pure_virtual(&ModelInterface::getNumberOfPointSources))\n .def(\"getPointSourcePosition\", pure_virtual(&ModelInterface::getPointSourcePosition))\n .def(\"getPointSourceFluxes\", pure_virtual(&ModelInterface::getPointSourceFluxes))\n .def(\"getPointSourceName\", pure_virtual(&ModelInterface::getPointSourceName))\n .def(\"getNumberOfExtendedSources\", pure_virtual(&ModelInterface::getNumberOfExtendedSources))\n .def(\"getExtendedSourceFluxes\", pure_virtual(&ModelInterface::getExtendedSourceFluxes))\n .def(\"getExtendedSourceName\", pure_virtual(&ModelInterface::getExtendedSourceName))\n .def(\"isInsideAnyExtendedSource\", pure_virtual(&ModelInterface::isInsideAnyExtendedSource))\n .def(\"getExtendedSourceBoundaries\", pure_virtual(&ModelInterface::getExtendedSourceBoundaries));\n\n numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n\n class_<pyToCppModelInterfaceCache, bases<ModelInterface> >(\"pyToCppModelInterfaceCache\", init< >())\n .def(\"getNumberOfPointSources\", &pyToCppModelInterfaceCache::getNumberOfPointSources)\n .def(\"getPointSourcePosition\", &pyToCppModelInterfaceCache::getPointSourcePosition)\n .def(\"getPointSourceFluxes\", &pyToCppModelInterfaceCache::getPointSourceFluxes)\n .def(\"getPointSourceName\", &pyToCppModelInterfaceCache::getPointSourceName)\n .def(\"getNumberOfExtendedSources\", &pyToCppModelInterfaceCache::getNumberOfExtendedSources)\n .def(\"getExtendedSourceFluxes\", &pyToCppModelInterfaceCache::getExtendedSourceFluxes)\n .def(\"getExtendedSourceName\", &pyToCppModelInterfaceCache::getExtendedSourceName)\n .def(\"isInsideAnyExtendedSource\", &pyToCppModelInterfaceCache::isInsideAnyExtendedSource)\n .def(\"getExtendedSourceBoundaries\", &pyToCppModelInterfaceCache::getExtendedSourceBoundaries)\n .def(\"setExtSourceBoundaries\", &pyToCppModelInterfaceCache::setExtSourceBoundaries)\n .def(\"setExtSourceCube\",&pyToCppModelInterfaceCache::setExtSourceCube)\n .def(\"getExtendedSourceFluxes_test\",&pyToCppModelInterfaceCache::getExtendedSourceFluxes_test)\n .def(\"reset\",&pyToCppModelInterfaceCache::reset);\n}\n<commit_msg>Now reset() empties the extended source pointer map<commit_after>#include <boost\/python.hpp>\n#include \"ModelInterface.h\"\n#include \"pyToCppModelInterfaceCache.h\"\n\n#include <boost\/python\/stl_iterator.hpp>\n#include <iostream>\n#include <stdexcept>\n#include <boost\/python\/numeric.hpp>\n#include <boost\/python\/tuple.hpp>\n#include <boost\/python\/module.hpp>\n#include <boost\/python\/def.hpp>\n#include <numpy\/noprefix.h>\n\n\nnamespace threeML {\n\ntemplate<typename T>\ninline\nstd::vector<T> to_std_vector(const boost::python::object &iterable) {\n return std::vector<T>(boost::python::stl_input_iterator<T>(iterable),\n boost::python::stl_input_iterator<T>());\n}\n\nvoid pyToCppModelInterfaceCache::setExtSourceBoundaries(const int id, const float lon_min, const float lon_max,\n const float lat_min, const float lat_max)\n{\n\n BoundingBox this_boundingBox;\n\n this_boundingBox.lon_min = lon_min;\n this_boundingBox.lon_max = lon_max;\n this_boundingBox.lat_min = lat_min;\n this_boundingBox.lat_max = lat_max;\n\n m_boundingBoxes[id] = this_boundingBox;\n\n}\n\nvoid pyToCppModelInterfaceCache::setExtSourceCube(const int id, const numeric::array &cube,\n const numeric::array &lon, const numeric::array &lat)\n{\n\n \/\/ Add an extended source to the cache (a map)\n\n PyArrayObject* cube__ = (PyArrayObject*) cube.ptr();\n\n unsigned int n_points = (unsigned int) *(cube__->dimensions);\n unsigned int n_energies = (unsigned int) *(cube__->dimensions+1);\n\n \/\/ This is n_points * n_energies in size\n\n double* cube_ = (double *) cube__->data;\n\n \/\/ These are both n_points in size\n\n double* lon_ = (double *) ((PyArrayObject*) lon.ptr())->data;\n double* lat_ = (double *) ((PyArrayObject*) lat.ptr())->data;\n\n ExtSrcCube this_srcCube;\n\n for(unsigned int i=0; i < n_points; ++i)\n {\n\n float this_lon = (float) lon_[i];\n float this_lat = (float) lat_[i];\n\n SkyCoord this_coord(this_lon, this_lat);\n\n \/\/ A little of pointer algebra\n\n int this_data_start = i * n_energies;\n int this_data_stop = this_data_start + n_energies;\n\n \/\/ Note how this construct avoid the double copy which would\n \/\/ occur if we were to first create a vector and then\n \/\/ copy it into a standard map. Here instead the operator\n \/\/ [] creates an empty vector, which is then filled with\n \/\/ the assign method\n\n this_srcCube[this_coord].assign(cube_ + this_data_start, cube_ + this_data_stop);\n\n }\n\n \/\/ Finally add to the map\n\n m_extSources[id] = this_srcCube;\n\n}\n\nbool pyToCppModelInterfaceCache::isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const {\n return true;\n}\n\nint pyToCppModelInterfaceCache::getNumberOfPointSources() const {\n\n return m_nPtSources;\n\n}\n\nvoid pyToCppModelInterfaceCache::getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const {\n\n throw std::runtime_error(\"ModelInterfaceCache: point source not yet implemented\");\n}\n\n\nvoid pyToCppModelInterfaceCache::reset() {\n\n \/\/Empty the cache\n\n m_extSources.clear();\n \/*\n m_boundingBoxes.clear();\n m_nExtSources = 0;\n m_nPtSources = 0;*\/\n\n}\n\nstd::vector<double>\npyToCppModelInterfaceCache::getPointSourceFluxes(int srcid, std::vector<double> energies) const {\n\n throw std::runtime_error(\"ModelInterfaceCache: point source not yet implemented\");\n\n}\n\nint pyToCppModelInterfaceCache::getNumberOfExtendedSources() const {\n\n \/\/ We use the size of bounding boxes and not of m_extSources because the latter\n \/\/ could get filled in a second moment\n return m_boundingBoxes.size();\n\n}\n\nstd::vector<double>\npyToCppModelInterfaceCache::getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec,\n std::vector<double> energies) const {\n\n SkyCoord sky_pos(j2000_ra, j2000_dec);\n\n try {\n\n return m_extSources.at(srcid).at(sky_pos);\n\n } catch (...) {\n\n std::cerr << \"Cache failure\" << std::endl;\n\n std::cerr << \"Requested id \" << srcid << \" at position \" << j2000_ra << \", \" << j2000_dec << std::endl;\n\n }\n}\n\nstd::vector<double>\npyToCppModelInterfaceCache::getExtendedSourceFluxes_test(int srcid, double j2000_ra, double j2000_dec) const {\n\n SkyCoord sky_pos(j2000_ra, j2000_dec);\n\n try {\n\n return m_extSources.at(srcid).at(sky_pos);\n\n } catch (...) {\n\n std::cerr << \"Cache failure\" << std::endl;\n\n std::cerr << \"Requested id \" << srcid << \" at position \" << j2000_ra << \", \" << j2000_dec << std::endl;\n\n }\n\n}\n\nstd::string pyToCppModelInterfaceCache::getPointSourceName(int srcid) const {\n\n \/\/TODO: implement a mechanism to actually keep the true name\n\n std::stringstream name;\n\n name << \"Point source \" << srcid;\n\n return name.str();\n}\n\nstd::string pyToCppModelInterfaceCache::getExtendedSourceName(int srcid) const {\n\n \/\/TODO: implement a mechanism to actually keep the true name\n\n std::stringstream name;\n\n name << \"Extended source \" << srcid;\n\n return name.str();\n}\n\nvoid pyToCppModelInterfaceCache::getExtendedSourceBoundaries(int srcid, double *j2000_ra_min,\n double *j2000_ra_max,\n double *j2000_dec_min,\n double *j2000_dec_max) const {\n\n const BoundingBox *this_boundingBox = &m_boundingBoxes.at(srcid);\n\n *j2000_ra_min = this_boundingBox->lon_min;\n *j2000_ra_max = this_boundingBox->lon_max;\n *j2000_dec_min = this_boundingBox->lat_min;\n *j2000_dec_max = this_boundingBox->lat_max;\n\n}\n\n}\n\nusing namespace threeML;\nusing namespace boost::python;\n\n\/\/This is needed to wrap the interface (i.e., all methods are virtual)\n\/\/contained in ModelInterface.h\nstruct ModelInterfaceCacheWrap: ModelInterface, wrapper<ModelInterface> {\n int getNumberOfPointSources() const { return this->get_override(\"getNumberOfPointSources\")(); }\n\n void getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const {\n this->get_override(\"getPointSourcePosition\")();\n }\n\n std::vector<double> getPointSourceFluxes(int srcid, std::vector<double> energies) const {\n return this->get_override(\"getPointSourceFluxes\")();\n }\n\n std::string getPointSourceName(int srcid) const { return this->get_override(\"getPointSourceName\")(); }\n\n int getNumberOfExtendedSources() const { return this->get_override(\"getNumberOfExtendedSources\")(); }\n\n std::vector<double> getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec,\n std::vector<double> energies) const {\n return this->get_override(\"getExtendedSourceFluxes\")();\n }\n\n std::string getExtendedSourceName(int srcid) const { return this->get_override(\"getExtendedSourceName\")(); }\n\n bool isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const {\n return this->get_override(\"isInsideAnyExtendedSource\")();\n }\n\n void getExtendedSourceBoundaries(int srcid, double *j2000_ra_min,\n double *j2000_ra_max,\n double *j2000_dec_min,\n double *j2000_dec_max) const { this->get_override(\"getExtendedSourceBoundaries\")(); }\n};\n\ntemplate<class T>\nstruct VecToList {\n static PyObject *convert(const std::vector<T> &vec) {\n boost::python::list *l = new boost::python::list();\n\n for (size_t i = 0; i < vec.size(); i++)\n (*l).append(vec[i]);\n\n return l->ptr();\n }\n};\n\n\nBOOST_PYTHON_MODULE (pyModelInterfaceCache) {\n \/\/hello\n to_python_converter<std::vector<double, std::allocator<double> >, VecToList<double> >();\n\n class_<ModelInterfaceCacheWrap, boost::noncopyable>(\"ModelInterface\")\n .def(\"getNumberOfPointSources\", pure_virtual(&ModelInterface::getNumberOfPointSources))\n .def(\"getPointSourcePosition\", pure_virtual(&ModelInterface::getPointSourcePosition))\n .def(\"getPointSourceFluxes\", pure_virtual(&ModelInterface::getPointSourceFluxes))\n .def(\"getPointSourceName\", pure_virtual(&ModelInterface::getPointSourceName))\n .def(\"getNumberOfExtendedSources\", pure_virtual(&ModelInterface::getNumberOfExtendedSources))\n .def(\"getExtendedSourceFluxes\", pure_virtual(&ModelInterface::getExtendedSourceFluxes))\n .def(\"getExtendedSourceName\", pure_virtual(&ModelInterface::getExtendedSourceName))\n .def(\"isInsideAnyExtendedSource\", pure_virtual(&ModelInterface::isInsideAnyExtendedSource))\n .def(\"getExtendedSourceBoundaries\", pure_virtual(&ModelInterface::getExtendedSourceBoundaries));\n\n numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n\n class_<pyToCppModelInterfaceCache, bases<ModelInterface> >(\"pyToCppModelInterfaceCache\", init< >())\n .def(\"getNumberOfPointSources\", &pyToCppModelInterfaceCache::getNumberOfPointSources)\n .def(\"getPointSourcePosition\", &pyToCppModelInterfaceCache::getPointSourcePosition)\n .def(\"getPointSourceFluxes\", &pyToCppModelInterfaceCache::getPointSourceFluxes)\n .def(\"getPointSourceName\", &pyToCppModelInterfaceCache::getPointSourceName)\n .def(\"getNumberOfExtendedSources\", &pyToCppModelInterfaceCache::getNumberOfExtendedSources)\n .def(\"getExtendedSourceFluxes\", &pyToCppModelInterfaceCache::getExtendedSourceFluxes)\n .def(\"getExtendedSourceName\", &pyToCppModelInterfaceCache::getExtendedSourceName)\n .def(\"isInsideAnyExtendedSource\", &pyToCppModelInterfaceCache::isInsideAnyExtendedSource)\n .def(\"getExtendedSourceBoundaries\", &pyToCppModelInterfaceCache::getExtendedSourceBoundaries)\n .def(\"setExtSourceBoundaries\", &pyToCppModelInterfaceCache::setExtSourceBoundaries)\n .def(\"setExtSourceCube\",&pyToCppModelInterfaceCache::setExtSourceCube)\n .def(\"getExtendedSourceFluxes_test\",&pyToCppModelInterfaceCache::getExtendedSourceFluxes_test)\n .def(\"reset\",&pyToCppModelInterfaceCache::reset);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017 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 \"GrCoverageCountingPathRenderer.h\"\n\n#include \"GrCaps.h\"\n#include \"GrClip.h\"\n#include \"GrProxyProvider.h\"\n#include \"SkMakeUnique.h\"\n#include \"SkPathOps.h\"\n#include \"ccpr\/GrCCClipProcessor.h\"\n#include \"ccpr\/GrCCDrawPathsOp.h\"\n#include \"ccpr\/GrCCPathParser.h\"\n\nusing PathInstance = GrCCPathProcessor::Instance;\n\n\/\/ If a path spans more pixels than this, we need to crop it or else analytic AA can run out of fp32\n\/\/ precision.\nstatic constexpr float kPathCropThreshold = 1 << 16;\n\nstatic void crop_path(const SkPath& path, const SkIRect& cropbox, SkPath* out) {\n SkPath cropboxPath;\n cropboxPath.addRect(SkRect::Make(cropbox));\n if (!Op(cropboxPath, path, kIntersect_SkPathOp, out)) {\n \/\/ This can fail if the PathOps encounter NaN or infinities.\n out->reset();\n }\n out->setIsVolatile(true);\n}\n\nbool GrCoverageCountingPathRenderer::IsSupported(const GrCaps& caps) {\n const GrShaderCaps& shaderCaps = *caps.shaderCaps();\n return shaderCaps.integerSupport() && shaderCaps.flatInterpolationSupport() &&\n caps.instanceAttribSupport() && GrCaps::kNone_MapFlags != caps.mapBufferFlags() &&\n caps.isConfigTexturable(kAlpha_half_GrPixelConfig) &&\n caps.isConfigRenderable(kAlpha_half_GrPixelConfig) &&\n !caps.blacklistCoverageCounting();\n}\n\nsk_sp<GrCoverageCountingPathRenderer> GrCoverageCountingPathRenderer::CreateIfSupported(\n const GrCaps& caps, bool drawCachablePaths) {\n auto ccpr = IsSupported(caps) ? new GrCoverageCountingPathRenderer(drawCachablePaths) : nullptr;\n return sk_sp<GrCoverageCountingPathRenderer>(ccpr);\n}\n\nGrCCPerOpListPaths* GrCoverageCountingPathRenderer::lookupPendingPaths(uint32_t opListID) {\n auto it = fPendingPaths.find(opListID);\n if (fPendingPaths.end() == it) {\n auto paths = skstd::make_unique<GrCCPerOpListPaths>();\n it = fPendingPaths.insert(std::make_pair(opListID, std::move(paths))).first;\n }\n return it->second.get();\n}\n\nvoid GrCoverageCountingPathRenderer::adoptAndRecordOp(GrCCDrawPathsOp* op,\n const DrawPathArgs& args) {\n GrRenderTargetContext* rtc = args.fRenderTargetContext;\n if (uint32_t opListID = rtc->addDrawOp(*args.fClip, std::unique_ptr<GrDrawOp>(op))) {\n \/\/ If the Op wasn't dropped or combined, give it a pointer to its owning GrCCPerOpListPaths.\n op->wasRecorded(this->lookupPendingPaths(opListID));\n }\n}\n\nGrPathRenderer::CanDrawPath GrCoverageCountingPathRenderer::onCanDrawPath(\n const CanDrawPathArgs& args) const {\n if (args.fShape->hasUnstyledKey() && !fDrawCachablePaths) {\n return CanDrawPath::kNo;\n }\n\n if (!args.fShape->style().isSimpleFill() || args.fShape->inverseFilled() ||\n args.fViewMatrix->hasPerspective() || GrAAType::kCoverage != args.fAAType) {\n return CanDrawPath::kNo;\n }\n\n SkPath path;\n args.fShape->asPath(&path);\n SkRect devBounds;\n SkIRect devIBounds;\n args.fViewMatrix->mapRect(&devBounds, path.getBounds());\n devBounds.roundOut(&devIBounds);\n if (!devIBounds.intersect(*args.fClipConservativeBounds)) {\n \/\/ Path is completely clipped away. Our code will eventually notice this before doing any\n \/\/ real work.\n return CanDrawPath::kYes;\n }\n\n if (devIBounds.height() * devIBounds.width() > 256 * 256) {\n \/\/ Large paths can blow up the atlas fast. And they are not ideal for a two-pass rendering\n \/\/ algorithm. Give the simpler direct renderers a chance before we commit to drawing it.\n return CanDrawPath::kAsBackup;\n }\n\n if (args.fShape->hasUnstyledKey() && path.countVerbs() > 50) {\n \/\/ Complex paths do better cached in an SDF, if the renderer will accept them.\n return CanDrawPath::kAsBackup;\n }\n\n return CanDrawPath::kYes;\n}\n\nbool GrCoverageCountingPathRenderer::onDrawPath(const DrawPathArgs& args) {\n SkASSERT(!fFlushing);\n\n SkIRect clipIBounds;\n GrRenderTargetContext* rtc = args.fRenderTargetContext;\n args.fClip->getConservativeBounds(rtc->width(), rtc->height(), &clipIBounds, nullptr);\n\n SkPath path;\n args.fShape->asPath(&path);\n\n SkRect devBounds;\n args.fViewMatrix->mapRect(&devBounds, path.getBounds());\n\n if (SkTMax(devBounds.height(), devBounds.width()) > kPathCropThreshold) {\n \/\/ The path is too large. Crop it or analytic AA can run out of fp32 precision.\n SkPath croppedPath;\n path.transform(*args.fViewMatrix, &croppedPath);\n crop_path(croppedPath, clipIBounds, &croppedPath);\n this->adoptAndRecordOp(new GrCCDrawPathsOp(std::move(args.fPaint), clipIBounds,\n SkMatrix::I(), croppedPath,\n croppedPath.getBounds()), args);\n return true;\n }\n\n this->adoptAndRecordOp(new GrCCDrawPathsOp(std::move(args.fPaint), clipIBounds,\n *args.fViewMatrix, path, devBounds), args);\n return true;\n}\n\nstd::unique_ptr<GrFragmentProcessor> GrCoverageCountingPathRenderer::makeClipProcessor(\n GrProxyProvider* proxyProvider,\n uint32_t opListID, const SkPath& deviceSpacePath, const SkIRect& accessRect,\n int rtWidth, int rtHeight) {\n using MustCheckBounds = GrCCClipProcessor::MustCheckBounds;\n\n SkASSERT(!fFlushing);\n\n GrCCClipPath& clipPath =\n this->lookupPendingPaths(opListID)->fClipPaths[deviceSpacePath.getGenerationID()];\n if (!clipPath.isInitialized()) {\n \/\/ This ClipPath was just created during lookup. Initialize it.\n const SkRect& pathDevBounds = deviceSpacePath.getBounds();\n if (SkTMax(pathDevBounds.height(), pathDevBounds.width()) > kPathCropThreshold) {\n \/\/ The path is too large. Crop it or analytic AA can run out of fp32 precision.\n SkPath croppedPath;\n int maxRTSize = proxyProvider->caps()->maxRenderTargetSize();\n crop_path(deviceSpacePath, SkIRect::MakeWH(maxRTSize, maxRTSize), &croppedPath);\n clipPath.init(proxyProvider, croppedPath, accessRect, rtWidth, rtHeight);\n } else {\n clipPath.init(proxyProvider, deviceSpacePath, accessRect, rtWidth, rtHeight);\n }\n } else {\n clipPath.addAccess(accessRect);\n }\n\n bool mustCheckBounds = !clipPath.pathDevIBounds().contains(accessRect);\n return skstd::make_unique<GrCCClipProcessor>(&clipPath, MustCheckBounds(mustCheckBounds),\n deviceSpacePath.getFillType());\n}\n\nvoid GrCoverageCountingPathRenderer::preFlush(GrOnFlushResourceProvider* onFlushRP,\n const uint32_t* opListIDs, int numOpListIDs,\n SkTArray<sk_sp<GrRenderTargetContext>>* atlasDraws) {\n SkASSERT(!fFlushing);\n SkASSERT(fFlushingPaths.empty());\n SkDEBUGCODE(fFlushing = true);\n\n if (fPendingPaths.empty()) {\n return; \/\/ Nothing to draw.\n }\n\n \/\/ Move the per-opList paths that are about to be flushed from fPendingPaths to fFlushingPaths,\n \/\/ and count up the paths about to be flushed so we can preallocate buffers.\n int numPathDraws = 0;\n int numClipPaths = 0;\n GrCCPathParser::PathStats flushingPathStats;\n fFlushingPaths.reserve(numOpListIDs);\n for (int i = 0; i < numOpListIDs; ++i) {\n auto iter = fPendingPaths.find(opListIDs[i]);\n if (fPendingPaths.end() == iter) {\n continue; \/\/ No paths on this opList.\n }\n\n fFlushingPaths.push_back(std::move(iter->second)).get();\n fPendingPaths.erase(iter);\n\n for (const GrCCDrawPathsOp* op : fFlushingPaths.back()->fDrawOps) {\n numPathDraws += op->countPaths(&flushingPathStats);\n }\n for (const auto& clipsIter : fFlushingPaths.back()->fClipPaths) {\n flushingPathStats.statPath(clipsIter.second.deviceSpacePath());\n }\n numClipPaths += fFlushingPaths.back()->fClipPaths.size();\n }\n\n if (0 == numPathDraws + numClipPaths) {\n return; \/\/ Nothing to draw.\n }\n\n auto resources = sk_make_sp<GrCCPerFlushResources>(onFlushRP, numPathDraws, numClipPaths,\n flushingPathStats);\n if (!resources->isMapped()) {\n return; \/\/ Some allocation failed.\n }\n\n \/\/ Layout atlas(es) and parse paths.\n SkDEBUGCODE(int numSkippedPaths = 0);\n for (const auto& flushingPaths : fFlushingPaths) {\n for (GrCCDrawPathsOp* op : flushingPaths->fDrawOps) {\n op->setupResources(resources.get(), onFlushRP);\n SkDEBUGCODE(numSkippedPaths += op->numSkippedInstances_debugOnly());\n }\n for (auto& clipsIter : flushingPaths->fClipPaths) {\n clipsIter.second.renderPathInAtlas(resources.get(), onFlushRP);\n }\n }\n SkASSERT(resources->nextPathInstanceIdx() == numPathDraws - numSkippedPaths);\n\n \/\/ Allocate the atlases and create instance buffers to draw them.\n if (!resources->finalize(onFlushRP, atlasDraws)) {\n return;\n }\n\n \/\/ Commit flushing paths to the resources once they are successfully completed.\n for (auto& flushingPaths : fFlushingPaths) {\n flushingPaths->fFlushResources = resources;\n }\n}\n\nvoid GrCoverageCountingPathRenderer::postFlush(GrDeferredUploadToken, const uint32_t* opListIDs,\n int numOpListIDs) {\n SkASSERT(fFlushing);\n \/\/ We wait to erase these until after flush, once Ops and FPs are done accessing their data.\n fFlushingPaths.reset();\n SkDEBUGCODE(fFlushing = false);\n}\n<commit_msg>Drop unneeded .get() in GrCoverageCountingPathRenderer.cpp<commit_after>\/*\n * Copyright 2017 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 \"GrCoverageCountingPathRenderer.h\"\n\n#include \"GrCaps.h\"\n#include \"GrClip.h\"\n#include \"GrProxyProvider.h\"\n#include \"SkMakeUnique.h\"\n#include \"SkPathOps.h\"\n#include \"ccpr\/GrCCClipProcessor.h\"\n#include \"ccpr\/GrCCDrawPathsOp.h\"\n#include \"ccpr\/GrCCPathParser.h\"\n\nusing PathInstance = GrCCPathProcessor::Instance;\n\n\/\/ If a path spans more pixels than this, we need to crop it or else analytic AA can run out of fp32\n\/\/ precision.\nstatic constexpr float kPathCropThreshold = 1 << 16;\n\nstatic void crop_path(const SkPath& path, const SkIRect& cropbox, SkPath* out) {\n SkPath cropboxPath;\n cropboxPath.addRect(SkRect::Make(cropbox));\n if (!Op(cropboxPath, path, kIntersect_SkPathOp, out)) {\n \/\/ This can fail if the PathOps encounter NaN or infinities.\n out->reset();\n }\n out->setIsVolatile(true);\n}\n\nbool GrCoverageCountingPathRenderer::IsSupported(const GrCaps& caps) {\n const GrShaderCaps& shaderCaps = *caps.shaderCaps();\n return shaderCaps.integerSupport() && shaderCaps.flatInterpolationSupport() &&\n caps.instanceAttribSupport() && GrCaps::kNone_MapFlags != caps.mapBufferFlags() &&\n caps.isConfigTexturable(kAlpha_half_GrPixelConfig) &&\n caps.isConfigRenderable(kAlpha_half_GrPixelConfig) &&\n !caps.blacklistCoverageCounting();\n}\n\nsk_sp<GrCoverageCountingPathRenderer> GrCoverageCountingPathRenderer::CreateIfSupported(\n const GrCaps& caps, bool drawCachablePaths) {\n auto ccpr = IsSupported(caps) ? new GrCoverageCountingPathRenderer(drawCachablePaths) : nullptr;\n return sk_sp<GrCoverageCountingPathRenderer>(ccpr);\n}\n\nGrCCPerOpListPaths* GrCoverageCountingPathRenderer::lookupPendingPaths(uint32_t opListID) {\n auto it = fPendingPaths.find(opListID);\n if (fPendingPaths.end() == it) {\n auto paths = skstd::make_unique<GrCCPerOpListPaths>();\n it = fPendingPaths.insert(std::make_pair(opListID, std::move(paths))).first;\n }\n return it->second.get();\n}\n\nvoid GrCoverageCountingPathRenderer::adoptAndRecordOp(GrCCDrawPathsOp* op,\n const DrawPathArgs& args) {\n GrRenderTargetContext* rtc = args.fRenderTargetContext;\n if (uint32_t opListID = rtc->addDrawOp(*args.fClip, std::unique_ptr<GrDrawOp>(op))) {\n \/\/ If the Op wasn't dropped or combined, give it a pointer to its owning GrCCPerOpListPaths.\n op->wasRecorded(this->lookupPendingPaths(opListID));\n }\n}\n\nGrPathRenderer::CanDrawPath GrCoverageCountingPathRenderer::onCanDrawPath(\n const CanDrawPathArgs& args) const {\n if (args.fShape->hasUnstyledKey() && !fDrawCachablePaths) {\n return CanDrawPath::kNo;\n }\n\n if (!args.fShape->style().isSimpleFill() || args.fShape->inverseFilled() ||\n args.fViewMatrix->hasPerspective() || GrAAType::kCoverage != args.fAAType) {\n return CanDrawPath::kNo;\n }\n\n SkPath path;\n args.fShape->asPath(&path);\n SkRect devBounds;\n SkIRect devIBounds;\n args.fViewMatrix->mapRect(&devBounds, path.getBounds());\n devBounds.roundOut(&devIBounds);\n if (!devIBounds.intersect(*args.fClipConservativeBounds)) {\n \/\/ Path is completely clipped away. Our code will eventually notice this before doing any\n \/\/ real work.\n return CanDrawPath::kYes;\n }\n\n if (devIBounds.height() * devIBounds.width() > 256 * 256) {\n \/\/ Large paths can blow up the atlas fast. And they are not ideal for a two-pass rendering\n \/\/ algorithm. Give the simpler direct renderers a chance before we commit to drawing it.\n return CanDrawPath::kAsBackup;\n }\n\n if (args.fShape->hasUnstyledKey() && path.countVerbs() > 50) {\n \/\/ Complex paths do better cached in an SDF, if the renderer will accept them.\n return CanDrawPath::kAsBackup;\n }\n\n return CanDrawPath::kYes;\n}\n\nbool GrCoverageCountingPathRenderer::onDrawPath(const DrawPathArgs& args) {\n SkASSERT(!fFlushing);\n\n SkIRect clipIBounds;\n GrRenderTargetContext* rtc = args.fRenderTargetContext;\n args.fClip->getConservativeBounds(rtc->width(), rtc->height(), &clipIBounds, nullptr);\n\n SkPath path;\n args.fShape->asPath(&path);\n\n SkRect devBounds;\n args.fViewMatrix->mapRect(&devBounds, path.getBounds());\n\n if (SkTMax(devBounds.height(), devBounds.width()) > kPathCropThreshold) {\n \/\/ The path is too large. Crop it or analytic AA can run out of fp32 precision.\n SkPath croppedPath;\n path.transform(*args.fViewMatrix, &croppedPath);\n crop_path(croppedPath, clipIBounds, &croppedPath);\n this->adoptAndRecordOp(new GrCCDrawPathsOp(std::move(args.fPaint), clipIBounds,\n SkMatrix::I(), croppedPath,\n croppedPath.getBounds()), args);\n return true;\n }\n\n this->adoptAndRecordOp(new GrCCDrawPathsOp(std::move(args.fPaint), clipIBounds,\n *args.fViewMatrix, path, devBounds), args);\n return true;\n}\n\nstd::unique_ptr<GrFragmentProcessor> GrCoverageCountingPathRenderer::makeClipProcessor(\n GrProxyProvider* proxyProvider,\n uint32_t opListID, const SkPath& deviceSpacePath, const SkIRect& accessRect,\n int rtWidth, int rtHeight) {\n using MustCheckBounds = GrCCClipProcessor::MustCheckBounds;\n\n SkASSERT(!fFlushing);\n\n GrCCClipPath& clipPath =\n this->lookupPendingPaths(opListID)->fClipPaths[deviceSpacePath.getGenerationID()];\n if (!clipPath.isInitialized()) {\n \/\/ This ClipPath was just created during lookup. Initialize it.\n const SkRect& pathDevBounds = deviceSpacePath.getBounds();\n if (SkTMax(pathDevBounds.height(), pathDevBounds.width()) > kPathCropThreshold) {\n \/\/ The path is too large. Crop it or analytic AA can run out of fp32 precision.\n SkPath croppedPath;\n int maxRTSize = proxyProvider->caps()->maxRenderTargetSize();\n crop_path(deviceSpacePath, SkIRect::MakeWH(maxRTSize, maxRTSize), &croppedPath);\n clipPath.init(proxyProvider, croppedPath, accessRect, rtWidth, rtHeight);\n } else {\n clipPath.init(proxyProvider, deviceSpacePath, accessRect, rtWidth, rtHeight);\n }\n } else {\n clipPath.addAccess(accessRect);\n }\n\n bool mustCheckBounds = !clipPath.pathDevIBounds().contains(accessRect);\n return skstd::make_unique<GrCCClipProcessor>(&clipPath, MustCheckBounds(mustCheckBounds),\n deviceSpacePath.getFillType());\n}\n\nvoid GrCoverageCountingPathRenderer::preFlush(GrOnFlushResourceProvider* onFlushRP,\n const uint32_t* opListIDs, int numOpListIDs,\n SkTArray<sk_sp<GrRenderTargetContext>>* atlasDraws) {\n SkASSERT(!fFlushing);\n SkASSERT(fFlushingPaths.empty());\n SkDEBUGCODE(fFlushing = true);\n\n if (fPendingPaths.empty()) {\n return; \/\/ Nothing to draw.\n }\n\n \/\/ Move the per-opList paths that are about to be flushed from fPendingPaths to fFlushingPaths,\n \/\/ and count up the paths about to be flushed so we can preallocate buffers.\n int numPathDraws = 0;\n int numClipPaths = 0;\n GrCCPathParser::PathStats flushingPathStats;\n fFlushingPaths.reserve(numOpListIDs);\n for (int i = 0; i < numOpListIDs; ++i) {\n auto iter = fPendingPaths.find(opListIDs[i]);\n if (fPendingPaths.end() == iter) {\n continue; \/\/ No paths on this opList.\n }\n\n fFlushingPaths.push_back(std::move(iter->second));\n fPendingPaths.erase(iter);\n\n for (const GrCCDrawPathsOp* op : fFlushingPaths.back()->fDrawOps) {\n numPathDraws += op->countPaths(&flushingPathStats);\n }\n for (const auto& clipsIter : fFlushingPaths.back()->fClipPaths) {\n flushingPathStats.statPath(clipsIter.second.deviceSpacePath());\n }\n numClipPaths += fFlushingPaths.back()->fClipPaths.size();\n }\n\n if (0 == numPathDraws + numClipPaths) {\n return; \/\/ Nothing to draw.\n }\n\n auto resources = sk_make_sp<GrCCPerFlushResources>(onFlushRP, numPathDraws, numClipPaths,\n flushingPathStats);\n if (!resources->isMapped()) {\n return; \/\/ Some allocation failed.\n }\n\n \/\/ Layout atlas(es) and parse paths.\n SkDEBUGCODE(int numSkippedPaths = 0);\n for (const auto& flushingPaths : fFlushingPaths) {\n for (GrCCDrawPathsOp* op : flushingPaths->fDrawOps) {\n op->setupResources(resources.get(), onFlushRP);\n SkDEBUGCODE(numSkippedPaths += op->numSkippedInstances_debugOnly());\n }\n for (auto& clipsIter : flushingPaths->fClipPaths) {\n clipsIter.second.renderPathInAtlas(resources.get(), onFlushRP);\n }\n }\n SkASSERT(resources->nextPathInstanceIdx() == numPathDraws - numSkippedPaths);\n\n \/\/ Allocate the atlases and create instance buffers to draw them.\n if (!resources->finalize(onFlushRP, atlasDraws)) {\n return;\n }\n\n \/\/ Commit flushing paths to the resources once they are successfully completed.\n for (auto& flushingPaths : fFlushingPaths) {\n flushingPaths->fFlushResources = resources;\n }\n}\n\nvoid GrCoverageCountingPathRenderer::postFlush(GrDeferredUploadToken, const uint32_t* opListIDs,\n int numOpListIDs) {\n SkASSERT(fFlushing);\n \/\/ We wait to erase these until after flush, once Ops and FPs are done accessing their data.\n fFlushingPaths.reset();\n SkDEBUGCODE(fFlushing = false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (c) 2009-2013, United States Government as represented by the\n\/\/ Administrator of the National Aeronautics and Space Administration. All\n\/\/ rights reserved.\n\/\/\n\/\/ The NGT platform is licensed under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance with the\n\/\/ License. You may obtain a copy of the License at\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\/\/ __END_LICENSE__\n\n#include <vw\/Camera\/CameraSolve.h>\n#include <asp\/Core\/StereoSettings.h>\n#include <asp\/Camera\/PeruSatXML.h>\n#include <asp\/Camera\/LinescanPeruSatModel.h>\n\nnamespace asp {\n\nusing vw::Vector3;\nusing vw::Matrix3x3;\n\n\/\/ TODO: Port these changes to the base class\n\nvw::Vector2 PeruSatCameraModel::point_to_pixel(Vector3 const& point, double starty) const {\n\n \/\/ Use the generic solver to find the pixel \n \/\/ - This method will be slower but works for more complicated geometries\n vw::camera::CameraGenericLMA model(this, point);\n int status;\n vw::Vector2 start = m_image_size \/ 2.0; \/\/ Use the center as the initial guess\n if (starty >= 0) \/\/ If the user provided a line number guess, use it.\n start[1] = starty;\n\n \/\/ Solver constants\n const double ABS_TOL = 1e-16;\n const double REL_TOL = 1e-16;\n const int MAX_ITERATIONS = 1e+5;\n const double MAX_ERROR = 0.01;\n\n Vector3 objective(0, 0, 0);\n vw::Vector2 solution = vw::math::levenberg_marquardtFixed<vw::camera::CameraGenericLMA, 2,3>\n (model, start, objective, status, ABS_TOL, REL_TOL, MAX_ITERATIONS);\n\n double error = norm_2(model(solution));\n\n VW_ASSERT( (status > 0) && (error < MAX_ERROR),\n vw::camera::PointToPixelErr()\n << \"Unable to project point into LinescanPeruSat model\" );\n\n return solution;\n}\n\nvoid PeruSatCameraModel::check_time(double time, std::string const& location) const {\n if ((time < m_min_time) || (time > m_max_time))\n vw::vw_throw(vw::ArgumentErr() << \"PeruSatCameraModel::\"<<location\n << \": Requested time \"<<time<<\" is out of bounds (\"\n << m_min_time << \" <-> \"<<m_max_time<<\")\\n\");\n}\n\nvw::Vector3 PeruSatCameraModel::get_camera_center_at_time(double time) const {\n check_time(time, \"get_camera_center_at_time\");\n return m_position_func(time);\n}\nvw::Vector3 PeruSatCameraModel::get_camera_velocity_at_time(double time) const { \n check_time(time, \"get_camera_velocity_at_time\");\n return m_velocity_func(time); \n}\nvw::Quat PeruSatCameraModel::get_camera_pose_at_time(double time) const {\n check_time(time, \"get_camera_pose_at_time\");\n return m_pose_func(time); \n}\n\ndouble PeruSatCameraModel::get_time_at_line(double line) const {\n \/\/ Allow finding the time at any line, even negative ones. Here a\n \/\/ simple slope-intercept formula is used rather than a table so one\n \/\/ cannot run out of bounds.\n return m_time_func(line); \n}\n\n\nVector3 PeruSatCameraModel::get_local_pixel_vector(vw::Vector2 const& pix) const {\n\n \/\/ According to Modelo%20Orbital%20PeruSAT-1.pdf:\n \n \/\/ psi_x = tan_psi_x[0] * (col - col_ref) + tan_psi_x[1]\n \/\/ psi_y = tan_psi_y[0] * (col - col_ref) + tan_psi_y[1]\n\n \/\/ where those coefficients are given in LINE_OF_SIGHT_TANPSIX\n \/\/ and LINE_OF_SIGHT_TANPSIY.\n\n \/\/ The doc says col_ref is 1, so for us it will be 0 since our\n \/\/ columns start form 0.\n\n double col = pix[0];\n double psi_x = m_tan_psi_x[0] * col + m_tan_psi_x[1];\n double psi_y = m_tan_psi_y[0] * col + m_tan_psi_y[1];\n Vector3 result = Vector3(tan(psi_y), -tan(psi_x), 1.0);\n\n \/\/ Make the direction have unit length\n result = normalize(result);\n \n \/\/ Go from sensor coordinates to satellite body coordinates.\n \/\/ The instrument biases were not documented at all and took a while\n \/\/ to figure out.\n result = m_inverse_instrument_biases.rotate(result);\n\n return result;\n}\n\nboost::shared_ptr<PeruSatCameraModel> load_perusat_camera_model_from_xml(std::string const& path){\n\n vw_out(vw::DebugMessage,\"asp\") << \"Loading PeruSat camera file: \" << path << std::endl;\n \/\/ Parse the PeruSat XML file\n PeruSatXML xml_reader;\n xml_reader.read_xml(path);\n\n \/\/ Get all the initial functors\n vw::camera::LinearTimeInterpolation\n time_func = xml_reader.setup_time_func();\n vw::camera::LagrangianInterpolation\n position_func = xml_reader.setup_position_func(time_func);\n vw::camera::LagrangianInterpolation\n velocity_func = xml_reader.setup_velocity_func(time_func);\n vw::camera::SLERPPoseInterpolation\n pose_func = xml_reader.setup_pose_func(time_func);\n\n \/\/ Find the range of times for which we can solve for position and pose\n\n double min_position_time = position_func.get_t0();\n double max_position_time = position_func.get_tend();\n \n double min_velocity_time = velocity_func.get_t0();\n double max_velocity_time = velocity_func.get_tend();\n\n double min_pose_time = pose_func.get_t0();\n double max_pose_time = pose_func.get_tend();\n\n double min_time = std::max(min_position_time, std::max(min_velocity_time, min_pose_time));\n double max_time = std::min(max_position_time, std::min(max_velocity_time, max_pose_time));\n\n std::cout << \"--disable velocity aberration is \"\n << stereo_settings().disable_correct_velocity_aberration << std::endl;\n \n std::cout << \"--disable correct atmospheric refraction is \"\n << stereo_settings().disable_correct_atmospheric_refraction << std::endl;\n \n \/\/ Feed everything into a new camera model.\n return boost::shared_ptr<PeruSatCameraModel>\n (new PeruSatCameraModel(position_func, velocity_func, \n pose_func, time_func, \n xml_reader.m_tan_psi_x,\n xml_reader.m_tan_psi_y,\n xml_reader.m_instrument_biases,\n xml_reader.m_image_size,\n min_time, max_time,\n !stereo_settings().disable_correct_velocity_aberration,\n !stereo_settings().disable_correct_atmospheric_refraction));\n\n} \/\/ End function load_perusat_camera_model()\n\n\n} \/\/ end namespace asp\n\n<commit_msg>perusat: Turn off for now velocity aberation and atmospheric refraction and print a message about that<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (c) 2009-2013, United States Government as represented by the\n\/\/ Administrator of the National Aeronautics and Space Administration. All\n\/\/ rights reserved.\n\/\/\n\/\/ The NGT platform is licensed under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance with the\n\/\/ License. You may obtain a copy of the License at\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\/\/ __END_LICENSE__\n\n#include <vw\/Camera\/CameraSolve.h>\n#include <asp\/Core\/StereoSettings.h>\n#include <asp\/Camera\/PeruSatXML.h>\n#include <asp\/Camera\/LinescanPeruSatModel.h>\n\nnamespace asp {\n\n\/\/ While static variables are not thread-safe, this will be changed only once,\n\/\/ the first time a PeruSatCameraModel is loaded, and model loading is a serial\n\/\/ process. \nstatic bool perusat_correction_note_printed = false;\n\nusing vw::Vector3;\nusing vw::Matrix3x3;\n\n\/\/ TODO: Port these changes to the base class\n\nvw::Vector2 PeruSatCameraModel::point_to_pixel(Vector3 const& point, double starty) const {\n\n \/\/ Use the generic solver to find the pixel \n \/\/ - This method will be slower but works for more complicated geometries\n vw::camera::CameraGenericLMA model(this, point);\n int status;\n vw::Vector2 start = m_image_size \/ 2.0; \/\/ Use the center as the initial guess\n if (starty >= 0) \/\/ If the user provided a line number guess, use it.\n start[1] = starty;\n\n \/\/ Solver constants\n const double ABS_TOL = 1e-16;\n const double REL_TOL = 1e-16;\n const int MAX_ITERATIONS = 1e+5;\n const double MAX_ERROR = 0.01;\n\n Vector3 objective(0, 0, 0);\n vw::Vector2 solution = vw::math::levenberg_marquardtFixed<vw::camera::CameraGenericLMA, 2,3>\n (model, start, objective, status, ABS_TOL, REL_TOL, MAX_ITERATIONS);\n\n double error = norm_2(model(solution));\n\n VW_ASSERT( (status > 0) && (error < MAX_ERROR),\n vw::camera::PointToPixelErr()\n << \"Unable to project point into LinescanPeruSat model\" );\n\n return solution;\n}\n\nvoid PeruSatCameraModel::check_time(double time, std::string const& location) const {\n if ((time < m_min_time) || (time > m_max_time))\n vw::vw_throw(vw::ArgumentErr() << \"PeruSatCameraModel::\"<<location\n << \": Requested time \"<<time<<\" is out of bounds (\"\n << m_min_time << \" <-> \"<<m_max_time<<\")\\n\");\n}\n\nvw::Vector3 PeruSatCameraModel::get_camera_center_at_time(double time) const {\n check_time(time, \"get_camera_center_at_time\");\n return m_position_func(time);\n}\nvw::Vector3 PeruSatCameraModel::get_camera_velocity_at_time(double time) const { \n check_time(time, \"get_camera_velocity_at_time\");\n return m_velocity_func(time); \n}\nvw::Quat PeruSatCameraModel::get_camera_pose_at_time(double time) const {\n check_time(time, \"get_camera_pose_at_time\");\n return m_pose_func(time); \n}\n\ndouble PeruSatCameraModel::get_time_at_line(double line) const {\n \/\/ Allow finding the time at any line, even negative ones. Here a\n \/\/ simple slope-intercept formula is used rather than a table so one\n \/\/ cannot run out of bounds.\n return m_time_func(line); \n}\n\n\nVector3 PeruSatCameraModel::get_local_pixel_vector(vw::Vector2 const& pix) const {\n\n \/\/ According to Modelo%20Orbital%20PeruSAT-1.pdf:\n \n \/\/ psi_x = tan_psi_x[0] * (col - col_ref) + tan_psi_x[1]\n \/\/ psi_y = tan_psi_y[0] * (col - col_ref) + tan_psi_y[1]\n\n \/\/ where those coefficients are given in LINE_OF_SIGHT_TANPSIX\n \/\/ and LINE_OF_SIGHT_TANPSIY.\n\n \/\/ The doc says col_ref is 1, so for us it will be 0 since our\n \/\/ columns start form 0.\n\n double col = pix[0];\n double psi_x = m_tan_psi_x[0] * col + m_tan_psi_x[1];\n double psi_y = m_tan_psi_y[0] * col + m_tan_psi_y[1];\n Vector3 result = Vector3(tan(psi_y), -tan(psi_x), 1.0);\n\n \/\/ Make the direction have unit length\n result = normalize(result);\n \n \/\/ Go from sensor coordinates to satellite body coordinates.\n \/\/ The instrument biases were not documented at all and took a while\n \/\/ to figure out.\n result = m_inverse_instrument_biases.rotate(result);\n\n return result;\n}\n\nboost::shared_ptr<PeruSatCameraModel> load_perusat_camera_model_from_xml(std::string const& path){\n\n vw_out(vw::DebugMessage,\"asp\") << \"Loading PeruSat camera file: \" << path << std::endl;\n \/\/ Parse the PeruSat XML file\n PeruSatXML xml_reader;\n xml_reader.read_xml(path);\n\n \/\/ Get all the initial functors\n vw::camera::LinearTimeInterpolation\n time_func = xml_reader.setup_time_func();\n vw::camera::LagrangianInterpolation\n position_func = xml_reader.setup_position_func(time_func);\n vw::camera::LagrangianInterpolation\n velocity_func = xml_reader.setup_velocity_func(time_func);\n vw::camera::SLERPPoseInterpolation\n pose_func = xml_reader.setup_pose_func(time_func);\n\n \/\/ Find the range of times for which we can solve for position and pose\n double min_position_time = position_func.get_t0();\n double max_position_time = position_func.get_tend();\n double min_velocity_time = velocity_func.get_t0();\n double max_velocity_time = velocity_func.get_tend();\n double min_pose_time = pose_func.get_t0();\n double max_pose_time = pose_func.get_tend();\n double min_time = std::max(min_position_time, std::max(min_velocity_time, min_pose_time));\n double max_time = std::min(max_position_time, std::min(max_velocity_time, max_pose_time));\n\n \/\/ See note on this below\n bool correct_velocity_aberration = false;\n bool correct_atmospheric_refraction = false;\n \n \/\/ Create the model. This can throw an exception.\n boost::shared_ptr<PeruSatCameraModel> cam\n (new PeruSatCameraModel(position_func, velocity_func, \n pose_func, time_func, \n xml_reader.m_tan_psi_x,\n xml_reader.m_tan_psi_y,\n xml_reader.m_instrument_biases,\n xml_reader.m_image_size,\n min_time, max_time,\n correct_velocity_aberration,\n correct_atmospheric_refraction));\n\n \/\/ Print this note only if PeruSat model loading was successful, as\n \/\/ sometimes this camera loading function is invoked when querying\n \/\/ an unknown XML model and we may not end up using this session if\n \/\/ loading fails.\n if (!perusat_correction_note_printed) {\n vw::vw_out() << \"Not using atmospheric and velocity aberration correction \"\n << \"with PeruSat cameras to maintain closer agreement with \"\n << \"the RPC approximation to this model.\\n\";\n perusat_correction_note_printed = true;\n }\n \n return cam;\n} \/\/ End function load_perusat_camera_model()\n\n} \/\/ end namespace asp\n\n<|endoftext|>"} {"text":"<commit_before>\n#ifdef HAVE_CONFIG_H\n# include \"elementary_config.h\"\n#endif\n\n#define ELM_INTERNAL_API_ARGESFSDFEFC\n#define ELM_INTERFACE_ATSPI_ACCESSIBLE_PROTECTED\n#define ELM_INTERFACE_ATSPI_COMPONENT_PROTECTED\n#define ELM_INTERFACE_ATSPI_ACTION_PROTECTED\n#define ELM_INTERFACE_ATSPI_VALUE_PROTECTED\n#define ELM_INTERFACE_ATSPI_EDITABLE_TEXT_PROTECTED\n#define ELM_INTERFACE_ATSPI_TEXT_PROTECTED\n#define ELM_INTERFACE_ATSPI_SELECTION_PROTECTED\n#define ELM_INTERFACE_ATSPI_IMAGE_PROTECTED\n#define ELM_INTERFACE_ATSPI_WIDGET_ACTION_PROTECTED\n\n#include <Eo.h>\n#include <Evas.h>\n#include <Elementary.h>\n#include <elm_widget.h>\n#include <elm_interface_atspi_accessible.h>\n\n#include <elc_ctxpopup.eo.hh>\n#include <elc_fileselector_button.eo.hh>\n#include <elc_fileselector_entry.eo.hh>\n#include <elc_fileselector.eo.hh>\n#include <elc_hoversel.eo.hh>\n#include <elc_multibuttonentry.eo.hh>\n#include <elc_naviframe.eo.hh>\n#include <elc_player.eo.hh>\n#include <elc_popup.eo.hh>\n#include <elm_access.eo.hh>\n#include <elm_actionslider.eo.hh>\n#include <elm_app_client.eo.hh>\n#include <elm_app_client_view.eo.hh>\n#include <elm_app_server.eo.hh>\n#include <elm_app_server_view.eo.hh>\n#include <elm_atspi_app_object.eo.hh>\n#include <elm_bg.eo.hh>\n#include <elm_box.eo.hh>\n#include <elm_bubble.eo.hh>\n#include <elm_button.eo.hh>\n#include <elm_calendar.eo.hh>\n#include <elm_check.eo.hh>\n#include <elm_clock.eo.hh>\n#include <elm_colorselector.eo.hh>\n#include <elm_conformant.eo.hh>\n#include <elm_container.eo.hh>\n#include <elm_datetime.eo.hh>\n#include <elm_dayselector.eo.hh>\n#include <elm_diskselector.eo.hh>\n#include <elm_entry.eo.hh>\n#include <elm_flip.eo.hh>\n#include <elm_flipselector.eo.hh>\n#include <elm_frame.eo.hh>\n#include <elm_gengrid.eo.hh>\n#include <elm_gengrid_pan.eo.hh>\n#include <elm_genlist.eo.hh>\n#include <elm_genlist_pan.eo.hh>\n#include <elm_gesture_layer.eo.hh>\n#include <elm_glview.eo.hh>\n#include <elm_grid.eo.hh>\n#include <elm_hover.eo.hh>\n#include <elm_icon.eo.hh>\n#include <elm_image.eo.hh>\n#include <elm_index.eo.hh>\n#include <elm_interface_atspi_accessible.eo.hh>\n#include <elm_interface_atspi_action.eo.hh>\n#include <elm_interface_atspi_component.eo.hh>\n#include <elm_interface_atspi_editable_text.eo.hh>\n#include <elm_interface_atspi_image.eo.hh>\n#include <elm_interface_atspi_selection.eo.hh>\n#include <elm_interface_atspi_text.eo.hh>\n#include <elm_interface_atspi_value.eo.hh>\n#include <elm_interface_atspi_widget_action.eo.hh>\n#include <elm_interface_atspi_widget.eo.hh>\n#include <elm_interface_atspi_window.eo.hh>\n#include <elm_interface_fileselector.eo.hh>\n#include <elm_interface_scrollable.eo.hh>\n#include <elm_inwin.eo.hh>\n#include <elm_label.eo.hh>\n#include <elm_layout.eo.hh>\n#include <elm_list.eo.hh>\n#include <elm_mapbuf.eo.hh>\n#include <elm_map.eo.hh>\n#include <elm_map_pan.eo.hh>\n#include <elm_menu.eo.hh>\n#include <elm_notify.eo.hh>\n#include <elm_panel.eo.hh>\n#include <elm_pan.eo.hh>\n#include <elm_panes.eo.hh>\n#include <elm_photocam.eo.hh>\n#include <elm_photocam_pan.eo.hh>\n#include <elm_photo.eo.hh>\n#include <elm_plug.eo.hh>\n#include <elm_prefs.eo.hh>\n#include <elm_progressbar.eo.hh>\n#include <elm_radio.eo.hh>\n#include <elm_route.eo.hh>\n#include <elm_scroller.eo.hh>\n#include <elm_segment_control.eo.hh>\n#include <elm_separator.eo.hh>\n#include <elm_slider.eo.hh>\n#include <elm_slideshow.eo.hh>\n#include <elm_spinner.eo.hh>\n#include <elm_systray.eo.hh>\n#include <elm_table.eo.hh>\n#include <elm_thumb.eo.hh>\n#include <elm_toolbar.eo.hh>\n#include <elm_video.eo.hh>\n#include <elm_web.eo.hh>\n#include <elm_widget.eo.hh>\n#include <elm_win.eo.hh>\n\nint main()\n{\n}\n<commit_msg>elementary++: Added missing includes.<commit_after>\n#ifdef HAVE_CONFIG_H\n# include \"elementary_config.h\"\n#endif\n\n#define ELM_INTERNAL_API_ARGESFSDFEFC\n#define ELM_INTERFACE_ATSPI_ACCESSIBLE_PROTECTED\n#define ELM_INTERFACE_ATSPI_COMPONENT_PROTECTED\n#define ELM_INTERFACE_ATSPI_ACTION_PROTECTED\n#define ELM_INTERFACE_ATSPI_VALUE_PROTECTED\n#define ELM_INTERFACE_ATSPI_EDITABLE_TEXT_PROTECTED\n#define ELM_INTERFACE_ATSPI_TEXT_PROTECTED\n#define ELM_INTERFACE_ATSPI_SELECTION_PROTECTED\n#define ELM_INTERFACE_ATSPI_IMAGE_PROTECTED\n#define ELM_INTERFACE_ATSPI_WIDGET_ACTION_PROTECTED\n\n#include <Eo.h>\n#include <Evas.h>\n#include <Elementary.h>\n\n#include <elm_widget.h>\n#include <elm_interface_scrollable.h>\n#include <elm_interface_atspi_text.h>\n#include <elm_interface_atspi_accessible.h>\n\n#include <elc_ctxpopup.eo.hh>\n#include <elc_fileselector_button.eo.hh>\n#include <elc_fileselector_entry.eo.hh>\n#include <elc_fileselector.eo.hh>\n#include <elc_hoversel.eo.hh>\n#include <elc_multibuttonentry.eo.hh>\n#include <elc_naviframe.eo.hh>\n#include <elc_player.eo.hh>\n#include <elc_popup.eo.hh>\n#include <elm_access.eo.hh>\n#include <elm_actionslider.eo.hh>\n#include <elm_app_client.eo.hh>\n#include <elm_app_client_view.eo.hh>\n#include <elm_app_server.eo.hh>\n#include <elm_app_server_view.eo.hh>\n#include <elm_atspi_app_object.eo.hh>\n#include <elm_bg.eo.hh>\n#include <elm_box.eo.hh>\n#include <elm_bubble.eo.hh>\n#include <elm_button.eo.hh>\n#include <elm_calendar.eo.hh>\n#include <elm_check.eo.hh>\n#include <elm_clock.eo.hh>\n#include <elm_colorselector.eo.hh>\n#include <elm_conformant.eo.hh>\n#include <elm_container.eo.hh>\n#include <elm_datetime.eo.hh>\n#include <elm_dayselector.eo.hh>\n#include <elm_diskselector.eo.hh>\n#include <elm_entry.eo.hh>\n#include <elm_flip.eo.hh>\n#include <elm_flipselector.eo.hh>\n#include <elm_frame.eo.hh>\n#include <elm_gengrid.eo.hh>\n#include <elm_gengrid_pan.eo.hh>\n#include <elm_genlist.eo.hh>\n#include <elm_genlist_pan.eo.hh>\n#include <elm_gesture_layer.eo.hh>\n#include <elm_glview.eo.hh>\n#include <elm_grid.eo.hh>\n#include <elm_hover.eo.hh>\n#include <elm_icon.eo.hh>\n#include <elm_image.eo.hh>\n#include <elm_index.eo.hh>\n#include <elm_interface_atspi_accessible.eo.hh>\n#include <elm_interface_atspi_action.eo.hh>\n#include <elm_interface_atspi_component.eo.hh>\n#include <elm_interface_atspi_editable_text.eo.hh>\n#include <elm_interface_atspi_image.eo.hh>\n#include <elm_interface_atspi_selection.eo.hh>\n#include <elm_interface_atspi_text.eo.hh>\n#include <elm_interface_atspi_value.eo.hh>\n#include <elm_interface_atspi_widget_action.eo.hh>\n#include <elm_interface_atspi_widget.eo.hh>\n#include <elm_interface_atspi_window.eo.hh>\n#include <elm_interface_fileselector.eo.hh>\n#include <elm_interface_scrollable.eo.hh>\n#include <elm_inwin.eo.hh>\n#include <elm_label.eo.hh>\n#include <elm_layout.eo.hh>\n#include <elm_list.eo.hh>\n#include <elm_mapbuf.eo.hh>\n#include <elm_map.eo.hh>\n#include <elm_map_pan.eo.hh>\n#include <elm_menu.eo.hh>\n#include <elm_notify.eo.hh>\n#include <elm_panel.eo.hh>\n#include <elm_pan.eo.hh>\n#include <elm_panes.eo.hh>\n#include <elm_photocam.eo.hh>\n#include <elm_photocam_pan.eo.hh>\n#include <elm_photo.eo.hh>\n#include <elm_plug.eo.hh>\n#include <elm_prefs.eo.hh>\n#include <elm_progressbar.eo.hh>\n#include <elm_radio.eo.hh>\n#include <elm_route.eo.hh>\n#include <elm_scroller.eo.hh>\n#include <elm_segment_control.eo.hh>\n#include <elm_separator.eo.hh>\n#include <elm_slider.eo.hh>\n#include <elm_slideshow.eo.hh>\n#include <elm_spinner.eo.hh>\n#include <elm_systray.eo.hh>\n#include <elm_table.eo.hh>\n#include <elm_thumb.eo.hh>\n#include <elm_toolbar.eo.hh>\n#include <elm_video.eo.hh>\n#include <elm_web.eo.hh>\n#include <elm_widget.eo.hh>\n#include <elm_win.eo.hh>\n\nint main()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* (C) 2016 Daniel Neus\n* 2016 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"tests.h\"\n\n#if defined(BOTAN_HAS_FILTERS)\n #include <botan\/secqueue.h>\n #include <botan\/pipe.h>\n #include <botan\/filters.h>\n #include <botan\/comp_filter.h>\n #include <botan\/cipher_filter.h>\n#endif\n\nnamespace Botan_Tests {\n\n#if defined(BOTAN_HAS_FILTERS)\n\nclass Filter_Tests : public Test\n {\n public:\n std::vector<Test::Result> run() override\n {\n std::vector<Test::Result> results;\n\n results.push_back(test_secqueue());\n results.push_back(test_pipe_hash());\n results.push_back(test_pipe_mac());\n results.push_back(test_pipe_stream());\n results.push_back(test_pipe_cipher());\n results.push_back(test_pipe_compress());\n results.push_back(test_pipe_codec());\n results.push_back(test_fork());\n\n#if defined(BOTAN_TARGET_OS_HAS_THREADS) && 0\n \/\/ Threaded_Fork is broken\n results.push_back(test_threaded_fork());\n#endif\n\n return results;\n }\n\n private:\n Test::Result test_secqueue()\n {\n Test::Result result(\"SecureQueue\");\n\n try\n {\n Botan::SecureQueue queue_a;\n std::vector<uint8_t> test_data = {0x24, 0xB2, 0xBF, 0xC2, 0xE6, 0xD4, 0x7E, 0x04, 0x67, 0xB3};\n queue_a.write(test_data.data(), test_data.size());\n\n result.test_eq(\"size of SecureQueue is correct\", queue_a.size(), test_data.size());\n result.test_eq(\"0 bytes read so far from SecureQueue\", queue_a.get_bytes_read(), 0);\n\n uint8_t b;\n size_t bytes_read = queue_a.read_byte(b);\n result.test_eq(\"1 byte read\", bytes_read, 1);\n\n Botan::secure_vector<uint8_t> produced(b);\n Botan::secure_vector<uint8_t> expected(test_data.at(0));\n result.test_eq(\"byte read is correct\", produced, expected);\n\n result.test_eq(\"1 bytes read so far from SecureQueue\", queue_a.get_bytes_read(), 1);\n\n Botan::SecureQueue queue_b;\n queue_a = queue_b;\n result.test_eq(\"bytes_read is set correctly\", queue_a.get_bytes_read(), 0);\n }\n catch (std::exception& e)\n {\n result.test_failure(\"SecureQueue\", e.what());\n }\n\n return result;\n }\n\n Test::Result test_pipe_mac()\n {\n Test::Result result(\"Pipe\");\n const Botan::SymmetricKey key(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n Botan::Pipe pipe(new Botan::MAC_Filter(\"HMAC(SHA-256)\", key, 12),\n new Botan::Base64_Encoder);\n\n pipe.process_msg(\"Hi\");\n pipe.process_msg(\"Bye\");\n pipe.process_msg(\"Hi\");\n\n result.test_eq(\"MAC 1\", pipe.read_all_as_string(0), \"e7NoVbtudgU0QiCZ\");\n result.test_eq(\"MAC 2\", pipe.read_all_as_string(1), \"LhPnfEG+0rk+Ej6y\");\n result.test_eq(\"MAC 3\", pipe.read_all_as_string(2), \"e7NoVbtudgU0QiCZ\");\n\n return result;\n }\n\n Test::Result test_pipe_hash()\n {\n Test::Result result(\"Pipe\");\n Botan::Pipe pipe(new Botan::Hash_Filter(\"SHA-224\"));\n pipe.pop();\n pipe.append(new Botan::Hash_Filter(\"SHA-256\"));\n\n result.test_eq(\"Message count\", pipe.message_count(), 0);\n\n pipe.start_msg();\n uint8_t inb = 0x41;\n pipe.write(&inb, 1);\n pipe.write(std::vector<uint8_t>(6, 0x41));\n pipe.write(inb);\n pipe.end_msg();\n\n result.test_eq(\"Message count\", pipe.message_count(), 1);\n result.test_eq(\"Message size\", pipe.remaining(), 32);\n\n std::vector<uint8_t> out(32), last16(16);\n\n result.test_eq(\"Bytes read\", pipe.get_bytes_read(0), 0);\n result.test_eq(\"Expected read count\", pipe.read(&out[0], 5), 5);\n result.test_eq(\"Bytes read\", pipe.get_bytes_read(0), 5);\n result.test_eq(\"Peek read\", pipe.peek(last16.data(), 18, 11), 16);\n result.test_eq(\"Expected read count\", pipe.read(&out[5], 17), 17);\n result.test_eq(\"Bytes read\", pipe.get_bytes_read(0), 22);\n result.test_eq(\"Remaining\", pipe.remaining(), 10);\n result.test_eq(\"Remaining\", pipe.remaining(), 10);\n result.test_eq(\"Expected read count\", pipe.read(&out[22], 12), 10);\n result.test_eq(\"Expected read count\", pipe.read(&out[0], 1), 0); \/\/ no more output\n result.test_eq(\"Bytes read\", pipe.get_bytes_read(0), 32);\n\n result.test_eq(\"Expected output\", out, \"C34AB6ABB7B2BB595BC25C3B388C872FD1D575819A8F55CC689510285E212385\");\n result.test_eq(\"Expected last16\", last16, \"D1D575819A8F55CC689510285E212385\");\n\n pipe.reset();\n\n#if defined(BOTAN_HAS_CRC32)\n pipe.prepend(new Botan::Hash_Filter(\"CRC32\"));\n pipe.append(new Botan::Hash_Filter(\"CRC32\"));\n pipe.process_msg(std::vector<byte>(1024, 0));\n result.test_eq(\"Expected CRC32d\", pipe.read_all(1), \"99841F60\");\n#endif\n\n return result;\n }\n\n Test::Result test_pipe_cipher()\n {\n Test::Result result(\"Pipe\");\n\n Botan::Cipher_Mode_Filter* cipher =\n new Botan::Cipher_Mode_Filter(Botan::get_cipher_mode(\"AES-128\/CBC\/PKCS7\", Botan::ENCRYPTION));\n\n \/\/ takes ownership of cipher\n Botan::Pipe pipe(cipher);\n\n cipher->set_key(Botan::SymmetricKey(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"));\n cipher->set_iv(Botan::InitializationVector(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"));\n\n pipe.process_msg(\"Don't use plain CBC mode\");\n\n auto ciphertext = pipe.read_all();\n\n result.test_eq(\"Ciphertext\", ciphertext, \"9BDD7300E0CB61CA71FFF957A71605DB6836159C36781246A1ADF50982757F4B\");\n\n Botan::Cipher_Mode_Filter* dec_cipher =\n new Botan::Cipher_Mode_Filter(Botan::get_cipher_mode(\"AES-128\/CBC\/PKCS7\", Botan::DECRYPTION));\n pipe.append(dec_cipher);\n dec_cipher->set_key(Botan::SymmetricKey(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"));\n dec_cipher->set_iv(Botan::InitializationVector(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB\"));\n cipher->set_iv(Botan::InitializationVector(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB\"));\n\n const std::vector<byte> zeros_in(1024);\n Botan::DataSource_Memory src(zeros_in);\n pipe.start_msg();\n pipe.write(src);\n pipe.end_msg();\n\n Botan::secure_vector<byte> zeros_out = pipe.read_all(1);\n\n result.test_eq(\"Cipher roundtrip\", zeros_in, zeros_out);\n return result;\n }\n\n Test::Result test_pipe_compress()\n {\n Test::Result result(\"Pipe\");\n\n#if defined(BOTAN_HAS_ZLIB)\n Botan::Pipe pipe(new Botan::Compression_Filter(\"zlib\", 9));\n\n const std::string input_str = \"Hello there HELLO there I said is this thing on?\";\n\n pipe.start_msg();\n pipe.write(input_str);\n pipe.end_msg();\n\n auto compr = pipe.read_all(0);\n \/\/ Can't do equality check on compression because output may differ\n result.test_lt(\"Compressed is shorter\", compr.size(), input_str.size());\n\n pipe.append(new Botan::Decompression_Filter(\"zlib\"));\n pipe.pop(); \/\/ remove compressor\n\n pipe.process_msg(compr);\n\n std::string decomp = pipe.read_all_as_string(1);\n result.test_eq(\"Decompressed ok\", decomp, input_str);\n#endif\n\n return result;\n }\n\n Test::Result test_pipe_codec()\n {\n Test::Result result(\"Pipe\");\n\n Botan::Pipe pipe(new Botan::Base64_Encoder);\n\n result.test_eq(\"Message count\", pipe.message_count(), 0);\n\n pipe.process_msg(\"ABCDX\");\n\n result.test_eq(\"Message count\", pipe.message_count(), 1);\n result.test_eq(\"Message size\", pipe.remaining(), 8);\n\n std::string output = pipe.read_all_as_string(0);\n result.test_eq(\"Message size\", pipe.remaining(0), 0);\n result.test_eq(\"Output round tripped\", output, \"QUJDRFg=\");\n\n pipe.append(new Botan::Base64_Decoder);\n pipe.process_msg(\"FOOBAZ\");\n\n result.test_eq(\"base64 roundtrip\", pipe.read_all_as_string(1), \"FOOBAZ\");\n\n pipe.pop();\n pipe.pop();\n\n \/\/ Pipe is empty of filters, should still pass through\n pipe.process_msg(\"surprise plaintext\");\n\n pipe.set_default_msg(2);\n result.test_eq(\"Message 2\", pipe.read_all_as_string(), \"surprise plaintext\");\n\n pipe.append(new Botan::Hex_Decoder);\n\n pipe.process_msg(\"F331F00D\");\n Botan::secure_vector<uint8_t> bin = pipe.read_all(3);\n result.test_eq(\"hex decoded\", bin, \"F331F00D\");\n\n pipe.append(new Botan::Hex_Encoder);\n pipe.process_msg(\"F331F00D\");\n result.test_eq(\"hex roundtrip\", pipe.read_all_as_string(4), \"F331F00D\");\n\n return result;\n }\n\n Test::Result test_pipe_stream()\n {\n Test::Result result(\"Pipe\");\n\n Botan::Keyed_Filter* aes = nullptr;\n const Botan::SymmetricKey key(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n const Botan::InitializationVector iv(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n Botan::Pipe pipe(aes = new Botan::StreamCipher_Filter(\"CTR-BE(AES-128)\", key));\n\n aes->set_iv(iv);\n\n pipe.process_msg(\"ABCDEF\");\n\n result.test_eq(\"Message count\", pipe.message_count(), 1);\n result.test_eq(\"Ciphertext\", pipe.read_all(), \"FDFD6238F7C6\");\n return result;\n }\n\n Test::Result test_fork()\n {\n Test::Result result(\"Fork\");\n\n Botan::Pipe pipe(new Botan::Fork(new Botan::Hash_Filter(\"SHA-256\"),\n new Botan::Hash_Filter(\"SHA-512-256\")));\n\n result.test_eq(\"Message count\", pipe.message_count(), 0);\n pipe.process_msg(\"OMG\");\n result.test_eq(\"Message count\", pipe.message_count(), 2);\n\n \/\/ Test reading out of order\n result.test_eq(\"Hash 2\", pipe.read_all(1), \"610480FFA82F24F6926544B976FE387878E3D973C03DFD591C2E9896EFB903E0\");\n result.test_eq(\"Hash 1\", pipe.read_all(0), \"C00862D1C6C1CF7C1B49388306E7B3C1BB79D8D6EC978B41035B556DBB3797DF\");\n\n return result;\n\n }\n\n#if defined(BOTAN_TARGET_OS_HAS_THREADS)\n Test::Result test_threaded_fork()\n {\n Test::Result result(\"Threaded_Fork\");\n\n Botan::Pipe pipe(new Botan::Threaded_Fork(new Botan::Hex_Encoder,\n new Botan::Base64_Encoder));\n\n result.test_eq(\"Message count\", pipe.message_count(), 0);\n pipe.process_msg(\"woo\");\n result.test_eq(\"Message count\", pipe.message_count(), 2);\n\n \/\/ Test reading out of order\n result.test_eq(\"Hash 2\", pipe.read_all_as_string(1), \"d29v\");\n result.test_eq(\"Hash 1\", pipe.read_all_as_string(0), \"776F6F\");\n\n pipe.reset();\n\n const size_t filter_count = 5;\n Botan::Filter* filters[filter_count];\n for(size_t i = 0; i != filter_count; ++i)\n filters[i] = new Botan::Hash_Filter(\"SHA-256\");\n\n pipe.append(new Botan::Threaded_Fork(filters, filter_count));\n\n result.test_eq(\"Message count before start_msg\", pipe.message_count(), 2);\n\n pipe.start_msg();\n for(size_t i = 0; i != 919; ++i)\n {\n std::vector<uint8_t> input(i + 5, static_cast<uint8_t>(i));\n pipe.write(input);\n }\n pipe.end_msg();\n\n result.test_eq(\"Message count after end_msg\", pipe.message_count(), 2+filter_count);\n for(size_t i = 0; i != filter_count; ++i)\n result.test_eq(\"Output \" + std::to_string(i),\n pipe.read_all(2+i),\n \"327AD8055223F5926693D8BEA40F7B35BDEEB535647DFB93F464E40EA01939A9\");\n\n return result;\n }\n#endif\n\n };\n\nBOTAN_REGISTER_TEST(\"filter\", Filter_Tests);\n\n#endif\n\n}\n<commit_msg>Re-enable the Threaded Fork test<commit_after>\/*\n* (C) 2016 Daniel Neus\n* 2016 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"tests.h\"\n\n#if defined(BOTAN_HAS_FILTERS)\n #include <botan\/secqueue.h>\n #include <botan\/pipe.h>\n #include <botan\/filters.h>\n #include <botan\/comp_filter.h>\n #include <botan\/cipher_filter.h>\n#endif\n\nnamespace Botan_Tests {\n\n#if defined(BOTAN_HAS_FILTERS)\n\nclass Filter_Tests : public Test\n {\n public:\n std::vector<Test::Result> run() override\n {\n std::vector<Test::Result> results;\n\n results.push_back(test_secqueue());\n results.push_back(test_pipe_hash());\n results.push_back(test_pipe_mac());\n results.push_back(test_pipe_stream());\n results.push_back(test_pipe_cipher());\n results.push_back(test_pipe_compress());\n results.push_back(test_pipe_codec());\n results.push_back(test_fork());\n\n#if defined(BOTAN_TARGET_OS_HAS_THREADS)\n \/\/ Threaded_Fork is broken\n results.push_back(test_threaded_fork());\n#endif\n\n return results;\n }\n\n private:\n Test::Result test_secqueue()\n {\n Test::Result result(\"SecureQueue\");\n\n try\n {\n Botan::SecureQueue queue_a;\n std::vector<uint8_t> test_data = {0x24, 0xB2, 0xBF, 0xC2, 0xE6, 0xD4, 0x7E, 0x04, 0x67, 0xB3};\n queue_a.write(test_data.data(), test_data.size());\n\n result.test_eq(\"size of SecureQueue is correct\", queue_a.size(), test_data.size());\n result.test_eq(\"0 bytes read so far from SecureQueue\", queue_a.get_bytes_read(), 0);\n\n uint8_t b;\n size_t bytes_read = queue_a.read_byte(b);\n result.test_eq(\"1 byte read\", bytes_read, 1);\n\n Botan::secure_vector<uint8_t> produced(b);\n Botan::secure_vector<uint8_t> expected(test_data.at(0));\n result.test_eq(\"byte read is correct\", produced, expected);\n\n result.test_eq(\"1 bytes read so far from SecureQueue\", queue_a.get_bytes_read(), 1);\n\n Botan::SecureQueue queue_b;\n queue_a = queue_b;\n result.test_eq(\"bytes_read is set correctly\", queue_a.get_bytes_read(), 0);\n }\n catch (std::exception& e)\n {\n result.test_failure(\"SecureQueue\", e.what());\n }\n\n return result;\n }\n\n Test::Result test_pipe_mac()\n {\n Test::Result result(\"Pipe\");\n const Botan::SymmetricKey key(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n Botan::Pipe pipe(new Botan::MAC_Filter(\"HMAC(SHA-256)\", key, 12),\n new Botan::Base64_Encoder);\n\n pipe.process_msg(\"Hi\");\n pipe.process_msg(\"Bye\");\n pipe.process_msg(\"Hi\");\n\n result.test_eq(\"MAC 1\", pipe.read_all_as_string(0), \"e7NoVbtudgU0QiCZ\");\n result.test_eq(\"MAC 2\", pipe.read_all_as_string(1), \"LhPnfEG+0rk+Ej6y\");\n result.test_eq(\"MAC 3\", pipe.read_all_as_string(2), \"e7NoVbtudgU0QiCZ\");\n\n return result;\n }\n\n Test::Result test_pipe_hash()\n {\n Test::Result result(\"Pipe\");\n Botan::Pipe pipe(new Botan::Hash_Filter(\"SHA-224\"));\n pipe.pop();\n pipe.append(new Botan::Hash_Filter(\"SHA-256\"));\n\n result.test_eq(\"Message count\", pipe.message_count(), 0);\n\n pipe.start_msg();\n uint8_t inb = 0x41;\n pipe.write(&inb, 1);\n pipe.write(std::vector<uint8_t>(6, 0x41));\n pipe.write(inb);\n pipe.end_msg();\n\n result.test_eq(\"Message count\", pipe.message_count(), 1);\n result.test_eq(\"Message size\", pipe.remaining(), 32);\n\n std::vector<uint8_t> out(32), last16(16);\n\n result.test_eq(\"Bytes read\", pipe.get_bytes_read(0), 0);\n result.test_eq(\"Expected read count\", pipe.read(&out[0], 5), 5);\n result.test_eq(\"Bytes read\", pipe.get_bytes_read(0), 5);\n result.test_eq(\"Peek read\", pipe.peek(last16.data(), 18, 11), 16);\n result.test_eq(\"Expected read count\", pipe.read(&out[5], 17), 17);\n result.test_eq(\"Bytes read\", pipe.get_bytes_read(0), 22);\n result.test_eq(\"Remaining\", pipe.remaining(), 10);\n result.test_eq(\"Remaining\", pipe.remaining(), 10);\n result.test_eq(\"Expected read count\", pipe.read(&out[22], 12), 10);\n result.test_eq(\"Expected read count\", pipe.read(&out[0], 1), 0); \/\/ no more output\n result.test_eq(\"Bytes read\", pipe.get_bytes_read(0), 32);\n\n result.test_eq(\"Expected output\", out, \"C34AB6ABB7B2BB595BC25C3B388C872FD1D575819A8F55CC689510285E212385\");\n result.test_eq(\"Expected last16\", last16, \"D1D575819A8F55CC689510285E212385\");\n\n pipe.reset();\n\n#if defined(BOTAN_HAS_CRC32)\n pipe.prepend(new Botan::Hash_Filter(\"CRC32\"));\n pipe.append(new Botan::Hash_Filter(\"CRC32\"));\n pipe.process_msg(std::vector<byte>(1024, 0));\n result.test_eq(\"Expected CRC32d\", pipe.read_all(1), \"99841F60\");\n#endif\n\n return result;\n }\n\n Test::Result test_pipe_cipher()\n {\n Test::Result result(\"Pipe\");\n\n Botan::Cipher_Mode_Filter* cipher =\n new Botan::Cipher_Mode_Filter(Botan::get_cipher_mode(\"AES-128\/CBC\/PKCS7\", Botan::ENCRYPTION));\n\n \/\/ takes ownership of cipher\n Botan::Pipe pipe(cipher);\n\n cipher->set_key(Botan::SymmetricKey(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"));\n cipher->set_iv(Botan::InitializationVector(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"));\n\n pipe.process_msg(\"Don't use plain CBC mode\");\n\n auto ciphertext = pipe.read_all();\n\n result.test_eq(\"Ciphertext\", ciphertext, \"9BDD7300E0CB61CA71FFF957A71605DB6836159C36781246A1ADF50982757F4B\");\n\n Botan::Cipher_Mode_Filter* dec_cipher =\n new Botan::Cipher_Mode_Filter(Botan::get_cipher_mode(\"AES-128\/CBC\/PKCS7\", Botan::DECRYPTION));\n pipe.append(dec_cipher);\n dec_cipher->set_key(Botan::SymmetricKey(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"));\n dec_cipher->set_iv(Botan::InitializationVector(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB\"));\n cipher->set_iv(Botan::InitializationVector(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB\"));\n\n const std::vector<byte> zeros_in(1024);\n Botan::DataSource_Memory src(zeros_in);\n pipe.start_msg();\n pipe.write(src);\n pipe.end_msg();\n\n Botan::secure_vector<byte> zeros_out = pipe.read_all(1);\n\n result.test_eq(\"Cipher roundtrip\", zeros_in, zeros_out);\n return result;\n }\n\n Test::Result test_pipe_compress()\n {\n Test::Result result(\"Pipe\");\n\n#if defined(BOTAN_HAS_ZLIB)\n Botan::Pipe pipe(new Botan::Compression_Filter(\"zlib\", 9));\n\n const std::string input_str = \"Hello there HELLO there I said is this thing on?\";\n\n pipe.start_msg();\n pipe.write(input_str);\n pipe.end_msg();\n\n auto compr = pipe.read_all(0);\n \/\/ Can't do equality check on compression because output may differ\n result.test_lt(\"Compressed is shorter\", compr.size(), input_str.size());\n\n pipe.append(new Botan::Decompression_Filter(\"zlib\"));\n pipe.pop(); \/\/ remove compressor\n\n pipe.process_msg(compr);\n\n std::string decomp = pipe.read_all_as_string(1);\n result.test_eq(\"Decompressed ok\", decomp, input_str);\n#endif\n\n return result;\n }\n\n Test::Result test_pipe_codec()\n {\n Test::Result result(\"Pipe\");\n\n Botan::Pipe pipe(new Botan::Base64_Encoder);\n\n result.test_eq(\"Message count\", pipe.message_count(), 0);\n\n pipe.process_msg(\"ABCDX\");\n\n result.test_eq(\"Message count\", pipe.message_count(), 1);\n result.test_eq(\"Message size\", pipe.remaining(), 8);\n\n std::string output = pipe.read_all_as_string(0);\n result.test_eq(\"Message size\", pipe.remaining(0), 0);\n result.test_eq(\"Output round tripped\", output, \"QUJDRFg=\");\n\n pipe.append(new Botan::Base64_Decoder);\n pipe.process_msg(\"FOOBAZ\");\n\n result.test_eq(\"base64 roundtrip\", pipe.read_all_as_string(1), \"FOOBAZ\");\n\n pipe.pop();\n pipe.pop();\n\n \/\/ Pipe is empty of filters, should still pass through\n pipe.process_msg(\"surprise plaintext\");\n\n pipe.set_default_msg(2);\n result.test_eq(\"Message 2\", pipe.read_all_as_string(), \"surprise plaintext\");\n\n pipe.append(new Botan::Hex_Decoder);\n\n pipe.process_msg(\"F331F00D\");\n Botan::secure_vector<uint8_t> bin = pipe.read_all(3);\n result.test_eq(\"hex decoded\", bin, \"F331F00D\");\n\n pipe.append(new Botan::Hex_Encoder);\n pipe.process_msg(\"F331F00D\");\n result.test_eq(\"hex roundtrip\", pipe.read_all_as_string(4), \"F331F00D\");\n\n return result;\n }\n\n Test::Result test_pipe_stream()\n {\n Test::Result result(\"Pipe\");\n\n Botan::Keyed_Filter* aes = nullptr;\n const Botan::SymmetricKey key(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n const Botan::InitializationVector iv(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n Botan::Pipe pipe(aes = new Botan::StreamCipher_Filter(\"CTR-BE(AES-128)\", key));\n\n aes->set_iv(iv);\n\n pipe.process_msg(\"ABCDEF\");\n\n result.test_eq(\"Message count\", pipe.message_count(), 1);\n result.test_eq(\"Ciphertext\", pipe.read_all(), \"FDFD6238F7C6\");\n return result;\n }\n\n Test::Result test_fork()\n {\n Test::Result result(\"Fork\");\n\n Botan::Pipe pipe(new Botan::Fork(new Botan::Hash_Filter(\"SHA-256\"),\n new Botan::Hash_Filter(\"SHA-512-256\")));\n\n result.test_eq(\"Message count\", pipe.message_count(), 0);\n pipe.process_msg(\"OMG\");\n result.test_eq(\"Message count\", pipe.message_count(), 2);\n\n \/\/ Test reading out of order\n result.test_eq(\"Hash 2\", pipe.read_all(1), \"610480FFA82F24F6926544B976FE387878E3D973C03DFD591C2E9896EFB903E0\");\n result.test_eq(\"Hash 1\", pipe.read_all(0), \"C00862D1C6C1CF7C1B49388306E7B3C1BB79D8D6EC978B41035B556DBB3797DF\");\n\n return result;\n\n }\n\n#if defined(BOTAN_TARGET_OS_HAS_THREADS)\n Test::Result test_threaded_fork()\n {\n Test::Result result(\"Threaded_Fork\");\n\n Botan::Pipe pipe(new Botan::Threaded_Fork(new Botan::Hex_Encoder,\n new Botan::Base64_Encoder));\n\n result.test_eq(\"Message count\", pipe.message_count(), 0);\n pipe.process_msg(\"woo\");\n result.test_eq(\"Message count\", pipe.message_count(), 2);\n\n \/\/ Test reading out of order\n result.test_eq(\"Hash 2\", pipe.read_all_as_string(1), \"d29v\");\n result.test_eq(\"Hash 1\", pipe.read_all_as_string(0), \"776F6F\");\n\n pipe.reset();\n\n const size_t filter_count = 5;\n Botan::Filter* filters[filter_count];\n for(size_t i = 0; i != filter_count; ++i)\n filters[i] = new Botan::Hash_Filter(\"SHA-256\");\n\n pipe.append(new Botan::Threaded_Fork(filters, filter_count));\n\n result.test_eq(\"Message count before start_msg\", pipe.message_count(), 2);\n\n pipe.start_msg();\n for(size_t i = 0; i != 919; ++i)\n {\n std::vector<uint8_t> input(i + 5, static_cast<uint8_t>(i));\n pipe.write(input);\n }\n pipe.end_msg();\n\n result.test_eq(\"Message count after end_msg\", pipe.message_count(), 2+filter_count);\n for(size_t i = 0; i != filter_count; ++i)\n result.test_eq(\"Output \" + std::to_string(i),\n pipe.read_all(2+i),\n \"327AD8055223F5926693D8BEA40F7B35BDEEB535647DFB93F464E40EA01939A9\");\n\n return result;\n }\n#endif\n\n };\n\nBOTAN_REGISTER_TEST(\"filter\", Filter_Tests);\n\n#endif\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file posix\/wait.cpp\n * @brief POSIX event\/timeout handling\n *\n * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK 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 * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\n * This file is also distributed under the terms of the GNU General\n * Public License, see http:\/\/www.gnu.org\/copyleft\/gpl.txt for details.\n *\/\n\n#include \"mega\/thread\/posixthread.h\"\n#include \"mega\/logging.h\"\n#include <sys\/time.h>\n#include <errno.h>\n\n#ifdef USE_PTHREAD\n#if defined (__MINGW32__) && !defined(__struct_timespec_defined)\nstruct timespec\n{\n long long\ttv_sec; \t\/* seconds *\/\n long \ttv_nsec;\t\/* nanoseconds *\/\n};\n# define __struct_timespec_defined 1\n#endif\n\nnamespace mega {\n\nPosixThread::PosixThread()\n{\n thread = new pthread_t();\n}\n\nvoid PosixThread::start(void *(*start_routine)(void*), void *parameter)\n{\n pthread_create(thread, NULL, start_routine, parameter);\n}\n\nvoid PosixThread::join()\n{\n pthread_join(*thread, NULL);\n}\n\nunsigned long long PosixThread::currentThreadId()\n{\n#if defined(_WIN32) && !defined(__WINPTHREADS_VERSION)\n return (unsigned long long) pthread_self().x;\n#else\n return (unsigned long long) pthread_self();\n#endif\n}\n\nPosixThread::~PosixThread()\n{\n delete thread;\n}\n\n\/\/PosixMutex\nPosixMutex::PosixMutex()\n{\n mutex = NULL;\n attr = NULL;\n}\n\nPosixMutex::PosixMutex(bool recursive)\n{\n mutex = NULL;\n attr = NULL;\n\n init(recursive);\n}\n\nvoid PosixMutex::init(bool recursive)\n{\n if (recursive)\n {\n mutex = new pthread_mutex_t();\n attr = new pthread_mutexattr_t();\n pthread_mutexattr_init(attr);\n pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE);\n pthread_mutex_init(mutex, attr);\n }\n else\n {\n mutex = new pthread_mutex_t();\n pthread_mutex_init(mutex, NULL);\n }\n}\n\nvoid PosixMutex::lock()\n{\n pthread_mutex_lock(mutex);\n}\n\nvoid PosixMutex::unlock()\n{\n pthread_mutex_unlock(mutex);\n}\n\nPosixMutex::~PosixMutex()\n{\n if (mutex)\n {\n pthread_mutex_destroy(mutex);\n delete mutex;\n }\n\n if (attr)\n {\n pthread_mutexattr_destroy(attr);\n delete attr;\n }\n}\n\n\/\/PosixSemaphore\nPosixSemaphore::PosixSemaphore()\n{\n count = 0;\n pthread_mutexattr_t attr;\n pthread_mutexattr_init(&attr);\n pthread_mutex_init(&mtx, &attr);\n pthread_mutexattr_destroy(&attr);\n pthread_cond_init(&cv, NULL);\n}\n\nvoid PosixSemaphore::wait()\n{\n pthread_mutex_lock(&mtx);\n while (!count)\n {\n int ret = pthread_cond_wait(&cv,&mtx);\n if (ret)\n {\n pthread_mutex_unlock(&mtx);\n LOG_fatal << \"Error in sem_wait: \" << ret;\n return;\n }\n }\n count--;\n pthread_mutex_unlock(&mtx);\n}\n\nstatic inline\nvoid timespec_add_msec(struct timespec *tv, int milliseconds)\n{\n int seconds = milliseconds \/ 1000;\n int milliseconds_left = milliseconds % 1000;\n\n tv->tv_sec += seconds;\n tv->tv_nsec += milliseconds_left * 1000000;\n\n if (tv->tv_nsec >= 1000000000)\n {\n tv->tv_nsec -= 1000000000;\n tv->tv_sec++;\n }\n}\n\nint PosixSemaphore::timedwait(int milliseconds)\n{\n struct timespec ts;\n struct timeval now;\n\n int ret = gettimeofday(&now, NULL); \/\/not Y2K38 safe :-D\n if (ret)\n {\n LOG_err << \"Error in gettimeofday: \" << ret;\n return -2;\n }\n ts.tv_sec = now.tv_sec;\n ts.tv_nsec = now.tv_usec * 1000;\n timespec_add_msec (&ts, milliseconds);\n\n pthread_mutex_lock(&mtx);\n while (!count)\n {\n int ret = pthread_cond_timedwait(&cv, &mtx, &ts);\n if (ret == ETIMEDOUT)\n {\n pthread_mutex_unlock(&mtx);\n return -1;\n }\n\n if (ret)\n {\n pthread_mutex_unlock(&mtx);\n LOG_err << \"Unexpected error in pthread_cond_timedwait: \" << ret;\n return -2;\n }\n }\n\n count--;\n pthread_mutex_unlock(&mtx);\n return 0;\n}\n\nvoid PosixSemaphore::release()\n{\n pthread_mutex_lock(&mtx);\n count++;\n int ret = pthread_cond_signal(&cv);\n if (ret)\n {\n LOG_fatal << \"Unexpected error in pthread_cond_signal: \" << ret;\n }\n pthread_mutex_unlock(&mtx);\n}\n\nPosixSemaphore::~PosixSemaphore()\n{\n pthread_mutex_destroy(&mtx);\n pthread_cond_destroy(&cv);\n}\n\n}\/\/ namespace\n\n#endif\n<commit_msg>posixthread: fix duplicate define of time_spec on mingw-w64 with posix<commit_after>\/**\n * @file posix\/wait.cpp\n * @brief POSIX event\/timeout handling\n *\n * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK 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 * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\n * This file is also distributed under the terms of the GNU General\n * Public License, see http:\/\/www.gnu.org\/copyleft\/gpl.txt for details.\n *\/\n\n#include \"mega\/thread\/posixthread.h\"\n#include \"mega\/logging.h\"\n#include <sys\/time.h>\n#include <errno.h>\n\n#ifdef USE_PTHREAD\n\/\/ Apparently this is defined by pthread.h, if that header had been included.\n\/\/ __struct_timespec_defined is defined in time.h for MinGW on Windows\n#if defined (__MINGW32__) && !defined(_TIMESPEC_DEFINED) && ! __struct_timespec_defined\nstruct timespec\n{\n long long\ttv_sec; \t\/* seconds *\/\n long \ttv_nsec;\t\/* nanoseconds *\/\n};\n# define __struct_timespec_defined 1\n#endif\n\nnamespace mega {\n\nPosixThread::PosixThread()\n{\n thread = new pthread_t();\n}\n\nvoid PosixThread::start(void *(*start_routine)(void*), void *parameter)\n{\n pthread_create(thread, NULL, start_routine, parameter);\n}\n\nvoid PosixThread::join()\n{\n pthread_join(*thread, NULL);\n}\n\nunsigned long long PosixThread::currentThreadId()\n{\n#if defined(_WIN32) && !defined(__WINPTHREADS_VERSION)\n return (unsigned long long) pthread_self().x;\n#else\n return (unsigned long long) pthread_self();\n#endif\n}\n\nPosixThread::~PosixThread()\n{\n delete thread;\n}\n\n\/\/PosixMutex\nPosixMutex::PosixMutex()\n{\n mutex = NULL;\n attr = NULL;\n}\n\nPosixMutex::PosixMutex(bool recursive)\n{\n mutex = NULL;\n attr = NULL;\n\n init(recursive);\n}\n\nvoid PosixMutex::init(bool recursive)\n{\n if (recursive)\n {\n mutex = new pthread_mutex_t();\n attr = new pthread_mutexattr_t();\n pthread_mutexattr_init(attr);\n pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE);\n pthread_mutex_init(mutex, attr);\n }\n else\n {\n mutex = new pthread_mutex_t();\n pthread_mutex_init(mutex, NULL);\n }\n}\n\nvoid PosixMutex::lock()\n{\n pthread_mutex_lock(mutex);\n}\n\nvoid PosixMutex::unlock()\n{\n pthread_mutex_unlock(mutex);\n}\n\nPosixMutex::~PosixMutex()\n{\n if (mutex)\n {\n pthread_mutex_destroy(mutex);\n delete mutex;\n }\n\n if (attr)\n {\n pthread_mutexattr_destroy(attr);\n delete attr;\n }\n}\n\n\/\/PosixSemaphore\nPosixSemaphore::PosixSemaphore()\n{\n count = 0;\n pthread_mutexattr_t attr;\n pthread_mutexattr_init(&attr);\n pthread_mutex_init(&mtx, &attr);\n pthread_mutexattr_destroy(&attr);\n pthread_cond_init(&cv, NULL);\n}\n\nvoid PosixSemaphore::wait()\n{\n pthread_mutex_lock(&mtx);\n while (!count)\n {\n int ret = pthread_cond_wait(&cv,&mtx);\n if (ret)\n {\n pthread_mutex_unlock(&mtx);\n LOG_fatal << \"Error in sem_wait: \" << ret;\n return;\n }\n }\n count--;\n pthread_mutex_unlock(&mtx);\n}\n\nstatic inline\nvoid timespec_add_msec(struct timespec *tv, int milliseconds)\n{\n int seconds = milliseconds \/ 1000;\n int milliseconds_left = milliseconds % 1000;\n\n tv->tv_sec += seconds;\n tv->tv_nsec += milliseconds_left * 1000000;\n\n if (tv->tv_nsec >= 1000000000)\n {\n tv->tv_nsec -= 1000000000;\n tv->tv_sec++;\n }\n}\n\nint PosixSemaphore::timedwait(int milliseconds)\n{\n struct timespec ts;\n struct timeval now;\n\n int ret = gettimeofday(&now, NULL); \/\/not Y2K38 safe :-D\n if (ret)\n {\n LOG_err << \"Error in gettimeofday: \" << ret;\n return -2;\n }\n ts.tv_sec = now.tv_sec;\n ts.tv_nsec = now.tv_usec * 1000;\n timespec_add_msec (&ts, milliseconds);\n\n pthread_mutex_lock(&mtx);\n while (!count)\n {\n int ret = pthread_cond_timedwait(&cv, &mtx, &ts);\n if (ret == ETIMEDOUT)\n {\n pthread_mutex_unlock(&mtx);\n return -1;\n }\n\n if (ret)\n {\n pthread_mutex_unlock(&mtx);\n LOG_err << \"Unexpected error in pthread_cond_timedwait: \" << ret;\n return -2;\n }\n }\n\n count--;\n pthread_mutex_unlock(&mtx);\n return 0;\n}\n\nvoid PosixSemaphore::release()\n{\n pthread_mutex_lock(&mtx);\n count++;\n int ret = pthread_cond_signal(&cv);\n if (ret)\n {\n LOG_fatal << \"Unexpected error in pthread_cond_signal: \" << ret;\n }\n pthread_mutex_unlock(&mtx);\n}\n\nPosixSemaphore::~PosixSemaphore()\n{\n pthread_mutex_destroy(&mtx);\n pthread_cond_destroy(&cv);\n}\n\n}\/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.\n#include \"stdafx.h\"\n#include <autowiring\/config_descriptor.h>\n#include <autowiring\/config.h>\n#include <autowiring\/ConfigRegistry.h>\n#include <autowiring\/observable.h>\n\nnamespace aw = autowiring;\n\nclass AutoConfigTest:\n public testing::Test\n{};\n\nnamespace {\n class multi_meta {\n public:\n static const bool multi = true;\n\n std::string name;\n\n template<typename T>\n void bind(const aw::config_field& field, T&) {\n name = field.name;\n }\n };\n\n static_assert(aw::valid<int, multi_meta>::value, \"Float metadata field not detected as being valid\");\n\n class single_meta {\n public:\n single_meta(const char* name) :\n name(name)\n {}\n\n const char* name;\n static const bool multi = false;\n };\n\n class MyConfigurableClass {\n public:\n autowiring::config<std::string> a{ \"Hello world!\" };\n std::atomic<int> b{ 929 };\n std::atomic<unsigned int> bUnsigned{ 92999 };\n volatile bool c = false;\n volatile float d = 1.0f;\n volatile double e = 99.2;\n autowiring::observable<int> obs{ 44 };\n autowiring::config<int> cfg{ 929999 };\n\n static autowiring::config_descriptor GetConfigDescriptor(void) {\n return {\n { \"a\", \"Field A description\", &MyConfigurableClass::a, \"Hello world!\" },\n { \"b\", \"Field B description\", &MyConfigurableClass::b, 929, aw::bounds<int>{ 0, 1000 }, multi_meta{}, multi_meta{} },\n { \"bUnsigned\", \"Description\", &MyConfigurableClass::bUnsigned, 4444, single_meta{\"Hello world!\"} },\n { \"c\", &MyConfigurableClass::c },\n { \"d\", &MyConfigurableClass::d },\n { \"e\", &MyConfigurableClass::e },\n { \"obs\", &MyConfigurableClass::obs },\n { \"cfg\", &MyConfigurableClass::cfg }\n };\n }\n };\n\n class BadClass {\n public:\n autowiring::config_descriptor GetConfigDescriptor(void) { return{}; }\n };\n}\n\nstatic_assert(!aw::is_multi<aw::bounds<int>>::value, \"Bounds should not have been marked as a multi-select type\");\nstatic_assert(!aw::is_multi<single_meta>::value, \"Single metadata type incorrectly detected as supporting multiple instantiations\");\nstatic_assert(aw::is_multi<multi_meta>::value, \"Multi metadata type not correctly detecting as supporting multiple instantiations\");\nstatic_assert(aw::has_getconfigdescriptor<MyConfigurableClass>::value, \"Static new not correctly detected\");\nstatic_assert(!aw::has_getconfigdescriptor<BadClass>::value, \"Bad class cannot have a configuration descriptor\");\nstatic_assert(!aw::has_bind<aw::bounds<int>, int>::value, \"Bind incorrectly detected on bounds field\");\nstatic_assert(aw::has_contextual_bind<multi_meta, int>::value, \"Contextual bind not detected on multimeta type\");\n\nTEST_F(AutoConfigTest, ConfigFieldAssign) {\n autowiring::config<std::string> x{ \"Hello world!\" };\n ASSERT_TRUE(x.is_dirty()) << \"Config values are assumed to be initially dirty\";\n}\n\nTEST_F(AutoConfigTest, String) {\n MyConfigurableClass c;\n\n std::string expected{ \"Forescore and seven years ago\" };\n autowiring::ConfigSet(\"a\", c, expected.c_str());\n ASSERT_TRUE(c.a.clear_dirty());\n ASSERT_STREQ(expected.c_str(), c.a->c_str()) << \"String configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, Integer) {\n MyConfigurableClass c;\n\n autowiring::ConfigSet(\"b\", c, \"999\");\n ASSERT_EQ(c.b, 999) << \"Integer configuration value not assigned\";\n\n autowiring::ConfigSet(\"b\", c, \"-999\");\n ASSERT_EQ(c.b, -999) << \"Negative integer configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, IntegerUnsigned) {\n MyConfigurableClass c;\n\n c.bUnsigned = 10929;\n std::string strVal = autowiring::ConfigGet(\"bUnsigned\", c);\n ASSERT_STREQ(\"10929\", strVal.c_str());\n\n autowiring::ConfigSet(\"bUnsigned\", c, \"999\");\n ASSERT_EQ(c.bUnsigned, 999) << \"Integer configuration value not assigned\";\n ASSERT_ANY_THROW(autowiring::ConfigSet(\"bUnsigned\", c, \"-999\")) << \"Incorrectly assigned as signed value to an unsigned field\";\n}\n\nTEST_F(AutoConfigTest, Bool) {\n MyConfigurableClass c;\n\n autowiring::ConfigSet(\"c\", c, \"true\");\n ASSERT_TRUE(c.c) << \"Boolean configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, Float) {\n MyConfigurableClass c;\n\n c.d = 10929.4f;\n std::string strVal = autowiring::ConfigGet(\"d\", c);\n ASSERT_STREQ(\"10929.4\", strVal.c_str());\n\n autowiring::ConfigSet(\"d\", c, \"123.4\");\n ASSERT_FLOAT_EQ(c.d, 123.4f) << \"Float configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, Double) {\n MyConfigurableClass c;\n std::string strVal;\n\n c.e = 10929.4423;\n strVal = autowiring::ConfigGet(\"e\", c);\n ASSERT_STREQ(\"10929.4423\", strVal.c_str());\n\n c.e = 109290000000000;\n strVal = autowiring::ConfigGet(\"e\", c);\n ASSERT_STREQ(\"109290000000000\", strVal.c_str());\n\n c.e = -0.0099291;\n strVal = autowiring::ConfigGet(\"e\", c);\n ASSERT_STREQ(\"-0.0099291\", strVal.c_str());\n\n autowiring::ConfigSet(\"e\", c, \"77482.4\");\n ASSERT_DOUBLE_EQ(c.e, 77482.4) << \"Double configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, Observable) {\n MyConfigurableClass c;\n\n bool hit = false;\n c.obs.onChanged += [&hit] { hit = true; };\n autowiring::ConfigSet(\"obs\", c, \"101\");\n ASSERT_EQ(101, c.obs) << \"Value not properly assigned\";\n ASSERT_TRUE(hit) << \"Observable signal not asserted\";\n}\n\nTEST_F(AutoConfigTest, Configurable) {\n AutoCurrentContext ctxt;\n AutoRequired<MyConfigurableClass> c;\n\n ASSERT_TRUE(c->cfg.clear_dirty()) << \"Dirty flag was not set on a value that should have been dirty\";\n ASSERT_FALSE(c->cfg.is_dirty());\n ctxt->Config.Set(\"cfg\", \"888\");\n ASSERT_TRUE(c->cfg.is_dirty()) << \"Dirty flag not set correctly after being updated in configuration\";\n ASSERT_TRUE(c->cfg.clear_dirty());\n ASSERT_EQ(888, c->cfg);\n}\n\nTEST_F(AutoConfigTest, ContextSetSimple) {\n AutoCurrentContext ctxt;\n AutoRequired<MyConfigurableClass> mcc;\n\n ctxt->Config.Set(\"b\", \"1029\");\n ASSERT_EQ(mcc->b, 1029);\n}\n\nTEST_F(AutoConfigTest, ContextSetAfter) {\n AutoCurrentContext ctxt;\n ctxt->Config.Set(\"b\", \"10442\");\n\n AutoRequired<MyConfigurableClass> mcc;\n ASSERT_EQ(mcc->b, 10442);\n}\n\nnamespace {\n class slider\n {\n public:\n template<typename U>\n struct valid {\n static const bool value = std::is_arithmetic<U>::value;\n };\n };\n\n static_assert(aw::valid<float, slider>::value, \"Float metadata field not detected as being valid\");\n static_assert(!std::is_arithmetic<std::string>::value, \"Strings are not arithmetic\");\n static_assert(!slider::valid<std::string>::value, \"Slider should not believe strings are valid\");\n static_assert(!aw::valid<std::string, slider>::value, \"String metadata field incorrectly detected as being valid\");\n\n class SliderManager {\n public:\n SliderManager(void) {\n AutoCurrentContext ctxt;\n ctxt->Config.When(\n [this] (const aw::config_field& field, const slider& slider) {\n sliderReg.push_back(slider);\n }\n );\n }\n\n std::vector<slider> sliderReg;\n };\n\n class ClassWithBoundsField {\n public:\n std::atomic<int> b{ 929 };\n\n static autowiring::config_descriptor GetConfigDescriptor(void) {\n return{\n aw::config_field { \"b\", \"Field B description\", &ClassWithBoundsField::b, 929, slider{}, aw::bounds<int>{ 10, 423 } },\n };\n }\n };\n}\n\nTEST_F(AutoConfigTest, OpenRegistry) {\n AutoRequired<SliderManager> mgr;\n AutoRequired<ClassWithBoundsField> cwbf;\n\n ASSERT_EQ(1UL, mgr->sliderReg.size()) << \"Slider registration count did not match expectatiosn\";\n}\n<commit_msg>Fix transposed letters<commit_after>\/\/ Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.\n#include \"stdafx.h\"\n#include <autowiring\/config_descriptor.h>\n#include <autowiring\/config.h>\n#include <autowiring\/ConfigRegistry.h>\n#include <autowiring\/observable.h>\n\nnamespace aw = autowiring;\n\nclass AutoConfigTest:\n public testing::Test\n{};\n\nnamespace {\n class multi_meta {\n public:\n static const bool multi = true;\n\n std::string name;\n\n template<typename T>\n void bind(const aw::config_field& field, T&) {\n name = field.name;\n }\n };\n\n static_assert(aw::valid<int, multi_meta>::value, \"Float metadata field not detected as being valid\");\n\n class single_meta {\n public:\n single_meta(const char* name) :\n name(name)\n {}\n\n const char* name;\n static const bool multi = false;\n };\n\n class MyConfigurableClass {\n public:\n autowiring::config<std::string> a{ \"Hello world!\" };\n std::atomic<int> b{ 929 };\n std::atomic<unsigned int> bUnsigned{ 92999 };\n volatile bool c = false;\n volatile float d = 1.0f;\n volatile double e = 99.2;\n autowiring::observable<int> obs{ 44 };\n autowiring::config<int> cfg{ 929999 };\n\n static autowiring::config_descriptor GetConfigDescriptor(void) {\n return {\n { \"a\", \"Field A description\", &MyConfigurableClass::a, \"Hello world!\" },\n { \"b\", \"Field B description\", &MyConfigurableClass::b, 929, aw::bounds<int>{ 0, 1000 }, multi_meta{}, multi_meta{} },\n { \"bUnsigned\", \"Description\", &MyConfigurableClass::bUnsigned, 4444, single_meta{\"Hello world!\"} },\n { \"c\", &MyConfigurableClass::c },\n { \"d\", &MyConfigurableClass::d },\n { \"e\", &MyConfigurableClass::e },\n { \"obs\", &MyConfigurableClass::obs },\n { \"cfg\", &MyConfigurableClass::cfg }\n };\n }\n };\n\n class BadClass {\n public:\n autowiring::config_descriptor GetConfigDescriptor(void) { return{}; }\n };\n}\n\nstatic_assert(!aw::is_multi<aw::bounds<int>>::value, \"Bounds should not have been marked as a multi-select type\");\nstatic_assert(!aw::is_multi<single_meta>::value, \"Single metadata type incorrectly detected as supporting multiple instantiations\");\nstatic_assert(aw::is_multi<multi_meta>::value, \"Multi metadata type not correctly detecting as supporting multiple instantiations\");\nstatic_assert(aw::has_getconfigdescriptor<MyConfigurableClass>::value, \"Static new not correctly detected\");\nstatic_assert(!aw::has_getconfigdescriptor<BadClass>::value, \"Bad class cannot have a configuration descriptor\");\nstatic_assert(!aw::has_bind<aw::bounds<int>, int>::value, \"Bind incorrectly detected on bounds field\");\nstatic_assert(aw::has_contextual_bind<multi_meta, int>::value, \"Contextual bind not detected on multimeta type\");\n\nTEST_F(AutoConfigTest, ConfigFieldAssign) {\n autowiring::config<std::string> x{ \"Hello world!\" };\n ASSERT_TRUE(x.is_dirty()) << \"Config values are assumed to be initially dirty\";\n}\n\nTEST_F(AutoConfigTest, String) {\n MyConfigurableClass c;\n\n std::string expected{ \"Forescore and seven years ago\" };\n autowiring::ConfigSet(\"a\", c, expected.c_str());\n ASSERT_TRUE(c.a.clear_dirty());\n ASSERT_STREQ(expected.c_str(), c.a->c_str()) << \"String configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, Integer) {\n MyConfigurableClass c;\n\n autowiring::ConfigSet(\"b\", c, \"999\");\n ASSERT_EQ(c.b, 999) << \"Integer configuration value not assigned\";\n\n autowiring::ConfigSet(\"b\", c, \"-999\");\n ASSERT_EQ(c.b, -999) << \"Negative integer configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, IntegerUnsigned) {\n MyConfigurableClass c;\n\n c.bUnsigned = 10929;\n std::string strVal = autowiring::ConfigGet(\"bUnsigned\", c);\n ASSERT_STREQ(\"10929\", strVal.c_str());\n\n autowiring::ConfigSet(\"bUnsigned\", c, \"999\");\n ASSERT_EQ(c.bUnsigned, 999) << \"Integer configuration value not assigned\";\n ASSERT_ANY_THROW(autowiring::ConfigSet(\"bUnsigned\", c, \"-999\")) << \"Incorrectly assigned as signed value to an unsigned field\";\n}\n\nTEST_F(AutoConfigTest, Bool) {\n MyConfigurableClass c;\n\n autowiring::ConfigSet(\"c\", c, \"true\");\n ASSERT_TRUE(c.c) << \"Boolean configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, Float) {\n MyConfigurableClass c;\n\n c.d = 10929.4f;\n std::string strVal = autowiring::ConfigGet(\"d\", c);\n ASSERT_STREQ(\"10929.4\", strVal.c_str());\n\n autowiring::ConfigSet(\"d\", c, \"123.4\");\n ASSERT_FLOAT_EQ(c.d, 123.4f) << \"Float configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, Double) {\n MyConfigurableClass c;\n std::string strVal;\n\n c.e = 10929.4423;\n strVal = autowiring::ConfigGet(\"e\", c);\n ASSERT_STREQ(\"10929.4423\", strVal.c_str());\n\n c.e = 109290000000000;\n strVal = autowiring::ConfigGet(\"e\", c);\n ASSERT_STREQ(\"109290000000000\", strVal.c_str());\n\n c.e = -0.0099291;\n strVal = autowiring::ConfigGet(\"e\", c);\n ASSERT_STREQ(\"-0.0099291\", strVal.c_str());\n\n autowiring::ConfigSet(\"e\", c, \"77482.4\");\n ASSERT_DOUBLE_EQ(c.e, 77482.4) << \"Double configuration value not assigned\";\n}\n\nTEST_F(AutoConfigTest, Observable) {\n MyConfigurableClass c;\n\n bool hit = false;\n c.obs.onChanged += [&hit] { hit = true; };\n autowiring::ConfigSet(\"obs\", c, \"101\");\n ASSERT_EQ(101, c.obs) << \"Value not properly assigned\";\n ASSERT_TRUE(hit) << \"Observable signal not asserted\";\n}\n\nTEST_F(AutoConfigTest, Configurable) {\n AutoCurrentContext ctxt;\n AutoRequired<MyConfigurableClass> c;\n\n ASSERT_TRUE(c->cfg.clear_dirty()) << \"Dirty flag was not set on a value that should have been dirty\";\n ASSERT_FALSE(c->cfg.is_dirty());\n ctxt->Config.Set(\"cfg\", \"888\");\n ASSERT_TRUE(c->cfg.is_dirty()) << \"Dirty flag not set correctly after being updated in configuration\";\n ASSERT_TRUE(c->cfg.clear_dirty());\n ASSERT_EQ(888, c->cfg);\n}\n\nTEST_F(AutoConfigTest, ContextSetSimple) {\n AutoCurrentContext ctxt;\n AutoRequired<MyConfigurableClass> mcc;\n\n ctxt->Config.Set(\"b\", \"1029\");\n ASSERT_EQ(mcc->b, 1029);\n}\n\nTEST_F(AutoConfigTest, ContextSetAfter) {\n AutoCurrentContext ctxt;\n ctxt->Config.Set(\"b\", \"10442\");\n\n AutoRequired<MyConfigurableClass> mcc;\n ASSERT_EQ(mcc->b, 10442);\n}\n\nnamespace {\n class slider\n {\n public:\n template<typename U>\n struct valid {\n static const bool value = std::is_arithmetic<U>::value;\n };\n };\n\n static_assert(aw::valid<float, slider>::value, \"Float metadata field not detected as being valid\");\n static_assert(!std::is_arithmetic<std::string>::value, \"Strings are not arithmetic\");\n static_assert(!slider::valid<std::string>::value, \"Slider should not believe strings are valid\");\n static_assert(!aw::valid<std::string, slider>::value, \"String metadata field incorrectly detected as being valid\");\n\n class SliderManager {\n public:\n SliderManager(void) {\n AutoCurrentContext ctxt;\n ctxt->Config.When(\n [this] (const aw::config_field& field, const slider& slider) {\n sliderReg.push_back(slider);\n }\n );\n }\n\n std::vector<slider> sliderReg;\n };\n\n class ClassWithBoundsField {\n public:\n std::atomic<int> b{ 929 };\n\n static autowiring::config_descriptor GetConfigDescriptor(void) {\n return{\n aw::config_field { \"b\", \"Field B description\", &ClassWithBoundsField::b, 929, slider{}, aw::bounds<int>{ 10, 423 } },\n };\n }\n };\n}\n\nTEST_F(AutoConfigTest, OpenRegistry) {\n AutoRequired<SliderManager> mgr;\n AutoRequired<ClassWithBoundsField> cwbf;\n\n ASSERT_EQ(1UL, mgr->sliderReg.size()) << \"Slider registration count did not match expectations\";\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pch.h\"\n#include \"axl_err_Error.h\"\n#include \"axl_spy_ImportTableMgr.h\"\n\n#if (_AXL_OS_POSIX)\n#\tinclude \"axl_sys_psx_DynamicLib.h\"\n#\tinclude <link.h>\n#endif\n\nnamespace axl {\nnamespace spy {\n\n\/\/..............................................................................\n\n#if (_AXL_OS_WIN)\n\nsize_t\nImportTableMgr::enumerateImports(void* module)\n{\n\tif (!module)\n\t\tmodule = ::GetModuleHandle(NULL);\n\n\tchar* moduleBase = (char*)module;\n\n\tIMAGE_DOS_HEADER* dosHdr = (IMAGE_DOS_HEADER*)moduleBase;\n\tif (dosHdr->e_magic != IMAGE_DOS_SIGNATURE)\n\t{\n\t\terr::setError(\"invalid module (bad DOS signature)\");\n\t\treturn -1;\n\t}\n\n\tIMAGE_NT_HEADERS* peHdr = (IMAGE_NT_HEADERS*)(moduleBase + dosHdr->e_lfanew);\n\tif (peHdr->Signature != IMAGE_NT_SIGNATURE)\n\t{\n\t\terr::setError(\"invalid module (bad PE signature)\");\n\t\treturn -1;\n\t}\n\n\tIMAGE_DATA_DIRECTORY* importDir = (IMAGE_DATA_DIRECTORY*)&peHdr->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];\n\tIMAGE_IMPORT_DESCRIPTOR* p = (IMAGE_IMPORT_DESCRIPTOR*)(moduleBase + importDir->VirtualAddress);\n\tIMAGE_IMPORT_DESCRIPTOR* end = p + importDir->Size \/ sizeof(IMAGE_IMPORT_DESCRIPTOR);\n\n\tsize_t count = 0;\n\n\tfor (; p < end && p->Name; p++)\n\t{\n IMAGE_THUNK_DATA* nameThunk = (IMAGE_THUNK_DATA*)(moduleBase + p->OriginalFirstThunk);\n IMAGE_THUNK_DATA* addrThunk = (IMAGE_THUNK_DATA*)(moduleBase + p->FirstThunk);\n\n\t\tconst char* moduleName = moduleBase + p->Name;\n\t\tprintf(\"%s\\n\", moduleName);\n\n\t\tfor (; addrThunk->u1.Function; nameThunk++, addrThunk++, count++)\n\t\t{\n if (IMAGE_SNAP_BY_ORDINAL(nameThunk->u1.Ordinal))\n\t\t\t{\n uint_t ordinal = IMAGE_ORDINAL(nameThunk->u1.Ordinal);\n\t\t\t\tprintf(\" @%d\\n\", ordinal);\n }\n\t\t\telse\n\t\t\t{\n\t\t\t\tIMAGE_IMPORT_BY_NAME* name = (IMAGE_IMPORT_BY_NAME*)(moduleBase + nameThunk->u1.AddressOfData);\n\t\t\t\tprintf(\" hint %04x: %s\\n\", name->Hint, name->Name);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn count;\n}\n\n#elif (_AXL_OS_LINUX)\n#\tif (_AXL_CPU_X86)\n#\tdefine ELF_R_TYPE ELF32_R_TYPE\n#\tdefine ELF_R_SYM ELF32_R_SYM\n#\tdefine ELF_ST_TYPE ELF32_ST_TYPE\n#\tdefine ELF_ST_BIND ELF32_ST_BIND\n\n\ttypedef ElfW(Rel) ElfRel;\n\n\tenum Dt\n\t{\n\t\tDt_Rel = DT_REL,\n\t\tDt_RelSz = DT_RELSZ,\n\t\tDt_RelEnt = DT_RELENT,\n\n\t\tR_GlobDat = R_386_GLOB_DAT,\n\t\tR_JumpSlot = R_386_JMP_SLOT,\n\t};\n#\telif (_AXL_CPU_AMD64)\n#\tdefine ELF_R_TYPE ELF64_R_TYPE\n#\tdefine ELF_R_SYM ELF64_R_SYM\n#\tdefine ELF_ST_TYPE ELF64_ST_TYPE\n#\tdefine ELF_ST_BIND ELF64_ST_BIND\n\n\ttypedef ElfW(Rela) ElfRel;\n\n\tenum\n\t{\n\t\tDt_Rel = DT_RELA,\n\t\tDt_RelSz = DT_RELASZ,\n\t\tDt_RelEnt = DT_RELAENT,\n\n\t\tR_GlobDat = R_X86_64_GLOB_DAT,\n\t\tR_JumpSlot = R_X86_64_JUMP_SLOT,\n\t}\n#\telif (_AXL_CPU_ARM32)\n#\tdefine ELF_R_TYPE ELF32_R_TYPE\n#\tdefine ELF_R_SYM ELF32_R_SYM\n#\tdefine ELF_ST_TYPE ELF32_ST_TYPE\n#\tdefine ELF_ST_BIND ELF32_ST_BIND\n\n\ttypedef ElfW(Rel) ElfRel;\n\n\tenum\n\t{\n\t\tDt_Rel = DT_RELA,\n\t\tDt_RelSz = DT_RELASZ,\n\t\tDt_RelEnt = DT_RELAENT,\n\n\t\tR_GlobDat = R_X86_64_GLOB_DAT,\n\t\tR_JumpSlot = R_X86_64_JUMP_SLOT,\n\t};\n#\tendif\n\nvoid\nprintRelTable(\n\tElfRel* rel,\n\tsize_t count,\n\tint relType,\n\tchar* moduleBase,\n\tElfW(Sym)* symbolTable,\n\tchar* stringTable,\n\tsize_t stringTableSize\n\t)\n{\n\tElfRel* end = rel + count;\n\n\tfor (; rel < end; rel++)\n\t{\n\t\tif (ELF_R_TYPE(rel->r_info) != relType)\n\t\t\tcontinue;\n\n\t\tsize_t symIdx = ELF_R_SYM(rel->r_info);\n\t\tElfW(Sym)* sym = symbolTable + symIdx;\n\t\tif (ELF_ST_TYPE(sym->st_info) != STT_FUNC)\n\t\t\tcontinue;\n\n\t\tif (sym->st_name >= stringTableSize)\n\t\t{\n\t\t\tprintf(\"*** symbol out of string table\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tchar* name = stringTable + sym->st_name;\n\t\tvoid** p = (void**)(moduleBase + rel->r_offset);\n\t\tprintf(\" %p %s\\n\", *p, name);\n\t}\n}\n\nsize_t\nImportTableMgr::enumerateImports(void* module)\n{\n\tbool result;\n\n\tsys::psx::DynamicLib exe;\n\tif (!module)\n\t{\n\t\tresult = exe.open(NULL, RTLD_LAZY | RTLD_NOLOAD);\n\t\tif (!result)\n\t\t\treturn -1;\n\n\t\tmodule = exe;\n\t}\n\n\tlink_map* linkMap;\n\n\tsys::psx::DynamicLib lib;\n\tlib.attach(module);\n\tresult = exe.getInfo(RTLD_DI_LINKMAP, &linkMap);\n\tlib.detach();\n\n\tif (!result)\n\t\treturn -1;\n\n\tElfW(Dyn)* dynTable[DT_NUM] = { 0 };\n\tElfW(Dyn)* dyn = linkMap->l_ld;\n\tfor (; dyn->d_tag; dyn++)\n\t{\n\t\tif (dyn->d_tag < countof(dynTable))\n\t\t\tdynTable[dyn->d_tag] = dyn;\n\t}\n\n\t\/\/ sanity checks\n\n\tif (!dynTable[DT_SYMTAB] ||\n\t\t!dynTable[DT_SYMENT] ||\n\t\t!dynTable[DT_STRTAB] ||\n\t\t!dynTable[DT_STRSZ] ||\n\t\t!dynTable[Dt_Rel] != !dynTable[Dt_RelSz] ||\n\t\t!dynTable[Dt_Rel] != !dynTable[Dt_RelEnt] ||\n\t\t!dynTable[DT_JMPREL] != !dynTable[DT_PLTRELSZ] ||\n\t\tdynTable[DT_SYMENT]->d_un.d_val != sizeof(ElfW(Sym)) ||\n\t\tdynTable[Dt_RelEnt]->d_un.d_val != sizeof(ElfRel))\n\t{\n\t\terr::setError(\"invalid ELF (missing or bad section(s))\");\n\t\treturn -1;\n\t}\n\n\tElfW(Sym)* symbolTable = (ElfW(Sym)*)dynTable[DT_SYMTAB]->d_un.d_ptr;\n\tchar* stringTable = (char*)dynTable[DT_STRTAB]->d_un.d_ptr;\n\tsize_t stringTableSize = dynTable[DT_STRSZ]->d_un.d_val;\n\n\tsize_t pltCount = dynTable[DT_PLTRELSZ] ? dynTable[DT_PLTRELSZ]->d_un.d_val \/ sizeof(ElfRel) : 0;\n\tsize_t gotCount = dynTable[Dt_RelSz] ? dynTable[Dt_RelSz]->d_un.d_val \/ sizeof(ElfRel) : 0;\n\n\tif (pltCount)\n\t{\n\t\tprintf(\"PLT:\\n\");\n\n\t\tprintRelTable(\n\t\t\t(ElfRel*)dynTable[DT_JMPREL]->d_un.d_ptr,\n\t\t\tpltCount,\n\t\t\tR_JumpSlot,\n\t\t\t(char*)linkMap->l_addr,\n\t\t\tsymbolTable,\n\t\t\tstringTable,\n\t\t\tstringTableSize\n\t\t\t);\n\t}\n\n\tif (gotCount)\n\t{\n\t\tprintf(\"GOT:\\n\");\n\n\t\tprintRelTable(\n\t\t\t(ElfRel*)dynTable[Dt_Rel]->d_un.d_ptr,\n\t\t\tgotCount,\n\t\t\tR_GlobDat,\n\t\t\t(char*)linkMap->l_addr,\n\t\t\tsymbolTable,\n\t\t\tstringTable,\n\t\t\tstringTableSize\n\t\t\t);\n\t}\n\n\treturn 0;\n}\n\n#elif (_AXL_OS_DARWIN)\n#endif\n\n\/\/..............................................................................\n\n} \/\/ namespace spy\n} \/\/ namespace axl\n<commit_msg>[axl_spy] enumerate import names for mach-o<commit_after>#include \"pch.h\"\n#include \"axl_err_Error.h\"\n#include \"axl_spy_ImportTableMgr.h\"\n#include \"axl_sl_Array.h\"\n\n#if (_AXL_OS_LINUX)\n#\tinclude \"axl_sys_psx_DynamicLib.h\"\n#\tinclude <link.h>\n#elif (_AXL_OS_DARWIN)\n# include <mach-o\/dyld.h>\n#endif\n\nnamespace axl {\nnamespace spy {\n\n\/\/..............................................................................\n\n#if (_AXL_OS_WIN)\n\nsize_t\nImportTableMgr::enumerateImports(void* module)\n{\n\tif (!module)\n\t\tmodule = ::GetModuleHandle(NULL);\n\n\tchar* moduleBase = (char*)module;\n\n\tIMAGE_DOS_HEADER* dosHdr = (IMAGE_DOS_HEADER*)moduleBase;\n\tif (dosHdr->e_magic != IMAGE_DOS_SIGNATURE)\n\t{\n\t\terr::setError(\"invalid module (bad DOS signature)\");\n\t\treturn -1;\n\t}\n\n\tIMAGE_NT_HEADERS* peHdr = (IMAGE_NT_HEADERS*)(moduleBase + dosHdr->e_lfanew);\n\tif (peHdr->Signature != IMAGE_NT_SIGNATURE)\n\t{\n\t\terr::setError(\"invalid module (bad PE signature)\");\n\t\treturn -1;\n\t}\n\n\tIMAGE_DATA_DIRECTORY* importDir = (IMAGE_DATA_DIRECTORY*)&peHdr->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];\n\tIMAGE_IMPORT_DESCRIPTOR* p = (IMAGE_IMPORT_DESCRIPTOR*)(moduleBase + importDir->VirtualAddress);\n\tIMAGE_IMPORT_DESCRIPTOR* end = p + importDir->Size \/ sizeof(IMAGE_IMPORT_DESCRIPTOR);\n\n\tsize_t count = 0;\n\n\tfor (; p < end && p->Name; p++)\n\t{\n IMAGE_THUNK_DATA* nameThunk = (IMAGE_THUNK_DATA*)(moduleBase + p->OriginalFirstThunk);\n IMAGE_THUNK_DATA* addrThunk = (IMAGE_THUNK_DATA*)(moduleBase + p->FirstThunk);\n\n\t\tconst char* moduleName = moduleBase + p->Name;\n\t\tprintf(\"%s\\n\", moduleName);\n\n\t\tfor (; addrThunk->u1.Function; nameThunk++, addrThunk++, count++)\n\t\t{\n if (IMAGE_SNAP_BY_ORDINAL(nameThunk->u1.Ordinal))\n\t\t\t{\n uint_t ordinal = IMAGE_ORDINAL(nameThunk->u1.Ordinal);\n\t\t\t\tprintf(\" @%d\\n\", ordinal);\n }\n\t\t\telse\n\t\t\t{\n\t\t\t\tIMAGE_IMPORT_BY_NAME* name = (IMAGE_IMPORT_BY_NAME*)(moduleBase + nameThunk->u1.AddressOfData);\n\t\t\t\tprintf(\" hint %04x: %s\\n\", name->Hint, name->Name);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn count;\n}\n\n#elif (_AXL_OS_LINUX)\n#\tif (_AXL_CPU_X86)\n#\tdefine ELF_R_TYPE ELF32_R_TYPE\n#\tdefine ELF_R_SYM ELF32_R_SYM\n#\tdefine ELF_ST_TYPE ELF32_ST_TYPE\n#\tdefine ELF_ST_BIND ELF32_ST_BIND\n\n\ttypedef ElfW(Rel) ElfRel;\n\n\tenum Dt\n\t{\n\t\tDt_Rel = DT_REL,\n\t\tDt_RelSz = DT_RELSZ,\n\t\tDt_RelEnt = DT_RELENT,\n\n\t\tR_GlobDat = R_386_GLOB_DAT,\n\t\tR_JumpSlot = R_386_JMP_SLOT,\n\t};\n#\telif (_AXL_CPU_AMD64)\n#\tdefine ELF_R_TYPE ELF64_R_TYPE\n#\tdefine ELF_R_SYM ELF64_R_SYM\n#\tdefine ELF_ST_TYPE ELF64_ST_TYPE\n#\tdefine ELF_ST_BIND ELF64_ST_BIND\n\n\ttypedef ElfW(Rela) ElfRel;\n\n\tenum\n\t{\n\t\tDt_Rel = DT_RELA,\n\t\tDt_RelSz = DT_RELASZ,\n\t\tDt_RelEnt = DT_RELAENT,\n\n\t\tR_GlobDat = R_X86_64_GLOB_DAT,\n\t\tR_JumpSlot = R_X86_64_JUMP_SLOT,\n\t}\n#\telif (_AXL_CPU_ARM32)\n#\tdefine ELF_R_TYPE ELF32_R_TYPE\n#\tdefine ELF_R_SYM ELF32_R_SYM\n#\tdefine ELF_ST_TYPE ELF32_ST_TYPE\n#\tdefine ELF_ST_BIND ELF32_ST_BIND\n\n\ttypedef ElfW(Rel) ElfRel;\n\n\tenum\n\t{\n\t\tDt_Rel = DT_RELA,\n\t\tDt_RelSz = DT_RELASZ,\n\t\tDt_RelEnt = DT_RELAENT,\n\n\t\tR_GlobDat = R_X86_64_GLOB_DAT,\n\t\tR_JumpSlot = R_X86_64_JUMP_SLOT,\n\t};\n#\tendif\n\nvoid\nprintRelTable(\n\tElfRel* rel,\n\tsize_t count,\n\tint relType,\n\tchar* moduleBase,\n\tElfW(Sym)* symbolTable,\n\tchar* stringTable,\n\tsize_t stringTableSize\n\t)\n{\n\tElfRel* end = rel + count;\n\n\tfor (; rel < end; rel++)\n\t{\n\t\tif (ELF_R_TYPE(rel->r_info) != relType)\n\t\t\tcontinue;\n\n\t\tsize_t symIdx = ELF_R_SYM(rel->r_info);\n\t\tElfW(Sym)* sym = symbolTable + symIdx;\n\t\tif (ELF_ST_TYPE(sym->st_info) != STT_FUNC)\n\t\t\tcontinue;\n\n\t\tif (sym->st_name >= stringTableSize)\n\t\t{\n\t\t\tprintf(\"*** symbol out of string table\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tchar* name = stringTable + sym->st_name;\n\t\tvoid** p = (void**)(moduleBase + rel->r_offset);\n\t\tprintf(\" %p %s\\n\", *p, name);\n\t}\n}\n\nsize_t\nImportTableMgr::enumerateImports(void* module)\n{\n\tbool result;\n\n\tlink_map* linkMap;\n\n\tsys::psx::DynamicLib exe;\n\tif (!module)\n\t{\n\t\tresult =\n\t\t\texe.open(NULL, RTLD_LAZY | RTLD_NOLOAD) &&\n\t\t\texe.getInfo(RTLD_DI_LINKMAP, &linkMap);\n\t}\n\telse\n\t{\n\t\tsys::psx::DynamicLib lib;\n\t\tlib.attach(module);\n\t\tresult = lib.getInfo(RTLD_DI_LINKMAP, &linkMap);\n\t\tlib.detach();\n\t}\n\n\tif (!result)\n\t\treturn -1;\n\n\tElfW(Dyn)* dynTable[DT_NUM] = { 0 };\n\tElfW(Dyn)* dyn = linkMap->l_ld;\n\tfor (; dyn->d_tag; dyn++)\n\t{\n\t\tif (dyn->d_tag < countof(dynTable))\n\t\t\tdynTable[dyn->d_tag] = dyn;\n\t}\n\n\t\/\/ sanity checks\n\n\tif (!dynTable[DT_SYMTAB] ||\n\t\t!dynTable[DT_SYMENT] ||\n\t\t!dynTable[DT_STRTAB] ||\n\t\t!dynTable[DT_STRSZ] ||\n\t\t!dynTable[Dt_Rel] != !dynTable[Dt_RelSz] ||\n\t\t!dynTable[Dt_Rel] != !dynTable[Dt_RelEnt] ||\n\t\t!dynTable[DT_JMPREL] != !dynTable[DT_PLTRELSZ] ||\n\t\tdynTable[DT_SYMENT]->d_un.d_val != sizeof(ElfW(Sym)) ||\n\t\tdynTable[Dt_RelEnt]->d_un.d_val != sizeof(ElfRel))\n\t{\n\t\terr::setError(\"invalid ELF (missing or bad section(s))\");\n\t\treturn -1;\n\t}\n\n\tElfW(Sym)* symbolTable = (ElfW(Sym)*)dynTable[DT_SYMTAB]->d_un.d_ptr;\n\tchar* stringTable = (char*)dynTable[DT_STRTAB]->d_un.d_ptr;\n\tsize_t stringTableSize = dynTable[DT_STRSZ]->d_un.d_val;\n\n\tsize_t pltCount = dynTable[DT_PLTRELSZ] ? dynTable[DT_PLTRELSZ]->d_un.d_val \/ sizeof(ElfRel) : 0;\n\tsize_t gotCount = dynTable[Dt_RelSz] ? dynTable[Dt_RelSz]->d_un.d_val \/ sizeof(ElfRel) : 0;\n\n\tif (pltCount)\n\t{\n\t\tprintf(\"PLT:\\n\");\n\n\t\tprintRelTable(\n\t\t\t(ElfRel*)dynTable[DT_JMPREL]->d_un.d_ptr,\n\t\t\tpltCount,\n\t\t\tR_JumpSlot,\n\t\t\t(char*)linkMap->l_addr,\n\t\t\tsymbolTable,\n\t\t\tstringTable,\n\t\t\tstringTableSize\n\t\t\t);\n\t}\n\n\tif (gotCount)\n\t{\n\t\tprintf(\"GOT:\\n\");\n\n\t\tprintRelTable(\n\t\t\t(ElfRel*)dynTable[Dt_Rel]->d_un.d_ptr,\n\t\t\tgotCount,\n\t\t\tR_GlobDat,\n\t\t\t(char*)linkMap->l_addr,\n\t\t\tsymbolTable,\n\t\t\tstringTable,\n\t\t\tstringTableSize\n\t\t\t);\n\t}\n\n\treturn pltCount + gotCount;\n}\n\n#elif (_AXL_OS_DARWIN)\n\nuint64_t uleb128(const uint8_t** p)\n{\n\tuint64_t r = 0;\n\tint s = 0;\n\n\tdo\n\t{\n\t\tr |= (uint64_t)(**p & 0x7f) << s;\n\t\ts += 7;\n\t} while (*(*p)++ >= 0x80);\n\n\treturn r;\n}\n\nint64_t sleb128(const uint8_t** p)\n{\n\tint64_t r = 0;\n\tint s = 0;\n\tfor (;;)\n\t{\n\t\tuint8_t b = *(*p)++;\n\t\tif (b < 0x80)\n\t\t{\n\t\t\tif (b & 0x40)\n\t\t\t\tr -= (0x80 - b) << s;\n\t\t\telse\n\t\t\t\tr |= (b & 0x3f) << s;\n\n\t\t\tbreak;\n\t\t}\n\n\t\tr |= (b & 0x7f) << s;\n\t\ts += 7;\n\t}\n\n\treturn r;\n}\n\nsize_t\nImportTableMgr::enumerateImports(void* module)\n{\n\tuint8_t* slide = (uint8_t*)_dyld_get_image_vmaddr_slide(0);\n\tmach_header_64* machHdr = (mach_header_64*)_dyld_get_image_header(0);\n\tload_command* cmd = (load_command*)(machHdr + 1);\n\n\tsl::Array<segment_command_64*> segmentCmdArray;\n\tsize_t linkEditSegmentIdx = -1;\n\tsize_t lazyBindOffset = -1;\n\tsize_t lazyBindSize = -1;\n\n\tfor (uint_t i = 0; i < machHdr->ncmds; i++)\n\t{\n\t\tprintf(\"load_command: 0x%x\\n\", cmd->cmd);\n\n\t\tswitch (cmd->cmd)\n\t\t{\n\t\t\tsegment_command_64* segmentCmd;\n\t\t\tdyld_info_command* dyldInfoCmd;\n\n\t\tcase LC_SEGMENT_64:\n\t\t\tsegmentCmd = (segment_command_64*)cmd;\n\n\t\t\tif (strcmp(segmentCmd->segname, \"__LINKEDIT\") == 0)\n\t\t\t\tlinkEditSegmentIdx = segmentCmdArray.getCount();\n\n\t\t\tsegmentCmdArray.append(segmentCmd);\n\t\t\tbreak;\n\n\t\tcase LC_DYLD_INFO_ONLY:\n\t\t\tdyldInfoCmd = (dyld_info_command*)cmd;\n\t\t\tlazyBindOffset = dyldInfoCmd->lazy_bind_off;\n\t\t\tlazyBindSize = dyldInfoCmd->lazy_bind_size;\n\t\t\tbreak;\n\t\t}\n\n\t\tcmd = (load_command*)((char*)cmd + cmd->cmdsize);\n\t}\n\n\tif (linkEditSegmentIdx == -1 ||\n\t\tlazyBindOffset == -1 ||\n\t\tlazyBindSize == -1)\n\t{\n\t\terr::setError(\"invalid MACH-O file\");\n\t\treturn -1;\n\t}\n\n\tsegment_command_64* linkEditSegmentCmd = segmentCmdArray[linkEditSegmentIdx];\n\n\tconst uint8_t* p = slide + linkEditSegmentCmd->vmaddr - linkEditSegmentCmd->fileoff + lazyBindOffset;\n\tconst uint8_t* end = p + lazyBindSize;\n\n\twhile (p < end)\n\t{\n\t\tuint8_t op = *p & BIND_OPCODE_MASK;\n\t\tuint8_t imm = *p & BIND_IMMEDIATE_MASK;\n\t\tp++;\n\n\t\tswitch (op)\n\t\t{\n\t\tcase BIND_OPCODE_DONE:\n\t\tcase BIND_OPCODE_DO_BIND:\n\t\tcase BIND_OPCODE_SET_TYPE_IMM:\n\t\tcase BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:\n\t\tcase BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:\n\t\tcase BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:\n\t\t\tbreak;\n\n\t\tcase BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:\n\t\t\tprintf(\" %s\\n\", p);\n\t\t\tp += strlen((char*)p) + 1;\n\t\t\tbreak;\n\n\t\tcase BIND_OPCODE_SET_ADDEND_SLEB:\n\t\t\tsleb128(&p);\n\t\t\tbreak;\n\n\t\tcase BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:\n\t\tcase BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:\n\t\tcase BIND_OPCODE_ADD_ADDR_ULEB:\n\t\tcase BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:\n\t\t\tuleb128(&p);\n\t\t\tbreak;\n\n\t\tcase BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:\n\t\t\tuleb128(&p);\n\t\t\tuleb128(&p);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tprintf(\"*** unexpected bind op: 0x%02x\\n\", op);\n\t\t}\n\t}\n\n\treturn -1;\n}\n\n#endif\n\n\/\/..............................................................................\n\n} \/\/ namespace spy\n} \/\/ namespace axl\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <glm\/glm.hpp>\n\nclass CollisionBox2D {\npublic:\n\tinline bool collide(const glm::vec2& point) { return point.x > _pos.x && point.x < _pos.x + _size.x && point.y > _pos.y && point.y < _pos.y + _size.y; }\n\tinline bool collide(const CollisionBox2D& other) {\n\t\treturn _pos.x < other._pos.x + other._size.x && _pos.x + _size.x > other._pos.x && _pos.y < other._pos.y + other._size.y && _pos.y + _size.y < other._pos.y;\n\t}\n\nprivate:\n\tglm::vec2 _pos;\n\tglm::vec2 _size;\n};<commit_msg>Small changes to CollisionBox2D<commit_after>#pragma once\n\n#include <glm\/glm.hpp>\n\nstruct CollisionBox2D {\n\tglm::vec2 position;\n\tglm::vec2 size;\n\n\tCollisionBox2D(glm::vec2 position, glm::vec2 size) : position(position), size(size) {\n\t}\n\n\tinline bool collide(const glm::vec2& point) {\n\t\treturn point.x > position.x && point.x < position.x + size.x && point.y > position.y && point.y < position.y + size.y;\n\t}\n\tinline bool collide(const CollisionBox2D& other) {\n\t\treturn position.x < other.position.x + other.size.x && position.x + size.x > other.position.x && position.y < other.position.y + other.size.y &&\n\t\t\t\t\t position.y + size.y < other.position.y;\n\t}\n};\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Remove extra ';'<commit_after><|endoftext|>"} {"text":"<commit_before> \/*************************************************************************\n *\n * $RCSfile: accembedded.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2003-03-27 15:39:17 $\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#ifdef PRECOMPILED\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n#ifndef _RTL_UUID_H_\n#include <rtl\/uuid.h>\n#endif\n#ifndef _FLYFRM_HXX\n#include <flyfrm.hxx>\n#endif\n\n#ifndef _ACCEMBEDDED_HXX\n#include \"accembedded.hxx\"\n#endif\n\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::uno;\nusing namespace ::drafts::com::sun::star::accessibility;\nusing namespace ::rtl;\n\nconst sal_Char sServiceName[] = \"com.sun.star.text.AccessibleTextEmbeddedObject\";\nconst sal_Char sImplementationName[] = \"com.sun.star.comp.Writer.SwAccessibleEmbeddedObject\";\n\nSwAccessibleEmbeddedObject::SwAccessibleEmbeddedObject(\n SwAccessibleMap *pMap,\n const SwFlyFrm *pFlyFrm ) :\n SwAccessibleNoTextFrame( pMap, AccessibleRole::EMBEDDED_OBJECT, pFlyFrm )\n{\n}\n\nSwAccessibleEmbeddedObject::~SwAccessibleEmbeddedObject()\n{\n}\n\nOUString SAL_CALL SwAccessibleEmbeddedObject::getImplementationName()\n throw( RuntimeException )\n{\n return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationName));\n}\n\nsal_Bool SAL_CALL SwAccessibleEmbeddedObject::supportsService(\n const ::rtl::OUString& sTestServiceName)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return sTestServiceName.equalsAsciiL( sServiceName,\n sizeof(sServiceName)-1 ) ||\n sTestServiceName.equalsAsciiL( sAccessibleServiceName,\n sizeof(sAccessibleServiceName)-1 );\n}\n\nSequence< OUString > SAL_CALL SwAccessibleEmbeddedObject::getSupportedServiceNames()\n throw( ::com::sun::star::uno::RuntimeException )\n{\n Sequence< OUString > aRet(2);\n OUString* pArray = aRet.getArray();\n pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceName) );\n pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );\n return aRet;\n}\n\n\nSequence< sal_Int8 > SAL_CALL SwAccessibleEmbeddedObject::getImplementationId()\n throw(RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n static Sequence< sal_Int8 > aId( 16 );\n static sal_Bool bInit = sal_False;\n if(!bInit)\n {\n rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );\n bInit = sal_True;\n }\n return aId;\n}\n<commit_msg>INTEGRATION: CWS os8 (1.3.8.1.48); FILE MERGED 2003\/04\/03 07:09:20 os 1.3.8.1.48.1: #108583# precompiled headers removed<commit_after> \/*************************************************************************\n *\n * $RCSfile: accembedded.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 13:35:08 $\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\n#pragma hdrstop\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n#ifndef _RTL_UUID_H_\n#include <rtl\/uuid.h>\n#endif\n#ifndef _FLYFRM_HXX\n#include <flyfrm.hxx>\n#endif\n\n#ifndef _ACCEMBEDDED_HXX\n#include \"accembedded.hxx\"\n#endif\n\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::uno;\nusing namespace ::drafts::com::sun::star::accessibility;\nusing namespace ::rtl;\n\nconst sal_Char sServiceName[] = \"com.sun.star.text.AccessibleTextEmbeddedObject\";\nconst sal_Char sImplementationName[] = \"com.sun.star.comp.Writer.SwAccessibleEmbeddedObject\";\n\nSwAccessibleEmbeddedObject::SwAccessibleEmbeddedObject(\n SwAccessibleMap *pMap,\n const SwFlyFrm *pFlyFrm ) :\n SwAccessibleNoTextFrame( pMap, AccessibleRole::EMBEDDED_OBJECT, pFlyFrm )\n{\n}\n\nSwAccessibleEmbeddedObject::~SwAccessibleEmbeddedObject()\n{\n}\n\nOUString SAL_CALL SwAccessibleEmbeddedObject::getImplementationName()\n throw( RuntimeException )\n{\n return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationName));\n}\n\nsal_Bool SAL_CALL SwAccessibleEmbeddedObject::supportsService(\n const ::rtl::OUString& sTestServiceName)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return sTestServiceName.equalsAsciiL( sServiceName,\n sizeof(sServiceName)-1 ) ||\n sTestServiceName.equalsAsciiL( sAccessibleServiceName,\n sizeof(sAccessibleServiceName)-1 );\n}\n\nSequence< OUString > SAL_CALL SwAccessibleEmbeddedObject::getSupportedServiceNames()\n throw( ::com::sun::star::uno::RuntimeException )\n{\n Sequence< OUString > aRet(2);\n OUString* pArray = aRet.getArray();\n pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceName) );\n pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );\n return aRet;\n}\n\n\nSequence< sal_Int8 > SAL_CALL SwAccessibleEmbeddedObject::getImplementationId()\n throw(RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n static Sequence< sal_Int8 > aId( 16 );\n static sal_Bool bInit = sal_False;\n if(!bInit)\n {\n rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );\n bInit = sal_True;\n }\n return aId;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------- multithread_info.cc ----------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- multithread_info.cc ----------------\n\n\n#include <base\/multithread_info.h>\n\n#if defined(__linux__)\n# include <fstream>\n# include <string>\n#endif\n\n#if defined(__sun__) || defined(__osf__) || defined(_AIX)\n# include <unistd.h>\n#endif\n\n#if defined(__sgi__)\n# include <unistd.h>\n#endif\n\n\n\n\n#if DEAL_II_USE_MT == 1\n\n#if defined(__linux__)\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n std::ifstream cpuinfo;\n std::string search;\n unsigned int nCPU = 0;\n \n cpuinfo.open(\"\/proc\/cpuinfo\");\n\n AssertThrow(cpuinfo,ExcProcNotPresent());\n \n while(cpuinfo)\n {\n cpuinfo >> search;\n if (search.find(\"processor\")!=std::string::npos)\n\tnCPU++;\t \n }\n cpuinfo.close();\n \n return nCPU;\n}\n\n\n#elif defined(__sun__) || defined(__osf__) || defined(_AIX)\n\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n return sysconf(_SC_NPROCESSORS_ONLN);\n}\n\n\n#elif defined(__sgi__)\n\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n return sysconf(_SC_NPROC_ONLN);\n}\n\n\n#else\n\n\/\/ if you get to see this warning, then this can have two reasons: either\n\/\/ because you fell through all of the above #if clauses and on your system\n\/\/ the detection of processors is really not implemented, or you are using\n\/\/ a compiler that does not understand the #warning directive, in which case\n\/\/ you will see a report on the screen even if the detection of processors\n\/\/ is implemented for your system. In the latter case, you need not worry\n\/\/ about the warning (although it is acknowledged that it is annoying),\n\/\/ otherwise you might want to consider implementing the missing feature\n\/\/ and submitting it back to the authors of the library.\n#warning Detection of Processors not supported on this OS\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n return 1;\n}\n\n#endif\n\n\n#else\t\t\t\t \/\/ not in multithreadmode\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n return 1;\n}\n\n#endif\n\n\nMultithreadInfo::MultithreadInfo () :\n n_cpus (get_n_cpus()),\n n_default_threads (n_cpus)\n{}\n\n\n\nunsigned int\nMultithreadInfo::memory_consumption ()\n{\n\t\t\t\t \/\/ only simple data elements, so\n\t\t\t\t \/\/ use sizeof operator\n return sizeof (MultithreadInfo);\n}\n\n\n\n\/\/ definition of the variable which is declared `extern' in the .h file\nMultithreadInfo multithread_info;\n<commit_msg>Indent prepro statements<commit_after>\/\/---------------------------- multithread_info.cc ----------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- multithread_info.cc ----------------\n\n\n#include <base\/multithread_info.h>\n\n#if defined(__linux__)\n# include <fstream>\n# include <string>\n#endif\n\n#if defined(__sun__) || defined(__osf__) || defined(_AIX)\n# include <unistd.h>\n#endif\n\n#if defined(__sgi__)\n# include <unistd.h>\n#endif\n\n\n\n\n#if DEAL_II_USE_MT == 1\n\n# if defined(__linux__)\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n std::ifstream cpuinfo;\n std::string search;\n unsigned int nCPU = 0;\n \n cpuinfo.open(\"\/proc\/cpuinfo\");\n\n AssertThrow(cpuinfo,ExcProcNotPresent());\n \n while(cpuinfo)\n {\n cpuinfo >> search;\n if (search.find(\"processor\")!=std::string::npos)\n\tnCPU++;\t \n }\n cpuinfo.close();\n \n return nCPU;\n}\n\n# elif defined(__sun__) || defined(__osf__) || defined(_AIX)\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n return sysconf(_SC_NPROCESSORS_ONLN);\n}\n\n\n# elif defined(__sgi__)\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n return sysconf(_SC_NPROC_ONLN);\n}\n\n# else\n\n\/\/ if you get to see this warning, then this can have two reasons: either\n\/\/ because you fell through all of the above #if clauses and on your system\n\/\/ the detection of processors is really not implemented, or you are using\n\/\/ a compiler that does not understand the #warning directive, in which case\n\/\/ you will see a report on the screen even if the detection of processors\n\/\/ is implemented for your system. In the latter case, you need not worry\n\/\/ about the warning (although it is acknowledged that it is annoying),\n\/\/ otherwise you might want to consider implementing the missing feature\n\/\/ and submitting it back to the authors of the library.\n# warning Detection of Processors not supported on this OS\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n return 1;\n}\n\n# endif\n\n\n#else\t\t\t\t \/\/ not in MT mode\n\nunsigned int MultithreadInfo::get_n_cpus()\n{\n return 1;\n}\n\n#endif\n\n\nMultithreadInfo::MultithreadInfo () :\n n_cpus (get_n_cpus()),\n n_default_threads (n_cpus)\n{}\n\n\n\nunsigned int\nMultithreadInfo::memory_consumption ()\n{\n\t\t\t\t \/\/ only simple data elements, so\n\t\t\t\t \/\/ use sizeof operator\n return sizeof (MultithreadInfo);\n}\n\n\n\n\/\/ definition of the variable which is declared `extern' in the .h file\nMultithreadInfo multithread_info;\n<|endoftext|>"} {"text":"<commit_before> \/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accfootnote.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 12:13:42 $\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_sw.hxx\"\n\n\n#ifndef _VOS_MUTEX_HXX_ \/\/autogen\n#include <vos\/mutex.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleStateType.hpp>\n#endif\n\n#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_\n#include <unotools\/accessiblestatesethelper.hxx>\n#endif\n#ifndef _RTL_UUID_H_\n#include <rtl\/uuid.h>\n#endif\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _FTNFRM_HXX\n#include <ftnfrm.hxx>\n#endif\n#ifndef _FMTFTN_HXX \/\/autogen\n#include <fmtftn.hxx>\n#endif\n#ifndef _TXTFTN_HXX \/\/autogen\n#include <txtftn.hxx>\n#endif\n#ifndef _VIEWSH_HXX\n#include <viewsh.hxx>\n#endif\n\n#ifndef _ACCMAP_HXX\n#include <accmap.hxx>\n#endif\n#ifndef _ACCFOOTNOTE_HXX\n#include \"accfootnote.hxx\"\n#endif\n#ifndef _ACCESS_HRC\n#include \"access.hrc\"\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::accessibility;\nusing ::rtl::OUString;\n\nconst sal_Char sServiceNameFootnote[] = \"com.sun.star.text.AccessibleFootnoteView\";\nconst sal_Char sServiceNameEndnote[] = \"com.sun.star.text.AccessibleEndnoteView\";\nconst sal_Char sImplementationNameFootnote[] = \"com.sun.star.comp.Writer.SwAccessibleFootnoteView\";\nconst sal_Char sImplementationNameEndnote[] = \"com.sun.star.comp.Writer.SwAccessibleEndnoteView\";\n\nSwAccessibleFootnote::SwAccessibleFootnote(\n SwAccessibleMap* pInitMap,\n sal_Bool bIsEndnote,\n sal_Int32 nFootEndNote,\n const SwFtnFrm *pFtnFrm ) :\n SwAccessibleContext( pInitMap,\n bIsEndnote ? AccessibleRole::END_NOTE : AccessibleRole::FOOTNOTE,\n pFtnFrm )\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n\n sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME\n : STR_ACCESS_FOOTNOTE_NAME;\n OUString sArg( OUString::valueOf( nFootEndNote ) );\n SetName( GetResource( nResId, &sArg ) );\n}\n\nSwAccessibleFootnote::~SwAccessibleFootnote()\n{\n}\n\nOUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)\n throw (uno::RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n\n CHECK_FOR_DEFUNC( XAccessibleContext )\n\n sal_uInt16 nResId = AccessibleRole::END_NOTE == GetRole()\n ? STR_ACCESS_ENDNOTE_DESC\n : STR_ACCESS_FOOTNOTE_DESC ;\n\n OUString sArg;\n const SwTxtFtn *pTxtFtn =\n static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();\n if( pTxtFtn )\n {\n const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();\n sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );\n }\n\n return GetResource( nResId, &sArg );\n}\n\nOUString SAL_CALL SwAccessibleFootnote::getImplementationName()\n throw( RuntimeException )\n{\n if( AccessibleRole::END_NOTE == GetRole() )\n return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));\n else\n return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));\n}\n\nsal_Bool SAL_CALL SwAccessibleFootnote::supportsService(\n const ::rtl::OUString& sTestServiceName)\n throw (uno::RuntimeException)\n{\n if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,\n sizeof(sAccessibleServiceName)-1 ) )\n return sal_True;\n else if( AccessibleRole::END_NOTE == GetRole() )\n return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );\n else\n return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );\n\n}\n\nSequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()\n throw( uno::RuntimeException )\n{\n Sequence< OUString > aRet(2);\n OUString* pArray = aRet.getArray();\n if( AccessibleRole::END_NOTE == GetRole() )\n pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );\n else\n pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );\n pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );\n return aRet;\n}\n\nSequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()\n throw(RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n static Sequence< sal_Int8 > aId( 16 );\n static sal_Bool bInit = sal_False;\n if(!bInit)\n {\n rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );\n bInit = sal_True;\n }\n return aId;\n}\n\nsal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )\n{\n const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();\n return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.15.34); FILE MERGED 2008\/04\/01 15:56:39 thb 1.15.34.3: #i85898# Stripping all external header guards 2008\/04\/01 12:53:44 thb 1.15.34.2: #i85898# Stripping all external header guards 2008\/03\/31 16:53:37 rt 1.15.34.1: #i87441# Change license header to LPGL v3.<commit_after> \/*************************************************************************\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: accfootnote.cxx,v $\n * $Revision: 1.16 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_sw.hxx\"\n\n\n#include <vos\/mutex.hxx>\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#include <com\/sun\/star\/accessibility\/AccessibleStateType.hpp>\n#include <unotools\/accessiblestatesethelper.hxx>\n#include <rtl\/uuid.h>\n#include <vcl\/svapp.hxx>\n#include <ftnfrm.hxx>\n#include <fmtftn.hxx>\n#include <txtftn.hxx>\n#include <viewsh.hxx>\n#include <accmap.hxx>\n#include \"accfootnote.hxx\"\n#ifndef _ACCESS_HRC\n#include \"access.hrc\"\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::accessibility;\nusing ::rtl::OUString;\n\nconst sal_Char sServiceNameFootnote[] = \"com.sun.star.text.AccessibleFootnoteView\";\nconst sal_Char sServiceNameEndnote[] = \"com.sun.star.text.AccessibleEndnoteView\";\nconst sal_Char sImplementationNameFootnote[] = \"com.sun.star.comp.Writer.SwAccessibleFootnoteView\";\nconst sal_Char sImplementationNameEndnote[] = \"com.sun.star.comp.Writer.SwAccessibleEndnoteView\";\n\nSwAccessibleFootnote::SwAccessibleFootnote(\n SwAccessibleMap* pInitMap,\n sal_Bool bIsEndnote,\n sal_Int32 nFootEndNote,\n const SwFtnFrm *pFtnFrm ) :\n SwAccessibleContext( pInitMap,\n bIsEndnote ? AccessibleRole::END_NOTE : AccessibleRole::FOOTNOTE,\n pFtnFrm )\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n\n sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME\n : STR_ACCESS_FOOTNOTE_NAME;\n OUString sArg( OUString::valueOf( nFootEndNote ) );\n SetName( GetResource( nResId, &sArg ) );\n}\n\nSwAccessibleFootnote::~SwAccessibleFootnote()\n{\n}\n\nOUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)\n throw (uno::RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n\n CHECK_FOR_DEFUNC( XAccessibleContext )\n\n sal_uInt16 nResId = AccessibleRole::END_NOTE == GetRole()\n ? STR_ACCESS_ENDNOTE_DESC\n : STR_ACCESS_FOOTNOTE_DESC ;\n\n OUString sArg;\n const SwTxtFtn *pTxtFtn =\n static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();\n if( pTxtFtn )\n {\n const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();\n sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );\n }\n\n return GetResource( nResId, &sArg );\n}\n\nOUString SAL_CALL SwAccessibleFootnote::getImplementationName()\n throw( RuntimeException )\n{\n if( AccessibleRole::END_NOTE == GetRole() )\n return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));\n else\n return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));\n}\n\nsal_Bool SAL_CALL SwAccessibleFootnote::supportsService(\n const ::rtl::OUString& sTestServiceName)\n throw (uno::RuntimeException)\n{\n if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,\n sizeof(sAccessibleServiceName)-1 ) )\n return sal_True;\n else if( AccessibleRole::END_NOTE == GetRole() )\n return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );\n else\n return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );\n\n}\n\nSequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()\n throw( uno::RuntimeException )\n{\n Sequence< OUString > aRet(2);\n OUString* pArray = aRet.getArray();\n if( AccessibleRole::END_NOTE == GetRole() )\n pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );\n else\n pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );\n pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );\n return aRet;\n}\n\nSequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()\n throw(RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n static Sequence< sal_Int8 > aId( 16 );\n static sal_Bool bInit = sal_False;\n if(!bInit)\n {\n rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );\n bInit = sal_True;\n }\n return aId;\n}\n\nsal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )\n{\n const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();\n return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CdsdkSourceDeviceImpl.hpp CDSDK - SourceDevice impl\n\/\/\n#pragma once\n\n\/\/ includes\n#include \"SourceDevice.hpp\"\n#include \"CdsdkCommon.hpp\"\n#include \"CdsdkRemoteReleaseControlImpl.hpp\"\n#include \"CdsdkViewfinderImpl.hpp\"\n#include \"CdsdkDevicePropertyAccess.hpp\"\n\nnamespace CDSDK\n{\n\n\/\/\/ source device impl for CDSDK\nclass SourceDeviceImpl:\n public SourceDevice,\n public std::enable_shared_from_this<SourceDeviceImpl>\n{\npublic:\n \/\/\/ ctor\n SourceDeviceImpl(RefSp spRef, cdHSource hSource)\n :m_spRef(spRef),\n m_hSource(hSource)\n {\n }\n\n \/\/\/ dtor\n virtual ~SourceDeviceImpl() throw()\n {\n cdError err = CDCloseSource(m_hSource);\n LOG_TRACE(_T(\"CDCloseSource(%08x) returned %08x\\n\"), m_hSource, err);\n }\n\n virtual bool GetDeviceCapability(SourceDevice::T_enDeviceCapability enDeviceCapability) const override\n {\n try\n {\n switch (enDeviceCapability)\n {\n case SourceDevice::capRemoteReleaseControl:\n {\n DeviceProperty p = GetDeviceProperty(cdDEVICE_PROP_RELEASE_CONTROL_CAP);\n unsigned int uiValue = p.Value().Get<unsigned int>();\n\n return (uiValue & 0x40000000) != 0;\n }\n break;\n\n case SourceDevice::capRemoteViewfinder:\n \/\/ TODO implement\n ATLASSERT(false);\n break;\n\n default:\n ATLASSERT(false);\n }\n }\n catch (Exception& ex)\n {\n LOG_TRACE(_T(\"Exception occured in GetDeviceCapability(): %s\\n\"),\n ex.Message().GetString());\n }\n catch (boost::bad_any_cast&)\n {\n LOG_TRACE(_T(\"boost::bad_any_cast exception occured in GetDeviceCapability()\\n\"));\n }\n catch (std::exception& ex)\n {\n LOG_TRACE(_T(\"std::exception occured in GetDeviceCapability(): %Hs\\n\"),\n ex.what());\n }\n return false;\n }\n\n virtual CString ModelName() const override\n {\n try\n {\n DevicePropertyAccess p(const_cast<cdHSource&>(m_hSource));\n Variant v = p.Get(cdDEVICE_PROP_MODEL_NAME);\n return v.Get<CString>();\n }\n catch (Exception& ex)\n {\n LOG_TRACE(_T(\"exception in ModelName(): %s\\n\"), ex.Message().GetString());\n }\n\n return CString();\n }\n\n virtual CString SerialNumber() const override\n {\n return CString();\n }\n\n virtual std::vector<unsigned int> EnumDeviceProperties() const override\n {\n \/\/ start enumerating\n cdHEnum hEnum = 0;\n\n \/\/ may return cdINVALID_PARAMETER, cdINVALID_HANDLE\n cdError err = CDEnumDevicePropertyReset(m_hSource, 0, &hEnum);\n LOG_TRACE(_T(\"CDEnumDevicePropertyReset(%08x) returned %08x\\n\"), m_hSource, err);\n CheckError(_T(\"CDEnumDeviceReset\"), err, __FILE__, __LINE__);\n\n \/\/ get count of properties\n cdUInt32 count = 0;\n\n \/\/ returns cdINVALID_HANDLE, cdINVALID_PARAMETER\n err = CDGetDevicePropertyCount(hEnum, &count);\n LOG_TRACE(_T(\"CDGetDevicePropertyCount(%08x, &count = %u) returned %08x\\n\"), hEnum, count, err);\n CheckError(_T(\"CDGetDevicePropertyCount\"), err, __FILE__, __LINE__);\n\n std::vector<unsigned int> vecData;\n for (cdUInt32 i=0; i<count+1; i++)\n {\n cdDevicePropertyStruct deviceProperty;\n\n \/\/ may return cdINVALID_PARAMETER, cdINVALID_HANDLE, cdENUM_NA\n err = CDEnumDevicePropertyNext(hEnum, &deviceProperty);\n LOG_TRACE(_T(\"CDEnumDevicePropertyNext(%08x, &propId = %08x) returned %08x\\n\"), hEnum, deviceProperty.DevPropID, err);\n if ((err & cdERROR_ERRORID_MASK) == cdENUM_NA)\n break;\n\n CheckError(_T(\"CDEnumDevicePropertyNext\"), err, __FILE__, __LINE__);\n\n vecData.push_back(deviceProperty.DevPropID);\n }\n\n \/\/ end enumerating\n \/\/ may return cdINVALID_HANDLE, cdINVALID_FN_CALL\n err = CDEnumDevicePropertyRelease(hEnum);\n LOG_TRACE(_T(\"CDEnumDevicePropertyRelease(%08x) returned %08x\\n\"), hEnum, err);\n CheckError(_T(\"CDEnumDevicePropertyRelease\"), err, __FILE__, __LINE__);\n\n return vecData;\n }\n\n virtual DeviceProperty GetDeviceProperty(unsigned int uiPropertyId) const override\n {\n DevicePropertyAccess access(GetSource());\n Variant value = access.Get(uiPropertyId);\n\n return DeviceProperty(variantCdsdk, uiPropertyId, value, true);\n }\n\n virtual std::shared_ptr<RemoteReleaseControl> EnterReleaseControl() override\n {\n if (!GetDeviceCapability(capRemoteReleaseControl))\n {\n throw CameraException(_T(\"EnterReleaseControl\"), _T(\"Not supported\"),\n cdERROR_CDSDK_COMPONENTID | cdNOT_SUPPORTED, __FILE__, __LINE__);\n }\n\n std::shared_ptr<SourceDeviceImpl> spSourceDevice = shared_from_this();\n\n return std::shared_ptr<RemoteReleaseControl>(new RemoteReleaseControlImpl(spSourceDevice));\n }\n\n \/\/\/ returns source\n cdHSource GetSource() const throw() { return m_hSource; }\n\nprivate:\n \/\/\/ source device handle\n cdHSource m_hSource;\n\n \/\/\/ SDK ref\n RefSp m_spRef;\n};\n\ninline cdHSource RemoteReleaseControlImpl::GetSource() const throw()\n{\n return m_spSourceDevice->GetSource();\n}\n\ninline cdHSource ViewfinderImpl::GetSource() const throw()\n{\n return m_spSourceDevice->GetSource();\n}\n\n} \/\/ namespace CDSDK\n<commit_msg>added outputting device property name when enumerating device properties<commit_after>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CdsdkSourceDeviceImpl.hpp CDSDK - SourceDevice impl\n\/\/\n#pragma once\n\n\/\/ includes\n#include \"SourceDevice.hpp\"\n#include \"CdsdkCommon.hpp\"\n#include \"CdsdkRemoteReleaseControlImpl.hpp\"\n#include \"CdsdkViewfinderImpl.hpp\"\n#include \"CdsdkDevicePropertyAccess.hpp\"\n\nnamespace CDSDK\n{\n\n\/\/\/ source device impl for CDSDK\nclass SourceDeviceImpl:\n public SourceDevice,\n public std::enable_shared_from_this<SourceDeviceImpl>\n{\npublic:\n \/\/\/ ctor\n SourceDeviceImpl(RefSp spRef, cdHSource hSource)\n :m_spRef(spRef),\n m_hSource(hSource)\n {\n }\n\n \/\/\/ dtor\n virtual ~SourceDeviceImpl() throw()\n {\n cdError err = CDCloseSource(m_hSource);\n LOG_TRACE(_T(\"CDCloseSource(%08x) returned %08x\\n\"), m_hSource, err);\n }\n\n virtual bool GetDeviceCapability(SourceDevice::T_enDeviceCapability enDeviceCapability) const override\n {\n try\n {\n switch (enDeviceCapability)\n {\n case SourceDevice::capRemoteReleaseControl:\n {\n DeviceProperty p = GetDeviceProperty(cdDEVICE_PROP_RELEASE_CONTROL_CAP);\n unsigned int uiValue = p.Value().Get<unsigned int>();\n\n return (uiValue & 0x40000000) != 0;\n }\n break;\n\n case SourceDevice::capRemoteViewfinder:\n \/\/ TODO implement\n ATLASSERT(false);\n break;\n\n default:\n ATLASSERT(false);\n }\n }\n catch (Exception& ex)\n {\n LOG_TRACE(_T(\"Exception occured in GetDeviceCapability(): %s\\n\"),\n ex.Message().GetString());\n }\n catch (boost::bad_any_cast&)\n {\n LOG_TRACE(_T(\"boost::bad_any_cast exception occured in GetDeviceCapability()\\n\"));\n }\n catch (std::exception& ex)\n {\n LOG_TRACE(_T(\"std::exception occured in GetDeviceCapability(): %Hs\\n\"),\n ex.what());\n }\n return false;\n }\n\n virtual CString ModelName() const override\n {\n try\n {\n DevicePropertyAccess p(const_cast<cdHSource&>(m_hSource));\n Variant v = p.Get(cdDEVICE_PROP_MODEL_NAME);\n return v.Get<CString>();\n }\n catch (Exception& ex)\n {\n LOG_TRACE(_T(\"exception in ModelName(): %s\\n\"), ex.Message().GetString());\n }\n\n return CString();\n }\n\n virtual CString SerialNumber() const override\n {\n return CString();\n }\n\n virtual std::vector<unsigned int> EnumDeviceProperties() const override\n {\n \/\/ start enumerating\n cdHEnum hEnum = 0;\n\n \/\/ may return cdINVALID_PARAMETER, cdINVALID_HANDLE\n cdError err = CDEnumDevicePropertyReset(m_hSource, 0, &hEnum);\n LOG_TRACE(_T(\"CDEnumDevicePropertyReset(%08x) returned %08x\\n\"), m_hSource, err);\n CheckError(_T(\"CDEnumDeviceReset\"), err, __FILE__, __LINE__);\n\n \/\/ get count of properties\n cdUInt32 count = 0;\n\n \/\/ returns cdINVALID_HANDLE, cdINVALID_PARAMETER\n err = CDGetDevicePropertyCount(hEnum, &count);\n LOG_TRACE(_T(\"CDGetDevicePropertyCount(%08x, &count = %u) returned %08x\\n\"), hEnum, count, err);\n CheckError(_T(\"CDGetDevicePropertyCount\"), err, __FILE__, __LINE__);\n\n std::vector<unsigned int> vecData;\n for (cdUInt32 i=0; i<count+1; i++)\n {\n cdDevicePropertyStruct deviceProperty;\n\n \/\/ may return cdINVALID_PARAMETER, cdINVALID_HANDLE, cdENUM_NA\n err = CDEnumDevicePropertyNext(hEnum, &deviceProperty);\n LOG_TRACE(_T(\"CDEnumDevicePropertyNext(%08x, &propId = %08x \\\"%s\\\") returned %08x\\n\"),\n hEnum, deviceProperty.DevPropID,\n DevicePropertyAccess::NameFromId(deviceProperty.DevPropID).GetString(),\n err);\n if ((err & cdERROR_ERRORID_MASK) == cdENUM_NA)\n break;\n\n CheckError(_T(\"CDEnumDevicePropertyNext\"), err, __FILE__, __LINE__);\n\n vecData.push_back(deviceProperty.DevPropID);\n }\n\n \/\/ end enumerating\n \/\/ may return cdINVALID_HANDLE, cdINVALID_FN_CALL\n err = CDEnumDevicePropertyRelease(hEnum);\n LOG_TRACE(_T(\"CDEnumDevicePropertyRelease(%08x) returned %08x\\n\"), hEnum, err);\n CheckError(_T(\"CDEnumDevicePropertyRelease\"), err, __FILE__, __LINE__);\n\n return vecData;\n }\n\n virtual DeviceProperty GetDeviceProperty(unsigned int uiPropertyId) const override\n {\n DevicePropertyAccess access(GetSource());\n Variant value = access.Get(uiPropertyId);\n\n return DeviceProperty(variantCdsdk, uiPropertyId, value, true);\n }\n\n virtual std::shared_ptr<RemoteReleaseControl> EnterReleaseControl() override\n {\n if (!GetDeviceCapability(capRemoteReleaseControl))\n {\n throw CameraException(_T(\"EnterReleaseControl\"), _T(\"Not supported\"),\n cdERROR_CDSDK_COMPONENTID | cdNOT_SUPPORTED, __FILE__, __LINE__);\n }\n\n std::shared_ptr<SourceDeviceImpl> spSourceDevice = shared_from_this();\n\n return std::shared_ptr<RemoteReleaseControl>(new RemoteReleaseControlImpl(spSourceDevice));\n }\n\n \/\/\/ returns source\n cdHSource GetSource() const throw() { return m_hSource; }\n\nprivate:\n \/\/\/ source device handle\n cdHSource m_hSource;\n\n \/\/\/ SDK ref\n RefSp m_spRef;\n};\n\ninline cdHSource RemoteReleaseControlImpl::GetSource() const throw()\n{\n return m_spSourceDevice->GetSource();\n}\n\ninline cdHSource ViewfinderImpl::GetSource() const throw()\n{\n return m_spSourceDevice->GetSource();\n}\n\n} \/\/ namespace CDSDK\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License as published by the Free Software\n * Foundation; version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\/\n\n#include \"resultview.h\"\n\n#include \"..\/iconmanager.h\"\n\n#include <QModelIndex>\n\nbool ResultView::alternateRows = false;\nQList<ResultView*> ResultView::instances = QList<ResultView*>();\n\nResultView::ResultView(QWidget *parent)\n : QWidget(parent) {\n setupUi(this);\n \/\/ Sincèrement, un jour, il faudra se poser la question de l'utilité de la\n \/\/ ligne suivante :\n table->setModel(0);\n\n \/\/ Par défaut, on visualise\n currentAction = Browse;\n \/\/ Aucun tri\n currentSorting = QPair<int, Qt::SortOrder>(-1, Qt::AscendingOrder);\n \/\/ Nécessaire pour la synchronisation sur l'option d'alternance des lignes\n instances << this;\n \/\/ On commence à la première ligne\n offset = 0;\n \/\/ Purement arbitraire, j'avoue\n m_mode = QueryMode;\n shortModel = new QStandardItemModel(this);\n table->setModel(shortModel);\n table->setAlternatingRowColors(alternateRows);\n\n\/\/ setupMenus();\n setupConnections();\n\n \/\/ loading icons from theme\n firstPageButton->setIcon(IconManager::get(\"go-first\"));\n lastPageButton->setIcon(IconManager::get(\"go-last\"));\n nextPageButton->setIcon(IconManager::get(\"go-next\"));\n prevPageButton->setIcon(IconManager::get(\"go-previous\"));\n reloadButton->setIcon(IconManager::get(\"view-refresh\"));\n insertButton->setIcon(IconManager::get(\"list-add\"));\n deleteButton->setIcon(IconManager::get(\"list-remove\"));\n\n insertButton->setVisible(false);\n deleteButton->setVisible(false);\n}\n\nResultView::~ResultView() {\n instances.removeAll(this);\n}\n\nvoid ResultView::apply() {\n if (modifiedRecords.size() == 0) {\n return;\n }\n\n insertButton->setIcon(IconManager::get(\"list-add\"));\n deleteButton->setIcon(IconManager::get(\"list-remove\"));\n\n QSqlTableModel *tmodel = (QSqlTableModel*) model;\n\n foreach (int row, modifiedRecords.keys()) {\n tmodel->setRecord(row, modifiedRecords[row]);\n }\n\n modifiedRecords.clear();\n\n if (!tmodel->submitAll()) {\n QMessageBox::critical(this, \"Error\", tmodel->lastError().text());\n }\n\n currentAction = Browse;\n tmodel->select();\n updateView();\n}\n\nvoid ResultView::exportContent()\n{\n if (model == 0)\n return;\n\n if (model->columnCount() == 0 || model->rowCount() == 0)\n return;\n\n\/\/ exportWizard = new ExportWizard(model, this);\n if (m_mode == TableMode) {\n exportWizard = new ExportWizard(model, this);\n } else {\n exportWizard = new ExportWizard(m_token, this);\n }\n\n exportWizard->exec();\n}\n\n\/**\n * Clic sur le bouton supprimer : peut annuler l'opération en cours ou supprimer\n * la ligne en cours.\n *\/\nvoid ResultView::on_deleteButton_clicked()\n{\n if(m_mode != TableMode)\n return;\n\n QSqlTableModel *tmodel = (QSqlTableModel*) model;\n\n if (currentAction != Browse) {\n \/\/ Annulation de l'opération en cours\n insertButton->setIcon(IconManager::get(\"list-add\"));\n deleteButton->setIcon(IconManager::get(\"list-remove\"));\n\n currentAction = Browse;\n tmodel->revertAll();\n } else {\n \/\/ suppression des lignes sélectionnées\n QSet<int> rows;\n foreach(QModelIndex i, table->selectionModel()->selectedIndexes())\n rows << (i.row() + offset);\n\n foreach(int r, rows)\n model->removeRow(r);\n\n tmodel->submitAll();\n }\n\n updateView();\n}\n\n\/**\n * Clic sur le bouton d'insertion : peut passer en mode insertion ou valider un\n * ajout\/modif.\n *\/\nvoid ResultView::on_insertButton_clicked()\n{\n if(m_mode != TableMode)\n return;\n\n if (currentAction == Insert || currentAction == Update) {\n apply();\n } else {\n insertButton->setIcon(QIcon());\n insertButton->setText(tr(\"Apply\"));\n deleteButton->setIcon(QIcon());\n deleteButton->setText(tr(\"Cancel\"));\n\n model->insertRow(model->rowCount());\n currentAction = Insert;\n updateView();\n table->scrollToBottom();\n\/\/ table->hold();\n }\n}\n\nvoid ResultView::on_reloadButton_clicked()\n{\n switch (m_mode) {\n case QueryMode:\n emit reloadRequested();\n break;\n\n case TableMode:\n ((QSqlTableModel*) model)->select();\n updateView();\n break;\n }\n}\n\nvoid ResultView::resizeColumnsToContents()\n{\n table->resizeColumnsToContents();\n}\n\nvoid ResultView::resizeRowsToContents()\n{\n table->resizeRowsToContents();\n}\n\nvoid ResultView::scrollBegin()\n{\n offset = 0;\n updateView();\n}\n\nvoid ResultView::scrollDown() {\n offset += resultSpinBox->value();\n updateView();\n}\n\nvoid ResultView::scrollEnd() {\n double last;\n modf(model->rowCount() \/ resultSpinBox->value(), &last);\n\n offset = last * resultSpinBox->value();\n updateView();\n}\n\nvoid ResultView::scrollUp() {\n offset -= resultSpinBox->value();\n updateView();\n}\n\nvoid ResultView::setAlternatingRowColors(bool enable, bool loop) {\n alternateRows = enable;\n table->setAlternatingRowColors(enable);\n\n if (loop) {\n foreach (ResultView *v, instances) {\n if (dynamic_cast<ResultView*>(v) && v != this) {\n v->setAlternatingRowColors(enable, false);\n }\n }\n }\n}\n\nvoid ResultView::setMode(Mode m) {\n m_mode = m;\n reloadButton->setEnabled(true);\n resultSpinBox->setEnabled(true);\n\n switch(m_mode) {\n case QueryMode:\n insertButton->setVisible(false);\n deleteButton->setVisible(false);\n table->setSortingEnabled(false);\n break;\n\n case TableMode:\n insertButton->setVisible(true);\n deleteButton->setVisible(true);\n table->setSortingEnabled(true);\n break;\n }\n}\n\nvoid ResultView::setModel(QSqlQueryModel *model) {\n this->model = model;\n updateView();\n}\n\nbool ResultView::setTable(QString table, QSqlDatabase *db) {\n setMode(TableMode);\n QSqlTableModel *m = new QSqlTableModel(this, *db);\n m->setTable(table);\n m->setEditStrategy(QSqlTableModel::OnManualSubmit);\n m->select();\n if(m->lastError().type() == QSqlError::NoError) {\n setModel(m);\n return true;\n } else {\n QMessageBox::critical(this,\n tr(\"Error\"),\n tr(\"Unable to open the table. Returned error :\\n%1\")\n .arg(m->lastError().text()),\n QMessageBox::Ok);\n return false;\n }\n}\n\nvoid ResultView::setToken(QueryToken *token) {\n setMode(QueryMode);\n m_token = token;\n offset = 0;\n\n setModel(m_token->model());\n}\n\nvoid ResultView::setupConnections() {\n connect(firstPageButton, SIGNAL(clicked()), this, SLOT(scrollBegin()));\n connect(prevPageButton, SIGNAL(clicked()), this, SLOT(scrollUp()));\n connect(nextPageButton, SIGNAL(clicked()), this, SLOT(scrollDown()));\n connect(lastPageButton, SIGNAL(clicked()), this, SLOT(scrollEnd()));\n\n connect(resultSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateView()));\n\n connect(shortModel, SIGNAL(itemChanged(QStandardItem*)),\n this, SLOT(updateItem(QStandardItem*)));\n\n connect(table, SIGNAL(rowLeaved(int)), this, SLOT(apply()));\n connect(table->horizontalHeader(), SIGNAL(sectionClicked(int)),\n this, SLOT(sort(int)));\n connect(table, SIGNAL(alternateRowsRequested(bool)),\n this, SLOT(setAlternatingRowColors(bool)));\n connect(table, SIGNAL(exportRequested()), this, SLOT(exportContent()));\n}\n\nvoid ResultView::sort(int col) {\n if (m_mode == QueryMode) {\n return;\n }\n\n if (currentSorting.first == col) {\n if (currentSorting.second == Qt::AscendingOrder) {\n currentSorting.second = Qt::DescendingOrder;\n } else {\n currentSorting.second = Qt::AscendingOrder;\n }\n } else {\n currentSorting = QPair<int, Qt::SortOrder>(col, Qt::AscendingOrder);\n }\n model->sort(currentSorting.first, currentSorting.second);\n updateView();\n}\n\n\/**\n * Called by the shortmodel's signal dataChanged in order to forward it to the\n * real one.\n *\/\nvoid ResultView::updateItem(QStandardItem *item) {\n if (currentAction == Browse) {\n currentAction = Update;\n insertButton->setIcon(QIcon());\n insertButton->setText(tr(\"Apply\"));\n deleteButton->setIcon(QIcon());\n deleteButton->setText(tr(\"Cancel\"));\n }\n\n QSqlRecord record;\n int row = item->row() + offset;\n if (modifiedRecords.contains(row)) {\n record = modifiedRecords[row];\n } else {\n record = model->record(row);\n }\n record.setValue(item->column(), item->data(Qt::DisplayRole));\n modifiedRecords[row] = record;\n}\n\n\/**\n * Mise à jour pagination\n *\/\nvoid ResultView::updateView() {\n int hpos = table->horizontalScrollBar()->value();\n\n shortModel->clear();\n\n if (!model) {\n return;\n }\n\n for(int i=0; i<model->columnCount(); i++)\n shortModel->setHorizontalHeaderItem(i, new QStandardItem(\n model->headerData(i, Qt::Horizontal).toString()));\n\n if(model->rowCount() == 0)\n return;\n\n \/\/ 1ère ligne à afficher\n int startIndex;\n startIndex = offset;\n if (startIndex > model->rowCount())\n startIndex = model->rowCount() - resultSpinBox->value();\n if (startIndex < 0)\n startIndex = 0;\n\n \/\/ Page en cours, nb de page\n double page, maxpage;\n modf(startIndex \/ resultSpinBox->value(), &page);\n modf(model->rowCount() \/ resultSpinBox->value(), &maxpage);\n pageLabel->setText(tr(\"Page %1\/%2\")\n .arg(page+1)\n .arg(maxpage+1));\n\n \/\/ dernière ligne à afficher\n int endIndex;\n endIndex = startIndex + resultSpinBox->value();\n if (endIndex > model->rowCount())\n endIndex = model->rowCount();\n\n firstPageButton->setEnabled(startIndex > 0);\n prevPageButton->setEnabled(startIndex > 0);\n nextPageButton->setEnabled(endIndex < model->rowCount());\n lastPageButton->setEnabled(endIndex < model->rowCount());\n\n QStandardItem *item;\n QStringList vlabels;\n QSqlRecord r;\n QList<QStandardItem*> row;\n for(int i=startIndex; i<endIndex; i++) {\n row.clear();\n r = model->record(i);\n for(int j=0; j<model->columnCount(); j++) {\n item = new QStandardItem();\n\/\/ if (r.value(j).canConvert(QVariant::String)\n\/\/ && r.value(j).toString().length() > 50) {\n\/\/ QString val = r.value(j).toString();\n\/\/ \/\/ BLOB\n\/\/ item->setData(val.left(47).append(\"...\"), Qt::DisplayRole);\n\/\/ item->setData(val, Qt::ToolTipRole);\n\/\/ item->setEditable(false);\n\/\/ item->setData(true, Qt::UserRole);\n\/\/ } else {\n item->setData(r.value(j), Qt::DisplayRole);\n item->setData(false, Qt::UserRole);\n\/\/ }\n item->setEditable(m_mode == TableMode);\n row << item;\n }\n shortModel->appendRow(row);\n vlabels << QString::number(i+1);\n }\n if(currentAction == Insert) {\n vlabels.removeLast();\n vlabels << \"*\";\n }\n shortModel->setVerticalHeaderLabels(vlabels);\n\n resizeColumnsToContents();\n resizeRowsToContents();\n\n if (m_mode == TableMode) {\n table->horizontalHeader()->setSortIndicatorShown(true);\n table->horizontalHeader()->setSortIndicator(currentSorting.first,\n currentSorting.second);\n }\n\n table->horizontalScrollBar()->setValue(hpos);\n}\n<commit_msg>Défilement vertical auto<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License as published by the Free Software\n * Foundation; version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\/\n\n#include \"resultview.h\"\n\n#include \"..\/iconmanager.h\"\n\n#include <QModelIndex>\n\nbool ResultView::alternateRows = false;\nQList<ResultView*> ResultView::instances = QList<ResultView*>();\n\nResultView::ResultView(QWidget *parent)\n : QWidget(parent) {\n setupUi(this);\n \/\/ Sincèrement, un jour, il faudra se poser la question de l'utilité de la\n \/\/ ligne suivante :\n table->setModel(0);\n\n \/\/ Par défaut, on visualise\n currentAction = Browse;\n \/\/ Aucun tri\n currentSorting = QPair<int, Qt::SortOrder>(-1, Qt::AscendingOrder);\n \/\/ Nécessaire pour la synchronisation sur l'option d'alternance des lignes\n instances << this;\n \/\/ On commence à la première ligne\n offset = 0;\n \/\/ Purement arbitraire, j'avoue\n m_mode = QueryMode;\n shortModel = new QStandardItemModel(this);\n table->setModel(shortModel);\n table->setAlternatingRowColors(alternateRows);\n\n\/\/ setupMenus();\n setupConnections();\n\n \/\/ loading icons from theme\n firstPageButton->setIcon(IconManager::get(\"go-first\"));\n lastPageButton->setIcon(IconManager::get(\"go-last\"));\n nextPageButton->setIcon(IconManager::get(\"go-next\"));\n prevPageButton->setIcon(IconManager::get(\"go-previous\"));\n reloadButton->setIcon(IconManager::get(\"view-refresh\"));\n insertButton->setIcon(IconManager::get(\"list-add\"));\n deleteButton->setIcon(IconManager::get(\"list-remove\"));\n\n insertButton->setVisible(false);\n deleteButton->setVisible(false);\n}\n\nResultView::~ResultView() {\n instances.removeAll(this);\n}\n\nvoid ResultView::apply() {\n if (modifiedRecords.size() == 0) {\n return;\n }\n\n insertButton->setIcon(IconManager::get(\"list-add\"));\n deleteButton->setIcon(IconManager::get(\"list-remove\"));\n\n QSqlTableModel *tmodel = (QSqlTableModel*) model;\n\n foreach (int row, modifiedRecords.keys()) {\n tmodel->setRecord(row, modifiedRecords[row]);\n }\n\n modifiedRecords.clear();\n\n if (!tmodel->submitAll()) {\n QMessageBox::critical(this, \"Error\", tmodel->lastError().text());\n }\n\n currentAction = Browse;\n tmodel->select();\n updateView();\n}\n\nvoid ResultView::exportContent()\n{\n if (model == 0)\n return;\n\n if (model->columnCount() == 0 || model->rowCount() == 0)\n return;\n\n\/\/ exportWizard = new ExportWizard(model, this);\n if (m_mode == TableMode) {\n exportWizard = new ExportWizard(model, this);\n } else {\n exportWizard = new ExportWizard(m_token, this);\n }\n\n exportWizard->exec();\n}\n\n\/**\n * Clic sur le bouton supprimer : peut annuler l'opération en cours ou supprimer\n * la ligne en cours.\n *\/\nvoid ResultView::on_deleteButton_clicked()\n{\n if(m_mode != TableMode)\n return;\n\n QSqlTableModel *tmodel = (QSqlTableModel*) model;\n\n if (currentAction != Browse) {\n \/\/ Annulation de l'opération en cours\n insertButton->setIcon(IconManager::get(\"list-add\"));\n deleteButton->setIcon(IconManager::get(\"list-remove\"));\n\n currentAction = Browse;\n tmodel->revertAll();\n } else {\n \/\/ suppression des lignes sélectionnées\n QSet<int> rows;\n foreach(QModelIndex i, table->selectionModel()->selectedIndexes())\n rows << (i.row() + offset);\n\n foreach(int r, rows)\n model->removeRow(r);\n\n tmodel->submitAll();\n }\n\n updateView();\n}\n\n\/**\n * Clic sur le bouton d'insertion : peut passer en mode insertion ou valider un\n * ajout\/modif.\n *\/\nvoid ResultView::on_insertButton_clicked()\n{\n if(m_mode != TableMode)\n return;\n\n if (currentAction == Insert || currentAction == Update) {\n apply();\n } else {\n insertButton->setIcon(QIcon());\n insertButton->setText(tr(\"Apply\"));\n deleteButton->setIcon(QIcon());\n deleteButton->setText(tr(\"Cancel\"));\n\n model->insertRow(model->rowCount());\n currentAction = Insert;\n updateView();\n table->scrollToBottom();\n\/\/ table->hold();\n }\n}\n\nvoid ResultView::on_reloadButton_clicked()\n{\n switch (m_mode) {\n case QueryMode:\n emit reloadRequested();\n break;\n\n case TableMode:\n ((QSqlTableModel*) model)->select();\n updateView();\n break;\n }\n}\n\nvoid ResultView::resizeColumnsToContents()\n{\n table->resizeColumnsToContents();\n}\n\nvoid ResultView::resizeRowsToContents()\n{\n table->resizeRowsToContents();\n}\n\nvoid ResultView::scrollBegin()\n{\n offset = 0;\n updateView();\n}\n\nvoid ResultView::scrollDown() {\n offset += resultSpinBox->value();\n updateView();\n}\n\nvoid ResultView::scrollEnd() {\n double last;\n modf(model->rowCount() \/ resultSpinBox->value(), &last);\n\n offset = last * resultSpinBox->value();\n updateView();\n}\n\nvoid ResultView::scrollUp() {\n offset -= resultSpinBox->value();\n updateView();\n}\n\nvoid ResultView::setAlternatingRowColors(bool enable, bool loop) {\n alternateRows = enable;\n table->setAlternatingRowColors(enable);\n\n if (loop) {\n foreach (ResultView *v, instances) {\n if (dynamic_cast<ResultView*>(v) && v != this) {\n v->setAlternatingRowColors(enable, false);\n }\n }\n }\n}\n\nvoid ResultView::setMode(Mode m) {\n m_mode = m;\n reloadButton->setEnabled(true);\n resultSpinBox->setEnabled(true);\n\n switch(m_mode) {\n case QueryMode:\n insertButton->setVisible(false);\n deleteButton->setVisible(false);\n table->setSortingEnabled(false);\n break;\n\n case TableMode:\n insertButton->setVisible(true);\n deleteButton->setVisible(true);\n table->setSortingEnabled(true);\n break;\n }\n}\n\nvoid ResultView::setModel(QSqlQueryModel *model) {\n this->model = model;\n updateView();\n}\n\nbool ResultView::setTable(QString table, QSqlDatabase *db) {\n setMode(TableMode);\n QSqlTableModel *m = new QSqlTableModel(this, *db);\n m->setTable(table);\n m->setEditStrategy(QSqlTableModel::OnManualSubmit);\n m->select();\n if(m->lastError().type() == QSqlError::NoError) {\n setModel(m);\n return true;\n } else {\n QMessageBox::critical(this,\n tr(\"Error\"),\n tr(\"Unable to open the table. Returned error :\\n%1\")\n .arg(m->lastError().text()),\n QMessageBox::Ok);\n return false;\n }\n}\n\nvoid ResultView::setToken(QueryToken *token) {\n setMode(QueryMode);\n m_token = token;\n offset = 0;\n\n setModel(m_token->model());\n}\n\nvoid ResultView::setupConnections() {\n connect(firstPageButton, SIGNAL(clicked()), this, SLOT(scrollBegin()));\n connect(prevPageButton, SIGNAL(clicked()), this, SLOT(scrollUp()));\n connect(nextPageButton, SIGNAL(clicked()), this, SLOT(scrollDown()));\n connect(lastPageButton, SIGNAL(clicked()), this, SLOT(scrollEnd()));\n\n connect(resultSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateView()));\n\n connect(shortModel, SIGNAL(itemChanged(QStandardItem*)),\n this, SLOT(updateItem(QStandardItem*)));\n\n connect(table, SIGNAL(rowLeaved(int)), this, SLOT(apply()));\n connect(table->horizontalHeader(), SIGNAL(sectionClicked(int)),\n this, SLOT(sort(int)));\n connect(table, SIGNAL(alternateRowsRequested(bool)),\n this, SLOT(setAlternatingRowColors(bool)));\n connect(table, SIGNAL(exportRequested()), this, SLOT(exportContent()));\n}\n\nvoid ResultView::sort(int col) {\n if (m_mode == QueryMode) {\n return;\n }\n\n if (currentSorting.first == col) {\n if (currentSorting.second == Qt::AscendingOrder) {\n currentSorting.second = Qt::DescendingOrder;\n } else {\n currentSorting.second = Qt::AscendingOrder;\n }\n } else {\n currentSorting = QPair<int, Qt::SortOrder>(col, Qt::AscendingOrder);\n }\n model->sort(currentSorting.first, currentSorting.second);\n updateView();\n}\n\n\/**\n * Called by the shortmodel's signal dataChanged in order to forward it to the\n * real one.\n *\/\nvoid ResultView::updateItem(QStandardItem *item) {\n if (currentAction == Browse) {\n currentAction = Update;\n insertButton->setIcon(QIcon());\n insertButton->setText(tr(\"Apply\"));\n deleteButton->setIcon(QIcon());\n deleteButton->setText(tr(\"Cancel\"));\n }\n\n QSqlRecord record;\n int row = item->row() + offset;\n if (modifiedRecords.contains(row)) {\n record = modifiedRecords[row];\n } else {\n record = model->record(row);\n }\n record.setValue(item->column(), item->data(Qt::DisplayRole));\n modifiedRecords[row] = record;\n}\n\n\/**\n * Mise à jour pagination\n *\/\nvoid ResultView::updateView() {\n int hpos = table->horizontalScrollBar()->value();\n int vpos = table->verticalScrollBar()->value();\n\n shortModel->clear();\n\n if (!model) {\n return;\n }\n\n for(int i=0; i<model->columnCount(); i++)\n shortModel->setHorizontalHeaderItem(i, new QStandardItem(\n model->headerData(i, Qt::Horizontal).toString()));\n\n if(model->rowCount() == 0)\n return;\n\n \/\/ 1ère ligne à afficher\n int startIndex;\n startIndex = offset;\n if (startIndex > model->rowCount())\n startIndex = model->rowCount() - resultSpinBox->value();\n if (startIndex < 0)\n startIndex = 0;\n\n \/\/ Page en cours, nb de page\n double page, maxpage;\n modf(startIndex \/ resultSpinBox->value(), &page);\n modf(model->rowCount() \/ resultSpinBox->value(), &maxpage);\n pageLabel->setText(tr(\"Page %1\/%2\")\n .arg(page+1)\n .arg(maxpage+1));\n\n \/\/ dernière ligne à afficher\n int endIndex;\n endIndex = startIndex + resultSpinBox->value();\n if (endIndex > model->rowCount())\n endIndex = model->rowCount();\n\n firstPageButton->setEnabled(startIndex > 0);\n prevPageButton->setEnabled(startIndex > 0);\n nextPageButton->setEnabled(endIndex < model->rowCount());\n lastPageButton->setEnabled(endIndex < model->rowCount());\n\n QStandardItem *item;\n QStringList vlabels;\n QSqlRecord r;\n QList<QStandardItem*> row;\n for(int i=startIndex; i<endIndex; i++) {\n row.clear();\n r = model->record(i);\n for(int j=0; j<model->columnCount(); j++) {\n item = new QStandardItem();\n\/\/ if (r.value(j).canConvert(QVariant::String)\n\/\/ && r.value(j).toString().length() > 50) {\n\/\/ QString val = r.value(j).toString();\n\/\/ \/\/ BLOB\n\/\/ item->setData(val.left(47).append(\"...\"), Qt::DisplayRole);\n\/\/ item->setData(val, Qt::ToolTipRole);\n\/\/ item->setEditable(false);\n\/\/ item->setData(true, Qt::UserRole);\n\/\/ } else {\n item->setData(r.value(j), Qt::DisplayRole);\n item->setData(false, Qt::UserRole);\n\/\/ }\n item->setEditable(m_mode == TableMode);\n row << item;\n }\n shortModel->appendRow(row);\n vlabels << QString::number(i+1);\n }\n if(currentAction == Insert) {\n vlabels.removeLast();\n vlabels << \"*\";\n }\n shortModel->setVerticalHeaderLabels(vlabels);\n\n resizeColumnsToContents();\n resizeRowsToContents();\n\n if (m_mode == TableMode) {\n table->horizontalHeader()->setSortIndicatorShown(true);\n table->horizontalHeader()->setSortIndicator(currentSorting.first,\n currentSorting.second);\n }\n\n table->horizontalScrollBar()->setValue(hpos);\n table->verticalScrollBar()->setValue(vpos);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n\n#include \"EC_PhysicsMotor.h\"\n#include \"EC_RigidBody.h\"\n#include \"EC_Placeable.h\"\n#include \"Entity.h\"\n#include \"Scene\/Scene.h\"\n#include \"PhysicsModule.h\"\n#include \"PhysicsWorld.h\"\n#include \"PhysicsUtils.h\"\n#include \"LoggingFunctions.h\"\n#include \"Profiler.h\"\n\n#include \"MemoryLeakCheck.h\"\n\nusing namespace Physics;\n\nEC_PhysicsMotor::EC_PhysicsMotor(Scene* scene) :\n IComponent(scene),\n INIT_ATTRIBUTE_VALUE(absoluteMoveForce, \"Absolute Move Force\", float3::zero),\n INIT_ATTRIBUTE_VALUE(relativeMoveForce, \"Relative Move Force\", float3::zero),\n INIT_ATTRIBUTE_VALUE(dampingForce, \"Damping Force\", float3::zero)\n{\n connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()), Qt::UniqueConnection);\n}\n\nEC_PhysicsMotor::~EC_PhysicsMotor()\n{\n}\n\nvoid EC_PhysicsMotor::UpdateSignals()\n{\n Entity* parent = ParentEntity();\n if (!parent)\n return;\n Scene* scene = parent->ParentScene();\n PhysicsWorld* world = scene->GetWorld<PhysicsWorld>().get();\n if (world)\n connect(world, SIGNAL(Updated(float)), this, SLOT(OnPhysicsUpdate()), Qt::UniqueConnection);\n \n connect(parent, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), this, SLOT(OnComponentStructureChanged()), Qt::UniqueConnection);\n connect(parent, SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), this, SLOT(OnComponentStructureChanged()), Qt::UniqueConnection);\n OnComponentStructureChanged(); \/\/ Check for Rigidbody & Placeable immediately\n}\n\nvoid EC_PhysicsMotor::OnComponentStructureChanged()\n{\n Entity* parent = ParentEntity();\n if (!parent)\n return;\n rigidBody_ = parent->GetComponent<EC_RigidBody>();\n placeable_ = parent->GetComponent<EC_Placeable>();\n}\n\nvoid EC_PhysicsMotor::OnPhysicsUpdate()\n{\n PROFILE(EC_PhysicsMotor_OnPhysicsUpdate);\n \n EC_RigidBody* body = rigidBody_.lock().get();\n EC_Placeable* placeable = placeable_.lock().get();\n \n if (body && placeable)\n {\n float3 absolute = absoluteMoveForce.Get();\n if (!absolute.Equals(float3::zero))\n body->ApplyImpulse(absolute);\n \n float3 relative = relativeMoveForce.Get();\n if (!relative.Equals(float3::zero))\n {\n float3 translate, scale;\n Quat rot;\n \n placeable->LocalToWorld().Decompose(translate, rot, scale);\n relative = rot * relative;\n body->ApplyImpulse(relative);\n }\n \n float3 damping = dampingForce.Get();\n if (!damping.Equals(float3::zero))\n {\n damping = -body->GetLinearVelocity() * damping;\n body->ApplyImpulse(damping);\n }\n }\n}\n<commit_msg>Use float3.Mul() instead of operator * to avoid ambiguous function call.<commit_after>\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n\n#include \"EC_PhysicsMotor.h\"\n#include \"EC_RigidBody.h\"\n#include \"EC_Placeable.h\"\n#include \"Entity.h\"\n#include \"Scene\/Scene.h\"\n#include \"PhysicsModule.h\"\n#include \"PhysicsWorld.h\"\n#include \"PhysicsUtils.h\"\n#include \"LoggingFunctions.h\"\n#include \"Profiler.h\"\n\n#include \"MemoryLeakCheck.h\"\n\nusing namespace Physics;\n\nEC_PhysicsMotor::EC_PhysicsMotor(Scene* scene) :\n IComponent(scene),\n INIT_ATTRIBUTE_VALUE(absoluteMoveForce, \"Absolute Move Force\", float3::zero),\n INIT_ATTRIBUTE_VALUE(relativeMoveForce, \"Relative Move Force\", float3::zero),\n INIT_ATTRIBUTE_VALUE(dampingForce, \"Damping Force\", float3::zero)\n{\n connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()), Qt::UniqueConnection);\n}\n\nEC_PhysicsMotor::~EC_PhysicsMotor()\n{\n}\n\nvoid EC_PhysicsMotor::UpdateSignals()\n{\n Entity* parent = ParentEntity();\n if (!parent)\n return;\n Scene* scene = parent->ParentScene();\n PhysicsWorld* world = scene->GetWorld<PhysicsWorld>().get();\n if (world)\n connect(world, SIGNAL(Updated(float)), this, SLOT(OnPhysicsUpdate()), Qt::UniqueConnection);\n \n connect(parent, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), this, SLOT(OnComponentStructureChanged()), Qt::UniqueConnection);\n connect(parent, SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), this, SLOT(OnComponentStructureChanged()), Qt::UniqueConnection);\n OnComponentStructureChanged(); \/\/ Check for Rigidbody & Placeable immediately\n}\n\nvoid EC_PhysicsMotor::OnComponentStructureChanged()\n{\n Entity* parent = ParentEntity();\n if (!parent)\n return;\n rigidBody_ = parent->GetComponent<EC_RigidBody>();\n placeable_ = parent->GetComponent<EC_Placeable>();\n}\n\nvoid EC_PhysicsMotor::OnPhysicsUpdate()\n{\n PROFILE(EC_PhysicsMotor_OnPhysicsUpdate);\n \n EC_RigidBody* body = rigidBody_.lock().get();\n EC_Placeable* placeable = placeable_.lock().get();\n \n if (body && placeable)\n {\n float3 absolute = absoluteMoveForce.Get();\n if (!absolute.Equals(float3::zero))\n body->ApplyImpulse(absolute);\n \n float3 relative = relativeMoveForce.Get();\n if (!relative.Equals(float3::zero))\n {\n float3 translate, scale;\n Quat rot;\n \n placeable->LocalToWorld().Decompose(translate, rot, scale);\n relative = rot * relative;\n body->ApplyImpulse(relative);\n }\n \n float3 damping = dampingForce.Get();\n if (!damping.Equals(float3::zero))\n {\n damping = -body->GetLinearVelocity().Mul(damping);\n body->ApplyImpulse(damping);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>class MicroStrings {\npublic:\n\tstring makeMicroString(int, int);\n}\n<commit_msg>untested solution<commit_after>#include <string>\n#include <vector>\n#include <sstream>\nusing namespace std;\n\nclass MicroStrings {\npublic:\n\tstring makeMicroString(int, int);\n}\n\nstring MicroStrings::makeMicroString(int A, int D) {\n\tvector<int> nums;\n\tint n = A \/ D;\n\tfor (int i = 0; i <= n; i++) nums.push_back(A - i * D);\n\t\n\tstringstream ss;\n\tfor (int i = 0; i < nums.size(); i++) ss << nums[i];\n\t\n\treturn ss.str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ LanguageDlg.cpp : implementation file\r\n\/\/\r\n\r\n#include \"LanguageDlg.h\"\r\n#include \"TolonSpellCheckInternals.h\"\r\n#include \"tscSession.h\"\r\n#include <iostream>\r\n#include <string>\r\n#include <sstream>\r\n#include <windows.h>\r\n#include <commctrl.h>\r\n#include <assert.h>\r\n\r\nextern HINSTANCE g_hInstDll;\r\n\r\nusing namespace TolonSpellCheck;\r\nusing namespace std;\r\n\r\nstatic enum COLUMNS {\r\n COL_CODE,\r\n COL_NAME,\r\n \r\n COLUMN_COUNT\r\n};\r\n\r\nstatic struct COLUMN_DATA {\r\n int Id;\r\n int Width;\r\n const wchar_t* Name;\r\n} s_columns[COLUMN_COUNT] = {\r\n { COL_CODE, 80, L\"Code\" },\r\n { COL_NAME, LVSCW_AUTOSIZE_USEHEADER, L\"Language\" }\r\n};\r\n\r\n\/\/static const int s_nColDisplayName;\r\n\/\/static const int s_nColCodeName;\r\n\r\nstatic const bool s_bDefaultSortAsc = true;\r\n\r\n\/\/ CLanguageDlg dialog\r\n\r\nstatic CLanguageDlg* s_pThis;\r\n\r\nbool CLanguageDlg::LangEnumCallback(LANGUAGE_DESC_WIDEDATA* pData, void* pUserData)\r\n{\r\n bool bResult = false;\r\n \r\n CLanguageDlg* pThis = reinterpret_cast<CLanguageDlg*>(pUserData);\r\n \r\n if (pData && pThis)\r\n {\r\n LVITEM lvi = {0};\r\n \r\n lvi.mask = LVIF_TEXT;\r\n lvi.iItem = 0;\r\n \r\n lvi.iSubItem = COL_CODE;\r\n lvi.pszText = pData->wszCodeName;\r\n ListView_InsertItem(pThis->GetLangListHwnd(), &lvi);\r\n \r\n ListView_SetItemText(pThis->GetLangListHwnd(), lvi.iItem, COL_NAME, pData->wszDisplayName);\r\n \r\n bResult = true;\r\n }\r\n \r\n return bResult;\r\n}\r\n\r\nCLanguageDlg::CLanguageDlg(TolonSpellCheck::CSession* pSession, HWND hwndParent \/*=NULL*\/) :\r\n m_pSession(pSession),\r\n m_hwnd(NULL),\r\n m_hwndParent(hwndParent),\r\n m_hwndLangList(NULL)\r\n{\r\n m_SortOptions.bAsc = s_bDefaultSortAsc;\r\n m_SortOptions.nCol = COL_NAME;\r\n}\r\n\r\nCLanguageDlg::~CLanguageDlg()\r\n{\r\n}\r\n\r\nint CLanguageDlg::DoModal()\r\n{\r\n s_pThis = this;\r\n DialogBox(g_hInstDll, MAKEINTRESOURCE(CLanguageDlg::IDD), m_hwndParent, CLanguageDlg::WndProc);\r\n return 0;\r\n}\r\n\r\n\/\/ CLanguageDlg message handlers\r\nBOOL CLanguageDlg::OnInitDialog()\r\n{\r\n \/\/ Sort out controls\r\n InitLangList();\r\n \r\n \/\/ Populate language list\r\n m_pSession->EnumLanguages(static_cast<LanguageEnumFn>(&CLanguageDlg::LangEnumCallback), this);\r\n \r\n \/\/ Fix up language list now it's populated with data\r\n ListView_SetColumnWidth(GetLangListHwnd(), 0, LVSCW_AUTOSIZE);\r\n ListView_SortItemsEx(GetLangListHwnd(), &CompareFunc, reinterpret_cast<LPARAM>(this));\r\n \r\n \/\/ Get default language\r\n UpdateLanguageDisplay();\r\n \r\n return TRUE;\r\n}\r\n\r\nvoid CLanguageDlg::InitLangList()\r\n{\r\n assert(m_hwnd);\r\n \r\n if (!m_hwnd)\r\n return;\r\n \r\n \/\/ Obtain HWND\r\n m_hwndLangList = GetDlgItem(IDC_DIC_LIST);\r\n\r\n \/\/ Set styles\r\n ListView_SetExtendedListViewStyleEx(GetLangListHwnd(), LVS_EX_FULLROWSELECT, LVS_EX_FULLROWSELECT);\r\n \r\n \/\/ Set up columns\r\n LVCOLUMN lvc = {0};\r\n lvc.mask = LVCF_TEXT;\r\n int nItem = 0;\r\n \r\n for ( int i = 0; i < COLUMN_COUNT; ++i )\r\n {\r\n lvc.pszText = const_cast<wchar_t*>(s_columns[i].Name);\r\n nItem = ListView_InsertColumn(GetLangListHwnd(), s_columns[i].Id, &lvc);\r\n ListView_SetColumnWidth(GetLangListHwnd(), nItem, s_columns[i].Width);\r\n }\r\n}\r\n\r\nint CALLBACK CLanguageDlg::WndProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n BOOL bHandled = FALSE;\r\n \r\n if (!s_pThis)\r\n return 0;\r\n \r\n if (!s_pThis->m_hwnd)\r\n s_pThis->m_hwnd = hDlg;\r\n \r\n switch (message)\r\n {\r\n case WM_COMMAND:\r\n {\r\n const WORD nCmd = LOWORD(wParam);\r\n \r\n if (nCmd == IDOK)\r\n { \r\n s_pThis->OnCmdOk();\r\n EndDialog(hDlg, nCmd);\r\n }\r\n else if (nCmd == IDCANCEL)\r\n {\r\n s_pThis->OnCmdCancel();\r\n EndDialog(hDlg, nCmd);\r\n }\r\n else if (nCmd == IDC_MAKEDEFAULT_BTN)\r\n { s_pThis->OnCmdMakeDefault(); }\r\n \r\n bHandled = TRUE;\r\n \r\n break;\r\n }\r\n\r\n case WM_INITDIALOG:\r\n return s_pThis->OnInitDialog();\r\n\r\n case WM_NOTIFY:\r\n switch (((LPNMHDR)lParam)->code)\r\n {\r\n case LVN_COLUMNCLICK:\r\n if (((LPNMHDR)lParam)->idFrom == IDC_DIC_LIST)\r\n {\r\n s_pThis->OnDicListColClick(lParam);\r\n return TRUE;\r\n }\r\n break; \r\n break;\r\n }\r\n }\r\n \r\n return bHandled;\r\n}\r\n\r\nvoid CLanguageDlg::OnCmdOk()\r\n{\r\n TolonSpellCheck::CSession* pSession = GetSession();\r\n\r\n if (!pSession)\r\n {\r\n ::MessageBox(GetHwnd(), L\"Internal Error. Could not set the chosen dictionary.\", L\"TolonSpellCheck\", MB_OK | MB_ICONEXCLAMATION);\r\n return;\r\n }\r\n else\r\n {\r\n string sChosenLang;\r\n\r\n \/\/ Get chosen language\r\n GetChosenLanguage(sChosenLang);\r\n \r\n \/\/ Set it on the session\r\n tsc_result r = TSC_E_FAIL;\r\n r = pSession->SetLanguage(sChosenLang.c_str());\r\n\r\n if (TSC_FAILED(r))\r\n {\r\n ::MessageBox(GetHwnd(), L\"Failed to set new language. :(\", L\"TolonSpellCheckLib\", MB_OK | MB_ICONEXCLAMATION);\r\n }\r\n }\r\n}\r\n\r\nvoid CLanguageDlg::OnCmdCancel()\r\n{\r\n}\r\n\r\nvoid CLanguageDlg::OnCmdMakeDefault()\r\n{\r\n}\r\n\r\nvoid CLanguageDlg::GetChosenLanguage(string& sLang)\r\n{\r\n int nItem = -1;\r\n nItem = ListView_GetNextItem(GetLangListHwnd(), -1, LVNI_SELECTED);\r\n\r\n if (nItem != -1)\r\n {\r\n const int nBufLen = 13;\r\n wchar_t wszBuf[nBufLen] = L\"\\0\";\r\n\r\n ListView_GetItemText( GetLangListHwnd(),\r\n nItem,\r\n COL_CODE,\r\n &wszBuf[0],\r\n nBufLen );\r\n\r\n char szBuffer[nBufLen] = \"\\0\";\r\n ::WideCharToMultiByte(CP_UTF8, 0, wszBuf, -1, szBuffer, nBufLen, NULL, NULL);\r\n\r\n sLang.assign(szBuffer);\r\n }\r\n}\r\n\r\nvoid CLanguageDlg::UpdateLanguageDisplay()\r\n{\r\n TolonSpellCheck::CSession* pSession = GetSession();\r\n\r\n if (pSession)\r\n {\r\n tsc_result result = TSC_S_OK;\r\n\r\n LANGUAGE_DESC_WIDEDATA ldwd;\r\n wchar_t wszLang[13];\r\n memset(&ldwd, 0, sizeof(LANGUAGE_DESC_WIDEDATA));\r\n memset(wszLang, 0, sizeof(wszLang));\r\n \r\n ldwd.cbSize = sizeof(LANGUAGE_DESC_WIDEDATA); \r\n result = pSession->GetCurrentLanguage(wszLang);\r\n \r\n if (TSC_SUCCEEDED(result))\r\n {\r\n result = m_pSession->DescribeLanguage(wszLang, &ldwd);\r\n \r\n if (TSC_SUCCEEDED(result))\r\n {\r\n HWND hwnd = GetDlgItem(IDC_DEFAULTLANG_STATIC);\r\n if (hwnd)\r\n {\r\n wstring ws(L\"Default: \");\r\n ws.append(ldwd.wszDisplayName);\r\n SetWindowText(hwnd, ws.c_str());\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nHWND CLanguageDlg::GetDlgItem(int nDlgItem) const\r\n{\r\n HWND hMain = GetHwnd();\r\n HWND hItem = NULL;\r\n\r\n if (hMain)\r\n {\r\n hItem = ::GetDlgItem(hMain, nDlgItem);\r\n }\r\n\r\n assert(hItem != NULL);\r\n return hItem;\r\n}\r\n\r\nHWND CLanguageDlg::GetHwnd() const\r\n{ \r\n assert(m_hwnd != NULL);\r\n return m_hwnd;\r\n}\r\n\r\nHWND CLanguageDlg::GetLangListHwnd() const\r\n{ \r\n assert(m_hwndLangList != NULL);\r\n return m_hwndLangList;\r\n}\r\n\r\nTolonSpellCheck::CSession* CLanguageDlg::GetSession() const\r\n{ \r\n assert(m_pSession != NULL);\r\n return m_pSession;\r\n}\r\n\r\n\/\/! @param lParam1 The list view index of the first item to compare.\r\n\/\/! @param lParam2 The list view index of the second item to compare.\r\n\/\/! @param lParamSort Indicates the order of the sort; ascending or descending.\r\nint CALLBACK CLanguageDlg::CompareFunc( LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort ) \r\n{\r\n CLanguageDlg* pThis = reinterpret_cast<CLanguageDlg*>(lParamSort);\r\n const size_t nTextBufferLength = 64;\r\n static wchar_t sText1[nTextBufferLength], sText2[nTextBufferLength];\r\n \r\n const int nSortColumn = pThis->m_SortOptions.nCol;\r\n const bool bAsc = pThis->m_SortOptions.bAsc;\r\n \r\n sText1[0] = L'\\0';\r\n ListView_GetItemText( pThis->GetLangListHwnd(), lParam1, nSortColumn, sText1, nTextBufferLength );\r\n sText2[0] = L'\\0';\r\n ListView_GetItemText( pThis->GetLangListHwnd(), lParam2, nSortColumn, sText2, nTextBufferLength );\r\n \r\n \/\/ We're dealing with a windows user interface, so use the Win32 string comparison.\r\n int nComp = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE, sText1, wcslen(sText1), sText2, wcslen(sText2) );\r\n\r\n \/\/ CompareString documentation says substract 2 to return standard <0, ==0, and >0 values.\r\n nComp = nComp - 2;\r\n if (bAsc)\r\n return -nComp;\r\n else\r\n return nComp;\r\n}\r\n\r\nvoid CLanguageDlg::OnDicListColClick(LPARAM lParam)\r\n{\r\n const NMLISTVIEW* pnmlv = reinterpret_cast<const NMLISTVIEW*>(lParam);\r\n\r\n if (pnmlv->iSubItem == m_SortOptions.nCol)\r\n {\r\n m_SortOptions.bAsc = !m_SortOptions.bAsc;\r\n }\r\n else\r\n {\r\n m_SortOptions.nCol = pnmlv->iSubItem;\r\n }\r\n\r\n ListView_SortItemsEx(GetLangListHwnd(), &CompareFunc, reinterpret_cast<LPARAM>(this));\r\n}\r\n<commit_msg>Completed CompareProc logic<commit_after>\/\/ LanguageDlg.cpp : implementation file\r\n\/\/\r\n\r\n#include \"LanguageDlg.h\"\r\n#include \"TolonSpellCheckInternals.h\"\r\n#include \"tscSession.h\"\r\n#include <iostream>\r\n#include <string>\r\n#include <sstream>\r\n#include <windows.h>\r\n#include <commctrl.h>\r\n#include <assert.h>\r\n\r\nextern HINSTANCE g_hInstDll;\r\n\r\nusing namespace TolonSpellCheck;\r\nusing namespace std;\r\n\r\nstatic enum COLUMNS {\r\n COL_CODE,\r\n COL_NAME,\r\n \r\n COLUMN_COUNT\r\n};\r\n\r\nstatic struct COLUMN_DATA {\r\n int Id;\r\n int Width;\r\n const wchar_t* Name;\r\n} s_columns[COLUMN_COUNT] = {\r\n { COL_CODE, 80, L\"Code\" },\r\n { COL_NAME, LVSCW_AUTOSIZE_USEHEADER, L\"Language\" }\r\n};\r\n\r\n\/\/static const int s_nColDisplayName;\r\n\/\/static const int s_nColCodeName;\r\n\r\nstatic const bool s_bDefaultSortAsc = true;\r\n\r\n\/\/ CLanguageDlg dialog\r\n\r\nstatic CLanguageDlg* s_pThis;\r\n\r\nbool CLanguageDlg::LangEnumCallback(LANGUAGE_DESC_WIDEDATA* pData, void* pUserData)\r\n{\r\n bool bResult = false;\r\n \r\n CLanguageDlg* pThis = reinterpret_cast<CLanguageDlg*>(pUserData);\r\n \r\n if (pData && pThis)\r\n {\r\n LVITEM lvi = {0};\r\n \r\n lvi.mask = LVIF_TEXT;\r\n lvi.iItem = 0;\r\n \r\n lvi.iSubItem = COL_CODE;\r\n lvi.pszText = pData->wszCodeName;\r\n ListView_InsertItem(pThis->GetLangListHwnd(), &lvi);\r\n \r\n ListView_SetItemText(pThis->GetLangListHwnd(), lvi.iItem, COL_NAME, pData->wszDisplayName);\r\n \r\n bResult = true;\r\n }\r\n \r\n return bResult;\r\n}\r\n\r\nCLanguageDlg::CLanguageDlg(TolonSpellCheck::CSession* pSession, HWND hwndParent \/*=NULL*\/) :\r\n m_pSession(pSession),\r\n m_hwnd(NULL),\r\n m_hwndParent(hwndParent),\r\n m_hwndLangList(NULL)\r\n{\r\n m_SortOptions.bAsc = s_bDefaultSortAsc;\r\n m_SortOptions.nCol = COL_NAME;\r\n}\r\n\r\nCLanguageDlg::~CLanguageDlg()\r\n{\r\n}\r\n\r\nint CLanguageDlg::DoModal()\r\n{\r\n s_pThis = this;\r\n DialogBox(g_hInstDll, MAKEINTRESOURCE(CLanguageDlg::IDD), m_hwndParent, CLanguageDlg::WndProc);\r\n return 0;\r\n}\r\n\r\n\/\/ CLanguageDlg message handlers\r\nBOOL CLanguageDlg::OnInitDialog()\r\n{\r\n \/\/ Sort out controls\r\n InitLangList();\r\n \r\n \/\/ Populate language list\r\n m_pSession->EnumLanguages(static_cast<LanguageEnumFn>(&CLanguageDlg::LangEnumCallback), this);\r\n \r\n \/\/ Fix up language list now it's populated with data\r\n ListView_SetColumnWidth(GetLangListHwnd(), 0, LVSCW_AUTOSIZE);\r\n ListView_SortItemsEx(GetLangListHwnd(), &CompareFunc, reinterpret_cast<LPARAM>(this));\r\n \r\n \/\/ Get default language\r\n UpdateLanguageDisplay();\r\n \r\n return TRUE;\r\n}\r\n\r\nvoid CLanguageDlg::InitLangList()\r\n{\r\n assert(m_hwnd);\r\n \r\n if (!m_hwnd)\r\n return;\r\n \r\n \/\/ Obtain HWND\r\n m_hwndLangList = GetDlgItem(IDC_DIC_LIST);\r\n\r\n \/\/ Set styles\r\n ListView_SetExtendedListViewStyleEx(GetLangListHwnd(), LVS_EX_FULLROWSELECT, LVS_EX_FULLROWSELECT);\r\n \r\n \/\/ Set up columns\r\n LVCOLUMN lvc = {0};\r\n lvc.mask = LVCF_TEXT;\r\n int nItem = 0;\r\n \r\n for ( int i = 0; i < COLUMN_COUNT; ++i )\r\n {\r\n lvc.pszText = const_cast<wchar_t*>(s_columns[i].Name);\r\n nItem = ListView_InsertColumn(GetLangListHwnd(), s_columns[i].Id, &lvc);\r\n ListView_SetColumnWidth(GetLangListHwnd(), nItem, s_columns[i].Width);\r\n }\r\n}\r\n\r\nint CALLBACK CLanguageDlg::WndProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n BOOL bHandled = FALSE;\r\n \r\n if (!s_pThis)\r\n return 0;\r\n \r\n if (!s_pThis->m_hwnd)\r\n s_pThis->m_hwnd = hDlg;\r\n \r\n switch (message)\r\n {\r\n case WM_COMMAND:\r\n {\r\n const WORD nCmd = LOWORD(wParam);\r\n \r\n if (nCmd == IDOK)\r\n { \r\n s_pThis->OnCmdOk();\r\n EndDialog(hDlg, nCmd);\r\n }\r\n else if (nCmd == IDCANCEL)\r\n {\r\n s_pThis->OnCmdCancel();\r\n EndDialog(hDlg, nCmd);\r\n }\r\n else if (nCmd == IDC_MAKEDEFAULT_BTN)\r\n { s_pThis->OnCmdMakeDefault(); }\r\n \r\n bHandled = TRUE;\r\n \r\n break;\r\n }\r\n\r\n case WM_INITDIALOG:\r\n return s_pThis->OnInitDialog();\r\n\r\n case WM_NOTIFY:\r\n switch (((LPNMHDR)lParam)->code)\r\n {\r\n case LVN_COLUMNCLICK:\r\n if (((LPNMHDR)lParam)->idFrom == IDC_DIC_LIST)\r\n {\r\n s_pThis->OnDicListColClick(lParam);\r\n return TRUE;\r\n }\r\n break; \r\n break;\r\n }\r\n }\r\n \r\n return bHandled;\r\n}\r\n\r\nvoid CLanguageDlg::OnCmdOk()\r\n{\r\n TolonSpellCheck::CSession* pSession = GetSession();\r\n\r\n if (!pSession)\r\n {\r\n ::MessageBox(GetHwnd(), L\"Internal Error. Could not set the chosen dictionary.\", L\"TolonSpellCheck\", MB_OK | MB_ICONEXCLAMATION);\r\n return;\r\n }\r\n else\r\n {\r\n string sChosenLang;\r\n\r\n \/\/ Get chosen language\r\n GetChosenLanguage(sChosenLang);\r\n \r\n \/\/ Set it on the session\r\n tsc_result r = TSC_E_FAIL;\r\n r = pSession->SetLanguage(sChosenLang.c_str());\r\n\r\n if (TSC_FAILED(r))\r\n {\r\n ::MessageBox(GetHwnd(), L\"Failed to set new language. :(\", L\"TolonSpellCheckLib\", MB_OK | MB_ICONEXCLAMATION);\r\n }\r\n }\r\n}\r\n\r\nvoid CLanguageDlg::OnCmdCancel()\r\n{\r\n}\r\n\r\nvoid CLanguageDlg::OnCmdMakeDefault()\r\n{\r\n}\r\n\r\nvoid CLanguageDlg::GetChosenLanguage(string& sLang)\r\n{\r\n int nItem = -1;\r\n nItem = ListView_GetNextItem(GetLangListHwnd(), -1, LVNI_SELECTED);\r\n\r\n if (nItem != -1)\r\n {\r\n const int nBufLen = 13;\r\n wchar_t wszBuf[nBufLen] = L\"\\0\";\r\n\r\n ListView_GetItemText( GetLangListHwnd(),\r\n nItem,\r\n COL_CODE,\r\n &wszBuf[0],\r\n nBufLen );\r\n\r\n char szBuffer[nBufLen] = \"\\0\";\r\n ::WideCharToMultiByte(CP_UTF8, 0, wszBuf, -1, szBuffer, nBufLen, NULL, NULL);\r\n\r\n sLang.assign(szBuffer);\r\n }\r\n}\r\n\r\nvoid CLanguageDlg::UpdateLanguageDisplay()\r\n{\r\n TolonSpellCheck::CSession* pSession = GetSession();\r\n\r\n if (pSession)\r\n {\r\n tsc_result result = TSC_S_OK;\r\n\r\n LANGUAGE_DESC_WIDEDATA ldwd;\r\n wchar_t wszLang[13];\r\n memset(&ldwd, 0, sizeof(LANGUAGE_DESC_WIDEDATA));\r\n memset(wszLang, 0, sizeof(wszLang));\r\n \r\n ldwd.cbSize = sizeof(LANGUAGE_DESC_WIDEDATA); \r\n result = pSession->GetCurrentLanguage(wszLang);\r\n \r\n if (TSC_SUCCEEDED(result))\r\n {\r\n result = m_pSession->DescribeLanguage(wszLang, &ldwd);\r\n \r\n if (TSC_SUCCEEDED(result))\r\n {\r\n HWND hwnd = GetDlgItem(IDC_DEFAULTLANG_STATIC);\r\n if (hwnd)\r\n {\r\n wstring ws(L\"Default: \");\r\n ws.append(ldwd.wszDisplayName);\r\n SetWindowText(hwnd, ws.c_str());\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nHWND CLanguageDlg::GetDlgItem(int nDlgItem) const\r\n{\r\n HWND hMain = GetHwnd();\r\n HWND hItem = NULL;\r\n\r\n if (hMain)\r\n {\r\n hItem = ::GetDlgItem(hMain, nDlgItem);\r\n }\r\n\r\n assert(hItem != NULL);\r\n return hItem;\r\n}\r\n\r\nHWND CLanguageDlg::GetHwnd() const\r\n{ \r\n assert(m_hwnd != NULL);\r\n return m_hwnd;\r\n}\r\n\r\nHWND CLanguageDlg::GetLangListHwnd() const\r\n{ \r\n assert(m_hwndLangList != NULL);\r\n return m_hwndLangList;\r\n}\r\n\r\nTolonSpellCheck::CSession* CLanguageDlg::GetSession() const\r\n{ \r\n assert(m_pSession != NULL);\r\n return m_pSession;\r\n}\r\n\r\n\/\/! @param lParam1 The list view index of the first item to compare.\r\n\/\/! @param lParam2 The list view index of the second item to compare.\r\n\/\/! @param lParamSort Indicates the order of the sort; ascending or descending.\r\nint CALLBACK CLanguageDlg::CompareFunc( LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort ) \r\n{\r\n CLanguageDlg* pThis = reinterpret_cast<CLanguageDlg*>(lParamSort);\r\n const size_t nTextBufferLength = 64;\r\n static wchar_t sText1[nTextBufferLength], sText2[nTextBufferLength];\r\n \r\n const int nSortColumn = pThis->m_SortOptions.nCol;\r\n const bool bAsc = pThis->m_SortOptions.bAsc;\r\n \r\n sText1[0] = L'\\0';\r\n ListView_GetItemText( pThis->GetLangListHwnd(), lParam1, nSortColumn, sText1, nTextBufferLength );\r\n sText2[0] = L'\\0';\r\n ListView_GetItemText( pThis->GetLangListHwnd(), lParam2, nSortColumn, sText2, nTextBufferLength );\r\n \r\n \/\/ We're dealing with a windows user interface, so use the Win32 string comparison.\r\n int nComp = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE, sText1, wcslen(sText1), sText2, wcslen(sText2) );\r\n\r\n \/\/ CompareString documentation says substract 2 to return standard <0, ==0, and >0 values.\r\n nComp = nComp - 2;\r\n if (bAsc)\r\n return nComp;\r\n else\r\n return -nComp;\r\n}\r\n\r\nvoid CLanguageDlg::OnDicListColClick(LPARAM lParam)\r\n{\r\n const NMLISTVIEW* pnmlv = reinterpret_cast<const NMLISTVIEW*>(lParam);\r\n\r\n if (pnmlv->iSubItem == m_SortOptions.nCol)\r\n {\r\n m_SortOptions.bAsc = !m_SortOptions.bAsc;\r\n }\r\n else\r\n {\r\n m_SortOptions.nCol = pnmlv->iSubItem;\r\n }\r\n\r\n ListView_SortItemsEx(GetLangListHwnd(), &CompareFunc, reinterpret_cast<LPARAM>(this));\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clangxx_asan -fsanitize-coverage=func -DSHARED %s -shared -o %dynamiclib -fPIC %ld_flags_rpath_so\n\/\/ RUN: %clangxx_asan -fsanitize-coverage=func %s %ld_flags_rpath_exe -o %t\n\/\/ RUN: rm -rf %T\/coverage && mkdir -p %T\/coverage && cd %T\/coverage\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-main\n\/\/ RUN: %sancov print `ls coverage.*sancov | grep -v '.so'` 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV1\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-foo\n\/\/ RUN: %sancov print `ls coverage.*sancov | grep -v '.so'` 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV2\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t bar 2>&1 | FileCheck %s --check-prefix=CHECK-bar\n\/\/ RUN: %sancov print `ls *coverage.*sancov | grep -v '.so'` 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV2\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t foo bar 2>&1 | FileCheck %s --check-prefix=CHECK-foo-bar\n\/\/ RUN: %sancov print `ls *coverage.*sancov | grep -v '.so'` 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV2\n\/\/ RUN: %sancov print `ls *coverage.*sancov | grep '.so'` 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV1\n\/\/ RUN: %sancov merge `ls *coverage.*sancov | grep -v '.so'` > merged-cov\n\/\/ RUN: %sancov print merged-cov 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV2\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 not %run %t foo bar 4 2>&1 | FileCheck %s --check-prefix=CHECK-report\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 not %run %t foo bar 4 5 2>&1 | FileCheck %s --check-prefix=CHECK-segv\n\/\/ RUN: rm -r %T\/coverage\n\/\/\n\/\/ https:\/\/code.google.com\/p\/address-sanitizer\/issues\/detail?id=263\n\/\/ XFAIL: android\n\n#include <sanitizer\/coverage_interface.h>\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n\n#ifdef SHARED\nvoid bar() { printf(\"bar\\n\"); }\n#else\n__attribute__((noinline))\nvoid foo() { printf(\"foo\\n\"); }\nextern void bar();\n\nint G[4];\n\nint main(int argc, char **argv) {\n fprintf(stderr, \"PID: %d\\n\", getpid());\n for (int i = 1; i < argc; i++) {\n if (!strcmp(argv[i], \"foo\")) {\n uintptr_t old_coverage = __sanitizer_get_total_unique_coverage();\n foo();\n uintptr_t new_coverage = __sanitizer_get_total_unique_coverage();\n assert(new_coverage > old_coverage);\n }\n if (!strcmp(argv[i], \"bar\"))\n bar();\n }\n if (argc == 5) {\n static volatile char *zero = 0;\n *zero = 0; \/\/ SEGV if argc == 5.\n }\n return G[argc]; \/\/ Buffer overflow if argc >= 4.\n}\n#endif\n\n\/\/ CHECK-main: PID: [[PID:[0-9]+]]\n\/\/ CHECK-main: [[PID]].sancov: 1 PCs written\n\/\/ CHECK-main-NOT: .so.[[PID]]\n\/\/\n\/\/ CHECK-foo: PID: [[PID:[0-9]+]]\n\/\/ CHECK-foo: [[PID]].sancov: 2 PCs written\n\/\/ CHECK-foo-NOT: .so.[[PID]]\n\/\/\n\/\/ CHECK-bar: PID: [[PID:[0-9]+]]\n\/\/ CHECK-bar: .so.[[PID]].sancov: 1 PCs written\n\/\/ CHECK-bar: [[PID]].sancov: 1 PCs written\n\/\/\n\/\/ CHECK-foo-bar: PID: [[PID:[0-9]+]]\n\/\/ CHECK-foo-bar: so.[[PID]].sancov: 1 PCs written\n\/\/ CHECK-foo-bar: [[PID]].sancov: 2 PCs written\n\/\/\n\/\/ CHECK-report: AddressSanitizer: global-buffer-overflow\n\/\/ CHECK-report: PCs written\n\/\/\n\/\/ CHECK-segv: AddressSanitizer: SEGV\n\/\/ CHECK-segv: PCs written\n\/\/\n\/\/ CHECK-SANCOV1: 1 PCs total\n\/\/ CHECK-SANCOV2: 2 PCs total\n<commit_msg>avoid a subshell.<commit_after>\/\/ RUN: %clangxx_asan -fsanitize-coverage=func -DSHARED %s -shared -o %dynamiclib -fPIC %ld_flags_rpath_so\n\/\/ RUN: %clangxx_asan -fsanitize-coverage=func %s %ld_flags_rpath_exe -o %t\n\/\/ RUN: rm -rf %T\/coverage && mkdir -p %T\/coverage && cd %T\/coverage\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-main\n\/\/ RUN: %sancov print coverage.*sancov 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV1\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-foo\n\/\/ RUN: %sancov print coverage.*sancov 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV2\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t bar 2>&1 | FileCheck %s --check-prefix=CHECK-bar\n\/\/ RUN: %sancov print coverage.*sancov 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV2\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t foo bar 2>&1 | FileCheck %s --check-prefix=CHECK-foo-bar\n\/\/ RUN: %sancov print coverage.*sancov 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV2\n\/\/ RUN: %sancov print libcoverage.*sancov 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV1\n\/\/ RUN: %sancov merge coverage.*sancov > merged-cov\n\/\/ RUN: %sancov print merged-cov 2>&1 | FileCheck %s --check-prefix=CHECK-SANCOV2\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 not %run %t foo bar 4 2>&1 | FileCheck %s --check-prefix=CHECK-report\n\/\/ RUN: %env_asan_opts=coverage=1:verbosity=1 not %run %t foo bar 4 5 2>&1 | FileCheck %s --check-prefix=CHECK-segv\n\/\/ RUN: rm -r %T\/coverage\n\/\/\n\/\/ https:\/\/code.google.com\/p\/address-sanitizer\/issues\/detail?id=263\n\/\/ XFAIL: android\n\n#include <sanitizer\/coverage_interface.h>\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n\n#ifdef SHARED\nvoid bar() { printf(\"bar\\n\"); }\n#else\n__attribute__((noinline))\nvoid foo() { printf(\"foo\\n\"); }\nextern void bar();\n\nint G[4];\n\nint main(int argc, char **argv) {\n fprintf(stderr, \"PID: %d\\n\", getpid());\n for (int i = 1; i < argc; i++) {\n if (!strcmp(argv[i], \"foo\")) {\n uintptr_t old_coverage = __sanitizer_get_total_unique_coverage();\n foo();\n uintptr_t new_coverage = __sanitizer_get_total_unique_coverage();\n assert(new_coverage > old_coverage);\n }\n if (!strcmp(argv[i], \"bar\"))\n bar();\n }\n if (argc == 5) {\n static volatile char *zero = 0;\n *zero = 0; \/\/ SEGV if argc == 5.\n }\n return G[argc]; \/\/ Buffer overflow if argc >= 4.\n}\n#endif\n\n\/\/ CHECK-main: PID: [[PID:[0-9]+]]\n\/\/ CHECK-main: [[PID]].sancov: 1 PCs written\n\/\/ CHECK-main-NOT: .so.[[PID]]\n\/\/\n\/\/ CHECK-foo: PID: [[PID:[0-9]+]]\n\/\/ CHECK-foo: [[PID]].sancov: 2 PCs written\n\/\/ CHECK-foo-NOT: .so.[[PID]]\n\/\/\n\/\/ CHECK-bar: PID: [[PID:[0-9]+]]\n\/\/ CHECK-bar: .so.[[PID]].sancov: 1 PCs written\n\/\/ CHECK-bar: [[PID]].sancov: 1 PCs written\n\/\/\n\/\/ CHECK-foo-bar: PID: [[PID:[0-9]+]]\n\/\/ CHECK-foo-bar: so.[[PID]].sancov: 1 PCs written\n\/\/ CHECK-foo-bar: [[PID]].sancov: 2 PCs written\n\/\/\n\/\/ CHECK-report: AddressSanitizer: global-buffer-overflow\n\/\/ CHECK-report: PCs written\n\/\/\n\/\/ CHECK-segv: AddressSanitizer: SEGV\n\/\/ CHECK-segv: PCs written\n\/\/\n\/\/ CHECK-SANCOV1: 1 PCs total\n\/\/ CHECK-SANCOV2: 2 PCs total\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * (c) 2009-2016 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n *\n * QGroundControl is licensed according to the terms in the file\n * COPYING.md in the root of the source code directory.\n *\n ****************************************************************************\/\n\n#include \"PlanMasterController.h\"\n#include \"QGCApplication.h\"\n#include \"MultiVehicleManager.h\"\n#include \"SettingsManager.h\"\n#include \"AppSettings.h\"\n#include \"JsonHelper.h\"\n#include \"MissionManager.h\"\n\n#include <QJsonDocument>\n#include <QFileInfo>\n\nQGC_LOGGING_CATEGORY(PlanMasterControllerLog, \"PlanMasterControllerLog\")\n\nconst int PlanMasterController::_planFileVersion = 1;\nconst char* PlanMasterController::_planFileType = \"Plan\";\nconst char* PlanMasterController::_jsonMissionObjectKey = \"mission\";\nconst char* PlanMasterController::_jsonGeoFenceObjectKey = \"geoFence\";\nconst char* PlanMasterController::_jsonRallyPointsObjectKey = \"rallyPoints\";\n\nPlanMasterController::PlanMasterController(QObject* parent)\n : QObject(parent)\n , _multiVehicleMgr(qgcApp()->toolbox()->multiVehicleManager())\n , _controllerVehicle(new Vehicle((MAV_AUTOPILOT)qgcApp()->toolbox()->settingsManager()->appSettings()->offlineEditingFirmwareType()->rawValue().toInt(), (MAV_TYPE)qgcApp()->toolbox()->settingsManager()->appSettings()->offlineEditingVehicleType()->rawValue().toInt(), qgcApp()->toolbox()->firmwarePluginManager()))\n , _managerVehicle(_controllerVehicle)\n , _editMode(false)\n , _offline(true)\n , _missionController(this)\n , _geoFenceController(this)\n , _rallyPointController(this)\n , _loadGeoFence(false)\n , _loadRallyPoints(false)\n , _sendGeoFence(false)\n , _sendRallyPoints(false)\n , _syncInProgress(false)\n{\n connect(&_missionController, &MissionController::dirtyChanged, this, &PlanMasterController::dirtyChanged);\n connect(&_geoFenceController, &GeoFenceController::dirtyChanged, this, &PlanMasterController::dirtyChanged);\n connect(&_rallyPointController, &RallyPointController::dirtyChanged, this, &PlanMasterController::dirtyChanged);\n\n connect(&_missionController, &MissionController::containsItemsChanged, this, &PlanMasterController::containsItemsChanged);\n connect(&_geoFenceController, &GeoFenceController::containsItemsChanged, this, &PlanMasterController::containsItemsChanged);\n connect(&_rallyPointController, &RallyPointController::containsItemsChanged, this, &PlanMasterController::containsItemsChanged);\n\n connect(&_missionController, &MissionController::syncInProgressChanged, this, &PlanMasterController::syncInProgressChanged);\n connect(&_geoFenceController, &GeoFenceController::syncInProgressChanged, this, &PlanMasterController::syncInProgressChanged);\n connect(&_rallyPointController, &RallyPointController::syncInProgressChanged, this, &PlanMasterController::syncInProgressChanged);\n}\n\nPlanMasterController::~PlanMasterController()\n{\n\n}\n\nvoid PlanMasterController::start(bool editMode)\n{\n _editMode = editMode;\n _missionController.start(editMode);\n _geoFenceController.start(editMode);\n _rallyPointController.start(editMode);\n\n connect(_multiVehicleMgr, &MultiVehicleManager::activeVehicleChanged, this, &PlanMasterController::_activeVehicleChanged);\n _activeVehicleChanged(_multiVehicleMgr->activeVehicle());\n}\n\nvoid PlanMasterController::startStaticActiveVehicle(Vehicle* vehicle)\n{\n _editMode = false;\n _activeVehicleChanged(vehicle);\n}\n\nvoid PlanMasterController::_activeVehicleChanged(Vehicle* activeVehicle)\n{\n if (_managerVehicle == activeVehicle) {\n \/\/ We are already setup for this vehicle\n return;\n }\n\n qCDebug(PlanMasterControllerLog) << \"_activeVehicleChanged\" << activeVehicle;\n\n bool newOffline = false;\n if (activeVehicle == NULL) {\n \/\/ Since there is no longer an active vehicle we use the offline controller vehicle as the manager vehicle\n _managerVehicle = _controllerVehicle;\n newOffline = true;\n } else {\n newOffline = false;\n _managerVehicle = activeVehicle;\n\n \/\/ Update controllerVehicle to the currently connected vehicle\n AppSettings* appSettings = qgcApp()->toolbox()->settingsManager()->appSettings();\n appSettings->offlineEditingFirmwareType()->setRawValue(AppSettings::offlineEditingFirmwareTypeFromFirmwareType(_managerVehicle->firmwareType()));\n appSettings->offlineEditingVehicleType()->setRawValue(AppSettings::offlineEditingVehicleTypeFromVehicleType(_managerVehicle->vehicleType()));\n\n \/\/ We use these signals to sequence upload and download to the multiple controller\/managers\n connect(_managerVehicle->missionManager(), &MissionManager::newMissionItemsAvailable, this, &PlanMasterController::_loadMissionComplete);\n connect(_managerVehicle->geoFenceManager(), &GeoFenceManager::loadComplete, this, &PlanMasterController::_loadGeoFenceComplete);\n connect(_managerVehicle->rallyPointManager(), &RallyPointManager::loadComplete, this, &PlanMasterController::_loadRallyPointsComplete);\n connect(_managerVehicle->missionManager(), &MissionManager::sendComplete, this, &PlanMasterController::_sendMissionComplete);\n connect(_managerVehicle->geoFenceManager(), &GeoFenceManager::sendComplete, this, &PlanMasterController::_sendGeoFenceComplete);\n connect(_managerVehicle->rallyPointManager(), &RallyPointManager::sendComplete, this, &PlanMasterController::_sendRallyPointsComplete);\n }\n if (newOffline != _offline) {\n _offline = newOffline;\n emit offlineEditingChanged(newOffline);\n }\n\n _missionController.managerVehicleChanged(_managerVehicle);\n _geoFenceController.managerVehicleChanged(_managerVehicle);\n _rallyPointController.managerVehicleChanged(_managerVehicle);\n\n if (_editMode) {\n if (!offline()) {\n \/\/ We are in Plan view and we have a newly connected vehicle:\n \/\/ - If there is no plan available in Plan view show the one from the vehicle\n \/\/ - Otherwise leave the current plan alone\n if (!containsItems()) {\n qCDebug(PlanMasterControllerLog) << \"_activeVehicleChanged: Plan view is empty so loading from manager\";\n _showPlanFromManagerVehicle();\n }\n }\n } else {\n if (offline()) {\n \/\/ No more active vehicle, clear mission\n qCDebug(PlanMasterControllerLog) << \"_activeVehicleChanged: Fly view is offline clearing plan\";\n removeAll();\n } else {\n \/\/ Fly view has changed to a new active vehicle, update to show correct mission\n qCDebug(PlanMasterControllerLog) << \"_activeVehicleChanged: Fly view is online so loading from manager\";\n _showPlanFromManagerVehicle();\n }\n }\n}\n\nvoid PlanMasterController::loadFromVehicle(void)\n{\n if (offline()) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::loadFromVehicle called while offline\";\n } else if (!_editMode) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::loadFromVehicle called from Fly view\";\n } else if (syncInProgress()) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::loadFromVehicle called while syncInProgress\";\n } else {\n _loadGeoFence = true;\n _syncInProgress = true;\n _missionController.loadFromVehicle();\n setDirty(false);\n }\n}\n\n\nvoid PlanMasterController::_loadMissionComplete(void)\n{\n if (_editMode && _loadGeoFence) {\n _loadGeoFence = false;\n _loadRallyPoints = true;\n _geoFenceController.loadFromVehicle();\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::_loadGeoFenceComplete(void)\n{\n if (_editMode && _loadRallyPoints) {\n _loadRallyPoints = false;\n _rallyPointController.loadFromVehicle();\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::_loadRallyPointsComplete(void)\n{\n if (_editMode) {\n _syncInProgress = false;\n emit syncInProgressChanged(false);\n }\n}\n\nvoid PlanMasterController::_sendMissionComplete(void)\n{\n if (_editMode && _sendGeoFence) {\n qCDebug(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle start fence sendToVehicle\";\n _sendGeoFence = false;\n _sendRallyPoints = true;\n _geoFenceController.sendToVehicle();\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::_sendGeoFenceComplete(void)\n{\n if (_editMode && _sendRallyPoints) {\n qCDebug(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle start rally sendToVehicle\";\n _sendRallyPoints = false;\n _rallyPointController.sendToVehicle();\n }\n}\n\nvoid PlanMasterController::_sendRallyPointsComplete(void)\n{\n if (_editMode && _syncInProgress) {\n qCDebug(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle rally point send complete\";\n _syncInProgress = false;\n emit syncInProgressChanged(false);\n }\n}\n\nvoid PlanMasterController::sendToVehicle(void)\n{\n if (offline()) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle called while offline\";\n } else if (!_editMode) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle called from Fly view\";\n } else if (syncInProgress()) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle called while syncInProgress\";\n } else {\n qCDebug(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle start mission sendToVehicle\";\n _sendGeoFence = true;\n _missionController.sendToVehicle();\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::loadFromFile(const QString& filename)\n{\n QString errorString;\n QString errorMessage = tr(\"Error reading Plan file (%1). %2\").arg(filename).arg(\"%1\");\n\n if (filename.isEmpty()) {\n return;\n }\n\n QFile file(filename);\n\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n errorString = file.errorString() + QStringLiteral(\" \") + filename;\n return;\n }\n\n QString fileExtension(\".%1\");\n if (filename.endsWith(fileExtension.arg(AppSettings::planFileExtension))) {\n QJsonDocument jsonDoc;\n QByteArray bytes = file.readAll();\n\n if (!JsonHelper::isJsonFile(bytes, jsonDoc, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n return;\n }\n\n int version;\n QJsonObject json = jsonDoc.object();\n if (!JsonHelper::validateQGCJsonFile(json, _planFileType, _planFileVersion, _planFileVersion, version, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n return;\n }\n\n QList<JsonHelper::KeyValidateInfo> rgKeyInfo = {\n { _jsonMissionObjectKey, QJsonValue::Object, true },\n { _jsonGeoFenceObjectKey, QJsonValue::Object, true },\n { _jsonRallyPointsObjectKey, QJsonValue::Object, true },\n };\n if (!JsonHelper::validateKeys(json, rgKeyInfo, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n return;\n }\n\n if (!_missionController.load(json[_jsonMissionObjectKey].toObject(), errorString) ||\n !_geoFenceController.load(json[_jsonGeoFenceObjectKey].toObject(), errorString) ||\n !_rallyPointController.load(json[_jsonRallyPointsObjectKey].toObject(), errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n }\n } else if (filename.endsWith(fileExtension.arg(AppSettings::missionFileExtension))) {\n if (!_missionController.loadJsonFile(file, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n }\n } else if (filename.endsWith(fileExtension.arg(AppSettings::waypointsFileExtension)) ||\n filename.endsWith(fileExtension.arg(QStringLiteral(\"txt\")))) {\n if (!_missionController.loadTextFile(file, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n }\n }\n\n if (!offline()) {\n setDirty(true);\n }\n}\n\nvoid PlanMasterController::saveToFile(const QString& filename)\n{\n if (filename.isEmpty()) {\n return;\n }\n\n QString planFilename = filename;\n if (!QFileInfo(filename).fileName().contains(\".\")) {\n planFilename += QString(\".%1\").arg(fileExtension());\n }\n\n QFile file(planFilename);\n\n if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n qgcApp()->showMessage(tr(\"Plan save error %1 : %2\").arg(filename).arg(file.errorString()));\n } else {\n QJsonObject planJson;\n QJsonObject missionJson;\n QJsonObject fenceJson;\n QJsonObject rallyJson;\n\n JsonHelper::saveQGCJsonFileHeader(planJson, _planFileType, _planFileVersion);\n _missionController.save(missionJson);\n _geoFenceController.save(fenceJson);\n _rallyPointController.save(rallyJson);\n planJson[_jsonMissionObjectKey] = missionJson;\n planJson[_jsonGeoFenceObjectKey] = fenceJson;\n planJson[_jsonRallyPointsObjectKey] = rallyJson;\n\n QJsonDocument saveDoc(planJson);\n file.write(saveDoc.toJson());\n }\n\n \/\/ Only clear dirty bit if we are offline\n if (offline()) {\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::removeAll(void)\n{\n _missionController.removeAll();\n _geoFenceController.removeAll();\n _rallyPointController.removeAll();\n}\n\nvoid PlanMasterController::removeAllFromVehicle(void)\n{\n if (!offline()) {\n _missionController.removeAllFromVehicle();\n _geoFenceController.removeAllFromVehicle();\n _rallyPointController.removeAllFromVehicle();\n } else {\n qWarning() << \"PlanMasterController::removeAllFromVehicle called while offline\";\n }\n}\n\nbool PlanMasterController::containsItems(void) const\n{\n return _missionController.containsItems() || _geoFenceController.containsItems() || _rallyPointController.containsItems();\n}\n\nbool PlanMasterController::dirty(void) const\n{\n return _missionController.dirty() || _geoFenceController.dirty() || _rallyPointController.dirty();\n}\n\nvoid PlanMasterController::setDirty(bool dirty)\n{\n _missionController.setDirty(dirty);\n _geoFenceController.setDirty(dirty);\n _rallyPointController.setDirty(dirty);\n}\n\nQString PlanMasterController::fileExtension(void) const\n{\n return AppSettings::planFileExtension;\n}\n\nQStringList PlanMasterController::loadNameFilters(void) const\n{\n QStringList filters;\n\n filters << tr(\"Supported types (*.%1 *.%2 *.%3 *.%4)\").arg(AppSettings::planFileExtension).arg(AppSettings::missionFileExtension).arg(AppSettings::waypointsFileExtension).arg(\"*.txt\") <<\n tr(\"All Files (*.*)\");\n return filters;\n}\n\n\nQStringList PlanMasterController::saveNameFilters(void) const\n{\n QStringList filters;\n\n filters << tr(\"Plan Files (*.%1)\").arg(fileExtension()) << tr(\"All Files (*.*)\");\n return filters;\n}\n\nvoid PlanMasterController::sendPlanToVehicle(Vehicle* vehicle, const QString& filename)\n{\n \/\/ Use a transient PlanMasterController to accomplish this\n PlanMasterController* controller = new PlanMasterController();\n controller->startStaticActiveVehicle(vehicle);\n controller->loadFromFile(filename);\n delete controller;\n}\n\nvoid PlanMasterController::_showPlanFromManagerVehicle(void)\n{\n \/\/ The crazy if structure is to handle the load propogating by itself through the system\n if (!_missionController.showPlanFromManagerVehicle()) {\n if (!_geoFenceController.showPlanFromManagerVehicle()) {\n _rallyPointController.showPlanFromManagerVehicle();\n }\n }\n}\n<commit_msg>Typo in file extensions<commit_after>\/****************************************************************************\n *\n * (c) 2009-2016 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n *\n * QGroundControl is licensed according to the terms in the file\n * COPYING.md in the root of the source code directory.\n *\n ****************************************************************************\/\n\n#include \"PlanMasterController.h\"\n#include \"QGCApplication.h\"\n#include \"MultiVehicleManager.h\"\n#include \"SettingsManager.h\"\n#include \"AppSettings.h\"\n#include \"JsonHelper.h\"\n#include \"MissionManager.h\"\n\n#include <QJsonDocument>\n#include <QFileInfo>\n\nQGC_LOGGING_CATEGORY(PlanMasterControllerLog, \"PlanMasterControllerLog\")\n\nconst int PlanMasterController::_planFileVersion = 1;\nconst char* PlanMasterController::_planFileType = \"Plan\";\nconst char* PlanMasterController::_jsonMissionObjectKey = \"mission\";\nconst char* PlanMasterController::_jsonGeoFenceObjectKey = \"geoFence\";\nconst char* PlanMasterController::_jsonRallyPointsObjectKey = \"rallyPoints\";\n\nPlanMasterController::PlanMasterController(QObject* parent)\n : QObject(parent)\n , _multiVehicleMgr(qgcApp()->toolbox()->multiVehicleManager())\n , _controllerVehicle(new Vehicle((MAV_AUTOPILOT)qgcApp()->toolbox()->settingsManager()->appSettings()->offlineEditingFirmwareType()->rawValue().toInt(), (MAV_TYPE)qgcApp()->toolbox()->settingsManager()->appSettings()->offlineEditingVehicleType()->rawValue().toInt(), qgcApp()->toolbox()->firmwarePluginManager()))\n , _managerVehicle(_controllerVehicle)\n , _editMode(false)\n , _offline(true)\n , _missionController(this)\n , _geoFenceController(this)\n , _rallyPointController(this)\n , _loadGeoFence(false)\n , _loadRallyPoints(false)\n , _sendGeoFence(false)\n , _sendRallyPoints(false)\n , _syncInProgress(false)\n{\n connect(&_missionController, &MissionController::dirtyChanged, this, &PlanMasterController::dirtyChanged);\n connect(&_geoFenceController, &GeoFenceController::dirtyChanged, this, &PlanMasterController::dirtyChanged);\n connect(&_rallyPointController, &RallyPointController::dirtyChanged, this, &PlanMasterController::dirtyChanged);\n\n connect(&_missionController, &MissionController::containsItemsChanged, this, &PlanMasterController::containsItemsChanged);\n connect(&_geoFenceController, &GeoFenceController::containsItemsChanged, this, &PlanMasterController::containsItemsChanged);\n connect(&_rallyPointController, &RallyPointController::containsItemsChanged, this, &PlanMasterController::containsItemsChanged);\n\n connect(&_missionController, &MissionController::syncInProgressChanged, this, &PlanMasterController::syncInProgressChanged);\n connect(&_geoFenceController, &GeoFenceController::syncInProgressChanged, this, &PlanMasterController::syncInProgressChanged);\n connect(&_rallyPointController, &RallyPointController::syncInProgressChanged, this, &PlanMasterController::syncInProgressChanged);\n}\n\nPlanMasterController::~PlanMasterController()\n{\n\n}\n\nvoid PlanMasterController::start(bool editMode)\n{\n _editMode = editMode;\n _missionController.start(editMode);\n _geoFenceController.start(editMode);\n _rallyPointController.start(editMode);\n\n connect(_multiVehicleMgr, &MultiVehicleManager::activeVehicleChanged, this, &PlanMasterController::_activeVehicleChanged);\n _activeVehicleChanged(_multiVehicleMgr->activeVehicle());\n}\n\nvoid PlanMasterController::startStaticActiveVehicle(Vehicle* vehicle)\n{\n _editMode = false;\n _activeVehicleChanged(vehicle);\n}\n\nvoid PlanMasterController::_activeVehicleChanged(Vehicle* activeVehicle)\n{\n if (_managerVehicle == activeVehicle) {\n \/\/ We are already setup for this vehicle\n return;\n }\n\n qCDebug(PlanMasterControllerLog) << \"_activeVehicleChanged\" << activeVehicle;\n\n bool newOffline = false;\n if (activeVehicle == NULL) {\n \/\/ Since there is no longer an active vehicle we use the offline controller vehicle as the manager vehicle\n _managerVehicle = _controllerVehicle;\n newOffline = true;\n } else {\n newOffline = false;\n _managerVehicle = activeVehicle;\n\n \/\/ Update controllerVehicle to the currently connected vehicle\n AppSettings* appSettings = qgcApp()->toolbox()->settingsManager()->appSettings();\n appSettings->offlineEditingFirmwareType()->setRawValue(AppSettings::offlineEditingFirmwareTypeFromFirmwareType(_managerVehicle->firmwareType()));\n appSettings->offlineEditingVehicleType()->setRawValue(AppSettings::offlineEditingVehicleTypeFromVehicleType(_managerVehicle->vehicleType()));\n\n \/\/ We use these signals to sequence upload and download to the multiple controller\/managers\n connect(_managerVehicle->missionManager(), &MissionManager::newMissionItemsAvailable, this, &PlanMasterController::_loadMissionComplete);\n connect(_managerVehicle->geoFenceManager(), &GeoFenceManager::loadComplete, this, &PlanMasterController::_loadGeoFenceComplete);\n connect(_managerVehicle->rallyPointManager(), &RallyPointManager::loadComplete, this, &PlanMasterController::_loadRallyPointsComplete);\n connect(_managerVehicle->missionManager(), &MissionManager::sendComplete, this, &PlanMasterController::_sendMissionComplete);\n connect(_managerVehicle->geoFenceManager(), &GeoFenceManager::sendComplete, this, &PlanMasterController::_sendGeoFenceComplete);\n connect(_managerVehicle->rallyPointManager(), &RallyPointManager::sendComplete, this, &PlanMasterController::_sendRallyPointsComplete);\n }\n if (newOffline != _offline) {\n _offline = newOffline;\n emit offlineEditingChanged(newOffline);\n }\n\n _missionController.managerVehicleChanged(_managerVehicle);\n _geoFenceController.managerVehicleChanged(_managerVehicle);\n _rallyPointController.managerVehicleChanged(_managerVehicle);\n\n if (_editMode) {\n if (!offline()) {\n \/\/ We are in Plan view and we have a newly connected vehicle:\n \/\/ - If there is no plan available in Plan view show the one from the vehicle\n \/\/ - Otherwise leave the current plan alone\n if (!containsItems()) {\n qCDebug(PlanMasterControllerLog) << \"_activeVehicleChanged: Plan view is empty so loading from manager\";\n _showPlanFromManagerVehicle();\n }\n }\n } else {\n if (offline()) {\n \/\/ No more active vehicle, clear mission\n qCDebug(PlanMasterControllerLog) << \"_activeVehicleChanged: Fly view is offline clearing plan\";\n removeAll();\n } else {\n \/\/ Fly view has changed to a new active vehicle, update to show correct mission\n qCDebug(PlanMasterControllerLog) << \"_activeVehicleChanged: Fly view is online so loading from manager\";\n _showPlanFromManagerVehicle();\n }\n }\n}\n\nvoid PlanMasterController::loadFromVehicle(void)\n{\n if (offline()) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::loadFromVehicle called while offline\";\n } else if (!_editMode) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::loadFromVehicle called from Fly view\";\n } else if (syncInProgress()) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::loadFromVehicle called while syncInProgress\";\n } else {\n _loadGeoFence = true;\n _syncInProgress = true;\n _missionController.loadFromVehicle();\n setDirty(false);\n }\n}\n\n\nvoid PlanMasterController::_loadMissionComplete(void)\n{\n if (_editMode && _loadGeoFence) {\n _loadGeoFence = false;\n _loadRallyPoints = true;\n _geoFenceController.loadFromVehicle();\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::_loadGeoFenceComplete(void)\n{\n if (_editMode && _loadRallyPoints) {\n _loadRallyPoints = false;\n _rallyPointController.loadFromVehicle();\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::_loadRallyPointsComplete(void)\n{\n if (_editMode) {\n _syncInProgress = false;\n emit syncInProgressChanged(false);\n }\n}\n\nvoid PlanMasterController::_sendMissionComplete(void)\n{\n if (_editMode && _sendGeoFence) {\n qCDebug(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle start fence sendToVehicle\";\n _sendGeoFence = false;\n _sendRallyPoints = true;\n _geoFenceController.sendToVehicle();\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::_sendGeoFenceComplete(void)\n{\n if (_editMode && _sendRallyPoints) {\n qCDebug(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle start rally sendToVehicle\";\n _sendRallyPoints = false;\n _rallyPointController.sendToVehicle();\n }\n}\n\nvoid PlanMasterController::_sendRallyPointsComplete(void)\n{\n if (_editMode && _syncInProgress) {\n qCDebug(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle rally point send complete\";\n _syncInProgress = false;\n emit syncInProgressChanged(false);\n }\n}\n\nvoid PlanMasterController::sendToVehicle(void)\n{\n if (offline()) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle called while offline\";\n } else if (!_editMode) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle called from Fly view\";\n } else if (syncInProgress()) {\n qCWarning(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle called while syncInProgress\";\n } else {\n qCDebug(PlanMasterControllerLog) << \"PlanMasterController::sendToVehicle start mission sendToVehicle\";\n _sendGeoFence = true;\n _missionController.sendToVehicle();\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::loadFromFile(const QString& filename)\n{\n QString errorString;\n QString errorMessage = tr(\"Error reading Plan file (%1). %2\").arg(filename).arg(\"%1\");\n\n if (filename.isEmpty()) {\n return;\n }\n\n QFile file(filename);\n\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n errorString = file.errorString() + QStringLiteral(\" \") + filename;\n return;\n }\n\n QString fileExtension(\".%1\");\n if (filename.endsWith(fileExtension.arg(AppSettings::planFileExtension))) {\n QJsonDocument jsonDoc;\n QByteArray bytes = file.readAll();\n\n if (!JsonHelper::isJsonFile(bytes, jsonDoc, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n return;\n }\n\n int version;\n QJsonObject json = jsonDoc.object();\n if (!JsonHelper::validateQGCJsonFile(json, _planFileType, _planFileVersion, _planFileVersion, version, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n return;\n }\n\n QList<JsonHelper::KeyValidateInfo> rgKeyInfo = {\n { _jsonMissionObjectKey, QJsonValue::Object, true },\n { _jsonGeoFenceObjectKey, QJsonValue::Object, true },\n { _jsonRallyPointsObjectKey, QJsonValue::Object, true },\n };\n if (!JsonHelper::validateKeys(json, rgKeyInfo, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n return;\n }\n\n if (!_missionController.load(json[_jsonMissionObjectKey].toObject(), errorString) ||\n !_geoFenceController.load(json[_jsonGeoFenceObjectKey].toObject(), errorString) ||\n !_rallyPointController.load(json[_jsonRallyPointsObjectKey].toObject(), errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n }\n } else if (filename.endsWith(fileExtension.arg(AppSettings::missionFileExtension))) {\n if (!_missionController.loadJsonFile(file, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n }\n } else if (filename.endsWith(fileExtension.arg(AppSettings::waypointsFileExtension)) ||\n filename.endsWith(fileExtension.arg(QStringLiteral(\"txt\")))) {\n if (!_missionController.loadTextFile(file, errorString)) {\n qgcApp()->showMessage(errorMessage.arg(errorString));\n }\n }\n\n if (!offline()) {\n setDirty(true);\n }\n}\n\nvoid PlanMasterController::saveToFile(const QString& filename)\n{\n if (filename.isEmpty()) {\n return;\n }\n\n QString planFilename = filename;\n if (!QFileInfo(filename).fileName().contains(\".\")) {\n planFilename += QString(\".%1\").arg(fileExtension());\n }\n\n QFile file(planFilename);\n\n if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n qgcApp()->showMessage(tr(\"Plan save error %1 : %2\").arg(filename).arg(file.errorString()));\n } else {\n QJsonObject planJson;\n QJsonObject missionJson;\n QJsonObject fenceJson;\n QJsonObject rallyJson;\n\n JsonHelper::saveQGCJsonFileHeader(planJson, _planFileType, _planFileVersion);\n _missionController.save(missionJson);\n _geoFenceController.save(fenceJson);\n _rallyPointController.save(rallyJson);\n planJson[_jsonMissionObjectKey] = missionJson;\n planJson[_jsonGeoFenceObjectKey] = fenceJson;\n planJson[_jsonRallyPointsObjectKey] = rallyJson;\n\n QJsonDocument saveDoc(planJson);\n file.write(saveDoc.toJson());\n }\n\n \/\/ Only clear dirty bit if we are offline\n if (offline()) {\n setDirty(false);\n }\n}\n\nvoid PlanMasterController::removeAll(void)\n{\n _missionController.removeAll();\n _geoFenceController.removeAll();\n _rallyPointController.removeAll();\n}\n\nvoid PlanMasterController::removeAllFromVehicle(void)\n{\n if (!offline()) {\n _missionController.removeAllFromVehicle();\n _geoFenceController.removeAllFromVehicle();\n _rallyPointController.removeAllFromVehicle();\n } else {\n qWarning() << \"PlanMasterController::removeAllFromVehicle called while offline\";\n }\n}\n\nbool PlanMasterController::containsItems(void) const\n{\n return _missionController.containsItems() || _geoFenceController.containsItems() || _rallyPointController.containsItems();\n}\n\nbool PlanMasterController::dirty(void) const\n{\n return _missionController.dirty() || _geoFenceController.dirty() || _rallyPointController.dirty();\n}\n\nvoid PlanMasterController::setDirty(bool dirty)\n{\n _missionController.setDirty(dirty);\n _geoFenceController.setDirty(dirty);\n _rallyPointController.setDirty(dirty);\n}\n\nQString PlanMasterController::fileExtension(void) const\n{\n return AppSettings::planFileExtension;\n}\n\nQStringList PlanMasterController::loadNameFilters(void) const\n{\n QStringList filters;\n\n filters << tr(\"Supported types (*.%1 *.%2 *.%3 *.%4)\").arg(AppSettings::planFileExtension).arg(AppSettings::missionFileExtension).arg(AppSettings::waypointsFileExtension).arg(\"txt\") <<\n tr(\"All Files (*.*)\");\n return filters;\n}\n\n\nQStringList PlanMasterController::saveNameFilters(void) const\n{\n QStringList filters;\n\n filters << tr(\"Plan Files (*.%1)\").arg(fileExtension()) << tr(\"All Files (*.*)\");\n return filters;\n}\n\nvoid PlanMasterController::sendPlanToVehicle(Vehicle* vehicle, const QString& filename)\n{\n \/\/ Use a transient PlanMasterController to accomplish this\n PlanMasterController* controller = new PlanMasterController();\n controller->startStaticActiveVehicle(vehicle);\n controller->loadFromFile(filename);\n delete controller;\n}\n\nvoid PlanMasterController::_showPlanFromManagerVehicle(void)\n{\n \/\/ The crazy if structure is to handle the load propogating by itself through the system\n if (!_missionController.showPlanFromManagerVehicle()) {\n if (!_geoFenceController.showPlanFromManagerVehicle()) {\n _rallyPointController.showPlanFromManagerVehicle();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012 Red Hat, Inc., Eike Rathke <erack@redhat.com>\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include <sal\/precppunit.hxx>\n\n#include <tubes\/contact-list.hxx>\n#include <tubes\/manager.hxx>\n\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n#include <rtl\/string.hxx>\n#include <rtl\/ustring.hxx>\n#include <rtl\/bootstrap.hxx>\n#include <unotest\/bootstrapfixturebase.hxx>\n\nnamespace {\n\nclass TestTeleTubes: public test::BootstrapFixtureBase\n{\npublic:\n\n TestTeleTubes();\n ~TestTeleTubes();\n void testSetupManager1();\n void testSetupManager2();\n void testConnect1();\n void testConnect2();\n void testContactList();\n void testPrepareAccountManager1();\n void testPrepareAccountManager2();\n void testStartBuddySession1();\n void testStartBuddySession2();\n void testSendPacket();\n void testReceivePacket();\n void testFlushLoops();\n void testDestroyManager1();\n void testDestroyManager2();\n void testDestroyAccepterContact();\n void testFailAlways();\n\n GMainLoop* mpMainLoop;\n\n \/\/ Order is significant.\n CPPUNIT_TEST_SUITE( TestTeleTubes );\n CPPUNIT_TEST( testSetupManager1 );\n CPPUNIT_TEST( testSetupManager2 );\n CPPUNIT_TEST( testConnect1 );\n CPPUNIT_TEST( testConnect2 );\n CPPUNIT_TEST( testContactList );\n CPPUNIT_TEST( testPrepareAccountManager1 );\n CPPUNIT_TEST( testPrepareAccountManager2 );\n CPPUNIT_TEST( testStartBuddySession1 );\n CPPUNIT_TEST( testStartBuddySession2 );\n CPPUNIT_TEST( testSendPacket );\n CPPUNIT_TEST( testReceivePacket );\n CPPUNIT_TEST( testFlushLoops );\n CPPUNIT_TEST( testDestroyManager1 );\n CPPUNIT_TEST( testDestroyManager2 );\n CPPUNIT_TEST( testDestroyAccepterContact );\n CPPUNIT_TEST( testFailAlways ); \/\/ need failure to display SAL_LOG, comment out for real builds\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\/\/ XXX The Jabber accounts specified in test-config.ini need to be setup in\n\/\/ Empathy, enabled, connected, and on each other's rosters.\n rtl::OUString maTestConfigIniURL;\n rtl::Bootstrap maTestConfig;\n\n rtl::OString maOffererIdentifier;\n rtl::OString maAccepterIdentifier;\n};\n\n\/\/ static, not members, so they actually survive cppunit test iteration\nstatic TeleManager* mpManager1 = NULL;\nstatic TeleManager* mpManager2 = NULL;\n\nstatic TpContact* mpAccepterContact = NULL;\n\nstatic sal_uInt32 nSentPackets = 0;\n\nTestTeleTubes::TestTeleTubes()\n : maTestConfigIniURL(getURLFromSrc(\"\/tubes\/qa\/test-config.ini\")),\n maTestConfig(maTestConfigIniURL)\n{\n TeleManager::addSuffixToNames( \"TeleTest\");\n\n rtl::OUString aOffererIdentifier;\n CPPUNIT_ASSERT_MESSAGE( \"See README for how to set up test-config.ini\",\n maTestConfig.getFrom(\"offerer\", aOffererIdentifier));\n maOffererIdentifier = OUStringToOString( aOffererIdentifier, RTL_TEXTENCODING_UTF8);\n\n rtl::OUString aAccepterIdentifier;\n CPPUNIT_ASSERT_MESSAGE( \"See README for how to set up test-config.ini\",\n maTestConfig.getFrom(\"accepter\", aAccepterIdentifier));\n maAccepterIdentifier = OUStringToOString( aAccepterIdentifier, RTL_TEXTENCODING_UTF8);\n}\n\nTestTeleTubes::~TestTeleTubes()\n{\n}\n\nstatic void TeleTestTubes_ContactListPrepared( GError *errorOr0, void *user_data )\n{\n TestTeleTubes *self = reinterpret_cast<TestTeleTubes *>(user_data);\n\n CPPUNIT_ASSERT( errorOr0 == 0 );\n\n g_main_loop_quit (self->mpMainLoop);\n}\n\nstatic gboolean\ntimed_out (void *user_data)\n{\n CPPUNIT_ASSERT( false);\n\n GMainLoop *loop = reinterpret_cast<GMainLoop *>(user_data);\n\n g_main_loop_quit (loop);\n return FALSE;\n}\n\nvoid TestTeleTubes::testContactList()\n{\n mpMainLoop = g_main_loop_new (NULL, FALSE);\n\n ContactList cl;\n cl.prepare( TeleTestTubes_ContactListPrepared, this );\n g_timeout_add_seconds (5, timed_out, mpMainLoop);\n g_main_loop_run (mpMainLoop);\n g_main_loop_unref (mpMainLoop);\n mpMainLoop = NULL;\n\n \/* Okay, now everything's prepared, we can get contacts synchronously. *\/\n AccountContactPairV pairs;\n\n pairs = cl.getContacts();\n guint i;\n\n \/* FIXME: this is racy, because we can't be 100% sure that MC has finished\n * discovering what we support and passing that on to the connection\n * manager...\n *\/\n\n \/* Both our accounts are meant to be signed in, and they both should be\n * capable of LibreOffice tubes because this test runs after we register\n * our handler. *\/\n CPPUNIT_ASSERT_MESSAGE(\n \"Make sure both your test accounts are signed in \"\n \"and are on each other's contact lists\",\n pairs.size() > 0 );\n CPPUNIT_ASSERT(!mpAccepterContact);\n\n for (i = 0; i < pairs.size(); i++)\n {\n AccountContactPair pair = pairs[i];\n\n \/* FIXME: verify that pair.first is the offerer account *\/\n if (tp_contact_get_identifier(pair.second) == maAccepterIdentifier) {\n mpAccepterContact = pair.second;\n g_object_ref(mpAccepterContact);\n }\n g_object_unref (pair.first);\n g_object_unref (pair.second);\n }\n\n CPPUNIT_ASSERT_MESSAGE(\n \"Couldn't find accepter contact. \"\n \"Make sure both your test accounts are signed in \"\n \"and are on each other's contact lists\",\n mpAccepterContact);\n}\n\nvoid TestTeleTubes::testSetupManager1()\n{\n mpManager1 = new TeleManager( true);\n}\n\nvoid TestTeleTubes::testSetupManager2()\n{\n mpManager2 = new TeleManager;\n}\n\nvoid TestTeleTubes::testPrepareAccountManager1()\n{\n mpManager1->prepareAccountManager();\n TeleManager::AccountManagerStatus eStatus = mpManager1->getAccountManagerStatus();\n CPPUNIT_ASSERT( eStatus == TeleManager::AMS_PREPARED);\n}\n\nvoid TestTeleTubes::testPrepareAccountManager2()\n{\n mpManager2->prepareAccountManager();\n TeleManager::AccountManagerStatus eStatus = mpManager2->getAccountManagerStatus();\n CPPUNIT_ASSERT( eStatus == TeleManager::AMS_PREPARED);\n}\n\nvoid TestTeleTubes::testStartBuddySession1()\n{\n TpAccount *pAcc1 = mpManager1->getAccount(maOffererIdentifier);\n CPPUNIT_ASSERT( pAcc1 != 0);\n \/* This has to run after testContactList has run successfully. *\/\n CPPUNIT_ASSERT( mpAccepterContact != 0);\n bool bStarted = mpManager1->startBuddySession( pAcc1, mpAccepterContact);\n CPPUNIT_ASSERT( bStarted == true);\n}\n\nvoid TestTeleTubes::testStartBuddySession2()\n{\n \/\/bool bStarted = mpManager2->startBuddySession( sAcc2, sAcc1);\n \/\/CPPUNIT_ASSERT( bStarted == true);\n}\n\nvoid TestTeleTubes::testConnect1()\n{\n bool bConnected = mpManager1->connect();\n CPPUNIT_ASSERT( bConnected == true);\n}\n\nvoid TestTeleTubes::testConnect2()\n{\n bool bConnected = mpManager2->connect();\n CPPUNIT_ASSERT( bConnected == true);\n}\n\nvoid TestTeleTubes::testSendPacket()\n{\n TelePacket aPacket( \"\", RTL_CONSTASCII_STRINGPARAM( \"from 1 to 2\"));\n nSentPackets = mpManager1->sendPacket( aPacket);\n CPPUNIT_ASSERT( nSentPackets == 2); \/\/ expect out+in conference, as own instance accepted self\n}\n\nvoid TestTeleTubes::testReceivePacket()\n{\n TelePacket aPacket( \"\", RTL_CONSTASCII_STRINGPARAM( \"from 1 to 2\"));\n TelePacket aReceived;\n sal_uInt32 nReceivedPackets = 0;\n bool bOk;\n do\n {\n do\n {\n bOk = mpManager1->popPacket( aReceived);\n if (bOk)\n {\n ++nReceivedPackets;\n CPPUNIT_ASSERT( aPacket == aReceived);\n }\n } while (bOk);\n if (nReceivedPackets < nSentPackets)\n mpManager1->iterateLoop();\n } while (nReceivedPackets < nSentPackets);\n CPPUNIT_ASSERT( nReceivedPackets == nSentPackets);\n}\n\nvoid TestTeleTubes::testFlushLoops()\n{\n mpManager1->flushLoop();\n mpManager2->flushLoop();\n}\n\nvoid TestTeleTubes::testDestroyManager1()\n{\n delete mpManager1;\n mpManager1 = NULL;\n}\n\nvoid TestTeleTubes::testDestroyManager2()\n{\n delete mpManager2;\n mpManager2 = NULL;\n}\n\nvoid TestTeleTubes::testDestroyAccepterContact()\n{\n if (mpAccepterContact) {\n g_object_unref(mpAccepterContact);\n mpAccepterContact = NULL;\n }\n}\n\nvoid TestTeleTubes::testFailAlways()\n{\n CPPUNIT_ASSERT( false);\n}\n\n\nCPPUNIT_TEST_SUITE_REGISTRATION( TestTeleTubes);\n\n}\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>tubes test: refactor spinning mainloop<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012 Red Hat, Inc., Eike Rathke <erack@redhat.com>\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include <sal\/precppunit.hxx>\n\n#include <tubes\/contact-list.hxx>\n#include <tubes\/manager.hxx>\n\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n#include <rtl\/string.hxx>\n#include <rtl\/ustring.hxx>\n#include <rtl\/bootstrap.hxx>\n#include <unotest\/bootstrapfixturebase.hxx>\n\nnamespace {\n\nclass TestTeleTubes: public test::BootstrapFixtureBase\n{\npublic:\n\n TestTeleTubes();\n ~TestTeleTubes();\n void testSetupManager1();\n void testSetupManager2();\n void testConnect1();\n void testConnect2();\n void testContactList();\n void testPrepareAccountManager1();\n void testPrepareAccountManager2();\n void testStartBuddySession1();\n void testStartBuddySession2();\n void testSendPacket();\n void testReceivePacket();\n void testFlushLoops();\n void testDestroyManager1();\n void testDestroyManager2();\n void testDestroyAccepterContact();\n void testFailAlways();\n\n GMainLoop* mpMainLoop;\n void spinMainLoop();\n\n \/\/ Order is significant.\n CPPUNIT_TEST_SUITE( TestTeleTubes );\n CPPUNIT_TEST( testSetupManager1 );\n CPPUNIT_TEST( testSetupManager2 );\n CPPUNIT_TEST( testConnect1 );\n CPPUNIT_TEST( testConnect2 );\n CPPUNIT_TEST( testContactList );\n CPPUNIT_TEST( testPrepareAccountManager1 );\n CPPUNIT_TEST( testPrepareAccountManager2 );\n CPPUNIT_TEST( testStartBuddySession1 );\n CPPUNIT_TEST( testStartBuddySession2 );\n CPPUNIT_TEST( testSendPacket );\n CPPUNIT_TEST( testReceivePacket );\n CPPUNIT_TEST( testFlushLoops );\n CPPUNIT_TEST( testDestroyManager1 );\n CPPUNIT_TEST( testDestroyManager2 );\n CPPUNIT_TEST( testDestroyAccepterContact );\n CPPUNIT_TEST( testFailAlways ); \/\/ need failure to display SAL_LOG, comment out for real builds\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\/\/ XXX The Jabber accounts specified in test-config.ini need to be setup in\n\/\/ Empathy, enabled, connected, and on each other's rosters.\n rtl::OUString maTestConfigIniURL;\n rtl::Bootstrap maTestConfig;\n\n rtl::OString maOffererIdentifier;\n rtl::OString maAccepterIdentifier;\n};\n\n\/\/ static, not members, so they actually survive cppunit test iteration\nstatic TeleManager* mpManager1 = NULL;\nstatic TeleManager* mpManager2 = NULL;\n\nstatic TpContact* mpAccepterContact = NULL;\n\nstatic sal_uInt32 nSentPackets = 0;\n\nstatic gboolean\ntimed_out (void *user_data)\n{\n CPPUNIT_ASSERT_MESSAGE( \"Test took longer than ten seconds!\", false);\n\n GMainLoop *loop = reinterpret_cast<GMainLoop *>(user_data);\n\n g_main_loop_quit (loop);\n return FALSE;\n}\n\nTestTeleTubes::TestTeleTubes()\n : maTestConfigIniURL(getURLFromSrc(\"\/tubes\/qa\/test-config.ini\")),\n maTestConfig(maTestConfigIniURL)\n{\n TeleManager::addSuffixToNames( \"TeleTest\");\n\n rtl::OUString aOffererIdentifier;\n CPPUNIT_ASSERT_MESSAGE( \"See README for how to set up test-config.ini\",\n maTestConfig.getFrom(\"offerer\", aOffererIdentifier));\n maOffererIdentifier = OUStringToOString( aOffererIdentifier, RTL_TEXTENCODING_UTF8);\n\n rtl::OUString aAccepterIdentifier;\n CPPUNIT_ASSERT_MESSAGE( \"See README for how to set up test-config.ini\",\n maTestConfig.getFrom(\"accepter\", aAccepterIdentifier));\n maAccepterIdentifier = OUStringToOString( aAccepterIdentifier, RTL_TEXTENCODING_UTF8);\n\n mpMainLoop = g_main_loop_new (NULL, FALSE);\n g_timeout_add_seconds (10, timed_out, mpMainLoop);\n}\n\nTestTeleTubes::~TestTeleTubes()\n{\n g_main_loop_unref( mpMainLoop);\n mpMainLoop = NULL;\n}\n\nstatic void TeleTestTubes_ContactListPrepared( GError *errorOr0, void *user_data )\n{\n TestTeleTubes *self = reinterpret_cast<TestTeleTubes *>(user_data);\n\n CPPUNIT_ASSERT( errorOr0 == 0 );\n\n g_main_loop_quit (self->mpMainLoop);\n}\n\nvoid TestTeleTubes::spinMainLoop()\n{\n g_main_loop_run( mpMainLoop);\n}\n\nvoid TestTeleTubes::testContactList()\n{\n ContactList cl;\n cl.prepare( TeleTestTubes_ContactListPrepared, this );\n spinMainLoop();\n\n \/* Okay, now everything's prepared, we can get contacts synchronously. *\/\n AccountContactPairV pairs;\n\n pairs = cl.getContacts();\n guint i;\n\n \/* FIXME: this is racy, because we can't be 100% sure that MC has finished\n * discovering what we support and passing that on to the connection\n * manager...\n *\/\n\n \/* Both our accounts are meant to be signed in, and they both should be\n * capable of LibreOffice tubes because this test runs after we register\n * our handler. *\/\n CPPUNIT_ASSERT_MESSAGE(\n \"Make sure both your test accounts are signed in \"\n \"and are on each other's contact lists\",\n pairs.size() > 0 );\n CPPUNIT_ASSERT(!mpAccepterContact);\n\n for (i = 0; i < pairs.size(); i++)\n {\n AccountContactPair pair = pairs[i];\n\n \/* FIXME: verify that pair.first is the offerer account *\/\n if (tp_contact_get_identifier(pair.second) == maAccepterIdentifier) {\n mpAccepterContact = pair.second;\n g_object_ref(mpAccepterContact);\n }\n g_object_unref (pair.first);\n g_object_unref (pair.second);\n }\n\n CPPUNIT_ASSERT_MESSAGE(\n \"Couldn't find accepter contact. \"\n \"Make sure both your test accounts are signed in \"\n \"and are on each other's contact lists\",\n mpAccepterContact);\n}\n\nvoid TestTeleTubes::testSetupManager1()\n{\n mpManager1 = new TeleManager( true);\n}\n\nvoid TestTeleTubes::testSetupManager2()\n{\n mpManager2 = new TeleManager;\n}\n\nvoid TestTeleTubes::testPrepareAccountManager1()\n{\n mpManager1->prepareAccountManager();\n TeleManager::AccountManagerStatus eStatus = mpManager1->getAccountManagerStatus();\n CPPUNIT_ASSERT( eStatus == TeleManager::AMS_PREPARED);\n}\n\nvoid TestTeleTubes::testPrepareAccountManager2()\n{\n mpManager2->prepareAccountManager();\n TeleManager::AccountManagerStatus eStatus = mpManager2->getAccountManagerStatus();\n CPPUNIT_ASSERT( eStatus == TeleManager::AMS_PREPARED);\n}\n\nvoid TestTeleTubes::testStartBuddySession1()\n{\n TpAccount *pAcc1 = mpManager1->getAccount(maOffererIdentifier);\n CPPUNIT_ASSERT( pAcc1 != 0);\n \/* This has to run after testContactList has run successfully. *\/\n CPPUNIT_ASSERT( mpAccepterContact != 0);\n bool bStarted = mpManager1->startBuddySession( pAcc1, mpAccepterContact);\n CPPUNIT_ASSERT( bStarted == true);\n}\n\nvoid TestTeleTubes::testStartBuddySession2()\n{\n \/\/bool bStarted = mpManager2->startBuddySession( sAcc2, sAcc1);\n \/\/CPPUNIT_ASSERT( bStarted == true);\n}\n\nvoid TestTeleTubes::testConnect1()\n{\n bool bConnected = mpManager1->connect();\n CPPUNIT_ASSERT( bConnected == true);\n}\n\nvoid TestTeleTubes::testConnect2()\n{\n bool bConnected = mpManager2->connect();\n CPPUNIT_ASSERT( bConnected == true);\n}\n\nvoid TestTeleTubes::testSendPacket()\n{\n TelePacket aPacket( \"\", RTL_CONSTASCII_STRINGPARAM( \"from 1 to 2\"));\n nSentPackets = mpManager1->sendPacket( aPacket);\n CPPUNIT_ASSERT( nSentPackets == 2); \/\/ expect out+in conference, as own instance accepted self\n}\n\nvoid TestTeleTubes::testReceivePacket()\n{\n TelePacket aPacket( \"\", RTL_CONSTASCII_STRINGPARAM( \"from 1 to 2\"));\n TelePacket aReceived;\n sal_uInt32 nReceivedPackets = 0;\n bool bOk;\n do\n {\n do\n {\n bOk = mpManager1->popPacket( aReceived);\n if (bOk)\n {\n ++nReceivedPackets;\n CPPUNIT_ASSERT( aPacket == aReceived);\n }\n } while (bOk);\n if (nReceivedPackets < nSentPackets)\n mpManager1->iterateLoop();\n } while (nReceivedPackets < nSentPackets);\n CPPUNIT_ASSERT( nReceivedPackets == nSentPackets);\n}\n\nvoid TestTeleTubes::testFlushLoops()\n{\n mpManager1->flushLoop();\n mpManager2->flushLoop();\n}\n\nvoid TestTeleTubes::testDestroyManager1()\n{\n delete mpManager1;\n mpManager1 = NULL;\n}\n\nvoid TestTeleTubes::testDestroyManager2()\n{\n delete mpManager2;\n mpManager2 = NULL;\n}\n\nvoid TestTeleTubes::testDestroyAccepterContact()\n{\n if (mpAccepterContact) {\n g_object_unref(mpAccepterContact);\n mpAccepterContact = NULL;\n }\n}\n\nvoid TestTeleTubes::testFailAlways()\n{\n CPPUNIT_ASSERT( false);\n}\n\n\nCPPUNIT_TEST_SUITE_REGISTRATION( TestTeleTubes);\n\n}\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef CONTAINERS_ARCHIVE_BOOST_TYPES_HPP_\n#define CONTAINERS_ARCHIVE_BOOST_TYPES_HPP_\n\n#include \"errors.hpp\"\n#include <boost\/optional.hpp>\n#include <boost\/variant.hpp>\n#include <boost\/uuid\/uuid.hpp>\n\n#include \"containers\/archive\/archive.hpp\"\n\ninline\nwrite_message_t &operator<<(UNUSED write_message_t &msg, UNUSED boost::detail::variant::void_ &v) {\n unreachable(\"You cannot do operator<<(write_message_t &, boost::detail::variant::void_ &).\");\n}\n\ninline\nint deserialize(UNUSED read_stream_t *s, UNUSED boost::detail::variant::void_ *v) {\n unreachable(\"You cannot do deserialize(read_stream_t *, boost::detail::variant::void_ *).\");\n}\n\n\n#define ARCHIVE_VARIANT_SERIALIZE_VISITOR_METHOD(i) \\\n void operator()(const T##i &x) { \\\n uint8_t n = i; \\\n *(this->msg) << n; \\\n *(this->msg) << x; \\\n }\n\n#define ARCHIVE_VARIANT_SERIALIZE_USING_DECL(i) \\\n using v_##i##_t<ARCHIVE_TL##i>::operator()\n\nnamespace archive_nonsense {\n\ntemplate <class T20> struct v_20_t : public boost::static_visitor<void> {\n v_20_t() : msg(NULL) { }\n write_message_t *msg;\n\n ARCHIVE_VARIANT_SERIALIZE_VISITOR_METHOD(20);\nprivate:\n DISABLE_COPYING(v_20_t);\n};\n\n#define ARCHIVE_CLASS_DECL(i, j) template <ARCHIVE_CL##i> struct v_##i##_t : public v_##j##_t<ARCHIVE_TL##j> { ARCHIVE_VARIANT_SERIALIZE_USING_DECL(j); ARCHIVE_VARIANT_SERIALIZE_VISITOR_METHOD(i); }\n\n\n#define ARCHIVE_CL19 class T19, class T20\n#define ARCHIVE_TL20 T20\nARCHIVE_CLASS_DECL(19, 20);\n#define ARCHIVE_CL18 class T18, ARCHIVE_CL19\n#define ARCHIVE_TL19 T19, ARCHIVE_TL20\nARCHIVE_CLASS_DECL(18, 19);\n#define ARCHIVE_CL17 class T17, ARCHIVE_CL18\n#define ARCHIVE_TL18 T18, ARCHIVE_TL19\nARCHIVE_CLASS_DECL(17, 18);\n#define ARCHIVE_CL16 class T16, ARCHIVE_CL17\n#define ARCHIVE_TL17 T17, ARCHIVE_TL18\nARCHIVE_CLASS_DECL(16, 17);\n#define ARCHIVE_CL15 class T15, ARCHIVE_CL16\n#define ARCHIVE_TL16 T16, ARCHIVE_TL17\nARCHIVE_CLASS_DECL(15, 16);\n#define ARCHIVE_CL14 class T14, ARCHIVE_CL15\n#define ARCHIVE_TL15 T15, ARCHIVE_TL16\nARCHIVE_CLASS_DECL(14, 15);\n#define ARCHIVE_CL13 class T13, ARCHIVE_CL14\n#define ARCHIVE_TL14 T14, ARCHIVE_TL15\nARCHIVE_CLASS_DECL(13, 14);\n#define ARCHIVE_CL12 class T12, ARCHIVE_CL13\n#define ARCHIVE_TL13 T13, ARCHIVE_TL14\nARCHIVE_CLASS_DECL(12, 13);\n#define ARCHIVE_CL11 class T11, ARCHIVE_CL12\n#define ARCHIVE_TL12 T12, ARCHIVE_TL13\nARCHIVE_CLASS_DECL(11, 12);\n#define ARCHIVE_CL10 class T10, ARCHIVE_CL11\n#define ARCHIVE_TL11 T11, ARCHIVE_TL12\nARCHIVE_CLASS_DECL(10, 11);\n#define ARCHIVE_CL9 class T9, ARCHIVE_CL10\n#define ARCHIVE_TL10 T10, ARCHIVE_TL11\nARCHIVE_CLASS_DECL(9, 10);\n#define ARCHIVE_CL8 class T8, ARCHIVE_CL9\n#define ARCHIVE_TL9 T9, ARCHIVE_TL10\nARCHIVE_CLASS_DECL(8, 9);\n#define ARCHIVE_CL7 class T7, ARCHIVE_CL8\n#define ARCHIVE_TL8 T8, ARCHIVE_TL9\nARCHIVE_CLASS_DECL(7, 8);\n#define ARCHIVE_CL6 class T6, ARCHIVE_CL7\n#define ARCHIVE_TL7 T7, ARCHIVE_TL8\nARCHIVE_CLASS_DECL(6, 7);\n#define ARCHIVE_CL5 class T5, ARCHIVE_CL6\n#define ARCHIVE_TL6 T6, ARCHIVE_TL7\nARCHIVE_CLASS_DECL(5, 6);\n#define ARCHIVE_CL4 class T4, ARCHIVE_CL5\n#define ARCHIVE_TL5 T5, ARCHIVE_TL6\nARCHIVE_CLASS_DECL(4, 5);\n#define ARCHIVE_CL3 class T3, ARCHIVE_CL4\n#define ARCHIVE_TL4 T4, ARCHIVE_TL5\nARCHIVE_CLASS_DECL(3, 4);\n#define ARCHIVE_CL2 class T2, ARCHIVE_CL3\n#define ARCHIVE_TL3 T3, ARCHIVE_TL4\nARCHIVE_CLASS_DECL(2, 3);\n#define ARCHIVE_CL1 class T1, ARCHIVE_CL2\n#define ARCHIVE_TL2 T2, ARCHIVE_TL3\nARCHIVE_CLASS_DECL(1, 2);\n\n} \/\/ namespace archive_nonsense\n\ntemplate <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16, class T17, class T18, class T19, class T20>\nwrite_message_t &operator<<(write_message_t &msg, const boost::variant<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> &x) {\n archive_nonsense::v_1_t<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> visitor;\n rassert(sizeof(visitor) == sizeof(write_message_t *));\n\n visitor.msg = &msg;\n\n boost::apply_visitor(visitor, x);\n\n return msg;\n}\n\ntemplate <class T> struct archive_variant_deserialize_standin_t {\n template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16, class T17, class T18, class T19, class T20>\n int do_the_deserialization(read_stream_t *s, boost::variant<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> *x) {\n T v;\n int res = deserialize(s, &v);\n if (res) { return res; }\n *x = v;\n }\n };\n\ntemplate <> struct archive_variant_deserialize_standin_t<boost::detail::variant::void_> {\n template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16, class T17, class T18, class T19, class T20>\n int do_the_deserialization(UNUSED read_stream_t *s, UNUSED boost::variant<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> *x) {\n return -3;\n }\n};\n\ntemplate <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16, class T17, class T18, class T19, class T20>\nint deserialize(read_stream_t *s, boost::variant<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> *x) {\n uint8_t n;\n int res = deserialize(s, &n);\n if (res) { return res; }\n if (!(1 <= n && n <= 20)) {\n return -3;\n }\n\n#define ARCHIVE_DESERIALIZE_CASE(i) case i: { archive_variant_deserialize_standin_t<T##i> st; return st.do_the_deserialization(s, x); }\n\n switch (n) {\n case 1: { archive_variant_deserialize_standin_t<T1> st; return st.do_the_deserialization(s, x); }\n case 2: { archive_variant_deserialize_standin_t<T2> st; return st.do_the_deserialization(s, x); }\n case 3: { archive_variant_deserialize_standin_t<T3> st; return st.do_the_deserialization(s, x); }\n case 4: { archive_variant_deserialize_standin_t<T4> st; return st.do_the_deserialization(s, x); }\n case 5: { archive_variant_deserialize_standin_t<T5> st; return st.do_the_deserialization(s, x); }\n case 6: { archive_variant_deserialize_standin_t<T6> st; return st.do_the_deserialization(s, x); }\n case 7: { archive_variant_deserialize_standin_t<T7> st; return st.do_the_deserialization(s, x); }\n case 8: { archive_variant_deserialize_standin_t<T8> st; return st.do_the_deserialization(s, x); }\n case 9: { archive_variant_deserialize_standin_t<T9> st; return st.do_the_deserialization(s, x); }\n case 10: { archive_variant_deserialize_standin_t<T10> st; return st.do_the_deserialization(s, x); }\n case 11: { archive_variant_deserialize_standin_t<T11> st; return st.do_the_deserialization(s, x); }\n case 12: { archive_variant_deserialize_standin_t<T12> st; return st.do_the_deserialization(s, x); }\n case 13: { archive_variant_deserialize_standin_t<T13> st; return st.do_the_deserialization(s, x); }\n case 14: { archive_variant_deserialize_standin_t<T14> st; return st.do_the_deserialization(s, x); }\n case 15: { archive_variant_deserialize_standin_t<T15> st; return st.do_the_deserialization(s, x); }\n case 16: { archive_variant_deserialize_standin_t<T16> st; return st.do_the_deserialization(s, x); }\n case 17: { archive_variant_deserialize_standin_t<T17> st; return st.do_the_deserialization(s, x); }\n case 18: { archive_variant_deserialize_standin_t<T18> st; return st.do_the_deserialization(s, x); }\n case 19: { archive_variant_deserialize_standin_t<T19> st; return st.do_the_deserialization(s, x); }\n case 20: { archive_variant_deserialize_standin_t<T20> st; return st.do_the_deserialization(s, x); }\n\n default:\n unreachable(\"impossible to reach, we already returned -3\");\n }\n\n unreachable(\"impossible to reach, we return from every case of the switch statement\");\n}\n\n\ninline write_message_t &operator<<(write_message_t &msg, const boost::uuids::uuid &uuid) {\n msg.append(uuid.data, boost::uuids::uuid::static_size());\n return msg;\n}\n\ninline int deserialize(read_stream_t *s, boost::uuids::uuid *uuid) {\n int64_t sz = boost::uuids::uuid::static_size();\n int64_t res = force_read(s, uuid->data, sz);\n\n if (res == -1) { return -1; }\n if (res < sz) { return -2; }\n rassert(res == sz);\n return 0;\n}\n\n\ntemplate <class T>\nwrite_message_t &operator<<(write_message_t &msg, const boost::optional<T> &x) {\n const T *ptr = x.get_ptr();\n bool exists = ptr;\n msg << exists;\n if (exists) {\n msg << *ptr;\n }\n return msg;\n}\n\ntemplate <class T>\nint deserialize(read_stream_t *s, boost::optional<T> *x) {\n bool exists;\n rassert(!x->get_ptr());\n\n int res = deserialize(s, &exists);\n if (res) { return res; }\n if (exists) {\n x->reset(T());\n res = deserialize(s, x->get_ptr());\n return res;\n } else {\n x->reset();\n return 0;\n }\n}\n\n#endif \/\/ CONTAINERS_ARCHIVE_BOOST_TYPES_HPP_\n<commit_msg>Removed an unused macro in boost_types.hpp.<commit_after>#ifndef CONTAINERS_ARCHIVE_BOOST_TYPES_HPP_\n#define CONTAINERS_ARCHIVE_BOOST_TYPES_HPP_\n\n#include \"errors.hpp\"\n#include <boost\/optional.hpp>\n#include <boost\/variant.hpp>\n#include <boost\/uuid\/uuid.hpp>\n\n#include \"containers\/archive\/archive.hpp\"\n\ninline\nwrite_message_t &operator<<(UNUSED write_message_t &msg, UNUSED boost::detail::variant::void_ &v) {\n unreachable(\"You cannot do operator<<(write_message_t &, boost::detail::variant::void_ &).\");\n}\n\ninline\nint deserialize(UNUSED read_stream_t *s, UNUSED boost::detail::variant::void_ *v) {\n unreachable(\"You cannot do deserialize(read_stream_t *, boost::detail::variant::void_ *).\");\n}\n\n\n#define ARCHIVE_VARIANT_SERIALIZE_VISITOR_METHOD(i) \\\n void operator()(const T##i &x) { \\\n uint8_t n = i; \\\n *(this->msg) << n; \\\n *(this->msg) << x; \\\n }\n\n#define ARCHIVE_VARIANT_SERIALIZE_USING_DECL(i) \\\n using v_##i##_t<ARCHIVE_TL##i>::operator()\n\nnamespace archive_nonsense {\n\ntemplate <class T20> struct v_20_t : public boost::static_visitor<void> {\n v_20_t() : msg(NULL) { }\n write_message_t *msg;\n\n ARCHIVE_VARIANT_SERIALIZE_VISITOR_METHOD(20);\nprivate:\n DISABLE_COPYING(v_20_t);\n};\n\n#define ARCHIVE_CLASS_DECL(i, j) template <ARCHIVE_CL##i> struct v_##i##_t : public v_##j##_t<ARCHIVE_TL##j> { ARCHIVE_VARIANT_SERIALIZE_USING_DECL(j); ARCHIVE_VARIANT_SERIALIZE_VISITOR_METHOD(i); }\n\n\n#define ARCHIVE_CL19 class T19, class T20\n#define ARCHIVE_TL20 T20\nARCHIVE_CLASS_DECL(19, 20);\n#define ARCHIVE_CL18 class T18, ARCHIVE_CL19\n#define ARCHIVE_TL19 T19, ARCHIVE_TL20\nARCHIVE_CLASS_DECL(18, 19);\n#define ARCHIVE_CL17 class T17, ARCHIVE_CL18\n#define ARCHIVE_TL18 T18, ARCHIVE_TL19\nARCHIVE_CLASS_DECL(17, 18);\n#define ARCHIVE_CL16 class T16, ARCHIVE_CL17\n#define ARCHIVE_TL17 T17, ARCHIVE_TL18\nARCHIVE_CLASS_DECL(16, 17);\n#define ARCHIVE_CL15 class T15, ARCHIVE_CL16\n#define ARCHIVE_TL16 T16, ARCHIVE_TL17\nARCHIVE_CLASS_DECL(15, 16);\n#define ARCHIVE_CL14 class T14, ARCHIVE_CL15\n#define ARCHIVE_TL15 T15, ARCHIVE_TL16\nARCHIVE_CLASS_DECL(14, 15);\n#define ARCHIVE_CL13 class T13, ARCHIVE_CL14\n#define ARCHIVE_TL14 T14, ARCHIVE_TL15\nARCHIVE_CLASS_DECL(13, 14);\n#define ARCHIVE_CL12 class T12, ARCHIVE_CL13\n#define ARCHIVE_TL13 T13, ARCHIVE_TL14\nARCHIVE_CLASS_DECL(12, 13);\n#define ARCHIVE_CL11 class T11, ARCHIVE_CL12\n#define ARCHIVE_TL12 T12, ARCHIVE_TL13\nARCHIVE_CLASS_DECL(11, 12);\n#define ARCHIVE_CL10 class T10, ARCHIVE_CL11\n#define ARCHIVE_TL11 T11, ARCHIVE_TL12\nARCHIVE_CLASS_DECL(10, 11);\n#define ARCHIVE_CL9 class T9, ARCHIVE_CL10\n#define ARCHIVE_TL10 T10, ARCHIVE_TL11\nARCHIVE_CLASS_DECL(9, 10);\n#define ARCHIVE_CL8 class T8, ARCHIVE_CL9\n#define ARCHIVE_TL9 T9, ARCHIVE_TL10\nARCHIVE_CLASS_DECL(8, 9);\n#define ARCHIVE_CL7 class T7, ARCHIVE_CL8\n#define ARCHIVE_TL8 T8, ARCHIVE_TL9\nARCHIVE_CLASS_DECL(7, 8);\n#define ARCHIVE_CL6 class T6, ARCHIVE_CL7\n#define ARCHIVE_TL7 T7, ARCHIVE_TL8\nARCHIVE_CLASS_DECL(6, 7);\n#define ARCHIVE_CL5 class T5, ARCHIVE_CL6\n#define ARCHIVE_TL6 T6, ARCHIVE_TL7\nARCHIVE_CLASS_DECL(5, 6);\n#define ARCHIVE_CL4 class T4, ARCHIVE_CL5\n#define ARCHIVE_TL5 T5, ARCHIVE_TL6\nARCHIVE_CLASS_DECL(4, 5);\n#define ARCHIVE_CL3 class T3, ARCHIVE_CL4\n#define ARCHIVE_TL4 T4, ARCHIVE_TL5\nARCHIVE_CLASS_DECL(3, 4);\n#define ARCHIVE_CL2 class T2, ARCHIVE_CL3\n#define ARCHIVE_TL3 T3, ARCHIVE_TL4\nARCHIVE_CLASS_DECL(2, 3);\n#define ARCHIVE_CL1 class T1, ARCHIVE_CL2\n#define ARCHIVE_TL2 T2, ARCHIVE_TL3\nARCHIVE_CLASS_DECL(1, 2);\n\n} \/\/ namespace archive_nonsense\n\ntemplate <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16, class T17, class T18, class T19, class T20>\nwrite_message_t &operator<<(write_message_t &msg, const boost::variant<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> &x) {\n archive_nonsense::v_1_t<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> visitor;\n rassert(sizeof(visitor) == sizeof(write_message_t *));\n\n visitor.msg = &msg;\n\n boost::apply_visitor(visitor, x);\n\n return msg;\n}\n\ntemplate <class T> struct archive_variant_deserialize_standin_t {\n template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16, class T17, class T18, class T19, class T20>\n int do_the_deserialization(read_stream_t *s, boost::variant<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> *x) {\n T v;\n int res = deserialize(s, &v);\n if (res) { return res; }\n *x = v;\n }\n };\n\ntemplate <> struct archive_variant_deserialize_standin_t<boost::detail::variant::void_> {\n template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16, class T17, class T18, class T19, class T20>\n int do_the_deserialization(UNUSED read_stream_t *s, UNUSED boost::variant<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> *x) {\n return -3;\n }\n};\n\ntemplate <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16, class T17, class T18, class T19, class T20>\nint deserialize(read_stream_t *s, boost::variant<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> *x) {\n uint8_t n;\n int res = deserialize(s, &n);\n if (res) { return res; }\n if (!(1 <= n && n <= 20)) {\n return -3;\n }\n\n switch (n) {\n case 1: { archive_variant_deserialize_standin_t<T1> st; return st.do_the_deserialization(s, x); }\n case 2: { archive_variant_deserialize_standin_t<T2> st; return st.do_the_deserialization(s, x); }\n case 3: { archive_variant_deserialize_standin_t<T3> st; return st.do_the_deserialization(s, x); }\n case 4: { archive_variant_deserialize_standin_t<T4> st; return st.do_the_deserialization(s, x); }\n case 5: { archive_variant_deserialize_standin_t<T5> st; return st.do_the_deserialization(s, x); }\n case 6: { archive_variant_deserialize_standin_t<T6> st; return st.do_the_deserialization(s, x); }\n case 7: { archive_variant_deserialize_standin_t<T7> st; return st.do_the_deserialization(s, x); }\n case 8: { archive_variant_deserialize_standin_t<T8> st; return st.do_the_deserialization(s, x); }\n case 9: { archive_variant_deserialize_standin_t<T9> st; return st.do_the_deserialization(s, x); }\n case 10: { archive_variant_deserialize_standin_t<T10> st; return st.do_the_deserialization(s, x); }\n case 11: { archive_variant_deserialize_standin_t<T11> st; return st.do_the_deserialization(s, x); }\n case 12: { archive_variant_deserialize_standin_t<T12> st; return st.do_the_deserialization(s, x); }\n case 13: { archive_variant_deserialize_standin_t<T13> st; return st.do_the_deserialization(s, x); }\n case 14: { archive_variant_deserialize_standin_t<T14> st; return st.do_the_deserialization(s, x); }\n case 15: { archive_variant_deserialize_standin_t<T15> st; return st.do_the_deserialization(s, x); }\n case 16: { archive_variant_deserialize_standin_t<T16> st; return st.do_the_deserialization(s, x); }\n case 17: { archive_variant_deserialize_standin_t<T17> st; return st.do_the_deserialization(s, x); }\n case 18: { archive_variant_deserialize_standin_t<T18> st; return st.do_the_deserialization(s, x); }\n case 19: { archive_variant_deserialize_standin_t<T19> st; return st.do_the_deserialization(s, x); }\n case 20: { archive_variant_deserialize_standin_t<T20> st; return st.do_the_deserialization(s, x); }\n\n default:\n unreachable(\"impossible to reach, we already returned -3\");\n }\n\n unreachable(\"impossible to reach, we return from every case of the switch statement\");\n}\n\n\ninline write_message_t &operator<<(write_message_t &msg, const boost::uuids::uuid &uuid) {\n msg.append(uuid.data, boost::uuids::uuid::static_size());\n return msg;\n}\n\ninline int deserialize(read_stream_t *s, boost::uuids::uuid *uuid) {\n int64_t sz = boost::uuids::uuid::static_size();\n int64_t res = force_read(s, uuid->data, sz);\n\n if (res == -1) { return -1; }\n if (res < sz) { return -2; }\n rassert(res == sz);\n return 0;\n}\n\n\ntemplate <class T>\nwrite_message_t &operator<<(write_message_t &msg, const boost::optional<T> &x) {\n const T *ptr = x.get_ptr();\n bool exists = ptr;\n msg << exists;\n if (exists) {\n msg << *ptr;\n }\n return msg;\n}\n\ntemplate <class T>\nint deserialize(read_stream_t *s, boost::optional<T> *x) {\n bool exists;\n rassert(!x->get_ptr());\n\n int res = deserialize(s, &exists);\n if (res) { return res; }\n if (exists) {\n x->reset(T());\n res = deserialize(s, x->get_ptr());\n return res;\n } else {\n x->reset();\n return 0;\n }\n}\n\n#endif \/\/ CONTAINERS_ARCHIVE_BOOST_TYPES_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015 gRPC authors.\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#include <grpc\/support\/port_platform.h>\n\n#include \"src\/core\/lib\/iomgr\/port.h\"\n\n#ifdef GRPC_POSIX_SOCKET_TCP_CLIENT\n\n#include \"src\/core\/lib\/iomgr\/tcp_client_posix.h\"\n\n#include <errno.h>\n#include <netinet\/in.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/string_util.h>\n#include <grpc\/support\/time.h>\n\n#include \"src\/core\/lib\/channel\/channel_args.h\"\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"src\/core\/lib\/iomgr\/ev_posix.h\"\n#include \"src\/core\/lib\/iomgr\/iomgr_posix.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr_utils.h\"\n#include \"src\/core\/lib\/iomgr\/socket_mutator.h\"\n#include \"src\/core\/lib\/iomgr\/socket_utils_posix.h\"\n#include \"src\/core\/lib\/iomgr\/tcp_posix.h\"\n#include \"src\/core\/lib\/iomgr\/timer.h\"\n#include \"src\/core\/lib\/iomgr\/unix_sockets_posix.h\"\n#include \"src\/core\/lib\/slice\/slice_internal.h\"\n\nextern grpc_core::TraceFlag grpc_tcp_trace;\n\ntypedef struct {\n gpr_mu mu;\n grpc_fd* fd;\n grpc_timer alarm;\n grpc_closure on_alarm;\n int refs;\n grpc_closure write_closure;\n grpc_pollset_set* interested_parties;\n char* addr_str;\n grpc_endpoint** ep;\n grpc_closure* closure;\n grpc_channel_args* channel_args;\n} async_connect;\n\nstatic grpc_error* prepare_socket(const grpc_resolved_address* addr, int fd,\n const grpc_channel_args* channel_args) {\n grpc_error* err = GRPC_ERROR_NONE;\n\n GPR_ASSERT(fd >= 0);\n\n err = grpc_set_socket_nonblocking(fd, 1);\n if (err != GRPC_ERROR_NONE) goto error;\n err = grpc_set_socket_cloexec(fd, 1);\n if (err != GRPC_ERROR_NONE) goto error;\n if (!grpc_is_unix_socket(addr)) {\n err = grpc_set_socket_low_latency(fd, 1);\n if (err != GRPC_ERROR_NONE) goto error;\n err = grpc_set_socket_tcp_user_timeout(fd, channel_args,\n true \/* is_client *\/);\n if (err != GRPC_ERROR_NONE) goto error;\n }\n err = grpc_set_socket_no_sigpipe_if_possible(fd);\n if (err != GRPC_ERROR_NONE) goto error;\n if (channel_args) {\n for (size_t i = 0; i < channel_args->num_args; i++) {\n if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_SOCKET_MUTATOR)) {\n GPR_ASSERT(channel_args->args[i].type == GRPC_ARG_POINTER);\n grpc_socket_mutator* mutator = static_cast<grpc_socket_mutator*>(\n channel_args->args[i].value.pointer.p);\n err = grpc_set_socket_with_mutator(fd, mutator);\n if (err != GRPC_ERROR_NONE) goto error;\n }\n }\n }\n goto done;\n\nerror:\n if (fd >= 0) {\n close(fd);\n }\ndone:\n return err;\n}\n\nstatic void tc_on_alarm(void* acp, grpc_error* error) {\n int done;\n async_connect* ac = static_cast<async_connect*>(acp);\n if (grpc_tcp_trace.enabled()) {\n const char* str = grpc_error_string(error);\n gpr_log(GPR_INFO, \"CLIENT_CONNECT: %s: on_alarm: error=%s\", ac->addr_str,\n str);\n }\n gpr_mu_lock(&ac->mu);\n if (ac->fd != nullptr) {\n grpc_fd_shutdown(\n ac->fd, GRPC_ERROR_CREATE_FROM_STATIC_STRING(\"connect() timed out\"));\n }\n done = (--ac->refs == 0);\n gpr_mu_unlock(&ac->mu);\n if (done) {\n gpr_mu_destroy(&ac->mu);\n gpr_free(ac->addr_str);\n grpc_channel_args_destroy(ac->channel_args);\n gpr_free(ac);\n }\n}\n\ngrpc_endpoint* grpc_tcp_client_create_from_fd(\n grpc_fd* fd, const grpc_channel_args* channel_args, const char* addr_str) {\n return grpc_tcp_create(fd, channel_args, addr_str);\n}\n\nstatic void on_writable(void* acp, grpc_error* error) {\n async_connect* ac = static_cast<async_connect*>(acp);\n int so_error = 0;\n socklen_t so_error_size;\n int err;\n int done;\n grpc_endpoint** ep = ac->ep;\n grpc_closure* closure = ac->closure;\n grpc_fd* fd;\n\n GRPC_ERROR_REF(error);\n\n if (grpc_tcp_trace.enabled()) {\n const char* str = grpc_error_string(error);\n gpr_log(GPR_INFO, \"CLIENT_CONNECT: %s: on_writable: error=%s\", ac->addr_str,\n str);\n }\n\n gpr_mu_lock(&ac->mu);\n GPR_ASSERT(ac->fd);\n fd = ac->fd;\n ac->fd = nullptr;\n gpr_mu_unlock(&ac->mu);\n\n grpc_timer_cancel(&ac->alarm);\n\n gpr_mu_lock(&ac->mu);\n if (error != GRPC_ERROR_NONE) {\n error =\n grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,\n grpc_slice_from_static_string(\"Timeout occurred\"));\n goto finish;\n }\n\n do {\n so_error_size = sizeof(so_error);\n err = getsockopt(grpc_fd_wrapped_fd(fd), SOL_SOCKET, SO_ERROR, &so_error,\n &so_error_size);\n } while (err < 0 && errno == EINTR);\n if (err < 0) {\n error = GRPC_OS_ERROR(errno, \"getsockopt\");\n goto finish;\n }\n\n switch (so_error) {\n case 0:\n grpc_pollset_set_del_fd(ac->interested_parties, fd);\n *ep = grpc_tcp_client_create_from_fd(fd, ac->channel_args, ac->addr_str);\n fd = nullptr;\n break;\n case ENOBUFS:\n \/* We will get one of these errors if we have run out of\n memory in the kernel for the data structures allocated\n when you connect a socket. If this happens it is very\n likely that if we wait a little bit then try again the\n connection will work (since other programs or this\n program will close their network connections and free up\n memory). This does _not_ indicate that there is anything\n wrong with the server we are connecting to, this is a\n local problem.\n\n If you are looking at this code, then chances are that\n your program or another program on the same computer\n opened too many network connections. The \"easy\" fix:\n don't do that! *\/\n gpr_log(GPR_ERROR, \"kernel out of buffers\");\n gpr_mu_unlock(&ac->mu);\n grpc_fd_notify_on_write(fd, &ac->write_closure);\n return;\n case ECONNREFUSED:\n \/* This error shouldn't happen for anything other than connect(). *\/\n error = GRPC_OS_ERROR(so_error, \"connect\");\n break;\n default:\n \/* We don't really know which syscall triggered the problem here,\n so punt by reporting getsockopt(). *\/\n error = GRPC_OS_ERROR(so_error, \"getsockopt(SO_ERROR)\");\n break;\n }\n\nfinish:\n if (fd != nullptr) {\n grpc_pollset_set_del_fd(ac->interested_parties, fd);\n grpc_fd_orphan(fd, nullptr, nullptr, \"tcp_client_orphan\");\n fd = nullptr;\n }\n done = (--ac->refs == 0);\n \/\/ Create a copy of the data from \"ac\" to be accessed after the unlock, as\n \/\/ \"ac\" and its contents may be deallocated by the time they are read.\n const grpc_slice addr_str_slice = grpc_slice_from_copied_string(ac->addr_str);\n gpr_mu_unlock(&ac->mu);\n if (error != GRPC_ERROR_NONE) {\n char* error_descr;\n grpc_slice str;\n bool ret = grpc_error_get_str(error, GRPC_ERROR_STR_DESCRIPTION, &str);\n GPR_ASSERT(ret);\n char* desc = grpc_slice_to_c_string(str);\n gpr_asprintf(&error_descr, \"Failed to connect to remote host: %s\", desc);\n error = grpc_error_set_str(error, GRPC_ERROR_STR_DESCRIPTION,\n grpc_slice_from_copied_string(error_descr));\n gpr_free(error_descr);\n gpr_free(desc);\n error = grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,\n addr_str_slice \/* takes ownership *\/);\n } else {\n grpc_slice_unref_internal(addr_str_slice);\n }\n if (done) {\n \/\/ This is safe even outside the lock, because \"done\", the sentinel, is\n \/\/ populated *inside* the lock.\n gpr_mu_destroy(&ac->mu);\n gpr_free(ac->addr_str);\n grpc_channel_args_destroy(ac->channel_args);\n gpr_free(ac);\n }\n GRPC_CLOSURE_SCHED(closure, error);\n}\n\ngrpc_error* grpc_tcp_client_prepare_fd(const grpc_channel_args* channel_args,\n const grpc_resolved_address* addr,\n grpc_resolved_address* mapped_addr,\n grpc_fd** fdobj) {\n grpc_dualstack_mode dsmode;\n int fd;\n grpc_error* error;\n char* name;\n char* addr_str;\n *fdobj = nullptr;\n \/* Use dualstack sockets where available. Set mapped to v6 or v4 mapped to\n v6. *\/\n if (!grpc_sockaddr_to_v4mapped(addr, mapped_addr)) {\n \/* addr is v4 mapped to v6 or v6. *\/\n memcpy(mapped_addr, addr, sizeof(*mapped_addr));\n }\n error =\n grpc_create_dualstack_socket(mapped_addr, SOCK_STREAM, 0, &dsmode, &fd);\n if (error != GRPC_ERROR_NONE) {\n return error;\n }\n if (dsmode == GRPC_DSMODE_IPV4) {\n \/* Original addr is either v4 or v4 mapped to v6. Set mapped_addr to v4. *\/\n if (!grpc_sockaddr_is_v4mapped(addr, mapped_addr)) {\n memcpy(mapped_addr, addr, sizeof(*mapped_addr));\n }\n }\n if ((error = prepare_socket(mapped_addr, fd, channel_args)) !=\n GRPC_ERROR_NONE) {\n return error;\n }\n addr_str = grpc_sockaddr_to_uri(mapped_addr);\n gpr_asprintf(&name, \"tcp-client:%s\", addr_str);\n *fdobj = grpc_fd_create(fd, name, true);\n gpr_free(name);\n gpr_free(addr_str);\n return GRPC_ERROR_NONE;\n}\n\nvoid grpc_tcp_client_create_from_prepared_fd(\n grpc_pollset_set* interested_parties, grpc_closure* closure, grpc_fd* fdobj,\n const grpc_channel_args* channel_args, const grpc_resolved_address* addr,\n grpc_millis deadline, grpc_endpoint** ep) {\n const int fd = grpc_fd_wrapped_fd(fdobj);\n int err;\n async_connect* ac;\n do {\n err = connect(fd, reinterpret_cast<const grpc_sockaddr*>(addr->addr),\n addr->len);\n } while (err < 0 && errno == EINTR);\n if (err >= 0) {\n char* addr_str = grpc_sockaddr_to_uri(addr);\n *ep = grpc_tcp_client_create_from_fd(fdobj, channel_args, addr_str);\n gpr_free(addr_str);\n GRPC_CLOSURE_SCHED(closure, GRPC_ERROR_NONE);\n return;\n }\n if (errno != EWOULDBLOCK && errno != EINPROGRESS) {\n grpc_fd_orphan(fdobj, nullptr, nullptr, \"tcp_client_connect_error\");\n GRPC_CLOSURE_SCHED(closure, GRPC_OS_ERROR(errno, \"connect\"));\n return;\n }\n\n grpc_pollset_set_add_fd(interested_parties, fdobj);\n\n ac = static_cast<async_connect*>(gpr_malloc(sizeof(async_connect)));\n ac->closure = closure;\n ac->ep = ep;\n ac->fd = fdobj;\n ac->interested_parties = interested_parties;\n ac->addr_str = grpc_sockaddr_to_uri(addr);\n gpr_mu_init(&ac->mu);\n ac->refs = 2;\n GRPC_CLOSURE_INIT(&ac->write_closure, on_writable, ac,\n grpc_schedule_on_exec_ctx);\n ac->channel_args = grpc_channel_args_copy(channel_args);\n\n if (grpc_tcp_trace.enabled()) {\n gpr_log(GPR_INFO, \"CLIENT_CONNECT: %s: asynchronously connecting fd %p\",\n ac->addr_str, fdobj);\n }\n\n gpr_mu_lock(&ac->mu);\n GRPC_CLOSURE_INIT(&ac->on_alarm, tc_on_alarm, ac, grpc_schedule_on_exec_ctx);\n grpc_timer_init(&ac->alarm, deadline, &ac->on_alarm);\n grpc_fd_notify_on_write(ac->fd, &ac->write_closure);\n gpr_mu_unlock(&ac->mu);\n}\n\nstatic void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,\n grpc_pollset_set* interested_parties,\n const grpc_channel_args* channel_args,\n const grpc_resolved_address* addr,\n grpc_millis deadline) {\n grpc_resolved_address mapped_addr;\n grpc_fd* fdobj = nullptr;\n grpc_error* error;\n *ep = nullptr;\n if ((error = grpc_tcp_client_prepare_fd(channel_args, addr, &mapped_addr,\n &fdobj)) != GRPC_ERROR_NONE) {\n GRPC_CLOSURE_SCHED(closure, error);\n return;\n }\n grpc_tcp_client_create_from_prepared_fd(interested_parties, closure, fdobj,\n channel_args, &mapped_addr, deadline,\n ep);\n}\n\ngrpc_tcp_client_vtable grpc_posix_tcp_client_vtable = {tcp_connect};\n#endif\n<commit_msg>Enable SO_REUSEADDR in client sockets<commit_after>\/*\n *\n * Copyright 2015 gRPC authors.\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#include <grpc\/support\/port_platform.h>\n\n#include \"src\/core\/lib\/iomgr\/port.h\"\n\n#ifdef GRPC_POSIX_SOCKET_TCP_CLIENT\n\n#include \"src\/core\/lib\/iomgr\/tcp_client_posix.h\"\n\n#include <errno.h>\n#include <netinet\/in.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/string_util.h>\n#include <grpc\/support\/time.h>\n\n#include \"src\/core\/lib\/channel\/channel_args.h\"\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"src\/core\/lib\/iomgr\/ev_posix.h\"\n#include \"src\/core\/lib\/iomgr\/iomgr_posix.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr_utils.h\"\n#include \"src\/core\/lib\/iomgr\/socket_mutator.h\"\n#include \"src\/core\/lib\/iomgr\/socket_utils_posix.h\"\n#include \"src\/core\/lib\/iomgr\/tcp_posix.h\"\n#include \"src\/core\/lib\/iomgr\/timer.h\"\n#include \"src\/core\/lib\/iomgr\/unix_sockets_posix.h\"\n#include \"src\/core\/lib\/slice\/slice_internal.h\"\n\nextern grpc_core::TraceFlag grpc_tcp_trace;\n\ntypedef struct {\n gpr_mu mu;\n grpc_fd* fd;\n grpc_timer alarm;\n grpc_closure on_alarm;\n int refs;\n grpc_closure write_closure;\n grpc_pollset_set* interested_parties;\n char* addr_str;\n grpc_endpoint** ep;\n grpc_closure* closure;\n grpc_channel_args* channel_args;\n} async_connect;\n\nstatic grpc_error* prepare_socket(const grpc_resolved_address* addr, int fd,\n const grpc_channel_args* channel_args) {\n grpc_error* err = GRPC_ERROR_NONE;\n\n GPR_ASSERT(fd >= 0);\n\n err = grpc_set_socket_nonblocking(fd, 1);\n if (err != GRPC_ERROR_NONE) goto error;\n err = grpc_set_socket_cloexec(fd, 1);\n if (err != GRPC_ERROR_NONE) goto error;\n if (!grpc_is_unix_socket(addr)) {\n err = grpc_set_socket_low_latency(fd, 1);\n if (err != GRPC_ERROR_NONE) goto error;\n err = grpc_set_socket_reuse_addr(fd, 1);\n if (err != GRPC_ERROR_NONE) goto error;\n err = grpc_set_socket_tcp_user_timeout(fd, channel_args,\n true \/* is_client *\/);\n if (err != GRPC_ERROR_NONE) goto error;\n }\n err = grpc_set_socket_no_sigpipe_if_possible(fd);\n if (err != GRPC_ERROR_NONE) goto error;\n if (channel_args) {\n for (size_t i = 0; i < channel_args->num_args; i++) {\n if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_SOCKET_MUTATOR)) {\n GPR_ASSERT(channel_args->args[i].type == GRPC_ARG_POINTER);\n grpc_socket_mutator* mutator = static_cast<grpc_socket_mutator*>(\n channel_args->args[i].value.pointer.p);\n err = grpc_set_socket_with_mutator(fd, mutator);\n if (err != GRPC_ERROR_NONE) goto error;\n }\n }\n }\n goto done;\n\nerror:\n if (fd >= 0) {\n close(fd);\n }\ndone:\n return err;\n}\n\nstatic void tc_on_alarm(void* acp, grpc_error* error) {\n int done;\n async_connect* ac = static_cast<async_connect*>(acp);\n if (grpc_tcp_trace.enabled()) {\n const char* str = grpc_error_string(error);\n gpr_log(GPR_INFO, \"CLIENT_CONNECT: %s: on_alarm: error=%s\", ac->addr_str,\n str);\n }\n gpr_mu_lock(&ac->mu);\n if (ac->fd != nullptr) {\n grpc_fd_shutdown(\n ac->fd, GRPC_ERROR_CREATE_FROM_STATIC_STRING(\"connect() timed out\"));\n }\n done = (--ac->refs == 0);\n gpr_mu_unlock(&ac->mu);\n if (done) {\n gpr_mu_destroy(&ac->mu);\n gpr_free(ac->addr_str);\n grpc_channel_args_destroy(ac->channel_args);\n gpr_free(ac);\n }\n}\n\ngrpc_endpoint* grpc_tcp_client_create_from_fd(\n grpc_fd* fd, const grpc_channel_args* channel_args, const char* addr_str) {\n return grpc_tcp_create(fd, channel_args, addr_str);\n}\n\nstatic void on_writable(void* acp, grpc_error* error) {\n async_connect* ac = static_cast<async_connect*>(acp);\n int so_error = 0;\n socklen_t so_error_size;\n int err;\n int done;\n grpc_endpoint** ep = ac->ep;\n grpc_closure* closure = ac->closure;\n grpc_fd* fd;\n\n GRPC_ERROR_REF(error);\n\n if (grpc_tcp_trace.enabled()) {\n const char* str = grpc_error_string(error);\n gpr_log(GPR_INFO, \"CLIENT_CONNECT: %s: on_writable: error=%s\", ac->addr_str,\n str);\n }\n\n gpr_mu_lock(&ac->mu);\n GPR_ASSERT(ac->fd);\n fd = ac->fd;\n ac->fd = nullptr;\n gpr_mu_unlock(&ac->mu);\n\n grpc_timer_cancel(&ac->alarm);\n\n gpr_mu_lock(&ac->mu);\n if (error != GRPC_ERROR_NONE) {\n error =\n grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,\n grpc_slice_from_static_string(\"Timeout occurred\"));\n goto finish;\n }\n\n do {\n so_error_size = sizeof(so_error);\n err = getsockopt(grpc_fd_wrapped_fd(fd), SOL_SOCKET, SO_ERROR, &so_error,\n &so_error_size);\n } while (err < 0 && errno == EINTR);\n if (err < 0) {\n error = GRPC_OS_ERROR(errno, \"getsockopt\");\n goto finish;\n }\n\n switch (so_error) {\n case 0:\n grpc_pollset_set_del_fd(ac->interested_parties, fd);\n *ep = grpc_tcp_client_create_from_fd(fd, ac->channel_args, ac->addr_str);\n fd = nullptr;\n break;\n case ENOBUFS:\n \/* We will get one of these errors if we have run out of\n memory in the kernel for the data structures allocated\n when you connect a socket. If this happens it is very\n likely that if we wait a little bit then try again the\n connection will work (since other programs or this\n program will close their network connections and free up\n memory). This does _not_ indicate that there is anything\n wrong with the server we are connecting to, this is a\n local problem.\n\n If you are looking at this code, then chances are that\n your program or another program on the same computer\n opened too many network connections. The \"easy\" fix:\n don't do that! *\/\n gpr_log(GPR_ERROR, \"kernel out of buffers\");\n gpr_mu_unlock(&ac->mu);\n grpc_fd_notify_on_write(fd, &ac->write_closure);\n return;\n case ECONNREFUSED:\n \/* This error shouldn't happen for anything other than connect(). *\/\n error = GRPC_OS_ERROR(so_error, \"connect\");\n break;\n default:\n \/* We don't really know which syscall triggered the problem here,\n so punt by reporting getsockopt(). *\/\n error = GRPC_OS_ERROR(so_error, \"getsockopt(SO_ERROR)\");\n break;\n }\n\nfinish:\n if (fd != nullptr) {\n grpc_pollset_set_del_fd(ac->interested_parties, fd);\n grpc_fd_orphan(fd, nullptr, nullptr, \"tcp_client_orphan\");\n fd = nullptr;\n }\n done = (--ac->refs == 0);\n \/\/ Create a copy of the data from \"ac\" to be accessed after the unlock, as\n \/\/ \"ac\" and its contents may be deallocated by the time they are read.\n const grpc_slice addr_str_slice = grpc_slice_from_copied_string(ac->addr_str);\n gpr_mu_unlock(&ac->mu);\n if (error != GRPC_ERROR_NONE) {\n char* error_descr;\n grpc_slice str;\n bool ret = grpc_error_get_str(error, GRPC_ERROR_STR_DESCRIPTION, &str);\n GPR_ASSERT(ret);\n char* desc = grpc_slice_to_c_string(str);\n gpr_asprintf(&error_descr, \"Failed to connect to remote host: %s\", desc);\n error = grpc_error_set_str(error, GRPC_ERROR_STR_DESCRIPTION,\n grpc_slice_from_copied_string(error_descr));\n gpr_free(error_descr);\n gpr_free(desc);\n error = grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,\n addr_str_slice \/* takes ownership *\/);\n } else {\n grpc_slice_unref_internal(addr_str_slice);\n }\n if (done) {\n \/\/ This is safe even outside the lock, because \"done\", the sentinel, is\n \/\/ populated *inside* the lock.\n gpr_mu_destroy(&ac->mu);\n gpr_free(ac->addr_str);\n grpc_channel_args_destroy(ac->channel_args);\n gpr_free(ac);\n }\n GRPC_CLOSURE_SCHED(closure, error);\n}\n\ngrpc_error* grpc_tcp_client_prepare_fd(const grpc_channel_args* channel_args,\n const grpc_resolved_address* addr,\n grpc_resolved_address* mapped_addr,\n grpc_fd** fdobj) {\n grpc_dualstack_mode dsmode;\n int fd;\n grpc_error* error;\n char* name;\n char* addr_str;\n *fdobj = nullptr;\n \/* Use dualstack sockets where available. Set mapped to v6 or v4 mapped to\n v6. *\/\n if (!grpc_sockaddr_to_v4mapped(addr, mapped_addr)) {\n \/* addr is v4 mapped to v6 or v6. *\/\n memcpy(mapped_addr, addr, sizeof(*mapped_addr));\n }\n error =\n grpc_create_dualstack_socket(mapped_addr, SOCK_STREAM, 0, &dsmode, &fd);\n if (error != GRPC_ERROR_NONE) {\n return error;\n }\n if (dsmode == GRPC_DSMODE_IPV4) {\n \/* Original addr is either v4 or v4 mapped to v6. Set mapped_addr to v4. *\/\n if (!grpc_sockaddr_is_v4mapped(addr, mapped_addr)) {\n memcpy(mapped_addr, addr, sizeof(*mapped_addr));\n }\n }\n if ((error = prepare_socket(mapped_addr, fd, channel_args)) !=\n GRPC_ERROR_NONE) {\n return error;\n }\n addr_str = grpc_sockaddr_to_uri(mapped_addr);\n gpr_asprintf(&name, \"tcp-client:%s\", addr_str);\n *fdobj = grpc_fd_create(fd, name, true);\n gpr_free(name);\n gpr_free(addr_str);\n return GRPC_ERROR_NONE;\n}\n\nvoid grpc_tcp_client_create_from_prepared_fd(\n grpc_pollset_set* interested_parties, grpc_closure* closure, grpc_fd* fdobj,\n const grpc_channel_args* channel_args, const grpc_resolved_address* addr,\n grpc_millis deadline, grpc_endpoint** ep) {\n const int fd = grpc_fd_wrapped_fd(fdobj);\n int err;\n async_connect* ac;\n do {\n err = connect(fd, reinterpret_cast<const grpc_sockaddr*>(addr->addr),\n addr->len);\n } while (err < 0 && errno == EINTR);\n if (err >= 0) {\n char* addr_str = grpc_sockaddr_to_uri(addr);\n *ep = grpc_tcp_client_create_from_fd(fdobj, channel_args, addr_str);\n gpr_free(addr_str);\n GRPC_CLOSURE_SCHED(closure, GRPC_ERROR_NONE);\n return;\n }\n if (errno != EWOULDBLOCK && errno != EINPROGRESS) {\n grpc_fd_orphan(fdobj, nullptr, nullptr, \"tcp_client_connect_error\");\n GRPC_CLOSURE_SCHED(closure, GRPC_OS_ERROR(errno, \"connect\"));\n return;\n }\n\n grpc_pollset_set_add_fd(interested_parties, fdobj);\n\n ac = static_cast<async_connect*>(gpr_malloc(sizeof(async_connect)));\n ac->closure = closure;\n ac->ep = ep;\n ac->fd = fdobj;\n ac->interested_parties = interested_parties;\n ac->addr_str = grpc_sockaddr_to_uri(addr);\n gpr_mu_init(&ac->mu);\n ac->refs = 2;\n GRPC_CLOSURE_INIT(&ac->write_closure, on_writable, ac,\n grpc_schedule_on_exec_ctx);\n ac->channel_args = grpc_channel_args_copy(channel_args);\n\n if (grpc_tcp_trace.enabled()) {\n gpr_log(GPR_INFO, \"CLIENT_CONNECT: %s: asynchronously connecting fd %p\",\n ac->addr_str, fdobj);\n }\n\n gpr_mu_lock(&ac->mu);\n GRPC_CLOSURE_INIT(&ac->on_alarm, tc_on_alarm, ac, grpc_schedule_on_exec_ctx);\n grpc_timer_init(&ac->alarm, deadline, &ac->on_alarm);\n grpc_fd_notify_on_write(ac->fd, &ac->write_closure);\n gpr_mu_unlock(&ac->mu);\n}\n\nstatic void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,\n grpc_pollset_set* interested_parties,\n const grpc_channel_args* channel_args,\n const grpc_resolved_address* addr,\n grpc_millis deadline) {\n grpc_resolved_address mapped_addr;\n grpc_fd* fdobj = nullptr;\n grpc_error* error;\n *ep = nullptr;\n if ((error = grpc_tcp_client_prepare_fd(channel_args, addr, &mapped_addr,\n &fdobj)) != GRPC_ERROR_NONE) {\n GRPC_CLOSURE_SCHED(closure, error);\n return;\n }\n grpc_tcp_client_create_from_prepared_fd(interested_parties, closure, fdobj,\n channel_args, &mapped_addr, deadline,\n ep);\n}\n\ngrpc_tcp_client_vtable grpc_posix_tcp_client_vtable = {tcp_connect};\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\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: axismodel.hxx,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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef OOX_DRAWINGML_CHART_AXISMODEL_HXX\n#define OOX_DRAWINGML_CHART_AXISMODEL_HXX\n\n#include \"oox\/drawingml\/shape.hxx\"\n#include \"oox\/drawingml\/chart\/titlemodel.hxx\"\n\nnamespace oox {\nnamespace drawingml {\nnamespace chart {\n\n\/\/ ============================================================================\n\nstruct AxisDispUnitsModel\n{\n typedef ModelRef< Shape > ShapeRef;\n typedef ModelRef< TextBody > TextBodyRef;\n typedef ModelRef< LayoutModel > LayoutRef;\n typedef ModelRef< TextModel > TextRef;\n\n ShapeRef mxShapeProp; \/\/\/ Label frame formatting.\n TextBodyRef mxTextProp; \/\/\/ Label text formatting.\n LayoutRef mxLayout; \/\/\/ Layout\/position of the axis units label.\n TextRef mxText; \/\/\/ Text source of the axis units label.\n double mfCustomUnit; \/\/\/ Custom unit size on value axis.\n sal_Int32 mnBuiltInUnit; \/\/\/ Built-in unit on value axis.\n\n explicit AxisDispUnitsModel();\n ~AxisDispUnitsModel();\n};\n\n\/\/ ============================================================================\n\nstruct AxisModel\n{\n typedef ModelRef< Shape > ShapeRef;\n typedef ModelRef< TextBody > TextBodyRef;\n typedef ModelRef< TitleModel > TitleRef;\n typedef ModelRef< AxisDispUnitsModel > AxisDispUnitsRef;\n\n ShapeRef mxShapeProp; \/\/\/ Axis line formatting.\n TextBodyRef mxTextProp; \/\/\/ Axis label text formatting.\n TitleRef mxTitle; \/\/\/ Axis title.\n AxisDispUnitsRef mxDispUnits; \/\/\/ Axis units label.\n ShapeRef mxMajorGridLines; \/\/\/ Major grid lines formatting.\n ShapeRef mxMinorGridLines; \/\/\/ Minor grid lines formatting.\n ::rtl::OUString maFormatCode; \/\/\/ Number format code for tick mark labels.\n OptDouble mofCrossesAt; \/\/\/ Position on this axis where another axis crosses.\n OptDouble mofMajorUnit; \/\/\/ Unit for major tick marks on date\/value axis.\n OptDouble mofMinorUnit; \/\/\/ Unit for minor tick marks on date\/value axis.\n OptDouble mofLogBase; \/\/\/ Logarithmic base for logarithmic axes.\n OptDouble mofMax; \/\/\/ Maximum axis value.\n OptDouble mofMin; \/\/\/ Minimum axis value.\n sal_Int32 mnAxisId; \/\/\/ Unique axis identifier.\n sal_Int32 mnAxisPos; \/\/\/ Position of the axis (top\/bottom\/left\/right).\n sal_Int32 mnBaseTimeUnit; \/\/\/ Base time unit shown on a date axis.\n sal_Int32 mnCrossAxisId; \/\/\/ Identifier of a crossing axis.\n sal_Int32 mnCrossBetween; \/\/\/ This value axis crosses between or inside category.\n sal_Int32 mnCrossMode; \/\/\/ Mode this axis crosses another axis (min, max, auto).\n sal_Int32 mnLabelAlign; \/\/\/ Tick mark label alignment.\n sal_Int32 mnLabelOffset; \/\/\/ Tick mark label distance from axis.\n sal_Int32 mnMajorTickMark; \/\/\/ Major tick mark style.\n sal_Int32 mnMajorTimeUnit; \/\/\/ Time unit for major tick marks on date axis.\n sal_Int32 mnMinorTickMark; \/\/\/ Mainor tick mark style.\n sal_Int32 mnMinorTimeUnit; \/\/\/ Time unit for minor tick marks on date axis.\n sal_Int32 mnOrientation; \/\/\/ Axis orientation (value order min to max, or max to min).\n sal_Int32 mnTickLabelPos; \/\/\/ Position of tick mark labels relative to the axis.\n sal_Int32 mnTickLabelSkip; \/\/\/ Number of tick mark labels to skip.\n sal_Int32 mnTickMarkSkip; \/\/\/ Number of tick marks to skip.\n sal_Int32 mnTypeId; \/\/\/ Type identifier of this axis.\n bool mbAuto; \/\/\/ True = automatic axis settings.\n bool mbDeleted; \/\/\/ True = axis has been deleted manually.\n bool mbNoMultiLevel; \/\/\/ True = no multi-level categories supported.\n bool mbSourceLinked; \/\/\/ True = number format linked to source data.\n\n explicit AxisModel( sal_Int32 nTypeId );\n ~AxisModel();\n};\n\n\/\/ ============================================================================\n\n} \/\/ namespace chart\n} \/\/ namespace drawingml\n} \/\/ namespace oox\n\n#endif\n\n<commit_msg>INTEGRATION: CWS xmlfilter05 (1.2.4); FILE MERGED 2008\/05\/21 10:26:54 dr 1.2.4.4: #i10000# new header 2008\/04\/16 13:10:07 dr 1.2.4.3: new optional token handling, fix default rotation in 3d charts 2008\/04\/02 12:41:47 hbrinkm 1.2.4.2: merged changes from xmlfilter04 to xmlfilter05 2008\/04\/01 15:37:18 hbrinkm 1.2.4.1: 'Merged xmlfilter04'<commit_after>\/*************************************************************************\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: axismodel.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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef OOX_DRAWINGML_CHART_AXISMODEL_HXX\n#define OOX_DRAWINGML_CHART_AXISMODEL_HXX\n\n#include \"oox\/drawingml\/shape.hxx\"\n#include \"oox\/drawingml\/chart\/titlemodel.hxx\"\n\nnamespace oox {\nnamespace drawingml {\nnamespace chart {\n\n\/\/ ============================================================================\n\nstruct AxisDispUnitsModel\n{\n typedef ModelRef< Shape > ShapeRef;\n typedef ModelRef< TextBody > TextBodyRef;\n typedef ModelRef< LayoutModel > LayoutRef;\n typedef ModelRef< TextModel > TextRef;\n\n ShapeRef mxShapeProp; \/\/\/ Label frame formatting.\n TextBodyRef mxTextProp; \/\/\/ Label text formatting.\n LayoutRef mxLayout; \/\/\/ Layout\/position of the axis units label.\n TextRef mxText; \/\/\/ Text source of the axis units label.\n double mfCustomUnit; \/\/\/ Custom unit size on value axis.\n sal_Int32 mnBuiltInUnit; \/\/\/ Built-in unit on value axis.\n\n explicit AxisDispUnitsModel();\n ~AxisDispUnitsModel();\n};\n\n\/\/ ============================================================================\n\nstruct AxisModel\n{\n typedef ModelRef< Shape > ShapeRef;\n typedef ModelRef< TextBody > TextBodyRef;\n typedef ModelRef< TitleModel > TitleRef;\n typedef ModelRef< AxisDispUnitsModel > AxisDispUnitsRef;\n\n ShapeRef mxShapeProp; \/\/\/ Axis line formatting.\n TextBodyRef mxTextProp; \/\/\/ Axis label text formatting.\n TitleRef mxTitle; \/\/\/ Axis title.\n AxisDispUnitsRef mxDispUnits; \/\/\/ Axis units label.\n ShapeRef mxMajorGridLines; \/\/\/ Major grid lines formatting.\n ShapeRef mxMinorGridLines; \/\/\/ Minor grid lines formatting.\n ::rtl::OUString maFormatCode; \/\/\/ Number format code for tick mark labels.\n OptValue< double > mofCrossesAt; \/\/\/ Position on this axis where another axis crosses.\n OptValue< double > mofMajorUnit; \/\/\/ Unit for major tick marks on date\/value axis.\n OptValue< double > mofMinorUnit; \/\/\/ Unit for minor tick marks on date\/value axis.\n OptValue< double > mofLogBase; \/\/\/ Logarithmic base for logarithmic axes.\n OptValue< double > mofMax; \/\/\/ Maximum axis value.\n OptValue< double > mofMin; \/\/\/ Minimum axis value.\n sal_Int32 mnAxisId; \/\/\/ Unique axis identifier.\n sal_Int32 mnAxisPos; \/\/\/ Position of the axis (top\/bottom\/left\/right).\n sal_Int32 mnBaseTimeUnit; \/\/\/ Base time unit shown on a date axis.\n sal_Int32 mnCrossAxisId; \/\/\/ Identifier of a crossing axis.\n sal_Int32 mnCrossBetween; \/\/\/ This value axis crosses between or inside category.\n sal_Int32 mnCrossMode; \/\/\/ Mode this axis crosses another axis (min, max, auto).\n sal_Int32 mnLabelAlign; \/\/\/ Tick mark label alignment.\n sal_Int32 mnLabelOffset; \/\/\/ Tick mark label distance from axis.\n sal_Int32 mnMajorTickMark; \/\/\/ Major tick mark style.\n sal_Int32 mnMajorTimeUnit; \/\/\/ Time unit for major tick marks on date axis.\n sal_Int32 mnMinorTickMark; \/\/\/ Mainor tick mark style.\n sal_Int32 mnMinorTimeUnit; \/\/\/ Time unit for minor tick marks on date axis.\n sal_Int32 mnOrientation; \/\/\/ Axis orientation (value order min to max, or max to min).\n sal_Int32 mnTickLabelPos; \/\/\/ Position of tick mark labels relative to the axis.\n sal_Int32 mnTickLabelSkip; \/\/\/ Number of tick mark labels to skip.\n sal_Int32 mnTickMarkSkip; \/\/\/ Number of tick marks to skip.\n sal_Int32 mnTypeId; \/\/\/ Type identifier of this axis.\n bool mbAuto; \/\/\/ True = automatic axis settings.\n bool mbDeleted; \/\/\/ True = axis has been deleted manually.\n bool mbNoMultiLevel; \/\/\/ True = no multi-level categories supported.\n bool mbSourceLinked; \/\/\/ True = number format linked to source data.\n\n explicit AxisModel( sal_Int32 nTypeId );\n ~AxisModel();\n};\n\n\/\/ ============================================================================\n\n} \/\/ namespace chart\n} \/\/ namespace drawingml\n} \/\/ namespace oox\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"third_party\/skia\/include\/core\/SkXfermode.h\"\n#include \"ui\/aura\/client\/default_capture_client.h\"\n#include \"ui\/aura\/client\/window_tree_client.h\"\n#include \"ui\/aura\/env.h\"\n#include \"ui\/aura\/test\/test_focus_client.h\"\n#include \"ui\/aura\/test\/test_screen.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/aura\/window_delegate.h\"\n#include \"ui\/aura\/window_tree_host.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/compositor\/test\/in_process_context_factory.h\"\n#include \"ui\/events\/event.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gl\/gl_surface.h\"\n\n#if defined(USE_X11)\n#include \"ui\/gfx\/x\/x11_connection.h\"\n#endif\n\nnamespace {\n\n\/\/ Trivial WindowDelegate implementation that draws a colored background.\nclass DemoWindowDelegate : public aura::WindowDelegate {\n public:\n explicit DemoWindowDelegate(SkColor color) : color_(color) {}\n\n \/\/ Overridden from WindowDelegate:\n virtual gfx::Size GetMinimumSize() const OVERRIDE {\n return gfx::Size();\n }\n\n virtual gfx::Size GetMaximumSize() const OVERRIDE {\n return gfx::Size();\n }\n\n virtual void OnBoundsChanged(const gfx::Rect& old_bounds,\n const gfx::Rect& new_bounds) OVERRIDE {}\n virtual gfx::NativeCursor GetCursor(const gfx::Point& point) OVERRIDE {\n return gfx::kNullCursor;\n }\n virtual int GetNonClientComponent(const gfx::Point& point) const OVERRIDE {\n return HTCAPTION;\n }\n virtual bool ShouldDescendIntoChildForEventHandling(\n aura::Window* child,\n const gfx::Point& location) OVERRIDE {\n return true;\n }\n virtual bool CanFocus() OVERRIDE { return true; }\n virtual void OnCaptureLost() OVERRIDE {}\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {\n canvas->DrawColor(color_, SkXfermode::kSrc_Mode);\n }\n virtual void OnDeviceScaleFactorChanged(float device_scale_factor) OVERRIDE {}\n virtual void OnWindowDestroying(aura::Window* window) OVERRIDE {}\n virtual void OnWindowDestroyed(aura::Window* window) OVERRIDE {}\n virtual void OnWindowTargetVisibilityChanged(bool visible) OVERRIDE {}\n virtual bool HasHitTestMask() const OVERRIDE { return false; }\n virtual void GetHitTestMask(gfx::Path* mask) const OVERRIDE {}\n\n private:\n SkColor color_;\n\n DISALLOW_COPY_AND_ASSIGN(DemoWindowDelegate);\n};\n\nclass DemoWindowTreeClient : public aura::client::WindowTreeClient {\n public:\n explicit DemoWindowTreeClient(aura::Window* window) : window_(window) {\n aura::client::SetWindowTreeClient(window_, this);\n }\n\n virtual ~DemoWindowTreeClient() {\n aura::client::SetWindowTreeClient(window_, NULL);\n }\n\n \/\/ Overridden from aura::client::WindowTreeClient:\n virtual aura::Window* GetDefaultParent(aura::Window* context,\n aura::Window* window,\n const gfx::Rect& bounds) OVERRIDE {\n if (!capture_client_) {\n capture_client_.reset(\n new aura::client::DefaultCaptureClient(window_->GetRootWindow()));\n }\n return window_;\n }\n\n private:\n aura::Window* window_;\n\n scoped_ptr<aura::client::DefaultCaptureClient> capture_client_;\n\n DISALLOW_COPY_AND_ASSIGN(DemoWindowTreeClient);\n};\n\nint DemoMain() {\n#if defined(USE_X11)\n \/\/ This demo uses InProcessContextFactory which uses X on a separate Gpu\n \/\/ thread.\n gfx::InitializeThreadedX11();\n#endif\n\n gfx::GLSurface::InitializeOneOff();\n\n \/\/ The ContextFactory must exist before any Compositors are created.\n scoped_ptr<ui::InProcessContextFactory> context_factory(\n new ui::InProcessContextFactory());\n ui::ContextFactory::SetInstance(context_factory.get());\n\n \/\/ Create the message-loop here before creating the root window.\n base::MessageLoopForUI message_loop;\n\n aura::Env::CreateInstance();\n scoped_ptr<aura::TestScreen> test_screen(aura::TestScreen::Create());\n gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, test_screen.get());\n scoped_ptr<aura::WindowTreeHost> host(\n test_screen->CreateHostForPrimaryDisplay());\n scoped_ptr<DemoWindowTreeClient> window_tree_client(\n new DemoWindowTreeClient(host->window()));\n aura::test::TestFocusClient focus_client;\n aura::client::SetFocusClient(host->window(), &focus_client);\n\n \/\/ Create a hierarchy of test windows.\n DemoWindowDelegate window_delegate1(SK_ColorBLUE);\n aura::Window window1(&window_delegate1);\n window1.set_id(1);\n window1.Init(aura::WINDOW_LAYER_TEXTURED);\n window1.SetBounds(gfx::Rect(100, 100, 400, 400));\n window1.Show();\n aura::client::ParentWindowWithContext(&window1, host->window(), gfx::Rect());\n\n DemoWindowDelegate window_delegate2(SK_ColorRED);\n aura::Window window2(&window_delegate2);\n window2.set_id(2);\n window2.Init(aura::WINDOW_LAYER_TEXTURED);\n window2.SetBounds(gfx::Rect(200, 200, 350, 350));\n window2.Show();\n aura::client::ParentWindowWithContext(&window2, host->window(), gfx::Rect());\n\n DemoWindowDelegate window_delegate3(SK_ColorGREEN);\n aura::Window window3(&window_delegate3);\n window3.set_id(3);\n window3.Init(aura::WINDOW_LAYER_TEXTURED);\n window3.SetBounds(gfx::Rect(10, 10, 50, 50));\n window3.Show();\n window2.AddChild(&window3);\n\n host->Show();\n base::MessageLoopForUI::current()->Run();\n\n return 0;\n}\n\n} \/\/ namespace\n\nint main(int argc, char** argv) {\n CommandLine::Init(argc, argv);\n\n \/\/ The exit manager is in charge of calling the dtors of singleton objects.\n base::AtExitManager exit_manager;\n\n base::i18n::InitializeICU();\n\n return DemoMain();\n}\n<commit_msg>Aura demo: Initialize device scale factor<commit_after>\/\/ 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 \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"third_party\/skia\/include\/core\/SkXfermode.h\"\n#include \"ui\/aura\/client\/default_capture_client.h\"\n#include \"ui\/aura\/client\/window_tree_client.h\"\n#include \"ui\/aura\/env.h\"\n#include \"ui\/aura\/test\/test_focus_client.h\"\n#include \"ui\/aura\/test\/test_screen.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/aura\/window_delegate.h\"\n#include \"ui\/aura\/window_tree_host.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/compositor\/test\/in_process_context_factory.h\"\n#include \"ui\/events\/event.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gl\/gl_surface.h\"\n\n#if defined(USE_X11)\n#include \"ui\/gfx\/x\/x11_connection.h\"\n#endif\n\n#if defined(OS_WIN)\n#include \"ui\/gfx\/win\/dpi.h\"\n#endif\n\nnamespace {\n\n\/\/ Trivial WindowDelegate implementation that draws a colored background.\nclass DemoWindowDelegate : public aura::WindowDelegate {\n public:\n explicit DemoWindowDelegate(SkColor color) : color_(color) {}\n\n \/\/ Overridden from WindowDelegate:\n virtual gfx::Size GetMinimumSize() const OVERRIDE {\n return gfx::Size();\n }\n\n virtual gfx::Size GetMaximumSize() const OVERRIDE {\n return gfx::Size();\n }\n\n virtual void OnBoundsChanged(const gfx::Rect& old_bounds,\n const gfx::Rect& new_bounds) OVERRIDE {}\n virtual gfx::NativeCursor GetCursor(const gfx::Point& point) OVERRIDE {\n return gfx::kNullCursor;\n }\n virtual int GetNonClientComponent(const gfx::Point& point) const OVERRIDE {\n return HTCAPTION;\n }\n virtual bool ShouldDescendIntoChildForEventHandling(\n aura::Window* child,\n const gfx::Point& location) OVERRIDE {\n return true;\n }\n virtual bool CanFocus() OVERRIDE { return true; }\n virtual void OnCaptureLost() OVERRIDE {}\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {\n canvas->DrawColor(color_, SkXfermode::kSrc_Mode);\n }\n virtual void OnDeviceScaleFactorChanged(float device_scale_factor) OVERRIDE {}\n virtual void OnWindowDestroying(aura::Window* window) OVERRIDE {}\n virtual void OnWindowDestroyed(aura::Window* window) OVERRIDE {}\n virtual void OnWindowTargetVisibilityChanged(bool visible) OVERRIDE {}\n virtual bool HasHitTestMask() const OVERRIDE { return false; }\n virtual void GetHitTestMask(gfx::Path* mask) const OVERRIDE {}\n\n private:\n SkColor color_;\n\n DISALLOW_COPY_AND_ASSIGN(DemoWindowDelegate);\n};\n\nclass DemoWindowTreeClient : public aura::client::WindowTreeClient {\n public:\n explicit DemoWindowTreeClient(aura::Window* window) : window_(window) {\n aura::client::SetWindowTreeClient(window_, this);\n }\n\n virtual ~DemoWindowTreeClient() {\n aura::client::SetWindowTreeClient(window_, NULL);\n }\n\n \/\/ Overridden from aura::client::WindowTreeClient:\n virtual aura::Window* GetDefaultParent(aura::Window* context,\n aura::Window* window,\n const gfx::Rect& bounds) OVERRIDE {\n if (!capture_client_) {\n capture_client_.reset(\n new aura::client::DefaultCaptureClient(window_->GetRootWindow()));\n }\n return window_;\n }\n\n private:\n aura::Window* window_;\n\n scoped_ptr<aura::client::DefaultCaptureClient> capture_client_;\n\n DISALLOW_COPY_AND_ASSIGN(DemoWindowTreeClient);\n};\n\nint DemoMain() {\n#if defined(USE_X11)\n \/\/ This demo uses InProcessContextFactory which uses X on a separate Gpu\n \/\/ thread.\n gfx::InitializeThreadedX11();\n#endif\n\n gfx::GLSurface::InitializeOneOff();\n\n#if defined(OS_WIN)\n gfx::InitDeviceScaleFactor(1.0f);\n#endif\n\n \/\/ The ContextFactory must exist before any Compositors are created.\n scoped_ptr<ui::InProcessContextFactory> context_factory(\n new ui::InProcessContextFactory());\n ui::ContextFactory::SetInstance(context_factory.get());\n\n \/\/ Create the message-loop here before creating the root window.\n base::MessageLoopForUI message_loop;\n\n aura::Env::CreateInstance();\n scoped_ptr<aura::TestScreen> test_screen(aura::TestScreen::Create());\n gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, test_screen.get());\n scoped_ptr<aura::WindowTreeHost> host(\n test_screen->CreateHostForPrimaryDisplay());\n scoped_ptr<DemoWindowTreeClient> window_tree_client(\n new DemoWindowTreeClient(host->window()));\n aura::test::TestFocusClient focus_client;\n aura::client::SetFocusClient(host->window(), &focus_client);\n\n \/\/ Create a hierarchy of test windows.\n DemoWindowDelegate window_delegate1(SK_ColorBLUE);\n aura::Window window1(&window_delegate1);\n window1.set_id(1);\n window1.Init(aura::WINDOW_LAYER_TEXTURED);\n window1.SetBounds(gfx::Rect(100, 100, 400, 400));\n window1.Show();\n aura::client::ParentWindowWithContext(&window1, host->window(), gfx::Rect());\n\n DemoWindowDelegate window_delegate2(SK_ColorRED);\n aura::Window window2(&window_delegate2);\n window2.set_id(2);\n window2.Init(aura::WINDOW_LAYER_TEXTURED);\n window2.SetBounds(gfx::Rect(200, 200, 350, 350));\n window2.Show();\n aura::client::ParentWindowWithContext(&window2, host->window(), gfx::Rect());\n\n DemoWindowDelegate window_delegate3(SK_ColorGREEN);\n aura::Window window3(&window_delegate3);\n window3.set_id(3);\n window3.Init(aura::WINDOW_LAYER_TEXTURED);\n window3.SetBounds(gfx::Rect(10, 10, 50, 50));\n window3.Show();\n window2.AddChild(&window3);\n\n host->Show();\n base::MessageLoopForUI::current()->Run();\n\n return 0;\n}\n\n} \/\/ namespace\n\nint main(int argc, char** argv) {\n CommandLine::Init(argc, argv);\n\n \/\/ The exit manager is in charge of calling the dtors of singleton objects.\n base::AtExitManager exit_manager;\n\n base::i18n::InitializeICU();\n\n return DemoMain();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n\n#include \"ee\/ads\/NullInterstitialAd.hpp\"\n#include \"ee\/ads\/NullRewardedVideo.hpp\"\n#include \"ee\/ads\/internal\/MediationManager.hpp\"\n#include \"ee\/core\/Logger.hpp\"\n#include \"ee\/core\/MessageBridge.hpp\"\n#include \"ee\/core\/Utils.hpp\"\n#include \"ee\/ironsource\/IronSourceBridge.hpp\"\n#include \"ee\/ironsource\/internal\/IronSourceInterstitialAd.hpp\"\n#include \"ee\/ironsource\/internal\/IronSourceRewardedVideo.hpp\"\n\n#include <ee\/nlohmann\/json.hpp>\n\nnamespace ee {\nnamespace ironsource {\nusing Self = IronSource;\n\nnamespace {\n\/\/ clang-format off\nconstexpr auto k__initialize = \"IronSource_initialize\";\nconstexpr auto k__hasRewardedVideo = \"IronSource_hasRewardedVideo\";\nconstexpr auto k__showRewardedVideo = \"IronSource_showRewardedVideo\";\n \nconstexpr auto k__loadInterstitial = \"IronSource_loadInterstitial\";\nconstexpr auto k__hasInterstitial = \"IronSource_hasInterstitial\";\nconstexpr auto k__showInterstitial = \"IronSource_showInterstitial\";\nconstexpr auto k__onRewarded = \"IronSource_onRewarded\";\nconstexpr auto k__onFailed = \"IronSource_onFailed\";\nconstexpr auto k__onOpened = \"IronSource_onOpened\";\nconstexpr auto k__onClosed = \"IronSource_onClosed\";\n \nconstexpr auto k__onInterstitialFailed = \"IronSource_onInterstitialFailed\";\nconstexpr auto k__onInterstitialOpened = \"IronSource_onInterstitialOpened\";\nconstexpr auto k__onInterstitialClosed = \"IronSource_onInterstitialClosed\";\n\/\/ clang-format on\n} \/\/ namespace\n\nSelf::IronSource()\n : Self(Logger::getSystemLogger()) {}\n\nSelf::IronSource(const Logger& logger)\n : bridge_(MessageBridge::getInstance())\n , _closeTimeout(0.0f)\n , logger_(logger) {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n rewarded_ = false;\n\n bridge_.registerHandler(\n [this](const std::string& message) {\n onRewarded(message);\n return \"\";\n },\n k__onRewarded);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onFailed();\n return \"\";\n },\n k__onFailed);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onOpened();\n return \"\";\n },\n k__onOpened);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onClosed();\n return \"\";\n },\n k__onClosed);\n\n bridge_.registerHandler(\n [this](const std::string& message) {\n onInterstitialOpened();\n return \"\";\n },\n k__onInterstitialOpened);\n\n bridge_.registerHandler(\n [this](const std::string& message) {\n onInterstitialFailed();\n return \"\";\n },\n k__onInterstitialFailed);\n\n bridge_.registerHandler(\n [this](const std::string& message) {\n onInterstitialClosed();\n return \"\";\n },\n k__onInterstitialClosed);\n\n handlerLock_ = std::make_unique<core::SpinLock>();\n}\n\nSelf::~IronSource() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n bridge_.deregisterHandler(k__onRewarded);\n bridge_.deregisterHandler(k__onFailed);\n bridge_.deregisterHandler(k__onOpened);\n bridge_.deregisterHandler(k__onClosed);\n\n bridge_.deregisterHandler(k__onInterstitialOpened);\n bridge_.deregisterHandler(k__onInterstitialFailed);\n bridge_.deregisterHandler(k__onInterstitialClosed);\n}\n\nvoid Self::initialize(const std::string& gameId) {\n logger_.debug(\"%s: gameId = %s\", __PRETTY_FUNCTION__, gameId.c_str());\n bridge_.call(k__initialize, gameId);\n}\n\nstd::shared_ptr<IRewardedVideo>\nSelf::createRewardedVideo(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n if (rewardedVideos_.count(placementId) != 0) {\n return std::make_shared<NullRewardedVideo>(logger_);\n }\n auto result = new RewardedVideo(logger_, this, placementId);\n rewardedVideos_[placementId] = result;\n return std::shared_ptr<IRewardedVideo>(result);\n}\n\nbool Self::destroyRewardedVideo(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n if (rewardedVideos_.count(placementId) == 0) {\n return false;\n }\n rewardedVideos_.erase(placementId);\n return true;\n}\n\nstd::shared_ptr<IInterstitialAd>\nSelf::createInterstitialAd(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n if (interstitialAds_.count(placementId) != 0) {\n return std::make_shared<NullInterstitialAd>();\n }\n auto result = new InterstitialAd(logger_, this, placementId);\n interstitialAds_[placementId] = result;\n return std::shared_ptr<IInterstitialAd>(result);\n}\n\nbool Self::destroyInterstitialAd(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n if (interstitialAds_.count(placementId) == 0) {\n return false;\n }\n interstitialAds_.erase(placementId);\n return true;\n}\n\nvoid Self::loadInterstitial() {\n bridge_.call(k__loadInterstitial);\n}\n\nbool Self::hasInterstitial() const {\n auto response = bridge_.call(k__hasInterstitial);\n return core::toBool(response);\n}\n\nbool Self::showInterstitial(const std::string& placementId) {\n if (not hasInterstitial()) {\n return false;\n }\n\n bridge_.call(k__showInterstitial, placementId);\n return true;\n}\n\nbool Self::hasRewardedVideo() const {\n auto response = bridge_.call(k__hasRewardedVideo);\n return core::toBool(response);\n}\n\nbool Self::showRewardedVideo(const std::string& placementId) {\n if (not hasRewardedVideo()) {\n return false;\n }\n rewarded_ = false;\n _shouldDoRewardInGame = false;\n bridge_.call(k__showRewardedVideo, placementId);\n return true;\n}\n\nvoid Self::onRewarded(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n rewarded_ = true;\n if (_shouldDoRewardInGame) {\n doRewardInGame();\n }\n _shouldDoRewardInGame = true;\n}\n\nvoid Self::onFailed() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n\n _shouldDoRewardInGame = true;\n onClosed();\n}\n\nvoid Self::onOpened() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n rewarded_ = false;\n _didRewardFlag = false;\n}\n\nvoid Self::onClosed() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n\n if (_shouldDoRewardInGame) {\n doRewardInGame();\n } else {\n \/\/ wait for reward\n \/\/ if out of time just callback failed\n ee::core::runFunctionDelay(\n [this] {\n std::lock_guard<core::SpinLock> guard(*handlerLock_);\n rewarded_ = false;\n doRewardInGame();\n },\n _closeTimeout);\n }\n _shouldDoRewardInGame = true;\n}\n\nvoid Self::doRewardInGame() {\n if (_didRewardFlag) {\n return;\n }\n\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n auto&& mediation = ads::MediationManager::getInstance();\n\n \/\/ Other mediation network.\n auto wasInterstitialAd = mediation.setInterstitialAdDone();\n auto wasRewardedVideo = mediation.finishRewardedVideo(rewarded_);\n\n _didRewardFlag = true;\n assert(wasInterstitialAd || wasRewardedVideo);\n}\n\n#pragma mark - For Interstitial\n\nvoid Self::onInterstitialOpened() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n}\n\nvoid Self::onInterstitialFailed() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n onInterstitialClosed();\n}\n\nvoid Self::onInterstitialClosed() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n \/\/ auto&& mediation = ads::MediationManager::getInstance();\n \/\/\n \/\/ auto successful = mediation.finishInterstitialAd();\n \/\/ assert(successful);\n _shouldDoRewardInGame = true;\n onClosed();\n}\n\n#pragma mark - Config\n\nvoid Self::setCloseTimeout(float timeout) {\n _closeTimeout = timeout;\n}\n} \/\/ namespace ironsource\n} \/\/ namespace ee\n<commit_msg>- fix build ios<commit_after>#include <cassert>\n\n#include \"ee\/ads\/NullInterstitialAd.hpp\"\n#include \"ee\/ads\/NullRewardedVideo.hpp\"\n#include \"ee\/ads\/internal\/MediationManager.hpp\"\n#include \"ee\/core\/Logger.hpp\"\n#include \"ee\/core\/MessageBridge.hpp\"\n#include \"ee\/core\/Utils.hpp\"\n#include \"ee\/core\/internal\/SpinLock.hpp\"\n#include \"ee\/ironsource\/IronSourceBridge.hpp\"\n#include \"ee\/ironsource\/internal\/IronSourceInterstitialAd.hpp\"\n#include \"ee\/ironsource\/internal\/IronSourceRewardedVideo.hpp\"\n\n#include <ee\/nlohmann\/json.hpp>\n\nnamespace ee {\nnamespace ironsource {\nusing Self = IronSource;\n\nnamespace {\n\/\/ clang-format off\nconstexpr auto k__initialize = \"IronSource_initialize\";\nconstexpr auto k__hasRewardedVideo = \"IronSource_hasRewardedVideo\";\nconstexpr auto k__showRewardedVideo = \"IronSource_showRewardedVideo\";\n \nconstexpr auto k__loadInterstitial = \"IronSource_loadInterstitial\";\nconstexpr auto k__hasInterstitial = \"IronSource_hasInterstitial\";\nconstexpr auto k__showInterstitial = \"IronSource_showInterstitial\";\nconstexpr auto k__onRewarded = \"IronSource_onRewarded\";\nconstexpr auto k__onFailed = \"IronSource_onFailed\";\nconstexpr auto k__onOpened = \"IronSource_onOpened\";\nconstexpr auto k__onClosed = \"IronSource_onClosed\";\n \nconstexpr auto k__onInterstitialFailed = \"IronSource_onInterstitialFailed\";\nconstexpr auto k__onInterstitialOpened = \"IronSource_onInterstitialOpened\";\nconstexpr auto k__onInterstitialClosed = \"IronSource_onInterstitialClosed\";\n\/\/ clang-format on\n} \/\/ namespace\n\nSelf::IronSource()\n : Self(Logger::getSystemLogger()) {}\n\nSelf::IronSource(const Logger& logger)\n : bridge_(MessageBridge::getInstance())\n , _closeTimeout(0.0f)\n , logger_(logger) {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n rewarded_ = false;\n\n bridge_.registerHandler(\n [this](const std::string& message) {\n onRewarded(message);\n return \"\";\n },\n k__onRewarded);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onFailed();\n return \"\";\n },\n k__onFailed);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onOpened();\n return \"\";\n },\n k__onOpened);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onClosed();\n return \"\";\n },\n k__onClosed);\n\n bridge_.registerHandler(\n [this](const std::string& message) {\n onInterstitialOpened();\n return \"\";\n },\n k__onInterstitialOpened);\n\n bridge_.registerHandler(\n [this](const std::string& message) {\n onInterstitialFailed();\n return \"\";\n },\n k__onInterstitialFailed);\n\n bridge_.registerHandler(\n [this](const std::string& message) {\n onInterstitialClosed();\n return \"\";\n },\n k__onInterstitialClosed);\n\n handlerLock_ = std::make_unique<core::SpinLock>();\n}\n\nSelf::~IronSource() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n bridge_.deregisterHandler(k__onRewarded);\n bridge_.deregisterHandler(k__onFailed);\n bridge_.deregisterHandler(k__onOpened);\n bridge_.deregisterHandler(k__onClosed);\n\n bridge_.deregisterHandler(k__onInterstitialOpened);\n bridge_.deregisterHandler(k__onInterstitialFailed);\n bridge_.deregisterHandler(k__onInterstitialClosed);\n}\n\nvoid Self::initialize(const std::string& gameId) {\n logger_.debug(\"%s: gameId = %s\", __PRETTY_FUNCTION__, gameId.c_str());\n bridge_.call(k__initialize, gameId);\n}\n\nstd::shared_ptr<IRewardedVideo>\nSelf::createRewardedVideo(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n if (rewardedVideos_.count(placementId) != 0) {\n return std::make_shared<NullRewardedVideo>(logger_);\n }\n auto result = new RewardedVideo(logger_, this, placementId);\n rewardedVideos_[placementId] = result;\n return std::shared_ptr<IRewardedVideo>(result);\n}\n\nbool Self::destroyRewardedVideo(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n if (rewardedVideos_.count(placementId) == 0) {\n return false;\n }\n rewardedVideos_.erase(placementId);\n return true;\n}\n\nstd::shared_ptr<IInterstitialAd>\nSelf::createInterstitialAd(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n if (interstitialAds_.count(placementId) != 0) {\n return std::make_shared<NullInterstitialAd>();\n }\n auto result = new InterstitialAd(logger_, this, placementId);\n interstitialAds_[placementId] = result;\n return std::shared_ptr<IInterstitialAd>(result);\n}\n\nbool Self::destroyInterstitialAd(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n if (interstitialAds_.count(placementId) == 0) {\n return false;\n }\n interstitialAds_.erase(placementId);\n return true;\n}\n\nvoid Self::loadInterstitial() {\n bridge_.call(k__loadInterstitial);\n}\n\nbool Self::hasInterstitial() const {\n auto response = bridge_.call(k__hasInterstitial);\n return core::toBool(response);\n}\n\nbool Self::showInterstitial(const std::string& placementId) {\n if (not hasInterstitial()) {\n return false;\n }\n\n bridge_.call(k__showInterstitial, placementId);\n return true;\n}\n\nbool Self::hasRewardedVideo() const {\n auto response = bridge_.call(k__hasRewardedVideo);\n return core::toBool(response);\n}\n\nbool Self::showRewardedVideo(const std::string& placementId) {\n if (not hasRewardedVideo()) {\n return false;\n }\n rewarded_ = false;\n _shouldDoRewardInGame = false;\n bridge_.call(k__showRewardedVideo, placementId);\n return true;\n}\n\nvoid Self::onRewarded(const std::string& placementId) {\n logger_.debug(\"%s: placementId = %s\", __PRETTY_FUNCTION__,\n placementId.c_str());\n rewarded_ = true;\n if (_shouldDoRewardInGame) {\n doRewardInGame();\n }\n _shouldDoRewardInGame = true;\n}\n\nvoid Self::onFailed() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n\n _shouldDoRewardInGame = true;\n onClosed();\n}\n\nvoid Self::onOpened() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n rewarded_ = false;\n _didRewardFlag = false;\n}\n\nvoid Self::onClosed() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n\n if (_shouldDoRewardInGame) {\n doRewardInGame();\n } else {\n \/\/ wait for reward\n \/\/ if out of time just callback failed\n ee::core::runFunctionDelay(\n [this] {\n std::lock_guard<core::SpinLock> guard(*handlerLock_);\n rewarded_ = false;\n doRewardInGame();\n },\n _closeTimeout);\n }\n _shouldDoRewardInGame = true;\n}\n\nvoid Self::doRewardInGame() {\n if (_didRewardFlag) {\n return;\n }\n\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n auto&& mediation = ads::MediationManager::getInstance();\n\n \/\/ Other mediation network.\n auto wasInterstitialAd = mediation.setInterstitialAdDone();\n auto wasRewardedVideo = mediation.finishRewardedVideo(rewarded_);\n\n _didRewardFlag = true;\n assert(wasInterstitialAd || wasRewardedVideo);\n}\n\n#pragma mark - For Interstitial\n\nvoid Self::onInterstitialOpened() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n}\n\nvoid Self::onInterstitialFailed() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n onInterstitialClosed();\n}\n\nvoid Self::onInterstitialClosed() {\n logger_.debug(\"%s\", __PRETTY_FUNCTION__);\n \/\/ auto&& mediation = ads::MediationManager::getInstance();\n \/\/\n \/\/ auto successful = mediation.finishInterstitialAd();\n \/\/ assert(successful);\n _shouldDoRewardInGame = true;\n onClosed();\n}\n\n#pragma mark - Config\n\nvoid Self::setCloseTimeout(float timeout) {\n _closeTimeout = timeout;\n}\n} \/\/ namespace ironsource\n} \/\/ namespace ee\n<|endoftext|>"} {"text":"<commit_before>#include <test\/unit\/math\/test_ad.hpp>\n#include <limits>\n#include <vector>\n\nTEST(mathMixCore, atan2) {\n auto f = [](const auto& x1, const auto& x2) {\n using stan::math::atan2;\n return atan2(x1, x2);\n };\n double nan = std::numeric_limits<double>::quiet_NaN();\n stan::test::expect_ad(f, nan, 1.0);\n stan::test::expect_ad(f, 1.0, nan);\n stan::test::expect_ad(f, nan, nan);\n stan::test::expect_ad(f, 1.0, 1.0);\n stan::test::expect_ad(f, 1.5, 1.5);\n stan::test::expect_ad(f, 1.2, 3.9);\n stan::test::expect_ad(f, 0.5, 2.3);\n}\n\nTEST(mathMixScalFun, atan2) {\n auto f = [](const auto& x1, const auto& x2) {\n using stan::math::atan2;\n return atan2(x1, x2);\n };\n\n stan::test::expect_common_nonzero_binary(f);\n\n stan::test::expect_ad(f, 1.0, 1.0);\n stan::test::expect_ad(f, 1.0, 0.5);\n stan::test::expect_ad(f, 1.2, 3.9);\n stan::test::expect_ad(f, 7.5, 1.8);\n\n Eigen::VectorXd in1(3);\n in1 << 1.0, 1.0, 1.2;\n Eigen::VectorXd in2(3);\n in2 << 1.0, 0.5, 3.9;\n stan::test::expect_ad_vectorized_binary(f, in1, in2);\n}\n\nTEST(mathMixScalFun, atan2_varmat) {\n auto f = [](const auto& x1, const auto& x2) {\n using stan::math::atan2;\n return atan2(x1, x2);\n };\n\n Eigen::VectorXd in1(3);\n in1 << 0.5, 3.4, 5.2;\n Eigen::VectorXd in2(3);\n in2 << 3.3, 0.9, 6.7;\n stan::test::expect_ad_matvar(f, in1, in2);\n stan::test::expect_ad_matvar(f, in1(0), in2);\n stan::test::expect_ad_matvar(f, in1, in2(0));\n}\n<commit_msg>Update atan2_test.cpp<commit_after>#include <test\/unit\/math\/test_ad.hpp>\n#include <limits>\n#include <vector>\n\nTEST(mathMixCore, atan2) {\n auto f = [](const auto& x1, const auto& x2) {\n using stan::math::atan2;\n return atan2(x1, x2);\n };\n double nan = std::numeric_limits<double>::quiet_NaN();\n stan::test::expect_ad(f, nan, 1.0);\n stan::test::expect_ad(f, 1.0, nan);\n stan::test::expect_ad(f, nan, nan);\n stan::test::expect_ad(f, 1.0, 1.0);\n stan::test::expect_ad(f, 1.5, 1.5);\n stan::test::expect_ad(f, 1.2, 3.9);\n stan::test::expect_ad(f, 0.5, 2.3);\n}\n\nTEST(mathMixScalFun, atan2) {\n auto f = [](const auto& x1, const auto& x2) {\n using stan::math::atan2;\n return atan2(x1, x2);\n };\n\n \/\/ finite differences fails for\n \/\/ infinite inputs \n \/\/ stan::test::expect_common_nonzero_binary(f);\n\n stan::test::expect_ad(f, 1.0, 1.0);\n stan::test::expect_ad(f, 1.0, 0.5);\n stan::test::expect_ad(f, 1.2, 3.9);\n stan::test::expect_ad(f, 7.5, 1.8);\n\n Eigen::VectorXd in1(3);\n in1 << 1.0, 1.0, 1.2;\n Eigen::VectorXd in2(3);\n in2 << 1.0, 0.5, 3.9;\n stan::test::expect_ad_vectorized_binary(f, in1, in2);\n}\n\nTEST(mathMixScalFun, atan2_varmat) {\n auto f = [](const auto& x1, const auto& x2) {\n using stan::math::atan2;\n return atan2(x1, x2);\n };\n\n Eigen::VectorXd in1(3);\n in1 << 0.5, 3.4, 5.2;\n Eigen::VectorXd in2(3);\n in2 << 3.3, 0.9, 6.7;\n stan::test::expect_ad_matvar(f, in1, in2);\n stan::test::expect_ad_matvar(f, in1(0), in2);\n stan::test::expect_ad_matvar(f, in1, in2(0));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"classui.h\"\r\n#include \"listworker.h\"\r\n#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nclassUI::classUI()\r\n{\r\n\r\n}\r\n\r\nvoid classUI::run()\r\n{\r\n bool runOn = true;\r\n string choice;\r\n do\r\n {\r\n cout << \"Welcome to the Amazing Database: \" << endl;\r\n cout << \"-----------------------------------------------------------\" << endl;\r\n cout << \"add\" << \"\\t\" << \"Add a person to the database\" << endl;\r\n cout << \"remove\" << \"\\t\" << \"Remove a person from the database\" << endl;\r\n cout << \"view\" << \"\\t\" << \"View the entire database\" << endl;\r\n cout << \"save\" << \"\\t\" << \"Save the database\" << endl;\r\n cout << \"search\" << \"\\t\" << \"Search the database\" << endl;\r\n cout << \"sort\" << \"\\t\" << \"Sort the database by name\/yearofbirth\" << endl;\r\n cout << \"exit\" << \"\\t\" << \"Exit\" << endl;\r\n cin >> choice;\r\n if (choice != \"exit\"){\r\n select(choice);\r\n }\r\n else{\r\n list.saveFile();\r\n runOn = false;\r\n }\r\n }while(runOn == true);\r\n}\r\n\r\nvoid classUI::select(string ch)\r\n{\r\n if(ch == \"add\" || ch == \"ADD\" || ch == \"Add\" ){\r\n addPerson();\r\n }\r\n\r\n else if(ch == \"view\" || ch == \"View\" || ch == \"VIEW\")\r\n {\r\n viewAll();\r\n }\r\n else if(ch == \"sort\" || ch == \"Sort\" || ch == \"SORT\")\r\n {\r\n string sortcho;\r\n cout << \"Enter 'name' or 'year' and then re-enter the 'view' command.\" << endl;\r\n cin >> sortcho;\r\n\r\n if(sortcho == \"name\" || sortcho == \"Name\" || sortcho == \"NAME\")\r\n {\r\n list.sortNames();\r\n }\r\n else if(sortcho == \"year\" || sortcho == \"Year\" || sortcho == \"YEAR\")\r\n {\r\n list.sortBirth();\r\n }\r\n viewAll();\r\n\r\n }\r\n else if(ch == \"search\" || ch == \"Search\" || ch == \"SEARCH\"){\r\n searching();\r\n }\r\n else if(ch == \"remove\" || ch == \"Remove\" || ch == \"REMOVE\"){\r\n remove();\r\n }\r\n else if(ch == \"save\" || ch == \"Save\" || ch == \"SAVE\"){\r\n save();\r\n }\r\n else if(ch == \"yo\" || ch == \"Yo\" || ch == \"yO\" || ch == \"YO\")\r\n {\r\n yo();\r\n }\r\n else\r\n {\r\n cout << \"Invalid input\" << endl;\r\n }\r\n}\r\nvoid classUI::view(int i)\r\n{\r\n int nameSize = list.getNameSize(i);\r\n cout << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \"Name\" << \"\\t\" << \"\\t\" << \"\\t\" << \"\\t\" << \"|Gender \" << \"|Born \" << \"\\t\" << \"|Death\" << endl;\r\n cout << \"--------------------------------|-------|-------|-------------\" << endl;\r\n\r\n cout << list.getName(i);\r\n if(nameSize > 0 && nameSize <= 7)\r\n {\r\n cout << \"\\t\" << \"\\t\" << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 7 && nameSize <= 15)\r\n {\r\n cout << \"\\t\" << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 15 && nameSize <= 23)\r\n {\r\n cout << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 23 && nameSize <= 31)\r\n {\r\n cout << \"\\t\";\r\n }\r\n\r\n if(list.getGender(i) == 'M' || list.getGender(i) == 'm')\r\n {\r\n cout << \"|Male\" << \"\\t\";\r\n }\r\n else\r\n {\r\n cout << \"|Female\" << \"\\t\";\r\n }\r\n cout << \"|\" << list.getBirth(i);\r\n if(list.getDeath(i) == 0)\r\n {\r\n cout << \"\\t\" << \"|Still kickin'\" << endl;\r\n }\r\n else\r\n {\r\n cout << \"\\t\" << \"|\" << list.getDeath(i) << endl;\r\n }\r\n cout << list.getComment(i) << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << endl;\r\n}\r\n\r\nvoid classUI::searching()\r\n{\r\n\r\n cout << \"----------Select any of the following options----------\" << endl;\r\n cout << \"What do you want to search for? \" << endl;\r\n cout << \"Name -- Searches for a name\" << endl;\r\n cout << \"Gender -- Searches for a Gender\" << endl;\r\n cout << \"Year -- Searches for a year born\" << endl;\r\n search();\r\n}\r\nvoid classUI::addPerson()\r\n{\r\n string name;\r\n char gender;\r\n int yearOfBirth = 0;\r\n int yearOfDeath = 0;\r\n string comment;\r\n\r\n cout << \"Input Name: \";\r\n cin.ignore();\r\n std::getline(std::cin,name);\r\n cout << \"Input gender (M\/F): \";\r\n cin >> gender;\r\n if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')\r\n {\r\n cout << \"Input year of birth: \";\r\n cin >> yearOfBirth;\r\n cout << \"Input year of death: \";\r\n cin >> yearOfDeath;\r\n cout << \"Input a comment: \";\r\n cin >> comment;\r\n }\r\n else\r\n {\r\n cout << \"Invalid gender! Try again.\" << endl;\r\n addPerson();\r\n }\r\n list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);\r\n\r\n}\r\n\r\nvoid classUI::search()\r\n{\r\n string searchChoice;\r\n cin >> searchChoice;\r\n if (searchChoice == \"Name\" || searchChoice == \"name\" || searchChoice == \"NAME\")\r\n {\r\n string namesearch;\r\n cout << \"Enter a name you want to search for: \";\r\n cin >> namesearch;\r\n\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(namesearch == list.getName(i))\r\n {\r\n namesearch = list.getName(i);\r\n view(i);\r\n }\r\n }\r\n \/*if ( eitthvad dot)\r\n {\r\n cout << \"Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu\" << endl;\r\n }*\/\r\n\r\n }\r\n else if (searchChoice == \"Gender\" || searchChoice == \"GENDER\" || searchChoice == \"gender\")\r\n {\r\n char gendersearch;\r\n\r\n cout << \"Enter a Gender you want to search for: (m\/f)\";\r\n cin >> gendersearch;\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(gendersearch == list.getGender(i))\r\n {\r\n gendersearch = list.getGender(i);\r\n view(i);\r\n cout << \"blabla\" << endl;\r\n }\r\n }\r\n \/*\r\n if (eitthvad dot)\r\n {\r\n cout << \"Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu\" << endl;\r\n }*\/\r\n\r\n }\r\n else if (searchChoice == \"year\" || searchChoice == \"YEAR\" || searchChoice == \"Year\")\r\n {\r\n int yearsearch;\r\n cout << \"Enter a Year you want to search for: \";\r\n cin >> yearsearch;\r\n\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(yearsearch == list.getBirth(i))\r\n {\r\n yearsearch = list.getBirth(i);\r\n\r\n view(i);\r\n }\r\n }\/*\r\n if (eitthvad dot)\r\n {\r\n cout << \"Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu\" << endl;\r\n }*\/\r\n }\r\n else\r\n {\r\n cout << \"Error reading input\" << endl;\r\n }\r\n\r\n}\r\n\r\n\r\nvoid classUI::remove()\r\n{\r\n string name;\r\n cout << \"Enter a name of person that you want to remove: \";\r\n cin >> name;\r\n if (list.removePerson(name) == true)\r\n {\r\n cout << \"Person removed!\" << endl;\r\n }\r\n else\r\n {\r\n cout << \"Person not found!\" << endl;\r\n }\r\n}\r\nvoid classUI::save()\r\n{\r\n list.saveFile();\r\n}\r\nvoid classUI::viewAll()\r\n{\r\n for(int i = 0; i < list.getPersonsSize(); i++)\r\n {\r\n view(i);\r\n }\r\n}\r\nvoid classUI::yo()\r\n{\r\n cout << endl;\r\n cout << \"`8.`8888. ,8' ,o888888o. \" << endl;\r\n cout << \" `8.`8888. ,8' . 8888 `88. \" << endl;\r\n cout << \" `8.`8888. ,8' ,8 8888 `8b \" << endl;\r\n cout << \" `8.`8888.,8' 88 8888 `8b \" << endl;\r\n cout << \" `8.`88888' 88 8888 88 \" << endl;\r\n cout << \" `8. 8888 88 8888 88 \" << endl;\r\n cout << \" `8 8888 88 8888 ,8P \" << endl;\r\n cout << \" 8 8888 `8 8888 ,8P \" << endl;\r\n cout << \" 8 8888 ` 8888 ,88' \" << endl;\r\n cout << \" 8 8888 `8888888P' \" << endl;\r\n cout << endl;\r\n}\r\n<commit_msg>Setti inn error message fyrir search ef að hlutir finnast ekki<commit_after>#include \"classui.h\"\r\n#include \"listworker.h\"\r\n#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nclassUI::classUI()\r\n{\r\n\r\n}\r\n\r\nvoid classUI::run()\r\n{\r\n bool runOn = true;\r\n string choice;\r\n do\r\n {\r\n cout << \"Welcome to the Amazing Database: \" << endl;\r\n cout << \"-----------------------------------------------------------\" << endl;\r\n cout << \"add\" << \"\\t\" << \"Add a person to the database\" << endl;\r\n cout << \"remove\" << \"\\t\" << \"Remove a person from the database\" << endl;\r\n cout << \"view\" << \"\\t\" << \"View the entire database\" << endl;\r\n cout << \"save\" << \"\\t\" << \"Save the database\" << endl;\r\n cout << \"search\" << \"\\t\" << \"Search the database\" << endl;\r\n cout << \"sort\" << \"\\t\" << \"Sort the database by name\/yearofbirth\" << endl;\r\n cout << \"exit\" << \"\\t\" << \"Exit\" << endl;\r\n cin >> choice;\r\n if (choice != \"exit\"){\r\n select(choice);\r\n }\r\n else{\r\n list.saveFile();\r\n runOn = false;\r\n }\r\n }while(runOn == true);\r\n}\r\n\r\nvoid classUI::select(string ch)\r\n{\r\n if(ch == \"add\" || ch == \"ADD\" || ch == \"Add\" ){\r\n addPerson();\r\n }\r\n\r\n else if(ch == \"view\" || ch == \"View\" || ch == \"VIEW\")\r\n {\r\n viewAll();\r\n }\r\n else if(ch == \"sort\")\r\n {\r\n string sortcho;\r\n cout << \"Enter 'name' or 'year' and then re-enter the 'view' command.\" << endl;\r\n cin >> sortcho;\r\n\r\n if(sortcho == \"name\")\r\n {\r\n list.sortNames();\r\n }\r\n else if(sortcho == \"year\")\r\n {\r\n list.sortBirth();\r\n }\r\n\r\n }\r\n else if(ch == \"search\" || ch == \"Search\" || ch == \"SEARCH\"){\r\n searching();\r\n }\r\n else if(ch == \"remove\" || ch == \"Remove\" || ch == \"REMOVE\"){\r\n remove();\r\n }\r\n else if(ch == \"save\" || ch == \"Save\" || ch == \"SAVE\"){\r\n save();\r\n }\r\n else if(ch == \"yo\" || ch == \"Yo\" || ch == \"yO\" || ch == \"YO\")\r\n {\r\n yo();\r\n }\r\n else\r\n {\r\n cout << \"Invalid input\" << endl;\r\n }\r\n}\r\nvoid classUI::view(int i)\r\n{\r\n int nameSize = list.getNameSize(i);\r\n cout << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \"Name\" << \"\\t\" << \"\\t\" << \"\\t\" << \"\\t\" << \"|Gender \" << \"|Born \" << \"\\t\" << \"|Death\" << endl;\r\n cout << \"--------------------------------|-------|-------|-------------\" << endl;\r\n\r\n cout << list.getName(i);\r\n if(nameSize > 0 && nameSize <= 7)\r\n {\r\n cout << \"\\t\" << \"\\t\" << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 7 && nameSize <= 15)\r\n {\r\n cout << \"\\t\" << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 15 && nameSize <= 23)\r\n {\r\n cout << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 23 && nameSize <= 31)\r\n {\r\n cout << \"\\t\";\r\n }\r\n\r\n if(list.getGender(i) == 'M' || list.getGender(i) == 'm')\r\n {\r\n cout << \"|Male\" << \"\\t\";\r\n }\r\n else\r\n {\r\n cout << \"|Female\" << \"\\t\";\r\n }\r\n cout << \"|\" << list.getBirth(i);\r\n if(list.getDeath(i) == 0)\r\n {\r\n cout << \"\\t\" << \"|Still kickin'\" << endl;\r\n }\r\n else\r\n {\r\n cout << \"\\t\" << \"|\" << list.getDeath(i) << endl;\r\n }\r\n cout << list.getComment(i) << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << endl;\r\n}\r\n\r\nvoid classUI::searching()\r\n{\r\n\r\n cout << \"----------Select any of the following options----------\" << endl;\r\n cout << \"What do you want to search for? \" << endl;\r\n cout << \"Name -- Searches for a name\" << endl;\r\n cout << \"Gender -- Searches for a Gender\" << endl;\r\n cout << \"Year -- Searches for a year born\" << endl;\r\n search();\r\n}\r\nvoid classUI::addPerson()\r\n{\r\n string name;\r\n char gender;\r\n int yearOfBirth = 0;\r\n int yearOfDeath = 0;\r\n string comment;\r\n\r\n cout << \"Input Name: \";\r\n cin.ignore();\r\n std::getline(std::cin,name);\r\n cout << \"Input gender (M\/F): \";\r\n cin >> gender;\r\n if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')\r\n {\r\n cout << \"Input year of birth: \";\r\n cin >> yearOfBirth;\r\n cout << \"Input year of death: \";\r\n cin >> yearOfDeath;\r\n cout << \"Input a comment: \";\r\n cin >> comment;\r\n }\r\n else\r\n {\r\n cout << \"Invalid gender! Try again.\" << endl;\r\n addPerson();\r\n }\r\n list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);\r\n\r\n}\r\n\r\nvoid classUI::search()\r\n{\r\n string searchChoice;\r\n cin >> searchChoice;\r\n if (searchChoice == \"Name\" || searchChoice == \"name\" || searchChoice == \"NAME\")\r\n {\r\n string namesearch;\r\n cout << \"Enter a name you want to search for: \";\r\n cin >> namesearch;\r\n\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(namesearch == list.getName(i))\r\n {\r\n namesearch = list.getName(i);\r\n view(i);\r\n }\r\n else if(i+1 == list.getPersonsSize())\r\n {\r\n cout << \"Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu\" << endl;\r\n }\r\n }\r\n }\r\n else if (searchChoice == \"Gender\" || searchChoice == \"GENDER\" || searchChoice == \"gender\")\r\n {\r\n char gendersearch;\r\n\r\n cout << \"Enter a Gender you want to search for: (m\/f)\";\r\n cin >> gendersearch;\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(gendersearch == list.getGender(i))\r\n {\r\n gendersearch = list.getGender(i);\r\n view(i);\r\n }\r\n else if(i+1 == list.getPersonsSize())\r\n {\r\n cout << \"Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu\" << endl;\r\n }\r\n }\r\n }\r\n else if (searchChoice == \"year\" || searchChoice == \"YEAR\" || searchChoice == \"Year\")\r\n {\r\n int yearsearch;\r\n cout << \"Enter a Year you want to search for: \";\r\n cin >> yearsearch;\r\n\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(yearsearch == list.getBirth(i))\r\n {\r\n yearsearch = list.getBirth(i);\r\n view(i);\r\n }\r\n else if(i+1 == list.getPersonsSize())\r\n {\r\n cout << \"Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu\" << endl;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n cout << \"Error reading input\" << endl;\r\n }\r\n}\r\nvoid classUI::remove()\r\n{\r\n string name;\r\n cout << \"Enter a name of person that you want to remove: \";\r\n cin >> name;\r\n if (list.removePerson(name) == true)\r\n {\r\n cout << \"Person removed!\" << endl;\r\n }\r\n else\r\n {\r\n cout << \"Person not found!\" << endl;\r\n }\r\n}\r\nvoid classUI::save()\r\n{\r\n list.saveFile();\r\n}\r\nvoid classUI::viewAll()\r\n{\r\n for(int i = 0; i < list.getPersonsSize(); i++)\r\n {\r\n view(i);\r\n }\r\n}\r\nvoid classUI::yo()\r\n{\r\n cout << endl;\r\n cout << \"`8.`8888. ,8' ,o888888o. \" << endl;\r\n cout << \" `8.`8888. ,8' . 8888 `88. \" << endl;\r\n cout << \" `8.`8888. ,8' ,8 8888 `8b \" << endl;\r\n cout << \" `8.`8888.,8' 88 8888 `8b \" << endl;\r\n cout << \" `8.`88888' 88 8888 88 \" << endl;\r\n cout << \" `8. 8888 88 8888 88 \" << endl;\r\n cout << \" `8 8888 88 8888 ,8P \" << endl;\r\n cout << \" 8 8888 `8 8888 ,8P \" << endl;\r\n cout << \" 8 8888 ` 8888 ,88' \" << endl;\r\n cout << \" 8 8888 `8888888P' \" << endl;\r\n cout << endl;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"classui.h\"\r\n#include \"listworker.h\"\r\n#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <time.h>\r\n\r\nusing namespace std;\r\n\r\nClassUI::ClassUI()\r\n{\r\n\r\n}\r\nvoid ClassUI::run()\r\n{\r\n cout << \"\\t\" << \"Welcome to the Amazing Database! \" << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \"\\t\" << \" *** Quote of the day ***\" << endl;\r\n cout << getQuotes() << endl;\r\n mainMenu();\r\n}\r\nvoid ClassUI::mainMenu()\r\n{\r\n string choice;\r\n do\r\n {\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \" (1) - \" << \"\\t\" << \"Add a person to the database.\" << endl;\r\n cout << \" (2) - \" << \"\\t\" << \"Remove a person from the database.\" << endl;\r\n cout << \" (3) - \" << \"\\t\" << \"View the entire database.\" << endl;\r\n cout << \" (4) - \" << \"\\t\" << \"Save the database.\" << endl;\r\n cout << \" (5) - \" << \"\\t\" << \"Search the database.\" << endl;\r\n cout << \" (6) - \" << \"\\t\" << \"Sort the database.\" << endl;\r\n cout << \" (7) - \" << \"\\t\" << \"Exit.\" << endl;\r\n cout << \"Enter your command (1 - 7): \";\r\n cin >> choice;\r\n cout << endl;\r\n\r\n if (choice != \"7\")\r\n {\r\n select(choice);\r\n }\r\n else\r\n {\r\n list.saveFile();\r\n runOn = false;\r\n }\r\n }while(runOn == true);\r\n}\r\nvoid ClassUI::select(string ch)\r\n{\r\n if(ch == \"1\")\r\n {\r\n addPerson();\r\n }\r\n else if(ch == \"2\")\r\n {\r\n remove();\r\n }\r\n else if(ch == \"3\")\r\n {\r\n viewAll();\r\n }\r\n else if(ch == \"4\")\r\n {\r\n save();\r\n }\r\n else if(ch == \"5\")\r\n {\r\n searching();\r\n }\r\n else if(ch == \"6\")\r\n {\r\n sorting();\r\n }\r\n else if(ch == \"yo\")\r\n {\r\n yo();\r\n }\r\n else\r\n {\r\n cout << \"Invalid input. Please enter a number between 1 - 7.\" << endl;\r\n }\r\n}\r\nvoid ClassUI::view(int i)\r\n{\r\n int nameSize = list.getNameSize(i);\r\n\r\n cout << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \"Name\" << \"\\t\" << \"\\t\" << \"\\t\" << \"\\t\" << \"|Gender \" << \"|Born \" << \"\\t\" << \"|Death\" << endl;\r\n cout << \"--------------------------------|-------|-------|-------------\" << endl;\r\n cout << list.getName(i);\r\n\r\n if(nameSize > 0 && nameSize <= 7)\r\n {\r\n cout << \"\\t\" << \"\\t\" << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 7 && nameSize <= 15)\r\n {\r\n cout << \"\\t\" << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 15 && nameSize <= 23)\r\n {\r\n cout << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 23 && nameSize <= 31)\r\n {\r\n cout << \"\\t\";\r\n }\r\n\r\n if(list.getGender(i) == 'M' || list.getGender(i) == 'm')\r\n {\r\n cout << \"|Male\" << \"\\t\";\r\n }\r\n else\r\n {\r\n cout << \"|Female\" << \"\\t\";\r\n }\r\n\r\n cout << \"|\" << list.getBirth(i);\r\n\r\n if(list.getDeath(i) == 0)\r\n {\r\n cout << \"\\t\" << \"| n\/a\" << endl;\r\n }\r\n else\r\n {\r\n cout << \"\\t\" << \"|\" << list.getDeath(i) << endl;\r\n }\r\n cout << list.getComment(i) << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << endl;\r\n}\r\nvoid ClassUI::searching()\r\n{\r\n\r\n cout << \"-------------Select any of the following commands-------------\" << endl;\r\n cout << \"What do you want to search for? (1 - 4)\" << endl;\r\n cout << \" (1) - Searches for a name.\" << endl;\r\n cout << \" (2) - Searches for a Gender.\" << endl;\r\n cout << \" (3) - Searches for a year born.\" << endl;\r\n cout << \" (4) - Return to main menu\" << endl;\r\n\r\n search();\r\n}\r\nvoid ClassUI::addPerson()\r\n{\r\n string name;\r\n string comment;\r\n char gender;\r\n char yesOrNo;\r\n int yearOfBirth = 0;\r\n int yearOfDeath = 0;\r\n\r\n cout << \"Input Name: \";\r\n cin.ignore();\r\n std::getline(std::cin,name);\r\n cout << \"Input gender (M\/F): \";\r\n cin >> gender;\r\n\r\n if (gender == 'm')\r\n {\r\n gender = 'M';\r\n }\r\n else if (gender == 'f')\r\n {\r\n gender = 'F';\r\n }\r\n\r\n if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')\r\n {\r\n cout << \"Input year of birth: \";\r\n cin >> yearOfBirth;\r\n\r\n cout << \"Is the individual deceased? (y\/n)\";\r\n cin >> yesOrNo;\r\n\r\n if (yesOrNo == 'Y' || yesOrNo == 'y')\r\n {\r\n cout << \"Input year of death: \";\r\n cin >> yearOfDeath;\r\n }\r\n cout << \"Input a comment about the individual: \";\r\n cin.ignore();\r\n std::getline(std::cin,comment);\r\n }\r\n else\r\n {\r\n cout << \"Invalid gender! Try again.\" << endl;\r\n addPerson();\r\n }\r\n\r\n cout << \"Are you sure that you want to add this person? (y\/n)\"; \/\/ Þetta er ógeðslegur texti, endilega finnum eitthvað skárra\r\n string validatePerson;\r\n cin >> validatePerson;\r\n\r\n if(validatePerson == \"y\")\r\n {\r\n cout << \"New person added!\" << endl;\r\n list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);\r\n }\r\n else\r\n {\r\n cout << \"Operation addPerson aborted!\" << endl; \/\/ Endilega komið með tillögu að breytingu á þessum texta\r\n }\r\n}\r\nvoid ClassUI::search()\r\n{\r\n string searchChoice;\r\n cout << \"Enter your command (1 - 4): \";\r\n cin >> searchChoice;\r\n cout << endl;\r\n\r\n if (searchChoice == \"1\")\r\n {\r\n string namesearch;\r\n cout << \"Enter a name you want to search for: \";\r\n cin.ignore();\r\n std::getline(std::cin,namesearch);\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n std::size_t found = list.getName(i).find(namesearch);\r\n if (found!=std::string::npos)\r\n {\r\n view(i);\r\n }\r\n }\r\n\r\n if(list.nameSearcher(namesearch) == false)\r\n {\r\n cout << \"Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu.\" << endl;\r\n searching();\r\n }\r\n }\r\n else if (searchChoice == \"2\")\r\n {\r\n char gendersearch;\r\n\r\n cout << \"Enter a gender you want to search for: (M\/F)\";\r\n cin >> gendersearch;\r\n\r\n if(gendersearch == 'm')\r\n {\r\n gendersearch = 'M';\r\n }\r\n else if (gendersearch == 'f')\r\n {\r\n gendersearch = 'F';\r\n }\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(gendersearch == list.getGender(i))\r\n {\r\n gendersearch = list.getGender(i);\r\n view(i);\r\n }\r\n }\r\n\r\n if(list.genderSearcher(gendersearch) == false)\r\n {\r\n cout << \"Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu.\" << endl;\r\n searching();\r\n }\r\n }\r\n else if (searchChoice == \"3\")\r\n {\r\n int yearsearch;\r\n cout << \"Enter a year you want to search for: \";\r\n cin >> yearsearch;\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(yearsearch == list.getBirth(i))\r\n {\r\n yearsearch = list.getBirth(i);\r\n view(i);\r\n }\r\n }\r\n\r\n if(list.yearSearcher(yearsearch) == false)\r\n {\r\n cout << \"Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu.\" << endl;\r\n searching();\r\n }\r\n }\r\n else if (searchChoice == \"4\")\r\n {\r\n mainMenu();\r\n }\r\n else\r\n {\r\n cout << \"Error reading input. Please enter a number between 1- 3.\" << endl;\r\n search();\r\n }\r\n}\r\nvoid ClassUI::remove()\r\n{\r\n string name;\r\n cout << \"Enter the full name of the person that you want to remove: \";\r\n cin.ignore();\r\n std::getline(std::cin,name);\r\n\r\n if (list.removePersonFound(name) == true)\r\n {\r\n char validateRemove;\r\n cout << \"Person found!\" << endl;\r\n cout << \"Are you sure you want to remove this person? (y\/n): \";\r\n cin >> validateRemove;\r\n\r\n if(validateRemove == 'y' || validateRemove == 'Y')\r\n {\r\n if(list.removePerson(name) == true)\r\n {\r\n cout << \"Person removed!\" << endl;\r\n }\r\n else\r\n {\r\n cout << \"Person not removed!\" << endl;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n cout << \"Person not found!\" << endl;\r\n }\r\n}\r\nvoid ClassUI::save()\r\n{\r\n list.saveFile();\r\n cout << \"Database saved.\" << endl;\r\n}\r\nvoid ClassUI::viewAll()\r\n{\r\n for(int i = 0; i < list.getPersonsSize(); i++)\r\n {\r\n view(i);\r\n }\r\n}\r\nvoid ClassUI::yo()\r\n{\r\n cout << endl;\r\n cout << \"`8.`8888. ,8' ,o888888o. \" << endl;\r\n cout << \" `8.`8888. ,8' . 8888 `88. \" << endl;\r\n cout << \" `8.`8888. ,8' ,8 8888 `8b \" << endl;\r\n cout << \" `8.`8888.,8' 88 8888 `8b \" << endl;\r\n cout << \" `8.`88888' 88 8888 88 \" << endl;\r\n cout << \" `8. 8888 88 8888 88 \" << endl;\r\n cout << \" `8 8888 88 8888 ,8P \" << endl;\r\n cout << \" 8 8888 `8 8888 ,8P \" << endl;\r\n cout << \" 8 8888 ` 8888 ,88' \" << endl;\r\n cout << \" 8 8888 `8888888P' \" << endl;\r\n cout << endl;\r\n}\r\nstring ClassUI::getQuotes()\r\n{\r\n string quotes[5] = {\"\\\"A good programmer is someone who always looks both ways before crossing a one-way street.\\\" (Doug Linder)\",\r\n \"\\\"Programming is like sex. One mistake and you have to support it for the rest of your life.\\\" (Michael Sinz)\",\r\n \"\\\"Walking on water and developing software from a specification are easy if both are frozen.\\\" (Edward V Berard)\",\r\n \"\\\"One man's crappy software is another man's full time job.\\\" (Jessica Gaston)\",\r\n \"\\\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\\\" (Waldi Ravens)\"\r\n };\r\n int v1 = 0;\r\n srand (time(NULL));\r\n v1 = rand() % 5;\r\n return quotes[v1];\r\n}\r\nvoid ClassUI::sorting()\r\n{\r\n string sortcho;\r\n cout << \"Enter a sort command (1 - 3):\" << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \" (1) - Sort by alphabetical order\" << endl;\r\n cout << \" (2) - Sort by chronological order\" << endl;\r\n cout << \" (3) - Return to main menu\" << endl;\r\n cout << \"Enter your command (1 - 2): \";\r\n cin >> sortcho;\r\n cout << endl;\r\n\r\n if(sortcho == \"1\")\r\n {\r\n list.sortNames();\r\n viewAll();\r\n }\r\n else if(sortcho == \"2\")\r\n {\r\n list.sortBirth();\r\n viewAll();\r\n }\r\n else if(sortcho == \"3\")\r\n {\r\n mainMenu();\r\n }\r\n}\r\n<commit_msg>lagað cout í addperson<commit_after>#include \"classui.h\"\r\n#include \"listworker.h\"\r\n#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <time.h>\r\n\r\nusing namespace std;\r\n\r\nClassUI::ClassUI()\r\n{\r\n\r\n}\r\nvoid ClassUI::run()\r\n{\r\n cout << \"\\t\" << \"Welcome to the Amazing Database! \" << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \"\\t\" << \" *** Quote of the day ***\" << endl;\r\n cout << getQuotes() << endl;\r\n mainMenu();\r\n}\r\nvoid ClassUI::mainMenu()\r\n{\r\n string choice;\r\n do\r\n {\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \" (1) - \" << \"\\t\" << \"Add a person to the database.\" << endl;\r\n cout << \" (2) - \" << \"\\t\" << \"Remove a person from the database.\" << endl;\r\n cout << \" (3) - \" << \"\\t\" << \"View the entire database.\" << endl;\r\n cout << \" (4) - \" << \"\\t\" << \"Save the database.\" << endl;\r\n cout << \" (5) - \" << \"\\t\" << \"Search the database.\" << endl;\r\n cout << \" (6) - \" << \"\\t\" << \"Sort the database.\" << endl;\r\n cout << \" (7) - \" << \"\\t\" << \"Exit.\" << endl;\r\n cout << \"Enter your command (1 - 7): \";\r\n cin >> choice;\r\n cout << endl;\r\n\r\n if (choice != \"7\")\r\n {\r\n select(choice);\r\n }\r\n else\r\n {\r\n list.saveFile();\r\n runOn = false;\r\n }\r\n }while(runOn == true);\r\n}\r\nvoid ClassUI::select(string ch)\r\n{\r\n if(ch == \"1\")\r\n {\r\n addPerson();\r\n }\r\n else if(ch == \"2\")\r\n {\r\n remove();\r\n }\r\n else if(ch == \"3\")\r\n {\r\n viewAll();\r\n }\r\n else if(ch == \"4\")\r\n {\r\n save();\r\n }\r\n else if(ch == \"5\")\r\n {\r\n searching();\r\n }\r\n else if(ch == \"6\")\r\n {\r\n sorting();\r\n }\r\n else if(ch == \"yo\")\r\n {\r\n yo();\r\n }\r\n else\r\n {\r\n cout << \"Invalid input. Please enter a number between 1 - 7.\" << endl;\r\n }\r\n}\r\nvoid ClassUI::view(int i)\r\n{\r\n int nameSize = list.getNameSize(i);\r\n\r\n cout << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \"Name\" << \"\\t\" << \"\\t\" << \"\\t\" << \"\\t\" << \"|Gender \" << \"|Born \" << \"\\t\" << \"|Death\" << endl;\r\n cout << \"--------------------------------|-------|-------|-------------\" << endl;\r\n cout << list.getName(i);\r\n\r\n if(nameSize > 0 && nameSize <= 7)\r\n {\r\n cout << \"\\t\" << \"\\t\" << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 7 && nameSize <= 15)\r\n {\r\n cout << \"\\t\" << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 15 && nameSize <= 23)\r\n {\r\n cout << \"\\t\" << \"\\t\";\r\n }\r\n else if(nameSize > 23 && nameSize <= 31)\r\n {\r\n cout << \"\\t\";\r\n }\r\n\r\n if(list.getGender(i) == 'M' || list.getGender(i) == 'm')\r\n {\r\n cout << \"|Male\" << \"\\t\";\r\n }\r\n else\r\n {\r\n cout << \"|Female\" << \"\\t\";\r\n }\r\n\r\n cout << \"|\" << list.getBirth(i);\r\n\r\n if(list.getDeath(i) == 0)\r\n {\r\n cout << \"\\t\" << \"| n\/a\" << endl;\r\n }\r\n else\r\n {\r\n cout << \"\\t\" << \"|\" << list.getDeath(i) << endl;\r\n }\r\n cout << list.getComment(i) << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << endl;\r\n}\r\nvoid ClassUI::searching()\r\n{\r\n\r\n cout << \"-------------Select any of the following commands-------------\" << endl;\r\n cout << \"What do you want to search for? (1 - 4)\" << endl;\r\n cout << \" (1) - Searches for a name.\" << endl;\r\n cout << \" (2) - Searches for a Gender.\" << endl;\r\n cout << \" (3) - Searches for a year born.\" << endl;\r\n cout << \" (4) - Return to main menu\" << endl;\r\n\r\n search();\r\n}\r\nvoid ClassUI::addPerson()\r\n{\r\n string name;\r\n string comment;\r\n char gender;\r\n char yesOrNo;\r\n int yearOfBirth = 0;\r\n int yearOfDeath = 0;\r\n\r\n cout << \"Input Name: \";\r\n cin.ignore();\r\n std::getline(std::cin,name);\r\n cout << \"Input gender (M\/F): \";\r\n cin >> gender;\r\n\r\n if (gender == 'm')\r\n {\r\n gender = 'M';\r\n }\r\n else if (gender == 'f')\r\n {\r\n gender = 'F';\r\n }\r\n\r\n if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')\r\n {\r\n cout << \"Input year of birth: \";\r\n cin >> yearOfBirth;\r\n\r\n cout << \"Is the individual deceased? (y\/n) \";\r\n cin >> yesOrNo;\r\n\r\n if (yesOrNo == 'Y' || yesOrNo == 'y')\r\n {\r\n cout << \"Input year of death: \";\r\n cin >> yearOfDeath;\r\n }\r\n cout << \"Input a comment about the individual: \";\r\n cin.ignore();\r\n std::getline(std::cin,comment);\r\n }\r\n else\r\n {\r\n cout << \"Invalid gender! Try again.\" << endl;\r\n addPerson();\r\n }\r\n\r\n cout << \"Are you sure that you want to add this person? (y\/n) \";\r\n string validatePerson;\r\n cin >> validatePerson;\r\n\r\n if(validatePerson == \"y\")\r\n {\r\n cout << \"New person added!\" << endl;\r\n list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);\r\n }\r\n else\r\n {\r\n cout << \"Person not added!\" << endl;\r\n }\r\n}\r\nvoid ClassUI::search()\r\n{\r\n string searchChoice;\r\n cout << \"Enter your command (1 - 4): \";\r\n cin >> searchChoice;\r\n cout << endl;\r\n\r\n if (searchChoice == \"1\")\r\n {\r\n string namesearch;\r\n cout << \"Enter a name you want to search for: \";\r\n cin.ignore();\r\n std::getline(std::cin,namesearch);\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n std::size_t found = list.getName(i).find(namesearch);\r\n if (found!=std::string::npos)\r\n {\r\n view(i);\r\n }\r\n }\r\n\r\n if(list.nameSearcher(namesearch) == false)\r\n {\r\n cout << \"Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu.\" << endl;\r\n searching();\r\n }\r\n }\r\n else if (searchChoice == \"2\")\r\n {\r\n char gendersearch;\r\n\r\n cout << \"Enter a gender you want to search for: (M\/F)\";\r\n cin >> gendersearch;\r\n\r\n if(gendersearch == 'm')\r\n {\r\n gendersearch = 'M';\r\n }\r\n else if (gendersearch == 'f')\r\n {\r\n gendersearch = 'F';\r\n }\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(gendersearch == list.getGender(i))\r\n {\r\n gendersearch = list.getGender(i);\r\n view(i);\r\n }\r\n }\r\n\r\n if(list.genderSearcher(gendersearch) == false)\r\n {\r\n cout << \"Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu.\" << endl;\r\n searching();\r\n }\r\n }\r\n else if (searchChoice == \"3\")\r\n {\r\n int yearsearch;\r\n cout << \"Enter a year you want to search for: \";\r\n cin >> yearsearch;\r\n\r\n for(int i = 0; i < list.getPersonsSize();++i)\r\n {\r\n if(yearsearch == list.getBirth(i))\r\n {\r\n yearsearch = list.getBirth(i);\r\n view(i);\r\n }\r\n }\r\n\r\n if(list.yearSearcher(yearsearch) == false)\r\n {\r\n cout << \"Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu.\" << endl;\r\n searching();\r\n }\r\n }\r\n else if (searchChoice == \"4\")\r\n {\r\n mainMenu();\r\n }\r\n else\r\n {\r\n cout << \"Error reading input. Please enter a number between 1- 3.\" << endl;\r\n search();\r\n }\r\n}\r\nvoid ClassUI::remove()\r\n{\r\n string name;\r\n cout << \"Enter the full name of the person that you want to remove: \";\r\n cin.ignore();\r\n std::getline(std::cin,name);\r\n\r\n if (list.removePersonFound(name) == true)\r\n {\r\n char validateRemove;\r\n cout << \"Person found!\" << endl;\r\n cout << \"Are you sure you want to remove this person? (y\/n): \";\r\n cin >> validateRemove;\r\n\r\n if(validateRemove == 'y' || validateRemove == 'Y')\r\n {\r\n if(list.removePerson(name) == true)\r\n {\r\n cout << \"Person removed!\" << endl;\r\n }\r\n else\r\n {\r\n cout << \"Person not removed!\" << endl;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n cout << \"Person not found!\" << endl;\r\n }\r\n}\r\nvoid ClassUI::save()\r\n{\r\n list.saveFile();\r\n cout << \"Database saved.\" << endl;\r\n}\r\nvoid ClassUI::viewAll()\r\n{\r\n for(int i = 0; i < list.getPersonsSize(); i++)\r\n {\r\n view(i);\r\n }\r\n}\r\nvoid ClassUI::yo()\r\n{\r\n cout << endl;\r\n cout << \"`8.`8888. ,8' ,o888888o. \" << endl;\r\n cout << \" `8.`8888. ,8' . 8888 `88. \" << endl;\r\n cout << \" `8.`8888. ,8' ,8 8888 `8b \" << endl;\r\n cout << \" `8.`8888.,8' 88 8888 `8b \" << endl;\r\n cout << \" `8.`88888' 88 8888 88 \" << endl;\r\n cout << \" `8. 8888 88 8888 88 \" << endl;\r\n cout << \" `8 8888 88 8888 ,8P \" << endl;\r\n cout << \" 8 8888 `8 8888 ,8P \" << endl;\r\n cout << \" 8 8888 ` 8888 ,88' \" << endl;\r\n cout << \" 8 8888 `8888888P' \" << endl;\r\n cout << endl;\r\n}\r\nstring ClassUI::getQuotes()\r\n{\r\n string quotes[5] = {\"\\\"A good programmer is someone who always looks both ways before crossing a one-way street.\\\" (Doug Linder)\",\r\n \"\\\"Programming is like sex. One mistake and you have to support it for the rest of your life.\\\" (Michael Sinz)\",\r\n \"\\\"Walking on water and developing software from a specification are easy if both are frozen.\\\" (Edward V Berard)\",\r\n \"\\\"One man's crappy software is another man's full time job.\\\" (Jessica Gaston)\",\r\n \"\\\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\\\" (Waldi Ravens)\"\r\n };\r\n int v1 = 0;\r\n srand (time(NULL));\r\n v1 = rand() % 5;\r\n return quotes[v1];\r\n}\r\nvoid ClassUI::sorting()\r\n{\r\n string sortcho;\r\n cout << \"Enter a sort command (1 - 3):\" << endl;\r\n cout << \"--------------------------------------------------------------\" << endl;\r\n cout << \" (1) - Sort by alphabetical order\" << endl;\r\n cout << \" (2) - Sort by chronological order\" << endl;\r\n cout << \" (3) - Return to main menu\" << endl;\r\n cout << \"Enter your command (1 - 2): \";\r\n cin >> sortcho;\r\n cout << endl;\r\n\r\n if(sortcho == \"1\")\r\n {\r\n list.sortNames();\r\n viewAll();\r\n }\r\n else if(sortcho == \"2\")\r\n {\r\n list.sortBirth();\r\n viewAll();\r\n }\r\n else if(sortcho == \"3\")\r\n {\r\n mainMenu();\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Android File Transfer For Linux.\n Copyright (C) 2015-2018 Vladimir Menshakov\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 2.1 of the License,\n or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful, but\n 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 License\n along with this library; if not, write to the Free Software Foundation,\n Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\n\n#include <stdio.h>\n#include <stdexcept>\n\n#include <usb\/Context.h>\n\n#include <cli\/CommandLine.h>\n#include <cli\/Session.h>\n\n#include <mtp\/log.h>\n#include <mtp\/version.h>\n\n#include <getopt.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\nint main(int argc, char **argv)\n{\n\tusing namespace mtp;\n\tbool forceInteractive = false;\n\tbool showHelp = false;\n\tbool showPrompt = true;\n\tbool showVersion = false;\n\tbool claimInterface = true;\n\tbool showEvents = false;\n\tconst char *fileInput = nullptr;\n\n\tif (!isatty(STDIN_FILENO))\n\t\tshowPrompt = false;\n\n\tstatic struct option long_options[] =\n\t{\n\t\t{\"verbose\",\t\t\tno_argument,\t\t0,\t'v' },\n\t\t{\"interactive\",\t\tno_argument,\t\t0,\t'i' },\n\t\t{\"batch\",\t\t\tno_argument,\t\t0,\t'b' },\n\t\t{\"events\",\t\t\tno_argument,\t\t0,\t'e' },\n\t\t{\"help\",\t\t\tno_argument,\t\t0,\t'h' },\n\t\t{\"version\",\t\t\tno_argument,\t\t0,\t'V' },\n\t\t{\"no-claim\",\t\tno_argument,\t\t0,\t'C' },\n\t\t{\"input-file\",\t\trequired_argument,\t0,\t'f' },\n\t\t{0,\t\t\t\t\t0,\t\t\t\t\t0,\t 0\t}\n\t};\n\n\twhile(true)\n\t{\n\t\tint optionIndex = 0; \/\/index of matching option\n\t\tint c = getopt_long(argc, argv, \"ibehvVCf:\", long_options, &optionIndex);\n\t\tif (c == -1)\n\t\t\tbreak;\n\t\tswitch(c)\n\t\t{\n\t\tcase 'f':\n\t\t\tfileInput = optarg; \/\/falling back to batch processing here\n\t\tcase 'b':\n\t\t\tshowPrompt = false; \/\/no break here, prompt = false, interactive = true\n\t\tcase 'i':\n\t\t\tforceInteractive = true;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tg_debug = true;\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tshowVersion = true;\n\t\t\tbreak;\n\t\tcase 'C':\n\t\t\tclaimInterface = false;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\tshowEvents = true;\n\t\t\tbreak;\n\t\tcase '?':\n\t\tcase 'h':\n\t\tdefault:\n\t\t\tshowHelp = true;\n\t\t}\n\t}\n\tif (fileInput)\n\t{\n\t\tclose(STDIN_FILENO);\n\t\tint fd = open(fileInput, O_RDONLY);\n\t\tif (fd == -1)\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\texit(1);\n\t\t}\n\t\tif (fd != STDIN_FILENO)\n\t\t{\n\t\t\tfprintf(stderr, \"failed to reopen stdin\\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tif (showHelp)\n\t{\n\t\terror(\n\t\t\t\"usage:\\n\"\n\t\t\t\"-h\\t--help\\t\\tshow this help\\n\"\n\t\t\t\"-v\\t--verbose\\tshow debug output\\n\"\n\t\t\t\"-i\\t--interactive\\tforce interactive mode\\n\"\n\t\t\t\"-b\\t--batch\\t\\tbatch command processing\\n\"\n\t\t\t\"-e\\t--events\\t\\tallow event processing\\n\"\n\t\t\t\"-f\\t--input-file\\tuse file to read input commands\\n\"\n\t\t\t\"-C\\t--no-claim\\tno usb interface claim\\n\"\n\t\t\t\"-V\\t--version\\tshow version information\"\n\t\t\t);\n\t\texit(0);\n\t}\n\n\tif (showVersion)\n\t{\n\t\tprint(GetVersion());\n\t\texit(0);\n\t}\n\n\tauto mtp = Device::FindFirst(claimInterface);\n\tif (!mtp)\n\t{\n\t\terror(\"no mtp device found\");\n\t\texit(1);\n\t}\n\n\ttry\n\t{\n\t\tbool hasCommands = optind >= argc;\n\t\tcli::Session session(mtp, showPrompt);\n\t\tif (!session.SetFirstStorage())\n\t\t{\n\t\t\terror(\"your device may be locked or does not have any storage available\");\n\t\t\texit(2);\n\t\t}\n\t\tsession.ShowEvents(showEvents);\n\n\t\tif (forceInteractive || (session.IsInteractive() && hasCommands))\n\t\t{\n\t\t\tsession.InteractiveInput();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(int i = optind; i < argc; ++i)\n\t\t\t{\n\t\t\t\tsession.ProcessCommand(argv[i]);\n\t\t\t}\n\t\t}\n\n\t\texit(0);\n\t}\n\tcatch (const std::exception &ex)\n\t{ error(\"error: \", ex.what()); exit(1); }\n}\n<commit_msg>added ctrl-c handler, interrupting current transaction<commit_after>\/*\n This file is part of Android File Transfer For Linux.\n Copyright (C) 2015-2018 Vladimir Menshakov\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 2.1 of the License,\n or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful, but\n 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 License\n along with this library; if not, write to the Free Software Foundation,\n Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\n\n#include <stdio.h>\n#include <stdexcept>\n\n#include <usb\/Context.h>\n\n#include <cli\/CommandLine.h>\n#include <cli\/Session.h>\n\n#include <mtp\/log.h>\n#include <mtp\/version.h>\n\n#include <atomic>\n\n#include <fcntl.h>\n#include <fcntl.h>\n#include <getopt.h>\n#include <unistd.h>\n#include <signal.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\nnamespace\n{\n\tstd::atomic<cli::Session *>\t\tgSession(nullptr);\n\n\tstatic void SigIntHandler(int)\n\t{\n\t\tcli::Session * session = gSession.load();\n\t\ttry\n\t\t{\n\t\t\tif (session)\n\t\t\t\tsession->Cancel();\n\t\t}\n\t\tcatch(const std::exception & ex)\n\t\t{\n\t\t\tmtp::debug(\"cancellation failed: \", ex.what());\n\t\t\texit(0);\n\t\t}\n\t}\n}\n\nint main(int argc, char **argv)\n{\n\tusing namespace mtp;\n\tbool forceInteractive = false;\n\tbool showHelp = false;\n\tbool showPrompt = true;\n\tbool showVersion = false;\n\tbool claimInterface = true;\n\tbool showEvents = false;\n\tconst char *fileInput = nullptr;\n\n\tif (!isatty(STDIN_FILENO))\n\t\tshowPrompt = false;\n\n\tstatic struct option long_options[] =\n\t{\n\t\t{\"verbose\",\t\t\tno_argument,\t\t0,\t'v' },\n\t\t{\"interactive\",\t\tno_argument,\t\t0,\t'i' },\n\t\t{\"batch\",\t\t\tno_argument,\t\t0,\t'b' },\n\t\t{\"events\",\t\t\tno_argument,\t\t0,\t'e' },\n\t\t{\"help\",\t\t\tno_argument,\t\t0,\t'h' },\n\t\t{\"version\",\t\t\tno_argument,\t\t0,\t'V' },\n\t\t{\"no-claim\",\t\tno_argument,\t\t0,\t'C' },\n\t\t{\"input-file\",\t\trequired_argument,\t0,\t'f' },\n\t\t{0,\t\t\t\t\t0,\t\t\t\t\t0,\t 0\t}\n\t};\n\n\tstruct sigaction newHandler = { };\n\tnewHandler.sa_handler = &SigIntHandler;\n\tnewHandler.sa_flags = SA_RESTART;\n\tif (sigaction(SIGINT, &newHandler, nullptr) != 0)\n\t\tperror(\"sigaction(SIGINT)\");\n\n\twhile(true)\n\t{\n\t\tint optionIndex = 0; \/\/index of matching option\n\t\tint c = getopt_long(argc, argv, \"ibehvVCf:\", long_options, &optionIndex);\n\t\tif (c == -1)\n\t\t\tbreak;\n\t\tswitch(c)\n\t\t{\n\t\tcase 'f':\n\t\t\tfileInput = optarg; \/\/falling back to batch processing here\n\t\tcase 'b':\n\t\t\tshowPrompt = false; \/\/no break here, prompt = false, interactive = true\n\t\tcase 'i':\n\t\t\tforceInteractive = true;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tg_debug = true;\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tshowVersion = true;\n\t\t\tbreak;\n\t\tcase 'C':\n\t\t\tclaimInterface = false;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\tshowEvents = true;\n\t\t\tbreak;\n\t\tcase '?':\n\t\tcase 'h':\n\t\tdefault:\n\t\t\tshowHelp = true;\n\t\t}\n\t}\n\tif (fileInput)\n\t{\n\t\tclose(STDIN_FILENO);\n\t\tint fd = open(fileInput, O_RDONLY);\n\t\tif (fd == -1)\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\texit(1);\n\t\t}\n\t\tif (fd != STDIN_FILENO)\n\t\t{\n\t\t\tfprintf(stderr, \"failed to reopen stdin\\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tif (showHelp)\n\t{\n\t\terror(\n\t\t\t\"usage:\\n\"\n\t\t\t\"-h\\t--help\\t\\tshow this help\\n\"\n\t\t\t\"-v\\t--verbose\\tshow debug output\\n\"\n\t\t\t\"-i\\t--interactive\\tforce interactive mode\\n\"\n\t\t\t\"-b\\t--batch\\t\\tbatch command processing\\n\"\n\t\t\t\"-e\\t--events\\t\\tallow event processing\\n\"\n\t\t\t\"-f\\t--input-file\\tuse file to read input commands\\n\"\n\t\t\t\"-C\\t--no-claim\\tno usb interface claim\\n\"\n\t\t\t\"-V\\t--version\\tshow version information\"\n\t\t\t);\n\t\texit(0);\n\t}\n\n\tif (showVersion)\n\t{\n\t\tprint(GetVersion());\n\t\texit(0);\n\t}\n\n\tauto mtp = Device::FindFirst(claimInterface);\n\tif (!mtp)\n\t{\n\t\terror(\"no mtp device found\");\n\t\texit(1);\n\t}\n\n\ttry\n\t{\n\t\tbool hasCommands = optind >= argc;\n\t\tcli::Session session(mtp, showPrompt);\n\t\tgSession.store(&session);\n\t\tif (!session.SetFirstStorage())\n\t\t{\n\t\t\terror(\"your device may be locked or does not have any storage available\");\n\t\t\texit(2);\n\t\t}\n\t\tsession.ShowEvents(showEvents);\n\n\t\tif (forceInteractive || (session.IsInteractive() && hasCommands))\n\t\t{\n\t\t\tsession.InteractiveInput();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(int i = optind; i < argc; ++i)\n\t\t\t{\n\t\t\t\tsession.ProcessCommand(argv[i]);\n\t\t\t}\n\t\t}\n\t\tgSession.store(nullptr);\n\n\t\texit(0);\n\t}\n\tcatch (const std::exception &ex)\n\t{ error(\"error: \", ex.what()); exit(1); }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"cnn\/exec.h\"\n\n#include \"cnn\/param-nodes.h\"\n\nusing namespace std;\n\nnamespace cnn {\n\nExecutionEngine::~ExecutionEngine() {}\n\nvoid SimpleExecutionEngine::invalidate() {\n last_node_evaluated = 0;\n}\n\nconst Tensor& SimpleExecutionEngine::forward() { \n const VariableIndex node_max_index = (VariableIndex)cg.nodes.size();\n return forward(node_max_index);\n}\n\nconst Tensor& SimpleExecutionEngine::forward(VariableIndex i) {\n invalidate();\n return incremental_forward(i);\n}\n\nconst Tensor& SimpleExecutionEngine::get_value(VariableIndex i) {\n assert(i < cg.nodes.size());\n if (i >= last_node_evaluated) {\n incremental_forward(i);\n }\n return nfxs[i];\n}\n\nconst Tensor& SimpleExecutionEngine::incremental_forward() {\n const VariableIndex node_max_index = (VariableIndex)cg.nodes.size();\n return incremental_forward(node_max_index);\n}\n\nconst Tensor& SimpleExecutionEngine::incremental_forward(VariableIndex node_max_index) {\n \/\/ free any old memory if this is a new HG\n if (last_node_evaluated == 0) fxs->free();\n\n assert(node_max_index > 0);\n nfxs.resize(node_max_index);\n if (node_max_index - last_node_evaluated == 0)\n return nfxs.back();\n\n \/\/vector<string> dummy(5, \"x\");\n vector<const Tensor*> xs(16);\n for (; last_node_evaluated < node_max_index; ++last_node_evaluated) {\n const Node* node = cg.nodes[last_node_evaluated];\n xs.resize(node->arity());\n unsigned ai = 0;\n for (VariableIndex arg : node->args) {\n xs[ai] = &nfxs[arg];\n ++ai;\n }\n nfxs[last_node_evaluated].d = node->dim;\n nfxs[last_node_evaluated].v = static_cast<float*>(fxs->allocate(node->dim.size() * sizeof(float)));\n if (nfxs[last_node_evaluated].v == nullptr) {\n cerr << \"out of memory\\n\";\n abort();\n }\n void* aux_mem = nullptr;\n size_t aux_size = node->aux_storage_size();\n if (aux_size) {\n aux_mem = fxs->allocate(aux_size);\n if (!aux_mem) {\n cerr << \"aux out of memory\\n\";\n abort();\n }\n }\n node->aux_mem = aux_mem;\n node->forward(xs, nfxs[last_node_evaluated]);\n }\n return nfxs.back();\n}\n\nvoid SimpleExecutionEngine::backward() {\n if (nfxs.back().d.size() != 1) {\n cerr << \"backward() called on non-scalar node.\\n\";\n abort();\n }\n\n const unsigned num_nodes = cg.nodes.size();\n ndEdfs.resize(num_nodes);\n dEdfs->free();\n for (unsigned i = 0; i < num_nodes; ++i) {\n const auto dim = nfxs[i].d;\n ndEdfs[i].d = dim;\n ndEdfs[i].v = static_cast<float*>(dEdfs->allocate(dim.size() * sizeof(float)));\n assert(ndEdfs[i].v);\n }\n dEdfs->zero_allocated_memory();\n \/\/ initialize dE\/dE = 1\n ndEdfs.back().v = kSCALAR_ONE;\n\n \/\/ here we find constant paths to avoid doing extra work\n vector<bool> needs_derivative(num_nodes, false);\n for (auto i : cg.parameter_nodes)\n needs_derivative[i] = true;\n\n for (unsigned ni = 0; ni < num_nodes; ++ni) {\n bool nd = needs_derivative[ni];\n for (auto arg : cg.nodes[ni]->args)\n nd |= needs_derivative[arg];\n needs_derivative[ni] = nd;\n }\n\n \/\/ loop in reverse topological order\n vector<const Tensor*> xs;\n for (int i = num_nodes - 1; i >= 0; --i) {\n const Node* node = cg.nodes[i];\n xs.resize(node->arity());\n unsigned ai = 0;\n for (VariableIndex arg : node->args) {\n xs[ai] = &nfxs[arg];\n ++ai;\n }\n ai = 0;\n for (VariableIndex arg : node->args) {\n if (needs_derivative[arg]) {\n node->backward(xs, nfxs[i], ndEdfs[i], ai, ndEdfs[arg]);\n }\n ++ai;\n }\n }\n\n \/\/ accumulate gradients into parameters\n \/\/ this is simpler than you might find in some other frameworks\n \/\/ since we assume parameters come into the graph as a \"function\"\n \/\/ that returns the current value of the parameters\n for (VariableIndex i : cg.parameter_nodes)\n static_cast<ParameterNodeBase*>(cg.nodes[i])->accumulate_grad(ndEdfs[i]);\n}\n\n} \/\/ namespace cnn\n<commit_msg>incremental_forward index fix<commit_after>#include \"cnn\/exec.h\"\n\n#include \"cnn\/param-nodes.h\"\n\nusing namespace std;\n\nnamespace cnn {\n\nExecutionEngine::~ExecutionEngine() {}\n\nvoid SimpleExecutionEngine::invalidate() {\n last_node_evaluated = 0;\n}\n\nconst Tensor& SimpleExecutionEngine::forward() { \n const VariableIndex node_max_index = (VariableIndex)cg.nodes.size();\n return forward(node_max_index);\n}\n\nconst Tensor& SimpleExecutionEngine::forward(VariableIndex i) {\n invalidate();\n return incremental_forward(i);\n}\n\nconst Tensor& SimpleExecutionEngine::get_value(VariableIndex i) {\n assert(i < cg.nodes.size());\n if (i >= last_node_evaluated) {\n \/\/ node_max_index is used as a sentinel here, so we should forward until (i+1) not i\n incremental_forward( (VariableIndex)((unsigned int)i+1) );\n }\n return nfxs[i];\n}\n\nconst Tensor& SimpleExecutionEngine::incremental_forward() {\n const VariableIndex node_max_index = (VariableIndex)cg.nodes.size();\n return incremental_forward(node_max_index);\n}\n\nconst Tensor& SimpleExecutionEngine::incremental_forward(VariableIndex node_max_index) {\n \/\/ free any old memory if this is a new HG\n if (last_node_evaluated == 0) fxs->free();\n\n assert(node_max_index > 0);\n nfxs.resize(node_max_index);\n if (node_max_index - last_node_evaluated == 0)\n return nfxs.back();\n\n \/\/vector<string> dummy(5, \"x\");\n vector<const Tensor*> xs(16);\n for (; last_node_evaluated < node_max_index; ++last_node_evaluated) {\n const Node* node = cg.nodes[last_node_evaluated];\n xs.resize(node->arity());\n unsigned ai = 0;\n for (VariableIndex arg : node->args) {\n xs[ai] = &nfxs[arg];\n ++ai;\n }\n nfxs[last_node_evaluated].d = node->dim;\n nfxs[last_node_evaluated].v = static_cast<float*>(fxs->allocate(node->dim.size() * sizeof(float)));\n if (nfxs[last_node_evaluated].v == nullptr) {\n cerr << \"out of memory\\n\";\n abort();\n }\n void* aux_mem = nullptr;\n size_t aux_size = node->aux_storage_size();\n if (aux_size) {\n aux_mem = fxs->allocate(aux_size);\n if (!aux_mem) {\n cerr << \"aux out of memory\\n\";\n abort();\n }\n }\n node->aux_mem = aux_mem;\n node->forward(xs, nfxs[last_node_evaluated]);\n }\n return nfxs.back();\n}\n\nvoid SimpleExecutionEngine::backward() {\n if (nfxs.back().d.size() != 1) {\n cerr << \"backward() called on non-scalar node.\\n\";\n abort();\n }\n\n const unsigned num_nodes = cg.nodes.size();\n ndEdfs.resize(num_nodes);\n dEdfs->free();\n for (unsigned i = 0; i < num_nodes; ++i) {\n const auto dim = nfxs[i].d;\n ndEdfs[i].d = dim;\n ndEdfs[i].v = static_cast<float*>(dEdfs->allocate(dim.size() * sizeof(float)));\n assert(ndEdfs[i].v);\n }\n dEdfs->zero_allocated_memory();\n \/\/ initialize dE\/dE = 1\n ndEdfs.back().v = kSCALAR_ONE;\n\n \/\/ here we find constant paths to avoid doing extra work\n vector<bool> needs_derivative(num_nodes, false);\n for (auto i : cg.parameter_nodes)\n needs_derivative[i] = true;\n\n for (unsigned ni = 0; ni < num_nodes; ++ni) {\n bool nd = needs_derivative[ni];\n for (auto arg : cg.nodes[ni]->args)\n nd |= needs_derivative[arg];\n needs_derivative[ni] = nd;\n }\n\n \/\/ loop in reverse topological order\n vector<const Tensor*> xs;\n for (int i = num_nodes - 1; i >= 0; --i) {\n const Node* node = cg.nodes[i];\n xs.resize(node->arity());\n unsigned ai = 0;\n for (VariableIndex arg : node->args) {\n xs[ai] = &nfxs[arg];\n ++ai;\n }\n ai = 0;\n for (VariableIndex arg : node->args) {\n if (needs_derivative[arg]) {\n node->backward(xs, nfxs[i], ndEdfs[i], ai, ndEdfs[arg]);\n }\n ++ai;\n }\n }\n\n \/\/ accumulate gradients into parameters\n \/\/ this is simpler than you might find in some other frameworks\n \/\/ since we assume parameters come into the graph as a \"function\"\n \/\/ that returns the current value of the parameters\n for (VariableIndex i : cg.parameter_nodes)\n static_cast<ParameterNodeBase*>(cg.nodes[i])->accumulate_grad(ndEdfs[i]);\n}\n\n} \/\/ namespace cnn\n<|endoftext|>"} {"text":"<commit_before><commit_msg>2a14f80a-2e4f-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before>9b2ab4ae-2e4e-11e5-9284-b827eb9e62be<commit_msg>9b2fedc0-2e4e-11e5-9284-b827eb9e62be<commit_after>9b2fedc0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>d92009f8-2e4e-11e5-9284-b827eb9e62be<commit_msg>d924fbc0-2e4e-11e5-9284-b827eb9e62be<commit_after>d924fbc0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before><commit_msg>aee983e0-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before>04ed6454-2e4f-11e5-9284-b827eb9e62be<commit_msg>04f26b0c-2e4f-11e5-9284-b827eb9e62be<commit_after>04f26b0c-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before><commit_msg>1c39ca32-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>615cdfa4-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>791d908a-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>0d7bd394-2e4f-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>3b2ba9be-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before>8433d18c-2e4d-11e5-9284-b827eb9e62be<commit_msg>8438c50c-2e4d-11e5-9284-b827eb9e62be<commit_after>8438c50c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before><commit_msg>7c665e38-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>30c26158-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>beb79712-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>75d308e2-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>efaa7ad2-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>bb0080c0-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>2a30d1da-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>1d27743a-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014, Xilinx Inc.\n\/\/ All rights reserved.\n\n#include <getopt.h>\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <cassert>\n#include <fstream>\n#include \"oclHelper.h\"\n#include \"pgm.h\"\n\nconst int FAST_THREADS_X = 16;\nconst int FAST_THREADS_Y = 16;\nconst int FAST_THREADS_NONMAX_X = 32;\nconst int FAST_THREADS_NONMAX_Y = 8;\n\n#define DIVUP(A, B) (((A) + (B) - 1) \/ (B))\n\n#define CL_INT_CHECK(err) do { \\\n if (err != CL_SUCCESS) { \\\n std::cout << \"OpenCL error (\" << err << \", \" << oclErrorCode(err) << \")\" << \\\n \" in file:line \" << __FILE__ << \":\" << __LINE__ << std::endl; \\\n return -1; \\\n } \\\n } while(0)\n\n#define CL_CHECK(fn) do { \\\n cl_int err = fn; \\\n if (err != CL_SUCCESS) { \\\n std::cout << \"OpenCL error (\" << err << \", \" << oclErrorCode(err) << \")\" << \\\n \" in file:line \" << __FILE__ << \":\" << __LINE__ << std::endl; \\\n return -1; \\\n } \\\n } while(0)\n\nclass Timer {\n time_t mTimeStart;\n time_t mTimeEnd;\npublic:\n Timer() {\n mTimeStart = std::time(0);\n mTimeEnd = mTimeStart;\n }\n double stop() {\n mTimeEnd = std::time(0);\n return std::difftime(mTimeEnd, mTimeStart);\n }\n void reset() {\n mTimeStart = time(0);\n mTimeEnd = mTimeStart;\n }\n};\n\ntypedef std::pair<int, int> Position;\n\nconst static struct option long_options[] = {\n {\"device\", required_argument, 0, 'd'},\n {\"kernel\", required_argument, 0, 'k'},\n {\"img_file\", required_argument, 0, 'f'},\n {\"iteration\", optional_argument, 0, 'i'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"help\", no_argument, 0, 'h'},\n {0, 0, 0, 0}\n};\n\nstatic void printHelp()\n{\n std::cout << \"usage: %s <options>\\n\";\n std::cout << \" -d <cpu|gpu|acc>\\n\";\n std::cout << \" -k <kernel_file> \\n\";\n std::cout << \" -f <img_file>\\n\";\n std::cout << \" -i <iteration_count>\\n\";\n std::cout << \" -t <fast_thr>\\n\";\n std::cout << \" -v\\n\";\n std::cout << \" -h\\n\";\n}\n\nint runTest(std::string imgFile, std::vector<int> fpgaX, std::vector<int> fpgaY, std::vector<int> fpgaScore)\n{\n int extIndex = imgFile.find_last_of(\".\");\n std::string testFile = imgFile.substr(0, extIndex) + std::string(\".test\");\n std::ifstream testStream;\n testStream.open(testFile.c_str());\n\n size_t nsamples = 0;\n testStream >> nsamples;\n\n if (nsamples != fpgaX.size())\n return 1;\n\n int* goldX = new int[nsamples];\n int* goldY = new int[nsamples];\n int* goldScore = new int[nsamples];\n\n for (size_t i = 0; i < nsamples; i++) {\n testStream >> goldX[i] >> goldY[i] >> goldScore[i];\n }\n\n for (size_t i = 0; i < nsamples; i++) {\n if (fpgaX[i] != goldX[i] || fpgaY[i] != goldY[i] || fpgaScore[i] != goldScore[i])\n return 1;\n }\n\n delete[] goldX;\n delete[] goldY;\n delete[] goldScore;\n\n testStream.close();\n\n return 0;\n}\n\nstatic int runOpenCL(std::string imgFile, std::string kernelFile, cl_device_type deviceType,\n int iteration, int fast_thr, bool verbose, double delay)\n{\n oclHardware hardware = getOclHardware(deviceType);\n if (!hardware.mQueue) {\n return -1;\n }\n std::cout << \"verbose: \" << verbose << std::endl;\n\n oclSoftware software;\n std::memset(&software, 0, sizeof(oclSoftware));\n std::strcpy(software.mKernelName, \"locate_features\");\n std::strcpy(software.mFileName, kernelFile.c_str());\n\n getOclSoftware(software, hardware);\n\n int* h_img;\n size_t w, h;\n readPGM(&h_img, &w, &h, imgFile);\n size_t img_el = w*h;\n\n int wi = (int)w, hi = (int)h;\n\n cl_int err = 0;\n\n cl_mem d_img = clCreateBuffer(hardware.mContext, CL_MEM_READ_ONLY, img_el * sizeof(int), NULL, &err);\n CL_INT_CHECK(err);\n cl_mem d_score = clCreateBuffer(hardware.mContext, CL_MEM_READ_WRITE, img_el * sizeof(int), NULL, &err);\n CL_INT_CHECK(err);\n\n CL_CHECK(clEnqueueWriteBuffer(hardware.mQueue, d_img, CL_TRUE, 0,\n img_el * sizeof(int), h_img, 0, 0, 0));\n\n int arg = 0;\n\n const unsigned edge = 3;\n const unsigned local_el = (FAST_THREADS_X + edge*2) * (FAST_THREADS_Y + edge*2);\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(cl_mem), &d_img));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &wi));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &hi));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(cl_mem), &d_score));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &fast_thr));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(unsigned), &edge));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, local_el * sizeof(int), NULL));\n\n size_t localSize[2] = { FAST_THREADS_X, FAST_THREADS_Y };\n\n unsigned groups_x = DIVUP(w, localSize[0]);\n unsigned groups_y = DIVUP(h, localSize[1]);\n size_t globalSize[2] = { localSize[0] * groups_x, localSize[1] * groups_y };\n\n if (verbose) {\n std::cout << \"Global size = (\" << globalSize[0] << \",\" << globalSize[1] << \",1)\" << std::endl;\n std::cout << \"Local size = (\" << localSize[0] << \",\" << localSize[1] << \",1)\" << std::endl;\n }\n\n std::vector<int> h_score_init(w * h, 0);\n int* h_score = new int[img_el];\n\n std::vector<int> x, y, score;\n\n Timer timer;\n for(int i = 0; i < iteration; i++)\n {\n \/\/ Here we start measurings host time for kernel execution\n CL_CHECK(clEnqueueWriteBuffer(hardware.mQueue, d_score, CL_TRUE, 0,\n img_el * sizeof(int), &h_score_init[0], 0, 0, 0));\n\n CL_CHECK(clEnqueueNDRangeKernel(hardware.mQueue, software.mKernel, 2, 0,\n globalSize, localSize, 0, 0, 0));\n\n CL_CHECK(clFinish(hardware.mQueue));\n\n CL_CHECK(clEnqueueReadBuffer(hardware.mQueue, d_score, CL_TRUE, 0,\n img_el * sizeof(int), h_score, 0, 0, 0));\n\n if (i == iteration-1) {\n for (size_t j = 0; j < h; j++) {\n for (size_t k = 0; k < w; k++) {\n size_t idx = j*w + k;\n int s = h_score[idx];\n if (s != 0) {\n x.push_back(k);\n y.push_back(j);\n score.push_back(s);\n\n if (verbose)\n std::cout << \"(\" << k << \", \" << j << \"): \" << s << std::endl;\n }\n }\n }\n }\n }\n delay = timer.stop();\n\n int testRes = runTest(imgFile, x, y, score);\n\n delete[] h_img;\n delete[] h_score;\n clReleaseMemObject(d_img);\n clReleaseMemObject(d_score);\n\n return testRes;\n}\n\n\nint main(int argc, char** argv)\n{\n cl_device_type deviceType = CL_DEVICE_TYPE_ACCELERATOR;;\n int option_index = 0;\n std::string kernelFile(\"fast.cl\");\n std::string imgFile(\".\/data\/square.pgm\");\n int iteration = 1;\n int fast_thr = 20;\n bool verbose = false;\n \/\/ Commandline\n int c;\n while ((c = getopt_long(argc, argv, \"d:k:f:i:t:vh\", long_options, &option_index)) != -1)\n {\n switch (c)\n {\n case 0:\n if (long_options[option_index].flag != 0)\n break;\n case 'd':\n if (strcmp(optarg, \"gpu\") == 0)\n deviceType = CL_DEVICE_TYPE_GPU;\n else if (strcmp(optarg, \"cpu\") == 0)\n deviceType = CL_DEVICE_TYPE_CPU;\n else if (strcmp(optarg, \"soft\") == 0)\n deviceType = CL_DEVICE_TYPE_DEFAULT;\n else if (strcmp(optarg, \"acc\") != 0) {\n std::cout << \"Incorrect platform specified\\n\";\n printHelp();\n return -1;\n }\n break;\n case 'k':\n kernelFile = optarg;\n break;\n case 'f':\n imgFile = optarg;\n break;\n case 'i':\n iteration = atoi(optarg);\n break;\n case 't':\n fast_thr = atoi(optarg);\n break;\n case 'h':\n printHelp();\n return 0;\n case 'v':\n verbose = true;\n break;\n default:\n printHelp();\n return 1;\n }\n }\n\n double delay = 0;\n if ((deviceType != CL_DEVICE_TYPE_DEFAULT) && runOpenCL(imgFile, kernelFile, deviceType,\n iteration, fast_thr, verbose, delay)) {\n std::cout << \"FAILED TEST\\n\";\n return 1;\n }\n \/\/runOpenCL(imgFile, kernelFile, deviceType, iteration, fast_thr, verbose, delay);\n\n std::cout << \"OpenCL total time: \" << delay << \" sec\\n\";\n std::cout << \"OpenCL average time per iteration: \" << delay\/iteration << \" sec\\n\";\n std::cout << \"PASSED TEST\\n\";\n return 0;\n}\n<commit_msg>Moved OpenCL helper macros to oclHelper.h<commit_after>\/\/ Copyright 2014, Xilinx Inc.\n\/\/ All rights reserved.\n\n#include <getopt.h>\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <cassert>\n#include <fstream>\n#include \"oclHelper.h\"\n#include \"pgm.h\"\n\nconst int FAST_THREADS_X = 16;\nconst int FAST_THREADS_Y = 16;\nconst int FAST_THREADS_NONMAX_X = 32;\nconst int FAST_THREADS_NONMAX_Y = 8;\n\nclass Timer {\n time_t mTimeStart;\n time_t mTimeEnd;\npublic:\n Timer() {\n mTimeStart = std::time(0);\n mTimeEnd = mTimeStart;\n }\n double stop() {\n mTimeEnd = std::time(0);\n return std::difftime(mTimeEnd, mTimeStart);\n }\n void reset() {\n mTimeStart = time(0);\n mTimeEnd = mTimeStart;\n }\n};\n\ntypedef std::pair<int, int> Position;\n\nconst static struct option long_options[] = {\n {\"device\", required_argument, 0, 'd'},\n {\"kernel\", required_argument, 0, 'k'},\n {\"img_file\", required_argument, 0, 'f'},\n {\"iteration\", optional_argument, 0, 'i'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"help\", no_argument, 0, 'h'},\n {0, 0, 0, 0}\n};\n\nstatic void printHelp()\n{\n std::cout << \"usage: %s <options>\\n\";\n std::cout << \" -d <cpu|gpu|acc>\\n\";\n std::cout << \" -k <kernel_file> \\n\";\n std::cout << \" -f <img_file>\\n\";\n std::cout << \" -i <iteration_count>\\n\";\n std::cout << \" -t <fast_thr>\\n\";\n std::cout << \" -v\\n\";\n std::cout << \" -h\\n\";\n}\n\nint runTest(std::string imgFile, std::vector<int> fpgaX, std::vector<int> fpgaY, std::vector<int> fpgaScore)\n{\n int extIndex = imgFile.find_last_of(\".\");\n std::string testFile = imgFile.substr(0, extIndex) + std::string(\".test\");\n std::ifstream testStream;\n testStream.open(testFile.c_str());\n\n size_t nsamples = 0;\n testStream >> nsamples;\n\n if (nsamples != fpgaX.size())\n return 1;\n\n int* goldX = new int[nsamples];\n int* goldY = new int[nsamples];\n int* goldScore = new int[nsamples];\n\n for (size_t i = 0; i < nsamples; i++) {\n testStream >> goldX[i] >> goldY[i] >> goldScore[i];\n }\n\n for (size_t i = 0; i < nsamples; i++) {\n if (fpgaX[i] != goldX[i] || fpgaY[i] != goldY[i] || fpgaScore[i] != goldScore[i])\n return 1;\n }\n\n delete[] goldX;\n delete[] goldY;\n delete[] goldScore;\n\n testStream.close();\n\n return 0;\n}\n\nstatic int runOpenCL(std::string imgFile, std::string kernelFile, cl_device_type deviceType,\n int iteration, int fast_thr, bool verbose, double delay)\n{\n oclHardware hardware = getOclHardware(deviceType);\n if (!hardware.mQueue) {\n return -1;\n }\n std::cout << \"verbose: \" << verbose << std::endl;\n\n oclSoftware software;\n std::memset(&software, 0, sizeof(oclSoftware));\n std::strcpy(software.mKernelName, \"locate_features\");\n std::strcpy(software.mFileName, kernelFile.c_str());\n\n getOclSoftware(software, hardware);\n\n int* h_img;\n size_t w, h;\n readPGM(&h_img, &w, &h, imgFile);\n size_t img_el = w*h;\n\n int wi = (int)w, hi = (int)h;\n\n cl_int err = 0;\n\n cl_mem d_img = clCreateBuffer(hardware.mContext, CL_MEM_READ_ONLY, img_el * sizeof(int), NULL, &err);\n CL_INT_CHECK(err);\n cl_mem d_score = clCreateBuffer(hardware.mContext, CL_MEM_READ_WRITE, img_el * sizeof(int), NULL, &err);\n CL_INT_CHECK(err);\n\n CL_CHECK(clEnqueueWriteBuffer(hardware.mQueue, d_img, CL_TRUE, 0,\n img_el * sizeof(int), h_img, 0, 0, 0));\n\n int arg = 0;\n\n const unsigned edge = 3;\n const unsigned local_el = (FAST_THREADS_X + edge*2) * (FAST_THREADS_Y + edge*2);\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(cl_mem), &d_img));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &wi));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &hi));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(cl_mem), &d_score));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &fast_thr));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(unsigned), &edge));\n CL_CHECK(clSetKernelArg(software.mKernel, arg++, local_el * sizeof(int), NULL));\n\n size_t localSize[2] = { FAST_THREADS_X, FAST_THREADS_Y };\n\n unsigned groups_x = DIVUP(w, localSize[0]);\n unsigned groups_y = DIVUP(h, localSize[1]);\n size_t globalSize[2] = { localSize[0] * groups_x, localSize[1] * groups_y };\n\n if (verbose) {\n std::cout << \"Global size = (\" << globalSize[0] << \",\" << globalSize[1] << \",1)\" << std::endl;\n std::cout << \"Local size = (\" << localSize[0] << \",\" << localSize[1] << \",1)\" << std::endl;\n }\n\n std::vector<int> h_score_init(w * h, 0);\n int* h_score = new int[img_el];\n\n std::vector<int> x, y, score;\n\n Timer timer;\n for(int i = 0; i < iteration; i++)\n {\n \/\/ Here we start measurings host time for kernel execution\n CL_CHECK(clEnqueueWriteBuffer(hardware.mQueue, d_score, CL_TRUE, 0,\n img_el * sizeof(int), &h_score_init[0], 0, 0, 0));\n\n CL_CHECK(clEnqueueNDRangeKernel(hardware.mQueue, software.mKernel, 2, 0,\n globalSize, localSize, 0, 0, 0));\n\n CL_CHECK(clFinish(hardware.mQueue));\n\n CL_CHECK(clEnqueueReadBuffer(hardware.mQueue, d_score, CL_TRUE, 0,\n img_el * sizeof(int), h_score, 0, 0, 0));\n\n if (i == iteration-1) {\n for (size_t j = 0; j < h; j++) {\n for (size_t k = 0; k < w; k++) {\n size_t idx = j*w + k;\n int s = h_score[idx];\n if (s != 0) {\n x.push_back(k);\n y.push_back(j);\n score.push_back(s);\n\n if (verbose)\n std::cout << \"(\" << k << \", \" << j << \"): \" << s << std::endl;\n }\n }\n }\n }\n }\n delay = timer.stop();\n\n int testRes = runTest(imgFile, x, y, score);\n\n delete[] h_img;\n delete[] h_score;\n clReleaseMemObject(d_img);\n clReleaseMemObject(d_score);\n\n return testRes;\n}\n\n\nint main(int argc, char** argv)\n{\n cl_device_type deviceType = CL_DEVICE_TYPE_ACCELERATOR;;\n int option_index = 0;\n std::string kernelFile(\"fast.cl\");\n std::string imgFile(\".\/data\/square.pgm\");\n int iteration = 1;\n int fast_thr = 20;\n bool verbose = false;\n \/\/ Commandline\n int c;\n while ((c = getopt_long(argc, argv, \"d:k:f:i:t:vh\", long_options, &option_index)) != -1)\n {\n switch (c)\n {\n case 0:\n if (long_options[option_index].flag != 0)\n break;\n case 'd':\n if (strcmp(optarg, \"gpu\") == 0)\n deviceType = CL_DEVICE_TYPE_GPU;\n else if (strcmp(optarg, \"cpu\") == 0)\n deviceType = CL_DEVICE_TYPE_CPU;\n else if (strcmp(optarg, \"soft\") == 0)\n deviceType = CL_DEVICE_TYPE_DEFAULT;\n else if (strcmp(optarg, \"acc\") != 0) {\n std::cout << \"Incorrect platform specified\\n\";\n printHelp();\n return -1;\n }\n break;\n case 'k':\n kernelFile = optarg;\n break;\n case 'f':\n imgFile = optarg;\n break;\n case 'i':\n iteration = atoi(optarg);\n break;\n case 't':\n fast_thr = atoi(optarg);\n break;\n case 'h':\n printHelp();\n return 0;\n case 'v':\n verbose = true;\n break;\n default:\n printHelp();\n return 1;\n }\n }\n\n double delay = 0;\n if ((deviceType != CL_DEVICE_TYPE_DEFAULT) && runOpenCL(imgFile, kernelFile, deviceType,\n iteration, fast_thr, verbose, delay)) {\n std::cout << \"FAILED TEST\\n\";\n return 1;\n }\n \/\/runOpenCL(imgFile, kernelFile, deviceType, iteration, fast_thr, verbose, delay);\n\n std::cout << \"OpenCL total time: \" << delay << \" sec\\n\";\n std::cout << \"OpenCL average time per iteration: \" << delay\/iteration << \" sec\\n\";\n std::cout << \"PASSED TEST\\n\";\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AccessibleComponentBase.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 16:35:55 $\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_svx.hxx\"\n\n\n#include <svx\/AccessibleComponentBase.hxx>\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_SELECTION_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleSelection.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_\n#include <com\/sun\/star\/container\/XChild.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_\n#include <com\/sun\/star\/drawing\/XShapes.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_\n#include <com\/sun\/star\/drawing\/XShapeDescriptor.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/IndexOutOfBoundsException.hpp>\n#endif\n#ifndef _TOOLS_COLOR_HXX\n#include <tools\/color.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::accessibility;\n\nnamespace accessibility {\n\n\/\/===== internal ============================================================\n\nAccessibleComponentBase::AccessibleComponentBase (void)\n{\n}\n\n\n\n\nAccessibleComponentBase::~AccessibleComponentBase (void)\n{\n}\n\n\n\n\n\/\/===== XAccessibleComponent ================================================\n\nsal_Bool SAL_CALL AccessibleComponentBase::containsPoint (\n const ::com::sun::star::awt::Point& aPoint)\n throw (::com::sun::star::uno::RuntimeException)\n{\n awt::Size aSize (getSize());\n return (aPoint.X >= 0)\n && (aPoint.X < aSize.Width)\n && (aPoint.Y >= 0)\n && (aPoint.Y < aSize.Height);\n}\n\n\n\n\nuno::Reference<XAccessible > SAL_CALL\n AccessibleComponentBase::getAccessibleAtPoint (\n const awt::Point& \/*aPoint*\/)\n throw (uno::RuntimeException)\n{\n return uno::Reference<XAccessible>();\n}\n\n\n\n\nawt::Rectangle SAL_CALL AccessibleComponentBase::getBounds (void)\n throw (uno::RuntimeException)\n{\n return awt::Rectangle();\n}\n\n\n\n\nawt::Point SAL_CALL AccessibleComponentBase::getLocation (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n awt::Rectangle aBBox (getBounds());\n return awt::Point (aBBox.X, aBBox.Y);\n}\n\n\n\n\nawt::Point SAL_CALL AccessibleComponentBase::getLocationOnScreen (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return awt::Point();\n}\n\n\n\n\n::com::sun::star::awt::Size SAL_CALL AccessibleComponentBase::getSize (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n awt::Rectangle aBBox (getBounds());\n return awt::Size (aBBox.Width, aBBox.Height);\n}\n\n\n\n\nvoid SAL_CALL AccessibleComponentBase::addFocusListener (\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XFocusListener >& \/*xListener*\/)\n throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ Ignored\n}\n\n\n\n\nvoid SAL_CALL AccessibleComponentBase::removeFocusListener (const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XFocusListener >& \/*xListener*\/ )\n throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ Ignored\n}\n\n\n\n\nvoid SAL_CALL AccessibleComponentBase::grabFocus (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n uno::Reference<XAccessibleContext> xContext (this, uno::UNO_QUERY);\n uno::Reference<XAccessibleSelection> xSelection (\n xContext->getAccessibleParent(), uno::UNO_QUERY);\n if (xSelection.is())\n {\n \/\/ Do a single selection on this object.\n xSelection->clearAccessibleSelection();\n xSelection->selectAccessibleChild (xContext->getAccessibleIndexInParent());\n }\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleComponentBase::getForeground (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return Color(COL_BLACK).GetColor();\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleComponentBase::getBackground (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return Color(COL_WHITE).GetColor();\n}\n\n\n\n\n\/\/===== XAccessibleExtendedComponent ========================================\n\n::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL\n AccessibleComponentBase::getFont (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return uno::Reference<awt::XFont>();\n}\n\n\n\n\n::rtl::OUString SAL_CALL AccessibleComponentBase::getTitledBorderText (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return ::rtl::OUString::createFromAscii (\"\");\n}\n\n\n\n\n::rtl::OUString SAL_CALL AccessibleComponentBase::getToolTipText (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return ::rtl::OUString::createFromAscii (\"\");\n}\n\n\n\n\n\/\/===== XTypeProvider ===================================================\n\nuno::Sequence<uno::Type> SAL_CALL\n AccessibleComponentBase::getTypes (void)\n throw (uno::RuntimeException)\n{\n \/\/ Get list of types from the context base implementation...\n uno::Sequence<uno::Type> aTypeList (2);\n \/\/ ...and add the additional type for the component.\n const uno::Type aComponentType =\n ::getCppuType((const uno::Reference<XAccessibleComponent>*)0);\n const uno::Type aExtendedComponentType =\n ::getCppuType((const uno::Reference<XAccessibleExtendedComponent>*)0);\n aTypeList[0] = aComponentType;\n aTypeList[1] = aExtendedComponentType;\n\n return aTypeList;\n}\n\n\n} \/\/ end of namespace accessibility\n<commit_msg>INTEGRATION: CWS changefileheader (1.16.368); FILE MERGED 2008\/04\/01 15:50:06 thb 1.16.368.3: #i85898# Stripping all external header guards 2008\/04\/01 12:47:57 thb 1.16.368.2: #i85898# Stripping all external header guards 2008\/03\/31 14:19:11 rt 1.16.368.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: AccessibleComponentBase.cxx,v $\n * $Revision: 1.17 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_svx.hxx\"\n\n\n#include <svx\/AccessibleComponentBase.hxx>\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_SELECTION_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleSelection.hpp>\n#endif\n#include <com\/sun\/star\/container\/XChild.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/drawing\/XShapes.hpp>\n#include <com\/sun\/star\/drawing\/XShapeDescriptor.hpp>\n#include <com\/sun\/star\/lang\/IndexOutOfBoundsException.hpp>\n#include <tools\/color.hxx>\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::accessibility;\n\nnamespace accessibility {\n\n\/\/===== internal ============================================================\n\nAccessibleComponentBase::AccessibleComponentBase (void)\n{\n}\n\n\n\n\nAccessibleComponentBase::~AccessibleComponentBase (void)\n{\n}\n\n\n\n\n\/\/===== XAccessibleComponent ================================================\n\nsal_Bool SAL_CALL AccessibleComponentBase::containsPoint (\n const ::com::sun::star::awt::Point& aPoint)\n throw (::com::sun::star::uno::RuntimeException)\n{\n awt::Size aSize (getSize());\n return (aPoint.X >= 0)\n && (aPoint.X < aSize.Width)\n && (aPoint.Y >= 0)\n && (aPoint.Y < aSize.Height);\n}\n\n\n\n\nuno::Reference<XAccessible > SAL_CALL\n AccessibleComponentBase::getAccessibleAtPoint (\n const awt::Point& \/*aPoint*\/)\n throw (uno::RuntimeException)\n{\n return uno::Reference<XAccessible>();\n}\n\n\n\n\nawt::Rectangle SAL_CALL AccessibleComponentBase::getBounds (void)\n throw (uno::RuntimeException)\n{\n return awt::Rectangle();\n}\n\n\n\n\nawt::Point SAL_CALL AccessibleComponentBase::getLocation (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n awt::Rectangle aBBox (getBounds());\n return awt::Point (aBBox.X, aBBox.Y);\n}\n\n\n\n\nawt::Point SAL_CALL AccessibleComponentBase::getLocationOnScreen (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return awt::Point();\n}\n\n\n\n\n::com::sun::star::awt::Size SAL_CALL AccessibleComponentBase::getSize (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n awt::Rectangle aBBox (getBounds());\n return awt::Size (aBBox.Width, aBBox.Height);\n}\n\n\n\n\nvoid SAL_CALL AccessibleComponentBase::addFocusListener (\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XFocusListener >& \/*xListener*\/)\n throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ Ignored\n}\n\n\n\n\nvoid SAL_CALL AccessibleComponentBase::removeFocusListener (const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XFocusListener >& \/*xListener*\/ )\n throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ Ignored\n}\n\n\n\n\nvoid SAL_CALL AccessibleComponentBase::grabFocus (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n uno::Reference<XAccessibleContext> xContext (this, uno::UNO_QUERY);\n uno::Reference<XAccessibleSelection> xSelection (\n xContext->getAccessibleParent(), uno::UNO_QUERY);\n if (xSelection.is())\n {\n \/\/ Do a single selection on this object.\n xSelection->clearAccessibleSelection();\n xSelection->selectAccessibleChild (xContext->getAccessibleIndexInParent());\n }\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleComponentBase::getForeground (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return Color(COL_BLACK).GetColor();\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleComponentBase::getBackground (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return Color(COL_WHITE).GetColor();\n}\n\n\n\n\n\/\/===== XAccessibleExtendedComponent ========================================\n\n::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL\n AccessibleComponentBase::getFont (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return uno::Reference<awt::XFont>();\n}\n\n\n\n\n::rtl::OUString SAL_CALL AccessibleComponentBase::getTitledBorderText (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return ::rtl::OUString::createFromAscii (\"\");\n}\n\n\n\n\n::rtl::OUString SAL_CALL AccessibleComponentBase::getToolTipText (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return ::rtl::OUString::createFromAscii (\"\");\n}\n\n\n\n\n\/\/===== XTypeProvider ===================================================\n\nuno::Sequence<uno::Type> SAL_CALL\n AccessibleComponentBase::getTypes (void)\n throw (uno::RuntimeException)\n{\n \/\/ Get list of types from the context base implementation...\n uno::Sequence<uno::Type> aTypeList (2);\n \/\/ ...and add the additional type for the component.\n const uno::Type aComponentType =\n ::getCppuType((const uno::Reference<XAccessibleComponent>*)0);\n const uno::Type aExtendedComponentType =\n ::getCppuType((const uno::Reference<XAccessibleExtendedComponent>*)0);\n aTypeList[0] = aComponentType;\n aTypeList[1] = aExtendedComponentType;\n\n return aTypeList;\n}\n\n\n} \/\/ end of namespace accessibility\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/system_wrappers\/interface\/data_log.h\"\n\n#include <cstdio>\n\n#include \"gtest\/gtest.h\"\n\nusing ::webrtc::DataLog;\n\nconst char* kDataLogFileName = \"table_1.txt\";\n\nvoid PerformLogging(std::string table_name) {\n \/\/ Simulate normal DataTable logging behavior using this table name.\n ASSERT_EQ(0, DataLog::AddTable(table_name));\n ASSERT_EQ(0, DataLog::AddColumn(table_name, \"test\", 1));\n for (int i = 0; i < 10; ++i) {\n \/\/ TODO(kjellander): Check InsertCell result when the DataLog dummy is\n \/\/ fixed.\n DataLog::InsertCell(table_name, \"test\", static_cast<double>(i));\n ASSERT_EQ(0, DataLog::NextRow(table_name));\n }\n}\n\n\/\/ Simple test to verify DataLog is still working when the GYP variable\n\/\/ enable_data_logging==0 (the default case).\nTEST(TestDataLogDisabled, VerifyLoggingWorks) {\n ASSERT_EQ(0, DataLog::CreateLog());\n \/\/ Generate a table_name name and assure it's an empty string\n \/\/ (dummy behavior).\n std::string table_name = DataLog::Combine(\"table\", 1);\n ASSERT_EQ(\"\", table_name);\n PerformLogging(table_name);\n DataLog::ReturnLog();\n}\n\nTEST(TestDataLogDisabled, EnsureNoFileIsWritten) {\n \/\/ Remove any previous data files on disk:\n std::remove(kDataLogFileName);\n ASSERT_EQ(0, DataLog::CreateLog());\n \/\/ Don't use the table name we would get from Combine on a disabled DataLog.\n \/\/ Use \"table_1\" instead (which is what an enabled DataLog would give us).\n PerformLogging(\"table_1\");\n DataLog::ReturnLog();\n \/\/ Verify no data log file have been written:\n ASSERT_EQ(NULL, fopen(kDataLogFileName, \"r\"));\n}\n<commit_msg>Tool found: pass by value when pass by reference is better in system wrapper unit test.<commit_after>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/system_wrappers\/interface\/data_log.h\"\n\n#include <cstdio>\n\n#include \"gtest\/gtest.h\"\n\nusing ::webrtc::DataLog;\n\nconst char* kDataLogFileName = \"table_1.txt\";\n\nvoid PerformLogging(const std::string& table_name) {\n \/\/ Simulate normal DataTable logging behavior using this table name.\n ASSERT_EQ(0, DataLog::AddTable(table_name));\n ASSERT_EQ(0, DataLog::AddColumn(table_name, \"test\", 1));\n for (int i = 0; i < 10; ++i) {\n \/\/ TODO(kjellander): Check InsertCell result when the DataLog dummy is\n \/\/ fixed.\n DataLog::InsertCell(table_name, \"test\", static_cast<double>(i));\n ASSERT_EQ(0, DataLog::NextRow(table_name));\n }\n}\n\n\/\/ Simple test to verify DataLog is still working when the GYP variable\n\/\/ enable_data_logging==0 (the default case).\nTEST(TestDataLogDisabled, VerifyLoggingWorks) {\n ASSERT_EQ(0, DataLog::CreateLog());\n \/\/ Generate a table_name name and assure it's an empty string\n \/\/ (dummy behavior).\n std::string table_name = DataLog::Combine(\"table\", 1);\n ASSERT_EQ(\"\", table_name);\n PerformLogging(table_name);\n DataLog::ReturnLog();\n}\n\nTEST(TestDataLogDisabled, EnsureNoFileIsWritten) {\n \/\/ Remove any previous data files on disk:\n std::remove(kDataLogFileName);\n ASSERT_EQ(0, DataLog::CreateLog());\n \/\/ Don't use the table name we would get from Combine on a disabled DataLog.\n \/\/ Use \"table_1\" instead (which is what an enabled DataLog would give us).\n PerformLogging(\"table_1\");\n DataLog::ReturnLog();\n \/\/ Verify no data log file have been written:\n ASSERT_EQ(NULL, fopen(kDataLogFileName, \"r\"));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"controller_node.h\"\n#include <std_msgs\/Bool.h>\n#include <std_srvs\/Empty.h>\n#include <iostream>\n\nController::Controller() :\n speedX_(1.05f), speedY_(1.05f), speedZ_(1.05f), speedYaw_(1.01f), goal_reached_(true),\n search_for_plane_(false), stick_to_plane_(false), sticking_distance_(0.5f), correction_speed_(0.5f) {\n\n std::cout << \"Controller node started...\" << std::endl;\n\n \/\/ get Ros parameters and set variables\n nh_.param(\"speedForward\", speedX_, speedX_);\n nh_.param(\"speedRight\", speedY_, speedY_);\n nh_.param(\"speedUp\", speedZ_, speedZ_);\n nh_.param(\"speedYaw\", speedYaw_, speedYaw_);\n\n \/\/ set subscriber and publisher\n sub_joy_ = nh_.subscribe<sensor_msgs::Joy>(\"joy\", 10, &Controller::callback, this);\n sub_mocap_pose_ = nh_.subscribe<geometry_msgs::PoseWithCovarianceStamped>(\"vrpn_client\/estimated_transform\", 10, &Controller::setMocapPose, this);\n sub_plane_tf_ = nh_.subscribe<geometry_msgs::TransformStamped>(\"plane\", 10, &Controller::processPlaneMsg, this);\n pub_pose_ = nh_.advertise<geometry_msgs::PoseStamped>(\"command\/pose\", 1);\n pub_stickToSurface_ = nh_.advertise<std_msgs::Bool>(\"stickToSurface\", 10);\n\n std::cout << \"speeds: \" << speedX_ << \" \" << speedY_ << \" \" << speedZ_ << \" \" << speedYaw_ << std::endl;\n\n \/\/ identity rotation matrix as quaternion\n tf::Quaternion q;\n q.setRPY(0,0,0);\n\n \/\/ init mocap_tf\n mavToWorld_.setOrigin( tf::Vector3(0,0,0) );\n mavToWorld_.setRotation(q);\n\n \/\/ init transform\n transform_.setOrigin( tf::Vector3(0,0,0) );\n transform_.setRotation(q);\n\n \/\/ TBD if we should be able to change this via launch file\n \/\/ init hover transform\n hover_goal_tf_.setOrigin( tf::Vector3(0,0,1) );\n hover_goal_tf_.setRotation(q);\n\n \/\/ init plane_tf\n plane_tf_.setOrigin(tf::Vector3(2,0,0));\n tf::Quaternion plane_q;\n plane_q.setRPY(0,0,-M_PI\/4.f);\n plane_tf_.setRotation(plane_q);\n\n \/\/ init snap_goal_tf\n snap_goal_tf_.setOrigin(tf::Vector3(0,0,0));\n snap_goal_tf_.setRotation(q);\n\n \/\/ set sensor offset tf by getting the relative offset\n\/\/ tf::TransformListener listener;\n\/\/ try {\n\/\/ listener.lookupTransform(\"euroc_hex\/ground_truth\", \"euroc_hex\/vi_sensor\/ground_truth\", ros::Time(0), sensor_offset_tf_);\n\/\/ } catch (tf::TransformException ex) {\n\/\/ ROS_ERROR(\"%s\",ex.what());\n\/\/ }\n\n \/\/ hack\n tf::Transform mavToWorld;\n mavToWorld.setOrigin(tf::Vector3(0,0,0.117));\n mavToWorld.setRotation(tf::Quaternion(0,0,0,1));\n tf::Transform sensorToWorld;\n sensorToWorld.setOrigin(tf::Vector3(0.133,0,0.0605));\n sensorToWorld.setRotation(tf::Quaternion(0,0.17365,0,0.98481));\n sensorToMav_ = mavToWorld.inverse() * sensorToWorld;\n}\n\nvoid Controller::setMocapPose(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) {\n mavToWorld_.setOrigin( tf::Vector3(msg->pose.pose.position.x, msg->pose.pose.position.y, msg->pose.pose.position.z) );\n mavToWorld_.setRotation( tf::Quaternion(msg->pose.pose.orientation.x, msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, msg->pose.pose.orientation.w) );\n\n if(!goal_reached_) {\n tf::Transform diff = mavToWorld_.inverse() * hover_goal_tf_;\n if(diff.getOrigin().length() < 0.05f) {\n goal_reached_ = true;\n }\n else {\n transform_ = diff;\n }\n }\n\n \/\/ world transform\n tf::Transform curr_transform;\n \/\/\/ stick to plane\n if(stick_to_plane_) {\n testPlanes();\n tf::Vector3 diff = snap_goal_tf_.getOrigin() - mavToWorld_.getOrigin();\n curr_transform.setOrigin(mavToWorld_.getOrigin() + correction_speed_*diff);\n curr_transform.setRotation(snap_goal_tf_.getRotation());\n } else {\n curr_transform = mavToWorld_ * transform_;\n }\n\n \/\/ convert tf into pose and publish the pose\n tf::Vector3 desired_pos = curr_transform.getOrigin();\n tf::Quaternion desired_rot = curr_transform.getRotation();\n\n geometry_msgs::PoseStamped pose;\n \/\/ set header\n pose.header.stamp = ros::Time::now();\n pose.header.frame_id = \"world\";\n \/\/ set pose\n pose.pose.position.x = desired_pos.x();\n pose.pose.position.y = desired_pos.y();\n pose.pose.position.z = desired_pos.z();\n pose.pose.orientation.x = desired_rot.x();\n pose.pose.orientation.y = desired_rot.y();\n pose.pose.orientation.z = desired_rot.z();\n pose.pose.orientation.w = desired_rot.w();\n pub_pose_.publish(pose);\n\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(curr_transform, ros::Time::now(), \"world\", \"controller\") );\n}\n\nvoid Controller::callback(const sensor_msgs::Joy::ConstPtr& joy) {\n \/\/\/ translation from controller axis\n float jx = speedX_ * joy->axes[PS3_AXIS_STICK_RIGHT_UPWARDS];\n float jy = speedY_ * joy->axes[PS3_AXIS_STICK_RIGHT_LEFTWARDS];\n float jz = speedZ_ * joy->axes[PS3_AXIS_STICK_LEFT_UPWARDS];\n \/\/ yaw from axis\n float jr = speedYaw_ * joy->axes[PS3_AXIS_STICK_LEFT_LEFTWARDS];\n\n \/\/ save only the latest relative transform in global variable transform_\n transform_.setOrigin( tf::Vector3(jx,jy,jz) );\n tf::Quaternion q;\n q.setRPY(0,0,jr);\n transform_.setRotation(q);\n\n \/\/\/ buttons\n \/\/ tell PcMeshBuilder to search for a plane\n if(joy->buttons[PS3_BUTTON_REAR_RIGHT_1]) {\n search_for_plane_ = true;\n std_msgs::Bool sticking;\n sticking.data = search_for_plane_;\n pub_stickToSurface_.publish(sticking);\n }\n if(joy->buttons[PS3_BUTTON_REAR_LEFT_1]) {\n search_for_plane_ = false;\n std_msgs::Bool sticking;\n sticking.data = search_for_plane_;\n pub_stickToSurface_.publish(sticking);\n }\n \/\/ enable or disable sticking to the plane\n if(joy->buttons[PS3_BUTTON_REAR_RIGHT_2]) {\n stick_to_plane_ = true;\n }\n if(joy->buttons[PS3_BUTTON_REAR_LEFT_2]) {\n stick_to_plane_ = false;\n }\n \/\/ sticking distance\n if(joy->buttons[PS3_BUTTON_CROSS_UP] && sticking_distance_ > 0.05f) {\n sticking_distance_ -= 0.005f;\n }\n if(joy->buttons[PS3_BUTTON_CROSS_DOWN]) {\n sticking_distance_ += 0.005f;\n }\n}\n\nvoid Controller::takeoffAndHover() {\n std_srvs::Empty::Request request;\n std_srvs::Empty::Response response;\n ros::service::call(\"euroc2\/takeoff\", request, response);\n\n tf::Vector3 desired_pos = tf::Vector3( mavToWorld_.getOrigin().x(), mavToWorld_.getOrigin().y(), 1.0f);\n tf::Quaternion desired_rot = mavToWorld_.getRotation();\n\n hover_goal_tf_.setOrigin(desired_pos);\n hover_goal_tf_.setRotation(desired_rot);\n}\n\n\/\/ TODO add constant offset transform for camera\n\/\/ TODO improve handedness correction\nvoid Controller::processPlaneMsg(const geometry_msgs::TransformStamped::ConstPtr& msg) {\n \/\/ realtive plane transform to mav\n \/\/planeToCam = plane_tf\n plane_tf_.setOrigin( tf::Vector3(msg->transform.translation.x, msg->transform.translation.y, msg->transform.translation.z) );\n plane_tf_.setRotation( tf::Quaternion(msg->transform.rotation.x, msg->transform.rotation.y, msg->transform.rotation.z, msg->transform.rotation.w) );\n\n \/\/plane_tf_.setOrigin( tf::Vector3(0,0,0) ); \/\/TODO rm debug\n \/\/plane_tf_.setRotation( tf::Quaternion::getIdentity() );\n\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"world\", \"plane_Cam_World\") );\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"euroc_hex\/vi_sensor\/ground_truth\", \"plane_Cam\") );\n\n \/\/ plane forward is z should be x, hack to fix it for testing\n \/\/CamToSensor\n tf::Quaternion correction_rot;\n\/\/ correction_rot.setRPY(M_PI\/2.0,-M_PI\/2.0,0);\n correction_rot.setRPY(M_PI\/2.0,-M_PI\/2.0,0);\n plane_tf_.setOrigin(tf::Matrix3x3(correction_rot)*plane_tf_.getOrigin());\n plane_tf_.setRotation(correction_rot*plane_tf_.getRotation());\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"euroc_hex\/vi_sensor\/ground_truth\", \"plane_Sensor\") );\n\n \/\/ correct the relative camera offset\n \/\/ planeToMav = plane_tf CORRECT\n plane_tf_ = sensorToMav_*plane_tf_;\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"euroc_hex\/ground_truth\", \"plane_Mav\") );\n\n \/\/ transform into global coordinates\n \/\/ planeToWorld = plane_tf_ CORRECT\n plane_tf_ = mavToWorld_*plane_tf_;\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"world\", \"plane_Global\") );\n}\n\n\/\/ TODO remove hacks enhance methods\nvoid Controller::testPlanes() {\n \/\/\/\/ mav\n \/\/ predicted mav tf\n tf::Transform mav_tf = mavToWorld_ * transform_;\n\n \/\/ Eigen conversions\n Eigen::Vector3f mav_pos = Eigen::Vector3f( mav_tf.getOrigin().x(),\n mav_tf.getOrigin().y(),\n mav_tf.getOrigin().z());\n\n \/\/\/\/ plane\n Eigen::Vector3f plane_pos = Eigen::Vector3f( plane_tf_.getOrigin().x(), plane_tf_.getOrigin().y(), plane_tf_.getOrigin().z() );\n tf::Quaternion plane_q = plane_tf_.getRotation();\n Eigen::Quaternionf plane_rot = Eigen::Quaternionf(plane_q.w(),plane_q.x(),plane_q.y(),plane_q.z());\n\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"world\", \"normal\") );\n\n \/\/\/\/ calculations\n Eigen::Vector3f normal = plane_rot*forward;\n normal.normalize();\n\/\/ normal = -normal;\n \/\/ determine if mav is in front or behind plane normal, take current pos to avoid switching of sides by wrong predictions in mav_tf\n Eigen::Vector3f curr_pos = Eigen::Vector3f(mavToWorld_.getOrigin().x(), mavToWorld_.getOrigin().y(), mavToWorld_.getOrigin().z());\n\n int facing = normal.dot(curr_pos-plane_pos) >= 0 ? 1 : -1;\n \/\/ calculate projected position of the mav onto the plane\n Eigen::Vector3f proj_pos = mav_pos + (facing*sticking_distance_ - normal.dot(mav_pos-plane_pos))*normal;\n\n \/\/ another hack\n\/\/ tf::Quaternion correction_rot;\n\/\/ correction_rot.setRPY(0,0,M_PI);\n\n \/\/ set snapping goal tf\n snap_goal_tf_.setOrigin( tf::Vector3(proj_pos.x(), proj_pos.y(), proj_pos.z()) );\n\/\/ snap_goal_tf_.setRotation(correction_rot*plane_tf_.getRotation());\n snap_goal_tf_.setRotation(plane_tf_.getRotation());\n}\n\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"te_joy_controller\");\n Controller rc;\n ros::spin();\n}\n<commit_msg>Found a strange bug with rotations. WIP<commit_after>#include \"controller_node.h\"\n#include <std_msgs\/Bool.h>\n#include <std_srvs\/Empty.h>\n#include <iostream>\n\nController::Controller() :\n speedX_(1.05f), speedY_(1.05f), speedZ_(1.05f), speedYaw_(1.01f), goal_reached_(true),\n search_for_plane_(false), stick_to_plane_(false), sticking_distance_(0.5f), correction_speed_(0.5f) {\n\n std::cout << \"Controller node started...\" << std::endl;\n\n \/\/ get Ros parameters and set variables\n nh_.param(\"speedForward\", speedX_, speedX_);\n nh_.param(\"speedRight\", speedY_, speedY_);\n nh_.param(\"speedUp\", speedZ_, speedZ_);\n nh_.param(\"speedYaw\", speedYaw_, speedYaw_);\n\n \/\/ set subscriber and publisher\n sub_joy_ = nh_.subscribe<sensor_msgs::Joy>(\"joy\", 10, &Controller::callback, this);\n sub_mocap_pose_ = nh_.subscribe<geometry_msgs::PoseWithCovarianceStamped>(\"vrpn_client\/estimated_transform\", 10, &Controller::setMocapPose, this);\n sub_plane_tf_ = nh_.subscribe<geometry_msgs::TransformStamped>(\"plane\", 10, &Controller::processPlaneMsg, this);\n pub_pose_ = nh_.advertise<geometry_msgs::PoseStamped>(\"command\/pose\", 1);\n pub_stickToSurface_ = nh_.advertise<std_msgs::Bool>(\"stickToSurface\", 10);\n\n std::cout << \"speeds: \" << speedX_ << \" \" << speedY_ << \" \" << speedZ_ << \" \" << speedYaw_ << std::endl;\n\n \/\/ identity rotation matrix as quaternion\n tf::Quaternion q;\n q.setRPY(0,0,0);\n\n \/\/ init mocap_tf\n mavToWorld_.setOrigin( tf::Vector3(0,0,0) );\n mavToWorld_.setRotation(q);\n\n \/\/ init transform\n transform_.setOrigin( tf::Vector3(0,0,0) );\n transform_.setRotation(q);\n\n \/\/ TBD if we should be able to change this via launch file\n \/\/ init hover transform\n hover_goal_tf_.setOrigin( tf::Vector3(0,0,1) );\n hover_goal_tf_.setRotation(q);\n\n \/\/ init plane_tf\n plane_tf_.setOrigin(tf::Vector3(2,0,0));\n tf::Quaternion plane_q;\n plane_q.setRPY(0,0,-M_PI\/4.f);\n plane_tf_.setRotation(plane_q);\n\n \/\/ init snap_goal_tf\n snap_goal_tf_.setOrigin(tf::Vector3(0,0,0));\n snap_goal_tf_.setRotation(q);\n\n \/\/ set sensor offset tf by getting the relative offset\n\/\/ tf::TransformListener listener;\n\/\/ try {\n\/\/ listener.lookupTransform(\"euroc_hex\/ground_truth\", \"euroc_hex\/vi_sensor\/ground_truth\", ros::Time(0), sensor_offset_tf_);\n\/\/ } catch (tf::TransformException ex) {\n\/\/ ROS_ERROR(\"%s\",ex.what());\n\/\/ }\n\n \/\/ hack\n tf::Transform mavToWorld;\n mavToWorld.setOrigin(tf::Vector3(0,0,0.117));\n mavToWorld.setRotation(tf::Quaternion(0,0,0,1));\n tf::Transform sensorToWorld;\n sensorToWorld.setOrigin(tf::Vector3(0.133,0,0.0605));\n sensorToWorld.setRotation(tf::Quaternion(0,0.17365,0,0.98481));\n sensorToMav_ = mavToWorld.inverse() * sensorToWorld;\n}\n\nvoid Controller::setMocapPose(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) {\n mavToWorld_.setOrigin( tf::Vector3(msg->pose.pose.position.x, msg->pose.pose.position.y, msg->pose.pose.position.z) );\n mavToWorld_.setRotation( tf::Quaternion(msg->pose.pose.orientation.x, msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, msg->pose.pose.orientation.w) );\n\n if(!goal_reached_) {\n tf::Transform diff = mavToWorld_.inverse() * hover_goal_tf_;\n if(diff.getOrigin().length() < 0.05f) {\n goal_reached_ = true;\n }\n else {\n transform_ = diff;\n }\n }\n\n \/\/ world transform\n tf::Transform curr_transform;\n \/\/\/ stick to plane\n if(stick_to_plane_) {\n testPlanes();\n tf::Vector3 diff = snap_goal_tf_.getOrigin() - mavToWorld_.getOrigin();\n curr_transform.setOrigin(mavToWorld_.getOrigin() + correction_speed_*diff);\n curr_transform.setRotation(snap_goal_tf_.getRotation());\n } else {\n curr_transform = mavToWorld_ * transform_;\n }\n\n \/\/ convert tf into pose and publish the pose\n tf::Vector3 desired_pos = curr_transform.getOrigin();\n tf::Quaternion desired_rot = curr_transform.getRotation();\n\n geometry_msgs::PoseStamped pose;\n \/\/ set header\n pose.header.stamp = ros::Time::now();\n pose.header.frame_id = \"world\";\n \/\/ set pose\n pose.pose.position.x = desired_pos.x();\n pose.pose.position.y = desired_pos.y();\n pose.pose.position.z = desired_pos.z();\n pose.pose.orientation.x = desired_rot.x();\n pose.pose.orientation.y = desired_rot.y();\n pose.pose.orientation.z = desired_rot.z();\n pose.pose.orientation.w = desired_rot.w();\n pub_pose_.publish(pose);\n\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(curr_transform, ros::Time::now(), \"world\", \"controller\") );\n}\n\nvoid Controller::callback(const sensor_msgs::Joy::ConstPtr& joy) {\n \/\/\/ translation from controller axis\n float jx = speedX_ * joy->axes[PS3_AXIS_STICK_RIGHT_UPWARDS];\n float jy = speedY_ * joy->axes[PS3_AXIS_STICK_RIGHT_LEFTWARDS];\n float jz = speedZ_ * joy->axes[PS3_AXIS_STICK_LEFT_UPWARDS];\n \/\/ yaw from axis\n float jr = speedYaw_ * joy->axes[PS3_AXIS_STICK_LEFT_LEFTWARDS];\n\n \/\/ save only the latest relative transform in global variable transform_\n transform_.setOrigin( tf::Vector3(jx,jy,jz) );\n tf::Quaternion q;\n q.setRPY(0,0,jr);\n transform_.setRotation(q);\n\n \/\/\/ buttons\n \/\/ tell PcMeshBuilder to search for a plane\n if(joy->buttons[PS3_BUTTON_REAR_RIGHT_1]) {\n search_for_plane_ = true;\n std_msgs::Bool sticking;\n sticking.data = search_for_plane_;\n pub_stickToSurface_.publish(sticking);\n }\n if(joy->buttons[PS3_BUTTON_REAR_LEFT_1]) {\n search_for_plane_ = false;\n std_msgs::Bool sticking;\n sticking.data = search_for_plane_;\n pub_stickToSurface_.publish(sticking);\n }\n \/\/ enable or disable sticking to the plane\n if(joy->buttons[PS3_BUTTON_REAR_RIGHT_2]) {\n stick_to_plane_ = true;\n }\n if(joy->buttons[PS3_BUTTON_REAR_LEFT_2]) {\n stick_to_plane_ = false;\n }\n \/\/ sticking distance\n if(joy->buttons[PS3_BUTTON_CROSS_UP] && sticking_distance_ > 0.05f) {\n sticking_distance_ -= 0.005f;\n }\n if(joy->buttons[PS3_BUTTON_CROSS_DOWN]) {\n sticking_distance_ += 0.005f;\n }\n}\n\nvoid Controller::takeoffAndHover() {\n std_srvs::Empty::Request request;\n std_srvs::Empty::Response response;\n ros::service::call(\"euroc2\/takeoff\", request, response);\n\n tf::Vector3 desired_pos = tf::Vector3( mavToWorld_.getOrigin().x(), mavToWorld_.getOrigin().y(), 1.0f);\n tf::Quaternion desired_rot = mavToWorld_.getRotation();\n\n hover_goal_tf_.setOrigin(desired_pos);\n hover_goal_tf_.setRotation(desired_rot);\n}\n\n\/\/ TODO add constant offset transform for camera\n\/\/ TODO improve handedness correction\nvoid Controller::processPlaneMsg(const geometry_msgs::TransformStamped::ConstPtr& msg) {\n \/\/ realtive plane transform to mav\n \/\/planeToCam = plane_tf\n plane_tf_.setOrigin( tf::Vector3(msg->transform.translation.x, msg->transform.translation.y, msg->transform.translation.z) );\n plane_tf_.setRotation( tf::Quaternion(msg->transform.rotation.x, msg->transform.rotation.y, msg->transform.rotation.z, msg->transform.rotation.w) );\n\n \/\/plane_tf_.setOrigin( tf::Vector3(0,0,0) ); \/\/TODO rm debug\n \/\/plane_tf_.setRotation( tf::Quaternion::getIdentity() );\n\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"world\", \"plane_Cam_World\") );\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"euroc_hex\/vi_sensor\/ground_truth\", \"plane_Cam\") );\n\n \/\/ plane forward is z should be x, hack to fix it for testing\n \/\/CamToSensor\n\/\/ tf::Matrix3x3 tmp_rot = tf::Matrix3x3(0,-1,0,0,0,-1,1,0,0);\n tf::Quaternion q1; q1.setRPY(0,M_PI\/2.0,0);\n tf::Quaternion q2; q2.setRPY(-M_PI\/2.0,0,0);\n tf::Quaternion correction_rot = q2*q1;\n plane_tf_.setOrigin( tf::Matrix3x3(correction_rot)*plane_tf_.getOrigin() );\n plane_tf_.setRotation( plane_tf_.getRotation() );\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"euroc_hex\/vi_sensor\/ground_truth\", \"plane_Sensor\") );\n\n \/\/\/ testing \/\/\/\n\/\/\/\/ tf::Quaternion q1; q1.setRPY(0,-M_PI\/2.0,0);\n\/\/\/\/ tf::Quaternion q2; q2.setRPY(M_PI\/2.0,0,0);\n\/\/\/\/ tf::Quaternion q3; q3.setRPY(0,0,M_PI);\n\/\/ tf::Quaternion q1; q1.setRPY(0,M_PI\/2.0,0);\n\/\/ tf::Quaternion q2; q2.setRPY(-M_PI\/2.0,0,0);\n\/\/ tf::Quaternion q3; q3.setRPY(0,0,0);\n\/\/ correction_rot = q3*q2*q1;\n\/\/ tf::Transform test0;\n\/\/ test0.setOrigin(tf::Vector3(-0.5,-0.5,1));\n\/\/ test0.setRotation(tf::Quaternion::getIdentity());\n\/\/ br_tf_.sendTransform( tf::StampedTransform(test0, ros::Time::now(), \"world\", \"test0\") );\n\/\/ tf::Transform test1;\n\/\/ test1.setOrigin( tf::Matrix3x3(correction_rot)*test0.getOrigin() );\n\/\/ test1.setRotation( test0.getRotation() );\n\/\/ br_tf_.sendTransform( tf::StampedTransform(test1, ros::Time::now(), \"world\", \"test1\") );\n \/\/\/ end of testing section \/\/\/\n\n \/\/ correct the relative camera offset\n \/\/ planeToMav = plane_tf CORRECT\n plane_tf_ = sensorToMav_.inverse()*plane_tf_;\n\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"world\", \"plane_Mav_World\") );\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"euroc_hex\/ground_truth\", \"plane_Mav\") );\n\n \/\/ transform into global coordinates\n \/\/ planeToWorld = plane_tf_ CORRECT\n plane_tf_ = mavToWorld_*plane_tf_;\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"world\", \"plane_Global\") );\n}\n\n\/\/ TODO remove hacks enhance methods\nvoid Controller::testPlanes() {\n \/\/\/\/ mav\n \/\/ predicted mav tf\n tf::Transform mav_tf = mavToWorld_ * transform_;\n\n \/\/ Eigen conversions\n Eigen::Vector3f mav_pos = Eigen::Vector3f( mav_tf.getOrigin().x(),\n mav_tf.getOrigin().y(),\n mav_tf.getOrigin().z());\n\n \/\/\/\/ plane\n Eigen::Vector3f plane_pos = Eigen::Vector3f( plane_tf_.getOrigin().x(), plane_tf_.getOrigin().y(), plane_tf_.getOrigin().z() );\n tf::Quaternion plane_q = plane_tf_.getRotation();\n Eigen::Quaternionf plane_rot = Eigen::Quaternionf(plane_q.w(),plane_q.x(),plane_q.y(),plane_q.z());\n\n \/\/ rviz debug\n br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), \"world\", \"normal\") );\n\n \/\/\/\/ calculations\n Eigen::Vector3f normal = plane_rot*forward;\n normal.normalize();\n\/\/ normal = -normal;\n \/\/ determine if mav is in front or behind plane normal, take current pos to avoid switching of sides by wrong predictions in mav_tf\n Eigen::Vector3f curr_pos = Eigen::Vector3f(mavToWorld_.getOrigin().x(), mavToWorld_.getOrigin().y(), mavToWorld_.getOrigin().z());\n\n int facing = normal.dot(curr_pos-plane_pos) >= 0 ? 1 : -1;\n \/\/ calculate projected position of the mav onto the plane\n Eigen::Vector3f proj_pos = mav_pos + (facing*sticking_distance_ - normal.dot(mav_pos-plane_pos))*normal;\n\n \/\/ another hack\n\/\/ tf::Quaternion correction_rot;\n\/\/ correction_rot.setRPY(0,0,M_PI);\n\n \/\/ set snapping goal tf\n snap_goal_tf_.setOrigin( tf::Vector3(proj_pos.x(), proj_pos.y(), proj_pos.z()) );\n\/\/ snap_goal_tf_.setRotation(correction_rot*plane_tf_.getRotation());\n snap_goal_tf_.setRotation(plane_tf_.getRotation());\n}\n\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"te_joy_controller\");\n Controller rc;\n ros::spin();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/pm\/p10_pm.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p10_pm.H\n\/\/\/ @brief Common header for Power Manangement procedures\n\/\/\/\n\n\/\/ *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Amit Tendolkar <amit.tendolkar@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : HS\n\n#ifndef _PM_H_\n#define _PM_H_\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Macro Defintions\n\/\/------------------------------------------------------------------------------\n\nextern const char* PM_FLOW_MODE_NAME[];\n\n#define PM_FLOW_MODE_NAME \\\n { \\\n \"PM_HALT\", \\\n \"PM_START\", \\\n \"PM_SETUP\", \\\n \"PM_SETUP_PIB\", \\\n \"PM_SETUP_ALL\", \\\n \"PM_RESET_SOFT\", \\\n \"PM_INIT_SOFT\", \\\n \"PM_INIT_SPECIAL\" \\\n }\n\n#define PM_MODE_NAME_VAR PM_FLOW_MODE_NAME[] = PM_FLOW_MODE_NAME\n\n#define PM_MODE_NAME(_mi_mode)( \\\n PM_FLOW_MODE_NAME[_mi_mode-1] \\\n )\n\n\n\n\n\/\/ Incase the attribute does not a have a value previously assigned,\n\/\/ assign the user given default value\n#define GETATTR_DEFAULT(_i_attr, _i_attr_name, _i_target, _i_value, _i_defVal){\\\n FAPI_ATTR_GET(_i_attr, _i_target, _i_value); \\\n if (!_i_value) \\\n { \\\n FAPI_DBG(\"Attribute %s set to default = 0x%x\",_i_attr_name,_i_defVal); \\\n _i_value = _i_defVal;\\\n } \\\n FAPI_INF(\"Value read from attribute %s = 0x%x\", _i_attr_name,_i_value);\\\n }\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/------------------------------------------------------------------------------\nnamespace pm\n{\n\nenum PM_FLOW_MODE\n{\n PM_HALT = 0x1,\n PM_START = 0x2,\n PM_SETUP = 0x3,\n PM_SETUP_PIB = 0x4,\n PM_SETUP_ALL = 0x5,\n PM_RESET_SOFT = 0x6,\n PM_INIT_SOFT = 0x7,\n PM_INIT_SPECIAL = 0x8,\n};\n\n} \/\/ end of namespace pm\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Functions\n\/\/------------------------------------------------------------------------------\n\n\/\/ Byte-reverse a 32-bit integer if on a little-endian machine\n\nuint32_t\nrevle32(uint32_t i_x)\n{\n uint32_t rx;\n\n#ifndef _BIG_ENDIAN\n uint8_t* pix = (uint8_t*)(&i_x);\n uint8_t* prx = (uint8_t*)(&rx);\n\n prx[0] = pix[3];\n prx[1] = pix[2];\n prx[2] = pix[1];\n prx[3] = pix[0];\n#else\n rx = i_x;\n#endif\n\n return rx;\n}\n\n\n\/\/ Byte-reverse a 64-bit integer if on a little-endian machine\n\nuint64_t\nrevle64(const uint64_t i_x)\n{\n uint64_t rx;\n\n#ifndef _BIG_ENDIAN\n uint8_t* pix = (uint8_t*)(&i_x);\n uint8_t* prx = (uint8_t*)(&rx);\n\n prx[0] = pix[7];\n prx[1] = pix[6];\n prx[2] = pix[5];\n prx[3] = pix[4];\n prx[4] = pix[3];\n prx[5] = pix[2];\n prx[6] = pix[1];\n prx[7] = pix[0];\n#else\n rx = i_x;\n#endif\n\n return rx;\n}\n\n\n#endif \/\/ _PM_H_\n<commit_msg>PM: P10 OCB Hardware Procedures (with new OCI headers)<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/pm\/p10_pm.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p10_pm.H\n\/\/\/ @brief Common header for Power Manangement procedures\n\/\/\/\n\n\/\/ *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Amit Tendolkar <amit.tendolkar@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : HS\n\n#ifndef _PM_H_\n#define _PM_H_\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Macro Defintions\n\/\/------------------------------------------------------------------------------\n\nextern const char* PM_FLOW_MODE_NAME[];\n\n#define PM_FLOW_MODE_NAME \\\n { \\\n \"PM_HALT\", \\\n \"PM_START\", \\\n \"PM_SETUP\", \\\n \"PM_SETUP_PIB\", \\\n \"PM_SETUP_ALL\", \\\n \"PM_RESET_SOFT\", \\\n \"PM_INIT_SOFT\", \\\n \"PM_INIT_SPECIAL\" \\\n }\n\n#define PM_MODE_NAME_VAR PM_FLOW_MODE_NAME[] = PM_FLOW_MODE_NAME\n\n#define PM_MODE_NAME(_mi_mode)( \\\n PM_FLOW_MODE_NAME[_mi_mode-1] \\\n )\n\n\n\n\n\/\/ Incase the attribute does not a have a value previously assigned,\n\/\/ assign the user given default value\n#define GETATTR_DEFAULT(_i_attr, _i_attr_name, _i_target, _i_value, _i_defVal){\\\n FAPI_ATTR_GET(_i_attr, _i_target, _i_value); \\\n if (!_i_value) \\\n { \\\n FAPI_DBG(\"Attribute %s set to default = 0x%x\",_i_attr_name,_i_defVal); \\\n _i_value = _i_defVal;\\\n } \\\n FAPI_INF(\"Value read from attribute %s = 0x%x\", _i_attr_name,_i_value);\\\n }\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/------------------------------------------------------------------------------\nnamespace pm\n{\n\nenum PM_FLOW_MODE\n{\n PM_HALT = 0x1,\n PM_START = 0x2,\n PM_SETUP = 0x3,\n PM_SETUP_PIB = 0x4,\n PM_SETUP_ALL = 0x5,\n PM_RESET_SOFT = 0x6,\n PM_INIT_SOFT = 0x7,\n PM_INIT_SPECIAL = 0x8,\n};\n\n} \/\/ end of namespace pm\n\n\n#endif \/\/ _PM_H_\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/error_info_defs.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2011,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file error_info_defs.H\n\/\/\/ @brief Defines to support the Error Information class\n\/\/\/\n\n#ifndef FAPI2_ERRORINFO_DEFS_H_\n#define FAPI2_ERRORINFO_DEFS_H_\n\n#include <stdint.h>\n#include <target.H>\n\n#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)\n #include <variable_buffer.H>\n #include <utility>\n#endif\nnamespace fapi2\n{\n\n\/\/\/\n\/\/\/ @brief Type to hold the ffdc data to be sent to hostboot\n\/\/\/\n\/\/\/ Note: Typical data sent seems to be register\/addresss info\n\/\/\/ rather than use extra space converting stuff just\n\/\/\/ send a uint64 always\n\/\/\/\nstruct sbeFfdc_t\n{\n uint32_t size;\n uint64_t data;\n} __attribute__((packed));\n\n\/\/ 10 entries limits the size of SbeFfdcData_t to 128 bytes\nenum\n{\n MAX_SBE_FFDC_ENTRIES = 10\n};\n\n\/\/ Data type for SBE ffdc buffer sent through fifo\ntypedef struct\n{\n uint32_t fapiRc; \/\/ Return code from failure\n uint32_t ffdcLength; \/\/ length of Fapi FFDC data (in bytes)\n struct sbeFfdc_t ffdcData[MAX_SBE_FFDC_ENTRIES]; \/\/ fapi FFDC data\n} SbeFfdcData_t; \/\/ 128 bytes\n\n\/\/\/\n\/\/\/ @brief Type to hold the ffdc element in the ffdc class\n\/\/\/ Needed so that the size can be squirled away before the\n\/\/\/ macro is called.\n\/\/\/\nstruct ffdc_struct\n{\n const void* ptr;\n size_t size;\n};\n\n\nclass ffdc_t\n{\n public:\n ffdc_t(void)\n {}\n\n void operator=(const ffdc_t& i )\n {\n iv_value.ptr = i.ptr();\n iv_value.size = i.size();\n }\n\n operator const void* () const\n {\n return iv_value.ptr;\n }\n operator uint8_t() const\n {\n return *(reinterpret_cast<const uint8_t*>(iv_value.ptr));\n }\n\n size_t size(void) const\n {\n return iv_value.size;\n }\n size_t& size(void)\n {\n return iv_value.size;\n }\n\n const void* ptr(void) const\n {\n return iv_value.ptr;\n }\n const void*& ptr(void)\n {\n return iv_value.ptr;\n }\n\n private:\n struct ffdc_struct iv_value = {}; \/\/init to zero\n};\n\n\/\/\/\n\/\/\/ @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a\n\/\/\/ special type that cannot simply be memcopied\nenum ErrorInfoFfdcSize\n{\n EI_FFDC_SIZE_BUF = 0xffff, \/\/ fapi2::buffer<T>\n EI_FFDC_SIZE_TARGET = 0xfffe, \/\/ fapi2::Target\n EI_FFDC_SIZE_VBUF = 0xfffd, \/\/ fapi2::variable_buffer\n EI_FFDC_MAX_SIZE = 0x1000, \/\/ Limit regular FFDC capture to 4kb\n};\n\n\/\/\/\n\/\/\/ @brief Enumeration of error log severity.\n\/\/\/\nenum errlSeverity_t\n{\n FAPI2_ERRL_SEV_UNDEFINED = 0x00, \/\/\/ Used internally by ffdc mechanism\n FAPI2_ERRL_SEV_RECOVERED = 0x10, \/\/\/ Not seen by customer\n FAPI2_ERRL_SEV_PREDICTIVE = 0x20, \/\/\/ Error recovered but customer will see\n FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 \/\/\/ Unrecoverable, general\n};\n\n\/\/\/\n\/\/\/ @brief Enumeration of ErrorInfo types\n\/\/\/\nenum ErrorInfoType\n{\n EI_TYPE_FFDC = 0,\n EI_TYPE_HW_CALLOUT = 1,\n EI_TYPE_PROCEDURE_CALLOUT = 2,\n EI_TYPE_BUS_CALLOUT = 3,\n EI_TYPE_CDG = 4, \/\/ Target Callout\/Deconfig\/GARD\n EI_TYPE_CHILDREN_CDG = 5, \/\/ Children Callout\/Deconfig\/GARD\n EI_TYPE_COLLECT_TRACE = 6,\n EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1,\n};\n\n#ifndef MINIMUM_FFDC\n\/\/\/\n\/\/\/ @enum HwCallout\n\/\/\/\n\/\/\/ This enumeration defines the possible Hardware Callouts that are not\n\/\/\/ represented by fapi2::Targets\n\/\/\/\n\/\/\/ Note that platform code may depend on the enum values starting at 0 and\n\/\/\/ incrementing in order to efficiently convert to a platform callout value\n\/\/\/ so do not reorder without consulting all platforms\n\/\/\/\nnamespace HwCallouts\n{\nenum HwCallout\n{\n \/\/ Where indicated, a HW Callout in FAPI Error XML must include a\n \/\/ reference target that is used to identify the HW. e.g. for\n \/\/ TOD_CLOCK, the proc chip that the clock is attached to must be\n \/\/ specified\n TOD_CLOCK = 0, \/\/ Include proc-chip ref (or child chiplet)\n MEM_REF_CLOCK = 1, \/\/ Include membuf-chip ref (or child chiplet)\n PROC_REF_CLOCK = 2, \/\/ Include proc-chip ref (or child chiplet)\n PCI_REF_CLOCK = 3, \/\/ Include proc-chip ref (or child chiplet)\n FLASH_CONTROLLER_PART = 4,\n PNOR_PART = 5,\n SBE_SEEPROM_PART = 6,\n VPD_PART = 7,\n LPC_SLAVE_PART = 8,\n GPIO_EXPANDER_PART = 9,\n SPIVID_SLAVE_PART = 10,\n};\n}\n\n\/\/\/\n\/\/\/ @enum ProcedureCallout\n\/\/\/\n\/\/\/ This enumeration defines the possible Procedure Callouts\n\/\/\/ These instruct the customer\/customer-engineer what to do\n\/\/\/\n\/\/\/ Note that platform code may depend on the enum values starting at 0 and\n\/\/\/ incrementing in order to efficiently convert to a platform callout value\n\/\/\/ so do not reorder without consulting all platforms\n\/\/\/\nnamespace ProcedureCallouts\n{\nenum ProcedureCallout\n{\n CODE = 0, \/\/ Code problem\n LVL_SUPPORT = 1, \/\/ Call next level of support\n MEMORY_PLUGGING_ERROR = 2, \/\/ DIMM Plugging error\n BUS_CALLOUT = 3, \/\/ Bus Called Out\n};\n}\n\n\/\/\/\n\/\/\/ @enum CalloutPriority\n\/\/\/\n\/\/\/ This enumeration defines the possible Procedure and Target callout priorities\n\/\/\/\n\/\/\/ Note that platform code may depend on the enum values starting at 0 and\n\/\/\/ incrementing in order to efficiently convert to a platform priority value\n\/\/\/ so do not reorder without consulting all platforms\n\/\/\/\nnamespace CalloutPriorities\n{\nenum CalloutPriority\n{\n LOW = 0,\n MEDIUM = 1,\n HIGH = 2,\n NONE = 3,\n};\n}\n\n\/\/\/\n\/\/\/ @enum CollectTrace\n\/\/\/\n\/\/\/ This enumeration defines the possible firmware traces to collect\n\/\/\/\nnamespace CollectTraces\n{\nconst uint32_t TRACE_SIZE = 256; \/\/ limit collected trace size\nenum CollectTrace\n{\n FSI = 1,\n SCOM = 2,\n SCAN = 3,\n MBOX = 4,\n};\n}\n\n\/\/ NOTE - this assumes no buffer_t or variable_buffers are passed\n\/\/ data is converted to a uint64_t when placed into the sbe ffdc\n\/\/ buffer\ninline fapi2::ffdc_t getFfdcData( sbeFfdc_t& i_sbeFfdc )\n{\n fapi2::ffdc_t temp;\n\n temp.size() = static_cast<size_t>(i_sbeFfdc.size);\n\n if(temp.size() == EI_FFDC_SIZE_TARGET)\n {\n#ifdef FAPI2_ENABLE_PLATFORM_GET_TARGET\n uint64_t targetData = i_sbeFfdc.data;\n fapi2::TargetType type = static_cast<fapi2::TargetType>(targetData >> 32);\n uint8_t instance = static_cast<uint8_t>(targetData & 0xFFFFFFFF);\n \/\/ call hostboot to get the fapi2 target reference\n temp.ptr() = static_cast<void*>(getTarget<TARGET_TYPE_ALL>(type, instance));\n#endif\n }\n else\n {\n \/\/ adjust the pointer based on the data size.\n temp.ptr() = static_cast<void*>(reinterpret_cast<uint8_t*>(&i_sbeFfdc.data) +\n (sizeof(uint64_t) - i_sbeFfdc.size));\n }\n\n return temp;\n}\n#endif\n\/\/\/\n\/\/\/ @brief Get FFDC Size\n\/\/\/\n\/\/\/ This is called by the FAPI_SET_HWP_ERROR macro to find out the size of\n\/\/\/ FFDC data. If the data is of a special type that is handled differently\n\/\/\/ than types that are simply memcopied then it is handled by a template\n\/\/\/ specialization.\n\/\/\/ If this function template is instantiated with a pointer, the compile\n\/\/\/ will fail.\n\/\/\/\n\/\/\/ @return uint16_t. Size of the FFDC data\n\/\/\/\ntemplate<typename T>\ninline uint16_t getErrorInfoFfdcSize(const T&)\n{\n static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE,\n \"FFDC too large to capture\");\n return sizeof(T);\n}\n#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)\n\/\/\/\n\/\/\/ @brief Compile error if caller tries to get the FFDC size of a pointer\n\/\/\/\ntemplate<typename T>\ninline uint16_t getErrorInfoFfdcSize(const T*)\n{\n static_assert(std::is_pointer<T>::value,\n \"pointer passed to getErrorInfoFfdcSize\");\n return 0;\n}\n#endif\n\/\/\/\n\/\/\/ @brief Get FFDC Size specialization for fapi2::Target\n\/\/\/\ntemplate<fapi2::TargetType T, typename V>\ninline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&)\n{\n return EI_FFDC_SIZE_TARGET;\n}\n\n#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)\n\/\/\/\n\/\/\/ @brief Get FFDC Size specialization for variable buffers\n\/\/\/\ntemplate<>\ninline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing)\n{\n \/\/ Limit a variable buffer to 4kb bytes, and we can memcpy the storage.\n return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE),\n i_thing.getLength<uint8_t>());\n}\n#endif\n\n\/\/\/\n\/\/\/ @brief Get FFDC Size specialization for ffdc_t\n\/\/\/\ntemplate<>\ninline uint16_t getErrorInfoFfdcSize(const fapi2::ffdc_t& i_ffdc)\n{\n return static_cast<uint16_t>(i_ffdc.size());\n}\n\n};\n\n#endif \/\/ FAPI2_ERRORINFO_DEFS_H_\n<commit_msg>Optimized PPE FFDC collection framework<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/error_info_defs.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2011,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file error_info_defs.H\n\/\/\/ @brief Defines to support the Error Information class\n\/\/\/\n\n#ifndef FAPI2_ERRORINFO_DEFS_H_\n#define FAPI2_ERRORINFO_DEFS_H_\n\n#include <stdint.h>\n#include <target.H>\n\n#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)\n #include <variable_buffer.H>\n #include <utility>\n#endif\nnamespace fapi2\n{\n\n\/\/\/\n\/\/\/ @brief Type to hold the ffdc data to be sent to hostboot\n\/\/\/\n\/\/\/ Note: Typical data sent seems to be register\/addresss info\n\/\/\/ rather than use extra space converting stuff just\n\/\/\/ send a uint64 always\n\/\/\/\nstruct sbeFfdc_t\n{\n uint32_t size;\n uint64_t data;\n} __attribute__((packed));\n\n\/\/ 20 entries limits the size of SbeFfdcData_t under 256 bytes\nenum\n{\n MAX_SBE_FFDC_ENTRIES = 20\n};\n\n\/\/ Data type for SBE ffdc buffer sent through fifo\ntypedef struct\n{\n uint32_t fapiRc; \/\/ Return code from failure\n uint32_t ffdcLength; \/\/ length of Fapi FFDC data (in bytes)\n struct sbeFfdc_t ffdcData[MAX_SBE_FFDC_ENTRIES]; \/\/ fapi FFDC data\n} SbeFfdcData_t; \/\/ ~248 bytes\n\n\/\/\/\n\/\/\/ @brief Type to hold the ffdc element in the ffdc class\n\/\/\/ Needed so that the size can be squirled away before the\n\/\/\/ macro is called.\n\/\/\/\nstruct ffdc_struct\n{\n const void* ptr;\n size_t size;\n};\n\n\nclass ffdc_t\n{\n public:\n ffdc_t(void)\n {}\n\n void operator=(const ffdc_t& i )\n {\n iv_value.ptr = i.ptr();\n iv_value.size = i.size();\n }\n\n operator const void* () const\n {\n return iv_value.ptr;\n }\n operator uint8_t() const\n {\n return *(reinterpret_cast<const uint8_t*>(iv_value.ptr));\n }\n\n size_t size(void) const\n {\n return iv_value.size;\n }\n size_t& size(void)\n {\n return iv_value.size;\n }\n\n const void* ptr(void) const\n {\n return iv_value.ptr;\n }\n const void*& ptr(void)\n {\n return iv_value.ptr;\n }\n\n private:\n struct ffdc_struct iv_value = {}; \/\/init to zero\n};\n\n\/\/\/\n\/\/\/ @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a\n\/\/\/ special type that cannot simply be memcopied\nenum ErrorInfoFfdcSize\n{\n EI_FFDC_SIZE_BUF = 0xffff, \/\/ fapi2::buffer<T>\n EI_FFDC_SIZE_TARGET = 0xfffe, \/\/ fapi2::Target\n EI_FFDC_SIZE_VBUF = 0xfffd, \/\/ fapi2::variable_buffer\n EI_FFDC_MAX_SIZE = 0x1000, \/\/ Limit regular FFDC capture to 4kb\n};\n\n\/\/\/\n\/\/\/ @brief Enumeration of error log severity.\n\/\/\/\nenum errlSeverity_t\n{\n FAPI2_ERRL_SEV_UNDEFINED = 0x00, \/\/\/ Used internally by ffdc mechanism\n FAPI2_ERRL_SEV_RECOVERED = 0x10, \/\/\/ Not seen by customer\n FAPI2_ERRL_SEV_PREDICTIVE = 0x20, \/\/\/ Error recovered but customer will see\n FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 \/\/\/ Unrecoverable, general\n};\n\n\/\/\/\n\/\/\/ @brief Enumeration of ErrorInfo types\n\/\/\/\nenum ErrorInfoType\n{\n EI_TYPE_FFDC = 0,\n EI_TYPE_HW_CALLOUT = 1,\n EI_TYPE_PROCEDURE_CALLOUT = 2,\n EI_TYPE_BUS_CALLOUT = 3,\n EI_TYPE_CDG = 4, \/\/ Target Callout\/Deconfig\/GARD\n EI_TYPE_CHILDREN_CDG = 5, \/\/ Children Callout\/Deconfig\/GARD\n EI_TYPE_COLLECT_TRACE = 6,\n EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1,\n};\n\n#ifndef MINIMUM_FFDC\n\/\/\/\n\/\/\/ @enum HwCallout\n\/\/\/\n\/\/\/ This enumeration defines the possible Hardware Callouts that are not\n\/\/\/ represented by fapi2::Targets\n\/\/\/\n\/\/\/ Note that platform code may depend on the enum values starting at 0 and\n\/\/\/ incrementing in order to efficiently convert to a platform callout value\n\/\/\/ so do not reorder without consulting all platforms\n\/\/\/\nnamespace HwCallouts\n{\nenum HwCallout\n{\n \/\/ Where indicated, a HW Callout in FAPI Error XML must include a\n \/\/ reference target that is used to identify the HW. e.g. for\n \/\/ TOD_CLOCK, the proc chip that the clock is attached to must be\n \/\/ specified\n TOD_CLOCK = 0, \/\/ Include proc-chip ref (or child chiplet)\n MEM_REF_CLOCK = 1, \/\/ Include membuf-chip ref (or child chiplet)\n PROC_REF_CLOCK = 2, \/\/ Include proc-chip ref (or child chiplet)\n PCI_REF_CLOCK = 3, \/\/ Include proc-chip ref (or child chiplet)\n FLASH_CONTROLLER_PART = 4,\n PNOR_PART = 5,\n SBE_SEEPROM_PART = 6,\n VPD_PART = 7,\n LPC_SLAVE_PART = 8,\n GPIO_EXPANDER_PART = 9,\n SPIVID_SLAVE_PART = 10,\n};\n}\n\n\/\/\/\n\/\/\/ @enum ProcedureCallout\n\/\/\/\n\/\/\/ This enumeration defines the possible Procedure Callouts\n\/\/\/ These instruct the customer\/customer-engineer what to do\n\/\/\/\n\/\/\/ Note that platform code may depend on the enum values starting at 0 and\n\/\/\/ incrementing in order to efficiently convert to a platform callout value\n\/\/\/ so do not reorder without consulting all platforms\n\/\/\/\nnamespace ProcedureCallouts\n{\nenum ProcedureCallout\n{\n CODE = 0, \/\/ Code problem\n LVL_SUPPORT = 1, \/\/ Call next level of support\n MEMORY_PLUGGING_ERROR = 2, \/\/ DIMM Plugging error\n BUS_CALLOUT = 3, \/\/ Bus Called Out\n};\n}\n\n\/\/\/\n\/\/\/ @enum CalloutPriority\n\/\/\/\n\/\/\/ This enumeration defines the possible Procedure and Target callout priorities\n\/\/\/\n\/\/\/ Note that platform code may depend on the enum values starting at 0 and\n\/\/\/ incrementing in order to efficiently convert to a platform priority value\n\/\/\/ so do not reorder without consulting all platforms\n\/\/\/\nnamespace CalloutPriorities\n{\nenum CalloutPriority\n{\n LOW = 0,\n MEDIUM = 1,\n HIGH = 2,\n NONE = 3,\n};\n}\n\n\/\/\/\n\/\/\/ @enum CollectTrace\n\/\/\/\n\/\/\/ This enumeration defines the possible firmware traces to collect\n\/\/\/\nnamespace CollectTraces\n{\nconst uint32_t TRACE_SIZE = 256; \/\/ limit collected trace size\nenum CollectTrace\n{\n FSI = 1,\n SCOM = 2,\n SCAN = 3,\n MBOX = 4,\n};\n}\n\n\/\/ NOTE - this assumes no buffer_t or variable_buffers are passed\n\/\/ data is converted to a uint64_t when placed into the sbe ffdc\n\/\/ buffer\ninline fapi2::ffdc_t getFfdcData( sbeFfdc_t& i_sbeFfdc )\n{\n fapi2::ffdc_t temp;\n\n temp.size() = static_cast<size_t>(i_sbeFfdc.size);\n\n if(temp.size() == EI_FFDC_SIZE_TARGET)\n {\n#ifdef FAPI2_ENABLE_PLATFORM_GET_TARGET\n uint64_t targetData = i_sbeFfdc.data;\n fapi2::TargetType type = static_cast<fapi2::TargetType>(targetData >> 32);\n uint8_t instance = static_cast<uint8_t>(targetData & 0xFFFFFFFF);\n \/\/ call hostboot to get the fapi2 target reference\n temp.ptr() = static_cast<void*>(getTarget<TARGET_TYPE_ALL>(type, instance));\n#endif\n }\n else\n {\n \/\/ adjust the pointer based on the data size.\n temp.ptr() = static_cast<void*>(reinterpret_cast<uint8_t*>(&i_sbeFfdc.data) +\n (sizeof(uint64_t) - i_sbeFfdc.size));\n }\n\n return temp;\n}\n#endif\n\/\/\/\n\/\/\/ @brief Get FFDC Size\n\/\/\/\n\/\/\/ This is called by the FAPI_SET_HWP_ERROR macro to find out the size of\n\/\/\/ FFDC data. If the data is of a special type that is handled differently\n\/\/\/ than types that are simply memcopied then it is handled by a template\n\/\/\/ specialization.\n\/\/\/ If this function template is instantiated with a pointer, the compile\n\/\/\/ will fail.\n\/\/\/\n\/\/\/ @return uint16_t. Size of the FFDC data\n\/\/\/\ntemplate<typename T>\ninline uint16_t getErrorInfoFfdcSize(const T&)\n{\n static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE,\n \"FFDC too large to capture\");\n return sizeof(T);\n}\n#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)\n\/\/\/\n\/\/\/ @brief Compile error if caller tries to get the FFDC size of a pointer\n\/\/\/\ntemplate<typename T>\ninline uint16_t getErrorInfoFfdcSize(const T*)\n{\n static_assert(std::is_pointer<T>::value,\n \"pointer passed to getErrorInfoFfdcSize\");\n return 0;\n}\n#endif\n\/\/\/\n\/\/\/ @brief Get FFDC Size specialization for fapi2::Target\n\/\/\/\ntemplate<fapi2::TargetType T, typename V>\ninline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&)\n{\n return EI_FFDC_SIZE_TARGET;\n}\n\n#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)\n\/\/\/\n\/\/\/ @brief Get FFDC Size specialization for variable buffers\n\/\/\/\ntemplate<>\ninline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing)\n{\n \/\/ Limit a variable buffer to 4kb bytes, and we can memcpy the storage.\n return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE),\n i_thing.getLength<uint8_t>());\n}\n#endif\n\n\/\/\/\n\/\/\/ @brief Get FFDC Size specialization for ffdc_t\n\/\/\/\ntemplate<>\ninline uint16_t getErrorInfoFfdcSize(const fapi2::ffdc_t& i_ffdc)\n{\n return static_cast<uint16_t>(i_ffdc.size());\n}\n\n};\n\n#endif \/\/ FAPI2_ERRORINFO_DEFS_H_\n<|endoftext|>"} {"text":"<commit_before>#include \"bayesian\/graph.hpp\"\n#include \"bayesian\/sampling.hpp\"\n\nnamespace bn {\n\nmatrix_type sampling::operator()(\n graph_t const& graph,\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n \/\/ パターン作る(generate_pattern)\n auto const generated_patterns = generate_pattern(graph, 100\/*tmp*\/, condition);\n\n \/\/ 数え上げを行う\n bn::matrix_type result(node->selectable_num, 1, 0.0);\n\tfor(auto const& pattern : generated_patterns)\n\t{\n\t\tresult[pattern.at(node)][0] += 1.0;\n\t}\n\t\n\t\/\/ 全要素をパターン数で割る\n\tfor(std::size_t i = 0; i < node->selectable_num; ++i)\n\t{\n\t\tresult[i][0] \/= generated_patterns.size();\n\t}\n\t\n return result;\n}\n\nsampling::pattern_list sampling::generate_pattern(\n graph_t const& graph,\n int const num,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n \/\/ 条件探査用関数\n auto const is_condition = [&condition](std::unordered_map<vertex_type, int> const& pattern) -> bool\n {\n for(auto const& forcus_cond : condition)\n {\n \/\/ ノードを探す.見つからなければfalse\n auto position = pattern.find(forcus_cond.first);\n if(position == pattern.cend()) return false;\n\n \/\/ 条件と一致しなければfalse\n if(position->second != forcus_cond.second) return false;\n }\n return true;\n };\n\n \/\/ 最初の要素をseed_node_listから削除したうえで再帰に移譲(当然ノードがなければ失敗)\n auto const seed_node_list = graph.vertex_list();\n if(seed_node_list.empty()) return {};\n\n\n \/\/ num回ループで生成する\n pattern_list result;\n while(result.size() < static_cast<std::size_t>(num))\n {\n auto node_list = seed_node_list;\n\t\tstd::unordered_map<vertex_type, int> pattern;\n\t\t\n while(!node_list.empty())\n {\n auto const first_node = node_list.back();\n node_list.pop_back();\n\n choice_pattern(graph, first_node, node_list, pattern);\n }\n\n\t\tif(is_condition(pattern))\n\t\t{\n\t\t\tresult.push_back(std::move(pattern));\n\t\t}\n }\n\n return result;\n}\n\nvoid sampling::choice_pattern(\n graph_t const& graph,\n vertex_type const& current,\n std::vector<vertex_type>& remain_node,\n std::unordered_map<vertex_type, int>& pattern\n )\n{\n \/\/ 上位ノードが決定していることを確認する.\n \/\/ 決定していなかった場合は再帰的処理\n std::unordered_map<vertex_type, int> parent_condition;\n for(auto const& edge : graph.in_edges(current))\n {\n auto const parent = graph.source(edge);\n auto const position = std::find(remain_node.begin(), remain_node.end(), parent);\n if(position != remain_node.end())\n {\n \/\/ 抜き出して消す\n auto const next_current = *position;\n remain_node.erase(position);\n\n \/\/ 再帰\n choice_pattern(graph, next_current, remain_node, pattern);\n }\n\n parent_condition[parent] = pattern[parent];\n }\n\n \/\/ CPTから必要データを取得\n auto const optional_cpt_data = current->cpt[parent_condition];\n std::vector<double> condition_probability;\n if(optional_cpt_data.first)\n {\n condition_probability = optional_cpt_data.second;\n }\n else\n {\n throw std::runtime_error(\"Invalid data from CPT(cannot search data)\");\n }\n\n \/\/ メルセンヌ・ツイスタで自身のノード値を生成\n auto const generated_value = probability_generator_();\n double total = 0.0;\n for(int i = 0; current->selectable_num; ++i)\n {\n auto const old_total = total;\n total += condition_probability.at(i);\n if(old_total <= generated_value && generated_value < total)\n {\n pattern[current] = i;\n break;\n }\n }\n\n return;\n}\n\nsampling::probability_generator::probability_generator()\n : distribution_(0.0, 1.0)\n{\n std::random_device rand_dev;\n std::vector<std::uint_least32_t> vec(10);\n std::generate(vec.begin(), vec.end(), std::ref(rand_dev));\n std::seed_seq seed(vec.begin(), vec.end());\n engine_.reset(new std::mt19937(seed));\n}\n\ndouble sampling::probability_generator::operator() ()\n{\n return distribution_(*engine_);\n}\n\n} \/\/ namespace bn\n\n<commit_msg>update: edit sample num.<commit_after>#include \"bayesian\/graph.hpp\"\n#include \"bayesian\/sampling.hpp\"\n\nnamespace bn {\n\nmatrix_type sampling::operator()(\n graph_t const& graph,\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n \/\/ パターン作る(generate_pattern)\n auto const generated_patterns = generate_pattern(graph, 10000\/*tmp*\/, condition);\n\n \/\/ 数え上げを行う\n bn::matrix_type result(node->selectable_num, 1, 0.0);\n\tfor(auto const& pattern : generated_patterns)\n\t{\n\t\tresult[pattern.at(node)][0] += 1.0;\n\t}\n\t\n\t\/\/ 全要素をパターン数で割る\n\tfor(std::size_t i = 0; i < node->selectable_num; ++i)\n\t{\n\t\tresult[i][0] \/= generated_patterns.size();\n\t}\n\t\n return result;\n}\n\nsampling::pattern_list sampling::generate_pattern(\n graph_t const& graph,\n int const num,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n \/\/ 条件探査用関数\n auto const is_condition = [&condition](std::unordered_map<vertex_type, int> const& pattern) -> bool\n {\n for(auto const& forcus_cond : condition)\n {\n \/\/ ノードを探す.見つからなければfalse\n auto position = pattern.find(forcus_cond.first);\n if(position == pattern.cend()) return false;\n\n \/\/ 条件と一致しなければfalse\n if(position->second != forcus_cond.second) return false;\n }\n return true;\n };\n\n \/\/ 最初の要素をseed_node_listから削除したうえで再帰に移譲(当然ノードがなければ失敗)\n auto const seed_node_list = graph.vertex_list();\n if(seed_node_list.empty()) return {};\n\n\n \/\/ num回ループで生成する\n pattern_list result;\n while(result.size() < static_cast<std::size_t>(num))\n {\n auto node_list = seed_node_list;\n\t\tstd::unordered_map<vertex_type, int> pattern;\n\t\t\n while(!node_list.empty())\n {\n auto const first_node = node_list.back();\n node_list.pop_back();\n\n choice_pattern(graph, first_node, node_list, pattern);\n }\n\n\t\tif(is_condition(pattern))\n\t\t{\n\t\t\tresult.push_back(std::move(pattern));\n\t\t}\n }\n\n return result;\n}\n\nvoid sampling::choice_pattern(\n graph_t const& graph,\n vertex_type const& current,\n std::vector<vertex_type>& remain_node,\n std::unordered_map<vertex_type, int>& pattern\n )\n{\n \/\/ 上位ノードが決定していることを確認する.\n \/\/ 決定していなかった場合は再帰的処理\n std::unordered_map<vertex_type, int> parent_condition;\n for(auto const& edge : graph.in_edges(current))\n {\n auto const parent = graph.source(edge);\n auto const position = std::find(remain_node.begin(), remain_node.end(), parent);\n if(position != remain_node.end())\n {\n \/\/ 抜き出して消す\n auto const next_current = *position;\n remain_node.erase(position);\n\n \/\/ 再帰\n choice_pattern(graph, next_current, remain_node, pattern);\n }\n\n parent_condition[parent] = pattern[parent];\n }\n\n \/\/ CPTから必要データを取得\n auto const optional_cpt_data = current->cpt[parent_condition];\n std::vector<double> condition_probability;\n if(optional_cpt_data.first)\n {\n condition_probability = optional_cpt_data.second;\n }\n else\n {\n throw std::runtime_error(\"Invalid data from CPT(cannot search data)\");\n }\n\n \/\/ メルセンヌ・ツイスタで自身のノード値を生成\n auto const generated_value = probability_generator_();\n double total = 0.0;\n for(int i = 0; current->selectable_num; ++i)\n {\n auto const old_total = total;\n total += condition_probability.at(i);\n if(old_total <= generated_value && generated_value < total)\n {\n pattern[current] = i;\n break;\n }\n }\n\n return;\n}\n\nsampling::probability_generator::probability_generator()\n : distribution_(0.0, 1.0)\n{\n std::random_device rand_dev;\n std::vector<std::uint_least32_t> vec(10);\n std::generate(vec.begin(), vec.end(), std::ref(rand_dev));\n std::seed_seq seed(vec.begin(), vec.end());\n engine_.reset(new std::mt19937(seed));\n}\n\ndouble sampling::probability_generator::operator() ()\n{\n return distribution_(*engine_);\n}\n\n} \/\/ namespace bn\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file StringUtils.hpp\n * @brief String utilities prototype.\n * @author zer0\n * @date 2016-04-04\n * @date 2016-12-05 (Rename: Strings -> StringUtils)\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_STRINGUTILS_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_STRINGUTILS_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#define CHECK_GNUC_CXX_REGEX\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n#include <libtbag\/Err.hpp>\n#include <libtbag\/Type.hpp>\n#include <libtbag\/util\/BufferInfo.hpp>\n\n#include <cstdint>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <array>\n#include <regex>\n#include <thread>\n#include <type_traits>\n#include <iterator>\n#include <utility>\n\n#define TBAG_WINDOWS_NEW_LINE \"\\r\\n\"\n#define TBAG_UNIX_NEW_LINE \"\\n\"\n\n#if defined(TBAG_PLATFORM_WINDOWS)\n#define TBAG_NEW_LINE TBAG_WINDOWS_NEW_LINE\n#else\n#define TBAG_NEW_LINE TBAG_UNIX_NEW_LINE\n#endif\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace string {\n\nTBAG_CONSTEXPR char const * const WINDOWS_NEW_LINE = TBAG_WINDOWS_NEW_LINE;\nTBAG_CONSTEXPR char const * const UNIX_NEW_LINE = TBAG_UNIX_NEW_LINE;\nTBAG_CONSTEXPR char const * const NEW_LINE = TBAG_NEW_LINE;\n\nTBAG_CONSTEXPR char const CHAR_SPACE = ' ';\nTBAG_CONSTEXPR char const CHAR_TAB = '\\t';\nTBAG_CONSTEXPR char const CHAR_RETURN = '\\n';\n\ntemplate <typename T>\nTBAG_CONSTEXPR T const * charOrWidechar(char const * c, wchar_t const * w);\n\ntemplate <>\ninline TBAG_CONSTEXPR char const * charOrWidechar<char>(char const * c, wchar_t const * w)\n{\n return c;\n}\n\ntemplate <>\ninline TBAG_CONSTEXPR wchar_t const * charOrWidechar<wchar_t>(char const * c, wchar_t const * w)\n{\n return w;\n}\n\n#ifndef CHAR_OR_WIDECHAR\n#define CHAR_OR_WIDECHAR(type, str) ::libtbag::string::charOrWidechar<type>(str, L##str)\n#endif\n\ntemplate <typename CharT>\ninline TBAG_CONSTEXPR std::size_t string_length(CharT const * text)\n{\n return (text == nullptr || *text == '\\0') ? 0U : 1U + string_length(text + 1U);\n}\n\ntemplate <typename FloatingType>\nstd::string convertStringWithFloatingPoint(FloatingType floating, int precision = 2)\n{\n static_assert(std::is_floating_point<FloatingType>::value, \"Not floating point type.\");\n\n std::stringstream ss;\n ss.setf(std::ios_base::showpoint);\n ss.setf(std::ios_base::fixed, std::ios_base::floatfield);\n ss.precision(precision);\n ss << floating;\n return ss.str();\n}\n\nenum class LineFeedStyle\n{\n LFS_NONE,\n LFS_UNIX,\n LFS_WINDOWS,\n LFS_AUTO,\n};\n\nTBAG_API LineFeedStyle getLineFeedStyle(std::string const & name);\nTBAG_API char const * getLineFeedStyleText(LineFeedStyle style) TBAG_NOEXCEPT;\n\nTBAG_API std::string getLineFeed(LineFeedStyle style = LineFeedStyle::LFS_AUTO);\nTBAG_API std::string getStdEndLine();\nTBAG_API bool appendLineFeed(LineFeedStyle style, char * buffer, int buffer_size, int offset) TBAG_NOEXCEPT;\n\n\/**\n * Separate tokens.\n *\n * @tparam CharType Character type.\n * @tparam StringType std::string type (Don't change this typename).\n *\n * @param[in] source Original string.\n * @param[in] delimiter Delimiter string.\n * @param[in] remove_empty Remove all empty tokens.\n *\n * @return\n * Token vector.\n *\/\nTBAG_API std::vector<std::string> splitTokens(std::string const & source, std::string const & delimiter, bool remove_empty = true);\nTBAG_API std::vector<std::string> splitUtf8Tokens(std::string const & utf8_source, std::string const & utf8_delimiter, bool remove_empty = true);\n\ntemplate <typename Iterator>\nstd::string mergeTokens(Iterator begin, Iterator end, std::string const & delimiter)\n{\n if (begin == end) {\n return {};\n }\n if (begin + 1 == end) {\n return *begin;\n }\n std::stringstream ss;\n ss << *begin;\n ++begin;\n for (; begin != end; ++begin) {\n ss << delimiter << *begin;\n }\n return ss.str();\n}\n\nTBAG_API std::string mergeTokens(std::vector<std::string> const & tokens, std::string const & delimiter);\nTBAG_API std::string mergeTokens(std::vector<std::string> const & tokens);\nTBAG_API std::string mergeArgv(char ** argv);\n\n\/**\n * Thread ID to string.\n *\/\nTBAG_API std::string convertStringWithThreadId(std::thread::id const & id);\n\nTBAG_CONSTEXPR char const * const STRING_EMPTY = \"\";\nTBAG_CONSTEXPR char const * const STRING_SPACE = \" \";\nTBAG_CONSTEXPR char const * const STRING_HEX_PREFIX = \"0x\";\nTBAG_CONSTEXPR int const DEFAULT_LINE_WIDTH = 2 * 8;\n\n\/**\n * Byte array to HEX string.\n *\/\nTBAG_API char convertHalfByteToHexChar(uint8_t half_byte);\nTBAG_API std::string convertByteToHexString(uint8_t hex);\nTBAG_API std::string convertByteArrayToHexString(uint8_t const * bytes, std::size_t size,\n std::string const & prefix = STRING_HEX_PREFIX,\n std::string const & separator = STRING_EMPTY);\nTBAG_API std::string convertByteArrayToHexStringBox(uint8_t const * bytes, std::size_t size,\n int line_width = DEFAULT_LINE_WIDTH,\n std::string const & prefix = STRING_HEX_PREFIX,\n std::string const & separator = STRING_SPACE,\n std::string const & new_line = NEW_LINE);\n\ntemplate <typename T>\nstd::string convertByteVectorToHexString(std::vector<T> const & bytes,\n std::string const & prefix = STRING_HEX_PREFIX,\n std::string const & separator = STRING_EMPTY)\n{\n return convertByteArrayToHexString((uint8_t const *)bytes.data(), bytes.size(), prefix, separator);\n}\n\ntemplate <typename T>\nstd::string convertByteVectorToHexStringBox(std::vector<T> const & bytes, int line_width = DEFAULT_LINE_WIDTH,\n std::string const & prefix = STRING_HEX_PREFIX,\n std::string const & separator = STRING_SPACE,\n std::string const & new_line = NEW_LINE)\n{\n return convertByteArrayToHexStringBox((uint8_t const *)bytes.data(),\n bytes.size(), line_width, prefix, separator, new_line);\n}\n\nTBAG_CONSTEXPR std::size_t const HEX_STRING_ADDRESS_BYTE_SIZE =\n (\/*PREFIX(0x)*\/2) + (sizeof(std::uint64_t) * 2\/*HEX STRING ADDRESS*\/) + (1\/*NULL*\/);\nusing AddressHexString = std::array<char, HEX_STRING_ADDRESS_BYTE_SIZE>;\n\n\/**\n * HEX string to Byte array.\n *\/\nTBAG_API Err convertHexCharToHalfByte(char hex_char, uint8_t & result);\nTBAG_API Err convertHexCharToByte(char high_char, char low_char, uint8_t & result);\nTBAG_API Err convertHexStringToBuffer(char const * hex_string, std::size_t length, libtbag::util::Buffer & buffer);\n\n\/**\n * Address to HEX string.\n *\/\nTBAG_API AddressHexString convertAddressToHexString(void const * address) TBAG_NOEXCEPT;\nTBAG_API AddressHexString convertUnsignedIntegerToHexString(std::uint64_t value) TBAG_NOEXCEPT;\nTBAG_API std::string convertAddressHexStringToString(AddressHexString const & address);\nTBAG_API std::string convertAddressToString(void const * address);\n\n\/**\n * Regex based token.\n *\/\nTBAG_API std::vector<std::string> splitMatch(std::string const & source, std::regex const & match);\nTBAG_API std::vector<std::string> splitMatch(std::string const & source, std::string const & match);\n\n\/\/ Regexp utilities.\nTBAG_API std::string replaceRegex(std::string const & source, std::string const & regex, std::string const & replace);\nTBAG_API std::string removeRegex(std::string const & source, std::string const & regex);\n\n\/**\n * Simple replace.\n *\/\nTBAG_API std::string replace(std::string const & source, std::string const & find, std::string const & replace);\n\nTBAG_API bool isMatch(std::string const & source, std::regex const & regex);\nTBAG_API bool isMatch(std::string const & source, std::string const & regex);\nTBAG_API bool isUtf8Match(std::string const & utf8_source, std::string const & regex);\n\n\/**\n * Checks whether str is a decimal digit character.\n *\n * @remarks\n * Decimal digits are any of: 0 1 2 3 4 5 6 7 8 9\n *\/\nTBAG_API bool isDigit(std::string const & str);\nTBAG_API bool isVariableName(char c);\nTBAG_API bool isVariableName(std::string const & str);\n\nTBAG_API std::string trimLeft(std::string const & str);\nTBAG_API std::string trimRight(std::string const & str);\nTBAG_API std::string trim(std::string const & str);\n\nTBAG_API bool createRandomString(char * buffer, std::size_t size);\n\nTBAG_API std::string lower(std::string const & str);\nTBAG_API std::string upper(std::string const & str);\n\nTBAG_API void lowerSelf(std::string & str);\nTBAG_API void upperSelf(std::string & str);\n\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR1 = \"on\";\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR2 = \"true\";\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR3 = \"ok\";\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR4 = \"yes\";\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR5 = \"y\";\n\nTBAG_CONSTEXPR char const * const FALSE_LOWER_STR1 = \"off\";\nTBAG_CONSTEXPR char const * const FALSE_LOWER_STR2 = \"false\";\nTBAG_CONSTEXPR char const * const FALSE_LOWER_STR3 = \"no\";\nTBAG_CONSTEXPR char const * const FALSE_LOWER_STR4 = \"n\";\n\nTBAG_API bool toVal(std::string const & str, bool & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, char & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned char & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, short & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned short & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, int & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned int & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, long & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned long & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, long long & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned long long & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, float & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, double & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, long double & to, std::size_t * index = nullptr, int base = 10);\n\ntemplate <typename T>\ninline T toValue(std::string const & str, T default_value = T(), int base = 10)\n{\n T result;\n if (toVal(str, result, nullptr, base)) {\n return result;\n }\n return default_value;\n}\n\ntemplate <typename T>\ninline std::string toString(T val)\n{\n return std::to_string(val);\n}\n\ninline std::string toString(bool val)\n{\n return std::to_string(val ? 1 : 0);\n}\n\nTBAG_API std::string toHexString(unsigned char val, bool upper = true);\nTBAG_API std::string toHexString(unsigned short val, bool upper = true);\nTBAG_API std::string toHexString(unsigned int val, bool upper = true);\nTBAG_API std::string toHexString(unsigned long val, bool upper = true);\nTBAG_API std::string toHexString(unsigned long long val, bool upper = true);\n\nTBAG_API std::size_t toByteSize(std::string const & str);\n\n} \/\/ namespace string\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_STRINGUTILS_HPP__\n\n<commit_msg>Create TBAG_EMPTY_STRING macro.<commit_after>\/**\n * @file StringUtils.hpp\n * @brief String utilities prototype.\n * @author zer0\n * @date 2016-04-04\n * @date 2016-12-05 (Rename: Strings -> StringUtils)\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_STRINGUTILS_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_STRINGUTILS_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#define CHECK_GNUC_CXX_REGEX\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n#include <libtbag\/Err.hpp>\n#include <libtbag\/Type.hpp>\n#include <libtbag\/util\/BufferInfo.hpp>\n\n#include <cstdint>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <array>\n#include <regex>\n#include <thread>\n#include <type_traits>\n#include <iterator>\n#include <utility>\n\n#define TBAG_WINDOWS_NEW_LINE \"\\r\\n\"\n#define TBAG_UNIX_NEW_LINE \"\\n\"\n\n#if defined(TBAG_PLATFORM_WINDOWS)\n#define TBAG_NEW_LINE TBAG_WINDOWS_NEW_LINE\n#else\n#define TBAG_NEW_LINE TBAG_UNIX_NEW_LINE\n#endif\n\n#define TBAG_EMPTY_STRING \"\"\n#define TBAG_EMPTY_STRING_WIDE L\"\"\n#define TBAG_SPACE_STRING \" \"\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace string {\n\nTBAG_CONSTEXPR char const * const WINDOWS_NEW_LINE = TBAG_WINDOWS_NEW_LINE;\nTBAG_CONSTEXPR char const * const UNIX_NEW_LINE = TBAG_UNIX_NEW_LINE;\nTBAG_CONSTEXPR char const * const NEW_LINE = TBAG_NEW_LINE;\n\nTBAG_CONSTEXPR char const CHAR_SPACE = ' ';\nTBAG_CONSTEXPR char const CHAR_TAB = '\\t';\nTBAG_CONSTEXPR char const CHAR_RETURN = '\\n';\n\ntemplate <typename T>\nTBAG_CONSTEXPR T const * charOrWidechar(char const * c, wchar_t const * w);\n\ntemplate <>\ninline TBAG_CONSTEXPR char const * charOrWidechar<char>(char const * c, wchar_t const * w)\n{\n return c;\n}\n\ntemplate <>\ninline TBAG_CONSTEXPR wchar_t const * charOrWidechar<wchar_t>(char const * c, wchar_t const * w)\n{\n return w;\n}\n\n#ifndef CHAR_OR_WIDECHAR\n#define CHAR_OR_WIDECHAR(type, str) ::libtbag::string::charOrWidechar<type>(str, L##str)\n#endif\n\ntemplate <typename CharT>\ninline TBAG_CONSTEXPR std::size_t string_length(CharT const * text)\n{\n return (text == nullptr || *text == '\\0') ? 0U : 1U + string_length(text + 1U);\n}\n\ntemplate <typename FloatingType>\nstd::string convertStringWithFloatingPoint(FloatingType floating, int precision = 2)\n{\n static_assert(std::is_floating_point<FloatingType>::value, \"Not floating point type.\");\n\n std::stringstream ss;\n ss.setf(std::ios_base::showpoint);\n ss.setf(std::ios_base::fixed, std::ios_base::floatfield);\n ss.precision(precision);\n ss << floating;\n return ss.str();\n}\n\nenum class LineFeedStyle\n{\n LFS_NONE,\n LFS_UNIX,\n LFS_WINDOWS,\n LFS_AUTO,\n};\n\nTBAG_API LineFeedStyle getLineFeedStyle(std::string const & name);\nTBAG_API char const * getLineFeedStyleText(LineFeedStyle style) TBAG_NOEXCEPT;\n\nTBAG_API std::string getLineFeed(LineFeedStyle style = LineFeedStyle::LFS_AUTO);\nTBAG_API std::string getStdEndLine();\nTBAG_API bool appendLineFeed(LineFeedStyle style, char * buffer, int buffer_size, int offset) TBAG_NOEXCEPT;\n\n\/**\n * Separate tokens.\n *\n * @tparam CharType Character type.\n * @tparam StringType std::string type (Don't change this typename).\n *\n * @param[in] source Original string.\n * @param[in] delimiter Delimiter string.\n * @param[in] remove_empty Remove all empty tokens.\n *\n * @return\n * Token vector.\n *\/\nTBAG_API std::vector<std::string> splitTokens(std::string const & source, std::string const & delimiter, bool remove_empty = true);\nTBAG_API std::vector<std::string> splitUtf8Tokens(std::string const & utf8_source, std::string const & utf8_delimiter, bool remove_empty = true);\n\ntemplate <typename Iterator>\nstd::string mergeTokens(Iterator begin, Iterator end, std::string const & delimiter)\n{\n if (begin == end) {\n return {};\n }\n if (begin + 1 == end) {\n return *begin;\n }\n std::stringstream ss;\n ss << *begin;\n ++begin;\n for (; begin != end; ++begin) {\n ss << delimiter << *begin;\n }\n return ss.str();\n}\n\nTBAG_API std::string mergeTokens(std::vector<std::string> const & tokens, std::string const & delimiter);\nTBAG_API std::string mergeTokens(std::vector<std::string> const & tokens);\nTBAG_API std::string mergeArgv(char ** argv);\n\n\/**\n * Thread ID to string.\n *\/\nTBAG_API std::string convertStringWithThreadId(std::thread::id const & id);\n\nTBAG_CONSTEXPR char const * const STRING_EMPTY = TBAG_EMPTY_STRING;\nTBAG_CONSTEXPR char const * const STRING_SPACE = TBAG_SPACE_STRING;\nTBAG_CONSTEXPR char const * const STRING_HEX_PREFIX = \"0x\";\nTBAG_CONSTEXPR int const DEFAULT_LINE_WIDTH = 2 * 8;\n\n\/**\n * Byte array to HEX string.\n *\/\nTBAG_API char convertHalfByteToHexChar(uint8_t half_byte);\nTBAG_API std::string convertByteToHexString(uint8_t hex);\nTBAG_API std::string convertByteArrayToHexString(uint8_t const * bytes, std::size_t size,\n std::string const & prefix = STRING_HEX_PREFIX,\n std::string const & separator = STRING_EMPTY);\nTBAG_API std::string convertByteArrayToHexStringBox(uint8_t const * bytes, std::size_t size,\n int line_width = DEFAULT_LINE_WIDTH,\n std::string const & prefix = STRING_HEX_PREFIX,\n std::string const & separator = STRING_SPACE,\n std::string const & new_line = NEW_LINE);\n\ntemplate <typename T>\nstd::string convertByteVectorToHexString(std::vector<T> const & bytes,\n std::string const & prefix = STRING_HEX_PREFIX,\n std::string const & separator = STRING_EMPTY)\n{\n return convertByteArrayToHexString((uint8_t const *)bytes.data(), bytes.size(), prefix, separator);\n}\n\ntemplate <typename T>\nstd::string convertByteVectorToHexStringBox(std::vector<T> const & bytes, int line_width = DEFAULT_LINE_WIDTH,\n std::string const & prefix = STRING_HEX_PREFIX,\n std::string const & separator = STRING_SPACE,\n std::string const & new_line = NEW_LINE)\n{\n return convertByteArrayToHexStringBox((uint8_t const *)bytes.data(),\n bytes.size(), line_width, prefix, separator, new_line);\n}\n\nTBAG_CONSTEXPR std::size_t const HEX_STRING_ADDRESS_BYTE_SIZE =\n (\/*PREFIX(0x)*\/2) + (sizeof(std::uint64_t) * 2\/*HEX STRING ADDRESS*\/) + (1\/*NULL*\/);\nusing AddressHexString = std::array<char, HEX_STRING_ADDRESS_BYTE_SIZE>;\n\n\/**\n * HEX string to Byte array.\n *\/\nTBAG_API Err convertHexCharToHalfByte(char hex_char, uint8_t & result);\nTBAG_API Err convertHexCharToByte(char high_char, char low_char, uint8_t & result);\nTBAG_API Err convertHexStringToBuffer(char const * hex_string, std::size_t length, libtbag::util::Buffer & buffer);\n\n\/**\n * Address to HEX string.\n *\/\nTBAG_API AddressHexString convertAddressToHexString(void const * address) TBAG_NOEXCEPT;\nTBAG_API AddressHexString convertUnsignedIntegerToHexString(std::uint64_t value) TBAG_NOEXCEPT;\nTBAG_API std::string convertAddressHexStringToString(AddressHexString const & address);\nTBAG_API std::string convertAddressToString(void const * address);\n\n\/**\n * Regex based token.\n *\/\nTBAG_API std::vector<std::string> splitMatch(std::string const & source, std::regex const & match);\nTBAG_API std::vector<std::string> splitMatch(std::string const & source, std::string const & match);\n\n\/\/ Regexp utilities.\nTBAG_API std::string replaceRegex(std::string const & source, std::string const & regex, std::string const & replace);\nTBAG_API std::string removeRegex(std::string const & source, std::string const & regex);\n\n\/**\n * Simple replace.\n *\/\nTBAG_API std::string replace(std::string const & source, std::string const & find, std::string const & replace);\n\nTBAG_API bool isMatch(std::string const & source, std::regex const & regex);\nTBAG_API bool isMatch(std::string const & source, std::string const & regex);\nTBAG_API bool isUtf8Match(std::string const & utf8_source, std::string const & regex);\n\n\/**\n * Checks whether str is a decimal digit character.\n *\n * @remarks\n * Decimal digits are any of: 0 1 2 3 4 5 6 7 8 9\n *\/\nTBAG_API bool isDigit(std::string const & str);\nTBAG_API bool isVariableName(char c);\nTBAG_API bool isVariableName(std::string const & str);\n\nTBAG_API std::string trimLeft(std::string const & str);\nTBAG_API std::string trimRight(std::string const & str);\nTBAG_API std::string trim(std::string const & str);\n\nTBAG_API bool createRandomString(char * buffer, std::size_t size);\n\nTBAG_API std::string lower(std::string const & str);\nTBAG_API std::string upper(std::string const & str);\n\nTBAG_API void lowerSelf(std::string & str);\nTBAG_API void upperSelf(std::string & str);\n\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR1 = \"on\";\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR2 = \"true\";\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR3 = \"ok\";\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR4 = \"yes\";\nTBAG_CONSTEXPR char const * const TRUE_LOWER_STR5 = \"y\";\n\nTBAG_CONSTEXPR char const * const FALSE_LOWER_STR1 = \"off\";\nTBAG_CONSTEXPR char const * const FALSE_LOWER_STR2 = \"false\";\nTBAG_CONSTEXPR char const * const FALSE_LOWER_STR3 = \"no\";\nTBAG_CONSTEXPR char const * const FALSE_LOWER_STR4 = \"n\";\n\nTBAG_API bool toVal(std::string const & str, bool & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, char & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned char & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, short & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned short & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, int & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned int & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, long & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned long & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, long long & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, unsigned long long & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, float & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, double & to, std::size_t * index = nullptr, int base = 10);\nTBAG_API bool toVal(std::string const & str, long double & to, std::size_t * index = nullptr, int base = 10);\n\ntemplate <typename T>\ninline T toValue(std::string const & str, T default_value = T(), int base = 10)\n{\n T result;\n if (toVal(str, result, nullptr, base)) {\n return result;\n }\n return default_value;\n}\n\ntemplate <typename T>\ninline std::string toString(T val)\n{\n return std::to_string(val);\n}\n\ninline std::string toString(bool val)\n{\n return std::to_string(val ? 1 : 0);\n}\n\nTBAG_API std::string toHexString(unsigned char val, bool upper = true);\nTBAG_API std::string toHexString(unsigned short val, bool upper = true);\nTBAG_API std::string toHexString(unsigned int val, bool upper = true);\nTBAG_API std::string toHexString(unsigned long val, bool upper = true);\nTBAG_API std::string toHexString(unsigned long long val, bool upper = true);\n\nTBAG_API std::size_t toByteSize(std::string const & str);\n\n} \/\/ namespace string\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_STRINGUTILS_HPP__\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clangxx -fsanitize=function %s -O3 -g -o %t\n\/\/ RUN: %run %t 2>&1 | FileCheck %s\n\/\/ Verify that we can disable symbolization if needed:\n\/\/ RUN: UBSAN_OPTIONS=symbolize=0 ASAN_OPTIONS=symbolize=0 %run %t 2>&1 | FileCheck %s --check-prefix=NOSYM\n\n#include <stdint.h>\n\nvoid f() {}\n\nvoid g(int x) {}\n\nint main(void) {\n \/\/ CHECK: runtime error: call to function f() through pointer to incorrect function type 'void (*)(int)'\n \/\/ CHECK-NEXT: function.cpp:8: note: f() defined here\n \/\/ NOSYM: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int)'\n \/\/ NOSYM-NEXT: ({{.*}}+0x{{.*}}): note: (unknown) defined here\n reinterpret_cast<void (*)(int)>(reinterpret_cast<uintptr_t>(f))(42);\n\n \/\/ CHECK-NOT: runtime error: call to function g\n reinterpret_cast<void (*)(int)>(reinterpret_cast<uintptr_t>(g))(42);\n}\n<commit_msg>[ubsan] Do not run Function\/function.cpp on Darwin where -fsanitize=function is not supported.<commit_after>\/\/ RUN: %clangxx -fsanitize=function %s -O3 -g -o %t\n\/\/ RUN: %run %t 2>&1 | FileCheck %s\n\/\/ Verify that we can disable symbolization if needed:\n\/\/ RUN: UBSAN_OPTIONS=symbolize=0 ASAN_OPTIONS=symbolize=0 %run %t 2>&1 | FileCheck %s --check-prefix=NOSYM\n\n\/\/ -fsanitize=function is unsupported on Darwin yet.\n\/\/ XFAIL: darwin\n\n#include <stdint.h>\n\nvoid f() {}\n\nvoid g(int x) {}\n\nint main(void) {\n \/\/ CHECK: runtime error: call to function f() through pointer to incorrect function type 'void (*)(int)'\n \/\/ CHECK-NEXT: function.cpp:8: note: f() defined here\n \/\/ NOSYM: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int)'\n \/\/ NOSYM-NEXT: ({{.*}}+0x{{.*}}): note: (unknown) defined here\n reinterpret_cast<void (*)(int)>(reinterpret_cast<uintptr_t>(f))(42);\n\n \/\/ CHECK-NOT: runtime error: call to function g\n reinterpret_cast<void (*)(int)>(reinterpret_cast<uintptr_t>(g))(42);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Sofa\/Components\/MeshTopologyLoader.h\"\n#include \"Sofa\/Components\/Common\/Vec.h\"\n\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n\nnamespace Sofa\n{\n\nnamespace Components\n{\n\nusing namespace Common;\n\nstatic void skipToEOL(FILE* f)\n{\n int\tch;\n while ((ch = fgetc(f)) != EOF && ch != '\\n');\n}\n\nstatic bool readLine(char* buf, int size, FILE* f)\n{\n buf[0] = '\\0';\n if (fgets(buf, size, f) == NULL)\n return false;\n if ((int)strlen(buf)==size-1 && buf[size-1] != '\\n')\n skipToEOL(f);\n return true;\n}\n\nbool MeshTopologyLoader::load(const char *filename)\n{\n char cmd[1024];\n FILE* file;\n int npoints = 0;\n int nlines = 0;\n int ntris = 0;\n int nquads = 0;\n int ntetras = 0;\n int ncubes = 0;\n\n if ((file = fopen(filename, \"r\")) == NULL)\n {\n std::cout << \"ERROR: cannot read file '\" << filename << \"'. Exiting...\" << std::endl;\n return false;\n }\n \/\/ Check first line\n if (!readLine(cmd, sizeof(cmd), file))\n {\n fclose(file);\n return false;\n }\n std::cout << cmd << std::endl;\n if (!strncmp(cmd,\"$NOD\",4)) \/\/ Gmsh format\n {\n std::cout << \"Loading Gmsh topology '\" << filename << \"'\" << std::endl;\n fscanf(file, \"%d\\n\", &npoints);\n setNbPoints(npoints);\n std::vector<int> pmap;\n for (int i=0; i<npoints; ++i)\n {\n int index = i;\n double x,y,z;\n fscanf(file, \"%d %lf %lf %lf\\n\", &index, &x, &y, &z);\n addPoint(x, y, z);\n if ((int)pmap.size() <= index) pmap.resize(index+1);\n pmap[index] = i;\n }\n\n readLine(cmd, sizeof(cmd), file);\n \/\/std::cout << cmd << std::endl;\n if (strncmp(cmd,\"$ENDNOD\",7))\n {\n std::cerr << \"'$ENDNOD' expected, found '\" << cmd << \"'\" << std::endl;\n fclose(file);\n return false;\n }\n\n readLine(cmd, sizeof(cmd), file);\n \/\/std::cout << cmd << std::endl;\n if (strncmp(cmd,\"$ELM\",4))\n {\n std::cerr << \"'$ELM' expected, found '\" << cmd << \"'\" << std::endl;\n fclose(file);\n return false;\n }\n\n int nelems = 0;\n fscanf(file, \"%d\\n\", &nelems);\n\n for (int i=0; i<nelems; ++i)\n {\n int index, etype, rphys, relem, nnodes;\n fscanf(file, \"%d %d %d %d %d\", &index, &etype, &rphys, &relem, &nnodes);\n std::vector<int> nodes;\n nodes.resize(nnodes);\n for (int n=0; n<nnodes; ++n)\n {\n int t = 0;\n fscanf(file, \"%d\",&t);\n nodes[n] = (((unsigned int)t)<pmap.size())?pmap[t]:0;\n }\n switch (etype)\n {\n case 1: \/\/ Line\n if (nnodes == 2)\n {\n addLine(nodes[0], nodes[1]);\n ++nlines;\n }\n break;\n case 2: \/\/ Triangle\n if (nnodes == 3)\n {\n addTriangle(nodes[0], nodes[1], nodes[2]);\n ++ntris;\n }\n break;\n case 3: \/\/ Quad\n if (nnodes == 4)\n {\n addQuad(nodes[0], nodes[1], nodes[2], nodes[3]);\n ++nquads;\n }\n break;\n case 4: \/\/ Tetra\n if (nnodes == 4)\n {\n addTetra(nodes[0], nodes[1], nodes[2], nodes[3]);\n ++ntetras;\n }\n break;\n case 5: \/\/ Hexa\n if (nnodes == 8)\n {\n addCube(nodes[0], nodes[1], nodes[2], nodes[3],\n nodes[4], nodes[5], nodes[6], nodes[7]);\n ++ncubes;\n }\n break;\n }\n skipToEOL(file);\n }\n readLine(cmd, sizeof(cmd), file);\n std::cout << cmd << std::endl;\n if (strncmp(cmd,\"$ENDELM\",7))\n {\n std::cerr << \"'$ENDELM' expected, found '\" << cmd << \"'\" << std::endl;\n fclose(file);\n return false;\n }\n }\n else if (!strncmp(cmd,\"Xsp 3.0\",7))\n {\n int totalNumMasses;\n int totalNumSprings;\n\n \/\/\t\tskipToEOL(file);\n\n \/\/ then find out number of masses and springs\n if (fscanf(file, \"%s\", cmd) != EOF && !strcmp(cmd,\"numm\"))\n {\n fscanf(file, \"%d\", &totalNumMasses);\n setNbPoints(totalNumMasses);\n }\n if (fscanf(file, \"%s\", cmd) != EOF && !strcmp(cmd,\"nums\"))\n {\n fscanf(file, \"%d\", &totalNumSprings);\n setNbLines(totalNumSprings);\n\/\/\t\tsetNumSprings(totalNumSprings);\n }\n\n std::cout << \"Model contains \"<< totalNumMasses <<\" masses and \"<< totalNumSprings <<\" springs\"<<std::endl;\n\n\n\n while (fscanf(file, \"%s\", cmd) != EOF)\n {\n if (!strcmp(cmd,\"mass\"))\n {\n int index;\n char location;\n double px,py,pz,vx,vy,vz,mass=0.0,elastic=0.0;\n bool fixed=false;\n fscanf(file, \"%d %c %lf %lf %lf %lf %lf %lf %lf %lf\\n\",\n &index, &location,\n &px, &py, &pz, &vx, &vy, &vz,\n &mass, &elastic);\n\n if (mass < 0)\n {\n \/\/ fixed point initialization\n mass = -mass;\n fixed = true;\n }\n addPoint(px,py,pz);\n }\n else if (!strcmp(cmd,\"lspg\"))\t\/\/ linear springs connector\n {\n int\tindex;\n int m1,m2;\n double ks=0.0,kd=0.0,initpos=-1;\n fscanf(file, \"%d %d %d %lf %lf %lf\\n\", &index,\n &m1,&m2,&ks,&kd,&initpos);\n --m1;\n --m2;\n\n addLine(m1,m2);\n }\n else if (!strcmp(cmd,\"grav\"))\n {\n double gx,gy,gz;\n fscanf(file, \"%lf %lf %lf\\n\", &gx, &gy, &gz);\n }\n else if (!strcmp(cmd,\"visc\"))\n {\n double viscosity;\n fscanf(file, \"%lf\\n\", &viscosity);\n }\n else if (!strcmp(cmd,\"step\"))\n {\n \/\/fscanf(file, \"%lf\\n\", &(MSparams.default_dt));\n skipToEOL(file);\n }\n else if (!strcmp(cmd,\"frce\"))\n {\n skipToEOL(file);\n }\n else if (cmd[0] == '#')\t\/\/ it's a comment\n {\n skipToEOL(file);\n }\n else\t\t\/\/ it's an unknown keyword\n {\n printf(\"%s: Unknown MassSpring keyword: %s\\n\", filename, cmd);\n skipToEOL(file);\n }\n }\n fclose(file);\n }\n else\n {\n std::cout << \"Loading mesh topology '\" << filename << \"'\" << std::endl;\n while (fscanf(file, \"%s\", cmd) != EOF)\n {\n if (!strcmp(cmd,\"line\"))\n {\n int p1,p2;\n fscanf(file, \"%d %d\\n\",\n &p1, &p2);\n addLine(p1, p2);\n ++nlines;\n }\n else if (!strcmp(cmd,\"triangle\"))\n {\n int p1,p2,p3;\n fscanf(file, \"%d %d %d\\n\",\n &p1, &p2, &p3);\n addTriangle(p1, p2, p3);\n ++ntris;\n }\n else if (!strcmp(cmd,\"quad\"))\n {\n int p1,p2,p3,p4;\n fscanf(file, \"%d %d %d %d\\n\",\n &p1, &p2, &p3, &p4);\n addQuad(p1, p2, p3, p4);\n ++nquads;\n }\n else if (!strcmp(cmd,\"tetra\"))\n {\n int p1,p2,p3,p4;\n fscanf(file, \"%d %d %d %d\\n\",\n &p1, &p2, &p3, &p4);\n addTetra(p1, p2, p3, p4);\n ++ntetras;\n }\n else if (!strcmp(cmd,\"cube\"))\n {\n int p1,p2,p3,p4,p5,p6,p7,p8;\n fscanf(file, \"%d %d %d %d %d %d %d %d\\n\",\n &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8);\n addCube(p1, p2, p3, p4, p5, p6, p7, p8);\n ++ncubes;\n }\n else if (!strcmp(cmd,\"point\"))\n {\n double px,py,pz;\n fscanf(file, \"%lf %lf %lf\\n\",\n &px, &py, &pz);\n addPoint(px, py, pz);\n ++npoints;\n }\n else if (!strcmp(cmd,\"v\"))\n {\n double px,py,pz;\n fscanf(file, \"%lf %lf %lf\\n\",\n &px, &py, &pz);\n addPoint(px, py, pz);\n ++npoints;\n }\n else if (!strcmp(cmd,\"f\"))\n {\n int p1,p2,p3,p4=0;\n fscanf(file, \"%d %d %d %d\\n\",\n &p1, &p2, &p3, &p4);\n if (p4)\n {\n addQuad(p1-1, p2-1, p3-1, p4-1);\n ++nquads;\n }\n else\n {\n addTriangle(p1-1, p2-1, p3-1);\n ++ntris;\n }\n }\n else if (!strcmp(cmd,\"mass\"))\n {\n int index;\n char location;\n double px,py,pz,vx,vy,vz,mass=0.0,elastic=0.0;\n fscanf(file, \"%d %c %lf %lf %lf %lf %lf %lf %lf %lf\\n\",\n &index, &location,\n &px, &py, &pz, &vx, &vy, &vz,\n &mass, &elastic);\n addPoint(px, py, pz);\n ++npoints;\n }\n else if (!strcmp(cmd,\"lspg\"))\n {\n int\tindex;\n int m1,m2;\n double ks=0.0,kd=0.0,initpos=-1;\n fscanf(file, \"%d %d %d %lf %lf %lf\\n\", &index,\n &m1,&m2,&ks,&kd,&initpos);\n --m1;\n --m2;\n addLine(m1,m2);\n ++nlines;\n }\n else if (cmd[0] == '#')\t\/\/ it's a comment\n {\n skipToEOL(file);\n }\n else\t\t\/\/ it's an unknown keyword\n {\n printf(\"%s: Unknown Mesh keyword: %s\\n\", filename, cmd);\n skipToEOL(file);\n return false;\n }\n }\n }\n std::cout << \"Loading topology complete:\";\n if (npoints>0) std::cout << ' ' << npoints << \" points\";\n if (nlines>0) std::cout << ' ' << nlines << \" lines\";\n if (ntris>0) std::cout << ' ' << ntris << \" triangles\";\n if (nquads>0) std::cout << ' ' << nquads << \" quads\";\n if (ntetras>0) std::cout << ' ' << ntetras << \" tetrahedra\";\n if (ncubes>0) std::cout << ' ' << ncubes << \" cubes\";\n std::cout << std::endl;\n fclose(file);\n return true;\n}\n\n} \/\/ namespace Components\n\n} \/\/ namespace Sofa\n<commit_msg>r718\/sofa-dev : bug corrected<commit_after>#include \"Sofa\/Components\/MeshTopologyLoader.h\"\n#include \"Sofa\/Components\/Common\/Vec.h\"\n\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n\nnamespace Sofa\n{\n\nnamespace Components\n{\n\nusing namespace Common;\n\nstatic void skipToEOL(FILE* f)\n{\n int\tch;\n while ((ch = fgetc(f)) != EOF && ch != '\\n');\n}\n\nstatic bool readLine(char* buf, int size, FILE* f)\n{\n buf[0] = '\\0';\n if (fgets(buf, size, f) == NULL)\n return false;\n if ((int)strlen(buf)==size-1 && buf[size-1] != '\\n')\n skipToEOL(f);\n return true;\n}\n\nbool MeshTopologyLoader::load(const char *filename)\n{\n char cmd[1024];\n FILE* file;\n int npoints = 0;\n int nlines = 0;\n int ntris = 0;\n int nquads = 0;\n int ntetras = 0;\n int ncubes = 0;\n\n if ((file = fopen(filename, \"r\")) == NULL)\n {\n std::cout << \"ERROR: cannot read file '\" << filename << \"'. Exiting...\" << std::endl;\n return false;\n }\n \/\/ Check first line\n if (!readLine(cmd, sizeof(cmd), file))\n {\n fclose(file);\n return false;\n }\n std::cout << cmd << std::endl;\n if (!strncmp(cmd,\"$NOD\",4)) \/\/ Gmsh format\n {\n std::cout << \"Loading Gmsh topology '\" << filename << \"'\" << std::endl;\n fscanf(file, \"%d\\n\", &npoints);\n setNbPoints(npoints);\n std::vector<int> pmap;\n for (int i=0; i<npoints; ++i)\n {\n int index = i;\n double x,y,z;\n fscanf(file, \"%d %lf %lf %lf\\n\", &index, &x, &y, &z);\n addPoint(x, y, z);\n if ((int)pmap.size() <= index) pmap.resize(index+1);\n pmap[index] = i;\n }\n\n readLine(cmd, sizeof(cmd), file);\n \/\/std::cout << cmd << std::endl;\n if (strncmp(cmd,\"$ENDNOD\",7))\n {\n std::cerr << \"'$ENDNOD' expected, found '\" << cmd << \"'\" << std::endl;\n fclose(file);\n return false;\n }\n\n readLine(cmd, sizeof(cmd), file);\n \/\/std::cout << cmd << std::endl;\n if (strncmp(cmd,\"$ELM\",4))\n {\n std::cerr << \"'$ELM' expected, found '\" << cmd << \"'\" << std::endl;\n fclose(file);\n return false;\n }\n\n int nelems = 0;\n fscanf(file, \"%d\\n\", &nelems);\n\n for (int i=0; i<nelems; ++i)\n {\n int index, etype, rphys, relem, nnodes;\n fscanf(file, \"%d %d %d %d %d\", &index, &etype, &rphys, &relem, &nnodes);\n std::vector<int> nodes;\n nodes.resize(nnodes);\n for (int n=0; n<nnodes; ++n)\n {\n int t = 0;\n fscanf(file, \"%d\",&t);\n nodes[n] = (((unsigned int)t)<pmap.size())?pmap[t]:0;\n }\n switch (etype)\n {\n case 1: \/\/ Line\n if (nnodes == 2)\n {\n addLine(nodes[0], nodes[1]);\n ++nlines;\n }\n break;\n case 2: \/\/ Triangle\n if (nnodes == 3)\n {\n addTriangle(nodes[0], nodes[1], nodes[2]);\n ++ntris;\n }\n break;\n case 3: \/\/ Quad\n if (nnodes == 4)\n {\n addQuad(nodes[0], nodes[1], nodes[2], nodes[3]);\n ++nquads;\n }\n break;\n case 4: \/\/ Tetra\n if (nnodes == 4)\n {\n addTetra(nodes[0], nodes[1], nodes[2], nodes[3]);\n ++ntetras;\n }\n break;\n case 5: \/\/ Hexa\n if (nnodes == 8)\n {\n addCube(nodes[0], nodes[1], nodes[2], nodes[3],\n nodes[4], nodes[5], nodes[6], nodes[7]);\n ++ncubes;\n }\n break;\n }\n skipToEOL(file);\n }\n readLine(cmd, sizeof(cmd), file);\n std::cout << cmd << std::endl;\n if (strncmp(cmd,\"$ENDELM\",7))\n {\n std::cerr << \"'$ENDELM' expected, found '\" << cmd << \"'\" << std::endl;\n fclose(file);\n return false;\n }\n }\n else if (!strncmp(cmd,\"Xsp 3.0\",7))\n {\n int totalNumMasses;\n int totalNumSprings;\n\n \/\/\t\tskipToEOL(file);\n\n \/\/ then find out number of masses and springs\n if (fscanf(file, \"%s\", cmd) != EOF && !strcmp(cmd,\"numm\"))\n {\n fscanf(file, \"%d\", &totalNumMasses);\n setNbPoints(totalNumMasses);\n npoints=totalNumMasses;\n }\n if (fscanf(file, \"%s\", cmd) != EOF && !strcmp(cmd,\"nums\"))\n {\n fscanf(file, \"%d\", &totalNumSprings);\n setNbLines(totalNumSprings);\n nlines=totalNumSprings;\n \/\/\t\tsetNumSprings(totalNumSprings);\n }\n\n \/\/std::cout << \"Model contains \"<< totalNumMasses <<\" masses and \"<< totalNumSprings <<\" springs\"<<std::endl;\n\n\n\n while (fscanf(file, \"%s\", cmd) != EOF)\n {\n if (!strcmp(cmd,\"mass\"))\n {\n int index;\n char location;\n double px,py,pz,vx,vy,vz,mass=0.0,elastic=0.0;\n bool fixed=false;\n fscanf(file, \"%d %c %lf %lf %lf %lf %lf %lf %lf %lf\\n\",\n &index, &location,\n &px, &py, &pz, &vx, &vy, &vz,\n &mass, &elastic);\n\n if (mass < 0)\n {\n \/\/ fixed point initialization\n mass = -mass;\n fixed = true;\n }\n addPoint(px,py,pz);\n }\n else if (!strcmp(cmd,\"lspg\"))\t\/\/ linear springs connector\n {\n int\tindex;\n int m1,m2;\n double ks=0.0,kd=0.0,initpos=-1;\n fscanf(file, \"%d %d %d %lf %lf %lf\\n\", &index,\n &m1,&m2,&ks,&kd,&initpos);\n --m1;\n --m2;\n\n addLine(m1,m2);\n }\n else if (!strcmp(cmd,\"grav\"))\n {\n double gx,gy,gz;\n fscanf(file, \"%lf %lf %lf\\n\", &gx, &gy, &gz);\n }\n else if (!strcmp(cmd,\"visc\"))\n {\n double viscosity;\n fscanf(file, \"%lf\\n\", &viscosity);\n }\n else if (!strcmp(cmd,\"step\"))\n {\n \/\/fscanf(file, \"%lf\\n\", &(MSparams.default_dt));\n skipToEOL(file);\n }\n else if (!strcmp(cmd,\"frce\"))\n {\n skipToEOL(file);\n }\n else if (cmd[0] == '#')\t\/\/ it's a comment\n {\n skipToEOL(file);\n }\n else\t\t\/\/ it's an unknown keyword\n {\n printf(\"%s: Unknown MassSpring keyword: %s\\n\", filename, cmd);\n skipToEOL(file);\n }\n }\n }\n else\n {\n std::cout << \"Loading mesh topology '\" << filename << \"'\" << std::endl;\n while (fscanf(file, \"%s\", cmd) != EOF)\n {\n if (!strcmp(cmd,\"line\"))\n {\n int p1,p2;\n fscanf(file, \"%d %d\\n\",\n &p1, &p2);\n addLine(p1, p2);\n ++nlines;\n }\n else if (!strcmp(cmd,\"triangle\"))\n {\n int p1,p2,p3;\n fscanf(file, \"%d %d %d\\n\",\n &p1, &p2, &p3);\n addTriangle(p1, p2, p3);\n ++ntris;\n }\n else if (!strcmp(cmd,\"quad\"))\n {\n int p1,p2,p3,p4;\n fscanf(file, \"%d %d %d %d\\n\",\n &p1, &p2, &p3, &p4);\n addQuad(p1, p2, p3, p4);\n ++nquads;\n }\n else if (!strcmp(cmd,\"tetra\"))\n {\n int p1,p2,p3,p4;\n fscanf(file, \"%d %d %d %d\\n\",\n &p1, &p2, &p3, &p4);\n addTetra(p1, p2, p3, p4);\n ++ntetras;\n }\n else if (!strcmp(cmd,\"cube\"))\n {\n int p1,p2,p3,p4,p5,p6,p7,p8;\n fscanf(file, \"%d %d %d %d %d %d %d %d\\n\",\n &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8);\n addCube(p1, p2, p3, p4, p5, p6, p7, p8);\n ++ncubes;\n }\n else if (!strcmp(cmd,\"point\"))\n {\n double px,py,pz;\n fscanf(file, \"%lf %lf %lf\\n\",\n &px, &py, &pz);\n addPoint(px, py, pz);\n ++npoints;\n }\n else if (!strcmp(cmd,\"v\"))\n {\n double px,py,pz;\n fscanf(file, \"%lf %lf %lf\\n\",\n &px, &py, &pz);\n addPoint(px, py, pz);\n ++npoints;\n }\n else if (!strcmp(cmd,\"f\"))\n {\n int p1,p2,p3,p4=0;\n fscanf(file, \"%d %d %d %d\\n\",\n &p1, &p2, &p3, &p4);\n if (p4)\n {\n addQuad(p1-1, p2-1, p3-1, p4-1);\n ++nquads;\n }\n else\n {\n addTriangle(p1-1, p2-1, p3-1);\n ++ntris;\n }\n }\n else if (!strcmp(cmd,\"mass\"))\n {\n int index;\n char location;\n double px,py,pz,vx,vy,vz,mass=0.0,elastic=0.0;\n fscanf(file, \"%d %c %lf %lf %lf %lf %lf %lf %lf %lf\\n\",\n &index, &location,\n &px, &py, &pz, &vx, &vy, &vz,\n &mass, &elastic);\n addPoint(px, py, pz);\n ++npoints;\n }\n else if (!strcmp(cmd,\"lspg\"))\n {\n int\tindex;\n int m1,m2;\n double ks=0.0,kd=0.0,initpos=-1;\n fscanf(file, \"%d %d %d %lf %lf %lf\\n\", &index,\n &m1,&m2,&ks,&kd,&initpos);\n --m1;\n --m2;\n addLine(m1,m2);\n ++nlines;\n }\n else if (cmd[0] == '#')\t\/\/ it's a comment\n {\n skipToEOL(file);\n }\n else\t\t\/\/ it's an unknown keyword\n {\n printf(\"%s: Unknown Mesh keyword: %s\\n\", filename, cmd);\n skipToEOL(file);\n return false;\n }\n }\n }\n std::cout << \"Loading topology complete:\";\n if (npoints>0) std::cout << ' ' << npoints << \" points\";\n if (nlines>0) std::cout << ' ' << nlines << \" lines\";\n if (ntris>0) std::cout << ' ' << ntris << \" triangles\";\n if (nquads>0) std::cout << ' ' << nquads << \" quads\";\n if (ntetras>0) std::cout << ' ' << ntetras << \" tetrahedra\";\n if (ncubes>0) std::cout << ' ' << ncubes << \" cubes\";\n std::cout << std::endl;\n fclose(file);\n return true;\n}\n\n} \/\/ namespace Components\n\n} \/\/ namespace Sofa\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com>\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 License\n along with this library; see the file COPYING.LGPL. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n Alternatively, this file is available under the Mozilla Public License\n Version 1.1. You may obtain a copy of the License at\n http:\/\/www.mozilla.org\/MPL\/\n*\/\n\n#include \"arguments.h\"\n#include \"connectaddress.h\"\n#include \"eventdispatcher.h\"\n#include \"imessagereceiver.h\"\n#include \"message.h\"\n#include \"pendingreply.h\"\n#include \"connection.h\"\n\n#include \"..\/testutil.h\"\n\n#include <iostream>\n#include <string>\n\nstatic void addressMessageToBus(Message *msg)\n{\n msg->setType(Message::MethodCallMessage);\n msg->setDestination(\"org.freedesktop.DBus\");\n msg->setInterface(\"org.freedesktop.DBus\");\n msg->setPath(\"\/org\/freedesktop\/DBus\");\n}\n\nclass ReplyCheck : public IMessageReceiver\n{\npublic:\n EventDispatcher *m_eventDispatcher;\n void handlePendingReplyFinished(PendingReply *pr) override\n {\n pr->dumpState();\n std::cout << \"got it!\\n\" << pr->reply()->arguments().prettyPrint();\n TEST(pr->isFinished());\n TEST(!pr->isError());\n\n \/\/ This is really a different test, it used to reproduce a memory leak under Valgrind\n Message reply = pr->takeReply();\n\n m_eventDispatcher->interrupt();\n }\n};\n\nstatic void testBusAddress(bool waitForConnected)\n{\n EventDispatcher eventDispatcher;\n Connection conn(&eventDispatcher, ConnectAddress::StandardBus::Session);\n\n Message msg;\n addressMessageToBus(&msg);\n msg.setMethod(\"RequestName\");\n\n Arguments::Writer writer;\n writer.writeString(\"Bana.nana\"); \/\/ requested name\n writer.writeUint32(4); \/\/ TODO proper enum or so: 4 == DBUS_NAME_FLAG_DO_NOT_QUEUE\n msg.setArguments(writer.finish());\n\n if (waitForConnected) {\n \/\/ finish creating the connection\n while (conn.uniqueName().empty()) {\n eventDispatcher.poll();\n }\n }\n\n PendingReply busNameReply = conn.send(std::move(msg));\n ReplyCheck replyCheck;\n replyCheck.m_eventDispatcher = &eventDispatcher;\n busNameReply.setReceiver(&replyCheck);\n\n while (eventDispatcher.poll()) {\n }\n}\n\nclass TimeoutCheck : public IMessageReceiver\n{\npublic:\n EventDispatcher *m_eventDispatcher;\n void handlePendingReplyFinished(PendingReply *reply) override\n {\n TEST(reply->isFinished());\n TEST(!reply->hasNonErrorReply());\n TEST(reply->error().code() == Error::Timeout);\n std::cout << \"We HAVE timed out.\\n\";\n m_eventDispatcher->interrupt();\n }\n};\n\nstatic void testTimeout()\n{\n EventDispatcher eventDispatcher;\n Connection conn(&eventDispatcher, ConnectAddress::StandardBus::Session);\n\n \/\/ finish creating the connection; we need to know our own name so we can send the message to\n \/\/ ourself so we can make sure that there will be no reply :)\n while (conn.uniqueName().empty()) {\n eventDispatcher.poll();\n }\n\n Message msg = Message::createCall(\"\/some\/dummy\/path\/lol\", \"dummy_interface\", \"non_existent_method\");\n msg.setDestination(conn.uniqueName());\n\n PendingReply neverGonnaGetReply = conn.send(std::move(msg), 200);\n TimeoutCheck timeoutCheck;\n timeoutCheck.m_eventDispatcher = &eventDispatcher;\n neverGonnaGetReply.setReceiver(&timeoutCheck);\n\n while (eventDispatcher.poll()) {\n }\n}\n\nint main(int, char *[])\n{\n testBusAddress(false);\n testBusAddress(true);\n testTimeout();\n \/\/ TODO testBadCall\n std::cout << \"Passed!\\n\";\n}\n<commit_msg>Make this dummy interface name valid according to spec<commit_after>\/*\n Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com>\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 License\n along with this library; see the file COPYING.LGPL. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n Alternatively, this file is available under the Mozilla Public License\n Version 1.1. You may obtain a copy of the License at\n http:\/\/www.mozilla.org\/MPL\/\n*\/\n\n#include \"arguments.h\"\n#include \"connectaddress.h\"\n#include \"eventdispatcher.h\"\n#include \"imessagereceiver.h\"\n#include \"message.h\"\n#include \"pendingreply.h\"\n#include \"connection.h\"\n\n#include \"..\/testutil.h\"\n\n#include <iostream>\n#include <string>\n\nstatic void addressMessageToBus(Message *msg)\n{\n msg->setType(Message::MethodCallMessage);\n msg->setDestination(\"org.freedesktop.DBus\");\n msg->setInterface(\"org.freedesktop.DBus\");\n msg->setPath(\"\/org\/freedesktop\/DBus\");\n}\n\nclass ReplyCheck : public IMessageReceiver\n{\npublic:\n EventDispatcher *m_eventDispatcher;\n void handlePendingReplyFinished(PendingReply *pr) override\n {\n pr->dumpState();\n std::cout << \"got it!\\n\" << pr->reply()->arguments().prettyPrint();\n TEST(pr->isFinished());\n TEST(!pr->isError());\n\n \/\/ This is really a different test, it used to reproduce a memory leak under Valgrind\n Message reply = pr->takeReply();\n\n m_eventDispatcher->interrupt();\n }\n};\n\nstatic void testBusAddress(bool waitForConnected)\n{\n EventDispatcher eventDispatcher;\n Connection conn(&eventDispatcher, ConnectAddress::StandardBus::Session);\n\n Message msg;\n addressMessageToBus(&msg);\n msg.setMethod(\"RequestName\");\n\n Arguments::Writer writer;\n writer.writeString(\"Bana.nana\"); \/\/ requested name\n writer.writeUint32(4); \/\/ TODO proper enum or so: 4 == DBUS_NAME_FLAG_DO_NOT_QUEUE\n msg.setArguments(writer.finish());\n\n if (waitForConnected) {\n \/\/ finish creating the connection\n while (conn.uniqueName().empty()) {\n eventDispatcher.poll();\n }\n }\n\n PendingReply busNameReply = conn.send(std::move(msg));\n ReplyCheck replyCheck;\n replyCheck.m_eventDispatcher = &eventDispatcher;\n busNameReply.setReceiver(&replyCheck);\n\n while (eventDispatcher.poll()) {\n }\n}\n\nclass TimeoutCheck : public IMessageReceiver\n{\npublic:\n EventDispatcher *m_eventDispatcher;\n void handlePendingReplyFinished(PendingReply *reply) override\n {\n TEST(reply->isFinished());\n TEST(!reply->hasNonErrorReply());\n TEST(reply->error().code() == Error::Timeout);\n std::cout << \"We HAVE timed out.\\n\";\n m_eventDispatcher->interrupt();\n }\n};\n\nstatic void testTimeout()\n{\n EventDispatcher eventDispatcher;\n Connection conn(&eventDispatcher, ConnectAddress::StandardBus::Session);\n\n \/\/ finish creating the connection; we need to know our own name so we can send the message to\n \/\/ ourself so we can make sure that there will be no reply :)\n while (conn.uniqueName().empty()) {\n eventDispatcher.poll();\n }\n\n Message msg = Message::createCall(\"\/some\/dummy\/path\", \"org.no_interface\", \"non_existent_method\");\n msg.setDestination(conn.uniqueName());\n\n PendingReply neverGonnaGetReply = conn.send(std::move(msg), 200);\n TimeoutCheck timeoutCheck;\n timeoutCheck.m_eventDispatcher = &eventDispatcher;\n neverGonnaGetReply.setReceiver(&timeoutCheck);\n\n while (eventDispatcher.poll()) {\n }\n}\n\nint main(int, char *[])\n{\n testBusAddress(false);\n testBusAddress(true);\n testTimeout();\n \/\/ TODO testBadCall\n std::cout << \"Passed!\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2014 P.L. Lucas <selairi@gmail.com>\n Copyright (C) 2014 Hong Jen Yee (PCMan) <pcman.tw@gmail.com>\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; 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. See the\n 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 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*\/\n\n#include \"xrandr.h\"\n#include <QProcess>\n#include <QDebug>\n#include <QRegExp>\n#include <QObject>\n#include <QDir>\n#include <QVector>\n\nstatic QByteArray indentString(QByteArray line) {\n QByteArray s;\n int length = line.size();\n char ch;\n for(int indent=0; indent < length; indent++ ) {\n ch = line[indent];\n if( ch == ' ' || ch == '\\t' )\n s.append(ch);\n else\n break;\n }\n return s;\n}\n\nstatic int indentLevel(QByteArray line) {\n int indent = 0;\n while(indent < line.size() && ( line[indent] == ' ' || line[indent] == '\\t' ) )\n ++indent;\n return indent;\n}\n\n\/\/ new parsing code using xrandr --verbose\nQList<MonitorInfo*> XRandRBackend::getMonitorsInfo() {\n QList<MonitorInfo*> monitors;\n \/\/ execute xrandr command and read its output\n QProcess process;\n \/\/ set locale to \"C\" guarantee English output of xrandr\n process.processEnvironment().insert(\"LC_ALL\", \"c\");\n process.start(\"xrandr --verbose\");\n process.waitForFinished(-1);\n if(process.exitCode() != 0)\n return monitors;\n QList<QByteArray> lines = process.readAllStandardOutput().split('\\n');\n \/\/ start parsing the output\n QRegExp regMonitorLine(\"([\\\\w-]+) +connected +(primary)? *(\\\\d+x\\\\d+\\\\+(\\\\d+)\\\\+(\\\\d+))?.*\");\n QRegExp regModeLine(\"\\\\s+(\\\\d+x\\\\d+).*\");\n QRegExp regRateLine(\"\\\\s+([vh]):.* clock\\\\s+([\\\\d.]+).?Hz.*\");\n QRegExp regKeyValue(\"\\\\s*(\\\\w[\\\\w ]*)\\\\s*:\\\\s*(\\\\S.*)?\");\n\n bool hasError = false;\n MonitorInfo* monitor = NULL;\n QList<QByteArray>::iterator it = lines.begin();\n bool readingModes = false;\n \/\/ currently, we only support one X screen, that is screen 0\n while(it != lines.end() && !hasError) {\n QByteArray& line = *it;\n if(!monitor) {\n if(regMonitorLine.exactMatch(line)) {\n \/\/ format: VGA-0 connected 1280x1024+1024+0 (0x55) normal...\n monitor = new MonitorInfo();\n monitor->name = regMonitorLine.cap(1);\n if(regMonitorLine.cap(2) == \"primary\") { \/\/ is primary monitor\n monitor->primaryOk = true;\n }\n if(!regMonitorLine.cap(3).isEmpty()) \/\/ mode+xpos+ypos\n monitor->enabledOk = true;\n monitor->xPos = regMonitorLine.cap(4).toInt();\n monitor->yPos = regMonitorLine.cap(5).toInt();\n }\n }\n else { \/\/ reading properties of this monitor\n if(regModeLine.exactMatch(line)) { \/\/ this is a mode line\n \/\/ sample: 1280x1024 (0x55) 108.000MHz +HSync +VSync *current +preferred\n readingModes = true;\n QString mode = regModeLine.cap(1);\n QString rate;\n bool isCurrent = line.contains(\"current\");\n bool isPreferred = line.contains(\"preferred\");\n ++it;\n while(it != lines.end()) {\n line = *it;\n if(regRateLine.exactMatch(line)) {\n \/\/ sample:\n \/\/ h: width 1280 start 1328 end 1440 total 1688 skew 0 clock 63.98KHz\n \/\/ v: height 1024 start 1025 end 1028 total 1066 clock 60.02Hz\n if(regRateLine.cap(1) == QLatin1String(\"v\"))\n rate = regRateLine.cap(2);\n ++it;\n }\n else {\n --it;\n break; \/\/ rate lines ended for this mode\n }\n }\n if(!mode.isEmpty() && !rate.isEmpty()) {\n if(!monitor->modes.contains(mode))\n monitor->modes.append(mode);\n if(!monitor->modeLines.contains(mode))\n monitor->modeLines[mode] = QStringList();\n monitor->modeLines[mode].append(rate);\n if(isPreferred) {\n monitor->preferredMode = mode;\n monitor->preferredRate = rate;\n }\n if(isCurrent) {\n monitor->currentMode = mode;\n monitor->currentRate = rate;\n }\n }\n }\n else { \/\/ this is not a mode line, read other properties\n if(readingModes) {\n \/\/ mode lines ended, so the whole monitor info is read\n monitors.append(monitor);\n monitor = NULL;\n readingModes = false;\n continue;\n }\n\n if(regKeyValue.exactMatch(line)) { \/\/ format: <key>: <value>\n QString key = regKeyValue.cap(1);\n QString value = regKeyValue.cap(2);\n QByteArray lineStringStart = indentString(line);\n int propertyIndentLevel = indentLevel(line);\n ++it;\n while( it != lines.end() ) {\n QByteArray& line = *it;\n int actualIndentLevel = indentLevel(line);\n if( actualIndentLevel>propertyIndentLevel && line.startsWith(lineStringStart) ) {\n value += \"\\n\" + line.trimmed();\n ++it;\n } else\n break;\n }\n qDebug() << key << \"=\" << value;\n if(key == \"Gamma\") {\n monitor->gamma = value;\n }\n else if(key == \"Brightness\") {\n monitor->brightness = value;\n }\n else if(key == \"EDID\") {\n monitor->edid = value ;\n \/\/ Get vendor\n QString hex = value.replace(\"\\n\",\"\").replace(\" \",\"\").toLower();\n int vendorPosStart = hex.indexOf(\"fc00\");\n if(vendorPosStart>0) {\n int vendorPosEnd = hex.indexOf(\"00\", vendorPosStart+4);\n QString vendorHex = hex.mid(vendorPosStart+4, vendorPosEnd-vendorPosStart-4);\n QByteArray vendor = QByteArray::fromHex(vendorHex.toLocal8Bit()).trimmed();\n \/\/ qDebug() << \"Vendor:\" << vendorHex << \"VendorHex\" << vendor ;\n monitor->vendor = vendor;\n }\n }\n continue;\n } \/\/ End format: <key>: <value>\n else { \/\/ this line is not key:value\n }\n }\n }\n if( it != lines.end() ) ++it;\n }\n\n if(monitor) \/\/ this should not happen unless a parsing error happens\n delete monitor;\n\n resolvePositions(monitors);\n\n \n return monitors;\n}\n\n\n\nbool XRandRBackend::setMonitorsSettings(const QList<MonitorSettings*> monitors) {\n QString cmd = getCommand(monitors);\n QProcess process;\n process.start(cmd);\n process.waitForFinished();\n return process.exitCode() == 0;\n}\n\n\n\n\nQString XRandRBackend::getCommand(const QList<MonitorSettings*> monitors) {\n QMap<MonitorSettings::Position, QString> positions;\n\n positions[MonitorSettings::Left] = \"--left-of\";\n positions[MonitorSettings::Right] = \"--right-of\";\n positions[MonitorSettings::Above] = \"--above\";\n positions[MonitorSettings::Bellow] = \"--below\";\n\n\n QByteArray cmd = \"xrandr\";\n\n foreach(MonitorSettings * monitor, monitors) {\n cmd += \" --output \";\n cmd.append(monitor->name);\n cmd.append(' ');\n\n \/\/ if the monitor is turned on\n if(monitor->enabledOk) {\n QString sel_res = monitor->currentMode;\n QString sel_rate = monitor->currentRate;\n\n if(sel_res == QObject::tr(\"Auto\")) \/\/ auto resolution\n cmd.append(\"--auto\");\n else {\n cmd.append(\"--mode \");\n cmd.append(sel_res);\n if(sel_rate != QObject::tr(\"Auto\")) { \/\/ not auto refresh rate\n cmd.append(\" --rate \");\n cmd.append(sel_rate);\n }\n }\n if(monitor->position != MonitorSettings::None) {\n cmd.append(\" \");\n cmd.append(positions[monitor->position]);\n cmd.append(\" \");\n cmd.append(monitor->positionRelativeToOutput);\n }\n if(monitor->primaryOk)\n cmd.append(\" --primary\");\n cmd.append(\" --brightness \");\n cmd.append(monitor->brightness);\n cmd.append(\" --gamma \");\n cmd.append(monitor->gamma);\n }\n else \/\/ turn off\n cmd.append(\"--off\");\n }\n\n\n qDebug() << \"cmd:\" << cmd;\n return cmd;\n}\n\n\/\/ resolve the position relationship among the montors\nvoid XRandRBackend::resolvePositions(QList< MonitorInfo* >& monitors) {\n Q_FOREACH(MonitorInfo * monitor, monitors) {\n MonitorSettings::Position pos;\n MonitorInfo* neighbor = findAdjacentMonitor(monitors, monitor, pos);\n if(neighbor) {\n monitor->position = pos;\n monitor->positionRelativeToOutput = neighbor->name;\n }\n }\n}\n\nMonitorInfo* XRandRBackend::findAdjacentMonitor(QList< MonitorInfo* >& monitors, MonitorInfo* monitor, MonitorSettings::Position& pos) {\n MonitorInfo* neighbor = NULL;\n QRect monitorRect = monitor->geometry();\n pos = MonitorSettings::None;\n Q_FOREACH(MonitorInfo * mon, monitors) {\n if(mon == monitor || mon->positionRelativeToOutput == monitor->name)\n continue;\n QRect neighborRect = mon->geometry();\n if(monitorRect.top() == neighborRect.top()) {\n if((monitorRect.right() + 1) == neighborRect.left()) { \/\/ monitor is at left of neighbor\n pos = MonitorSettings::Left;\n neighbor = mon;\n break;\n }\n else if(monitorRect.left() == (neighborRect.right() + 1)) { \/\/ monitor is at right of neighbor\n pos = MonitorSettings::Right;\n neighbor = mon;\n break;\n }\n }\n if(monitorRect.left() == neighborRect.left()) {\n if((monitorRect.bottom() + 1) == neighborRect.top()) { \/\/ monitor is above neighbor\n pos = MonitorSettings::Above;\n neighbor = mon;\n break;\n }\n else if(monitorRect.top() == (neighborRect.bottom() + 1)) { \/\/ monitor is below neighbor\n pos = MonitorSettings::Bellow;\n neighbor = mon;\n break;\n }\n }\n }\n return neighbor;\n}\n<commit_msg>Fixed: Restore position of monitor when user cancels settings.<commit_after>\/*\n Copyright (C) 2014 P.L. Lucas <selairi@gmail.com>\n Copyright (C) 2014 Hong Jen Yee (PCMan) <pcman.tw@gmail.com>\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; 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. See the\n 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 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*\/\n\n#include \"xrandr.h\"\n#include <QProcess>\n#include <QDebug>\n#include <QRegExp>\n#include <QObject>\n#include <QDir>\n#include <QVector>\n\nstatic QByteArray indentString(QByteArray line) {\n QByteArray s;\n int length = line.size();\n char ch;\n for(int indent=0; indent < length; indent++ ) {\n ch = line[indent];\n if( ch == ' ' || ch == '\\t' )\n s.append(ch);\n else\n break;\n }\n return s;\n}\n\nstatic int indentLevel(QByteArray line) {\n int indent = 0;\n while(indent < line.size() && ( line[indent] == ' ' || line[indent] == '\\t' ) )\n ++indent;\n return indent;\n}\n\n\/\/ new parsing code using xrandr --verbose\nQList<MonitorInfo*> XRandRBackend::getMonitorsInfo() {\n QList<MonitorInfo*> monitors;\n \/\/ execute xrandr command and read its output\n QProcess process;\n \/\/ set locale to \"C\" guarantee English output of xrandr\n process.processEnvironment().insert(\"LC_ALL\", \"c\");\n process.start(\"xrandr --verbose\");\n process.waitForFinished(-1);\n if(process.exitCode() != 0)\n return monitors;\n QList<QByteArray> lines = process.readAllStandardOutput().split('\\n');\n \/\/ start parsing the output\n QRegExp regMonitorLine(\"([\\\\w-]+) +connected +(primary)? *(\\\\d+x\\\\d+\\\\+(\\\\d+)\\\\+(\\\\d+))?.*\");\n QRegExp regModeLine(\"\\\\s+(\\\\d+x\\\\d+).*\");\n QRegExp regRateLine(\"\\\\s+([vh]):.* clock\\\\s+([\\\\d.]+).?Hz.*\");\n QRegExp regKeyValue(\"\\\\s*(\\\\w[\\\\w ]*)\\\\s*:\\\\s*(\\\\S.*)?\");\n\n bool hasError = false;\n MonitorInfo* monitor = NULL;\n QList<QByteArray>::iterator it = lines.begin();\n bool readingModes = false;\n \/\/ currently, we only support one X screen, that is screen 0\n while(it != lines.end() && !hasError) {\n QByteArray& line = *it;\n if(!monitor) {\n if(regMonitorLine.exactMatch(line)) {\n \/\/ format: VGA-0 connected 1280x1024+1024+0 (0x55) normal...\n monitor = new MonitorInfo();\n monitor->name = regMonitorLine.cap(1);\n if(regMonitorLine.cap(2) == \"primary\") { \/\/ is primary monitor\n monitor->primaryOk = true;\n }\n if(!regMonitorLine.cap(3).isEmpty()) \/\/ mode+xpos+ypos\n monitor->enabledOk = true;\n monitor->xPos = regMonitorLine.cap(4).toInt();\n monitor->yPos = regMonitorLine.cap(5).toInt();\n }\n }\n else { \/\/ reading properties of this monitor\n if(regModeLine.exactMatch(line)) { \/\/ this is a mode line\n \/\/ sample: 1280x1024 (0x55) 108.000MHz +HSync +VSync *current +preferred\n readingModes = true;\n QString mode = regModeLine.cap(1);\n QString rate;\n bool isCurrent = line.contains(\"current\");\n bool isPreferred = line.contains(\"preferred\");\n ++it;\n while(it != lines.end()) {\n line = *it;\n if(regRateLine.exactMatch(line)) {\n \/\/ sample:\n \/\/ h: width 1280 start 1328 end 1440 total 1688 skew 0 clock 63.98KHz\n \/\/ v: height 1024 start 1025 end 1028 total 1066 clock 60.02Hz\n if(regRateLine.cap(1) == QLatin1String(\"v\"))\n rate = regRateLine.cap(2);\n ++it;\n }\n else {\n --it;\n break; \/\/ rate lines ended for this mode\n }\n }\n if(!mode.isEmpty() && !rate.isEmpty()) {\n if(!monitor->modes.contains(mode))\n monitor->modes.append(mode);\n if(!monitor->modeLines.contains(mode))\n monitor->modeLines[mode] = QStringList();\n monitor->modeLines[mode].append(rate);\n if(isPreferred) {\n monitor->preferredMode = mode;\n monitor->preferredRate = rate;\n }\n if(isCurrent) {\n monitor->currentMode = mode;\n monitor->currentRate = rate;\n }\n }\n }\n else { \/\/ this is not a mode line, read other properties\n if(readingModes) {\n \/\/ mode lines ended, so the whole monitor info is read\n monitors.append(monitor);\n monitor = NULL;\n readingModes = false;\n continue;\n }\n\n if(regKeyValue.exactMatch(line)) { \/\/ format: <key>: <value>\n QString key = regKeyValue.cap(1);\n QString value = regKeyValue.cap(2);\n QByteArray lineStringStart = indentString(line);\n int propertyIndentLevel = indentLevel(line);\n ++it;\n while( it != lines.end() ) {\n QByteArray& line = *it;\n int actualIndentLevel = indentLevel(line);\n if( actualIndentLevel>propertyIndentLevel && line.startsWith(lineStringStart) ) {\n value += \"\\n\" + line.trimmed();\n ++it;\n } else\n break;\n }\n qDebug() << key << \"=\" << value;\n if(key == \"Gamma\") {\n monitor->gamma = value;\n }\n else if(key == \"Brightness\") {\n monitor->brightness = value;\n }\n else if(key == \"EDID\") {\n monitor->edid = value ;\n \/\/ Get vendor\n QString hex = value.replace(\"\\n\",\"\").replace(\" \",\"\").toLower();\n int vendorPosStart = hex.indexOf(\"fc00\");\n if(vendorPosStart>0) {\n int vendorPosEnd = hex.indexOf(\"00\", vendorPosStart+4);\n QString vendorHex = hex.mid(vendorPosStart+4, vendorPosEnd-vendorPosStart-4);\n QByteArray vendor = QByteArray::fromHex(vendorHex.toLocal8Bit()).trimmed();\n \/\/ qDebug() << \"Vendor:\" << vendorHex << \"VendorHex\" << vendor ;\n monitor->vendor = vendor;\n }\n }\n continue;\n } \/\/ End format: <key>: <value>\n else { \/\/ this line is not key:value\n }\n }\n }\n if( it != lines.end() ) ++it;\n }\n\n if(monitor) \/\/ this should not happen unless a parsing error happens\n delete monitor;\n\n resolvePositions(monitors);\n\n \n return monitors;\n}\n\n\n\nbool XRandRBackend::setMonitorsSettings(const QList<MonitorSettings*> monitors) {\n QString cmd = getCommand(monitors);\n QProcess process;\n process.start(cmd);\n process.waitForFinished();\n return process.exitCode() == 0;\n}\n\n\n\n\nQString XRandRBackend::getCommand(const QList<MonitorSettings*> monitors) {\n QMap<MonitorSettings::Position, QString> positions;\n\n positions[MonitorSettings::Left] = \"--left-of\";\n positions[MonitorSettings::Right] = \"--right-of\";\n positions[MonitorSettings::Above] = \"--above\";\n positions[MonitorSettings::Bellow] = \"--below\";\n\n\n QByteArray cmd = \"xrandr\";\n\n foreach(MonitorSettings * monitor, monitors) {\n cmd += \" --output \";\n cmd.append(monitor->name);\n cmd.append(' ');\n\n \/\/ if the monitor is turned on\n if(monitor->enabledOk) {\n QString sel_res = monitor->currentMode;\n QString sel_rate = monitor->currentRate;\n\n if(sel_res == QObject::tr(\"Auto\")) \/\/ auto resolution\n cmd.append(\"--auto\");\n else {\n cmd.append(\"--mode \");\n cmd.append(sel_res);\n if(sel_rate != QObject::tr(\"Auto\")) { \/\/ not auto refresh rate\n cmd.append(\" --rate \");\n cmd.append(sel_rate);\n }\n }\n if(monitor->position != MonitorSettings::None) {\n cmd.append(\" \");\n cmd.append(positions[monitor->position]);\n cmd.append(\" \");\n cmd.append(monitor->positionRelativeToOutput);\n } else\n cmd.append(\" --pos 0x0\");\n if(monitor->primaryOk)\n cmd.append(\" --primary\");\n cmd.append(\" --brightness \");\n cmd.append(monitor->brightness);\n cmd.append(\" --gamma \");\n cmd.append(monitor->gamma);\n }\n else \/\/ turn off\n cmd.append(\"--off\");\n }\n\n\n qDebug() << \"cmd:\" << cmd;\n return cmd;\n}\n\n\/\/ resolve the position relationship among the montors\nvoid XRandRBackend::resolvePositions(QList< MonitorInfo* >& monitors) {\n Q_FOREACH(MonitorInfo * monitor, monitors) {\n MonitorSettings::Position pos;\n MonitorInfo* neighbor = findAdjacentMonitor(monitors, monitor, pos);\n if(neighbor) {\n monitor->position = pos;\n monitor->positionRelativeToOutput = neighbor->name;\n }\n }\n}\n\nMonitorInfo* XRandRBackend::findAdjacentMonitor(QList< MonitorInfo* >& monitors, MonitorInfo* monitor, MonitorSettings::Position& pos) {\n MonitorInfo* neighbor = NULL;\n QRect monitorRect = monitor->geometry();\n pos = MonitorSettings::None;\n Q_FOREACH(MonitorInfo * mon, monitors) {\n if(mon == monitor || mon->positionRelativeToOutput == monitor->name)\n continue;\n QRect neighborRect = mon->geometry();\n if(monitorRect.top() == neighborRect.top()) {\n if((monitorRect.right() + 1) == neighborRect.left()) { \/\/ monitor is at left of neighbor\n pos = MonitorSettings::Left;\n neighbor = mon;\n break;\n }\n else if(monitorRect.left() == (neighborRect.right() + 1)) { \/\/ monitor is at right of neighbor\n pos = MonitorSettings::Right;\n neighbor = mon;\n break;\n }\n }\n if(monitorRect.left() == neighborRect.left()) {\n if((monitorRect.bottom() + 1) == neighborRect.top()) { \/\/ monitor is above neighbor\n pos = MonitorSettings::Above;\n neighbor = mon;\n break;\n }\n else if(monitorRect.top() == (neighborRect.bottom() + 1)) { \/\/ monitor is below neighbor\n pos = MonitorSettings::Bellow;\n neighbor = mon;\n break;\n }\n }\n }\n return neighbor;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <glib\/gstdio.h>\n\n#include <fstream>\n#include <iostream>\n\n#include \"settings.h\"\nusing namespace AhoViewer;\n\n#include \"config.h\"\n\nSettingsManager AhoViewer::Settings;\n\nSettingsManager::SettingsManager()\n : ConfigPath(Glib::build_filename(Glib::get_user_config_dir(), PACKAGE)),\n ConfigFilePath(Glib::build_filename(ConfigPath, PACKAGE \".cfg\")),\n BooruPath(Glib::build_filename(ConfigPath, \"booru\")),\n FavoriteTagsPath(Glib::build_filename(ConfigPath, \"favorite-tags\")),\n\/\/ Defaults {{{\n DefaultBools(\n {\n { \"AutoOpenArchive\", true },\n { \"MangaMode\", true },\n { \"RememberLastFile\", true },\n { \"RememberLastSavePath\", true },\n { \"SaveThumbnails\", true },\n { \"StartFullscreen\", false },\n { \"StoreRecentFiles\", true },\n { \"SmartNavigation\", false },\n\n { \"BooruBrowserVisible\", true },\n { \"MenuBarVisible\", true },\n { \"ScrollbarsVisible\", true },\n { \"StatusBarVisible\", true },\n { \"ThumbnailBarVisible\", false },\n { \"HideAll\", false },\n { \"HideAllFullscreen\", true },\n }),\n DefaultInts(\n {\n { \"ArchiveIndex\", -1 },\n { \"CacheSize\", 2 },\n { \"SlideshowDelay\", 5 },\n { \"CursorHideDelay\", 2 },\n { \"TagViewPosition\", 560 },\n { \"SelectedBooru\", 0 },\n { \"BooruLimit\", 50 },\n { \"BooruWidth\", -1 },\n }),\n DefaultSites(\n {\n std::make_tuple(\"Gelbooru\", \"http:\/\/gelbooru.com\", Booru::Site::Type::GELBOORU),\n std::make_tuple(\"Danbooru\", \"https:\/\/danbooru.donmai.us\", Booru::Site::Type::DANBOORU),\n std::make_tuple(\"Konachan\", \"http:\/\/konachan.com\", Booru::Site::Type::MOEBOORU),\n std::make_tuple(\"yande.re\", \"https:\/\/yande.re\", Booru::Site::Type::MOEBOORU),\n std::make_tuple(\"Safebooru\", \"http:\/\/safebooru.org\", Booru::Site::Type::GELBOORU),\n }),\n DefaultKeybindings(\n {\n {\n \"File\",\n {\n { \"OpenFile\", \"<Primary>o\" },\n { \"Preferences\", \"p\" },\n { \"Close\", \"<Primary>w\" },\n { \"Quit\", \"<Primary>q\" },\n }\n },\n {\n \"ViewMode\",\n {\n { \"ToggleMangaMode\", \"g\" },\n { \"AutoFitMode\", \"a\" },\n { \"FitWidthMode\", \"w\" },\n { \"FitHeightMode\", \"h\" },\n { \"ManualZoomMode\", \"m\" },\n }\n },\n {\n \"UserInterface\",\n {\n { \"ToggleFullscreen\", \"f\" },\n { \"ToggleMenuBar\", \"<Primary>m\" },\n { \"ToggleStatusBar\", \"<Primary>b\" },\n { \"ToggleScrollbars\", \"<Primary>l\" },\n { \"ToggleThumbnailBar\", \"t\" },\n { \"ToggleBooruBrowser\", \"b\" },\n { \"ToggleHideAll\", \"i\" },\n }\n },\n {\n \"Zoom\",\n {\n { \"ZoomIn\", \"<Primary>equal\" },\n { \"ZoomOut\", \"<Primary>minus\" },\n { \"ResetZoom\", \"<Primary>0\" },\n }\n },\n {\n \"Navigation\",\n {\n { \"NextImage\", \"Page_Down\" },\n { \"PreviousImage\", \"Page_Up\" },\n { \"FirstImage\", \"Home\" },\n { \"LastImage\", \"End\" },\n { \"ToggleSlideshow\", \"s\" },\n }\n },\n {\n \"Scroll\",\n {\n { \"ScrollUp\", \"Up\" },\n { \"ScrollDown\", \"Down\" },\n { \"ScrollLeft\", \"Left\" },\n { \"ScrollRight\", \"Right\" },\n }\n },\n {\n \"BooruBrowser\",\n {\n { \"NewTab\", \"<Primary>t\" },\n { \"SaveImage\", \"<Primary>s\" },\n { \"SaveImages\", \"<Primary><Shift>s\" },\n { \"ViewPost\", \"<Primary><Shift>o\" },\n { \"CopyImageURL\", \"y\" },\n }\n }\n }),\n DefaultBGColor(\"#161616\")\n\/\/ }}}\n{\n Config.setTabWidth(4); \/\/ this is very important\n if (Glib::file_test(ConfigFilePath, Glib::FILE_TEST_EXISTS))\n {\n try\n {\n Config.readFile(ConfigFilePath.c_str());\n }\n catch (const libconfig::ParseException &ex)\n {\n std::cerr << \"libconfig::Config.readFile: \" << ex.what() << std::endl;\n }\n }\n\n if (!Glib::file_test(BooruPath, Glib::FILE_TEST_EXISTS))\n g_mkdir_with_parents(BooruPath.c_str(), 0700);\n\n if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS))\n {\n std::ifstream ifs(FavoriteTagsPath);\n\n if (ifs)\n std::copy(std::istream_iterator<std::string>(ifs),\n std::istream_iterator<std::string>(),\n std::inserter(m_FavoriteTags, m_FavoriteTags.begin()));\n }\n\n load_keybindings();\n}\n\nSettingsManager::~SettingsManager()\n{\n try\n {\n Config.writeFile(ConfigFilePath.c_str());\n }\n catch (const libconfig::FileIOException &ex)\n {\n std::cerr << \"libconfig::Config.writeFile: \" << ex.what() << std::endl;\n }\n\n if (!m_FavoriteTags.empty())\n {\n std::ofstream ofs(FavoriteTagsPath);\n\n if (ofs)\n std::copy(m_FavoriteTags.begin(), m_FavoriteTags.end(),\n std::ostream_iterator<std::string>(ofs, \"\\n\"));\n }\n else if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS))\n {\n g_unlink(FavoriteTagsPath.c_str());\n }\n}\n\nbool SettingsManager::get_bool(const std::string &key) const\n{\n if (Config.exists(key))\n return Config.lookup(key);\n\n return DefaultBools.at(key);\n}\n\nint SettingsManager::get_int(const std::string &key) const\n{\n if (Config.exists(key))\n return Config.lookup(key);\n\n return DefaultInts.at(key);\n}\n\nstd::string SettingsManager::get_string(const std::string &key) const\n{\n if (Config.exists(key))\n return (const char*)Config.lookup(key);\n\n return \"\";\n}\n\nstd::vector<std::shared_ptr<Booru::Site>>& SettingsManager::get_sites()\n{\n if (m_Sites.size())\n {\n return m_Sites;\n }\n else if (Config.exists(\"Sites\"))\n {\n const Setting &sites = Config.lookup(\"Sites\");\n if (sites.getLength() > 0)\n {\n for (size_t i = 0; i < static_cast<size_t>(sites.getLength()); ++i)\n {\n const Setting &s = sites[i];\n m_Sites.push_back(std::make_shared<Booru::Site>(s[\"name\"], s[\"url\"],\n static_cast<Booru::Site::Type>(static_cast<int>(s[\"type\"]))));\n }\n\n return m_Sites;\n }\n }\n else\n {\n for (const std::tuple<std::string, std::string, Booru::Site::Type> &s : DefaultSites)\n m_Sites.push_back(std::make_shared<Booru::Site>(\n std::get<0>(s), std::get<1>(s), std::get<2>(s)));\n }\n\n return m_Sites;\n}\n\nvoid SettingsManager::update_sites()\n{\n remove(\"Sites\");\n Setting &sites = Config.getRoot().add(\"Sites\", Setting::TypeList);\n\n for (const std::shared_ptr<Booru::Site> &s : m_Sites)\n {\n Setting &site = sites.add(Setting::TypeGroup);\n set(\"name\", s->get_name(), Setting::TypeString, site);\n set(\"url\", s->get_url(), Setting::TypeString, site);\n set(\"type\", static_cast<int>(s->get_type()), Setting::TypeInt, site);\n }\n}\n\nbool SettingsManager::get_geometry(int &x, int &y, int &w, int &h) const\n{\n if (Config.lookupValue(\"Geometry.x\", x) && Config.lookupValue(\"Geometry.y\", y) &&\n Config.lookupValue(\"Geometry.w\", w) && Config.lookupValue(\"Geometry.h\", h))\n {\n return true;\n }\n\n return false;\n}\n\nvoid SettingsManager::set_geometry(const int x, const int y, const int w, const int h)\n{\n if (!Config.exists(\"Geometry\"))\n Config.getRoot().add(\"Geometry\", Setting::TypeGroup);\n\n Setting &geo = Config.lookup(\"Geometry\");\n\n set(\"x\", x, Setting::TypeInt, geo);\n set(\"y\", y, Setting::TypeInt, geo);\n set(\"w\", w, Setting::TypeInt, geo);\n set(\"h\", h, Setting::TypeInt, geo);\n}\n\nstd::string SettingsManager::get_keybinding(const std::string &group, const std::string &name) const\n{\n return m_Keybindings.at(group).at(name);\n}\n\n\/**\n * Clears the first (only) binding that has the same value as value\n * Sets the group and name parameters to those of the binding that was cleared\n * Returns true if it actually cleared a binding\n **\/\nbool SettingsManager::clear_keybinding(const std::string &value, std::string &group, std::string &name)\n{\n for (const std::pair<std::string, std::map<std::string, std::string>> &i : m_Keybindings)\n {\n for (const std::pair<std::string, std::string> &j : i.second)\n {\n if (j.second == value)\n {\n group = i.first;\n name = j.first;\n\n set_keybinding(group, name, \"\");\n\n return true;\n }\n }\n }\n\n return false;\n}\n\nvoid SettingsManager::set_keybinding(const std::string &group, const std::string &name, const std::string &value)\n{\n if (!Config.exists(\"Keybindings\"))\n Config.getRoot().add(\"Keybindings\", Setting::TypeGroup);\n\n Setting &keys = Config.lookup(\"Keybindings\");\n\n if (!keys.exists(group))\n keys.add(group, Setting::TypeGroup);\n\n set(name, value, Setting::TypeString, keys[group.c_str()]);\n m_Keybindings[group][name] = value;\n}\n\nstd::string SettingsManager::reset_keybinding(const std::string &group, const std::string &name)\n{\n if (Config.exists(\"Keybindings\"))\n {\n Setting &keys = Config.lookup(\"Keybindings\");\n\n if (keys.exists(group) && keys[group.c_str()].exists(name))\n keys[group.c_str()].remove(name);\n }\n\n return m_Keybindings[group][name] = DefaultKeybindings.at(group).at(name);\n}\n\nGdk::Color SettingsManager::get_background_color() const\n{\n if (Config.exists(\"BackgroundColor\"))\n return Gdk::Color((const char*)Config.lookup(\"BackgroundColor\"));\n\n return DefaultBGColor;\n}\n\nvoid SettingsManager::set_background_color(const Gdk::Color &value)\n{\n set(\"BackgroundColor\", value.to_string());\n}\n\nBooru::Site::Rating SettingsManager::get_booru_max_rating() const\n{\n if (Config.exists(\"BooruMaxRating\"))\n return Booru::Site::Rating(static_cast<int>(Config.lookup(\"BooruMaxRating\")));\n\n return DefaultBooruMaxRating;\n}\n\nvoid SettingsManager::set_booru_max_rating(const Booru::Site::Rating value)\n{\n set(\"BooruMaxRating\", static_cast<int>(value));\n}\n\nImageBox::ZoomMode SettingsManager::get_zoom_mode() const\n{\n if (Config.exists(\"ZoomMode\"))\n return ImageBox::ZoomMode(((const char*)Config.lookup(\"ZoomMode\"))[0]);\n\n return DefaultZoomMode;\n}\n\nvoid SettingsManager::set_zoom_mode(const ImageBox::ZoomMode value)\n{\n set(\"ZoomMode\", std::string(1, static_cast<char>(value)));\n}\n\nvoid SettingsManager::remove(const std::string &key)\n{\n if (Config.exists(key))\n Config.getRoot().remove(key);\n}\n\nvoid SettingsManager::load_keybindings()\n{\n if (Config.exists(\"Keybindings\"))\n {\n Setting &keys = Config.lookup(\"Keybindings\");\n\n for (const std::pair<std::string, std::map<std::string, std::string>> &i : DefaultKeybindings)\n {\n if (keys.exists(i.first))\n {\n for (const std::pair<std::string, std::string> &j : i.second)\n {\n if (keys[i.first.c_str()].exists(j.first))\n {\n m_Keybindings[i.first][j.first] = std::string(keys[i.first.c_str()][j.first.c_str()].c_str());\n }\n else\n {\n m_Keybindings[i.first][j.first] = DefaultKeybindings.at(i.first).at(j.first);\n }\n }\n }\n else\n {\n m_Keybindings[i.first] = DefaultKeybindings.at(i.first);\n }\n }\n }\n else\n {\n m_Keybindings = DefaultKeybindings;\n }\n}\n<commit_msg>settings: Make Danbooru the default selected booru site<commit_after>#include <glib\/gstdio.h>\n\n#include <fstream>\n#include <iostream>\n\n#include \"settings.h\"\nusing namespace AhoViewer;\n\n#include \"config.h\"\n\nSettingsManager AhoViewer::Settings;\n\nSettingsManager::SettingsManager()\n : ConfigPath(Glib::build_filename(Glib::get_user_config_dir(), PACKAGE)),\n ConfigFilePath(Glib::build_filename(ConfigPath, PACKAGE \".cfg\")),\n BooruPath(Glib::build_filename(ConfigPath, \"booru\")),\n FavoriteTagsPath(Glib::build_filename(ConfigPath, \"favorite-tags\")),\n\/\/ Defaults {{{\n DefaultBools(\n {\n { \"AutoOpenArchive\", true },\n { \"MangaMode\", true },\n { \"RememberLastFile\", true },\n { \"RememberLastSavePath\", true },\n { \"SaveThumbnails\", true },\n { \"StartFullscreen\", false },\n { \"StoreRecentFiles\", true },\n { \"SmartNavigation\", false },\n\n { \"BooruBrowserVisible\", true },\n { \"MenuBarVisible\", true },\n { \"ScrollbarsVisible\", true },\n { \"StatusBarVisible\", true },\n { \"ThumbnailBarVisible\", false },\n { \"HideAll\", false },\n { \"HideAllFullscreen\", true },\n }),\n DefaultInts(\n {\n { \"ArchiveIndex\", -1 },\n { \"CacheSize\", 2 },\n { \"SlideshowDelay\", 5 },\n { \"CursorHideDelay\", 2 },\n { \"TagViewPosition\", 560 },\n { \"SelectedBooru\", 0 },\n { \"BooruLimit\", 50 },\n { \"BooruWidth\", -1 },\n }),\n DefaultSites(\n {\n \/\/ std::make_tuple(\"Gelbooru\", \"http:\/\/gelbooru.com\", Booru::Site::Type::GELBOORU),\n std::make_tuple(\"Danbooru\", \"https:\/\/danbooru.donmai.us\", Booru::Site::Type::DANBOORU),\n std::make_tuple(\"Konachan\", \"http:\/\/konachan.com\", Booru::Site::Type::MOEBOORU),\n std::make_tuple(\"yande.re\", \"https:\/\/yande.re\", Booru::Site::Type::MOEBOORU),\n std::make_tuple(\"Safebooru\", \"http:\/\/safebooru.org\", Booru::Site::Type::GELBOORU),\n }),\n DefaultKeybindings(\n {\n {\n \"File\",\n {\n { \"OpenFile\", \"<Primary>o\" },\n { \"Preferences\", \"p\" },\n { \"Close\", \"<Primary>w\" },\n { \"Quit\", \"<Primary>q\" },\n }\n },\n {\n \"ViewMode\",\n {\n { \"ToggleMangaMode\", \"g\" },\n { \"AutoFitMode\", \"a\" },\n { \"FitWidthMode\", \"w\" },\n { \"FitHeightMode\", \"h\" },\n { \"ManualZoomMode\", \"m\" },\n }\n },\n {\n \"UserInterface\",\n {\n { \"ToggleFullscreen\", \"f\" },\n { \"ToggleMenuBar\", \"<Primary>m\" },\n { \"ToggleStatusBar\", \"<Primary>b\" },\n { \"ToggleScrollbars\", \"<Primary>l\" },\n { \"ToggleThumbnailBar\", \"t\" },\n { \"ToggleBooruBrowser\", \"b\" },\n { \"ToggleHideAll\", \"i\" },\n }\n },\n {\n \"Zoom\",\n {\n { \"ZoomIn\", \"<Primary>equal\" },\n { \"ZoomOut\", \"<Primary>minus\" },\n { \"ResetZoom\", \"<Primary>0\" },\n }\n },\n {\n \"Navigation\",\n {\n { \"NextImage\", \"Page_Down\" },\n { \"PreviousImage\", \"Page_Up\" },\n { \"FirstImage\", \"Home\" },\n { \"LastImage\", \"End\" },\n { \"ToggleSlideshow\", \"s\" },\n }\n },\n {\n \"Scroll\",\n {\n { \"ScrollUp\", \"Up\" },\n { \"ScrollDown\", \"Down\" },\n { \"ScrollLeft\", \"Left\" },\n { \"ScrollRight\", \"Right\" },\n }\n },\n {\n \"BooruBrowser\",\n {\n { \"NewTab\", \"<Primary>t\" },\n { \"SaveImage\", \"<Primary>s\" },\n { \"SaveImages\", \"<Primary><Shift>s\" },\n { \"ViewPost\", \"<Primary><Shift>o\" },\n { \"CopyImageURL\", \"y\" },\n }\n }\n }),\n DefaultBGColor(\"#161616\")\n\/\/ }}}\n{\n Config.setTabWidth(4); \/\/ this is very important\n if (Glib::file_test(ConfigFilePath, Glib::FILE_TEST_EXISTS))\n {\n try\n {\n Config.readFile(ConfigFilePath.c_str());\n }\n catch (const libconfig::ParseException &ex)\n {\n std::cerr << \"libconfig::Config.readFile: \" << ex.what() << std::endl;\n }\n }\n\n if (!Glib::file_test(BooruPath, Glib::FILE_TEST_EXISTS))\n g_mkdir_with_parents(BooruPath.c_str(), 0700);\n\n if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS))\n {\n std::ifstream ifs(FavoriteTagsPath);\n\n if (ifs)\n std::copy(std::istream_iterator<std::string>(ifs),\n std::istream_iterator<std::string>(),\n std::inserter(m_FavoriteTags, m_FavoriteTags.begin()));\n }\n\n load_keybindings();\n}\n\nSettingsManager::~SettingsManager()\n{\n try\n {\n Config.writeFile(ConfigFilePath.c_str());\n }\n catch (const libconfig::FileIOException &ex)\n {\n std::cerr << \"libconfig::Config.writeFile: \" << ex.what() << std::endl;\n }\n\n if (!m_FavoriteTags.empty())\n {\n std::ofstream ofs(FavoriteTagsPath);\n\n if (ofs)\n std::copy(m_FavoriteTags.begin(), m_FavoriteTags.end(),\n std::ostream_iterator<std::string>(ofs, \"\\n\"));\n }\n else if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS))\n {\n g_unlink(FavoriteTagsPath.c_str());\n }\n}\n\nbool SettingsManager::get_bool(const std::string &key) const\n{\n if (Config.exists(key))\n return Config.lookup(key);\n\n return DefaultBools.at(key);\n}\n\nint SettingsManager::get_int(const std::string &key) const\n{\n if (Config.exists(key))\n return Config.lookup(key);\n\n return DefaultInts.at(key);\n}\n\nstd::string SettingsManager::get_string(const std::string &key) const\n{\n if (Config.exists(key))\n return (const char*)Config.lookup(key);\n\n return \"\";\n}\n\nstd::vector<std::shared_ptr<Booru::Site>>& SettingsManager::get_sites()\n{\n if (m_Sites.size())\n {\n return m_Sites;\n }\n else if (Config.exists(\"Sites\"))\n {\n const Setting &sites = Config.lookup(\"Sites\");\n if (sites.getLength() > 0)\n {\n for (size_t i = 0; i < static_cast<size_t>(sites.getLength()); ++i)\n {\n const Setting &s = sites[i];\n m_Sites.push_back(std::make_shared<Booru::Site>(s[\"name\"], s[\"url\"],\n static_cast<Booru::Site::Type>(static_cast<int>(s[\"type\"]))));\n }\n\n return m_Sites;\n }\n }\n else\n {\n for (const std::tuple<std::string, std::string, Booru::Site::Type> &s : DefaultSites)\n m_Sites.push_back(std::make_shared<Booru::Site>(\n std::get<0>(s), std::get<1>(s), std::get<2>(s)));\n }\n\n return m_Sites;\n}\n\nvoid SettingsManager::update_sites()\n{\n remove(\"Sites\");\n Setting &sites = Config.getRoot().add(\"Sites\", Setting::TypeList);\n\n for (const std::shared_ptr<Booru::Site> &s : m_Sites)\n {\n Setting &site = sites.add(Setting::TypeGroup);\n set(\"name\", s->get_name(), Setting::TypeString, site);\n set(\"url\", s->get_url(), Setting::TypeString, site);\n set(\"type\", static_cast<int>(s->get_type()), Setting::TypeInt, site);\n }\n}\n\nbool SettingsManager::get_geometry(int &x, int &y, int &w, int &h) const\n{\n if (Config.lookupValue(\"Geometry.x\", x) && Config.lookupValue(\"Geometry.y\", y) &&\n Config.lookupValue(\"Geometry.w\", w) && Config.lookupValue(\"Geometry.h\", h))\n {\n return true;\n }\n\n return false;\n}\n\nvoid SettingsManager::set_geometry(const int x, const int y, const int w, const int h)\n{\n if (!Config.exists(\"Geometry\"))\n Config.getRoot().add(\"Geometry\", Setting::TypeGroup);\n\n Setting &geo = Config.lookup(\"Geometry\");\n\n set(\"x\", x, Setting::TypeInt, geo);\n set(\"y\", y, Setting::TypeInt, geo);\n set(\"w\", w, Setting::TypeInt, geo);\n set(\"h\", h, Setting::TypeInt, geo);\n}\n\nstd::string SettingsManager::get_keybinding(const std::string &group, const std::string &name) const\n{\n return m_Keybindings.at(group).at(name);\n}\n\n\/**\n * Clears the first (only) binding that has the same value as value\n * Sets the group and name parameters to those of the binding that was cleared\n * Returns true if it actually cleared a binding\n **\/\nbool SettingsManager::clear_keybinding(const std::string &value, std::string &group, std::string &name)\n{\n for (const std::pair<std::string, std::map<std::string, std::string>> &i : m_Keybindings)\n {\n for (const std::pair<std::string, std::string> &j : i.second)\n {\n if (j.second == value)\n {\n group = i.first;\n name = j.first;\n\n set_keybinding(group, name, \"\");\n\n return true;\n }\n }\n }\n\n return false;\n}\n\nvoid SettingsManager::set_keybinding(const std::string &group, const std::string &name, const std::string &value)\n{\n if (!Config.exists(\"Keybindings\"))\n Config.getRoot().add(\"Keybindings\", Setting::TypeGroup);\n\n Setting &keys = Config.lookup(\"Keybindings\");\n\n if (!keys.exists(group))\n keys.add(group, Setting::TypeGroup);\n\n set(name, value, Setting::TypeString, keys[group.c_str()]);\n m_Keybindings[group][name] = value;\n}\n\nstd::string SettingsManager::reset_keybinding(const std::string &group, const std::string &name)\n{\n if (Config.exists(\"Keybindings\"))\n {\n Setting &keys = Config.lookup(\"Keybindings\");\n\n if (keys.exists(group) && keys[group.c_str()].exists(name))\n keys[group.c_str()].remove(name);\n }\n\n return m_Keybindings[group][name] = DefaultKeybindings.at(group).at(name);\n}\n\nGdk::Color SettingsManager::get_background_color() const\n{\n if (Config.exists(\"BackgroundColor\"))\n return Gdk::Color((const char*)Config.lookup(\"BackgroundColor\"));\n\n return DefaultBGColor;\n}\n\nvoid SettingsManager::set_background_color(const Gdk::Color &value)\n{\n set(\"BackgroundColor\", value.to_string());\n}\n\nBooru::Site::Rating SettingsManager::get_booru_max_rating() const\n{\n if (Config.exists(\"BooruMaxRating\"))\n return Booru::Site::Rating(static_cast<int>(Config.lookup(\"BooruMaxRating\")));\n\n return DefaultBooruMaxRating;\n}\n\nvoid SettingsManager::set_booru_max_rating(const Booru::Site::Rating value)\n{\n set(\"BooruMaxRating\", static_cast<int>(value));\n}\n\nImageBox::ZoomMode SettingsManager::get_zoom_mode() const\n{\n if (Config.exists(\"ZoomMode\"))\n return ImageBox::ZoomMode(((const char*)Config.lookup(\"ZoomMode\"))[0]);\n\n return DefaultZoomMode;\n}\n\nvoid SettingsManager::set_zoom_mode(const ImageBox::ZoomMode value)\n{\n set(\"ZoomMode\", std::string(1, static_cast<char>(value)));\n}\n\nvoid SettingsManager::remove(const std::string &key)\n{\n if (Config.exists(key))\n Config.getRoot().remove(key);\n}\n\nvoid SettingsManager::load_keybindings()\n{\n if (Config.exists(\"Keybindings\"))\n {\n Setting &keys = Config.lookup(\"Keybindings\");\n\n for (const std::pair<std::string, std::map<std::string, std::string>> &i : DefaultKeybindings)\n {\n if (keys.exists(i.first))\n {\n for (const std::pair<std::string, std::string> &j : i.second)\n {\n if (keys[i.first.c_str()].exists(j.first))\n {\n m_Keybindings[i.first][j.first] = std::string(keys[i.first.c_str()][j.first.c_str()].c_str());\n }\n else\n {\n m_Keybindings[i.first][j.first] = DefaultKeybindings.at(i.first).at(j.first);\n }\n }\n }\n else\n {\n m_Keybindings[i.first] = DefaultKeybindings.at(i.first);\n }\n }\n }\n else\n {\n m_Keybindings = DefaultKeybindings;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"db\/mail\/MailSpool.h\"\n\n#include \"db\/io\/ByteArrayInputStream.h\"\n#include \"db\/io\/FileInputStream.h\"\n#include \"db\/io\/FileOutputStream.h\"\n#include \"db\/data\/Data.h\"\n#include \"db\/data\/json\/JsonReader.h\"\n#include \"db\/data\/json\/JsonWriter.h\"\n#include \"db\/mail\/MailTemplateParser.h\"\n\nusing namespace db::data::json;\nusing namespace db::io;\nusing namespace db::mail;\nusing namespace db::rt;\n\nMailSpool::MailSpool() :\n mFile((FileImpl*)NULL)\n{\n \/\/ spool empty thus far\n mHead = mTail = mCount = 0;\n}\n\nMailSpool::~MailSpool()\n{\n}\n\nbool MailSpool::writeIndex()\n{\n bool rval;\n \n \/\/ get associated index name\n std::string name = mFile->getAbsolutePath();\n name.append(\".idx\");\n File file(name.c_str());\n \n \/\/ write out index data\n FileOutputStream fos(file);\n DynamicObject config;\n config[\"head\"] = mHead;\n config[\"tail\"] = mTail;\n config[\"count\"] = mCount;\n JsonWriter writer;\n rval = writer.write(config, &fos);\n fos.close();\n \n return rval;\n}\n\nvoid MailSpool::lock()\n{\n mSpoolLock.lock();\n}\n\nvoid MailSpool::unlock()\n{\n mSpoolLock.unlock();\n}\n\nbool MailSpool::setFile(File& file)\n{\n bool rval;\n \n lock();\n {\n \/\/ set file\n mFile = file;\n \n \/\/ read associated index\n std::string name = mFile->getAbsolutePath();\n name.append(\".idx\");\n File file(name.c_str());\n if(!file->exists())\n {\n \/\/ create new spool index\n mHead = mTail = mCount = 0;\n rval = writeIndex();\n }\n else\n {\n \/\/ read existing spool index\n FileInputStream fis(file);\n JsonReader reader;\n DynamicObject config;\n reader.start(config);\n rval = reader.read(&fis) && reader.finish();\n fis.close();\n \n if(rval)\n {\n mHead = config[\"head\"]->getUInt32();\n mTail = config[\"tail\"]->getUInt32();\n mCount = config[\"count\"]->getUInt32();\n }\n }\n }\n unlock();\n \n return rval;\n}\n\nbool MailSpool::spool(Mail* mail)\n{\n bool rval;\n \n \/\/ convert mail to template\n std::string tpl = mail->toTemplate();\n \n lock();\n {\n \/\/ write out mail entry\n FileOutputStream fos(mFile, mCount > 0);\n \n \/\/ entry = index + size + tpl\n uint32_t idx = DB_UINT32_TO_LE(mTail);\n uint32_t size = DB_UINT32_TO_LE(tpl.length());\n rval =\n fos.write((char*)&idx, 4) &&\n fos.write((char*)&size, 4) &&\n fos.write(tpl.c_str(), tpl.length());\n fos.close();\n \n \/\/ increment tail, count\n mTail++;\n mCount++;\n \n \/\/ write out index\n rval = rval && writeIndex();\n }\n unlock();\n \n return rval;\n}\n\nbool MailSpool::getFirst(Mail* mail)\n{\n bool rval = false;\n \n lock();\n {\n if(mCount == 0)\n {\n ExceptionRef e = new Exception(\n \"Cannot get first mail from spool! Spool is empty!\");\n Exception::setLast(e, false);\n }\n else\n {\n \/\/ read from spool file\n FileInputStream fis(mFile);\n char b[2048];\n int numBytes = 1;\n uint32_t idx;\n uint32_t size;\n \n \/\/ skip mail entries until head is reached\n while(numBytes > 0)\n {\n \/\/ read current index\n if((numBytes = fis.read(b, 4)) == 4)\n {\n memcpy(&idx, b, 4);\n idx = DB_UINT32_FROM_LE(idx);\n }\n \n \/\/ read current size\n if((numBytes = fis.read(b, 4) == 4))\n {\n memcpy(&size, b, 4);\n size = DB_UINT32_FROM_LE(size);\n }\n \n \/\/ read mail if current index is head\n if(idx == mHead)\n {\n \/\/ read mail data\n ByteBuffer bb(size);\n int read = (int)(size > 2048 ? 2048 : size);\n while(read > 0 && (numBytes = fis.read(b, read)) > 0)\n {\n bb.put(b, numBytes, false);\n size -= numBytes;\n read = (int)(size > 2048 ? 2048 : size);\n }\n \n if(numBytes != -1)\n {\n \/\/ parse mail data\n ByteArrayInputStream bais(&bb, false);\n MailTemplateParser parser;\n DynamicObject vars;\n rval = parser.parse(mail, vars, false, &bais);\n }\n break;\n }\n else\n {\n \/\/ skip mail data\n if(fis.skip(size) < 0)\n {\n \/\/ error while skipping\n numBytes = -1;\n }\n }\n }\n \n \/\/ close spool file\n fis.close();\n }\n }\n unlock();\n \n return rval;\n}\n\nbool MailSpool::unwind()\n{\n bool rval;\n \n lock();\n {\n if(mCount == 0)\n {\n \/\/ nothing to do, spool is empty\n rval = true;\n }\n else\n {\n \/\/ increment head, decrement count\n mHead++;\n mCount--;\n \n if(mCount == 0)\n {\n \/\/ reset index, spool now empty\n mHead = mTail = 0;\n mFile->remove();\n }\n \n \/\/ write out index\n rval = writeIndex();\n }\n }\n unlock();\n \n return rval;\n}\n\nuint32_t MailSpool::getCount()\n{\n return mCount;\n}\n<commit_msg>Added code to create necessary directories for mail spool file.<commit_after>\/*\n * Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"db\/mail\/MailSpool.h\"\n\n#include \"db\/io\/ByteArrayInputStream.h\"\n#include \"db\/io\/FileInputStream.h\"\n#include \"db\/io\/FileOutputStream.h\"\n#include \"db\/data\/Data.h\"\n#include \"db\/data\/json\/JsonReader.h\"\n#include \"db\/data\/json\/JsonWriter.h\"\n#include \"db\/mail\/MailTemplateParser.h\"\n\nusing namespace db::data::json;\nusing namespace db::io;\nusing namespace db::mail;\nusing namespace db::rt;\n\nMailSpool::MailSpool() :\n mFile((FileImpl*)NULL)\n{\n \/\/ spool empty thus far\n mHead = mTail = mCount = 0;\n}\n\nMailSpool::~MailSpool()\n{\n}\n\nbool MailSpool::writeIndex()\n{\n bool rval;\n \n \/\/ get associated index name\n std::string name = mFile->getAbsolutePath();\n name.append(\".idx\");\n File file(name.c_str());\n if((rval = file->mkdirs()))\n {\n \/\/ write out index data\n FileOutputStream fos(file);\n DynamicObject config;\n config[\"head\"] = mHead;\n config[\"tail\"] = mTail;\n config[\"count\"] = mCount;\n JsonWriter writer;\n rval = writer.write(config, &fos);\n fos.close();\n }\n \n return rval;\n}\n\nvoid MailSpool::lock()\n{\n mSpoolLock.lock();\n}\n\nvoid MailSpool::unlock()\n{\n mSpoolLock.unlock();\n}\n\nbool MailSpool::setFile(File& file)\n{\n bool rval;\n \n lock();\n {\n \/\/ set file\n mFile = file;\n \n \/\/ read associated index\n std::string name = mFile->getAbsolutePath();\n name.append(\".idx\");\n File file(name.c_str());\n if(!file->exists())\n {\n \/\/ create new spool index\n mHead = mTail = mCount = 0;\n rval = writeIndex();\n }\n else\n {\n \/\/ read existing spool index\n FileInputStream fis(file);\n JsonReader reader;\n DynamicObject config;\n reader.start(config);\n rval = reader.read(&fis) && reader.finish();\n fis.close();\n \n if(rval)\n {\n mHead = config[\"head\"]->getUInt32();\n mTail = config[\"tail\"]->getUInt32();\n mCount = config[\"count\"]->getUInt32();\n }\n }\n }\n unlock();\n \n return rval;\n}\n\nbool MailSpool::spool(Mail* mail)\n{\n bool rval;\n \n \/\/ convert mail to template\n std::string tpl = mail->toTemplate();\n \n lock();\n {\n \/\/ write out mail entry\n FileOutputStream fos(mFile, mCount > 0);\n \n \/\/ entry = index + size + tpl\n uint32_t idx = DB_UINT32_TO_LE(mTail);\n uint32_t size = DB_UINT32_TO_LE(tpl.length());\n rval =\n fos.write((char*)&idx, 4) &&\n fos.write((char*)&size, 4) &&\n fos.write(tpl.c_str(), tpl.length());\n fos.close();\n \n \/\/ increment tail, count\n mTail++;\n mCount++;\n \n \/\/ write out index\n rval = rval && writeIndex();\n }\n unlock();\n \n return rval;\n}\n\nbool MailSpool::getFirst(Mail* mail)\n{\n bool rval = false;\n \n lock();\n {\n if(mCount == 0)\n {\n ExceptionRef e = new Exception(\n \"Cannot get first mail from spool! Spool is empty!\");\n Exception::setLast(e, false);\n }\n else\n {\n \/\/ read from spool file\n FileInputStream fis(mFile);\n char b[2048];\n int numBytes = 1;\n uint32_t idx;\n uint32_t size;\n \n \/\/ skip mail entries until head is reached\n while(numBytes > 0)\n {\n \/\/ read current index\n if((numBytes = fis.read(b, 4)) == 4)\n {\n memcpy(&idx, b, 4);\n idx = DB_UINT32_FROM_LE(idx);\n }\n \n \/\/ read current size\n if((numBytes = fis.read(b, 4) == 4))\n {\n memcpy(&size, b, 4);\n size = DB_UINT32_FROM_LE(size);\n }\n \n \/\/ read mail if current index is head\n if(idx == mHead)\n {\n \/\/ read mail data\n ByteBuffer bb(size);\n int read = (int)(size > 2048 ? 2048 : size);\n while(read > 0 && (numBytes = fis.read(b, read)) > 0)\n {\n bb.put(b, numBytes, false);\n size -= numBytes;\n read = (int)(size > 2048 ? 2048 : size);\n }\n \n if(numBytes != -1)\n {\n \/\/ parse mail data\n ByteArrayInputStream bais(&bb, false);\n MailTemplateParser parser;\n DynamicObject vars;\n rval = parser.parse(mail, vars, false, &bais);\n }\n break;\n }\n else\n {\n \/\/ skip mail data\n if(fis.skip(size) < 0)\n {\n \/\/ error while skipping\n numBytes = -1;\n }\n }\n }\n \n \/\/ close spool file\n fis.close();\n }\n }\n unlock();\n \n return rval;\n}\n\nbool MailSpool::unwind()\n{\n bool rval;\n \n lock();\n {\n if(mCount == 0)\n {\n \/\/ nothing to do, spool is empty\n rval = true;\n }\n else\n {\n \/\/ increment head, decrement count\n mHead++;\n mCount--;\n \n if(mCount == 0)\n {\n \/\/ reset index, spool now empty\n mHead = mTail = 0;\n mFile->remove();\n }\n \n \/\/ write out index\n rval = writeIndex();\n }\n }\n unlock();\n \n return rval;\n}\n\nuint32_t MailSpool::getCount()\n{\n return mCount;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"shaders.h\"\n\n\/\/#include \"mathutils.h\"\n\n#define INVALID_SHADER 0\n\n#define DEBUG_SHADER_ERRORS true\n\n\/\/\n\/\/ AnyShader\n\/\/\n\nAnyShader::AnyShader() {\n \/\/empty\n}\n\nAnyShader::~AnyShader() {\n \/\/empty\n}\n\n\/**\n * Create the shader program.\n *\/\nbool AnyShader::create() {\n if (failed) {\n return false;\n }\n\n if (prog != INVALID_PROGRAM) {\n return true;\n }\n\n \/\/compile\n GLuint handle = glCreateProgram();\n\n if (handle == INVALID_PROGRAM) {\n error = \"glCreateProgram failed.\";\n\n return false;\n }\n\n if (!vertexShader.empty()) {\n GLuint vertShader = compileShader(vertexShader, GL_VERTEX_SHADER);\n\n if (vertShader == INVALID_SHADER) {\n \/\/cleanup\n glDeleteProgram(handle);\n\n return false;\n }\n\n glAttachShader(handle, vertShader);\n glDeleteShader(vertShader);\n }\n\n if (!fragmentShader.empty()) {\n GLuint fragShader = compileShader(fragmentShader, GL_FRAGMENT_SHADER);\n\n if (fragShader == INVALID_SHADER) {\n \/\/cleanup\n glDeleteProgram(handle);\n\n return false;\n }\n\n glAttachShader(handle, fragShader);\n glDeleteShader(fragShader);\n }\n\n \/\/link\n glLinkProgram(handle);\n\n GLint linkStatus;\n\n glGetProgramiv(handle, GL_LINK_STATUS, &linkStatus);\n\n if (linkStatus == GL_FALSE) {\n \/\/cleanup\n glDeleteProgram(handle);\n\n \/\/get error\n GLchar messages[256];\n\n glGetProgramInfoLog(handle, sizeof(messages), 0, &messages[0]);\n\n if (DEBUG_SHADER_ERRORS) {\n printf(\"shader linking failed: %s\\n\", messages);\n }\n\n return false;\n }\n\n prog = handle;\n\n \/\/initialize\n initShader();\n\n return true;\n}\n\n\/**\n * Compile a shader.\n *\n * Note: sets error on failure.\n *\/\nGLuint AnyShader::compileShader(std::string source, const GLenum type) {\n GLint compileStatus;\n GLuint handle = glCreateShader(type);\n\n if (handle == INVALID_SHADER) {\n error = \"glCreateShader() failed\";\n return -1;\n }\n\n#ifdef RPI\n \/\/add GLSL version\n source = \"#version 100\\n\" + source;\n#endif\n\n GLchar *src = (GLchar *)source.c_str();\n\n glShaderSource(handle, 1, (const GLchar **)&src, NULL);\n glCompileShader(handle);\n\n \/\/get status\n glGetShaderiv(handle, GL_COMPILE_STATUS, &compileStatus);\n\n if (compileStatus == GL_FALSE) {\n \/\/free\n glDeleteShader(handle);\n handle = INVALID_SHADER;\n\n \/\/get error\n GLchar messages[256];\n\n glGetShaderInfoLog(handle, sizeof(messages), 0, &messages[0]);\n\n if (DEBUG_SHADER_ERRORS) {\n std::string typeStr;\n\n if (type == GL_VERTEX_SHADER) {\n typeStr = \"vertex shader\";\n } else if (type == GL_FRAGMENT_SHADER) {\n typeStr = \"fragment shader\";\n }\n\n printf(\"shader compilation error: %s\\ntype: %s\\n\", messages, typeStr.c_str());\n }\n\n error = std::string(messages);\n }\n\n return handle;\n}\n\n\/**\n * Destroy the shader.\n *\n * Note: has to be called in OpenGL thread.\n *\/\nvoid AnyShader::destroy() {\n if (prog != INVALID_PROGRAM) {\n glDeleteProgram(prog);\n prog = INVALID_PROGRAM;\n }\n\n \/\/reset failed\n failed = false;\n}\n\n\/**\n * Get attribute location.\n *\/\nGLint AnyShader::getAttributeLocation(std::string name) {\n GLint loc = glGetAttribLocation(prog, name.c_str());\n\n if (DEBUG_SHADER_ERRORS) {\n if (loc == -1) {\n printf(\"could not get location of attribute %s\\n\", name.c_str());\n }\n }\n\n return loc;\n}\n\n\/**\n * Get uniform location.\n *\/\nGLint AnyShader::getUniformLocation(std::string name) {\n GLint loc = glGetUniformLocation(prog, name.c_str());\n\n if (DEBUG_SHADER_ERRORS) {\n if (loc == -1) {\n printf(\"could not get location of uniform %s\\n\", name.c_str());\n }\n }\n\n return loc;\n}\n\n\/**\n * Use the shader.\n *\n * Note: has to be called before any setters are used!\n *\/\nvoid AnyShader::useShader(bool active) {\n if (!active) {\n glUseProgram(prog);\n }\n}\n\n\/\/\n\/\/ AnyAminoShader\n\/\/\n\nAnyAminoShader::AnyAminoShader() : AnyShader() {\n \/\/default vertex shader\n vertexShader = R\"(\n uniform mat4 mvp;\n uniform mat4 trans;\n\n attribute vec4 pos;\n\n void main() {\n gl_Position = mvp * trans * pos;\n }\n )\";\n}\n\n\/**\n * Initialize the shader.\n *\/\nvoid AnyAminoShader::initShader() {\n useShader(false);\n\n \/\/attributes\n aPos = getAttributeLocation(\"pos\");\n\n \/\/uniforms\n uMVP = getUniformLocation(\"mvp\");\n uTrans = getUniformLocation(\"trans\");\n}\n\n\/**\n * Set transformation matrix.\n *\/\nvoid AnyAminoShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {\n glUniformMatrix4fv(uMVP, 1, GL_FALSE, modelView);\n glUniformMatrix4fv(uTrans, 1, GL_FALSE, transition);\n}\n\n\/**\n * Set vertex data.\n *\/\nvoid AnyAminoShader::setVertexData(GLsizei dim, GLfloat *vertices) {\n \/*\n * Coords per vertex (2 or 3).\n *\n * Note: vertices is NULL in case of VBO usage\n *\/\n\n glVertexAttribPointer(aPos, dim, GL_FLOAT, GL_FALSE, 0, vertices);\n}\n\n\/**\n * Draw triangles.\n *\/\nvoid AnyAminoShader::drawTriangles(GLsizei vertices, GLenum mode) {\n glEnableVertexAttribArray(aPos);\n\n glDrawArrays(mode, 0, vertices);\n\n glDisableVertexAttribArray(aPos);\n}\n\n\/**\n * Draw elements.\n *\/\nvoid AnyAminoShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {\n glEnableVertexAttribArray(aPos);\n\n \/\/Note: indices is offset in case of VBO\n glDrawElements(mode, elements, GL_UNSIGNED_SHORT, indices);\n\n glDisableVertexAttribArray(aPos);\n}\n\n\/\/\n\/\/ ColorShader\n\/\/\n\n\/**\n * Create color shader.\n *\/\nColorShader::ColorShader() : AnyAminoShader() {\n \/\/shaders\n fragmentShader = R\"(\n uniform vec4 color;\n\n void main() {\n gl_FragColor = color;\n }\n )\";\n}\n\n\/**\n * Initialize the color shader.\n *\/\nvoid ColorShader::initShader() {\n AnyAminoShader::initShader();\n\n \/\/uniforms\n uColor = getUniformLocation(\"color\");\n}\n\n\/**\n * Set color.\n *\/\nvoid ColorShader::setColor(GLfloat color[4]) {\n glUniform4f(uColor, color[0], color[1], color[2], color[3]);\n}\n\n\/\/\n\/\/ ColorLightingShader\n\/\/\n\n\/**\n * Create color lighting shader.\n *\/\nColorLightingShader::ColorLightingShader() : ColorShader() {\n \/\/shaders\n vertexShader = R\"(\n uniform mat4 mvp;\n uniform mat4 trans;\n\n \/\/uniform mat4 normalMatrix;\n uniform vec3 lightDir;\n\n attribute vec4 pos;\n attribute vec3 normal;\n\n varying float lightFac;\n\n void main() {\n gl_Position = mvp * trans * pos;\n\n \/\/simple version\n vec4 normalTrans = trans * vec4(normal, 0.);\n\n lightFac = abs(dot(normalTrans.xyz, -lightDir));\n\n \/\/normalMatrix version\n \/\/vec4 normalTrans = mvp * normalMatrix * vec4(normal, 1.);\n \/\/lightFac = max(dot(normalTrans.xyz, -lightDir), 0.);\n }\n )\";\n\n fragmentShader = R\"(\n varying float lightFac;\n\n uniform vec4 color;\n\n void main() {\n gl_FragColor = vec4(color.rgb * lightFac, color.a);\n }\n )\";\n}\n\n\/**\n * Initialize the color lighting shader.\n *\/\nvoid ColorLightingShader::initShader() {\n ColorShader::initShader();\n\n \/\/attributes\n aNormal = getAttributeLocation(\"normal\");\n\n \/\/uniforms\n \/\/uNormalMatrix = getUniformLocation(\"normalMatrix\");\n uLightDir = getUniformLocation(\"lightDir\");\n\n \/\/default values\n GLfloat lightDir[3] = { 0, 0, -1 }; \/\/parallel light on screen\n\n setLightDirection(lightDir);\n}\n\n\/**\n * Set light direction.\n *\/\nvoid ColorLightingShader::setLightDirection(GLfloat dir[3]) {\n glUniform3f(uLightDir, dir[0], dir[1], dir[2]);\n}\n\n\/**\n * Set normal vectors.\n *\/\nvoid ColorLightingShader::setNormalVectors(GLfloat *normals) {\n glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, normals);\n}\n\n\/**\n * Set matrix.\n *\/\nvoid ColorLightingShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {\n AnyAminoShader::setTransformation(modelView, transition);\n\n \/\/normal matrix\n \/*\n GLfloat invMatrix[16];\n GLfloat normalMatrix[16];\n\n assert(invert_matrix(transition, invMatrix));\n transpose_matrix(normalMatrix, invMatrix);\n\n glUniformMatrix4fv(uNormalMatrix, 1, GL_FALSE, normalMatrix);\n *\/\n}\n\n\/**\n * Draw triangles.\n *\/\nvoid ColorLightingShader::drawTriangles(GLsizei vertices, GLenum mode) {\n glEnableVertexAttribArray(aNormal);\n\n AnyAminoShader::drawTriangles(vertices, mode);\n\n glDisableVertexAttribArray(aNormal);\n}\n\n\/**\n * Draw elements.\n *\/\nvoid ColorLightingShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {\n glEnableVertexAttribArray(aNormal);\n\n AnyAminoShader::drawElements(indices, elements, mode);\n\n glDisableVertexAttribArray(aNormal);\n}\n\n\/\/\n\/\/ TextureShader\n\/\/\n\nTextureShader::TextureShader() : AnyAminoShader() {\n \/\/shader\n vertexShader = R\"(\n uniform mat4 mvp;\n uniform mat4 trans;\n\n attribute vec4 pos;\n attribute vec2 texCoord;\n\n varying vec2 uv;\n\n void main() {\n gl_Position = mvp * trans * pos;\n uv = texCoord;\n }\n )\";\n\n fragmentShader = R\"(\n varying vec2 uv;\n\n uniform float opacity;\n uniform sampler2D tex;\n\n void main() {\n vec4 pixel = texture2D(tex, uv);\n\n gl_FragColor = vec4(pixel.rgb, pixel.a * opacity);\n }\n )\";\n}\n\n\/**\n * Initialize the color shader.\n *\/\nvoid TextureShader::initShader() {\n AnyAminoShader::initShader();\n\n \/\/attributes\n aTexCoord = getAttributeLocation(\"texCoord\");\n\n \/\/uniforms\n uOpacity = getUniformLocation(\"opacity\");\n uTex = getUniformLocation(\"tex\");\n\n \/\/default values\n glUniform1i(uTex, 0); \/\/GL_TEXTURE0\n}\n\n\/**\n * Set opacity.\n *\/\nvoid TextureShader::setOpacity(GLfloat opacity) {\n glUniform1f(uOpacity, opacity);\n}\n\n\/**\n * Set texture coordinates.\n *\/\nvoid TextureShader::setTextureCoordinates(GLfloat uv[][2]) {\n glVertexAttribPointer(aTexCoord, 2, GL_FLOAT, GL_FALSE, 0, uv);\n}\n\n\/**\n * Draw texture.\n *\/\nvoid TextureShader::drawTriangles(GLsizei vertices, GLenum mode) {\n glEnableVertexAttribArray(aTexCoord);\n\n glActiveTexture(GL_TEXTURE0);\n\n AnyAminoShader::drawTriangles(vertices, mode);\n\n glDisableVertexAttribArray(aTexCoord);\n}\n\n\/**\n * Draw elements.\n *\/\nvoid TextureShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {\n glEnableVertexAttribArray(aTexCoord);\n\n glActiveTexture(GL_TEXTURE0);\n\n AnyAminoShader::drawElements(indices, elements, mode);\n\n glDisableVertexAttribArray(aTexCoord);\n}\n\n\/\/\n\/\/ TextureClampToBorderShader\n\/\/\n\n\nTextureClampToBorderShader::TextureClampToBorderShader() : TextureShader() {\n \/\/Note: supports clamp to border, using transparent texture\n fragmentShader = R\"(\n varying vec2 uv;\n\n uniform float opacity;\n uniform sampler2D tex;\n\n float clamp_to_border_factor(vec2 coords) {\n bvec2 out1 = greaterThan(coords, vec2(1, 1));\n bvec2 out2 = lessThan(coords, vec2(0, 0));\n bool do_clamp = (any(out1) || any(out2));\n\n return float(!do_clamp);\n }\n\n void main() {\n vec4 pixel = texture2D(tex, uv);\n\n gl_FragColor = vec4(pixel.rgb, pixel.a * opacity * clamp_to_border_factor(uv));\n }\n )\";\n}\n\n\/\/\n\/\/ TextureLightingShader\n\/\/\n\n\/**\n * Create color lighting shader.\n *\/\nTextureLightingShader::TextureLightingShader() : TextureShader() {\n \/\/shaders\n vertexShader = R\"(\n uniform mat4 mvp;\n uniform mat4 trans;\n\n uniform vec3 lightDir;\n\n attribute vec4 pos;\n attribute vec2 texCoord;\n attribute vec3 normal;\n\n varying vec2 uv;\n varying float lightFac;\n\n void main() {\n gl_Position = mvp * trans * pos;\n\n uv = texCoord;\n\n vec4 normalTrans = trans * vec4(normal, 0.);\n\n \/\/translucent layers\n lightFac = abs(dot(normalTrans.xyz, -lightDir));\n }\n )\";\n\n fragmentShader = R\"(\n varying vec2 uv;\n varying float lightFac;\n\n uniform float opacity;\n uniform sampler2D tex;\n\n void main() {\n vec4 pixel = texture2D(tex, uv);\n\n gl_FragColor = vec4(pixel.rgb * lightFac, pixel.a * opacity);\n }\n )\";\n}\n\n\/**\n * Initialize the color lighting shader.\n *\/\nvoid TextureLightingShader::initShader() {\n TextureShader::initShader();\n\n \/\/attributes\n aNormal = getAttributeLocation(\"normal\");\n\n \/\/uniforms\n \/\/uNormalMatrix = getUniformLocation(\"normalMatrix\");\n uLightDir = getUniformLocation(\"lightDir\");\n\n \/\/default values\n GLfloat lightDir[3] = { 0, 0, -1 }; \/\/parallel light on screen\n\n setLightDirection(lightDir);\n}\n\n\/**\n * Set light direction.\n *\/\nvoid TextureLightingShader::setLightDirection(GLfloat dir[3]) {\n glUniform3f(uLightDir, dir[0], dir[1], dir[2]);\n}\n\n\/**\n * Set normal vectors.\n *\/\nvoid TextureLightingShader::setNormalVectors(GLfloat *normals) {\n glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, normals);\n}\n\n\/**\n * Draw triangles.\n *\/\nvoid TextureLightingShader::drawTriangles(GLsizei vertices, GLenum mode) {\n glEnableVertexAttribArray(aNormal);\n\n TextureShader::drawTriangles(vertices, mode);\n\n glDisableVertexAttribArray(aNormal);\n}\n\n\/**\n * Draw elements.\n *\/\nvoid TextureLightingShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {\n glEnableVertexAttribArray(aNormal);\n\n TextureShader::drawElements(indices, elements, mode);\n\n glDisableVertexAttribArray(aNormal);\n}\n<commit_msg>shader cleanup<commit_after>#include \"shaders.h\"\n\n\/\/#include \"mathutils.h\"\n\n#define INVALID_SHADER 0\n\n#define DEBUG_SHADER_ERRORS true\n\n\/\/\n\/\/ AnyShader\n\/\/\n\nAnyShader::AnyShader() {\n \/\/empty\n}\n\nAnyShader::~AnyShader() {\n \/\/empty\n}\n\n\/**\n * Create the shader program.\n *\/\nbool AnyShader::create() {\n if (failed) {\n return false;\n }\n\n if (prog != INVALID_PROGRAM) {\n return true;\n }\n\n \/\/compile\n GLuint handle = glCreateProgram();\n\n if (handle == INVALID_PROGRAM) {\n error = \"glCreateProgram failed.\";\n\n return false;\n }\n\n if (!vertexShader.empty()) {\n GLuint vertShader = compileShader(vertexShader, GL_VERTEX_SHADER);\n\n if (vertShader == INVALID_SHADER) {\n \/\/cleanup\n glDeleteProgram(handle);\n\n return false;\n }\n\n glAttachShader(handle, vertShader);\n glDeleteShader(vertShader);\n }\n\n if (!fragmentShader.empty()) {\n GLuint fragShader = compileShader(fragmentShader, GL_FRAGMENT_SHADER);\n\n if (fragShader == INVALID_SHADER) {\n \/\/cleanup\n glDeleteProgram(handle);\n\n return false;\n }\n\n glAttachShader(handle, fragShader);\n glDeleteShader(fragShader);\n }\n\n \/\/link\n glLinkProgram(handle);\n\n GLint linkStatus;\n\n glGetProgramiv(handle, GL_LINK_STATUS, &linkStatus);\n\n if (linkStatus == GL_FALSE) {\n \/\/cleanup\n glDeleteProgram(handle);\n\n \/\/get error\n GLchar messages[256];\n\n glGetProgramInfoLog(handle, sizeof(messages), 0, &messages[0]);\n\n if (DEBUG_SHADER_ERRORS) {\n printf(\"shader linking failed: %s\\n\", messages);\n }\n\n return false;\n }\n\n prog = handle;\n\n \/\/initialize\n initShader();\n\n return true;\n}\n\n\/**\n * Compile a shader.\n *\n * Note: sets error on failure.\n *\/\nGLuint AnyShader::compileShader(std::string source, const GLenum type) {\n GLint compileStatus;\n GLuint handle = glCreateShader(type);\n\n if (handle == INVALID_SHADER) {\n error = \"glCreateShader() failed\";\n return -1;\n }\n\n#ifdef RPI\n \/\/add GLSL version\n source = \"#version 100\\n\" + source;\n#endif\n\n GLchar *src = (GLchar *)source.c_str();\n\n glShaderSource(handle, 1, (const GLchar **)&src, NULL);\n glCompileShader(handle);\n\n \/\/get status\n glGetShaderiv(handle, GL_COMPILE_STATUS, &compileStatus);\n\n if (compileStatus == GL_FALSE) {\n \/\/free\n glDeleteShader(handle);\n handle = INVALID_SHADER;\n\n \/\/get error\n GLchar messages[256];\n\n glGetShaderInfoLog(handle, sizeof(messages), 0, &messages[0]);\n\n if (DEBUG_SHADER_ERRORS) {\n std::string typeStr;\n\n if (type == GL_VERTEX_SHADER) {\n typeStr = \"vertex shader\";\n } else if (type == GL_FRAGMENT_SHADER) {\n typeStr = \"fragment shader\";\n }\n\n printf(\"shader compilation error: %s\\ntype: %s\\n\", messages, typeStr.c_str());\n }\n\n error = std::string(messages);\n }\n\n return handle;\n}\n\n\/**\n * Destroy the shader.\n *\n * Note: has to be called in OpenGL thread.\n *\/\nvoid AnyShader::destroy() {\n if (prog != INVALID_PROGRAM) {\n glDeleteProgram(prog);\n prog = INVALID_PROGRAM;\n }\n\n \/\/reset failed\n failed = false;\n}\n\n\/**\n * Get attribute location.\n *\/\nGLint AnyShader::getAttributeLocation(std::string name) {\n GLint loc = glGetAttribLocation(prog, name.c_str());\n\n if (DEBUG_SHADER_ERRORS) {\n if (loc == -1) {\n printf(\"could not get location of attribute %s\\n\", name.c_str());\n }\n }\n\n return loc;\n}\n\n\/**\n * Get uniform location.\n *\/\nGLint AnyShader::getUniformLocation(std::string name) {\n GLint loc = glGetUniformLocation(prog, name.c_str());\n\n if (DEBUG_SHADER_ERRORS) {\n if (loc == -1) {\n printf(\"could not get location of uniform %s\\n\", name.c_str());\n }\n }\n\n return loc;\n}\n\n\/**\n * Use the shader.\n *\n * Note: has to be called before any setters are used!\n *\/\nvoid AnyShader::useShader(bool active) {\n if (!active) {\n glUseProgram(prog);\n }\n}\n\n\/\/\n\/\/ AnyAminoShader\n\/\/\n\nAnyAminoShader::AnyAminoShader() : AnyShader() {\n \/\/default vertex shader\n vertexShader = R\"(\n uniform mat4 mvp;\n uniform mat4 trans;\n\n attribute vec4 pos;\n\n void main() {\n gl_Position = mvp * trans * pos;\n }\n )\";\n}\n\n\/**\n * Initialize the shader.\n *\/\nvoid AnyAminoShader::initShader() {\n useShader(false);\n\n \/\/attributes\n aPos = getAttributeLocation(\"pos\");\n\n \/\/uniforms\n uMVP = getUniformLocation(\"mvp\");\n uTrans = getUniformLocation(\"trans\");\n}\n\n\/**\n * Set transformation matrix.\n *\/\nvoid AnyAminoShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {\n glUniformMatrix4fv(uMVP, 1, GL_FALSE, modelView);\n glUniformMatrix4fv(uTrans, 1, GL_FALSE, transition);\n}\n\n\/**\n * Set vertex data.\n *\/\nvoid AnyAminoShader::setVertexData(GLsizei dim, GLfloat *vertices) {\n \/*\n * Coords per vertex (2 or 3).\n *\n * Note: vertices is NULL in case of VBO usage\n *\/\n\n glVertexAttribPointer(aPos, dim, GL_FLOAT, GL_FALSE, 0, vertices);\n}\n\n\/**\n * Draw triangles.\n *\/\nvoid AnyAminoShader::drawTriangles(GLsizei vertices, GLenum mode) {\n glEnableVertexAttribArray(aPos);\n\n glDrawArrays(mode, 0, vertices);\n\n glDisableVertexAttribArray(aPos);\n}\n\n\/**\n * Draw elements.\n *\/\nvoid AnyAminoShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {\n glEnableVertexAttribArray(aPos);\n\n \/\/Note: indices is offset in case of VBO\n glDrawElements(mode, elements, GL_UNSIGNED_SHORT, indices);\n\n glDisableVertexAttribArray(aPos);\n}\n\n\/\/\n\/\/ ColorShader\n\/\/\n\n\/**\n * Create color shader.\n *\/\nColorShader::ColorShader() : AnyAminoShader() {\n \/\/shaders\n fragmentShader = R\"(\n uniform vec4 color;\n\n void main() {\n gl_FragColor = color;\n }\n )\";\n}\n\n\/**\n * Initialize the color shader.\n *\/\nvoid ColorShader::initShader() {\n AnyAminoShader::initShader();\n\n \/\/uniforms\n uColor = getUniformLocation(\"color\");\n}\n\n\/**\n * Set color.\n *\/\nvoid ColorShader::setColor(GLfloat color[4]) {\n glUniform4f(uColor, color[0], color[1], color[2], color[3]);\n}\n\n\/\/\n\/\/ ColorLightingShader\n\/\/\n\n\/**\n * Create color lighting shader.\n *\/\nColorLightingShader::ColorLightingShader() : ColorShader() {\n \/\/shaders\n vertexShader = R\"(\n uniform mat4 mvp;\n uniform mat4 trans;\n\n \/\/uniform mat4 normalMatrix;\n uniform vec3 lightDir;\n\n attribute vec4 pos;\n attribute vec3 normal;\n\n varying float lightFac;\n\n void main() {\n gl_Position = mvp * trans * pos;\n\n \/\/simple version\n vec4 normalTrans = trans * vec4(normal, 0.);\n\n lightFac = abs(dot(normalTrans.xyz, -lightDir));\n }\n )\";\n\n fragmentShader = R\"(\n varying float lightFac;\n\n uniform vec4 color;\n\n void main() {\n gl_FragColor = vec4(color.rgb * lightFac, color.a);\n }\n )\";\n}\n\n\/**\n * Initialize the color lighting shader.\n *\/\nvoid ColorLightingShader::initShader() {\n ColorShader::initShader();\n\n \/\/attributes\n aNormal = getAttributeLocation(\"normal\");\n\n \/\/uniforms\n \/\/uNormalMatrix = getUniformLocation(\"normalMatrix\");\n uLightDir = getUniformLocation(\"lightDir\");\n\n \/\/default values\n GLfloat lightDir[3] = { 0, 0, -1 }; \/\/parallel light on screen\n\n setLightDirection(lightDir);\n}\n\n\/**\n * Set light direction.\n *\/\nvoid ColorLightingShader::setLightDirection(GLfloat dir[3]) {\n glUniform3f(uLightDir, dir[0], dir[1], dir[2]);\n}\n\n\/**\n * Set normal vectors.\n *\/\nvoid ColorLightingShader::setNormalVectors(GLfloat *normals) {\n glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, normals);\n}\n\n\/**\n * Set matrix.\n *\/\nvoid ColorLightingShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {\n AnyAminoShader::setTransformation(modelView, transition);\n\n \/\/normal matrix\n \/*\n GLfloat invMatrix[16];\n GLfloat normalMatrix[16];\n\n assert(invert_matrix(transition, invMatrix));\n transpose_matrix(normalMatrix, invMatrix);\n\n glUniformMatrix4fv(uNormalMatrix, 1, GL_FALSE, normalMatrix);\n *\/\n}\n\n\/**\n * Draw triangles.\n *\/\nvoid ColorLightingShader::drawTriangles(GLsizei vertices, GLenum mode) {\n glEnableVertexAttribArray(aNormal);\n\n AnyAminoShader::drawTriangles(vertices, mode);\n\n glDisableVertexAttribArray(aNormal);\n}\n\n\/**\n * Draw elements.\n *\/\nvoid ColorLightingShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {\n glEnableVertexAttribArray(aNormal);\n\n AnyAminoShader::drawElements(indices, elements, mode);\n\n glDisableVertexAttribArray(aNormal);\n}\n\n\/\/\n\/\/ TextureShader\n\/\/\n\nTextureShader::TextureShader() : AnyAminoShader() {\n \/\/shader\n vertexShader = R\"(\n uniform mat4 mvp;\n uniform mat4 trans;\n\n attribute vec4 pos;\n attribute vec2 texCoord;\n\n varying vec2 uv;\n\n void main() {\n gl_Position = mvp * trans * pos;\n uv = texCoord;\n }\n )\";\n\n fragmentShader = R\"(\n varying vec2 uv;\n\n uniform float opacity;\n uniform sampler2D tex;\n\n void main() {\n vec4 pixel = texture2D(tex, uv);\n\n gl_FragColor = vec4(pixel.rgb, pixel.a * opacity);\n }\n )\";\n}\n\n\/**\n * Initialize the color shader.\n *\/\nvoid TextureShader::initShader() {\n AnyAminoShader::initShader();\n\n \/\/attributes\n aTexCoord = getAttributeLocation(\"texCoord\");\n\n \/\/uniforms\n uOpacity = getUniformLocation(\"opacity\");\n uTex = getUniformLocation(\"tex\");\n\n \/\/default values\n glUniform1i(uTex, 0); \/\/GL_TEXTURE0\n}\n\n\/**\n * Set opacity.\n *\/\nvoid TextureShader::setOpacity(GLfloat opacity) {\n glUniform1f(uOpacity, opacity);\n}\n\n\/**\n * Set texture coordinates.\n *\/\nvoid TextureShader::setTextureCoordinates(GLfloat uv[][2]) {\n glVertexAttribPointer(aTexCoord, 2, GL_FLOAT, GL_FALSE, 0, uv);\n}\n\n\/**\n * Draw texture.\n *\/\nvoid TextureShader::drawTriangles(GLsizei vertices, GLenum mode) {\n glEnableVertexAttribArray(aTexCoord);\n\n glActiveTexture(GL_TEXTURE0);\n\n AnyAminoShader::drawTriangles(vertices, mode);\n\n glDisableVertexAttribArray(aTexCoord);\n}\n\n\/**\n * Draw elements.\n *\/\nvoid TextureShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {\n glEnableVertexAttribArray(aTexCoord);\n\n glActiveTexture(GL_TEXTURE0);\n\n AnyAminoShader::drawElements(indices, elements, mode);\n\n glDisableVertexAttribArray(aTexCoord);\n}\n\n\/\/\n\/\/ TextureClampToBorderShader\n\/\/\n\n\nTextureClampToBorderShader::TextureClampToBorderShader() : TextureShader() {\n \/\/Note: supports clamp to border, using transparent texture\n fragmentShader = R\"(\n varying vec2 uv;\n\n uniform float opacity;\n uniform sampler2D tex;\n\n float clamp_to_border_factor(vec2 coords) {\n bvec2 out1 = greaterThan(coords, vec2(1, 1));\n bvec2 out2 = lessThan(coords, vec2(0, 0));\n bool do_clamp = (any(out1) || any(out2));\n\n return float(!do_clamp);\n }\n\n void main() {\n vec4 pixel = texture2D(tex, uv);\n\n gl_FragColor = vec4(pixel.rgb, pixel.a * opacity * clamp_to_border_factor(uv));\n }\n )\";\n}\n\n\/\/\n\/\/ TextureLightingShader\n\/\/\n\n\/**\n * Create color lighting shader.\n *\/\nTextureLightingShader::TextureLightingShader() : TextureShader() {\n \/\/shaders\n vertexShader = R\"(\n uniform mat4 mvp;\n uniform mat4 trans;\n\n uniform vec3 lightDir;\n\n attribute vec4 pos;\n attribute vec2 texCoord;\n attribute vec3 normal;\n\n varying vec2 uv;\n varying float lightFac;\n\n void main() {\n gl_Position = mvp * trans * pos;\n\n uv = texCoord;\n\n vec4 normalTrans = trans * vec4(normal, 0.);\n\n \/\/translucent layers\n lightFac = abs(dot(normalTrans.xyz, -lightDir));\n }\n )\";\n\n fragmentShader = R\"(\n varying vec2 uv;\n varying float lightFac;\n\n uniform float opacity;\n uniform sampler2D tex;\n\n void main() {\n vec4 pixel = texture2D(tex, uv);\n\n gl_FragColor = vec4(pixel.rgb * lightFac, pixel.a * opacity);\n }\n )\";\n}\n\n\/**\n * Initialize the color lighting shader.\n *\/\nvoid TextureLightingShader::initShader() {\n TextureShader::initShader();\n\n \/\/attributes\n aNormal = getAttributeLocation(\"normal\");\n\n \/\/uniforms\n \/\/uNormalMatrix = getUniformLocation(\"normalMatrix\");\n uLightDir = getUniformLocation(\"lightDir\");\n\n \/\/default values\n GLfloat lightDir[3] = { 0, 0, -1 }; \/\/parallel light on screen\n\n setLightDirection(lightDir);\n}\n\n\/**\n * Set light direction.\n *\/\nvoid TextureLightingShader::setLightDirection(GLfloat dir[3]) {\n glUniform3f(uLightDir, dir[0], dir[1], dir[2]);\n}\n\n\/**\n * Set normal vectors.\n *\/\nvoid TextureLightingShader::setNormalVectors(GLfloat *normals) {\n glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, normals);\n}\n\n\/**\n * Draw triangles.\n *\/\nvoid TextureLightingShader::drawTriangles(GLsizei vertices, GLenum mode) {\n glEnableVertexAttribArray(aNormal);\n\n TextureShader::drawTriangles(vertices, mode);\n\n glDisableVertexAttribArray(aNormal);\n}\n\n\/**\n * Draw elements.\n *\/\nvoid TextureLightingShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {\n glEnableVertexAttribArray(aNormal);\n\n TextureShader::drawElements(indices, elements, mode);\n\n glDisableVertexAttribArray(aNormal);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"unittest.hxx\"\n\n#include \"vigra\/accessor.hxx\"\n#include \"vigra\/tinyvector.hxx\"\n#include \"vigra\/rgbvalue.hxx\"\n\nusing namespace vigra;\n\nstatic float di[] = {1, 2, 4 };\nstatic float df[] = {1.2, 2.4, 3.6 };\n\ntemplate <class BVector, class IVector, class FVector>\nstruct TinyVectorTest\n{\n typedef BVector BV;\n typedef IVector IV;\n typedef FVector FV; \n \n BV bv0, bv1, bv3;\n IV iv0, iv1, iv3;\n FV fv0, fv1, fv3;\n \n template <class VECTOR>\n void printVector(VECTOR const & v)\n {\n std::cerr << \"(\";\n for(int i=0; i<v.size(); ++i)\n std::cerr << (float)v[i] << \", \";\n std::cerr << \")\\n\";\n }\n \n template <class VECTOR, class VALUE>\n bool equalValue(VECTOR const & v, VALUE const & vv)\n {\n for(int i=0; i<v.size(); ++i)\n if(v[i] != vv)\n return false;\n return true;\n }\n \n template <class VECTOR1, class VECTOR2>\n bool equalVector(VECTOR1 const & v1, VECTOR2 const & v2)\n {\n for(int i=0; i<v1.size(); ++i)\n if(v1[i] != v2[i])\n return false;\n return true;\n }\n \n template <class ITER1, class ITER2>\n bool equalIter(ITER1 i1, ITER1 i1end, ITER2 i2)\n {\n if(i1end - i1 != 3)\n return false;\n for(; i1<i1end; ++i1, ++i2)\n if(*i1 != *i2)\n return false;\n return true;\n }\n \n TinyVectorTest()\n : bv0(0), bv1(1), bv3(), \n iv0(0), iv1(1), iv3(), \n fv0(0.0), fv1(1.0), fv3()\n {\n bv3.init(df, df+3);\n iv3.init(df, df+3);\n fv3.init(df, df+3);\n }\n \n void testConstruction()\n {\n should(bv0.size() == 3);\n should(iv0.size() == 3);\n should(fv0.size() == 3);\n \n should(equalValue(bv0, 0));\n should(equalValue(iv0, 0));\n should(equalValue(fv0, 0.0f));\n \n should(equalValue(bv1, 1));\n should(equalValue(iv1, 1));\n should(equalValue(fv1, 1.0f));\n \n should(equalIter(bv3.begin(), bv3.end(), di));\n should(equalIter(iv3.begin(), iv3.end(), di));\n should(equalIter(fv3.begin(), fv3.end(), df));\n \n should(!equalVector(bv3, fv3));\n should(!equalVector(iv3, fv3));\n \n BV bv(fv3);\n should(equalIter(bv3.begin(), bv3.end(), bv.begin()));\n should(equalVector(bv3, bv));\n \n FV fv(iv3);\n should(equalIter(iv3.begin(), iv3.end(), fv.begin()));\n should(equalVector(iv3, fv));\n \n fv = fv3;\n should(equalIter(fv3.begin(), fv3.end(), fv.begin()));\n should(equalVector(fv3, fv));\n \n fv = bv3;\n should(equalIter(bv3.begin(), bv3.end(), fv.begin()));\n should(equalVector(bv3, fv));\n }\n \n void testComparison()\n {\n should(bv0 == bv0);\n should(iv0 == iv0);\n should(fv0 == fv0);\n should(iv0 == bv0);\n should(iv0 == fv0);\n should(fv0 == bv0);\n \n should(bv3 == bv3);\n should(iv3 == iv3);\n should(fv3 == fv3);\n should(iv3 == bv3);\n should(iv3 != fv3);\n should(fv3 != bv3);\n }\n \n void testArithmetic()\n {\n IV ivm3 = -iv3;\n FV fvm3 = -fv3;\n \n int mi[] = { -1, -2, -4};\n float mf[] = { -1.2, -2.4, -3.6 };\n \n should(equalIter(ivm3.begin(), ivm3.end(), mi));\n should(equalIter(fvm3.begin(), fvm3.end(), mf));\n \n IV iva3 = abs(ivm3);\n FV fva3 = abs(fvm3);\n should(equalVector(iv3, iva3));\n should(equalVector(fv3, fva3));\n \n int fmi[] = { -2, -3, -4};\n int fpi[] = { 1, 2, 3};\n IV ivi3 = floor(fvm3);\n should(equalIter(ivi3.begin(), ivi3.end(), fmi));\n ivi3 = -ceil(fv3);\n should(equalIter(ivi3.begin(), ivi3.end(), fmi));\n ivi3 = floor(fv3);\n should(equalIter(ivi3.begin(), ivi3.end(), fpi));\n ivi3 = -ceil(fvm3);\n should(equalIter(ivi3.begin(), ivi3.end(), fpi));\n \n should(bv1.squaredMagnitude() == 3);\n should(iv1.squaredMagnitude() == 3);\n should(fv1.squaredMagnitude() == 3.0);\n \n shouldEqualTolerance(fv3.squaredMagnitude(), (1.2f*1.2f + 2.4f*2.4f + 3.6f*3.6f), 1e-7f);\n \n should(dot(bv3, bv3) == bv3.squaredMagnitude());\n should(dot(iv3, bv3) == iv3.squaredMagnitude());\n should(dot(fv3, fv3) == fv3.squaredMagnitude());\n \n should(sqrt(dot(bv3, bv3)) == bv3.magnitude());\n should(sqrt(dot(iv3, bv3)) == iv3.magnitude());\n should(sqrt(dot(fv3, fv3)) == fv3.magnitude());\n \n BV bv = bv3;\n bv[2] = 200;\n should(dot(bv, bv) == 40005);\n should(bv.squaredMagnitude() == 40005);\n \n should(equalVector(bv3 - iv3, bv0));\n should(equalVector(fv3 - fv3, fv0));\n BV bvp = (bv3 + bv3)*0.5;\n FV fvp = (fv3 + fv3)*0.5;\n should(equalVector(bvp, bv3));\n should(equalVector(fvp, fv3));\n bvp = 2.0*bv3 - bv3;\n fvp = 2.0*fv3 - fv3;\n should(equalVector(bvp, bv3));\n should(equalVector(fvp, fv3));\n \n IV ivp = bv + bv;\n int ip1[] = {2, 4, 400};\n should(equalIter(ivp.begin(), ivp.end(), ip1));\n should(equalVector(bv0 - iv1, -iv1));\n \n bvp = bv3 \/ 2.0;\n fvp = bv3 \/ 2.0;\n int ip[] = {1, 1, 2};\n float fp[] = {0.5, 1.0, 2.0};\n should(equalIter(bvp.begin(), bvp.end(), ip));\n should(equalIter(fvp.begin(), fvp.end(), fp));\n fvp = fv3 \/ 2.0;\n float fp1[] = {0.6, 1.2, 1.8};\n should(equalIter(fvp.begin(), fvp.end(), fp1));\n }\n \n void testAccessor()\n {\n vigra::VectorAccessor<FV> v;\n FV pfa[] = {fv3, fv1};\n FV * pf = pfa;\n \n should(v.size(pf) == 3);\n should(v.size(pf, 1) == 3);\n should(equalVector(v(pf), fv3));\n should(equalIter(v.begin(pf), v.end(pf), fv3.begin()));\n should(v.getComponent(pf, 2) == fv3[2]);\n v.setComponent(5.5, pf, 1);\n should(pf[0][1] == 5.5);\n should(equalVector(v(pf, 1), fv1));\n should(equalIter(v.begin(pf, 1), v.end(pf, 1), fv1.begin()));\n should(v.getComponent(pf, 1, 2) == fv1[2]);\n v.setComponent(5.5, pf, 1, 1);\n should(pf[1][1] == 5.5);\n }\n};\n\nstruct RGBValueTest\n: public TinyVectorTest<vigra::RGBValue<unsigned char>,\n vigra::RGBValue<int>,\n vigra::RGBValue<float> > \n{\n typedef TinyVectorTest<vigra::RGBValue<unsigned char>,\n vigra::RGBValue<int>,\n vigra::RGBValue<float> > Base;\n \n RGBValueTest()\n : Base()\n {}\n \n \n void testRGBAccessors()\n {\n vigra::RGBAccessor<FV> rgb;\n vigra::RedAccessor<FV> red;\n vigra::GreenAccessor<FV> green;\n vigra::BlueAccessor<FV> blue;\n vigra::RGBToGrayAccessor<FV> gray;\n \n FV pfa[] = { FV(0.0), FV(1.0)};\n FV * pf = pfa;\n \n should(rgb(pf) == vigra::NumericTraits<FV>::zero());\n should(red(pf) == 0.0);\n should(green(pf) == 0.0);\n should(blue(pf) == 0.0);\n should(gray(pf) == 0.0);\n \n should(rgb(pf, 1) == vigra::NumericTraits<FV>::one());\n should(red(pf, 1) == 1.0);\n should(green(pf, 1) == 1.0);\n should(blue(pf, 1) == 1.0);\n should(gray(pf, 1) == 1.0);\n \n rgb.setRed(1.0, pf);\n rgb.setGreen(2.0, pf);\n rgb.setBlue(3.0, pf);\n should(red(pf) == 1.0);\n should(green(pf) == 2.0);\n should(blue(pf) == 3.0);\n \n red.set(4.0, pf);\n green.set(5.0, pf);\n blue.set(6.0, pf);\n should(rgb.red(pf) == 4.0);\n should(rgb.green(pf) == 5.0);\n should(rgb.blue(pf) == 6.0);\n should(vigra::abs(gray(pf) - 4.81) < 0.00001);\n \n rgb.setRed(7.0, pf, 1);\n rgb.setGreen(8.0, pf, 1);\n rgb.setBlue(9.0, pf, 1);\n should(red(pf, 1) == 7.0);\n should(green(pf, 1) == 8.0);\n should(blue(pf, 1) == 9.0);\n \n red.set(10.0, pf, 1);\n green.set(11.0, pf, 1);\n blue.set(12.0, pf, 1);\n should(rgb.red(pf, 1) == 10.0);\n should(rgb.green(pf, 1) == 11.0);\n should(rgb.blue(pf, 1) == 12.0);\n should(vigra::abs(gray(pf, 1) - 10.81) <0.00001);\n }\n \n};\n\nstruct PixelTypesTestSuite\n: public vigra::test_suite\n{\n typedef TinyVectorTest<vigra::TinyVector<unsigned char, 3>,\n vigra::TinyVector<int, 3>,\n vigra::TinyVector<float, 3> > TinyVectorTest;\n \n PixelTypesTestSuite()\n : vigra::test_suite(\"PixelTypesTest\")\n {\n add( testCase(&TinyVectorTest::testConstruction));\n add( testCase(&TinyVectorTest::testComparison));\n add( testCase(&TinyVectorTest::testArithmetic));\n add( testCase(&TinyVectorTest::testAccessor));\n\n add( testCase(&RGBValueTest::testConstruction));\n add( testCase(&RGBValueTest::testComparison));\n add( testCase(&RGBValueTest::testArithmetic));\n add( testCase(&RGBValueTest::testAccessor));\n add( testCase(&RGBValueTest::testRGBAccessors));\n }\n};\n\nint main()\n{\n PixelTypesTestSuite test;\n\n int failed = test.run();\n\n std::cout << test.report() << std::endl;\n\n return (failed != 0);\n}\n<commit_msg>added typecasts necessary for g++ 3<commit_after>#include <iostream>\n#include \"unittest.hxx\"\n\n#include \"vigra\/accessor.hxx\"\n#include \"vigra\/tinyvector.hxx\"\n#include \"vigra\/rgbvalue.hxx\"\n\nusing namespace vigra;\n\nstatic float di[] = {1, 2, 4 };\nstatic float df[] = {1.2, 2.4, 3.6 };\n\ntemplate <class BVector, class IVector, class FVector>\nstruct TinyVectorTest\n{\n typedef BVector BV;\n typedef IVector IV;\n typedef FVector FV; \n \n BV bv0, bv1, bv3;\n IV iv0, iv1, iv3;\n FV fv0, fv1, fv3;\n \n template <class VECTOR>\n void printVector(VECTOR const & v)\n {\n std::cerr << \"(\";\n for(int i=0; i<v.size(); ++i)\n std::cerr << (float)v[i] << \", \";\n std::cerr << \")\\n\";\n }\n \n template <class VECTOR, class VALUE>\n bool equalValue(VECTOR const & v, VALUE const & vv)\n {\n for(int i=0; i<v.size(); ++i)\n if(v[i] != vv)\n return false;\n return true;\n }\n \n template <class VECTOR1, class VECTOR2>\n bool equalVector(VECTOR1 const & v1, VECTOR2 const & v2)\n {\n for(int i=0; i<v1.size(); ++i)\n if(v1[i] != v2[i])\n return false;\n return true;\n }\n \n template <class ITER1, class ITER2>\n bool equalIter(ITER1 i1, ITER1 i1end, ITER2 i2)\n {\n if(i1end - i1 != 3)\n return false;\n for(; i1<i1end; ++i1, ++i2)\n if(*i1 != *i2)\n return false;\n return true;\n }\n \n TinyVectorTest()\n : bv0(0), bv1(1), bv3(), \n iv0(0), iv1(1), iv3(), \n fv0(0.0), fv1(1.0), fv3()\n {\n bv3.init(df, df+3);\n iv3.init(df, df+3);\n fv3.init(df, df+3);\n }\n \n void testConstruction()\n {\n should(bv0.size() == 3);\n should(iv0.size() == 3);\n should(fv0.size() == 3);\n \n should(equalValue(bv0, 0));\n should(equalValue(iv0, 0));\n should(equalValue(fv0, 0.0f));\n \n should(equalValue(bv1, 1));\n should(equalValue(iv1, 1));\n should(equalValue(fv1, 1.0f));\n \n should(equalIter(bv3.begin(), bv3.end(), di));\n should(equalIter(iv3.begin(), iv3.end(), di));\n should(equalIter(fv3.begin(), fv3.end(), df));\n \n should(!equalVector(bv3, fv3));\n should(!equalVector(iv3, fv3));\n \n BV bv(fv3);\n should(equalIter(bv3.begin(), bv3.end(), bv.begin()));\n should(equalVector(bv3, bv));\n \n FV fv(iv3);\n should(equalIter(iv3.begin(), iv3.end(), fv.begin()));\n should(equalVector(iv3, fv));\n \n fv = fv3;\n should(equalIter(fv3.begin(), fv3.end(), fv.begin()));\n should(equalVector(fv3, fv));\n \n fv = bv3;\n should(equalIter(bv3.begin(), bv3.end(), fv.begin()));\n should(equalVector(bv3, fv));\n }\n \n void testComparison()\n {\n should(bv0 == bv0);\n should(iv0 == iv0);\n should(fv0 == fv0);\n should(iv0 == bv0);\n should(iv0 == fv0);\n should(fv0 == bv0);\n \n should(bv3 == bv3);\n should(iv3 == iv3);\n should(fv3 == fv3);\n should(iv3 == bv3);\n should(iv3 != fv3);\n should(fv3 != bv3);\n }\n \n void testArithmetic()\n {\n IV ivm3 = -iv3;\n FV fvm3 = -fv3;\n \n int mi[] = { -1, -2, -4};\n float mf[] = { -1.2, -2.4, -3.6 };\n \n should(equalIter(ivm3.begin(), ivm3.end(), mi));\n should(equalIter(fvm3.begin(), fvm3.end(), mf));\n \n IV iva3 = abs(ivm3);\n FV fva3 = abs(fvm3);\n should(equalVector(iv3, iva3));\n should(equalVector(fv3, fva3));\n \n int fmi[] = { -2, -3, -4};\n int fpi[] = { 1, 2, 3};\n IV ivi3 = floor(fvm3);\n should(equalIter(ivi3.begin(), ivi3.end(), fmi));\n ivi3 = -ceil(fv3);\n should(equalIter(ivi3.begin(), ivi3.end(), fmi));\n ivi3 = floor(fv3);\n should(equalIter(ivi3.begin(), ivi3.end(), fpi));\n ivi3 = -ceil(fvm3);\n should(equalIter(ivi3.begin(), ivi3.end(), fpi));\n \n should(bv1.squaredMagnitude() == 3);\n should(iv1.squaredMagnitude() == 3);\n should(fv1.squaredMagnitude() == 3.0);\n \n shouldEqualTolerance(fv3.squaredMagnitude(), (1.2f*1.2f + 2.4f*2.4f + 3.6f*3.6f), 1e-7f);\n \n should(dot(bv3, bv3) == bv3.squaredMagnitude());\n should(dot(iv3, bv3) == iv3.squaredMagnitude());\n should(dot(fv3, fv3) == fv3.squaredMagnitude());\n \n shouldEqualTolerance(VIGRA_CSTD::sqrt(\n (NumericTraits<typename BV::value_type>::RealPromote)\n dot(bv3, bv3)), bv3.magnitude(), 0.0);\n shouldEqualTolerance(VIGRA_CSTD::sqrt(\n (NumericTraits<typename IV::value_type>::RealPromote)\n dot(iv3, bv3)), iv3.magnitude(), 0.0);\n shouldEqualTolerance(VIGRA_CSTD::sqrt(\n (NumericTraits<typename FV::value_type>::RealPromote)\n dot(fv3, fv3)), fv3.magnitude(), 0.0);\n \n BV bv = bv3;\n bv[2] = 200;\n should(dot(bv, bv) == 40005);\n should(bv.squaredMagnitude() == 40005);\n \n should(equalVector(bv3 - iv3, bv0));\n should(equalVector(fv3 - fv3, fv0));\n BV bvp = (bv3 + bv3)*0.5;\n FV fvp = (fv3 + fv3)*0.5;\n should(equalVector(bvp, bv3));\n should(equalVector(fvp, fv3));\n bvp = 2.0*bv3 - bv3;\n fvp = 2.0*fv3 - fv3;\n should(equalVector(bvp, bv3));\n should(equalVector(fvp, fv3));\n \n IV ivp = bv + bv;\n int ip1[] = {2, 4, 400};\n should(equalIter(ivp.begin(), ivp.end(), ip1));\n should(equalVector(bv0 - iv1, -iv1));\n \n bvp = bv3 \/ 2.0;\n fvp = bv3 \/ 2.0;\n int ip[] = {1, 1, 2};\n float fp[] = {0.5, 1.0, 2.0};\n should(equalIter(bvp.begin(), bvp.end(), ip));\n should(equalIter(fvp.begin(), fvp.end(), fp));\n fvp = fv3 \/ 2.0;\n float fp1[] = {0.6, 1.2, 1.8};\n should(equalIter(fvp.begin(), fvp.end(), fp1));\n }\n \n void testAccessor()\n {\n vigra::VectorAccessor<FV> v;\n FV pfa[] = {fv3, fv1};\n FV * pf = pfa;\n \n should(v.size(pf) == 3);\n should(v.size(pf, 1) == 3);\n should(equalVector(v(pf), fv3));\n should(equalIter(v.begin(pf), v.end(pf), fv3.begin()));\n should(v.getComponent(pf, 2) == fv3[2]);\n v.setComponent(5.5, pf, 1);\n should(pf[0][1] == 5.5);\n should(equalVector(v(pf, 1), fv1));\n should(equalIter(v.begin(pf, 1), v.end(pf, 1), fv1.begin()));\n should(v.getComponent(pf, 1, 2) == fv1[2]);\n v.setComponent(5.5, pf, 1, 1);\n should(pf[1][1] == 5.5);\n }\n};\n\nstruct RGBValueTest\n: public TinyVectorTest<vigra::RGBValue<unsigned char>,\n vigra::RGBValue<int>,\n vigra::RGBValue<float> > \n{\n typedef TinyVectorTest<vigra::RGBValue<unsigned char>,\n vigra::RGBValue<int>,\n vigra::RGBValue<float> > Base;\n \n RGBValueTest()\n : Base()\n {}\n \n \n void testRGBAccessors()\n {\n vigra::RGBAccessor<FV> rgb;\n vigra::RedAccessor<FV> red;\n vigra::GreenAccessor<FV> green;\n vigra::BlueAccessor<FV> blue;\n vigra::RGBToGrayAccessor<FV> gray;\n \n FV pfa[] = { FV(0.0), FV(1.0)};\n FV * pf = pfa;\n \n should(rgb(pf) == vigra::NumericTraits<FV>::zero());\n should(red(pf) == 0.0);\n should(green(pf) == 0.0);\n should(blue(pf) == 0.0);\n should(gray(pf) == 0.0);\n \n should(rgb(pf, 1) == vigra::NumericTraits<FV>::one());\n should(red(pf, 1) == 1.0);\n should(green(pf, 1) == 1.0);\n should(blue(pf, 1) == 1.0);\n should(gray(pf, 1) == 1.0);\n \n rgb.setRed(1.0, pf);\n rgb.setGreen(2.0, pf);\n rgb.setBlue(3.0, pf);\n should(red(pf) == 1.0);\n should(green(pf) == 2.0);\n should(blue(pf) == 3.0);\n \n red.set(4.0, pf);\n green.set(5.0, pf);\n blue.set(6.0, pf);\n should(rgb.red(pf) == 4.0);\n should(rgb.green(pf) == 5.0);\n should(rgb.blue(pf) == 6.0);\n should(vigra::abs(gray(pf) - 4.81) < 0.00001);\n \n rgb.setRed(7.0, pf, 1);\n rgb.setGreen(8.0, pf, 1);\n rgb.setBlue(9.0, pf, 1);\n should(red(pf, 1) == 7.0);\n should(green(pf, 1) == 8.0);\n should(blue(pf, 1) == 9.0);\n \n red.set(10.0, pf, 1);\n green.set(11.0, pf, 1);\n blue.set(12.0, pf, 1);\n should(rgb.red(pf, 1) == 10.0);\n should(rgb.green(pf, 1) == 11.0);\n should(rgb.blue(pf, 1) == 12.0);\n should(vigra::abs(gray(pf, 1) - 10.81) <0.00001);\n }\n \n};\n\nstruct PixelTypesTestSuite\n: public vigra::test_suite\n{\n typedef TinyVectorTest<vigra::TinyVector<unsigned char, 3>,\n vigra::TinyVector<int, 3>,\n vigra::TinyVector<float, 3> > TinyVectorTest;\n \n PixelTypesTestSuite()\n : vigra::test_suite(\"PixelTypesTest\")\n {\n add( testCase(&TinyVectorTest::testConstruction));\n add( testCase(&TinyVectorTest::testComparison));\n add( testCase(&TinyVectorTest::testArithmetic));\n add( testCase(&TinyVectorTest::testAccessor));\n\n add( testCase(&RGBValueTest::testConstruction));\n add( testCase(&RGBValueTest::testComparison));\n add( testCase(&RGBValueTest::testArithmetic));\n add( testCase(&RGBValueTest::testAccessor));\n add( testCase(&RGBValueTest::testRGBAccessors));\n }\n};\n\nint main()\n{\n PixelTypesTestSuite test;\n\n int failed = test.run();\n\n std::cout << test.report() << std::endl;\n\n return (failed != 0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ThreadUtils.hpp\n\/\/ Pods\n\/\/\n\/\/ Created by eps on 6\/16\/20.\n\/\/\n\n#ifndef EE_X_THREAD_UTILS_HPP\n#define EE_X_THREAD_UTILS_HPP\n\n#ifdef __cplusplus\n\n#include <future>\n\n#include \"ee\/CoreFwd.hpp\"\n\nnamespace ee {\nnamespace core {\ntemplate <class T = void>\nusing Runnable = std::function<T()>;\n\nclass Thread {\npublic:\n \/\/\/ Checks whether the current thread is the UI thread (Android) or Main\n \/\/\/ thread (iOS).\n static bool isMainThread();\n\n \/\/\/ Runs the specified runnable on the main thread.\n \/\/\/ @returns Whether the function is executed immediately.\n static bool runOnMainThread(const Runnable<>& runnable);\n\n \/\/\/ Runs the specifieid runnable on the main thread after a delay.\n static void runOnMainThreadDelayed(const Runnable<>& runnable, float delay);\n};\n\n\/\/\/ Runs the specified runnable on the main thread and block the current\n\/\/\/ thread. If the current thread is the main thread, it will be executed\n\/\/\/ immediately.\n[[deprecated]] void runOnUiThreadAndWait(const Runnable<>& runnable);\n\ntemplate <class T>\n[[deprecated]] T runOnUiThreadAndWaitResult(const Runnable<T>& runnable) {\n std::promise<T> promise;\n runOnUiThread([runnable, &promise] { \/\/ Fix clang-format.\n promise.set_value(runnable());\n });\n return promise.get_future().get();\n}\n} \/\/ namespace core\n\nconstexpr auto isMainThread = &Thread::isMainThread;\nconstexpr auto runOnMainThread = &Thread::runOnMainThread;\nconstexpr auto runOnMainThreadDelayed = &Thread::runOnMainThreadDelayed;\n[[deprecated]] constexpr auto runOnUiThread = runOnMainThread;\n[[deprecated]] constexpr auto runOnUiThreadDelayed = runOnMainThreadDelayed;\nusing core::runOnUiThreadAndWait;\nusing core::runOnUiThreadAndWaitResult;\n} \/\/ namespace ee\n\n#endif \/\/ __cplusplus\n\n#if defined(EE_X_IOS) || defined(EE_X_OSX)\n#ifdef __cplusplus\nextern \"C\" {\n#endif \/\/ __cplusplus\n\nextern void ee_runOnMainThreadCallback();\nextern void ee_runOnMainThreadDelayedCallback(int key);\n\n#ifdef __cplusplus\n} \/\/ extern \"C\"\n#endif \/\/ __cplusplus\n#endif \/\/ defined(EE_X_IOS) || defined(EE_X_OSX)\n\n#endif \/* EE_X_THREAD_UTILS_HPP *\/\n<commit_msg>Rename header guard.<commit_after>\/\/\n\/\/ ThreadUtils.hpp\n\/\/ Pods\n\/\/\n\/\/ Created by eps on 6\/16\/20.\n\/\/\n\n#ifndef EE_X_THREAD_HPP\n#define EE_X_THREAD_HPP\n\n#ifdef __cplusplus\n\n#include <future>\n\n#include \"ee\/CoreFwd.hpp\"\n\nnamespace ee {\nnamespace core {\ntemplate <class T = void>\nusing Runnable = std::function<T()>;\n\nclass Thread {\npublic:\n \/\/\/ Checks whether the current thread is the UI thread (Android) or Main\n \/\/\/ thread (iOS).\n static bool isMainThread();\n\n \/\/\/ Runs the specified runnable on the main thread.\n \/\/\/ @returns Whether the function is executed immediately.\n static bool runOnMainThread(const Runnable<>& runnable);\n\n \/\/\/ Runs the specifieid runnable on the main thread after a delay.\n static void runOnMainThreadDelayed(const Runnable<>& runnable, float delay);\n};\n\n\/\/\/ Runs the specified runnable on the main thread and block the current\n\/\/\/ thread. If the current thread is the main thread, it will be executed\n\/\/\/ immediately.\n[[deprecated]] void runOnUiThreadAndWait(const Runnable<>& runnable);\n\ntemplate <class T>\n[[deprecated]] T runOnUiThreadAndWaitResult(const Runnable<T>& runnable) {\n std::promise<T> promise;\n runOnUiThread([runnable, &promise] { \/\/ Fix clang-format.\n promise.set_value(runnable());\n });\n return promise.get_future().get();\n}\n} \/\/ namespace core\n\nconstexpr auto isMainThread = &Thread::isMainThread;\nconstexpr auto runOnMainThread = &Thread::runOnMainThread;\nconstexpr auto runOnMainThreadDelayed = &Thread::runOnMainThreadDelayed;\n[[deprecated]] constexpr auto runOnUiThread = runOnMainThread;\n[[deprecated]] constexpr auto runOnUiThreadDelayed = runOnMainThreadDelayed;\nusing core::runOnUiThreadAndWait;\nusing core::runOnUiThreadAndWaitResult;\n} \/\/ namespace ee\n\n#endif \/\/ __cplusplus\n\n#if defined(EE_X_IOS) || defined(EE_X_OSX)\n#ifdef __cplusplus\nextern \"C\" {\n#endif \/\/ __cplusplus\n\nextern void ee_runOnMainThreadCallback();\nextern void ee_runOnMainThreadDelayedCallback(int key);\n\n#ifdef __cplusplus\n} \/\/ extern \"C\"\n#endif \/\/ __cplusplus\n#endif \/\/ defined(EE_X_IOS) || defined(EE_X_OSX)\n\n#endif \/* EE_X_THREAD_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <cstring>\n#include <cerrno>\n#include <cstdlib>\n#include <cstdio>\n#include <string>\n#include <mist\/stream.h>\n#include <mist\/defines.h>\n\n#include \"input_av.h\"\n\nnamespace Mist {\n inputAV::inputAV(Util::Config * cfg) : Input(cfg) {\n pFormatCtx = 0;\n capa[\"name\"] = \"AV\";\n capa[\"decs\"] = \"Enables generic avformat\/avcodec based input\";\n capa[\"source_match\"] = \"\/*\";\n capa[\"priority\"] = 1ll;\n capa[\"codecs\"][0u][0u].null();\n capa[\"codecs\"][0u][1u].null();\n capa[\"codecs\"][0u][2u].null();\n av_register_all();\n AVCodec * cInfo = 0;\n while ((cInfo = av_codec_next(cInfo)) != 0){\n if (cInfo->type == AVMEDIA_TYPE_VIDEO){\n capa[\"codecs\"][0u][0u].append(cInfo->name);\n }\n if (cInfo->type == AVMEDIA_TYPE_AUDIO){\n capa[\"codecs\"][0u][1u].append(cInfo->name);\n }\n if (cInfo->type == AVMEDIA_TYPE_SUBTITLE){\n capa[\"codecs\"][0u][3u].append(cInfo->name);\n }\n }\n }\n\n inputAV::~inputAV(){\n if (pFormatCtx){\n avformat_close_input(&pFormatCtx);\n }\n }\n \n bool inputAV::setup() {\n if (config->getString(\"input\") == \"-\") {\n std::cerr << \"Input from stdin not yet supported\" << std::endl;\n return false;\n }\n if (!config->getString(\"streamname\").size()){\n if (config->getString(\"output\") == \"-\") {\n std::cerr << \"Output to stdout not yet supported\" << std::endl;\n return false;\n }\n }else{\n if (config->getString(\"output\") != \"-\") {\n std::cerr << \"File output in player mode not supported\" << std::endl;\n return false;\n }\n }\n\n \/\/make sure all av inputs are registered properly, just in case\n \/\/setup() already does this, but under windows it doesn't remember that it has.\n \/\/Very sad, that. We may need to get windows some medication for it.\n av_register_all();\n \n \/\/close any already open files\n if (pFormatCtx){\n avformat_close_input(&pFormatCtx);\n pFormatCtx = 0;\n }\n \n \/\/Open video file\n int ret = avformat_open_input(&pFormatCtx, config->getString(\"input\").c_str(), NULL, NULL);\n if(ret != 0){\n char errstr[300];\n av_strerror(ret, errstr, 300);\n DEBUG_MSG(DLVL_FAIL, \"Could not open file: %s\", errstr);\n return false; \/\/ Couldn't open file\n }\n \n \/\/Retrieve stream information\n ret = avformat_find_stream_info(pFormatCtx, NULL);\n if(ret < 0){\n char errstr[300];\n av_strerror(ret, errstr, 300);\n DEBUG_MSG(DLVL_FAIL, \"Could not find stream info: %s\", errstr);\n return false;\n }\n return true;\n }\n\n bool inputAV::readHeader() {\n \/\/See whether a separate header file exists.\n if (readExistingHeader()){return true;}\n\n myMeta.tracks.clear();\n for(unsigned int i=0; i < pFormatCtx->nb_streams; ){\n AVStream * strm = pFormatCtx->streams[i++];\n myMeta.tracks[i].trackID = i;\n switch (strm->codec->codec_id){\n case AV_CODEC_ID_HEVC:\n myMeta.tracks[i].codec = \"HEVC\";\n break;\n case AV_CODEC_ID_H264:\n myMeta.tracks[i].codec = \"H264\";\n break;\n case AV_CODEC_ID_THEORA:\n myMeta.tracks[i].codec = \"theora\";\n break;\n case AV_CODEC_ID_VORBIS:\n myMeta.tracks[i].codec = \"vorbis\";\n break;\n case AV_CODEC_ID_OPUS:\n myMeta.tracks[i].codec = \"opus\";\n break;\n case AV_CODEC_ID_AAC:\n myMeta.tracks[i].codec = \"AAC\";\n break;\n case AV_CODEC_ID_MP3:\n myMeta.tracks[i].codec = \"MP3\";\n break;\n case AV_CODEC_ID_AC3:\n case AV_CODEC_ID_EAC3:\n myMeta.tracks[i].codec = \"AC3\";\n break; \n default:\n const AVCodecDescriptor *desc = av_codec_get_codec_descriptor(strm->codec);\n if (desc && desc->name){\n myMeta.tracks[i].codec = desc->name;\n }else{\n myMeta.tracks[i].codec = \"?\";\n }\n break;\n }\n if (strm->codec->extradata_size){\n myMeta.tracks[i].init = std::string((char*)strm->codec->extradata, strm->codec->extradata_size);\n }\n if(strm->codec->codec_type == AVMEDIA_TYPE_VIDEO){\n myMeta.tracks[i].type = \"video\";\n if (strm->avg_frame_rate.den && strm->avg_frame_rate.num){\n myMeta.tracks[i].fpks = (strm->avg_frame_rate.num * 1000) \/ strm->avg_frame_rate.den;\n }else{\n myMeta.tracks[i].fpks = 0;\n }\n myMeta.tracks[i].width = strm->codec->width;\n myMeta.tracks[i].height = strm->codec->height;\n }\n if(strm->codec->codec_type == AVMEDIA_TYPE_AUDIO){\n myMeta.tracks[i].type = \"audio\";\n myMeta.tracks[i].rate = strm->codec->sample_rate;\n switch (strm->codec->sample_fmt){\n case AV_SAMPLE_FMT_U8:\n case AV_SAMPLE_FMT_U8P:\n myMeta.tracks[i].size = 8;\n break;\n case AV_SAMPLE_FMT_S16:\n case AV_SAMPLE_FMT_S16P:\n myMeta.tracks[i].size = 16;\n break;\n case AV_SAMPLE_FMT_S32:\n case AV_SAMPLE_FMT_S32P:\n case AV_SAMPLE_FMT_FLT:\n case AV_SAMPLE_FMT_FLTP:\n myMeta.tracks[i].size = 32;\n break;\n case AV_SAMPLE_FMT_DBL:\n case AV_SAMPLE_FMT_DBLP:\n myMeta.tracks[i].size = 64;\n break;\n default:\n myMeta.tracks[i].size = 0;\n break;\n }\n myMeta.tracks[i].channels = strm->codec->channels;\n }\n }\n \n AVPacket packet;\n while(av_read_frame(pFormatCtx, &packet)>=0){\n AVStream * strm = pFormatCtx->streams[packet.stream_index];\n long long packTime = (packet.dts * 1000 * strm->time_base.num \/ strm->time_base.den);\n long long packOffset = 0;\n bool isKey = false;\n if (packTime < 0){\n packTime = 0;\n }\n if (packet.flags & AV_PKT_FLAG_KEY && myMeta.tracks[(long long)packet.stream_index + 1].type != \"audio\"){\n isKey = true;\n }\n if (packet.pts != AV_NOPTS_VALUE && packet.pts != packet.dts){\n packOffset = ((packet.pts - packet.dts) * 1000 * strm->time_base.num \/ strm->time_base.den);\n }\n myMeta.update(packTime, packOffset, packet.stream_index + 1, packet.size, packet.pos, isKey);\n av_free_packet(&packet);\n }\n \n myMeta.toFile(config->getString(\"input\") + \".dtsh\");\n \n seek(0);\n return true;\n }\n \n void inputAV::getNext(bool smart) {\n AVPacket packet;\n while (av_read_frame(pFormatCtx, &packet)>=0){\n \/\/filter tracks we don't care about\n if (!selectedTracks.count(packet.stream_index + 1)){\n DEBUG_MSG(DLVL_HIGH, \"Track %u not selected\", packet.stream_index + 1);\n continue;\n }\n AVStream * strm = pFormatCtx->streams[packet.stream_index];\n long long packTime = (packet.dts * 1000 * strm->time_base.num \/ strm->time_base.den);\n long long packOffset = 0;\n bool isKey = false;\n if (packTime < 0){\n packTime = 0;\n }\n if (packet.flags & AV_PKT_FLAG_KEY && myMeta.tracks[(long long)packet.stream_index + 1].type != \"audio\"){\n isKey = true;\n }\n if (packet.pts != AV_NOPTS_VALUE && packet.pts != packet.dts){\n packOffset = ((packet.pts - packet.dts) * 1000 * strm->time_base.num \/ strm->time_base.den);\n }\n thisPacket.genericFill(packTime, packOffset, packet.stream_index + 1, (const char*)packet.data, packet.size, 0, isKey);\n av_free_packet(&packet);\n return;\/\/success!\n }\n thisPacket.null();\n setup();\n \/\/failure :-(\n DEBUG_MSG(DLVL_FAIL, \"getNext failed\");\n }\n\n void inputAV::seek(int seekTime) {\n int stream_index = av_find_default_stream_index(pFormatCtx);\n \/\/Convert ts to frame\n unsigned long long reseekTime = av_rescale(seekTime, pFormatCtx->streams[stream_index]->time_base.den, pFormatCtx->streams[stream_index]->time_base.num);\n reseekTime \/= 1000;\n unsigned long long seekStreamDuration = pFormatCtx->streams[stream_index]->duration;\n int flags = AVSEEK_FLAG_BACKWARD;\n if (reseekTime > 0 && reseekTime < seekStreamDuration){\n flags |= AVSEEK_FLAG_ANY; \/\/ H.264 I frames don't always register as \"key frames\" in FFmpeg\n }\n int ret = av_seek_frame(pFormatCtx, stream_index, reseekTime, flags);\n if (ret < 0){\n ret = av_seek_frame(pFormatCtx, stream_index, reseekTime, AVSEEK_FLAG_ANY);\n }\n }\n\n void inputAV::trackSelect(std::string trackSpec) {\n selectedTracks.clear();\n long long unsigned int index;\n while (trackSpec != \"\") {\n index = trackSpec.find(' ');\n selectedTracks.insert(atoi(trackSpec.substr(0, index).c_str()));\n if (index != std::string::npos) {\n trackSpec.erase(0, index + 1);\n } else {\n trackSpec = \"\";\n }\n }\n \/\/inFile.selectTracks(selectedTracks);\n }\n}\n\n<commit_msg>Updated MistInAV in line with recent libavformat deprecations<commit_after>#include <iostream>\n#include <fstream>\n#include <cstring>\n#include <cerrno>\n#include <cstdlib>\n#include <cstdio>\n#include <string>\n#include <mist\/stream.h>\n#include <mist\/defines.h>\n\n#include \"input_av.h\"\n\nnamespace Mist {\n inputAV::inputAV(Util::Config * cfg) : Input(cfg) {\n pFormatCtx = 0;\n capa[\"name\"] = \"AV\";\n capa[\"decs\"] = \"Enables generic avformat\/avcodec based input\";\n capa[\"source_match\"] = \"\/*\";\n capa[\"priority\"] = 1ll;\n capa[\"codecs\"][0u][0u].null();\n capa[\"codecs\"][0u][1u].null();\n capa[\"codecs\"][0u][2u].null();\n av_register_all();\n AVCodec * cInfo = 0;\n while ((cInfo = av_codec_next(cInfo)) != 0){\n if (cInfo->type == AVMEDIA_TYPE_VIDEO){\n capa[\"codecs\"][0u][0u].append(cInfo->name);\n }\n if (cInfo->type == AVMEDIA_TYPE_AUDIO){\n capa[\"codecs\"][0u][1u].append(cInfo->name);\n }\n if (cInfo->type == AVMEDIA_TYPE_SUBTITLE){\n capa[\"codecs\"][0u][3u].append(cInfo->name);\n }\n }\n }\n\n inputAV::~inputAV(){\n if (pFormatCtx){\n avformat_close_input(&pFormatCtx);\n }\n }\n \n bool inputAV::setup() {\n if (config->getString(\"input\") == \"-\") {\n std::cerr << \"Input from stdin not yet supported\" << std::endl;\n return false;\n }\n if (!config->getString(\"streamname\").size()){\n if (config->getString(\"output\") == \"-\") {\n std::cerr << \"Output to stdout not yet supported\" << std::endl;\n return false;\n }\n }else{\n if (config->getString(\"output\") != \"-\") {\n std::cerr << \"File output in player mode not supported\" << std::endl;\n return false;\n }\n }\n\n \/\/make sure all av inputs are registered properly, just in case\n \/\/setup() already does this, but under windows it doesn't remember that it has.\n \/\/Very sad, that. We may need to get windows some medication for it.\n av_register_all();\n \n \/\/close any already open files\n if (pFormatCtx){\n avformat_close_input(&pFormatCtx);\n pFormatCtx = 0;\n }\n \n \/\/Open video file\n int ret = avformat_open_input(&pFormatCtx, config->getString(\"input\").c_str(), NULL, NULL);\n if(ret != 0){\n char errstr[300];\n av_strerror(ret, errstr, 300);\n DEBUG_MSG(DLVL_FAIL, \"Could not open file: %s\", errstr);\n return false; \/\/ Couldn't open file\n }\n \n \/\/Retrieve stream information\n ret = avformat_find_stream_info(pFormatCtx, NULL);\n if(ret < 0){\n char errstr[300];\n av_strerror(ret, errstr, 300);\n DEBUG_MSG(DLVL_FAIL, \"Could not find stream info: %s\", errstr);\n return false;\n }\n return true;\n }\n\n bool inputAV::readHeader() {\n \/\/See whether a separate header file exists.\n if (readExistingHeader()){return true;}\n\n myMeta.tracks.clear();\n for(unsigned int i=0; i < pFormatCtx->nb_streams; ){\n AVStream * strm = pFormatCtx->streams[i++];\n myMeta.tracks[i].trackID = i;\n switch (strm->codecpar->codec_id){\n case AV_CODEC_ID_HEVC:\n myMeta.tracks[i].codec = \"HEVC\";\n break;\n case AV_CODEC_ID_H264:\n myMeta.tracks[i].codec = \"H264\";\n break;\n case AV_CODEC_ID_THEORA:\n myMeta.tracks[i].codec = \"theora\";\n break;\n case AV_CODEC_ID_VORBIS:\n myMeta.tracks[i].codec = \"vorbis\";\n break;\n case AV_CODEC_ID_OPUS:\n myMeta.tracks[i].codec = \"opus\";\n break;\n case AV_CODEC_ID_AAC:\n myMeta.tracks[i].codec = \"AAC\";\n break;\n case AV_CODEC_ID_MP3:\n myMeta.tracks[i].codec = \"MP3\";\n break;\n case AV_CODEC_ID_AC3:\n case AV_CODEC_ID_EAC3:\n myMeta.tracks[i].codec = \"AC3\";\n break; \n default:\n const AVCodecDescriptor *desc = avcodec_descriptor_get(strm->codecpar->codec_id);\n if (desc && desc->name){\n myMeta.tracks[i].codec = desc->name;\n }else{\n myMeta.tracks[i].codec = \"?\";\n }\n break;\n }\n if (strm->codecpar->extradata_size){\n myMeta.tracks[i].init = std::string((char*)strm->codecpar->extradata, strm->codecpar->extradata_size);\n }\n if(strm->codecpar->codec_type == AVMEDIA_TYPE_VIDEO){\n myMeta.tracks[i].type = \"video\";\n if (strm->avg_frame_rate.den && strm->avg_frame_rate.num){\n myMeta.tracks[i].fpks = (strm->avg_frame_rate.num * 1000) \/ strm->avg_frame_rate.den;\n }else{\n myMeta.tracks[i].fpks = 0;\n }\n myMeta.tracks[i].width = strm->codecpar->width;\n myMeta.tracks[i].height = strm->codecpar->height;\n }\n if(strm->codecpar->codec_type == AVMEDIA_TYPE_AUDIO){\n myMeta.tracks[i].type = \"audio\";\n myMeta.tracks[i].rate = strm->codecpar->sample_rate;\n myMeta.tracks[i].size = strm->codecpar->frame_size;\n myMeta.tracks[i].channels = strm->codecpar->channels;\n }\n }\n \n AVPacket packet;\n while(av_read_frame(pFormatCtx, &packet)>=0){\n AVStream * strm = pFormatCtx->streams[packet.stream_index];\n long long packTime = (packet.dts * 1000 * strm->time_base.num \/ strm->time_base.den);\n long long packOffset = 0;\n bool isKey = false;\n if (packTime < 0){\n packTime = 0;\n }\n if (packet.flags & AV_PKT_FLAG_KEY && myMeta.tracks[(long long)packet.stream_index + 1].type != \"audio\"){\n isKey = true;\n }\n if (packet.pts != AV_NOPTS_VALUE && packet.pts != packet.dts){\n packOffset = ((packet.pts - packet.dts) * 1000 * strm->time_base.num \/ strm->time_base.den);\n }\n myMeta.update(packTime, packOffset, packet.stream_index + 1, packet.size, packet.pos, isKey);\n av_packet_unref(&packet);\n }\n \n myMeta.toFile(config->getString(\"input\") + \".dtsh\");\n \n seek(0);\n return true;\n }\n \n void inputAV::getNext(bool smart) {\n AVPacket packet;\n while (av_read_frame(pFormatCtx, &packet)>=0){\n \/\/filter tracks we don't care about\n if (!selectedTracks.count(packet.stream_index + 1)){\n DEBUG_MSG(DLVL_HIGH, \"Track %u not selected\", packet.stream_index + 1);\n continue;\n }\n AVStream * strm = pFormatCtx->streams[packet.stream_index];\n long long packTime = (packet.dts * 1000 * strm->time_base.num \/ strm->time_base.den);\n long long packOffset = 0;\n bool isKey = false;\n if (packTime < 0){\n packTime = 0;\n }\n if (packet.flags & AV_PKT_FLAG_KEY && myMeta.tracks[(long long)packet.stream_index + 1].type != \"audio\"){\n isKey = true;\n }\n if (packet.pts != AV_NOPTS_VALUE && packet.pts != packet.dts){\n packOffset = ((packet.pts - packet.dts) * 1000 * strm->time_base.num \/ strm->time_base.den);\n }\n thisPacket.genericFill(packTime, packOffset, packet.stream_index + 1, (const char*)packet.data, packet.size, 0, isKey);\n av_packet_unref(&packet);\n return;\/\/success!\n }\n thisPacket.null();\n setup();\n \/\/failure :-(\n DEBUG_MSG(DLVL_FAIL, \"getNext failed\");\n }\n\n void inputAV::seek(int seekTime) {\n int stream_index = av_find_default_stream_index(pFormatCtx);\n \/\/Convert ts to frame\n unsigned long long reseekTime = av_rescale(seekTime, pFormatCtx->streams[stream_index]->time_base.den, pFormatCtx->streams[stream_index]->time_base.num);\n reseekTime \/= 1000;\n unsigned long long seekStreamDuration = pFormatCtx->streams[stream_index]->duration;\n int flags = AVSEEK_FLAG_BACKWARD;\n if (reseekTime > 0 && reseekTime < seekStreamDuration){\n flags |= AVSEEK_FLAG_ANY; \/\/ H.264 I frames don't always register as \"key frames\" in FFmpeg\n }\n int ret = av_seek_frame(pFormatCtx, stream_index, reseekTime, flags);\n if (ret < 0){\n ret = av_seek_frame(pFormatCtx, stream_index, reseekTime, AVSEEK_FLAG_ANY);\n }\n }\n\n void inputAV::trackSelect(std::string trackSpec) {\n selectedTracks.clear();\n long long unsigned int index;\n while (trackSpec != \"\") {\n index = trackSpec.find(' ');\n selectedTracks.insert(atoi(trackSpec.substr(0, index).c_str()));\n if (index != std::string::npos) {\n trackSpec.erase(0, index + 1);\n } else {\n trackSpec = \"\";\n }\n }\n \/\/inFile.selectTracks(selectedTracks);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"generator.h\"\n#include <iostream>\n\nusing namespace lars;\nusing namespace std;\n\n\n\n\nGenerator<int> fibonacci(int n){\n return Generator<int>([=](Yield<int> &yield){\n int a = 0, b = 1;\n for (int i=0;i<n;i++){\n int t = a + b;\n yield(t);\n a = b;\n b = t;\n }\n });\n}\n\nint main(){\n for(int i:fibonacci(10)) std::cout << i << std::endl;\n}\n\n\n<commit_msg>update fibonacci.cpp<commit_after>\n#include \"generator.h\"\n#include <iostream>\n\nusing namespace lars;\nusing namespace std;\n\nGenerator<int> fibonacci(int n){\n return Generator<int>([=](Yield<int> &yield){\n int a = 0, b = 1;\n for (int i=0;i<n;i++){\n int t = a + b;\n yield(t);\n a = b;\n b = t;\n }\n });\n}\n\nint main(){\n for(int i:fibonacci(10)) std::cout << i << std::endl;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/Fibonacci sequence printer!\n#include <iostream>\nusing namespace std;\n\n\nint main()\n{\n\tint n,i;\n\tcout<<\"Welcome to Fibbonacci Sequence Printer!\"<<endl;\n\tcout<<\"Pleas enter the number of terms, you want printed out: \"<<endl;\n\tcin>>n;\n\tcout<<\"First \"<<n<<\" terms of Fibonacci sequence are:\"<<endl;\n\tunsigned long fibo(int);\n\tfor(i=0;i<=n;i++)\n\t{\n\t\tcout<<\"Term(\"<<i<<\")=\"<<fibo(i)<<endl;\n\t}\n\tcout<<\"The Sum of terms of the number you entered:\"<<endl<<\"Fib(\"<<n<<\")=\"<<fibo(i)+fibo(i-1)-1;\n\t\n\tcin.get();\n\tcin.ignore();\n\treturn 0;\n\n}\n\nlong fibo(int x)\n{\n\tif(x==0) return 0;\n\tif(x==1) return 1;\n\telse return fibo(x-2)+fibo(x-1);\n}\n<commit_msg>Delete fibonacci.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <moveit\/collision_detection_fcl\/collision_detector_fcl_plugin_loader.h>\n#include <pluginlib\/class_list_macros.h>\n\nnamespace collision_detection\n{\nbool CollisionDetectorFCLPluginLoader::initialize(const planning_scene::PlanningScenePtr& scene,\n bool exclusive) const\n{\n scene->setActiveCollisionDetector(CollisionDetectorAllocatorFCL::create(), exclusive);\n return true;\n}\n}\n\nPLUGINLIB_EXPORT_CLASS(collision_detection::CollisionDetectorFCLPluginLoader, collision_detection::CollisionPlugin)\n<commit_msg>clang format<commit_after>#include <moveit\/collision_detection_fcl\/collision_detector_fcl_plugin_loader.h>\n#include <pluginlib\/class_list_macros.h>\n\nnamespace collision_detection\n{\nbool CollisionDetectorFCLPluginLoader::initialize(const planning_scene::PlanningScenePtr& scene, bool exclusive) const\n{\n scene->setActiveCollisionDetector(CollisionDetectorAllocatorFCL::create(), exclusive);\n return true;\n}\n}\n\nPLUGINLIB_EXPORT_CLASS(collision_detection::CollisionDetectorFCLPluginLoader, collision_detection::CollisionPlugin)\n<|endoftext|>"} {"text":"<commit_before>#include \"tests.h\"\n\nusing namespace swoole;\n\nTEST(coroutine_base, create)\n{\n long _cid;\n long cid = Coroutine::create([](void *arg)\n {\n *(long *) arg = Coroutine::get_current_cid();\n }, &_cid);\n\n ASSERT_GT(cid, 0);\n ASSERT_EQ(cid, _cid);\n}\n\nTEST(coroutine_base, get_current)\n{\n long _cid;\n long cid = Coroutine::create([](void *arg)\n {\n auto co = Coroutine::get_current();\n *(long *) arg = co->get_cid();\n }, &_cid);\n\n ASSERT_GT(cid, 0);\n ASSERT_EQ(cid, _cid);\n}\n\nTEST(coroutine_base, yield_resume)\n{\n long _cid;\n long cid = Coroutine::create([](void *arg)\n {\n long cid = Coroutine::get_current_cid();\n Coroutine *co = Coroutine::get_by_cid(cid);\n co->yield();\n *(long *) arg = Coroutine::get_current_cid();\n }, &_cid);\n\n ASSERT_GT(cid, 0);\n Coroutine::get_by_cid(cid)->resume();\n ASSERT_EQ(cid, _cid);\n}\n<commit_msg>test: add coroutine core test (#3209)<commit_after>#include \"tests.h\"\n\nusing namespace swoole;\n\nTEST(coroutine_base, create)\n{\n long _cid;\n long cid = Coroutine::create([](void *arg)\n {\n *(long *) arg = Coroutine::get_current_cid();\n }, &_cid);\n\n ASSERT_GT(cid, 0);\n ASSERT_EQ(cid, _cid);\n}\n\nTEST(coroutine_base, get_current)\n{\n long _cid;\n long cid = Coroutine::create([](void *arg)\n {\n auto co = Coroutine::get_current();\n *(long *) arg = co->get_cid();\n }, &_cid);\n\n ASSERT_GT(cid, 0);\n ASSERT_EQ(cid, _cid);\n}\n\nTEST(coroutine_base, yield_resume)\n{\n long _cid;\n long cid = Coroutine::create([](void *arg)\n {\n long cid = Coroutine::get_current_cid();\n Coroutine *co = Coroutine::get_by_cid(cid);\n co->yield();\n *(long *) arg = Coroutine::get_current_cid();\n }, &_cid);\n\n ASSERT_GT(cid, 0);\n Coroutine::get_by_cid(cid)->resume();\n ASSERT_EQ(cid, _cid);\n}\n\nTEST(coroutine_base, get_cid)\n{\n Coroutine::create([](void *arg)\n {\n auto co = Coroutine::get_current();\n long cid = co->get_cid();\n \n ASSERT_GT(cid, 0);\n });\n}\n\nTEST(coroutine_base, get_origin)\n{\n Coroutine::create([](void *arg)\n {\n auto *co = Coroutine::get_current();\n\n Coroutine::create([](void *arg)\n {\n auto current_co = Coroutine::get_current();\n auto origin_co = current_co->get_origin();\n\n ASSERT_EQ(arg, origin_co);\n }, co);\n });\n}\n\nTEST(coroutine_base, get_origin_cid)\n{\n Coroutine::create([](void *arg)\n {\n auto _cid = Coroutine::get_current_cid();\n\n Coroutine::create([](void *arg)\n {\n auto origin_cid = Coroutine::get_current()->get_origin_cid();\n\n ASSERT_EQ(*(long *) arg, origin_cid);\n }, &_cid);\n });\n}\n\nTEST(coroutine_base, is_end)\n{\n Coroutine::create([](void *_arg)\n {\n auto co = Coroutine::get_current();\n ASSERT_FALSE(co->is_end());\n });\n}\n\nTEST(coroutine_base, set_task)\n{\n Coroutine::create([](void *_arg)\n {\n int task;\n auto co = Coroutine::get_current();\n co->set_task(&task);\n void *actual = co->get_task();\n ASSERT_EQ(actual, &task);\n });\n}\n\nTEST(coroutine_base, get_current_task)\n{\n Coroutine::create([](void *_arg)\n {\n int task;\n auto co = Coroutine::get_current();\n co->set_task(&task);\n void *actual = co->get_task();\n ASSERT_EQ(actual, Coroutine::get_current_task());\n });\n}\n\nTEST(coroutine_base, get_current_cid)\n{\n Coroutine::create([](void *_arg)\n {\n auto co = Coroutine::get_current();\n auto actual = co->get_cid();\n ASSERT_EQ(actual, Coroutine::get_current_cid());\n });\n}\n\nTEST(coroutine_base, get_by_cid)\n{\n Coroutine::create([](void *_arg)\n {\n auto actual = Coroutine::get_current();\n auto cid = actual->get_cid();\n ASSERT_EQ(actual, Coroutine::get_by_cid(cid));\n });\n}\n\nTEST(coroutine_base, get_task_by_cid)\n{\n Coroutine::create([](void *_arg)\n {\n int task;\n auto co = Coroutine::get_current();\n co->set_task(&task);\n auto actual = co->get_task();\n ASSERT_EQ(actual, Coroutine::get_task_by_cid(co->get_cid()));\n });\n}\n\nTEST(coroutine_base, get_last_cid)\n{\n Coroutine::create([](void *_arg)\n {\n });\n Coroutine::create([](void *_arg)\n {\n });\n long cid = Coroutine::create([](void *_arg)\n {\n });\n\n ASSERT_EQ(Coroutine::get_last_cid(), cid);\n}\n\nTEST(coroutine_base, count)\n{\n Coroutine::create([](void *_arg)\n {\n ASSERT_EQ(Coroutine::count(), 1);\n Coroutine::create([](void *_arg)\n {\n ASSERT_EQ(Coroutine::count(), 2);\n });\n });\n ASSERT_EQ(Coroutine::count(), 0);\n}\n\nTEST(coroutine_base, get_peak_num)\n{\n Coroutine::create([](void *_arg)\n {\n Coroutine::create([](void *_arg)\n {\n ASSERT_GE(Coroutine::get_peak_num(), 2);\n });\n });\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"testApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid testApp::setup(){\n ofBackground(0,0,0);\n ofSetBackgroundAuto(false);\n isFullScreen = false;\n ofSetFrameRate(30);\n \n masterCounter = 0;\n direction = 1; \/\/count up\n \n \/\/ OSC STUFF\n receiver.setup(PORT);\n\tcurrent_msg_string = 0;\n mainMix = 0;\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::update(){\n\n \/\/ hide old messages\n\tfor(int i = 0; i < NUM_MSG_STRINGS; i++){\n\t\tif(timers[i] < ofGetElapsedTimef()){\n\t\t\tmsg_strings[i] = \"\";\n\t\t}\n\t}\n \n\t\/\/ check for waiting messages\n\twhile(receiver.hasWaitingMessages()){\n\t\t\/\/ get the next message\n\t\tofxOscMessage m;\n\t\treceiver.getNextMessage(&m);\n \n\t\t\/\/ check for mouse moved message\n\t\tif(m.getAddress() == \"\/main\/mix\"){\n\t\t\t\/\/ both the arguments are int32's\n\t\t\tmainMix = m.getArgAsFloat(0);\n ofLogNotice(\"you are the master of the universe\"+ofToString(m.getArgAsFloat(0)));\n\t\t}\n\t\t\/\/ check for mouse button message\n\t\telse{\n\t\t\t\/\/ unrecognized message: display on the bottom of the screen\n\t\t\tstring msg_string;\n\t\t\tmsg_string = m.getAddress();\n\t\t\tmsg_string += \": \";\n\t\t\tfor(int i = 0; i < m.getNumArgs(); i++){\n\t\t\t\t\/\/ get the argument type\n\t\t\t\tmsg_string += m.getArgTypeName(i);\n\t\t\t\tmsg_string += \":\";\n\t\t\t\t\/\/ display the argument - make sure we get the right type\n\t\t\t\tif(m.getArgType(i) == OFXOSC_TYPE_INT32){\n\t\t\t\t\tmsg_string += ofToString(m.getArgAsInt32(i));\n\t\t\t\t}\n\t\t\t\telse if(m.getArgType(i) == OFXOSC_TYPE_FLOAT){\n\t\t\t\t\tmsg_string += ofToString(m.getArgAsFloat(i));\n\t\t\t\t}\n\t\t\t\telse if(m.getArgType(i) == OFXOSC_TYPE_STRING){\n\t\t\t\t\tmsg_string += m.getArgAsString(i);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tmsg_string += \"unknown\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ add to the list of strings to display\n\t\t\tmsg_strings[current_msg_string] = msg_string;\n\t\t\ttimers[current_msg_string] = ofGetElapsedTimef() + 5.0f;\n\t\t\tcurrent_msg_string = (current_msg_string + 1) % NUM_MSG_STRINGS;\n\t\t\t\/\/ clear the next line\n\t\t\tmsg_strings[current_msg_string] = \"\";\n\t\t}\n \n\t}\n \n \/\/ FUN STUFF\n masterCounter+=direction;\n if (masterCounter > 2000) {\n direction = -1;\n }\n if (masterCounter < -2000) {\n direction = 1;\n }\n\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::draw(){\n \/\/normalize mouse (within the window space...\n float daMouseX = float(mouseX)\/float(ofGetWidth());\n float daMouseY = float(mouseY)\/ofGetHeight();\n \/\/ ofLogNotice(ofToString(daMouseX));\n \n \/\/Abstract line stuff\n for (int i = 0; i < ofGetWidth(); i++) {\n int r = daMouseX*sin(masterCounter)\/4;\n int g = i\/4;\n int b = daMouseX*daMouseY*i\/4;\n ofSetColor(r, g, b); \/\/Replace this with pixel colors from feed\n ofLine(i, ofGetHeight()\/2, i*sin(i)*mouseY, i*cos(i)*\/*mouseY*30*\/masterCounter);\n }\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyPressed(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseMoved(int x, int y ){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseReleased(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::windowResized(int w, int h){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::dragEvent(ofDragInfo dragInfo){ \n\n}\n<commit_msg>initial audio reactivity established. mainMix controls *someVariable*<commit_after>#include \"testApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid testApp::setup(){\n ofBackground(0,0,0);\n ofSetBackgroundAuto(false);\n isFullScreen = false;\n ofSetFrameRate(30);\n \n masterCounter = 0;\n direction = 1; \/\/count up\n \n \/\/ OSC STUFF\n receiver.setup(PORT);\n\tcurrent_msg_string = 0;\n mainMix = 0;\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::update(){\n\n \/\/ hide old messages\n\tfor(int i = 0; i < NUM_MSG_STRINGS; i++){\n\t\tif(timers[i] < ofGetElapsedTimef()){\n\t\t\tmsg_strings[i] = \"\";\n\t\t}\n\t}\n \n\t\/\/ check for waiting messages\n\twhile(receiver.hasWaitingMessages()){\n\t\t\/\/ get the next message\n\t\tofxOscMessage m;\n\t\treceiver.getNextMessage(&m);\n \n\t\t\/\/ check for mouse moved message\n\t\tif(m.getAddress() == \"\/main\/mix\"){\n\t\t\t\/\/ both the arguments are int32's\n\t\t\tmainMix = m.getArgAsFloat(0);\n ofLogNotice(\"mainMix: \"+ofToString(m.getArgAsFloat(0)));\n\t\t}\n\t\t\/\/ check for mouse button message\n\t\telse{\n\t\t\t\/\/ unrecognized message: display on the bottom of the screen\n\t\t\tstring msg_string;\n\t\t\tmsg_string = m.getAddress();\n\t\t\tmsg_string += \": \";\n\t\t\tfor(int i = 0; i < m.getNumArgs(); i++){\n\t\t\t\t\/\/ get the argument type\n\t\t\t\tmsg_string += m.getArgTypeName(i);\n\t\t\t\tmsg_string += \":\";\n\t\t\t\t\/\/ display the argument - make sure we get the right type\n\t\t\t\tif(m.getArgType(i) == OFXOSC_TYPE_INT32){\n\t\t\t\t\tmsg_string += ofToString(m.getArgAsInt32(i));\n\t\t\t\t}\n\t\t\t\telse if(m.getArgType(i) == OFXOSC_TYPE_FLOAT){\n\t\t\t\t\tmsg_string += ofToString(m.getArgAsFloat(i));\n\t\t\t\t}\n\t\t\t\telse if(m.getArgType(i) == OFXOSC_TYPE_STRING){\n\t\t\t\t\tmsg_string += m.getArgAsString(i);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tmsg_string += \"unknown\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ add to the list of strings to display\n\t\t\tmsg_strings[current_msg_string] = msg_string;\n\t\t\ttimers[current_msg_string] = ofGetElapsedTimef() + 5.0f;\n\t\t\tcurrent_msg_string = (current_msg_string + 1) % NUM_MSG_STRINGS;\n\t\t\t\/\/ clear the next line\n\t\t\tmsg_strings[current_msg_string] = \"\";\n\t\t}\n \n\t}\n \n \/\/ FUN STUFF\n masterCounter+=direction;\n if (masterCounter > 2000) {\n direction = -1;\n }\n if (masterCounter < -2000) {\n direction = 1;\n }\n\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::draw(){\n \/\/normalize mouse (within the window space...\n float daMouseX = float(mouseX)\/float(ofGetWidth());\n float daMouseY = float(mouseY)\/ofGetHeight();\n \/\/ ofLogNotice(ofToString(daMouseX));\n \n \/\/Abstract line stuff\n for (int i = 0; i < ofGetWidth(); i++) {\n int r = daMouseX*sin(masterCounter)\/4;\n int g = i\/4;\n int b = daMouseX*daMouseY*i\/4;\n ofSetColor(r, g, b); \/\/Replace this with pixel colors from feed\n ofLine(i, ofGetHeight()\/2, i*sin(i), i*cos(i)*mainMix*\/*mouseY*30*\/masterCounter);\n }\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyPressed(int key){\n if (key == 'f' || 'F') {\n isFullScreen = !isFullScreen;\n ofSetFullscreen(isFullScreen);\n }\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseMoved(int x, int y ){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseReleased(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::windowResized(int w, int h){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::dragEvent(ofDragInfo dragInfo){ \n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fmitems.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 23:17:07 $\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 _SVX_FMITEMS_HXX\n#define _SVX_FMITEMS_HXX\n\n\n#ifndef _SFXPOOLITEM_HXX \/\/autogen\n#include <svtools\/poolitem.hxx>\n#endif\n\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n\/\/ FORWARD_DECLARE_INTERFACE(awt,XControlContainer)\nFORWARD_DECLARE_INTERFACE(uno,Any)\n\/\/ class ::com::sun::star::uno::Any;\n\n\/\/==================================================================\nclass FmInterfaceItem : public SfxPoolItem\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xInterface;\n\npublic:\n TYPEINFO();\n\n FmInterfaceItem( const sal_uInt16 nId, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxInterface )\n :SfxPoolItem( nId )\n ,xInterface( rxInterface )\n {}\n\n inline FmInterfaceItem& operator=( const FmInterfaceItem &rCpy );\n\n \/\/ \"pure virtual Methoden\" vom SfxPoolItem\n virtual int operator==( const SfxPoolItem& ) const;\n\n virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;\n virtual SfxPoolItem* Create(SvStream &, sal_uInt16) const;\n virtual SvStream& Store(SvStream &, sal_uInt16 nItemVersion ) const;\n\n const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > GetInterface() const { return xInterface; }\n};\n\ninline FmInterfaceItem& FmInterfaceItem::operator=( const FmInterfaceItem &rCpy )\n{\n xInterface = rCpy.xInterface;\n\n return *this;\n}\n\n\n\n#endif \/\/ _SVX_FMITEMS_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.1252); FILE MERGED 2008\/04\/01 15:51:09 thb 1.5.1252.2: #i85898# Stripping all external header guards 2008\/03\/31 14:22:19 rt 1.5.1252.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: fmitems.hxx,v $\n * $Revision: 1.6 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_FMITEMS_HXX\n#define _SVX_FMITEMS_HXX\n\n\n#include <svtools\/poolitem.hxx>\n#include <comphelper\/uno3.hxx>\n\/\/ FORWARD_DECLARE_INTERFACE(awt,XControlContainer)\nFORWARD_DECLARE_INTERFACE(uno,Any)\n\/\/ class ::com::sun::star::uno::Any;\n\n\/\/==================================================================\nclass FmInterfaceItem : public SfxPoolItem\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xInterface;\n\npublic:\n TYPEINFO();\n\n FmInterfaceItem( const sal_uInt16 nId, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxInterface )\n :SfxPoolItem( nId )\n ,xInterface( rxInterface )\n {}\n\n inline FmInterfaceItem& operator=( const FmInterfaceItem &rCpy );\n\n \/\/ \"pure virtual Methoden\" vom SfxPoolItem\n virtual int operator==( const SfxPoolItem& ) const;\n\n virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;\n virtual SfxPoolItem* Create(SvStream &, sal_uInt16) const;\n virtual SvStream& Store(SvStream &, sal_uInt16 nItemVersion ) const;\n\n const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > GetInterface() const { return xInterface; }\n};\n\ninline FmInterfaceItem& FmInterfaceItem::operator=( const FmInterfaceItem &rCpy )\n{\n xInterface = rCpy.xInterface;\n\n return *this;\n}\n\n\n\n#endif \/\/ _SVX_FMITEMS_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: break.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: mba $ $Date: 2002-07-01 08:57:11 $\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#ifndef _BREAK_HXX\n#define _BREAK_HXX\n\n#ifndef _SVX_STDDLG_HXX \/\/autogen\n#include <svx\/stddlg.hxx>\n#endif\n\n#ifndef _BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\nclass SwWrtShell;\n\nclass SwBreakDlg: public SvxStandardDialog\n{\n SwWrtShell &rSh;\n RadioButton aLineBtn;\n RadioButton aColumnBtn;\n RadioButton aPageBtn;\n FixedText aPageCollText;\n ListBox aPageCollBox;\n CheckBox aPageNumBox;\n NumericField aPageNumEdit;\n FixedLine aBreakFL;\n\n OKButton aOkBtn;\n CancelButton aCancelBtn;\n HelpButton aHelpBtn;\n\n String aTemplate;\n USHORT nKind;\n USHORT nPgNum;\n\n BOOL bHtmlMode;\n\n DECL_LINK( ClickHdl, void * );\n DECL_LINK( PageNumHdl, CheckBox * );\n DECL_LINK( PageNumModifyHdl, Edit * );\n DECL_LINK( OkHdl, Button * );\n\n void CheckEnable();\n\nprotected:\n virtual void Apply();\n\npublic:\n SwBreakDlg( Window *pParent, SwWrtShell &rSh );\n ~SwBreakDlg();\n\n String GetTemplateName() { return aTemplate; }\n USHORT GetKind() { return nKind; }\n USHORT GetPageNumber() { return nPgNum; }\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.1424); FILE MERGED 2005\/09\/05 13:44:58 rt 1.3.1424.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: break.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 09:01:48 $\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 _BREAK_HXX\n#define _BREAK_HXX\n\n#ifndef _SVX_STDDLG_HXX \/\/autogen\n#include <svx\/stddlg.hxx>\n#endif\n\n#ifndef _BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\nclass SwWrtShell;\n\nclass SwBreakDlg: public SvxStandardDialog\n{\n SwWrtShell &rSh;\n RadioButton aLineBtn;\n RadioButton aColumnBtn;\n RadioButton aPageBtn;\n FixedText aPageCollText;\n ListBox aPageCollBox;\n CheckBox aPageNumBox;\n NumericField aPageNumEdit;\n FixedLine aBreakFL;\n\n OKButton aOkBtn;\n CancelButton aCancelBtn;\n HelpButton aHelpBtn;\n\n String aTemplate;\n USHORT nKind;\n USHORT nPgNum;\n\n BOOL bHtmlMode;\n\n DECL_LINK( ClickHdl, void * );\n DECL_LINK( PageNumHdl, CheckBox * );\n DECL_LINK( PageNumModifyHdl, Edit * );\n DECL_LINK( OkHdl, Button * );\n\n void CheckEnable();\n\nprotected:\n virtual void Apply();\n\npublic:\n SwBreakDlg( Window *pParent, SwWrtShell &rSh );\n ~SwBreakDlg();\n\n String GetTemplateName() { return aTemplate; }\n USHORT GetKind() { return nKind; }\n USHORT GetPageNumber() { return nPgNum; }\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ $Id$\n\/\/ \n\n#include \"AVGImage.h\"\n#include \"AVGDFBDisplayEngine.h\"\n#include \"AVGPlayer.h\"\n\n#include <paintlib\/plbitmap.h>\n#include <paintlib\/planybmp.h>\n#include <paintlib\/plpngenc.h>\n#include <paintlib\/planydec.h>\n#include <paintlib\/Filter\/plfilterresizebilinear.h>\n#include <paintlib\/Filter\/plfilterfliprgb.h>\n#include <paintlib\/Filter\/plfilterfill.h>\n\n#include <nsMemory.h>\n#include <xpcom\/nsComponentManagerUtils.h>\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nNS_IMPL_ISUPPORTS1_CI(AVGImage, IAVGNode);\n\n\nAVGImage * AVGImage::create()\n{\n return createNode<AVGImage>(\"@c-base.org\/avgimage;1\");\n} \n\nAVGImage::AVGImage ()\n : m_pBmp(0)\n{\n NS_INIT_ISUPPORTS();\n}\n\nAVGImage::~AVGImage ()\n{\n if (m_pBmp) {\n delete m_pBmp;\n }\n}\n\nNS_IMETHODIMP \nAVGImage::GetType(PRInt32 *_retval)\n{\n *_retval = NT_IMAGE;\n return NS_OK;\n}\n\nvoid AVGImage::init (const std::string& id, int x, int y, int z, \n int width, int height, double opacity, const std::string& filename, \n AVGDFBDisplayEngine * pEngine, AVGContainer * pParent, AVGPlayer * pPlayer)\n{\n AVGNode::init(id, pEngine, pParent, pPlayer);\n\n m_Filename = filename;\n AVG_TRACE(AVGPlayer::DEBUG_MEMORY, \"Loading \" << m_Filename << endl);\n m_pBmp = getEngine()->createSurface();\n\n PLAnyPicDecoder decoder;\n decoder.MakeBmpFromFile(m_Filename.c_str(), m_pBmp);\n m_pBmp->ApplyFilter(PLFilterFlipRGB());\n \n initVisible(x, y, z, width, height, opacity);\n\n PLPoint size = PLPoint(getRelViewport().Width(), getRelViewport().Height());\n if (m_pBmp->GetWidth() != size.x || m_pBmp->GetHeight() != size.y) {\n m_pBmp->ApplyFilter (PLFilterResizeBilinear(size.x, size.y));\n }\n}\n\nvoid AVGImage::render (const PLRect& Rect)\n{\n\/\/ cerr << \"render \" << getID() << endl;\n \n PLRect SrcRect(0, 0, getRelViewport().Width(), getRelViewport().Height());\n if (getRelViewport().tl.x < 0) {\n SrcRect.tl.x = -getRelViewport().tl.x;\n }\n if (getRelViewport().tl.x < 0) {\n SrcRect.tl.y = -getRelViewport().tl.y;\n }\n getEngine()->render(m_pBmp, &SrcRect, getAbsViewport().tl, getEffectiveOpacity());\n}\n\nbool AVGImage::obscures (const PLRect& Rect, int z) \n{\n return (getEffectiveOpacity() > 0.999 && !m_pBmp->HasAlpha() &&\n getZ() > z && getAbsViewport().Contains(Rect));\n}\n\nstring AVGImage::getTypeStr ()\n{\n return \"AVGImage\";\n}\n\nPLPoint AVGImage::getPreferredMediaSize()\n{\n return m_pBmp->GetSize();\n}\n\n<commit_msg>Fixed neg. coordinate bug.<commit_after>\/\/\n\/\/ $Id$\n\/\/ \n\n#include \"AVGImage.h\"\n#include \"AVGDFBDisplayEngine.h\"\n#include \"AVGPlayer.h\"\n\n#include <paintlib\/plbitmap.h>\n#include <paintlib\/planybmp.h>\n#include <paintlib\/plpngenc.h>\n#include <paintlib\/planydec.h>\n#include <paintlib\/Filter\/plfilterresizebilinear.h>\n#include <paintlib\/Filter\/plfilterfliprgb.h>\n#include <paintlib\/Filter\/plfilterfill.h>\n\n#include <nsMemory.h>\n#include <xpcom\/nsComponentManagerUtils.h>\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nNS_IMPL_ISUPPORTS1_CI(AVGImage, IAVGNode);\n\n\nAVGImage * AVGImage::create()\n{\n return createNode<AVGImage>(\"@c-base.org\/avgimage;1\");\n} \n\nAVGImage::AVGImage ()\n : m_pBmp(0)\n{\n NS_INIT_ISUPPORTS();\n}\n\nAVGImage::~AVGImage ()\n{\n if (m_pBmp) {\n delete m_pBmp;\n }\n}\n\nNS_IMETHODIMP \nAVGImage::GetType(PRInt32 *_retval)\n{\n *_retval = NT_IMAGE;\n return NS_OK;\n}\n\nvoid AVGImage::init (const std::string& id, int x, int y, int z, \n int width, int height, double opacity, const std::string& filename, \n AVGDFBDisplayEngine * pEngine, AVGContainer * pParent, AVGPlayer * pPlayer)\n{\n AVGNode::init(id, pEngine, pParent, pPlayer);\n\n m_Filename = filename;\n AVG_TRACE(AVGPlayer::DEBUG_MEMORY, \"Loading \" << m_Filename << endl);\n m_pBmp = getEngine()->createSurface();\n\n PLAnyPicDecoder decoder;\n decoder.MakeBmpFromFile(m_Filename.c_str(), m_pBmp);\n m_pBmp->ApplyFilter(PLFilterFlipRGB());\n \n initVisible(x, y, z, width, height, opacity);\n\n PLPoint size = PLPoint(getRelViewport().Width(), getRelViewport().Height());\n if (m_pBmp->GetWidth() != size.x || m_pBmp->GetHeight() != size.y) {\n m_pBmp->ApplyFilter (PLFilterResizeBilinear(size.x, size.y));\n }\n}\n\nvoid AVGImage::render (const PLRect& Rect)\n{\n\/\/ cerr << \"render \" << getID() << endl;\n \n PLRect SrcRect(0, 0, getRelViewport().Width(), getRelViewport().Height());\n if (getRelViewport().tl.x < 0) {\n SrcRect.tl.x = -getRelViewport().tl.x;\n }\n if (getRelViewport().tl.y < 0) {\n SrcRect.tl.y = -getRelViewport().tl.y;\n }\n getEngine()->render(m_pBmp, &SrcRect, getAbsViewport().tl, getEffectiveOpacity());\n}\n\nbool AVGImage::obscures (const PLRect& Rect, int z) \n{\n return (getEffectiveOpacity() > 0.999 && !m_pBmp->HasAlpha() &&\n getZ() > z && getAbsViewport().Contains(Rect));\n}\n\nstring AVGImage::getTypeStr ()\n{\n return \"AVGImage\";\n}\n\nPLPoint AVGImage::getPreferredMediaSize()\n{\n return m_pBmp->GetSize();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtMultimedia module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/www.qtsoftware.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"player.h\"\n\n#include \"playercontrols.h\"\n#include \"playlistmodel.h\"\n\n#include <qabstractmediaservice.h>\n#include <qmediaplaylist.h>\n#include <qmediametadata.h>\n#include <qmediawidgetendpoint.h>\n\n#include <QtGui>\n\n#define USE_VIDEOWIDGET\n\nPlayer::Player(QWidget *parent)\n : QWidget(parent)\n , videoWidget(0)\n , coverLabel(0)\n , slider(0)\n , colorDialog(0)\n{\n player = new QMediaPlayer;\n metaData = new QMediaMetadata(player);\n\n connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));\n connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));\n connect(player, SIGNAL(playlistPositionChanged(int)), SLOT(playlistPositionChanged(int)));\n connect(metaData, SIGNAL(metadataChanged()), SLOT(metadataChanged()));\n connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),\n this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));\n connect(player, SIGNAL(bufferingChanged(bool)), this, SLOT(bufferingChanged(bool)));\n connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));\n\n#ifdef USE_VIDEOWIDGET\n videoWidget = new QVideoWidget(player);\n\n connect(videoWidget, SIGNAL(displayModeChanged(QVideoWidget::DisplayMode)),\n this, SLOT(displayModeChanged(QVideoWidget::DisplayMode)));\n#else\n QWidget *videoWidget = player->service()->createEndpoint<QMediaWidgetEndpoint *>();\n\n if (videoWidget) {\n qDebug() << \"service supports video widgets, nice\";\n player->service()->setVideoOutput(videoWidget);\n } else {\n coverLabel = new QLabel;\n }\n#endif\n playlistModel = new PlaylistModel(this);\n playlistModel->setPlaylist(player->mediaPlaylist());\n\n playlistView = new QTableView;\n playlistView->setModel(playlistModel);\n playlistView->setCurrentIndex(playlistModel->index(player->playlistPosition(), 0));\n\n connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));\n\n slider = new QSlider(Qt::Horizontal);\n slider->setRange(0, player->duration() \/ 1000);\n\n connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));\n\n QPushButton *openButton = new QPushButton(tr(\"Open\"));\n\n connect(openButton, SIGNAL(clicked()), this, SLOT(open()));\n\n PlayerControls *controls = new PlayerControls;\n controls->setState(player->state());\n controls->setVolume(player->volume());\n controls->setMuted(controls->isMuted());\n\n connect(controls, SIGNAL(play()), player, SLOT(play()));\n connect(controls, SIGNAL(pause()), player, SLOT(pause()));\n connect(controls, SIGNAL(stop()), player, SLOT(stop()));\n connect(controls, SIGNAL(next()), player, SLOT(advance()));\n connect(controls, SIGNAL(previous()), player, SLOT(back()));\n connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));\n connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));\n\n connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),\n controls, SLOT(setState(QMediaPlayer::State)));\n connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));\n connect(player, SIGNAL(mutingChanged(bool)), controls, SLOT(setMuted(bool)));\n\n QPushButton *fullscreenButton = new QPushButton(tr(\"Fullscreen\"));\n fullscreenButton->setCheckable(true);\n\n connect(fullscreenButton, SIGNAL(clicked(bool)), this, SLOT(setFullscreen(bool)));\n connect(this, SIGNAL(fullscreenChanged(bool)), fullscreenButton, SLOT(setChecked(bool)));\n\n fullscreenButton->setEnabled(videoWidget != 0);\n\n QPushButton *colorButton = new QPushButton(tr(\"Color Options...\"));\n if (videoWidget)\n connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));\n else\n colorButton->setEnabled(false);\n\n QBoxLayout *controlLayout = new QHBoxLayout;\n controlLayout->setMargin(0);\n controlLayout->addWidget(openButton);\n controlLayout->addStretch(1);\n controlLayout->addWidget(controls);\n controlLayout->addStretch(1);\n controlLayout->addWidget(fullscreenButton);\n controlLayout->addWidget(colorButton);\n\n QBoxLayout *layout = new QVBoxLayout;\n if (videoWidget) {\n QSplitter *splitter = new QSplitter(Qt::Vertical);\n\n splitter->addWidget(videoWidget);\n splitter->addWidget(playlistView);\n\n \/*\n connect(player, SIGNAL(videoAvailabilityChanged(bool)), videoWidget, SLOT(setVisible(bool)));\n videoWidget->setMinimumSize(64,64);\n videoWidget->setVisible(false);*\/\n\n layout->addWidget(splitter);\n } else {\n layout->addWidget(coverLabel, 0, Qt::AlignCenter);\n layout->addWidget(playlistView);\n }\n layout->addWidget(slider);\n layout->addLayout(controlLayout);\n\n setLayout(layout);\n\n metadataChanged();\n}\n\nPlayer::~Player()\n{\n delete player;\n}\n\nvoid Player::open()\n{\n QStringList fileNames = QFileDialog::getOpenFileNames();\n\n foreach (QString const &fileName, fileNames) {\n#ifndef Q_OS_WIN\n player->mediaPlaylist()->appendItem(\n QMediaResource(QUrl(QLatin1String(\"file:\/\/\") + fileName)));\n#else\n player->mediaPlaylist()->appendItem(\n QMediaResource(QUrl(QLatin1String(\"file:\/\/\/\") + fileName)));\n#endif\n }\n}\n\nvoid Player::durationChanged(qint64 duration)\n{\n slider->setMaximum(duration \/ 1000);\n}\n\nvoid Player::positionChanged(qint64 progress)\n{\n slider->setValue(progress \/ 1000);\n}\n\nvoid Player::metadataChanged()\n{\n qDebug() << \"update metadata\" << metaData->metadata(QLatin1String(\"title\")).toString();\n if (metaData->metadataAvailable()) {\n setTrackInfo(QString(\"%1 - %2\")\n .arg(metaData->metadata(QLatin1String(\"Artist\")).toString())\n .arg(metaData->metadata(QLatin1String(\"Title\")).toString()));\n\n if (coverLabel) {\n QMediaResource cover;\n foreach (const QMediaResource &resource, metaData->resources()) {\n if (resource.role() == QMediaResource::CoverArtRole\n && (cover.isNull()\n || resource.resolution().height() > cover.resolution().height())) {\n cover = resource;\n }\n }\n coverLabel->setPixmap(!cover.isNull()\n ? QPixmap(cover.uri().toString())\n : QPixmap());\n }\n }\n}\n\nvoid Player::jump(const QModelIndex &index)\n{\n if (index.isValid()) {\n player->setPlaylistPosition(index.row());\n }\n}\n\nvoid Player::playlistPositionChanged(int currentItem)\n{\n playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));\n}\n\nvoid Player::seek(int seconds)\n{\n player->setPosition(seconds * 1000);\n}\n\nvoid Player::statusChanged(QMediaPlayer::MediaStatus status)\n{\n switch (status) {\n case QMediaPlayer::UnknownMediaStatus:\n case QMediaPlayer::NoMedia:\n case QMediaPlayer::LoadedMedia:\n case QMediaPlayer::PrimedMedia:\n unsetCursor();\n setStatusInfo(QString());\n break;\n case QMediaPlayer::LoadingMedia:\n setCursor(QCursor(Qt::BusyCursor));\n setStatusInfo(tr(\"Loading...\"));\n break;\n case QMediaPlayer::StalledMedia:\n setCursor(QCursor(Qt::BusyCursor));\n break;\n case QMediaPlayer::EndOfMedia:\n unsetCursor();\n setStatusInfo(QString());\n QApplication::alert(this);\n break;\n case QMediaPlayer::InvalidMedia:\n unsetCursor();\n setStatusInfo(player->errorString());\n break;\n }\n}\n\nvoid Player::bufferingChanged(bool buffering)\n{\n if (buffering)\n statusChanged(player->mediaStatus());\n}\n\nvoid Player::bufferingProgress(int progress)\n{\n setStatusInfo(tr(\"Buffering %4%%\").arg(progress));\n}\n\nvoid Player::setTrackInfo(const QString &info)\n{\n trackInfo = info;\n\n if (!statusInfo.isEmpty())\n setWindowTitle(QString(\"%1 | %2\").arg(trackInfo).arg(statusInfo));\n else\n setWindowTitle(trackInfo);\n\n}\n\nvoid Player::setStatusInfo(const QString &info)\n{\n statusInfo = info;\n\n if (!statusInfo.isEmpty())\n setWindowTitle(QString(\"%1 | %2\").arg(trackInfo).arg(statusInfo));\n else\n setWindowTitle(trackInfo);\n}\n\nvoid Player::setFullscreen(bool fullscreen)\n{\n videoWidget->setDisplayMode(\n fullscreen ? QVideoWidget::FullscreenDisplay : QVideoWidget::WindowedDisplay);\n}\n\nvoid Player::displayModeChanged(QVideoWidget::DisplayMode mode)\n{\n emit fullscreenChanged(mode == QVideoWidget::FullscreenDisplay);\n}\n\nvoid Player::showColorDialog()\n{\n if (!colorDialog) {\n QSlider *brightnessSlider = new QSlider(Qt::Horizontal);\n brightnessSlider->setRange(-100, 100);\n brightnessSlider->setValue(videoWidget->brightness());\n connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));\n connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));\n\n QSlider *contrastSlider = new QSlider(Qt::Horizontal);\n contrastSlider->setRange(-100, 100);\n contrastSlider->setValue(videoWidget->contrast());\n connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));\n connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));\n\n QSlider *hueSlider = new QSlider(Qt::Horizontal);\n hueSlider->setRange(-100, 100);\n hueSlider->setValue(videoWidget->hue());\n connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));\n connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));\n\n QSlider *saturationSlider = new QSlider(Qt::Horizontal);\n saturationSlider->setRange(-100, 100);\n saturationSlider->setValue(videoWidget->saturation());\n connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));\n connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));\n\n QFormLayout *layout = new QFormLayout;\n layout->addRow(tr(\"Brightness\"), brightnessSlider);\n layout->addRow(tr(\"Contrast\"), contrastSlider);\n layout->addRow(tr(\"Hue\"), hueSlider);\n layout->addRow(tr(\"Saturation\"), saturationSlider);\n\n colorDialog = new QDialog(this);\n colorDialog->setWindowTitle(tr(\"Color Options\"));\n colorDialog->setLayout(layout);\n }\n colorDialog->show();\n}\n<commit_msg>Compile with QT_NO_CURSOR defined.<commit_after>\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtMultimedia module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/www.qtsoftware.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"player.h\"\n\n#include \"playercontrols.h\"\n#include \"playlistmodel.h\"\n\n#include <qabstractmediaservice.h>\n#include <qmediaplaylist.h>\n#include <qmediametadata.h>\n#include <qmediawidgetendpoint.h>\n\n#include <QtGui>\n\n#define USE_VIDEOWIDGET\n\nPlayer::Player(QWidget *parent)\n : QWidget(parent)\n , videoWidget(0)\n , coverLabel(0)\n , slider(0)\n , colorDialog(0)\n{\n player = new QMediaPlayer;\n metaData = new QMediaMetadata(player);\n\n connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));\n connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));\n connect(player, SIGNAL(playlistPositionChanged(int)), SLOT(playlistPositionChanged(int)));\n connect(metaData, SIGNAL(metadataChanged()), SLOT(metadataChanged()));\n connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),\n this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));\n connect(player, SIGNAL(bufferingChanged(bool)), this, SLOT(bufferingChanged(bool)));\n connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));\n\n#ifdef USE_VIDEOWIDGET\n videoWidget = new QVideoWidget(player);\n\n connect(videoWidget, SIGNAL(displayModeChanged(QVideoWidget::DisplayMode)),\n this, SLOT(displayModeChanged(QVideoWidget::DisplayMode)));\n#else\n QWidget *videoWidget = player->service()->createEndpoint<QMediaWidgetEndpoint *>();\n\n if (videoWidget) {\n qDebug() << \"service supports video widgets, nice\";\n player->service()->setVideoOutput(videoWidget);\n } else {\n coverLabel = new QLabel;\n }\n#endif\n playlistModel = new PlaylistModel(this);\n playlistModel->setPlaylist(player->mediaPlaylist());\n\n playlistView = new QTableView;\n playlistView->setModel(playlistModel);\n playlistView->setCurrentIndex(playlistModel->index(player->playlistPosition(), 0));\n\n connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));\n\n slider = new QSlider(Qt::Horizontal);\n slider->setRange(0, player->duration() \/ 1000);\n\n connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));\n\n QPushButton *openButton = new QPushButton(tr(\"Open\"));\n\n connect(openButton, SIGNAL(clicked()), this, SLOT(open()));\n\n PlayerControls *controls = new PlayerControls;\n controls->setState(player->state());\n controls->setVolume(player->volume());\n controls->setMuted(controls->isMuted());\n\n connect(controls, SIGNAL(play()), player, SLOT(play()));\n connect(controls, SIGNAL(pause()), player, SLOT(pause()));\n connect(controls, SIGNAL(stop()), player, SLOT(stop()));\n connect(controls, SIGNAL(next()), player, SLOT(advance()));\n connect(controls, SIGNAL(previous()), player, SLOT(back()));\n connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));\n connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));\n\n connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),\n controls, SLOT(setState(QMediaPlayer::State)));\n connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));\n connect(player, SIGNAL(mutingChanged(bool)), controls, SLOT(setMuted(bool)));\n\n QPushButton *fullscreenButton = new QPushButton(tr(\"Fullscreen\"));\n fullscreenButton->setCheckable(true);\n\n connect(fullscreenButton, SIGNAL(clicked(bool)), this, SLOT(setFullscreen(bool)));\n connect(this, SIGNAL(fullscreenChanged(bool)), fullscreenButton, SLOT(setChecked(bool)));\n\n fullscreenButton->setEnabled(videoWidget != 0);\n\n QPushButton *colorButton = new QPushButton(tr(\"Color Options...\"));\n if (videoWidget)\n connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));\n else\n colorButton->setEnabled(false);\n\n QBoxLayout *controlLayout = new QHBoxLayout;\n controlLayout->setMargin(0);\n controlLayout->addWidget(openButton);\n controlLayout->addStretch(1);\n controlLayout->addWidget(controls);\n controlLayout->addStretch(1);\n controlLayout->addWidget(fullscreenButton);\n controlLayout->addWidget(colorButton);\n\n QBoxLayout *layout = new QVBoxLayout;\n if (videoWidget) {\n QSplitter *splitter = new QSplitter(Qt::Vertical);\n\n splitter->addWidget(videoWidget);\n splitter->addWidget(playlistView);\n\n \/*\n connect(player, SIGNAL(videoAvailabilityChanged(bool)), videoWidget, SLOT(setVisible(bool)));\n videoWidget->setMinimumSize(64,64);\n videoWidget->setVisible(false);*\/\n\n layout->addWidget(splitter);\n } else {\n layout->addWidget(coverLabel, 0, Qt::AlignCenter);\n layout->addWidget(playlistView);\n }\n layout->addWidget(slider);\n layout->addLayout(controlLayout);\n\n setLayout(layout);\n\n metadataChanged();\n}\n\nPlayer::~Player()\n{\n delete player;\n}\n\nvoid Player::open()\n{\n QStringList fileNames = QFileDialog::getOpenFileNames();\n\n foreach (QString const &fileName, fileNames) {\n#ifndef Q_OS_WIN\n player->mediaPlaylist()->appendItem(\n QMediaResource(QUrl(QLatin1String(\"file:\/\/\") + fileName)));\n#else\n player->mediaPlaylist()->appendItem(\n QMediaResource(QUrl(QLatin1String(\"file:\/\/\/\") + fileName)));\n#endif\n }\n}\n\nvoid Player::durationChanged(qint64 duration)\n{\n slider->setMaximum(duration \/ 1000);\n}\n\nvoid Player::positionChanged(qint64 progress)\n{\n slider->setValue(progress \/ 1000);\n}\n\nvoid Player::metadataChanged()\n{\n qDebug() << \"update metadata\" << metaData->metadata(QLatin1String(\"title\")).toString();\n if (metaData->metadataAvailable()) {\n setTrackInfo(QString(\"%1 - %2\")\n .arg(metaData->metadata(QLatin1String(\"Artist\")).toString())\n .arg(metaData->metadata(QLatin1String(\"Title\")).toString()));\n\n if (coverLabel) {\n QMediaResource cover;\n foreach (const QMediaResource &resource, metaData->resources()) {\n if (resource.role() == QMediaResource::CoverArtRole\n && (cover.isNull()\n || resource.resolution().height() > cover.resolution().height())) {\n cover = resource;\n }\n }\n coverLabel->setPixmap(!cover.isNull()\n ? QPixmap(cover.uri().toString())\n : QPixmap());\n }\n }\n}\n\nvoid Player::jump(const QModelIndex &index)\n{\n if (index.isValid()) {\n player->setPlaylistPosition(index.row());\n }\n}\n\nvoid Player::playlistPositionChanged(int currentItem)\n{\n playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));\n}\n\nvoid Player::seek(int seconds)\n{\n player->setPosition(seconds * 1000);\n}\n\nvoid Player::statusChanged(QMediaPlayer::MediaStatus status)\n{\n switch (status) {\n case QMediaPlayer::UnknownMediaStatus:\n case QMediaPlayer::NoMedia:\n case QMediaPlayer::LoadedMedia:\n case QMediaPlayer::PrimedMedia:\n#ifndef QT_NO_CURSOR\n unsetCursor();\n#endif\n setStatusInfo(QString());\n break;\n case QMediaPlayer::LoadingMedia:\n#ifndef QT_NO_CURSOR\n setCursor(QCursor(Qt::BusyCursor));\n#endif\n setStatusInfo(tr(\"Loading...\"));\n break;\n case QMediaPlayer::StalledMedia:\n setCursor(QCursor(Qt::BusyCursor));\n break;\n case QMediaPlayer::EndOfMedia:\n#ifndef QT_NO_CURSOR\n unsetCursor();\n#endif\n setStatusInfo(QString());\n QApplication::alert(this);\n break;\n case QMediaPlayer::InvalidMedia:\n#ifndef QT_NO_CURSOR\n unsetCursor();\n#endif\n setStatusInfo(player->errorString());\n break;\n }\n}\n\nvoid Player::bufferingChanged(bool buffering)\n{\n if (buffering)\n statusChanged(player->mediaStatus());\n}\n\nvoid Player::bufferingProgress(int progress)\n{\n setStatusInfo(tr(\"Buffering %4%%\").arg(progress));\n}\n\nvoid Player::setTrackInfo(const QString &info)\n{\n trackInfo = info;\n\n if (!statusInfo.isEmpty())\n setWindowTitle(QString(\"%1 | %2\").arg(trackInfo).arg(statusInfo));\n else\n setWindowTitle(trackInfo);\n\n}\n\nvoid Player::setStatusInfo(const QString &info)\n{\n statusInfo = info;\n\n if (!statusInfo.isEmpty())\n setWindowTitle(QString(\"%1 | %2\").arg(trackInfo).arg(statusInfo));\n else\n setWindowTitle(trackInfo);\n}\n\nvoid Player::setFullscreen(bool fullscreen)\n{\n videoWidget->setDisplayMode(\n fullscreen ? QVideoWidget::FullscreenDisplay : QVideoWidget::WindowedDisplay);\n}\n\nvoid Player::displayModeChanged(QVideoWidget::DisplayMode mode)\n{\n emit fullscreenChanged(mode == QVideoWidget::FullscreenDisplay);\n}\n\nvoid Player::showColorDialog()\n{\n if (!colorDialog) {\n QSlider *brightnessSlider = new QSlider(Qt::Horizontal);\n brightnessSlider->setRange(-100, 100);\n brightnessSlider->setValue(videoWidget->brightness());\n connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));\n connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));\n\n QSlider *contrastSlider = new QSlider(Qt::Horizontal);\n contrastSlider->setRange(-100, 100);\n contrastSlider->setValue(videoWidget->contrast());\n connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));\n connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));\n\n QSlider *hueSlider = new QSlider(Qt::Horizontal);\n hueSlider->setRange(-100, 100);\n hueSlider->setValue(videoWidget->hue());\n connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));\n connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));\n\n QSlider *saturationSlider = new QSlider(Qt::Horizontal);\n saturationSlider->setRange(-100, 100);\n saturationSlider->setValue(videoWidget->saturation());\n connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));\n connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));\n\n QFormLayout *layout = new QFormLayout;\n layout->addRow(tr(\"Brightness\"), brightnessSlider);\n layout->addRow(tr(\"Contrast\"), contrastSlider);\n layout->addRow(tr(\"Hue\"), hueSlider);\n layout->addRow(tr(\"Saturation\"), saturationSlider);\n\n colorDialog = new QDialog(this);\n colorDialog->setWindowTitle(tr(\"Color Options\"));\n colorDialog->setLayout(layout);\n }\n colorDialog->show();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Module: Log4CPLUS\n\/\/ File: threads.cxx\n\/\/ Created: 6\/2001\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2001-2014 Tad E. Smith\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 <log4cplus\/config.hxx>\n\n#include <exception>\n#include <ostream>\n#include <cerrno>\n\n#ifdef LOG4CPLUS_HAVE_SYS_TYPES_H\n#include <sys\/types.h>\n#endif\n\n#ifdef LOG4CPLUS_HAVE_SYS_SYSCALL_H\n#include <sys\/syscall.h>\n#endif\n\n#ifdef LOG4CPLUS_HAVE_ERRNO_H\n#include <errno.h>\n#endif\n\n#ifdef LOG4CPLUS_HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\n#if defined(LOG4CPLUS_USE_PTHREADS)\n# include <pthread.h>\n# include <sched.h>\n# include <signal.h>\n#elif defined (LOG4CPLUS_USE_WIN32_THREADS)\n# include <process.h>\n#endif\n#include <log4cplus\/config\/windowsh-inc.h>\n#include <log4cplus\/thread\/syncprims-pub-impl.h>\n#include <log4cplus\/tstring.h>\n#include <log4cplus\/internal\/cygwin-win32.h>\n#include <log4cplus\/streams.h>\n\n#ifndef LOG4CPLUS_SINGLE_THREADED\n\n#include <log4cplus\/thread\/threads.h>\n#include <log4cplus\/thread\/impl\/threads-impl.h>\n#include <log4cplus\/thread\/impl\/tls.h>\n#include <log4cplus\/ndc.h>\n#include <log4cplus\/helpers\/loglog.h>\n#include <log4cplus\/helpers\/stringhelper.h>\n#include <log4cplus\/helpers\/timehelper.h>\n#include <log4cplus\/internal\/internal.h>\n\n#endif \/\/ LOG4CPLUS_SINGLE_THREADED\n\n\nnamespace log4cplus { namespace thread {\n\nLOG4CPLUS_EXPORT\nvoid\nblockAllSignals()\n{\n#if defined (LOG4CPLUS_USE_PTHREADS)\n \/\/ Block all signals.\n sigset_t signal_set;\n sigfillset (&signal_set);\n pthread_sigmask (SIG_BLOCK, &signal_set, 0);\n#endif\n}\n\n\nLOG4CPLUS_EXPORT\nvoid\nyield()\n{\n#if defined(LOG4CPLUS_USE_PTHREADS)\n sched_yield();\n#elif defined(_WIN32)\n if (! SwitchToThread ())\n Sleep (0);\n#endif\n}\n\n#if defined(LOG4CPLUS_SINGLE_THREADED)\nstatic log4cplus::tstring thread_name(LOG4CPLUS_TEXT(\"single\"))\n LOG4CPLUS_INIT_PRIORITY (LOG4CPLUS_INIT_PRIORITY_BASE - 1);\nstatic log4cplus::tstring thread_name2(thread_name)\n LOG4CPLUS_INIT_PRIORITY (LOG4CPLUS_INIT_PRIORITY_BASE - 1);\n#endif\n\nLOG4CPLUS_EXPORT\nlog4cplus::tstring const &\ngetCurrentThreadName()\n{\n#if ! defined (LOG4CPLUS_SINGLE_THREADED)\n log4cplus::tstring & name = log4cplus::internal::get_thread_name_str ();\n if (LOG4CPLUS_UNLIKELY (name.empty ()))\n {\n log4cplus::tostringstream tmp;\n tmp << impl::getCurrentThreadId ();\n name = tmp.str ();\n }\n#else\n log4cplus::tstring & name = thread_name;\n if (LOG4CPLUS_UNLIKELY(name.empty()))\n {\n name = LOG4CPLUS_TEXT(\"single\");\n }\n#endif\n\n return name;\n}\n\n\nnamespace\n{\n\n\nstatic\nbool\nget_current_thread_name_alt (log4cplus::tostream * s)\n{\n log4cplus::tostream & os = *s;\n\n#if defined (LOG4CPLUS_USE_PTHREADS) && defined (__linux__) \\\n && defined (LOG4CPLUS_HAVE_GETTID)\n pid_t tid = syscall (SYS_gettid);\n os << tid;\n\n#elif defined (__CYGWIN__)\n unsigned long tid = cygwin::get_current_win32_thread_id ();\n os << tid;\n\n#else\n os << getCurrentThreadName ();\n\n#endif\n\n return true;\n}\n\n\n} \/\/ namespace\n\n\nLOG4CPLUS_EXPORT\nlog4cplus::tstring const &\ngetCurrentThreadName2()\n{\n#if ! defined (LOG4CPLUS_SINGLE_THREADED)\n log4cplus::tstring & name = log4cplus::internal::get_thread_name2_str ();\n if (LOG4CPLUS_UNLIKELY (name.empty ()))\n {\n log4cplus::tostringstream tmp;\n get_current_thread_name_alt (&tmp);\n name = tmp.str ();\n }\n\n#else\n log4cplus::tstring & name = thread_name2;\n if (LOG4CPLUS_UNLIKELY(name.empty()))\n {\n name = getCurrentThreadName();\n }\n\n#endif\n\n return name;\n}\n\nLOG4CPLUS_EXPORT void setCurrentThreadName(const log4cplus::tstring & name)\n{\n#if ! defined (LOG4CPLUS_SINGLE_THREADED)\n log4cplus::internal::get_thread_name_str() = name;\n#else\n thread_name = name;\n#endif\n}\n\nLOG4CPLUS_EXPORT void setCurrentThreadName2(const log4cplus::tstring & name)\n{\n#if ! defined (LOG4CPLUS_SINGLE_THREADED)\n log4cplus::internal::get_thread_name2_str() = name;\n#else\n thread_name2 = name;\n#endif\n}\n\n\n#ifndef LOG4CPLUS_SINGLE_THREADED\n\n\/\/\n\/\/\n\/\/\n\nAbstractThread::AbstractThread ()\n{ }\n\n\nbool\nAbstractThread::isRunning() const\n{\n return (flags & fRUNNING) != 0;\n}\n\n\nvoid\nAbstractThread::start()\n{\n try\n {\n addReference ();\n flags |= fRUNNING;\n thread.reset (\n new std::thread ([this] () {\n blockAllSignals ();\n AbstractThreadPtr thread_ptr (this);\n this->removeReference ();\n helpers::LogLog * loglog = helpers::LogLog::getLogLog();\n try\n {\n this->run ();\n }\n catch (std::exception const & e)\n {\n tstring err (LOG4CPLUS_TEXT (\"threadStartFunc()\")\n LOG4CPLUS_TEXT (\"- run() terminated with an exception: \"));\n err += LOG4CPLUS_C_STR_TO_TSTRING(e.what());\n loglog->warn(err);\n }\n catch(...)\n {\n loglog->warn(LOG4CPLUS_TEXT(\"threadStartFunc()\")\n LOG4CPLUS_TEXT (\"- run() terminated with an exception.\"));\n }\n this->flags &= ~fRUNNING;\n threadCleanup ();\n }));\n }\n catch (...)\n {\n flags &= ~fRUNNING;\n removeReference ();\n throw;\n }\n}\n\n\nvoid\nAbstractThread::join () const\n{\n if (! thread\n || (flags & fJOINED) == fJOINED)\n throw std::logic_error (\"this thread is not running\");\n\n thread->join ();\n flags |= +fJOINED;\n}\n\n\nAbstractThread::~AbstractThread()\n{\n if ((flags & fJOINED) == 0)\n thread->detach ();\n}\n\n#endif \/\/ LOG4CPLUS_SINGLE_THREADED\n\n\n} } \/\/ namespace log4cplus { namespace thread {\n<commit_msg>threads.cxx: Add AbstractThreadPtr parameter to thread's lambda to remove the addReference()\/removeReference() dance.<commit_after>\/\/ Module: Log4CPLUS\n\/\/ File: threads.cxx\n\/\/ Created: 6\/2001\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2001-2014 Tad E. Smith\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 <log4cplus\/config.hxx>\n\n#include <exception>\n#include <ostream>\n#include <cerrno>\n\n#ifdef LOG4CPLUS_HAVE_SYS_TYPES_H\n#include <sys\/types.h>\n#endif\n\n#ifdef LOG4CPLUS_HAVE_SYS_SYSCALL_H\n#include <sys\/syscall.h>\n#endif\n\n#ifdef LOG4CPLUS_HAVE_ERRNO_H\n#include <errno.h>\n#endif\n\n#ifdef LOG4CPLUS_HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\n#if defined(LOG4CPLUS_USE_PTHREADS)\n# include <pthread.h>\n# include <sched.h>\n# include <signal.h>\n#elif defined (LOG4CPLUS_USE_WIN32_THREADS)\n# include <process.h>\n#endif\n#include <log4cplus\/config\/windowsh-inc.h>\n#include <log4cplus\/thread\/syncprims-pub-impl.h>\n#include <log4cplus\/tstring.h>\n#include <log4cplus\/internal\/cygwin-win32.h>\n#include <log4cplus\/streams.h>\n\n#ifndef LOG4CPLUS_SINGLE_THREADED\n\n#include <log4cplus\/thread\/threads.h>\n#include <log4cplus\/thread\/impl\/threads-impl.h>\n#include <log4cplus\/thread\/impl\/tls.h>\n#include <log4cplus\/ndc.h>\n#include <log4cplus\/helpers\/loglog.h>\n#include <log4cplus\/helpers\/stringhelper.h>\n#include <log4cplus\/helpers\/timehelper.h>\n#include <log4cplus\/internal\/internal.h>\n\n#endif \/\/ LOG4CPLUS_SINGLE_THREADED\n\n\nnamespace log4cplus { namespace thread {\n\nLOG4CPLUS_EXPORT\nvoid\nblockAllSignals()\n{\n#if defined (LOG4CPLUS_USE_PTHREADS)\n \/\/ Block all signals.\n sigset_t signal_set;\n sigfillset (&signal_set);\n pthread_sigmask (SIG_BLOCK, &signal_set, 0);\n#endif\n}\n\n\nLOG4CPLUS_EXPORT\nvoid\nyield()\n{\n#if defined(LOG4CPLUS_USE_PTHREADS)\n sched_yield();\n#elif defined(_WIN32)\n if (! SwitchToThread ())\n Sleep (0);\n#endif\n}\n\n#if defined(LOG4CPLUS_SINGLE_THREADED)\nstatic log4cplus::tstring thread_name(LOG4CPLUS_TEXT(\"single\"))\n LOG4CPLUS_INIT_PRIORITY (LOG4CPLUS_INIT_PRIORITY_BASE - 1);\nstatic log4cplus::tstring thread_name2(thread_name)\n LOG4CPLUS_INIT_PRIORITY (LOG4CPLUS_INIT_PRIORITY_BASE - 1);\n#endif\n\nLOG4CPLUS_EXPORT\nlog4cplus::tstring const &\ngetCurrentThreadName()\n{\n#if ! defined (LOG4CPLUS_SINGLE_THREADED)\n log4cplus::tstring & name = log4cplus::internal::get_thread_name_str ();\n if (LOG4CPLUS_UNLIKELY (name.empty ()))\n {\n log4cplus::tostringstream tmp;\n tmp << impl::getCurrentThreadId ();\n name = tmp.str ();\n }\n#else\n log4cplus::tstring & name = thread_name;\n if (LOG4CPLUS_UNLIKELY(name.empty()))\n {\n name = LOG4CPLUS_TEXT(\"single\");\n }\n#endif\n\n return name;\n}\n\n\nnamespace\n{\n\n\nstatic\nbool\nget_current_thread_name_alt (log4cplus::tostream * s)\n{\n log4cplus::tostream & os = *s;\n\n#if defined (LOG4CPLUS_USE_PTHREADS) && defined (__linux__) \\\n && defined (LOG4CPLUS_HAVE_GETTID)\n pid_t tid = syscall (SYS_gettid);\n os << tid;\n\n#elif defined (__CYGWIN__)\n unsigned long tid = cygwin::get_current_win32_thread_id ();\n os << tid;\n\n#else\n os << getCurrentThreadName ();\n\n#endif\n\n return true;\n}\n\n\n} \/\/ namespace\n\n\nLOG4CPLUS_EXPORT\nlog4cplus::tstring const &\ngetCurrentThreadName2()\n{\n#if ! defined (LOG4CPLUS_SINGLE_THREADED)\n log4cplus::tstring & name = log4cplus::internal::get_thread_name2_str ();\n if (LOG4CPLUS_UNLIKELY (name.empty ()))\n {\n log4cplus::tostringstream tmp;\n get_current_thread_name_alt (&tmp);\n name = tmp.str ();\n }\n\n#else\n log4cplus::tstring & name = thread_name2;\n if (LOG4CPLUS_UNLIKELY(name.empty()))\n {\n name = getCurrentThreadName();\n }\n\n#endif\n\n return name;\n}\n\nLOG4CPLUS_EXPORT void setCurrentThreadName(const log4cplus::tstring & name)\n{\n#if ! defined (LOG4CPLUS_SINGLE_THREADED)\n log4cplus::internal::get_thread_name_str() = name;\n#else\n thread_name = name;\n#endif\n}\n\nLOG4CPLUS_EXPORT void setCurrentThreadName2(const log4cplus::tstring & name)\n{\n#if ! defined (LOG4CPLUS_SINGLE_THREADED)\n log4cplus::internal::get_thread_name2_str() = name;\n#else\n thread_name2 = name;\n#endif\n}\n\n\n#ifndef LOG4CPLUS_SINGLE_THREADED\n\n\/\/\n\/\/\n\/\/\n\nAbstractThread::AbstractThread ()\n{ }\n\n\nbool\nAbstractThread::isRunning() const\n{\n return (flags & fRUNNING) != 0;\n}\n\n\nvoid\nAbstractThread::start()\n{\n try\n {\n flags |= fRUNNING;\n thread.reset (\n new std::thread ([this] (AbstractThreadPtr const & thread_ptr) {\n (void) thread_ptr;\n blockAllSignals ();\n helpers::LogLog * loglog = helpers::LogLog::getLogLog();\n try\n {\n this->run ();\n }\n catch (std::exception const & e)\n {\n tstring err (LOG4CPLUS_TEXT (\"threadStartFunc()\")\n LOG4CPLUS_TEXT (\"- run() terminated with an exception: \"));\n err += LOG4CPLUS_C_STR_TO_TSTRING(e.what());\n loglog->warn(err);\n }\n catch(...)\n {\n loglog->warn(LOG4CPLUS_TEXT(\"threadStartFunc()\")\n LOG4CPLUS_TEXT (\"- run() terminated with an exception.\"));\n }\n this->flags &= ~fRUNNING;\n threadCleanup ();\n }, AbstractThreadPtr (this)));\n }\n catch (...)\n {\n flags &= ~fRUNNING;\n throw;\n }\n}\n\n\nvoid\nAbstractThread::join () const\n{\n if (! thread\n || (flags & fJOINED) == fJOINED)\n throw std::logic_error (\"this thread is not running\");\n\n thread->join ();\n flags |= +fJOINED;\n}\n\n\nAbstractThread::~AbstractThread()\n{\n if ((flags & fJOINED) == 0)\n thread->detach ();\n}\n\n#endif \/\/ LOG4CPLUS_SINGLE_THREADED\n\n\n} } \/\/ namespace log4cplus { namespace thread {\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, Facebook, Inc. All rights reserved.\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#include <cstdio>\n#include <string>\n\n#include \"rocksdb\/db.h\"\n#include \"rocksdb\/slice.h\"\n#include \"rocksdb\/options.h\"\n\nusing namespace rocksdb;\n\nstd::string kDBPath = \"\/tmp\/rocksdb_simple_example\";\n\nint main() {\n DB* db;\n Options options;\n \/\/ Optimize RocksDB. This is the easiest way to get RocksDB to perform well\n options.IncreaseParallelism();\n options.OptimizeLevelStyleCompaction();\n \/\/ create the DB if it's not already present\n options.create_if_missing = true;\n\n \/\/ open DB\n Status s = DB::Open(options, kDBPath, &db);\n assert(s.ok());\n\n \/\/ Put key-value\n s = db->Put(WriteOptions(), \"key\", \"value\");\n assert(s.ok());\n std::string value;\n \/\/ get value\n s = db->Get(ReadOptions(), \"key\", &value);\n assert(s.ok());\n assert(value == \"value\");\n\n delete db;\n\n return 0;\n}\n<commit_msg>Added WriteBatch block to simple_example.cc<commit_after>\/\/ Copyright (c) 2013, Facebook, Inc. All rights reserved.\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#include <cstdio>\n#include <string>\n\n#include \"rocksdb\/db.h\"\n#include \"rocksdb\/slice.h\"\n#include \"rocksdb\/options.h\"\n\nusing namespace rocksdb;\n\nstd::string kDBPath = \"\/tmp\/rocksdb_simple_example\";\n\nint main() {\n DB* db;\n Options options;\n \/\/ Optimize RocksDB. This is the easiest way to get RocksDB to perform well\n options.IncreaseParallelism();\n options.OptimizeLevelStyleCompaction();\n \/\/ create the DB if it's not already present\n options.create_if_missing = true;\n\n \/\/ open DB\n Status s = DB::Open(options, kDBPath, &db);\n assert(s.ok());\n\n \/\/ Put key-value\n s = db->Put(WriteOptions(), \"key1\", \"value\");\n assert(s.ok());\n std::string value;\n \/\/ get value\n s = db->Get(ReadOptions(), \"key1\", &value);\n assert(s.ok());\n assert(value == \"value\");\n\n \/\/ atomically apply a set of updates\n {\n WriteBatch batch;\n batch.Delete(\"key1\");\n batch.Put(\"key2\", value);\n s = db->Write(WriteOptions(), &batch);\n }\n\n s = db->Get(ReadOptions(), \"key1\", &value);\n assert(s.IsNotFound());\n\n db->Get(ReadOptions(), \"key2\", &value);\n assert(value == \"value\");\n\n delete db;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2012, Stuart W Baker\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 met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file Fileio.cxx\n * This file implements the generic fileio.\n *\n * @author Stuart W. Baker\n * @date 27 December 2012\n *\/\n\n#include <sys\/stat.h>\n#include <cstring>\n#include <cerrno>\n#include <cstdarg>\n#include <algorithm>\n#include <fcntl.h>\n#include \"reent.h\"\n#include \"Devtab.hxx\"\n#include \"os\/OS.hxx\"\n#include \"can_ioctl.h\"\n#include \"executor\/Notifiable.hxx\"\n\nDevice *Device::first = NULL;\nOSMutex Device::mutex;\n\n#ifdef TARGET_LPC11Cxx\n#define NUM_OPEN_FILES 4\n#else\n#define NUM_OPEN_FILES 8\n#endif\n\n\n\/** Null device instance *\/\nclass Null : public Device\n{\npublic:\n \/** Constructor *\/\n Null(const char* path) : Device(path)\n {\n }\n\n \/** Open method *\/\n int open(File *, const char *, int, int) OVERRIDE;\n \/** Close method *\/\n int close(File *) OVERRIDE;\n \/** Read method *\/\n ssize_t read(File *, void *, size_t) OVERRIDE;\n \/** Write method *\/\n ssize_t write(File *, const void *, size_t) OVERRIDE;\n};\n\nNull null(\"\/dev\/null\");\n\n\/** default stdin *\/\nconst char *STDIN_DEVICE __attribute__ ((weak)) = \"\/dev\/null\";\n\n\/** default stdout *\/\nconst char *STDOUT_DEVICE __attribute__ ((weak)) = \"\/dev\/null\";\n\n\/** default stderr *\/\nconst char *STDERR_DEVICE __attribute__ ((weak)) = \"\/dev\/null\";\n\n\/** File descriptor array. *\/\nstatic File files[NUM_OPEN_FILES];\n\n\/** Allocate a free file descriptor.\n * @return file number on success, else -1 on failure\n *\/\nint fd_alloc(void)\n{\n for (unsigned int i = 0; i < NUM_OPEN_FILES; i++)\n {\n if (files[i].inuse == 0)\n {\n files[i].inuse = 1;\n files[i].priv = nullptr;\n files[i].dev = nullptr;\n files[i].offset = 0;\n files[i].flags = 0;\n return i;\n }\n }\n return -1;\n}\n\n\/** Free up a file descriptor.\n * @param fd number to free up\n *\/\nvoid fd_free(int fd)\n{\n files[fd].inuse = 0;\n}\n\n\/** Looks up an fd.\n *\n * @param fd is a file descriptor as supplied to the read-write-close-ioctl\n * commands.\n * @returns NULL and sets errno if fd is invalid, otherwise the file structure\n * pointer. *\/\nFile* fd_find(int fd) {\n if (fd < 0 || fd >= NUM_OPEN_FILES)\n {\n errno = EBADF;\n return nullptr;\n }\n if (files[fd].inuse == 0)\n {\n errno = EBADF;\n return nullptr;\n }\n return &files[fd];\n}\n\n\/** Open a file or device.\n * @param reent thread save reentrant structure\n * @param path file or device name\n * @param flags open flags\n * @param mode open mode, ignored in this implementation\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint _open_r(struct _reent *reent, const char *path, int flags, int mode)\n{\n return Device::open(reent, path, flags, mode);\n}\n\n\/** Close a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to close\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint _close_r(struct _reent *reent, int fd)\n{\n File* f = fd_find(fd);\n if (!f) \n {\n return -1;\n }\n if (fd >=0 && fd <= 2)\n {\n \/\/ stdin, stdout, and stderr never get closed\n return 0;\n }\n int result = f->dev->close(f);\n if (result < 0)\n {\n errno = -result;\n return -1;\n }\n fd_free(fd);\n return 0;\n}\n\n\/** Read from a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to read\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t _read_r(struct _reent *reent, int fd, void *buf, size_t count)\n{\n File* f = fd_find(fd);\n if (!f) \n {\n return -1;\n }\n ssize_t result = f->dev->read(f, buf, count);\n if (result < 0)\n {\n errno = -result;\n return -1;\n }\n return result;\n}\n\n\/** Write to a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to write\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t _write_r(struct _reent *reent, int fd, const void *buf, size_t count)\n{\n File* f = fd_find(fd);\n if (!f) \n {\n return -1;\n }\n ssize_t result = f->dev->write(f, buf, count);\n if (result < 0)\n {\n errno = -result;\n return -1;\n }\n return result;\n}\n\n\/** Get the status information of a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to get status of\n * @param stat structure to fill status info into\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint _fstat_r(struct _reent *reent, int fd, struct stat *stat)\n{\n return 0;\n}\n\n\/** Get the tty information of a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor determine if it is a tty\n * @return 1 if a tty, else 0\n *\/\nint _isatty_r(struct _reent *reent, int fd)\n{\n return 1;\n}\n\n\/** Change the offset index of a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to seek\n * @param offset offset within file\n * @param whence type of seek to complete\n * @return resulting offset from beginning of file, -1 upon failure with errno containing the cause\n *\/\n_off_t _lseek_r(struct _reent *reent, int fd, _off_t offset, int whence)\n{\n File* f = fd_find(fd);\n if (!f)\n {\n return (_off_t) -1;\n }\n return f->dev->lseek(f, offset, whence);\n}\n\n\/** Request and ioctl transaction.\n * @param fd file descriptor\n * @param key ioctl key\n * @param ... key data\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint ioctl(int fd, unsigned long int key, ...)\n{\n File* f = fd_find(fd);\n if (!f) \n {\n return -1;\n }\n\n va_list ap;\n va_start(ap, key);\n\n int result = f->dev->ioctl(f, key, va_arg(ap, unsigned long));\n \n va_end(ap);\n return result;\n}\n\nDevice::Device(const char *name)\n : name(name)\n{\n mutex.lock();\n next = first;\n first = this;\n mutex.unlock();\n}\n\n\/** Open a file or device.\n * @param reent thread save reentrant structure\n * @param path file or device name\n * @param flags open flags\n * @param mode open mode, ignored in this implementation\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint Device::open(struct _reent *reent, const char *path, int flags, int mode)\n{\n mutex.lock();\n int fd = fd_alloc();\n mutex.unlock();\n if (fd < 0)\n {\n errno = EMFILE;\n return -1;\n }\n \/\/ Sets the dev to a safe default in case we don't find the file later.\n files[fd].dev = &null;\n files[fd].flags = flags;\n for (Device *dev = first; dev != NULL; dev = dev->next)\n {\n if (!strcmp(dev->name, path))\n {\n files[fd].dev = dev;\n int result = dev->open(&files[fd], path, flags, mode);\n if (result < 0)\n {\n fd_free(fd);\n errno = -result;\n return -1;\n }\n return fd;\n }\n }\n \/\/ No device found.\n fd_free(fd);\n errno = ENODEV;\n return -1;\n}\n\noff_t Device::lseek(File* f, off_t offset, int whence)\n{\n switch (whence) {\n case SEEK_SET:\n f->offset = offset;\n return offset;\n case SEEK_CUR:\n f->offset += offset;\n return f->offset;\n }\n errno = EINVAL;\n return (off_t)-1;\n}\n\n\/** Open a device.\n * @param file new file reference to this device\n * @param path file or device name\n * @param flags open flags\n * @param mode open mode\n * @return 0 upon success, negative errno upon failure\n *\/\nint Null::open(File* file, const char *path, int flags, int mode)\n{ \n return 0;\n}\n\n\/** Close a device.\n * @param file file reference for this device\n * @param node node reference for this device\n * @return 0 upon success, negative errno upon failure\n *\/\nint Null::close(File *file)\n{ \n return 0;\n}\n\n\/** Read from a file or device.\n * @param file file reference for this device\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t Null::read(File *file, void *buf, size_t count)\n{\n \/\/ \/dev\/null returns EOF when trying to read from it.\n return 0;\n}\n\n\/** Write to a file or device.\n * @param file file reference for this device\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t Null::write(File *file, const void *buf, size_t count)\n{ \n return count;\n}\n\nint Device::ioctl(File *, unsigned long int, unsigned long) {\n return -EINVAL;\n}\n\n\/** Open method *\/\nint Node::open(File *, const char *, int, int) OVERRIDE {\n OSMutexLock l(&lock_);\n if (references_++ == 0) {\n enable();\n }\n return 0;\n}\n\n\/** Close method *\/\nint Node::close(File *) OVERRIDE {\n OSMutexLock l(&lock_);\n if (--references_ <= 0) {\n disable();\n references_ = 0;\n }\n return 0;\n}\n\n\n\n\/** Request an ioctl transaction\n * @param file file reference for this device\n * @param node node reference for this device\n * @param key ioctl key\n * @param data key data\n *\/\nint NonBlockNode::ioctl(File *file, unsigned long int key, unsigned long data)\n{\n \/* sanity check to be sure we have a valid key for this device *\/\n HASSERT(IOC_TYPE(key) == CAN_IOC_MAGIC);\n\n \/\/ Will be called at the end if non-null.\n Notifiable* n = nullptr;\n\n if (IOC_SIZE(key) == NOTIFIABLE_TYPE) {\n n = reinterpret_cast<Notifiable*>(data);\n }\n\n switch (key)\n {\n default:\n return -EINVAL;\n case CAN_IOC_READ_ACTIVE:\n portENTER_CRITICAL();\n if (!has_rx_buffer_data())\n {\n swap(n, readableNotify_);\n }\n portEXIT_CRITICAL();\n break;\n case CAN_IOC_WRITE_ACTIVE:\n portENTER_CRITICAL();\n if (!has_tx_buffer_space())\n {\n swap(n, writableNotify_);\n }\n portEXIT_CRITICAL();\n break;\n }\n if (n)\n {\n n->notify();\n }\n return 0;\n}\n<commit_msg>trivial coding style change<commit_after>\/** \\copyright\n * Copyright (c) 2012, Stuart W Baker\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 met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file Fileio.cxx\n * This file implements the generic fileio.\n *\n * @author Stuart W. Baker\n * @date 27 December 2012\n *\/\n\n#include <sys\/stat.h>\n#include <cstring>\n#include <cerrno>\n#include <cstdarg>\n#include <algorithm>\n#include <fcntl.h>\n#include \"reent.h\"\n#include \"Devtab.hxx\"\n#include \"os\/OS.hxx\"\n#include \"can_ioctl.h\"\n#include \"executor\/Notifiable.hxx\"\n\nDevice *Device::first = NULL;\nOSMutex Device::mutex;\n\n#ifdef TARGET_LPC11Cxx\n#define NUM_OPEN_FILES 4\n#else\n#define NUM_OPEN_FILES 8\n#endif\n\n\n\/** Null device instance *\/\nclass Null : public Device\n{\npublic:\n \/** Constructor *\/\n Null(const char* path) : Device(path)\n {\n }\n\n \/** Open method *\/\n int open(File *, const char *, int, int) OVERRIDE;\n \/** Close method *\/\n int close(File *) OVERRIDE;\n \/** Read method *\/\n ssize_t read(File *, void *, size_t) OVERRIDE;\n \/** Write method *\/\n ssize_t write(File *, const void *, size_t) OVERRIDE;\n};\n\nNull null(\"\/dev\/null\");\n\n\/** default stdin *\/\nconst char *STDIN_DEVICE __attribute__ ((weak)) = \"\/dev\/null\";\n\n\/** default stdout *\/\nconst char *STDOUT_DEVICE __attribute__ ((weak)) = \"\/dev\/null\";\n\n\/** default stderr *\/\nconst char *STDERR_DEVICE __attribute__ ((weak)) = \"\/dev\/null\";\n\n\/** File descriptor array. *\/\nstatic File files[NUM_OPEN_FILES];\n\n\/** Allocate a free file descriptor.\n * @return file number on success, else -1 on failure\n *\/\nint fd_alloc(void)\n{\n for (unsigned int i = 0; i < NUM_OPEN_FILES; i++)\n {\n if (files[i].inuse == 0)\n {\n files[i].inuse = 1;\n files[i].priv = nullptr;\n files[i].dev = nullptr;\n files[i].offset = 0;\n files[i].flags = 0;\n return i;\n }\n }\n return -1;\n}\n\n\/** Free up a file descriptor.\n * @param fd number to free up\n *\/\nvoid fd_free(int fd)\n{\n files[fd].inuse = 0;\n}\n\n\/** Looks up an fd.\n *\n * @param fd is a file descriptor as supplied to the read-write-close-ioctl\n * commands.\n * @returns NULL and sets errno if fd is invalid, otherwise the file structure\n * pointer. *\/\nFile* fd_find(int fd) {\n if (fd < 0 || fd >= NUM_OPEN_FILES)\n {\n errno = EBADF;\n return nullptr;\n }\n if (files[fd].inuse == 0)\n {\n errno = EBADF;\n return nullptr;\n }\n return &files[fd];\n}\n\n\/** Open a file or device.\n * @param reent thread save reentrant structure\n * @param path file or device name\n * @param flags open flags\n * @param mode open mode, ignored in this implementation\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint _open_r(struct _reent *reent, const char *path, int flags, int mode)\n{\n return Device::open(reent, path, flags, mode);\n}\n\n\/** Close a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to close\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint _close_r(struct _reent *reent, int fd)\n{\n File* f = fd_find(fd);\n if (!f) \n {\n return -1;\n }\n if (fd >=0 && fd <= 2)\n {\n \/\/ stdin, stdout, and stderr never get closed\n return 0;\n }\n int result = f->dev->close(f);\n if (result < 0)\n {\n errno = -result;\n return -1;\n }\n fd_free(fd);\n return 0;\n}\n\n\/** Read from a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to read\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t _read_r(struct _reent *reent, int fd, void *buf, size_t count)\n{\n File* f = fd_find(fd);\n if (!f) \n {\n return -1;\n }\n ssize_t result = f->dev->read(f, buf, count);\n if (result < 0)\n {\n errno = -result;\n return -1;\n }\n return result;\n}\n\n\/** Write to a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to write\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t _write_r(struct _reent *reent, int fd, const void *buf, size_t count)\n{\n File* f = fd_find(fd);\n if (!f) \n {\n return -1;\n }\n ssize_t result = f->dev->write(f, buf, count);\n if (result < 0)\n {\n errno = -result;\n return -1;\n }\n return result;\n}\n\n\/** Get the status information of a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to get status of\n * @param stat structure to fill status info into\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint _fstat_r(struct _reent *reent, int fd, struct stat *stat)\n{\n return 0;\n}\n\n\/** Get the tty information of a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor determine if it is a tty\n * @return 1 if a tty, else 0\n *\/\nint _isatty_r(struct _reent *reent, int fd)\n{\n return 1;\n}\n\n\/** Change the offset index of a file or device.\n * @param reent thread save reentrant structure\n * @param fd file descriptor to seek\n * @param offset offset within file\n * @param whence type of seek to complete\n * @return resulting offset from beginning of file, -1 upon failure with errno containing the cause\n *\/\n_off_t _lseek_r(struct _reent *reent, int fd, _off_t offset, int whence)\n{\n File* f = fd_find(fd);\n if (!f)\n {\n return (_off_t) -1;\n }\n return f->dev->lseek(f, offset, whence);\n}\n\n\/** Request and ioctl transaction.\n * @param fd file descriptor\n * @param key ioctl key\n * @param ... key data\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint ioctl(int fd, unsigned long int key, ...)\n{\n File* f = fd_find(fd);\n if (!f) \n {\n return -1;\n }\n\n va_list ap;\n va_start(ap, key);\n\n int result = f->dev->ioctl(f, key, va_arg(ap, unsigned long));\n \n va_end(ap);\n return result;\n}\n\nDevice::Device(const char *name)\n : name(name)\n{\n mutex.lock();\n next = first;\n first = this;\n mutex.unlock();\n}\n\n\/** Open a file or device.\n * @param reent thread save reentrant structure\n * @param path file or device name\n * @param flags open flags\n * @param mode open mode, ignored in this implementation\n * @return 0 upon success, -1 upon failure with errno containing the cause\n *\/\nint Device::open(struct _reent *reent, const char *path, int flags, int mode)\n{\n mutex.lock();\n int fd = fd_alloc();\n mutex.unlock();\n if (fd < 0)\n {\n errno = EMFILE;\n return -1;\n }\n \/\/ Sets the dev to a safe default in case we don't find the file later.\n files[fd].dev = &null;\n files[fd].flags = flags;\n for (Device *dev = first; dev != NULL; dev = dev->next)\n {\n if (!strcmp(dev->name, path))\n {\n files[fd].dev = dev;\n int result = dev->open(&files[fd], path, flags, mode);\n if (result < 0)\n {\n fd_free(fd);\n errno = -result;\n return -1;\n }\n return fd;\n }\n }\n \/\/ No device found.\n fd_free(fd);\n errno = ENODEV;\n return -1;\n}\n\noff_t Device::lseek(File* f, off_t offset, int whence)\n{\n switch (whence)\n {\n case SEEK_SET:\n f->offset = offset;\n return offset;\n case SEEK_CUR:\n f->offset += offset;\n return f->offset;\n }\n errno = EINVAL;\n return (off_t)-1;\n}\n\n\/** Open a device.\n * @param file new file reference to this device\n * @param path file or device name\n * @param flags open flags\n * @param mode open mode\n * @return 0 upon success, negative errno upon failure\n *\/\nint Null::open(File* file, const char *path, int flags, int mode)\n{ \n return 0;\n}\n\n\/** Close a device.\n * @param file file reference for this device\n * @param node node reference for this device\n * @return 0 upon success, negative errno upon failure\n *\/\nint Null::close(File *file)\n{ \n return 0;\n}\n\n\/** Read from a file or device.\n * @param file file reference for this device\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t Null::read(File *file, void *buf, size_t count)\n{\n \/\/ \/dev\/null returns EOF when trying to read from it.\n return 0;\n}\n\n\/** Write to a file or device.\n * @param file file reference for this device\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t Null::write(File *file, const void *buf, size_t count)\n{ \n return count;\n}\n\nint Device::ioctl(File *, unsigned long int, unsigned long) {\n return -EINVAL;\n}\n\n\/** Open method *\/\nint Node::open(File *, const char *, int, int) OVERRIDE {\n OSMutexLock l(&lock_);\n if (references_++ == 0) {\n enable();\n }\n return 0;\n}\n\n\/** Close method *\/\nint Node::close(File *) OVERRIDE {\n OSMutexLock l(&lock_);\n if (--references_ <= 0) {\n disable();\n references_ = 0;\n }\n return 0;\n}\n\n\n\n\/** Request an ioctl transaction\n * @param file file reference for this device\n * @param node node reference for this device\n * @param key ioctl key\n * @param data key data\n *\/\nint NonBlockNode::ioctl(File *file, unsigned long int key, unsigned long data)\n{\n \/* sanity check to be sure we have a valid key for this device *\/\n HASSERT(IOC_TYPE(key) == CAN_IOC_MAGIC);\n\n \/\/ Will be called at the end if non-null.\n Notifiable* n = nullptr;\n\n if (IOC_SIZE(key) == NOTIFIABLE_TYPE) {\n n = reinterpret_cast<Notifiable*>(data);\n }\n\n switch (key)\n {\n default:\n return -EINVAL;\n case CAN_IOC_READ_ACTIVE:\n portENTER_CRITICAL();\n if (!has_rx_buffer_data())\n {\n swap(n, readableNotify_);\n }\n portEXIT_CRITICAL();\n break;\n case CAN_IOC_WRITE_ACTIVE:\n portENTER_CRITICAL();\n if (!has_tx_buffer_space())\n {\n swap(n, writableNotify_);\n }\n portEXIT_CRITICAL();\n break;\n }\n if (n)\n {\n n->notify();\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2014 - 2015 CyberTech Labs Ltd.\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 \"trikScriptRunnerTest.h\"\n\n#include <QtCore\/QEventLoop>\n\n#include <trikControl\/brickFactory.h>\n#include <trikKernel\/fileUtils.h>\n#include <testUtils\/wait.h>\n\nusing namespace tests;\n\nQScriptValue scriptAssert(QScriptContext *context, QScriptEngine *engine)\n{\n\tQ_UNUSED(engine);\n\n\tif (context->argumentCount() != 1) {\n\t\tADD_FAILURE() << \"'assert' shall have exactly one argument\";\n\t\treturn {};\n\t}\n\n\tif (!context->argument(0).toBool()) {\n\t\tADD_FAILURE() << \"Assertion failure at\\n\"\n\t\t\t\t<< QStringList(context->backtrace().mid(1)).join(\"\\n\").toStdString();\n\t}\n\n\treturn {};\n}\n\nvoid TrikScriptRunnerTest::SetUp()\n{\n\tmBrick.reset(trikControl::BrickFactory::create(\".\/\", \".\/\"));\n\tmScriptRunner.reset(new trikScriptRunner::TrikScriptRunner(*mBrick, nullptr, nullptr));\n\tmScriptRunner->registerUserFunction(\"assert\", scriptAssert);\n}\n\nvoid TrikScriptRunnerTest::TearDown()\n{\n}\n\nvoid TrikScriptRunnerTest::run(const QString &script)\n{\n\tQEventLoop waitingLoop;\n\tQObject::connect(mScriptRunner.data(), SIGNAL(completed(QString, int)), &waitingLoop, SLOT(quit()));\n\tmScriptRunner->run(script);\n\n\twaitingLoop.exec();\n}\n\nvoid TrikScriptRunnerTest::runDirectCommandAndWaitForQuit(const QString &script)\n{\n\tQEventLoop waitingLoop;\n\tQObject::connect(mScriptRunner.data(), SIGNAL(completed(QString, int)), &waitingLoop, SLOT(quit()));\n\tmScriptRunner->runDirectCommand(script);\n\n\twaitingLoop.exec();\n}\n\nvoid TrikScriptRunnerTest::runFromFile(const QString &fileName)\n{\n\tconst auto fileContents = trikKernel::FileUtils::readFromFile(\"data\/\" + fileName);\n\trun(fileContents);\n}\n\ntrikScriptRunner::TrikScriptRunner &TrikScriptRunnerTest::scriptRunner()\n{\n\treturn *mScriptRunner;\n}\n\nTEST_F(TrikScriptRunnerTest, sanityCheck)\n{\n\trun(\"1 + 1\");\n}\n\nTEST_F(TrikScriptRunnerTest, fileTest)\n{\n\trunFromFile(\"file-test.js\");\n}\n\nTEST_F(TrikScriptRunnerTest, asyncSystemTest)\n{\n\tQFile testFile(\"test\");\n\ttestFile.remove();\n\tASSERT_FALSE(testFile.exists());\n\trunFromFile(\"async-system-test.js\");\n\tASSERT_FALSE(testFile.exists());\n\ttests::utils::Wait::wait(2500);\n\tASSERT_TRUE(testFile.exists());\n}\n\nTEST_F(TrikScriptRunnerTest, syncSystemTest)\n{\n\tQFile testFile(\"test\");\n\ttestFile.remove();\n\tASSERT_FALSE(testFile.exists());\n\trunFromFile(\"sync-system-test.js\");\n\tASSERT_TRUE(testFile.exists());\n}\n\nTEST_F(TrikScriptRunnerTest, directCommandTest)\n{\n\tQFile testFile(\"test\");\n\ttestFile.remove();\n\tASSERT_FALSE(testFile.exists());\n\tscriptRunner().runDirectCommand(\"script.system('echo 123 > test', true);\");\n\ttests::utils::Wait::wait(100);\n\tASSERT_TRUE(testFile.exists());\n\tscriptRunner().runDirectCommand(\"script.system('rm test', true);\");\n\ttests::utils::Wait::wait(100);\n\tASSERT_FALSE(testFile.exists());\n\tscriptRunner().runDirectCommand(\"script.quit();\");\n}\n\nTEST_F(TrikScriptRunnerTest, directCommandThatQuitsImmediatelyTest)\n{\n\tQFile testFile(\"test\");\n\ttestFile.remove();\n\tASSERT_FALSE(testFile.exists());\n\trunDirectCommandAndWaitForQuit(\"script.system('echo 123 > test', true); script.quit();\");\n\tASSERT_TRUE(testFile.exists());\n\trunDirectCommandAndWaitForQuit(\"script.system('rm test', true); script.quit();\");\n\tASSERT_FALSE(testFile.exists());\n}\n<commit_msg>Added test that sumultaneously launches two scripts<commit_after>\/* Copyright 2014 - 2015 CyberTech Labs Ltd.\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 \"trikScriptRunnerTest.h\"\n\n#include <QtCore\/QEventLoop>\n\n#include <trikControl\/brickFactory.h>\n#include <trikKernel\/fileUtils.h>\n#include <testUtils\/wait.h>\n\nusing namespace tests;\n\nQScriptValue scriptAssert(QScriptContext *context, QScriptEngine *engine)\n{\n\tQ_UNUSED(engine);\n\n\tif (context->argumentCount() != 1) {\n\t\tADD_FAILURE() << \"'assert' shall have exactly one argument\";\n\t\treturn {};\n\t}\n\n\tif (!context->argument(0).toBool()) {\n\t\tADD_FAILURE() << \"Assertion failure at\\n\"\n\t\t\t\t<< QStringList(context->backtrace().mid(1)).join(\"\\n\").toStdString();\n\t}\n\n\treturn {};\n}\n\nvoid TrikScriptRunnerTest::SetUp()\n{\n\tmBrick.reset(trikControl::BrickFactory::create(\".\/\", \".\/\"));\n\tmScriptRunner.reset(new trikScriptRunner::TrikScriptRunner(*mBrick, nullptr, nullptr));\n\tmScriptRunner->registerUserFunction(\"assert\", scriptAssert);\n}\n\nvoid TrikScriptRunnerTest::TearDown()\n{\n}\n\nvoid TrikScriptRunnerTest::run(const QString &script)\n{\n\tQEventLoop waitingLoop;\n\tQObject::connect(mScriptRunner.data(), SIGNAL(completed(QString, int)), &waitingLoop, SLOT(quit()));\n\tmScriptRunner->run(script);\n\n\twaitingLoop.exec();\n}\n\nvoid TrikScriptRunnerTest::runDirectCommandAndWaitForQuit(const QString &script)\n{\n\tQEventLoop waitingLoop;\n\tQObject::connect(mScriptRunner.data(), SIGNAL(completed(QString, int)), &waitingLoop, SLOT(quit()));\n\tmScriptRunner->runDirectCommand(script);\n\n\twaitingLoop.exec();\n}\n\nvoid TrikScriptRunnerTest::runFromFile(const QString &fileName)\n{\n\tconst auto fileContents = trikKernel::FileUtils::readFromFile(\"data\/\" + fileName);\n\trun(fileContents);\n}\n\ntrikScriptRunner::TrikScriptRunner &TrikScriptRunnerTest::scriptRunner()\n{\n\treturn *mScriptRunner;\n}\n\nTEST_F(TrikScriptRunnerTest, sanityCheck)\n{\n\trun(\"1 + 1\");\n}\n\nTEST_F(TrikScriptRunnerTest, fileTest)\n{\n\trunFromFile(\"file-test.js\");\n}\n\nTEST_F(TrikScriptRunnerTest, asyncSystemTest)\n{\n\tQFile testFile(\"test\");\n\ttestFile.remove();\n\tASSERT_FALSE(testFile.exists());\n\trunFromFile(\"async-system-test.js\");\n\tASSERT_FALSE(testFile.exists());\n\ttests::utils::Wait::wait(2500);\n\tASSERT_TRUE(testFile.exists());\n}\n\nTEST_F(TrikScriptRunnerTest, syncSystemTest)\n{\n\tQFile testFile(\"test\");\n\ttestFile.remove();\n\tASSERT_FALSE(testFile.exists());\n\trunFromFile(\"sync-system-test.js\");\n\tASSERT_TRUE(testFile.exists());\n}\n\nTEST_F(TrikScriptRunnerTest, directCommandTest)\n{\n\tQFile testFile(\"test\");\n\ttestFile.remove();\n\tASSERT_FALSE(testFile.exists());\n\tscriptRunner().runDirectCommand(\"script.system('echo 123 > test', true);\");\n\ttests::utils::Wait::wait(100);\n\tASSERT_TRUE(testFile.exists());\n\tscriptRunner().runDirectCommand(\"script.system('rm test', true);\");\n\ttests::utils::Wait::wait(100);\n\tASSERT_FALSE(testFile.exists());\n\tscriptRunner().runDirectCommand(\"script.quit();\");\n}\n\nTEST_F(TrikScriptRunnerTest, directCommandThatQuitsImmediatelyTest)\n{\n\tQFile testFile(\"test\");\n\ttestFile.remove();\n\tASSERT_FALSE(testFile.exists());\n\trunDirectCommandAndWaitForQuit(\"script.system('echo 123 > test', true); script.quit();\");\n\tASSERT_TRUE(testFile.exists());\n\trunDirectCommandAndWaitForQuit(\"script.system('rm test', true); script.quit();\");\n\tASSERT_FALSE(testFile.exists());\n}\n\nTEST_F(TrikScriptRunnerTest, twoProgramsTest)\n{\n\tscriptRunner().run(\"script.wait(500);\");\n\ttests::utils::Wait::wait(100);\n\tscriptRunner().run(\"script.wait(500);\");\n\ttests::utils::Wait::wait(600);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file compile_filter_main.cc\n *\n * @section LICENSE\n *\n * The MIT License\n *\n * @copyright Copyright (c) 2022 TileDB, Inc.\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\n#include \"..\/bzip_compressor.h\"\n#include \"..\/dd_compressor.h\"\n#include \"..\/dict_compressor.h\"\n#include \"..\/gzip_compressor.h\"\n#include \"..\/lz4_compressor.h\"\n#include \"..\/rle_compressor.h\"\n#include \"..\/zstd_compressor.h\"\n\n#include \"tiledb\/common\/common.h\"\n#include \"tiledb\/common\/scoped_executor.h\"\n#include \"tiledb\/sm\/buffer\/buffer.h\"\n#include \"tiledb\/sm\/filter\/filter_buffer.h\"\n#include \"tiledb\/sm\/filter\/filter_storage.h\"\n#include \"tiledb\/sm\/misc\/types.h\"\n\n#include \"gzip_wrappers.h\"\n\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <iomanip>\n#include <iostream>\n#include <memory>\n#include <sstream>\n\n#ifdef _WIN32\n#include <fcntl.h>\n#include <io.h>\n#endif\n\nint main(int argc, char* argv[]) {\n (void)sizeof(tiledb::sm::GZip);\n\n const int seg_sz = 4096;\n char fbuf[seg_sz];\n auto filter_stg = make_shared<tiledb::sm::FilterStorage>(HERE());\n auto inbuf = make_shared<tiledb::sm::Buffer>(HERE());\n auto zipped_buf = make_shared<tiledb::sm::FilterBuffer>(HERE(), &*filter_stg);\n uint64_t nread;\n uint64_t cntread = 0;\n\n auto infile = stdin;\n auto outfile = stdout;\n\n \/\/ note: If stdout used ( '>' ), compressed data subject to being\n \/\/ intermixed with any application output, corrupting the compressed\n \/\/ output stream.\n\n if (argc > 1) {\n outfile = fopen(argv[1], \"w+b\");\n if (!outfile) {\n fprintf(stderr, \"Unable to create file %s\\n\", argv[1]);\n exit(-2);\n }\n }\n auto closefile = [&]() { fclose(outfile); };\n tiledb::common::ScopedExecutor onexit1(closefile);\n\n#ifdef _WIN32\n \/\/ need to be sure in\/out are in binay mode, windows default won't be!!!\n if ((-1 == _setmode(fileno(stdin), _O_BINARY)) ||\n (-1 == _setmode(fileno(stdout), _O_BINARY))) {\n fprintf(stderr, \"failure setting stdin\/stdout to binary mode!\");\n exit(-1);\n }\n#endif\n\n do {\n nread = fread(fbuf, 1, sizeof(fbuf), infile);\n if (nread) {\n inbuf->write(fbuf, nread);\n cntread += nread;\n }\n } while (nread == sizeof(fbuf));\n\n tiledb::sm::ConstBuffer const_inbuf(&*inbuf);\n \/\/ Ensure space in output buffer for worst case.\n if (!zipped_buf->prepend_buffer(inbuf->size()).ok()) {\n printf(\"output buffer allocation error!\\n\");\n exit(-3);\n }\n tiledb::sm::Buffer* out_buffer_ptr = zipped_buf->buffer_ptr(0);\n assert(out_buffer_ptr != nullptr);\n out_buffer_ptr->reset_offset();\n if (!tiledb::sm::GZip::compress(9, &const_inbuf, out_buffer_ptr).ok()) {\n printf(\"Error compressing data!\\n\");\n exit(-4);\n }\n std::cerr << \"sizes input \" << inbuf->size() << \", compressed \"\n << out_buffer_ptr->size() << std::endl;\n if(0) \/\/ leave available for future possible diagnostic need\n {\n \/\/ save compressed data to allow examination from filesystem\n auto outgzip = fopen(\"magic-mgc.tdbgzip\", \"wb\");\n if (!outgzip) {\n fprintf(stderr, \"Unable to create magic-mgc.tdbgzip!\\n\");\n exit(-21);\n }\n if (fwrite(out_buffer_ptr->data(0), 1, out_buffer_ptr->size(), outgzip) !=\n out_buffer_ptr->size()) {\n fprintf(stderr, \"write failure magic-mgc.tdbgzip!\\n\");\n exit(-22);\n }\n fclose(outgzip);\n }\n auto tdb_gzip_buf = make_shared<tiledb::sm::Buffer>(HERE());\n\n unsigned maxnperline = 128;\n auto addbytevals = [&](void* _pbytes, uint64_t nbytes) {\n uint8_t* pbytes = reinterpret_cast<uint8_t*>(_pbytes);\n static unsigned cntout = 0;\n for (auto i = 0u; i < nbytes; ++i) {\n fprintf(outfile, \"'\\\\x%02x',\", pbytes[i]);\n if (++cntout > maxnperline) {\n cntout = 0;\n fprintf(outfile, \"\\n\");\n }\n }\n };\n addbytevals(&cntread, sizeof(cntread));\n tdb_gzip_buf->write(&cntread, sizeof(cntread));\n uint64_t compressed_size = zipped_buf->size();\n addbytevals(&compressed_size, sizeof(compressed_size));\n tdb_gzip_buf->write(&compressed_size, sizeof(compressed_size));\n auto nremaining = zipped_buf->size();\n \/\/ vs19 complained...\n \/\/ A) could not find raw string literal terminator\n \/\/ for almost identical error, though not quite same cause, can see\n \/\/ https:\/\/developercommunity.visualstudio.com\/t\/bug-in-raw-string-implementation-converning-eof-02\/254730)\n \/\/ vs19 16.11.3 was in use with tiledb failed #include of raw literal file\n \/\/ B) that (all data as) one string was to large a string\n \/\/ C) many shorter strings expecting concatention were causing\n \/\/ compiler heap memory errors (100+GB)\n \/\/ D) caused warnings trying to do direct 0xXX numeric values\n \/\/ end result format is comma delimited '\\xXX' characters with periodic line\n \/\/ splits\n while (nremaining) {\n auto ntowrite = nremaining > seg_sz ? seg_sz : nremaining;\n \/\/ TBD: error from ->read()?\n if (!zipped_buf->read(fbuf, ntowrite).ok()) {\n printf(\"ERROR reading from compressed data.\\n\");\n exit(-7);\n }\n if (!tdb_gzip_buf->write(fbuf, ntowrite).ok()) {\n printf(\"ERROR writing compressed format buffer.\");\n exit(-11);\n }\n addbytevals(fbuf, ntowrite);\n nremaining -= ntowrite;\n }\n\n \/\/ brief sanity check that wrapper compression matches unwrapped compression\n shared_ptr<tiledb::sm::Buffer> out_gzipped_buf =\n make_shared<tiledb::sm::Buffer>(HERE());\n gzip_compress(out_gzipped_buf, inbuf->data(0), inbuf->size());\n if (out_gzipped_buf->size() != tdb_gzip_buf->size()) {\n printf(\n \"Error, compressed data sizes mismatch! %\" PRIu64 \", %\" PRIu64 \"u\\n\",\n out_gzipped_buf->size(),\n tdb_gzip_buf->size());\n exit(-13);\n }\n if (memcmp(\n out_gzipped_buf->data(0),\n tdb_gzip_buf->data(0),\n out_gzipped_buf->size()) \/\/ tdb_gzip_buf->size())\n ) {\n printf(\"Error, compressed data mismatch!\\n\");\n exit(-17);\n }\n\n shared_ptr<tiledb::sm::ByteVecValue> expanded_buffer =\n make_shared<tiledb::sm::ByteVecValue>(HERE());\n\n \/\/ brief sanity check the decompressed()d data matches original\n tdb_gzip_buf->set_offset(0);\n gzip_decompress(expanded_buffer, static_cast<uint8_t*>(tdb_gzip_buf->data()));\n if (expanded_buffer->size() != inbuf->size()) {\n fprintf(stderr, \"re-expanded size different from original size!\\n\");\n exit(-29);\n }\n if (memcmp(expanded_buffer->data(), inbuf->data(), inbuf->size())) {\n printf(\"Error uncompress data != original data!\\n\");\n exit(-21);\n }\n\n return 0;\n}\n<commit_msg>clang format<commit_after>\/**\n * @file compile_filter_main.cc\n *\n * @section LICENSE\n *\n * The MIT License\n *\n * @copyright Copyright (c) 2022 TileDB, Inc.\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\n#include \"..\/bzip_compressor.h\"\n#include \"..\/dd_compressor.h\"\n#include \"..\/dict_compressor.h\"\n#include \"..\/gzip_compressor.h\"\n#include \"..\/lz4_compressor.h\"\n#include \"..\/rle_compressor.h\"\n#include \"..\/zstd_compressor.h\"\n\n#include \"tiledb\/common\/common.h\"\n#include \"tiledb\/common\/scoped_executor.h\"\n#include \"tiledb\/sm\/buffer\/buffer.h\"\n#include \"tiledb\/sm\/filter\/filter_buffer.h\"\n#include \"tiledb\/sm\/filter\/filter_storage.h\"\n#include \"tiledb\/sm\/misc\/types.h\"\n\n#include \"gzip_wrappers.h\"\n\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <iomanip>\n#include <iostream>\n#include <memory>\n#include <sstream>\n\n#ifdef _WIN32\n#include <fcntl.h>\n#include <io.h>\n#endif\n\nint main(int argc, char* argv[]) {\n (void)sizeof(tiledb::sm::GZip);\n\n const int seg_sz = 4096;\n char fbuf[seg_sz];\n auto filter_stg = make_shared<tiledb::sm::FilterStorage>(HERE());\n auto inbuf = make_shared<tiledb::sm::Buffer>(HERE());\n auto zipped_buf = make_shared<tiledb::sm::FilterBuffer>(HERE(), &*filter_stg);\n uint64_t nread;\n uint64_t cntread = 0;\n\n auto infile = stdin;\n auto outfile = stdout;\n\n \/\/ note: If stdout used ( '>' ), compressed data subject to being\n \/\/ intermixed with any application output, corrupting the compressed\n \/\/ output stream.\n\n if (argc > 1) {\n outfile = fopen(argv[1], \"w+b\");\n if (!outfile) {\n fprintf(stderr, \"Unable to create file %s\\n\", argv[1]);\n exit(-2);\n }\n }\n auto closefile = [&]() { fclose(outfile); };\n tiledb::common::ScopedExecutor onexit1(closefile);\n\n#ifdef _WIN32\n \/\/ need to be sure in\/out are in binay mode, windows default won't be!!!\n if ((-1 == _setmode(fileno(stdin), _O_BINARY)) ||\n (-1 == _setmode(fileno(stdout), _O_BINARY))) {\n fprintf(stderr, \"failure setting stdin\/stdout to binary mode!\");\n exit(-1);\n }\n#endif\n\n do {\n nread = fread(fbuf, 1, sizeof(fbuf), infile);\n if (nread) {\n inbuf->write(fbuf, nread);\n cntread += nread;\n }\n } while (nread == sizeof(fbuf));\n\n tiledb::sm::ConstBuffer const_inbuf(&*inbuf);\n \/\/ Ensure space in output buffer for worst case.\n if (!zipped_buf->prepend_buffer(inbuf->size()).ok()) {\n printf(\"output buffer allocation error!\\n\");\n exit(-3);\n }\n tiledb::sm::Buffer* out_buffer_ptr = zipped_buf->buffer_ptr(0);\n assert(out_buffer_ptr != nullptr);\n out_buffer_ptr->reset_offset();\n if (!tiledb::sm::GZip::compress(9, &const_inbuf, out_buffer_ptr).ok()) {\n printf(\"Error compressing data!\\n\");\n exit(-4);\n }\n std::cerr << \"sizes input \" << inbuf->size() << \", compressed \"\n << out_buffer_ptr->size() << std::endl;\n if (0) \/\/ leave available for future possible diagnostic need\n {\n \/\/ save compressed data to allow examination from filesystem\n auto outgzip = fopen(\"magic-mgc.tdbgzip\", \"wb\");\n if (!outgzip) {\n fprintf(stderr, \"Unable to create magic-mgc.tdbgzip!\\n\");\n exit(-21);\n }\n if (fwrite(out_buffer_ptr->data(0), 1, out_buffer_ptr->size(), outgzip) !=\n out_buffer_ptr->size()) {\n fprintf(stderr, \"write failure magic-mgc.tdbgzip!\\n\");\n exit(-22);\n }\n fclose(outgzip);\n }\n auto tdb_gzip_buf = make_shared<tiledb::sm::Buffer>(HERE());\n\n unsigned maxnperline = 128;\n auto addbytevals = [&](void* _pbytes, uint64_t nbytes) {\n uint8_t* pbytes = reinterpret_cast<uint8_t*>(_pbytes);\n static unsigned cntout = 0;\n for (auto i = 0u; i < nbytes; ++i) {\n fprintf(outfile, \"'\\\\x%02x',\", pbytes[i]);\n if (++cntout > maxnperline) {\n cntout = 0;\n fprintf(outfile, \"\\n\");\n }\n }\n };\n addbytevals(&cntread, sizeof(cntread));\n tdb_gzip_buf->write(&cntread, sizeof(cntread));\n uint64_t compressed_size = zipped_buf->size();\n addbytevals(&compressed_size, sizeof(compressed_size));\n tdb_gzip_buf->write(&compressed_size, sizeof(compressed_size));\n auto nremaining = zipped_buf->size();\n \/\/ vs19 complained...\n \/\/ A) could not find raw string literal terminator\n \/\/ for almost identical error, though not quite same cause, can see\n \/\/ https:\/\/developercommunity.visualstudio.com\/t\/bug-in-raw-string-implementation-converning-eof-02\/254730)\n \/\/ vs19 16.11.3 was in use with tiledb failed #include of raw literal file\n \/\/ B) that (all data as) one string was to large a string\n \/\/ C) many shorter strings expecting concatention were causing\n \/\/ compiler heap memory errors (100+GB)\n \/\/ D) caused warnings trying to do direct 0xXX numeric values\n \/\/ end result format is comma delimited '\\xXX' characters with periodic line\n \/\/ splits\n while (nremaining) {\n auto ntowrite = nremaining > seg_sz ? seg_sz : nremaining;\n \/\/ TBD: error from ->read()?\n if (!zipped_buf->read(fbuf, ntowrite).ok()) {\n printf(\"ERROR reading from compressed data.\\n\");\n exit(-7);\n }\n if (!tdb_gzip_buf->write(fbuf, ntowrite).ok()) {\n printf(\"ERROR writing compressed format buffer.\");\n exit(-11);\n }\n addbytevals(fbuf, ntowrite);\n nremaining -= ntowrite;\n }\n\n \/\/ brief sanity check that wrapper compression matches unwrapped compression\n shared_ptr<tiledb::sm::Buffer> out_gzipped_buf =\n make_shared<tiledb::sm::Buffer>(HERE());\n gzip_compress(out_gzipped_buf, inbuf->data(0), inbuf->size());\n if (out_gzipped_buf->size() != tdb_gzip_buf->size()) {\n printf(\n \"Error, compressed data sizes mismatch! %\" PRIu64 \", %\" PRIu64 \"u\\n\",\n out_gzipped_buf->size(),\n tdb_gzip_buf->size());\n exit(-13);\n }\n if (memcmp(\n out_gzipped_buf->data(0),\n tdb_gzip_buf->data(0),\n out_gzipped_buf->size()) \/\/ tdb_gzip_buf->size())\n ) {\n printf(\"Error, compressed data mismatch!\\n\");\n exit(-17);\n }\n\n shared_ptr<tiledb::sm::ByteVecValue> expanded_buffer =\n make_shared<tiledb::sm::ByteVecValue>(HERE());\n\n \/\/ brief sanity check the decompressed()d data matches original\n tdb_gzip_buf->set_offset(0);\n gzip_decompress(expanded_buffer, static_cast<uint8_t*>(tdb_gzip_buf->data()));\n if (expanded_buffer->size() != inbuf->size()) {\n fprintf(stderr, \"re-expanded size different from original size!\\n\");\n exit(-29);\n }\n if (memcmp(expanded_buffer->data(), inbuf->data(), inbuf->size())) {\n printf(\"Error uncompress data != original data!\\n\");\n exit(-21);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"run_submission.h\"\n#include <stdio.h>\n#include <string.h>\n\nconst char * safe_get(Table& t, const char* key, const char* defaultValue)\n{\n Table::const_iterator got = t.find(key);\n if (got == t.end())\n return defaultValue;\n return got->second.c_str();\n}\n\nvoid translate(Table& envT, Table& userT, DTable& userDT)\n{\n enum QueueType { UNKNOWN = -1, SLURM = 1, SGE, SLURM_TACC, PBS, LSF };\n QueueType queueType = UNKNOWN;\n\n \/\/ Pick type of queuing system.\n\n\n if (envT.count(\"SGE_ACCOUNT\"))\n queueType = SGE;\n else if (envT.count(\"SLURM_TACC_ACCOUNT\") || envT.count(\"SLURM_TACC_JOBNAME\"))\n queueType = SLURM_TACC;\n else if (envT.count(\"SBATCH_ACCOUNT\"))\n queueType = SLURM;\n else if (envT.count(\"PBS_JOBID\"))\n queueType = PBS;\n else if (envT.count(\"LSF_VERSION\"))\n queueType = LSF;\n\n \/\/ userDT[\"num_tasks\"] has a safe default value of 1 if not overridden by the run.\n userDT[\"num_cores\"] = userDT[\"num_tasks\"]; \n\n \/\/ Now fill in num_cores, num_nodes, account, job_id, queue, submit_host in userT from the environment\n if (queueType == SGE)\n {\n userT[\"account\"] = safe_get(envT, \"SGE_ACCOUNT\", \"unknown\");\n userT[\"job_id\"] = safe_get(envT, \"JOB_ID\", \"unknown\");\n userT[\"queue\"] = safe_get(envT, \"QUEUE\", \"unknown\");\n userT[\"submit_host\"] = \"unknown\";\n userDT[\"num_nodes\"] = strtod(safe_get(envT, \"NHOSTS\", \"1\"), (char **) NULL);\n }\n else if (queueType == SLURM_TACC || queueType == SLURM )\n {\n userT[\"job_id\"] = safe_get(envT, \"SLURM_JOB_ID\", \"unknown\");\n userT[\"queue\"] = safe_get(envT, \"SLURM_QUEUE\", \"unknown\");\n userT[\"submit_host\"] = safe_get(envT, \"SLURM_SUBMIT_HOST\", \"unknown\");\n userT[\"account\"] = safe_get(envT, \"SLURM_TACC_ACCOUNT\", \"unknown\");\n userDT[\"num_nodes\"] = strtod(safe_get(envT, \"SLURM_NNODES\", \"1\"), (char **) NULL);\n }\n else if (queueType == PBS)\n {\n std::string job_id = safe_get(envT, \"PBS_JOBID\", \"unknown\");\n std::size_t idx = job_id.find_first_not_of(\"0123456789\");\n userT[\"job_id\"] = job_id.substr(0,idx);\n userT[\"queue\"] = safe_get(envT, \"PBS_QUEUE\", \"unknown\");\n userT[\"submit_host\"] = safe_get(envT, \"PBS_O_HOST\", \"unknown\");\n userT[\"account\"] = safe_get(envT, \"PBS_ACCOUNT\", \"unknown\");\n userDT[\"num_nodes\"] = strtod(safe_get(envT, \"PBS_NUM_NODES\", \"1\"), (char **) NULL);;\n }\n else if (queueType == LSF)\n {\n \/\/ We must count the number of \"words\" in mcpuA.\n \/\/ We find the number of words by counting space blocks and add 1;\n \/\/ then divide by 2. then convert to a string.\n std::string mcpuA = safe_get(envT, \"LSB_MCPU_HOSTS\", \"a 1\");\n std::string::size_type idx;\n int count = 1;\n idx = 0;\n while (1)\n {\n idx = mcpuA.find(\" \",idx);\n if (idx == std::string::npos)\n break;\n count++;\n idx = mcpuA.find_first_not_of(\" \",idx+1);\n }\n count \/= 2;\n\n userT[\"job_id\"] = safe_get(envT, \"LSB_JOBID\", \"unknown\");\n userT[\"queue\"] = safe_get(envT, \"LSB_QUEUE\", \"unknown\");\n userT[\"submit_host\"] = safe_get(envT, \"LSB_EXEC_CLUSTER\", \"unknown\");\n userT[\"account\"] = \"unknown\";\n userDT[\"num_nodes\"] = (double) count;\n }\n else\n {\n userT[\"job_id\"] = \"unknown\";\n userT[\"queue\"] = \"unknown\";\n userT[\"submit_host\"] = \"unknown\";\n userT[\"account\"] = \"unknown\";\n userDT[\"num_nodes\"] = 1.0;\n }\n}\n<commit_msg>Support Torque job arrays where ID would be form of 123[1]<commit_after>#include \"run_submission.h\"\n#include <stdio.h>\n#include <string.h>\n\nconst char * safe_get(Table& t, const char* key, const char* defaultValue)\n{\n Table::const_iterator got = t.find(key);\n if (got == t.end())\n return defaultValue;\n return got->second.c_str();\n}\n\nvoid translate(Table& envT, Table& userT, DTable& userDT)\n{\n enum QueueType { UNKNOWN = -1, SLURM = 1, SGE, SLURM_TACC, PBS, LSF };\n QueueType queueType = UNKNOWN;\n\n \/\/ Pick type of queuing system.\n\n\n if (envT.count(\"SGE_ACCOUNT\"))\n queueType = SGE;\n else if (envT.count(\"SLURM_TACC_ACCOUNT\") || envT.count(\"SLURM_TACC_JOBNAME\"))\n queueType = SLURM_TACC;\n else if (envT.count(\"SBATCH_ACCOUNT\"))\n queueType = SLURM;\n else if (envT.count(\"PBS_JOBID\"))\n queueType = PBS;\n else if (envT.count(\"LSF_VERSION\"))\n queueType = LSF;\n\n \/\/ userDT[\"num_tasks\"] has a safe default value of 1 if not overridden by the run.\n userDT[\"num_cores\"] = userDT[\"num_tasks\"]; \n\n \/\/ Now fill in num_cores, num_nodes, account, job_id, queue, submit_host in userT from the environment\n if (queueType == SGE)\n {\n userT[\"account\"] = safe_get(envT, \"SGE_ACCOUNT\", \"unknown\");\n userT[\"job_id\"] = safe_get(envT, \"JOB_ID\", \"unknown\");\n userT[\"queue\"] = safe_get(envT, \"QUEUE\", \"unknown\");\n userT[\"submit_host\"] = \"unknown\";\n userDT[\"num_nodes\"] = strtod(safe_get(envT, \"NHOSTS\", \"1\"), (char **) NULL);\n }\n else if (queueType == SLURM_TACC || queueType == SLURM )\n {\n userT[\"job_id\"] = safe_get(envT, \"SLURM_JOB_ID\", \"unknown\");\n userT[\"queue\"] = safe_get(envT, \"SLURM_QUEUE\", \"unknown\");\n userT[\"submit_host\"] = safe_get(envT, \"SLURM_SUBMIT_HOST\", \"unknown\");\n userT[\"account\"] = safe_get(envT, \"SLURM_TACC_ACCOUNT\", \"unknown\");\n userDT[\"num_nodes\"] = strtod(safe_get(envT, \"SLURM_NNODES\", \"1\"), (char **) NULL);\n }\n else if (queueType == PBS)\n {\n std::string job_id = safe_get(envT, \"PBS_JOBID\", \"unknown\");\n std::size_t idx = job_id.find_first_not_of(\"0123456789[]\");\n userT[\"job_id\"] = job_id.substr(0,idx);\n userT[\"queue\"] = safe_get(envT, \"PBS_QUEUE\", \"unknown\");\n userT[\"submit_host\"] = safe_get(envT, \"PBS_O_HOST\", \"unknown\");\n userT[\"account\"] = safe_get(envT, \"PBS_ACCOUNT\", \"unknown\");\n userDT[\"num_nodes\"] = strtod(safe_get(envT, \"PBS_NUM_NODES\", \"1\"), (char **) NULL);;\n }\n else if (queueType == LSF)\n {\n \/\/ We must count the number of \"words\" in mcpuA.\n \/\/ We find the number of words by counting space blocks and add 1;\n \/\/ then divide by 2. then convert to a string.\n std::string mcpuA = safe_get(envT, \"LSB_MCPU_HOSTS\", \"a 1\");\n std::string::size_type idx;\n int count = 1;\n idx = 0;\n while (1)\n {\n idx = mcpuA.find(\" \",idx);\n if (idx == std::string::npos)\n break;\n count++;\n idx = mcpuA.find_first_not_of(\" \",idx+1);\n }\n count \/= 2;\n\n userT[\"job_id\"] = safe_get(envT, \"LSB_JOBID\", \"unknown\");\n userT[\"queue\"] = safe_get(envT, \"LSB_QUEUE\", \"unknown\");\n userT[\"submit_host\"] = safe_get(envT, \"LSB_EXEC_CLUSTER\", \"unknown\");\n userT[\"account\"] = \"unknown\";\n userDT[\"num_nodes\"] = (double) count;\n }\n else\n {\n userT[\"job_id\"] = \"unknown\";\n userT[\"queue\"] = \"unknown\";\n userT[\"submit_host\"] = \"unknown\";\n userT[\"account\"] = \"unknown\";\n userDT[\"num_nodes\"] = 1.0;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, Willow Garage, Inc.\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 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 * $Id$\n *\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <pcl\/point_types.h>\n#include <pcl\/features\/normal_3d.h>\n#include <pcl\/features\/integral_image_normal.h>\n\n#include <iostream>\n\nusing namespace pcl;\nusing namespace std;\n\ntypedef search::KdTree<PointXYZ>::Ptr KdTreePtr;\nPointCloud<PointXYZ> cloud;\nKdTreePtr tree;\n\nNormalEstimation<PointXYZ, Normal> n;\nIntegralImageNormalEstimation<PointXYZ, Normal> ne;\n\nTEST(PCL, IntegralImage)\n{\n const unsigned width = 640;\n const unsigned height = 480;\n const unsigned max_window_size = 11;\n IntegralImage2Dim<float,1> integral_image(true);\n \n \/\/ test for dense data with elementstride = 1\n float* data = new float[width * height];\n for(unsigned yIdx = 0; yIdx < height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width; ++xIdx)\n {\n data[width * yIdx + xIdx] = 1;\n }\n }\n integral_image.setInput (data, width, height, 1, width);\n \n for (unsigned window_width = 2; window_width < max_window_size; ++window_width)\n {\n for (unsigned window_height = 2; window_height < max_window_size; ++window_height)\n {\n for(unsigned yIdx = 0; yIdx < height - window_height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width - window_width; ++xIdx)\n {\n EXPECT_EQ (window_width * window_height, integral_image.getFirstOrderSum (xIdx, yIdx, window_width, window_height)[0]);\n }\n }\n } \n }\n delete[] data;\n\n \/\/now test with element-stride 2\n unsigned element_stride = 2;\n unsigned row_stride = width * element_stride; \n data = new float[row_stride * height];\n for(unsigned yIdx = 0; yIdx < height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < row_stride; xIdx += element_stride)\n {\n data[row_stride * yIdx + xIdx] = 1;\n data[row_stride * yIdx + xIdx + 1] = -1;\n }\n }\n integral_image.setInput (data, width, height, element_stride, row_stride);\n for (unsigned window_width = 1; window_width < max_window_size; ++window_width)\n {\n for (unsigned window_height = 1; window_height < max_window_size; ++window_height)\n {\n for(unsigned yIdx = 0; yIdx < height - window_height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width - window_width; ++xIdx)\n {\n EXPECT_EQ (window_width * window_height, integral_image.getFirstOrderSum (xIdx, yIdx, window_width, window_height)[0]);\n }\n }\n } \n }\n delete[] data;\n\n \/\/now test with odd element-stride 3 and modulo-uneven row_stride\n element_stride = 3;\n row_stride = width * element_stride + 1; \/\/ +1 to enforce a non-zero modulo\n data = new float[row_stride * height];\n for(unsigned yIdx = 0; yIdx < height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width; ++xIdx)\n {\n data[row_stride * yIdx + element_stride * xIdx] = 1;\n data[row_stride * yIdx + element_stride * xIdx + 1] = 2;\n data[row_stride * yIdx + element_stride * xIdx + 2] = xIdx;\n }\n }\n integral_image.setInput (data, width, height, element_stride, row_stride);\n for (unsigned window_width = 1; window_width < max_window_size; ++window_width)\n {\n for (unsigned window_height = 1; window_height < max_window_size; ++window_height)\n {\n for(unsigned yIdx = 0; yIdx < height - window_height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width - window_width; ++xIdx)\n {\n EXPECT_EQ (window_width * window_height, integral_image.getFirstOrderSum (xIdx, yIdx, window_width, window_height)[0]);\n EXPECT_EQ (window_width * window_height, integral_image.getSecondOrderSum (xIdx, yIdx, window_width, window_height)[0]);\n }\n }\n } \n }\n delete[] data;\n\n \/\/ now test multidimensional case with 3D but element_stride = 4 and row_stride non-dividable by element_stride\n IntegralImage2Dim<float, 3> integral_image3(true);\n element_stride = 4;\n row_stride = width * element_stride + 1;\n data = new float[row_stride * height];\n for(unsigned yIdx = 0; yIdx < height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width; ++xIdx)\n {\n data[row_stride * yIdx + xIdx * element_stride] = xIdx;\n data[row_stride * yIdx + xIdx * element_stride + 1] = yIdx;\n data[row_stride * yIdx + xIdx * element_stride + 2] = xIdx + yIdx;\n data[row_stride * yIdx + xIdx * element_stride + 3] = -1000;\n }\n }\n integral_image3.setInput (data, width, height, element_stride, row_stride);\n for (unsigned window_width = 1; window_width < max_window_size; ++window_width)\n {\n for (unsigned window_height = 1; window_height < max_window_size; ++window_height)\n {\n for(unsigned yIdx = 0; yIdx < height - window_height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width - window_width; ++xIdx)\n {\n IntegralImage2Dim<float, 3>::ElementType sum = integral_image3.getFirstOrderSum (xIdx, yIdx, window_width, window_height);\n\n EXPECT_EQ (window_height * window_width * (window_width + 2 * xIdx - 1), sum[0] * 2);\n EXPECT_EQ (window_width * window_height * (window_height + 2 * yIdx - 1), sum[1] * 2);\n EXPECT_EQ (window_width * window_height * (window_height + 2 * yIdx - 1) + window_height * window_width * (window_width + 2 * xIdx - 1), sum[2] * 2);\n\n IntegralImage2Dim<float, 3>::SecondOrderType sumSqr = integral_image3.getSecondOrderSum (xIdx, yIdx, window_width, window_height);\n \n IntegralImage2Dim<float, 3>::SecondOrderType ground_truth;\n ground_truth.setZero ();\n for (unsigned wy = yIdx; wy < yIdx + window_height; ++wy)\n {\n for (unsigned wx = xIdx; wx < xIdx + window_width; ++wx)\n {\n float* val = data + (wy * row_stride + wx * element_stride);\n \/\/ground_truth[0] += val[0] * val[0];\n ground_truth[1] += val[0] * val[1];\n ground_truth[2] += val[0] * val[2];\n \/\/ground_truth[3] += val[1] * val[1];\n ground_truth[4] += val[1] * val[2];\n ground_truth[5] += val[2] * val[2];\n }\n }\n\n \/\/EXPECT_EQ (ground_truth [0], sumSqr[0]);\n EXPECT_EQ (ground_truth [1], sumSqr[1]);\n EXPECT_EQ (ground_truth [2], sumSqr[2]);\n \/\/EXPECT_EQ (ground_truth [3], sumSqr[3]);\n EXPECT_EQ (ground_truth [4], sumSqr[4]);\n EXPECT_EQ (ground_truth [5], sumSqr[5]);\n\n int w = window_width + xIdx - 1;\n long result = w * (w + 1) * (2*w + 1) - xIdx * (xIdx - 1) * (2*xIdx - 1);\n\n EXPECT_EQ (window_height * result, sumSqr[0] * 6);\n\n int h = window_height + yIdx - 1;\n result = h * (h + 1) * (2*h + 1) - yIdx * (yIdx - 1) * (2*yIdx - 1);\n EXPECT_EQ (window_width * result, sumSqr[3] * 6);\n }\n }\n } \n }\n delete[] data;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST (PCL, NormalEstimation)\n{\n tree.reset (new search::KdTree<PointXYZ> (false));\n n.setSearchMethod (tree);\n n.setKSearch (10);\n\n n.setInputCloud (cloud.makeShared ());\n\n PointCloud<Normal> output;\n n.compute (output);\n\n EXPECT_EQ (output.points.size (), cloud.points.size ());\n EXPECT_EQ (output.width, cloud.width);\n EXPECT_EQ (output.height, cloud.height);\n\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n EXPECT_NEAR (fabs (output.points[i].normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (output.points[i].normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (output.points[i].normal_z), 1.0, 1e-2);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST (PCL, IINormalEstimation)\n{\n Normal normal;\n ne.setInputCloud (cloud.makeShared ());\n ne.setRectSize (2, 2);\n ne.computePointNormal (160, 120, normal);\n ne.setNormalEstimationMethod (ne.COVARIANCE_MATRIX);\n\n EXPECT_NEAR (fabs (normal.normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (normal.normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (normal.normal_z), 1.0, 1e-2);\n\n PointCloud<Normal> output;\n ne.compute (output);\n\n EXPECT_EQ (output.points.size (), cloud.points.size ());\n EXPECT_EQ (output.width, cloud.width);\n EXPECT_EQ (output.height, cloud.height);\n\n for (size_t v = 0; v < cloud.height; ++v)\n {\n for (size_t u = 0; u < cloud.width; ++u)\n {\n if (!pcl_isfinite(output (u, v).normal_x) && \n !pcl_isfinite(output (u, v).normal_y) && \n !pcl_isfinite(output (u, v).normal_z)) \n continue;\n\n EXPECT_NEAR (fabs (output (u, v).normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (output (u, v).normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (output (u, v).normal_z), 1.0, 1e-2);\n }\n }\n EXPECT_NEAR (fabs (output (160, 120).normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (output (160, 120).normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (output (160, 120).normal_z), 1.0, 1e-2);\n\n\n ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT);\n ne.compute (output);\n\n EXPECT_EQ (output.points.size (), cloud.points.size ());\n EXPECT_EQ (output.width, cloud.width);\n EXPECT_EQ (output.height, cloud.height);\n\n for (size_t v = 0; v < cloud.height; ++v)\n {\n for (size_t u = 0; u < cloud.width; ++u)\n {\n if (!pcl_isfinite(output (u, v).normal_x) && \n !pcl_isfinite(output (u, v).normal_y) && \n !pcl_isfinite(output (u, v).normal_z)) \n continue;\n\n EXPECT_NEAR (fabs (output (u, v).normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (output (u, v).normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (output (u, v).normal_z), 1.0, 1e-2);\n }\n }\n}\n\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n cloud.points.resize (320 * 240);\n cloud.width = 320;\n cloud.height = 240;\n cloud.is_dense = true;\n for (size_t v = 0; v < cloud.height; ++v)\n {\n for (size_t u = 0; u < cloud.width; ++u)\n {\n cloud (u, v).x = u;\n cloud (u, v).y = v;\n cloud (u, v).z = 10;\n }\n }\n\n testing::InitGoogleTest (&argc, argv);\n return (RUN_ALL_TESTS ());\n \n return 1;\n}\n\/* ]--- *\/\n\n<commit_msg>fixing the II unit test<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, Willow Garage, Inc.\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 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 * $Id$\n *\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <pcl\/point_types.h>\n#include <pcl\/features\/normal_3d.h>\n#include <pcl\/features\/integral_image_normal.h>\n\n#include <iostream>\n\nusing namespace pcl;\nusing namespace std;\n\ntypedef search::KdTree<PointXYZ>::Ptr KdTreePtr;\nPointCloud<PointXYZ> cloud;\nKdTreePtr tree;\n\nNormalEstimation<PointXYZ, Normal> n;\nIntegralImageNormalEstimation<PointXYZ, Normal> ne;\n\nTEST(PCL, IntegralImage)\n{\n const unsigned width = 640;\n const unsigned height = 480;\n const unsigned max_window_size = 11;\n IntegralImage2D<float,1> integral_image(true);\n \n \/\/ test for dense data with elementstride = 1\n float* data = new float[width * height];\n for(unsigned yIdx = 0; yIdx < height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width; ++xIdx)\n {\n data[width * yIdx + xIdx] = 1;\n }\n }\n integral_image.setInput (data, width, height, 1, width);\n \n for (unsigned window_width = 2; window_width < max_window_size; ++window_width)\n {\n for (unsigned window_height = 2; window_height < max_window_size; ++window_height)\n {\n for(unsigned yIdx = 0; yIdx < height - window_height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width - window_width; ++xIdx)\n {\n EXPECT_EQ (window_width * window_height, integral_image.getFirstOrderSum (xIdx, yIdx, window_width, window_height));\n }\n }\n } \n }\n delete[] data;\n\n \/\/now test with element-stride 2\n unsigned element_stride = 2;\n unsigned row_stride = width * element_stride; \n data = new float[row_stride * height];\n for(unsigned yIdx = 0; yIdx < height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < row_stride; xIdx += element_stride)\n {\n data[row_stride * yIdx + xIdx] = 1;\n data[row_stride * yIdx + xIdx + 1] = -1;\n }\n }\n integral_image.setInput (data, width, height, element_stride, row_stride);\n for (unsigned window_width = 1; window_width < max_window_size; ++window_width)\n {\n for (unsigned window_height = 1; window_height < max_window_size; ++window_height)\n {\n for(unsigned yIdx = 0; yIdx < height - window_height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width - window_width; ++xIdx)\n {\n EXPECT_EQ (window_width * window_height, integral_image.getFirstOrderSum (xIdx, yIdx, window_width, window_height));\n }\n }\n } \n }\n delete[] data;\n\n \/\/now test with odd element-stride 3 and modulo-uneven row_stride\n element_stride = 3;\n row_stride = width * element_stride + 1; \/\/ +1 to enforce a non-zero modulo\n data = new float[row_stride * height];\n for(unsigned yIdx = 0; yIdx < height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width; ++xIdx)\n {\n data[row_stride * yIdx + element_stride * xIdx] = 1;\n data[row_stride * yIdx + element_stride * xIdx + 1] = 2;\n data[row_stride * yIdx + element_stride * xIdx + 2] = xIdx;\n }\n }\n integral_image.setInput (data, width, height, element_stride, row_stride);\n for (unsigned window_width = 1; window_width < max_window_size; ++window_width)\n {\n for (unsigned window_height = 1; window_height < max_window_size; ++window_height)\n {\n for(unsigned yIdx = 0; yIdx < height - window_height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width - window_width; ++xIdx)\n {\n EXPECT_EQ (window_width * window_height, integral_image.getFirstOrderSum (xIdx, yIdx, window_width, window_height));\n EXPECT_EQ (window_width * window_height, integral_image.getSecondOrderSum (xIdx, yIdx, window_width, window_height));\n }\n }\n } \n }\n delete[] data;\n\n \/\/ now test multidimensional case with 3D but element_stride = 4 and row_stride non-dividable by element_stride\n IntegralImage2D<float, 3> integral_image3(true);\n element_stride = 4;\n row_stride = width * element_stride + 1;\n data = new float[row_stride * height];\n for(unsigned yIdx = 0; yIdx < height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width; ++xIdx)\n {\n data[row_stride * yIdx + xIdx * element_stride] = xIdx;\n data[row_stride * yIdx + xIdx * element_stride + 1] = yIdx;\n data[row_stride * yIdx + xIdx * element_stride + 2] = xIdx + yIdx;\n data[row_stride * yIdx + xIdx * element_stride + 3] = -1000;\n }\n }\n integral_image3.setInput (data, width, height, element_stride, row_stride);\n for (unsigned window_width = 1; window_width < max_window_size; ++window_width)\n {\n for (unsigned window_height = 1; window_height < max_window_size; ++window_height)\n {\n for(unsigned yIdx = 0; yIdx < height - window_height; ++yIdx)\n {\n for(unsigned xIdx = 0; xIdx < width - window_width; ++xIdx)\n {\n IntegralImage2D<float, 3>::ElementType sum = integral_image3.getFirstOrderSum (xIdx, yIdx, window_width, window_height);\n\n EXPECT_EQ (window_height * window_width * (window_width + 2 * xIdx - 1), sum[0] * 2);\n EXPECT_EQ (window_width * window_height * (window_height + 2 * yIdx - 1), sum[1] * 2);\n EXPECT_EQ (window_width * window_height * (window_height + 2 * yIdx - 1) + window_height * window_width * (window_width + 2 * xIdx - 1), sum[2] * 2);\n\n IntegralImage2D<float, 3>::SecondOrderType sumSqr = integral_image3.getSecondOrderSum (xIdx, yIdx, window_width, window_height);\n \n IntegralImage2D<float, 3>::SecondOrderType ground_truth;\n ground_truth.setZero ();\n for (unsigned wy = yIdx; wy < yIdx + window_height; ++wy)\n {\n for (unsigned wx = xIdx; wx < xIdx + window_width; ++wx)\n {\n float* val = data + (wy * row_stride + wx * element_stride);\n \/\/ground_truth[0] += val[0] * val[0];\n ground_truth[1] += val[0] * val[1];\n ground_truth[2] += val[0] * val[2];\n \/\/ground_truth[3] += val[1] * val[1];\n ground_truth[4] += val[1] * val[2];\n ground_truth[5] += val[2] * val[2];\n }\n }\n\n \/\/EXPECT_EQ (ground_truth [0], sumSqr[0]);\n EXPECT_EQ (ground_truth [1], sumSqr[1]);\n EXPECT_EQ (ground_truth [2], sumSqr[2]);\n \/\/EXPECT_EQ (ground_truth [3], sumSqr[3]);\n EXPECT_EQ (ground_truth [4], sumSqr[4]);\n EXPECT_EQ (ground_truth [5], sumSqr[5]);\n\n int w = window_width + xIdx - 1;\n long result = w * (w + 1) * (2*w + 1) - xIdx * (xIdx - 1) * (2*xIdx - 1);\n\n EXPECT_EQ (window_height * result, sumSqr[0] * 6);\n\n int h = window_height + yIdx - 1;\n result = h * (h + 1) * (2*h + 1) - yIdx * (yIdx - 1) * (2*yIdx - 1);\n EXPECT_EQ (window_width * result, sumSqr[3] * 6);\n }\n }\n } \n }\n delete[] data;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST (PCL, NormalEstimation)\n{\n tree.reset (new search::KdTree<PointXYZ> (false));\n n.setSearchMethod (tree);\n n.setKSearch (10);\n\n n.setInputCloud (cloud.makeShared ());\n\n PointCloud<Normal> output;\n n.compute (output);\n\n EXPECT_EQ (output.points.size (), cloud.points.size ());\n EXPECT_EQ (output.width, cloud.width);\n EXPECT_EQ (output.height, cloud.height);\n\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n EXPECT_NEAR (fabs (output.points[i].normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (output.points[i].normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (output.points[i].normal_z), 1.0, 1e-2);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST (PCL, IINormalEstimation)\n{\n Normal normal;\n ne.setInputCloud (cloud.makeShared ());\n ne.setRectSize (2, 2);\n ne.computePointNormal (160, 120, normal);\n ne.setNormalEstimationMethod (ne.COVARIANCE_MATRIX);\n\n EXPECT_NEAR (fabs (normal.normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (normal.normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (normal.normal_z), 1.0, 1e-2);\n\n PointCloud<Normal> output;\n ne.compute (output);\n\n EXPECT_EQ (output.points.size (), cloud.points.size ());\n EXPECT_EQ (output.width, cloud.width);\n EXPECT_EQ (output.height, cloud.height);\n\n for (size_t v = 0; v < cloud.height; ++v)\n {\n for (size_t u = 0; u < cloud.width; ++u)\n {\n if (!pcl_isfinite(output (u, v).normal_x) && \n !pcl_isfinite(output (u, v).normal_y) && \n !pcl_isfinite(output (u, v).normal_z)) \n continue;\n\n EXPECT_NEAR (fabs (output (u, v).normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (output (u, v).normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (output (u, v).normal_z), 1.0, 1e-2);\n }\n }\n EXPECT_NEAR (fabs (output (160, 120).normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (output (160, 120).normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (output (160, 120).normal_z), 1.0, 1e-2);\n\n\n ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT);\n ne.compute (output);\n\n EXPECT_EQ (output.points.size (), cloud.points.size ());\n EXPECT_EQ (output.width, cloud.width);\n EXPECT_EQ (output.height, cloud.height);\n\n for (size_t v = 0; v < cloud.height; ++v)\n {\n for (size_t u = 0; u < cloud.width; ++u)\n {\n if (!pcl_isfinite(output (u, v).normal_x) && \n !pcl_isfinite(output (u, v).normal_y) && \n !pcl_isfinite(output (u, v).normal_z)) \n continue;\n\n EXPECT_NEAR (fabs (output (u, v).normal_x), 0, 1e-2);\n EXPECT_NEAR (fabs (output (u, v).normal_y), 0, 1e-2);\n EXPECT_NEAR (fabs (output (u, v).normal_z), 1.0, 1e-2);\n }\n }\n}\n\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n cloud.points.resize (320 * 240);\n cloud.width = 320;\n cloud.height = 240;\n cloud.is_dense = true;\n for (size_t v = 0; v < cloud.height; ++v)\n {\n for (size_t u = 0; u < cloud.width; ++u)\n {\n cloud (u, v).x = u;\n cloud (u, v).y = v;\n cloud (u, v).z = 10;\n }\n }\n\n testing::InitGoogleTest (&argc, argv);\n return (RUN_ALL_TESTS ());\n \n return 1;\n}\n\/* ]--- *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 Gigatribe\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#include \"CurlProgress.h\"\n#include \"..\/..\/rest\/HttpErrors.h\"\n\n#include <curl_easy.h>\n#include <mutex>\n#include <curl_exception.h>\n#include <chrono>\n#include <thread>\n\nusing namespace std::chrono;\n\nnamespace giga\n{\nnamespace details\n{\n\nCurlProgress::CurlProgress (pplx::cancellation_token token) :\n _mut{}, _item{0ul, 0ul, 0ul, 0ul}, _cancelToken{token}, _pause{false}, _isPaused{false}, _curl{nullptr},\n _limitRate{0ul}, _currentLimitRate{0ul}, _rateTime{}, _rateBytes{0ul}, _bucket{0ul}, _upPostion{0ul}\n{\n}\n\nCurlProgress::CurlProgress (const CurlProgress& other) :\n _mut{},\n _item{other._item.dltotal, other._item.dlnow, other._item.ultotal, other._item.ulnow},\n _cancelToken{other._cancelToken},\n _pause{other._pause},\n _isPaused{other._isPaused},\n _curl{other._curl},\n _limitRate{other._limitRate},\n _currentLimitRate{other._currentLimitRate},\n _rateTime{other._rateTime},\n _rateBytes{other._rateBytes},\n _bucket{other._bucket},\n _upPostion{other._upPostion}\n{\n}\n\nCurlProgress::Item\nCurlProgress::data () const\n{\n std::lock_guard<std::mutex> l(_mut);\n return _item;\n}\n\nvoid\nCurlProgress::setPause (bool pause)\n{\n std::lock_guard<std::mutex> l(_mut);\n _pause = pause;\n}\n\nvoid\nCurlProgress::setUploadPosition (uint64_t pos)\n{\n std::lock_guard<std::mutex> l(_mut);\n _upPostion = pos;\n}\n\nvoid\nCurlProgress::setLimitRate (uint64_t rate)\n{\n std::lock_guard<std::mutex> l(_mut);\n _limitRate = rate;\n}\n\nvoid\nCurlProgress::setCurl (curl::curl_easy& curl)\n{\n std::lock_guard<std::mutex> l(_mut);\n _curl = &curl;\n}\n\nbool\nCurlProgress::isPaused () const\n{\n std::lock_guard<std::mutex> l(_mut);\n return _pause;\n}\n\nint\nCurlProgress::onCallback (curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) noexcept\n{\n try {\n uint64_t limitRate = 0;\n {\n std::lock_guard<std::mutex> l(_mut);\n limitRate = _limitRate;\n\n _item.dltotal = static_cast<uint64_t>(dltotal);\n _item.dlnow = static_cast<uint64_t>(dlnow);\n _item.ultotal = static_cast<uint64_t>(ultotal + _upPostion);\n _item.ulnow = static_cast<uint64_t>(ulnow + _upPostion);\n\n if (_pause != _isPaused && _curl != nullptr)\n {\n _curl->pause(_pause ? CURLPAUSE_ALL : CURLPAUSE_CONT);\n _isPaused = _pause;\n }\n if (_cancelToken.is_canceled())\n {\n return CURLE_ABORTED_BY_CALLBACK;\n }\n }\n\n \/\/ Do the limit rate outside of the mutex locked zone\n \/\/ because there is waiting here.\n auto transfered = static_cast<uint64_t>(dlnow + ulnow);\n if (limitRate != _currentLimitRate || transfered == 0ul)\n {\n _rateBytes = transfered;\n _currentLimitRate = limitRate;\n _rateTime = high_resolution_clock::now();\n _bucket = _limitRate; \/\/ give it 1 sec\n }\n if (limitRate > 0 && transfered > 0)\n {\n auto now = high_resolution_clock::now();\n do\n {\n \/\/ calculate duration\n duration<float> duration = now - _rateTime;\n auto elapsedMs = duration_cast<milliseconds>(duration).count();\n _rateTime = now;\n\n \/\/ add bytes in the bucket\n _bucket += std::max(static_cast<uint64_t>((elapsedMs * _limitRate) \/ 1000), static_cast<uint64_t>(1ul));\n\n \/\/ take bytes in the bucket\n auto take = std::min(_bucket, transfered - _rateBytes);\n _bucket -= take;\n _rateBytes += take;\n\n \/\/ wait for new bytes.\n if (_bucket == 0)\n {\n std::this_thread::sleep_for(milliseconds(500));\n now = high_resolution_clock::now();\n }\n } while (_bucket == 0 && (dlnow - _rateBytes) > 0);\n }\n } catch (...) {\n return CURLE_OBSOLETE40;\n }\n return CURLE_OK;\n}\n\n} \/* namespace details *\/\n} \/* namespace giga *\/\n<commit_msg>fix the limitRate feature<commit_after>\/*\n * Copyright 2016 Gigatribe\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#include \"CurlProgress.h\"\n#include \"..\/..\/rest\/HttpErrors.h\"\n\n#include <curl_easy.h>\n#include <mutex>\n#include <curl_exception.h>\n#include <chrono>\n#include <thread>\n\nusing namespace std::chrono;\n\nnamespace giga\n{\nnamespace details\n{\n\nCurlProgress::CurlProgress (pplx::cancellation_token token) :\n _mut{}, _item{0ul, 0ul, 0ul, 0ul}, _cancelToken{token}, _pause{false}, _isPaused{false}, _curl{nullptr},\n _limitRate{0ul}, _currentLimitRate{0ul}, _rateTime{}, _rateBytes{0ul}, _bucket{0ul}, _upPostion{0ul}\n{\n}\n\nCurlProgress::CurlProgress (const CurlProgress& other) :\n _mut{},\n _item{other._item.dltotal, other._item.dlnow, other._item.ultotal, other._item.ulnow},\n _cancelToken{other._cancelToken},\n _pause{other._pause},\n _isPaused{other._isPaused},\n _curl{other._curl},\n _limitRate{other._limitRate},\n _currentLimitRate{other._currentLimitRate},\n _rateTime{other._rateTime},\n _rateBytes{other._rateBytes},\n _bucket{other._bucket},\n _upPostion{other._upPostion}\n{\n}\n\nCurlProgress::Item\nCurlProgress::data () const\n{\n std::lock_guard<std::mutex> l(_mut);\n return _item;\n}\n\nvoid\nCurlProgress::setPause (bool pause)\n{\n std::lock_guard<std::mutex> l(_mut);\n _pause = pause;\n}\n\nvoid\nCurlProgress::setUploadPosition (uint64_t pos)\n{\n std::lock_guard<std::mutex> l(_mut);\n _upPostion = pos;\n}\n\nvoid\nCurlProgress::setLimitRate (uint64_t rate)\n{\n std::lock_guard<std::mutex> l(_mut);\n _limitRate = rate;\n}\n\nvoid\nCurlProgress::setCurl (curl::curl_easy& curl)\n{\n std::lock_guard<std::mutex> l(_mut);\n _curl = &curl;\n}\n\nbool\nCurlProgress::isPaused () const\n{\n std::lock_guard<std::mutex> l(_mut);\n return _pause;\n}\n\nint\nCurlProgress::onCallback (curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) noexcept\n{\n try {\n uint64_t limitRate = 0;\n {\n std::lock_guard<std::mutex> l(_mut);\n limitRate = _limitRate;\n\n _item.dltotal = static_cast<uint64_t>(dltotal);\n _item.dlnow = static_cast<uint64_t>(dlnow);\n _item.ultotal = static_cast<uint64_t>(ultotal + _upPostion);\n _item.ulnow = static_cast<uint64_t>(ulnow + _upPostion);\n\n if (_pause != _isPaused && _curl != nullptr)\n {\n _curl->pause(_pause ? CURLPAUSE_ALL : CURLPAUSE_CONT);\n _isPaused = _pause;\n }\n if (_cancelToken.is_canceled())\n {\n return CURLE_ABORTED_BY_CALLBACK;\n }\n }\n\n \/\/ Do the limit rate outside of the mutex locked zone\n \/\/ because there is waiting here.\n auto transfered = static_cast<uint64_t>(dlnow + ulnow);\n if (limitRate != _currentLimitRate || transfered == 0ul)\n {\n _rateBytes = transfered;\n _currentLimitRate = limitRate;\n _rateTime = high_resolution_clock::now();\n _bucket = _limitRate; \/\/ give it 1 sec\n }\n if (limitRate > 0 && transfered > 0)\n {\n auto now = high_resolution_clock::now();\n do\n {\n \/\/ calculate duration\n duration<float> duration = now - _rateTime;\n auto elapsedMs = duration_cast<milliseconds>(duration).count();\n _rateTime = now;\n\n \/\/ add bytes in the bucket\n _bucket += std::max(static_cast<uint64_t>((elapsedMs * limitRate) \/ 1000), static_cast<uint64_t>(1ul));\n\n \/\/ take bytes in the bucket\n auto take = std::min(_bucket, transfered - _rateBytes);\n _bucket -= take;\n _rateBytes += take;\n\n \/\/ wait for new bytes.\n if (_bucket == 0)\n {\n std::this_thread::sleep_for(milliseconds(500));\n now = high_resolution_clock::now();\n }\n } while (_bucket == 0 && (dlnow - _rateBytes) > 0);\n }\n } catch (...) {\n return CURLE_OBSOLETE40;\n }\n return CURLE_OK;\n}\n\n} \/* namespace details *\/\n} \/* namespace giga *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Add a TODO comment to describe when we can remove the const_cast for the NSS function SGN_Update.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>WaE: type name first seen using 'class' now seen using 'struct'<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011, 2012 Esrille Inc.\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#include <GL\/freeglut.h>\n\n#include \"WindowImp.h\"\n#include \"Test.util.h\"\n#include \"http\/HTTPConnection.h\"\n\nusing namespace org::w3c::dom::bootstrap;\nusing namespace org::w3c::dom;\n\nextern html::Window window;\n\nvoid reshape(int w, int h)\n{\n glViewport(0, 0, w, h);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0, w, h, 0, -1000.0, 1.0);\n\n glMatrixMode(GL_TEXTURE);\n glLoadIdentity();\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n}\n\nvoid display()\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->render();\n glutSwapBuffers(); \/\/ This would block until the sync happens\n}\n\nunsigned getCharKeyCode(int key)\n{\n \/\/ US Qwerty\n static unsigned map[] = {\n 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 12, 13, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 27, 0, 0, 0, 0,\n 32, 49 \/* ! *\/, 222 \/* \" *\/, 51 \/* # *\/, 52 \/* $ *\/, 53 \/* % *\/, 55 \/* & *\/, 222 \/* ' *\/,\n 57 \/* ( *\/, 48 \/* ) *\/, 56 \/* * *\/, 187 \/* + *\/, 188 \/* , *\/, 189 \/* - *\/, 190 \/* . *\/, 191 \/* \/ *\/,\n 48 \/* 0 *\/, 49 \/* 1 *\/, 50 \/* 2 *\/, 51 \/* 3 *\/, 52 \/* 4 *\/, 53 \/* 5 *\/, 54 \/* 6 *\/, 55 \/* 7 *\/,\n 56 \/* 8 *\/, 57 \/* 9 *\/, 186 \/* : *\/, 186 \/* ; *\/, 188 \/* < *\/, 187 \/* = *\/, 190 \/* > *\/, 191 \/* ? *\/,\n 50 \/* @ *\/, 65 \/* A *\/, 66 \/* B *\/, 67 \/* C *\/, 68 \/* D *\/, 69 \/* E *\/, 70 \/* F *\/, 71 \/* G *\/,\n 72 \/* H *\/, 73 \/* I *\/, 74 \/* J *\/, 75 \/* K *\/, 76 \/* L *\/, 77 \/* M *\/, 78 \/* N *\/, 79 \/* O *\/,\n 80 \/* P *\/, 81 \/* Q *\/, 82 \/* R *\/, 83 \/* S *\/, 84 \/* T *\/, 85 \/* U *\/, 86 \/* V *\/, 87 \/* W *\/,\n 88 \/* X *\/, 89 \/* Y *\/, 90 \/* Z *\/, 219 \/* [ *\/, 220 \/* \\ *\/, 221 \/* ] *\/, 54 \/* ^ *\/, 189 \/* _ *\/,\n 192 \/* ` *\/, 65 \/* a *\/, 66 \/* b *\/, 67 \/* c *\/, 68 \/* d *\/, 69 \/* e *\/, 70 \/* f *\/, 71 \/* g *\/,\n 72 \/* h *\/, 73 \/* i *\/, 74 \/* j *\/, 75 \/* k *\/, 76 \/* l *\/, 77 \/* m *\/, 78 \/* n *\/, 79 \/* o *\/,\n 80 \/* p *\/, 81 \/* q *\/, 82 \/* r *\/, 83 \/* s *\/, 84 \/* t *\/, 85 \/* u *\/, 86 \/* v *\/, 87 \/* w *\/,\n 88 \/* x *\/, 89 \/* y *\/, 90 \/* z *\/, 219 \/* { *\/, 220 \/* | *\/, 221 \/* } *\/, 192 \/* ~ *\/, 46 \/* DEL *\/\n };\n static_assert(sizeof map \/sizeof map[0] == 128, \"invalid map\");\n return (0 <= key && key <= 127) ? map[key] : 0;\n}\n\nvoid keyboard(unsigned char key, int x, int y)\n{\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->keydown(key, getCharKeyCode(key), glutGetModifiers());\n}\n\nvoid keyboardUp(unsigned char key, int x, int y)\n{\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->keyup(key, getCharKeyCode(key), glutGetModifiers());\n}\n\nunsigned getSpecialKeyCode(int key)\n{\n switch (key) {\n case GLUT_KEY_F1:\n return 112;\n case GLUT_KEY_F2:\n return 113;\n case GLUT_KEY_F3:\n return 114;\n case GLUT_KEY_F4:\n return 115;\n case GLUT_KEY_F5:\n return 116;\n case GLUT_KEY_F6:\n return 117;\n case GLUT_KEY_F7:\n return 118;\n case GLUT_KEY_F8:\n return 119;\n case GLUT_KEY_F9:\n return 120;\n case GLUT_KEY_F10:\n return 121;\n case GLUT_KEY_F11:\n return 122;\n case GLUT_KEY_F12:\n return 123;\n case GLUT_KEY_LEFT:\n return 37;\n case GLUT_KEY_UP:\n return 38;\n case GLUT_KEY_RIGHT:\n return 39;\n case GLUT_KEY_DOWN:\n return 40;\n case GLUT_KEY_PAGE_UP:\n return 33;\n case GLUT_KEY_PAGE_DOWN:\n return 34;\n case GLUT_KEY_HOME:\n return 36;\n case GLUT_KEY_END:\n return 35;\n case GLUT_KEY_INSERT:\n return 45;\n case 109: \/\/ Num Lock\n return 144;\n default:\n return 0;\n }\n}\n\nvoid special(int key, int x, int y)\n{\n unsigned keycode = getSpecialKeyCode(key);\n if (keycode) {\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->keydown(0, keycode, glutGetModifiers());\n }\n}\n\nvoid specialUp(int key, int x, int y)\n{\n unsigned keycode = getSpecialKeyCode(key);\n if (keycode) {\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->keyup(0, keycode, glutGetModifiers());\n }\n}\n\nvoid mouse(int button, int state, int x, int y)\n{\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->mouse(button, state, x, y, glutGetModifiers());\n}\n\nvoid mouseMove(int x, int y)\n{\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->mouseMove(x, y, glutGetModifiers());\n}\n\nvoid timer(int value)\n{\n HttpConnectionManager::getIOService().poll();\n if (WindowImp* imp = static_cast<WindowImp*>(window.self())) {\n if (imp->poll())\n glutPostRedisplay();\n }\n glutTimerFunc(50, timer, 0);\n \/\/ TODO: do GC here or maybe in the idle proc\n}\n\nvoid init(int* argc, char* argv[])\n{\n glutInit(argc, argv);\n glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);\n glutInitWindowSize(816, 1056);\n glutCreateWindow(argv[0]);\n glutReshapeFunc(reshape);\n glutDisplayFunc(display);\n glClearColor(1.0, 1.0, 1.0, 1.0);\n glEnable(GL_TEXTURE_2D);\n glDepthFunc(GL_LEQUAL);\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_ALPHA_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glutKeyboardFunc(keyboard);\n glutKeyboardUpFunc(keyboardUp);\n glutSpecialFunc(special);\n glutSpecialUpFunc(specialUp);\n glutMouseFunc(mouse);\n glutMotionFunc(mouseMove);\n glutPassiveMotionFunc(mouseMove);\n glutTimerFunc(50, timer, 0);\n glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);\n}\n<commit_msg>(keyboard, keyboardUp) : Fix bugs.<commit_after>\/*\n * Copyright 2011, 2012 Esrille Inc.\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#include <GL\/freeglut.h>\n\n#include \"WindowImp.h\"\n#include \"Test.util.h\"\n#include \"http\/HTTPConnection.h\"\n\nusing namespace org::w3c::dom::bootstrap;\nusing namespace org::w3c::dom;\n\nextern html::Window window;\n\nvoid reshape(int w, int h)\n{\n glViewport(0, 0, w, h);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0, w, h, 0, -1000.0, 1.0);\n\n glMatrixMode(GL_TEXTURE);\n glLoadIdentity();\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n}\n\nvoid display()\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->render();\n glutSwapBuffers(); \/\/ This would block until the sync happens\n}\n\nunsigned getCharKeyCode(int key)\n{\n \/\/ US Qwerty\n static unsigned map[] = {\n 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 12, 13, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 27, 0, 0, 0, 0,\n 32, 49 \/* ! *\/, 222 \/* \" *\/, 51 \/* # *\/, 52 \/* $ *\/, 53 \/* % *\/, 55 \/* & *\/, 222 \/* ' *\/,\n 57 \/* ( *\/, 48 \/* ) *\/, 56 \/* * *\/, 187 \/* + *\/, 188 \/* , *\/, 189 \/* - *\/, 190 \/* . *\/, 191 \/* \/ *\/,\n 48 \/* 0 *\/, 49 \/* 1 *\/, 50 \/* 2 *\/, 51 \/* 3 *\/, 52 \/* 4 *\/, 53 \/* 5 *\/, 54 \/* 6 *\/, 55 \/* 7 *\/,\n 56 \/* 8 *\/, 57 \/* 9 *\/, 186 \/* : *\/, 186 \/* ; *\/, 188 \/* < *\/, 187 \/* = *\/, 190 \/* > *\/, 191 \/* ? *\/,\n 50 \/* @ *\/, 65 \/* A *\/, 66 \/* B *\/, 67 \/* C *\/, 68 \/* D *\/, 69 \/* E *\/, 70 \/* F *\/, 71 \/* G *\/,\n 72 \/* H *\/, 73 \/* I *\/, 74 \/* J *\/, 75 \/* K *\/, 76 \/* L *\/, 77 \/* M *\/, 78 \/* N *\/, 79 \/* O *\/,\n 80 \/* P *\/, 81 \/* Q *\/, 82 \/* R *\/, 83 \/* S *\/, 84 \/* T *\/, 85 \/* U *\/, 86 \/* V *\/, 87 \/* W *\/,\n 88 \/* X *\/, 89 \/* Y *\/, 90 \/* Z *\/, 219 \/* [ *\/, 220 \/* \\ *\/, 221 \/* ] *\/, 54 \/* ^ *\/, 189 \/* _ *\/,\n 192 \/* ` *\/, 65 \/* a *\/, 66 \/* b *\/, 67 \/* c *\/, 68 \/* d *\/, 69 \/* e *\/, 70 \/* f *\/, 71 \/* g *\/,\n 72 \/* h *\/, 73 \/* i *\/, 74 \/* j *\/, 75 \/* k *\/, 76 \/* l *\/, 77 \/* m *\/, 78 \/* n *\/, 79 \/* o *\/,\n 80 \/* p *\/, 81 \/* q *\/, 82 \/* r *\/, 83 \/* s *\/, 84 \/* t *\/, 85 \/* u *\/, 86 \/* v *\/, 87 \/* w *\/,\n 88 \/* x *\/, 89 \/* y *\/, 90 \/* z *\/, 219 \/* { *\/, 220 \/* | *\/, 221 \/* } *\/, 192 \/* ~ *\/, 46 \/* DEL *\/\n };\n static_assert(sizeof map \/sizeof map[0] == 128, \"invalid map\");\n return (0 <= key && key <= 127) ? map[key] : 0;\n}\n\nvoid keyboard(unsigned char key, int x, int y)\n{\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->keydown(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());\n}\n\nvoid keyboardUp(unsigned char key, int x, int y)\n{\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->keyup(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());\n}\n\nunsigned getSpecialKeyCode(int key)\n{\n switch (key) {\n case GLUT_KEY_F1:\n return 112;\n case GLUT_KEY_F2:\n return 113;\n case GLUT_KEY_F3:\n return 114;\n case GLUT_KEY_F4:\n return 115;\n case GLUT_KEY_F5:\n return 116;\n case GLUT_KEY_F6:\n return 117;\n case GLUT_KEY_F7:\n return 118;\n case GLUT_KEY_F8:\n return 119;\n case GLUT_KEY_F9:\n return 120;\n case GLUT_KEY_F10:\n return 121;\n case GLUT_KEY_F11:\n return 122;\n case GLUT_KEY_F12:\n return 123;\n case GLUT_KEY_LEFT:\n return 37;\n case GLUT_KEY_UP:\n return 38;\n case GLUT_KEY_RIGHT:\n return 39;\n case GLUT_KEY_DOWN:\n return 40;\n case GLUT_KEY_PAGE_UP:\n return 33;\n case GLUT_KEY_PAGE_DOWN:\n return 34;\n case GLUT_KEY_HOME:\n return 36;\n case GLUT_KEY_END:\n return 35;\n case GLUT_KEY_INSERT:\n return 45;\n case 109: \/\/ Num Lock\n return 144;\n default:\n return 0;\n }\n}\n\nvoid special(int key, int x, int y)\n{\n unsigned keycode = getSpecialKeyCode(key);\n if (keycode) {\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->keydown(0, keycode, glutGetModifiers());\n }\n}\n\nvoid specialUp(int key, int x, int y)\n{\n unsigned keycode = getSpecialKeyCode(key);\n if (keycode) {\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->keyup(0, keycode, glutGetModifiers());\n }\n}\n\nvoid mouse(int button, int state, int x, int y)\n{\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->mouse(button, state, x, y, glutGetModifiers());\n}\n\nvoid mouseMove(int x, int y)\n{\n if (WindowImp* imp = static_cast<WindowImp*>(window.self()))\n imp->mouseMove(x, y, glutGetModifiers());\n}\n\nvoid timer(int value)\n{\n HttpConnectionManager::getIOService().poll();\n if (WindowImp* imp = static_cast<WindowImp*>(window.self())) {\n if (imp->poll())\n glutPostRedisplay();\n }\n glutTimerFunc(50, timer, 0);\n \/\/ TODO: do GC here or maybe in the idle proc\n}\n\nvoid init(int* argc, char* argv[])\n{\n glutInit(argc, argv);\n glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);\n glutInitWindowSize(816, 1056);\n glutCreateWindow(argv[0]);\n glutReshapeFunc(reshape);\n glutDisplayFunc(display);\n glClearColor(1.0, 1.0, 1.0, 1.0);\n glEnable(GL_TEXTURE_2D);\n glDepthFunc(GL_LEQUAL);\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_ALPHA_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glutKeyboardFunc(keyboard);\n glutKeyboardUpFunc(keyboardUp);\n glutSpecialFunc(special);\n glutSpecialUpFunc(specialUp);\n glutMouseFunc(mouse);\n glutMotionFunc(mouseMove);\n glutPassiveMotionFunc(mouseMove);\n glutTimerFunc(50, timer, 0);\n glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ghost\/config.h\"\n#include \"ghost\/types.h\"\n#include \"ghost\/densemat.h\"\n#include \"ghost\/util.h\"\n#include \"ghost\/math.h\"\n#include \"ghost\/tsmttsm.h\"\n#include \"ghost\/tsmttsm_gen.h\"\n#include \"ghost\/tsmttsm_avx2_gen.h\"\n#include \"ghost\/tsmttsm_avx_gen.h\"\n#include \"ghost\/tsmttsm_sse_gen.h\"\n#include \"ghost\/timing.h\"\n\n#include <map>\n\nusing namespace std;\n\nstatic bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b) \n{ \n return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,ghost_hash(a.xstor,a.wstor,a.alignment))) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,ghost_hash(b.xstor,b.wstor,b.alignment))); \n}\n\nstatic map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels;\n\n\nghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv, \nghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror) \n{\n \/*if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {\n if (printerror) {\n ERROR_LOG(\"w must be stored row-major!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {\n if (printerror) {\n ERROR_LOG(\"v must be stored row-major!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {\n if (printerror) {\n ERROR_LOG(\"x must be stored col-major!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }*\/\n if (x->traits.location != GHOST_LOCATION_HOST || v->traits.location != GHOST_LOCATION_HOST || w->traits.location != GHOST_LOCATION_HOST) {\n if (printerror) {\n ERROR_LOG(\"TSMTTSM only implemented for host densemats!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n\n if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {\n if (printerror) {\n ERROR_LOG(\"Different data types!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {\n if (printerror) {\n ERROR_LOG(\"Scattered densemats not supported!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (!strncasecmp(transv,\"N\",1)) {\n if (printerror) {\n ERROR_LOG(\"v must be transposed!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (strncasecmp(transw,\"N\",1)) {\n if (printerror) {\n ERROR_LOG(\"w must not be transposed!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n\n UNUSED(alpha);\n UNUSED(beta);\n UNUSED(reduce);\n\n return GHOST_SUCCESS;\n}\n\n\nghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv)\n{\n GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);\n ghost_error_t ret;\n\n const char *vtrans;\n if (conjv && v->traits.datatype & GHOST_DT_COMPLEX) {\n vtrans = \"C\";\n } else {\n vtrans = \"T\";\n }\n\n if ((ret = ghost_tsmttsm_valid(x,v,vtrans,w,\"N\",alpha,beta,reduce,1)) != GHOST_SUCCESS) {\n INFO_LOG(\"TSMTTSM cannot be applied. Checking whether GEMM is fine!\");\n if ((ret = ghost_gemm_valid(x,v,vtrans,w,\"N\",alpha,beta,reduce,GHOST_GEMM_DEFAULT,1)) != GHOST_SUCCESS) {\n ERROR_LOG(\"GEMM cannot be applied!\");\n return ret;\n } else {\n return ghost_gemm(x,v,vtrans,w,\"N\",alpha,beta,reduce,GHOST_GEMM_NOT_SPECIAL);\n }\n }\n \n if (ghost_tsmttsm_kernels.empty()) {\n#include \"tsmttsm.def\"\n#include \"tsmttsm_avx2.def\"\n#include \"tsmttsm_avx.def\"\n#include \"tsmttsm_sse.def\"\n }\n \n ghost_tsmttsm_parameters_t p;\n ghost_tsmttsm_kernel_t kernel = NULL;\n\n#ifdef GHOST_HAVE_MIC\n p.impl = GHOST_IMPLEMENTATION_MIC;\n#elif defined(GHOST_HAVE_AVX2)\n p.impl = GHOST_IMPLEMENTATION_AVX2;\n#elif defined(GHOST_HAVE_AVX)\n p.impl = GHOST_IMPLEMENTATION_AVX;\n#elif defined(GHOST_HAVE_SSE)\n p.impl = GHOST_IMPLEMENTATION_SSE;\n#else\n p.impl = GHOST_IMPLEMENTATION_PLAIN;\n#endif\n \n \/*if (x->traits.ncolspadded < 4 || x->traits.flags & GHOST_DENSEMAT_VIEW) {\n p.impl = GHOST_IMPLEMENTATION_PLAIN;\n }*\/\n \/\/p.impl = GHOST_IMPLEMENTATION_PLAIN;\n\n p.alignment = GHOST_ALIGNED;\n p.dt = x->traits.datatype;\n p.xstor = x->traits.storage;\n p.wstor = w->traits.storage;\n \n p.vcols = v->traits.ncols;\n \n if (p.impl == GHOST_IMPLEMENTATION_SSE) {\n if (!IS_ALIGNED(x->val,16) || !IS_ALIGNED(v->val,16) || !IS_ALIGNED(w->val,16) || \n (x->stride*x->elSize)%16 || (v->stride*v->elSize)%16 || (w->stride*w->elSize)%16) {\n p.alignment = GHOST_UNALIGNED;\n PERFWARNING_LOG(\"Switching to the unaligned kernel!\");\n }\n }\n if (p.impl == GHOST_IMPLEMENTATION_AVX || p.impl == GHOST_IMPLEMENTATION_AVX2) {\n if (!IS_ALIGNED(x->val,32) || !IS_ALIGNED(v->val,32) || !IS_ALIGNED(w->val,32) || \n (x->stride*x->elSize)%32 || (v->stride*v->elSize)%32 || (w->stride*w->elSize)%32) {\n p.alignment = GHOST_UNALIGNED;\n PERFWARNING_LOG(\"Switching to the unaligned kernel!\");\n }\n }\n if (p.impl == GHOST_IMPLEMENTATION_PLAIN || p.impl == GHOST_IMPLEMENTATION_MIC) {\n if (!IS_ALIGNED(x->val,64) || !IS_ALIGNED(v->val,64) || !IS_ALIGNED(w->val,64) || \n (x->stride*x->elSize)%64 || (v->stride*v->elSize)%64 || (w->stride*w->elSize)%64) {\n p.alignment = GHOST_UNALIGNED;\n PERFWARNING_LOG(\"Switching to the unaligned kernel!\");\n }\n }\n p.wcols = w->traits.ncols;\n \n INFO_LOG(\"Inital search for kernel %d %d %d %d %d %d!\",p.dt,p.wcols,p.vcols,p.xstor,p.wstor,p.alignment);\n kernel = ghost_tsmttsm_kernels[p];\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary wcols\");\n p.wcols = -1;\n p.vcols = v->traits.ncols;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary vcols\");\n p.wcols = w->traits.ncols;\n p.vcols = -1;\n kernel = ghost_tsmttsm_kernels[p];\n }\n\n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary block sizes\");\n p.wcols = -1;\n p.vcols = -1;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try plain implementation\");\n p.impl = GHOST_IMPLEMENTATION_PLAIN;\n p.vcols = v->traits.ncols;\n p.wcols = w->traits.ncols;\n if (!IS_ALIGNED(x->val,64) || !IS_ALIGNED(v->val,64) || !IS_ALIGNED(w->val,64) || \n (x->stride*x->elSize)%64 || (v->stride*v->elSize)%64 || (w->stride*w->elSize)%64) {\n p.alignment = GHOST_UNALIGNED;\n PERFWARNING_LOG(\"Switching to the unaligned kernel!\");\n }\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary wcols\");\n p.wcols = -1;\n p.vcols = v->traits.ncols;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary vcols\");\n p.wcols = w->traits.ncols;\n p.vcols = -1;\n kernel = ghost_tsmttsm_kernels[p];\n }\n\n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary block sizes\");\n p.wcols = -1;\n p.vcols = -1;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try unaligned kernel\");\n p.alignment = GHOST_UNALIGNED;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n \n if (!kernel) {\n INFO_LOG(\"Could not find TSMTTSM kernel with %d %d %d %d %d. Fallback to GEMM\",p.dt,p.wcols,p.vcols,p.xstor,p.wstor);\n return GHOST_ERR_INVALID_ARG;\n \n \/\/return ghost_gemm(x,v,\"T\",w,\"N\",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL);\n }\n \n ret = kernel(x,v,w,alpha,beta,conjv);\n\n if (reduce != GHOST_GEMM_NO_REDUCE && v->context) {\n x->reduce(x,v->context->mpicomm,reduce);\n }\n\n#ifdef GHOST_HAVE_INSTR_TIMING\n ghost_gemm_perf_args_t tsmttsm_perfargs;\n tsmttsm_perfargs.n = w->traits.ncols;\n tsmttsm_perfargs.m = v->traits.ncols;\n if (v->context) {\n tsmttsm_perfargs.k = v->context->gnrows;\n } else {\n tsmttsm_perfargs.k = v->traits.nrows;\n }\n tsmttsm_perfargs.dt = x->traits.datatype;\n tsmttsm_perfargs.betaiszero = ghost_iszero(beta,p.dt);\n tsmttsm_perfargs.alphaisone = ghost_isone(alpha,p.dt);\n ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GBs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),\"GB\/s\");\n ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),\"GF\/s\");\n#endif\n\n GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);\n\n return ret;\n}\n\n\n<commit_msg>Adjust AVX tsmttsm kernel selection<commit_after>#include \"ghost\/config.h\"\n#include \"ghost\/types.h\"\n#include \"ghost\/densemat.h\"\n#include \"ghost\/util.h\"\n#include \"ghost\/math.h\"\n#include \"ghost\/tsmttsm.h\"\n#include \"ghost\/tsmttsm_gen.h\"\n#include \"ghost\/tsmttsm_avx2_gen.h\"\n#include \"ghost\/tsmttsm_avx_gen.h\"\n#include \"ghost\/tsmttsm_sse_gen.h\"\n#include \"ghost\/timing.h\"\n\n#include <map>\n\nusing namespace std;\n\nstatic bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b) \n{ \n return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,ghost_hash(a.xstor,a.wstor,a.alignment))) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,ghost_hash(b.xstor,b.wstor,b.alignment))); \n}\n\nstatic map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels;\n\n\nghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv, \nghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror) \n{\n \/*if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {\n if (printerror) {\n ERROR_LOG(\"w must be stored row-major!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {\n if (printerror) {\n ERROR_LOG(\"v must be stored row-major!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {\n if (printerror) {\n ERROR_LOG(\"x must be stored col-major!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }*\/\n if (x->traits.location != GHOST_LOCATION_HOST || v->traits.location != GHOST_LOCATION_HOST || w->traits.location != GHOST_LOCATION_HOST) {\n if (printerror) {\n ERROR_LOG(\"TSMTTSM only implemented for host densemats!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n\n if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {\n if (printerror) {\n ERROR_LOG(\"Different data types!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {\n if (printerror) {\n ERROR_LOG(\"Scattered densemats not supported!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (!strncasecmp(transv,\"N\",1)) {\n if (printerror) {\n ERROR_LOG(\"v must be transposed!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n if (strncasecmp(transw,\"N\",1)) {\n if (printerror) {\n ERROR_LOG(\"w must not be transposed!\");\n }\n return GHOST_ERR_INVALID_ARG;\n }\n\n UNUSED(alpha);\n UNUSED(beta);\n UNUSED(reduce);\n\n return GHOST_SUCCESS;\n}\n\n\nghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv)\n{\n GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);\n ghost_error_t ret;\n\n const char *vtrans;\n if (conjv && v->traits.datatype & GHOST_DT_COMPLEX) {\n vtrans = \"C\";\n } else {\n vtrans = \"T\";\n }\n\n if ((ret = ghost_tsmttsm_valid(x,v,vtrans,w,\"N\",alpha,beta,reduce,1)) != GHOST_SUCCESS) {\n INFO_LOG(\"TSMTTSM cannot be applied. Checking whether GEMM is fine!\");\n if ((ret = ghost_gemm_valid(x,v,vtrans,w,\"N\",alpha,beta,reduce,GHOST_GEMM_DEFAULT,1)) != GHOST_SUCCESS) {\n ERROR_LOG(\"GEMM cannot be applied!\");\n return ret;\n } else {\n return ghost_gemm(x,v,vtrans,w,\"N\",alpha,beta,reduce,GHOST_GEMM_NOT_SPECIAL);\n }\n }\n \n if (ghost_tsmttsm_kernels.empty()) {\n#include \"tsmttsm.def\"\n#include \"tsmttsm_avx2.def\"\n#include \"tsmttsm_avx.def\"\n#include \"tsmttsm_sse.def\"\n }\n \n ghost_tsmttsm_parameters_t p;\n ghost_tsmttsm_kernel_t kernel = NULL;\n\n#ifdef GHOST_HAVE_MIC\n p.impl = GHOST_IMPLEMENTATION_MIC;\n#elif defined(GHOST_HAVE_AVX2)\n p.impl = GHOST_IMPLEMENTATION_AVX2;\n#elif defined(GHOST_HAVE_AVX)\n p.impl = GHOST_IMPLEMENTATION_AVX;\n#elif defined(GHOST_HAVE_SSE)\n p.impl = GHOST_IMPLEMENTATION_SSE;\n#else\n p.impl = GHOST_IMPLEMENTATION_PLAIN;\n#endif\n \n \/*if (x->traits.ncolspadded < 4 || x->traits.flags & GHOST_DENSEMAT_VIEW) {\n p.impl = GHOST_IMPLEMENTATION_PLAIN;\n }*\/\n \/\/p.impl = GHOST_IMPLEMENTATION_PLAIN;\n\n p.alignment = GHOST_ALIGNED;\n p.dt = x->traits.datatype;\n p.xstor = x->traits.storage;\n p.wstor = w->traits.storage;\n \n p.vcols = v->traits.ncols;\n \n if (p.impl == GHOST_IMPLEMENTATION_SSE) {\n if (!IS_ALIGNED(x->val,16) || !IS_ALIGNED(v->val,16) || !IS_ALIGNED(w->val,16) || \n (x->stride*x->elSize)%16 || (v->stride*v->elSize)%16 || (w->stride*w->elSize)%16) {\n p.alignment = GHOST_UNALIGNED;\n PERFWARNING_LOG(\"Switching to the unaligned kernel!\");\n }\n }\n if (p.impl == GHOST_IMPLEMENTATION_AVX || p.impl == GHOST_IMPLEMENTATION_AVX2) {\n if (!IS_ALIGNED(x->val,32) || !IS_ALIGNED(v->val,32) || !IS_ALIGNED(w->val,32) || \n ((x->stride*x->elSize)%32 && (x->stride*x->elSize)>32) ||\n ((v->stride*v->elSize)%32 && (v->stride*v->elSize)>32) ||\n ((w->stride*w->elSize)%32 && (w->stride*w->elSize)>32) ){\n p.alignment = GHOST_UNALIGNED;\n PERFWARNING_LOG(\"Switching to the unaligned kernel!\");\n }\n }\n if (p.impl == GHOST_IMPLEMENTATION_PLAIN || p.impl == GHOST_IMPLEMENTATION_MIC) {\n if (!IS_ALIGNED(x->val,64) || !IS_ALIGNED(v->val,64) || !IS_ALIGNED(w->val,64) || \n (x->stride*x->elSize)%64 || (v->stride*v->elSize)%64 || (w->stride*w->elSize)%64) {\n p.alignment = GHOST_UNALIGNED;\n PERFWARNING_LOG(\"Switching to the unaligned kernel!\");\n }\n }\n p.wcols = w->traits.ncols;\n \n INFO_LOG(\"Inital search for kernel %d %d %d %d %d %d!\",p.dt,p.wcols,p.vcols,p.xstor,p.wstor,p.alignment);\n kernel = ghost_tsmttsm_kernels[p];\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary wcols\");\n p.wcols = -1;\n p.vcols = v->traits.ncols;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary vcols\");\n p.wcols = w->traits.ncols;\n p.vcols = -1;\n kernel = ghost_tsmttsm_kernels[p];\n }\n\n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary block sizes\");\n p.wcols = -1;\n p.vcols = -1;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try plain implementation\");\n p.impl = GHOST_IMPLEMENTATION_PLAIN;\n p.vcols = v->traits.ncols;\n p.wcols = w->traits.ncols;\n if (!IS_ALIGNED(x->val,64) || !IS_ALIGNED(v->val,64) || !IS_ALIGNED(w->val,64) || \n (x->stride*x->elSize)%64 || (v->stride*v->elSize)%64 || (w->stride*w->elSize)%64) {\n p.alignment = GHOST_UNALIGNED;\n PERFWARNING_LOG(\"Switching to the unaligned kernel!\");\n }\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary wcols\");\n p.wcols = -1;\n p.vcols = v->traits.ncols;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary vcols\");\n p.wcols = w->traits.ncols;\n p.vcols = -1;\n kernel = ghost_tsmttsm_kernels[p];\n }\n\n if (!kernel) {\n PERFWARNING_LOG(\"Try kernel with arbitrary block sizes\");\n p.wcols = -1;\n p.vcols = -1;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n if (!kernel) {\n PERFWARNING_LOG(\"Try unaligned kernel\");\n p.alignment = GHOST_UNALIGNED;\n kernel = ghost_tsmttsm_kernels[p];\n }\n \n \n if (!kernel) {\n INFO_LOG(\"Could not find TSMTTSM kernel with %d %d %d %d %d. Fallback to GEMM\",p.dt,p.wcols,p.vcols,p.xstor,p.wstor);\n return GHOST_ERR_INVALID_ARG;\n \n \/\/return ghost_gemm(x,v,\"T\",w,\"N\",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL);\n }\n \n ret = kernel(x,v,w,alpha,beta,conjv);\n\n if (reduce != GHOST_GEMM_NO_REDUCE && v->context) {\n x->reduce(x,v->context->mpicomm,reduce);\n }\n\n#ifdef GHOST_HAVE_INSTR_TIMING\n ghost_gemm_perf_args_t tsmttsm_perfargs;\n tsmttsm_perfargs.n = w->traits.ncols;\n tsmttsm_perfargs.m = v->traits.ncols;\n if (v->context) {\n tsmttsm_perfargs.k = v->context->gnrows;\n } else {\n tsmttsm_perfargs.k = v->traits.nrows;\n }\n tsmttsm_perfargs.dt = x->traits.datatype;\n tsmttsm_perfargs.betaiszero = ghost_iszero(beta,p.dt);\n tsmttsm_perfargs.alphaisone = ghost_isone(alpha,p.dt);\n ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GBs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),\"GB\/s\");\n ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),\"GF\/s\");\n#endif\n\n GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);\n\n return ret;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <SmurffCpp\/Utils\/HDF5Group.h>\n\n#include <Utils\/Error.h>\n#include <Utils\/StringUtils.h>\n\n\nnamespace smurff {\n\nbool HDF5Group::hasDataSet(const std::string& section, const std::string& tag) const\n{\n if (!m_group.exist(section)) return false;\n auto section_group = m_group.getGroup(section);\n return (section_group.exist(tag));\n}\n\nbool HDF5Group::hasSection(const std::string& section) const\n{\n return m_group.exist(section);\n}\n\nh5::Group HDF5Group::addGroup(const std::string& name)\n{\n if (!m_group.exist(name)) m_group.createGroup(name);\n return getGroup(name);\n}\n\nh5::Group HDF5Group::getGroup(const std::string& name) const\n{\n return m_group.getGroup(name);\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, Matrix &X) const\n{\n auto dataset = m_group.getGroup(section).getDataSet(tag);\n std::vector<size_t> dims = dataset.getDimensions();\n X.resize(dims[0], dims[1]);\n dataset.read(X.data());\n\n if (!X.IsRowMajor)\n {\n Matrix colMajor = Eigen::Map<Eigen::Matrix<\n typename Matrix::Scalar,\n Matrix::RowsAtCompileTime,\n Matrix::ColsAtCompileTime,\n Matrix::ColsAtCompileTime==1?Eigen::ColMajor:Eigen::RowMajor,\n Matrix::MaxRowsAtCompileTime,\n Matrix::MaxColsAtCompileTime>>(X.data(), dims[0], dims[1]);\n\n std::swap(colMajor, X);\n }\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, Vector &X) const\n{\n auto dataset = m_group.getGroup(section).getDataSet(tag);\n std::vector<size_t> dims = dataset.getDimensions();\n THROWERROR_ASSERT(dims[0] == 1);\n X.resize(dims[1]);\n dataset.read(X.data());\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, SparseMatrix &X) const\n{\n auto sparse_group = m_group.getGroup(section).getGroup(tag); \n\n std::string format;\n sparse_group.getAttribute(\"h5sparse_format\").read(format);\n THROWERROR_ASSERT(( SparseMatrix::IsRowMajor && format == \"csr\") || \\\n (!SparseMatrix::IsRowMajor && format == \"csc\"));\n \n std::vector<Eigen::Index> shape(2);\n sparse_group.getAttribute(\"h5sparse_shape\").read(shape);\n X.resize(shape.at(0), shape.at(1));\n X.makeCompressed();\n\n auto data = sparse_group.getDataSet(\"data\");\n THROWERROR_ASSERT(data.getDataType() == h5::AtomicType<SparseMatrix::value_type>());\n X.resizeNonZeros(data.getElementCount());\n data.read(X.valuePtr());\n\n auto indptr = sparse_group.getDataSet(\"indptr\");\n THROWERROR_ASSERT(indptr.getDataType() == h5::AtomicType<SparseMatrix::Index>());\n indptr.read(X.outerIndexPtr());\n\n auto indices = sparse_group.getDataSet(\"indices\");\n THROWERROR_ASSERT(indices.getDataType() == h5::AtomicType<SparseMatrix::Index>());\n indices.read(X.innerIndexPtr());\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, DenseTensor &) const\n{\n THROWERROR_NOTIMPL();\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, SparseTensor &) const\n{\n THROWERROR_NOTIMPL();\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const Vector &V)\n{\n write(section, tag, Matrix(V));\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const Matrix &M)\n{\n if (!m_group.exist(section))\n m_group.createGroup(section);\n\n h5::Group group = m_group.getGroup(section);\n h5::DataSet dataset = group.createDataSet<Matrix::Scalar>(tag, h5::DataSpace({static_cast<size_t>(M.rows()), static_cast<size_t>(M.cols())}));\n\n Eigen::Ref<\n const Eigen::Matrix<\n Matrix::Scalar,\n Matrix::RowsAtCompileTime,\n Matrix::ColsAtCompileTime,\n Matrix::ColsAtCompileTime==1?Eigen::ColMajor:Eigen::RowMajor,\n Matrix::MaxRowsAtCompileTime,\n Matrix::MaxColsAtCompileTime>,\n 0,\n Eigen::InnerStride<1>> row_major(M);\n\n dataset.write(row_major.data());\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const SparseMatrix &X)\n{\n if (!m_group.exist(section))\n m_group.createGroup(section);\n\n h5::Group sparse_group = m_group.getGroup(section).createGroup(tag);\n\n sparse_group.createAttribute<std::string>(\"h5sparse_format\", (SparseMatrix::IsRowMajor ? \"csr\" : \"csc\"));\n std::vector<Eigen::Index> shape{X.innerSize(), X.outerSize()};\n sparse_group.createAttribute<Eigen::Index>(\"h5sparse_shape\", h5::DataSpace::From(shape)).write(shape);\n\n auto data = sparse_group.createDataSet<SparseMatrix::value_type>(\"data\", h5::DataSpace(X.nonZeros()));\n data.write(X.valuePtr());\n\n auto indptr = sparse_group.createDataSet<SparseMatrix::Index>(\"indptr\", h5::DataSpace(X.outerSize() + 1));\n indptr.write(X.outerIndexPtr());\n\n auto indices = sparse_group.createDataSet<SparseMatrix::Index>(\"indices\", h5::DataSpace(X.nonZeros()));\n indices.write(X.innerIndexPtr());\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const DenseTensor &X)\n{\n THROWERROR_NOTIMPL();\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const SparseTensor &X)\n{\n THROWERROR_NOTIMPL();\n}\n\n\n} \/\/ end namespace smurff\n<commit_msg>FIX: h5sparse format rows\/cols was switched<commit_after>#include <iostream>\n\n#include <SmurffCpp\/Utils\/HDF5Group.h>\n\n#include <Utils\/Error.h>\n#include <Utils\/StringUtils.h>\n\n\nnamespace smurff {\n\nbool HDF5Group::hasDataSet(const std::string& section, const std::string& tag) const\n{\n if (!m_group.exist(section)) return false;\n auto section_group = m_group.getGroup(section);\n return (section_group.exist(tag));\n}\n\nbool HDF5Group::hasSection(const std::string& section) const\n{\n return m_group.exist(section);\n}\n\nh5::Group HDF5Group::addGroup(const std::string& name)\n{\n if (!m_group.exist(name)) m_group.createGroup(name);\n return getGroup(name);\n}\n\nh5::Group HDF5Group::getGroup(const std::string& name) const\n{\n return m_group.getGroup(name);\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, Matrix &X) const\n{\n auto dataset = m_group.getGroup(section).getDataSet(tag);\n std::vector<size_t> dims = dataset.getDimensions();\n X.resize(dims[0], dims[1]);\n dataset.read(X.data());\n\n if (!X.IsRowMajor)\n {\n Matrix colMajor = Eigen::Map<Eigen::Matrix<\n typename Matrix::Scalar,\n Matrix::RowsAtCompileTime,\n Matrix::ColsAtCompileTime,\n Matrix::ColsAtCompileTime==1?Eigen::ColMajor:Eigen::RowMajor,\n Matrix::MaxRowsAtCompileTime,\n Matrix::MaxColsAtCompileTime>>(X.data(), dims[0], dims[1]);\n\n std::swap(colMajor, X);\n }\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, Vector &X) const\n{\n auto dataset = m_group.getGroup(section).getDataSet(tag);\n std::vector<size_t> dims = dataset.getDimensions();\n THROWERROR_ASSERT(dims[0] == 1);\n X.resize(dims[1]);\n dataset.read(X.data());\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, SparseMatrix &X) const\n{\n auto sparse_group = m_group.getGroup(section).getGroup(tag); \n\n std::string format;\n sparse_group.getAttribute(\"h5sparse_format\").read(format);\n THROWERROR_ASSERT(( SparseMatrix::IsRowMajor && format == \"csr\") || \\\n (!SparseMatrix::IsRowMajor && format == \"csc\"));\n \n std::vector<Eigen::Index> shape(2);\n sparse_group.getAttribute(\"h5sparse_shape\").read(shape);\n X.resize(shape.at(0), shape.at(1));\n X.makeCompressed();\n\n auto data = sparse_group.getDataSet(\"data\");\n THROWERROR_ASSERT(data.getDataType() == h5::AtomicType<SparseMatrix::value_type>());\n X.resizeNonZeros(data.getElementCount());\n data.read(X.valuePtr());\n\n auto indptr = sparse_group.getDataSet(\"indptr\");\n THROWERROR_ASSERT(indptr.getDataType() == h5::AtomicType<SparseMatrix::Index>());\n indptr.read(X.outerIndexPtr());\n\n auto indices = sparse_group.getDataSet(\"indices\");\n THROWERROR_ASSERT(indices.getDataType() == h5::AtomicType<SparseMatrix::Index>());\n indices.read(X.innerIndexPtr());\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, DenseTensor &) const\n{\n THROWERROR_NOTIMPL();\n}\n\nvoid HDF5Group::read(const std::string& section, const std::string& tag, SparseTensor &) const\n{\n THROWERROR_NOTIMPL();\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const Vector &V)\n{\n write(section, tag, Matrix(V));\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const Matrix &M)\n{\n if (!m_group.exist(section))\n m_group.createGroup(section);\n\n h5::Group group = m_group.getGroup(section);\n h5::DataSet dataset = group.createDataSet<Matrix::Scalar>(tag, h5::DataSpace({static_cast<size_t>(M.rows()), static_cast<size_t>(M.cols())}));\n\n Eigen::Ref<\n const Eigen::Matrix<\n Matrix::Scalar,\n Matrix::RowsAtCompileTime,\n Matrix::ColsAtCompileTime,\n Matrix::ColsAtCompileTime==1?Eigen::ColMajor:Eigen::RowMajor,\n Matrix::MaxRowsAtCompileTime,\n Matrix::MaxColsAtCompileTime>,\n 0,\n Eigen::InnerStride<1>> row_major(M);\n\n dataset.write(row_major.data());\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const SparseMatrix &X)\n{\n if (!m_group.exist(section))\n m_group.createGroup(section);\n\n h5::Group sparse_group = m_group.getGroup(section).createGroup(tag);\n\n sparse_group.createAttribute<std::string>(\"h5sparse_format\", (SparseMatrix::IsRowMajor ? \"csr\" : \"csc\"));\n std::vector<Eigen::Index> shape{X.rows(), X.cols()};\n sparse_group.createAttribute<Eigen::Index>(\"h5sparse_shape\", h5::DataSpace::From(shape)).write(shape);\n\n auto data = sparse_group.createDataSet<SparseMatrix::value_type>(\"data\", h5::DataSpace(X.nonZeros()));\n data.write(X.valuePtr());\n\n auto indptr = sparse_group.createDataSet<SparseMatrix::Index>(\"indptr\", h5::DataSpace(X.outerSize() + 1));\n indptr.write(X.outerIndexPtr());\n\n auto indices = sparse_group.createDataSet<SparseMatrix::Index>(\"indices\", h5::DataSpace(X.nonZeros()));\n indices.write(X.innerIndexPtr());\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const DenseTensor &X)\n{\n THROWERROR_NOTIMPL();\n}\n\nvoid HDF5Group::write(const std::string& section, const std::string& tag, const SparseTensor &X)\n{\n THROWERROR_NOTIMPL();\n}\n\n\n} \/\/ end namespace smurff\n<|endoftext|>"} {"text":"<commit_before>\/** \\brief Utility for validating and fixing up records harvested by zts_harvester\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2018-2020 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (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. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <unordered_set>\n#include <cstdio>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"EmailSender.h\"\n#include \"IniFile.h\"\n#include \"MARC.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n ::Usage(\"marc_input marc_output missed_expectations_file email_address\");\n}\n\n\nenum FieldPresence { ALWAYS, SOMETIMES, IGNORE };\n\n\nstruct FieldInfo {\n std::string name_;\n FieldPresence presence_;\npublic:\n FieldInfo(const std::string &name, const FieldPresence presence): name_(name), presence_(presence) { }\n};\n\n\nclass JournalInfo {\n bool not_in_database_yet_;\n std::vector<FieldInfo> field_infos_;\npublic:\n using const_iterator = std::vector<FieldInfo>::const_iterator;\n using iterator = std::vector<FieldInfo>::iterator;\npublic:\n explicit JournalInfo(const bool not_in_database_yet): not_in_database_yet_(not_in_database_yet) { }\n JournalInfo() = default;\n JournalInfo(const JournalInfo &rhs) = default;\n\n size_t size() const { return field_infos_.size(); }\n bool isInDatabase() const { return not not_in_database_yet_; }\n void addField(const std::string &field_name, const FieldPresence field_presence)\n { field_infos_.emplace_back(field_name, field_presence); }\n const_iterator begin() const { return field_infos_.cbegin(); }\n const_iterator end() const { return field_infos_.cend(); }\n iterator begin() { return field_infos_.begin(); }\n iterator end() { return field_infos_.end(); }\n iterator find(const std::string &field_name) {\n return std::find_if(field_infos_.begin(), field_infos_.end(),\n [&field_name](const FieldInfo &field_info){ return field_name == field_info.name_; });\n }\n};\n\n\nFieldPresence StringToFieldPresence(const std::string &s) {\n if (s == \"always\")\n return ALWAYS;\n if (s == \"sometimes\")\n return SOMETIMES;\n if (s == \"ignore\")\n return IGNORE;\n LOG_ERROR(\"unknown enumerated value \\\"\" + s + \"\\\"!\");\n}\n\n\nstd::string FieldPresenceToString(const FieldPresence field_presence) {\n switch (field_presence) {\n case ALWAYS:\n return \"always\";\n case SOMETIMES:\n return \"sometimes\";\n case IGNORE:\n return \"ignore\";\n default:\n LOG_ERROR(\"we should *never get here!\");\n }\n}\n\n\nvoid LoadFromDatabaseOrCreateFromScratch(DbConnection * const db_connection, const std::string &journal_name,\n JournalInfo * const journal_info)\n{\n db_connection->queryOrDie(\"SELECT metadata_field_name,field_presence FROM metadata_presence_tracer WHERE journal_name='\"\n + db_connection->escapeString(journal_name) + \"'\");\n DbResultSet result_set(db_connection->getLastResultSet());\n if (result_set.empty()) {\n LOG_INFO(\"\\\"\" + journal_name + \"\\\" was not yet in the database.\");\n *journal_info = JournalInfo(\/* not_in_database_yet = *\/true);\n return;\n }\n\n *journal_info = JournalInfo(\/* not_in_database_yet = *\/false);\n while (auto row = result_set.getNextRow())\n journal_info->addField(row[\"metadata_field_name\"], StringToFieldPresence(row[\"field_presence\"]));\n}\n\n\n\/\/ Two-way mapping required as the map is uni-directional\nconst std::map<std::string, std::string> EQUIVALENT_TAGS_MAP{\n { \"700\", \"100\" }, { \"100\", \"700\" }\n};\n\n\nvoid AnalyseNewJournalRecord(const MARC::Record &record, const bool first_record, JournalInfo * const journal_info) {\n std::unordered_set<std::string> seen_tags;\n MARC::Tag last_tag;\n for (const auto &field : record) {\n auto current_tag(field.getTag());\n if (current_tag == last_tag)\n continue;\n\n seen_tags.emplace(current_tag.toString());\n\n if (first_record)\n journal_info->addField(current_tag.toString(), ALWAYS);\n else if (journal_info->find(current_tag.toString()) == journal_info->end())\n journal_info->addField(current_tag.toString(), SOMETIMES);\n\n last_tag = current_tag;\n }\n\n for (auto &field_info : *journal_info) {\n if (seen_tags.find(field_info.name_) == seen_tags.end())\n field_info.presence_ = SOMETIMES;\n }\n}\n\n\nbool RecordMeetsExpectations(const MARC::Record &record, const std::string &journal_name, const JournalInfo &journal_info) {\n std::unordered_set<std::string> seen_tags;\n MARC::Tag last_tag;\n for (const auto &field : record) {\n const auto current_tag(field.getTag());\n if (current_tag == last_tag)\n continue;\n seen_tags.emplace(current_tag.toString());\n last_tag = current_tag;\n }\n\n bool missed_at_least_one_expectation(false);\n for (const auto &field_info : journal_info) {\n if (field_info.presence_ != ALWAYS)\n continue; \/\/ we only care about required fields that are missing\n\n const auto equivalent_tag(EQUIVALENT_TAGS_MAP.find(field_info.name_));\n if (seen_tags.find(field_info.name_) != seen_tags.end())\n ;\/\/ required tag found\n else if (equivalent_tag != EQUIVALENT_TAGS_MAP.end() and seen_tags.find(equivalent_tag->second) != seen_tags.end())\n ;\/\/ equivalent tag found\n else {\n LOG_WARNING(\"Record w\/ control number \" + record.getControlNumber() + \" in \\\"\" + journal_name\n + \"\\\" is missing the always expected \" + field_info.name_ + \" field.\");\n missed_at_least_one_expectation = true;\n }\n }\n\n return not missed_at_least_one_expectation;\n}\n\n\nvoid WriteToDatabase(DbConnection * const db_connection, const std::string &journal_name, const JournalInfo &journal_info) {\n for (const auto &field_info : journal_info)\n db_connection->queryOrDie(\"INSERT INTO metadata_presence_tracer SET journal_name='\" + journal_name\n + \"', metadata_field_name='\" + db_connection->escapeString(field_info.name_)\n + \"', field_presence='\" + FieldPresenceToString(field_info.presence_) + \"'\");\n}\n\n\nvoid SendEmail(const std::string &email_address, const std::string &message_subject, const std::string &message_body) {\n const auto reply_code(EmailSender::SendEmail(\"zts_harvester_delivery_pipeline@uni-tuebingen.de\",\n email_address, message_subject, message_body,\n EmailSender::MEDIUM, EmailSender::PLAIN_TEXT, \/* reply_to = *\/ \"\",\n \/* use_ssl = *\/ true, \/* use_authentication = *\/ true));\n\n if (reply_code >= 300)\n LOG_WARNING(\"failed to send email, the response code was: \" + std::to_string(reply_code));\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 5)\n Usage();\n\n DbConnection db_connection;\n auto reader(MARC::Reader::Factory(argv[1]));\n auto valid_records_writer(MARC::Writer::Factory(argv[2]));\n auto delinquent_records_writer(MARC::Writer::Factory(argv[3]));\n std::map<std::string, JournalInfo> journal_name_to_info_map;\n const std::string email_address(argv[4]);\n\n unsigned total_record_count(0), new_record_count(0), missed_expectation_count(0);\n while (const auto record = reader->read()) {\n ++total_record_count;\n bool validation_failed(false);\n\n \/\/ Intentionally true to allow early breaking\n while (true) {\n const auto journal_name(record.getSuperiorTitle());\n if (journal_name.empty()) {\n LOG_WARNING(\"Record w\/ control number \\\"\" + record.getControlNumber() + \"\\\" is missing a superior title!\");\n validation_failed = true;\n break;\n }\n\n auto journal_name_and_info(journal_name_to_info_map.find(journal_name));\n bool first_record(false); \/\/ True if the current record is the first encounter of a journal\n if (journal_name_and_info == journal_name_to_info_map.end()) {\n first_record = true;\n JournalInfo new_journal_info;\n LoadFromDatabaseOrCreateFromScratch(&db_connection, journal_name, &new_journal_info);\n journal_name_to_info_map[journal_name] = new_journal_info;\n journal_name_and_info = journal_name_to_info_map.find(journal_name);\n }\n\n if (journal_name_and_info->second.isInDatabase()) {\n if (not RecordMeetsExpectations(record, journal_name_and_info->first, journal_name_and_info->second)) {\n validation_failed = true;\n ++missed_expectation_count;\n break;\n }\n } else {\n AnalyseNewJournalRecord(record, first_record, &journal_name_and_info->second);\n ++new_record_count;\n }\n\n \/\/ Break unconditionally\n break;\n }\n\n if (validation_failed)\n delinquent_records_writer->write(record);\n else\n valid_records_writer->write(record);\n }\n\n for (const auto &journal_name_and_info : journal_name_to_info_map) {\n if (not journal_name_and_info.second.isInDatabase())\n WriteToDatabase(&db_connection, journal_name_and_info.first, journal_name_and_info.second);\n }\n\n if (missed_expectation_count > 0) {\n \/\/ send notification to the email address\n SendEmail(email_address, \"validate_harvested_records encountered warnings\",\n \"Some records missed expectations with respect to MARC fields. \"\n \"Check the log at '\/usr\/local\/var\/log\/tuefind\/zts_harvester_delivery_pipeline.log' for details.\");\n }\n\n LOG_INFO(\"Processed \" + std::to_string(total_record_count) + \" record(s) of which \" + std::to_string(new_record_count)\n + \" was\/were (a) record(s) of new journals and \" + std::to_string(missed_expectation_count)\n + \" record(s) missed expectations.\");\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Added a new mode to alter expectations for MARC fields.<commit_after>\/** \\brief Utility for validating and fixing up records harvested by zts_harvester\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2018-2020 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (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. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <unordered_set>\n#include <cstdio>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"EmailSender.h\"\n#include \"IniFile.h\"\n#include \"MARC.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n ::Usage(\"(marc_input marc_output missed_expectations_file email_address| update_db journal_name field_name field_presence)\\n\"\n \"\\tThis tool has two operating modes 1) checking MARC data for missed expectations and 2) altering these expectations.\\n\"\n \"\\tin the \\\"update_db\\\" mode, \\\"field_name\\\" must be a 3-character MARC tag and \\\"field_presence\\\" must be one of\\n\"\n \"\\tALWAYS, SOMETIMES, IGNORE. Please note that only existing entries can be changed!\");\n}\n\n\nenum FieldPresence { ALWAYS, SOMETIMES, IGNORE };\n\n\nbool StringToFieldPresence(const std::string &field_presence_str, FieldPresence * const field_presence) {\n if (field_presence_str == \"ALWAYS\") {\n *field_presence = ALWAYS;\n return true;\n }\n\n if (field_presence_str == \"SOMETIMES\") {\n *field_presence = SOMETIMES;\n return true;\n }\n\n if (field_presence_str == \"IGNORE\") {\n *field_presence = IGNORE;\n return true;\n }\n\n return false;\n}\n\n\nstruct FieldInfo {\n std::string name_;\n FieldPresence presence_;\npublic:\n FieldInfo(const std::string &name, const FieldPresence presence): name_(name), presence_(presence) { }\n};\n\n\nclass JournalInfo {\n bool not_in_database_yet_;\n std::vector<FieldInfo> field_infos_;\npublic:\n using const_iterator = std::vector<FieldInfo>::const_iterator;\n using iterator = std::vector<FieldInfo>::iterator;\npublic:\n explicit JournalInfo(const bool not_in_database_yet): not_in_database_yet_(not_in_database_yet) { }\n JournalInfo() = default;\n JournalInfo(const JournalInfo &rhs) = default;\n\n size_t size() const { return field_infos_.size(); }\n bool isInDatabase() const { return not not_in_database_yet_; }\n void addField(const std::string &field_name, const FieldPresence field_presence)\n { field_infos_.emplace_back(field_name, field_presence); }\n const_iterator begin() const { return field_infos_.cbegin(); }\n const_iterator end() const { return field_infos_.cend(); }\n iterator begin() { return field_infos_.begin(); }\n iterator end() { return field_infos_.end(); }\n iterator find(const std::string &field_name) {\n return std::find_if(field_infos_.begin(), field_infos_.end(),\n [&field_name](const FieldInfo &field_info){ return field_name == field_info.name_; });\n }\n};\n\n\nFieldPresence StringToFieldPresence(const std::string &s) {\n if (s == \"always\")\n return ALWAYS;\n if (s == \"sometimes\")\n return SOMETIMES;\n if (s == \"ignore\")\n return IGNORE;\n LOG_ERROR(\"unknown enumerated value \\\"\" + s + \"\\\"!\");\n}\n\n\nstd::string FieldPresenceToString(const FieldPresence field_presence) {\n switch (field_presence) {\n case ALWAYS:\n return \"always\";\n case SOMETIMES:\n return \"sometimes\";\n case IGNORE:\n return \"ignore\";\n default:\n LOG_ERROR(\"we should *never get here!\");\n }\n}\n\n\nvoid LoadFromDatabaseOrCreateFromScratch(DbConnection * const db_connection, const std::string &journal_name,\n JournalInfo * const journal_info)\n{\n db_connection->queryOrDie(\"SELECT metadata_field_name,field_presence FROM metadata_presence_tracer WHERE journal_name='\"\n + db_connection->escapeString(journal_name) + \"'\");\n DbResultSet result_set(db_connection->getLastResultSet());\n if (result_set.empty()) {\n LOG_INFO(\"\\\"\" + journal_name + \"\\\" was not yet in the database.\");\n *journal_info = JournalInfo(\/* not_in_database_yet = *\/true);\n return;\n }\n\n *journal_info = JournalInfo(\/* not_in_database_yet = *\/false);\n while (auto row = result_set.getNextRow())\n journal_info->addField(row[\"metadata_field_name\"], StringToFieldPresence(row[\"field_presence\"]));\n}\n\n\n\/\/ Two-way mapping required as the map is uni-directional\nconst std::map<std::string, std::string> EQUIVALENT_TAGS_MAP{\n { \"700\", \"100\" }, { \"100\", \"700\" }\n};\n\n\nvoid AnalyseNewJournalRecord(const MARC::Record &record, const bool first_record, JournalInfo * const journal_info) {\n std::unordered_set<std::string> seen_tags;\n MARC::Tag last_tag;\n for (const auto &field : record) {\n auto current_tag(field.getTag());\n if (current_tag == last_tag)\n continue;\n\n seen_tags.emplace(current_tag.toString());\n\n if (first_record)\n journal_info->addField(current_tag.toString(), ALWAYS);\n else if (journal_info->find(current_tag.toString()) == journal_info->end())\n journal_info->addField(current_tag.toString(), SOMETIMES);\n\n last_tag = current_tag;\n }\n\n for (auto &field_info : *journal_info) {\n if (seen_tags.find(field_info.name_) == seen_tags.end())\n field_info.presence_ = SOMETIMES;\n }\n}\n\n\nbool RecordMeetsExpectations(const MARC::Record &record, const std::string &journal_name, const JournalInfo &journal_info) {\n std::unordered_set<std::string> seen_tags;\n MARC::Tag last_tag;\n for (const auto &field : record) {\n const auto current_tag(field.getTag());\n if (current_tag == last_tag)\n continue;\n seen_tags.emplace(current_tag.toString());\n last_tag = current_tag;\n }\n\n bool missed_at_least_one_expectation(false);\n for (const auto &field_info : journal_info) {\n if (field_info.presence_ != ALWAYS)\n continue; \/\/ we only care about required fields that are missing\n\n const auto equivalent_tag(EQUIVALENT_TAGS_MAP.find(field_info.name_));\n if (seen_tags.find(field_info.name_) != seen_tags.end())\n ;\/\/ required tag found\n else if (equivalent_tag != EQUIVALENT_TAGS_MAP.end() and seen_tags.find(equivalent_tag->second) != seen_tags.end())\n ;\/\/ equivalent tag found\n else {\n LOG_WARNING(\"Record w\/ control number \" + record.getControlNumber() + \" in \\\"\" + journal_name\n + \"\\\" is missing the always expected \" + field_info.name_ + \" field.\");\n missed_at_least_one_expectation = true;\n }\n }\n\n return not missed_at_least_one_expectation;\n}\n\n\nvoid WriteToDatabase(DbConnection * const db_connection, const std::string &journal_name, const JournalInfo &journal_info) {\n for (const auto &field_info : journal_info)\n db_connection->queryOrDie(\"INSERT INTO metadata_presence_tracer SET journal_name='\" + journal_name\n + \"', metadata_field_name='\" + db_connection->escapeString(field_info.name_)\n + \"', field_presence='\" + FieldPresenceToString(field_info.presence_) + \"'\");\n}\n\n\nvoid SendEmail(const std::string &email_address, const std::string &message_subject, const std::string &message_body) {\n const auto reply_code(EmailSender::SendEmail(\"zts_harvester_delivery_pipeline@uni-tuebingen.de\",\n email_address, message_subject, message_body,\n EmailSender::MEDIUM, EmailSender::PLAIN_TEXT, \/* reply_to = *\/ \"\",\n \/* use_ssl = *\/ true, \/* use_authentication = *\/ true));\n\n if (reply_code >= 300)\n LOG_WARNING(\"failed to send email, the response code was: \" + std::to_string(reply_code));\n}\n\n\nvoid UpdateDB(DbConnection * const db_connection, const std::string &journal_name, const std::string &field_name, const std::string &field_presence_str) {\n FieldPresence field_presence;\n if (not StringToFieldPresence(field_presence_str, &field_presence))\n LOG_ERROR(\"\\\"\" + field_presence_str + \"\\\" is not a valid field_presence!\");\n if (field_name.length() != MARC::Record::TAG_LENGTH)\n LOG_ERROR(\"\\\"\" + field_name + \"\\\" is not a valid field name!\");\n\n DbTransaction transcation(db_connection);\n db_connection->queryOrDie(\"SELECT field_presence FROM metadata_presence_tracer WHERE journal_name=\"\n + db_connection->escapeAndQuoteString(journal_name) + \" AND field_name='\" + field_name + \"'\");\n const DbResultSet result_set(db_connection->getLastResultSet());\n if (result_set.empty())\n LOG_ERROR(\"can't update non-existent database entry!\");\n db_connection->queryOrDie(\"UPDATE metadata_presence_tracer SET field_presence='\" + field_presence_str + \"' WHERE journal_name=\"\n + db_connection->escapeAndQuoteString(journal_name) + \" AND field_name='\" + field_name + \"'\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 5)\n Usage();\n\n DbConnection db_connection;\n\n if (std::strcmp(argv[1], \"update_db\") == 0) {\n UpdateDB(&db_connection, argv[2], argv[3], argv[4]);\n return EXIT_SUCCESS;\n }\n\n auto reader(MARC::Reader::Factory(argv[1]));\n auto valid_records_writer(MARC::Writer::Factory(argv[2]));\n auto delinquent_records_writer(MARC::Writer::Factory(argv[3]));\n std::map<std::string, JournalInfo> journal_name_to_info_map;\n const std::string email_address(argv[4]);\n\n unsigned total_record_count(0), new_record_count(0), missed_expectation_count(0);\n while (const auto record = reader->read()) {\n ++total_record_count;\n bool validation_failed(false);\n\n \/\/ Intentionally true to allow early breaking\n while (true) {\n const auto journal_name(record.getSuperiorTitle());\n if (journal_name.empty()) {\n LOG_WARNING(\"Record w\/ control number \\\"\" + record.getControlNumber() + \"\\\" is missing a superior title!\");\n validation_failed = true;\n break;\n }\n\n auto journal_name_and_info(journal_name_to_info_map.find(journal_name));\n bool first_record(false); \/\/ True if the current record is the first encounter of a journal\n if (journal_name_and_info == journal_name_to_info_map.end()) {\n first_record = true;\n JournalInfo new_journal_info;\n LoadFromDatabaseOrCreateFromScratch(&db_connection, journal_name, &new_journal_info);\n journal_name_to_info_map[journal_name] = new_journal_info;\n journal_name_and_info = journal_name_to_info_map.find(journal_name);\n }\n\n if (journal_name_and_info->second.isInDatabase()) {\n if (not RecordMeetsExpectations(record, journal_name_and_info->first, journal_name_and_info->second)) {\n validation_failed = true;\n ++missed_expectation_count;\n break;\n }\n } else {\n AnalyseNewJournalRecord(record, first_record, &journal_name_and_info->second);\n ++new_record_count;\n }\n\n \/\/ Break unconditionally\n break;\n }\n\n if (validation_failed)\n delinquent_records_writer->write(record);\n else\n valid_records_writer->write(record);\n }\n\n for (const auto &journal_name_and_info : journal_name_to_info_map) {\n if (not journal_name_and_info.second.isInDatabase())\n WriteToDatabase(&db_connection, journal_name_and_info.first, journal_name_and_info.second);\n }\n\n if (missed_expectation_count > 0) {\n \/\/ send notification to the email address\n SendEmail(email_address, \"validate_harvested_records encountered warnings\",\n \"Some records missed expectations with respect to MARC fields. \"\n \"Check the log at '\/usr\/local\/var\/log\/tuefind\/zts_harvester_delivery_pipeline.log' for details.\");\n }\n\n LOG_INFO(\"Processed \" + std::to_string(total_record_count) + \" record(s) of which \" + std::to_string(new_record_count)\n + \" was\/were (a) record(s) of new journals and \" + std::to_string(missed_expectation_count)\n + \" record(s) missed expectations.\");\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <queue>\n#include <vector>\n#include <utility>\n#include <iostream>\n#include <string>\n#include <stack>\n\nusing namespace std;\n\nstack<string> lv1;\nstack<string> lv2;\nstack<string> lv3;\n\nstring temp;\nint templv;\nint temptime=0;\nint usernum;\nint users=0;\nint read(int now){\n\tif(now < temptime) return 0;\n\n\tdo{\n\t\tprintf(\"test\\n\");\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tif(users<usernum)\n\t\t\tcin >>temptime>>templv>>temp;\n\t\telse\n\t\t\treturn 0;\n\t\tusers++;\n\t}while(temptime<=now);\n\n\n\n}\nint main(int argc, char const *argv[])\n{\n\t\tint time;\n\t\tscanf(\"%d%d\",&usernum,&time);\n\t\tfor (int i = 0; i < time; ++i)\n\t\t{\t\n\t\t\tread(i);\n\t\t\tcout<<i<<\"\\n\"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;\n\t\t\tif(users==usernum) break;\n\t\t}\n\t\t\t\n\t\t\t\n\t\t\n\t \n\t\n\treturn 0;\n}<commit_msg>update uoj2254<commit_after>#include <stdio.h>\n#include <queue>\n#include <vector>\n#include <utility>\n#include <iostream>\n#include <string>\n#include <stack>\n\nusing namespace std;\n\nstack<string> lv1;\nstack<string> lv2;\nstack<string> lv3;\n\nstring temp;\nint templv;\nint temptime=0;\nint usernum;\nint users=0;\nint read(int now){\n\tif(now < temptime) return 0;\n\n\tdo{\n\t\tprintf(\"test\\n\");\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tif(users<usernum)\n\t\t\tcin >>temptime>>templv>>temp;\n\t\telse\n\t\t\treturn 0;\n\t\tusers++;\n\t}while(temptime<=now);\n\n\n\n}\nint main(int argc, char const *argv[])\n{\n\t\tint time;\n\t\tscanf(\"%d%d\",&usernum,&time);\n\t\tfor (int i = 0; i < time; ++i)\n\t\t{\t\n\t\t\tread(i);\n\t\t\tcout<<i<<\"\\n\"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;\n\t\t\t\n\t\t}\n\t\t\t\n\t\t\t\n\t\t\n\t \n\t\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <X11\/Xlib.h>\n#include <X11\/keysym.h>\n#include <irrlicht\/Keycodes.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#define RETURN 13\n#define BS 8\n#define SPACE 32\n\nXKeyEvent createKeyEvent(Display *display,\n Window &win,\n Window &winRoot,\n bool press,\n int keycode,\n int modifiers)\n{\n \/\/ Largely lifted from\n \/\/ http:\/\/www.doctort.org\/adam\/nerd-notes\/x11-fake-keypress-event.html\n XKeyEvent event;\n event.display = display;\n event.window = win;\n event.root = winRoot;\n event.subwindow = None;\n event.time = CurrentTime;\n event.x = 1;\n event.y = 1;\n event.x_root = 1;\n event.y_root = 1;\n event.same_screen = True;\n event.keycode = XKeysymToKeycode(display, keycode);\n event.state = modifiers;\n\n if(press)\n event.type = KeyPress;\n else\n event.type = KeyRelease;\n\n return event;\n}\n\nclass X11Display {\n public:\n Display *display;\n X11Display(const char* dispName);\n};\n\nX11Display::X11Display(const char* dispName) :\n display(XOpenDisplay(dispName)){}\n\nint mapKeyCode(int irrcode){\n switch(irrcode){\n \/\/FIXME: only to get rid of arrow spam\n case 37 ... 40:\n return -1;\n case irr::KEY_BACK :\n return XK_BackSpace;\n case irr::KEY_TAB :\n return XK_Tab;\n case irr::KEY_RETURN :\n return XK_Return;\n case irr::KEY_MINUS :\n return XK_minus;\n case irr::KEY_OEM_7 :\n return XK_apostrophe;\n default:\n return irrcode;\n }\n}\n\nint sendKeyEvent(const char* disp, int keycode)\n{\n if(-1==keycode)\n return 0;\n printf(\"sendKeyEvent keycode: %d\\n\", keycode);\n Window winFocus;\n int revert;\n\n Display *display = XOpenDisplay(disp);\n if(NULL == display)\n return -1;\n Window winRoot = XDefaultRootWindow(display);\n \/\/XSetInputFocus(display, 1, revert, CurrentTime);\n XGetInputFocus(display, &winFocus, &revert);\n XKeyEvent event = createKeyEvent(display, winFocus, winRoot, true, keycode, 0);\n XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);\n event = createKeyEvent(display, winFocus, winRoot, false, keycode, 0);\n XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);\n XCloseDisplay(display);\n return 0;\n}\n<commit_msg>Constructor, destructor, no segfault<commit_after>#include <X11\/Xlib.h>\n#include <X11\/keysym.h>\n#include <irrlicht\/Keycodes.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#define RETURN 13\n#define BS 8\n#define SPACE 32\n\nXKeyEvent createKeyEvent(Display *display,\n Window &win,\n Window &winRoot,\n bool press,\n int keycode,\n int modifiers)\n{\n \/\/ Largely lifted from\n \/\/ http:\/\/www.doctort.org\/adam\/nerd-notes\/x11-fake-keypress-event.html\n XKeyEvent event;\n event.display = display;\n event.window = win;\n event.root = winRoot;\n event.subwindow = None;\n event.time = CurrentTime;\n event.x = 1;\n event.y = 1;\n event.x_root = 1;\n event.y_root = 1;\n event.same_screen = True;\n event.keycode = XKeysymToKeycode(display, keycode);\n event.state = modifiers;\n\n if(press)\n event.type = KeyPress;\n else\n event.type = KeyRelease;\n\n return event;\n}\n\nclass X11Display {\n public:\n Display *display;\n X11Display(const char* dispName);\n ~X11Display();\n};\n\nX11Display::X11Display(const char* dispName) :\n display(XOpenDisplay(dispName)){}\n\nX11Display::~X11Display() { XCloseDisplay(display); }\n\nint mapKeyCode(int irrcode){\n switch(irrcode){\n \/\/FIXME: only to get rid of arrow spam\n case 37 ... 40:\n return -1;\n case irr::KEY_BACK :\n return XK_BackSpace;\n case irr::KEY_TAB :\n return XK_Tab;\n case irr::KEY_RETURN :\n return XK_Return;\n case irr::KEY_MINUS :\n return XK_minus;\n case irr::KEY_OEM_7 :\n return XK_apostrophe;\n default:\n return irrcode;\n }\n}\n\nint sendKeyEvent(const char* disp, int keycode)\n{\n if(-1==keycode)\n return 0;\n printf(\"sendKeyEvent keycode: %d\\n\", keycode);\n Window winFocus;\n int revert;\n\n X11Display X11Display(disp);\n\n Display *display = XOpenDisplay(disp);\n if(NULL == display)\n return -1;\n Window winRoot = XDefaultRootWindow(display);\n \/\/XSetInputFocus(display, 1, revert, CurrentTime);\n XGetInputFocus(display, &winFocus, &revert);\n XKeyEvent event = createKeyEvent(display, winFocus, winRoot, true, keycode, 0);\n XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);\n event = createKeyEvent(display, winFocus, winRoot, false, keycode, 0);\n XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);\n XCloseDisplay(display);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <queue>\n#include <vector>\n#include <utility>\n\n#include <string>\n#include <stack>\n\nusing space std;\n\nstack<string> lv1;\nstack<string> lv2;\nstack<string> lv3;\n\nstring temp;\nint templv;\nint temptime=0;\n\nint read(int now){\n\tif(now < temptime) return 0;\n\n\tdo{\n\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tcin >>temptime>>templv>>temp;\n\t}while(temptime>=now);\n\n\n\n}\nint main(int argc, char const *argv[])\n{\n\t\twhlie(1){\n\t\t\tread();\n\t\t\tcout<<lv1.size()<<lv2.size()<<lv3.size();\n\t\t}\n\t \n\t\n\treturn 0;\n}<commit_msg>update uoj2254<commit_after>#include <stdio.h>\n#include <queue>\n#include <vector>\n#include <utility>\n\n#include <string>\n#include <stack>\n\nusing namespace std;\n\nstack<string> lv1;\nstack<string> lv2;\nstack<string> lv3;\n\nstring temp;\nint templv;\nint temptime=0;\n\nint read(int now){\n\tif(now < temptime) return 0;\n\n\tdo{\n\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tcin >>temptime>>templv>>temp;\n\t}while(temptime>=now);\n\n\n\n}\nint main(int argc, char const *argv[])\n{\n\t\twhlie(1){\n\t\t\tread();\n\t\t\tcout<<lv1.size()<<lv2.size()<<lv3.size();\n\t\t}\n\t \n\t\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Library General Public\nLicense version 2 as published by the Free Software Foundation.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLibrary General Public License for more details.\n\nYou should have received a copy of the GNU Library General Public License\nalong with this library; see the file COPYING.LIB. If not, write to\nthe Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\nBoston, MA 02110-1301, USA.\n*\/\n\n#include \"scenemodel.h\"\n#include <gluon\/gameobject.h>\n#include <typeinfo>\n#include <objectmanager.h>\n\n#include <debughelper.h>\n#include <qmimedata.h>\n#include <KLocalizedString>\n\nusing namespace Gluon;\nusing namespace Gluon::Creator;\n\nSceneModel::SceneModel(QObject* parent): QAbstractItemModel(parent)\n{\n m_root = 0;\n connect(ObjectManager::instance(), SIGNAL(newObject(Gluon::GameObject*)), SIGNAL(layoutChanged()));\n}\n\n\nGameObject* SceneModel::rootGameObject()\n{\n if(m_root) return m_root->childGameObject(0);\n return 0;\n}\n\n\nvoid SceneModel::setRootGameObject(GameObject* obj)\n{\n if(obj)\n {\n if(m_root) delete m_root;\n m_root = new GameObject(this);\n m_root->addChild(obj);\n reset();\n }\n}\n\nQVariant SceneModel::data(const QModelIndex& index, int role) const\n{\n if (index.isValid() && role == Qt::DisplayRole)\n {\n GameObject *item = static_cast<GameObject*>(index.internalPointer());\n\n if(item)\n return item->name();\n }\n\n return QVariant();\n}\n\nint SceneModel::columnCount(const QModelIndex&) const\n{\n return 1;\n}\n\nint SceneModel::rowCount(const QModelIndex& parent) const\n{\n GameObject *parentItem;\n if (parent.column() > 0)\n return 0;\n\n if (!parent.isValid())\n parentItem = m_root;\n else\n parentItem = static_cast<GameObject*>(parent.internalPointer());\n\n if(parentItem) return parentItem->childCount();\n return 0;\n}\n\nQModelIndex SceneModel::parent(const QModelIndex& child) const\n{\n if (!child.isValid())\n return QModelIndex();\n\n GameObject *childItem = static_cast<GameObject*>(child.internalPointer());\n GameObject *parentItem = childItem->parentGameObject();\n\n if (parentItem == m_root)\n return QModelIndex();\n\n return createIndex(rowIndex(parentItem), 0, parentItem);\n}\n\nQModelIndex SceneModel::index(int row, int column, const QModelIndex& parent) const\n{\n if (!hasIndex(row, column, parent))\n return QModelIndex();\n\n GameObject *parentItem;\n\n if (!parent.isValid())\n parentItem = m_root;\n else\n parentItem = static_cast<GameObject*>(parent.internalPointer());\n\n GameObject *childItem = parentItem->childGameObject(row);\n if (childItem)\n return createIndex(row, column, childItem);\n else\n return QModelIndex();\n}\n\nQVariant SceneModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n Q_UNUSED(section)\n Q_UNUSED(orientation)\n Q_UNUSED(role)\n\n return QVariant();\n}\n\nint SceneModel::rowIndex(GameObject* object) const\n{\n if(object && object->parentGameObject())\n {\n return object->parentGameObject()->childIndex(object);\n }\n return 0;\n}\n\n\nQt::DropActions SceneModel::supportedDropActions() const\n{\n return Qt::CopyAction | Qt::MoveAction;\n}\n\nQt::ItemFlags SceneModel::flags(const QModelIndex& index) const\n{\n if (index.isValid())\n return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n else\n return Qt::ItemIsDropEnabled | Qt::ItemIsEnabled;\n}\n\nbool SceneModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent)\n{\n DEBUG_FUNC_NAME\n\n DEBUG_TEXT(data->data(\"application\/x-qabstractitemmodeldatalist\"));\n return true;\n}\n\nbool SceneModel::setData(const QModelIndex& index, const QVariant& value, int role)\n{\n if (index.isValid() && role == Qt::EditRole) {\n static_cast<GluonObject*>(index.internalPointer())->setName(value.toString());\n emit dataChanged(index, index);\n return true;\n }\n return false;\n}\n\nbool SceneModel::insertRows(int row, int count, const QModelIndex& parent)\n{\n beginInsertRows(parent, row, row + count - 1);\n\n GameObject* obj = static_cast<GameObject*>(parent.internalPointer());\n for (int i = 0; i < count; ++i) {\n obj->addChild(new GameObject());\n }\n\n endInsertRows();\n return true;\n}\n\nbool SceneModel::removeRows(int row, int count, const QModelIndex& parent)\n{\n\n}\n\n\n\n#include \"scenemodel.moc\"\n\n<commit_msg>You can't do checks like that... but it still crashes on save for some to me utterly inexplicable reason - help!<commit_after>\/*\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Library General Public\nLicense version 2 as published by the Free Software Foundation.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLibrary General Public License for more details.\n\nYou should have received a copy of the GNU Library General Public License\nalong with this library; see the file COPYING.LIB. If not, write to\nthe Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\nBoston, MA 02110-1301, USA.\n*\/\n\n#include \"scenemodel.h\"\n#include <gluon\/gameobject.h>\n#include <typeinfo>\n#include <objectmanager.h>\n\n#include <debughelper.h>\n#include <qmimedata.h>\n#include <KLocalizedString>\n\nusing namespace Gluon;\nusing namespace Gluon::Creator;\n\nSceneModel::SceneModel(QObject* parent): QAbstractItemModel(parent)\n{\n m_root = 0;\n connect(ObjectManager::instance(), SIGNAL(newObject(Gluon::GameObject*)), SIGNAL(layoutChanged()));\n}\n\n\nGameObject* SceneModel::rootGameObject()\n{\n if(m_root) return m_root->childGameObject(0);\n return 0;\n}\n\n\nvoid SceneModel::setRootGameObject(GameObject* obj)\n{\n if(obj)\n {\n if(m_root) delete m_root;\n m_root = new GameObject(this);\n m_root->addChild(obj);\n reset();\n }\n}\n\nQVariant SceneModel::data(const QModelIndex& index, int role) const\n{\n if (index.isValid() && role == Qt::DisplayRole)\n {\n GameObject *item = static_cast<GameObject*>(index.internalPointer());\n\n if(item)\n return item->name();\n }\n\n return QVariant();\n}\n\nint SceneModel::columnCount(const QModelIndex&) const\n{\n return 1;\n}\n\nint SceneModel::rowCount(const QModelIndex& parent) const\n{\n GameObject *parentItem;\n if (parent.column() > 0)\n return 0;\n\n if (!parent.isValid())\n parentItem = m_root;\n else\n parentItem = static_cast<GameObject*>(parent.internalPointer());\n\n if(parentItem) return parentItem->childCount();\n return 0;\n}\n\nQModelIndex SceneModel::parent(const QModelIndex& child) const\n{\n if (!child.isValid())\n return QModelIndex();\n\n GameObject *childItem = static_cast<GameObject*>(child.internalPointer());\n \n if(!childItem)\n return QModelIndex();\n \n GameObject *parentItem = childItem->parentGameObject();\n\n if (parentItem == m_root)\n return QModelIndex();\n\n return createIndex(rowIndex(parentItem), 0, parentItem);\n}\n\nQModelIndex SceneModel::index(int row, int column, const QModelIndex& parent) const\n{\n if (!hasIndex(row, column, parent))\n return QModelIndex();\n\n GameObject *parentItem;\n\n if (!parent.isValid())\n parentItem = m_root;\n else\n parentItem = static_cast<GameObject*>(parent.internalPointer());\n\n GameObject *childItem = parentItem->childGameObject(row);\n if (childItem)\n return createIndex(row, column, childItem);\n else\n return QModelIndex();\n}\n\nQVariant SceneModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n Q_UNUSED(section)\n Q_UNUSED(orientation)\n Q_UNUSED(role)\n\n return QVariant();\n}\n\nint SceneModel::rowIndex(GameObject* object) const\n{\n if(object)\n {\n if(object->parentGameObject())\n {\n return object->parentGameObject()->childIndex(object);\n }\n }\n return 0;\n}\n\n\nQt::DropActions SceneModel::supportedDropActions() const\n{\n return Qt::CopyAction | Qt::MoveAction;\n}\n\nQt::ItemFlags SceneModel::flags(const QModelIndex& index) const\n{\n if (index.isValid())\n return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n else\n return Qt::ItemIsDropEnabled | Qt::ItemIsEnabled;\n}\n\nbool SceneModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent)\n{\n DEBUG_FUNC_NAME\n\n DEBUG_TEXT(data->data(\"application\/x-qabstractitemmodeldatalist\"));\n return true;\n}\n\nbool SceneModel::setData(const QModelIndex& index, const QVariant& value, int role)\n{\n if (index.isValid() && role == Qt::EditRole) {\n static_cast<GluonObject*>(index.internalPointer())->setName(value.toString());\n emit dataChanged(index, index);\n return true;\n }\n return false;\n}\n\nbool SceneModel::insertRows(int row, int count, const QModelIndex& parent)\n{\n beginInsertRows(parent, row, row + count - 1);\n\n GameObject* obj = static_cast<GameObject*>(parent.internalPointer());\n for (int i = 0; i < count; ++i) {\n obj->addChild(new GameObject());\n }\n\n endInsertRows();\n return true;\n}\n\nbool SceneModel::removeRows(int row, int count, const QModelIndex& parent)\n{\n\n}\n\n\n\n#include \"scenemodel.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/\/\n\/\/ fastcgi.hpp\n\/\/ ~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2017 Mohsen Khaki (mohsen dot khaki at gmail dot com)\n\/\/\n\/\/ Distributed under the MIT License\n\/\/\n\n#include <cstdint>\n#include <algorithm>\n\nnamespace FastCGI\n{\n\nenum class Type : uint8_t\n{\n\tBEGIN_REQUEST = 1, \/* [in] *\/\n\tABORT_REQUEST = 2, \/* [in] *\/\n\tEND_REQUEST = 3, \/* [out] *\/\n\tPARAM = 4, \/* [in] environment variables *\/\n\tSTDIN = 5, \/* [in] post data *\/\n\tSTDOUT = 6, \/* [out] response *\/\n\tSTDERR = 7, \/* [out] errors *\/\n\tDATA = 8, \/* [in] filter data *\/\n\tGET_VALUES = 9, \/* [in] *\/\n\tGET_VALUES_RESULT = 10, \/* [out] *\/\n\tUNKNOWN_TYPE = 11, \/* [out] *\/\n};\n\nstruct RecordHeader\n{\n\tuint8_t version = 0;\n\tType type = Type::UNKNOWN_TYPE;\n\tuint8_t requestIDB1 = 0;\n\tuint8_t requestIDB0 = 0;\n\tuint8_t contentLengthB1 = 0;\n\tuint8_t contentLengthB0 = 0;\n\tuint8_t paddingLength = 0;\n\tuint8_t reserved;\n\n\tuint16_t requestID() const\n\t{\n\t\treturn (static_cast<uint16_t>(requestIDB1) << 8) | requestIDB0;\n\t}\n\n\tvoid requestID(uint16_t id)\n\t{\n\t\trequestIDB0 = id & 0xff;\n\t\tid >>= 8;\n\t\trequestIDB1 = id & 0xff;\n\t}\n\n\tuint16_t contentLength() const\n\t{\n\t\treturn (static_cast<uint16_t>(contentLengthB1) << 8) | contentLengthB0;\n\t}\n\n\tvoid contentLength(uint16_t length)\n\t{\n\t\tpaddingLength = static_cast<uint8_t>(((static_cast<uint32_t>(length) + 7u) & ~uint32_t(7u)) - length);\n\t\tcontentLengthB0 = length & 0xff;\n\t\tlength >>= 8;\n\t\tcontentLengthB1 = length & 0xff;\n\t}\n};\n\nenum BeginRequestFlag : uint8_t\n{\n\tKEEP_CONN = 0x01,\n};\n\nenum class BeginRequestRoles : uint16_t\n{\n\tRESPONDER = 1,\n\tAUTHORIZER = 2,\n\tFILTER = 3,\n};\n\nenum class EndRequestProtocolStatus : uint8_t\n{\n\tREQUEST_COMPLETE = 0,\n\tCANT_MPX_CONN = 1,\n\tOVERLOADED = 2,\n\tUNKNOWN_ROLE = 3,\n};\n\nstruct Length\n{\n\tuint8_t lengthB3 = 0;\n\tuint8_t lengthB2 = 0;\n\tuint8_t lengthB1 = 0;\n\tuint8_t lengthB0 = 0;\n\tuint32_t length() const\n\t{\n\t\treturn (static_cast<uint32_t>(lengthB3 & 0x7fu) << 24) |\n\t\t (static_cast<uint32_t>(lengthB2) << 16) |\n\t\t (static_cast<uint32_t>(lengthB1) << 8) | lengthB0;\n\t}\n};\n\nstruct NameValue\n{\n\tNameValue()\n\t{\n\t}\n\tNameValue(const char* name, const uint32_t nameLength, const char* value, const uint32_t valueLength)\n\t\t: name(name), nameLength(nameLength), value(value), valueLength(valueLength)\n\t{\n\t}\n\tconst char* name = nullptr;\n\tuint32_t nameLength = 0;\n\tconst char* value = nullptr;\n\tuint32_t valueLength = 0;\n};\n\nstruct NameValueIterator\n{\n\tNameValueIterator()\n\t{\n\t}\n\tNameValueIterator(const char* buffer, const size_t length)\n\t{\n\t\tinitialize(buffer, length);\n\t}\n\tbool invalid() const\n\t{\n\t\treturn length_ == 0;\n\t}\n\tNameValueIterator operator++(int) const\n\t{\n\t\treturn NameValueIterator(buffer_ + sectionLength_, length_ - sectionLength_);\n\t}\n\tNameValueIterator& operator++()\n\t{\n\t\tif (length_ > sectionLength_)\n\t\t{\n\t\t\tinitialize(buffer_ + sectionLength_, length_ - sectionLength_);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tinitialize(buffer_ + sectionLength_, 0);\n\t\t}\n\t\treturn *this;\n\t}\n\n\tbool operator==(const NameValueIterator& other) const\n\t{\n\t\treturn buffer_ == other.buffer_ && length_ == other.length_;\n\t}\n\tbool operator!=(const NameValueIterator& other) const\n\t{\n\t\treturn !(*this == other);\n\t}\n\n\tconst NameValue& operator*() const\n\t{\n\t\treturn nameValue_;\n\t}\n\tconst NameValue* operator->() const\n\t{\n\t\treturn &nameValue_;\n\t}\n\n\tvoid initialize(const char* buffer, const size_t length)\n\t{\n\t\tbuffer_ = buffer;\n\t\tlength_ = length;\n\t\tif (length > 0)\n\t\t{\n\t\t\tuint32_t nameLength = readLength(buffer);\n\t\t\tuint32_t valueLength = readLength(buffer);\n\t\t\tnameValue_ = NameValue(buffer, nameLength, buffer + nameLength, valueLength);\n\t\t\tsectionLength_ = (buffer + nameLength + valueLength - buffer_);\n\t\t}\n\t}\n\n\tstatic uint32_t readLength(const char*& buffer)\n\t{\n\t\tuint8_t lengthB0 = *reinterpret_cast<const uint8_t*>(buffer);\n\t\tif ((lengthB0 & 0x80u) == 0)\n\t\t{\n\t\t\tbuffer += 1;\n\t\t\treturn lengthB0;\n\t\t}\n\t\tLength length;\n\t\tstd::copy(buffer, buffer + sizeof(length), reinterpret_cast<char*>(&length));\n\t\tbuffer += sizeof(length);\n\t\treturn length.length();\n\t}\n\n\tNameValue nameValue_;\n\tconst char* buffer_ = nullptr;\n\tsize_t sectionLength_ = 0;\n\tsize_t length_ = 0;\n\n};\n\n\nstruct BeginRequest\n{\n\tuint8_t roleB1 = 0;\n\tuint8_t roleB0 = 0;\n\tuint8_t flags = 0;\n\tuint8_t reserved[5];\n\tBeginRequestRoles role() const\n\t{\n\t\treturn static_cast<BeginRequestRoles>((static_cast<uint16_t>(roleB1) << 8) | roleB0);\n\t}\n\tvoid role(const BeginRequestRoles role)\n\t{\n\t\tuint16_t roleValue = static_cast<uint16_t>(role);\n\t\troleB0 = roleValue & 0xff;\n\t\troleValue >>= 8;\n\t\troleB1 = roleValue & 0xff;\n\t}\n};\n\nstruct EndRequest\n{\n\tuint8_t appStatusB3 = 0;\n\tuint8_t appStatusB2 = 0;\n\tuint8_t appStatusB1 = 0;\n\tuint8_t appStatusB0 = 0;\n\tEndRequestProtocolStatus protocolStatus = EndRequestProtocolStatus::REQUEST_COMPLETE;\n\tuint8_t reserved[3];\n\tint32_t appStatus() const\n\t{\n\t\treturn (static_cast<uint32_t>(appStatusB3) << 24) |\n\t\t (static_cast<uint32_t>(appStatusB2) << 16) |\n\t\t (static_cast<uint32_t>(appStatusB1) << 8) | appStatusB0;\n\t}\n\tvoid appStatus(const int32_t status)\n\t{\n\t\tuint32_t statusValue = static_cast<uint32_t>(status);\n\t\tappStatusB0 = statusValue & 0xff;\n\t\tstatusValue >>= 8;\n\t\tappStatusB1 = statusValue & 0xff;\n\t\tstatusValue >>= 8;\n\t\tappStatusB2 = statusValue & 0xff;\n\t\tstatusValue >>= 8;\n\t\tappStatusB3 = statusValue & 0xff;\n\t}\n};\n\nstruct UnknownType\n{\n\tuint8_t type;\n\tuint8_t reserved[7];\n};\n\ntemplate<Type TYPE>\nstruct Atom {};\n\nclass Decoder\n{\npublic:\n\ttemplate<class HANDLER>\n\tvoid write(const char* buffer, size_t lengthInBytes, HANDLER& handler)\n\t{\n\t\tif (!buffer_.empty())\n\t\t{\n\t\t\twhile (expected_ > buffer_.size())\n\t\t\t{\n\t\t\t\tconst size_t length = std::min(expected_, lengthInBytes);\n\t\t\t\tbuffer_.insert(buffer_.end(), buffer, buffer + length);\n\t\t\t\tbuffer += length;\n\t\t\t\tlengthInBytes -= length;\n\t\t\t\tif (!decode(buffer_.data(), buffer_.size(), expected_, handler) || lengthInBytes == 0)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (buffer_.size() >= expected_)\n\t\t\t\t{\n\t\t\t\t\tbuffer_.clear();\n\t\t\t\t\texpected_ = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twhile (true)\n\t\t{\n\t\t\tif (!decode(buffer, lengthInBytes, expected_, handler))\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (lengthInBytes < expected_)\n\t\t\t{\n\t\t\t\tbuffer_.assign(buffer, buffer + lengthInBytes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlengthInBytes -= expected_;\n\t\t\tbuffer += expected_;\n\t\t}\n\t}\nprivate:\n\ttemplate<class HANDLER>\n\tstatic bool decode(const char* buffer, size_t length, size_t& expected, HANDLER& handler)\n\t{\n\t\tif (length < sizeof(RecordHeader))\n\t\t{\n\t\t\texpected = sizeof(RecordHeader);\n\t\t\treturn true;\n\t\t}\n\t\tRecordHeader header;\n\t\tstd::copy(buffer, buffer + sizeof(RecordHeader), reinterpret_cast<char*>(&header));\n\t\tconst size_t contentLength = header.contentLength();\n\t\texpected = sizeof(RecordHeader) + contentLength + header.paddingLength;\n\t\tif (expected > length)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\tbuffer += sizeof(RecordHeader);\n\t\tswitch (header.type)\n\t\t{\n\t\tcase Type::BEGIN_REQUEST:\n\t\t{\n\t\t\tBeginRequest beginRequest;\n\t\t\tstd::copy(buffer, buffer + sizeof(beginRequest), reinterpret_cast<char*>(&beginRequest));\n\t\t\treturn handler(Atom<Type::BEGIN_REQUEST>(), header, beginRequest);\n\t\t}\n\t\tcase Type::ABORT_REQUEST:\n\t\t{\n\t\t\treturn handler(Atom<Type::ABORT_REQUEST>(), header);\n\t\t}\n\t\tcase Type::END_REQUEST:\n\t\t{\n\t\t\tEndRequest endRequest;\n\t\t\tstd::copy(buffer, buffer + sizeof(endRequest), reinterpret_cast<char*>(&endRequest));\n\t\t\treturn handler(Atom<Type::END_REQUEST>(), header, endRequest);\n\t\t}\n\t\tcase Type::PARAM:\n\t\t{\n\t\t\tconst char* endParams = buffer + contentLength;\n\t\t\treturn handler(Atom<Type::PARAM>(), header, NameValueIterator(buffer, contentLength), NameValueIterator(endParams, 0));\n\t\t}\n\t\tcase Type::STDIN:\n\t\t{\n\t\t\treturn handler(Atom<Type::STDIN>(), header, buffer, contentLength);\n\t\t}\n\t\tcase Type::STDOUT:\n\t\t{\n\t\t\treturn handler(Atom<Type::STDOUT>(), header, buffer, contentLength);\n\t\t}\n\t\tcase Type::STDERR:\n\t\t{\n\t\t\treturn handler(Atom<Type::STDERR>(), header, buffer, contentLength);\n\t\t}\n\t\tcase Type::DATA:\n\t\t{\n\t\t\treturn handler(Atom<Type::DATA>(), header, buffer, contentLength);\n\t\t}\n\t\tcase Type::GET_VALUES:\n\t\t{\n\t\t\tconst char* endParams = buffer + contentLength;\n\t\t\treturn handler(Atom<Type::GET_VALUES>(), header, NameValueIterator(buffer, contentLength), NameValueIterator(endParams, 0));\n\t\t}\n\t\tcase Type::GET_VALUES_RESULT:\n\t\t{\n\t\t\tconst char* endParams = buffer + contentLength;\n\t\t\treturn handler(Atom<Type::GET_VALUES_RESULT>(), header, NameValueIterator(buffer, contentLength), NameValueIterator(endParams, 0));\n\t\t}\n\t\tcase Type::UNKNOWN_TYPE:\n\t\t{\n\t\t\treturn handler(Atom<Type::UNKNOWN_TYPE>(), header, buffer, contentLength);\n\t\t}\n\t\t}\n\t\treturn handler(header, buffer, contentLength);\n\t}\n\tstd::vector<char> buffer_;\n\tsize_t expected_ = 0;\n};\n\n}\n<commit_msg>Fix the usage of left over bytes<commit_after>#pragma once\n\n\/\/\n\/\/ fastcgi.hpp\n\/\/ ~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2017 Mohsen Khaki (mohsen dot khaki at gmail dot com)\n\/\/\n\/\/ Distributed under the MIT License\n\/\/\n\n#include <cstdint>\n#include <algorithm>\n\nnamespace FastCGI\n{\n\nenum class Type : uint8_t\n{\n\tBEGIN_REQUEST = 1, \/* [in] *\/\n\tABORT_REQUEST = 2, \/* [in] *\/\n\tEND_REQUEST = 3, \/* [out] *\/\n\tPARAM = 4, \/* [in] environment variables *\/\n\tSTDIN = 5, \/* [in] post data *\/\n\tSTDOUT = 6, \/* [out] response *\/\n\tSTDERR = 7, \/* [out] errors *\/\n\tDATA = 8, \/* [in] filter data *\/\n\tGET_VALUES = 9, \/* [in] *\/\n\tGET_VALUES_RESULT = 10, \/* [out] *\/\n\tUNKNOWN_TYPE = 11, \/* [out] *\/\n};\n\nstruct RecordHeader\n{\n\tuint8_t version = 0;\n\tType type = Type::UNKNOWN_TYPE;\n\tuint8_t requestIDB1 = 0;\n\tuint8_t requestIDB0 = 0;\n\tuint8_t contentLengthB1 = 0;\n\tuint8_t contentLengthB0 = 0;\n\tuint8_t paddingLength = 0;\n\tuint8_t reserved;\n\n\tuint16_t requestID() const\n\t{\n\t\treturn (static_cast<uint16_t>(requestIDB1) << 8) | requestIDB0;\n\t}\n\n\tvoid requestID(uint16_t id)\n\t{\n\t\trequestIDB0 = id & 0xff;\n\t\tid >>= 8;\n\t\trequestIDB1 = id & 0xff;\n\t}\n\n\tuint16_t contentLength() const\n\t{\n\t\treturn (static_cast<uint16_t>(contentLengthB1) << 8) | contentLengthB0;\n\t}\n\n\tvoid contentLength(uint16_t length)\n\t{\n\t\tpaddingLength = static_cast<uint8_t>(((static_cast<uint32_t>(length) + 7u) & ~uint32_t(7u)) - length);\n\t\tcontentLengthB0 = length & 0xff;\n\t\tlength >>= 8;\n\t\tcontentLengthB1 = length & 0xff;\n\t}\n};\n\nenum BeginRequestFlag : uint8_t\n{\n\tKEEP_CONN = 0x01,\n};\n\nenum class BeginRequestRoles : uint16_t\n{\n\tRESPONDER = 1,\n\tAUTHORIZER = 2,\n\tFILTER = 3,\n};\n\nenum class EndRequestProtocolStatus : uint8_t\n{\n\tREQUEST_COMPLETE = 0,\n\tCANT_MPX_CONN = 1,\n\tOVERLOADED = 2,\n\tUNKNOWN_ROLE = 3,\n};\n\nstruct Length\n{\n\tuint8_t lengthB3 = 0;\n\tuint8_t lengthB2 = 0;\n\tuint8_t lengthB1 = 0;\n\tuint8_t lengthB0 = 0;\n\tuint32_t length() const\n\t{\n\t\treturn (static_cast<uint32_t>(lengthB3 & 0x7fu) << 24) |\n\t\t (static_cast<uint32_t>(lengthB2) << 16) |\n\t\t (static_cast<uint32_t>(lengthB1) << 8) | lengthB0;\n\t}\n};\n\nstruct NameValue\n{\n\tNameValue()\n\t{\n\t}\n\tNameValue(const char* name, const uint32_t nameLength, const char* value, const uint32_t valueLength)\n\t\t: name(name), nameLength(nameLength), value(value), valueLength(valueLength)\n\t{\n\t}\n\tconst char* name = nullptr;\n\tuint32_t nameLength = 0;\n\tconst char* value = nullptr;\n\tuint32_t valueLength = 0;\n};\n\nstruct NameValueIterator\n{\n\tNameValueIterator()\n\t{\n\t}\n\tNameValueIterator(const char* buffer, const size_t length)\n\t{\n\t\tinitialize(buffer, length);\n\t}\n\tbool invalid() const\n\t{\n\t\treturn length_ == 0;\n\t}\n\tNameValueIterator operator++(int) const\n\t{\n\t\treturn NameValueIterator(buffer_ + sectionLength_, length_ - sectionLength_);\n\t}\n\tNameValueIterator& operator++()\n\t{\n\t\tif (length_ > sectionLength_)\n\t\t{\n\t\t\tinitialize(buffer_ + sectionLength_, length_ - sectionLength_);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tinitialize(buffer_ + sectionLength_, 0);\n\t\t}\n\t\treturn *this;\n\t}\n\n\tbool operator==(const NameValueIterator& other) const\n\t{\n\t\treturn buffer_ == other.buffer_ && length_ == other.length_;\n\t}\n\tbool operator!=(const NameValueIterator& other) const\n\t{\n\t\treturn !(*this == other);\n\t}\n\n\tconst NameValue& operator*() const\n\t{\n\t\treturn nameValue_;\n\t}\n\tconst NameValue* operator->() const\n\t{\n\t\treturn &nameValue_;\n\t}\n\n\tvoid initialize(const char* buffer, const size_t length)\n\t{\n\t\tbuffer_ = buffer;\n\t\tlength_ = length;\n\t\tif (length > 0)\n\t\t{\n\t\t\tuint32_t nameLength = readLength(buffer);\n\t\t\tuint32_t valueLength = readLength(buffer);\n\t\t\tnameValue_ = NameValue(buffer, nameLength, buffer + nameLength, valueLength);\n\t\t\tsectionLength_ = (buffer + nameLength + valueLength - buffer_);\n\t\t}\n\t}\n\n\tstatic uint32_t readLength(const char*& buffer)\n\t{\n\t\tuint8_t lengthB0 = *reinterpret_cast<const uint8_t*>(buffer);\n\t\tif ((lengthB0 & 0x80u) == 0)\n\t\t{\n\t\t\tbuffer += 1;\n\t\t\treturn lengthB0;\n\t\t}\n\t\tLength length;\n\t\tstd::copy(buffer, buffer + sizeof(length), reinterpret_cast<char*>(&length));\n\t\tbuffer += sizeof(length);\n\t\treturn length.length();\n\t}\n\n\tNameValue nameValue_;\n\tconst char* buffer_ = nullptr;\n\tsize_t sectionLength_ = 0;\n\tsize_t length_ = 0;\n\n};\n\n\nstruct BeginRequest\n{\n\tuint8_t roleB1 = 0;\n\tuint8_t roleB0 = 0;\n\tuint8_t flags = 0;\n\tuint8_t reserved[5];\n\tBeginRequestRoles role() const\n\t{\n\t\treturn static_cast<BeginRequestRoles>((static_cast<uint16_t>(roleB1) << 8) | roleB0);\n\t}\n\tvoid role(const BeginRequestRoles role)\n\t{\n\t\tuint16_t roleValue = static_cast<uint16_t>(role);\n\t\troleB0 = roleValue & 0xff;\n\t\troleValue >>= 8;\n\t\troleB1 = roleValue & 0xff;\n\t}\n};\n\nstruct EndRequest\n{\n\tuint8_t appStatusB3 = 0;\n\tuint8_t appStatusB2 = 0;\n\tuint8_t appStatusB1 = 0;\n\tuint8_t appStatusB0 = 0;\n\tEndRequestProtocolStatus protocolStatus = EndRequestProtocolStatus::REQUEST_COMPLETE;\n\tuint8_t reserved[3];\n\tint32_t appStatus() const\n\t{\n\t\treturn (static_cast<uint32_t>(appStatusB3) << 24) |\n\t\t (static_cast<uint32_t>(appStatusB2) << 16) |\n\t\t (static_cast<uint32_t>(appStatusB1) << 8) | appStatusB0;\n\t}\n\tvoid appStatus(const int32_t status)\n\t{\n\t\tuint32_t statusValue = static_cast<uint32_t>(status);\n\t\tappStatusB0 = statusValue & 0xff;\n\t\tstatusValue >>= 8;\n\t\tappStatusB1 = statusValue & 0xff;\n\t\tstatusValue >>= 8;\n\t\tappStatusB2 = statusValue & 0xff;\n\t\tstatusValue >>= 8;\n\t\tappStatusB3 = statusValue & 0xff;\n\t}\n};\n\nstruct UnknownType\n{\n\tuint8_t type;\n\tuint8_t reserved[7];\n};\n\ntemplate<Type TYPE>\nstruct Atom {};\n\nclass Decoder\n{\npublic:\n\ttemplate<class HANDLER>\n\tvoid write(const char* buffer, size_t lengthInBytes, HANDLER& handler)\n\t{\n\t\tif (!buffer_.empty())\n\t\t{\n\t\t\twhile (expected_ > buffer_.size())\n\t\t\t{\n\t\t\t\tconst size_t length = std::min(expected_ - buffer_.size(), lengthInBytes);\n\t\t\t\tbuffer_.insert(buffer_.end(), buffer, buffer + length);\n\t\t\t\tbuffer += length;\n\t\t\t\tlengthInBytes -= length;\n\t\t\t\tif (!decode(buffer_.data(), buffer_.size(), expected_, handler) || lengthInBytes == 0)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (buffer_.size() >= expected_)\n\t\t\t\t{\n\t\t\t\t\tbuffer_.clear();\n\t\t\t\t\texpected_ = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twhile (true)\n\t\t{\n\t\t\tif (!decode(buffer, lengthInBytes, expected_, handler))\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (lengthInBytes < expected_)\n\t\t\t{\n\t\t\t\tbuffer_.assign(buffer, buffer + lengthInBytes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlengthInBytes -= expected_;\n\t\t\tbuffer += expected_;\n\t\t}\n\t}\nprivate:\n\ttemplate<class HANDLER>\n\tstatic bool decode(const char* buffer, size_t length, size_t& expected, HANDLER& handler)\n\t{\n\t\tif (length < sizeof(RecordHeader))\n\t\t{\n\t\t\texpected = sizeof(RecordHeader);\n\t\t\treturn true;\n\t\t}\n\t\tRecordHeader header;\n\t\tstd::copy(buffer, buffer + sizeof(RecordHeader), reinterpret_cast<char*>(&header));\n\t\tconst size_t contentLength = header.contentLength();\n\t\texpected = sizeof(RecordHeader) + contentLength + header.paddingLength;\n\t\tif (expected > length)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\tbuffer += sizeof(RecordHeader);\n\t\tswitch (header.type)\n\t\t{\n\t\tcase Type::BEGIN_REQUEST:\n\t\t{\n\t\t\tBeginRequest beginRequest;\n\t\t\tstd::copy(buffer, buffer + sizeof(beginRequest), reinterpret_cast<char*>(&beginRequest));\n\t\t\treturn handler(Atom<Type::BEGIN_REQUEST>(), header, beginRequest);\n\t\t}\n\t\tcase Type::ABORT_REQUEST:\n\t\t{\n\t\t\treturn handler(Atom<Type::ABORT_REQUEST>(), header);\n\t\t}\n\t\tcase Type::END_REQUEST:\n\t\t{\n\t\t\tEndRequest endRequest;\n\t\t\tstd::copy(buffer, buffer + sizeof(endRequest), reinterpret_cast<char*>(&endRequest));\n\t\t\treturn handler(Atom<Type::END_REQUEST>(), header, endRequest);\n\t\t}\n\t\tcase Type::PARAM:\n\t\t{\n\t\t\tconst char* endParams = buffer + contentLength;\n\t\t\treturn handler(Atom<Type::PARAM>(), header, NameValueIterator(buffer, contentLength), NameValueIterator(endParams, 0));\n\t\t}\n\t\tcase Type::STDIN:\n\t\t{\n\t\t\treturn handler(Atom<Type::STDIN>(), header, buffer, contentLength);\n\t\t}\n\t\tcase Type::STDOUT:\n\t\t{\n\t\t\treturn handler(Atom<Type::STDOUT>(), header, buffer, contentLength);\n\t\t}\n\t\tcase Type::STDERR:\n\t\t{\n\t\t\treturn handler(Atom<Type::STDERR>(), header, buffer, contentLength);\n\t\t}\n\t\tcase Type::DATA:\n\t\t{\n\t\t\treturn handler(Atom<Type::DATA>(), header, buffer, contentLength);\n\t\t}\n\t\tcase Type::GET_VALUES:\n\t\t{\n\t\t\tconst char* endParams = buffer + contentLength;\n\t\t\treturn handler(Atom<Type::GET_VALUES>(), header, NameValueIterator(buffer, contentLength), NameValueIterator(endParams, 0));\n\t\t}\n\t\tcase Type::GET_VALUES_RESULT:\n\t\t{\n\t\t\tconst char* endParams = buffer + contentLength;\n\t\t\treturn handler(Atom<Type::GET_VALUES_RESULT>(), header, NameValueIterator(buffer, contentLength), NameValueIterator(endParams, 0));\n\t\t}\n\t\tcase Type::UNKNOWN_TYPE:\n\t\t{\n\t\t\treturn handler(Atom<Type::UNKNOWN_TYPE>(), header, buffer, contentLength);\n\t\t}\n\t\t}\n\t\treturn handler(header, buffer, contentLength);\n\t}\n\tstd::vector<char> buffer_;\n\tsize_t expected_ = 0;\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ (C) 2014 Arek Olek\n\n#pragma once\n\n#include <iostream>\n\n#include <boost\/graph\/adjacency_list.hpp>\n#include <boost\/graph\/graphviz.hpp>\n\nstruct red_points_dashed {\n void operator()(std::ostream& out) const {\n out << \"node [shape=point color=brown]\" << std::endl;\n out << \"edge [style=dashed color=burlywood1]\" << std::endl;\n }\n};\n\ntemplate <class Graph>\nclass node_writer {\npublic:\n node_writer(Graph const& t) : T(t) {}\n template <class V>\n void operator()(std::ostream& out, const V& v) const {\n if(degree(v, T) == 1)\n out << \"[color=green]\";\n if(degree(v, T) > 2)\n out << \"[color=red]\";\n }\nprivate:\n Graph const& T;\n};\n\ntemplate <class Graph>\nnode_writer<Graph> make_node_writer(Graph t) {\n return node_writer<Graph>(t);\n}\n\ntemplate <class Graph>\nclass edge_writer {\npublic:\n edge_writer(Graph const& g, Graph const& t) : G(g), T(t) {}\n template <class E>\n void operator()(std::ostream& out, const E& e) const {\n auto vs = adjacent_vertices(source(e, G), T);\n for(auto vit = vs.first; vit != vs.second; ++vit)\n if(*vit == target(e, G)) {\n out << \"[style=solid color=burlywood]\";\n break;\n }\n }\nprivate:\n Graph const& G;\n Graph const& T;\n};\n\ntemplate <class Graph>\nedge_writer<Graph> make_edge_writer(Graph g, Graph t) {\n return edge_writer<Graph>(g, t);\n}\n\ntemplate<class Graph>\nvoid show(std::string file, Graph g, Graph t) {\n std::ofstream f(file);\n write_graphviz(f, g,\n make_node_writer(t), make_edge_writer(g, t), red_points_dashed());\n f.close();\n}\n\n<commit_msg>refactor debug methods<commit_after>\/\/ (C) 2014 Arek Olek\n\n#pragma once\n\n#include <iostream>\n\n#include <boost\/graph\/adjacency_list.hpp>\n#include <boost\/graph\/graphviz.hpp>\n\nstruct red_points_dashed {\n void operator()(std::ostream& out) const {\n out << \"node [shape=point color=brown]\" << std::endl;\n out << \"edge [style=dashed color=burlywood1]\" << std::endl;\n }\n};\n\ntemplate <class Graph>\nclass node_writer {\npublic:\n node_writer(Graph const& t) : T(t) {}\n template <class V>\n void operator()(std::ostream& out, const V& v) const {\n if(degree(v, T) == 1)\n out << \"[color=green]\";\n if(degree(v, T) > 2)\n out << \"[color=red]\";\n }\nprivate:\n Graph const& T;\n};\n\ntemplate <class Graph>\nnode_writer<Graph> make_node_writer(Graph t) {\n return node_writer<Graph>(t);\n}\n\ntemplate<class Graph, class Tree>\nclass edge_writer {\npublic:\n edge_writer(Graph const& g, Tree const& t) : G(g), T(t) {}\n template <class E>\n void operator()(std::ostream& out, const E& e) const {\n auto vs = adjacent_vertices(source(e, G), T);\n for(auto vit = vs.first; vit != vs.second; ++vit)\n if(*vit == target(e, G)) {\n out << \"[style=solid color=burlywood]\";\n break;\n }\n }\nprivate:\n Graph const& G;\n Tree const& T;\n};\n\ntemplate<class Graph, class Tree>\nedge_writer<Graph, Tree> make_edge_writer(Graph g, Tree t) {\n return edge_writer<Graph, Tree>(g, t);\n}\n\ntemplate<class Graph, class Tree>\nvoid show(std::string file, Graph g, Tree t) {\n std::ofstream f(file);\n write_graphviz(f, g,\n make_node_writer(t), make_edge_writer(g, t), red_points_dashed());\n f.close();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ @file init_tasks.cpp\n\/\/\/\n\/\/\/ @brief Implementation of init_tasks.hpp\n\/\/\/ @date 12\/09\/2015\n\/\/\/\n\/\/\/ (c) Koheron 2014-2015\n\n#include \"init_tasks.hpp\"\n\n#include <cstdio>\n#include <cstring>\n\nextern \"C\" {\n #include <sys\/socket.h>\n #include <sys\/types.h> \n #include <arpa\/inet.h>\n #include <ifaddrs.h>\n}\n\n#include \"..\/drivers\/core\/wr_register.hpp\"\n\nInitTasks::InitTasks(Klib::DevMem& dev_mem_)\n: dev_mem(dev_mem_)\n{}\n\n#define LED_ADDR 0x43C00000\n#define MAP_SIZE 4096\n#define LED_OFFSET 0x0\n\nvoid InitTasks::show_ip_on_leds()\n{\n\/\/ http:\/\/stackoverflow.com\/questions\/20800319\/how-to-get-my-ip-address-in-c-linux\n \n struct ifaddrs *addrs;\n getifaddrs(&addrs);\n ifaddrs *tmp = addrs;\n\n \/\/ Turn all the leds ON\n Klib::MemMapID dev_num = dev_mem.AddMemoryMap(LED_ADDR, 16*MAP_SIZE);\n Klib::WriteReg32(dev_mem.GetBaseAddr(dev_num) + LED_OFFSET, 255);\n\n char interface[] = \"eth0\";\n\n while(tmp) {\n \/\/ Works only for IPv4 address\n if(tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) { \n struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;\n int val = strcmp(tmp->ifa_name,interface);\n \n if(val != 0) {\n tmp = tmp->ifa_next;\n continue;\n }\n \n \/\/ Interface found\n printf(\"Interface %s found: %s\\n\", \n tmp->ifa_name, inet_ntoa(pAddr->sin_addr));\n uint32_t ip = htonl(pAddr->sin_addr.s_addr);\n\n \/\/ Write IP address in FPGA memory\n \/\/ The 8 Least Significant Bits should be connected to the FPGA LEDs\n Klib::WriteReg32(dev_mem.GetBaseAddr(dev_num) + LED_OFFSET, ip);\n\n break;\n }\n \n tmp = tmp->ifa_next;\n }\n\n freeifaddrs(addrs);\n dev_mem.RmMemoryMap(dev_num);\n}\n<commit_msg>Clean up<commit_after>\/\/\/ Implementation of init_tasks.hpp\n\/\/\/\n\/\/\/ (c) Koheron\n\n#include \"init_tasks.hpp\"\n\n#include <cstdio>\n#include <cstring>\n\nextern \"C\" {\n #include <sys\/socket.h>\n #include <sys\/types.h> \n #include <arpa\/inet.h>\n #include <ifaddrs.h>\n}\n\n#include \"..\/drivers\/core\/wr_register.hpp\"\n\nInitTasks::InitTasks(Klib::DevMem& dev_mem_)\n: dev_mem(dev_mem_)\n{}\n\n#define LED_ADDR 0x43C00000\n#define MAP_SIZE 4096\n#define LED_OFFSET 0x0\n\nvoid InitTasks::show_ip_on_leds()\n{\n\/\/ http:\/\/stackoverflow.com\/questions\/20800319\/how-to-get-my-ip-address-in-c-linux\n \n struct ifaddrs *addrs;\n getifaddrs(&addrs);\n ifaddrs *tmp = addrs;\n\n \/\/ Turn all the leds ON\n Klib::MemMapID dev_num = dev_mem.AddMemoryMap(LED_ADDR, 16*MAP_SIZE);\n Klib::WriteReg32(dev_mem.GetBaseAddr(dev_num) + LED_OFFSET, 255);\n\n char interface[] = \"eth0\";\n\n while(tmp) {\n \/\/ Works only for IPv4 address\n if(tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) { \n struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;\n int val = strcmp(tmp->ifa_name,interface);\n \n if(val != 0) {\n tmp = tmp->ifa_next;\n continue;\n }\n \n \/\/ Interface found\n printf(\"Interface %s found: %s\\n\", \n tmp->ifa_name, inet_ntoa(pAddr->sin_addr));\n uint32_t ip = htonl(pAddr->sin_addr.s_addr);\n\n \/\/ Write IP address in FPGA memory\n \/\/ The 8 Least Significant Bits should be connected to the FPGA LEDs\n Klib::WriteReg32(dev_mem.GetBaseAddr(dev_num) + LED_OFFSET, ip);\n\n break;\n }\n \n tmp = tmp->ifa_next;\n }\n\n freeifaddrs(addrs);\n dev_mem.RmMemoryMap(dev_num);\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (C) 2015 Mark Charlebois. All rights reserved.\n * Author: @author Mark Charlebois <charlebm#gmail.com>\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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 * @file px4_posix_tasks.c\n * Implementation of existing task API for Linux\n *\/\n\n#include <px4_log.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <stdbool.h>\n\n#if !defined(__PX4_QURT)\n#include <signal.h>\n#endif\n\n#include <fcntl.h>\n#include <sched.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <string>\n\n#include <px4_tasks.h>\n\n#define MAX_CMD_LEN 100\n\n#define PX4_MAX_TASKS 50\n#define SHELL_TASK_ID (PX4_MAX_TASKS+1)\n\npthread_t _shell_task_id = 0;\n\nstruct task_entry {\n\tpthread_t pid;\n\tstd::string name;\n\tbool isused;\n\ttask_entry() : isused(false) {}\n};\n\nstatic task_entry taskmap[PX4_MAX_TASKS];\n\ntypedef struct {\n\tpx4_main_t entry;\n\tint argc;\n\tchar *argv[];\n\t\/\/ strings are allocated after the\n} pthdata_t;\n\nstatic void *entry_adapter(void *ptr)\n{\n\tpthdata_t *data;\n\tdata = (pthdata_t *) ptr;\n\n\tdata->entry(data->argc, data->argv);\n\tPX4_WARN(\"Before waiting infinte busy loop\");\n\t\/\/for( ;; )\n\t\/\/{\n\t\/\/ volatile int x = 0;\n\t\/\/ ++x;\n\t\/\/ }\n\tfree(ptr);\n\tpx4_task_exit(0);\n\n\treturn NULL;\n}\n\nvoid\npx4_systemreset(bool to_bootloader)\n{\n\tPX4_WARN(\"Called px4_system_reset\");\n}\n\npx4_task_t px4_task_spawn_cmd(const char *name, int scheduler, int priority, int stack_size, px4_main_t entry,\n\t\t\t char *const argv[])\n{\n\tint rv;\n\tint argc = 0;\n\tint i;\n\tunsigned int len = 0;\n\tunsigned long offset;\n\tunsigned long structsize;\n\tchar *p = (char *)argv;\n\n\tPX4_DEBUG(\"Creating %s\\n\", name);\n\tpthread_t task;\n\tpthread_attr_t attr;\n\tstruct sched_param param;\n\n\t\/\/ Calculate argc\n\twhile (p != (char *)0) {\n\t\tp = argv[argc];\n\n\t\tif (p == (char *)0) {\n\t\t\tbreak;\n\t\t}\n\n\t\t++argc;\n\t\tlen += strlen(p) + 1;\n\t}\n\n\tstructsize = sizeof(pthdata_t) + (argc + 1) * sizeof(char *);\n\tpthdata_t *taskdata;\n\n\t\/\/ not safe to pass stack data to the thread creation\n\ttaskdata = (pthdata_t *)malloc(structsize + len);\n\toffset = ((unsigned long)taskdata) + structsize;\n\n\ttaskdata->entry = entry;\n\ttaskdata->argc = argc;\n\n\tfor (i = 0; i < argc; i++) {\n\t\tPX4_DEBUG(\"arg %d %s\\n\", i, argv[i]);\n\t\ttaskdata->argv[i] = (char *)offset;\n\t\tstrcpy((char *)offset, argv[i]);\n\t\toffset += strlen(argv[i]) + 1;\n\t}\n\n\t\/\/ Must add NULL at end of argv\n\ttaskdata->argv[argc] = (char *)0;\n\n\trv = pthread_attr_init(&attr);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to init thread attrs\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n#if 0\n\trv = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to set inherit sched\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n\trv = pthread_attr_setschedpolicy(&attr, scheduler);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to set sched policy\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n#endif\n\tsize_t fixed_stacksize = -1;\n\tpthread_attr_getstacksize(&attr, &fixed_stacksize);\n\tPX4_WARN(\"stack size: %d passed stacksize(%d)\", fixed_stacksize, stack_size);\n\tfixed_stacksize = 8 * 1024;\n\tfixed_stacksize = (fixed_stacksize < (size_t)stack_size) ? (size_t)stack_size : fixed_stacksize;\n\n\tPX4_WARN(\"setting the thread[%s] stack size to[%d]\", name, fixed_stacksize);\n\tpthread_attr_setstacksize(&attr, fixed_stacksize);\n\t\/\/pthread_attr_setstacksize(&attr, stack_size);\n\n\n\tparam.sched_priority = priority;\n\n\trv = pthread_attr_setschedparam(&attr, ¶m);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to set sched param\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n\trv = pthread_create(&task, &attr, &entry_adapter, (void *) taskdata);\n\n\tif (rv != 0) {\n\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n\tfor (i = 0; i < PX4_MAX_TASKS; ++i) {\n\t\tif (taskmap[i].isused == false) {\n\t\t\ttaskmap[i].pid = task;\n\t\t\ttaskmap[i].name = name;\n\t\t\ttaskmap[i].isused = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (i >= PX4_MAX_TASKS) {\n\t\treturn -ENOSPC;\n\t}\n\n\treturn i;\n}\n\nint px4_task_delete(px4_task_t id)\n{\n\tint rv = 0;\n\tpthread_t pid;\n\tPX4_WARN(\"Called px4_task_delete\");\n\n\tif (id < PX4_MAX_TASKS && taskmap[id].isused) {\n\t\tpid = taskmap[id].pid;\n\n\t} else {\n\t\treturn -EINVAL;\n\t}\n\n\t\/\/ If current thread then exit, otherwise cancel\n\tif (pthread_self() == pid) {\n\t\ttaskmap[id].isused = false;\n\t\tpthread_exit(0);\n\n\t} else {\n\t\trv = pthread_cancel(pid);\n\t}\n\n\ttaskmap[id].isused = false;\n\n\treturn rv;\n}\n\nvoid px4_task_exit(int ret)\n{\n\tint i;\n\tpthread_t pid = pthread_self();\n\n\t\/\/ Get pthread ID from the opaque ID\n\tfor (i = 0; i < PX4_MAX_TASKS; ++i) {\n\t\tif (taskmap[i].pid == pid) {\n\t\t\ttaskmap[i].isused = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (i >= PX4_MAX_TASKS) {\n\t\tPX4_ERR(\"px4_task_exit: self task not found!\");\n\n\t} else {\n\t\tPX4_DEBUG(\"px4_task_exit: %s\", taskmap[i].name.c_str());\n\t}\n\n\t\/\/pthread_exit((void *)(unsigned long)ret);\n}\n\nint px4_task_kill(px4_task_t id, int sig)\n{\n\tint rv = 0;\n\tpthread_t pid;\n\tPX4_DEBUG(\"Called px4_task_kill %d, taskname %s\", sig, taskmap[id].name.c_str());\n\n\tif (id < PX4_MAX_TASKS && taskmap[id].pid != 0) {\n\t\tpid = taskmap[id].pid;\n\n\t} else {\n\t\treturn -EINVAL;\n\t}\n\n\t\/\/ If current thread then exit, otherwise cancel\n\trv = pthread_kill(pid, sig);\n\n\treturn rv;\n}\n\nvoid px4_show_tasks()\n{\n\tint idx;\n\tint count = 0;\n\n\tPX4_INFO(\"Active Tasks:\");\n\n\tfor (idx = 0; idx < PX4_MAX_TASKS; idx++) {\n\t\tif (taskmap[idx].isused) {\n\t\t\tPX4_INFO(\" %-10s %d\", taskmap[idx].name.c_str(), taskmap[idx].pid);\n\t\t\tcount++;\n\t\t}\n\t}\n\n\tif (count == 0) {\n\t\tPX4_INFO(\" No running tasks\");\n\t}\n\n}\n\n__BEGIN_DECLS\n\nint px4_getpid()\n{\n\tpthread_t pid = pthread_self();\n\/\/\n\/\/\tif (pid == _shell_task_id)\n\/\/\t\treturn SHELL_TASK_ID;\n\n\t\/\/ Get pthread ID from the opaque ID\n\tfor (int i = 0; i < PX4_MAX_TASKS; ++i) {\n\t\tif (taskmap[i].isused && taskmap[i].pid == pid) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\tPX4_ERR(\"px4_getpid() called from unknown thread context!\");\n\treturn -EINVAL;\n}\n\n\nconst char *getprogname();\nconst char *getprogname()\n{\n\tpthread_t pid = pthread_self();\n\n\tfor (int i = 0; i < PX4_MAX_TASKS; i++) {\n\t\tif (taskmap[i].isused && taskmap[i].pid == pid) {\n\t\t\treturn taskmap[i].name.c_str();\n\t\t}\n\t}\n\n\treturn \"Unknown App\";\n}\n__END_DECLS\n\n<commit_msg>QuRT: Set thread attributes correctly<commit_after>\/****************************************************************************\n *\n * Copyright (C) 2015 Mark Charlebois. All rights reserved.\n * Author: @author Mark Charlebois <charlebm#gmail.com>\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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 * @file px4_posix_tasks.c\n * Implementation of existing task API for Linux\n *\/\n\n#include <px4_log.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <stdbool.h>\n\n#if !defined(__PX4_QURT)\n#include <signal.h>\n#endif\n\n#include <fcntl.h>\n#include <sched.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <string>\n\n#include <px4_tasks.h>\n\n#define MAX_CMD_LEN 100\n\n#define PX4_MAX_TASKS 50\n#define SHELL_TASK_ID (PX4_MAX_TASKS+1)\n\npthread_t _shell_task_id = 0;\n\nstruct task_entry {\n\tpthread_t pid;\n\tstd::string name;\n\tbool isused;\n\ttask_entry() : isused(false) {}\n};\n\nstatic task_entry taskmap[PX4_MAX_TASKS];\n\ntypedef struct {\n\tpx4_main_t entry;\n\tint argc;\n\tchar *argv[];\n\t\/\/ strings are allocated after the\n} pthdata_t;\n\nstatic void *entry_adapter(void *ptr)\n{\n\tpthdata_t *data;\n\tdata = (pthdata_t *) ptr;\n\n\tdata->entry(data->argc, data->argv);\n\tPX4_WARN(\"Before waiting infinte busy loop\");\n\t\/\/for( ;; )\n\t\/\/{\n\t\/\/ volatile int x = 0;\n\t\/\/ ++x;\n\t\/\/ }\n\tfree(ptr);\n\tpx4_task_exit(0);\n\n\treturn NULL;\n}\n\nvoid\npx4_systemreset(bool to_bootloader)\n{\n\tPX4_WARN(\"Called px4_system_reset\");\n}\n\npx4_task_t px4_task_spawn_cmd(const char *name, int scheduler, int priority, int stack_size, px4_main_t entry,\n\t\t\t char *const argv[])\n{\n\tint rv;\n\tint argc = 0;\n\tint i;\n\tunsigned int len = 0;\n\tunsigned long offset;\n\tunsigned long structsize;\n\tchar *p = (char *)argv;\n\n\tPX4_DEBUG(\"Creating %s\\n\", name);\n\tpthread_t task;\n\tpthread_attr_t attr;\n\tstruct sched_param param;\n\n\t\/\/ Calculate argc\n\twhile (p != (char *)0) {\n\t\tp = argv[argc];\n\n\t\tif (p == (char *)0) {\n\t\t\tbreak;\n\t\t}\n\n\t\t++argc;\n\t\tlen += strlen(p) + 1;\n\t}\n\n\tstructsize = sizeof(pthdata_t) + (argc + 1) * sizeof(char *);\n\tpthdata_t *taskdata;\n\n\t\/\/ not safe to pass stack data to the thread creation\n\ttaskdata = (pthdata_t *)malloc(structsize + len);\n\toffset = ((unsigned long)taskdata) + structsize;\n\n\ttaskdata->entry = entry;\n\ttaskdata->argc = argc;\n\n\tfor (i = 0; i < argc; i++) {\n\t\tPX4_DEBUG(\"arg %d %s\\n\", i, argv[i]);\n\t\ttaskdata->argv[i] = (char *)offset;\n\t\tstrcpy((char *)offset, argv[i]);\n\t\toffset += strlen(argv[i]) + 1;\n\t}\n\n\t\/\/ Must add NULL at end of argv\n\ttaskdata->argv[argc] = (char *)0;\n\n\trv = pthread_attr_init(&attr);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to init thread attrs\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n\trv = pthread_attr_getschedparam(&attr, ¶m);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to get thread sched param\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n#if 0\n\trv = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to set inherit sched\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n\trv = pthread_attr_setschedpolicy(&attr, scheduler);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to set sched policy\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n#endif\n\tsize_t fixed_stacksize = -1;\n\tpthread_attr_getstacksize(&attr, &fixed_stacksize);\n\tPX4_WARN(\"stack size: %d passed stacksize(%d)\", fixed_stacksize, stack_size);\n\tfixed_stacksize = 8 * 1024;\n\tfixed_stacksize = (fixed_stacksize < (size_t)stack_size) ? (size_t)stack_size : fixed_stacksize;\n\n\tPX4_WARN(\"setting the thread[%s] stack size to[%d]\", name, fixed_stacksize);\n\tpthread_attr_setstacksize(&attr, fixed_stacksize);\n\t\/\/pthread_attr_setstacksize(&attr, stack_size);\n\n\n\tparam.sched_priority = priority;\n\n\trv = pthread_attr_setschedparam(&attr, ¶m);\n\n\tif (rv != 0) {\n\t\tPX4_WARN(\"px4_task_spawn_cmd: failed to set sched param\");\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n\trv = pthread_create(&task, &attr, &entry_adapter, (void *) taskdata);\n\n\tif (rv != 0) {\n\n\t\treturn (rv < 0) ? rv : -rv;\n\t}\n\n\tfor (i = 0; i < PX4_MAX_TASKS; ++i) {\n\t\tif (taskmap[i].isused == false) {\n\t\t\ttaskmap[i].pid = task;\n\t\t\ttaskmap[i].name = name;\n\t\t\ttaskmap[i].isused = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (i >= PX4_MAX_TASKS) {\n\t\treturn -ENOSPC;\n\t}\n\n\treturn i;\n}\n\nint px4_task_delete(px4_task_t id)\n{\n\tint rv = 0;\n\tpthread_t pid;\n\tPX4_WARN(\"Called px4_task_delete\");\n\n\tif (id < PX4_MAX_TASKS && taskmap[id].isused) {\n\t\tpid = taskmap[id].pid;\n\n\t} else {\n\t\treturn -EINVAL;\n\t}\n\n\t\/\/ If current thread then exit, otherwise cancel\n\tif (pthread_self() == pid) {\n\t\ttaskmap[id].isused = false;\n\t\tpthread_exit(0);\n\n\t} else {\n\t\trv = pthread_cancel(pid);\n\t}\n\n\ttaskmap[id].isused = false;\n\n\treturn rv;\n}\n\nvoid px4_task_exit(int ret)\n{\n\tint i;\n\tpthread_t pid = pthread_self();\n\n\t\/\/ Get pthread ID from the opaque ID\n\tfor (i = 0; i < PX4_MAX_TASKS; ++i) {\n\t\tif (taskmap[i].pid == pid) {\n\t\t\ttaskmap[i].isused = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (i >= PX4_MAX_TASKS) {\n\t\tPX4_ERR(\"px4_task_exit: self task not found!\");\n\n\t} else {\n\t\tPX4_DEBUG(\"px4_task_exit: %s\", taskmap[i].name.c_str());\n\t}\n\n\t\/\/pthread_exit((void *)(unsigned long)ret);\n}\n\nint px4_task_kill(px4_task_t id, int sig)\n{\n\tint rv = 0;\n\tpthread_t pid;\n\tPX4_DEBUG(\"Called px4_task_kill %d, taskname %s\", sig, taskmap[id].name.c_str());\n\n\tif (id < PX4_MAX_TASKS && taskmap[id].pid != 0) {\n\t\tpid = taskmap[id].pid;\n\n\t} else {\n\t\treturn -EINVAL;\n\t}\n\n\t\/\/ If current thread then exit, otherwise cancel\n\trv = pthread_kill(pid, sig);\n\n\treturn rv;\n}\n\nvoid px4_show_tasks()\n{\n\tint idx;\n\tint count = 0;\n\n\tPX4_INFO(\"Active Tasks:\");\n\n\tfor (idx = 0; idx < PX4_MAX_TASKS; idx++) {\n\t\tif (taskmap[idx].isused) {\n\t\t\tPX4_INFO(\" %-10s %d\", taskmap[idx].name.c_str(), taskmap[idx].pid);\n\t\t\tcount++;\n\t\t}\n\t}\n\n\tif (count == 0) {\n\t\tPX4_INFO(\" No running tasks\");\n\t}\n\n}\n\n__BEGIN_DECLS\n\nint px4_getpid()\n{\n\tpthread_t pid = pthread_self();\n\/\/\n\/\/\tif (pid == _shell_task_id)\n\/\/\t\treturn SHELL_TASK_ID;\n\n\t\/\/ Get pthread ID from the opaque ID\n\tfor (int i = 0; i < PX4_MAX_TASKS; ++i) {\n\t\tif (taskmap[i].isused && taskmap[i].pid == pid) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\tPX4_ERR(\"px4_getpid() called from unknown thread context!\");\n\treturn -EINVAL;\n}\n\n\nconst char *getprogname();\nconst char *getprogname()\n{\n\tpthread_t pid = pthread_self();\n\n\tfor (int i = 0; i < PX4_MAX_TASKS; i++) {\n\t\tif (taskmap[i].isused && taskmap[i].pid == pid) {\n\t\t\treturn taskmap[i].name.c_str();\n\t\t}\n\t}\n\n\treturn \"Unknown App\";\n}\n__END_DECLS\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008 Apple Inc. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * 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\n#include \"config.h\"\n#include \"ConstructData.h\"\n\n#include \"JSFunction.h\"\n\n\n#ifdef QT_BUILD_SCRIPT_LIB\n#include \"Debugger.h\"\n#include \"DebuggerCallFrame.h\"\n#endif\n\nnamespace JSC {\n\n#ifdef QT_BUILD_SCRIPT_LIB\nJSObject* JSC::NativeConstrWrapper::operator() (ExecState* exec, JSObject* jsobj, const ArgList& argList) const\n{\n Debugger* debugger = exec->lexicalGlobalObject()->debugger();\n if (debugger)\n debugger->callEvent(DebuggerCallFrame(exec), -1, -1);\n\n JSObject* returnValue = ptr(exec, jsobj, argList);\n\n if ((debugger) && (callDebuggerFunctionExit))\n debugger->functionExit(JSValue(returnValue), -1);\n\n return returnValue;\n}\n#endif\n\nJSObject* construct(ExecState* exec, JSValue callee, ConstructType constructType, const ConstructData& constructData, const ArgList& args)\n{\n if (constructType == ConstructTypeHost)\n return constructData.native.function(exec, asObject(callee), args);\n ASSERT(constructType == ConstructTypeJS);\n \/\/ FIXME: Can this be done more efficiently using the constructData?\n return asFunction(callee)->construct(exec, args);\n}\n\n} \/\/ namespace JSC\n<commit_msg>compile<commit_after>\/*\n * Copyright (C) 2008 Apple Inc. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * 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\n#include \"config.h\"\n#include \"ConstructData.h\"\n\n#include \"JSFunction.h\"\n\n\n#ifdef QT_BUILD_SCRIPT_LIB\n#include \"Debugger.h\"\n#include \"DebuggerCallFrame.h\"\n#include \"JSGlobalObject.h\"\n#endif\n\nnamespace JSC {\n\n#ifdef QT_BUILD_SCRIPT_LIB\nJSObject* JSC::NativeConstrWrapper::operator() (ExecState* exec, JSObject* jsobj, const ArgList& argList) const\n{\n Debugger* debugger = exec->lexicalGlobalObject()->debugger();\n if (debugger)\n debugger->callEvent(DebuggerCallFrame(exec), -1, -1);\n\n JSObject* returnValue = ptr(exec, jsobj, argList);\n\n if ((debugger) && (callDebuggerFunctionExit))\n debugger->functionExit(JSValue(returnValue), -1);\n\n return returnValue;\n}\n#endif\n\nJSObject* construct(ExecState* exec, JSValue callee, ConstructType constructType, const ConstructData& constructData, const ArgList& args)\n{\n if (constructType == ConstructTypeHost)\n return constructData.native.function(exec, asObject(callee), args);\n ASSERT(constructType == ConstructTypeJS);\n \/\/ FIXME: Can this be done more efficiently using the constructData?\n return asFunction(callee)->construct(exec, args);\n}\n\n} \/\/ namespace JSC\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cairo_spritehelper.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2007-11-09 11:32: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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_canvas.hxx\"\n\n#include <canvas\/debug.hxx>\n#include <canvas\/verbosetrace.hxx>\n\n#include <rtl\/logfile.hxx>\n#include <rtl\/math.hxx>\n\n#include <canvas\/canvastools.hxx>\n\n#include <basegfx\/matrix\/b2dhommatrix.hxx>\n#include <basegfx\/point\/b2dpoint.hxx>\n#include <basegfx\/tools\/canvastools.hxx>\n#include <basegfx\/numeric\/ftools.hxx>\n#include <basegfx\/polygon\/b2dpolypolygontools.hxx>\n#include <basegfx\/polygon\/b2dpolygontools.hxx>\n#include <basegfx\/polygon\/b2dpolypolygonrasterconverter.hxx>\n#include <basegfx\/polygon\/b2dpolygontriangulator.hxx>\n#include <basegfx\/polygon\/b2dpolygoncutandtouch.hxx>\n\n#include \"cairo_canvascustomsprite.hxx\"\n#include \"cairo_spritehelper.hxx\"\n\n#include <memory>\n\n\nusing namespace ::cairo;\nusing namespace ::com::sun::star;\n\nnamespace cairocanvas\n{\n SpriteHelper::SpriteHelper() :\n mpSpriteCanvas(),\n mbTextureDirty( true ),\n mpBufferSurface( NULL )\n {\n }\n\n void SpriteHelper::init( const geometry::RealSize2D& rSpriteSize,\n const SpriteCanvasRef& rSpriteCanvas)\n {\n ENSURE_AND_THROW( rSpriteCanvas.get(),\n \"SpriteHelper::init(): Invalid device, sprite canvas or surface\" );\n\n mpSpriteCanvas = rSpriteCanvas;\n mbTextureDirty = true;\n\n \/\/ also init base class\n CanvasCustomSpriteHelper::init( rSpriteSize,\n rSpriteCanvas.get() );\n }\n\n void SpriteHelper::setSurface( Surface* pBufferSurface )\n {\n if( mpBufferSurface )\n mpBufferSurface->Unref();\n\n mpBufferSurface = pBufferSurface;\n mpBufferSurface->Ref();\n }\n\n void SpriteHelper::disposing()\n {\n mpSpriteCanvas.clear();\n\n \/\/ forward to parent\n CanvasCustomSpriteHelper::disposing();\n\n if( mpBufferSurface ) {\n mpBufferSurface->Unref();\n mpBufferSurface = NULL;\n }\n }\n\n void SpriteHelper::redraw( Cairo* pCairo,\n const ::basegfx::B2DPoint& rPos,\n bool& \/*io_bSurfacesDirty*\/,\n bool \/*bBufferedUpdate*\/ ) const\n {\n #ifdef CAIRO_CANVAS_PERF_TRACE\n struct timespec aTimer;\n mxDevice->startPerfTrace( &aTimer );\n #endif\n\n const double fAlpha( getAlpha() );\n const ::basegfx::B2DHomMatrix aTransform( getTransformation() );\n\n if( isActive() && !::basegfx::fTools::equalZero( fAlpha ) ) {\n OSL_TRACE (\"CanvasCustomSprite::redraw called\");\n if( pCairo ) {\n basegfx::B2DVector aSize = getSizePixel();\n cairo_save( pCairo );\n\n double fX, fY;\n\n fX = rPos.getX();\n fY = rPos.getY();\n\n if( !aTransform.isIdentity() ) {\n cairo_matrix_t aMatrix, aInverseMatrix;\n cairo_matrix_init( &aMatrix,\n aTransform.get( 0, 0 ), aTransform.get( 1, 0 ), aTransform.get( 0, 1 ),\n aTransform.get( 1, 1 ), aTransform.get( 0, 2 ), aTransform.get( 1, 2 ) );\n\n aMatrix.x0 = round( aMatrix.x0 );\n aMatrix.y0 = round( aMatrix.y0 );\n\n cairo_matrix_init( &aInverseMatrix, aMatrix.xx, aMatrix.yx, aMatrix.xy, aMatrix.yy, aMatrix.x0, aMatrix.y0 );\n cairo_matrix_invert( &aInverseMatrix );\n cairo_matrix_transform_distance( &aInverseMatrix, &fX, &fY );\n\n cairo_set_matrix( pCairo, &aMatrix );\n }\n\n fX = round( fX );\n fY = round( fY );\n\n cairo_matrix_t aOrigMatrix;\n cairo_get_matrix( pCairo, &aOrigMatrix );\n cairo_translate( pCairo, fX, fY );\n\n if( getClip().is() )\n {\n ::basegfx::B2DPolyPolygon aClipPoly(\n ::canvas::tools::polyPolygonFromXPolyPolygon2D(\n getClip() ));\n\n \/\/cairo_reset_clip( pCairo );\n doPolyPolygonImplementation( aClipPoly, Clip, pCairo );\n }\n\n OSL_TRACE (\"aSize %f x %f position: %f,%f\", aSize.getX(), aSize.getY(), fX, fY );\n cairo_rectangle( pCairo, 0, 0, floor( aSize.getX() ), floor( aSize.getY() ) );\n cairo_clip( pCairo );\n cairo_set_matrix( pCairo, &aOrigMatrix );\n\n if( isContentFullyOpaque() )\n cairo_set_operator( pCairo, CAIRO_OPERATOR_SOURCE );\n cairo_set_source_surface( pCairo, mpBufferSurface->mpSurface, fX, fY );\n if( ::rtl::math::approxEqual( fAlpha, 1.0 ) )\n cairo_paint( pCairo );\n else\n cairo_paint_with_alpha( pCairo, fAlpha );\n\n cairo_restore( pCairo );\n }\n }\n\n #ifdef CAIRO_CANVAS_PERF_TRACE\n mxDevice->stopPerfTrace( &aTimer, \"sprite redraw\" );\n #endif\n }\n\n ::basegfx::B2DPolyPolygon SpriteHelper::polyPolygonFromXPolyPolygon2D( uno::Reference< rendering::XPolyPolygon2D >& xPoly ) const\n {\n return ::canvas::tools::polyPolygonFromXPolyPolygon2D( xPoly );\n }\n}\n<commit_msg>INTEGRATION: CWS cairoquartz01 (1.4.22); FILE MERGED 2007\/12\/10 17:45:38 mox 1.4.22.3: RESYNC: (1.5-1.6); FILE MERGED 2007\/07\/28 15:31:00 mox 1.4.22.2: RESYNC: (1.4-1.5); FILE MERGED 2007\/06\/02 23:05:33 thb 1.4.22.1: #i70519# Merged in tml's fixes for WinCairo; made code compile warning-free under Linux; added prex\/postx.h (which where already referenced); cleaned up a bit; replaces plain round() call with basegfx::fround; asserting unexpected\/unimplemented case at selected places<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cairo_spritehelper.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2008-04-02 09:44:12 $\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_canvas.hxx\"\n\n#include <canvas\/debug.hxx>\n#include <canvas\/verbosetrace.hxx>\n\n#include <rtl\/logfile.hxx>\n#include <rtl\/math.hxx>\n\n#include <canvas\/canvastools.hxx>\n\n#include <basegfx\/matrix\/b2dhommatrix.hxx>\n#include <basegfx\/point\/b2dpoint.hxx>\n#include <basegfx\/tools\/canvastools.hxx>\n#include <basegfx\/numeric\/ftools.hxx>\n#include <basegfx\/polygon\/b2dpolypolygontools.hxx>\n#include <basegfx\/polygon\/b2dpolygontools.hxx>\n#include <basegfx\/polygon\/b2dpolypolygonrasterconverter.hxx>\n#include <basegfx\/polygon\/b2dpolygontriangulator.hxx>\n#include <basegfx\/polygon\/b2dpolygoncutandtouch.hxx>\n\n#include \"cairo_canvascustomsprite.hxx\"\n#include \"cairo_spritehelper.hxx\"\n\n#include <memory>\n\n\nusing namespace ::cairo;\nusing namespace ::com::sun::star;\n\nnamespace cairocanvas\n{\n SpriteHelper::SpriteHelper() :\n mpSpriteCanvas(),\n mbTextureDirty( true ),\n mpBufferSurface( NULL )\n {\n }\n\n void SpriteHelper::init( const geometry::RealSize2D& rSpriteSize,\n const SpriteCanvasRef& rSpriteCanvas)\n {\n ENSURE_AND_THROW( rSpriteCanvas.get(),\n \"SpriteHelper::init(): Invalid device, sprite canvas or surface\" );\n\n mpSpriteCanvas = rSpriteCanvas;\n mbTextureDirty = true;\n\n \/\/ also init base class\n CanvasCustomSpriteHelper::init( rSpriteSize,\n rSpriteCanvas.get() );\n }\n\n void SpriteHelper::setSurface( Surface* pBufferSurface )\n {\n if( mpBufferSurface )\n mpBufferSurface->Unref();\n\n mpBufferSurface = pBufferSurface;\n mpBufferSurface->Ref();\n }\n\n void SpriteHelper::disposing()\n {\n mpSpriteCanvas.clear();\n\n \/\/ forward to parent\n CanvasCustomSpriteHelper::disposing();\n\n if( mpBufferSurface ) {\n mpBufferSurface->Unref();\n mpBufferSurface = NULL;\n }\n }\n\n void SpriteHelper::redraw( Cairo* pCairo,\n const ::basegfx::B2DPoint& rPos,\n bool& \/*io_bSurfacesDirty*\/,\n bool \/*bBufferedUpdate*\/ ) const\n {\n #ifdef CAIRO_CANVAS_PERF_TRACE\n struct timespec aTimer;\n mxDevice->startPerfTrace( &aTimer );\n #endif\n\n const double fAlpha( getAlpha() );\n const ::basegfx::B2DHomMatrix aTransform( getTransformation() );\n\n if( isActive() && !::basegfx::fTools::equalZero( fAlpha ) ) {\n OSL_TRACE (\"CanvasCustomSprite::redraw called\");\n if( pCairo ) {\n basegfx::B2DVector aSize = getSizePixel();\n cairo_save( pCairo );\n\n double fX, fY;\n\n fX = rPos.getX();\n fY = rPos.getY();\n\n if( !aTransform.isIdentity() ) {\n cairo_matrix_t aMatrix, aInverseMatrix;\n cairo_matrix_init( &aMatrix,\n aTransform.get( 0, 0 ), aTransform.get( 1, 0 ), aTransform.get( 0, 1 ),\n aTransform.get( 1, 1 ), aTransform.get( 0, 2 ), aTransform.get( 1, 2 ) );\n\n aMatrix.x0 = basegfx::fround( aMatrix.x0 );\n aMatrix.y0 = basegfx::fround( aMatrix.y0 );\n\n cairo_matrix_init( &aInverseMatrix, aMatrix.xx, aMatrix.yx, aMatrix.xy, aMatrix.yy, aMatrix.x0, aMatrix.y0 );\n cairo_matrix_invert( &aInverseMatrix );\n cairo_matrix_transform_distance( &aInverseMatrix, &fX, &fY );\n\n cairo_set_matrix( pCairo, &aMatrix );\n }\n\n fX = basegfx::fround( fX );\n fY = basegfx::fround( fY );\n\n cairo_matrix_t aOrigMatrix;\n cairo_get_matrix( pCairo, &aOrigMatrix );\n cairo_translate( pCairo, fX, fY );\n\n if( getClip().is() )\n {\n ::basegfx::B2DPolyPolygon aClipPoly(\n ::canvas::tools::polyPolygonFromXPolyPolygon2D(\n getClip() ));\n\n \/\/cairo_reset_clip( pCairo );\n doPolyPolygonImplementation( aClipPoly, Clip, pCairo );\n }\n\n OSL_TRACE (\"aSize %f x %f position: %f,%f\", aSize.getX(), aSize.getY(), fX, fY );\n cairo_rectangle( pCairo, 0, 0, floor( aSize.getX() ), floor( aSize.getY() ) );\n cairo_clip( pCairo );\n cairo_set_matrix( pCairo, &aOrigMatrix );\n\n if( isContentFullyOpaque() )\n cairo_set_operator( pCairo, CAIRO_OPERATOR_SOURCE );\n cairo_set_source_surface( pCairo, mpBufferSurface->mpSurface, fX, fY );\n if( ::rtl::math::approxEqual( fAlpha, 1.0 ) )\n cairo_paint( pCairo );\n else\n cairo_paint_with_alpha( pCairo, fAlpha );\n\n cairo_restore( pCairo );\n }\n }\n\n #ifdef CAIRO_CANVAS_PERF_TRACE\n mxDevice->stopPerfTrace( &aTimer, \"sprite redraw\" );\n #endif\n }\n\n ::basegfx::B2DPolyPolygon SpriteHelper::polyPolygonFromXPolyPolygon2D( uno::Reference< rendering::XPolyPolygon2D >& xPoly ) const\n {\n return ::canvas::tools::polyPolygonFromXPolyPolygon2D( xPoly );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2022, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \"problems\/cvrp\/operators\/reverse_two_opt.h\"\n\nnamespace vroom {\nnamespace cvrp {\n\nReverseTwoOpt::ReverseTwoOpt(const Input& input,\n const utils::SolutionState& sol_state,\n RawRoute& s_route,\n Index s_vehicle,\n Index s_rank,\n RawRoute& t_route,\n Index t_vehicle,\n Index t_rank)\n : Operator(OperatorName::ReverseTwoOpt,\n input,\n sol_state,\n s_route,\n s_vehicle,\n s_rank,\n t_route,\n t_vehicle,\n t_rank) {\n assert(s_vehicle != t_vehicle);\n assert(s_route.size() >= 1);\n assert(t_route.size() >= 1);\n assert(s_rank < s_route.size());\n assert(t_rank < t_route.size());\n\n assert(_sol_state.bwd_skill_rank[s_vehicle][t_vehicle] <= s_rank + 1);\n assert(t_rank < _sol_state.fwd_skill_rank[t_vehicle][s_vehicle]);\n}\n\nvoid ReverseTwoOpt::compute_gain() {\n const auto& s_v = _input.vehicles[s_vehicle];\n const auto& t_v = _input.vehicles[t_vehicle];\n\n Index s_index = _input.jobs[s_route[s_rank]].index();\n Index t_index = _input.jobs[t_route[t_rank]].index();\n Index last_s = _input.jobs[s_route.back()].index();\n Index first_t = _input.jobs[t_route.front()].index();\n\n bool last_in_source = (s_rank == s_route.size() - 1);\n bool last_in_target = (t_rank == t_route.size() - 1);\n\n \/\/ Cost of swapping route for vehicle s_vehicle after step\n \/\/ s_rank with route for vehicle t_vehicle up to step\n \/\/ t_rank, but reversed.\n\n \/\/ Add new source -> target edge.\n s_gain -= s_v.eval(s_index, t_index);\n\n \/\/ Cost of reversing target route portion. First remove forward cost\n \/\/ for beginning of target route as seen from target vehicle. Then\n \/\/ add backward cost for beginning of target route as seen from\n \/\/ source vehicle since it's the new source route end.\n t_gain += _sol_state.fwd_costs[t_vehicle][t_vehicle][t_rank];\n s_gain -= _sol_state.bwd_costs[t_vehicle][s_vehicle][t_rank];\n\n if (!last_in_target) {\n \/\/ Spare next edge in target route.\n Index next_index = _input.jobs[t_route[t_rank + 1]].index();\n t_gain += t_v.eval(t_index, next_index);\n }\n\n if (!last_in_source) {\n \/\/ Spare next edge in source route.\n Index next_index = _input.jobs[s_route[s_rank + 1]].index();\n s_gain += s_v.eval(s_index, next_index);\n\n \/\/ Part of source route is moved to target route.\n Index next_s_index = _input.jobs[s_route[s_rank + 1]].index();\n\n \/\/ Cost or reverting source route portion. First remove forward\n \/\/ cost for end of source route as seen from source vehicle\n \/\/ (subtracting intermediate cost to overall cost). Then add\n \/\/ backward cost for end of source route as seen from target\n \/\/ vehicle since it's the new target route start.\n s_gain += _sol_state.fwd_costs[s_vehicle][s_vehicle].back();\n s_gain -= _sol_state.fwd_costs[s_vehicle][s_vehicle][s_rank + 1];\n t_gain -= _sol_state.bwd_costs[s_vehicle][t_vehicle].back();\n t_gain += _sol_state.bwd_costs[s_vehicle][t_vehicle][s_rank + 1];\n\n if (last_in_target) {\n if (t_v.has_end()) {\n \/\/ Handle target route new end.\n auto end_t = t_v.end.value().index();\n t_gain += t_v.eval(t_index, end_t);\n t_gain -= t_v.eval(next_s_index, end_t);\n }\n } else {\n \/\/ Add new target -> source edge.\n Index next_t_index = _input.jobs[t_route[t_rank + 1]].index();\n t_gain -= t_v.eval(next_s_index, next_t_index);\n }\n }\n\n if (s_v.has_end()) {\n \/\/ Update cost to source end because last job changed.\n auto end_s = s_v.end.value().index();\n s_gain += s_v.eval(last_s, end_s);\n s_gain -= s_v.eval(first_t, end_s);\n }\n\n if (t_v.has_start()) {\n \/\/ Spare cost from target start because first job changed.\n auto start_t = t_v.start.value().index();\n t_gain += t_v.eval(start_t, first_t);\n if (!last_in_source) {\n t_gain -= t_v.eval(start_t, last_s);\n } else {\n \/\/ No job from source route actually swapped to target route.\n if (!last_in_target) {\n \/\/ Going straight from start to next job in target route.\n Index next_index = _input.jobs[t_route[t_rank + 1]].index();\n t_gain -= t_v.eval(start_t, next_index);\n } else {\n \/\/ Emptying the whole target route here, so also gaining cost\n \/\/ to end if it exists.\n if (t_v.has_end()) {\n auto end_t = t_v.end.value().index();\n t_gain += t_v.eval(t_index, end_t);\n }\n }\n }\n }\n\n stored_gain = s_gain + t_gain;\n gain_computed = true;\n}\n\nbool ReverseTwoOpt::is_valid() {\n const auto& t_delivery = target.fwd_deliveries(t_rank);\n const auto& t_pickup = target.fwd_pickups(t_rank);\n\n bool valid = source.is_valid_addition_for_capacity_margins(_input,\n t_pickup,\n t_delivery,\n s_rank + 1,\n s_route.size());\n\n const auto& s_delivery = source.bwd_deliveries(s_rank);\n const auto& s_pickup = source.bwd_pickups(s_rank);\n\n valid = valid && target.is_valid_addition_for_capacity_margins(_input,\n s_pickup,\n s_delivery,\n 0,\n t_rank + 1);\n\n valid =\n valid && source.is_valid_addition_for_capacity_inclusion(_input,\n t_delivery,\n t_route.rbegin() +\n t_route.size() -\n 1 - t_rank,\n t_route.rend(),\n s_rank + 1,\n s_route.size());\n\n valid =\n valid && target.is_valid_addition_for_capacity_inclusion(_input,\n s_delivery,\n s_route.rbegin(),\n s_route.rbegin() +\n s_route.size() -\n 1 - s_rank,\n 0,\n t_rank + 1);\n\n return valid;\n}\n\nvoid ReverseTwoOpt::apply() {\n auto nb_source = s_route.size() - 1 - s_rank;\n\n t_route.insert(t_route.begin(),\n s_route.rbegin(),\n s_route.rbegin() + nb_source);\n s_route.erase(s_route.begin() + s_rank + 1, s_route.end());\n s_route.insert(s_route.end(),\n t_route.rend() - t_rank - nb_source - 1,\n t_route.rend() - nb_source);\n t_route.erase(t_route.begin() + nb_source,\n t_route.begin() + nb_source + t_rank + 1);\n\n source.update_amounts(_input);\n target.update_amounts(_input);\n}\n\nstd::vector<Index> ReverseTwoOpt::addition_candidates() const {\n return {s_vehicle, t_vehicle};\n}\n\nstd::vector<Index> ReverseTwoOpt::update_candidates() const {\n return {s_vehicle, t_vehicle};\n}\n\n} \/\/ namespace cvrp\n} \/\/ namespace vroom\n<commit_msg>Check max_travel_time validity in ReverseTwoOpt.<commit_after>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2022, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \"problems\/cvrp\/operators\/reverse_two_opt.h\"\n\nnamespace vroom {\nnamespace cvrp {\n\nReverseTwoOpt::ReverseTwoOpt(const Input& input,\n const utils::SolutionState& sol_state,\n RawRoute& s_route,\n Index s_vehicle,\n Index s_rank,\n RawRoute& t_route,\n Index t_vehicle,\n Index t_rank)\n : Operator(OperatorName::ReverseTwoOpt,\n input,\n sol_state,\n s_route,\n s_vehicle,\n s_rank,\n t_route,\n t_vehicle,\n t_rank) {\n assert(s_vehicle != t_vehicle);\n assert(s_route.size() >= 1);\n assert(t_route.size() >= 1);\n assert(s_rank < s_route.size());\n assert(t_rank < t_route.size());\n\n assert(_sol_state.bwd_skill_rank[s_vehicle][t_vehicle] <= s_rank + 1);\n assert(t_rank < _sol_state.fwd_skill_rank[t_vehicle][s_vehicle]);\n}\n\nvoid ReverseTwoOpt::compute_gain() {\n const auto& s_v = _input.vehicles[s_vehicle];\n const auto& t_v = _input.vehicles[t_vehicle];\n\n Index s_index = _input.jobs[s_route[s_rank]].index();\n Index t_index = _input.jobs[t_route[t_rank]].index();\n Index last_s = _input.jobs[s_route.back()].index();\n Index first_t = _input.jobs[t_route.front()].index();\n\n bool last_in_source = (s_rank == s_route.size() - 1);\n bool last_in_target = (t_rank == t_route.size() - 1);\n\n \/\/ Cost of swapping route for vehicle s_vehicle after step\n \/\/ s_rank with route for vehicle t_vehicle up to step\n \/\/ t_rank, but reversed.\n\n \/\/ Add new source -> target edge.\n s_gain -= s_v.eval(s_index, t_index);\n\n \/\/ Cost of reversing target route portion. First remove forward cost\n \/\/ for beginning of target route as seen from target vehicle. Then\n \/\/ add backward cost for beginning of target route as seen from\n \/\/ source vehicle since it's the new source route end.\n t_gain += _sol_state.fwd_costs[t_vehicle][t_vehicle][t_rank];\n s_gain -= _sol_state.bwd_costs[t_vehicle][s_vehicle][t_rank];\n\n if (!last_in_target) {\n \/\/ Spare next edge in target route.\n Index next_index = _input.jobs[t_route[t_rank + 1]].index();\n t_gain += t_v.eval(t_index, next_index);\n }\n\n if (!last_in_source) {\n \/\/ Spare next edge in source route.\n Index next_index = _input.jobs[s_route[s_rank + 1]].index();\n s_gain += s_v.eval(s_index, next_index);\n\n \/\/ Part of source route is moved to target route.\n Index next_s_index = _input.jobs[s_route[s_rank + 1]].index();\n\n \/\/ Cost or reverting source route portion. First remove forward\n \/\/ cost for end of source route as seen from source vehicle\n \/\/ (subtracting intermediate cost to overall cost). Then add\n \/\/ backward cost for end of source route as seen from target\n \/\/ vehicle since it's the new target route start.\n s_gain += _sol_state.fwd_costs[s_vehicle][s_vehicle].back();\n s_gain -= _sol_state.fwd_costs[s_vehicle][s_vehicle][s_rank + 1];\n t_gain -= _sol_state.bwd_costs[s_vehicle][t_vehicle].back();\n t_gain += _sol_state.bwd_costs[s_vehicle][t_vehicle][s_rank + 1];\n\n if (last_in_target) {\n if (t_v.has_end()) {\n \/\/ Handle target route new end.\n auto end_t = t_v.end.value().index();\n t_gain += t_v.eval(t_index, end_t);\n t_gain -= t_v.eval(next_s_index, end_t);\n }\n } else {\n \/\/ Add new target -> source edge.\n Index next_t_index = _input.jobs[t_route[t_rank + 1]].index();\n t_gain -= t_v.eval(next_s_index, next_t_index);\n }\n }\n\n if (s_v.has_end()) {\n \/\/ Update cost to source end because last job changed.\n auto end_s = s_v.end.value().index();\n s_gain += s_v.eval(last_s, end_s);\n s_gain -= s_v.eval(first_t, end_s);\n }\n\n if (t_v.has_start()) {\n \/\/ Spare cost from target start because first job changed.\n auto start_t = t_v.start.value().index();\n t_gain += t_v.eval(start_t, first_t);\n if (!last_in_source) {\n t_gain -= t_v.eval(start_t, last_s);\n } else {\n \/\/ No job from source route actually swapped to target route.\n if (!last_in_target) {\n \/\/ Going straight from start to next job in target route.\n Index next_index = _input.jobs[t_route[t_rank + 1]].index();\n t_gain -= t_v.eval(start_t, next_index);\n } else {\n \/\/ Emptying the whole target route here, so also gaining cost\n \/\/ to end if it exists.\n if (t_v.has_end()) {\n auto end_t = t_v.end.value().index();\n t_gain += t_v.eval(t_index, end_t);\n }\n }\n }\n }\n\n stored_gain = s_gain + t_gain;\n gain_computed = true;\n}\n\nbool ReverseTwoOpt::is_valid() {\n const auto& t_delivery = target.fwd_deliveries(t_rank);\n const auto& t_pickup = target.fwd_pickups(t_rank);\n\n bool valid = source.is_valid_addition_for_capacity_margins(_input,\n t_pickup,\n t_delivery,\n s_rank + 1,\n s_route.size());\n\n const auto& s_delivery = source.bwd_deliveries(s_rank);\n const auto& s_pickup = source.bwd_pickups(s_rank);\n\n valid = valid && target.is_valid_addition_for_capacity_margins(_input,\n s_pickup,\n s_delivery,\n 0,\n t_rank + 1);\n\n const auto& s_v = _input.vehicles[s_vehicle];\n const auto s_travel_time = _sol_state.route_evals[s_vehicle].duration;\n valid = valid && (s_travel_time <= s_v.max_travel_time + s_gain.duration);\n\n const auto& t_v = _input.vehicles[t_vehicle];\n const auto t_travel_time = _sol_state.route_evals[t_vehicle].duration;\n valid = valid && (t_travel_time <= t_v.max_travel_time + t_gain.duration);\n\n valid =\n valid && source.is_valid_addition_for_capacity_inclusion(_input,\n t_delivery,\n t_route.rbegin() +\n t_route.size() -\n 1 - t_rank,\n t_route.rend(),\n s_rank + 1,\n s_route.size());\n\n valid =\n valid && target.is_valid_addition_for_capacity_inclusion(_input,\n s_delivery,\n s_route.rbegin(),\n s_route.rbegin() +\n s_route.size() -\n 1 - s_rank,\n 0,\n t_rank + 1);\n\n return valid;\n}\n\nvoid ReverseTwoOpt::apply() {\n auto nb_source = s_route.size() - 1 - s_rank;\n\n t_route.insert(t_route.begin(),\n s_route.rbegin(),\n s_route.rbegin() + nb_source);\n s_route.erase(s_route.begin() + s_rank + 1, s_route.end());\n s_route.insert(s_route.end(),\n t_route.rend() - t_rank - nb_source - 1,\n t_route.rend() - nb_source);\n t_route.erase(t_route.begin() + nb_source,\n t_route.begin() + nb_source + t_rank + 1);\n\n source.update_amounts(_input);\n target.update_amounts(_input);\n}\n\nstd::vector<Index> ReverseTwoOpt::addition_candidates() const {\n return {s_vehicle, t_vehicle};\n}\n\nstd::vector<Index> ReverseTwoOpt::update_candidates() const {\n return {s_vehicle, t_vehicle};\n}\n\n} \/\/ namespace cvrp\n} \/\/ namespace vroom\n<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2011 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n\/\/\/ \\file StereoSessionIsis.cc\n\/\/\/\n\n\/\/ Vision Workbench\n#include <vw\/FileIO.h>\n#include <vw\/Math\/Functors.h>\n#include <vw\/Math\/Geometry.h>\n#include <vw\/Math\/RANSAC.h>\n#include <vw\/InterestPoint.h>\n#include <vw\/Stereo\/DisparityMap.h>\n#include <vw\/Cartography.h>\n\n\/\/ Stereo Pipeline\n#include <asp\/Sessions\/ISIS\/StereoSessionIsis.h>\n#include <asp\/IsisIO\/IsisCameraModel.h>\n#include <asp\/Core\/StereoSettings.h>\n#include <asp\/IsisIO\/IsisAdjustCameraModel.h>\n#include <asp\/IsisIO\/DiskImageResourceIsis.h>\n#include <asp\/Sessions\/ISIS\/PhotometricOutlier.h>\n\n\/\/ Boost\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/shared_ptr.hpp>\nnamespace fs = boost::filesystem;\n\n#include <algorithm>\n\nusing namespace vw;\nusing namespace vw::camera;\nusing namespace asp;\n\n\/\/ Allows FileIO to correctly read\/write these pixel types\nnamespace vw {\n template<> struct PixelFormatID<Vector3> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };\n}\n\n\/\/ Process a single ISIS image to find an ideal min max. The reason we\n\/\/ need to do this, is that ASP is to get image intensity values in\n\/\/ the range of 0-1. To some extent we are compressing the dynamic\n\/\/ range, but we try to minimize that.\nvoid find_ideal_isis_range( std::string const& in_file,\n std::string const& tag,\n float & isis_lo, float & isis_hi ) {\n\n boost::shared_ptr<DiskImageResourceIsis> isis_rsrc( new DiskImageResourceIsis(in_file) );\n DiskImageView<PixelGray<float> > disk_image(isis_rsrc);\n\n float isis_mean, isis_std;\n\n \/\/ Calculating statistics. We subsample the images so statistics\n \/\/ only does about a million samples.\n {\n vw_out(InfoMessage) << \"\\t--> Computing statistics for the \"+tag+\" image\\n\";\n int left_stat_scale = int(ceil(sqrt(float(disk_image.cols())*float(disk_image.rows()) \/ 1000000)));\n ChannelAccumulator<math::CDFAccumulator<float> > accumulator;\n for_each_pixel(\n subsample(create_mask( edge_extend(disk_image, ConstantEdgeExtension()),\n isis_rsrc->valid_minimum(),\n isis_rsrc->valid_maximum() ),\n left_stat_scale ),\n accumulator );\n isis_lo = accumulator.quantile(0);\n isis_hi = accumulator.quantile(1);\n isis_mean = accumulator.approximate_mean();\n isis_std = accumulator.approximate_stddev();\n\n vw_out(InfoMessage) << \"\\t \"+tag+\": [ lo:\" << isis_lo << \" hi:\" << isis_hi\n << \" m: \" << isis_mean << \" s: \" << isis_std << \"]\\n\";\n }\n\n \/\/ Normalizing to -+2 sigmas around mean\n if ( stereo_settings().force_max_min == 0 ) {\n vw_out(InfoMessage) << \"\\t--> Adjusting hi and lo to -+2 sigmas around mean.\\n\";\n\n if ( isis_lo < isis_mean - 2*isis_std )\n isis_lo = isis_mean - 2*isis_std;\n if ( isis_hi > isis_mean + 2*isis_std )\n isis_hi = isis_mean + 2*isis_std;\n\n vw_out(InfoMessage) << \"\\t \"+tag+\" changed: [ lo:\"\n << isis_lo << \" hi:\" << isis_hi << \"]\\n\";\n }\n}\n\n\/\/ This tells the GDAL settings we should be using\n\/\/\n\/\/ I don't like having this here. We should somehow use the settings\n\/\/ decided by stereo. Unfortunately Sessions can not depend on the tool.\nvw::DiskImageResourceGDAL::Options\ngdal_settings( int32 const& cols, int32 const& rows ) {\n vw::DiskImageResourceGDAL::Options option;\n#if defined(VW_HAS_BIGTIFF) && VW_HAS_BIGTIFF == 1\n option[\"COMPRESS\"] = \"LZW\";\n if ( cols*rows > 10e6 )\n option[\"BIGTIFF\"] = \"IF_SAFER\";\n else\n option[\"BIGTIFF\"] = \"NO\";\n#else\n option[\"COMPRESS\"] = \"NONE\";\n option[\"BIGTIFF\"] = \"NO\";\n#endif\n return option;\n}\n\n\/\/ This actually modifies and writes the pre-processed image.\nvoid write_preprocessed_isis_image( std::string const& in_file,\n std::string const& out_file,\n std::string const& tag,\n float const& isis_lo, float const& isis_hi,\n float const& out_lo, float const& out_hi,\n Matrix<double> const& matrix,\n Vector2i const& crop_size ) {\n DiskImageView<PixelGray<float> > disk_image(in_file);\n ImageViewRef<PixelGray<float> > applied_image;\n if ( matrix == math::identity_matrix<3>() ) {\n applied_image =\n crop(edge_extend(clamp(normalize(remove_isis_special_pixels(disk_image,\n isis_lo, isis_hi, out_lo),\n out_lo, out_hi, 0.0, 1.0)),\n ZeroEdgeExtension()),\n 0, 0, crop_size[0], crop_size[1]);\n } else {\n applied_image =\n clamp(transform(normalize(remove_isis_special_pixels(disk_image,\n isis_lo, isis_hi,\n out_lo),\n out_lo, out_hi, 0.0, 1.0),\n HomographyTransform(matrix),\n crop_size[0], crop_size[1]));\n }\n\n \/\/ Write the results to disk.\n vw_out() << \"\\t--> Writing normalized images.\\n\";\n DiskImageResourceGDAL out_rsrc( out_file, applied_image.format(),\n Vector2i(vw_settings().default_tile_size(),\n vw_settings().default_tile_size()),\n gdal_settings(applied_image.cols(),\n applied_image.rows()));\n block_write_image( out_rsrc, applied_image,\n TerminalProgressCallback(\"asp\", \"\\t \"+tag+\": \"));\n}\n\nvoid\nasp::StereoSessionIsis::pre_preprocessing_hook(std::string const& input_file1,\n std::string const& input_file2,\n std::string & output_file1,\n std::string & output_file2) {\n output_file1 = m_out_prefix + \"-L.tif\";\n output_file2 = m_out_prefix + \"-R.tif\";\n\n if ( fs::exists(output_file1) && fs::exists(output_file2) ) {\n try {\n vw_log().console_log().rule_set().add_rule(-1,\"fileio\");\n DiskImageView<PixelGray<float32> > out1(output_file1);\n DiskImageView<PixelGray<float32> > out2(output_file2);\n vw_out(InfoMessage) << \"\\t--> Using cached normalized input images.\\n\";\n vw_settings().reload_config();\n return;\n } catch (vw::ArgumentErr const& e) {\n \/\/ This throws on a corrupted file.\n vw_settings().reload_config();\n } catch (vw::IOErr const& e) {\n vw_settings().reload_config();\n }\n }\n\n float left_lo, left_hi, right_lo, right_hi;\n find_ideal_isis_range( input_file1, \"left\",\n left_lo, left_hi );\n find_ideal_isis_range( input_file2, \"right\",\n right_lo, right_hi );\n\n \/\/ Working out alignment\n float lo = std::min (left_lo, right_lo); \/\/ Finding global\n float hi = std::max (left_hi, right_hi);\n Matrix<double> align_matrix(3,3);\n align_matrix.set_identity();\n if ( stereo_settings().keypoint_alignment) {\n DiskImageView<PixelGray<float> > left_disk_image(input_file1);\n DiskImageView<PixelGray<float> > right_disk_image(input_file2);\n ImageViewRef<PixelGray<float> > left_view =\n normalize(remove_isis_special_pixels(left_disk_image, lo),\n lo, hi, 0, 1.0);\n ImageViewRef<PixelGray<float> > right_view =\n normalize(remove_isis_special_pixels(right_disk_image, lo),\n lo, hi, 0, 1.0);\n align_matrix = determine_image_align(input_file1, input_file2,\n left_view, right_view );\n }\n write_matrix( m_out_prefix + \"-align.exr\", align_matrix );\n\n \/\/ Getting left image size\n Vector2i left_size;\n {\n DiskImageView<PixelGray<float> > left_image(input_file1);\n left_size = Vector2i(left_image.cols(), left_image.rows());\n }\n\n \/\/ Apply alignment and normalization\n if (stereo_settings().individually_normalize == 0 ) {\n vw_out() << \"\\t--> Normalizing globally to: [\"<<lo<<\" \"<<hi<<\"]\\n\";\n write_preprocessed_isis_image( input_file1, output_file1, \"left\",\n left_lo, left_hi, lo, hi,\n math::identity_matrix<3>(), left_size );\n write_preprocessed_isis_image( input_file2, output_file2, \"right\",\n right_lo, right_hi, lo, hi,\n align_matrix, left_size );\n } else {\n vw_out() << \"\\t--> Individually normalizing.\\n\";\n write_preprocessed_isis_image( input_file1, output_file1, \"left\",\n left_lo, left_hi, left_lo, left_hi,\n math::identity_matrix<3>(), left_size );\n write_preprocessed_isis_image( input_file2, output_file2, \"right\",\n right_lo, right_hi, right_lo, right_hi,\n align_matrix, left_size );\n }\n}\n\ninline std::string write_shadow_mask( std::string const& output_prefix,\n std::string const& input_image,\n std::string const& mask_postfix ) {\n \/\/ This thresholds at -25000 as the input sub4s for Apollo that I've\n \/\/ processed have a range somewhere between -32000 and +32000. -ZMM\n DiskImageView<PixelGray<float> > disk_image( input_image );\n DiskImageView<uint8> disk_mask( output_prefix + mask_postfix );\n ImageViewRef<uint8> mask =\n apply_mask(intersect_mask(create_mask(disk_mask),\n create_mask(threshold(disk_image,-25000,0,1.0))));\n std::string output_mask =\n output_prefix+mask_postfix.substr(0,mask_postfix.size()-4)+\"Debug.tif\";\n\n DiskImageResourceGDAL\n out_mask_rsrc( output_mask, mask.format(),\n Vector2i(vw_settings().default_tile_size(),\n vw_settings().default_tile_size()),\n gdal_settings( mask.cols(), mask.rows()) );\n block_write_image( out_mask_rsrc, mask );\n return output_mask;\n}\n\n\/\/ Stage 2: Correlation\n\/\/\n\/\/ Pre file is a pair of grayscale images. ( ImageView<PixelGray<float> > )\n\/\/ Post file is a disparity map. ( ImageView<PixelMask<Vector2f> > )\nvoid\nasp::StereoSessionIsis::pre_filtering_hook(std::string const& input_file,\n std::string & output_file) {\n output_file = input_file;\n\n \/\/ ****************************************************\n \/\/ The following code is for Apollo Metric Camera ONLY!\n \/\/ (use at your own risk)\n \/\/ ****************************************************\n if (stereo_settings().mask_flatfield) {\n vw_out() << \"\\t--> Masking pixels that are less than 0.0. (NOTE: Use this option with Apollo Metric Camera frames only!)\\n\";\n output_file = m_out_prefix + \"-R-masked.exr\";\n\n std::string shadowLmask_name =\n write_shadow_mask( m_out_prefix, m_left_image_file,\n \"-lMask.tif\" );\n std::string shadowRmask_name =\n write_shadow_mask( m_out_prefix, m_right_image_file,\n \"-rMask.tif\" );\n\n DiskImageView<uint8> shadowLmask( shadowLmask_name );\n DiskImageView<uint8> shadowRmask( shadowRmask_name );\n\n DiskImageView<PixelMask<Vector2f> > disparity_disk_image(input_file);\n ImageViewRef<PixelMask<Vector2f> > disparity_map =\n stereo::disparity_mask(disparity_disk_image,\n shadowLmask, shadowRmask );\n\n DiskImageResourceOpenEXR disparity_map_rsrc(output_file, disparity_map.format() );\n Vector2i block_size(std::min<size_t>(vw_settings().default_tile_size(),\n disparity_map.cols()),\n std::min<size_t>(vw_settings().default_tile_size(),\n disparity_map.rows()));\n disparity_map_rsrc.set_block_write_size(block_size);\n block_write_image( disparity_map_rsrc, disparity_map,\n TerminalProgressCallback( \"asp\", \"\\t--> Saving Mask :\") );\n }\n}\n\n\/\/ Reverse any pre-alignment that was done to the images.\nvoid\nasp::StereoSessionIsis::pre_pointcloud_hook(std::string const& input_file,\n std::string & output_file) {\n\n \/\/ ****************************************************\n \/\/ The following code is for Apollo Metric Camera ONLY!\n \/\/ (use at your own risk)\n \/\/ ****************************************************\n std::string dust_result = input_file;\n if ( stereo_settings().mask_flatfield ) {\n vw_out() << \"\\t--> Masking pixels that appear to be dust. (NOTE: Use this option with Apollo Metric Camera frames only!)\\n\";\n photometric_outlier_rejection( m_out_prefix, input_file,\n dust_result, stereo_settings().h_kern );\n }\n\n DiskImageView<PixelMask<Vector2f> > disparity_map(dust_result);\n output_file = m_out_prefix + \"-F-corrected.tif\";\n\n \/\/ We used a homography to line up the images, we may want\n \/\/ to generate pre-alignment disparities before passing this information\n \/\/ onto the camera model in the next stage of the stereo pipeline.\n Matrix<double> align_matrix;\n try {\n read_matrix(align_matrix, m_out_prefix + \"-align.exr\");\n vw_out(DebugMessage) << \"Alignment Matrix: \" << align_matrix << \"\\n\";\n } catch (vw::IOErr const& e) {\n vw_out() << \"\\nCould not read in aligment matrix: \" << m_out_prefix\n << \"-align.exr. Exiting. \\n\\n\";\n exit(1);\n }\n\n \/\/ Remove pixels that are outside the bounds of the secondary image.\n DiskImageView<PixelGray<float> > right_disk_image(m_right_image_file);\n ImageViewRef<PixelMask<Vector2f> > result =\n stereo::disparity_range_mask(stereo::transform_disparities(disparity_map,\n HomographyTransform(align_matrix)),\n Vector2f(0,0),\n Vector2f( right_disk_image.cols(),\n right_disk_image.rows() ) );\n\n DiskImageResourceGDAL\n disparity_corrected_rsrc( output_file, result.format(),\n Vector2i(vw_settings().default_tile_size(),\n vw_settings().default_tile_size()),\n gdal_settings( result.cols(), result.rows() ) );\n block_write_image( disparity_corrected_rsrc, result,\n TerminalProgressCallback(\"asp\", \"\\t Processing:\"));\n}\n\nboost::shared_ptr<vw::camera::CameraModel>\nasp::StereoSessionIsis::camera_model(std::string const& image_file,\n std::string const& camera_file) {\n\n if (boost::ends_with(boost::to_lower_copy(camera_file), \".isis_adjust\")){\n \/\/ Creating Equations for the files\n std::ifstream input( camera_file.c_str() );\n boost::shared_ptr<asp::BaseEquation> posF = read_equation( input );\n boost::shared_ptr<asp::BaseEquation> poseF = read_equation( input );\n input.close();\n\n \/\/ Finally creating camera model\n return boost::shared_ptr<camera::CameraModel>(new IsisAdjustCameraModel( image_file, posF, poseF ));\n\n } else {\n return boost::shared_ptr<camera::CameraModel>(new IsisCameraModel(image_file));\n }\n\n}\n\n\n<commit_msg>Use Common for StereoSession parallel write<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2011 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n\/\/\/ \\file StereoSessionIsis.cc\n\/\/\/\n\n\/\/ Vision Workbench\n#include <vw\/FileIO.h>\n#include <vw\/Math\/Functors.h>\n#include <vw\/Math\/Geometry.h>\n#include <vw\/Math\/RANSAC.h>\n#include <vw\/InterestPoint.h>\n#include <vw\/Stereo\/DisparityMap.h>\n#include <vw\/Cartography.h>\n\n\/\/ Stereo Pipeline\n#include <asp\/Sessions\/ISIS\/StereoSessionIsis.h>\n#include <asp\/IsisIO\/IsisCameraModel.h>\n#include <asp\/Core\/StereoSettings.h>\n#include <asp\/IsisIO\/IsisAdjustCameraModel.h>\n#include <asp\/IsisIO\/DiskImageResourceIsis.h>\n#include <asp\/Sessions\/ISIS\/PhotometricOutlier.h>\n\n\/\/ Boost\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/shared_ptr.hpp>\nnamespace fs = boost::filesystem;\n\n#include <algorithm>\n\nusing namespace vw;\nusing namespace vw::camera;\nusing namespace asp;\n\n\/\/ Allows FileIO to correctly read\/write these pixel types\nnamespace vw {\n template<> struct PixelFormatID<Vector3> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };\n}\n\n\/\/ Process a single ISIS image to find an ideal min max. The reason we\n\/\/ need to do this, is that ASP is to get image intensity values in\n\/\/ the range of 0-1. To some extent we are compressing the dynamic\n\/\/ range, but we try to minimize that.\nvoid find_ideal_isis_range( std::string const& in_file,\n std::string const& tag,\n float & isis_lo, float & isis_hi ) {\n\n boost::shared_ptr<DiskImageResourceIsis> isis_rsrc( new DiskImageResourceIsis(in_file) );\n DiskImageView<PixelGray<float> > disk_image(isis_rsrc);\n\n float isis_mean, isis_std;\n\n \/\/ Calculating statistics. We subsample the images so statistics\n \/\/ only does about a million samples.\n {\n vw_out(InfoMessage) << \"\\t--> Computing statistics for the \"+tag+\" image\\n\";\n int left_stat_scale = int(ceil(sqrt(float(disk_image.cols())*float(disk_image.rows()) \/ 1000000)));\n ChannelAccumulator<math::CDFAccumulator<float> > accumulator;\n for_each_pixel(\n subsample(create_mask( edge_extend(disk_image, ConstantEdgeExtension()),\n isis_rsrc->valid_minimum(),\n isis_rsrc->valid_maximum() ),\n left_stat_scale ),\n accumulator );\n isis_lo = accumulator.quantile(0);\n isis_hi = accumulator.quantile(1);\n isis_mean = accumulator.approximate_mean();\n isis_std = accumulator.approximate_stddev();\n\n vw_out(InfoMessage) << \"\\t \"+tag+\": [ lo:\" << isis_lo << \" hi:\" << isis_hi\n << \" m: \" << isis_mean << \" s: \" << isis_std << \"]\\n\";\n }\n\n \/\/ Normalizing to -+2 sigmas around mean\n if ( stereo_settings().force_max_min == 0 ) {\n vw_out(InfoMessage) << \"\\t--> Adjusting hi and lo to -+2 sigmas around mean.\\n\";\n\n if ( isis_lo < isis_mean - 2*isis_std )\n isis_lo = isis_mean - 2*isis_std;\n if ( isis_hi > isis_mean + 2*isis_std )\n isis_hi = isis_mean + 2*isis_std;\n\n vw_out(InfoMessage) << \"\\t \"+tag+\" changed: [ lo:\"\n << isis_lo << \" hi:\" << isis_hi << \"]\\n\";\n }\n}\n\n\/\/ This actually modifies and writes the pre-processed image.\nvoid write_preprocessed_isis_image( BaseOptions const& opt,\n std::string const& in_file,\n std::string const& out_file,\n std::string const& tag,\n float const& isis_lo, float const& isis_hi,\n float const& out_lo, float const& out_hi,\n Matrix<double> const& matrix,\n Vector2i const& crop_size ) {\n DiskImageView<PixelGray<float> > disk_image(in_file);\n ImageViewRef<PixelGray<float> > applied_image;\n if ( matrix == math::identity_matrix<3>() ) {\n applied_image =\n crop(edge_extend(clamp(normalize(remove_isis_special_pixels(disk_image,\n isis_lo, isis_hi, out_lo),\n out_lo, out_hi, 0.0, 1.0)),\n ZeroEdgeExtension()),\n 0, 0, crop_size[0], crop_size[1]);\n } else {\n applied_image =\n clamp(transform(normalize(remove_isis_special_pixels(disk_image,\n isis_lo, isis_hi,\n out_lo),\n out_lo, out_hi, 0.0, 1.0),\n HomographyTransform(matrix),\n crop_size[0], crop_size[1]));\n }\n\n \/\/ Write the results to disk.\n vw_out() << \"\\t--> Writing normalized images.\\n\";\n block_write_gdal_image( out_file, applied_image, opt,\n TerminalProgressCallback(\"asp\", \"\\t \"+tag+\": \") );\n}\n\nvoid\nasp::StereoSessionIsis::pre_preprocessing_hook(std::string const& input_file1,\n std::string const& input_file2,\n std::string & output_file1,\n std::string & output_file2) {\n output_file1 = m_out_prefix + \"-L.tif\";\n output_file2 = m_out_prefix + \"-R.tif\";\n\n if ( fs::exists(output_file1) && fs::exists(output_file2) ) {\n try {\n vw_log().console_log().rule_set().add_rule(-1,\"fileio\");\n DiskImageView<PixelGray<float32> > out1(output_file1);\n DiskImageView<PixelGray<float32> > out2(output_file2);\n vw_out(InfoMessage) << \"\\t--> Using cached normalized input images.\\n\";\n vw_settings().reload_config();\n return;\n } catch (vw::ArgumentErr const& e) {\n \/\/ This throws on a corrupted file.\n vw_settings().reload_config();\n } catch (vw::IOErr const& e) {\n vw_settings().reload_config();\n }\n }\n\n float left_lo, left_hi, right_lo, right_hi;\n find_ideal_isis_range( input_file1, \"left\",\n left_lo, left_hi );\n find_ideal_isis_range( input_file2, \"right\",\n right_lo, right_hi );\n\n \/\/ Working out alignment\n float lo = std::min (left_lo, right_lo); \/\/ Finding global\n float hi = std::max (left_hi, right_hi);\n Matrix<double> align_matrix(3,3);\n align_matrix.set_identity();\n if ( stereo_settings().keypoint_alignment) {\n DiskImageView<PixelGray<float> > left_disk_image(input_file1);\n DiskImageView<PixelGray<float> > right_disk_image(input_file2);\n ImageViewRef<PixelGray<float> > left_view =\n normalize(remove_isis_special_pixels(left_disk_image, lo),\n lo, hi, 0, 1.0);\n ImageViewRef<PixelGray<float> > right_view =\n normalize(remove_isis_special_pixels(right_disk_image, lo),\n lo, hi, 0, 1.0);\n align_matrix = determine_image_align(input_file1, input_file2,\n left_view, right_view );\n }\n write_matrix( m_out_prefix + \"-align.exr\", align_matrix );\n\n \/\/ Getting left image size\n Vector2i left_size;\n {\n DiskImageView<PixelGray<float> > left_image(input_file1);\n left_size = Vector2i(left_image.cols(), left_image.rows());\n }\n\n \/\/ Apply alignment and normalization\n if (stereo_settings().individually_normalize == 0 ) {\n vw_out() << \"\\t--> Normalizing globally to: [\"<<lo<<\" \"<<hi<<\"]\\n\";\n write_preprocessed_isis_image( m_options, input_file1, output_file1, \"left\",\n left_lo, left_hi, lo, hi,\n math::identity_matrix<3>(), left_size );\n write_preprocessed_isis_image( m_options, input_file2, output_file2, \"right\",\n right_lo, right_hi, lo, hi,\n align_matrix, left_size );\n } else {\n vw_out() << \"\\t--> Individually normalizing.\\n\";\n write_preprocessed_isis_image( m_options, input_file1, output_file1, \"left\",\n left_lo, left_hi, left_lo, left_hi,\n math::identity_matrix<3>(), left_size );\n write_preprocessed_isis_image( m_options, input_file2, output_file2, \"right\",\n right_lo, right_hi, right_lo, right_hi,\n align_matrix, left_size );\n }\n}\n\ninline std::string write_shadow_mask( BaseOptions const& opt,\n std::string const& output_prefix,\n std::string const& input_image,\n std::string const& mask_postfix ) {\n \/\/ This thresholds at -25000 as the input sub4s for Apollo that I've\n \/\/ processed have a range somewhere between -32000 and +32000. -ZMM\n DiskImageView<PixelGray<float> > disk_image( input_image );\n DiskImageView<uint8> disk_mask( output_prefix + mask_postfix );\n ImageViewRef<uint8> mask =\n apply_mask(intersect_mask(create_mask(disk_mask),\n create_mask(threshold(disk_image,-25000,0,1.0))));\n std::string output_mask =\n output_prefix+mask_postfix.substr(0,mask_postfix.size()-4)+\"Debug.tif\";\n\n block_write_gdal_image( output_mask, mask, opt,\n TerminalProgressCallback(\"asp\",\"\\t Shadow:\") );\n return output_mask;\n}\n\n\/\/ Stage 2: Correlation\n\/\/\n\/\/ Pre file is a pair of grayscale images. ( ImageView<PixelGray<float> > )\n\/\/ Post file is a disparity map. ( ImageView<PixelMask<Vector2f> > )\nvoid\nasp::StereoSessionIsis::pre_filtering_hook(std::string const& input_file,\n std::string & output_file) {\n output_file = input_file;\n\n \/\/ ****************************************************\n \/\/ The following code is for Apollo Metric Camera ONLY!\n \/\/ (use at your own risk)\n \/\/ ****************************************************\n if (stereo_settings().mask_flatfield) {\n vw_out() << \"\\t--> Masking pixels that are less than 0.0. (NOTE: Use this option with Apollo Metric Camera frames only!)\\n\";\n output_file = m_out_prefix + \"-R-masked.exr\";\n\n std::string shadowLmask_name =\n write_shadow_mask( m_options, m_out_prefix, m_left_image_file,\n \"-lMask.tif\" );\n std::string shadowRmask_name =\n write_shadow_mask( m_options, m_out_prefix, m_right_image_file,\n \"-rMask.tif\" );\n\n DiskImageView<uint8> shadowLmask( shadowLmask_name );\n DiskImageView<uint8> shadowRmask( shadowRmask_name );\n\n DiskImageView<PixelMask<Vector2f> > disparity_disk_image(input_file);\n ImageViewRef<PixelMask<Vector2f> > disparity_map =\n stereo::disparity_mask(disparity_disk_image,\n shadowLmask, shadowRmask );\n\n DiskImageResourceOpenEXR disparity_map_rsrc(output_file, disparity_map.format() );\n Vector2i block_size(std::min<size_t>(vw_settings().default_tile_size(),\n disparity_map.cols()),\n std::min<size_t>(vw_settings().default_tile_size(),\n disparity_map.rows()));\n disparity_map_rsrc.set_block_write_size(block_size);\n block_write_image( disparity_map_rsrc, disparity_map,\n TerminalProgressCallback( \"asp\", \"\\t--> Saving Mask :\") );\n }\n}\n\n\/\/ Reverse any pre-alignment that was done to the images.\nvoid\nasp::StereoSessionIsis::pre_pointcloud_hook(std::string const& input_file,\n std::string & output_file) {\n\n \/\/ ****************************************************\n \/\/ The following code is for Apollo Metric Camera ONLY!\n \/\/ (use at your own risk)\n \/\/ ****************************************************\n std::string dust_result = input_file;\n if ( stereo_settings().mask_flatfield ) {\n vw_out() << \"\\t--> Masking pixels that appear to be dust. (NOTE: Use this option with Apollo Metric Camera frames only!)\\n\";\n photometric_outlier_rejection( m_out_prefix, input_file,\n dust_result, stereo_settings().h_kern );\n }\n\n DiskImageView<PixelMask<Vector2f> > disparity_map(dust_result);\n output_file = m_out_prefix + \"-F-corrected.tif\";\n\n \/\/ We used a homography to line up the images, we may want\n \/\/ to generate pre-alignment disparities before passing this information\n \/\/ onto the camera model in the next stage of the stereo pipeline.\n Matrix<double> align_matrix;\n try {\n read_matrix(align_matrix, m_out_prefix + \"-align.exr\");\n vw_out(DebugMessage) << \"Alignment Matrix: \" << align_matrix << \"\\n\";\n } catch (vw::IOErr const& e) {\n vw_out() << \"\\nCould not read in aligment matrix: \" << m_out_prefix\n << \"-align.exr. Exiting. \\n\\n\";\n exit(1);\n }\n\n \/\/ Remove pixels that are outside the bounds of the secondary image.\n DiskImageView<PixelGray<float> > right_disk_image(m_right_image_file);\n ImageViewRef<PixelMask<Vector2f> > result =\n stereo::disparity_range_mask(stereo::transform_disparities(disparity_map,\n HomographyTransform(align_matrix)),\n Vector2f(0,0),\n Vector2f( right_disk_image.cols(),\n right_disk_image.rows() ) );\n\n block_write_gdal_image( output_file, result, m_options,\n TerminalProgressCallback(\"asp\", \"\\t Processing:\") );\n}\n\nboost::shared_ptr<vw::camera::CameraModel>\nasp::StereoSessionIsis::camera_model(std::string const& image_file,\n std::string const& camera_file) {\n\n if (boost::ends_with(boost::to_lower_copy(camera_file), \".isis_adjust\")){\n \/\/ Creating Equations for the files\n std::ifstream input( camera_file.c_str() );\n boost::shared_ptr<asp::BaseEquation> posF = read_equation( input );\n boost::shared_ptr<asp::BaseEquation> poseF = read_equation( input );\n input.close();\n\n \/\/ Finally creating camera model\n return boost::shared_ptr<camera::CameraModel>(new IsisAdjustCameraModel( image_file, posF, poseF ));\n\n } else {\n return boost::shared_ptr<camera::CameraModel>(new IsisCameraModel(image_file));\n }\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef VECMATH_HPP\n#define VECMATH_HPP\n\n#include <SFML\/System.hpp>\n#include <cmath>\n\nnamespace vecmath\n{\n const float pi = 3.1415926535897;\n\n template<typename T>\nT norm(const sf::Vector2<T>& a)\n{\n return std::sqrt(a.x*a.x + a.y*a.y);\n}\n\ntemplate<typename T>\n\nT dot(const sf::Vector2<T>& a, const sf::Vector2<T>& b)\n{\n return a.x*b.x + a.y*b.y;\n}\n}\n\n#endif \/* VECMATH_HPP *\/\n<commit_msg>Added function to compute intersection of two vectors<commit_after>#ifndef VECMATH_HPP\n#define VECMATH_HPP\n\n#include <SFML\/System.hpp>\n#include <cmath>\n\nnamespace vecmath\n{\nconst float pi = 3.1415926535897;\n\ntemplate<typename T>\nT norm(const sf::Vector2<T>& a)\n{\n return std::sqrt(a.x*a.x + a.y*a.y);\n}\n\ntemplate<typename T>\nT dot(const sf::Vector2<T>& a, const sf::Vector2<T>& b)\n{\n return a.x*b.x + a.y*b.y;\n}\n\ntemplate<typename T>\nbool intersect(const sf::Vector2<T>& p0, const sf::Vector2<T>& p1,\n const sf::Vector2<T>& q0, const sf::Vector2<T>& q1,\n sf::Vector2<T>* intersection)\n{\n auto dp = sf::Vector2<T>(-(q1.y-q0.y), q1.x-q0.x);\n auto dq = q1 - q0;\n \/\/ dp is orthogonal to p1-p0, so if dp.dq = 0 then\n \/\/ dp is parallel to dq and there's no intersection\n if(std::abs(vecmath::dot(dp, dq)) < 10e-5) return false;\n float mu = vecmath::dot((p0 - q0), dp) \/ vecmath::dot(dp, dq);\n \/\/ mu is parameter for Q\n intersection->x = q0.x + mu * (q1.x-q0.x);\n intersection->y = q0.y + mu * (q1.y-q0.y);\n\n return true;\n}\n}\n\n#endif \/* VECMATH_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Sterlingcoin\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \": Full Release\"\n\/\/# define GIT_COMMIT_DATE \"$Format:%cD\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE GIT_COMMIT_DATE\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<commit_msg>One release<commit_after>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Sterlingcoin\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \": Release\"\n\/\/# define GIT_COMMIT_DATE \"$Format:%cD\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE GIT_COMMIT_DATE\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<|endoftext|>"} {"text":"<commit_before>#include \"dynet\/nodes.h\"\n#include \"dynet\/dynet.h\"\n#include \"dynet\/training.h\"\n#include \"dynet\/gpu-ops.h\"\n#include \"dynet\/expr.h\"\n#include \"dynet\/mp.h\"\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace dynet;\nusing namespace dynet::expr;\nusing namespace dynet::mp;\n\nstruct Datum {\n Datum() {}\n Datum(const vector<dynet::real>& x, const dynet::real y) : x(x), y(y) {}\n\n vector<dynet::real> x;\n dynet::real y;\n};\n\nclass XorModel {\npublic:\n XorModel(const unsigned hidden_size, Model& dynet_model) : pcg(nullptr) {\n p_W = dynet_model.add_parameters({hidden_size, 2});\n p_b = dynet_model.add_parameters({hidden_size});\n p_V = dynet_model.add_parameters({1, hidden_size});\n p_a = dynet_model.add_parameters({1});\n }\n\n void new_graph(ComputationGraph& cg) {\n W = parameter(cg, p_W);\n b = parameter(cg, p_b);\n V = parameter(cg, p_V);\n a = parameter(cg, p_a);\n pcg = &cg;\n }\n\n Expression compute_loss(const Datum& datum) {\n Expression x = input(*pcg, {2}, &datum.x);\n Expression y = input(*pcg, &datum.y);\n\n Expression h = tanh(W*x + b);\n Expression y_pred = V*h + a;\n Expression loss_expr = squared_distance(y_pred, y);\n return loss_expr;\n }\n\nprivate:\n XorModel() : pcg(nullptr) {}\n\n Parameter p_W, p_b, p_V, p_a;\n Expression W, b, V, a;\n ComputationGraph* pcg;\n\n friend class boost::serialization::access;\n template<class Archive>\n void serialize(Archive& ar, const unsigned int) {\n ar & p_W & p_b & p_V & p_a;\n }\n};\n\nvoid serialize(const XorModel* const xor_model, const Model& dynet_model, const Trainer* const trainer) {\n \/\/ Remove existing stdout output\n int r = ftruncate(fileno(stdout), 0);\n if (r != 0) {}\n\n \/\/ Move the cursor to the beginning of the stdout stream\n fseek(stdout, 0, SEEK_SET);\n\n \/\/ Dump the model to stdout\n boost::archive::text_oarchive oa(cout);\n oa & dynet_model;\n oa & xor_model;\n oa & trainer;\n}\n\nvoid deserialize(const string& filename, XorModel* xor_model, Model& dynet_model, Trainer* trainer) {\n ifstream in(filename.c_str());\n boost::archive::text_iarchive ia(in);\n ia & dynet_model;\n ia & xor_model;\n ia & trainer;\n in.close();\n}\n\nclass SufficientStats {\npublic:\n dynet::real loss;\n unsigned example_count;\n\n SufficientStats() : loss(), example_count() {}\n\n SufficientStats(dynet::real loss, unsigned example_count) : loss(loss), example_count(example_count) {}\n\n SufficientStats& operator+=(const SufficientStats& rhs) {\n loss += rhs.loss;\n example_count += rhs.example_count;\n return *this;\n }\n\n friend SufficientStats operator+(SufficientStats lhs, const SufficientStats& rhs) {\n lhs += rhs;\n return lhs;\n }\n\n bool operator<(const SufficientStats& rhs) {\n return loss < rhs.loss;\n }\n\n friend std::ostream& operator<< (std::ostream& stream, const SufficientStats& stats) {\n return stream << exp(stats.loss \/ stats.example_count) << \" (\" << stats.loss << \" over \" << stats.example_count << \" examples)\";\n }\n};\n\nclass Learner : public ILearner<Datum, SufficientStats> {\npublic:\n Learner(XorModel* xor_model, Model& dynet_model, const Trainer* const trainer, bool quiet) : xor_model(xor_model), dynet_model(dynet_model), trainer(trainer), quiet(quiet) {}\n ~Learner() {}\n SufficientStats LearnFromDatum(const Datum& datum, bool learn) {\n ComputationGraph cg;\n xor_model->new_graph(cg);\n Expression loss_expr = xor_model->compute_loss(datum);\n dynet::real loss = as_scalar(loss_expr.value());\n\n if (learn) {\n cg.backward(loss_expr);\n }\n return SufficientStats(loss, 1);\n }\n\n void SaveModel() {\n if (!quiet) {\n serialize(xor_model, dynet_model, trainer);\n }\n }\n\nprivate:\n XorModel* xor_model;\n Model& dynet_model; \n const Trainer* const trainer;\n bool quiet;\n};\n\nint main(int argc, char** argv) {\n dynet::initialize(argc, argv, true);\n\n \/\/ parameters\n const unsigned num_cores = 4;\n const unsigned ITERATIONS = 1000;\n Model dynet_model;\n XorModel* xor_model = nullptr;\n Trainer* trainer = nullptr;\n\n if (argc == 2) {\n \/\/ Load the model and parameters from file if given.\n deserialize(argv[1], xor_model, dynet_model, trainer);\n }\n else {\n \/\/ Otherwise, just create a new model.\n const unsigned HIDDEN_SIZE = 8;\n xor_model = new XorModel(HIDDEN_SIZE, dynet_model);\n trainer = new SimpleSGDTrainer(&dynet_model);\n }\n\n vector<Datum> data(4);\n data[0] = Datum({0, 0}, 0);\n data[1] = Datum({0, 1}, 1);\n data[2] = Datum({1, 0}, 1);\n data[3] = Datum({1, 1}, 0);\n\n Learner learner(xor_model, dynet_model, trainer, true);\n if (num_cores == 0) {\n run_single_process<Datum>(&learner, trainer, data, data, ITERATIONS, data.size(), data.size(), data.size());\n }\n else {\n run_multi_process<Datum>(num_cores, &learner, trainer, data, data, ITERATIONS, data.size(), data.size());\n }\n}\n<commit_msg>allow xor-mp to dump its model to stdout<commit_after>#include \"dynet\/nodes.h\"\n#include \"dynet\/dynet.h\"\n#include \"dynet\/training.h\"\n#include \"dynet\/gpu-ops.h\"\n#include \"dynet\/expr.h\"\n#include \"dynet\/mp.h\"\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace dynet;\nusing namespace dynet::expr;\nusing namespace dynet::mp;\n\nstruct Datum {\n Datum() {}\n Datum(const vector<dynet::real>& x, const dynet::real y) : x(x), y(y) {}\n\n vector<dynet::real> x;\n dynet::real y;\n};\n\nclass XorModel {\npublic:\n XorModel(const unsigned hidden_size, Model& dynet_model) : pcg(nullptr) {\n p_W = dynet_model.add_parameters({hidden_size, 2});\n p_b = dynet_model.add_parameters({hidden_size});\n p_V = dynet_model.add_parameters({1, hidden_size});\n p_a = dynet_model.add_parameters({1});\n }\n\n void new_graph(ComputationGraph& cg) {\n W = parameter(cg, p_W);\n b = parameter(cg, p_b);\n V = parameter(cg, p_V);\n a = parameter(cg, p_a);\n pcg = &cg;\n }\n\n Expression compute_loss(const Datum& datum) {\n Expression x = input(*pcg, {2}, &datum.x);\n Expression y = input(*pcg, &datum.y);\n\n Expression h = tanh(W*x + b);\n Expression y_pred = V*h + a;\n Expression loss_expr = squared_distance(y_pred, y);\n return loss_expr;\n }\n\nprivate:\n XorModel() : pcg(nullptr) {}\n\n Parameter p_W, p_b, p_V, p_a;\n Expression W, b, V, a;\n ComputationGraph* pcg;\n\n friend class boost::serialization::access;\n template<class Archive>\n void serialize(Archive& ar, const unsigned int) {\n ar & p_W & p_b & p_V & p_a;\n }\n};\n\nvoid serialize(const XorModel* const xor_model, const Model& dynet_model, const Trainer* const trainer) {\n \/\/ Remove existing stdout output\n int r = ftruncate(fileno(stdout), 0);\n if (r != 0) {}\n\n \/\/ Move the cursor to the beginning of the stdout stream\n fseek(stdout, 0, SEEK_SET);\n\n \/\/ Dump the model to stdout\n boost::archive::text_oarchive oa(cout);\n oa & dynet_model;\n oa & xor_model;\n oa & trainer;\n}\n\nvoid deserialize(const string& filename, XorModel* xor_model, Model& dynet_model, Trainer* trainer) {\n ifstream in(filename.c_str());\n boost::archive::text_iarchive ia(in);\n ia & dynet_model;\n ia & xor_model;\n ia & trainer;\n in.close();\n}\n\nclass SufficientStats {\npublic:\n dynet::real loss;\n unsigned example_count;\n\n SufficientStats() : loss(), example_count() {}\n\n SufficientStats(dynet::real loss, unsigned example_count) : loss(loss), example_count(example_count) {}\n\n SufficientStats& operator+=(const SufficientStats& rhs) {\n loss += rhs.loss;\n example_count += rhs.example_count;\n return *this;\n }\n\n friend SufficientStats operator+(SufficientStats lhs, const SufficientStats& rhs) {\n lhs += rhs;\n return lhs;\n }\n\n bool operator<(const SufficientStats& rhs) {\n return loss < rhs.loss;\n }\n\n friend std::ostream& operator<< (std::ostream& stream, const SufficientStats& stats) {\n return stream << exp(stats.loss \/ stats.example_count) << \" (\" << stats.loss << \" over \" << stats.example_count << \" examples)\";\n }\n};\n\nclass Learner : public ILearner<Datum, SufficientStats> {\npublic:\n Learner(XorModel* xor_model, Model& dynet_model, const Trainer* const trainer, bool quiet) : xor_model(xor_model), dynet_model(dynet_model), trainer(trainer), quiet(quiet) {}\n ~Learner() {}\n SufficientStats LearnFromDatum(const Datum& datum, bool learn) {\n ComputationGraph cg;\n xor_model->new_graph(cg);\n Expression loss_expr = xor_model->compute_loss(datum);\n dynet::real loss = as_scalar(loss_expr.value());\n\n if (learn) {\n cg.backward(loss_expr);\n }\n return SufficientStats(loss, 1);\n }\n\n void SaveModel() {\n if (!quiet) {\n serialize(xor_model, dynet_model, trainer);\n }\n }\n\nprivate:\n XorModel* xor_model;\n Model& dynet_model; \n const Trainer* const trainer;\n bool quiet;\n};\n\nint main(int argc, char** argv) {\n dynet::initialize(argc, argv, true);\n\n \/\/ parameters\n const unsigned num_cores = 4;\n const unsigned ITERATIONS = 1000;\n Model dynet_model;\n XorModel* xor_model = nullptr;\n Trainer* trainer = nullptr;\n\n if (argc == 2) {\n \/\/ Load the model and parameters from file if given.\n deserialize(argv[1], xor_model, dynet_model, trainer);\n }\n else {\n \/\/ Otherwise, just create a new model.\n const unsigned HIDDEN_SIZE = 8;\n xor_model = new XorModel(HIDDEN_SIZE, dynet_model);\n trainer = new SimpleSGDTrainer(&dynet_model);\n }\n\n vector<Datum> data(4);\n data[0] = Datum({0, 0}, 0);\n data[1] = Datum({0, 1}, 1);\n data[2] = Datum({1, 0}, 1);\n data[3] = Datum({1, 1}, 0);\n\n Learner learner(xor_model, dynet_model, trainer, false);\n if (num_cores == 0) {\n run_single_process<Datum>(&learner, trainer, data, data, ITERATIONS, data.size(), data.size(), data.size());\n }\n else {\n run_multi_process<Datum>(num_cores, &learner, trainer, data, data, ITERATIONS, data.size(), data.size());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com>\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#include \"linkedassetstore.hpp\"\n\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/make_shared.hpp>\n#include <string>\n#include <time.h>\n\nusing namespace std;\n\nnamespace asio = boost::asio;\nnamespace fs = boost::filesystem;\n\nusing namespace bithorded;\n\nconst fs::path META_DIR = \".bh_meta\/assets\";\nconst fs::path TIGER_DIR = \".bh_meta\/tiger\";\n\nconst int THREADPOOL_CONCURRENCY = 4;\n\nLinkedAssetStore::LinkedAssetStore(boost::asio::io_service& ioSvc, const boost::filesystem3::path& baseDir) :\n\t_threadPool(THREADPOOL_CONCURRENCY),\n\t_ioSvc(ioSvc),\n\t_baseDir(baseDir),\n\t_assetsFolder(baseDir\/META_DIR),\n\t_tigerFolder(baseDir\/TIGER_DIR)\n{\n\tif (!fs::exists(_baseDir))\n\t\tthrow ios_base::failure(\"LinkedAssetStore: baseDir does not exist\");\n\tif (!fs::exists(_assetsFolder))\n\t\tfs::create_directories(_assetsFolder);\n\tif (!fs::exists(_tigerFolder))\n\t\tfs::create_directories(_tigerFolder);\n\tsrand(time(NULL));\n}\n\nstruct HashTask : public Task {\n\tAsset::Ptr asset;\n\tasio::io_service& io_svc;\n\tasio::io_service::work _work;\n\tLinkedAssetStore::ResultHandler handler;\n\n\tHashTask(Asset::Ptr asset, asio::io_service& io_svc, LinkedAssetStore::ResultHandler handler )\n\t\t: asset(asset), io_svc(io_svc), _work(io_svc), handler(handler)\n\t{}\n\t\n\tvoid operator()() {\n\t\tasset->notifyValidRange(0, asset->size());\n\n\t\tio_svc.post(boost::bind(handler, asset));\n\t\tdelete this;\n\t}\n};\n\nbool path_is_in(const fs::path& path, const fs::path& folder) {\n\tstring path_(fs::absolute(path).string());\n\tstring folder_(fs::absolute(folder).string()+'\/');\n\treturn boost::starts_with(path_, folder_);\n}\n\nstring random_string(size_t len) {\n\tstatic const char alphanum[] =\n\t\t\"0123456789\"\n\t\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\t\t\"abcdefghijklmnopqrstuvwxyz\";\n\n\tstring s(len, ' ');\n\tfor (size_t i = 0; i < len; ++i) {\n\t\ts[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n\t}\n\n\treturn s;\n}\n\nbool LinkedAssetStore::addAsset(const boost::filesystem3::path& file, LinkedAssetStore::ResultHandler handler)\n{\n\tif (!path_is_in(file, _baseDir)) {\n\t\treturn false;\n\t} else {\n\t\tfs::path assetFolder;\n\t\tdo {\n\t\t\tassetFolder = _assetsFolder \/ random_string(20);\n\t\t} while (fs::exists(assetFolder));\n\n\t\tfs::create_directory(assetFolder);\n\t\tfs::create_symlink(file, assetFolder\/\"data\");\n\n\t\tAsset::Ptr asset = boost::make_shared<Asset>(assetFolder);\n\t\tHashTask* task = new HashTask(asset, _ioSvc, boost::bind(&LinkedAssetStore::_addAsset, this, _1, handler));\n\t\t_threadPool.post(*task);\n\t\treturn true;\n\t}\n}\n\nvoid LinkedAssetStore::_addAsset(Asset::Ptr& asset, LinkedAssetStore::ResultHandler upstream)\n{\n\tBitHordeIds ids;\n\tif (asset.get() && asset->getIds(ids)) {\n\t\tfor (auto iter=ids.begin(); iter != ids.end(); iter++) {\n\t\t\tif (iter->type() == bithorde::HashType::TREE_TIGER) {\n\t\t\t\tfs::path link = _tigerFolder \/ base32encode(iter->id());\n\t\t\t\tif (fs::exists(fs::symlink_status(link)))\n\t\t\t\t\tfs::remove(link);\n\n\t\t\t\t\/\/ TODO: make links relative instead, so storage can be moved around a little.\n\t\t\t\tfs::create_symlink(fs::absolute(asset->folder()), link);\n\t\t\t}\n\t\t}\n\t}\n\tupstream(asset);\n}\n\nAsset::Ptr LinkedAssetStore::findAsset(const BitHordeIds& ids)\n{\n\tfor (auto iter=ids.begin(); iter != ids.end(); iter++) {\n\t\tif (iter->type() == bithorde::HashType::TREE_TIGER) {\n\t\t\tfs::path link = _tigerFolder \/ base32encode(iter->id());\n\t\t\tboost::system::error_code e;\n\t\t\tauto asset = fs::read_symlink(link, e);\n\t\t\tif (!e && fs::is_directory(asset)) {\n\t\t\t\treturn boost::make_shared<Asset>(asset);\n\t\t\t}\n\t\t}\n\t}\n\treturn Asset::Ptr();\n}\n\n\n<commit_msg>[bithorded\/store\/LinkedAssetStore]Validate asset-status (including checking mtime) before returning it.<commit_after>\/*\n Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com>\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#include \"linkedassetstore.hpp\"\n\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/make_shared.hpp>\n#include <string>\n#include <time.h>\n#include <utime.h>\n\nusing namespace std;\n\nnamespace asio = boost::asio;\nnamespace fs = boost::filesystem;\n\nusing namespace bithorded;\n\nconst fs::path META_DIR = \".bh_meta\/assets\";\nconst fs::path TIGER_DIR = \".bh_meta\/tiger\";\n\nconst int THREADPOOL_CONCURRENCY = 4;\n\nLinkedAssetStore::LinkedAssetStore(boost::asio::io_service& ioSvc, const boost::filesystem3::path& baseDir) :\n\t_threadPool(THREADPOOL_CONCURRENCY),\n\t_ioSvc(ioSvc),\n\t_baseDir(baseDir),\n\t_assetsFolder(baseDir\/META_DIR),\n\t_tigerFolder(baseDir\/TIGER_DIR)\n{\n\tif (!fs::exists(_baseDir))\n\t\tthrow ios_base::failure(\"LinkedAssetStore: baseDir does not exist\");\n\tif (!fs::exists(_assetsFolder))\n\t\tfs::create_directories(_assetsFolder);\n\tif (!fs::exists(_tigerFolder))\n\t\tfs::create_directories(_tigerFolder);\n\tsrand(time(NULL));\n}\n\nstruct HashTask : public Task {\n\tAsset::Ptr asset;\n\tasio::io_service& io_svc;\n\tasio::io_service::work _work;\n\tLinkedAssetStore::ResultHandler handler;\n\n\tHashTask(Asset::Ptr asset, asio::io_service& io_svc, LinkedAssetStore::ResultHandler handler )\n\t\t: asset(asset), io_svc(io_svc), _work(io_svc), handler(handler)\n\t{}\n\t\n\tvoid operator()() {\n\t\tasset->notifyValidRange(0, asset->size());\n\n\t\tio_svc.post(boost::bind(handler, asset));\n\t\tdelete this;\n\t}\n};\n\nbool path_is_in(const fs::path& path, const fs::path& folder) {\n\tstring path_(fs::absolute(path).string());\n\tstring folder_(fs::absolute(folder).string()+'\/');\n\treturn boost::starts_with(path_, folder_);\n}\n\nstring random_string(size_t len) {\n\tstatic const char alphanum[] =\n\t\t\"0123456789\"\n\t\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\t\t\"abcdefghijklmnopqrstuvwxyz\";\n\n\tstring s(len, ' ');\n\tfor (size_t i = 0; i < len; ++i) {\n\t\ts[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n\t}\n\n\treturn s;\n}\n\nbool LinkedAssetStore::addAsset(const boost::filesystem3::path& file, LinkedAssetStore::ResultHandler handler)\n{\n\tif (!path_is_in(file, _baseDir)) {\n\t\treturn false;\n\t} else {\n\t\tfs::path assetFolder;\n\t\tdo {\n\t\t\tassetFolder = _assetsFolder \/ random_string(20);\n\t\t} while (fs::exists(assetFolder));\n\n\t\tfs::create_directory(assetFolder);\n\t\tfs::create_symlink(file, assetFolder\/\"data\");\n\n\t\tAsset::Ptr asset = boost::make_shared<Asset>(assetFolder);\n\t\tHashTask* task = new HashTask(asset, _ioSvc, boost::bind(&LinkedAssetStore::_addAsset, this, _1, handler));\n\t\t_threadPool.post(*task);\n\t\treturn true;\n\t}\n}\n\nvoid LinkedAssetStore::_addAsset(Asset::Ptr& asset, LinkedAssetStore::ResultHandler upstream)\n{\n\tBitHordeIds ids;\n\tif (asset.get() && asset->getIds(ids)) {\n\t\tconst char *data_path = (asset->folder()\/\"data\").c_str();\n\t\tlutimes(data_path, NULL);\n\t\tcerr << data_path << endl;\n\n\t\tfor (auto iter=ids.begin(); iter != ids.end(); iter++) {\n\t\t\tif (iter->type() == bithorde::HashType::TREE_TIGER) {\n\t\t\t\tfs::path link = _tigerFolder \/ base32encode(iter->id());\n\t\t\t\tif (fs::exists(fs::symlink_status(link)))\n\t\t\t\t\tfs::remove(link);\n\n\t\t\t\t\/\/ TODO: make links relative instead, so storage can be moved around a little.\n\t\t\t\tfs::create_symlink(fs::absolute(asset->folder()), link);\n\t\t\t}\n\t\t}\n\t}\n\tupstream(asset);\n}\n\n\nvoid purgeLink(const fs::path& path) {\n\tfs::remove(path);\n}\n\nvoid purgeLinkAndAsset(const fs::path& path) {\n\tboost::system::error_code e;\n\tauto asset = fs::read_symlink(path, e);\n\tpurgeLink(path);\n\tif (!e && fs::is_directory(asset))\n\t\tfs::remove_all(asset);\n}\n\nenum LinkStatus{\n\tOK,\n\tBROKEN,\n\tOUTDATED,\n};\n\nLinkStatus validateDataSymlink(const fs::path& path) {\n\tstruct stat linkStat, dataStat;\n\n\tconst char* c_path = path.c_str();\n\tif (lstat(c_path, &linkStat) ||\n\t !S_ISLNK(linkStat.st_mode) ||\n\t stat(c_path, &dataStat) ||\n\t !S_ISREG(dataStat.st_mode))\n\t\treturn BROKEN;\n\tif (linkStat.st_mtime >= dataStat.st_mtime)\n\t\treturn OK;\n\telse\n\t\treturn OUTDATED;\n}\n\nvoid noop(Asset::Ptr) {}\n\nAsset::Ptr LinkedAssetStore::findAsset(const BitHordeIds& ids)\n{\n\tfor (auto iter=ids.begin(); iter != ids.end(); iter++) {\n\t\tif (iter->type() == bithorde::HashType::TREE_TIGER) {\n\t\t\tfs::path hashLink = _tigerFolder \/ base32encode(iter->id());\n\t\t\tboost::system::error_code e;\n\t\t\tauto assetFolder = fs::read_symlink(hashLink, e);\n\t\t\tAsset::Ptr asset;\n\t\t\tif (e || !fs::is_directory(assetFolder)) {\n\t\t\t\tpurgeLink(hashLink);\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tauto assetDataPath = assetFolder\/\"data\";\n\t\t\t\tswitch (validateDataSymlink(assetDataPath)) {\n\t\t\t\tcase OUTDATED:\n\t\t\t\t\tcerr << \"Warning; outdated asset detected, \" << assetFolder << endl;\n\t\t\t\t\tpurgeLink(hashLink);\n\t\t\t\t\tfs::remove(assetFolder\/\"meta\");\n\t\t\t\tcase OK:\n\t\t\t\t\tasset = boost::make_shared<Asset>(assetFolder);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase BROKEN:\n\t\t\t\t\tcerr << \"Warning; broken asset detected, \" << assetFolder << endl;\n\t\t\t\t\tpurgeLinkAndAsset(hashLink);\n\t\t\t\tdefault:\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (asset->hasRootHash()) {\n\t\t\t\treturn asset;\n\t\t\t} else {\n\t\t\t\tcerr << \"Unhashed asset detected, hashing\" << endl;\n\t\t\t\t_threadPool.post(*new HashTask(asset, _ioSvc, boost::bind(&LinkedAssetStore::_addAsset, this, _1, &noop)));\n\t\t\t}\n\t\t}\n\t}\n\treturn Asset::Ptr();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: Filter.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2003-12-11 12:28:37 $\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 FORMS_COMPONENT_FILTER_HXX\n#define FORMS_COMPONENT_FILTER_HXX\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_\n#include <com\/sun\/star\/sdbc\/XDatabaseMetaData.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FORM_XBOUNDCOMPONENT_HPP_\n#include <com\/sun\/star\/form\/XBoundComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_\n#include <com\/sun\/star\/util\/XNumberFormatter.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XTEXTCOMPONENT_HPP_\n#include <com\/sun\/star\/awt\/XTextComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_\n#include <com\/sun\/star\/sdb\/SQLContext.hpp>\n#endif\n\n#ifndef _TOOLKIT_CONTROLS_UNOCONTROL_HXX_\n#include <toolkit\/controls\/unocontrol.hxx>\n#endif\n\n#ifndef _TOOLKIT_AWT_LISTENERMULTIPLEXER_HXX_\n#include <toolkit\/helper\/listenermultiplexer.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE5_HXX_\n#include <cppuhelper\/implbase5.hxx>\n#endif\n\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE4_HXX_\n#include <cppuhelper\/implbase4.hxx>\n#endif\n#ifndef _CONNECTIVITY_SQLPARSE_HXX\n#include <connectivity\/sqlparse.hxx>\n#endif\n\n#ifndef SVX_QUERYDESIGNCONTEXT_HXX\n#include <svx\/ParseContext.hxx>\n#endif\n\nclass Window;\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/ OFilterControl\n \/\/=====================================================================\n typedef ::cppu::ImplHelper5 < ::com::sun::star::awt::XTextComponent\n , ::com::sun::star::awt::XFocusListener\n , ::com::sun::star::awt::XItemListener\n , ::com::sun::star::form::XBoundComponent\n , ::com::sun::star::lang::XInitialization\n > OFilterControl_BASE;\n\n class OFilterControl :public UnoControl\n ,public OFilterControl_BASE\n ,public ::svxform::OParseContextClient\n {\n TextListenerMultiplexer m_aTextListeners;\n\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB;\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xField;\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xMessageParent;\n\n ::rtl::OUString m_aText;\n ::connectivity::OSQLParser m_aParser;\n sal_Int16 m_nControlClass; \/\/ which kind of control do we use?\n sal_Bool m_bFilterList : 1;\n sal_Bool m_bMultiLine : 1;\n sal_Bool m_bFilterListFilled : 1;\n\n private:\n\/\/ OFilterControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);\n\n void implInitFilterList();\n\n public:\n OFilterControl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB );\n\n DECLARE_UNO3_AGG_DEFAULTS(OFilterControl,OWeakAggObject);\n ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n\n static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId();\n sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 > & rId );\n\n virtual ::rtl::OUString GetComponentServiceName();\n virtual void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit > & rxToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > & rParentPeer ) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::lang::XComponent\n virtual void SAL_CALL dispose(void) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::awt::XTextComponent\n virtual void SAL_CALL addTextListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextListener > & l ) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL removeTextListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextListener > & l ) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL setText( const ::rtl::OUString& aText ) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL insertText( const ::com::sun::star::awt::Selection& rSel, const ::rtl::OUString& aText ) throw( ::com::sun::star::uno::RuntimeException );\n virtual ::rtl::OUString SAL_CALL getText() throw( ::com::sun::star::uno::RuntimeException );\n virtual ::rtl::OUString SAL_CALL getSelectedText() throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL setSelection( const ::com::sun::star::awt::Selection& aSelection ) throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::awt::Selection SAL_CALL getSelection() throw( ::com::sun::star::uno::RuntimeException );\n virtual sal_Bool SAL_CALL isEditable() throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL setEditable( sal_Bool bEditable ) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL setMaxTextLen( sal_Int16 nLength ) throw( ::com::sun::star::uno::RuntimeException );\n virtual sal_Int16 SAL_CALL getMaxTextLen() throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::form::XBoundComponent\n virtual void SAL_CALL addUpdateListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XUpdateListener > & l) throw( ::com::sun::star::uno::RuntimeException ) {}\n virtual void SAL_CALL removeUpdateListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XUpdateListener > & l) throw( ::com::sun::star::uno::RuntimeException ) {}\n virtual sal_Bool SAL_CALL commit() throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::lang::XEventListener\n virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::awt::XFocusListener\n virtual void SAL_CALL focusGained(const ::com::sun::star::awt::FocusEvent& e) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL focusLost(const ::com::sun::star::awt::FocusEvent& e) throw( ::com::sun::star::uno::RuntimeException ){}\n\n \/\/ ::com::sun::star::awt::XItemListener\n virtual void SAL_CALL itemStateChanged(const ::com::sun::star::awt::ItemEvent& rEvent) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::util::XInitialization\n virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ com::sun::star::lang::XServiceInfo - static version\n static ::rtl::OUString SAL_CALL getImplementationName_Static();\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static();\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory );\n\n protected:\n virtual void PrepareWindowDescriptor( ::com::sun::star::awt::WindowDescriptor& rDesc );\n virtual void ImplSetPeerProperty( const ::rtl::OUString& rPropName, const ::com::sun::star::uno::Any& rVal );\n\n sal_Bool ensureInitialized( );\n\n void displayException( const ::com::sun::star::sdb::SQLContext& _rExcept );\n };\n\/\/.........................................................................\n} \/\/ namespace frm\n\/\/.........................................................................\n\n#endif \/\/ FORMS_COMPONENT_FILTER_HXX\n<commit_msg>INTEGRATION: CWS dba12 (1.3.40); FILE MERGED 2004\/04\/28 06:54:32 fs 1.3.40.1: #i26720# use a OPredicateInputController to normalize the input<commit_after>\/*************************************************************************\n *\n * $RCSfile: Filter.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hjs $ $Date: 2004-06-28 17:09:14 $\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 FORMS_COMPONENT_FILTER_HXX\n#define FORMS_COMPONENT_FILTER_HXX\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FORM_XBOUNDCOMPONENT_HPP_\n#include <com\/sun\/star\/form\/XBoundComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_\n#include <com\/sun\/star\/util\/XNumberFormatter.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XTEXTCOMPONENT_HPP_\n#include <com\/sun\/star\/awt\/XTextComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_\n#include <com\/sun\/star\/sdb\/SQLContext.hpp>\n#endif\n\n#ifndef _TOOLKIT_CONTROLS_UNOCONTROL_HXX_\n#include <toolkit\/controls\/unocontrol.hxx>\n#endif\n\n#ifndef _TOOLKIT_AWT_LISTENERMULTIPLEXER_HXX_\n#include <toolkit\/helper\/listenermultiplexer.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE5_HXX_\n#include <cppuhelper\/implbase5.hxx>\n#endif\n\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE4_HXX_\n#include <cppuhelper\/implbase4.hxx>\n#endif\n#ifndef _CONNECTIVITY_SQLPARSE_HXX\n#include <connectivity\/sqlparse.hxx>\n#endif\n\n#ifndef SVX_QUERYDESIGNCONTEXT_HXX\n#include <svx\/ParseContext.hxx>\n#endif\n\nclass Window;\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/ OFilterControl\n \/\/=====================================================================\n typedef ::cppu::ImplHelper5 < ::com::sun::star::awt::XTextComponent\n , ::com::sun::star::awt::XFocusListener\n , ::com::sun::star::awt::XItemListener\n , ::com::sun::star::form::XBoundComponent\n , ::com::sun::star::lang::XInitialization\n > OFilterControl_BASE;\n\n class OFilterControl :public UnoControl\n ,public OFilterControl_BASE\n ,public ::svxform::OParseContextClient\n {\n TextListenerMultiplexer m_aTextListeners;\n\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB;\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xField;\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xMessageParent;\n\n ::rtl::OUString m_aText;\n ::connectivity::OSQLParser m_aParser;\n sal_Int16 m_nControlClass; \/\/ which kind of control do we use?\n sal_Bool m_bFilterList : 1;\n sal_Bool m_bMultiLine : 1;\n sal_Bool m_bFilterListFilled : 1;\n\n private:\n\/\/ OFilterControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);\n\n void implInitFilterList();\n\n public:\n OFilterControl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB );\n\n DECLARE_UNO3_AGG_DEFAULTS(OFilterControl,OWeakAggObject);\n ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n\n static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId();\n sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 > & rId );\n\n virtual ::rtl::OUString GetComponentServiceName();\n virtual void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit > & rxToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > & rParentPeer ) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::lang::XComponent\n virtual void SAL_CALL dispose(void) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::awt::XTextComponent\n virtual void SAL_CALL addTextListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextListener > & l ) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL removeTextListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextListener > & l ) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL setText( const ::rtl::OUString& aText ) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL insertText( const ::com::sun::star::awt::Selection& rSel, const ::rtl::OUString& aText ) throw( ::com::sun::star::uno::RuntimeException );\n virtual ::rtl::OUString SAL_CALL getText() throw( ::com::sun::star::uno::RuntimeException );\n virtual ::rtl::OUString SAL_CALL getSelectedText() throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL setSelection( const ::com::sun::star::awt::Selection& aSelection ) throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::awt::Selection SAL_CALL getSelection() throw( ::com::sun::star::uno::RuntimeException );\n virtual sal_Bool SAL_CALL isEditable() throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL setEditable( sal_Bool bEditable ) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL setMaxTextLen( sal_Int16 nLength ) throw( ::com::sun::star::uno::RuntimeException );\n virtual sal_Int16 SAL_CALL getMaxTextLen() throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::form::XBoundComponent\n virtual void SAL_CALL addUpdateListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XUpdateListener > & l) throw( ::com::sun::star::uno::RuntimeException ) {}\n virtual void SAL_CALL removeUpdateListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XUpdateListener > & l) throw( ::com::sun::star::uno::RuntimeException ) {}\n virtual sal_Bool SAL_CALL commit() throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::lang::XEventListener\n virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::awt::XFocusListener\n virtual void SAL_CALL focusGained(const ::com::sun::star::awt::FocusEvent& e) throw( ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL focusLost(const ::com::sun::star::awt::FocusEvent& e) throw( ::com::sun::star::uno::RuntimeException ){}\n\n \/\/ ::com::sun::star::awt::XItemListener\n virtual void SAL_CALL itemStateChanged(const ::com::sun::star::awt::ItemEvent& rEvent) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ ::com::sun::star::util::XInitialization\n virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ com::sun::star::lang::XServiceInfo - static version\n static ::rtl::OUString SAL_CALL getImplementationName_Static();\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static();\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory );\n\n protected:\n virtual void PrepareWindowDescriptor( ::com::sun::star::awt::WindowDescriptor& rDesc );\n virtual void ImplSetPeerProperty( const ::rtl::OUString& rPropName, const ::com::sun::star::uno::Any& rVal );\n\n sal_Bool ensureInitialized( );\n\n void displayException( const ::com::sun::star::sdb::SQLContext& _rExcept );\n };\n\/\/.........................................................................\n} \/\/ namespace frm\n\/\/.........................................................................\n\n#endif \/\/ FORMS_COMPONENT_FILTER_HXX\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\nnamespace Channel9\n{\n\t\/\/round a number up to the nearest power of 2\n\ttemplate<typename uint>\n\tinline uint ceil_power2(uint v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tif(sizeof(uint) >= 2) v |= v >> 8;\n\t\tif(sizeof(uint) >= 4) v |= v >> 16;\n\t\tif(sizeof(uint) >= 8) v |= v >> 32;\n\t\tv++;\n\t\treturn v;\n\t}\n\n\tinline uint64_t ceil_power2(uint64_t v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv |= v >> 8;\n\t\tv |= v >> 16;\n\t\tv |= v >> 32;\n\t\tv++;\n\t\treturn v;\n\t}\n\tinline uint32_t ceil_power2(uint32_t v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv |= v >> 8;\n\t\tv |= v >> 16;\n\t\tv++;\n\t\treturn v;\n\t}\n\tinline uint16_t ceil_power2(uint16_t v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv |= v >> 8;\n\t\tv++;\n\t\treturn v;\n\t}\n\tinline uint8_t ceil_power2(uint8_t v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv++;\n\t\treturn v;\n\t}\n\n\n\n\t\/\/returns true if exactly 1 bit is set\n\ttemplate<typename uint>\n\tinline bool is_power2(uint n){\n\t\treturn (n && !(n & (n - 1)));\n\t}\n\n\ttemplate<typename uint>\n\tinline uint clear_bottom_bits(uint n, int num_bits){\n\t\treturn (n & ~((1 << num_bits)-1));\n\t}\n\n\n\t\/\/count the trailing zeroes, essentially what power of 2 is it\n\ttemplate<typename uint>\n\tinline uint count_bottom_zeros1(uint n){\n\t\tif(n == 0)\n\t\t\treturn 0;\/\/sizeof(uint) * 8;\n\n\t\tuint count = 0;\n\t\twhile((n & 1) == 0){\n\t\t\t++count;\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn count;\n\t}\n\n\t\/\/count the trailing zeroes, essentially what power of 2 is it\n\ttemplate<typename uint>\n\tinline uint count_bottom_zeros2(uint n){\n\t\tif(n == 0)\n\t\t\treturn 0;\/\/sizeof(uint) * 8;\n\n\t\tuint count = 0;\n\t\tuint bits = sizeof(uint) * 4;\n\t\tdo {\n\t\t\tif((n & ((1 << bits) - 1)) == 0){\n\t\t\t\tcount += bits;\n\t\t\t\tn >>= bits;\n\t\t\t}\n\t\t\tbits >>= 1;\n\t\t}while(bits);\n\n\t\treturn count;\n\t}\n\n\t\/\/count the trailing zeroes, essentially what power of 2 is it\n\ttemplate<typename uint>\n\tinline uint count_bottom_zeros3(uint n){\n\t\tif(n == 0)\n\t\t\treturn 0;\/\/sizeof(uint) * 8;\n\n\t\tuint count = 0;\n\t\tuint bits = sizeof(uint) * 4;\n\t\tuint mask = (1 << bits) - 1;\n\t\tdo {\n\t\t\tif((n & mask) == 0){\n\t\t\t\tcount += bits;\n\t\t\t\tn >>= bits;\n\t\t\t}\n\t\t\tbits >>= 1;\n\t\t\tmask >>= bits;\n\t\t}while(bits && (n & 1) == 0);\n\n\t\treturn count;\n\t}\n\n\t\/\/count the trailing zeroes, essentially what power of 2 is it\n\ttemplate<typename uint>\n\tinline uint count_bottom_zeros4(uint n){\n\t\tif(n == 0)\n\t\t\treturn 0; \/\/sizeof(uint) * 8;\n\n\t\tuint count = 0;\n\n\t\tif(sizeof(uint) >= 8 && (n & 0xFFFFFFFFULL) == 0){ count += 32; n >>= 32; }\n\t\tif(sizeof(uint) >= 4 && (n & 0x0000FFFFULL) == 0){ count += 16; n >>= 16; }\n\t\tif(sizeof(uint) >= 2 && (n & 0x000000FFULL) == 0){ count += 8; n >>= 8; }\n\t\tif(sizeof(uint) >= 1 && (n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif(sizeof(uint) >= 1 && (n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif(sizeof(uint) >= 1 && (n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\n\t\treturn count;\n\t}\n\tinline uint8_t count_bottom_zeros4(uint8_t n){\n\t\tif(n == 0)\n\t\t\treturn 0;\n\t\tuint8_t count = 0;\n\t\tif((n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif((n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif((n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\t\treturn count;\n\t}\n\tinline uint16_t count_bottom_zeros4(uint16_t n){\n\t\tif(n == 0)\n\t\t\treturn 0;\n\t\tuint16_t count = 0;\n\t\tif((n & 0x000000FFULL) == 0){ count += 8; n >>= 8; }\n\t\tif((n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif((n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif((n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\t\treturn count;\n\t}\n\tinline uint32_t count_bottom_zeros4(uint32_t n){\n\t\tif(n == 0)\n\t\t\treturn 0;\n\t\tuint32_t count = 0;\n\t\tif((n & 0x0000FFFFULL) == 0){ count += 16; n >>= 16; }\n\t\tif((n & 0x000000FFULL) == 0){ count += 8; n >>= 8; }\n\t\tif((n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif((n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif((n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\t\treturn count;\n\t}\n\tinline uint64_t count_bottom_zeros4(uint64_t n){\n\t\tif(n == 0)\n\t\t\treturn 0;\n\t\tuint64_t count = 0;\n\t\tif((n & 0xFFFFFFFFULL) == 0){ count += 32; n >>= 32; }\n\t\tif((n & 0x0000FFFFULL) == 0){ count += 16; n >>= 16; }\n\t\tif((n & 0x000000FFULL) == 0){ count += 8; n >>= 8; }\n\t\tif((n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif((n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif((n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\t\treturn count;\n\t}\n\n\n\t\/\/count how many bits are set\n\ttemplate<typename uint>\n\tinline uint count_bits_set(uint n){\n\t\tuint count = 0;\n\t\twhile(n){\n\t\t\t++count;\n\t\t\tn &= (n - 1);\n\t\t}\n\t\treturn count;\n\t}\n\n\t\/\/give a good distribution over the hash space to have fewer collisions, both copied from MurmurHash\n\tinline uint32_t mix_bits(uint32_t h){\n\t\th ^= h >> 16;\n\t\th *= 0x85ebca6b;\n\t\th ^= h >> 13;\n\t\th *= 0xc2b2ae35;\n\t\th ^= h >> 16;\n\t\treturn h;\n\t}\n\tinline uint64_t mix_bits(uint64_t h){\n\t\th ^= h >> 33;\n\t\th *= 0xff51afd7ed558ccd;\n\t\th ^= h >> 33;\n\t\th *= 0xc4ceb9fe1a85ec53;\n\t\th ^= h >> 33;\n\t\treturn h;\n\t}\n}\n<commit_msg>Add a version of ceil_power2 that rounds up to a specific power of 2, this is useful for 8 byte alignment or similar<commit_after>#pragma once\n\nnamespace Channel9\n{\n\t\/\/round a number up to the nearest full power of 2\n\ttemplate<typename uint>\n\tinline uint ceil_power2(uint v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tif(sizeof(uint) >= 2) v |= v >> 8;\n\t\tif(sizeof(uint) >= 4) v |= v >> 16;\n\t\tif(sizeof(uint) >= 8) v |= v >> 32;\n\t\tv++;\n\t\treturn v;\n\t}\n\n\tinline uint64_t ceil_power2(uint64_t v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv |= v >> 8;\n\t\tv |= v >> 16;\n\t\tv |= v >> 32;\n\t\tv++;\n\t\treturn v;\n\t}\n\tinline uint32_t ceil_power2(uint32_t v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv |= v >> 8;\n\t\tv |= v >> 16;\n\t\tv++;\n\t\treturn v;\n\t}\n\tinline uint16_t ceil_power2(uint16_t v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv |= v >> 8;\n\t\tv++;\n\t\treturn v;\n\t}\n\tinline uint8_t ceil_power2(uint8_t v) {\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv++;\n\t\treturn v;\n\t}\n\n\t\/\/round up to a multiple of a specific power of 2\n\ttemplate<typename uint>\n\tinline uint ceil_power2(uint n, int bits){\n\t\tuint p = 1 << bits;\n\t\tuint m = p-1;\n\t\treturn (n + m) & ~m;\n\/\/\t\treturn n + ((p - (n & m)) & m);\n\/\/\t\treturn n + ((p - (n % p)) % p);\n\t}\n\n\n\t\/\/returns true if exactly 1 bit is set\n\ttemplate<typename uint>\n\tinline bool is_power2(uint n){\n\t\treturn (n && !(n & (n - 1)));\n\t}\n\n\ttemplate<typename uint>\n\tinline uint clear_bottom_bits(uint n, int num_bits){\n\t\treturn (n & ~((1 << num_bits)-1));\n\t}\n\n\n\t\/\/count the trailing zeroes, essentially what power of 2 is it\n\ttemplate<typename uint>\n\tinline uint count_bottom_zeros1(uint n){\n\t\tif(n == 0)\n\t\t\treturn 0;\/\/sizeof(uint) * 8;\n\n\t\tuint count = 0;\n\t\twhile((n & 1) == 0){\n\t\t\t++count;\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn count;\n\t}\n\n\t\/\/count the trailing zeroes, essentially what power of 2 is it\n\ttemplate<typename uint>\n\tinline uint count_bottom_zeros2(uint n){\n\t\tif(n == 0)\n\t\t\treturn 0;\/\/sizeof(uint) * 8;\n\n\t\tuint count = 0;\n\t\tuint bits = sizeof(uint) * 4;\n\t\tdo {\n\t\t\tif((n & ((1 << bits) - 1)) == 0){\n\t\t\t\tcount += bits;\n\t\t\t\tn >>= bits;\n\t\t\t}\n\t\t\tbits >>= 1;\n\t\t}while(bits);\n\n\t\treturn count;\n\t}\n\n\t\/\/count the trailing zeroes, essentially what power of 2 is it\n\ttemplate<typename uint>\n\tinline uint count_bottom_zeros3(uint n){\n\t\tif(n == 0)\n\t\t\treturn 0;\/\/sizeof(uint) * 8;\n\n\t\tuint count = 0;\n\t\tuint bits = sizeof(uint) * 4;\n\t\tuint mask = (1 << bits) - 1;\n\t\tdo {\n\t\t\tif((n & mask) == 0){\n\t\t\t\tcount += bits;\n\t\t\t\tn >>= bits;\n\t\t\t}\n\t\t\tbits >>= 1;\n\t\t\tmask >>= bits;\n\t\t}while(bits && (n & 1) == 0);\n\n\t\treturn count;\n\t}\n\n\t\/\/count the trailing zeroes, essentially what power of 2 is it\n\ttemplate<typename uint>\n\tinline uint count_bottom_zeros4(uint n){\n\t\tif(n == 0)\n\t\t\treturn 0; \/\/sizeof(uint) * 8;\n\n\t\tuint count = 0;\n\n\t\tif(sizeof(uint) >= 8 && (n & 0xFFFFFFFFULL) == 0){ count += 32; n >>= 32; }\n\t\tif(sizeof(uint) >= 4 && (n & 0x0000FFFFULL) == 0){ count += 16; n >>= 16; }\n\t\tif(sizeof(uint) >= 2 && (n & 0x000000FFULL) == 0){ count += 8; n >>= 8; }\n\t\tif(sizeof(uint) >= 1 && (n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif(sizeof(uint) >= 1 && (n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif(sizeof(uint) >= 1 && (n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\n\t\treturn count;\n\t}\n\tinline uint8_t count_bottom_zeros4(uint8_t n){\n\t\tif(n == 0)\n\t\t\treturn 0;\n\t\tuint8_t count = 0;\n\t\tif((n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif((n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif((n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\t\treturn count;\n\t}\n\tinline uint16_t count_bottom_zeros4(uint16_t n){\n\t\tif(n == 0)\n\t\t\treturn 0;\n\t\tuint16_t count = 0;\n\t\tif((n & 0x000000FFULL) == 0){ count += 8; n >>= 8; }\n\t\tif((n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif((n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif((n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\t\treturn count;\n\t}\n\tinline uint32_t count_bottom_zeros4(uint32_t n){\n\t\tif(n == 0)\n\t\t\treturn 0;\n\t\tuint32_t count = 0;\n\t\tif((n & 0x0000FFFFULL) == 0){ count += 16; n >>= 16; }\n\t\tif((n & 0x000000FFULL) == 0){ count += 8; n >>= 8; }\n\t\tif((n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif((n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif((n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\t\treturn count;\n\t}\n\tinline uint64_t count_bottom_zeros4(uint64_t n){\n\t\tif(n == 0)\n\t\t\treturn 0;\n\t\tuint64_t count = 0;\n\t\tif((n & 0xFFFFFFFFULL) == 0){ count += 32; n >>= 32; }\n\t\tif((n & 0x0000FFFFULL) == 0){ count += 16; n >>= 16; }\n\t\tif((n & 0x000000FFULL) == 0){ count += 8; n >>= 8; }\n\t\tif((n & 0x0000000FULL) == 0){ count += 4; n >>= 4; }\n\t\tif((n & 0x00000003ULL) == 0){ count += 2; n >>= 2; }\n\t\tif((n & 0x00000001ULL) == 0){ count += 1; n >>= 1; }\n\t\treturn count;\n\t}\n\n\n\t\/\/count how many bits are set\n\ttemplate<typename uint>\n\tinline uint count_bits_set(uint n){\n\t\tuint count = 0;\n\t\twhile(n){\n\t\t\t++count;\n\t\t\tn &= (n - 1);\n\t\t}\n\t\treturn count;\n\t}\n\n\t\/\/give a good distribution over the hash space to have fewer collisions, both copied from MurmurHash\n\tinline uint32_t mix_bits(uint32_t h){\n\t\th ^= h >> 16;\n\t\th *= 0x85ebca6b;\n\t\th ^= h >> 13;\n\t\th *= 0xc2b2ae35;\n\t\th ^= h >> 16;\n\t\treturn h;\n\t}\n\tinline uint64_t mix_bits(uint64_t h){\n\t\th ^= h >> 33;\n\t\th *= 0xff51afd7ed558ccd;\n\t\th ^= h >> 33;\n\t\th *= 0xc4ceb9fe1a85ec53;\n\t\th ^= h >> 33;\n\t\treturn h;\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015, Google Inc.\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:\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 disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. 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 *\/\n\n#include <string.h>\n\n#include <node.h>\n#include <nan.h>\n#include \"grpc\/grpc.h\"\n#include \"grpc\/byte_buffer_reader.h\"\n#include \"grpc\/support\/slice.h\"\n\n#include \"byte_buffer.h\"\n\nnamespace grpc {\nnamespace node {\n\n\nusing v8::Context;\nusing v8::Function;\nusing v8::Local;\nusing v8::Object;\nusing v8::Number;\nusing v8::Value;\n\ngrpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {\n Nan::HandleScope scope;\n int length = ::node::Buffer::Length(buffer);\n char *data = ::node::Buffer::Data(buffer);\n gpr_slice slice = gpr_slice_malloc(length);\n memcpy(GPR_SLICE_START_PTR(slice), data, length);\n grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));\n gpr_slice_unref(slice);\n return byte_buffer;\n}\n\nnamespace {\nvoid delete_buffer(char *data, void *hint) { delete[] data; }\n}\n\nLocal<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {\n Nan::EscapableHandleScope scope;\n if (buffer == NULL) {\n return scope.Escape(Nan::Null());\n }\n size_t length = grpc_byte_buffer_length(buffer);\n char *result = new char[length];\n size_t offset = 0;\n grpc_byte_buffer_reader reader;\n grpc_byte_buffer_reader_init(&reader, buffer);\n gpr_slice next;\n while (grpc_byte_buffer_reader_next(&reader, &next) != 0) {\n memcpy(result + offset, GPR_SLICE_START_PTR(next), GPR_SLICE_LENGTH(next));\n offset += GPR_SLICE_LENGTH(next);\n gpr_slice_unref(next);\n }\n return scope.Escape(MakeFastBuffer(\n Nan::NewBuffer(result, length, delete_buffer, NULL).ToLocalChecked()));\n}\n\nLocal<Value> MakeFastBuffer(Local<Value> slowBuffer) {\n Nan::EscapableHandleScope scope;\n Local<Object> globalObj = Nan::GetCurrentContext()->Global();\n Local<Function> bufferConstructor = Local<Function>::Cast(\n globalObj->Get(Nan::New(\"Buffer\").ToLocalChecked()));\n Local<Value> consArgs[3] = {\n slowBuffer,\n Nan::New<Number>(::node::Buffer::Length(slowBuffer)),\n Nan::New<Number>(0)\n };\n Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);\n return scope.Escape(fastBuffer);\n}\n} \/\/ namespace node\n} \/\/ namespace grpc\n<commit_msg>Make Node not segfault when it receives a compressed message<commit_after>\/*\n *\n * Copyright 2015, Google Inc.\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:\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 disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. 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 *\/\n\n#include <string.h>\n\n#include <node.h>\n#include <nan.h>\n#include \"grpc\/grpc.h\"\n#include \"grpc\/byte_buffer_reader.h\"\n#include \"grpc\/support\/slice.h\"\n#include \"grpc\/support\/log.h\"\n\n#include \"byte_buffer.h\"\n\nnamespace grpc {\nnamespace node {\n\n\nusing v8::Context;\nusing v8::Function;\nusing v8::Local;\nusing v8::Object;\nusing v8::Number;\nusing v8::Value;\n\ngrpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {\n Nan::HandleScope scope;\n int length = ::node::Buffer::Length(buffer);\n char *data = ::node::Buffer::Data(buffer);\n gpr_slice slice = gpr_slice_malloc(length);\n memcpy(GPR_SLICE_START_PTR(slice), data, length);\n grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));\n gpr_slice_unref(slice);\n return byte_buffer;\n}\n\nnamespace {\nvoid delete_buffer(char *data, void *hint) { delete[] data; }\n}\n\nLocal<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {\n Nan::EscapableHandleScope scope;\n if (buffer == NULL) {\n return scope.Escape(Nan::Null());\n }\n gpr_log(GPR_DEBUG, \"Compressed size: %d\", grpc_byte_buffer_length(buffer));\n grpc_byte_buffer_reader reader;\n grpc_byte_buffer_reader_init(&reader, buffer);\n gpr_slice slice = grpc_byte_buffer_reader_readall(&reader);\n size_t length = GPR_SLICE_LENGTH(slice);\n char *result = new char[length];\n memcpy(result, GPR_SLICE_START_PTR(slice), length);\n return scope.Escape(MakeFastBuffer(\n Nan::NewBuffer(result, length, delete_buffer, NULL).ToLocalChecked()));\n}\n\nLocal<Value> MakeFastBuffer(Local<Value> slowBuffer) {\n Nan::EscapableHandleScope scope;\n Local<Object> globalObj = Nan::GetCurrentContext()->Global();\n Local<Function> bufferConstructor = Local<Function>::Cast(\n globalObj->Get(Nan::New(\"Buffer\").ToLocalChecked()));\n Local<Value> consArgs[3] = {\n slowBuffer,\n Nan::New<Number>(::node::Buffer::Length(slowBuffer)),\n Nan::New<Number>(0)\n };\n Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);\n return scope.Escape(fastBuffer);\n}\n} \/\/ namespace node\n} \/\/ namespace grpc\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"fstream.hh\"\n#include \"align.hh\"\n#include \"circular_buffer.hh\"\n#include \"semaphore.hh\"\n#include \"reactor.hh\"\n#include <malloc.h>\n#include <string.h>\n\nclass file_data_source_impl : public data_source_impl {\n file _file;\n uint64_t _pos;\n size_t _buffer_size;\npublic:\n file_data_source_impl(file f, uint64_t pos, size_t buffer_size)\n : _file(std::move(f)), _pos(pos), _buffer_size(buffer_size) {}\n virtual future<temporary_buffer<char>> get() override {\n using buf_type = temporary_buffer<char>;\n return _file.dma_read_bulk<char>(_pos, _buffer_size).then(\n [this] (buf_type buf) {\n _pos += buf.size();\n return std::move(buf);\n });\n }\n};\n\nclass file_data_source : public data_source {\npublic:\n file_data_source(file f, uint64_t offset, size_t buffer_size)\n : data_source(std::make_unique<file_data_source_impl>(\n std::move(f), offset, buffer_size)) {}\n};\n\ninput_stream<char> make_file_input_stream(\n file f, uint64_t offset, size_t buffer_size) {\n return input_stream<char>(file_data_source(std::move(f), offset, buffer_size));\n}\n\nclass file_data_sink_impl : public data_sink_impl {\n file _file;\n file_output_stream_options _options;\n uint64_t _pos = 0;\n \/\/ At offsets < _preallocating_at, preallocation was completed.\n \/\/ At offsets >= _preallocating_at, we may be preallocating\n \/\/ disk space, so all writes must wait until _preallocation_done[i]\n \/\/ becomes ready (in _options.preallocation_size units)\n \/\/ At offsets >= _preallocating_at + _options.preallocation_size *\n \/\/ _preallocation_done.size(), we have not yet started.\n uint64_t _preallocating_at = 0;\n \/\/ Each promise vector lists writes that are waiting for a single preallocation\n circular_buffer<std::vector<promise<>>> _preallocation_done;\n semaphore _write_behind_sem = { _options.write_behind };\n future<> _background_writes_done = make_ready_future<>();\n bool _failed = false;\npublic:\n file_data_sink_impl(file f, file_output_stream_options options)\n : _file(std::move(f)), _options(options) {}\n future<> put(net::packet data) { abort(); }\n virtual temporary_buffer<char> allocate_buffer(size_t size) override {\n return temporary_buffer<char>::aligned(file::dma_alignment, size);\n }\n virtual future<> put(temporary_buffer<char> buf) override {\n uint64_t pos = _pos;\n _pos += buf.size();\n if (!_options.write_behind) {\n return do_put(pos, std::move(buf));\n }\n \/\/ Write behind strategy:\n \/\/\n \/\/ 1. Issue N writes in parallel, using a semphore to limit to N\n \/\/ 2. Collect results in _background_writes_done, merging exception futures\n \/\/ 3. If we've already seen a failure, don't issue more writes.\n return _write_behind_sem.wait().then([this, pos, buf = std::move(buf)] () mutable {\n if (_failed) {\n _write_behind_sem.signal();\n auto ret = std::move(_background_writes_done);\n _background_writes_done = make_ready_future<>();\n return ret;\n }\n auto this_write_done = do_put(pos, std::move(buf)).finally([this] {\n _write_behind_sem.signal();\n });\n _background_writes_done = when_all(std::move(_background_writes_done), std::move(this_write_done))\n .then([this] (std::tuple<future<>, future<>> possible_errors) {\n \/\/ merge the two errors, preferring the first\n auto& e1 = std::get<0>(possible_errors);\n auto& e2 = std::get<1>(possible_errors);\n if (e1.failed()) {\n e2.ignore_ready_future();\n return std::move(e1);\n } else {\n if (e2.failed()) {\n _failed = true;\n }\n return std::move(e2);\n }\n });\n return make_ready_future<>();\n });\n }\nprivate:\n virtual future<> do_put(uint64_t pos, temporary_buffer<char> buf) {\n \/\/ put() must usually be of chunks multiple of file::dma_alignment.\n \/\/ Only the last part can have an unaligned length. If put() was\n \/\/ called again with an unaligned pos, we have a bug in the caller.\n assert(!(pos & (file::dma_alignment - 1)));\n bool truncate = false;\n auto p = static_cast<const char*>(buf.get());\n size_t buf_size = buf.size();\n\n if ((buf.size() & (file::dma_alignment - 1)) != 0) {\n \/\/ If buf size isn't aligned, copy its content into a new aligned buf.\n \/\/ This should only happen when the user calls output_stream::flush().\n auto tmp = allocate_buffer(align_up(buf.size(), file::dma_alignment));\n ::memcpy(tmp.get_write(), buf.get(), buf.size());\n buf = std::move(tmp);\n p = buf.get();\n buf_size = buf.size();\n truncate = true;\n }\n auto prealloc = preallocate(pos, buf.size());\n return prealloc.then([this, pos, p, buf_size, truncate, buf = std::move(buf)] () mutable {\n return _file.dma_write(pos, p, buf_size).then(\n [this, buf = std::move(buf), truncate] (size_t size) {\n if (truncate) {\n return _file.truncate(_pos);\n }\n return make_ready_future<>();\n });\n });\n }\n future<> preallocate(uint64_t pos, uint64_t size) {\n auto ret = make_ready_future<>();\n if (pos + size <= _preallocating_at) {\n return ret;\n }\n auto skip = std::max(_preallocating_at, pos) - pos;\n pos += skip;\n size -= skip;\n size_t idx = (pos - _preallocating_at) \/ _options.preallocation_size;\n while (size) {\n if (idx == _preallocation_done.size()) {\n start_new_preallocation();\n }\n _preallocation_done[idx].emplace_back();\n auto this_prealloc_done = _preallocation_done[idx].back().get_future();\n ret = when_all(std::move(ret), std::move(this_prealloc_done)).discard_result();\n skip = std::min<uint64_t>(size, _options.preallocation_size);\n pos += skip;\n size -= skip;\n ++idx;\n }\n return ret;\n }\n void start_new_preallocation() {\n auto pos = _preallocating_at + _preallocation_done.size() * _options.preallocation_size;\n _preallocation_done.emplace_back();\n _file.allocate(pos, _options.preallocation_size).then_wrapped([this, pos] (future<> ret) {\n complete_preallocation(pos, std::move(ret));\n });\n }\n void complete_preallocation(uint64_t pos, future<> result) {\n \/\/ Preallocation may have failed. But it's just preallocation,\n \/\/ so we can ignore the result.\n result.ignore_ready_future();\n size_t idx = (pos - _preallocating_at) \/ _options.preallocation_size;\n for (auto&& pr : _preallocation_done[idx]) {\n pr.set_value();\n }\n _preallocation_done[idx].clear();\n while (!_preallocation_done.empty() && _preallocation_done.front().empty()) {\n _preallocation_done.pop_front();\n _preallocating_at += _options.preallocation_size;\n }\n }\n future<> wait() {\n return _write_behind_sem.wait(_options.write_behind).then([this] {\n return _background_writes_done.then([this] {\n \/\/ restore to pristine state; for flush() + close() sequence\n \/\/ (we allow either flush, or close, or both)\n _write_behind_sem.signal(_options.write_behind);\n _background_writes_done = make_ready_future<>();\n });\n });\n }\npublic:\n virtual future<> flush() override {\n return wait().then([this] {\n return _file.flush();\n });\n }\n virtual future<> close() {\n return wait().then([this] {\n return _file.close();\n });\n }\n};\n\nclass file_data_sink : public data_sink {\npublic:\n file_data_sink(file f, file_output_stream_options options)\n : data_sink(std::make_unique<file_data_sink_impl>(\n std::move(f), options)) {}\n};\n\noutput_stream<char> make_file_output_stream(file f, size_t buffer_size) {\n file_output_stream_options options;\n options.buffer_size = buffer_size;\n return make_file_output_stream(std::move(f), options);\n}\n\noutput_stream<char> make_file_output_stream(file f, file_output_stream_options options) {\n return output_stream<char>(file_data_sink(std::move(f), options), options.buffer_size, true);\n}\n\n<commit_msg>fstream: fix write-behind on filesystems that don't support fallocate()<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"fstream.hh\"\n#include \"align.hh\"\n#include \"circular_buffer.hh\"\n#include \"semaphore.hh\"\n#include \"reactor.hh\"\n#include <malloc.h>\n#include <string.h>\n\nclass file_data_source_impl : public data_source_impl {\n file _file;\n uint64_t _pos;\n size_t _buffer_size;\npublic:\n file_data_source_impl(file f, uint64_t pos, size_t buffer_size)\n : _file(std::move(f)), _pos(pos), _buffer_size(buffer_size) {}\n virtual future<temporary_buffer<char>> get() override {\n using buf_type = temporary_buffer<char>;\n return _file.dma_read_bulk<char>(_pos, _buffer_size).then(\n [this] (buf_type buf) {\n _pos += buf.size();\n return std::move(buf);\n });\n }\n};\n\nclass file_data_source : public data_source {\npublic:\n file_data_source(file f, uint64_t offset, size_t buffer_size)\n : data_source(std::make_unique<file_data_source_impl>(\n std::move(f), offset, buffer_size)) {}\n};\n\ninput_stream<char> make_file_input_stream(\n file f, uint64_t offset, size_t buffer_size) {\n return input_stream<char>(file_data_source(std::move(f), offset, buffer_size));\n}\n\nclass file_data_sink_impl : public data_sink_impl {\n file _file;\n file_output_stream_options _options;\n uint64_t _pos = 0;\n \/\/ At offsets < _preallocating_at, preallocation was completed.\n \/\/ At offsets >= _preallocating_at, we may be preallocating\n \/\/ disk space, so all writes must wait until _preallocation_done[i]\n \/\/ becomes ready (in _options.preallocation_size units)\n \/\/ At offsets >= _preallocating_at + _options.preallocation_size *\n \/\/ _preallocation_done.size(), we have not yet started.\n uint64_t _preallocating_at = 0;\n \/\/ Each promise vector lists writes that are waiting for a single preallocation\n circular_buffer<std::vector<promise<>>> _preallocation_done;\n semaphore _write_behind_sem = { _options.write_behind };\n future<> _background_writes_done = make_ready_future<>();\n bool _failed = false;\npublic:\n file_data_sink_impl(file f, file_output_stream_options options)\n : _file(std::move(f)), _options(options) {}\n future<> put(net::packet data) { abort(); }\n virtual temporary_buffer<char> allocate_buffer(size_t size) override {\n return temporary_buffer<char>::aligned(file::dma_alignment, size);\n }\n virtual future<> put(temporary_buffer<char> buf) override {\n uint64_t pos = _pos;\n _pos += buf.size();\n if (!_options.write_behind) {\n return do_put(pos, std::move(buf));\n }\n \/\/ Write behind strategy:\n \/\/\n \/\/ 1. Issue N writes in parallel, using a semphore to limit to N\n \/\/ 2. Collect results in _background_writes_done, merging exception futures\n \/\/ 3. If we've already seen a failure, don't issue more writes.\n return _write_behind_sem.wait().then([this, pos, buf = std::move(buf)] () mutable {\n if (_failed) {\n _write_behind_sem.signal();\n auto ret = std::move(_background_writes_done);\n _background_writes_done = make_ready_future<>();\n return ret;\n }\n auto this_write_done = do_put(pos, std::move(buf)).finally([this] {\n _write_behind_sem.signal();\n });\n _background_writes_done = when_all(std::move(_background_writes_done), std::move(this_write_done))\n .then([this] (std::tuple<future<>, future<>> possible_errors) {\n \/\/ merge the two errors, preferring the first\n auto& e1 = std::get<0>(possible_errors);\n auto& e2 = std::get<1>(possible_errors);\n if (e1.failed()) {\n e2.ignore_ready_future();\n return std::move(e1);\n } else {\n if (e2.failed()) {\n _failed = true;\n }\n return std::move(e2);\n }\n });\n return make_ready_future<>();\n });\n }\nprivate:\n virtual future<> do_put(uint64_t pos, temporary_buffer<char> buf) {\n \/\/ put() must usually be of chunks multiple of file::dma_alignment.\n \/\/ Only the last part can have an unaligned length. If put() was\n \/\/ called again with an unaligned pos, we have a bug in the caller.\n assert(!(pos & (file::dma_alignment - 1)));\n bool truncate = false;\n auto p = static_cast<const char*>(buf.get());\n size_t buf_size = buf.size();\n\n if ((buf.size() & (file::dma_alignment - 1)) != 0) {\n \/\/ If buf size isn't aligned, copy its content into a new aligned buf.\n \/\/ This should only happen when the user calls output_stream::flush().\n auto tmp = allocate_buffer(align_up(buf.size(), file::dma_alignment));\n ::memcpy(tmp.get_write(), buf.get(), buf.size());\n buf = std::move(tmp);\n p = buf.get();\n buf_size = buf.size();\n truncate = true;\n }\n auto prealloc = preallocate(pos, buf.size());\n return prealloc.then([this, pos, p, buf_size, truncate, buf = std::move(buf)] () mutable {\n return _file.dma_write(pos, p, buf_size).then(\n [this, buf = std::move(buf), truncate] (size_t size) {\n if (truncate) {\n return _file.truncate(_pos);\n }\n return make_ready_future<>();\n });\n });\n }\n future<> preallocate(uint64_t pos, uint64_t size) {\n auto ret = make_ready_future<>();\n restart:\n if (pos + size <= _preallocating_at) {\n return ret;\n }\n auto skip = std::max(_preallocating_at, pos) - pos;\n pos += skip;\n size -= skip;\n size_t idx = (pos - _preallocating_at) \/ _options.preallocation_size;\n while (size) {\n if (idx == _preallocation_done.size()) {\n start_new_preallocation();\n \/\/ May have caused _preallocating_at to change, so redo the loop\n goto restart;\n }\n _preallocation_done[idx].emplace_back();\n auto this_prealloc_done = _preallocation_done[idx].back().get_future();\n ret = when_all(std::move(ret), std::move(this_prealloc_done)).discard_result();\n skip = std::min<uint64_t>(size, _options.preallocation_size);\n pos += skip;\n size -= skip;\n ++idx;\n }\n return ret;\n }\n void start_new_preallocation() {\n auto pos = _preallocating_at + _preallocation_done.size() * _options.preallocation_size;\n _preallocation_done.emplace_back();\n _file.allocate(pos, _options.preallocation_size).then_wrapped([this, pos] (future<> ret) {\n complete_preallocation(pos, std::move(ret));\n });\n }\n void complete_preallocation(uint64_t pos, future<> result) {\n \/\/ Preallocation may have failed. But it's just preallocation,\n \/\/ so we can ignore the result.\n result.ignore_ready_future();\n size_t idx = (pos - _preallocating_at) \/ _options.preallocation_size;\n for (auto&& pr : _preallocation_done[idx]) {\n pr.set_value();\n }\n _preallocation_done[idx].clear();\n while (!_preallocation_done.empty() && _preallocation_done.front().empty()) {\n _preallocation_done.pop_front();\n _preallocating_at += _options.preallocation_size;\n }\n }\n future<> wait() {\n return _write_behind_sem.wait(_options.write_behind).then([this] {\n return _background_writes_done.then([this] {\n \/\/ restore to pristine state; for flush() + close() sequence\n \/\/ (we allow either flush, or close, or both)\n _write_behind_sem.signal(_options.write_behind);\n _background_writes_done = make_ready_future<>();\n });\n });\n }\npublic:\n virtual future<> flush() override {\n return wait().then([this] {\n return _file.flush();\n });\n }\n virtual future<> close() {\n return wait().then([this] {\n return _file.close();\n });\n }\n};\n\nclass file_data_sink : public data_sink {\npublic:\n file_data_sink(file f, file_output_stream_options options)\n : data_sink(std::make_unique<file_data_sink_impl>(\n std::move(f), options)) {}\n};\n\noutput_stream<char> make_file_output_stream(file f, size_t buffer_size) {\n file_output_stream_options options;\n options.buffer_size = buffer_size;\n return make_file_output_stream(std::move(f), options);\n}\n\noutput_stream<char> make_file_output_stream(file f, file_output_stream_options options) {\n return output_stream<char>(file_data_sink(std::move(f), options), options.buffer_size, true);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <cstdio>\n#include <mutex>\n#include <thread>\n#include <condition_variable>\n\nstruct LogMetaData\n{\n struct OneLogData { int line; const char* fmt; };\n std::vector<OneLogData> logs;\n \n int registering(int line, const char* fmt)\n {\n logs.push_back( OneLogData{line,fmt} );\n return logs.size() - 1;\n } \n};\nstatic LogMetaData g_logmetadata;\n\nstruct OneLog\n{\n OneLog(int line, const char *fmt)\n { id = g_logmetadata.registering (line, fmt); }\n int id;\n};\n\nstruct Logger\n{\n template <typename T>\n void print(int id, T value);\n};\n\n#define LOG(fmt,value) { static const OneLog log(__LINE__,fmt); logger.print(log.id,value); }\n\nbool run = true;\n\nint main (int argc, char **argv)\n{\n Logger logger;\n for (int i = 0; i < argc+1; ++i)\n {\n LOG(\"argc =%d\",argc );\n LOG(\"argv[0]=%s\",argv[0]);\n }\n run = false;\n}\n\n\/*\ntemplate <typename T>\nvoid Logger::print(int id, T value)\n{\n std::printf(\"\\nLogID=%d at line=%d message=\", id, g_logmetadata.logs[id].line);\n std::printf(g_logmetadata.logs[id].fmt, value); \n}\n*\/\n\ntemplate <typename T>\nvoid Logger::print(int id, T value)\n{\n static T static_value;\n static std::mutex m;\n std::condition_variable cv;\n static std::thread t([&]{\n while(run)\n {\n T local_value;\n {\n std::unique_lock<std::mutex> lk(m);\n cv.wait(lk);\n local_value = static_value;\n }\n std::printf(\"\\nLogID=%d at line=%d message=\", id, g_logmetadata.logs[id].line);\n std::printf(g_logmetadata.logs[id].fmt, local_value);\n }\n });\n {\n std::unique_lock<std::mutex> lk(m);\n static_value = value;\n }\n cv.notify_one();\n}\n<commit_msg>Use std::lock_guard<commit_after>#include <vector>\n#include <cstdio>\n#include <mutex>\n#include <thread>\n#include <condition_variable>\n\nstruct LogMetaData\n{\n struct OneLogData { int line; const char* fmt; };\n std::vector<OneLogData> logs;\n \n int registering(int line, const char* fmt)\n {\n logs.push_back( OneLogData{line,fmt} );\n return logs.size() - 1;\n } \n};\nstatic LogMetaData g_logmetadata;\n\nstruct OneLog\n{\n OneLog(int line, const char *fmt)\n { id = g_logmetadata.registering (line, fmt); }\n int id;\n};\n\nstruct Logger\n{\n template <typename T>\n void print(int id, T value);\n};\n\n#define LOG(fmt,value) { static const OneLog log(__LINE__,fmt); logger.print(log.id,value); }\n\nbool run = true;\n\nint main (int argc, char **argv)\n{\n Logger logger;\n for (int i = 0; i < argc+1; ++i)\n {\n LOG(\"argc =%d\",argc );\n LOG(\"argv[0]=%s\",argv[0]);\n }\n run = false;\n}\n\n\/*\ntemplate <typename T>\nvoid Logger::print(int id, T value)\n{\n std::printf(\"\\nLogID=%d at line=%d message=\", id, g_logmetadata.logs[id].line);\n std::printf(g_logmetadata.logs[id].fmt, value); \n}\n*\/\n\ntemplate <typename T>\nvoid Logger::print(int id, T value)\n{\n static T static_value;\n static std::mutex m;\n std::condition_variable cv;\n static std::thread t([&]{\n while(run)\n {\n T local_value;\n {\n std::unique_lock<std::mutex> lock(m);\n cv.wait(lock);\n local_value = static_value;\n }\n std::printf(\"\\nLogID=%d at line=%d message=\", id, g_logmetadata.logs[id].line);\n std::printf(g_logmetadata.logs[id].fmt, local_value);\n }\n });\n {\n std::lock_guard<std::mutex> lock(m);\n static_value = value;\n }\n cv.notify_one();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center, \nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without \neven the implied warranty of MERCHANTABILITY or FITNESS FOR \nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkCommon.h\"\n#include \"mitkTestingMacros.h\"\n#include <itkMultiThreader.h>\n#include <itksys\/SystemTools.hxx>\n\n\n\/** Documentation\n *\n * @brief Objects of this class can start an internal thread by calling the Start() method.\n * The thread is then logging messages until the method Stop() is called. The class\n * can be used to test if logging is thread-save by using multiple objects and let \n * them log simuntanously.\n *\/\nclass mitkTestLoggingThread\n{\nprotected:\n\nbool LoggingRunning;\n\nint ThreadID;\n\nitk::MultiThreader::Pointer m_MultiThreader;\n\nvoid LogMessages()\n {\n \n while(LoggingRunning)\n {\n MITK_INFO << \"Test info stream in thread \" << ThreadID;\n MITK_WARN << \"Test warning stream in thread \" << ThreadID;\n MITK_DEBUG << \"Test debugging stream in thread \" << ThreadID;\n MITK_ERROR << \"Test error stream in thread \" << ThreadID;\n MITK_FATAL << \"Test fatal stream in thread \" << ThreadID;\n }\n }\n\n\nstatic ITK_THREAD_RETURN_TYPE mitkTestLoggingThread::ThreadStartTracking(void* pInfoStruct)\n {\n \/* extract this pointer from Thread Info structure *\/\n struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;\n if (pInfo == NULL)\n {\n return ITK_THREAD_RETURN_VALUE;\n }\n if (pInfo->UserData == NULL)\n {\n return ITK_THREAD_RETURN_VALUE;\n }\n mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData;\n\n if (thisthread != NULL)\n thisthread->LogMessages();\n\n return ITK_THREAD_RETURN_VALUE;\n }\n\npublic:\n\nmitkTestLoggingThread(int number, itk::MultiThreader::Pointer MultiThreader)\n {\n ThreadID = number;\n m_MultiThreader = MultiThreader;\n }\n\nvoid Start()\n {\n LoggingRunning = true;\n m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);\n }\n\nvoid Stop()\n {\n LoggingRunning = false;\n }\n\n};\n\n\/** Documentation\n *\n * @brief This class holds static test methods to sturcture the test of the mitk logging mechanism. \n *\/\nclass mitkLogTestClass\n{ \n\npublic:\n\nstatic void TestSimpleLog()\n {\n bool testSucceded = true;\n try\n {\n MITK_INFO << \"Test info stream.\";\n MITK_WARN << \"Test warning stream.\";\n MITK_DEBUG << \"Test debugging stream.\"; \/\/only activated if cmake variable is on!\n \/\/so no worries if you see no output for this line\n MITK_ERROR << \"Test error stream.\";\n MITK_FATAL << \"Test fatal stream.\";\n }\n catch(mitk::Exception e)\n {\n testSucceded = false;\n } \n MITK_TEST_CONDITION_REQUIRED(testSucceded,\"Test logging streams.\");\n }\n\nstatic void TestThreadSaveLog()\n {\n bool testSucceded = true;\n\n try\n {\n \/\/initialize two threads...\n itk::MultiThreader::Pointer myThreader = itk::MultiThreader::New();\n mitkTestLoggingThread myThreadClass1 = mitkTestLoggingThread(1,myThreader);\n mitkTestLoggingThread myThreadClass2 = mitkTestLoggingThread(2,myThreader);\n \n \/\/start them\n myThreadClass1.Start();\n myThreadClass2.Start();\n \n\n \/\/wait for 500 ms\n itksys::SystemTools::Delay(500);\n\n \/\/stop them\n myThreadClass1.Stop();\n myThreadClass2.Stop();\n\n \/\/sleep again to let all threads end\n itksys::SystemTools::Delay(200);\n }\n catch(...)\n {\n testSucceded = false;\n }\n\n \/\/if no error occured until now, everything is ok\n MITK_TEST_CONDITION_REQUIRED(testSucceded,\"Test logging in different threads.\");\n }\n\nstatic void TestLoggingToFile()\n {\n\n }\n\nstatic void TestAddAndRemoveBackends()\n {\n mbilog::BackendCout myBackend = mbilog::BackendCout();\n mbilog::RegisterBackend(&myBackend);\n MITK_INFO << \"Test logging\";\n mbilog::UnregisterBackend(&myBackend);\n\n \/\/if no error occured until now, everything is ok\n MITK_TEST_CONDITION_REQUIRED(true,\"Test add\/remove logging backend.\");\n }\n\nstatic void TestDefaultBackend()\n {\n \/\/not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test.\n }\n\n\n};\n\nint mitkLogTest(int \/* argc *\/, char* \/*argv*\/[])\n{\n \/\/ always start with this!\n MITK_TEST_BEGIN(\"Log\")\n\n MITK_TEST_OUTPUT(<<\"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!\")\n \n mitkLogTestClass::TestSimpleLog();\n mitkLogTestClass::TestThreadSaveLog();\n mitkLogTestClass::TestLoggingToFile();\n mitkLogTestClass::TestAddAndRemoveBackends();\n \n \/\/ always end with this!\n MITK_TEST_END()\n}\n<commit_msg>implemented test method for logging to file<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center, \nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without \neven the implied warranty of MERCHANTABILITY or FITNESS FOR \nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkCommon.h\"\n#include \"mitkTestingMacros.h\"\n#include <mitkLog.h>\n#include <itkMultiThreader.h>\n#include <itksys\/SystemTools.hxx>\n#include <mitkStandardFileLocations.h>\n\n\n\/** Documentation\n *\n * @brief Objects of this class can start an internal thread by calling the Start() method.\n * The thread is then logging messages until the method Stop() is called. The class\n * can be used to test if logging is thread-save by using multiple objects and let \n * them log simuntanously.\n *\/\nclass mitkTestLoggingThread\n{\nprotected:\n\nbool LoggingRunning;\n\nint ThreadID;\n\nitk::MultiThreader::Pointer m_MultiThreader;\n\nvoid LogMessages()\n {\n \n while(LoggingRunning)\n {\n MITK_INFO << \"Test info stream in thread \" << ThreadID;\n MITK_WARN << \"Test warning stream in thread \" << ThreadID;\n MITK_DEBUG << \"Test debugging stream in thread \" << ThreadID;\n MITK_ERROR << \"Test error stream in thread \" << ThreadID;\n MITK_FATAL << \"Test fatal stream in thread \" << ThreadID;\n }\n }\n\n\nstatic ITK_THREAD_RETURN_TYPE mitkTestLoggingThread::ThreadStartTracking(void* pInfoStruct)\n {\n \/* extract this pointer from Thread Info structure *\/\n struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;\n if (pInfo == NULL)\n {\n return ITK_THREAD_RETURN_VALUE;\n }\n if (pInfo->UserData == NULL)\n {\n return ITK_THREAD_RETURN_VALUE;\n }\n mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData;\n\n if (thisthread != NULL)\n thisthread->LogMessages();\n\n return ITK_THREAD_RETURN_VALUE;\n }\n\npublic:\n\nmitkTestLoggingThread(int number, itk::MultiThreader::Pointer MultiThreader)\n {\n ThreadID = number;\n m_MultiThreader = MultiThreader;\n }\n\nvoid Start()\n {\n LoggingRunning = true;\n m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);\n }\n\nvoid Stop()\n {\n LoggingRunning = false;\n }\n\n};\n\n\/** Documentation\n *\n * @brief This class holds static test methods to sturcture the test of the mitk logging mechanism. \n *\/\nclass mitkLogTestClass\n{ \n\npublic:\n\nstatic void TestSimpleLog()\n {\n bool testSucceded = true;\n try\n {\n MITK_INFO << \"Test info stream.\";\n MITK_WARN << \"Test warning stream.\";\n MITK_DEBUG << \"Test debugging stream.\"; \/\/only activated if cmake variable is on!\n \/\/so no worries if you see no output for this line\n MITK_ERROR << \"Test error stream.\";\n MITK_FATAL << \"Test fatal stream.\";\n }\n catch(mitk::Exception e)\n {\n testSucceded = false;\n } \n MITK_TEST_CONDITION_REQUIRED(testSucceded,\"Test logging streams.\");\n }\n\nstatic void TestThreadSaveLog()\n {\n bool testSucceded = true;\n\n try\n {\n \/\/initialize two threads...\n itk::MultiThreader::Pointer myThreader = itk::MultiThreader::New();\n mitkTestLoggingThread myThreadClass1 = mitkTestLoggingThread(1,myThreader);\n mitkTestLoggingThread myThreadClass2 = mitkTestLoggingThread(2,myThreader);\n \n \/\/start them\n myThreadClass1.Start();\n myThreadClass2.Start();\n \n\n \/\/wait for 500 ms\n itksys::SystemTools::Delay(500);\n\n \/\/stop them\n myThreadClass1.Stop();\n myThreadClass2.Stop();\n\n \/\/sleep again to let all threads end\n itksys::SystemTools::Delay(200);\n }\n catch(...)\n {\n testSucceded = false;\n }\n\n \/\/if no error occured until now, everything is ok\n MITK_TEST_CONDITION_REQUIRED(testSucceded,\"Test logging in different threads.\");\n }\n\nstatic void TestLoggingToFile()\n {\n std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + \"\/testlog.log\";\n mitk::LoggingBackend::SetLogFile(filename.c_str());\n MITK_INFO << \"Test logging to default filename: \" << mitk::LoggingBackend::GetLogFile();\n MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(filename.c_str()),\"Testing if log file exists.\");\n \/\/TODO delete log file?\n }\n\nstatic void TestAddAndRemoveBackends()\n {\n mbilog::BackendCout myBackend = mbilog::BackendCout();\n mbilog::RegisterBackend(&myBackend);\n MITK_INFO << \"Test logging\";\n mbilog::UnregisterBackend(&myBackend);\n\n \/\/if no error occured until now, everything is ok\n MITK_TEST_CONDITION_REQUIRED(true,\"Test add\/remove logging backend.\");\n }\n\nstatic void TestDefaultBackend()\n {\n \/\/not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test.\n }\n\n\n};\n\nint mitkLogTest(int \/* argc *\/, char* \/*argv*\/[])\n{\n \/\/ always start with this!\n MITK_TEST_BEGIN(\"Log\")\n\n MITK_TEST_OUTPUT(<<\"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!\")\n \n mitkLogTestClass::TestSimpleLog();\n mitkLogTestClass::TestThreadSaveLog();\n mitkLogTestClass::TestLoggingToFile();\n mitkLogTestClass::TestAddAndRemoveBackends();\n \n \/\/ always end with this!\n MITK_TEST_END()\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date: 2010-01-14 14:20:26 +0100 (Thu, 14 Jan 2010) $\nVersion: $Revision: 21047 $\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html 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\n#include \"QmitkTextOverlay.h\"\n\n#include \"mitkProperties.h\"\n#include \"mitkColorProperty.h\"\n#include \"mitkPropertyList.h\"\n\n#include <itkCommand.h>\n\n#include <QLayout>\n\n\nQmitkTextOverlay::QmitkTextOverlay( const char* id ): \nQmitkOverlay(id), m_Widget( NULL )\n{\n m_Widget = new QLabel();\n m_Widget->setStyleSheet(\"\");\n}\n\nQmitkTextOverlay::~QmitkTextOverlay()\n{\n m_Widget = NULL;\n}\n\nvoid QmitkTextOverlay::GenerateData( mitk::PropertyList::Pointer pl )\n{\n if ( pl.IsNull() )\n return;\n\n m_PropertyList = pl;\n\n if ( m_PropertyList.IsNotNull() )\n {\n this->SetupCallback( m_PropertyList->GetProperty( m_Id ) );\n\n this->GetTextProperties( pl );\n this->SetText();\n }\n else\n {\n MITK_ERROR << \"invalid propList\";\n }\n\n}\n\nvoid QmitkTextOverlay::SetText()\n{\n std::string text = \"\";\n if ( m_PropertyList.IsNull() || !m_PropertyList->GetStringProperty( m_Id, text ) )\n {\n MITK_WARN << \"Property \" << m_Id << \" could not be found\";\n }\n m_Widget->setText( text.c_str() );\n}\n\n\nvoid QmitkTextOverlay::GetTextProperties( mitk::PropertyList::Pointer pl )\n{\n if ( pl.IsNull() )\n return;\n\n mitk::PropertyList::Pointer propertyList = pl;\n QPalette palette = QPalette();\n QFont font = QFont();\n\n \/\/ get the desired color of the textOverlays\n mitk::ColorProperty::Pointer colorProp = \n dynamic_cast<mitk::ColorProperty*>( propertyList->GetProperty( \"overlay.color\" ) );\n\n if ( colorProp.IsNull() )\n {\n MITK_ERROR << \"creating new colorProperty\";\n colorProp = mitk::ColorProperty::New( 127.0, 196.0, 232.0 );\n }\n\n mitk::Color color = colorProp->GetColor();\n palette.setColor( QPalette::Foreground, QColor( color[0],color[1],color[2],255 ) );\n palette.setColor( QPalette::Window, Qt::transparent);\n m_Widget->setPalette( palette );\n\n \/\/ get the desired opacity of the overlays\n \/\/mitk::FloatProperty::Pointer opacityProperty =\n \/\/ dynamic_cast<mitk::FloatProperty*>( propertyList->GetProperty( \"overlay.opacity\" ) );\n\n \/\/if ( opacityProperty.IsNull() )\n \/\/{\n \/\/ m_Widget->setWindowOpacity( 1 );\n \/\/} \n \/\/else\n \/\/{\n \/\/ m_Widget->setWindowOpacity( opacityProperty->GetValue() );\n \/\/}\n \n \/\/set the desired font-size of the overlays\n int fontSize = 0;\n if ( !propertyList->GetIntProperty( \"overlay.fontSize\", fontSize ) )\n {\n fontSize = 16;\n } \n font.setPointSize( fontSize );\n\n bool useKerning = false;\n if ( !propertyList->GetBoolProperty( \"overlay.kerning\", useKerning ) )\n {\n useKerning = true;\n }\n font.setKerning( useKerning );\n\n std::string fontFamily = \"\";\n if ( !propertyList->GetStringProperty( \"overlay.fontFamily\", fontFamily ) )\n {\n fontFamily = \"Verdana\";\n }\n font.setFamily( QString(fontFamily.c_str()) );\n\n m_Widget->setFont( font );\n \n}\n\nQLabel* QmitkTextOverlay::GetWidget()\n{\n return m_Widget;\n}\n\n\nvoid QmitkTextOverlay::SetupCallback( mitk::BaseProperty::Pointer prop )\n{\n if ( prop.IsNotNull() )\n {\n typedef itk::SimpleMemberCommand< QmitkTextOverlay > MemberCommandType;\n MemberCommandType::Pointer propModifiedCommand;\n propModifiedCommand = MemberCommandType::New();\n propModifiedCommand->SetCallbackFunction( this, &QmitkTextOverlay::SetText );\n prop->AddObserver( itk::ModifiedEvent(), propModifiedCommand );\n }\n else\n {\n MITK_ERROR << \"invalid property\";\n }\n}\n\n<commit_msg>FIX (#5038): adding QLabel::repaint to immediately re-render the text when the textProperty has changed<commit_after>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date: 2010-01-14 14:20:26 +0100 (Thu, 14 Jan 2010) $\nVersion: $Revision: 21047 $\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html 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\n#include \"QmitkTextOverlay.h\"\n\n#include \"mitkProperties.h\"\n#include \"mitkColorProperty.h\"\n#include \"mitkPropertyList.h\"\n\n#include <itkCommand.h>\n\n#include <QLayout>\n\n\nQmitkTextOverlay::QmitkTextOverlay( const char* id ): \nQmitkOverlay(id), m_Widget( NULL )\n{\n m_Widget = new QLabel();\n m_Widget->setStyleSheet(\"\");\n}\n\nQmitkTextOverlay::~QmitkTextOverlay()\n{\n m_Widget = NULL;\n}\n\nvoid QmitkTextOverlay::GenerateData( mitk::PropertyList::Pointer pl )\n{\n if ( pl.IsNull() )\n return;\n\n m_PropertyList = pl;\n\n if ( m_PropertyList.IsNotNull() )\n {\n this->SetupCallback( m_PropertyList->GetProperty( m_Id ) );\n\n this->GetTextProperties( pl );\n this->SetText();\n }\n else\n {\n MITK_ERROR << \"invalid propList\";\n }\n\n}\n\nvoid QmitkTextOverlay::SetText()\n{\n std::string text = \"\";\n if ( m_PropertyList.IsNull() || !m_PropertyList->GetStringProperty( m_Id, text ) )\n {\n MITK_WARN << \"Property \" << m_Id << \" could not be found\";\n }\n m_Widget->setText( text.c_str() );\n m_Widget->repaint();\n}\n\n\nvoid QmitkTextOverlay::GetTextProperties( mitk::PropertyList::Pointer pl )\n{\n if ( pl.IsNull() )\n return;\n\n mitk::PropertyList::Pointer propertyList = pl;\n QPalette palette = QPalette();\n QFont font = QFont();\n\n \/\/ get the desired color of the textOverlays\n mitk::ColorProperty::Pointer colorProp = \n dynamic_cast<mitk::ColorProperty*>( propertyList->GetProperty( \"overlay.color\" ) );\n\n if ( colorProp.IsNull() )\n {\n MITK_ERROR << \"creating new colorProperty\";\n colorProp = mitk::ColorProperty::New( 127.0, 196.0, 232.0 );\n }\n\n mitk::Color color = colorProp->GetColor();\n palette.setColor( QPalette::Foreground, QColor( color[0],color[1],color[2],255 ) );\n palette.setColor( QPalette::Window, Qt::transparent);\n m_Widget->setPalette( palette );\n\n \/\/ get the desired opacity of the overlays\n \/\/mitk::FloatProperty::Pointer opacityProperty =\n \/\/ dynamic_cast<mitk::FloatProperty*>( propertyList->GetProperty( \"overlay.opacity\" ) );\n\n \/\/if ( opacityProperty.IsNull() )\n \/\/{\n \/\/ m_Widget->setWindowOpacity( 1 );\n \/\/} \n \/\/else\n \/\/{\n \/\/ m_Widget->setWindowOpacity( opacityProperty->GetValue() );\n \/\/}\n \n \/\/set the desired font-size of the overlays\n int fontSize = 0;\n if ( !propertyList->GetIntProperty( \"overlay.fontSize\", fontSize ) )\n {\n fontSize = 16;\n } \n font.setPointSize( fontSize );\n\n bool useKerning = false;\n if ( !propertyList->GetBoolProperty( \"overlay.kerning\", useKerning ) )\n {\n useKerning = true;\n }\n font.setKerning( useKerning );\n\n std::string fontFamily = \"\";\n if ( !propertyList->GetStringProperty( \"overlay.fontFamily\", fontFamily ) )\n {\n fontFamily = \"Verdana\";\n }\n font.setFamily( QString(fontFamily.c_str()) );\n\n m_Widget->setFont( font );\n \n}\n\nQLabel* QmitkTextOverlay::GetWidget()\n{\n return m_Widget;\n}\n\n\nvoid QmitkTextOverlay::SetupCallback( mitk::BaseProperty::Pointer prop )\n{\n if ( prop.IsNotNull() )\n {\n typedef itk::SimpleMemberCommand< QmitkTextOverlay > MemberCommandType;\n MemberCommandType::Pointer propModifiedCommand;\n propModifiedCommand = MemberCommandType::New();\n propModifiedCommand->SetCallbackFunction( this, &QmitkTextOverlay::SetText );\n prop->AddObserver( itk::ModifiedEvent(), propModifiedCommand );\n }\n else\n {\n MITK_ERROR << \"invalid property\";\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * OXT - OS eXtensions for boosT\n * Provides important functionality necessary for writing robust server software.\n *\n * Copyright (c) 2010 Phusion\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#ifndef _OXT_THREAD_HPP_\n#define _OXT_THREAD_HPP_\n\n#include <boost\/thread.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include \"system_calls.hpp\"\n#include \"backtrace.hpp\"\n#ifdef OXT_BACKTRACE_IS_ENABLED\n\t#include <sstream>\n#endif\n#include <string>\n#include <list>\n#include <unistd.h>\n#include <limits.h> \/\/ for PTHREAD_STACK_MIN\n\nnamespace oxt {\n\nextern boost::mutex _next_thread_number_mutex;\nextern unsigned int _next_thread_number;\n\n\/**\n * Enhanced thread class with support for:\n * - user-defined stack size.\n * - system call interruption.\n * - backtraces.\n *\/\nclass thread: public boost::thread {\nprivate:\n\tstruct thread_data {\n\t\tstd::string name;\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tthread_registration *registration;\n\t\t\tboost::mutex registration_lock;\n\t\t\tbool done;\n\t\t#endif\n\t};\n\t\n\ttypedef boost::shared_ptr<thread_data> thread_data_ptr;\n\t\n\tthread_data_ptr data;\n\n\tvoid initialize_data(const std::string &thread_name) {\n\t\tdata = thread_data_ptr(new thread_data());\n\t\tif (thread_name.empty()) {\n\t\t\tboost::mutex::scoped_lock l(_next_thread_number_mutex);\n\t\t\tstd::stringstream str;\n\t\t\t\n\t\t\tstr << \"Thread #\" << _next_thread_number;\n\t\t\t_next_thread_number++;\n\t\t\tdata->name = str.str();\n\t\t} else {\n\t\t\tdata->name = thread_name;\n\t\t}\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tdata->registration = NULL;\n\t\t\tdata->done = false;\n\t\t#endif\n\t}\n\t\n\tstatic void thread_main(boost::function<void ()> func, thread_data_ptr data) {\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tinitialize_backtrace_support_for_this_thread i(data->name);\n\t\t\tdata->registration = i.registration;\n\t\t#endif\n\t\t\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\t\/\/ Put finalization code in a struct destructor,\n\t\t\t\/\/ for exception safety.\n\t\t\tstruct finalization_routines {\n\t\t\t\tthread_data_ptr &data;\n\t\t\t\t\n\t\t\t\tfinalization_routines(thread_data_ptr &data_)\n\t\t\t\t\t: data(data_) {}\n\t\t\t\t\n\t\t\t\t~finalization_routines() {\n\t\t\t\t\tboost::mutex::scoped_lock l(data->registration_lock);\n\t\t\t\t\tdata->registration = NULL;\n\t\t\t\t\tdata->done = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\tfinalization_routines f(data);\n\t\t#endif\n\t\t\n\t\tfunc();\n\t}\n\t\npublic:\n\t\/**\n\t * Create a new thread.\n\t *\n\t * @param func A function object which will be called as the thread's\n\t * main function. This object must be copyable. <tt>func<\/tt> is\n\t * copied into storage managed internally by the thread library,\n\t * and that copy is invoked on a newly-created thread of execution.\n\t * @param name A name for this thread. If an empty string is given, then\n\t * a name will be automatically chosen.\n\t * @param stack_size The stack size, in bytes, that the thread should\n\t * have. If 0 is specified, the operating system's default stack\n\t * size is used. If non-zero is specified, and the size is smaller\n\t * than the operating system's minimum stack size, then the operating\n\t * system's minimum stack size will be used.\n\t * @pre func must be copyable.\n\t * @throws boost::thread_resource_error Something went wrong during\n\t * creation of the thread.\n\t *\/\n\texplicit thread(boost::function<void ()> func, const std::string &name = \"\", unsigned int stack_size = 0) {\n\t\tinitialize_data(name);\n\t\t\n\t\tset_thread_main_function(boost::bind(thread_main, func, data));\n\t\t\n\t\tunsigned long min_stack_size;\n\t\tbool stack_min_size_defined;\n\t\tbool round_stack_size;\n\t\t\n\t\t#ifdef PTHREAD_STACK_MIN\n\t\t\t\/\/ PTHREAD_STACK_MIN may not be a constant macro so we need\n\t\t\t\/\/ to evaluate it dynamically.\n\t\t\tmin_stack_size = PTHREAD_STACK_MIN;\n\t\t\tstack_min_size_defined = true;\n\t\t#else\n\t\t\t\/\/ Assume minimum stack size is 128 KB.\n\t\t\tmin_stack_size = 128 * 1024;\n\t\t\tstack_min_size_defined = false;\n\t\t#endif\n\t\tif (stack_size != 0 && stack_size < min_stack_size) {\n\t\t\tstack_size = min_stack_size;\n\t\t\tround_stack_size = !stack_min_size_defined;\n\t\t} else {\n\t\t\tround_stack_size = true;\n\t\t}\n\t\t\n\t\tif (round_stack_size) {\n\t\t\t\/\/ Round stack size up to page boundary.\n\t\t\tlong page_size;\n\t\t\t#if defined(_SC_PAGESIZE)\n\t\t\t\tpage_size = sysconf(_SC_PAGESIZE);\n\t\t\t#elif defined(_SC_PAGE_SIZE)\n\t\t\t\tpage_size = sysconf(_SC_PAGE_SIZE);\n\t\t\t#elif defined(PAGESIZE)\n\t\t\t\tpage_size = sysconf(PAGESIZE);\n\t\t\t#elif defined(PAGE_SIZE)\n\t\t\t\tpage_size = sysconf(PAGE_SIZE);\n\t\t\t#else\n\t\t\t\tpage_size = getpagesize();\n\t\t\t#endif\n\t\t\tif (stack_size % page_size != 0) {\n\t\t\t\tstack_size = stack_size - (stack_size % page_size) + page_size;\n\t\t\t}\n\t\t}\n\t\t\n\t\tstart_thread(stack_size);\n\t}\n\t\n\t\/**\n\t * Return this thread's name. The name was set during construction.\n\t *\/\n\tstd::string name() const throw() {\n\t\treturn data->name;\n\t}\n\t\n\t\/**\n\t * Return the current backtrace of the thread of execution, as a string.\n\t *\/\n\tstd::string backtrace() const throw() {\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tboost::mutex::scoped_lock l(data->registration_lock);\n\t\t\tif (data->registration == NULL) {\n\t\t\t\tif (data->done) {\n\t\t\t\t\treturn \" (no backtrace: thread has quit)\";\n\t\t\t\t} else {\n\t\t\t\t\treturn \" (no backtrace: thread hasn't been started yet)\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tspin_lock::scoped_lock l2(*data->registration->backtrace_lock);\n\t\t\t\treturn _format_backtrace(data->registration->backtrace);\n\t\t\t}\n\t\t#else\n\t\t\treturn \" (backtrace support disabled during compile time)\";\n\t\t#endif\n\t}\n\t\n\t\/**\n\t * Return the backtraces of all oxt::thread threads, as well as that of the\n\t * main thread, in a nicely formatted string.\n\t *\/\n\tstatic std::string all_backtraces() throw() {\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tboost::mutex::scoped_lock l(_thread_registration_mutex);\n\t\t\tlist<thread_registration *>::const_iterator it;\n\t\t\tstd::stringstream result;\n\t\t\t\n\t\t\tfor (it = _registered_threads.begin(); it != _registered_threads.end(); it++) {\n\t\t\t\tthread_registration *r = *it;\n\t\t\t\tresult << \"Thread '\" << r->name << \"':\" << endl;\n\t\t\t\t\n\t\t\t\tspin_lock::scoped_lock l(*r->backtrace_lock);\n\t\t\t\tresult << _format_backtrace(r->backtrace) << endl;\n\t\t\t}\n\t\t\treturn result.str();\n\t\t#else\n\t\t\treturn \"(backtrace support disabled during compile time)\";\n\t\t#endif\n\t}\n\t\n\t\/**\n\t * Interrupt the thread. This method behaves just like\n\t * boost::thread::interrupt(), but will also respect the interruption\n\t * points defined in oxt::syscalls.\n\t *\n\t * Note that an interruption request may get lost, depending on the\n\t * current execution point of the thread. Thus, one should call this\n\t * method in a loop, until a certain goal condition has been fulfilled.\n\t * interrupt_and_join() is a convenience method that implements this\n\t * pattern.\n\t *\/\n\tvoid interrupt() {\n\t\tint ret;\n\t\t\n\t\tboost::thread::interrupt();\n\t\tdo {\n\t\t\tret = pthread_kill(native_handle(),\n\t\t\t\tINTERRUPTION_SIGNAL);\n\t\t} while (ret == EINTR);\n\t}\n\t\n\t\/**\n\t * Keep interrupting the thread until it's done, then join it.\n\t *\n\t * @throws boost::thread_interrupted The calling thread has been\n\t * interrupted before we could join this thread.\n\t *\/\n\tvoid interrupt_and_join() {\n\t\tbool done = false;\n\t\twhile (!done) {\n\t\t\tinterrupt();\n\t\t\tdone = timed_join(boost::posix_time::millisec(10));\n\t\t}\n\t}\n\t\n\t\/**\n\t * Keep interrupting the thread until it's done, then join it.\n\t * This method will keep trying for at most <em>timeout<\/em> milliseconds.\n\t *\n\t * @param timeout The maximum number of milliseconds that this method\n\t * should keep trying.\n\t * @return True if the thread was successfully joined, false if the\n\t * timeout has been reached.\n\t * @throws boost::thread_interrupted The calling thread has been\n\t * interrupted before we could join this thread.\n\t *\/\n\tbool interrupt_and_join(unsigned int timeout) {\n\t\tbool joined = false, timed_out = false;\n\t\tboost::posix_time::ptime deadline =\n\t\t\tboost::posix_time::microsec_clock::local_time() +\n\t\t\tboost::posix_time::millisec(timeout);\n\t\twhile (!joined && !timed_out) {\n\t\t\tinterrupt();\n\t\t\tjoined = timed_join(boost::posix_time::millisec(10));\n\t\t\ttimed_out = !joined && boost::posix_time::microsec_clock::local_time() > deadline;\n\t\t}\n\t\treturn joined;\n\t}\n\t\n\t\/**\n\t * Interrupt and join multiple threads in a way that's more efficient than calling\n\t * interrupt_and_join() on each thread individually. It iterates over all threads,\n\t * interrupts each one without joining it, then waits until at least one thread\n\t * is joinable. This is repeated until all threads are joined.\n\t *\n\t * @param threads An array of threads to join.\n\t * @param size The number of elements in <em>threads<\/em>.\n\t * @throws boost::thread_interrupted The calling thread has been\n\t * interrupted before all threads have been joined. Some threads\n\t * may have been successfully joined while others haven't.\n\t *\/\n\tstatic void interrupt_and_join_multiple(oxt::thread **threads, unsigned int size) {\n\t\tstd::list<oxt::thread *> remaining_threads;\n\t\tstd::list<oxt::thread *>::iterator it, current;\n\t\toxt::thread *thread;\n\t\tunsigned int i;\n\t\t\n\t\tfor (i = 0; i < size; i++) {\n\t\t\tremaining_threads.push_back(threads[i]);\n\t\t}\n\t\t\n\t\twhile (!remaining_threads.empty()) {\n\t\t\tfor (it = remaining_threads.begin(); it != remaining_threads.end(); it++) {\n\t\t\t\tthread = *it;\n\t\t\t\tthread->interrupt();\n\t\t\t}\n\t\t\tfor (it = remaining_threads.begin(); it != remaining_threads.end(); it++) {\n\t\t\t\tthread = *it;\n\t\t\t\tif (thread->timed_join(boost::posix_time::millisec(0))) {\n\t\t\t\t\tcurrent = it;\n\t\t\t\t\tit--;\n\t\t\t\t\tremaining_threads.erase(current);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!remaining_threads.empty()) {\n\t\t\t\tsyscalls::usleep(10000);\n\t\t\t}\n\t\t}\n\t}\n};\n\n\/**\n * Like boost::lock_guard, but is interruptable.\n *\/\ntemplate<typename TimedLockable>\nclass interruptable_lock_guard {\nprivate:\n\tTimedLockable &mutex;\npublic:\n\tinterruptable_lock_guard(TimedLockable &m): mutex(m) {\n\t\tbool locked = false;\n\t\t\n\t\twhile (!locked) {\n\t\t\tlocked = m.timed_lock(boost::posix_time::milliseconds(10));\n\t\t\tif (!locked) {\n\t\t\t\tboost::this_thread::interruption_point();\n\t\t\t}\n\t\t}\n\t}\n\t\n\t~interruptable_lock_guard() {\n\t\tmutex.unlock();\n\t}\n};\n\n} \/\/ namespace oxt\n\n#endif \/* _OXT_THREAD_HPP_ *\/\n\n<commit_msg>Increase interruptable_lock_guard busy loop sleep time to 20 msec.<commit_after>\/*\n * OXT - OS eXtensions for boosT\n * Provides important functionality necessary for writing robust server software.\n *\n * Copyright (c) 2010 Phusion\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#ifndef _OXT_THREAD_HPP_\n#define _OXT_THREAD_HPP_\n\n#include <boost\/thread.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include \"system_calls.hpp\"\n#include \"backtrace.hpp\"\n#ifdef OXT_BACKTRACE_IS_ENABLED\n\t#include <sstream>\n#endif\n#include <string>\n#include <list>\n#include <unistd.h>\n#include <limits.h> \/\/ for PTHREAD_STACK_MIN\n\nnamespace oxt {\n\nextern boost::mutex _next_thread_number_mutex;\nextern unsigned int _next_thread_number;\n\n\/**\n * Enhanced thread class with support for:\n * - user-defined stack size.\n * - system call interruption.\n * - backtraces.\n *\/\nclass thread: public boost::thread {\nprivate:\n\tstruct thread_data {\n\t\tstd::string name;\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tthread_registration *registration;\n\t\t\tboost::mutex registration_lock;\n\t\t\tbool done;\n\t\t#endif\n\t};\n\t\n\ttypedef boost::shared_ptr<thread_data> thread_data_ptr;\n\t\n\tthread_data_ptr data;\n\n\tvoid initialize_data(const std::string &thread_name) {\n\t\tdata = thread_data_ptr(new thread_data());\n\t\tif (thread_name.empty()) {\n\t\t\tboost::mutex::scoped_lock l(_next_thread_number_mutex);\n\t\t\tstd::stringstream str;\n\t\t\t\n\t\t\tstr << \"Thread #\" << _next_thread_number;\n\t\t\t_next_thread_number++;\n\t\t\tdata->name = str.str();\n\t\t} else {\n\t\t\tdata->name = thread_name;\n\t\t}\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tdata->registration = NULL;\n\t\t\tdata->done = false;\n\t\t#endif\n\t}\n\t\n\tstatic void thread_main(boost::function<void ()> func, thread_data_ptr data) {\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tinitialize_backtrace_support_for_this_thread i(data->name);\n\t\t\tdata->registration = i.registration;\n\t\t#endif\n\t\t\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\t\/\/ Put finalization code in a struct destructor,\n\t\t\t\/\/ for exception safety.\n\t\t\tstruct finalization_routines {\n\t\t\t\tthread_data_ptr &data;\n\t\t\t\t\n\t\t\t\tfinalization_routines(thread_data_ptr &data_)\n\t\t\t\t\t: data(data_) {}\n\t\t\t\t\n\t\t\t\t~finalization_routines() {\n\t\t\t\t\tboost::mutex::scoped_lock l(data->registration_lock);\n\t\t\t\t\tdata->registration = NULL;\n\t\t\t\t\tdata->done = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\tfinalization_routines f(data);\n\t\t#endif\n\t\t\n\t\tfunc();\n\t}\n\t\npublic:\n\t\/**\n\t * Create a new thread.\n\t *\n\t * @param func A function object which will be called as the thread's\n\t * main function. This object must be copyable. <tt>func<\/tt> is\n\t * copied into storage managed internally by the thread library,\n\t * and that copy is invoked on a newly-created thread of execution.\n\t * @param name A name for this thread. If an empty string is given, then\n\t * a name will be automatically chosen.\n\t * @param stack_size The stack size, in bytes, that the thread should\n\t * have. If 0 is specified, the operating system's default stack\n\t * size is used. If non-zero is specified, and the size is smaller\n\t * than the operating system's minimum stack size, then the operating\n\t * system's minimum stack size will be used.\n\t * @pre func must be copyable.\n\t * @throws boost::thread_resource_error Something went wrong during\n\t * creation of the thread.\n\t *\/\n\texplicit thread(boost::function<void ()> func, const std::string &name = \"\", unsigned int stack_size = 0) {\n\t\tinitialize_data(name);\n\t\t\n\t\tset_thread_main_function(boost::bind(thread_main, func, data));\n\t\t\n\t\tunsigned long min_stack_size;\n\t\tbool stack_min_size_defined;\n\t\tbool round_stack_size;\n\t\t\n\t\t#ifdef PTHREAD_STACK_MIN\n\t\t\t\/\/ PTHREAD_STACK_MIN may not be a constant macro so we need\n\t\t\t\/\/ to evaluate it dynamically.\n\t\t\tmin_stack_size = PTHREAD_STACK_MIN;\n\t\t\tstack_min_size_defined = true;\n\t\t#else\n\t\t\t\/\/ Assume minimum stack size is 128 KB.\n\t\t\tmin_stack_size = 128 * 1024;\n\t\t\tstack_min_size_defined = false;\n\t\t#endif\n\t\tif (stack_size != 0 && stack_size < min_stack_size) {\n\t\t\tstack_size = min_stack_size;\n\t\t\tround_stack_size = !stack_min_size_defined;\n\t\t} else {\n\t\t\tround_stack_size = true;\n\t\t}\n\t\t\n\t\tif (round_stack_size) {\n\t\t\t\/\/ Round stack size up to page boundary.\n\t\t\tlong page_size;\n\t\t\t#if defined(_SC_PAGESIZE)\n\t\t\t\tpage_size = sysconf(_SC_PAGESIZE);\n\t\t\t#elif defined(_SC_PAGE_SIZE)\n\t\t\t\tpage_size = sysconf(_SC_PAGE_SIZE);\n\t\t\t#elif defined(PAGESIZE)\n\t\t\t\tpage_size = sysconf(PAGESIZE);\n\t\t\t#elif defined(PAGE_SIZE)\n\t\t\t\tpage_size = sysconf(PAGE_SIZE);\n\t\t\t#else\n\t\t\t\tpage_size = getpagesize();\n\t\t\t#endif\n\t\t\tif (stack_size % page_size != 0) {\n\t\t\t\tstack_size = stack_size - (stack_size % page_size) + page_size;\n\t\t\t}\n\t\t}\n\t\t\n\t\tstart_thread(stack_size);\n\t}\n\t\n\t\/**\n\t * Return this thread's name. The name was set during construction.\n\t *\/\n\tstd::string name() const throw() {\n\t\treturn data->name;\n\t}\n\t\n\t\/**\n\t * Return the current backtrace of the thread of execution, as a string.\n\t *\/\n\tstd::string backtrace() const throw() {\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tboost::mutex::scoped_lock l(data->registration_lock);\n\t\t\tif (data->registration == NULL) {\n\t\t\t\tif (data->done) {\n\t\t\t\t\treturn \" (no backtrace: thread has quit)\";\n\t\t\t\t} else {\n\t\t\t\t\treturn \" (no backtrace: thread hasn't been started yet)\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tspin_lock::scoped_lock l2(*data->registration->backtrace_lock);\n\t\t\t\treturn _format_backtrace(data->registration->backtrace);\n\t\t\t}\n\t\t#else\n\t\t\treturn \" (backtrace support disabled during compile time)\";\n\t\t#endif\n\t}\n\t\n\t\/**\n\t * Return the backtraces of all oxt::thread threads, as well as that of the\n\t * main thread, in a nicely formatted string.\n\t *\/\n\tstatic std::string all_backtraces() throw() {\n\t\t#ifdef OXT_BACKTRACE_IS_ENABLED\n\t\t\tboost::mutex::scoped_lock l(_thread_registration_mutex);\n\t\t\tlist<thread_registration *>::const_iterator it;\n\t\t\tstd::stringstream result;\n\t\t\t\n\t\t\tfor (it = _registered_threads.begin(); it != _registered_threads.end(); it++) {\n\t\t\t\tthread_registration *r = *it;\n\t\t\t\tresult << \"Thread '\" << r->name << \"':\" << endl;\n\t\t\t\t\n\t\t\t\tspin_lock::scoped_lock l(*r->backtrace_lock);\n\t\t\t\tresult << _format_backtrace(r->backtrace) << endl;\n\t\t\t}\n\t\t\treturn result.str();\n\t\t#else\n\t\t\treturn \"(backtrace support disabled during compile time)\";\n\t\t#endif\n\t}\n\t\n\t\/**\n\t * Interrupt the thread. This method behaves just like\n\t * boost::thread::interrupt(), but will also respect the interruption\n\t * points defined in oxt::syscalls.\n\t *\n\t * Note that an interruption request may get lost, depending on the\n\t * current execution point of the thread. Thus, one should call this\n\t * method in a loop, until a certain goal condition has been fulfilled.\n\t * interrupt_and_join() is a convenience method that implements this\n\t * pattern.\n\t *\/\n\tvoid interrupt() {\n\t\tint ret;\n\t\t\n\t\tboost::thread::interrupt();\n\t\tdo {\n\t\t\tret = pthread_kill(native_handle(),\n\t\t\t\tINTERRUPTION_SIGNAL);\n\t\t} while (ret == EINTR);\n\t}\n\t\n\t\/**\n\t * Keep interrupting the thread until it's done, then join it.\n\t *\n\t * @throws boost::thread_interrupted The calling thread has been\n\t * interrupted before we could join this thread.\n\t *\/\n\tvoid interrupt_and_join() {\n\t\tbool done = false;\n\t\twhile (!done) {\n\t\t\tinterrupt();\n\t\t\tdone = timed_join(boost::posix_time::millisec(10));\n\t\t}\n\t}\n\t\n\t\/**\n\t * Keep interrupting the thread until it's done, then join it.\n\t * This method will keep trying for at most <em>timeout<\/em> milliseconds.\n\t *\n\t * @param timeout The maximum number of milliseconds that this method\n\t * should keep trying.\n\t * @return True if the thread was successfully joined, false if the\n\t * timeout has been reached.\n\t * @throws boost::thread_interrupted The calling thread has been\n\t * interrupted before we could join this thread.\n\t *\/\n\tbool interrupt_and_join(unsigned int timeout) {\n\t\tbool joined = false, timed_out = false;\n\t\tboost::posix_time::ptime deadline =\n\t\t\tboost::posix_time::microsec_clock::local_time() +\n\t\t\tboost::posix_time::millisec(timeout);\n\t\twhile (!joined && !timed_out) {\n\t\t\tinterrupt();\n\t\t\tjoined = timed_join(boost::posix_time::millisec(10));\n\t\t\ttimed_out = !joined && boost::posix_time::microsec_clock::local_time() > deadline;\n\t\t}\n\t\treturn joined;\n\t}\n\t\n\t\/**\n\t * Interrupt and join multiple threads in a way that's more efficient than calling\n\t * interrupt_and_join() on each thread individually. It iterates over all threads,\n\t * interrupts each one without joining it, then waits until at least one thread\n\t * is joinable. This is repeated until all threads are joined.\n\t *\n\t * @param threads An array of threads to join.\n\t * @param size The number of elements in <em>threads<\/em>.\n\t * @throws boost::thread_interrupted The calling thread has been\n\t * interrupted before all threads have been joined. Some threads\n\t * may have been successfully joined while others haven't.\n\t *\/\n\tstatic void interrupt_and_join_multiple(oxt::thread **threads, unsigned int size) {\n\t\tstd::list<oxt::thread *> remaining_threads;\n\t\tstd::list<oxt::thread *>::iterator it, current;\n\t\toxt::thread *thread;\n\t\tunsigned int i;\n\t\t\n\t\tfor (i = 0; i < size; i++) {\n\t\t\tremaining_threads.push_back(threads[i]);\n\t\t}\n\t\t\n\t\twhile (!remaining_threads.empty()) {\n\t\t\tfor (it = remaining_threads.begin(); it != remaining_threads.end(); it++) {\n\t\t\t\tthread = *it;\n\t\t\t\tthread->interrupt();\n\t\t\t}\n\t\t\tfor (it = remaining_threads.begin(); it != remaining_threads.end(); it++) {\n\t\t\t\tthread = *it;\n\t\t\t\tif (thread->timed_join(boost::posix_time::millisec(0))) {\n\t\t\t\t\tcurrent = it;\n\t\t\t\t\tit--;\n\t\t\t\t\tremaining_threads.erase(current);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!remaining_threads.empty()) {\n\t\t\t\tsyscalls::usleep(10000);\n\t\t\t}\n\t\t}\n\t}\n};\n\n\/**\n * Like boost::lock_guard, but is interruptable.\n *\/\ntemplate<typename TimedLockable>\nclass interruptable_lock_guard {\nprivate:\n\tTimedLockable &mutex;\npublic:\n\tinterruptable_lock_guard(TimedLockable &m): mutex(m) {\n\t\tbool locked = false;\n\t\t\n\t\twhile (!locked) {\n\t\t\tlocked = m.timed_lock(boost::posix_time::milliseconds(20));\n\t\t\tif (!locked) {\n\t\t\t\tboost::this_thread::interruption_point();\n\t\t\t}\n\t\t}\n\t}\n\t\n\t~interruptable_lock_guard() {\n\t\tmutex.unlock();\n\t}\n};\n\n} \/\/ namespace oxt\n\n#endif \/* _OXT_THREAD_HPP_ *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\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 <memory>\n#include <string>\n\n#include \"SurgSim\/Blocks\/BasicSceneElement.h\"\n#include \"SurgSim\/Blocks\/TransferInputPoseBehavior.h\"\n#include \"SurgSim\/Devices\/MultiAxis\/MultiAxisDevice.h\"\n#include \"SurgSim\/Framework\/BehaviorManager.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Input\/InputComponent.h\"\n#include \"SurgSim\/Input\/InputManager.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgSceneryRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgView.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n#include \"Examples\/ExampleStapling\/AddStapleBehavior.h\"\n\n\/\/\/ Load scenery object from file\n\/\/\/ \\param name Name of this scenery representation.\n\/\/\/ \\param fileName Name of the file from which the scenery representation is loaded.\n\/\/\/ \\return A SceneElement containing the scenery representation.\nstd::shared_ptr<SurgSim::Framework::SceneElement> createSceneryObject(const std::string& name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t const std::string& fileName)\n{\n\tstd::shared_ptr<SurgSim::Graphics::SceneryRepresentation> sceneryRepresentation =\n\t\tstd::make_shared<SurgSim::Graphics::OsgSceneryRepresentation>(name + \"SceneryRepresentation\");\n\tsceneryRepresentation->setFileName(fileName);\n\n\tauto sceneElement = std::make_shared<SurgSim::Blocks::BasicSceneElement>(name + \"SceneElement\");\n\tsceneElement->addComponent(sceneryRepresentation);\n\n\treturn sceneElement;\n}\n\nstd::shared_ptr<SurgSim::Graphics::ViewElement> createView()\n{\n\tauto view = std::make_shared<SurgSim::Graphics::OsgViewElement>(\"StaplingDemoView\");\n\n\tview->enableManipulator(true);\n\tview->setManipulatorParameters(SurgSim::Math::Vector3d(0.0, 0.5, 0.5), SurgSim::Math::Vector3d::Zero());\n\n\treturn view;\n}\n\nint main(int argc, char* argv[])\n{\n\tauto behaviorManager = std::make_shared<SurgSim::Framework::BehaviorManager>();\n\tauto graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>();\n\tauto inputManager = std::make_shared<SurgSim::Input::InputManager>();\n\tauto physicsManager = std::make_shared<SurgSim::Physics::PhysicsManager>();\n\n\tauto runtime = std::make_shared<SurgSim::Framework::Runtime>(\"config.txt\");\n\truntime->addManager(behaviorManager);\n\truntime->addManager(graphicsManager);\n\truntime->addManager(inputManager);\n\truntime->addManager(physicsManager);\n\n\tauto toolDevice = std::make_shared<SurgSim::Device::MultiAxisDevice>(\"MultiAxisDevice\");\n\tSURGSIM_ASSERT(toolDevice->initialize() == true) <<\n\t\t\"Could not initialize device \" << toolDevice->getName() << \" for the tool.\\n\";\n\tinputManager->addDevice(toolDevice);\n\n\tstd::shared_ptr<SurgSim::Framework::SceneElement> staplerSceneElement =\n\t\tcreateSceneryObject(\"stapler\", \"Geometry\/stapler.obj\");\n\n\t\/\/ In order to connect the stapler scenery representation to an input device, after create a SceneElement for it,\n\t\/\/ we need to retrieve the stapler scenery representation from the SceneElement.\n\tstd::shared_ptr<SurgSim::Framework::Component> staplerComponent =\n\t\tstaplerSceneElement->getComponent(\"staplerSceneryRepresentation\");\n\tauto staplerSceneryRepresentation = std::static_pointer_cast<SurgSim::Framework::Representation>(staplerComponent);\n\n\tauto inputComponent = std::make_shared<SurgSim::Input::InputComponent>(\"input\");\n\tinputComponent->setDeviceName(\"MultiAxisDevice\");\n\n\tauto transferInputPose = std::make_shared<SurgSim::Blocks::TransferInputPoseBehavior>(\"Input to graphicalStapler\");\n\ttransferInputPose->setPoseSender(inputComponent);\n\ttransferInputPose->setPoseReceiver(staplerSceneryRepresentation);\n\n\tauto addStapleBehavior = std::make_shared<AddStapleFromInputBehavior>(\"Staple\");\n\taddStapleBehavior->setInputComponent(inputComponent);\n\n\tstaplerSceneElement->addComponent(inputComponent);\n\tstaplerSceneElement->addComponent(transferInputPose);\n\tstaplerSceneElement->addComponent(addStapleBehavior);\n\n\tstd::shared_ptr<SurgSim::Framework::Scene> scene = runtime->getScene();\n\tscene->addSceneElement(createSceneryObject(\"arm\", \"Geometry\/forearm.osgb\"));\n\tscene->addSceneElement(createView());\n\tscene->addSceneElement(staplerSceneElement);\n\n\truntime->execute();\n\n\treturn 0;\n}\n<commit_msg>Include all stapler parts into stapling demo.<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\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 <memory>\n#include <string>\n\n#include \"SurgSim\/Blocks\/BasicSceneElement.h\"\n#include \"SurgSim\/Blocks\/TransferInputPoseBehavior.h\"\n#include \"SurgSim\/Devices\/MultiAxis\/MultiAxisDevice.h\"\n#include \"SurgSim\/Framework\/BehaviorManager.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Framework\/TransferPropertiesBehavior.h\"\n#include \"SurgSim\/Input\/InputComponent.h\"\n#include \"SurgSim\/Input\/InputManager.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgSceneryRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgView.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n#include \"Examples\/ExampleStapling\/AddStapleBehavior.h\"\n\nusing SurgSim::Blocks::BasicSceneElement;\nusing SurgSim::Blocks::TransferInputPoseBehavior;\nusing SurgSim::Framework::BehaviorManager;\nusing SurgSim::Framework::Runtime;\nusing SurgSim::Framework::Scene;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Framework::TransferPropertiesBehavior;\nusing SurgSim::Graphics::SceneryRepresentation;\nusing SurgSim::Graphics::ViewElement;\nusing SurgSim::Graphics::OsgManager;\nusing SurgSim::Graphics::OsgViewElement;\nusing SurgSim::Graphics::OsgSceneryRepresentation;\nusing SurgSim::Input::DeviceInterface;\nusing SurgSim::Input::InputComponent;\nusing SurgSim::Input::InputManager;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Physics::PhysicsManager;\n\n\/\/\/ Load scenery object from file\n\/\/\/ \\param name Name of this scenery representation.\n\/\/\/ \\param fileName Name of the file from which the scenery representation is loaded.\n\/\/\/ \\return A SceneElement containing the scenery representation.\nstd::shared_ptr<SceneElement> createSceneryObject(const std::string& name, const std::string& fileName)\n{\n\tstd::shared_ptr<SceneryRepresentation> sceneryRepresentation =\n\t\tstd::make_shared<OsgSceneryRepresentation>(name + \"SceneryRepresentation\");\n\tsceneryRepresentation->setFileName(fileName);\n\n\tstd::shared_ptr<SceneElement> sceneElement = std::make_shared<BasicSceneElement>(name + \"SceneElement\");\n\tsceneElement->addComponent(sceneryRepresentation);\n\n\treturn sceneElement;\n}\n\nstd::shared_ptr<SceneElement> createStapler(const std::string& staplerName, const std::string& deviceName)\n{\n\tstd::shared_ptr<SceneryRepresentation> staplerHandle =\n\t\tstd::make_shared<OsgSceneryRepresentation>(staplerName + \"Handle\");\n\tstd::shared_ptr<SceneryRepresentation> staplerIndicator =\n\t\tstd::make_shared<OsgSceneryRepresentation>(staplerName + \"Indicator\");\n\tstd::shared_ptr<SceneryRepresentation> staplerMarkings=\n\t\tstd::make_shared<OsgSceneryRepresentation>(staplerName + \"Markings\");\n\tstd::shared_ptr<SceneryRepresentation> staplerTrigger =\n\t\tstd::make_shared<OsgSceneryRepresentation>(staplerName + \"Trigger\");\n\n\tstaplerHandle->setFileName(\"Geometry\/stapler_handle.obj\");\n\tstaplerIndicator->setFileName(\"Geometry\/stapler_indicator.obj\");\n\tstaplerMarkings->setFileName(\"Geometry\/stapler_markings.obj\");\n\tstaplerTrigger->setFileName(\"Geometry\/stapler_trigger.obj\");\n\n\tstd::shared_ptr<TransferPropertiesBehavior> glue = std::make_shared<TransferPropertiesBehavior>(\"StaplerGlue\");\n\tglue->connect(staplerHandle, \"pose\", staplerIndicator, \"pose\");\n\tglue->connect(staplerHandle, \"pose\", staplerMarkings, \"pose\");\n\tglue->connect(staplerHandle, \"pose\", staplerTrigger, \"pose\");\n\n\tstd::shared_ptr<InputComponent> inputComponent = std::make_shared<InputComponent>(\"input\");\n\tinputComponent->setDeviceName(deviceName);\n\n\tstd::shared_ptr<TransferInputPoseBehavior> transferInputPose =\n\t\tstd::make_shared<TransferInputPoseBehavior>(\"Input to graphicalStapler\");\n\ttransferInputPose->setPoseSender(inputComponent);\n\ttransferInputPose->setPoseReceiver(staplerHandle);\n\n\tstd::shared_ptr<AddStapleFromInputBehavior> addStapleBehavior =\n\t\tstd::make_shared<AddStapleFromInputBehavior>(\"Staple\");\n\taddStapleBehavior->setInputComponent(inputComponent);\n\n\tstd::shared_ptr<SceneElement> sceneElement = std::make_shared<BasicSceneElement>(staplerName + \"SceneElement\");\n\tsceneElement->addComponent(staplerHandle);\n\tsceneElement->addComponent(staplerIndicator);\n\tsceneElement->addComponent(staplerMarkings);\n\tsceneElement->addComponent(staplerTrigger);\n\tsceneElement->addComponent(glue);\n\tsceneElement->addComponent(inputComponent);\n\tsceneElement->addComponent(transferInputPose);\n\tsceneElement->addComponent(addStapleBehavior);\n\n\treturn sceneElement;\n}\n\nstd::shared_ptr<ViewElement> createView()\n{\n\tstd::shared_ptr<OsgViewElement> view = std::make_shared<OsgViewElement>(\"StaplingDemoView\");\n\n\tview->enableManipulator(true);\n\tview->setManipulatorParameters(Vector3d(0.0, 0.5, 0.5), Vector3d::Zero());\n\n\treturn view;\n}\n\nint main(int argc, char* argv[])\n{\n\tconst std::string deviceName = \"MultiAxisDevice\";\n\n\tstd::shared_ptr<BehaviorManager> behaviorManager = std::make_shared<BehaviorManager>();\n\tstd::shared_ptr<OsgManager> graphicsManager = std::make_shared<OsgManager>();\n\tstd::shared_ptr<InputManager> inputManager = std::make_shared<InputManager>();\n\tstd::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>();\n\n\tstd::shared_ptr<Runtime> runtime = std::make_shared<Runtime>(\"config.txt\");\n\truntime->addManager(behaviorManager);\n\truntime->addManager(graphicsManager);\n\truntime->addManager(inputManager);\n\truntime->addManager(physicsManager);\n\n\tstd::shared_ptr<DeviceInterface> toolDevice = std::make_shared<SurgSim::Device::MultiAxisDevice>(deviceName);\n\tSURGSIM_ASSERT(toolDevice->initialize() == true) <<\n\t\t\"Could not initialize device \" << toolDevice->getName() << \" for the tool.\\n\";\n\tinputManager->addDevice(toolDevice);\n\n\tstd::shared_ptr<Scene> scene = runtime->getScene();\n\tscene->addSceneElement(createSceneryObject(\"arm\", \"Geometry\/forearm.osgb\"));\n\tscene->addSceneElement(createView());\n\tscene->addSceneElement(createStapler(\"stapler\", deviceName));\n\n\truntime->execute();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ruby.h>\n#if defined(HAVE_RUBY_ENCODING_H)\n#include <ruby\/encoding.h>\n#endif\n\n#include \"unf\/normalizer.hh\"\n\nextern \"C\" {\n VALUE unf_allocate(VALUE klass);\n VALUE unf_initialize(VALUE self);\n VALUE unf_delete(UNF::Normalizer* ptr);\n VALUE unf_normalize(VALUE self, VALUE source, VALUE normalization_form);\n\n ID FORM_NFD;\n ID FORM_NFC;\n ID FORM_NFKD;\n ID FORM_NFKC;\n\n void Init_unf_ext() {\n VALUE mdl = rb_define_module(\"UNF\");\n\n VALUE cls = rb_define_class_under(mdl, \"Normalizer\", rb_cObject);\n rb_define_alloc_func(cls, unf_allocate);\n rb_define_method(cls, \"initialize\", (VALUE (*)(...))unf_initialize, 0);\n rb_define_method(cls, \"normalize\", (VALUE (*)(...))unf_normalize, 2);\n\n FORM_NFD = rb_intern(\"nfd\");\n FORM_NFC = rb_intern(\"nfc\");\n FORM_NFKD= rb_intern(\"nfkd\");\n FORM_NFKC= rb_intern(\"nfkc\");\n }\n\n\n VALUE unf_allocate(VALUE klass) {\n UNF::Normalizer* ptr;\n VALUE obj = Data_Make_Struct(klass, UNF::Normalizer, NULL, unf_delete, ptr);\n new ((void*)ptr) UNF::Normalizer;\n return obj;\n }\n\n VALUE unf_initialize(VALUE self) {\n return self;\n }\n\n VALUE unf_delete(UNF::Normalizer* ptr) {\n ptr->~Normalizer();\n ruby_xfree(ptr);\n }\n\n VALUE unf_normalize(VALUE self, VALUE source, VALUE normalization_form) {\n UNF::Normalizer* ptr;\n Data_Get_Struct(self, UNF::Normalizer, ptr);\n\n const char* src = StringValueCStr(source);\n const char* rlt;\n ID form_id = SYM2ID(normalization_form);\n\n if(form_id == FORM_NFD)\n rlt = ptr->normalize(src, UNF::Normalizer::FORM_NFD);\n else if(form_id == FORM_NFC)\n rlt = ptr->normalize(src, UNF::Normalizer::FORM_NFC);\n else if(form_id == FORM_NFKD)\n rlt = ptr->normalize(src, UNF::Normalizer::FORM_NFKD);\n else if(form_id == FORM_NFKC)\n rlt = ptr->normalize(src, UNF::Normalizer::FORM_NFKC);\n else\n rb_raise(rb_eArgError, \"Specified Normalization-Form is unknown. Please select one from among :nfc, :nfd, :nfkc, :nfkd.\");\n\n#if defined(HAVE_RUBY_ENCODING_H)\n return rb_enc_str_new(rlt, strlen(rlt), rb_utf8_encoding());\n#else\n return rb_str_new2(rlt);\n#endif\n }\n}\n<commit_msg>Include ruby.h after unf\/normalizer.hh so fix build with 1.8 on win32.<commit_after>#include \"unf\/normalizer.hh\"\n\n#include <ruby.h>\n#if defined(HAVE_RUBY_ENCODING_H)\n#include <ruby\/encoding.h>\n#endif\n\nextern \"C\" {\n VALUE unf_allocate(VALUE klass);\n VALUE unf_initialize(VALUE self);\n VALUE unf_delete(UNF::Normalizer* ptr);\n VALUE unf_normalize(VALUE self, VALUE source, VALUE normalization_form);\n\n ID FORM_NFD;\n ID FORM_NFC;\n ID FORM_NFKD;\n ID FORM_NFKC;\n\n void Init_unf_ext() {\n VALUE mdl = rb_define_module(\"UNF\");\n\n VALUE cls = rb_define_class_under(mdl, \"Normalizer\", rb_cObject);\n rb_define_alloc_func(cls, unf_allocate);\n rb_define_method(cls, \"initialize\", (VALUE (*)(...))unf_initialize, 0);\n rb_define_method(cls, \"normalize\", (VALUE (*)(...))unf_normalize, 2);\n\n FORM_NFD = rb_intern(\"nfd\");\n FORM_NFC = rb_intern(\"nfc\");\n FORM_NFKD= rb_intern(\"nfkd\");\n FORM_NFKC= rb_intern(\"nfkc\");\n }\n\n\n VALUE unf_allocate(VALUE klass) {\n UNF::Normalizer* ptr;\n VALUE obj = Data_Make_Struct(klass, UNF::Normalizer, NULL, unf_delete, ptr);\n new ((void*)ptr) UNF::Normalizer;\n return obj;\n }\n\n VALUE unf_initialize(VALUE self) {\n return self;\n }\n\n VALUE unf_delete(UNF::Normalizer* ptr) {\n ptr->~Normalizer();\n ruby_xfree(ptr);\n }\n\n VALUE unf_normalize(VALUE self, VALUE source, VALUE normalization_form) {\n UNF::Normalizer* ptr;\n Data_Get_Struct(self, UNF::Normalizer, ptr);\n\n const char* src = StringValueCStr(source);\n const char* rlt;\n ID form_id = SYM2ID(normalization_form);\n\n if(form_id == FORM_NFD)\n rlt = ptr->normalize(src, UNF::Normalizer::FORM_NFD);\n else if(form_id == FORM_NFC)\n rlt = ptr->normalize(src, UNF::Normalizer::FORM_NFC);\n else if(form_id == FORM_NFKD)\n rlt = ptr->normalize(src, UNF::Normalizer::FORM_NFKD);\n else if(form_id == FORM_NFKC)\n rlt = ptr->normalize(src, UNF::Normalizer::FORM_NFKC);\n else\n rb_raise(rb_eArgError, \"Specified Normalization-Form is unknown. Please select one from among :nfc, :nfd, :nfkc, :nfkd.\");\n\n#if defined(HAVE_RUBY_ENCODING_H)\n return rb_enc_str_new(rlt, strlen(rlt), rb_utf8_encoding());\n#else\n return rb_str_new2(rlt);\n#endif\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: serviceinfohelper.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2003-03-19 16:19:05 $\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: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_\n#define CONFIGMGR_SERVICEINFOHELPER_HXX_\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n using ::rtl::OUString;\n\/\/ -----------------------------------------------------------------------------\n\n typedef sal_Char const * AsciiServiceName;\n\/\/ -----------------------------------------------------------------------------\n\n \/\/\/ POD struct describing the registration information of a service implementation\n struct ServiceRegistrationInfo\n {\n \/\/\/ The implementation name of this service implementation\n AsciiServiceName implementationName;\n \/\/\/ The services for which this service implementation is registered\n AsciiServiceName const * registeredServiceNames;\n };\n\/\/ -----------------------------------------------------------------------------\n\n \/\/\/ POD struct describing the implementation information of a service implementation\n struct ServiceImplementationInfo\n {\n \/\/\/ The implementation name of this service implementation\n AsciiServiceName implementationName;\n \/\/\/ The services for which this service implementation is registered\n AsciiServiceName const * registeredServiceNames;\n \/\/\/ Additional services implemented by this service implementation, for which it is not registered\n AsciiServiceName const * additionalServiceNames;\n };\n\/\/ -----------------------------------------------------------------------------\n\n \/\/ ServiceImplementationInfo has a compatible initial sequence with struct ServiceRegistrationInfo\n\n inline\n ServiceRegistrationInfo const *\n getRegistrationInfo(ServiceImplementationInfo const * _info)\n {\n return reinterpret_cast<ServiceRegistrationInfo const *>(_info);\n }\n\/\/ -----------------------------------------------------------------------------\n\n \/\/\/ POD struct describing the registration information of a singleton\n struct SingletonRegistrationInfo\n {\n \/\/\/ The name of this singleton\n AsciiServiceName singletonName;\n \/\/\/ The implementation, which owns this singleton\n AsciiServiceName implementationName;\n \/\/\/ The service, which should be instatiated for this singleton\n AsciiServiceName instantiatedServiceName;\n \/\/\/ A name for a pseudo-implementation, which is mapped to this singleton\n ServiceRegistrationInfo const * mappedImplementation;\n };\n\/\/ -----------------------------------------------------------------------------\n\n class ServiceRegistrationHelper\n {\n ServiceRegistrationInfo const*const m_info;\n\n public:\n ServiceRegistrationHelper(ServiceRegistrationInfo const* _info)\n : m_info(_info)\n {}\n\n ServiceRegistrationHelper(ServiceImplementationInfo const* _info)\n : m_info(getRegistrationInfo(_info))\n {}\n\n sal_Int32 countServices() const;\n\n OUString getImplementationName( ) const\n throw(uno::RuntimeException);\n\n uno::Sequence< OUString > getRegisteredServiceNames( ) const\n throw(uno::RuntimeException);\n };\n\/\/ -----------------------------------------------------------------------------\n\n class ServiceInfoHelper\n {\n ServiceImplementationInfo const*const m_info;\n\n public:\n ServiceInfoHelper(ServiceImplementationInfo const* _info)\n : m_info(_info)\n {}\n\n sal_Int32 countServices() const;\n\n OUString getImplementationName( ) const\n throw(uno::RuntimeException);\n\n sal_Bool supportsService( OUString const & ServiceName ) const\n throw(uno::RuntimeException);\n\n uno::Sequence< OUString > getSupportedServiceNames( ) const\n throw(uno::RuntimeException);\n };\n\/\/ -----------------------------------------------------------------------------\n\n} \/\/ namespace configmgr\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.194); FILE MERGED 2005\/09\/05 17:04:35 rt 1.3.194.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: serviceinfohelper.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 03:55:54 $\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 CONFIGMGR_SERVICEINFOHELPER_HXX_\n#define CONFIGMGR_SERVICEINFOHELPER_HXX_\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n using ::rtl::OUString;\n\/\/ -----------------------------------------------------------------------------\n\n typedef sal_Char const * AsciiServiceName;\n\/\/ -----------------------------------------------------------------------------\n\n \/\/\/ POD struct describing the registration information of a service implementation\n struct ServiceRegistrationInfo\n {\n \/\/\/ The implementation name of this service implementation\n AsciiServiceName implementationName;\n \/\/\/ The services for which this service implementation is registered\n AsciiServiceName const * registeredServiceNames;\n };\n\/\/ -----------------------------------------------------------------------------\n\n \/\/\/ POD struct describing the implementation information of a service implementation\n struct ServiceImplementationInfo\n {\n \/\/\/ The implementation name of this service implementation\n AsciiServiceName implementationName;\n \/\/\/ The services for which this service implementation is registered\n AsciiServiceName const * registeredServiceNames;\n \/\/\/ Additional services implemented by this service implementation, for which it is not registered\n AsciiServiceName const * additionalServiceNames;\n };\n\/\/ -----------------------------------------------------------------------------\n\n \/\/ ServiceImplementationInfo has a compatible initial sequence with struct ServiceRegistrationInfo\n\n inline\n ServiceRegistrationInfo const *\n getRegistrationInfo(ServiceImplementationInfo const * _info)\n {\n return reinterpret_cast<ServiceRegistrationInfo const *>(_info);\n }\n\/\/ -----------------------------------------------------------------------------\n\n \/\/\/ POD struct describing the registration information of a singleton\n struct SingletonRegistrationInfo\n {\n \/\/\/ The name of this singleton\n AsciiServiceName singletonName;\n \/\/\/ The implementation, which owns this singleton\n AsciiServiceName implementationName;\n \/\/\/ The service, which should be instatiated for this singleton\n AsciiServiceName instantiatedServiceName;\n \/\/\/ A name for a pseudo-implementation, which is mapped to this singleton\n ServiceRegistrationInfo const * mappedImplementation;\n };\n\/\/ -----------------------------------------------------------------------------\n\n class ServiceRegistrationHelper\n {\n ServiceRegistrationInfo const*const m_info;\n\n public:\n ServiceRegistrationHelper(ServiceRegistrationInfo const* _info)\n : m_info(_info)\n {}\n\n ServiceRegistrationHelper(ServiceImplementationInfo const* _info)\n : m_info(getRegistrationInfo(_info))\n {}\n\n sal_Int32 countServices() const;\n\n OUString getImplementationName( ) const\n throw(uno::RuntimeException);\n\n uno::Sequence< OUString > getRegisteredServiceNames( ) const\n throw(uno::RuntimeException);\n };\n\/\/ -----------------------------------------------------------------------------\n\n class ServiceInfoHelper\n {\n ServiceImplementationInfo const*const m_info;\n\n public:\n ServiceInfoHelper(ServiceImplementationInfo const* _info)\n : m_info(_info)\n {}\n\n sal_Int32 countServices() const;\n\n OUString getImplementationName( ) const\n throw(uno::RuntimeException);\n\n sal_Bool supportsService( OUString const & ServiceName ) const\n throw(uno::RuntimeException);\n\n uno::Sequence< OUString > getSupportedServiceNames( ) const\n throw(uno::RuntimeException);\n };\n\/\/ -----------------------------------------------------------------------------\n\n} \/\/ namespace configmgr\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <jni.h>\n#include \"demopkg_Process.h\"\n\nJNIEXPORT void JNICALL Java_demopkg_Process_nativeLongOperation\n (JNIEnv *env, jobject owner, jobject param1)\n{\n\tjclass cls = env->GetObjectClass(param1);\n\tjmethodID mid = env->GetMethodID(cls, \"OnPercent\", \"(I)V\");\n if (mid == NULL) {\n\t\tprintf(\"1. not found method..\\n\");\n return; \n } else printf(\"1. found method!\\n\");\n\t\/\/env->CallVoidMethod(owner, mid);\/\/error\n\tfor (int i=1; i<=100; i++)\n\t\tenv->CallVoidMethod(param1, mid, i);\/\/ok\n\tmid = env->GetMethodID(cls, \"OnPercentEx\", \"(Ldemopkg\/CmplxStruct;)V\");\n if (mid == NULL) {\n\t\tprintf(\"2. not found method..\\n\");\n return; \n } else printf(\"2. found method!\\n\");\n\tjclass clazz = env->FindClass(\"demopkg\/CmplxStruct\");\n\tjobject obj = env->AllocObject(clazz);\n\tif (obj == NULL) {\n\t\tprintf(\"2. can't alloc..\\n\");\n return; \n } else printf(\"2. alloc ok!\\n\");\n\tenv->CallVoidMethod(param1, mid, obj);\n}<commit_msg>set integer to field of callback param<commit_after>#include <jni.h>\n#include \"demopkg_Process.h\"\n\nJNIEXPORT void JNICALL Java_demopkg_Process_nativeLongOperation\n (JNIEnv *env, jobject owner, jobject param1)\n{\n\tjclass cls = env->GetObjectClass(param1);\n\tjmethodID mid = env->GetMethodID(cls, \"OnPercent\", \"(I)V\");\n if (mid == NULL) {\n\t\tprintf(\"1. not found method..\\n\");\n return; \n } else printf(\"1. found method!\\n\");\n\t\/\/env->CallVoidMethod(owner, mid);\/\/error\n\tfor (int i=1; i<=10; i++)\n\t\tenv->CallVoidMethod(param1, mid, i);\/\/ok\n\tmid = env->GetMethodID(cls, \"OnPercentEx\", \"(Ldemopkg\/CmplxStruct;)V\");\n if (mid == NULL) {\n\t\tprintf(\"2. not found method..\\n\");\n return; \n } else printf(\"2. found method!\\n\");\n\tjclass clazz = env->FindClass(\"demopkg\/CmplxStruct\");\n\tjobject obj = env->AllocObject(clazz);\n\tif (obj == NULL) {\n\t\tprintf(\"2. can't alloc..\\n\");\n return; \n } else printf(\"2. alloc ok!\\n\");\n\tjfieldID fld = env->GetFieldID(clazz, \"fieldI\",\"I\");\n\tenv->SetIntField(obj, fld, 3);\n\tenv->CallVoidMethod(param1, mid, obj);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * vector-benches.cpp\n *\n * Benchmarks relating to SSE and AVX instructions.\n *\/\n\n#if !UARCH_BENCH_PORTABLE\n\n#include <immintrin.h>\n\n#include \"benchmark.hpp\"\n#include \"opt-control.hpp\"\n\nextern \"C\" {\n\nbench2_f bypass_vmovdqa_latency;\nbench2_f bypass_vmovdqu_latency;\nbench2_f bypass_vmovups_latency;\nbench2_f bypass_vmovupd_latency;\n\nbench2_f bypass_movd_latency;\nbench2_f bypass_movq_latency;\n\nbench2_f vector_load_load_lat_movdqu_0_xmm;\nbench2_f vector_load_load_lat_vmovdqu_0_xmm;\nbench2_f vector_load_load_lat_lddqu_0_xmm;\nbench2_f vector_load_load_lat_vlddqu_0_xmm;\nbench2_f vector_load_load_lat_vmovdqu_0_ymm;\nbench2_f vector_load_load_lat_vmovdqu32_0_zmm;\n\nbench2_f vector_load_load_lat_movdqu_63_xmm;\nbench2_f vector_load_load_lat_vmovdqu_63_xmm;\nbench2_f vector_load_load_lat_lddqu_63_xmm;\nbench2_f vector_load_load_lat_vlddqu_63_xmm;\nbench2_f vector_load_load_lat_vmovdqu_63_ymm;\nbench2_f vector_load_load_lat_vmovdqu32_63_zmm;\n\nbench2_f p01_fusion_p1;\nbench2_f p01_fusion_p0;\n\n}\n\n\/**\n * Specialization of modify for double to use the xmm\n * register type (x86 specific).\n *\/\nHEDLEY_ALWAYS_INLINE\nstatic void modify(__m256i& x) {\n __asm__ volatile (\" \" :\"+x\"(x)::);\n}\n\nHEDLEY_NEVER_INLINE\nlong intrinsic_bench(uint64_t iters, void*) {\n\n __m256i total = _mm256_setzero_si256(), addend = _mm256_set1_epi32(1);\n\n do {\n for (int i = 0; i < 4; i++) {\n total = _mm256_add_epi32(total, addend);\n modify(total);\n }\n } while (--iters);\n\n return _mm256_extract_epi32(total, 0);\n}\n\ntemplate <typename TIMER>\nvoid register_vector(GroupList& list) {\n {\n std::shared_ptr<BenchmarkGroup> group = std::make_shared<BenchmarkGroup>(\"vector\/bypass\", \"Vector unit bypass latency\");\n list.push_back(group);\n\n auto maker = DeltaMaker<TIMER>(group.get(), 100000);\n\n maker.template make<bypass_vmovdqa_latency>(\"movdqa\", \"movdqa [mem] -> paddb latency\", 1);\n maker.template make<bypass_vmovdqu_latency>(\"movdqu\", \"movdqu [mem] -> paddb latency\", 1);\n maker.template make<bypass_vmovups_latency>(\"movups\", \"movups [mem] -> paddb latency\", 1);\n maker.template make<bypass_vmovupd_latency>(\"movupd\", \"movupd [mem] -> paddb latency\", 1);\n\n maker.template make<bypass_movd_latency>(\"movd\", \"movq rax,xmm0 -> xmm0,rax lat\", 1);\n maker.template make<bypass_movq_latency>(\"movq\", \"movq rax,xmm0 -> xmm0,rax lat\", 1);\n\n }\n\n {\n std::shared_ptr<BenchmarkGroup> group = std::make_shared<BenchmarkGroup>(\"vector\/load-load\", \"Vector load-load latency\");\n list.push_back(group);\n\n auto maker = DeltaMaker<TIMER>(group.get(), 100000).setFeatures({AVX2});\n auto m512 = maker.setFeatures({AVX512F});\n\n maker.template make< vector_load_load_lat_movdqu_0_xmm >( \"movdqu-aligned\" , \"aligned movdqu xmm load lat\", 1);\n maker.template make<vector_load_load_lat_vmovdqu_0_xmm >( \"vmovdqu-aligned\" , \"aligned vmovdqu xmm load lat\", 1);\n maker.template make< vector_load_load_lat_lddqu_0_xmm >( \"lddqu-aligned\" , \"aligned lddqu xmm load lat\", 1);\n maker.template make< vector_load_load_lat_vlddqu_0_xmm >( \"vlddqu-aligned\" , \"aligned vlddqu xmm load lat\", 1);\n maker.template make<vector_load_load_lat_vmovdqu_0_ymm >( \"vmovdqu-aligned-ymm\", \"aligned vmovdqu ymm load lat\", 1);\n m512 .template make<vector_load_load_lat_vmovdqu32_0_zmm>( \"vmovdqu-aligned-zmm\", \"aligned vmovdqu zmm load lat\", 1);\n\n maker.template make< vector_load_load_lat_movdqu_63_xmm >( \"movdqu-misaligned\" , \"misaligned movdqu xmm load lat\", 1);\n maker.template make<vector_load_load_lat_vmovdqu_63_xmm >(\"vmovdqu-misaligned\" , \"misaligned vmovdqu xmm load lat\", 1);\n maker.template make< vector_load_load_lat_lddqu_63_xmm >( \"lddqu-misaligned\" , \"misaligned lddqu xmm load lat\", 1);\n maker.template make< vector_load_load_lat_vlddqu_63_xmm >( \"vlddqu-misaligned\" , \"misaligned vlddqu xmm load lat\", 1);\n maker.template make<vector_load_load_lat_vmovdqu_63_ymm >(\"vmovdqu-misaligned-ymm\", \"misaligned vmovdqu ymm load lat\", 1);\n m512 .template make<vector_load_load_lat_vmovdqu32_63_zmm>(\"vmovdqu-misaligned-zmm\", \"misaligned vmovdqu zmm load lat\", 1);\n }\n\n {\n std::shared_ptr<BenchmarkGroup> group = std::make_shared<BenchmarkGroup>(\"vector\/misc\", \"Miscellaneous vector benches\");\n list.push_back(group);\n\n auto m512 = DeltaMaker<TIMER>(group.get(), 1000).setFeatures({AVX512F});\n\n m512.template make<p01_fusion_p1>(\"p01-fusion-p1\", \"check that scalar ops go to p1\", 100);\n m512.template make<p01_fusion_p0>(\"p01-fusion-p0\", \"check that scalar ops go to p0\", 100);\n\n auto maker = DeltaMaker<TIMER>(group.get()).setFeatures({AVX2});\n\n maker.template make<intrinsic_bench>(\"intrinsic\", \"demo how to write intrinsic bench\", 4);\n maker.useLoopDelta().template make<intrinsic_bench>(\"intrinsic-loop-delta\", \"demo with loop delta\", 4);\n }\n\n}\n\n#define REGISTER_ALL(CLOCK) template void register_vector<CLOCK>(GroupList& list);\n\nALL_TIMERS_X(REGISTER_ALL)\n\n#endif \/\/ #if !UARCH_BENCH_PORTABLE\n\n\n<commit_msg>make bench AVX2 specific<commit_after>\/*\n * vector-benches.cpp\n *\n * Benchmarks relating to SSE and AVX instructions.\n *\/\n\n#if !UARCH_BENCH_PORTABLE\n\n#ifdef __AVX2__\n#include <immintrin.h>\n#endif\n\n#include \"benchmark.hpp\"\n#include \"opt-control.hpp\"\n\nextern \"C\" {\n\nbench2_f bypass_vmovdqa_latency;\nbench2_f bypass_vmovdqu_latency;\nbench2_f bypass_vmovups_latency;\nbench2_f bypass_vmovupd_latency;\n\nbench2_f bypass_movd_latency;\nbench2_f bypass_movq_latency;\n\nbench2_f vector_load_load_lat_movdqu_0_xmm;\nbench2_f vector_load_load_lat_vmovdqu_0_xmm;\nbench2_f vector_load_load_lat_lddqu_0_xmm;\nbench2_f vector_load_load_lat_vlddqu_0_xmm;\nbench2_f vector_load_load_lat_vmovdqu_0_ymm;\nbench2_f vector_load_load_lat_vmovdqu32_0_zmm;\n\nbench2_f vector_load_load_lat_movdqu_63_xmm;\nbench2_f vector_load_load_lat_vmovdqu_63_xmm;\nbench2_f vector_load_load_lat_lddqu_63_xmm;\nbench2_f vector_load_load_lat_vlddqu_63_xmm;\nbench2_f vector_load_load_lat_vmovdqu_63_ymm;\nbench2_f vector_load_load_lat_vmovdqu32_63_zmm;\n\nbench2_f p01_fusion_p1;\nbench2_f p01_fusion_p0;\n\n}\n\n#ifdef __AVX2__\n\n\/**\n * Specialization of modify for double to use the xmm\n * register type (x86 specific).\n *\/\nHEDLEY_ALWAYS_INLINE\nstatic void modify(__m256i& x) {\n __asm__ volatile (\" \" :\"+x\"(x)::);\n}\n\nHEDLEY_NEVER_INLINE\nlong intrinsic_bench(uint64_t iters, void*) {\n\n __m256i total = _mm256_setzero_si256(), addend = _mm256_set1_epi32(1);\n\n do {\n for (int i = 0; i < 4; i++) {\n total = _mm256_add_epi32(total, addend);\n modify(total);\n }\n } while (--iters);\n\n return _mm256_extract_epi32(total, 0);\n}\n\n#endif\n\ntemplate <typename TIMER>\nvoid register_vector(GroupList& list) {\n {\n std::shared_ptr<BenchmarkGroup> group = std::make_shared<BenchmarkGroup>(\"vector\/bypass\", \"Vector unit bypass latency\");\n list.push_back(group);\n\n auto maker = DeltaMaker<TIMER>(group.get(), 100000);\n\n maker.template make<bypass_vmovdqa_latency>(\"movdqa\", \"movdqa [mem] -> paddb latency\", 1);\n maker.template make<bypass_vmovdqu_latency>(\"movdqu\", \"movdqu [mem] -> paddb latency\", 1);\n maker.template make<bypass_vmovups_latency>(\"movups\", \"movups [mem] -> paddb latency\", 1);\n maker.template make<bypass_vmovupd_latency>(\"movupd\", \"movupd [mem] -> paddb latency\", 1);\n\n maker.template make<bypass_movd_latency>(\"movd\", \"movq rax,xmm0 -> xmm0,rax lat\", 1);\n maker.template make<bypass_movq_latency>(\"movq\", \"movq rax,xmm0 -> xmm0,rax lat\", 1);\n\n }\n\n {\n std::shared_ptr<BenchmarkGroup> group = std::make_shared<BenchmarkGroup>(\"vector\/load-load\", \"Vector load-load latency\");\n list.push_back(group);\n\n auto maker = DeltaMaker<TIMER>(group.get(), 100000).setFeatures({AVX2});\n auto m512 = maker.setFeatures({AVX512F});\n\n maker.template make< vector_load_load_lat_movdqu_0_xmm >( \"movdqu-aligned\" , \"aligned movdqu xmm load lat\", 1);\n maker.template make<vector_load_load_lat_vmovdqu_0_xmm >( \"vmovdqu-aligned\" , \"aligned vmovdqu xmm load lat\", 1);\n maker.template make< vector_load_load_lat_lddqu_0_xmm >( \"lddqu-aligned\" , \"aligned lddqu xmm load lat\", 1);\n maker.template make< vector_load_load_lat_vlddqu_0_xmm >( \"vlddqu-aligned\" , \"aligned vlddqu xmm load lat\", 1);\n maker.template make<vector_load_load_lat_vmovdqu_0_ymm >( \"vmovdqu-aligned-ymm\", \"aligned vmovdqu ymm load lat\", 1);\n m512 .template make<vector_load_load_lat_vmovdqu32_0_zmm>( \"vmovdqu-aligned-zmm\", \"aligned vmovdqu zmm load lat\", 1);\n\n maker.template make< vector_load_load_lat_movdqu_63_xmm >( \"movdqu-misaligned\" , \"misaligned movdqu xmm load lat\", 1);\n maker.template make<vector_load_load_lat_vmovdqu_63_xmm >(\"vmovdqu-misaligned\" , \"misaligned vmovdqu xmm load lat\", 1);\n maker.template make< vector_load_load_lat_lddqu_63_xmm >( \"lddqu-misaligned\" , \"misaligned lddqu xmm load lat\", 1);\n maker.template make< vector_load_load_lat_vlddqu_63_xmm >( \"vlddqu-misaligned\" , \"misaligned vlddqu xmm load lat\", 1);\n maker.template make<vector_load_load_lat_vmovdqu_63_ymm >(\"vmovdqu-misaligned-ymm\", \"misaligned vmovdqu ymm load lat\", 1);\n m512 .template make<vector_load_load_lat_vmovdqu32_63_zmm>(\"vmovdqu-misaligned-zmm\", \"misaligned vmovdqu zmm load lat\", 1);\n }\n\n {\n std::shared_ptr<BenchmarkGroup> group = std::make_shared<BenchmarkGroup>(\"vector\/misc\", \"Miscellaneous vector benches\");\n list.push_back(group);\n\n auto m512 = DeltaMaker<TIMER>(group.get(), 1000).setFeatures({AVX512F});\n\n m512.template make<p01_fusion_p1>(\"p01-fusion-p1\", \"check that scalar ops go to p1\", 100);\n m512.template make<p01_fusion_p0>(\"p01-fusion-p0\", \"check that scalar ops go to p0\", 100);\n\n#ifdef __AVX2__\n auto maker = DeltaMaker<TIMER>(group.get()).setFeatures({AVX2});\n\n maker.template make<intrinsic_bench>(\"intrinsic\", \"demo how to write intrinsic bench\", 4);\n maker.useLoopDelta().template make<intrinsic_bench>(\"intrinsic-loop-delta\", \"demo with loop delta\", 4);\n#endif\n }\n\n}\n\n#define REGISTER_ALL(CLOCK) template void register_vector<CLOCK>(GroupList& list);\n\nALL_TIMERS_X(REGISTER_ALL)\n\n#endif \/\/ #if !UARCH_BENCH_PORTABLE\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Defuzzification.h\"\n#include \"FuzzyLogic.h\"\n#include \"InputFuzzySetTrapezoidal.h\"\n#include \"InputFuzzySetTriangular.h\"\n#include \"LibInfoFuzzyEngine.h\"\n#include \"OutputFuzzySetTrapezoidal.h\"\n#include \"OutputFuzzySetTriangular.h\"\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iostream>\n\nconst double EPS{0.01};\n\nSUITE(FuzzyEngine)\n{\n TEST(mbs_InputFuzzySetTriangular)\n {\n std::cout << \"--- mbs_InputFuzzySetTriangular\" << std::endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 10, 20);\n\n ifz.setInput(-10.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(0.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(2.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(5.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(7.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(25.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetLeftTriangular)\n {\n std::cout << \"--- mbs_InputFuzzySetLeftTriangular\" << std::endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 5, 15);\n\n ifz.setInput(5.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetRightTriangular)\n {\n std::cout << \"--- mbs_InputFuzzySetRightTriangular\" << std::endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 15, 15);\n\n ifz.setInput(0.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(5.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetTrapezoidal)\n {\n std::cout << \"--- mbs_InputFuzzySetTrapezoidal\" << std::endl;\n InputFuzzySetTrapezoidal ifz(\"Test\", 5, 10, 20, 40);\n\n ifz.setInput(-10.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(0.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(2.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(5.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(7.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(30.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(40.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(50.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetLeftTrapezoidal)\n {\n std::cout << \"--- mbs_InputFuzzySetLeftTrapezoidal\" << std::endl;\n InputFuzzySetTrapezoidal ifz(\"Test\", 0, 0, 20, 40);\n\n ifz.setInput(0.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(30.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(40.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(50.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetRightTrapezoidal)\n {\n std::cout << \"--- mbs_InputFuzzySetRightTrapezoidal\" << std::endl;\n InputFuzzySetTrapezoidal ifz(\"Test\", 5, 10, 20, 20);\n\n ifz.setInput(-10.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(0.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(2.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(5.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(7.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(30.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(defuz_OutputFuzzySetTriangular)\n {\n std::cout << \"--- defuz_OutputFuzzySetTriangular\" << std::endl;\n OutputFuzzySetTriangular ofz(\"Test\", 5, 10, 20);\n\n ofz.setMbs(0.5);\n CHECK_CLOSE(7.5, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(15.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((7.5 + 15.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n ofz.clearMbs();\n\n ofz.setMbs(0.1);\n CHECK_CLOSE(5.5, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(19.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((5.5 + 19.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n std::cout << std::endl;\n }\n\n TEST(defuz_OutputFuzzySetTrapezoidal)\n {\n std::cout << \"--- defuz_OutputFuzzySetTrapezoidal\" << std::endl;\n OutputFuzzySetTrapezoidal ofz(\"Test\", 0, 5, 10, 20);\n\n ofz.setMbs(0.5);\n CHECK_CLOSE(2.5, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(15.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((2.5 + 15.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n ofz.clearMbs();\n\n ofz.setMbs(0.1);\n CHECK_CLOSE(0.5, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(19.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((0.5 + 19.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n std::cout << std::endl;\n }\n\n TEST(defuz_OutputFuzzySetLeftTrapezoidal)\n {\n std::cout << \"--- defuz_OutputFuzzySetLeftTrapezoidal\" << std::endl;\n OutputFuzzySetTrapezoidal ofz(\"Test\", 0, 0, 10, 20);\n\n ofz.setMbs(0.5);\n CHECK_CLOSE(0.0, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(15.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((0.0 + 15.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n ofz.clearMbs();\n\n ofz.setMbs(0.1);\n CHECK_CLOSE(0.0, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(19.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((0.0 + 19.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n std::cout << std::endl;\n }\n\n TEST(defuz_outputsFuzzySets)\n {\n std::cout << \"-- defuz output Fuzzy Sets\" << std::endl;\n OutputFuzzySetTrapezoidal ofz1(\"Test\", 0, 1, 4, 5);\n OutputFuzzySetTrapezoidal ofz2(\"Test\", 3, 4, 6, 7);\n OutputFuzzySetTrapezoidal ofz3(\"Test\", 5, 6, 7, 8);\n std::vector<OutputFuzzySet *> all{&ofz1, &ofz2, &ofz3};\n\n ofz1.setMbs(0.3);\n ofz2.setMbs(0.5);\n ofz3.setMbs(1.0);\n CHECK_CLOSE(6.0, defuzFirstOfMaxima(all), EPS);\n CHECK_CLOSE(6.5, defuzMeanOfMaximum(all), EPS);\n CHECK_CLOSE(7.0, defuzLastOfMaxima(all), EPS);\n CHECK_CLOSE(5.416, defuzWeightedAverage(all), EPS);\n std::cout << std::endl;\n }\n\n TEST(FuzzyLogic_or)\n {\n std::cout << \"-- Fuzzy logic OR\" << std::endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz1.setInput(12.5);\n ifz2.setInput(12.5);\n ofz = ifz1 or ifz2;\n CHECK_CLOSE(0.5, ofz.getMbs(), EPS);\n auto mom = ofz.meanOfMaximum();\n std::cout << std::endl;\n }\n\n TEST(FuzzyLogic_and)\n {\n std::cout << \"-- Fuzzy logic AND\" << std::endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz1.setInput(10);\n ifz2.setInput(10);\n ofz = ifz1 and ifz2;\n CHECK_CLOSE(0.0, ofz.getMbs(), EPS);\n std::cout << std::endl;\n }\n\n TEST(FuzzyLogic_not)\n {\n std::cout << \"-- Fuzzy logic NOT\" << std::endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 10, 15);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz.setInput(13.75);\n ofz = not ifz;\n CHECK_CLOSE(0.75, ofz.getMbs(), EPS);\n\n ifz.setInput(20);\n ofz = not ifz;\n CHECK_CLOSE(1.0, ofz.getMbs(), EPS);\n std::cout << std::endl;\n }\n}\n\nint main()\n{\n std::cout << \"Tests: \" << fuzzy::libName << \" v\" << fuzzy::libVersion\n << std::endl\n << std::endl;\n\n auto result = UnitTest::RunAllTests();\n std::cout << std::endl;\n return result;\n}\n<commit_msg>Solved warning<commit_after>#include \"Defuzzification.h\"\n#include \"FuzzyLogic.h\"\n#include \"InputFuzzySetTrapezoidal.h\"\n#include \"InputFuzzySetTriangular.h\"\n#include \"LibInfoFuzzyEngine.h\"\n#include \"OutputFuzzySetTrapezoidal.h\"\n#include \"OutputFuzzySetTriangular.h\"\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iostream>\n\nconst double EPS{0.01};\n\nSUITE(FuzzyEngine)\n{\n TEST(mbs_InputFuzzySetTriangular)\n {\n std::cout << \"--- mbs_InputFuzzySetTriangular\" << std::endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 10, 20);\n\n ifz.setInput(-10.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(0.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(2.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(5.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(7.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(25.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetLeftTriangular)\n {\n std::cout << \"--- mbs_InputFuzzySetLeftTriangular\" << std::endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 5, 15);\n\n ifz.setInput(5.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetRightTriangular)\n {\n std::cout << \"--- mbs_InputFuzzySetRightTriangular\" << std::endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 15, 15);\n\n ifz.setInput(0.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(5.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetTrapezoidal)\n {\n std::cout << \"--- mbs_InputFuzzySetTrapezoidal\" << std::endl;\n InputFuzzySetTrapezoidal ifz(\"Test\", 5, 10, 20, 40);\n\n ifz.setInput(-10.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(0.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(2.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(5.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(7.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(30.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(40.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(50.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetLeftTrapezoidal)\n {\n std::cout << \"--- mbs_InputFuzzySetLeftTrapezoidal\" << std::endl;\n InputFuzzySetTrapezoidal ifz(\"Test\", 0, 0, 20, 40);\n\n ifz.setInput(0.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(30.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(40.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(50.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(mbs_InputFuzzySetRightTrapezoidal)\n {\n std::cout << \"--- mbs_InputFuzzySetRightTrapezoidal\" << std::endl;\n InputFuzzySetTrapezoidal ifz(\"Test\", 5, 10, 20, 20);\n\n ifz.setInput(-10.0);\n auto mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(0.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(2.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(5.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.0, mbs, EPS);\n\n ifz.setInput(7.5);\n mbs = ifz.getMbs();\n CHECK_CLOSE(0.5, mbs, EPS);\n\n ifz.setInput(10.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(15.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(20.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n\n ifz.setInput(30.0);\n mbs = ifz.getMbs();\n CHECK_CLOSE(1.0, mbs, EPS);\n std::cout << std::endl;\n }\n\n TEST(defuz_OutputFuzzySetTriangular)\n {\n std::cout << \"--- defuz_OutputFuzzySetTriangular\" << std::endl;\n OutputFuzzySetTriangular ofz(\"Test\", 5, 10, 20);\n\n ofz.setMbs(0.5);\n CHECK_CLOSE(7.5, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(15.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((7.5 + 15.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n ofz.clearMbs();\n\n ofz.setMbs(0.1);\n CHECK_CLOSE(5.5, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(19.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((5.5 + 19.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n std::cout << std::endl;\n }\n\n TEST(defuz_OutputFuzzySetTrapezoidal)\n {\n std::cout << \"--- defuz_OutputFuzzySetTrapezoidal\" << std::endl;\n OutputFuzzySetTrapezoidal ofz(\"Test\", 0, 5, 10, 20);\n\n ofz.setMbs(0.5);\n CHECK_CLOSE(2.5, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(15.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((2.5 + 15.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n ofz.clearMbs();\n\n ofz.setMbs(0.1);\n CHECK_CLOSE(0.5, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(19.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((0.5 + 19.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n std::cout << std::endl;\n }\n\n TEST(defuz_OutputFuzzySetLeftTrapezoidal)\n {\n std::cout << \"--- defuz_OutputFuzzySetLeftTrapezoidal\" << std::endl;\n OutputFuzzySetTrapezoidal ofz(\"Test\", 0, 0, 10, 20);\n\n ofz.setMbs(0.5);\n CHECK_CLOSE(0.0, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(15.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((0.0 + 15.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n ofz.clearMbs();\n\n ofz.setMbs(0.1);\n CHECK_CLOSE(0.0, ofz.firstOfMaxima(), EPS);\n CHECK_CLOSE(19.0, ofz.lastOfMaxima(), EPS);\n CHECK_CLOSE((0.0 + 19.0) \/ 2.0, ofz.meanOfMaximum(), EPS);\n std::cout << std::endl;\n }\n\n TEST(defuz_outputsFuzzySets)\n {\n std::cout << \"-- defuz output Fuzzy Sets\" << std::endl;\n OutputFuzzySetTrapezoidal ofz1(\"Test\", 0, 1, 4, 5);\n OutputFuzzySetTrapezoidal ofz2(\"Test\", 3, 4, 6, 7);\n OutputFuzzySetTrapezoidal ofz3(\"Test\", 5, 6, 7, 8);\n std::vector<OutputFuzzySet *> all{&ofz1, &ofz2, &ofz3};\n\n ofz1.setMbs(0.3);\n ofz2.setMbs(0.5);\n ofz3.setMbs(1.0);\n CHECK_CLOSE(6.0, defuzFirstOfMaxima(all), EPS);\n CHECK_CLOSE(6.5, defuzMeanOfMaximum(all), EPS);\n CHECK_CLOSE(7.0, defuzLastOfMaxima(all), EPS);\n CHECK_CLOSE(5.416, defuzWeightedAverage(all), EPS);\n std::cout << std::endl;\n }\n\n TEST(FuzzyLogic_or)\n {\n std::cout << \"-- Fuzzy logic OR\" << std::endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz1.setInput(12.5);\n ifz2.setInput(12.5);\n ofz = ifz1 or ifz2;\n CHECK_CLOSE(0.5, ofz.getMbs(), EPS);\n std::cout << std::endl;\n }\n\n TEST(FuzzyLogic_and)\n {\n std::cout << \"-- Fuzzy logic AND\" << std::endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz1.setInput(10);\n ifz2.setInput(10);\n ofz = ifz1 and ifz2;\n CHECK_CLOSE(0.0, ofz.getMbs(), EPS);\n std::cout << std::endl;\n }\n\n TEST(FuzzyLogic_not)\n {\n std::cout << \"-- Fuzzy logic NOT\" << std::endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 10, 15);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz.setInput(13.75);\n ofz = not ifz;\n CHECK_CLOSE(0.75, ofz.getMbs(), EPS);\n\n ifz.setInput(20);\n ofz = not ifz;\n CHECK_CLOSE(1.0, ofz.getMbs(), EPS);\n std::cout << std::endl;\n }\n}\n\nint main()\n{\n std::cout << \"Tests: \" << fuzzy::libName << \" v\" << fuzzy::libVersion\n << std::endl\n << std::endl;\n\n auto result = UnitTest::RunAllTests();\n std::cout << std::endl;\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <boost\/asio.hpp>\n\n#include <bh.h>\n#include <bh_serialize.h>\n#include \"comm.h\"\n\nusing boost::asio::ip::tcp;\nusing namespace std;\nusing namespace bohrium;\n\nnamespace bohrium {\nnamespace proxy {\n\nboost::asio::io_service io_service;\ntcp::socket socket(io_service);\n\nstatic void init_client_socket(tcp::socket &socket, const std::string &address, int port)\n{\n for(unsigned int i = 0; i < 1000000; ++i)\n {\n try\n {\n tcp::resolver resolver(io_service);\n tcp::resolver::query query(address, to_string(port));\n tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n boost::asio::connect(socket, endpoint_iterator);\n break;\n }\n catch(...)\n {\n cout << \"retry\" << endl;\n\n }\n\n }\n}\n\nstatic void init_server_socket(tcp::socket &socket, int port)\n{\n tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port));\n acceptor.accept(socket);\n}\n\nCommFrontend::CommFrontend(const char* component_name, const std::string &address, int port)\n{\n init_client_socket(socket, address, port);\n\n \/\/Serialize message body\n vector<char> buf_body;\n serialize::Init body(component_name);\n body.serialize(buf_body);\n\n \/\/Serialize message head\n vector<char> buf_head;\n serialize::Header head(serialize::TYPE_INIT, buf_body.size());\n head.serialize(buf_head);\n\n \/\/Send serialized message\n cout << \"server send INIT message \" << endl;\n boost::asio::write(socket, boost::asio::buffer(buf_head));\n boost::asio::write(socket, boost::asio::buffer(buf_body));\n}\n\nvoid CommFrontend::shutdown()\n{\n \/\/Serialize message head\n vector<char> buf_head;\n serialize::Header head(serialize::TYPE_SHUTDOWN, 0);\n head.serialize(buf_head);\n\n \/\/Send serialized message\n cout << \"server send SHUTDOWN message \" << endl;\n boost::asio::write(socket, boost::asio::buffer(buf_head));\n socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);\n socket.close();\n\n}\n\nvoid CommFrontend::execute(bh_ir &bhir)\n{\n \/\/Serialize the BhIR\n vector<char> buf_body;\n vector<bh_base*> data_send;\n vector<bh_base*> data_recv;\n exec_serializer.serialize(bhir, buf_body, data_send, data_recv);\n\n \/\/Serialize message head\n vector<char> buf_head;\n serialize::Header head(serialize::TYPE_EXEC, buf_body.size());\n head.serialize(buf_head);\n\n \/\/Send serialized message\n cout << \"server send EXEC message \" << endl;\n boost::asio::write(socket, boost::asio::buffer(buf_head));\n boost::asio::write(socket, boost::asio::buffer(buf_body));\n\n \/\/Send array data\n cout << \"EXEC send new base data: \";\n for(size_t i=0; i< data_send.size(); ++i)\n {\n bh_base *base = data_send[i];\n assert(base->data != NULL);\n printf(\"%p \", base);\n send_array_data(base);\n }\n cout << endl;\n\n \/\/Cleanup discard base array etc.\n exec_serializer.cleanup(bhir);\n\n \/\/Receive sync'ed array data\n cout << \"EXEC recv sync'ed base data: [\";\n for(size_t i=0; i< data_recv.size(); ++i)\n {\n bh_base *base = data_recv[i];\n bh_data_malloc(base);\n printf(\"%p \", base);\n recv_array_data(base);\n }\n cout << \"]\" << endl;\n}\n\nvoid CommFrontend::send_array_data(const bh_base *base)\n{\n assert(base->data != NULL);\n boost::asio::write(socket, boost::asio::buffer(base->data, bh_base_size(base)));\n}\n\nvoid CommFrontend::recv_array_data(bh_base *base)\n{\n assert(base->data != NULL);\n boost::asio::read(socket, boost::asio::buffer(base->data, bh_base_size(base)));\n}\n\n\nCommBackend::CommBackend(const std::string &address, int port) {\n init_server_socket(socket, port);\n}\n\nserialize::Header CommBackend::next_message_head()\n{\n \/\/Let's read the head of the message\n vector<char> buf_head(serialize::HeaderSize);\n boost::asio::read(socket, boost::asio::buffer(buf_head));\n serialize::Header head(buf_head);\n\n cout << \"client read head with body size of \" << head.body_size << endl;\n return head;\n}\n\nvoid CommBackend::next_message_body(std::vector<char> &buffer)\n{\n boost::asio::read(socket, boost::asio::buffer(buffer));\n}\n\nvoid CommBackend::shutdown()\n{\n socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);\n socket.close();\n}\n\nvoid CommBackend::send_array_data(const bh_base *base)\n{\n assert(base->data != NULL);\n boost::asio::write(socket, boost::asio::buffer(base->data, bh_base_size(base)));\n}\n\nvoid CommBackend::recv_array_data(bh_base *base)\n{\n assert(base->data != NULL);\n boost::asio::read(socket, boost::asio::buffer(base->data, bh_base_size(base)));\n}\n\n}}\n<commit_msg>proxy: replaced boost::asio::connect() with a more legacy compatible implementation<commit_after>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <boost\/asio.hpp>\n\n#include <bh.h>\n#include <bh_serialize.h>\n#include \"comm.h\"\n\nusing boost::asio::ip::tcp;\nusing namespace std;\nusing namespace bohrium;\n\nnamespace bohrium {\nnamespace proxy {\n\nboost::asio::io_service io_service;\ntcp::socket socket(io_service);\n\nstatic void init_client_socket(tcp::socket &socket, const std::string &address, int port)\n{\n for(unsigned int i = 0; i < 1000000; ++i)\n {\n try\n {\n \/\/ Get a list of endpoints corresponding to the server name.\n tcp::resolver resolver(io_service);\n tcp::resolver::query query(address, to_string(port));\n tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n tcp::resolver::iterator end;\n\n \/\/ Try each endpoint until we successfully establish a connection.\n boost::system::error_code error = boost::asio::error::host_not_found;\n while (error && endpoint_iterator != end)\n {\n socket.close();\n socket.connect(*endpoint_iterator++, error);\n }\n if (error)\n throw boost::system::system_error(error);\n\n return;\n }\n catch(...)\n {\n cout << \"retry\" << endl;\n\n }\n\n }\n}\n\nstatic void init_server_socket(tcp::socket &socket, int port)\n{\n tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port));\n acceptor.accept(socket);\n}\n\nCommFrontend::CommFrontend(const char* component_name, const std::string &address, int port)\n{\n init_client_socket(socket, address, port);\n\n \/\/Serialize message body\n vector<char> buf_body;\n serialize::Init body(component_name);\n body.serialize(buf_body);\n\n \/\/Serialize message head\n vector<char> buf_head;\n serialize::Header head(serialize::TYPE_INIT, buf_body.size());\n head.serialize(buf_head);\n\n \/\/Send serialized message\n cout << \"server send INIT message \" << endl;\n boost::asio::write(socket, boost::asio::buffer(buf_head));\n boost::asio::write(socket, boost::asio::buffer(buf_body));\n}\n\nvoid CommFrontend::shutdown()\n{\n \/\/Serialize message head\n vector<char> buf_head;\n serialize::Header head(serialize::TYPE_SHUTDOWN, 0);\n head.serialize(buf_head);\n\n \/\/Send serialized message\n cout << \"server send SHUTDOWN message \" << endl;\n boost::asio::write(socket, boost::asio::buffer(buf_head));\n socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);\n socket.close();\n\n}\n\nvoid CommFrontend::execute(bh_ir &bhir)\n{\n \/\/Serialize the BhIR\n vector<char> buf_body;\n vector<bh_base*> data_send;\n vector<bh_base*> data_recv;\n exec_serializer.serialize(bhir, buf_body, data_send, data_recv);\n\n \/\/Serialize message head\n vector<char> buf_head;\n serialize::Header head(serialize::TYPE_EXEC, buf_body.size());\n head.serialize(buf_head);\n\n \/\/Send serialized message\n cout << \"server send EXEC message \" << endl;\n boost::asio::write(socket, boost::asio::buffer(buf_head));\n boost::asio::write(socket, boost::asio::buffer(buf_body));\n\n \/\/Send array data\n cout << \"EXEC send new base data: \";\n for(size_t i=0; i< data_send.size(); ++i)\n {\n bh_base *base = data_send[i];\n assert(base->data != NULL);\n printf(\"%p \", base);\n send_array_data(base);\n }\n cout << endl;\n\n \/\/Cleanup discard base array etc.\n exec_serializer.cleanup(bhir);\n\n \/\/Receive sync'ed array data\n cout << \"EXEC recv sync'ed base data: [\";\n for(size_t i=0; i< data_recv.size(); ++i)\n {\n bh_base *base = data_recv[i];\n bh_data_malloc(base);\n printf(\"%p \", base);\n recv_array_data(base);\n }\n cout << \"]\" << endl;\n}\n\nvoid CommFrontend::send_array_data(const bh_base *base)\n{\n assert(base->data != NULL);\n boost::asio::write(socket, boost::asio::buffer(base->data, bh_base_size(base)));\n}\n\nvoid CommFrontend::recv_array_data(bh_base *base)\n{\n assert(base->data != NULL);\n boost::asio::read(socket, boost::asio::buffer(base->data, bh_base_size(base)));\n}\n\n\nCommBackend::CommBackend(const std::string &address, int port) {\n init_server_socket(socket, port);\n}\n\nserialize::Header CommBackend::next_message_head()\n{\n \/\/Let's read the head of the message\n vector<char> buf_head(serialize::HeaderSize);\n boost::asio::read(socket, boost::asio::buffer(buf_head));\n serialize::Header head(buf_head);\n\n cout << \"client read head with body size of \" << head.body_size << endl;\n return head;\n}\n\nvoid CommBackend::next_message_body(std::vector<char> &buffer)\n{\n boost::asio::read(socket, boost::asio::buffer(buffer));\n}\n\nvoid CommBackend::shutdown()\n{\n socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);\n socket.close();\n}\n\nvoid CommBackend::send_array_data(const bh_base *base)\n{\n assert(base->data != NULL);\n boost::asio::write(socket, boost::asio::buffer(base->data, bh_base_size(base)));\n}\n\nvoid CommBackend::recv_array_data(bh_base *base)\n{\n assert(base->data != NULL);\n boost::asio::read(socket, boost::asio::buffer(base->data, bh_base_size(base)));\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2005, 2014, Oracle and\/or its affiliates. All rights reserved.\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 2 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; see the file COPYING. If not, write to the\n Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n MA 02110-1301 USA.\n*\/\n\n\n\/* yaSSL buffer header implements input\/output buffers to simulate streaming\n * with SSL types and sockets\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <string.h> \/\/ memcpy\n#include \"runtime.hpp\"\n#include \"buffer.hpp\"\n#include \"yassl_types.hpp\"\n\nnamespace yaSSL {\n\n\n\n\n\/* return 0 on check success, always true for NoCheck policy *\/\nint NoCheck::check(uint, uint) \n{\n return 0;\n}\n\n\/* return 0 on check success *\/\nint Check::check(uint i, uint max) \n{\n if (i < max)\n return 0;\n\n return -1;\n}\n\n\n\/* input_buffer operates like a smart c style array with a checking option, \n * meant to be read from through [] with AUTO index or read().\n * Should only write to at\/near construction with assign() or raw (e.g., recv)\n * followed by add_size with the number of elements added by raw write.\n *\n * Not using vector because need checked []access, offset, and the ability to\n * write to the buffer bulk wise and have the correct size\n *\/\n\n\ninput_buffer::input_buffer() \n : size_(0), current_(0), buffer_(0), end_(0), error_(0), zero_(0)\n{}\n\n\ninput_buffer::input_buffer(uint s) \n : size_(0), current_(0), buffer_(NEW_YS byte[s]), end_(buffer_ + s),\n error_(0), zero_(0)\n{}\n\n\n\/\/ with assign\ninput_buffer::input_buffer(uint s, const byte* t, uint len) \n : size_(0), current_(0), buffer_(NEW_YS byte[s]), end_(buffer_ + s),\n error_(0), zero_(0)\n{ \n assign(t, len); \n}\n\n\ninput_buffer::~input_buffer() \n{ \n ysArrayDelete(buffer_); \n}\n\n\n\/\/ users can pass defualt zero length buffer and then allocate\nvoid input_buffer::allocate(uint s) \n{ \n if (error_ == 0) {\n buffer_ = NEW_YS byte[s];\n end_ = buffer_ + s;\n }\n}\n\n\n\/\/ for passing to raw writing functions at beginning, then use add_size\nbyte* input_buffer::get_buffer() const \n{ \n return buffer_; \n}\n\n\n\/\/ after a raw write user can set NEW_YS size\n\/\/ if you know the size before the write use assign()\nvoid input_buffer::add_size(uint i) \n{ \n if (error_ == 0 && check(size_ + i-1, get_capacity()) == 0)\n size_ += i;\n else\n error_ = -1;\n}\n\n\nuint input_buffer::get_capacity() const \n{ \n if (error_ == 0)\n return end_ - buffer_;\n\n return 0;\n}\n\n\nuint input_buffer::get_current() const \n{ \n if (error_ == 0)\n return current_;\n\n return 0;\n}\n\n\nuint input_buffer::get_size() const \n{ \n if (error_ == 0)\n return size_;\n\n return 0;\n}\n\n\nuint input_buffer::get_remaining() const \n{ \n if (error_ == 0)\n return size_ - current_;\n\n return 0;\n}\n\n\nint input_buffer::get_error() const \n{ \n return error_;\n}\n\n\nvoid input_buffer::set_error()\n{ \n error_ = -1;\n}\n\n\nvoid input_buffer::set_current(uint i) \n{\n if (error_ == 0 && i && check(i - 1, size_) == 0)\n current_ = i;\n else\n error_ = -1;\n}\n\n\n\/\/ read only access through [], advance current\n\/\/ user passes in AUTO index for ease of use\nconst byte& input_buffer::operator[](uint i) \n{\n if (error_ == 0 && check(current_, size_) == 0)\n return buffer_[current_++];\n\n error_ = -1;\n return zero_;\n}\n\n\n\/\/ end of input test\nbool input_buffer::eof() \n{ \n if (error_ != 0)\n return true;\n\n return current_ >= size_; \n}\n\n\n\/\/ peek ahead\nbyte input_buffer::peek()\n{\n if (error_ == 0 && check(current_, size_) == 0)\n return buffer_[current_];\n\n error_ = -1;\n return 0;\n}\n\n\n\/\/ write function, should use at\/near construction\nvoid input_buffer::assign(const byte* t, uint s)\n{\n if (t && error_ == 0 && check(current_, get_capacity()) == 0) {\n add_size(s);\n if (error_ == 0) {\n memcpy(&buffer_[current_], t, s);\n return; \/\/ success\n }\n }\n\n error_ = -1;\n}\n\n\n\/\/ use read to query input, adjusts current\nvoid input_buffer::read(byte* dst, uint length)\n{\n if (dst && error_ == 0 && check(current_ + length - 1, size_) == 0) {\n memcpy(dst, &buffer_[current_], length);\n current_ += length;\n } else {\n error_ = -1;\n }\n}\n\n\n\n\/* output_buffer operates like a smart c style array with a checking option.\n * Meant to be written to through [] with AUTO index or write().\n * Size (current) counter increases when written to. Can be constructed with \n * zero length buffer but be sure to allocate before first use. \n * Don't use add write for a couple bytes, use [] instead, way less overhead.\n * \n * Not using vector because need checked []access and the ability to\n * write to the buffer bulk wise and retain correct size\n *\/\n\n\noutput_buffer::output_buffer() \n : current_(0), buffer_(0), end_(0) \n{}\n\n\n\/\/ with allocate\noutput_buffer::output_buffer(uint s) \n : current_(0), buffer_(NEW_YS byte[s]), end_(buffer_ + s) \n{}\n\n\n\/\/ with assign\noutput_buffer::output_buffer(uint s, const byte* t, uint len) \n : current_(0), buffer_(NEW_YS byte[s]), end_(buffer_+ s) \n{ \n write(t, len); \n}\n\n\noutput_buffer::~output_buffer() \n{ \n ysArrayDelete(buffer_); \n}\n\n\nuint output_buffer::get_size() const \n{ \n return current_; \n}\n\n\nuint output_buffer::get_capacity() const \n{ \n return (uint) (end_ - buffer_); \n}\n\n\nvoid output_buffer::set_current(uint c) \n{ \n check(c, get_capacity()); \n current_ = c; \n}\n\n\n\/\/ users can pass defualt zero length buffer and then allocate\nvoid output_buffer::allocate(uint s) \n{ \n buffer_ = NEW_YS byte[s]; end_ = buffer_ + s; \n}\n\n\n\/\/ for passing to reading functions when finished\nconst byte* output_buffer::get_buffer() const \n{ \n return buffer_; \n}\n\n\n\/\/ allow write access through [], update current\n\/\/ user passes in AUTO as index for ease of use\nbyte& output_buffer::operator[](uint i) \n{\n check(current_, get_capacity());\n return buffer_[current_++];\n}\n\n\n\/\/ end of output test\nbool output_buffer::eof() \n{ \n return current_ >= get_capacity(); \n}\n\n\nvoid output_buffer::write(const byte* t, uint s)\n{\n check(current_ + s - 1, get_capacity()); \n memcpy(&buffer_[current_], t, s);\n current_ += s;\n}\n\n\n\n} \/\/ naemspace\n\n<commit_msg>Fix YaSSL on windows<commit_after>\/*\n Copyright (c) 2005, 2014, Oracle and\/or its affiliates. All rights reserved.\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 2 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; see the file COPYING. If not, write to the\n Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n MA 02110-1301 USA.\n*\/\n\n\n\/* yaSSL buffer header implements input\/output buffers to simulate streaming\n * with SSL types and sockets\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <string.h> \/\/ memcpy\n#include \"runtime.hpp\"\n#include \"buffer.hpp\"\n#include \"yassl_types.hpp\"\n\nnamespace yaSSL {\n\n\n\n\n\/* return 0 on check success, always true for NoCheck policy *\/\nint NoCheck::check(uint, uint) \n{\n return 0;\n}\n\n\/* return 0 on check success *\/\nint Check::check(uint i, uint max) \n{\n if (i < max)\n return 0;\n\n return -1;\n}\n\n\n\/* input_buffer operates like a smart c style array with a checking option, \n * meant to be read from through [] with AUTO index or read().\n * Should only write to at\/near construction with assign() or raw (e.g., recv)\n * followed by add_size with the number of elements added by raw write.\n *\n * Not using vector because need checked []access, offset, and the ability to\n * write to the buffer bulk wise and have the correct size\n *\/\n\n\ninput_buffer::input_buffer() \n : size_(0), current_(0), buffer_(0), end_(0), error_(0), zero_(0)\n{}\n\n\ninput_buffer::input_buffer(uint s) \n : size_(0), current_(0), buffer_(NEW_YS byte[s]), end_(buffer_ + s),\n error_(0), zero_(0)\n{}\n\n\n\/\/ with assign\ninput_buffer::input_buffer(uint s, const byte* t, uint len) \n : size_(0), current_(0), buffer_(NEW_YS byte[s]), end_(buffer_ + s),\n error_(0), zero_(0)\n{ \n assign(t, len); \n}\n\n\ninput_buffer::~input_buffer() \n{ \n ysArrayDelete(buffer_); \n}\n\n\n\/\/ users can pass defualt zero length buffer and then allocate\nvoid input_buffer::allocate(uint s) \n{ \n if (error_ == 0) {\n buffer_ = NEW_YS byte[s];\n end_ = buffer_ + s;\n }\n}\n\n\n\/\/ for passing to raw writing functions at beginning, then use add_size\nbyte* input_buffer::get_buffer() const \n{ \n return buffer_; \n}\n\n\n\/\/ after a raw write user can set NEW_YS size\n\/\/ if you know the size before the write use assign()\nvoid input_buffer::add_size(uint i) \n{ \n if (error_ == 0 && check(size_ + i-1, get_capacity()) == 0)\n size_ += i;\n else\n error_ = -1;\n}\n\n\nuint input_buffer::get_capacity() const \n{ \n if (error_ == 0)\n return end_ - buffer_;\n\n return 0;\n}\n\n\nuint input_buffer::get_current() const \n{ \n if (error_ == 0)\n return current_;\n\n return 0;\n}\n\n\nuint input_buffer::get_size() const \n{ \n if (error_ == 0)\n return size_;\n\n return 0;\n}\n\n\nuint input_buffer::get_remaining() const \n{ \n if (error_ == 0)\n return size_ - current_;\n\n return 0;\n}\n\n\nint input_buffer::get_error() const \n{ \n return error_;\n}\n\n\nvoid input_buffer::set_error()\n{ \n error_ = -1;\n}\n\n\nvoid input_buffer::set_current(uint i) \n{\n if (error_ == 0 && (i == 0 || check(i - 1, size_) == 0))\n current_ = i;\n else\n error_ = -1;\n}\n\n\n\/\/ read only access through [], advance current\n\/\/ user passes in AUTO index for ease of use\nconst byte& input_buffer::operator[](uint i) \n{\n if (error_ == 0 && check(current_, size_) == 0)\n return buffer_[current_++];\n\n error_ = -1;\n return zero_;\n}\n\n\n\/\/ end of input test\nbool input_buffer::eof() \n{ \n if (error_ != 0)\n return true;\n\n return current_ >= size_; \n}\n\n\n\/\/ peek ahead\nbyte input_buffer::peek()\n{\n if (error_ == 0 && check(current_, size_) == 0)\n return buffer_[current_];\n\n error_ = -1;\n return 0;\n}\n\n\n\/\/ write function, should use at\/near construction\nvoid input_buffer::assign(const byte* t, uint s)\n{\n if (t && error_ == 0 && check(current_, get_capacity()) == 0) {\n add_size(s);\n if (error_ == 0) {\n memcpy(&buffer_[current_], t, s);\n return; \/\/ success\n }\n }\n\n error_ = -1;\n}\n\n\n\/\/ use read to query input, adjusts current\nvoid input_buffer::read(byte* dst, uint length)\n{\n if (dst && error_ == 0 && check(current_ + length - 1, size_) == 0) {\n memcpy(dst, &buffer_[current_], length);\n current_ += length;\n } else {\n error_ = -1;\n }\n}\n\n\n\n\/* output_buffer operates like a smart c style array with a checking option.\n * Meant to be written to through [] with AUTO index or write().\n * Size (current) counter increases when written to. Can be constructed with \n * zero length buffer but be sure to allocate before first use. \n * Don't use add write for a couple bytes, use [] instead, way less overhead.\n * \n * Not using vector because need checked []access and the ability to\n * write to the buffer bulk wise and retain correct size\n *\/\n\n\noutput_buffer::output_buffer() \n : current_(0), buffer_(0), end_(0) \n{}\n\n\n\/\/ with allocate\noutput_buffer::output_buffer(uint s) \n : current_(0), buffer_(NEW_YS byte[s]), end_(buffer_ + s) \n{}\n\n\n\/\/ with assign\noutput_buffer::output_buffer(uint s, const byte* t, uint len) \n : current_(0), buffer_(NEW_YS byte[s]), end_(buffer_+ s) \n{ \n write(t, len); \n}\n\n\noutput_buffer::~output_buffer() \n{ \n ysArrayDelete(buffer_); \n}\n\n\nuint output_buffer::get_size() const \n{ \n return current_; \n}\n\n\nuint output_buffer::get_capacity() const \n{ \n return (uint) (end_ - buffer_); \n}\n\n\nvoid output_buffer::set_current(uint c) \n{ \n check(c, get_capacity()); \n current_ = c; \n}\n\n\n\/\/ users can pass defualt zero length buffer and then allocate\nvoid output_buffer::allocate(uint s) \n{ \n buffer_ = NEW_YS byte[s]; end_ = buffer_ + s; \n}\n\n\n\/\/ for passing to reading functions when finished\nconst byte* output_buffer::get_buffer() const \n{ \n return buffer_; \n}\n\n\n\/\/ allow write access through [], update current\n\/\/ user passes in AUTO as index for ease of use\nbyte& output_buffer::operator[](uint i) \n{\n check(current_, get_capacity());\n return buffer_[current_++];\n}\n\n\n\/\/ end of output test\nbool output_buffer::eof() \n{ \n return current_ >= get_capacity(); \n}\n\n\nvoid output_buffer::write(const byte* t, uint s)\n{\n check(current_ + s - 1, get_capacity()); \n memcpy(&buffer_[current_], t, s);\n current_ += s;\n}\n\n\n\n} \/\/ naemspace\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>\n\/\/\n\n#include \"RoutingInputWidget.h\"\n\n#include \"MarbleDebug.h\"\n#include \"MarbleLocale.h\"\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleRunnerManager.h\"\n#include \"RouteSkeleton.h\"\n#include \"TinyWebBrowser.h\"\n\n#include <QtCore\/QTimer>\n#include <QtCore\/QUrl>\n#include <QtGui\/QHBoxLayout>\n#include <QtGui\/QIcon>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QPushButton>\n#include <QtGui\/QMovie>\n#include <QtNetwork\/QNetworkAccessManager>\n#include <QtNetwork\/QNetworkReply>\n#include <QtXml\/QDomDocument>\n\nnamespace Marble\n{\n\nclass RoutingInputWidgetPrivate\n{\npublic:\n QPushButton *m_stateButton;\n\n QLineEdit *m_lineEdit;\n\n QPushButton *m_removeButton;\n\n QPushButton *m_pickButton;\n\n MarbleRunnerManager *m_runnerManager;\n\n MarblePlacemarkModel *m_placemarkModel;\n\n QMovie m_progress;\n\n QTimer m_progressTimer;\n\n RouteSkeleton *m_route;\n\n int m_index;\n\n QNetworkAccessManager *m_manager;\n\n QTimer m_nominatimTimer;\n\n bool m_workOffline;\n\n \/** Constructor *\/\n RoutingInputWidgetPrivate( RouteSkeleton *skeleton, int index, PluginManager* manager, QWidget *parent );\n\n \/** Initiate reverse geocoding request to download address *\/\n void adjustText();\n};\n\nRoutingInputWidgetPrivate::RoutingInputWidgetPrivate( RouteSkeleton *skeleton, int index, PluginManager* manager, QWidget *parent ) :\n m_lineEdit( 0 ), m_runnerManager( new MarbleRunnerManager( manager, parent ) ),\n m_placemarkModel( 0 ), m_progress( \":\/data\/bitmaps\/progress.mng\" ),\n m_route( skeleton ), m_index( index ), m_manager( new QNetworkAccessManager( parent ) ),\n m_workOffline( false )\n{\n m_stateButton = new QPushButton( parent );\n m_stateButton->setToolTip( \"Center Map here\" );\n m_stateButton->setVisible( false );\n m_stateButton->setIcon( QIcon( m_route->pixmap( m_index ) ) );\n m_stateButton->setFlat( true );\n m_stateButton->setMaximumWidth( 22 );\n m_stateButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\n\n m_lineEdit = new QLineEdit( parent );\n\n m_removeButton = new QPushButton( parent );\n m_removeButton->setIcon( QIcon( \":\/data\/bitmaps\/routing_remove.png\" ) );\n m_removeButton->setToolTip( \"Remove this position\" );\n m_removeButton->setFlat( true );\n m_removeButton->setMaximumWidth( 22 );\n\n m_pickButton = new QPushButton( parent );\n m_pickButton->setIcon( QIcon( m_route->pixmap( m_index ) ) );\n m_pickButton->setToolTip( \"Choose position from the map\" );\n m_pickButton->setCheckable( true );\n m_pickButton->setFlat( true );\n m_pickButton->setMaximumWidth( 22 );\n m_pickButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\n\n m_progressTimer.setInterval( 100 );\n m_nominatimTimer.setInterval( 1000 );\n m_nominatimTimer.setSingleShot( true );\n\n GeoDataCoordinates pos = m_route->at( m_index );\n if ( pos.longitude() != 0.0 && pos.latitude() != 0.0 ) {\n m_lineEdit->setText( pos.toString() );\n m_pickButton->setVisible( false );\n m_stateButton->setVisible( true );\n }\n}\n\nvoid RoutingInputWidgetPrivate::adjustText()\n{\n m_nominatimTimer.start();\n}\n\nRoutingInputWidget::RoutingInputWidget( RouteSkeleton *skeleton, int index, PluginManager* manager, QWidget *parent ) :\n QWidget( parent ), d( new RoutingInputWidgetPrivate( skeleton, index, manager, this ) )\n{\n QHBoxLayout *layout = new QHBoxLayout( this );\n layout->setSpacing( 0 );\n layout->setMargin( 0 );\n\n layout->addWidget( d->m_pickButton );\n layout->addWidget( d->m_stateButton );\n layout->addWidget( d->m_lineEdit );\n layout->addWidget( d->m_removeButton );\n\n connect( d->m_stateButton, SIGNAL( clicked() ),\n this, SLOT( requestActivity() ) );\n connect( d->m_pickButton, SIGNAL( clicked( bool ) ),\n this, SLOT( setMapInputModeEnabled( bool ) ) );\n connect( d->m_removeButton, SIGNAL( clicked() ),\n this, SLOT( requestRemoval() ) );\n\n connect( d->m_runnerManager, SIGNAL( searchResultChanged( MarblePlacemarkModel * ) ),\n this, SLOT( setPlacemarkModel( MarblePlacemarkModel * ) ) );\n connect( d->m_runnerManager, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark )),\n this, SLOT(retrieveReverseGeocodingResult( GeoDataCoordinates, GeoDataPlacemark ) ) );\n connect( d->m_lineEdit, SIGNAL( returnPressed() ),\n this, SLOT( findPlacemarks() ) );\n connect( d->m_lineEdit, SIGNAL( textChanged( QString ) ),\n this, SLOT( setInvalid() ) );\n connect( &d->m_progressTimer, SIGNAL( timeout() ),\n this, SLOT( updateProgress() ) );\n connect( d->m_runnerManager, SIGNAL( searchFinished( QString ) ),\n this, SLOT( finishSearch() ) );\n connect( skeleton, SIGNAL( positionChanged( int, GeoDataCoordinates ) ),\n this, SLOT( updatePosition( int, GeoDataCoordinates ) ) );\n connect( &d->m_nominatimTimer, SIGNAL( timeout() ),\n this, SLOT( reverseGeocoding() ) );\n\n d->adjustText();\n}\n\nRoutingInputWidget::~RoutingInputWidget()\n{\n delete d;\n}\n\nvoid RoutingInputWidget::reverseGeocoding()\n{\n if ( d->m_workOffline || !hasTargetPosition() ) {\n return;\n }\n\n d->m_runnerManager->reverseGeocoding( targetPosition() );\n}\n\nvoid RoutingInputWidget::setPlacemarkModel( MarblePlacemarkModel *model )\n{\n d->m_placemarkModel = model;\n}\n\nvoid RoutingInputWidget::setTargetPosition( const GeoDataCoordinates &position )\n{\n if ( !hasInput() || d->m_pickButton->isChecked() ) {\n d->m_lineEdit->setText( position.toString() );\n }\n\n d->m_pickButton->setVisible( false );\n d->m_route->setPosition( d->m_index, position );\n d->m_progressTimer.stop();\n d->m_stateButton->setVisible( true );\n d->m_stateButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n emit targetValidityChanged( true );\n}\n\nbool RoutingInputWidget::hasTargetPosition() const\n{\n GeoDataCoordinates pos = targetPosition();\n return pos.longitude() != 0.0 && pos.latitude() != 0.0;\n}\n\nGeoDataCoordinates RoutingInputWidget::targetPosition() const\n{\n return d->m_route->at( d->m_index );\n}\n\nvoid RoutingInputWidget::findPlacemarks()\n{\n QString text = d->m_lineEdit->text();\n if ( text.isEmpty() ) {\n setInvalid();\n } else {\n d->m_pickButton->setVisible( false );\n d->m_stateButton->setVisible( true );\n d->m_progressTimer.start();\n d->m_runnerManager->findPlacemarks( text );\n }\n}\n\nMarblePlacemarkModel *RoutingInputWidget::searchResultModel()\n{\n return d->m_placemarkModel;\n}\n\nvoid RoutingInputWidget::requestActivity()\n{\n if ( hasTargetPosition() ) {\n emit activityRequest( this );\n }\n}\n\nvoid RoutingInputWidget::requestRemoval()\n{\n emit removalRequest( this );\n}\n\nbool RoutingInputWidget::hasInput() const\n{\n return !d->m_lineEdit->text().isEmpty();\n}\n\nvoid RoutingInputWidget::setMapInputModeEnabled( bool enabled )\n{\n emit mapInputModeEnabled( this, enabled );\n}\n\nvoid RoutingInputWidget::updateProgress()\n{\n d->m_progress.jumpToNextFrame();\n QPixmap frame = d->m_progress.currentPixmap();\n d->m_stateButton->setIcon( frame );\n}\n\nvoid RoutingInputWidget::finishSearch()\n{\n d->m_progressTimer.stop();\n d->m_stateButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n d->m_pickButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n d->m_pickButton->setVisible( false );\n d->m_stateButton->setVisible( true );\n emit searchFinished( this );\n}\n\nvoid RoutingInputWidget::setInvalid()\n{\n if ( !hasTargetPosition() ) {\n emit targetValidityChanged( false );\n }\n}\n\nvoid RoutingInputWidget::abortMapInputRequest()\n{\n d->m_pickButton->setChecked( false );\n}\n\nvoid RoutingInputWidget::setIndex( int index )\n{\n d->m_index = index;\n d->m_stateButton->setVisible( hasTargetPosition() );\n d->m_stateButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n d->m_pickButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n}\n\nvoid RoutingInputWidget::updatePosition( int index, const GeoDataCoordinates &position )\n{\n if ( index == d->m_index ) {\n d->m_lineEdit->setText( position.toString() );\n d->m_stateButton->setVisible( hasTargetPosition() );\n d->m_stateButton->setIcon( d->m_route->pixmap( d->m_index ) );\n d->m_pickButton->setIcon( d->m_route->pixmap( d->m_index ) );\n emit targetValidityChanged( hasTargetPosition() );\n d->adjustText();\n }\n}\n\nvoid RoutingInputWidget::setWorkOffline( bool offline )\n{\n d->m_workOffline = offline;\n}\n\nvoid RoutingInputWidget::clear()\n{\n d->m_nominatimTimer.stop();\n d->m_progressTimer.stop();\n d->m_pickButton->setChecked( false );\n d->m_pickButton->setVisible( true );\n d->m_stateButton->setVisible( false );\n d->m_stateButton->setIcon( d->m_route->pixmap( d->m_index ) );\n d->m_route->setPosition( d->m_index, GeoDataCoordinates() );\n d->m_lineEdit->clear();\n emit targetValidityChanged( false );\n}\n\nvoid RoutingInputWidget::retrieveReverseGeocodingResult( const GeoDataCoordinates &, const GeoDataPlacemark &placemark )\n{\n d->m_lineEdit->setText( placemark.address() );\n d->m_lineEdit->setCursorPosition( 0 );\n}\n\n} \/\/ namespace Marble\n\n#include \"RoutingInputWidget.moc\"\n<commit_msg>Add tr() calls to tooltips. CCBUG: 246048<commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>\n\/\/\n\n#include \"RoutingInputWidget.h\"\n\n#include \"MarbleDebug.h\"\n#include \"MarbleLocale.h\"\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleRunnerManager.h\"\n#include \"RouteSkeleton.h\"\n#include \"TinyWebBrowser.h\"\n\n#include <QtCore\/QTimer>\n#include <QtCore\/QUrl>\n#include <QtGui\/QHBoxLayout>\n#include <QtGui\/QIcon>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QPushButton>\n#include <QtGui\/QMovie>\n#include <QtNetwork\/QNetworkAccessManager>\n#include <QtNetwork\/QNetworkReply>\n#include <QtXml\/QDomDocument>\n\nnamespace Marble\n{\n\nclass RoutingInputWidgetPrivate\n{\npublic:\n QPushButton *m_stateButton;\n\n QLineEdit *m_lineEdit;\n\n QPushButton *m_removeButton;\n\n QPushButton *m_pickButton;\n\n MarbleRunnerManager *m_runnerManager;\n\n MarblePlacemarkModel *m_placemarkModel;\n\n QMovie m_progress;\n\n QTimer m_progressTimer;\n\n RouteSkeleton *m_route;\n\n int m_index;\n\n QNetworkAccessManager *m_manager;\n\n QTimer m_nominatimTimer;\n\n bool m_workOffline;\n\n \/** Constructor *\/\n RoutingInputWidgetPrivate( RouteSkeleton *skeleton, int index, PluginManager* manager, QWidget *parent );\n\n \/** Initiate reverse geocoding request to download address *\/\n void adjustText();\n};\n\nRoutingInputWidgetPrivate::RoutingInputWidgetPrivate( RouteSkeleton *skeleton, int index, PluginManager* manager, QWidget *parent ) :\n m_lineEdit( 0 ), m_runnerManager( new MarbleRunnerManager( manager, parent ) ),\n m_placemarkModel( 0 ), m_progress( \":\/data\/bitmaps\/progress.mng\" ),\n m_route( skeleton ), m_index( index ), m_manager( new QNetworkAccessManager( parent ) ),\n m_workOffline( false )\n{\n m_stateButton = new QPushButton( parent );\n m_stateButton->setToolTip( QObject::tr( \"Center Map here\" ) );\n m_stateButton->setVisible( false );\n m_stateButton->setIcon( QIcon( m_route->pixmap( m_index ) ) );\n m_stateButton->setFlat( true );\n m_stateButton->setMaximumWidth( 22 );\n m_stateButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\n\n m_lineEdit = new QLineEdit( parent );\n\n m_removeButton = new QPushButton( parent );\n m_removeButton->setIcon( QIcon( \":\/data\/bitmaps\/routing_remove.png\" ) );\n m_removeButton->setToolTip( QObject::tr( \"Remove this position\" ) );\n m_removeButton->setFlat( true );\n m_removeButton->setMaximumWidth( 22 );\n\n m_pickButton = new QPushButton( parent );\n m_pickButton->setIcon( QIcon( m_route->pixmap( m_index ) ) );\n m_pickButton->setToolTip( QObject::tr( \"Choose position from the map\" ) );\n m_pickButton->setCheckable( true );\n m_pickButton->setFlat( true );\n m_pickButton->setMaximumWidth( 22 );\n m_pickButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\n\n m_progressTimer.setInterval( 100 );\n m_nominatimTimer.setInterval( 1000 );\n m_nominatimTimer.setSingleShot( true );\n\n GeoDataCoordinates pos = m_route->at( m_index );\n if ( pos.longitude() != 0.0 && pos.latitude() != 0.0 ) {\n m_lineEdit->setText( pos.toString() );\n m_pickButton->setVisible( false );\n m_stateButton->setVisible( true );\n }\n}\n\nvoid RoutingInputWidgetPrivate::adjustText()\n{\n m_nominatimTimer.start();\n}\n\nRoutingInputWidget::RoutingInputWidget( RouteSkeleton *skeleton, int index, PluginManager* manager, QWidget *parent ) :\n QWidget( parent ), d( new RoutingInputWidgetPrivate( skeleton, index, manager, this ) )\n{\n QHBoxLayout *layout = new QHBoxLayout( this );\n layout->setSpacing( 0 );\n layout->setMargin( 0 );\n\n layout->addWidget( d->m_pickButton );\n layout->addWidget( d->m_stateButton );\n layout->addWidget( d->m_lineEdit );\n layout->addWidget( d->m_removeButton );\n\n connect( d->m_stateButton, SIGNAL( clicked() ),\n this, SLOT( requestActivity() ) );\n connect( d->m_pickButton, SIGNAL( clicked( bool ) ),\n this, SLOT( setMapInputModeEnabled( bool ) ) );\n connect( d->m_removeButton, SIGNAL( clicked() ),\n this, SLOT( requestRemoval() ) );\n\n connect( d->m_runnerManager, SIGNAL( searchResultChanged( MarblePlacemarkModel * ) ),\n this, SLOT( setPlacemarkModel( MarblePlacemarkModel * ) ) );\n connect( d->m_runnerManager, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark )),\n this, SLOT(retrieveReverseGeocodingResult( GeoDataCoordinates, GeoDataPlacemark ) ) );\n connect( d->m_lineEdit, SIGNAL( returnPressed() ),\n this, SLOT( findPlacemarks() ) );\n connect( d->m_lineEdit, SIGNAL( textChanged( QString ) ),\n this, SLOT( setInvalid() ) );\n connect( &d->m_progressTimer, SIGNAL( timeout() ),\n this, SLOT( updateProgress() ) );\n connect( d->m_runnerManager, SIGNAL( searchFinished( QString ) ),\n this, SLOT( finishSearch() ) );\n connect( skeleton, SIGNAL( positionChanged( int, GeoDataCoordinates ) ),\n this, SLOT( updatePosition( int, GeoDataCoordinates ) ) );\n connect( &d->m_nominatimTimer, SIGNAL( timeout() ),\n this, SLOT( reverseGeocoding() ) );\n\n d->adjustText();\n}\n\nRoutingInputWidget::~RoutingInputWidget()\n{\n delete d;\n}\n\nvoid RoutingInputWidget::reverseGeocoding()\n{\n if ( d->m_workOffline || !hasTargetPosition() ) {\n return;\n }\n\n d->m_runnerManager->reverseGeocoding( targetPosition() );\n}\n\nvoid RoutingInputWidget::setPlacemarkModel( MarblePlacemarkModel *model )\n{\n d->m_placemarkModel = model;\n}\n\nvoid RoutingInputWidget::setTargetPosition( const GeoDataCoordinates &position )\n{\n if ( !hasInput() || d->m_pickButton->isChecked() ) {\n d->m_lineEdit->setText( position.toString() );\n }\n\n d->m_pickButton->setVisible( false );\n d->m_route->setPosition( d->m_index, position );\n d->m_progressTimer.stop();\n d->m_stateButton->setVisible( true );\n d->m_stateButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n emit targetValidityChanged( true );\n}\n\nbool RoutingInputWidget::hasTargetPosition() const\n{\n GeoDataCoordinates pos = targetPosition();\n return pos.longitude() != 0.0 && pos.latitude() != 0.0;\n}\n\nGeoDataCoordinates RoutingInputWidget::targetPosition() const\n{\n return d->m_route->at( d->m_index );\n}\n\nvoid RoutingInputWidget::findPlacemarks()\n{\n QString text = d->m_lineEdit->text();\n if ( text.isEmpty() ) {\n setInvalid();\n } else {\n d->m_pickButton->setVisible( false );\n d->m_stateButton->setVisible( true );\n d->m_progressTimer.start();\n d->m_runnerManager->findPlacemarks( text );\n }\n}\n\nMarblePlacemarkModel *RoutingInputWidget::searchResultModel()\n{\n return d->m_placemarkModel;\n}\n\nvoid RoutingInputWidget::requestActivity()\n{\n if ( hasTargetPosition() ) {\n emit activityRequest( this );\n }\n}\n\nvoid RoutingInputWidget::requestRemoval()\n{\n emit removalRequest( this );\n}\n\nbool RoutingInputWidget::hasInput() const\n{\n return !d->m_lineEdit->text().isEmpty();\n}\n\nvoid RoutingInputWidget::setMapInputModeEnabled( bool enabled )\n{\n emit mapInputModeEnabled( this, enabled );\n}\n\nvoid RoutingInputWidget::updateProgress()\n{\n d->m_progress.jumpToNextFrame();\n QPixmap frame = d->m_progress.currentPixmap();\n d->m_stateButton->setIcon( frame );\n}\n\nvoid RoutingInputWidget::finishSearch()\n{\n d->m_progressTimer.stop();\n d->m_stateButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n d->m_pickButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n d->m_pickButton->setVisible( false );\n d->m_stateButton->setVisible( true );\n emit searchFinished( this );\n}\n\nvoid RoutingInputWidget::setInvalid()\n{\n if ( !hasTargetPosition() ) {\n emit targetValidityChanged( false );\n }\n}\n\nvoid RoutingInputWidget::abortMapInputRequest()\n{\n d->m_pickButton->setChecked( false );\n}\n\nvoid RoutingInputWidget::setIndex( int index )\n{\n d->m_index = index;\n d->m_stateButton->setVisible( hasTargetPosition() );\n d->m_stateButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n d->m_pickButton->setIcon( QIcon( d->m_route->pixmap( d->m_index ) ) );\n}\n\nvoid RoutingInputWidget::updatePosition( int index, const GeoDataCoordinates &position )\n{\n if ( index == d->m_index ) {\n d->m_lineEdit->setText( position.toString() );\n d->m_stateButton->setVisible( hasTargetPosition() );\n d->m_stateButton->setIcon( d->m_route->pixmap( d->m_index ) );\n d->m_pickButton->setIcon( d->m_route->pixmap( d->m_index ) );\n emit targetValidityChanged( hasTargetPosition() );\n d->adjustText();\n }\n}\n\nvoid RoutingInputWidget::setWorkOffline( bool offline )\n{\n d->m_workOffline = offline;\n}\n\nvoid RoutingInputWidget::clear()\n{\n d->m_nominatimTimer.stop();\n d->m_progressTimer.stop();\n d->m_pickButton->setChecked( false );\n d->m_pickButton->setVisible( true );\n d->m_stateButton->setVisible( false );\n d->m_stateButton->setIcon( d->m_route->pixmap( d->m_index ) );\n d->m_route->setPosition( d->m_index, GeoDataCoordinates() );\n d->m_lineEdit->clear();\n emit targetValidityChanged( false );\n}\n\nvoid RoutingInputWidget::retrieveReverseGeocodingResult( const GeoDataCoordinates &, const GeoDataPlacemark &placemark )\n{\n d->m_lineEdit->setText( placemark.address() );\n d->m_lineEdit->setCursorPosition( 0 );\n}\n\n} \/\/ namespace Marble\n\n#include \"RoutingInputWidget.moc\"\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <geneial\/core\/operations\/crossover\/MultiValuePermutationCrossover.h>\n#include <geneial\/utility\/Random.h>\n\ngeneial_private_namespace(geneial)\n{\ngeneial_private_namespace(operation)\n{\ngeneial_private_namespace(crossover)\n{\nusing ::geneial::population::Population;\nusing ::geneial::population::chromosome::MultiValueChromosome;\nusing ::geneial::operation::coupling::BaseCouplingOperation;\nusing ::geneial::utility::Random;\n\nenum COPY_MODE\n{\n\tCOPY_LEFT_PART,\n\tCOPY_RIGHT_PART\n};\n\ntemplate<typename VALUE_TYPE, typename FITNESS_TYPE>\nvoid copyContainerPart(const typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::value_container& source,\n\t\t\t\t\t typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::value_container& dest,\n\t\t\t\t\t COPY_MODE mode,\n\t\t\t\t\t const unsigned int separator\n)\n{\n\tassert(separator < source.size());\n\tassert(separator >= 0);\n\tassert(separator < dest.size());\n\n\tif(mode == COPY_MODE::COPY_LEFT_PART)\n\t{\n\t\tstd::copy(source.begin() , source.begin() + separator + 1, dest.begin());\n\t}\n\telse \/\/RIGHT PART\n\t{\n\t\tstd::copy(source.begin() + separator , source.end(), dest.begin() + separator);\n\t}\n}\n\ntemplate<typename VALUE_TYPE, typename FITNESS_TYPE>\nvoid copyRemainder(const typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::value_container& source,\n\t\t\t\t typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::value_container& dest,\n\t\t\t\t COPY_MODE alreadyCopied,\n\t\t\t\t const unsigned int separator)\n{\n\tif(alreadyCopied == COPY_MODE::COPY_LEFT_PART)\n\t{\n\t\t\/\/We need to copy everything to begin() --> end() from source\n\t\t\/\/Values already present are in begin() --> begin() + separator of dest\n\t\tunsigned int nextSourcePos = 0;\n\t\tfor(unsigned int nextCopyPos = separator + 1; nextCopyPos < dest.size(); nextCopyPos ++)\n\t\t{\n\t\t\t\/\/Find a value that we can copy.\n\t\t\tfor(; nextSourcePos < source.size();nextSourcePos++)\n\t\t\t{\n\t\t\t\t\/\/Do we have this value already?\n\t\t\t\tif(std::find( dest.begin(), dest.begin() + nextCopyPos, source[nextSourcePos]) != dest.begin() + nextCopyPos)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdest[nextCopyPos] = source[nextSourcePos];\n\t\t\tnextSourcePos++;\n\t\t}\n\t}\n\telse \/\/ Right Part was copied\n\t{\n\t\t\/\/We need to copy everything to begin() --> end() from source what is not contained in dest\n\t\t\/\/Values already present are in begin() + separator --> end() separator of dest\n\t\tunsigned int nextSourcePos = 0;\n\t\tfor(int nextCopyPos = separator -1 ; nextCopyPos >= 0; nextCopyPos --)\n\t\t{\n\t\t\t\/\/Find a value that we can copy.\n\t\t\tfor(; nextSourcePos < source.size();nextSourcePos++)\n\t\t\t{\n\t\t\t\t\/\/Do we have this value already?\n\t\t\t\tif(std::find( dest.begin()+nextCopyPos + 1, dest.end(), source[nextSourcePos]) != dest.end())\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdest[nextCopyPos] = source[nextSourcePos];\n\t\t\tnextSourcePos++;\n\t\t}\n\t}\n}\n\ngeneial_export_namespace\n{\n\ntemplate<typename VALUE_TYPE, typename FITNESS_TYPE>\ntypename BaseCrossoverOperation<FITNESS_TYPE>::crossover_result_set MultiValuePermutationCrossover<VALUE_TYPE,\n FITNESS_TYPE>::doMultiValueCrossover(\n const typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::const_ptr &mommy,\n const typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::const_ptr &daddy) const\n{\n\n typename BaseCouplingOperation<FITNESS_TYPE>::offspring_result_set resultset;\n\n auto child_candidate = this->createChildCandidate();\n\n const auto &daddy_container = daddy->getContainer();\n const auto &mommy_container = mommy->getContainer();\n\n auto &child_container = child_candidate->getContainer();\n\n assert(daddy_container.size() == mommy_container.size());\n\n COPY_MODE copyMode = Random::generateBit() ? COPY_MODE::COPY_LEFT_PART : COPY_MODE::COPY_RIGHT_PART;\n auto startWithMommy = Random::generateBit();\n const unsigned int where = Random::generate<int>(0, daddy_container.size() -1 );\n\n child_container.resize(daddy_container.size(),0);\n\n\n copyContainerPart<VALUE_TYPE,FITNESS_TYPE>(startWithMommy?mommy_container:daddy_container, child_container, copyMode, where);\n copyRemainder<VALUE_TYPE,FITNESS_TYPE>(startWithMommy?daddy_container:mommy_container, child_container, copyMode, where);\n\n assert(std::accumulate(child_container.begin(),child_container.end(),0) == 6);\n\n \/\/Now some parts of the container have elements of mommy\/daddy.\n \/\/Next we need to fill up the gap with\n\n\n resultset.emplace_back(std::move(child_candidate));\n return std::move(resultset);\n}\n\n} \/* geneial_export_namespace *\/\n} \/* private namespace crossover *\/\n} \/* private namespace operation *\/\n} \/* private namespace geneial *\/\n\n<commit_msg>remove debugging assertion<commit_after>#pragma once\n\n#include <geneial\/core\/operations\/crossover\/MultiValuePermutationCrossover.h>\n#include <geneial\/utility\/Random.h>\n\ngeneial_private_namespace(geneial)\n{\ngeneial_private_namespace(operation)\n{\ngeneial_private_namespace(crossover)\n{\nusing ::geneial::population::Population;\nusing ::geneial::population::chromosome::MultiValueChromosome;\nusing ::geneial::operation::coupling::BaseCouplingOperation;\nusing ::geneial::utility::Random;\n\nenum COPY_MODE\n{\n\tCOPY_LEFT_PART,\n\tCOPY_RIGHT_PART\n};\n\ntemplate<typename VALUE_TYPE, typename FITNESS_TYPE>\nvoid copyContainerPart(const typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::value_container& source,\n\t\t\t\t\t typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::value_container& dest,\n\t\t\t\t\t COPY_MODE mode,\n\t\t\t\t\t const unsigned int separator\n)\n{\n\tassert(separator < source.size());\n\tassert(separator >= 0);\n\tassert(separator < dest.size());\n\n\tif(mode == COPY_MODE::COPY_LEFT_PART)\n\t{\n\t\tstd::copy(source.begin() , source.begin() + separator + 1, dest.begin());\n\t}\n\telse \/\/RIGHT PART\n\t{\n\t\tstd::copy(source.begin() + separator , source.end(), dest.begin() + separator);\n\t}\n}\n\ntemplate<typename VALUE_TYPE, typename FITNESS_TYPE>\nvoid copyRemainder(const typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::value_container& source,\n\t\t\t\t typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::value_container& dest,\n\t\t\t\t COPY_MODE alreadyCopied,\n\t\t\t\t const unsigned int separator)\n{\n\tif(alreadyCopied == COPY_MODE::COPY_LEFT_PART)\n\t{\n\t\t\/\/We need to copy everything to begin() --> end() from source\n\t\t\/\/Values already present are in begin() --> begin() + separator of dest\n\t\tunsigned int nextSourcePos = 0;\n\t\tfor(unsigned int nextCopyPos = separator + 1; nextCopyPos < dest.size(); nextCopyPos ++)\n\t\t{\n\t\t\t\/\/Find a value that we can copy.\n\t\t\tfor(; nextSourcePos < source.size();nextSourcePos++)\n\t\t\t{\n\t\t\t\t\/\/Do we have this value already?\n\t\t\t\tif(std::find( dest.begin(), dest.begin() + nextCopyPos, source[nextSourcePos]) != dest.begin() + nextCopyPos)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdest[nextCopyPos] = source[nextSourcePos];\n\t\t\tnextSourcePos++;\n\t\t}\n\t}\n\telse \/\/ Right Part was copied\n\t{\n\t\t\/\/We need to copy everything to begin() --> end() from source what is not contained in dest\n\t\t\/\/Values already present are in begin() + separator --> end() separator of dest\n\t\tunsigned int nextSourcePos = 0;\n\t\tfor(int nextCopyPos = separator -1 ; nextCopyPos >= 0; nextCopyPos --)\n\t\t{\n\t\t\t\/\/Find a value that we can copy.\n\t\t\tfor(; nextSourcePos < source.size();nextSourcePos++)\n\t\t\t{\n\t\t\t\t\/\/Do we have this value already?\n\t\t\t\tif(std::find( dest.begin()+nextCopyPos + 1, dest.end(), source[nextSourcePos]) != dest.end())\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdest[nextCopyPos] = source[nextSourcePos];\n\t\t\tnextSourcePos++;\n\t\t}\n\t}\n}\n\ngeneial_export_namespace\n{\n\ntemplate<typename VALUE_TYPE, typename FITNESS_TYPE>\ntypename BaseCrossoverOperation<FITNESS_TYPE>::crossover_result_set MultiValuePermutationCrossover<VALUE_TYPE,\n FITNESS_TYPE>::doMultiValueCrossover(\n const typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::const_ptr &mommy,\n const typename MultiValueChromosome<VALUE_TYPE, FITNESS_TYPE>::const_ptr &daddy) const\n{\n\n typename BaseCouplingOperation<FITNESS_TYPE>::offspring_result_set resultset;\n\n auto child_candidate = this->createChildCandidate();\n\n const auto &daddy_container = daddy->getContainer();\n const auto &mommy_container = mommy->getContainer();\n\n auto &child_container = child_candidate->getContainer();\n\n assert(daddy_container.size() == mommy_container.size());\n\n COPY_MODE copyMode = Random::generateBit() ? COPY_MODE::COPY_LEFT_PART : COPY_MODE::COPY_RIGHT_PART;\n auto startWithMommy = Random::generateBit();\n const unsigned int where = Random::generate<int>(0, daddy_container.size() -1 );\n\n child_container.resize(daddy_container.size(),0);\n\n\n copyContainerPart<VALUE_TYPE,FITNESS_TYPE>(startWithMommy?mommy_container:daddy_container, child_container, copyMode, where);\n copyRemainder<VALUE_TYPE,FITNESS_TYPE>(startWithMommy?daddy_container:mommy_container, child_container, copyMode, where);\n\n \/\/Now some parts of the container have elements of mommy\/daddy.\n \/\/Next we need to fill up the gap with\n\n\n resultset.emplace_back(std::move(child_candidate));\n return std::move(resultset);\n}\n\n} \/* geneial_export_namespace *\/\n} \/* private namespace crossover *\/\n} \/* private namespace operation *\/\n} \/* private namespace geneial *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix mistake in the supports_expression macro.<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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#ifndef __MESOS_CONTAINERIZER_HPP__\n#define __MESOS_CONTAINERIZER_HPP__\n\n#include <list>\n#include <vector>\n\n#include <stout\/hashmap.hpp>\n#include <stout\/multihashmap.hpp>\n\n#include \"slave\/containerizer\/containerizer.hpp\"\n#include \"slave\/containerizer\/isolator.hpp\"\n#include \"slave\/containerizer\/launcher.hpp\"\n\nnamespace mesos {\nnamespace internal {\nnamespace slave {\n\n\/\/ Forward declaration.\nclass MesosContainerizerProcess;\n\nclass MesosContainerizer : public Containerizer\n{\npublic:\n static Try<MesosContainerizer*> create(\n const Flags& flags,\n bool local,\n Fetcher* fetcher);\n\n MesosContainerizer(\n const Flags& flags,\n bool local,\n Fetcher* fetcher,\n const process::Owned<Launcher>& launcher,\n const std::vector<process::Owned<Isolator>>& isolators);\n\n \/\/ Used for testing.\n MesosContainerizer(const process::Owned<MesosContainerizerProcess>& _process);\n\n virtual ~MesosContainerizer();\n\n virtual process::Future<Nothing> recover(\n const Option<state::SlaveState>& state);\n\n virtual process::Future<bool> launch(\n const ContainerID& containerId,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint);\n\n virtual process::Future<bool> launch(\n const ContainerID& containerId,\n const TaskInfo& taskInfo,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint);\n\n virtual process::Future<Nothing> update(\n const ContainerID& containerId,\n const Resources& resources);\n\n virtual process::Future<ResourceStatistics> usage(\n const ContainerID& containerId);\n\n virtual process::Future<containerizer::Termination> wait(\n const ContainerID& containerId);\n\n virtual void destroy(const ContainerID& containerId);\n\n virtual process::Future<hashset<ContainerID>> containers();\n\nprivate:\n process::Owned<MesosContainerizerProcess> process;\n};\n\n\nclass MesosContainerizerProcess\n : public process::Process<MesosContainerizerProcess>\n{\npublic:\n MesosContainerizerProcess(\n const Flags& _flags,\n bool _local,\n Fetcher* _fetcher,\n const process::Owned<Launcher>& _launcher,\n const std::vector<process::Owned<Isolator>>& _isolators)\n : flags(_flags),\n local(_local),\n fetcher(_fetcher),\n launcher(_launcher),\n isolators(_isolators) {}\n\n virtual ~MesosContainerizerProcess() {}\n\n virtual process::Future<Nothing> recover(\n const Option<state::SlaveState>& state);\n\n virtual process::Future<bool> launch(\n const ContainerID& containerId,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint);\n\n virtual process::Future<bool> launch(\n const ContainerID& containerId,\n const TaskInfo& taskInfo,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint);\n\n virtual process::Future<Nothing> update(\n const ContainerID& containerId,\n const Resources& resources);\n\n virtual process::Future<ResourceStatistics> usage(\n const ContainerID& containerId);\n\n virtual process::Future<containerizer::Termination> wait(\n const ContainerID& containerId);\n\n virtual process::Future<bool> exec(\n const ContainerID& containerId,\n int pipeWrite);\n\n virtual void destroy(const ContainerID& containerId);\n\n virtual process::Future<hashset<ContainerID>> containers();\n\nprivate:\n process::Future<Nothing> _recover(\n const std::list<state::RunState>& recoverable);\n\n process::Future<Nothing> __recover(\n const std::list<state::RunState>& recovered);\n\n process::Future<std::list<Option<CommandInfo>>> prepare(\n const ContainerID& containerId,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user);\n\n process::Future<Nothing> fetch(\n const ContainerID& containerId,\n const CommandInfo& commandInfo,\n const std::string& directory,\n const Option<std::string>& user);\n\n process::Future<bool> _launch(\n const ContainerID& containerId,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint,\n const std::list<Option<CommandInfo>>& scripts);\n\n process::Future<bool> isolate(\n const ContainerID& containerId,\n pid_t _pid);\n\n \/\/ Continues 'destroy()' once isolators has completed.\n void _destroy(const ContainerID& containerId);\n\n \/\/ Continues 'destroy()' once all processes have been killed by the launcher.\n void __destroy(\n const ContainerID& containerId,\n const process::Future<Nothing>& future);\n\n \/\/ Continues '_destroy()' once we get the exit status of the executor.\n void ___destroy(\n const ContainerID& containerId,\n const process::Future<Option<int>>& status);\n\n \/\/ Continues (and completes) '__destroy()' once all isolators have completed\n \/\/ cleanup.\n void ____destroy(\n const ContainerID& containerId,\n const process::Future<Option<int>>& status,\n const process::Future<std::list<process::Future<Nothing>>>& cleanups);\n\n \/\/ Call back for when an isolator limits a container and impacts the\n \/\/ processes. This will trigger container destruction.\n void limited(\n const ContainerID& containerId,\n const process::Future<Limitation>& future);\n\n \/\/ Call back for when the executor exits. This will trigger container\n \/\/ destroy.\n void reaped(const ContainerID& containerId);\n\n const Flags flags;\n const bool local;\n Fetcher* fetcher;\n const process::Owned<Launcher> launcher;\n const std::vector<process::Owned<Isolator>> isolators;\n\n enum State\n {\n PREPARING,\n ISOLATING,\n FETCHING,\n RUNNING,\n DESTROYING\n };\n\n struct Container\n {\n \/\/ Promise for futures returned from wait().\n process::Promise<containerizer::Termination> promise;\n\n \/\/ We need to keep track of the future exit status for each\n \/\/ executor because we'll only get a single notification when\n \/\/ the executor exits.\n process::Future<Option<int>> status;\n\n \/\/ We keep track of the future that is waiting for all the\n \/\/ isolator's futures, so that destroy will only start calling\n \/\/ cleanup after all isolators has finished isolating.\n process::Future<std::list<Nothing>> isolation;\n\n \/\/ We keep track of any limitations received from each isolator so we can\n \/\/ determine the cause of an executor termination.\n std::vector<Limitation> limitations;\n\n \/\/ We keep track of the resources for each container so we can set the\n \/\/ ResourceStatistics limits in usage().\n Resources resources;\n\n State state;\n };\n\n hashmap<ContainerID, process::Owned<Container>> containers_;\n};\n\n} \/\/ namespace slave {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n#endif \/\/ __MESOS_CONTAINERIZER_HPP__\n<commit_msg>Add an optional container rootfs for MesosContainerizer.<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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#ifndef __MESOS_CONTAINERIZER_HPP__\n#define __MESOS_CONTAINERIZER_HPP__\n\n#include <list>\n#include <vector>\n\n#include <stout\/hashmap.hpp>\n#include <stout\/multihashmap.hpp>\n\n#include \"slave\/containerizer\/containerizer.hpp\"\n#include \"slave\/containerizer\/isolator.hpp\"\n#include \"slave\/containerizer\/launcher.hpp\"\n\nnamespace mesos {\nnamespace internal {\nnamespace slave {\n\n\/\/ Forward declaration.\nclass MesosContainerizerProcess;\n\nclass MesosContainerizer : public Containerizer\n{\npublic:\n static Try<MesosContainerizer*> create(\n const Flags& flags,\n bool local,\n Fetcher* fetcher);\n\n MesosContainerizer(\n const Flags& flags,\n bool local,\n Fetcher* fetcher,\n const process::Owned<Launcher>& launcher,\n const std::vector<process::Owned<Isolator>>& isolators);\n\n \/\/ Used for testing.\n MesosContainerizer(const process::Owned<MesosContainerizerProcess>& _process);\n\n virtual ~MesosContainerizer();\n\n virtual process::Future<Nothing> recover(\n const Option<state::SlaveState>& state);\n\n virtual process::Future<bool> launch(\n const ContainerID& containerId,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint);\n\n virtual process::Future<bool> launch(\n const ContainerID& containerId,\n const TaskInfo& taskInfo,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint);\n\n virtual process::Future<Nothing> update(\n const ContainerID& containerId,\n const Resources& resources);\n\n virtual process::Future<ResourceStatistics> usage(\n const ContainerID& containerId);\n\n virtual process::Future<containerizer::Termination> wait(\n const ContainerID& containerId);\n\n virtual void destroy(const ContainerID& containerId);\n\n virtual process::Future<hashset<ContainerID>> containers();\n\nprivate:\n process::Owned<MesosContainerizerProcess> process;\n};\n\n\nclass MesosContainerizerProcess\n : public process::Process<MesosContainerizerProcess>\n{\npublic:\n MesosContainerizerProcess(\n const Flags& _flags,\n bool _local,\n Fetcher* _fetcher,\n const process::Owned<Launcher>& _launcher,\n const std::vector<process::Owned<Isolator>>& _isolators)\n : flags(_flags),\n local(_local),\n fetcher(_fetcher),\n launcher(_launcher),\n isolators(_isolators) {}\n\n virtual ~MesosContainerizerProcess() {}\n\n virtual process::Future<Nothing> recover(\n const Option<state::SlaveState>& state);\n\n virtual process::Future<bool> launch(\n const ContainerID& containerId,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint);\n\n virtual process::Future<bool> launch(\n const ContainerID& containerId,\n const TaskInfo& taskInfo,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint);\n\n virtual process::Future<Nothing> update(\n const ContainerID& containerId,\n const Resources& resources);\n\n virtual process::Future<ResourceStatistics> usage(\n const ContainerID& containerId);\n\n virtual process::Future<containerizer::Termination> wait(\n const ContainerID& containerId);\n\n virtual process::Future<bool> exec(\n const ContainerID& containerId,\n int pipeWrite);\n\n virtual void destroy(const ContainerID& containerId);\n\n virtual process::Future<hashset<ContainerID>> containers();\n\nprivate:\n process::Future<Nothing> _recover(\n const std::list<state::RunState>& recoverable);\n\n process::Future<Nothing> __recover(\n const std::list<state::RunState>& recovered);\n\n process::Future<std::list<Option<CommandInfo>>> prepare(\n const ContainerID& containerId,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user);\n\n process::Future<Nothing> fetch(\n const ContainerID& containerId,\n const CommandInfo& commandInfo,\n const std::string& directory,\n const Option<std::string>& user);\n\n process::Future<bool> _launch(\n const ContainerID& containerId,\n const ExecutorInfo& executorInfo,\n const std::string& directory,\n const Option<std::string>& user,\n const SlaveID& slaveId,\n const process::PID<Slave>& slavePid,\n bool checkpoint,\n const std::list<Option<CommandInfo>>& scripts);\n\n process::Future<bool> isolate(\n const ContainerID& containerId,\n pid_t _pid);\n\n \/\/ Continues 'destroy()' once isolators has completed.\n void _destroy(const ContainerID& containerId);\n\n \/\/ Continues 'destroy()' once all processes have been killed by the launcher.\n void __destroy(\n const ContainerID& containerId,\n const process::Future<Nothing>& future);\n\n \/\/ Continues '_destroy()' once we get the exit status of the executor.\n void ___destroy(\n const ContainerID& containerId,\n const process::Future<Option<int>>& status);\n\n \/\/ Continues (and completes) '__destroy()' once all isolators have completed\n \/\/ cleanup.\n void ____destroy(\n const ContainerID& containerId,\n const process::Future<Option<int>>& status,\n const process::Future<std::list<process::Future<Nothing>>>& cleanups);\n\n \/\/ Call back for when an isolator limits a container and impacts the\n \/\/ processes. This will trigger container destruction.\n void limited(\n const ContainerID& containerId,\n const process::Future<Limitation>& future);\n\n \/\/ Call back for when the executor exits. This will trigger container\n \/\/ destroy.\n void reaped(const ContainerID& containerId);\n\n const Flags flags;\n const bool local;\n Fetcher* fetcher;\n const process::Owned<Launcher> launcher;\n const std::vector<process::Owned<Isolator>> isolators;\n\n enum State\n {\n PREPARING,\n ISOLATING,\n FETCHING,\n RUNNING,\n DESTROYING\n };\n\n struct Container\n {\n \/\/ Promise for futures returned from wait().\n process::Promise<containerizer::Termination> promise;\n\n \/\/ We need to keep track of the future exit status for each\n \/\/ executor because we'll only get a single notification when\n \/\/ the executor exits.\n process::Future<Option<int>> status;\n\n \/\/ We keep track of the future that is waiting for all the\n \/\/ isolator's futures, so that destroy will only start calling\n \/\/ cleanup after all isolators has finished isolating.\n process::Future<std::list<Nothing>> isolation;\n\n \/\/ We keep track of any limitations received from each isolator so we can\n \/\/ determine the cause of an executor termination.\n std::vector<Limitation> limitations;\n\n \/\/ We keep track of the resources for each container so we can set the\n \/\/ ResourceStatistics limits in usage().\n Resources resources;\n\n \/\/ The path to the container's rootfs, if full filesystem\n \/\/ isolation is used.\n Option<std::string> rootfs;\n\n State state;\n };\n\n hashmap<ContainerID, process::Owned<Container>> containers_;\n};\n\n} \/\/ namespace slave {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n#endif \/\/ __MESOS_CONTAINERIZER_HPP__\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n Copyright 2019 Allied Telesis Labs Ltd. All rights reserved.\n \nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. 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\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 OWNER 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#include <buildsys.h>\n\nstatic bool directory_exists(const std::string & dir)\n{\n\tif(!filesystem::exists(dir)) {\n\t\t\/* Nothing here *\/\n\t\treturn false;\n\t} else if(buildsys::filesystem::is_directory(dir)) {\n\t\t\/* Actually a directory *\/\n\t\treturn true;\n\t}\n\t\/* Something other than a directory *\/\n\treturn false;\n}\n\nstatic bool refspec_is_commitid(const std::string & refspec)\n{\n\tif(refspec.length() != 40) {\n\t\treturn false;\n\t}\n\n\tfor(char const &c:refspec) {\n\t\tif(!isxdigit(c)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstatic std::string git_hash_ref(const std::string & gdir, const std::string & refspec)\n{\n\tstd::string cmd = string_format(\"cd %s && git rev-parse %s\", gdir.c_str(),\n\t\t\t\t\trefspec.c_str());\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == NULL) {\n\t\tthrow CustomException(\"git rev-parse ref failed\");\n\t}\n\tchar *commit = (char *) calloc(41, sizeof(char));\n\tfread(commit, sizeof(char), 40, f);\n\tpclose(f);\n\n\tstd::string ret = std::string(commit);\n\tfree(commit);\n\n\treturn ret;\n}\n\nstatic std::string git_hash(const std::string & gdir)\n{\n\treturn git_hash_ref(gdir, \"HEAD\");\n}\n\nstatic std::string git_diff_hash(const std::string & gdir)\n{\n\tstd::string cmd = string_format(\"cd %s && git diff HEAD | sha1sum\", gdir.c_str());\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == NULL) {\n\t\tthrow CustomException(\"git diff | sha1sum failed\");\n\t}\n\tchar *delta_hash = (char *) calloc(41, sizeof(char));\n\tfread(delta_hash, sizeof(char), 40, f);\n\tpclose(f);\n\tstd::string ret(delta_hash);\n\tfree(delta_hash);\n\treturn ret;\n}\n\nstatic std::string git_remote(const std::string & gdir, const std::string & remote)\n{\n\tstd::string cmd = string_format(\"cd %s && git config --local --get remote.%s.url\",\n\t\t\t\t\tgdir.c_str(), remote.c_str());\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == NULL) {\n\t\tthrow CustomException(\"git config --local --get remote. .url failed\");\n\t}\n\tchar *Remote = (char *) calloc(1025, sizeof(char));\n\tfread(Remote, sizeof(char), 1024, f);\n\tpclose(f);\n\tstd::string ret(Remote);\n\tfree(Remote);\n\treturn ret;\n}\n\nGitDirExtractionUnit::GitDirExtractionUnit(const std::string & git_dir,\n\t\t\t\t\t const std::string & to_dir)\n{\n\tthis->uri = git_dir;\n\tthis->hash = git_hash(this->uri);\n\tthis->toDir = to_dir;\n}\n\nGitDirExtractionUnit::GitDirExtractionUnit()\n{\n}\n\nbool GitDirExtractionUnit::isDirty()\n{\n\tif(!directory_exists(this->localPath())) {\n\t\t\/* If the source directory doesn't exist, then it can't be dirty *\/\n\t\treturn false;\n\t}\n\n\tstd::string cmd = string_format(\"cd %s && git diff --quiet HEAD\",\n\t\t\t\t\tthis->localPath().c_str());\n\tint res = std::system(cmd.c_str());\n\treturn (res != 0);\n}\n\nstd::string GitDirExtractionUnit::dirtyHash()\n{\n\treturn git_diff_hash(this->localPath());\n}\n\nGitExtractionUnit::GitExtractionUnit(const std::string & remote, const std::string & local,\n\t\t\t\t std::string refspec, Package * P)\n{\n\tthis->uri = remote;\n\tthis->local = P->getWorld()->getWorkingDir() + \"\/source\/\" + local;\n\tthis->refspec = refspec;\n\tthis->P = P;\n\tthis->fetched = false;\n}\n\nbool GitExtractionUnit::updateOrigin()\n{\n\tstd::string location = this->uri;\n\tstd::string source_dir = this->local;\n\tstd::string remote_url = git_remote(source_dir, \"origin\");\n\n\tif(remote_url != location) {\n\t\tPackageCmd pc(source_dir.c_str(), \"git\");\n\t\tpc.addArg(\"remote\");\n\t\t\/\/ If the remote doesn't exist, add it\n\t\tif(remote_url == \"\") {\n\t\t\tpc.addArg(\"add\");\n\t\t} else {\n\t\t\tpc.addArg(\"set-url\");\n\t\t}\n\t\tpc.addArg(\"origin\");\n\t\tpc.addArg(location.c_str());\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed: git remote set-url origin\");\n\t\t}\n\n\t\tpc = PackageCmd(source_dir.c_str(), \"git\");\n\t\tpc.addArg(\"fetch\");\n\t\tpc.addArg(\"origin\");\n\t\tpc.addArg(\"--tags\");\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool GitExtractionUnit::fetch(BuildDir * d)\n{\n\tstd::string location = this->uri;\n\tstd::string source_dir = this->local;\n\tstd::string cwd = d->getWorld()->getWorkingDir();\n\n\tbool exists = directory_exists(source_dir);\n\n\tPackageCmd pc(exists ? source_dir : cwd, \"git\");\n\n\tif(exists) {\n\t\t\/* Update the origin *\/\n\t\tthis->updateOrigin();\n\t\t\/* Check if the commit is already present *\/\n\t\tstd::string cmd =\n\t\t \"cd \" + source_dir + \"; git cat-file -e \" + this->refspec +\n\t\t \" 2>\/dev\/null\";\n\t\tif(std::system(cmd.c_str()) != 0) {\n\t\t\t\/* If not, fetch everything from origin *\/\n\t\t\tpc.addArg(\"fetch\");\n\t\t\tpc.addArg(\"origin\");\n\t\t\tpc.addArg(\"--tags\");\n\t\t\tif(!pc.Run(this->P)) {\n\t\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tpc.addArg(\"clone\");\n\t\tpc.addArg(\"-n\");\n\t\tpc.addArg(location.c_str());\n\t\tpc.addArg(source_dir.c_str());\n\t\tif(!pc.Run(this->P))\n\t\t\tthrow CustomException(\"Failed to git clone\");\n\t}\n\n\tif(this->refspec.compare(\"HEAD\") == 0) {\n\t\t\/\/ Don't touch it\n\t} else {\n\t\tstd::string cmd =\n\t\t \"cd \" + source_dir +\n\t\t \"; git show-ref --quiet --verify -- refs\/heads\/\" + this->refspec;\n\t\tif(std::system(cmd.c_str()) == 0) {\n\t\t\tstd::string head_hash = git_hash_ref(source_dir, \"HEAD\");\n\t\t\tstd::string branch_hash = git_hash_ref(source_dir, this->refspec);\n\t\t\tif(head_hash != branch_hash) {\n\t\t\t\tthrow CustomException(\"Asked to use branch: \" +\n\t\t\t\t\t\t this->refspec + \", but \" +\n\t\t\t\t\t\t source_dir +\n\t\t\t\t\t\t \" is off somewhere else\");\n\t\t\t}\n\t\t} else {\n\t\t\tpc = PackageCmd(source_dir.c_str(), \"git\");\n\t\t\t\/\/ switch to refspec\n\t\t\tpc.addArg(\"checkout\");\n\t\t\tpc.addArg(\"-q\");\n\t\t\tpc.addArg(\"--detach\");\n\t\t\tpc.addArg(this->refspec.c_str());\n\t\t\tif(!pc.Run(this->P))\n\t\t\t\tthrow CustomException(\"Failed to checkout\");\n\t\t}\n\t}\n\tbool res = true;\n\n\tstd::string hash = git_hash(source_dir);\n\n\tif(!this->hash.empty()) {\n\t\tif(this->hash != hash) {\n\t\t\tlog(this->P,\n\t\t\t \"Hash mismatch for %s\\n(committed to %s, providing %s)\\n\",\n\t\t\t this->uri.c_str(), this->hash.c_str(), hash.c_str());\n\t\t\tres = false;\n\t\t}\n\t} else {\n\t\tthis->hash = hash;\n\t}\n\n\tthis->fetched = res;\n\n\treturn res;\n}\n\nstd::string GitExtractionUnit::HASH()\n{\n\tif(refspec_is_commitid(this->refspec)) {\n\t\tthis->hash = std::string(this->refspec);\n\t} else {\n\t\tstd::string digest_name = string_format(\"%s#%s\", this->uri.c_str(),\n\t\t\t\t\t\t\tthis->refspec.c_str());\n\t\t\/* Check if the package contains pre-computed hashes *\/\n\t\tstd::string Hash = P->getFileHash(digest_name);\n\t\tif(Hash.empty()) {\n\t\t\tthis->fetch(P->builddir());\n\t\t} else {\n\t\t\tthis->hash = Hash;\n\t\t}\n\t}\n\treturn this->hash;\n}\n\nbool GitExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\t\/\/ make sure it has been fetched\n\tif(!this->fetched) {\n\t\tif(!this->fetch(bd)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\/\/ copy to work dir\n\tPackageCmd pc(bd->getPath(), \"cp\");\n\tpc.addArg(\"-dpRuf\");\n\tpc.addArg(this->localPath());\n\tpc.addArg(\".\");\n\tif(!pc.Run(P))\n\t\tthrow CustomException(\"Failed to checkout\");\n\n\treturn true;\n}\n\nbool LinkGitDirExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tPackageCmd pc(bd->getPath(), \"ln\");\n\n\tpc.addArg(\"-sfT\");\n\n\tif(this->uri.at(0) == '.') {\n\t\tstd::string arg = P->getWorld()->getWorkingDir() + \"\/\" + this->uri;\n\t\tpc.addArg(arg);\n\t} else {\n\t\tpc.addArg(this->uri);\n\t}\n\tpc.addArg(this->toDir);\n\n\tif(!pc.Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n\nbool CopyGitDirExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tPackageCmd pc(bd->getPath(), \"cp\");\n\tpc.addArg(\"-dpRuf\");\n\n\tif(this->uri.at(0) == '.') {\n\t\tstd::string arg = P->getWorld()->getWorkingDir() + \"\/\" + this->uri;\n\t\tpc.addArg(arg);\n\t} else {\n\t\tpc.addArg(this->uri);\n\t}\n\tpc.addArg(this->toDir);\n\n\tif(!pc.Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n<commit_msg>extraction\/git: Remove usages of calloc<commit_after>\/******************************************************************************\n Copyright 2019 Allied Telesis Labs Ltd. All rights reserved.\n \nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. 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\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 OWNER 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#include <buildsys.h>\n\nstatic bool directory_exists(const std::string & dir)\n{\n\tif(!filesystem::exists(dir)) {\n\t\t\/* Nothing here *\/\n\t\treturn false;\n\t} else if(buildsys::filesystem::is_directory(dir)) {\n\t\t\/* Actually a directory *\/\n\t\treturn true;\n\t}\n\t\/* Something other than a directory *\/\n\treturn false;\n}\n\nstatic bool refspec_is_commitid(const std::string & refspec)\n{\n\tif(refspec.length() != 40) {\n\t\treturn false;\n\t}\n\n\tfor(char const &c:refspec) {\n\t\tif(!isxdigit(c)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstatic std::string git_hash_ref(const std::string & gdir, const std::string & refspec)\n{\n\tstd::string cmd = \"cd \" + gdir + \" && git rev-parse \" + refspec;\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == NULL) {\n\t\tthrow CustomException(\"git rev-parse ref failed\");\n\t}\n\tchar commit[41] = {};\n\tfread(commit, sizeof(char), 40, f);\n\tpclose(f);\n\n\treturn std::string(commit);\n}\n\nstatic std::string git_hash(const std::string & gdir)\n{\n\treturn git_hash_ref(gdir, \"HEAD\");\n}\n\nstatic std::string git_diff_hash(const std::string & gdir)\n{\n\tstd::string cmd = \"cd \" + gdir + \" && git diff HEAD | sha1sum\";\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == NULL) {\n\t\tthrow CustomException(\"git diff | sha1sum failed\");\n\t}\n\tchar delta_hash[41] = {};\n\tfread(delta_hash, sizeof(char), 40, f);\n\tpclose(f);\n\n\treturn std::string(delta_hash);\n}\n\nstatic std::string git_remote(const std::string & gdir, const std::string & remote)\n{\n\tstd::string cmd = \"cd \" + gdir + \" && git config --local --get remote.\" + remote + \".url\";\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == NULL) {\n\t\tthrow CustomException(\"git config --local --get remote. .url failed\");\n\t}\n\tchar output[1025] = {};\n\tfread(output, sizeof(char), 1024, f);\n\tpclose(f);\n\n\treturn std::string(output);\n}\n\nGitDirExtractionUnit::GitDirExtractionUnit(const std::string & git_dir,\n\t\t\t\t\t const std::string & to_dir)\n{\n\tthis->uri = git_dir;\n\tthis->hash = git_hash(this->uri);\n\tthis->toDir = to_dir;\n}\n\nGitDirExtractionUnit::GitDirExtractionUnit()\n{\n}\n\nbool GitDirExtractionUnit::isDirty()\n{\n\tif(!directory_exists(this->localPath())) {\n\t\t\/* If the source directory doesn't exist, then it can't be dirty *\/\n\t\treturn false;\n\t}\n\n\tstd::string cmd = string_format(\"cd %s && git diff --quiet HEAD\",\n\t\t\t\t\tthis->localPath().c_str());\n\tint res = std::system(cmd.c_str());\n\treturn (res != 0);\n}\n\nstd::string GitDirExtractionUnit::dirtyHash()\n{\n\treturn git_diff_hash(this->localPath());\n}\n\nGitExtractionUnit::GitExtractionUnit(const std::string & remote, const std::string & local,\n\t\t\t\t std::string refspec, Package * P)\n{\n\tthis->uri = remote;\n\tthis->local = P->getWorld()->getWorkingDir() + \"\/source\/\" + local;\n\tthis->refspec = refspec;\n\tthis->P = P;\n\tthis->fetched = false;\n}\n\nbool GitExtractionUnit::updateOrigin()\n{\n\tstd::string location = this->uri;\n\tstd::string source_dir = this->local;\n\tstd::string remote_url = git_remote(source_dir, \"origin\");\n\n\tif(remote_url != location) {\n\t\tPackageCmd pc(source_dir.c_str(), \"git\");\n\t\tpc.addArg(\"remote\");\n\t\t\/\/ If the remote doesn't exist, add it\n\t\tif(remote_url == \"\") {\n\t\t\tpc.addArg(\"add\");\n\t\t} else {\n\t\t\tpc.addArg(\"set-url\");\n\t\t}\n\t\tpc.addArg(\"origin\");\n\t\tpc.addArg(location.c_str());\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed: git remote set-url origin\");\n\t\t}\n\n\t\tpc = PackageCmd(source_dir.c_str(), \"git\");\n\t\tpc.addArg(\"fetch\");\n\t\tpc.addArg(\"origin\");\n\t\tpc.addArg(\"--tags\");\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool GitExtractionUnit::fetch(BuildDir * d)\n{\n\tstd::string location = this->uri;\n\tstd::string source_dir = this->local;\n\tstd::string cwd = d->getWorld()->getWorkingDir();\n\n\tbool exists = directory_exists(source_dir);\n\n\tPackageCmd pc(exists ? source_dir : cwd, \"git\");\n\n\tif(exists) {\n\t\t\/* Update the origin *\/\n\t\tthis->updateOrigin();\n\t\t\/* Check if the commit is already present *\/\n\t\tstd::string cmd =\n\t\t \"cd \" + source_dir + \"; git cat-file -e \" + this->refspec +\n\t\t \" 2>\/dev\/null\";\n\t\tif(std::system(cmd.c_str()) != 0) {\n\t\t\t\/* If not, fetch everything from origin *\/\n\t\t\tpc.addArg(\"fetch\");\n\t\t\tpc.addArg(\"origin\");\n\t\t\tpc.addArg(\"--tags\");\n\t\t\tif(!pc.Run(this->P)) {\n\t\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tpc.addArg(\"clone\");\n\t\tpc.addArg(\"-n\");\n\t\tpc.addArg(location.c_str());\n\t\tpc.addArg(source_dir.c_str());\n\t\tif(!pc.Run(this->P))\n\t\t\tthrow CustomException(\"Failed to git clone\");\n\t}\n\n\tif(this->refspec.compare(\"HEAD\") == 0) {\n\t\t\/\/ Don't touch it\n\t} else {\n\t\tstd::string cmd =\n\t\t \"cd \" + source_dir +\n\t\t \"; git show-ref --quiet --verify -- refs\/heads\/\" + this->refspec;\n\t\tif(std::system(cmd.c_str()) == 0) {\n\t\t\tstd::string head_hash = git_hash_ref(source_dir, \"HEAD\");\n\t\t\tstd::string branch_hash = git_hash_ref(source_dir, this->refspec);\n\t\t\tif(head_hash != branch_hash) {\n\t\t\t\tthrow CustomException(\"Asked to use branch: \" +\n\t\t\t\t\t\t this->refspec + \", but \" +\n\t\t\t\t\t\t source_dir +\n\t\t\t\t\t\t \" is off somewhere else\");\n\t\t\t}\n\t\t} else {\n\t\t\tpc = PackageCmd(source_dir.c_str(), \"git\");\n\t\t\t\/\/ switch to refspec\n\t\t\tpc.addArg(\"checkout\");\n\t\t\tpc.addArg(\"-q\");\n\t\t\tpc.addArg(\"--detach\");\n\t\t\tpc.addArg(this->refspec.c_str());\n\t\t\tif(!pc.Run(this->P))\n\t\t\t\tthrow CustomException(\"Failed to checkout\");\n\t\t}\n\t}\n\tbool res = true;\n\n\tstd::string hash = git_hash(source_dir);\n\n\tif(!this->hash.empty()) {\n\t\tif(this->hash != hash) {\n\t\t\tlog(this->P,\n\t\t\t \"Hash mismatch for %s\\n(committed to %s, providing %s)\\n\",\n\t\t\t this->uri.c_str(), this->hash.c_str(), hash.c_str());\n\t\t\tres = false;\n\t\t}\n\t} else {\n\t\tthis->hash = hash;\n\t}\n\n\tthis->fetched = res;\n\n\treturn res;\n}\n\nstd::string GitExtractionUnit::HASH()\n{\n\tif(refspec_is_commitid(this->refspec)) {\n\t\tthis->hash = std::string(this->refspec);\n\t} else {\n\t\tstd::string digest_name = string_format(\"%s#%s\", this->uri.c_str(),\n\t\t\t\t\t\t\tthis->refspec.c_str());\n\t\t\/* Check if the package contains pre-computed hashes *\/\n\t\tstd::string Hash = P->getFileHash(digest_name);\n\t\tif(Hash.empty()) {\n\t\t\tthis->fetch(P->builddir());\n\t\t} else {\n\t\t\tthis->hash = Hash;\n\t\t}\n\t}\n\treturn this->hash;\n}\n\nbool GitExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\t\/\/ make sure it has been fetched\n\tif(!this->fetched) {\n\t\tif(!this->fetch(bd)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\/\/ copy to work dir\n\tPackageCmd pc(bd->getPath(), \"cp\");\n\tpc.addArg(\"-dpRuf\");\n\tpc.addArg(this->localPath());\n\tpc.addArg(\".\");\n\tif(!pc.Run(P))\n\t\tthrow CustomException(\"Failed to checkout\");\n\n\treturn true;\n}\n\nbool LinkGitDirExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tPackageCmd pc(bd->getPath(), \"ln\");\n\n\tpc.addArg(\"-sfT\");\n\n\tif(this->uri.at(0) == '.') {\n\t\tstd::string arg = P->getWorld()->getWorkingDir() + \"\/\" + this->uri;\n\t\tpc.addArg(arg);\n\t} else {\n\t\tpc.addArg(this->uri);\n\t}\n\tpc.addArg(this->toDir);\n\n\tif(!pc.Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n\nbool CopyGitDirExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tPackageCmd pc(bd->getPath(), \"cp\");\n\tpc.addArg(\"-dpRuf\");\n\n\tif(this->uri.at(0) == '.') {\n\t\tstd::string arg = P->getWorld()->getWorkingDir() + \"\/\" + this->uri;\n\t\tpc.addArg(arg);\n\t} else {\n\t\tpc.addArg(this->uri);\n\t}\n\tpc.addArg(this->toDir);\n\n\tif(!pc.Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"spatial_organization\/binary_tree_element.h\"\n\n#include <stack>\n#include <sstream>\n\n#include \"string_util.h\"\n#include \"physics\/physical_node.h\"\n\nnamespace bdm {\nnamespace spatial_organization {\n\ntemplate<class T>\nBinaryTreeElement<T>* BinaryTreeElement<T>::generateTreeHead() {\n return new TreeHead<T>();\n}\n\ntemplate<class T>\nBinaryTreeElement<T>::BinaryTreeElement(SpaceNode<T>* content)\n : content_ { content },\n smaller_ { nullptr },\n bigger_ { nullptr } {\n if (content_ != nullptr) {\n content_id_ = getHash(content);\n } else {\n content_id_ = -1;\n }\n}\n\ntemplate<class T>\nBinaryTreeElement<T>::~BinaryTreeElement() {\n delete smaller_;\n delete bigger_;\n}\n\ntemplate<class T>\nbool BinaryTreeElement<T>::contains(SpaceNode<T>* content) const {\n return contains(getHash(content), content);\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::insert(SpaceNode<T>* content) {\n if (content != nullptr) {\n insert(new BinaryTreeElement<T>(content));\n }\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::remove(SpaceNode<T>* content, BinaryTreeElement* parent) {\n remove(getHash(content), content, parent);\n}\n\ntemplate<class T>\nstd::string BinaryTreeElement<T>::toString() const {\n stringstream str_stream;\n str_stream << StringUtil::toStr(smaller_);\n str_stream << \", \";\n str_stream << StringUtil::toStr(content_);\n str_stream << \", \";\n str_stream << StringUtil::toStr(bigger_);\n return str_stream.str();\n}\n\ntemplate<class T>\nint BinaryTreeElement<T>::getHash(SpaceNode<T>* content) const {\n uint64_t id = content_->getId();\n uint64_t c = 7481;\n return (id * c) % 74317;\n}\n\ntemplate<class T>\nbool BinaryTreeElement<T>::contains(int id, SpaceNode<T>* content) const {\n return contains(getHash(content), content);\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::insert(BinaryTreeElement* element) {\n if (content_id_ == element->content_id_ && content_ == element->content_) {\n delete element;\n return;\n } else if ((content_id_ >= element->content_id_)) {\n if ((smaller_ != nullptr)) {\n smaller_->insert(element);\n } else {\n smaller_ = element;\n }\n } else if (content_id_ < element->content_id_) {\n if (bigger_ != nullptr) {\n bigger_->insert(element);\n } else {\n bigger_ = element;\n }\n }\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::remove(int id, SpaceNode<T>* content, BinaryTreeElement* parent) {\n if ((content_id_ == id) && (content_ == content)) {\n if ((smaller_ == nullptr) && (bigger_ == nullptr)) {\n parent->changeLink(this, nullptr);\n \/\/use of randomization in the next if showed no influence on the simulation outcome\n } else if ((smaller_ != nullptr) || (bigger_ == nullptr)) {\n parent->changeLink(this, smaller_);\n if (bigger_ != nullptr) {\n smaller_->insert(bigger_);\n }\n } else {\n parent->changeLink(this, bigger_);\n if (smaller_ != nullptr) {\n bigger_->insert(smaller_);\n }\n }\n } else {\n if ((content_id_ >= id) && (smaller_ != nullptr)) {\n smaller_->remove(id, content, this);\n\n } else if ((content_id_ < id) && (bigger_ != nullptr)) {\n bigger_->remove(id, content, this);\n }\n }\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::changeLink(BinaryTreeElement* old_el, BinaryTreeElement* new_el) {\n if (smaller_ == old_el) {\n smaller_ = new_el;\n } else if (bigger_ == old_el) {\n bigger_ = new_el;\n }\n}\n\ntemplate<class T>\nstd::vector<SpaceNode<T>*> BinaryTreeElement<T>::inOrderTraversal() const {\n std::vector<SpaceNode<T>*> traversal;\n std::stack<const BinaryTreeElement<T>*> stack;\n const BinaryTreeElement<T>* dummy = this;\n while (dummy != nullptr) {\n stack.push(dummy);\n dummy = dummy->smaller_;\n }\n\n while (!stack.empty()) {\n dummy = stack.top();\n stack.pop();\n auto it = dummy->bigger_;\n while (it != nullptr) {\n stack.push(it);\n it = it->smaller_;\n }\n traversal.push_back(dummy->content_);\n }\n return traversal;\n}\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ TreeHead\n\ntemplate<class T>\nTreeHead<T>::TreeHead()\n : BinaryTreeElement<T>(nullptr) {\n\n}\n\ntemplate<class T>\nbool TreeHead<T>::contains(SpaceNode<T>* content) const {\n return BinaryTreeElement < T > ::bigger_ != nullptr ? BinaryTreeElement < T > ::bigger_->contains(content) : false;\n}\n\ntemplate<class T>\nvoid TreeHead<T>::insert(SpaceNode<T>* content) {\n if (BinaryTreeElement < T > ::bigger_ != nullptr) {\n BinaryTreeElement < T > ::bigger_->insert(content);\n } else {\n BinaryTreeElement < T > ::bigger_ = new BinaryTreeElement<T>(content);\n }\n}\n\ntemplate<class T>\nvoid TreeHead<T>::remove(SpaceNode<T>* content, BinaryTreeElement<T>* parent) {\n if (BinaryTreeElement < T > ::bigger_ != nullptr) {\n BinaryTreeElement < T > ::bigger_->remove(content, this);\n }\n}\n\ntemplate<class T>\nstd::vector<SpaceNode<T>*> TreeHead<T>::inOrderTraversal() const {\n if (BinaryTreeElement < T > ::bigger_ != nullptr) {\n return BinaryTreeElement < T > ::bigger_->inOrderTraversal();\n }\n return std::vector<SpaceNode<T>*>();\n}\n\ntemplate class BinaryTreeElement<bdm::physics::PhysicalNode> ;\n\n} \/\/ namespace spatial_organization\n} \/\/ namespace bdm\n<commit_msg>Fix copy paste error in BinaryTreeElement::contains method - fixes BIOD-5<commit_after>#include \"spatial_organization\/binary_tree_element.h\"\n\n#include <stack>\n#include <sstream>\n\n#include \"string_util.h\"\n#include \"physics\/physical_node.h\"\n\nnamespace bdm {\nnamespace spatial_organization {\n\ntemplate<class T>\nBinaryTreeElement<T>* BinaryTreeElement<T>::generateTreeHead() {\n return new TreeHead<T>();\n}\n\ntemplate<class T>\nBinaryTreeElement<T>::BinaryTreeElement(SpaceNode<T>* content)\n : content_ { content },\n smaller_ { nullptr },\n bigger_ { nullptr } {\n if (content_ != nullptr) {\n content_id_ = getHash(content);\n } else {\n content_id_ = -1;\n }\n}\n\ntemplate<class T>\nBinaryTreeElement<T>::~BinaryTreeElement() {\n delete smaller_;\n delete bigger_;\n}\n\ntemplate<class T>\nbool BinaryTreeElement<T>::contains(SpaceNode<T>* content) const {\n return contains(getHash(content), content);\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::insert(SpaceNode<T>* content) {\n if (content != nullptr) {\n insert(new BinaryTreeElement<T>(content));\n }\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::remove(SpaceNode<T>* content, BinaryTreeElement* parent) {\n remove(getHash(content), content, parent);\n}\n\ntemplate<class T>\nstd::string BinaryTreeElement<T>::toString() const {\n stringstream str_stream;\n str_stream << StringUtil::toStr(smaller_);\n str_stream << \", \";\n str_stream << StringUtil::toStr(content_);\n str_stream << \", \";\n str_stream << StringUtil::toStr(bigger_);\n return str_stream.str();\n}\n\ntemplate<class T>\nint BinaryTreeElement<T>::getHash(SpaceNode<T>* content) const {\n uint64_t id = content_->getId();\n uint64_t c = 7481;\n return (id * c) % 74317;\n}\n\ntemplate<class T>\nbool BinaryTreeElement<T>::contains(int id, SpaceNode<T>* content) const {\n if (content_ == content) {\n return true;\n } else {\n if (content_id_ >= id && smaller_ != nullptr) {\n return smaller_->contains(id, content);\n } else if (content_id_ < id && bigger_ != nullptr) {\n return bigger_->contains(id, content);\n }else {\n return false;\n }\n }\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::insert(BinaryTreeElement* element) {\n if (content_id_ == element->content_id_ && content_ == element->content_) {\n delete element;\n return;\n } else if ((content_id_ >= element->content_id_)) {\n if ((smaller_ != nullptr)) {\n smaller_->insert(element);\n } else {\n smaller_ = element;\n }\n } else if (content_id_ < element->content_id_) {\n if (bigger_ != nullptr) {\n bigger_->insert(element);\n } else {\n bigger_ = element;\n }\n }\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::remove(int id, SpaceNode<T>* content, BinaryTreeElement* parent) {\n if ((content_id_ == id) && (content_ == content)) {\n if ((smaller_ == nullptr) && (bigger_ == nullptr)) {\n parent->changeLink(this, nullptr);\n \/\/use of randomization in the next if showed no influence on the simulation outcome\n } else if ((smaller_ != nullptr) || (bigger_ == nullptr)) {\n parent->changeLink(this, smaller_);\n if (bigger_ != nullptr) {\n smaller_->insert(bigger_);\n }\n } else {\n parent->changeLink(this, bigger_);\n if (smaller_ != nullptr) {\n bigger_->insert(smaller_);\n }\n }\n } else {\n if ((content_id_ >= id) && (smaller_ != nullptr)) {\n smaller_->remove(id, content, this);\n\n } else if ((content_id_ < id) && (bigger_ != nullptr)) {\n bigger_->remove(id, content, this);\n }\n }\n}\n\ntemplate<class T>\nvoid BinaryTreeElement<T>::changeLink(BinaryTreeElement* old_el, BinaryTreeElement* new_el) {\n if (smaller_ == old_el) {\n smaller_ = new_el;\n } else if (bigger_ == old_el) {\n bigger_ = new_el;\n }\n}\n\ntemplate<class T>\nstd::vector<SpaceNode<T>*> BinaryTreeElement<T>::inOrderTraversal() const {\n std::vector<SpaceNode<T>*> traversal;\n std::stack<const BinaryTreeElement<T>*> stack;\n const BinaryTreeElement<T>* dummy = this;\n while (dummy != nullptr) {\n stack.push(dummy);\n dummy = dummy->smaller_;\n }\n\n while (!stack.empty()) {\n dummy = stack.top();\n stack.pop();\n auto it = dummy->bigger_;\n while (it != nullptr) {\n stack.push(it);\n it = it->smaller_;\n }\n traversal.push_back(dummy->content_);\n }\n return traversal;\n}\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ TreeHead\n\ntemplate<class T>\nTreeHead<T>::TreeHead()\n : BinaryTreeElement<T>(nullptr) {\n\n}\n\ntemplate<class T>\nbool TreeHead<T>::contains(SpaceNode<T>* content) const {\n return BinaryTreeElement < T > ::bigger_ != nullptr ? BinaryTreeElement < T > ::bigger_->contains(content) : false;\n}\n\ntemplate<class T>\nvoid TreeHead<T>::insert(SpaceNode<T>* content) {\n if (BinaryTreeElement < T > ::bigger_ != nullptr) {\n BinaryTreeElement < T > ::bigger_->insert(content);\n } else {\n BinaryTreeElement < T > ::bigger_ = new BinaryTreeElement<T>(content);\n }\n}\n\ntemplate<class T>\nvoid TreeHead<T>::remove(SpaceNode<T>* content, BinaryTreeElement<T>* parent) {\n if (BinaryTreeElement < T > ::bigger_ != nullptr) {\n BinaryTreeElement < T > ::bigger_->remove(content, this);\n }\n}\n\ntemplate<class T>\nstd::vector<SpaceNode<T>*> TreeHead<T>::inOrderTraversal() const {\n if (BinaryTreeElement < T > ::bigger_ != nullptr) {\n return BinaryTreeElement < T > ::bigger_->inOrderTraversal();\n }\n return std::vector<SpaceNode<T>*>();\n}\n\ntemplate class BinaryTreeElement<bdm::physics::PhysicalNode> ;\n\n} \/\/ namespace spatial_organization\n} \/\/ namespace bdm\n<|endoftext|>"} {"text":"<commit_before>#ifndef OBJECT_GL_COLOUR_FORMAT_HPP\n#define OBJECT_GL_COLOUR_FORMAT_HPP\n\n\/\/Copyright 2015 Adam Smith\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\/\/ Contact :\n\/\/ Email : $objectgl_email\n\/\/ GitHub repository : $objectgl_git\n\n\/*!\n\t\\file ColourFormat.hpp\n\t\\brief\n\t\\author Adam Smith\n\t\\date 6th November 2015\n*\/\n\n#include <cstdint>\n#include \"ObjectGLInit.inl\"\n#include \"BinaryData.hpp\"\n\nnamespace ObjectGL { namespace ColourFormat{\n\n\tnamespace Implementation{\n\n\t\ttemplate<const GLuint BITS>\n\t\tstatic void CopyBits(const void* aSrc, const GLuint aSrcOffset, void* aDst, const GLuint aDstOffset){\n\n\t\t\tconst bool byteAligned = ! ((BITS & 7) || (aSrcOffset & 7) || (aDstOffset & 7));\n\n\t\t\tif(byteAligned){\n\t\t\t\tstd::memcpy(\n\t\t\t\t\tstatic_cast<const uint8_t*>(aSrc) + (aSrcOffset \/ 8), \n\t\t\t\t\tstatic_cast<uint8_t*>(aDst) + (aDstOffset \/ 8),\n\t\t\t\t\tBITS \/ 8\n\t\t\t\t);\n\t\t\t}else{\n\t\t\t\t\/\/! \\todo Optimise\n\t\t\t\tconst uint8_t* const src = static_cast<const uint8_t*>(aSrc);\n\t\t\t\tuint8_t* const dst = static_cast<uint8_t*>(aDst);\n\n\t\t\t\tGLuint srcOffset = aSrcOffset;\n\t\t\t\tGLuint dstOffset = aDstOffset;\n\t\t\t\tfor(GLuint i = 0; i != BITS; ++i){\n\t\t\t\t\tconst uint8_t srcByte = src[srcOffset \/ 8];\n\t\t\t\t\tuint8_t& dstByte = dst[dstOffset \/ 8];\n\n\t\t\t\t\tconst uint8_t srcMask = 1 << (aSrcOffset & 7);\n\t\t\t\t\tconst uint8_t dstMask = 1 << (dstOffset & 7);\n\n\t\t\t\t\tuint8_t bit = srcByte & srcMask;\n\n\t\t\t\t\tdstByte &= ~dstMask;\n\t\t\t\t\tif(bit) dstByte |= dstMask;\n\n\t\t\t\t\t++srcOffset;\n\t\t\t\t\t++dstOffset;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate<class Format>\n\tstatic typename Format::Type Read(const void* const aData, const GLuint aOffset){\n\t\ttypename Format::Type tmp = 0;\n\t\treturn Implementation::CopyBits<Format::BitDepth>(aData, aOffset * Format::BitDepth, &tmp, 0);\n\t\treturn tmp;\n\t}\n\n\ttemplate<class Format>\n\tstatic void Write(void* const aData, const GLuint aOffset, const typename Format::Type aValue){\n\t\treturn Implementation::CopyBits<Format::BitDepth>(&aValue, 0, aData, aOffset * Format::BitDepth);\n\t}\n\n\tenum class Storage : GLenum{\n\t\tNONE\t\t\t\t= GL_NONE,\n\t\tUNSIGNED_NORMALISED\t= GL_UNSIGNED_NORMALIZED,\n\t\tSIGNED_NORMALISED\t= GL_SIGNED_NORMALIZED,\n\t\tUNSIGNED_INTEGRAL\t= GL_UNSIGNED_INT,\n\t\tSIGNED_INTEGRAL\t\t= GL_INT,\n\t\tFLOAT\t\t\t\t= GL_FLOAT\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct StorageType{\n\t\ttypedef void Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = 0,\n\t\t\tSizeBits = 0\n\t\t};\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::NONE>{\n\t\ttypedef void Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = 0,\n\t\t\tSizeBits = 0\n\t\t};\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::UNSIGNED_NORMALISED>{\n\t\ttypedef uint8_t Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<UNSIGNED_NORMALISED> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<UNSIGNED_NORMALISED> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::SIGNED_NORMALISED>{\n\t\ttypedef int8_t Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<SIGNED_NORMALISED> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<SIGNED_NORMALISED> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::UNSIGNED_INTEGRAL>{\n\t\ttypedef uint8_t Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<UNSIGNED_INTEGRAL> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<UNSIGNED_INTEGRAL> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::SIGNED_INTEGRAL>{\n\t\ttypedef uint8_t Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<SIGNED_INTEGRAL> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<SIGNED_INTEGRAL> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::FLOAT>{\n\t\ttypedef float Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<FLOAT> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<FLOAT> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct R{\n\t\tenum : GLuint{\n\t\t\tElementCount = 1,\n\t\t\tFormatEnum = GL_RED,\n\t\t\tElementSizeBits = StorageType<TYPE>::SizeBits,\n\t\t\tElementSizeBytes = StorageType<TYPE>::SizeBytes,\n\t\t\tFormatSizeBits = ElementSizeBits * ElementCount,\n\t\t\tFormatSizeBytes = ElementSizeBytes * ElementCount,\n\t\t\tElementEnum = static_cast<GLuint>(TYPE)\n\t\t};\n\n\t\ttypedef BinaryData<FormatSizeBytes> FormatType;\n\t\ttypedef typename StorageType<TYPE>::Type ElementType;\n\n\t\tstatic_assert(sizeof(FormatType) >= FormatSizeBytes, \"ObjectGL::R FormatType is not large enough to contain FormatSize\");\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct RG{\n\t\tenum : GLuint{\n\t\t\tElementCount = 2,\n\t\t\tFormatEnum = GL_RG,\n\t\t\tElementSizeBits = StorageType<TYPE>::SizeBits,\n\t\t\tElementSizeBytes = StorageType<TYPE>::SizeBytes,\n\t\t\tFormatSizeBits = ElementSizeBits * ElementCount,\n\t\t\tFormatSizeBytes = ElementSizeBytes * ElementCount,\n\t\t\tElementEnum = static_cast<GLuint>(TYPE)\n\t\t};\n\n\t\ttypedef BinaryData<FormatSizeBytes> FormatType;\n\t\ttypedef typename StorageType<TYPE>::Type ElementType;\n\n\t\tstatic_assert(sizeof(FormatType) >= FormatSizeBytes, \"ObjectGL::RG FormatType is not large enough to contain FormatSize\");\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct RGB{\n\t\tenum : GLuint{\n\t\t\tElementCount = 3,\n\t\t\tFormatEnum = GL_RGB,\n\t\t\tElementSizeBits = StorageType<TYPE>::SizeBits,\n\t\t\tElementSizeBytes = StorageType<TYPE>::SizeBytes,\n\t\t\tFormatSizeBits = ElementSizeBits * ElementCount,\n\t\t\tFormatSizeBytes = ElementSizeBytes * ElementCount,\n\t\t\tElementEnum = static_cast<GLuint>(TYPE)\n\t\t};\n\n\t\ttypedef BinaryData<FormatSizeBytes> FormatType;\n\t\ttypedef typename StorageType<TYPE>::Type ElementType;\n\n\t\tstatic_assert(sizeof(FormatType) >= FormatSizeBytes, \"ObjectGL::RGB FormatType is not large enough to contain FormatSize\");\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct RGBA{\n\t\tenum : GLuint{\n\t\t\tElementCount = 4,\n\t\t\tFormatEnum = GL_RGBA,\n\t\t\tElementSizeBits = StorageType<TYPE>::SizeBits,\n\t\t\tElementSizeBytes = StorageType<TYPE>::SizeBytes,\n\t\t\tFormatSizeBits = ElementSizeBits * ElementCount,\n\t\t\tFormatSizeBytes = ElementSizeBytes * ElementCount,\n\t\t\tElementEnum = static_cast<GLuint>(TYPE)\n\t\t};\n\n\t\ttypedef BinaryData<FormatSizeBytes> FormatType;\n\t\ttypedef typename StorageType<TYPE>::Type ElementType;\n\n\t\tstatic_assert(sizeof(FormatType) * 8 >= FormatSizeBytes, \"ObjectGL::RGBA FormatType is not large enough to contain FormatSize\");\n\t};\n}}\n\n#endif\n<commit_msg>Format Read \/ Write fix<commit_after>#ifndef OBJECT_GL_COLOUR_FORMAT_HPP\n#define OBJECT_GL_COLOUR_FORMAT_HPP\n\n\/\/Copyright 2015 Adam Smith\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\/\/ Contact :\n\/\/ Email : $objectgl_email\n\/\/ GitHub repository : $objectgl_git\n\n\/*!\n\t\\file ColourFormat.hpp\n\t\\brief\n\t\\author Adam Smith\n\t\\date 6th November 2015\n*\/\n\n#include <cstdint>\n#include \"ObjectGLInit.inl\"\n#include \"BinaryData.hpp\"\n\nnamespace ObjectGL { namespace ColourFormat{\n\n\tnamespace Implementation{\n\n\t\ttemplate<const GLuint BITS>\n\t\tstatic void CopyBits(const void* aSrc, const GLuint aSrcOffset, void* aDst, const GLuint aDstOffset){\n\n\t\t\tconst bool byteAligned = ! ((BITS & 7) || (aSrcOffset & 7) || (aDstOffset & 7));\n\n\t\t\tif(byteAligned){\n\t\t\t\tstd::memcpy(\n\t\t\t\t\tstatic_cast<const uint8_t*>(aSrc) + (aSrcOffset \/ 8), \n\t\t\t\t\tstatic_cast<uint8_t*>(aDst) + (aDstOffset \/ 8),\n\t\t\t\t\tBITS \/ 8\n\t\t\t\t);\n\t\t\t}else{\n\t\t\t\t\/\/! \\todo Optimise\n\t\t\t\tconst uint8_t* const src = static_cast<const uint8_t*>(aSrc);\n\t\t\t\tuint8_t* const dst = static_cast<uint8_t*>(aDst);\n\n\t\t\t\tGLuint srcOffset = aSrcOffset;\n\t\t\t\tGLuint dstOffset = aDstOffset;\n\t\t\t\tfor(GLuint i = 0; i != BITS; ++i){\n\t\t\t\t\tconst uint8_t srcByte = src[srcOffset \/ 8];\n\t\t\t\t\tuint8_t& dstByte = dst[dstOffset \/ 8];\n\n\t\t\t\t\tconst uint8_t srcMask = 1 << (aSrcOffset & 7);\n\t\t\t\t\tconst uint8_t dstMask = 1 << (dstOffset & 7);\n\n\t\t\t\t\tuint8_t bit = srcByte & srcMask;\n\n\t\t\t\t\tdstByte &= ~dstMask;\n\t\t\t\t\tif(bit) dstByte |= dstMask;\n\n\t\t\t\t\t++srcOffset;\n\t\t\t\t\t++dstOffset;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate<class Format>\n\tstatic typename Format::FormatType Read(const void* const aData, const GLuint aOffset){\n\t\ttypename Format::FormatType tmp = 0;\n\t\treturn Implementation::CopyBits<Format::FormatSizeBits>(aData, aOffset * Format::FormatSizeBits, &tmp, 0);\n\t\treturn tmp;\n\t}\n\n\ttemplate<class Format>\n\tstatic void Write(void* const aData, const GLuint aOffset, const typename Format::FormatType aValue){\n\t\treturn Implementation::CopyBits<Format::FormatSizeBits>(&aValue, 0, aData, aOffset * Format::FormatSizeBits);\n\t}\n\n\tenum class Storage : GLenum{\n\t\tNONE\t\t\t\t= GL_NONE,\n\t\tUNSIGNED_NORMALISED\t= GL_UNSIGNED_NORMALIZED,\n\t\tSIGNED_NORMALISED\t= GL_SIGNED_NORMALIZED,\n\t\tUNSIGNED_INTEGRAL\t= GL_UNSIGNED_INT,\n\t\tSIGNED_INTEGRAL\t\t= GL_INT,\n\t\tFLOAT\t\t\t\t= GL_FLOAT\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct StorageType{\n\t\ttypedef void Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = 0,\n\t\t\tSizeBits = 0\n\t\t};\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::NONE>{\n\t\ttypedef void Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = 0,\n\t\t\tSizeBits = 0\n\t\t};\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::UNSIGNED_NORMALISED>{\n\t\ttypedef uint8_t Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<UNSIGNED_NORMALISED> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<UNSIGNED_NORMALISED> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::SIGNED_NORMALISED>{\n\t\ttypedef int8_t Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<SIGNED_NORMALISED> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<SIGNED_NORMALISED> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::UNSIGNED_INTEGRAL>{\n\t\ttypedef uint8_t Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<UNSIGNED_INTEGRAL> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<UNSIGNED_INTEGRAL> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::SIGNED_INTEGRAL>{\n\t\ttypedef uint8_t Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<SIGNED_INTEGRAL> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<SIGNED_INTEGRAL> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<>\n\tstruct StorageType<Storage::FLOAT>{\n\t\ttypedef float Type;\n\t\tenum : GLuint{\n\t\t\tSizeBytes = sizeof(Type),\n\t\t\tSizeBits = SizeBytes * 8\n\t\t};\n\n\t\tstatic_assert(SizeBytes * 8 >= SizeBytes, \"ObjectGL::StorageType<FLOAT> SizeBits is larger than SizeBytes\");\n\t\tstatic_assert(sizeof(Type) >= SizeBytes, \"ObjectGL::StorageType<FLOAT> Type is not large enough to contain Size SizeBytes\");\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct R{\n\t\tenum : GLuint{\n\t\t\tElementCount = 1,\n\t\t\tFormatEnum = GL_RED,\n\t\t\tElementSizeBits = StorageType<TYPE>::SizeBits,\n\t\t\tElementSizeBytes = StorageType<TYPE>::SizeBytes,\n\t\t\tFormatSizeBits = ElementSizeBits * ElementCount,\n\t\t\tFormatSizeBytes = ElementSizeBytes * ElementCount,\n\t\t\tElementEnum = static_cast<GLuint>(TYPE)\n\t\t};\n\n\t\ttypedef BinaryData<FormatSizeBytes> FormatType;\n\t\ttypedef typename StorageType<TYPE>::Type ElementType;\n\n\t\tstatic_assert(sizeof(FormatType) >= FormatSizeBytes, \"ObjectGL::R FormatType is not large enough to contain FormatSize\");\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct RG{\n\t\tenum : GLuint{\n\t\t\tElementCount = 2,\n\t\t\tFormatEnum = GL_RG,\n\t\t\tElementSizeBits = StorageType<TYPE>::SizeBits,\n\t\t\tElementSizeBytes = StorageType<TYPE>::SizeBytes,\n\t\t\tFormatSizeBits = ElementSizeBits * ElementCount,\n\t\t\tFormatSizeBytes = ElementSizeBytes * ElementCount,\n\t\t\tElementEnum = static_cast<GLuint>(TYPE)\n\t\t};\n\n\t\ttypedef BinaryData<FormatSizeBytes> FormatType;\n\t\ttypedef typename StorageType<TYPE>::Type ElementType;\n\n\t\tstatic_assert(sizeof(FormatType) >= FormatSizeBytes, \"ObjectGL::RG FormatType is not large enough to contain FormatSize\");\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct RGB{\n\t\tenum : GLuint{\n\t\t\tElementCount = 3,\n\t\t\tFormatEnum = GL_RGB,\n\t\t\tElementSizeBits = StorageType<TYPE>::SizeBits,\n\t\t\tElementSizeBytes = StorageType<TYPE>::SizeBytes,\n\t\t\tFormatSizeBits = ElementSizeBits * ElementCount,\n\t\t\tFormatSizeBytes = ElementSizeBytes * ElementCount,\n\t\t\tElementEnum = static_cast<GLuint>(TYPE)\n\t\t};\n\n\t\ttypedef BinaryData<FormatSizeBytes> FormatType;\n\t\ttypedef typename StorageType<TYPE>::Type ElementType;\n\n\t\tstatic_assert(sizeof(FormatType) >= FormatSizeBytes, \"ObjectGL::RGB FormatType is not large enough to contain FormatSize\");\n\t};\n\n\ttemplate<const Storage TYPE>\n\tstruct RGBA{\n\t\tenum : GLuint{\n\t\t\tElementCount = 4,\n\t\t\tFormatEnum = GL_RGBA,\n\t\t\tElementSizeBits = StorageType<TYPE>::SizeBits,\n\t\t\tElementSizeBytes = StorageType<TYPE>::SizeBytes,\n\t\t\tFormatSizeBits = ElementSizeBits * ElementCount,\n\t\t\tFormatSizeBytes = ElementSizeBytes * ElementCount,\n\t\t\tElementEnum = static_cast<GLuint>(TYPE)\n\t\t};\n\n\t\ttypedef BinaryData<FormatSizeBytes> FormatType;\n\t\ttypedef typename StorageType<TYPE>::Type ElementType;\n\n\t\tstatic_assert(sizeof(FormatType) * 8 >= FormatSizeBytes, \"ObjectGL::RGBA FormatType is not large enough to contain FormatSize\");\n\t};\n}}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Executor.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 29\/04\/2022.\n\/\/ Copyright © 2022 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Executor.hpp\"\n\nusing namespace InstructionSet::M68k;\n\ntemplate <Model model, typename BusHandler>\nExecutor<model, BusHandler>::Executor(BusHandler &handler) : bus_handler_(handler) {\n\treset();\n}\n\ntemplate <Model model, typename BusHandler>\nvoid Executor<model, BusHandler>::reset() {\n\n}\n\ntemplate <Model model, typename BusHandler>\nvoid Executor<model, BusHandler>::run_for_instructions(int count) {\n\twhile(count--) {\n\t\t\/\/ TODO: check interrupt level, trace flag.\n\n\t\t\/\/ Read the next instruction.\n\t\tconst Preinstruction instruction = decoder_.decode(bus_handler_.template read<uint16_t>(program_counter_.l));\n\t\tconst auto instruction_address = program_counter_.l;\n\t\tprogram_counter_.l += 2;\n\n\t\t\/\/ Obtain the appropriate sequence.\n\t\tSequence<model> sequence(instruction.operation);\n\n\t\t\/\/ Perform it.\n\t\twhile(!sequence.empty()) {\n\t\t\tconst auto step = sequence.pop_front();\n\t\t}\n\t}\n}\n<commit_msg>Figure out what the call to `perform` should look like.<commit_after>\/\/\n\/\/ Executor.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 29\/04\/2022.\n\/\/ Copyright © 2022 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Executor.hpp\"\n\n#include \"Perform.hpp\"\n\n#include <cassert>\n\nusing namespace InstructionSet::M68k;\n\ntemplate <Model model, typename BusHandler>\nExecutor<model, BusHandler>::Executor(BusHandler &handler) : bus_handler_(handler) {\n\treset();\n}\n\ntemplate <Model model, typename BusHandler>\nvoid Executor<model, BusHandler>::reset() {\n\t\/\/ TODO.\n}\n\ntemplate <Model model, typename BusHandler>\nvoid Executor<model, BusHandler>::run_for_instructions(int count) {\n\twhile(count--) {\n\t\t\/\/ TODO: check interrupt level, trace flag.\n\n\t\t\/\/ Read the next instruction.\n\t\tconst Preinstruction instruction = decoder_.decode(bus_handler_.template read<uint16_t>(program_counter_.l));\n\t\tconst auto instruction_address = program_counter_.l;\n\t\tprogram_counter_.l += 2;\n\n\t\t\/\/ Obtain the appropriate sequence.\n\t\tSequence<model> sequence(instruction.operation);\n\n\t\t\/\/ Temporary storage.\n\t\tCPU::SlicedInt32 source, dest;\n\n\t\t\/\/ Perform it.\n\t\twhile(!sequence.empty()) {\n\t\t\tconst auto step = sequence.pop_front();\n\n\t\t\tswitch(step) {\n\t\t\t\tdefault: assert(false);\t\/\/ i.e. TODO\n\n\t\t\t\tcase Step::Perform:\n\t\t\t\t\tperform<model>(instruction, source, dest, status_, this);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Name: drs4analysis\n Based on read_binary.cpp by Stefan Ritt <stefan.ritt@psi.ch>\n\n Purpose: analyse data saved by drs4daq\n \n The present version only plots the oscillograms from all 4 channels\n in a pdf file.\n*\/\n\n#include <stdio.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n#include <math.h>\n\n#include \"TGraph.h\"\n#include \"TH1F.h\"\n#include \"TFile.h\"\n#include \"TTree.h\"\n#include \"TCanvas.h\"\n#include \"TStyle.h\"\n#include \"TString.h\"\n\n#include \"WaveProcessor.h\"\n#include \"DRS4_data.h\"\n\n\ntypedef struct {\n char tag[3];\n char version;\n} FHEADER;\n\ntypedef struct {\n char time_header[4];\n} THEADER;\n\ntypedef struct {\n char bn[2];\n unsigned short board_serial_number;\n} BHEADER;\n\ntypedef struct {\n char event_header[4];\n unsigned int event_serial_number;\n unsigned short year;\n unsigned short month;\n unsigned short day;\n unsigned short hour;\n unsigned short minute;\n unsigned short second;\n unsigned short millisecond;\n unsigned short range;\n} EHEADER;\n\ntypedef struct {\n char tc[2];\n unsigned short trigger_cell;\n} TCHEADER;\n\ntypedef struct {\n char c[1];\n char cn[3];\n} CHEADER;\n\n\/*-----------------------------------------------------------------------------*\/\n\nint main(int argc, const char * argv[])\n{\n FHEADER fh;\n THEADER th;\n BHEADER bh;\n EHEADER eh;\n TCHEADER tch;\n CHEADER ch;\n \n unsigned int scaler;\n int16_t voltage[4][1024];\n float waveform[16][4][1024], time[16][4][1024];\n float bin_width[16][4][1024];\n int i, j, b, chn, iEvt, n_boards;\n int chn_index[4];\n double t1, t2, dt;\n char filename[256];\n\n int ndt;\n double threshold, sumdt, sumdt2;\n \n if (argc > 1)\n strcpy(filename, argv[1]);\n else {\n printf(\"Usage: drs4analysis <filename>\\n\");\n return 0;\n }\n \n \/\/ open the binary waveform file\n FILE *f = fopen(filename, \"rb\");\n if (f == NULL) {\n printf(\"Cannot find file \\'%s\\'\\n\", filename);\n return 0;\n }\n\n \/\/ read file header\n fread(&fh, sizeof(fh), 1, f);\n if (fh.tag[0] != 'D' || fh.tag[1] != 'R' || fh.tag[2] != 'S') {\n printf(\"Found invalid file header in file \\'%s\\', aborting.\\n\", filename);\n return 0;\n }\n \n if (fh.version != '2' && fh.version != '4') {\n printf(\"Found invalid file version \\'%c\\' in file \\'%s\\', should be \\'2\\', aborting.\\n\", fh.version, filename);\n return 0;\n }\n\n \/\/ read time header\n fread(&th, sizeof(th), 1, f);\n if (memcmp(th.time_header, \"TIME\", 4) != 0) {\n printf(\"Invalid time header in file \\'%s\\', aborting.\\n\", filename);\n return 0;\n }\n\n for (b = 0 ; ; b++) {\n \/\/ read board header\n fread(&bh, sizeof(bh), 1, f);\n if (memcmp(bh.bn, \"B#\", 2) != 0) {\n \/\/ probably event header found\n fseek(f, -4, SEEK_CUR);\n break;\n }\n \n printf(\"Found data for board #%d\\n\", bh.board_serial_number);\n \n \/\/ read time bin widths\n memset(bin_width[b], sizeof(bin_width[0]), 0);\n for (chn=0 ; chn<5 ; chn++) {\n fread(&ch, sizeof(ch), 1, f);\n if (ch.c[0] != 'C') {\n \/\/ event header found\n fseek(f, -4, SEEK_CUR);\n break;\n }\n i = ch.cn[2] - '0' - 1;\n printf(\"Found timing calibration for channel #%d\\n\", i+1);\n fread(&bin_width[b][i][0], sizeof(float), 1024, f);\n \/\/ fix for 2048 bin mode: double channel\n if (bin_width[b][i][1023] > 10 || bin_width[b][i][1023] < 0.01) {\n for (j=0 ; j<512 ; j++)\n bin_width[b][i][j+512] = bin_width[b][i][j];\n }\n }\n }\n n_boards = b;\n \n \/\/ initialize statistics\n ndt = 0;\n sumdt = sumdt2 = 0;\n \n \/*** Prepare oscillogram plots ***\/\n TCanvas c(\"can\", \"cancan\", 800, 600);\n gStyle->SetPaperSize(18, 12);\n gStyle->SetLabelSize(0.06, \"XY\");\n gStyle->SetTitleSize(0.06, \"XY\");\n gStyle->SetPadLeftMargin(0.12);\n gStyle->SetPadBottomMargin(0.12);\n c.Divide(2, 2, .01, .01);\n c.GetPad(1)->SetGrid(1, 0);\n c.GetPad(2)->SetGrid(1, 0);\n c.GetPad(3)->SetGrid(1, 0);\n c.GetPad(4)->SetGrid(1, 0);\n TH1F frame(\"frame\", \"frame; t (ns); A (mV)\", 10, 0., 200);\n frame.SetMinimum(-500);\n frame.SetMaximum(50);\n frame.SetLineColor(kGray);\n frame.SetStats(false);\n TString pdfname(filename);\n if (pdfname.EndsWith(\".dat\")) pdfname.Resize(pdfname.Sizeof() - 5);\n pdfname += \".pdf\";\n bool firstpage = true, lastpage = false;\n\n \/*** Prepare tree ***\/\n\n TString rfname(filename);\n if (rfname.EndsWith(\".dat\")) rfname.Resize(pdfname.Sizeof() - 5);\n rfname += \".root\";\n TFile file(rfname, \"RECREATE\");\n\n unsigned nCh = 4;\n DRS4_data::Observables obs[nCh];\n TTree events(\"events\", \"events\");\n\n for (unsigned iCh=0; iCh<nCh; iCh++) {\n\n for (unsigned iObs=0; iObs<DRS4_data::nObservables; iObs++) {\n const char *varname = Form(\"%s_S%d\", obs[iCh].Name(DRS4_data::kObservables(iObs)), iCh+1);\n events.Branch(varname, &obs[iCh].Value(DRS4_data::kObservables(iObs)), varname);\n }\n }\n\n \/*** Prepare average waveforms ***\/\n\n TH1F *havg[4];\n for (int ich=0; ich<4; ich++) {\n havg[ich] = new TH1F(Form(\"havg_S%d\", ich+1), \"Average waveform; t (ns); A (mV)\", 1000, 0., 200.);\n }\n\n\n \/\/ loop over all events in the data file\n for (iEvt=0 ; iEvt<100000; iEvt++) {\n \/\/ read event header\n i = (int)fread(&eh, sizeof(eh), 1, f);\n if (i < 1)\n break;\n\n if (iEvt%100 == 0) {\n printf(\"Found event #%d at %d s %d ms\\n\", eh.event_serial_number, eh.second, eh.millisecond);\n }\n \n \/\/ loop over all boards in data file\n for (b=0 ; b<n_boards ; b++) {\n \n \/\/ read board header\n fread(&bh, sizeof(bh), 1, f);\n if (memcmp(bh.bn, \"B#\", 2) != 0) {\n printf(\"Invalid board header in file \\'%s\\', aborting.\\n\", filename);\n return 0;\n }\n \n \/\/ read trigger cell\n fread(&tch, sizeof(tch), 1, f);\n if (memcmp(tch.tc, \"T#\", 2) != 0) {\n printf(\"Invalid trigger cell header in file \\'%s\\', aborting.\\n\", filename);\n return 0;\n }\n\n if (n_boards > 1)\n printf(\"Found data for board #%d\\n\", bh.board_serial_number);\n \n for (chn=0 ; chn<4 ; chn++) {\n chn_index[chn] = 0;\n }\n\n \/\/ read channel data\n for (chn=0 ; chn<4 ; chn++) {\n \n \/\/ read channel header\n fread(&ch, sizeof(ch), 1, f);\n if (ch.c[0] != 'C') {\n \/\/ event header found\n fseek(f, -4, SEEK_CUR);\n break;\n }\n chn_index[chn] = ch.cn[2] - '0' - 1;\n fread(&scaler, sizeof(int), 1, f);\n fread(voltage[chn], sizeof(short), 1024, f);\n }\n\n \/\/ Remove spikes\n \/\/ Wrote own function because trigger cell is not always well written in file\n \/\/ DRS4_data::RemoveSpikes(voltage, 20, 2);\n\n for (chn=0 ; chn<4 ; chn++) {\n\n int chidx = chn_index[chn];\n \n for (i=0 ; i<1024 ; i++) {\n\n float t = 0;\n for (j=0,time[b][(chidx)][i]=0 ; j<i ; j++)\n t += bin_width[b][chidx][(j+tch.trigger_cell) % 1024];\n\n time[b][chidx][i] = t;\n\n \/\/ Voltage data is encoded in units of 0.1 mV\n float v = static_cast<float>(voltage[chn][i]) \/ 10;\n waveform[b][chidx][i] = v;\n\n }\n\n float blw = 30.;\n if (chidx < 2) blw = 38;\n DRS4_data::Observables *tmpObs = WaveProcessor::ProcessOnline(time[b][chidx], waveform[b][chidx], 1024, 5., blw);\n\n obs[chn] = *tmpObs;\n\n delete tmpObs; tmpObs = NULL;\n\n\n } \/\/ Loop over channels\n \n\n events.Fill();\n\n float tref = (obs[2].Value(DRS4_data::arrivalTime) + obs[3].Value(DRS4_data::arrivalTime)) \/ 2;\n\n for (unsigned ichan=0 ; ichan<4 ; ichan++) {\n \/\/ Selection of amplitudes of at least 10 MIP in S1, S2\n if (ichan==0 && obs[ichan].Value(DRS4_data::maxVal) > 18) continue;\n if (ichan==1 && obs[ichan].Value(DRS4_data::maxVal) > 16) continue;\n for (unsigned ibin=0 ; ibin<1024 ; ibin++) {\n float t = time[b][ichan][ibin] - tref + 30.;\n float v = waveform[b][ichan][ibin] + obs[ichan].Value(DRS4_data::baseLine);\n havg[ichan]->Fill(t, v);\n }\n }\n\n\/\/ if (iEvt < 20) {\n if ( obs[0].Value(DRS4_data::baseLineRMS) > 1\n || obs[1].Value(DRS4_data::baseLineRMS) > 1\n || obs[2].Value(DRS4_data::baseLineRMS) > 1\n || obs[3].Value(DRS4_data::baseLineRMS) > 1 )\n \/* if ( obs[0].Value(DRS4_data::arrivalTime) < 42.\n || obs[0].Value(DRS4_data::arrivalTime) > 52.\n || obs[1].Value(DRS4_data::arrivalTime) < 41.\n || obs[1].Value(DRS4_data::arrivalTime) > 51. )*\/\n {\n\n for (unsigned ichan=0; ichan<4; ichan++) {\n TGraph *gr = new TGraph(1024, time[b][ichan], waveform[b][ichan]);\n\n if (gr->IsZombie()) {\n printf(\"Zombie.\\n\");\n exit(0);\n }\n c.cd(ichan+1);\n frame.SetTitle(Form(\"Ch. %d, baseline RMS %.1f, evt. %d\", ichan+1, obs[ichan].Value(DRS4_data::baseLineRMS), iEvt));\n frame.DrawCopy();\n gr->SetLineColor(kRed);\n gr->SetLineWidth(1);\n gr->Draw(\"l\");\n }\n\n if (firstpage) {\n c.Print(TString(pdfname + \"(\").Data());\n firstpage = false;\n }\n else {\n c.Print(pdfname.Data());\n }\n } \/\/ if printing pdf\n\n } \/\/ Loop over the boards\n } \/\/ Loop over events\n \n c.Print(TString(pdfname + \")\").Data());\n file.Write();\n file.Close();\n\n\n return 1;\n}\n\n<commit_msg>Subtraction of common baseline drift in drs4analysis. Option to switch spike removal on and off.<commit_after>\/*\n Name: drs4analysis\n Based on read_binary.cpp by Stefan Ritt <stefan.ritt@psi.ch>\n\n Purpose: analyse data saved by drs4daq\n \n The present version only plots the oscillograms from all 4 channels\n in a pdf file.\n*\/\n\n#include <stdio.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n#include <math.h>\n\n#include \"TGraph.h\"\n#include \"TH1F.h\"\n#include \"TFile.h\"\n#include \"TTree.h\"\n#include \"TCanvas.h\"\n#include \"TStyle.h\"\n#include \"TString.h\"\n\n#include \"WaveProcessor.h\"\n#include \"DRS4_data.h\"\n\n\ntypedef struct {\n char tag[3];\n char version;\n} FHEADER;\n\ntypedef struct {\n char time_header[4];\n} THEADER;\n\ntypedef struct {\n char bn[2];\n unsigned short board_serial_number;\n} BHEADER;\n\ntypedef struct {\n char event_header[4];\n unsigned int event_serial_number;\n unsigned short year;\n unsigned short month;\n unsigned short day;\n unsigned short hour;\n unsigned short minute;\n unsigned short second;\n unsigned short millisecond;\n unsigned short range;\n} EHEADER;\n\ntypedef struct {\n char tc[2];\n unsigned short trigger_cell;\n} TCHEADER;\n\ntypedef struct {\n char c[1];\n char cn[3];\n} CHEADER;\n\n\/*-----------------------------------------------------------------------------*\/\n\nint main(int argc, const char * argv[])\n{\n FHEADER fh;\n THEADER th;\n BHEADER bh;\n EHEADER eh;\n TCHEADER tch;\n CHEADER ch;\n \n unsigned int scaler;\n int16_t voltage[4][1024];\n float waveform[16][4][1024], time[16][4][1024];\n float bin_width[16][4][1024];\n int i, j, b, chn, iEvt, n_boards;\n int chn_index[4];\n double t1, t2, dt;\n TString infilename, cmfilename;\n\n int ndt;\n double threshold, sumdt, sumdt2;\n \n if (argc > 1) infilename = argv[1];\n else {\n printf(\"Usage: drs4analysis <filename> <remove spikes (1|0)> [<common mode file name>]\\n\");\n return 0;\n }\n bool removeSpikes = false;\n if (argc > 2) removeSpikes = atoi(argv[2]);\n if (argc > 3) cmfilename = argv[3];\n else cmfilename = \"BaseLine_CommonMode.root\";\n \n \/\/ open the binary waveform file\n FILE *f = fopen(infilename.Data(), \"rb\");\n if (f == NULL) {\n printf(\"Cannot find file \\'%s\\'\\n\", infilename.Data());\n return 0;\n }\n\n \/\/ read file header\n fread(&fh, sizeof(fh), 1, f);\n if (fh.tag[0] != 'D' || fh.tag[1] != 'R' || fh.tag[2] != 'S') {\n printf(\"Found invalid file header in file \\'%s\\', aborting.\\n\", infilename.Data());\n return 0;\n }\n \n if (fh.version != '2' && fh.version != '4') {\n printf(\"Found invalid file version \\'%c\\' in file \\'%s\\', should be \\'2\\' or \\'4\\', aborting.\\n\",\n fh.version, infilename.Data());\n return 0;\n }\n\n \/\/ read time header\n fread(&th, sizeof(th), 1, f);\n if (memcmp(th.time_header, \"TIME\", 4) != 0) {\n printf(\"Invalid time header in file \\'%s\\', aborting.\\n\", infilename.Data());\n return 0;\n }\n\n for (b = 0 ; ; b++) {\n \/\/ read board header\n fread(&bh, sizeof(bh), 1, f);\n if (memcmp(bh.bn, \"B#\", 2) != 0) {\n \/\/ probably event header found\n fseek(f, -4, SEEK_CUR);\n break;\n }\n \n printf(\"Found data for board #%d\\n\", bh.board_serial_number);\n \n \/\/ read time bin widths\n memset(bin_width[b], sizeof(bin_width[0]), 0);\n for (chn=0 ; chn<5 ; chn++) {\n fread(&ch, sizeof(ch), 1, f);\n if (ch.c[0] != 'C') {\n \/\/ event header found\n fseek(f, -4, SEEK_CUR);\n break;\n }\n i = ch.cn[2] - '0' - 1;\n printf(\"Found timing calibration for channel #%d\\n\", i+1);\n fread(&bin_width[b][i][0], sizeof(float), 1024, f);\n \/\/ fix for 2048 bin mode: double channel\n if (bin_width[b][i][1023] > 10 || bin_width[b][i][1023] < 0.01) {\n for (j=0 ; j<512 ; j++)\n bin_width[b][i][j+512] = bin_width[b][i][j];\n }\n }\n }\n n_boards = b;\n \n \/\/ initialize statistics\n ndt = 0;\n sumdt = sumdt2 = 0;\n \n \/*** Prepare oscillogram plots ***\/\n TCanvas c(\"can\", \"cancan\", 800, 600);\n gStyle->SetPaperSize(18, 12);\n gStyle->SetLabelSize(0.06, \"XY\");\n gStyle->SetTitleSize(0.06, \"XY\");\n gStyle->SetPadLeftMargin(0.12);\n gStyle->SetPadBottomMargin(0.12);\n c.Divide(2, 2, .01, .01);\n c.GetPad(1)->SetGrid(1, 0);\n c.GetPad(2)->SetGrid(1, 0);\n c.GetPad(3)->SetGrid(1, 0);\n c.GetPad(4)->SetGrid(1, 0);\n TH1F frame(\"frame\", \"frame; t (ns); A (mV)\", 10, 0., 200);\n frame.SetMinimum(-500);\n frame.SetMaximum(50);\n frame.SetLineColor(kGray);\n frame.SetStats(false);\n TString pdfname(infilename);\n if (pdfname.EndsWith(\".dat\")) pdfname.Resize(pdfname.Sizeof() - 5);\n pdfname += \".pdf\";\n bool firstpage = true, lastpage = false;\n\n \/*** Prepare average waveforms ***\/\n\n TFile cmHistos(cmfilename.Data());\n if (!cmHistos.IsOpen()) {\n std::cout << \"Error: Cannot open file \" << cmfilename.Data() << \".\\n\";\n return -1;\n }\n TH1F *hcm[2] = { NULL, NULL};\n cmHistos.GetObject(\"havg_S1\", hcm[0]);\n hcm[0]->SetName(\"commonModeCH1\");\n cmHistos.GetObject(\"havg_S2\", hcm[1]);\n hcm[1]->SetName(\"commonModeCH2\");\n if (!hcm[0] || !hcm[1]) {\n std::cout << \"Error: Cannot read common mode histograms \\'havg_S1\\' and \\'havg_S2\\' from file \"\n << cmfilename.Data() << \".\\n\";\n return -2;\n }\n\n\n \/*** Prepare tree and output histos ***\/\n\n TString rfname(infilename);\n if (rfname.EndsWith(\".dat\")) rfname.Resize(pdfname.Sizeof() - 5);\n rfname += \".root\";\n TFile file(rfname, \"RECREATE\");\n\n TH1F *havg[4];\n for (int ich=0; ich<4; ich++) {\n havg[ich] = new TH1F(Form(\"havg_S%d\", ich+1), \"Average waveform; t (ns); A (mV)\", 1000, 0., 200.);\n }\n\n unsigned nCh = 4;\n DRS4_data::Observables obs[nCh];\n TTree events(\"events\", \"events\");\n\n for (unsigned iCh=0; iCh<nCh; iCh++) {\n\n for (unsigned iObs=0; iObs<DRS4_data::nObservables; iObs++) {\n const char *varname = Form(\"%s_S%d\", obs[iCh].Name(DRS4_data::kObservables(iObs)), iCh+1);\n events.Branch(varname, &obs[iCh].Value(DRS4_data::kObservables(iObs)), varname);\n }\n }\n\n \/\/ loop over all events in the data file\n for (iEvt=0 ; iEvt<100000; iEvt++) {\n \/\/ read event header\n i = (int)fread(&eh, sizeof(eh), 1, f);\n if (i < 1)\n break;\n\n if (iEvt%100 == 0) {\n printf(\"Found event #%d at %d s %d ms\\n\", eh.event_serial_number, eh.second, eh.millisecond);\n }\n \n \/\/ loop over all boards in data file\n for (b=0 ; b<n_boards ; b++) {\n \n \/\/ read board header\n fread(&bh, sizeof(bh), 1, f);\n if (memcmp(bh.bn, \"B#\", 2) != 0) {\n printf(\"Invalid board header in file \\'%s\\', aborting.\\n\", infilename.Data());\n return 0;\n }\n \n \/\/ read trigger cell\n fread(&tch, sizeof(tch), 1, f);\n if (memcmp(tch.tc, \"T#\", 2) != 0) {\n printf(\"Invalid trigger cell header in file \\'%s\\', aborting.\\n\", infilename.Data());\n return 0;\n }\n\n if (n_boards > 1)\n printf(\"Found data for board #%d\\n\", bh.board_serial_number);\n \n for (chn=0 ; chn<4 ; chn++) {\n chn_index[chn] = 0;\n }\n\n \/\/ read channel data\n for (chn=0 ; chn<4 ; chn++) {\n \n \/\/ read channel header\n fread(&ch, sizeof(ch), 1, f);\n if (ch.c[0] != 'C') {\n \/\/ event header found\n fseek(f, -4, SEEK_CUR);\n break;\n }\n chn_index[chn] = ch.cn[2] - '0' - 1;\n fread(&scaler, sizeof(int), 1, f);\n fread(voltage[chn], sizeof(short), 1024, f);\n }\n\n \/\/ Remove spikes\n \/\/ Wrote own function because trigger cell is not always well written in file\n if (removeSpikes) DRS4_data::RemoveSpikes(voltage, 20, 2);\n\n for (chn=0 ; chn<4 ; chn++) {\n\n int chidx = chn_index[chn];\n \n for (i=0 ; i<1024 ; i++) {\n\n float t = 0;\n for (j=0,time[b][(chidx)][i]=0 ; j<i ; j++)\n t += bin_width[b][chidx][(j+tch.trigger_cell) % 1024];\n\n time[b][chidx][i] = t;\n\n \/\/ Voltage data is encoded in units of 0.1 mV\n float v = static_cast<float>(voltage[chn][i]) \/ 10;\n waveform[b][chidx][i] = v;\n\n }\n\n float blw = 30.;\n if (chidx < 2) blw = 38;\n DRS4_data::Observables *tmpObs = WaveProcessor::ProcessOnline(time[b][chidx], waveform[b][chidx], 1024, 5., blw);\n\n obs[chn] = *tmpObs;\n\n delete tmpObs; tmpObs = NULL;\n\n\n } \/\/ Loop over channels\n \n\n events.Fill();\n\n float tref = (obs[2].Value(DRS4_data::arrivalTime) + obs[3].Value(DRS4_data::arrivalTime)) \/ 2;\n\n for (unsigned ichan=0 ; ichan<4 ; ichan++) {\n \/\/ Selection of amplitudes of at least 10 MIP in S1, S2\n if (ichan==0 && obs[ichan].Value(DRS4_data::maxVal) > 18) continue;\n if (ichan==1 && obs[ichan].Value(DRS4_data::maxVal) > 16) continue;\n for (unsigned ibin=0 ; ibin<1024 ; ibin++) {\n float t = time[b][ichan][ibin] - tref + 30.;\n float v = waveform[b][ichan][ibin] + obs[ichan].Value(DRS4_data::baseLine);\n havg[ichan]->Fill(t, v);\n }\n }\n\n\/\/ if (iEvt < 20) {\n if ( obs[0].Value(DRS4_data::baseLineRMS) > 1\n || obs[1].Value(DRS4_data::baseLineRMS) > 1\n || obs[2].Value(DRS4_data::baseLineRMS) > 1\n || obs[3].Value(DRS4_data::baseLineRMS) > 1 )\n \/* if ( obs[0].Value(DRS4_data::arrivalTime) < 42.\n || obs[0].Value(DRS4_data::arrivalTime) > 52.\n || obs[1].Value(DRS4_data::arrivalTime) < 41.\n || obs[1].Value(DRS4_data::arrivalTime) > 51. )*\/\n {\n\n for (unsigned ichan=0; ichan<4; ichan++) {\n TGraph *gr = new TGraph(1024, time[b][ichan], waveform[b][ichan]);\n\n if (gr->IsZombie()) {\n printf(\"Zombie.\\n\");\n exit(0);\n }\n c.cd(ichan+1);\n frame.SetTitle(Form(\"Ch. %d, baseline RMS %.1f, evt. %d\", ichan+1, obs[ichan].Value(DRS4_data::baseLineRMS), iEvt));\n frame.DrawCopy();\n gr->SetLineColor(kRed);\n gr->SetLineWidth(1);\n gr->Draw(\"l\");\n }\n\n if (firstpage) {\n c.Print(TString(pdfname + \"(\").Data());\n firstpage = false;\n }\n else {\n c.Print(pdfname.Data());\n }\n } \/\/ if printing pdf\n\n } \/\/ Loop over the boards\n } \/\/ Loop over events\n \n std::cout << \"Counted \" << iEvt << \" events. Event tree has \" << events.GetEntries() << \" entries.\\n\";\n\n c.Print(TString(pdfname + \")\").Data());\n for (int ich=0; ich<4; ich++) {\n havg[ich]->Scale(1.\/iEvt);\n if (ich<2) {\n havg[ich]->Add(hcm[ich], -1.);\n }\n }\n file.Write();\n file.Close();\n\n cmHistos.Close();\n\n return 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_TEST_PROLONGATIONS_L2_HH\n#define DUNE_GDT_TEST_PROLONGATIONS_L2_HH\n\n#include <dune\/common\/unused.hh>\n\n#include <dune\/gdt\/prolongations\/l2.hh>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Test {\n\n\ntemplate <class SpaceType>\nstruct L2ProlongationLocalizableOperatorTest\n : public LocalizableProlongationOperatorBase<SpaceType, SpaceType, L2ProlongationLocalizableOperator>\n{\n typedef LocalizableProlongationOperatorBase<SpaceType, SpaceType, L2ProlongationLocalizableOperator> BaseType;\n using typename BaseType::ProlongationOperatorType;\n\n void constructible_by_ctor(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n const auto& source = this->coarse_discrete_function_;\n auto& range = this->fine_discrete_function_;\n\n ProlongationOperatorType DUNE_UNUSED(w_over_integrate)(0, grid_view, source, range);\n ProlongationOperatorType DUNE_UNUSED(wo_over_integrate)(grid_view, source, range);\n } \/\/ ... constructible_by_ctor(...)\n\n void constructible_by_factory(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n const auto& source = this->coarse_discrete_function_;\n auto& range = this->fine_discrete_function_;\n\n auto DUNE_UNUSED(w_gv_w_oi) = make_global_l2_prolongation_localizable_operator(grid_view, source, range, 1);\n auto DUNE_UNUSED(w_gv_wo_oi) = make_global_l2_prolongation_localizable_operator(grid_view, source, range);\n auto DUNE_UNUSED(wo_gv_w_oi) = make_global_l2_prolongation_localizable_operator(source, range, 1);\n auto DUNE_UNUSED(wo_gv_wo_oi) = make_global_l2_prolongation_localizable_operator(source, range);\n } \/\/ ... constructible_by_factory(...)\n};\n\n\ntemplate <class SpaceType>\nstruct L2ProlongationOperatorTest : public ProlongationOperatorBase<SpaceType, SpaceType, L2ProlongationOperator>\n{\n typedef ProlongationOperatorBase<SpaceType, SpaceType, L2ProlongationOperator> BaseType;\n using typename BaseType::ProlongationOperatorType;\n\n void constructible_by_ctor(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n const auto& source = this->coarse_discrete_function_;\n auto& range = this->fine_discrete_function_;\n\n ProlongationOperatorType DUNE_UNUSED(w_over_integrate)(0, grid_view);\n ProlongationOperatorType DUNE_UNUSED(wo_over_integrate)(grid_view);\n } \/\/ ... constructible_by_ctor(...)\n\n void constructible_by_factory(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n\n auto DUNE_UNUSED(w_over_integrate) = make_l2_prolongation_operator(grid_view, 1);\n auto DUNE_UNUSED(wo_over_integrate) = make_l2_prolongation_operator(grid_view);\n } \/\/ ... constructible_by_factory(...)\n\n void free_function_callable(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n const auto& source = this->coarse_discrete_function_;\n auto& range = this->fine_discrete_function_;\n\n prolong_l2(grid_view, source, range);\n prolong_l2(source, range);\n } \/\/ ... free_function_callable(...)\n};\n\n\n} \/\/ namespace Test\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_TEST_PROLONGATIONS_L2_HH\n<commit_msg>[test.prolongations.l2] add more signatures of prolong_l2<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_TEST_PROLONGATIONS_L2_HH\n#define DUNE_GDT_TEST_PROLONGATIONS_L2_HH\n\n#include <dune\/common\/unused.hh>\n\n#include <dune\/gdt\/prolongations\/l2.hh>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Test {\n\n\ntemplate <class SpaceType>\nstruct L2ProlongationLocalizableOperatorTest\n : public LocalizableProlongationOperatorBase<SpaceType, SpaceType, L2ProlongationLocalizableOperator>\n{\n typedef LocalizableProlongationOperatorBase<SpaceType, SpaceType, L2ProlongationLocalizableOperator> BaseType;\n using typename BaseType::ProlongationOperatorType;\n\n void constructible_by_ctor(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n const auto& source = this->coarse_discrete_function_;\n auto& range = this->fine_discrete_function_;\n\n ProlongationOperatorType DUNE_UNUSED(w_over_integrate)(0, grid_view, source, range);\n ProlongationOperatorType DUNE_UNUSED(wo_over_integrate)(grid_view, source, range);\n } \/\/ ... constructible_by_ctor(...)\n\n void constructible_by_factory(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n const auto& source = this->coarse_discrete_function_;\n auto& range = this->fine_discrete_function_;\n\n auto DUNE_UNUSED(w_gv_w_oi) = make_global_l2_prolongation_localizable_operator(grid_view, source, range, 1);\n auto DUNE_UNUSED(w_gv_wo_oi) = make_global_l2_prolongation_localizable_operator(grid_view, source, range);\n auto DUNE_UNUSED(wo_gv_w_oi) = make_global_l2_prolongation_localizable_operator(source, range, 1);\n auto DUNE_UNUSED(wo_gv_wo_oi) = make_global_l2_prolongation_localizable_operator(source, range);\n } \/\/ ... constructible_by_factory(...)\n};\n\n\ntemplate <class SpaceType>\nstruct L2ProlongationOperatorTest : public ProlongationOperatorBase<SpaceType, SpaceType, L2ProlongationOperator>\n{\n typedef ProlongationOperatorBase<SpaceType, SpaceType, L2ProlongationOperator> BaseType;\n using typename BaseType::ProlongationOperatorType;\n\n void constructible_by_ctor(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n const auto& source = this->coarse_discrete_function_;\n auto& range = this->fine_discrete_function_;\n\n ProlongationOperatorType DUNE_UNUSED(w_over_integrate)(0, grid_view);\n ProlongationOperatorType DUNE_UNUSED(wo_over_integrate)(grid_view);\n } \/\/ ... constructible_by_ctor(...)\n\n void constructible_by_factory(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n\n auto DUNE_UNUSED(w_over_integrate) = make_l2_prolongation_operator(grid_view, 1);\n auto DUNE_UNUSED(wo_over_integrate) = make_l2_prolongation_operator(grid_view);\n } \/\/ ... constructible_by_factory(...)\n\n void free_function_callable(const double tolerance = 1e-15)\n {\n this->prepare(tolerance);\n\n auto grid_view = this->fine_space_.grid_view();\n const auto& source = this->coarse_discrete_function_;\n auto& range = this->fine_discrete_function_;\n\n prolong_l2(grid_view, source, range, 1);\n prolong_l2(grid_view, source, range);\n prolong_l2(source, range, 1);\n prolong_l2(source, range);\n } \/\/ ... free_function_callable(...)\n};\n\n\n} \/\/ namespace Test\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_TEST_PROLONGATIONS_L2_HH\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Control: fixed a bug in control.<commit_after><|endoftext|>"} {"text":"<commit_before>#include <MutilaDebug.h>\n#include <stdint.h>\n#include \"SmallTextMode.h\"\n#include \"Matrix.h\"\n\nSmallTextMode_ SmallTextMode;\n\nvoid SmallTextMode_::start(const char* data)\n{\n DB(F(\"SmallTextMode::start \"));\n DBLN(data);\n String line[3];\n uint8_t lineCount = 1;\n for (uint8_t i=0; i<strlen(data); i++) {\n DB(\"in: \");\n DB(data[i]);\n DB(\" (int)\");\n DBLN((int)data[i]);\n if (data[i] == '\\r' && lineCount<3) {\n DBLN(\"newline\");\n lineCount++;\n continue;\n }\n DB(\"append:\");\n DB(data[i]);\n DB(\" (int)\");\n DBLN((int)data[i]);\n line[lineCount-1] += data[i];\n }\n DB(\"lines=\");\n DBLN(lineCount);\n for (uint8_t i=0; i<lineCount; i++) {\n DB(i);\n DB('=');\n DBLN(line[i]);\n }\n \n uint8_t y;\n if (lineCount == 1) y = 18;\n else if (lineCount == 2) y = 14;\n else y = 10;\n\n Matrix.clear();\n Matrix.setFont(2);\n for (uint8_t i=0; i<lineCount; i++) {\n Matrix.text(MATRIX_ORANGE, 1, y, line[i]);\n y += 8;\n }\n Matrix.paint();\n}\n\n<commit_msg>add alternative newline characters<commit_after>#include <MutilaDebug.h>\n#include <stdint.h>\n#include \"SmallTextMode.h\"\n#include \"Matrix.h\"\n\nSmallTextMode_ SmallTextMode;\n\nvoid SmallTextMode_::start(const char* data)\n{\n DB(F(\"SmallTextMode::start \"));\n DBLN(data);\n String line[3];\n uint8_t lineCount = 1;\n for (uint8_t i=0; i<strlen(data); i++) {\n DB(\"in: \");\n DB(data[i]);\n DB(\" (int)\");\n DBLN((int)data[i]);\n if ((data[i] == '\\r' || data[i] == '\\n' || data[i] == '|') && lineCount<3) {\n DBLN(\"newline\");\n lineCount++;\n continue;\n }\n DB(\"append:\");\n DB(data[i]);\n DB(\" (int)\");\n DBLN((int)data[i]);\n line[lineCount-1] += data[i];\n }\n DB(\"lines=\");\n DBLN(lineCount);\n for (uint8_t i=0; i<lineCount; i++) {\n DB(i);\n DB('=');\n DBLN(line[i]);\n }\n \n uint8_t y;\n if (lineCount == 1) y = 18;\n else if (lineCount == 2) y = 14;\n else y = 10;\n\n Matrix.clear();\n Matrix.setFont(2);\n for (uint8_t i=0; i<lineCount; i++) {\n Matrix.text(MATRIX_ORANGE, 1, y, line[i]);\n y += 8;\n }\n Matrix.paint();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <fnord-base\/stringutil.h>\n#include <fnord-base\/exception.h>\n#include <fnord-base\/inspect.h>\n#include <fnord-msg\/MessageSchema.h>\n#include <fnord-msg\/CodingOptions.pb.h>\n#include <fnord-msg\/msg.h>\n\nnamespace fnord {\nnamespace msg {\n\nRefPtr<MessageSchema> MessageSchema::fromProtobuf(\n const google::protobuf::Descriptor* dsc) {\n Vector<msg::MessageSchemaField> fields;\n\n auto nfields = dsc->field_count();\n for (size_t i = 0; i < nfields; ++i) {\n auto field = dsc->field(i);\n\n CodingOptions coding;\n\n auto fopts_str = field->options().SerializeAsString();\n if (!fopts_str.empty()) {\n coding = msg::decode<CodingOptions>(fopts_str.substr(2)); \/\/ FIXPAUL HACK!!! ;)\n }\n\n EncodingHint enc_hint = EncodingHint::NONE;\n if (coding.encoding() == \"BITPACK\") enc_hint = EncodingHint::BITPACK;\n if (coding.encoding() == \"LEB128\") enc_hint = EncodingHint::LEB128;\n\n switch (field->type()) {\n\n case google::protobuf::FieldDescriptor::TYPE_BOOL:\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::BOOLEAN,\n 0,\n field->is_repeated(),\n field->is_optional(),\n enc_hint);\n break;\n\n case google::protobuf::FieldDescriptor::TYPE_STRING:\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::STRING,\n coding.has_maxval() ? coding.maxval() : 0xffffffff,\n field->is_repeated(),\n field->is_optional(),\n enc_hint);\n break;\n\n case google::protobuf::FieldDescriptor::TYPE_UINT64:\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::UINT64,\n coding.has_maxval() ?\n coding.maxval() : std::numeric_limits<uint64_t>::max(),\n field->is_repeated(),\n field->is_optional(),\n enc_hint);\n break;\n\n case google::protobuf::FieldDescriptor::TYPE_UINT32:\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::UINT32,\n coding.has_maxval() ?\n coding.maxval() : std::numeric_limits<uint32_t>::max(),\n field->is_repeated(),\n field->is_optional(),\n enc_hint);\n break;\n\n case google::protobuf::FieldDescriptor::TYPE_ENUM: {\n size_t maxval = 0;\n auto enum_dsc = field->enum_type();\n auto nvals = enum_dsc->value_count();\n for (int j = 0; j < nvals; ++j) {\n auto enum_val = enum_dsc->value(j);\n if (enum_val->number() > maxval) {\n maxval = enum_val->number();\n }\n }\n\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::UINT64,\n maxval,\n field->is_repeated(),\n field->is_optional());\n break;\n }\n\n case google::protobuf::FieldDescriptor::TYPE_MESSAGE:\n fields.emplace_back(\n MessageSchemaField::mkObjectField(\n field->number(),\n field->name(),\n field->is_repeated(),\n field->is_optional(),\n MessageSchema::fromProtobuf(field->message_type())));\n break;\n\n default:\n RAISEF(\n kNotImplementedError,\n \"field type not implemented: $0\",\n field->type_name());\n\n }\n }\n\n return new msg::MessageSchema(dsc->full_name(), fields);\n}\n\nstatic void schemaNodeToString(\n size_t level,\n const MessageSchemaField& field,\n String* str) {\n String ws(level * 2, ' ');\n String type_name;\n String attrs;\n\n String type_prefix = \"\";\n String type_suffix = \"\";\n\n if (field.optional) {\n type_prefix += \"optional[\";\n type_suffix += \"]\";\n }\n\n if (field.repeated) {\n type_prefix += \"list[\";\n type_suffix += \"]\";\n }\n\n switch (field.type) {\n\n case FieldType::OBJECT:\n str->append(StringUtil::format(\n \"$0$1object$2 $3 = $4 {\\n\",\n ws,\n type_prefix,\n type_suffix,\n field.name,\n field.id));\n\n for (const auto& f : field.schema->fields()) {\n schemaNodeToString(level + 1, f, str);\n }\n\n str->append(ws + \"}\\n\");\n return;\n\n case FieldType::BOOLEAN:\n type_name = \"bool\";\n break;\n\n case FieldType::UINT32:\n type_name = \"uint32\";\n attrs += StringUtil::format(\" @maxval=$0\", field.type_size);\n break;\n\n case FieldType::UINT64:\n type_name = \"uint64\";\n attrs += StringUtil::format(\" @maxval=$0\", field.type_size);\n break;\n\n case FieldType::STRING:\n type_name = \"string\";\n attrs += StringUtil::format(\" @maxlen=$0\", field.type_size);\n break;\n\n }\n\n switch (field.encoding) {\n\n case EncodingHint::NONE:\n break;\n\n case EncodingHint::BITPACK:\n attrs += \" @encoding=BITPACK\";\n break;\n\n case EncodingHint::LEB128:\n attrs += \" @encoding=LEB128\";\n break;\n\n }\n\n\n str->append(StringUtil::format(\n \"$0$1$2$3 $4 = $5$6;\\n\",\n ws,\n type_prefix,\n type_name,\n type_suffix,\n field.name,\n field.id,\n attrs));\n}\n\nMessageSchemaField MessageSchemaField::mkObjectField(\n uint32_t id,\n String name,\n bool repeated,\n bool optional,\n RefPtr<msg::MessageSchema> schema) {\n MessageSchemaField field(\n id,\n name,\n FieldType::OBJECT,\n 0,\n repeated,\n optional);\n\n field.schema = schema;\n return field;\n}\n\nMessageSchema::MessageSchema(\n const String& name,\n Vector<MessageSchemaField> fields) :\n name_(name),\n fields_(fields) {\n for (const auto& field : fields_) {\n field_ids_.emplace(field.name, field.id);\n field_types_.emplace(field.id, field.type);\n field_names_.emplace(field.id, field.name);\n }\n}\n\nMessageSchema::MessageSchema(const MessageSchema& other) :\n name_(other.name_),\n fields_(other.fields_),\n field_ids_(other.field_ids_),\n field_types_(other.field_types_),\n field_names_(other.field_names_) {}\n\nconst String& MessageSchema::name() const {\n return name_;\n}\n\nconst Vector<MessageSchemaField>& MessageSchema::fields() const {\n return fields_;\n}\n\nString MessageSchema::toString() const {\n String str = StringUtil::format(\"object $0 {\\n\", name_);\n\n for (const auto& f : fields_) {\n schemaNodeToString(1, f, &str);\n }\n\n str += \"}\";\n return str;\n}\n\nuint32_t MessageSchema::fieldId(const String& path) const {\n auto id = field_ids_.find(path);\n if (id == field_ids_.end()) {\n RAISEF(kIndexError, \"field not found: $0\", path);\n } else {\n return id->second;\n }\n}\n\nFieldType MessageSchema::fieldType(uint32_t id) const {\n if (id == 0) {\n return FieldType::OBJECT;\n }\n\n auto type = field_types_.find(id);\n if (type == field_types_.end()) {\n RAISEF(kIndexError, \"field not found: $0\", id);\n } else {\n return type->second;\n }\n}\n\nconst String& MessageSchema::fieldName(uint32_t id) const {\n if (id == 0) {\n return name_;\n }\n\n auto name = field_names_.find(id);\n if (name == field_names_.end()) {\n RAISEF(kIndexError, \"field not found: $0\", id);\n } else {\n return name->second;\n }\n}\n\nRefPtr<MessageSchema> MessageSchema::fieldSchema(uint32_t id) const {\n for (const auto& field : fields_) {\n if (field.id == id) {\n return field.schema;\n }\n }\n\n RAISEF(kIndexError, \"field not found: $0\", id);\n}\n\nSet<String> MessageSchema::columns() const {\n Set<String> columns;\n\n for (const auto& c : field_names_) {\n columns.emplace(c.second);\n }\n\n return columns;\n}\n\nRefPtr<MessageSchema> MessageSchemaRepository::getSchema(\n const String& name) const {\n auto iter = schemas_.find(name);\n if (iter == schemas_.end()) {\n RAISEF(kRuntimeError, \"schema not found: '$0'\", name);\n }\n\n return iter->second;\n}\n\nvoid MessageSchemaRepository::registerSchema(RefPtr<MessageSchema> schema) {\n schemas_.emplace(schema->name(), schema);\n}\n\n} \/\/ namespace msg\n} \/\/ namespace fnord\n<commit_msg>remove hack<commit_after>\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <fnord-base\/stringutil.h>\n#include <fnord-base\/exception.h>\n#include <fnord-base\/inspect.h>\n#include <fnord-msg\/MessageSchema.h>\n#include <fnord-msg\/CodingOptions.pb.h>\n#include <fnord-msg\/msg.h>\n\nnamespace fnord {\nnamespace msg {\n\nRefPtr<MessageSchema> MessageSchema::fromProtobuf(\n const google::protobuf::Descriptor* dsc) {\n Vector<msg::MessageSchemaField> fields;\n\n auto nfields = dsc->field_count();\n for (size_t i = 0; i < nfields; ++i) {\n auto field = dsc->field(i);\n\n CodingOptions copts = field->options().GetExtension(coding);\n\n EncodingHint enc_hint = EncodingHint::NONE;\n if (copts.encoding() == \"BITPACK\") enc_hint = EncodingHint::BITPACK;\n if (copts.encoding() == \"LEB128\") enc_hint = EncodingHint::LEB128;\n\n switch (field->type()) {\n\n case google::protobuf::FieldDescriptor::TYPE_BOOL:\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::BOOLEAN,\n 0,\n field->is_repeated(),\n field->is_optional(),\n enc_hint);\n break;\n\n case google::protobuf::FieldDescriptor::TYPE_STRING:\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::STRING,\n copts.has_maxval() ? copts.maxval() : 0xffffffff,\n field->is_repeated(),\n field->is_optional(),\n enc_hint);\n break;\n\n case google::protobuf::FieldDescriptor::TYPE_UINT64:\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::UINT64,\n copts.has_maxval() ?\n copts.maxval() : std::numeric_limits<uint64_t>::max(),\n field->is_repeated(),\n field->is_optional(),\n enc_hint);\n break;\n\n case google::protobuf::FieldDescriptor::TYPE_UINT32:\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::UINT32,\n copts.has_maxval() ?\n copts.maxval() : std::numeric_limits<uint32_t>::max(),\n field->is_repeated(),\n field->is_optional(),\n enc_hint);\n break;\n\n case google::protobuf::FieldDescriptor::TYPE_ENUM: {\n size_t maxval = 0;\n auto enum_dsc = field->enum_type();\n auto nvals = enum_dsc->value_count();\n for (int j = 0; j < nvals; ++j) {\n auto enum_val = enum_dsc->value(j);\n if (enum_val->number() > maxval) {\n maxval = enum_val->number();\n }\n }\n\n fields.emplace_back(\n field->number(),\n field->name(),\n msg::FieldType::UINT64,\n maxval,\n field->is_repeated(),\n field->is_optional());\n break;\n }\n\n case google::protobuf::FieldDescriptor::TYPE_MESSAGE:\n fields.emplace_back(\n MessageSchemaField::mkObjectField(\n field->number(),\n field->name(),\n field->is_repeated(),\n field->is_optional(),\n MessageSchema::fromProtobuf(field->message_type())));\n break;\n\n default:\n RAISEF(\n kNotImplementedError,\n \"field type not implemented: $0\",\n field->type_name());\n\n }\n }\n\n return new msg::MessageSchema(dsc->full_name(), fields);\n}\n\nstatic void schemaNodeToString(\n size_t level,\n const MessageSchemaField& field,\n String* str) {\n String ws(level * 2, ' ');\n String type_name;\n String attrs;\n\n String type_prefix = \"\";\n String type_suffix = \"\";\n\n if (field.optional) {\n type_prefix += \"optional[\";\n type_suffix += \"]\";\n }\n\n if (field.repeated) {\n type_prefix += \"list[\";\n type_suffix += \"]\";\n }\n\n switch (field.type) {\n\n case FieldType::OBJECT:\n str->append(StringUtil::format(\n \"$0$1object$2 $3 = $4 {\\n\",\n ws,\n type_prefix,\n type_suffix,\n field.name,\n field.id));\n\n for (const auto& f : field.schema->fields()) {\n schemaNodeToString(level + 1, f, str);\n }\n\n str->append(ws + \"}\\n\");\n return;\n\n case FieldType::BOOLEAN:\n type_name = \"bool\";\n break;\n\n case FieldType::UINT32:\n type_name = \"uint32\";\n attrs += StringUtil::format(\" @maxval=$0\", field.type_size);\n break;\n\n case FieldType::UINT64:\n type_name = \"uint64\";\n attrs += StringUtil::format(\" @maxval=$0\", field.type_size);\n break;\n\n case FieldType::STRING:\n type_name = \"string\";\n attrs += StringUtil::format(\" @maxlen=$0\", field.type_size);\n break;\n\n }\n\n switch (field.encoding) {\n\n case EncodingHint::NONE:\n break;\n\n case EncodingHint::BITPACK:\n attrs += \" @encoding=BITPACK\";\n break;\n\n case EncodingHint::LEB128:\n attrs += \" @encoding=LEB128\";\n break;\n\n }\n\n\n str->append(StringUtil::format(\n \"$0$1$2$3 $4 = $5$6;\\n\",\n ws,\n type_prefix,\n type_name,\n type_suffix,\n field.name,\n field.id,\n attrs));\n}\n\nMessageSchemaField MessageSchemaField::mkObjectField(\n uint32_t id,\n String name,\n bool repeated,\n bool optional,\n RefPtr<msg::MessageSchema> schema) {\n MessageSchemaField field(\n id,\n name,\n FieldType::OBJECT,\n 0,\n repeated,\n optional);\n\n field.schema = schema;\n return field;\n}\n\nMessageSchema::MessageSchema(\n const String& name,\n Vector<MessageSchemaField> fields) :\n name_(name),\n fields_(fields) {\n for (const auto& field : fields_) {\n field_ids_.emplace(field.name, field.id);\n field_types_.emplace(field.id, field.type);\n field_names_.emplace(field.id, field.name);\n }\n}\n\nMessageSchema::MessageSchema(const MessageSchema& other) :\n name_(other.name_),\n fields_(other.fields_),\n field_ids_(other.field_ids_),\n field_types_(other.field_types_),\n field_names_(other.field_names_) {}\n\nconst String& MessageSchema::name() const {\n return name_;\n}\n\nconst Vector<MessageSchemaField>& MessageSchema::fields() const {\n return fields_;\n}\n\nString MessageSchema::toString() const {\n String str = StringUtil::format(\"object $0 {\\n\", name_);\n\n for (const auto& f : fields_) {\n schemaNodeToString(1, f, &str);\n }\n\n str += \"}\";\n return str;\n}\n\nuint32_t MessageSchema::fieldId(const String& path) const {\n auto id = field_ids_.find(path);\n if (id == field_ids_.end()) {\n RAISEF(kIndexError, \"field not found: $0\", path);\n } else {\n return id->second;\n }\n}\n\nFieldType MessageSchema::fieldType(uint32_t id) const {\n if (id == 0) {\n return FieldType::OBJECT;\n }\n\n auto type = field_types_.find(id);\n if (type == field_types_.end()) {\n RAISEF(kIndexError, \"field not found: $0\", id);\n } else {\n return type->second;\n }\n}\n\nconst String& MessageSchema::fieldName(uint32_t id) const {\n if (id == 0) {\n return name_;\n }\n\n auto name = field_names_.find(id);\n if (name == field_names_.end()) {\n RAISEF(kIndexError, \"field not found: $0\", id);\n } else {\n return name->second;\n }\n}\n\nRefPtr<MessageSchema> MessageSchema::fieldSchema(uint32_t id) const {\n for (const auto& field : fields_) {\n if (field.id == id) {\n return field.schema;\n }\n }\n\n RAISEF(kIndexError, \"field not found: $0\", id);\n}\n\nSet<String> MessageSchema::columns() const {\n Set<String> columns;\n\n for (const auto& c : field_names_) {\n columns.emplace(c.second);\n }\n\n return columns;\n}\n\nRefPtr<MessageSchema> MessageSchemaRepository::getSchema(\n const String& name) const {\n auto iter = schemas_.find(name);\n if (iter == schemas_.end()) {\n RAISEF(kRuntimeError, \"schema not found: '$0'\", name);\n }\n\n return iter->second;\n}\n\nvoid MessageSchemaRepository::registerSchema(RefPtr<MessageSchema> schema) {\n schemas_.emplace(schema->name(), schema);\n}\n\n} \/\/ namespace msg\n} \/\/ namespace fnord\n<|endoftext|>"} {"text":"<commit_before>#include \"Render.h\"\n#include \"interface\/Interface.h\"\n#include \"base\/basedef.h\"\n#include \"math\/hash.h\"\n#include <GL\/glew.h>\n\nusing fei::Render;\n\nstatic const GLchar *basicVertexShader = {\n\t\"void main()\"\n\t\"{\"\n\t\"\tgl_TexCoord[0] = gl_MultiTexCoord0;\"\n\t\"\tgl_FrontColor = gl_Color;\"\n\t\"\tgl_Position = ftransform();\"\n\t\"}\"\n};\n\nstatic const GLchar *basicFragmentShader = {\n\t\"uniform sampler2D feiTex;\"\n\t\"uniform float feiUseTex;\"\n\t\"void main() {\"\n\t\"\tvec4 color = gl_Color;\"\n\t\"\tif (feiUseTex == 1.0) {\"\n\t\"\t\tvec4 texColor = texture2D(feiTex, gl_TexCoord[0].st);\"\n\t\"\t\tif (texColor.a == 0.0 || color.a == 0.0) discard;\"\n\t\"\t\tcolor *= texColor;\"\n\t\"\t}\"\n\t\"\tgl_FragColor = color;\"\n\t\"}\"\n};\n\nRender* Render::instance = nullptr;\n\nRender* Render::getInstance()\n{\n\tif (!instance) {\n\t\tinstance = new Render();\n\t}\n\treturn instance; \n}\n\nRender::Render()\n{\n}\n\nbool Render::init()\n{\n\tif (_isLoad) return true;\n\t_isLoad = true;\n\tif (!fei::Interface::getInstance()->init()) {\n\t\t_isLoad = false;\n\t\treturn false;\n\t}\n\tGLenum err = glewInit();\n\tif (GLEW_OK != err) {\n\t\tstd::fprintf(stderr, \"GLEW Error: %s\\n\", glewGetErrorString(err));\n\t\t_isLoad = false;\n\t} else {\n\t\tstd::printf(\"GLEW Version: %s\\n\", glewGetString(GLEW_VERSION));\n\t\tstd::printf(\"OpenGL Version: %s\\n\", glGetString(GL_VERSION));\n\t\tif (GLEW_VERSION_2_0) {\n\t\t\tstd::printf(\"GLSL Version: %s\\n\", glGetString(GL_SHADING_LANGUAGE_VERSION));\n\t\t\tbasicShader.loadString(basicVertexShader, basicFragmentShader);\n\t\t\tbasicShader.push();\n\t\t} else {\n\t\t\tstd::printf(\"Shader unsupported!\\n\");\n\t\t}\n\t\tglEnable(GL_CULL_FACE);\n\t\tglCullFace(GL_FRONT);\n\t}\n\treturn _isLoad;\n}\n\nvoid Render::destroy()\n{\n\twhile (!shaderStack.empty()) {\n\t\tshaderStack.pop();\n\t}\n\tdeleteUnusedTexture();\n}\n\nvoid Render::executeBeforeFrame()\n{\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tauto shader = getShaderProgram();\n\tif (shader) {\n\t\tshader->use();\n\t}\n}\n\nvoid Render::executeAfterFrame()\n{\n\tdeleteUnusedTexture();\n}\n\nvoid Render::setViewport(const fei::Rect& viewport)\n{\n\tglViewport((GLint)viewport.getPosition().x, (GLint)viewport.getPosition().y,\n\t\t(GLsizei)viewport.getSize().x, (GLsizei)viewport.getSize().y);\n}\n\nconst fei::Rect Render::getViewport()\n{\n\tint viewport[4];\n\tglGetIntegerv(GL_VIEWPORT, viewport);\n\treturn fei::Rect((float)viewport[0], (float)viewport[1], (float)viewport[2], (float)viewport[3]);\n}\n\nvoid Render::pushShader(fei::ShaderProgram* shader)\n{\n\tif (shaderStack.empty() || shaderStack.top() != shader) {\n\t\tshaderStack.push(shader);\n\t\tshader->use();\n\t}\n}\n\nvoid Render::popShader(fei::ShaderProgram* shader)\n{\n\tif (!shaderStack.empty() && shaderStack.top() == shader) {\n\t\tshaderStack.pop();\n\t\tif (shaderStack.empty()) {\n\t\t\tglUseProgram(0);\n\t\t} else {\n\t\t\tshaderStack.top()->use();\n\t\t}\n\t}\n}\n\nfei::ShaderProgram* Render::getShaderProgram()\n{\n\tif (!shaderStack.empty()) {\n\t\treturn shaderStack.top();\n\t} else {\n\t\treturn nullptr;\n\t}\n}\n\nvoid Render::registTexture(const char* filename, GLuint id)\n{\n\tint hash = fei::bkdrHash(filename);\n\tfileTextureMap[hash] = id;\n}\n\nvoid Render::deleteTexture(GLuint id)\n{\n\tglDeleteTextures(1, &id);\n\ttextureSizeMap.erase(textureSizeMap.find(id));\n\tfor (auto it = fileTextureMap.begin(); it != fileTextureMap.end(); ++it) {\n\t\tif (it->second == id) {\n\t\t\tfileTextureMap.erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nint Render::queryTexture(const char* filename)\n{\n\tint hash = fei::bkdrHash(filename);\n\tGLuint ans = 0;\n\tauto it = fileTextureMap.find(hash);\n\tif (it != fileTextureMap.end()) {\n\t\tans = it->second;\n\t}\n\treturn ans;\n}\n\nvoid Render::registTexSize(GLuint id, const Vec2& s)\n{\n\ttextureSizeMap[id] = s;\n}\n\nconst fei::Vec2 Render::queryTexSize(GLuint id)\n{\n\treturn textureSizeMap[id];\n}\n\nvoid Render::addRefTexture(GLuint id)\n{\n\tif (!id) return;\n\ttextureRCMap[id]++;\n}\n\nvoid Render::releaseTexture(GLuint id)\n{\n\tif (!id) return;\n\ttextureRCMap[id]--;\n}\n\nvoid Render::deleteUnusedTexture()\n{\n\tfor (auto it = textureRCMap.begin(); it != textureRCMap.end();) {\n\t\tif (it->second == 0) {\n\t\t\tdeleteTexture(it->first);\n\t\t\tit = textureRCMap.erase(it);\n\t\t} else {\n\t\t\t++it;\n\t\t}\n\t}\n}\n\nvoid Render::bindTexture(GLuint tex)\n{\n\tglBindTexture(GL_TEXTURE_2D, tex);\n\tauto shader = getShaderProgram();\n\tif (shader) {\n\t\tshader->setUniform(\"feiUseTex\", 1.0f);\n\t\tshader->setUniform(\"feiTex\", (float)tex);\n\t}\n}\n\nvoid Render::drawTexQuad(const fei::Vec2& size, GLfloat* texCoord)\n{\n\tGLfloat w2 = size.x \/ 2.0f;\n\tGLfloat h2 = size.y \/ 2.0f;\n\tGLfloat vertex[] = {-w2, h2, -w2, -h2, w2, h2, w2, -h2};\n\tGLfloat defaultTexCoord[] = {0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f};\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\tglVertexPointer(2, GL_FLOAT, 0, vertex);\n\tif (texCoord) {\n\t\tglTexCoordPointer(2, GL_FLOAT, 0, texCoord);\n\t} else {\n\t\tglTexCoordPointer(2, GL_FLOAT, 0, defaultTexCoord);\n\t}\n\tglDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n}\n<commit_msg>fix namespace problem<commit_after>#include \"Render.h\"\n#include \"interface\/Interface.h\"\n#include \"base\/basedef.h\"\n#include \"math\/hash.h\"\n#include <GL\/glew.h>\n\nusing fei::Render;\n\nstatic const GLchar *basicVertexShader = {\n\t\"void main()\"\n\t\"{\"\n\t\"\tgl_TexCoord[0] = gl_MultiTexCoord0;\"\n\t\"\tgl_FrontColor = gl_Color;\"\n\t\"\tgl_Position = ftransform();\"\n\t\"}\"\n};\n\nstatic const GLchar *basicFragmentShader = {\n\t\"uniform sampler2D feiTex;\"\n\t\"uniform float feiUseTex;\"\n\t\"void main() {\"\n\t\"\tvec4 color = gl_Color;\"\n\t\"\tif (feiUseTex == 1.0) {\"\n\t\"\t\tvec4 texColor = texture2D(feiTex, gl_TexCoord[0].st);\"\n\t\"\t\tif (texColor.a == 0.0 || color.a == 0.0) discard;\"\n\t\"\t\tcolor *= texColor;\"\n\t\"\t}\"\n\t\"\tgl_FragColor = color;\"\n\t\"}\"\n};\n\nRender* Render::instance = nullptr;\n\nRender* Render::getInstance()\n{\n\tif (!instance) {\n\t\tinstance = new Render();\n\t}\n\treturn instance; \n}\n\nRender::Render()\n{\n}\n\nbool Render::init()\n{\n\tif (_isLoad) return true;\n\t_isLoad = true;\n\tif (!fei::Interface::getInstance()->init()) {\n\t\t_isLoad = false;\n\t\treturn false;\n\t}\n\tGLenum err = glewInit();\n\tif (GLEW_OK != err) {\n\t\tstd::fprintf(stderr, \"GLEW Error: %s\\n\", glewGetErrorString(err));\n\t\t_isLoad = false;\n\t} else {\n\t\tstd::printf(\"GLEW Version: %s\\n\", glewGetString(GLEW_VERSION));\n\t\tstd::printf(\"OpenGL Version: %s\\n\", glGetString(GL_VERSION));\n\t\tif (GLEW_VERSION_2_0) {\n\t\t\tstd::printf(\"GLSL Version: %s\\n\", glGetString(GL_SHADING_LANGUAGE_VERSION));\n\t\t\tbasicShader.loadString(basicVertexShader, basicFragmentShader);\n\t\t\tbasicShader.push();\n\t\t} else {\n\t\t\tstd::printf(\"Shader unsupported!\\n\");\n\t\t}\n\t\tglEnable(GL_CULL_FACE);\n\t\tglCullFace(GL_FRONT);\n\t}\n\treturn _isLoad;\n}\n\nvoid Render::destroy()\n{\n\twhile (!shaderStack.empty()) {\n\t\tshaderStack.pop();\n\t}\n\tdeleteUnusedTexture();\n}\n\nvoid Render::executeBeforeFrame()\n{\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tauto shader = getShaderProgram();\n\tif (shader) {\n\t\tshader->use();\n\t}\n}\n\nvoid Render::executeAfterFrame()\n{\n\tdeleteUnusedTexture();\n}\n\nvoid Render::setViewport(const fei::Rect& viewport)\n{\n\tglViewport((GLint)viewport.getPosition().x, (GLint)viewport.getPosition().y,\n\t\t(GLsizei)viewport.getSize().x, (GLsizei)viewport.getSize().y);\n}\n\nconst fei::Rect Render::getViewport()\n{\n\tint viewport[4];\n\tglGetIntegerv(GL_VIEWPORT, viewport);\n\treturn fei::Rect((float)viewport[0], (float)viewport[1], (float)viewport[2], (float)viewport[3]);\n}\n\nvoid Render::pushShader(fei::ShaderProgram* shader)\n{\n\tif (shaderStack.empty() || shaderStack.top() != shader) {\n\t\tshaderStack.push(shader);\n\t\tshader->use();\n\t}\n}\n\nvoid Render::popShader(fei::ShaderProgram* shader)\n{\n\tif (!shaderStack.empty() && shaderStack.top() == shader) {\n\t\tshaderStack.pop();\n\t\tif (shaderStack.empty()) {\n\t\t\tglUseProgram(0);\n\t\t} else {\n\t\t\tshaderStack.top()->use();\n\t\t}\n\t}\n}\n\nfei::ShaderProgram* Render::getShaderProgram()\n{\n\tif (!shaderStack.empty()) {\n\t\treturn shaderStack.top();\n\t} else {\n\t\treturn nullptr;\n\t}\n}\n\nvoid Render::registTexture(const char* filename, GLuint id)\n{\n\tint hash = fei::bkdrHash(filename);\n\tfileTextureMap[hash] = id;\n}\n\nvoid Render::deleteTexture(GLuint id)\n{\n\tglDeleteTextures(1, &id);\n\ttextureSizeMap.erase(textureSizeMap.find(id));\n\tfor (auto it = fileTextureMap.begin(); it != fileTextureMap.end(); ++it) {\n\t\tif (it->second == id) {\n\t\t\tfileTextureMap.erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nint Render::queryTexture(const char* filename)\n{\n\tint hash = fei::bkdrHash(filename);\n\tGLuint ans = 0;\n\tauto it = fileTextureMap.find(hash);\n\tif (it != fileTextureMap.end()) {\n\t\tans = it->second;\n\t}\n\treturn ans;\n}\n\nvoid Render::registTexSize(GLuint id, const fei::Vec2& size)\n{\n\ttextureSizeMap[id] = size;\n}\n\nconst fei::Vec2 Render::queryTexSize(GLuint id)\n{\n\treturn textureSizeMap[id];\n}\n\nvoid Render::addRefTexture(GLuint id)\n{\n\tif (!id) return;\n\ttextureRCMap[id]++;\n}\n\nvoid Render::releaseTexture(GLuint id)\n{\n\tif (!id) return;\n\ttextureRCMap[id]--;\n}\n\nvoid Render::deleteUnusedTexture()\n{\n\tfor (auto it = textureRCMap.begin(); it != textureRCMap.end();) {\n\t\tif (it->second == 0) {\n\t\t\tdeleteTexture(it->first);\n\t\t\tit = textureRCMap.erase(it);\n\t\t} else {\n\t\t\t++it;\n\t\t}\n\t}\n}\n\nvoid Render::bindTexture(GLuint tex)\n{\n\tglBindTexture(GL_TEXTURE_2D, tex);\n\tauto shader = getShaderProgram();\n\tif (shader) {\n\t\tshader->setUniform(\"feiUseTex\", 1.0f);\n\t\tshader->setUniform(\"feiTex\", (float)tex);\n\t}\n}\n\nvoid Render::drawTexQuad(const fei::Vec2& size, GLfloat* texCoord)\n{\n\tGLfloat w2 = size.x \/ 2.0f;\n\tGLfloat h2 = size.y \/ 2.0f;\n\tGLfloat vertex[] = {-w2, h2, -w2, -h2, w2, h2, w2, -h2};\n\tGLfloat defaultTexCoord[] = {0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f};\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\tglVertexPointer(2, GL_FLOAT, 0, vertex);\n\tif (texCoord) {\n\t\tglTexCoordPointer(2, GL_FLOAT, 0, texCoord);\n\t} else {\n\t\tglTexCoordPointer(2, GL_FLOAT, 0, defaultTexCoord);\n\t}\n\tglDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (c) 2006, Mathieu Champlon\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are\r\n * met :\r\n *\r\n * . Redistributions of source code must retain the above copyright\r\n * notice, this list of conditions and the following disclaimer.\r\n *\r\n * . Redistributions in binary form must reproduce the above copyright\r\n * notice, this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n *\r\n * . Neither the name of the copyright holders nor the names of the\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT\r\n * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include \"xeumeuleu_test_pch.h\"\r\n#include <string>\r\n\r\nnamespace\r\n{\r\n static std::string data_directory;\r\n\r\n void set_data_directory( int argc, char* argv[] )\r\n {\r\n while( argc-- )\r\n {\r\n const std::string argument = argv[argc];\r\n const std::string::size_type n = argument.find( '=' );\r\n if( n != std::string::npos && argument.substr( 0, n ) == \"--data_directory\" )\r\n data_directory = argument.substr( n+1 );\r\n }\r\n }\r\n}\r\n\r\n::boost::unit_test::test_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n set_data_directory( argc, argv );\r\n return 0;\r\n}\r\n\r\nstd::string BOOST_RESOLVE( const std::string& filename )\r\n{\r\n if( data_directory.empty() )\r\n return filename;\r\n return data_directory + '\/' + filename;\r\n}\r\n<commit_msg>Cleanup<commit_after>\/*\r\n * Copyright (c) 2006, Mathieu Champlon\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are\r\n * met :\r\n *\r\n * . Redistributions of source code must retain the above copyright\r\n * notice, this list of conditions and the following disclaimer.\r\n *\r\n * . Redistributions in binary form must reproduce the above copyright\r\n * notice, this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n *\r\n * . Neither the name of the copyright holders nor the names of the\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT\r\n * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include \"xeumeuleu_test_pch.h\"\r\n#include <string>\r\n\r\nnamespace\r\n{\r\n std::string data_directory;\r\n\r\n void set_data_directory( int argc, char* argv[] )\r\n {\r\n while( argc-- )\r\n {\r\n const std::string argument = argv[argc];\r\n const std::string::size_type n = argument.find( '=' );\r\n if( n != std::string::npos && argument.substr( 0, n ) == \"--data_directory\" )\r\n data_directory = argument.substr( n+1 );\r\n }\r\n }\r\n}\r\n\r\n::boost::unit_test::test_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n set_data_directory( argc, argv );\r\n return 0;\r\n}\r\n\r\nstd::string BOOST_RESOLVE( const std::string& filename )\r\n{\r\n if( data_directory.empty() )\r\n return filename;\r\n return data_directory + '\/' + filename;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"mmcore\/CoreInstance.h\"\n#include \"mmcore\/MegaMolGraph.h\"\n\n#include \"mmcore\/utility\/log\/Log.h\"\n#include \"mmcore\/utility\/log\/DefaultTarget.h\"\n\n#include \"FrameStatistics_Service.hpp\"\n#include \"FrontendServiceCollection.hpp\"\n#include \"GUI_Service.hpp\"\n#include \"Lua_Service_Wrapper.hpp\"\n#include \"OpenGL_GLFW_Service.hpp\"\n#include \"Screenshot_Service.hpp\"\n\n#include \"mmcore\/view\/AbstractView_EventConsumption.h\"\n\n#include <cxxopts.hpp>\n#include \"mmcore\/LuaAPI.h\"\n#include \"mmcore\/utility\/graphics\/ScreenShotComments.h\"\n\n\/\/ Filesystem\n#if defined(_HAS_CXX17) || ((defined(_MSC_VER) && (_MSC_VER > 1916))) \/\/ C++2017 or since VS2019\n#include <filesystem>\nnamespace stdfs = std::filesystem;\n#else\n\/\/ WINDOWS\n#ifdef _WIN32\n#include <filesystem>\nnamespace stdfs = std::experimental::filesystem;\n#else\n\/\/ LINUX\n#include <experimental\/filesystem>\nnamespace stdfs = std::experimental::filesystem;\n#endif\n#endif\n\n\/\/ make sure that all configuration parameters have sane and useful and EXPLICIT initialization values!\nstruct CLIConfig {\n std::string program_invocation_string = \"\";\n std::vector<std::string> project_files = {};\n std::string lua_host_address = \"tcp:\/\/127.0.0.1:33333\";\n bool load_example_project = false;\n bool opengl_khr_debug = true;\n};\n\nCLIConfig handle_cli_inputs(int argc, char* argv[]);\n\nbool set_up_example_graph(megamol::core::MegaMolGraph& graph);\n\nint main(int argc, char* argv[]) {\n\n auto config = handle_cli_inputs(argc, argv);\n\n \/\/ setup log\n megamol::core::utility::log::Log::DefaultLog.SetLevel(megamol::core::utility::log::Log::LEVEL_ALL);\n megamol::core::utility::log::Log::DefaultLog.SetEchoLevel(megamol::core::utility::log::Log::LEVEL_ALL);\n megamol::core::utility::log::Log::DefaultLog.SetOfflineMessageBufferSize(100);\n megamol::core::utility::log::Log::DefaultLog.SetMainTarget(\n std::make_shared<megamol::core::utility::log::DefaultTarget>(megamol::core::utility::log::Log::LEVEL_ALL));\n\n megamol::core::CoreInstance core;\n core.Initialise(false); \/\/ false makes core not start his own lua service (else we collide on default port)\n\n const megamol::core::factories::ModuleDescriptionManager& moduleProvider = core.GetModuleDescriptionManager();\n const megamol::core::factories::CallDescriptionManager& callProvider = core.GetCallDescriptionManager();\n\n megamol::frontend::OpenGL_GLFW_Service gl_service;\n megamol::frontend::OpenGL_GLFW_Service::Config openglConfig;\n openglConfig.windowTitlePrefix = openglConfig.windowTitlePrefix + \" ~ Main3000\";\n openglConfig.versionMajor = 4;\n openglConfig.versionMinor = 5;\n openglConfig.enableKHRDebug = config.opengl_khr_debug;\n gl_service.setPriority(2);\n\n megamol::frontend::GUI_Service gui_service;\n megamol::frontend::GUI_Service::Config guiConfig;\n guiConfig.imgui_api = megamol::frontend::GUI_Service::ImGuiAPI::OPEN_GL;\n guiConfig.core_instance = &core;\n \/\/ priority must be higher than priority of gl_service (=1)\n \/\/ service callbacks get called in order of priority of the service.\n \/\/ postGraphRender() and close() are called in reverse order of priorities.\n gui_service.setPriority(23);\n\n megamol::frontend::Screenshot_Service screenshot_service;\n megamol::frontend::Screenshot_Service::Config screenshotConfig;\n screenshot_service.setPriority(30);\n\n megamol::frontend::FrameStatistics_Service framestatistics_service;\n megamol::frontend::FrameStatistics_Service::Config framestatisticsConfig;\n \/\/ needs to execute before gl_service at frame start, after gl service at frame end\n framestatistics_service.setPriority(1);\n\n megamol::core::MegaMolGraph graph(core, moduleProvider, callProvider);\n\n bool lua_imperative_only = false; \/\/ allow mmFlush, mmList* and mmGetParam*\n megamol::core::LuaAPI lua_api(graph, lua_imperative_only);\n megamol::frontend::Lua_Service_Wrapper lua_service_wrapper;\n megamol::frontend::Lua_Service_Wrapper::Config luaConfig;\n luaConfig.lua_api_ptr = &lua_api;\n luaConfig.host_address = config.lua_host_address;\n lua_service_wrapper.setPriority(0);\n\n \/\/ clang-format off\n \/\/ the main loop is organized around services that can 'do something' in different parts of the main loop.\n \/\/ a service is something that implements the AbstractFrontendService interface from 'megamol\\frontend_services\\include'.\n \/\/ a central mechanism that allows services to communicate with each other and with graph modules are _resources_.\n \/\/ (see FrontendResource in 'megamol\\frontend_resources\\include').\n \/\/ services may provide resources to the system and they may request resources they need themselves for functioning.\n \/\/ think of a resource as a struct (or some type of your choice) that gets wrapped\n \/\/ by a helper structure and gets a name attached to it. the fronend makes sure (at least\n \/\/ attempts to) to hand each service the resources it requested, or else fail execution of megamol with an error message.\n \/\/ resource assignment is done by the name of the resource, so this is a very loose interface based on trust.\n \/\/ type safety of resources is ensured in the sense that extracting the wrong type from a FrontendResource will\n \/\/ lead to an unhandled bad type cast exception, leading to the shutdown of megamol.\n \/\/ clang-format on\n bool run_megamol = true;\n megamol::frontend::FrontendServiceCollection services;\n services.add(gl_service, &openglConfig);\n services.add(gui_service, &guiConfig);\n services.add(lua_service_wrapper, &luaConfig);\n services.add(screenshot_service, &screenshotConfig);\n services.add(framestatistics_service, &framestatisticsConfig);\n\n \/\/ clang-format off\n \/\/ TODO: port cinematic as frontend service\n \/\/ TODO: FBO-centered rendering (View redesign)\n \/\/ => explicit FBOs!\n \/\/ => explicit camera \/ animation time \/ FBO resources\/modules in graph?\n \/\/ => do or dont show GUI in screenshots, depending on ...\n \/\/ TODO: ZMQ context as frontend resource\n \/\/ TODO: port CLI commands from mmconsole\n \/\/ TODO: eliminate the core instance:\n \/\/ => extract module\/call description manager into new factories; remove from core\n \/\/ => key\/value store for CLI configuration as frontend resource (emulate config params)\n \/\/ TODO: main3000 raw hot loop performance vs. mmconsole performance\n \/\/ TODO: centralize project loading\/saving to\/from .lua\/.png.\n \/\/ => has to collect graph serialization from graph, gui state from gui.\n \/\/ clang-format on\n\n const bool init_ok = services.init(); \/\/ runs init(config_ptr) on all services with provided config sructs\n\n if (!init_ok) {\n std::cout << \"ERROR: some frontend service could not be initialized successfully. abort. \" << std::endl;\n services.close();\n return 1;\n }\n\n \/\/ graph is also a resource that may be accessed by services\n services.getProvidedResources().push_back({\"MegaMolGraph\", graph});\n\n \/\/ proof of concept: a resource that returns a list of names of available resources\n \/\/ used by Lua Wrapper and LuaAPI to return list of available resources via remoteconsole\n const std::function<std::vector<std::string>()> resource_lister = [&]() -> std::vector<std::string> {\n std::vector<std::string> resources;\n for (auto& resource : services.getProvidedResources()) {\n resources.push_back(resource.getIdentifier());\n }\n resources.push_back(\"FrontendResourcesList\");\n return resources;\n };\n services.getProvidedResources().push_back({\"FrontendResourcesList\", resource_lister});\n\n \/\/ distribute registered resources among registered services.\n const bool resources_ok = services.assignRequestedResources();\n \/\/ for each service we call their resource callbacks here:\n \/\/ std::vector<FrontendResource>& getProvidedResources()\n \/\/ std::vector<std::string> getRequestedResourceNames()\n \/\/ void setRequestedResources(std::vector<FrontendResource>& resources)\n if (!resources_ok) {\n std::cout << \"ERROR: frontend could not assign requested service resources. abort. \" << std::endl;\n run_megamol = false;\n }\n\n auto frontend_resources = services.getProvidedResources();\n graph.AddModuleDependencies(frontend_resources);\n\n uint32_t frameID = 0;\n const auto render_next_frame = [&]() -> bool {\n \/\/ set global Frame Counter\n core.SetFrameID(frameID++);\n\n \/\/ services: receive inputs (GLFW poll events [keyboard, mouse, window], network, lua)\n services.updateProvidedResources();\n\n \/\/ aka simulation step\n \/\/ services: digest new inputs via ModuleResources (GUI digest user inputs, lua digest inputs, network ?)\n \/\/ e.g. graph updates, module and call creation via lua and GUI happen here\n services.digestChangedRequestedResources();\n\n \/\/ services tell us wheter we should shut down megamol\n if (services.shouldShutdown())\n return false;\n\n \/\/ actual rendering\n {\n services.preGraphRender(); \/\/ e.g. start frame timer, clear render buffers\n\n graph.RenderNextFrame(); \/\/ executes graph views, those digest input events like keyboard\/mouse, then render\n\n services.postGraphRender(); \/\/ render GUI, glfw swap buffers, stop frame timer\n }\n\n services.resetProvidedResources(); \/\/ clear buffers holding glfw keyboard+mouse input\n\n return true;\n };\n\n \/\/ lua can issue rendering of frames\n lua_api.setFlushCallback(render_next_frame);\n\n \/\/ load project files via lua\n for (auto& file : config.project_files) {\n std::string result;\n if (megamol::core::utility::graphics::ScreenShotComments::EndsWithCaseInsensitive(file, \".png\")) {\n if (!lua_api.RunString(\n megamol::core::utility::graphics::ScreenShotComments::GetProjectFromPNG(file), result)) {\n std::cout << \"Project file \\\"\" << file << \"\\\" did not execute correctly: \" << result << std::endl;\n run_megamol = false;\n }\n } else {\n if (!lua_api.RunFile(file, result)) {\n std::cout << \"Project file \\\"\" << file << \"\\\" did not execute correctly: \" << result << std::endl;\n run_megamol = false;\n }\n }\n }\n if (config.load_example_project) {\n const bool graph_ok = set_up_example_graph(graph);\n if (!graph_ok) {\n std::cout << \"ERROR: frontend could not build graph. abort. \" << std::endl;\n run_megamol = false;\n }\n }\n\n while (run_megamol) {\n run_megamol = render_next_frame();\n }\n\n \/\/ close glfw context, network connections, other system resources\n services.close();\n\n \/\/ clean up modules, calls in graph\n \/\/ TODO: implement graph destructor\n\n return 0;\n}\n\nCLIConfig handle_cli_inputs(int argc, char* argv[]) {\n CLIConfig config;\n\n cxxopts::Options options(argv[0], \"MegaMol Frontend 3000\");\n\n config.program_invocation_string = std::string{argv[0]};\n\n \/\/ clang-format off\n \/\/ parse input project files\n options.positional_help(\"<additional project files>\");\n options.add_options()\n (\"project-files\", \"projects to load\", cxxopts::value<std::vector<std::string>>())\n (\"host\", \"address of lua host server, default: \"+config.lua_host_address, cxxopts::value<std::string>())\n (\"example\", \"load minimal test spheres example project\", cxxopts::value<bool>())\n (\"khrdebug\", \"enable OpenGL KHR debug messages\", cxxopts::value<bool>()->default_value(\"false\"))\n (\"help\", \"print help\")\n ;\n \/\/ clang-format on\n\n options.parse_positional({\"project-files\"});\n\n try {\n auto parsed_options = options.parse(argc, argv);\n std::string res;\n\n if (parsed_options.count(\"help\")) {\n std::cout << options.help({\"\"}) << std::endl;\n exit(0);\n }\n\n\n \/\/ verify project files exist in file system\n if (parsed_options.count(\"project-files\")) {\n const auto& v = parsed_options[\"project-files\"].as<std::vector<std::string>>();\n for (const auto& p : v) {\n if (!stdfs::exists(p)) {\n std::cout << \"Project file \\\"\" << p << \"\\\" does not exist!\" << std::endl;\n std::exit(1);\n }\n }\n\n config.project_files = v;\n }\n\n if (parsed_options.count(\"host\")) {\n config.lua_host_address = parsed_options[\"host\"].as<std::string>();\n }\n\n if (parsed_options.count(\"example\")) {\n config.load_example_project = parsed_options[\"example\"].as<bool>();\n }\n\n config.opengl_khr_debug = parsed_options[\"khrdebug\"].as<bool>();\n } catch (cxxopts::option_not_exists_exception ex) {\n std::cout << ex.what() << std::endl;\n std::cout << options.help({\"\"}) << std::endl;\n std::exit(1);\n }\n\n return config;\n}\n\nbool set_up_example_graph(megamol::core::MegaMolGraph& graph) {\n#define check(X) \\\n if (!X) \\\n return false;\n\n check(graph.CreateModule(\"View3D_2\", \"::view\"));\n check(graph.CreateModule(\"SphereRenderer\", \"::spheres\"));\n check(graph.CreateModule(\"TestSpheresDataSource\", \"::datasource\"));\n check(graph.CreateCall(\"CallRender3D_2\", \"::view::rendering\", \"::spheres::rendering\"));\n check(graph.CreateCall(\"MultiParticleDataCall\", \"::spheres::getdata\", \"::datasource::getData\"));\n\n check(graph.SetGraphEntryPoint(\"::view\", megamol::core::view::get_gl_view_runtime_resources_requests(),\n megamol::core::view::view_rendering_execution, megamol::core::view::view_init_rendering_state));\n\n std::string parameter_name(\"::datasource::numSpheres\");\n auto parameterPtr = graph.FindParameter(parameter_name);\n if (parameterPtr) {\n parameterPtr->ParseValue(\"23\");\n } else {\n std::cout << \"ERROR: could not find parameter: \" << parameter_name << std::endl;\n return false;\n }\n\n return true;\n}\n<commit_msg>frontend: initial window size at startup<commit_after>#include \"mmcore\/CoreInstance.h\"\n#include \"mmcore\/MegaMolGraph.h\"\n\n#include \"mmcore\/utility\/log\/Log.h\"\n#include \"mmcore\/utility\/log\/DefaultTarget.h\"\n\n#include \"FrameStatistics_Service.hpp\"\n#include \"FrontendServiceCollection.hpp\"\n#include \"GUI_Service.hpp\"\n#include \"Lua_Service_Wrapper.hpp\"\n#include \"OpenGL_GLFW_Service.hpp\"\n#include \"Screenshot_Service.hpp\"\n\n#include \"mmcore\/view\/AbstractView_EventConsumption.h\"\n\n#include <cxxopts.hpp>\n#include \"mmcore\/LuaAPI.h\"\n#include \"mmcore\/utility\/graphics\/ScreenShotComments.h\"\n\n\/\/ Filesystem\n#if defined(_HAS_CXX17) || ((defined(_MSC_VER) && (_MSC_VER > 1916))) \/\/ C++2017 or since VS2019\n#include <filesystem>\nnamespace stdfs = std::filesystem;\n#else\n\/\/ WINDOWS\n#ifdef _WIN32\n#include <filesystem>\nnamespace stdfs = std::experimental::filesystem;\n#else\n\/\/ LINUX\n#include <experimental\/filesystem>\nnamespace stdfs = std::experimental::filesystem;\n#endif\n#endif\n\n\/\/ make sure that all configuration parameters have sane and useful and EXPLICIT initialization values!\nstruct CLIConfig {\n std::string program_invocation_string = \"\";\n std::vector<std::string> project_files = {};\n std::string lua_host_address = \"tcp:\/\/127.0.0.1:33333\";\n bool load_example_project = false;\n bool opengl_khr_debug = true;\n std::array<unsigned int, 2> window_size = {0, 0};\n};\n\nCLIConfig handle_cli_inputs(int argc, char* argv[]);\n\nbool set_up_example_graph(megamol::core::MegaMolGraph& graph);\n\nint main(int argc, char* argv[]) {\n\n auto config = handle_cli_inputs(argc, argv);\n\n \/\/ setup log\n megamol::core::utility::log::Log::DefaultLog.SetLevel(megamol::core::utility::log::Log::LEVEL_ALL);\n megamol::core::utility::log::Log::DefaultLog.SetEchoLevel(megamol::core::utility::log::Log::LEVEL_ALL);\n megamol::core::utility::log::Log::DefaultLog.SetOfflineMessageBufferSize(100);\n megamol::core::utility::log::Log::DefaultLog.SetMainTarget(\n std::make_shared<megamol::core::utility::log::DefaultTarget>(megamol::core::utility::log::Log::LEVEL_ALL));\n\n megamol::core::CoreInstance core;\n core.Initialise(false); \/\/ false makes core not start his own lua service (else we collide on default port)\n\n const megamol::core::factories::ModuleDescriptionManager& moduleProvider = core.GetModuleDescriptionManager();\n const megamol::core::factories::CallDescriptionManager& callProvider = core.GetCallDescriptionManager();\n\n megamol::frontend::OpenGL_GLFW_Service gl_service;\n megamol::frontend::OpenGL_GLFW_Service::Config openglConfig;\n openglConfig.windowTitlePrefix = openglConfig.windowTitlePrefix + \" ~ Main3000\";\n openglConfig.versionMajor = 4;\n openglConfig.versionMinor = 5;\n openglConfig.enableKHRDebug = config.opengl_khr_debug;\n openglConfig.windowPlacement.w = config.window_size[0];\n openglConfig.windowPlacement.h = config.window_size[1];\n openglConfig.windowPlacement.size = config.window_size[0] > 0 && config.window_size[1] > 0;\n gl_service.setPriority(2);\n\n megamol::frontend::GUI_Service gui_service;\n megamol::frontend::GUI_Service::Config guiConfig;\n guiConfig.imgui_api = megamol::frontend::GUI_Service::ImGuiAPI::OPEN_GL;\n guiConfig.core_instance = &core;\n \/\/ priority must be higher than priority of gl_service (=1)\n \/\/ service callbacks get called in order of priority of the service.\n \/\/ postGraphRender() and close() are called in reverse order of priorities.\n gui_service.setPriority(23);\n\n megamol::frontend::Screenshot_Service screenshot_service;\n megamol::frontend::Screenshot_Service::Config screenshotConfig;\n screenshot_service.setPriority(30);\n\n megamol::frontend::FrameStatistics_Service framestatistics_service;\n megamol::frontend::FrameStatistics_Service::Config framestatisticsConfig;\n \/\/ needs to execute before gl_service at frame start, after gl service at frame end\n framestatistics_service.setPriority(1);\n\n megamol::core::MegaMolGraph graph(core, moduleProvider, callProvider);\n\n bool lua_imperative_only = false; \/\/ allow mmFlush, mmList* and mmGetParam*\n megamol::core::LuaAPI lua_api(graph, lua_imperative_only);\n megamol::frontend::Lua_Service_Wrapper lua_service_wrapper;\n megamol::frontend::Lua_Service_Wrapper::Config luaConfig;\n luaConfig.lua_api_ptr = &lua_api;\n luaConfig.host_address = config.lua_host_address;\n lua_service_wrapper.setPriority(0);\n\n \/\/ clang-format off\n \/\/ the main loop is organized around services that can 'do something' in different parts of the main loop.\n \/\/ a service is something that implements the AbstractFrontendService interface from 'megamol\\frontend_services\\include'.\n \/\/ a central mechanism that allows services to communicate with each other and with graph modules are _resources_.\n \/\/ (see FrontendResource in 'megamol\\frontend_resources\\include').\n \/\/ services may provide resources to the system and they may request resources they need themselves for functioning.\n \/\/ think of a resource as a struct (or some type of your choice) that gets wrapped\n \/\/ by a helper structure and gets a name attached to it. the fronend makes sure (at least\n \/\/ attempts to) to hand each service the resources it requested, or else fail execution of megamol with an error message.\n \/\/ resource assignment is done by the name of the resource, so this is a very loose interface based on trust.\n \/\/ type safety of resources is ensured in the sense that extracting the wrong type from a FrontendResource will\n \/\/ lead to an unhandled bad type cast exception, leading to the shutdown of megamol.\n \/\/ clang-format on\n bool run_megamol = true;\n megamol::frontend::FrontendServiceCollection services;\n services.add(gl_service, &openglConfig);\n services.add(gui_service, &guiConfig);\n services.add(lua_service_wrapper, &luaConfig);\n services.add(screenshot_service, &screenshotConfig);\n services.add(framestatistics_service, &framestatisticsConfig);\n\n \/\/ clang-format off\n \/\/ TODO: port cinematic as frontend service\n \/\/ TODO: FBO-centered rendering (View redesign)\n \/\/ => explicit FBOs!\n \/\/ => explicit camera \/ animation time \/ FBO resources\/modules in graph?\n \/\/ => do or dont show GUI in screenshots, depending on ...\n \/\/ TODO: ZMQ context as frontend resource\n \/\/ TODO: port CLI commands from mmconsole\n \/\/ TODO: eliminate the core instance:\n \/\/ => extract module\/call description manager into new factories; remove from core\n \/\/ => key\/value store for CLI configuration as frontend resource (emulate config params)\n \/\/ TODO: main3000 raw hot loop performance vs. mmconsole performance\n \/\/ TODO: centralize project loading\/saving to\/from .lua\/.png.\n \/\/ => has to collect graph serialization from graph, gui state from gui.\n \/\/ clang-format on\n\n const bool init_ok = services.init(); \/\/ runs init(config_ptr) on all services with provided config sructs\n\n if (!init_ok) {\n std::cout << \"ERROR: some frontend service could not be initialized successfully. abort. \" << std::endl;\n services.close();\n return 1;\n }\n\n \/\/ graph is also a resource that may be accessed by services\n services.getProvidedResources().push_back({\"MegaMolGraph\", graph});\n\n \/\/ proof of concept: a resource that returns a list of names of available resources\n \/\/ used by Lua Wrapper and LuaAPI to return list of available resources via remoteconsole\n const std::function<std::vector<std::string>()> resource_lister = [&]() -> std::vector<std::string> {\n std::vector<std::string> resources;\n for (auto& resource : services.getProvidedResources()) {\n resources.push_back(resource.getIdentifier());\n }\n resources.push_back(\"FrontendResourcesList\");\n return resources;\n };\n services.getProvidedResources().push_back({\"FrontendResourcesList\", resource_lister});\n\n \/\/ distribute registered resources among registered services.\n const bool resources_ok = services.assignRequestedResources();\n \/\/ for each service we call their resource callbacks here:\n \/\/ std::vector<FrontendResource>& getProvidedResources()\n \/\/ std::vector<std::string> getRequestedResourceNames()\n \/\/ void setRequestedResources(std::vector<FrontendResource>& resources)\n if (!resources_ok) {\n std::cout << \"ERROR: frontend could not assign requested service resources. abort. \" << std::endl;\n run_megamol = false;\n }\n\n auto frontend_resources = services.getProvidedResources();\n graph.AddModuleDependencies(frontend_resources);\n\n uint32_t frameID = 0;\n const auto render_next_frame = [&]() -> bool {\n \/\/ set global Frame Counter\n core.SetFrameID(frameID++);\n\n \/\/ services: receive inputs (GLFW poll events [keyboard, mouse, window], network, lua)\n services.updateProvidedResources();\n\n \/\/ aka simulation step\n \/\/ services: digest new inputs via ModuleResources (GUI digest user inputs, lua digest inputs, network ?)\n \/\/ e.g. graph updates, module and call creation via lua and GUI happen here\n services.digestChangedRequestedResources();\n\n \/\/ services tell us wheter we should shut down megamol\n if (services.shouldShutdown())\n return false;\n\n \/\/ actual rendering\n {\n services.preGraphRender(); \/\/ e.g. start frame timer, clear render buffers\n\n graph.RenderNextFrame(); \/\/ executes graph views, those digest input events like keyboard\/mouse, then render\n\n services.postGraphRender(); \/\/ render GUI, glfw swap buffers, stop frame timer\n }\n\n services.resetProvidedResources(); \/\/ clear buffers holding glfw keyboard+mouse input\n\n return true;\n };\n\n \/\/ lua can issue rendering of frames\n lua_api.setFlushCallback(render_next_frame);\n\n \/\/ load project files via lua\n for (auto& file : config.project_files) {\n std::string result;\n if (megamol::core::utility::graphics::ScreenShotComments::EndsWithCaseInsensitive(file, \".png\")) {\n if (!lua_api.RunString(\n megamol::core::utility::graphics::ScreenShotComments::GetProjectFromPNG(file), result)) {\n std::cout << \"Project file \\\"\" << file << \"\\\" did not execute correctly: \" << result << std::endl;\n run_megamol = false;\n }\n } else {\n if (!lua_api.RunFile(file, result)) {\n std::cout << \"Project file \\\"\" << file << \"\\\" did not execute correctly: \" << result << std::endl;\n run_megamol = false;\n }\n }\n }\n if (config.load_example_project) {\n const bool graph_ok = set_up_example_graph(graph);\n if (!graph_ok) {\n std::cout << \"ERROR: frontend could not build graph. abort. \" << std::endl;\n run_megamol = false;\n }\n }\n\n while (run_megamol) {\n run_megamol = render_next_frame();\n }\n\n \/\/ close glfw context, network connections, other system resources\n services.close();\n\n \/\/ clean up modules, calls in graph\n \/\/ TODO: implement graph destructor\n\n return 0;\n}\n\nCLIConfig handle_cli_inputs(int argc, char* argv[]) {\n CLIConfig config;\n\n cxxopts::Options options(argv[0], \"MegaMol Frontend 3000\");\n\n config.program_invocation_string = std::string{argv[0]};\n\n \/\/ clang-format off\n \/\/ parse input project files\n options.positional_help(\"<additional project files>\");\n options.add_options()\n (\"project-files\", \"projects to load\", cxxopts::value<std::vector<std::string>>())\n (\"host\", \"address of lua host server, default: \"+config.lua_host_address, cxxopts::value<std::string>())\n (\"example\", \"load minimal test spheres example project\", cxxopts::value<bool>())\n (\"khrdebug\", \"enable OpenGL KHR debug messages\", cxxopts::value<bool>()->default_value(\"false\"))\n (\"help\", \"print help\")\n ;\n \/\/ clang-format on\n\n options.parse_positional({\"project-files\"});\n\n try {\n auto parsed_options = options.parse(argc, argv);\n std::string res;\n\n if (parsed_options.count(\"help\")) {\n std::cout << options.help({\"\"}) << std::endl;\n exit(0);\n }\n\n\n \/\/ verify project files exist in file system\n if (parsed_options.count(\"project-files\")) {\n const auto& v = parsed_options[\"project-files\"].as<std::vector<std::string>>();\n for (const auto& p : v) {\n if (!stdfs::exists(p)) {\n std::cout << \"Project file \\\"\" << p << \"\\\" does not exist!\" << std::endl;\n std::exit(1);\n }\n }\n\n config.project_files = v;\n }\n\n if (parsed_options.count(\"host\")) {\n config.lua_host_address = parsed_options[\"host\"].as<std::string>();\n }\n\n if (parsed_options.count(\"example\")) {\n config.load_example_project = parsed_options[\"example\"].as<bool>();\n }\n\n config.opengl_khr_debug = parsed_options[\"khrdebug\"].as<bool>();\n } catch (cxxopts::option_not_exists_exception ex) {\n std::cout << ex.what() << std::endl;\n std::cout << options.help({\"\"}) << std::endl;\n std::exit(1);\n }\n\n return config;\n}\n\nbool set_up_example_graph(megamol::core::MegaMolGraph& graph) {\n#define check(X) \\\n if (!X) \\\n return false;\n\n check(graph.CreateModule(\"View3D_2\", \"::view\"));\n check(graph.CreateModule(\"SphereRenderer\", \"::spheres\"));\n check(graph.CreateModule(\"TestSpheresDataSource\", \"::datasource\"));\n check(graph.CreateCall(\"CallRender3D_2\", \"::view::rendering\", \"::spheres::rendering\"));\n check(graph.CreateCall(\"MultiParticleDataCall\", \"::spheres::getdata\", \"::datasource::getData\"));\n\n check(graph.SetGraphEntryPoint(\"::view\", megamol::core::view::get_gl_view_runtime_resources_requests(),\n megamol::core::view::view_rendering_execution, megamol::core::view::view_init_rendering_state));\n\n std::string parameter_name(\"::datasource::numSpheres\");\n auto parameterPtr = graph.FindParameter(parameter_name);\n if (parameterPtr) {\n parameterPtr->ParseValue(\"23\");\n } else {\n std::cout << \"ERROR: could not find parameter: \" << parameter_name << std::endl;\n return false;\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2015 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/cpu\/backend\/x64\/x64_code_cache.h\"\n\n#include <cstdlib>\n#include <cstring>\n\n#include \"xenia\/base\/assert.h\"\n#include \"xenia\/base\/clock.h\"\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/math.h\"\n#include \"xenia\/base\/memory.h\"\n#include \"xenia\/base\/platform_win.h\"\n#include \"xenia\/cpu\/function.h\"\n\n\/\/ When enabled, this will use Windows 8 APIs to get unwind info.\n\/\/ TODO(benvanik): figure out why the callback variant doesn't work.\n#define USE_GROWABLE_FUNCTION_TABLE\n\nnamespace xe {\nnamespace cpu {\nnamespace backend {\nnamespace x64 {\n\n\/\/ Size of unwind info per function.\n\/\/ TODO(benvanik): move this to emitter.\nstatic const uint32_t kUnwindInfoSize = 4 + (2 * 1 + 2 + 2);\n\nclass Win32X64CodeCache : public X64CodeCache {\n public:\n Win32X64CodeCache();\n ~Win32X64CodeCache() override;\n\n bool Initialize() override;\n\n void* LookupUnwindInfo(uint64_t host_pc) override;\n\n private:\n UnwindReservation RequestUnwindReservation(uint8_t* entry_address) override;\n void PlaceCode(uint32_t guest_address, void* machine_code, size_t code_size,\n size_t stack_size, void* code_address,\n UnwindReservation unwind_reservation) override;\n\n void InitializeUnwindEntry(uint8_t* unwind_entry_address,\n size_t unwind_table_slot, void* code_address,\n size_t code_size, size_t stack_size);\n\n \/\/ Growable function table system handle.\n void* unwind_table_handle_ = nullptr;\n \/\/ Actual unwind table entries.\n std::vector<RUNTIME_FUNCTION> unwind_table_;\n \/\/ Current number of entries in the table.\n std::atomic<uint32_t> unwind_table_count_ = {0};\n};\n\nstd::unique_ptr<X64CodeCache> X64CodeCache::Create() {\n return std::make_unique<Win32X64CodeCache>();\n}\n\nWin32X64CodeCache::Win32X64CodeCache() = default;\n\nWin32X64CodeCache::~Win32X64CodeCache() {\n#ifdef USE_GROWABLE_FUNCTION_TABLE\n if (unwind_table_handle_) {\n RtlDeleteGrowableFunctionTable(unwind_table_handle_);\n }\n#else\n if (generated_code_base_) {\n RtlDeleteFunctionTable(reinterpret_cast<PRUNTIME_FUNCTION>(\n reinterpret_cast<DWORD64>(generated_code_base_) | 0x3));\n }\n#endif \/\/ USE_GROWABLE_FUNCTION_TABLE\n}\n\nbool Win32X64CodeCache::Initialize() {\n if (!X64CodeCache::Initialize()) {\n return false;\n }\n\n \/\/ Compute total number of unwind entries we should allocate.\n \/\/ We don't support reallocing right now, so this should be high.\n unwind_table_.resize(kMaximumFunctionCount);\n\n#ifdef USE_GROWABLE_FUNCTION_TABLE\n \/\/ Create table and register with the system. It's empty now, but we'll grow\n \/\/ it as functions are added.\n if (RtlAddGrowableFunctionTable(\n &unwind_table_handle_, unwind_table_.data(), unwind_table_count_,\n DWORD(unwind_table_.size()),\n reinterpret_cast<ULONG_PTR>(generated_code_base_),\n reinterpret_cast<ULONG_PTR>(generated_code_base_ +\n kGeneratedCodeSize))) {\n XELOGE(\"Unable to create unwind function table\");\n return false;\n }\n#else\n \/\/ Install a callback that the debugger will use to lookup unwind info on\n \/\/ demand.\n if (!RtlInstallFunctionTableCallback(\n reinterpret_cast<DWORD64>(generated_code_base_) | 0x3,\n reinterpret_cast<DWORD64>(generated_code_base_), kGeneratedCodeSize,\n [](uintptr_t control_pc, void* context) {\n auto code_cache = reinterpret_cast<X64CodeCache*>(context);\n return reinterpret_cast<PRUNTIME_FUNCTION>(\n code_cache->LookupUnwindEntry(control_pc));\n },\n this, nullptr)) {\n XELOGE(\"Unable to install function table callback\");\n return false;\n }\n#endif \/\/ USE_GROWABLE_FUNCTION_TABLE\n\n return true;\n}\n\nWin32X64CodeCache::UnwindReservation\nWin32X64CodeCache::RequestUnwindReservation(uint8_t* entry_address) {\n UnwindReservation unwind_reservation;\n unwind_reservation.data_size = xe::round_up(kUnwindInfoSize, 16);\n unwind_reservation.table_slot = ++unwind_table_count_;\n unwind_reservation.entry_address = entry_address;\n assert_false(unwind_table_count_ >= kMaximumFunctionCount);\n\n return unwind_reservation;\n}\n\nvoid Win32X64CodeCache::PlaceCode(uint32_t guest_address, void* machine_code,\n size_t code_size, size_t stack_size,\n void* code_address,\n UnwindReservation unwind_reservation) {\n \/\/ Add unwind info.\n InitializeUnwindEntry(unwind_reservation.entry_address,\n unwind_reservation.table_slot, code_address, code_size,\n stack_size);\n\n#ifdef USE_GROWABLE_FUNCTION_TABLE\n \/\/ Notify that the unwind table has grown.\n \/\/ We do this outside of the lock, but with the latest total count.\n RtlGrowFunctionTable(unwind_table_handle_, unwind_table_count_);\n#endif \/\/ USE_GROWABLE_FUNCTION_TABLE\n\n \/\/ This isn't needed on x64 (probably), but is convention.\n FlushInstructionCache(GetCurrentProcess(), code_address, code_size);\n}\n\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ssa62fwe.aspx\ntypedef enum _UNWIND_OP_CODES {\n UWOP_PUSH_NONVOL = 0, \/* info == register number *\/\n UWOP_ALLOC_LARGE, \/* no info, alloc size in next 2 slots *\/\n UWOP_ALLOC_SMALL, \/* info == size of allocation \/ 8 - 1 *\/\n UWOP_SET_FPREG, \/* no info, FP = RSP + UNWIND_INFO.FPRegOffset*16 *\/\n UWOP_SAVE_NONVOL, \/* info == register number, offset in next slot *\/\n UWOP_SAVE_NONVOL_FAR, \/* info == register number, offset in next 2 slots *\/\n UWOP_SAVE_XMM128, \/* info == XMM reg number, offset in next slot *\/\n UWOP_SAVE_XMM128_FAR, \/* info == XMM reg number, offset in next 2 slots *\/\n UWOP_PUSH_MACHFRAME \/* info == 0: no error-code, 1: error-code *\/\n} UNWIND_CODE_OPS;\nclass UNWIND_REGISTER {\n public:\n enum _ {\n RAX = 0,\n RCX = 1,\n RDX = 2,\n RBX = 3,\n RSP = 4,\n RBP = 5,\n RSI = 6,\n RDI = 7,\n R8 = 8,\n R9 = 9,\n R10 = 10,\n R11 = 11,\n R12 = 12,\n R13 = 13,\n R14 = 14,\n R15 = 15,\n };\n};\n\ntypedef union _UNWIND_CODE {\n struct {\n uint8_t CodeOffset;\n uint8_t UnwindOp : 4;\n uint8_t OpInfo : 4;\n };\n USHORT FrameOffset;\n} UNWIND_CODE, *PUNWIND_CODE;\n\ntypedef struct _UNWIND_INFO {\n uint8_t Version : 3;\n uint8_t Flags : 5;\n uint8_t SizeOfProlog;\n uint8_t CountOfCodes;\n uint8_t FrameRegister : 4;\n uint8_t FrameOffset : 4;\n UNWIND_CODE UnwindCode[1];\n \/* UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];\n * union {\n * OPTIONAL ULONG ExceptionHandler;\n * OPTIONAL ULONG FunctionEntry;\n * };\n * OPTIONAL ULONG ExceptionData[]; *\/\n} UNWIND_INFO, *PUNWIND_INFO;\n\nvoid Win32X64CodeCache::InitializeUnwindEntry(uint8_t* unwind_entry_address,\n size_t unwind_table_slot,\n void* code_address,\n size_t code_size,\n size_t stack_size) {\n auto unwind_info = reinterpret_cast<UNWIND_INFO*>(unwind_entry_address);\n\n if (!stack_size) {\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ddssxxy8.aspx\n unwind_info->Version = 1;\n unwind_info->Flags = 0;\n unwind_info->SizeOfProlog = 0;\n unwind_info->CountOfCodes = 0;\n unwind_info->FrameRegister = 0;\n unwind_info->FrameOffset = 0;\n } else if (stack_size <= 128) {\n uint8_t prolog_size = 4;\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ddssxxy8.aspx\n unwind_info->Version = 1;\n unwind_info->Flags = 0;\n unwind_info->SizeOfProlog = prolog_size;\n unwind_info->CountOfCodes = 1;\n unwind_info->FrameRegister = 0;\n unwind_info->FrameOffset = 0;\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ck9asaa9.aspx\n size_t co = 0;\n auto& unwind_code = unwind_info->UnwindCode[co++];\n unwind_code.CodeOffset =\n 14; \/\/ end of instruction + 1 == offset of next instruction\n unwind_code.UnwindOp = UWOP_ALLOC_SMALL;\n unwind_code.OpInfo = stack_size \/ 8 - 1;\n } else {\n \/\/ TODO(benvanik): take as parameters?\n uint8_t prolog_size = 7;\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ddssxxy8.aspx\n unwind_info->Version = 1;\n unwind_info->Flags = 0;\n unwind_info->SizeOfProlog = prolog_size;\n unwind_info->CountOfCodes = 2;\n unwind_info->FrameRegister = 0;\n unwind_info->FrameOffset = 0;\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ck9asaa9.aspx\n size_t co = 0;\n auto& unwind_code = unwind_info->UnwindCode[co++];\n unwind_code.CodeOffset =\n 7; \/\/ end of instruction + 1 == offset of next instruction\n unwind_code.UnwindOp = UWOP_ALLOC_LARGE;\n unwind_code.OpInfo = 0;\n\n assert_true((stack_size \/ 8) < 65536u);\n unwind_code = unwind_info->UnwindCode[co++];\n unwind_code.FrameOffset = (USHORT)(stack_size) \/ 8;\n }\n\n \/\/ Add entry.\n auto& fn_entry = unwind_table_[unwind_table_slot];\n fn_entry.BeginAddress =\n (DWORD)(reinterpret_cast<uint8_t*>(code_address) - generated_code_base_);\n fn_entry.EndAddress = (DWORD)(fn_entry.BeginAddress + code_size);\n fn_entry.UnwindData = (DWORD)(unwind_entry_address - generated_code_base_);\n}\n\nvoid* Win32X64CodeCache::LookupUnwindInfo(uint64_t host_pc) {\n return std::bsearch(\n &host_pc, unwind_table_.data(), unwind_table_count_ + 1,\n sizeof(RUNTIME_FUNCTION),\n [](const void* key_ptr, const void* element_ptr) {\n auto key =\n *reinterpret_cast<const uintptr_t*>(key_ptr) - kGeneratedCodeBase;\n auto element = reinterpret_cast<const RUNTIME_FUNCTION*>(element_ptr);\n if (key < element->BeginAddress) {\n return -1;\n } else if (key > element->EndAddress) {\n return 1;\n } else {\n return 0;\n }\n });\n}\n\n} \/\/ namespace x64\n} \/\/ namespace backend\n} \/\/ namespace cpu\n} \/\/ namespace xe\n<commit_msg>[x64] Fix unwind info bug; Cleanup win code cache<commit_after>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2015 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/cpu\/backend\/x64\/x64_code_cache.h\"\n\n#include <cstdlib>\n#include <cstring>\n\n#include \"xenia\/base\/assert.h\"\n#include \"xenia\/base\/clock.h\"\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/math.h\"\n#include \"xenia\/base\/memory.h\"\n#include \"xenia\/base\/platform_win.h\"\n#include \"xenia\/cpu\/function.h\"\n\n\/\/ When enabled, this will use Windows 8 APIs to get unwind info.\n\/\/ TODO(benvanik): figure out why the callback variant doesn't work.\n#define USE_GROWABLE_FUNCTION_TABLE\n\nnamespace xe {\nnamespace cpu {\nnamespace backend {\nnamespace x64 {\n\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ssa62fwe.aspx\ntypedef enum _UNWIND_OP_CODES {\n UWOP_PUSH_NONVOL = 0, \/* info == register number *\/\n UWOP_ALLOC_LARGE, \/* no info, alloc size in next 2 slots *\/\n UWOP_ALLOC_SMALL, \/* info == size of allocation \/ 8 - 1 *\/\n UWOP_SET_FPREG, \/* no info, FP = RSP + UNWIND_INFO.FPRegOffset*16 *\/\n UWOP_SAVE_NONVOL, \/* info == register number, offset in next slot *\/\n UWOP_SAVE_NONVOL_FAR, \/* info == register number, offset in next 2 slots *\/\n UWOP_SAVE_XMM128, \/* info == XMM reg number, offset in next slot *\/\n UWOP_SAVE_XMM128_FAR, \/* info == XMM reg number, offset in next 2 slots *\/\n UWOP_PUSH_MACHFRAME \/* info == 0: no error-code, 1: error-code *\/\n} UNWIND_CODE_OPS;\nclass UNWIND_REGISTER {\n public:\n enum _ {\n RAX = 0,\n RCX = 1,\n RDX = 2,\n RBX = 3,\n RSP = 4,\n RBP = 5,\n RSI = 6,\n RDI = 7,\n R8 = 8,\n R9 = 9,\n R10 = 10,\n R11 = 11,\n R12 = 12,\n R13 = 13,\n R14 = 14,\n R15 = 15,\n };\n};\n\ntypedef union _UNWIND_CODE {\n struct {\n uint8_t CodeOffset;\n uint8_t UnwindOp : 4;\n uint8_t OpInfo : 4;\n };\n USHORT FrameOffset;\n} UNWIND_CODE, *PUNWIND_CODE;\n\ntypedef struct _UNWIND_INFO {\n uint8_t Version : 3;\n uint8_t Flags : 5;\n uint8_t SizeOfProlog;\n uint8_t CountOfCodes;\n uint8_t FrameRegister : 4;\n uint8_t FrameOffset : 4;\n UNWIND_CODE UnwindCode[1];\n \/* UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];\n * union {\n * OPTIONAL ULONG ExceptionHandler;\n * OPTIONAL ULONG FunctionEntry;\n * };\n * OPTIONAL ULONG ExceptionData[]; *\/\n} UNWIND_INFO, *PUNWIND_INFO;\n\n\/\/ Size of unwind info per function.\n\/\/ TODO(benvanik): move this to emitter.\nstatic const uint32_t kUnwindInfoSize =\n sizeof(UNWIND_INFO) + (sizeof(UNWIND_CODE) * (6 - 1));\n\nclass Win32X64CodeCache : public X64CodeCache {\n public:\n Win32X64CodeCache();\n ~Win32X64CodeCache() override;\n\n bool Initialize() override;\n\n void* LookupUnwindInfo(uint64_t host_pc) override;\n\n private:\n UnwindReservation RequestUnwindReservation(uint8_t* entry_address) override;\n void PlaceCode(uint32_t guest_address, void* machine_code, size_t code_size,\n size_t stack_size, void* code_address,\n UnwindReservation unwind_reservation) override;\n\n void InitializeUnwindEntry(uint8_t* unwind_entry_address,\n size_t unwind_table_slot, void* code_address,\n size_t code_size, size_t stack_size);\n\n \/\/ Growable function table system handle.\n void* unwind_table_handle_ = nullptr;\n \/\/ Actual unwind table entries.\n std::vector<RUNTIME_FUNCTION> unwind_table_;\n \/\/ Current number of entries in the table.\n std::atomic<uint32_t> unwind_table_count_ = {0};\n};\n\nstd::unique_ptr<X64CodeCache> X64CodeCache::Create() {\n return std::make_unique<Win32X64CodeCache>();\n}\n\nWin32X64CodeCache::Win32X64CodeCache() = default;\n\nWin32X64CodeCache::~Win32X64CodeCache() {\n#ifdef USE_GROWABLE_FUNCTION_TABLE\n if (unwind_table_handle_) {\n RtlDeleteGrowableFunctionTable(unwind_table_handle_);\n }\n#else\n if (generated_code_base_) {\n RtlDeleteFunctionTable(reinterpret_cast<PRUNTIME_FUNCTION>(\n reinterpret_cast<DWORD64>(generated_code_base_) | 0x3));\n }\n#endif \/\/ USE_GROWABLE_FUNCTION_TABLE\n}\n\nbool Win32X64CodeCache::Initialize() {\n if (!X64CodeCache::Initialize()) {\n return false;\n }\n\n \/\/ Compute total number of unwind entries we should allocate.\n \/\/ We don't support reallocing right now, so this should be high.\n unwind_table_.resize(kMaximumFunctionCount);\n\n#ifdef USE_GROWABLE_FUNCTION_TABLE\n \/\/ Create table and register with the system. It's empty now, but we'll grow\n \/\/ it as functions are added.\n if (RtlAddGrowableFunctionTable(\n &unwind_table_handle_, unwind_table_.data(), unwind_table_count_,\n DWORD(unwind_table_.size()),\n reinterpret_cast<ULONG_PTR>(generated_code_base_),\n reinterpret_cast<ULONG_PTR>(generated_code_base_ +\n kGeneratedCodeSize))) {\n XELOGE(\"Unable to create unwind function table\");\n return false;\n }\n#else\n \/\/ Install a callback that the debugger will use to lookup unwind info on\n \/\/ demand.\n if (!RtlInstallFunctionTableCallback(\n reinterpret_cast<DWORD64>(generated_code_base_) | 0x3,\n reinterpret_cast<DWORD64>(generated_code_base_), kGeneratedCodeSize,\n [](DWORD64 control_pc, PVOID context) {\n auto code_cache = reinterpret_cast<Win32X64CodeCache*>(context);\n return reinterpret_cast<PRUNTIME_FUNCTION>(\n code_cache->LookupUnwindInfo(control_pc));\n },\n this, nullptr)) {\n XELOGE(\"Unable to install function table callback\");\n return false;\n }\n#endif \/\/ USE_GROWABLE_FUNCTION_TABLE\n\n return true;\n}\n\nWin32X64CodeCache::UnwindReservation\nWin32X64CodeCache::RequestUnwindReservation(uint8_t* entry_address) {\n UnwindReservation unwind_reservation;\n unwind_reservation.data_size = xe::round_up(kUnwindInfoSize, 16);\n unwind_reservation.table_slot = ++unwind_table_count_;\n unwind_reservation.entry_address = entry_address;\n assert_false(unwind_table_count_ >= kMaximumFunctionCount);\n\n return unwind_reservation;\n}\n\nvoid Win32X64CodeCache::PlaceCode(uint32_t guest_address, void* machine_code,\n size_t code_size, size_t stack_size,\n void* code_address,\n UnwindReservation unwind_reservation) {\n \/\/ Add unwind info.\n InitializeUnwindEntry(unwind_reservation.entry_address,\n unwind_reservation.table_slot, code_address, code_size,\n stack_size);\n\n#ifdef USE_GROWABLE_FUNCTION_TABLE\n \/\/ Notify that the unwind table has grown.\n \/\/ We do this outside of the lock, but with the latest total count.\n RtlGrowFunctionTable(unwind_table_handle_, unwind_table_count_);\n#endif \/\/ USE_GROWABLE_FUNCTION_TABLE\n\n \/\/ This isn't needed on x64 (probably), but is convention.\n FlushInstructionCache(GetCurrentProcess(), code_address, code_size);\n}\n\nvoid Win32X64CodeCache::InitializeUnwindEntry(uint8_t* unwind_entry_address,\n size_t unwind_table_slot,\n void* code_address,\n size_t code_size,\n size_t stack_size) {\n auto unwind_info = reinterpret_cast<UNWIND_INFO*>(unwind_entry_address);\n UNWIND_CODE* unwind_code = nullptr;\n\n if (!stack_size) {\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ddssxxy8.aspx\n unwind_info->Version = 1;\n unwind_info->Flags = 0;\n unwind_info->SizeOfProlog = 0;\n unwind_info->CountOfCodes = 0;\n unwind_info->FrameRegister = 0;\n unwind_info->FrameOffset = 0;\n } else if (stack_size <= 128) {\n uint8_t prolog_size = 4;\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ddssxxy8.aspx\n unwind_info->Version = 1;\n unwind_info->Flags = 0;\n unwind_info->SizeOfProlog = prolog_size;\n unwind_info->CountOfCodes = 0;\n unwind_info->FrameRegister = 0;\n unwind_info->FrameOffset = 0;\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ck9asaa9.aspx\n unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++];\n unwind_code->CodeOffset =\n 14; \/\/ end of instruction + 1 == offset of next instruction\n unwind_code->UnwindOp = UWOP_ALLOC_SMALL;\n unwind_code->OpInfo = stack_size \/ 8 - 1;\n } else {\n \/\/ TODO(benvanik): take as parameters?\n uint8_t prolog_size = 7;\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ddssxxy8.aspx\n unwind_info->Version = 1;\n unwind_info->Flags = 0;\n unwind_info->SizeOfProlog = prolog_size;\n unwind_info->CountOfCodes = 0;\n unwind_info->FrameRegister = 0;\n unwind_info->FrameOffset = 0;\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/ck9asaa9.aspx\n unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++];\n unwind_code->CodeOffset =\n 7; \/\/ end of instruction + 1 == offset of next instruction\n unwind_code->UnwindOp = UWOP_ALLOC_LARGE;\n unwind_code->OpInfo = 0; \/\/ One slot for size\n\n assert_true((stack_size \/ 8) < 65536u);\n unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++];\n unwind_code->FrameOffset = (USHORT)(stack_size) \/ 8;\n }\n\n if (unwind_info->CountOfCodes % 1) {\n \/\/ Count of unwind codes must always be even.\n std::memset(&unwind_info->UnwindCode[unwind_info->CountOfCodes + 1], 0,\n sizeof(UNWIND_CODE));\n }\n\n \/\/ Add entry.\n auto& fn_entry = unwind_table_[unwind_table_slot];\n fn_entry.BeginAddress =\n (DWORD)(reinterpret_cast<uint8_t*>(code_address) - generated_code_base_);\n fn_entry.EndAddress = (DWORD)(fn_entry.BeginAddress + code_size);\n fn_entry.UnwindData = (DWORD)(unwind_entry_address - generated_code_base_);\n}\n\nvoid* Win32X64CodeCache::LookupUnwindInfo(uint64_t host_pc) {\n return std::bsearch(\n &host_pc, unwind_table_.data(), unwind_table_count_ + 1,\n sizeof(RUNTIME_FUNCTION),\n [](const void* key_ptr, const void* element_ptr) {\n auto key =\n *reinterpret_cast<const uintptr_t*>(key_ptr) - kGeneratedCodeBase;\n auto element = reinterpret_cast<const RUNTIME_FUNCTION*>(element_ptr);\n if (key < element->BeginAddress) {\n return -1;\n } else if (key > element->EndAddress) {\n return 1;\n } else {\n return 0;\n }\n });\n}\n\n} \/\/ namespace x64\n} \/\/ namespace backend\n} \/\/ namespace cpu\n} \/\/ namespace xe\n<|endoftext|>"} {"text":"<commit_before>#ifndef REPORTDESIGN_API_REPORTENGINEJFREE_HXX\n#define REPORTDESIGN_API_REPORTENGINEJFREE_HXX\n\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ReportEngineJFree.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2007-07-09 11:56:15 $\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 _COM_SUN_STAR_REPORT_XREPORTENGINE_HPP_\n#include <com\/sun\/star\/report\/XReportEngine.hpp>\n#endif\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include <cppuhelper\/compbase2.hxx>\n#endif\n#ifndef _COMPHELPER_BROADCASTHELPER_HXX_\n#include <comphelper\/broadcasthelper.hxx>\n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#ifndef INCLUDED_CPPUHELPER_PROPERTYSETMIXIN_HXX\n#include <cppuhelper\/propertysetmixin.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_\n#include <com\/sun\/star\/sdbc\/XRowSet.hpp>\n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n#ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX\n#include <comphelper\/implementationreference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\nnamespace reportdesign\n{\n typedef ::cppu::WeakComponentImplHelper2< com::sun::star::report::XReportEngine\n ,com::sun::star::lang::XServiceInfo> ReportEngineBase;\n typedef ::cppu::PropertySetMixin<com::sun::star::report::XReportEngine> ReportEnginePropertySet;\n\n class OReportEngineJFree : public comphelper::OMutexAndBroadcastHelper,\n public ReportEngineBase,\n public ReportEnginePropertySet\n {\n typedef ::std::multimap< ::rtl::OUString, ::com::sun::star::uno::Any , ::comphelper::UStringMixLess> TComponentMap;\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;\n ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > m_xReport;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > m_xRowSet;\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator> m_StatusIndicator;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xActiveConnection;\n private:\n OReportEngineJFree(const OReportEngineJFree&);\n OReportEngineJFree& operator=(const OReportEngineJFree&);\n template <typename T> void set( const ::rtl::OUString& _sProperty\n ,const T& _Value\n ,T& _member)\n {\n BoundListeners l;\n {\n ::osl::MutexGuard aGuard(m_aMutex);\n prepareSet(_sProperty, ::com::sun::star::uno::makeAny(_member), ::com::sun::star::uno::makeAny(_Value), &l);\n _member = _Value;\n }\n l.notify();\n }\n\n \/** transform the report defintion format into a jfree report format.\n *\n * \\return The URL of the newly created file.\n *\/\n ::rtl::OUString transform();\n\n \/** returns the file url for a new model\n *\n * \\return The new file url.\n *\/\n ::rtl::OUString getNewOutputName();\n\n \/** set the rowset properties.\n *\n *\/\n void setRowSetProperties();\n\n \/** generates the order statement defined by the groups of the report\n *\n * \\return the ORDER BY part\n *\/\n ::rtl::OUString getOrderStatement() const;\n protected:\n virtual ~OReportEngineJFree();\n public:\n typedef ::comphelper::ImplementationReference< OReportEngineJFree ,::com::sun::star::report::XReportEngine,::com::sun::star::uno::XWeak > TReportEngine;\n\n OReportEngineJFree(const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& context);\n\n DECLARE_XINTERFACE( )\n \/\/ ::com::sun::star::lang::XServiceInfo\n virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);\n\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );\n static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL\n create(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext);\n \/\/ com::sun::star::beans::XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XReportEngine\n \/\/ Attributes\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > SAL_CALL getReportDefinition() throw (::com::sun::star::uno::RuntimeException) ;\n virtual void SAL_CALL setReportDefinition( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition >& _reportdefinition ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getActiveConnection() throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setActiveConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _activeconnection ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL getStatusIndicator() throw (::com::sun::star::uno::RuntimeException) ;\n virtual void SAL_CALL setStatusIndicator( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator >& _statusindicator ) throw (::com::sun::star::uno::RuntimeException) ;\n \/\/ Methods\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > SAL_CALL createDocumentModel( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ;\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > SAL_CALL createDocumentAlive( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _frame ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ;\n virtual ::com::sun::star::util::URL SAL_CALL createDocument( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ;\n virtual void SAL_CALL interrupt( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ;\n\n \/\/ XComponent\n virtual void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & aListener) throw(::com::sun::star::uno::RuntimeException)\n {\n cppu::WeakComponentImplHelperBase::addEventListener(aListener);\n }\n virtual void SAL_CALL removeEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & aListener) throw(::com::sun::star::uno::RuntimeException)\n {\n cppu::WeakComponentImplHelperBase::removeEventListener(aListener);\n }\n };\n}\n#endif \/\/REPORTDESIGN_API_REPORTENGINEJFREE_HXX\n<commit_msg>INTEGRATION: CWS rptchart01_DEV300 (1.2.70); FILE MERGED 2008\/02\/13 07:12:47 oj 1.2.70.2: #i85225# impl chart readhandler and oleproducer 2008\/01\/24 12:39:31 oj 1.2.70.1: #i85225# changes for chart<commit_after>#ifndef REPORTDESIGN_API_REPORTENGINEJFREE_HXX\n#define REPORTDESIGN_API_REPORTENGINEJFREE_HXX\n\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ReportEngineJFree.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 17:56:06 $\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 _COM_SUN_STAR_REPORT_XREPORTENGINE_HPP_\n#include <com\/sun\/star\/report\/XReportEngine.hpp>\n#endif\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include <cppuhelper\/compbase2.hxx>\n#endif\n#ifndef _COMPHELPER_BROADCASTHELPER_HXX_\n#include <comphelper\/broadcasthelper.hxx>\n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#ifndef INCLUDED_CPPUHELPER_PROPERTYSETMIXIN_HXX\n#include <cppuhelper\/propertysetmixin.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_\n#include <com\/sun\/star\/sdbc\/XRowSet.hpp>\n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n#ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX\n#include <comphelper\/implementationreference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\nnamespace reportdesign\n{\n typedef ::cppu::WeakComponentImplHelper2< com::sun::star::report::XReportEngine\n ,com::sun::star::lang::XServiceInfo> ReportEngineBase;\n typedef ::cppu::PropertySetMixin<com::sun::star::report::XReportEngine> ReportEnginePropertySet;\n\n class OReportEngineJFree : public comphelper::OMutexAndBroadcastHelper,\n public ReportEngineBase,\n public ReportEnginePropertySet\n {\n typedef ::std::multimap< ::rtl::OUString, ::com::sun::star::uno::Any , ::comphelper::UStringMixLess> TComponentMap;\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;\n ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > m_xReport;\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator> m_StatusIndicator;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xActiveConnection;\n private:\n OReportEngineJFree(const OReportEngineJFree&);\n OReportEngineJFree& operator=(const OReportEngineJFree&);\n template <typename T> void set( const ::rtl::OUString& _sProperty\n ,const T& _Value\n ,T& _member)\n {\n BoundListeners l;\n {\n ::osl::MutexGuard aGuard(m_aMutex);\n prepareSet(_sProperty, ::com::sun::star::uno::makeAny(_member), ::com::sun::star::uno::makeAny(_Value), &l);\n _member = _Value;\n }\n l.notify();\n }\n\n \/** transform the report defintion format into a jfree report format.\n *\n * \\return The URL of the newly created file.\n *\/\n ::rtl::OUString transform();\n\n \/** returns the file url for a new model\n *\n * \\return The new file url.\n *\/\n ::rtl::OUString getNewOutputName();\n\n \/** generates the order statement defined by the groups of the report\n *\n * \\return the ORDER BY part\n *\/\n ::rtl::OUString getOrderStatement() const;\n protected:\n \/\/ TODO: VirtualFunctionFinder: This is virtual function!\n \/\/\n virtual ~OReportEngineJFree();\n public:\n typedef ::comphelper::ImplementationReference< OReportEngineJFree ,::com::sun::star::report::XReportEngine,::com::sun::star::uno::XWeak > TReportEngine;\n\n OReportEngineJFree(const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& context);\n\n DECLARE_XINTERFACE( )\n \/\/ ::com::sun::star::lang::XServiceInfo\n virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);\n\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );\n static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL\n create(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext);\n \/\/ com::sun::star::beans::XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XReportEngine\n \/\/ Attributes\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > SAL_CALL getReportDefinition() throw (::com::sun::star::uno::RuntimeException) ;\n virtual void SAL_CALL setReportDefinition( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition >& _reportdefinition ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getActiveConnection() throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setActiveConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _activeconnection ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL getStatusIndicator() throw (::com::sun::star::uno::RuntimeException) ;\n virtual void SAL_CALL setStatusIndicator( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator >& _statusindicator ) throw (::com::sun::star::uno::RuntimeException) ;\n \/\/ Methods\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > SAL_CALL createDocumentModel( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ;\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > SAL_CALL createDocumentAlive( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _frame ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ;\n virtual ::com::sun::star::util::URL SAL_CALL createDocument( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ;\n virtual void SAL_CALL interrupt( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ;\n\n \/\/ XComponent\n virtual void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & aListener) throw(::com::sun::star::uno::RuntimeException)\n {\n cppu::WeakComponentImplHelperBase::addEventListener(aListener);\n }\n virtual void SAL_CALL removeEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & aListener) throw(::com::sun::star::uno::RuntimeException)\n {\n cppu::WeakComponentImplHelperBase::removeEventListener(aListener);\n }\n };\n}\n#endif \/\/REPORTDESIGN_API_REPORTENGINEJFREE_HXX\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright NumFOCUS\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#ifndef itkFFTWHalfHermitianToRealInverseFFTImageFilter_hxx\n#define itkFFTWHalfHermitianToRealInverseFFTImageFilter_hxx\n\n#include \"itkFFTWHalfHermitianToRealInverseFFTImageFilter.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkProgressReporter.h\"\n#include \"itkMultiThreaderBase.h\"\n\nnamespace itk\n{\n\ntemplate <typename TInputImage, typename TOutputImage>\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::FFTWHalfHermitianToRealInverseFFTImageFilter()\n{\n#ifndef ITK_USE_CUFFTW\n m_PlanRigor = FFTWGlobalConfiguration::GetPlanRigor();\n#endif\n this->DynamicMultiThreadingOn();\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::BeforeThreadedGenerateData()\n{\n \/\/ Get pointers to the input and output.\n typename InputImageType::ConstPointer inputPtr = this->GetInput();\n typename OutputImageType::Pointer outputPtr = this->GetOutput();\n\n if (!inputPtr || !outputPtr)\n {\n return;\n }\n\n \/\/ We don't have a nice progress to report, but at least this simple line\n \/\/ reports the beginning and the end of the process.\n ProgressReporter progress(this, 0, 1);\n\n \/\/ Allocate output buffer memory.\n outputPtr->SetBufferedRegion(outputPtr->GetRequestedRegion());\n outputPtr->Allocate();\n\n const InputSizeType inputSize = inputPtr->GetLargestPossibleRegion().GetSize();\n const OutputSizeType outputSize = outputPtr->GetLargestPossibleRegion().GetSize();\n\n \/\/ Figure out sizes.\n \/\/ Size of input and output aren't the same which is handled in the superclass,\n \/\/ sort of.\n \/\/ The input size and output size only differ in the fastest moving dimension.\n unsigned int totalOutputSize = 1;\n unsigned int totalInputSize = 1;\n\n for (unsigned i = 0; i < ImageDimension; i++)\n {\n totalOutputSize *= outputSize[i];\n totalInputSize *= inputSize[i];\n }\n\n typename FFTWProxyType::ComplexType * in;\n \/\/ The complex-to-real transform doesn't support the\n \/\/ FFTW_PRESERVE_INPUT flag at this time. So if the input can't be\n \/\/ destroyed, we have to copy the input data to a buffer before\n \/\/ running the IFFT.\n if (m_CanUseDestructiveAlgorithm)\n {\n \/\/ Ok, so lets use the input buffer directly, to save some memory.\n in = (typename FFTWProxyType::ComplexType *)inputPtr->GetBufferPointer();\n }\n else\n {\n \/\/ We must use a buffer where fftw can work and destroy what it wants.\n in = new typename FFTWProxyType::ComplexType[totalInputSize];\n }\n OutputPixelType * out = outputPtr->GetBufferPointer();\n typename FFTWProxyType::PlanType plan;\n\n int sizes[ImageDimension];\n for (unsigned int i = 0; i < ImageDimension; i++)\n {\n sizes[(ImageDimension - 1) - i] = outputSize[i];\n }\n plan = FFTWProxyType::Plan_dft_c2r(ImageDimension,\n sizes,\n in,\n out,\n m_PlanRigor,\n MultiThreaderBase::GetGlobalDefaultNumberOfThreads(),\n !m_CanUseDestructiveAlgorithm);\n if (!m_CanUseDestructiveAlgorithm)\n {\n \/\/ complex<double> and double[2] types are compatible memory layouts.\n \/\/ The reinterpret_cast is used here to\n \/\/ make the \"C\" fftw libary compatible with the c++ complex<double>.\n std::copy_n(\n inputPtr->GetBufferPointer(), totalInputSize, reinterpret_cast<typename InputImageType::PixelType *>(in));\n }\n FFTWProxyType::Execute(plan);\n\n \/\/ Some cleanup.\n FFTWProxyType::DestroyPlan(plan);\n if (!m_CanUseDestructiveAlgorithm)\n {\n delete[] in;\n }\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::DynamicThreadedGenerateData(\n const OutputRegionType & outputRegionForThread)\n{\n using IteratorType = ImageRegionIterator<OutputImageType>;\n unsigned long totalOutputSize = this->GetOutput()->GetRequestedRegion().GetNumberOfPixels();\n IteratorType it(this->GetOutput(), outputRegionForThread);\n while (!it.IsAtEnd())\n {\n it.Set(it.Value() \/ totalOutputSize);\n ++it;\n }\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::UpdateOutputData(DataObject * output)\n{\n \/\/ We need to catch that information now, because it is changed\n \/\/ later during the pipeline execution, and thus can't be grabbed in\n \/\/ GenerateData().\n m_CanUseDestructiveAlgorithm = this->GetInput()->GetReleaseDataFlag();\n Superclass::UpdateOutputData(output);\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os,\n Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n\n#ifndef ITK_USE_CUFFTW\n os << indent << \"PlanRigor: \" << FFTWGlobalConfiguration::GetPlanRigorName(m_PlanRigor) << \" (\" << m_PlanRigor << \")\"\n << std::endl;\n#endif\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nSizeValueType\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::GetSizeGreatestPrimeFactor() const\n{\n return FFTWProxyType::GREATEST_PRIME_FACTOR;\n}\n\n} \/\/ namespace itk\n#endif \/\/ _itkFFTWHalfHermitianToRealInverseFFTImageFilter_hxx\n<commit_msg>COMP: Preserve const qualifier for variable<commit_after>\/*=========================================================================\n *\n * Copyright NumFOCUS\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#ifndef itkFFTWHalfHermitianToRealInverseFFTImageFilter_hxx\n#define itkFFTWHalfHermitianToRealInverseFFTImageFilter_hxx\n\n#include \"itkFFTWHalfHermitianToRealInverseFFTImageFilter.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkProgressReporter.h\"\n#include \"itkMultiThreaderBase.h\"\n\nnamespace itk\n{\n\ntemplate <typename TInputImage, typename TOutputImage>\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::FFTWHalfHermitianToRealInverseFFTImageFilter()\n{\n#ifndef ITK_USE_CUFFTW\n m_PlanRigor = FFTWGlobalConfiguration::GetPlanRigor();\n#endif\n this->DynamicMultiThreadingOn();\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::BeforeThreadedGenerateData()\n{\n \/\/ Get pointers to the input and output.\n typename InputImageType::ConstPointer inputPtr = this->GetInput();\n typename OutputImageType::Pointer outputPtr = this->GetOutput();\n\n if (!inputPtr || !outputPtr)\n {\n return;\n }\n\n \/\/ We don't have a nice progress to report, but at least this simple line\n \/\/ reports the beginning and the end of the process.\n ProgressReporter progress(this, 0, 1);\n\n \/\/ Allocate output buffer memory.\n outputPtr->SetBufferedRegion(outputPtr->GetRequestedRegion());\n outputPtr->Allocate();\n\n const InputSizeType inputSize = inputPtr->GetLargestPossibleRegion().GetSize();\n const OutputSizeType outputSize = outputPtr->GetLargestPossibleRegion().GetSize();\n\n \/\/ Figure out sizes.\n \/\/ Size of input and output aren't the same which is handled in the superclass,\n \/\/ sort of.\n \/\/ The input size and output size only differ in the fastest moving dimension.\n unsigned int totalOutputSize = 1;\n unsigned int totalInputSize = 1;\n\n for (unsigned i = 0; i < ImageDimension; i++)\n {\n totalOutputSize *= outputSize[i];\n totalInputSize *= inputSize[i];\n }\n\n \/\/ The complex-to-real transform doesn't support the\n \/\/ FFTW_PRESERVE_INPUT flag at this time. So if the input can't be\n \/\/ destroyed, we have to copy the input data to a buffer before\n \/\/ running the IFFT.\n typename FFTWProxyType::ComplexType * const in = [&]() -> typename FFTWProxyType::ComplexType *\n {\n if (m_CanUseDestructiveAlgorithm)\n {\n \/\/ Ok, so lets use the input buffer directly, to save some memory.\n return const_cast<typename FFTWProxyType::ComplexType *>(\n reinterpret_cast<const typename FFTWProxyType::ComplexType *>(inputPtr->GetBufferPointer()));\n }\n else\n {\n \/\/ We must use a buffer where fftw can work and destroy what it wants.\n return new typename FFTWProxyType::ComplexType[totalInputSize];\n }\n }\n ();\n OutputPixelType * out = outputPtr->GetBufferPointer();\n typename FFTWProxyType::PlanType plan;\n\n int sizes[ImageDimension];\n for (unsigned int i = 0; i < ImageDimension; i++)\n {\n sizes[(ImageDimension - 1) - i] = outputSize[i];\n }\n plan = FFTWProxyType::Plan_dft_c2r(ImageDimension,\n sizes,\n in,\n out,\n m_PlanRigor,\n MultiThreaderBase::GetGlobalDefaultNumberOfThreads(),\n !m_CanUseDestructiveAlgorithm);\n if (!m_CanUseDestructiveAlgorithm)\n {\n \/\/ complex<double> and double[2] types are compatible memory layouts.\n \/\/ The reinterpret_cast is used here to\n \/\/ make the \"C\" fftw libary compatible with the c++ complex<double>.\n std::copy_n(\n inputPtr->GetBufferPointer(), totalInputSize, reinterpret_cast<typename InputImageType::PixelType *>(in));\n }\n FFTWProxyType::Execute(plan);\n\n \/\/ Some cleanup.\n FFTWProxyType::DestroyPlan(plan);\n if (!m_CanUseDestructiveAlgorithm)\n {\n delete[] in;\n }\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::DynamicThreadedGenerateData(\n const OutputRegionType & outputRegionForThread)\n{\n using IteratorType = ImageRegionIterator<OutputImageType>;\n unsigned long totalOutputSize = this->GetOutput()->GetRequestedRegion().GetNumberOfPixels();\n IteratorType it(this->GetOutput(), outputRegionForThread);\n while (!it.IsAtEnd())\n {\n it.Set(it.Value() \/ totalOutputSize);\n ++it;\n }\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::UpdateOutputData(DataObject * output)\n{\n \/\/ We need to catch that information now, because it is changed\n \/\/ later during the pipeline execution, and thus can't be grabbed in\n \/\/ GenerateData().\n m_CanUseDestructiveAlgorithm = this->GetInput()->GetReleaseDataFlag();\n Superclass::UpdateOutputData(output);\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os,\n Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n\n#ifndef ITK_USE_CUFFTW\n os << indent << \"PlanRigor: \" << FFTWGlobalConfiguration::GetPlanRigorName(m_PlanRigor) << \" (\" << m_PlanRigor << \")\"\n << std::endl;\n#endif\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nSizeValueType\nFFTWHalfHermitianToRealInverseFFTImageFilter<TInputImage, TOutputImage>::GetSizeGreatestPrimeFactor() const\n{\n return FFTWProxyType::GREATEST_PRIME_FACTOR;\n}\n\n} \/\/ namespace itk\n#endif \/\/ _itkFFTWHalfHermitianToRealInverseFFTImageFilter_hxx\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"connected.hpp\"\n\nBOOST_FIXTURE_TEST_CASE( respond_with_an_unknown_rsp, unconnected )\n{\n check_single_ll_control_pdu(\n { 0x03, 0x01, 0xff },\n {\n 0x03, 0x02,\n 0x07, 0xff\n },\n \"respond_with_an_unknown_rsp\"\n );\n}\n\nBOOST_FIXTURE_TEST_CASE( responding_in_feature_setup, unconnected )\n{\n}\n\nBOOST_FIXTURE_TEST_CASE( respond_to_a_version_ind, unconnected )\n{\n check_single_ll_control_pdu(\n {\n 0x03, 0x06,\n 0x0C, \/\/ LL_VERSION_IND\n 0x08, \/\/ VersNr = Core Specification 4.2\n 0x00, 0x02, \/\/ CompId\n 0x00, 0x00 \/\/ SubVersNr\n },\n {\n 0x03, 0x06,\n 0x0C, \/\/ LL_VERSION_IND\n 0x09, \/\/ VersNr = Core Specification 5.0\n 0x69, 0x02, \/\/ CompId\n 0x00, 0x00 \/\/ SubVersNr\n },\n \"respond_to_a_version_ind\"\n );\n}\n\nBOOST_FIXTURE_TEST_CASE( respond_to_a_ping, unconnected )\n{\n check_single_ll_control_pdu(\n {\n 0x03, 0x01,\n 0x12 \/\/ LL_PING_REQ\n },\n {\n 0x03, 0x01,\n 0x13 \/\/ LL_PING_RSP\n },\n \"respond_to_a_ping\"\n );\n}\n\nBOOST_FIXTURE_TEST_CASE( starts_advertising_after_termination, unconnected )\n{\n respond_to( 37, valid_connection_request_pdu );\n add_connection_event_respond(\n {\n 0x03, 0x02,\n 0x02, 0x12\n } );\n\n run();\n\n \/\/ the second advertising PDU is the response to the terminate PDU\n \/\/ and must happen much earlier than the supervision timeout\n BOOST_REQUIRE_GT( advertisings().size(), 1u );\n const auto& second_advertisment = advertisings()[ 1 ];\n\n BOOST_CHECK_LT( second_advertisment.on_air_time, bluetoe::link_layer::delta_time::msec( 50 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( do_not_respond_to_UNKNOWN_RSP, unconnected )\n{\n check_single_ll_control_pdu(\n {\n 0x03, 0x02,\n 0x07, \/\/ LL_UNKNOWN_RSP\n 0x07 \/\/ request opcode\n },\n {\n 0x01, 0x00\n },\n \"do_not_respond_to_UNKNOWN_RSP\"\n );\n}\n\nBOOST_FIXTURE_TEST_CASE( do_not_respond_to_UNKNOWN_RSP_even_if_broken, unconnected )\n{\n check_single_ll_control_pdu(\n {\n 0x03, 0x03,\n 0x07, \/\/ LL_UNKNOWN_RSP\n 0x07, \/\/ request opcode\n 0xff \/\/ additional byte\n },\n {\n 0x01, 0x00\n },\n \"do_not_respond_to_UNKNOWN_RSP\"\n );\n}\n<commit_msg>add tests for Channel Map Update procedure<commit_after>#define BOOST_TEST_MODULE\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"connected.hpp\"\n\nBOOST_FIXTURE_TEST_CASE( respond_with_an_unknown_rsp, unconnected )\n{\n check_single_ll_control_pdu(\n { 0x03, 0x01, 0xff },\n {\n 0x03, 0x02,\n 0x07, 0xff\n },\n \"respond_with_an_unknown_rsp\"\n );\n}\n\nBOOST_FIXTURE_TEST_CASE( responding_in_feature_setup, unconnected )\n{\n}\n\nBOOST_FIXTURE_TEST_CASE( respond_to_a_version_ind, unconnected )\n{\n check_single_ll_control_pdu(\n {\n 0x03, 0x06,\n 0x0C, \/\/ LL_VERSION_IND\n 0x08, \/\/ VersNr = Core Specification 4.2\n 0x00, 0x02, \/\/ CompId\n 0x00, 0x00 \/\/ SubVersNr\n },\n {\n 0x03, 0x06,\n 0x0C, \/\/ LL_VERSION_IND\n 0x09, \/\/ VersNr = Core Specification 5.0\n 0x69, 0x02, \/\/ CompId\n 0x00, 0x00 \/\/ SubVersNr\n },\n \"respond_to_a_version_ind\"\n );\n}\n\nBOOST_FIXTURE_TEST_CASE( respond_to_a_ping, unconnected )\n{\n check_single_ll_control_pdu(\n {\n 0x03, 0x01,\n 0x12 \/\/ LL_PING_REQ\n },\n {\n 0x03, 0x01,\n 0x13 \/\/ LL_PING_RSP\n },\n \"respond_to_a_ping\"\n );\n}\n\nBOOST_FIXTURE_TEST_CASE( starts_advertising_after_termination, unconnected )\n{\n respond_to( 37, valid_connection_request_pdu );\n add_connection_event_respond(\n {\n 0x03, 0x02,\n 0x02, 0x12\n } );\n\n run();\n\n \/\/ the second advertising PDU is the response to the terminate PDU\n \/\/ and must happen much earlier than the supervision timeout\n BOOST_REQUIRE_GT( advertisings().size(), 1u );\n const auto& second_advertisment = advertisings()[ 1 ];\n\n BOOST_CHECK_LT( second_advertisment.on_air_time, bluetoe::link_layer::delta_time::msec( 50 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( do_not_respond_to_UNKNOWN_RSP, unconnected )\n{\n check_single_ll_control_pdu(\n {\n 0x03, 0x02,\n 0x07, \/\/ LL_UNKNOWN_RSP\n 0x07 \/\/ request opcode\n },\n {\n 0x01, 0x00\n },\n \"do_not_respond_to_UNKNOWN_RSP\"\n );\n}\n\nBOOST_FIXTURE_TEST_CASE( do_not_respond_to_UNKNOWN_RSP_even_if_broken, unconnected )\n{\n check_single_ll_control_pdu(\n {\n 0x03, 0x03,\n 0x07, \/\/ LL_UNKNOWN_RSP\n 0x07, \/\/ request opcode\n 0xff \/\/ additional byte\n },\n {\n 0x01, 0x00\n },\n \"do_not_respond_to_UNKNOWN_RSP\"\n );\n}\n\n\/*\n * Example from core spec Vol6, Part B, 5.1.2\n *\/\nBOOST_FIXTURE_TEST_CASE( Channel_Map_Update_procedure, unconnected )\n{\n respond_to( 37, valid_connection_request_pdu );\n\n ll_control_pdu(\n {\n 0x01, \/\/ LL_CHANNEL_MAP_IND\n 0xff, 0xf7, 0xff, 0xff, 0x1f, \/\/ new channel map: all channels enabled except channel 11\n 0x64, 0x00 \/\/ Instance: 100dez\n }\n );\n\n ll_empty_pdus( 101 );\n\n run();\n\n BOOST_CHECK_EQUAL( connection_events()[ 99 ].channel, 1u );\n BOOST_CHECK_EQUAL( connection_events()[ 100 ].channel, 12u );\n BOOST_CHECK_EQUAL( connection_events()[ 101 ].channel, 21u );\n}\n\nBOOST_FIXTURE_TEST_CASE( Channel_Map_Update_procedure_With_Latency, unconnected )\n{\n respond_to( 37, {\n 0xc5, 0x22, \/\/ header\n 0x3c, 0x1c, 0x62, 0x92, 0xf0, 0x48, \/\/ InitA: 48:f0:92:62:1c:3c (random)\n 0x47, 0x11, 0x08, 0x15, 0x0f, 0xc0, \/\/ AdvA: c0:0f:15:08:11:47 (random)\n 0x5a, 0xb3, 0x9a, 0xaf, \/\/ Access Address\n 0x08, 0x81, 0xf6, \/\/ CRC Init\n 0x03, \/\/ transmit window size\n 0x0b, 0x00, \/\/ window offset\n 0x18, 0x00, \/\/ interval (30ms)\n 0x28, 0x00, \/\/ peripheral latency 40\n 0x48, 0x01, \/\/ connection timeout (3280ms)\n 0xff, 0xff, 0xff, 0xff, 0x1f, \/\/ used channel map\n 0xaa \/\/ hop increment and sleep clock accuracy (10 and 50ppm)\n } );\n\n ll_control_pdu(\n {\n 0x01, \/\/ LL_CHANNEL_MAP_IND\n 0xff, 0xf7, 0xff, 0xff, 0x1f, \/\/ new channel map: all channels enabled except channel 11\n 0x64, 0x00 \/\/ Instance: 100dez\n }\n );\n\n ll_empty_pdus( 5 );\n\n run();\n\n \/\/ First event at instant 0; second at 41, third at 82; 4th at 100\n BOOST_CHECK_EQUAL( connection_events()[ 3 ].channel, 12u );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2017 The nanoFramework project contributors\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n#include <nanoHAL.h>\n#include <nanoCLR_Application.h>\n#include <nanoCLR_Runtime.h>\n#include <nanoCLR_Types.h>\n#include <CLRStartup.h>\n\n\/\/ FIXME \n\/\/ these are dummy data, we'll have to figure out how to fill these after the build happens\nchar nanoCLR_Dat_Start[100 ];\nchar nanoCLR_Dat_End [1 ];\n\nstruct Settings\n{\n CLR_SETTINGS m_clrOptions;\n bool m_fInitialized;\n\n \/\/--\/\/\n \n HRESULT Initialize(CLR_SETTINGS params)\n {\n NANOCLR_HEADER();\n\n m_clrOptions = params;\n\n NANOCLR_CHECK_HRESULT(CLR_RT_ExecutionEngine::CreateInstance());\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Created EE.\\r\\n\" );\n#endif\n\n#if !defined(BUILD_RTM)\n if(params.WaitForDebugger)\n {\n CLR_EE_DBG_SET( Stopped );\n }\n#endif\n\n NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.StartHardware());\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Started Hardware.\\r\\n\" );\n#endif\n\n \/\/ UNDONE: FIXME: CLR_DBG_Debugger::Debugger_Discovery();\n\n m_fInitialized = true;\n\n\n NANOCLR_NOCLEANUP();\n }\n\n \n HRESULT LoadAssembly( const CLR_RECORD_ASSEMBLY* header, CLR_RT_Assembly*& assm )\n { \n NANOCLR_HEADER();\n \n const CLR_RT_NativeAssemblyData *pNativeAssmData;\n \n NANOCLR_CHECK_HRESULT(CLR_RT_Assembly::CreateInstance( header, assm ));\n \n \/\/ Get handlers for native functions in assembly\n pNativeAssmData = GetAssemblyNativeData( assm->m_szName );\n \n \/\/ If pNativeAssmData not NULL- means this assembly has native calls and there is pointer to table with native calls.\n if ( pNativeAssmData != NULL )\n { \n \/\/ First verify that check sum in assembly object matches hardcoded check sum. \n if ( assm->m_header->nativeMethodsChecksum != pNativeAssmData->m_checkSum )\n {\n CLR_Debug::Printf(\"***********************************************************************\\r\\n\");\n CLR_Debug::Printf(\"* *\\r\\n\");\n CLR_Debug::Printf(\"* ERROR!!!! Firmware version does not match managed code version!!!! *\\r\\n\");\n CLR_Debug::Printf(\"* *\\r\\n\");\n CLR_Debug::Printf(\"* *\\r\\n\");\n CLR_Debug::Printf(\"* Invalid native checksum: %s 0x%08X!=0x%08X *\\r\\n\",\n assm->m_szName,\n assm->m_header->nativeMethodsChecksum,\n pNativeAssmData->m_checkSum\n );\n CLR_Debug::Printf(\"* *\\r\\n\");\n CLR_Debug::Printf(\"***********************************************************************\\r\\n\");\n\n NANOCLR_SET_AND_LEAVE(CLR_E_ASSM_WRONG_CHECKSUM);\n }\n\n \/\/ Assembly has valid pointer to table with native methods. Save it.\n assm->m_nativeCode = (const CLR_RT_MethodHandler *)pNativeAssmData->m_pNativeMethods;\n }\n g_CLR_RT_TypeSystem.Link( assm );\n NANOCLR_NOCLEANUP();\n }\n\n\n HRESULT Load()\n {\n NANOCLR_HEADER();\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Create TS.\\r\\n\" );\n#endif\n \/\/NANOCLR_CHECK_HRESULT(LoadKnownAssemblies( (char*)&__deployment_start__, (char*)&__deployment_end__ ));\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Loading Deployment Assemblies.\\r\\n\" );\n#endif\n\n LoadDeploymentAssemblies();\n\n \/\/--\/\/\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Resolving.\\r\\n\" );\n#endif\n NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.ResolveAll());\n\n g_CLR_RT_Persistence_Manager.Initialize();\n\n \/\/ UNDONE: FIXME: NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.PrepareForExecution());\n\n#if defined(NANOCLR_PROFILE_HANDLER)\n CLR_PROF_Handler::Calibrate();\n#endif\n\n NANOCLR_CLEANUP();\n\n#if !defined(BUILD_RTM)\n if(FAILED(hr)) CLR_Debug::Printf( \"Error: %08x\\r\\n\", hr );\n#endif\n\n NANOCLR_CLEANUP_END();\n }\n\n HRESULT LoadKnownAssemblies( char* start, char* end )\n {\n \/\/--\/\/\n NANOCLR_HEADER();\n char *assStart = start;\n char *assEnd = end;\n const CLR_RECORD_ASSEMBLY* header;\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf(\" Loading start at %x, end %x\\r\\n\", (unsigned int)assStart, (unsigned int)assEnd);\n#endif \n\n g_buildCRC = SUPPORT_ComputeCRC( assStart, (unsigned int)assEnd -(unsigned int) assStart, 0 );\n\n\n header = (const CLR_RECORD_ASSEMBLY*)assStart;\n\n while((char*)header + sizeof(CLR_RECORD_ASSEMBLY) < assEnd && header->GoodAssembly())\n {\n CLR_RT_Assembly* assm;\n\n \/\/ Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem \n NANOCLR_CHECK_HRESULT(LoadAssembly( header, assm ));\n \n header = (const CLR_RECORD_ASSEMBLY*)ROUNDTOMULTIPLE((size_t)header + header->TotalSize(), CLR_UINT32);\n }\n \n NANOCLR_NOCLEANUP();\n }\n\n\n HRESULT ContiguousBlockAssemblies(BlockStorageStream stream) \n {\n NANOCLR_HEADER();\n\n const CLR_RECORD_ASSEMBLY* header;\n unsigned char * assembliesBuffer ;\n signed int headerInBytes = sizeof(CLR_RECORD_ASSEMBLY);\n unsigned char * headerBuffer = NULL;\n\n headerBuffer = (unsigned char*)CLR_RT_Memory::Allocate( headerInBytes, true ); CHECK_ALLOCATION(headerBuffer);\n CLR_RT_Memory::ZeroFill( headerBuffer, headerInBytes );\n\n while(TRUE)\n {\n if(!BlockStorageStream_Read(&stream, &headerBuffer, headerInBytes )) break;\n\n header = (const CLR_RECORD_ASSEMBLY*)headerBuffer;\n\n \/\/ check header first before read\n if(!header->GoodHeader())\n {\n break;\n }\n\n unsigned int assemblySizeInByte = ROUNDTOMULTIPLE(header->TotalSize(), CLR_UINT32);\n\n \/\/ read the assemblies\n assembliesBuffer = (unsigned char*)CLR_RT_Memory::Allocate_And_Erase( assemblySizeInByte, CLR_RT_HeapBlock ::HB_Unmovable );\n \n if (!assembliesBuffer) \n {\n \/\/ release the headerbuffer which has being used and leave\n CLR_RT_Memory::Release( headerBuffer );\n \n NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_MEMORY);\n }\n\n BlockStorageStream_Seek(&stream, -headerInBytes, BlockStorageStream_SeekCurrent);\n\n if(!BlockStorageStream_Read(&stream, &assembliesBuffer, assemblySizeInByte)) break;\n\n header = (const CLR_RECORD_ASSEMBLY*)assembliesBuffer;\n\n if(!header->GoodAssembly())\n {\n CLR_RT_Memory::Release( assembliesBuffer );\n break;\n }\n \n \/\/ we have good Assembly \n\n CLR_RT_Assembly* assm;\n\n CLR_Debug::Printf( \"Attaching deployed file.\\r\\n\" );\n\n \/\/ Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem \n if (FAILED(LoadAssembly(header, assm)))\n {\n CLR_RT_Memory::Release( assembliesBuffer );\n break;\n }\n assm->m_flags |= CLR_RT_Assembly::Deployed;\n }\n\n CLR_RT_Memory::Release( headerBuffer );\n \n NANOCLR_NOCLEANUP();\n }\n\n HRESULT LoadDeploymentAssemblies()\n {\n NANOCLR_HEADER();\n\n \/\/ perform initialization of BlockStorageStream structure\n BlockStorageStream stream;\n\n \/\/ init the stream for deployment storage\n if (!BlockStorageStream_Initialize(&stream, StorageUsage_DEPLOYMENT))\n {\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"ERROR: failed to initialize DEPLOYMENT storage\\r\\n\" );\n#endif \n NANOCLR_SET_AND_LEAVE(CLR_E_NOT_SUPPORTED);\n }\n\n ContiguousBlockAssemblies(stream);\n \n NANOCLR_NOCLEANUP();\n }\n\n void Cleanup()\n {\n g_CLR_RT_Persistence_Manager.Uninitialize();\n\n \/\/ UNDONE: FIXME: CLR_RT_ExecutionEngine::DeleteInstance();\n\n m_fInitialized = false;\n }\n\n Settings()\n {\n m_fInitialized = false;\n }\n\n};\n\n\nstatic Settings s_ClrSettings;\n\nvoid ClrStartup(CLR_SETTINGS params)\n{\n NATIVE_PROFILE_CLR_STARTUP();\n Settings settings;\n ASSERT(sizeof(CLR_RT_HeapBlock_Raw) == sizeof(CLR_RT_HeapBlock));\n bool softReboot;\n\n do\n {\n softReboot = false;\n\n CLR_RT_Assembly::InitString();\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"\\r\\nnanoCLR (Build %d.%d.%d.%d)\\r\\n\\r\\n\", VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD, VERSION_REVISION );\n#endif\n\n CLR_RT_Memory::Reset();\n \n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Starting...\\r\\n\" );\n#endif\n\n\n HRESULT hr;\n\n if(SUCCEEDED(hr = s_ClrSettings.Initialize(params)))\n {\n if(SUCCEEDED(hr = s_ClrSettings.Load()))\n {\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Ready.\\r\\n\" );\n#endif\n\n (void)g_CLR_RT_ExecutionEngine.Execute( NULL, params.MaxContextSwitches );\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Done.\\r\\n\" );\n#endif\n }\n }\n\n if( CLR_EE_DBG_IS_NOT( RebootPending ))\n {\n#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)\n CLR_EE_DBG_SET_MASK(State_ProgramExited, State_Mask);\n CLR_EE_DBG_EVENT_BROADCAST(CLR_DBG_Commands::c_Monitor_ProgramExit, 0, NULL, WP_Flags_c_NonCritical);\n#endif \/\/#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)\n\n if(params.EnterDebuggerLoopAfterExit)\n {\n \/\/ UNDONE: FIXME: CLR_DBG_Debugger::Debugger_WaitForCommands();\n }\n }\n\n \/\/ DO NOT USE 'ELSE IF' here because the state can change in Debugger_WaitForCommands() call\n \n if( CLR_EE_DBG_IS( RebootPending ))\n {\n if(CLR_EE_REBOOT_IS( ClrOnly ))\n {\n softReboot = true;\n\n params.WaitForDebugger = CLR_EE_REBOOT_IS(ClrOnlyStopDebugger);\n \n s_ClrSettings.Cleanup();\n\n \/\/ UNDONE: FIXME: HAL_Uninitialize();\n\n \/\/ UNDONE: FIXME: SmartPtr_IRQ::ForceDisabled();\n\n \/\/re-init the hal for the reboot (initially it is called in bootentry)\n \/\/ UNDONE: FIXME: HAL_Initialize();\n\n \/\/ make sure interrupts are back on\n \/\/ UNDONE: FIXME: SmartPtr_IRQ::ForceEnabled();\n }\n else\n {\n CPU_Reset();\n }\n }\n\n } while( softReboot );\n\n}\n<commit_msg>Improve ContiguousBlockAssemblies (#371)<commit_after>\/\/\n\/\/ Copyright (c) 2017 The nanoFramework project contributors\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n#include <nanoHAL.h>\n#include <nanoCLR_Application.h>\n#include <nanoCLR_Runtime.h>\n#include <nanoCLR_Types.h>\n#include <CLRStartup.h>\n\n\/\/ FIXME \n\/\/ these are dummy data, we'll have to figure out how to fill these after the build happens\nchar nanoCLR_Dat_Start[100 ];\nchar nanoCLR_Dat_End [1 ];\n\nstruct Settings\n{\n CLR_SETTINGS m_clrOptions;\n bool m_fInitialized;\n\n \/\/--\/\/\n \n HRESULT Initialize(CLR_SETTINGS params)\n {\n NANOCLR_HEADER();\n\n m_clrOptions = params;\n\n NANOCLR_CHECK_HRESULT(CLR_RT_ExecutionEngine::CreateInstance());\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Created EE.\\r\\n\" );\n#endif\n\n#if !defined(BUILD_RTM)\n if(params.WaitForDebugger)\n {\n CLR_EE_DBG_SET( Stopped );\n }\n#endif\n\n NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.StartHardware());\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Started Hardware.\\r\\n\" );\n#endif\n\n \/\/ UNDONE: FIXME: CLR_DBG_Debugger::Debugger_Discovery();\n\n m_fInitialized = true;\n\n\n NANOCLR_NOCLEANUP();\n }\n\n \n HRESULT LoadAssembly( const CLR_RECORD_ASSEMBLY* header, CLR_RT_Assembly*& assm )\n { \n NANOCLR_HEADER();\n \n const CLR_RT_NativeAssemblyData *pNativeAssmData;\n \n NANOCLR_CHECK_HRESULT(CLR_RT_Assembly::CreateInstance( header, assm ));\n \n \/\/ Get handlers for native functions in assembly\n pNativeAssmData = GetAssemblyNativeData( assm->m_szName );\n \n \/\/ If pNativeAssmData not NULL- means this assembly has native calls and there is pointer to table with native calls.\n if ( pNativeAssmData != NULL )\n { \n \/\/ First verify that check sum in assembly object matches hardcoded check sum. \n if ( assm->m_header->nativeMethodsChecksum != pNativeAssmData->m_checkSum )\n {\n CLR_Debug::Printf(\"***********************************************************************\\r\\n\");\n CLR_Debug::Printf(\"* *\\r\\n\");\n CLR_Debug::Printf(\"* ERROR!!!! Firmware version does not match managed code version!!!! *\\r\\n\");\n CLR_Debug::Printf(\"* *\\r\\n\");\n CLR_Debug::Printf(\"* *\\r\\n\");\n CLR_Debug::Printf(\"* Invalid native checksum: %s 0x%08X!=0x%08X *\\r\\n\",\n assm->m_szName,\n assm->m_header->nativeMethodsChecksum,\n pNativeAssmData->m_checkSum\n );\n CLR_Debug::Printf(\"* *\\r\\n\");\n CLR_Debug::Printf(\"***********************************************************************\\r\\n\");\n\n NANOCLR_SET_AND_LEAVE(CLR_E_ASSM_WRONG_CHECKSUM);\n }\n\n \/\/ Assembly has valid pointer to table with native methods. Save it.\n assm->m_nativeCode = (const CLR_RT_MethodHandler *)pNativeAssmData->m_pNativeMethods;\n }\n g_CLR_RT_TypeSystem.Link( assm );\n NANOCLR_NOCLEANUP();\n }\n\n\n HRESULT Load()\n {\n NANOCLR_HEADER();\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Create TS.\\r\\n\" );\n#endif\n \/\/NANOCLR_CHECK_HRESULT(LoadKnownAssemblies( (char*)&__deployment_start__, (char*)&__deployment_end__ ));\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Loading Deployment Assemblies.\\r\\n\" );\n#endif\n\n LoadDeploymentAssemblies();\n\n \/\/--\/\/\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Resolving.\\r\\n\" );\n#endif\n NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.ResolveAll());\n\n g_CLR_RT_Persistence_Manager.Initialize();\n\n NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.PrepareForExecution());\n\n#if defined(NANOCLR_PROFILE_HANDLER)\n CLR_PROF_Handler::Calibrate();\n#endif\n\n NANOCLR_CLEANUP();\n\n#if !defined(BUILD_RTM)\n if(FAILED(hr)) CLR_Debug::Printf( \"Error: %08x\\r\\n\", hr );\n#endif\n\n NANOCLR_CLEANUP_END();\n }\n\n HRESULT LoadKnownAssemblies( char* start, char* end )\n {\n \/\/--\/\/\n NANOCLR_HEADER();\n char *assStart = start;\n char *assEnd = end;\n const CLR_RECORD_ASSEMBLY* header;\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf(\" Loading start at %x, end %x\\r\\n\", (unsigned int)assStart, (unsigned int)assEnd);\n#endif \n\n g_buildCRC = SUPPORT_ComputeCRC( assStart, (unsigned int)assEnd -(unsigned int) assStart, 0 );\n\n\n header = (const CLR_RECORD_ASSEMBLY*)assStart;\n\n while((char*)header + sizeof(CLR_RECORD_ASSEMBLY) < assEnd && header->GoodAssembly())\n {\n CLR_RT_Assembly* assm;\n\n \/\/ Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem \n NANOCLR_CHECK_HRESULT(LoadAssembly( header, assm ));\n \n header = (const CLR_RECORD_ASSEMBLY*)ROUNDTOMULTIPLE((size_t)header + header->TotalSize(), CLR_UINT32);\n }\n \n NANOCLR_NOCLEANUP();\n }\n\n\n HRESULT ContiguousBlockAssemblies(BlockStorageStream stream) \n {\n NANOCLR_HEADER();\n\n const CLR_RECORD_ASSEMBLY* header;\n unsigned char * assembliesBuffer ;\n signed int headerInBytes = sizeof(CLR_RECORD_ASSEMBLY);\n unsigned char * headerBuffer = NULL;\n\n while(TRUE)\n {\n if(!BlockStorageStream_Read(&stream, &headerBuffer, headerInBytes )) break;\n\n header = (const CLR_RECORD_ASSEMBLY*)headerBuffer;\n\n \/\/ check header first before read\n if(!header->GoodHeader())\n {\n \/\/ check failed, try to continue to the next \n continue;\n }\n\n unsigned int assemblySizeInByte = ROUNDTOMULTIPLE(header->TotalSize(), CLR_UINT32);\n\n \/\/ advance stream beyond header\n BlockStorageStream_Seek(&stream, -headerInBytes, BlockStorageStream_SeekCurrent);\n\n \/\/ read the assembly\n if(!BlockStorageStream_Read(&stream, &assembliesBuffer, assemblySizeInByte)) break;\n\n header = (const CLR_RECORD_ASSEMBLY*)assembliesBuffer;\n\n if(!header->GoodAssembly())\n {\n \/\/ check failed, try to continue to the next \n continue;\n }\n \n \/\/ we have good Assembly \n CLR_RT_Assembly* assm;\n\n CLR_Debug::Printf( \"Attaching deployed file.\\r\\n\" );\n\n \/\/ Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem \n if (FAILED(LoadAssembly(header, assm)))\n {\n \/\/ load failed, try to continue to the next \n continue;\n }\n\n \/\/ load successfull, mark as deployed\n assm->m_flags |= CLR_RT_Assembly::Deployed;\n }\n \n NANOCLR_NOCLEANUP();\n }\n\n HRESULT LoadDeploymentAssemblies()\n {\n NANOCLR_HEADER();\n\n \/\/ perform initialization of BlockStorageStream structure\n BlockStorageStream stream;\n\n \/\/ init the stream for deployment storage\n if (!BlockStorageStream_Initialize(&stream, StorageUsage_DEPLOYMENT))\n {\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"ERROR: failed to initialize DEPLOYMENT storage\\r\\n\" );\n#endif \n NANOCLR_SET_AND_LEAVE(CLR_E_NOT_SUPPORTED);\n }\n\n ContiguousBlockAssemblies(stream);\n \n NANOCLR_NOCLEANUP();\n }\n\n void Cleanup()\n {\n g_CLR_RT_Persistence_Manager.Uninitialize();\n\n \/\/ UNDONE: FIXME: CLR_RT_ExecutionEngine::DeleteInstance();\n\n m_fInitialized = false;\n }\n\n Settings()\n {\n m_fInitialized = false;\n }\n\n};\n\n\nstatic Settings s_ClrSettings;\n\nvoid ClrStartup(CLR_SETTINGS params)\n{\n NATIVE_PROFILE_CLR_STARTUP();\n Settings settings;\n ASSERT(sizeof(CLR_RT_HeapBlock_Raw) == sizeof(CLR_RT_HeapBlock));\n bool softReboot;\n\n do\n {\n softReboot = false;\n\n CLR_RT_Assembly::InitString();\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"\\r\\nnanoCLR (Build %d.%d.%d.%d)\\r\\n\\r\\n\", VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD, VERSION_REVISION );\n#endif\n\n CLR_RT_Memory::Reset();\n \n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Starting...\\r\\n\" );\n#endif\n\n\n HRESULT hr;\n\n if(SUCCEEDED(hr = s_ClrSettings.Initialize(params)))\n {\n if(SUCCEEDED(hr = s_ClrSettings.Load()))\n {\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Ready.\\r\\n\" );\n#endif\n\n (void)g_CLR_RT_ExecutionEngine.Execute( NULL, params.MaxContextSwitches );\n\n#if !defined(BUILD_RTM)\n CLR_Debug::Printf( \"Done.\\r\\n\" );\n#endif\n }\n }\n\n if( CLR_EE_DBG_IS_NOT( RebootPending ))\n {\n#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)\n CLR_EE_DBG_SET_MASK(State_ProgramExited, State_Mask);\n CLR_EE_DBG_EVENT_BROADCAST(CLR_DBG_Commands::c_Monitor_ProgramExit, 0, NULL, WP_Flags_c_NonCritical);\n#endif \/\/#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)\n\n if(params.EnterDebuggerLoopAfterExit)\n {\n \/\/ UNDONE: FIXME: CLR_DBG_Debugger::Debugger_WaitForCommands();\n }\n }\n\n \/\/ DO NOT USE 'ELSE IF' here because the state can change in Debugger_WaitForCommands() call\n \n if( CLR_EE_DBG_IS( RebootPending ))\n {\n if(CLR_EE_REBOOT_IS( ClrOnly ))\n {\n softReboot = true;\n\n params.WaitForDebugger = CLR_EE_REBOOT_IS(ClrOnlyStopDebugger);\n \n s_ClrSettings.Cleanup();\n\n \/\/ UNDONE: FIXME: HAL_Uninitialize();\n\n \/\/ UNDONE: FIXME: SmartPtr_IRQ::ForceDisabled();\n\n \/\/re-init the hal for the reboot (initially it is called in bootentry)\n \/\/ UNDONE: FIXME: HAL_Initialize();\n\n \/\/ make sure interrupts are back on\n \/\/ UNDONE: FIXME: SmartPtr_IRQ::ForceEnabled();\n }\n else\n {\n CPU_Reset();\n }\n }\n\n } while( softReboot );\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"rosplan_knowledge_base\/KnowledgeComparitor.h\"\n\n\/* implementation of KnowledgeComparitor.h *\/\nnamespace KCL_rosplan {\n\n\t\/** \n\t * returns true iff a matches the knowledge in b.\n\t *\/\n\tbool KnowledgeComparitor::containsKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) {\n\n\t\tif(a.knowledge_type != b.knowledge_type) return false;\n\t\n\t\tif(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) {\n\t\t\t\n\t\t\t\/\/ check instance knowledge\n\t\t\tif(0!=a.instance_type.compare(b.instance_type)) return false;\n\t\t\tif(a.instance_name!=\"\" && 0!=a.instance_name.compare(b.instance_name)) return false;\n\n\t\t} else {\n\n\t\t\t\/\/ check fact or function\n\t\t\tif(a.attribute_name!=\"\" && 0!=a.attribute_name.compare(b.attribute_name)) return false;\n\t\t\tif(a.is_negative != b.is_negative) return false;\n\t\t\tif(a.values.size() != b.values.size()) return false;\n\t\t\tfor(size_t i=0;i<a.values.size();i++) {\n\t\t\t\tif(\"\"!=a.values[i].value && a.values[i].value != b.values[i].value)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t\/**\n\t * returns true is the knowledge item contains the instance, as instance or attribute parameter.\n\t *\/\n\tbool KnowledgeComparitor::containsInstance(const rosplan_knowledge_msgs::KnowledgeItem &a, std::string &name) {\n\n\t\tif(0==a.instance_name.compare(name))\n\t\t\treturn true;\n\n\t\tfor(size_t i=0;i<a.values.size();i++) {\n\t\t\tif(0==a.values[i].value.compare(name))\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n} \/\/ close namespace\n<commit_msg>checking parameter labels in knowledge base<commit_after>#include \"rosplan_knowledge_base\/KnowledgeComparitor.h\"\n\n\/* implementation of KnowledgeComparitor.h *\/\nnamespace KCL_rosplan {\n\n\t\/** \n\t * returns true iff a matches the knowledge in b.\n\t *\/\n\tbool KnowledgeComparitor::containsKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) {\n\n\t\tif(a.knowledge_type != b.knowledge_type) return false;\n\t\n\t\tif(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) {\n\t\t\t\n\t\t\t\/\/ check instance knowledge\n\t\t\tif(0!=a.instance_type.compare(b.instance_type)) return false;\n\t\t\tif(a.instance_name!=\"\" && 0!=a.instance_name.compare(b.instance_name)) return false;\n\n\t\t} else {\n\n\t\t\t\/\/ check fact or function\n\t\t\tif(a.attribute_name!=\"\" && 0!=a.attribute_name.compare(b.attribute_name)) return false;\n\t\t\tif(a.is_negative != b.is_negative) return false;\n\t\t\tif(a.values.size() != b.values.size()) return false;\n\n\t\t\tfor(size_t i=0;i<a.values.size();i++) {\n\n\t\t\t\t\/\/ don't care about this parameter\n\t\t\t\tif(\"\"==a.values[i].value) continue;\n\n\t\t\t\t\/\/ find matching object in parameters of b\n\t\t\t\tbool found = false;\n\t\t\t\tfor(size_t i=0;i<b.values.size();i++) {\n\t\t\t\t\t if(a.values[i].key == b.values[i].key && a.values[i].value == b.values[i].value) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!found) return false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t\/**\n\t * returns true is the knowledge item contains the instance, as instance or attribute parameter.\n\t *\/\n\tbool KnowledgeComparitor::containsInstance(const rosplan_knowledge_msgs::KnowledgeItem &a, std::string &name) {\n\n\t\tif(0==a.instance_name.compare(name))\n\t\t\treturn true;\n\n\t\tfor(size_t i=0;i<a.values.size();i++) {\n\t\t\tif(0==a.values[i].value.compare(name))\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n} \/\/ close namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ GettingFrameData\n\/\/\n\/\/ Created by 中村 薫 on 2013\/08\/12.\n\/\/ Copyright (c) 2013年 中村 薫. All rights reserved.\n\/\/\n#include <iostream>\n#include <Leap.h>\n\nvoid GettingFramesByPolling()\n{\n Leap::Controller leap;\n \n int64_t lastFrame = 0;\n while ( 1 ) {\n auto frame = leap.frame();\n if ( !leap.isConnected() ) {\n std::cout << \"leap is not connected.\" << std::endl;\n continue;\n }\n \n bool focus = leap.hasFocus();\n if ( !focus ) {\n std::cout << \"application is not focus.\" << std::endl;\n continue;\n }\n \n auto currentFrameid = frame.id();\n if ( currentFrameid == lastFrame ) {\n \/\/std::cout << \"processed frame id.\" << std::endl;\n continue;\n }\n \n \/\/std::cout << \"frame count : \" << (currentFrameid - lastFrame) << std::endl;\n \n lastFrame = currentFrameid;\n \n \/\/ 指の位置の平均値を計算する\n int count = 0;\n Leap::Vector average = Leap::Vector();\n Leap::Finger fingerToAverage = frame.fingers()[0];\n for( int i = 0; i < 10; i++ ) {\n \/\/ フレーム履歴と指のIDで、過去の指の位置を取得する\n Leap::Finger fingerFromFrame = leap.frame(i).finger(fingerToAverage.id());\n if( fingerFromFrame.isValid() ) {\n average += fingerFromFrame.tipPosition();\n count++;\n }\n }\n average \/= count;\n std::cout << \"finger point : \" << average << std::endl;\n }\n}\n\n\nclass SampleListrener : public Leap::Listener\n{\npublic:\n \n virtual void onFocusGained(const Leap::Controller&) {\n std::cout << __FUNCTION__ << std::endl;\n }\n \n virtual void onFocusLost(const Leap::Controller&) {\n std::cout << __FUNCTION__ << std::endl;\n }\n \n};\n\nvoid GettingFramesWithCallbacks()\n{\n SampleListrener listner;\n Leap::Controller leap;\n leap.addListener( listner );\n \n std::cout << \"Press Enter to quit...\" << std::endl;\n std::cin.get();\n \n leap.removeListener( listner );\n}\n\n#if 1\nint main()\n{\n#if 0\n \/\/ ポーリング\n GettingFramesByPolling();\n#else\n \/\/ コールバック\n GettingFramesWithCallbacks();\n#endif\n\n return 0;\n}\n#endif\n\n\n#if 0\nint main()\n{\n Leap::Controller leap;\n int64_t previousFrameId = -1;\n \n \/\/ 以前のフレームを取得する\n \n while ( 1 ) {\n auto frame = leap.frame();\n if ( previousFrameId == frame.id() ) {\n continue;\n }\n \n previousFrameId = frame.id();\n \n \/\/ フレーム更新処理(onFrame()相当)\n }\n \n \/\/ 終了処理(onExit()相当)\n\n return 0;\n}\n#endif\n\n#if 0\nint main()\n{\n bool isPrevConnected = false;\n bool hadPrevFocus = false;\n int64_t previousFrameId = -1;\n \n Leap::Controller leap;\n \n \/\/ 初期化処理(oninit()相当)\n \n while ( 1 ) {\n auto frame = leap.frame();\n \n \/\/ 接続状態を確認する\n {\n bool isCurrentConnected = leap.isConnected();\n if ( isPrevConnected != isCurrentConnected ) {\n if ( isCurrentConnected ) {\n \/\/ Leap Motion コントローラーが接続された(onConnected()相当)\n std::cout << \"Leap Motion connected.\" << std::endl;\n }\n else {\n \/\/ Leap Motion コントローラーが抜かれた(onDisconnected()相当)\n std::cout << \"Leap Motion disconnected.\" << std::endl;\n }\n }\n \n isPrevConnected = isCurrentConnected;\n }\n \n \/\/ フォーカス状態を確認する\n {\n bool hadCurrentFocus = leap.hasFocus();\n if ( hadPrevFocus != hadCurrentFocus ) {\n if ( hadCurrentFocus ) {\n \/\/ アプリケーションのフォーカスが有効になった(onFocusGained()相当)\n std::cout << \"Focus gained.\" << std::endl;\n }\n else {\n \/\/ アプリケーションのフォーカスが無効になった(onFocusLost()相当)\n std::cout << \"Focus lost.\" << std::endl;\n }\n }\n \n hadPrevFocus = hadCurrentFocus;\n }\n \n \/\/ フレームが更新されていなければ何もしない\n {\n if ( previousFrameId == frame.id() ) {\n continue;\n }\n \n previousFrameId = frame.id();\n }\n \n \/\/ フレーム更新処理(onFrame()相当)\n }\n \n \/\/ 終了処理(onExit()相当)\n\n return 0;\n}\n#endif\n\n#if 0\nint main()\n{\n Leap::Controller leap;\n int64_t previousFrameId = -1;\n \n while ( 1 ) {\n \/\/ 最新のフレームを取得する (leap.frame( 0 ) と同じ)\n auto currentFrame = leap.frame();\n if ( previousFrameId == currentFrame.id() ) {\n continue;\n }\n \n previousFrameId = currentFrame.id();\n \n \/\/ 直前の5フレームを取得する\n std::cout << currentFrame.id() << \", \";\n for ( int i = 1; i <= 5; ++i ) {\n auto previousFrame = leap.frame( i );\n std::cout << previousFrame.id() << \", \";\n }\n std::cout << std::endl;\n }\n \n \/\/ 終了処理(onExit()相当)\n \n return 0;\n}\n#endif\n<commit_msg>動作のコメントを追加<commit_after>\/\/\r\n\/\/ main.cpp\r\n\/\/ GettingFrameData\r\n\/\/\r\n\/\/ Created by 中村 薫 on 2013\/08\/12.\r\n\/\/ Copyright (c) 2013年 中村 薫. All rights reserved.\r\n\/\/\r\n#include <iostream>\r\n#include <Leap.h>\r\n\r\n\/\/ ポーリングでフレームを取得する\r\nvoid GettingFramesByPolling()\r\n{\r\n Leap::Controller leap;\r\n \r\n int64_t lastFrame = 0;\r\n while ( 1 ) {\r\n auto frame = leap.frame();\r\n if ( !leap.isConnected() ) {\r\n std::cout << \"leap is not connected.\" << std::endl;\r\n continue;\r\n }\r\n \r\n bool focus = leap.hasFocus();\r\n if ( !focus ) {\r\n std::cout << \"application is not focus.\" << std::endl;\r\n continue;\r\n }\r\n \r\n auto currentFrameid = frame.id();\r\n if ( currentFrameid == lastFrame ) {\r\n \/\/std::cout << \"processed frame id.\" << std::endl;\r\n continue;\r\n }\r\n \r\n \/\/std::cout << \"frame count : \" << (currentFrameid - lastFrame) << std::endl;\r\n \r\n lastFrame = currentFrameid;\r\n \r\n \/\/ 指の位置の平均値を計算する\r\n int count = 0;\r\n Leap::Vector average = Leap::Vector();\r\n Leap::Finger fingerToAverage = frame.fingers()[0];\r\n for( int i = 0; i < 10; i++ ) {\r\n \/\/ フレーム履歴と指のIDで、過去の指の位置を取得する\r\n Leap::Finger fingerFromFrame = leap.frame(i).finger(fingerToAverage.id());\r\n if( fingerFromFrame.isValid() ) {\r\n average += fingerFromFrame.tipPosition();\r\n count++;\r\n }\r\n }\r\n average \/= count;\r\n std::cout << \"finger point : \" << average << std::endl;\r\n }\r\n}\r\n\r\n\r\nclass SampleListrener : public Leap::Listener\r\n{\r\npublic:\r\n \r\n virtual void onFocusGained(const Leap::Controller&) {\r\n std::cout << __FUNCTION__ << std::endl;\r\n }\r\n \r\n virtual void onFocusLost(const Leap::Controller&) {\r\n std::cout << __FUNCTION__ << std::endl;\r\n }\r\n \r\n};\r\n\r\nvoid GettingFramesWithCallbacks()\r\n{\r\n SampleListrener listner;\r\n Leap::Controller leap;\r\n leap.addListener( listner );\r\n \r\n std::cout << \"Press Enter to quit...\" << std::endl;\r\n std::cin.get();\r\n \r\n leap.removeListener( listner );\r\n}\r\n\r\n\/\/ フレームの取り方のサンプル\r\n#if 0\r\nint main()\r\n{\r\n#if 0\r\n \/\/ ポーリング\r\n GettingFramesByPolling();\r\n#else\r\n \/\/ コールバック\r\n GettingFramesWithCallbacks();\r\n#endif\r\n\r\n return 0;\r\n}\r\n#endif\r\n\r\n\r\n\/\/ ポーリング処理の例\r\n#if 0\r\nint main()\r\n{\r\n Leap::Controller leap;\r\n int64_t previousFrameId = -1;\r\n \r\n \/\/ 以前のフレームを取得する\r\n \r\n while ( 1 ) {\r\n auto frame = leap.frame();\r\n if ( previousFrameId == frame.id() ) {\r\n continue;\r\n }\r\n \r\n previousFrameId = frame.id();\r\n \r\n \/\/ フレーム更新処理(onFrame()相当)\r\n }\r\n \r\n \/\/ 終了処理(onExit()相当)\r\n\r\n return 0;\r\n}\r\n#endif\r\n\r\n\/\/ ポーリング時の接続状態およびフォーカス状態を取得する\r\n#if 1\r\nint main()\r\n{\r\n bool isPrevConnected = false;\r\n bool hadPrevFocus = false;\r\n int64_t previousFrameId = -1;\r\n \r\n Leap::Controller leap;\r\n \r\n \/\/ 初期化処理(oninit()相当)\r\n \r\n while ( 1 ) {\r\n auto frame = leap.frame();\r\n \r\n \/\/ 接続状態を確認する\r\n {\r\n bool isCurrentConnected = leap.isConnected();\r\n if ( isPrevConnected != isCurrentConnected ) {\r\n if ( isCurrentConnected ) {\r\n \/\/ Leap Motion コントローラーが接続された(onConnected()相当)\r\n std::cout << \"Leap Motion connected.\" << std::endl;\r\n }\r\n else {\r\n \/\/ Leap Motion コントローラーが抜かれた(onDisconnected()相当)\r\n std::cout << \"Leap Motion disconnected.\" << std::endl;\r\n }\r\n }\r\n \r\n isPrevConnected = isCurrentConnected;\r\n }\r\n \r\n \/\/ フォーカス状態を確認する\r\n {\r\n bool hadCurrentFocus = leap.hasFocus();\r\n if ( hadPrevFocus != hadCurrentFocus ) {\r\n if ( hadCurrentFocus ) {\r\n \/\/ アプリケーションのフォーカスが有効になった(onFocusGained()相当)\r\n std::cout << \"Focus gained.\" << std::endl;\r\n }\r\n else {\r\n \/\/ アプリケーションのフォーカスが無効になった(onFocusLost()相当)\r\n std::cout << \"Focus lost.\" << std::endl;\r\n }\r\n }\r\n \r\n hadPrevFocus = hadCurrentFocus;\r\n }\r\n \r\n \/\/ フレームが更新されていなければ何もしない\r\n {\r\n if ( previousFrameId == frame.id() ) {\r\n continue;\r\n }\r\n \r\n previousFrameId = frame.id();\r\n }\r\n \r\n \/\/ フレーム更新処理(onFrame()相当)\r\n }\r\n \r\n \/\/ 終了処理(onExit()相当)\r\n\r\n return 0;\r\n}\r\n#endif\r\n\r\n\/\/ 直前のフレームを取得する\r\n#if 0\r\nint main()\r\n{\r\n Leap::Controller leap;\r\n int64_t previousFrameId = -1;\r\n \r\n while ( 1 ) {\r\n \/\/ 最新のフレームを取得する (leap.frame( 0 ) と同じ)\r\n auto currentFrame = leap.frame();\r\n if ( previousFrameId == currentFrame.id() ) {\r\n continue;\r\n }\r\n \r\n previousFrameId = currentFrame.id();\r\n \r\n \/\/ 直前の5フレームを取得する\r\n std::cout << currentFrame.id() << \", \";\r\n for ( int i = 1; i <= 5; ++i ) {\r\n auto previousFrame = leap.frame( i );\r\n std::cout << previousFrame.id() << \", \";\r\n }\r\n std::cout << std::endl;\r\n }\r\n \r\n \/\/ 終了処理(onExit()相当)\r\n \r\n return 0;\r\n}\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XMLTableShapeImportHelper.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 19:59:29 $\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_XMLTABLESHAPEIMPORTHELPER_HXX\n#define _SC_XMLTABLESHAPEIMPORTHELPER_HXX\n\n#ifndef _XMLOFF_SHAPEIMPORT_HXX_\n#include <xmloff\/shapeimport.hxx>\n#endif\n#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_\n#include <com\/sun\/star\/table\/CellAddress.hpp>\n#endif\n\nclass ScXMLImport;\nclass ScXMLAnnotationContext;\n\nclass XMLTableShapeImportHelper : public XMLShapeImportHelper\n{\n ::com::sun::star::table::CellAddress aStartCell;\n ScXMLAnnotationContext* pAnnotationContext;\n sal_Bool bOnTable;\n\npublic:\n\n XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper=0 );\n ~XMLTableShapeImportHelper();\n\n void SetLayer(com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const;\n virtual void finishShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList,\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);\n\n\n void SetCell (const ::com::sun::star::table::CellAddress& rAddress) { aStartCell = rAddress; }\n void SetOnTable (const sal_Bool bTempOnTable) { bOnTable = bTempOnTable; }\n void SetAnnotation(ScXMLAnnotationContext* pAnnotation) { pAnnotationContext = pAnnotation; }\n};\n\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.10.700); FILE MERGED 2008\/04\/01 15:30:29 thb 1.10.700.3: #i85898# Stripping all external header guards 2008\/04\/01 12:36:32 thb 1.10.700.2: #i85898# Stripping all external header guards 2008\/03\/31 17:14:56 rt 1.10.700.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: XMLTableShapeImportHelper.hxx,v $\n * $Revision: 1.11 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SC_XMLTABLESHAPEIMPORTHELPER_HXX\n#define _SC_XMLTABLESHAPEIMPORTHELPER_HXX\n\n#include <xmloff\/shapeimport.hxx>\n#include <com\/sun\/star\/table\/CellAddress.hpp>\n\nclass ScXMLImport;\nclass ScXMLAnnotationContext;\n\nclass XMLTableShapeImportHelper : public XMLShapeImportHelper\n{\n ::com::sun::star::table::CellAddress aStartCell;\n ScXMLAnnotationContext* pAnnotationContext;\n sal_Bool bOnTable;\n\npublic:\n\n XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper=0 );\n ~XMLTableShapeImportHelper();\n\n void SetLayer(com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const;\n virtual void finishShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList,\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);\n\n\n void SetCell (const ::com::sun::star::table::CellAddress& rAddress) { aStartCell = rAddress; }\n void SetOnTable (const sal_Bool bTempOnTable) { bOnTable = bTempOnTable; }\n void SetAnnotation(ScXMLAnnotationContext* pAnnotation) { pAnnotationContext = pAnnotation; }\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: MasterScriptProvider.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: svesik $ $Date: 2004-04-19 23:16:21 $\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 _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_\n#define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_\n\n#include <rtl\/ustring>\n#include <cppuhelper\/implbase4.hxx>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n\n#include <drafts\/com\/sun\/star\/script\/provider\/XScriptProvider.hpp>\n#include <drafts\/com\/sun\/star\/script\/browse\/XBrowseNode.hpp>\n\n#include \"InvocationCtxProperties.hxx\"\n#include \"ProviderCache.hxx\"\nnamespace func_provider\n{\n\/\/ for simplification\n#define css ::com::sun::star\n#define dcsss ::drafts::com::sun::star::script\n\nclass MasterScriptProvider :\n public ::cppu::WeakImplHelper4 < dcsss::provider::XScriptProvider,\n dcsss::browse::XBrowseNode, css::lang::XServiceInfo,\n css::lang::XInitialization >\n{\npublic:\n MasterScriptProvider(\n const css::uno::Reference< css::uno::XComponentContext >\n & xContext ) throw( css::uno::RuntimeException );\n ~MasterScriptProvider();\n\n \/\/ XServiceInfo implementation\n virtual ::rtl::OUString SAL_CALL getImplementationName( )\n throw( css::uno::RuntimeException );\n\n \/\/ XBrowseNode implementation\n virtual ::rtl::OUString SAL_CALL getName()\n throw ( css::uno::RuntimeException );\n virtual css::uno::Sequence< css::uno::Reference< dcsss::browse::XBrowseNode > > SAL_CALL getChildNodes()\n throw ( css::uno::RuntimeException );\n virtual sal_Bool SAL_CALL hasChildNodes()\n throw ( css::uno::RuntimeException );\n virtual sal_Int16 SAL_CALL getType()\n throw ( css::uno::RuntimeException );\n\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw( css::uno::RuntimeException );\n virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )\n throw( css::uno::RuntimeException );\n\n \/\/ XScriptProvider implementation\n virtual css::uno::Reference < dcsss::provider::XScript > SAL_CALL\n getScript( const ::rtl::OUString& scriptURI )\n throw( css::lang::IllegalArgumentException, css::uno::RuntimeException );\n\n \/**\n * XInitialise implementation\n *\n * @param args expected to contain a single ::rtl::OUString\n * containing the URI\n *\/\n virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args )\n throw ( css::uno::Exception, css::uno::RuntimeException);\n\n \/\/ Public method to return all Language Providers in this MasterScriptProviders\n \/\/ context.\n css::uno::Sequence< css::uno::Reference< dcsss::provider::XScriptProvider > > SAL_CALL\n getAllProviders() throw ( css::uno::RuntimeException );\nprivate:\n bool isValid();\n const css::uno::Sequence< ::rtl::OUString >& getProviderNames();\n\n ProviderCache* providerCache();\n \/* to obtain other services if needed *\/\n css::uno::Reference< css::uno::XComponentContext > m_xContext;\n css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;\n css::uno::Reference< css::frame::XModel > m_xModel;\n css::uno::Sequence< css::uno::Any > m_sAargs;\n \/\/ This component supports XInitialization, it can be created\n \/\/ using createInstanceXXX() or createInstanceWithArgumentsXXX using\n \/\/ the service Mangager.\n \/\/ Need to detect proper initialisation and validity\n \/\/ for the object, so m_bIsValid indicates that the object is valid is set in ctor\n \/\/ in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset\n \/\/ and then set to true when initialisation is complete\n\n bool m_bIsValid;\n \/\/ m_bInitialised ensure initialisation only takes place once.\n bool m_bInitialised;\n css::uno::Reference< css::beans::XPropertySet > m_XScriptingContext;\n ProviderCache* m_pPCache;\n osl::Mutex m_mutex;\n};\n} \/\/ namespace func_provider\n#endif \/\/_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_\n<commit_msg>INTEGRATION: CWS scriptingf4 (1.7.4); FILE MERGED 2004\/05\/06 12:47:20 npower 1.7.4.1: #i28812# Adding support for new MasterScriptProviderFactory service. MasterScriptProvider no longer aggregates the browsenodes of all other MasterScriptProviders ( was a bad idea anyway ). This function is now performed by the standalone singleton css:script:browse::theBrowseNodeFactory which will aggregate the nodes, merge nodes from various languages and also sort them Issue number: Submitted by: Reviewed by:<commit_after>\/*************************************************************************\n *\n * $RCSfile: MasterScriptProvider.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2004-05-19 08:28:24 $\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 _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_\n#define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_\n\n#include <rtl\/ustring>\n#include <cppuhelper\/implbase4.hxx>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n\n#include <drafts\/com\/sun\/star\/script\/provider\/XScriptProvider.hpp>\n#include <drafts\/com\/sun\/star\/script\/browse\/XBrowseNode.hpp>\n\n#include \"InvocationCtxProperties.hxx\"\n#include \"ProviderCache.hxx\"\nnamespace func_provider\n{\n\/\/ for simplification\n#define css ::com::sun::star\n#define dcsss ::drafts::com::sun::star::script\n\n typedef ::cppu::WeakImplHelper4<\n dcsss::provider::XScriptProvider,\n dcsss::browse::XBrowseNode, css::lang::XServiceInfo,\n css::lang::XInitialization > t_helper;\nclass MasterScriptProvider : public t_helper\n{\npublic:\n MasterScriptProvider(\n const css::uno::Reference< css::uno::XComponentContext >\n & xContext ) throw( css::uno::RuntimeException );\n ~MasterScriptProvider();\n\n \/\/ XServiceInfo implementation\n virtual ::rtl::OUString SAL_CALL getImplementationName( )\n throw( css::uno::RuntimeException );\n\n \/\/ XBrowseNode implementation\n virtual ::rtl::OUString SAL_CALL getName()\n throw ( css::uno::RuntimeException );\n virtual css::uno::Sequence< css::uno::Reference< dcsss::browse::XBrowseNode > > SAL_CALL getChildNodes()\n throw ( css::uno::RuntimeException );\n virtual sal_Bool SAL_CALL hasChildNodes()\n throw ( css::uno::RuntimeException );\n virtual sal_Int16 SAL_CALL getType()\n throw ( css::uno::RuntimeException );\n\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw( css::uno::RuntimeException );\n virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )\n throw( css::uno::RuntimeException );\n\n \/\/ XScriptProvider implementation\n virtual css::uno::Reference < dcsss::provider::XScript > SAL_CALL\n getScript( const ::rtl::OUString& scriptURI )\n throw( css::lang::IllegalArgumentException, css::uno::RuntimeException );\n\n \/**\n * XInitialise implementation\n *\n * @param args expected to contain a single ::rtl::OUString\n * containing the URI\n *\/\n virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args )\n throw ( css::uno::Exception, css::uno::RuntimeException);\n\n \/\/ Public method to return all Language Providers in this MasterScriptProviders\n \/\/ context.\n css::uno::Sequence< css::uno::Reference< dcsss::provider::XScriptProvider > > SAL_CALL\n getAllProviders() throw ( css::uno::RuntimeException );\nprivate:\n ::rtl::OUString parseLocationName( const ::rtl::OUString& location );\n void createPkgProvider();\n bool isValid();\n const css::uno::Sequence< ::rtl::OUString >& getProviderNames();\n\n ProviderCache* providerCache();\n \/* to obtain other services if needed *\/\n css::uno::Reference< css::uno::XComponentContext > m_xContext;\n css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;\n css::uno::Reference< css::frame::XModel > m_xModel;\n css::uno::Sequence< css::uno::Any > m_sAargs;\n ::rtl::OUString m_sNodeName;\n \/\/ This component supports XInitialization, it can be created\n \/\/ using createInstanceXXX() or createInstanceWithArgumentsXXX using\n \/\/ the service Mangager.\n \/\/ Need to detect proper initialisation and validity\n \/\/ for the object, so m_bIsValid indicates that the object is valid is set in ctor\n \/\/ in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset\n \/\/ and then set to true when initialisation is complete\n\n bool m_bIsValid;\n \/\/ m_bInitialised ensure initialisation only takes place once.\n bool m_bInitialised;\n css::uno::Reference< css::beans::XPropertySet > m_XScriptingContext;\n ProviderCache* m_pPCache;\n osl::Mutex m_mutex;\n ::rtl::OUString m_sCtxString;\n};\n} \/\/ namespace func_provider\n#endif \/\/_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_\n<|endoftext|>"} {"text":"<commit_before>#include \"adopter.h\"\n#include \"serializer.h\"\n#include \"mousegestures.h\"\n#include \"ui_mousegestures.h\"\n#include \"pathcorrector.h\"\n#include \"validpathcreator.h\"\n#include \"GeometricForms.h\"\n#include \"paintmanager.h\"\n#include \"multistrokeRecognizers\/multistrokeGesturesManagers.h\"\n#include \"test\/xmlparser.h\"\n\n\nstatic const QString xmlDir = \"..\/..\/unreal\/trunk\/qrxml\";\nstatic const QString idealGesturesFile =\n \"NeuralNetwork\/learnGestures\/ideal_gestures.xml\";\nstatic const QString generatedGesturesFile = \"NeuralNetwork\/learnGestures\/generated_gestures.xml\";\nstatic const QString testGesturesFile = \"usersGestures.xml\";\n\nMouseGestures::MouseGestures(QWidget *parent)\n : QMainWindow(parent), ui(new Ui::MouseGestures)\n{\n ui->setupUi(this);\n connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(loadFile()));\n connect(ui->twObjectPathTable, SIGNAL\n (currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), this, SLOT(drawGesture()));\n connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(save()));\n connect(ui->actionTest, SIGNAL(triggered()), this, SLOT(chooseTestAlgorithm()));\n connect(ui->actionGenerate_gestures, SIGNAL(triggered()), this, SLOT(generateGestures()));\n connect(ui->actionSave_test_gestures, SIGNAL(triggered()), this, SLOT(saveTestGestures()));\n connect(ui->actionOpen_test_gestures, SIGNAL(triggered()), this, SLOT(openTestGestures()));\n mPaintManager = new PaintManager(ui->gvGesture);\n mGesturesManager = new LevenshteinHullGesturesManager();\n mRecognizer = new AbstractRecognizer(mGesturesManager);\n}\n\nvoid MouseGestures::openTestGestures()\n{\n QMap<QString, UsersGestures> usersGestures = XmlParser::parseXml(testGesturesFile);\n mRecognizer = new AbstractRecognizer(mGesturesManager, usersGestures);\n showTable();\n}\n\nvoid MouseGestures::saveTestGestures()\n{\n XmlParser::saveMore(this->mRecognizer->getAllGestures(), testGesturesFile);\n}\n\nvoid MouseGestures::generateGestures()\n{\n \/\/TODO:: change idealGestures\n QMap<QString, UsersGestures> usersGestures = XmlParser::parseXml(idealGesturesFile);\n QMap<QString, UsersGestures> generatedGestures;\n foreach (QString object, usersGestures.keys())\n {\n const int maxAngle = 45;\n const int angleDiff = 10;\n PathVector idealGesture = usersGestures[object].first;\n QList<QString> newGestures;\n qDebug() << object;\n for (int i = - maxAngle; i <= maxAngle; i += angleDiff)\n {\n int maxSecondAngle = maxAngle - abs(i);\n for (int j = - maxSecondAngle; j <= maxSecondAngle; j += angleDiff)\n {\n PathVector gesture = PathCorrector::distortGesture(idealGesture, i, j);\n \/\/TODO:: change for incoherent gestures\n newGestures.push_back(Parser::pathToString(gesture));\n }\n }\n UsersGestures generatedGesture(usersGestures[object].first, newGestures);\n generatedGestures.insert(object, generatedGesture);\n }\n XmlParser::save(generatedGestures, generatedGesturesFile);\n}\n\nvoid MouseGestures::chooseTestAlgorithm()\n{\n mTestWindow = new TestWindow(this);\n mTestWindow->show();\n}\n\nvoid MouseGestures::contextMenuEvent(QContextMenuEvent *event)\n{\n QMenu menu(this);\n QAction *rotate = new QAction(\"Rotate path\", this);\n connect(rotate, SIGNAL(triggered()), this, SLOT(rotatePath()));\n menu.addAction(rotate);\n QAction *increase = new QAction(\"Increase path\", this);\n connect(increase, SIGNAL(triggered()), this, SLOT(increasePath()));\n menu.addAction(increase);\n QAction *decrease = new QAction(\"Decrease path\", this);\n connect(decrease, SIGNAL(triggered()), this, SLOT(decreasePath()));\n menu.addAction(decrease);\n menu.exec(event->globalPos());\n}\n\nvoid MouseGestures::rotatePath()\n{\n\/\/ QString pathStr = ui->twObjectPathTable->currentItem()->text();\n\/\/ QList<QPoint> path = Parser::stringToPath(pathStr);\n\/\/ path = PathCorrector::rotate(path);\n\/\/ ui->twObjectPathTable->currentItem()->setText(Parser::pathToString(path));\n\/\/ \/\/TODO:: add changing path for single-stroke gestures\n}\n\nvoid MouseGestures::increasePath(double koef)\n{\n\/\/ QString pathStr = ui->twObjectPathTable->currentItem()->text();\n\/\/ QList<QPoint> path = Parser::stringToPath(pathStr);\n\/\/ path = PathCorrector::increase(path, koef);\n\/\/ ui->twObjectPathTable->currentItem()->setText(Parser::pathToString(path));\n\/\/ \/\/TODO:: add changing path for single-stroke gestures\n}\n\nvoid MouseGestures::increasePath()\n{\n increasePath(2);\n}\n\nvoid MouseGestures::decreasePath()\n{\n increasePath(0.5);\n}\n\nvoid MouseGestures::save()\n{\n Objects objects;\n Serializer serializer(mFileName);\n serializer.serialize(objects);\n}\n\nvoid MouseGestures::changePath()\n{\n \/\/\tint currentRow = ui->twObjectPathTable->currentRow();\n \/\/\tQString name = ui->twObjectPathTable->item(currentRow, objectColumn)->text();\n \/\/\tQString pathStr = ui->twObjectPathTable->item(currentRow, pathColumn)->text();\n \/\/\tQList<QPoint> path = Parser::stringToPath(pathStr);\n \/\/\tif (path.isEmpty())\n \/\/\t{\n \/\/\t\tQMessageBox msgBox;\n \/\/\t\tmsgBox.setText(\"Invalid string. Path cannot be modified.\");\n \/\/\t\tmsgBox.exec();\n \/\/\t}\n}\n\nvoid MouseGestures::loadFile()\n{\n \/\/save();\n mFileName = QFileDialog::getOpenFileName(this,\n tr(\"Open Xml\"), xmlDir,\n tr(\"Xml files (*.xml)\"));\n int rowCount = ui->twObjectPathTable->rowCount();\n for (int i = 0; i < rowCount; i++)\n {\n ui->twObjectPathTable->removeRow(0);\n }\n Serializer serializer(mFileName);\n EntityVector entities = serializer.deserialize();\n \/\/mGesturesManager = new LevenshteinHullGesturesManager();\n mRecognizer = new AbstractRecognizer(mGesturesManager, entities);\n \/\/\taddEntities(entities);\n showTable();\n \/\/\tthis->mKeyBulder = new MultistrokeGesturesManager(entities);\n}\n\nvoid MouseGestures::showTable()\n{\n this->disconnect(ui->twObjectPathTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changePath()));\n foreach (QString object, mRecognizer->getObjects())\n {\n int rowCount = ui->twObjectPathTable->rowCount();\n ui->twObjectPathTable->setRowCount(rowCount + 1);\n QTableWidgetItem *item = new QTableWidgetItem(object);\n ui->twObjectPathTable->setItem(rowCount, 0, item);\n }\n connect(ui->twObjectPathTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changePath()));\n}\n\nvoid MouseGestures::mouseMoveEvent(QMouseEvent * event)\n{\n mRecognizer->mouseMove(event->pos());\n this->update();\n}\n\nvoid MouseGestures::mouseReleaseEvent(QMouseEvent *event)\n{\n \/\/ mCorrectPath = PathCorrector::correctPath(mMousePath);\n \/\/ QString object = mKeyObjectTable.getObject(mCorrectPath);\n \/\/ ui->teObject->setText(object);\n mRecognizer->mouseRelease(event->pos());\n this->update();\n}\n\nvoid MouseGestures::keyPressEvent(QKeyEvent * event)\n{\n if (event->key() != Qt::Key_Return)\n return;\n QString object = mRecognizer->recognizeObject();\n showObjectsMenu(object);\n \/\/mCorrectPath = PathCorrector::correctPath(mMousePath);\n ui->teObject->setText(object);\n this->update();\n}\n\nvoid MouseGestures::showObjectsMenu(QString const & object)\n{\n QMenu * menu = new QMenu(this);\n QList<QString> objects = mRecognizer->getObjects();\n objects.removeAll(object);\n objects.push_front(object);\n foreach (QString object, objects)\n {\n QAction * action = new QAction(object, this);\n menu->addAction(action);\n }\n connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(addTestGesture(QAction *)));\n menu->exec();\n}\n\nvoid MouseGestures::addTestGesture(QAction * action)\n{\n mRecognizer->saveGesture(action->text());\n}\n\nvoid MouseGestures::mousePressEvent(QMouseEvent * event)\n{\n mRecognizer->mousePress(event->pos());\n this->update();\n}\n\nvoid MouseGestures::paintEvent(QPaintEvent *)\n{\n QPainter painter(this);\n PaintManager::drawPath(&painter, mRecognizer->getGesture());\n}\n\nvoid MouseGestures::drawGesture()\n{\n QString name = ui->twObjectPathTable->currentItem()->text();\n mRecognizer->drawGesture(name, mPaintManager);\n}\n\nMouseGestures::~MouseGestures()\n{\n delete ui;\n}\n<commit_msg>change way of choosing object<commit_after>#include \"adopter.h\"\n#include \"serializer.h\"\n#include \"mousegestures.h\"\n#include \"ui_mousegestures.h\"\n#include \"pathcorrector.h\"\n#include \"validpathcreator.h\"\n#include \"GeometricForms.h\"\n#include \"paintmanager.h\"\n#include \"multistrokeRecognizers\/multistrokeGesturesManagers.h\"\n#include \"test\/xmlparser.h\"\n\n\nstatic const QString xmlDir = \"..\/..\/unreal\/trunk\/qrxml\";\nstatic const QString idealGesturesFile =\n \"NeuralNetwork\/learnGestures\/ideal_gestures.xml\";\nstatic const QString generatedGesturesFile = \"NeuralNetwork\/learnGestures\/generated_gestures.xml\";\nstatic const QString testGesturesFile = \"usersGestures.xml\";\n\nMouseGestures::MouseGestures(QWidget *parent)\n : QMainWindow(parent), ui(new Ui::MouseGestures)\n{\n ui->setupUi(this);\n connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(loadFile()));\n connect(ui->twObjectPathTable, SIGNAL\n (currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), this, SLOT(drawGesture()));\n connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(save()));\n connect(ui->actionTest, SIGNAL(triggered()), this, SLOT(chooseTestAlgorithm()));\n connect(ui->actionGenerate_gestures, SIGNAL(triggered()), this, SLOT(generateGestures()));\n connect(ui->actionSave_test_gestures, SIGNAL(triggered()), this, SLOT(saveTestGestures()));\n connect(ui->actionOpen_test_gestures, SIGNAL(triggered()), this, SLOT(openTestGestures()));\n mPaintManager = new PaintManager(ui->gvGesture);\n mGesturesManager = new LevenshteinHullGesturesManager();\n mRecognizer = new AbstractRecognizer(mGesturesManager);\n}\n\nvoid MouseGestures::openTestGestures()\n{\n QMap<QString, UsersGestures> usersGestures = XmlParser::parseXml(testGesturesFile);\n mRecognizer = new AbstractRecognizer(mGesturesManager, usersGestures);\n showTable();\n}\n\nvoid MouseGestures::saveTestGestures()\n{\n XmlParser::saveMore(this->mRecognizer->getAllGestures(), testGesturesFile);\n}\n\nvoid MouseGestures::generateGestures()\n{\n \/\/TODO:: change idealGestures\n QMap<QString, UsersGestures> usersGestures = XmlParser::parseXml(idealGesturesFile);\n QMap<QString, UsersGestures> generatedGestures;\n foreach (QString object, usersGestures.keys())\n {\n const int maxAngle = 45;\n const int angleDiff = 10;\n PathVector idealGesture = usersGestures[object].first;\n QList<QString> newGestures;\n qDebug() << object;\n for (int i = - maxAngle; i <= maxAngle; i += angleDiff)\n {\n int maxSecondAngle = maxAngle - abs(i);\n for (int j = - maxSecondAngle; j <= maxSecondAngle; j += angleDiff)\n {\n PathVector gesture = PathCorrector::distortGesture(idealGesture, i, j);\n \/\/TODO:: change for incoherent gestures\n newGestures.push_back(Parser::pathToString(gesture));\n }\n }\n UsersGestures generatedGesture(usersGestures[object].first, newGestures);\n generatedGestures.insert(object, generatedGesture);\n }\n XmlParser::save(generatedGestures, generatedGesturesFile);\n}\n\nvoid MouseGestures::chooseTestAlgorithm()\n{\n mTestWindow = new TestWindow(this);\n mTestWindow->show();\n}\n\nvoid MouseGestures::contextMenuEvent(QContextMenuEvent *event)\n{\n QMenu menu(this);\n QAction *rotate = new QAction(\"Rotate path\", this);\n connect(rotate, SIGNAL(triggered()), this, SLOT(rotatePath()));\n menu.addAction(rotate);\n QAction *increase = new QAction(\"Increase path\", this);\n connect(increase, SIGNAL(triggered()), this, SLOT(increasePath()));\n menu.addAction(increase);\n QAction *decrease = new QAction(\"Decrease path\", this);\n connect(decrease, SIGNAL(triggered()), this, SLOT(decreasePath()));\n menu.addAction(decrease);\n menu.exec(event->globalPos());\n}\n\nvoid MouseGestures::rotatePath()\n{\n \/\/ QString pathStr = ui->twObjectPathTable->currentItem()->text();\n \/\/ QList<QPoint> path = Parser::stringToPath(pathStr);\n \/\/ path = PathCorrector::rotate(path);\n \/\/ ui->twObjectPathTable->currentItem()->setText(Parser::pathToString(path));\n \/\/ \/\/TODO:: add changing path for single-stroke gestures\n}\n\nvoid MouseGestures::increasePath(double koef)\n{\n \/\/ QString pathStr = ui->twObjectPathTable->currentItem()->text();\n \/\/ QList<QPoint> path = Parser::stringToPath(pathStr);\n \/\/ path = PathCorrector::increase(path, koef);\n \/\/ ui->twObjectPathTable->currentItem()->setText(Parser::pathToString(path));\n \/\/ \/\/TODO:: add changing path for single-stroke gestures\n}\n\nvoid MouseGestures::increasePath()\n{\n increasePath(2);\n}\n\nvoid MouseGestures::decreasePath()\n{\n increasePath(0.5);\n}\n\nvoid MouseGestures::save()\n{\n Objects objects;\n Serializer serializer(mFileName);\n serializer.serialize(objects);\n}\n\nvoid MouseGestures::changePath()\n{\n \/\/\tint currentRow = ui->twObjectPathTable->currentRow();\n \/\/\tQString name = ui->twObjectPathTable->item(currentRow, objectColumn)->text();\n \/\/\tQString pathStr = ui->twObjectPathTable->item(currentRow, pathColumn)->text();\n \/\/\tQList<QPoint> path = Parser::stringToPath(pathStr);\n \/\/\tif (path.isEmpty())\n \/\/\t{\n \/\/\t\tQMessageBox msgBox;\n \/\/\t\tmsgBox.setText(\"Invalid string. Path cannot be modified.\");\n \/\/\t\tmsgBox.exec();\n \/\/\t}\n}\n\nvoid MouseGestures::loadFile()\n{\n \/\/save();\n mFileName = QFileDialog::getOpenFileName(this,\n tr(\"Open Xml\"), xmlDir,\n tr(\"Xml files (*.xml)\"));\n int rowCount = ui->twObjectPathTable->rowCount();\n for (int i = 0; i < rowCount; i++)\n {\n ui->twObjectPathTable->removeRow(0);\n }\n Serializer serializer(mFileName);\n EntityVector entities = serializer.deserialize();\n \/\/mGesturesManager = new LevenshteinHullGesturesManager();\n mRecognizer = new AbstractRecognizer(mGesturesManager, entities);\n \/\/\taddEntities(entities);\n showTable();\n \/\/\tthis->mKeyBulder = new MultistrokeGesturesManager(entities);\n}\n\nvoid MouseGestures::showTable()\n{\n this->disconnect(ui->twObjectPathTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changePath()));\n foreach (QString object, mRecognizer->getObjects())\n {\n int rowCount = ui->twObjectPathTable->rowCount();\n ui->twObjectPathTable->setRowCount(rowCount + 1);\n QTableWidgetItem *item = new QTableWidgetItem(object);\n ui->twObjectPathTable->setItem(rowCount, 0, item);\n }\n connect(ui->twObjectPathTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changePath()));\n}\n\nvoid MouseGestures::mouseMoveEvent(QMouseEvent * event)\n{\n mRecognizer->mouseMove(event->pos());\n this->update();\n}\n\nvoid MouseGestures::mouseReleaseEvent(QMouseEvent *event)\n{\n \/\/ mCorrectPath = PathCorrector::correctPath(mMousePath);\n \/\/ QString object = mKeyObjectTable.getObject(mCorrectPath);\n \/\/ ui->teObject->setText(object);\n mRecognizer->mouseRelease(event->pos());\n this->update();\n}\n\nvoid MouseGestures::keyPressEvent(QKeyEvent * event)\n{\n if (event->key() != Qt::Key_Return)\n return;\n QString object = mRecognizer->recognizeObject();\n if (ui->twObjectPathTable->rowCount() != 0)\n {\n QTableWidgetItem * currentItem = ui->twObjectPathTable->currentItem();\n if (currentItem != NULL)\n mRecognizer->saveGesture(currentItem->text());\n }\n \/\/showObjectsMenu(object);\n \/\/mCorrectPath = PathCorrector::correctPath(mMousePath);\n ui->teObject->setText(object);\n this->update();\n}\n\nvoid MouseGestures::showObjectsMenu(QString const & object)\n{\n QMenu * menu = new QMenu(this);\n QList<QString> objects = mRecognizer->getObjects();\n objects.removeAll(object);\n objects.push_front(object);\n foreach (QString object, objects)\n {\n QAction * action = new QAction(object, this);\n menu->addAction(action);\n }\n connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(addTestGesture(QAction *)));\n menu->exec();\n}\n\nvoid MouseGestures::addTestGesture(QAction * action)\n{\n mRecognizer->saveGesture(action->text());\n}\n\nvoid MouseGestures::mousePressEvent(QMouseEvent * event)\n{\n mRecognizer->mousePress(event->pos());\n this->update();\n}\n\nvoid MouseGestures::paintEvent(QPaintEvent *)\n{\n QPainter painter(this);\n PaintManager::drawPath(&painter, mRecognizer->getGesture());\n}\n\nvoid MouseGestures::drawGesture()\n{\n QString name = ui->twObjectPathTable->currentItem()->text();\n mRecognizer->drawGesture(name, mPaintManager);\n}\n\nMouseGestures::~MouseGestures()\n{\n delete ui;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>PUT, GET, RESERVE - CLIETN SIDE - OK<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_roofit\n\/\/\/ \\notebook -js\n\/\/\/ Likelihood and minimization: Parameter uncertainties for weighted unbinned ML fits\n\/\/\/\n\/\/\/ \\macro_image\n\/\/\/ \\macro_output\n\/\/\/ \\macro_code\n\/\/\/ \\author 11\/2019 - Christoph Langenbruch\n\n#include \"TH1D.h\"\n#include \"TCanvas.h\"\n#include \"TROOT.h\"\n#include \"TStyle.h\"\n#include \"TRandom3.h\"\n#include \"TLegend.h\"\n#include \"RooRealVar.h\"\n#include \"RooFitResult.h\"\n#include \"RooDataSet.h\"\n#include \"RooPolynomial.h\"\n\nusing namespace RooFit;\n\n\nint rf611_weightedfits(int acceptancemodel=2) {\n \/\/ P a r a m e t e r u n c e r t a i n t i e s f o r w e i g h t e d u n b i n n e d M L f i t s\n \/\/ ---------------------------------------------------------------------------------------------------------\n \/\/\n \/\/Based on example from https:\/\/arxiv.org\/abs\/1911.01303 \n \/\/\n \/\/This example compares different approaches to determining parameter uncertainties in weighted unbinned maximum likelihood fits.\n \/\/Performing a weighted unbinned maximum likelihood fits can be useful to account for acceptance effects and to statistically subtract background events using the sPlot formalism. \n \/\/It is however well known that the inverse Hessian matrix does not yield parameter uncertainties with correct coverage in the presence of event weights.\n \/\/Three approaches to the determination of parameter uncertainties are compared in this example:\n \/\/\n \/\/1. Using the inverse weighted Hessian matrix [SumW2Error(false)]\n \/\/\n \/\/2. Using the expression [SumW2Error(true)]\n \/\/ V_{ij} = H_{ik}^{-1} C_{kl} H_{lj}^{-1}\n \/\/ where H is the weighted Hessian matrix and C is the Hessian matrix with squared weights\n \/\/\n \/\/3. The asymptotically correct approach (for details please see https:\/\/arxiv.org\/abs\/1911.01303) [Asymptotic(true)]\n \/\/ V_{ij} = H_{ik}^{-1} D_{kl} H_{lj}^{-1}\n \/\/ where H is the weighted Hessian matrix and D is given by\n \/\/ D_{kl} = sum_{e=1}^{N} w_e^2 \\frac{\\partial log P}{\\partial lambda_k}\\frac{\\partial log P}{\\partial lambda_l}\n \/\/ with the event weight w_e\n \/\/\n \/\/The example performs the fit of a second order polynomial in the angle cos(theta) [-1,1] to a weighted data set.\n \/\/The polynomial is given by\n \/\/ P = (1 + c0*cos(theta) + c1*cos(theta)*cos(theta)) \/ Norm\n \/\/The two coefficients c0 and c1 and their uncertainties are to be determined in the fit.\n \/\/\n \/\/The per-event weight is used to correct for an acceptance effect, two different acceptance models can be studied:\n \/\/ acceptancemodel==1: eff = 0.3+0.7*cos(theta)*cos(theta)\n \/\/ acceptancemodel==2: eff = 1.0-0.7*cos(theta)*cos(theta)\n \/\/The data is generated to be flat before the acceptance effect.\n \/\/\n \/\/The performance of the different approaches to determine parameter uncertainties is compared using the pull distributions from a large number of pseudoexperiments.\n \/\/The pull is defined as (lambda_i-\\lambda_{gen})\/\\sigma(\\lambda_i), where \\lambda_i is the fitted parameter and \\sigma(\\lambda_i) its uncertainty for pseudoexperiment number i.\n \/\/If the fit is unbiased and the parameter uncertainties are estimated correctly, the pull distribution should be a Gaussian centered around zero with a width of one.\n\n \n \/\/ I n i t i a l i s a t i o n a n d S e t u p\n \/\/------------------------------------------------ \n\n \/\/plotting options\n gStyle->SetPaintTextFormat(\".1f\");\n gStyle->SetEndErrorSize(6.0);\n gStyle->SetTitleSize(0.05, \"XY\");\n gStyle->SetLabelSize(0.05, \"XY\");\n gStyle->SetTitleOffset(0.9, \"XY\");\n gStyle->SetTextSize(0.05);\n gStyle->SetPadLeftMargin(0.125);\n gStyle->SetPadBottomMargin(0.125);\n gStyle->SetPadTopMargin(0.075);\n gStyle->SetPadRightMargin(0.075);\n gStyle->SetMarkerStyle(20);\n gStyle->SetMarkerSize(1.0);\n gStyle->SetHistLineWidth(2.0);\n gStyle->SetHistLineColor(1);\n\n \/\/initialise TRandom3\n TRandom3* rnd = new TRandom3();\n rnd->SetSeed(191101303);\n\n \/\/accepted events and events weighted to account for the acceptance\n TH1D* haccepted = new TH1D(\"haccepted\", \"Generated events;cos(#theta);#events\", 40, -1.0, 1.0);\n TH1D* hweighted = new TH1D(\"hweighted\", \"Generated events;cos(#theta);#events\", 40, -1.0, 1.0);\n \/\/histograms holding pull distributions \n \/\/using the inverse Hessian matrix\n TH1D* hc0pull1 = new TH1D(\"hc0pull1\", \"Inverse weighted Hessian matrix [SumW2Error(false)];Pull (c_{0}^{fit}-c_{0}^{gen})\/#sigma(c_{0});\", 20, -5.0, 5.0);\n TH1D* hc1pull1 = new TH1D(\"hc1pull1\", \"Inverse weighted Hessian matrix [SumW2Error(false)];Pull (c_{1}^{fit}-c_{1}^{gen})\/#sigma(c_{1});\", 20, -5.0, 5.0);\n \/\/using the correction with the Hessian matrix with squared weights\n TH1D* hc0pull2 = new TH1D(\"hc0pull2\", \"Hessian matrix with squared weights [SumW2Error(true)];Pull (c_{0}^{fit}-c_{0}^{gen})\/#sigma(c_{0});\", 20, -5.0, 5.0);\n TH1D* hc1pull2 = new TH1D(\"hc1pull2\", \"Hessian matrix with squared weights [SumW2Error(true)];Pull (c_{1}^{fit}-c_{1}^{gen})\/#sigma(c_{1});\", 20, -5.0, 5.0);\n \/\/asymptotically correct approach\n TH1D* hc0pull3 = new TH1D(\"hc0pull3\", \"Asymptotically correct approach [Asymptotic(true)];Pull (c_{0}^{fit}-c_{0}^{gen})\/#sigma(c_{0});\", 20, -5.0, 5.0);\n TH1D* hc1pull3 = new TH1D(\"hc1pull3\", \"Asymptotically correct approach [Asymptotic(true)];Pull (c_{1}^{fit}-c_{1}^{gen})\/#sigma(c_{1});\", 20, -5.0, 5.0);\n\n \/\/number of pseudoexperiments (toys) and number of events per pseudoexperiment\n unsigned int ntoys = 500;\n unsigned int nstats = 5000;\n \/\/parameters used in the generation\n double c0gen = 0.0;\n double c1gen = 0.0;\n\n \/\/ M a i n l o o p o v e r a l l p s e u d o e x p e r i m e n t s\n \/\/------------------------------------------------------------------------\n for (unsigned int i=0; i<ntoys; i++)\n {\n \/\/S e t u p p a r a m e t e r s a n d P D F\n \/\/-----------------------------------------------\n \/\/angle theta and the weight to account for the acceptance effect\n RooRealVar costheta(\"costheta\",\"costheta\", -1.0, 1.0);\n RooRealVar weight(\"weight\",\"weight\", 0.0, 1000.0);\n\n \/\/initialise parameters to fit\n RooRealVar c0(\"c0\",\"c0\", c0gen, -1.0, 1.0);\n RooRealVar c1(\"c1\",\"c1\", c1gen, -1.0, 1.0);\n c0.setError(0.01);\n c1.setError(0.01);\n \/\/create simple second order polynomial as probability density function\n RooPolynomial pol(\"pol\", \"pol\", costheta, RooArgList(c0, c1), 1);\n\n \/\/G e n e r a t e d a t a s e t f o r p s e u d o e x p e r i m e n t i\n \/\/-------------------------------------------------------------------------------\n RooDataSet data(\"data\",\"data\",RooArgSet(costheta, weight), WeightVar(\"weight\"));\n \/\/generate nstats events \n for (unsigned int j=0; j<nstats; j++)\n\t{\n\t bool finished = false;\n\t \/\/use simple accept\/reject for generation\n\t while (!finished)\n\t {\n\t costheta = 2.0*rnd->Rndm()-1.0;\n\t \/\/efficiency for the specific value of cos(theta)\n\t double eff = 1.0;\n\t if (acceptancemodel == 1)\n\t\teff = 1.0 - 0.7 * costheta.getValV()*costheta.getValV();\n\t else\n\t\teff = 0.3 + 0.7 * costheta.getValV()*costheta.getValV();\n\t \/\/use 1\/eff as weight to account for acceptance\n\t weight = 1.0\/eff;\n\t \/\/accept\/reject\n\t if (10.0*rnd->Rndm() < eff*pol.getValV())\n\t\tfinished = true;\n\t }\n\t haccepted->Fill(costheta.getValV());\n\t hweighted->Fill(costheta.getValV(), weight.getValV());\n\t data.add(RooArgSet(costheta, weight), weight.getValV());\n\t}\n\n \/\/F i t t o y u s i n g t h e t h r e e d i f f e r e n t a p p r o a c h e s t o u n c e r t a i n t y d e t e r m i n a t i o n\n \/\/-------------------------------------------------------------------------------------------------------------------------------------------------\n RooFitResult* result = pol.fitTo(data, Save(true), SumW2Error(false));\/\/this uses the inverse weighted Hessian matrix\n hc0pull1->Fill((c0.getValV()-c0gen)\/c0.getError());\n hc1pull1->Fill((c1.getValV()-c1gen)\/c1.getError());\n \n result = pol.fitTo(data, Save(true), SumW2Error(true));\/\/this uses the correction with the Hesse matrix with squared weights\n hc0pull2->Fill((c0.getValV()-c0gen)\/c0.getError());\n hc1pull2->Fill((c1.getValV()-c1gen)\/c1.getError());\n \n result = pol.fitTo(data, Save(true), AsymptoticError(true));\/\/this uses the asymptotically correct approach\n hc0pull3->Fill((c0.getValV()-c0gen)\/c0.getError());\n hc1pull3->Fill((c1.getValV()-c1gen)\/c1.getError()); \n }\n \n \/\/ P l o t o u t p u t d i s t r i b u t i o n s\n \/\/--------------------------------------------------\n \n \/\/plot accepted (weighted) events\n gStyle->SetOptStat(0);\n gStyle->SetOptFit(0);\n TCanvas* cevents = new TCanvas(\"cevents\", \"cevents\", 800, 600);\n cevents->cd(1);\n hweighted->SetMinimum(0.0);\n hweighted->SetLineColor(2);\n hweighted->Draw(\"hist\");\n haccepted->Draw(\"same hist\");\n TLegend* leg = new TLegend(0.6, 0.8, 0.9, 0.9);\n leg->AddEntry(haccepted, \"Accepted\");\n leg->AddEntry(hweighted, \"Weighted\");\n leg->Draw();\n cevents->Update();\n \n \/\/plot pull distributions\n TCanvas* cpull = new TCanvas(\"cpull\", \"cpull\", 1200, 800);\n cpull->Divide(3,2);\n cpull->cd(1);\n gStyle->SetOptStat(1100);\n gStyle->SetOptFit(11);\n hc0pull1->Fit(\"gaus\");\n hc0pull1->Draw(\"ep\");\n cpull->cd(2);\n hc0pull2->Fit(\"gaus\");\n hc0pull2->Draw(\"ep\");\n cpull->cd(3);\n hc0pull3->Fit(\"gaus\");\n hc0pull3->Draw(\"ep\");\n cpull->cd(4);\n hc1pull1->Fit(\"gaus\");\n hc1pull1->Draw(\"ep\");\n cpull->cd(5);\n hc1pull2->Fit(\"gaus\");\n hc1pull2->Draw(\"ep\");\n cpull->cd(6);\n hc1pull3->Fit(\"gaus\");\n hc1pull3->Draw(\"ep\");\n cpull->Update();\n\n return 0;\n}\n<commit_msg>[RF] Update tutorial for asymptotic errors.<commit_after>\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_roofit\n\/\/\/ \\notebook -js\n\/\/\/ Likelihood and minimization: Parameter uncertainties for weighted unbinned ML fits\n\/\/\/\n\/\/\/ ## Parameter uncertainties for weighted unbinned ML fits\n\/\/\/\n\/\/\/ Based on example from https:\/\/arxiv.org\/abs\/1911.01303\n\/\/\/\n\/\/\/ This example compares different approaches to determining parameter uncertainties in weighted unbinned maximum likelihood fits.\n\/\/\/ Performing a weighted unbinned maximum likelihood fits can be useful to account for acceptance effects and to statistically subtract background events using the sPlot formalism.\n\/\/\/ It is however well known that the inverse Hessian matrix does not yield parameter uncertainties with correct coverage in the presence of event weights.\n\/\/\/ Three approaches to the determination of parameter uncertainties are compared in this example:\n\/\/\/\n\/\/\/ 1. Using the inverse weighted Hessian matrix [`SumW2Error(false)`]\n\/\/\/\n\/\/\/ 2. Using the expression [`SumW2Error(true)`]\n\/\/\/ \\f[\n\/\/\/ V_{ij} = H_{ik}^{-1} C_{kl} H_{lj}^{-1}\n\/\/\/ \\f]\n\/\/\/ where H is the weighted Hessian matrix and C is the Hessian matrix with squared weights\n\/\/\/\n\/\/\/ 3. The asymptotically correct approach (for details please see https:\/\/arxiv.org\/abs\/1911.01303) [`Asymptotic(true)`]\n\/\/\/ \\f[\n\/\/\/ V_{ij} = H_{ik}^{-1} D_{kl} H_{lj}^{-1}\n\/\/\/ \\f]\n\/\/\/ where H is the weighted Hessian matrix and D is given by\n\/\/\/ \\f[\n\/\/\/ D_{kl} = \\sum_{e=1}^{N} w_e^2 \\frac{\\partial \\log(P)}{\\partial \\lambda_k}\\frac{\\partial \\log(P)}{\\partial \\lambda_l}\n\/\/\/ \\f]\n\/\/\/ with the event weight \\f$w_e\\f$.\n\/\/\/\n\/\/\/ The example performs the fit of a second order polynomial in the angle cos(theta) [-1,1] to a weighted data set.\n\/\/\/ The polynomial is given by\n\/\/\/ \\f[\n\/\/\/ P = \\frac{ 1 + c_0 \\cdot \\cos(\\theta) + c_1 \\cdot \\cos(\\theta) \\cdot \\cos(\\theta) }{\\mathrm{Norm}}\n\/\/\/ \\f]\n\/\/\/ The two coefficients \\f$ c_0 \\f$ and \\f$ c_1 \\f$ and their uncertainties are to be determined in the fit.\n\/\/\/\n\/\/\/ The per-event weight is used to correct for an acceptance effect, two different acceptance models can be studied:\n\/\/\/ - `acceptancemodel==1`: eff = \\f$ 0.3 + 0.7 \\cdot \\cos(\\theta) \\cdot \\cos(\\theta) \\f$\n\/\/\/ - `acceptancemodel==2`: eff = \\f$ 1.0 - 0.7 \\cdot \\cos(\\theta) \\cdot \\cos(\\theta) \\f$\n\/\/\/ The data is generated to be flat before the acceptance effect.\n\/\/\/\n\/\/\/ The performance of the different approaches to determine parameter uncertainties is compared using the pull distributions from a large number of pseudoexperiments.\n\/\/\/ The pull is defined as \\f$ (\\lambda_i - \\lambda_{gen})\/\\sigma(\\lambda_i) \\f$, where \\f$ \\lambda_i \\f$ is the fitted parameter and \\f$ \\sigma(\\lambda_i) \\f$ its\n\/\/\/ uncertainty for pseudoexperiment number i.\n\/\/\/ If the fit is unbiased and the parameter uncertainties are estimated correctly, the pull distribution should be a Gaussian centered around zero with a width of one.\n\/\/\/\n\/\/\/ \\macro_image\n\/\/\/ \\macro_output\n\/\/\/ \\macro_code\n\/\/\/ \\author 11\/2019 - Christoph Langenbruch\n\n#include \"TH1D.h\"\n#include \"TCanvas.h\"\n#include \"TROOT.h\"\n#include \"TStyle.h\"\n#include \"TRandom3.h\"\n#include \"TLegend.h\"\n#include \"RooRealVar.h\"\n#include \"RooFitResult.h\"\n#include \"RooDataSet.h\"\n#include \"RooPolynomial.h\"\n\nusing namespace RooFit;\n\n\nint rf611_weightedfits(int acceptancemodel=2) {\n \/\/ I n i t i a l i s a t i o n a n d S e t u p\n \/\/------------------------------------------------ \n\n \/\/plotting options\n gStyle->SetPaintTextFormat(\".1f\");\n gStyle->SetEndErrorSize(6.0);\n gStyle->SetTitleSize(0.05, \"XY\");\n gStyle->SetLabelSize(0.05, \"XY\");\n gStyle->SetTitleOffset(0.9, \"XY\");\n gStyle->SetTextSize(0.05);\n gStyle->SetPadLeftMargin(0.125);\n gStyle->SetPadBottomMargin(0.125);\n gStyle->SetPadTopMargin(0.075);\n gStyle->SetPadRightMargin(0.075);\n gStyle->SetMarkerStyle(20);\n gStyle->SetMarkerSize(1.0);\n gStyle->SetHistLineWidth(2.0);\n gStyle->SetHistLineColor(1);\n\n \/\/initialise TRandom3\n TRandom3* rnd = new TRandom3();\n rnd->SetSeed(191101303);\n\n \/\/accepted events and events weighted to account for the acceptance\n TH1D* haccepted = new TH1D(\"haccepted\", \"Generated events;cos(#theta);#events\", 40, -1.0, 1.0);\n TH1D* hweighted = new TH1D(\"hweighted\", \"Generated events;cos(#theta);#events\", 40, -1.0, 1.0);\n \/\/histograms holding pull distributions \n \/\/using the inverse Hessian matrix\n TH1D* hc0pull1 = new TH1D(\"hc0pull1\", \"Inverse weighted Hessian matrix [SumW2Error(false)];Pull (c_{0}^{fit}-c_{0}^{gen})\/#sigma(c_{0});\", 20, -5.0, 5.0);\n TH1D* hc1pull1 = new TH1D(\"hc1pull1\", \"Inverse weighted Hessian matrix [SumW2Error(false)];Pull (c_{1}^{fit}-c_{1}^{gen})\/#sigma(c_{1});\", 20, -5.0, 5.0);\n \/\/using the correction with the Hessian matrix with squared weights\n TH1D* hc0pull2 = new TH1D(\"hc0pull2\", \"Hessian matrix with squared weights [SumW2Error(true)];Pull (c_{0}^{fit}-c_{0}^{gen})\/#sigma(c_{0});\", 20, -5.0, 5.0);\n TH1D* hc1pull2 = new TH1D(\"hc1pull2\", \"Hessian matrix with squared weights [SumW2Error(true)];Pull (c_{1}^{fit}-c_{1}^{gen})\/#sigma(c_{1});\", 20, -5.0, 5.0);\n \/\/asymptotically correct approach\n TH1D* hc0pull3 = new TH1D(\"hc0pull3\", \"Asymptotically correct approach [Asymptotic(true)];Pull (c_{0}^{fit}-c_{0}^{gen})\/#sigma(c_{0});\", 20, -5.0, 5.0);\n TH1D* hc1pull3 = new TH1D(\"hc1pull3\", \"Asymptotically correct approach [Asymptotic(true)];Pull (c_{1}^{fit}-c_{1}^{gen})\/#sigma(c_{1});\", 20, -5.0, 5.0);\n\n \/\/number of pseudoexperiments (toys) and number of events per pseudoexperiment\n constexpr unsigned int ntoys = 500;\n constexpr unsigned int nstats = 5000;\n \/\/parameters used in the generation\n constexpr double c0gen = 0.0;\n constexpr double c1gen = 0.0;\n\n \/\/ Silence fitting and minimisation messages\n auto& msgSv = RooMsgService::instance();\n msgSv.getStream(1).removeTopic(RooFit::Minimization);\n msgSv.getStream(1).removeTopic(RooFit::Fitting);\n\n std::cout << \"Running \" << ntoys*3 << \" toy fits ...\" << std::endl;\n\n \/\/ M a i n l o o p : r u n p s e u d o e x p e r i m e n t s\n \/\/----------------------------------------------------------------\n for (unsigned int i=0; i<ntoys; i++) {\n \/\/S e t u p p a r a m e t e r s a n d P D F\n \/\/-----------------------------------------------\n \/\/angle theta and the weight to account for the acceptance effect\n RooRealVar costheta(\"costheta\",\"costheta\", -1.0, 1.0);\n RooRealVar weight(\"weight\",\"weight\", 0.0, 1000.0);\n\n \/\/initialise parameters to fit\n RooRealVar c0(\"c0\",\"0th-order coefficient\", c0gen, -1.0, 1.0);\n RooRealVar c1(\"c1\",\"1st-order coefficient\", c1gen, -1.0, 1.0);\n c0.setError(0.01);\n c1.setError(0.01);\n \/\/create simple second-order polynomial as probability density function\n RooPolynomial pol(\"pol\", \"pol\", costheta, RooArgList(c0, c1), 1);\n\n \/\/G e n e r a t e d a t a s e t f o r p s e u d o e x p e r i m e n t i\n \/\/-------------------------------------------------------------------------------\n RooDataSet data(\"data\",\"data\",RooArgSet(costheta, weight), WeightVar(\"weight\"));\n \/\/generate nstats events\n for (unsigned int j=0; j<nstats; j++) {\n bool finished = false;\n \/\/use simple accept\/reject for generation\n while (!finished) {\n costheta = 2.0*rnd->Rndm()-1.0;\n \/\/efficiency for the specific value of cos(theta)\n double eff = 1.0;\n if (acceptancemodel == 1)\n eff = 1.0 - 0.7 * costheta.getVal()*costheta.getVal();\n else\n eff = 0.3 + 0.7 * costheta.getVal()*costheta.getVal();\n \/\/use 1\/eff as weight to account for acceptance\n weight = 1.0\/eff;\n \/\/accept\/reject\n if (10.0*rnd->Rndm() < eff*pol.getVal())\n finished = true;\n }\n haccepted->Fill(costheta.getVal());\n hweighted->Fill(costheta.getVal(), weight.getVal());\n data.add(RooArgSet(costheta, weight), weight.getVal());\n }\n\n \/\/F i t t o y u s i n g t h e t h r e e d i f f e r e n t a p p r o a c h e s t o u n c e r t a i n t y d e t e r m i n a t i o n\n \/\/-------------------------------------------------------------------------------------------------------------------------------------------------\n \/\/this uses the inverse weighted Hessian matrix\n RooFitResult* result = pol.fitTo(data, Save(true), SumW2Error(false), PrintLevel(-1), BatchMode(true));\n hc0pull1->Fill((c0.getVal()-c0gen)\/c0.getError());\n hc1pull1->Fill((c1.getVal()-c1gen)\/c1.getError());\n\n \/\/this uses the correction with the Hesse matrix with squared weights\n result = pol.fitTo(data, Save(true), SumW2Error(true), PrintLevel(-1), BatchMode(true));\n hc0pull2->Fill((c0.getVal()-c0gen)\/c0.getError());\n hc1pull2->Fill((c1.getVal()-c1gen)\/c1.getError());\n\n \/\/this uses the asymptotically correct approach\n result = pol.fitTo(data, Save(true), AsymptoticError(true), PrintLevel(-1), BatchMode(true));\n hc0pull3->Fill((c0.getVal()-c0gen)\/c0.getError());\n hc1pull3->Fill((c1.getVal()-c1gen)\/c1.getError());\n }\n \n std::cout << \"... done.\" << std::endl;\n\n \/\/ P l o t o u t p u t d i s t r i b u t i o n s\n \/\/--------------------------------------------------\n \n \/\/plot accepted (weighted) events\n gStyle->SetOptStat(0);\n gStyle->SetOptFit(0);\n TCanvas* cevents = new TCanvas(\"cevents\", \"cevents\", 800, 600);\n cevents->cd(1);\n hweighted->SetMinimum(0.0);\n hweighted->SetLineColor(2);\n hweighted->Draw(\"hist\");\n haccepted->Draw(\"same hist\");\n TLegend* leg = new TLegend(0.6, 0.8, 0.9, 0.9);\n leg->AddEntry(haccepted, \"Accepted\");\n leg->AddEntry(hweighted, \"Weighted\");\n leg->Draw();\n cevents->Update();\n \n \/\/plot pull distributions\n TCanvas* cpull = new TCanvas(\"cpull\", \"cpull\", 1200, 800);\n cpull->Divide(3,2);\n cpull->cd(1);\n gStyle->SetOptStat(1100);\n gStyle->SetOptFit(11);\n hc0pull1->Fit(\"gaus\");\n hc0pull1->Draw(\"ep\");\n cpull->cd(2);\n hc0pull2->Fit(\"gaus\");\n hc0pull2->Draw(\"ep\");\n cpull->cd(3);\n hc0pull3->Fit(\"gaus\");\n hc0pull3->Draw(\"ep\");\n cpull->cd(4);\n hc1pull1->Fit(\"gaus\");\n hc1pull1->Draw(\"ep\");\n cpull->cd(5);\n hc1pull2->Fit(\"gaus\");\n hc1pull2->Draw(\"ep\");\n cpull->cd(6);\n hc1pull3->Fit(\"gaus\");\n hc1pull3->Draw(\"ep\");\n cpull->Update();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"skiphash_copy.h\"\r\n#include <string>\r\n#include \"..\/..\/urbackupcommon\/chunk_hasher.h\"\r\n#include \"..\/..\/stringtools.h\"\r\n#include \"..\/..\/urbackupcommon\/os_functions.h\"\r\n#include <memory>\r\n\r\nbool skiphash_copy(const std::wstring& src_path,\r\n\tconst std::wstring& dst_path,\r\n\tconst std::wstring& hashinput_path)\r\n{\r\n\tstd::auto_ptr<IFile> src(Server->openFile(os_file_prefix(src_path), MODE_READ_SEQUENTIAL));\r\n\r\n\tif(!src.get())\r\n\t{\r\n\t\tServer->Log(L\"Could not open source file for reading at \\\"\" + src_path+L\"\\\"\", LL_ERROR);\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::auto_ptr<IFile> hashoutput(Server->openFile(os_file_prefix(dst_path+L\".hash\"), MODE_WRITE));\r\n\r\n\tif(!hashoutput.get())\r\n\t{\r\n\t\tServer->Log(L\"Could not open hash output for writing at \\\"\"+dst_path+L\".hash\\\"\", LL_ERROR);\r\n\t\treturn false;\r\n\t}\r\n\r\n\tbool dst_exists = Server->fileExists(dst_path);\r\n\r\n\tstd::auto_ptr<IFile> dst(Server->openFile(os_file_prefix(dst_path), MODE_RW));\r\n\r\n\tif(!dst.get())\r\n\t{\r\n\t\tServer->Log(L\"Could not open output file for writing at \\\"\"+dst_path+L\"\\\"\", LL_ERROR);\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::auto_ptr<IFile> hashinput;\r\n\t\r\n\tif(!hashinput_path.empty())\r\n\t{\r\n\t\thashinput.reset(Server->openFile(os_file_prefix(hashinput_path), MODE_READ));\r\n\r\n\t\tif(!hashinput.get())\r\n\t\t{\r\n\t\t\tServer->Log(L\"Could not open hash input file at \\\"\"+hashinput_path+L\"\\\"\", LL_ERROR);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tif(!dst_exists || !hashinput.get())\r\n\t{\r\n\t\tServer->Log(\"Destination file does not exist or there is no hash input. Performing full copy (with hash output)...\", LL_INFO);\r\n\t\treturn build_chunk_hashs(src.get(), hashoutput.get(), NULL, false, dst.get(), false)!=\"\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint64 inplace_written = 0;\r\n\t\tbool ret = build_chunk_hashs(src.get(), hashoutput.get(), NULL, false,\r\n\t\t\tdst.get(), true, &inplace_written, hashinput.get())!=\"\";\r\n\t\tfloat skipped_pc=0;\r\n\t\tif(src->Size()>0)\r\n\t\t{\r\n\t\t\tskipped_pc = 100.f - 100.f*src->Size()\/inplace_written;\r\n\t\t}\r\n\t\t\r\n\t\tServer->Log(\"Wrote \"+PrettyPrintBytes(inplace_written)\r\n\t\t\t+\". Skipped \"+PrettyPrintBytes(src->Size()-inplace_written)+\" (\"+\r\n\t\t\tnconvert(static_cast<int>(skipped_pc+0.5f))+\"%)\", LL_INFO);\r\n\r\n\t\treturn ret;\r\n\t}\r\n}\r\n\r\nint skiphash_copy_file()\r\n{\r\n\tstd::string src = Server->getServerParameter(\"src\");\r\n\tstd::string dst = Server->getServerParameter(\"dst\");\r\n\tstd::string hashsrc = Server->getServerParameter(\"hashsrc\");\r\n\r\n\treturn skiphash_copy(Server->ConvertToUnicode(src),\r\n\t\tServer->ConvertToUnicode(dst),\r\n\t\tServer->ConvertToUnicode(hashsrc)) ? 1 : 0;\r\n}\r\n<commit_msg>Create file if it does not exist<commit_after>#include \"skiphash_copy.h\"\r\n#include <string>\r\n#include \"..\/..\/urbackupcommon\/chunk_hasher.h\"\r\n#include \"..\/..\/stringtools.h\"\r\n#include \"..\/..\/urbackupcommon\/os_functions.h\"\r\n#include <memory>\r\n\r\nbool skiphash_copy(const std::wstring& src_path,\r\n\tconst std::wstring& dst_path,\r\n\tconst std::wstring& hashinput_path)\r\n{\r\n\tstd::auto_ptr<IFile> src(Server->openFile(os_file_prefix(src_path), MODE_READ_SEQUENTIAL));\r\n\r\n\tif(!src.get())\r\n\t{\r\n\t\tServer->Log(L\"Could not open source file for reading at \\\"\" + src_path+L\"\\\"\", LL_ERROR);\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::auto_ptr<IFile> hashoutput(Server->openFile(os_file_prefix(dst_path+L\".hash\"), MODE_WRITE));\r\n\r\n\tif(!hashoutput.get())\r\n\t{\r\n\t\tServer->Log(L\"Could not open hash output for writing at \\\"\"+dst_path+L\".hash\\\"\", LL_ERROR);\r\n\t\treturn false;\r\n\t}\r\n\r\n\tbool dst_exists = Server->fileExists(dst_path);\r\n\r\n\tstd::auto_ptr<IFile> dst(Server->openFile(os_file_prefix(dst_path), MODE_RW));\r\n\r\n\tif(!dst.get())\r\n\t{\r\n\t\tdst.reset(Server->openFile(os_file_prefix(dst_path), MODE_WRITE));\r\n\t}\r\n\r\n\tif(!dst.get())\r\n\t{\r\n\t\tServer->Log(L\"Could not open output file for writing at \\\"\"+dst_path+L\"\\\"\", LL_ERROR);\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::auto_ptr<IFile> hashinput;\r\n\t\r\n\tif(!hashinput_path.empty())\r\n\t{\r\n\t\thashinput.reset(Server->openFile(os_file_prefix(hashinput_path), MODE_READ));\r\n\r\n\t\tif(!hashinput.get())\r\n\t\t{\r\n\t\t\tServer->Log(L\"Could not open hash input file at \\\"\"+hashinput_path+L\"\\\"\", LL_ERROR);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tif(!dst_exists || !hashinput.get())\r\n\t{\r\n\t\tServer->Log(\"Destination file does not exist or there is no hash input. Performing full copy (with hash output)...\", LL_INFO);\r\n\t\treturn build_chunk_hashs(src.get(), hashoutput.get(), NULL, false, dst.get(), false)!=\"\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint64 inplace_written = 0;\r\n\t\tbool ret = build_chunk_hashs(src.get(), hashoutput.get(), NULL, false,\r\n\t\t\tdst.get(), true, &inplace_written, hashinput.get())!=\"\";\r\n\t\tfloat skipped_pc=0;\r\n\t\tif(src->Size()>0)\r\n\t\t{\r\n\t\t\tskipped_pc = 100.f - 100.f*src->Size()\/inplace_written;\r\n\t\t}\r\n\t\t\r\n\t\tServer->Log(\"Wrote \"+PrettyPrintBytes(inplace_written)\r\n\t\t\t+\". Skipped \"+PrettyPrintBytes(src->Size()-inplace_written)+\" (\"+\r\n\t\t\tnconvert(static_cast<int>(skipped_pc+0.5f))+\"%)\", LL_INFO);\r\n\r\n\t\treturn ret;\r\n\t}\r\n}\r\n\r\nint skiphash_copy_file()\r\n{\r\n\tstd::string src = Server->getServerParameter(\"src\");\r\n\tstd::string dst = Server->getServerParameter(\"dst\");\r\n\tstd::string hashsrc = Server->getServerParameter(\"hashsrc\");\r\n\r\n\treturn skiphash_copy(Server->ConvertToUnicode(src),\r\n\t\tServer->ConvertToUnicode(dst),\r\n\t\tServer->ConvertToUnicode(hashsrc)) ? 1 : 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"views\/controls\/textfield\/textfield.h\"\n\n#if defined(OS_LINUX)\n#include <gdk\/gdkkeysyms.h>\n#endif\n\n#include \"app\/gfx\/insets.h\"\n#if defined(OS_WIN)\n#include \"app\/win_util.h\"\n#include \"base\/win_util.h\"\n#endif\n\n#include \"base\/string_util.h\"\n#include \"views\/controls\/textfield\/native_textfield_wrapper.h\"\n#include \"views\/widget\/widget.h\"\n\n#if defined(OS_WIN)\n\/\/ TODO(beng): this should be removed when the OS_WIN hack from\n\/\/ ViewHierarchyChanged is removed.\n#include \"views\/controls\/textfield\/native_textfield_win.h\"\n#endif\n\nnamespace views {\n\n\/\/ static\nconst char Textfield::kViewClassName[] = \"views\/Textfield\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Textfield\n\nTextfield::Textfield()\n : native_wrapper_(NULL),\n controller_(NULL),\n style_(STYLE_DEFAULT),\n read_only_(false),\n default_width_in_chars_(0),\n draw_border_(true),\n text_color_(SK_ColorBLACK),\n background_color_(SK_ColorWHITE),\n use_default_text_color_(true),\n use_default_background_color_(true),\n num_lines_(1),\n initialized_(false) {\n SetFocusable(true);\n}\n\nTextfield::Textfield(StyleFlags style)\n : native_wrapper_(NULL),\n controller_(NULL),\n style_(style),\n read_only_(false),\n default_width_in_chars_(0),\n draw_border_(true),\n text_color_(SK_ColorBLACK),\n background_color_(SK_ColorWHITE),\n use_default_text_color_(true),\n use_default_background_color_(true),\n num_lines_(1),\n initialized_(false) {\n SetFocusable(true);\n}\n\nTextfield::~Textfield() {\n}\n\nvoid Textfield::SetController(Controller* controller) {\n controller_ = controller;\n}\n\nTextfield::Controller* Textfield::GetController() const {\n return controller_;\n}\n\nvoid Textfield::SetReadOnly(bool read_only) {\n read_only_ = read_only;\n if (native_wrapper_) {\n native_wrapper_->UpdateReadOnly();\n native_wrapper_->UpdateTextColor();\n native_wrapper_->UpdateBackgroundColor();\n }\n}\n\nbool Textfield::IsPassword() const {\n return style_ & STYLE_PASSWORD;\n}\n\nbool Textfield::IsMultiLine() const {\n return !!(style_ & STYLE_MULTILINE);\n}\n\nvoid Textfield::SetText(const string16& text) {\n text_ = text;\n if (native_wrapper_)\n native_wrapper_->UpdateText();\n}\n\nvoid Textfield::AppendText(const string16& text) {\n text_ += text;\n if (native_wrapper_)\n native_wrapper_->AppendText(text);\n}\n\nvoid Textfield::SelectAll() {\n if (native_wrapper_)\n native_wrapper_->SelectAll();\n}\n\nstring16 Textfield::GetSelectedText() const {\n if (native_wrapper_)\n return native_wrapper_->GetSelectedText();\n return string16();\n}\n\nvoid Textfield::ClearSelection() const {\n if (native_wrapper_)\n native_wrapper_->ClearSelection();\n}\n\nvoid Textfield::SetTextColor(SkColor color) {\n text_color_ = color;\n use_default_text_color_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateTextColor();\n}\n\nvoid Textfield::UseDefaultTextColor() {\n use_default_text_color_ = true;\n if (native_wrapper_)\n native_wrapper_->UpdateTextColor();\n}\n\nvoid Textfield::SetBackgroundColor(SkColor color) {\n background_color_ = color;\n use_default_background_color_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateBackgroundColor();\n}\n\nvoid Textfield::UseDefaultBackgroundColor() {\n use_default_background_color_ = true;\n if (native_wrapper_)\n native_wrapper_->UpdateBackgroundColor();\n}\n\nvoid Textfield::SetFont(const gfx::Font& font) {\n font_ = font;\n if (native_wrapper_)\n native_wrapper_->UpdateFont();\n}\n\nvoid Textfield::SetHorizontalMargins(int left, int right) {\n if (native_wrapper_)\n native_wrapper_->SetHorizontalMargins(left, right);\n}\n\nvoid Textfield::SetHeightInLines(int num_lines) {\n DCHECK(IsMultiLine());\n num_lines_ = num_lines;\n}\n\nvoid Textfield::RemoveBorder() {\n if (!draw_border_)\n return;\n\n draw_border_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateBorder();\n}\n\n\nvoid Textfield::CalculateInsets(gfx::Insets* insets) {\n DCHECK(insets);\n\n if (!draw_border_)\n return;\n\n \/\/ NOTE: One would think GetThemeMargins would return the insets we should\n \/\/ use, but it doesn't. The margins returned by GetThemeMargins are always\n \/\/ 0.\n\n \/\/ This appears to be the insets used by Windows.\n insets->Set(3, 3, 3, 3);\n}\n\nvoid Textfield::SyncText() {\n if (native_wrapper_)\n text_ = native_wrapper_->GetText();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Textfield, View overrides:\n\nvoid Textfield::Layout() {\n if (native_wrapper_) {\n native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));\n native_wrapper_->GetView()->Layout();\n }\n}\n\ngfx::Size Textfield::GetPreferredSize() {\n gfx::Insets insets;\n CalculateInsets(&insets);\n return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +\n insets.width(),\n num_lines_ * font_.height() + insets.height());\n}\n\nbool Textfield::IsFocusable() const {\n return IsEnabled() && !read_only_;\n}\n\nvoid Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {\n SelectAll();\n}\n\nbool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {\n#if defined(OS_WIN)\n \/\/ TODO(hamaji): Figure out which keyboard combinations we need to add here,\n \/\/ similar to LocationBarView::SkipDefaultKeyEventProcessing.\n const int c = e.GetCharacter();\n if (c == VK_BACK)\n return true; \/\/ We'll handle BackSpace ourselves.\n\n \/\/ We don't translate accelerators for ALT + NumPad digit, they are used for\n \/\/ entering special characters. We do translate alt-home.\n if (e.IsAltDown() && (c != VK_HOME) &&\n win_util::IsNumPadDigit(c, e.IsExtendedKey()))\n return true;\n#endif\n return false;\n}\n\nvoid Textfield::SetEnabled(bool enabled) {\n View::SetEnabled(enabled);\n if (native_wrapper_)\n native_wrapper_->UpdateEnabled();\n}\n\nvoid Textfield::Focus() {\n if (native_wrapper_) {\n \/\/ Forward the focus to the wrapper if it exists.\n native_wrapper_->SetFocus();\n } else {\n \/\/ If there is no wrapper, cause the RootView to be focused so that we still\n \/\/ get keyboard messages.\n View::Focus();\n }\n}\n\nvoid Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {\n if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {\n initialized_ = true;\n\n \/\/ The native wrapper's lifetime will be managed by the view hierarchy after\n \/\/ we call AddChildView.\n native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);\n AddChildView(native_wrapper_->GetView());\n \/\/ TODO(beng): Move this initialization to NativeTextfieldWin once it\n \/\/ subclasses NativeControlWin.\n native_wrapper_->UpdateText();\n native_wrapper_->UpdateTextColor();\n native_wrapper_->UpdateBackgroundColor();\n native_wrapper_->UpdateReadOnly();\n native_wrapper_->UpdateFont();\n native_wrapper_->UpdateEnabled();\n native_wrapper_->UpdateBorder();\n\n#if defined(OS_WIN)\n \/\/ TODO(beng): remove this once NativeTextfieldWin subclasses\n \/\/ NativeControlWin. This is currently called to perform post-AddChildView\n \/\/ initialization for the wrapper. The GTK version subclasses things\n \/\/ correctly and doesn't need this.\n \/\/\n \/\/ Remove the include for native_textfield_win.h above when you fix this.\n static_cast<NativeTextfieldWin*>(native_wrapper_)->AttachHack();\n#endif\n }\n}\n\nstd::string Textfield::GetClassName() const {\n return kViewClassName;\n}\n\nNativeTextfieldWrapper* Textfield::CreateWrapper() {\n NativeTextfieldWrapper* native_wrapper =\n NativeTextfieldWrapper::CreateWrapper(this);\n\n native_wrapper->UpdateText();\n native_wrapper->UpdateBackgroundColor();\n native_wrapper->UpdateReadOnly();\n native_wrapper->UpdateFont();\n native_wrapper->UpdateEnabled();\n native_wrapper->UpdateBorder();\n\n return native_wrapper;\n}\n\nbase::KeyboardCode Textfield::Keystroke::GetKeyboardCode() const {\n#if defined(OS_WIN)\n return static_cast<base::KeyboardCode>(key_);\n#else\n return static_cast<base::KeyboardCode>(event_.keyval);\n#endif\n}\n\n#if defined(OS_WIN)\nbool Textfield::Keystroke::IsControlHeld() const {\n return win_util::IsCtrlPressed();\n}\n\nbool Textfield::Keystroke::IsShiftHeld() const {\n return win_util::IsShiftPressed();\n}\n#else\nbool Textfield::Keystroke::IsControlHeld() const {\n return (event_.state & gtk_accelerator_get_default_mod_mask()) ==\n GDK_CONTROL_MASK;\n}\n\nbool Textfield::Keystroke::IsShiftHeld() const {\n return (event_.state & gtk_accelerator_get_default_mod_mask()) ==\n GDK_SHIFT_MASK;\n}\n#endif\n\n} \/\/ namespace views\n<commit_msg>fix Linux views build.<commit_after>\/\/ 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 \"views\/controls\/textfield\/textfield.h\"\n\n#if defined(OS_LINUX)\n#include <gdk\/gdkkeysyms.h>\n#endif\n\n#include \"app\/gfx\/insets.h\"\n#if defined(OS_WIN)\n#include \"app\/win_util.h\"\n#include \"base\/win_util.h\"\n#endif\n\n#include \"base\/string_util.h\"\n#include \"views\/controls\/textfield\/native_textfield_wrapper.h\"\n#include \"views\/widget\/widget.h\"\n\n#if defined(OS_WIN)\n\/\/ TODO(beng): this should be removed when the OS_WIN hack from\n\/\/ ViewHierarchyChanged is removed.\n#include \"views\/controls\/textfield\/native_textfield_win.h\"\n#endif\n\nnamespace views {\n\n\/\/ static\nconst char Textfield::kViewClassName[] = \"views\/Textfield\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Textfield\n\nTextfield::Textfield()\n : native_wrapper_(NULL),\n controller_(NULL),\n style_(STYLE_DEFAULT),\n read_only_(false),\n default_width_in_chars_(0),\n draw_border_(true),\n text_color_(SK_ColorBLACK),\n use_default_text_color_(true),\n background_color_(SK_ColorWHITE),\n use_default_background_color_(true),\n num_lines_(1),\n initialized_(false) {\n SetFocusable(true);\n}\n\nTextfield::Textfield(StyleFlags style)\n : native_wrapper_(NULL),\n controller_(NULL),\n style_(style),\n read_only_(false),\n default_width_in_chars_(0),\n draw_border_(true),\n text_color_(SK_ColorBLACK),\n use_default_text_color_(true),\n background_color_(SK_ColorWHITE),\n use_default_background_color_(true),\n num_lines_(1),\n initialized_(false) {\n SetFocusable(true);\n}\n\nTextfield::~Textfield() {\n}\n\nvoid Textfield::SetController(Controller* controller) {\n controller_ = controller;\n}\n\nTextfield::Controller* Textfield::GetController() const {\n return controller_;\n}\n\nvoid Textfield::SetReadOnly(bool read_only) {\n read_only_ = read_only;\n if (native_wrapper_) {\n native_wrapper_->UpdateReadOnly();\n native_wrapper_->UpdateTextColor();\n native_wrapper_->UpdateBackgroundColor();\n }\n}\n\nbool Textfield::IsPassword() const {\n return style_ & STYLE_PASSWORD;\n}\n\nbool Textfield::IsMultiLine() const {\n return !!(style_ & STYLE_MULTILINE);\n}\n\nvoid Textfield::SetText(const string16& text) {\n text_ = text;\n if (native_wrapper_)\n native_wrapper_->UpdateText();\n}\n\nvoid Textfield::AppendText(const string16& text) {\n text_ += text;\n if (native_wrapper_)\n native_wrapper_->AppendText(text);\n}\n\nvoid Textfield::SelectAll() {\n if (native_wrapper_)\n native_wrapper_->SelectAll();\n}\n\nstring16 Textfield::GetSelectedText() const {\n if (native_wrapper_)\n return native_wrapper_->GetSelectedText();\n return string16();\n}\n\nvoid Textfield::ClearSelection() const {\n if (native_wrapper_)\n native_wrapper_->ClearSelection();\n}\n\nvoid Textfield::SetTextColor(SkColor color) {\n text_color_ = color;\n use_default_text_color_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateTextColor();\n}\n\nvoid Textfield::UseDefaultTextColor() {\n use_default_text_color_ = true;\n if (native_wrapper_)\n native_wrapper_->UpdateTextColor();\n}\n\nvoid Textfield::SetBackgroundColor(SkColor color) {\n background_color_ = color;\n use_default_background_color_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateBackgroundColor();\n}\n\nvoid Textfield::UseDefaultBackgroundColor() {\n use_default_background_color_ = true;\n if (native_wrapper_)\n native_wrapper_->UpdateBackgroundColor();\n}\n\nvoid Textfield::SetFont(const gfx::Font& font) {\n font_ = font;\n if (native_wrapper_)\n native_wrapper_->UpdateFont();\n}\n\nvoid Textfield::SetHorizontalMargins(int left, int right) {\n if (native_wrapper_)\n native_wrapper_->SetHorizontalMargins(left, right);\n}\n\nvoid Textfield::SetHeightInLines(int num_lines) {\n DCHECK(IsMultiLine());\n num_lines_ = num_lines;\n}\n\nvoid Textfield::RemoveBorder() {\n if (!draw_border_)\n return;\n\n draw_border_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateBorder();\n}\n\n\nvoid Textfield::CalculateInsets(gfx::Insets* insets) {\n DCHECK(insets);\n\n if (!draw_border_)\n return;\n\n \/\/ NOTE: One would think GetThemeMargins would return the insets we should\n \/\/ use, but it doesn't. The margins returned by GetThemeMargins are always\n \/\/ 0.\n\n \/\/ This appears to be the insets used by Windows.\n insets->Set(3, 3, 3, 3);\n}\n\nvoid Textfield::SyncText() {\n if (native_wrapper_)\n text_ = native_wrapper_->GetText();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Textfield, View overrides:\n\nvoid Textfield::Layout() {\n if (native_wrapper_) {\n native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));\n native_wrapper_->GetView()->Layout();\n }\n}\n\ngfx::Size Textfield::GetPreferredSize() {\n gfx::Insets insets;\n CalculateInsets(&insets);\n return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +\n insets.width(),\n num_lines_ * font_.height() + insets.height());\n}\n\nbool Textfield::IsFocusable() const {\n return IsEnabled() && !read_only_;\n}\n\nvoid Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {\n SelectAll();\n}\n\nbool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {\n#if defined(OS_WIN)\n \/\/ TODO(hamaji): Figure out which keyboard combinations we need to add here,\n \/\/ similar to LocationBarView::SkipDefaultKeyEventProcessing.\n const int c = e.GetCharacter();\n if (c == VK_BACK)\n return true; \/\/ We'll handle BackSpace ourselves.\n\n \/\/ We don't translate accelerators for ALT + NumPad digit, they are used for\n \/\/ entering special characters. We do translate alt-home.\n if (e.IsAltDown() && (c != VK_HOME) &&\n win_util::IsNumPadDigit(c, e.IsExtendedKey()))\n return true;\n#endif\n return false;\n}\n\nvoid Textfield::SetEnabled(bool enabled) {\n View::SetEnabled(enabled);\n if (native_wrapper_)\n native_wrapper_->UpdateEnabled();\n}\n\nvoid Textfield::Focus() {\n if (native_wrapper_) {\n \/\/ Forward the focus to the wrapper if it exists.\n native_wrapper_->SetFocus();\n } else {\n \/\/ If there is no wrapper, cause the RootView to be focused so that we still\n \/\/ get keyboard messages.\n View::Focus();\n }\n}\n\nvoid Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {\n if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {\n initialized_ = true;\n\n \/\/ The native wrapper's lifetime will be managed by the view hierarchy after\n \/\/ we call AddChildView.\n native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);\n AddChildView(native_wrapper_->GetView());\n \/\/ TODO(beng): Move this initialization to NativeTextfieldWin once it\n \/\/ subclasses NativeControlWin.\n native_wrapper_->UpdateText();\n native_wrapper_->UpdateTextColor();\n native_wrapper_->UpdateBackgroundColor();\n native_wrapper_->UpdateReadOnly();\n native_wrapper_->UpdateFont();\n native_wrapper_->UpdateEnabled();\n native_wrapper_->UpdateBorder();\n\n#if defined(OS_WIN)\n \/\/ TODO(beng): remove this once NativeTextfieldWin subclasses\n \/\/ NativeControlWin. This is currently called to perform post-AddChildView\n \/\/ initialization for the wrapper. The GTK version subclasses things\n \/\/ correctly and doesn't need this.\n \/\/\n \/\/ Remove the include for native_textfield_win.h above when you fix this.\n static_cast<NativeTextfieldWin*>(native_wrapper_)->AttachHack();\n#endif\n }\n}\n\nstd::string Textfield::GetClassName() const {\n return kViewClassName;\n}\n\nNativeTextfieldWrapper* Textfield::CreateWrapper() {\n NativeTextfieldWrapper* native_wrapper =\n NativeTextfieldWrapper::CreateWrapper(this);\n\n native_wrapper->UpdateText();\n native_wrapper->UpdateBackgroundColor();\n native_wrapper->UpdateReadOnly();\n native_wrapper->UpdateFont();\n native_wrapper->UpdateEnabled();\n native_wrapper->UpdateBorder();\n\n return native_wrapper;\n}\n\nbase::KeyboardCode Textfield::Keystroke::GetKeyboardCode() const {\n#if defined(OS_WIN)\n return static_cast<base::KeyboardCode>(key_);\n#else\n return static_cast<base::KeyboardCode>(event_.keyval);\n#endif\n}\n\n#if defined(OS_WIN)\nbool Textfield::Keystroke::IsControlHeld() const {\n return win_util::IsCtrlPressed();\n}\n\nbool Textfield::Keystroke::IsShiftHeld() const {\n return win_util::IsShiftPressed();\n}\n#else\nbool Textfield::Keystroke::IsControlHeld() const {\n return (event_.state & gtk_accelerator_get_default_mod_mask()) ==\n GDK_CONTROL_MASK;\n}\n\nbool Textfield::Keystroke::IsShiftHeld() const {\n return (event_.state & gtk_accelerator_get_default_mod_mask()) ==\n GDK_SHIFT_MASK;\n}\n#endif\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2010, Willow Garage, Inc.\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 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 * \\author Nico Blodow (blodow@cs.tum.edu), Julius Kammerl (julius@kammerl.de)\n * *\/\n\n#include \"pcl\/octree\/octree.h\"\n#include <pcl\/visualization\/pcl_visualizer.h>\n#include <pcl\/io\/pcd_io.h>\n#include <iostream>\n\n#include <vtkCubeSource.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create a vtkSmartPointer object containing a cube\nvtkSmartPointer<vtkPolyData>\nGetCuboid (double minX, double maxX, double minY, double maxY, double minZ, double maxZ)\n{\n vtkSmartPointer < vtkCubeSource > cube = vtkSmartPointer<vtkCubeSource>::New ();\n cube->SetBounds (minX, maxX, minY, maxY, minZ, maxZ);\n return cube->GetOutput ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create vtkActorCollection of vtkSmartPointers describing octree cubes\nvoid\nGetOctreeActors (std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> >& voxelCenters, double voxelSideLen, vtkSmartPointer<vtkActorCollection> coll)\n{\n\n vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New ();\n\n size_t i;\n double s = voxelSideLen\/2.0;\n\n for (i = 0; i < voxelCenters.size (); i++)\n {\n\n double x = voxelCenters[i].x;\n double y = voxelCenters[i].y;\n double z = voxelCenters[i].z;\n\n treeWireframe->AddInput (GetCuboid (x - s, x + s, y - s, y + s, z - s, z + s));\n }\n\n vtkSmartPointer < vtkActor > treeActor = vtkSmartPointer<vtkActor>::New ();\n\n vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New ();\n mapper->SetInput (treeWireframe->GetOutput ());\n treeActor->SetMapper (mapper);\n\n treeActor->GetProperty ()->SetRepresentationToWireframe ();\n treeActor->GetProperty ()->SetColor (0.0, 0.0, 1.0);\n treeActor->GetProperty ()->SetLineWidth (2);\n coll->AddItem (treeActor);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create a vtkPolyData object from a set of vtkPoints\nvtkDataSet*\n createDataSetFromVTKPoints (vtkPoints *points)\n{\n vtkCellArray *verts = vtkCellArray::New ();\n vtkPolyData *data = vtkPolyData::New ();\n \/\/ Iterate through the points\n for (vtkIdType i = 0; i < points->GetNumberOfPoints (); i++)\n verts->InsertNextCell ((vtkIdType)1, &i);\n data->SetPoints (points);\n data->SetVerts (verts);\n return data;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create vtkActorCollection of vtkSmartPointers describing input points\nvoid\n GetPointActors (pcl::PointCloud<pcl::PointXYZ>& cloud, vtkSmartPointer<vtkActorCollection> coll)\n{\n vtkPolyData* points_poly;\n\n size_t i;\n\n vtkPoints *octreeLeafPoints = vtkPoints::New ();\n\n \/\/ add all points from octree to vtkPoint object\n for (i=0; i< cloud.points.size(); i++) {\n octreeLeafPoints->InsertNextPoint (cloud.points[i].x, cloud.points[i].y, cloud.points[i].z);\n }\n points_poly = (vtkPolyData*)createDataSetFromVTKPoints(octreeLeafPoints);\n\n vtkSmartPointer<vtkActor> pointsActor = vtkSmartPointer<vtkActor>::New ();\n\n vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New ();\n mapper->SetInput (points_poly);\n pointsActor->SetMapper (mapper);\n\n pointsActor->GetProperty ()->SetColor (1.0, 0.0, 0.0);\n pointsActor->GetProperty ()->SetPointSize (4);\n coll->AddItem (pointsActor);\n\n}\n\nvoid\nprintHelp (int argc, char **argv)\n{\n std::cout << \"Syntax is \" << argv[0] << \" <file_name.pcd> <octree resolution> \\n\";\n std::cout << \"Example: .\/octree_viewer ..\/..\/test\/bunny.pcd 0.02 \\n\";\n\n exit(1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ MAIN\n\/* ---[ *\/\nint\n main (int argc, char** argv)\n{\n\n if (argc!=3) {\n printHelp(argc, argv);\n }\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);\n pcl::io::loadPCDFile (argv[1], *cloud);\n\n vtkSmartPointer<vtkActorCollection> coll = vtkActorCollection::New ();\n\n vtkRenderer* ren = vtkRenderer::New ();\n\n\n\n \/\/ create octree from pointcloud\n pcl::octree::OctreePointCloud<pcl::PointXYZ> octree (atof (argv[2]));\n octree.setInputCloud (cloud);\n octree.addPointsFromInputCloud ();\n\n \/\/ get vector of voxel centers from octree\n double voxelSideLen;\n std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> > voxelCenters;\n octree.getOccupiedVoxelCenters (voxelCenters);\n voxelSideLen = sqrt (octree.getVoxelSquaredSideLen ());\n\n \/\/ delete octree\n octree.deleteTree();\n\n \/\/ generate voxel boxes\n GetOctreeActors ( voxelCenters, voxelSideLen, coll);\n\n \/\/ visualize point input\n GetPointActors ( *cloud, coll);\n\n vtkActor* a;\n coll->InitTraversal ();\n a = coll->GetNextActor ();\n while(a!=0)\n {\n ren->AddActor (a);\n a = coll->GetNextActor ();\n }\n\n \/\/ Create Renderer and Interractor\n ren->SetBackground (1.0, 1.0, 1.0);\n\n vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New ();\n vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New ();\n win->AddRenderer (ren);\n\n iren->SetRenderWindow (win);\n iren->Start ();\n}\n<commit_msg>no window is opened in octree_viewer on Windows<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2010, Willow Garage, Inc.\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 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 * \\author Nico Blodow (blodow@cs.tum.edu), Julius Kammerl (julius@kammerl.de)\n * *\/\n\n#include \"pcl\/octree\/octree.h\"\n#include <pcl\/visualization\/pcl_visualizer.h>\n#include <pcl\/io\/pcd_io.h>\n#include <iostream>\n\n#include <vtkCubeSource.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create a vtkSmartPointer object containing a cube\nvtkSmartPointer<vtkPolyData>\nGetCuboid (double minX, double maxX, double minY, double maxY, double minZ, double maxZ)\n{\n vtkSmartPointer < vtkCubeSource > cube = vtkSmartPointer<vtkCubeSource>::New ();\n cube->SetBounds (minX, maxX, minY, maxY, minZ, maxZ);\n return cube->GetOutput ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create vtkActorCollection of vtkSmartPointers describing octree cubes\nvoid\nGetOctreeActors (std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> >& voxelCenters, double voxelSideLen, vtkSmartPointer<vtkActorCollection> coll)\n{\n\n vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New ();\n\n size_t i;\n double s = voxelSideLen\/2.0;\n\n for (i = 0; i < voxelCenters.size (); i++)\n {\n\n double x = voxelCenters[i].x;\n double y = voxelCenters[i].y;\n double z = voxelCenters[i].z;\n\n treeWireframe->AddInput (GetCuboid (x - s, x + s, y - s, y + s, z - s, z + s));\n }\n\n vtkSmartPointer < vtkActor > treeActor = vtkSmartPointer<vtkActor>::New ();\n\n vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New ();\n mapper->SetInput (treeWireframe->GetOutput ());\n treeActor->SetMapper (mapper);\n\n treeActor->GetProperty ()->SetRepresentationToWireframe ();\n treeActor->GetProperty ()->SetColor (0.0, 0.0, 1.0);\n treeActor->GetProperty ()->SetLineWidth (2);\n coll->AddItem (treeActor);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create a vtkPolyData object from a set of vtkPoints\nvtkDataSet*\n createDataSetFromVTKPoints (vtkPoints *points)\n{\n vtkCellArray *verts = vtkCellArray::New ();\n vtkPolyData *data = vtkPolyData::New ();\n \/\/ Iterate through the points\n for (vtkIdType i = 0; i < points->GetNumberOfPoints (); i++)\n verts->InsertNextCell ((vtkIdType)1, &i);\n data->SetPoints (points);\n data->SetVerts (verts);\n return data;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create vtkActorCollection of vtkSmartPointers describing input points\nvoid\n GetPointActors (pcl::PointCloud<pcl::PointXYZ>& cloud, vtkSmartPointer<vtkActorCollection> coll)\n{\n vtkPolyData* points_poly;\n\n size_t i;\n\n vtkPoints *octreeLeafPoints = vtkPoints::New ();\n\n \/\/ add all points from octree to vtkPoint object\n for (i=0; i< cloud.points.size(); i++) {\n octreeLeafPoints->InsertNextPoint (cloud.points[i].x, cloud.points[i].y, cloud.points[i].z);\n }\n points_poly = (vtkPolyData*)createDataSetFromVTKPoints(octreeLeafPoints);\n\n vtkSmartPointer<vtkActor> pointsActor = vtkSmartPointer<vtkActor>::New ();\n\n vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New ();\n mapper->SetInput (points_poly);\n pointsActor->SetMapper (mapper);\n\n pointsActor->GetProperty ()->SetColor (1.0, 0.0, 0.0);\n pointsActor->GetProperty ()->SetPointSize (4);\n coll->AddItem (pointsActor);\n\n}\n\nvoid\nprintHelp (int argc, char **argv)\n{\n std::cout << \"Syntax is \" << argv[0] << \" <file_name.pcd> <octree resolution> \\n\";\n std::cout << \"Example: .\/octree_viewer ..\/..\/test\/bunny.pcd 0.02 \\n\";\n\n exit(1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ MAIN\n\/* ---[ *\/\nint\n main (int argc, char** argv)\n{\n\n if (argc!=3) {\n printHelp(argc, argv);\n }\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);\n pcl::io::loadPCDFile (argv[1], *cloud);\n\n vtkSmartPointer<vtkActorCollection> coll = vtkActorCollection::New ();\n\n vtkRenderer* ren = vtkRenderer::New ();\n\n\n\n \/\/ create octree from pointcloud\n pcl::octree::OctreePointCloud<pcl::PointXYZ> octree (atof (argv[2]));\n octree.setInputCloud (cloud);\n octree.addPointsFromInputCloud ();\n\n \/\/ get vector of voxel centers from octree\n double voxelSideLen;\n std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> > voxelCenters;\n octree.getOccupiedVoxelCenters (voxelCenters);\n voxelSideLen = sqrt (octree.getVoxelSquaredSideLen ());\n\n \/\/ delete octree\n octree.deleteTree();\n\n \/\/ generate voxel boxes\n GetOctreeActors ( voxelCenters, voxelSideLen, coll);\n\n \/\/ visualize point input\n GetPointActors ( *cloud, coll);\n\n vtkActor* a;\n coll->InitTraversal ();\n a = coll->GetNextActor ();\n while(a!=0)\n {\n ren->AddActor (a);\n a = coll->GetNextActor ();\n }\n\n \/\/ Create Renderer and Interractor\n ren->SetBackground (1.0, 1.0, 1.0);\n\n vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New ();\n vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New ();\n win->AddRenderer (ren);\n\n iren->SetRenderWindow (win);\n win->Render ();\n iren->Start ();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * variable.cpp - implementation of the dynamically derived value container compare.\n * Copyright (C) 2001, Ron Steinke\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Contact: Joseph Zupko\n * jaz147@psu.edu\n *\n * 189 Reese St.\n * Old Forge, PA 18518\n *\/\n \n#include <string>\n#include <varconf\/dyncmp.h>\n\nnamespace varconf {\nnamespace dynvar {\n\nCompare& Compare::operator=( const Compare& c)\n{\n VarBase::operator=(c);\n m_v1 = c.m_v1;\n m_v2 = c.m_v2;\n}\n\nvoid Compare::set_val()\n{\n if(m_v1.is_bool() && m_v2.is_bool())\n VarBase::operator=(bool_cmp(bool(m_v1), bool(m_v2)));\n else if(m_v1.is_int() && m_v2.is_int())\n VarBase::operator=(int_cmp(int(m_v1), int(m_v2)));\n else if(m_v1.is_double() && m_v2.is_double())\n VarBase::operator=(double_cmp(double(m_v1), double(m_v2)));\n else if(m_v1.is_string() && m_v2.is_string()) {\n std::string s1 = std::string(m_v1), s2 = std::string(m_v2);\n VarBase::operator=(string_cmp(s1, s2));\n }\n else\n VarBase::operator=(VarBase()); \/\/ Set it invalid\n}\n\n}} \/\/ namespace varconf::dynvar\n<commit_msg>BUGFIX Tsk tsk. Added a missing return statement to this piece of ancient code. Probably unused anyway but hey.<commit_after>\/*\n * variable.cpp - implementation of the dynamically derived value container compare.\n * Copyright (C) 2001, Ron Steinke\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Contact: Joseph Zupko\n * jaz147@psu.edu\n *\n * 189 Reese St.\n * Old Forge, PA 18518\n *\/\n \n#include <string>\n#include <varconf\/dyncmp.h>\n\nnamespace varconf {\nnamespace dynvar {\n\nCompare& Compare::operator=( const Compare& c)\n{\n VarBase::operator=(c);\n m_v1 = c.m_v1;\n m_v2 = c.m_v2;\n return *this;\n}\n\nvoid Compare::set_val()\n{\n if(m_v1.is_bool() && m_v2.is_bool())\n VarBase::operator=(bool_cmp(bool(m_v1), bool(m_v2)));\n else if(m_v1.is_int() && m_v2.is_int())\n VarBase::operator=(int_cmp(int(m_v1), int(m_v2)));\n else if(m_v1.is_double() && m_v2.is_double())\n VarBase::operator=(double_cmp(double(m_v1), double(m_v2)));\n else if(m_v1.is_string() && m_v2.is_string()) {\n std::string s1 = std::string(m_v1), s2 = std::string(m_v2);\n VarBase::operator=(string_cmp(s1, s2));\n }\n else\n VarBase::operator=(VarBase()); \/\/ Set it invalid\n}\n\n}} \/\/ namespace varconf::dynvar\n<|endoftext|>"} {"text":"<commit_before><commit_msg>SessionManagerClient::open need not be exported<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef UPPER_LOWER_CASE_CONVERTER\n#define UPPER_LOWER_CASE_CONVERTER\n\n#include \"ConversionInterface.hpp\"\n\nnamespace protobuf_decoder\n{\n\nclass UpperLowerCaseConverter : public ConversionInterface\n{\npublic:\n\n virtual std::string encode(const std::string& iDecodedString);\n\n virtual std::string decode(const std::string& iEncodedString);\n\n virtual void setEncodeAlgorithm(const std::string& iAlgoName);\n\n virtual void setMessagePath(const std::string& iMessagePath);\n\n};\n\n}\n\n\n#endif \/\/ UPPER_LOWER_CASE_CONVERTER\n<commit_msg>Delete UpperLowerCaseConverter.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"control.h\"\n\nvoid switch_allele(char* str)\n{\n\tswitch(*str)\n\t{\n\t\tcase 'A':\n\t\t\t*str = 'T';\n\t\t\tbreak;\n\t\tcase 'T':\n\t\t\t*str = 'A';\n\t\t\tbreak;\n\t\tcase 'C':\n\t\t\t*str = 'G';\n\t\t\tbreak;\n\t\tcase 'G':\n\t\t\t*str = 'C';\n\t\t\tbreak;\n\t\t\/*case '1':\n\t\t\t*str = '2';\n\t\t\tbreak;\n\t\tcase '2':\n\t\t\t*str = '1';\n\t\t\tbreak;*\/\t\t\t\n\t}\n}\n\nvoid frequency(int total_people, int** chr, int num_of_chrs)\n{\/\/http:\/\/pngu.mgh.harvard.edu\/~purcell\/plink\/binary.shtml BED file format\n\tchar pattern[CHAR_MAX_LENGTH+1]=\"\";char pattern1[CHAR_MAX_LENGTH+1]=\"\";\n\t\n\tifstream input_bim, input_fre;\n\tofstream output_fre;\n\tinput_bim.open(BIM,ios::in);\n\toutput_fre.open(\"fre_result.freq\",ios::out);\n\t\n\tbool external_freq_or_not;\n\tstreamoff position;\n\t\n\textern char Freq_ext_result[150];\n\tif(strcmp(Freq_ext_result,\"0\") == 0) \n\t{\n\t\t\/\/cout<<\"--\"<<Freq_ext_result<<\"--\"<<endl;getchar();\n\t\texternal_freq_or_not = false;\n\t}\n\telse \n\t{\n\t\t\/\/cout<<\"==\"<<Freq_ext_result<<\"==\"<<endl;getchar();\n\t\texternal_freq_or_not = true;\n\t\tinput_fre.open(Freq_ext_result,ios::in);\t\t\n\t\tinput_fre.getline(pattern, CHAR_MAX_LENGTH);\/\/first line is useless\n\t\tposition = input_fre.tellg();\n\t}\n\t\/\/===============================================set propriate pre-fetch array size\n\tint remain_people = total_people%4;\n\tint boundary;\/\/for last byte\n\tint const_need_per_marker;\/\/byte\n\t\tif(remain_people != 0) \n\t\t{\n\t\t\tconst_need_per_marker = total_people\/4 + 1;\n\t\t\tboundary = remain_people*2;\n\t\t}\n\t\telse\n\t\t{\t\t\n\t\t\tconst_need_per_marker = total_people\/4;\n\t\t\tboundary = 8;\n\t\t}\n\t\/\/===============================================calculate total markers\n\tint total_marker = 0;\n\tFILE* input_bed = fopen(BED,\"r\");\n\tbitset<8> a_byte;\/\/represent 4 people\n\tfgets(pattern, 3+1, input_bed);\/\/first 3 bytes is for special use\n\n\tfor(int i=0;i<num_of_chrs;i++) \n\t{\n\t\tchar buffer[50];\n\t\tsprintf (buffer, \"metadata%d.ped\", chr[i][0]);\n\t\tofstream output_ped;\n\t\toutput_ped.open(buffer,ios::out);\n\t\t\n\t\tint total_marker_for_chr = chr[i][1];\n\t\ttotal_marker += chr[i][1];\n\t\t\/\/cout<<num_of_chrs;getchar();\n\t\t\/\/cout<<total_marker_for_chr;getchar();\n\t\t\/\/===============================================\n\t\tint num_pre_fetch_marker = 1;\/\/decide_prefetch_chrs_once(chr,num_of_chrs,const_need_per_marker);\/\/一次處理幾個marker\n\t\tint pre_fetch_size = num_pre_fetch_marker*const_need_per_marker;\n\t\twhile(total_marker_for_chr)\/\/共幾個marker\n\t\t{\n\t\t\tmemset(pattern,0,sizeof(pattern));\n\t\t\tfread((void*)pattern, 1, pre_fetch_size, input_bed);\n\t\t\tfor(int h=0;h<num_pre_fetch_marker;h++)\/\/依序處理marker \n\t\t\t{\t\t\t\n\t\t\t\tchar* _tmp;\n\t\t\t\tstring string1;\n\t\t\t\tchar* _tmp_A[2];\n\t\t\t\t{\n\t\t\t\t\tinput_bim.getline(pattern1, CHAR_MAX_LENGTH);\n\t\t\t\t\t\/\/if(!strtok(pattern,\" \t,\")) break;\n\t\t\t\t\t_tmp = strtok(pattern1, \" \t\");\n\t\t\t\t\t\/\/cout<<_tmp<<\"==\"<<strlen(_tmp)<<endl;\n\t\t\t\t\t_tmp = strtok(NULL, \" \t\");\n\t\t\t\t\t\/\/cout<<_tmp<<\"==\"<<strlen(_tmp)<<endl;\n\t\t\t\t\t\/\/allele_count[3] = atoi(_tmp);\/\/NAME\n\t\t\t\t\tstring1 = _tmp; \n\t\t\t\t\t\/\/cout<<string1;getchar();\n\t\t\t\t\t\/\/cout<<atoi(_tmp)<<\" \"<<endl;\n\t\t\t\t\t_tmp = strtok(NULL, \" \t\");\n\t\t\t\t\t_tmp = strtok(NULL, \" \t\");\n\t\t\t\t\t\/\/cout<<_tmp;getchar();\n\t\t\t\t\t_tmp_A[0] = strtok(NULL, \" \t\");\n\t\t\t\t\t_tmp_A[1] = strtok(NULL, \" \t\");\n\t\t\t\t\t\/\/cout<<_tmp_A[0]<<\" \"<<endl;cout<<_tmp_A[1]<<\" \"<<endl;getchar();\n\t\t\t\t}\n\t\t\t\t\/\/===================\n\t\t\t\tint start = const_need_per_marker*h;\n\t\t\t\tint end = start + const_need_per_marker -1;\n\t\t\t\tdouble allele_count[4]={0};\/\/two alleles: (A,T,C,G,1,2), missing, NAME\n\t\t\t\t{\n\t\t\t\t\t\/\/leave last byte to another handle\n\t\t\t\t\tfor(int k=start;k<end;k++)\n\t\t\t\t\t{\n\t\t\t\t\t\ta_byte = pattern[k];\n\t\t\t\t\t\tfor(int ii=0;ii<8;ii+=2) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(a_byte[ii]==1 && a_byte[ii+1]==0) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tallele_count[2]+=2;\n\t\t\t\t\t\t\t\toutput_ped<<\"0 0 \";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse for(int jj=ii;jj<ii+2;jj++) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tallele_count[a_byte[jj]]++;\n\t\t\t\t\t\t\t\toutput_ped<<_tmp_A[a_byte[jj]]<<\" \";\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\t\/\/for last byte\n\t\t\t\t\ta_byte = pattern[end];\n\t\t\t\t\tfor(int ii=0;ii<boundary;ii+=2) \n\t\t\t\t\t{\n\t\t\t\t\t\tif(a_byte[ii]==1 && a_byte[ii+1]==0) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tallele_count[2]+=2;\n\t\t\t\t\t\t\toutput_ped<<\"0 0 \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse for(int jj=ii;jj<ii+2;jj++) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tallele_count[a_byte[jj]]++;\n\t\t\t\t\t\t\toutput_ped<<_tmp_A[a_byte[jj]]<<\" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\toutput_ped<<endl;\/\/end of a marker\n\t\t\t\t}\n\t\t\t\t\/\/cout<<allele_count[0]<<\" \"<<allele_count[1]<<\" \"<<allele_count[2]<<endl;\n\t\t\t\tif(allele_count[0]+allele_count[1]+allele_count[2] != total_people*2) cout<<\"some errors occur!!\"<<endl;\n\t\t\t\t\n\t\t\t\tint allele_sample_space = total_people*2-allele_count[2];\n\t\t\t\tif(allele_sample_space == 0)\n\t\t\t\t{\n\t\t\t\t\tallele_count[0] = allele_count[1] = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tallele_count[0] = allele_count[0]\/allele_sample_space;\n\t\t\t\t\tallele_count[1] = 1-allele_count[0];\n\t\t\t\t}\n\t\t\t\t\/\/===================\n\t\t\t\tif(external_freq_or_not)\/\/use external freq file or not\n\t\t\t\t{\n\t\t\t\t\tchar* tmp;\n\t\t\t\t\tstring string2;\n\t\t\t\t\tchar* tmp_A[2];\n\t\t\t\t\tinput_fre.clear();\n\t\t\t\t\tinput_fre.seekg(position);\n\t\t\t\t\tdo{\n\t\t\t\t\t\tinput_fre.getline(pattern, CHAR_MAX_LENGTH);\n\t\t\t\t\t\ttmp = strtok(pattern, \" \t\");\n\t\t\t\t\t\tif(!tmp) break;\n\t\t\t\t\t\ttmp = strtok(NULL, \" \t\");\n\t\t\t\t\t\tstring2 = tmp;\n\t\t\t\t\t\t\/\/cout<<string2;getchar();\n\t\t\t\t\t}\n\t\t\t\t\twhile(string1.compare(string2)!=0);\n\t\t\t\t\tif(string1.compare(string2)==0)\n\t\t\t\t\t{\n\t\t\t\t\t\tposition = input_fre.tellg();\n\t\t\t\t\t\t\/\/cout<<\"hit!!!!!!!!!!!!!!!!!!!!!\"<<endl;getchar();\n\t\t\t\t\t\ttmp_A[0] = strtok(NULL, \" \t\");\n\t\t\t\t\t\ttmp_A[1] = strtok(NULL, \" \t\");\n\t\t\t\t\t\t\n\t\t\t\t\t\tint match_valid;\n\t\t\t\t\t\tif(strcmp(_tmp_A[0],tmp_A[0]) == 0 && strcmp(_tmp_A[1],tmp_A[1]) == 0) match_valid = 1;\/\/ok\n\t\t\t\t\t\telse if(strcmp(_tmp_A[0],tmp_A[1]) == 0 && strcmp(_tmp_A[1],tmp_A[0]) == 0) match_valid = 2;\/\/ok\n\t\t\t\t\t\telse \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tswitch_allele(tmp_A[0]);\n\t\t\t\t\t\t\tswitch_allele(tmp_A[1]);\n\t\t\t\t\t\t\tmatch_valid = 0;\n\t\t\t\t\t\t\tif(strcmp(_tmp_A[0],tmp_A[0]) == 0 && strcmp(_tmp_A[1],tmp_A[1]) == 0) match_valid = 1;\/\/ok\n\t\t\t\t\t\t\telse if(strcmp(_tmp_A[0],tmp_A[1]) == 0 && strcmp(_tmp_A[1],tmp_A[0]) == 0) match_valid = 2;\/\/ok\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(match_valid)\/\/marker is matched in ASN.freq\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttmp = strtok(NULL, \" \t\");\/\/MAF\n\t\t\t\t\t\t\tdouble MAF = atof(tmp);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdouble n1 = allele_sample_space\/2;\/\/n1\n\t\t\t\t\t\t\ttmp = strtok(NULL, \" \t\");\n\t\t\t\t\t\t\tdouble n2 = atoi(tmp);\/\/n2\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(match_valid == 1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tallele_count[0] = allele_count[0]*(n1\/(n1+n2)) + MAF*(n2\/(n1+n2));\n\t\t\t\t\t\t\t\tallele_count[1] = allele_count[1]*(n1\/(n1+n2)) + (1-MAF)*(n2\/(n1+n2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if(match_valid == 2)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tallele_count[0] = allele_count[0]*(n1\/(n1+n2)) + (1-MAF)*(n2\/(n1+n2));\n\t\t\t\t\t\t\t\tallele_count[1] = allele_count[1]*(n1\/(n1+n2)) + (MAF)*(n2\/(n1+n2));\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/frequency.snp\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {}\/\/no matched marker in ASN.freq\n\t\t\t\t}\n\t\t\t\t\/\/===================\n\t\t\t\t\/\/output_fre<<\"M \"<<allele_count[3]<<endl;\n\t\t\t\toutput_fre<<\"M \"<<string1<<endl;\n\t\t\t\t\/\/cout <<\"M \"<<string1<<endl;\n\t\t\t\tfor(int i=0;i<2;i++)\n\t\t\t\t{\n\t\t\t\t\tif(allele_count[i]>0) \n\t\t\t\t\t{\n\t\t\t\t\t\toutput_fre<<\"A \"<<(_tmp_A[i])<<\" \"<<allele_count[i]<<endl;\n\t\t\t\t\t\t\/\/cout <<\"A \"<<(_tmp_A[i])<<\" \"<<allele_count[i]<<endl;\n\t\t\t\t\t}\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/cout<<total_marker_for_chr<<endl;getchar();\n\t\t\ttotal_marker_for_chr -= num_pre_fetch_marker;\n\t\t}\n\t\toutput_ped.close();\n\t}\n\t\/\/cout<<total_marker<<endl;getchar();\/\/1000,4737983\n\tif(external_freq_or_not) input_fre.close();\t\n\t\/\/===============================================\n\tfclose(input_bed);\n\tinput_bim.close();\n\toutput_fre.close();\n}<commit_msg>modify frequency calculation formula<commit_after>#include \"control.h\"\n\nvoid switch_allele(char* str)\n{\n\tswitch(*str)\n\t{\n\t\tcase 'A':\n\t\t\t*str = 'T';\n\t\t\tbreak;\n\t\tcase 'T':\n\t\t\t*str = 'A';\n\t\t\tbreak;\n\t\tcase 'C':\n\t\t\t*str = 'G';\n\t\t\tbreak;\n\t\tcase 'G':\n\t\t\t*str = 'C';\n\t\t\tbreak;\n\t\t\/*case '1':\n\t\t\t*str = '2';\n\t\t\tbreak;\n\t\tcase '2':\n\t\t\t*str = '1';\n\t\t\tbreak;*\/\t\t\t\n\t}\n}\n\nvoid frequency(int total_people, int** chr, int num_of_chrs)\n{\/\/http:\/\/pngu.mgh.harvard.edu\/~purcell\/plink\/binary.shtml BED file format\n\tchar pattern[CHAR_MAX_LENGTH+1]=\"\";char pattern1[CHAR_MAX_LENGTH+1]=\"\";\n\t\n\tifstream input_bim, input_fre;\n\tofstream output_fre;\n\tinput_bim.open(BIM,ios::in);\n\toutput_fre.open(\"fre_result.freq\",ios::out);\n\t\n\tbool external_freq_or_not;\n\tstreamoff position;\n\t\n\textern char Freq_ext_result[150];\n\tif(strcmp(Freq_ext_result,\"0\") == 0) \n\t{\n\t\t\/\/cout<<\"--\"<<Freq_ext_result<<\"--\"<<endl;getchar();\n\t\texternal_freq_or_not = false;\n\t}\n\telse \n\t{\n\t\t\/\/cout<<\"==\"<<Freq_ext_result<<\"==\"<<endl;getchar();\n\t\texternal_freq_or_not = true;\n\t\tinput_fre.open(Freq_ext_result,ios::in);\t\t\n\t\tinput_fre.getline(pattern, CHAR_MAX_LENGTH);\/\/first line is useless\n\t\tposition = input_fre.tellg();\n\t}\n\t\/\/===============================================set propriate pre-fetch array size\n\tint remain_people = total_people%4;\n\tint boundary;\/\/for last byte\n\tint const_need_per_marker;\/\/byte\n\t\tif(remain_people != 0) \n\t\t{\n\t\t\tconst_need_per_marker = total_people\/4 + 1;\n\t\t\tboundary = remain_people*2;\n\t\t}\n\t\telse\n\t\t{\t\t\n\t\t\tconst_need_per_marker = total_people\/4;\n\t\t\tboundary = 8;\n\t\t}\n\t\/\/===============================================calculate total markers\n\tint total_marker = 0;\n\tFILE* input_bed = fopen(BED,\"r\");\n\tbitset<8> a_byte;\/\/represent 4 people\n\tfgets(pattern, 3+1, input_bed);\/\/first 3 bytes is for special use\n\n\tfor(int i=0;i<num_of_chrs;i++) \n\t{\n\t\tchar buffer[50];\n\t\tsprintf (buffer, \"metadata%d.ped\", chr[i][0]);\n\t\tofstream output_ped;\n\t\toutput_ped.open(buffer,ios::out);\n\t\t\n\t\tint total_marker_for_chr = chr[i][1];\n\t\ttotal_marker += chr[i][1];\n\t\t\/\/cout<<num_of_chrs;getchar();\n\t\t\/\/cout<<total_marker_for_chr;getchar();\n\t\t\/\/===============================================\n\t\tint num_pre_fetch_marker = 1;\/\/decide_prefetch_chrs_once(chr,num_of_chrs,const_need_per_marker);\/\/一次處理幾個marker\n\t\tint pre_fetch_size = num_pre_fetch_marker*const_need_per_marker;\n\t\twhile(total_marker_for_chr)\/\/共幾個marker\n\t\t{\n\t\t\tmemset(pattern,0,sizeof(pattern));\n\t\t\tfread((void*)pattern, 1, pre_fetch_size, input_bed);\n\t\t\tfor(int h=0;h<num_pre_fetch_marker;h++)\/\/依序處理marker \n\t\t\t{\t\t\t\n\t\t\t\tchar* _tmp;\n\t\t\t\tstring string1;\n\t\t\t\tchar* _tmp_A[2];\n\t\t\t\t{\n\t\t\t\t\tinput_bim.getline(pattern1, CHAR_MAX_LENGTH);\n\t\t\t\t\t\/\/if(!strtok(pattern,\" \t,\")) break;\n\t\t\t\t\t_tmp = strtok(pattern1, \" \t\");\n\t\t\t\t\t\/\/cout<<_tmp<<\"==\"<<strlen(_tmp)<<endl;\n\t\t\t\t\t_tmp = strtok(NULL, \" \t\");\n\t\t\t\t\t\/\/cout<<_tmp<<\"==\"<<strlen(_tmp)<<endl;\n\t\t\t\t\t\/\/allele_count[3] = atoi(_tmp);\/\/NAME\n\t\t\t\t\tstring1 = _tmp; \n\t\t\t\t\t\/\/cout<<string1;getchar();\n\t\t\t\t\t\/\/cout<<atoi(_tmp)<<\" \"<<endl;\n\t\t\t\t\t_tmp = strtok(NULL, \" \t\");\n\t\t\t\t\t_tmp = strtok(NULL, \" \t\");\n\t\t\t\t\t\/\/cout<<_tmp;getchar();\n\t\t\t\t\t_tmp_A[0] = strtok(NULL, \" \t\");\n\t\t\t\t\t_tmp_A[1] = strtok(NULL, \" \t\");\n\t\t\t\t\t\/\/cout<<_tmp_A[0]<<\" \"<<endl;cout<<_tmp_A[1]<<\" \"<<endl;getchar();\n\t\t\t\t}\n\t\t\t\t\/\/===================\n\t\t\t\tint start = const_need_per_marker*h;\n\t\t\t\tint end = start + const_need_per_marker -1;\n\t\t\t\tdouble allele_count[4]={0};\/\/two alleles: (A,T,C,G,1,2), missing, NAME\n\t\t\t\t{\n\t\t\t\t\t\/\/leave last byte to another handle\n\t\t\t\t\tfor(int k=start;k<end;k++)\n\t\t\t\t\t{\n\t\t\t\t\t\ta_byte = pattern[k];\n\t\t\t\t\t\tfor(int ii=0;ii<8;ii+=2) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(a_byte[ii]==1 && a_byte[ii+1]==0) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tallele_count[2]+=2;\n\t\t\t\t\t\t\t\toutput_ped<<\"0 0 \";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse for(int jj=ii;jj<ii+2;jj++) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tallele_count[a_byte[jj]]++;\n\t\t\t\t\t\t\t\toutput_ped<<_tmp_A[a_byte[jj]]<<\" \";\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\t\/\/for last byte\n\t\t\t\t\ta_byte = pattern[end];\n\t\t\t\t\tfor(int ii=0;ii<boundary;ii+=2) \n\t\t\t\t\t{\n\t\t\t\t\t\tif(a_byte[ii]==1 && a_byte[ii+1]==0) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tallele_count[2]+=2;\n\t\t\t\t\t\t\toutput_ped<<\"0 0 \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse for(int jj=ii;jj<ii+2;jj++) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tallele_count[a_byte[jj]]++;\n\t\t\t\t\t\t\toutput_ped<<_tmp_A[a_byte[jj]]<<\" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\toutput_ped<<endl;\/\/end of a marker\n\t\t\t\t}\n\t\t\t\t\/\/cout<<allele_count[0]<<\" \"<<allele_count[1]<<\" \"<<allele_count[2]<<endl;\n\t\t\t\tif(allele_count[0]+allele_count[1]+allele_count[2] != total_people*2) cout<<\"some errors occur!!\"<<endl;\n\t\t\t\t\n\t\t\t\tint allele_sample_space = total_people*2-allele_count[2];\n\t\t\t\tif(allele_sample_space == 0)\n\t\t\t\t{\n\t\t\t\t\tallele_count[0] = allele_count[1] = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tallele_count[0] = allele_count[0]\/allele_sample_space;\n\t\t\t\t\tallele_count[1] = 1-allele_count[0];\n\t\t\t\t}\n\t\t\t\t\/\/===================\n\t\t\t\tif(external_freq_or_not)\/\/use external freq file or not\n\t\t\t\t{\n\t\t\t\t\tchar* tmp;\n\t\t\t\t\tstring string2;\n\t\t\t\t\tchar* tmp_A[2];\n\t\t\t\t\tinput_fre.clear();\n\t\t\t\t\tinput_fre.seekg(position);\n\t\t\t\t\tdo{\n\t\t\t\t\t\tinput_fre.getline(pattern, CHAR_MAX_LENGTH);\n\t\t\t\t\t\ttmp = strtok(pattern, \" \t\");\n\t\t\t\t\t\tif(!tmp) break;\n\t\t\t\t\t\ttmp = strtok(NULL, \" \t\");\n\t\t\t\t\t\tstring2 = tmp;\n\t\t\t\t\t\t\/\/cout<<string2;getchar();\n\t\t\t\t\t}\n\t\t\t\t\twhile(string1.compare(string2)!=0);\n\t\t\t\t\tif(string1.compare(string2)==0)\n\t\t\t\t\t{\n\t\t\t\t\t\tposition = input_fre.tellg();\n\t\t\t\t\t\t\/\/cout<<\"hit!!!!!!!!!!!!!!!!!!!!!\"<<endl;getchar();\n\t\t\t\t\t\ttmp_A[0] = strtok(NULL, \" \t\");\n\t\t\t\t\t\ttmp_A[1] = strtok(NULL, \" \t\");\n\t\t\t\t\t\t\n\t\t\t\t\t\tint match_valid;\n\t\t\t\t\t\tif(strcmp(_tmp_A[0],tmp_A[0]) == 0 && strcmp(_tmp_A[1],tmp_A[1]) == 0) match_valid = 1;\/\/ok\n\t\t\t\t\t\telse if(strcmp(_tmp_A[0],tmp_A[1]) == 0 && strcmp(_tmp_A[1],tmp_A[0]) == 0) match_valid = 2;\/\/ok\n\t\t\t\t\t\telse \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tswitch_allele(tmp_A[0]);\n\t\t\t\t\t\t\tswitch_allele(tmp_A[1]);\n\t\t\t\t\t\t\tmatch_valid = 0;\n\t\t\t\t\t\t\tif(strcmp(_tmp_A[0],tmp_A[0]) == 0 && strcmp(_tmp_A[1],tmp_A[1]) == 0) match_valid = 1;\/\/ok\n\t\t\t\t\t\t\telse if(strcmp(_tmp_A[0],tmp_A[1]) == 0 && strcmp(_tmp_A[1],tmp_A[0]) == 0) match_valid = 2;\/\/ok\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(match_valid)\/\/marker is matched in ASN.freq\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttmp = strtok(NULL, \" \t\");\/\/MAF\n\t\t\t\t\t\t\tdouble MAF = atof(tmp);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdouble n1 = allele_sample_space\/2;\/\/n1\n\t\t\t\t\t\t\ttmp = strtok(NULL, \" \t\");\n\t\t\t\t\t\t\tdouble n2 = atoi(tmp);\/\/n2\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(match_valid == 1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tallele_count[0] = allele_count[0]*(n1\/(n1+n2)) + MAF*(n2\/(n1+n2));\n\t\t\t\t\t\t\t\tallele_count[1] = 1=allele_count[0];\/\/allele_count[1]*(n1\/(n1+n2)) + (1-MAF)*(n2\/(n1+n2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if(match_valid == 2)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tallele_count[0] = allele_count[0]*(n1\/(n1+n2)) + (1-MAF)*(n2\/(n1+n2));\n\t\t\t\t\t\t\t\tallele_count[1] = 1=allele_count[0];\/\/allele_count[1]*(n1\/(n1+n2)) + (MAF)*(n2\/(n1+n2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/frequency.snp\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {}\/\/no matched marker in ASN.freq\n\t\t\t\t}\n\t\t\t\t\/\/===================\n\t\t\t\t\/\/output_fre<<\"M \"<<allele_count[3]<<endl;\n\t\t\t\toutput_fre<<\"M \"<<string1<<endl;\n\t\t\t\t\/\/cout <<\"M \"<<string1<<endl;\n\t\t\t\tfor(int i=0;i<2;i++)\n\t\t\t\t{\n\t\t\t\t\tif(allele_count[i]>0) \n\t\t\t\t\t{\n\t\t\t\t\t\toutput_fre<<\"A \"<<(_tmp_A[i])<<\" \"<<allele_count[i]<<endl;\n\t\t\t\t\t\t\/\/cout <<\"A \"<<(_tmp_A[i])<<\" \"<<allele_count[i]<<endl;\n\t\t\t\t\t}\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/cout<<total_marker_for_chr<<endl;getchar();\n\t\t\ttotal_marker_for_chr -= num_pre_fetch_marker;\n\t\t}\n\t\toutput_ped.close();\n\t}\n\t\/\/cout<<total_marker<<endl;getchar();\/\/1000,4737983\n\tif(external_freq_or_not) input_fre.close();\t\n\t\/\/===============================================\n\tfclose(input_bed);\n\tinput_bim.close();\n\toutput_fre.close();\n}<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/common_runtime\/kernel_benchmark_testlib.h\"\n#include \"tensorflow\/core\/framework\/fake_input.h\"\n#include \"tensorflow\/core\/framework\/node_def_builder.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/graph\/node_builder.h\"\n#include \"tensorflow\/core\/kernels\/ops_testutil.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n#include \"tensorflow\/core\/platform\/test_benchmark.h\"\n\nnamespace tensorflow {\n\ntemplate <typename InputShape>\nstatic Graph* BroadcastTo(int size, InputShape input_shape) {\n Graph* g = new Graph(OpRegistry::Global());\n\n Tensor input(DT_FLOAT, input_shape(size));\n input.flat<float>() = input.flat<float>().setRandom();\n\n Tensor shape(DT_INT32, TensorShape({2}));\n shape.flat<int32>()(0) = size;\n shape.flat<int32>()(1) = size;\n\n Node* node;\n TF_CHECK_OK(NodeBuilder(g->NewName(\"n\"), \"BroadcastTo\")\n .Input(test::graph::Constant(g, input))\n .Input(test::graph::Constant(g, shape))\n .Attr(\"T\", DT_FLOAT)\n .Attr(\"Tidx\", DT_INT32)\n .Finalize(g, &node));\n return g;\n}\n\n#define BM_BroadcastTo_InnerDim(SIZE, type) \\\n static void BM_BroadcastTo_Inner##_##type##_##SIZE(int iters) { \\\n testing::UseRealTime(); \\\n testing::ItemsProcessed(static_cast<int64>(iters) * SIZE * SIZE); \\\n test::Benchmark(#type, BroadcastTo(SIZE, \\\n [](int size) { \\\n return TensorShape({size, 1}); \\\n })) \\\n .Run(iters); \\\n } \\\n BENCHMARK(BM_BroadcastTo_Inner##_##type##_##SIZE);\n\n#define BM_BroadcastTo_OuterDim(SIZE, type) \\\n static void BM_BroadcastTo_Outer##_##type##_##SIZE(int iters) { \\\n testing::UseRealTime(); \\\n testing::ItemsProcessed(static_cast<int64>(iters) * SIZE * SIZE); \\\n test::Benchmark(#type, BroadcastTo(SIZE, \\\n [](int size) { \\\n return TensorShape({1, size}); \\\n })) \\\n .Run(iters); \\\n } \\\n BENCHMARK(BM_BroadcastTo_Outer##_##type##_##SIZE);\n\nBM_BroadcastTo_InnerDim(64, cpu);\nBM_BroadcastTo_InnerDim(128, cpu);\nBM_BroadcastTo_InnerDim(256, cpu);\nBM_BroadcastTo_InnerDim(512, cpu);\nBM_BroadcastTo_InnerDim(1024, cpu);\n\nBM_BroadcastTo_OuterDim(64, cpu);\nBM_BroadcastTo_OuterDim(128, cpu);\nBM_BroadcastTo_OuterDim(256, cpu);\nBM_BroadcastTo_OuterDim(512, cpu);\nBM_BroadcastTo_OuterDim(1024, cpu);\n\n} \/\/ end namespace tensorflow\n<commit_msg>Add more benchmarks to BroadcastTo test<commit_after>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/common_runtime\/kernel_benchmark_testlib.h\"\n#include \"tensorflow\/core\/framework\/node_def_builder.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/graph\/node_builder.h\"\n#include \"tensorflow\/core\/kernels\/ops_testutil.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n#include \"tensorflow\/core\/platform\/test_benchmark.h\"\n\nnamespace tensorflow {\n\ntemplate <typename InputShape>\nstatic Graph* BroadcastTo(int dim0, int dim1, InputShape input_shape) {\n Graph* g = new Graph(OpRegistry::Global());\n\n Tensor input(DT_FLOAT, input_shape(dim0, dim1));\n input.flat<float>() = input.flat<float>().setRandom();\n\n Tensor shape(DT_INT32, TensorShape({2}));\n shape.flat<int32>()(0) = dim0;\n shape.flat<int32>()(1) = dim1;\n\n Node* node;\n TF_CHECK_OK(NodeBuilder(g->NewName(\"n\"), \"BroadcastTo\")\n .Input(test::graph::Constant(g, input))\n .Input(test::graph::Constant(g, shape))\n .Attr(\"T\", DT_FLOAT)\n .Attr(\"Tidx\", DT_INT32)\n .Finalize(g, &node));\n return g;\n}\n\n#define BM_BroadcastTo_InnerDim(DIM0, DIM1, type) \\\n static void BM_BroadcastTo_Inner##_##type##_##DIM0##_##DIM1(int iters) { \\\n testing::UseRealTime(); \\\n testing::ItemsProcessed(static_cast<int64>(iters) * DIM0 * DIM1); \\\n test::Benchmark(#type, BroadcastTo(DIM0, DIM1, \\\n [](int dim0, int dim1) { \\\n return TensorShape({dim0, 1}); \\\n })) \\\n .Run(iters); \\\n } \\\n BENCHMARK(BM_BroadcastTo_Inner##_##type##_##DIM0##_##DIM1);\n\n#define BM_BroadcastTo_OuterDim(DIM0, DIM1, type) \\\n static void BM_BroadcastTo_Outer##_##type##_##DIM0##_##DIM1(int iters) { \\\n testing::UseRealTime(); \\\n testing::ItemsProcessed(static_cast<int64>(iters) * DIM0 * DIM1); \\\n test::Benchmark(#type, BroadcastTo(DIM0, DIM1, \\\n [](int dim0, int dim1) { \\\n return TensorShape({1, dim1}); \\\n })) \\\n .Run(iters); \\\n } \\\n BENCHMARK(BM_BroadcastTo_Outer##_##type##_##DIM0##_##DIM1);\n\nBM_BroadcastTo_InnerDim(64, 64, cpu);\nBM_BroadcastTo_InnerDim(128, 128, cpu);\nBM_BroadcastTo_InnerDim(256, 256, cpu);\nBM_BroadcastTo_InnerDim(512, 512, cpu);\nBM_BroadcastTo_InnerDim(1024, 1024, cpu);\nBM_BroadcastTo_InnerDim(500, 20000, cpu);\n\nBM_BroadcastTo_OuterDim(64, 64, cpu);\nBM_BroadcastTo_OuterDim(128, 128, cpu);\nBM_BroadcastTo_OuterDim(256, 256, cpu);\nBM_BroadcastTo_OuterDim(512, 512, cpu);\nBM_BroadcastTo_OuterDim(1024, 1024, cpu);\nBM_BroadcastTo_OuterDim(500, 20000, cpu);\n\n} \/\/ end namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Project Vogue. 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 \"elang\/lir\/value.h\"\n\n#include \"base\/logging.h\"\n\nnamespace elang {\nnamespace lir {\n\nbool Value::is_memory_slot() const {\n return is_parameter() || is_argument() || is_stack_slot() || is_spill_slot();\n}\n\nValue Value::Argument(Value type, int data) {\n return Value(type.type, type.size, Kind::Argument, data);\n}\n\nbool Value::CanBeImmediate(int64_t value) {\n return value >= kMinimumImmediate && value <= kMaximumImmediate;\n}\n\nValue Value::False() {\n return Value(Type::Integer, ValueSize::Size8, Kind::Condition, 0);\n}\n\nValue Value::Float32Literal() {\n return Value(Float32Type(), Kind::Literal);\n}\n\nValue Value::Float64Literal() {\n return Value(Float64Type(), Kind::Literal);\n}\n\nValue Value::Float32Type() {\n return Value(Type::Float, ValueSize::Size32, Kind::Void, 0);\n}\n\nValue Value::Float64Type() {\n return Value(Type::Float, ValueSize::Size64, Kind::Void, 0);\n}\n\nValue Value::FrameSlot(Value type, int data) {\n return Value(type.type, type.size, Kind::FrameSlot, data);\n}\n\nValue Value::Immediate(ValueSize size, int data) {\n DCHECK(CanBeImmediate(data));\n return Value(Type::Integer, size, Kind::Immediate, data);\n}\n\nValue Value::Int16Type() {\n return Value(Type::Integer, ValueSize::Size16, Kind::Void, 0);\n}\n\nValue Value::Int32Type() {\n return Value(Type::Integer, ValueSize::Size32, Kind::Void, 0);\n}\n\nValue Value::Int64Type() {\n return Value(Type::Integer, ValueSize::Size64, Kind::Void, 0);\n}\n\nValue Value::Int8Type() {\n return Value(Type::Integer, ValueSize::Size8, Kind::Void, 0);\n}\n\nValue Value::Literal(Value type) {\n return Value(type, Kind::Literal);\n}\n\nValue Value::Parameter(Value type, int data) {\n return Value(type.type, type.size, Kind::Parameter, data);\n}\n\nValue Value::Register(Value type, int data) {\n return Value(type.type, type.size, Kind::VirtualRegister, data);\n}\n\nValue Value::SmallInt16(int data) {\n DCHECK_LT(static_cast<uint32_t>(data), 1u << 16);\n return Immediate(ValueSize::Size16, data);\n}\n\nValue Value::SmallInt32(int data) {\n return Immediate(ValueSize::Size32, data);\n}\n\nValue Value::SmallInt64(int data) {\n return Immediate(ValueSize::Size64, data);\n}\n\nValue Value::SmallInt8(int data) {\n DCHECK_LT(static_cast<uint32_t>(data), 1u << 8);\n return Immediate(ValueSize::Size8, data);\n}\n\nValue Value::SpillSlot(Value type, int data) {\n return Value(type.type, type.size, Kind::SpillSlot, data);\n}\n\nValue Value::StackSlot(Value type, int data) {\n return Value(type.type, type.size, Kind::StackSlot, data);\n}\n\nValue Value::True() {\n return Value(Type::Integer, ValueSize::Size8, Kind::Condition, 1);\n}\n\nbool Value::is_output() const {\n switch (kind) {\n case Kind::Argument:\n case Kind::Condition:\n case Kind::FrameSlot:\n case Kind::Parameter:\n case Kind::PhysicalRegister:\n case Kind::SpillSlot:\n case Kind::StackSlot:\n case Kind::VirtualRegister:\n return true;\n }\n return false;\n}\n\n} \/\/ namespace lir\n} \/\/ namespace elang\n\nnamespace std {\nsize_t hash<elang::lir::Value>::operator()(\n const elang::lir::Value& value) const {\n auto const p = reinterpret_cast<const uint32_t*>(&value);\n return std::hash<uint32_t>()(*p);\n}\n} \/\/ namespace std\n<commit_msg>elang\/lir: Make |Value::is_memory_slot()| to recognize |FrameSlot|.<commit_after>\/\/ Copyright 2015 Project Vogue. 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 \"elang\/lir\/value.h\"\n\n#include \"base\/logging.h\"\n\nnamespace elang {\nnamespace lir {\n\nbool Value::is_memory_slot() const {\n return is_parameter() || is_argument() || is_stack_slot() ||\n is_frame_slot() || is_spill_slot();\n}\n\nValue Value::Argument(Value type, int data) {\n return Value(type.type, type.size, Kind::Argument, data);\n}\n\nbool Value::CanBeImmediate(int64_t value) {\n return value >= kMinimumImmediate && value <= kMaximumImmediate;\n}\n\nValue Value::False() {\n return Value(Type::Integer, ValueSize::Size8, Kind::Condition, 0);\n}\n\nValue Value::Float32Literal() {\n return Value(Float32Type(), Kind::Literal);\n}\n\nValue Value::Float64Literal() {\n return Value(Float64Type(), Kind::Literal);\n}\n\nValue Value::Float32Type() {\n return Value(Type::Float, ValueSize::Size32, Kind::Void, 0);\n}\n\nValue Value::Float64Type() {\n return Value(Type::Float, ValueSize::Size64, Kind::Void, 0);\n}\n\nValue Value::FrameSlot(Value type, int data) {\n return Value(type.type, type.size, Kind::FrameSlot, data);\n}\n\nValue Value::Immediate(ValueSize size, int data) {\n DCHECK(CanBeImmediate(data));\n return Value(Type::Integer, size, Kind::Immediate, data);\n}\n\nValue Value::Int16Type() {\n return Value(Type::Integer, ValueSize::Size16, Kind::Void, 0);\n}\n\nValue Value::Int32Type() {\n return Value(Type::Integer, ValueSize::Size32, Kind::Void, 0);\n}\n\nValue Value::Int64Type() {\n return Value(Type::Integer, ValueSize::Size64, Kind::Void, 0);\n}\n\nValue Value::Int8Type() {\n return Value(Type::Integer, ValueSize::Size8, Kind::Void, 0);\n}\n\nValue Value::Literal(Value type) {\n return Value(type, Kind::Literal);\n}\n\nValue Value::Parameter(Value type, int data) {\n return Value(type.type, type.size, Kind::Parameter, data);\n}\n\nValue Value::Register(Value type, int data) {\n return Value(type.type, type.size, Kind::VirtualRegister, data);\n}\n\nValue Value::SmallInt16(int data) {\n DCHECK_LT(static_cast<uint32_t>(data), 1u << 16);\n return Immediate(ValueSize::Size16, data);\n}\n\nValue Value::SmallInt32(int data) {\n return Immediate(ValueSize::Size32, data);\n}\n\nValue Value::SmallInt64(int data) {\n return Immediate(ValueSize::Size64, data);\n}\n\nValue Value::SmallInt8(int data) {\n DCHECK_LT(static_cast<uint32_t>(data), 1u << 8);\n return Immediate(ValueSize::Size8, data);\n}\n\nValue Value::SpillSlot(Value type, int data) {\n return Value(type.type, type.size, Kind::SpillSlot, data);\n}\n\nValue Value::StackSlot(Value type, int data) {\n return Value(type.type, type.size, Kind::StackSlot, data);\n}\n\nValue Value::True() {\n return Value(Type::Integer, ValueSize::Size8, Kind::Condition, 1);\n}\n\nbool Value::is_output() const {\n switch (kind) {\n case Kind::Argument:\n case Kind::Condition:\n case Kind::FrameSlot:\n case Kind::Parameter:\n case Kind::PhysicalRegister:\n case Kind::SpillSlot:\n case Kind::StackSlot:\n case Kind::VirtualRegister:\n return true;\n }\n return false;\n}\n\n} \/\/ namespace lir\n} \/\/ namespace elang\n\nnamespace std {\nsize_t hash<elang::lir::Value>::operator()(\n const elang::lir::Value& value) const {\n auto const p = reinterpret_cast<const uint32_t*>(&value);\n return std::hash<uint32_t>()(*p);\n}\n} \/\/ namespace std\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/environment.h\"\n\n#include <string>\n#include <vector>\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/util.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/shape.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace cl {\nnamespace {\nabsl::Status CreateEnvironment(Environment* result, bool shared,\n cl_context_properties egl_context,\n cl_context_properties egl_display) {\n CLDevice gpu;\n RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));\n\n CLContext context;\n if (shared) {\n RETURN_IF_ERROR(CreateCLGLContext(gpu, egl_context, egl_display, &context));\n } else {\n RETURN_IF_ERROR(CreateCLContext(gpu, &context));\n }\n CLCommandQueue queue;\n RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));\n ProfilingCommandQueue profiling_queue;\n RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));\n\n *result = Environment(std::move(gpu), std::move(context), std::move(queue),\n std::move(profiling_queue));\n\n return result->Init();\n}\n\nbool IsGpuSupportsStorageType(const GpuInfo& gpu_info,\n TensorStorageType storage_type) {\n switch (storage_type) {\n case TensorStorageType::TEXTURE_2D:\n return !gpu_info.IsAMD();\n case TensorStorageType::BUFFER:\n return true;\n case TensorStorageType::TEXTURE_ARRAY:\n return !gpu_info.IsAMD() && gpu_info.SupportsTextureArray();\n case TensorStorageType::IMAGE_BUFFER:\n return (gpu_info.IsAdreno() || gpu_info.IsAMD() || gpu_info.IsNvidia()) &&\n gpu_info.SupportsImageBuffer();\n case TensorStorageType::TEXTURE_3D:\n return !gpu_info.IsAMD() && gpu_info.SupportsImage3D();\n case TensorStorageType::SINGLE_TEXTURE_2D:\n return false;\n case TensorStorageType::UNKNOWN:\n return false;\n }\n return false;\n}\n\nbool IsGpuSupportsPrecision(const GpuInfo& gpu_info,\n CalculationsPrecision precision) {\n switch (precision) {\n case CalculationsPrecision::F32_F16:\n case CalculationsPrecision::F16:\n return gpu_info.SupportsFP16();\n case CalculationsPrecision::F32:\n return true;\n }\n}\n\n} \/\/ namespace\n\nEnvironment::Environment(CLDevice&& device, CLContext&& context,\n CLCommandQueue&& queue,\n ProfilingCommandQueue&& profiling_queue)\n : device_(std::move(device)),\n context_(std::move(context)),\n queue_(std::move(queue)),\n profiling_queue_(std::move(profiling_queue)) {}\n\nEnvironment::Environment(Environment&& environment)\n : device_(std::move(environment.device_)),\n context_(std::move(environment.context_)),\n queue_(std::move(environment.queue_)),\n profiling_queue_(std::move(environment.profiling_queue_)),\n program_cache_(std::move(environment.program_cache_)) {}\n\nEnvironment& Environment::operator=(Environment&& environment) {\n if (this != &environment) {\n device_ = std::move(environment.device_);\n context_ = std::move(environment.context_);\n queue_ = std::move(environment.queue_);\n profiling_queue_ = std::move(environment.profiling_queue_);\n program_cache_ = std::move(environment.program_cache_);\n }\n return *this;\n}\n\nabsl::Status Environment::Init() {\n if (device().GetInfo().IsAdreno() &&\n device().GetInfo().SupportsTextureArray()) {\n const auto& adreno_info = device().info_.adreno_info;\n \/\/ Some Adreno < 600 have bug with one layer texture array. b\/131099086\n \/\/ If we have one layer texture array and will write smt from kernel to this\n \/\/ texture, we will get zeroes instead of actual values.\n \/\/ The same kernel will work, if we use texture array with more than one\n \/\/ layer.\n if (adreno_info.IsAdreno3xx() || adreno_info.IsAdreno4xx() ||\n adreno_info.IsAdreno5xx()) {\n GetDevicePtr()->DisableOneLayerTextureArray();\n }\n }\n return absl::OkStatus();\n}\n\nvoid Environment::SetHighPerformance() const {\n \/\/ TODO(sorokin) use cl_perf_hint if available\n}\n\nvoid Environment::SetDefaultPerformance() const {\n \/\/ TODO(sorokin) use cl_perf_hint if available\n}\n\nvoid Environment::SetLowPerformance() const {\n \/\/ TODO(sorokin) use cl_perf_hint if available\n}\n\nstd::vector<CalculationsPrecision> Environment::GetSupportedPrecisions() const {\n std::vector<CalculationsPrecision> precisions;\n for (CalculationsPrecision precision :\n {CalculationsPrecision::F32, CalculationsPrecision::F32_F16,\n CalculationsPrecision::F16}) {\n if (IsSupported(precision)) {\n precisions.push_back(precision);\n }\n }\n return precisions;\n}\n\nbool Environment::IsSupported(CalculationsPrecision precision) const {\n return IsGpuSupportsPrecision(device_.GetInfo(), precision);\n}\n\nstd::vector<TensorStorageType> Environment::GetSupportedStorages() const {\n std::vector<TensorStorageType> storage_types;\n for (auto storage_type :\n {TensorStorageType::TEXTURE_2D, TensorStorageType::BUFFER,\n TensorStorageType::TEXTURE_ARRAY, TensorStorageType::IMAGE_BUFFER,\n TensorStorageType::TEXTURE_3D}) {\n if (IsSupported(storage_type)) {\n storage_types.push_back(storage_type);\n }\n }\n return storage_types;\n}\n\nstd::vector<TensorStorageType>\nEnvironment::GetSupportedStoragesWithHWZeroClampSupport() const {\n std::vector<TensorStorageType> storage_types;\n for (auto storage_type :\n {TensorStorageType::TEXTURE_2D, TensorStorageType::TEXTURE_ARRAY,\n TensorStorageType::TEXTURE_3D}) {\n if (IsSupported(storage_type)) {\n storage_types.push_back(storage_type);\n }\n }\n return storage_types;\n}\n\nbool Environment::IsSupported(TensorStorageType storage_type) const {\n return IsGpuSupportsStorageType(device_.GetInfo(), storage_type);\n}\n\nTensorStorageType GetFastestStorageType(const GpuInfo& gpu_info) {\n if (gpu_info.IsAdreno()) {\n if (gpu_info.adreno_info.IsAdreno6xxOrHigher() &&\n !gpu_info.opencl_info.IsImage2dFromBufferSupported()) {\n return TensorStorageType::TEXTURE_ARRAY;\n } else {\n return TensorStorageType::TEXTURE_2D;\n }\n } else if (gpu_info.IsPowerVR()) {\n return TensorStorageType::TEXTURE_2D;\n } else if (gpu_info.IsMali()) {\n const MaliInfo mali_info = gpu_info.mali_info;\n if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||\n mali_info.IsValhall()) {\n return TensorStorageType::TEXTURE_2D;\n } else {\n return TensorStorageType::BUFFER;\n }\n } else if (gpu_info.IsNvidia()) {\n return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER\n : TensorStorageType::BUFFER;\n } else if (gpu_info.IsAMD()) {\n return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER\n : TensorStorageType::BUFFER;\n } else if (gpu_info.IsIntel()) {\n return TensorStorageType::BUFFER;\n }\n return TensorStorageType::BUFFER;\n}\n\nTensorStorageType GetStorageTypeWithMinimalMemoryConsumption(\n const GpuInfo& gpu_info) {\n if (gpu_info.IsAdreno()) {\n if (gpu_info.adreno_info.IsAdreno3xx() ||\n gpu_info.adreno_info.IsAdreno4xx()) {\n return TensorStorageType::BUFFER;\n } else {\n if (gpu_info.opencl_info.IsImage2dFromBufferSupported()) {\n return TensorStorageType::TEXTURE_2D;\n } else {\n return TensorStorageType::IMAGE_BUFFER;\n }\n }\n } else if (gpu_info.IsPowerVR()) {\n if (gpu_info.opencl_info.IsImage2dFromBufferSupported() &&\n CanUseSubBufferForImage2d(gpu_info)) {\n return TensorStorageType::TEXTURE_2D;\n } else {\n return TensorStorageType::BUFFER;\n }\n } else if (gpu_info.IsMali()) {\n const MaliInfo mali_info = gpu_info.mali_info;\n if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||\n mali_info.IsValhall()) {\n if (gpu_info.opencl_info.IsImage2dFromBufferSupported() &&\n CanUseSubBufferForImage2d(gpu_info)) {\n return TensorStorageType::TEXTURE_2D;\n } else {\n return TensorStorageType::BUFFER;\n }\n } else {\n return TensorStorageType::BUFFER;\n }\n } else if (gpu_info.IsNvidia()) {\n return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER\n : TensorStorageType::BUFFER;\n } else if (gpu_info.IsAMD()) {\n return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER\n : TensorStorageType::BUFFER;\n } else if (gpu_info.IsIntel()) {\n return TensorStorageType::BUFFER;\n }\n return TensorStorageType::BUFFER;\n}\n\nbool CanUseSubBufferForImage2d(const GpuInfo& gpu_info) {\n if (!gpu_info.IsCL11OrHigher()) {\n return false;\n }\n if (gpu_info.IsPowerVR()) {\n \/\/ driver issue\n return false;\n }\n if (gpu_info.IsMali() &&\n (gpu_info.mali_info.IsBifrost() || gpu_info.mali_info.IsMidgard())) {\n \/\/ Known driver issue on some G72 (Bifrost), G76 (Bifrost), T830 (Midgard),\n \/\/ and T880 (Midgard) devices.\n return false;\n }\n return true;\n}\n\nabsl::Status CreateEnvironment(Environment* result) {\n CLDevice gpu;\n RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));\n\n CLContext context;\n RETURN_IF_ERROR(CreateCLContext(gpu, &context));\n CLCommandQueue queue;\n RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));\n ProfilingCommandQueue profiling_queue;\n RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));\n\n *result = Environment(std::move(gpu), std::move(context), std::move(queue),\n std::move(profiling_queue));\n return result->Init();\n}\n\n} \/\/ namespace cl\n} \/\/ namespace gpu\n} \/\/ namespace tflite\n<commit_msg>Nvidia excluded from CanUseSubBufferForImage2d.<commit_after>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/environment.h\"\n\n#include <string>\n#include <vector>\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/util.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/shape.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace cl {\nnamespace {\nabsl::Status CreateEnvironment(Environment* result, bool shared,\n cl_context_properties egl_context,\n cl_context_properties egl_display) {\n CLDevice gpu;\n RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));\n\n CLContext context;\n if (shared) {\n RETURN_IF_ERROR(CreateCLGLContext(gpu, egl_context, egl_display, &context));\n } else {\n RETURN_IF_ERROR(CreateCLContext(gpu, &context));\n }\n CLCommandQueue queue;\n RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));\n ProfilingCommandQueue profiling_queue;\n RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));\n\n *result = Environment(std::move(gpu), std::move(context), std::move(queue),\n std::move(profiling_queue));\n\n return result->Init();\n}\n\nbool IsGpuSupportsStorageType(const GpuInfo& gpu_info,\n TensorStorageType storage_type) {\n switch (storage_type) {\n case TensorStorageType::TEXTURE_2D:\n return !gpu_info.IsAMD();\n case TensorStorageType::BUFFER:\n return true;\n case TensorStorageType::TEXTURE_ARRAY:\n return !gpu_info.IsAMD() && gpu_info.SupportsTextureArray();\n case TensorStorageType::IMAGE_BUFFER:\n return (gpu_info.IsAdreno() || gpu_info.IsAMD() || gpu_info.IsNvidia()) &&\n gpu_info.SupportsImageBuffer();\n case TensorStorageType::TEXTURE_3D:\n return !gpu_info.IsAMD() && gpu_info.SupportsImage3D();\n case TensorStorageType::SINGLE_TEXTURE_2D:\n return false;\n case TensorStorageType::UNKNOWN:\n return false;\n }\n return false;\n}\n\nbool IsGpuSupportsPrecision(const GpuInfo& gpu_info,\n CalculationsPrecision precision) {\n switch (precision) {\n case CalculationsPrecision::F32_F16:\n case CalculationsPrecision::F16:\n return gpu_info.SupportsFP16();\n case CalculationsPrecision::F32:\n return true;\n }\n}\n\n} \/\/ namespace\n\nEnvironment::Environment(CLDevice&& device, CLContext&& context,\n CLCommandQueue&& queue,\n ProfilingCommandQueue&& profiling_queue)\n : device_(std::move(device)),\n context_(std::move(context)),\n queue_(std::move(queue)),\n profiling_queue_(std::move(profiling_queue)) {}\n\nEnvironment::Environment(Environment&& environment)\n : device_(std::move(environment.device_)),\n context_(std::move(environment.context_)),\n queue_(std::move(environment.queue_)),\n profiling_queue_(std::move(environment.profiling_queue_)),\n program_cache_(std::move(environment.program_cache_)) {}\n\nEnvironment& Environment::operator=(Environment&& environment) {\n if (this != &environment) {\n device_ = std::move(environment.device_);\n context_ = std::move(environment.context_);\n queue_ = std::move(environment.queue_);\n profiling_queue_ = std::move(environment.profiling_queue_);\n program_cache_ = std::move(environment.program_cache_);\n }\n return *this;\n}\n\nabsl::Status Environment::Init() {\n if (device().GetInfo().IsAdreno() &&\n device().GetInfo().SupportsTextureArray()) {\n const auto& adreno_info = device().info_.adreno_info;\n \/\/ Some Adreno < 600 have bug with one layer texture array. b\/131099086\n \/\/ If we have one layer texture array and will write smt from kernel to this\n \/\/ texture, we will get zeroes instead of actual values.\n \/\/ The same kernel will work, if we use texture array with more than one\n \/\/ layer.\n if (adreno_info.IsAdreno3xx() || adreno_info.IsAdreno4xx() ||\n adreno_info.IsAdreno5xx()) {\n GetDevicePtr()->DisableOneLayerTextureArray();\n }\n }\n return absl::OkStatus();\n}\n\nvoid Environment::SetHighPerformance() const {\n \/\/ TODO(sorokin) use cl_perf_hint if available\n}\n\nvoid Environment::SetDefaultPerformance() const {\n \/\/ TODO(sorokin) use cl_perf_hint if available\n}\n\nvoid Environment::SetLowPerformance() const {\n \/\/ TODO(sorokin) use cl_perf_hint if available\n}\n\nstd::vector<CalculationsPrecision> Environment::GetSupportedPrecisions() const {\n std::vector<CalculationsPrecision> precisions;\n for (CalculationsPrecision precision :\n {CalculationsPrecision::F32, CalculationsPrecision::F32_F16,\n CalculationsPrecision::F16}) {\n if (IsSupported(precision)) {\n precisions.push_back(precision);\n }\n }\n return precisions;\n}\n\nbool Environment::IsSupported(CalculationsPrecision precision) const {\n return IsGpuSupportsPrecision(device_.GetInfo(), precision);\n}\n\nstd::vector<TensorStorageType> Environment::GetSupportedStorages() const {\n std::vector<TensorStorageType> storage_types;\n for (auto storage_type :\n {TensorStorageType::TEXTURE_2D, TensorStorageType::BUFFER,\n TensorStorageType::TEXTURE_ARRAY, TensorStorageType::IMAGE_BUFFER,\n TensorStorageType::TEXTURE_3D}) {\n if (IsSupported(storage_type)) {\n storage_types.push_back(storage_type);\n }\n }\n return storage_types;\n}\n\nstd::vector<TensorStorageType>\nEnvironment::GetSupportedStoragesWithHWZeroClampSupport() const {\n std::vector<TensorStorageType> storage_types;\n for (auto storage_type :\n {TensorStorageType::TEXTURE_2D, TensorStorageType::TEXTURE_ARRAY,\n TensorStorageType::TEXTURE_3D}) {\n if (IsSupported(storage_type)) {\n storage_types.push_back(storage_type);\n }\n }\n return storage_types;\n}\n\nbool Environment::IsSupported(TensorStorageType storage_type) const {\n return IsGpuSupportsStorageType(device_.GetInfo(), storage_type);\n}\n\nTensorStorageType GetFastestStorageType(const GpuInfo& gpu_info) {\n if (gpu_info.IsAdreno()) {\n if (gpu_info.adreno_info.IsAdreno6xxOrHigher() &&\n !gpu_info.opencl_info.IsImage2dFromBufferSupported()) {\n return TensorStorageType::TEXTURE_ARRAY;\n } else {\n return TensorStorageType::TEXTURE_2D;\n }\n } else if (gpu_info.IsPowerVR()) {\n return TensorStorageType::TEXTURE_2D;\n } else if (gpu_info.IsMali()) {\n const MaliInfo mali_info = gpu_info.mali_info;\n if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||\n mali_info.IsValhall()) {\n return TensorStorageType::TEXTURE_2D;\n } else {\n return TensorStorageType::BUFFER;\n }\n } else if (gpu_info.IsNvidia()) {\n return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER\n : TensorStorageType::BUFFER;\n } else if (gpu_info.IsAMD()) {\n return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER\n : TensorStorageType::BUFFER;\n } else if (gpu_info.IsIntel()) {\n return TensorStorageType::BUFFER;\n }\n return TensorStorageType::BUFFER;\n}\n\nTensorStorageType GetStorageTypeWithMinimalMemoryConsumption(\n const GpuInfo& gpu_info) {\n if (gpu_info.IsAdreno()) {\n if (gpu_info.adreno_info.IsAdreno3xx() ||\n gpu_info.adreno_info.IsAdreno4xx()) {\n return TensorStorageType::BUFFER;\n } else {\n if (gpu_info.opencl_info.IsImage2dFromBufferSupported()) {\n return TensorStorageType::TEXTURE_2D;\n } else {\n return TensorStorageType::IMAGE_BUFFER;\n }\n }\n } else if (gpu_info.IsPowerVR()) {\n if (gpu_info.opencl_info.IsImage2dFromBufferSupported() &&\n CanUseSubBufferForImage2d(gpu_info)) {\n return TensorStorageType::TEXTURE_2D;\n } else {\n return TensorStorageType::BUFFER;\n }\n } else if (gpu_info.IsMali()) {\n const MaliInfo mali_info = gpu_info.mali_info;\n if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||\n mali_info.IsValhall()) {\n if (gpu_info.opencl_info.IsImage2dFromBufferSupported() &&\n CanUseSubBufferForImage2d(gpu_info)) {\n return TensorStorageType::TEXTURE_2D;\n } else {\n return TensorStorageType::BUFFER;\n }\n } else {\n return TensorStorageType::BUFFER;\n }\n } else if (gpu_info.IsNvidia()) {\n return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER\n : TensorStorageType::BUFFER;\n } else if (gpu_info.IsAMD()) {\n return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER\n : TensorStorageType::BUFFER;\n } else if (gpu_info.IsIntel()) {\n return TensorStorageType::BUFFER;\n }\n return TensorStorageType::BUFFER;\n}\n\nbool CanUseSubBufferForImage2d(const GpuInfo& gpu_info) {\n if (!gpu_info.IsCL11OrHigher()) {\n return false;\n }\n if (gpu_info.IsPowerVR()) {\n \/\/ driver issue\n return false;\n }\n if (gpu_info.IsNvidia()) {\n return false;\n }\n if (gpu_info.IsMali() &&\n (gpu_info.mali_info.IsBifrost() || gpu_info.mali_info.IsMidgard())) {\n \/\/ Known driver issue on some G72 (Bifrost), G76 (Bifrost), T830 (Midgard),\n \/\/ and T880 (Midgard) devices.\n return false;\n }\n return true;\n}\n\nabsl::Status CreateEnvironment(Environment* result) {\n CLDevice gpu;\n RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));\n\n CLContext context;\n RETURN_IF_ERROR(CreateCLContext(gpu, &context));\n CLCommandQueue queue;\n RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));\n ProfilingCommandQueue profiling_queue;\n RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));\n\n *result = Environment(std::move(gpu), std::move(context), std::move(queue),\n std::move(profiling_queue));\n return result->Init();\n}\n\n} \/\/ namespace cl\n} \/\/ namespace gpu\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -fsyntax-only -verify %s\n\nnamespace PR6915 {\n template <typename T>\n class D {\n enum T::X v; \/\/ expected-error{{use of 'X' with tag type that does not match previous declaration}} \\\n \/\/ expected-error{{no enum named 'X' in 'PR6915::D3'}}\n };\n\n struct D1 {\n enum X { value };\n };\n struct D2 { \n class X { }; \/\/ expected-note{{previous use is here}}\n };\n struct D3 { };\n\n template class D<D1>;\n template class D<D2>; \/\/ expected-note{{in instantiation of}}\n template class D<D3>; \/\/ expected-note{{in instantiation of}}\n}\n\ntemplate<typename T>\nstruct DeclOrDef {\n enum T::foo; \/\/ expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}\n enum T::bar { \/\/ expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}\n value \n };\n};\n\nnamespace PR6649 {\n template <typename T> struct foo { \n class T::bar; \/\/ expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}\n };\n}\n<commit_msg>Tweak test case slightly<commit_after>\/\/ RUN: %clang_cc1 -fsyntax-only -verify %s\n\nnamespace PR6915 {\n template <typename T>\n class D {\n enum T::X v; \/\/ expected-error{{use of 'X' with tag type that does not match previous declaration}} \\\n \/\/ expected-error{{no enum named 'X' in 'PR6915::D3'}}\n };\n\n struct D1 {\n enum X { value };\n };\n struct D2 { \n class X { }; \/\/ expected-note{{previous use is here}}\n };\n struct D3 { };\n\n template class D<D1>;\n template class D<D2>; \/\/ expected-note{{in instantiation of}}\n template class D<D3>; \/\/ expected-note{{in instantiation of}}\n}\n\ntemplate<typename T>\nstruct DeclOrDef {\n enum T::foo; \/\/ expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}\n enum T::bar { \/\/ expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}\n value \n };\n};\n\nnamespace PR6649 {\n template <typename T> struct foo { \n class T::bar; \/\/ expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}\n class T::bar { int x; }; \/\/ expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/pm\/p10_update_ec_state.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2022 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/ @file p10_update_ec_state.C\n\/\/\/ @brief Update the core configured data in CCSR register and then deals with\n\/\/\/ deconfigured cores to verify the chiplet state..if it is still running then\n\/\/\/ will put the core to stop 11 state\n\/\/\/\n\/\/\/ *HWP HW Owner : Greg Still <stillgs@us.ibm.com>\n\/\/\/ *HWP FW Owner : Prasad Bg Ranganath <prasadbgr@in.ibm.com>\n\/\/\/ *HWP Team : PM\n\/\/\/ *HWP Level : 2\n\/\/\/ *HWP Consumed by : HB,PGPE,CME,OCC\n\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Includes\n\/\/ -----------------------------------------------------------------------------\n#include \"p10_update_ec_state.H\"\n#include \"p10_hcd_common.H\"\n#include \"p10_hcd_cache_stopclocks.H\"\n#include \"p10_hcd_core_poweroff.H\"\n#include \"p10_hcd_l3_purge.H\"\n#include \"p10_hcd_l2_purge.H\"\n#include \"p10_hcd_powerbus_purge.H\"\n#include \"p10_hcd_l2_tlbie_quiesce.H\"\n#include \"p10_hcd_ncu_purge.H\"\n#include \"p10_hcd_chtm_purge.H\"\n#include \"p10_hcd_core_stopclocks.H\"\n#include \"p10_hcd_cache_poweroff.H\"\n#include \"p10_hcd_core_shadows_disable.H\"\n#include \"p10_hcd_core_stopgrid.H\"\n#include <p10_scom_proc.H>\n#include <p10_scom_c.H>\n#include <p10_scom_eq.H>\n\n\nusing namespace scomt;\nusing namespace proc;\nusing namespace c;\nusing namespace eq;\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Function prototypes\n\/\/ -----------------------------------------------------------------------------\nstatic fapi2::ReturnCode update_ec_config(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n\n\nfapi2::ReturnCode verify_ec_hw_state(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n\n\n\nfapi2::ReturnCode p10_check_core_l3_clock_power_state(\n const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,\n uint8_t i_core_unit_pos);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Constants\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ See .H for documentation\nfapi2::ReturnCode p10_update_ec_state(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n uint8_t i_qssr_skip)\n{\n\n FAPI_IMP(\"> p10_update_ec_state\");\n\n FAPI_TRY(update_ec_config(i_target),\n \"Error update_core_config detected\");\n \/\/TODO Need to find the right way to get deconfigured target\n FAPI_TRY(verify_ec_hw_state(i_target));\n\nfapi_try_exit:\n FAPI_INF(\"< p10_update_ec_state\");\n\n return fapi2::current_err;\n} \/\/ END p10_update_ec_state\n\nfapi2::ReturnCode verify_ec_hw_state(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_INF (\">>verify_hw_state\");\n#if 0\n uint8_t l_present_core_unit_pos;\n uint8_t l_functional_core_unit_pos;\n\n uint8_t l_core_match = 0;\n\n \/\/Get the perv target lists\n auto l_core_present_target_vector = i_target.getChildren<fapi2::TARGET_TYPE_CORE>(\n fapi2::TARGET_STATE_PRESENT);\n\n \/\/Get the functional lists\n auto l_core_functional_vector =\n i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_FUNCTIONAL);\n\n \/\/Verify Core state\n for (auto core_present_it : l_core_present_target_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_present_it,\n l_present_core_unit_pos));\n\n l_core_match = 1;\n\n FAPI_INF(\"Present core %d \", l_present_core_unit_pos);\n\n for (auto core_functional_it : l_core_functional_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_functional_it,\n l_functional_core_unit_pos));\n FAPI_INF(\" Functional EC %d\",\n l_functional_core_unit_pos);\n\n if (l_functional_core_unit_pos == l_present_core_unit_pos)\n {\n l_core_match = 1;\n break;\n }\n else\n {\n l_core_match = 0;\n }\n }\/\/end of functional\n\n if (!l_core_match)\n {\n for ( auto l_core_target : core_present_it.getChildren<fapi2::TARGET_TYPE_CORE>(fapi2::TARGET_STATE_PRESENT) )\n {\n FAPI_INF(\"Core present but non functional %d\",\n l_present_core_unit_pos);\n\n \/\/Check the clock state and power state\n FAPI_TRY(p10_check_core_l3_clock_power_state(l_core_target, l_present_core_unit_pos));\n\n }\n }\n }\/\/end of present\n\nfapi_try_exit:\n#endif\n FAPI_INF(\"< update_core_config...\");\n return fapi2::current_err;\n\n}\n\n\/\/\/ @brief Update the CCSR for cores\n\/\/\/\n\/\/\/ @param[in] i_target Reference to TARGET_TYPE_PROC_CHIP target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nstatic fapi2::ReturnCode update_ec_config(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_INF(\"> update_core_config...\");\n\n uint8_t l_present_core_unit_pos;\n uint8_t l_functional_core_unit_pos;\n fapi2::buffer<uint64_t> l_core_config = 0;\n fapi2::buffer<uint64_t> l_pscom_config = 0;\n\n auto l_core_present_vector =\n i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_PRESENT);\n\n auto l_core_functional_vector =\n i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_FUNCTIONAL);\n\n FAPI_INF(\" Number of present cores = %d; Number of functional cores = %d\",\n l_core_present_vector.size(),\n l_core_functional_vector.size());\n\n \/\/ For each present core, set multicast groups and the CCSR\n for (auto core_present_it : l_core_present_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_present_it,\n l_present_core_unit_pos));\n\n FAPI_INF(\" Checking if present EC %d is functional\",\n l_present_core_unit_pos);\n\n for (auto core_functional_it : l_core_functional_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_functional_it,\n l_functional_core_unit_pos));\n FAPI_DBG(\" Functional EC %d\",\n l_functional_core_unit_pos);\n\n if (l_functional_core_unit_pos == l_present_core_unit_pos)\n {\n \/\/ Set the appropriate bit in the Core Configuration Status\n \/\/ Register buffer\n FAPI_INF(\" Setting EC %d as good in value to be written to CCSR\",\n l_present_core_unit_pos);\n l_core_config.setBit(l_present_core_unit_pos);\n\n auto l_eq = core_functional_it.getParent<fapi2::TARGET_TYPE_EQ>();\n\n l_present_core_unit_pos = l_present_core_unit_pos % 4;\n\n \/\/Update the pscom enable bit\n l_pscom_config.setBit(l_present_core_unit_pos + 5);\n\n FAPI_TRY(fapi2::putScom(l_eq, CPLT_CTRL3_WO_OR, l_pscom_config));\n break;\n } \/\/ Current core\n } \/\/ Functional core loop\n } \/\/ Present core loop\n\n \/\/ Write the recalculated OCC Core Configuration Status Register\n FAPI_INF(\" Writing OCC CCSR\");\n FAPI_TRY(fapi2::putScom(i_target, TP_TPCHIP_OCC_OCI_OCB_CCSR_RW, l_core_config));\n\n\nfapi_try_exit:\n FAPI_INF(\"< update_core_config...\");\n return fapi2::current_err;\n\n}\n\n#define CORE_START_POSITION 5\n#define CACHE_START_POSITION 9\n\nfapi2::ReturnCode p10_check_core_l3_clock_power_state(\n const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,\n uint8_t i_core_unit_pos)\n{\n fapi2::buffer<uint64_t> l_data = 0;\n uint64_t l_pfet_sense = 0;\n uint8_t l_core_relative_pos = i_core_unit_pos % 4;\n uint8_t l_l3_relative_pos = i_core_unit_pos % 4;\n uint8_t l_core_clock_State = 0;\n uint8_t l_l3_clock_State = 0;\n\n\n do\n {\n auto l_eq_target = i_core_target.getParent<fapi2::TARGET_TYPE_EQ>();\n \/\/Read the power state of core\/l2\n FAPI_TRY(GET_CPMS_CL2_PFETSTAT(i_core_target, l_data));\n GET_CPMS_CL2_PFETSTAT_VDD_PFETS_ENABLED_SENSE(l_data, l_pfet_sense);\n\n \/\/verify L3\/core clocks are on\n FAPI_TRY(GET_CLOCK_STAT_SL(l_eq_target, l_data));\n l_core_clock_State = l_data & BIT64(l_core_relative_pos + CORE_START_POSITION);\n l_l3_clock_State = l_data & BIT64(l_l3_relative_pos + CACHE_START_POSITION);\n\n \/\/Verify core is powered on\n \/\/If core is powered on\n \/\/ then if core(ECl2) clocks are on\n \/\/ then need to purge the l2 and stop the core clocks\n \/\/ if L3 clocks are on\n \/\/ then purge L3 and stop the l3 clocks\n \/\/ Power off the core and L3\n if( l_pfet_sense)\n {\n if (!l_core_clock_State)\n {\n FAPI_TRY(p10_hcd_l2_purge(i_core_target));\n FAPI_TRY(p10_hcd_l2_tlbie_quiesce(i_core_target));\n FAPI_TRY(p10_hcd_ncu_purge(i_core_target));\n FAPI_TRY(p10_hcd_core_shadows_disable(i_core_target));\n FAPI_TRY(p10_hcd_core_stopclocks(i_core_target));\n FAPI_TRY(p10_hcd_core_stopgrid(i_core_target));\n }\n\n FAPI_TRY(p10_hcd_core_poweroff(i_core_target));\n\n if (!l_l3_clock_State)\n {\n FAPI_TRY(p10_hcd_chtm_purge(i_core_target));\n FAPI_TRY(p10_hcd_l3_purge(i_core_target));\n FAPI_TRY(p10_hcd_powerbus_purge(i_core_target));\n FAPI_TRY(p10_hcd_cache_stopclocks(i_core_target));\n }\n\n FAPI_TRY(p10_hcd_cache_poweroff(i_core_target));\n }\n }\n while(0);\n\nfapi_try_exit:\n FAPI_INF(\"< p10_check_core_clock_power_state...\");\n return fapi2::current_err;\n\n}\n<commit_msg>Make p10_update_ec_state match header prototype<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/pm\/p10_update_ec_state.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2022 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/ @file p10_update_ec_state.C\n\/\/\/ @brief Update the core configured data in CCSR register and then deals with\n\/\/\/ deconfigured cores to verify the chiplet state..if it is still running then\n\/\/\/ will put the core to stop 11 state\n\/\/\/\n\/\/\/ *HWP HW Owner : Greg Still <stillgs@us.ibm.com>\n\/\/\/ *HWP FW Owner : Prasad Bg Ranganath <prasadbgr@in.ibm.com>\n\/\/\/ *HWP Team : PM\n\/\/\/ *HWP Level : 2\n\/\/\/ *HWP Consumed by : HB,PGPE,CME,OCC\n\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Includes\n\/\/ -----------------------------------------------------------------------------\n#include \"p10_update_ec_state.H\"\n#include \"p10_hcd_common.H\"\n#include \"p10_hcd_cache_stopclocks.H\"\n#include \"p10_hcd_core_poweroff.H\"\n#include \"p10_hcd_l3_purge.H\"\n#include \"p10_hcd_l2_purge.H\"\n#include \"p10_hcd_powerbus_purge.H\"\n#include \"p10_hcd_l2_tlbie_quiesce.H\"\n#include \"p10_hcd_ncu_purge.H\"\n#include \"p10_hcd_chtm_purge.H\"\n#include \"p10_hcd_core_stopclocks.H\"\n#include \"p10_hcd_cache_poweroff.H\"\n#include \"p10_hcd_core_shadows_disable.H\"\n#include \"p10_hcd_core_stopgrid.H\"\n#include <p10_scom_proc.H>\n#include <p10_scom_c.H>\n#include <p10_scom_eq.H>\n\n\nusing namespace scomt;\nusing namespace proc;\nusing namespace c;\nusing namespace eq;\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Function prototypes\n\/\/ -----------------------------------------------------------------------------\nstatic fapi2::ReturnCode update_ec_config(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n\n\nfapi2::ReturnCode verify_ec_hw_state(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n\n\n\nfapi2::ReturnCode p10_check_core_l3_clock_power_state(\n const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,\n uint8_t i_core_unit_pos);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Constants\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ See .H for documentation\nfapi2::ReturnCode p10_update_ec_state(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n\n FAPI_IMP(\"> p10_update_ec_state\");\n\n FAPI_TRY(update_ec_config(i_target),\n \"Error update_core_config detected\");\n \/\/TODO Need to find the right way to get deconfigured target\n FAPI_TRY(verify_ec_hw_state(i_target));\n\nfapi_try_exit:\n FAPI_INF(\"< p10_update_ec_state\");\n\n return fapi2::current_err;\n} \/\/ END p10_update_ec_state\n\nfapi2::ReturnCode verify_ec_hw_state(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_INF (\">>verify_hw_state\");\n#if 0\n uint8_t l_present_core_unit_pos;\n uint8_t l_functional_core_unit_pos;\n\n uint8_t l_core_match = 0;\n\n \/\/Get the perv target lists\n auto l_core_present_target_vector = i_target.getChildren<fapi2::TARGET_TYPE_CORE>(\n fapi2::TARGET_STATE_PRESENT);\n\n \/\/Get the functional lists\n auto l_core_functional_vector =\n i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_FUNCTIONAL);\n\n \/\/Verify Core state\n for (auto core_present_it : l_core_present_target_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_present_it,\n l_present_core_unit_pos));\n\n l_core_match = 1;\n\n FAPI_INF(\"Present core %d \", l_present_core_unit_pos);\n\n for (auto core_functional_it : l_core_functional_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_functional_it,\n l_functional_core_unit_pos));\n FAPI_INF(\" Functional EC %d\",\n l_functional_core_unit_pos);\n\n if (l_functional_core_unit_pos == l_present_core_unit_pos)\n {\n l_core_match = 1;\n break;\n }\n else\n {\n l_core_match = 0;\n }\n }\/\/end of functional\n\n if (!l_core_match)\n {\n for ( auto l_core_target : core_present_it.getChildren<fapi2::TARGET_TYPE_CORE>(fapi2::TARGET_STATE_PRESENT) )\n {\n FAPI_INF(\"Core present but non functional %d\",\n l_present_core_unit_pos);\n\n \/\/Check the clock state and power state\n FAPI_TRY(p10_check_core_l3_clock_power_state(l_core_target, l_present_core_unit_pos));\n\n }\n }\n }\/\/end of present\n\nfapi_try_exit:\n#endif\n FAPI_INF(\"< update_core_config...\");\n return fapi2::current_err;\n\n}\n\n\/\/\/ @brief Update the CCSR for cores\n\/\/\/\n\/\/\/ @param[in] i_target Reference to TARGET_TYPE_PROC_CHIP target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nstatic fapi2::ReturnCode update_ec_config(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_INF(\"> update_core_config...\");\n\n uint8_t l_present_core_unit_pos;\n uint8_t l_functional_core_unit_pos;\n fapi2::buffer<uint64_t> l_core_config = 0;\n fapi2::buffer<uint64_t> l_pscom_config = 0;\n\n auto l_core_present_vector =\n i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_PRESENT);\n\n auto l_core_functional_vector =\n i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_FUNCTIONAL);\n\n FAPI_INF(\" Number of present cores = %d; Number of functional cores = %d\",\n l_core_present_vector.size(),\n l_core_functional_vector.size());\n\n \/\/ For each present core, set multicast groups and the CCSR\n for (auto core_present_it : l_core_present_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_present_it,\n l_present_core_unit_pos));\n\n FAPI_INF(\" Checking if present EC %d is functional\",\n l_present_core_unit_pos);\n\n for (auto core_functional_it : l_core_functional_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_functional_it,\n l_functional_core_unit_pos));\n FAPI_DBG(\" Functional EC %d\",\n l_functional_core_unit_pos);\n\n if (l_functional_core_unit_pos == l_present_core_unit_pos)\n {\n \/\/ Set the appropriate bit in the Core Configuration Status\n \/\/ Register buffer\n FAPI_INF(\" Setting EC %d as good in value to be written to CCSR\",\n l_present_core_unit_pos);\n l_core_config.setBit(l_present_core_unit_pos);\n\n auto l_eq = core_functional_it.getParent<fapi2::TARGET_TYPE_EQ>();\n\n l_present_core_unit_pos = l_present_core_unit_pos % 4;\n\n \/\/Update the pscom enable bit\n l_pscom_config.setBit(l_present_core_unit_pos + 5);\n\n FAPI_TRY(fapi2::putScom(l_eq, CPLT_CTRL3_WO_OR, l_pscom_config));\n break;\n } \/\/ Current core\n } \/\/ Functional core loop\n } \/\/ Present core loop\n\n \/\/ Write the recalculated OCC Core Configuration Status Register\n FAPI_INF(\" Writing OCC CCSR\");\n FAPI_TRY(fapi2::putScom(i_target, TP_TPCHIP_OCC_OCI_OCB_CCSR_RW, l_core_config));\n\n\nfapi_try_exit:\n FAPI_INF(\"< update_core_config...\");\n return fapi2::current_err;\n\n}\n\n#define CORE_START_POSITION 5\n#define CACHE_START_POSITION 9\n\nfapi2::ReturnCode p10_check_core_l3_clock_power_state(\n const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target,\n uint8_t i_core_unit_pos)\n{\n fapi2::buffer<uint64_t> l_data = 0;\n uint64_t l_pfet_sense = 0;\n uint8_t l_core_relative_pos = i_core_unit_pos % 4;\n uint8_t l_l3_relative_pos = i_core_unit_pos % 4;\n uint8_t l_core_clock_State = 0;\n uint8_t l_l3_clock_State = 0;\n\n\n do\n {\n auto l_eq_target = i_core_target.getParent<fapi2::TARGET_TYPE_EQ>();\n \/\/Read the power state of core\/l2\n FAPI_TRY(GET_CPMS_CL2_PFETSTAT(i_core_target, l_data));\n GET_CPMS_CL2_PFETSTAT_VDD_PFETS_ENABLED_SENSE(l_data, l_pfet_sense);\n\n \/\/verify L3\/core clocks are on\n FAPI_TRY(GET_CLOCK_STAT_SL(l_eq_target, l_data));\n l_core_clock_State = l_data & BIT64(l_core_relative_pos + CORE_START_POSITION);\n l_l3_clock_State = l_data & BIT64(l_l3_relative_pos + CACHE_START_POSITION);\n\n \/\/Verify core is powered on\n \/\/If core is powered on\n \/\/ then if core(ECl2) clocks are on\n \/\/ then need to purge the l2 and stop the core clocks\n \/\/ if L3 clocks are on\n \/\/ then purge L3 and stop the l3 clocks\n \/\/ Power off the core and L3\n if( l_pfet_sense)\n {\n if (!l_core_clock_State)\n {\n FAPI_TRY(p10_hcd_l2_purge(i_core_target));\n FAPI_TRY(p10_hcd_l2_tlbie_quiesce(i_core_target));\n FAPI_TRY(p10_hcd_ncu_purge(i_core_target));\n FAPI_TRY(p10_hcd_core_shadows_disable(i_core_target));\n FAPI_TRY(p10_hcd_core_stopclocks(i_core_target));\n FAPI_TRY(p10_hcd_core_stopgrid(i_core_target));\n }\n\n FAPI_TRY(p10_hcd_core_poweroff(i_core_target));\n\n if (!l_l3_clock_State)\n {\n FAPI_TRY(p10_hcd_chtm_purge(i_core_target));\n FAPI_TRY(p10_hcd_l3_purge(i_core_target));\n FAPI_TRY(p10_hcd_powerbus_purge(i_core_target));\n FAPI_TRY(p10_hcd_cache_stopclocks(i_core_target));\n }\n\n FAPI_TRY(p10_hcd_cache_poweroff(i_core_target));\n }\n }\n while(0);\n\nfapi_try_exit:\n FAPI_INF(\"< p10_check_core_clock_power_state...\");\n return fapi2::current_err;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 \"autopilot_tester.h\"\n#include <chrono>\n\n\nTEST_CASE(\"Offboard takeoff and land\", \"[multicopter][offboard]\")\n{\n\tAutopilotTester tester;\n\tOffboard::PositionNedYaw takeoff_position {0.0f, 0.0f, -2.0f, 0.0f};\n\ttester.connect(connection_url);\n\ttester.wait_until_ready();\n\ttester.store_home();\n\ttester.arm();\n\tstd::chrono::seconds goto_timeout = std::chrono::seconds(90);\n\ttester.offboard_goto(takeoff_position, 0.1f, goto_timeout);\n\ttester.offboard_land();\n\ttester.wait_until_disarmed(std::chrono::seconds(120));\n\ttester.check_home_within(1.0f);\n}\n\nTEST_CASE(\"Offboard position control\", \"[multicopter][offboard]\")\n{\n\tAutopilotTester tester;\n\tOffboard::PositionNedYaw takeoff_position {0.0f, 0.0f, -2.0f, 0.0f};\n\tOffboard::PositionNedYaw setpoint_1 {0.0f, 5.0f, -2.0f, 180.0f};\n\tOffboard::PositionNedYaw setpoint_2 {5.0f, 5.0f, -4.0f, 180.0f};\n\tOffboard::PositionNedYaw setpoint_3 {5.0f, 0.0f, -4.0f, 90.0f};\n\ttester.connect(connection_url);\n\ttester.wait_until_ready();\n\ttester.store_home();\n\ttester.arm();\n\tstd::chrono::seconds goto_timeout = std::chrono::seconds(90);\n\ttester.offboard_goto(takeoff_position, 0.1f, goto_timeout);\n\ttester.offboard_goto(setpoint_1, 0.1f, goto_timeout);\n\ttester.offboard_goto(setpoint_2, 0.1f, goto_timeout);\n\ttester.offboard_goto(setpoint_3, 0.1f, goto_timeout);\n\ttester.offboard_goto(takeoff_position, 0.1f, goto_timeout);\n\ttester.offboard_land();\n\ttester.wait_until_disarmed(std::chrono::seconds(120));\n\ttester.check_home_within(1.0f);\n}\n<commit_msg>mavsdk_tests: fix timeout at 1x speed<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 \"autopilot_tester.h\"\n#include <chrono>\n\n\nTEST_CASE(\"Offboard takeoff and land\", \"[multicopter][offboard]\")\n{\n\tAutopilotTester tester;\n\tOffboard::PositionNedYaw takeoff_position {0.0f, 0.0f, -2.0f, 0.0f};\n\ttester.connect(connection_url);\n\ttester.wait_until_ready();\n\ttester.store_home();\n\ttester.arm();\n\tstd::chrono::seconds goto_timeout = std::chrono::seconds(90);\n\ttester.offboard_goto(takeoff_position, 0.1f, goto_timeout);\n\ttester.offboard_land();\n\ttester.wait_until_disarmed(std::chrono::seconds(120));\n\ttester.check_home_within(1.0f);\n}\n\nTEST_CASE(\"Offboard position control\", \"[multicopter][offboard]\")\n{\n\tAutopilotTester tester;\n\tOffboard::PositionNedYaw takeoff_position {0.0f, 0.0f, -2.0f, 0.0f};\n\tOffboard::PositionNedYaw setpoint_1 {0.0f, 5.0f, -2.0f, 180.0f};\n\tOffboard::PositionNedYaw setpoint_2 {5.0f, 5.0f, -4.0f, 180.0f};\n\tOffboard::PositionNedYaw setpoint_3 {5.0f, 0.0f, -4.0f, 90.0f};\n\ttester.connect(connection_url);\n\ttester.wait_until_ready();\n\ttester.store_home();\n\ttester.arm();\n\tstd::chrono::seconds goto_timeout = std::chrono::seconds(120);\n\ttester.offboard_goto(takeoff_position, 0.1f, goto_timeout);\n\ttester.offboard_goto(setpoint_1, 0.1f, goto_timeout);\n\ttester.offboard_goto(setpoint_2, 0.1f, goto_timeout);\n\ttester.offboard_goto(setpoint_3, 0.1f, goto_timeout);\n\ttester.offboard_goto(takeoff_position, 0.1f, goto_timeout);\n\ttester.offboard_land();\n\ttester.wait_until_disarmed(std::chrono::seconds(120));\n\ttester.check_home_within(1.0f);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012-2013 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\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: Thomas Grass\n * Andreas Hansson\n * Sascha Bischoff\n *\/\n\n#include <sstream>\n\n#include \"base\/random.hh\"\n#include \"cpu\/testers\/traffic_gen\/traffic_gen.hh\"\n#include \"debug\/Checkpoint.hh\"\n#include \"debug\/TrafficGen.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\n\nTrafficGen::TrafficGen(const TrafficGenParams* p)\n : MemObject(p),\n system(p->system),\n masterID(system->getMasterId(name())),\n configFile(p->config_file),\n elasticReq(p->elastic_req),\n nextTransitionTick(0),\n nextPacketTick(0),\n port(name() + \".port\", *this),\n retryPkt(NULL),\n retryPktTick(0),\n updateEvent(this),\n drainManager(NULL)\n{\n}\n\nTrafficGen*\nTrafficGenParams::create()\n{\n return new TrafficGen(this);\n}\n\nBaseMasterPort&\nTrafficGen::getMasterPort(const string& if_name, PortID idx)\n{\n if (if_name == \"port\") {\n return port;\n } else {\n return MemObject::getMasterPort(if_name, idx);\n }\n}\n\nvoid\nTrafficGen::init()\n{\n if (!port.isConnected())\n fatal(\"The port of %s is not connected!\\n\", name());\n\n \/\/ if the system is in timing mode active the request generator\n if (system->isTimingMode()) {\n DPRINTF(TrafficGen, \"Timing mode, activating request generator\\n\");\n\n parseConfig();\n\n \/\/ enter initial state\n enterState(currState);\n } else {\n DPRINTF(TrafficGen,\n \"Traffic generator is only active in timing mode\\n\");\n }\n}\n\nvoid\nTrafficGen::initState()\n{\n \/\/ when not restoring from a checkpoint, make sure we kick things off\n if (system->isTimingMode()) {\n \/\/ call nextPacketTick on the state to advance it\n nextPacketTick = states[currState]->nextPacketTick(elasticReq, 0);\n schedule(updateEvent, std::min(nextPacketTick, nextTransitionTick));\n } else {\n DPRINTF(TrafficGen,\n \"Traffic generator is only active in timing mode\\n\");\n }\n}\n\nunsigned int\nTrafficGen::drain(DrainManager *dm)\n{\n if (!updateEvent.scheduled()) {\n \/\/ no event has been scheduled yet (e.g. switched from atomic mode)\n return 0;\n }\n\n if (retryPkt == NULL) {\n \/\/ shut things down\n nextPacketTick = MaxTick;\n nextTransitionTick = MaxTick;\n deschedule(updateEvent);\n return 0;\n } else {\n drainManager = dm;\n return 1;\n }\n}\n\nvoid\nTrafficGen::serialize(ostream &os)\n{\n DPRINTF(Checkpoint, \"Serializing TrafficGen\\n\");\n\n \/\/ save ticks of the graph event if it is scheduled\n Tick nextEvent = updateEvent.scheduled() ? updateEvent.when() : 0;\n\n DPRINTF(TrafficGen, \"Saving nextEvent=%llu\\n\", nextEvent);\n\n SERIALIZE_SCALAR(nextEvent);\n\n SERIALIZE_SCALAR(nextTransitionTick);\n\n SERIALIZE_SCALAR(nextPacketTick);\n\n SERIALIZE_SCALAR(currState);\n}\n\nvoid\nTrafficGen::unserialize(Checkpoint* cp, const string& section)\n{\n \/\/ restore scheduled events\n Tick nextEvent;\n UNSERIALIZE_SCALAR(nextEvent);\n if (nextEvent != 0) {\n schedule(updateEvent, nextEvent);\n }\n\n UNSERIALIZE_SCALAR(nextTransitionTick);\n\n UNSERIALIZE_SCALAR(nextPacketTick);\n\n \/\/ @todo In the case of a stateful generator state such as the\n \/\/ trace player we would also have to restore the position in the\n \/\/ trace playback and the tick offset\n UNSERIALIZE_SCALAR(currState);\n}\n\nvoid\nTrafficGen::update()\n{\n \/\/ if we have reached the time for the next state transition, then\n \/\/ perform the transition\n if (curTick() >= nextTransitionTick) {\n transition();\n } else {\n assert(curTick() >= nextPacketTick);\n \/\/ get the next packet and try to send it\n PacketPtr pkt = states[currState]->getNextPacket();\n numPackets++;\n if (!port.sendTimingReq(pkt)) {\n retryPkt = pkt;\n retryPktTick = curTick();\n }\n }\n\n \/\/ if we are waiting for a retry, do not schedule any further\n \/\/ events, in the case of a transition or a successful send, go\n \/\/ ahead and determine when the next update should take place\n if (retryPkt == NULL) {\n \/\/ schedule next update event based on either the next execute\n \/\/ tick or the next transition, which ever comes first\n nextPacketTick = states[currState]->nextPacketTick(elasticReq, 0);\n Tick nextEventTick = std::min(nextPacketTick, nextTransitionTick);\n DPRINTF(TrafficGen, \"Next event scheduled at %lld\\n\", nextEventTick);\n schedule(updateEvent, nextEventTick);\n }\n}\n\nvoid\nTrafficGen::parseConfig()\n{\n \/\/ keep track of the transitions parsed to create the matrix when\n \/\/ done\n vector<Transition> transitions;\n\n \/\/ open input file\n ifstream infile;\n infile.open(configFile.c_str(), ifstream::in);\n if (!infile.is_open()) {\n fatal(\"Traffic generator %s config file not found at %s\\n\",\n name(), configFile);\n }\n\n \/\/ read line by line and determine the action based on the first\n \/\/ keyword\n string keyword;\n string line;\n\n while (getline(infile, line).good()) {\n \/\/ see if this line is a comment line, and if so skip it\n if (line.find('#') != 1) {\n \/\/ create an input stream for the tokenization\n istringstream is(line);\n\n \/\/ determine the keyword\n is >> keyword;\n\n if (keyword == \"STATE\") {\n \/\/ parse the behaviour of this state\n uint32_t id;\n Tick duration;\n string mode;\n\n is >> id >> duration >> mode;\n\n if (mode == \"TRACE\") {\n string traceFile;\n Addr addrOffset;\n\n is >> traceFile >> addrOffset;\n\n states[id] = new TraceGen(name(), masterID, duration,\n traceFile, addrOffset);\n DPRINTF(TrafficGen, \"State: %d TraceGen\\n\", id);\n } else if (mode == \"IDLE\") {\n states[id] = new IdleGen(name(), masterID, duration);\n DPRINTF(TrafficGen, \"State: %d IdleGen\\n\", id);\n } else if (mode == \"LINEAR\" || mode == \"RANDOM\") {\n uint32_t read_percent;\n Addr start_addr;\n Addr end_addr;\n Addr blocksize;\n Tick min_period;\n Tick max_period;\n Addr data_limit;\n\n is >> read_percent >> start_addr >> end_addr >>\n blocksize >> min_period >> max_period >> data_limit;\n\n DPRINTF(TrafficGen, \"%s, addr %x to %x, size %d,\"\n \" period %d to %d, %d%% reads\\n\",\n mode, start_addr, end_addr, blocksize, min_period,\n max_period, read_percent);\n\n\n if (blocksize > system->cacheLineSize())\n fatal(\"TrafficGen %s block size (%d) is larger than \"\n \"system block size (%d)\\n\", name(),\n blocksize, system->cacheLineSize());\n\n if (read_percent > 100)\n fatal(\"%s cannot have more than 100% reads\", name());\n\n if (min_period > max_period)\n fatal(\"%s cannot have min_period > max_period\", name());\n\n if (mode == \"LINEAR\") {\n states[id] = new LinearGen(name(), masterID,\n duration, start_addr,\n end_addr, blocksize,\n min_period, max_period,\n read_percent, data_limit);\n DPRINTF(TrafficGen, \"State: %d LinearGen\\n\", id);\n } else if (mode == \"RANDOM\") {\n states[id] = new RandomGen(name(), masterID,\n duration, start_addr,\n end_addr, blocksize,\n min_period, max_period,\n read_percent, data_limit);\n DPRINTF(TrafficGen, \"State: %d RandomGen\\n\", id);\n }\n } else {\n fatal(\"%s: Unknown traffic generator mode: %s\",\n name(), mode);\n }\n } else if (keyword == \"TRANSITION\") {\n Transition transition;\n\n is >> transition.from >> transition.to >> transition.p;\n\n transitions.push_back(transition);\n\n DPRINTF(TrafficGen, \"Transition: %d -> %d\\n\", transition.from,\n transition.to);\n } else if (keyword == \"INIT\") {\n \/\/ set the initial state as the active state\n is >> currState;\n\n DPRINTF(TrafficGen, \"Initial state: %d\\n\", currState);\n }\n }\n }\n\n \/\/ resize and populate state transition matrix\n transitionMatrix.resize(states.size());\n for (size_t i = 0; i < states.size(); i++) {\n transitionMatrix[i].resize(states.size());\n }\n\n for (vector<Transition>::iterator t = transitions.begin();\n t != transitions.end(); ++t) {\n transitionMatrix[t->from][t->to] = t->p;\n }\n\n \/\/ ensure the egress edges do not have a probability larger than\n \/\/ one\n for (size_t i = 0; i < states.size(); i++) {\n double sum = 0;\n for (size_t j = 0; j < states.size(); j++) {\n sum += transitionMatrix[i][j];\n }\n\n \/\/ avoid comparing floating point numbers\n if (abs(sum - 1.0) > 0.001)\n fatal(\"%s has transition probability != 1 for state %d\\n\",\n name(), i);\n }\n\n \/\/ close input file\n infile.close();\n}\n\nvoid\nTrafficGen::transition()\n{\n \/\/ exit the current state\n states[currState]->exit();\n\n \/\/ determine next state\n double p = random_mt.gen_real1();\n assert(currState < transitionMatrix.size());\n double cumulative = 0.0;\n size_t i = 0;\n do {\n cumulative += transitionMatrix[currState][i];\n ++i;\n } while (cumulative < p && i < transitionMatrix[currState].size());\n\n enterState(i - 1);\n}\n\nvoid\nTrafficGen::enterState(uint32_t newState)\n{\n DPRINTF(TrafficGen, \"Transition to state %d\\n\", newState);\n\n currState = newState;\n \/\/ we could have been delayed and not transitioned on the exact\n \/\/ tick when we were supposed to (due to back pressure when\n \/\/ sending a packet)\n nextTransitionTick = curTick() + states[currState]->duration;\n states[currState]->enter();\n}\n\nvoid\nTrafficGen::recvRetry()\n{\n assert(retryPkt != NULL);\n\n DPRINTF(TrafficGen, \"Received retry\\n\");\n numRetries++;\n \/\/ attempt to send the packet, and if we are successful start up\n \/\/ the machinery again\n if (port.sendTimingReq(retryPkt)) {\n retryPkt = NULL;\n \/\/ remember how much delay was incurred due to back-pressure\n \/\/ when sending the request, we also use this to derive\n \/\/ the tick for the next packet\n Tick delay = curTick() - retryPktTick;\n retryPktTick = 0;\n retryTicks += delay;\n\n if (drainManager == NULL) {\n \/\/ packet is sent, so find out when the next one is due\n nextPacketTick = states[currState]->nextPacketTick(elasticReq,\n delay);\n Tick nextEventTick = std::min(nextPacketTick, nextTransitionTick);\n schedule(updateEvent, std::max(curTick(), nextEventTick));\n } else {\n \/\/ shut things down\n nextPacketTick = MaxTick;\n nextTransitionTick = MaxTick;\n drainManager->signalDrainDone();\n \/\/ Clear the drain event once we're done with it.\n drainManager = NULL;\n }\n }\n}\n\nvoid\nTrafficGen::regStats()\n{\n \/\/ Initialise all the stats\n using namespace Stats;\n\n numPackets\n .name(name() + \".numPackets\")\n .desc(\"Number of packets generated\");\n\n numRetries\n .name(name() + \".numRetries\")\n .desc(\"Number of retries\");\n\n retryTicks\n .name(name() + \".retryTicks\")\n .desc(\"Time spent waiting due to back-pressure (ticks)\");\n}\n\nbool\nTrafficGen::TrafficGenPort::recvTimingResp(PacketPtr pkt)\n{\n delete pkt->req;\n delete pkt;\n\n return true;\n}\n<commit_msg>cpu: Add basic check to TrafficGen initial state<commit_after>\/*\n * Copyright (c) 2012-2013 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\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: Thomas Grass\n * Andreas Hansson\n * Sascha Bischoff\n *\/\n\n#include <sstream>\n\n#include \"base\/random.hh\"\n#include \"cpu\/testers\/traffic_gen\/traffic_gen.hh\"\n#include \"debug\/Checkpoint.hh\"\n#include \"debug\/TrafficGen.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\n\nTrafficGen::TrafficGen(const TrafficGenParams* p)\n : MemObject(p),\n system(p->system),\n masterID(system->getMasterId(name())),\n configFile(p->config_file),\n elasticReq(p->elastic_req),\n nextTransitionTick(0),\n nextPacketTick(0),\n port(name() + \".port\", *this),\n retryPkt(NULL),\n retryPktTick(0),\n updateEvent(this),\n drainManager(NULL)\n{\n}\n\nTrafficGen*\nTrafficGenParams::create()\n{\n return new TrafficGen(this);\n}\n\nBaseMasterPort&\nTrafficGen::getMasterPort(const string& if_name, PortID idx)\n{\n if (if_name == \"port\") {\n return port;\n } else {\n return MemObject::getMasterPort(if_name, idx);\n }\n}\n\nvoid\nTrafficGen::init()\n{\n if (!port.isConnected())\n fatal(\"The port of %s is not connected!\\n\", name());\n\n \/\/ if the system is in timing mode active the request generator\n if (system->isTimingMode()) {\n DPRINTF(TrafficGen, \"Timing mode, activating request generator\\n\");\n\n parseConfig();\n\n \/\/ enter initial state\n enterState(currState);\n } else {\n DPRINTF(TrafficGen,\n \"Traffic generator is only active in timing mode\\n\");\n }\n}\n\nvoid\nTrafficGen::initState()\n{\n \/\/ when not restoring from a checkpoint, make sure we kick things off\n if (system->isTimingMode()) {\n \/\/ call nextPacketTick on the state to advance it\n nextPacketTick = states[currState]->nextPacketTick(elasticReq, 0);\n schedule(updateEvent, std::min(nextPacketTick, nextTransitionTick));\n } else {\n DPRINTF(TrafficGen,\n \"Traffic generator is only active in timing mode\\n\");\n }\n}\n\nunsigned int\nTrafficGen::drain(DrainManager *dm)\n{\n if (!updateEvent.scheduled()) {\n \/\/ no event has been scheduled yet (e.g. switched from atomic mode)\n return 0;\n }\n\n if (retryPkt == NULL) {\n \/\/ shut things down\n nextPacketTick = MaxTick;\n nextTransitionTick = MaxTick;\n deschedule(updateEvent);\n return 0;\n } else {\n drainManager = dm;\n return 1;\n }\n}\n\nvoid\nTrafficGen::serialize(ostream &os)\n{\n DPRINTF(Checkpoint, \"Serializing TrafficGen\\n\");\n\n \/\/ save ticks of the graph event if it is scheduled\n Tick nextEvent = updateEvent.scheduled() ? updateEvent.when() : 0;\n\n DPRINTF(TrafficGen, \"Saving nextEvent=%llu\\n\", nextEvent);\n\n SERIALIZE_SCALAR(nextEvent);\n\n SERIALIZE_SCALAR(nextTransitionTick);\n\n SERIALIZE_SCALAR(nextPacketTick);\n\n SERIALIZE_SCALAR(currState);\n}\n\nvoid\nTrafficGen::unserialize(Checkpoint* cp, const string& section)\n{\n \/\/ restore scheduled events\n Tick nextEvent;\n UNSERIALIZE_SCALAR(nextEvent);\n if (nextEvent != 0) {\n schedule(updateEvent, nextEvent);\n }\n\n UNSERIALIZE_SCALAR(nextTransitionTick);\n\n UNSERIALIZE_SCALAR(nextPacketTick);\n\n \/\/ @todo In the case of a stateful generator state such as the\n \/\/ trace player we would also have to restore the position in the\n \/\/ trace playback and the tick offset\n UNSERIALIZE_SCALAR(currState);\n}\n\nvoid\nTrafficGen::update()\n{\n \/\/ if we have reached the time for the next state transition, then\n \/\/ perform the transition\n if (curTick() >= nextTransitionTick) {\n transition();\n } else {\n assert(curTick() >= nextPacketTick);\n \/\/ get the next packet and try to send it\n PacketPtr pkt = states[currState]->getNextPacket();\n numPackets++;\n if (!port.sendTimingReq(pkt)) {\n retryPkt = pkt;\n retryPktTick = curTick();\n }\n }\n\n \/\/ if we are waiting for a retry, do not schedule any further\n \/\/ events, in the case of a transition or a successful send, go\n \/\/ ahead and determine when the next update should take place\n if (retryPkt == NULL) {\n \/\/ schedule next update event based on either the next execute\n \/\/ tick or the next transition, which ever comes first\n nextPacketTick = states[currState]->nextPacketTick(elasticReq, 0);\n Tick nextEventTick = std::min(nextPacketTick, nextTransitionTick);\n DPRINTF(TrafficGen, \"Next event scheduled at %lld\\n\", nextEventTick);\n schedule(updateEvent, nextEventTick);\n }\n}\n\nvoid\nTrafficGen::parseConfig()\n{\n \/\/ keep track of the transitions parsed to create the matrix when\n \/\/ done\n vector<Transition> transitions;\n\n \/\/ open input file\n ifstream infile;\n infile.open(configFile.c_str(), ifstream::in);\n if (!infile.is_open()) {\n fatal(\"Traffic generator %s config file not found at %s\\n\",\n name(), configFile);\n }\n\n bool init_state_set = false;\n\n \/\/ read line by line and determine the action based on the first\n \/\/ keyword\n string keyword;\n string line;\n\n while (getline(infile, line).good()) {\n \/\/ see if this line is a comment line, and if so skip it\n if (line.find('#') != 1) {\n \/\/ create an input stream for the tokenization\n istringstream is(line);\n\n \/\/ determine the keyword\n is >> keyword;\n\n if (keyword == \"STATE\") {\n \/\/ parse the behaviour of this state\n uint32_t id;\n Tick duration;\n string mode;\n\n is >> id >> duration >> mode;\n\n if (mode == \"TRACE\") {\n string traceFile;\n Addr addrOffset;\n\n is >> traceFile >> addrOffset;\n\n states[id] = new TraceGen(name(), masterID, duration,\n traceFile, addrOffset);\n DPRINTF(TrafficGen, \"State: %d TraceGen\\n\", id);\n } else if (mode == \"IDLE\") {\n states[id] = new IdleGen(name(), masterID, duration);\n DPRINTF(TrafficGen, \"State: %d IdleGen\\n\", id);\n } else if (mode == \"LINEAR\" || mode == \"RANDOM\") {\n uint32_t read_percent;\n Addr start_addr;\n Addr end_addr;\n Addr blocksize;\n Tick min_period;\n Tick max_period;\n Addr data_limit;\n\n is >> read_percent >> start_addr >> end_addr >>\n blocksize >> min_period >> max_period >> data_limit;\n\n DPRINTF(TrafficGen, \"%s, addr %x to %x, size %d,\"\n \" period %d to %d, %d%% reads\\n\",\n mode, start_addr, end_addr, blocksize, min_period,\n max_period, read_percent);\n\n\n if (blocksize > system->cacheLineSize())\n fatal(\"TrafficGen %s block size (%d) is larger than \"\n \"system block size (%d)\\n\", name(),\n blocksize, system->cacheLineSize());\n\n if (read_percent > 100)\n fatal(\"%s cannot have more than 100% reads\", name());\n\n if (min_period > max_period)\n fatal(\"%s cannot have min_period > max_period\", name());\n\n if (mode == \"LINEAR\") {\n states[id] = new LinearGen(name(), masterID,\n duration, start_addr,\n end_addr, blocksize,\n min_period, max_period,\n read_percent, data_limit);\n DPRINTF(TrafficGen, \"State: %d LinearGen\\n\", id);\n } else if (mode == \"RANDOM\") {\n states[id] = new RandomGen(name(), masterID,\n duration, start_addr,\n end_addr, blocksize,\n min_period, max_period,\n read_percent, data_limit);\n DPRINTF(TrafficGen, \"State: %d RandomGen\\n\", id);\n }\n } else {\n fatal(\"%s: Unknown traffic generator mode: %s\",\n name(), mode);\n }\n } else if (keyword == \"TRANSITION\") {\n Transition transition;\n\n is >> transition.from >> transition.to >> transition.p;\n\n transitions.push_back(transition);\n\n DPRINTF(TrafficGen, \"Transition: %d -> %d\\n\", transition.from,\n transition.to);\n } else if (keyword == \"INIT\") {\n \/\/ set the initial state as the active state\n is >> currState;\n\n init_state_set = true;\n\n DPRINTF(TrafficGen, \"Initial state: %d\\n\", currState);\n }\n }\n }\n\n if (!init_state_set)\n fatal(\"%s: initial state not specified (add 'INIT <id>' line \"\n \"to the config file)\\n\", name());\n\n \/\/ resize and populate state transition matrix\n transitionMatrix.resize(states.size());\n for (size_t i = 0; i < states.size(); i++) {\n transitionMatrix[i].resize(states.size());\n }\n\n for (vector<Transition>::iterator t = transitions.begin();\n t != transitions.end(); ++t) {\n transitionMatrix[t->from][t->to] = t->p;\n }\n\n \/\/ ensure the egress edges do not have a probability larger than\n \/\/ one\n for (size_t i = 0; i < states.size(); i++) {\n double sum = 0;\n for (size_t j = 0; j < states.size(); j++) {\n sum += transitionMatrix[i][j];\n }\n\n \/\/ avoid comparing floating point numbers\n if (abs(sum - 1.0) > 0.001)\n fatal(\"%s has transition probability != 1 for state %d\\n\",\n name(), i);\n }\n\n \/\/ close input file\n infile.close();\n}\n\nvoid\nTrafficGen::transition()\n{\n \/\/ exit the current state\n states[currState]->exit();\n\n \/\/ determine next state\n double p = random_mt.gen_real1();\n assert(currState < transitionMatrix.size());\n double cumulative = 0.0;\n size_t i = 0;\n do {\n cumulative += transitionMatrix[currState][i];\n ++i;\n } while (cumulative < p && i < transitionMatrix[currState].size());\n\n enterState(i - 1);\n}\n\nvoid\nTrafficGen::enterState(uint32_t newState)\n{\n DPRINTF(TrafficGen, \"Transition to state %d\\n\", newState);\n\n currState = newState;\n \/\/ we could have been delayed and not transitioned on the exact\n \/\/ tick when we were supposed to (due to back pressure when\n \/\/ sending a packet)\n nextTransitionTick = curTick() + states[currState]->duration;\n states[currState]->enter();\n}\n\nvoid\nTrafficGen::recvRetry()\n{\n assert(retryPkt != NULL);\n\n DPRINTF(TrafficGen, \"Received retry\\n\");\n numRetries++;\n \/\/ attempt to send the packet, and if we are successful start up\n \/\/ the machinery again\n if (port.sendTimingReq(retryPkt)) {\n retryPkt = NULL;\n \/\/ remember how much delay was incurred due to back-pressure\n \/\/ when sending the request, we also use this to derive\n \/\/ the tick for the next packet\n Tick delay = curTick() - retryPktTick;\n retryPktTick = 0;\n retryTicks += delay;\n\n if (drainManager == NULL) {\n \/\/ packet is sent, so find out when the next one is due\n nextPacketTick = states[currState]->nextPacketTick(elasticReq,\n delay);\n Tick nextEventTick = std::min(nextPacketTick, nextTransitionTick);\n schedule(updateEvent, std::max(curTick(), nextEventTick));\n } else {\n \/\/ shut things down\n nextPacketTick = MaxTick;\n nextTransitionTick = MaxTick;\n drainManager->signalDrainDone();\n \/\/ Clear the drain event once we're done with it.\n drainManager = NULL;\n }\n }\n}\n\nvoid\nTrafficGen::regStats()\n{\n \/\/ Initialise all the stats\n using namespace Stats;\n\n numPackets\n .name(name() + \".numPackets\")\n .desc(\"Number of packets generated\");\n\n numRetries\n .name(name() + \".numRetries\")\n .desc(\"Number of retries\");\n\n retryTicks\n .name(name() + \".retryTicks\")\n .desc(\"Time spent waiting due to back-pressure (ticks)\");\n}\n\nbool\nTrafficGen::TrafficGenPort::recvTimingResp(PacketPtr pkt)\n{\n delete pkt->req;\n delete pkt;\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#):$Id$\n\/\/ Author: Andrei Gheata 01\/03\/11\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\/\/ TGeoBranchArray - An array of daughter indices making a geometry path. \n\/\/ Can be used to backup\/restore a state. To setup an object of this type,\n\/\/ one should use:\n\/\/ TGeoBranchArray *array = new TGeoBranchArray(level);\n\/\/ array->InitFromNavigator(nav); (To initialize from current navigator state)\n\/\/ The navigator can be updated to reflect this path array:\n\/\/ array->UpdateNavigator(); \n\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGeoBranchArray.h\"\n\n#include \"TMath.h\"\n#include \"TThread.h\"\n#include \"TString.h\"\n#include \"TGeoMatrix.h\"\n#include \"TGeoNavigator.h\"\n#include \"TGeoManager.h\"\n\nClassImp(TGeoBranchArray)\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::TGeoBranchArray(UShort_t level)\n :fLevel(level),\n fArray(NULL),\n fMatrix(NULL),\n fClient(NULL)\n{\n\/\/ Constructor. Alocates the array with a size given by level.\n fArray = new UShort_t[level];\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::~TGeoBranchArray()\n{\n\/\/ Destructor.\n delete [] fArray;\n delete fMatrix;\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::TGeoBranchArray(const TGeoBranchArray& other)\n :TObject(other),\n fLevel(other.fLevel),\n fArray(NULL),\n fMatrix(NULL),\n fClient(other.fClient)\n{\n\/\/ Copy constructor.\n if (fLevel) fArray = new UShort_t[fLevel];\n if (other.fMatrix) fMatrix = new TGeoHMatrix(*(other.fMatrix));\n} \n \n\/\/______________________________________________________________________________\nTGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other)\n{\n\/\/ Assignment.\n if (&other == this) return *this;\n fLevel = other.fLevel;\n if (fLevel) fArray = new UShort_t[fLevel];\n if (other.fMatrix) {\n fMatrix = new TGeoHMatrix();\n fMatrix->CopyFrom(other.fMatrix);\n }\n fClient = other.fClient;\n return *this;\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::AddLevel(UShort_t dindex)\n{\n\/\/ Add and extra daughter to the current path array. No validity check performed !\n if (!fLevel) {\n Error(\"AddLevel\", \"You must initialize from navigator or copy from another branch array first.\");\n return;\n }\n fLevel++;\n UShort_t *array = new UShort_t[fLevel];\n memcpy(array, fArray, (fLevel-1)*sizeof(UShort_t));\n array[fLevel-1] = dindex;\n delete [] fArray;\n fArray = array;\n} \n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value==0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const\n{\n\/\/ Not equal operator.\n Int_t value = Compare(&other);\n if (value!=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value>0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value<0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value>=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value<=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nLong64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value)\n{\n\/\/ Binary search in an array of n pointers to branch arrays, to locate value.\n\/\/ Returns element index or index of nearest element smaller than value\n Long64_t nabove, nbelow, middle;\n const TGeoBranchArray *pind;\n nabove = n+1;\n nbelow = 0;\n while(nabove-nbelow > 1) {\n middle = (nabove+nbelow)\/2;\n pind = array[middle-1];\n if (*value == *pind) return middle-1;\n if (*value < *pind) nabove = middle;\n else nbelow = middle;\n }\n return nbelow-1;\n} \n\n\/\/______________________________________________________________________________\nInt_t TGeoBranchArray::Compare(const TObject *obj) const\n{\n\/\/ Compare with other object of same type. Returns -1 if this is smaller (first\n\/\/ smaller array value prevails), 0 if equal (size and values) and 1 if this is \n\/\/ larger.\n UShort_t i;\n TGeoBranchArray *other = (TGeoBranchArray*)obj;\n UShort_t otherLevel = other->GetLevel();\n UShort_t maxLevel = TMath::Min(fLevel, otherLevel);\n UShort_t *otherArray = other->GetArray();\n for (i=0; i<maxLevel; i++) {\n if (fArray[i]==otherArray[i]) continue;\n if (fArray[i]<otherArray[i]) return -1;\n return 1;\n }\n if (fLevel==otherLevel) return 0;\n if (fLevel<otherLevel) return -1;\n return 1;\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::CleanMatrix()\n{\n\/\/ Garbage collect the stored matrix.\n delete fMatrix; fMatrix = 0;\n}\n\n\/\/______________________________________________________________________________\nTGeoNode *TGeoBranchArray::GetNode(UShort_t level) const\n{\n TGeoNode *node = gGeoManager->GetTopNode();\n if (!level) return node;\n if (level>fLevel) return NULL;\n for (Int_t i=0; i<level; i++) node = node->GetVolume()->GetNode(fArray[i]);\n return node;\n}\n \n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav)\n{\n\/\/ Init the branch array from current navigator state.\n TThread::Lock();\n UShort_t level = (UShort_t)nav->GetLevel();\n if (!fMatrix) fMatrix = new TGeoHMatrix();\n fMatrix->CopyFrom(nav->GetCurrentMatrix());\n if (!level) {\n\/\/ delete [] fArray; fArray = 0;\n fLevel = 0;\n return;\n }\n if (!fArray || level>fLevel) {\n delete [] fArray; \n fArray = new UShort_t[level];\n }\n fLevel = level;\n TGeoNode *mother = nav->GetMother(fLevel);\n for (Int_t i=fLevel-1; i>=0; i--) {\n TGeoNode *node = nav->GetMother(i);\n Int_t index = mother->GetVolume()->GetIndex(node);\n fArray[fLevel-i-1] = index;\n mother = node;\n } \n TThread::UnLock();\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::GetPath(TString &path) const\n{\n\/\/ Fill path pointed by the array.\n path = \"\/\";\n TGeoNode *node = GetNode(0);\n path += node->GetName();\n for (Int_t i=0; i<fLevel; i++) {\n path += \"\/\";\n node = node->GetVolume()->GetNode(fArray[i]);\n path += node->GetName();\n }\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Print(Option_t *) const\n{\n\/\/ Print branch information\n TString path;\n GetPath(path);\n printf(\"branch: %s\\n\", path.Data());\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down)\n{\n\/\/ Sorting of an array of branch array pointers.\n for (Int_t i=0; i<n; i++) index[i] = i;\n if (down)\n std::sort(index, index + n, compareBAdesc(array));\n else \n std::sort(index, index + n, compareBAasc(array));\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::UpdateNavigator(TGeoNavigator *nav) const\n{\n\/\/ Update the navigator to reflect the branch.\n nav->CdTop();\n for (Int_t i=0; i<fLevel; i++) nav->CdDown(fArray[i]);\n}\n<commit_msg>Fix deadlock in TGeoBranchArray<commit_after>\/\/ @(#):$Id$\n\/\/ Author: Andrei Gheata 01\/03\/11\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\/\/ TGeoBranchArray - An array of daughter indices making a geometry path. \n\/\/ Can be used to backup\/restore a state. To setup an object of this type,\n\/\/ one should use:\n\/\/ TGeoBranchArray *array = new TGeoBranchArray(level);\n\/\/ array->InitFromNavigator(nav); (To initialize from current navigator state)\n\/\/ The navigator can be updated to reflect this path array:\n\/\/ array->UpdateNavigator(); \n\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGeoBranchArray.h\"\n\n#include \"TMath.h\"\n#include \"TThread.h\"\n#include \"TString.h\"\n#include \"TGeoMatrix.h\"\n#include \"TGeoNavigator.h\"\n#include \"TGeoManager.h\"\n\nClassImp(TGeoBranchArray)\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::TGeoBranchArray(UShort_t level)\n :fLevel(level),\n fArray(NULL),\n fMatrix(NULL),\n fClient(NULL)\n{\n\/\/ Constructor. Alocates the array with a size given by level.\n fArray = new UShort_t[level];\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::~TGeoBranchArray()\n{\n\/\/ Destructor.\n delete [] fArray;\n delete fMatrix;\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::TGeoBranchArray(const TGeoBranchArray& other)\n :TObject(other),\n fLevel(other.fLevel),\n fArray(NULL),\n fMatrix(NULL),\n fClient(other.fClient)\n{\n\/\/ Copy constructor.\n if (fLevel) fArray = new UShort_t[fLevel];\n if (other.fMatrix) fMatrix = new TGeoHMatrix(*(other.fMatrix));\n} \n \n\/\/______________________________________________________________________________\nTGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other)\n{\n\/\/ Assignment.\n if (&other == this) return *this;\n TThread::Lock();\n fLevel = other.fLevel;\n if (fLevel) fArray = new UShort_t[fLevel];\n if (other.fMatrix) {\n fMatrix = new TGeoHMatrix();\n fMatrix->CopyFrom(other.fMatrix);\n }\n fClient = other.fClient;\n TThread::UnLock();\n return *this;\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::AddLevel(UShort_t dindex)\n{\n\/\/ Add and extra daughter to the current path array. No validity check performed !\n if (!fLevel) {\n Error(\"AddLevel\", \"You must initialize from navigator or copy from another branch array first.\");\n return;\n }\n fLevel++;\n UShort_t *array = new UShort_t[fLevel];\n memcpy(array, fArray, (fLevel-1)*sizeof(UShort_t));\n array[fLevel-1] = dindex;\n delete [] fArray;\n fArray = array;\n} \n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value==0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const\n{\n\/\/ Not equal operator.\n Int_t value = Compare(&other);\n if (value!=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value>0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value<0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value>=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value<=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nLong64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value)\n{\n\/\/ Binary search in an array of n pointers to branch arrays, to locate value.\n\/\/ Returns element index or index of nearest element smaller than value\n Long64_t nabove, nbelow, middle;\n const TGeoBranchArray *pind;\n nabove = n+1;\n nbelow = 0;\n while(nabove-nbelow > 1) {\n middle = (nabove+nbelow)\/2;\n pind = array[middle-1];\n if (*value == *pind) return middle-1;\n if (*value < *pind) nabove = middle;\n else nbelow = middle;\n }\n return nbelow-1;\n} \n\n\/\/______________________________________________________________________________\nInt_t TGeoBranchArray::Compare(const TObject *obj) const\n{\n\/\/ Compare with other object of same type. Returns -1 if this is smaller (first\n\/\/ smaller array value prevails), 0 if equal (size and values) and 1 if this is \n\/\/ larger.\n UShort_t i;\n TGeoBranchArray *other = (TGeoBranchArray*)obj;\n UShort_t otherLevel = other->GetLevel();\n UShort_t maxLevel = TMath::Min(fLevel, otherLevel);\n UShort_t *otherArray = other->GetArray();\n for (i=0; i<maxLevel; i++) {\n if (fArray[i]==otherArray[i]) continue;\n if (fArray[i]<otherArray[i]) return -1;\n return 1;\n }\n if (fLevel==otherLevel) return 0;\n if (fLevel<otherLevel) return -1;\n return 1;\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::CleanMatrix()\n{\n\/\/ Garbage collect the stored matrix.\n delete fMatrix; fMatrix = 0;\n}\n\n\/\/______________________________________________________________________________\nTGeoNode *TGeoBranchArray::GetNode(UShort_t level) const\n{\n TGeoNode *node = gGeoManager->GetTopNode();\n if (!level) return node;\n if (level>fLevel) return NULL;\n for (Int_t i=0; i<level; i++) node = node->GetVolume()->GetNode(fArray[i]);\n return node;\n}\n \n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav)\n{\n\/\/ Init the branch array from current navigator state.\n TThread::Lock();\n UShort_t level = (UShort_t)nav->GetLevel();\n if (!fMatrix) fMatrix = new TGeoHMatrix();\n fMatrix->CopyFrom(nav->GetCurrentMatrix());\n if (!level) {\n\/\/ delete [] fArray; fArray = 0;\n fLevel = 0;\n TThread::UnLock();\n return;\n }\n if (!fArray || level>fLevel) {\n delete [] fArray; \n fArray = new UShort_t[level];\n }\n fLevel = level;\n TGeoNode *mother = nav->GetMother(fLevel);\n for (Int_t i=fLevel-1; i>=0; i--) {\n TGeoNode *node = nav->GetMother(i);\n Int_t index = mother->GetVolume()->GetIndex(node);\n fArray[fLevel-i-1] = index;\n mother = node;\n } \n TThread::UnLock();\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::GetPath(TString &path) const\n{\n\/\/ Fill path pointed by the array.\n path = \"\/\";\n TGeoNode *node = GetNode(0);\n path += node->GetName();\n for (Int_t i=0; i<fLevel; i++) {\n path += \"\/\";\n node = node->GetVolume()->GetNode(fArray[i]);\n path += node->GetName();\n }\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Print(Option_t *) const\n{\n\/\/ Print branch information\n TString path;\n GetPath(path);\n printf(\"branch: %s\\n\", path.Data());\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down)\n{\n\/\/ Sorting of an array of branch array pointers.\n for (Int_t i=0; i<n; i++) index[i] = i;\n if (down)\n std::sort(index, index + n, compareBAdesc(array));\n else \n std::sort(index, index + n, compareBAasc(array));\n} \n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::UpdateNavigator(TGeoNavigator *nav) const\n{\n\/\/ Update the navigator to reflect the branch.\n nav->CdTop();\n for (Int_t i=0; i<fLevel; i++) nav->CdDown(fArray[i]);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>crosstool's gcc gives lots of warnings like \"warning: suggest parentheses around && within ||\" For base\/string_util.cc, just add the suggested parentheses.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n SVGMin - Aggressive SVG minifier\n\n Copyright (C) 2009 Ariya Hidayat (ariya.hidayat@gmail.com)\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\n#include \"svgminifier.h\"\n\n#include <QtCore>\n\n#include \"qcssparser_p.h\"\n\nclass SvgMinifier::Private\n{\npublic:\n QString inFile;\n QString outFile;\n bool autoFormat;\n QStringList excludedTags;\n QStringList excludedPrefixes;\n QStringList excludedId;\n};\n\nSvgMinifier::SvgMinifier()\n{\n d = new Private;\n d->autoFormat = false;\n}\n\nSvgMinifier::~SvgMinifier()\n{\n delete d;\n}\n\nvoid SvgMinifier::setInputFile(const QString &in)\n{\n d->inFile = in;\n}\n\nvoid SvgMinifier::setOutputFile(const QString &out)\n{\n d->outFile = out;\n}\n\nvoid SvgMinifier::setAutoFormat(bool format)\n{\n d->autoFormat = format;\n}\n\nvoid SvgMinifier::addTagExclude(const QString &tag)\n{\n d->excludedTags += tag;\n}\n\nvoid SvgMinifier::addPrefixExclude(const QString &prefix)\n{\n d->excludedPrefixes += prefix;\n}\n\nvoid SvgMinifier::addIdExclude(const QString &id)\n{\n d->excludedId += id;\n}\n\nstatic bool listContains(const QStringList &list, const QStringRef &str)\n{\n if (str.isEmpty())\n return false;\n QString check = str.toString();\n foreach (const QString &s, list)\n if (check.startsWith(s))\n return true;\n return false;\n}\n\n\nstatic QXmlStreamAttributes parseStyle(const QStringRef &styleRef)\n{\n QXmlStreamAttributes attributes;\n QCss::Parser parser;\n\n parser.init(styleRef.toString());\n QString key;\n\n while (parser.hasNext()) {\n parser.skipSpace();\n\n if (!parser.hasNext())\n break;\n parser.next();\n\n QString name = parser.lexem();\n\n parser.skipSpace();\n if (!parser.test(QCss::COLON))\n break;\n\n parser.skipSpace();\n if (!parser.hasNext())\n break;\n\n const int firstSymbol = parser.index;\n int symbolCount = 0;\n do {\n parser.next();\n ++symbolCount;\n } while (parser.hasNext() && !parser.test(QCss::SEMICOLON));\n\n QString value;\n for (int i = firstSymbol; i < firstSymbol + symbolCount; ++i)\n value += parser.symbols.at(i).lexem();\n\n parser.skipSpace();\n\n attributes.append(name, value);\n }\n\n return attributes;\n}\n\n\/\/ take the value of the \"style\" attribute, parse it and then\n\/\/ merged the result with other XML attributes\nstatic QXmlStreamAttributes mergedStyle(const QXmlStreamAttributes &attributes)\n{\n if (!attributes.hasAttribute(\"style\"))\n return attributes;\n\n QXmlStreamAttributes result;\n result.reserve(attributes.count());\n\n foreach (const QXmlStreamAttribute &attr, attributes)\n if (attr.name() != \"style\")\n result += attr;\n\n QXmlStreamAttributes styles = parseStyle(attributes.value(\"style\"));\n foreach (const QXmlStreamAttribute &attr, styles)\n if (!attributes.hasAttribute(attr.value().toString()))\n result += attr;\n\n return result;\n}\n\nstatic bool isDrawingNode(const QStringRef &str)\n{\n if (str == QLatin1String(\"linearGradient\"))\n return false;\n if (str == QLatin1String(\"path\"))\n return true;\n if (str == QLatin1String(\"text\"))\n return true;\n if (str == QLatin1String(\"g\"))\n return true;\n if (str == QLatin1String(\"rect\"))\n return true;\n if (str == QLatin1String(\"circle\"))\n return true;\n if (str == QLatin1String(\"polygon\"))\n return true;\n if (str == QLatin1String(\"polyline\"))\n return true;\n return false;\n}\n\nvoid SvgMinifier::run()\n{\n QFile file;\n file.setFileName(d->inFile);\n if (!file.open(QFile::ReadOnly))\n return;\n\n QFile result;\n if (!d->outFile.isEmpty()) {\n result.setFileName(d->outFile);\n result.open(QFile::WriteOnly);\n } else {\n result.open(stdout, QFile::WriteOnly);\n }\n\n QXmlStreamReader *xml = new QXmlStreamReader(&file);\n xml->setNamespaceProcessing(false);\n QXmlStreamWriter *out = new QXmlStreamWriter(&result);\n out->setAutoFormatting(d->autoFormat);\n\n bool skip;\n QStack<bool> skipElement;\n skipElement.push(false);\n\n while (!xml->atEnd()) {\n switch (xml->readNext()) {\n\n case QXmlStreamReader::StartDocument:\n out->writeStartDocument(xml->documentVersion().toString(),\n xml->isStandaloneDocument());\n break;\n\n case QXmlStreamReader::EndDocument:\n out->writeEndDocument();\n break;\n\n case QXmlStreamReader::StartElement:\n if (skipElement.top()) {\n skipElement.push(true);\n } else {\n skip = listContains(d->excludedPrefixes, xml->prefix());\n skip = skip || d->excludedTags.contains(xml->name().toString());\n skipElement.push(skip);\n if (!skip) {\n const QStringRef &tag = xml->qualifiedName();\n out->writeStartElement(tag.toString());\n QXmlStreamAttributes attr = mergedStyle(xml->attributes());\n foreach (const QXmlStreamAttribute &a, attr) {\n if (listContains(d->excludedPrefixes, a.prefix()))\n continue;\n if (a.qualifiedName() == \"id\" && isDrawingNode(tag))\n if (listContains(d->excludedId, a.value()))\n continue;\n out->writeAttribute(a);\n }\n }\n }\n break;\n\n case QXmlStreamReader::EndElement:\n skip = skipElement.pop();\n if (!skip)\n out->writeEndElement();\n break;\n\n case QXmlStreamReader::Characters:\n if (!skipElement.top())\n out->writeCharacters(xml->text().toString());\n break;\n\n case QXmlStreamReader::ProcessingInstruction:\n out->writeProcessingInstruction(xml->processingInstructionTarget().toString(),\n xml->processingInstructionData().toString());\n break;\n\n default:\n break;\n }\n }\n\n file.close();\n result.close();\n}\n\n\n<commit_msg>Handle CDATA differently than normal text.<commit_after>\/*\n SVGMin - Aggressive SVG minifier\n\n Copyright (C) 2009 Ariya Hidayat (ariya.hidayat@gmail.com)\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\n#include \"svgminifier.h\"\n\n#include <QtCore>\n\n#include \"qcssparser_p.h\"\n\nclass SvgMinifier::Private\n{\npublic:\n QString inFile;\n QString outFile;\n bool autoFormat;\n QStringList excludedTags;\n QStringList excludedPrefixes;\n QStringList excludedId;\n};\n\nSvgMinifier::SvgMinifier()\n{\n d = new Private;\n d->autoFormat = false;\n}\n\nSvgMinifier::~SvgMinifier()\n{\n delete d;\n}\n\nvoid SvgMinifier::setInputFile(const QString &in)\n{\n d->inFile = in;\n}\n\nvoid SvgMinifier::setOutputFile(const QString &out)\n{\n d->outFile = out;\n}\n\nvoid SvgMinifier::setAutoFormat(bool format)\n{\n d->autoFormat = format;\n}\n\nvoid SvgMinifier::addTagExclude(const QString &tag)\n{\n d->excludedTags += tag;\n}\n\nvoid SvgMinifier::addPrefixExclude(const QString &prefix)\n{\n d->excludedPrefixes += prefix;\n}\n\nvoid SvgMinifier::addIdExclude(const QString &id)\n{\n d->excludedId += id;\n}\n\nstatic bool listContains(const QStringList &list, const QStringRef &str)\n{\n if (str.isEmpty())\n return false;\n QString check = str.toString();\n foreach (const QString &s, list)\n if (check.startsWith(s))\n return true;\n return false;\n}\n\n\nstatic QXmlStreamAttributes parseStyle(const QStringRef &styleRef)\n{\n QXmlStreamAttributes attributes;\n QCss::Parser parser;\n\n parser.init(styleRef.toString());\n QString key;\n\n while (parser.hasNext()) {\n parser.skipSpace();\n\n if (!parser.hasNext())\n break;\n parser.next();\n\n QString name = parser.lexem();\n\n parser.skipSpace();\n if (!parser.test(QCss::COLON))\n break;\n\n parser.skipSpace();\n if (!parser.hasNext())\n break;\n\n const int firstSymbol = parser.index;\n int symbolCount = 0;\n do {\n parser.next();\n ++symbolCount;\n } while (parser.hasNext() && !parser.test(QCss::SEMICOLON));\n\n QString value;\n for (int i = firstSymbol; i < firstSymbol + symbolCount; ++i)\n value += parser.symbols.at(i).lexem();\n\n parser.skipSpace();\n\n attributes.append(name, value);\n }\n\n return attributes;\n}\n\n\/\/ take the value of the \"style\" attribute, parse it and then\n\/\/ merged the result with other XML attributes\nstatic QXmlStreamAttributes mergedStyle(const QXmlStreamAttributes &attributes)\n{\n if (!attributes.hasAttribute(\"style\"))\n return attributes;\n\n QXmlStreamAttributes result;\n result.reserve(attributes.count());\n\n foreach (const QXmlStreamAttribute &attr, attributes)\n if (attr.name() != \"style\")\n result += attr;\n\n QXmlStreamAttributes styles = parseStyle(attributes.value(\"style\"));\n foreach (const QXmlStreamAttribute &attr, styles)\n if (!attributes.hasAttribute(attr.value().toString()))\n result += attr;\n\n return result;\n}\n\nstatic bool isDrawingNode(const QStringRef &str)\n{\n if (str == QLatin1String(\"linearGradient\"))\n return false;\n if (str == QLatin1String(\"path\"))\n return true;\n if (str == QLatin1String(\"text\"))\n return true;\n if (str == QLatin1String(\"g\"))\n return true;\n if (str == QLatin1String(\"rect\"))\n return true;\n if (str == QLatin1String(\"circle\"))\n return true;\n if (str == QLatin1String(\"polygon\"))\n return true;\n if (str == QLatin1String(\"polyline\"))\n return true;\n return false;\n}\n\nvoid SvgMinifier::run()\n{\n QFile file;\n file.setFileName(d->inFile);\n if (!file.open(QFile::ReadOnly))\n return;\n\n QFile result;\n if (!d->outFile.isEmpty()) {\n result.setFileName(d->outFile);\n result.open(QFile::WriteOnly);\n } else {\n result.open(stdout, QFile::WriteOnly);\n }\n\n QXmlStreamReader *xml = new QXmlStreamReader(&file);\n xml->setNamespaceProcessing(false);\n QXmlStreamWriter *out = new QXmlStreamWriter(&result);\n out->setAutoFormatting(d->autoFormat);\n\n bool skip;\n QStack<bool> skipElement;\n skipElement.push(false);\n\n while (!xml->atEnd()) {\n switch (xml->readNext()) {\n\n case QXmlStreamReader::StartDocument:\n out->writeStartDocument(xml->documentVersion().toString(),\n xml->isStandaloneDocument());\n break;\n\n case QXmlStreamReader::EndDocument:\n out->writeEndDocument();\n break;\n\n case QXmlStreamReader::StartElement:\n if (skipElement.top()) {\n skipElement.push(true);\n } else {\n skip = listContains(d->excludedPrefixes, xml->prefix());\n skip = skip || d->excludedTags.contains(xml->name().toString());\n skipElement.push(skip);\n if (!skip) {\n const QStringRef &tag = xml->qualifiedName();\n out->writeStartElement(tag.toString());\n QXmlStreamAttributes attr = mergedStyle(xml->attributes());\n foreach (const QXmlStreamAttribute &a, attr) {\n if (listContains(d->excludedPrefixes, a.prefix()))\n continue;\n if (a.qualifiedName() == \"id\" && isDrawingNode(tag))\n if (listContains(d->excludedId, a.value()))\n continue;\n out->writeAttribute(a);\n }\n }\n }\n break;\n\n case QXmlStreamReader::EndElement:\n skip = skipElement.pop();\n if (!skip)\n out->writeEndElement();\n break;\n\n case QXmlStreamReader::Characters:\n if (!skipElement.top()) {\n if (xml->isCDATA())\n out->writeCDATA(xml->text().toString());\n else\n out->writeCharacters(xml->text().toString());\n }\n break;\n\n case QXmlStreamReader::ProcessingInstruction:\n out->writeProcessingInstruction(xml->processingInstructionTarget().toString(),\n xml->processingInstructionData().toString());\n break;\n\n default:\n break;\n }\n }\n\n file.close();\n result.close();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\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 \"paddle\/fluid\/operators\/dot_op.h\"\n\nnamespace paddle {\nnamespace operators {\n\nclass DotOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE_EQ(true, ctx->HasInput(\"X\"),\n platform::errors::PreconditionNotMet(\n \"Input(X) of DotOp should not be null.\"));\n PADDLE_ENFORCE_EQ(true, ctx->HasInput(\"Y\"),\n platform::errors::PreconditionNotMet(\n \"Input(Y) of DotOp should not be null.\"));\n PADDLE_ENFORCE_EQ(true, ctx->HasOutput(\"Out\"),\n platform::errors::PreconditionNotMet(\n \"Output(Out) of DotOp should not be null.\"));\n\n auto x_dims = ctx->GetInputDim(\"X\");\n auto x_rank = static_cast<size_t>(x_dims.size());\n PADDLE_ENFORCE_EQ(true, 1 == x_rank || 2 == x_rank,\n platform::errors::PreconditionNotMet(\n \"ShapeError: The dimensions of input tensor X (%s) \"\n \"should be 1 or 2\",\n x_dims.to_str()));\n\n auto y_dims = ctx->GetInputDim(\"Y\");\n PADDLE_ENFORCE_EQ(\n true, x_rank == (size_t)y_dims.size(),\n platform::errors::PreconditionNotMet(\n \"ShapeError: The shape of input tensor Y: %s should match with \"\n \"input tenosr X: %s\",\n y_dims.to_str(), x_dims.to_str()));\n bool shape_match = true;\n for (size_t i = 0; i < x_rank; ++i) {\n if (x_dims[i] != y_dims[i]) {\n shape_match = false;\n break;\n }\n }\n\n PADDLE_ENFORCE_EQ(true, shape_match,\n platform::errors::PreconditionNotMet(\n \"ShapeError: The shape of input tensor X: %s should \"\n \"be exactly the same \"\n \"with input tensor Y: %s\",\n x_dims.to_str(), y_dims.to_str()));\n auto dims = vectorize(x_dims);\n dims[dims.size() - 1] = 1;\n ctx->SetOutputDim(\"Out\", phi::make_ddim(dims));\n }\n\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n return framework::OpKernelType(\n OperatorWithKernel::IndicateVarDataType(ctx, \"X\"), ctx.GetPlace());\n }\n};\n\nclass DotOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() final {\n AddInput(\"X\", \"(Tensor) The first input tensor. \");\n AddInput(\"Y\", \"(Tensor) The second input tensor. \");\n AddOutput(\"Out\", \"(Tensor) The result tensor.\");\n AddComment(\"\");\n }\n};\n\nclass DotGradOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE_EQ(\n true, ctx->HasInput(\"X\"),\n platform::errors::PreconditionNotMet(\"Input(X) should not be null.\"));\n PADDLE_ENFORCE_EQ(\n true, ctx->HasInput(\"Y\"),\n platform::errors::PreconditionNotMet(\"Input(Y) should not be null.\"));\n PADDLE_ENFORCE_EQ(true, ctx->HasInput(framework::GradVarName(\"Out\")),\n platform::errors::PreconditionNotMet(\n \"Input(Out@GRAD) should not be null.\"));\n\n auto x_grad_name = framework::GradVarName(\"X\");\n auto y_grad_name = framework::GradVarName(\"Y\");\n if (ctx->HasOutput(x_grad_name)) {\n ctx->ShareDim(\"X\", \/*->*\/ x_grad_name);\n ctx->ShareLoD(\"X\", \/*->*\/ x_grad_name);\n }\n if (ctx->HasOutput(y_grad_name)) {\n ctx->ShareDim(\"Y\", \/*->*\/ y_grad_name);\n ctx->ShareLoD(\"Y\", \/*->*\/ y_grad_name);\n }\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(\n ctx, framework::GradVarName(\"Out\")),\n ctx.GetPlace());\n }\n};\n\ntemplate <typename T>\nclass DotOpGradMaker : public framework::SingleGradOpMaker<T> {\n public:\n using framework::SingleGradOpMaker<T>::SingleGradOpMaker;\n\n protected:\n void Apply(GradOpPtr<T> op) const override {\n op->SetType(\"dot_grad\");\n\n op->SetInput(\"X\", this->Input(\"X\"));\n op->SetInput(\"Y\", this->Input(\"Y\"));\n op->SetInput(framework::GradVarName(\"Out\"), this->OutputGrad(\"Out\"));\n op->SetAttrMap(this->Attrs());\n op->SetOutput(framework::GradVarName(\"X\"), this->InputGrad(\"X\"));\n op->SetOutput(framework::GradVarName(\"Y\"), this->InputGrad(\"Y\"));\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(dot, ops::DotOp, ops::DotOpMaker,\n ops::DotOpGradMaker<paddle::framework::OpDesc>,\n ops::DotOpGradMaker<paddle::imperative::OpBase>);\n\nREGISTER_OPERATOR(dot_grad, ops::DotGradOp);\n\nREGISTER_OP_CPU_KERNEL(\n dot, ops::DotKernel<paddle::platform::CPUDeviceContext, float>,\n ops::DotKernel<paddle::platform::CPUDeviceContext, double>,\n ops::DotKernel<paddle::platform::CPUDeviceContext, int>,\n ops::DotKernel<paddle::platform::CPUDeviceContext, int64_t>,\n ops::DotKernel<paddle::platform::CPUDeviceContext,\n paddle::platform::complex<float>>,\n ops::DotKernel<paddle::platform::CPUDeviceContext,\n paddle::platform::complex<double>>);\nREGISTER_OP_CPU_KERNEL(\n dot_grad, ops::DotGradKernel<paddle::platform::CPUDeviceContext, float>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext, double>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext, int>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext, int64_t>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext,\n paddle::platform::complex<float>>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext,\n paddle::platform::complex<double>>);\n<commit_msg>remove dot infershape (#39945)<commit_after>\/\/ Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\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 \"paddle\/fluid\/operators\/dot_op.h\"\n\n#include \"paddle\/fluid\/framework\/infershape_utils.h\"\n#include \"paddle\/phi\/core\/infermeta_utils.h\"\n#include \"paddle\/phi\/infermeta\/binary.h\"\n\nnamespace paddle {\nnamespace operators {\n\nclass DotOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n return framework::OpKernelType(\n OperatorWithKernel::IndicateVarDataType(ctx, \"X\"), ctx.GetPlace());\n }\n};\n\nclass DotOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() final {\n AddInput(\"X\", \"(Tensor) The first input tensor. \");\n AddInput(\"Y\", \"(Tensor) The second input tensor. \");\n AddOutput(\"Out\", \"(Tensor) The result tensor.\");\n AddComment(\"\");\n }\n};\n\nclass DotGradOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE_EQ(\n true, ctx->HasInput(\"X\"),\n platform::errors::PreconditionNotMet(\"Input(X) should not be null.\"));\n PADDLE_ENFORCE_EQ(\n true, ctx->HasInput(\"Y\"),\n platform::errors::PreconditionNotMet(\"Input(Y) should not be null.\"));\n PADDLE_ENFORCE_EQ(true, ctx->HasInput(framework::GradVarName(\"Out\")),\n platform::errors::PreconditionNotMet(\n \"Input(Out@GRAD) should not be null.\"));\n\n auto x_grad_name = framework::GradVarName(\"X\");\n auto y_grad_name = framework::GradVarName(\"Y\");\n if (ctx->HasOutput(x_grad_name)) {\n ctx->ShareDim(\"X\", \/*->*\/ x_grad_name);\n ctx->ShareLoD(\"X\", \/*->*\/ x_grad_name);\n }\n if (ctx->HasOutput(y_grad_name)) {\n ctx->ShareDim(\"Y\", \/*->*\/ y_grad_name);\n ctx->ShareLoD(\"Y\", \/*->*\/ y_grad_name);\n }\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(\n ctx, framework::GradVarName(\"Out\")),\n ctx.GetPlace());\n }\n};\n\ntemplate <typename T>\nclass DotOpGradMaker : public framework::SingleGradOpMaker<T> {\n public:\n using framework::SingleGradOpMaker<T>::SingleGradOpMaker;\n\n protected:\n void Apply(GradOpPtr<T> op) const override {\n op->SetType(\"dot_grad\");\n\n op->SetInput(\"X\", this->Input(\"X\"));\n op->SetInput(\"Y\", this->Input(\"Y\"));\n op->SetInput(framework::GradVarName(\"Out\"), this->OutputGrad(\"Out\"));\n op->SetAttrMap(this->Attrs());\n op->SetOutput(framework::GradVarName(\"X\"), this->InputGrad(\"X\"));\n op->SetOutput(framework::GradVarName(\"Y\"), this->InputGrad(\"Y\"));\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nDELCARE_INFER_SHAPE_FUNCTOR(dot, DotInferShapeFunctor,\n PT_INFER_META(phi::DotInferMeta));\n\nREGISTER_OPERATOR(dot, ops::DotOp, ops::DotOpMaker,\n ops::DotOpGradMaker<paddle::framework::OpDesc>,\n ops::DotOpGradMaker<paddle::imperative::OpBase>,\n DotInferShapeFunctor);\n\nREGISTER_OPERATOR(dot_grad, ops::DotGradOp);\n\nREGISTER_OP_CPU_KERNEL(\n dot, ops::DotKernel<paddle::platform::CPUDeviceContext, float>,\n ops::DotKernel<paddle::platform::CPUDeviceContext, double>,\n ops::DotKernel<paddle::platform::CPUDeviceContext, int>,\n ops::DotKernel<paddle::platform::CPUDeviceContext, int64_t>,\n ops::DotKernel<paddle::platform::CPUDeviceContext,\n paddle::platform::complex<float>>,\n ops::DotKernel<paddle::platform::CPUDeviceContext,\n paddle::platform::complex<double>>);\nREGISTER_OP_CPU_KERNEL(\n dot_grad, ops::DotGradKernel<paddle::platform::CPUDeviceContext, float>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext, double>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext, int>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext, int64_t>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext,\n paddle::platform::complex<float>>,\n ops::DotGradKernel<paddle::platform::CPUDeviceContext,\n paddle::platform::complex<double>>);\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. 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,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include <cstdint>\n#include <cstdlib>\n#include <ostream>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <gflags\/gflags.h>\n#include <gflags\/gflags_declare.h>\n#include <glog\/logging.h>\n#include <gtest\/gtest.h>\n\n#include \"kudu\/client\/callbacks.h\"\n#include \"kudu\/client\/client.h\"\n#include \"kudu\/client\/row_result.h\"\n#include \"kudu\/client\/schema.h\"\n#include \"kudu\/client\/shared_ptr.h\"\n#include \"kudu\/client\/write_op.h\"\n#include \"kudu\/common\/partial_row.h\"\n#include \"kudu\/gutil\/gscoped_ptr.h\"\n#include \"kudu\/gutil\/port.h\"\n#include \"kudu\/gutil\/ref_counted.h\"\n#include \"kudu\/gutil\/strings\/strcat.h\"\n#include \"kudu\/master\/mini_master.h\"\n#include \"kudu\/mini-cluster\/internal_mini_cluster.h\"\n#include \"kudu\/tserver\/mini_tablet_server.h\"\n#include \"kudu\/util\/async_util.h\"\n#include \"kudu\/util\/countdown_latch.h\"\n#include \"kudu\/util\/curl_util.h\"\n#include \"kudu\/util\/faststring.h\"\n#include \"kudu\/util\/monotime.h\"\n#include \"kudu\/util\/net\/sockaddr.h\"\n#include \"kudu\/util\/status.h\"\n#include \"kudu\/util\/stopwatch.h\"\n#include \"kudu\/util\/test_macros.h\"\n#include \"kudu\/util\/test_util.h\"\n#include \"kudu\/util\/thread.h\"\n\nDECLARE_int32(flush_threshold_mb);\nDECLARE_int32(log_segment_size_mb);\nDECLARE_int32(maintenance_manager_polling_interval_ms);\nDEFINE_int32(mbs_for_flushes_and_rolls, 1, \"How many MBs are needed to flush and roll\");\nDEFINE_int32(row_count, 2000, \"How many rows will be used in this test for the base data\");\nDEFINE_int32(seconds_to_run, 4,\n \"How long this test runs for, after inserting the base data, in seconds\");\n\nusing std::string;\nusing std::vector;\n\nnamespace kudu {\nnamespace tablet {\n\nusing client::KuduInsert;\nusing client::KuduClient;\nusing client::KuduClientBuilder;\nusing client::KuduColumnSchema;\nusing client::KuduRowResult;\nusing client::KuduScanner;\nusing client::KuduSchema;\nusing client::KuduSchemaBuilder;\nusing client::KuduSession;\nusing client::KuduStatusCallback;\nusing client::KuduStatusMemberCallback;\nusing client::KuduTable;\nusing client::KuduTableCreator;\nusing client::KuduUpdate;\nusing client::sp::shared_ptr;\nusing cluster::InternalMiniCluster;\nusing cluster::InternalMiniClusterOptions;\n\n\/\/ This integration test tries to trigger all the update-related bits while also serving as a\n\/\/ foundation for benchmarking. It first inserts 'row_count' rows and then starts two threads,\n\/\/ one that continuously updates all the rows sequentially and one that scans them all, until\n\/\/ it's been running for 'seconds_to_run'. It doesn't test for correctness, unless something\n\/\/ FATALs.\nclass UpdateScanDeltaCompactionTest : public KuduTest {\n protected:\n UpdateScanDeltaCompactionTest() {\n KuduSchemaBuilder b;\n b.AddColumn(\"key\")->Type(KuduColumnSchema::INT64)->NotNull()->PrimaryKey();\n b.AddColumn(\"string\")->Type(KuduColumnSchema::STRING)->NotNull();\n b.AddColumn(\"int64\")->Type(KuduColumnSchema::INT64)->NotNull();\n CHECK_OK(b.Build(&schema_));\n }\n\n virtual void SetUp() OVERRIDE {\n KuduTest::SetUp();\n }\n\n void CreateTable() {\n ASSERT_NO_FATAL_FAILURE(InitCluster());\n gscoped_ptr<KuduTableCreator> table_creator(client_->NewTableCreator());\n ASSERT_OK(table_creator->table_name(kTableName)\n .schema(&schema_)\n .set_range_partition_columns({ \"key\" })\n .num_replicas(1)\n .Create());\n ASSERT_OK(client_->OpenTable(kTableName, &table_));\n }\n\n virtual void TearDown() OVERRIDE {\n if (cluster_) {\n cluster_->Shutdown();\n }\n KuduTest::TearDown();\n }\n\n \/\/ Inserts row_count rows sequentially.\n void InsertBaseData();\n\n \/\/ Starts the update and scan threads then stops them after seconds_to_run.\n void RunThreads();\n\n private:\n enum {\n kKeyCol,\n kStrCol,\n kInt64Col\n };\n static const char* const kTableName;\n\n void InitCluster() {\n \/\/ Start mini-cluster with 1 tserver.\n cluster_.reset(new InternalMiniCluster(env_, InternalMiniClusterOptions()));\n ASSERT_OK(cluster_->Start());\n KuduClientBuilder client_builder;\n client_builder.add_master_server_addr(\n cluster_->mini_master()->bound_rpc_addr_str());\n ASSERT_OK(client_builder.Build(&client_));\n }\n\n shared_ptr<KuduSession> CreateSession() {\n shared_ptr<KuduSession> session = client_->NewSession();\n session->SetTimeoutMillis(5000);\n CHECK_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH));\n return session;\n }\n\n \/\/ Continuously updates the existing data until 'stop_latch' drops to 0.\n void UpdateRows(CountDownLatch* stop_latch);\n\n \/\/ Continuously scans the data until 'stop_latch' drops to 0.\n void ScanRows(CountDownLatch* stop_latch) const;\n\n \/\/ Continuously fetch various web pages on the TS.\n void CurlWebPages(CountDownLatch* stop_latch) const;\n\n \/\/ Sets the passed values on the row.\n \/\/ TODO randomize the string column.\n void MakeRow(int64_t key, int64_t val, KuduPartialRow* row) const;\n\n \/\/ If 'key' is a multiple of kSessionBatchSize, it uses 'last_s' to wait for the previous batch\n \/\/ to finish and then flushes the current one.\n Status WaitForLastBatchAndFlush(int64_t key,\n Synchronizer* last_s,\n KuduStatusCallback* last_s_cb,\n shared_ptr<KuduSession> session);\n\n KuduSchema schema_;\n std::shared_ptr<InternalMiniCluster> cluster_;\n shared_ptr<KuduTable> table_;\n shared_ptr<KuduClient> client_;\n};\n\nconst char* const UpdateScanDeltaCompactionTest::kTableName = \"update-scan-delta-compact-tbl\";\nconst int kSessionBatchSize = 1000;\n\nTEST_F(UpdateScanDeltaCompactionTest, TestAll) {\n OverrideFlagForSlowTests(\"seconds_to_run\", \"100\");\n OverrideFlagForSlowTests(\"row_count\", \"1000000\");\n OverrideFlagForSlowTests(\"mbs_for_flushes_and_rolls\", \"8\");\n \/\/ Setting this high enough that we see the effects of flushes and compactions.\n OverrideFlagForSlowTests(\"maintenance_manager_polling_interval_ms\", \"2000\");\n FLAGS_flush_threshold_mb = FLAGS_mbs_for_flushes_and_rolls;\n FLAGS_log_segment_size_mb = FLAGS_mbs_for_flushes_and_rolls;\n if (!AllowSlowTests()) {\n \/\/ Make it run more often since it's not a long test.\n FLAGS_maintenance_manager_polling_interval_ms = 50;\n }\n\n ASSERT_NO_FATAL_FAILURE(CreateTable());\n ASSERT_NO_FATAL_FAILURE(InsertBaseData());\n ASSERT_NO_FATAL_FAILURE(RunThreads());\n}\n\nvoid UpdateScanDeltaCompactionTest::InsertBaseData() {\n shared_ptr<KuduSession> session = CreateSession();\n Synchronizer last_s;\n KuduStatusMemberCallback<Synchronizer> last_s_cb(&last_s,\n &Synchronizer::StatusCB);\n last_s_cb.Run(Status::OK());\n\n LOG_TIMING(INFO, \"Insert\") {\n for (int64_t key = 0; key < FLAGS_row_count; key++) {\n gscoped_ptr<KuduInsert> insert(table_->NewInsert());\n MakeRow(key, 0, insert->mutable_row());\n ASSERT_OK(session->Apply(insert.release()));\n ASSERT_OK(WaitForLastBatchAndFlush(key, &last_s, &last_s_cb, session));\n }\n ASSERT_OK(WaitForLastBatchAndFlush(kSessionBatchSize, &last_s, &last_s_cb, session));\n ASSERT_OK(last_s.Wait());\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::RunThreads() {\n vector<scoped_refptr<Thread> > threads;\n\n CountDownLatch stop_latch(1);\n\n {\n scoped_refptr<Thread> t;\n ASSERT_OK(Thread::Create(CURRENT_TEST_NAME(),\n StrCat(CURRENT_TEST_CASE_NAME(), \"-update\"),\n &UpdateScanDeltaCompactionTest::UpdateRows, this,\n &stop_latch, &t));\n threads.push_back(t);\n }\n\n {\n scoped_refptr<Thread> t;\n ASSERT_OK(Thread::Create(CURRENT_TEST_NAME(),\n StrCat(CURRENT_TEST_CASE_NAME(), \"-scan\"),\n &UpdateScanDeltaCompactionTest::ScanRows, this,\n &stop_latch, &t));\n threads.push_back(t);\n }\n\n {\n scoped_refptr<Thread> t;\n ASSERT_OK(Thread::Create(CURRENT_TEST_NAME(),\n StrCat(CURRENT_TEST_CASE_NAME(), \"-curl\"),\n &UpdateScanDeltaCompactionTest::CurlWebPages, this,\n &stop_latch, &t));\n threads.push_back(t);\n }\n\n SleepFor(MonoDelta::FromSeconds(FLAGS_seconds_to_run * 1.0));\n stop_latch.CountDown();\n\n for (const scoped_refptr<Thread>& thread : threads) {\n ASSERT_OK(ThreadJoiner(thread.get())\n .warn_every_ms(500)\n .Join());\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::UpdateRows(CountDownLatch* stop_latch) {\n shared_ptr<KuduSession> session = CreateSession();\n Synchronizer last_s;\n KuduStatusMemberCallback<Synchronizer> last_s_cb(&last_s,\n &Synchronizer::StatusCB);\n\n for (int64_t iteration = 1; stop_latch->count() > 0; iteration++) {\n last_s_cb.Run(Status::OK());\n LOG_TIMING(INFO, \"Update\") {\n for (int64_t key = 0; key < FLAGS_row_count && stop_latch->count() > 0; key++) {\n gscoped_ptr<KuduUpdate> update(table_->NewUpdate());\n MakeRow(key, iteration, update->mutable_row());\n CHECK_OK(session->Apply(update.release()));\n CHECK_OK(WaitForLastBatchAndFlush(key, &last_s, &last_s_cb, session));\n }\n CHECK_OK(WaitForLastBatchAndFlush(kSessionBatchSize, &last_s, &last_s_cb, session));\n CHECK_OK(last_s.Wait());\n }\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::ScanRows(CountDownLatch* stop_latch) const {\n while (stop_latch->count() > 0) {\n KuduScanner scanner(table_.get());\n \/\/ Sometimes use fault-tolerant scans, to get more coverage of the\n \/\/ MergeIterator code paths.\n if (rand() % 2 == 1) {\n CHECK_OK(scanner.SetFaultTolerant());\n }\n LOG_TIMING(INFO, \"Scan\") {\n CHECK_OK(scanner.Open());\n vector<KuduRowResult> rows;\n while (scanner.HasMoreRows()) {\n CHECK_OK(scanner.NextBatch(&rows));\n }\n }\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::CurlWebPages(CountDownLatch* stop_latch) const {\n vector<string> urls;\n string base_url = cluster_->mini_tablet_server(0)->bound_http_addr().ToString();\n urls.push_back(base_url + \"\/scans\");\n urls.push_back(base_url + \"\/transactions\");\n\n EasyCurl curl;\n faststring dst;\n while (stop_latch->count() > 0) {\n for (const string& url : urls) {\n VLOG(1) << \"Curling URL \" << url;\n Status status = curl.FetchURL(url, &dst);\n if (status.ok()) {\n CHECK_GT(dst.length(), 0);\n }\n }\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::MakeRow(int64_t key,\n int64_t val,\n KuduPartialRow* row) const {\n CHECK_OK(row->SetInt64(kKeyCol, key));\n CHECK_OK(row->SetStringCopy(kStrCol, \"TODO random string\"));\n CHECK_OK(row->SetInt64(kInt64Col, val));\n}\n\nStatus UpdateScanDeltaCompactionTest::WaitForLastBatchAndFlush(int64_t key,\n Synchronizer* last_s,\n KuduStatusCallback* last_s_cb,\n shared_ptr<KuduSession> session) {\n if (key % kSessionBatchSize == 0) {\n RETURN_NOT_OK(last_s->Wait());\n last_s->Reset();\n session->FlushAsync(last_s_cb);\n }\n return Status::OK();\n}\n\n} \/\/ namespace tablet\n} \/\/ namespace kudu\n<commit_msg>KUDU-2222. update_scan_delta_compact-test: increase write timeout<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. 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,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include <cstdint>\n#include <cstdlib>\n#include <ostream>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <gflags\/gflags.h>\n#include <gflags\/gflags_declare.h>\n#include <glog\/logging.h>\n#include <gtest\/gtest.h>\n\n#include \"kudu\/client\/callbacks.h\"\n#include \"kudu\/client\/client.h\"\n#include \"kudu\/client\/row_result.h\"\n#include \"kudu\/client\/schema.h\"\n#include \"kudu\/client\/shared_ptr.h\"\n#include \"kudu\/client\/write_op.h\"\n#include \"kudu\/common\/partial_row.h\"\n#include \"kudu\/gutil\/gscoped_ptr.h\"\n#include \"kudu\/gutil\/port.h\"\n#include \"kudu\/gutil\/ref_counted.h\"\n#include \"kudu\/gutil\/strings\/strcat.h\"\n#include \"kudu\/master\/mini_master.h\"\n#include \"kudu\/mini-cluster\/internal_mini_cluster.h\"\n#include \"kudu\/tserver\/mini_tablet_server.h\"\n#include \"kudu\/util\/async_util.h\"\n#include \"kudu\/util\/countdown_latch.h\"\n#include \"kudu\/util\/curl_util.h\"\n#include \"kudu\/util\/faststring.h\"\n#include \"kudu\/util\/monotime.h\"\n#include \"kudu\/util\/net\/sockaddr.h\"\n#include \"kudu\/util\/status.h\"\n#include \"kudu\/util\/stopwatch.h\"\n#include \"kudu\/util\/test_macros.h\"\n#include \"kudu\/util\/test_util.h\"\n#include \"kudu\/util\/thread.h\"\n\nDECLARE_int32(flush_threshold_mb);\nDECLARE_int32(log_segment_size_mb);\nDECLARE_int32(maintenance_manager_polling_interval_ms);\nDEFINE_int32(mbs_for_flushes_and_rolls, 1, \"How many MBs are needed to flush and roll\");\nDEFINE_int32(row_count, 2000, \"How many rows will be used in this test for the base data\");\nDEFINE_int32(seconds_to_run, 4,\n \"How long this test runs for, after inserting the base data, in seconds\");\n\nusing std::string;\nusing std::vector;\n\nnamespace kudu {\nnamespace tablet {\n\nusing client::KuduInsert;\nusing client::KuduClient;\nusing client::KuduClientBuilder;\nusing client::KuduColumnSchema;\nusing client::KuduRowResult;\nusing client::KuduScanner;\nusing client::KuduSchema;\nusing client::KuduSchemaBuilder;\nusing client::KuduSession;\nusing client::KuduStatusCallback;\nusing client::KuduStatusMemberCallback;\nusing client::KuduTable;\nusing client::KuduTableCreator;\nusing client::KuduUpdate;\nusing client::sp::shared_ptr;\nusing cluster::InternalMiniCluster;\nusing cluster::InternalMiniClusterOptions;\n\n\/\/ This integration test tries to trigger all the update-related bits while also serving as a\n\/\/ foundation for benchmarking. It first inserts 'row_count' rows and then starts two threads,\n\/\/ one that continuously updates all the rows sequentially and one that scans them all, until\n\/\/ it's been running for 'seconds_to_run'. It doesn't test for correctness, unless something\n\/\/ FATALs.\nclass UpdateScanDeltaCompactionTest : public KuduTest {\n protected:\n UpdateScanDeltaCompactionTest() {\n KuduSchemaBuilder b;\n b.AddColumn(\"key\")->Type(KuduColumnSchema::INT64)->NotNull()->PrimaryKey();\n b.AddColumn(\"string\")->Type(KuduColumnSchema::STRING)->NotNull();\n b.AddColumn(\"int64\")->Type(KuduColumnSchema::INT64)->NotNull();\n CHECK_OK(b.Build(&schema_));\n }\n\n virtual void SetUp() OVERRIDE {\n KuduTest::SetUp();\n }\n\n void CreateTable() {\n ASSERT_NO_FATAL_FAILURE(InitCluster());\n gscoped_ptr<KuduTableCreator> table_creator(client_->NewTableCreator());\n ASSERT_OK(table_creator->table_name(kTableName)\n .schema(&schema_)\n .set_range_partition_columns({ \"key\" })\n .num_replicas(1)\n .Create());\n ASSERT_OK(client_->OpenTable(kTableName, &table_));\n }\n\n virtual void TearDown() OVERRIDE {\n if (cluster_) {\n cluster_->Shutdown();\n }\n KuduTest::TearDown();\n }\n\n \/\/ Inserts row_count rows sequentially.\n void InsertBaseData();\n\n \/\/ Starts the update and scan threads then stops them after seconds_to_run.\n void RunThreads();\n\n private:\n enum {\n kKeyCol,\n kStrCol,\n kInt64Col\n };\n static const char* const kTableName;\n\n void InitCluster() {\n \/\/ Start mini-cluster with 1 tserver.\n cluster_.reset(new InternalMiniCluster(env_, InternalMiniClusterOptions()));\n ASSERT_OK(cluster_->Start());\n KuduClientBuilder client_builder;\n client_builder.add_master_server_addr(\n cluster_->mini_master()->bound_rpc_addr_str());\n ASSERT_OK(client_builder.Build(&client_));\n }\n\n shared_ptr<KuduSession> CreateSession() {\n shared_ptr<KuduSession> session = client_->NewSession();\n session->SetTimeoutMillis(30000);\n CHECK_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH));\n return session;\n }\n\n \/\/ Continuously updates the existing data until 'stop_latch' drops to 0.\n void UpdateRows(CountDownLatch* stop_latch);\n\n \/\/ Continuously scans the data until 'stop_latch' drops to 0.\n void ScanRows(CountDownLatch* stop_latch) const;\n\n \/\/ Continuously fetch various web pages on the TS.\n void CurlWebPages(CountDownLatch* stop_latch) const;\n\n \/\/ Sets the passed values on the row.\n \/\/ TODO randomize the string column.\n void MakeRow(int64_t key, int64_t val, KuduPartialRow* row) const;\n\n \/\/ If 'key' is a multiple of kSessionBatchSize, it uses 'last_s' to wait for the previous batch\n \/\/ to finish and then flushes the current one.\n Status WaitForLastBatchAndFlush(int64_t key,\n Synchronizer* last_s,\n KuduStatusCallback* last_s_cb,\n shared_ptr<KuduSession> session);\n\n KuduSchema schema_;\n std::shared_ptr<InternalMiniCluster> cluster_;\n shared_ptr<KuduTable> table_;\n shared_ptr<KuduClient> client_;\n};\n\nconst char* const UpdateScanDeltaCompactionTest::kTableName = \"update-scan-delta-compact-tbl\";\nconst int kSessionBatchSize = 1000;\n\nTEST_F(UpdateScanDeltaCompactionTest, TestAll) {\n OverrideFlagForSlowTests(\"seconds_to_run\", \"100\");\n OverrideFlagForSlowTests(\"row_count\", \"1000000\");\n OverrideFlagForSlowTests(\"mbs_for_flushes_and_rolls\", \"8\");\n \/\/ Setting this high enough that we see the effects of flushes and compactions.\n OverrideFlagForSlowTests(\"maintenance_manager_polling_interval_ms\", \"2000\");\n FLAGS_flush_threshold_mb = FLAGS_mbs_for_flushes_and_rolls;\n FLAGS_log_segment_size_mb = FLAGS_mbs_for_flushes_and_rolls;\n if (!AllowSlowTests()) {\n \/\/ Make it run more often since it's not a long test.\n FLAGS_maintenance_manager_polling_interval_ms = 50;\n }\n\n ASSERT_NO_FATAL_FAILURE(CreateTable());\n ASSERT_NO_FATAL_FAILURE(InsertBaseData());\n ASSERT_NO_FATAL_FAILURE(RunThreads());\n}\n\nvoid UpdateScanDeltaCompactionTest::InsertBaseData() {\n shared_ptr<KuduSession> session = CreateSession();\n Synchronizer last_s;\n KuduStatusMemberCallback<Synchronizer> last_s_cb(&last_s,\n &Synchronizer::StatusCB);\n last_s_cb.Run(Status::OK());\n\n LOG_TIMING(INFO, \"Insert\") {\n for (int64_t key = 0; key < FLAGS_row_count; key++) {\n gscoped_ptr<KuduInsert> insert(table_->NewInsert());\n MakeRow(key, 0, insert->mutable_row());\n ASSERT_OK(session->Apply(insert.release()));\n ASSERT_OK(WaitForLastBatchAndFlush(key, &last_s, &last_s_cb, session));\n }\n ASSERT_OK(WaitForLastBatchAndFlush(kSessionBatchSize, &last_s, &last_s_cb, session));\n ASSERT_OK(last_s.Wait());\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::RunThreads() {\n vector<scoped_refptr<Thread> > threads;\n\n CountDownLatch stop_latch(1);\n\n {\n scoped_refptr<Thread> t;\n ASSERT_OK(Thread::Create(CURRENT_TEST_NAME(),\n StrCat(CURRENT_TEST_CASE_NAME(), \"-update\"),\n &UpdateScanDeltaCompactionTest::UpdateRows, this,\n &stop_latch, &t));\n threads.push_back(t);\n }\n\n {\n scoped_refptr<Thread> t;\n ASSERT_OK(Thread::Create(CURRENT_TEST_NAME(),\n StrCat(CURRENT_TEST_CASE_NAME(), \"-scan\"),\n &UpdateScanDeltaCompactionTest::ScanRows, this,\n &stop_latch, &t));\n threads.push_back(t);\n }\n\n {\n scoped_refptr<Thread> t;\n ASSERT_OK(Thread::Create(CURRENT_TEST_NAME(),\n StrCat(CURRENT_TEST_CASE_NAME(), \"-curl\"),\n &UpdateScanDeltaCompactionTest::CurlWebPages, this,\n &stop_latch, &t));\n threads.push_back(t);\n }\n\n SleepFor(MonoDelta::FromSeconds(FLAGS_seconds_to_run * 1.0));\n stop_latch.CountDown();\n\n for (const scoped_refptr<Thread>& thread : threads) {\n ASSERT_OK(ThreadJoiner(thread.get())\n .warn_every_ms(500)\n .Join());\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::UpdateRows(CountDownLatch* stop_latch) {\n shared_ptr<KuduSession> session = CreateSession();\n Synchronizer last_s;\n KuduStatusMemberCallback<Synchronizer> last_s_cb(&last_s,\n &Synchronizer::StatusCB);\n\n for (int64_t iteration = 1; stop_latch->count() > 0; iteration++) {\n last_s_cb.Run(Status::OK());\n LOG_TIMING(INFO, \"Update\") {\n for (int64_t key = 0; key < FLAGS_row_count && stop_latch->count() > 0; key++) {\n gscoped_ptr<KuduUpdate> update(table_->NewUpdate());\n MakeRow(key, iteration, update->mutable_row());\n CHECK_OK(session->Apply(update.release()));\n CHECK_OK(WaitForLastBatchAndFlush(key, &last_s, &last_s_cb, session));\n }\n CHECK_OK(WaitForLastBatchAndFlush(kSessionBatchSize, &last_s, &last_s_cb, session));\n CHECK_OK(last_s.Wait());\n }\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::ScanRows(CountDownLatch* stop_latch) const {\n while (stop_latch->count() > 0) {\n KuduScanner scanner(table_.get());\n \/\/ Sometimes use fault-tolerant scans, to get more coverage of the\n \/\/ MergeIterator code paths.\n if (rand() % 2 == 1) {\n CHECK_OK(scanner.SetFaultTolerant());\n }\n LOG_TIMING(INFO, \"Scan\") {\n CHECK_OK(scanner.Open());\n vector<KuduRowResult> rows;\n while (scanner.HasMoreRows()) {\n CHECK_OK(scanner.NextBatch(&rows));\n }\n }\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::CurlWebPages(CountDownLatch* stop_latch) const {\n vector<string> urls;\n string base_url = cluster_->mini_tablet_server(0)->bound_http_addr().ToString();\n urls.push_back(base_url + \"\/scans\");\n urls.push_back(base_url + \"\/transactions\");\n\n EasyCurl curl;\n faststring dst;\n while (stop_latch->count() > 0) {\n for (const string& url : urls) {\n VLOG(1) << \"Curling URL \" << url;\n Status status = curl.FetchURL(url, &dst);\n if (status.ok()) {\n CHECK_GT(dst.length(), 0);\n }\n }\n }\n}\n\nvoid UpdateScanDeltaCompactionTest::MakeRow(int64_t key,\n int64_t val,\n KuduPartialRow* row) const {\n CHECK_OK(row->SetInt64(kKeyCol, key));\n CHECK_OK(row->SetStringCopy(kStrCol, \"TODO random string\"));\n CHECK_OK(row->SetInt64(kInt64Col, val));\n}\n\nStatus UpdateScanDeltaCompactionTest::WaitForLastBatchAndFlush(int64_t key,\n Synchronizer* last_s,\n KuduStatusCallback* last_s_cb,\n shared_ptr<KuduSession> session) {\n if (key % kSessionBatchSize == 0) {\n RETURN_NOT_OK(last_s->Wait());\n last_s->Reset();\n session->FlushAsync(last_s_cb);\n }\n return Status::OK();\n}\n\n} \/\/ namespace tablet\n} \/\/ namespace kudu\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE libraries and the Kate part.\n *\n * Copyright (C) 2008-2011 Erlend Hamberg <ehamberg@gmail.com>\n * Copyright (C) 2011 Svyatoslav Kuzmich <svatoslav1@gmail.com>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kateviinsertmode.h\"\n#include \"kateviinputmodemanager.h\"\n#include \"kateview.h\"\n#include \"kateviewinternal.h\"\n#include \"kateconfig.h\"\n#include \"katecompletionwidget.h\"\n#include \"kateglobal.h\"\n#include \"katevikeyparser.h\"\n\nusing KTextEditor::Cursor;\n\nKateViInsertMode::KateViInsertMode( KateViInputModeManager *viInputModeManager,\n KateView * view, KateViewInternal * viewInternal ) : KateViModeBase()\n{\n m_view = view;\n m_viewInternal = viewInternal;\n m_viInputModeManager = viInputModeManager;\n\n m_blockInsert = None;\n m_eolPos = 0;\n}\n\nKateViInsertMode::~KateViInsertMode()\n{\n}\n\n\nbool KateViInsertMode::commandInsertFromAbove()\n{\n Cursor c( m_view->cursorPosition() );\n\n if ( c.line() <= 0 ) {\n return false;\n }\n\n QString line = doc()->line( c.line()-1 );\n int tabWidth = doc()->config()->tabWidth();\n QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );\n\n if ( ch == QChar::Null ) {\n return false;\n }\n\n return doc()->insertText( c, ch );\n}\n\nbool KateViInsertMode::commandInsertFromBelow()\n{\n Cursor c( m_view->cursorPosition() );\n\n if ( c.line() >= doc()->lines()-1 ) {\n return false;\n }\n\n QString line = doc()->line( c.line()+1 );\n int tabWidth = doc()->config()->tabWidth();\n QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );\n\n if ( ch == QChar::Null ) {\n return false;\n }\n\n return doc()->insertText( c, ch );\n}\n\nbool KateViInsertMode::commandDeleteWord()\n{\n Cursor c1( m_view->cursorPosition() );\n Cursor c2;\n\n c2 = findPrevWordStart( c1.line(), c1.column() );\n\n if ( c2.line() != c1.line() ) {\n if ( c1.column() == 0 ) {\n c2.setColumn( doc()->line( c2.line() ).length() );\n } else {\n c2.setColumn( 0 );\n c2.setLine( c2.line()+1 );\n }\n }\n\n KateViRange r( c2.line(), c2.column(), c1.line(), c1.column(), ViMotion::ExclusiveMotion );\n\n return deleteRange( r, CharWise, false );\n}\n\nbool KateViInsertMode::commandDeleteCharBackward()\n{\n kDebug( 13070 ) << \"Char backward!\\n\";\n Cursor c( m_view->cursorPosition() );\n\n KateViRange r( c.line(), c.column()-getCount(), c.line(), c.column(), ViMotion::ExclusiveMotion );\n\n if (c.column() == 0) {\n if (c.line() == 0) {\n return true;\n } else {\n r.startColumn = doc()->line(c.line()-1).length();\n r.startLine--;\n }\n }\n\n return deleteRange( r, CharWise );\n}\n\nbool KateViInsertMode::commandNewLine()\n{\n doc()->newLine( m_view );\n return true; \n}\n\nbool KateViInsertMode::commandIndent()\n{\n Cursor c( m_view->cursorPosition() );\n doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), 1 );\n return true;\n}\n\nbool KateViInsertMode::commandUnindent()\n{\n Cursor c( m_view->cursorPosition() );\n doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), -1 );\n return true;\n}\n\nbool KateViInsertMode::commandToFirstCharacterInFile()\n{\n Cursor c;\n\n c.setLine( 0 );\n c.setColumn( 0 );\n\n updateCursor( c );\n\n return true;\n}\n\nbool KateViInsertMode::commandToLastCharacterInFile()\n{\n Cursor c;\n\n int lines = doc()->lines()-1;\n c.setLine( lines );\n c.setColumn( doc()->line( lines ).length() );\n\n updateCursor( c );\n\n return true;\n}\n\nbool KateViInsertMode::commandMoveOneWordLeft()\n{\n Cursor c( m_view->cursorPosition() );\n c = findPrevWordStart( c.line(), c.column() );\n\n updateCursor( c );\n return true;\n}\n\nbool KateViInsertMode::commandMoveOneWordRight()\n{\n Cursor c( m_view->cursorPosition() );\n c = findNextWordStart( c.line(), c.column() );\n\n updateCursor( c );\n return true;\n}\n\nbool KateViInsertMode::commandCompleteNext()\n{\n if(m_view->completionWidget()->isCompletionActive()) {\n m_view->completionWidget()->cursorDown();\n } else {\n m_view->userInvokedCompletion();\n }\n return true;\n}\n\nbool KateViInsertMode::commandCompletePrevious()\n{\n if(m_view->completionWidget()->isCompletionActive()) {\n m_view->completionWidget()->cursorUp();\n } else {\n m_view->userInvokedCompletion();\n m_view->completionWidget()->bottom();\n }\n return true;\n}\n\nbool KateViInsertMode::commandInsertContentOfRegister(){\n Cursor c( m_view->cursorPosition() );\n Cursor cAfter = c;\n QChar reg = getChosenRegister( m_register );\n\n OperationMode m = getRegisterFlag( reg );\n QString textToInsert = getRegisterContent( reg );\n\n if ( textToInsert.isNull() ) {\n error(i18n(\"Nothing in register %1\", reg ));\n return false;\n }\n\n if ( m == LineWise ) {\n textToInsert.chop( 1 ); \/\/ remove the last \\n\n c.setColumn( doc()->lineLength( c.line() ) ); \/\/ paste after the current line and ...\n textToInsert.prepend( QChar( '\\n' ) ); \/\/ ... prepend a \\n, so the text starts on a new line\n\n cAfter.setLine( cAfter.line()+1 );\n cAfter.setColumn( 0 );\n }\n\n doc()->insertText( c, textToInsert, m == Block );\n\n updateCursor( cAfter );\n\n return true;\n}\n\n\/\/ Start Normal mode just for one command and return to Insert mode\nbool KateViInsertMode::commandSwitchToNormalModeForJustOneCommand(){\n m_viInputModeManager->setTemporaryNormalMode(true);\n m_viInputModeManager->changeViMode(NormalMode);\n m_view->setCaretStyle( KateRenderer::Block, true );\n m_view->updateViModeBarMode();\n m_viewInternal->repaint();\n return true;\n}\n\n\/**\n * checks if the key is a valid command\n * @return true if a command was completed and executed, false otherwise\n *\/\nbool KateViInsertMode::handleKeypress( const QKeyEvent *e )\n{\n \/\/ backspace should work even if the shift key is down\n if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) {\n m_view->backspace();\n return true;\n }\n\n if(m_keys.isEmpty()){\n if ( e->modifiers() == Qt::NoModifier ) {\n switch ( e->key() ) {\n case Qt::Key_Escape:\n leaveInsertMode();\n return true;\n break;\n case Qt::Key_Left:\n m_view->cursorLeft();\n return true;\n case Qt::Key_Right:\n m_view->cursorRight();\n return true;\n case Qt::Key_Up:\n m_view->up();\n return true;\n case Qt::Key_Down:\n m_view->down();\n return true;\n case Qt::Key_Delete:\n m_view->keyDelete();\n return true;\n case Qt::Key_Home:\n m_view->home();\n return true;\n case Qt::Key_End:\n m_view->end();\n return true;\n case Qt::Key_PageUp:\n m_view->pageUp();\n return true;\n case Qt::Key_PageDown:\n m_view->pageDown();\n return true;\n default:\n return false;\n break;\n }\n } else if ( e->modifiers() == Qt::ControlModifier ) {\n switch( e->key() ) {\n case Qt::Key_BracketLeft:\n case Qt::Key_3:\n leaveInsertMode();\n return true;\n break;\n case Qt::Key_C:\n leaveInsertMode( true );\n return true;\n break;\n case Qt::Key_D:\n commandUnindent();\n return true;\n break;\n case Qt::Key_E:\n commandInsertFromBelow();\n return true;\n break;\n case Qt::Key_N:\n commandCompleteNext();\n return true;\n break;\n case Qt::Key_P:\n commandCompletePrevious();\n return true;\n break;\n case Qt::Key_T:\n commandIndent();\n return true;\n break;\n case Qt::Key_W:\n commandDeleteWord();\n return true;\n break;\n case Qt::Key_J:\n commandNewLine();\n return true;\n break;\n case Qt::Key_H:\n commandDeleteCharBackward();\n return true;\n break;\n case Qt::Key_Y:\n commandInsertFromAbove();\n return true;\n break;\n case Qt::Key_O:\n commandSwitchToNormalModeForJustOneCommand();\n return true;\n break;\n case Qt::Key_Home:\n commandToFirstCharacterInFile();\n return true;\n break;\n case Qt::Key_R:\n m_keys = \"cR\";\n \/\/ Waiting for register\n return true;\n break;\n case Qt::Key_End:\n commandToLastCharacterInFile();\n return true;\n break;\n case Qt::Key_Left:\n commandMoveOneWordLeft();\n return true;\n break;\n case Qt::Key_Right:\n commandMoveOneWordRight();\n return true;\n break;\n default:\n return false;\n }\n }\n\n return false;\n} else {\n\n \/\/ Was waiting for register for Ctrl-R\n if (m_keys == \"cR\"){\n QChar key = KateViKeyParser::self()->KeyEventToQChar(\n e->key(),\n e->text(),\n e->modifiers(),\n e->nativeScanCode() );\n key = key.toLower();\n\n \/\/ is it register ?\n if ( ( key >= '0' && key <= '9' ) || ( key >= 'a' && key <= 'z' ) ||\n key == '_' || key == '+' || key == '*' ) {\n m_register = key;\n } else {\n m_keys = \"\";\n return false;\n }\n commandInsertContentOfRegister();\n m_keys = \"\";\n return true;\n }\n }\n return false;\n}\n\n\/\/ leave insert mode when esc, etc, is pressed. if leaving block\n\/\/ prepend\/append, the inserted text will be added to all block lines. if\n\/\/ ctrl-c is used to exit insert mode this is not done.\nvoid KateViInsertMode::leaveInsertMode( bool force )\n{\n if ( !force && m_blockInsert != None ) { \/\/ block append\/prepend\n\n \/\/ make sure cursor haven't been moved\n if ( m_blockRange.startLine == m_view->cursorPosition().line() ) {\n int start, len;\n QString added;\n Cursor c;\n\n switch ( m_blockInsert ) {\n case Append:\n case Prepend:\n if ( m_blockInsert == Append ) {\n start = m_blockRange.endColumn+1;\n } else {\n start = m_blockRange.startColumn;\n }\n\n len = m_view->cursorPosition().column()-start;\n added = getLine().mid( start, len );\n\n c = Cursor( m_blockRange.startLine, start );\n for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {\n c.setLine( i );\n doc()->insertText( c, added );\n }\n break;\n case AppendEOL:\n start = m_eolPos;\n len = m_view->cursorPosition().column()-start;\n added = getLine().mid( start, len );\n\n c = Cursor( m_blockRange.startLine, start );\n for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {\n c.setLine( i );\n c.setColumn( doc()->lineLength( i ) );\n doc()->insertText( c, added );\n }\n break;\n default:\n error(\"not supported\");\n }\n }\n\n m_blockInsert = None;\n }\n startNormalMode();\n}\n\nvoid KateViInsertMode::setBlockPrependMode( KateViRange blockRange )\n{\n \/\/ ignore if not more than one line is selected\n if ( blockRange.startLine != blockRange.endLine ) {\n m_blockInsert = Prepend;\n m_blockRange = blockRange;\n }\n}\n\nvoid KateViInsertMode::setBlockAppendMode( KateViRange blockRange, BlockInsert b )\n{\n Q_ASSERT( b == Append || b == AppendEOL );\n\n if ( b == AppendEOL ) {\n m_eolPos = doc()->lineLength( m_blockRange.startLine );\n }\n \/\/ ignore if not more than one line is selected\n if ( blockRange.startLine != blockRange.endLine ) {\n m_blockRange = blockRange;\n m_blockInsert = b;\n } else {\n kDebug( 13070 ) << \"cursor moved. ignoring block append\/prepend\";\n }\n}\n<commit_msg>Enable insert repetition when completing text<commit_after>\/* This file is part of the KDE libraries and the Kate part.\n *\n * Copyright (C) 2008-2011 Erlend Hamberg <ehamberg@gmail.com>\n * Copyright (C) 2011 Svyatoslav Kuzmich <svatoslav1@gmail.com>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kateviinsertmode.h\"\n#include \"kateviinputmodemanager.h\"\n#include \"kateview.h\"\n#include \"kateviewinternal.h\"\n#include \"kateconfig.h\"\n#include \"katecompletionwidget.h\"\n#include \"kateglobal.h\"\n#include \"katevikeyparser.h\"\n\nusing KTextEditor::Cursor;\n\nKateViInsertMode::KateViInsertMode( KateViInputModeManager *viInputModeManager,\n KateView * view, KateViewInternal * viewInternal ) : KateViModeBase()\n{\n m_view = view;\n m_viewInternal = viewInternal;\n m_viInputModeManager = viInputModeManager;\n\n m_blockInsert = None;\n m_eolPos = 0;\n}\n\nKateViInsertMode::~KateViInsertMode()\n{\n}\n\n\nbool KateViInsertMode::commandInsertFromAbove()\n{\n Cursor c( m_view->cursorPosition() );\n\n if ( c.line() <= 0 ) {\n return false;\n }\n\n QString line = doc()->line( c.line()-1 );\n int tabWidth = doc()->config()->tabWidth();\n QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );\n\n if ( ch == QChar::Null ) {\n return false;\n }\n\n return doc()->insertText( c, ch );\n}\n\nbool KateViInsertMode::commandInsertFromBelow()\n{\n Cursor c( m_view->cursorPosition() );\n\n if ( c.line() >= doc()->lines()-1 ) {\n return false;\n }\n\n QString line = doc()->line( c.line()+1 );\n int tabWidth = doc()->config()->tabWidth();\n QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );\n\n if ( ch == QChar::Null ) {\n return false;\n }\n\n return doc()->insertText( c, ch );\n}\n\nbool KateViInsertMode::commandDeleteWord()\n{\n Cursor c1( m_view->cursorPosition() );\n Cursor c2;\n\n c2 = findPrevWordStart( c1.line(), c1.column() );\n\n if ( c2.line() != c1.line() ) {\n if ( c1.column() == 0 ) {\n c2.setColumn( doc()->line( c2.line() ).length() );\n } else {\n c2.setColumn( 0 );\n c2.setLine( c2.line()+1 );\n }\n }\n\n KateViRange r( c2.line(), c2.column(), c1.line(), c1.column(), ViMotion::ExclusiveMotion );\n\n return deleteRange( r, CharWise, false );\n}\n\nbool KateViInsertMode::commandDeleteCharBackward()\n{\n kDebug( 13070 ) << \"Char backward!\\n\";\n Cursor c( m_view->cursorPosition() );\n\n KateViRange r( c.line(), c.column()-getCount(), c.line(), c.column(), ViMotion::ExclusiveMotion );\n\n if (c.column() == 0) {\n if (c.line() == 0) {\n return true;\n } else {\n r.startColumn = doc()->line(c.line()-1).length();\n r.startLine--;\n }\n }\n\n return deleteRange( r, CharWise );\n}\n\nbool KateViInsertMode::commandNewLine()\n{\n doc()->newLine( m_view );\n return true; \n}\n\nbool KateViInsertMode::commandIndent()\n{\n Cursor c( m_view->cursorPosition() );\n doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), 1 );\n return true;\n}\n\nbool KateViInsertMode::commandUnindent()\n{\n Cursor c( m_view->cursorPosition() );\n doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), -1 );\n return true;\n}\n\nbool KateViInsertMode::commandToFirstCharacterInFile()\n{\n Cursor c;\n\n c.setLine( 0 );\n c.setColumn( 0 );\n\n updateCursor( c );\n\n return true;\n}\n\nbool KateViInsertMode::commandToLastCharacterInFile()\n{\n Cursor c;\n\n int lines = doc()->lines()-1;\n c.setLine( lines );\n c.setColumn( doc()->line( lines ).length() );\n\n updateCursor( c );\n\n return true;\n}\n\nbool KateViInsertMode::commandMoveOneWordLeft()\n{\n Cursor c( m_view->cursorPosition() );\n c = findPrevWordStart( c.line(), c.column() );\n\n updateCursor( c );\n return true;\n}\n\nbool KateViInsertMode::commandMoveOneWordRight()\n{\n Cursor c( m_view->cursorPosition() );\n c = findNextWordStart( c.line(), c.column() );\n\n updateCursor( c );\n return true;\n}\n\nbool KateViInsertMode::commandCompleteNext()\n{\n \/\/ Completion may yield different results when performed\n \/\/ other places in the document. Therefore, repeat the\n \/\/ inserted text instead of the typed keystrokes.\n m_viInputModeManager->setTextualRepeat();\n if(m_view->completionWidget()->isCompletionActive()) {\n m_view->completionWidget()->cursorDown();\n } else {\n m_view->userInvokedCompletion();\n }\n return true;\n}\n\nbool KateViInsertMode::commandCompletePrevious()\n{\n m_viInputModeManager->setTextualRepeat();\n if(m_view->completionWidget()->isCompletionActive()) {\n m_view->completionWidget()->cursorUp();\n } else {\n m_view->userInvokedCompletion();\n m_view->completionWidget()->bottom();\n }\n return true;\n}\n\nbool KateViInsertMode::commandInsertContentOfRegister(){\n Cursor c( m_view->cursorPosition() );\n Cursor cAfter = c;\n QChar reg = getChosenRegister( m_register );\n\n OperationMode m = getRegisterFlag( reg );\n QString textToInsert = getRegisterContent( reg );\n\n if ( textToInsert.isNull() ) {\n error(i18n(\"Nothing in register %1\", reg ));\n return false;\n }\n\n if ( m == LineWise ) {\n textToInsert.chop( 1 ); \/\/ remove the last \\n\n c.setColumn( doc()->lineLength( c.line() ) ); \/\/ paste after the current line and ...\n textToInsert.prepend( QChar( '\\n' ) ); \/\/ ... prepend a \\n, so the text starts on a new line\n\n cAfter.setLine( cAfter.line()+1 );\n cAfter.setColumn( 0 );\n }\n\n doc()->insertText( c, textToInsert, m == Block );\n\n updateCursor( cAfter );\n\n return true;\n}\n\n\/\/ Start Normal mode just for one command and return to Insert mode\nbool KateViInsertMode::commandSwitchToNormalModeForJustOneCommand(){\n m_viInputModeManager->setTemporaryNormalMode(true);\n m_viInputModeManager->changeViMode(NormalMode);\n m_view->setCaretStyle( KateRenderer::Block, true );\n m_view->updateViModeBarMode();\n m_viewInternal->repaint();\n return true;\n}\n\n\/**\n * checks if the key is a valid command\n * @return true if a command was completed and executed, false otherwise\n *\/\nbool KateViInsertMode::handleKeypress( const QKeyEvent *e )\n{\n \/\/ backspace should work even if the shift key is down\n if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) {\n m_view->backspace();\n return true;\n }\n\n if(m_keys.isEmpty()){\n if ( e->modifiers() == Qt::NoModifier ) {\n switch ( e->key() ) {\n case Qt::Key_Escape:\n leaveInsertMode();\n return true;\n break;\n case Qt::Key_Left:\n m_view->cursorLeft();\n return true;\n case Qt::Key_Right:\n m_view->cursorRight();\n return true;\n case Qt::Key_Up:\n m_view->up();\n return true;\n case Qt::Key_Down:\n m_view->down();\n return true;\n case Qt::Key_Delete:\n m_view->keyDelete();\n return true;\n case Qt::Key_Home:\n m_view->home();\n return true;\n case Qt::Key_End:\n m_view->end();\n return true;\n case Qt::Key_PageUp:\n m_view->pageUp();\n return true;\n case Qt::Key_PageDown:\n m_view->pageDown();\n return true;\n default:\n return false;\n break;\n }\n } else if ( e->modifiers() == Qt::ControlModifier ) {\n switch( e->key() ) {\n case Qt::Key_BracketLeft:\n case Qt::Key_3:\n leaveInsertMode();\n return true;\n break;\n case Qt::Key_Space:\n commandCompleteNext();\n return true;\n break;\n case Qt::Key_C:\n leaveInsertMode( true );\n return true;\n break;\n case Qt::Key_D:\n commandUnindent();\n return true;\n break;\n case Qt::Key_E:\n commandInsertFromBelow();\n return true;\n break;\n case Qt::Key_N:\n commandCompleteNext();\n return true;\n break;\n case Qt::Key_P:\n commandCompletePrevious();\n return true;\n break;\n case Qt::Key_T:\n commandIndent();\n return true;\n break;\n case Qt::Key_W:\n commandDeleteWord();\n return true;\n break;\n case Qt::Key_J:\n commandNewLine();\n return true;\n break;\n case Qt::Key_H:\n commandDeleteCharBackward();\n return true;\n break;\n case Qt::Key_Y:\n commandInsertFromAbove();\n return true;\n break;\n case Qt::Key_O:\n commandSwitchToNormalModeForJustOneCommand();\n return true;\n break;\n case Qt::Key_Home:\n commandToFirstCharacterInFile();\n return true;\n break;\n case Qt::Key_R:\n m_keys = \"cR\";\n \/\/ Waiting for register\n return true;\n break;\n case Qt::Key_End:\n commandToLastCharacterInFile();\n return true;\n break;\n case Qt::Key_Left:\n commandMoveOneWordLeft();\n return true;\n break;\n case Qt::Key_Right:\n commandMoveOneWordRight();\n return true;\n break;\n default:\n return false;\n }\n }\n\n return false;\n} else {\n\n \/\/ Was waiting for register for Ctrl-R\n if (m_keys == \"cR\"){\n QChar key = KateViKeyParser::self()->KeyEventToQChar(\n e->key(),\n e->text(),\n e->modifiers(),\n e->nativeScanCode() );\n key = key.toLower();\n\n \/\/ is it register ?\n if ( ( key >= '0' && key <= '9' ) || ( key >= 'a' && key <= 'z' ) ||\n key == '_' || key == '+' || key == '*' ) {\n m_register = key;\n } else {\n m_keys = \"\";\n return false;\n }\n commandInsertContentOfRegister();\n m_keys = \"\";\n return true;\n }\n }\n return false;\n}\n\n\/\/ leave insert mode when esc, etc, is pressed. if leaving block\n\/\/ prepend\/append, the inserted text will be added to all block lines. if\n\/\/ ctrl-c is used to exit insert mode this is not done.\nvoid KateViInsertMode::leaveInsertMode( bool force )\n{\n if ( !force && m_blockInsert != None ) { \/\/ block append\/prepend\n\n \/\/ make sure cursor haven't been moved\n if ( m_blockRange.startLine == m_view->cursorPosition().line() ) {\n int start, len;\n QString added;\n Cursor c;\n\n switch ( m_blockInsert ) {\n case Append:\n case Prepend:\n if ( m_blockInsert == Append ) {\n start = m_blockRange.endColumn+1;\n } else {\n start = m_blockRange.startColumn;\n }\n\n len = m_view->cursorPosition().column()-start;\n added = getLine().mid( start, len );\n\n c = Cursor( m_blockRange.startLine, start );\n for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {\n c.setLine( i );\n doc()->insertText( c, added );\n }\n break;\n case AppendEOL:\n start = m_eolPos;\n len = m_view->cursorPosition().column()-start;\n added = getLine().mid( start, len );\n\n c = Cursor( m_blockRange.startLine, start );\n for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {\n c.setLine( i );\n c.setColumn( doc()->lineLength( i ) );\n doc()->insertText( c, added );\n }\n break;\n default:\n error(\"not supported\");\n }\n }\n\n m_blockInsert = None;\n }\n startNormalMode();\n}\n\nvoid KateViInsertMode::setBlockPrependMode( KateViRange blockRange )\n{\n \/\/ ignore if not more than one line is selected\n if ( blockRange.startLine != blockRange.endLine ) {\n m_blockInsert = Prepend;\n m_blockRange = blockRange;\n }\n}\n\nvoid KateViInsertMode::setBlockAppendMode( KateViRange blockRange, BlockInsert b )\n{\n Q_ASSERT( b == Append || b == AppendEOL );\n\n if ( b == AppendEOL ) {\n m_eolPos = doc()->lineLength( m_blockRange.startLine );\n }\n \/\/ ignore if not more than one line is selected\n if ( blockRange.startLine != blockRange.endLine ) {\n m_blockRange = blockRange;\n m_blockInsert = b;\n } else {\n kDebug( 13070 ) << \"cursor moved. ignoring block append\/prepend\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Paul Asmuth <paul@eventql.io>\n * - Laura Schlimmer <laura@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include \"eventql\/sql\/svalue.h\"\n#include \"eventql\/server\/sql\/partition_cursor.h\"\n#include \"eventql\/transport\/native\/frames\/error.h\"\n#include \"eventql\/transport\/native\/frames\/query_remote.h\"\n#include \"eventql\/transport\/native\/frames\/query_remote_result.h\"\n#include \"eventql\/db\/database.h\"\n\nnamespace eventql {\n\nPartitionCursor::PartitionCursor(\n csql::Transaction* txn,\n csql::ExecutionContext* execution_context,\n RefPtr<Table> table,\n RefPtr<PartitionSnapshot> snap,\n RefPtr<csql::SequentialScanNode> stmt) :\n txn_(txn),\n execution_context_(execution_context),\n table_(table),\n snap_(snap),\n stmt_(stmt),\n cur_table_(0),\n fast_scan_enabled_(true) {\n if (stmt_->aggregationStrategy() != csql::AggregationStrategy::NO_AGGREGATION) {\n fast_scan_enabled_ = false;\n }\n}\n\nReturnCode PartitionCursor::execute() {\n return ReturnCode::success();\n}\n\nReturnCode PartitionCursor::nextBatch(\n csql::SVector* columns,\n size_t* nrows) {\n for (;;) {\n if (cur_scan_.get() == nullptr) {\n if (!openNextTable()) {\n break;\n }\n }\n\n auto rc = cur_scan_->nextBatch(columns, nrows);\n if (!rc.isSuccess()) {\n return rc;\n }\n\n if (!*nrows) {\n cur_scan_.reset(nullptr);\n continue;\n }\n\n return ReturnCode::success();\n }\n\n *nrows = 0;\n return ReturnCode::success();\n}\n\nbool PartitionCursor::openNextTable() {\n RefPtr<cstable::CSTableReader> cstable;\n String cstable_filename;\n RefPtr<cstable::ColumnReader> skip_col;\n\n cur_skiplist_.reset();\n\n switch (cur_table_) {\n case 0: {\n if (snap_->head_arena.get() &&\n snap_->head_arena->getCSTableFile()) {\n cur_skiplist_.reset(\n new PartitionArena::SkiplistReader(\n snap_->head_arena->getSkiplistReader()));\n cstable = cstable::CSTableReader::openFile(\n snap_->head_arena->getCSTableFile(),\n cur_skiplist_->size());\n cstable_filename = StringUtil::format(\n \"memory:\/\/$0\/$1\/$2\/head_arena\",\n snap_->state.tsdb_namespace(),\n snap_->state.table_key(),\n snap_->key.toString());\n break;\n } else {\n ++cur_table_;\n \/* fallthrough *\/\n }\n }\n\n case 1: {\n if (snap_->compacting_arena.get() &&\n snap_->compacting_arena->getCSTableFile()) {\n cur_skiplist_.reset(\n new PartitionArena::SkiplistReader(\n snap_->compacting_arena->getSkiplistReader()));\n cstable = cstable::CSTableReader::openFile(\n snap_->compacting_arena->getCSTableFile(),\n cur_skiplist_->size());\n cstable_filename = StringUtil::format(\n \"memory:\/\/$0\/$1\/$2\/compacting_arena\",\n snap_->state.tsdb_namespace(),\n snap_->state.table_key(),\n snap_->key.toString());\n break;\n } else {\n ++cur_table_;\n \/* fallthrough *\/\n }\n }\n\n default: {\n if (cur_table_ >= snap_->state.lsm_tables().size() + 2) {\n return false;\n }\n const auto& tbl = (snap_->state.lsm_tables().data())[\n snap_->state.lsm_tables().size() - (cur_table_ - 1)];\n auto cstable_file = FileUtil::joinPaths(\n snap_->base_path,\n tbl->filename() + \".cst\");\n cstable = cstable::CSTableReader::openFile(cstable_file);\n cstable_filename = cstable_file;\n if (tbl->has_skiplist()) {\n skip_col = cstable->getColumnReader(\"__lsm_skip\");\n }\n break;\n }\n }\n\n \/* read filter *\/\n std::vector<bool> filter(cstable->numRecords(), true);\n auto id_col = cstable->getColumnReader(\"__lsm_id\");\n auto is_update_col = cstable->getColumnReader(\"__lsm_is_update\");\n for (size_t i = 0; i < filter.size(); ++i) {\n uint64_t rlvl;\n uint64_t dlvl;\n\n String id_str;\n id_col->readString(&rlvl, &dlvl, &id_str);\n SHA1Hash id(id_str.data(), id_str.size());\n\n bool is_update;\n is_update_col->readBoolean(&rlvl, &dlvl, &is_update);\n\n bool skip = false;\n if (skip_col.get()) {\n skip_col->readBoolean(&rlvl, &dlvl, &skip);\n }\n\n if (cur_skiplist_) {\n skip = cur_skiplist_->readNext();\n }\n\n if (skip || id_set_.count(id) > 0) {\n filter[i] = false;\n } else {\n if (is_update) {\n id_set_.emplace(id);\n }\n\n filter[i] = true;\n }\n }\n\n if (fast_scan_enabled_) {\n cur_scan_.reset(\n new csql::FastCSTableScan(\n txn_,\n execution_context_,\n stmt_,\n cstable,\n cstable_filename));\n } else {\n cur_scan_.reset(\n new csql::CSTableScan(\n txn_,\n execution_context_,\n stmt_,\n cstable,\n cstable_filename));\n }\n\n cur_scan_->setFilter(std::move(filter));\n\n ++cur_table_;\n\n auto rc = cur_scan_->execute();\n if (!rc.isSuccess()) {\n RAISE(kRuntimeError, rc.getMessage());\n }\n\n return true;\n}\n\nsize_t PartitionCursor::getColumnCount() const {\n return stmt_->getNumComputedColumns();\n}\n\ncsql::SType PartitionCursor::getColumnType(size_t idx) const {\n return stmt_->getColumnType(idx);\n}\n\nRemotePartitionCursor::RemotePartitionCursor(\n Session* session,\n csql::Transaction* txn,\n csql::ExecutionContext* execution_context,\n const std::string& database,\n RefPtr<csql::SequentialScanNode> stmt,\n const std::vector<std::string>& servers) :\n txn_(txn),\n execution_context_(execution_context),\n database_(database),\n stmt_(stmt),\n servers_(servers),\n ncols_(stmt->getNumComputedColumns()),\n row_buf_pos_(0),\n running_(false),\n done_(false),\n timeout_(\n session->getDatabaseContext()->config->getInt(\n \"server.s2s_io_timeout\").get()),\n client_(\n session->getDatabaseContext()->connection_pool,\n session->getDatabaseContext()->dns_cache,\n session->getDatabaseContext()->config->getInt(\n \"server.s2s_io_timeout\",\n 0),\n session->getDatabaseContext()->config->getInt(\n \"server.s2s_idle_timeout\",\n 0)) {}\n\nReturnCode RemotePartitionCursor::execute() {\n return ReturnCode::success();\n}\n\nReturnCode RemotePartitionCursor::nextBatch(\n csql::SVector* output,\n size_t* output_len) {\n if (done_) {\n *output_len = 0;\n return ReturnCode::success();\n }\n\n if (running_) {\n auto rc = client_.sendFrame(EVQL_OP_QUERY_CONTINUE, 0, nullptr, 0);\n if (!rc.isSuccess()) {\n return rc;\n }\n } else {\n auto session = static_cast<eventql::Session*>(txn_->getUserData());\n auto cdir = session->getDatabaseContext()->config_directory;\n\n std::string qtree_coded;\n auto qtree_coded_os = StringOutputStream::fromString(&qtree_coded);\n csql::QueryTreeCoder qtree_coder(txn_);\n qtree_coder.encode(stmt_.get(), qtree_coded_os.get());\n\n native_transport::QueryRemoteFrame q_frame;\n q_frame.setEncodedQtree(std::move(qtree_coded));\n q_frame.setDatabase(session->getEffectiveNamespace());\n\n for (const auto& s : servers_) {\n auto server_cfg = cdir->getServerConfig(s);\n if (server_cfg.server_status() != SERVER_UP) {\n logError(\"evqld\", \"server is down: $0\", s);\n continue;\n }\n\n auto rc = client_.connect(server_cfg.server_addr(), true);\n if (!rc.isSuccess()) {\n logError(\"evqld\", \"Remote SQL Error: $0\", rc.getMessage());\n continue;\n }\n\n rc = client_.sendFrame(&q_frame, 0);\n if (rc.isSuccess()) {\n running_ = true;\n } else {\n logError(\"evqld\", \"Remote SQL Error: $0\", rc.getMessage());\n continue;\n }\n }\n\n if (!running_) {\n return ReturnCode::error(\"ERUNTIME\", \"no server available for query\");\n }\n }\n\n uint16_t ret_opcode = 0;\n uint16_t ret_flags;\n std::string ret_payload;\n while (ret_opcode != EVQL_OP_QUERY_REMOTE_RESULT) {\n auto rc = txn_->triggerHeartbeat();\n if (!rc.isSuccess()) {\n return rc;\n }\n\n rc = client_.recvFrame(&ret_opcode, &ret_flags, &ret_payload, timeout_);\n if (!rc.isSuccess()) {\n return rc;\n }\n\n if (ret_flags & EVQL_ENDOFREQUEST) {\n done_ = true;\n }\n\n switch (ret_opcode) {\n case EVQL_OP_HEARTBEAT:\n continue;\n case EVQL_OP_QUERY_REMOTE_RESULT:\n break;\n case EVQL_OP_ERROR: {\n native_transport::ErrorFrame eframe;\n eframe.parseFrom(ret_payload.data(), ret_payload.size());\n return ReturnCode::error(\"ERUNTIME\", eframe.getError());\n }\n default:\n return ReturnCode::error(\"ERUNTIME\", \"invalid opcode\");\n }\n }\n\n native_transport::QueryRemoteResultFrame r_frame;\n auto rc = r_frame.parseFrom(ret_payload.data(), ret_payload.size());\n\n if (r_frame.getColumnCount() != ncols_) {\n return ReturnCode::error(\"ERUNTIME\", \"invalid column count\");\n }\n\n for (size_t i = 0; i < ncols_; ++i) {\n const auto& coldata = r_frame.getColumnData(i);\n output[i].append(coldata.data(), coldata.size());\n }\n\n *output_len = r_frame.getRowCount();\n return ReturnCode::success();\n}\n\nsize_t RemotePartitionCursor::getColumnCount() const {\n return stmt_->getNumComputedColumns();\n}\n\ncsql::SType RemotePartitionCursor::getColumnType(size_t idx) const {\n return stmt_->getColumnType(idx);\n}\n\n}\n<commit_msg>skip CSTable filter if possible<commit_after>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Paul Asmuth <paul@eventql.io>\n * - Laura Schlimmer <laura@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include \"eventql\/sql\/svalue.h\"\n#include \"eventql\/server\/sql\/partition_cursor.h\"\n#include \"eventql\/transport\/native\/frames\/error.h\"\n#include \"eventql\/transport\/native\/frames\/query_remote.h\"\n#include \"eventql\/transport\/native\/frames\/query_remote_result.h\"\n#include \"eventql\/db\/database.h\"\n\nnamespace eventql {\n\nPartitionCursor::PartitionCursor(\n csql::Transaction* txn,\n csql::ExecutionContext* execution_context,\n RefPtr<Table> table,\n RefPtr<PartitionSnapshot> snap,\n RefPtr<csql::SequentialScanNode> stmt) :\n txn_(txn),\n execution_context_(execution_context),\n table_(table),\n snap_(snap),\n stmt_(stmt),\n cur_table_(0),\n fast_scan_enabled_(true) {\n if (stmt_->aggregationStrategy() != csql::AggregationStrategy::NO_AGGREGATION) {\n fast_scan_enabled_ = false;\n }\n}\n\nReturnCode PartitionCursor::execute() {\n return ReturnCode::success();\n}\n\nReturnCode PartitionCursor::nextBatch(\n csql::SVector* columns,\n size_t* nrows) {\n for (;;) {\n if (cur_scan_.get() == nullptr) {\n if (!openNextTable()) {\n break;\n }\n }\n\n auto rc = cur_scan_->nextBatch(columns, nrows);\n if (!rc.isSuccess()) {\n return rc;\n }\n\n if (!*nrows) {\n cur_scan_.reset(nullptr);\n continue;\n }\n\n return ReturnCode::success();\n }\n\n *nrows = 0;\n return ReturnCode::success();\n}\n\nbool PartitionCursor::openNextTable() {\n RefPtr<cstable::CSTableReader> cstable;\n String cstable_filename;\n RefPtr<cstable::ColumnReader> skip_col;\n\n cur_skiplist_.reset();\n\n bool needs_filter = true;\n switch (cur_table_) {\n case 0: {\n if (snap_->head_arena.get() &&\n snap_->head_arena->getCSTableFile()) {\n cur_skiplist_.reset(\n new PartitionArena::SkiplistReader(\n snap_->head_arena->getSkiplistReader()));\n cstable = cstable::CSTableReader::openFile(\n snap_->head_arena->getCSTableFile(),\n cur_skiplist_->size());\n cstable_filename = StringUtil::format(\n \"memory:\/\/$0\/$1\/$2\/head_arena\",\n snap_->state.tsdb_namespace(),\n snap_->state.table_key(),\n snap_->key.toString());\n break;\n } else {\n ++cur_table_;\n \/* fallthrough *\/\n }\n }\n\n case 1: {\n if (snap_->compacting_arena.get() &&\n snap_->compacting_arena->getCSTableFile()) {\n cur_skiplist_.reset(\n new PartitionArena::SkiplistReader(\n snap_->compacting_arena->getSkiplistReader()));\n cstable = cstable::CSTableReader::openFile(\n snap_->compacting_arena->getCSTableFile(),\n cur_skiplist_->size());\n cstable_filename = StringUtil::format(\n \"memory:\/\/$0\/$1\/$2\/compacting_arena\",\n snap_->state.tsdb_namespace(),\n snap_->state.table_key(),\n snap_->key.toString());\n break;\n } else {\n ++cur_table_;\n \/* fallthrough *\/\n }\n }\n\n default: {\n if (cur_table_ >= snap_->state.lsm_tables().size() + 2) {\n return false;\n }\n auto tblidx = snap_->state.lsm_tables().size() - (cur_table_ - 1);\n const auto& tbl = (snap_->state.lsm_tables().data())[tblidx];\n auto cstable_file = FileUtil::joinPaths(\n snap_->base_path,\n tbl->filename() + \".cst\");\n cstable = cstable::CSTableReader::openFile(cstable_file);\n cstable_filename = cstable_file;\n if (tbl->has_skiplist()) {\n skip_col = cstable->getColumnReader(\"__lsm_skip\");\n }\n\n if (!tbl->has_skiplist() && tblidx == 0 && id_set_.empty()) {\n needs_filter = false;\n }\n break;\n }\n }\n\n \/* read filter *\/\n std::vector<bool> filter(cstable->numRecords(), true);\n if (needs_filter) {\n auto id_col = cstable->getColumnReader(\"__lsm_id\");\n auto is_update_col = cstable->getColumnReader(\"__lsm_is_update\");\n for (size_t i = 0; i < filter.size(); ++i) {\n uint64_t rlvl;\n uint64_t dlvl;\n\n String id_str;\n id_col->readString(&rlvl, &dlvl, &id_str);\n SHA1Hash id(id_str.data(), id_str.size());\n\n bool is_update;\n is_update_col->readBoolean(&rlvl, &dlvl, &is_update);\n\n bool skip = false;\n if (skip_col.get()) {\n skip_col->readBoolean(&rlvl, &dlvl, &skip);\n }\n\n if (cur_skiplist_) {\n skip = cur_skiplist_->readNext();\n }\n\n if (skip || id_set_.count(id) > 0) {\n filter[i] = false;\n } else {\n if (is_update) {\n id_set_.emplace(id);\n }\n\n filter[i] = true;\n }\n }\n }\n\n if (fast_scan_enabled_) {\n cur_scan_.reset(\n new csql::FastCSTableScan(\n txn_,\n execution_context_,\n stmt_,\n cstable,\n cstable_filename));\n } else {\n cur_scan_.reset(\n new csql::CSTableScan(\n txn_,\n execution_context_,\n stmt_,\n cstable,\n cstable_filename));\n }\n\n if (needs_filter) {\n cur_scan_->setFilter(std::move(filter));\n }\n\n ++cur_table_;\n\n auto rc = cur_scan_->execute();\n if (!rc.isSuccess()) {\n RAISE(kRuntimeError, rc.getMessage());\n }\n\n return true;\n}\n\nsize_t PartitionCursor::getColumnCount() const {\n return stmt_->getNumComputedColumns();\n}\n\ncsql::SType PartitionCursor::getColumnType(size_t idx) const {\n return stmt_->getColumnType(idx);\n}\n\nRemotePartitionCursor::RemotePartitionCursor(\n Session* session,\n csql::Transaction* txn,\n csql::ExecutionContext* execution_context,\n const std::string& database,\n RefPtr<csql::SequentialScanNode> stmt,\n const std::vector<std::string>& servers) :\n txn_(txn),\n execution_context_(execution_context),\n database_(database),\n stmt_(stmt),\n servers_(servers),\n ncols_(stmt->getNumComputedColumns()),\n row_buf_pos_(0),\n running_(false),\n done_(false),\n timeout_(\n session->getDatabaseContext()->config->getInt(\n \"server.s2s_io_timeout\").get()),\n client_(\n session->getDatabaseContext()->connection_pool,\n session->getDatabaseContext()->dns_cache,\n session->getDatabaseContext()->config->getInt(\n \"server.s2s_io_timeout\",\n 0),\n session->getDatabaseContext()->config->getInt(\n \"server.s2s_idle_timeout\",\n 0)) {}\n\nReturnCode RemotePartitionCursor::execute() {\n return ReturnCode::success();\n}\n\nReturnCode RemotePartitionCursor::nextBatch(\n csql::SVector* output,\n size_t* output_len) {\n if (done_) {\n *output_len = 0;\n return ReturnCode::success();\n }\n\n if (running_) {\n auto rc = client_.sendFrame(EVQL_OP_QUERY_CONTINUE, 0, nullptr, 0);\n if (!rc.isSuccess()) {\n return rc;\n }\n } else {\n auto session = static_cast<eventql::Session*>(txn_->getUserData());\n auto cdir = session->getDatabaseContext()->config_directory;\n\n std::string qtree_coded;\n auto qtree_coded_os = StringOutputStream::fromString(&qtree_coded);\n csql::QueryTreeCoder qtree_coder(txn_);\n qtree_coder.encode(stmt_.get(), qtree_coded_os.get());\n\n native_transport::QueryRemoteFrame q_frame;\n q_frame.setEncodedQtree(std::move(qtree_coded));\n q_frame.setDatabase(session->getEffectiveNamespace());\n\n for (const auto& s : servers_) {\n auto server_cfg = cdir->getServerConfig(s);\n if (server_cfg.server_status() != SERVER_UP) {\n logError(\"evqld\", \"server is down: $0\", s);\n continue;\n }\n\n auto rc = client_.connect(server_cfg.server_addr(), true);\n if (!rc.isSuccess()) {\n logError(\"evqld\", \"Remote SQL Error: $0\", rc.getMessage());\n continue;\n }\n\n rc = client_.sendFrame(&q_frame, 0);\n if (rc.isSuccess()) {\n running_ = true;\n } else {\n logError(\"evqld\", \"Remote SQL Error: $0\", rc.getMessage());\n continue;\n }\n }\n\n if (!running_) {\n return ReturnCode::error(\"ERUNTIME\", \"no server available for query\");\n }\n }\n\n uint16_t ret_opcode = 0;\n uint16_t ret_flags;\n std::string ret_payload;\n while (ret_opcode != EVQL_OP_QUERY_REMOTE_RESULT) {\n auto rc = txn_->triggerHeartbeat();\n if (!rc.isSuccess()) {\n return rc;\n }\n\n rc = client_.recvFrame(&ret_opcode, &ret_flags, &ret_payload, timeout_);\n if (!rc.isSuccess()) {\n return rc;\n }\n\n if (ret_flags & EVQL_ENDOFREQUEST) {\n done_ = true;\n }\n\n switch (ret_opcode) {\n case EVQL_OP_HEARTBEAT:\n continue;\n case EVQL_OP_QUERY_REMOTE_RESULT:\n break;\n case EVQL_OP_ERROR: {\n native_transport::ErrorFrame eframe;\n eframe.parseFrom(ret_payload.data(), ret_payload.size());\n return ReturnCode::error(\"ERUNTIME\", eframe.getError());\n }\n default:\n return ReturnCode::error(\"ERUNTIME\", \"invalid opcode\");\n }\n }\n\n native_transport::QueryRemoteResultFrame r_frame;\n auto rc = r_frame.parseFrom(ret_payload.data(), ret_payload.size());\n\n if (r_frame.getColumnCount() != ncols_) {\n return ReturnCode::error(\"ERUNTIME\", \"invalid column count\");\n }\n\n for (size_t i = 0; i < ncols_; ++i) {\n const auto& coldata = r_frame.getColumnData(i);\n output[i].append(coldata.data(), coldata.size());\n }\n\n *output_len = r_frame.getRowCount();\n return ReturnCode::success();\n}\n\nsize_t RemotePartitionCursor::getColumnCount() const {\n return stmt_->getNumComputedColumns();\n}\n\ncsql::SType RemotePartitionCursor::getColumnType(size_t idx) const {\n return stmt_->getColumnType(idx);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n +----------------------------------------------------------------------+\n | PHP Version 5 |\n +----------------------------------------------------------------------+\n | Copyright (c) 1997-2013 The PHP Group |\n +----------------------------------------------------------------------+\n | http:\/\/www.opensource.org\/licenses\/mit-license.php MIT License |\n +----------------------------------------------------------------------+\n | Author: Jani Taskinen <jani.taskinen@iki.fi> |\n | Author: Patrick Reilly <preilly@php.net> |\n +----------------------------------------------------------------------+\n*\/\n\n\/* $Id$ *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"php_v8js_macros.h\"\n\nextern \"C\" {\n#include \"zend_exceptions.h\"\n}\n\n\/* Forward declarations *\/\nvoid php_v8js_commonjs_normalise_identifier(char *base, char *identifier, char *normalised_path, char *module_name);\n\n\/* global.exit - terminate execution *\/\nV8JS_METHOD(exit) \/* {{{ *\/\n{\n\tv8::V8::TerminateExecution();\n}\n\/* }}} *\/\n\n\/* global.sleep - sleep for passed seconds *\/\nV8JS_METHOD(sleep) \/* {{{ *\/\n{\n\tphp_sleep(info[0]->Int32Value());\n}\n\/* }}} *\/\n\n\/* global.print - php print() *\/\nV8JS_METHOD(print) \/* {{{ *\/\n{\n\tint ret = 0;\n\tTSRMLS_FETCH();\n\n\tfor (int i = 0; i < info.Length(); i++) {\n\t\tv8::String::Utf8Value str(info[i]);\n\t\tconst char *cstr = ToCString(str);\n\t\tret = PHPWRITE(cstr, strlen(cstr));\n\t}\n\tinfo.GetReturnValue().Set(V8JS_INT(ret));\n}\n\/* }}} *\/\n\nstatic void _php_v8js_dumper(v8::Local<v8::Value> var, int level TSRMLS_DC) \/* {{{ *\/\n{\n\tv8::String::Utf8Value str(var->ToDetailString());\n\tconst char *valstr = ToCString(str);\n\tsize_t valstr_len = (valstr) ? strlen(valstr) : 0;\n\n\tif (level > 1) {\n\t\tphp_printf(\"%*c\", (level - 1) * 2, ' ');\n\t}\n\n\tif (var->IsString())\n\t{\n\t\tphp_printf(\"string(%zu) \\\"%s\\\"\\n\", valstr_len, valstr);\n\t}\n\telse if (var->IsBoolean())\n\t{\n\t\tphp_printf(\"bool(%s)\\n\", valstr);\n\t}\n\telse if (var->IsInt32() || var->IsUint32())\n\t{\n\t\tphp_printf(\"int(%s)\\n\", valstr);\n\t}\n\telse if (var->IsNumber())\n\t{\n\t\tphp_printf(\"float(%s)\\n\", valstr);\n\t}\n\telse if (var->IsDate())\n\t{\n\t\tphp_printf(\"Date(%s)\\n\", valstr);\n\t}\n#if PHP_V8_API_VERSION >= 2003007\n\telse if (var->IsRegExp())\n\t{\n\t\tphp_printf(\"RegExp(%s)\\n\", valstr);\n\t}\n#endif\n\telse if (var->IsArray())\n\t{\n\t\tv8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(var);\n\t\tuint32_t length = array->Length();\n\n\t\tphp_printf(\"array(%d) {\\n\", length);\n\n\t\tfor (unsigned i = 0; i < length; i++) {\n\t\t\tphp_printf(\"%*c[%d] =>\\n\", level * 2, ' ', i);\n\t\t\t_php_v8js_dumper(array->Get(i), level + 1 TSRMLS_CC);\n\t\t}\n\n\t\tif (level > 1) {\n\t\t\tphp_printf(\"%*c\", (level - 1) * 2, ' ');\n\t\t}\n\n\t\tZEND_PUTS(\"}\\n\");\n\t}\n\telse if (var->IsObject())\n\t{\n\t\tv8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(var);\n\t\tV8JS_GET_CLASS_NAME(cname, object);\n\n\t\tif (var->IsFunction())\n\t\t{\n\t\t\tv8::String::Utf8Value csource(object->ToString());\n\t\t\tphp_printf(\"object(%s)#%d {\\n%*c%s\\n\", ToCString(cname), object->GetIdentityHash(), level * 2 + 2, ' ', ToCString(csource));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tv8::Local<v8::Array> keys = object->GetPropertyNames();\n\t\t\tuint32_t length = keys->Length();\n\n\t\t\tphp_printf(\"object(%s)#%d (%d) {\\n\", ToCString(cname), object->GetIdentityHash(), length);\n\n\t\t\tfor (unsigned i = 0; i < length; i++) {\n\t\t\t\tv8::Local<v8::String> key = keys->Get(i)->ToString();\n\t\t\t\tv8::String::Utf8Value kname(key);\n\t\t\t\tphp_printf(\"%*c[\\\"%s\\\"] =>\\n\", level * 2, ' ', ToCString(kname));\n\t\t\t\t_php_v8js_dumper(object->Get(key), level + 1 TSRMLS_CC);\n\t\t\t}\n\t\t}\n\n\t\tif (level > 1) {\n\t\t\tphp_printf(\"%*c\", (level - 1) * 2, ' ');\n\t\t}\n\n\t\tZEND_PUTS(\"}\\n\");\n\t}\n\telse \/* null, undefined, etc. *\/\n\t{\n\t\tphp_printf(\"<%s>\\n\", valstr);\n\t}\n}\n\/* }}} *\/\n\n\/* global.var_dump - Dump JS values *\/\nV8JS_METHOD(var_dump) \/* {{{ *\/\n{\n\tTSRMLS_FETCH();\n\n\tfor (int i = 0; i < info.Length(); i++) {\n\t\t_php_v8js_dumper(info[i], 1 TSRMLS_CC);\n\t}\n\n\tinfo.GetReturnValue().Set(V8JS_NULL);\n}\n\/* }}} *\/\n\nV8JS_METHOD(require)\n{\n\tTSRMLS_FETCH();\n\n\t\/\/ Get the extension context\n\tv8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(info.Data());\n\tphp_v8js_ctx *c = static_cast<php_v8js_ctx*>(data->Value());\n\n\t\/\/ Check that we have a module loader\n\tif (c->module_loader == NULL) {\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"No module loader\")));\n\t\treturn;\n\t}\n\n\tv8::String::Utf8Value module_id_v8(info[0]);\n\n\t\/\/ Make sure to duplicate the module name string so it doesn't get freed by the V8 garbage collector\n\tchar *module_id = estrdup(ToCString(module_id_v8));\n\tchar *normalised_path = (char *)emalloc(PATH_MAX);\n\tchar *module_name = (char *)emalloc(PATH_MAX);\n\n\tphp_v8js_commonjs_normalise_identifier(c->modules_base.back(), module_id, normalised_path, module_name);\n\tefree(module_id);\n\n\tchar *normalised_module_id = (char *)emalloc(strlen(module_id));\n\t*normalised_module_id = 0;\n\n\tif (strlen(normalised_path) > 0) {\n\t\tstrcat(normalised_module_id, normalised_path);\n\t\tstrcat(normalised_module_id, \"\/\");\n\t}\n\n\tstrcat(normalised_module_id, module_name);\n\tefree(module_name);\n\n\t\/\/ Check for module cyclic dependencies\n\tfor (std::vector<char *>::iterator it = c->modules_stack.begin(); it != c->modules_stack.end(); ++it)\n {\n \tif (!strcmp(*it, normalised_module_id)) {\n \t\tefree(normalised_path);\n\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module cyclic dependency\")));\n\t\treturn;\n \t}\n }\n\n \/\/ If we have already loaded and cached this module then use it\n\tif (V8JSG(modules_loaded).count(normalised_module_id) > 0) {\n\t\tefree(normalised_path);\n\n\t\tinfo.GetReturnValue().Set(V8JSG(modules_loaded)[normalised_module_id]);\n\t\treturn;\n\t}\n\n\t\/\/ Callback to PHP to load the module code\n\n\tzval module_code;\n\tzval *normalised_path_zend;\n\n\tMAKE_STD_ZVAL(normalised_path_zend);\n\tZVAL_STRING(normalised_path_zend, normalised_module_id, 1);\n\tzval* params[] = { normalised_path_zend };\n\n\tif (FAILURE == call_user_function(EG(function_table), NULL, c->module_loader, &module_code, 1, params TSRMLS_CC)) {\n\t\tefree(normalised_path);\n\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module loader callback failed\")));\n\t\treturn;\n\t}\n\n\t\/\/ Check if an exception was thrown\n\tif (EG(exception)) {\n\t\tefree(normalised_path);\n\n\t\t\/\/ Clear the PHP exception and throw it in V8 instead\n\t\tzend_clear_exception(TSRMLS_C);\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module loader callback exception\")));\n\t\treturn;\n\t}\n\n\t\/\/ Convert the return value to string\n\tif (Z_TYPE(module_code) != IS_STRING) {\n \tconvert_to_string(&module_code);\n\t}\n\n\t\/\/ Check that some code has been returned\n\tif (!strlen(Z_STRVAL(module_code))) {\n\t\tefree(normalised_path);\n\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module loader callback did not return code\")));\n\t\treturn;\n\t}\n\n\t\/\/ Create a template for the global object and set the built-in global functions\n\tv8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();\n\tglobal->Set(v8::String::New(\"print\"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);\n\tglobal->Set(V8JS_SYM(\"sleep\"), v8::FunctionTemplate::New(V8JS_MN(sleep)), v8::ReadOnly);\n\tglobal->Set(v8::String::New(\"require\"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);\n\n\t\/\/ Add the exports object in which the module can return its API\n\tv8::Handle<v8::ObjectTemplate> exports_template = v8::ObjectTemplate::New();\n\tv8::Handle<v8::Object> exports = exports_template->NewInstance();\n\tglobal->Set(v8::String::New(\"exports\"), exports);\n\n\t\/\/ Add the module object in which the module can have more fine-grained control over what it can return\n\tv8::Handle<v8::ObjectTemplate> module_template = v8::ObjectTemplate::New();\n\tv8::Handle<v8::Object> module = module_template->NewInstance();\n\tmodule->Set(v8::String::New(\"id\"), v8::String::New(normalised_module_id));\n\tglobal->Set(v8::String::New(\"module\"), module);\n\n\t\/\/ Each module gets its own context so different modules do not affect each other\n\tv8::Local<v8::Context> context = v8::Local<v8::Context>::New(c->isolate, v8::Context::New(c->isolate, NULL, global));\n\n\t\/\/ Catch JS exceptions\n\tv8::TryCatch try_catch;\n\n\tv8::Locker locker(c->isolate);\n\tv8::Isolate::Scope isolate_scope(c->isolate);\n\n\tv8::HandleScope handle_scope(c->isolate);\n\n\t\/\/ Enter the module context\n\tv8::Context::Scope scope(context);\n\t\/\/ Set script identifier\n\tv8::Local<v8::String> sname = V8JS_SYM(\"require\");\n\n\tv8::Local<v8::String> source = v8::String::New(Z_STRVAL(module_code));\n\n\t\/\/ Create and compile script\n\tv8::Local<v8::Script> script = v8::Script::New(source, sname);\n\n\t\/\/ The script will be empty if there are compile errors\n\tif (script.IsEmpty()) {\n\t\tefree(normalised_path);\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module script compile failed\")));\n\t\treturn;\n\t}\n\n\t\/\/ Add this module and path to the stack\n\tc->modules_stack.push_back(normalised_module_id);\n\n\tc->modules_base.push_back(normalised_path);\n\n\t\/\/ Run script\n\tv8::Local<v8::Value> result = script->Run();\n\n\t\/\/ Remove this module and path from the stack\n\tc->modules_stack.pop_back();\n\tc->modules_base.pop_back();\n\n\tefree(normalised_path);\n\n\t\/\/ Script possibly terminated, return immediately\n\tif (!try_catch.CanContinue()) {\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module script compile failed\")));\n\t\treturn;\n\t}\n\n\t\/\/ Handle runtime JS exceptions\n\tif (try_catch.HasCaught()) {\n\t\t\/\/ Rethrow the exception back to JS\n\t\tinfo.GetReturnValue().Set(try_catch.ReThrow());\n\t\treturn;\n\t}\n\n\t\/\/ Cache the module so it doesn't need to be compiled and run again\n\t\/\/ Ensure compatibility with CommonJS implementations such as NodeJS by playing nicely with module.exports and exports\n\tif (module->Has(v8::String::New(\"exports\")) && !module->Get(v8::String::New(\"exports\"))->IsUndefined()) {\n\t\t\/\/ If module.exports has been set then we cache this arbitrary value...\n\t\tV8JSG(modules_loaded)[normalised_module_id] = handle_scope.Close(module->Get(v8::String::New(\"exports\"))->ToObject());\n\t} else {\n\t\t\/\/ ...otherwise we cache the exports object itself\n\t\tV8JSG(modules_loaded)[normalised_module_id] = handle_scope.Close(exports);\n\t}\n\n\tinfo.GetReturnValue().Set(V8JSG(modules_loaded)[normalised_module_id]);\n}\n\nvoid php_v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, php_v8js_ctx *c) \/* {{{ *\/\n{\n\tglobal->Set(V8JS_SYM(\"exit\"), v8::FunctionTemplate::New(V8JS_MN(exit)), v8::ReadOnly);\n\tglobal->Set(V8JS_SYM(\"sleep\"), v8::FunctionTemplate::New(V8JS_MN(sleep)), v8::ReadOnly);\n\tglobal->Set(V8JS_SYM(\"print\"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);\n\tglobal->Set(V8JS_SYM(\"var_dump\"), v8::FunctionTemplate::New(V8JS_MN(var_dump)), v8::ReadOnly);\n\n\tc->modules_base.push_back(\"\");\n\tglobal->Set(V8JS_SYM(\"require\"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);\n}\n\/* }}} *\/\n\n\/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: noet sw=4 ts=4 fdm=marker\n * vim<600: noet sw=4 ts=4\n *\/\n<commit_msg>Handle NULL in global.var_dump().<commit_after>\/*\n +----------------------------------------------------------------------+\n | PHP Version 5 |\n +----------------------------------------------------------------------+\n | Copyright (c) 1997-2013 The PHP Group |\n +----------------------------------------------------------------------+\n | http:\/\/www.opensource.org\/licenses\/mit-license.php MIT License |\n +----------------------------------------------------------------------+\n | Author: Jani Taskinen <jani.taskinen@iki.fi> |\n | Author: Patrick Reilly <preilly@php.net> |\n +----------------------------------------------------------------------+\n*\/\n\n\/* $Id$ *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"php_v8js_macros.h\"\n\nextern \"C\" {\n#include \"zend_exceptions.h\"\n}\n\n\/* Forward declarations *\/\nvoid php_v8js_commonjs_normalise_identifier(char *base, char *identifier, char *normalised_path, char *module_name);\n\n\/* global.exit - terminate execution *\/\nV8JS_METHOD(exit) \/* {{{ *\/\n{\n\tv8::V8::TerminateExecution();\n}\n\/* }}} *\/\n\n\/* global.sleep - sleep for passed seconds *\/\nV8JS_METHOD(sleep) \/* {{{ *\/\n{\n\tphp_sleep(info[0]->Int32Value());\n}\n\/* }}} *\/\n\n\/* global.print - php print() *\/\nV8JS_METHOD(print) \/* {{{ *\/\n{\n\tint ret = 0;\n\tTSRMLS_FETCH();\n\n\tfor (int i = 0; i < info.Length(); i++) {\n\t\tv8::String::Utf8Value str(info[i]);\n\t\tconst char *cstr = ToCString(str);\n\t\tret = PHPWRITE(cstr, strlen(cstr));\n\t}\n\tinfo.GetReturnValue().Set(V8JS_INT(ret));\n}\n\/* }}} *\/\n\nstatic void _php_v8js_dumper(v8::Local<v8::Value> var, int level TSRMLS_DC) \/* {{{ *\/\n{\n\tif (level > 1) {\n\t\tphp_printf(\"%*c\", (level - 1) * 2, ' ');\n\t}\n\n\tif (var->IsNull())\n\t{\n\t\tphp_printf(\"NULL\\n\");\n\t\treturn;\n\t}\n\n\tv8::String::Utf8Value str(var->ToDetailString());\n\tconst char *valstr = ToCString(str);\n\tsize_t valstr_len = (valstr) ? strlen(valstr) : 0;\n\n\tif (var->IsString())\n\t{\n\t\tphp_printf(\"string(%zu) \\\"%s\\\"\\n\", valstr_len, valstr);\n\t}\n\telse if (var->IsBoolean())\n\t{\n\t\tphp_printf(\"bool(%s)\\n\", valstr);\n\t}\n\telse if (var->IsInt32() || var->IsUint32())\n\t{\n\t\tphp_printf(\"int(%s)\\n\", valstr);\n\t}\n\telse if (var->IsNumber())\n\t{\n\t\tphp_printf(\"float(%s)\\n\", valstr);\n\t}\n\telse if (var->IsDate())\n\t{\n\t\tphp_printf(\"Date(%s)\\n\", valstr);\n\t}\n#if PHP_V8_API_VERSION >= 2003007\n\telse if (var->IsRegExp())\n\t{\n\t\tphp_printf(\"RegExp(%s)\\n\", valstr);\n\t}\n#endif\n\telse if (var->IsArray())\n\t{\n\t\tv8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(var);\n\t\tuint32_t length = array->Length();\n\n\t\tphp_printf(\"array(%d) {\\n\", length);\n\n\t\tfor (unsigned i = 0; i < length; i++) {\n\t\t\tphp_printf(\"%*c[%d] =>\\n\", level * 2, ' ', i);\n\t\t\t_php_v8js_dumper(array->Get(i), level + 1 TSRMLS_CC);\n\t\t}\n\n\t\tif (level > 1) {\n\t\t\tphp_printf(\"%*c\", (level - 1) * 2, ' ');\n\t\t}\n\n\t\tZEND_PUTS(\"}\\n\");\n\t}\n\telse if (var->IsObject())\n\t{\n\t\tv8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(var);\n\t\tV8JS_GET_CLASS_NAME(cname, object);\n\n\t\tif (var->IsFunction())\n\t\t{\n\t\t\tv8::String::Utf8Value csource(object->ToString());\n\t\t\tphp_printf(\"object(%s)#%d {\\n%*c%s\\n\", ToCString(cname), object->GetIdentityHash(), level * 2 + 2, ' ', ToCString(csource));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tv8::Local<v8::Array> keys = object->GetPropertyNames();\n\t\t\tuint32_t length = keys->Length();\n\n\t\t\tphp_printf(\"object(%s)#%d (%d) {\\n\", ToCString(cname), object->GetIdentityHash(), length);\n\n\t\t\tfor (unsigned i = 0; i < length; i++) {\n\t\t\t\tv8::Local<v8::String> key = keys->Get(i)->ToString();\n\t\t\t\tv8::String::Utf8Value kname(key);\n\t\t\t\tphp_printf(\"%*c[\\\"%s\\\"] =>\\n\", level * 2, ' ', ToCString(kname));\n\t\t\t\t_php_v8js_dumper(object->Get(key), level + 1 TSRMLS_CC);\n\t\t\t}\n\t\t}\n\n\t\tif (level > 1) {\n\t\t\tphp_printf(\"%*c\", (level - 1) * 2, ' ');\n\t\t}\n\n\t\tZEND_PUTS(\"}\\n\");\n\t}\n\telse \/* null, undefined, etc. *\/\n\t{\n\t\tphp_printf(\"<%s>\\n\", valstr);\n\t}\n}\n\/* }}} *\/\n\n\/* global.var_dump - Dump JS values *\/\nV8JS_METHOD(var_dump) \/* {{{ *\/\n{\n\tTSRMLS_FETCH();\n\n\tfor (int i = 0; i < info.Length(); i++) {\n\t\t_php_v8js_dumper(info[i], 1 TSRMLS_CC);\n\t}\n\n\tinfo.GetReturnValue().Set(V8JS_NULL);\n}\n\/* }}} *\/\n\nV8JS_METHOD(require)\n{\n\tTSRMLS_FETCH();\n\n\t\/\/ Get the extension context\n\tv8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(info.Data());\n\tphp_v8js_ctx *c = static_cast<php_v8js_ctx*>(data->Value());\n\n\t\/\/ Check that we have a module loader\n\tif (c->module_loader == NULL) {\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"No module loader\")));\n\t\treturn;\n\t}\n\n\tv8::String::Utf8Value module_id_v8(info[0]);\n\n\t\/\/ Make sure to duplicate the module name string so it doesn't get freed by the V8 garbage collector\n\tchar *module_id = estrdup(ToCString(module_id_v8));\n\tchar *normalised_path = (char *)emalloc(PATH_MAX);\n\tchar *module_name = (char *)emalloc(PATH_MAX);\n\n\tphp_v8js_commonjs_normalise_identifier(c->modules_base.back(), module_id, normalised_path, module_name);\n\tefree(module_id);\n\n\tchar *normalised_module_id = (char *)emalloc(strlen(module_id));\n\t*normalised_module_id = 0;\n\n\tif (strlen(normalised_path) > 0) {\n\t\tstrcat(normalised_module_id, normalised_path);\n\t\tstrcat(normalised_module_id, \"\/\");\n\t}\n\n\tstrcat(normalised_module_id, module_name);\n\tefree(module_name);\n\n\t\/\/ Check for module cyclic dependencies\n\tfor (std::vector<char *>::iterator it = c->modules_stack.begin(); it != c->modules_stack.end(); ++it)\n {\n \tif (!strcmp(*it, normalised_module_id)) {\n \t\tefree(normalised_path);\n\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module cyclic dependency\")));\n\t\treturn;\n \t}\n }\n\n \/\/ If we have already loaded and cached this module then use it\n\tif (V8JSG(modules_loaded).count(normalised_module_id) > 0) {\n\t\tefree(normalised_path);\n\n\t\tinfo.GetReturnValue().Set(V8JSG(modules_loaded)[normalised_module_id]);\n\t\treturn;\n\t}\n\n\t\/\/ Callback to PHP to load the module code\n\n\tzval module_code;\n\tzval *normalised_path_zend;\n\n\tMAKE_STD_ZVAL(normalised_path_zend);\n\tZVAL_STRING(normalised_path_zend, normalised_module_id, 1);\n\tzval* params[] = { normalised_path_zend };\n\n\tif (FAILURE == call_user_function(EG(function_table), NULL, c->module_loader, &module_code, 1, params TSRMLS_CC)) {\n\t\tefree(normalised_path);\n\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module loader callback failed\")));\n\t\treturn;\n\t}\n\n\t\/\/ Check if an exception was thrown\n\tif (EG(exception)) {\n\t\tefree(normalised_path);\n\n\t\t\/\/ Clear the PHP exception and throw it in V8 instead\n\t\tzend_clear_exception(TSRMLS_C);\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module loader callback exception\")));\n\t\treturn;\n\t}\n\n\t\/\/ Convert the return value to string\n\tif (Z_TYPE(module_code) != IS_STRING) {\n \tconvert_to_string(&module_code);\n\t}\n\n\t\/\/ Check that some code has been returned\n\tif (!strlen(Z_STRVAL(module_code))) {\n\t\tefree(normalised_path);\n\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module loader callback did not return code\")));\n\t\treturn;\n\t}\n\n\t\/\/ Create a template for the global object and set the built-in global functions\n\tv8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();\n\tglobal->Set(v8::String::New(\"print\"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);\n\tglobal->Set(V8JS_SYM(\"sleep\"), v8::FunctionTemplate::New(V8JS_MN(sleep)), v8::ReadOnly);\n\tglobal->Set(v8::String::New(\"require\"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);\n\n\t\/\/ Add the exports object in which the module can return its API\n\tv8::Handle<v8::ObjectTemplate> exports_template = v8::ObjectTemplate::New();\n\tv8::Handle<v8::Object> exports = exports_template->NewInstance();\n\tglobal->Set(v8::String::New(\"exports\"), exports);\n\n\t\/\/ Add the module object in which the module can have more fine-grained control over what it can return\n\tv8::Handle<v8::ObjectTemplate> module_template = v8::ObjectTemplate::New();\n\tv8::Handle<v8::Object> module = module_template->NewInstance();\n\tmodule->Set(v8::String::New(\"id\"), v8::String::New(normalised_module_id));\n\tglobal->Set(v8::String::New(\"module\"), module);\n\n\t\/\/ Each module gets its own context so different modules do not affect each other\n\tv8::Local<v8::Context> context = v8::Local<v8::Context>::New(c->isolate, v8::Context::New(c->isolate, NULL, global));\n\n\t\/\/ Catch JS exceptions\n\tv8::TryCatch try_catch;\n\n\tv8::Locker locker(c->isolate);\n\tv8::Isolate::Scope isolate_scope(c->isolate);\n\n\tv8::HandleScope handle_scope(c->isolate);\n\n\t\/\/ Enter the module context\n\tv8::Context::Scope scope(context);\n\t\/\/ Set script identifier\n\tv8::Local<v8::String> sname = V8JS_SYM(\"require\");\n\n\tv8::Local<v8::String> source = v8::String::New(Z_STRVAL(module_code));\n\n\t\/\/ Create and compile script\n\tv8::Local<v8::Script> script = v8::Script::New(source, sname);\n\n\t\/\/ The script will be empty if there are compile errors\n\tif (script.IsEmpty()) {\n\t\tefree(normalised_path);\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module script compile failed\")));\n\t\treturn;\n\t}\n\n\t\/\/ Add this module and path to the stack\n\tc->modules_stack.push_back(normalised_module_id);\n\n\tc->modules_base.push_back(normalised_path);\n\n\t\/\/ Run script\n\tv8::Local<v8::Value> result = script->Run();\n\n\t\/\/ Remove this module and path from the stack\n\tc->modules_stack.pop_back();\n\tc->modules_base.pop_back();\n\n\tefree(normalised_path);\n\n\t\/\/ Script possibly terminated, return immediately\n\tif (!try_catch.CanContinue()) {\n\t\tinfo.GetReturnValue().Set(v8::ThrowException(v8::String::New(\"Module script compile failed\")));\n\t\treturn;\n\t}\n\n\t\/\/ Handle runtime JS exceptions\n\tif (try_catch.HasCaught()) {\n\t\t\/\/ Rethrow the exception back to JS\n\t\tinfo.GetReturnValue().Set(try_catch.ReThrow());\n\t\treturn;\n\t}\n\n\t\/\/ Cache the module so it doesn't need to be compiled and run again\n\t\/\/ Ensure compatibility with CommonJS implementations such as NodeJS by playing nicely with module.exports and exports\n\tif (module->Has(v8::String::New(\"exports\")) && !module->Get(v8::String::New(\"exports\"))->IsUndefined()) {\n\t\t\/\/ If module.exports has been set then we cache this arbitrary value...\n\t\tV8JSG(modules_loaded)[normalised_module_id] = handle_scope.Close(module->Get(v8::String::New(\"exports\"))->ToObject());\n\t} else {\n\t\t\/\/ ...otherwise we cache the exports object itself\n\t\tV8JSG(modules_loaded)[normalised_module_id] = handle_scope.Close(exports);\n\t}\n\n\tinfo.GetReturnValue().Set(V8JSG(modules_loaded)[normalised_module_id]);\n}\n\nvoid php_v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, php_v8js_ctx *c) \/* {{{ *\/\n{\n\tglobal->Set(V8JS_SYM(\"exit\"), v8::FunctionTemplate::New(V8JS_MN(exit)), v8::ReadOnly);\n\tglobal->Set(V8JS_SYM(\"sleep\"), v8::FunctionTemplate::New(V8JS_MN(sleep)), v8::ReadOnly);\n\tglobal->Set(V8JS_SYM(\"print\"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);\n\tglobal->Set(V8JS_SYM(\"var_dump\"), v8::FunctionTemplate::New(V8JS_MN(var_dump)), v8::ReadOnly);\n\n\tc->modules_base.push_back(\"\");\n\tglobal->Set(V8JS_SYM(\"require\"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);\n}\n\/* }}} *\/\n\n\/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: noet sw=4 ts=4 fdm=marker\n * vim<600: noet sw=4 ts=4\n *\/\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nenum class Token\n{\n Invalid = 0,\n Minus = 1,\n Plus = 2,\n Mul = 3,\n Div = 4,\n Number = 5,\n End = 6\n};\n\n\/\/ получение текущего токена\nToken getToken(const char*& text, bool isShiftedAfterOperation = true, bool isShiftedAfterNumber = false)\n{\n const char* prev_text = text;\n\n while (const auto c = *text++)\n {\n switch (c) {\n case ' ':\n continue;\n case '-':\n if(!isShiftedAfterOperation)\n text = prev_text;\n return Token::Minus;\n case '+':\n if(!isShiftedAfterOperation)\n text = prev_text;\n return Token::Plus;\n case '\/':\n if(!isShiftedAfterOperation)\n text = prev_text;\n return Token::Div;\n case '*':\n if(!isShiftedAfterOperation)\n text = prev_text;\n return Token::Mul;\n }\n\n if (c >= '0' && c <= '9') {\n for (auto c = *(text); c>= '0' && c<= '9';)\n {\n \/\/skip digits\n ++text;\n c = *text;\n }\n\n if(!isShiftedAfterNumber)\n text = prev_text;\n\n return Token::Number;\n }\n return Token::Invalid;\n }\n return Token ::End;\n}\n\n\/\/ вычисление числа с унарным минусом\nint prim(const char*& text)\n{\n\n bool isNegative = false;\n if(getToken(text) == Token::Minus)\n {\n isNegative = true;\n }\n\n int res = 0;\n bool isNumber = false;\n for(;(*text >= '0' && *text <= '9') || *text == ' ' ; ++text)\n {\n if(*text == ' ')\n continue;\n\n res = res * 10 + (*text - '0');\n isNumber = true;\n }\n\n if(!isNumber)\n throw std::exception();\n\n if(isNegative)\n return -res;\n else\n return res;\n}\n\n\n\/\/ вычисление терма в выражении\nint term(const char*& text)\n{\n int res = prim(text);\n\n Token tk = getToken(text);\n while (tk == Token::Mul || tk == Token::Div)\n {\n if(tk == Token::Mul)\n {\n res *= prim(text);\n }\n\n if(tk == Token::Div)\n {\n res\/= prim(text);\n }\n\n tk = getToken(text);\n }\n --text;\n\n return res;\n}\n\n\/\/ сложение и вычитание термов\nint expr(const char*& text)\n{\n int res = term(text);\n\n Token tk;\n\n tk = getToken(text);\n for (;tk != Token::End; tk = getToken(text))\n {\n\n if(tk == Token::Invalid)\n {\n throw std::exception();\n }\n\n if(tk == Token::Plus)\n {\n res += term(text);\n }\n if(tk == Token::Minus)\n {\n res -= term(text);\n }\n }\n\n return res;\n}\n\n\nint main(int argc, char* argv[])\n{\n const char* text = \"1 + 2\/2 * 3 - -4*-1\";\n\n if (argc == 1) \n {\n std::cout << \"Empty input!\" << std::endl;\n return 2;\n }\n text = argv[1];\n\n if(getToken(text, false, false) == Token::End)\n {\n std::cout<<\"Empty input!\"<< std::endl;\n return 2;\n }\n\n try\n {\n int res = expr(text);\n std::cout<<res<<std::endl;\n }\n catch (std::exception ex)\n {\n std::cout<<\"error in input!\"<<std::endl;\n }\n\n return 0;\n}\n<commit_msg>hw2 update<commit_after>#include <iostream>\n\n\nenum class Token\n{\n Invalid = 0,\n Minus = 1,\n Plus = 2,\n Mul = 3,\n Div = 4,\n Number = 5,\n End = 6\n};\n\n\n\/\/ получение текущего токена\nToken getToken(const char*& text, bool isShiftedAfterOperation = true, bool isShiftedAfterNumber = false)\n{\n const char* prev_text = text;\n\n while (const auto c = *text++)\n {\n switch (c) {\n case ' ':\n continue;\n case '-':\n if(!isShiftedAfterOperation)\n text = prev_text;\n return Token::Minus;\n case '+':\n if(!isShiftedAfterOperation)\n text = prev_text;\n return Token::Plus;\n case '\/':\n if(!isShiftedAfterOperation)\n text = prev_text;\n return Token::Div;\n case '*':\n if(!isShiftedAfterOperation)\n text = prev_text;\n return Token::Mul;\n }\n\n if (c >= '0' && c <= '9') {\n for (auto c = *(text); c>= '0' && c<= '9';)\n {\n \/\/skip digits\n ++text;\n c = *text;\n }\n\n if(!isShiftedAfterNumber)\n text = prev_text;\n\n return Token::Number;\n }\n return Token::Invalid;\n }\n return Token ::End;\n}\n\nbool isNegativeNumber(const char*& text)\n{\n const char* prev_text = text;\n\n if(getToken(text) == Token::Minus)\n {\n return true;\n }\n\n\n text = prev_text;\n return false;\n}\n\n\/\/ вычисление числа с унарным минусом\nint prim(const char*& text)\n{\n\n bool isNegative = isNegativeNumber(text);\n\n int res = 0;\n bool isNumber = false;\n\n for(;(*text >= '0' && *text <= '9') || *text == ' ' ; ++text)\n {\n if(*text == ' ')\n continue;\n\n res = res * 10 + (*text - '0');\n isNumber = true;\n }\n\n if(!isNumber)\n throw std::runtime_error(\"Error in number input!\");\n\n if(isNegative)\n return -res;\n else\n return res;\n}\n\n\n\/\/ вычисление терма в выражении\nint term(const char*& text)\n{\n int res = prim(text);\n\n Token tk = getToken(text);\n while (tk == Token::Mul || tk == Token::Div)\n {\n if(tk == Token::Mul)\n {\n int pr = prim(text);\n res *= pr;\n }\n\n if(tk == Token::Div)\n {\n int pr = prim(text);\n if(pr == 0)\n {\n throw std::runtime_error(\"Division by zero!\");\n }\n\n res \/= pr;\n }\n\n tk = getToken(text);\n }\n --text;\n\n return res;\n}\n\n\/\/ сложение и вычитание термов\nint expr(const char*& text)\n{\n int res = term(text);\n\n Token tk;\n\n tk = getToken(text);\n for (;tk != Token::End; tk = getToken(text))\n {\n\n if(tk == Token::Invalid)\n {\n throw std::runtime_error(\"Invalid character!\");\n }\n\n if(tk == Token::Plus)\n {\n res += term(text);\n }\n if(tk == Token::Minus)\n {\n res -= term(text);\n }\n }\n\n return res;\n}\n\n\nint main(int argc, char* argv[])\n{\n const char* text = \"\";\n\n\n if (argc == 1)\n {\n std::cout << \"Empty input!\" << std::endl;\n return -1;\n }\n text = argv[1];\n\n if(getToken(text, false, false) == Token::End)\n {\n std::cout<<\"Empty input!\"<< std::endl;\n return -1;\n }\n\n\n try\n {\n int res = expr(text);\n std::cout<<res<<std::endl;\n }\n catch (std::exception& ex)\n {\n std::cout<<ex.what()<<std::endl;\n return -1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include \"smc_compiler.h\"\n#include \"gen.h\"\n\nusing namespace std;\n\nstatic void generate_state_map(state_map_t const& state_map, std::string const& package_name, std::string const& fsmclass, std::string const& class_name, std::set<string> const& action_set, transition_set_t const& transition_set);\n\nvoid gen_swift(std::string const& package_name, std::string const& fsmclass, state_map_list_t const& state_map_list, std::string const& start_map, std::string const& start_state, transition_set_t const& transition_set, std::string const& class_name, std::set<string> const& action_set)\n{\n string full_fsm_name = package_name + \"_\" + fsmclass;\n\n cout << \"\/\/ -*- tab-width: 4; -*-\\n\";\n cout << \"\/\/ -*- coding: utf-8 -*-\\n\";\n cout << \"\\n\";\n cout << \"\/\/\\n\";\n cout << \"\/\/ This file is automatically generated by State Machine Generator.\\n\";\n cout << \"\/\/\\n\";\n cout << \"\\n\";\n\n cout\n << \"import Foundation\\n\"\n << \"\\n\"\n ;\n\n cout << \"public protocol \" << package_name << \"_Action {\\n\";\n for (auto const& action : action_set) {\n cout << \" func \" << action << \"()\\n\";\n }\n cout << \"}\\n\";\n\n cout << \"public class \" << class_name << \" : \" << package_name << \"_Action {\\n\";\n for (auto const& action : action_set) {\n cout << \" public func \" << action << \"() {}\\n\";\n }\n cout << \"}\\n\";\n\n cout\n << \"\\n\"\n << \"public class \" << full_fsm_name << \" {\\n\"\n << \"\\n\"\n << \" private var currentState : \" << package_name << \"_ButtonStateMap_State?\\n\"\n << \" private var previousState : \" << package_name << \"_ButtonStateMap_State?\\n\"\n << \" public var debugMode = false\\n\"\n << \" let ctxt : \" << class_name << \"\\n\"\n << \"\\n\"\n << \" public init(ctxt:\" << class_name << \") {\\n\"\n << \" self.currentState = _\" << package_name << \"_\" << start_map << \".\" << start_state << \"()\\n\"\n << \" self.ctxt = ctxt\\n\"\n << \" }\\n\"\n << \"\\n\"\n << \" public func enterStartState() {\\n\"\n << \" currentState!.Entry(self, ctxt: ctxt)\\n\"\n << \" }\\n\"\n << \"\\n\"\n << \" private func setState(state:\" << package_name << \"_ButtonStateMap_State) {\\n\"\n << \" currentState = state;\\n\"\n << \" if (debugMode) {\\n\"\n << \" NSLog(\\\"ENTER STATE: %s\\\", state.getName())\\n\"\n << \" }\\n\"\n << \" }\\n\"\n ;\n\n for (auto&& transition_name : transition_set) {\n cout << \"\\n\";\n cout << \" public func \" << transition_name << \"() {\\n\";\n cout << \" currentState!.\" << transition_name << \"(self, ctxt: ctxt)\\n\";\n cout << \" }\\n\";\n }\n\n cout << \"\\n\";\n cout << \"}\\n\";\n cout << \"\\n\";\n cout << \"\\n\";\n cout << \"\\n\";\n\n for (auto&& state_map : state_map_list) {\n generate_state_map(state_map, package_name, fsmclass, class_name, action_set, transition_set);\n }\n}\n\n\nstatic void generate_state_map(state_map_t const& state_map, std::string const& package_name, std::string const& fsmclass, std::string const& class_name, std::set<string> const& action_set, transition_set_t const& transition_set)\n{\n string full_fsm_name = package_name + \"_\" + fsmclass;\n\n string const& state_map_name = package_name + \"_\" + state_map.get_state_map_name();\n state_list_t const& state_list = state_map.get_state_list();\n\n \/\/ カスタムアクションの出力とステート遷移の出力\n auto generate_transition = [&](transition_t const& transition, int indent)\n {\n intented_out out(cout, indent);\n\n \/\/ 遷移先のステートがある場合には Exit() を出力する。\n if ( !transition.get_next_state().empty()) {\n out << \"fsm.currentState!.Exit(fsm, ctxt: ctxt)\\n\";\n }\n\n \/\/ 現在のステートをNULLにセットする。\n out << \"fsm.previousState = fsm.currentState\\n\";\n\n \/\/ カスタムアクションを出力する。\n if ( !transition.get_action_list().empty()) {\n out << \"fsm.currentState = nil\\n\";\n out << \"\/\/try {\" << \"\\n\";\n out << \"\/\/ Custom action\" << \"\\n\";\n }\n\n for (auto const& action : transition.get_action_list()) {\n out << \"ctxt.\" << action << \"()\\n\";\n }\n\n \/\/ 次の遷移先への移動をfinally区の中に入れるかどうか\n int next_state_indent = 0;\n\n if ( !transition.get_action_list().empty()) {\n out << \"\/\/} finally {\" << \"\\n\";\n \/\/next_state_indent++;\n }\n\n \/\/ 遷移先のステートがある場合には Entry() を出力する。\n if (transition.get_next_state().empty()) {\n out(next_state_indent) << \"fsm.currentState = previousState\\n\";\n }\n else {\n out(next_state_indent) << \"fsm.setState(\" << state_map_name << \"._\" << transition.get_next_state() << \")\\n\";\n out(next_state_indent) << \"fsm.currentState!.Entry(fsm, ctxt: ctxt)\\n\";\n }\n\n if ( !transition.get_action_list().empty()) {\n out << \"\/\/}\" << \"\\n\";\n }\n };\n\n cout << \"private protocol \" << state_map_name << \"_State {\\n\";\n cout << \" func getName() -> String\\n\";\n cout << \" func Entry(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \")\\n\";\n cout << \" func Exit(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \")\\n\";\n for (auto&& transition_name : transition_set) {\n cout << \" func \" << transition_name << \"(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \")\\n\";\n }\n cout << \"}\\n\";\n\n intented_out out(cout, 0);\n bool need_comma = false;\n out << \"let \" << state_map_name << \" = _\" << state_map_name << \"()\\n\";\n cout << \"\\n\";\n out << \"public class _\" << state_map_name << \" {\\n\";\n for (auto const& state : state_list) {\n cout << \" let _\" << state.get_state_name() << \" = \" << state.get_state_name() << \"()\\n\";\n }\n\n\n\n cout << \"\\n\";\n out(1) << \"public class DefaultState : \" << state_map_name << \"_State {\\n\";\n out(2) << \"public func getName() -> String { return \\\"DefaultState\\\" }\\n\\n\";\n out(2) << \"public func Entry(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {}\\n\";\n out(2) << \"public func Exit(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {}\\n\";\n\n for (auto&& transition_name : transition_set) {\n out(2) << \"public func \" << transition_name << \"(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {}\\n\";\n }\n out(1) << \"}\\n\";\n cout << \"\\n\";\n\n\n\n for (auto const& state : state_list) {\n if (need_comma) cout << \"\\n\";\n\n cout << \"\\n\";\n out(1) << \"public class \" << state.get_state_name() << \" : DefaultState {\\n\";\n out(2) << \"override public func getName() -> String { return \\\"\" << state.get_state_name() << \"\\\" }\\n\\n\";\n out(2) << \"override public func Entry(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {\\n\";\n\n for (auto&& action : state.get_entry()) {\n out(3) << \"ctxt.\" << action << \"()\\n\";\n }\n out(2) << \"}\\n\";\n cout << \"\\n\";\n out(2) << \"override public func Exit(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {\\n\";\n ;\n for (auto const& action : state.get_exit()) {\n out(3) << \"ctxt.\" << action << \"()\\n\";\n }\n out(2) << \"}\\n\";\n\n for (auto const& transition_name_list_pair : state.get_transitions()) {\n string const& transition_name = transition_name_list_pair.first;\n\n cout << \"\\n\";\n out(2) << \"override public func \" << transition_name << \"(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {\\n\";\n\n bool else_block = false;\n for (auto&& transition : transition_name_list_pair.second) {\n if ( !transition.get_guard().empty()) {\n out(3) << (else_block ? \"else if\" : \"if\") << \" (\" << transition.get_guard() << \") {\\n\";\n\n generate_transition(transition, 5);\n\n out(3) << \"}\\n\";\n else_block = true;\n }\n else {\n if (else_block) {\n out(3) << \"else {\\n\";\n }\n\n generate_transition(transition, else_block ? 4 : 3);\n\n if (else_block) {\n out(3) << \"}\\n\";\n }\n }\n }\n\n out(2) << \"}\\n\";\n }\n\n cout << \"\\n\";\n out(1) << \"}\\n\"\n ;\n need_comma = true;\n }\n\n cout << \"}\" << endl;\n\n}\n<commit_msg>Swiftのコード生成を調整<commit_after>#include <iostream>\n#include <string>\n#include \"smc_compiler.h\"\n#include \"gen.h\"\n\nusing namespace std;\n\nstatic void generate_state_map(state_map_t const& state_map, std::string const& package_name, std::string const& fsmclass, std::string const& class_name, std::set<string> const& action_set, transition_set_t const& transition_set);\n\nvoid gen_swift(std::string const& package_name, std::string const& fsmclass, state_map_list_t const& state_map_list, std::string const& start_map, std::string const& start_state, transition_set_t const& transition_set, std::string const& class_name, std::set<string> const& action_set)\n{\n string full_fsm_name = package_name + \"_\" + fsmclass;\n\n cout << \"\/\/ -*- tab-width: 4; -*-\\n\";\n cout << \"\/\/ -*- coding: utf-8 -*-\\n\";\n cout << \"\\n\";\n cout << \"\/\/\\n\";\n cout << \"\/\/ This file is automatically generated by State Machine Generator.\\n\";\n cout << \"\/\/\\n\";\n cout << \"\\n\";\n\n cout\n << \"import Foundation\\n\"\n << \"\\n\"\n ;\n\n cout << \"public protocol \" << package_name << \"_Action {\\n\";\n for (auto const& action : action_set) {\n cout << \" func \" << action << \"()\\n\";\n }\n cout << \"}\\n\";\n\n cout << \"\/\/public class \" << class_name << \" : \" << package_name << \"_Action {\\n\";\n for (auto const& action : action_set) {\n cout << \"\/\/ public func \" << action << \"() {}\\n\";\n }\n cout << \"\/\/}\\n\";\n\n cout\n << \"\\n\"\n << \"public class \" << full_fsm_name << \" {\\n\"\n << \"\\n\"\n << \" private var currentState : \" << package_name << \"_ButtonStateMap_State?\\n\"\n << \" private var previousState : \" << package_name << \"_ButtonStateMap_State?\\n\"\n << \" public var debugMode = false\\n\"\n << \" let ctxt : \" << class_name << \"\\n\"\n << \"\\n\"\n << \" public init(context:\" << class_name << \") {\\n\"\n << \" self.currentState = _\" << package_name << \"_\" << start_map << \"._\" << start_state << \"\\n\"\n << \" self.ctxt = context\\n\"\n << \" }\\n\"\n << \"\\n\"\n << \" public func enterStartState() {\\n\"\n << \" currentState!.Entry(self, ctxt: ctxt)\\n\"\n << \" }\\n\"\n << \"\\n\"\n << \" private func setState(state:\" << package_name << \"_ButtonStateMap_State) {\\n\"\n << \" currentState = state;\\n\"\n << \" if (debugMode) {\\n\"\n << \" NSLog(\\\"ENTER STATE: %s\\\", state.getName())\\n\"\n << \" }\\n\"\n << \" }\\n\"\n ;\n\n for (auto&& transition_name : transition_set) {\n cout << \"\\n\";\n cout << \" public func \" << transition_name << \"() {\\n\";\n cout << \" currentState!.\" << transition_name << \"(self, ctxt: ctxt)\\n\";\n cout << \" }\\n\";\n }\n\n cout << \"\\n\";\n cout << \"}\\n\";\n cout << \"\\n\";\n cout << \"\\n\";\n cout << \"\\n\";\n\n for (auto&& state_map : state_map_list) {\n generate_state_map(state_map, package_name, fsmclass, class_name, action_set, transition_set);\n }\n}\n\n\nstatic void generate_state_map(state_map_t const& state_map, std::string const& package_name, std::string const& fsmclass, std::string const& class_name, std::set<string> const& action_set, transition_set_t const& transition_set)\n{\n string full_fsm_name = package_name + \"_\" + fsmclass;\n\n string const& state_map_name = package_name + \"_\" + state_map.get_state_map_name();\n state_list_t const& state_list = state_map.get_state_list();\n\n \/\/ カスタムアクションの出力とステート遷移の出力\n auto generate_transition = [&](transition_t const& transition, int indent)\n {\n intented_out out(cout, indent);\n\n \/\/ 遷移先のステートがある場合には Exit() を出力する。\n if ( !transition.get_next_state().empty()) {\n out << \"fsm.currentState!.Exit(fsm, ctxt: ctxt)\\n\";\n }\n\n \/\/ 現在のステートをNULLにセットする。\n out << \"fsm.previousState = fsm.currentState\\n\";\n\n \/\/ カスタムアクションを出力する。\n if ( !transition.get_action_list().empty()) {\n out << \"fsm.currentState = nil\\n\";\n out << \"\/\/try {\" << \"\\n\";\n out << \"\/\/ Custom action\" << \"\\n\";\n }\n\n for (auto const& action : transition.get_action_list()) {\n out << \"ctxt.\" << action << \"()\\n\";\n }\n\n \/\/ 次の遷移先への移動をfinally区の中に入れるかどうか\n int next_state_indent = 0;\n\n if ( !transition.get_action_list().empty()) {\n out << \"\/\/} finally {\" << \"\\n\";\n \/\/next_state_indent++;\n }\n\n \/\/ 遷移先のステートがある場合には Entry() を出力する。\n if (transition.get_next_state().empty()) {\n out(next_state_indent) << \"fsm.currentState = previousState\\n\";\n }\n else {\n out(next_state_indent) << \"fsm.setState(\" << state_map_name << \"._\" << transition.get_next_state() << \")\\n\";\n out(next_state_indent) << \"fsm.currentState!.Entry(fsm, ctxt: ctxt)\\n\";\n }\n\n if ( !transition.get_action_list().empty()) {\n out << \"\/\/}\" << \"\\n\";\n }\n };\n\n cout << \"private protocol \" << state_map_name << \"_State {\\n\";\n cout << \" func getName() -> String\\n\";\n cout << \" func Entry(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \")\\n\";\n cout << \" func Exit(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \")\\n\";\n for (auto&& transition_name : transition_set) {\n cout << \" func \" << transition_name << \"(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \")\\n\";\n }\n cout << \"}\\n\";\n\n intented_out out(cout, 0);\n bool need_comma = false;\n out << \"let \" << state_map_name << \" = _\" << state_map_name << \"()\\n\";\n cout << \"\\n\";\n out << \"public class _\" << state_map_name << \" {\\n\";\n for (auto const& state : state_list) {\n cout << \" let _\" << state.get_state_name() << \" = \" << state.get_state_name() << \"()\\n\";\n }\n\n\n\n cout << \"\\n\";\n out(1) << \"public class DefaultState : \" << state_map_name << \"_State {\\n\";\n out(2) << \"public func getName() -> String { return \\\"DefaultState\\\" }\\n\\n\";\n out(2) << \"public func Entry(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {}\\n\";\n out(2) << \"public func Exit(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {}\\n\";\n\n for (auto&& transition_name : transition_set) {\n out(2) << \"public func \" << transition_name << \"(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {}\\n\";\n }\n out(1) << \"}\\n\";\n cout << \"\\n\";\n\n\n\n for (auto const& state : state_list) {\n if (need_comma) cout << \"\\n\";\n\n cout << \"\\n\";\n out(1) << \"public class \" << state.get_state_name() << \" : DefaultState {\\n\";\n out(2) << \"override public func getName() -> String { return \\\"\" << state.get_state_name() << \"\\\" }\\n\\n\";\n out(2) << \"override public func Entry(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {\\n\";\n\n for (auto&& action : state.get_entry()) {\n out(3) << \"ctxt.\" << action << \"()\\n\";\n }\n out(2) << \"}\\n\";\n cout << \"\\n\";\n out(2) << \"override public func Exit(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {\\n\";\n ;\n for (auto const& action : state.get_exit()) {\n out(3) << \"ctxt.\" << action << \"()\\n\";\n }\n out(2) << \"}\\n\";\n\n for (auto const& transition_name_list_pair : state.get_transitions()) {\n string const& transition_name = transition_name_list_pair.first;\n\n cout << \"\\n\";\n out(2) << \"override public func \" << transition_name << \"(fsm:\" << full_fsm_name << \", ctxt:\" << class_name << \") {\\n\";\n\n bool else_block = false;\n for (auto&& transition : transition_name_list_pair.second) {\n if ( !transition.get_guard().empty()) {\n out(3) << (else_block ? \"else if\" : \"if\") << \" (\" << transition.get_guard() << \") {\\n\";\n\n generate_transition(transition, 5);\n\n out(3) << \"}\\n\";\n else_block = true;\n }\n else {\n if (else_block) {\n out(3) << \"else {\\n\";\n }\n\n generate_transition(transition, else_block ? 4 : 3);\n\n if (else_block) {\n out(3) << \"}\\n\";\n }\n }\n }\n\n out(2) << \"}\\n\";\n }\n\n cout << \"\\n\";\n out(1) << \"}\\n\"\n ;\n need_comma = true;\n }\n\n cout << \"}\" << endl;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode:C++; c-file-style:\"gnu\"; indent-tabs-mode:nil -*- *\/\n\/**\n * Copyright (C) 2013 Regents of the University of California.\n * @author: Jeff Thompson <jefft0@remap.ucla.edu>\n * See COPYING for copyright and distribution information.\n *\/\n\n#include \"..\/c\/util\/crypto.h\"\n#include \"..\/c\/encoding\/binary-xml-data.h\"\n#include \"..\/encoding\/binary-xml-encoder.hpp\"\n#include <ndn-cpp\/sha256-with-rsa-signature.hpp>\n#include \"..\/util\/logging.hpp\"\n#include <ndn-cpp\/security\/security-exception.hpp>\n#include <ndn-cpp\/security\/policy\/policy-manager.hpp>\n#include <ndn-cpp\/security\/key-chain.hpp>\n\nusing namespace std;\nusing namespace ndn::ptr_lib;\n\nnamespace ndn {\n\n#if 1\nstatic uint8_t DEFAULT_PUBLIC_KEY_DER[] = {\n0x30, 0x81, 0x9F, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81,\n0x8D, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xE1, 0x7D, 0x30, 0xA7, 0xD8, 0x28, 0xAB, 0x1B, 0x84, 0x0B, 0x17,\n0x54, 0x2D, 0xCA, 0xF6, 0x20, 0x7A, 0xFD, 0x22, 0x1E, 0x08, 0x6B, 0x2A, 0x60, 0xD1, 0x6C, 0xB7, 0xF5, 0x44, 0x48, 0xBA,\n0x9F, 0x3F, 0x08, 0xBC, 0xD0, 0x99, 0xDB, 0x21, 0xDD, 0x16, 0x2A, 0x77, 0x9E, 0x61, 0xAA, 0x89, 0xEE, 0xE5, 0x54, 0xD3,\n0xA4, 0x7D, 0xE2, 0x30, 0xBC, 0x7A, 0xC5, 0x90, 0xD5, 0x24, 0x06, 0x7C, 0x38, 0x98, 0xBB, 0xA6, 0xF5, 0xDC, 0x43, 0x60,\n0xB8, 0x45, 0xED, 0xA4, 0x8C, 0xBD, 0x9C, 0xF1, 0x26, 0xA7, 0x23, 0x44, 0x5F, 0x0E, 0x19, 0x52, 0xD7, 0x32, 0x5A, 0x75,\n0xFA, 0xF5, 0x56, 0x14, 0x4F, 0x9A, 0x98, 0xAF, 0x71, 0x86, 0xB0, 0x27, 0x86, 0x85, 0xB8, 0xE2, 0xC0, 0x8B, 0xEA, 0x87,\n0x17, 0x1B, 0x4D, 0xEE, 0x58, 0x5C, 0x18, 0x28, 0x29, 0x5B, 0x53, 0x95, 0xEB, 0x4A, 0x17, 0x77, 0x9F, 0x02, 0x03, 0x01,\n0x00, 01 \n};\n#endif\n\nKeyChain::KeyChain(const shared_ptr<IdentityManager>& identityManager, const shared_ptr<PolicyManager>& policyManager)\n: identityManager_(identityManager), policyManager_(policyManager), face_(0), maxSteps_(100)\n{ \n}\n\nstatic bool \nverifySignature(const Data& data \/*, const Publickey& publickey *\/)\n{\n#if 0\n using namespace CryptoPP;\n\n Blob unsignedData(data.getSignedBlob()->signed_buf(), data.getSignedBlob()->signed_size());\n bool result = false;\n \n \/\/ Temporarily hardwire. It should be assigned by Signature.getAlgorithm().\n DigestAlgorithm digestAlg = DIGEST_SHA256;\n \/\/ Temporarily hardwire. It should be assigned by Publickey.getKeyType().\n KeyType keyType = KEY_TYPE_RSA; \n if (keyType == KEY_TYPE_RSA) {\n RSA::PublicKey pubKey;\n ByteQueue queue;\n\n queue.Put((const byte*)publickey.getKeyBlob ().buf (), publickey.getKeyBlob ().size ());\n pubKey.Load(queue);\n\n if (DIGEST_SHA256 == digestAlg) {\n Ptr<const signature::Sha256WithRsa> sigPtr = boost::dynamic_pointer_cast<const signature::Sha256WithRsa> (data.getSignature());\n const Blob & sigBits = sigPtr->getSignatureBits();\n\n RSASS<PKCS1v15, SHA256>::Verifier verifier (pubKey);\n result = verifier.VerifyMessage((const byte*) unsignedData.buf(), unsignedData.size(), (const byte*)sigBits.buf(), sigBits.size()); \n _LOG_DEBUG(\"Signature verified? \" << data.getName() << \" \" << boolalpha << result); \n }\n }\n \n return result;\n#else\n const Sha256WithRsaSignature *signature = dynamic_cast<const Sha256WithRsaSignature*>(data.getSignature());\n if (!signature)\n throw SecurityException(\"signature is not Sha256WithRsaSignature.\");\n \n if (signature->getDigestAlgorithm().size() != 0)\n \/\/ TODO: Allow a non-default digest algorithm.\n throw UnrecognizedDigestAlgorithmException(\"Cannot verify a data packet with a non-default digest algorithm.\");\n if (!data.getDefaultWireEncoding())\n data.wireEncode();\n uint8_t signedPortionDigest[SHA256_DIGEST_LENGTH];\n ndn_digestSha256(data.getDefaultWireEncoding().signedBuf(), data.getDefaultWireEncoding().signedSize(), signedPortionDigest);\n \n \/\/ Verify the signedPortionDigest.\n \/\/ Use a temporary pointer since d2i updates it.\n const uint8_t *derPointer = DEFAULT_PUBLIC_KEY_DER;\n RSA *publicKey = d2i_RSA_PUBKEY(NULL, &derPointer, sizeof(DEFAULT_PUBLIC_KEY_DER));\n if (!publicKey)\n throw UnrecognizedKeyFormatException(\"Error decoding public key in d2i_RSAPublicKey\");\n int success = RSA_verify\n (NID_sha256, signedPortionDigest, sizeof(signedPortionDigest), (uint8_t *)signature->getSignature().buf(), \n signature->getSignature().size(), publicKey);\n \/\/ Free the public key before checking for success.\n RSA_free(publicKey);\n \n return (success == 1);\n#endif\n}\n\nvoid \nKeyChain::sign(Data& data, const Name& certificateName, WireFormat& wireFormat)\n{\n identityManager_->signByCertificate(data, certificateName, wireFormat);\n}\n\nshared_ptr<Signature> \nKeyChain::sign(const uint8_t* buffer, size_t bufferLength, const Name& certificateName)\n{\n return identityManager_->signByCertificate(buffer, bufferLength, certificateName);\n}\n\nvoid \nKeyChain::signByIdentity(Data& data, const Name& identityName, WireFormat& wireFormat)\n{\n Name signingCertificateName;\n \n if (identityName.getComponentCount() == 0) {\n Name inferredIdentity = policyManager_->inferSigningIdentity(data.getName());\n if (inferredIdentity.getComponentCount() == 0)\n signingCertificateName = identityManager_->getDefaultCertificateName();\n else\n signingCertificateName = identityManager_->getDefaultCertificateNameForIdentity(inferredIdentity); \n }\n else\n signingCertificateName = identityManager_->getDefaultCertificateNameForIdentity(identityName);\n\n if (signingCertificateName.getComponentCount() == 0)\n throw SecurityException(\"No qualified certificate name found!\");\n\n if (!policyManager_->checkSigningPolicy(data.getName(), signingCertificateName))\n throw SecurityException(\"Signing Cert name does not comply with signing policy\");\n\n identityManager_->signByCertificate(data, signingCertificateName); \n}\n\n shared_ptr<Signature> \n KeyChain::signByIdentity(const uint8_t* buffer, size_t bufferLength, const Name& identityName)\n {\n Name signingCertificateName = identityManager_->getDefaultCertificateNameForIdentity(identityName);\n \n if (signingCertificateName.size() == 0)\n throw SecurityException(\"No qualified certificate name found!\");\n\n return identityManager_->signByCertificate(buffer, bufferLength, signingCertificateName);\n }\n\nvoid\nKeyChain::verifyData\n (const shared_ptr<Data>& data, const OnVerified& onVerified, const OnVerifyFailed& onVerifyFailed, int stepCount)\n{\n _LOG_TRACE(\"Enter Verify\");\n\n#if 0\n if (m_policyManager->requireVerify(*dataPtr))\n stepVerify(dataPtr, true, maxStep_, onVerified, onVerifyFailed);\n else if(m_policyManager->skipVerify(*dataPtr))\n#else\n if (verifySignature(*data))\n#endif\n onVerified(data);\n else\n onVerifyFailed(data);\n}\n\n}\n<commit_msg>code style: Fix indentation for KeyChain::signByIdentity.<commit_after>\/* -*- Mode:C++; c-file-style:\"gnu\"; indent-tabs-mode:nil -*- *\/\n\/**\n * Copyright (C) 2013 Regents of the University of California.\n * @author: Jeff Thompson <jefft0@remap.ucla.edu>\n * See COPYING for copyright and distribution information.\n *\/\n\n#include \"..\/c\/util\/crypto.h\"\n#include \"..\/c\/encoding\/binary-xml-data.h\"\n#include \"..\/encoding\/binary-xml-encoder.hpp\"\n#include <ndn-cpp\/sha256-with-rsa-signature.hpp>\n#include \"..\/util\/logging.hpp\"\n#include <ndn-cpp\/security\/security-exception.hpp>\n#include <ndn-cpp\/security\/policy\/policy-manager.hpp>\n#include <ndn-cpp\/security\/key-chain.hpp>\n\nusing namespace std;\nusing namespace ndn::ptr_lib;\n\nnamespace ndn {\n\n#if 1\nstatic uint8_t DEFAULT_PUBLIC_KEY_DER[] = {\n0x30, 0x81, 0x9F, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81,\n0x8D, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xE1, 0x7D, 0x30, 0xA7, 0xD8, 0x28, 0xAB, 0x1B, 0x84, 0x0B, 0x17,\n0x54, 0x2D, 0xCA, 0xF6, 0x20, 0x7A, 0xFD, 0x22, 0x1E, 0x08, 0x6B, 0x2A, 0x60, 0xD1, 0x6C, 0xB7, 0xF5, 0x44, 0x48, 0xBA,\n0x9F, 0x3F, 0x08, 0xBC, 0xD0, 0x99, 0xDB, 0x21, 0xDD, 0x16, 0x2A, 0x77, 0x9E, 0x61, 0xAA, 0x89, 0xEE, 0xE5, 0x54, 0xD3,\n0xA4, 0x7D, 0xE2, 0x30, 0xBC, 0x7A, 0xC5, 0x90, 0xD5, 0x24, 0x06, 0x7C, 0x38, 0x98, 0xBB, 0xA6, 0xF5, 0xDC, 0x43, 0x60,\n0xB8, 0x45, 0xED, 0xA4, 0x8C, 0xBD, 0x9C, 0xF1, 0x26, 0xA7, 0x23, 0x44, 0x5F, 0x0E, 0x19, 0x52, 0xD7, 0x32, 0x5A, 0x75,\n0xFA, 0xF5, 0x56, 0x14, 0x4F, 0x9A, 0x98, 0xAF, 0x71, 0x86, 0xB0, 0x27, 0x86, 0x85, 0xB8, 0xE2, 0xC0, 0x8B, 0xEA, 0x87,\n0x17, 0x1B, 0x4D, 0xEE, 0x58, 0x5C, 0x18, 0x28, 0x29, 0x5B, 0x53, 0x95, 0xEB, 0x4A, 0x17, 0x77, 0x9F, 0x02, 0x03, 0x01,\n0x00, 01 \n};\n#endif\n\nKeyChain::KeyChain(const shared_ptr<IdentityManager>& identityManager, const shared_ptr<PolicyManager>& policyManager)\n: identityManager_(identityManager), policyManager_(policyManager), face_(0), maxSteps_(100)\n{ \n}\n\nstatic bool \nverifySignature(const Data& data \/*, const Publickey& publickey *\/)\n{\n#if 0\n using namespace CryptoPP;\n\n Blob unsignedData(data.getSignedBlob()->signed_buf(), data.getSignedBlob()->signed_size());\n bool result = false;\n \n \/\/ Temporarily hardwire. It should be assigned by Signature.getAlgorithm().\n DigestAlgorithm digestAlg = DIGEST_SHA256;\n \/\/ Temporarily hardwire. It should be assigned by Publickey.getKeyType().\n KeyType keyType = KEY_TYPE_RSA; \n if (keyType == KEY_TYPE_RSA) {\n RSA::PublicKey pubKey;\n ByteQueue queue;\n\n queue.Put((const byte*)publickey.getKeyBlob ().buf (), publickey.getKeyBlob ().size ());\n pubKey.Load(queue);\n\n if (DIGEST_SHA256 == digestAlg) {\n Ptr<const signature::Sha256WithRsa> sigPtr = boost::dynamic_pointer_cast<const signature::Sha256WithRsa> (data.getSignature());\n const Blob & sigBits = sigPtr->getSignatureBits();\n\n RSASS<PKCS1v15, SHA256>::Verifier verifier (pubKey);\n result = verifier.VerifyMessage((const byte*) unsignedData.buf(), unsignedData.size(), (const byte*)sigBits.buf(), sigBits.size()); \n _LOG_DEBUG(\"Signature verified? \" << data.getName() << \" \" << boolalpha << result); \n }\n }\n \n return result;\n#else\n const Sha256WithRsaSignature *signature = dynamic_cast<const Sha256WithRsaSignature*>(data.getSignature());\n if (!signature)\n throw SecurityException(\"signature is not Sha256WithRsaSignature.\");\n \n if (signature->getDigestAlgorithm().size() != 0)\n \/\/ TODO: Allow a non-default digest algorithm.\n throw UnrecognizedDigestAlgorithmException(\"Cannot verify a data packet with a non-default digest algorithm.\");\n if (!data.getDefaultWireEncoding())\n data.wireEncode();\n uint8_t signedPortionDigest[SHA256_DIGEST_LENGTH];\n ndn_digestSha256(data.getDefaultWireEncoding().signedBuf(), data.getDefaultWireEncoding().signedSize(), signedPortionDigest);\n \n \/\/ Verify the signedPortionDigest.\n \/\/ Use a temporary pointer since d2i updates it.\n const uint8_t *derPointer = DEFAULT_PUBLIC_KEY_DER;\n RSA *publicKey = d2i_RSA_PUBKEY(NULL, &derPointer, sizeof(DEFAULT_PUBLIC_KEY_DER));\n if (!publicKey)\n throw UnrecognizedKeyFormatException(\"Error decoding public key in d2i_RSAPublicKey\");\n int success = RSA_verify\n (NID_sha256, signedPortionDigest, sizeof(signedPortionDigest), (uint8_t *)signature->getSignature().buf(), \n signature->getSignature().size(), publicKey);\n \/\/ Free the public key before checking for success.\n RSA_free(publicKey);\n \n return (success == 1);\n#endif\n}\n\nvoid \nKeyChain::sign(Data& data, const Name& certificateName, WireFormat& wireFormat)\n{\n identityManager_->signByCertificate(data, certificateName, wireFormat);\n}\n\nshared_ptr<Signature> \nKeyChain::sign(const uint8_t* buffer, size_t bufferLength, const Name& certificateName)\n{\n return identityManager_->signByCertificate(buffer, bufferLength, certificateName);\n}\n\nvoid \nKeyChain::signByIdentity(Data& data, const Name& identityName, WireFormat& wireFormat)\n{\n Name signingCertificateName;\n \n if (identityName.getComponentCount() == 0) {\n Name inferredIdentity = policyManager_->inferSigningIdentity(data.getName());\n if (inferredIdentity.getComponentCount() == 0)\n signingCertificateName = identityManager_->getDefaultCertificateName();\n else\n signingCertificateName = identityManager_->getDefaultCertificateNameForIdentity(inferredIdentity); \n }\n else\n signingCertificateName = identityManager_->getDefaultCertificateNameForIdentity(identityName);\n\n if (signingCertificateName.getComponentCount() == 0)\n throw SecurityException(\"No qualified certificate name found!\");\n\n if (!policyManager_->checkSigningPolicy(data.getName(), signingCertificateName))\n throw SecurityException(\"Signing Cert name does not comply with signing policy\");\n\n identityManager_->signByCertificate(data, signingCertificateName); \n}\n\nshared_ptr<Signature> \nKeyChain::signByIdentity(const uint8_t* buffer, size_t bufferLength, const Name& identityName)\n{\n Name signingCertificateName = identityManager_->getDefaultCertificateNameForIdentity(identityName);\n \n if (signingCertificateName.size() == 0)\n throw SecurityException(\"No qualified certificate name found!\");\n\n return identityManager_->signByCertificate(buffer, bufferLength, signingCertificateName);\n}\n\nvoid\nKeyChain::verifyData\n (const shared_ptr<Data>& data, const OnVerified& onVerified, const OnVerifyFailed& onVerifyFailed, int stepCount)\n{\n _LOG_TRACE(\"Enter Verify\");\n\n#if 0\n if (m_policyManager->requireVerify(*dataPtr))\n stepVerify(dataPtr, true, maxStep_, onVerified, onVerifyFailed);\n else if(m_policyManager->skipVerify(*dataPtr))\n#else\n if (verifySignature(*data))\n#endif\n onVerified(data);\n else\n onVerifyFailed(data);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\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#include \"QUECTEL_BC95_CellularNetwork.h\"\n\nusing namespace mbed;\n\nQUECTEL_BC95_CellularNetwork::QUECTEL_BC95_CellularNetwork(ATHandler &atHandler) : AT_CellularNetwork(atHandler)\n{\n _op_act = RAT_NB1;\n}\n\nQUECTEL_BC95_CellularNetwork::~QUECTEL_BC95_CellularNetwork()\n{\n}\n\nAT_CellularNetwork::RegistrationMode QUECTEL_BC95_CellularNetwork::has_registration(RegistrationType reg_tech)\n{\n return (reg_tech == C_EREG) ? RegistrationModeLAC : RegistrationModeDisable;\n}\n\nnsapi_error_t QUECTEL_BC95_CellularNetwork::set_access_technology_impl(RadioAccessTechnology opRat)\n{\n if (opRat != RAT_NB1) {\n \/\/TODO: Set as unknown or force to NB1?\n _op_act = RAT_UNKNOWN;\n return NSAPI_ERROR_UNSUPPORTED;\n }\n\n return NSAPI_ERROR_OK;\n}\n<commit_msg>Cellular: Fixed bc95 to accept only RAT_NB1 as it's only valid rat that modem supports.<commit_after>\/*\n * Copyright (c) 2017, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\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#include \"QUECTEL_BC95_CellularNetwork.h\"\n\nusing namespace mbed;\n\nQUECTEL_BC95_CellularNetwork::QUECTEL_BC95_CellularNetwork(ATHandler &atHandler) : AT_CellularNetwork(atHandler)\n{\n _op_act = RAT_NB1;\n}\n\nQUECTEL_BC95_CellularNetwork::~QUECTEL_BC95_CellularNetwork()\n{\n}\n\nAT_CellularNetwork::RegistrationMode QUECTEL_BC95_CellularNetwork::has_registration(RegistrationType reg_tech)\n{\n return (reg_tech == C_EREG) ? RegistrationModeLAC : RegistrationModeDisable;\n}\n\nnsapi_error_t QUECTEL_BC95_CellularNetwork::set_access_technology_impl(RadioAccessTechnology opRat)\n{\n if (opRat != RAT_NB1) {\n \/\/ only rat that is supported by this modem\n _op_act = RAT_NB1;\n return NSAPI_ERROR_UNSUPPORTED;\n }\n\n return NSAPI_ERROR_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) Timur Iskhakov.\n\/\/ Distributed under the terms of the MIT License.\n\n\n#include \"core.hpp\"\n\n#include <algorithm>\n#include <stdexcept>\n\n\ntemplate <class Real>\nstd::vector<Real> linear_system(const Matrix<Real> &M, const std::vector<Real> &b) {\n return lu_decomposition(M, b);\n}\n\n\nclass LinearSystemException : public std::exception {\n\tvirtual const char* what() const noexcept = 0;\n};\n\nclass LinearSystemInfiniteSolutions : public LinearSystemException {\n\tconst char* what() const noexcept override { return \"infinite solutions\"; }\n};\n\nclass LinearSystemNoSolutions : public LinearSystemException {\n\tconst char* what() const noexcept override { return \"no solutions\"; }\n};\n\n\ntemplate <class ForwardIt>\nForwardIt max_absolute_element(ForwardIt, ForwardIt);\n\n\ntemplate <class Real>\nstd::vector<Real> solve_upper_triangular(const Matrix<Real> &M, const std::vector<Real> &b) {\n if (M.size() != b.size()) {\n throw std::invalid_argument(\"solve_upper_triangular: matrix size is not equal to vector\");\n }\n\n size_t n = M.row_size();\n std::vector<Real> ret(n);\n\n for (ssize_t pos = n - 1; pos >= 0; --pos) {\n ret[pos] = b[pos];\n for (size_t i = pos + 1; i != n; ++i) {\n ret[pos] -= M[pos][i] * ret[i];\n }\n ret[pos] \/= M[pos][pos];\n }\n\n return ret;\n}\n\n\ntemplate <class Real>\nstd::vector<Real> solve_lower_triangular(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"solve_lower_triangular: matrix size is not equal to vector\");\n }\n\n auto M = _M;\n auto b = _b;\n\n std::reverse(M.matrix.begin(), M.matrix.end());\n for (auto &row : M.matrix) {\n std::reverse(row.begin(), row.end());\n }\n\n std::reverse(b.begin(), b.end());\n auto ret = solve_upper_triangular(M, b);\n std::reverse(ret.begin(), ret.end());\n\n return ret;\n}\n\n\ntemplate <class Real>\nbool is_linear_dependent(const std::vector<Real> &a, const std::vector<Real> &b) {\n if (a.size() != b.size()) {\n throw std::invalid_argument(\"is_linear_dependent vectors have different sizes\");\n }\n\n for (size_t i = 1; i != a.size(); ++i) {\n if (!equal(a[i] * b[0], a[0] * b[i])) {\n return false;\n }\n }\n return true;\n}\n\n\ntemplate <class Real>\nvoid build_linear_basis(Matrix<Real> &M, std::vector<Real> &b) {\n if (M.size() != b.size()) {\n throw std::invalid_argument(\"build_linear_basis: matrix row size is not equal to vector\");\n }\n\n size_t end = M.size();\n for (size_t i = 0; i != end; ++i) {\n for (size_t j = 0; j != i; ++j) {\n if (is_linear_dependent(M.get_row(i), M.get_row(j))) {\n if (!equal(b[i] * M[j][0], b[j] * M[i][0])) {\n throw LinearSystemNoSolutions();\n }\n\n std::swap(M[i], M[end - 1]);\n std::swap(b[i], b[end - 1]);\n --end;\n --i;\n break;\n }\n }\n }\n}\n\n\ntemplate <class Real>\nstd::vector<Real> gaussian_elimination(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n\tif (_M.size() != _b.size()) {\n\t\tthrow std::invalid_argument(\"gaussian_elimination: matrix size is not equal to vector\");\n\t}\n\n auto M = _M;\n auto b = _b;\n\n build_linear_basis(M, b);\n\n size_t n = M.row_size();\n\n if (M.size() < n) {\n throw LinearSystemInfiniteSolutions();\n }\n\n for (size_t pos = 0; pos != n; ++pos) {\n\t\tauto column = M.get_column(pos);\n auto next = max_absolute_element(column.begin() + pos, column.end());\n if (equal(*next)) {\n throw LinearSystemInfiniteSolutions();\n }\n\n\n std::swap(M[next - column.begin()], M[pos]);\n std::swap(b[next - column.begin()], b[pos]);\n\n for (size_t i = pos + 1; i != n; ++i) {\n if (equal(M[i][pos])) {\n continue;\n }\n\n Real coef = M[i][pos] \/ M[pos][pos];\n\n M[i][pos] = 0.0;\n for (size_t j = pos + 1; j != n; ++j) {\n M[i][j] -= coef * M[pos][j];\n }\n b[i] -= coef * b[pos];\n }\n }\n\n return solve_upper_triangular(M, b);\n}\n\n\ntemplate <class Real>\nstd::vector<Real> lu_decomposition(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"lu_decomposition: matrix size is not equal to vector\");\n }\n\n auto M = _M;\n auto b = _b;\n\n build_linear_basis(M, b);\n\n size_t n = M.row_size();\n\n if (M.size() < n) {\n throw LinearSystemInfiniteSolutions();\n }\n\n Matrix<Real> L(n, n), U(n, n);\n\n for (size_t pos = 0; pos != n; ++pos) {\n L[pos][pos] = 1.0;\n\n auto column = M.get_column(pos);\n auto next = max_absolute_element(column.begin() + pos, column.end());\n std::swap(M[next - column.begin()], M[pos]);\n std::swap(b[next - column.begin()], b[pos]);\n\n for (size_t i = 0; i != pos + 1; ++i) {\n U[i][pos] = M[i][pos];\n for (size_t j = 0; j != i; ++j) {\n U[i][pos] -= U[j][pos] * L[i][j];\n }\n\n }\n if (equal(U[pos][pos])) {\n throw LinearSystemInfiniteSolutions();\n }\n\n for (size_t i = pos; i != n; ++i) {\n L[i][pos] = M[i][pos];\n for (size_t j = 0; j != pos; ++j) {\n L[i][pos] -= U[j][pos] * L[i][j];\n }\n L[i][pos] \/= U[pos][pos];\n }\n if (equal(L[pos][pos])) {\n throw LinearSystemInfiniteSolutions();\n }\n }\n\n auto sub_b = std::vector<Real>(b.begin(), b.begin() + n);\n return solve_upper_triangular(U, solve_lower_triangular(L, sub_b));\n}\n\n\ntemplate <class Real>\nstd::vector<Real> tridiagonal_thomas(\n const std::vector<Real> &A,\n const std::vector<Real> &C,\n const std::vector<Real> &B,\n const std::vector<Real> &F)\n{\n if (A.size() != C.size() || A.size() != B.size() || A.size() != F.size()) {\n throw std::invalid_argument(\"tridiagonal_thomas: invalid tridiagonal argument sizes\");\n }\n\n size_t n = A.size();\n\n std::vector<Real> alpha(n), beta(n);\n alpha[0] = 0.0;\n beta[0] = 0.0;\n\n Real z;\n for (size_t i = 1; i != n; ++i) {\n z = (A[i - 1] * alpha[i - 1] + C[i - 1]);\n alpha[i] = -B[i - 1] \/ z;\n beta[i] = (F[i - 1] - A[i - 1] * beta[i - 1]) \/ z;\n }\n\n std::vector<Real> ret(n);\n ret[n - 1] = (F[n - 1] - A[n - 1] * beta[n - 1]) \/ (C[n - 1] + A[n - 1] * alpha[n - 1]);\n\n for (ssize_t i = n - 2; i >= 0; --i) {\n ret[i] = alpha[i + 1] * ret[i + 1] + beta[i + 1];\n }\n\n return ret;\n}\n\n\ntemplate <class ForwardIt>\nForwardIt max_absolute_element(ForwardIt begin, ForwardIt end) {\n ForwardIt ret = begin;\n\n for (auto it = begin; it != end; ++it) {\n if (abs(*it) > abs(*ret)) {\n ret = it;\n }\n }\n\n return ret;\n}\n\n\ntemplate std::vector<double> linear_system(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> gaussian_elimination(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> lu_decomposition(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> tridiagonal_thomas(const std::vector<double> &, const std::vector<double> &,\n const std::vector<double> &, const std::vector<double> &);\n<commit_msg>linear system bug fixed<commit_after>\/\/ Copyright (c) Timur Iskhakov.\n\/\/ Distributed under the terms of the MIT License.\n\n\n#include \"core.hpp\"\n\n#include <algorithm>\n#include <stdexcept>\n\n\ntemplate <class Real>\nstd::vector<Real> linear_system(const Matrix<Real> &M, const std::vector<Real> &b) {\n return lu_decomposition(M, b);\n}\n\n\nclass LinearSystemException : public std::exception {\n\tvirtual const char* what() const noexcept = 0;\n};\n\nclass LinearSystemInfiniteSolutions : public LinearSystemException {\n\tconst char* what() const noexcept override { return \"infinite solutions\"; }\n};\n\nclass LinearSystemNoSolution : public LinearSystemException {\n\tconst char* what() const noexcept override { return \"no solution\"; }\n};\n\n\ntemplate <class ForwardIt>\nForwardIt max_absolute_element(ForwardIt, ForwardIt);\n\n\ntemplate <class Real>\nstd::vector<Real> solve_upper_triangular(const Matrix<Real> &M, const std::vector<Real> &b) {\n if (M.size() != b.size()) {\n throw std::invalid_argument(\"solve_upper_triangular: matrix size is not equal to vector\");\n }\n\n size_t n = M.row_size();\n std::vector<Real> ret(n);\n\n for (ssize_t pos = n - 1; pos >= 0; --pos) {\n ret[pos] = b[pos];\n for (size_t i = pos + 1; i != n; ++i) {\n ret[pos] -= M[pos][i] * ret[i];\n }\n ret[pos] \/= M[pos][pos];\n }\n\n return ret;\n}\n\n\ntemplate <class Real>\nstd::vector<Real> solve_lower_triangular(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"solve_lower_triangular: matrix size is not equal to vector\");\n }\n\n auto M = _M;\n auto b = _b;\n\n std::reverse(M.matrix.begin(), M.matrix.end());\n for (auto &row : M.matrix) {\n std::reverse(row.begin(), row.end());\n }\n\n std::reverse(b.begin(), b.end());\n auto ret = solve_upper_triangular(M, b);\n std::reverse(ret.begin(), ret.end());\n\n return ret;\n}\n\n\ntemplate <class Real>\nstd::vector<Real> gaussian_elimination(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n\tif (_M.size() != _b.size()) {\n\t\tthrow std::invalid_argument(\"gaussian_elimination: matrix size is not equal to vector\");\n\t}\n\n auto M = _M;\n auto b = _b;\n\n size_t n = M.row_size(), m = M.size();\n\n if (M.size() < n) {\n throw LinearSystemInfiniteSolutions();\n }\n\n for (size_t pos = 0; pos != n; ++pos) {\n\t\tauto column = M.get_column(pos);\n auto next = max_absolute_element(column.begin() + pos, column.end());\n if (equal(*next)) {\n throw LinearSystemInfiniteSolutions();\n }\n\n std::swap(M[next - column.begin()], M[pos]);\n std::swap(b[next - column.begin()], b[pos]);\n\n for (size_t i = pos + 1; i != m; ++i) {\n if (equal(M[i][pos])) {\n continue;\n }\n\n Real coef = M[i][pos] \/ M[pos][pos];\n\n M[i][pos] = 0.0;\n for (size_t j = pos + 1; j != n; ++j) {\n M[i][j] -= coef * M[pos][j];\n }\n b[i] -= coef * b[pos];\n }\n }\n\n for (size_t i = n; i != m; ++i) {\n if (!equal(b[i])) {\n throw LinearSystemNoSolution();\n }\n }\n\n return solve_upper_triangular(M, b);\n}\n\n\ntemplate <class Real>\nstd::vector<Real> lu_decomposition(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"lu_decomposition: matrix size is not equal to vector\");\n }\n\n if (_M.size() != _M.row_size()) {\n throw std::invalid_argument(\"lu_decomposition: only square matices are supported\");\n }\n\n auto M = _M;\n auto b = _b;\n\n size_t n = M.row_size();\n\n Matrix<Real> L(n, n), U(n, n);\n\n for (size_t pos = 0; pos != n; ++pos) {\n auto column = M.get_column(pos);\n auto next = max_absolute_element(column.begin() + pos, column.end());\n std::swap(M[next - column.begin()], M[pos]);\n std::swap(b[next - column.begin()], b[pos]);\n }\n\n for (size_t pos = 0; pos != n; ++pos) {\n L[pos][pos] = 1.0;\n\n for (size_t i = 0; i != pos + 1; ++i) {\n U[i][pos] = M[i][pos];\n for (size_t j = 0; j != i; ++j) {\n U[i][pos] -= U[j][pos] * L[i][j];\n }\n }\n if (equal(U[pos][pos])) {\n throw LinearSystemInfiniteSolutions();\n }\n\n for (size_t i = pos; i != n; ++i) {\n L[i][pos] = M[i][pos];\n for (size_t j = 0; j != pos; ++j) {\n L[i][pos] -= U[j][pos] * L[i][j];\n }\n L[i][pos] \/= U[pos][pos];\n }\n }\n\n auto sub_b = std::vector<Real>(b.begin(), b.begin() + n);\n return solve_upper_triangular(U, solve_lower_triangular(L, sub_b));\n}\n\n\ntemplate <class Real>\nstd::vector<Real> tridiagonal_thomas(\n const std::vector<Real> &A,\n const std::vector<Real> &C,\n const std::vector<Real> &B,\n const std::vector<Real> &F)\n{\n if (A.size() != C.size() || A.size() != B.size() || A.size() != F.size()) {\n throw std::invalid_argument(\"tridiagonal_thomas: invalid tridiagonal argument sizes\");\n }\n\n size_t n = A.size();\n\n std::vector<Real> alpha(n), beta(n);\n alpha[0] = 0.0;\n beta[0] = 0.0;\n\n Real z;\n for (size_t i = 1; i != n; ++i) {\n z = (A[i - 1] * alpha[i - 1] + C[i - 1]);\n alpha[i] = -B[i - 1] \/ z;\n beta[i] = (F[i - 1] - A[i - 1] * beta[i - 1]) \/ z;\n }\n\n std::vector<Real> ret(n);\n ret[n - 1] = (F[n - 1] - A[n - 1] * beta[n - 1]) \/ (C[n - 1] + A[n - 1] * alpha[n - 1]);\n\n for (ssize_t i = n - 2; i >= 0; --i) {\n ret[i] = alpha[i + 1] * ret[i + 1] + beta[i + 1];\n }\n\n return ret;\n}\n\n\ntemplate <class ForwardIt>\nForwardIt max_absolute_element(ForwardIt begin, ForwardIt end) {\n ForwardIt ret = begin;\n\n for (auto it = begin; it != end; ++it) {\n if (abs(*it) > abs(*ret)) {\n ret = it;\n }\n }\n\n return ret;\n}\n\n\ntemplate std::vector<double> linear_system(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> gaussian_elimination(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> lu_decomposition(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> tridiagonal_thomas(const std::vector<double> &, const std::vector<double> &,\n const std::vector<double> &, const std::vector<double> &);\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) Timur Iskhakov.\n\/\/ Distributed under the terms of the MIT License.\n\n\n#include \"core.hpp\"\n\n#include <algorithm>\n#include <stdexcept>\n\n\ntemplate <class Real>\nstd::vector<Real> linear_system(const Matrix<Real> &M, const std::vector<Real> &b) {\n return lu_decomposition(M, b);\n}\n\n\nclass LinearSystemException : public std::exception {\n\tvirtual const char* what() const noexcept = 0;\n};\n\nclass LinearSystemInfiniteSolutions : public LinearSystemException {\n\tconst char* what() const noexcept override { return \"infinite solutions\"; }\n};\n\nclass LinearSystemNoSolution : public LinearSystemException {\n\tconst char* what() const noexcept override { return \"no solution\"; }\n};\n\n\ntemplate <class ForwardIt>\nForwardIt max_absolute_element(ForwardIt, ForwardIt);\n\n\ntemplate <class Real>\nstd::vector<Real> solve_upper_triangular(const Matrix<Real> &M, const std::vector<Real> &b) {\n if (M.size() != b.size()) {\n throw std::invalid_argument(\"solve_upper_triangular: matrix size is not equal to vector\");\n }\n\n size_t n = M.row_size();\n std::vector<Real> ret(n);\n\n for (ssize_t pos = n - 1; pos >= 0; --pos) {\n ret[pos] = b[pos];\n for (size_t i = pos + 1; i != n; ++i) {\n ret[pos] -= M[pos][i] * ret[i];\n }\n ret[pos] \/= M[pos][pos];\n }\n\n return ret;\n}\n\n\ntemplate <class Real>\nstd::vector<Real> solve_lower_triangular(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"solve_lower_triangular: matrix size is not equal to vector\");\n }\n\n auto M = _M;\n auto b = _b;\n\n std::reverse(M.matrix.begin(), M.matrix.end());\n for (auto &row : M.matrix) {\n std::reverse(row.begin(), row.end());\n }\n\n std::reverse(b.begin(), b.end());\n auto ret = solve_upper_triangular(M, b);\n std::reverse(ret.begin(), ret.end());\n\n return ret;\n}\n\n\ntemplate <class Real>\nstd::vector<Real> gaussian_elimination(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n\tif (_M.size() != _b.size()) {\n\t\tthrow std::invalid_argument(\"gaussian_elimination: matrix size is not equal to vector\");\n\t}\n\n auto M = _M;\n auto b = _b;\n\n size_t n = M.row_size(), m = M.size();\n\n if (M.size() < n) {\n throw LinearSystemInfiniteSolutions();\n }\n\n for (size_t pos = 0; pos != n; ++pos) {\n\t\tauto column = M.get_column(pos);\n auto next = max_absolute_element(column.begin() + pos, column.end());\n if (equal(*next)) {\n throw LinearSystemInfiniteSolutions();\n }\n\n std::swap(M[next - column.begin()], M[pos]);\n std::swap(b[next - column.begin()], b[pos]);\n\n for (size_t i = pos + 1; i != m; ++i) {\n if (equal(M[i][pos])) {\n continue;\n }\n\n Real coef = M[i][pos] \/ M[pos][pos];\n\n M[i][pos] = 0.0;\n for (size_t j = pos + 1; j != n; ++j) {\n M[i][j] -= coef * M[pos][j];\n }\n b[i] -= coef * b[pos];\n }\n }\n\n for (size_t i = n; i != m; ++i) {\n if (!equal(b[i])) {\n throw LinearSystemNoSolution();\n }\n }\n\n return solve_upper_triangular(M, b);\n}\n\n\ntemplate <class Real>\nstd::vector<Real> lu_decomposition(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"lu_decomposition: matrix size is not equal to vector\");\n }\n\n if (_M.size() != _M.row_size()) {\n throw std::invalid_argument(\"lu_decomposition: only square matices are supported\");\n }\n\n auto M = _M;\n auto b = _b;\n\n size_t n = M.row_size();\n\n Matrix<Real> L(n, n), U(n, n);\n\n for (size_t pos = 0; pos != n; ++pos) {\n auto column = M.get_column(pos);\n auto next = max_absolute_element(column.begin() + pos, column.end());\n std::swap(M[next - column.begin()], M[pos]);\n std::swap(b[next - column.begin()], b[pos]);\n }\n\n for (size_t pos = 0; pos != n; ++pos) {\n L[pos][pos] = 1.0;\n\n for (size_t i = 0; i != pos + 1; ++i) {\n U[i][pos] = M[i][pos];\n for (size_t j = 0; j != i; ++j) {\n U[i][pos] -= U[j][pos] * L[i][j];\n }\n }\n if (equal(U[pos][pos])) {\n throw LinearSystemInfiniteSolutions();\n }\n\n for (size_t i = pos; i != n; ++i) {\n L[i][pos] = M[i][pos];\n for (size_t j = 0; j != pos; ++j) {\n L[i][pos] -= U[j][pos] * L[i][j];\n }\n L[i][pos] \/= U[pos][pos];\n }\n }\n\n auto sub_b = std::vector<Real>(b.begin(), b.begin() + n);\n return solve_upper_triangular(U, solve_lower_triangular(L, sub_b));\n}\n\n\ntemplate <class Real>\nstd::vector<Real> tridiagonal_thomas(\n const std::vector<Real> &A,\n const std::vector<Real> &C,\n const std::vector<Real> &B,\n const std::vector<Real> &F)\n{\n if (A.size() != C.size() || A.size() != B.size() || A.size() != F.size()) {\n throw std::invalid_argument(\"tridiagonal_thomas: invalid tridiagonal argument sizes\");\n }\n\n size_t n = A.size();\n\n std::vector<Real> alpha(n), beta(n);\n alpha[0] = 0.0;\n beta[0] = 0.0;\n\n Real z;\n for (size_t i = 1; i != n; ++i) {\n z = (A[i - 1] * alpha[i - 1] + C[i - 1]);\n alpha[i] = -B[i - 1] \/ z;\n beta[i] = (F[i - 1] - A[i - 1] * beta[i - 1]) \/ z;\n }\n\n std::vector<Real> ret(n);\n ret[n - 1] = (F[n - 1] - A[n - 1] * beta[n - 1]) \/ (C[n - 1] + A[n - 1] * alpha[n - 1]);\n\n for (ssize_t i = n - 2; i >= 0; --i) {\n ret[i] = alpha[i + 1] * ret[i + 1] + beta[i + 1];\n }\n\n return ret;\n}\n\n\ntemplate <class ForwardIt>\nForwardIt max_absolute_element(ForwardIt begin, ForwardIt end) {\n ForwardIt ret = begin;\n\n for (auto it = begin; it != end; ++it) {\n if (abs(*it) > abs(*ret)) {\n ret = it;\n }\n }\n\n return ret;\n}\n\n\ntemplate std::vector<double> linear_system(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> gaussian_elimination(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> lu_decomposition(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> tridiagonal_thomas(const std::vector<double> &, const std::vector<double> &,\n const std::vector<double> &, const std::vector<double> &);\n<commit_msg>linear systems bug fix<commit_after>\/\/ Copyright (c) Timur Iskhakov.\n\/\/ Distributed under the terms of the MIT License.\n\n\n#include \"core.hpp\"\n\n#include <algorithm>\n#include <stdexcept>\n\n\ntemplate <class Real>\nstd::vector<Real> linear_system(const Matrix<Real> &M, const std::vector<Real> &b) {\n return lu_decomposition(M, b);\n}\n\n\nclass LinearSystemException : public std::exception {\n\tvirtual const char* what() const noexcept = 0;\n};\n\nclass LinearSystemInfiniteSolutions : public LinearSystemException {\n\tconst char* what() const noexcept override { return \"infinite solutions\"; }\n};\n\nclass LinearSystemNoSolution : public LinearSystemException {\n\tconst char* what() const noexcept override { return \"no solution\"; }\n};\n\n\ntemplate <class ForwardIt>\nForwardIt max_absolute_element(ForwardIt, ForwardIt);\n\n\ntemplate <class Real>\nstd::vector<Real> solve_upper_triangular(const Matrix<Real> &M, const std::vector<Real> &b) {\n if (M.size() != b.size()) {\n throw std::invalid_argument(\"solve_upper_triangular: matrix size is not equal to vector\");\n }\n\n size_t n = M.row_size();\n std::vector<Real> ret(n);\n\n for (ssize_t pos = n - 1; pos >= 0; --pos) {\n ret[pos] = b[pos];\n for (size_t i = pos + 1; i != n; ++i) {\n ret[pos] -= M[pos][i] * ret[i];\n }\n ret[pos] \/= M[pos][pos];\n }\n\n return ret;\n}\n\n\ntemplate <class Real>\nstd::vector<Real> solve_lower_triangular(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"solve_lower_triangular: matrix size is not equal to vector\");\n }\n\n auto M = _M;\n auto b = _b;\n\n std::reverse(M.matrix.begin(), M.matrix.end());\n for (auto &row : M.matrix) {\n std::reverse(row.begin(), row.end());\n }\n\n std::reverse(b.begin(), b.end());\n auto ret = solve_upper_triangular(M, b);\n std::reverse(ret.begin(), ret.end());\n\n return ret;\n}\n\n\ntemplate <class Real>\nstd::vector<Real> gaussian_elimination(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n\tif (_M.size() != _b.size()) {\n\t\tthrow std::invalid_argument(\"gaussian_elimination: matrix size is not equal to vector\");\n\t}\n\n auto M = _M;\n auto b = _b;\n\n size_t n = M.row_size(), m = M.size();\n\n if (M.size() < n) {\n throw LinearSystemInfiniteSolutions();\n }\n\n for (size_t pos = 0; pos != n; ++pos) {\n\t\tauto column = M.get_column(pos);\n auto next = max_absolute_element(column.begin() + pos, column.end());\n\n if (equal(*next)) {\n throw LinearSystemInfiniteSolutions();\n }\n\n std::swap(M[next - column.begin()], M[pos]);\n std::swap(b[next - column.begin()], b[pos]);\n\n for (size_t i = pos + 1; i != m; ++i) {\n if (equal(M[i][pos])) {\n continue;\n }\n\n Real coef = M[i][pos] \/ M[pos][pos];\n\n M[i][pos] = 0.0;\n for (size_t j = pos + 1; j != n; ++j) {\n M[i][j] -= coef * M[pos][j];\n }\n b[i] -= coef * b[pos];\n }\n }\n\n for (size_t i = n; i != m; ++i) {\n if (!equal(b[i])) {\n throw LinearSystemNoSolution();\n }\n }\n\n return solve_upper_triangular(M, b);\n}\n\n\ntemplate <class Real>\nvoid pivot_doolittle(Matrix<Real> &_M, std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"pivot_doolittle: matrix size is not equal to vector\");\n }\n\n if (_M.size() != _M.row_size()) {\n throw std::invalid_argument(\"pivot_doolittle: only square matices are supported\");\n }\n\n size_t n = _M.size();\n\n std::vector<size_t> perm(n);\n for (size_t i = 0; i != n; ++i) {\n perm[i] = i;\n }\n\n for (size_t pos = 0; pos != n; ++pos) {\n auto column = _M.get_column(pos);\n auto next = max_absolute_element(column.begin() + pos, column.end());\n\n if (next - column.begin() != static_cast<ssize_t>(pos)) {\n std::swap(perm[next - column.begin()], perm[pos]);\n }\n }\n\n auto M = _M;\n auto b = _b;\n\n for (size_t i = 0; i != n; ++i) {\n M[i] = _M[perm[i]];\n b[i] = _b[perm[i]];\n }\n\n _M = M;\n _b = b;\n}\n\n\ntemplate <class Real>\nstd::vector<Real> lu_decomposition(const Matrix<Real> &_M, const std::vector<Real> &_b) {\n if (_M.size() != _b.size()) {\n throw std::invalid_argument(\"lu_decomposition: matrix size is not equal to vector\");\n }\n\n if (_M.size() != _M.row_size()) {\n throw std::invalid_argument(\"lu_decomposition: only square matices are supported\");\n }\n\n auto M = _M;\n auto b = _b;\n\n size_t n = M.row_size();\n\n Matrix<Real> L(n, n), U(n, n);\n pivot_doolittle(M, b);\n\n for (size_t pos = 0; pos != n; ++pos) {\n L[pos][pos] = 1.0;\n\n for (size_t i = 0; i != pos + 1; ++i) {\n U[i][pos] = M[i][pos];\n for (size_t j = 0; j != i; ++j) {\n U[i][pos] -= U[j][pos] * L[i][j];\n }\n }\n if (equal(U[pos][pos])) {\n throw LinearSystemInfiniteSolutions();\n }\n\n for (size_t i = pos; i != n; ++i) {\n L[i][pos] = M[i][pos];\n for (size_t j = 0; j != pos; ++j) {\n L[i][pos] -= U[j][pos] * L[i][j];\n }\n L[i][pos] \/= U[pos][pos];\n }\n }\n\n return solve_upper_triangular(U, solve_lower_triangular(L, b));\n}\n\n\ntemplate <class Real>\nstd::vector<Real> tridiagonal_thomas(\n const std::vector<Real> &A,\n const std::vector<Real> &C,\n const std::vector<Real> &B,\n const std::vector<Real> &F)\n{\n if (A.size() != C.size() || A.size() != B.size() || A.size() != F.size()) {\n throw std::invalid_argument(\"tridiagonal_thomas: invalid tridiagonal argument sizes\");\n }\n\n size_t n = A.size();\n\n std::vector<Real> alpha(n), beta(n);\n alpha[0] = 0.0;\n beta[0] = 0.0;\n\n Real z;\n for (size_t i = 1; i != n; ++i) {\n z = (A[i - 1] * alpha[i - 1] + C[i - 1]);\n alpha[i] = -B[i - 1] \/ z;\n beta[i] = (F[i - 1] - A[i - 1] * beta[i - 1]) \/ z;\n }\n\n std::vector<Real> ret(n);\n ret[n - 1] = (F[n - 1] - A[n - 1] * beta[n - 1]) \/ (C[n - 1] + A[n - 1] * alpha[n - 1]);\n\n for (ssize_t i = n - 2; i >= 0; --i) {\n ret[i] = alpha[i + 1] * ret[i + 1] + beta[i + 1];\n }\n\n return ret;\n}\n\n\ntemplate <class ForwardIt>\nForwardIt max_absolute_element(ForwardIt begin, ForwardIt end) {\n ForwardIt ret = begin;\n\n for (auto it = std::next(begin); it != end; ++it) {\n if (std::abs(*it) > std::abs(*ret)) {\n ret = it;\n }\n }\n\n return ret;\n}\n\n\ntemplate std::vector<double> linear_system(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> gaussian_elimination(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> lu_decomposition(const Matrix<double> &, const std::vector<double> &);\ntemplate std::vector<double> tridiagonal_thomas(const std::vector<double> &, const std::vector<double> &,\n const std::vector<double> &, const std::vector<double> &);\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Hashidsxx (c) 2014 Toon Schoenmakers\n *\n * https:\/\/github.com\/schoentoon\/hashidsxx\n * hashidsxx may be freely distributed under the MIT license.\n *\/\n\n#include <getopt.h>\n#include <string.h>\n\n#include \"hashids.h\"\n\n#include <iostream>\n#include <list>\n\nstatic const struct option g_LongOpts[] = {\n { \"help\", no_argument, 0, 'h' },\n { \"salt\", required_argument, 0, 's' },\n { \"alphabet\", required_argument, 0, 'a' },\n { \"min\", required_argument, 0, 'm' },\n { \"input\", required_argument, 0, 'i' },\n { 0, 0, 0, 0 }\n};\n\nstatic int usage(const char *prog) {\n std::cerr << \"USAGE: [encode|decode]\" << prog << \" [options]\" << std::endl\n << \"-h, --help Show this help message\" << std::endl\n << \"-s, --salt The salt to use for the encryption\" << std::endl\n << \"-a, --alphabet A custom alphabet to use\" << std::endl\n << \"-m, --min The minimum amount of characters to use, only \"\n \"useful when encoding\" << std::endl\n << \"-i, --input Input numbers, in case of encode repeat this \"\n \"for multiple input numbers\" << std::endl;\n return 1;\n};\n\nint main(int argc, char **argv) {\n if (argc == 1)\n return usage(argv[0]);\n\n std::string salt;\n std::string alphabet(DEFAULT_ALPHABET);\n unsigned int min_length = 0;\n\n bool encode = (strcmp(argv[1], \"encode\") == 0);\n if (encode == false && strcmp(argv[1], \"decode\") != 0)\n return usage(argv[0]); \/\/ we must make sure we were at least decode or\n \/\/ encode you know\n\n std::list<uint32_t> encode_input;\n std::string decode_input;\n\n int arg, optindex;\n while ((arg = getopt_long(argc, argv, \"hs:a:m:i:\", g_LongOpts, &optindex)) !=\n -1) {\n switch (arg) {\n case 'h':\n return usage(argv[0]);\n case 's':\n salt = std::string(optarg);\n break;\n case 'a':\n alphabet = std::string(optarg);\n break;\n case 'm':\n min_length = std::stoi(std::string(optarg));\n break;\n case 'i':\n if (encode)\n encode_input.push_back(std::stoi(std::string(optarg)));\n else\n decode_input = std::string(optarg);\n break;\n }\n }\n\n try {\n hashidsxx::Hashids hash(salt, min_length, alphabet);\n\n if (encode)\n std::cout << hash.encode(encode_input.begin(), encode_input.end())\n << std::endl;\n else {\n for (uint32_t number : hash.decode(decode_input))\n std::cout << number << std::endl;\n }\n }\n catch (const std::runtime_error &error) {\n std::cerr << error.what() << std::endl;\n return 1;\n };\n\n return 0;\n};\n<commit_msg>Added support for encode and decode hex<commit_after>\/**\n * Hashidsxx (c) 2014 Toon Schoenmakers\n *\n * https:\/\/github.com\/schoentoon\/hashidsxx\n * hashidsxx may be freely distributed under the MIT license.\n *\/\n\n#include <getopt.h>\n#include <string.h>\n\n#include \"hashids.h\"\n\n#include <iostream>\n#include <list>\n\nstatic const struct option g_LongOpts[] = {\n { \"help\", no_argument, 0, 'h' },\n { \"salt\", required_argument, 0, 's' },\n { \"alphabet\", required_argument, 0, 'a' },\n { \"min\", required_argument, 0, 'm' },\n { \"input\", required_argument, 0, 'i' },\n { 0, 0, 0, 0 }\n};\n\nstatic int usage(const char *prog) {\n std::cerr << \"USAGE: [encode|decode|encodeHex|decodeHex]\" << prog\n << \" [options]\" << std::endl\n << \"-h, --help Show this help message\" << std::endl\n << \"-s, --salt The salt to use for the encryption\" << std::endl\n << \"-a, --alphabet A custom alphabet to use\" << std::endl\n << \"-m, --min The minimum amount of characters to use, only \"\n \"useful when encoding\" << std::endl\n << \"-i, --input Input numbers, in case of encode repeat this \"\n \"for multiple input numbers\" << std::endl;\n return 1;\n};\n\nint main(int argc, char **argv) {\n if (argc == 1)\n return usage(argv[0]);\n\n std::string salt;\n std::string alphabet(DEFAULT_ALPHABET);\n unsigned int min_length = 0;\n\n std::string mode(argv[1]);\n\n if (mode != \"encode\" && mode != \"encodeHex\" && mode != \"decode\" &&\n mode != \"decodeHex\")\n return usage(argv[0]);\n\n bool encode = mode.compare(0, 6, \"encode\") == 0;\n bool hex = mode.compare(6, 3, \"Hex\") == 0;\n\n std::list<uint32_t> encode_input;\n std::string decode_input;\n std::string hexInput;\n\n int arg, optindex;\n while ((arg = getopt_long(argc, argv, \"hs:a:m:i:\", g_LongOpts, &optindex)) !=\n -1) {\n switch (arg) {\n case 'h':\n return usage(argv[0]);\n case 's':\n salt = std::string(optarg);\n break;\n case 'a':\n alphabet = std::string(optarg);\n break;\n case 'm':\n min_length = std::stoi(std::string(optarg));\n break;\n case 'i':\n if (hex)\n hexInput = std::string(optarg);\n else if (encode)\n encode_input.push_back(std::stoi(std::string(optarg)));\n else\n decode_input = std::string(optarg);\n break;\n }\n }\n\n try {\n hashidsxx::Hashids hash(salt, min_length, alphabet);\n\n if (hex) {\n if (encode)\n std::cout << hash.encodeHex(hexInput) << std::endl;\n else\n std::cout << hash.decodeHex(hexInput) << std::endl;\n } else {\n if (encode)\n std::cout << hash.encode(encode_input.begin(), encode_input.end())\n << std::endl;\n else {\n for (uint32_t number : hash.decode(decode_input))\n std::cout << number << std::endl;\n }\n }\n }\n catch (const std::runtime_error &error) {\n std::cerr << error.what() << std::endl;\n return 1;\n };\n\n return 0;\n};<|endoftext|>"} {"text":"<commit_before>#ifndef OM_ALLOCATOR_HPP_\n#define OM_ALLOCATOR_HPP_\n\n#include <Om\/AllocationSite.hpp>\n#include <Om\/Bytes.hpp>\n#include <Om\/Cell.hpp>\n#include <Om\/Context.hpp>\n#include <Om\/Heap.hpp>\n#include <Om\/Maybe.hpp>\n#include <Om\/Object.hpp>\n#include <Om\/RawAllocator.hpp>\n\nnamespace Om {\nnamespace Mm {\n\nstruct ObjectTemplate {\n\tSize slotCount_;\n};\n\nstruct AllocationRequest {\n\tObjectTemplate objectTemplate_;\n};\n\nstruct Allocation {\n\tMaybe<Object*> object_;\n};\n\nclass MemoryContext {\n\t\/\/ TODO(rwy0717) nothing\n};\n\nclass ObjectAllocator {\npublic:\n\ttemplate <GcSafe gcSafe = GcSafe::yes>\n\tinline auto allocate(Context& cx, const AllocationRequest& site) -> Maybe<Ref<Object>> {\n\t\tauto alloc = Maybe<Ref<Object>>{rawAllocator_.allocate<gcSafe>(cx, mib(32))};\n\t}\n\n\tinline constexpr auto raw() -> RawAllocator& {\n\t\treturn rawAllocator_;\n\t}\n\nprivate:\n\tRawAllocator rawAllocator_;\n};\n\n} \/\/ namespace Mm\n} \/\/ namespace Om\n\n#endif \/\/ OM_ALLOCATOR_HPP_<commit_msg>Remove constexpr member in non-literal type<commit_after>#ifndef OM_ALLOCATOR_HPP_\n#define OM_ALLOCATOR_HPP_\n\n#include <Om\/AllocationSite.hpp>\n#include <Om\/Bytes.hpp>\n#include <Om\/Cell.hpp>\n#include <Om\/Context.hpp>\n#include <Om\/Heap.hpp>\n#include <Om\/Maybe.hpp>\n#include <Om\/Object.hpp>\n#include <Om\/RawAllocator.hpp>\n\nnamespace Om {\nnamespace Mm {\n\nstruct ObjectTemplate {\n\tSize slotCount_;\n};\n\nstruct AllocationRequest {\n\tObjectTemplate objectTemplate_;\n};\n\nstruct Allocation {\n\tMaybe<Object*> object_;\n};\n\nclass MemoryContext {\n\t\/\/ TODO(rwy0717) nothing\n};\n\nclass ObjectAllocator {\npublic:\n\ttemplate <GcSafe gcSafe = GcSafe::yes>\n\tinline auto allocate(Context& cx, const AllocationRequest& site) -> Maybe<Ref<Object>> {\n\t\tauto alloc = Maybe<Ref<Object>>{rawAllocator_.allocate<gcSafe>(cx, mib(32))};\n\t}\n\n\tinline auto raw() -> RawAllocator& {\n\t\treturn rawAllocator_;\n\t}\n\nprivate:\n\tRawAllocator rawAllocator_;\n};\n\n} \/\/ namespace Mm\n} \/\/ namespace Om\n\n#endif \/\/ OM_ALLOCATOR_HPP_<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/atomspace\/AtomSpace.cc\n *\n * Copyright (c) 2008-2010 OpenCog Foundation\n * Copyright (c) 2009, 2013 Linas Vepstas\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <list>\n\n#include <stdlib.h>\n\n#include <opencog\/util\/Logger.h>\n#include <opencog\/util\/oc_assert.h>\n\n#include <opencog\/atoms\/base\/Link.h>\n#include <opencog\/atoms\/base\/Node.h>\n#include <opencog\/atoms\/proto\/types.h>\n\n#include \"AtomSpace.h\"\n\n\/\/#define DPRINTF printf\n#define DPRINTF(...)\n\nusing std::string;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::min;\nusing std::max;\nusing namespace opencog;\n\n\/\/ ====================================================================\n\n\/**\n * Transient atomspaces skip some of the initialization steps,\n * so that they can be constructed more quickly. Transient atomspaces\n * are typically used as scratch spaces, to hold temporary results\n * during evaluation, pattern matching and inference. Such temporary\n * spaces don't need some of the heavier-weight crud that atomspaces\n * are festooned with.\n *\/\nAtomSpace::AtomSpace(AtomSpace* parent, bool transient) :\n _atom_table(parent? &parent->_atom_table : nullptr, this, transient),\n _backing_store(nullptr),\n _read_only(false)\n{\n}\n\nAtomSpace::~AtomSpace()\n{\n}\n\nvoid AtomSpace::ready_transient(AtomSpace* parent)\n{\n _atom_table.ready_transient(parent? &parent->_atom_table : nullptr, this);\n}\n\nvoid AtomSpace::clear_transient()\n{\n _atom_table.clear_transient();\n}\n\n\/\/ An extremely primitive permissions system.\nvoid AtomSpace::set_read_only(void)\n{\n _read_only = true;\n}\n\nvoid AtomSpace::set_read_write(void)\n{\n _read_only = false;\n}\n\nbool AtomSpace::compare_atomspaces(const AtomSpace& space_first,\n const AtomSpace& space_second,\n bool check_truth_values,\n bool emit_diagnostics)\n{\n \/\/ Compare sizes\n if (space_first.get_size() != space_second.get_size())\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - size \" << \n space_first.get_size() << \" != size \" << \n space_second.get_size() << std::endl;\n return false;\n }\n\n \/\/ Compare node count\n if (space_first.get_num_nodes() != space_second.get_num_nodes())\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - node count \" << \n space_first.get_num_nodes() << \" != node count \" << \n space_second.get_num_nodes() << std::endl;\n return false;\n }\n\n \/\/ Compare link count\n if (space_first.get_num_links() != space_second.get_num_links())\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - link count \" << \n space_first.get_num_links() << \" != link count \" << \n space_second.get_num_links() << std::endl;\n return false;\n }\n\n \/\/ If we get this far, we need to compare each individual atom.\n\n \/\/ Get the atoms in each atomspace.\n HandleSeq atomsInFirstSpace, atomsInSecondSpace;\n space_first.get_all_atoms(atomsInFirstSpace);\n space_second.get_all_atoms(atomsInSecondSpace);\n\n \/\/ Uncheck each atom in the second atomspace.\n for (auto atom : atomsInSecondSpace)\n atom->setUnchecked();\n\n \/\/ Loop to see if each atom in the first has a match in the second.\n const AtomTable& table_second = space_second._atom_table;\n for (auto atom_first : atomsInFirstSpace)\n {\n Handle atom_second = table_second.getHandle(atom_first);\n\n if( false)\n {\n Handle atom_second;\n if (atom_first->is_node())\n {\n atom_second = table_second.getHandle(atom_first->get_type(),\n atom_first->get_name());\n }\n else if (atom_first->is_link())\n {\n atom_second = table_second.getHandle(atom_first->get_type(),\n atom_first->getOutgoingSet());\n }\n else\n {\n throw opencog::RuntimeException(TRACE_INFO,\n \"AtomSpace::compare_atomspaces - atom not Node or Link\");\n }\n }\n\n \/\/ If the atoms don't match because one of them is null.\n if ((atom_first and not atom_second) or\n (atom_second and not atom_first))\n {\n if (emit_diagnostics)\n {\n if (atom_first)\n std::cout << \"compare_atomspaces - first atom \" << \n atom_first->to_string() << \" != NULL \" <<\n std::endl;\n if (atom_second)\n std::cout << \"compare_atomspaces - first atom \" <<\n \"NULL != second atom \" << \n atom_second->to_string() << std::endl;\n }\n return false;\n }\n\n \/\/ If the atoms don't match... Compare the atoms not the pointers\n \/\/ which is the default if we just use Handle operator ==.\n if (*((AtomPtr) atom_first) != *((AtomPtr) atom_second))\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - first atom \" << \n atom_first->to_string() << \" != second atom \" <<\n atom_second->to_string() << std::endl;\n return false;\n }\n\n \/\/ Check the truth values...\n if (check_truth_values)\n {\n TruthValuePtr truth_first = atom_first->getTruthValue();\n TruthValuePtr truth_second = atom_second->getTruthValue();\n if (*truth_first != *truth_second)\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - first truth \" << \n atom_first->to_string() << \" != second truth \" <<\n atom_second->to_string() << std::endl;\n return false;\n }\n }\n\n \/\/ Set the check for the second atom.\n atom_second->setChecked();\n }\n\n \/\/ Make sure each atom in the second atomspace has been checked.\n bool all_checked = true;\n for (auto atom : atomsInSecondSpace)\n {\n if (!atom->isChecked())\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - unchecked space atom \" << \n atom->to_string() << std::endl;\n all_checked = false;\n }\n }\n if (!all_checked)\n return false;\n\n \/\/ If we get this far, then the spaces are equal.\n return true;\n}\n\nbool AtomSpace::operator==(const AtomSpace& other) const\n{\n return compare_atomspaces(*this, other, CHECK_TRUTH_VALUES, \n DONT_EMIT_DIAGNOSTICS);\n}\n\nbool AtomSpace::operator!=(const AtomSpace& other) const\n{\n return not operator==(other);\n}\n\n\n\/\/ ====================================================================\n\nbool AtomSpace::isAttachedToBackingStore()\n{\n if (nullptr != _backing_store) return true;\n return false;\n}\n\nvoid AtomSpace::registerBackingStore(BackingStore *bs)\n{\n if (isAttachedToBackingStore())\n throw RuntimeException(TRACE_INFO,\n \"AtomSpace is already connected to a BackingStore.\");\n\n _backing_store = bs;\n}\n\nvoid AtomSpace::unregisterBackingStore(BackingStore *bs)\n{\n if (not isAttachedToBackingStore())\n throw RuntimeException(TRACE_INFO,\n \"AtomSpace is not connected to a BackingStore.\");\n\n if (bs == _backing_store) _backing_store = nullptr;\n}\n\n\/\/ ====================================================================\n\nHandle AtomSpace::add_atom(const Handle& h, bool async)\n{\n \/\/ If it is a DeleteLink, then the addition will fail. Deal with it.\n Handle rh;\n try {\n rh = _atom_table.add(h, async);\n }\n catch (const DeleteException& ex) {\n \/\/ Atom deletion has not been implemented in the backing store\n \/\/ This is a major to-do item.\n if (_backing_store)\n _backing_store->removeAtom(h, false);\n }\n return rh;\n}\n\nHandle AtomSpace::add_node(Type t, const string& name,\n bool async)\n{\n return _atom_table.add(createNode(t, name), async);\n}\n\nHandle AtomSpace::get_node(Type t, const string& name)\n{\n return _atom_table.getHandle(t, name);\n}\n\nHandle AtomSpace::add_link(Type t, const HandleSeq& outgoing, bool async)\n{\n \/\/ If it is a DeleteLink, then the addition will fail. Deal with it.\n Handle rh;\n try {\n rh = _atom_table.add(createLink(outgoing, t), async);\n }\n catch (const DeleteException& ex) {\n if (_backing_store) {\n Handle h(createLink(outgoing, t));\n _backing_store->removeAtom(h, false);\n }\n }\n return rh;\n}\n\nHandle AtomSpace::get_link(Type t, const HandleSeq& outgoing)\n{\n return _atom_table.getHandle(t, outgoing);\n}\n\nvoid AtomSpace::store_atom(const Handle& h)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n\n _backing_store->storeAtom(h);\n}\n\nHandle AtomSpace::fetch_atom(const Handle& h)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n if (nullptr == h) return Handle::UNDEFINED;\n\n \/\/ First, make sure the atom is actually in the atomspace.\n Handle hc(_atom_table.add(h, false));\n\n \/\/ Now, get the latest values from the backing store.\n \/\/ The operation here is to CLOBBER the values, NOT to merge them!\n \/\/ The goal of an explicit fetch is to explicitly fetch the values,\n \/\/ and not to play monkey-shines with them. If you want something\n \/\/ else, then save the old TV, fetch the new TV, and combine them\n \/\/ with your favorite algo.\n Handle hv;\n if (h->is_node()) {\n hv = _backing_store->getNode(h->get_type(),\n h->get_name().c_str());\n }\n else if (h->is_link()) {\n hv = _backing_store->getLink(h->get_type(),\n h->getOutgoingSet());\n }\n\n \/\/ Hmm I don't quite get it ... shouldn't hv and hc be the same\n \/\/ atom, by now? So the below should not be needed...!?\n if (hv and hv != hc)\n {\n hc->copyValues(hv);\n TruthValuePtr tv = hv->getTruthValue();\n hc->setTruthValue(tv);\n }\n\n return hc;\n}\n\nHandle AtomSpace::fetch_incoming_set(Handle h, bool recursive)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n\n h = get_atom(h);\n if (nullptr == h) return h;\n\n \/\/ Get everything from the backing store.\n _backing_store->getIncomingSet(_atom_table, h);\n\n if (not recursive) return h;\n\n IncomingSet vh(h->getIncomingSet());\n for (const LinkPtr& lp : vh)\n fetch_incoming_set(Handle(lp), true);\n\n return h;\n}\n\nHandle AtomSpace::fetch_incoming_by_type(Handle h, Type t)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n\n h = get_atom(h);\n if (nullptr == h) return h;\n\n \/\/ Get everything from the backing store.\n _backing_store->getIncomingByType(_atom_table, h, t);\n\n return h;\n}\n\nvoid AtomSpace::fetch_valuations(Handle key, bool get_all_values)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n\n key = get_atom(key);\n if (nullptr == key) return;\n\n \/\/ Get everything from the backing store.\n _backing_store->getValuations(_atom_table, key, get_all_values);\n}\n\nbool AtomSpace::remove_atom(Handle h, bool recursive)\n{\n if (_backing_store)\n _backing_store->removeAtom(h, recursive);\n return 0 < _atom_table.extract(h, recursive).size();\n}\n\nstd::string AtomSpace::to_string() const\n{\n\tstd::stringstream ss;\n\tss << *this;\n\treturn ss.str();\n}\n\nnamespace std {\n\nostream& operator<<(ostream& out, const opencog::AtomSpace& as) {\n list<opencog::Handle> results;\n as.get_handles_by_type(back_inserter(results), opencog::ATOM, true);\n for (const opencog::Handle& h : results)\n\t if (h->getIncomingSetSize() == 0)\n\t\t out << h->to_string() << endl;\n return out;\n}\n\n} \/\/ namespace std\n<commit_msg>Start implementing the read-only constraint.<commit_after>\/*\n * opencog\/atomspace\/AtomSpace.cc\n *\n * Copyright (c) 2008-2010 OpenCog Foundation\n * Copyright (c) 2009, 2013 Linas Vepstas\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <list>\n\n#include <stdlib.h>\n\n#include <opencog\/util\/Logger.h>\n#include <opencog\/util\/oc_assert.h>\n\n#include <opencog\/atoms\/base\/Link.h>\n#include <opencog\/atoms\/base\/Node.h>\n#include <opencog\/atoms\/proto\/types.h>\n\n#include \"AtomSpace.h\"\n\n\/\/#define DPRINTF printf\n#define DPRINTF(...)\n\nusing std::string;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::min;\nusing std::max;\nusing namespace opencog;\n\n\/\/ ====================================================================\n\n\/**\n * Transient atomspaces skip some of the initialization steps,\n * so that they can be constructed more quickly. Transient atomspaces\n * are typically used as scratch spaces, to hold temporary results\n * during evaluation, pattern matching and inference. Such temporary\n * spaces don't need some of the heavier-weight crud that atomspaces\n * are festooned with.\n *\/\nAtomSpace::AtomSpace(AtomSpace* parent, bool transient) :\n _atom_table(parent? &parent->_atom_table : nullptr, this, transient),\n _backing_store(nullptr),\n _read_only(false)\n{\n}\n\nAtomSpace::~AtomSpace()\n{\n}\n\nvoid AtomSpace::ready_transient(AtomSpace* parent)\n{\n _atom_table.ready_transient(parent? &parent->_atom_table : nullptr, this);\n}\n\nvoid AtomSpace::clear_transient()\n{\n _atom_table.clear_transient();\n}\n\n\/\/ An extremely primitive permissions system.\nvoid AtomSpace::set_read_only(void)\n{\n _read_only = true;\n}\n\nvoid AtomSpace::set_read_write(void)\n{\n _read_only = false;\n}\n\nbool AtomSpace::compare_atomspaces(const AtomSpace& space_first,\n const AtomSpace& space_second,\n bool check_truth_values,\n bool emit_diagnostics)\n{\n \/\/ Compare sizes\n if (space_first.get_size() != space_second.get_size())\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - size \" << \n space_first.get_size() << \" != size \" << \n space_second.get_size() << std::endl;\n return false;\n }\n\n \/\/ Compare node count\n if (space_first.get_num_nodes() != space_second.get_num_nodes())\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - node count \" << \n space_first.get_num_nodes() << \" != node count \" << \n space_second.get_num_nodes() << std::endl;\n return false;\n }\n\n \/\/ Compare link count\n if (space_first.get_num_links() != space_second.get_num_links())\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - link count \" << \n space_first.get_num_links() << \" != link count \" << \n space_second.get_num_links() << std::endl;\n return false;\n }\n\n \/\/ If we get this far, we need to compare each individual atom.\n\n \/\/ Get the atoms in each atomspace.\n HandleSeq atomsInFirstSpace, atomsInSecondSpace;\n space_first.get_all_atoms(atomsInFirstSpace);\n space_second.get_all_atoms(atomsInSecondSpace);\n\n \/\/ Uncheck each atom in the second atomspace.\n for (auto atom : atomsInSecondSpace)\n atom->setUnchecked();\n\n \/\/ Loop to see if each atom in the first has a match in the second.\n const AtomTable& table_second = space_second._atom_table;\n for (auto atom_first : atomsInFirstSpace)\n {\n Handle atom_second = table_second.getHandle(atom_first);\n\n if( false)\n {\n Handle atom_second;\n if (atom_first->is_node())\n {\n atom_second = table_second.getHandle(atom_first->get_type(),\n atom_first->get_name());\n }\n else if (atom_first->is_link())\n {\n atom_second = table_second.getHandle(atom_first->get_type(),\n atom_first->getOutgoingSet());\n }\n else\n {\n throw opencog::RuntimeException(TRACE_INFO,\n \"AtomSpace::compare_atomspaces - atom not Node or Link\");\n }\n }\n\n \/\/ If the atoms don't match because one of them is null.\n if ((atom_first and not atom_second) or\n (atom_second and not atom_first))\n {\n if (emit_diagnostics)\n {\n if (atom_first)\n std::cout << \"compare_atomspaces - first atom \" << \n atom_first->to_string() << \" != NULL \" <<\n std::endl;\n if (atom_second)\n std::cout << \"compare_atomspaces - first atom \" <<\n \"NULL != second atom \" << \n atom_second->to_string() << std::endl;\n }\n return false;\n }\n\n \/\/ If the atoms don't match... Compare the atoms not the pointers\n \/\/ which is the default if we just use Handle operator ==.\n if (*((AtomPtr) atom_first) != *((AtomPtr) atom_second))\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - first atom \" << \n atom_first->to_string() << \" != second atom \" <<\n atom_second->to_string() << std::endl;\n return false;\n }\n\n \/\/ Check the truth values...\n if (check_truth_values)\n {\n TruthValuePtr truth_first = atom_first->getTruthValue();\n TruthValuePtr truth_second = atom_second->getTruthValue();\n if (*truth_first != *truth_second)\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - first truth \" << \n atom_first->to_string() << \" != second truth \" <<\n atom_second->to_string() << std::endl;\n return false;\n }\n }\n\n \/\/ Set the check for the second atom.\n atom_second->setChecked();\n }\n\n \/\/ Make sure each atom in the second atomspace has been checked.\n bool all_checked = true;\n for (auto atom : atomsInSecondSpace)\n {\n if (!atom->isChecked())\n {\n if (emit_diagnostics)\n std::cout << \"compare_atomspaces - unchecked space atom \" << \n atom->to_string() << std::endl;\n all_checked = false;\n }\n }\n if (!all_checked)\n return false;\n\n \/\/ If we get this far, then the spaces are equal.\n return true;\n}\n\nbool AtomSpace::operator==(const AtomSpace& other) const\n{\n return compare_atomspaces(*this, other, CHECK_TRUTH_VALUES, \n DONT_EMIT_DIAGNOSTICS);\n}\n\nbool AtomSpace::operator!=(const AtomSpace& other) const\n{\n return not operator==(other);\n}\n\n\n\/\/ ====================================================================\n\nbool AtomSpace::isAttachedToBackingStore()\n{\n if (nullptr != _backing_store) return true;\n return false;\n}\n\nvoid AtomSpace::registerBackingStore(BackingStore *bs)\n{\n if (isAttachedToBackingStore())\n throw RuntimeException(TRACE_INFO,\n \"AtomSpace is already connected to a BackingStore.\");\n\n _backing_store = bs;\n}\n\nvoid AtomSpace::unregisterBackingStore(BackingStore *bs)\n{\n if (not isAttachedToBackingStore())\n throw RuntimeException(TRACE_INFO,\n \"AtomSpace is not connected to a BackingStore.\");\n\n if (bs == _backing_store) _backing_store = nullptr;\n}\n\n\/\/ ====================================================================\n\nHandle AtomSpace::add_atom(const Handle& h, bool async)\n{\n \/\/ Cannot add atoms to a read-only atomspce. But if it's already\n \/\/ in the atomspace, return it.\n if (_read_only) return _atom_table.getHandle(h);\n\n \/\/ If it is a DeleteLink, then the addition will fail. Deal with it.\n Handle rh;\n try {\n rh = _atom_table.add(h, async);\n }\n catch (const DeleteException& ex) {\n \/\/ Atom deletion has not been implemented in the backing store\n \/\/ This is a major to-do item.\n if (_backing_store)\n _backing_store->removeAtom(h, false);\n }\n return rh;\n}\n\nHandle AtomSpace::add_node(Type t, const string& name,\n bool async)\n{\n return _atom_table.add(createNode(t, name), async);\n}\n\nHandle AtomSpace::get_node(Type t, const string& name)\n{\n return _atom_table.getHandle(t, name);\n}\n\nHandle AtomSpace::add_link(Type t, const HandleSeq& outgoing, bool async)\n{\n \/\/ Cannot add atoms to a read-only atomspce. But if it's already\n \/\/ in the atomspace, return it.\n if (_read_only) return _atom_table.getHandle(t, outgoing);\n\n \/\/ If it is a DeleteLink, then the addition will fail. Deal with it.\n Handle rh;\n try {\n rh = _atom_table.add(createLink(outgoing, t), async);\n }\n catch (const DeleteException& ex) {\n if (_backing_store) {\n Handle h(createLink(outgoing, t));\n _backing_store->removeAtom(h, false);\n }\n }\n return rh;\n}\n\nHandle AtomSpace::get_link(Type t, const HandleSeq& outgoing)\n{\n return _atom_table.getHandle(t, outgoing);\n}\n\nvoid AtomSpace::store_atom(const Handle& h)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n\n if (_read_only)\n throw RuntimeException(TRACE_INFO, \"Read-only AtomSpace!\");\n\n _backing_store->storeAtom(h);\n}\n\nHandle AtomSpace::fetch_atom(const Handle& h)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n if (nullptr == h) return Handle::UNDEFINED;\n\n \/\/ Now, get the latest values from the backing store.\n \/\/ The operation here is to CLOBBER the values, NOT to merge them!\n \/\/ The goal of an explicit fetch is to explicitly fetch the values,\n \/\/ and not to play monkey-shines with them. If you want something\n \/\/ else, then save the old TV, fetch the new TV, and combine them\n \/\/ with your favorite algo.\n Handle hv;\n if (h->is_node()) {\n hv = _backing_store->getNode(h->get_type(),\n h->get_name().c_str());\n }\n else if (h->is_link()) {\n hv = _backing_store->getLink(h->get_type(),\n h->getOutgoingSet());\n }\n\n \/\/ If we found it, add it to the atomspace -- even when the\n \/\/ atomspace is marked read-only; the atomspace is acting as\n \/\/ a cache for the backingstore.\n if (hv) return _atom_table.add(hv, false);\n\n \/\/ If it is not found, then it cannot be added.\n if (_read_only) return Handle::UNDEFINED;\n\n return _atom_table.add(h, false);\n}\n\nHandle AtomSpace::fetch_incoming_set(Handle h, bool recursive)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n\n h = get_atom(h);\n if (nullptr == h) return h;\n\n \/\/ Get everything from the backing store.\n _backing_store->getIncomingSet(_atom_table, h);\n\n if (not recursive) return h;\n\n IncomingSet vh(h->getIncomingSet());\n for (const LinkPtr& lp : vh)\n fetch_incoming_set(Handle(lp), true);\n\n return h;\n}\n\nHandle AtomSpace::fetch_incoming_by_type(Handle h, Type t)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n\n h = get_atom(h);\n if (nullptr == h) return h;\n\n \/\/ Get everything from the backing store.\n _backing_store->getIncomingByType(_atom_table, h, t);\n\n return h;\n}\n\nvoid AtomSpace::fetch_valuations(Handle key, bool get_all_values)\n{\n if (nullptr == _backing_store)\n throw RuntimeException(TRACE_INFO, \"No backing store\");\n\n key = get_atom(key);\n if (nullptr == key) return;\n\n \/\/ Get everything from the backing store.\n _backing_store->getValuations(_atom_table, key, get_all_values);\n}\n\nbool AtomSpace::remove_atom(Handle h, bool recursive)\n{\n if (_backing_store)\n _backing_store->removeAtom(h, recursive);\n return 0 < _atom_table.extract(h, recursive).size();\n}\n\nstd::string AtomSpace::to_string() const\n{\n\tstd::stringstream ss;\n\tss << *this;\n\treturn ss.str();\n}\n\nnamespace std {\n\nostream& operator<<(ostream& out, const opencog::AtomSpace& as) {\n list<opencog::Handle> results;\n as.get_handles_by_type(back_inserter(results), opencog::ATOM, true);\n for (const opencog::Handle& h : results)\n\t if (h->getIncomingSetSize() == 0)\n\t\t out << h->to_string() << endl;\n return out;\n}\n\n} \/\/ namespace std\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/base:$Name: $:$Id: TBuffer3D.cxx,v 1.00\n\/\/ Author: Olivier Couet 05\/05\/04\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TBuffer3D.h\"\n#include \"TVirtualPad.h\"\n#include \"TVirtualViewer3D.h\"\n#include \"TView.h\"\n\nClassImp(TBuffer3D)\n\n\n\/\/______________________________________________________________________________\nTBuffer3D::TBuffer3D()\n{\n fTransparency = 0;\n fType = -1;\n fOption = kPAD;\n fId = 0;\n fNbPnts = 0;\n fNbSegs = 0;\n fNbPols = 0;\n fPnts = 0;\n fSegs = 0;\n fPols = 0;\n fPntsSize = 0;\n fSegsSize = 0;\n fPolsSize = 0;\n fColor = 0;\n}\n\n\n\/\/______________________________________________________________________________\nTBuffer3D::TBuffer3D(Int_t n1, Int_t n2, Int_t n3)\n{\n fTransparency = 0;\n fPntsSize = n1;\n fSegsSize = n2;\n fPolsSize = n3;\n\n fType = -1;\n fOption = kPAD;\n fId = 0;\n\n fNbPnts = 0;\n fNbSegs = 0;\n fNbPols = 0;\n\n fPnts = 0;\n fSegs = 0;\n fPols = 0;\n fColor = 0;\n if ( fPntsSize>0 ) fPnts = new Double_t[fPntsSize];\n if ( fSegsSize>0 ) fSegs = new Int_t[fSegsSize];\n if ( fPolsSize>0 ) fPols = new Int_t[fPolsSize];\n}\n\n\n\/\/______________________________________________________________________________\nTBuffer3D::~TBuffer3D()\n{\n if (fPnts) delete [] fPnts;\n if (fSegs) delete [] fSegs;\n if (fPols) delete [] fPols;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TBuffer3D::Paint(Option_t *option)\n{\n Int_t i, i0, i1, i2;\n Double_t x0, y0, z0, x1, y1, z1;\n TVirtualViewer3D *viewer3D;\n TView *view;\n\n \/\/ Compute the shape range and update gPad->fView\n switch (fOption) {\n case kRANGE:\n x0 = x1 = fPnts[0];\n y0 = y1 = fPnts[1];\n z0 = z1 = fPnts[2];\n for (i=1; i<fNbPnts; i++) {\n i0 = 3*i; i1 = i0+1; i2 = i0+2;\n x0 = fPnts[i0] < x0 ? fPnts[i0] : x0;\n y0 = fPnts[i1] < y0 ? fPnts[i1] : y0;\n z0 = fPnts[i2] < z0 ? fPnts[i2] : z0;\n x1 = fPnts[i0] > x1 ? fPnts[i0] : x1;\n y1 = fPnts[i1] > y1 ? fPnts[i1] : y1;\n z1 = fPnts[i2] > z1 ? fPnts[i2] : z1;\n }\n view = gPad->GetView();\n if (view->GetAutoRange()) view->SetRange(x0,y0,z0,x1,y1,z1,2);\n break;\n \n \/\/ Update viewer\n case kSIZE:\n case kX3D:\n case kOGL:\n viewer3D = gPad->GetViewer3D();\n if (viewer3D) viewer3D->UpdateScene(option);\n break;\n\n \/\/ Paint this in gPad\n case kPAD:\n default:\n if (option && strlen(option) > 0) {\n if (strcmp(option,\"SAME\") && strcmp(option,\"same\")) return;\n } \n if (fTransparency > 50) return; \/\/do not show semi transparent objects\n if ( fType==kMARKER ) {\n view = gPad->GetView();\n Double_t pndc[3], temp[3];\n for (i=0; i<fNbPnts; i++) {\n for ( i0=0; i0<3; i0++ ) temp[i0] = fPnts[3*i+i0];\n view->WCtoNDC(temp, pndc);\n gPad->PaintPolyMarker(1, &pndc[0], &pndc[1]);\n }\n } else {\n for (i=0; i<fNbSegs; i++) {\n i0 = 3*fSegs[3*i+1];\n Double_t *ptpoints_0 = &(fPnts[i0]);\n i0 = 3*fSegs[3*i+2];\n Double_t *ptpoints_3 = &(fPnts[i0]);\n gPad->PaintLine3D(ptpoints_0, ptpoints_3);\n }\n }\n break;\n }\n}\n\n\n\/\/______________________________________________________________________________\nvoid TBuffer3D::ReAllocate(Int_t n1, Int_t n2, Int_t n3)\n{\n if (n1 > fPntsSize) {\n delete [] fPnts;\n fPntsSize = n1;\n fPnts = new Double_t[fPntsSize];\n }\n if (n2 > fSegsSize) {\n delete [] fSegs;\n fSegsSize = n2;\n fSegs = new Int_t[fSegsSize];\n }\n if (n3 > fPolsSize) {\n delete [] fPols;\n fPolsSize = n3;\n fPols = new Int_t[fPolsSize];\n }\n}\n<commit_msg>From Olivier: - revision 1.5 had a bad side effect: it was not anymore possible to visualize the 3D histograms as box plots. This fix preserve what was aimed in rev1.5 (not drawing in the pad when the OpenGL viewer is active), and allow to see 3D histograms with the \"box\" option.<commit_after>\/\/ @(#)root\/base:$Name: $:$Id: TBuffer3D.cxx,v 1.00\n\/\/ Author: Olivier Couet 05\/05\/04\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TBuffer3D.h\"\n#include \"TVirtualPad.h\"\n#include \"TVirtualViewer3D.h\"\n#include \"TView.h\"\n\nClassImp(TBuffer3D)\n\n\n\/\/______________________________________________________________________________\nTBuffer3D::TBuffer3D()\n{\n fTransparency = 0;\n fType = -1;\n fOption = kPAD;\n fId = 0;\n fNbPnts = 0;\n fNbSegs = 0;\n fNbPols = 0;\n fPnts = 0;\n fSegs = 0;\n fPols = 0;\n fPntsSize = 0;\n fSegsSize = 0;\n fPolsSize = 0;\n fColor = 0;\n}\n\n\n\/\/______________________________________________________________________________\nTBuffer3D::TBuffer3D(Int_t n1, Int_t n2, Int_t n3)\n{\n fTransparency = 0;\n fPntsSize = n1;\n fSegsSize = n2;\n fPolsSize = n3;\n\n fType = -1;\n fOption = kPAD;\n fId = 0;\n\n fNbPnts = 0;\n fNbSegs = 0;\n fNbPols = 0;\n\n fPnts = 0;\n fSegs = 0;\n fPols = 0;\n fColor = 0;\n if ( fPntsSize>0 ) fPnts = new Double_t[fPntsSize];\n if ( fSegsSize>0 ) fSegs = new Int_t[fSegsSize];\n if ( fPolsSize>0 ) fPols = new Int_t[fPolsSize];\n}\n\n\n\/\/______________________________________________________________________________\nTBuffer3D::~TBuffer3D()\n{\n if (fPnts) delete [] fPnts;\n if (fSegs) delete [] fSegs;\n if (fPols) delete [] fPols;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TBuffer3D::Paint(Option_t *option)\n{\n Int_t i, i0, i1, i2;\n Double_t x0, y0, z0, x1, y1, z1;\n TVirtualViewer3D *viewer3D;\n TView *view;\n\n \/\/ Compute the shape range and update gPad->fView\n switch (fOption) {\n case kRANGE:\n x0 = x1 = fPnts[0];\n y0 = y1 = fPnts[1];\n z0 = z1 = fPnts[2];\n for (i=1; i<fNbPnts; i++) {\n i0 = 3*i; i1 = i0+1; i2 = i0+2;\n x0 = fPnts[i0] < x0 ? fPnts[i0] : x0;\n y0 = fPnts[i1] < y0 ? fPnts[i1] : y0;\n z0 = fPnts[i2] < z0 ? fPnts[i2] : z0;\n x1 = fPnts[i0] > x1 ? fPnts[i0] : x1;\n y1 = fPnts[i1] > y1 ? fPnts[i1] : y1;\n z1 = fPnts[i2] > z1 ? fPnts[i2] : z1;\n }\n view = gPad->GetView();\n if (view->GetAutoRange()) view->SetRange(x0,y0,z0,x1,y1,z1,2);\n break;\n\n \/\/ Update viewer\n case kSIZE:\n case kX3D:\n case kOGL:\n viewer3D = gPad->GetViewer3D();\n if (viewer3D) viewer3D->UpdateScene(option);\n break;\n\n \/\/ Paint this in gPad\n case kPAD:\n default:\n if (option && !strcmp(option, \"ogl\")) return; \/\/ In case of OpenGL, the pad is not redrawn\n if (fTransparency > 50) return; \/\/do not show semi transparent objects\n if ( fType==kMARKER ) {\n view = gPad->GetView();\n Double_t pndc[3], temp[3];\n for (i=0; i<fNbPnts; i++) {\n for ( i0=0; i0<3; i0++ ) temp[i0] = fPnts[3*i+i0];\n view->WCtoNDC(temp, pndc);\n gPad->PaintPolyMarker(1, &pndc[0], &pndc[1]);\n }\n } else {\n for (i=0; i<fNbSegs; i++) {\n i0 = 3*fSegs[3*i+1];\n Double_t *ptpoints_0 = &(fPnts[i0]);\n i0 = 3*fSegs[3*i+2];\n Double_t *ptpoints_3 = &(fPnts[i0]);\n gPad->PaintLine3D(ptpoints_0, ptpoints_3);\n }\n }\n break;\n }\n}\n\n\n\/\/______________________________________________________________________________\nvoid TBuffer3D::ReAllocate(Int_t n1, Int_t n2, Int_t n3)\n{\n if (n1 > fPntsSize) {\n delete [] fPnts;\n fPntsSize = n1;\n fPnts = new Double_t[fPntsSize];\n }\n if (n2 > fSegsSize) {\n delete [] fSegs;\n fSegsSize = n2;\n fSegs = new Int_t[fSegsSize];\n }\n if (n3 > fPolsSize) {\n delete [] fPols;\n fPolsSize = n3;\n fPols = new Int_t[fPolsSize];\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"AliITSPreprocessorSSD.h\"\n \n#include \"AliCDBMetaData.h\"\n#include \"AliLog.h\"\n#include \"TFile.h\"\n\n#include <TTimeStamp.h>\n#include <TObjString.h>\n\n#include \"AliITSRawStreamSSD.h\"\n#include \"AliITSNoiseSSD.h\"\n#include \"AliITSPedestalSSD.h\"\n#include \"AliITSBadChannelsSSD.h\"\n#include <Riostream.h>\n\n\n\/\/\n\/\/ Author: Enrico Fragiacomo\n\/\/ Date: 13\/10\/2006\n\/\/ \n\/\/ SHUTTLE preprocessing class for SSD calibration files\n\n\/* $Id$ *\/\n\nconst Int_t AliITSPreprocessorSSD::fgkNumberOfSSD = 1698;\n\nClassImp(AliITSPreprocessorSSD)\n\n\/\/-----------------------------------------------------------------------\nAliITSPreprocessorSSD::AliITSPreprocessorSSD(AliShuttleInterface* shuttle) :\n AliPreprocessor(\"SSD\", shuttle)\n{\n \/\/ constructor\n\n AddRunType(\"ELECTRONICS_CALIBRATION_RUN\");\n AddRunType(\"PEDESTAL\");\n AddRunType(\"PHYSICS\");\n\n}\n\n\/\/\/______________________________________________________________________________________________\nvoid AliITSPreprocessorSSD::Initialize(Int_t run, UInt_t startTime,\n\tUInt_t endTime)\n{\n \n AliPreprocessor::Initialize(run, startTime, endTime);\n \n Log(Form(\"\\n\\tRun %d \\n\\tStartTime %s \\n\\tEndTime %s\", run,\n\t TTimeStamp(startTime).AsString(),\n\t TTimeStamp(endTime).AsString()));\n \n}\n\n\/\/______________________________________________________________________________________________\nUInt_t AliITSPreprocessorSSD::Process(TMap* \/*dcsAliasMap*\/)\n{\n\n \/\/ Note. To be modified: dcsAliasMap is not needed but I can not get rid\n \/\/ of it unless the base class AliPreprocessor is modified accordingly.\n\n TObjArray calib_array(fgkNumberOfSSD); \n TObjArray badch_array(fgkNumberOfSSD); \n TObjArray ped_array(fgkNumberOfSSD); \n \/\/Float_t noise=0, gain=0;\n \n TString runType = GetRunType();\n if(runType == \"ELECTRONICS_CALIBRATION_RUN\") {\n \n }\n else if(runType == \"PEDESTAL\") {\n\n TList* list = GetFileSources(kDAQ, \"CALIBRATION\");\n if (list && list->GetEntries() > 0)\n {\n\tLog(\"The following sources produced files with the id CALIBRATION\");\n\tlist->Print();\n\t\n\t\/\/ create iterator over list of LDCs (provides list of TObjString)\n\tTIter next(list);\n\tTObjString *ok;\n\t\n\t\/\/---------------------------------------\n\t\/\/ in case some module was not calibrated!\n\tfor(Int_t i=0; i<fgkNumberOfSSD; i++) {\n\t AliITSNoiseSSD *calib = new AliITSNoiseSSD();\n\t calib->SetMod((UShort_t) i+500);\n\t calib->SetNNoiseP(768);\n\t calib->SetNNoiseN(768);\n\t \/\/ take a reasonable averaged value for the noise on P- and N-side strips\n\t for(Int_t j=0; j<768; j++) {\n\t calib->AddNoiseP(j,1000.);\n\t calib->AddNoiseN(j,1000.);\n\t }\n\t calib_array.AddAt(calib,i);\n\t}\n\t\/\/-----------------------------------------\n\t\/\/---------------------------------------\n\t\/\/ in case some module was not calibrated!\n\tfor(Int_t i=0; i<fgkNumberOfSSD; i++) {\n\t AliITSBadChannelsSSD *badch = new AliITSBadChannelsSSD();\n\t badch->SetMod((UShort_t) i+500);\n\t badch_array.AddAt(badch,i);\n\t}\n\t\/\/-----------------------------------------\n\t\n\t\/\/---------------------------------------\n\t\/\/ in case some module was not calibrated!\n\tfor(Int_t i=0; i<fgkNumberOfSSD; i++) {\n\t AliITSPedestalSSD *pedel = new AliITSPedestalSSD();\n\t pedel->SetMod((UShort_t) i+500);\n\t pedel->SetNPedestalP(768);\n\t pedel->SetNPedestalN(768);\n\t for(Int_t j=0; j<768; j++) {\n\t pedel->AddPedestalP(j,0.);\n\t pedel->AddPedestalN(j,0.);\n\t }\n\t ped_array.AddAt(pedel,i);\n\t}\n\t\/\/-----------------------------------------\n\t\n\t\n\t\n\t\/\/ expect to iterate 3 times (LDC0, LDC1, LDC2)\n\twhile ( (ok = (TObjString*) next()) ) { \n\t \n\t TString key = ok->String();\n\t \n\t TString fileName = GetFile(kDAQ, \"CALIBRATION\", key.Data());\n\t if (fileName.Length() > 0) {\n\t \n\t Log(Form(\"Got the file %s, now we can extract some values.\", fileName.Data()));\n\t \n\t TFile *f = new TFile(fileName.Data());\n\t if(!f || !f->IsOpen()){\n\t \tLog(\"Error opening file!\");\n\t\tdelete list;\n\t\treturn 2;\n\t }\n\t \n\t TObjArray *cal; \n\t f->GetObject(\"Noise;1\", cal); \n\t if(!cal) {\n\t \tLog(\"File does not contain expected data for the noise!\");\n\t\tdelete list;\n\t\treturn 3;\n\t }\t \n\n\t Int_t nmod = cal->GetEntries();\n\t Log(Form(\"\\n#Mod %d\", nmod ));\n\t for(Int_t mod=0; mod<nmod; mod++) {\n\t AliITSNoiseSSD *calib = (AliITSNoiseSSD*) cal->At(mod);\n\t Log(Form(\"\\nModId %d\", calib->GetMod() ));\n\t if((calib->GetMod()<500)||(calib->GetMod()>2198)) continue;\n\t calib_array.AddAt(calib,calib->GetMod()-500);\n\t }\n\n\t TObjArray *bad; \n\t f->GetObject(\"BadChannels;1\", bad); \n\t if(!bad) {\n\t \tLog(\"File does not contain expected data for bad channels !\");\n\t\tdelete list;\n\t\treturn 4;\n\t }\t \n\t nmod = bad->GetEntries();\n\t for(Int_t mod=0; mod<nmod; mod++) {\n\t AliITSBadChannelsSSD *badch = (AliITSBadChannelsSSD*) bad->At(mod);\n\t if((badch->GetMod()<500)||(badch->GetMod()>2198)) continue;\n\t badch_array.AddAt(badch,badch->GetMod()-500);\n\t }\n\n\t TObjArray *ped; \n\t f->GetObject(\"Pedestal;1\", ped); \n\t if(!ped) {\n\t \tLog(\"File does not contain expected data for the pedestals!\");\n\t\tdelete list;\n\t\treturn 5;\n\t }\t \n\t nmod = ped->GetEntries();\n\t for(Int_t mod=0; mod<nmod; mod++) {\n\t AliITSPedestalSSD *pedel = (AliITSPedestalSSD*) ped->At(mod);\n\t if((pedel->GetMod()<500)||(pedel->GetMod()>2198)) continue;\n\t ped_array.AddAt(pedel,pedel->GetMod()-500);\n\t }\n\n\t f->Close(); delete f;\t \n\t\t\n\t } else {\n\t \tLog(\"GetFile error!\");\n\t\tdelete list;\n\t\treturn 6;\n\t } \/\/ if filename\n\t} \/\/ end iteration over LDCs\n\t\n\tdelete list;\n } else {\n \t Log(\"GetFileSources error!\");\n\t if(list) delete list;\n\t return 7;\n } \/\/ if list\n \n \/\/Now we have to store the final CDB file\n AliCDBMetaData metaData;\n metaData.SetBeamPeriod(0);\n metaData.SetResponsible(\"Enrico Fragiacomo\");\n metaData.SetComment(\"Fills noise, pedestal and bad channels TObjArray\");\n \n if(!Store(\"Calib\", \"NoiseSSD\", &calib_array, &metaData, 0, 1)) {\n\tLog(\"no store\");\n return 1;\n } \n \n if(!Store(\"Calib\", \"BadChannelsSSD\", &badch_array, &metaData, 0, 1)) {\n\tLog(\"no store\");\n return 1;\n } \n \n if(!StoreReferenceData(\"Calib\",\"PedestalSSD\", &ped_array, &metaData)) {\n\tLog(\"no store\");\n\treturn 1;\n }\n\t \n } \/\/ end if pedestal run\n else {\n Log(\"Nothing to do\");\n return 0;\n }\n \n Log(\"Database updated\");\n return 0; \/\/ 0 means success\n\n}\n\n<commit_msg>new implementation of bad channel map (E. Fragiacomo)<commit_after>#include \"AliITSPreprocessorSSD.h\"\n \n#include \"AliCDBMetaData.h\"\n#include \"AliLog.h\"\n#include \"TFile.h\"\n\n#include <TTimeStamp.h>\n#include <TObjString.h>\n\n#include \"AliITSRawStreamSSD.h\"\n#include \"AliITSNoiseSSD.h\"\n#include \"AliITSPedestalSSD.h\"\n#include \"AliITSBadChannelsSSD.h\"\n#include <Riostream.h>\n\n\n\/\/\n\/\/ Author: Enrico Fragiacomo\n\/\/ Date: 13\/10\/2006\n\/\/ \n\/\/ SHUTTLE preprocessing class for SSD calibration files\n\n\/* $Id$ *\/\n\nconst Int_t AliITSPreprocessorSSD::fgkNumberOfSSD = 1698;\n\nClassImp(AliITSPreprocessorSSD)\n\n\/\/-----------------------------------------------------------------------\nAliITSPreprocessorSSD::AliITSPreprocessorSSD(AliShuttleInterface* shuttle) :\n AliPreprocessor(\"SSD\", shuttle)\n{\n \/\/ constructor\n\n AddRunType(\"ELECTRONICS_CALIBRATION_RUN\");\n AddRunType(\"PEDESTAL\");\n AddRunType(\"PHYSICS\");\n\n}\n\n\/\/\/______________________________________________________________________________________________\nvoid AliITSPreprocessorSSD::Initialize(Int_t run, UInt_t startTime,\n\tUInt_t endTime)\n{\n \n AliPreprocessor::Initialize(run, startTime, endTime);\n \n Log(Form(\"\\n\\tRun %d \\n\\tStartTime %s \\n\\tEndTime %s\", run,\n\t TTimeStamp(startTime).AsString(),\n\t TTimeStamp(endTime).AsString()));\n \n}\n\n\/\/______________________________________________________________________________________________\nUInt_t AliITSPreprocessorSSD::Process(TMap* \/*dcsAliasMap*\/)\n{\n\n \/\/ Note. To be modified: dcsAliasMap is not needed but I can not get rid\n \/\/ of it unless the base class AliPreprocessor is modified accordingly.\n\n TObjArray calib_array(fgkNumberOfSSD); \n TObjArray badch_array(fgkNumberOfSSD); \n TObjArray ped_array(fgkNumberOfSSD); \n \/\/Float_t noise=0, gain=0;\n \n TString runType = GetRunType();\n if(runType == \"ELECTRONICS_CALIBRATION_RUN\") {\n \n }\n else if(runType == \"PEDESTAL\") {\n\n TList* list = GetFileSources(kDAQ, \"CALIBRATION\");\n if (list && list->GetEntries() > 0)\n {\n\tLog(\"The following sources produced files with the id CALIBRATION\");\n\tlist->Print();\n\t\n\t\/\/ create iterator over list of LDCs (provides list of TObjString)\n\tTIter next(list);\n\tTObjString *ok;\n\t\n\t\/\/---------------------------------------\n\t\/\/ in case some module was not calibrated!\n\tfor(Int_t i=0; i<fgkNumberOfSSD; i++) {\n\t AliITSNoiseSSD *calib = new AliITSNoiseSSD();\n\t calib->SetMod((UShort_t) i+500);\n\t calib->SetNNoiseP(768);\n\t calib->SetNNoiseN(768);\n\t \/\/ take a reasonable averaged value for the noise on P- and N-side strips\n\t for(Int_t j=0; j<768; j++) {\n\t calib->AddNoiseP(j,1000.);\n\t calib->AddNoiseN(j,1000.);\n\t }\n\t calib_array.AddAt(calib,i);\n\t}\n\t\/\/-----------------------------------------\n\t\/\/---------------------------------------\n\t\/\/ in case some module was not calibrated!\n\tfor(Int_t i=0; i<fgkNumberOfSSD; i++) {\n\t AliITSBadChannelsSSD *badch = new AliITSBadChannelsSSD();\n\t badch->SetMod((UShort_t) i+500);\n\t badch->SetNBadPChannelsList(768);\n\t badch->SetNBadNChannelsList(768);\n\t badch_array.AddAt(badch,i);\n\t}\n\t\/\/-----------------------------------------\n\t\n\t\/\/---------------------------------------\n\t\/\/ in case some module was not calibrated!\n\tfor(Int_t i=0; i<fgkNumberOfSSD; i++) {\n\t AliITSPedestalSSD *pedel = new AliITSPedestalSSD();\n\t pedel->SetMod((UShort_t) i+500);\n\t pedel->SetNPedestalP(768);\n\t pedel->SetNPedestalN(768);\n\t for(Int_t j=0; j<768; j++) {\n\t pedel->AddPedestalP(j,0.);\n\t pedel->AddPedestalN(j,0.);\n\t }\n\t ped_array.AddAt(pedel,i);\n\t}\n\t\/\/-----------------------------------------\n\t\n\t\n\t\n\t\/\/ expect to iterate 3 times (LDC0, LDC1, LDC2)\n\twhile ( (ok = (TObjString*) next()) ) { \n\t \n\t TString key = ok->String();\n\t \n\t TString fileName = GetFile(kDAQ, \"CALIBRATION\", key.Data());\n\t if (fileName.Length() > 0) {\n\t \n\t Log(Form(\"Got the file %s, now we can extract some values.\", fileName.Data()));\n\t \n\t TFile *f = new TFile(fileName.Data());\n\t if(!f || !f->IsOpen()){\n\t \tLog(\"Error opening file!\");\n\t\tdelete list;\n\t\treturn 2;\n\t }\n\t \n\t TObjArray *cal; \n\t f->GetObject(\"Noise;1\", cal); \n\t if(!cal) {\n\t \tLog(\"File does not contain expected data for the noise!\");\n\t\tdelete list;\n\t\treturn 3;\n\t }\t \n\n\t Int_t nmod = cal->GetEntries();\n\t Log(Form(\"\\n#Mod %d\", nmod ));\n\t for(Int_t mod=0; mod<nmod; mod++) {\n\t AliITSNoiseSSD *calib = (AliITSNoiseSSD*) cal->At(mod);\n\t Log(Form(\"\\nModId %d\", calib->GetMod() ));\n\t if((calib->GetMod()<500)||(calib->GetMod()>2198)) continue;\n\t calib_array.AddAt(calib,calib->GetMod()-500);\n\t }\n\n\t TObjArray *bad; \n\t f->GetObject(\"BadChannels;1\", bad); \n\t if(!bad) {\n\t \tLog(\"File does not contain expected data for bad channels !\");\n\t\tdelete list;\n\t\treturn 4;\n\t }\t \n\t nmod = bad->GetEntries();\n\t for(Int_t mod=0; mod<nmod; mod++) {\n\t AliITSBadChannelsSSD *badch = (AliITSBadChannelsSSD*) bad->At(mod);\n\t if((badch->GetMod()<500)||(badch->GetMod()>2198)) continue;\n\t badch_array.AddAt(badch,badch->GetMod()-500);\n\t }\n\n\t TObjArray *ped; \n\t f->GetObject(\"Pedestal;1\", ped); \n\t if(!ped) {\n\t \tLog(\"File does not contain expected data for the pedestals!\");\n\t\tdelete list;\n\t\treturn 5;\n\t }\t \n\t nmod = ped->GetEntries();\n\t for(Int_t mod=0; mod<nmod; mod++) {\n\t AliITSPedestalSSD *pedel = (AliITSPedestalSSD*) ped->At(mod);\n\t if((pedel->GetMod()<500)||(pedel->GetMod()>2198)) continue;\n\t ped_array.AddAt(pedel,pedel->GetMod()-500);\n\t }\n\n\t f->Close(); delete f;\t \n\t\t\n\t } else {\n\t \tLog(\"GetFile error!\");\n\t\tdelete list;\n\t\treturn 6;\n\t } \/\/ if filename\n\t} \/\/ end iteration over LDCs\n\t\n\tdelete list;\n } else {\n \t Log(\"GetFileSources error!\");\n\t if(list) delete list;\n\t return 7;\n } \/\/ if list\n \n \/\/Now we have to store the final CDB file\n AliCDBMetaData metaData;\n metaData.SetBeamPeriod(0);\n metaData.SetResponsible(\"Enrico Fragiacomo\");\n metaData.SetComment(\"Fills noise, pedestal and bad channels TObjArray\");\n \n if(!Store(\"Calib\", \"NoiseSSD\", &calib_array, &metaData, 0, 1)) {\n\tLog(\"no store\");\n return 1;\n } \n \n if(!Store(\"Calib\", \"BadChannelsSSD\", &badch_array, &metaData, 0, 1)) {\n\tLog(\"no store\");\n return 1;\n } \n \n if(!StoreReferenceData(\"Calib\",\"PedestalSSD\", &ped_array, &metaData)) {\n\tLog(\"no store\");\n\treturn 1;\n }\n\t \n } \/\/ end if pedestal run\n else {\n Log(\"Nothing to do\");\n return 0;\n }\n \n Log(\"Database updated\");\n return 0; \/\/ 0 means success\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n \n#include <TROOT.h>\n#include <TSystem.h>\n#include <TInterpreter.h>\n#include <TChain.h>\n#include <TFile.h>\n#include <TList.h>\n\n#include \"AliAnalysisTaskJets.h\"\n#include \"AliAnalysisManager.h\"\n#include \"AliJetFinder.h\"\n#include \"AliJetHistos.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESD.h\"\n#include \"AliAODEvent.h\"\n#include \"AliAODHandler.h\"\n#include \"AliMCEventHandler.h\"\n#include \"AliESDInputHandler.h\"\n#include \"AliMCEvent.h\"\n#include \"AliStack.h\"\n\n\nClassImp(AliAnalysisTaskJets)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nAliAnalysisTaskJets::AliAnalysisTaskJets():\n AliAnalysisTaskSE(),\n fConfigFile(\"ConfigJetAnalysis.C\"), \n fNonStdBranch(\"\"), \n fJetFinder(0x0),\n fHistos(0x0),\n fListOfHistos(0x0)\n{\n \/\/ Default constructor\n}\n\nAliAnalysisTaskJets::AliAnalysisTaskJets(const char* name):\n AliAnalysisTaskSE(name),\n fConfigFile(\"ConfigJetAnalysis.C\"), \n fNonStdBranch(\"\"), \n fJetFinder(0x0),\n fHistos(0x0),\n fListOfHistos(0x0)\n{\n \/\/ Default constructor\n DefineOutput(1, TList::Class());\n}\n\nvoid AliAnalysisTaskJets::UserCreateOutputObjects()\n{\n\/\/ Create the output container\n\/\/\n if (fDebug > 1) printf(\"AnalysisTaskJets::CreateOutPutData() \\n\");\n\n\n if(fNonStdBranch.Length()==0){\n \/\/ Connec default AOD to jet finder\n fJetFinder->ConnectAOD(AODEvent());\n }\n else{\n \/\/ Create a new branch for jets...\n \/\/ how is this is reset cleared in the UserExec....\n \/\/ Can this be handled by the framework?\n TClonesArray *tca = new TClonesArray(\"AliAODJet\", 0);\n tca->SetName(fNonStdBranch);\n AddAODBranch(\"TClonesArray\",&tca);\n fJetFinder->ConnectAODNonStd(AODEvent(),fNonStdBranch.Data());\n }\n \/\/ Histograms\n OpenFile(1);\n fListOfHistos = new TList();\n fHistos = new AliJetHistos();\n fHistos->AddHistosToList(fListOfHistos);\n \n}\n\nvoid AliAnalysisTaskJets::Init()\n{\n \/\/ Initialization\n if (fDebug > 1) printf(\"AnalysisTaskJets::Init() \\n\");\n\n \/\/ Call configuration file\n gROOT->LoadMacro(fConfigFile);\n fJetFinder = (AliJetFinder*) gInterpreter->ProcessLine(\"ConfigJetAnalysis()\");\n \/\/ Initialise Jet Analysis\n fJetFinder->Init();\n \/\/ Write header information to local file\n fJetFinder->WriteHeaders();\n}\n\n \n\n\n\nvoid AliAnalysisTaskJets::UserExec(Option_t *\/*option*\/)\n{\n \/\/ Execute analysis for current event\n \/\/\n\n\n \/\/ Fill control histos\n TClonesArray* jarray = 0;\n if(fNonStdBranch.Length()==0){\n jarray = AODEvent()->GetJets();\n }\n else{\n jarray = dynamic_cast<TClonesArray*>(AODEvent()->FindListObject(fNonStdBranch.Data()));\n jarray->Delete(); \/\/ this is our responsibility, clear before filling again\n }\n\n fJetFinder->GetReader()->SetInputEvent(InputEvent(), AODEvent(), MCEvent());\n fJetFinder->ProcessEvent();\n\n fHistos->FillHistos(jarray);\n \/\/ Post the data\n PostData(1, fListOfHistos);\n}\n\nvoid AliAnalysisTaskJets::Terminate(Option_t *\/*option*\/)\n{\n\/\/ Terminate analysis\n\/\/\n if (fDebug > 1) printf(\"AnalysisJets: Terminate() \\n\");\n\/\/ if (fJetFinder) fJetFinder->FinishRun();\n}\n\n<commit_msg>Write the jet header information to the UserInfo of the output AOD<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n \n#include <TROOT.h>\n#include <TSystem.h>\n#include <TInterpreter.h>\n#include <TChain.h>\n#include <TFile.h>\n#include <TList.h>\n\n#include \"AliAnalysisTaskJets.h\"\n#include \"AliAnalysisManager.h\"\n#include \"AliJetFinder.h\"\n#include \"AliJetHeader.h\"\n#include \"AliJetHistos.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESD.h\"\n#include \"AliAODEvent.h\"\n#include \"AliAODHandler.h\"\n#include \"AliMCEventHandler.h\"\n#include \"AliESDInputHandler.h\"\n#include \"AliMCEvent.h\"\n#include \"AliStack.h\"\n\n\nClassImp(AliAnalysisTaskJets)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nAliAnalysisTaskJets::AliAnalysisTaskJets():\n AliAnalysisTaskSE(),\n fConfigFile(\"ConfigJetAnalysis.C\"), \n fNonStdBranch(\"\"), \n fJetFinder(0x0),\n fHistos(0x0),\n fListOfHistos(0x0)\n{\n \/\/ Default constructor\n}\n\nAliAnalysisTaskJets::AliAnalysisTaskJets(const char* name):\n AliAnalysisTaskSE(name),\n fConfigFile(\"ConfigJetAnalysis.C\"), \n fNonStdBranch(\"\"), \n fJetFinder(0x0),\n fHistos(0x0),\n fListOfHistos(0x0)\n{\n \/\/ Default constructor\n DefineOutput(1, TList::Class());\n}\n\nvoid AliAnalysisTaskJets::UserCreateOutputObjects()\n{\n\/\/ Create the output container\n\/\/\n if (fDebug > 1) printf(\"AnalysisTaskJets::CreateOutPutData() \\n\");\n\n \n\n if(fNonStdBranch.Length()==0){\n \/\/ Connec default AOD to jet finder\n fJetFinder->ConnectAOD(AODEvent());\n }\n else{\n \/\/ Create a new branch for jets...\n \/\/ how is this is reset cleared in the UserExec....\n \/\/ Can this be handled by the framework?\n TClonesArray *tca = new TClonesArray(\"AliAODJet\", 0);\n tca->SetName(fNonStdBranch);\n AddAODBranch(\"TClonesArray\",&tca);\n fJetFinder->ConnectAODNonStd(AODEvent(),fNonStdBranch.Data());\n }\n \/\/ Histograms\n OpenFile(1);\n fListOfHistos = new TList();\n fHistos = new AliJetHistos();\n fHistos->AddHistosToList(fListOfHistos);\n \n \/\/ Add the JetFinderInforamtion to the Outputlist\n AliJetHeader *fH = fJetFinder->GetHeader();\n \/\/ Compose a characteristic output name\n \/\/ with the name of the output branch\n if(fH){\n if(fNonStdBranch.Length()==0){\n\tfH->SetName(\"AliJetHeader_jets\");\n }\n else{\n\tfH->SetName(Form(\"AliJetHeader_%s\",fNonStdBranch.Data()));\n }\n }\n OutputTree()->GetUserInfo()->Add(fH);\n}\n\nvoid AliAnalysisTaskJets::Init()\n{\n \/\/ Initialization\n if (fDebug > 1) printf(\"AnalysisTaskJets::Init() \\n\");\n\n \/\/ Call configuration file\n gROOT->LoadMacro(fConfigFile);\n fJetFinder = (AliJetFinder*) gInterpreter->ProcessLine(\"ConfigJetAnalysis()\");\n \/\/ Initialise Jet Analysis\n fJetFinder->Init();\n \/\/ Write header information to local file\n fJetFinder->WriteHeaders();\n}\n\n \n\n\n\nvoid AliAnalysisTaskJets::UserExec(Option_t *\/*option*\/)\n{\n \/\/ Execute analysis for current event\n \/\/\n\n\n \/\/ Fill control histos\n TClonesArray* jarray = 0;\n if(fNonStdBranch.Length()==0){\n jarray = AODEvent()->GetJets();\n }\n else{\n jarray = dynamic_cast<TClonesArray*>(AODEvent()->FindListObject(fNonStdBranch.Data()));\n jarray->Delete(); \/\/ this is our responsibility, clear before filling again\n }\n\n fJetFinder->GetReader()->SetInputEvent(InputEvent(), AODEvent(), MCEvent());\n fJetFinder->ProcessEvent();\n\n fHistos->FillHistos(jarray);\n \/\/ Post the data\n PostData(1, fListOfHistos);\n}\n\nvoid AliAnalysisTaskJets::Terminate(Option_t *\/*option*\/)\n{\n\/\/ Terminate analysis\n\/\/\n if (fDebug > 1) printf(\"AnalysisJets: Terminate() \\n\");\n\/\/ if (fJetFinder) fJetFinder->FinishRun();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n *\n * Mantis_Camera_Focus.cpp\n * Author: Bryan D. Maione\n *\n * This script enables the focusing of all the Mcams in a Mantis system with either\n * autofocus, or assisted manual focus.\n *\n *****************************************************************************\/\n \/* gcc -std=c++11 -o Mantis_Camera_Focus Mantis_Camera_Focus.cpp -lMantisAPI -lpthread -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lm -lstdc++\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <math.h>\n#include <sstream>\n#include <mutex>\n#include <utility>\n\n#include \"opencv2\/core\/mat.hpp\"\n#include \"opencv2\/core\/utility.hpp\"\n#include \"opencv2\/imgproc.hpp\"\n#include \"opencv2\/imgcodecs.hpp\"\n#include \"opencv2\/highgui.hpp\"\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <iostream>\n\n#include \"mantis\/MantisAPI.h\"\nconst int portbase = 13000;\nusing namespace cv;\nusing namespace std;\n\n\nvoid newMCamCallback(MICRO_CAMERA mcam, void* data)\n{\n static int mcamCounter = 0;\n MICRO_CAMERA* mcamList = (MICRO_CAMERA*) data;\n mcamList[mcamCounter++] = mcam;\n}\n\n\/**\n * \\brief Function to handle recieving microcamera frames that just \n * prints the mcam ID and timestamp of the received frame\n **\/\n \npair<double,Mat> calculateFocusMetric(Mat img){\n Mat edge;\n int edgeThresh = 100;\n int imgsize = img.rows*img.cols;\n Canny(img, edge, edgeThresh, edgeThresh*2, 3);\n double metric = cv::sum( edge )[0]\/imgsize;\n return make_pair(metric, edge);\n}\n\nbool processing = false;\ndouble metric = 0;\n\nvoid mcamFrameCallback(FRAME frame, void* data)\n{\n \n if (!processing && frame.m_metadata.m_height == 1080 \/*frame.m_metadata.m_camId == mcamlist[mcamnum]*\/){\n processing = true;\n \/\/ cout << \"Rendering Frame\" << \"\\n\";\n int imgsize = frame.m_metadata.m_size;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)frame.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n pair<double,Mat> output;\n output = calculateFocusMetric(loaded);\n Mat edges = output.second;\n metric = output.first;\n cvtColor(edges, edges, CV_GRAY2BGR);\n addWeighted(loaded , 0.5, edges, 0.5, 0.0, loaded);\n loaded += edges;\n imshow(\"Image\",loaded);\n waitKey(50);\n processing = false;\n }\n}\n\n\/**\n * \\ Function that computes the focus metric from an image\n **\/\n\n\n\nvoid printHelp()\n{\n printf(\"McamStream Demo Application\\n\");\n printf(\"Usage:\\n\");\n printf(\"\\t-c FILE Host file for microcameras (default sync.cfg) \\n\");\n printf(\"\\t-port <port> port connect to (default 9999)\\n\\n\");\n}\n\nint getIpsFromSyncFile(char fileName[])\n{\n\n \/\/ sleep(5);\n printf(\"i think the filename is %s \\n\",fileName);\n \/\/ fileName = \"sync.cfg\"; \/* should check that argc > 1 *\/\n FILE* file = fopen(fileName, \"r\"); \/* should check the result *\/\n char line[256];\n int d;\n int currentCam=0;\n int currentChar=0;\n int readingIP=0;\n char ip[10][24];\n memset( ip, '\\0', sizeof(ip) -1 );\n int numIps;\n int port = 9999;\n printf(\"in readsync now \\n\");\n while (fgets(line, sizeof(line), file)) {\n \/* note that fgets don't strip the terminating \\n, checking its\n presence would allow to handle lines longer that sizeof(line) *\/\n printf(\"%s\", line); \n\n \tfor(d=0;d<strlen(line);d++) {\n \t\t\t\t\t\n\t\tif(line[d] == ':'){\n\t\t\t\/\/printf(\"I found the colon \\n\");\n\t\t\treadingIP=0;\n\t\t}\n\t\tif(readingIP == 1){\n\t\t\tip[currentCam][currentChar]=line[d];\n\t\t\tcurrentChar++;\n\t\t}\n\t\tif(line[d] == '@'){\n \t \t\t\/\/printf(\"I found the ampersand \\n\");\n\t\t\treadingIP=1;\n\t\t}\n\n \t}\n\tcurrentCam++;\n\tcurrentChar=0;\n\n\n }\n \/* may check feof here to make a difference between eof and io failure -- network\n timeout for instance *\/\n numIps=currentCam;\n for( int ii=0; ii<numIps; ii++){\n \/* Connect directly to the Tegra hosting the microcamera.\n * If the IP\/port of the desired microcamera is unknown, it\n * can be found using the getCameraMcamList method shown in \n * the MantisGetFrames example, which returns MICRO_CAMERA \n * structs for each microcamera in a Mantis system. These \n * structs contain the IP\/port of the Tegras which host them *\/\n\tprintf(\"About to connect to ip %s on port %d \\n\", ip[ii],port);\n mCamConnect(ip[ii], port);\n\tprintf(\"Connected \\n\");\n\n\t}\n\n fclose(file);\nreturn numIps; }\n\nvoid autofocusMcam(MICRO_CAMERA automcam){\n int step = 100; \/\/Doing a focus sweep with 100 step increments\n int numiter = 2200\/step;\n double metricprev = 0;\n double localbestmetric = 0;\n double globalbestmetric= 0;\n int globalbestpos = 0;\n int finalbestpos = 0;\n bool stopflag = false;\n \/\/Bring to near focus\n setMCamFocusNear(automcam, 0);\n sleep(2);\n \/* Start the focus sweep for each micro camera connected to this tegra*\/\n for ( int i = 0; i <= numiter-1; i++ ){\n cout << \"Current Position: \"+to_string(i*step) << \"\\n\";\n FRAME frame = grabMCamFrame(portbase, 1.0 );\n int imgsize = frame.m_metadata.m_size;\n \/\/size_t stepcv=CV_AUTO_STEP;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)frame.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n \/* Calculate the focus metric from the image*\/\n metric = calculateFocusMetric(loaded).first;\n cout << \"Current metric value: \"+to_string(metric) << \"\\n\";\n setMCamFocusFar(automcam, step);\n sleep(2);\n \/* If the metric increased update the best value and position *\/\n if ( metric > metricprev){\n cout << \"metric value increased\" << \"\\n\";\n localbestmetric = metric;\n \/* If the current metric is the best we've seen yet, update as current best*\/\n if ( localbestmetric > globalbestmetric){\n cout << \"Global best updated\" << \"\\n\";\n globalbestmetric = localbestmetric;\n globalbestpos = i+1; \n }\n } \n metricprev = metric; \n }\/\/end coarse sweep\n \n \/* Bring each Mcam to 100 steps before best focus position*\/\n int initpos = 2200;\n int nstep = initpos - globalbestpos*step;\n setMCamFocusNear(automcam, nstep);\n \/*Recalculate the metric *\/\n FRAME frame = grabMCamFrame(portbase, 1.0 );\n int imgsize = frame.m_metadata.m_size;\n \/\/size_t step=CV_AUTO_STEP;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)frame.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n \/* Calculate the focus metric from the image*\/\n metricprev = calculateFocusMetric(loaded).first;\n \/*DO A FINE FOCUS SWEEP*\/\n for (int i=0; i<20; i++){\n if (!stopflag){\n int stepfine = 10;\n setMCamFocusNear(automcam, stepfine);\n }\n FRAME frame = grabMCamFrame(portbase, 1.0 );\n int imgsize = frame.m_metadata.m_size;\n \/\/size_t step=CV_AUTO_STEP;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)frame.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n \/* Calculate the focus metric from the image*\/\n metric = calculateFocusMetric(loaded).first;\n \n if (metric>=globalbestmetric && metricprev>=metric){\n \/* Step back 10 steps stop focusing this camera *\/\n cout << \"Best focus acheived\" << \"\\n\";\n setMCamFocusFar(automcam, 10);\n stopflag=true;\n }\n metricprev = metric;\n }\n \n}\n \nint main(int argc, char* argv[]){\n \n \/\/Parse arguments\n int argCount = 0;\n char* hostfile = \"sync.cfg\";\n \/\/std::string clipfile = DEFAULT_CLIPFILE;\n for( int i = 1; i < argc; i++ ){\n if( !strcmp( argv[i], \"-c\" ) ){\n argCount++;\n i++;\n if( i > argc ){\n std::cout << \"-c option must specify a directory\"\n << std::endl;\n printHelp();\n exit(1);\n }\n hostfile=argv[i];\n std::cout << \"using hostfile: \" << hostfile << std::endl;\n } else if( !strcmp( argv[i], \"-p\" ) ){\n argCount++;\n i++;\n if( i > argc ){\n std::cout << \"-p option must specify an image port\"\n << std::endl;\n printHelp();\n exit(1);\n }\n \/\/imagePort = std::stoi(argv[1]);\n } else if( !strcmp( argv[i], \"-h\" ) ){\n printHelp();\n exit(0);\n }else {\n printHelp();\n exit(0);\n }\n }\n \n \/**************** Camera Initialization *****************\/ \n \/********************************************************\/\n \/* start stream *\/\n getIpsFromSyncFile(hostfile);\n \/* get cameras from API *\/\n int numMCams = getNumberOfMCams();\n printf(\"API reported that there are %d microcameras available\\n\", numMCams);\n MICRO_CAMERA mcamList[numMCams];\n \/* create new microcamera callback struct *\/\n NEW_MICRO_CAMERA_CALLBACK mcamCB;\n mcamCB.f = newMCamCallback;\n mcamCB.data = mcamList;\n\n \/* call setNewMCamCallback; this function sets a callback that is\n * triggered each time a new microcamera is discovered by the API,\n * and also calls the callback function for each microcamera that\n * has already been discovered at the time of setting the callback *\/\n setNewMCamCallback(mcamCB);\n\n\n \/* Next we set a callback function to receive the stream of frames\n * from the desired microcamera *\/\n MICRO_CAMERA_FRAME_CALLBACK frameCB;\n frameCB.f = mcamFrameCallback;\n frameCB.data = NULL;\n setMCamFrameCallback(frameCB);\n \/\/MICRO_CAMERA myMCam = mcamList[0];\n \n\n \/* now if we check our list, we should see a populated list\n * of MICRO_CAMERA objects *\/\n initMCamFrameReceiver( portbase, 1 );\n \/*for( int i = 0; i < numMCams; i++ ){\n \n printf(\"Found mcam with ID %u\\n\", mcamList[i].mcamID);\n \/\/ Star the stream for each Mcam in the list\n if( !startMCamStream(mcamList[i], portbase) ){\n printf(\"Failed to start streaming mcam %u\\n\", mcamList[i].mcamID);\n exit(0);\n }\n }*\/\n \n \/* We only want to stream HD frame *\/\n \/* for( int i = 0; i < numMCams; i++ ){\n \tsetMCamStreamFilter(mcamList[i], portbase, 2);\n }*\/\n \/*************************************************************\/\n \/*************************************************************\/\n \n \/* Start a loop of polling the keyboard to determine action*\/\n int stepsize = 100;\n int mcamnum = 0;\n if( !startMCamStream(mcamList[mcamnum], portbase) ){\n printf(\"Failed to start streaming mcam %u\\n\", mcamList[mcamnum].mcamID);\n exit(0);\n }\n while (true){\n \/*FRAME image = grabMCamFrame(portbase+mcamnum, 1.0 );\n int imgsize = image.m_metadata.m_size;\n \n size_t step=CV_AUTO_STEP;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)image.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n pair<double,Mat> output;\n output = calculateFocusMetric(loaded);\n \/\/Mat edges = output.second;\n \/\/cvtColor(edges, edges, CV_GRAY2BGR);\n \/\/addWeighted(loaded , 0.5, edges, 0.5, 0.0, loaded);\n \/\/loaded += edges;*\/\n\n\t\n\n cout << \"Current Metric Value:\"+to_string(metric) << \"\\n\";\n\n \n \/\/imshow(\"Image\", loaded);\n \/\/waitKey(1000);\n char input;\n cout << \"a = auto i=In o=Out s=Step n=next camera q=Quit: \";\n cin >> input;\n if (input== 'i'){\n setMCamFocusFar(mcamList[mcamnum], stepsize);\n sleep(1);\n }\n else if (input== 'o'){\n setMCamFocusNear(mcamList[mcamnum], stepsize);\n sleep(1);\n }\n else if (input== 's'){\n int newstepsize;\n cout << \"Enter new step size: \";\n cin >> newstepsize;\n stepsize = newstepsize;\n }\n else if (input== 'q'){\n\t\tif (!stopMCamStream(mcamList[mcamnum], portbase)){ \n\t\tprintf(\"unable to stop stream\\n\"); \n\t\t}\n break;\n }\n else if (input== 'a'){\n destroyAllWindows();\n cout << \"Autofocusing Current Mcam\" << \"\\n\";\n autofocusMcam(mcamList[mcamnum]);\n }\n else if (input== 'n'){\n if (mcamnum < numMCams-1){\n\t\t if (!stopMCamStream(mcamList[mcamnum], portbase)){ \n \t\t printf(\"unable to stop stream\\n\"); \n\t\t } \n\t\t mcamnum++; \n\t\t if( !startMCamStream(mcamList[mcamnum], portbase) ){\n\t\t printf(\"Failed to start streaming mcam %u\\n\", mcamList[mcamnum].mcamID);\n\t\t exit(0);\n\t\t }\n cout << \"Switched Mcam\" << \"\\n\";\n }\n else{\n if (!stopMCamStream(mcamList[mcamnum], portbase)){ \n \t\t printf(\"unable to stop stream\\n\"); \n\t\t } \n mcamnum=0;\n if( !startMCamStream(mcamList[mcamnum], portbase) ){\n\t\t printf(\"Failed to start streaming mcam %u\\n\", mcamList[mcamnum].mcamID);\n\t\t exit(0);\n\t\t }\n cout << \"Switched Mcam\" << \"\\n\";\n }\n }\n else{\n ; \/\/ Do nothing\n }\n \n }\n}\n\n\n\n<commit_msg>Added ability to go to previous cameras, closed mcamFrameReceiver on exit, and added sleeps between stopping and starting streams<commit_after>\/******************************************************************************\n *\n * Mantis_Camera_Focus.cpp\n * Author: Bryan D. Maione\n *\n * This script enables the focusing of all the Mcams in a Mantis system with either\n * autofocus, or assisted manual focus.\n *\n *****************************************************************************\/\n \/* gcc -std=c++11 -o Mantis_Camera_Focus Mantis_Camera_Focus.cpp -lMantisAPI -lpthread -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lm -lstdc++\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <math.h>\n#include <sstream>\n#include <mutex>\n#include <utility>\n\n#include \"opencv2\/core\/mat.hpp\"\n#include \"opencv2\/core\/utility.hpp\"\n#include \"opencv2\/imgproc.hpp\"\n#include \"opencv2\/imgcodecs.hpp\"\n#include \"opencv2\/highgui.hpp\"\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <iostream>\n\n#include \"mantis\/MantisAPI.h\"\nconst int portbase = 13000;\nusing namespace cv;\nusing namespace std;\n\n\nvoid newMCamCallback(MICRO_CAMERA mcam, void* data)\n{\n static int mcamCounter = 0;\n MICRO_CAMERA* mcamList = (MICRO_CAMERA*) data;\n mcamList[mcamCounter++] = mcam;\n}\n\n\/**\n * \\brief Function to handle recieving microcamera frames that just \n * prints the mcam ID and timestamp of the received frame\n **\/\n \npair<double,Mat> calculateFocusMetric(Mat img){\n Mat edge;\n int edgeThresh = 100;\n int imgsize = img.rows*img.cols;\n Canny(img, edge, edgeThresh, edgeThresh*2, 3);\n double metric = cv::sum( edge )[0]\/imgsize;\n return make_pair(metric, edge);\n}\n\nbool processing = false;\ndouble metric = 0;\n\nvoid mcamFrameCallback(FRAME frame, void* data)\n{\n \n if (!processing && frame.m_metadata.m_height == 1080 \/*frame.m_metadata.m_camId == mcamlist[mcamnum]*\/){\n processing = true;\n \/\/ cout << \"Rendering Frame\" << \"\\n\";\n int imgsize = frame.m_metadata.m_size;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)frame.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n pair<double,Mat> output;\n output = calculateFocusMetric(loaded);\n Mat edges = output.second;\n metric = output.first;\n cvtColor(edges, edges, CV_GRAY2BGR);\n addWeighted(loaded , 0.5, edges, 0.5, 0.0, loaded);\n loaded += edges;\n imshow(\"Image\",loaded);\n waitKey(50);\n processing = false;\n }\n}\n\n\/**\n * \\ Function that computes the focus metric from an image\n **\/\n\n\n\nvoid printHelp()\n{\n printf(\"McamStream Demo Application\\n\");\n printf(\"Usage:\\n\");\n printf(\"\\t-c FILE Host file for microcameras (default sync.cfg) \\n\");\n printf(\"\\t-port <port> port connect to (default 9999)\\n\\n\");\n}\n\nint getIpsFromSyncFile(char fileName[])\n{\n\n \/\/ sleep(5);\n printf(\"i think the filename is %s \\n\",fileName);\n \/\/ fileName = \"sync.cfg\"; \/* should check that argc > 1 *\/\n FILE* file = fopen(fileName, \"r\"); \/* should check the result *\/\n char line[256];\n int d;\n int currentCam=0;\n int currentChar=0;\n int readingIP=0;\n char ip[10][24];\n memset( ip, '\\0', sizeof(ip) -1 );\n int numIps;\n int port = 9999;\n printf(\"in readsync now \\n\");\n while (fgets(line, sizeof(line), file)) {\n \/* note that fgets don't strip the terminating \\n, checking its\n presence would allow to handle lines longer that sizeof(line) *\/\n printf(\"%s\", line); \n\n \tfor(d=0;d<strlen(line);d++) {\n \t\t\t\t\t\n\t\tif(line[d] == ':'){\n\t\t\t\/\/printf(\"I found the colon \\n\");\n\t\t\treadingIP=0;\n\t\t}\n\t\tif(readingIP == 1){\n\t\t\tip[currentCam][currentChar]=line[d];\n\t\t\tcurrentChar++;\n\t\t}\n\t\tif(line[d] == '@'){\n \t \t\t\/\/printf(\"I found the ampersand \\n\");\n\t\t\treadingIP=1;\n\t\t}\n\n \t}\n\tcurrentCam++;\n\tcurrentChar=0;\n\n\n }\n \/* may check feof here to make a difference between eof and io failure -- network\n timeout for instance *\/\n numIps=currentCam;\n for( int ii=0; ii<numIps; ii++){\n \/* Connect directly to the Tegra hosting the microcamera.\n * If the IP\/port of the desired microcamera is unknown, it\n * can be found using the getCameraMcamList method shown in \n * the MantisGetFrames example, which returns MICRO_CAMERA \n * structs for each microcamera in a Mantis system. These \n * structs contain the IP\/port of the Tegras which host them *\/\n\tprintf(\"About to connect to ip %s on port %d \\n\", ip[ii],port);\n mCamConnect(ip[ii], port);\n\tprintf(\"Connected \\n\");\n\n\t}\n\n fclose(file);\nreturn numIps; }\n\nvoid autofocusMcam(MICRO_CAMERA automcam){\n int step = 100; \/\/Doing a focus sweep with 100 step increments\n int numiter = 2200\/step;\n double metricprev = 0;\n double localbestmetric = 0;\n double globalbestmetric= 0;\n int globalbestpos = 0;\n int finalbestpos = 0;\n bool stopflag = false;\n \/\/Bring to near focus\n setMCamFocusNear(automcam, 0);\n sleep(2);\n \/* Start the focus sweep for each micro camera connected to this tegra*\/\n for ( int i = 0; i <= numiter-1; i++ ){\n cout << \"Current Position: \"+to_string(i*step) << \"\\n\";\n FRAME frame = grabMCamFrame(portbase, 1.0 );\n int imgsize = frame.m_metadata.m_size;\n \/\/size_t stepcv=CV_AUTO_STEP;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)frame.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n \/* Calculate the focus metric from the image*\/\n metric = calculateFocusMetric(loaded).first;\n cout << \"Current metric value: \"+to_string(metric) << \"\\n\";\n setMCamFocusFar(automcam, step);\n sleep(2);\n \/* If the metric increased update the best value and position *\/\n if ( metric > metricprev){\n cout << \"metric value increased\" << \"\\n\";\n localbestmetric = metric;\n \/* If the current metric is the best we've seen yet, update as current best*\/\n if ( localbestmetric > globalbestmetric){\n cout << \"Global best updated\" << \"\\n\";\n globalbestmetric = localbestmetric;\n globalbestpos = i+1; \n }\n } \n metricprev = metric; \n }\/\/end coarse sweep\n \n \/* Bring each Mcam to 100 steps before best focus position*\/\n int initpos = 2200;\n int nstep = initpos - globalbestpos*step;\n setMCamFocusNear(automcam, nstep);\n \/*Recalculate the metric *\/\n FRAME frame = grabMCamFrame(portbase, 1.0 );\n int imgsize = frame.m_metadata.m_size;\n \/\/size_t step=CV_AUTO_STEP;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)frame.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n \/* Calculate the focus metric from the image*\/\n metricprev = calculateFocusMetric(loaded).first;\n \/*DO A FINE FOCUS SWEEP*\/\n for (int i=0; i<20; i++){\n if (!stopflag){\n int stepfine = 10;\n setMCamFocusNear(automcam, stepfine);\n }\n FRAME frame = grabMCamFrame(portbase, 1.0 );\n int imgsize = frame.m_metadata.m_size;\n \/\/size_t step=CV_AUTO_STEP;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)frame.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n \/* Calculate the focus metric from the image*\/\n metric = calculateFocusMetric(loaded).first;\n \n if (metric>=globalbestmetric && metricprev>=metric){\n \/* Step back 10 steps stop focusing this camera *\/\n cout << \"Best focus acheived\" << \"\\n\";\n setMCamFocusFar(automcam, 10);\n stopflag=true;\n }\n metricprev = metric;\n }\n \n}\n \nint main(int argc, char* argv[]){\n \n \/\/Parse arguments\n int argCount = 0;\n char* hostfile = \"sync.cfg\";\n \/\/std::string clipfile = DEFAULT_CLIPFILE;\n for( int i = 1; i < argc; i++ ){\n if( !strcmp( argv[i], \"-c\" ) ){\n argCount++;\n i++;\n if( i > argc ){\n std::cout << \"-c option must specify a directory\"\n << std::endl;\n printHelp();\n exit(1);\n }\n hostfile=argv[i];\n std::cout << \"using hostfile: \" << hostfile << std::endl;\n } else if( !strcmp( argv[i], \"-p\" ) ){\n argCount++;\n i++;\n if( i > argc ){\n std::cout << \"-p option must specify an image port\"\n << std::endl;\n printHelp();\n exit(1);\n }\n \/\/imagePort = std::stoi(argv[1]);\n } else if( !strcmp( argv[i], \"-h\" ) ){\n printHelp();\n exit(0);\n }else {\n printHelp();\n exit(0);\n }\n }\n \n \/**************** Camera Initialization *****************\/ \n \/********************************************************\/\n \/* start stream *\/\n getIpsFromSyncFile(hostfile);\n \/* get cameras from API *\/\n int numMCams = getNumberOfMCams();\n printf(\"API reported that there are %d microcameras available\\n\", numMCams);\n MICRO_CAMERA mcamList[numMCams];\n \/* create new microcamera callback struct *\/\n NEW_MICRO_CAMERA_CALLBACK mcamCB;\n mcamCB.f = newMCamCallback;\n mcamCB.data = mcamList;\n\n \/* call setNewMCamCallback; this function sets a callback that is\n * triggered each time a new microcamera is discovered by the API,\n * and also calls the callback function for each microcamera that\n * has already been discovered at the time of setting the callback *\/\n setNewMCamCallback(mcamCB);\n\n\n \/* Next we set a callback function to receive the stream of frames\n * from the desired microcamera *\/\n MICRO_CAMERA_FRAME_CALLBACK frameCB;\n frameCB.f = mcamFrameCallback;\n frameCB.data = NULL;\n setMCamFrameCallback(frameCB);\n \/\/MICRO_CAMERA myMCam = mcamList[0];\n \n\n \/* now if we check our list, we should see a populated list\n * of MICRO_CAMERA objects *\/\n initMCamFrameReceiver( portbase, 1 );\n \/*for( int i = 0; i < numMCams; i++ ){\n \n printf(\"Found mcam with ID %u\\n\", mcamList[i].mcamID);\n \/\/ Star the stream for each Mcam in the list\n if( !startMCamStream(mcamList[i], portbase) ){\n printf(\"Failed to start streaming mcam %u\\n\", mcamList[i].mcamID);\n exit(0);\n }\n }*\/\n \n \/* We only want to stream HD frame *\/\n \/* for( int i = 0; i < numMCams; i++ ){\n \tsetMCamStreamFilter(mcamList[i], portbase, 2);\n }*\/\n \/*************************************************************\/\n \/*************************************************************\/\n \n \/* Start a loop of polling the keyboard to determine action*\/\n int stepsize = 100;\n int mcamnum = 0;\n if( !startMCamStream(mcamList[mcamnum], portbase) ){\n printf(\"Failed to start streaming mcam %u\\n\", mcamList[mcamnum].mcamID);\n exit(0);\n }\n while (true){\n \/*FRAME image = grabMCamFrame(portbase+mcamnum, 1.0 );\n int imgsize = image.m_metadata.m_size;\n \n size_t step=CV_AUTO_STEP;\n Mat rawdata = Mat(1, imgsize , CV_8UC1, (void *)image.m_image); \/\/compressed jpg data\n Mat loaded = imdecode(rawdata,1);\n if (loaded.data==NULL){\n cerr << \"Failed to decode data\" <<\"\\n\";\n }\n pair<double,Mat> output;\n output = calculateFocusMetric(loaded);\n \/\/Mat edges = output.second;\n \/\/cvtColor(edges, edges, CV_GRAY2BGR);\n \/\/addWeighted(loaded , 0.5, edges, 0.5, 0.0, loaded);\n \/\/loaded += edges;*\/\n\n\t\n\n cout << \"Current Metric Value:\"+to_string(metric) << \"\\n\";\n\n \n \/\/imshow(\"Image\", loaded);\n \/\/waitKey(1000);\n char input;\n cout << \"a = auto i=In o=Out s=Step n=next camera p= previous camera q=Quit: \";\n cin >> input;\n if (input== 'i'){\n setMCamFocusFar(mcamList[mcamnum], stepsize);\n sleep(1);\n }\n else if (input== 'o'){\n setMCamFocusNear(mcamList[mcamnum], stepsize);\n sleep(1);\n }\n else if (input== 's'){\n int newstepsize;\n cout << \"Enter new step size: \";\n cin >> newstepsize;\n stepsize = newstepsize;\n }\n else if (input== 'q'){\n\t\tif (!stopMCamStream(mcamList[mcamnum], portbase)){ \n\t\tprintf(\"unable to stop stream\\n\"); \n\t\t}\n\t\tcloseMCamFrameReceiver(portbase);\n break;\n }\n else if (input== 'a'){\n destroyAllWindows();\n cout << \"Autofocusing Current Mcam\" << \"\\n\";\n autofocusMcam(mcamList[mcamnum]);\n }\n else if (input== 'n' || input== 'p'){\n if (mcamnum < numMCams-1){\n\t\t if (!stopMCamStream(mcamList[mcamnum], portbase)){ \n \t\t printf(\"unable to stop stream\\n\"); \n\t\t }\n\t\t\tsleep(0.5); \n\t\t\tif (input == 'n') {\n\t\t\t mcamnum++; }\n\t\t\telse {\n\t\t\t\tmcamnum--;\n\t\t\t}\n\t\t\tif (mcamnum<0) {\n\t\t\t\tmcamnum=numMCams-1;\n\t\t\t} \n\t\t if( !startMCamStream(mcamList[mcamnum], portbase) ){\n\t\t printf(\"Failed to start streaming mcam %u\\n\", mcamList[mcamnum].mcamID);\n\t\t exit(0);\n\t\t }\n cout << \"Switched Mcam\" << \"\\n\";\n }\n else{\n if (!stopMCamStream(mcamList[mcamnum], portbase)){ \n \t\t printf(\"unable to stop stream\\n\"); \n\t\t } \n mcamnum=0;\n\t\tsleep(0.5); \n if( !startMCamStream(mcamList[mcamnum], portbase) ){\n\t\t printf(\"Failed to start streaming mcam %u\\n\", mcamList[mcamnum].mcamID);\n\t\t exit(0);\n\t\t }\n cout << \"Switched Mcam\" << \"\\n\";\n }\n }\n else{\n ; \/\/ Do nothing\n }\n \n }\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"chimera\/render\/scene\/Scene.hpp\"\n#include \"chimera\/core\/ScriptableEntity.hpp\"\n#include \"chimera\/core\/buffer\/VertexArray.hpp\"\n#include \"chimera\/core\/bullet\/Solid.hpp\"\n#include \"chimera\/core\/device\/MouseDevice.hpp\"\n#include \"chimera\/core\/partition\/BSPTree.hpp\"\n#include \"chimera\/core\/visible\/CameraControllerFPS.hpp\"\n#include \"chimera\/core\/visible\/CameraControllerOrbit.hpp\"\n#include \"chimera\/core\/visible\/Material.hpp\"\n#include \"chimera\/core\/visible\/Transform.hpp\"\n#include \"chimera\/render\/3d\/RenderCommand.hpp\"\n#include \"chimera\/render\/3d\/Renderable3D.hpp\"\n#include \"chimera\/render\/3d\/RenderableArray.hpp\"\n#include \"chimera\/render\/3d\/RenderableBsp.hpp\"\n#include \"chimera\/render\/3d\/RenderableParticles.hpp\"\n#include \"chimera\/render\/VertexData.hpp\"\n#include \"chimera\/render\/scene\/Components.hpp\"\n#include <SDL2\/SDL.h>\n\nnamespace Chimera {\n\nScene::Scene(Registry& r, StateStack& s)\n : stack(&s), registry(&r), activeCam(nullptr), origem(nullptr), shadowPass(nullptr), logRender(false) {}\n\nScene::~Scene() {\n if (shadowPass) {\n delete shadowPass;\n shadowPass = nullptr;\n }\n}\n\nRenderBuffer* Scene::initRB(const uint32_t& initW, const uint32_t& initH, const uint32_t& width, const uint32_t& height) {\n \/\/ Define o framebuffer de desenho\n Shader shader;\n std::unordered_map<GLenum, std::string> shadeData;\n shadeData[GL_FRAGMENT_SHADER] = \".\/assets\/shaders\/CanvasHMD.frag\";\n shadeData[GL_VERTEX_SHADER] = \".\/assets\/shaders\/CanvasHMD.vert\";\n ShaderManager::load(\"CanvasHMD\", shadeData, shader);\n\n FrameBufferSpecification fbSpec;\n fbSpec.attachments = {\n TexParam(TexFormat::RGBA, TexFormat::RGBA, TexFilter::LINEAR, TexWrap::CLAMP, TexDType::UNSIGNED_BYTE),\n \/\/ TexParam(TexFormat::RED_INTEGER, TexFormat::R32I, TexFilter::LINEAR, TexWrap::CLAMP_TO_EDGE, TexDType::UNSIGNED_BYTE),\n TexParam(TexFormat::DEPTH_COMPONENT, TexFormat::DEPTH_ATTACHMENT, TexFilter::NONE, TexWrap::NONE, TexDType::UNSIGNED_BYTE)};\n\n fbSpec.width = width;\n fbSpec.height = height;\n fbSpec.swapChainTarget = false;\n fbSpec.samples = 1;\n\n return new RenderBuffer(initW, initH, new FrameBuffer(fbSpec), shader);\n}\n\nvoid Scene::createRenderBuffer(const uint8_t& size, const uint32_t& width, const uint32_t& height) {\n\n for (auto rb : vRB) {\n delete rb;\n rb = nullptr;\n }\n\n vRB.clear();\n uint32_t halfHidth = width \/ 2;\n if (size == 2) {\n vRB.push_back(initRB(0, 0, halfHidth, height)); \/\/ left\n vRB.push_back(initRB(halfHidth, 0, halfHidth, height)); \/\/ right\n } else {\n vRB.push_back(initRB(0, 0, width, height)); \/\/ full only\n }\n}\n\nvoid Scene::onDeatach() {\n \/\/ destroy scripts\n registry->get().view<NativeScriptComponent>().each([=](auto entity, auto& nsc) {\n if (!nsc.instance) {\n nsc.instance->onDestroy();\n nsc.destroyScript(&nsc);\n }\n });\n}\n\nvoid Scene::onAttach() {\n\n \/\/ lista as tags nas entidades registradas\n registry->get().each([&](auto entityID) {\n Entity entity{entityID, registry};\n auto& tc = entity.getComponent<TagComponent>();\n SDL_Log(\"Tag: %s Id: %s\", tc.tag.c_str(), tc.id.c_str());\n\n \/\/ Se for um mesh inicializar componente (já que nao tenho classe de Mesh)\n if (entity.hasComponent<MeshComponent>()) {\n MeshComponent& mesh = entity.getComponent<MeshComponent>();\n\n \/\/ Inicializa Materiais\n if (entity.hasComponent<MaterialComponent>()) {\n MaterialComponent& material = entity.getComponent<MaterialComponent>();\n if (!material.material->isValid())\n material.material->init();\n } else {\n MaterialComponent& material = entity.addComponent<MaterialComponent>();\n material.material->setDefaultEffect();\n material.material->init();\n }\n\n \/\/ Se nja nao foi inicializado um Renderable3dComponent ao mesh\n if (!entity.hasComponent<Renderable3dComponent>()) { \/\/ FIXME: Depoin do BSP mudar o teste ja que todos serao criados aqui!!!\n\n Renderable3dComponent& rc = entity.addComponent<Renderable3dComponent>();\n\n if (mesh.type == MeshType::SIMPLE) {\n\n \/\/ Transforma Mesh em VertexData comprimindo-o\n std::vector<VertexData> renderData;\n vertexDataFromMesh(mesh.mesh, renderData);\n\n std::vector<uint32_t> index;\n std::vector<VertexData> vertexDataOut;\n vertexDataIndexCompile(renderData, vertexDataOut, index);\n\n \/\/ Create VAO, VBO and IBO\n VertexArray* vao = new VertexArray();\n vao->bind();\n\n VertexBuffer* vbo = new VertexBuffer(BufferType::STATIC);\n vbo->bind();\n\n BufferLayout layout;\n layout.Push<float>(3, false);\n layout.Push<float>(3, false);\n layout.Push<float>(2, false);\n\n vbo->setLayout(layout);\n vbo->setData(&vertexDataOut[0], vertexDataOut.size());\n vbo->unbind();\n vao->push(vbo);\n\n vao->unbind();\n\n glm::vec3 min, max, size;\n vertexDataIndexMinMaxSize(&vertexDataOut[0], vertexDataOut.size(), &index[0], index.size(), min, max, size);\n\n IndexBuffer* ibo = new IndexBuffer(&index[0], index.size());\n Renderable3D* r = new Renderable3D(vao, ibo, AABB(min, max));\n\n rc.renderable = r;\n } else if (mesh.type == MeshType::ARRAY) {\n\n std::vector<VertexData> renderData;\n vertexDataFromMesh(mesh.mesh, renderData);\n\n rc.renderable = new RenderableArray(mesh.vTrisIndex, renderData);\n\n } else if (mesh.type == MeshType::BSTREE) {\n\n Mesh meshFinal;\n meshReCompile(*mesh.mesh, meshFinal);\n\n \/\/ btree root, leafs, vertex\n BspTree bspTree;\n mesh.root = bspTree.create(&meshFinal, mesh.vTrisIndex);\n\n rc.renderable = new RenderableBsp(mesh.root, mesh.vTrisIndex, &meshFinal);\n }\n }\n\n if (entity.hasComponent<TransComponent>()) {\n glm::vec3 min, max, size;\n meshMinMaxSize(mesh.mesh, min, max, size);\n\n TransComponent& tc = entity.getComponent<TransComponent>();\n if (tc.solid) {\n Solid* solid = (Solid*)tc.trans;\n solid->init(size); \/\/ Cria rigidBody iniciaza transformacao e inicializa shape se ele nao existir\n }\n }\n }\n\n if (entity.hasComponent<EmitterComponent>()) {\n EmitterComponent& ec = entity.getComponent<EmitterComponent>();\n\n if (!entity.hasComponent<RenderableParticlesComponent>()) {\n\n RenderableParticlesComponent& particleSys = entity.addComponent<RenderableParticlesComponent>();\n particleSys.enable = true;\n RenderableParticles* p = new RenderableParticles();\n ParticleContainer* pc = ec.emitter->getContainer(0); \/\/ FIXME: melhorar!!!!\n p->setParticleContainer(pc);\n p->create();\n particleSys.renderable = p;\n this->pushEmitters(ec.emitter);\n }\n }\n\n if (entity.hasComponent<EyeView>()) {\n EyeView& ev = entity.getComponent<EyeView>();\n eyeView = &ev;\n }\n\n if (entity.hasComponent<CanvasComponent>()) {\n CanvasComponent& cc = entity.getComponent<CanvasComponent>();\n this->onViewportResize(cc.canvas->getWidth(), cc.canvas->getHeight());\n }\n });\n\n {\n \/\/ Registra Camera controllers EyeView deve ser localizado acima\n auto view1 = registry->get().view<CameraComponent>();\n for (auto entity : view1) {\n Entity e = Entity{entity, registry};\n\n auto& cc = e.getComponent<CameraComponent>();\n cc.eyeView = eyeView;\n if (cc.camKind == CamKind::FPS) {\n e.addComponent<NativeScriptComponent>().bind<CameraControllerFPS>(\"CameraController\");\n } else if (cc.camKind == CamKind::ORBIT) {\n e.addComponent<NativeScriptComponent>().bind<CameraControllerOrbit>(\"CameraController\");\n } else if (cc.camKind == CamKind::STATIC) {\n \/\/ e.addComponent<NativeScriptComponent>().bind<CameraController>(\"CameraController\");\n }\n }\n }\n\n {\n \/\/ initialize scripts\n registry->get().view<NativeScriptComponent>().each([=](auto entity, auto& nsc) {\n if (!nsc.instance) {\n nsc.instance = nsc.instantiateScript();\n nsc.instance->entity = Entity{entity, registry};\n nsc.instance->onCreate();\n }\n });\n }\n\n origem = new Transform(); \/\/ FIXME: coisa feia!!!!\n}\n\nCanvas* Scene::getCanvas() {\n CanvasComponent& cc = registry->findComponent<CanvasComponent>(\"main_screem\");\n return cc.canvas;\n}\n\nvoid Scene::onUpdate(const double& ts) {\n \/\/ update scripts (PhysicController aqui dentro!!!)\n registry->get().view<NativeScriptComponent>().each([=](auto entity, auto& nsc) {\n if (nsc.instance)\n nsc.instance->onUpdate(ts);\n });\n\n for (auto emissor : emitters)\n emissor->recycleLife(ts);\n}\n\nvoid Scene::onViewportResize(const uint32_t& width, const uint32_t& height) {\n\n auto view = registry->get().view<CameraComponent>();\n for (auto entity : view) {\n\n auto& cameraComponent = view.get<CameraComponent>(entity);\n if (!cameraComponent.fixedAspectRatio) {\n cameraComponent.camera->setViewportSize(width, height);\n\n \/\/ carrega camera defalt da cena\n if (cameraComponent.primary == true) {\n createRenderBuffer(eyeView->size(), width, height);\n activeCam = cameraComponent.camera;\n }\n }\n }\n}\n\nbool Scene::onEvent(const SDL_Event& event) {\n switch (event.type) {\n case SDL_WINDOWEVENT: {\n switch (event.window.event) {\n case SDL_WINDOWEVENT_RESIZED: \/\/ aqui para camera e engine acerta a janela\n onViewportResize(event.window.data1, event.window.data2);\n break;\n }\n } break;\n case SDL_KEYDOWN: {\n switch (event.key.keysym.sym) {\n case SDLK_F9:\n logRender = !logRender;\n break;\n }\n } break;\n }\n return true;\n}\n\nvoid Scene::execEmitterPass(Camera* camera, IRenderer3d& renderer) {\n auto view = registry->get().view<RenderableParticlesComponent>();\n for (auto entity : view) {\n\n RenderableParticlesComponent& rc = view.get<RenderableParticlesComponent>(entity);\n IRenderable3d* renderable = rc.renderable;\n\n Entity e = {entity, registry};\n TransComponent& tc = e.getComponent<TransComponent>(); \/\/ FIXME: group this!!!\n Shader& sc = e.getComponent<Shader>();\n MaterialComponent& mc = e.getComponent<MaterialComponent>();\n\n RenderCommand command;\n command.camera = camera;\n command.eyeView = eyeView;\n command.logRender = logRender;\n command.transform = tc.trans->translateSrc(origem->getPosition());\n command.renderable = renderable;\n command.shader = sc;\n mc.material->bindMaterialInformation(command.uniforms, command.vTex);\n\n command.uniforms[\"model\"] = UValue(command.transform);\n\n renderable->submit(command, renderer);\n }\n}\n\nvoid Scene::execRenderPass(Camera* camera, IRenderer3d& renderer) {\n auto group = registry->get().group<Shader, MaterialComponent, TransComponent, Renderable3dComponent>();\n for (auto entity : group) {\n auto [sc, mc, tc, rc] = group.get<Shader, MaterialComponent, TransComponent, Renderable3dComponent>(entity);\n\n RenderCommand command;\n command.camera = camera;\n command.eyeView = eyeView;\n command.logRender = logRender;\n command.transform = tc.trans->translateSrc(origem->getPosition());\n command.renderable = rc.renderable;\n command.shader = sc;\n mc.material->bindMaterialInformation(command.uniforms, command.vTex);\n command.uniforms[\"model\"] = UValue(command.transform);\n rc.renderable->submit(command, renderer);\n }\n}\n\nvoid Scene::onRender() {\n\n Camera* camera = activeCam;\n\n if (logRender == true) {\n const glm::vec3& pos = camera->getPosition();\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Eye: %0.2f; %0.3f; %0.3f\", pos.x, pos.y, pos.z);\n }\n\n \/\/ render a shadows in framebuffer\n if (shadowPass)\n shadowPass->render(registry, camera, eyeView, renderBatch, origem, logRender);\n\n uint8_t count = 0;\n for (auto renderBuffer : vRB) {\n camera->setViewportSize(renderBuffer->getWidth(), renderBuffer->getHeight());\n eyeView->setIndex(count);\n count++;\n\n \/\/ used by all\n renderBatch.uQueue().insert(std::make_pair(\"projection\", UValue(camera->getProjection())));\n renderBatch.uQueue().insert(std::make_pair(\"view\", UValue(eyeView->getView())));\n\n \/\/ load shadows props to renderBatch\n if (shadowPass)\n shadowPass->setProp(camera->getPosition(), renderBatch);\n\n auto lightView = registry->get().view<LightComponent>();\n for (auto entity : lightView) {\n auto& lc = lightView.get<LightComponent>(entity);\n auto& tc = registry->get().get<TransComponent>(entity); \/\/ lightView.get<LightComponent>(entity);\n if (lc.global) \/\/ biding light prop\n lc.light->bindLight(renderBatch.uQueue(), tc.trans->getMatrix());\n }\n\n { \/\/ Render mesh\n renderBatch.begin(eyeView);\n this->execRenderPass(camera, renderBatch);\n\n renderBatch.end();\n renderBuffer->bind(); \/\/ we're not using the stencil buffer now\n\n renderBatch.flush(); \/\/ desenha aqui!!!!\n }\n\n if (emitters.size() > 0) {\n \/\/ inicializa state machine do opengl\n BinaryStateEnable depth(GL_DEPTH_TEST); \/\/ glEnable(GL_DEPTH_TEST);\/\/ Enable depth test\n BinaryStateEnable blender(GL_BLEND); \/\/ glEnable(GL_BLEND);\n DepthFuncSetter depthFunc(GL_LESS); \/\/ glDepthFunc(GL_LESS); \/\/ Accept fragment if it closer to the camera than the former one\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n renderBatch.begin(eyeView);\n this->execEmitterPass(camera, renderBatch);\n\n renderBatch.end();\n renderBatch.flush();\n }\n\n {\n \/\/ TODO: captura do entity no framebuffer da tela\n \/\/ \/\/ get val from color buffer (must be inside framebuffer renderer\n \/\/ glm::ivec2 pos = MouseDevice::getMove();\n \/\/ pos.y = viewportHeight - pos.y;\n \/\/ int val = renderBuffer->getFramBuffer()->readPixel(1, pos.x, pos.y);\n \/\/ SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"mouse(X: %d \/ Y: %d): %d\", pos.x, pos.y, val);\n }\n\n renderBuffer->unbind();\n renderBuffer->render();\n }\n}\n} \/\/ namespace Chimera<commit_msg>re-org scene<commit_after>#include \"chimera\/render\/scene\/Scene.hpp\"\n#include \"chimera\/core\/ScriptableEntity.hpp\"\n#include \"chimera\/core\/buffer\/VertexArray.hpp\"\n#include \"chimera\/core\/bullet\/Solid.hpp\"\n#include \"chimera\/core\/device\/MouseDevice.hpp\"\n#include \"chimera\/core\/partition\/BSPTree.hpp\"\n#include \"chimera\/core\/visible\/CameraControllerFPS.hpp\"\n#include \"chimera\/core\/visible\/CameraControllerOrbit.hpp\"\n#include \"chimera\/core\/visible\/Material.hpp\"\n#include \"chimera\/core\/visible\/Transform.hpp\"\n#include \"chimera\/render\/3d\/RenderCommand.hpp\"\n#include \"chimera\/render\/3d\/Renderable3D.hpp\"\n#include \"chimera\/render\/3d\/RenderableArray.hpp\"\n#include \"chimera\/render\/3d\/RenderableBsp.hpp\"\n#include \"chimera\/render\/3d\/RenderableParticles.hpp\"\n#include \"chimera\/render\/VertexData.hpp\"\n#include \"chimera\/render\/scene\/Components.hpp\"\n#include <SDL2\/SDL.h>\n\nnamespace Chimera {\n\nScene::Scene(Registry& r, StateStack& s)\n : stack(&s), registry(&r), activeCam(nullptr), origem(nullptr), shadowPass(nullptr), logRender(false) {}\n\nScene::~Scene() {\n if (shadowPass) {\n delete shadowPass;\n shadowPass = nullptr;\n }\n}\n\nRenderBuffer* Scene::initRB(const uint32_t& initW, const uint32_t& initH, const uint32_t& width, const uint32_t& height) {\n \/\/ Define o framebuffer de desenho\n Shader shader;\n std::unordered_map<GLenum, std::string> shadeData;\n shadeData[GL_FRAGMENT_SHADER] = \".\/assets\/shaders\/CanvasHMD.frag\";\n shadeData[GL_VERTEX_SHADER] = \".\/assets\/shaders\/CanvasHMD.vert\";\n ShaderManager::load(\"CanvasHMD\", shadeData, shader);\n\n FrameBufferSpecification fbSpec;\n fbSpec.attachments = {\n TexParam(TexFormat::RGBA, TexFormat::RGBA, TexFilter::LINEAR, TexWrap::CLAMP, TexDType::UNSIGNED_BYTE),\n \/\/ TexParam(TexFormat::RED_INTEGER, TexFormat::R32I, TexFilter::LINEAR, TexWrap::CLAMP_TO_EDGE, TexDType::UNSIGNED_BYTE),\n TexParam(TexFormat::DEPTH_COMPONENT, TexFormat::DEPTH_ATTACHMENT, TexFilter::NONE, TexWrap::NONE, TexDType::UNSIGNED_BYTE)};\n\n fbSpec.width = width;\n fbSpec.height = height;\n fbSpec.swapChainTarget = false;\n fbSpec.samples = 1;\n\n return new RenderBuffer(initW, initH, new FrameBuffer(fbSpec), shader);\n}\n\nvoid Scene::createRenderBuffer(const uint8_t& size, const uint32_t& width, const uint32_t& height) {\n\n for (auto rb : vRB) {\n delete rb;\n rb = nullptr;\n }\n\n vRB.clear();\n uint32_t halfHidth = width \/ 2;\n if (size == 2) {\n vRB.push_back(initRB(0, 0, halfHidth, height)); \/\/ left\n vRB.push_back(initRB(halfHidth, 0, halfHidth, height)); \/\/ right\n } else {\n vRB.push_back(initRB(0, 0, width, height)); \/\/ full only\n }\n}\n\nvoid Scene::onDeatach() {\n \/\/ destroy scripts\n registry->get().view<NativeScriptComponent>().each([=](auto entity, auto& nsc) {\n if (!nsc.instance) {\n nsc.instance->onDestroy();\n nsc.destroyScript(&nsc);\n }\n });\n}\n\nvoid Scene::onAttach() {\n\n \/\/ lista as tags nas entidades registradas\n registry->get().each([&](auto entityID) {\n Entity entity{entityID, registry};\n auto& tc = entity.getComponent<TagComponent>();\n SDL_Log(\"Tag: %s Id: %s\", tc.tag.c_str(), tc.id.c_str());\n\n \/\/ Se for um mesh inicializar componente (já que nao tenho classe de Mesh)\n if (entity.hasComponent<MeshComponent>()) {\n MeshComponent& mesh = entity.getComponent<MeshComponent>();\n\n \/\/ Inicializa Materiais\n if (entity.hasComponent<MaterialComponent>()) {\n MaterialComponent& material = entity.getComponent<MaterialComponent>();\n if (!material.material->isValid())\n material.material->init();\n } else {\n MaterialComponent& material = entity.addComponent<MaterialComponent>();\n material.material->setDefaultEffect();\n material.material->init();\n }\n\n \/\/ Se nja nao foi inicializado um Renderable3dComponent ao mesh\n if (!entity.hasComponent<Renderable3dComponent>()) { \/\/ FIXME: Depoin do BSP mudar o teste ja que todos serao criados aqui!!!\n\n Renderable3dComponent& rc = entity.addComponent<Renderable3dComponent>();\n\n if (mesh.type == MeshType::SIMPLE) {\n\n \/\/ Transforma Mesh em VertexData comprimindo-o\n std::vector<VertexData> renderData;\n vertexDataFromMesh(mesh.mesh, renderData);\n\n std::vector<uint32_t> index;\n std::vector<VertexData> vertexDataOut;\n vertexDataIndexCompile(renderData, vertexDataOut, index);\n\n \/\/ Create VAO, VBO and IBO\n VertexArray* vao = new VertexArray();\n vao->bind();\n\n VertexBuffer* vbo = new VertexBuffer(BufferType::STATIC);\n vbo->bind();\n\n BufferLayout layout;\n layout.Push<float>(3, false);\n layout.Push<float>(3, false);\n layout.Push<float>(2, false);\n\n vbo->setLayout(layout);\n vbo->setData(&vertexDataOut[0], vertexDataOut.size());\n vbo->unbind();\n vao->push(vbo);\n\n vao->unbind();\n\n glm::vec3 min, max, size;\n vertexDataIndexMinMaxSize(&vertexDataOut[0], vertexDataOut.size(), &index[0], index.size(), min, max, size);\n\n IndexBuffer* ibo = new IndexBuffer(&index[0], index.size());\n Renderable3D* r = new Renderable3D(vao, ibo, AABB(min, max));\n\n rc.renderable = r;\n } else if (mesh.type == MeshType::ARRAY) {\n\n std::vector<VertexData> renderData;\n vertexDataFromMesh(mesh.mesh, renderData);\n\n rc.renderable = new RenderableArray(mesh.vTrisIndex, renderData);\n\n } else if (mesh.type == MeshType::BSTREE) {\n\n Mesh meshFinal;\n meshReCompile(*mesh.mesh, meshFinal);\n\n \/\/ btree root, leafs, vertex\n BspTree bspTree;\n mesh.root = bspTree.create(&meshFinal, mesh.vTrisIndex);\n\n rc.renderable = new RenderableBsp(mesh.root, mesh.vTrisIndex, &meshFinal);\n }\n }\n\n if (entity.hasComponent<TransComponent>()) {\n glm::vec3 min, max, size;\n meshMinMaxSize(mesh.mesh, min, max, size);\n\n TransComponent& tc = entity.getComponent<TransComponent>();\n if (tc.solid) {\n Solid* solid = (Solid*)tc.trans;\n solid->init(size); \/\/ Cria rigidBody iniciaza transformacao e inicializa shape se ele nao existir\n }\n }\n }\n\n if (entity.hasComponent<EmitterComponent>()) {\n EmitterComponent& ec = entity.getComponent<EmitterComponent>();\n\n if (!entity.hasComponent<RenderableParticlesComponent>()) {\n\n RenderableParticlesComponent& particleSys = entity.addComponent<RenderableParticlesComponent>();\n particleSys.enable = true;\n RenderableParticles* p = new RenderableParticles();\n ParticleContainer* pc = ec.emitter->getContainer(0); \/\/ FIXME: melhorar!!!!\n p->setParticleContainer(pc);\n p->create();\n particleSys.renderable = p;\n this->pushEmitters(ec.emitter);\n }\n }\n\n if (entity.hasComponent<EyeView>()) {\n EyeView& ev = entity.getComponent<EyeView>();\n eyeView = &ev;\n }\n\n if (entity.hasComponent<CanvasComponent>()) {\n CanvasComponent& cc = entity.getComponent<CanvasComponent>();\n this->onViewportResize(cc.canvas->getWidth(), cc.canvas->getHeight());\n }\n });\n\n {\n \/\/ Registra Camera controllers EyeView deve ser localizado acima\n auto view1 = registry->get().view<CameraComponent>();\n for (auto entity : view1) {\n Entity e = Entity{entity, registry};\n\n auto& cc = e.getComponent<CameraComponent>();\n cc.eyeView = eyeView;\n if (cc.camKind == CamKind::FPS) {\n e.addComponent<NativeScriptComponent>().bind<CameraControllerFPS>(\"CameraController\");\n } else if (cc.camKind == CamKind::ORBIT) {\n e.addComponent<NativeScriptComponent>().bind<CameraControllerOrbit>(\"CameraController\");\n } else if (cc.camKind == CamKind::STATIC) {\n \/\/ e.addComponent<NativeScriptComponent>().bind<CameraController>(\"CameraController\");\n }\n }\n }\n\n {\n \/\/ initialize scripts\n registry->get().view<NativeScriptComponent>().each([=](auto entity, auto& nsc) {\n if (!nsc.instance) {\n nsc.instance = nsc.instantiateScript();\n nsc.instance->entity = Entity{entity, registry};\n nsc.instance->onCreate();\n }\n });\n }\n\n origem = new Transform(); \/\/ FIXME: coisa feia!!!!\n}\n\nCanvas* Scene::getCanvas() {\n CanvasComponent& cc = registry->findComponent<CanvasComponent>(\"main_screem\");\n return cc.canvas;\n}\n\nvoid Scene::onUpdate(const double& ts) {\n \/\/ update scripts (PhysicController aqui dentro!!!)\n registry->get().view<NativeScriptComponent>().each([=](auto entity, auto& nsc) {\n if (nsc.instance)\n nsc.instance->onUpdate(ts);\n });\n\n for (auto emissor : emitters)\n emissor->recycleLife(ts);\n}\n\nvoid Scene::onViewportResize(const uint32_t& width, const uint32_t& height) {\n\n auto view = registry->get().view<CameraComponent>();\n for (auto entity : view) {\n\n auto& cameraComponent = view.get<CameraComponent>(entity);\n if (!cameraComponent.fixedAspectRatio) {\n cameraComponent.camera->setViewportSize(width, height);\n\n \/\/ carrega camera defalt da cena\n if (cameraComponent.primary == true) {\n createRenderBuffer(eyeView->size(), width, height);\n activeCam = cameraComponent.camera;\n }\n }\n }\n}\n\nbool Scene::onEvent(const SDL_Event& event) {\n switch (event.type) {\n case SDL_WINDOWEVENT: {\n switch (event.window.event) {\n case SDL_WINDOWEVENT_RESIZED: \/\/ aqui para camera e engine acerta a janela\n onViewportResize(event.window.data1, event.window.data2);\n break;\n }\n } break;\n case SDL_KEYDOWN: {\n switch (event.key.keysym.sym) {\n case SDLK_F9:\n logRender = !logRender;\n break;\n }\n } break;\n }\n return true;\n}\n\nvoid Scene::execEmitterPass(Camera* camera, IRenderer3d& renderer) {\n \/\/ inicializa state machine do opengl\n BinaryStateEnable depth(GL_DEPTH_TEST); \/\/ glEnable(GL_DEPTH_TEST);\/\/ Enable depth test\n BinaryStateEnable blender(GL_BLEND); \/\/ glEnable(GL_BLEND);\n DepthFuncSetter depthFunc(GL_LESS); \/\/ glDepthFunc(GL_LESS); \/\/ Accept fragment if it closer to the camera than the former one\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n renderer.begin(eyeView);\n auto view = registry->get().view<RenderableParticlesComponent>();\n for (auto entity : view) {\n\n RenderableParticlesComponent& rc = view.get<RenderableParticlesComponent>(entity);\n IRenderable3d* renderable = rc.renderable;\n\n Entity e = {entity, registry};\n TransComponent& tc = e.getComponent<TransComponent>(); \/\/ FIXME: group this!!!\n Shader& sc = e.getComponent<Shader>();\n MaterialComponent& mc = e.getComponent<MaterialComponent>();\n\n RenderCommand command;\n command.camera = camera;\n command.eyeView = eyeView;\n command.logRender = logRender;\n command.transform = tc.trans->translateSrc(origem->getPosition());\n command.renderable = renderable;\n command.shader = sc;\n mc.material->bindMaterialInformation(command.uniforms, command.vTex);\n\n command.uniforms[\"model\"] = UValue(command.transform);\n\n renderable->submit(command, renderer);\n }\n\n renderer.end();\n renderer.flush();\n}\n\nvoid Scene::execRenderPass(Camera* camera, IRenderer3d& renderer) {\n\n renderer.begin(eyeView);\n auto group = registry->get().group<Shader, MaterialComponent, TransComponent, Renderable3dComponent>();\n for (auto entity : group) {\n auto [sc, mc, tc, rc] = group.get<Shader, MaterialComponent, TransComponent, Renderable3dComponent>(entity);\n\n RenderCommand command;\n command.camera = camera;\n command.eyeView = eyeView;\n command.logRender = logRender;\n command.transform = tc.trans->translateSrc(origem->getPosition());\n command.renderable = rc.renderable;\n command.shader = sc;\n mc.material->bindMaterialInformation(command.uniforms, command.vTex);\n command.uniforms[\"model\"] = UValue(command.transform);\n rc.renderable->submit(command, renderer);\n }\n\n renderer.end();\n renderer.flush();\n}\n\nvoid Scene::onRender() {\n\n Camera* camera = activeCam;\n\n if (logRender == true) {\n const glm::vec3& pos = camera->getPosition();\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Eye: %0.2f; %0.3f; %0.3f\", pos.x, pos.y, pos.z);\n }\n\n \/\/ render a shadows in framebuffer\n if (shadowPass)\n shadowPass->render(registry, camera, eyeView, renderBatch, origem, logRender);\n\n uint8_t count = 0;\n for (auto renderBuffer : vRB) {\n camera->setViewportSize(renderBuffer->getWidth(), renderBuffer->getHeight());\n eyeView->setIndex(count);\n count++;\n\n \/\/ used by all\n renderBatch.uQueue().insert(std::make_pair(\"projection\", UValue(camera->getProjection())));\n renderBatch.uQueue().insert(std::make_pair(\"view\", UValue(eyeView->getView())));\n\n \/\/ load shadows props to renderBatch\n if (shadowPass)\n shadowPass->setProp(camera->getPosition(), renderBatch);\n\n auto lightView = registry->get().view<LightComponent>();\n for (auto entity : lightView) {\n auto& lc = lightView.get<LightComponent>(entity);\n auto& tc = registry->get().get<TransComponent>(entity); \/\/ lightView.get<LightComponent>(entity);\n if (lc.global) \/\/ biding light prop\n lc.light->bindLight(renderBatch.uQueue(), tc.trans->getMatrix());\n }\n\n renderBuffer->bind(); \/\/ bind renderbuffer to draw we're not using the stencil buffer now\n\n this->execRenderPass(camera, renderBatch);\n\n if (emitters.size() > 0)\n this->execEmitterPass(camera, renderBatch);\n\n {\n \/\/ TODO: captura do entity no framebuffer da tela\n \/\/ \/\/ get val from color buffer (must be inside framebuffer renderer\n \/\/ glm::ivec2 pos = MouseDevice::getMove();\n \/\/ pos.y = viewportHeight - pos.y;\n \/\/ int val = renderBuffer->getFramBuffer()->readPixel(1, pos.x, pos.y);\n \/\/ SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"mouse(X: %d \/ Y: %d): %d\", pos.x, pos.y, val);\n }\n\n renderBuffer->unbind();\n renderBuffer->render();\n }\n}\n} \/\/ namespace Chimera<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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\/browser\/browser_shutdown.h\"\n\n#include <map>\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"base\/time.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/about_flags.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/first_run\/upgrade_util.h\"\n#include \"chrome\/browser\/jankometer.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/service\/service_process_control.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_url_data_manager.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/switch_utils.h\"\n#include \"content\/browser\/plugin_process_host.h\"\n#include \"content\/browser\/renderer_host\/render_process_host.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\n#if defined(OS_WIN)\n#include \"chrome\/browser\/browser_util_win.h\"\n#include \"chrome\/browser\/first_run\/upgrade_util_win.h\"\n#include \"chrome\/browser\/rlz\/rlz.h\"\n#endif\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/boot_times_loader.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#endif\n\nusing base::Time;\nusing base::TimeDelta;\nusing content::BrowserThread;\n\nnamespace browser_shutdown {\n\n\/\/ Whether the browser is trying to quit (e.g., Quit chosen from menu).\nbool g_trying_to_quit = false;\n\n\/\/ Whether the browser should quit without closing browsers.\nbool g_shutting_down_without_closing_browsers = false;\n\nTime shutdown_started_;\nShutdownType shutdown_type_ = NOT_VALID;\nint shutdown_num_processes_;\nint shutdown_num_processes_slow_;\n\nbool delete_resources_on_shutdown = true;\n\nconst char kShutdownMsFile[] = \"chrome_shutdown_ms.txt\";\n\nvoid RegisterPrefs(PrefService* local_state) {\n local_state->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID);\n local_state->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0);\n local_state->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0);\n}\n\nShutdownType GetShutdownType() {\n return shutdown_type_;\n}\n\nvoid OnShutdownStarting(ShutdownType type) {\n if (shutdown_type_ != NOT_VALID)\n return;\n\n shutdown_type_ = type;\n \/\/ For now, we're only counting the number of renderer processes\n \/\/ since we can't safely count the number of plugin processes from this\n \/\/ thread, and we'd really like to avoid anything which might add further\n \/\/ delays to shutdown time.\n shutdown_started_ = Time::Now();\n\n \/\/ Call FastShutdown on all of the RenderProcessHosts. This will be\n \/\/ a no-op in some cases, so we still need to go through the normal\n \/\/ shutdown path for the ones that didn't exit here.\n shutdown_num_processes_ = 0;\n shutdown_num_processes_slow_ = 0;\n for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());\n !i.IsAtEnd(); i.Advance()) {\n ++shutdown_num_processes_;\n if (!i.GetCurrentValue()->FastShutdownIfPossible())\n ++shutdown_num_processes_slow_;\n }\n}\n\nFilePath GetShutdownMsPath() {\n FilePath shutdown_ms_file;\n PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file);\n return shutdown_ms_file.AppendASCII(kShutdownMsFile);\n}\n\nvoid Shutdown() {\n#if defined(OS_CHROMEOS)\n chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(\n \"BrowserShutdownStarted\", false);\n#endif\n \/\/ During shutdown we will end up some blocking operations. But the\n \/\/ work needs to get done and we're going to wait for them no matter\n \/\/ what thread they're on, so don't worry about it slowing down\n \/\/ shutdown.\n base::ThreadRestrictions::SetIOAllowed(true);\n\n \/\/ Shutdown the IPC channel to the service processes.\n ServiceProcessControl::GetInstance()->Disconnect();\n\n \/\/ WARNING: During logoff\/shutdown (WM_ENDSESSION) we may not have enough\n \/\/ time to get here. If you have something that *must* happen on end session,\n \/\/ consider putting it in BrowserProcessImpl::EndSession.\n PrefService* prefs = g_browser_process->local_state();\n\n MetricsService* metrics = g_browser_process->metrics_service();\n if (metrics)\n metrics->RecordCompletedSessionEnd();\n\n if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {\n \/\/ Record the shutdown info so that we can put it into a histogram at next\n \/\/ startup.\n prefs->SetInteger(prefs::kShutdownType, shutdown_type_);\n prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_);\n prefs->SetInteger(prefs::kShutdownNumProcessesSlow,\n shutdown_num_processes_slow_);\n }\n\n \/\/ Check local state for the restart flag so we can restart the session below.\n bool restart_last_session = false;\n if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) {\n restart_last_session =\n prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown);\n prefs->ClearPref(prefs::kRestartLastSessionOnShutdown);\n }\n\n prefs->SavePersistentPrefs();\n\n#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)\n \/\/ Cleanup any statics created by RLZ. Must be done before NotificationService\n \/\/ is destroyed.\n RLZTracker::CleanupRlz();\n#endif\n\n \/\/ The jank'o'meter requires that the browser process has been destroyed\n \/\/ before calling UninstallJankometer().\n delete g_browser_process;\n g_browser_process = NULL;\n\n \/\/ crbug.com\/95079 - This needs to happen after the browser process object\n \/\/ goes away.\n ProfileManager::NukeDeletedProfilesFromDisk();\n\n#if defined(OS_CHROMEOS)\n chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(\"BrowserDeleted\",\n true);\n#endif\n\n \/\/ Uninstall Jank-O-Meter here after the IO thread is no longer running.\n UninstallJankometer();\n\n if (delete_resources_on_shutdown)\n ResourceBundle::CleanupSharedInstance();\n\n#if defined(OS_WIN)\n if (!browser_util::IsBrowserAlreadyRunning() &&\n shutdown_type_ != browser_shutdown::END_SESSION) {\n upgrade_util::SwapNewChromeExeIfPresent();\n }\n#endif\n\n if (restart_last_session) {\n#if !defined(OS_CHROMEOS)\n \/\/ Make sure to relaunch the browser with the original command line plus\n \/\/ the Restore Last Session flag. Note that Chrome can be launched (ie.\n \/\/ through ShellExecute on Windows) with a switch argument terminator at\n \/\/ the end (double dash, as described in b\/1366444) plus a URL,\n \/\/ which prevents us from appending to the command line directly (issue\n \/\/ 46182). We therefore use GetSwitches to copy the command line (it stops\n \/\/ at the switch argument terminator).\n CommandLine old_cl(*CommandLine::ForCurrentProcess());\n scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl.GetProgram()));\n std::map<std::string, CommandLine::StringType> switches =\n old_cl.GetSwitches();\n \/\/ Remove the switches that shouldn't persist across restart.\n about_flags::RemoveFlagsSwitches(&switches);\n switches::RemoveSwitchesForAutostart(&switches);\n \/\/ Append the old switches to the new command line.\n for (std::map<std::string, CommandLine::StringType>::const_iterator i =\n switches.begin(); i != switches.end(); ++i) {\n CommandLine::StringType switch_value = i->second;\n if (!switch_value.empty())\n new_cl->AppendSwitchNative(i->first, i->second);\n else\n new_cl->AppendSwitch(i->first);\n }\n \/\/ Ensure restore last session is set.\n if (!new_cl->HasSwitch(switches::kRestoreLastSession))\n new_cl->AppendSwitch(switches::kRestoreLastSession);\n\n upgrade_util::RelaunchChromeBrowser(*new_cl.get());\n#else\n NOTIMPLEMENTED();\n#endif \/\/ !defined(OS_CHROMEOS)\n }\n\n if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {\n \/\/ Measure total shutdown time as late in the process as possible\n \/\/ and then write it to a file to be read at startup.\n \/\/ We can't use prefs since all services are shutdown at this point.\n TimeDelta shutdown_delta = Time::Now() - shutdown_started_;\n std::string shutdown_ms =\n base::Int64ToString(shutdown_delta.InMilliseconds());\n int len = static_cast<int>(shutdown_ms.length()) + 1;\n FilePath shutdown_ms_file = GetShutdownMsPath();\n file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len);\n }\n\n#if defined(OS_CHROMEOS)\n BrowserList::NotifyAndTerminate(false);\n#endif\n\n ChromeURLDataManager::DeleteDataSources();\n}\n\nvoid ReadLastShutdownFile(\n ShutdownType type,\n int num_procs,\n int num_procs_slow) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n FilePath shutdown_ms_file = GetShutdownMsPath();\n std::string shutdown_ms_str;\n int64 shutdown_ms = 0;\n if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str))\n base::StringToInt64(shutdown_ms_str, &shutdown_ms);\n file_util::Delete(shutdown_ms_file, false);\n\n if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0)\n return;\n\n const char *time_fmt = \"Shutdown.%s.time\";\n const char *time_per_fmt = \"Shutdown.%s.time_per_process\";\n std::string time;\n std::string time_per;\n if (type == WINDOW_CLOSE) {\n time = base::StringPrintf(time_fmt, \"window_close\");\n time_per = base::StringPrintf(time_per_fmt, \"window_close\");\n } else if (type == BROWSER_EXIT) {\n time = base::StringPrintf(time_fmt, \"browser_exit\");\n time_per = base::StringPrintf(time_per_fmt, \"browser_exit\");\n } else if (type == END_SESSION) {\n time = base::StringPrintf(time_fmt, \"end_session\");\n time_per = base::StringPrintf(time_per_fmt, \"end_session\");\n } else {\n NOTREACHED();\n }\n\n if (time.empty())\n return;\n\n \/\/ TODO(erikkay): change these to UMA histograms after a bit more testing.\n UMA_HISTOGRAM_TIMES(time.c_str(),\n TimeDelta::FromMilliseconds(shutdown_ms));\n UMA_HISTOGRAM_TIMES(time_per.c_str(),\n TimeDelta::FromMilliseconds(shutdown_ms \/ num_procs));\n UMA_HISTOGRAM_COUNTS_100(\"Shutdown.renderers.total\", num_procs);\n UMA_HISTOGRAM_COUNTS_100(\"Shutdown.renderers.slow\", num_procs_slow);\n}\n\nvoid ReadLastShutdownInfo() {\n PrefService* prefs = g_browser_process->local_state();\n ShutdownType type =\n static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType));\n int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses);\n int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow);\n \/\/ clear the prefs immediately so we don't pick them up on a future run\n prefs->SetInteger(prefs::kShutdownType, NOT_VALID);\n prefs->SetInteger(prefs::kShutdownNumProcesses, 0);\n prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0);\n\n \/\/ Read and delete the file on the file thread.\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n NewRunnableFunction(\n &ReadLastShutdownFile, type, num_procs, num_procs_slow));\n}\n\nvoid SetTryingToQuit(bool quitting) {\n g_trying_to_quit = quitting;\n}\n\nbool IsTryingToQuit() {\n return g_trying_to_quit;\n}\n\nbool ShuttingDownWithoutClosingBrowsers() {\n return g_shutting_down_without_closing_browsers;\n}\n\nvoid SetShuttingDownWithoutClosingBrowsers(bool without_close) {\n g_shutting_down_without_closing_browsers = without_close;\n}\n\n} \/\/ namespace browser_shutdown\n<commit_msg>Replace NewRunnableFunction with Bind in BrowserShutdown.<commit_after>\/\/ Copyright (c) 2011 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\/browser\/browser_shutdown.h\"\n\n#include <map>\n#include <string>\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"base\/time.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/about_flags.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/first_run\/upgrade_util.h\"\n#include \"chrome\/browser\/jankometer.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/service\/service_process_control.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_url_data_manager.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/switch_utils.h\"\n#include \"content\/browser\/plugin_process_host.h\"\n#include \"content\/browser\/renderer_host\/render_process_host.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\n#if defined(OS_WIN)\n#include \"chrome\/browser\/browser_util_win.h\"\n#include \"chrome\/browser\/first_run\/upgrade_util_win.h\"\n#include \"chrome\/browser\/rlz\/rlz.h\"\n#endif\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/boot_times_loader.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#endif\n\nusing base::Time;\nusing base::TimeDelta;\nusing content::BrowserThread;\n\nnamespace browser_shutdown {\n\n\/\/ Whether the browser is trying to quit (e.g., Quit chosen from menu).\nbool g_trying_to_quit = false;\n\n\/\/ Whether the browser should quit without closing browsers.\nbool g_shutting_down_without_closing_browsers = false;\n\nTime shutdown_started_;\nShutdownType shutdown_type_ = NOT_VALID;\nint shutdown_num_processes_;\nint shutdown_num_processes_slow_;\n\nbool delete_resources_on_shutdown = true;\n\nconst char kShutdownMsFile[] = \"chrome_shutdown_ms.txt\";\n\nvoid RegisterPrefs(PrefService* local_state) {\n local_state->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID);\n local_state->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0);\n local_state->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0);\n}\n\nShutdownType GetShutdownType() {\n return shutdown_type_;\n}\n\nvoid OnShutdownStarting(ShutdownType type) {\n if (shutdown_type_ != NOT_VALID)\n return;\n\n shutdown_type_ = type;\n \/\/ For now, we're only counting the number of renderer processes\n \/\/ since we can't safely count the number of plugin processes from this\n \/\/ thread, and we'd really like to avoid anything which might add further\n \/\/ delays to shutdown time.\n shutdown_started_ = Time::Now();\n\n \/\/ Call FastShutdown on all of the RenderProcessHosts. This will be\n \/\/ a no-op in some cases, so we still need to go through the normal\n \/\/ shutdown path for the ones that didn't exit here.\n shutdown_num_processes_ = 0;\n shutdown_num_processes_slow_ = 0;\n for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());\n !i.IsAtEnd(); i.Advance()) {\n ++shutdown_num_processes_;\n if (!i.GetCurrentValue()->FastShutdownIfPossible())\n ++shutdown_num_processes_slow_;\n }\n}\n\nFilePath GetShutdownMsPath() {\n FilePath shutdown_ms_file;\n PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file);\n return shutdown_ms_file.AppendASCII(kShutdownMsFile);\n}\n\nvoid Shutdown() {\n#if defined(OS_CHROMEOS)\n chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(\n \"BrowserShutdownStarted\", false);\n#endif\n \/\/ During shutdown we will end up some blocking operations. But the\n \/\/ work needs to get done and we're going to wait for them no matter\n \/\/ what thread they're on, so don't worry about it slowing down\n \/\/ shutdown.\n base::ThreadRestrictions::SetIOAllowed(true);\n\n \/\/ Shutdown the IPC channel to the service processes.\n ServiceProcessControl::GetInstance()->Disconnect();\n\n \/\/ WARNING: During logoff\/shutdown (WM_ENDSESSION) we may not have enough\n \/\/ time to get here. If you have something that *must* happen on end session,\n \/\/ consider putting it in BrowserProcessImpl::EndSession.\n PrefService* prefs = g_browser_process->local_state();\n\n MetricsService* metrics = g_browser_process->metrics_service();\n if (metrics)\n metrics->RecordCompletedSessionEnd();\n\n if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {\n \/\/ Record the shutdown info so that we can put it into a histogram at next\n \/\/ startup.\n prefs->SetInteger(prefs::kShutdownType, shutdown_type_);\n prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_);\n prefs->SetInteger(prefs::kShutdownNumProcessesSlow,\n shutdown_num_processes_slow_);\n }\n\n \/\/ Check local state for the restart flag so we can restart the session below.\n bool restart_last_session = false;\n if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) {\n restart_last_session =\n prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown);\n prefs->ClearPref(prefs::kRestartLastSessionOnShutdown);\n }\n\n prefs->SavePersistentPrefs();\n\n#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)\n \/\/ Cleanup any statics created by RLZ. Must be done before NotificationService\n \/\/ is destroyed.\n RLZTracker::CleanupRlz();\n#endif\n\n \/\/ The jank'o'meter requires that the browser process has been destroyed\n \/\/ before calling UninstallJankometer().\n delete g_browser_process;\n g_browser_process = NULL;\n\n \/\/ crbug.com\/95079 - This needs to happen after the browser process object\n \/\/ goes away.\n ProfileManager::NukeDeletedProfilesFromDisk();\n\n#if defined(OS_CHROMEOS)\n chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(\"BrowserDeleted\",\n true);\n#endif\n\n \/\/ Uninstall Jank-O-Meter here after the IO thread is no longer running.\n UninstallJankometer();\n\n if (delete_resources_on_shutdown)\n ResourceBundle::CleanupSharedInstance();\n\n#if defined(OS_WIN)\n if (!browser_util::IsBrowserAlreadyRunning() &&\n shutdown_type_ != browser_shutdown::END_SESSION) {\n upgrade_util::SwapNewChromeExeIfPresent();\n }\n#endif\n\n if (restart_last_session) {\n#if !defined(OS_CHROMEOS)\n \/\/ Make sure to relaunch the browser with the original command line plus\n \/\/ the Restore Last Session flag. Note that Chrome can be launched (ie.\n \/\/ through ShellExecute on Windows) with a switch argument terminator at\n \/\/ the end (double dash, as described in b\/1366444) plus a URL,\n \/\/ which prevents us from appending to the command line directly (issue\n \/\/ 46182). We therefore use GetSwitches to copy the command line (it stops\n \/\/ at the switch argument terminator).\n CommandLine old_cl(*CommandLine::ForCurrentProcess());\n scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl.GetProgram()));\n std::map<std::string, CommandLine::StringType> switches =\n old_cl.GetSwitches();\n \/\/ Remove the switches that shouldn't persist across restart.\n about_flags::RemoveFlagsSwitches(&switches);\n switches::RemoveSwitchesForAutostart(&switches);\n \/\/ Append the old switches to the new command line.\n for (std::map<std::string, CommandLine::StringType>::const_iterator i =\n switches.begin(); i != switches.end(); ++i) {\n CommandLine::StringType switch_value = i->second;\n if (!switch_value.empty())\n new_cl->AppendSwitchNative(i->first, i->second);\n else\n new_cl->AppendSwitch(i->first);\n }\n \/\/ Ensure restore last session is set.\n if (!new_cl->HasSwitch(switches::kRestoreLastSession))\n new_cl->AppendSwitch(switches::kRestoreLastSession);\n\n upgrade_util::RelaunchChromeBrowser(*new_cl.get());\n#else\n NOTIMPLEMENTED();\n#endif \/\/ !defined(OS_CHROMEOS)\n }\n\n if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {\n \/\/ Measure total shutdown time as late in the process as possible\n \/\/ and then write it to a file to be read at startup.\n \/\/ We can't use prefs since all services are shutdown at this point.\n TimeDelta shutdown_delta = Time::Now() - shutdown_started_;\n std::string shutdown_ms =\n base::Int64ToString(shutdown_delta.InMilliseconds());\n int len = static_cast<int>(shutdown_ms.length()) + 1;\n FilePath shutdown_ms_file = GetShutdownMsPath();\n file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len);\n }\n\n#if defined(OS_CHROMEOS)\n BrowserList::NotifyAndTerminate(false);\n#endif\n\n ChromeURLDataManager::DeleteDataSources();\n}\n\nvoid ReadLastShutdownFile(\n ShutdownType type,\n int num_procs,\n int num_procs_slow) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n FilePath shutdown_ms_file = GetShutdownMsPath();\n std::string shutdown_ms_str;\n int64 shutdown_ms = 0;\n if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str))\n base::StringToInt64(shutdown_ms_str, &shutdown_ms);\n file_util::Delete(shutdown_ms_file, false);\n\n if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0)\n return;\n\n const char *time_fmt = \"Shutdown.%s.time\";\n const char *time_per_fmt = \"Shutdown.%s.time_per_process\";\n std::string time;\n std::string time_per;\n if (type == WINDOW_CLOSE) {\n time = base::StringPrintf(time_fmt, \"window_close\");\n time_per = base::StringPrintf(time_per_fmt, \"window_close\");\n } else if (type == BROWSER_EXIT) {\n time = base::StringPrintf(time_fmt, \"browser_exit\");\n time_per = base::StringPrintf(time_per_fmt, \"browser_exit\");\n } else if (type == END_SESSION) {\n time = base::StringPrintf(time_fmt, \"end_session\");\n time_per = base::StringPrintf(time_per_fmt, \"end_session\");\n } else {\n NOTREACHED();\n }\n\n if (time.empty())\n return;\n\n \/\/ TODO(erikkay): change these to UMA histograms after a bit more testing.\n UMA_HISTOGRAM_TIMES(time.c_str(),\n TimeDelta::FromMilliseconds(shutdown_ms));\n UMA_HISTOGRAM_TIMES(time_per.c_str(),\n TimeDelta::FromMilliseconds(shutdown_ms \/ num_procs));\n UMA_HISTOGRAM_COUNTS_100(\"Shutdown.renderers.total\", num_procs);\n UMA_HISTOGRAM_COUNTS_100(\"Shutdown.renderers.slow\", num_procs_slow);\n}\n\nvoid ReadLastShutdownInfo() {\n PrefService* prefs = g_browser_process->local_state();\n ShutdownType type =\n static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType));\n int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses);\n int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow);\n \/\/ clear the prefs immediately so we don't pick them up on a future run\n prefs->SetInteger(prefs::kShutdownType, NOT_VALID);\n prefs->SetInteger(prefs::kShutdownNumProcesses, 0);\n prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0);\n\n \/\/ Read and delete the file on the file thread.\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n base::Bind(&ReadLastShutdownFile, type, num_procs, num_procs_slow));\n}\n\nvoid SetTryingToQuit(bool quitting) {\n g_trying_to_quit = quitting;\n}\n\nbool IsTryingToQuit() {\n return g_trying_to_quit;\n}\n\nbool ShuttingDownWithoutClosingBrowsers() {\n return g_shutting_down_without_closing_browsers;\n}\n\nvoid SetShuttingDownWithoutClosingBrowsers(bool without_close) {\n g_shutting_down_without_closing_browsers = without_close;\n}\n\n} \/\/ namespace browser_shutdown\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n\n#include <vector>\n\n#include <openrave-core.h>\n#include <openrave_ompl_bridge\/RRTConnect.h>\n#include <openrave_ompl_bridge\/RRTConnectParameters.h>\n\nusing namespace openrave_ompl_bridge;\n\nclass PlannerTest : public ::testing::Test \n{\n protected:\n virtual void SetUp()\n {\n OpenRAVE::RaveInitialize();\n env = OpenRAVE::RaveCreateEnvironment();\n\n planner = OpenRAVE::RaveCreatePlanner(env, \"omplrrtconnect\");\n planner2 = boost::static_pointer_cast<openrave_ompl_bridge::RRTConnect>(planner);\n\n herb = env->ReadRobotXMLFile(\"robots\/herb2_padded_nosensors.robot.xml\");\n env->Add(herb);\n\n std::vector<OpenRAVE::RobotBase::ManipulatorPtr> herb_manipulators = herb->GetManipulators();\n for (unsigned int i=0; i<herb_manipulators.size(); i++)\n {\n if(herb_manipulators[i] && (herb_manipulators[i]->GetName().compare(\"right_wam\") == 0))\n {\n right_arm = herb_manipulators[i];\n }\n else if(herb_manipulators[i] && (herb_manipulators[i]->GetName().compare(\"left_wam\") == 0))\n {\n left_arm = herb_manipulators[i];\n }\n }\n\n parameters = RRTConnectParametersPtr(new RRTConnectParameters());\n\n herb->SetActiveDOFs(right_arm->GetArmIndices());\n parameters->SetRobotActiveJoints(herb);\n\n parameters->planning_timelimit = 3.0;\n parameters->smoothing_timelimit = 1.0;\n\n parameters->vinitialconfig.clear();\n herb->GetActiveDOFValues(parameters->vinitialconfig);\n\n parameters->vgoalconfig.clear();\n for(unsigned int i=0; i<herb->GetActiveDOF(); i++)\n parameters->vgoalconfig.push_back(1.0);\n\n std::vector<int> joint_indices;\n for (unsigned int i=0; i<herb->GetJoints().size(); i++)\n joint_indices.push_back((int)i);\n herb->SetActiveDOFs(joint_indices);\n }\n\n virtual void TearDown()\n {\n OpenRAVE::RaveDestroy();\n }\n\n OpenRAVE::EnvironmentBasePtr env;\n OpenRAVE::RobotBasePtr herb; \n OpenRAVE::RobotBase::ManipulatorPtr right_arm, left_arm;\n OpenRAVE::PlannerBasePtr planner;\n RRTConnectPtr planner2;\n RRTConnectParametersPtr parameters;\n};\n\nTEST_F(PlannerTest, InitPlan)\n{\n ASSERT_TRUE(planner2);\n ASSERT_TRUE(herb);\n ASSERT_TRUE(right_arm);\n ASSERT_TRUE(parameters);\n herb->SetActiveDOFs(right_arm->GetArmIndices());\n EXPECT_TRUE(planner2->InitPlan(herb, parameters));\n}\n\nTEST_F(PlannerTest, PlanPath)\n{\n ASSERT_TRUE(planner2);\n ASSERT_TRUE(herb);\n ASSERT_TRUE(right_arm);\n ASSERT_TRUE(parameters);\n herb->SetActiveDOFs(right_arm->GetArmIndices());\n ASSERT_TRUE(planner2->InitPlan(herb, parameters));\n OpenRAVE::TrajectoryBasePtr trajectory = OpenRAVE::RaveCreateTrajectory(env, right_arm->GetArmIndices().size());\n EXPECT_EQ(OpenRAVE::PS_HasSolution, planner2->PlanPath(trajectory));\n}\n<commit_msg>Removed two compiler warning.<commit_after>#include <gtest\/gtest.h>\n\n#include <vector>\n\n#include <openrave-core.h>\n#include <openrave_ompl_bridge\/RRTConnect.h>\n#include <openrave_ompl_bridge\/RRTConnectParameters.h>\n\nusing namespace openrave_ompl_bridge;\n\nclass PlannerTest : public ::testing::Test \n{\n protected:\n virtual void SetUp()\n {\n OpenRAVE::RaveInitialize();\n env = OpenRAVE::RaveCreateEnvironment();\n\n planner = OpenRAVE::RaveCreatePlanner(env, \"omplrrtconnect\");\n planner2 = boost::static_pointer_cast<openrave_ompl_bridge::RRTConnect>(planner);\n\n herb = env->ReadRobotXMLFile(\"robots\/herb2_padded_nosensors.robot.xml\");\n env->Add(herb);\n\n std::vector<OpenRAVE::RobotBase::ManipulatorPtr> herb_manipulators = herb->GetManipulators();\n for (unsigned int i=0; i<herb_manipulators.size(); i++)\n {\n if(herb_manipulators[i] && (herb_manipulators[i]->GetName().compare(\"right_wam\") == 0))\n {\n right_arm = herb_manipulators[i];\n }\n else if(herb_manipulators[i] && (herb_manipulators[i]->GetName().compare(\"left_wam\") == 0))\n {\n left_arm = herb_manipulators[i];\n }\n }\n\n parameters = RRTConnectParametersPtr(new RRTConnectParameters());\n\n herb->SetActiveDOFs(right_arm->GetArmIndices());\n parameters->SetRobotActiveJoints(herb);\n\n parameters->planning_timelimit = 3.0;\n parameters->smoothing_timelimit = 1.0;\n\n parameters->vinitialconfig.clear();\n herb->GetActiveDOFValues(parameters->vinitialconfig);\n\n parameters->vgoalconfig.clear();\n for(int i=0; i<herb->GetActiveDOF(); i++)\n parameters->vgoalconfig.push_back(1.0);\n\n std::vector<int> joint_indices;\n for (unsigned int i=0; i<herb->GetJoints().size(); i++)\n joint_indices.push_back((int)i);\n herb->SetActiveDOFs(joint_indices);\n }\n\n virtual void TearDown()\n {\n OpenRAVE::RaveDestroy();\n }\n\n OpenRAVE::EnvironmentBasePtr env;\n OpenRAVE::RobotBasePtr herb; \n OpenRAVE::RobotBase::ManipulatorPtr right_arm, left_arm;\n OpenRAVE::PlannerBasePtr planner;\n RRTConnectPtr planner2;\n RRTConnectParametersPtr parameters;\n};\n\nTEST_F(PlannerTest, InitPlan)\n{\n ASSERT_TRUE(planner2);\n ASSERT_TRUE(herb);\n ASSERT_TRUE(right_arm);\n ASSERT_TRUE(parameters);\n herb->SetActiveDOFs(right_arm->GetArmIndices());\n EXPECT_TRUE(planner2->InitPlan(herb, parameters));\n}\n\nTEST_F(PlannerTest, PlanPath)\n{\n ASSERT_TRUE(planner2);\n ASSERT_TRUE(herb);\n ASSERT_TRUE(right_arm);\n ASSERT_TRUE(parameters);\n herb->SetActiveDOFs(right_arm->GetArmIndices());\n ASSERT_TRUE(planner2->InitPlan(herb, parameters));\n OpenRAVE::TrajectoryBasePtr trajectory = OpenRAVE::RaveCreateTrajectory(env);\n EXPECT_EQ(OpenRAVE::PS_HasSolution, planner2->PlanPath(trajectory));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Chris Liebert\n\n#include <cmath>\n#include \"simulation.h\"\n\nSimulation::Simulation() {\n\tcollision_configuration = new btDefaultCollisionConfiguration();\n\tassert(collision_configuration);\n\tdispatcher = new btCollisionDispatcher(collision_configuration);\n\tassert(dispatcher);\n\toverlapping_pair_cache = new btDbvtBroadphase();\n\tassert(overlapping_pair_cache);\n\tsolver = new btSequentialImpulseConstraintSolver;\n\tassert(solver);\n\tdynamics_world = new btDiscreteDynamicsWorld(dispatcher,\n\t\t\toverlapping_pair_cache, solver, collision_configuration);\n\tassert(dynamics_world);\n\tdynamics_world->setGravity(btVector3(0, -10, 0));\n}\n\nSimulation::~Simulation() {\n\n\n\tfor(std::map<std::string, btRigidBody*>::iterator it = rigid_bodies.begin(); it != rigid_bodies.end(); ++it) {\n\t\tbtRigidBody* rb = it->second;\n\t\tif(rb) {\n\t\t\tdelete rb;\n\t\t\trb = 0;\n\t\t}\n\t}\n\n\tfor(std::map<std::string, btBoxShape*>::iterator it = box_shapes.begin(); it != box_shapes.end(); ++it) {\n\t\tbtBoxShape* box = it->second;\n\t\tif(box) {\n\t\t\tdelete box;\n\t\t\tbox = 0;\n\t\t}\n\t}\n\n\tfor(std::map<std::string, btConvexHullShape*>::iterator it = convex_hull_shapes.begin(); it != convex_hull_shapes.end(); ++it) {\n\t\tbtConvexHullShape* chs = it->second;\n\t\tif(chs) {\n\t\t\tdelete chs;\n\t\t\tchs = 0;\n\t\t}\n\t}\n\n\tdelete dynamics_world;\n\tdelete solver;\n\tdelete overlapping_pair_cache;\n\tdelete dispatcher;\n\tdelete collision_configuration;\n}\n\nvoid Simulation::parseXMLNode(rapidxml::xml_node<>* my_xml_node, scenegraph::Node* scenegraph_root) {\n\tif (!my_xml_node)\n\t\treturn;\n\tchar* c_name = my_xml_node->name();\n\tif (0 == strlen(c_name))\n\t\treturn;\n\tstd::string name(c_name);\n\tif (0 == std::string(\"PhysicsNode\").compare(name)) {\n\t\tfloat mass = 0.f;\n\t\tfloat offset_x = 0.f;\n\t\tfloat offset_y = 0.f;\n\t\tfloat offset_z = 0.f;\n\t\tfloat width = 0.f;\n\t\tfloat height = 0.f;\n\t\tfloat length = 0.f;\n\t\tstd::string object_name(\"\");\n\t\tfor (rapidxml::xml_attribute<> *attr = my_xml_node->first_attribute();\n\t\t\t\tattr; attr = attr->next_attribute()) {\n\t\t\tif (0 == std::string(\"mass\").compare(attr->name())) {\n\t\t\t\tmass = atof(attr->value());\n\t\t\t} else if (0 == std::string(\"name\").compare(attr->name())) {\n\t\t\t\tobject_name = std::string(attr->value());\n\t\t\t}\n\t\t}\n\t\tfor (rapidxml::xml_node<>* child = my_xml_node->first_node(); child;\n\t\t\t\tchild = child->next_sibling()) {\n\t\t\tif (0 == std::string(\"CollisionShape\").compare(child->name())) {\n\t\t\t\tif (0 == std::string(\"Box\").compare(child->value())) {\n\t\t\t\t\tfor (rapidxml::xml_attribute<> *col_attr =\n\t\t\t\t\t\t\tchild->first_attribute(); col_attr; col_attr =\n\t\t\t\t\t\t\tcol_attr->next_attribute()) {\n\t\t\t\t\t\tif (0 == std::string(\"width\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\twidth = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"height\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\theight = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"length\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\tlength = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"offset_x\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\toffset_x = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"offset_y\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\toffset_y = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"offset_z\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\toffset_z = atof(col_attr->value());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tTransformNode* trans_node = scenegraph::find_transform_node(object_name, scenegraph_root);\n\t\t\t\t\tif (trans_node) {\n\t\t\t\t\t\taddPhysicsBoxNode(trans_node, mass, width, height,\n\t\t\t\t\t\t\t\tlength, offset_x, offset_y, offset_z);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLOGI(\"%s was referenced in configuration, but not loaded\", object_name.c_str());\n\t\t\t\t\t}\n\t\t\t\t} else if (0 == std::string(\"ConvexHull\").compare(child->value())) {\n\t\t\t\t\tTransformNode* trans_node = scenegraph::find_transform_node(object_name, scenegraph_root);\n\t\t\t\t\tif (trans_node) {\n\t\t\t\t\t\taddPhysicsConvexHullNode(trans_node, mass);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLOGI(\"%s was referenced in configuration, but not loaded\",\tobject_name.c_str());\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tLOGI(\"WARNING, only Box and ConvexHull collision shapes are implemented %s.\", child->value());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Recursively parse children and siblings\n\tparseXMLNode(my_xml_node->first_node(), scenegraph_root);\n\tparseXMLNode(my_xml_node->next_sibling(), scenegraph_root);\n}\n\nvoid Simulation::addPhysicsNode(TransformNode* trans_node,\n\t\tbtCollisionShape* collision_shape, float mass, float offset_x,\n\t\tfloat offset_y, float offset_z) {\n\tassert(collision_shape);\n\tassert(trans_node);\n\tcollision_shapes.push_back(collision_shape);\n\n\t\/\/\/ Create Dynamic Objects\n\tbtTransform start_transform;\n\tstart_transform.setIdentity();\n\n\t\/\/ rigid body is dynamic if mass is non zero, otherwise it is static\n\tbool is_dynamic = (mass != 0.f);\n\n\tbtVector3 local_inertia(0, 0, 0);\n\tif (is_dynamic) {\n\t\tcollision_shape->calculateLocalInertia(mass, local_inertia);\n\t}\n\n\tglm::vec4 translation = trans_node->matrix\n\t\t\t* glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);\n\tstart_transform.setOrigin(\n\t\t\tbtVector3(translation.x + offset_x, translation.y + offset_y,\n\t\t\t\t\ttranslation.z + offset_z));\n\n\tbtDefaultMotionState* motion_state = new btDefaultMotionState(\n\t\t\tstart_transform);\n\tassert(motion_state);\n\tbtRigidBody::btRigidBodyConstructionInfo rb_info(mass, motion_state,\n\t\t\tcollision_shape, local_inertia);\n\tbtRigidBody* body = new btRigidBody(rb_info);\n\tassert(body);\n\trigid_bodies.insert(std::make_pair(trans_node->name, body));\n\tdynamics_world->addRigidBody(body);\n\n\tPhysicsNode* physics_node = new PhysicsNode;\n\tassert(physics_node);\n\tphysics_node->collision_shape = collision_shape;\n\tphysics_node->body = body;\n\tphysics_node->transform_node = trans_node;\n\tphysics_node->mass = btScalar(mass);\n\tint index = dynamics_world->getNumCollisionObjects() - 1;\n\tcollision_node_index.insert(std::make_pair(index, physics_node));\n}\n\nvoid Simulation::addPhysicsNode(TransformNode* trans_node,\n\t\tbtCollisionShape* collision_shape, float mass) {\n\taddPhysicsNode(trans_node, collision_shape, mass, 0.f, 0.f, 0.f);\n}\n\nvoid Simulation::addPhysicsBoxNode(TransformNode* trans_node, float mass,\n\t\tfloat width, float height, float length, float offset_x, float offset_y,\n\t\tfloat offset_z) {\n\tbtBoxShape* collision_shape = new btBoxShape(btVector3(width, height, length));\n\tassert(collision_shape);\n\tbox_shapes.insert(std::make_pair(trans_node->name, collision_shape));\n\taddPhysicsNode(trans_node, collision_shape, mass, offset_x, offset_y,\n\t\t\toffset_z);\n}\n\nvoid Simulation::addPhysicsBoxNode(TransformNode* trans_node, float mass,\n\t\tfloat width, float height, float length) {\n\taddPhysicsBoxNode(trans_node, mass, width, height, length, 0.f, 0.f, 0.f);\n}\n\nvoid populateConvexHullShapeFromNode(scenegraph::Node* root, btConvexHullShape* convex_hull, glm::mat4& matrix) {\n\tif(root->type == scenegraph::NodeType::Geometry) {\n\t\tscenegraph::GeometryNode* geometry_node = (scenegraph::GeometryNode*) root;\n\t\tfor(std::vector<scenegraph::Vertex>::iterator it = geometry_node->vertex_data.begin(); it != geometry_node->vertex_data.end(); ++it) {\n\t\t\tscenegraph::Vertex* v = &*it;\n\t\t\tglm::vec4 v_trans = glm::vec4(v->position[0], v->position[1], v->position[2], 1.0f) * matrix;\n\t\t\tconvex_hull->addPoint(btVector3(v_trans.x, v_trans.y, v_trans.z));\n\t\t}\n\t} else if(root->type == scenegraph::NodeType::Transform) {\n\t\tscenegraph::TransformNode* transform_node = (scenegraph::TransformNode*) root;\n\t\tmatrix *= transform_node->matrix;\n\t} else {\n\t\tLOGE(\"Node type not implemented for trimesh %s\", root->name.c_str());\n\t}\n\tfor(std::vector<scenegraph::Node*>::iterator it = root->children.begin(); it != root->children.end(); ++it) {\n\t\tscenegraph::Node* child = *it;\n\t\tpopulateConvexHullShapeFromNode(child, convex_hull, matrix);\n\t}\n}\n\nvoid Simulation::addPhysicsConvexHullNode(TransformNode* trans_node, float mass) {\n\tbtConvexHullShape * convex_hull_shape = new btConvexHullShape();\n\tassert(convex_hull_shape);\n\tconvex_hull_shapes.insert(std::make_pair(trans_node->name, convex_hull_shape));\n\tglm::mat4 identity(1.f);\n\tpopulateConvexHullShapeFromNode(trans_node, convex_hull_shape, identity);\n\taddPhysicsNode(trans_node, convex_hull_shape, mass);\n}\n\nvoid Simulation::step() {\n\tdynamics_world->stepSimulation(1.f \/ 60.f, 10);\n}\n\nvoid Simulation::applyForce(const std::string& rigid_body_name, const btVector3& force, const btVector3& rel_pos) {\n\tstd::map<std::string, btRigidBody*>::iterator itr = rigid_bodies.find(rigid_body_name);\n\tif(itr != rigid_bodies.end()) {\n\t\titr->second->applyForce(force, rel_pos);\n\t} else {\n\t\tLOGI(\"Unable to find rigid body called %s, can not apply force\", rigid_body_name.c_str());\n\t}\n}\n<commit_msg>reverted simulation destructor to use Bullet hello world example algorithm after clearing mapped pointer arrays to rigid bodies and collision shapes.<commit_after>\/\/ Copyright (C) 2017 Chris Liebert\n\n#include <cmath>\n#include \"simulation.h\"\n\nSimulation::Simulation() {\n\tcollision_configuration = new btDefaultCollisionConfiguration();\n\tassert(collision_configuration);\n\tdispatcher = new btCollisionDispatcher(collision_configuration);\n\tassert(dispatcher);\n\toverlapping_pair_cache = new btDbvtBroadphase();\n\tassert(overlapping_pair_cache);\n\tsolver = new btSequentialImpulseConstraintSolver;\n\tassert(solver);\n\tdynamics_world = new btDiscreteDynamicsWorld(dispatcher,\n\t\t\toverlapping_pair_cache, solver, collision_configuration);\n\tassert(dynamics_world);\n\tdynamics_world->setGravity(btVector3(0, -10, 0));\n}\n\nSimulation::~Simulation() {\n\trigid_bodies.clear();\n\tbox_shapes.clear();\n\tconvex_hull_shapes.clear();\n\tfor (int i = dynamics_world->getNumCollisionObjects() - 1; i >= 0; i--) {\n\t\tbtCollisionObject* obj = dynamics_world->getCollisionObjectArray()[i];\n\t\tbtRigidBody* body = btRigidBody::upcast(obj);\n\t\tif (body && body->getMotionState()) {\n\t\t\tdelete body->getMotionState();\n\t\t}\n\t\tdynamics_world->removeCollisionObject(obj);\n\t\tdelete obj;\n\t}\n\n\t\/\/delete collision shapes\n\tfor (int j = 0; j < collision_shapes.size(); j++) {\n\t\tbtCollisionShape* shape = collision_shapes[j];\n\t\tcollision_shapes[j] = 0;\n\t\tdelete shape;\n\t}\n\n\tdelete dynamics_world;\n\tdelete solver;\n\tdelete overlapping_pair_cache;\n\tdelete dispatcher;\n\tdelete collision_configuration;\n}\n\nvoid Simulation::parseXMLNode(rapidxml::xml_node<>* my_xml_node, scenegraph::Node* scenegraph_root) {\n\tif (!my_xml_node)\n\t\treturn;\n\tchar* c_name = my_xml_node->name();\n\tif (0 == strlen(c_name))\n\t\treturn;\n\tstd::string name(c_name);\n\tif (0 == std::string(\"PhysicsNode\").compare(name)) {\n\t\tfloat mass = 0.f;\n\t\tfloat offset_x = 0.f;\n\t\tfloat offset_y = 0.f;\n\t\tfloat offset_z = 0.f;\n\t\tfloat width = 0.f;\n\t\tfloat height = 0.f;\n\t\tfloat length = 0.f;\n\t\tstd::string object_name(\"\");\n\t\tfor (rapidxml::xml_attribute<> *attr = my_xml_node->first_attribute();\n\t\t\t\tattr; attr = attr->next_attribute()) {\n\t\t\tif (0 == std::string(\"mass\").compare(attr->name())) {\n\t\t\t\tmass = atof(attr->value());\n\t\t\t} else if (0 == std::string(\"name\").compare(attr->name())) {\n\t\t\t\tobject_name = std::string(attr->value());\n\t\t\t}\n\t\t}\n\t\tfor (rapidxml::xml_node<>* child = my_xml_node->first_node(); child;\n\t\t\t\tchild = child->next_sibling()) {\n\t\t\tif (0 == std::string(\"CollisionShape\").compare(child->name())) {\n\t\t\t\tif (0 == std::string(\"Box\").compare(child->value())) {\n\t\t\t\t\tfor (rapidxml::xml_attribute<> *col_attr =\n\t\t\t\t\t\t\tchild->first_attribute(); col_attr; col_attr =\n\t\t\t\t\t\t\tcol_attr->next_attribute()) {\n\t\t\t\t\t\tif (0 == std::string(\"width\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\twidth = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"height\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\theight = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"length\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\tlength = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"offset_x\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\toffset_x = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"offset_y\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\toffset_y = atof(col_attr->value());\n\t\t\t\t\t\t} else if (0\n\t\t\t\t\t\t\t\t== std::string(\"offset_z\").compare(\n\t\t\t\t\t\t\t\t\t\tcol_attr->name())) {\n\t\t\t\t\t\t\toffset_z = atof(col_attr->value());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tTransformNode* trans_node = scenegraph::find_transform_node(object_name, scenegraph_root);\n\t\t\t\t\tif (trans_node) {\n\t\t\t\t\t\taddPhysicsBoxNode(trans_node, mass, width, height,\n\t\t\t\t\t\t\t\tlength, offset_x, offset_y, offset_z);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLOGI(\"%s was referenced in configuration, but not loaded\", object_name.c_str());\n\t\t\t\t\t}\n\t\t\t\t} else if (0 == std::string(\"ConvexHull\").compare(child->value())) {\n\t\t\t\t\tTransformNode* trans_node = scenegraph::find_transform_node(object_name, scenegraph_root);\n\t\t\t\t\tif (trans_node) {\n\t\t\t\t\t\taddPhysicsConvexHullNode(trans_node, mass);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLOGI(\"%s was referenced in configuration, but not loaded\",\tobject_name.c_str());\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tLOGI(\"WARNING, only Box and ConvexHull collision shapes are implemented %s.\", child->value());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Recursively parse children and siblings\n\tparseXMLNode(my_xml_node->first_node(), scenegraph_root);\n\tparseXMLNode(my_xml_node->next_sibling(), scenegraph_root);\n}\n\nvoid Simulation::addPhysicsNode(TransformNode* trans_node,\n\t\tbtCollisionShape* collision_shape, float mass, float offset_x,\n\t\tfloat offset_y, float offset_z) {\n\tassert(collision_shape);\n\tassert(trans_node);\n\tcollision_shapes.push_back(collision_shape);\n\n\t\/\/\/ Create Dynamic Objects\n\tbtTransform start_transform;\n\tstart_transform.setIdentity();\n\n\t\/\/ rigid body is dynamic if mass is non zero, otherwise it is static\n\tbool is_dynamic = (mass != 0.f);\n\n\tbtVector3 local_inertia(0, 0, 0);\n\tif (is_dynamic) {\n\t\tcollision_shape->calculateLocalInertia(mass, local_inertia);\n\t}\n\n\tglm::vec4 translation = trans_node->matrix\n\t\t\t* glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);\n\tstart_transform.setOrigin(\n\t\t\tbtVector3(translation.x + offset_x, translation.y + offset_y,\n\t\t\t\t\ttranslation.z + offset_z));\n\n\tbtDefaultMotionState* motion_state = new btDefaultMotionState(\n\t\t\tstart_transform);\n\tassert(motion_state);\n\tbtRigidBody::btRigidBodyConstructionInfo rb_info(mass, motion_state,\n\t\t\tcollision_shape, local_inertia);\n\tbtRigidBody* body = new btRigidBody(rb_info);\n\tassert(body);\n\trigid_bodies.insert(std::make_pair(trans_node->name, body));\n\tdynamics_world->addRigidBody(body);\n\n\tPhysicsNode* physics_node = new PhysicsNode;\n\tassert(physics_node);\n\tphysics_node->collision_shape = collision_shape;\n\tphysics_node->body = body;\n\tphysics_node->transform_node = trans_node;\n\tphysics_node->mass = btScalar(mass);\n\tint index = dynamics_world->getNumCollisionObjects() - 1;\n\tcollision_node_index.insert(std::make_pair(index, physics_node));\n}\n\nvoid Simulation::addPhysicsNode(TransformNode* trans_node,\n\t\tbtCollisionShape* collision_shape, float mass) {\n\taddPhysicsNode(trans_node, collision_shape, mass, 0.f, 0.f, 0.f);\n}\n\nvoid Simulation::addPhysicsBoxNode(TransformNode* trans_node, float mass,\n\t\tfloat width, float height, float length, float offset_x, float offset_y,\n\t\tfloat offset_z) {\n\tbtBoxShape* collision_shape = new btBoxShape(btVector3(width, height, length));\n\tassert(collision_shape);\n\tbox_shapes.insert(std::make_pair(trans_node->name, collision_shape));\n\taddPhysicsNode(trans_node, collision_shape, mass, offset_x, offset_y,\n\t\t\toffset_z);\n}\n\nvoid Simulation::addPhysicsBoxNode(TransformNode* trans_node, float mass,\n\t\tfloat width, float height, float length) {\n\taddPhysicsBoxNode(trans_node, mass, width, height, length, 0.f, 0.f, 0.f);\n}\n\nvoid populateConvexHullShapeFromNode(scenegraph::Node* root, btConvexHullShape* convex_hull, glm::mat4& matrix) {\n\tif(root->type == scenegraph::NodeType::Geometry) {\n\t\tscenegraph::GeometryNode* geometry_node = (scenegraph::GeometryNode*) root;\n\t\tfor(std::vector<scenegraph::Vertex>::iterator it = geometry_node->vertex_data.begin(); it != geometry_node->vertex_data.end(); ++it) {\n\t\t\tscenegraph::Vertex* v = &*it;\n\t\t\tglm::vec4 v_trans = glm::vec4(v->position[0], v->position[1], v->position[2], 1.0f) * matrix;\n\t\t\tconvex_hull->addPoint(btVector3(v_trans.x, v_trans.y, v_trans.z));\n\t\t}\n\t} else if(root->type == scenegraph::NodeType::Transform) {\n\t\tscenegraph::TransformNode* transform_node = (scenegraph::TransformNode*) root;\n\t\tmatrix *= transform_node->matrix;\n\t} else {\n\t\tLOGE(\"Node type not implemented for trimesh %s\", root->name.c_str());\n\t}\n\tfor(std::vector<scenegraph::Node*>::iterator it = root->children.begin(); it != root->children.end(); ++it) {\n\t\tscenegraph::Node* child = *it;\n\t\tpopulateConvexHullShapeFromNode(child, convex_hull, matrix);\n\t}\n}\n\nvoid Simulation::addPhysicsConvexHullNode(TransformNode* trans_node, float mass) {\n\tbtConvexHullShape * convex_hull_shape = new btConvexHullShape();\n\tassert(convex_hull_shape);\n\tconvex_hull_shapes.insert(std::make_pair(trans_node->name, convex_hull_shape));\n\tglm::mat4 identity(1.f);\n\tpopulateConvexHullShapeFromNode(trans_node, convex_hull_shape, identity);\n\taddPhysicsNode(trans_node, convex_hull_shape, mass);\n}\n\nvoid Simulation::step() {\n\tdynamics_world->stepSimulation(1.f \/ 60.f, 10);\n}\n\nvoid Simulation::applyForce(const std::string& rigid_body_name, const btVector3& force, const btVector3& rel_pos) {\n\tstd::map<std::string, btRigidBody*>::iterator itr = rigid_bodies.find(rigid_body_name);\n\tif(itr != rigid_bodies.end()) {\n\t\titr->second->applyForce(force, rel_pos);\n\t} else {\n\t\tLOGI(\"Unable to find rigid body called %s, can not apply force\", rigid_body_name.c_str());\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) [2004-2014] Novell, Inc.\n * Copyright (c) [2016-2018] SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program 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 General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact Novell, Inc.\n *\n * To contact Novell about this file by physical or electronic mail, you may\n * find current contact information at www.novell.com.\n *\/\n\n\n#include <locale>\n#include <cmath>\n#include <vector>\n#include <sstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include \"storage\/Utils\/Text.h\"\n#include \"storage\/Utils\/HumanString.h\"\n#include \"storage\/Utils\/Math.h\"\n#include \"storage\/Utils\/ExceptionImpl.h\"\n\n\nnamespace storage\n{\n using std::string;\n\n\n int\n num_suffixes()\n {\n\treturn 7;\n }\n\n\n vector<Text>\n get_all_suffixes(int i, bool all = false, bool sloppy = false)\n {\n\tvector<Text> ret;\n\n\tswitch (i)\n\t{\n\t case 0:\n\t\t\/\/ TRANSLATORS: symbol for \"bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"B\"));\n\t\tif (sloppy)\n\t\t ret.push_back(Text(\"\", \"\"));\n\t\tbreak;\n\n\t case 1:\n\t\t\/\/ TRANSLATORS: symbol for \"kibi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"KiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"kilo bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"kB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"kilo\" (best keep untranslated)\n\t\t ret.push_back(_(\"k\"));\n\t\tbreak;\n\n\t case 2:\n\t\t\/\/ TRANSLATORS: symbol for \"mebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"MiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"mega bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"MB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"mega\" (best keep untranslated)\n\t\t ret.push_back(_(\"M\"));\n\t\tbreak;\n\n\t case 3:\n\t\t\/\/ TRANSLATORS: symbol for \"gibi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"GiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"giga bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"GB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"giga\" (best keep untranslated)\n\t\t ret.push_back(_(\"G\"));\n\t\tbreak;\n\n\t case 4:\n\t\t\/\/ TRANSLATORS: symbol for \"tebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"TiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"tera bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"TB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"tera\" (best keep untranslated)\n\t\t ret.push_back(_(\"T\"));\n\t\tbreak;\n\n\t case 5:\n\t\t\/\/ TRANSLATORS: symbol for \"pebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"PiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"peta bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"PB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"peta\" (best keep untranslated)\n\t\t ret.push_back(_(\"P\"));\n\t\tbreak;\n\n\t case 6:\n\t\t\/\/ TRANSLATORS: symbol for \"exbi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"EiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"exa bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"EB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"exa\" (best keep untranslated)\n\t\t ret.push_back(_(\"E\"));\n\t\tbreak;\n\t}\n\n\treturn ret;\n }\n\n\n string\n get_suffix(int i, bool classic)\n {\n\treturn classic ? get_all_suffixes(i).front().native : get_all_suffixes(i).front().translated;\n }\n\n\n string\n byte_to_humanstring(unsigned long long size, bool classic, int precision, bool omit_zeroes)\n {\n\tconst locale loc = classic ? locale::classic() : locale();\n\n\t\/\/ Calculate the index of the suffix to use. The index increases by 1\n\t\/\/ when the number of leading zeros decreases by 10.\n\n\tint i = size > 0 ? (64 - (clz(size) + 1)) \/ 10 : 0;\n\n\tif ((i == 0) || (omit_zeroes && is_multiple_of(size, 1ULL << 10 * i)))\n\t{\n\t unsigned long long v = size >> 10 * i;\n\n\t std::ostringstream s;\n\t s.imbue(loc);\n\t s << v << ' ' << get_suffix(i, classic);\n\t return s.str();\n\t}\n\telse\n\t{\n\t long double v = std::ldexp((long double)(size), - 10 * i);\n\n\t std::ostringstream s;\n\t s.imbue(loc);\n\t s.setf(ios::fixed);\n\t s.precision(precision);\n\t s << v << ' ' << get_suffix(i, classic);\n\t return s.str();\n\t}\n }\n\n\n namespace\n {\n\t\/\/ Helper functions to parse a number as int or float, multiply\n\t\/\/ according to the suffix. Do all required error checks.\n\n\tpair<bool, unsigned long long>\n\tparse_i(const string& str, int i, const locale& loc)\n\t{\n\t istringstream s(str);\n\t s.imbue(loc);\n\n\t unsigned long long v;\n\t s >> v;\n\n\t if (!s.eof())\n\t\treturn make_pair(false, 0);\n\n\t if (s.fail())\n\t {\n\t\tif (v == std::numeric_limits<unsigned long long>::max())\n\t\t ST_THROW(OverflowException());\n\n\t\treturn make_pair(false, 0);\n\t }\n\n\t if (v != 0 && str[0] == '-')\n\t\tST_THROW(OverflowException());\n\n\t if (v > 0 && clz(v) < 10 * i)\n\t\tST_THROW(OverflowException());\n\n\t v <<= 10 * i;\n\n\t return make_pair(true, v);\n\t}\n\n\n\tpair<bool, unsigned long long>\n\tparse_f(const string& str, int i, const locale& loc)\n\t{\n\t istringstream s(str);\n\t s.imbue(loc);\n\n\t long double v;\n\t s >> v;\n\n\t if (!s.eof())\n\t\treturn make_pair(false, 0);\n\n\t if (s.fail())\n\t {\n\t\tif (v == std::numeric_limits<long double>::max())\n\t\t ST_THROW(OverflowException());\n\n\t\treturn make_pair(false, 0);\n\t }\n\n\t if (v < 0.0)\n\t\tST_THROW(OverflowException());\n\n\t v = std::round(std::ldexp(v, 10 * i));\n\n\t if (v > std::numeric_limits<unsigned long long>::max())\n\t\tST_THROW(OverflowException());\n\n\t return make_pair(true, v);\n\t}\n\n }\n\n\n unsigned long long\n humanstring_to_byte(const string& str, bool classic)\n {\n\tconst locale loc = classic ? locale::classic() : locale();\n\n\tconst string str_trimmed = boost::trim_copy(str, loc);\n\n\tfor (int i = 0; i < num_suffixes(); ++i)\n\t{\n\t vector<Text> suffixes = get_all_suffixes(i, true, !classic);\n\n\t for (const Text& suffix : suffixes)\n\t {\n\t\tconst string& tmp = classic ? suffix.native : suffix.translated;\n\n\t\tif (boost::iends_with(str_trimmed, tmp, loc))\n\t\t{\n\t\t string number = boost::trim_copy(str_trimmed.substr(0, str_trimmed.size() - tmp.size()), loc);\n\n\t\t pair<bool, unsigned long long> v;\n\n\t\t v = parse_i(number, i, loc);\n\t\t if (v.first)\n\t\t\treturn v.second;\n\n\t\t v = parse_f(number, i, loc);\n\t\t if (v.first)\n\t\t\treturn v.second;\n\t\t}\n\t }\n\t}\n\n\tST_THROW(ParseException(\"failed to parse\", str, \"something like 1 GiB\"));\n }\n\n}\n<commit_msg>- added note<commit_after>\/*\n * Copyright (c) [2004-2014] Novell, Inc.\n * Copyright (c) [2016-2018] SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program 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 General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact Novell, Inc.\n *\n * To contact Novell about this file by physical or electronic mail, you may\n * find current contact information at www.novell.com.\n *\/\n\n\n#include <locale>\n#include <cmath>\n#include <vector>\n#include <sstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include \"storage\/Utils\/Text.h\"\n#include \"storage\/Utils\/HumanString.h\"\n#include \"storage\/Utils\/Math.h\"\n#include \"storage\/Utils\/ExceptionImpl.h\"\n\n\nnamespace storage\n{\n using std::string;\n\n\n int\n num_suffixes()\n {\n\treturn 7;\n }\n\n\n vector<Text>\n get_all_suffixes(int i, bool all = false, bool sloppy = false)\n {\n\tvector<Text> ret;\n\n\tswitch (i)\n\t{\n\t case 0:\n\t\t\/\/ TRANSLATORS: symbol for \"bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"B\"));\n\t\tif (sloppy)\n\t\t ret.push_back(Text(\"\", \"\"));\n\t\tbreak;\n\n\t case 1:\n\t\t\/\/ TRANSLATORS: symbol for \"kibi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"KiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"kilo bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"kB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"kilo\" (best keep untranslated)\n\t\t ret.push_back(_(\"k\"));\n\t\tbreak;\n\n\t case 2:\n\t\t\/\/ TRANSLATORS: symbol for \"mebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"MiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"mega bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"MB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"mega\" (best keep untranslated)\n\t\t ret.push_back(_(\"M\"));\n\t\tbreak;\n\n\t case 3:\n\t\t\/\/ TRANSLATORS: symbol for \"gibi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"GiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"giga bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"GB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"giga\" (best keep untranslated)\n\t\t ret.push_back(_(\"G\"));\n\t\tbreak;\n\n\t case 4:\n\t\t\/\/ TRANSLATORS: symbol for \"tebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"TiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"tera bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"TB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"tera\" (best keep untranslated)\n\t\t ret.push_back(_(\"T\"));\n\t\tbreak;\n\n\t case 5:\n\t\t\/\/ TRANSLATORS: symbol for \"pebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"PiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"peta bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"PB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"peta\" (best keep untranslated)\n\t\t ret.push_back(_(\"P\"));\n\t\tbreak;\n\n\t case 6:\n\t\t\/\/ TRANSLATORS: symbol for \"exbi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"EiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"exa bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"EB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"exa\" (best keep untranslated)\n\t\t ret.push_back(_(\"E\"));\n\t\tbreak;\n\t}\n\n\treturn ret;\n }\n\n\n string\n get_suffix(int i, bool classic)\n {\n\treturn classic ? get_all_suffixes(i).front().native : get_all_suffixes(i).front().translated;\n }\n\n\n \/\/ Both byte_to_humanstring and humanstring_to_byte use integer arithmetic\n \/\/ as long as possible to provide exact results for those cases.\n\n\n string\n byte_to_humanstring(unsigned long long size, bool classic, int precision, bool omit_zeroes)\n {\n\tconst locale loc = classic ? locale::classic() : locale();\n\n\t\/\/ Calculate the index of the suffix to use. The index increases by 1\n\t\/\/ when the number of leading zeros decreases by 10.\n\n\tint i = size > 0 ? (64 - (clz(size) + 1)) \/ 10 : 0;\n\n\tif ((i == 0) || (omit_zeroes && is_multiple_of(size, 1ULL << 10 * i)))\n\t{\n\t unsigned long long v = size >> 10 * i;\n\n\t std::ostringstream s;\n\t s.imbue(loc);\n\t s << v << ' ' << get_suffix(i, classic);\n\t return s.str();\n\t}\n\telse\n\t{\n\t long double v = std::ldexp((long double)(size), - 10 * i);\n\n\t std::ostringstream s;\n\t s.imbue(loc);\n\t s.setf(ios::fixed);\n\t s.precision(precision);\n\t s << v << ' ' << get_suffix(i, classic);\n\t return s.str();\n\t}\n }\n\n\n namespace\n {\n\t\/\/ Helper functions to parse a number as int or float, multiply\n\t\/\/ according to the suffix. Do all required error checks.\n\n\tpair<bool, unsigned long long>\n\tparse_i(const string& str, int i, const locale& loc)\n\t{\n\t istringstream s(str);\n\t s.imbue(loc);\n\n\t unsigned long long v;\n\t s >> v;\n\n\t if (!s.eof())\n\t\treturn make_pair(false, 0);\n\n\t if (s.fail())\n\t {\n\t\tif (v == std::numeric_limits<unsigned long long>::max())\n\t\t ST_THROW(OverflowException());\n\n\t\treturn make_pair(false, 0);\n\t }\n\n\t if (v != 0 && str[0] == '-')\n\t\tST_THROW(OverflowException());\n\n\t if (v > 0 && clz(v) < 10 * i)\n\t\tST_THROW(OverflowException());\n\n\t v <<= 10 * i;\n\n\t return make_pair(true, v);\n\t}\n\n\n\tpair<bool, unsigned long long>\n\tparse_f(const string& str, int i, const locale& loc)\n\t{\n\t istringstream s(str);\n\t s.imbue(loc);\n\n\t long double v;\n\t s >> v;\n\n\t if (!s.eof())\n\t\treturn make_pair(false, 0);\n\n\t if (s.fail())\n\t {\n\t\tif (v == std::numeric_limits<long double>::max())\n\t\t ST_THROW(OverflowException());\n\n\t\treturn make_pair(false, 0);\n\t }\n\n\t if (v < 0.0)\n\t\tST_THROW(OverflowException());\n\n\t v = std::round(std::ldexp(v, 10 * i));\n\n\t if (v > std::numeric_limits<unsigned long long>::max())\n\t\tST_THROW(OverflowException());\n\n\t return make_pair(true, v);\n\t}\n\n }\n\n\n unsigned long long\n humanstring_to_byte(const string& str, bool classic)\n {\n\tconst locale loc = classic ? locale::classic() : locale();\n\n\tconst string str_trimmed = boost::trim_copy(str, loc);\n\n\tfor (int i = 0; i < num_suffixes(); ++i)\n\t{\n\t vector<Text> suffixes = get_all_suffixes(i, true, !classic);\n\n\t for (const Text& suffix : suffixes)\n\t {\n\t\tconst string& tmp = classic ? suffix.native : suffix.translated;\n\n\t\tif (boost::iends_with(str_trimmed, tmp, loc))\n\t\t{\n\t\t string number = boost::trim_copy(str_trimmed.substr(0, str_trimmed.size() - tmp.size()), loc);\n\n\t\t pair<bool, unsigned long long> v;\n\n\t\t v = parse_i(number, i, loc);\n\t\t if (v.first)\n\t\t\treturn v.second;\n\n\t\t v = parse_f(number, i, loc);\n\t\t if (v.first)\n\t\t\treturn v.second;\n\t\t}\n\t }\n\t}\n\n\tST_THROW(ParseException(\"failed to parse\", str, \"something like 1 GiB\"));\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Minimum Size Subarray Sum<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Fix HttpListenSocket.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008 Google Inc.\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\/\/ This file provides a stub implementation of most plugin entrypoints.\n\n#include <npapi.h>\n#include \"npn_api.h\"\n#include \"globals_glue.h\"\n\nnamespace glue {\nnamespace globals {\n\nvoid SetLastError(NPP npp, const char *error) {\n}\n\n}\n}\n\nextern \"C\" {\n NPError OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) {\n pluginFuncs->version = 11;\n pluginFuncs->size = sizeof(*pluginFuncs);\n pluginFuncs->newp = NPP_New;\n pluginFuncs->destroy = NPP_Destroy;\n pluginFuncs->setwindow = NPP_SetWindow;\n pluginFuncs->newstream = NPP_NewStream;\n pluginFuncs->destroystream = NPP_DestroyStream;\n pluginFuncs->asfile = NPP_StreamAsFile;\n pluginFuncs->writeready = NPP_WriteReady;\n pluginFuncs->write = NPP_Write;\n pluginFuncs->print = NPP_Print;\n pluginFuncs->event = NPP_HandleEvent;\n pluginFuncs->urlnotify = NPP_URLNotify;\n pluginFuncs->getvalue = NPP_GetValue;\n pluginFuncs->setvalue = NPP_SetValue;\n\n return NPERR_NO_ERROR;\n }\n\n#if defined(OS_WINDOWS) || defined(OS_MACOSX)\n NPError OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs) {\n return InitializeNPNApi(browserFuncs);\n }\n#else\n NPError OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs,\n NPPluginFuncs *pluginFuncs) {\n NPError retval = InitializeNPNApi(browserFuncs);\n if (retval != NPERR_NO_ERROR) return retval;\n NP_GetEntryPoints(pluginFuncs);\n return NPERR_NO_ERROR;\n }\n#endif\n\n NPError OSCALL NP_Shutdown(void) {\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16_t mode,\n int16_t argc, char *argn[], char *argv[],\n NPSavedData *saved) {\n glue::InitializeGlue(instance);\n NPObject *object = glue::CreateStaticNPObject(instance);\n instance->pdata = object;\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_Destroy(NPP instance, NPSavedData **save) {\n NPObject *object = static_cast<NPObject*>(instance->pdata);\n if (object) {\n NPN_ReleaseObject(object);\n instance->pdata = NULL;\n }\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {\n switch (variable) {\n case NPPVpluginScriptableNPObject: {\n void **v = static_cast<void **>(value);\n NPObject *obj = static_cast<NPObject *>(instance->pdata);\n NPN_RetainObject(obj);\n *v = obj;\n break;\n }\n case NPPVpluginNeedsXEmbed:\n *static_cast<NPBool *>(value) = true;\n break;\n default:\n return NPERR_INVALID_PARAM;\n break;\n }\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {\n return NPERR_GENERIC_ERROR;\n }\n\n\n NPError NPP_SetWindow(NPP instance, NPWindow *window) {\n return NPERR_NO_ERROR;\n }\n\n void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) {\n }\n\n int16_t NPP_HandleEvent(NPP instance, void *event) {\n return 0;\n }\n\n NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream,\n NPBool seekable, uint16_t *stype) {\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) {\n return NPERR_NO_ERROR;\n }\n\n int32_t NPP_WriteReady(NPP instance, NPStream *stream) {\n return 0;\n }\n\n int32_t NPP_Write(NPP instance, NPStream *stream, int32_t offset, int32_t len,\n void *buffer) {\n return 0;\n }\n\n void NPP_Print(NPP instance, NPPrint *platformPrint) {\n }\n\n void NPP_URLNotify(NPP instance, const char *url, NPReason reason,\n void *notifyData) {\n }\n} \/\/ extern \"C\"\n<commit_msg>nixysa\/mac: Use CG\/Cocoa rendering model<commit_after>\/\/ Copyright 2008 Google Inc.\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\/\/ This file provides a stub implementation of most plugin entrypoints.\n\n#include <npapi.h>\n#include \"npn_api.h\"\n#include \"globals_glue.h\"\n\nnamespace glue {\nnamespace globals {\n\nvoid SetLastError(NPP npp, const char *error) {\n}\n\n}\n}\n\nextern \"C\" {\n NPError OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) {\n pluginFuncs->version = 11;\n pluginFuncs->size = sizeof(*pluginFuncs);\n pluginFuncs->newp = NPP_New;\n pluginFuncs->destroy = NPP_Destroy;\n pluginFuncs->setwindow = NPP_SetWindow;\n pluginFuncs->newstream = NPP_NewStream;\n pluginFuncs->destroystream = NPP_DestroyStream;\n pluginFuncs->asfile = NPP_StreamAsFile;\n pluginFuncs->writeready = NPP_WriteReady;\n pluginFuncs->write = NPP_Write;\n pluginFuncs->print = NPP_Print;\n pluginFuncs->event = NPP_HandleEvent;\n pluginFuncs->urlnotify = NPP_URLNotify;\n pluginFuncs->getvalue = NPP_GetValue;\n pluginFuncs->setvalue = NPP_SetValue;\n\n return NPERR_NO_ERROR;\n }\n\n#if defined(OS_WINDOWS) || defined(OS_MACOSX)\n NPError OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs) {\n return InitializeNPNApi(browserFuncs);\n }\n#else\n NPError OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs,\n NPPluginFuncs *pluginFuncs) {\n NPError retval = InitializeNPNApi(browserFuncs);\n if (retval != NPERR_NO_ERROR) return retval;\n NP_GetEntryPoints(pluginFuncs);\n return NPERR_NO_ERROR;\n }\n#endif\n\n NPError OSCALL NP_Shutdown(void) {\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16_t mode,\n int16_t argc, char *argn[], char *argv[],\n NPSavedData *saved) {\n glue::InitializeGlue(instance);\n NPObject *object = glue::CreateStaticNPObject(instance);\n instance->pdata = object;\n\n#if defined(OS_MACOSX)\n \/\/ On the Mac, starting from Google Chrome 22, we need to negotiate\n \/\/ CoreGraphics and Cocoa even though we don't use it.\n \/\/ See: http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=134761\n \/\/ Code ported from http:\/\/gwt-code-reviews.appspot.com\/1844803\/\n\n \/\/ Select the right drawing model if necessary\n NPBool supports_core_graphics = false;\n if (NPN_GetValue(instance, NPNVsupportsCoreGraphicsBool,\n &supports_core_graphics) == NPERR_NO_ERROR &&\n supports_core_graphics) {\n NPN_SetValue(instance, NPPVpluginDrawingModel,\n reinterpret_cast<void*>(NPDrawingModelCoreGraphics));\n }\n \/\/ Select the Cocoa event model\n NPBool supports_cocoa_events = false;\n if (NPN_GetValue(instance, NPNVsupportsCocoaBool,\n &supports_cocoa_events) == NPERR_NO_ERROR &&\n supports_cocoa_events) {\n NPN_SetValue(instance, NPPVpluginEventModel,\n reinterpret_cast<void*>(NPEventModelCocoa));\n }\n#endif\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_Destroy(NPP instance, NPSavedData **save) {\n NPObject *object = static_cast<NPObject*>(instance->pdata);\n if (object) {\n NPN_ReleaseObject(object);\n instance->pdata = NULL;\n }\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {\n switch (variable) {\n case NPPVpluginScriptableNPObject: {\n void **v = static_cast<void **>(value);\n NPObject *obj = static_cast<NPObject *>(instance->pdata);\n NPN_RetainObject(obj);\n *v = obj;\n break;\n }\n case NPPVpluginNeedsXEmbed:\n *static_cast<NPBool *>(value) = true;\n break;\n default:\n return NPERR_INVALID_PARAM;\n break;\n }\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {\n return NPERR_GENERIC_ERROR;\n }\n\n\n NPError NPP_SetWindow(NPP instance, NPWindow *window) {\n return NPERR_NO_ERROR;\n }\n\n void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) {\n }\n\n int16_t NPP_HandleEvent(NPP instance, void *event) {\n return 0;\n }\n\n NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream,\n NPBool seekable, uint16_t *stype) {\n return NPERR_NO_ERROR;\n }\n\n NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) {\n return NPERR_NO_ERROR;\n }\n\n int32_t NPP_WriteReady(NPP instance, NPStream *stream) {\n return 0;\n }\n\n int32_t NPP_Write(NPP instance, NPStream *stream, int32_t offset, int32_t len,\n void *buffer) {\n return 0;\n }\n\n void NPP_Print(NPP instance, NPPrint *platformPrint) {\n }\n\n void NPP_URLNotify(NPP instance, const char *url, NPReason reason,\n void *notifyData) {\n }\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>#include \"MotionControl.hpp\"\n#include <SystemState.hpp>\n#include <RobotConfig.hpp>\n#include <Robot.hpp>\n#include <Utils.hpp>\n#include \"TrapezoidalMotion.hpp\"\n#include <Geometry2d\/Util.hpp>\n#include <planning\/MotionInstant.hpp>\n\n#include <cmath>\n#include <stdio.h>\n#include <algorithm>\n\nusing namespace std;\nusing namespace Geometry2d;\nusing namespace Planning;\n\n#pragma mark Config Variables\n\nREGISTER_CONFIGURABLE(MotionControl);\n\nConfigDouble* MotionControl::_max_acceleration;\nConfigDouble* MotionControl::_max_velocity;\n\nvoid MotionControl::createConfiguration(Configuration* cfg) {\n _max_acceleration =\n new ConfigDouble(cfg, \"MotionControl\/Max Acceleration\", 1.5);\n _max_velocity = new ConfigDouble(cfg, \"MotionControl\/Max Velocity\", 2.0);\n}\n\n#pragma mark MotionControl\n\nMotionControl::MotionControl(OurRobot* robot) : _angleController(0, 0, 0, 50) {\n _robot = robot;\n\n _robot->radioTx.set_robot_id(_robot->shell());\n _lastCmdTime = -1;\n}\n\nvoid MotionControl::run() {\n if (!_robot) return;\n\n const MotionConstraints& constraints = _robot->motionConstraints();\n\n \/\/ update PID parameters\n _positionXController.kp = *_robot->config->translation.p;\n _positionXController.ki = *_robot->config->translation.i;\n _positionXController.setWindup(*_robot->config->translation.i_windup);\n _positionXController.kd = *_robot->config->translation.d;\n _positionYController.kp = *_robot->config->translation.p;\n _positionYController.ki = *_robot->config->translation.i;\n _positionYController.setWindup(*_robot->config->translation.i_windup);\n _positionYController.kd = *_robot->config->translation.d;\n _angleController.kp = *_robot->config->rotation.p;\n _angleController.ki = *_robot->config->rotation.i;\n _angleController.kd = *_robot->config->rotation.d;\n\n\n float timeIntoPath =\n ((float)(RJ::timestamp() - _robot->path().startTime())) *\n TimestampToSecs +\n 1.0 \/ 60.0;\n\n \/\/ evaluate path - where should we be right now?\n boost::optional<RobotInstant> optTarget =\n _robot->path().evaluate(timeIntoPath);\n\n\n \/\/ Angle control \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n float targetW = 0;\n auto& rotationCommand = _robot->rotationCommand();\n const auto& rotationConstraints = _robot->rotationConstraints();\n\n boost::optional<Geometry2d::Point> targetPt;\n const auto& motionCommand = _robot->motionCommand();\n if (motionCommand->getCommandType() == MotionCommand::Pivot) {\n PivotCommand command = *static_cast<PivotCommand*>(motionCommand.get());\n targetPt = command.pivotTarget;\n }\n\n\/*\n switch (rotationCommand.getCommandType()) {\n case RotationCommand::FacePoint:\n targetPt = static_cast<const Planning::FacePointCommand&>(rotationCommand).targetPos;\n break;\n case RotationCommand::None:\n \/\/ do nothing\n break;\n default:\n debugThrow(\"RotationCommand Not implemented\");\n break;\n }\n *\/\n float targetAngleFinal = 0;\n if (optTarget) {\n std::cout<<\"optTarget\"<<std::endl;\n if (optTarget->angle) {\n\n std::cout<<\"optTarget->angle\"<<std::endl;\n if (optTarget->angle->angle) {\n\n std::cout<<\"optTarget->final\"<<std::endl;\n targetAngleFinal = *optTarget->angle->angle;\n std::cout<<targetAngleFinal<<std::endl;\n }\n }\n }\n if (targetPt) {\n \/\/ fixing the angle ensures that we don't go the long way around to get\n \/\/ to our final angle\n std::cout<<\"targetPt\"<<std::endl;\n targetAngleFinal = (*targetPt - _robot->pos).angle();\n }\n\n\n float angleError = fixAngleRadians(targetAngleFinal - _robot->angle);\n\n std::cout<<\"angleError:\"<< angleError<<std::endl;\n targetW = _angleController.run(angleError);\n\n \/\/ limit W\n if (abs(targetW) > (rotationConstraints.maxSpeed)) {\n if (targetW > 0) {\n targetW = (rotationConstraints.maxSpeed);\n } else {\n targetW = -(rotationConstraints.maxSpeed);\n }\n }\n\n \/*\n _robot->addText(QString(\"targetW: %1\").arg(targetW));\n _robot->addText(QString(\"angleError: %1\").arg(angleError));\n _robot->addText(QString(\"targetGlobalAngle: %1\").arg(targetAngleFinal));\n _robot->addText(QString(\"angle: %1\").arg(_robot->angle));\n *\/\n _targetAngleVel(targetW);\n \/\/_targetAngleVel(targetW);\n\n \/\/ handle body velocity for pivot command\n if (motionCommand->getCommandType() == MotionCommand::Pivot) {\n float r = Robot_Radius;\n const float FudgeFactor = *_robot->config->pivotVelMultiplier;\n float speed = RadiansToDegrees(r * targetW * FudgeFactor);\n Point vel(speed, 0);\n\n \/\/ the robot body coordinate system is wierd...\n vel.rotate(-M_PI_2);\n\n _targetBodyVel(vel);\n\n return; \/\/ pivot handles both angle and position\n }\n\n \/\/ Position control \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MotionInstant target;\n \/\/ if no target position is given, we don't have a path to follow\n\/\/ if (!_robot->path()) {\n\/\/ _targetBodyVel(Point(0, 0));\n\/\/ std::cout<<\"No Path\"<<std::endl;\n\/\/ debugThrow(\"No Path set\");\n\/\/ return;\n\/\/ } else {\n \/\/\n \/\/ Path following\n \/\/\n\n \/\/ convert from microseconds to seconds\n\n if (!optTarget) {\n \/\/ use the path end if our timeIntoPath is greater than the duration\n target.vel = Point();\n target.pos = _robot->path().end().motion.pos;\n } else {\n target = optTarget->motion;\n }\n \/\/ tracking error\n Point posError = target.pos - _robot->pos;\n\n \/\/ acceleration factor\n Point acceleration;\n boost::optional<RobotInstant> nextTarget =\n _robot->path().evaluate(timeIntoPath + 1.0 \/ 60.0);\n if (nextTarget) {\n acceleration = (nextTarget->motion.vel - target.vel) \/ 60.0f;\n } else {\n acceleration = {0, 0};\n }\n Point accelFactor =\n acceleration * 60.0f * (*_robot->config->accelerationMultiplier);\n\n target.vel += accelFactor;\n\n \/\/ PID on position\n target.vel.x += _positionXController.run(posError.x);\n target.vel.y += _positionYController.run(posError.y);\n\n \/\/ draw target pt\n _robot->state()->drawCircle(target.pos, .04, Qt::red, \"MotionControl\");\n _robot->state()->drawLine(target.pos, target.pos + target.vel, Qt::blue,\n \"MotionControl\");\n\n \/\/ convert from world to body coordinates\n target.vel = target.vel.rotated(-_robot->angle);\n\/\/ }\n\n this->_targetBodyVel(target.vel);\n}\n\nvoid MotionControl::stopped() {\n _targetBodyVel(Point(0, 0));\n _targetAngleVel(0);\n}\n\nvoid MotionControl::_targetAngleVel(float angleVel) {\n \/\/ velocity multiplier\n angleVel *= *_robot->config->angleVelMultiplier;\n\n \/\/ convert units\n angleVel = RadiansToDegrees(angleVel);\n\n \/\/ If the angular speed is very low, it won't make the robot move at all, so\n \/\/ we make sure it's above a threshold value\n float minEffectiveAngularSpeed = *_robot->config->minEffectiveAngularSpeed;\n if (std::abs(angleVel) < minEffectiveAngularSpeed &&\n std::abs(angleVel) > 0.2) {\n angleVel =\n angleVel > 0 ? minEffectiveAngularSpeed : -minEffectiveAngularSpeed;\n }\n\n \/\/ the robot firmware still speaks degrees, so that's how we send it over\n _robot->radioTx.set_body_w(angleVel);\n}\n\nvoid MotionControl::_targetBodyVel(Point targetVel) {\n \/\/ Limit Velocity\n targetVel.clamp(*_max_velocity);\n\n \/\/ Limit Acceleration\n if (_lastCmdTime == -1) {\n targetVel.clamp(*_max_acceleration);\n } else {\n float dt = (float)((RJ::timestamp() - _lastCmdTime) \/ 1000000.0f);\n Point targetAccel = (targetVel - _lastVelCmd) \/ dt;\n targetAccel.clamp(*_max_acceleration);\n\n targetVel = _lastVelCmd + targetAccel * dt;\n }\n\n \/\/ make sure we don't send any bad values\n if (isnan(targetVel.x) || isnan(targetVel.y)) {\n targetVel = Point(0, 0);\n }\n\n \/\/ track these values so we can limit acceleration\n _lastVelCmd = targetVel;\n _lastCmdTime = RJ::timestamp();\n\n \/\/ velocity multiplier\n targetVel *= *_robot->config->velMultiplier;\n\n \/\/ if the velocity is nonzero, make sure it's not so small that the robot\n \/\/ doesn't even move\n float minEffectiveVelocity = *_robot->config->minEffectiveVelocity;\n if (targetVel.mag() < minEffectiveVelocity && targetVel.mag() > 0.05) {\n targetVel = targetVel.normalized() * minEffectiveVelocity;\n }\n\n \/\/ set radioTx values\n _robot->radioTx.set_body_x(targetVel.x);\n _robot->radioTx.set_body_y(targetVel.y);\n}\n<commit_msg>Change it so that the Motion Planner uses the End Motion and direction if the path is finished.<commit_after>#include \"MotionControl.hpp\"\n#include <SystemState.hpp>\n#include <RobotConfig.hpp>\n#include <Robot.hpp>\n#include <Utils.hpp>\n#include \"TrapezoidalMotion.hpp\"\n#include <Geometry2d\/Util.hpp>\n#include <planning\/MotionInstant.hpp>\n\n#include <cmath>\n#include <stdio.h>\n#include <algorithm>\n\nusing namespace std;\nusing namespace Geometry2d;\nusing namespace Planning;\n\n#pragma mark Config Variables\n\nREGISTER_CONFIGURABLE(MotionControl);\n\nConfigDouble* MotionControl::_max_acceleration;\nConfigDouble* MotionControl::_max_velocity;\n\nvoid MotionControl::createConfiguration(Configuration* cfg) {\n _max_acceleration =\n new ConfigDouble(cfg, \"MotionControl\/Max Acceleration\", 1.5);\n _max_velocity = new ConfigDouble(cfg, \"MotionControl\/Max Velocity\", 2.0);\n}\n\n#pragma mark MotionControl\n\nMotionControl::MotionControl(OurRobot* robot) : _angleController(0, 0, 0, 50) {\n _robot = robot;\n\n _robot->radioTx.set_robot_id(_robot->shell());\n _lastCmdTime = -1;\n}\n\nvoid MotionControl::run() {\n if (!_robot) return;\n\n const MotionConstraints& constraints = _robot->motionConstraints();\n\n \/\/ update PID parameters\n _positionXController.kp = *_robot->config->translation.p;\n _positionXController.ki = *_robot->config->translation.i;\n _positionXController.setWindup(*_robot->config->translation.i_windup);\n _positionXController.kd = *_robot->config->translation.d;\n _positionYController.kp = *_robot->config->translation.p;\n _positionYController.ki = *_robot->config->translation.i;\n _positionYController.setWindup(*_robot->config->translation.i_windup);\n _positionYController.kd = *_robot->config->translation.d;\n _angleController.kp = *_robot->config->rotation.p;\n _angleController.ki = *_robot->config->rotation.i;\n _angleController.kd = *_robot->config->rotation.d;\n\n\n float timeIntoPath =\n ((float)(RJ::timestamp() - _robot->path().startTime())) *\n TimestampToSecs +\n 1.0 \/ 60.0;\n\n \/\/ evaluate path - where should we be right now?\n boost::optional<RobotInstant> optTarget =\n _robot->path().evaluate(timeIntoPath);\n if (!optTarget) {\n optTarget = _robot->path().end();\n }\n\n\n \/\/ Angle control \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n float targetW = 0;\n auto& rotationCommand = _robot->rotationCommand();\n const auto& rotationConstraints = _robot->rotationConstraints();\n\n boost::optional<Geometry2d::Point> targetPt;\n const auto& motionCommand = _robot->motionCommand();\n\n float targetAngleFinal = 0;\n if (motionCommand->getCommandType() == MotionCommand::Pivot) {\n PivotCommand command = *static_cast<PivotCommand*>(motionCommand.get());\n targetPt = command.pivotTarget;\n } else {\n if (optTarget) {\n std::cout << \"optTarget\" << std::endl;\n if (optTarget->angle) {\n\n std::cout << \"optTarget->angle\" << std::endl;\n if (optTarget->angle->angle) {\n\n std::cout << \"optTarget->final\" << std::endl;\n targetAngleFinal = *optTarget->angle->angle;\n std::cout << targetAngleFinal << std::endl;\n }\n }\n }\n }\n if (targetPt) {\n \/\/ fixing the angle ensures that we don't go the long way around to get\n \/\/ to our final angle\n std::cout<<\"targetPt\"<<std::endl;\n targetAngleFinal = (*targetPt - _robot->pos).angle();\n }\n\n\n float angleError = fixAngleRadians(targetAngleFinal - _robot->angle);\n\n std::cout<<\"angleError:\"<< angleError<<std::endl;\n targetW = _angleController.run(angleError);\n\n \/\/ limit W\n if (abs(targetW) > (rotationConstraints.maxSpeed)) {\n if (targetW > 0) {\n targetW = (rotationConstraints.maxSpeed);\n } else {\n targetW = -(rotationConstraints.maxSpeed);\n }\n }\n\n \/*\n _robot->addText(QString(\"targetW: %1\").arg(targetW));\n _robot->addText(QString(\"angleError: %1\").arg(angleError));\n _robot->addText(QString(\"targetGlobalAngle: %1\").arg(targetAngleFinal));\n _robot->addText(QString(\"angle: %1\").arg(_robot->angle));\n *\/\n _targetAngleVel(targetW);\n \/\/_targetAngleVel(targetW);\n\n \/\/ handle body velocity for pivot command\n if (motionCommand->getCommandType() == MotionCommand::Pivot) {\n float r = Robot_Radius;\n const float FudgeFactor = *_robot->config->pivotVelMultiplier;\n float speed = RadiansToDegrees(r * targetW * FudgeFactor);\n Point vel(speed, 0);\n\n \/\/ the robot body coordinate system is wierd...\n vel.rotate(-M_PI_2);\n\n _targetBodyVel(vel);\n\n return; \/\/ pivot handles both angle and position\n }\n\n \/\/ Position control \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MotionInstant target;\n \/\/ if no target position is given, we don't have a path to follow\n\/\/ if (!_robot->path()) {\n\/\/ _targetBodyVel(Point(0, 0));\n\/\/ std::cout<<\"No Path\"<<std::endl;\n\/\/ debugThrow(\"No Path set\");\n\/\/ return;\n\/\/ } else {\n \/\/\n \/\/ Path following\n \/\/\n\n \/\/ convert from microseconds to seconds\n\n if (!optTarget) {\n \/\/ use the path end if our timeIntoPath is greater than the duration\n target.vel = Point();\n target.pos = _robot->path().end().motion.pos;\n } else {\n target = optTarget->motion;\n }\n \/\/ tracking error\n Point posError = target.pos - _robot->pos;\n\n \/\/ acceleration factor\n Point acceleration;\n boost::optional<RobotInstant> nextTarget =\n _robot->path().evaluate(timeIntoPath + 1.0 \/ 60.0);\n if (nextTarget) {\n acceleration = (nextTarget->motion.vel - target.vel) \/ 60.0f;\n } else {\n acceleration = {0, 0};\n }\n Point accelFactor =\n acceleration * 60.0f * (*_robot->config->accelerationMultiplier);\n\n target.vel += accelFactor;\n\n \/\/ PID on position\n target.vel.x += _positionXController.run(posError.x);\n target.vel.y += _positionYController.run(posError.y);\n\n \/\/ draw target pt\n _robot->state()->drawCircle(target.pos, .04, Qt::red, \"MotionControl\");\n _robot->state()->drawLine(target.pos, target.pos + target.vel, Qt::blue,\n \"MotionControl\");\n\n \/\/ convert from world to body coordinates\n target.vel = target.vel.rotated(-_robot->angle);\n\/\/ }\n\n this->_targetBodyVel(target.vel);\n}\n\nvoid MotionControl::stopped() {\n _targetBodyVel(Point(0, 0));\n _targetAngleVel(0);\n}\n\nvoid MotionControl::_targetAngleVel(float angleVel) {\n \/\/ velocity multiplier\n angleVel *= *_robot->config->angleVelMultiplier;\n\n \/\/ convert units\n angleVel = RadiansToDegrees(angleVel);\n\n \/\/ If the angular speed is very low, it won't make the robot move at all, so\n \/\/ we make sure it's above a threshold value\n float minEffectiveAngularSpeed = *_robot->config->minEffectiveAngularSpeed;\n if (std::abs(angleVel) < minEffectiveAngularSpeed &&\n std::abs(angleVel) > 0.2) {\n angleVel =\n angleVel > 0 ? minEffectiveAngularSpeed : -minEffectiveAngularSpeed;\n }\n\n \/\/ the robot firmware still speaks degrees, so that's how we send it over\n _robot->radioTx.set_body_w(angleVel);\n}\n\nvoid MotionControl::_targetBodyVel(Point targetVel) {\n \/\/ Limit Velocity\n targetVel.clamp(*_max_velocity);\n\n \/\/ Limit Acceleration\n if (_lastCmdTime == -1) {\n targetVel.clamp(*_max_acceleration);\n } else {\n float dt = (float)((RJ::timestamp() - _lastCmdTime) \/ 1000000.0f);\n Point targetAccel = (targetVel - _lastVelCmd) \/ dt;\n targetAccel.clamp(*_max_acceleration);\n\n targetVel = _lastVelCmd + targetAccel * dt;\n }\n\n \/\/ make sure we don't send any bad values\n if (isnan(targetVel.x) || isnan(targetVel.y)) {\n targetVel = Point(0, 0);\n }\n\n \/\/ track these values so we can limit acceleration\n _lastVelCmd = targetVel;\n _lastCmdTime = RJ::timestamp();\n\n \/\/ velocity multiplier\n targetVel *= *_robot->config->velMultiplier;\n\n \/\/ if the velocity is nonzero, make sure it's not so small that the robot\n \/\/ doesn't even move\n float minEffectiveVelocity = *_robot->config->minEffectiveVelocity;\n if (targetVel.mag() < minEffectiveVelocity && targetVel.mag() > 0.05) {\n targetVel = targetVel.normalized() * minEffectiveVelocity;\n }\n\n \/\/ set radioTx values\n _robot->radioTx.set_body_x(targetVel.x);\n _robot->radioTx.set_body_y(targetVel.y);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: snapShot.C,v 1.21 2001\/03\/11 19:32:31 anker Exp $\n\n\/\/ BALL includes \n#include <BALL\/MOLMEC\/COMMON\/snapShot.h>\n#include <BALL\/CONCEPT\/XDRPersistenceManager.h>\n\n\/\/ STL includes \n#include <algorithm>\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\t\/\/ The default constructor of the SnapShot class. \n SnapShot::SnapShot()\n\t\tthrow()\n\t\t:\tindex_(0),\n\t\t\tnumber_of_atoms_(0),\n\t\t\tpotential_energy_(0.0),\n\t\t\tkinetic_energy_(0.0),\n\t\t\tatom_positions_(0),\n\t\t\tatom_velocities_(0),\n\t\t\tatom_forces_(0),\n\t\t\tvalid_(false)\n\t{\n\t}\n\n\n\t\/\/ The copy constructor of the SnapShot class. \n\tSnapShot::SnapShot (const SnapShot& snapshot)\n\t\tthrow()\n\t\t:\tindex_(snapshot.index_),\n\t\t\tnumber_of_atoms_(snapshot.number_of_atoms_),\n\t\t\tpotential_energy_(snapshot.potential_energy_),\n\t\t\tkinetic_energy_(snapshot.kinetic_energy_),\n\t\t\tatom_positions_(snapshot.atom_positions_),\n\t\t\tatom_velocities_(snapshot.atom_velocities_),\n\t\t\tatom_forces_(snapshot.atom_forces_),\n\t\t\tvalid_(snapshot.valid_)\n\t{\n\t}\n\n\n\t\/\/ The destructor just deletes all STL components (superfluous and just\n\t\/\/ for clarity) \n\tSnapShot::~SnapShot()\n\t\tthrow()\n\t{\n\t\tclear();\n\n\t\tvalid_ = false;\n\t}\n\n\n\t\/\/ The assignment operator \n\tconst SnapShot& SnapShot::operator = (const SnapShot& snapshot)\n\t\tthrow()\n\t{\n\t\tvalid_ = snapshot.valid_;\n\t\tindex_ = snapshot.index_;\n\t\tnumber_of_atoms_ = snapshot.number_of_atoms_;\n\t\tpotential_energy_ = snapshot.potential_energy_;\n\t\tkinetic_energy_ = snapshot.kinetic_energy_;\n\t\tatom_positions_ = snapshot.atom_positions_;\n\t\tatom_velocities_ = snapshot.atom_velocities_;\n\t\tatom_forces_ = snapshot.atom_forces_;\n\n\t\treturn *this;\n\t}\n\n\n\tvoid SnapShot::clear()\n\t\tthrow()\n\t{\n\t\tvalid_ = false;\n\t\tindex_ = 0;\n\t\tnumber_of_atoms_ = 0;\n\t\tpotential_energy_ = 0.0;\n\t\tkinetic_energy_ = 0.0;\n\n\t\tatom_positions_.clear();\n\t\tatom_velocities_.clear();\n\t\tatom_forces_.clear();\n\t}\n\n\n\tbool SnapShot::operator == (const SnapShot& snapshot) const\n\t\tthrow()\n\t{\n\t\treturn ((valid_ == snapshot.valid_)\n\t\t\t&& (index_ == snapshot.index_)\n\t\t\t&& (number_of_atoms_ == snapshot.number_of_atoms_)\n\t\t\t&& (potential_energy_ == snapshot.potential_energy_)\n\t\t\t&& (kinetic_energy_ == snapshot.kinetic_energy_)\n\t\t\t&& (atom_positions_ == snapshot.atom_positions_)\n\t\t\t&& (atom_velocities_ == snapshot.atom_velocities_)\n\t\t\t&& (atom_forces_ == snapshot.atom_forces_));\n\t}\n\n\n\tbool SnapShot::isValid() const\n\t\tthrow()\n\t{\n\t\treturn valid_;\n\t}\n\n\t\n\tvoid SnapShot::setIndex(Size index)\n\t\tthrow()\n\t{\n\t\tindex_ = index;\n\t}\n\n\n\tSize SnapShot::getIndex() const\n\t\tthrow()\n\t{\n\t\treturn index_;\n\t}\n\n\n\tvoid SnapShot::setNumberOfAtoms(Size number_of_atoms)\n\t\tthrow()\n\t{\n\t\tnumber_of_atoms_ = number_of_atoms;\n\t}\n\n\n\tSize SnapShot::getNumberOfAtoms() const\n\t\tthrow()\n\t{\n\t\treturn number_of_atoms_;\n\t}\n\n\n\tDoubleReal SnapShot::getPotentialEnergy() const\n\t\tthrow()\n\t{\n\t\treturn potential_energy_;\n\t}\n\n\n\tvoid SnapShot::setPotentialEnergy(DoubleReal potential_energy) \n\t\tthrow()\n\t{\n\t\tpotential_energy_ = potential_energy;\n\t}\n\n\n\tDoubleReal SnapShot::getKineticEnergy() const\n\t\tthrow()\n\t{\n\t\treturn kinetic_energy_;\n\t}\n\n\n\tvoid SnapShot::setKineticEnergy(DoubleReal kinetic_energy)\n\t\tthrow()\n\t{\n\t\tkinetic_energy_ = kinetic_energy;\n\t}\n\n\n\tvoid SnapShot::setAtomPositions(const ::std::vector<Vector3>& atom_postions)\n\t\tthrow()\n\t{\n\t\tatom_positions_ = atom_postions;\n\t}\n\n\n\tconst ::std::vector<Vector3>& SnapShot::getAtomPositions() const\n\t\tthrow()\n\t{\n\t\treturn atom_positions_;\n\t}\n\n\n\tvoid SnapShot::setAtomVelocitites(const ::std::vector<Vector3>& atom_velocities)\n\t\tthrow()\n\t{\n\t\tatom_velocities_ = atom_velocities;\n\t}\n\n\n\tconst ::std::vector<Vector3>& SnapShot::getAtomVelocities() const\n\t\tthrow()\n\t{\n\t\treturn atom_velocities_;\n\t}\n\n\n\tvoid SnapShot::setAtomForces(const ::std::vector<Vector3>& atom_forces)\n\t\tthrow()\n\t{\n\t\tatom_forces_ = atom_forces;\n\t}\n\n\n\tconst ::std::vector<Vector3>& SnapShot::getAtomForces() const\n\t\tthrow()\n\t{\n\t\treturn atom_forces_;\n\t}\n\n\n\tvoid SnapShot::takeSnapShot(const System& system)\n\t\tthrow(Exception::OutOfMemory)\n\t{\n\t\tnumber_of_atoms_ = system.countAtoms();\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\t\/\/ reserve memory\n\t\tatom_positions_.resize(number_of_atoms_);\n\t\tatom_velocities_.resize(number_of_atoms_);\n\t\tatom_forces_.resize(number_of_atoms_);\n\t\t\n\t\t\/\/ This is the data section of the snapshot object \n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_positions_[i] = atom_it->getPosition();\n\t\t\tatom_velocities_[i] = atom_it->getVelocity();\n\t\t\tatom_forces_[i] = atom_it->getForce();\n\t\t}\n\t}\n\n\n\tvoid SnapShot::applySnapShot(System& system) const\n\t\tthrow()\n\t{\n\t\tif (system.countAtoms() != number_of_atoms_)\n\t\t{\n\t\t\tLog.error () << \"SnapShot::applySnapShot(): \"\n\t\t\t\t<< \"Atom counts do not match.\" << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_it->setPosition(atom_positions_[i]);\n\t\t\tatom_it->setVelocity(atom_velocities_[i]);\n\t\t\tatom_it->setForce(atom_forces_[i]);\n\t\t}\n\t}\n\n\n\tvoid SnapShot::getAtomPositions(const System& system)\n\t\tthrow(Exception::OutOfMemory)\n\t{\n\t\t\/\/ obtain the number of atoms\n\t\tnumber_of_atoms_ = system.countAtoms();\n\n\t\t\/\/ reserve memory \n\t\tatom_positions_.resize(number_of_atoms_);\n\n\t\t\/\/ copy data\n\t\tAtomIterator atom_it = system.beginAtom();\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_positions_[i] = atom_it->getPosition();\n\t\t}\n\t}\n\n\n\tvoid SnapShot::setAtomPositions(System& system) const\n\t\tthrow()\n\t{\n\t\tif (system.countAtoms() != number_of_atoms_)\n\t\t{\n\t\t\tLog.error () << \"SnapShot::applySnapShot(): \"\n\t\t\t\t<< \"Atom counts do not match.\" << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_it->setPosition(atom_positions_[i]);\n\t\t}\n\t}\n\n\n\tvoid SnapShot::getAtomVelocities(const System& system)\n\t\tthrow(Exception::OutOfMemory)\n\t{\n\t\tnumber_of_atoms_ = system.countAtoms();\n\t\tatom_velocities_.resize(number_of_atoms_);\n\t\tAtomIterator atom_it = system.beginAtom();\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_velocities_[i] = atom_it->getVelocity();\n\t\t}\n\t}\n\n\n\tvoid SnapShot::setAtomVelocitites(System& system) const\n\t\tthrow()\n\t{\n\t\tif (system.countAtoms() != number_of_atoms_)\n\t\t{\n\t\t\tLog.error () << \"SnapShot::applySnapShot(): \"\n\t\t\t\t<< \"Atom counts do not match.\" << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\t\/\/ This is the data section of the snapshot object \n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_it->setVelocity(atom_velocities_[i]);\n\t\t}\n\t}\n\n\n\tvoid SnapShot::getAtomForces(const System& system)\n\t\tthrow(Exception::OutOfMemory)\n\t{\n\t\tnumber_of_atoms_ = system.countAtoms();\n\t\tatom_forces_.resize(number_of_atoms_);\n\t\tAtomIterator atom_it = system.beginAtom();\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_forces_[i] = atom_it->getForce();\n\t\t}\n\t}\n\n\n\tvoid SnapShot::setAtomForces(System& system) const\n\t\tthrow()\n\t{\n\t\tif (system.countAtoms() != number_of_atoms_)\n\t\t{\n\t\t\tLog.error () << \"SnapShot::applySnapShot(): \"\n\t\t\t\t<< \"Atom counts do not match.\" << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\t\/\/ This is the data section of the snapshot object \n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_it->setForce(atom_forces_[i]);\n\t\t}\n\t}\n\n\n\t::std::ostream& operator << (::std::ostream& os, const SnapShot& ss)\n\t{\n\t\tos << ss.getNumberOfAtoms() << endl;\n\n\t\tvector<Vector3> data = ss.getAtomPositions();\n\n\t\tvector<Vector3>::const_iterator it = data.begin();\n\t\tfor (; it != data.end(); ++it)\n\t\t{\n\t\t\tos << *it << endl;\n\t\t}\n\n\t\tdata = ss.getAtomVelocities();\n\t\tfor (it = data.begin(); it != data.end(); ++it)\n\t\t{\n\t\t\tos << *it << endl;\n\t\t}\n\n\t\tdata = ss.getAtomForces();\n\t\tfor (it = data.begin(); it != data.end(); ++it)\n\t\t{\n\t\t\tos << *it << endl;\n\t\t}\n\t\treturn os;\n\t}\n\n\n\t::std::istream& operator >> (::std::istream& is, SnapShot& ss)\n\t{\n\t\t\/\/ BAUSTELLE:\n\t\t\/\/ this istream does not check anything!\n\n\t\tSize number;\n\t\tis >> number;\n\n\t\tvector<Vector3> data;\n\t\tdata.resize(number);\n\n\t\tfor (Size i = 0; i < number; ++i)\n\t\t{\n\t\t\tis >> data[i];\n\t\t}\n\t\tss.setAtomPositions(data);\n\n\t\tfor (Size i = 0; i < number; ++i)\n\t\t{\n\t\t\tis >> data[i];\n\t\t}\n\t\tss.setAtomVelocitites(data);\n\n\t\tfor (Size i = 0; i < number; ++i)\n\t\t{\n\t\t\tis >> data[i];\n\t\t}\n\t\tss.setAtomForces(data);\n\t\treturn is;\n\t}\n\n}\t\/\/ end of namespace BALL\n<commit_msg>fixed: no sigsegv anymore because of accessing non-existant atom data fixed: improved diagnostic output in error cases<commit_after>\/\/ $Id: snapShot.C,v 1.22 2001\/03\/21 16:23:33 anker Exp $\n\n\/\/ BALL includes \n#include <BALL\/MOLMEC\/COMMON\/snapShot.h>\n#include <BALL\/CONCEPT\/XDRPersistenceManager.h>\n\n\/\/ STL includes \n#include <algorithm>\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\t\/\/ The default constructor of the SnapShot class. \n SnapShot::SnapShot()\n\t\tthrow()\n\t\t:\tindex_(0),\n\t\t\tnumber_of_atoms_(0),\n\t\t\tpotential_energy_(0.0),\n\t\t\tkinetic_energy_(0.0),\n\t\t\tatom_positions_(0),\n\t\t\tatom_velocities_(0),\n\t\t\tatom_forces_(0),\n\t\t\tvalid_(false)\n\t{\n\t}\n\n\n\t\/\/ The copy constructor of the SnapShot class. \n\tSnapShot::SnapShot (const SnapShot& snapshot)\n\t\tthrow()\n\t\t:\tindex_(snapshot.index_),\n\t\t\tnumber_of_atoms_(snapshot.number_of_atoms_),\n\t\t\tpotential_energy_(snapshot.potential_energy_),\n\t\t\tkinetic_energy_(snapshot.kinetic_energy_),\n\t\t\tatom_positions_(snapshot.atom_positions_),\n\t\t\tatom_velocities_(snapshot.atom_velocities_),\n\t\t\tatom_forces_(snapshot.atom_forces_),\n\t\t\tvalid_(snapshot.valid_)\n\t{\n\t}\n\n\n\t\/\/ The destructor just deletes all STL components (superfluous and just\n\t\/\/ for clarity) \n\tSnapShot::~SnapShot()\n\t\tthrow()\n\t{\n\t\tclear();\n\n\t\tvalid_ = false;\n\t}\n\n\n\t\/\/ The assignment operator \n\tconst SnapShot& SnapShot::operator = (const SnapShot& snapshot)\n\t\tthrow()\n\t{\n\t\tvalid_ = snapshot.valid_;\n\t\tindex_ = snapshot.index_;\n\t\tnumber_of_atoms_ = snapshot.number_of_atoms_;\n\t\tpotential_energy_ = snapshot.potential_energy_;\n\t\tkinetic_energy_ = snapshot.kinetic_energy_;\n\t\tatom_positions_ = snapshot.atom_positions_;\n\t\tatom_velocities_ = snapshot.atom_velocities_;\n\t\tatom_forces_ = snapshot.atom_forces_;\n\n\t\treturn *this;\n\t}\n\n\n\tvoid SnapShot::clear()\n\t\tthrow()\n\t{\n\t\tvalid_ = false;\n\t\tindex_ = 0;\n\t\tnumber_of_atoms_ = 0;\n\t\tpotential_energy_ = 0.0;\n\t\tkinetic_energy_ = 0.0;\n\n\t\tatom_positions_.clear();\n\t\tatom_velocities_.clear();\n\t\tatom_forces_.clear();\n\t}\n\n\n\tbool SnapShot::operator == (const SnapShot& snapshot) const\n\t\tthrow()\n\t{\n\t\treturn ((valid_ == snapshot.valid_)\n\t\t\t&& (index_ == snapshot.index_)\n\t\t\t&& (number_of_atoms_ == snapshot.number_of_atoms_)\n\t\t\t&& (potential_energy_ == snapshot.potential_energy_)\n\t\t\t&& (kinetic_energy_ == snapshot.kinetic_energy_)\n\t\t\t&& (atom_positions_ == snapshot.atom_positions_)\n\t\t\t&& (atom_velocities_ == snapshot.atom_velocities_)\n\t\t\t&& (atom_forces_ == snapshot.atom_forces_));\n\t}\n\n\n\tbool SnapShot::isValid() const\n\t\tthrow()\n\t{\n\t\treturn valid_;\n\t}\n\n\t\n\tvoid SnapShot::setIndex(Size index)\n\t\tthrow()\n\t{\n\t\tindex_ = index;\n\t}\n\n\n\tSize SnapShot::getIndex() const\n\t\tthrow()\n\t{\n\t\treturn index_;\n\t}\n\n\n\tvoid SnapShot::setNumberOfAtoms(Size number_of_atoms)\n\t\tthrow()\n\t{\n\t\tnumber_of_atoms_ = number_of_atoms;\n\t}\n\n\n\tSize SnapShot::getNumberOfAtoms() const\n\t\tthrow()\n\t{\n\t\treturn number_of_atoms_;\n\t}\n\n\n\tDoubleReal SnapShot::getPotentialEnergy() const\n\t\tthrow()\n\t{\n\t\treturn potential_energy_;\n\t}\n\n\n\tvoid SnapShot::setPotentialEnergy(DoubleReal potential_energy) \n\t\tthrow()\n\t{\n\t\tpotential_energy_ = potential_energy;\n\t}\n\n\n\tDoubleReal SnapShot::getKineticEnergy() const\n\t\tthrow()\n\t{\n\t\treturn kinetic_energy_;\n\t}\n\n\n\tvoid SnapShot::setKineticEnergy(DoubleReal kinetic_energy)\n\t\tthrow()\n\t{\n\t\tkinetic_energy_ = kinetic_energy;\n\t}\n\n\n\tvoid SnapShot::setAtomPositions(const ::std::vector<Vector3>& atom_postions)\n\t\tthrow()\n\t{\n\t\tatom_positions_ = atom_postions;\n\t}\n\n\n\tconst ::std::vector<Vector3>& SnapShot::getAtomPositions() const\n\t\tthrow()\n\t{\n\t\treturn atom_positions_;\n\t}\n\n\n\tvoid SnapShot::setAtomVelocitites(const ::std::vector<Vector3>& atom_velocities)\n\t\tthrow()\n\t{\n\t\tatom_velocities_ = atom_velocities;\n\t}\n\n\n\tconst ::std::vector<Vector3>& SnapShot::getAtomVelocities() const\n\t\tthrow()\n\t{\n\t\treturn atom_velocities_;\n\t}\n\n\n\tvoid SnapShot::setAtomForces(const ::std::vector<Vector3>& atom_forces)\n\t\tthrow()\n\t{\n\t\tatom_forces_ = atom_forces;\n\t}\n\n\n\tconst ::std::vector<Vector3>& SnapShot::getAtomForces() const\n\t\tthrow()\n\t{\n\t\treturn atom_forces_;\n\t}\n\n\n\tvoid SnapShot::takeSnapShot(const System& system)\n\t\tthrow(Exception::OutOfMemory)\n\t{\n\t\tnumber_of_atoms_ = system.countAtoms();\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\t\/\/ reserve memory\n\t\tatom_positions_.resize(number_of_atoms_);\n\t\tatom_velocities_.resize(number_of_atoms_);\n\t\tatom_forces_.resize(number_of_atoms_);\n\t\t\n\t\t\/\/ This is the data section of the snapshot object \n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_positions_[i] = atom_it->getPosition();\n\t\t\tatom_velocities_[i] = atom_it->getVelocity();\n\t\t\tatom_forces_[i] = atom_it->getForce();\n\t\t}\n\t}\n\n\n\tvoid SnapShot::applySnapShot(System& system) const\n\t\tthrow()\n\t{\n\t\tif (system.countAtoms() != number_of_atoms_)\n\t\t{\n\t\t\tLog.error () << \"SnapShot::applySnapShot(): \"\n\t\t\t\t<< \"Atom counts do not match: System: \" << system.countAtoms()\n\t\t\t\t<< \" SnapShot: \" << number_of_atoms_ << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tif (atom_positions_.size() > 0)\n\t\t\t{\n\t\t\t\tatom_it->setPosition(atom_positions_[i]);\n\t\t\t}\n\t\t\tif (atom_velocities_.size() > 0)\n\t\t\t{\n\t\t\t\tatom_it->setVelocity(atom_velocities_[i]);\n\t\t\t}\n\t\t\tif (atom_forces_.size() > 0)\n\t\t\t{\n\t\t\t\tatom_it->setForce(atom_forces_[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid SnapShot::getAtomPositions(const System& system)\n\t\tthrow(Exception::OutOfMemory)\n\t{\n\t\t\/\/ obtain the number of atoms\n\t\tnumber_of_atoms_ = system.countAtoms();\n\n\t\t\/\/ reserve memory \n\t\tatom_positions_.resize(number_of_atoms_);\n\n\t\t\/\/ copy data\n\t\tAtomIterator atom_it = system.beginAtom();\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_positions_[i] = atom_it->getPosition();\n\t\t}\n\t}\n\n\n\tvoid SnapShot::setAtomPositions(System& system) const\n\t\tthrow()\n\t{\n\t\tif (system.countAtoms() != number_of_atoms_)\n\t\t{\n\t\t\tLog.error () << \"SnapShot::setAtomPositions(): \"\n\t\t\t\t<< \"Atom counts do not match: System: \" << system.countAtoms()\n\t\t\t\t<< \" SnapShot: \" << number_of_atoms_ << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_it->setPosition(atom_positions_[i]);\n\t\t}\n\t}\n\n\n\tvoid SnapShot::getAtomVelocities(const System& system)\n\t\tthrow(Exception::OutOfMemory)\n\t{\n\t\tnumber_of_atoms_ = system.countAtoms();\n\t\tatom_velocities_.resize(number_of_atoms_);\n\t\tAtomIterator atom_it = system.beginAtom();\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_velocities_[i] = atom_it->getVelocity();\n\t\t}\n\t}\n\n\n\tvoid SnapShot::setAtomVelocitites(System& system) const\n\t\tthrow()\n\t{\n\t\tif (system.countAtoms() != number_of_atoms_)\n\t\t{\n\t\t\tLog.error () << \"SnapShot::setAtomVelocitites(): \"\n\t\t\t\t<< \"Atom counts do not match: System: \" << system.countAtoms()\n\t\t\t\t<< \" SnapShot: \" << number_of_atoms_ << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\t\/\/ This is the data section of the snapshot object \n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_it->setVelocity(atom_velocities_[i]);\n\t\t}\n\t}\n\n\n\tvoid SnapShot::getAtomForces(const System& system)\n\t\tthrow(Exception::OutOfMemory)\n\t{\n\t\tnumber_of_atoms_ = system.countAtoms();\n\t\tatom_forces_.resize(number_of_atoms_);\n\t\tAtomIterator atom_it = system.beginAtom();\n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_forces_[i] = atom_it->getForce();\n\t\t}\n\t}\n\n\n\tvoid SnapShot::setAtomForces(System& system) const\n\t\tthrow()\n\t{\n\t\tif (system.countAtoms() != number_of_atoms_)\n\t\t{\n\t\t\tLog.error () << \"SnapShot::setAtomForces(): \"\n\t\t\t\t<< \"Atom counts do not match: System: \" << system.countAtoms()\n\t\t\t\t<< \" SnapShot: \" << number_of_atoms_ << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tAtomIterator atom_it = system.beginAtom();\n\n\t\t\/\/ This is the data section of the snapshot object \n\t\tfor (Size i = 0; +atom_it; ++atom_it, ++i)\n\t\t{\n\t\t\tatom_it->setForce(atom_forces_[i]);\n\t\t}\n\t}\n\n\n\t::std::ostream& operator << (::std::ostream& os, const SnapShot& ss)\n\t{\n\t\tos << ss.getNumberOfAtoms() << endl;\n\n\t\tvector<Vector3> data = ss.getAtomPositions();\n\n\t\tvector<Vector3>::const_iterator it = data.begin();\n\t\tfor (; it != data.end(); ++it)\n\t\t{\n\t\t\tos << *it << endl;\n\t\t}\n\n\t\tdata = ss.getAtomVelocities();\n\t\tfor (it = data.begin(); it != data.end(); ++it)\n\t\t{\n\t\t\tos << *it << endl;\n\t\t}\n\n\t\tdata = ss.getAtomForces();\n\t\tfor (it = data.begin(); it != data.end(); ++it)\n\t\t{\n\t\t\tos << *it << endl;\n\t\t}\n\t\treturn os;\n\t}\n\n\n\t::std::istream& operator >> (::std::istream& is, SnapShot& ss)\n\t{\n\t\t\/\/ BAUSTELLE:\n\t\t\/\/ this istream does not check anything!\n\n\t\tSize number;\n\t\tis >> number;\n\n\t\tvector<Vector3> data;\n\t\tdata.resize(number);\n\n\t\tfor (Size i = 0; i < number; ++i)\n\t\t{\n\t\t\tis >> data[i];\n\t\t}\n\t\tss.setAtomPositions(data);\n\n\t\tfor (Size i = 0; i < number; ++i)\n\t\t{\n\t\t\tis >> data[i];\n\t\t}\n\t\tss.setAtomVelocitites(data);\n\n\t\tfor (Size i = 0; i < number; ++i)\n\t\t{\n\t\t\tis >> data[i];\n\t\t}\n\t\tss.setAtomForces(data);\n\t\treturn is;\n\t}\n\n}\t\/\/ end of namespace BALL\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n\n#include \"comp_math.h\"\n#include \"composition.h\"\n#include \"cyc_limits.h\"\n#include \"error.h\"\n\nnamespace cm = cyclus::compmath;\nusing cyclus::Composition;\nusing cyclus::CompMap;\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, SubSame) {\n CompMap v;\n v[922350000] = 1;\n v[922380000] = 2;\n\n v = cm::Sub(v, v);\n\n for (CompMap::iterator it = v.begin(); it != v.end(); ++it) {\n EXPECT_DOUBLE_EQ(0, it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, SubCloseSize) {\n CompMap v;\n double qty = 0.1;\n v[922350000] = qty;\n\n CompMap v2(v);\n cm::Normalize(&v2, qty - cyclus::eps_rsrc());\n\n CompMap remainder;\n\n remainder = cm::Sub(v, v2);\n CompMap::iterator it;\n for (it = remainder.begin(); it != remainder.end(); ++it) {\n double expected = cyclus::eps_rsrc();\n EXPECT_FLOAT_EQ(expected, it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, SubCloseComp) {\n double qty = 0.1;\n\n CompMap v;\n v[922350000] = 1;\n v[922410000] = 1;\n v[822080000] = 1;\n cm::Normalize(&v, qty);\n\n CompMap closev(v);\n closev[92241] -= cyclus::eps_rsrc();\n\n CompMap remainder;\n remainder = cm::Sub(v, closev);\n\n CompMap::iterator it;\n for (it = remainder.begin(); it != remainder.end(); ++it) {\n double expected = 0;\n if (it->first == 92241) {\n expected = v[92241] - closev[92241];\n }\n EXPECT_FLOAT_EQ(expected, it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, Sum) {\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n EXPECT_FLOAT_EQ(6.0, cm::Sum(&v));\n\n}\n\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdZero) {\n \/\/ if the threshold is 0, applying the threshold should do nothing\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n EXPECT_NO_THROW(cm::ApplyThreshold(&v, 0));\n\n CompMap::iterator it;\n for (it = v.begin(); it != v.end(); ++it) {\n EXPECT_FLOAT_EQ(v[it->first], it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdInf) {\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n \/\/ if the threshold is infinit, applying it should zero any vector\n double infty = std::numeric_limits<double>::infinity();\n EXPECT_NO_THROW(cm::ApplyThreshold(&v, infty));\n\n CompMap::iterator it;\n for (it = v.begin(); it != v.end(); ++it) {\n EXPECT_FLOAT_EQ(0, it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdNegative) {\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n EXPECT_THROW(cm::ApplyThreshold(&v, -1), cyclus::ValueError);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdMedium) {\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n \/\/ if the threshold is in a reasonable range, it should zero small vals\n CompMap::iterator it;\n for (it = v.begin(); it != v.end(); ++it) {\n EXPECT_NO_THROW(cm::ApplyThreshold(&v, it->second));\n EXPECT_FLOAT_EQ(0, v[it->first]);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdSeqIter) {\n \/\/ tests for a bug caused by improper iteration over CompMap\n CompMap v;\n v[0] = 2.0;\n v[1] = 0.1;\n v[2] = 0.1;\n v[3] = 0.1;\n v[4] = 3.0;\n\n EXPECT_NO_THROW(cm::ApplyThreshold(&v, 1.0));\n EXPECT_FLOAT_EQ(2, v[0]);\n EXPECT_FLOAT_EQ(0, v[1]);\n EXPECT_FLOAT_EQ(0, v[2]);\n EXPECT_FLOAT_EQ(0, v[3]);\n EXPECT_FLOAT_EQ(3, v[4]);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, AlmostEq) {\n CompMap v1;\n v1[1] = 0.1;\n v1[2] = 0.1;\n v1[3] = 0.1;\n\n CompMap v2(v1);\n CompMap::iterator it;\n for (it = v2.begin(); it != v2.end(); ++it) {\n v2[it->first] = 0.11;\n }\n\n EXPECT_TRUE(cm::AlmostEq(v1, v2, 0.1));\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, AlmostEqualZeroEntry) {\n CompMap v1;\n v1[1] = 0.1;\n v1[2] = 0.1;\n v1[3] = 0.1;\n\n CompMap v2(v1);\n CompMap::iterator it;\n for (it = v1.begin(); it != v1.end(); ++it) {\n v1[it->first] = 0;\n }\n\n EXPECT_TRUE(cm::AlmostEq(v1, v2, 1.1));\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, AlmostEqualNegThresh) {\n CompMap v1, v2;\n EXPECT_THROW(cm::AlmostEq(v1, v2, -1.0), cyclus::ValueError);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, SimpleAdd) {\n CompMap v1;\n v1[1] = 1.1;\n v1[2] = 2.2;\n v1[3] = 3.3;\n cm::Normalize(&v1, 1.0);\n CompMap v2(v1);\n cm::Normalize(&v2, 2.0);\n\n CompMap result = cm::Add(v1, v2);\n cm::Normalize(&result);\n EXPECT_TRUE(cm::AlmostEq(v1, result, 1e-15));\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, Add) {\n CompMap v1;\n v1[1] = 1.0;\n v1[2] = 2.0;\n v1[3] = 3.0;\n\n\n CompMap v2;\n v2[1] = 1.1;\n v2[2] = 2.2;\n v2[3] = 3.3;\n\n CompMap expect;\n expect[1] = 2.1;\n expect[2] = 4.2;\n expect[3] = 6.3;\n\n CompMap result;\n\n result = cm::Add(v1, v2);\n EXPECT_TRUE(cm::AlmostEq(result, expect, 0));\n for (CompMap::iterator it = result.begin();\n it != result.end(); it++) {\n EXPECT_DOUBLE_EQ(it->second, expect[it->first]);\n }\n}\n<commit_msg>moved errant ampersand<commit_after>#include \"gtest\/gtest.h\"\n\n#include \"comp_math.h\"\n#include \"composition.h\"\n#include \"cyc_limits.h\"\n#include \"error.h\"\n\nnamespace cm = cyclus::compmath;\nusing cyclus::Composition;\nusing cyclus::CompMap;\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, SubSame) {\n CompMap v;\n v[922350000] = 1;\n v[922380000] = 2;\n\n v = cm::Sub(v, v);\n\n for (CompMap::iterator it = v.begin(); it != v.end(); ++it) {\n EXPECT_DOUBLE_EQ(0, it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, SubCloseSize) {\n CompMap v;\n double qty = 0.1;\n v[922350000] = qty;\n\n CompMap v2(v);\n cm::Normalize(&v2, qty - cyclus::eps_rsrc());\n\n CompMap remainder;\n\n remainder = cm::Sub(v, v2);\n CompMap::iterator it;\n for (it = remainder.begin(); it != remainder.end(); ++it) {\n double expected = cyclus::eps_rsrc();\n EXPECT_FLOAT_EQ(expected, it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, SubCloseComp) {\n double qty = 0.1;\n\n CompMap v;\n v[922350000] = 1;\n v[922410000] = 1;\n v[822080000] = 1;\n cm::Normalize(&v, qty);\n\n CompMap closev(v);\n closev[92241] -= cyclus::eps_rsrc();\n\n CompMap remainder;\n remainder = cm::Sub(v, closev);\n\n CompMap::iterator it;\n for (it = remainder.begin(); it != remainder.end(); ++it) {\n double expected = 0;\n if (it->first == 92241) {\n expected = v[92241] - closev[92241];\n }\n EXPECT_FLOAT_EQ(expected, it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, Sum) {\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n EXPECT_FLOAT_EQ(6.0, cm::Sum(v));\n\n}\n\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdZero) {\n \/\/ if the threshold is 0, applying the threshold should do nothing\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n EXPECT_NO_THROW(cm::ApplyThreshold(&v, 0));\n\n CompMap::iterator it;\n for (it = v.begin(); it != v.end(); ++it) {\n EXPECT_FLOAT_EQ(v[it->first], it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdInf) {\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n \/\/ if the threshold is infinit, applying it should zero any vector\n double infty = std::numeric_limits<double>::infinity();\n EXPECT_NO_THROW(cm::ApplyThreshold(&v, infty));\n\n CompMap::iterator it;\n for (it = v.begin(); it != v.end(); ++it) {\n EXPECT_FLOAT_EQ(0, it->second);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdNegative) {\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n EXPECT_THROW(cm::ApplyThreshold(&v, -1), cyclus::ValueError);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdMedium) {\n CompMap v;\n v[1] = 1.0;\n v[2] = 2.0;\n v[3] = 3.0;\n\n \/\/ if the threshold is in a reasonable range, it should zero small vals\n CompMap::iterator it;\n for (it = v.begin(); it != v.end(); ++it) {\n EXPECT_NO_THROW(cm::ApplyThreshold(&v, it->second));\n EXPECT_FLOAT_EQ(0, v[it->first]);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, ApplyThresholdSeqIter) {\n \/\/ tests for a bug caused by improper iteration over CompMap\n CompMap v;\n v[0] = 2.0;\n v[1] = 0.1;\n v[2] = 0.1;\n v[3] = 0.1;\n v[4] = 3.0;\n\n EXPECT_NO_THROW(cm::ApplyThreshold(&v, 1.0));\n EXPECT_FLOAT_EQ(2, v[0]);\n EXPECT_FLOAT_EQ(0, v[1]);\n EXPECT_FLOAT_EQ(0, v[2]);\n EXPECT_FLOAT_EQ(0, v[3]);\n EXPECT_FLOAT_EQ(3, v[4]);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, AlmostEq) {\n CompMap v1;\n v1[1] = 0.1;\n v1[2] = 0.1;\n v1[3] = 0.1;\n\n CompMap v2(v1);\n CompMap::iterator it;\n for (it = v2.begin(); it != v2.end(); ++it) {\n v2[it->first] = 0.11;\n }\n\n EXPECT_TRUE(cm::AlmostEq(v1, v2, 0.1));\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, AlmostEqualZeroEntry) {\n CompMap v1;\n v1[1] = 0.1;\n v1[2] = 0.1;\n v1[3] = 0.1;\n\n CompMap v2(v1);\n CompMap::iterator it;\n for (it = v1.begin(); it != v1.end(); ++it) {\n v1[it->first] = 0;\n }\n\n EXPECT_TRUE(cm::AlmostEq(v1, v2, 1.1));\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, AlmostEqualNegThresh) {\n CompMap v1, v2;\n EXPECT_THROW(cm::AlmostEq(v1, v2, -1.0), cyclus::ValueError);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, SimpleAdd) {\n CompMap v1;\n v1[1] = 1.1;\n v1[2] = 2.2;\n v1[3] = 3.3;\n cm::Normalize(&v1, 1.0);\n CompMap v2(v1);\n cm::Normalize(&v2, 2.0);\n\n CompMap result = cm::Add(v1, v2);\n cm::Normalize(&result);\n EXPECT_TRUE(cm::AlmostEq(v1, result, 1e-15));\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nTEST(CompMathTests, Add) {\n CompMap v1;\n v1[1] = 1.0;\n v1[2] = 2.0;\n v1[3] = 3.0;\n\n\n CompMap v2;\n v2[1] = 1.1;\n v2[2] = 2.2;\n v2[3] = 3.3;\n\n CompMap expect;\n expect[1] = 2.1;\n expect[2] = 4.2;\n expect[3] = 6.3;\n\n CompMap result;\n\n result = cm::Add(v1, v2);\n EXPECT_TRUE(cm::AlmostEq(result, expect, 0));\n for (CompMap::iterator it = result.begin();\n it != result.end(); it++) {\n EXPECT_DOUBLE_EQ(it->second, expect[it->first]);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the CutePaste project\n * Copyright (c) 2013 Laszlo Papp <lpapp@kde.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 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\n#include <QSslError>\n#include <QNetworkAccessManager>\n#include <QNetworkRequest>\n#include <QNetworkReply>\n#include <QTcpSocket>\n\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QJsonParseError>\n#include <QFile>\n#include <QScopedPointer>\n#include <QTextStream>\n#include <QStringList>\n#include <QCoreApplication>\n\n#include <QDebug>\n\nint main(int argc, char **argv)\n{\n QCoreApplication application(argc, argv);\n application.setOrganizationName(\"CutePaste\");\n application.setApplicationName(\"CutePaste Desktop Console Frontend\");\n\n QTextStream standardOutputStream(stdout);\n QFile dataFile;\n QString firstArgument = QCoreApplication::arguments().size() < 2 ? QString() : QCoreApplication::arguments().at(1);\n if (!firstArgument.isEmpty()) {\n dataFile.setFileName(firstArgument);\n dataFile.open(QIODevice::ReadOnly);\n } else {\n dataFile.open(stdin, QIODevice::ReadOnly);\n }\n\n QByteArray pasteTextByteArray = dataFile.readAll();\n\n QJsonObject requestJsonObject;\n requestJsonObject.insert(QStringLiteral(\"data\"), QString::fromUtf8(pasteTextByteArray));\n requestJsonObject.insert(QStringLiteral(\"language\"), QStringLiteral(\"text\"));\n\n QJsonDocument requestJsonDocument(requestJsonObject);\n\n QNetworkRequest networkRequest;\n networkRequest.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);\n networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, \"application\/json\");\n networkRequest.setUrl(QUrl(\"http:\/\/sandbox.pastebin.kde.org\/api\/json\/create\"));\n\n QNetworkAccessManager networkAccessManager;\n QScopedPointer<QNetworkReply> networkReplyScopedPointer(networkAccessManager.post(networkRequest, requestJsonDocument.toJson()));\n QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::finished, [&]() {\n\n QJsonParseError jsonParseError;\n QByteArray replyJsonByteArray = networkReplyScopedPointer->readAll();\n QJsonDocument replyJsonDocument = QJsonDocument::fromJson(replyJsonByteArray, &jsonParseError);\n if (!replyJsonDocument.isObject()) {\n qDebug() << \"Reply error:\" << jsonParseError.errorString();\n return;\n }\n \n QJsonObject replyJsonObject = replyJsonDocument.object();\n QJsonValue identifierValue = replyJsonObject.value(QStringLiteral(\"result\")).toObject().value(QStringLiteral(\"id\"));\n\n if (identifierValue.isString())\n endl(standardOutputStream << \"http:\/\/sandbox.pastebin.kde.org\/\" << identifierValue.toString());\n\n QCoreApplication::quit();\n });\n\n QObject::connect(networkReplyScopedPointer.data(), static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [&](QNetworkReply::NetworkError networkReplyError) {\n if (networkReplyError != QNetworkReply::NoError)\n endl(standardOutputStream << networkReplyScopedPointer->errorString());\n });\n\n QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::sslErrors, [&](QList<QSslError> networkReplySslErrors) {\n if (!networkReplySslErrors.isEmpty()) {\n foreach (const QSslError &networkReplySslError, networkReplySslErrors)\n endl(standardOutputStream << networkReplySslError.errorString());\n }\n });\n\n bool returnValue = application.exec();\n\n dataFile.close();\n if (dataFile.error() != QFileDevice::NoError)\n endl(standardOutputStream << dataFile.errorString());\n\n return returnValue;\n}\n<commit_msg>Use the new API url and establish an internal variable for flexibility<commit_after>\/******************************************************************************\n * This file is part of the CutePaste project\n * Copyright (c) 2013 Laszlo Papp <lpapp@kde.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 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\n#include <QSslError>\n#include <QNetworkAccessManager>\n#include <QNetworkRequest>\n#include <QNetworkReply>\n#include <QTcpSocket>\n\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QJsonParseError>\n#include <QFile>\n#include <QScopedPointer>\n#include <QTextStream>\n#include <QStringList>\n#include <QCoreApplication>\n\n#include <QDebug>\n\nint main(int argc, char **argv)\n{\n QCoreApplication application(argc, argv);\n application.setOrganizationName(\"CutePaste\");\n application.setApplicationName(\"CutePaste Desktop Console Frontend\");\n\n QTextStream standardOutputStream(stdout);\n QFile dataFile;\n QString firstArgument = QCoreApplication::arguments().size() < 2 ? QString() : QCoreApplication::arguments().at(1);\n if (!firstArgument.isEmpty()) {\n dataFile.setFileName(firstArgument);\n dataFile.open(QIODevice::ReadOnly);\n } else {\n dataFile.open(stdin, QIODevice::ReadOnly);\n }\n\n QByteArray pasteTextByteArray = dataFile.readAll();\n\n QJsonObject requestJsonObject;\n requestJsonObject.insert(QStringLiteral(\"data\"), QString::fromUtf8(pasteTextByteArray));\n requestJsonObject.insert(QStringLiteral(\"language\"), QStringLiteral(\"text\"));\n\n QJsonDocument requestJsonDocument(requestJsonObject);\n\n QString baseUrlString = QStringLiteral(\"http:\/\/pastebin.kde.org\");\n\n QNetworkRequest networkRequest;\n networkRequest.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);\n networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, \"application\/json\");\n networkRequest.setUrl(QUrl(baseUrlString + \"\/api\/json\/create\"));\n\n QNetworkAccessManager networkAccessManager;\n QScopedPointer<QNetworkReply> networkReplyScopedPointer(networkAccessManager.post(networkRequest, requestJsonDocument.toJson()));\n QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::finished, [&]() {\n\n QJsonParseError jsonParseError;\n QByteArray replyJsonByteArray = networkReplyScopedPointer->readAll();\n QJsonDocument replyJsonDocument = QJsonDocument::fromJson(replyJsonByteArray, &jsonParseError);\n if (!replyJsonDocument.isObject()) {\n qDebug() << \"Reply error:\" << jsonParseError.errorString();\n return;\n }\n \n QJsonObject replyJsonObject = replyJsonDocument.object();\n QJsonValue identifierValue = replyJsonObject.value(QStringLiteral(\"result\")).toObject().value(QStringLiteral(\"id\"));\n\n if (identifierValue.isString())\n endl(standardOutputStream << baseUrlString << identifierValue.toString());\n\n QCoreApplication::quit();\n });\n\n QObject::connect(networkReplyScopedPointer.data(), static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [&](QNetworkReply::NetworkError networkReplyError) {\n if (networkReplyError != QNetworkReply::NoError)\n endl(standardOutputStream << networkReplyScopedPointer->errorString());\n });\n\n QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::sslErrors, [&](QList<QSslError> networkReplySslErrors) {\n if (!networkReplySslErrors.isEmpty()) {\n foreach (const QSslError &networkReplySslError, networkReplySslErrors)\n endl(standardOutputStream << networkReplySslError.errorString());\n }\n });\n\n bool returnValue = application.exec();\n\n dataFile.close();\n if (dataFile.error() != QFileDevice::NoError)\n endl(standardOutputStream << dataFile.errorString());\n\n return returnValue;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <catch2\/catch.hpp>\n\n#include <vector>\n#include <optional>\n\n\nstruct Block\n{\n size_t offset;\n size_t size;\n};\n\nstruct TLSFSizeClass\n{\n size_t sizeClass;\n uint64_t slBitmap;\n std::vector<std::vector<Block>> freeBlocks;\n};\n\nstruct TLSFControl\n{\n uint64_t flBitmap;\n std::vector<TLSFSizeClass> sizeclasses;\n};\n\nclass TLSFAllocator\n{\n unsigned fli; \/\/ first level index\n unsigned sli; \/\/ second level index, typically 5\n unsigned sli_count; \/\/ second level index, typically 5\n unsigned mbs; \/\/ minimum block size\n TLSFControl control;\n size_t m_size;\n\n int fls(uint64_t size)\n {\n unsigned long index;\n return _BitScanReverse64(&index, size) ? index : -1;\n }\n\n int ffs(uint64_t size)\n {\n unsigned long index;\n return _BitScanForward64(&index, size) ? index : -1;\n }\n\n void mapping(size_t size, unsigned& fl, unsigned& sl)\n {\n fl = fls(size);\n sl = ((size ^ (1<<fl)) >> (fl - sli));\n }\n\n void initialize()\n {\n fli = ffs(m_size);\n sli = 5;\n sli_count = 1 << sli;\n mbs = 16;\n control.flBitmap = 0;\n for (int i = 0; i < fli; ++i)\n {\n size_t sizeClass = 1 << i;\n std::vector<std::vector<Block>> vectors;\n for (int k = 0; k < sli; ++k)\n {\n vectors.push_back(std::vector<Block>());\n }\n control.sizeclasses.push_back(TLSFSizeClass{sizeClass, 0, vectors});\n }\n }\npublic:\n\n TLSFAllocator(size_t size)\n : m_size(size)\n {\n initialize();\n }\n\n std::optional<Block> allocate(size_t size)\n {\n unsigned fl, sl;\n mapping(size, fl, sl);\n printf(\"%zu -> fl %u sl %u\\n\", size, fl, sl);\n return {};\n }\n\n void free(Block block)\n {\n \/\/ immediately merge with existing free blocks.\n }\n};\n\nTEST_CASE(\"can allocate\")\n{\n TLSFAllocator tlsf(4);\n auto block = tlsf.allocate(5);\n REQUIRE(!block);\n block = tlsf.allocate(5);\n REQUIRE(block);\n if (block)\n {\n REQUIRE(block.value().size == 1);\n }\n}<commit_msg>Wrote a really crappy tlsf implementation merging is bruteforced because I cannot use boundary tag technique splitting can also take time...<commit_after>#include <catch2\/catch.hpp>\n\n#include <vector>\n#include <optional>\n\n\nstruct Block\n{\n size_t offset;\n size_t size;\n operator bool()\n {\n return size != 0;\n }\n};\n\nclass TLSFAllocator\n{\n struct TLSFSizeClass\n {\n size_t sizeClass;\n uint64_t slBitmap;\n std::vector<std::vector<Block>> freeBlocks;\n };\n\n struct TLSFControl\n {\n uint64_t flBitmap;\n std::vector<TLSFSizeClass> sizeclasses;\n };\n\n unsigned fli; \/\/ first level index\n unsigned sli; \/\/ second level index, typically 5\n unsigned sli_count; \/\/ second level index, typically 5\n unsigned mbs; \/\/ minimum block size\n TLSFControl control;\n size_t m_size;\n\n int fls(uint64_t size)\n {\n unsigned long index;\n return _BitScanReverse64(&index, size) ? index : -1;\n }\n\n int ffs(uint64_t size)\n {\n unsigned long index;\n return _BitScanForward64(&index, size) ? index : -1;\n }\n\n void mapping(size_t size, unsigned& fl, unsigned& sl)\n {\n fl = fls(size);\n sl = ((size ^ (1<<fl)) >> (fl - sli));\n \/\/printf(\"%zu -> fl %u sl %u\\n\", size, fl, sl);\n }\n\n void initialize()\n {\n fli = ffs(m_size);\n sli = 5;\n sli_count = 1 << sli;\n mbs = 16;\n control.flBitmap = 0;\n for (int i = 0; i <= fli; ++i)\n {\n size_t sizeClass = 1 << i;\n std::vector<std::vector<Block>> vectors;\n for (int k = 0; k < sli; ++k)\n {\n vectors.push_back(std::vector<Block>());\n }\n control.sizeclasses.push_back(TLSFSizeClass{sizeClass, 0, vectors});\n }\n }\n\n void remove_bit(uint64_t& value, int index)\n {\n value = value & (~(1 << index));\n }\n\n void set_bit(uint64_t& value, int index)\n {\n value |= (1 << index);\n }\n\n void insert(Block block, unsigned fl, unsigned sl)\n {\n auto& sizeClass = control.sizeclasses[fl];\n auto& secondLv = sizeClass.freeBlocks[sl];\n secondLv.push_back(block);\n set_bit(sizeClass.slBitmap, sl);\n set_bit(control.flBitmap, fl);\n }\n\n Block search_suitable_block(size_t size, unsigned fl, unsigned sl)\n {\n \/\/ first step, assume we got something at fl \/ sl location\n auto& sizeClass = control.sizeclasses[fl];\n auto& secondLv = sizeClass.freeBlocks[sl];\n if (!secondLv.empty() && sizeClass.sizeClass >= size) {\n auto block = secondLv.back();\n secondLv.pop_back();\n \/\/ remove bitmap bit\n if (secondLv.empty()) remove_bit(sizeClass.slBitmap, sl);\n if (sizeClass.slBitmap == 0) remove_bit(control.flBitmap, fl);\n return block;\n }\n else {\n \/\/ second step, scan bitmaps for empty slots\n auto mask = ~((1 << (fl+1))-1); \/\/ create mask to ignore first bits, could be wrong\n auto fl2 = ffs(control.flBitmap & mask);\n if (fl2 >= 0) {\n auto& sizeClass2 = control.sizeclasses[fl2];\n auto sl2 = ffs(sizeClass2.slBitmap);\n if (sl2 >= 0 && sizeClass2.sizeClass >= size) {\n assert(!sizeClass2.freeBlocks[sl2].empty());\n auto block = sizeClass2.freeBlocks[sl2].back();\n sizeClass2.freeBlocks[sl2].pop_back();\n \/\/ remove bitmap bit\n if (secondLv.empty()) remove_bit(sizeClass2.slBitmap, sl2);\n if (sizeClass2.slBitmap == 0) remove_bit(control.flBitmap, fl2);\n return block;\n }\n }\n }\n \n return {};\n }\n\n Block split(Block& block)\n {\n auto new_size = block.size \/ 2;\n Block new_block = {block.offset+new_size, new_size};\n block.size = new_size;\n return new_block;\n }\n\n Block merge(Block block)\n {\n \/\/ try to merge with some existing block???????????????\n auto otf = block.offset;\n auto otf2 = block.offset + block.size;\n \/\/ BRUTEFORCE\n auto fl = 0;\n for (auto&& firstLevel : control.sizeclasses)\n {\n auto sl = 0;\n for (auto&& secondLevel : firstLevel.freeBlocks)\n {\n auto iter = std::find_if(secondLevel.begin(), secondLevel.end(), [otf, otf2](Block b){\n return (b.offset+b.size == otf) || (b.offset == otf2);\n });\n if (iter != secondLevel.end())\n {\n auto rb = *iter;\n secondLevel.erase(iter);\n if (secondLevel.empty()) remove_bit(firstLevel.slBitmap, sl);\n if (firstLevel.slBitmap == 0) remove_bit(control.flBitmap, fl);\n\n if (rb.offset+rb.size == otf) {\n rb.size += block.size;\n return rb;\n }\n else if(rb.offset == otf2) {\n block.size += rb.size;\n return block;\n }\n }\n sl++;\n }\n fl++;\n }\n return block;\n }\npublic:\n TLSFAllocator(size_t size)\n : m_size(size)\n {\n initialize();\n unsigned fl, sl;\n mapping(size, fl, sl);\n insert({0, size}, fl, sl);\n }\n\n std::optional<Block> allocate(size_t size)\n {\n unsigned fl, sl, fl2, sl2;\n mapping(size, fl, sl);\n auto found_block = search_suitable_block(size,fl,sl);\n if (found_block) {\n while (found_block.size >= size*2)\n {\n auto remaining_block = split(found_block);\n mapping(remaining_block.size, fl2, sl2);\n insert(remaining_block, fl2, sl2); \/\/ O(1)\n }\n return found_block;\n }\n return {};\n }\n\n void free(Block block)\n {\n \/\/ immediately merge with existing free blocks.\n unsigned fl, sl;\n auto big_free_block = merge(block); \/\/ O(1)\n mapping(big_free_block.size, fl, sl);\n insert(big_free_block, fl, sl); \/\/ O(1)\n }\n};\n\nTEST_CASE(\"some basic allocation tests\")\n{\n TLSFAllocator tlsf(4);\n auto block = tlsf.allocate(5);\n REQUIRE_FALSE(block);\n block = tlsf.allocate(2);\n REQUIRE(block);\n if (block)\n {\n REQUIRE(block.value().size == 2);\n }\n tlsf.free(block.value());\n block = tlsf.allocate(4);\n REQUIRE(block);\n if (block)\n {\n REQUIRE(block.value().size == 4);\n }\n\n tlsf.free(block.value());\n block = tlsf.allocate(3);\n REQUIRE(block);\n if (block)\n {\n REQUIRE(block.value().size == 4);\n }\n\n tlsf.free(block.value());\n block = tlsf.allocate(2);\n auto block2 = tlsf.allocate(2);\n REQUIRE(block);\n REQUIRE(block2);\n if (block && block2)\n {\n REQUIRE(block.value().size == 2);\n REQUIRE(block2.value().size == 2);\n }\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>IndexedFaceSet triangle is introduced, but not tested<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"viewer\/primitives\/simple_geometry.hh\"\n#include \"viewer\/window_3d.hh\"\n\n#include \"estimation\/jet\/jet_filter.hh\"\n#include \"estimation\/jet\/jet_pose_opt.hh\"\n\n#include \"estimation\/jet\/jet_rk4.hh\"\n\n#include \"util\/environment.hh\"\n\n#include \"eigen.hh\"\n#include \"sophus.hh\"\n\nnamespace estimation {\nnamespace jet_filter {\nnamespace {\n\/*\nvoid go() {\n setup();\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n\n const jcc::Vec3 g(0.0, 0.0, 0.0);\n const SO3 r_sensor_from_body;\n const jcc::Vec3 t_sensor_from_body = jcc::Vec3(0.0, 0.0, 1.0);\n const SE3 sensor_from_body = SE3(r_sensor_from_body, t_sensor_from_body);\n\n State x;\n x.T_body_from_world = SE3(SO3(), jcc::Vec3(5.0, 0.0, 0.0));\n\n x.eps_dot[0] = 0.0;\n x.eps_dot[1] = 0.0;\n x.eps_dot[2] = 0.0;\n x.eps_dot[3] = 0.0;\n x.eps_dot[4] = 0.0;\n x.eps_dot[5] = 0.0;\n\n x.eps_ddot[0] = 0.0;\n x.eps_ddot[1] = 1.0;\n x.eps_ddot[2] = 0.0;\n x.eps_ddot[3] = 0.0;\n x.eps_ddot[4] = 0.0;\n x.eps_ddot[5] = 1.0;\n\n p = mock_parameters();\n const auto res = observe_accel(x, p);\n\n constexpr double dt = 0.01;\n while (!view->should_close()) {\n x = dynamics(x, dt);\n\n geo->add_axes({x.T_body_from_world.inverse()});\n const SE3 world_from_sensor = (sensor_from_body * x.T_body_from_world).inverse();\n geo->add_axes({world_from_sensor, 0.25});\n const auto res =\n observe_accel(x.T_body_from_world, x.eps_dot, x.eps_ddot, sensor_from_body, g);\n\n geo->add_ray(\n {world_from_sensor.translation(), world_from_sensor.so3() * res, res.norm()});\n\n geo->flip();\n\n view->spin_until_step();\n }\n}\n*\/\n\nParameters mock_parameters() {\n const jcc::Vec3 g(0.0, 0.0, 4.1);\n const SE3 vehicle_from_sensor;\n Parameters p;\n p.T_sensor_from_body = vehicle_from_sensor;\n p.g_world = g;\n return p;\n}\n\nvoid setup() {\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n view->set_target_from_world(\n SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));\n view->set_continue_time_ms(10);\n\n const auto background = view->add_primitive<viewer::SimpleGeometry>();\n const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};\n background->add_plane({ground});\n background->flip();\n}\n\nvoid draw_states(viewer::SimpleGeometry& geo,\n const std::vector<State>& states,\n bool truth) {\n for (const auto& state : states) {\n const SE3 T_world_from_body = state.T_body_from_world.inverse();\n if (truth) {\n geo.add_axes({T_world_from_body, 1.0});\n } else {\n geo.add_axes({T_world_from_body, 0.5, 2.0, true});\n }\n }\n}\n} \/\/ namespace\n\nclass JetOptimizer {\n public:\n JetOptimizer() {\n imu_id_ = pose_opt_.add_error_model<AccelMeasurement>(accel_error_model);\n fiducial_id_ = pose_opt_.add_error_model<FiducialMeasurement>(fiducial_error_model);\n }\n\n void measure_imu(const AccelMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, imu_id_);\n }\n\n void measure_fiducial(const FiducialMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, fiducial_id_);\n }\n\n JetPoseOptimizer::Solution solve(const std::vector<State> x, const Parameters& p) {\n const auto visitor = [](const JetPoseOptimizer::Solution& soln) {\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n draw_states(*geo, soln.x, false);\n geo->flip();\n view->spin_until_step();\n geo->clear();\n };\n\n return pose_opt_.solve({x, p}, visitor);\n }\n\n private:\n JetPoseOptimizer pose_opt_{rk4_integrate};\n int imu_id_ = -1;\n int fiducial_id_ = -1;\n};\n\nvoid run_filter() {\n const Parameters true_params = mock_parameters();\n\n JetOptimizer jet_opt;\n\n FilterState<State> xp0;\n xp0.P.setIdentity();\n xp0.x.eps_ddot[0] = 0.0;\n\n State true_x = xp0.x;\n true_x.eps_dot[0] = 0.1;\n true_x.eps_dot[3] = -0.1;\n true_x.eps_dot[4] = 0.1;\n\n JetFilter jf(xp0);\n\n \/\/ AccelMeasurement imu_meas;\n \/\/ imu_meas.observed_acceleration[0] = 2.0;\n\n std::vector<State> ground_truth;\n std::vector<State> est_states;\n\n TimePoint start_time = {};\n constexpr auto dt = to_duration(0.5);\n\n constexpr int NUM_SIM_STEPS = 76;\n\n for (int k = 0; k < NUM_SIM_STEPS; ++k) {\n const TimePoint obs_time = (dt * k) + start_time;\n const AccelMeasurement imu_meas = {observe_accel(true_x, true_params)};\n std::cout << \"Accel: \" << imu_meas.observed_acceleration.transpose() << std::endl;\n\n jf.measure_imu(imu_meas, obs_time);\n jet_opt.measure_imu(imu_meas, obs_time);\n jf.free_run();\n est_states.push_back(jf.state().x);\n ground_truth.push_back(true_x);\n\n constexpr auto dt2 = to_duration(0.1);\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt2));\n ground_truth.push_back(true_x);\n const FiducialMeasurement fiducial_meas = observe_fiducial(true_x, true_params);\n\n jf.measure_fiducial(fiducial_meas, obs_time + dt2);\n jet_opt.measure_fiducial(fiducial_meas, obs_time + dt2);\n jf.free_run();\n est_states.push_back(jf.state().x);\n\n const auto xp = jf.state();\n std::cout << \"k: \" << k << std::endl;\n std::cout << \"\\teps_dot : \" << xp.x.eps_dot.transpose() << std::endl;\n std::cout << \"\\teps_ddot : \" << xp.x.eps_ddot.transpose() << std::endl;\n std::cout << \"\\taccel_bias: \" << xp.x.accel_bias.transpose() << std::endl;\n std::cout << \"\\tgyro_bias : \" << xp.x.gyro_bias.transpose() << std::endl;\n\n std::cout << \"\\tModelled Error: \"\n << accel_error_model(xp.x, imu_meas, true_params).transpose() << std::endl;\n const auto res = observe_accel(xp.x, mock_parameters());\n std::cout << \"\\tExpected Measurement: \" << res.transpose() << std::endl;\n\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt));\n }\n\n \/\/ Do the optimization\n setup();\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n draw_states(*geo, ground_truth, true);\n\n const auto solution = jet_opt.solve(est_states, {});\n std::cout << \"Optimized g: \" << solution.p.g_world.transpose() << std::endl;\n std::cout << \"Optimized T_sensor_from_body: \"\n << solution.p.T_sensor_from_body.log().transpose() << std::endl;\n\n draw_states(*geo, solution.x, false);\n\n geo->flip();\n\n view->spin_until_step();\n}\n\n} \/\/ namespace jet_filter\n} \/\/ namespace estimation\n\nint main() {\n \/\/ estimation::jet_filter::go();\n estimation::jet_filter::run_filter();\n}<commit_msg>Filter demo is working<commit_after>#include \"viewer\/primitives\/simple_geometry.hh\"\n#include \"viewer\/window_3d.hh\"\n\n#include \"estimation\/jet\/jet_filter.hh\"\n#include \"estimation\/jet\/jet_pose_opt.hh\"\n\n#include \"estimation\/jet\/jet_rk4.hh\"\n\n#include \"util\/environment.hh\"\n\n#include \"eigen.hh\"\n#include \"sophus.hh\"\n\nnamespace estimation {\nnamespace jet_filter {\nnamespace {\n\/*\nvoid go() {\n setup();\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n\n const jcc::Vec3 g(0.0, 0.0, 0.0);\n const SO3 r_sensor_from_body;\n const jcc::Vec3 t_sensor_from_body = jcc::Vec3(0.0, 0.0, 1.0);\n const SE3 sensor_from_body = SE3(r_sensor_from_body, t_sensor_from_body);\n\n State x;\n x.T_body_from_world = SE3(SO3(), jcc::Vec3(5.0, 0.0, 0.0));\n\n x.eps_dot[0] = 0.0;\n x.eps_dot[1] = 0.0;\n x.eps_dot[2] = 0.0;\n x.eps_dot[3] = 0.0;\n x.eps_dot[4] = 0.0;\n x.eps_dot[5] = 0.0;\n\n x.eps_ddot[0] = 0.0;\n x.eps_ddot[1] = 1.0;\n x.eps_ddot[2] = 0.0;\n x.eps_ddot[3] = 0.0;\n x.eps_ddot[4] = 0.0;\n x.eps_ddot[5] = 1.0;\n\n p = mock_parameters();\n const auto res = observe_accel(x, p);\n\n constexpr double dt = 0.01;\n while (!view->should_close()) {\n x = dynamics(x, dt);\n\n geo->add_axes({x.T_body_from_world.inverse()});\n const SE3 world_from_sensor = (sensor_from_body * x.T_body_from_world).inverse();\n geo->add_axes({world_from_sensor, 0.25});\n const auto res =\n observe_accel(x.T_body_from_world, x.eps_dot, x.eps_ddot, sensor_from_body, g);\n\n geo->add_ray(\n {world_from_sensor.translation(), world_from_sensor.so3() * res, res.norm()});\n\n geo->flip();\n\n view->spin_until_step();\n }\n}\n*\/\n\nParameters mock_parameters() {\n const jcc::Vec3 g(0.0, 0.0, -1.3);\n \/\/ const jcc::Vec3 t(0.1, 0.5, 0.1);\n const jcc::Vec3 t(0.0, 0.1, 0.25);\n \/\/ const jcc::Vec3 t = jcc::Vec3::Zero();\n const SO3 r_vehicle_from_sensor = SO3::exp(jcc::Vec3(0.0, 0.0, 0.0));\n const SE3 vehicle_from_sensor(r_vehicle_from_sensor, t);\n Parameters p;\n p.T_sensor_from_body = vehicle_from_sensor;\n p.g_world = g;\n return p;\n}\n\nvoid setup() {\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n view->set_target_from_world(\n SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));\n view->set_continue_time_ms(10);\n\n const auto background = view->add_primitive<viewer::SimpleGeometry>();\n const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};\n background->add_plane({ground});\n background->flip();\n}\n\nvoid draw_states(viewer::SimpleGeometry& geo,\n const std::vector<State>& states,\n bool truth) {\n const int n_states = static_cast<int>(states.size());\n for (int k = 0; k < n_states; ++k) {\n auto& state = states.at(k);\n const SE3 T_world_from_body = state.T_body_from_world.inverse();\n if (truth) {\n geo.add_axes({T_world_from_body, 0.1});\n } else {\n geo.add_axes({T_world_from_body, 0.05, 2.0, true});\n\n if (k < n_states - 1) {\n const auto& next_state = states.at(k + 1);\n const SE3 T_world_from_body_next = next_state.T_body_from_world.inverse();\n geo.add_line(\n {T_world_from_body.translation(), T_world_from_body_next.translation()});\n }\n }\n }\n}\n\nvoid print_state(const State& x) {\n std::cout << \"\\teps_dot : \" << x.eps_dot.transpose() << std::endl;\n std::cout << \"\\teps_ddot : \" << x.eps_ddot.transpose() << std::endl;\n std::cout << \"\\taccel_bias: \" << x.accel_bias.transpose() << std::endl;\n std::cout << \"\\tgyro_bias : \" << x.gyro_bias.transpose() << std::endl;\n \/\/ const auto res = observe_accel(xp.x, true_params);\n \/\/ std::cout << \"\\tExpected Measurement: \" << res.transpose() << std::endl;\n}\n\ntemplate <int dim, int row, int mat_size>\nvoid set_diag_to_value(MatNd<mat_size, mat_size>& mat, double value) {\n mat.template block<dim, dim>(row, row) = (MatNd<dim, dim>::Identity() * value);\n}\n} \/\/ namespace\n\nclass JetOptimizer {\n public:\n JetOptimizer() {\n MatNd<AccelMeasurement::DIM, AccelMeasurement::DIM> accel_cov;\n accel_cov.setZero();\n set_diag_to_value<AccelMeasurementDelta::observed_acceleration_error_dim,\n AccelMeasurementDelta::observed_acceleration_error_ind>(accel_cov,\n 0.01);\n\n MatNd<FiducialMeasurement::DIM, FiducialMeasurement::DIM> fiducial_cov;\n fiducial_cov.block<3, 3>(0, 0) = MatNd<3, 3>::Identity() * 0.001;\n fiducial_cov.block<3, 3>(3, 3) = MatNd<3, 3>::Identity() * 0.0001;\n\n MatNd<State::DIM, State::DIM> state_cov;\n state_cov.setZero();\n set_diag_to_value<StateDelta::accel_bias_error_dim, StateDelta::accel_bias_error_ind>(\n state_cov, 0.0001);\n set_diag_to_value<StateDelta::gyro_bias_error_dim, StateDelta::gyro_bias_error_ind>(\n state_cov, 0.0001);\n set_diag_to_value<StateDelta::eps_dot_error_dim, StateDelta::eps_dot_error_ind>(\n state_cov, 0.0001);\n set_diag_to_value<StateDelta::eps_ddot_error_dim, StateDelta::eps_ddot_error_ind>(\n state_cov, 0.0001);\n\n constexpr int T_error_dim = StateDelta::T_body_from_world_error_log_dim;\n constexpr int T_error_ind = StateDelta::T_body_from_world_error_log_ind;\n set_diag_to_value<T_error_dim, T_error_ind>(state_cov, 0.001);\n\n std::cout << \"AAAAA\" << std::endl;\n std::cout << accel_cov << std::endl;\n\n imu_id_ = pose_opt_.add_error_model<AccelMeasurement>(accel_error_model, accel_cov);\n fiducial_id_ = pose_opt_.add_error_model<FiducialMeasurement>(fiducial_error_model,\n fiducial_cov);\n pose_opt_.set_dynamics_cov(state_cov);\n }\n\n void measure_imu(const AccelMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, imu_id_);\n }\n\n void measure_fiducial(const FiducialMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, fiducial_id_);\n }\n\n JetPoseOptimizer::Solution solve(const std::vector<State> x, const Parameters& p) {\n const auto visitor = [](const JetPoseOptimizer::Solution& soln) {\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n\n draw_states(*geo, soln.x, false);\n geo->flip();\n std::cout << \"\\tOptimized g: \" << soln.p.g_world.transpose() << std::endl;\n std::cout << \"\\tOptimized T_sensor_from_body: \"\n << soln.p.T_sensor_from_body.translation().transpose() << \"; \"\n << soln.p.T_sensor_from_body.so3().log().transpose() << std::endl;\n view->spin_until_step();\n geo->clear();\n };\n\n return pose_opt_.solve({x, p}, visitor);\n }\n\n private:\n JetPoseOptimizer pose_opt_{rk4_integrate};\n int imu_id_ = -1;\n int fiducial_id_ = -1;\n};\n\nvoid run_filter() {\n const Parameters true_params = mock_parameters();\n\n JetOptimizer jet_opt;\n\n FilterState<State> xp0;\n xp0.P.setIdentity();\n xp0.x.eps_dot[0] = 1.0;\n xp0.x.eps_dot[4] = -0.1;\n xp0.x.eps_dot[5] = -1.0;\n\n xp0.x.eps_ddot[1] = 0.01;\n xp0.x.eps_ddot[5] = 0.01;\n\n xp0.time_of_validity = {};\n\n State true_x = xp0.x;\n true_x.eps_dot[4] = 0.1;\n\n JetFilter jf(xp0);\n\n \/\/ AccelMeasurement imu_meas;\n \/\/ imu_meas.observed_acceleration[0] = 2.0;\n\n setup();\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto obs_geo = view->add_primitive<viewer::SimpleGeometry>();\n constexpr double sphere_size_m = 0.05;\n\n std::vector<State> ground_truth;\n std::vector<State> est_states;\n\n TimePoint start_time = {};\n constexpr auto dt = to_duration(0.1);\n\n constexpr int NUM_SIM_STEPS = 25;\n\n TimePoint current_time = start_time;\n\n for (int k = 0; k < NUM_SIM_STEPS; ++k) {\n if (k > 75 && k < 95) {\n true_x.eps_ddot[4] = 0.1;\n true_x.eps_ddot[3] = 0.1;\n true_x.eps_ddot[5] = -0.01;\n true_x.eps_ddot[1] = -0.01;\n } else if (k > 95) {\n true_x.eps_ddot.setZero();\n }\n\n \/\/\n \/\/ Accelerometer Observation\n \/\/\n \/\/ if ((k % 10 == 0) && k > 75) {\n if (true) {\n ground_truth.push_back(true_x);\n const AccelMeasurement imu_meas = {observe_accel(true_x, true_params)};\n std::cout << \"Accel: \" << imu_meas.observed_acceleration.transpose() << std::endl;\n\n jf.measure_imu(imu_meas, current_time);\n jet_opt.measure_imu(imu_meas, current_time);\n\n jf.free_run();\n est_states.push_back(jf.state().x);\n assert(jf.state().time_of_validity == current_time);\n\n const jcc::Vec4 accel_color(0.0, 0.7, 0.7, 0.8);\n obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),\n sphere_size_m, accel_color});\n\n const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();\n const jcc::Vec3 observed_accel_body_frame =\n (world_from_body.so3() * true_params.T_sensor_from_body.so3().inverse() *\n imu_meas.observed_acceleration);\n\n obs_geo->add_line(\n {world_from_body.translation(),\n world_from_body.translation() + (0.25 * observed_accel_body_frame),\n accel_color});\n }\n\n \/\/\n \/\/ Fiducial Measurement\n \/\/\n\n {\n constexpr auto dt2 = to_duration(0.05);\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt2));\n current_time += dt2;\n\n ground_truth.push_back(true_x);\n const FiducialMeasurement fiducial_meas = observe_fiducial(true_x, true_params);\n\n jf.measure_fiducial(fiducial_meas, current_time);\n jet_opt.measure_fiducial(fiducial_meas, current_time);\n\n jf.free_run();\n est_states.push_back(jf.state().x);\n assert(jf.state().time_of_validity == current_time);\n obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),\n sphere_size_m, jcc::Vec4(1.0, 0.0, 0.0, 1.0)});\n }\n\n \/\/\n \/\/ Printout\n \/\/\n {\n const auto xp = jf.state();\n std::cout << \"k: \" << k << std::endl;\n print_state(xp.x);\n }\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt));\n current_time += dt;\n }\n\n \/\/ Do the optimization\n\n obs_geo->flip();\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n draw_states(*geo, ground_truth, true);\n geo->flip();\n\n \/\/ const std::vector<State> crap_init(est_states.size(), xp0.x);\n \/\/ const auto solution = jet_opt.solve(crap_init, jf.parameters());\n const auto solution = jet_opt.solve(est_states, jf.parameters());\n \/\/ const auto solution = jet_opt.solve(ground_truth, jf.parameters());\n\n for (std::size_t k = 0; k < solution.x.size(); ++k) {\n const auto& state = solution.x.at(k);\n std::cout << \"----- \" << k << std::endl;\n print_state(state);\n std::cout << \"\\\\\\\\\\\\\\\\\\\\\\\\\" << std::endl;\n print_state(ground_truth.at(k));\n }\n std::cout << \"Optimized g: \" << solution.p.g_world.transpose() << std::endl;\n std::cout << \"Optimized T_sensor_from_body: \"\n << solution.p.T_sensor_from_body.translation().transpose() << \"; \"\n << solution.p.T_sensor_from_body.so3().log().transpose() << std::endl;\n\n draw_states(*geo, solution.x, false);\n\n view->spin_until_step();\n}\n\n} \/\/ namespace jet_filter\n} \/\/ namespace estimation\n\nint main() {\n \/\/ estimation::jet_filter::go();\n estimation::jet_filter::run_filter();\n}<|endoftext|>"} {"text":"<commit_before>#include \"application.h\"\n#include \"TimeAlarms.h\"\n#include \"Adafruit_LEDBackpack.h\"\n#include \"Adafruit_GFX.h\"\n#include \"Adafruit_MCP9808.h\"\n#include <vector>\n#undef now()\n\nbool isDST(int dayOfMonth, int month, int dayOfWeek, String rule);\nvoid refreshDisplayTime();\nvoid addAlarms();\nvoid markDelete(int hour, int minute);\nint checkDelete(AlarmID_t ID);\nvoid setAlarm(int hour, int minute, int second, bool isOnce, bool light, bool sound, int dayOfWeek); \/\/ignore = -1, Sunday = 1, etc\nvoid SoundAlarm();\nvoid LightAlarm();\nvoid lightFadeIn(int hour, int minute);\n\nAdafruit_7segment display = Adafruit_7segment();\nAdafruit_MCP9808 tempSensor = Adafruit_MCP9808();\n\nconst int ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;\nunsigned long lastSync = millis();\nunsigned long lastBeep = millis();\nint DSTJumpHour; \/\/When DST takes effect\ndouble temp;\nbool alarm = false;\n\nstruct Preferences {\n int timeZone; \/\/UTC time zone offset\n int hourFormat; \/\/12 or 24\n int piezoHertz; \/\/Piezo alarm frequency\n String DSTRule; \/\/US, EU, or OFF\n std::vector<std::vector<int>> alarmTimes; \/\/ {hour, minute, second, isOnce, light, sound, dayOfWeek, del}\n} preferences;\n\nint piezoPin = A4;\n\nvoid setup() {\n if(EEPROM.read(0) == 117) {\n EEPROM.get(1, preferences);\n } else {\n preferences = {-8, 12, 2000, \"US\"};\n EEPROM.put(1, preferences);\n EEPROM.put(0, 117);\n }\n\n if(preferences.DSTRule == \"US\") {\n DSTJumpHour = 2;\n } else if(preferences.DSTRule == \"EU\") {\n DSTJumpHour = 1 + preferences.timeZone;\n } else {\n DSTJumpHour = 0;\n }\n\n \/\/Set the proper time zone according to DST status\n Time.zone(isDST(Time.day(), Time.month(), Time.weekday(), preferences.DSTRule) ? preferences.timeZone + 1 : preferences.timeZone);\n\n \/\/Setup the 7-segment display\n display.begin(0x70);\n display.setBrightness(15); \/\/TODO: adjust brightness to optimize for veneer\/time\n\n \/\/Add alarms stored in eeprom\n addAlarms();\n\n \/\/Setup the temperature sensor\n tempSensor.setResolution(MCP9808_SLOWEST);\n\n \/\/Cloud variables\n Spark.variable(\"Temperature\", &temp, DOUBLE);\n}\n\nvoid loop() {\n \/\/Request time synchronization from the Spark Cloud every 24 hours\n if (millis() - lastSync > ONE_DAY_MILLIS) {\n Spark.syncTime();\n lastSync = millis();\n }\n\n \/\/Update time zone at DSTJumpHour incase DST is now in effect\n if(Time.hour() == DSTJumpHour && Time.minute() == 0) {\n Time.zone(isDST(Time.day(), Time.month(), Time.weekday(), preferences.DSTRule) ? preferences.timeZone + 1 : preferences.timeZone);\n }\n\n refreshDisplayTime();\n temp = tempSensor.getTemperature();\n\n \/\/Sound alarm check\n if(alarm) {\n if(millis() - lastBeep > 600) {\n lastBeep = millis();\n tone(piezoPin, preferences.piezoHertz, 300);\n }\n }\n\n \/\/Delay for checking alarms\/timers\n Alarm.delay(1);\n}\n\n\/\/Return true if DST is currently observed\nbool isDST(int dayOfMonth, int month, int dayOfWeek, String rule) {\n if(rule == \"US\") {\n \/\/Month quick check\n if (month < 3 || month > 11) {\n return false;\n } else if (month > 3 && month < 11) {\n return true;\n }\n \/\/The US observes DST from the first Sunday of March\n \/\/The US observes DST until the first Sunday of November\n int previousSunday = dayOfMonth - dayOfWeek + 1;\n if (month == 3) {\n return previousSunday >= 1;\n } else {\n return previousSunday <= 0;\n }\n } else if(rule == \"EU\") {\n \/\/Month quick check\n if (month < 3 || month > 10) {\n return false;\n } else if (month > 3 && month < 10) {\n return true;\n }\n \/\/The EU observes DST from the last Sunday of March\n \/\/The EU observes DST until the last Sunday of November\n int previousSunday = dayOfMonth - dayOfWeek + 1;\n if(month == 3) {\n if(previousSunday+7>31) {\n return true;\n } else {\n return false;\n }\n } else {\n if(previousSunday+7>31) {\n return false;\n } else {\n return true;\n }\n }\n } else {\n return false;\n }\n}\n\n\/\/display the current time on the 7-segment display\nvoid refreshDisplayTime() {\n unsigned long currentTime = Time.now();\n int minute = Time.minute(currentTime);\n int hour;\n int digits;\n\n if(preferences.hourFormat == 12) {\n hour = Time.hourFormat12(currentTime);\n } else {\n hour = Time.hour(currentTime);\n }\n\n digits = hour\/10*1000 + hour%10*100 + minute\/10*10 + minute%10;\n\n display.print(digits);\n display.drawColon(true);\n display.writeDisplay();\n}\n\n\/\/Add alarms from eeprom\nvoid addAlarms() {\n for(int i=0;i<preferences.alarmTimes.size();i++) {\n setAlarm(preferences.alarmTimes.at(i).at(0), preferences.alarmTimes.at(i).at(1), preferences.alarmTimes.at(i).at(2), preferences.alarmTimes.at(3),\n preferences.alarmTimes.at(i).at(4), preferences.alarmTimes.at(i).at(5), preferences.alarmTimes.at(i).at(6));\n }\n}\n\n\/\/Mark an alarm for deletion\nvoid markDelete(int day, int hour, int minute) {\n for(int i=0;i<preferences.alarmTimes.size();i++) {\n if(preferences.alarmTimes.at(i).at(6) == day && preferences.alarmTimes.at(i).at(0) == hour && preferences.alarmTimes.at(i).at(1) == minute) {\n preferences.alarmTimes.at(i).at(7) = true;\n }\n }\n}\n\n\/\/Check and if marked, delete the alarm from eeprom and TimeAlarms\n\/\/Returns 0 if deleted, -1 if not found, or the vector index\nint checkDelete(AlarmID_t ID) {\n unsigned long currentTime = Time.now();\n int hour = Time.hour(currentTime);\n int minute = Time.minute(currentTime);\n int alarmIndex = -1;\n\n for(int i=0;i<preferences.alarmTimes.size();i++) {\n if(preferences.alarmTimes.at(i).at(0) == hour && preferences.alarmTimes.at(i).at(1) == minute) {\n alarmIndex = i;\n if(preferences.alarmTimes.at(i).at(7) == true) {\n Alarm.free(ID);\n preferences.alarmTimes.erase(i);\n return 0;\n }\n }\n }\n return alarmIndex;\n}\n\n\/\/Set an alarm according to the given parameters\nvoid setAlarm(int hour, int minute, int second, bool isOnce, bool light, bool sound, int dayOfWeek) {\n unsigned long currentTime = Time.now();\n int currentDay = Time.weekday(currentTime);\n int currentHour = Time.hour(currentTime);\n int currentMinute = Time.minute(currentTime);\n int day2 = dayOfWeek;\n int hour2 = hour;\n int minute2 = minute;\n\n \/\/set a LightAlarm to go off 30 minutes early if light is enabled\n if(light) {\n minute2 -= 30;\n if(minute2 < 0) {\n minute2 = 60 + minute2;\n hour2 -= 1;\n if(hour2 < 0) {\n hour2 = 23;\n day2 -= 1;\n if(day2 < 1) {\n day2 = 7;\n }\n }\n }\n\n bool enoughTime = true;\n currentMinute -= 30;\n if(currentMinute < 0) {\n currentMinute = 60 + currentMinute;\n currentHour -= 1;\n if(currentHour < 0) {\n currentHour = 23;\n currentDay -= 1;\n if(currentDay < 1) {\n currentDay = 7;\n }\n }\n }\n if(currentDay == day2 && currentHour >= hour2 && currentMinute >= minute2) {\n enoughTime = false;\n }\n\n if(!enoughTime) {\n\n }\n if(isOnce) {\n if(!enoughTime) {\n markDelete(dayOfWeek, hour, minute);\n } else if(dayOfWeek != -1) {\n Alarm.alarmOnce(day2, hour2, minute2, second, LightAlarm);\n } else {\n Alarm.alarmOnce(hour2, minute2, second, LightAlarm);\n }\n } else {\n if(dayOfWeek != -1) {\n Alarm.alarmRepeat(day2, hour2, minute2, second, LightAlarm);\n } else {\n Alarm.alarmRepeat(hour2, minute2, second, LightAlarm);\n }\n }\n }\n\n \/\/set a SoundAlarm if sound is enabled or if both sound and light are disabled\n if(sound || (!light && !sound)) {\n if(isOnce) {\n if(dayOfWeek != -1) {\n Alarm.alarmOnce(dayOfWeek, hour, minute, second, SoundAlarm);\n } else {\n Alarm.alarmOnce(hour, minute, second, SoundAlarm);\n }\n } else {\n if(dayOfWeek != -1) {\n Alarm.alarmRepeat(dayOfWeek, hour, minute, second, SoundAlarm);\n } else {\n Alarm.alarmRepeat(hour, minute, second, SoundAlarm);\n }\n }\n }\n\n preferences.lightAlarmTimes.push_back(hour, minute, second, isOnce, light, sound, dayOfWeek, false);\n}\n\nvoid SoundAlarm() {\n int alarmIndex = checkDelete(Alarm.getTriggeredAlarmId());\n if(alarmIndex == 0) {\n return;\n }\n alarm = true;\n}\n\nvoid LightAlarm() {\n int alarmIndex = checkDelete(Alarm.getTriggeredAlarmId());\n if(alarmIndex == 0) {\n return;\n }\n lightFadeIn(preferences.alarmTimes.at(alarmIndex).at(0), preferences.alarmTimes.at(alarmIndex).at(1));\n}\n\nvoid lightFadeIn(int hour, int minute) {\n \/\/start led fade in to given time\n}\n<commit_msg>Light Fade in Functionality<commit_after>#include \"application.h\"\n#include \"TimeAlarms.h\"\n#include \"Adafruit_LEDBackpack.h\"\n#include \"Adafruit_GFX.h\"\n#include \"Adafruit_MCP9808.h\"\n#include <vector>\n#undef now()\n\nbool isDST(int dayOfMonth, int month, int dayOfWeek, String rule);\nvoid refreshDisplayTime();\nvoid addAlarms();\nvoid markDelete(int hour, int minute);\nint checkDelete(AlarmID_t ID);\nvoid setAlarm(int hour, int minute, int second, bool isOnce, bool light, bool sound, int dayOfWeek); \/\/ignore = -1, Sunday = 1, etc\nvoid SoundAlarm();\nvoid LightAlarm();\nvoid lightFadeIn(int hour, int minute);\n\nAdafruit_7segment display = Adafruit_7segment();\nAdafruit_MCP9808 tempSensor = Adafruit_MCP9808();\n\nconst int ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;\nunsigned long lastSync = millis();\nunsigned long lastBeep = millis();\nunsigned long lightS;\nunsigned long lightF;\nint maxBrightness;\nint DSTJumpHour; \/\/When DST takes effect\nint driverCurrent = 1000; \/\/Driver current output (in mA)\nint maxBrightness;\ndouble temp;\nbool alarm = false;\nbool light = false;\n\nstruct Preferences {\n int timeZone; \/\/UTC time zone offset\n int hourFormat; \/\/12 or 24\n int piezoHertz; \/\/Piezo alarm frequency\n int LEDCurrent; \/\/LED current rating (in mA)\n int ledBrightness; \/\/Maximum brightness (0 to 100%)\n String DSTRule; \/\/US, EU, or OFF\n std::vector<std::vector<int>> alarmTimes; \/\/ {hour, minute, second, isOnce, light, sound, dayOfWeek, del}\n} preferences;\n\nint piezoPin = A4;\nint LEDPin = A7;\n\nvoid setup() {\n if(EEPROM.read(0) == 117) {\n EEPROM.get(1, preferences);\n } else {\n std::vector<std::vector<int>> alarmTimes;\n preferences = {-8, 12, 2000, .7, 100, \"US\", alarmTimes};\n EEPROM.put(1, preferences);\n EEPROM.put(0, 117);\n }\n\n if(preferences.DSTRule == \"US\") {\n DSTJumpHour = 2;\n } else if(preferences.DSTRule == \"EU\") {\n DSTJumpHour = 1 + preferences.timeZone;\n } else {\n DSTJumpHour = 0;\n }\n\n \/\/Set the proper time zone according to DST status\n Time.zone(isDST(Time.day(), Time.month(), Time.weekday(), preferences.DSTRule) ? preferences.timeZone + 1 : preferences.timeZone);\n\n \/\/Setup the 7-segment display\n display.begin(0x70);\n display.setBrightness(15); \/\/TODO: adjust brightness to optimize for veneer\/time\n\n \/\/Pin setup\n pinMode(LEDPin, OUTPUT);\n\n \/\/Add alarms stored in eeprom\n addAlarms();\n\n \/\/Setup the temperature sensor\n tempSensor.setResolution(MCP9808_SLOWEST);\n\n \/\/Cloud variables\n Spark.variable(\"Temperature\", &temp, DOUBLE);\n}\n\nvoid loop() {\n unsigned long currentTime = Time.now();\n\n \/\/Request time synchronization from the Spark Cloud every 24 hours\n if (millis() - lastSync > ONE_DAY_MILLIS) {\n Spark.syncTime();\n lastSync = millis();\n }\n\n \/\/Update time zone at DSTJumpHour incase DST is now in effect\n if(Time.hour(currentTime) == DSTJumpHour && Time.minute(currentTime) == 0) {\n Time.zone(isDST(Time.day(currentTime), Time.month(currentTime), Time.weekday(currentTime), preferences.DSTRule) ? preferences.timeZone + 1 : preferences.timeZone);\n }\n\n refreshDisplayTime();\n temp = tempSensor.getTemperature();\n\n \/\/Sound alarm check\n if(alarm) {\n if(millis() - lastBeep > 600) {\n lastBeep = millis();\n tone(piezoPin, preferences.piezoHertz, 300);\n }\n }\n\n \/\/Light alarm check\n if(light) {\n analogWrite(LEDPin, min(maxBrightness, ((currentTime - lightS) \/ (lightF - lightS)) * maxBrightness));\n }\n\n \/\/Delay for checking alarms\/timers\n Alarm.delay(1);\n}\n\n\/\/Return true if DST is currently observed\nbool isDST(int dayOfMonth, int month, int dayOfWeek, String rule) {\n if(rule == \"US\") {\n \/\/Month quick check\n if (month < 3 || month > 11) {\n return false;\n } else if (month > 3 && month < 11) {\n return true;\n }\n \/\/The US observes DST from the first Sunday of March\n \/\/The US observes DST until the first Sunday of November\n int previousSunday = dayOfMonth - dayOfWeek + 1;\n if (month == 3) {\n return previousSunday >= 1;\n } else {\n return previousSunday <= 0;\n }\n } else if(rule == \"EU\") {\n \/\/Month quick check\n if (month < 3 || month > 10) {\n return false;\n } else if (month > 3 && month < 10) {\n return true;\n }\n \/\/The EU observes DST from the last Sunday of March\n \/\/The EU observes DST until the last Sunday of November\n int previousSunday = dayOfMonth - dayOfWeek + 1;\n if(month == 3) {\n if(previousSunday+7>31) {\n return true;\n } else {\n return false;\n }\n } else {\n if(previousSunday+7>31) {\n return false;\n } else {\n return true;\n }\n }\n } else {\n return false;\n }\n}\n\n\/\/display the current time on the 7-segment display\nvoid refreshDisplayTime() {\n unsigned long currentTime = Time.now();\n int minute = Time.minute(currentTime);\n int hour;\n int digits;\n\n if(preferences.hourFormat == 12) {\n hour = Time.hourFormat12(currentTime);\n } else {\n hour = Time.hour(currentTime);\n }\n\n digits = hour\/10*1000 + hour%10*100 + minute\/10*10 + minute%10;\n\n display.print(digits);\n display.drawColon(true);\n display.writeDisplay();\n}\n\n\/\/Add alarms from eeprom\nvoid addAlarms() {\n for(int i=0;i<preferences.alarmTimes.size();i++) {\n setAlarm(preferences.alarmTimes.at(i).at(0), preferences.alarmTimes.at(i).at(1), preferences.alarmTimes.at(i).at(2), preferences.alarmTimes.at(3),\n preferences.alarmTimes.at(i).at(4), preferences.alarmTimes.at(i).at(5), preferences.alarmTimes.at(i).at(6));\n }\n}\n\n\/\/Mark an alarm for deletion\nvoid markDelete(int day, int hour, int minute) {\n for(int i=0;i<preferences.alarmTimes.size();i++) {\n if(preferences.alarmTimes.at(i).at(6) == day && preferences.alarmTimes.at(i).at(0) == hour && preferences.alarmTimes.at(i).at(1) == minute) {\n preferences.alarmTimes.at(i).at(7) = true;\n }\n }\n}\n\n\/\/Check and if marked, delete the alarm from eeprom and TimeAlarms\n\/\/Returns 0 if deleted, -1 if not found, or the vector index\nint checkDelete(AlarmID_t ID) {\n unsigned long currentTime = Time.now();\n int hour = Time.hour(currentTime);\n int minute = Time.minute(currentTime);\n int alarmIndex = -1;\n\n for(int i=0;i<preferences.alarmTimes.size();i++) {\n if(preferences.alarmTimes.at(i).at(0) == hour && preferences.alarmTimes.at(i).at(1) == minute) {\n alarmIndex = i;\n if(preferences.alarmTimes.at(i).at(7) == true) {\n Alarm.free(ID);\n preferences.alarmTimes.erase(i);\n return 0;\n }\n }\n }\n return alarmIndex;\n}\n\n\/\/Set an alarm according to the given parameters\nvoid setAlarm(int hour, int minute, int second, bool isOnce, bool light, bool sound, int dayOfWeek) {\n unsigned long currentTime = Time.now();\n int currentDay = Time.weekday(currentTime);\n int currentHour = Time.hour(currentTime);\n int currentMinute = Time.minute(currentTime);\n int day2 = dayOfWeek;\n int hour2 = hour;\n int minute2 = minute;\n\n \/\/set a LightAlarm to go off 30 minutes early if light is enabled\n if(light) {\n minute2 -= 30;\n if(minute2 < 0) {\n minute2 = 60 + minute2;\n hour2 -= 1;\n if(hour2 < 0) {\n hour2 = 23;\n day2 -= 1;\n if(day2 < 1) {\n day2 = 7;\n }\n }\n }\n\n bool enoughTime = true;\n currentMinute -= 30;\n if(currentMinute < 0) {\n currentMinute = 60 + currentMinute;\n currentHour -= 1;\n if(currentHour < 0) {\n currentHour = 23;\n currentDay -= 1;\n if(currentDay < 1) {\n currentDay = 7;\n }\n }\n }\n if(currentDay == day2 && currentHour >= hour2 && currentMinute >= minute2) {\n enoughTime = false;\n }\n\n if(!enoughTime) {\n\n }\n if(isOnce) {\n if(!enoughTime) {\n markDelete(dayOfWeek, hour, minute);\n } else if(dayOfWeek != -1) {\n Alarm.alarmOnce(day2, hour2, minute2, second, LightAlarm);\n } else {\n Alarm.alarmOnce(hour2, minute2, second, LightAlarm);\n }\n } else {\n if(dayOfWeek != -1) {\n Alarm.alarmRepeat(day2, hour2, minute2, second, LightAlarm);\n } else {\n Alarm.alarmRepeat(hour2, minute2, second, LightAlarm);\n }\n }\n }\n\n \/\/set a SoundAlarm if sound is enabled or if both sound and light are disabled\n if(sound || (!light && !sound)) {\n if(isOnce) {\n if(dayOfWeek != -1) {\n Alarm.alarmOnce(dayOfWeek, hour, minute, second, SoundAlarm);\n } else {\n Alarm.alarmOnce(hour, minute, second, SoundAlarm);\n }\n } else {\n if(dayOfWeek != -1) {\n Alarm.alarmRepeat(dayOfWeek, hour, minute, second, SoundAlarm);\n } else {\n Alarm.alarmRepeat(hour, minute, second, SoundAlarm);\n }\n }\n }\n\n preferences.lightAlarmTimes.push_back(hour, minute, second, isOnce, light, sound, dayOfWeek, false);\n}\n\nvoid SoundAlarm() {\n int alarmIndex = checkDelete(Alarm.getTriggeredAlarmId());\n if(alarmIndex == 0) {\n return;\n }\n alarm = true;\n}\n\nvoid LightAlarm() {\n int alarmIndex = checkDelete(Alarm.getTriggeredAlarmId());\n if(alarmIndex == 0) {\n return;\n }\n lightFadeIn(preferences.alarmTimes.at(alarmIndex).at(0), preferences.alarmTimes.at(alarmIndex).at(1));\n}\n\n\/\/Start light fade in to a given time\nvoid lightFadeIn(int hour, int minute) {\n lightS = Time.now();\n int difference = (hour*60 + minute) - (Time.hour(lightS)*60 + Time.minute(lightS));\n if(difference < 0) {\n difference += 24*60;\n }\n lightF = lightS + difference*60;\n maxBrightness = 4095*(preferences.LEDCurrent\/driverCurrent)*(preferences.ledBrightness\/100);\n light = true;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2011 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#include \"SkBenchmark.h\"\n#include \"SkBitmap.h\"\n#include \"SkCanvas.h\"\n#include \"SkDashPathEffect.h\"\n#include \"SkPaint.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n#include \"SkString.h\"\n#include \"SkTDArray.h\"\n\n\n\/*\n * Cases to consider:\n *\n * 1. antialiasing on\/off (esp. width <= 1)\n * 2. strokewidth == 0, 1, 2\n * 3. hline, vline, diagonal, rect, oval\n * 4. dots [1,1] ([N,N] where N=strokeWidth?) or arbitrary (e.g. [2,1] or [1,2,3,2])\n *\/\nstatic void path_hline(SkPath* path) {\n path->moveTo(SkIntToScalar(10), SkIntToScalar(10));\n path->lineTo(SkIntToScalar(600), SkIntToScalar(10));\n}\n\nclass DashBench : public SkBenchmark {\nprotected:\n SkString fName;\n SkTDArray<SkScalar> fIntervals;\n int fWidth;\n SkPoint fPts[2];\n bool fDoClip;\n\n enum {\n N = SkBENCHLOOP(100)\n };\npublic:\n DashBench(void* param, const SkScalar intervals[], int count, int width,\n bool doClip = false) : INHERITED(param) {\n fIntervals.append(count, intervals);\n for (int i = 0; i < count; ++i) {\n fIntervals[i] *= width;\n }\n fWidth = width;\n fName.printf(\"dash_%d_%s\", width, doClip ? \"clipped\" : \"noclip\");\n fDoClip = doClip;\n\n fPts[0].set(SkIntToScalar(10), SkIntToScalar(10));\n fPts[1].set(SkIntToScalar(600), SkIntToScalar(10));\n }\n\n virtual void makePath(SkPath* path) {\n path_hline(path);\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPaint paint;\n this->setupPaint(&paint);\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(SkIntToScalar(fWidth));\n paint.setAntiAlias(false);\n\n SkPath path;\n this->makePath(&path);\n\n paint.setPathEffect(new SkDashPathEffect(fIntervals.begin(),\n fIntervals.count(), 0))->unref();\n\n if (fDoClip) {\n SkRect r = path.getBounds();\n r.inset(-SkIntToScalar(20), -SkIntToScalar(20));\n \/\/ now move it so we don't intersect\n r.offset(0, r.height() * 3 \/ 2);\n canvas->clipRect(r);\n }\n\n this->handlePath(canvas, path, paint, N);\n }\n\n virtual void handlePath(SkCanvas* canvas, const SkPath& path,\n const SkPaint& paint, int N) {\n for (int i = 0; i < N; ++i) {\n\/\/ canvas->drawPoints(SkCanvas::kLines_PointMode, 2, fPts, paint);\n canvas->drawPath(path, paint);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\nclass RectDashBench : public DashBench {\npublic:\n RectDashBench(void* param, const SkScalar intervals[], int count, int width, bool doClip = false)\n : INHERITED(param, intervals, count, width) {\n fName.append(\"_rect\");\n }\n\nprotected:\n virtual void handlePath(SkCanvas* canvas, const SkPath& path,\n const SkPaint& paint, int N) SK_OVERRIDE {\n SkPoint pts[2];\n if (!path.isLine(pts) || pts[0].fY != pts[1].fY) {\n this->INHERITED::handlePath(canvas, path, paint, N);\n } else {\n SkRect rect;\n rect.fLeft = pts[0].fX;\n rect.fTop = pts[0].fY - paint.getStrokeWidth() \/ 2;\n rect.fRight = rect.fLeft + SkIntToScalar(fWidth);\n rect.fBottom = rect.fTop + paint.getStrokeWidth();\n\n SkPaint p(paint);\n p.setStyle(SkPaint::kFill_Style);\n p.setPathEffect(NULL);\n\n int count = SkScalarRoundToInt((pts[1].fX - pts[0].fX) \/ (2*fWidth));\n SkScalar dx = SkIntToScalar(2 * fWidth);\n\n for (int i = 0; i < N*10; ++i) {\n SkRect r = rect;\n for (int j = 0; j < count; ++j) {\n canvas->drawRect(r, p);\n r.offset(dx, 0);\n }\n }\n }\n }\n\nprivate:\n typedef DashBench INHERITED;\n};\n\nstatic void make_unit_star(SkPath* path, int n) {\n SkScalar rad = -SK_ScalarPI \/ 2;\n const SkScalar drad = (n >> 1) * SK_ScalarPI * 2 \/ n;\n\n path->moveTo(0, -SK_Scalar1);\n for (int i = 1; i < n; i++) {\n rad += drad;\n SkScalar cosV, sinV = SkScalarSinCos(rad, &cosV);\n path->lineTo(cosV, sinV);\n }\n path->close();\n}\n\nstatic void make_poly(SkPath* path) {\n make_unit_star(path, 9);\n SkMatrix matrix;\n matrix.setScale(SkIntToScalar(100), SkIntToScalar(100));\n path->transform(matrix);\n}\n\nstatic void make_quad(SkPath* path) {\n SkScalar x0 = SkIntToScalar(10);\n SkScalar y0 = SkIntToScalar(10);\n path->moveTo(x0, y0);\n path->quadTo(x0, y0 + 400 * SK_Scalar1,\n x0 + 600 * SK_Scalar1, y0 + 400 * SK_Scalar1);\n}\n\nstatic void make_cubic(SkPath* path) {\n SkScalar x0 = SkIntToScalar(10);\n SkScalar y0 = SkIntToScalar(10);\n path->moveTo(x0, y0);\n path->cubicTo(x0, y0 + 400 * SK_Scalar1,\n x0 + 600 * SK_Scalar1, y0 + 400 * SK_Scalar1,\n x0 + 600 * SK_Scalar1, y0);\n}\n\nclass MakeDashBench : public SkBenchmark {\n SkString fName;\n SkPath fPath;\n SkAutoTUnref<SkPathEffect> fPE;\n\n enum {\n N = SkBENCHLOOP(400)\n };\n\npublic:\n MakeDashBench(void* param, void (*proc)(SkPath*), const char name[]) : INHERITED(param) {\n fName.printf(\"makedash_%s\", name);\n proc(&fPath);\n\n SkScalar vals[] = { SkIntToScalar(4), SkIntToScalar(4) };\n fPE.reset(new SkDashPathEffect(vals, 2, 0));\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPath dst;\n for (int i = 0; i < N; ++i) {\n SkStrokeRec rec(SkStrokeRec::kHairline_InitStyle);\n\n fPE->filterPath(&dst, fPath, &rec);\n dst.rewind();\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/*\n * We try to special case square dashes (intervals are equal to strokewidth).\n *\/\nclass DashLineBench : public SkBenchmark {\n SkString fName;\n SkScalar fStrokeWidth;\n bool fIsRound;\n SkAutoTUnref<SkPathEffect> fPE;\n\n enum {\n N = SkBENCHLOOP(200)\n };\n\npublic:\n DashLineBench(void* param, SkScalar width, bool isRound) : INHERITED(param) {\n fName.printf(\"dashline_%g_%s\", SkScalarToFloat(width), isRound ? \"circle\" : \"square\");\n fStrokeWidth = width;\n fIsRound = isRound;\n\n SkScalar vals[] = { SK_Scalar1, SK_Scalar1 };\n fPE.reset(new SkDashPathEffect(vals, 2, 0));\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPaint paint;\n this->setupPaint(&paint);\n paint.setStrokeWidth(fStrokeWidth);\n paint.setStrokeCap(fIsRound ? SkPaint::kRound_Cap : SkPaint::kSquare_Cap);\n paint.setPathEffect(fPE);\n for (int i = 0; i < N; ++i) {\n canvas->drawLine(10 * SK_Scalar1, 10 * SK_Scalar1,\n 640 * SK_Scalar1, 10 * SK_Scalar1, paint);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\nclass DrawPointsDashingBench : public SkBenchmark {\n SkString fName;\n int fStrokeWidth;\n bool fDoAA;\n\n SkAutoTUnref<SkPathEffect> fPathEffect;\n\n enum {\n N = SkBENCHLOOP(480)\n };\n\npublic:\n DrawPointsDashingBench(void* param, int dashLength, int strokeWidth, bool doAA)\n : INHERITED(param) {\n fName.printf(\"drawpointsdash_%d_%d%s\", dashLength, strokeWidth, doAA ? \"_aa\" : \"_bw\");\n fStrokeWidth = strokeWidth;\n fDoAA = doAA;\n\n SkScalar vals[] = { SkIntToScalar(dashLength), SkIntToScalar(dashLength) };\n fPathEffect.reset(new SkDashPathEffect(vals, 2, SK_Scalar1, false));\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n\n SkPaint p;\n this->setupPaint(&p);\n p.setColor(SK_ColorBLACK);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SkIntToScalar(fStrokeWidth));\n p.setPathEffect(fPathEffect);\n p.setAntiAlias(fDoAA);\n\n SkPoint pts[2] = {\n { SkIntToScalar(10), 0 },\n { SkIntToScalar(640), 0 }\n };\n\n for (int i = 0; i < N; ++i) {\n\n pts[0].fY = pts[1].fY = SkIntToScalar(i % 480);\n canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\nclass GiantDashBench : public SkBenchmark {\n SkString fName;\n SkPoint fPts[2];\n SkAutoTUnref<SkPathEffect> fPathEffect;\n \n enum {\n N = SkBENCHLOOP(10)\n };\n\npublic:\n enum LineType {\n kHori_LineType,\n kVert_LineType,\n kDiag_LineType\n };\n\n static const char* LineTypeName(LineType lt) {\n static const char* gNames[] = { \"hori\", \"vert\", \"diag\" };\n SkASSERT((size_t)lt <= SK_ARRAY_COUNT(gNames));\n return gNames[lt];\n }\n\n GiantDashBench(void* param, LineType lt) : INHERITED(param) {\n fName.printf(\"giantdashline_%s\", LineTypeName(lt));\n \n \/\/ deliberately pick intervals that won't be caught by asPoints(), so\n \/\/ we can test the filterPath code-path.\n const SkScalar intervals[] = { 2, 1 };\n fPathEffect.reset(new SkDashPathEffect(intervals,\n SK_ARRAY_COUNT(intervals), 0));\n\n SkScalar cx = 640 \/ 2; \/\/ center X\n SkScalar cy = 480 \/ 2; \/\/ center Y\n SkMatrix matrix;\n \n switch (lt) {\n case kHori_LineType:\n matrix.setIdentity();\n break;\n case kVert_LineType:\n matrix.setRotate(90, cx, cy);\n break;\n case kDiag_LineType:\n matrix.setRotate(45, cx, cy);\n break;\n }\n \n const SkScalar overshoot = 10*1000;\n const SkPoint pts[2] = {\n { -overshoot, cy }, { 640 + overshoot, cy }\n };\n matrix.mapPoints(fPts, pts, 2);\n }\n \nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n \n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPaint p;\n this->setupPaint(&p);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(1);\n p.setPathEffect(fPathEffect);\n\n for (int i = 0; i < N; ++i) {\n canvas->drawPoints(SkCanvas::kLines_PointMode, 2, fPts, p);\n }\n }\n \nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic const SkScalar gDots[] = { SK_Scalar1, SK_Scalar1 };\n\n#define PARAM(array) array, SK_ARRAY_COUNT(array)\n\nDEF_BENCH( return new DashBench(p, PARAM(gDots), 0); )\nDEF_BENCH( return new DashBench(p, PARAM(gDots), 1); )\nDEF_BENCH( return new DashBench(p, PARAM(gDots), 1, true); )\nDEF_BENCH( return new DashBench(p, PARAM(gDots), 4); )\nDEF_BENCH( return new MakeDashBench(p, make_poly, \"poly\"); )\nDEF_BENCH( return new MakeDashBench(p, make_quad, \"quad\"); )\nDEF_BENCH( return new MakeDashBench(p, make_cubic, \"cubic\"); )\nDEF_BENCH( return new DashLineBench(p, 0, false); )\nDEF_BENCH( return new DashLineBench(p, SK_Scalar1, false); )\nDEF_BENCH( return new DashLineBench(p, 2 * SK_Scalar1, false); )\nDEF_BENCH( return new DashLineBench(p, 0, true); )\nDEF_BENCH( return new DashLineBench(p, SK_Scalar1, true); )\nDEF_BENCH( return new DashLineBench(p, 2 * SK_Scalar1, true); )\n\nDEF_BENCH( return new DrawPointsDashingBench(p, 1, 1, false); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 1, 1, true); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 3, 1, false); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 3, 1, true); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 5, 5, false); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 5, 5, true); )\n\nDEF_BENCH( return new GiantDashBench(p, GiantDashBench::kHori_LineType); )\nDEF_BENCH( return new GiantDashBench(p, GiantDashBench::kVert_LineType); )\nDEF_BENCH( return new GiantDashBench(p, GiantDashBench::kDiag_LineType); )\n<commit_msg>update to emphasis the culling aspect of the test (making the line much longer, and adding hairline and non-hairline cases.)<commit_after>\n\/*\n * Copyright 2011 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#include \"SkBenchmark.h\"\n#include \"SkBitmap.h\"\n#include \"SkCanvas.h\"\n#include \"SkDashPathEffect.h\"\n#include \"SkPaint.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n#include \"SkString.h\"\n#include \"SkTDArray.h\"\n\n\n\/*\n * Cases to consider:\n *\n * 1. antialiasing on\/off (esp. width <= 1)\n * 2. strokewidth == 0, 1, 2\n * 3. hline, vline, diagonal, rect, oval\n * 4. dots [1,1] ([N,N] where N=strokeWidth?) or arbitrary (e.g. [2,1] or [1,2,3,2])\n *\/\nstatic void path_hline(SkPath* path) {\n path->moveTo(SkIntToScalar(10), SkIntToScalar(10));\n path->lineTo(SkIntToScalar(600), SkIntToScalar(10));\n}\n\nclass DashBench : public SkBenchmark {\nprotected:\n SkString fName;\n SkTDArray<SkScalar> fIntervals;\n int fWidth;\n SkPoint fPts[2];\n bool fDoClip;\n\n enum {\n N = SkBENCHLOOP(100)\n };\npublic:\n DashBench(void* param, const SkScalar intervals[], int count, int width,\n bool doClip = false) : INHERITED(param) {\n fIntervals.append(count, intervals);\n for (int i = 0; i < count; ++i) {\n fIntervals[i] *= width;\n }\n fWidth = width;\n fName.printf(\"dash_%d_%s\", width, doClip ? \"clipped\" : \"noclip\");\n fDoClip = doClip;\n\n fPts[0].set(SkIntToScalar(10), SkIntToScalar(10));\n fPts[1].set(SkIntToScalar(600), SkIntToScalar(10));\n }\n\n virtual void makePath(SkPath* path) {\n path_hline(path);\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPaint paint;\n this->setupPaint(&paint);\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(SkIntToScalar(fWidth));\n paint.setAntiAlias(false);\n\n SkPath path;\n this->makePath(&path);\n\n paint.setPathEffect(new SkDashPathEffect(fIntervals.begin(),\n fIntervals.count(), 0))->unref();\n\n if (fDoClip) {\n SkRect r = path.getBounds();\n r.inset(-SkIntToScalar(20), -SkIntToScalar(20));\n \/\/ now move it so we don't intersect\n r.offset(0, r.height() * 3 \/ 2);\n canvas->clipRect(r);\n }\n\n this->handlePath(canvas, path, paint, N);\n }\n\n virtual void handlePath(SkCanvas* canvas, const SkPath& path,\n const SkPaint& paint, int N) {\n for (int i = 0; i < N; ++i) {\n\/\/ canvas->drawPoints(SkCanvas::kLines_PointMode, 2, fPts, paint);\n canvas->drawPath(path, paint);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\nclass RectDashBench : public DashBench {\npublic:\n RectDashBench(void* param, const SkScalar intervals[], int count, int width, bool doClip = false)\n : INHERITED(param, intervals, count, width) {\n fName.append(\"_rect\");\n }\n\nprotected:\n virtual void handlePath(SkCanvas* canvas, const SkPath& path,\n const SkPaint& paint, int N) SK_OVERRIDE {\n SkPoint pts[2];\n if (!path.isLine(pts) || pts[0].fY != pts[1].fY) {\n this->INHERITED::handlePath(canvas, path, paint, N);\n } else {\n SkRect rect;\n rect.fLeft = pts[0].fX;\n rect.fTop = pts[0].fY - paint.getStrokeWidth() \/ 2;\n rect.fRight = rect.fLeft + SkIntToScalar(fWidth);\n rect.fBottom = rect.fTop + paint.getStrokeWidth();\n\n SkPaint p(paint);\n p.setStyle(SkPaint::kFill_Style);\n p.setPathEffect(NULL);\n\n int count = SkScalarRoundToInt((pts[1].fX - pts[0].fX) \/ (2*fWidth));\n SkScalar dx = SkIntToScalar(2 * fWidth);\n\n for (int i = 0; i < N*10; ++i) {\n SkRect r = rect;\n for (int j = 0; j < count; ++j) {\n canvas->drawRect(r, p);\n r.offset(dx, 0);\n }\n }\n }\n }\n\nprivate:\n typedef DashBench INHERITED;\n};\n\nstatic void make_unit_star(SkPath* path, int n) {\n SkScalar rad = -SK_ScalarPI \/ 2;\n const SkScalar drad = (n >> 1) * SK_ScalarPI * 2 \/ n;\n\n path->moveTo(0, -SK_Scalar1);\n for (int i = 1; i < n; i++) {\n rad += drad;\n SkScalar cosV, sinV = SkScalarSinCos(rad, &cosV);\n path->lineTo(cosV, sinV);\n }\n path->close();\n}\n\nstatic void make_poly(SkPath* path) {\n make_unit_star(path, 9);\n SkMatrix matrix;\n matrix.setScale(SkIntToScalar(100), SkIntToScalar(100));\n path->transform(matrix);\n}\n\nstatic void make_quad(SkPath* path) {\n SkScalar x0 = SkIntToScalar(10);\n SkScalar y0 = SkIntToScalar(10);\n path->moveTo(x0, y0);\n path->quadTo(x0, y0 + 400 * SK_Scalar1,\n x0 + 600 * SK_Scalar1, y0 + 400 * SK_Scalar1);\n}\n\nstatic void make_cubic(SkPath* path) {\n SkScalar x0 = SkIntToScalar(10);\n SkScalar y0 = SkIntToScalar(10);\n path->moveTo(x0, y0);\n path->cubicTo(x0, y0 + 400 * SK_Scalar1,\n x0 + 600 * SK_Scalar1, y0 + 400 * SK_Scalar1,\n x0 + 600 * SK_Scalar1, y0);\n}\n\nclass MakeDashBench : public SkBenchmark {\n SkString fName;\n SkPath fPath;\n SkAutoTUnref<SkPathEffect> fPE;\n\n enum {\n N = SkBENCHLOOP(400)\n };\n\npublic:\n MakeDashBench(void* param, void (*proc)(SkPath*), const char name[]) : INHERITED(param) {\n fName.printf(\"makedash_%s\", name);\n proc(&fPath);\n\n SkScalar vals[] = { SkIntToScalar(4), SkIntToScalar(4) };\n fPE.reset(new SkDashPathEffect(vals, 2, 0));\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPath dst;\n for (int i = 0; i < N; ++i) {\n SkStrokeRec rec(SkStrokeRec::kHairline_InitStyle);\n\n fPE->filterPath(&dst, fPath, &rec);\n dst.rewind();\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/*\n * We try to special case square dashes (intervals are equal to strokewidth).\n *\/\nclass DashLineBench : public SkBenchmark {\n SkString fName;\n SkScalar fStrokeWidth;\n bool fIsRound;\n SkAutoTUnref<SkPathEffect> fPE;\n\n enum {\n N = SkBENCHLOOP(200)\n };\n\npublic:\n DashLineBench(void* param, SkScalar width, bool isRound) : INHERITED(param) {\n fName.printf(\"dashline_%g_%s\", SkScalarToFloat(width), isRound ? \"circle\" : \"square\");\n fStrokeWidth = width;\n fIsRound = isRound;\n\n SkScalar vals[] = { SK_Scalar1, SK_Scalar1 };\n fPE.reset(new SkDashPathEffect(vals, 2, 0));\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPaint paint;\n this->setupPaint(&paint);\n paint.setStrokeWidth(fStrokeWidth);\n paint.setStrokeCap(fIsRound ? SkPaint::kRound_Cap : SkPaint::kSquare_Cap);\n paint.setPathEffect(fPE);\n for (int i = 0; i < N; ++i) {\n canvas->drawLine(10 * SK_Scalar1, 10 * SK_Scalar1,\n 640 * SK_Scalar1, 10 * SK_Scalar1, paint);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\nclass DrawPointsDashingBench : public SkBenchmark {\n SkString fName;\n int fStrokeWidth;\n bool fDoAA;\n\n SkAutoTUnref<SkPathEffect> fPathEffect;\n\n enum {\n N = SkBENCHLOOP(480)\n };\n\npublic:\n DrawPointsDashingBench(void* param, int dashLength, int strokeWidth, bool doAA)\n : INHERITED(param) {\n fName.printf(\"drawpointsdash_%d_%d%s\", dashLength, strokeWidth, doAA ? \"_aa\" : \"_bw\");\n fStrokeWidth = strokeWidth;\n fDoAA = doAA;\n\n SkScalar vals[] = { SkIntToScalar(dashLength), SkIntToScalar(dashLength) };\n fPathEffect.reset(new SkDashPathEffect(vals, 2, SK_Scalar1, false));\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n\n SkPaint p;\n this->setupPaint(&p);\n p.setColor(SK_ColorBLACK);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SkIntToScalar(fStrokeWidth));\n p.setPathEffect(fPathEffect);\n p.setAntiAlias(fDoAA);\n\n SkPoint pts[2] = {\n { SkIntToScalar(10), 0 },\n { SkIntToScalar(640), 0 }\n };\n\n for (int i = 0; i < N; ++i) {\n\n pts[0].fY = pts[1].fY = SkIntToScalar(i % 480);\n canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/\/ Want to test how we handle dashing when 99% of the dash is clipped out\nclass GiantDashBench : public SkBenchmark {\n SkString fName;\n SkScalar fStrokeWidth;\n SkPoint fPts[2];\n SkAutoTUnref<SkPathEffect> fPathEffect;\n \npublic:\n enum LineType {\n kHori_LineType,\n kVert_LineType,\n kDiag_LineType\n };\n\n static const char* LineTypeName(LineType lt) {\n static const char* gNames[] = { \"hori\", \"vert\", \"diag\" };\n SkASSERT((size_t)lt <= SK_ARRAY_COUNT(gNames));\n return gNames[lt];\n }\n\n GiantDashBench(void* param, LineType lt, SkScalar width) : INHERITED(param) {\n fName.printf(\"giantdashline_%s_%g\", LineTypeName(lt), width);\n fStrokeWidth = width;\n\n \/\/ deliberately pick intervals that won't be caught by asPoints(), so\n \/\/ we can test the filterPath code-path.\n const SkScalar intervals[] = { 2, 1 };\n fPathEffect.reset(new SkDashPathEffect(intervals,\n SK_ARRAY_COUNT(intervals), 0));\n\n SkScalar cx = 640 \/ 2; \/\/ center X\n SkScalar cy = 480 \/ 2; \/\/ center Y\n SkMatrix matrix;\n \n switch (lt) {\n case kHori_LineType:\n matrix.setIdentity();\n break;\n case kVert_LineType:\n matrix.setRotate(90, cx, cy);\n break;\n case kDiag_LineType:\n matrix.setRotate(45, cx, cy);\n break;\n }\n \n const SkScalar overshoot = 100*1000;\n const SkPoint pts[2] = {\n { -overshoot, cy }, { 640 + overshoot, cy }\n };\n matrix.mapPoints(fPts, pts, 2);\n }\n \nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n \n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPaint p;\n this->setupPaint(&p);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(fStrokeWidth);\n p.setPathEffect(fPathEffect);\n\n canvas->drawPoints(SkCanvas::kLines_PointMode, 2, fPts, p);\n }\n \nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic const SkScalar gDots[] = { SK_Scalar1, SK_Scalar1 };\n\n#define PARAM(array) array, SK_ARRAY_COUNT(array)\n\nDEF_BENCH( return new DashBench(p, PARAM(gDots), 0); )\nDEF_BENCH( return new DashBench(p, PARAM(gDots), 1); )\nDEF_BENCH( return new DashBench(p, PARAM(gDots), 1, true); )\nDEF_BENCH( return new DashBench(p, PARAM(gDots), 4); )\nDEF_BENCH( return new MakeDashBench(p, make_poly, \"poly\"); )\nDEF_BENCH( return new MakeDashBench(p, make_quad, \"quad\"); )\nDEF_BENCH( return new MakeDashBench(p, make_cubic, \"cubic\"); )\nDEF_BENCH( return new DashLineBench(p, 0, false); )\nDEF_BENCH( return new DashLineBench(p, SK_Scalar1, false); )\nDEF_BENCH( return new DashLineBench(p, 2 * SK_Scalar1, false); )\nDEF_BENCH( return new DashLineBench(p, 0, true); )\nDEF_BENCH( return new DashLineBench(p, SK_Scalar1, true); )\nDEF_BENCH( return new DashLineBench(p, 2 * SK_Scalar1, true); )\n\nDEF_BENCH( return new DrawPointsDashingBench(p, 1, 1, false); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 1, 1, true); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 3, 1, false); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 3, 1, true); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 5, 5, false); )\nDEF_BENCH( return new DrawPointsDashingBench(p, 5, 5, true); )\n\nDEF_BENCH( return new GiantDashBench(p, GiantDashBench::kHori_LineType, 0); )\nDEF_BENCH( return new GiantDashBench(p, GiantDashBench::kVert_LineType, 0); )\nDEF_BENCH( return new GiantDashBench(p, GiantDashBench::kDiag_LineType, 0); )\n\n\/\/ pass 2 to explicitly avoid any 1-is-the-same-as-hairline special casing\n\n\/\/ hori_2 is just too slow to enable at the moment\n\/\/DEF_BENCH( return new GiantDashBench(p, GiantDashBench::kHori_LineType, 2); )\nDEF_BENCH( return new GiantDashBench(p, GiantDashBench::kVert_LineType, 2); )\nDEF_BENCH( return new GiantDashBench(p, GiantDashBench::kDiag_LineType, 2); )\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 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 <ctype.h>\n\n#include \"Benchmark.h\"\n#include \"CrashHandler.h\"\n#include \"Stats.h\"\n#include \"Timer.h\"\n\n#include \"SkCanvas.h\"\n#include \"SkCommandLineFlags.h\"\n#include \"SkForceLinking.h\"\n#include \"SkGraphics.h\"\n#include \"SkString.h\"\n#include \"SkSurface.h\"\n\n#if SK_SUPPORT_GPU\n #include \"GrContextFactory.h\"\n GrContextFactory gGrFactory;\n#endif\n\n__SK_FORCE_IMAGE_DECODER_LINKING;\n\nDEFINE_int32(samples, 10, \"Number of samples to measure for each bench.\");\nDEFINE_int32(overheadLoops, 100000, \"Loops to estimate timer overhead.\");\nDEFINE_double(overheadGoal, 0.0001,\n \"Loop until timer overhead is at most this fraction of our measurments.\");\nDEFINE_string(match, \"\", \"The usual filters on file names of benchmarks to measure.\");\nDEFINE_bool2(quiet, q, false, \"Print only bench name and minimum sample.\");\nDEFINE_bool2(verbose, v, false, \"Print all samples.\");\nDEFINE_string(config, \"nonrendering 8888 gpu\", \"Configs to measure. Options: \"\n \"565 8888 gpu nonrendering debug nullgpu msaa4 msaa16 nvprmsaa4 nvprmsaa16 angle\");\nDEFINE_double(gpuMs, 5, \"Target bench time in millseconds for GPU.\");\nDEFINE_int32(gpuFrameLag, 5, \"Overestimate of maximum number of frames GPU allows to lag.\");\n\n\nstatic SkString humanize(double ms) {\n if (ms > 1e+3) return SkStringPrintf(\"%.3gs\", ms\/1e3);\n if (ms < 1e-3) return SkStringPrintf(\"%.3gns\", ms*1e6);\n if (ms < 1) return SkStringPrintf(\"%.3gµs\", ms*1e3);\n return SkStringPrintf(\"%.3gms\", ms);\n}\n\nstatic double time(int loops, Benchmark* bench, SkCanvas* canvas, SkGLContextHelper* gl) {\n WallTimer timer;\n timer.start();\n if (bench) {\n bench->draw(loops, canvas);\n }\n if (canvas) {\n canvas->flush();\n }\n#if SK_SUPPORT_GPU\n if (gl) {\n SK_GL(*gl, Flush());\n gl->swapBuffers();\n }\n#endif\n timer.end();\n return timer.fWall;\n}\n\nstatic double estimate_timer_overhead() {\n double overhead = 0;\n for (int i = 0; i < FLAGS_overheadLoops; i++) {\n overhead += time(1, NULL, NULL, NULL);\n }\n return overhead \/ FLAGS_overheadLoops;\n}\n\nstatic int cpu_bench(const double overhead, Benchmark* bench, SkCanvas* canvas, double* samples) {\n \/\/ First figure out approximately how many loops of bench it takes to make overhead negligible.\n double bench_plus_overhead;\n do {\n bench_plus_overhead = time(1, bench, canvas, NULL);\n } while (bench_plus_overhead < overhead); \/\/ Shouldn't normally happen.\n\n \/\/ Later we'll just start and stop the timer once but loop N times.\n \/\/ We'll pick N to make timer overhead negligible:\n \/\/\n \/\/ overhead\n \/\/ ------------------------- < FLAGS_overheadGoal\n \/\/ overhead + N * Bench Time\n \/\/\n \/\/ where bench_plus_overhead ≈ overhead + Bench Time.\n \/\/\n \/\/ Doing some math, we get:\n \/\/\n \/\/ (overhead \/ FLAGS_overheadGoal) - overhead\n \/\/ ------------------------------------------ < N\n \/\/ bench_plus_overhead - overhead)\n \/\/\n \/\/ Luckily, this also works well in practice. :)\n const double numer = overhead \/ FLAGS_overheadGoal - overhead;\n const double denom = bench_plus_overhead - overhead;\n const int loops = (int)ceil(numer \/ denom);\n\n for (int i = 0; i < FLAGS_samples; i++) {\n samples[i] = time(loops, bench, canvas, NULL) \/ loops;\n }\n return loops;\n}\n\n#if SK_SUPPORT_GPU\nstatic int gpu_bench(SkGLContextHelper* gl,\n Benchmark* bench,\n SkCanvas* canvas,\n double* samples) {\n \/\/ Make sure we're done with whatever came before.\n SK_GL(*gl, Finish);\n\n \/\/ First, figure out how many loops it'll take to get a frame up to FLAGS_gpuMs.\n int loops = 1;\n double elapsed = 0;\n do {\n loops *= 2;\n \/\/ If the GPU lets frames lag at all, we need to make sure we're timing\n \/\/ _this_ round, not still timing last round. We force this by looping\n \/\/ more times than any reasonable GPU will allow frames to lag.\n for (int i = 0; i < FLAGS_gpuFrameLag; i++) {\n elapsed = time(loops, bench, canvas, gl);\n }\n } while (elapsed < FLAGS_gpuMs);\n\n \/\/ We've overshot at least a little. Scale back linearly.\n loops = (int)ceil(loops * FLAGS_gpuMs \/ elapsed);\n\n \/\/ Might as well make sure we're not still timing our calibration.\n SK_GL(*gl, Finish);\n\n \/\/ Pretty much the same deal as the calibration: do some warmup to make\n \/\/ sure we're timing steady-state pipelined frames.\n for (int i = 0; i < FLAGS_gpuFrameLag; i++) {\n time(loops, bench, canvas, gl);\n }\n\n \/\/ Now, actually do the timing!\n for (int i = 0; i < FLAGS_samples; i++) {\n samples[i] = time(loops, bench, canvas, gl) \/ loops;\n }\n return loops;\n}\n#endif\n\nstatic SkString to_lower(const char* str) {\n SkString lower(str);\n for (size_t i = 0; i < lower.size(); i++) {\n lower[i] = tolower(lower[i]);\n }\n return lower;\n}\n\nstruct Target {\n const char* config;\n Benchmark::Backend backend;\n SkAutoTDelete<SkSurface> surface;\n#if SK_SUPPORT_GPU\n SkGLContextHelper* gl;\n#endif\n};\n\n\/\/ If bench is enabled for backend\/config, returns a Target* for them, otherwise NULL.\nstatic Target* is_enabled(Benchmark* bench, Benchmark::Backend backend, const char* config) {\n if (!bench->isSuitableFor(backend)) {\n return NULL;\n }\n\n for (int i = 0; i < FLAGS_config.count(); i++) {\n if (to_lower(FLAGS_config[i]).equals(config)) {\n Target* target = new Target;\n target->config = config;\n target->backend = backend;\n return target;\n }\n }\n return NULL;\n}\n\n\/\/ Append all targets that are suitable for bench.\nstatic void create_targets(Benchmark* bench, SkTDArray<Target*>* targets) {\n const int w = bench->getSize().fX,\n h = bench->getSize().fY;\n const SkImageInfo _8888 = { w, h, kN32_SkColorType, kPremul_SkAlphaType },\n _565 = { w, h, kRGB_565_SkColorType, kOpaque_SkAlphaType };\n\n #define CPU_TARGET(config, backend, code) \\\n if (Target* t = is_enabled(bench, Benchmark::backend, #config)) { \\\n t->surface.reset(code); \\\n targets->push(t); \\\n }\n CPU_TARGET(nonrendering, kNonRendering_Backend, NULL)\n CPU_TARGET(8888, kRaster_Backend, SkSurface::NewRaster(_8888))\n CPU_TARGET(565, kRaster_Backend, SkSurface::NewRaster(_565))\n\n#if SK_SUPPORT_GPU\n #define GPU_TARGET(config, ctxType, info, samples) \\\n if (Target* t = is_enabled(bench, Benchmark::kGPU_Backend, #config)) { \\\n t->surface.reset(SkSurface::NewRenderTarget(gGrFactory.get(ctxType), info, samples)); \\\n t->gl = gGrFactory.getGLContext(ctxType); \\\n targets->push(t); \\\n }\n GPU_TARGET(gpu, GrContextFactory::kNative_GLContextType, _8888, 0)\n GPU_TARGET(msaa4, GrContextFactory::kNative_GLContextType, _8888, 4)\n GPU_TARGET(msaa16, GrContextFactory::kNative_GLContextType, _8888, 16)\n GPU_TARGET(nvprmsaa4, GrContextFactory::kNVPR_GLContextType, _8888, 4)\n GPU_TARGET(nvprmsaa16, GrContextFactory::kNVPR_GLContextType, _8888, 16)\n GPU_TARGET(debug, GrContextFactory::kDebug_GLContextType, _8888, 0)\n GPU_TARGET(nullgpu, GrContextFactory::kNull_GLContextType, _8888, 0)\n #if SK_ANGLE\n GPU_TARGET(angle, GrContextFactory::kANGLE_GLContextType, _8888, 0)\n #endif\n#endif\n}\n\nint tool_main(int argc, char** argv);\nint tool_main(int argc, char** argv) {\n SetupCrashHandler();\n SkAutoGraphics ag;\n SkCommandLineFlags::Parse(argc, argv);\n\n const double overhead = estimate_timer_overhead();\n SkAutoTMalloc<double> samples(FLAGS_samples);\n\n \/\/ TODO: display add median, use it in --quiet mode\n\n if (FLAGS_verbose) {\n \/\/ No header.\n } else if (FLAGS_quiet) {\n SkDebugf(\"min\\tbench\\tconfig\\n\");\n } else {\n SkDebugf(\"loops\\tmin\\tmean\\tmax\\tstddev\\tconfig\\tbench\\n\");\n }\n\n for (const BenchRegistry* r = BenchRegistry::Head(); r != NULL; r = r->next()) {\n SkAutoTDelete<Benchmark> bench(r->factory()(NULL));\n if (SkCommandLineFlags::ShouldSkip(FLAGS_match, bench->getName())) {\n continue;\n }\n\n SkTDArray<Target*> targets;\n create_targets(bench.get(), &targets);\n\n bench->preDraw();\n for (int j = 0; j < targets.count(); j++) {\n SkCanvas* canvas = targets[j]->surface.get() ? targets[j]->surface->getCanvas() : NULL;\n\n const int loops =\n#if SK_SUPPORT_GPU\n Benchmark::kGPU_Backend == targets[j]->backend\n ? gpu_bench(targets[j]->gl, bench.get(), canvas, samples.get())\n :\n#endif\n cpu_bench( overhead, bench.get(), canvas, samples.get());\n\n Stats stats(samples.get(), FLAGS_samples);\n\n const char* config = targets[j]->config;\n if (FLAGS_verbose) {\n for (int i = 0; i < FLAGS_samples; i++) {\n SkDebugf(\"%s \", humanize(samples[i]).c_str());\n }\n SkDebugf(\"%s\\n\", bench->getName());\n } else if (FLAGS_quiet) {\n if (targets.count() == 1) {\n config = \"\"; \/\/ Only print the config if we run the same bench on more than one.\n }\n SkDebugf(\"%s\\t%s\\t%s\\n\", humanize(stats.min).c_str(), bench->getName(), config);\n } else {\n const double stddev_percent = 100 * sqrt(stats.var) \/ stats.mean;\n SkDebugf(\"%d\\t%s\\t%s\\t%s\\t%.0f%%\\t%s\\t%s\\n\"\n , loops\n , humanize(stats.min).c_str()\n , humanize(stats.mean).c_str()\n , humanize(stats.max).c_str()\n , stddev_percent\n , config\n , bench->getName()\n );\n }\n }\n targets.deleteAll();\n }\n\n return 0;\n}\n\n#if !defined SK_BUILD_FOR_IOS\nint main(int argc, char * const argv[]) {\n return tool_main(argc, (char**) argv);\n}\n#endif\n<commit_msg>Hey, maybe we should _call_ glFinish.<commit_after>\/*\n * Copyright 2014 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 <ctype.h>\n\n#include \"Benchmark.h\"\n#include \"CrashHandler.h\"\n#include \"Stats.h\"\n#include \"Timer.h\"\n\n#include \"SkCanvas.h\"\n#include \"SkCommandLineFlags.h\"\n#include \"SkForceLinking.h\"\n#include \"SkGraphics.h\"\n#include \"SkString.h\"\n#include \"SkSurface.h\"\n\n#if SK_SUPPORT_GPU\n #include \"GrContextFactory.h\"\n GrContextFactory gGrFactory;\n#endif\n\n__SK_FORCE_IMAGE_DECODER_LINKING;\n\nDEFINE_int32(samples, 10, \"Number of samples to measure for each bench.\");\nDEFINE_int32(overheadLoops, 100000, \"Loops to estimate timer overhead.\");\nDEFINE_double(overheadGoal, 0.0001,\n \"Loop until timer overhead is at most this fraction of our measurments.\");\nDEFINE_string(match, \"\", \"The usual filters on file names of benchmarks to measure.\");\nDEFINE_bool2(quiet, q, false, \"Print only bench name and minimum sample.\");\nDEFINE_bool2(verbose, v, false, \"Print all samples.\");\nDEFINE_string(config, \"nonrendering 8888 gpu\", \"Configs to measure. Options: \"\n \"565 8888 gpu nonrendering debug nullgpu msaa4 msaa16 nvprmsaa4 nvprmsaa16 angle\");\nDEFINE_double(gpuMs, 5, \"Target bench time in millseconds for GPU.\");\nDEFINE_int32(gpuFrameLag, 5, \"Overestimate of maximum number of frames GPU allows to lag.\");\n\n\nstatic SkString humanize(double ms) {\n if (ms > 1e+3) return SkStringPrintf(\"%.3gs\", ms\/1e3);\n if (ms < 1e-3) return SkStringPrintf(\"%.3gns\", ms*1e6);\n if (ms < 1) return SkStringPrintf(\"%.3gµs\", ms*1e3);\n return SkStringPrintf(\"%.3gms\", ms);\n}\n\nstatic double time(int loops, Benchmark* bench, SkCanvas* canvas, SkGLContextHelper* gl) {\n WallTimer timer;\n timer.start();\n if (bench) {\n bench->draw(loops, canvas);\n }\n if (canvas) {\n canvas->flush();\n }\n#if SK_SUPPORT_GPU\n if (gl) {\n SK_GL(*gl, Flush());\n gl->swapBuffers();\n }\n#endif\n timer.end();\n return timer.fWall;\n}\n\nstatic double estimate_timer_overhead() {\n double overhead = 0;\n for (int i = 0; i < FLAGS_overheadLoops; i++) {\n overhead += time(1, NULL, NULL, NULL);\n }\n return overhead \/ FLAGS_overheadLoops;\n}\n\nstatic int cpu_bench(const double overhead, Benchmark* bench, SkCanvas* canvas, double* samples) {\n \/\/ First figure out approximately how many loops of bench it takes to make overhead negligible.\n double bench_plus_overhead;\n do {\n bench_plus_overhead = time(1, bench, canvas, NULL);\n } while (bench_plus_overhead < overhead); \/\/ Shouldn't normally happen.\n\n \/\/ Later we'll just start and stop the timer once but loop N times.\n \/\/ We'll pick N to make timer overhead negligible:\n \/\/\n \/\/ overhead\n \/\/ ------------------------- < FLAGS_overheadGoal\n \/\/ overhead + N * Bench Time\n \/\/\n \/\/ where bench_plus_overhead ≈ overhead + Bench Time.\n \/\/\n \/\/ Doing some math, we get:\n \/\/\n \/\/ (overhead \/ FLAGS_overheadGoal) - overhead\n \/\/ ------------------------------------------ < N\n \/\/ bench_plus_overhead - overhead)\n \/\/\n \/\/ Luckily, this also works well in practice. :)\n const double numer = overhead \/ FLAGS_overheadGoal - overhead;\n const double denom = bench_plus_overhead - overhead;\n const int loops = (int)ceil(numer \/ denom);\n\n for (int i = 0; i < FLAGS_samples; i++) {\n samples[i] = time(loops, bench, canvas, NULL) \/ loops;\n }\n return loops;\n}\n\n#if SK_SUPPORT_GPU\nstatic int gpu_bench(SkGLContextHelper* gl,\n Benchmark* bench,\n SkCanvas* canvas,\n double* samples) {\n \/\/ Make sure we're done with whatever came before.\n SK_GL(*gl, Finish());\n\n \/\/ First, figure out how many loops it'll take to get a frame up to FLAGS_gpuMs.\n int loops = 1;\n double elapsed = 0;\n do {\n loops *= 2;\n \/\/ If the GPU lets frames lag at all, we need to make sure we're timing\n \/\/ _this_ round, not still timing last round. We force this by looping\n \/\/ more times than any reasonable GPU will allow frames to lag.\n for (int i = 0; i < FLAGS_gpuFrameLag; i++) {\n elapsed = time(loops, bench, canvas, gl);\n }\n } while (elapsed < FLAGS_gpuMs);\n\n \/\/ We've overshot at least a little. Scale back linearly.\n loops = (int)ceil(loops * FLAGS_gpuMs \/ elapsed);\n\n \/\/ Might as well make sure we're not still timing our calibration.\n SK_GL(*gl, Finish());\n\n \/\/ Pretty much the same deal as the calibration: do some warmup to make\n \/\/ sure we're timing steady-state pipelined frames.\n for (int i = 0; i < FLAGS_gpuFrameLag; i++) {\n time(loops, bench, canvas, gl);\n }\n\n \/\/ Now, actually do the timing!\n for (int i = 0; i < FLAGS_samples; i++) {\n samples[i] = time(loops, bench, canvas, gl) \/ loops;\n }\n return loops;\n}\n#endif\n\nstatic SkString to_lower(const char* str) {\n SkString lower(str);\n for (size_t i = 0; i < lower.size(); i++) {\n lower[i] = tolower(lower[i]);\n }\n return lower;\n}\n\nstruct Target {\n const char* config;\n Benchmark::Backend backend;\n SkAutoTDelete<SkSurface> surface;\n#if SK_SUPPORT_GPU\n SkGLContextHelper* gl;\n#endif\n};\n\n\/\/ If bench is enabled for backend\/config, returns a Target* for them, otherwise NULL.\nstatic Target* is_enabled(Benchmark* bench, Benchmark::Backend backend, const char* config) {\n if (!bench->isSuitableFor(backend)) {\n return NULL;\n }\n\n for (int i = 0; i < FLAGS_config.count(); i++) {\n if (to_lower(FLAGS_config[i]).equals(config)) {\n Target* target = new Target;\n target->config = config;\n target->backend = backend;\n return target;\n }\n }\n return NULL;\n}\n\n\/\/ Append all targets that are suitable for bench.\nstatic void create_targets(Benchmark* bench, SkTDArray<Target*>* targets) {\n const int w = bench->getSize().fX,\n h = bench->getSize().fY;\n const SkImageInfo _8888 = { w, h, kN32_SkColorType, kPremul_SkAlphaType },\n _565 = { w, h, kRGB_565_SkColorType, kOpaque_SkAlphaType };\n\n #define CPU_TARGET(config, backend, code) \\\n if (Target* t = is_enabled(bench, Benchmark::backend, #config)) { \\\n t->surface.reset(code); \\\n targets->push(t); \\\n }\n CPU_TARGET(nonrendering, kNonRendering_Backend, NULL)\n CPU_TARGET(8888, kRaster_Backend, SkSurface::NewRaster(_8888))\n CPU_TARGET(565, kRaster_Backend, SkSurface::NewRaster(_565))\n\n#if SK_SUPPORT_GPU\n #define GPU_TARGET(config, ctxType, info, samples) \\\n if (Target* t = is_enabled(bench, Benchmark::kGPU_Backend, #config)) { \\\n t->surface.reset(SkSurface::NewRenderTarget(gGrFactory.get(ctxType), info, samples)); \\\n t->gl = gGrFactory.getGLContext(ctxType); \\\n targets->push(t); \\\n }\n GPU_TARGET(gpu, GrContextFactory::kNative_GLContextType, _8888, 0)\n GPU_TARGET(msaa4, GrContextFactory::kNative_GLContextType, _8888, 4)\n GPU_TARGET(msaa16, GrContextFactory::kNative_GLContextType, _8888, 16)\n GPU_TARGET(nvprmsaa4, GrContextFactory::kNVPR_GLContextType, _8888, 4)\n GPU_TARGET(nvprmsaa16, GrContextFactory::kNVPR_GLContextType, _8888, 16)\n GPU_TARGET(debug, GrContextFactory::kDebug_GLContextType, _8888, 0)\n GPU_TARGET(nullgpu, GrContextFactory::kNull_GLContextType, _8888, 0)\n #if SK_ANGLE\n GPU_TARGET(angle, GrContextFactory::kANGLE_GLContextType, _8888, 0)\n #endif\n#endif\n}\n\nint tool_main(int argc, char** argv);\nint tool_main(int argc, char** argv) {\n SetupCrashHandler();\n SkAutoGraphics ag;\n SkCommandLineFlags::Parse(argc, argv);\n\n const double overhead = estimate_timer_overhead();\n SkAutoTMalloc<double> samples(FLAGS_samples);\n\n \/\/ TODO: display add median, use it in --quiet mode\n\n if (FLAGS_verbose) {\n \/\/ No header.\n } else if (FLAGS_quiet) {\n SkDebugf(\"min\\tbench\\tconfig\\n\");\n } else {\n SkDebugf(\"loops\\tmin\\tmean\\tmax\\tstddev\\tconfig\\tbench\\n\");\n }\n\n for (const BenchRegistry* r = BenchRegistry::Head(); r != NULL; r = r->next()) {\n SkAutoTDelete<Benchmark> bench(r->factory()(NULL));\n if (SkCommandLineFlags::ShouldSkip(FLAGS_match, bench->getName())) {\n continue;\n }\n\n SkTDArray<Target*> targets;\n create_targets(bench.get(), &targets);\n\n bench->preDraw();\n for (int j = 0; j < targets.count(); j++) {\n SkCanvas* canvas = targets[j]->surface.get() ? targets[j]->surface->getCanvas() : NULL;\n\n const int loops =\n#if SK_SUPPORT_GPU\n Benchmark::kGPU_Backend == targets[j]->backend\n ? gpu_bench(targets[j]->gl, bench.get(), canvas, samples.get())\n :\n#endif\n cpu_bench( overhead, bench.get(), canvas, samples.get());\n\n Stats stats(samples.get(), FLAGS_samples);\n\n const char* config = targets[j]->config;\n if (FLAGS_verbose) {\n for (int i = 0; i < FLAGS_samples; i++) {\n SkDebugf(\"%s \", humanize(samples[i]).c_str());\n }\n SkDebugf(\"%s\\n\", bench->getName());\n } else if (FLAGS_quiet) {\n if (targets.count() == 1) {\n config = \"\"; \/\/ Only print the config if we run the same bench on more than one.\n }\n SkDebugf(\"%s\\t%s\\t%s\\n\", humanize(stats.min).c_str(), bench->getName(), config);\n } else {\n const double stddev_percent = 100 * sqrt(stats.var) \/ stats.mean;\n SkDebugf(\"%d\\t%s\\t%s\\t%s\\t%.0f%%\\t%s\\t%s\\n\"\n , loops\n , humanize(stats.min).c_str()\n , humanize(stats.mean).c_str()\n , humanize(stats.max).c_str()\n , stddev_percent\n , config\n , bench->getName()\n );\n }\n }\n targets.deleteAll();\n }\n\n return 0;\n}\n\n#if !defined SK_BUILD_FOR_IOS\nint main(int argc, char * const argv[]) {\n return tool_main(argc, (char**) argv);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*$Log$\n *Revision 1.23 2003\/10\/09 09:42:42 strk\n *Tried to \"formalize\" constant nature of the first argument given to constructor by PrecisionModel and SRID specification. Added CVS Log on top.\n **\/\n#include \"..\/headers\/geom.h\"\n#include \"..\/headers\/util.h\"\n#include <typeinfo>\n\nnamespace geos {\n\nGeometryFactory::GeometryFactory() {\n\tprecisionModel=new PrecisionModel();\n\tSRID=0;\n}\n\n\/**\n* Create a geometry factory using given precision model and srid.\n* Will make a copy of given PrecisionModel object, so callers\n* can safely delete it afterwards.\n* We should use the 'const' modifier, but that made my compiler\n* crazy !! --strk;\n*\/\nGeometryFactory::GeometryFactory(PrecisionModel* pm, int newSRID){\n precisionModel=new PrecisionModel(*pm);\n SRID=newSRID;\n}\nGeometryFactory::~GeometryFactory(){\n\tdelete precisionModel;\n}\n \nPoint* GeometryFactory::createPointFromInternalCoord(Coordinate* coord, Geometry *exemplar) {\n\texemplar->getPrecisionModel()->makePrecise(coord);\n\treturn new Point(*coord,exemplar->getPrecisionModel(),exemplar->getSRID());\n}\n\n\nGeometry* GeometryFactory::toGeometry(Envelope* envelope,PrecisionModel* precisionModel,int SRID) {\n\tif (envelope->isNull()) {\n\t\treturn new Point(*(new Coordinate()),precisionModel,SRID);\n\t}\n\tif (envelope->getMinX()==envelope->getMaxX() && envelope->getMinY()==envelope->getMaxY()) {\n\t\treturn new Point(*(new Coordinate(envelope->getMinX(),envelope->getMinY())),precisionModel,SRID);\n\t}\n\tCoordinateList *cl=CoordinateListFactory::internalFactory->createCoordinateList();\n\tcl->add(*(new Coordinate(envelope->getMinX(), envelope->getMinY())));\n\tcl->add(*(new Coordinate(envelope->getMaxX(), envelope->getMinY())));\n\tcl->add(*(new Coordinate(envelope->getMaxX(), envelope->getMaxY())));\n\tcl->add(*(new Coordinate(envelope->getMinX(), envelope->getMaxY())));\n\tcl->add(*(new Coordinate(envelope->getMinX(), envelope->getMinY())));\n\treturn new Polygon(new LinearRing(cl,precisionModel,SRID),precisionModel,SRID);\n}\n\nPrecisionModel* GeometryFactory::getPrecisionModel(){\n\treturn precisionModel;\n}\n\nPoint* GeometryFactory::createPoint(Coordinate& coordinate){\n\treturn new Point(coordinate,precisionModel,SRID);\n}\n\nMultiLineString* GeometryFactory::createMultiLineString(vector<Geometry *> *lineStrings){\n\treturn new MultiLineString(lineStrings,precisionModel,SRID);\n}\n\nGeometryCollection* GeometryFactory::createGeometryCollection(vector<Geometry *> *geometries){\n\treturn new GeometryCollection(geometries,precisionModel,SRID);\n}\n\nMultiPolygon* GeometryFactory::createMultiPolygon(vector<Geometry *> *polygons){\n\treturn new MultiPolygon(polygons,precisionModel,SRID);\n}\n\nLinearRing* GeometryFactory::createLinearRing(CoordinateList* coordinates) {\n\tif (coordinates->getSize()>0 && \n\t\t!coordinates->getAt(0).equals2D(coordinates->getAt(coordinates->getSize() - 1))) {\n\t\t\tdelete precisionModel;\n\t\t\tthrow new IllegalArgumentException(\"LinearRing not closed\");\n\t}\n\treturn new LinearRing(coordinates, precisionModel, SRID);\n}\n\nMultiPoint* GeometryFactory::createMultiPoint(vector<Geometry *> *point) {\n\treturn new MultiPoint(point,precisionModel,SRID);\n}\n\nMultiPoint* GeometryFactory::createMultiPoint(CoordinateList* coordinates) {\n\tvector<Geometry *> *pts=new vector<Geometry *>();\n\tfor (int i=0; i<coordinates->getSize(); i++) {\n\t\tPoint *pt=createPoint(coordinates->getAt(i));\n\t\tpts->push_back(pt);\n\t}\n\tdelete coordinates;\n\treturn createMultiPoint(pts);\n}\n\nPolygon* GeometryFactory::createPolygon(LinearRing *shell, vector<Geometry *> *holes) {\n\treturn new Polygon(shell, holes, precisionModel, SRID);\n}\n\nLineString* GeometryFactory::createLineString(CoordinateList* coordinates) {\n\treturn new LineString(coordinates, precisionModel, SRID);\n}\n\nGeometry* GeometryFactory::buildGeometry(vector<Geometry *> *geoms) {\n\tstring geomClass(\"NULL\");\n\tbool isHeterogeneous=false;\n\tbool isCollection=geoms->size()>1;\n\tunsigned int i;\n \n\tfor (i=0; i<geoms->size(); i++) {\n\t\tstring partClass(typeid(*(*geoms)[i]).name());\n\t\tif (geomClass==\"NULL\") {\n\t\t\tgeomClass=partClass;\n\t\t}\n\t\tif (partClass!=geomClass) {\n\t\t\tisHeterogeneous = true;\n\t\t}\n\t}\n \/\/ for the empty geometry, return an empty GeometryCollection\n\tif (geomClass==\"NULL\") {\n\t\treturn createGeometryCollection(NULL);\n\t}\n\tif (isHeterogeneous) {\n\t\treturn createGeometryCollection(new vector<Geometry*>(*geoms));\n\t}\n\tGeometry *geom0=(*geoms)[0];\n\tif (isCollection) {\n\t\tif (typeid(*geom0)==typeid(Polygon)) {\n\t\t\treturn createMultiPolygon(new vector<Geometry*>(*geoms));\n\t\t} else if (typeid(*geom0)==typeid(LineString)) {\n\t\t\treturn createMultiLineString(new vector<Geometry*>(*geoms));\n\t\t} else if (typeid(*geom0)==typeid(Point)) {\n\t\t\treturn createMultiPoint(new vector<Geometry*>(*geoms));\n\t\t}\n\t\tAssert::shouldNeverReachHere();\n\t}\n\tif (typeid(*geom0)==typeid(Polygon))\n\t\treturn (Polygon*) geom0;\n\t\/\/ LineString also handles LinearRings\n\telse if (typeid(*geom0)==typeid(LineString))\n\t\treturn (LineString*) geom0;\n\telse if (typeid(*geom0)==typeid(Point))\n\t\treturn (Point*) geom0;\n\telse if (typeid(*geom0)==typeid(MultiPoint))\n\t\treturn (MultiPoint*) geom0;\n\telse if (typeid(*geom0)==typeid(MultiLineString))\n\t\treturn (MultiLineString*) geom0;\n\telse if (typeid(*geom0)==typeid(MultiPolygon))\n\t\treturn (MultiPolygon*) geom0;\n\telse if (typeid(*geom0)==typeid(GeometryCollection))\n\t\treturn (GeometryCollection*) geom0;\n\telse \n\t\treturn geom0;\n}\n\n}\n\n<commit_msg>just a style change in top Log comment.<commit_after>\/*\n* $Log$\n* Revision 1.24 2003\/10\/09 10:14:06 strk\n* just a style change in top Log comment.\n*\n*\/\n#include \"..\/headers\/geom.h\"\n#include \"..\/headers\/util.h\"\n#include <typeinfo>\n\nnamespace geos {\n\nGeometryFactory::GeometryFactory() {\n\tprecisionModel=new PrecisionModel();\n\tSRID=0;\n}\n\n\/**\n* Create a geometry factory using given precision model and srid.\n* Will make a copy of given PrecisionModel object, so callers\n* can safely delete it afterwards.\n* We should use the 'const' modifier, but that made my compiler\n* crazy !! --strk;\n*\/\nGeometryFactory::GeometryFactory(PrecisionModel* pm, int newSRID){\n precisionModel=new PrecisionModel(*pm);\n SRID=newSRID;\n}\nGeometryFactory::~GeometryFactory(){\n\tdelete precisionModel;\n}\n \nPoint* GeometryFactory::createPointFromInternalCoord(Coordinate* coord, Geometry *exemplar) {\n\texemplar->getPrecisionModel()->makePrecise(coord);\n\treturn new Point(*coord,exemplar->getPrecisionModel(),exemplar->getSRID());\n}\n\n\nGeometry* GeometryFactory::toGeometry(Envelope* envelope,PrecisionModel* precisionModel,int SRID) {\n\tif (envelope->isNull()) {\n\t\treturn new Point(*(new Coordinate()),precisionModel,SRID);\n\t}\n\tif (envelope->getMinX()==envelope->getMaxX() && envelope->getMinY()==envelope->getMaxY()) {\n\t\treturn new Point(*(new Coordinate(envelope->getMinX(),envelope->getMinY())),precisionModel,SRID);\n\t}\n\tCoordinateList *cl=CoordinateListFactory::internalFactory->createCoordinateList();\n\tcl->add(*(new Coordinate(envelope->getMinX(), envelope->getMinY())));\n\tcl->add(*(new Coordinate(envelope->getMaxX(), envelope->getMinY())));\n\tcl->add(*(new Coordinate(envelope->getMaxX(), envelope->getMaxY())));\n\tcl->add(*(new Coordinate(envelope->getMinX(), envelope->getMaxY())));\n\tcl->add(*(new Coordinate(envelope->getMinX(), envelope->getMinY())));\n\treturn new Polygon(new LinearRing(cl,precisionModel,SRID),precisionModel,SRID);\n}\n\nPrecisionModel* GeometryFactory::getPrecisionModel(){\n\treturn precisionModel;\n}\n\nPoint* GeometryFactory::createPoint(Coordinate& coordinate){\n\treturn new Point(coordinate,precisionModel,SRID);\n}\n\nMultiLineString* GeometryFactory::createMultiLineString(vector<Geometry *> *lineStrings){\n\treturn new MultiLineString(lineStrings,precisionModel,SRID);\n}\n\nGeometryCollection* GeometryFactory::createGeometryCollection(vector<Geometry *> *geometries){\n\treturn new GeometryCollection(geometries,precisionModel,SRID);\n}\n\nMultiPolygon* GeometryFactory::createMultiPolygon(vector<Geometry *> *polygons){\n\treturn new MultiPolygon(polygons,precisionModel,SRID);\n}\n\nLinearRing* GeometryFactory::createLinearRing(CoordinateList* coordinates) {\n\tif (coordinates->getSize()>0 && \n\t\t!coordinates->getAt(0).equals2D(coordinates->getAt(coordinates->getSize() - 1))) {\n\t\t\tdelete precisionModel;\n\t\t\tthrow new IllegalArgumentException(\"LinearRing not closed\");\n\t}\n\treturn new LinearRing(coordinates, precisionModel, SRID);\n}\n\nMultiPoint* GeometryFactory::createMultiPoint(vector<Geometry *> *point) {\n\treturn new MultiPoint(point,precisionModel,SRID);\n}\n\nMultiPoint* GeometryFactory::createMultiPoint(CoordinateList* coordinates) {\n\tvector<Geometry *> *pts=new vector<Geometry *>();\n\tfor (int i=0; i<coordinates->getSize(); i++) {\n\t\tPoint *pt=createPoint(coordinates->getAt(i));\n\t\tpts->push_back(pt);\n\t}\n\tdelete coordinates;\n\treturn createMultiPoint(pts);\n}\n\nPolygon* GeometryFactory::createPolygon(LinearRing *shell, vector<Geometry *> *holes) {\n\treturn new Polygon(shell, holes, precisionModel, SRID);\n}\n\nLineString* GeometryFactory::createLineString(CoordinateList* coordinates) {\n\treturn new LineString(coordinates, precisionModel, SRID);\n}\n\nGeometry* GeometryFactory::buildGeometry(vector<Geometry *> *geoms) {\n\tstring geomClass(\"NULL\");\n\tbool isHeterogeneous=false;\n\tbool isCollection=geoms->size()>1;\n\tunsigned int i;\n \n\tfor (i=0; i<geoms->size(); i++) {\n\t\tstring partClass(typeid(*(*geoms)[i]).name());\n\t\tif (geomClass==\"NULL\") {\n\t\t\tgeomClass=partClass;\n\t\t}\n\t\tif (partClass!=geomClass) {\n\t\t\tisHeterogeneous = true;\n\t\t}\n\t}\n \/\/ for the empty geometry, return an empty GeometryCollection\n\tif (geomClass==\"NULL\") {\n\t\treturn createGeometryCollection(NULL);\n\t}\n\tif (isHeterogeneous) {\n\t\treturn createGeometryCollection(new vector<Geometry*>(*geoms));\n\t}\n\tGeometry *geom0=(*geoms)[0];\n\tif (isCollection) {\n\t\tif (typeid(*geom0)==typeid(Polygon)) {\n\t\t\treturn createMultiPolygon(new vector<Geometry*>(*geoms));\n\t\t} else if (typeid(*geom0)==typeid(LineString)) {\n\t\t\treturn createMultiLineString(new vector<Geometry*>(*geoms));\n\t\t} else if (typeid(*geom0)==typeid(Point)) {\n\t\t\treturn createMultiPoint(new vector<Geometry*>(*geoms));\n\t\t}\n\t\tAssert::shouldNeverReachHere();\n\t}\n\tif (typeid(*geom0)==typeid(Polygon))\n\t\treturn (Polygon*) geom0;\n\t\/\/ LineString also handles LinearRings\n\telse if (typeid(*geom0)==typeid(LineString))\n\t\treturn (LineString*) geom0;\n\telse if (typeid(*geom0)==typeid(Point))\n\t\treturn (Point*) geom0;\n\telse if (typeid(*geom0)==typeid(MultiPoint))\n\t\treturn (MultiPoint*) geom0;\n\telse if (typeid(*geom0)==typeid(MultiLineString))\n\t\treturn (MultiLineString*) geom0;\n\telse if (typeid(*geom0)==typeid(MultiPolygon))\n\t\treturn (MultiPolygon*) geom0;\n\telse if (typeid(*geom0)==typeid(GeometryCollection))\n\t\treturn (GeometryCollection*) geom0;\n\telse \n\t\treturn geom0;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * tests\/net\/group_test.cpp\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#include <c7a\/net\/collective_communication.hpp>\n#include <c7a\/net\/dispatcher.hpp>\n#include <c7a\/net\/flow_control_channel.hpp>\n#include <c7a\/net\/group.hpp>\n#include <c7a\/net\/manager.hpp>\n#include <gtest\/gtest.h>\n\n#include <random>\n#include <string>\n#include <thread>\n#include <vector>\n\nusing namespace c7a::net;\n\nstatic void ThreadInitializeAsyncRead(Group* net) {\n \/\/ send a message to all other clients except ourselves.\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n net->connection(i).GetSocket().send(&i, sizeof(size_t));\n }\n\n size_t received = 0;\n Dispatcher dispatcher;\n\n Dispatcher::AsyncReadCallback callback =\n [net, &received](Connection& \/* s *\/, const Buffer& buffer) {\n ASSERT_EQ(*(reinterpret_cast<const size_t*>(buffer.data())),\n net->MyRank());\n received++;\n };\n\n \/\/ add async reads to net dispatcher\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n dispatcher.AsyncRead(net->connection(i), sizeof(size_t), callback);\n }\n\n while (received < net->Size() - 1) {\n dispatcher.Dispatch();\n }\n}\n\nstatic void ThreadInitializeSendCyclic(Group* net) {\n\n size_t id = net->MyRank();\n\n if (id != 0) {\n size_t res;\n net->ReceiveFrom<size_t>(id - 1, &res);\n ASSERT_EQ(id - 1, res);\n }\n\n if (id != net->Size() - 1) {\n net->SendTo(id + 1, id);\n }\n}\n\nstatic void ThreadInitializeBroadcastIntegral(Group* net) {\n\n static const bool debug = false;\n\n \/\/Broadcast our ID to everyone\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n net->SendTo(i, net->MyRank());\n }\n\n \/\/Receive the id from everyone. Make sure that the id is correct.\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n\n size_t val;\n ClientId id;\n\n net->ReceiveFromAny<size_t>(&id, &val);\n\n LOG << \"Received \" << val << \" from \" << id;\n\n ASSERT_EQ((int)id, (int)val);\n }\n}\n\nstatic void ThreadInitializeSendReceive(Group* net) {\n static const bool debug = false;\n\n \/\/ send a message to all other clients except ourselves.\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n net->SendStringTo(i, \"Hello \" + std::to_string(net->MyRank())\n + \" -> \" + std::to_string(i));\n }\n \/\/ receive the n-1 messages from clients in order\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n\n std::string msg;\n net->ReceiveStringFrom(i, &msg);\n sLOG << \"Received from client\" << i << \"msg\" << msg;\n\n ASSERT_EQ(msg, \"Hello \" + std::to_string(i)\n + \" -> \" + std::to_string(net->MyRank()));\n }\n\n \/\/ *****************************************************************\n\n \/\/ send another message to all other clients except ourselves. Now with connection access.\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n net->connection(i).SendString(\"Hello \" + std::to_string(net->MyRank())\n + \" -> \" + std::to_string(i));\n }\n \/\/ receive the n-1 messages from clients in any order\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n\n ClientId from;\n std::string msg;\n net->ReceiveStringFromAny(&from, &msg);\n sLOG << \"Received from client\" << i << \"msg\" << msg;\n\n ASSERT_EQ(msg, \"Hello \" + std::to_string(from)\n + \" -> \" + std::to_string(net->MyRank()));\n }\n}\n\nstatic void ThreadInitializeSendReceiveALot(Group* net) {\n for (int i = 0; i < 100; i++) {\n ThreadInitializeSendReceive(net);\n }\n}\n\nstatic void ThreadInitializeSendReceiveAsyncALot(Group* net) {\n for (int i = 0; i < 100; i++) {\n ThreadInitializeAsyncRead(net);\n }\n}\n\nstatic void RealGroupConstructAndCall(\n std::function<void(Group*)> thread_function) {\n \/\/ randomize base port number for test\n std::random_device random_device;\n std::default_random_engine generator(random_device());\n std::uniform_int_distribution<int> distribution(10000, 30000);\n const size_t port_base = distribution(generator);\n\n std::vector<Endpoint> endpoints = {\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 0)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 1)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 2)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 3)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 4)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 5))\n };\n\n sLOG1 << \"Group test uses ports\" << port_base << \"-\" << port_base + 5;\n\n const size_t count = endpoints.size();\n\n std::vector<std::thread> threads(count);\n\n \/\/ lambda to construct Group and call user thread function.\n\n std::vector<Manager> groups(count);\n\n for (size_t i = 0; i < count; i++) {\n threads[i] = std::thread(\n [i, &endpoints, thread_function, &groups]() {\n \/\/ construct Group i with endpoints\n groups[i].Initialize(i, endpoints);\n \/\/ run thread function\n thread_function(&groups[i].GetFlowGroup());\n });\n }\n\n for (size_t i = 0; i < count; i++) {\n threads[i].join();\n }\n for (size_t i = 0; i < count; i++) {\n groups[i].Close();\n }\n}\n\nTEST(Group, RealInitializeAndClose) {\n \/\/ Construct a real Group of 6 workers which do nothing but terminate.\n RealGroupConstructAndCall([](Group*) { });\n}\n\nTEST(Group, RealInitializeSendReceive) {\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all neighbors.\n RealGroupConstructAndCall(ThreadInitializeSendReceive);\n}\n\nTEST(Group, RealInitializeSendReceiveALot) {\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all neighbors.\n RealGroupConstructAndCall(ThreadInitializeSendReceive);\n}\n\nTEST(Group, RealInitializeSendReceiveAsync) { \/\/TODO(ej) test hangs from time to time\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ which sends and receives asynchronous messages between all workers.\n RealGroupConstructAndCall(ThreadInitializeAsyncRead);\n}\n\nTEST(Group, RealInitializeSendReceiveAsyncALot) {\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all neighbors.\n RealGroupConstructAndCall(ThreadInitializeSendReceive);\n}\n\nTEST(Group, RealInitializeBroadcast) {\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all workers.\n RealGroupConstructAndCall(ThreadInitializeBroadcastIntegral);\n}\nTEST(Group, RealSendCyclic) {\n RealGroupConstructAndCall(ThreadInitializeSendCyclic);\n}\n\nTEST(Group, InitializeAndClose) {\n \/\/ Construct a Group of 6 workers which do nothing but terminate.\n Group::ExecuteLocalMock(6, [](Group*) { });\n}\n\nTEST(Group, InitializeSendReceive) {\n \/\/ Construct a Group of 6 workers which execute the thread function\n \/\/ which sends and receives asynchronous messages between all workers.\n Group::ExecuteLocalMock(6, ThreadInitializeSendReceive);\n}\n\nTEST(Group, InitializeBroadcast) {\n \/\/ Construct a Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all workers.\n Group::ExecuteLocalMock(6, ThreadInitializeBroadcastIntegral);\n}\n\nTEST(Group, SendCyclic) {\n Group::ExecuteLocalMock(6, ThreadInitializeSendCyclic);\n}\n\nTEST(Group, TestPrefixSum) {\n for (size_t p = 1; p <= 8; ++p) {\n \/\/ Construct Group of p workers which perform a PrefixSum collective\n Group::ExecuteLocalMock(\n p, [](Group* net) {\n size_t local_value = 1;\n PrefixSum(*net, local_value);\n ASSERT_EQ(local_value, net->MyRank() + 1);\n });\n }\n}\n\nTEST(Group, TestAllReduce) {\n for (size_t p = 0; p <= 8; ++p) {\n \/\/ Construct Group of p workers which perform an AllReduce collective\n Group::ExecuteLocalMock(\n p, [](Group* net) {\n size_t local_value = net->MyRank();\n AllReduce(*net, local_value);\n ASSERT_EQ(local_value, net->Size() * (net->Size() - 1) \/ 2);\n });\n }\n}\n\nTEST(Group, TestBroadcast) {\n for (size_t p = 0; p <= 8; ++p) {\n \/\/ Construct Group of p workers which perform an Broadcast collective\n Group::ExecuteLocalMock(\n p, [](Group* net) {\n size_t local_value;\n if (net->MyRank() == 0) local_value = 42;\n Broadcast(*net, local_value);\n ASSERT_EQ(local_value, 42u);\n });\n }\n}\n\nTEST(Group, TestReduceToRoot) {\n for (size_t p = 0; p <= 8; ++p) {\n \/\/ Construct Group of p workers which perform an Broadcast collective\n Group::ExecuteLocalMock(\n p, [](Group* net) {\n size_t local_value = net->MyRank();\n ReduceToRoot(*net, local_value);\n if (net->MyRank() == 0)\n ASSERT_EQ(local_value, net->Size() * (net->Size() - 1) \/ 2);\n });\n }\n}\n\nTEST(Group, TestBarrier) {\n static const bool debug = false;\n std::mutex sync_mtx; \/\/ Synchronisation mutex for the barrier\n std::mutex local_mtx; \/\/ Mutex for writing to the results array\n std::condition_variable cv; \/\/ Condition variable for the barrier\n\n for (int p = 0; p <= 8; ++p) {\n int workers = p;\n int workers_copy = workers; \/\/ Will be decremented by the barrier function\n\n std::vector<char> result(2 * workers);\n int k = 0; \/\/ The counter for the result array\n sLOG << \"I'm in test\" << workers;\n\n Group::ExecuteLocalMock(\n workers, [&](Group* net) {\n local_mtx.lock();\n result[k++] = 'B'; \/\/ B stands for 'Before barrier'\n local_mtx.unlock();\n\n sLOG << \"Before Barrier, worker\" << net->MyRank();\n\n ThreadBarrier(sync_mtx, cv, workers_copy);\n\n local_mtx.lock();\n result[k++] = 'A'; \/\/ A stands for 'After barrier'\n local_mtx.unlock();\n\n sLOG << \"After Barrier, worker\" << net->MyRank();\n });\n for (int i = 0; i < workers; ++i) {\n sLOG << \"Checking position\" << i;\n ASSERT_EQ(result[i], 'B');\n }\n for (int i = workers; i < 2 * workers; ++i) {\n sLOG << \"Checking position\" << i;\n ASSERT_EQ(result[i], 'A');\n }\n }\n}\n\n\/******************************************************************************\/\n<commit_msg>Removing two tests that generate \"unused\" warnings.<commit_after>\/*******************************************************************************\n * tests\/net\/group_test.cpp\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#include <c7a\/net\/collective_communication.hpp>\n#include <c7a\/net\/dispatcher.hpp>\n#include <c7a\/net\/flow_control_channel.hpp>\n#include <c7a\/net\/group.hpp>\n#include <c7a\/net\/manager.hpp>\n#include <gtest\/gtest.h>\n\n#include <random>\n#include <string>\n#include <thread>\n#include <vector>\n\nusing namespace c7a::net;\n\nstatic void ThreadInitializeAsyncRead(Group* net) {\n \/\/ send a message to all other clients except ourselves.\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n net->connection(i).GetSocket().send(&i, sizeof(size_t));\n }\n\n size_t received = 0;\n Dispatcher dispatcher;\n\n Dispatcher::AsyncReadCallback callback =\n [net, &received](Connection& \/* s *\/, const Buffer& buffer) {\n ASSERT_EQ(*(reinterpret_cast<const size_t*>(buffer.data())),\n net->MyRank());\n received++;\n };\n\n \/\/ add async reads to net dispatcher\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n dispatcher.AsyncRead(net->connection(i), sizeof(size_t), callback);\n }\n\n while (received < net->Size() - 1) {\n dispatcher.Dispatch();\n }\n}\n\nstatic void ThreadInitializeSendCyclic(Group* net) {\n\n size_t id = net->MyRank();\n\n if (id != 0) {\n size_t res;\n net->ReceiveFrom<size_t>(id - 1, &res);\n ASSERT_EQ(id - 1, res);\n }\n\n if (id != net->Size() - 1) {\n net->SendTo(id + 1, id);\n }\n}\n\nstatic void ThreadInitializeBroadcastIntegral(Group* net) {\n\n static const bool debug = false;\n\n \/\/Broadcast our ID to everyone\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n net->SendTo(i, net->MyRank());\n }\n\n \/\/Receive the id from everyone. Make sure that the id is correct.\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n\n size_t val;\n ClientId id;\n\n net->ReceiveFromAny<size_t>(&id, &val);\n\n LOG << \"Received \" << val << \" from \" << id;\n\n ASSERT_EQ((int)id, (int)val);\n }\n}\n\nstatic void ThreadInitializeSendReceive(Group* net) {\n static const bool debug = false;\n\n \/\/ send a message to all other clients except ourselves.\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n net->SendStringTo(i, \"Hello \" + std::to_string(net->MyRank())\n + \" -> \" + std::to_string(i));\n }\n \/\/ receive the n-1 messages from clients in order\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n\n std::string msg;\n net->ReceiveStringFrom(i, &msg);\n sLOG << \"Received from client\" << i << \"msg\" << msg;\n\n ASSERT_EQ(msg, \"Hello \" + std::to_string(i)\n + \" -> \" + std::to_string(net->MyRank()));\n }\n\n \/\/ *****************************************************************\n\n \/\/ send another message to all other clients except ourselves. Now with connection access.\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n net->connection(i).SendString(\"Hello \" + std::to_string(net->MyRank())\n + \" -> \" + std::to_string(i));\n }\n \/\/ receive the n-1 messages from clients in any order\n for (size_t i = 0; i != net->Size(); ++i)\n {\n if (i == net->MyRank()) continue;\n\n ClientId from;\n std::string msg;\n net->ReceiveStringFromAny(&from, &msg);\n sLOG << \"Received from client\" << i << \"msg\" << msg;\n\n ASSERT_EQ(msg, \"Hello \" + std::to_string(from)\n + \" -> \" + std::to_string(net->MyRank()));\n }\n}\n\nstatic void RealGroupConstructAndCall(\n std::function<void(Group*)> thread_function) {\n \/\/ randomize base port number for test\n std::random_device random_device;\n std::default_random_engine generator(random_device());\n std::uniform_int_distribution<int> distribution(10000, 30000);\n const size_t port_base = distribution(generator);\n\n std::vector<Endpoint> endpoints = {\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 0)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 1)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 2)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 3)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 4)),\n Endpoint(\"127.0.0.1:\" + std::to_string(port_base + 5))\n };\n\n sLOG1 << \"Group test uses ports\" << port_base << \"-\" << port_base + 5;\n\n const size_t count = endpoints.size();\n\n std::vector<std::thread> threads(count);\n\n \/\/ lambda to construct Group and call user thread function.\n\n std::vector<Manager> groups(count);\n\n for (size_t i = 0; i < count; i++) {\n threads[i] = std::thread(\n [i, &endpoints, thread_function, &groups]() {\n \/\/ construct Group i with endpoints\n groups[i].Initialize(i, endpoints);\n \/\/ run thread function\n thread_function(&groups[i].GetFlowGroup());\n });\n }\n\n for (size_t i = 0; i < count; i++) {\n threads[i].join();\n }\n for (size_t i = 0; i < count; i++) {\n groups[i].Close();\n }\n}\n\nTEST(Group, RealInitializeAndClose) {\n \/\/ Construct a real Group of 6 workers which do nothing but terminate.\n RealGroupConstructAndCall([](Group*) { });\n}\n\nTEST(Group, RealInitializeSendReceive) {\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all neighbors.\n RealGroupConstructAndCall(ThreadInitializeSendReceive);\n}\n\nTEST(Group, RealInitializeSendReceiveALot) {\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all neighbors.\n RealGroupConstructAndCall(ThreadInitializeSendReceive);\n}\n\nTEST(Group, RealInitializeSendReceiveAsync) { \/\/TODO(ej) test hangs from time to time\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ which sends and receives asynchronous messages between all workers.\n RealGroupConstructAndCall(ThreadInitializeAsyncRead);\n}\n\nTEST(Group, RealInitializeSendReceiveAsyncALot) {\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all neighbors.\n RealGroupConstructAndCall(ThreadInitializeSendReceive);\n}\n\nTEST(Group, RealInitializeBroadcast) {\n \/\/ Construct a real Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all workers.\n RealGroupConstructAndCall(ThreadInitializeBroadcastIntegral);\n}\nTEST(Group, RealSendCyclic) {\n RealGroupConstructAndCall(ThreadInitializeSendCyclic);\n}\n\nTEST(Group, InitializeAndClose) {\n \/\/ Construct a Group of 6 workers which do nothing but terminate.\n Group::ExecuteLocalMock(6, [](Group*) { });\n}\n\nTEST(Group, InitializeSendReceive) {\n \/\/ Construct a Group of 6 workers which execute the thread function\n \/\/ which sends and receives asynchronous messages between all workers.\n Group::ExecuteLocalMock(6, ThreadInitializeSendReceive);\n}\n\nTEST(Group, InitializeBroadcast) {\n \/\/ Construct a Group of 6 workers which execute the thread function\n \/\/ above which sends and receives a message from all workers.\n Group::ExecuteLocalMock(6, ThreadInitializeBroadcastIntegral);\n}\n\nTEST(Group, SendCyclic) {\n Group::ExecuteLocalMock(6, ThreadInitializeSendCyclic);\n}\n\nTEST(Group, TestPrefixSum) {\n for (size_t p = 1; p <= 8; ++p) {\n \/\/ Construct Group of p workers which perform a PrefixSum collective\n Group::ExecuteLocalMock(\n p, [](Group* net) {\n size_t local_value = 1;\n PrefixSum(*net, local_value);\n ASSERT_EQ(local_value, net->MyRank() + 1);\n });\n }\n}\n\nTEST(Group, TestAllReduce) {\n for (size_t p = 0; p <= 8; ++p) {\n \/\/ Construct Group of p workers which perform an AllReduce collective\n Group::ExecuteLocalMock(\n p, [](Group* net) {\n size_t local_value = net->MyRank();\n AllReduce(*net, local_value);\n ASSERT_EQ(local_value, net->Size() * (net->Size() - 1) \/ 2);\n });\n }\n}\n\nTEST(Group, TestBroadcast) {\n for (size_t p = 0; p <= 8; ++p) {\n \/\/ Construct Group of p workers which perform an Broadcast collective\n Group::ExecuteLocalMock(\n p, [](Group* net) {\n size_t local_value;\n if (net->MyRank() == 0) local_value = 42;\n Broadcast(*net, local_value);\n ASSERT_EQ(local_value, 42u);\n });\n }\n}\n\nTEST(Group, TestReduceToRoot) {\n for (size_t p = 0; p <= 8; ++p) {\n \/\/ Construct Group of p workers which perform an Broadcast collective\n Group::ExecuteLocalMock(\n p, [](Group* net) {\n size_t local_value = net->MyRank();\n ReduceToRoot(*net, local_value);\n if (net->MyRank() == 0)\n ASSERT_EQ(local_value, net->Size() * (net->Size() - 1) \/ 2);\n });\n }\n}\n\nTEST(Group, TestBarrier) {\n static const bool debug = false;\n std::mutex sync_mtx; \/\/ Synchronisation mutex for the barrier\n std::mutex local_mtx; \/\/ Mutex for writing to the results array\n std::condition_variable cv; \/\/ Condition variable for the barrier\n\n for (int p = 0; p <= 8; ++p) {\n int workers = p;\n int workers_copy = workers; \/\/ Will be decremented by the barrier function\n\n std::vector<char> result(2 * workers);\n int k = 0; \/\/ The counter for the result array\n sLOG << \"I'm in test\" << workers;\n\n Group::ExecuteLocalMock(\n workers, [&](Group* net) {\n local_mtx.lock();\n result[k++] = 'B'; \/\/ B stands for 'Before barrier'\n local_mtx.unlock();\n\n sLOG << \"Before Barrier, worker\" << net->MyRank();\n\n ThreadBarrier(sync_mtx, cv, workers_copy);\n\n local_mtx.lock();\n result[k++] = 'A'; \/\/ A stands for 'After barrier'\n local_mtx.unlock();\n\n sLOG << \"After Barrier, worker\" << net->MyRank();\n });\n for (int i = 0; i < workers; ++i) {\n sLOG << \"Checking position\" << i;\n ASSERT_EQ(result[i], 'B');\n }\n for (int i = workers; i < 2 * workers; ++i) {\n sLOG << \"Checking position\" << i;\n ASSERT_EQ(result[i], 'A');\n }\n }\n}\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/asio\/deadline_timer.hpp>\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/asio\/streambuf.hpp>\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <chrono>\n#include <memory>\n\nnamespace boost {\n namespace asio { class io_service; }\n}\n\n\/\/=============================================================================\nnamespace riak {\n\/\/=============================================================================\n\nclass request_with_timeout\n : public std::enable_shared_from_this<request_with_timeout>\n{\n public:\n typedef std::function<void(const boost::system::error_code&, std::size_t, boost::asio::streambuf&)> response_handler;\n \n \/*!\n * Packages a task, but does not send it or begin any timeout counting.\n * \\param timeout is in milliseconds.\n *\/\n request_with_timeout (\n const std::string& data,\n std::chrono::milliseconds timeout,\n boost::asio::ip::tcp::socket& s,\n response_handler& h,\n boost::asio::io_service& ios);\n \n \/*!\n * Sends the request and begins listening for a response asynchronously. Timeout countdown starts now.\n * \\pre There must exist a shared pointer to this request at the time of dispatch. It may be\n * reset as soon as the request is dispatched.\n *\/\n void dispatch ();\n\n private:\n void on_response (const boost::system::error_code&, std::size_t);\n void on_timeout (const boost::system::error_code&);\n void on_write (const boost::system::error_code&, std::size_t);\n \n mutable boost::mutex mutex_;\n boost::asio::ip::tcp::socket& socket_;\n std::chrono::milliseconds timeout_length_;\n boost::asio::deadline_timer timeout_;\n response_handler response_callback_;\n const std::string request_data_;\n boost::asio::streambuf response_data_;\n \n bool succeeded_;\n bool timed_out_;\n};\n\n\/\/=============================================================================\n} \/\/ namespace riak\n\/\/=============================================================================\n<commit_msg>Removed a dependency on boost DateTime.<commit_after>#include <boost\/asio\/deadline_timer.hpp>\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/asio\/streambuf.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <chrono>\n#include <memory>\n\nnamespace boost {\n namespace asio { class io_service; }\n}\n\n\/\/=============================================================================\nnamespace riak {\n\/\/=============================================================================\n\nclass request_with_timeout\n : public std::enable_shared_from_this<request_with_timeout>\n{\n public:\n typedef std::function<void(const boost::system::error_code&, std::size_t, boost::asio::streambuf&)> response_handler;\n \n \/*!\n * Packages a task, but does not send it or begin any timeout counting.\n * \\param timeout is in milliseconds.\n *\/\n request_with_timeout (\n const std::string& data,\n std::chrono::milliseconds timeout,\n boost::asio::ip::tcp::socket& s,\n response_handler& h,\n boost::asio::io_service& ios);\n \n \/*!\n * Sends the request and begins listening for a response asynchronously. Timeout countdown starts now.\n * \\pre There must exist a shared pointer to this request at the time of dispatch. It may be\n * reset as soon as the request is dispatched.\n *\/\n void dispatch ();\n\n private:\n void on_response (const boost::system::error_code&, std::size_t);\n void on_timeout (const boost::system::error_code&);\n void on_write (const boost::system::error_code&, std::size_t);\n \n mutable boost::mutex mutex_;\n boost::asio::ip::tcp::socket& socket_;\n std::chrono::milliseconds timeout_length_;\n boost::asio::deadline_timer timeout_;\n response_handler response_callback_;\n const std::string request_data_;\n boost::asio::streambuf response_data_;\n \n bool succeeded_;\n bool timed_out_;\n};\n\n\/\/=============================================================================\n} \/\/ namespace riak\n\/\/=============================================================================\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: border.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 16:49:40 $\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 _SVX_BORDER_HXX\n#define _SVX_BORDER_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n\n#ifndef _CTRLBOX_HXX \/\/autogen\n#include <svtools\/ctrlbox.hxx>\n#endif\n#ifndef _GROUP_HXX \/\/autogen\n#include <vcl\/group.hxx>\n#endif\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _VALUESET_HXX \/\/autogen\n#include <svtools\/valueset.hxx>\n#endif\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include <sfx2\/tabdlg.hxx>\n#endif\n#ifndef SVX_FRMSEL_HXX\n#include <svx\/frmsel.hxx>\n#endif\n\/\/ forward ---------------------------------------------------------------\n\nclass SvxBorderLine;\nclass XColorTable;\n\n\/\/ class SvxBorderTabPage ------------------------------------------------\n\/*\n{k:\\svx\\prototyp\\dialog\\border.bmp}\n[Beschreibung]\nTabPage zur Einstellung der Umrandung (Staerke, Farbe, Schatten, ...)\n[Items]\n<SvxBoxItem><SID_ATTR_BORDER_OUTER>\n<SvxBoxInfoItem><SID_ATTR_BORDER_INNER>\n<SvxShadowItem><SID_ATTR_BORDER_SHADOW>\n*\/\n\n\/\/ Border-Modes for paragraphs, textframes and tables\n\/\/CHINA001 #define SW_BORDER_MODE_PARA 0x01\n\/\/CHINA001 #define SW_BORDER_MODE_TABLE 0x02\n\/\/CHINA001 #define SW_BORDER_MODE_FRAME 0x04\n#include \"flagsdef.hxx\"\/\/CHINA001\n\nclass SvxBorderTabPage : public SfxTabPage\n{\n using TabPage::DeactivatePage;\n\npublic:\n static SfxTabPage* Create( Window* pParent,\n const SfxItemSet& rAttrSet);\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet( SfxItemSet& rCoreAttrs );\n virtual void Reset( const SfxItemSet& );\n\n void HideShadowControls();\n virtual void PageCreated (SfxAllItemSet aSet); \/\/add CHINA001\nprotected:\n virtual int DeactivatePage( SfxItemSet* pSet = 0 );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\nprivate:\n SvxBorderTabPage( Window* pParent, const SfxItemSet& rCoreAttrs );\n ~SvxBorderTabPage();\n\n \/\/ Controls\n FixedLine aFlBorder;\n FixedText aDefaultFT;\n ValueSet aWndPresets;\n FixedText aUserDefFT;\n svx::FrameSelector aFrameSel;\n\n FixedLine aFlSep1;\n FixedLine aFlLine;\n FixedText aStyleFT;\n LineListBox aLbLineStyle;\n FixedText aColorFT;\n ColorListBox aLbLineColor;\n\n FixedLine aFlSep2;\n FixedLine aDistanceFL;\n FixedText aLeftFT;\n MetricField aLeftMF;\n FixedText aRightFT;\n MetricField aRightMF;\n FixedText aTopFT;\n MetricField aTopMF;\n FixedText aBottomFT;\n MetricField aBottomMF;\n CheckBox aSynchronizeCB;\n\n FixedLine aFlShadow;\n FixedText aFtShadowPos;\n ValueSet aWndShadows;\n FixedText aFtShadowSize;\n MetricField aEdShadowSize;\n FixedText aFtShadowColor;\n ColorListBox aLbShadowColor;\n\n \/\/properties - \"Merge with next paragraph\" in Writer\n FixedLine aPropertiesFL;\n CheckBox aMergeWithNextCB;\n \/\/ --> collapsing table borders FME 2005-05-27 #i29550#\n CheckBox aMergeAdjacentBordersCB;\n \/\/ <--\n\n ImageList aShadowImgLstH;\n ImageList aShadowImgLst;\n ImageList aBorderImgLstH;\n ImageList aBorderImgLst;\n\n long nMinValue; \/\/ minimum distance\n int nSWMode; \/\/ table, textframe, paragraph\n\n bool mbHorEnabled; \/\/\/ true = Inner horizontal border enabled.\n bool mbVerEnabled; \/\/\/ true = Inner vertical border enabled.\n bool mbTLBREnabled; \/\/\/ true = Top-left to bottom-right border enabled.\n bool mbBLTREnabled; \/\/\/ true = Bottom-left to top-right border enabled.\n bool mbUseMarginItem;\n\n static BOOL bSync;\n\n#ifdef _SVX_BORDER_CXX\n \/\/ Handler\n DECL_LINK( SelStyleHdl_Impl, ListBox* pLb );\n DECL_LINK( SelColHdl_Impl, ListBox* pLb );\n DECL_LINK( SelPreHdl_Impl, void* );\n DECL_LINK( SelSdwHdl_Impl, void* );\n DECL_LINK( LinesChanged_Impl, void* );\n DECL_LINK( ModifyDistanceHdl_Impl, MetricField*);\n DECL_LINK( SyncHdl_Impl, CheckBox*);\n\n USHORT GetPresetImageId( USHORT nValueSetIdx ) const;\n USHORT GetPresetStringId( USHORT nValueSetIdx ) const;\n\n void FillPresetVS();\n void FillShadowVS();\n void FillValueSets();\n\n \/\/ Filler\n void FillLineListBox_Impl();\n\n \/\/ Setzen von einzelnen Frame-\/Core-Linien\n void ResetFrameLine_Impl( svx::FrameBorderType eBorder,\n const SvxBorderLine* pCurLine,\n bool bValid );\n#endif\n};\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.368); FILE MERGED 2008\/04\/01 15:50:13 thb 1.7.368.3: #i85898# Stripping all external header guards 2008\/04\/01 12:48:05 thb 1.7.368.2: #i85898# Stripping all external header guards 2008\/03\/31 14:19:19 rt 1.7.368.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: border.hxx,v $\n * $Revision: 1.8 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_BORDER_HXX\n#define _SVX_BORDER_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n\n#include <svtools\/ctrlbox.hxx>\n#ifndef _GROUP_HXX \/\/autogen\n#include <vcl\/group.hxx>\n#endif\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#include <svtools\/valueset.hxx>\n#include <sfx2\/tabdlg.hxx>\n#include <svx\/frmsel.hxx>\n\/\/ forward ---------------------------------------------------------------\n\nclass SvxBorderLine;\nclass XColorTable;\n\n\/\/ class SvxBorderTabPage ------------------------------------------------\n\/*\n{k:\\svx\\prototyp\\dialog\\border.bmp}\n[Beschreibung]\nTabPage zur Einstellung der Umrandung (Staerke, Farbe, Schatten, ...)\n[Items]\n<SvxBoxItem><SID_ATTR_BORDER_OUTER>\n<SvxBoxInfoItem><SID_ATTR_BORDER_INNER>\n<SvxShadowItem><SID_ATTR_BORDER_SHADOW>\n*\/\n\n\/\/ Border-Modes for paragraphs, textframes and tables\n\/\/CHINA001 #define SW_BORDER_MODE_PARA 0x01\n\/\/CHINA001 #define SW_BORDER_MODE_TABLE 0x02\n\/\/CHINA001 #define SW_BORDER_MODE_FRAME 0x04\n#include \"flagsdef.hxx\"\/\/CHINA001\n\nclass SvxBorderTabPage : public SfxTabPage\n{\n using TabPage::DeactivatePage;\n\npublic:\n static SfxTabPage* Create( Window* pParent,\n const SfxItemSet& rAttrSet);\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet( SfxItemSet& rCoreAttrs );\n virtual void Reset( const SfxItemSet& );\n\n void HideShadowControls();\n virtual void PageCreated (SfxAllItemSet aSet); \/\/add CHINA001\nprotected:\n virtual int DeactivatePage( SfxItemSet* pSet = 0 );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\nprivate:\n SvxBorderTabPage( Window* pParent, const SfxItemSet& rCoreAttrs );\n ~SvxBorderTabPage();\n\n \/\/ Controls\n FixedLine aFlBorder;\n FixedText aDefaultFT;\n ValueSet aWndPresets;\n FixedText aUserDefFT;\n svx::FrameSelector aFrameSel;\n\n FixedLine aFlSep1;\n FixedLine aFlLine;\n FixedText aStyleFT;\n LineListBox aLbLineStyle;\n FixedText aColorFT;\n ColorListBox aLbLineColor;\n\n FixedLine aFlSep2;\n FixedLine aDistanceFL;\n FixedText aLeftFT;\n MetricField aLeftMF;\n FixedText aRightFT;\n MetricField aRightMF;\n FixedText aTopFT;\n MetricField aTopMF;\n FixedText aBottomFT;\n MetricField aBottomMF;\n CheckBox aSynchronizeCB;\n\n FixedLine aFlShadow;\n FixedText aFtShadowPos;\n ValueSet aWndShadows;\n FixedText aFtShadowSize;\n MetricField aEdShadowSize;\n FixedText aFtShadowColor;\n ColorListBox aLbShadowColor;\n\n \/\/properties - \"Merge with next paragraph\" in Writer\n FixedLine aPropertiesFL;\n CheckBox aMergeWithNextCB;\n \/\/ --> collapsing table borders FME 2005-05-27 #i29550#\n CheckBox aMergeAdjacentBordersCB;\n \/\/ <--\n\n ImageList aShadowImgLstH;\n ImageList aShadowImgLst;\n ImageList aBorderImgLstH;\n ImageList aBorderImgLst;\n\n long nMinValue; \/\/ minimum distance\n int nSWMode; \/\/ table, textframe, paragraph\n\n bool mbHorEnabled; \/\/\/ true = Inner horizontal border enabled.\n bool mbVerEnabled; \/\/\/ true = Inner vertical border enabled.\n bool mbTLBREnabled; \/\/\/ true = Top-left to bottom-right border enabled.\n bool mbBLTREnabled; \/\/\/ true = Bottom-left to top-right border enabled.\n bool mbUseMarginItem;\n\n static BOOL bSync;\n\n#ifdef _SVX_BORDER_CXX\n \/\/ Handler\n DECL_LINK( SelStyleHdl_Impl, ListBox* pLb );\n DECL_LINK( SelColHdl_Impl, ListBox* pLb );\n DECL_LINK( SelPreHdl_Impl, void* );\n DECL_LINK( SelSdwHdl_Impl, void* );\n DECL_LINK( LinesChanged_Impl, void* );\n DECL_LINK( ModifyDistanceHdl_Impl, MetricField*);\n DECL_LINK( SyncHdl_Impl, CheckBox*);\n\n USHORT GetPresetImageId( USHORT nValueSetIdx ) const;\n USHORT GetPresetStringId( USHORT nValueSetIdx ) const;\n\n void FillPresetVS();\n void FillShadowVS();\n void FillValueSets();\n\n \/\/ Filler\n void FillLineListBox_Impl();\n\n \/\/ Setzen von einzelnen Frame-\/Core-Linien\n void ResetFrameLine_Impl( svx::FrameBorderType eBorder,\n const SvxBorderLine* pCurLine,\n bool bValid );\n#endif\n};\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nSome numbers:\nMax ActorID: 1971696\nNRows: 17316773-1\nMax MovieID: 1151758\n*\/\n\n#include <iostream>\n#include <ios>\n#include <fstream>\n#include <vector>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys\/mman.h>\n#include <list>\n#include <thread>\n\nusing namespace std;\n\n\n\/\/ BAD CODING!!! <3\nint *actor_keys = new int[1971696];\nint *act2mov_actors = new int[1971696];\nint *act2mov_movies = new int[17316773-1];\nint *mov2act_movies = new int[1151758];\nint *mov2act_actors = new int[17316773-1]();\n\n\/\/ Breadth-First Search\nint BFS(\n int *act2mov_actors,\n int *act2mov_movies,\n int *mov2act_movies,\n int *mov2act_actors,\n int actorid2, \n vector<int> current_nodes,\n bool *actor_visited,\n bool *movie_visited\n ) {\n \/*\n Iterate over the current nodes.\n For each actor find all movies.\n If we visited the movie already skip it, otherwise find all actors in that movie.\n Add the actors we did not look at already to the neighbourhood.\n Swap neighbours and current_nodes and start again.\n *\/\n \n vector<int> neighbours;\n int depth = 0;\n\n while(!current_nodes.empty()){\n depth++;\n for(int i : current_nodes) {\n for(int j = act2mov_actors[i-1]; j < act2mov_actors[i]; j++) {\n int movie = act2mov_movies[j];\n if(!movie_visited[movie]){\n movie_visited[movie] = 1;\n for(int k=mov2act_movies[movie-1]; k<mov2act_movies[movie]; k++){\n int new_actor = mov2act_actors[k];\n if(!actor_visited[new_actor]) {\n if(new_actor==actorid2){\n return depth;\n }\n actor_visited[new_actor] = 1;\n neighbours.push_back(new_actor);\n }\n }\n }\n }\n }\n\n current_nodes.swap(neighbours);\n neighbours.clear();\n }\n\n return -1;\n}\n\nvoid BFSThread(int thread_a1, int thread_a2, int *dist_thread, int i){\n \n if(thread_a1 == thread_a2){\n dist_thread[i] = 0;\n return;\n }\n\n \/\/ Boolean arrays to save which has been visited\n bool *actor_visited = new bool[1971696+1]();\n bool *movie_visited = new bool[1151758+1]();\n \n \/\/ We start with only actor 1 on the current node\n vector<int> current_nodes;\n current_nodes.push_back(actor_keys[thread_a1]);\n \/\/ Start Breadth-First-Search\n int dist;\n dist = BFS(\n act2mov_actors, act2mov_movies, \n mov2act_movies, mov2act_actors,\n actor_keys[thread_a2], current_nodes, actor_visited, movie_visited);\n cout << \"Process: \" << i << \" Distance: \" << dist << endl;\n dist_thread[i] = dist;\n\n \/\/ delete unsused variable\n delete[] actor_visited;\n delete[] movie_visited;\n}\n\nint main(int argc, char** argv) {\n\n \/\/ Movie to actor map - Will be replaced later\n vector<vector<int>> M(1151758+1);\n\n \/\/ Open file and figre out length\n int handle = open(argv[1],O_RDONLY);\n if (handle<0) return 1;\n lseek(handle,0,SEEK_END);\n long length = lseek(handle,0,SEEK_CUR);\n \n \/\/ Map file into address space\n auto data = static_cast<const char*>(mmap(nullptr,length,PROT_READ,MAP_SHARED,handle,0));\n auto dataLimit = data + length;\n \n \/* Read file and create our datatypes\n We store the actor to movie relation in a CSR and movie to actor in a map\n *\/\n const char* line = data;\n int actor_index = -1;\n int current_line = 0;\n int last_actor = 0;\n for (const char* current=data;current!=dataLimit;) {\n const char* last=line;\n unsigned column=0;\n int actor=0;\n int movie=0;\n for (;current!=dataLimit;++current) {\n char c=*current;\n if (c==',') {\n last=current+1;\n ++column;\n }else if (c=='\\n') {\n \/* Check if the actor is different to the last one\n If yes increase actor_index and add entry to actor_keys *\/\n if(actor != last_actor){\n last_actor = actor;\n act2mov_actors[actor_index] = current_line;\n ++actor_index;\n actor_keys[actor] = actor_index;\n }\n\n \/\/ Insert entry into Movie->Actor Map\n M[movie].push_back(actor_index);\n \n \/\/ Insert movie to list\n act2mov_movies[current_line] = movie;\n \n \/\/ Update index\n ++current_line;\n \n ++current;\n break;\n }else if (column==0) {\n actor=10*actor+c-'0';\n }else if (column==1) {\n movie=10*movie+c-'0';\n }\n }\n }\n act2mov_actors[actor_index] = current_line;\n\n cout << \"File eingelesen\" << endl;\n\n \/\/ Create CSR for movie to actor relation\n int iterator = 0;\n for(int movie_id=1; movie_id<=1151758; movie_id++){\n for(int actor : M.at(movie_id)){\n mov2act_actors[iterator] = actor;\n\t ++iterator;\n }\n mov2act_movies[movie_id] = iterator;\n }\n\n \/\/ While there is an input: read, store, compute\n int actorid1;\n int actorid2;\n vector<int> actor1;\n vector<int> actor2;\n \n while((cin >> actorid1) && (cin >> actorid2)) {\n actor1.push_back(actorid1);\n actor2.push_back(actorid2);\n }\n\n \n int inputlen = actor1.size();\n int *distance = new int[inputlen];\n thread *thread_arr = new thread[inputlen];\n for(int time_counter = 0; time_counter<1; ++time_counter){\n for(int i=0; i < inputlen; i++){\n thread_arr[i] = thread(BFSThread, actor1[i], actor2[i], distance, i);\n }\n cout << \"Threading started\" << endl;\n for(int i=0; i < inputlen; i++){\n thread_arr[i].join();\n }\n }\n \n for(int j=0; j<inputlen; j++){\n cout << distance[j] << endl;\n }\n return 0;\n}\n<commit_msg>final lookin' good!<commit_after>\/*\nSome numbers:\nMax ActorID: 1971696\nNRows: 17316773-1\nMax MovieID: 1151758\n*\/\n\n#include <iostream>\n#include <vector>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys\/mman.h>\n#include <thread>\n\nusing namespace std;\n\n\n\/\/ BAD CODING!!! <3\nint *actor_keys = new int[1971696];\nint *act2mov_actors = new int[1971696];\nint *act2mov_movies = new int[17316773-1];\nint *mov2act_movies = new int[1151758];\nint *mov2act_actors = new int[17316773-1]();\n\n\/\/ Breadth-First Search\nint BFS(\n int *act2mov_actors,\n int *act2mov_movies,\n int *mov2act_movies,\n int *mov2act_actors,\n int actorid2, \n vector<int> current_nodes,\n bool *actor_visited,\n bool *movie_visited\n ) {\n \/*\n Iterate over the current nodes.\n For each actor find all movies.\n If we visited the movie already skip it, otherwise find all actors in that movie.\n Add the actors we did not look at already to the neighbourhood.\n Swap neighbours and current_nodes and start again.\n *\/\n \n vector<int> neighbours;\n int depth = 0;\n\n while(!current_nodes.empty()){\n depth++;\n for(int i : current_nodes) {\n for(int j = act2mov_actors[i-1]; j < act2mov_actors[i]; j++) {\n int movie = act2mov_movies[j];\n if(!movie_visited[movie]){\n movie_visited[movie] = 1;\n for(int k=mov2act_movies[movie-1]; k<mov2act_movies[movie]; k++){\n int new_actor = mov2act_actors[k];\n if(!actor_visited[new_actor]) {\n if(new_actor==actorid2){\n return depth;\n }\n actor_visited[new_actor] = 1;\n neighbours.push_back(new_actor);\n }\n }\n }\n }\n }\n\n current_nodes.swap(neighbours);\n neighbours.clear();\n }\n\n return -1;\n}\n\nvoid BFSThread(int thread_a1, int thread_a2, int *dist_thread, int i){\n \n if(thread_a1 == thread_a2){\n dist_thread[i] = 0;\n return;\n }\n\n \/\/ Boolean arrays to save which has been visited\n bool *actor_visited = new bool[1971696+1]();\n bool *movie_visited = new bool[1151758+1]();\n \n \/\/ We start with only actor 1 on the current node\n vector<int> current_nodes;\n current_nodes.push_back(actor_keys[thread_a1]);\n \/\/ Start Breadth-First-Search\n int dist;\n dist = BFS(\n act2mov_actors, act2mov_movies, \n mov2act_movies, mov2act_actors,\n actor_keys[thread_a2], current_nodes, actor_visited, movie_visited);\n \/\/ cout << \"Process: \" << i << \" Distance: \" << dist << endl;\n dist_thread[i] = dist;\n\n \/\/ delete unsused variable\n delete[] actor_visited;\n delete[] movie_visited;\n}\n\nint main(int argc, char** argv) {\n\n \/\/ Movie to actor map - Will be replaced later\n vector<vector<int>> M(1151758+1);\n\n \/\/ Open file and figre out length\n int handle = open(argv[1],O_RDONLY);\n if (handle<0) return 1;\n lseek(handle,0,SEEK_END);\n long length = lseek(handle,0,SEEK_CUR);\n \n \/\/ Map file into address space\n auto data = static_cast<const char*>(mmap(nullptr,length,PROT_READ,MAP_SHARED,handle,0));\n auto dataLimit = data + length;\n \n \/* Read file and create our datatypes\n We store the actor to movie relation in a CSR and movie to actor in a map\n *\/\n const char* line = data;\n int actor_index = -1;\n int current_line = 0;\n int last_actor = 0;\n for (const char* current=data;current!=dataLimit;) {\n const char* last=line;\n unsigned column=0;\n int actor=0;\n int movie=0;\n for (;current!=dataLimit;++current) {\n char c=*current;\n if (c==',') {\n last=current+1;\n ++column;\n }else if (c=='\\n') {\n \/* Check if the actor is different to the last one\n If yes increase actor_index and add entry to actor_keys *\/\n if(actor != last_actor){\n last_actor = actor;\n act2mov_actors[actor_index] = current_line;\n ++actor_index;\n actor_keys[actor] = actor_index;\n }\n\n \/\/ Insert entry into Movie->Actor Map\n M[movie].push_back(actor_index);\n \n \/\/ Insert movie to list\n act2mov_movies[current_line] = movie;\n \n \/\/ Update index\n ++current_line;\n \n ++current;\n break;\n }else if (column==0) {\n actor=10*actor+c-'0';\n }else if (column==1) {\n movie=10*movie+c-'0';\n }\n }\n }\n act2mov_actors[actor_index] = current_line;\n\n \/\/ cout << \"File eingelesen\" << endl;\n\n \/\/ Create CSR for movie to actor relation\n int iterator = 0;\n for(int movie_id=1; movie_id<=1151758; movie_id++){\n for(int actor : M.at(movie_id)){\n mov2act_actors[iterator] = actor;\n\t ++iterator;\n }\n mov2act_movies[movie_id] = iterator;\n }\n\n \/\/ While there is an input: read, store, compute\n int actorid1;\n int actorid2;\n vector<int> actor1;\n vector<int> actor2;\n \n while((cin >> actorid1) && (cin >> actorid2)) {\n actor1.push_back(actorid1);\n actor2.push_back(actorid2);\n }\n\n \n int inputlen = actor1.size();\n int *distance = new int[inputlen];\n thread *thread_arr = new thread[inputlen];\n for(int time_counter = 0; time_counter<1; ++time_counter){\n for(int i=0; i < inputlen; i++){\n thread_arr[i] = thread(BFSThread, actor1[i], actor2[i], distance, i);\n }\n \/\/ cout << \"Threading started\" << endl;\n for(int i=0; i < inputlen; i++){\n thread_arr[i].join();\n }\n }\n \n for(int j=0; j<inputlen; j++){\n cout << distance[j] << endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: SwStyleNameMapper.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2004-08-23 08:27:31 $\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): Martin Gallwey ( gallwey@sun.com )\n *\n *\n ************************************************************************\/\n#ifndef _SWSTYLENAMEMAPPER_HXX\n#define _SWSTYLENAMEMAPPER_HXX\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _GETPOOLIDFROMNAMEENUM_HXX\n#include <SwGetPoolIdFromName.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\n#ifndef INCLUDED_HASH_MAP\n#include <hash_map>\n#define INCLUDED_HASH_MAP\n#endif\n\n#ifndef _STRINGHASH_HXX\n#include <stringhash.hxx>\n#endif\n\n\/* This class holds all data about the names of styles used in the user\n * interface (UI names...these are localised into different languages).\n * These UI names are loaded from the resource files on demand.\n *\n * It also holds all information about the 'Programmatic' names of styles\n * which remain static (and are hardcoded in the corresponding cxx file)\n * for all languages.\n *\n * This class also provides static functions which can be used for the\n * following conversions:\n *\n * 1. Programmatic Name -> UI Name\n * 2. Programmatic Name -> Pool ID\n * 3. UI Name -> Programmatic Name\n * 4. UI Name -> Pool ID\n * 5. Pool ID -> UI Name\n * 6. Pool ID -> Programmatic Name\n *\n * The relationship of these tables to the style families is as follows:\n *\n * 1. Paragraph contains the Text, Lists, Extra, Register, Doc and HTML\n * name arrays.\n * 2. Character contains the ChrFmt and HTMLChrFmt name arrays.\n * 3. Page contains the PageDesc name array.\n * 4. Frame contains the FrmFmt name array.\n * 5. Numbering Rule contains the NumRule name array.\n *\/\n\n\/*\n * There is a further complication that came to light later. If someone enters\n * a user-defined style name which is the same as a programmatic name, this\n * name clash must be handled.\n *\n * Therefore, when there is a danger of a nameclash, the boolean bDisambiguate\n * must be set to true in the SwStyleNameMapper call (it defaults to false).\n * This will cause the following to happen:\n *\n * If the UI style name either equals a programmatic name or already ends\n * with \" (user)\", then it must append \" (user)\" to the end.\n *\n * When a programmatic name is being converted to a UI name, if it ends in\n * \" (user)\", we simply remove it.\n *\/\n\nclass SvStringsDtor;\nclass String;\nstruct SwTableEntry;\n\n\ntypedef ::std::hash_map < const String*, sal_uInt16, StringHash, StringEq > NameToIdHash;\n\nclass SwStyleNameMapper\n{\n friend void _InitCore();\n friend void _FinitCore();\n\nprotected:\n \/\/ UI Name tables\n static SvStringsDtor *pTextUINameArray,\n *pListsUINameArray,\n *pExtraUINameArray,\n *pRegisterUINameArray,\n *pDocUINameArray,\n *pHTMLUINameArray,\n *pFrmFmtUINameArray,\n *pChrFmtUINameArray,\n *pHTMLChrFmtUINameArray,\n *pPageDescUINameArray,\n *pNumRuleUINameArray,\n \/\/ Programmatic Name tables\n *pTextProgNameArray,\n *pListsProgNameArray,\n *pExtraProgNameArray,\n *pRegisterProgNameArray,\n *pDocProgNameArray,\n *pHTMLProgNameArray,\n *pFrmFmtProgNameArray,\n *pChrFmtProgNameArray,\n *pHTMLChrFmtProgNameArray,\n *pPageDescProgNameArray,\n *pNumRuleProgNameArray;\n\n static NameToIdHash *pParaUIMap,\n *pCharUIMap,\n *pPageUIMap,\n *pFrameUIMap,\n *pNumRuleUIMap,\n\n *pParaProgMap,\n *pCharProgMap,\n *pPageProgMap,\n *pFrameProgMap,\n *pNumRuleProgMap;\n\n static SvStringsDtor* NewUINameArray( SvStringsDtor*&,\n sal_uInt16 nStt,\n sal_uInt16 nEnd );\n\n static SvStringsDtor* NewProgNameArray( SvStringsDtor*&,\n const SwTableEntry *pTable,\n sal_uInt8 nCount);\n\n static void fillNameFromId ( sal_uInt16 nId, String &rName, sal_Bool bProgName );\n static const String& getNameFromId ( sal_uInt16 nId, const String &rName, sal_Bool bProgName );\n static const NameToIdHash& getHashTable ( SwGetPoolIdFromName, sal_Bool bProgName );\n static sal_Bool SuffixIsUser ( const String & rString );\n static void CheckSuffixAndDelete ( String & rString );\n\npublic:\n \/\/ This gets the UI Name from the programmatic name\n static const String& GetUIName ( const String& rName, SwGetPoolIdFromName );\n static void FillUIName ( const String& rName, String& rFillName, SwGetPoolIdFromName, sal_Bool bDisambiguate = sal_False );\n\n \/\/ Get the programmatic Name from the UI name\n static const String& GetProgName ( const String& rName, SwGetPoolIdFromName );\n static void FillProgName ( const String& rName, String& rFillName, SwGetPoolIdFromName, sal_Bool bDisambiguate = sal_False );\n\n \/\/ This gets the UI Name from the Pool ID\n SW_DLLPUBLIC static void FillUIName ( sal_uInt16 nId, String& rFillName );\n SW_DLLPUBLIC static const String& GetUIName ( sal_uInt16 nId, const String& rName );\n\n \/\/ This gets the programmatic Name from the Pool ID\n static void FillProgName( sal_uInt16 nId, String& rFillName );\n static const String& GetProgName ( sal_uInt16 nId, const String& rName );\n\n \/\/ This gets the PoolId from the UI Name\n SW_DLLPUBLIC static sal_uInt16 GetPoolIdFromUIName( const String& rName, SwGetPoolIdFromName );\n\n \/\/ Get the Pool ID from the programmatic name\n static sal_uInt16 GetPoolIdFromProgName( const String& rName, SwGetPoolIdFromName );\n\n \/\/ used to convert the 4 special ExtraProg\/UINames for\n \/\/ RES_POOLCOLL_LABEL_DRAWING, RES_POOLCOLL_LABEL_ABB,\n \/\/ RES_POOLCOLL_LABEL_TABLE, RES_POOLCOLL_LABEL_FRAME\n \/\/ forth and back.\n \/\/ Non-matching names remain unchanged.\n SW_DLLPUBLIC static const String GetSpecialExtraProgName( const String& rExtraUIName );\n static const String GetSpecialExtraUIName( const String& rExtraProgName );\n\n static const SvStringsDtor& GetTextUINameArray();\n static const SvStringsDtor& GetListsUINameArray();\n static const SvStringsDtor& GetExtraUINameArray();\n static const SvStringsDtor& GetRegisterUINameArray();\n static const SvStringsDtor& GetDocUINameArray();\n static const SvStringsDtor& GetHTMLUINameArray();\n static const SvStringsDtor& GetFrmFmtUINameArray();\n static const SvStringsDtor& GetChrFmtUINameArray();\n static const SvStringsDtor& GetHTMLChrFmtUINameArray();\n static const SvStringsDtor& GetPageDescUINameArray();\n static const SvStringsDtor& GetNumRuleUINameArray();\n\n static const SvStringsDtor& GetTextProgNameArray();\n static const SvStringsDtor& GetListsProgNameArray();\n static const SvStringsDtor& GetExtraProgNameArray();\n static const SvStringsDtor& GetRegisterProgNameArray();\n static const SvStringsDtor& GetDocProgNameArray();\n static const SvStringsDtor& GetHTMLProgNameArray();\n static const SvStringsDtor& GetFrmFmtProgNameArray();\n static const SvStringsDtor& GetChrFmtProgNameArray();\n static const SvStringsDtor& GetHTMLChrFmtProgNameArray();\n static const SvStringsDtor& GetPageDescProgNameArray();\n static const SvStringsDtor& GetNumRuleProgNameArray();\n};\n#endif \/\/ _NAME_MAPPER_HXX\n<commit_msg>INTEGRATION: CWS ooo19126 (1.6.596); FILE MERGED 2005\/09\/05 13:35:35 rt 1.6.596.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SwStyleNameMapper.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:29:53 $\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 _SWSTYLENAMEMAPPER_HXX\n#define _SWSTYLENAMEMAPPER_HXX\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _GETPOOLIDFROMNAMEENUM_HXX\n#include <SwGetPoolIdFromName.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\n#ifndef INCLUDED_HASH_MAP\n#include <hash_map>\n#define INCLUDED_HASH_MAP\n#endif\n\n#ifndef _STRINGHASH_HXX\n#include <stringhash.hxx>\n#endif\n\n\/* This class holds all data about the names of styles used in the user\n * interface (UI names...these are localised into different languages).\n * These UI names are loaded from the resource files on demand.\n *\n * It also holds all information about the 'Programmatic' names of styles\n * which remain static (and are hardcoded in the corresponding cxx file)\n * for all languages.\n *\n * This class also provides static functions which can be used for the\n * following conversions:\n *\n * 1. Programmatic Name -> UI Name\n * 2. Programmatic Name -> Pool ID\n * 3. UI Name -> Programmatic Name\n * 4. UI Name -> Pool ID\n * 5. Pool ID -> UI Name\n * 6. Pool ID -> Programmatic Name\n *\n * The relationship of these tables to the style families is as follows:\n *\n * 1. Paragraph contains the Text, Lists, Extra, Register, Doc and HTML\n * name arrays.\n * 2. Character contains the ChrFmt and HTMLChrFmt name arrays.\n * 3. Page contains the PageDesc name array.\n * 4. Frame contains the FrmFmt name array.\n * 5. Numbering Rule contains the NumRule name array.\n *\/\n\n\/*\n * There is a further complication that came to light later. If someone enters\n * a user-defined style name which is the same as a programmatic name, this\n * name clash must be handled.\n *\n * Therefore, when there is a danger of a nameclash, the boolean bDisambiguate\n * must be set to true in the SwStyleNameMapper call (it defaults to false).\n * This will cause the following to happen:\n *\n * If the UI style name either equals a programmatic name or already ends\n * with \" (user)\", then it must append \" (user)\" to the end.\n *\n * When a programmatic name is being converted to a UI name, if it ends in\n * \" (user)\", we simply remove it.\n *\/\n\nclass SvStringsDtor;\nclass String;\nstruct SwTableEntry;\n\n\ntypedef ::std::hash_map < const String*, sal_uInt16, StringHash, StringEq > NameToIdHash;\n\nclass SwStyleNameMapper\n{\n friend void _InitCore();\n friend void _FinitCore();\n\nprotected:\n \/\/ UI Name tables\n static SvStringsDtor *pTextUINameArray,\n *pListsUINameArray,\n *pExtraUINameArray,\n *pRegisterUINameArray,\n *pDocUINameArray,\n *pHTMLUINameArray,\n *pFrmFmtUINameArray,\n *pChrFmtUINameArray,\n *pHTMLChrFmtUINameArray,\n *pPageDescUINameArray,\n *pNumRuleUINameArray,\n \/\/ Programmatic Name tables\n *pTextProgNameArray,\n *pListsProgNameArray,\n *pExtraProgNameArray,\n *pRegisterProgNameArray,\n *pDocProgNameArray,\n *pHTMLProgNameArray,\n *pFrmFmtProgNameArray,\n *pChrFmtProgNameArray,\n *pHTMLChrFmtProgNameArray,\n *pPageDescProgNameArray,\n *pNumRuleProgNameArray;\n\n static NameToIdHash *pParaUIMap,\n *pCharUIMap,\n *pPageUIMap,\n *pFrameUIMap,\n *pNumRuleUIMap,\n\n *pParaProgMap,\n *pCharProgMap,\n *pPageProgMap,\n *pFrameProgMap,\n *pNumRuleProgMap;\n\n static SvStringsDtor* NewUINameArray( SvStringsDtor*&,\n sal_uInt16 nStt,\n sal_uInt16 nEnd );\n\n static SvStringsDtor* NewProgNameArray( SvStringsDtor*&,\n const SwTableEntry *pTable,\n sal_uInt8 nCount);\n\n static void fillNameFromId ( sal_uInt16 nId, String &rName, sal_Bool bProgName );\n static const String& getNameFromId ( sal_uInt16 nId, const String &rName, sal_Bool bProgName );\n static const NameToIdHash& getHashTable ( SwGetPoolIdFromName, sal_Bool bProgName );\n static sal_Bool SuffixIsUser ( const String & rString );\n static void CheckSuffixAndDelete ( String & rString );\n\npublic:\n \/\/ This gets the UI Name from the programmatic name\n static const String& GetUIName ( const String& rName, SwGetPoolIdFromName );\n static void FillUIName ( const String& rName, String& rFillName, SwGetPoolIdFromName, sal_Bool bDisambiguate = sal_False );\n\n \/\/ Get the programmatic Name from the UI name\n static const String& GetProgName ( const String& rName, SwGetPoolIdFromName );\n static void FillProgName ( const String& rName, String& rFillName, SwGetPoolIdFromName, sal_Bool bDisambiguate = sal_False );\n\n \/\/ This gets the UI Name from the Pool ID\n SW_DLLPUBLIC static void FillUIName ( sal_uInt16 nId, String& rFillName );\n SW_DLLPUBLIC static const String& GetUIName ( sal_uInt16 nId, const String& rName );\n\n \/\/ This gets the programmatic Name from the Pool ID\n static void FillProgName( sal_uInt16 nId, String& rFillName );\n static const String& GetProgName ( sal_uInt16 nId, const String& rName );\n\n \/\/ This gets the PoolId from the UI Name\n SW_DLLPUBLIC static sal_uInt16 GetPoolIdFromUIName( const String& rName, SwGetPoolIdFromName );\n\n \/\/ Get the Pool ID from the programmatic name\n static sal_uInt16 GetPoolIdFromProgName( const String& rName, SwGetPoolIdFromName );\n\n \/\/ used to convert the 4 special ExtraProg\/UINames for\n \/\/ RES_POOLCOLL_LABEL_DRAWING, RES_POOLCOLL_LABEL_ABB,\n \/\/ RES_POOLCOLL_LABEL_TABLE, RES_POOLCOLL_LABEL_FRAME\n \/\/ forth and back.\n \/\/ Non-matching names remain unchanged.\n SW_DLLPUBLIC static const String GetSpecialExtraProgName( const String& rExtraUIName );\n static const String GetSpecialExtraUIName( const String& rExtraProgName );\n\n static const SvStringsDtor& GetTextUINameArray();\n static const SvStringsDtor& GetListsUINameArray();\n static const SvStringsDtor& GetExtraUINameArray();\n static const SvStringsDtor& GetRegisterUINameArray();\n static const SvStringsDtor& GetDocUINameArray();\n static const SvStringsDtor& GetHTMLUINameArray();\n static const SvStringsDtor& GetFrmFmtUINameArray();\n static const SvStringsDtor& GetChrFmtUINameArray();\n static const SvStringsDtor& GetHTMLChrFmtUINameArray();\n static const SvStringsDtor& GetPageDescUINameArray();\n static const SvStringsDtor& GetNumRuleUINameArray();\n\n static const SvStringsDtor& GetTextProgNameArray();\n static const SvStringsDtor& GetListsProgNameArray();\n static const SvStringsDtor& GetExtraProgNameArray();\n static const SvStringsDtor& GetRegisterProgNameArray();\n static const SvStringsDtor& GetDocProgNameArray();\n static const SvStringsDtor& GetHTMLProgNameArray();\n static const SvStringsDtor& GetFrmFmtProgNameArray();\n static const SvStringsDtor& GetChrFmtProgNameArray();\n static const SvStringsDtor& GetHTMLChrFmtProgNameArray();\n static const SvStringsDtor& GetPageDescProgNameArray();\n static const SvStringsDtor& GetNumRuleProgNameArray();\n};\n#endif \/\/ _NAME_MAPPER_HXX\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\r\n#include \"error.h\"\r\n#include \"utils.h\"\r\n\r\nconst wstr msg_table[] = {\r\n\tL\"Could't open the file \\\"%1%\\\".\",\r\n\tL\"Couldn't open the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't create the file \\\"%1%\\\".\",\r\n\tL\"Couldn't create the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't delete the file \\\"%1%\\\".\",\r\n\tL\"Couldn't delete the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't get contents of the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't get information of the file \\\"%1%\\\".\",\r\n\tL\"Couldn't get extended attributes of the file or directory \\\"%1%\\\".\",\r\n\tL\"Couldn't set extended attributes of the file or directory \\\"%1%\\\".\",\r\n\tL\"Couldn't set the case sensitive attribute of the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't create the hard link from \\\"%1%\\\" to \\\"%2%\\\".\",\r\n\tL\"Couldn't read from the file \\\"%1%\\\".\",\r\n\tL\"Couldn't write to the file \\\"%1%\\\".\",\r\n\tL\"Couldn't recognize the path \\\"%1%\\\".\",\r\n\tL\"Couldn't convert a string from UTF-8 encoding to wide chars.\",\r\n\tL\"Error occurred while processing the archive.\",\r\n\tL\"Couldn't get Windows version information. \\\"%1%\\\"\",\r\n\tL\"Windows 10 v%1% (v10.0.%2%) or later is required. Please upgrade your system.\",\r\n\tL\"Couldn't open or create the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't delete the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't get subkeys of the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't copy the registry key \\\"%1%\\\" to \\\"%2%\\\".\",\r\n\tL\"Couldn't get the value \\\"%2%\\\" of the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't set the value \\\"%2%\\\" of the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't create a GUID.\",\r\n\tL\"Couldn't convert a GUID to a string.\",\r\n\tL\"Couldn't find the distro named \\\"%1%\\\".\",\r\n\tL\"A distro named \\\"%1%\\\" already exists.\",\r\n\tL\"No action is specified.\",\r\n\tL\"The action \\\"%1%\\\" is not recognized.\",\r\n\tL\"Couldn't load wslapi.dll. Please make sure that WSL has been installed.\",\r\n\tL\"Error occurred when trying to launch the distro \\\"%1%\\\".\",\r\n\tL\"Error occurred when creating a shortcut.\"\r\n};\r\n\r\nerr error_hresult(err_msg msg_code, const std::vector<wstr> &msg_args, HRESULT err_code) {\r\n\treturn err{ msg_code,msg_args,err_code };\r\n}\r\n\r\nerr error_win32(err_msg msg_code, const std::vector<wstr> &msg_args, uint32_t err_code) {\r\n\treturn error_hresult(msg_code, msg_args, HRESULT_FROM_WIN32(err_code));\r\n}\r\n\r\nerr error_win32_last(err_msg msg_code, const std::vector<wstr> &msg_args) {\r\n\treturn error_win32(msg_code, msg_args, GetLastError());\r\n}\r\n\r\nerr error_nt(err_msg msg_code, const std::vector<wstr> &msg_args, NTSTATUS err_code) {\r\n\treturn error_hresult(msg_code, msg_args, HRESULT_FROM_NT(err_code));\r\n}\r\n\r\nerr error_other(err_msg msg_code, const std::vector<wstr> &msg_args) {\r\n\treturn error_hresult(msg_code, msg_args, S_OK);\r\n}\r\n\r\nwstr err::format() const {\r\n\tstd::wstringstream ss;\r\n\r\n\tauto fmt = boost::wformat(msg_table[msg_code]);\r\n\tfor (const auto &s : msg_args) fmt = fmt % s;\r\n\tss << fmt << std::endl;\r\n\r\n\tif (err_code) {\r\n\t\tss << L\"Reason: \";\r\n\t\tif (err_code & FACILITY_NT_BIT) {\r\n\t\t\tauto stat = err_code & ~FACILITY_NT_BIT;\r\n\t\t\twchar_t *buf = nullptr;\r\n\t\t\tauto f = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS;\r\n\t\t\tauto hm = LoadLibrary(L\"ntdll.dll\");\r\n\t\t\tauto ok = hm && FormatMessage(f, hm, stat, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (wchar_t *)&buf, 0, nullptr);\r\n\t\t\tif (hm) FreeLibrary(hm);\r\n\t\t\tif (ok) {\r\n\t\t\t\tss << buf;\r\n\t\t\t\tLocalFree(buf);\r\n\t\t\t} else {\r\n\t\t\t\tss << L\"Unknown NTSTATUS: \" << L\"0x\" << std::setfill(L'0') << std::setw(8) << std::hex << stat;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t_com_error ce(err_code);\r\n\t\t\tss << ce.ErrorMessage();\r\n\t\t}\r\n\t}\r\n\r\n\treturn ss.str();\r\n}\r\n\r\nvoid err::push_if_empty(crwstr arg) {\r\n\tif (msg_args.empty()) msg_args.push_back(arg);\r\n}\r\n<commit_msg>fix typo Could't Couldn't<commit_after>#include \"stdafx.h\"\r\n#include \"error.h\"\r\n#include \"utils.h\"\r\n\r\nconst wstr msg_table[] = {\r\n\tL\"Couldn't open the file \\\"%1%\\\".\",\r\n\tL\"Couldn't open the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't create the file \\\"%1%\\\".\",\r\n\tL\"Couldn't create the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't delete the file \\\"%1%\\\".\",\r\n\tL\"Couldn't delete the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't get contents of the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't get information of the file \\\"%1%\\\".\",\r\n\tL\"Couldn't get extended attributes of the file or directory \\\"%1%\\\".\",\r\n\tL\"Couldn't set extended attributes of the file or directory \\\"%1%\\\".\",\r\n\tL\"Couldn't set the case sensitive attribute of the directory \\\"%1%\\\".\",\r\n\tL\"Couldn't create the hard link from \\\"%1%\\\" to \\\"%2%\\\".\",\r\n\tL\"Couldn't read from the file \\\"%1%\\\".\",\r\n\tL\"Couldn't write to the file \\\"%1%\\\".\",\r\n\tL\"Couldn't recognize the path \\\"%1%\\\".\",\r\n\tL\"Couldn't convert a string from UTF-8 encoding to wide chars.\",\r\n\tL\"Error occurred while processing the archive.\",\r\n\tL\"Couldn't get Windows version information. \\\"%1%\\\"\",\r\n\tL\"Windows 10 v%1% (v10.0.%2%) or later is required. Please upgrade your system.\",\r\n\tL\"Couldn't open or create the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't delete the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't get subkeys of the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't copy the registry key \\\"%1%\\\" to \\\"%2%\\\".\",\r\n\tL\"Couldn't get the value \\\"%2%\\\" of the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't set the value \\\"%2%\\\" of the registry key \\\"%1%\\\".\",\r\n\tL\"Couldn't create a GUID.\",\r\n\tL\"Couldn't convert a GUID to a string.\",\r\n\tL\"Couldn't find the distro named \\\"%1%\\\".\",\r\n\tL\"A distro named \\\"%1%\\\" already exists.\",\r\n\tL\"No action is specified.\",\r\n\tL\"The action \\\"%1%\\\" is not recognized.\",\r\n\tL\"Couldn't load wslapi.dll. Please make sure that WSL has been installed.\",\r\n\tL\"Error occurred when trying to launch the distro \\\"%1%\\\".\",\r\n\tL\"Error occurred when creating a shortcut.\"\r\n};\r\n\r\nerr error_hresult(err_msg msg_code, const std::vector<wstr> &msg_args, HRESULT err_code) {\r\n\treturn err{ msg_code,msg_args,err_code };\r\n}\r\n\r\nerr error_win32(err_msg msg_code, const std::vector<wstr> &msg_args, uint32_t err_code) {\r\n\treturn error_hresult(msg_code, msg_args, HRESULT_FROM_WIN32(err_code));\r\n}\r\n\r\nerr error_win32_last(err_msg msg_code, const std::vector<wstr> &msg_args) {\r\n\treturn error_win32(msg_code, msg_args, GetLastError());\r\n}\r\n\r\nerr error_nt(err_msg msg_code, const std::vector<wstr> &msg_args, NTSTATUS err_code) {\r\n\treturn error_hresult(msg_code, msg_args, HRESULT_FROM_NT(err_code));\r\n}\r\n\r\nerr error_other(err_msg msg_code, const std::vector<wstr> &msg_args) {\r\n\treturn error_hresult(msg_code, msg_args, S_OK);\r\n}\r\n\r\nwstr err::format() const {\r\n\tstd::wstringstream ss;\r\n\r\n\tauto fmt = boost::wformat(msg_table[msg_code]);\r\n\tfor (const auto &s : msg_args) fmt = fmt % s;\r\n\tss << fmt << std::endl;\r\n\r\n\tif (err_code) {\r\n\t\tss << L\"Reason: \";\r\n\t\tif (err_code & FACILITY_NT_BIT) {\r\n\t\t\tauto stat = err_code & ~FACILITY_NT_BIT;\r\n\t\t\twchar_t *buf = nullptr;\r\n\t\t\tauto f = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS;\r\n\t\t\tauto hm = LoadLibrary(L\"ntdll.dll\");\r\n\t\t\tauto ok = hm && FormatMessage(f, hm, stat, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (wchar_t *)&buf, 0, nullptr);\r\n\t\t\tif (hm) FreeLibrary(hm);\r\n\t\t\tif (ok) {\r\n\t\t\t\tss << buf;\r\n\t\t\t\tLocalFree(buf);\r\n\t\t\t} else {\r\n\t\t\t\tss << L\"Unknown NTSTATUS: \" << L\"0x\" << std::setfill(L'0') << std::setw(8) << std::hex << stat;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t_com_error ce(err_code);\r\n\t\t\tss << ce.ErrorMessage();\r\n\t\t}\r\n\t}\r\n\r\n\treturn ss.str();\r\n}\r\n\r\nvoid err::push_if_empty(crwstr arg) {\r\n\tif (msg_args.empty()) msg_args.push_back(arg);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: actctrl.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2004-11-16 17:00:00 $\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#ifndef _ACTCTRL_HXX\n#define _ACTCTRL_HXX\n\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\n\/*--------------------------------------------------------------------\n Beschreibung: numerische Eingabe\n --------------------------------------------------------------------*\/\n\nclass SW_DLLPUBLIC NumEditAction: public NumericField\n{\n Link aActionLink;\n\nprotected:\n virtual void Action();\n virtual long Notify( NotifyEvent& rNEvt );\npublic:\n NumEditAction( Window* pParent, const ResId& rResId ) :\n NumericField(pParent, rResId) {}\n\n void SetActionHdl( const Link& rLink ) { aActionLink = rLink;}\n const Link& GetActionHdl() const { return aActionLink; }\n};\n\n\n\/* -----------------21.04.98 08:11-------------------\n * Edit, dass keine Spaces akzeptiert\n * --------------------------------------------------*\/\nclass SW_DLLPUBLIC NoSpaceEdit : public Edit\n{\n String sForbiddenChars;\nprotected:\n virtual void KeyInput( const KeyEvent& );\n virtual void Modify();\n\npublic:\n NoSpaceEdit( Window* pParent, const ResId& rResId)\n : Edit(pParent, rResId),\n sForbiddenChars(String::CreateFromAscii(\" \"))\n {}\n void SetForbiddenChars(const String& rSet){sForbiddenChars = rSet;}\n const String& GetForbiddenChars(){return sForbiddenChars;}\n};\n\n\/* -----------------21.04.98 08:33-------------------\n * Kein Space und kein Punkt\n * --------------------------------------------------*\/\nclass TableNameEdit : public NoSpaceEdit\n{\npublic:\n TableNameEdit(Window* pWin, const ResId& rResId) :\n NoSpaceEdit(pWin, rResId)\n {SetForbiddenChars(String::CreateFromAscii(\" .<>\"));}\n};\n\/* -----------------25.06.2003 15:55-----------------\n call a link when KEY_RETURN is pressed\n --------------------------------------------------*\/\nclass SW_DLLPUBLIC ReturnActionEdit : public Edit\n{\n Link aReturnActionLink;\npublic:\n ReturnActionEdit( Window* pParent, const ResId& rResId)\n : Edit(pParent, rResId){}\n ~ReturnActionEdit();\n virtual void KeyInput( const KeyEvent& );\n\n void SetReturnActionLink(const Link& rLink)\n { aReturnActionLink = rLink;}\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.6.460); FILE MERGED 2005\/09\/05 13:44:55 rt 1.6.460.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: actctrl.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 08:58:09 $\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 _ACTCTRL_HXX\n#define _ACTCTRL_HXX\n\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\n\/*--------------------------------------------------------------------\n Beschreibung: numerische Eingabe\n --------------------------------------------------------------------*\/\n\nclass SW_DLLPUBLIC NumEditAction: public NumericField\n{\n Link aActionLink;\n\nprotected:\n virtual void Action();\n virtual long Notify( NotifyEvent& rNEvt );\npublic:\n NumEditAction( Window* pParent, const ResId& rResId ) :\n NumericField(pParent, rResId) {}\n\n void SetActionHdl( const Link& rLink ) { aActionLink = rLink;}\n const Link& GetActionHdl() const { return aActionLink; }\n};\n\n\n\/* -----------------21.04.98 08:11-------------------\n * Edit, dass keine Spaces akzeptiert\n * --------------------------------------------------*\/\nclass SW_DLLPUBLIC NoSpaceEdit : public Edit\n{\n String sForbiddenChars;\nprotected:\n virtual void KeyInput( const KeyEvent& );\n virtual void Modify();\n\npublic:\n NoSpaceEdit( Window* pParent, const ResId& rResId)\n : Edit(pParent, rResId),\n sForbiddenChars(String::CreateFromAscii(\" \"))\n {}\n void SetForbiddenChars(const String& rSet){sForbiddenChars = rSet;}\n const String& GetForbiddenChars(){return sForbiddenChars;}\n};\n\n\/* -----------------21.04.98 08:33-------------------\n * Kein Space und kein Punkt\n * --------------------------------------------------*\/\nclass TableNameEdit : public NoSpaceEdit\n{\npublic:\n TableNameEdit(Window* pWin, const ResId& rResId) :\n NoSpaceEdit(pWin, rResId)\n {SetForbiddenChars(String::CreateFromAscii(\" .<>\"));}\n};\n\/* -----------------25.06.2003 15:55-----------------\n call a link when KEY_RETURN is pressed\n --------------------------------------------------*\/\nclass SW_DLLPUBLIC ReturnActionEdit : public Edit\n{\n Link aReturnActionLink;\npublic:\n ReturnActionEdit( Window* pParent, const ResId& rResId)\n : Edit(pParent, rResId){}\n ~ReturnActionEdit();\n virtual void KeyInput( const KeyEvent& );\n\n void SetReturnActionLink(const Link& rLink)\n { aReturnActionLink = rLink;}\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Check compiling a module interface to a .pcm file.\n\/\/\n\/\/ RUN: %clang -fmodules-ts -x c++-module --precompile %s -Dimplementation= -o %t.pcm -v 2>&1 | FileCheck %s --check-prefix=CHECK-PRECOMPILE\n\/\/\n\/\/ CHECK-PRECOMPILE: -cc1 {{.*}} -emit-module-interface\n\/\/ CHECK-PRECOMPILE-SAME: -o {{.*}}.pcm\n\/\/ CHECK-PRECOMPILE-SAME: -x c++-module\n\/\/ CHECK-PRECOMPILE-SAME: modules-ts.cpp\n\n\/\/ Check compiling a .pcm file to a .o file.\n\/\/\n\/\/ RUN: %clang -fmodules-ts %t.pcm -c -o %t.pcm.o -v 2>&1 | FileCheck %s --check-prefix=CHECK-COMPILE\n\/\/\n\/\/ CHECK-COMPILE: -cc1 {{.*}} -emit-obj\n\/\/ CHECK-COMPILE-SAME: -o {{.*}}.pcm.o\n\/\/ CHECK-COMPILE-SAME: -x pcm\n\/\/ CHECK-COMPILE-SAME: {{.*}}.pcm\n\n\/\/ Check use of a .pcm file in another compilation.\n\/\/\n\/\/ RUN: %clang -fmodules-ts -fmodule-file=%t.pcm %s -c -o %t.o -v 2>&1 | FileCheck %s --check-prefix=CHECK-USE\n\/\/\n\/\/ CHECK-USE: -cc1\n\/\/ CHECK-USE-SAME: -emit-obj\n\/\/ CHECK-USE-SAME: -fmodule-file={{.*}}.pcm\n\/\/ CHECK-USE-SAME: -o {{.*}}.o {{.*}}-x c++\n\/\/ CHECK-USE-SAME: modules-ts.cpp\n\n\/\/ Check combining precompile and compile steps works.\n\/\/\n\/\/ RUN: %clang -fmodules-ts -x c++-module %s -Dimplementation= -c -o %t.pcm.o -v 2>&1 | FileCheck %s --check-prefix=CHECK-PRECOMPILE --check-prefix=CHECK-COMPILE\n\n\/\/ Check that .cppm is treated as a module implicitly.\n\/\/ RUN: cp %s %t.cppm\n\/\/ RUN: %clang -fmodules-ts --precompile %t.cppm -Dimplementation= -o %t.pcm -v 2>&1 | FileCheck %s --check-prefix=CHECK-PRECOMPILE\n\n\/\/ Note, we use -Dimplementation= to make this a valid module interface unit when building the interface.\nmodule implementation foo;\n<commit_msg>clang\/test\/Driver\/modules-ts.cpp: Satisfy quoted filename.<commit_after>\/\/ Check compiling a module interface to a .pcm file.\n\/\/\n\/\/ RUN: %clang -fmodules-ts -x c++-module --precompile %s -Dimplementation= -o %t.pcm -v 2>&1 | FileCheck %s --check-prefix=CHECK-PRECOMPILE\n\/\/\n\/\/ CHECK-PRECOMPILE: -cc1 {{.*}} -emit-module-interface\n\/\/ CHECK-PRECOMPILE-SAME: -o {{.*}}.pcm\n\/\/ CHECK-PRECOMPILE-SAME: -x c++-module\n\/\/ CHECK-PRECOMPILE-SAME: modules-ts.cpp\n\n\/\/ Check compiling a .pcm file to a .o file.\n\/\/\n\/\/ RUN: %clang -fmodules-ts %t.pcm -c -o %t.pcm.o -v 2>&1 | FileCheck %s --check-prefix=CHECK-COMPILE\n\/\/\n\/\/ CHECK-COMPILE: -cc1 {{.*}} -emit-obj\n\/\/ CHECK-COMPILE-SAME: -o {{.*}}.pcm.o\n\/\/ CHECK-COMPILE-SAME: -x pcm\n\/\/ CHECK-COMPILE-SAME: {{.*}}.pcm\n\n\/\/ Check use of a .pcm file in another compilation.\n\/\/\n\/\/ RUN: %clang -fmodules-ts -fmodule-file=%t.pcm %s -c -o %t.o -v 2>&1 | FileCheck %s --check-prefix=CHECK-USE\n\/\/\n\/\/ CHECK-USE: -cc1\n\/\/ CHECK-USE-SAME: -emit-obj\n\/\/ CHECK-USE-SAME: -fmodule-file={{.*}}.pcm\n\/\/ CHECK-USE-SAME: -o {{.*}}.o{{\"?}} {{.*}}-x c++\n\/\/ CHECK-USE-SAME: modules-ts.cpp\n\n\/\/ Check combining precompile and compile steps works.\n\/\/\n\/\/ RUN: %clang -fmodules-ts -x c++-module %s -Dimplementation= -c -o %t.pcm.o -v 2>&1 | FileCheck %s --check-prefix=CHECK-PRECOMPILE --check-prefix=CHECK-COMPILE\n\n\/\/ Check that .cppm is treated as a module implicitly.\n\/\/ RUN: cp %s %t.cppm\n\/\/ RUN: %clang -fmodules-ts --precompile %t.cppm -Dimplementation= -o %t.pcm -v 2>&1 | FileCheck %s --check-prefix=CHECK-PRECOMPILE\n\n\/\/ Note, we use -Dimplementation= to make this a valid module interface unit when building the interface.\nmodule implementation foo;\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: glosdoc.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2003-04-01 15:40:57 $\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#ifndef _GLOSDOC_HXX\n#define _GLOSDOC_HXX\n\n\n#ifndef _STRING_HXX \/\/autogen\n#include <tools\/string.hxx>\n#endif\n\n\n#ifndef _SVARRAY_HXX \/\/autogen\n#include <svtools\/svarray.hxx>\n#endif\n#ifndef _COM_SUN_STAR_TEXT_XAUTOTEXTGROUP_HPP_\n#include <com\/sun\/star\/text\/XAutoTextGroup.hpp>\n#endif\n\nclass SwTextBlocks;\nclass SvStrings;\nclass SwDocShell;\n\n#ifndef SW_DECL_SWDOCSHELL_DEFINED\n#define SW_DECL_SWDOCSHELL_DEFINED\n#ifndef _REF_HXX\n#include <tools\/ref.hxx>\n#endif\nSV_DECL_REF( SwDocShell )\n#endif\n\n#ifndef _CPPUHELPER_WEAKREF_HXX_\n#include <cppuhelper\/weakref.hxx>\n#endif\n\n#include <vector>\n\ntypedef ::com::sun::star::uno::WeakReference< ::com::sun::star::text::XAutoTextGroup > AutoTextGroupRef;\ntypedef ::std::vector< AutoTextGroupRef > UnoAutoTextGroups;\n\ntypedef ::com::sun::star::uno::Reference< ::com::sun::star::text::XAutoTextEntry > AutoTextEntryRef;\ntypedef ::std::vector< AutoTextEntryRef > UnoAutoTextEntries;\n\n#define GLOS_DELIM (sal_Unicode)'*'\n\n\/\/ CLASS -----------------------------------------------------------------\nclass SwGlossaries\n{\n UnoAutoTextGroups aGlossaryGroups;\n UnoAutoTextEntries aGlossaryEntries;\n String aPath;\n String sOldErrPath;\n String sErrPath;\n SvStrings *pPathArr;\n SvStrings *pGlosArr;\n BOOL bError;\n\n SwTextBlocks* GetGlosDoc(const String &rName, BOOL bCreate = TRUE) const;\n SvStrings *GetNameList();\n \/\/ implementation in unoatxt.cxx\n void RemoveFileFromList( const String& rGroup );\n void InvalidateUNOOjects();\n\npublic:\n SwGlossaries();\n ~SwGlossaries();\n\n \/** returns the cached AutoTextGroup (if any) for the given group name\n\n @precond\n If <arg>_bCreate<\/arg> is <TRUE\/>, the SolarMutex must be locked when calling into this method.\n\n @param _rGroupName\n the name of the glossaries group\n @param _bCreate\n if <TRUE\/>, the group is created if it does not yet exist\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::text::XAutoTextGroup >\n GetAutoTextGroup(\n const ::rtl::OUString& _rGroupName,\n bool _bCreate = false\n );\n\n \/** returns the cached AutoTextEntry (if any) for the given group\/with the given name\n\n @precond\n If <arg>_bCreate<\/arg> is <TRUE\/>, the SolarMutex must be locked when calling into this method.\n\n @param _rGroupAccessName\n the name to access the group\n @param _rGroupName\n the name of the glossaries group, as to be passed to the entry\n @param _rEntryName\n the name of the auto text entry\n @param _bCreate\n if <TRUE\/>, the entry is created if it does not yet exist\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::text::XAutoTextEntry >\n GetAutoTextEntry(\n const String& _rCompleteGroupName,\n const ::rtl::OUString& _rGroupName,\n const ::rtl::OUString& _rEntryName,\n bool _bCreate = false\n );\n\n USHORT GetGroupCnt();\n String GetGroupName(USHORT );\n String GetGroupTitle( const String& rGroupName );\n\n BOOL FindGroupName(String & rGroup);\n\n SwTextBlocks* GetGroupDoc(const String &rName,\n BOOL bCreate = FALSE) const;\n SwTextBlocks* GetDefGroupDoc() const {return GetGroupDoc(GetDefName());}\n void PutGroupDoc(SwTextBlocks *pBlock);\n static String GetDefName();\n static String GetExtension();\n\n BOOL NewGroupDoc(String &rGroupName, const String& rTitle);\n BOOL RenameGroupDoc(const String& sOldGroup, String& sNewGroup, const String& rNewTitle);\n BOOL DelGroupDoc(const String &);\n SwDocShellRef EditGroupDoc(const String &rGrpName, const String& rShortName, BOOL bShow = TRUE );\n void SaveGroupDoc(const String &rGrpName, const String& rLongName );\n void UpdateGlosPath(BOOL bFull);\n void ShowError();\n inline ULONG IsGlosPathErr() { return bError; }\n const SvStrings* GetPathArray() const {return pPathArr;}\n};\n\n\n#endif \/\/ _GLOSDOC_HXX\n<commit_msg>INTEGRATION: CWS tune03 (1.5.598); FILE MERGED 2004\/07\/19 19:11:27 mhu 1.5.598.1: #i29979# Added SW_DLLPUBLIC\/PRIVATE (see swdllapi.h) to exported symbols\/classes.<commit_after>\/*************************************************************************\n *\n * $RCSfile: glosdoc.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2004-08-23 08:59:15 $\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#ifndef _GLOSDOC_HXX\n#define _GLOSDOC_HXX\n\n#ifndef _STRING_HXX \/\/autogen\n#include <tools\/string.hxx>\n#endif\n#ifndef _SVARRAY_HXX \/\/autogen\n#include <svtools\/svarray.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_TEXT_XAUTOTEXTGROUP_HPP_\n#include <com\/sun\/star\/text\/XAutoTextGroup.hpp>\n#endif\n\nclass SwTextBlocks;\nclass SvStrings;\nclass SwDocShell;\n\n#ifndef SW_DECL_SWDOCSHELL_DEFINED\n#define SW_DECL_SWDOCSHELL_DEFINED\n#ifndef _REF_HXX\n#include <tools\/ref.hxx>\n#endif\nSV_DECL_REF( SwDocShell )\n#endif\n\n#ifndef _CPPUHELPER_WEAKREF_HXX_\n#include <cppuhelper\/weakref.hxx>\n#endif\n\n#ifndef INCLUDED_VECTOR\n#include <vector>\n#define INCLUDED_VECTOR\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\ntypedef ::com::sun::star::uno::WeakReference< ::com::sun::star::text::XAutoTextGroup > AutoTextGroupRef;\ntypedef ::std::vector< AutoTextGroupRef > UnoAutoTextGroups;\n\ntypedef ::com::sun::star::uno::Reference< ::com::sun::star::text::XAutoTextEntry > AutoTextEntryRef;\ntypedef ::std::vector< AutoTextEntryRef > UnoAutoTextEntries;\n\n#define GLOS_DELIM (sal_Unicode)'*'\n\n\/\/ CLASS -----------------------------------------------------------------\nclass SW_DLLPUBLIC SwGlossaries\n{\n UnoAutoTextGroups aGlossaryGroups;\n UnoAutoTextEntries aGlossaryEntries;\n String aPath;\n String sOldErrPath;\n String sErrPath;\n SvStrings *pPathArr;\n SvStrings *pGlosArr;\n BOOL bError;\n\n SW_DLLPRIVATE SwTextBlocks* GetGlosDoc(const String &rName, BOOL bCreate = TRUE) const;\n SW_DLLPRIVATE SvStrings *GetNameList();\n\n \/\/ implementation in unoatxt.cxx\n SW_DLLPRIVATE void RemoveFileFromList( const String& rGroup );\n SW_DLLPRIVATE void InvalidateUNOOjects();\n\npublic:\n SwGlossaries();\n ~SwGlossaries();\n\n \/** returns the cached AutoTextGroup (if any) for the given group name\n\n @precond\n If <arg>_bCreate<\/arg> is <TRUE\/>, the SolarMutex must be locked when calling into this method.\n\n @param _rGroupName\n the name of the glossaries group\n @param _bCreate\n if <TRUE\/>, the group is created if it does not yet exist\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::text::XAutoTextGroup >\n GetAutoTextGroup(\n const ::rtl::OUString& _rGroupName,\n bool _bCreate = false\n );\n\n \/** returns the cached AutoTextEntry (if any) for the given group\/with the given name\n\n @precond\n If <arg>_bCreate<\/arg> is <TRUE\/>, the SolarMutex must be locked when calling into this method.\n\n @param _rGroupAccessName\n the name to access the group\n @param _rGroupName\n the name of the glossaries group, as to be passed to the entry\n @param _rEntryName\n the name of the auto text entry\n @param _bCreate\n if <TRUE\/>, the entry is created if it does not yet exist\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::text::XAutoTextEntry >\n GetAutoTextEntry(\n const String& _rCompleteGroupName,\n const ::rtl::OUString& _rGroupName,\n const ::rtl::OUString& _rEntryName,\n bool _bCreate = false\n );\n\n USHORT GetGroupCnt();\n String GetGroupName(USHORT );\n String GetGroupTitle( const String& rGroupName );\n\n BOOL FindGroupName(String & rGroup);\n\n SwTextBlocks* GetGroupDoc(const String &rName,\n BOOL bCreate = FALSE) const;\n SwTextBlocks* GetDefGroupDoc() const {return GetGroupDoc(GetDefName());}\n void PutGroupDoc(SwTextBlocks *pBlock);\n static String GetDefName();\n static String GetExtension();\n\n BOOL NewGroupDoc(String &rGroupName, const String& rTitle);\n BOOL RenameGroupDoc(const String& sOldGroup, String& sNewGroup, const String& rNewTitle);\n BOOL DelGroupDoc(const String &);\n SwDocShellRef EditGroupDoc(const String &rGrpName, const String& rShortName, BOOL bShow = TRUE );\n void SaveGroupDoc(const String &rGrpName, const String& rLongName );\n void UpdateGlosPath(BOOL bFull);\n void ShowError();\n inline ULONG IsGlosPathErr() { return bError; }\n const SvStrings* GetPathArray() const {return pPathArr;}\n};\n\n\n#endif \/\/ _GLOSDOC_HXX\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: outline.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: vg $ $Date: 2007-10-22 15:21:26 $\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 _OUTLINE_HXX\n#define _OUTLINE_HXX\n\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include <sfx2\/tabdlg.hxx>\n#endif\n\n\n#ifndef _SV_MENU_HXX \/\/autogen\n#include <vcl\/menu.hxx>\n#endif\n\n#ifndef _BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n\n#ifndef _STDCTRL_HXX \/\/autogen\n#include <svtools\/stdctrl.hxx>\n#endif\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef _EDIT_HXX \/\/autogen\n#include <vcl\/edit.hxx>\n#endif\n\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\n#include \"swtypes.hxx\" \/\/fuer MAXLEVEL\n#ifndef _NUMPREVW_HXX\n#include <numprevw.hxx>\n#endif\n#ifndef _NUMBERINGTYPELISTBOX_HXX\n#include <numberingtypelistbox.hxx>\n#endif\n\nclass SwWrtShell;\nclass SwNumRule;\nclass SwChapterNumRules;\n\n\/* -----------------07.07.98 13:38-------------------\n *\n * --------------------------------------------------*\/\nclass SwOutlineTabDialog : public SfxTabDialog\n{\n static USHORT nNumLevel;\n\n String aNullStr;\n String aCollNames[MAXLEVEL];\n PopupMenu aFormMenu;\n\n SwWrtShell& rWrtSh;\n SwNumRule* pNumRule;\n SwChapterNumRules* pChapterNumRules;\n\n BOOL bModified : 1;\n\n protected:\n DECL_LINK( CancelHdl, Button * );\n DECL_LINK( FormHdl, Button * );\n DECL_LINK( MenuSelectHdl, Menu * );\n\n virtual void PageCreated(USHORT nPageId, SfxTabPage& rPage);\n virtual short Ok();\n\n public:\n SwOutlineTabDialog(Window* pParent,\n const SfxItemSet* pSwItemSet,\n SwWrtShell &);\n ~SwOutlineTabDialog();\n\n SwNumRule* GetNumRule() {return pNumRule;}\n USHORT GetLevel(const String &rFmtName) const;\n String* GetCollNames() {return aCollNames;}\n\n static USHORT GetActNumLevel() {return nNumLevel;}\n static void SetActNumLevel(USHORT nSet) {nNumLevel = nSet;}\n};\n\/* -----------------07.07.98 13:47-------------------\n *\n * --------------------------------------------------*\/\nclass SwOutlineSettingsTabPage : public SfxTabPage\n{\n ListBox aLevelLB;\n FixedLine aLevelFL;\n\n FixedText aCollLbl;\n ListBox aCollBox;\n FixedText aNumberLbl;\n SwNumberingTypeListBox aNumberBox;\n FixedText aCharFmtFT;\n ListBox aCharFmtLB;\n FixedText aAllLevelFT;\n NumericField aAllLevelNF;\n FixedText aDelim;\n FixedText aPrefixFT;\n Edit aPrefixED;\n FixedText aSuffixFT;\n Edit aSuffixED;\n FixedText aStartLbl;\n NumericField aStartEdit;\n FixedLine aNumberFL;\n NumberingPreview aPreviewWIN;\n\n String aNoFmtName;\n String aSaveCollNames[MAXLEVEL];\n SwWrtShell* pSh;\n SwNumRule* pNumRule;\n String* pCollNames;\n USHORT nActLevel;\n\n DECL_LINK( LevelHdl, ListBox * );\n DECL_LINK( ToggleComplete, NumericField * );\n DECL_LINK( CollSelect, ListBox * );\n DECL_LINK( CollSelectGetFocus, ListBox * );\n DECL_LINK( NumberSelect, SwNumberingTypeListBox * );\n DECL_LINK( DelimModify, Edit * );\n DECL_LINK( StartModified, NumericField * );\n DECL_LINK( CharFmtHdl, ListBox * );\n\n void Update();\n\n void SetModified(){aPreviewWIN.Invalidate();}\n void CheckForStartValue_Impl(sal_uInt16 nNumberingType);\n\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\npublic:\n SwOutlineSettingsTabPage(Window* pParent, const SfxItemSet& rSet);\n ~SwOutlineSettingsTabPage();\n\n void SetWrtShell(SwWrtShell* pShell);\n\n virtual void ActivatePage(const SfxItemSet& rSet);\n virtual int DeactivatePage(SfxItemSet *pSet);\n\n virtual BOOL FillItemSet( SfxItemSet& rSet );\n virtual void Reset( const SfxItemSet& rSet );\n static SfxTabPage* Create( Window* pParent,\n const SfxItemSet& rAttrSet);\n};\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.9.216); FILE MERGED 2008\/04\/01 15:59:18 thb 1.9.216.3: #i85898# Stripping all external header guards 2008\/04\/01 12:55:30 thb 1.9.216.2: #i85898# Stripping all external header guards 2008\/03\/31 16:58:37 rt 1.9.216.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: outline.hxx,v $\n * $Revision: 1.10 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _OUTLINE_HXX\n#define _OUTLINE_HXX\n\n#include <sfx2\/tabdlg.hxx>\n\n\n#include <vcl\/menu.hxx>\n\n#ifndef _BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#include <svtools\/stdctrl.hxx>\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef _EDIT_HXX \/\/autogen\n#include <vcl\/edit.hxx>\n#endif\n\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\n#include \"swtypes.hxx\" \/\/fuer MAXLEVEL\n#include <numprevw.hxx>\n#include <numberingtypelistbox.hxx>\n\nclass SwWrtShell;\nclass SwNumRule;\nclass SwChapterNumRules;\n\n\/* -----------------07.07.98 13:38-------------------\n *\n * --------------------------------------------------*\/\nclass SwOutlineTabDialog : public SfxTabDialog\n{\n static USHORT nNumLevel;\n\n String aNullStr;\n String aCollNames[MAXLEVEL];\n PopupMenu aFormMenu;\n\n SwWrtShell& rWrtSh;\n SwNumRule* pNumRule;\n SwChapterNumRules* pChapterNumRules;\n\n BOOL bModified : 1;\n\n protected:\n DECL_LINK( CancelHdl, Button * );\n DECL_LINK( FormHdl, Button * );\n DECL_LINK( MenuSelectHdl, Menu * );\n\n virtual void PageCreated(USHORT nPageId, SfxTabPage& rPage);\n virtual short Ok();\n\n public:\n SwOutlineTabDialog(Window* pParent,\n const SfxItemSet* pSwItemSet,\n SwWrtShell &);\n ~SwOutlineTabDialog();\n\n SwNumRule* GetNumRule() {return pNumRule;}\n USHORT GetLevel(const String &rFmtName) const;\n String* GetCollNames() {return aCollNames;}\n\n static USHORT GetActNumLevel() {return nNumLevel;}\n static void SetActNumLevel(USHORT nSet) {nNumLevel = nSet;}\n};\n\/* -----------------07.07.98 13:47-------------------\n *\n * --------------------------------------------------*\/\nclass SwOutlineSettingsTabPage : public SfxTabPage\n{\n ListBox aLevelLB;\n FixedLine aLevelFL;\n\n FixedText aCollLbl;\n ListBox aCollBox;\n FixedText aNumberLbl;\n SwNumberingTypeListBox aNumberBox;\n FixedText aCharFmtFT;\n ListBox aCharFmtLB;\n FixedText aAllLevelFT;\n NumericField aAllLevelNF;\n FixedText aDelim;\n FixedText aPrefixFT;\n Edit aPrefixED;\n FixedText aSuffixFT;\n Edit aSuffixED;\n FixedText aStartLbl;\n NumericField aStartEdit;\n FixedLine aNumberFL;\n NumberingPreview aPreviewWIN;\n\n String aNoFmtName;\n String aSaveCollNames[MAXLEVEL];\n SwWrtShell* pSh;\n SwNumRule* pNumRule;\n String* pCollNames;\n USHORT nActLevel;\n\n DECL_LINK( LevelHdl, ListBox * );\n DECL_LINK( ToggleComplete, NumericField * );\n DECL_LINK( CollSelect, ListBox * );\n DECL_LINK( CollSelectGetFocus, ListBox * );\n DECL_LINK( NumberSelect, SwNumberingTypeListBox * );\n DECL_LINK( DelimModify, Edit * );\n DECL_LINK( StartModified, NumericField * );\n DECL_LINK( CharFmtHdl, ListBox * );\n\n void Update();\n\n void SetModified(){aPreviewWIN.Invalidate();}\n void CheckForStartValue_Impl(sal_uInt16 nNumberingType);\n\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\npublic:\n SwOutlineSettingsTabPage(Window* pParent, const SfxItemSet& rSet);\n ~SwOutlineSettingsTabPage();\n\n void SetWrtShell(SwWrtShell* pShell);\n\n virtual void ActivatePage(const SfxItemSet& rSet);\n virtual int DeactivatePage(SfxItemSet *pSet);\n\n virtual BOOL FillItemSet( SfxItemSet& rSet );\n virtual void Reset( const SfxItemSet& rSet );\n static SfxTabPage* Create( Window* pParent,\n const SfxItemSet& rAttrSet);\n};\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n** Author: Zach Colbert\n** Date: 22 September 2017\n** Description: This program prints a message with your name in it.\n*********************************************************************\/\n\n#include <iostream>\n\/\/ using namespace std;\n\nint main()\n{\n std::cout << \"Hi! It\\'s me.\\n\";\n std::cout << \"I\\'m learning to program!\\n\";\n return 0;\n}\n<commit_msg>Reset the hello example to it's textbook form<commit_after>\/*********************************************************************\n** Author: Zach Colbert\n** Date: 22 September 2017\n** Description: This program prints a message with your name in it.\n*********************************************************************\/\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n cout << \"Hi! It\\'s me.\\n\";\n cout << \"I\\'m learning to program!\\n\";\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>increase default ground affordance size from 10 to 15<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n\n#include <BALL\/FORMAT\/molFileFactory.h>\n#include <BALL\/FORMAT\/genericMolFile.h>\n#include <BALL\/KERNEL\/system.h>\n#include <BALL\/FORMAT\/commandlineParser.h>\n\n#include \"version.h\";\n\nusing namespace BALL;\n\nint main(int argc, char* argv[])\n{\n\t\/\/ instantiate CommandlineParser object\n\tCommandlineParser parpars(\"MolecularFileConverter\", \"converts molecular file-formats\", VERSION, String(__DATE__), \"File conversion\");\n\tparpars.registerParameter(\"i\", \"input file\", INFILE, true);\n\tparpars.registerParameter(\"of\", \"output format\", STRING, false);\n\tparpars.registerParameter(\"o\", \"output file\", OUTFILE, true);\n\n\t\/\/ the available formats\n\tString supp_formats = MolFileFactory::getSupportedFormats();\n\n\t\/\/ the manual\n\tString man = String(\"This tool converts different molecular file formats.\\nSupported formats are \") + supp_formats + String(\".\");\n\n\t\/\/ we support: mol2, sdf, drf, pdb, ac, ent, brk, hin, mol, xyz, \n\t\/\/ mol2.gz, sdf.gz, drf.gz, pdb.gz, ac.gz, ent.gz, brk.gz, hin.gz, mol.gz, xyz.gz.\n\tparpars.setToolManual(man);\n\n\tparpars.setSupportedFormats(\"i\", supp_formats);\n\tparpars.setSupportedFormats(\"o\", supp_formats);\n\n\t\/\/ set supported formats as options for parameter of\n\tString formats = supp_formats;\n\tvector<String> temp;\n\tformats.split(temp,\",\");\n\tlist<String> supp_format_list;\n\tfor (Size i=0; i<temp.size(); i++)\n\t{\n\t\tsupp_format_list.push_back(temp[i]);\n\t}\n\tparpars.setParameterRestrictions(\"of\", supp_format_list);\n\n\t\/\/ parse the command line\n\tparpars.parse(argc, argv);\n\n\t\/\/ check if optional parameter 'of' is given\n\tString default_format = \"mol2\";\n\tif (parpars.has(\"of\"))\n\t\tdefault_format = parpars.get(\"of\");\n\n\t\/\/ read input\/output file\n\tGenericMolFile* in_file = MolFileFactory::open(parpars.get(\"i\"), std::ios::in);\n\tGenericMolFile* out_file = MolFileFactory::open(parpars.get(\"o\"), std::ios::out, default_format);\n\n\tif (!in_file)\n\t{\n\t\t\/\/ if file does not exist: complain and abort\n\t\tLog.error() << \"error opening \" << parpars.get(\"i\") << \" for input.\" << std::endl;\n\t\treturn 2;\n\t}\n\tif (!out_file)\n\t{\n\t\t\/\/ if file does not exist: complain and abort\n\t\tLog.error() << \"error opening \" << parpars.get(\"o\") << \" for output.\" << std::endl;\n\t\treturn 2;\n\t}\n\n\t\/\/ create a system and read the contents of the molecular file\n\tSystem S;\n\tin_file->read(S);\n\tin_file->close();\n\n\t\/\/ and write\n\tif (out_file)\n\t{\n\t\tout_file->write(S);\n\t\tout_file->close();\n\t\tLog.info() << \"Wrote converted file \" << parpars.get(\"o\") << std::endl;\n\t}\n\n\tdelete in_file;\n\tdelete out_file;\n}\n\n<commit_msg>Fix typo in MolecularFileConverter<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n\n#include <BALL\/FORMAT\/molFileFactory.h>\n#include <BALL\/FORMAT\/genericMolFile.h>\n#include <BALL\/KERNEL\/system.h>\n#include <BALL\/FORMAT\/commandlineParser.h>\n\n#include \"version.h\"\n\nusing namespace BALL;\n\nint main(int argc, char* argv[])\n{\n\t\/\/ instantiate CommandlineParser object\n\tCommandlineParser parpars(\"MolecularFileConverter\", \"converts molecular file-formats\", VERSION, String(__DATE__), \"File conversion\");\n\tparpars.registerParameter(\"i\", \"input file\", INFILE, true);\n\tparpars.registerParameter(\"of\", \"output format\", STRING, false);\n\tparpars.registerParameter(\"o\", \"output file\", OUTFILE, true);\n\n\t\/\/ the available formats\n\tString supp_formats = MolFileFactory::getSupportedFormats();\n\n\t\/\/ the manual\n\tString man = String(\"This tool converts different molecular file formats.\\nSupported formats are \") + supp_formats + String(\".\");\n\n\t\/\/ we support: mol2, sdf, drf, pdb, ac, ent, brk, hin, mol, xyz, \n\t\/\/ mol2.gz, sdf.gz, drf.gz, pdb.gz, ac.gz, ent.gz, brk.gz, hin.gz, mol.gz, xyz.gz.\n\tparpars.setToolManual(man);\n\n\tparpars.setSupportedFormats(\"i\", supp_formats);\n\tparpars.setSupportedFormats(\"o\", supp_formats);\n\n\t\/\/ set supported formats as options for parameter of\n\tString formats = supp_formats;\n\tvector<String> temp;\n\tformats.split(temp,\",\");\n\tlist<String> supp_format_list;\n\tfor (Size i=0; i<temp.size(); i++)\n\t{\n\t\tsupp_format_list.push_back(temp[i]);\n\t}\n\tparpars.setParameterRestrictions(\"of\", supp_format_list);\n\n\t\/\/ parse the command line\n\tparpars.parse(argc, argv);\n\n\t\/\/ check if optional parameter 'of' is given\n\tString default_format = \"mol2\";\n\tif (parpars.has(\"of\"))\n\t\tdefault_format = parpars.get(\"of\");\n\n\t\/\/ read input\/output file\n\tGenericMolFile* in_file = MolFileFactory::open(parpars.get(\"i\"), std::ios::in);\n\tGenericMolFile* out_file = MolFileFactory::open(parpars.get(\"o\"), std::ios::out, default_format);\n\n\tif (!in_file)\n\t{\n\t\t\/\/ if file does not exist: complain and abort\n\t\tLog.error() << \"error opening \" << parpars.get(\"i\") << \" for input.\" << std::endl;\n\t\texit(2);\n\t}\n\tif (!out_file)\n\t{\n\t\t\/\/ if file does not exist: complain and abort\n\t\tLog.error() << \"error opening \" << parpars.get(\"o\") << \" for output.\" << std::endl;\n\t\texit(2);\n\t}\n\n\t\/\/ create a system and read the contents of the molecular file\n\tSystem S;\n\tin_file->read(S);\n\tin_file->close();\n\n\t\/\/ and write\n\tif (out_file)\n\t{\n\t\tout_file->write(S);\n\t\tout_file->close();\n\t\tLog.info() << \"Wrote converted file \" << parpars.get(\"o\") << std::endl;\n\t}\n\n\tdelete in_file;\n\tdelete out_file;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2022 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\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 *\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\n * distribution.\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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"http\/CookieExtract.hxx\"\n\n#include <gtest\/gtest.h>\n\nusing std::string_view_literals::operator\"\"sv;\n\nTEST(CookieExtract, Basic)\n{\n\tconstexpr auto input = \"a=b\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"c\").data(), nullptr);\n\tASSERT_EQ(ExtractCookieRaw(input, \"a\"), \"b\"sv);\n}\n\nTEST(CookieExtract, Basic2)\n{\n\tconstexpr auto input = \"c=d;e=f\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"c\"), \"d\"sv);\n\tASSERT_EQ(ExtractCookieRaw(input, \"e\"), \"f\"sv);\n}\n\nTEST(CookieExtract, Quoted)\n{\n\tconstexpr auto input = \"quoted=\\\"quoted!\\\\\\\\\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"quoted\"), \"quoted!\\\\\\\\\");\n}\n\nTEST(CookieExtract, Invalid1)\n{\n\tconstexpr auto input = \"invalid1=foo\\t\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"invalid1\"), \"foo\");\n}\n\nTEST(CookieExtract, Invalid2)\n{\n\t\/* this is actually invalid, but unfortunately RFC ignorance is\n\t viral, and forces us to accept square brackets :-( *\/\n\tconstexpr auto input = \"invalid2=foo |[bar] ,\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"invalid2\"), \"foo |[bar] ,\");\n}\n<commit_msg>test\/TestCookieExtract: add another \"quoted\" test<commit_after>\/*\n * Copyright 2007-2022 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\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 *\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\n * distribution.\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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"http\/CookieExtract.hxx\"\n\n#include <gtest\/gtest.h>\n\nusing std::string_view_literals::operator\"\"sv;\n\nTEST(CookieExtract, Basic)\n{\n\tconstexpr auto input = \"a=b\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"c\").data(), nullptr);\n\tASSERT_EQ(ExtractCookieRaw(input, \"a\"), \"b\"sv);\n}\n\nTEST(CookieExtract, Basic2)\n{\n\tconstexpr auto input = \"c=d;e=f\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"c\"), \"d\"sv);\n\tASSERT_EQ(ExtractCookieRaw(input, \"e\"), \"f\"sv);\n}\n\nTEST(CookieExtract, Quoted)\n{\n\tconstexpr auto input = \"quoted=\\\"quoted!\\\\\\\\\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"quoted\"), \"quoted!\\\\\\\\\");\n}\n\nTEST(CookieExtract, Quoted2)\n{\n\tconstexpr auto input = \"quoted=\\\"quoted!\\\\\\\\\\\"\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"quoted\"), \"quoted!\\\\\\\\\");\n}\n\nTEST(CookieExtract, Invalid1)\n{\n\tconstexpr auto input = \"invalid1=foo\\t\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"invalid1\"), \"foo\");\n}\n\nTEST(CookieExtract, Invalid2)\n{\n\t\/* this is actually invalid, but unfortunately RFC ignorance is\n\t viral, and forces us to accept square brackets :-( *\/\n\tconstexpr auto input = \"invalid2=foo |[bar] ,\"sv;\n\tASSERT_EQ(ExtractCookieRaw(input, \"invalid2\"), \"foo |[bar] ,\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlproject.h\"\n#include \"qmlprojectmanagerconstants.h\"\n#include \"qmlprojectrunconfiguration.h\"\n#include \"qmlprojecttarget.h\"\n\n#include <coreplugin\/editormanager\/editormanager.h>\n#include <coreplugin\/editormanager\/ieditor.h>\n#include <coreplugin\/icore.h>\n#include <coreplugin\/ifile.h>\n#include <utils\/synchronousprocess.h>\n#include <utils\/pathchooser.h>\n\n#include <QFormLayout>\n#include <QComboBox>\n#include <QCoreApplication>\n#include <QLineEdit>\n#include <QSpinBox>\n\nnamespace QmlProjectManager {\n\nQmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent) :\n ProjectExplorer::RunConfiguration(parent, QLatin1String(Constants::QML_RC_ID)),\n m_debugServerAddress(\"127.0.0.1\"),\n m_debugServerPort(Constants::QML_DEFAULT_DEBUG_SERVER_PORT)\n{\n ctor();\n}\n\nQmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent, QmlProjectRunConfiguration *source) :\n ProjectExplorer::RunConfiguration(parent, source),\n m_scriptFile(source->m_scriptFile),\n m_qmlViewerCustomPath(source->m_qmlViewerCustomPath),\n m_qmlViewerArgs(source->m_qmlViewerArgs),\n m_debugServerAddress(source->m_debugServerAddress),\n m_debugServerPort(source->m_debugServerPort)\n{\n ctor();\n}\n\nvoid QmlProjectRunConfiguration::ctor()\n{\n setDisplayName(tr(\"QML Viewer\", \"QMLRunConfiguration display name.\"));\n\n \/\/ prepend creator\/bin dir to search path (only useful for special creator-qml package)\n const QString searchPath = QCoreApplication::applicationDirPath()\n + Utils::SynchronousProcess::pathSeparator()\n + QString(qgetenv(\"PATH\"));\n m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String(\"qmlviewer\"));\n}\n\nQmlProjectRunConfiguration::~QmlProjectRunConfiguration()\n{\n}\n\nQString QmlProjectRunConfiguration::debugServerAddress() const\n{\n return m_debugServerAddress;\n}\n\nInternal::QmlProjectTarget *QmlProjectRunConfiguration::qmlTarget() const\n{\n return static_cast<Internal::QmlProjectTarget *>(target());\n}\n\nQString QmlProjectRunConfiguration::viewerPath() const\n{\n if (!m_qmlViewerCustomPath.isEmpty())\n return m_qmlViewerCustomPath;\n return m_qmlViewerDefaultPath;\n}\n\nQStringList QmlProjectRunConfiguration::viewerArguments() const\n{\n QStringList args;\n\n \/\/ arguments in .user file\n if (!m_qmlViewerArgs.isEmpty())\n args.append(m_qmlViewerArgs);\n\n \/\/ arguments from .qmlproject file\n foreach (const QString &libraryPath, qmlTarget()->qmlProject()->libraryPaths()) {\n args.append(QLatin1String(\"-L\"));\n args.append(libraryPath);\n }\n\n const QString s = mainScript();\n if (! s.isEmpty())\n args.append(s);\n return args;\n}\n\nQString QmlProjectRunConfiguration::workingDirectory() const\n{\n QFileInfo projectFile(qmlTarget()->qmlProject()->file()->fileName());\n return projectFile.absolutePath();\n}\n\nuint QmlProjectRunConfiguration::debugServerPort() const\n{\n return m_debugServerPort;\n}\n\nQWidget *QmlProjectRunConfiguration::configurationWidget()\n{\n QWidget *config = new QWidget;\n QFormLayout *form = new QFormLayout(config);\n\n QComboBox *combo = new QComboBox;\n\n QDir projectDir = qmlTarget()->qmlProject()->projectDir();\n QStringList files;\n\n files.append(tr(\"<Current File>\"));\n\n int currentIndex = -1;\n\n foreach (const QString &fn, qmlTarget()->qmlProject()->files()) {\n QFileInfo fileInfo(fn);\n if (fileInfo.suffix() != QLatin1String(\"qml\"))\n continue;\n\n QString fileName = projectDir.relativeFilePath(fn);\n if (fileName == m_scriptFile)\n currentIndex = files.size();\n\n files.append(fileName);\n }\n\n combo->addItems(files);\n if (currentIndex != -1)\n combo->setCurrentIndex(currentIndex);\n\n connect(combo, SIGNAL(activated(QString)), this, SLOT(setMainScript(QString)));\n\n Utils::PathChooser *qmlViewer = new Utils::PathChooser;\n qmlViewer->setExpectedKind(Utils::PathChooser::Command);\n qmlViewer->setPath(viewerPath());\n connect(qmlViewer, SIGNAL(changed(QString)), this, SLOT(onQmlViewerChanged()));\n\n QLineEdit *qmlViewerArgs = new QLineEdit;\n qmlViewerArgs->setText(m_qmlViewerArgs);\n connect(qmlViewerArgs, SIGNAL(textChanged(QString)), this, SLOT(onQmlViewerArgsChanged()));\n\n QLineEdit *debugServer = new QLineEdit;\n debugServer->setText(m_debugServerAddress);\n connect(debugServer, SIGNAL(textChanged(QString)), this, SLOT(onDebugServerAddressChanged()));\n\n QSpinBox *debugPort = new QSpinBox;\n debugPort->setMinimum(1024); \/\/ valid registered\/dynamic\/free ports according to http:\/\/www.iana.org\/assignments\/port-numbers\n debugPort->setMaximum(65535);\n debugPort->setValue(m_debugServerPort);\n connect(debugPort, SIGNAL(valueChanged(int)), this, SLOT(onDebugServerPortChanged()));\n\n form->addRow(tr(\"QML Viewer\"), qmlViewer);\n form->addRow(tr(\"QML Viewer arguments:\"), qmlViewerArgs);\n form->addRow(tr(\"Main QML File:\"), combo);\n form->addRow(tr(\"Debugging Address:\"), debugServer);\n form->addRow(tr(\"Debugging Port:\"), debugPort);\n\n return config;\n}\n\nQString QmlProjectRunConfiguration::mainScript() const\n{\n if (m_scriptFile.isEmpty() || m_scriptFile == tr(\"<Current File>\")) {\n Core::EditorManager *editorManager = Core::ICore::instance()->editorManager();\n if (Core::IEditor *editor = editorManager->currentEditor()) {\n return editor->file()->fileName();\n }\n }\n\n return qmlTarget()->qmlProject()->projectDir().absoluteFilePath(m_scriptFile);\n}\n\nvoid QmlProjectRunConfiguration::setMainScript(const QString &scriptFile)\n{\n m_scriptFile = scriptFile;\n}\n\nvoid QmlProjectRunConfiguration::onQmlViewerChanged()\n{\n if (Utils::PathChooser *chooser = qobject_cast<Utils::PathChooser *>(sender())) {\n m_qmlViewerCustomPath = chooser->path();\n }\n}\n\nvoid QmlProjectRunConfiguration::onQmlViewerArgsChanged()\n{\n if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender()))\n m_qmlViewerArgs = lineEdit->text();\n}\n\nvoid QmlProjectRunConfiguration::onDebugServerPortChanged()\n{\n if (QSpinBox *spinBox = qobject_cast<QSpinBox*>(sender())) {\n m_debugServerPort = spinBox->value();\n }\n}\n\nQVariantMap QmlProjectRunConfiguration::toMap() const\n{\n QVariantMap map(ProjectExplorer::RunConfiguration::toMap());\n\n map.insert(QLatin1String(Constants::QML_VIEWER_KEY), m_qmlViewerCustomPath);\n map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs);\n map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY), m_scriptFile);\n map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), m_debugServerPort);\n return map;\n}\n\nbool QmlProjectRunConfiguration::fromMap(const QVariantMap &map)\n{\n m_qmlViewerCustomPath = map.value(QLatin1String(Constants::QML_VIEWER_KEY)).toString();\n m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString();\n m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), tr(\"<Current File>\")).toString();\n m_debugServerPort = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), Constants::QML_DEFAULT_DEBUG_SERVER_PORT).toUInt();\n\n return RunConfiguration::fromMap(map);\n}\n\n} \/\/ namespace QmlProjectManager\n<commit_msg>Added a missing slot implementation for server address change<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlproject.h\"\n#include \"qmlprojectmanagerconstants.h\"\n#include \"qmlprojectrunconfiguration.h\"\n#include \"qmlprojecttarget.h\"\n\n#include <coreplugin\/editormanager\/editormanager.h>\n#include <coreplugin\/editormanager\/ieditor.h>\n#include <coreplugin\/icore.h>\n#include <coreplugin\/ifile.h>\n#include <utils\/synchronousprocess.h>\n#include <utils\/pathchooser.h>\n\n#include <QFormLayout>\n#include <QComboBox>\n#include <QCoreApplication>\n#include <QLineEdit>\n#include <QSpinBox>\n\nnamespace QmlProjectManager {\n\nQmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent) :\n ProjectExplorer::RunConfiguration(parent, QLatin1String(Constants::QML_RC_ID)),\n m_debugServerAddress(\"127.0.0.1\"),\n m_debugServerPort(Constants::QML_DEFAULT_DEBUG_SERVER_PORT)\n{\n ctor();\n}\n\nQmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent, QmlProjectRunConfiguration *source) :\n ProjectExplorer::RunConfiguration(parent, source),\n m_scriptFile(source->m_scriptFile),\n m_qmlViewerCustomPath(source->m_qmlViewerCustomPath),\n m_qmlViewerArgs(source->m_qmlViewerArgs),\n m_debugServerAddress(source->m_debugServerAddress),\n m_debugServerPort(source->m_debugServerPort)\n{\n ctor();\n}\n\nvoid QmlProjectRunConfiguration::ctor()\n{\n setDisplayName(tr(\"QML Viewer\", \"QMLRunConfiguration display name.\"));\n\n \/\/ prepend creator\/bin dir to search path (only useful for special creator-qml package)\n const QString searchPath = QCoreApplication::applicationDirPath()\n + Utils::SynchronousProcess::pathSeparator()\n + QString(qgetenv(\"PATH\"));\n m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String(\"qmlviewer\"));\n}\n\nQmlProjectRunConfiguration::~QmlProjectRunConfiguration()\n{\n}\n\nQString QmlProjectRunConfiguration::debugServerAddress() const\n{\n return m_debugServerAddress;\n}\n\nInternal::QmlProjectTarget *QmlProjectRunConfiguration::qmlTarget() const\n{\n return static_cast<Internal::QmlProjectTarget *>(target());\n}\n\nQString QmlProjectRunConfiguration::viewerPath() const\n{\n if (!m_qmlViewerCustomPath.isEmpty())\n return m_qmlViewerCustomPath;\n return m_qmlViewerDefaultPath;\n}\n\nQStringList QmlProjectRunConfiguration::viewerArguments() const\n{\n QStringList args;\n\n \/\/ arguments in .user file\n if (!m_qmlViewerArgs.isEmpty())\n args.append(m_qmlViewerArgs);\n\n \/\/ arguments from .qmlproject file\n foreach (const QString &libraryPath, qmlTarget()->qmlProject()->libraryPaths()) {\n args.append(QLatin1String(\"-L\"));\n args.append(libraryPath);\n }\n\n const QString s = mainScript();\n if (! s.isEmpty())\n args.append(s);\n return args;\n}\n\nQString QmlProjectRunConfiguration::workingDirectory() const\n{\n QFileInfo projectFile(qmlTarget()->qmlProject()->file()->fileName());\n return projectFile.absolutePath();\n}\n\nuint QmlProjectRunConfiguration::debugServerPort() const\n{\n return m_debugServerPort;\n}\n\nQWidget *QmlProjectRunConfiguration::configurationWidget()\n{\n QWidget *config = new QWidget;\n QFormLayout *form = new QFormLayout(config);\n\n QComboBox *combo = new QComboBox;\n\n QDir projectDir = qmlTarget()->qmlProject()->projectDir();\n QStringList files;\n\n files.append(tr(\"<Current File>\"));\n\n int currentIndex = -1;\n\n foreach (const QString &fn, qmlTarget()->qmlProject()->files()) {\n QFileInfo fileInfo(fn);\n if (fileInfo.suffix() != QLatin1String(\"qml\"))\n continue;\n\n QString fileName = projectDir.relativeFilePath(fn);\n if (fileName == m_scriptFile)\n currentIndex = files.size();\n\n files.append(fileName);\n }\n\n combo->addItems(files);\n if (currentIndex != -1)\n combo->setCurrentIndex(currentIndex);\n\n connect(combo, SIGNAL(activated(QString)), this, SLOT(setMainScript(QString)));\n\n Utils::PathChooser *qmlViewer = new Utils::PathChooser;\n qmlViewer->setExpectedKind(Utils::PathChooser::Command);\n qmlViewer->setPath(viewerPath());\n connect(qmlViewer, SIGNAL(changed(QString)), this, SLOT(onQmlViewerChanged()));\n\n QLineEdit *qmlViewerArgs = new QLineEdit;\n qmlViewerArgs->setText(m_qmlViewerArgs);\n connect(qmlViewerArgs, SIGNAL(textChanged(QString)), this, SLOT(onQmlViewerArgsChanged()));\n\n QLineEdit *debugServer = new QLineEdit;\n debugServer->setText(m_debugServerAddress);\n connect(debugServer, SIGNAL(textChanged(QString)), this, SLOT(onDebugServerAddressChanged()));\n\n QSpinBox *debugPort = new QSpinBox;\n debugPort->setMinimum(1024); \/\/ valid registered\/dynamic\/free ports according to http:\/\/www.iana.org\/assignments\/port-numbers\n debugPort->setMaximum(65535);\n debugPort->setValue(m_debugServerPort);\n connect(debugPort, SIGNAL(valueChanged(int)), this, SLOT(onDebugServerPortChanged()));\n\n form->addRow(tr(\"QML Viewer\"), qmlViewer);\n form->addRow(tr(\"QML Viewer arguments:\"), qmlViewerArgs);\n form->addRow(tr(\"Main QML File:\"), combo);\n form->addRow(tr(\"Debugging Address:\"), debugServer);\n form->addRow(tr(\"Debugging Port:\"), debugPort);\n\n return config;\n}\n\nQString QmlProjectRunConfiguration::mainScript() const\n{\n if (m_scriptFile.isEmpty() || m_scriptFile == tr(\"<Current File>\")) {\n Core::EditorManager *editorManager = Core::ICore::instance()->editorManager();\n if (Core::IEditor *editor = editorManager->currentEditor()) {\n return editor->file()->fileName();\n }\n }\n\n return qmlTarget()->qmlProject()->projectDir().absoluteFilePath(m_scriptFile);\n}\n\nvoid QmlProjectRunConfiguration::onDebugServerAddressChanged()\n{\n if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender()))\n m_debugServerAddress = lineEdit->text();\n}\n\nvoid QmlProjectRunConfiguration::setMainScript(const QString &scriptFile)\n{\n m_scriptFile = scriptFile;\n}\n\nvoid QmlProjectRunConfiguration::onQmlViewerChanged()\n{\n if (Utils::PathChooser *chooser = qobject_cast<Utils::PathChooser *>(sender())) {\n m_qmlViewerCustomPath = chooser->path();\n }\n}\n\nvoid QmlProjectRunConfiguration::onQmlViewerArgsChanged()\n{\n if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender()))\n m_qmlViewerArgs = lineEdit->text();\n}\n\nvoid QmlProjectRunConfiguration::onDebugServerPortChanged()\n{\n if (QSpinBox *spinBox = qobject_cast<QSpinBox*>(sender())) {\n m_debugServerPort = spinBox->value();\n }\n}\n\nQVariantMap QmlProjectRunConfiguration::toMap() const\n{\n QVariantMap map(ProjectExplorer::RunConfiguration::toMap());\n\n map.insert(QLatin1String(Constants::QML_VIEWER_KEY), m_qmlViewerCustomPath);\n map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs);\n map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY), m_scriptFile);\n map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), m_debugServerPort);\n return map;\n}\n\nbool QmlProjectRunConfiguration::fromMap(const QVariantMap &map)\n{\n m_qmlViewerCustomPath = map.value(QLatin1String(Constants::QML_VIEWER_KEY)).toString();\n m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString();\n m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), tr(\"<Current File>\")).toString();\n m_debugServerPort = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), Constants::QML_DEFAULT_DEBUG_SERVER_PORT).toUInt();\n\n return RunConfiguration::fromMap(map);\n}\n\n} \/\/ namespace QmlProjectManager\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright (C) 2014 Aldebaran\n*\/\n#include <qi\/application.hpp>\n#include <qi\/future.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/foreach.hpp>\n#include <qi\/os.hpp>\n#include <qi\/strand.hpp>\n#include <qi\/periodictask.hpp>\n#include <qi\/actor.hpp>\n#include <qi\/log.hpp>\n#include <qi\/anyobject.hpp>\n#include <qi\/type\/dynamicobjectbuilder.hpp>\n#include <gtest\/gtest.h>\n\nqiLogCategory(\"test\");\n\nvoid setValueWait(boost::mutex& mutex, int waittime, int& i, int v)\n{\n boost::unique_lock<boost::mutex> lock(mutex, boost::try_to_lock);\n \/\/ we should never be called in parallel\n ASSERT_TRUE(lock.owns_lock());\n if (waittime)\n qi::os::msleep(waittime);\n i = v;\n}\n\nTEST(TestStrand, StrandSimple)\n{\n boost::mutex mutex;\n\n qi::Strand strand(*qi::getEventLoop());\n int i = 0;\n qi::Future<void> f1 = strand.async(boost::bind<void>(&setValueWait,\n boost::ref(mutex), 100, boost::ref(i), 1));\n qi::os::msleep(5);\n EXPECT_FALSE(f1.isFinished());\n qi::Future<void> f2 = strand.async(boost::bind<void>(&setValueWait,\n boost::ref(mutex), 0, boost::ref(i), 2));\n qi::os::msleep(200);\n EXPECT_EQ(i, 2);\n}\n\nstatic void fail()\n{\n ASSERT_TRUE(false);\n}\n\nTEST(TestStrand, StrandCancel)\n{\n qi::Strand strand(*qi::getEventLoop());\n \/\/ cancel before scheduling\n qi::Future<void> f1 = strand.asyncDelay(fail, qi::Seconds(1000));\n f1.cancel();\n ASSERT_EQ(qi::FutureState_Canceled, f1.wait());\n}\n\nTEST(TestStrand, StrandCancelScheduled)\n{\n qi::Strand strand(*qi::getEventLoop());\n \/\/ cancel before scheduling\n qi::Future<void> f1 = strand.async(boost::bind(qi::os::msleep, 100));\n qi::Future<void> f2 = strand.async(fail);\n qi::os::msleep(30);\n f2.cancel();\n ASSERT_EQ(qi::FutureState_FinishedWithValue, f1.wait()) << f1.error();\n ASSERT_EQ(qi::FutureState_Canceled, f2.wait());\n}\n\nstatic void increment(boost::mutex& mutex, int waittime, boost::atomic<unsigned int>& i)\n{\n boost::unique_lock<boost::mutex> lock(mutex, boost::try_to_lock);\n \/\/ we should never be called in parallel\n ASSERT_TRUE(lock.owns_lock());\n if (waittime)\n qi::os::msleep(waittime);\n ++i;\n}\n\nstatic const unsigned int STRAND_NB_TRIES = 100;\n\nTEST(TestStrand, AggressiveCancel)\n{\n boost::mutex mutex;\n std::vector<qi::Future<void> > futures;\n\n qi::Strand strand(*qi::getEventLoop());\n boost::atomic<unsigned int> i(0);\n for (unsigned int j = 0; j < STRAND_NB_TRIES; ++j)\n {\n qi::Future<void> f1 = strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n futures.push_back(f1);\n f1 = strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 50, boost::ref(i)));\n futures.push_back(f1);\n }\n BOOST_FOREACH(qi::Future<void>& future, futures)\n future.cancel();\n\n unsigned int successCount = 0;\n BOOST_FOREACH(qi::Future<void>& future, futures)\n {\n if (future.wait() != qi::FutureState_Canceled)\n successCount++;\n }\n if (i == futures.size() || i == 0)\n qiLogWarning() << \"i = \" << i <<\n \", this test is meaningless, you should do something about that\";\n ASSERT_EQ(successCount, i);\n}\n\nTEST(TestStrand, StrandDestruction)\n{\n boost::mutex mutex;\n boost::atomic<unsigned int> i(0);\n\n std::vector<qi::Future<void>> futures;\n {\n qi::Strand strand(*qi::getEventLoop());\n futures.reserve(STRAND_NB_TRIES);\n for (unsigned int j = 0; j < STRAND_NB_TRIES; ++j)\n {\n futures.push_back(strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i))));\n }\n }\n for (auto& future : futures)\n ASSERT_TRUE(future.isFinished());\n}\n\nTEST(TestStrand, StrandDestructionWithMethodAndConcurrency)\n{\n \/\/ ASSERT_NOSEGFAULT_NOCRASH_NOBADTHINGS();\n boost::mutex mutex;\n boost::atomic<unsigned int> i(0);\n\n std::vector<qi::Future<void>> futures;\n qi::Strand strand(*qi::getEventLoop());\n futures.reserve(STRAND_NB_TRIES);\n for (unsigned int j = 0; j < STRAND_NB_TRIES\/4; ++j)\n futures.push_back(qi::getEventLoop()->async([&]{\n strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n }));\n for (unsigned int j = 0; j < STRAND_NB_TRIES\/4; ++j)\n strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n strand.join();\n for (unsigned int j = 0; j < STRAND_NB_TRIES\/4; ++j)\n futures.push_back(qi::getEventLoop()->async([&]{\n strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n }));\n for (unsigned int j = 0; j < STRAND_NB_TRIES\/4; ++j)\n strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n for (auto& future : futures)\n ASSERT_TRUE(future.wait());\n}\n\nTEST(TestStrand, StrandDestructionWithCancel)\n{\n boost::mutex mutex;\n std::vector<qi::Future<void> > futures;\n boost::atomic<unsigned int> i(0);\n\n {\n qi::Strand strand(*qi::getEventLoop());\n for (unsigned int j = 0; j < STRAND_NB_TRIES; ++j)\n {\n qi::Future<void> f1 = strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n futures.push_back(f1);\n f1 = strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 50, boost::ref(i)));\n futures.push_back(f1);\n }\n BOOST_FOREACH(qi::Future<void>& future, futures)\n future.cancel();\n }\n\n unsigned int successCount = 0;\n BOOST_FOREACH(qi::Future<void>& future, futures)\n {\n if (future.wait() != qi::FutureState_Canceled)\n successCount++;\n }\n if (i == futures.size() || i == 0)\n qiLogWarning() << \"i = \" << i <<\n \", this test is meaningless, you should do something about that\";\n ASSERT_EQ(successCount, i);\n}\n\nstatic void deleteStrand(qi::Strand* strand)\n{\n delete strand;\n}\n\nTEST(TestStrand, StrandDestructionBeforeEnd)\n{\n qi::Strand* strand = new qi::Strand(*qi::getEventLoop());\n qi::Future<void> f = strand->async(boost::bind(deleteStrand, strand));\n f.value();\n}\n\nboost::atomic<int> callcount;\n\nstruct MyActor : qi::Actor\n{\n boost::atomic<bool> calling;\n MyActor() : calling(0) {}\n ~MyActor() { strand()->join(); }\n int f(int end, qi::Promise<void> finished)\n {\n int startval = prop.get();\n EXPECT_FALSE(calling);\n calling = true;\n qi::os::msleep(5);\n EXPECT_TRUE(calling);\n calling = false;\n EXPECT_EQ(startval, prop.get());\n if (++callcount == end + 1)\n finished.setValue(0);\n return 42;\n }\n qi::Signal<int> sig;\n qi::Property<int> prop;\n};\nQI_REGISTER_OBJECT(MyActor, f, sig, prop);\n\nTEST(TestStrand, AllFutureSignalPropertyPeriodicTaskAsyncTypeErasedDynamic)\n{\n static const int TOTAL = 50;\n srand(1828);\n\n callcount = 0;\n {\n boost::shared_ptr<MyActor> obj(new MyActor);\n\n qi::DynamicObjectBuilder builder;\n builder.setThreadingModel(qi::ObjectThreadingModel_SingleThread);\n builder.advertiseMethod(\"f\",\n boost::function<void(int, qi::Promise<void>)>(boost::bind(&MyActor::f, obj, _1, _2)));\n builder.advertiseSignal(\"sig\", &obj->sig);\n builder.advertiseProperty(\"prop\", &obj->prop);\n\n qi::AnyObject aobj(builder.object());\n\n qi::Promise<void> finished;\n\n for (int i = 0; i < 25; ++i)\n aobj.async<void>(\"f\", TOTAL, finished);\n for (int i = 0; i < 50; ++i)\n aobj.setProperty(\"prop\", rand());\n QI_EMIT obj->sig(TOTAL);\n \/\/ we need one more call (the second test expects a periodic task to run at\n \/\/ least once)\n for (int i = 0; i < 26; ++i)\n aobj.async<void>(\"f\", TOTAL, finished);\n finished.future().wait();\n }\n ASSERT_EQ(TOTAL + 1, callcount);\n}\n\nvoid chaincall(qi::AnyObject aobj, qi::Promise<void> finished, int TOTAL)\n{\n for (int i = 0; i < 50; ++i)\n EXPECT_EQ(42, aobj.call<int>(\"f\", TOTAL, finished));\n}\n\nTEST(TestStrand, AllFutureSignalPropertyPeriodicTaskAsyncCallTypeErased)\n{\n static const int TOTAL = 300;\n srand(1828);\n\n callcount = 0;\n {\n boost::shared_ptr<MyActor> obj(new MyActor);\n qi::AnyObject aobj(obj);\n\n qi::Promise<void> finished;\n\n qi::PeriodicTask per;\n per.setUsPeriod(30);\n per.setCallback(&MyActor::f, obj.get(), TOTAL, finished);\n\n qi::Promise<void> prom;\n qi::Signal<int> signal;\n\n static_assert(std::is_same<decltype(prom.future().andThen(qi::bind(&MyActor::f, obj.get(), TOTAL, finished))), qi::Future<int>>::value, \"andThen future type incorrect\");\n static_assert(std::is_same<decltype(prom.future().then(qi::bind(&MyActor::f, obj.get(), TOTAL, finished))), qi::Future<int>>::value, \"then future type incorrect\");\n\n for (int i = 0; i < 25; ++i)\n prom.future().connect(&MyActor::f, obj.get(), TOTAL, finished);\n for (int i = 0; i < 10; ++i)\n prom.future().thenR<int>(&MyActor::f, obj.get(), TOTAL, finished);\n for (int i = 0; i < 10; ++i)\n prom.future().andThen(qi::bind(&MyActor::f, obj.get(), TOTAL, finished));\n for (int i = 0; i < 5; ++i)\n prom.future().then(qi::bind(&MyActor::f, obj.get(), TOTAL, finished));\n for (int i = 0; i < 50; ++i)\n signal.connect(&MyActor::f, obj.get(), _1, finished);\n for (int i = 0; i < 50; ++i)\n aobj.connect(\"sig\", boost::function<void(int)>(obj->strand()->schedulerFor(boost::bind(&MyActor::f, obj, _1, finished))));\n\n per.start();\n for (int i = 0; i < 25; ++i)\n aobj.async<void>(\"f\", TOTAL, finished);\n for (int i = 0; i < 25; ++i)\n qi::async(qi::bind(&MyActor::f, obj, TOTAL, finished));\n for (int i = 0; i < 50; ++i)\n aobj.setProperty(\"prop\", rand());\n qi::Future<void> f = qi::async(boost::bind(chaincall, aobj, finished, TOTAL));\n prom.setValue(0);\n QI_EMIT signal(TOTAL);\n QI_EMIT obj->sig(TOTAL);\n for (int i = 0; i < 25; ++i)\n aobj.async<void>(\"f\", TOTAL, finished);\n for (int i = 0; i < 25; ++i)\n qi::async(qi::bind(&MyActor::f, obj, TOTAL, finished));\n f.wait();\n finished.future().wait();\n }\n ASSERT_LT(TOTAL, callcount);\n}\n\nTEST(TestStrand, FutureThenActorCancel)\n{\n callcount = 0;\n {\n boost::shared_ptr<MyActor> obj(new MyActor);\n qi::AnyObject aobj(obj);\n\n qi::Promise<void> finished;\n\n qi::Promise<int> prom(qi::PromiseNoop<int>);\n qi::Future<int> masterFut = prom.future().thenR<int>(&MyActor::f, obj, _1, finished);\n masterFut.cancel();\n ASSERT_TRUE(prom.isCancelRequested());\n prom.setValue(0);\n ASSERT_EQ(42, masterFut.value());\n ASSERT_NO_THROW(finished.future().value());\n }\n}\n\nint main(int argc, char* argv[])\n{\n qi::Application app(argc, argv);\n ::testing::InitGoogleTest(&argc, argv);\n \/\/ better for these tests, since a task is 5ms long\n qi::os::setenv(\"QI_STRAND_QUANTUM_US\", \"50000\");\n return RUN_ALL_TESTS();\n}\n<commit_msg>Actor: add test for calls with success and error<commit_after>\/*\n** Copyright (C) 2014 Aldebaran\n*\/\n#include <qi\/application.hpp>\n#include <qi\/future.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/foreach.hpp>\n#include <qi\/os.hpp>\n#include <qi\/strand.hpp>\n#include <qi\/periodictask.hpp>\n#include <qi\/actor.hpp>\n#include <qi\/log.hpp>\n#include <qi\/anyobject.hpp>\n#include <qi\/type\/dynamicobjectbuilder.hpp>\n#include <gtest\/gtest.h>\n\nqiLogCategory(\"test\");\n\nvoid setValueWait(boost::mutex& mutex, int waittime, int& i, int v)\n{\n boost::unique_lock<boost::mutex> lock(mutex, boost::try_to_lock);\n \/\/ we should never be called in parallel\n ASSERT_TRUE(lock.owns_lock());\n if (waittime)\n qi::os::msleep(waittime);\n i = v;\n}\n\nTEST(TestStrand, StrandSimple)\n{\n boost::mutex mutex;\n\n qi::Strand strand(*qi::getEventLoop());\n int i = 0;\n qi::Future<void> f1 = strand.async(boost::bind<void>(&setValueWait,\n boost::ref(mutex), 100, boost::ref(i), 1));\n qi::os::msleep(5);\n EXPECT_FALSE(f1.isFinished());\n qi::Future<void> f2 = strand.async(boost::bind<void>(&setValueWait,\n boost::ref(mutex), 0, boost::ref(i), 2));\n qi::os::msleep(200);\n EXPECT_EQ(i, 2);\n}\n\nstatic void fail()\n{\n ASSERT_TRUE(false);\n}\n\nTEST(TestStrand, StrandCancel)\n{\n qi::Strand strand(*qi::getEventLoop());\n \/\/ cancel before scheduling\n qi::Future<void> f1 = strand.asyncDelay(fail, qi::Seconds(1000));\n f1.cancel();\n ASSERT_EQ(qi::FutureState_Canceled, f1.wait());\n}\n\nTEST(TestStrand, StrandCancelScheduled)\n{\n qi::Strand strand(*qi::getEventLoop());\n \/\/ cancel before scheduling\n qi::Future<void> f1 = strand.async(boost::bind(qi::os::msleep, 100));\n qi::Future<void> f2 = strand.async(fail);\n qi::os::msleep(30);\n f2.cancel();\n ASSERT_EQ(qi::FutureState_FinishedWithValue, f1.wait()) << f1.error();\n ASSERT_EQ(qi::FutureState_Canceled, f2.wait());\n}\n\nstatic void increment(boost::mutex& mutex, int waittime, boost::atomic<unsigned int>& i)\n{\n boost::unique_lock<boost::mutex> lock(mutex, boost::try_to_lock);\n \/\/ we should never be called in parallel\n ASSERT_TRUE(lock.owns_lock());\n if (waittime)\n qi::os::msleep(waittime);\n ++i;\n}\n\nstatic const unsigned int STRAND_NB_TRIES = 100;\n\nTEST(TestStrand, AggressiveCancel)\n{\n boost::mutex mutex;\n std::vector<qi::Future<void> > futures;\n\n qi::Strand strand(*qi::getEventLoop());\n boost::atomic<unsigned int> i(0);\n for (unsigned int j = 0; j < STRAND_NB_TRIES; ++j)\n {\n qi::Future<void> f1 = strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n futures.push_back(f1);\n f1 = strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 50, boost::ref(i)));\n futures.push_back(f1);\n }\n BOOST_FOREACH(qi::Future<void>& future, futures)\n future.cancel();\n\n unsigned int successCount = 0;\n BOOST_FOREACH(qi::Future<void>& future, futures)\n {\n if (future.wait() != qi::FutureState_Canceled)\n successCount++;\n }\n if (i == futures.size() || i == 0)\n qiLogWarning() << \"i = \" << i <<\n \", this test is meaningless, you should do something about that\";\n ASSERT_EQ(successCount, i);\n}\n\nTEST(TestStrand, StrandDestruction)\n{\n boost::mutex mutex;\n boost::atomic<unsigned int> i(0);\n\n std::vector<qi::Future<void>> futures;\n {\n qi::Strand strand(*qi::getEventLoop());\n futures.reserve(STRAND_NB_TRIES);\n for (unsigned int j = 0; j < STRAND_NB_TRIES; ++j)\n {\n futures.push_back(strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i))));\n }\n }\n for (auto& future : futures)\n ASSERT_TRUE(future.isFinished());\n}\n\nTEST(TestStrand, StrandDestructionWithMethodAndConcurrency)\n{\n \/\/ ASSERT_NOSEGFAULT_NOCRASH_NOBADTHINGS();\n boost::mutex mutex;\n boost::atomic<unsigned int> i(0);\n\n std::vector<qi::Future<void>> futures;\n qi::Strand strand(*qi::getEventLoop());\n futures.reserve(STRAND_NB_TRIES);\n for (unsigned int j = 0; j < STRAND_NB_TRIES\/4; ++j)\n futures.push_back(qi::getEventLoop()->async([&]{\n strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n }));\n for (unsigned int j = 0; j < STRAND_NB_TRIES\/4; ++j)\n strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n strand.join();\n for (unsigned int j = 0; j < STRAND_NB_TRIES\/4; ++j)\n futures.push_back(qi::getEventLoop()->async([&]{\n strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n }));\n for (unsigned int j = 0; j < STRAND_NB_TRIES\/4; ++j)\n strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n for (auto& future : futures)\n ASSERT_TRUE(future.wait());\n}\n\nTEST(TestStrand, StrandDestructionWithCancel)\n{\n boost::mutex mutex;\n std::vector<qi::Future<void> > futures;\n boost::atomic<unsigned int> i(0);\n\n {\n qi::Strand strand(*qi::getEventLoop());\n for (unsigned int j = 0; j < STRAND_NB_TRIES; ++j)\n {\n qi::Future<void> f1 = strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 1, boost::ref(i)));\n futures.push_back(f1);\n f1 = strand.async(boost::bind<void>(&increment,\n boost::ref(mutex), 50, boost::ref(i)));\n futures.push_back(f1);\n }\n BOOST_FOREACH(qi::Future<void>& future, futures)\n future.cancel();\n }\n\n unsigned int successCount = 0;\n BOOST_FOREACH(qi::Future<void>& future, futures)\n {\n if (future.wait() != qi::FutureState_Canceled)\n successCount++;\n }\n if (i == futures.size() || i == 0)\n qiLogWarning() << \"i = \" << i <<\n \", this test is meaningless, you should do something about that\";\n ASSERT_EQ(successCount, i);\n}\n\nstatic void deleteStrand(qi::Strand* strand)\n{\n delete strand;\n}\n\nTEST(TestStrand, StrandDestructionBeforeEnd)\n{\n qi::Strand* strand = new qi::Strand(*qi::getEventLoop());\n qi::Future<void> f = strand->async(boost::bind(deleteStrand, strand));\n f.value();\n}\n\nboost::atomic<int> callcount;\n\nstruct MyActor : qi::Actor\n{\n boost::atomic<bool> calling;\n MyActor() : calling(0) {}\n ~MyActor() { strand()->join(); }\n int f(int end, qi::Promise<void> finished)\n {\n int startval = prop.get();\n EXPECT_FALSE(calling);\n calling = true;\n qi::os::msleep(5);\n EXPECT_TRUE(calling);\n calling = false;\n EXPECT_EQ(startval, prop.get());\n if (++callcount == end + 1)\n finished.setValue(0);\n return 42;\n }\n qi::Future<int> val()\n {\n return qi::Future<int>(42);\n }\n qi::Future<int> thrw()\n {\n throw std::runtime_error(\"throw\");\n }\n qi::Future<int> fail()\n {\n return qi::makeFutureError<int>(\"fail\");\n }\n qi::Signal<int> sig;\n qi::Property<int> prop;\n};\nQI_REGISTER_OBJECT(MyActor, f, val, thrw, fail, sig, prop);\n\nTEST(TestStrand, TypeErasedCall)\n{\n boost::shared_ptr<MyActor> obj(new MyActor);\n qi::AnyObject aobj(obj);\n\n EXPECT_EQ(42, aobj.async<int>(\"val\").value());\n EXPECT_TRUE(aobj.async<int>(\"thrw\").hasError());\n EXPECT_TRUE(aobj.async<int>(\"fail\").hasError());\n\n EXPECT_EQ(42, aobj.call<int>(\"val\"));\n EXPECT_ANY_THROW(aobj.call<int>(\"thrw\"));\n EXPECT_ANY_THROW(aobj.call<int>(\"fail\"));\n}\n\nTEST(TestStrand, AllFutureSignalPropertyPeriodicTaskAsyncTypeErasedDynamic)\n{\n static const int TOTAL = 50;\n srand(1828);\n\n callcount = 0;\n {\n boost::shared_ptr<MyActor> obj(new MyActor);\n\n qi::DynamicObjectBuilder builder;\n builder.setThreadingModel(qi::ObjectThreadingModel_SingleThread);\n builder.advertiseMethod(\"f\",\n boost::function<void(int, qi::Promise<void>)>(boost::bind(&MyActor::f, obj, _1, _2)));\n builder.advertiseSignal(\"sig\", &obj->sig);\n builder.advertiseProperty(\"prop\", &obj->prop);\n\n qi::AnyObject aobj(builder.object());\n\n qi::Promise<void> finished;\n\n for (int i = 0; i < 25; ++i)\n aobj.async<void>(\"f\", TOTAL, finished);\n for (int i = 0; i < 50; ++i)\n aobj.setProperty(\"prop\", rand());\n QI_EMIT obj->sig(TOTAL);\n \/\/ we need one more call (the second test expects a periodic task to run at\n \/\/ least once)\n for (int i = 0; i < 26; ++i)\n aobj.async<void>(\"f\", TOTAL, finished);\n finished.future().wait();\n }\n ASSERT_EQ(TOTAL + 1, callcount);\n}\n\nvoid chaincall(qi::AnyObject aobj, qi::Promise<void> finished, int TOTAL)\n{\n for (int i = 0; i < 50; ++i)\n EXPECT_EQ(42, aobj.call<int>(\"f\", TOTAL, finished));\n}\n\nTEST(TestStrand, AllFutureSignalPropertyPeriodicTaskAsyncCallTypeErased)\n{\n static const int TOTAL = 300;\n srand(1828);\n\n callcount = 0;\n {\n boost::shared_ptr<MyActor> obj(new MyActor);\n qi::AnyObject aobj(obj);\n\n qi::Promise<void> finished;\n\n qi::PeriodicTask per;\n per.setUsPeriod(30);\n per.setCallback(&MyActor::f, obj.get(), TOTAL, finished);\n\n qi::Promise<void> prom;\n qi::Signal<int> signal;\n\n static_assert(std::is_same<decltype(prom.future().andThen(qi::bind(&MyActor::f, obj.get(), TOTAL, finished))), qi::Future<int>>::value, \"andThen future type incorrect\");\n static_assert(std::is_same<decltype(prom.future().then(qi::bind(&MyActor::f, obj.get(), TOTAL, finished))), qi::Future<int>>::value, \"then future type incorrect\");\n\n for (int i = 0; i < 25; ++i)\n prom.future().connect(&MyActor::f, obj.get(), TOTAL, finished);\n for (int i = 0; i < 10; ++i)\n prom.future().thenR<int>(&MyActor::f, obj.get(), TOTAL, finished);\n for (int i = 0; i < 10; ++i)\n prom.future().andThen(qi::bind(&MyActor::f, obj.get(), TOTAL, finished));\n for (int i = 0; i < 5; ++i)\n prom.future().then(qi::bind(&MyActor::f, obj.get(), TOTAL, finished));\n for (int i = 0; i < 50; ++i)\n signal.connect(&MyActor::f, obj.get(), _1, finished);\n for (int i = 0; i < 50; ++i)\n aobj.connect(\"sig\", boost::function<void(int)>(obj->strand()->schedulerFor(boost::bind(&MyActor::f, obj, _1, finished))));\n\n per.start();\n for (int i = 0; i < 25; ++i)\n aobj.async<void>(\"f\", TOTAL, finished);\n for (int i = 0; i < 25; ++i)\n qi::async(qi::bind(&MyActor::f, obj, TOTAL, finished));\n for (int i = 0; i < 50; ++i)\n aobj.setProperty(\"prop\", rand());\n qi::Future<void> f = qi::async(boost::bind(chaincall, aobj, finished, TOTAL));\n prom.setValue(0);\n QI_EMIT signal(TOTAL);\n QI_EMIT obj->sig(TOTAL);\n for (int i = 0; i < 25; ++i)\n aobj.async<void>(\"f\", TOTAL, finished);\n for (int i = 0; i < 25; ++i)\n qi::async(qi::bind(&MyActor::f, obj, TOTAL, finished));\n f.wait();\n finished.future().wait();\n }\n ASSERT_LT(TOTAL, callcount);\n}\n\nTEST(TestStrand, FutureThenActorCancel)\n{\n callcount = 0;\n {\n boost::shared_ptr<MyActor> obj(new MyActor);\n qi::AnyObject aobj(obj);\n\n qi::Promise<void> finished;\n\n qi::Promise<int> prom(qi::PromiseNoop<int>);\n qi::Future<int> masterFut = prom.future().thenR<int>(&MyActor::f, obj, _1, finished);\n masterFut.cancel();\n ASSERT_TRUE(prom.isCancelRequested());\n prom.setValue(0);\n ASSERT_EQ(42, masterFut.value());\n ASSERT_NO_THROW(finished.future().value());\n }\n}\n\nint main(int argc, char* argv[])\n{\n qi::Application app(argc, argv);\n ::testing::InitGoogleTest(&argc, argv);\n \/\/ better for these tests, since a task is 5ms long\n qi::os::setenv(\"QI_STRAND_QUANTUM_US\", \"50000\");\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n#include <cstdio>\n\n#include <qi\/os.hpp>\n#include <boost\/thread\/thread.hpp>\n#include <boost\/thread\/condition_variable.hpp>\n\nstatic class threadTest\n{\npublic:\n inline threadTest();\n inline ~threadTest();\n\n void run()\n {\n while (_glInit)\n {\n printTest();\n qi::os::sleep(1);\n }\n\n std::cout << \"Stop running\" << std::endl;\n fflush(stdout);\n }\n\n void printTest()\n {\n std::cout << \"Running...\" << std::endl;\n fflush(stdout);\n }\n\npublic:\n bool _glInit;\n boost::thread _glThread;\n boost::mutex _glLock;\n boost::condition_variable _glCond;\n} threadGolbal;\n\ninline threadTest::threadTest()\n{\n _glInit = true;\n _glThread = boost::thread(&threadTest::run, &threadGolbal);\n std::cout << \"Creating main thread\" << std::endl;\n fflush(stdout);\n};\n\ninline threadTest::~threadTest()\n{\n _glInit = false;\n\n _glThread.interrupt();\n std::cout << \"Interrupting main thread\" << std::endl;\n fflush(stdout);\n\n _glThread.join();\n std::cout << \"Joinning main thread\" << std::endl;\n fflush(stdout);\n\n printTest();\n std::cout << \"Main thread destroyed\" << std::endl;\n fflush(stdout);\n};\n\n\nint main(int argc, char *argv[])\n{\n std::cout << \"Entering main function\" << std::endl;\n fflush(stdout);\n\n qi::os::sleep(5);\n\n std::cout << \"Leaving main function\" << std::endl;\n fflush(stdout);\n\n exit(0);\n}\n<commit_msg>Fix helgrind warnings in test_thread<commit_after>\/*\n * Copyright (c) 2012-2015 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n#include <atomic>\n#include <cstdio>\n#include <mutex>\n\n#include <qi\/os.hpp>\n#include <boost\/thread\/thread.hpp>\n#include <boost\/thread\/condition_variable.hpp>\n\nstruct SafeCout\n{\n static std::mutex m;\n\n template<typename T>\n std::ostream& operator<<(const T& whatever)\n {\n std::unique_lock<std::mutex> l{m};\n auto& o = std::cout << whatever;\n fflush(stdout);\n return o;\n }\n} safeCout;\n\nstd::mutex SafeCout::m = {};\n\nstatic class threadTest\n{\npublic:\n inline threadTest();\n inline ~threadTest();\n\n void run()\n {\n while (_glInit)\n {\n printTest();\n qi::os::sleep(1);\n }\n\n safeCout << \"Stop running\" << std::endl;\n }\n\n void printTest()\n {\n safeCout << \"Running...\" << std::endl;\n }\n\npublic:\n std::atomic<bool> _glInit;\n boost::thread _glThread;\n} threadGlobal;\n\ninline threadTest::threadTest()\n{\n _glInit = true;\n safeCout << \"Creating main thread\" << std::endl;\n _glThread = boost::thread(&threadTest::run, &threadGlobal);\n};\n\ninline threadTest::~threadTest()\n{\n _glInit = false;\n\n _glThread.interrupt();\n safeCout << \"Interrupting main thread\" << std::endl;\n\n _glThread.join();\n safeCout << \"Joining main thread\" << std::endl;\n\n printTest();\n safeCout << \"Main thread destroyed\" << std::endl;\n};\n\n\nint main(int argc, char *argv[])\n{\n safeCout << \"Entering main function\" << std::endl;\n\n qi::os::sleep(5);\n\n safeCout << \"Leaving main function\" << std::endl;\n\n exit(0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n\tdon't remove the top of BOM for VC\r\n*\/\r\n#include <cybozu\/test.hpp>\r\n#include <cybozu\/fmindex.hpp>\r\n#include <cybozu\/file.hpp>\r\n#include <cybozu\/mmap.hpp>\r\n#include <cybozu\/string.hpp>\r\n#include <set>\r\n\r\ntypedef std::set<int> Set;\r\n\r\nstd::string g_textTbl[] = {\r\n\t\"\",\r\n\t\"abracatabra\",\r\n\t\"cybozuabcabcintint}}\",\r\n};\r\n\r\nstruct Init {\r\n\tInit()\r\n\t{\r\n\t\tstd::string path = cybozu::file::GetExePath();\r\n\t\tsize_t pos = path.find(\"cybozulib\");\r\n\t\tCYBOZU_TEST_ASSERT(pos != std::string::npos);\r\n\t\tpath = path.substr(0, pos + 9) + \"\/include\/cybozu\/fmindex.hpp\";\r\n\t\tcybozu::Mmap mmap(path);\r\n\t\tg_textTbl[0].assign(mmap.get(), (size_t)mmap.size());\r\n\t}\r\n} init;\r\n\r\n\/\/\tf.getPrevString(out, 0, f.wm.size() - 1);\r\n\r\ntemplate<class FMINDEX, class STRING>\r\nSet searchPos1(const FMINDEX& f, const STRING& key)\r\n{\r\n\tSet ret;\r\n\tsize_t begin, end;\r\n\tif (f.getRange(&begin, &end, key)) {\r\n\t\twhile (begin != end) {\r\n\t\t\tret.insert((int)f.convertPosition(begin));\r\n\t\t\t++begin;\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n\/\/ standard search\r\ntemplate<class STRING>\r\nSet searchPos2(const STRING& text, const STRING& key)\r\n{\r\n\tSet ret;\r\n\tsize_t pos = 0;\r\n\tfor (;;) {\r\n\t\tsize_t q = text.find(key, pos);\r\n\t\tif (q == std::string::npos) break;\r\n\t\tret.insert((int)q);\r\n\t\tpos = q + 1;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\ntemplate<class FMINDEX, class STRING>\r\nvoid compareText(const FMINDEX& f, const STRING& text, const STRING *keyTbl, size_t keySize)\r\n{\r\n\tfor (size_t i = 0; i < keySize; i++) {\r\n\t\tconst STRING& key = keyTbl[i];\r\n\t\tSet a = searchPos1(f, key);\r\n\t\tSet b = searchPos2(text, key);\r\n\t\tCYBOZU_TEST_EQUAL(a.size(), b.size());\r\n\t\tif (a.size() == b.size()) {\r\n\t\t\tsize_t pos = 0;\r\n\t\t\tfor (Set::const_iterator ia = a.begin(), ib = b.begin(); pos < a.size(); ++ia, ++ib, ++pos) {\r\n\t\t\t\tCYBOZU_TEST_EQUAL(*ia, *ib);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\/\/ recover string\r\n\tSTRING org;\r\n\tf.getPrevString(org, 0, f.wm.size() - 1);\r\n\tCYBOZU_TEST_EQUAL(org.size(), text.size());\r\n\tCYBOZU_TEST_ASSERT(org == text);\r\n}\r\n\r\ntemplate<class FMINDEX, class STRING>\r\nvoid searchTest(const STRING& text, const STRING *keyTbl, size_t keySize)\r\n{\r\n\tFMINDEX f;\r\n\tf.init(text.begin(), text.end());\r\n\tcompareText(f, text, keyTbl, keySize);\r\n\tstd::stringstream ss;\r\n\tf.save(ss);\r\n\t{\r\n\t\tFMINDEX ff;\r\n\t\tff.load(ss);\r\n\t\tcompareText(ff, text, keyTbl, keySize);\r\n\t}\r\n}\r\n\r\nCYBOZU_TEST_AUTO(string)\r\n{\r\n\tstatic const std::string tbl[] = {\r\n\t\t\"double\", \"int\", \"cybozu\", \"std\", \"}\", \"\\t\", \"xxx\",\r\n\t};\r\n\tfor (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(g_textTbl); i++) {\r\n\t\tsearchTest<cybozu::FMindex, std::string>(g_textTbl[i], tbl, CYBOZU_NUM_OF_ARRAY(tbl));\r\n\t}\r\n}\r\n\r\nCYBOZU_TEST_AUTO(wstring)\r\n{\r\n\tstatic const cybozu::String text(CYBOZU_STR_W(\"あいうえおabcあいうえおaaabあああうえabうえあいう\"));\r\n\tstatic const cybozu::String tbl[] = {\r\n\t\tCYBOZU_STR_W(\"あいう\"),\r\n\t\tCYBOZU_STR_W(\"ab\"),\r\n\t\tCYBOZU_STR_W(\"うえ\"),\r\n\t};\r\n\tsearchTest<cybozu::FMindexT<cybozu::Char>, cybozu::String>(text, tbl, CYBOZU_NUM_OF_ARRAY(tbl));\r\n}\r\n<commit_msg>disable warning about end<commit_after>\/*\r\n\tdon't remove the top of BOM for VC\r\n*\/\r\n#include <cybozu\/test.hpp>\r\n#include <cybozu\/fmindex.hpp>\r\n#include <cybozu\/file.hpp>\r\n#include <cybozu\/mmap.hpp>\r\n#include <cybozu\/string.hpp>\r\n#include <set>\r\n\r\ntypedef std::set<int> Set;\r\n\r\nstd::string g_textTbl[] = {\r\n\t\"\",\r\n\t\"abracatabra\",\r\n\t\"cybozuabcabcintint}}\",\r\n};\r\n\r\nstruct Init {\r\n\tInit()\r\n\t{\r\n\t\tstd::string path = cybozu::file::GetExePath();\r\n\t\tsize_t pos = path.find(\"cybozulib\");\r\n\t\tCYBOZU_TEST_ASSERT(pos != std::string::npos);\r\n\t\tpath = path.substr(0, pos + 9) + \"\/include\/cybozu\/fmindex.hpp\";\r\n\t\tcybozu::Mmap mmap(path);\r\n\t\tg_textTbl[0].assign(mmap.get(), (size_t)mmap.size());\r\n\t}\r\n} init;\r\n\r\n\/\/\tf.getPrevString(out, 0, f.wm.size() - 1);\r\n\r\ntemplate<class FMINDEX, class STRING>\r\nSet searchPos1(const FMINDEX& f, const STRING& key)\r\n{\r\n\tSet ret;\r\n\tsize_t begin, end = 0;\r\n\tif (f.getRange(&begin, &end, key)) {\r\n\t\twhile (begin != end) {\r\n\t\t\tret.insert((int)f.convertPosition(begin));\r\n\t\t\t++begin;\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n\/\/ standard search\r\ntemplate<class STRING>\r\nSet searchPos2(const STRING& text, const STRING& key)\r\n{\r\n\tSet ret;\r\n\tsize_t pos = 0;\r\n\tfor (;;) {\r\n\t\tsize_t q = text.find(key, pos);\r\n\t\tif (q == std::string::npos) break;\r\n\t\tret.insert((int)q);\r\n\t\tpos = q + 1;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\ntemplate<class FMINDEX, class STRING>\r\nvoid compareText(const FMINDEX& f, const STRING& text, const STRING *keyTbl, size_t keySize)\r\n{\r\n\tfor (size_t i = 0; i < keySize; i++) {\r\n\t\tconst STRING& key = keyTbl[i];\r\n\t\tSet a = searchPos1(f, key);\r\n\t\tSet b = searchPos2(text, key);\r\n\t\tCYBOZU_TEST_EQUAL(a.size(), b.size());\r\n\t\tif (a.size() == b.size()) {\r\n\t\t\tsize_t pos = 0;\r\n\t\t\tfor (Set::const_iterator ia = a.begin(), ib = b.begin(); pos < a.size(); ++ia, ++ib, ++pos) {\r\n\t\t\t\tCYBOZU_TEST_EQUAL(*ia, *ib);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\/\/ recover string\r\n\tSTRING org;\r\n\tf.getPrevString(org, 0, f.wm.size() - 1);\r\n\tCYBOZU_TEST_EQUAL(org.size(), text.size());\r\n\tCYBOZU_TEST_ASSERT(org == text);\r\n}\r\n\r\ntemplate<class FMINDEX, class STRING>\r\nvoid searchTest(const STRING& text, const STRING *keyTbl, size_t keySize)\r\n{\r\n\tFMINDEX f;\r\n\tf.init(text.begin(), text.end());\r\n\tcompareText(f, text, keyTbl, keySize);\r\n\tstd::stringstream ss;\r\n\tf.save(ss);\r\n\t{\r\n\t\tFMINDEX ff;\r\n\t\tff.load(ss);\r\n\t\tcompareText(ff, text, keyTbl, keySize);\r\n\t}\r\n}\r\n\r\nCYBOZU_TEST_AUTO(string)\r\n{\r\n\tstatic const std::string tbl[] = {\r\n\t\t\"double\", \"int\", \"cybozu\", \"std\", \"}\", \"\\t\", \"xxx\",\r\n\t};\r\n\tfor (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(g_textTbl); i++) {\r\n\t\tsearchTest<cybozu::FMindex, std::string>(g_textTbl[i], tbl, CYBOZU_NUM_OF_ARRAY(tbl));\r\n\t}\r\n}\r\n\r\nCYBOZU_TEST_AUTO(wstring)\r\n{\r\n\tstatic const cybozu::String text(CYBOZU_STR_W(\"あいうえおabcあいうえおaaabあああうえabうえあいう\"));\r\n\tstatic const cybozu::String tbl[] = {\r\n\t\tCYBOZU_STR_W(\"あいう\"),\r\n\t\tCYBOZU_STR_W(\"ab\"),\r\n\t\tCYBOZU_STR_W(\"うえ\"),\r\n\t};\r\n\tsearchTest<cybozu::FMindexT<cybozu::Char>, cybozu::String>(text, tbl, CYBOZU_NUM_OF_ARRAY(tbl));\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2015 Dims dev-team\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"common\/manageNetwork.h\"\n#include \"common\/actionHandler.h\"\n\n#include \"monitor\/recognizeNetworkAction.h\"\n#include \"monitor\/connectNodeAction.h\"\n#include \"monitor\/filters.h\"\n\n#include <boost\/statechart\/state.hpp>\n#include <boost\/statechart\/transition.hpp>\n#include <boost\/statechart\/custom_reaction.hpp>\n\nnamespace monitor\n{\n\nstruct CGetDnsInfo : boost::statechart::state< CGetDnsInfo, CRecognizeNetworkAction >\n{\n\tCGetDnsInfo( my_context ctx ) : my_base( ctx )\n\t{\n\t\t\/\/ search for seeder action\n\t\tstd::vector<CAddress> vAdd;\n\n\t\tcommon::CManageNetwork::getInstance()->getIpsFromSeed( vAdd );\n\n\t\tif ( !vAdd.empty() )\n\t\t{\n\t\t\tBOOST_FOREACH( CAddress address, vAdd )\n\t\t\t{\n\t\t\t\tcontext< CRecognizeNetworkAction >().dropRequests();\n\t\t\t\tcontext< CRecognizeNetworkAction >().addRequest(\n\t\t\t\t\t\t\tnew common::CScheduleActionRequest< common::CMonitorTypes >(\n\t\t\t\t\t\t\t\tnew CConnectNodeAction( address )\n\t\t\t\t\t\t\t\t, new CMediumClassFilter( common::CMediumKinds::Schedule) ) );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcommon::CManageNetwork::getInstance()->getSeedIps( vAdd );\n\n\t\t\t\/\/ let know seed about our existence\n\t\t\tBOOST_FOREACH( CAddress address, vAdd )\n\t\t\t{\n\t\t\t\tcontext< CRecognizeNetworkAction >().dropRequests();\n\t\t\t\tcontext< CRecognizeNetworkAction >().addRequest(\n\t\t\t\t\t\t\tnew common::CScheduleActionRequest< common::CMonitorTypes >(\n\t\t\t\t\t\t\t\tnew CConnectNodeAction( address )\n\t\t\t\t\t\t\t\t, new CMediumClassFilter( common::CMediumKinds::Schedule) ) );\n\t\t\t}\n\t\t}\n\t}\n\n\tboost::statechart::result react( common::CNetworkInfoEvent const & _networkInfoEvent )\n\t{\n\t\t\/\/return transit< CDetermineRoleConnecting >();\n\t\treturn discard_event();\n\t}\n\n\ttypedef boost::mpl::list<\n\tboost::statechart::custom_reaction< common::CNetworkInfoEvent >\n\t> reactions;\n\n};\n\n\nCRecognizeNetworkAction::CRecognizeNetworkAction()\n{\n\tinitiate();\n}\n\nvoid\nCRecognizeNetworkAction::accept( common::CSetResponseVisitor< common::CMonitorTypes > & _visitor )\n{\n\t_visitor.visit( *this );\n}\n\n}\n<commit_msg>small in monitor<commit_after>\/\/ Copyright (c) 2014-2015 Dims dev-team\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"common\/manageNetwork.h\"\n#include \"common\/actionHandler.h\"\n\n#include \"monitor\/recognizeNetworkAction.h\"\n#include \"monitor\/connectNodeAction.h\"\n#include \"monitor\/filters.h\"\n\n#include <boost\/statechart\/state.hpp>\n#include <boost\/statechart\/transition.hpp>\n#include <boost\/statechart\/custom_reaction.hpp>\n\nnamespace monitor\n{\n\nstruct CGetDnsInfo : boost::statechart::state< CGetDnsInfo, CRecognizeNetworkAction >\n{\n\tCGetDnsInfo( my_context ctx ) : my_base( ctx )\n\t{\n\t\t\/\/ search for seeder action\n\t\tstd::vector<CAddress> vAdd;\n\n\t\tcommon::CManageNetwork::getInstance()->getIpsFromSeed( vAdd );\n\n\t\tif ( !vAdd.empty() )\n\t\t{\n\t\t\tBOOST_FOREACH( CAddress address, vAdd )\n\t\t\t{\n\t\t\t\tcontext< CRecognizeNetworkAction >().dropRequests();\n\t\t\t\tcontext< CRecognizeNetworkAction >().addRequest(\n\t\t\t\t\t\t\tnew common::CScheduleActionRequest< common::CMonitorTypes >(\n\t\t\t\t\t\t\t\tnew CConnectNodeAction( address )\n\t\t\t\t\t\t\t\t, new CMediumClassFilter( common::CMediumKinds::Schedule) ) );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcommon::CManageNetwork::getInstance()->getSeedIps( vAdd );\n\n\t\t\t\/\/ let know seed about our existence\n\t\t\tBOOST_FOREACH( CAddress address, vAdd )\n\t\t\t{\n\t\t\t\tcontext< CRecognizeNetworkAction >().dropRequests();\n\t\t\t\tcontext< CRecognizeNetworkAction >().addRequest(\n\t\t\t\t\t\t\tnew common::CScheduleActionRequest< common::CMonitorTypes >(\n\t\t\t\t\t\t\t\tnew CConnectNodeAction( address )\n\t\t\t\t\t\t\t\t, new CMediumClassFilter( common::CMediumKinds::Schedule) ) );\n\t\t\t}\n\t\t}\n\t}\n\n\tboost::statechart::result react( common::CNetworkInfoEvent const & _networkInfoEvent )\n\t{\n\t\tcontext< CRecognizeNetworkAction >().setExit();\n\t\treturn discard_event();\n\t}\n\n\ttypedef boost::mpl::list<\n\tboost::statechart::custom_reaction< common::CNetworkInfoEvent >\n\t> reactions;\n\n};\n\n\nCRecognizeNetworkAction::CRecognizeNetworkAction()\n{\n\tinitiate();\n}\n\nvoid\nCRecognizeNetworkAction::accept( common::CSetResponseVisitor< common::CMonitorTypes > & _visitor )\n{\n\t_visitor.visit( *this );\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>`Font2D`: `screen_width`, `screen_height`, `font_texture_file_format`.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>A few more bitmap fixes for the GL build Review URL: http:\/\/codereview.chromium.org\/149684<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2015-2017 by the parties listed in the AUTHORS file.\nAll rights reserved. Use of this source code is governed by\na BSD-style license that can be found in the LICENSE file.\n*\/\n\n\n#ifndef timing_manager_hpp_\n#define timing_manager_hpp_\n\n\/\/----------------------------------------------------------------------------\/\/\n\n#include <unordered_map>\n#include <deque>\n#include <string>\n#include \"timer.hpp\"\n\n#include <mpi.h>\n\n#ifdef _OPENMP\n# include <omp.h>\n#endif\n\n#include <cereal\/cereal.hpp>\n#include <cereal\/types\/deque.hpp>\n#include <cereal\/access.hpp>\n#include <cereal\/types\/unordered_map.hpp>\n#include <cereal\/types\/chrono.hpp>\n#include <cereal\/archives\/adapters.hpp>\n#include <cereal\/archives\/binary.hpp>\n#include <cereal\/archives\/json.hpp>\n#include <cereal\/archives\/portable_binary.hpp>\n#include <cereal\/archives\/xml.hpp>\n\nnamespace toast\n{\nnamespace util\n{\n\n\/\/----------------------------------------------------------------------------\/\/\n\ninline bool mpi_is_initialized()\n{\n int32_t _init = 0;\n MPI_Initialized(&_init);\n return (_init != 0) ? true : false;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\ninline int32_t mpi_rank()\n{\n int32_t _rank = 0;\n if(mpi_is_initialized())\n MPI_Comm_rank(MPI_COMM_WORLD, &_rank);\n return std::max(_rank, (int32_t) 0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\ninline int32_t mpi_size()\n{\n int32_t _size = 1;\n if(mpi_is_initialized())\n MPI_Comm_size(MPI_COMM_WORLD, &_size);\n return std::max(_size, (int32_t) 1);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\ninline int32_t get_max_threads()\n{\n#ifdef _OPENMP\n return omp_get_max_threads();\n#else\n return 1;\n#endif\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\nstruct timer_tuple : public std::tuple<uint64_t, uint64_t, std::string,\n toast::util::timer&>\n{\n typedef std::string string_t;\n typedef toast::util::timer toast_timer_t;\n typedef uint64_t first_type;\n typedef uint64_t second_type;\n typedef string_t third_type;\n typedef toast_timer_t& fourth_type;\n typedef std::tuple<uint64_t, uint64_t, string_t,\n toast_timer_t&> base_type;\n\n timer_tuple(const base_type& _data) : base_type(_data) { }\n timer_tuple(first_type _b, second_type _s, third_type _t, fourth_type _f)\n : base_type(_b, _s, _t, _f) { }\n\n timer_tuple& operator=(const base_type& rhs)\n {\n if(this == &rhs)\n return *this;\n base_type::operator =(rhs);\n return *this;\n }\n\n first_type& key() { return std::get<0>(*this); }\n const first_type& key() const { return std::get<0>(*this); }\n\n second_type& level() { return std::get<1>(*this); }\n const second_type& level() const { return std::get<1>(*this); }\n\n third_type tag() { return std::get<2>(*this); }\n const third_type tag() const { return std::get<2>(*this); }\n\n fourth_type timer() { return std::get<3>(*this); }\n const fourth_type timer() const { return std::get<3>(*this); }\n\n \/\/ serialization function\n template <typename Archive> void\n serialize(Archive& ar, const unsigned int \/*version*\/)\n {\n ar(cereal::make_nvp(\"timer.key\", std::get<0>(*this)),\n cereal::make_nvp(\"timer.level\", std::get<1>(*this)),\n cereal::make_nvp(\"timer.tag\", std::get<2>(*this)),\n cereal::make_nvp(\"timer.ref\", std::get<3>(*this)));\n }\n};\n\n\/\/----------------------------------------------------------------------------\/\/\n\nclass timing_manager\n{\npublic:\n template <typename _Key, typename _Mapped>\n using uomap = std::unordered_map<_Key, _Mapped>;\n\n typedef toast::util::timer toast_timer_t;\n typedef toast_timer_t::string_t string_t;\n typedef timer_tuple timer_tuple_t;\n typedef std::deque<timer_tuple_t> timer_list_t;\n typedef timer_list_t::iterator iterator;\n typedef timer_list_t::const_iterator const_iterator;\n typedef timer_list_t::size_type size_type;\n typedef uomap<uint64_t, toast_timer_t> timer_map_t;\n typedef toast_timer_t::ostream_t ostream_t;\n typedef toast_timer_t::ofstream_t ofstream_t;\n typedef toast::clock_type clock_type;\n\npublic:\n\t\/\/ Constructor and Destructors\n timing_manager();\n virtual ~timing_manager();\n\npublic:\n \/\/ Public static functions\n static timing_manager* instance();\n static void write_json(const string_t& _fname);\n\npublic:\n \/\/ Public member functions\n size_type size() const { return m_timer_list.size(); }\n void clear();\n\n toast_timer_t& timer(const string_t& key,\n const string_t& tag = \"cxx\",\n int32_t ncount = 0,\n int32_t nhash = 0);\n\n toast_timer_t& at(size_t i) { return m_timer_list.at(i).timer(); }\n\n \/\/ time a function with a return type and no arguments\n template <typename _Ret, typename _Func>\n _Ret time(const string_t& key, _Func);\n\n \/\/ time a function with a return type and arguments\n template <typename _Ret, typename _Func, typename... _Args>\n _Ret time(const string_t& key, _Func, _Args...);\n\n \/\/ time a function with no return type and no arguments\n template <typename _Func>\n void time(const string_t& key, _Func);\n\n \/\/ time a function with no return type and arguments\n template <typename _Func, typename... _Args>\n void time(const string_t& key, _Func, _Args...);\n\n \/\/ serialization function\n template <typename Archive> void\n serialize(Archive& ar, const unsigned int \/*version*\/);\n\n \/\/ iteration of timers\n iterator begin() { return m_timer_list.begin(); }\n const_iterator begin() const { return m_timer_list.cbegin(); }\n const_iterator cbegin() const { return m_timer_list.cbegin(); }\n\n iterator end() { return m_timer_list.end(); }\n const_iterator end() const { return m_timer_list.cend(); }\n const_iterator cend() const { return m_timer_list.cend(); }\n\n void report() const;\n void set_output_stream(ostream_t&);\n void set_output_stream(const string_t&);\n\nprotected:\n inline uint64_t string_hash(const string_t&) const;\n\nprivate:\n \/\/ Private functions\n ofstream_t* get_ofstream(ostream_t* m_os) const;\n void report(ostream_t*) const;\n\nprivate:\n\t\/\/ Private variables\n static timing_manager* fgInstance;\n \/\/ hashed string map for fast lookup\n timer_map_t m_timer_map;\n \/\/ ordered list for output (outputs in order of timer instantiation)\n timer_list_t m_timer_list;\n \/\/ output stream for total timing report\n ostream_t* m_report;\n};\n\n\/\/----------------------------------------------------------------------------\/\/\ninline void\ntiming_manager::clear()\n{\n m_timer_list.clear();\n m_timer_map.clear();\n details::base_timer::get_instance_count() = 0;\n details::base_timer::get_instance_hash() = 0;\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename _Ret, typename _Func>\ninline _Ret\ntiming_manager::time(const string_t& key, _Func func)\n{\n toast_timer_t& _t = this->instance()->timer(key);\n _t.start();\n _Ret _ret = func();\n _t.stop();\n return _ret;\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename _Ret, typename _Func, typename... _Args>\ninline _Ret\ntiming_manager::time(const string_t& key, _Func func, _Args... args)\n{\n toast_timer_t& _t = this->instance()->timer(key);\n _t.start();\n _Ret _ret = func(args...);\n _t.stop();\n return _ret;\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename _Func>\ninline void\ntiming_manager::time(const string_t& key, _Func func)\n{\n toast_timer_t& _t = this->instance()->timer(key);\n _t.start();\n func();\n _t.stop();\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename _Func, typename... _Args>\ninline void\ntiming_manager::time(const string_t& key, _Func func, _Args... args)\n{\n toast_timer_t& _t = this->instance()->timer(key);\n _t.start();\n func(args...);\n _t.stop();\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename Archive>\ninline void\ntiming_manager::serialize(Archive& ar, const unsigned int \/*version*\/)\n{\n uint32_t omp_nthreads = get_max_threads();\n ar(cereal::make_nvp(\"omp_concurrency\", omp_nthreads));\n ar(cereal::make_nvp(\"timers\", m_timer_list));\n}\n\/\/----------------------------------------------------------------------------\/\/\ninline uint64_t\ntiming_manager::string_hash(const string_t& str) const\n{\n \/\/return std::hash<string_t>()(str);\n \/\/ computes the hash of an employee using a variant\n \/\/ of the Fowler-Noll-Vo hash function\n uint64_t result = 2166136261;\n\n for(const auto& itr : str)\n result = (result * 16777619) ^ itr;\n return result ^ str.length();\n}\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ namespace util\n\n} \/\/ namespace toast\n\n#endif \/\/ timing_manager_hpp_\n<commit_msg>Replaced custom string hashing with STL string hashing<commit_after>\/*\nCopyright (c) 2015-2017 by the parties listed in the AUTHORS file.\nAll rights reserved. Use of this source code is governed by\na BSD-style license that can be found in the LICENSE file.\n*\/\n\n\n#ifndef timing_manager_hpp_\n#define timing_manager_hpp_\n\n\/\/----------------------------------------------------------------------------\/\/\n\n#include <unordered_map>\n#include <deque>\n#include <string>\n#include \"timer.hpp\"\n\n#include <mpi.h>\n\n#ifdef _OPENMP\n# include <omp.h>\n#endif\n\n#include <cereal\/cereal.hpp>\n#include <cereal\/types\/deque.hpp>\n#include <cereal\/access.hpp>\n#include <cereal\/types\/unordered_map.hpp>\n#include <cereal\/types\/chrono.hpp>\n#include <cereal\/archives\/adapters.hpp>\n#include <cereal\/archives\/binary.hpp>\n#include <cereal\/archives\/json.hpp>\n#include <cereal\/archives\/portable_binary.hpp>\n#include <cereal\/archives\/xml.hpp>\n\nnamespace toast\n{\nnamespace util\n{\n\n\/\/----------------------------------------------------------------------------\/\/\n\ninline bool mpi_is_initialized()\n{\n int32_t _init = 0;\n MPI_Initialized(&_init);\n return (_init != 0) ? true : false;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\ninline int32_t mpi_rank()\n{\n int32_t _rank = 0;\n if(mpi_is_initialized())\n MPI_Comm_rank(MPI_COMM_WORLD, &_rank);\n return std::max(_rank, (int32_t) 0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\ninline int32_t mpi_size()\n{\n int32_t _size = 1;\n if(mpi_is_initialized())\n MPI_Comm_size(MPI_COMM_WORLD, &_size);\n return std::max(_size, (int32_t) 1);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\ninline int32_t get_max_threads()\n{\n#ifdef _OPENMP\n return omp_get_max_threads();\n#else\n return 1;\n#endif\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\nstruct timer_tuple : public std::tuple<uint64_t, uint64_t, std::string,\n toast::util::timer&>\n{\n typedef std::string string_t;\n typedef toast::util::timer toast_timer_t;\n typedef uint64_t first_type;\n typedef uint64_t second_type;\n typedef string_t third_type;\n typedef toast_timer_t& fourth_type;\n typedef std::tuple<uint64_t, uint64_t, string_t,\n toast_timer_t&> base_type;\n\n timer_tuple(const base_type& _data) : base_type(_data) { }\n timer_tuple(first_type _b, second_type _s, third_type _t, fourth_type _f)\n : base_type(_b, _s, _t, _f) { }\n\n timer_tuple& operator=(const base_type& rhs)\n {\n if(this == &rhs)\n return *this;\n base_type::operator =(rhs);\n return *this;\n }\n\n first_type& key() { return std::get<0>(*this); }\n const first_type& key() const { return std::get<0>(*this); }\n\n second_type& level() { return std::get<1>(*this); }\n const second_type& level() const { return std::get<1>(*this); }\n\n third_type tag() { return std::get<2>(*this); }\n const third_type tag() const { return std::get<2>(*this); }\n\n fourth_type timer() { return std::get<3>(*this); }\n const fourth_type timer() const { return std::get<3>(*this); }\n\n \/\/ serialization function\n template <typename Archive> void\n serialize(Archive& ar, const unsigned int \/*version*\/)\n {\n ar(cereal::make_nvp(\"timer.key\", std::get<0>(*this)),\n cereal::make_nvp(\"timer.level\", std::get<1>(*this)),\n cereal::make_nvp(\"timer.tag\", std::get<2>(*this)),\n cereal::make_nvp(\"timer.ref\", std::get<3>(*this)));\n }\n};\n\n\/\/----------------------------------------------------------------------------\/\/\n\nclass timing_manager\n{\npublic:\n template <typename _Key, typename _Mapped>\n using uomap = std::unordered_map<_Key, _Mapped>;\n\n typedef toast::util::timer toast_timer_t;\n typedef toast_timer_t::string_t string_t;\n typedef timer_tuple timer_tuple_t;\n typedef std::deque<timer_tuple_t> timer_list_t;\n typedef timer_list_t::iterator iterator;\n typedef timer_list_t::const_iterator const_iterator;\n typedef timer_list_t::size_type size_type;\n typedef uomap<uint64_t, toast_timer_t> timer_map_t;\n typedef toast_timer_t::ostream_t ostream_t;\n typedef toast_timer_t::ofstream_t ofstream_t;\n typedef toast::clock_type clock_type;\n\npublic:\n\t\/\/ Constructor and Destructors\n timing_manager();\n virtual ~timing_manager();\n\npublic:\n \/\/ Public static functions\n static timing_manager* instance();\n static void write_json(const string_t& _fname);\n\npublic:\n \/\/ Public member functions\n size_type size() const { return m_timer_list.size(); }\n void clear();\n\n toast_timer_t& timer(const string_t& key,\n const string_t& tag = \"cxx\",\n int32_t ncount = 0,\n int32_t nhash = 0);\n\n toast_timer_t& at(size_t i) { return m_timer_list.at(i).timer(); }\n\n \/\/ time a function with a return type and no arguments\n template <typename _Ret, typename _Func>\n _Ret time(const string_t& key, _Func);\n\n \/\/ time a function with a return type and arguments\n template <typename _Ret, typename _Func, typename... _Args>\n _Ret time(const string_t& key, _Func, _Args...);\n\n \/\/ time a function with no return type and no arguments\n template <typename _Func>\n void time(const string_t& key, _Func);\n\n \/\/ time a function with no return type and arguments\n template <typename _Func, typename... _Args>\n void time(const string_t& key, _Func, _Args...);\n\n \/\/ serialization function\n template <typename Archive> void\n serialize(Archive& ar, const unsigned int \/*version*\/);\n\n \/\/ iteration of timers\n iterator begin() { return m_timer_list.begin(); }\n const_iterator begin() const { return m_timer_list.cbegin(); }\n const_iterator cbegin() const { return m_timer_list.cbegin(); }\n\n iterator end() { return m_timer_list.end(); }\n const_iterator end() const { return m_timer_list.cend(); }\n const_iterator cend() const { return m_timer_list.cend(); }\n\n void report() const;\n void set_output_stream(ostream_t&);\n void set_output_stream(const string_t&);\n\nprotected:\n inline uint64_t string_hash(const string_t&) const;\n\nprivate:\n \/\/ Private functions\n ofstream_t* get_ofstream(ostream_t* m_os) const;\n void report(ostream_t*) const;\n\nprivate:\n\t\/\/ Private variables\n static timing_manager* fgInstance;\n \/\/ hashed string map for fast lookup\n timer_map_t m_timer_map;\n \/\/ ordered list for output (outputs in order of timer instantiation)\n timer_list_t m_timer_list;\n \/\/ output stream for total timing report\n ostream_t* m_report;\n};\n\n\/\/----------------------------------------------------------------------------\/\/\ninline void\ntiming_manager::clear()\n{\n m_timer_list.clear();\n m_timer_map.clear();\n details::base_timer::get_instance_count() = 0;\n details::base_timer::get_instance_hash() = 0;\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename _Ret, typename _Func>\ninline _Ret\ntiming_manager::time(const string_t& key, _Func func)\n{\n toast_timer_t& _t = this->instance()->timer(key);\n _t.start();\n _Ret _ret = func();\n _t.stop();\n return _ret;\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename _Ret, typename _Func, typename... _Args>\ninline _Ret\ntiming_manager::time(const string_t& key, _Func func, _Args... args)\n{\n toast_timer_t& _t = this->instance()->timer(key);\n _t.start();\n _Ret _ret = func(args...);\n _t.stop();\n return _ret;\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename _Func>\ninline void\ntiming_manager::time(const string_t& key, _Func func)\n{\n toast_timer_t& _t = this->instance()->timer(key);\n _t.start();\n func();\n _t.stop();\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename _Func, typename... _Args>\ninline void\ntiming_manager::time(const string_t& key, _Func func, _Args... args)\n{\n toast_timer_t& _t = this->instance()->timer(key);\n _t.start();\n func(args...);\n _t.stop();\n}\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename Archive>\ninline void\ntiming_manager::serialize(Archive& ar, const unsigned int \/*version*\/)\n{\n uint32_t omp_nthreads = get_max_threads();\n ar(cereal::make_nvp(\"omp_concurrency\", omp_nthreads));\n ar(cereal::make_nvp(\"timers\", m_timer_list));\n}\n\/\/----------------------------------------------------------------------------\/\/\ninline uint64_t\ntiming_manager::string_hash(const string_t& str) const\n{\n return std::hash<string_t>()(str);\n}\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ namespace util\n\n} \/\/ namespace toast\n\n#endif \/\/ timing_manager_hpp_\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <tclap\/CmdLine.h>\n\nusing namespace TCLAP;\n\nint main(int argc, char** argv)\n{\n\t\/\/ Wrap everything in a try block. Do this every time, \n\t\/\/ because exceptions will be thrown for problems. \n\ttry { \n\n\t\/\/ Define the command line object.\n\tCmdLine cmd(\"Command description message. This is a long multi-line message meant to test line wrapping. This is more text that doesn't really do anything besides take up lots of space that otherwise might be used for something real. That should be enough, don't you think?\", ' ', \"0.9\");\n\n\tvector<string> allowed;\n\tallowed.push_back(\"homer\");\n\tallowed.push_back(\"marge\");\n\tallowed.push_back(\"bart\");\n\tallowed.push_back(\"lisa\");\n\tallowed.push_back(\"maggie\");\n\n\tMultiArg<string> nameArg(\"n\",\"name\",\"Name to print. This is a long, nonsensical message to test line wrapping. Hopefully it works.\",true,allowed);\n\tcmd.add( nameArg );\n\n\tvector<int> iallowed;\n\tiallowed.push_back(1);\n\tiallowed.push_back(2);\n\tiallowed.push_back(3);\n\n\tUnlabeledMultiArg<int> intArg(\"times\",\"Number of times to print\",iallowed);\n\tcmd.add( intArg );\n\n\t\/\/ Parse the args.\n\tcmd.parse( argc, argv );\n\n\t\/\/ Get the value parsed by each arg. \n\tvector<int> num = intArg.getValue();\n\n\tfor ( unsigned int i = 0; i < num.size(); i++ )\n\t\tcout << \"Got num \" << num[i] << endl;\n\n\tvector<string> name = nameArg.getValue();\n\n\tfor ( unsigned int i = 0; i < name.size(); i++ )\n\t\tcout << \"Got name \" << name[i] << endl;\n\t\n\n\t} catch (ArgException e) \/\/ catch any exceptions\n\t{ cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << endl; }\n}\n\n<commit_msg>added more args to better test output printing<commit_after>#include <string>\n#include <tclap\/CmdLine.h>\n\nusing namespace TCLAP;\nusing namespace std;\n\nint main(int argc, char** argv)\n{\n\t\/\/ Wrap everything in a try block. Do this every time, \n\t\/\/ because exceptions will be thrown for problems. \n\ttry { \n\n\t\/\/ Define the command line object.\n\tCmdLine cmd(\"Command description message. This is a long multi-line message meant to test line wrapping. This is more text that doesn't really do anything besides take up lots of space that otherwise might be used for something real. That should be enough, don't you think?\", ' ', \"0.9\");\n\n\tvector<string> allowed;\n\tallowed.push_back(\"homer\");\n\tallowed.push_back(\"marge\");\n\tallowed.push_back(\"bart\");\n\tallowed.push_back(\"lisa\");\n\tallowed.push_back(\"maggie\");\n\n\tMultiArg<string> nameArg(\"n\",\"name\",\"Name to print. This is a long, nonsensical message to test line wrapping. Hopefully it works.\",true,allowed);\n\tcmd.add( nameArg );\n\n\tvector<int> iallowed;\n\tiallowed.push_back(1);\n\tiallowed.push_back(2);\n\tiallowed.push_back(3);\n\n\tUnlabeledMultiArg<int> intArg(\"times\",\"Number of times to print\",iallowed);\n\tcmd.add( intArg );\n\n\t\/\/ Ignore the names and comments! These args mean nothing (to this\n\t\/\/ program) and are here solely to take up space.\n ValueArg<int> gapCreate(\"f\",\"gapCreate\", \"The cost of creating a gap\",\n\t false, -10, \"negative int\");\n\tcmd.add( gapCreate );\n\n\tValueArg<int> gapExtend(\"g\",\"gapExtend\",\n\t\t\"The cost for each extension of a gap\", false, -2, \"negative int\");\n\tcmd.add( gapExtend );\n\n\tSwitchArg dna(\"d\",\"isDna\",\"The input sequences are DNA\", false);\n\tcmd.add( dna );\n\t\n\tValueArg<string> scoringMatrixName(\"s\",\"scoringMatrix\",\n\t\t\"Scoring Matrix name\", false,\"BLOSUM50\",\"name string\");\n\tcmd.add( scoringMatrixName );\n\t\n\tValueArg<string> seq1Filename (\"f\",\"filename1\",\n\t\t\"Sequence 1 filename (FASTA format)\", false,\"\",\"filename\");\n\tcmd.add( seq1Filename );\n\n\tValueArg<string> seq2Filename (\"F\",\"filename2\",\n\t\t\"Sequence 2 filename (FASTA format)\", false,\"\",\"filename\");\n\tcmd.add( seq2Filename );\n\n\tValueArg<float> lowerBound(\"b\",\"lowerBound\", \"lower percentage bound\",\n\t\tfalse,1.0,\"float lte 1\");\n\tcmd.add( lowerBound );\n\t\n\tValueArg<float> upperBound(\"u\",\"upperBound\", \"upper percentage bound\",\n\t\tfalse,1.0,\"float lte 1\");\n\tcmd.add( upperBound );\n\t\n\tValueArg<int> limit(\"l\",\"limit\",\"Max number of alignments allowed\",\n\t\tfalse, 1000,\"int\");\n\tcmd.add( limit );\n\t\n\t\/\/ Parse the args.\n\tcmd.parse( argc, argv );\n\n\t\/\/ Get the value parsed by each arg. \n\tvector<int> num = intArg.getValue();\n\n\tfor ( unsigned int i = 0; i < num.size(); i++ )\n\t\tcout << \"Got num \" << num[i] << endl;\n\n\tvector<string> name = nameArg.getValue();\n\n\tfor ( unsigned int i = 0; i < name.size(); i++ )\n\t\tcout << \"Got name \" << name[i] << endl;\n\t\n\n\t} catch (ArgException e) \/\/ catch any exceptions\n\t{ cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << endl; }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2015 Realm Inc.\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#ifndef REALM_UTIL_COMPILER_HPP\n#define REALM_UTIL_COMPILER_HPP\n\n#ifdef __has_cpp_attribute\n#define REALM_HAS_CCP_ATTRIBUTE(attr) __has_cpp_attribute(attr)\n#else\n#define REALM_HAS_CCP_ATTRIBUTE(attr) 0\n#endif\n\n#if REALM_HAS_CCP_ATTRIBUTE(clang::fallthrough)\n#define REALM_FALLTHROUGH [[clang::fallthrough]]\n#else\n#define REALM_FALLTHROUGH\n#endif\n\n#endif \/\/ REALM_UTIL_COMPILER_HPP\n<commit_msg>Fix a typo in the name of a #define.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2015 Realm Inc.\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#ifndef REALM_UTIL_COMPILER_HPP\n#define REALM_UTIL_COMPILER_HPP\n\n#ifdef __has_cpp_attribute\n#define REALM_HAS_CPP_ATTRIBUTE(attr) __has_cpp_attribute(attr)\n#else\n#define REALM_HAS_CPP_ATTRIBUTE(attr) 0\n#endif\n\n#if REALM_HAS_CPP_ATTRIBUTE(clang::fallthrough)\n#define REALM_FALLTHROUGH [[clang::fallthrough]]\n#else\n#define REALM_FALLTHROUGH\n#endif\n\n#endif \/\/ REALM_UTIL_COMPILER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 cpichard.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#if HAVE_ALEMBIC\n\n#include \"AlembicImporter.hpp\"\n\n#include <Alembic\/AbcGeom\/All.h>\n#include <Alembic\/AbcCoreFactory\/All.h>\n\n\nusing namespace Alembic::Abc;\nnamespace AbcG = Alembic::AbcGeom;\nusing namespace AbcG;\n\nnamespace openMVG {\nnamespace dataio {\n\n\/\/ Top down insertion of 3d objects\n\nvoid AlembicImporter::visitObject(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)\n{\n using namespace openMVG::geometry;\n using namespace openMVG::cameras;\n using namespace openMVG::sfm;\n\n const MetaData& md = iObj.getMetaData();\n if(IPoints::matches(md) && (flags_part & sfm::ESfM_Data::STRUCTURE))\n {\n IPoints points(iObj, kWrapExisting);\n IPointsSchema ms = points.getSchema();\n P3fArraySamplePtr positions = ms.getValue().getPositions();\n\n \/\/@todo use positions->get() and positions->size());\n \/\/@todo put the points somewhere...\n }\n else if(IXform::matches(md))\n {\n IXform xform(iObj, kWrapExisting);\n XformSample xs;\n xform.getSchema().get(xs);\n mat *= xs.getMatrix();\n }\n else if(ICamera::matches(md) && (flags_part & sfm::ESfM_Data::EXTRINSICS))\n {\n \/\/ OpenMVG Camera\n Mat3 cam_r;\n cam_r(0,0) = mat[0][0];\n cam_r(0,1) = mat[0][1];\n cam_r(0,2) = mat[0][2];\n cam_r(1,0) = mat[1][0];\n cam_r(1,1) = mat[1][1];\n cam_r(1,2) = mat[1][2];\n cam_r(2,0) = mat[2][0];\n cam_r(2,1) = mat[2][1];\n cam_r(2,2) = mat[2][2];\n Vec3 cam_t;\n cam_t(0) = mat[3][0];\n cam_t(1) = mat[3][1];\n cam_t(2) = mat[3][2];\n Pose3 pose(cam_r, cam_t);\n \n ICamera camera(iObj, kWrapExisting);\n ICameraSchema cs = camera.getSchema();\n CameraSample camSample = cs.getValue();\n\n double width = camSample.getHorizontalAperture(); \/\/ TODO\n double height = camSample.getVerticalAperture();\n\n Pinhole_Intrinsic intrinsic(\n width, height,\n camSample.getFocalLength(), \/\/ TODO: pix\n camSample.getHorizontalFilmOffset(), camSample.getVerticalFilmOffset());\n\n IndexT id_view = sfmdata.GetViews().size(); \/\/ TODO real index\n IndexT id_pose = sfmdata.GetPoses().size();\n IndexT id_intrinsics = sfmdata.GetIntrinsics().size();\n \n const std::string objectName = iObj.getName();\n\n sfmdata.views.emplace(id_view, std::make_shared<View>(objectName, id_view, id_pose, id_intrinsics, width, height));\n sfmdata.poses.emplace(id_pose, pose);\n sfmdata.intrinsics.emplace(id_intrinsics, std::make_shared<Pinhole_Intrinsic>(intrinsic));\n }\n\n \/\/ Recurse\n for(size_t i = 0; i < iObj.getNumChildren(); i++)\n {\n visitObject(iObj.getChild(i), mat, sfmdata, flags_part);\n }\n}\n\nAlembicImporter::AlembicImporter(const std::string &filename)\n{\n Alembic::AbcCoreFactory::IFactory factory;\n Alembic::AbcCoreFactory::IFactory::CoreType coreType;\n Abc::IArchive archive = factory.getArchive(filename, coreType);\n\n \/\/ TODO : test if archive is correctly opened\n _rootEntity = archive.getTop();\n}\n\nvoid AlembicImporter::populate(sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)\n{\n \/\/ TODO : handle the case where the archive wasn't correctly opened\n M44d xformMat;\n visitObject(_rootEntity, xformMat, sfmdata, flags_part);\n\n \/\/ TODO: fusion of common intrinsics\n}\n\n} \/\/ namespace data_io\n} \/\/ namespace openMVG\n#endif \/\/ WITH_ALEMBIC\n\n<commit_msg>[alembic] remove 'camera_' prefix if exists<commit_after>\/\/ Copyright (c) 2015 cpichard.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#if HAVE_ALEMBIC\n\n#include \"AlembicImporter.hpp\"\n\n#include <Alembic\/AbcGeom\/All.h>\n#include <Alembic\/AbcCoreFactory\/All.h>\n\n\nusing namespace Alembic::Abc;\nnamespace AbcG = Alembic::AbcGeom;\nusing namespace AbcG;\n\nnamespace openMVG {\nnamespace dataio {\n\n\/\/ Top down insertion of 3d objects\n\nvoid AlembicImporter::visitObject(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)\n{\n using namespace openMVG::geometry;\n using namespace openMVG::cameras;\n using namespace openMVG::sfm;\n\n const MetaData& md = iObj.getMetaData();\n if(IPoints::matches(md) && (flags_part & sfm::ESfM_Data::STRUCTURE))\n {\n IPoints points(iObj, kWrapExisting);\n IPointsSchema ms = points.getSchema();\n P3fArraySamplePtr positions = ms.getValue().getPositions();\n\n \/\/@todo use positions->get() and positions->size());\n \/\/@todo put the points somewhere...\n }\n else if(IXform::matches(md))\n {\n IXform xform(iObj, kWrapExisting);\n XformSample xs;\n xform.getSchema().get(xs);\n mat *= xs.getMatrix();\n }\n else if(ICamera::matches(md) && (flags_part & sfm::ESfM_Data::EXTRINSICS))\n {\n \/\/ OpenMVG Camera\n Mat3 cam_r;\n cam_r(0,0) = mat[0][0];\n cam_r(0,1) = mat[0][1];\n cam_r(0,2) = mat[0][2];\n cam_r(1,0) = mat[1][0];\n cam_r(1,1) = mat[1][1];\n cam_r(1,2) = mat[1][2];\n cam_r(2,0) = mat[2][0];\n cam_r(2,1) = mat[2][1];\n cam_r(2,2) = mat[2][2];\n Vec3 cam_t;\n cam_t(0) = mat[3][0];\n cam_t(1) = mat[3][1];\n cam_t(2) = mat[3][2];\n Pose3 pose(cam_r, cam_t);\n \n ICamera camera(iObj, kWrapExisting);\n ICameraSchema cs = camera.getSchema();\n CameraSample camSample = cs.getValue();\n\n double width = camSample.getHorizontalAperture(); \/\/ TODO\n double height = camSample.getVerticalAperture();\n\n Pinhole_Intrinsic intrinsic(\n width, height,\n camSample.getFocalLength(), \/\/ TODO: pix\n camSample.getHorizontalFilmOffset(), camSample.getVerticalFilmOffset());\n\n IndexT id_view = sfmdata.GetViews().size(); \/\/ TODO real index\n IndexT id_pose = sfmdata.GetPoses().size();\n IndexT id_intrinsics = sfmdata.GetIntrinsics().size();\n \n std::string objectName = iObj.getName();\n \/\/ For readability in exporter we add a prefix 'camera_' for each view\n if(objectName.substr(0,7) == \"camera_\")\n objectName = objectName.substr(7);\n\n sfmdata.views.emplace(id_view, std::make_shared<View>(objectName, id_view, id_pose, id_intrinsics, width, height));\n sfmdata.poses.emplace(id_pose, pose);\n sfmdata.intrinsics.emplace(id_intrinsics, std::make_shared<Pinhole_Intrinsic>(intrinsic));\n }\n\n \/\/ Recurse\n for(size_t i = 0; i < iObj.getNumChildren(); i++)\n {\n visitObject(iObj.getChild(i), mat, sfmdata, flags_part);\n }\n}\n\nAlembicImporter::AlembicImporter(const std::string &filename)\n{\n Alembic::AbcCoreFactory::IFactory factory;\n Alembic::AbcCoreFactory::IFactory::CoreType coreType;\n Abc::IArchive archive = factory.getArchive(filename, coreType);\n\n \/\/ TODO : test if archive is correctly opened\n _rootEntity = archive.getTop();\n}\n\nvoid AlembicImporter::populate(sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)\n{\n \/\/ TODO : handle the case where the archive wasn't correctly opened\n M44d xformMat;\n visitObject(_rootEntity, xformMat, sfmdata, flags_part);\n\n \/\/ TODO: fusion of common intrinsics\n}\n\n} \/\/ namespace data_io\n} \/\/ namespace openMVG\n#endif \/\/ WITH_ALEMBIC\n\n<|endoftext|>"} {"text":"<commit_before>#include \"kfold.h\"\n#include <vector>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\/**\nClass to generate the vectors from a dataset for kfold cross validation.\ndata is the whole dataset\nnumGenes is the number of rows\nclassSizes is a vector containing the 2 classSizes\nk is the number of folds\n**\/\nkfold::kfold( vector<double> & data, int numGenes, vector<int> & classSizes, int k){\n this->nGenes = numGenes;\n this->orig_data = &data;\n this->class1size = classSizes[0];\n this->class2size = classSizes[1];\n this->k = k;\n this->it = 0;\n this->samp_vector = generateSampleVector();\n this->next_fold = 0;\n this->generated_data = NULL;\n this->generated_test = NULL;\n this->curr_class = -1;\n this->curr_classSizes = classSizes;\n}\n\nkfold::~kfold(){\n delete generated_data;\n delete generated_test;\n orig_data = NULL;\n}\n\/**\nGenerates a vector containing [0,...,n-1] that has been shuffled.\n**\/\nvector<int> kfold::generateSampleVector(){\n \n srand(time(NULL));\n if (k > class1size + class2size){\n k = class1size + class2size;\n \/\/k is bigger than our sample size, so lets do loocv \n }\n vector<int> samples(class1size+class2size);\n for(int i = 0;i<class1size+class2size;i++){\n samples[i] = i; \n }\n for(int i=class1size+class2size-1;i>0;i--){\/\/fisher-yates shuffle\n int j = rand() % i;\n int temp = samples[i];\n samples[i] = samples[j];\n samples[j] = temp;\n }\n \n if (checkFoldsGood(samples)){\n return samples;\n } else {\n \/\/all our pigeons are in the same hole.\n \/\/shuffle shuffle\n return generateSampleVector();\n } \n\n}\n\/**\nChecks that we will not have a training set without any samples for a class.\n\n**\/\nbool kfold::checkFoldsGood( vector<int> & sample){\n int fsize = getFoldSize();\n \n bool good = true;\n\n if (class1size > fsize && class2size > fsize) return good;\/\/shortcircuit pigeon\n int class1counter, class2counter;\n for( int i = 0; i < sample.size();i++ ){\n \/\/the only way for this to happen is if all of one class ends up in a\n \/\/fold\n if (i%fsize == 0){\/\/new fold\n class1counter = 0;\n class2counter = 0;\n }\n \/\/size of class[1||2] in this fold \n if(sample.at(i) < class1size){\/\/class1sample\n class1counter++;\n } else {\/\/class2sample\n class2counter++;\n }\n if ((class1counter == class1size) \n || (class2counter == class2size)){\n \/\/Oh noes!!!!All our eggs are in one basket.\n good = false;\n break;\n }\n }\n return good;\n}\n\/**\nReturns a vector that contains the training set for the next set of learners\nReturns null if there are no more training sets to be generated.\n\nNOTE: on each call to this function the previous training set is deleted!!\nYou will need to copy the vector if you want to keep it.\n**\/\nvector<double> * kfold::getNextTrainingSet(){\n next_fold = next_fold + getFoldSize();\n curr_classSizes[0] = 0;\n curr_classSizes[1] = 0;\n \n\n if (next_fold > samp_vector.size()) next_fold = samp_vector.size();\n if (samp_vector.size() == it) return NULL;\n\n\n delete generated_data;\n generated_data = new vector<double>();\n for(int base_i = 0; base_i<class1size+class2size;base_i++){\n if(trainingData(base_i) ){\n curr_classSizes[base_i >= class1size]++; \n for(int j=0; j<nGenes;j++){\n generated_data->push_back(orig_data->at(base_i*nGenes + j));\n }\n }\n \n }\n return generated_data;\n}\n\/**\nReturns the current test vector.\nReturns null if their are no more test vectors for the current training set\n\nNOTE: on each call to this function the previous test vector is deleted!!\nYou will need to copy the vector if you want to keep it.\n**\/\nvector<double> * kfold::getNextTestVector(){ \n delete generated_test;\n if(it == next_fold){\n curr_class = -1;\n generated_test = NULL;\n return NULL;\n }\n generated_test = new vector<double>();\n int next_sample = samp_vector[it];\n if (next_sample < class1size){\n curr_class = 0;\n } else {\n curr_class = 1;\n }\n int col = nGenes*next_sample;\n \n for(int i = 0; i<nGenes; i++){\n generated_test->push_back(orig_data->at(col + i));\n }\n it++;\n return generated_test;\n}\nvector<int> kfold::getClassSizes(){\n return curr_classSizes;\n}\n\nint kfold::getTestVectorClass(){\n return curr_class;\n}\n\/**\nGiven a sample number\nreturn true if sample is in training set\nreturn false is sample is to be used for crossvalidation\n**\/\nbool kfold::trainingData(int sample){\n int ksize = getFoldSize();\n int temp_it = it;\n for(int i=it; i < next_fold;i++){\n if(samp_vector[i] == sample){\n return false;\n }\n }\n return true;\n}\nint kfold::getFoldSize(){\n int ksize = (class1size+class2size)\/k;\n if((class1size+class2size)%k > 0){\n ksize++;\n }\n return ksize; \n}\nvoid printVect(vector<double> a, int rows){\n for(int i=0;i<a.size();i++){\n if (i%rows == 0){cout << endl;}\n cout << a.at(i) << \" \";\n }\n cout << endl;\n}\n\/**\nint main(){\n\n vector<double> data;\n vector<int> cs;\n \n int c1=5;\n int c2 = 5;\n int nGenes = 10;\n float base = 0.0;\n for (int i=0; i<c1;i++){\n for(int j=0;j<nGenes;j++){\n base = 0.0;\n data.push_back(i*nGenes + j + base);\n }\n \n }\n for (int i=c1; i<c1+c2;i++){\n for(int j=0;j<nGenes;j++){\n base = 0.5;\n data.push_back(i*nGenes + j + base);\n }\n \n }\n cs.push_back(c1);\n cs.push_back(c2);\n kfold k(data,nGenes, cs, 3);\n vector<double> * ts;\n vector<double> * ls;\n ts = k.getNextTrainingSet();\n int counter = 0;\n while(ts != NULL){\n counter++;\n cout <<endl<< \"ts\" << endl;\n printVect((*ts), nGenes);\n ls = k.getNextTestVector();\n while(ls != NULL){\n cout << endl<< \"ls\" << endl;\n printVect((*ls), nGenes);\n cout << \"class=\" << k.getTestVectorClass()<<endl;\n cout << \"cs1=\" <<k.getClassSizes()[0];\n cout << \"cs2=\" <<k.getClassSizes()[1];\n k.getTestVectorClass();\n ls = k.getNextTestVector();\n }\n ts = k.getNextTrainingSet();\n }\n\n cout << \"times ran = \" << counter << endl;\n}**\/\n<commit_msg>Cleanup<commit_after>#include \"kfold.h\"\n#include <vector>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\/**\nClass to generate the vectors from a dataset for kfold cross validation.\ndata is the whole dataset\nnumGenes is the number of rows\nclassSizes is a vector containing the 2 classSizes\nk is the number of folds\n**\/\nkfold::kfold( vector<double> & data, int numGenes, vector<int> & classSizes, int k){\n this->nGenes = numGenes;\n this->orig_data = &data;\n this->class1size = classSizes[0];\n this->class2size = classSizes[1];\n this->k = k;\n this->it = 0;\n this->samp_vector = generateSampleVector();\n this->next_fold = 0;\n this->generated_data = NULL;\n this->generated_test = NULL;\n this->curr_class = -1;\n this->curr_classSizes = classSizes;\n}\n\nkfold::~kfold(){\n delete generated_data;\n delete generated_test;\n orig_data = NULL;\n}\n\/**\nGenerates a vector containing [0,...,n-1] that has been shuffled.\n**\/\nvector<int> kfold::generateSampleVector(){\n \n srand(time(NULL));\n if (k > class1size + class2size){\n k = class1size + class2size;\n \/\/k is bigger than our sample size, so lets do loocv \n }\n vector<int> samples(class1size+class2size);\n for(int i = 0;i<class1size+class2size;i++){\n samples[i] = i; \n }\n for(int i=class1size+class2size-1;i>0;i--){\/\/fisher-yates shuffle\n int j = rand() % i;\n int temp = samples[i];\n samples[i] = samples[j];\n samples[j] = temp;\n }\n \n if (checkFoldsGood(samples)){\n return samples;\n } else {\n \/\/all our pigeons are in the same hole.\n \/\/shuffle shuffle\n return generateSampleVector();\n } \n\n}\n\/**\nChecks that we will not have a training set without any samples for a class.\n\n**\/\nbool kfold::checkFoldsGood( vector<int> & sample){\n int fsize = getFoldSize();\n \n bool good = true;\n\n if (class1size > fsize && class2size > fsize) return good;\/\/shortcircuit pigeon\n int class1counter=0;\n int class2counter=0;\n for(unsigned int i = 0; i < sample.size();i++ ){\n \/\/the only way for this to happen is if all of one class ends up in a\n \/\/fold\n if (i%fsize == 0){\/\/new fold\n class1counter = 0;\n class2counter = 0;\n }\n \/\/size of class[1||2] in this fold \n if(sample.at(i) < class1size){\/\/class1sample\n class1counter++;\n } else {\/\/class2sample\n class2counter++;\n }\n if ((class1counter == class1size) \n || (class2counter == class2size)){\n \/\/Oh noes!!!!All our eggs are in one basket.\n good = false;\n break;\n }\n }\n return good;\n}\n\/**\nReturns a vector that contains the training set for the next set of learners\nReturns null if there are no more training sets to be generated.\n\nNOTE: on each call to this function the previous training set is deleted!!\nYou will need to copy the vector if you want to keep it.\n**\/\nvector<double> * kfold::getNextTrainingSet(){\n next_fold = next_fold + getFoldSize();\n curr_classSizes[0] = 0;\n curr_classSizes[1] = 0;\n \n\n if (next_fold > (int)samp_vector.size()) next_fold = (int)samp_vector.size();\n if ((int)samp_vector.size() == it) return NULL;\n\n\n delete generated_data;\n generated_data = new vector<double>();\n for(int base_i = 0; base_i<class1size+class2size;base_i++){\n if(trainingData(base_i) ){\n curr_classSizes[base_i >= class1size]++; \n for(int j=0; j<nGenes;j++){\n generated_data->push_back(orig_data->at(base_i*nGenes + j));\n }\n }\n \n }\n return generated_data;\n}\n\/**\nReturns the current test vector.\nReturns null if their are no more test vectors for the current training set\n\nNOTE: on each call to this function the previous test vector is deleted!!\nYou will need to copy the vector if you want to keep it.\n**\/\nvector<double> * kfold::getNextTestVector(){ \n delete generated_test;\n if(it == next_fold){\n curr_class = -1;\n generated_test = NULL;\n return NULL;\n }\n generated_test = new vector<double>();\n int next_sample = samp_vector[it];\n if (next_sample < class1size){\n curr_class = 0;\n } else {\n curr_class = 1;\n }\n int col = nGenes*next_sample;\n \n for(int i = 0; i<nGenes; i++){\n generated_test->push_back(orig_data->at(col + i));\n }\n it++;\n return generated_test;\n}\nvector<int> kfold::getClassSizes(){\n return curr_classSizes;\n}\n\nint kfold::getTestVectorClass(){\n return curr_class;\n}\n\/**\nGiven a sample number\nreturn true if sample is in training set\nreturn false is sample is to be used for crossvalidation\n**\/\nbool kfold::trainingData(int sample){\n for(int i=it; i < next_fold;i++){\n if(samp_vector[i] == sample){\n return false;\n }\n }\n return true;\n}\nint kfold::getFoldSize(){\n int ksize = (class1size+class2size)\/k;\n if((class1size+class2size)%k > 0){\n ksize++;\n }\n return ksize; \n}\nvoid printVect(vector<double> a, int rows){\n for(unsigned int i=0;i<a.size();i++){\n if (i%rows == 0){cout << endl;}\n cout << a.at(i) << \" \";\n }\n cout << endl;\n}\n\/**\nint main(){\n\n vector<double> data;\n vector<int> cs;\n \n int c1=5;\n int c2 = 5;\n int nGenes = 10;\n float base = 0.0;\n for (int i=0; i<c1;i++){\n for(int j=0;j<nGenes;j++){\n base = 0.0;\n data.push_back(i*nGenes + j + base);\n }\n \n }\n for (int i=c1; i<c1+c2;i++){\n for(int j=0;j<nGenes;j++){\n base = 0.5;\n data.push_back(i*nGenes + j + base);\n }\n \n }\n cs.push_back(c1);\n cs.push_back(c2);\n kfold k(data,nGenes, cs, 3);\n vector<double> * ts;\n vector<double> * ls;\n ts = k.getNextTrainingSet();\n int counter = 0;\n while(ts != NULL){\n counter++;\n cout <<endl<< \"ts\" << endl;\n printVect((*ts), nGenes);\n ls = k.getNextTestVector();\n while(ls != NULL){\n cout << endl<< \"ls\" << endl;\n printVect((*ls), nGenes);\n cout << \"class=\" << k.getTestVectorClass()<<endl;\n cout << \"cs1=\" <<k.getClassSizes()[0];\n cout << \"cs2=\" <<k.getClassSizes()[1];\n k.getTestVectorClass();\n ls = k.getNextTestVector();\n }\n ts = k.getNextTrainingSet();\n }\n\n cout << \"times ran = \" << counter << endl;\n}**\/\n<|endoftext|>"} {"text":"<commit_before>#include \"MatrixTransform.h\"\n#include \"Group.h\"\n\n#include <osg\/Notify>\n\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/Registry>\n\nusing namespace osg;\nusing namespace osgDB;\n\nclass IVEReaderWriter : public ReaderWriter\n{\n public:\n virtual const char* className() { return \"IVE Reader\/Writer\"; }\n\n virtual bool acceptsExtension(const std::string& extension)\n {\n return equalCaseInsensitive(extension,\"ive\");\n }\n\n virtual ReadResult readNode(const std::string& fileName, const Options* options)\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n \n std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);\n return readNode(istream,options);\n }\n \n virtual ReadResult readNode(std::istream& fin, const Options*)\n {\n\t try{\n \/\/ Create datainputstream.\n ive::DataInputStream in(&fin);\n\n return in.readNode();\n\t }\n\t catch(ive::Exception e)\n {\n\t std::cout<<\"Error reading file: \"<< e.getError()<<std::endl;\n\t return ReadResult::FILE_NOT_HANDLED;\n\t }\n return 0;\n }\n\n virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options)\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n\n std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);\n WriteResult result = writeNode(node, fout, options);\n fout.close();\n return result;\n }\n \n virtual WriteResult writeNode(const Node& node,std::ostream& fout, const osgDB::ReaderWriter::Options*)\n {\n try\n {\n ive::DataOutputStream out(&fout);\n \n out.writeNode(const_cast<osg::Node*>(&node));\n return WriteResult::FILE_SAVED;\n }\n catch(ive::Exception e)\n {\n\t osg::notify(osg::WARN)<<\"Error parsing OSG file: \"<< e.getError() << std::endl;\t\t\t\n }\n return WriteResult::FILE_NOT_HANDLED;\n\n }\n\n};\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nRegisterReaderWriterProxy<IVEReaderWriter> g_IVEReaderWriterProxy;\n<commit_msg>Added #ifdef IVE_CATCH_EXCEPTIONS to allow catching of exceptions to be turned off for debugging purposes.<commit_after>#include \"MatrixTransform.h\"\n#include \"Group.h\"\n\n#include <osg\/Notify>\n\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/Registry>\n\nusing namespace osg;\nusing namespace osgDB;\n\nclass IVEReaderWriter : public ReaderWriter\n{\n public:\n virtual const char* className() { return \"IVE Reader\/Writer\"; }\n\n virtual bool acceptsExtension(const std::string& extension)\n {\n return equalCaseInsensitive(extension,\"ive\");\n }\n\n virtual ReadResult readNode(const std::string& fileName, const Options* options)\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n \n std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);\n return readNode(istream,options);\n }\n \n virtual ReadResult readNode(std::istream& fin, const Options*)\n {\n #define IVE_CATCH_EXCEPTIONS\n #ifdef IVE_CATCH_EXCEPTIONS\n\t try{\n #endif\n \/\/ Create datainputstream.\n ive::DataInputStream in(&fin);\n\n return in.readNode();\n #ifdef IVE_CATCH_EXCEPTIONS\n\t }\n\t catch(ive::Exception e)\n {\n\t std::cout<<\"Error reading file: \"<< e.getError()<<std::endl;\n\t return ReadResult::FILE_NOT_HANDLED;\n\t }\n return 0;\n #endif\n }\n\n virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options)\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n\n std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);\n WriteResult result = writeNode(node, fout, options);\n fout.close();\n return result;\n }\n \n virtual WriteResult writeNode(const Node& node,std::ostream& fout, const osgDB::ReaderWriter::Options*)\n {\n try\n {\n ive::DataOutputStream out(&fout);\n \n out.writeNode(const_cast<osg::Node*>(&node));\n return WriteResult::FILE_SAVED;\n }\n catch(ive::Exception e)\n {\n\t osg::notify(osg::WARN)<<\"Error parsing OSG file: \"<< e.getError() << std::endl;\t\t\t\n }\n return WriteResult::FILE_NOT_HANDLED;\n\n }\n\n};\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nRegisterReaderWriterProxy<IVEReaderWriter> g_IVEReaderWriterProxy;\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <osg\/Notify>\n\n#include <osgDB\/Input>\n#include <osgDB\/Registry>\n#include <osgDB\/FileUtils>\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/ReadFile>\n#include <osgDB\/WriteFile>\n#include <osgDB\/FileUtils>\n#include <osgDB\/Archive>\n#include <osg\/MatrixTransform>\n#include <osg\/Group>\n#include <osg\/Timer>\n#include \"sockinet.h\"\n\n \/*\n * Semantics:\n * Two methods for using the .net loader.\n * 1) Add a hostname prefix and a '.net' suffix on a model when passing \n * to osgDB::readNodeFile() \n * e.g: osgDB::readNodeFile( \"openscenegraph.org:cow.osg.net\" );\n *\n * 2) Explicitely load the .net plugin and pass the plugin options including\n * hostname=<hostname>\n *\n * Method #1 takes precedence. SO, if the hostname option is passed the\n * plugin, but the name also contains a hostname prefix, the hostname\n * prefix on the file name will override the option\n *\n * Plugin options:\n * hostname=<hostname> - Specify the host where the data file is to \n * be fetched from.\n *\n * prefix=<prefix> - Specify a server directory to prefix the \n * file name with.\n * \n * local_cache_dir=<dir> - Specify a directory in which to cache files\n * on the local machine once they've been fetched. \n * This directory is also searched before fetching\n * the file from the server when Read mode is \n * enabled on the cache.\n *\n * cache_mode=<mode> - Set the mode for the local cache if local_cache\n * was specified. If local_cache was not specified\n * this directive is ignored. <mode> may\n * be specified with ReadOnly, WriteOnly, or\n * ReadWrite. Behavior for the different modes is\n * defined as:\n *\n * ReadOnly - When retrieving files, cache is \n * searched first, and if the file is\n * not present, it is fetched from the\n * server. If it is fetched from the\n * server it is not stored in local cache\n *\n * WriteOnly - When retrieving files, cache is not\n * searched, file is always retrieved\n * from the server and always written to\n * cache.\n *\n * ReadWrite - (the default). When retrieving files\n * cache is searched first, if file is\n * not present in cache, it is fetched from\n * the server. If fetched, it is written\n * to cache.\n *\n *\/\n\n\nclass NetReader : public osgDB::ReaderWriter\n{\n public:\n NetReader() {}\n \n virtual const char* className() const { return \"HTTP Protocol Model Reader\"; }\n \n virtual bool acceptsExtension(const std::string& extension) const\n {\n return osgDB::equalCaseInsensitive(extension,\"net\");\n }\n\n enum ObjectType\n {\n OBJECT,\n ARCHIVE,\n IMAGE,\n HEIGHTFIELD,\n NODE\n };\n \n virtual ReadResult openArchive(const std::string& fileName,ArchiveStatus status, unsigned int , const Options* options) const\n {\n if (status!=READ) return ReadResult(ReadResult::FILE_NOT_HANDLED);\n else return readFile(ARCHIVE,fileName,options);\n }\n\n virtual ReadResult readObject(const std::string& fileName, const Options* options) const\n {\n return readFile(OBJECT,fileName,options);\n }\n \n virtual ReadResult readImage(const std::string& fileName, const Options *options) const\n {\n return readFile(IMAGE,fileName,options);\n }\n\n virtual ReadResult readHeightField(const std::string& fileName, const Options *options) const\n {\n return readFile(HEIGHTFIELD,fileName,options);\n }\n\n virtual ReadResult readNode(const std::string& fileName, const Options *options) const\n {\n return readFile(NODE,fileName,options);\n }\n\n ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options) const\n {\n switch(objectType)\n {\n case(OBJECT): return rw->readObject(fin,options);\n case(ARCHIVE): return rw->openArchive(fin,options);\n case(IMAGE): return rw->readImage(fin,options);\n case(HEIGHTFIELD): return rw->readHeightField(fin,options);\n case(NODE): return rw->readNode(fin,options);\n default: break;\n }\n return ReadResult::FILE_NOT_HANDLED;\n }\n\n virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options) const\n {\n osg::Timer_t start = osg::Timer::instance()->tick();\n\n osg::notify(osg::NOTICE) << \"osgPlugin .net: start load\" << inFileName << std::endl;\n\n std::string hostname;\n std::string serverPrefix;\n std::string localCacheDir;\n int port = 80;\n\n enum CacheMode {\n Read = 1,\n Write = 2,\n ReadWrite = 3\n };\n\n CacheMode cacheMode = ReadWrite;\n\n if (options)\n {\n std::istringstream iss(options->getOptionString());\n std::string opt;\n while (iss >> opt) \n {\n int index = opt.find( \"=\" );\n if( opt.substr( 0, index ) == \"hostname\" ||\n opt.substr( 0, index ) == \"HOSTNAME\" )\n {\n hostname = opt.substr( index+1 );\n }\n else if( opt.substr( 0, index ) == \"port\" ||\n opt.substr( 0, index ) == \"PORT\" )\n {\n port = atoi( opt.substr(index+1).c_str() );\n }\n else if( opt.substr( 0, index ) == \"server_prefix\" ||\n opt.substr( 0, index ) == \"SERVER_PREFIX\" ||\n opt.substr( 0, index ) == \"prefix\" ||\n opt.substr( 0, index ) == \"PREFIX\" )\n {\n serverPrefix = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"local_cache_dir\" ||\n opt.substr( 0, index ) == \"LOCAL_CACHE_DIR\" )\n {\n localCacheDir = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"cache_mode\" ||\n opt.substr( 0, index ) == \"CACHE_MODE\" )\n {\n if( opt.substr(index+1) == \"ReadOnly\" )\n cacheMode = Read;\n else if( opt.substr(index+1) == \"WriteOnly\" )\n cacheMode = Write;\n else if( opt.substr(index+1) == \"ReadWrite\" )\n cacheMode = ReadWrite;\n else\n osg::notify(osg::WARN) << \n \"NET plug-in warning: cache_mode \" << opt.substr(index+1) << \n \" not understood. Defaulting to ReadWrite.\" << std::endl;\n }\n }\n }\n\n ReadResult readResult = ReadResult::FILE_NOT_HANDLED;\n\n \/* * we accept all extensions\n std::string ext = osgDB::getFileExtension(inFileName);\n if (!acceptsExtension(ext))\n return ReadResult::FILE_NOT_HANDLED;\n *\/\n\n\n std::string fileName;\n int index = inFileName.find(\":\");\n \/\/ If we haven't been given a hostname as an option\n \/\/ and it hasn't been prefixed to the name, we fail\n if( index != -1 )\n {\n hostname = inFileName.substr( 0, index);\n \/\/ need to strip the inFileName of the hostname prefix\n fileName = inFileName.substr( index+1 );\n }\n else\n {\n if( hostname.empty() )\n return ReadResult::FILE_NOT_HANDLED;\n else\n fileName = inFileName;\n }\n\n \/\/ Let's also strip the possible .net extension\n if( osgDB::getFileExtension( fileName ) == \"net\" )\n {\n int rindex = fileName.rfind( \".\" );\n fileName = fileName.substr( 0, rindex );\n }\n\n if( !serverPrefix.empty() )\n fileName = serverPrefix + '\/' + fileName;\n\n osg::notify(osg::WARN) << \"hostname \" << hostname << std::endl;\n osg::notify(osg::WARN) << \"filename \" << fileName << std::endl;\n\n\n \/\/ Invoke the reader corresponding to the extension\n osgDB::ReaderWriter *reader = \n osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));\n if( reader == 0L )\n return ReadResult::FILE_NOT_HANDLED;\n\n \/\/ Before we go to the network, lets see if it is in local cache, if cache\n \/\/ was specified and Read bit is set\n if( !localCacheDir.empty() && (cacheMode & Read) )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::fileExists( cacheFile ))\n {\n std::ifstream in(cacheFile.c_str());\n readResult = readFile(objectType, reader, in, options );\n\n in.close();\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from local cache.\" << std::endl;\n return readResult;\n }\n }\n\n \/\/ Fetch from the network\n osg::ref_ptr<iosockinet> sio = new iosockinet(sockbuf::sock_stream);\n try {\n sio->rdbuf()->connect( hostname.c_str(), port );\n }\n catch( sockerr e )\n {\n osg::notify(osg::WARN) << \"osgPlugin .net reader: Unable to connect to host \" << hostname << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n\n *sio << \"GET \/\" << fileName << \" HTTP\/1.1\\n\" << \"Host: \" << hostname << \"\\n\\n\";\n sio->flush();\n \n char linebuff[256];\n do\n {\n sio->getline( linebuff, sizeof( linebuff ));\n\n std::istringstream iss(linebuff);\n std::string directive;\n iss >> directive;\n if( directive.substr(0,4) == \"HTTP\" )\n {\n iss >> directive;\n \/\/ Code 200. We be ok.\n if( directive == \"200\" )\n ;\n \/\/ Code 400 Bad Request\n else if( directive == \"400\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 400 - Bad Request\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 401 Bad Request\n else if( directive == \"401\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 401 - Unauthorized Access\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 403 Bad Request\n else if( directive == \"403\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 403 - Access Forbidden\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 404 File not found\n else if( directive == \"404\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 404 - File Not Found\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 405 Method not allowed\n else if( directive == \"405\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 405 - Method Not Allowed\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ There's more....\n }\n\n } while( linebuff[0] != '\\r' );\n\n \/\/ code for setting up the database path so that any paged\n \/\/ databases can be automatically located. \n osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);\n if (!local_opt) local_opt = new Options;\n\n if (local_opt.valid() && local_opt->getDatabasePathList().empty())\n {\n local_opt->setDatabasePath(osgDB::getFilePath(inFileName));\n }\n \n \n\n\n if( reader != 0L )\n readResult = readFile(objectType, reader, *sio, local_opt.get() );\n\n double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from server. in\" << ms <<\" ms\"<< std::endl;\n\n if (objectType==ARCHIVE && readResult.validArchive())\n {\n \/\/ attach the socket istream to the archive to keep it alive.\n osgDB::Archive* archive = readResult.getArchive();\n archive->setUserData(sio.get());\n }\n\n if( !localCacheDir.empty() && cacheMode & Write )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::makeDirectoryForFile( cacheFile ) )\n {\n \n switch(objectType)\n {\n case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );\n case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );\n case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );\n case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;\n default: break;\n }\n \n \n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" stored to local cache.\" << std::endl;\n }\n }\n\n return readResult;\n }\n \n};\n\nosgDB::RegisterReaderWriterProxy<NetReader> g_netReader_Proxy;\n\n \n\n\n<commit_msg>Fixed osgDB:: prefix for Windows build<commit_after>#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <osg\/Notify>\n\n#include <osgDB\/Input>\n#include <osgDB\/Registry>\n#include <osgDB\/FileUtils>\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/ReadFile>\n#include <osgDB\/WriteFile>\n#include <osgDB\/FileUtils>\n#include <osgDB\/Archive>\n#include <osg\/MatrixTransform>\n#include <osg\/Group>\n#include <osg\/Timer>\n#include \"sockinet.h\"\n\n \/*\n * Semantics:\n * Two methods for using the .net loader.\n * 1) Add a hostname prefix and a '.net' suffix on a model when passing \n * to osgDB::readNodeFile() \n * e.g: osgDB::readNodeFile( \"openscenegraph.org:cow.osg.net\" );\n *\n * 2) Explicitely load the .net plugin and pass the plugin options including\n * hostname=<hostname>\n *\n * Method #1 takes precedence. SO, if the hostname option is passed the\n * plugin, but the name also contains a hostname prefix, the hostname\n * prefix on the file name will override the option\n *\n * Plugin options:\n * hostname=<hostname> - Specify the host where the data file is to \n * be fetched from.\n *\n * prefix=<prefix> - Specify a server directory to prefix the \n * file name with.\n * \n * local_cache_dir=<dir> - Specify a directory in which to cache files\n * on the local machine once they've been fetched. \n * This directory is also searched before fetching\n * the file from the server when Read mode is \n * enabled on the cache.\n *\n * cache_mode=<mode> - Set the mode for the local cache if local_cache\n * was specified. If local_cache was not specified\n * this directive is ignored. <mode> may\n * be specified with ReadOnly, WriteOnly, or\n * ReadWrite. Behavior for the different modes is\n * defined as:\n *\n * ReadOnly - When retrieving files, cache is \n * searched first, and if the file is\n * not present, it is fetched from the\n * server. If it is fetched from the\n * server it is not stored in local cache\n *\n * WriteOnly - When retrieving files, cache is not\n * searched, file is always retrieved\n * from the server and always written to\n * cache.\n *\n * ReadWrite - (the default). When retrieving files\n * cache is searched first, if file is\n * not present in cache, it is fetched from\n * the server. If fetched, it is written\n * to cache.\n *\n *\/\n\n\nclass NetReader : public osgDB::ReaderWriter\n{\n public:\n NetReader() {}\n \n virtual const char* className() const { return \"HTTP Protocol Model Reader\"; }\n \n virtual bool acceptsExtension(const std::string& extension) const\n {\n return osgDB::equalCaseInsensitive(extension,\"net\");\n }\n\n enum ObjectType\n {\n OBJECT,\n ARCHIVE,\n IMAGE,\n HEIGHTFIELD,\n NODE\n };\n \n virtual ReadResult openArchive(const std::string& fileName,ArchiveStatus status, unsigned int , const Options* options) const\n {\n if (status!=READ) return ReadResult(ReadResult::FILE_NOT_HANDLED);\n else return readFile(ARCHIVE,fileName,options);\n }\n\n virtual ReadResult readObject(const std::string& fileName, const Options* options) const\n {\n return readFile(OBJECT,fileName,options);\n }\n \n virtual ReadResult readImage(const std::string& fileName, const Options *options) const\n {\n return readFile(IMAGE,fileName,options);\n }\n\n virtual ReadResult readHeightField(const std::string& fileName, const Options *options) const\n {\n return readFile(HEIGHTFIELD,fileName,options);\n }\n\n virtual ReadResult readNode(const std::string& fileName, const Options *options) const\n {\n return readFile(NODE,fileName,options);\n }\n\n ReadResult readFile(ObjectType objectType, osgDB::ReaderWriter* rw, std::istream& fin, const Options *options) const\n {\n switch(objectType)\n {\n case(OBJECT): return rw->readObject(fin,options);\n case(ARCHIVE): return rw->openArchive(fin,options);\n case(IMAGE): return rw->readImage(fin,options);\n case(HEIGHTFIELD): return rw->readHeightField(fin,options);\n case(NODE): return rw->readNode(fin,options);\n default: break;\n }\n return ReadResult::FILE_NOT_HANDLED;\n }\n\n virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options) const\n {\n osg::Timer_t start = osg::Timer::instance()->tick();\n\n osg::notify(osg::NOTICE) << \"osgPlugin .net: start load\" << inFileName << std::endl;\n\n std::string hostname;\n std::string serverPrefix;\n std::string localCacheDir;\n int port = 80;\n\n enum CacheMode {\n Read = 1,\n Write = 2,\n ReadWrite = 3\n };\n\n CacheMode cacheMode = ReadWrite;\n\n if (options)\n {\n std::istringstream iss(options->getOptionString());\n std::string opt;\n while (iss >> opt) \n {\n int index = opt.find( \"=\" );\n if( opt.substr( 0, index ) == \"hostname\" ||\n opt.substr( 0, index ) == \"HOSTNAME\" )\n {\n hostname = opt.substr( index+1 );\n }\n else if( opt.substr( 0, index ) == \"port\" ||\n opt.substr( 0, index ) == \"PORT\" )\n {\n port = atoi( opt.substr(index+1).c_str() );\n }\n else if( opt.substr( 0, index ) == \"server_prefix\" ||\n opt.substr( 0, index ) == \"SERVER_PREFIX\" ||\n opt.substr( 0, index ) == \"prefix\" ||\n opt.substr( 0, index ) == \"PREFIX\" )\n {\n serverPrefix = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"local_cache_dir\" ||\n opt.substr( 0, index ) == \"LOCAL_CACHE_DIR\" )\n {\n localCacheDir = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"cache_mode\" ||\n opt.substr( 0, index ) == \"CACHE_MODE\" )\n {\n if( opt.substr(index+1) == \"ReadOnly\" )\n cacheMode = Read;\n else if( opt.substr(index+1) == \"WriteOnly\" )\n cacheMode = Write;\n else if( opt.substr(index+1) == \"ReadWrite\" )\n cacheMode = ReadWrite;\n else\n osg::notify(osg::WARN) << \n \"NET plug-in warning: cache_mode \" << opt.substr(index+1) << \n \" not understood. Defaulting to ReadWrite.\" << std::endl;\n }\n }\n }\n\n ReadResult readResult = ReadResult::FILE_NOT_HANDLED;\n\n \/* * we accept all extensions\n std::string ext = osgDB::getFileExtension(inFileName);\n if (!acceptsExtension(ext))\n return ReadResult::FILE_NOT_HANDLED;\n *\/\n\n\n std::string fileName;\n int index = inFileName.find(\":\");\n \/\/ If we haven't been given a hostname as an option\n \/\/ and it hasn't been prefixed to the name, we fail\n if( index != -1 )\n {\n hostname = inFileName.substr( 0, index);\n \/\/ need to strip the inFileName of the hostname prefix\n fileName = inFileName.substr( index+1 );\n }\n else\n {\n if( hostname.empty() )\n return ReadResult::FILE_NOT_HANDLED;\n else\n fileName = inFileName;\n }\n\n \/\/ Let's also strip the possible .net extension\n if( osgDB::getFileExtension( fileName ) == \"net\" )\n {\n int rindex = fileName.rfind( \".\" );\n fileName = fileName.substr( 0, rindex );\n }\n\n if( !serverPrefix.empty() )\n fileName = serverPrefix + '\/' + fileName;\n\n osg::notify(osg::WARN) << \"hostname \" << hostname << std::endl;\n osg::notify(osg::WARN) << \"filename \" << fileName << std::endl;\n\n\n \/\/ Invoke the reader corresponding to the extension\n osgDB::ReaderWriter *reader = \n osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));\n if( reader == 0L )\n return ReadResult::FILE_NOT_HANDLED;\n\n \/\/ Before we go to the network, lets see if it is in local cache, if cache\n \/\/ was specified and Read bit is set\n if( !localCacheDir.empty() && (cacheMode & Read) )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::fileExists( cacheFile ))\n {\n std::ifstream in(cacheFile.c_str());\n readResult = readFile(objectType, reader, in, options );\n\n in.close();\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from local cache.\" << std::endl;\n return readResult;\n }\n }\n\n \/\/ Fetch from the network\n osg::ref_ptr<iosockinet> sio = new iosockinet(sockbuf::sock_stream);\n try {\n sio->rdbuf()->connect( hostname.c_str(), port );\n }\n catch( sockerr e )\n {\n osg::notify(osg::WARN) << \"osgPlugin .net reader: Unable to connect to host \" << hostname << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n\n *sio << \"GET \/\" << fileName << \" HTTP\/1.1\\n\" << \"Host: \" << hostname << \"\\n\\n\";\n sio->flush();\n \n char linebuff[256];\n do\n {\n sio->getline( linebuff, sizeof( linebuff ));\n\n std::istringstream iss(linebuff);\n std::string directive;\n iss >> directive;\n if( directive.substr(0,4) == \"HTTP\" )\n {\n iss >> directive;\n \/\/ Code 200. We be ok.\n if( directive == \"200\" )\n ;\n \/\/ Code 400 Bad Request\n else if( directive == \"400\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 400 - Bad Request\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 401 Bad Request\n else if( directive == \"401\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 401 - Unauthorized Access\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 403 Bad Request\n else if( directive == \"403\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 403 - Access Forbidden\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 404 File not found\n else if( directive == \"404\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 404 - File Not Found\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 405 Method not allowed\n else if( directive == \"405\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 405 - Method Not Allowed\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ There's more....\n }\n\n } while( linebuff[0] != '\\r' );\n\n \/\/ code for setting up the database path so that any paged\n \/\/ databases can be automatically located. \n osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);\n if (!local_opt) local_opt = new Options;\n\n if (local_opt.valid() && local_opt->getDatabasePathList().empty())\n {\n local_opt->setDatabasePath(osgDB::getFilePath(inFileName));\n }\n \n \n\n\n if( reader != 0L )\n readResult = readFile(objectType, reader, *sio, local_opt.get() );\n\n double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from server. in\" << ms <<\" ms\"<< std::endl;\n\n if (objectType==ARCHIVE && readResult.validArchive())\n {\n \/\/ attach the socket istream to the archive to keep it alive.\n osgDB::Archive* archive = readResult.getArchive();\n archive->setUserData(sio.get());\n }\n\n if( !localCacheDir.empty() && cacheMode & Write )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::makeDirectoryForFile( cacheFile ) )\n {\n \n switch(objectType)\n {\n case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );\n case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );\n case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );\n case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;\n default: break;\n }\n \n \n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" stored to local cache.\" << std::endl;\n }\n }\n\n return readResult;\n }\n \n};\n\nosgDB::RegisterReaderWriterProxy<NetReader> g_netReader_Proxy;\n\n \n\n\n<|endoftext|>"} {"text":"<commit_before>\/* \n * File: main.cpp\n * Author: RedSpiderMkV\n *\n * Created on 11 November 2015, 21:38\n *\/\n\n#include <iostream>\n#include <string>\n#include \"Converter\/DecimalConverter.h\"\n#include \"Converter\/HexadecimalConverter.h\"\n#include \"Converter\/BinaryConverter.h\"\n\nusing namespace std;\nusing namespace NumberBaseConverter;\n\/*\n * \n *\/\nint main(int argc, char* argv[])\n{\n cout << \"Hello world!\" << endl;\n \n DecimalConverter newConverter;\n HexadecimalConverter hexConverter;\n BinaryConverter binConverter;\n \n string input = \"0\";\n while(input != \"-1\")\n {\n cin >> input;\n \/\/cout << newConverter.ConvertToBinary(input) << \"\\t\";\n \/\/cout << newConverter.ConvertToHexadecimal(input) << endl;\n \n \/\/cout << hexConverter.ConvertToBinary(input) << \"\\t\";\n \/\/cout << hexConverter.ConvertToDecimal(input) << endl;\n \n cout << binConverter.ConvertToDecimal(input) << \"\\t\";\n cout << binConverter.ConvertToHexadecimal(input) << endl;\n }\n \n return 0;\n} \/\/ end method\n\n<commit_msg>main - taking input from command line<commit_after>\/* \n * File: main.cpp\n * Author: RedSpiderMkV\n *\n * Created on 11 November 2015, 21:38\n *\/\n\n#include <iostream>\n#include <string>\n#include \"Converter\/DecimalConverter.h\"\n#include \"Converter\/HexadecimalConverter.h\"\n#include \"Converter\/BinaryConverter.h\"\n\nusing namespace std;\nusing namespace NumberBaseConverter;\n\nbool argumentCountValid(int argc)\n{\n if(argc != 4)\n {\n cout << \"Incorrect usage. Usage:\" << endl;\n cout << \"bindechexconverter dec hex 10\" << endl << endl;\n \n return false;\n } \/\/ end if\n \n return true;\n} \/\/ end method\n\nbool inputBaseValid(string inputBase)\n{\n if(inputBase != \"dec\" && inputBase != \"hex\" && inputBase != \"bin\")\n {\n cout << \"Specified input base is unrecognised: \" << inputBase << endl;\n cout << \"Can be dec, hex or bin\" << endl << endl;\n \n return false;\n } \/\/ end if\n \n return true;\n} \/\/ end method\n\nbool outputBaseValid(string outputBase)\n{\n if(outputBase != \"dec\" && outputBase != \"hex\" && outputBase != \"bin\")\n {\n cout << \"Specified output base is unrecognised: \" << outputBase << endl;\n cout << \"Can be dec, hex or bin\" << endl << endl;\n \n return false;\n } \/\/ end if\n \n return true;\n} \/\/ end method\n\nint main(int argc, char* argv[])\n{\n if(!argumentCountValid(argc)\n || !inputBaseValid(string(argv[1]))\n || !outputBaseValid(string(argv[2])))\n {\n cout << \"Conversion failed, exiting\" << endl;\n \n return -1;\n } \/\/ end if\n \n DecimalConverter newConverter;\n HexadecimalConverter hexConverter;\n BinaryConverter binConverter;\n \n \n \n return 0;\n} \/\/ end method\n\n<|endoftext|>"} {"text":"<commit_before>#include \"CommandRequest.h\"\n\nusing namespace opencog;\n\nCommandRequest::~CommandRequest() {\n}\n\nCommandRequest::CommandRequest(CallBackInterface *callBack, std::string &command, std::queue<std::string> &args) {\n this->callBackRequestor = callBack;\n this->command = command;\n this->args = args;\n}\n\nstd::string CommandRequest::getType() {\n return \"COMMAND_LINE\";\n}\n\nvoid CommandRequest::setAnswer(std::string &commandOutput) {\n answer = commandOutput;\n}\n\nstd::string CommandRequest::getCommand() {\n return command;\n}\n\nstd::queue<std::string> CommandRequest::getArgs() {\n return args;\n}\n\nvoid CommandRequest::callBack() {\n callBackRequestor->callBack(answer);\n}\n<commit_msg>wrap long lines to fit 80 columns<commit_after>#include \"CommandRequest.h\"\n\nusing namespace opencog;\n\nCommandRequest::~CommandRequest() {\n}\n\nCommandRequest::CommandRequest(CallBackInterface *callBack, \n std::string &command,\n std::queue<std::string> &args)\n{\n this->callBackRequestor = callBack;\n this->command = command;\n this->args = args;\n}\n\nstd::string CommandRequest::getType() {\n return \"COMMAND_LINE\";\n}\n\nvoid CommandRequest::setAnswer(std::string &commandOutput) {\n answer = commandOutput;\n}\n\nstd::string CommandRequest::getCommand() {\n return command;\n}\n\nstd::queue<std::string> CommandRequest::getArgs() {\n return args;\n}\n\nvoid CommandRequest::callBack() {\n callBackRequestor->callBack(answer);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Updated max line length<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <gtest\/gtest.h>\n#include \"twosum.hxx\"\n\nnamespace {\n class TwoSumTest : public testing::Test\n {\n protected:\n TwoSumTest(void) {}\n virtual ~TwoSumTest(void) {}\n virtual void SetUp(void) {}\n virtual void TearDown(void) {}\n };\n\n TEST(TwoSumTest, TwoSum1)\n {\n auto actual = 0\/*Solution{}.numTrees(1)*\/;\n decltype(actual) expected = 1;\n\n EXPECT_EQ(expected, actual);\n }\n}\n<commit_msg>first unit test for twosum<commit_after>#pragma once\n\n#include <vector>\n#include <gtest\/gtest.h>\n\n#include \"..\/..\/..\/..\/include\/cpp\/gtest-array.hxx\"\n#include \"twosum.hxx\"\n\nusing std::vector;\n\nnamespace {\n class TwoSumTest : public testing::Test\n {\n protected:\n TwoSumTest(void) {}\n virtual ~TwoSumTest(void) {}\n virtual void SetUp(void) {}\n virtual void TearDown(void) {}\n };\n\n TEST(TwoSumTest, TwoSum1)\n {\n vector<int> input{2, 7, 11, 15};\n auto actual = Solution{}.twoSum(input, 9);\n vector<int> expected{1, 2};\n\n EXPECT_TRUE(arrayMatch(expected, actual));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"process_based_isolation_module.hpp\"\n\n#include \"foreach.hpp\"\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::list;\nusing std::make_pair;\nusing std::ostringstream;\nusing std::pair;\nusing std::queue;\nusing std::string;\nusing std::vector;\n\nusing boost::lexical_cast;\nusing boost::unordered_map;\nusing boost::unordered_set;\n\nusing namespace nexus;\nusing namespace nexus::internal;\nusing namespace nexus::internal::slave;\n\n\nProcessBasedIsolationModule::ProcessBasedIsolationModule(Slave* slave)\n{\n this->slave = slave;\n reaper = new Reaper(this);\n Process::spawn(reaper);\n}\n\n\nProcessBasedIsolationModule::~ProcessBasedIsolationModule()\n{\n \/\/ We want to wait until the reaper has completed because it\n \/\/ accesses 'this' in order to make callbacks ... deleting 'this'\n \/\/ could thus lead to a seg fault!\n Process::post(reaper->getPID(), SHUTDOWN_REAPER);\n Process::wait(reaper);\n delete reaper;\n}\n\n\nvoid ProcessBasedIsolationModule::frameworkAdded(Framework* framework)\n{\n pgids[framework->id] = -1;\n framework->executorStatus = \"No executor running\";\n}\n\n\nvoid ProcessBasedIsolationModule::frameworkRemoved(Framework* framework)\n{\n pgids.erase(framework->id);\n}\n\n\nvoid ProcessBasedIsolationModule::startExecutor(Framework* framework)\n{\n LOG(INFO) << \"Starting executor for framework \" << framework->id << \": \"\n << framework->executorInfo.uri;\n CHECK(pgids[framework->id] == -1);\n\n pid_t pid;\n if ((pid = fork()) == -1)\n PLOG(FATAL) << \"Failed to fork to launch new executor\";\n\n if (pid) {\n \/\/ In parent process, record the pgid for killpg later.\n LOG(INFO) << \"Started executor, OS pid = \" << pid;\n pgids[framework->id] = pid;\n framework->executorStatus = \"PID: \" + lexical_cast<string>(pid);\n } else {\n \/\/ In child process, make cleanup easier.\n if (setpgid(0, 0) < 0)\n PLOG(FATAL) << \"Failed to put executor in own process group\";\n\/\/ if ((pid = setsid()) == -1)\n\/\/ PLOG(FATAL) << \"Failed to put executor in own session\";\n\n createExecutorLauncher(framework)->run();\n }\n}\n\n\nvoid ProcessBasedIsolationModule::killExecutor(Framework* fw)\n{\n if (pgids[fw->id] != -1) {\n \/\/ TODO(benh): Consider sending a SIGTERM, then after so much time\n \/\/ if it still hasn't exited do a SIGKILL (can use a libprocess\n \/\/ process for this).\n LOG(INFO) << \"Sending SIGKILL to gpid \" << pgids[fw->id];\n killpg(pgids[fw->id], SIGKILL);\n pgids[fw->id] = -1;\n fw->executorStatus = \"No executor running\";\n \/\/ TODO(benh): Kill all of the process's descendants? Perhaps\n \/\/ create a new libprocess process that continually tries to kill\n \/\/ all the processes that are a descendant of the executor, trying\n \/\/ to kill the executor last ... maybe this is just too much of a\n \/\/ burden?\n }\n}\n\n\nvoid ProcessBasedIsolationModule::resourcesChanged(Framework* fw)\n{\n \/\/ Do nothing; subclasses may override this.\n}\n\n\nExecutorLauncher* ProcessBasedIsolationModule::createExecutorLauncher(Framework* fw)\n{\n return new ExecutorLauncher(fw->id, fw->executorInfo.uri, fw->user,\n\t\t\t slave->getWorkDirectory(fw->id),\n\t\t\t slave->self(), !slave->local);\n}\n\n\nProcessBasedIsolationModule::Reaper::Reaper(ProcessBasedIsolationModule* m)\n : module(m)\n{}\n\n \nvoid ProcessBasedIsolationModule::Reaper::operator () ()\n{\n link(module->slave->getPID());\n while (true) {\n switch (receive(1)) {\n case PROCESS_TIMEOUT: {\n \/\/ Check whether any child process has exited\n pid_t pid;\n int status;\n if ((pid = waitpid((pid_t) -1, &status, WNOHANG)) > 0) {\n\tforeachpair (FrameworkID fid, pid_t& pgid, module->pgids) {\n\t if (pgid == pid) {\n\t \/\/ Kill the process group to clean up the tasks.\n\t LOG(INFO) << \"Sending SIGKILL to gpid \" << pgid;\n\t killpg(pgid, SIGKILL);\n\t module->pgids[fid] = -1;\n\t LOG(INFO) << \"Telling slave of lost framework \" << fid;\n\t \/\/ TODO(benh): This is broken if\/when libprocess is parallel!\n\t module->slave->executorExited(fid, status);\n\t break;\n\t }\n\t}\n }\n break;\n }\n case SHUTDOWN_REAPER:\n case PROCESS_EXIT:\n return;\n }\n }\n}\n\n<commit_msg>Using sessions instead of process groups.<commit_after>#include \"process_based_isolation_module.hpp\"\n\n#include \"foreach.hpp\"\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::list;\nusing std::make_pair;\nusing std::ostringstream;\nusing std::pair;\nusing std::queue;\nusing std::string;\nusing std::vector;\n\nusing boost::lexical_cast;\nusing boost::unordered_map;\nusing boost::unordered_set;\n\nusing namespace nexus;\nusing namespace nexus::internal;\nusing namespace nexus::internal::slave;\n\n\nProcessBasedIsolationModule::ProcessBasedIsolationModule(Slave* slave)\n{\n this->slave = slave;\n reaper = new Reaper(this);\n Process::spawn(reaper);\n}\n\n\nProcessBasedIsolationModule::~ProcessBasedIsolationModule()\n{\n \/\/ We want to wait until the reaper has completed because it\n \/\/ accesses 'this' in order to make callbacks ... deleting 'this'\n \/\/ could thus lead to a seg fault!\n Process::post(reaper->getPID(), SHUTDOWN_REAPER);\n Process::wait(reaper);\n delete reaper;\n}\n\n\nvoid ProcessBasedIsolationModule::frameworkAdded(Framework* framework)\n{\n pgids[framework->id] = -1;\n framework->executorStatus = \"No executor running\";\n}\n\n\nvoid ProcessBasedIsolationModule::frameworkRemoved(Framework* framework)\n{\n pgids.erase(framework->id);\n}\n\n\nvoid ProcessBasedIsolationModule::startExecutor(Framework* framework)\n{\n LOG(INFO) << \"Starting executor for framework \" << framework->id << \": \"\n << framework->executorInfo.uri;\n CHECK(pgids[framework->id] == -1);\n\n pid_t pid;\n if ((pid = fork()) == -1)\n PLOG(FATAL) << \"Failed to fork to launch new executor\";\n\n if (pid) {\n \/\/ In parent process, record the pgid for killpg later.\n LOG(INFO) << \"Started executor, OS pid = \" << pid;\n pgids[framework->id] = pid;\n framework->executorStatus = \"PID: \" + lexical_cast<string>(pid);\n } else {\n \/\/ In child process, make cleanup easier.\n\/\/ if (setpgid(0, 0) < 0)\n\/\/ PLOG(FATAL) << \"Failed to put executor in own process group\";\n if ((pid = setsid()) == -1)\n PLOG(FATAL) << \"Failed to put executor in own session\";\n\n createExecutorLauncher(framework)->run();\n }\n}\n\n\nvoid ProcessBasedIsolationModule::killExecutor(Framework* fw)\n{\n if (pgids[fw->id] != -1) {\n \/\/ TODO(benh): Consider sending a SIGTERM, then after so much time\n \/\/ if it still hasn't exited do a SIGKILL (can use a libprocess\n \/\/ process for this).\n LOG(INFO) << \"Sending SIGKILL to gpid \" << pgids[fw->id];\n killpg(pgids[fw->id], SIGKILL);\n pgids[fw->id] = -1;\n fw->executorStatus = \"No executor running\";\n \/\/ TODO(benh): Kill all of the process's descendants? Perhaps\n \/\/ create a new libprocess process that continually tries to kill\n \/\/ all the processes that are a descendant of the executor, trying\n \/\/ to kill the executor last ... maybe this is just too much of a\n \/\/ burden?\n }\n}\n\n\nvoid ProcessBasedIsolationModule::resourcesChanged(Framework* fw)\n{\n \/\/ Do nothing; subclasses may override this.\n}\n\n\nExecutorLauncher* ProcessBasedIsolationModule::createExecutorLauncher(Framework* fw)\n{\n return new ExecutorLauncher(fw->id, fw->executorInfo.uri, fw->user,\n\t\t\t slave->getWorkDirectory(fw->id),\n\t\t\t slave->self(), !slave->local);\n}\n\n\nProcessBasedIsolationModule::Reaper::Reaper(ProcessBasedIsolationModule* m)\n : module(m)\n{}\n\n \nvoid ProcessBasedIsolationModule::Reaper::operator () ()\n{\n link(module->slave->getPID());\n while (true) {\n switch (receive(1)) {\n case PROCESS_TIMEOUT: {\n \/\/ Check whether any child process has exited\n pid_t pid;\n int status;\n if ((pid = waitpid((pid_t) -1, &status, WNOHANG)) > 0) {\n\tforeachpair (FrameworkID fid, pid_t& pgid, module->pgids) {\n\t if (pgid == pid) {\n\t \/\/ Kill the process group to clean up the tasks.\n\t LOG(INFO) << \"Sending SIGKILL to gpid \" << pgid;\n\t killpg(pgid, SIGKILL);\n\t module->pgids[fid] = -1;\n\t LOG(INFO) << \"Telling slave of lost framework \" << fid;\n\t \/\/ TODO(benh): This is broken if\/when libprocess is parallel!\n\t module->slave->executorExited(fid, status);\n\t break;\n\t }\n\t}\n }\n break;\n }\n case SHUTDOWN_REAPER:\n case PROCESS_EXIT:\n return;\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)\n *\n * This file is part of vanillacoin.\n *\n * vanillacoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see 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 Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef COIN_INVENTORY_VECTOR_HPP\n#define COIN_INVENTORY_VECTOR_HPP\n\n#include <cstdint>\n\n#include <coin\/protocol.hpp>\n#include <coin\/sha256.hpp>\n\nnamespace coin {\n\n class data_buffer;\n class db_tx;\n \n \/**\n * The inventory vector structure.\n * type uint32_t Identifies the object type linked to this inventory.\n * hash char[32] Hash of the object.\n *\/\n class inventory_vector\n {\n public:\n \n \/**\n * The types.\n * @param type_error Any data of with this number may be ignored.\n * @param type_msg_tx Hash is related to a transaction.\n * @param type_msg_block Hash is related to a data block.\n * @param type_msg_ztlock Hash is related to a zerotime lock.\n * @param type_msg_ztvote Hash is related to zerotime vote.\n * @param type_msg_ivote Hash is related to incentive vote.\n *\/\n typedef enum\n {\n type_error,\n type_msg_tx,\n type_msg_block,\n type_msg_ztlock,\n type_msg_ztvote,\n type_msg_ivote,\n } type_t;\n \n \/**\n * Constructor\n *\/\n inventory_vector();\n \n \/**\n * Constructor\n *\/\n inventory_vector(const type_t & type, const sha256 & hash);\n \n \/**\n * Constructor\n *\/\n inventory_vector(\n const std::string & type, const sha256 & hash\n );\n\n \/**\n * Encodes\n * buffer The data_buffer.\n *\/\n bool encode(data_buffer & buffer);\n \n \/**\n * Decodes\n * buffer The data_buffer.\n *\/\n bool decode(data_buffer & buffer);\n\n \/**\n * The type.\n *\/\n const type_t & type() const;\n \n \/**\n * The hash.\n *\/\n const sha256 & hash() const;\n \n \/**\n * If true it is of a known type.\n *\/\n bool is_know_type() const;\n \n \/**\n * The command.\n *\/\n const std::string command() const;\n \n \/**\n * Returns the string representation.\n *\/\n const std::string to_string() const;\n \n \/**\n * Checks if we already have the transaction.\n * @param tx_db The transaction database.\n * @param inv The inventory_vector.\n *\/\n static bool already_have(\n db_tx & tx_db, const inventory_vector & inv\n );\n\n \/**\n * operator ==\n *\/\n friend bool operator == (\n const inventory_vector & a, const inventory_vector & b\n )\n {\n return a.m_type == b.m_type && a.m_hash == b.m_hash;\n }\n \n \/**\n * operator <\n *\/\n friend bool operator < (\n const inventory_vector & a, const inventory_vector & b\n )\n {\n return\n a.m_type < b.m_type ||\n (a.m_type == b.m_type && a.m_hash < b.m_hash)\n ;\n }\n \n private:\n \n \/**\n * The type.\n *\/\n type_t m_type;\n \n \/**\n * The hash.\n *\/\n sha256 m_hash;\n \n protected:\n \n \/\/ ...\n };\n \n} \/\/ namespace coin\n\n#endif \/\/ COIN_INVENTORY_VECTOR_HPP\n<commit_msg>0.4.5 partial merge<commit_after>\/*\n * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)\n *\n * This file is part of vanillacoin.\n *\n * vanillacoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see 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 Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef COIN_INVENTORY_VECTOR_HPP\n#define COIN_INVENTORY_VECTOR_HPP\n\n#include <cstdint>\n\n#include <coin\/protocol.hpp>\n#include <coin\/sha256.hpp>\n\nnamespace coin {\n\n class data_buffer;\n class db_tx;\n \n \/**\n * The inventory vector structure.\n * type uint32_t Identifies the object type linked to this inventory.\n * hash char[32] Hash of the object.\n *\/\n class inventory_vector\n {\n public:\n \n \/**\n * The types.\n * @param type_error Any data of with this number may be ignored.\n * @param type_msg_tx Hash is related to a transaction.\n * @param type_msg_block Hash is related to a data block.\n * @param type_msg_filtered_block Hash is related to a filtered\n * block.\n * @param type_msg_ztlock Hash is related to a zerotime lock.\n * @param type_msg_ztvote Hash is related to zerotime vote.\n * @param type_msg_ivote Hash is related to incentive vote.\n *\/\n typedef enum\n {\n type_error,\n type_msg_tx,\n type_msg_block,\n#if 0 \/* BIP-0037 *\/\n type_msg_filtered_block,\n#endif\n type_msg_ztlock,\n type_msg_ztvote,\n type_msg_ivote,\n } type_t;\n \n \/**\n * Constructor\n *\/\n inventory_vector();\n \n \/**\n * Constructor\n *\/\n inventory_vector(const type_t & type, const sha256 & hash);\n \n \/**\n * Constructor\n *\/\n inventory_vector(\n const std::string & type, const sha256 & hash\n );\n\n \/**\n * Encodes\n * buffer The data_buffer.\n *\/\n bool encode(data_buffer & buffer);\n \n \/**\n * Decodes\n * buffer The data_buffer.\n *\/\n bool decode(data_buffer & buffer);\n\n \/**\n * The type.\n *\/\n const type_t & type() const;\n \n \/**\n * The hash.\n *\/\n const sha256 & hash() const;\n \n \/**\n * If true it is of a known type.\n *\/\n bool is_know_type() const;\n \n \/**\n * The command.\n *\/\n const std::string command() const;\n \n \/**\n * Returns the string representation.\n *\/\n const std::string to_string() const;\n \n \/**\n * Checks if we already have the transaction.\n * @param tx_db The transaction database.\n * @param inv The inventory_vector.\n *\/\n static bool already_have(\n db_tx & tx_db, const inventory_vector & inv\n );\n\n \/**\n * operator ==\n *\/\n friend bool operator == (\n const inventory_vector & a, const inventory_vector & b\n )\n {\n return a.m_type == b.m_type && a.m_hash == b.m_hash;\n }\n \n \/**\n * operator <\n *\/\n friend bool operator < (\n const inventory_vector & a, const inventory_vector & b\n )\n {\n return\n a.m_type < b.m_type ||\n (a.m_type == b.m_type && a.m_hash < b.m_hash)\n ;\n }\n \n private:\n \n \/**\n * The type.\n *\/\n type_t m_type;\n \n \/**\n * The hash.\n *\/\n sha256 m_hash;\n \n protected:\n \n \/\/ ...\n };\n \n} \/\/ namespace coin\n\n#endif \/\/ COIN_INVENTORY_VECTOR_HPP\n<|endoftext|>"} {"text":"<commit_before>#pragma once \n\n\/* \n A generic forward checker for properties\n *\/\n\n#include <crab\/common\/types.hpp>\n#include <crab\/common\/stats.hpp>\n#include <crab\/checkers\/base_property.hpp>\n#include <crab\/analysis\/fwd_analyzer.hpp>\n#include <crab\/analysis\/inter_fwd_analyzer.hpp>\n\nnamespace crab {\n\n namespace checker {\n\n template<typename Analyzer>\n class checker {\n \/*\n The checker propagates the invariants that hold at the entry of\n each block (assume forward analysis) to each program point while\n checking for the properties. The analysis results are shared by\n all the property checkers so the analysis needs to be run only\n once.\n *\/\n\n checker(const checker<Analyzer>& other); \/\/ non construction copyable\n checker<Analyzer>& operator=(const checker<Analyzer>& other); \/\/ non-copyable\n \n public:\n\n typedef boost::shared_ptr<property_checker<Analyzer>> prop_checker_ptr;\n typedef std::vector<prop_checker_ptr> prop_checker_vector;\n\n protected:\n\n prop_checker_vector m_checkers;\n \n public:\n\n checker(prop_checker_vector checkers): m_checkers(checkers) { }\n\n virtual ~checker(){ }\n \n virtual void run() = 0;\n \n virtual void show(crab_os& o) {\n for (auto prop_checker: m_checkers) {\n prop_checker->write(o);\n }\n }\n\n \/\/ merge all the databases in one: useful for crab clients\n virtual checks_db get_all_checks() const {\n checks_db res;\n for (auto prop_checker: m_checkers) {\n res += prop_checker->get_db();\n }\n return res;\n }\n\n };\n\n template<typename Analyzer> \n class intra_checker: public checker<Analyzer> {\n public:\n\n typedef checker<Analyzer> base_checker_t;\n using typename base_checker_t::prop_checker_ptr;\n using typename base_checker_t::prop_checker_vector;\n\n private:\n\n typedef typename Analyzer::cfg_t cfg_t;\n typedef typename cfg_t::statement_t statement_t;\n typedef typename Analyzer::abs_dom_t abs_dom_t;\n typedef typename Analyzer::abs_tr_t abs_tr_t;\n\n Analyzer& m_analyzer;\n\n public:\n\n intra_checker(Analyzer& analyzer, prop_checker_vector checkers)\n : base_checker_t(checkers)\n , m_analyzer(analyzer) { }\n \n \n virtual void run() override {\n CRAB_VERBOSE_IF(1, crab::outs() << \"Started property checker.\\n\";); \n crab::ScopedCrabStats __st__(\"Checker\");\n cfg_t cfg = m_analyzer.get_cfg();\n\n \/\/ In some cases, the analyzer might know that an assertion is\n \/\/ safe but it cannot be proven by propagating only\n \/\/ invariants. This is common if the analyzer is based on a\n \/\/ forward\/backward refinement loop.\n std::set<const statement_t*> safe_assertions;\n m_analyzer.get_safe_assertions(safe_assertions);\n \n for (auto &bb: cfg) {\n for (auto checker: this->m_checkers) {\n crab::ScopedCrabStats __st__(\"Checker.\" + checker->get_property_name());\n abs_dom_t inv = m_analyzer[bb.label()];\n\t boost::shared_ptr<abs_tr_t> abs_tr = m_analyzer.get_abs_transformer(&inv);\n \/\/ propagate forward the invariants from the block entry \n \/\/ while checking the property\n checker->set(&*abs_tr, safe_assertions);\n for (auto &stmt: bb) {\n\t stmt.accept(&*checker);\n\t }\n }\n }\n CRAB_VERBOSE_IF(1, crab::outs() << \"Finished property checker.\\n\";);\n }\n };\n\n\n template< typename Analyzer>\n class inter_checker: public checker<Analyzer> {\n public:\n\n typedef checker<Analyzer> base_checker_t;\n using typename base_checker_t::prop_checker_ptr;\n using typename base_checker_t::prop_checker_vector;\n\n private:\n\n typedef typename Analyzer::cg_t cg_t;\n typedef typename Analyzer::cfg_t cfg_t;\n typedef typename Analyzer::abs_dom_t abs_dom_t;\n typedef typename Analyzer::abs_tr_t abs_tr_t;\n \n Analyzer& m_analyzer;\n \n public:\n\n inter_checker(Analyzer& analyzer, prop_checker_vector checkers)\n : base_checker_t(checkers), m_analyzer(analyzer) { }\n \n virtual void run() override {\n CRAB_VERBOSE_IF(1, crab::outs() << \"Started property checker.\\n\";);\n crab::ScopedCrabStats __st__(\"Checker\");\n cg_t& cg = m_analyzer.get_call_graph(); \n for (auto &v: boost::make_iterator_range(vertices(cg))) {\n cfg_t cfg = v.get_cfg();\n\n for (auto &bb: cfg) {\n for (auto checker: this->m_checkers) {\n crab::ScopedCrabStats __st__(\"Checker.\" + checker->get_property_name());\n abs_dom_t inv = m_analyzer.get_pre(cfg, bb.label());\n\t boost::shared_ptr<abs_tr_t> abs_tr = m_analyzer.get_abs_transformer(&inv);\n \/\/ propagate forward the invariants from the block entry \n \/\/ while checking the property\n checker->set(&*abs_tr);\n for (auto &stmt: bb) {\n stmt.accept(&*checker);\n\t }\n }\n }\n }\n CRAB_VERBOSE_IF(1, crab::outs() << \"Finished property checker.\";);\n\n \n }\n };\n\n } \/\/ end namespace\n} \/\/ end namespace\n<commit_msg>Forgot from last commit<commit_after>#pragma once \n\n\/* \n A generic forward checker for properties\n *\/\n\n#include <crab\/common\/types.hpp>\n#include <crab\/common\/stats.hpp>\n#include <crab\/checkers\/base_property.hpp>\n#include <crab\/analysis\/fwd_analyzer.hpp>\n#include <crab\/analysis\/inter_fwd_analyzer.hpp>\n\nnamespace crab {\n\n namespace checker {\n\n template<typename Analyzer>\n class checker {\n \/*\n The checker propagates the invariants that hold at the entry of\n each block (assume forward analysis) to each program point while\n checking for the properties. The analysis results are shared by\n all the property checkers so the analysis needs to be run only\n once.\n *\/\n\n checker(const checker<Analyzer>& other); \/\/ non construction copyable\n checker<Analyzer>& operator=(const checker<Analyzer>& other); \/\/ non-copyable\n \n public:\n\n typedef boost::shared_ptr<property_checker<Analyzer>> prop_checker_ptr;\n typedef std::vector<prop_checker_ptr> prop_checker_vector;\n\n protected:\n\n prop_checker_vector m_checkers;\n \n public:\n\n checker(prop_checker_vector checkers): m_checkers(checkers) {}\n\n virtual ~checker() {}\n \n virtual void run() = 0;\n \n virtual void show(crab_os& o) {\n for (auto prop_checker: m_checkers) {\n prop_checker->write(o);\n }\n }\n\n \/\/ merge all the databases in one: useful for crab clients\n virtual checks_db get_all_checks() const {\n checks_db res;\n for (auto prop_checker: m_checkers) {\n res += prop_checker->get_db();\n }\n return res;\n }\n\n };\n\n template<typename Analyzer> \n class intra_checker: public checker<Analyzer> {\n public:\n\n typedef checker<Analyzer> base_checker_t;\n using typename base_checker_t::prop_checker_ptr;\n using typename base_checker_t::prop_checker_vector;\n\n private:\n\n typedef typename Analyzer::cfg_t cfg_t;\n typedef typename cfg_t::statement_t statement_t;\n typedef typename Analyzer::abs_dom_t abs_dom_t;\n typedef typename Analyzer::abs_tr_t abs_tr_t;\n\n Analyzer& m_analyzer;\n\n public:\n\n intra_checker(Analyzer& analyzer, prop_checker_vector checkers)\n : base_checker_t(checkers)\n , m_analyzer(analyzer) { }\n \n \n virtual void run() override {\n CRAB_VERBOSE_IF(1, crab::outs() << \"Started property checker.\\n\";); \n crab::ScopedCrabStats __st__(\"Checker\");\n cfg_t cfg = m_analyzer.get_cfg();\n\n \/\/ In some cases, the analyzer might know that an assertion is\n \/\/ safe but it cannot be proven by propagating only\n \/\/ invariants. This is possible if the analyzer is based on a\n \/\/ forward\/backward refinement loop.\n std::set<const statement_t*> safe_assertions;\n m_analyzer.get_safe_assertions(safe_assertions);\n \n for (auto &bb: cfg) {\n for (auto checker: this->m_checkers) {\n crab::ScopedCrabStats __st__(\"Checker.\" + checker->get_property_name());\n abs_dom_t inv = m_analyzer[bb.label()];\n\t boost::shared_ptr<abs_tr_t> abs_tr = m_analyzer.get_abs_transformer(&inv);\n \/\/ propagate forward the invariants from the block entry \n \/\/ while checking the property\n checker->set(&*abs_tr, safe_assertions);\n for (auto &stmt: bb) {\n\t stmt.accept(&*checker);\n\t }\n }\n }\n CRAB_VERBOSE_IF(1, crab::outs() << \"Finished property checker.\\n\";);\n }\n };\n\n\n template< typename Analyzer>\n class inter_checker: public checker<Analyzer> {\n public:\n\n typedef checker<Analyzer> base_checker_t;\n using typename base_checker_t::prop_checker_ptr;\n using typename base_checker_t::prop_checker_vector;\n\n private:\n\n typedef typename Analyzer::cg_t cg_t;\n typedef typename Analyzer::cfg_t cfg_t;\n typedef typename cfg_t::statement_t statement_t; \n typedef typename Analyzer::abs_dom_t abs_dom_t;\n typedef typename Analyzer::abs_tr_t abs_tr_t;\n \n Analyzer& m_analyzer;\n \n public:\n\n inter_checker(Analyzer& analyzer, prop_checker_vector checkers)\n : base_checker_t(checkers), m_analyzer(analyzer) { }\n \n virtual void run() override {\n CRAB_VERBOSE_IF(1, crab::outs() << \"Started property checker.\\n\";);\n crab::ScopedCrabStats __st__(\"Checker\");\n cg_t& cg = m_analyzer.get_call_graph(); \n for (auto &v: boost::make_iterator_range(vertices(cg))) {\n cfg_t cfg = v.get_cfg();\n\t\n for (auto &bb: cfg) {\n\t \/\/ the forward+backward analyzer only works for\n\t \/\/ intra-procedural analysis.\n\t std::set<const statement_t*> safe_assertions;\n for (auto checker: this->m_checkers) {\n crab::ScopedCrabStats __st__(\"Checker.\" + checker->get_property_name());\n abs_dom_t inv = m_analyzer.get_pre(cfg, bb.label());\n\t boost::shared_ptr<abs_tr_t> abs_tr = m_analyzer.get_abs_transformer(&inv);\n \/\/ propagate forward the invariants from the block entry \n \/\/ while checking the property\n checker->set(&*abs_tr, safe_assertions);\n for (auto &stmt: bb) {\n stmt.accept(&*checker);\n\t }\n }\n }\n }\n CRAB_VERBOSE_IF(1, crab::outs() << \"Finished property checker.\";);\n\n \n }\n };\n\n } \/\/ end namespace\n} \/\/ end namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014, Salesforce.com, Inc. 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 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 Salesforce.com nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this\n\/\/ 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 HOLDER 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; LOSS\n\/\/ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n\/\/ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n\/\/ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include <cmath>\n#include <vector>\n#include <cstring>\n#include <iostream>\n#include <limits>\n#include <distributions\/common.hpp>\n#include <distributions\/vendor\/fmath.hpp>\n\n#define M_PIf (3.14159265358979f)\n\nnamespace distributions\n{\n\ntemplate<class T> T sqr (const T & t)\n{\n return t * t;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ fast_log, fast_exp, fast_log_sum_exp, log_sum_exp\n\nnamespace detail\n{\n\n\/\/\/ Implements the ICSI fast log algorithm, v2.\nclass FastLog\n{\npublic:\n\n FastLog (int N);\n\n inline float log (float x)\n {\n \/\/int intx = * reinterpret_cast<int *>(& x);\n int intx;\n memcpy(&intx, &x, 4);\n\n register const int exp = ((intx >> 23) & 255) - 127;\n register const int man = (intx & 0x7FFFFF) >> (23 - N_);\n\n \/\/ exponent plus lookup refinement\n return ((float)(exp) + table_[man]) * 0.69314718055994529f;\n }\n\nprivate:\n\n const int N_;\n std::vector<float> table_;\n};\n\nstatic FastLog GLOBAL_FAST_LOG_14(14);\n\n} \/\/ namespace detail\n\ninline float eric_log (float x)\n{\n return detail::GLOBAL_FAST_LOG_14.log(x);\n}\n\ninline float fast_log (float x)\n{\n return eric_log(x);\n \/\/return fmath::log(x);\n}\n\ninline float fast_exp (float x)\n{\n return fmath::exp(x);\n}\n\ninline float fast_log_sum_exp (float x, float y)\n{\n float min = x < y ? x : y;\n float max = x < y ? y : x;\n\n return max + fast_log(1.0f + fast_exp(min - max));\n}\n\ninline float log_sum_exp (float x, float y)\n{\n float min = x < y ? x : y;\n float max = x < y ? y : x;\n return max + logf(1.0f + expf(min - max));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ fast_lgamma, fast_log_beta, log_beta, log_binom, fast_log_binom\n\nnamespace detail\n{\n\nextern const char LogTable256[256];\nextern const float lgamma_approx_coeff5[];\n\n} \/\/ namespace detail\n\ninline float fast_lgamma (float y)\n{\n \/\/ A piecewise fifth-order approximation of loggamma,\n \/\/ which bottoms out in libc gammaln for vals < 1.0\n \/\/ and throws an exception outside of the domain 2**32\n \/\/\n \/\/ see loggamma.py for the code used to generate the coefficient table\n\n if (DIST_UNLIKELY(y < 2.5f or 4294967295.0f <= y)) {\n return lgammaf(y);\n }\n\n \/\/ adapted from:\n \/\/ http:\/\/www-graphics.stanford.edu\/~seander\/bithacks.html#IntegerLogLookup\n float v = y; \/\/ find int(log2(v)), where v > 0.0 && finite(v)\n int c; \/\/ 32-bit int c gets the result;\n int x = *(const int *) &v; \/\/ or portably: memcpy(&x, &v, sizeof x);\n\n c = x >> 23;\n\n if (c) {\n c -= 127;\n } else { \/\/ subnormal, so recompute using mantissa: c = intlog2(x) - 149;\n register unsigned int t; \/\/ temporary\n if ((t = x >> 16)) {\n c = detail::LogTable256[t] - 133;\n } else {\n c = (t = x >> 8)\n ? detail::LogTable256[t] - 141\n : detail::LogTable256[x] - 149;\n }\n }\n\n int pos = c *6;\n float a5 = detail::lgamma_approx_coeff5[pos];\n float a4 = detail::lgamma_approx_coeff5[pos + 1];\n float a3 = detail::lgamma_approx_coeff5[pos + 2];\n float a2 = detail::lgamma_approx_coeff5[pos + 3];\n float a1 = detail::lgamma_approx_coeff5[pos + 4];\n float a0 = detail::lgamma_approx_coeff5[pos + 5];\n\n double yprod = y;\n double sum = a0;\n sum += a1 * yprod;\n\n yprod *= y;\n sum += a2 * yprod;\n\n yprod *= y;\n sum += a3 * yprod;\n\n yprod *= y;\n sum += a4 * yprod;\n\n yprod *= y;\n sum += a5 * yprod;\n\n return sum;\n}\n\ninline float log_beta (float alpha, float beta)\n{\n if (DIST_UNLIKELY(alpha <= 0.f or beta <= 0.f)) {\n return - std::numeric_limits<float>::infinity();\n } else {\n return lgamma(alpha) + lgamma(beta) - lgamma(alpha + beta);\n }\n}\n\ninline float fast_log_beta (float alpha, float beta)\n{\n if (DIST_UNLIKELY(alpha <= 0.f or beta <= 0.f)) {\n return - std::numeric_limits<float>::infinity();\n } else {\n return fast_lgamma(alpha)\n + fast_lgamma(beta)\n - fast_lgamma(alpha + beta);\n }\n}\n\ninline float log_binom (float N, float k)\n{\n return lgamma(N + 1) - (lgamma(k + 1) + lgamma(N - k + 1));\n}\n\ninline float fast_log_binom (float N, float k)\n{\n return fast_lgamma(N + 1) - (fast_lgamma(k + 1) + fast_lgamma(N - k + 1));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ fast_log_factorial\n\nnamespace detail\n{\n\nextern const float log_factorial_table[64];\n\n} \/\/ namespace detail\n\ninline float fast_log_factorial(const uint32_t & n)\n{\n if (n < 64) {\n return detail::log_factorial_table[n];\n } else {\n return fast_lgamma(n + 1);\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ fast_lgamma_nu\n\nnamespace detail\n{\n\nextern const float lgamma_nu_func_approx_coeff3[];\n\ninline float poly_eval_3 (\n const float * __restrict__ coeff,\n float x)\n{\n \/\/ evaluate the polynomial with the indicated\n \/\/ coefficients\n float a0 = coeff[3];\n float a1 = coeff[2];\n float a2 = coeff[1];\n float a3 = coeff[0];\n\n return a0 + x*a1 + x*x*a2 + x*x*x*a3;\n}\n\n} \/\/ namespace detail\n\ninline float fast_lgamma_nu (float nu)\n{\n \/\/ Approximation of the sensitive, time-consuming\n \/\/ lgamma(nu \/ 2.0 + 0.5) - lgamma(nu\/2.0)\n \/\/ function inside log student t\n\n \/\/ see loggamma.py:lstudent for coeff gen\n\n if (DIST_UNLIKELY(nu < 0.0625f or 4294967295.0f <= nu)) {\n return lgammaf(nu * 0.5f + 0.5f) - lgammaf(nu * 0.5f);\n }\n\n \/\/ adapted from:\n \/\/ http:\/\/www-graphics.stanford.edu\/~seander\/bithacks.html#IntegerLogLookup\n float v = nu; \/\/ find int(log2(v)), where v > 0.0 && finite(v)\n int c; \/\/ 32-bit int c gets the result;\n int x = *(const int *) &v; \/\/ or portably: memcpy(&x, &v, sizeof x);\n\n c = x >> 23;\n\n if (c) {\n c -= 127;\n } else { \/\/ subnormal, so recompute using mantissa: c = intlog2(x) - 149;\n register unsigned int t; \/\/ temporary\n if ((t = x >> 16)) {\n c = detail::LogTable256[t] - 133;\n } else {\n c = (t = x >> 8)\n ? detail::LogTable256[t] - 141\n : detail::LogTable256[x] - 149;\n }\n }\n\n int pos = ((c + 4) \/ 2) * 4 ; \/\/ remember the POT range is 2\n return detail::poly_eval_3(detail::lgamma_nu_func_approx_coeff3 + pos, nu);\n}\n\n\/**\n * http:\/\/en.wikipedia.org\/wiki\/Multivariate_gamma_function\n *\/\ninline float lmultigamma(unsigned d, float a)\n{\n DIST_ASSERT1(d > 0, \"zero dim lmultigamma\");\n const float term1 = 0.25*float(d*(d-1))*1.1447298858494002 \/* log(pi) *\/;\n float term2 = 0.;\n for (int j = 1; j <= (int)d; j++)\n term2 += fast_lgamma(a + 0.5*float(1-j));\n return term1 + term2;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ misc\n\n\/\/ Compute stirling numbers of first kind S(n,k), one row at a time\n\/\/ return [log(S(n,0), ..., log(S(n,n))]\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Stirling_numbers_of_the_first_kind\ntemplate<class Alloc>\nvoid get_log_stirling1_row (size_t n, std::vector<float, Alloc> & result);\n\ninline std::vector<float> log_stirling1_row (size_t n)\n{\n std::vector<float> result;\n get_log_stirling1_row(n, result);\n return result;\n}\n\n} \/\/ namespace distributions\n<commit_msg>missing style<commit_after>\/\/ Copyright (c) 2014, Salesforce.com, Inc. 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 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 Salesforce.com nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this\n\/\/ 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 HOLDER 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; LOSS\n\/\/ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n\/\/ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n\/\/ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include <cmath>\n#include <vector>\n#include <cstring>\n#include <iostream>\n#include <limits>\n#include <distributions\/common.hpp>\n#include <distributions\/vendor\/fmath.hpp>\n\n#define M_PIf (3.14159265358979f)\n\nnamespace distributions\n{\n\ntemplate<class T> T sqr (const T & t)\n{\n return t * t;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ fast_log, fast_exp, fast_log_sum_exp, log_sum_exp\n\nnamespace detail\n{\n\n\/\/\/ Implements the ICSI fast log algorithm, v2.\nclass FastLog\n{\npublic:\n\n FastLog (int N);\n\n inline float log (float x)\n {\n \/\/int intx = * reinterpret_cast<int *>(& x);\n int intx;\n memcpy(&intx, &x, 4);\n\n register const int exp = ((intx >> 23) & 255) - 127;\n register const int man = (intx & 0x7FFFFF) >> (23 - N_);\n\n \/\/ exponent plus lookup refinement\n return ((float)(exp) + table_[man]) * 0.69314718055994529f;\n }\n\nprivate:\n\n const int N_;\n std::vector<float> table_;\n};\n\nstatic FastLog GLOBAL_FAST_LOG_14(14);\n\n} \/\/ namespace detail\n\ninline float eric_log (float x)\n{\n return detail::GLOBAL_FAST_LOG_14.log(x);\n}\n\ninline float fast_log (float x)\n{\n return eric_log(x);\n \/\/return fmath::log(x);\n}\n\ninline float fast_exp (float x)\n{\n return fmath::exp(x);\n}\n\ninline float fast_log_sum_exp (float x, float y)\n{\n float min = x < y ? x : y;\n float max = x < y ? y : x;\n\n return max + fast_log(1.0f + fast_exp(min - max));\n}\n\ninline float log_sum_exp (float x, float y)\n{\n float min = x < y ? x : y;\n float max = x < y ? y : x;\n return max + logf(1.0f + expf(min - max));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ fast_lgamma, fast_log_beta, log_beta, log_binom, fast_log_binom\n\nnamespace detail\n{\n\nextern const char LogTable256[256];\nextern const float lgamma_approx_coeff5[];\n\n} \/\/ namespace detail\n\ninline float fast_lgamma (float y)\n{\n \/\/ A piecewise fifth-order approximation of loggamma,\n \/\/ which bottoms out in libc gammaln for vals < 1.0\n \/\/ and throws an exception outside of the domain 2**32\n \/\/\n \/\/ see loggamma.py for the code used to generate the coefficient table\n\n if (DIST_UNLIKELY(y < 2.5f or 4294967295.0f <= y)) {\n return lgammaf(y);\n }\n\n \/\/ adapted from:\n \/\/ http:\/\/www-graphics.stanford.edu\/~seander\/bithacks.html#IntegerLogLookup\n float v = y; \/\/ find int(log2(v)), where v > 0.0 && finite(v)\n int c; \/\/ 32-bit int c gets the result;\n int x = *(const int *) &v; \/\/ or portably: memcpy(&x, &v, sizeof x);\n\n c = x >> 23;\n\n if (c) {\n c -= 127;\n } else { \/\/ subnormal, so recompute using mantissa: c = intlog2(x) - 149;\n register unsigned int t; \/\/ temporary\n if ((t = x >> 16)) {\n c = detail::LogTable256[t] - 133;\n } else {\n c = (t = x >> 8)\n ? detail::LogTable256[t] - 141\n : detail::LogTable256[x] - 149;\n }\n }\n\n int pos = c *6;\n float a5 = detail::lgamma_approx_coeff5[pos];\n float a4 = detail::lgamma_approx_coeff5[pos + 1];\n float a3 = detail::lgamma_approx_coeff5[pos + 2];\n float a2 = detail::lgamma_approx_coeff5[pos + 3];\n float a1 = detail::lgamma_approx_coeff5[pos + 4];\n float a0 = detail::lgamma_approx_coeff5[pos + 5];\n\n double yprod = y;\n double sum = a0;\n sum += a1 * yprod;\n\n yprod *= y;\n sum += a2 * yprod;\n\n yprod *= y;\n sum += a3 * yprod;\n\n yprod *= y;\n sum += a4 * yprod;\n\n yprod *= y;\n sum += a5 * yprod;\n\n return sum;\n}\n\ninline float log_beta (float alpha, float beta)\n{\n if (DIST_UNLIKELY(alpha <= 0.f or beta <= 0.f)) {\n return - std::numeric_limits<float>::infinity();\n } else {\n return lgamma(alpha) + lgamma(beta) - lgamma(alpha + beta);\n }\n}\n\ninline float fast_log_beta (float alpha, float beta)\n{\n if (DIST_UNLIKELY(alpha <= 0.f or beta <= 0.f)) {\n return - std::numeric_limits<float>::infinity();\n } else {\n return fast_lgamma(alpha)\n + fast_lgamma(beta)\n - fast_lgamma(alpha + beta);\n }\n}\n\ninline float log_binom (float N, float k)\n{\n return lgamma(N + 1) - (lgamma(k + 1) + lgamma(N - k + 1));\n}\n\ninline float fast_log_binom (float N, float k)\n{\n return fast_lgamma(N + 1) - (fast_lgamma(k + 1) + fast_lgamma(N - k + 1));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ fast_log_factorial\n\nnamespace detail\n{\n\nextern const float log_factorial_table[64];\n\n} \/\/ namespace detail\n\ninline float fast_log_factorial(const uint32_t & n)\n{\n if (n < 64) {\n return detail::log_factorial_table[n];\n } else {\n return fast_lgamma(n + 1);\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ fast_lgamma_nu\n\nnamespace detail\n{\n\nextern const float lgamma_nu_func_approx_coeff3[];\n\ninline float poly_eval_3 (\n const float * __restrict__ coeff,\n float x)\n{\n \/\/ evaluate the polynomial with the indicated\n \/\/ coefficients\n float a0 = coeff[3];\n float a1 = coeff[2];\n float a2 = coeff[1];\n float a3 = coeff[0];\n\n return a0 + x*a1 + x*x*a2 + x*x*x*a3;\n}\n\n} \/\/ namespace detail\n\ninline float fast_lgamma_nu (float nu)\n{\n \/\/ Approximation of the sensitive, time-consuming\n \/\/ lgamma(nu \/ 2.0 + 0.5) - lgamma(nu\/2.0)\n \/\/ function inside log student t\n\n \/\/ see loggamma.py:lstudent for coeff gen\n\n if (DIST_UNLIKELY(nu < 0.0625f or 4294967295.0f <= nu)) {\n return lgammaf(nu * 0.5f + 0.5f) - lgammaf(nu * 0.5f);\n }\n\n \/\/ adapted from:\n \/\/ http:\/\/www-graphics.stanford.edu\/~seander\/bithacks.html#IntegerLogLookup\n float v = nu; \/\/ find int(log2(v)), where v > 0.0 && finite(v)\n int c; \/\/ 32-bit int c gets the result;\n int x = *(const int *) &v; \/\/ or portably: memcpy(&x, &v, sizeof x);\n\n c = x >> 23;\n\n if (c) {\n c -= 127;\n } else { \/\/ subnormal, so recompute using mantissa: c = intlog2(x) - 149;\n register unsigned int t; \/\/ temporary\n if ((t = x >> 16)) {\n c = detail::LogTable256[t] - 133;\n } else {\n c = (t = x >> 8)\n ? detail::LogTable256[t] - 141\n : detail::LogTable256[x] - 149;\n }\n }\n\n int pos = ((c + 4) \/ 2) * 4 ; \/\/ remember the POT range is 2\n return detail::poly_eval_3(detail::lgamma_nu_func_approx_coeff3 + pos, nu);\n}\n\n\/**\n * http:\/\/en.wikipedia.org\/wiki\/Multivariate_gamma_function\n *\/\ninline float lmultigamma(unsigned d, float a)\n{\n DIST_ASSERT1(d > 0, \"zero dim lmultigamma\");\n const float log_pi = 1.1447298858494002;\n const float term1 = 0.25 * float(d * (d - 1)) * log_pi;\n float term2 = 0.;\n for (int j = 1; j <= (int)d; j++)\n term2 += fast_lgamma(a + 0.5 * float(1 - j));\n return term1 + term2;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ misc\n\n\/\/ Compute stirling numbers of first kind S(n,k), one row at a time\n\/\/ return [log(S(n,0), ..., log(S(n,n))]\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Stirling_numbers_of_the_first_kind\ntemplate<class Alloc>\nvoid get_log_stirling1_row (size_t n, std::vector<float, Alloc> & result);\n\ninline std::vector<float> log_stirling1_row (size_t n)\n{\n std::vector<float> result;\n get_log_stirling1_row(n, result);\n return result;\n}\n\n} \/\/ namespace distributions\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2006-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#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED\n#define TORRENT_EXTENSIONS_HPP_INCLUDED\n\n#ifndef TORRENT_DISABLE_EXTENSIONS\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/weak_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/socket.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux { struct session_impl; }\n\n\tstruct peer_plugin;\n\tclass bt_peer_connection;\n\tstruct peer_request;\n\tclass peer_connection;\n\tclass entry;\n\tstruct lazy_entry;\n\tstruct disk_buffer_holder;\n\tstruct bitfield;\n\tclass alert;\n\tstruct torrent_plugin;\n\tclass torrent;\n\n\tstruct TORRENT_EXPORT plugin\n\t{\n\t\tvirtual ~plugin() {}\n\n\t\tvirtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)\n\t\t{ return boost::shared_ptr<torrent_plugin>(); }\n\n\t\t\/\/ called when plugin is added to a session\n\t\tvirtual void added(boost::weak_ptr<aux::session_impl> s) {}\n\n\t\t\/\/ called when an alert is posted\n\t\t\/\/ alerts that are filtered are not\n\t\t\/\/ posted\n\t\tvirtual void on_alert(alert const* a) {}\n\n\t\t\/\/ called once per second\n\t\tvirtual void on_tick() {}\n\n\t\t\/\/ called when saving settings state\n\t\tvirtual void save_state(entry& ent) const {}\n\n\t\t\/\/ called when loading settings state\n\t\tvirtual void load_state(lazy_entry const& ent) {}\n\t};\n\n\tstruct TORRENT_EXPORT torrent_plugin\n\t{\n\t\tvirtual ~torrent_plugin() {}\n\t\t\/\/ throwing an exception closes the connection\n\t\t\/\/ returning a 0 pointer is valid and will not add\n\t\t\/\/ the peer_plugin to the peer_connection\n\t\tvirtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)\n\t\t{ return boost::shared_ptr<peer_plugin>(); }\n\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ if true is returned, it means the handler handled the event,\n\t\t\/\/ and no other plugins will have their handlers called, and the\n\t\t\/\/ default behavior will be skipped\n\t\tvirtual bool on_pause() { return false; }\n\t\tvirtual bool on_resume() { return false; }\n\n\t\t\/\/ this is called when the initial checking of\n\t\t\/\/ files is completed.\n\t\tvirtual void on_files_checked() {}\n\n\t\t\/\/ called when the torrent changes state\n\t\t\/\/ the state is one of torrent_status::state_t\n\t\t\/\/ enum members\n\t\tvirtual void on_state(int s) {}\n\n\t\t\/\/ called every time policy::add_peer is called\n\t\t\/\/ src is a bitmask of which sources this peer\n\t\t\/\/ has been seen from. flags is a bitmask of:\n\n\t\tenum flags_t {\n\t\t\t\/\/ this is the first time we see this peer\n\t\t\tfirst_time = 1,\n\t\t\t\/\/ this peer was not added because it was\n\t\t\t\/\/ filtered by the IP filter\n\t\t\tfiltered = 2\n\t\t};\n\n\t\tvirtual void on_add_peer(tcp::endpoint const& ip\n\t\t\t, int src, int flags) {}\n\t};\n\n\tstruct TORRENT_EXPORT peer_plugin\n\t{\n\t\tvirtual ~peer_plugin() {}\n\n\t\tvirtual char const* type() const { return \"\"; }\n\n\t\t\/\/ can add entries to the extension handshake\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual void add_handshake(entry&) {}\n\t\t\n\t\t\/\/ throwing an exception from any of the handlers (except add_handshake)\n\t\t\/\/ closes the connection\n\t\t\n\t\t\/\/ this is called when the initial BT handshake is received. Returning false\n\t\t\/\/ means that the other end doesn't support this extension and will remove\n\t\t\/\/ it from the list of plugins.\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_handshake(char const* reserved_bits) { return true; }\n\t\t\n\t\t\/\/ called when the extension handshake from the other end is received\n\t\t\/\/ if this returns false, it means that this extension isn't\n\t\t\/\/ supported by this peer. It will result in this peer_plugin\n\t\t\/\/ being removed from the peer_connection and destructed. \n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extension_handshake(lazy_entry const& h) { return true; }\n\n\t\t\/\/ returning true from any of the message handlers\n\t\t\/\/ indicates that the plugin has handeled the message.\n\t\t\/\/ it will break the plugin chain traversing and not let\n\t\t\/\/ anyone else handle the message, including the default\n\t\t\/\/ handler.\n\n\t\tvirtual bool on_choke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_unchoke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_not_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_dont_have(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_bitfield(bitfield const& bitfield)\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_all()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_none()\n\t\t{ return false; }\n\n\t\tvirtual bool on_allowed_fast(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_request(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)\n\t\t{ return false; }\n\n\t\tvirtual bool on_cancel(peer_request const& req)\n\t\t{ return false; }\n\t\n\t\tvirtual bool on_reject(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_suggest(int index)\n\t\t{ return false; }\n\n\t\t\/\/ called when an extended message is received. If returning true,\n\t\t\/\/ the message is not processed by any other plugin and if false\n\t\t\/\/ is returned the next plugin in the chain will receive it to\n\t\t\/\/ be able to handle it\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extended(int length\n\t\t\t, int msg, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_unknown_message(int length, int msg\n\t\t\t, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ called when a piece that this peer participated in either\n\t\t\/\/ fails or passes the hash_check\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ called each time a request message is to be sent. If true\n\t\t\/\/ is returned, the original request message won't be sent and\n\t\t\/\/ no other plugin will have this function called.\n\t\tvirtual bool write_request(peer_request const& r) { return false; }\n\t};\n\n}\n\n#endif\n\n#endif \/\/ TORRENT_EXTENSIONS_HPP_INCLUDED\n\n<commit_msg>fix some unused variables warnings in extension.hpp<commit_after>\/*\n\nCopyright (c) 2006-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#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED\n#define TORRENT_EXTENSIONS_HPP_INCLUDED\n\n#ifndef TORRENT_DISABLE_EXTENSIONS\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/weak_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/socket.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux { struct session_impl; }\n\n\tstruct peer_plugin;\n\tclass bt_peer_connection;\n\tstruct peer_request;\n\tclass peer_connection;\n\tclass entry;\n\tstruct lazy_entry;\n\tstruct disk_buffer_holder;\n\tstruct bitfield;\n\tclass alert;\n\tstruct torrent_plugin;\n\tclass torrent;\n\n\tstruct TORRENT_EXPORT plugin\n\t{\n\t\tvirtual ~plugin() {}\n\n\t\tvirtual boost::shared_ptr<torrent_plugin> new_torrent(torrent*, void*)\n\t\t{ return boost::shared_ptr<torrent_plugin>(); }\n\n\t\t\/\/ called when plugin is added to a session\n\t\tvirtual void added(boost::weak_ptr<aux::session_impl>) {}\n\n\t\t\/\/ called when an alert is posted\n\t\t\/\/ alerts that are filtered are not\n\t\t\/\/ posted\n\t\tvirtual void on_alert(alert const*) {}\n\n\t\t\/\/ called once per second\n\t\tvirtual void on_tick() {}\n\n\t\t\/\/ called when saving settings state\n\t\tvirtual void save_state(entry&) const {}\n\n\t\t\/\/ called when loading settings state\n\t\tvirtual void load_state(lazy_entry const&) {}\n\t};\n\n\tstruct TORRENT_EXPORT torrent_plugin\n\t{\n\t\tvirtual ~torrent_plugin() {}\n\t\t\/\/ throwing an exception closes the connection\n\t\t\/\/ returning a 0 pointer is valid and will not add\n\t\t\/\/ the peer_plugin to the peer_connection\n\t\tvirtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)\n\t\t{ return boost::shared_ptr<peer_plugin>(); }\n\n\t\tvirtual void on_piece_pass(int \/*index*\/) {}\n\t\tvirtual void on_piece_failed(int \/*index*\/) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ if true is returned, it means the handler handled the event,\n\t\t\/\/ and no other plugins will have their handlers called, and the\n\t\t\/\/ default behavior will be skipped\n\t\tvirtual bool on_pause() { return false; }\n\t\tvirtual bool on_resume() { return false; }\n\n\t\t\/\/ this is called when the initial checking of\n\t\t\/\/ files is completed.\n\t\tvirtual void on_files_checked() {}\n\n\t\t\/\/ called when the torrent changes state\n\t\t\/\/ the state is one of torrent_status::state_t\n\t\t\/\/ enum members\n\t\tvirtual void on_state(int \/*s*\/) {}\n\n\t\t\/\/ called every time policy::add_peer is called\n\t\t\/\/ src is a bitmask of which sources this peer\n\t\t\/\/ has been seen from. flags is a bitmask of:\n\n\t\tenum flags_t {\n\t\t\t\/\/ this is the first time we see this peer\n\t\t\tfirst_time = 1,\n\t\t\t\/\/ this peer was not added because it was\n\t\t\t\/\/ filtered by the IP filter\n\t\t\tfiltered = 2\n\t\t};\n\n\t\tvirtual void on_add_peer(tcp::endpoint const&,\n\t\t\tint \/*src*\/, int \/*flags*\/) {}\n\t};\n\n\tstruct TORRENT_EXPORT peer_plugin\n\t{\n\t\tvirtual ~peer_plugin() {}\n\n\t\tvirtual char const* type() const { return \"\"; }\n\n\t\t\/\/ can add entries to the extension handshake\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual void add_handshake(entry&) {}\n\t\t\n\t\t\/\/ throwing an exception from any of the handlers (except add_handshake)\n\t\t\/\/ closes the connection\n\t\t\n\t\t\/\/ this is called when the initial BT handshake is received. Returning false\n\t\t\/\/ means that the other end doesn't support this extension and will remove\n\t\t\/\/ it from the list of plugins.\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_handshake(char const* \/*reserved_bits*\/) { return true; }\n\t\t\n\t\t\/\/ called when the extension handshake from the other end is received\n\t\t\/\/ if this returns false, it means that this extension isn't\n\t\t\/\/ supported by this peer. It will result in this peer_plugin\n\t\t\/\/ being removed from the peer_connection and destructed. \n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extension_handshake(lazy_entry const&) { return true; }\n\n\t\t\/\/ returning true from any of the message handlers\n\t\t\/\/ indicates that the plugin has handeled the message.\n\t\t\/\/ it will break the plugin chain traversing and not let\n\t\t\/\/ anyone else handle the message, including the default\n\t\t\/\/ handler.\n\n\t\tvirtual bool on_choke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_unchoke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_not_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have(int \/*index*\/)\n\t\t{ return false; }\n\n\t\tvirtual bool on_dont_have(int \/*index*\/)\n\t\t{ return false; }\n\n\t\tvirtual bool on_bitfield(bitfield const& \/*bitfield*\/)\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_all()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_none()\n\t\t{ return false; }\n\n\t\tvirtual bool on_allowed_fast(int \/*index*\/)\n\t\t{ return false; }\n\n\t\tvirtual bool on_request(peer_request const&)\n\t\t{ return false; }\n\n\t\tvirtual bool on_piece(peer_request const& \/*piece*\/, disk_buffer_holder& \/*data*\/)\n\t\t{ return false; }\n\n\t\tvirtual bool on_cancel(peer_request const&)\n\t\t{ return false; }\n\t\n\t\tvirtual bool on_reject(peer_request const&)\n\t\t{ return false; }\n\n\t\tvirtual bool on_suggest(int \/*index*\/)\n\t\t{ return false; }\n\n\t\t\/\/ called when an extended message is received. If returning true,\n\t\t\/\/ the message is not processed by any other plugin and if false\n\t\t\/\/ is returned the next plugin in the chain will receive it to\n\t\t\/\/ be able to handle it\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extended(int \/*length*\/, int \/*msg*\/,\n\t\t\tbuffer::const_interval \/*body*\/)\n\t\t{ return false; }\n\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_unknown_message(int \/*length*\/, int \/*msg*\/,\n\t\t\tbuffer::const_interval \/*body*\/)\n\t\t{ return false; }\n\n\t\t\/\/ called when a piece that this peer participated in either\n\t\t\/\/ fails or passes the hash_check\n\t\tvirtual void on_piece_pass(int \/*index*\/) {}\n\t\tvirtual void on_piece_failed(int \/*index*\/) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ called each time a request message is to be sent. If true\n\t\t\/\/ is returned, the original request message won't be sent and\n\t\t\/\/ no other plugin will have this function called.\n\t\tvirtual bool write_request(peer_request const&) { return false; }\n\t};\n\n}\n\n#endif\n\n#endif \/\/ TORRENT_EXTENSIONS_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/*\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#ifndef TORRENT_LAZY_ENTRY_HPP_INCLUDED\n#define TORRENT_LAZY_ENTRY_HPP_INCLUDED\n\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstring>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/size_type.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\n#if TORRENT_USE_IOSTREAM\n#include <iosfwd>\n#endif\n\nnamespace libtorrent\n{\n\tstruct lazy_entry;\n\n\tTORRENT_EXPORT char const* parse_int(char const* start, char const* end\n\t\t, char delimiter, boost::int64_t& val);\n\n\t\/\/ return 0 = success\n\tTORRENT_EXPORT int lazy_bdecode(char const* start, char const* end\n\t\t, lazy_entry& ret, error_code& ec, int* error_pos = 0\n\t\t, int depth_limit = 1000, int item_limit = 1000000);\n\n#ifndef TORRENT_NO_DEPRECATE\n\t\/\/ for backwards compatibility, does not report error code\n\t\/\/ deprecated in 0.16\n\tTORRENT_DEPRECATED_PREFIX\n\tTORRENT_EXPORT int lazy_bdecode(char const* start, char const* end\n\t\t, lazy_entry& ret, int depth_limit = 1000, int item_limit = 1000000) TORRENT_DEPRECATED;\n#endif\n\n\tstruct pascal_string\n\t{\n\t\tpascal_string(char const* p, int l): len(l), ptr(p) {}\n\t\tint len;\n\t\tchar const* ptr;\n\t\tbool operator<(pascal_string const& rhs) const\n\t\t{\n\t\t\treturn std::memcmp(ptr, rhs.ptr, (std::min)(len, rhs.len)) < 0\n\t\t\t\t|| len < rhs.len;\n\t\t}\n\t};\n\n\tstruct lazy_dict_entry;\n\n\tstruct TORRENT_EXPORT lazy_entry\n\t{\n\t\tenum entry_type_t\n\t\t{\n\t\t\tnone_t, dict_t, list_t, string_t, int_t\n\t\t};\n\n\t\tlazy_entry() : m_begin(0), m_len(0), m_size(0), m_capacity(0), m_type(none_t)\n\t\t{ m_data.start = 0; }\n\n\t\tentry_type_t type() const { return (entry_type_t)m_type; }\n\n\t\t\/\/ start points to the first decimal digit\n\t\t\/\/ length is the number of digits\n\t\tvoid construct_int(char const* start, int length)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = int_t;\n\t\t\tm_data.start = start;\n\t\t\tm_size = length;\n\t\t\tm_begin = start - 1; \/\/ include 'i'\n\t\t\tm_len = length + 2; \/\/ include 'e'\n\t\t}\n\n\t\tsize_type int_value() const;\n\n\t\t\/\/ string functions\n\t\t\/\/ ================\n\n\t\tvoid construct_string(char const* start, int length);\n\n\t\t\/\/ the string is not null-terminated!\n\t\tchar const* string_ptr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn m_data.start;\n\t\t}\n\n\t\t\/\/ this will return a null terminated string\n\t\t\/\/ it will write to the source buffer!\n\t\tchar const* string_cstr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\tconst_cast<char*>(m_data.start)[m_size] = 0;\n\t\t\treturn m_data.start;\n\t\t}\n\n\t\tpascal_string string_pstr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn pascal_string(m_data.start, m_size);\n\t\t}\n\n\t\tstd::string string_value() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn std::string(m_data.start, m_size);\n\t\t}\n\n\t\tint string_length() const\n\t\t{ return m_size; }\n\n\t\t\/\/ dictionary functions\n\t\t\/\/ ====================\n\n\t\tvoid construct_dict(char const* begin)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = dict_t;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_begin = begin;\n\t\t}\n\n\t\tlazy_entry* dict_append(char const* name);\n\t\tvoid pop();\n\t\tlazy_entry* dict_find(char const* name);\n\t\tlazy_entry const* dict_find(char const* name) const\n\t\t{ return const_cast<lazy_entry*>(this)->dict_find(name); }\n\n\t\tstd::string dict_find_string_value(char const* name) const;\n\t\tpascal_string dict_find_pstr(char const* name) const;\n\t\tsize_type dict_find_int_value(char const* name, size_type default_val = 0) const;\n\t\tlazy_entry const* dict_find_dict(char const* name) const;\n\t\tlazy_entry const* dict_find_list(char const* name) const;\n\t\tlazy_entry const* dict_find_string(char const* name) const;\n\t\tlazy_entry const* dict_find_int(char const* name) const;\n\n\t\tstd::pair<std::string, lazy_entry const*> dict_at(int i) const;\n\n\t\tint dict_size() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == dict_t);\n\t\t\treturn m_size;\n\t\t}\n\n\t\t\/\/ list functions\n\t\t\/\/ ==============\n\n\t\tvoid construct_list(char const* begin)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = list_t;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_begin = begin;\n\t\t}\n\n\t\tlazy_entry* list_append();\n\t\tlazy_entry* list_at(int i)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == list_t);\n\t\t\tTORRENT_ASSERT(i < int(m_size));\n\t\t\treturn &m_data.list[i];\n\t\t}\n\t\tlazy_entry const* list_at(int i) const\n\t\t{ return const_cast<lazy_entry*>(this)->list_at(i); }\n\n\t\tstd::string list_string_value_at(int i) const;\n\t\tpascal_string list_pstr_at(int i) const;\n\t\tsize_type list_int_value_at(int i, size_type default_val = 0) const;\n\n\t\tint list_size() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == list_t);\n\t\t\treturn int(m_size);\n\t\t}\n\n\t\t\/\/ end points one byte passed last byte\n\t\tvoid set_end(char const* end)\n\t\t{\n\t\t\tTORRENT_ASSERT(end > m_begin);\n\t\t\tm_len = end - m_begin;\n\t\t}\n\t\t\n\t\tvoid clear();\n\n\t\t\/\/ releases ownership of any memory allocated\n\t\tvoid release()\n\t\t{\n\t\t\tm_data.start = 0;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_type = none_t;\n\t\t}\n\n\t\t~lazy_entry()\n\t\t{ clear(); }\n\n\t\t\/\/ returns pointers into the source buffer where\n\t\t\/\/ this entry has its bencoded data\n\t\tstd::pair<char const*, int> data_section() const;\n\n\t\tvoid swap(lazy_entry& e)\n\t\t{\n\t\t\tusing std::swap;\n\t\t\tboost::uint32_t tmp = e.m_type;\n\t\t\te.m_type = m_type;\n\t\t\tm_type = tmp;\n\t\t\ttmp = e.m_capacity;\n\t\t\te.m_capacity = m_capacity;\n\t\t\tm_capacity = tmp;\n\t\t\tswap(m_data.start, e.m_data.start);\n\t\t\tswap(m_size, e.m_size);\n\t\t\tswap(m_begin, e.m_begin);\n\t\t\tswap(m_len, e.m_len);\n\t\t}\n\n\tprivate:\n\n\t\tunion data_t\n\t\t{\n\t\t\tlazy_dict_entry* dict;\n\t\t\tlazy_entry* list;\n\t\t\tchar const* start;\n\t\t} m_data;\n\n\t\t\/\/ used for dictionaries and lists to record the range\n\t\t\/\/ in the original buffer they are based on\n\t\tchar const* m_begin;\n\t\t\/\/ the number of bytes this entry extends in the\n\t\t\/\/ bencoded byffer\n\t\tboost::uint32_t m_len;\n\n\t\t\/\/ if list or dictionary, the number of items\n\t\tboost::uint32_t m_size;\n\t\t\/\/ if list or dictionary, allocated number of items\n\t\tboost::uint32_t m_capacity:29;\n\t\t\/\/ element type (dict, list, int, string)\n\t\tboost::uint32_t m_type:3;\n\n\t\t\/\/ non-copyable\n\t\tlazy_entry(lazy_entry const&);\n\t\tlazy_entry const& operator=(lazy_entry const&);\n\t};\n\n\tstruct lazy_dict_entry\n\t{\n\t\tchar const* name;\n\t\tlazy_entry val;\n\t};\n\n\tTORRENT_EXPORT std::string print_entry(lazy_entry const& e\n\t\t, bool single_line = false, int indent = 0);\n#if TORRENT_USE_IOSTREAM\n\tTORRENT_EXPORT std::ostream& operator<<(std::ostream& os, lazy_entry const& e);\n#endif\n\n}\n\n\n#endif\n\n<commit_msg>attempt to fix msvc12 build<commit_after>\/*\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#ifndef TORRENT_LAZY_ENTRY_HPP_INCLUDED\n#define TORRENT_LAZY_ENTRY_HPP_INCLUDED\n\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/size_type.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\n#if TORRENT_USE_IOSTREAM\n#include <iosfwd>\n#endif\n\nnamespace libtorrent\n{\n\tstruct lazy_entry;\n\n\tTORRENT_EXPORT char const* parse_int(char const* start, char const* end\n\t\t, char delimiter, boost::int64_t& val);\n\n\t\/\/ return 0 = success\n\tTORRENT_EXPORT int lazy_bdecode(char const* start, char const* end\n\t\t, lazy_entry& ret, error_code& ec, int* error_pos = 0\n\t\t, int depth_limit = 1000, int item_limit = 1000000);\n\n#ifndef TORRENT_NO_DEPRECATE\n\t\/\/ for backwards compatibility, does not report error code\n\t\/\/ deprecated in 0.16\n\tTORRENT_DEPRECATED_PREFIX\n\tTORRENT_EXPORT int lazy_bdecode(char const* start, char const* end\n\t\t, lazy_entry& ret, int depth_limit = 1000, int item_limit = 1000000) TORRENT_DEPRECATED;\n#endif\n\n\tstruct pascal_string\n\t{\n\t\tpascal_string(char const* p, int l): len(l), ptr(p) {}\n\t\tint len;\n\t\tchar const* ptr;\n\t\tbool operator<(pascal_string const& rhs) const\n\t\t{\n\t\t\treturn std::memcmp(ptr, rhs.ptr, (std::min)(len, rhs.len)) < 0\n\t\t\t\t|| len < rhs.len;\n\t\t}\n\t};\n\n\tstruct lazy_dict_entry;\n\n\tstruct TORRENT_EXPORT lazy_entry\n\t{\n\t\tenum entry_type_t\n\t\t{\n\t\t\tnone_t, dict_t, list_t, string_t, int_t\n\t\t};\n\n\t\tlazy_entry() : m_begin(0), m_len(0), m_size(0), m_capacity(0), m_type(none_t)\n\t\t{ m_data.start = 0; }\n\n\t\tentry_type_t type() const { return (entry_type_t)m_type; }\n\n\t\t\/\/ start points to the first decimal digit\n\t\t\/\/ length is the number of digits\n\t\tvoid construct_int(char const* start, int length)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = int_t;\n\t\t\tm_data.start = start;\n\t\t\tm_size = length;\n\t\t\tm_begin = start - 1; \/\/ include 'i'\n\t\t\tm_len = length + 2; \/\/ include 'e'\n\t\t}\n\n\t\tsize_type int_value() const;\n\n\t\t\/\/ string functions\n\t\t\/\/ ================\n\n\t\tvoid construct_string(char const* start, int length);\n\n\t\t\/\/ the string is not null-terminated!\n\t\tchar const* string_ptr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn m_data.start;\n\t\t}\n\n\t\t\/\/ this will return a null terminated string\n\t\t\/\/ it will write to the source buffer!\n\t\tchar const* string_cstr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\tconst_cast<char*>(m_data.start)[m_size] = 0;\n\t\t\treturn m_data.start;\n\t\t}\n\n\t\tpascal_string string_pstr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn pascal_string(m_data.start, m_size);\n\t\t}\n\n\t\tstd::string string_value() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn std::string(m_data.start, m_size);\n\t\t}\n\n\t\tint string_length() const\n\t\t{ return m_size; }\n\n\t\t\/\/ dictionary functions\n\t\t\/\/ ====================\n\n\t\tvoid construct_dict(char const* begin)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = dict_t;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_begin = begin;\n\t\t}\n\n\t\tlazy_entry* dict_append(char const* name);\n\t\tvoid pop();\n\t\tlazy_entry* dict_find(char const* name);\n\t\tlazy_entry const* dict_find(char const* name) const\n\t\t{ return const_cast<lazy_entry*>(this)->dict_find(name); }\n\n\t\tstd::string dict_find_string_value(char const* name) const;\n\t\tpascal_string dict_find_pstr(char const* name) const;\n\t\tsize_type dict_find_int_value(char const* name, size_type default_val = 0) const;\n\t\tlazy_entry const* dict_find_dict(char const* name) const;\n\t\tlazy_entry const* dict_find_list(char const* name) const;\n\t\tlazy_entry const* dict_find_string(char const* name) const;\n\t\tlazy_entry const* dict_find_int(char const* name) const;\n\n\t\tstd::pair<std::string, lazy_entry const*> dict_at(int i) const;\n\n\t\tint dict_size() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == dict_t);\n\t\t\treturn m_size;\n\t\t}\n\n\t\t\/\/ list functions\n\t\t\/\/ ==============\n\n\t\tvoid construct_list(char const* begin)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = list_t;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_begin = begin;\n\t\t}\n\n\t\tlazy_entry* list_append();\n\t\tlazy_entry* list_at(int i)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == list_t);\n\t\t\tTORRENT_ASSERT(i < int(m_size));\n\t\t\treturn &m_data.list[i];\n\t\t}\n\t\tlazy_entry const* list_at(int i) const\n\t\t{ return const_cast<lazy_entry*>(this)->list_at(i); }\n\n\t\tstd::string list_string_value_at(int i) const;\n\t\tpascal_string list_pstr_at(int i) const;\n\t\tsize_type list_int_value_at(int i, size_type default_val = 0) const;\n\n\t\tint list_size() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == list_t);\n\t\t\treturn int(m_size);\n\t\t}\n\n\t\t\/\/ end points one byte passed last byte\n\t\tvoid set_end(char const* end)\n\t\t{\n\t\t\tTORRENT_ASSERT(end > m_begin);\n\t\t\tm_len = end - m_begin;\n\t\t}\n\t\t\n\t\tvoid clear();\n\n\t\t\/\/ releases ownership of any memory allocated\n\t\tvoid release()\n\t\t{\n\t\t\tm_data.start = 0;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_type = none_t;\n\t\t}\n\n\t\t~lazy_entry()\n\t\t{ clear(); }\n\n\t\t\/\/ returns pointers into the source buffer where\n\t\t\/\/ this entry has its bencoded data\n\t\tstd::pair<char const*, int> data_section() const;\n\n\t\tvoid swap(lazy_entry& e)\n\t\t{\n\t\t\tusing std::swap;\n\t\t\tboost::uint32_t tmp = e.m_type;\n\t\t\te.m_type = m_type;\n\t\t\tm_type = tmp;\n\t\t\ttmp = e.m_capacity;\n\t\t\te.m_capacity = m_capacity;\n\t\t\tm_capacity = tmp;\n\t\t\tswap(m_data.start, e.m_data.start);\n\t\t\tswap(m_size, e.m_size);\n\t\t\tswap(m_begin, e.m_begin);\n\t\t\tswap(m_len, e.m_len);\n\t\t}\n\n\tprivate:\n\n\t\tunion data_t\n\t\t{\n\t\t\tlazy_dict_entry* dict;\n\t\t\tlazy_entry* list;\n\t\t\tchar const* start;\n\t\t} m_data;\n\n\t\t\/\/ used for dictionaries and lists to record the range\n\t\t\/\/ in the original buffer they are based on\n\t\tchar const* m_begin;\n\t\t\/\/ the number of bytes this entry extends in the\n\t\t\/\/ bencoded byffer\n\t\tboost::uint32_t m_len;\n\n\t\t\/\/ if list or dictionary, the number of items\n\t\tboost::uint32_t m_size;\n\t\t\/\/ if list or dictionary, allocated number of items\n\t\tboost::uint32_t m_capacity:29;\n\t\t\/\/ element type (dict, list, int, string)\n\t\tboost::uint32_t m_type:3;\n\n\t\t\/\/ non-copyable\n\t\tlazy_entry(lazy_entry const&);\n\t\tlazy_entry const& operator=(lazy_entry const&);\n\t};\n\n\tstruct lazy_dict_entry\n\t{\n\t\tchar const* name;\n\t\tlazy_entry val;\n\t};\n\n\tTORRENT_EXPORT std::string print_entry(lazy_entry const& e\n\t\t, bool single_line = false, int indent = 0);\n#if TORRENT_USE_IOSTREAM\n\tTORRENT_EXPORT std::ostream& operator<<(std::ostream& os, lazy_entry const& e);\n#endif\n\n}\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, 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#ifndef TORRENT_PROXY_BASE_HPP_INCLUDED\n#define TORRENT_PROXY_BASE_HPP_INCLUDED\n\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include <boost\/bind.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/function.hpp>\n#include <asio\/read.hpp>\n#include <asio\/write.hpp>\n\n\nnamespace libtorrent {\n\nclass proxy_base : boost::noncopyable\n{\npublic:\n\n\ttypedef stream_socket::lowest_layer_type lowest_layer_type;\n\ttypedef stream_socket::endpoint_type endpoint_type;\n\ttypedef stream_socket::protocol_type protocol_type;\n\n\texplicit proxy_base(asio::io_service& io_service)\n\t\t: m_sock(io_service)\n\t\t, m_resolver(io_service)\n\t{}\n\n\tvoid set_proxy(std::string hostname, int port)\n\t{\n\t\tm_hostname = hostname;\n\t\tm_port = port;\n\t}\n\n\ttemplate <class Mutable_Buffers, class Handler>\n\tvoid async_read_some(Mutable_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tm_sock.async_read_some(buffers, handler);\n\t}\n\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers, asio::error_code& ec)\n\t{\n\t\treturn m_sock.read_some(buffers, ec);\n\t}\n\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers)\n\t{\n\t\treturn m_sock.read_some(buffers);\n\t}\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc)\n\t{\n\t\tm_sock.io_control(ioc);\n\t}\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc, asio::error_code& ec)\n\t{\n\t\tm_sock.io_control(ioc, ec);\n\t}\n\n\ttemplate <class Const_Buffers, class Handler>\n\tvoid async_write_some(Const_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tm_sock.async_write_some(buffers, handler);\n\t}\n\n\tvoid bind(endpoint_type const& endpoint)\n\t{\n\t\tm_sock.bind(endpoint);\n\t}\n\n\tvoid bind(endpoint_type const& endpoint, asio::error_code& ec)\n\t{\n\t\tm_sock.bind(endpoint, ec);\n\t}\n\n\tvoid open(protocol_type const& p)\n\t{\n\t\tm_sock.open(p);\n\t}\n\n\tvoid open(protocol_type const& p, asio::error_code& ec)\n\t{\n\t\tm_sock.open(p, ec);\n\t}\n\n\tvoid close()\n\t{\n\t\tm_remote_endpoint = endpoint_type();\n\t\tm_sock.close();\n\t}\n\n\tvoid close(asio::error_code& ec)\n\t{\n\t\tm_sock.close(ec);\n\t\tm_resolver.cancel();\n\t}\n\n\tendpoint_type remote_endpoint()\n\t{\n\t\treturn m_remote_endpoint;\n\t}\n\n\tendpoint_type remote_endpoint(asio::error_code& ec)\n\t{\n\t\treturn m_remote_endpoint;\n\t}\n\n\tendpoint_type local_endpoint()\n\t{\n\t\treturn m_sock.local_endpoint();\n\t}\n\n\tendpoint_type local_endpoint(asio::error_code& ec)\n\t{\n\t\treturn m_sock.local_endpoint(ec);\n\t}\n\n\tasio::io_service& io_service()\n\t{\n\t\treturn m_sock.io_service();\n\t}\n\n\tlowest_layer_type& lowest_layer()\n\t{\n\t\treturn m_sock.lowest_layer();\n\t}\n\t\nprotected:\n\n\tstream_socket m_sock;\n\tstd::string m_hostname;\n\tint m_port;\n\n\tendpoint_type m_remote_endpoint;\n\n\ttcp::resolver m_resolver;\n};\n\n}\n\n#endif\n\n<commit_msg>proxy_base shutdown fix<commit_after>\/*\n\nCopyright (c) 2007, 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#ifndef TORRENT_PROXY_BASE_HPP_INCLUDED\n#define TORRENT_PROXY_BASE_HPP_INCLUDED\n\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include <boost\/bind.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/function.hpp>\n#include <asio\/read.hpp>\n#include <asio\/write.hpp>\n\n\nnamespace libtorrent {\n\nclass proxy_base : boost::noncopyable\n{\npublic:\n\n\ttypedef stream_socket::lowest_layer_type lowest_layer_type;\n\ttypedef stream_socket::endpoint_type endpoint_type;\n\ttypedef stream_socket::protocol_type protocol_type;\n\n\texplicit proxy_base(asio::io_service& io_service)\n\t\t: m_sock(io_service)\n\t\t, m_resolver(io_service)\n\t{}\n\n\tvoid set_proxy(std::string hostname, int port)\n\t{\n\t\tm_hostname = hostname;\n\t\tm_port = port;\n\t}\n\n\ttemplate <class Mutable_Buffers, class Handler>\n\tvoid async_read_some(Mutable_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tm_sock.async_read_some(buffers, handler);\n\t}\n\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers, asio::error_code& ec)\n\t{\n\t\treturn m_sock.read_some(buffers, ec);\n\t}\n\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers)\n\t{\n\t\treturn m_sock.read_some(buffers);\n\t}\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc)\n\t{\n\t\tm_sock.io_control(ioc);\n\t}\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc, asio::error_code& ec)\n\t{\n\t\tm_sock.io_control(ioc, ec);\n\t}\n\n\ttemplate <class Const_Buffers, class Handler>\n\tvoid async_write_some(Const_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tm_sock.async_write_some(buffers, handler);\n\t}\n\n\tvoid bind(endpoint_type const& endpoint)\n\t{\n\t\tm_sock.bind(endpoint);\n\t}\n\n\tvoid bind(endpoint_type const& endpoint, asio::error_code& ec)\n\t{\n\t\tm_sock.bind(endpoint, ec);\n\t}\n\n\tvoid open(protocol_type const& p)\n\t{\n\t\tm_sock.open(p);\n\t}\n\n\tvoid open(protocol_type const& p, asio::error_code& ec)\n\t{\n\t\tm_sock.open(p, ec);\n\t}\n\n\tvoid close()\n\t{\n\t\tm_remote_endpoint = endpoint_type();\n\t\tm_sock.close();\n\t\tm_resolver.cancel();\n\t}\n\n\tvoid close(asio::error_code& ec)\n\t{\n\t\tm_sock.close(ec);\n\t\tm_resolver.cancel();\n\t}\n\n\tendpoint_type remote_endpoint()\n\t{\n\t\treturn m_remote_endpoint;\n\t}\n\n\tendpoint_type remote_endpoint(asio::error_code& ec)\n\t{\n\t\treturn m_remote_endpoint;\n\t}\n\n\tendpoint_type local_endpoint()\n\t{\n\t\treturn m_sock.local_endpoint();\n\t}\n\n\tendpoint_type local_endpoint(asio::error_code& ec)\n\t{\n\t\treturn m_sock.local_endpoint(ec);\n\t}\n\n\tasio::io_service& io_service()\n\t{\n\t\treturn m_sock.io_service();\n\t}\n\n\tlowest_layer_type& lowest_layer()\n\t{\n\t\treturn m_sock.lowest_layer();\n\t}\n\t\nprotected:\n\n\tstream_socket m_sock;\n\tstd::string m_hostname;\n\tint m_port;\n\n\tendpoint_type m_remote_endpoint;\n\n\ttcp::resolver m_resolver;\n};\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_MARKER_HELPERS_HPP\n#define MAPNIK_MARKER_HELPERS_HPP\n\n#include <mapnik\/feature.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/geometry_type.hpp>\n#include <mapnik\/geometry_centroid.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/svg\/svg_path_attributes.hpp>\n#include <mapnik\/marker.hpp> \/\/ for svg_storage_type\n#include <mapnik\/markers_placement.hpp>\n#include <mapnik\/attribute.hpp>\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/vertex_processor.hpp>\n#include <mapnik\/renderer_common\/apply_vertex_converter.hpp>\n#include <mapnik\/renderer_common\/render_markers_symbolizer.hpp>\n\n\/\/ agg\n#include \"agg_trans_affine.h\"\n\n\/\/ stl\n#include <memory>\n\nnamespace mapnik {\n\nstruct clip_poly_tag;\n\nusing svg_attribute_type = agg::pod_bvector<svg::path_attributes>;\n\ntemplate <typename Detector>\nstruct vector_markers_dispatch : util::noncopyable\n{\n vector_markers_dispatch(svg_path_ptr const& src,\n svg_path_adapter & path,\n svg_attribute_type const& attrs,\n agg::trans_affine const& marker_trans,\n symbolizer_base const& sym,\n Detector & detector,\n double scale_factor,\n feature_impl const& feature,\n attributes const& vars,\n bool snap_to_pixels,\n markers_renderer_context & renderer_context)\n : params_(src->bounding_box(), recenter(src) * marker_trans,\n sym, feature, vars, scale_factor, snap_to_pixels)\n , renderer_context_(renderer_context)\n , src_(src)\n , path_(path)\n , attrs_(attrs)\n , detector_(detector)\n {}\n\n template <typename T>\n void add_path(T & path)\n {\n markers_placement_finder<T, Detector> placement_finder(\n params_.placement_method, path, detector_, params_.placement_params);\n double x, y, angle = .0;\n while (placement_finder.get_point(x, y, angle, params_.ignore_placement))\n {\n agg::trans_affine matrix = params_.placement_params.tr;\n matrix.rotate(angle);\n matrix.translate(x, y);\n renderer_context_.render_marker(src_, path_, attrs_, params_, matrix);\n }\n }\n\nprotected:\n static agg::trans_affine recenter(svg_path_ptr const& src)\n {\n coord2d center = src->bounding_box().center();\n return agg::trans_affine_translation(-center.x, -center.y);\n }\n\n markers_dispatch_params params_;\n markers_renderer_context & renderer_context_;\n svg_path_ptr const& src_;\n svg_path_adapter & path_;\n svg_attribute_type const& attrs_;\n Detector & detector_;\n};\n\ntemplate <typename Detector>\nstruct raster_markers_dispatch : util::noncopyable\n{\n raster_markers_dispatch(image_rgba8 const& src,\n agg::trans_affine const& marker_trans,\n symbolizer_base const& sym,\n Detector & detector,\n double scale_factor,\n feature_impl const& feature,\n attributes const& vars,\n markers_renderer_context & renderer_context)\n : params_(box2d<double>(0, 0, src.width(), src.height()),\n marker_trans, sym, feature, vars, scale_factor)\n , renderer_context_(renderer_context)\n , src_(src)\n , detector_(detector)\n {}\n\n template <typename T>\n void add_path(T & path)\n {\n markers_placement_finder<T, Detector> placement_finder(\n params_.placement_method, path, detector_, params_.placement_params);\n double x, y, angle = .0;\n while (placement_finder.get_point(x, y, angle, params_.ignore_placement))\n {\n agg::trans_affine matrix = params_.placement_params.tr;\n matrix.rotate(angle);\n matrix.translate(x, y);\n renderer_context_.render_marker(src_, params_, matrix);\n }\n }\n\nprotected:\n markers_dispatch_params params_;\n markers_renderer_context & renderer_context_;\n image_rgba8 const& src_;\n Detector & detector_;\n};\n\nvoid build_ellipse(symbolizer_base const& sym, mapnik::feature_impl & feature, attributes const& vars,\n svg_storage_type & marker_ellipse, svg::svg_path_adapter & svg_path);\n\nbool push_explicit_style(svg_attribute_type const& src,\n svg_attribute_type & dst,\n symbolizer_base const& sym,\n feature_impl & feature,\n attributes const& vars);\n\nvoid setup_transform_scaling(agg::trans_affine & tr,\n double svg_width,\n double svg_height,\n mapnik::feature_impl & feature,\n attributes const& vars,\n symbolizer_base const& sym);\n\n\/\/ Apply markers to a feature with multiple geometries\n\ntemplate <typename Converter, typename Processor>\nvoid apply_markers_single(Converter & converter, Processor & proc, geometry::geometry<double> const& geom)\n{\n geometry::geometry_types type = geometry::geometry_type(geom);\n\n if (type == geometry::geometry_types::Point)\n {\n geometry::point_vertex_adapter<double> va(geom.get<geometry::point<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::LineString)\n {\n geometry::line_string_vertex_adapter<double> va(geom.get<geometry::line_string<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::Polygon)\n {\n geometry::polygon_vertex_adapter<double> va(geom.get<geometry::polygon<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::MultiPoint)\n {\n for (auto const& pt : geom.get<geometry::multi_point<double>>())\n {\n geometry::point_vertex_adapter<double> va(pt);\n converter.apply(va, proc);\n }\n }\n else if (type == geometry::geometry_types::MultiLineString)\n {\n for (auto const& line : geom.get<geometry::multi_line_string<double>>())\n {\n geometry::line_string_vertex_adapter<double> va(line);\n converter.apply(va, proc);\n }\n }\n else if (type == geometry::geometry_types::MultiPolygon)\n {\n for (auto const& poly : geom.get<geometry::multi_polygon<double>>())\n {\n geometry::polygon_vertex_adapter<double> va(poly);\n converter.apply(va, proc);\n }\n }\n}\n\ntemplate <typename Converter, typename Processor>\nvoid apply_markers_multi(feature_impl const& feature, attributes const& vars, Converter & converter, Processor & proc, symbolizer_base const& sym)\n{\n using apply_vertex_converter_type = detail::apply_vertex_converter<Converter,Processor>;\n apply_vertex_converter_type apply(converter, proc);\n auto const& geom = feature.get_geometry();\n geometry::geometry_types type = geometry::geometry_type(geom);\n\n if (type == geometry::geometry_types::Point\n ||\n type == geometry::geometry_types::LineString\n ||\n type == geometry::geometry_types::Polygon)\n {\n apply_markers_single(converter, proc, geom);\n }\n else\n {\n\n marker_multi_policy_enum multi_policy = get<marker_multi_policy_enum, keys::markers_multipolicy>(sym, feature, vars);\n marker_placement_enum placement = get<marker_placement_enum, keys::markers_placement_type>(sym, feature, vars);\n\n if (placement == MARKER_POINT_PLACEMENT &&\n multi_policy == MARKER_WHOLE_MULTI)\n {\n geometry::point<double> pt;\n \/\/ test if centroid is contained by bounding box\n if (geometry::centroid(geom, pt) && converter.disp_.args_.bbox.contains(pt.x, pt.y))\n {\n \/\/ unset any clipping since we're now dealing with a point\n converter.template unset<clip_poly_tag>();\n geometry::point_vertex_adapter<double> va(pt);\n converter.apply(va, proc);\n }\n }\n else if ((placement == MARKER_POINT_PLACEMENT || placement == MARKER_INTERIOR_PLACEMENT) &&\n multi_policy == MARKER_LARGEST_MULTI)\n {\n \/\/ Only apply to path with largest envelope area\n \/\/ TODO: consider using true area for polygon types\n if (type == geometry::geometry_types::MultiPolygon)\n {\n geometry::multi_polygon<double> const& multi_poly = mapnik::util::get<geometry::multi_polygon<double> >(geom);\n double maxarea = 0;\n geometry::polygon<double> const* largest = 0;\n for (geometry::polygon<double> const& poly : multi_poly)\n {\n box2d<double> bbox = geometry::envelope(poly);\n double area = bbox.width() * bbox.height();\n if (area > maxarea)\n {\n maxarea = area;\n largest = &poly;\n }\n }\n if (largest)\n {\n geometry::polygon_vertex_adapter<double> va(*largest);\n converter.apply(va, proc);\n }\n }\n else\n {\n MAPNIK_LOG_WARN(marker_symbolizer) << \"TODO: if you get here -> open an issue\";\n }\n }\n else\n {\n if (multi_policy != MARKER_EACH_MULTI && placement != MARKER_POINT_PLACEMENT)\n {\n MAPNIK_LOG_WARN(marker_symbolizer) << \"marker_multi_policy != 'each' has no effect with marker_placement != 'point'\";\n }\n if (type == geometry::geometry_types::GeometryCollection)\n {\n for (auto const& g : geom.get<geometry::geometry_collection<double>>())\n {\n apply_markers_single(converter, proc, g);\n }\n }\n else\n {\n apply_markers_single(converter, proc, geom);\n }\n }\n }\n}\n\n}\n\n#endif \/\/MAPNIK_MARKER_HELPERS_HPP\n<commit_msg>reuse `type`<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_MARKER_HELPERS_HPP\n#define MAPNIK_MARKER_HELPERS_HPP\n\n#include <mapnik\/feature.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/geometry_type.hpp>\n#include <mapnik\/geometry_centroid.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/svg\/svg_path_attributes.hpp>\n#include <mapnik\/marker.hpp> \/\/ for svg_storage_type\n#include <mapnik\/markers_placement.hpp>\n#include <mapnik\/attribute.hpp>\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/vertex_processor.hpp>\n#include <mapnik\/renderer_common\/apply_vertex_converter.hpp>\n#include <mapnik\/renderer_common\/render_markers_symbolizer.hpp>\n\n\/\/ agg\n#include \"agg_trans_affine.h\"\n\n\/\/ stl\n#include <memory>\n\nnamespace mapnik {\n\nstruct clip_poly_tag;\n\nusing svg_attribute_type = agg::pod_bvector<svg::path_attributes>;\n\ntemplate <typename Detector>\nstruct vector_markers_dispatch : util::noncopyable\n{\n vector_markers_dispatch(svg_path_ptr const& src,\n svg_path_adapter & path,\n svg_attribute_type const& attrs,\n agg::trans_affine const& marker_trans,\n symbolizer_base const& sym,\n Detector & detector,\n double scale_factor,\n feature_impl const& feature,\n attributes const& vars,\n bool snap_to_pixels,\n markers_renderer_context & renderer_context)\n : params_(src->bounding_box(), recenter(src) * marker_trans,\n sym, feature, vars, scale_factor, snap_to_pixels)\n , renderer_context_(renderer_context)\n , src_(src)\n , path_(path)\n , attrs_(attrs)\n , detector_(detector)\n {}\n\n template <typename T>\n void add_path(T & path)\n {\n markers_placement_finder<T, Detector> placement_finder(\n params_.placement_method, path, detector_, params_.placement_params);\n double x, y, angle = .0;\n while (placement_finder.get_point(x, y, angle, params_.ignore_placement))\n {\n agg::trans_affine matrix = params_.placement_params.tr;\n matrix.rotate(angle);\n matrix.translate(x, y);\n renderer_context_.render_marker(src_, path_, attrs_, params_, matrix);\n }\n }\n\nprotected:\n static agg::trans_affine recenter(svg_path_ptr const& src)\n {\n coord2d center = src->bounding_box().center();\n return agg::trans_affine_translation(-center.x, -center.y);\n }\n\n markers_dispatch_params params_;\n markers_renderer_context & renderer_context_;\n svg_path_ptr const& src_;\n svg_path_adapter & path_;\n svg_attribute_type const& attrs_;\n Detector & detector_;\n};\n\ntemplate <typename Detector>\nstruct raster_markers_dispatch : util::noncopyable\n{\n raster_markers_dispatch(image_rgba8 const& src,\n agg::trans_affine const& marker_trans,\n symbolizer_base const& sym,\n Detector & detector,\n double scale_factor,\n feature_impl const& feature,\n attributes const& vars,\n markers_renderer_context & renderer_context)\n : params_(box2d<double>(0, 0, src.width(), src.height()),\n marker_trans, sym, feature, vars, scale_factor)\n , renderer_context_(renderer_context)\n , src_(src)\n , detector_(detector)\n {}\n\n template <typename T>\n void add_path(T & path)\n {\n markers_placement_finder<T, Detector> placement_finder(\n params_.placement_method, path, detector_, params_.placement_params);\n double x, y, angle = .0;\n while (placement_finder.get_point(x, y, angle, params_.ignore_placement))\n {\n agg::trans_affine matrix = params_.placement_params.tr;\n matrix.rotate(angle);\n matrix.translate(x, y);\n renderer_context_.render_marker(src_, params_, matrix);\n }\n }\n\nprotected:\n markers_dispatch_params params_;\n markers_renderer_context & renderer_context_;\n image_rgba8 const& src_;\n Detector & detector_;\n};\n\nvoid build_ellipse(symbolizer_base const& sym, mapnik::feature_impl & feature, attributes const& vars,\n svg_storage_type & marker_ellipse, svg::svg_path_adapter & svg_path);\n\nbool push_explicit_style(svg_attribute_type const& src,\n svg_attribute_type & dst,\n symbolizer_base const& sym,\n feature_impl & feature,\n attributes const& vars);\n\nvoid setup_transform_scaling(agg::trans_affine & tr,\n double svg_width,\n double svg_height,\n mapnik::feature_impl & feature,\n attributes const& vars,\n symbolizer_base const& sym);\n\n\/\/ Apply markers to a feature with multiple geometries\ntemplate <typename Converter, typename Processor>\nvoid apply_markers_single(Converter & converter, Processor & proc, geometry::geometry<double> const& geom, geometry::geometry_types type)\n{\n if (type == geometry::geometry_types::Point)\n {\n geometry::point_vertex_adapter<double> va(geom.get<geometry::point<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::LineString)\n {\n geometry::line_string_vertex_adapter<double> va(geom.get<geometry::line_string<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::Polygon)\n {\n geometry::polygon_vertex_adapter<double> va(geom.get<geometry::polygon<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::MultiPoint)\n {\n for (auto const& pt : geom.get<geometry::multi_point<double>>())\n {\n geometry::point_vertex_adapter<double> va(pt);\n converter.apply(va, proc);\n }\n }\n else if (type == geometry::geometry_types::MultiLineString)\n {\n for (auto const& line : geom.get<geometry::multi_line_string<double>>())\n {\n geometry::line_string_vertex_adapter<double> va(line);\n converter.apply(va, proc);\n }\n }\n else if (type == geometry::geometry_types::MultiPolygon)\n {\n for (auto const& poly : geom.get<geometry::multi_polygon<double>>())\n {\n geometry::polygon_vertex_adapter<double> va(poly);\n converter.apply(va, proc);\n }\n }\n}\n\ntemplate <typename Converter, typename Processor>\nvoid apply_markers_multi(feature_impl const& feature, attributes const& vars, Converter & converter, Processor & proc, symbolizer_base const& sym)\n{\n using apply_vertex_converter_type = detail::apply_vertex_converter<Converter,Processor>;\n apply_vertex_converter_type apply(converter, proc);\n auto const& geom = feature.get_geometry();\n geometry::geometry_types type = geometry::geometry_type(geom);\n\n if (type == geometry::geometry_types::Point\n ||\n type == geometry::geometry_types::LineString\n ||\n type == geometry::geometry_types::Polygon)\n {\n apply_markers_single(converter, proc, geom, type);\n }\n else\n {\n\n marker_multi_policy_enum multi_policy = get<marker_multi_policy_enum, keys::markers_multipolicy>(sym, feature, vars);\n marker_placement_enum placement = get<marker_placement_enum, keys::markers_placement_type>(sym, feature, vars);\n\n if (placement == MARKER_POINT_PLACEMENT &&\n multi_policy == MARKER_WHOLE_MULTI)\n {\n geometry::point<double> pt;\n \/\/ test if centroid is contained by bounding box\n if (geometry::centroid(geom, pt) && converter.disp_.args_.bbox.contains(pt.x, pt.y))\n {\n \/\/ unset any clipping since we're now dealing with a point\n converter.template unset<clip_poly_tag>();\n geometry::point_vertex_adapter<double> va(pt);\n converter.apply(va, proc);\n }\n }\n else if ((placement == MARKER_POINT_PLACEMENT || placement == MARKER_INTERIOR_PLACEMENT) &&\n multi_policy == MARKER_LARGEST_MULTI)\n {\n \/\/ Only apply to path with largest envelope area\n \/\/ TODO: consider using true area for polygon types\n if (type == geometry::geometry_types::MultiPolygon)\n {\n geometry::multi_polygon<double> const& multi_poly = mapnik::util::get<geometry::multi_polygon<double> >(geom);\n double maxarea = 0;\n geometry::polygon<double> const* largest = 0;\n for (geometry::polygon<double> const& poly : multi_poly)\n {\n box2d<double> bbox = geometry::envelope(poly);\n double area = bbox.width() * bbox.height();\n if (area > maxarea)\n {\n maxarea = area;\n largest = &poly;\n }\n }\n if (largest)\n {\n geometry::polygon_vertex_adapter<double> va(*largest);\n converter.apply(va, proc);\n }\n }\n else\n {\n MAPNIK_LOG_WARN(marker_symbolizer) << \"TODO: if you get here -> open an issue\";\n }\n }\n else\n {\n if (multi_policy != MARKER_EACH_MULTI && placement != MARKER_POINT_PLACEMENT)\n {\n MAPNIK_LOG_WARN(marker_symbolizer) << \"marker_multi_policy != 'each' has no effect with marker_placement != 'point'\";\n }\n if (type == geometry::geometry_types::GeometryCollection)\n {\n for (auto const& g : geom.get<geometry::geometry_collection<double>>())\n {\n apply_markers_single(converter, proc, g, geometry::geometry_type(g));\n }\n }\n else\n {\n apply_markers_single(converter, proc, geom, type);\n }\n }\n }\n}\n\n}\n\n#endif \/\/MAPNIK_MARKER_HELPERS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 https:\/\/github.com\/mandreyel\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this\n * software and associated documentation files (the \"Software\"), to deal in the Software\n * without restriction, including without limitation the rights to use, copy, modify,\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies\n * or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef MIO_BASIC_MMAP_IMPL\n#define MIO_BASIC_MMAP_IMPL\n\n#include \"basic_mmap.hpp\"\n#include \"string_util.hpp\"\n#include \"..\/page.hpp\"\n\n#include <algorithm>\n#include <cstdint>\n\n#ifndef _WIN32\n# include <unistd.h>\n# include <fcntl.h>\n# include <sys\/mman.h>\n# include <sys\/stat.h>\n#endif\n\nnamespace mio {\nnamespace detail {\n\n\/\/ Generic handle type for use by free functions.\nusing handle_type = basic_mmap<char>::handle_type;\n\n#if defined(_WIN32)\ninline DWORD int64_high(int64_t n) noexcept\n{\n return n >> 32;\n}\n\ninline DWORD int64_low(int64_t n) noexcept\n{\n return n & 0xff'ff'ff'ff;\n}\n#endif\n\ninline std::error_code last_error() noexcept\n{\n std::error_code error;\n#ifdef _WIN32\n error.assign(GetLastError(), std::system_category());\n#else\n error.assign(errno, std::system_category());\n#endif\n return error;\n}\n\ntemplate<typename Path>\nhandle_type open_file(const Path& path, const access_mode mode, std::error_code& error)\n{\n error.clear();\n if(detail::empty(path))\n {\n error = std::make_error_code(std::errc::invalid_argument);\n return INVALID_HANDLE_VALUE;\n }\n#if defined(_WIN32)\n const auto handle = ::CreateFile(c_str(path),\n mode == access_mode::read_only ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,\n FILE_SHARE_READ | FILE_SHARE_WRITE,\n 0,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n 0);\n#else\n const auto handle = ::open(c_str(path),\n mode == access_mode::read_only ? O_RDONLY : O_RDWR);\n#endif\n if(handle == INVALID_HANDLE_VALUE)\n {\n error = last_error();\n }\n return handle;\n}\n\nint64_t query_file_size(handle_type handle, std::error_code& error)\n{\n error.clear();\n#ifdef _WIN32\n LARGE_INTEGER file_size;\n if(::GetFileSizeEx(handle, &file_size) == 0)\n {\n error = last_error();\n return 0;\n }\n\treturn static_cast<int64_t>(file_size.QuadPart);\n#else\n struct stat sbuf;\n if(::fstat(handle, &sbuf) == -1)\n {\n error = last_error();\n return 0;\n }\n return sbuf.st_size;\n#endif\n}\n\n\/\/ -- basic_mmap --\n\ntemplate<typename CharT, typename CharTraits>\nbasic_mmap<CharT, CharTraits>::~basic_mmap()\n{\n unmap();\n}\n\ntemplate<typename CharT, typename CharTraits>\nbasic_mmap<CharT, CharTraits>::basic_mmap(basic_mmap<CharT, CharTraits>&& other)\n : data_(std::move(other.data_))\n , length_(std::move(other.length_))\n , mapped_length_(std::move(other.mapped_length_))\n , file_handle_(std::move(other.file_handle_))\n#ifdef _WIN32\n , file_mapping_handle_(std::move(other.file_mapping_handle_))\n#endif\n , is_handle_internal_(std::move(other.is_handle_internal_))\n{\n other.data_ = nullptr;\n other.length_ = other.mapped_length_ = 0;\n other.file_handle_ = INVALID_HANDLE_VALUE;\n#ifdef _WIN32\n other.file_mapping_handle_ = INVALID_HANDLE_VALUE;\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\nbasic_mmap<CharT, CharTraits>& basic_mmap<CharT, CharTraits>::operator=(basic_mmap<CharT, CharTraits>&& other)\n{\n if(this != &other)\n {\n \/\/ First the existing mapping needs to be removed.\n unmap();\n data_ = std::move(other.data_);\n length_ = std::move(other.length_);\n mapped_length_ = std::move(other.mapped_length_);\n file_handle_ = std::move(other.file_handle_);\n#ifdef _WIN32\n file_mapping_handle_ = std::move(other.file_mapping_handle_);\n#endif\n is_handle_internal_ = std::move(other.is_handle_internal_);\n\n \/\/ The moved from basic_mmap's fields need to be reset, because otherwise other's\n \/\/ destructor will unmap the same mapping that was just moved into this.\n other.data_ = nullptr;\n other.length_ = other.mapped_length_ = 0;\n other.file_handle_ = INVALID_HANDLE_VALUE;\n#ifdef _WIN32\n other.file_mapping_handle_ = INVALID_HANDLE_VALUE;\n#endif\n other.is_handle_internal_ = false;\n }\n return *this;\n}\n\ntemplate<typename CharT, typename CharTraits>\ntypename basic_mmap<CharT, CharTraits>::handle_type\nbasic_mmap<CharT, CharTraits>::mapping_handle() const noexcept\n{\n#ifdef _WIN32\n return file_mapping_handle_;\n#else\n return file_handle_;\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\ntemplate<typename String>\nvoid basic_mmap<CharT, CharTraits>::map(String& path, size_type offset,\n size_type length, access_mode mode, std::error_code& error)\n{\n error.clear();\n if(detail::empty(path))\n {\n error = std::make_error_code(std::errc::invalid_argument);\n return;\n }\n if(!is_open())\n {\n const auto handle = open_file(path, mode, error);\n if(error) { return; }\n map(handle, offset, length, mode, error);\n \/\/ MUST be after the call to map, as that sets this to true.\n is_handle_internal_ = true;\n }\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::map(handle_type handle, size_type offset,\n size_type length, access_mode mode, std::error_code& error)\n{\n error.clear();\n if(handle == INVALID_HANDLE_VALUE)\n {\n error = std::make_error_code(std::errc::bad_file_descriptor);\n return;\n }\n\n const auto file_size = query_file_size(handle, error);\n if(error) { return; }\n\n if(length <= use_full_file_size)\n {\n length = file_size;\n }\n else if(offset + length > file_size)\n {\n error = std::make_error_code(std::errc::invalid_argument);\n return;\n }\n\n file_handle_ = handle;\n is_handle_internal_ = false;\n map(offset, length, mode, error);\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::map(const size_type offset, const size_type length,\n const access_mode mode, std::error_code& error)\n{\n const size_type aligned_offset = make_offset_page_aligned(offset);\n const size_type length_to_map = offset - aligned_offset + length;\n#if defined(_WIN32)\n const size_type max_file_size = offset + length;\n file_mapping_handle_ = ::CreateFileMapping(\n file_handle_,\n 0,\n mode == access_mode::read_only ? PAGE_READONLY : PAGE_READWRITE,\n int64_high(max_file_size),\n int64_low(max_file_size),\n 0);\n if(file_mapping_handle_ == INVALID_HANDLE_VALUE)\n {\n error = last_error();\n return;\n }\n\n const pointer mapping_start = static_cast<pointer>(::MapViewOfFile(\n file_mapping_handle_,\n mode == access_mode::read_only ? FILE_MAP_READ : FILE_MAP_WRITE,\n int64_high(aligned_offset),\n int64_low(aligned_offset),\n length_to_map));\n if(mapping_start == nullptr)\n {\n error = last_error();\n return;\n }\n#else\n const pointer mapping_start = static_cast<pointer>(::mmap(\n 0, \/\/ Don't give hint as to where to map.\n length_to_map,\n mode == access_mode::read_only ? PROT_READ : PROT_WRITE,\n MAP_SHARED, \/\/ TODO do we want to share it?\n file_handle_,\n aligned_offset));\n if(mapping_start == MAP_FAILED)\n {\n error = last_error();\n return;\n }\n#endif\n data_ = mapping_start + offset - aligned_offset;\n length_ = length;\n mapped_length_ = length_to_map;\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::sync(std::error_code& error)\n{\n error.clear();\n if(!is_open())\n {\n error = std::make_error_code(std::errc::bad_file_descriptor);\n return;\n }\n\n if(data() != nullptr)\n {\n#ifdef _WIN32\n if(::FlushViewOfFile(get_mapping_start(), mapped_length_) == 0\n || ::FlushFileBuffers(file_handle_) == 0)\n#else\n if(::msync(get_mapping_start(), mapped_length_, MS_SYNC) != 0)\n#endif\n {\n error = last_error();\n return;\n }\n }\n#ifdef _WIN32\n if(::FlushFileBuffers(file_handle_) == 0)\n {\n error = last_error();\n }\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::unmap()\n{\n if(!is_open()) { return; }\n \/\/ TODO do we care about errors here?\n#ifdef _WIN32\n if(is_mapped())\n {\n ::UnmapViewOfFile(get_mapping_start());\n ::CloseHandle(file_mapping_handle_);\n file_mapping_handle_ = INVALID_HANDLE_VALUE;\n }\n#else\n if(data_) { ::munmap(const_cast<pointer>(get_mapping_start()), mapped_length_); }\n#endif\n\n \/\/ If file handle was obtained by our opening it (when map is called with a path,\n \/\/ rather than an existing file handle), we need to close it, otherwise it must not\n \/\/ be closed as it may still be used outside of this basic_mmap instance.\n if(is_handle_internal_)\n {\n#ifdef _WIN32\n ::CloseHandle(file_handle_);\n#else\n ::close(file_handle_);\n#endif\n }\n\n \/\/ Reset fields to their default values.\n data_ = nullptr;\n length_ = mapped_length_ = 0;\n file_handle_ = INVALID_HANDLE_VALUE;\n#ifdef _WIN32\n file_mapping_handle_ = INVALID_HANDLE_VALUE;\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\ntypename basic_mmap<CharT, CharTraits>::pointer\nbasic_mmap<CharT, CharTraits>::get_mapping_start() noexcept\n{\n if(!data_) { return nullptr; }\n const auto offset = mapped_length_ - length_;\n return data_ - offset;\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool basic_mmap<CharT, CharTraits>::is_open() const noexcept\n{\n return file_handle_ != INVALID_HANDLE_VALUE;\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool basic_mmap<CharT, CharTraits>::is_mapped() const noexcept\n{\n#ifdef _WIN32\n return file_mapping_handle_ != INVALID_HANDLE_VALUE;\n#else\n return is_open();\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::swap(basic_mmap<CharT, CharTraits>& other)\n{\n if(this != &other)\n {\n using std::swap;\n swap(data_, other.data_); \n swap(file_handle_, other.file_handle_); \n#ifdef _WIN32\n swap(file_mapping_handle_, other.file_mapping_handle_); \n#endif\n swap(length_, other.length_); \n swap(mapped_length_, other.mapped_length_); \n swap(is_handle_internal_, other.is_handle_internal_); \n }\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool operator==(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return a.size() == b.size()\n && CharTraits::compare(a.data(), b.data(), a.size()) == 0;\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool operator!=(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return !(a == b);\n}\n\n\/*\ntemplate<typename CharT, typename CharTraits>\nbool operator<(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return CharTraits::compare(a.data(), b.data(), a.size()) < 0;\n}\n\n\/\/ TODO optimize\ntemplate<typename CharT, typename CharTraits>\nbool operator<=(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return (a == b) || (a < b);\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool operator>(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return CharTraits::compare(a.data(), b.data(), a.size()) > 0;\n}\n\n\/\/ TODO optimize\ntemplate<typename CharT, typename CharTraits>\nbool operator>=(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return (a == b) || (a > b);\n}\n*\/\n\n} \/\/ namespace detail\n} \/\/ namespace mio\n\n#endif \/\/ MIO_BASIC_MMAP_IMPL\n<commit_msg>fixed mult.def. linking error<commit_after>\/* Copyright 2017 https:\/\/github.com\/mandreyel\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this\n * software and associated documentation files (the \"Software\"), to deal in the Software\n * without restriction, including without limitation the rights to use, copy, modify,\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies\n * or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef MIO_BASIC_MMAP_IMPL\n#define MIO_BASIC_MMAP_IMPL\n\n#include \"basic_mmap.hpp\"\n#include \"string_util.hpp\"\n#include \"..\/page.hpp\"\n\n#include <algorithm>\n#include <cstdint>\n\n#ifndef _WIN32\n# include <unistd.h>\n# include <fcntl.h>\n# include <sys\/mman.h>\n# include <sys\/stat.h>\n#endif\n\nnamespace mio {\nnamespace detail {\n\n\/\/ Generic handle type for use by free functions.\nusing handle_type = basic_mmap<char>::handle_type;\n\n#if defined(_WIN32)\ninline DWORD int64_high(int64_t n) noexcept\n{\n return n >> 32;\n}\n\ninline DWORD int64_low(int64_t n) noexcept\n{\n return n & 0xff'ff'ff'ff;\n}\n#endif\n\ninline std::error_code last_error() noexcept\n{\n std::error_code error;\n#ifdef _WIN32\n error.assign(GetLastError(), std::system_category());\n#else\n error.assign(errno, std::system_category());\n#endif\n return error;\n}\n\ntemplate<typename Path>\nhandle_type open_file(const Path& path, const access_mode mode, std::error_code& error)\n{\n error.clear();\n if(detail::empty(path))\n {\n error = std::make_error_code(std::errc::invalid_argument);\n return INVALID_HANDLE_VALUE;\n }\n#if defined(_WIN32)\n const auto handle = ::CreateFile(c_str(path),\n mode == access_mode::read_only ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,\n FILE_SHARE_READ | FILE_SHARE_WRITE,\n 0,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n 0);\n#else\n const auto handle = ::open(c_str(path),\n mode == access_mode::read_only ? O_RDONLY : O_RDWR);\n#endif\n if(handle == INVALID_HANDLE_VALUE)\n {\n error = last_error();\n }\n return handle;\n}\n\ninline int64_t query_file_size(handle_type handle, std::error_code& error)\n{\n error.clear();\n#ifdef _WIN32\n LARGE_INTEGER file_size;\n if(::GetFileSizeEx(handle, &file_size) == 0)\n {\n error = last_error();\n return 0;\n }\n\treturn static_cast<int64_t>(file_size.QuadPart);\n#else\n struct stat sbuf;\n if(::fstat(handle, &sbuf) == -1)\n {\n error = last_error();\n return 0;\n }\n return sbuf.st_size;\n#endif\n}\n\n\/\/ -- basic_mmap --\n\ntemplate<typename CharT, typename CharTraits>\nbasic_mmap<CharT, CharTraits>::~basic_mmap()\n{\n unmap();\n}\n\ntemplate<typename CharT, typename CharTraits>\nbasic_mmap<CharT, CharTraits>::basic_mmap(basic_mmap<CharT, CharTraits>&& other)\n : data_(std::move(other.data_))\n , length_(std::move(other.length_))\n , mapped_length_(std::move(other.mapped_length_))\n , file_handle_(std::move(other.file_handle_))\n#ifdef _WIN32\n , file_mapping_handle_(std::move(other.file_mapping_handle_))\n#endif\n , is_handle_internal_(std::move(other.is_handle_internal_))\n{\n other.data_ = nullptr;\n other.length_ = other.mapped_length_ = 0;\n other.file_handle_ = INVALID_HANDLE_VALUE;\n#ifdef _WIN32\n other.file_mapping_handle_ = INVALID_HANDLE_VALUE;\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\nbasic_mmap<CharT, CharTraits>& basic_mmap<CharT, CharTraits>::operator=(basic_mmap<CharT, CharTraits>&& other)\n{\n if(this != &other)\n {\n \/\/ First the existing mapping needs to be removed.\n unmap();\n data_ = std::move(other.data_);\n length_ = std::move(other.length_);\n mapped_length_ = std::move(other.mapped_length_);\n file_handle_ = std::move(other.file_handle_);\n#ifdef _WIN32\n file_mapping_handle_ = std::move(other.file_mapping_handle_);\n#endif\n is_handle_internal_ = std::move(other.is_handle_internal_);\n\n \/\/ The moved from basic_mmap's fields need to be reset, because otherwise other's\n \/\/ destructor will unmap the same mapping that was just moved into this.\n other.data_ = nullptr;\n other.length_ = other.mapped_length_ = 0;\n other.file_handle_ = INVALID_HANDLE_VALUE;\n#ifdef _WIN32\n other.file_mapping_handle_ = INVALID_HANDLE_VALUE;\n#endif\n other.is_handle_internal_ = false;\n }\n return *this;\n}\n\ntemplate<typename CharT, typename CharTraits>\ntypename basic_mmap<CharT, CharTraits>::handle_type\nbasic_mmap<CharT, CharTraits>::mapping_handle() const noexcept\n{\n#ifdef _WIN32\n return file_mapping_handle_;\n#else\n return file_handle_;\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\ntemplate<typename String>\nvoid basic_mmap<CharT, CharTraits>::map(String& path, size_type offset,\n size_type length, access_mode mode, std::error_code& error)\n{\n error.clear();\n if(detail::empty(path))\n {\n error = std::make_error_code(std::errc::invalid_argument);\n return;\n }\n if(!is_open())\n {\n const auto handle = open_file(path, mode, error);\n if(error) { return; }\n map(handle, offset, length, mode, error);\n \/\/ MUST be after the call to map, as that sets this to true.\n is_handle_internal_ = true;\n }\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::map(handle_type handle, size_type offset,\n size_type length, access_mode mode, std::error_code& error)\n{\n error.clear();\n if(handle == INVALID_HANDLE_VALUE)\n {\n error = std::make_error_code(std::errc::bad_file_descriptor);\n return;\n }\n\n const auto file_size = query_file_size(handle, error);\n if(error) { return; }\n\n if(length <= use_full_file_size)\n {\n length = file_size;\n }\n else if(offset + length > file_size)\n {\n error = std::make_error_code(std::errc::invalid_argument);\n return;\n }\n\n file_handle_ = handle;\n is_handle_internal_ = false;\n map(offset, length, mode, error);\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::map(const size_type offset, const size_type length,\n const access_mode mode, std::error_code& error)\n{\n const size_type aligned_offset = make_offset_page_aligned(offset);\n const size_type length_to_map = offset - aligned_offset + length;\n#if defined(_WIN32)\n const size_type max_file_size = offset + length;\n file_mapping_handle_ = ::CreateFileMapping(\n file_handle_,\n 0,\n mode == access_mode::read_only ? PAGE_READONLY : PAGE_READWRITE,\n int64_high(max_file_size),\n int64_low(max_file_size),\n 0);\n if(file_mapping_handle_ == INVALID_HANDLE_VALUE)\n {\n error = last_error();\n return;\n }\n\n const pointer mapping_start = static_cast<pointer>(::MapViewOfFile(\n file_mapping_handle_,\n mode == access_mode::read_only ? FILE_MAP_READ : FILE_MAP_WRITE,\n int64_high(aligned_offset),\n int64_low(aligned_offset),\n length_to_map));\n if(mapping_start == nullptr)\n {\n error = last_error();\n return;\n }\n#else\n const pointer mapping_start = static_cast<pointer>(::mmap(\n 0, \/\/ Don't give hint as to where to map.\n length_to_map,\n mode == access_mode::read_only ? PROT_READ : PROT_WRITE,\n MAP_SHARED, \/\/ TODO do we want to share it?\n file_handle_,\n aligned_offset));\n if(mapping_start == MAP_FAILED)\n {\n error = last_error();\n return;\n }\n#endif\n data_ = mapping_start + offset - aligned_offset;\n length_ = length;\n mapped_length_ = length_to_map;\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::sync(std::error_code& error)\n{\n error.clear();\n if(!is_open())\n {\n error = std::make_error_code(std::errc::bad_file_descriptor);\n return;\n }\n\n if(data() != nullptr)\n {\n#ifdef _WIN32\n if(::FlushViewOfFile(get_mapping_start(), mapped_length_) == 0\n || ::FlushFileBuffers(file_handle_) == 0)\n#else\n if(::msync(get_mapping_start(), mapped_length_, MS_SYNC) != 0)\n#endif\n {\n error = last_error();\n return;\n }\n }\n#ifdef _WIN32\n if(::FlushFileBuffers(file_handle_) == 0)\n {\n error = last_error();\n }\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::unmap()\n{\n if(!is_open()) { return; }\n \/\/ TODO do we care about errors here?\n#ifdef _WIN32\n if(is_mapped())\n {\n ::UnmapViewOfFile(get_mapping_start());\n ::CloseHandle(file_mapping_handle_);\n file_mapping_handle_ = INVALID_HANDLE_VALUE;\n }\n#else\n if(data_) { ::munmap(const_cast<pointer>(get_mapping_start()), mapped_length_); }\n#endif\n\n \/\/ If file handle was obtained by our opening it (when map is called with a path,\n \/\/ rather than an existing file handle), we need to close it, otherwise it must not\n \/\/ be closed as it may still be used outside of this basic_mmap instance.\n if(is_handle_internal_)\n {\n#ifdef _WIN32\n ::CloseHandle(file_handle_);\n#else\n ::close(file_handle_);\n#endif\n }\n\n \/\/ Reset fields to their default values.\n data_ = nullptr;\n length_ = mapped_length_ = 0;\n file_handle_ = INVALID_HANDLE_VALUE;\n#ifdef _WIN32\n file_mapping_handle_ = INVALID_HANDLE_VALUE;\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\ntypename basic_mmap<CharT, CharTraits>::pointer\nbasic_mmap<CharT, CharTraits>::get_mapping_start() noexcept\n{\n if(!data_) { return nullptr; }\n const auto offset = mapped_length_ - length_;\n return data_ - offset;\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool basic_mmap<CharT, CharTraits>::is_open() const noexcept\n{\n return file_handle_ != INVALID_HANDLE_VALUE;\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool basic_mmap<CharT, CharTraits>::is_mapped() const noexcept\n{\n#ifdef _WIN32\n return file_mapping_handle_ != INVALID_HANDLE_VALUE;\n#else\n return is_open();\n#endif\n}\n\ntemplate<typename CharT, typename CharTraits>\nvoid basic_mmap<CharT, CharTraits>::swap(basic_mmap<CharT, CharTraits>& other)\n{\n if(this != &other)\n {\n using std::swap;\n swap(data_, other.data_); \n swap(file_handle_, other.file_handle_); \n#ifdef _WIN32\n swap(file_mapping_handle_, other.file_mapping_handle_); \n#endif\n swap(length_, other.length_); \n swap(mapped_length_, other.mapped_length_); \n swap(is_handle_internal_, other.is_handle_internal_); \n }\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool operator==(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return a.size() == b.size()\n && CharTraits::compare(a.data(), b.data(), a.size()) == 0;\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool operator!=(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return !(a == b);\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool operator<(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return CharTraits::compare(a.data(), b.data(), a.size()) < 0;\n}\n\n\/\/ TODO optimize\ntemplate<typename CharT, typename CharTraits>\nbool operator<=(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return (a == b) || (a < b);\n}\n\ntemplate<typename CharT, typename CharTraits>\nbool operator>(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return CharTraits::compare(a.data(), b.data(), a.size()) > 0;\n}\n\n\/\/ TODO optimize\ntemplate<typename CharT, typename CharTraits>\nbool operator>=(const basic_mmap<CharT, CharTraits>& a,\n const basic_mmap<CharT, CharTraits>& b)\n{\n return (a == b) || (a > b);\n}\n\n} \/\/ namespace detail\n} \/\/ namespace mio\n\n#endif \/\/ MIO_BASIC_MMAP_IMPL\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#ifndef NIFTY_HDF5_HDF5_ARRAY\n#define NIFTY_HDF5_HDF5_ARRAY\n\n#include <string>\n#include <vector>\n\n#include \"nifty\/tools\/block_access.hxx\"\n#include \"nifty\/tools\/runtime_check.hxx\"\n#include \"nifty\/marray\/marray_hdf5.hxx\"\n\nnamespace nifty{\nnamespace hdf5{\n \n using namespace marray::hdf5;\n\n\n\n template<class T>\n class Hdf5Array{\n public:\n template<class SHAPE_ITER, class CHUNK_SHAPE_ITER>\n Hdf5Array(\n const hid_t& groupHandle,\n const std::string & datasetName,\n SHAPE_ITER shapeBegin,\n SHAPE_ITER shapeEnd,\n CHUNK_SHAPE_ITER chunkShapeBegin\n )\n : groupHandle_(groupHandle),\n dataset_(),\n datatype_(),\n isChunked_(true)\n {\n datatype_ = H5Tcopy(hdf5Type<T>());\n const auto dim = std::distance(shapeBegin, shapeEnd);\n\n shape_.resize(dim);\n chunkShape_.resize(dim);\n\n std::vector<hsize_t> shape(dim);\n std::vector<hsize_t> chunkShape(dim);\n\n for(auto d=0; d<dim; ++d){\n const auto s = *shapeBegin;\n const auto cs = *chunkShapeBegin;\n shape[d] = s;\n shape_[d] = s;\n chunkShape[d] = cs;\n chunkShape_[d] = cs;\n ++shapeBegin;\n ++chunkShapeBegin;\n }\n\n \/\/ chunk properties\n hid_t dcplId = H5Pcreate(H5P_DATASET_CREATE);\n H5Pset_chunk(dcplId, hsize_t(dim), chunkShape.data());\n\n \/\/ dataset shape\n auto dataspace = H5Screate_simple(hsize_t(dim), shape.data(), NULL);\n\n \/\/ create the dataset\n dataset_ = H5Dcreate(groupHandle_, datasetName.c_str(), datatype_, dataspace, \n H5P_DEFAULT,dcplId, H5P_DEFAULT);\n\n \/\/ close the dataspace and the chunk properties\n H5Sclose(dataspace);\n H5Pclose(dcplId);\n }\n\n Hdf5Array(\n const hid_t& groupHandle,\n const std::string & datasetName\n )\n : groupHandle_(groupHandle),\n dataset_(),\n datatype_(),\n isChunked_(true)\n {\n\n\n\n dataset_ = H5Dopen(groupHandle_, datasetName.c_str(), H5P_DEFAULT);\n if(dataset_ < 0) {\n throw std::runtime_error(\"Marray cannot open dataset.\");\n }\n\n \/\/ select dataspace hyperslab\n datatype_ = H5Dget_type(dataset_);\n if(!H5Tequal(datatype_, hdf5Type<T>())) {\n throw std::runtime_error(\"data type of stored hdf5 dataset and passed array do not match in loadHyperslab\");\n }\n \n\n this->loadShape(shape_);\n this->loadChunkShape(chunkShape_);\n }\n\n int setCache(){\n \/\/herr_t H5Pset_cache(hid_t plist_id, int mdc_nelmts, size_t rdcc_nslots, size_t rdcc_nbytes, double rdcc_w0)\n }\n\n ~Hdf5Array(){\n H5Tclose(datatype_);\n H5Dclose(dataset_);\n }\n\n uint64_t dimension()const{\n return shape_.size();\n }\n uint64_t shape(const size_t d)const{\n return shape_[d];\n }\n const std::vector<uint64_t> & shape()const{\n return shape_;\n }\n uint64_t chunkShape(const size_t d)const{\n return chunkShape_[d];\n }\n const std::vector<uint64_t> & chunkShape()const{\n return chunkShape_;\n }\n\n bool isChunked()const{\n return isChunked_;\n }\n\n template<class ITER>\n void readSubarray(\n ITER roiBeginIter,\n marray::View<T> & out\n )const{\n NIFTY_CHECK_OP(out.dimension(),==,this->dimension(),\"out has wrong dimension\");\n NIFTY_CHECK(out.coordinateOrder() == marray::FirstMajorOrder, \n \"currently only views with last major order are supported\"\n );\n \/\/std::cout<<\"load hyperslab\\n\";\n this->loadHyperslab(roiBeginIter, roiBeginIter+out.dimension(), out.shapeBegin(), out);\n }\n\n template<class ITER>\n void writeSubarray(\n ITER roiBeginIter,\n const marray::View<T> & in\n ){\n NIFTY_CHECK_OP(in.dimension(),==,this->dimension(),\"in has wrong dimension\");\n NIFTY_CHECK(in.coordinateOrder() == marray::FirstMajorOrder, \n \"currently only views with last major order are supported\"\n );\n this->saveHyperslab(roiBeginIter, roiBeginIter+in.dimension(), in.shapeBegin(), in);\n }\n\n private:\n template<class BaseIterator, class ShapeIterator>\n void loadHyperslab(\n BaseIterator baseBegin,\n BaseIterator baseEnd,\n ShapeIterator shapeBegin,\n marray::View<T> & out\n ) const {\n HandleCheck<marray::MARRAY_NO_DEBUG> handleCheck;\n\n \/\/ determine shape of hyperslab and array\n std::size_t size = std::distance(baseBegin, baseEnd);\n std::vector<hsize_t> offset(size);\n std::vector<hsize_t> slabShape(size);\n std::vector<hsize_t> marrayShape(size);\n marray::CoordinateOrder coordinateOrder;\n if(H5Aexists(dataset_, reverseShapeAttributeName) > 0) {\n NIFTY_CHECK(false, \"currently we do not allow to load from datasets with reverseShapeAttribute\")\n } \n else {\n \/\/ don't reverse base and shape\n coordinateOrder = marray::FirstMajorOrder;\n for(std::size_t j=0; j<size; ++j) {\n offset[j] = hsize_t(*baseBegin);\n slabShape[j] = hsize_t(*shapeBegin);\n marrayShape[j] = slabShape[j];\n\n ++baseBegin;\n ++shapeBegin;\n }\n }\n \n hid_t dataspace = H5Dget_space(dataset_);\n herr_t status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, \n &offset[0], NULL, &slabShape[0], NULL);\n if(status < 0) {\n H5Sclose(dataspace);\n throw std::runtime_error(\"Marray cannot select hyperslab. Check offset and shape !\");\n }\n\n \/\/ select memspace hyperslab\n hid_t memspace = H5Screate_simple(int(size), &marrayShape[0], NULL);\n std::vector<hsize_t> offsetOut(size, 0); \/\/ no offset\n status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, &offsetOut[0],\n NULL, &marrayShape[0], NULL);\n if(status < 0) {\n H5Sclose(memspace); \n H5Sclose(dataspace);\n throw std::runtime_error(\"Marray cannot select hyperslab. Check offset and shape s!\");\n }\n\n \/\/ read from dataspace into memspace\n \/\/out = Marray<T>(SkipInitialization, &marrayShape[0], \n \/\/ (&marrayShape[0])+size, coordinateOrder);\n \n if(out.isSimple()){\n \/\/std::cout<<\"is simple\\n\";\n status = H5Dread(dataset_, datatype_, memspace, dataspace,\n H5P_DEFAULT, &(out(0)));\n\n \/\/std::cout<<\"read status \"<<status<<\"\\n\";\n }\n else{\n \/\/std::cout<<\"is not simple\\n\";\n marray::Marray<T> tmpOut(marray::SkipInitialization, &marrayShape[0], \n (&marrayShape[0])+size, coordinateOrder);\n\n status = H5Dread(dataset_, datatype_, memspace, dataspace,\n H5P_DEFAULT, &(tmpOut(0)));\n\n \/\/std::cout<<\"read status \"<<status<<\"\\n\";\n\n out = tmpOut;\n }\n\n \/\/ clean up\n H5Sclose(memspace); \n H5Sclose(dataspace);\n if(status < 0) {\n throw std::runtime_error(\"Marray cannot read from dataset.\");\n }\n handleCheck.check();\n }\n\n template<class BaseIterator, class ShapeIterator>\n void \n saveHyperslab(\n BaseIterator baseBegin,\n BaseIterator baseEnd,\n ShapeIterator shapeBegin,\n const marray::View<T> & in\n ) {\n HandleCheck<marray::MARRAY_NO_DEBUG> handleCheck;\n\n \/\/ determine hyperslab shape\n std::vector<hsize_t> memoryShape(in.dimension());\n for(std::size_t j=0; j<in.dimension(); ++j) {\n memoryShape[j] = in.shape(j);\n }\n std::size_t size = std::distance(baseBegin, baseEnd);\n std::vector<hsize_t> offset(size);\n std::vector<hsize_t> slabShape(size);\n bool reverseShapeAttribute = (H5Aexists(dataset_, reverseShapeAttributeName) > 0);\n if(reverseShapeAttribute || in.coordinateOrder() == marray::LastMajorOrder) {\n NIFTY_CHECK(false, \"neither reverseShapeAttribute nor LastMajorOrder are currently supported\");\n }\n else{\n for(std::size_t j=0; j<size; ++j) {\n offset[j] = hsize_t(*baseBegin);\n slabShape[j] = hsize_t(*shapeBegin);\n ++baseBegin;\n ++shapeBegin;\n }\n }\n\n \/\/ select dataspace hyperslab\n hid_t dataspace = H5Dget_space(dataset_);\n herr_t status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, \n &offset[0], NULL, &slabShape[0], NULL);\n if(status < 0) {\n H5Sclose(dataspace);\n H5Dclose(dataset_);\n throw std::runtime_error(\"Marray cannot select hyperslab. Check offset and shape!\");\n }\n\n \/\/ select memspace hyperslab\n hid_t memspace = H5Screate_simple(int(in.dimension()), &memoryShape[0], NULL);\n std::vector<hsize_t> memoryOffset(int(in.dimension()), 0); \/\/ no offset\n status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, &memoryOffset[0], NULL,\n &memoryShape[0], NULL);\n if(status < 0) {\n H5Sclose(memspace); ;\n H5Sclose(dataspace);\n H5Dclose(dataset_);\n throw std::runtime_error(\"Marray cannot select hyperslab. Check offset and shape!\");\n }\n\n if(in.isSimple()){\n status = H5Dwrite(dataset_, datatype_, memspace, dataspace, H5P_DEFAULT, &(in(0)));\n }\n else{\n marray::Marray<T> tmp(in);\n status = H5Dwrite(dataset_, datatype_, memspace, dataspace, H5P_DEFAULT, &(tmp(0)));\n }\n \/\/ clean up\n H5Sclose(memspace); \n H5Sclose(dataspace);\n if(status < 0) {\n throw std::runtime_error(\"Marray cannot write to dataset.\");\n }\n handleCheck.check();\n }\n\n void loadShape(std::vector<uint64_t> & shapeVec){\n\n marray::marray_detail::Assert(marray::MARRAY_NO_ARG_TEST || groupHandle_ >= 0);\n HandleCheck<marray::MARRAY_NO_DEBUG> handleCheck;\n\n hid_t filespace = H5Dget_space(dataset_);\n hsize_t dimension = H5Sget_simple_extent_ndims(filespace);\n hsize_t* shape = new hsize_t[(std::size_t)(dimension)];\n herr_t status = H5Sget_simple_extent_dims(filespace, shape, NULL);\n if(status < 0) {\n H5Sclose(filespace);\n delete[] shape;\n throw std::runtime_error(\"MarrayNifty cannot get extension of dataset.\");\n }\n \/\/ write shape to shape_\n shapeVec.resize(dimension);\n if(H5Aexists(dataset_, reverseShapeAttributeName) > 0) {\n NIFTY_CHECK(false, \"currently we do not allow to load from datasets with reverseShapeAttribute\")\n }\n else {\n for(std::size_t j=0; j<shapeVec.size(); ++j) {\n shapeVec[j] = uint64_t(shape[j]);\n }\n }\n \/\/ clean up\n delete[] shape;\n H5Sclose(filespace);\n handleCheck.check();\n }\n\n void loadChunkShape(std::vector<uint64_t> & chunkShape){\n const auto d = this->dimension();\n std::vector<hsize_t> chunkShapeTmp(d);\n auto plist = H5Dget_create_plist(dataset_);\n\n\n bool couldBeChunked = false;\n const auto layout = H5Pget_layout(plist);\n if(layout == H5D_CHUNKED){\n couldBeChunked = true;\n }\n if(couldBeChunked){\n herr_t status = H5Pget_chunk(plist, int(d), chunkShapeTmp.data()); \n if(status < 0) {\n isChunked_ = false;\n chunkShape_ = shape_;\n \/\/H5Pclose(plist);\n \/\/throw std::runtime_error(\"Nifty cannot get chunkShape of dataset\");\n }\n else{\n isChunked_ = true;\n chunkShape_.resize(d);\n std::copy(chunkShapeTmp.begin(), chunkShapeTmp.end(), chunkShape_.begin());\n }\n }\n else{\n isChunked_ = false;\n chunkShape_ = shape_;\n }\n H5Pclose(plist);\n }\n\n hid_t groupHandle_;\n hid_t dataset_;\n hid_t datatype_;\n std::vector<uint64_t> shape_;\n std::vector<uint64_t> chunkShape_;\n bool isChunked_;\n };\n\n\n namespace tools{\n\n}\n\n\n} \/\/ namespace nifty::hdf5\n\n\n\nnamespace tools{\n\n template<class T, class COORD>\n inline void readSubarray(\n const hdf5::Hdf5Array<T> array,\n const COORD & beginCoord,\n const COORD & endCoord,\n marray::View<T> & subarray\n ){\n array.readSubarray(beginCoord.begin(), subarray);\n }\n\n\n\n template<class ARRAY>\n struct BlockStorageSelector;\n\n template<class T>\n struct BlockStorageSelector<hdf5::Hdf5Array<T> >\n {\n typedef BlockStorage<T> type;\n };\n} \/\/ namespace nifty::tools\n\n\n} \/\/ namespace nifty\n\n#endif \/\/ NIFTY_HDF5_HDF5_ARRAY\n<commit_msg>Added missing call by reference in tools::readSubarray<commit_after>#pragma once\n#ifndef NIFTY_HDF5_HDF5_ARRAY\n#define NIFTY_HDF5_HDF5_ARRAY\n\n#include <string>\n#include <vector>\n\n#include \"nifty\/tools\/block_access.hxx\"\n#include \"nifty\/tools\/runtime_check.hxx\"\n#include \"nifty\/marray\/marray_hdf5.hxx\"\n\nnamespace nifty{\nnamespace hdf5{\n \n using namespace marray::hdf5;\n\n\n\n template<class T>\n class Hdf5Array{\n public:\n template<class SHAPE_ITER, class CHUNK_SHAPE_ITER>\n Hdf5Array(\n const hid_t& groupHandle,\n const std::string & datasetName,\n SHAPE_ITER shapeBegin,\n SHAPE_ITER shapeEnd,\n CHUNK_SHAPE_ITER chunkShapeBegin\n )\n : groupHandle_(groupHandle),\n dataset_(),\n datatype_(),\n isChunked_(true)\n {\n datatype_ = H5Tcopy(hdf5Type<T>());\n const auto dim = std::distance(shapeBegin, shapeEnd);\n\n shape_.resize(dim);\n chunkShape_.resize(dim);\n\n std::vector<hsize_t> shape(dim);\n std::vector<hsize_t> chunkShape(dim);\n\n for(auto d=0; d<dim; ++d){\n const auto s = *shapeBegin;\n const auto cs = *chunkShapeBegin;\n shape[d] = s;\n shape_[d] = s;\n chunkShape[d] = cs;\n chunkShape_[d] = cs;\n ++shapeBegin;\n ++chunkShapeBegin;\n }\n\n \/\/ chunk properties\n hid_t dcplId = H5Pcreate(H5P_DATASET_CREATE);\n H5Pset_chunk(dcplId, hsize_t(dim), chunkShape.data());\n\n \/\/ dataset shape\n auto dataspace = H5Screate_simple(hsize_t(dim), shape.data(), NULL);\n\n \/\/ create the dataset\n dataset_ = H5Dcreate(groupHandle_, datasetName.c_str(), datatype_, dataspace, \n H5P_DEFAULT,dcplId, H5P_DEFAULT);\n\n \/\/ close the dataspace and the chunk properties\n H5Sclose(dataspace);\n H5Pclose(dcplId);\n }\n\n Hdf5Array(\n const hid_t& groupHandle,\n const std::string & datasetName\n )\n : groupHandle_(groupHandle),\n dataset_(),\n datatype_(),\n isChunked_(true)\n {\n\n\n\n dataset_ = H5Dopen(groupHandle_, datasetName.c_str(), H5P_DEFAULT);\n if(dataset_ < 0) {\n throw std::runtime_error(\"Marray cannot open dataset.\");\n }\n\n \/\/ select dataspace hyperslab\n datatype_ = H5Dget_type(dataset_);\n if(!H5Tequal(datatype_, hdf5Type<T>())) {\n throw std::runtime_error(\"data type of stored hdf5 dataset and passed array do not match in loadHyperslab\");\n }\n \n\n this->loadShape(shape_);\n this->loadChunkShape(chunkShape_);\n }\n\n int setCache(){\n \/\/herr_t H5Pset_cache(hid_t plist_id, int mdc_nelmts, size_t rdcc_nslots, size_t rdcc_nbytes, double rdcc_w0)\n }\n\n ~Hdf5Array(){\n H5Tclose(datatype_);\n H5Dclose(dataset_);\n }\n\n uint64_t dimension()const{\n return shape_.size();\n }\n uint64_t shape(const size_t d)const{\n return shape_[d];\n }\n const std::vector<uint64_t> & shape()const{\n return shape_;\n }\n uint64_t chunkShape(const size_t d)const{\n return chunkShape_[d];\n }\n const std::vector<uint64_t> & chunkShape()const{\n return chunkShape_;\n }\n\n bool isChunked()const{\n return isChunked_;\n }\n\n template<class ITER>\n void readSubarray(\n ITER roiBeginIter,\n marray::View<T> & out\n )const{\n NIFTY_CHECK_OP(out.dimension(),==,this->dimension(),\"out has wrong dimension\");\n NIFTY_CHECK(out.coordinateOrder() == marray::FirstMajorOrder, \n \"currently only views with last major order are supported\"\n );\n \/\/std::cout<<\"load hyperslab\\n\";\n this->loadHyperslab(roiBeginIter, roiBeginIter+out.dimension(), out.shapeBegin(), out);\n }\n\n template<class ITER>\n void writeSubarray(\n ITER roiBeginIter,\n const marray::View<T> & in\n ){\n NIFTY_CHECK_OP(in.dimension(),==,this->dimension(),\"in has wrong dimension\");\n NIFTY_CHECK(in.coordinateOrder() == marray::FirstMajorOrder, \n \"currently only views with last major order are supported\"\n );\n this->saveHyperslab(roiBeginIter, roiBeginIter+in.dimension(), in.shapeBegin(), in);\n }\n\n private:\n template<class BaseIterator, class ShapeIterator>\n void loadHyperslab(\n BaseIterator baseBegin,\n BaseIterator baseEnd,\n ShapeIterator shapeBegin,\n marray::View<T> & out\n ) const {\n HandleCheck<marray::MARRAY_NO_DEBUG> handleCheck;\n\n \/\/ determine shape of hyperslab and array\n std::size_t size = std::distance(baseBegin, baseEnd);\n std::vector<hsize_t> offset(size);\n std::vector<hsize_t> slabShape(size);\n std::vector<hsize_t> marrayShape(size);\n marray::CoordinateOrder coordinateOrder;\n if(H5Aexists(dataset_, reverseShapeAttributeName) > 0) {\n NIFTY_CHECK(false, \"currently we do not allow to load from datasets with reverseShapeAttribute\")\n } \n else {\n \/\/ don't reverse base and shape\n coordinateOrder = marray::FirstMajorOrder;\n for(std::size_t j=0; j<size; ++j) {\n offset[j] = hsize_t(*baseBegin);\n slabShape[j] = hsize_t(*shapeBegin);\n marrayShape[j] = slabShape[j];\n\n ++baseBegin;\n ++shapeBegin;\n }\n }\n \n hid_t dataspace = H5Dget_space(dataset_);\n herr_t status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, \n &offset[0], NULL, &slabShape[0], NULL);\n if(status < 0) {\n H5Sclose(dataspace);\n throw std::runtime_error(\"Marray cannot select hyperslab. Check offset and shape !\");\n }\n\n \/\/ select memspace hyperslab\n hid_t memspace = H5Screate_simple(int(size), &marrayShape[0], NULL);\n std::vector<hsize_t> offsetOut(size, 0); \/\/ no offset\n status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, &offsetOut[0],\n NULL, &marrayShape[0], NULL);\n if(status < 0) {\n H5Sclose(memspace); \n H5Sclose(dataspace);\n throw std::runtime_error(\"Marray cannot select hyperslab. Check offset and shape s!\");\n }\n\n \/\/ read from dataspace into memspace\n \/\/out = Marray<T>(SkipInitialization, &marrayShape[0], \n \/\/ (&marrayShape[0])+size, coordinateOrder);\n \n if(out.isSimple()){\n \/\/std::cout<<\"is simple\\n\";\n status = H5Dread(dataset_, datatype_, memspace, dataspace,\n H5P_DEFAULT, &(out(0)));\n\n \/\/std::cout<<\"read status \"<<status<<\"\\n\";\n }\n else{\n \/\/std::cout<<\"is not simple\\n\";\n marray::Marray<T> tmpOut(marray::SkipInitialization, &marrayShape[0], \n (&marrayShape[0])+size, coordinateOrder);\n\n status = H5Dread(dataset_, datatype_, memspace, dataspace,\n H5P_DEFAULT, &(tmpOut(0)));\n\n \/\/std::cout<<\"read status \"<<status<<\"\\n\";\n\n out = tmpOut;\n }\n\n \/\/ clean up\n H5Sclose(memspace); \n H5Sclose(dataspace);\n if(status < 0) {\n throw std::runtime_error(\"Marray cannot read from dataset.\");\n }\n handleCheck.check();\n }\n\n template<class BaseIterator, class ShapeIterator>\n void \n saveHyperslab(\n BaseIterator baseBegin,\n BaseIterator baseEnd,\n ShapeIterator shapeBegin,\n const marray::View<T> & in\n ) {\n HandleCheck<marray::MARRAY_NO_DEBUG> handleCheck;\n\n \/\/ determine hyperslab shape\n std::vector<hsize_t> memoryShape(in.dimension());\n for(std::size_t j=0; j<in.dimension(); ++j) {\n memoryShape[j] = in.shape(j);\n }\n std::size_t size = std::distance(baseBegin, baseEnd);\n std::vector<hsize_t> offset(size);\n std::vector<hsize_t> slabShape(size);\n bool reverseShapeAttribute = (H5Aexists(dataset_, reverseShapeAttributeName) > 0);\n if(reverseShapeAttribute || in.coordinateOrder() == marray::LastMajorOrder) {\n NIFTY_CHECK(false, \"neither reverseShapeAttribute nor LastMajorOrder are currently supported\");\n }\n else{\n for(std::size_t j=0; j<size; ++j) {\n offset[j] = hsize_t(*baseBegin);\n slabShape[j] = hsize_t(*shapeBegin);\n ++baseBegin;\n ++shapeBegin;\n }\n }\n\n \/\/ select dataspace hyperslab\n hid_t dataspace = H5Dget_space(dataset_);\n herr_t status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, \n &offset[0], NULL, &slabShape[0], NULL);\n if(status < 0) {\n H5Sclose(dataspace);\n H5Dclose(dataset_);\n throw std::runtime_error(\"Marray cannot select hyperslab. Check offset and shape!\");\n }\n\n \/\/ select memspace hyperslab\n hid_t memspace = H5Screate_simple(int(in.dimension()), &memoryShape[0], NULL);\n std::vector<hsize_t> memoryOffset(int(in.dimension()), 0); \/\/ no offset\n status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, &memoryOffset[0], NULL,\n &memoryShape[0], NULL);\n if(status < 0) {\n H5Sclose(memspace); ;\n H5Sclose(dataspace);\n H5Dclose(dataset_);\n throw std::runtime_error(\"Marray cannot select hyperslab. Check offset and shape!\");\n }\n\n if(in.isSimple()){\n status = H5Dwrite(dataset_, datatype_, memspace, dataspace, H5P_DEFAULT, &(in(0)));\n }\n else{\n marray::Marray<T> tmp(in);\n status = H5Dwrite(dataset_, datatype_, memspace, dataspace, H5P_DEFAULT, &(tmp(0)));\n }\n \/\/ clean up\n H5Sclose(memspace); \n H5Sclose(dataspace);\n if(status < 0) {\n throw std::runtime_error(\"Marray cannot write to dataset.\");\n }\n handleCheck.check();\n }\n\n void loadShape(std::vector<uint64_t> & shapeVec){\n\n marray::marray_detail::Assert(marray::MARRAY_NO_ARG_TEST || groupHandle_ >= 0);\n HandleCheck<marray::MARRAY_NO_DEBUG> handleCheck;\n\n hid_t filespace = H5Dget_space(dataset_);\n hsize_t dimension = H5Sget_simple_extent_ndims(filespace);\n hsize_t* shape = new hsize_t[(std::size_t)(dimension)];\n herr_t status = H5Sget_simple_extent_dims(filespace, shape, NULL);\n if(status < 0) {\n H5Sclose(filespace);\n delete[] shape;\n throw std::runtime_error(\"MarrayNifty cannot get extension of dataset.\");\n }\n \/\/ write shape to shape_\n shapeVec.resize(dimension);\n if(H5Aexists(dataset_, reverseShapeAttributeName) > 0) {\n NIFTY_CHECK(false, \"currently we do not allow to load from datasets with reverseShapeAttribute\")\n }\n else {\n for(std::size_t j=0; j<shapeVec.size(); ++j) {\n shapeVec[j] = uint64_t(shape[j]);\n }\n }\n \/\/ clean up\n delete[] shape;\n H5Sclose(filespace);\n handleCheck.check();\n }\n\n void loadChunkShape(std::vector<uint64_t> & chunkShape){\n const auto d = this->dimension();\n std::vector<hsize_t> chunkShapeTmp(d);\n auto plist = H5Dget_create_plist(dataset_);\n\n\n bool couldBeChunked = false;\n const auto layout = H5Pget_layout(plist);\n if(layout == H5D_CHUNKED){\n couldBeChunked = true;\n }\n if(couldBeChunked){\n herr_t status = H5Pget_chunk(plist, int(d), chunkShapeTmp.data()); \n if(status < 0) {\n isChunked_ = false;\n chunkShape_ = shape_;\n \/\/H5Pclose(plist);\n \/\/throw std::runtime_error(\"Nifty cannot get chunkShape of dataset\");\n }\n else{\n isChunked_ = true;\n chunkShape_.resize(d);\n std::copy(chunkShapeTmp.begin(), chunkShapeTmp.end(), chunkShape_.begin());\n }\n }\n else{\n isChunked_ = false;\n chunkShape_ = shape_;\n }\n H5Pclose(plist);\n }\n\n hid_t groupHandle_;\n hid_t dataset_;\n hid_t datatype_;\n std::vector<uint64_t> shape_;\n std::vector<uint64_t> chunkShape_;\n bool isChunked_;\n };\n\n\n namespace tools{\n\n}\n\n\n} \/\/ namespace nifty::hdf5\n\n\n\nnamespace tools{\n\n template<class T, class COORD>\n inline void readSubarray(\n const hdf5::Hdf5Array<T> & array,\n const COORD & beginCoord,\n const COORD & endCoord,\n marray::View<T> & subarray\n ){\n array.readSubarray(beginCoord.begin(), subarray);\n }\n\n\n\n template<class ARRAY>\n struct BlockStorageSelector;\n\n template<class T>\n struct BlockStorageSelector<hdf5::Hdf5Array<T> >\n {\n typedef BlockStorage<T> type;\n };\n} \/\/ namespace nifty::tools\n\n\n} \/\/ namespace nifty\n\n#endif \/\/ NIFTY_HDF5_HDF5_ARRAY\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n nomlib - C++11 cross-platform game engine\n\nCopyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other 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 OWNER 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\nON ANY 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#ifndef NOMLIB_SDL2_IMAGE_HEADERS\n#define NOMLIB_SDL2_IMAGE_HEADERS\n\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <memory>\n\n#include \"SDL.h\"\n#include \"SDL_image.h\"\n\n#include \"nomlib\/config.hpp\"\n#include \"nomlib\/math\/Color.hpp\"\n#include \"nomlib\/math\/Coords.hpp\"\n#include \"nomlib\/math\/Rect-inl.hpp\"\n#include \"nomlib\/graphics\/smart_ptr.hpp\"\n\nnamespace nom {\n\n\/\/\/ \\brief Bitmap storage container\nclass Image\n{\n public:\n \/\/\/ Default constructor -- initializes to sane defaults.\n Image ( void );\n\n \/\/\/ Destructor.\n virtual ~Image ( void );\n\n \/\/\/ Construct an Image object with specified flags passed to the library\n \/\/\/ extension(s) used in this object.\n Image ( uint32 img_flags );\n\n \/\/\/ Copy constructor\n Image ( const Image& other );\n\n \/\/\/ Copy assignment constructor\n Image& operator = ( const Image& other );\n\n \/\/\/ Obtain the SDL_Surface struct used in this object instance\n SDL_Surface* get ( void ) const;\n\n \/\/\/ Is this object initialized? Valid when *NOT* nullptr\n bool valid ( void ) const;\n\n \/\/\/ Supports every file type that the libSDL_image extension has been\n \/\/\/ compiled with\n bool load ( const std::string& filename );\n\n \/\/\/ Uses SDL's built-in BMP file loader; no alpha channeling support ...\n \/\/\/ perfect for setting window icons!\n \/\/\/\n \/\/\/ (I have yet to find success using IMG_Load to load an ordinary bitmap\n \/\/\/ file, whereas SDL_LoadBMP does load fine).\n bool load_bmp ( const std::string& filename );\n\n \/\/\/ Saves as an uncompressed RGB Windows Bitmap (BMP)\n \/\/\/\n \/\/\/ NOTE: AFAIK, no existing file handling \/ overwriting checks are done\n \/\/\/ whatsoever\n bool save ( const std::string& filename, SDL_Surface* video_buffer );\n\n \/\/\/ Obtain the width and height (in pixels) of the stored bitmap buffer\n const Coords getSize ( void ) const;\n\n private:\n std::shared_ptr<SDL_Surface> image_buffer;\n};\n\n\n} \/\/ namespace nom\n\n#endif \/\/ NOMLIB_SDL_IMAGE_HEADERS defined\n<commit_msg>Introduce a type definition 'SharedPtr'<commit_after>\/******************************************************************************\n\n nomlib - C++11 cross-platform game engine\n\nCopyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other 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 OWNER 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\nON ANY 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#ifndef NOMLIB_SDL2_IMAGE_HEADERS\n#define NOMLIB_SDL2_IMAGE_HEADERS\n\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <memory>\n\n#include \"SDL.h\"\n#include \"SDL_image.h\"\n\n#include \"nomlib\/config.hpp\"\n#include \"nomlib\/math\/Color.hpp\"\n#include \"nomlib\/math\/Coords.hpp\"\n#include \"nomlib\/math\/Rect-inl.hpp\"\n#include \"nomlib\/graphics\/smart_ptr.hpp\"\n\nnamespace nom {\n\n\/\/\/ \\brief Bitmap storage container\nclass Image\n{\n public:\n \/\/\/ Convenience definition type for the std::unique_ptr variant\n typedef std::shared_ptr<SDL_Surface> SharedPtr;\n\n \/\/\/ Default constructor -- initializes to sane defaults.\n Image ( void );\n\n \/\/\/ Destructor.\n virtual ~Image ( void );\n\n \/\/\/ Construct an Image object with specified flags passed to the library\n \/\/\/ extension(s) used in this object.\n Image ( uint32 img_flags );\n\n \/\/\/ Copy constructor\n Image ( const Image& other );\n\n \/\/\/ Copy assignment constructor\n Image& operator = ( const Image& other );\n\n \/\/\/ Obtain the SDL_Surface struct used in this object instance\n SDL_Surface* get ( void ) const;\n\n \/\/\/ Is this object initialized? Valid when *NOT* nullptr\n bool valid ( void ) const;\n\n \/\/\/ Supports every file type that the libSDL_image extension has been\n \/\/\/ compiled with\n bool load ( const std::string& filename );\n\n \/\/\/ Uses SDL's built-in BMP file loader; no alpha channeling support ...\n \/\/\/ perfect for setting window icons!\n \/\/\/\n \/\/\/ (I have yet to find success using IMG_Load to load an ordinary bitmap\n \/\/\/ file, whereas SDL_LoadBMP does load fine).\n bool load_bmp ( const std::string& filename );\n\n \/\/\/ Saves as an uncompressed RGB Windows Bitmap (BMP)\n \/\/\/\n \/\/\/ NOTE: AFAIK, no existing file handling \/ overwriting checks are done\n \/\/\/ whatsoever\n bool save ( const std::string& filename, SDL_Surface* video_buffer );\n\n \/\/\/ Obtain the width and height (in pixels) of the stored bitmap buffer\n const Coords getSize ( void ) const;\n\n private:\n Image::SharedPtr image_buffer;\n};\n\n\n} \/\/ namespace nom\n\n#endif \/\/ NOMLIB_SDL_IMAGE_HEADERS defined\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: providerhelper.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 16:29:47 $\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 _UCBHELPER_PROVIDERHELPER_HXX\n#define _UCBHELPER_PROVIDERHELPER_HXX\n\n#ifndef __LIST__\n#include <list>\n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_\n#include <com\/sun\/star\/ucb\/XContentProvider.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include <com\/sun\/star\/lang\/XTypeProvider.hpp>\n#endif\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include <cppuhelper\/weak.hxx>\n#endif\n#ifndef _VOS_MUTEX_HXX_\n#include <vos\/mutex.hxx>\n#endif\n#ifndef _VOS_REF_HXX_\n#include <vos\/ref.hxx>\n#endif\n#ifndef _UCBHELPER_MACROS_HXX\n#include <ucbhelper\/macros.hxx>\n#endif\n#ifndef INCLUDED_UCBHELPERDLLAPI_H\n#include \"ucbhelper\/ucbhelperdllapi.h\"\n#endif\n\n\/\/=========================================================================\n\nnamespace com { namespace sun { namespace star { namespace ucb {\n class XPropertySetRegistry;\n class XPersistentPropertySet;\n} } } }\n\nnamespace ucb_impl { struct ContentProviderImplHelper_Impl; }\n\nnamespace ucb {\n\n\/\/=========================================================================\n\nclass ContentImplHelper;\ntypedef vos::ORef< ContentImplHelper >ContentImplHelperRef;\ntypedef std::list< ContentImplHelperRef > ContentRefList;\n\n\/**\n * This is an abstract base class for implementations of the service\n * com.sun.star.ucb.ContentProvider. It provides contents derived from\n * class ucb::ContentImplHelper.\n *\n * Features of the base class implementation:\n * - standard interfaces ( XInterface, XTypeProvider, XServiceInfo )\n * - maintains a set of ContentImplHelper objects, which were created by\n * the provider implementation. So there will be exactly one object for\n * one Content Identifier.\n * - Provides access to the Additional Core PropertySet of a content.\n * ( These set contains the properties added to a content using its\n * XPropertyContainer interface )\n *\/\nclass UCBHELPER_DLLPUBLIC ContentProviderImplHelper : public cppu::OWeakObject,\n public com::sun::star::lang::XTypeProvider,\n public com::sun::star::lang::XServiceInfo,\n public com::sun::star::ucb::XContentProvider\n{\n friend class ContentImplHelper;\n\n ucb_impl::ContentProviderImplHelper_Impl* m_pImpl;\n\nprotected:\n vos::OMutex m_aMutex;\n ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory > m_xSMgr;\n\nprivate:\n UCBHELPER_DLLPRIVATE void addContent ( ContentImplHelper* pContent );\n UCBHELPER_DLLPRIVATE void removeContent( ContentImplHelper* pContent );\n UCBHELPER_DLLPRIVATE void removeContent( const ::rtl::OUString& rURL );\n\n UCBHELPER_DLLPRIVATE ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XPropertySetRegistry >\n getAdditionalPropertySetRegistry();\n\nprotected:\n \/**\n * This method returns a content with the given id, if it already exists.\n * Use this method in your \"queryContent\" implementation to ensure unique\n * objects.\n *\n * @param Identifier is the content identifier, for that an existing\n * content object is requested.\n * @return the content with the given identifier, if it exists or 0, if it\n * does not exist.\n *\/\n vos::ORef< ContentImplHelper >\n queryExistingContent( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Identifier );\n\n \/**\n * This method returns a content with the given URL, if it already exists.\n *\n * @param rURL is the URL ( content identifier string ), for that an\n * existing content object is requested.\n * @return the content with the given URL, if it exists or 0, if it\n * does not exist.\n *\/\n vos::ORef< ContentImplHelper >\n queryExistingContent( const ::rtl::OUString& rURL );\n\npublic:\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Contsruction\/Destruction\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n ContentProviderImplHelper(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory >& rXSMgr );\n virtual ~ContentProviderImplHelper();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ XInterface\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n XINTERFACE_DECL()\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ XTypeProvider\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n XTYPEPROVIDER_DECL()\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ XServiceInfo\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n virtual ::rtl::OUString SAL_CALL\n getImplementationName()\n throw( ::com::sun::star::uno::RuntimeException ) = 0;\n virtual sal_Bool SAL_CALL\n supportsService( const ::rtl::OUString& ServiceName )\n throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL\n getSupportedServiceNames()\n throw( ::com::sun::star::uno::RuntimeException ) = 0;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ XContentProvider\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/**\n * This method returns a content with the requested id.\n *\n * The implementation should:\n *\n * - Check, whether the Identifier is valid ( URL syntax ).\n * - Use queryExistingContent(...) to determine, whether there exists\n * already a content with the given id.\n * - Return the possibly existing content.Create and return a new\n * content, otherwise\n *\/\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContent > SAL_CALL\n queryContent( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Identifier )\n throw( ::com::sun::star::ucb::IllegalIdentifierException,\n ::com::sun::star::uno::RuntimeException ) = 0;\n virtual sal_Int32 SAL_CALL\n compareContentIds( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Id1,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Id2 )\n throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Non-interface methods.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/**\n * This method returns a mutex, which protects the content list of the\n * provider. So you can prevent modifications of that list easyly.\n *\n * @return the mutex.\n *\/\n vos::OMutex& getContentListMutex() { return m_aMutex; }\n\n \/**\n * This method fills a list with all contents existing at calling time.\n * Note: You may prevent modifications of the content list at any time\n * by acquiring the content list mutex of the provider.\n *\n * @param rContents is the list to fill with the children.\n *\/\n void queryExistingContents( ContentRefList& rContents );\n\n \/**\n * This method returns the propertyset containing the Additional Core\n * Properties of a content.\n *\n * @param rKey is the key for the propertyset.\n * @param bCreate is a flag indicating whether the propertyset shall\n * be created in case it does not exist.\n * @return the propertyset containing the Additional Core Properties.\n *\/\n ::com::sun::star::uno::Reference<\n com::sun::star::ucb::XPersistentPropertySet >\n getAdditionalPropertySet( const ::rtl::OUString& rKey, sal_Bool bCreate );\n\n \/**\n * This method renames the propertyset containing the Additional Core\n * Properties of a content.\n *\n * @param rOldKey is the old key of the propertyset.\n * @param rNewKey is the new key for the propertyset.\n * @param bRecursive is a flag indicating whether propertysets for\n * children described by rOldKey shall be renamed, too.\n * @return True, if the operation succeeded - False, otherwise.\n *\/\n sal_Bool renameAdditionalPropertySet( const ::rtl::OUString& rOldKey,\n const ::rtl::OUString& rNewKey,\n sal_Bool bRecursive );\n\n \/**\n * This method copies the propertyset containing the Additional Core\n * Properties of a content.\n *\n * @param rSourceKey is the key of the source propertyset.\n * @param rTargetKey is the key of the target propertyset.\n * @param bRecursive is a flag indicating whether propertysets for\n * children described by rSourceKey shall be copied, too.\n * @return True, if the operation succeeded - False, otherwise.\n *\/\n sal_Bool copyAdditionalPropertySet( const ::rtl::OUString& rSourceKey,\n const ::rtl::OUString& rTargetKey,\n sal_Bool bRecursive );\n\n \/**\n * This method removes the propertyset containing the Additional Core\n * Properties of a content.\n *\n * @param rKey is the key of the propertyset.\n * @param bRecursive is a flag indicating whether propertysets for\n * children described by rOldKey shall be removed, too.\n * @return True, if the operation succeeded - False, otherwise.\n *\/\n sal_Bool removeAdditionalPropertySet( const ::rtl::OUString& rKey,\n sal_Bool bRecursive );\n};\n\n} \/\/ namespace ucb\n\n#endif \/* !_UCBHELPER_PROVIDERHELPER_HXX *\/\n<commit_msg>INTEGRATION: CWS bgdlremove (1.5.64); FILE MERGED 2007\/05\/18 11:38:09 kso 1.5.64.2: #i77419# - cleanup of ucbhelper namespaces. 2007\/05\/11 12:54:06 kso 1.5.64.1: #i76911# - ucbhelper no longer uses VOS<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: providerhelper.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: ihi $ $Date: 2007-06-05 14:50:14 $\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 _UCBHELPER_PROVIDERHELPER_HXX\n#define _UCBHELPER_PROVIDERHELPER_HXX\n\n#ifndef __LIST__\n#include <list>\n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_\n#include <com\/sun\/star\/ucb\/XContentProvider.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include <com\/sun\/star\/lang\/XTypeProvider.hpp>\n#endif\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include <cppuhelper\/weak.hxx>\n#endif\n\n#include \"osl\/mutex.hxx\"\n#include \"rtl\/ref.hxx\"\n\n#ifndef _UCBHELPER_MACROS_HXX\n#include <ucbhelper\/macros.hxx>\n#endif\n#ifndef INCLUDED_UCBHELPERDLLAPI_H\n#include \"ucbhelper\/ucbhelperdllapi.h\"\n#endif\n\n\/\/=========================================================================\n\nnamespace com { namespace sun { namespace star { namespace ucb {\n class XPropertySetRegistry;\n class XPersistentPropertySet;\n} } } }\n\nnamespace ucbhelper_impl { struct ContentProviderImplHelper_Impl; }\n\nnamespace ucbhelper {\n\n\/\/=========================================================================\n\nclass ContentImplHelper;\ntypedef rtl::Reference< ContentImplHelper > ContentImplHelperRef;\ntypedef std::list< ContentImplHelperRef > ContentRefList;\n\n\/**\n * This is an abstract base class for implementations of the service\n * com.sun.star.ucb.ContentProvider. It provides contents derived from\n * class ucb::ContentImplHelper.\n *\n * Features of the base class implementation:\n * - standard interfaces ( XInterface, XTypeProvider, XServiceInfo )\n * - maintains a set of ContentImplHelper objects, which were created by\n * the provider implementation. So there will be exactly one object for\n * one Content Identifier.\n * - Provides access to the Additional Core PropertySet of a content.\n * ( These set contains the properties added to a content using its\n * XPropertyContainer interface )\n *\/\nclass UCBHELPER_DLLPUBLIC ContentProviderImplHelper : public cppu::OWeakObject,\n public com::sun::star::lang::XTypeProvider,\n public com::sun::star::lang::XServiceInfo,\n public com::sun::star::ucb::XContentProvider\n{\n friend class ContentImplHelper;\n\n ucbhelper_impl::ContentProviderImplHelper_Impl* m_pImpl;\n\nprotected:\n osl::Mutex m_aMutex;\n ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory > m_xSMgr;\n\nprivate:\n UCBHELPER_DLLPRIVATE void addContent ( ContentImplHelper* pContent );\n UCBHELPER_DLLPRIVATE void removeContent( ContentImplHelper* pContent );\n UCBHELPER_DLLPRIVATE void removeContent( const ::rtl::OUString& rURL );\n\n UCBHELPER_DLLPRIVATE ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XPropertySetRegistry >\n getAdditionalPropertySetRegistry();\n\nprotected:\n \/**\n * This method returns a content with the given id, if it already exists.\n * Use this method in your \"queryContent\" implementation to ensure unique\n * objects.\n *\n * @param Identifier is the content identifier, for that an existing\n * content object is requested.\n * @return the content with the given identifier, if it exists or 0, if it\n * does not exist.\n *\/\n rtl::Reference< ContentImplHelper >\n queryExistingContent( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Identifier );\n\n \/**\n * This method returns a content with the given URL, if it already exists.\n *\n * @param rURL is the URL ( content identifier string ), for that an\n * existing content object is requested.\n * @return the content with the given URL, if it exists or 0, if it\n * does not exist.\n *\/\n rtl::Reference< ContentImplHelper >\n queryExistingContent( const ::rtl::OUString& rURL );\n\npublic:\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Contsruction\/Destruction\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n ContentProviderImplHelper(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory >& rXSMgr );\n virtual ~ContentProviderImplHelper();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ XInterface\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n XINTERFACE_DECL()\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ XTypeProvider\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n XTYPEPROVIDER_DECL()\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ XServiceInfo\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n virtual ::rtl::OUString SAL_CALL\n getImplementationName()\n throw( ::com::sun::star::uno::RuntimeException ) = 0;\n virtual sal_Bool SAL_CALL\n supportsService( const ::rtl::OUString& ServiceName )\n throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL\n getSupportedServiceNames()\n throw( ::com::sun::star::uno::RuntimeException ) = 0;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ XContentProvider\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/**\n * This method returns a content with the requested id.\n *\n * The implementation should:\n *\n * - Check, whether the Identifier is valid ( URL syntax ).\n * - Use queryExistingContent(...) to determine, whether there exists\n * already a content with the given id.\n * - Return the possibly existing content.Create and return a new\n * content, otherwise\n *\/\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContent > SAL_CALL\n queryContent( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Identifier )\n throw( ::com::sun::star::ucb::IllegalIdentifierException,\n ::com::sun::star::uno::RuntimeException ) = 0;\n virtual sal_Int32 SAL_CALL\n compareContentIds( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Id1,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Id2 )\n throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Non-interface methods.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/**\n * This method returns a mutex, which protects the content list of the\n * provider. So you can prevent modifications of that list easyly.\n *\n * @return the mutex.\n *\/\n osl::Mutex& getContentListMutex() { return m_aMutex; }\n\n \/**\n * This method fills a list with all contents existing at calling time.\n * Note: You may prevent modifications of the content list at any time\n * by acquiring the content list mutex of the provider.\n *\n * @param rContents is the list to fill with the children.\n *\/\n void queryExistingContents( ContentRefList& rContents );\n\n \/**\n * This method returns the propertyset containing the Additional Core\n * Properties of a content.\n *\n * @param rKey is the key for the propertyset.\n * @param bCreate is a flag indicating whether the propertyset shall\n * be created in case it does not exist.\n * @return the propertyset containing the Additional Core Properties.\n *\/\n ::com::sun::star::uno::Reference<\n com::sun::star::ucb::XPersistentPropertySet >\n getAdditionalPropertySet( const ::rtl::OUString& rKey, sal_Bool bCreate );\n\n \/**\n * This method renames the propertyset containing the Additional Core\n * Properties of a content.\n *\n * @param rOldKey is the old key of the propertyset.\n * @param rNewKey is the new key for the propertyset.\n * @param bRecursive is a flag indicating whether propertysets for\n * children described by rOldKey shall be renamed, too.\n * @return True, if the operation succeeded - False, otherwise.\n *\/\n sal_Bool renameAdditionalPropertySet( const ::rtl::OUString& rOldKey,\n const ::rtl::OUString& rNewKey,\n sal_Bool bRecursive );\n\n \/**\n * This method copies the propertyset containing the Additional Core\n * Properties of a content.\n *\n * @param rSourceKey is the key of the source propertyset.\n * @param rTargetKey is the key of the target propertyset.\n * @param bRecursive is a flag indicating whether propertysets for\n * children described by rSourceKey shall be copied, too.\n * @return True, if the operation succeeded - False, otherwise.\n *\/\n sal_Bool copyAdditionalPropertySet( const ::rtl::OUString& rSourceKey,\n const ::rtl::OUString& rTargetKey,\n sal_Bool bRecursive );\n\n \/**\n * This method removes the propertyset containing the Additional Core\n * Properties of a content.\n *\n * @param rKey is the key of the propertyset.\n * @param bRecursive is a flag indicating whether propertysets for\n * children described by rOldKey shall be removed, too.\n * @return True, if the operation succeeded - False, otherwise.\n *\/\n sal_Bool removeAdditionalPropertySet( const ::rtl::OUString& rKey,\n sal_Bool bRecursive );\n};\n\n} \/\/ namespace ucbhelper\n\n#endif \/* !_UCBHELPER_PROVIDERHELPER_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Used for testing, do not use it as an example\n#include <iostream>\n\n#include \"qpp.h\"\n\nint main() {\n \/\/\/\/\/\/\/\/\/\/\/ testing \/\/\/\/\/\/\/\/\/\/\/\n using namespace qpp;\n}\n<commit_msg>Update _test.cpp<commit_after>\/\/ Used for testing, do not use it as an example\n#include <iostream>\n\n#include \"qpp.h\"\n\nint main() {\n \/\/\/\/\/\/\/\/\/\/\/ testing \/\/\/\/\/\/\/\/\/\/\/\n using namespace qpp;\n\n \/\/ Quantum coin flip\n QCircuit qc{1, 1};\n qc.gate(gt.H, 0).measureZ(0, 0);\n\n QEngine q_engine{qc};\n q_engine.execute();\n std::cout << q_engine << '\\n';\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * examples\/bench.cpp\n *\n\n\/*******************************************************************************\n * examples\/bench.cpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#include <c7a\/api\/dia.hpp>\n#include <c7a\/core\/reduce_pre_table.hpp>\n\nint main(int argc, char* argv[]) {\n auto emit = [](int in) {\n in = in;\n \/\/std::cout << in << std::endl;\n };\n\n auto key_ex = [](int in) {\n return in;\n };\n\n auto red_fn = [](int in1, int in2) {\n return in1 + in2;\n };\n\n srand(time(NULL));\n int workers = std::stoi(argv[2]);\n int modulo = std::stoi(argv[3]);\n\n c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>\n table(workers, key_ex, red_fn, { emit });\n\n int end = std::stoi(argv[1]);\n\n clock_t time = std::clock();\n\n for (int i = 0; i < end; i++) {\n table.Insert(rand() % modulo);\n }\n\n table.Flush();\n\n time = std::clock() - time;\n\n printf(\"%f\", ((double)(time * 1000000) \/ (double)CLOCKS_PER_SEC));\n \/\/printf(std::endl);\n\n \/\/std::cout << (time * 1000000) \/ (double) CLOCKS_PER_SEC << std::endl;\n\n return 0;\n}\n\n\/******************************************************************************\/\n<commit_msg>fix compiler warning<commit_after>\/*******************************************************************************\n * examples\/bench.cpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#include <c7a\/api\/dia.hpp>\n#include <c7a\/core\/reduce_pre_table.hpp>\n\nint main(int argc, char* argv[]) {\n auto emit = [](int in) {\n in = in;\n \/\/std::cout << in << std::endl;\n };\n\n auto key_ex = [](int in) {\n return in;\n };\n\n auto red_fn = [](int in1, int in2) {\n return in1 + in2;\n };\n\n srand(time(NULL));\n int workers = std::stoi(argv[2]);\n int modulo = std::stoi(argv[3]);\n\n c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>\n table(workers, key_ex, red_fn, { emit });\n\n int end = std::stoi(argv[1]);\n\n clock_t time = std::clock();\n\n for (int i = 0; i < end; i++) {\n table.Insert(rand() % modulo);\n }\n\n table.Flush();\n\n time = std::clock() - time;\n\n printf(\"%f\", ((double)(time * 1000000) \/ (double)CLOCKS_PER_SEC));\n \/\/printf(std::endl);\n\n \/\/std::cout << (time * 1000000) \/ (double) CLOCKS_PER_SEC << std::endl;\n\n return 0;\n}\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>#include \"ludii.h\"\n#include <iostream>\n#include <string>\n#include <vector>\n\n\nLudii::Ludii(const std::string jar_location){\n\tinitJVM(jar_location);\n}\n\nLudii::~Ludii(){\n\tcloseJVM();\n}\n\nstd::vector<std::string> Ludii::listGames(){\n\n\tstd::vector<std::string> gamesVector;\n\n\tjclass gameLoader = env->FindClass(\"player\/GameLoader\");\n\n \/\/find the listGames method\n jmethodID mid = env->GetStaticMethodID(gameLoader,\"listGames\",\"()[Ljava\/lang\/String;\");\n\n \/\/execute the listGames method\n jobjectArray stringArray = (jobjectArray) env->CallStaticObjectMethod(gameLoader,mid);\n\n \/\/put list of games in vector\n int stringCount = env->GetArrayLength(stringArray);\n\n\tfor (int i=0; i<stringCount; i++) {\n\t\t\/\/get array element and convert it from jstrng\n jstring string = (jstring) (env->GetObjectArrayElement(stringArray, i));\n const char *rawString = env->GetStringUTFChars(string, 0);\n \n \tstd::string cppString(rawString);\n gamesVector.push_back(cppString);\n\n env->ReleaseStringUTFChars(string, rawString);\n }\n\n\treturn gamesVector;\n}\n\nvoid Ludii::loadGameAndDoStuff(std::string game_name){\n\n\t\/\/create game object i.e. `Game game = GameLoader.loadGameFromName`\n\tjclass gameLoader = env->FindClass(\"player\/GameLoader\");\n jmethodID mid = env->GetStaticMethodID(gameLoader,\"loadGameFromName\",\"(Ljava\/lang\/String;)Lgame\/Game;\");\n\n\t\/\/convert game name to java string\n\tchar game_name_char[1024];\n\tstrcpy(game_name_char, game_name.c_str());\n\tjstring j_game_name = env->NewStringUTF(game_name_char);\n\n\tjobject game_obj = env->CallStaticObjectMethod(gameLoader,mid,j_game_name);\n\n\t\/\/call the `name()` method on the game object we just created\n\tjclass gameClass = env->FindClass(\"game\/Game\");\n\tjmethodID name_id = env->GetMethodID(gameClass,\"name\",\"()Ljava\/lang\/String;\");\n\tjstring stringArray =(jstring) env->CallObjectMethod(game_obj,name_id);\n\t\n\t\/\/convert jstring game name to char array and print\n\tconst char *strReturn = env->GetStringUTFChars(stringArray, 0);\n\tstd::cout<< \"name() result: \"<<strReturn<<std::endl;\n \n env->ReleaseStringUTFChars(stringArray, strReturn);\n}\n\n\nint main(){\n\n\tstd::string jar_location = \"\/home\/alex\/Downloads\/Ludii-0.3.0.jar\";\n\n\tLudii test_ludii = Ludii(jar_location);\n\n\tstd::vector<std::string> games = test_ludii.listGames();\n\n\ttest_ludii.loadGameAndDoStuff(\"board\/space\/blocking\/Amazons.lud\");\n}<commit_msg>for some reason the indentation in sublime is different than what is showing in github<commit_after>#include \"ludii.h\"\n#include <iostream>\n#include <string>\n#include <vector>\n\n\nLudii::Ludii(const std::string jar_location){\n\tinitJVM(jar_location);\n}\n\nLudii::~Ludii(){\n\tcloseJVM();\n}\n\nstd::vector<std::string> Ludii::listGames(){\n\n\tstd::vector<std::string> gamesVector;\n\n\tjclass gameLoader = env->FindClass(\"player\/GameLoader\");\n\n \t\/\/find the listGames method\n \tjmethodID mid = env->GetStaticMethodID(gameLoader,\"listGames\",\"()[Ljava\/lang\/String;\");\n\n \t\/\/execute the listGames method\n \tjobjectArray stringArray = (jobjectArray) env->CallStaticObjectMethod(gameLoader,mid);\n\n \t\/\/put list of games in vector\n \tint stringCount = env->GetArrayLength(stringArray);\n\n\tfor (int i=0; i<stringCount; i++) {\n\t\t\/\/get array element and convert it from jstrng\n \tjstring string = (jstring) (env->GetObjectArrayElement(stringArray, i));\n \tconst char *rawString = env->GetStringUTFChars(string, 0);\n \n \t\tstd::string cppString(rawString);\n \tgamesVector.push_back(cppString);\n\n \tenv->ReleaseStringUTFChars(string, rawString);\n \t}\n\n\treturn gamesVector;\n}\n\nvoid Ludii::loadGameAndDoStuff(std::string game_name){\n\n\t\/\/create game object i.e. `Game game = GameLoader.loadGameFromName()`\n\tjclass gameLoader = env->FindClass(\"player\/GameLoader\");\n \tjmethodID mid = env->GetStaticMethodID(gameLoader,\"loadGameFromName\",\"(Ljava\/lang\/String;)Lgame\/Game;\");\n\n\t\/\/convert game name to java string\n\tchar game_name_char[1024];\n\tstrcpy(game_name_char, game_name.c_str());\n\tjstring j_game_name = env->NewStringUTF(game_name_char);\n\n\tjobject game_obj = env->CallStaticObjectMethod(gameLoader,mid,j_game_name);\n\n\t\/\/call the `name()` method on the game object we just created\n\tjclass gameClass = env->FindClass(\"game\/Game\");\n\tjmethodID name_id = env->GetMethodID(gameClass,\"name\",\"()Ljava\/lang\/String;\");\n\tjstring stringArray =(jstring) env->CallObjectMethod(game_obj,name_id);\n\t\n\t\/\/convert jstring game name to char array and print\n\tconst char *strReturn = env->GetStringUTFChars(stringArray, 0);\n\tstd::cout<< \"name() result: \"<<strReturn<<std::endl;\n \n \tenv->ReleaseStringUTFChars(stringArray, strReturn);\n}\n\n\nint main(){\n\n\tstd::string jar_location = \"\/home\/alex\/Downloads\/Ludii-0.3.0.jar\";\n\n\tLudii test_ludii = Ludii(jar_location);\n\n\tstd::vector<std::string> games = test_ludii.listGames();\n\n\ttest_ludii.loadGameAndDoStuff(\"board\/space\/blocking\/Amazons.lud\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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#include <vector>\n\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/TypeBuilder.h\"\n#if (LLVM_VERSION_MINOR >= 5)\n #include \"llvm\/IR\/InstIterator.h\"\n#else\n #include \"llvm\/Support\/InstIterator.h\"\n#endif\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n\nusing namespace llvm;\n\nclass InitializeUninitialized : public FunctionPass {\n public:\n static char ID;\n\n InitializeUninitialized() : FunctionPass(ID) {}\n\n virtual bool runOnFunction(Function &F);\n};\n\n\nstatic RegisterPass<InitializeUninitialized> INIUNINI(\"initialize-uninitialized\",\n \"initialize all uninitialized variables to non-deterministic value\");\nchar InitializeUninitialized::ID;\n\nbool InitializeUninitialized::runOnFunction(Function &F)\n{\n \/\/ do not run the initializer on __VERIFIER and __INSTR functions\n const auto& fname = F.getName();\n if (fname.startswith(\"__VERIFIER_\") || fname.startswith(\"__INSTR_\"))\n return false;\n\n bool modified = false;\n Module *M = F.getParent();\n LLVMContext& Ctx = M->getContext();\n DataLayout *DL = new DataLayout(M->getDataLayout());\n Constant *name_init = ConstantDataArray::getString(Ctx, \"nondet\");\n GlobalVariable *name = new GlobalVariable(*M, name_init->getType(), true, GlobalValue::PrivateLinkage, name_init);\n Type *size_t_Ty;\n\n if (DL->getPointerSizeInBits() > 32)\n size_t_Ty = Type::getInt64Ty(Ctx);\n else\n size_t_Ty = Type::getInt32Ty(Ctx);\n\n \/\/void klee_make_symbolic(void *addr, size_t nbytes, const char *name);\n Constant *C = M->getOrInsertFunction(\"klee_make_symbolic\",\n Type::getVoidTy(Ctx),\n Type::getInt8PtrTy(Ctx), \/\/ addr\n size_t_Ty, \/\/ nbytes\n Type::getInt8PtrTy(Ctx), \/\/ name\n NULL);\n\n\n for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {\n Instruction *ins = &*I;\n ++I;\n\n if (AllocaInst *AI = dyn_cast<AllocaInst>(ins)) {\n Type *Ty = AI->getAllocatedType();\n AllocaInst *newAlloca = NULL;\n CallInst *CI = NULL;\n CastInst *CastI = NULL;\n StoreInst *SI = NULL;\n LoadInst *LI = NULL;\n\n std::vector<Value *> args;\n\n \/\/ create new allocainst, declare it symbolic and store it\n \/\/ to the original alloca. This way slicer will slice this\n \/\/ initialization away if program initialize it manually later\n if (Ty->isSized()) {\n \/\/ if this is an array allocation, just call klee_make_symbolic on it,\n \/\/ since storing whole symbolic array into it would have soo huge overhead\n if (Ty->isArrayTy()) {\n CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));\n args.push_back(CastI);\n args.push_back(ConstantInt::get(size_t_Ty, DL->getTypeAllocSize(Ty)));\n args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));\n\n CI = CallInst::Create(C, args);\n CastI->insertAfter(AI);\n CI->insertAfter(CastI);\n } else {\n \/\/ when this is not an array allocation, create new symbolic memory and\n \/\/ store it into the allocated memory using normal StoreInst.\n \/\/ That will allow slice away more unneeded allocations\n newAlloca = new AllocaInst(Ty, \"alloca_uninitial\");\n CastI = CastInst::CreatePointerCast(newAlloca, Type::getInt8PtrTy(Ctx));\n\n args.push_back(CastI);\n args.push_back(ConstantInt::get(size_t_Ty, DL->getTypeAllocSize(Ty)));\n args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));\n CI = CallInst::Create(C, args);\n\n LI = new LoadInst(newAlloca);\n SI = new StoreInst(LI, AI);\n\n newAlloca->insertAfter(AI);\n CastI->insertAfter(newAlloca);\n CI->insertAfter(CastI);\n LI->insertAfter(CI);\n SI->insertAfter(LI);\n }\n\n modified = true;\n }\n }\n }\n\n delete DL;\n return modified;\n}\n\n<commit_msg>InitializeUninitialized: initialize less memory<commit_after>\/\/ 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#include <vector>\n\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/TypeBuilder.h\"\n#if (LLVM_VERSION_MINOR >= 5)\n #include \"llvm\/IR\/InstIterator.h\"\n#else\n #include \"llvm\/Support\/InstIterator.h\"\n#endif\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n\nusing namespace llvm;\n\nclass InitializeUninitialized : public FunctionPass {\n public:\n static char ID;\n\n InitializeUninitialized() : FunctionPass(ID) {}\n\n virtual bool runOnFunction(Function &F);\n};\n\n\nstatic RegisterPass<InitializeUninitialized> INIUNINI(\"initialize-uninitialized\",\n \"initialize all uninitialized variables to non-deterministic value\");\nchar InitializeUninitialized::ID;\n\n\/\/ no hard analysis, just check wether the alloca is initialized\n\/\/ in the same block. (we could do an O(n) analysis that would\n\/\/ do DFS and if the alloca would be initialized on every path\n\/\/ before reaching some backedge, then it must be initialized),\n\/\/ for all allocas the running time would be O(n^2) and it could\n\/\/ probably be decreased (without pointers)\nstatic bool mayBeUnititialized(const llvm::AllocaInst *AI)\n{\n using namespace llvm;\n\n\tType *AITy = AI->getAllocatedType();\n\tif(!AITy->isSized())\n\t\treturn true;\n\n const BasicBlock *block = AI->getParent();\n auto I = block->begin();\n auto E = block->end();\n \/\/ shift to AI\n while (I != E && (&*I) != AI)\n ++I;\n\n if (I == E)\n return true;\n\n \/\/ iterate over instructions after AI in this block\n for (++I \/* shift after AI *\/; I != E; ++I) {\n if (const StoreInst *SI = dyn_cast<StoreInst>(&*I)) {\n \/\/ we store into AI and we store the same type\n \/\/ (that is, we overwrite the whole memory?)\n if (SI->getPointerOperand() == AI &&\n SI->getValueOperand()->getType() == AITy)\n return false;\n }\n }\n\n return true;\n}\n\nbool InitializeUninitialized::runOnFunction(Function &F)\n{\n \/\/ do not run the initializer on __VERIFIER and __INSTR functions\n const auto& fname = F.getName();\n if (fname.startswith(\"__VERIFIER_\") || fname.startswith(\"__INSTR_\"))\n return false;\n\n bool modified = false;\n Module *M = F.getParent();\n LLVMContext& Ctx = M->getContext();\n DataLayout *DL = new DataLayout(M->getDataLayout());\n Constant *name_init = ConstantDataArray::getString(Ctx, \"nondet\");\n GlobalVariable *name = new GlobalVariable(*M, name_init->getType(), true,\n GlobalValue::PrivateLinkage,\n name_init);\n Type *size_t_Ty;\n\n if (DL->getPointerSizeInBits() > 32)\n size_t_Ty = Type::getInt64Ty(Ctx);\n else\n size_t_Ty = Type::getInt32Ty(Ctx);\n\n \/\/void klee_make_symbolic(void *addr, size_t nbytes, const char *name);\n Constant *C = M->getOrInsertFunction(\"klee_make_symbolic\",\n Type::getVoidTy(Ctx),\n Type::getInt8PtrTy(Ctx), \/\/ addr\n size_t_Ty, \/\/ nbytes\n Type::getInt8PtrTy(Ctx), \/\/ name\n NULL);\n\n\n for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {\n Instruction *ins = &*I;\n ++I;\n\n if (AllocaInst *AI = dyn_cast<AllocaInst>(ins)) {\n if (!mayBeUnititialized(AI))\n continue;\n\n Type *Ty = AI->getAllocatedType();\n AllocaInst *newAlloca = nullptr;\n CallInst *CI = nullptr;\n CastInst *CastI = nullptr;\n StoreInst *SI = nullptr;\n LoadInst *LI = nullptr;\n\n std::vector<Value *> args;\n\n \/\/ create new allocainst, declare it symbolic and store it\n \/\/ to the original alloca. This way slicer will slice this\n \/\/ initialization away if program initialize it manually later\n if (Ty->isSized()) {\n \/\/ if this is an array allocation, just call klee_make_symbolic on it,\n \/\/ since storing whole symbolic array into it would have soo huge overhead\n if (Ty->isArrayTy()) {\n CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));\n args.push_back(CastI);\n args.push_back(ConstantInt::get(size_t_Ty, DL->getTypeAllocSize(Ty)));\n args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));\n\n CI = CallInst::Create(C, args);\n CastI->insertAfter(AI);\n CI->insertAfter(CastI);\n } else {\n \/\/ when this is not an array allocation, create new symbolic memory and\n \/\/ store it into the allocated memory using normal StoreInst.\n \/\/ That will allow slice away more unneeded allocations\n newAlloca = new AllocaInst(Ty, \"alloca_uninitial\");\n CastI = CastInst::CreatePointerCast(newAlloca, Type::getInt8PtrTy(Ctx));\n\n args.push_back(CastI);\n args.push_back(ConstantInt::get(size_t_Ty, DL->getTypeAllocSize(Ty)));\n args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));\n CI = CallInst::Create(C, args);\n\n LI = new LoadInst(newAlloca);\n SI = new StoreInst(LI, AI);\n\n newAlloca->insertAfter(AI);\n CastI->insertAfter(newAlloca);\n CI->insertAfter(CastI);\n LI->insertAfter(CI);\n SI->insertAfter(LI);\n }\n\n modified = true;\n }\n }\n }\n\n delete DL;\n return modified;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2019, Vinitha Ranganeni\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 met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. 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\/\/ 3. Neither the name of the copyright holder 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 \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef LIBCOZMO_STATESPACE_STATESPACE_HPP_\n#define LIBCOZMO_STATESPACE_STATESPACE_HPP_\n\n#include \"aikido\/distance\/SE2.hpp\"\n\nnamespace libcozmo {\nnamespace statespace {\n\nclass StateSpace\n{\n public:\n\n \t\/\/\/ Base class for all discrete states\n \tclass State;\n\n \t\/\/\/ Checks if given (discrete) state exists in the statespace; if not, \n \/\/\/ creates and adds the state to the statespace\n \/\/\/\n \/\/\/ \\param state Input state\n \/\/\/ \\return state ID\n \tvirtual int get_or_create_state(const State* _state) = 0;\n \t\n \t\/\/\/ Checks if given (continuous) state exists in the statespace; if not, \n \/\/\/ creates and adds the state to the statespace\n \/\/\/\n \/\/\/ \\param state Input state\n \/\/\/ \\return State ID\n \tvirtual int get_or_create_state(\n \t\tconst aikido::statespace::StateSpace::State* _state) = 0;\n\n \/\/\/ Converts the given discrete state into a continuous state\n \/\/\/\n \/\/\/ \\param _state Input discrete state\n \/\/\/ \\param[out] _state Output continuous state\n \tvirtual void discrete_state_to_continuous(\n const State* _state,\n aikido::statespace::StateSpace::State* _continuous_state) const = 0;\n\n \/\/\/ Converts the given continuous state into a discrete state\n \/\/\/\n \/\/\/ \\param _state Input discrete state \n \/\/\/ \\param[out] _state Output continuous state\n \tvirtual void continuous_state_to_discrete(\n const aikido::statespace::StateSpace::State* _state, \n State* _discrete_state) const = 0;\n\n \t\/\/\/ Gets the state ID for the given state if the state exists in the\n \/\/\/ statespace\n \/\/\/\n \/\/\/ \\param _state Input discrete state\n \/\/\/ \\param[out] state_id State ID\n \/\/\/ \\return True if the state ID was found and false otherwise\n \tvirtual bool get_state_id(const State* _state, int* _state_id) const = 0;\n\n \t\/\/\/ Gets the state for the give ID if the state exists in the statespace\n \/\/\/\n \/\/\/ \\param state_id The ID of the state\n \/\/\/ \\return Pointer to the discrete state\n \tvirtual State* get_state(const int& _state_id) const = 0;\n\n \t\/\/\/ Checks if the given state is a valid state; validity of state varies \n \t\/\/\/ based on state type\n \/\/\/\n \/\/\/ \\param _state Input discrete state\n \/\/\/ \\return True if the state if valid and false otherwise\n \tvirtual bool is_valid_state(const State* _state) const = 0;\n\n \/\/\/ Get the number of states in the statespace\n \/\/\/\n \/\/\/ \\return Number of states\n virtual int size() const = 0;\n\n \/\/\/ Gets the distance between two SE2 states\n \/\/\/\n \/\/\/ \\param state_1, state_2 The discrete states to calculate the SE2 \n \/\/\/ distance between\n \/\/\/ \\return Distance between the states\n virtual double get_distance(\n const State* _state_1, const State* _state_2) const = 0;\n\n \/\/\/ Gets the distance between two SE2 states\n \/\/\/\n \/\/\/ \\param state_1, state_2 The continuous states to calculate the SE2 \n \/\/\/ distance between\n \/\/\/ \\return Distance between the states\n virtual double get_distance(\n const aikido::statespace::StateSpace::State* _state_1,\n const aikido::statespace::StateSpace::State* _state_2) const = 0;\n\n \/\/\/ Copies a discrete state\n \/\/\/ \n \/\/\/ \\param _source Input state (state to copy)\n \/\/\/ \\param[out] _destination Output state\n virtual void copy_state(const State* _source, State* _destination) const = 0;\n\n private:\n \tvirtual State* create_state() = 0;\n};\n\n\nclass StateSpace::State\n{\n protected:\n \t\/\/ This is a base class that should only only be used in derived classes.\n \tState() = default;\n\n \t~State() = default;\n};\n\n} \/\/ namespace statespace\n} \/\/ namespace libcozmo\n\n#endif<commit_msg>converted indentation to spaces<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2019, Vinitha Ranganeni\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 met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. 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\/\/ 3. Neither the name of the copyright holder 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 \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef LIBCOZMO_STATESPACE_STATESPACE_HPP_\n#define LIBCOZMO_STATESPACE_STATESPACE_HPP_\n\n#include \"aikido\/distance\/SE2.hpp\"\n\nnamespace libcozmo {\nnamespace statespace {\n\nclass StateSpace\n{\n public:\n\n \/\/\/ Base class for all discrete states\n class State;\n\n \/\/\/ Checks if given (discrete) state exists in the statespace; if not, \n \/\/\/ creates and adds the state to the statespace\n \/\/\/\n \/\/\/ \\param state Input state\n \/\/\/ \\return state ID\n virtual int get_or_create_state(const State* _state) = 0;\n \n \/\/\/ Checks if given (continuous) state exists in the statespace; if not, \n \/\/\/ creates and adds the state to the statespace\n \/\/\/\n \/\/\/ \\param state Input state\n \/\/\/ \\return State ID\n virtual int get_or_create_state(\n const aikido::statespace::StateSpace::State* _state) = 0;\n\n \/\/\/ Converts the given discrete state into a continuous state\n \/\/\/\n \/\/\/ \\param _state Input discrete state\n \/\/\/ \\param[out] _state Output continuous state\n virtual void discrete_state_to_continuous(\n const State* _state,\n aikido::statespace::StateSpace::State* _continuous_state) const = 0;\n\n \/\/\/ Converts the given continuous state into a discrete state\n \/\/\/\n \/\/\/ \\param _state Input discrete state \n \/\/\/ \\param[out] _state Output continuous state\n virtual void continuous_state_to_discrete(\n const aikido::statespace::StateSpace::State* _state, \n State* _discrete_state) const = 0;\n\n \/\/\/ Gets the state ID for the given state if the state exists in the\n \/\/\/ statespace\n \/\/\/\n \/\/\/ \\param _state Input discrete state\n \/\/\/ \\param[out] state_id State ID\n \/\/\/ \\return True if the state ID was found and false otherwise\n virtual bool get_state_id(const State* _state, int* _state_id) const = 0;\n\n \/\/\/ Gets the state for the give ID if the state exists in the statespace\n \/\/\/\n \/\/\/ \\param state_id The ID of the state\n \/\/\/ \\return Pointer to the discrete state\n virtual State* get_state(const int& _state_id) const = 0;\n\n \/\/\/ Checks if the given state is a valid state; validity of state varies \n \/\/\/ based on state type\n \/\/\/\n \/\/\/ \\param _state Input discrete state\n \/\/\/ \\return True if the state if valid and false otherwise\n virtual bool is_valid_state(const State* _state) const = 0;\n\n \/\/\/ Get the number of states in the statespace\n \/\/\/\n \/\/\/ \\return Number of states\n virtual int size() const = 0;\n\n \/\/\/ Gets the distance between two SE2 states\n \/\/\/\n \/\/\/ \\param state_1, state_2 The discrete states to calculate the SE2 \n \/\/\/ distance between\n \/\/\/ \\return Distance between the states\n virtual double get_distance(\n const State* _state_1, const State* _state_2) const = 0;\n\n \/\/\/ Gets the distance between two SE2 states\n \/\/\/\n \/\/\/ \\param state_1, state_2 The continuous states to calculate the SE2 \n \/\/\/ distance between\n \/\/\/ \\return Distance between the states\n virtual double get_distance(\n const aikido::statespace::StateSpace::State* _state_1,\n const aikido::statespace::StateSpace::State* _state_2) const = 0;\n\n \/\/\/ Copies a discrete state\n \/\/\/ \n \/\/\/ \\param _source Input state (state to copy)\n \/\/\/ \\param[out] _destination Output state\n virtual void copy_state(const State* _source, State* _destination) const = 0;\n\n private:\n virtual State* create_state() = 0;\n};\n\n\nclass StateSpace::State\n{\n protected:\n \/\/ This is a base class that should only only be used in derived classes.\n State() = default;\n\n ~State() = default;\n};\n\n} \/\/ namespace statespace\n} \/\/ namespace libcozmo\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Adrian Palmquist on 15-04-28.\n\/\/\n\n#pragma once\n\n#include <BulletCollision\/NarrowPhaseCollision\/btRaycastCallback.h>\n#include <events\/DebugdrawerEvent.hpp>\n#include <events\/GravityChangeEvent.hpp>\n#include \"entityx\/entityx.h\"\n#include \"btBulletDynamicsCommon.h\"\n#include \"components\/PhysicsComponent.hpp\"\n#include \"physics\/MyDebugDrawer.hpp\"\n#include \"HelperFunctions.hpp\"\n\n#include \"events\/ProjectionViewEvent.hpp\"\n#include \"events\/PickUpObjectEvent.hpp\"\n\nnamespace ex = entityx;\n\nnamespace sw {\n\n class PhysicsSystem : public ex::System<PhysicsSystem>, public ex::Receiver<PhysicsSystem> {\n public:\n\n PhysicsSystem() {\n \/\/ create the collision configuration\n m_pCollisionConfiguration = new btDefaultCollisionConfiguration();\n\n \/\/ Default collision dispatcher\n m_pDispatcher = new btCollisionDispatcher(m_pCollisionConfiguration);\n\n \/\/ create the broadphase\n m_pBroadphase = new btDbvtBroadphase();\n\n \/\/ create the constraint solver\n m_pSolver = new btSequentialImpulseConstraintSolver();\n\n\n \/\/ create the world\n m_pWorld = new btDiscreteDynamicsWorld(m_pDispatcher, m_pBroadphase, m_pSolver, m_pCollisionConfiguration);\n\n m_pWorld->setGravity(btVector3(0, -10, 0));\n\n debugDrawer_ = new MyDebugDrawer();\n m_pWorld->setDebugDrawer(debugDrawer_);\n\n m_pWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_MAX_DEBUG_DRAW_MODE);\n\n will_update_current_bodies_ = false;\n dim_from_ = Dim::DIMENSION_ONE;\n last_dim_change_num = -1;\n }\n\n\n void configure(ex::EventManager &events) override {\n events.subscribe<DebugdrawerEvent>(*this);\n events.subscribe<DimensionChangeInProgressEvent>(*this);\n events.subscribe<PickUpObjectEvent>(*this);\n events.subscribe<ProjectionViewEvent>(*this);\n events.subscribe<GravityChangeEvent>(*this);\n\n }\n\n\n void populateWorld(ex::EntityManager &es) {\n auto physics = ex::ComponentHandle<PhysicsComponent>();\n auto dimension = ex::ComponentHandle<DimensionComponent>();\n\n for (ex::Entity e : es.entities_with_components(physics, dimension)) {\n Dim d = dimension->dimension_;\n\n std::cout << \"populateworld\" << std::endl;\n \/*\n std::cout << \"Group: \" << physics->group_ << std::endl;\n std::cout << \"Mask: \" << physics->mask_ << std::endl;\n std::cout << \"Previous flags: \" << physics->body_->getCollisionFlags() << std::endl;\n *\/\n std::cout << \" dimension: \" << d << \"\\n\";\n physics->body_->activate(true);\n\n m_pWorld->addRigidBody(physics->body_, d, d);\n }\n\n auto player = ex::ComponentHandle<PlayerComponent>();\n for (ex::Entity e : es.entities_with_components(player, physics)) {\n\n btTransform temp;\n physics->body_->getMotionState()->getWorldTransform(temp);\n btVector3 playerMin = temp.getOrigin();\n btVector3 btTo(playerMin.x(), -500.0f, playerMin.z());\n\n btCollisionWorld::ClosestRayResultCallback res(playerMin, btTo);\n\n m_pWorld->rayTest(playerMin, btTo, res);\n\n if (res.hasHit()) {\n\n\n btTo = res.m_hitPointWorld;\n btScalar p = playerMin.distance(btTo);\n\n player->distance_to_bottom_ = physics->height_;\n\n std::cout << \"Distance to bottom: \" << p << std::endl;\n\n\n }\n\n }\n }\n\n\n ~PhysicsSystem() {\n delete m_pWorld;\n delete debugDrawer_;\n delete m_pBroadphase;\n delete m_pDispatcher;\n delete m_pCollisionConfiguration;\n delete m_pSolver;\n }\n\n\n void update(entityx::EntityManager &entityManager, entityx::EventManager &eventManager, entityx::TimeDelta dt) {\n if (will_update_current_bodies_) {\n \/*std::cout << \"Will update bitches\\n\";\n auto dimension = ex::ComponentHandle<DimensionComponent>();\n auto physics = ex::ComponentHandle<PhysicsComponent>();\n for (ex::Entity e : entityManager.entities_with_components(dimension, physics)) {\n Dim d = dimension->dimension_;\n if (d == Dim::DIMENSION_BOTH)\n continue;\n if (d == dim_from_) {\n \/\/m_pWorld->removeRigidBody(physics->body_);\n physics->body_->setActivationState(ISLAND_SLEEPING);\n \/\/physics->body_->setActivationState(DISABLE_SIMULATION);\n std::cout << \"Disabled a bitch\\n\";\n }\n else {\n \/\/m_pWorld->addRigidBody(physics->body_);\n \/\/physics->body_->setActivationState(DISABLE_DEACTIVATION);\n physics->body_->activate(true);\n std::cout << \"Enabled a bitch\\n\";\n }\n }*\/\n auto physics = ex::ComponentHandle<PhysicsComponent>();\n auto dimension = ex::ComponentHandle<DimensionComponent>();\n auto player = ex::ComponentHandle<PlayerComponent>();\n\n for (ex::Entity p : entityManager.entities_with_components(player, physics, dimension)) {\n Dim d = dimension->dimension_;\n m_pWorld->removeRigidBody(physics->body_);\n m_pWorld->addRigidBody(physics->body_, d, d);\n std::cout << \"Current player dimension is: \" << d << \"\\n\";\n }\n\n will_update_current_bodies_ = false;\n }\n\n\n m_pWorld->stepSimulation(dt);\n\n if (m_debugMode) {\n m_pWorld->debugDrawWorld();\n debugDrawer_->drawLines();\n\n }\n\n\n auto player = ex::ComponentHandle<PlayerComponent>();\n auto physics = ex::ComponentHandle<PhysicsComponent>();\n\n for (ex::Entity e : entityManager.entities_with_components(player, physics)) {\n\n if (!proj_view_events_.empty()) {\n view_ = proj_view_events_.front().view_matrix_;\n camera_projection_ = proj_view_events_.front().projection_matrix_;\n\n proj_view_events_.clear();\n }\n\n if (!pickup_events_.empty()) {\n processPickupEvents(physics);\n }\n\n btTransform temp;\n btVector3 tempVec;\n btVector3 playerMin;\n\n physics->body_->getMotionState()->getWorldTransform(temp);\n\n playerMin = temp.getOrigin();\n\n playerMin.setY(playerMin.getY() - (physics->height_));\n\n \/\/std::cout << \"playerMin: \" << playerMin.getY() << std::endl;\n\n btVector3 btTo(playerMin.x(), -500.0f, playerMin.z());\n\n btCollisionWorld::ClosestRayResultCallback res(playerMin, btTo);\n\n \/\/btCollisionWorld::ClosestConvexResultCallback\n\n m_pWorld->rayTest(playerMin, btTo, res);\n\n res.m_flags |= btTriangleRaycastCallback::kF_FilterBackfaces;\n\n res.m_flags |= btTriangleRaycastCallback::kF_KeepUnflippedNormal;\n\n\n if (res.hasHit()) {\n\n btTo = res.m_hitPointWorld;\n btVector3 normal = res.m_hitNormalWorld;\n\n btScalar p = playerMin.distance(btTo);\n\n \/\/sw::printMatVec(\"Collision, p: \", p);\n\n \/\/sw::printMatVec(\"Playermin: \", playerMin);\n\n \/\/std::cout << \"Distance to collision point: \" << p << std::endl;\n\n \/\/std::cout << \"p: \" << p << \" ,distance_to_bottom_: \" << player->distance_to_bottom_ << std::endl;\n\n if (p > 0.05 && std::abs(physics->body_->getLinearVelocity().getY()) > 0.0) {\n player->state_ = STATE_AIRBOURNE;\n } else {\n player->state_ = STATE_STANDING;\n }\n }\n }\n\n \/\/std::cout << \"Player speed: \" << physics->body_->getLinearVelocity().getY() << std::endl;\n }\n\n \/\/ Process pickup events generated this frame\n void processPickupEvents(ex::ComponentHandle<PhysicsComponent> physics) {\n\n pickup_events_.clear();\n\n glm::mat4 inverted_view = glm::inverse(view_);\n\n glm::vec4 lookAtInViewSpace(0, 0, -1,\n 1); \/\/ Forward vector (use 0, 0, -1 if you have a right-handed coordinate system)\n glm::vec4 lookAtInWorldSpaceTemp = lookAtInViewSpace * inverted_view; \/\/ Transform into world space.\n\n glm::vec3 lookAtInWorldSpace = glm::vec3(lookAtInWorldSpaceTemp);\n\n lookAtInWorldSpace = lookAtInWorldSpace * 1000.0f;\n\n \/\/ The player's position\n btTransform temp;\n physics->body_->getMotionState()->getWorldTransform(temp);\n btVector3 bt_out_origin = temp.getOrigin();\n\n \/\/ The ray's direction\n btVector3 bt_out_direction = sw::vec3_to_btVector3(lookAtInWorldSpace);\n\n printMatVec(\"View: \", view_);\n printMatVec(\"Origin: \", bt_out_origin);\n printMatVec(\"Direction\", bt_out_direction);\n\n btCollisionWorld::ClosestRayResultCallback RayCallback(bt_out_origin, bt_out_direction);\n RayCallback.m_flags |= btTriangleRaycastCallback::kF_FilterBackfaces;\n RayCallback.m_flags |= btTriangleRaycastCallback::kF_KeepUnflippedNormal;\n\n m_pWorld->rayTest(bt_out_origin, bt_out_direction, RayCallback);\n\n std::string message;\n\n \/\/ If the ray hit something, set the object's linear velocity and print its position\n if (RayCallback.hasHit()) {\n if(!is_lifting) {\n std::ostringstream oss;\n oss << \"hit\";\n btRigidBody *temp_body = (btRigidBody *) RayCallback.m_collisionObject->getUserPointer();\n \/\/temp_body->setLinearVelocity(btVector3(0.0f, 2.0f, 0.0f));\n btTransform transA, transB;\n bool useLinearReferenceFrameA = true;\n transA.setIdentity();\n transB.setIdentity();\n bt_out_direction.setY(0.5f);\n transB.setOrigin(bt_out_direction \/ 1000.f);\n cons = new btGeneric6DofConstraint(*temp_body, *physics->body_, transA,\n transB, useLinearReferenceFrameA);\n m_pWorld->addConstraint(cons);\n temp_body->setAngularFactor(0.f);\n temp_body->setActivationState(DISABLE_DEACTIVATION);\n is_lifting = true;\n }\n else{\n cons->getRigidBodyA().setAngularFactor(1.f);\n cons->getRigidBodyA().setActivationState(ACTIVE_TAG);\n cons->getRigidBodyA().removeConstraintRef(cons);\n cons->getRigidBodyB().removeConstraintRef(cons);\n m_pWorld->removeConstraint(cons);\n is_lifting = false;\n }\n \/\/ printMatVec(temp_body->getWorldTransform().getOrigin());\n } else {\n message = \"background\";\n }\n\n std::cout << message << std::endl;\n\n\n }\n\n void receive(const DimensionChangeInProgressEvent &dimChange) {\n if (last_dim_change_num == dimChange.NUM_)\n return;\n\n if (dimChange.completion_factor_ >= 0.5f) {\n dim_from_ = dimChange.dim_from_;\n last_dim_change_num = dimChange.NUM_;\n\n \/\/ The dimension change has occurred\n will_update_current_bodies_ = true;\n }\n }\n\n\n void receive(const DebugdrawerEvent &debugdraw) {\n m_debugMode = debugdraw.debugMode_;\n }\n\n void receive(const ProjectionViewEvent &proj_view_event) {\n proj_view_events_.push_back(proj_view_event);\n }\n\n\n void receive(const PickUpObjectEvent &pickUpObjectEvent) {\n pickup_events_.push_back(pickUpObjectEvent);\n }\n\n void receive(const GravityChangeEvent &gravityChangeEvent){\n if (gravityChangeEvent.gravityChange_){\n for (int n=0;n<m_pWorld->getCollisionObjectArray().size();n++) {\n m_pWorld->getCollisionObjectArray().at(n)->setActivationState(DISABLE_DEACTIVATION);\n }\n m_pWorld->setGravity(btVector3(0.f,0.1f,0.f));\n }\n else{\n for (int n=0;n<m_pWorld->getCollisionObjectArray().size();n++) {\n m_pWorld->getCollisionObjectArray().at(n)->setActivationState(ACTIVE_TAG);\n }\n m_pWorld->setGravity(btVector3(0.f,-10.,0.f));\n }\n }\n\n private:\n btBroadphaseInterface *m_pBroadphase;\n\n btCollisionDispatcher *m_pDispatcher;\n btSequentialImpulseConstraintSolver *m_pSolver;\n btDefaultCollisionConfiguration *m_pCollisionConfiguration;\n btDynamicsWorld *m_pWorld;\n\n MyDebugDrawer *debugDrawer_;\n\n std::vector<PickUpObjectEvent> pickup_events_;\n std::vector<ProjectionViewEvent> proj_view_events_;\n\n glm::mat4 camera_projection_;\n glm::mat4 view_;\n\n\n bool m_debugMode = false;\n\n bool is_lifting = false;\n btGeneric6DofConstraint *cons;\n\n\n \/* DIMENSION CHANGE *\/\n Dim dim_from_;\n bool will_update_current_bodies_;\n int last_dim_change_num;\n\n\n };\n\n}<commit_msg>fix: can't pick up static objects or yourself<commit_after>\/\/\n\/\/ Created by Adrian Palmquist on 15-04-28.\n\/\/\n\n#pragma once\n\n#include <BulletCollision\/NarrowPhaseCollision\/btRaycastCallback.h>\n#include <events\/DebugdrawerEvent.hpp>\n#include <events\/GravityChangeEvent.hpp>\n#include \"entityx\/entityx.h\"\n#include \"btBulletDynamicsCommon.h\"\n#include \"components\/PhysicsComponent.hpp\"\n#include \"physics\/MyDebugDrawer.hpp\"\n#include \"HelperFunctions.hpp\"\n\n#include \"events\/ProjectionViewEvent.hpp\"\n#include \"events\/PickUpObjectEvent.hpp\"\n\nnamespace ex = entityx;\n\nnamespace sw {\n\n class PhysicsSystem : public ex::System<PhysicsSystem>, public ex::Receiver<PhysicsSystem> {\n public:\n\n PhysicsSystem() {\n \/\/ create the collision configuration\n m_pCollisionConfiguration = new btDefaultCollisionConfiguration();\n\n \/\/ Default collision dispatcher\n m_pDispatcher = new btCollisionDispatcher(m_pCollisionConfiguration);\n\n \/\/ create the broadphase\n m_pBroadphase = new btDbvtBroadphase();\n\n \/\/ create the constraint solver\n m_pSolver = new btSequentialImpulseConstraintSolver();\n\n\n \/\/ create the world\n m_pWorld = new btDiscreteDynamicsWorld(m_pDispatcher, m_pBroadphase, m_pSolver, m_pCollisionConfiguration);\n\n m_pWorld->setGravity(btVector3(0, -10, 0));\n\n debugDrawer_ = new MyDebugDrawer();\n m_pWorld->setDebugDrawer(debugDrawer_);\n\n m_pWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_MAX_DEBUG_DRAW_MODE);\n\n will_update_current_bodies_ = false;\n dim_from_ = Dim::DIMENSION_ONE;\n last_dim_change_num = -1;\n }\n\n\n void configure(ex::EventManager &events) override {\n events.subscribe<DebugdrawerEvent>(*this);\n events.subscribe<DimensionChangeInProgressEvent>(*this);\n events.subscribe<PickUpObjectEvent>(*this);\n events.subscribe<ProjectionViewEvent>(*this);\n events.subscribe<GravityChangeEvent>(*this);\n\n }\n\n\n void populateWorld(ex::EntityManager &es) {\n auto physics = ex::ComponentHandle<PhysicsComponent>();\n auto dimension = ex::ComponentHandle<DimensionComponent>();\n\n for (ex::Entity e : es.entities_with_components(physics, dimension)) {\n Dim d = dimension->dimension_;\n\n std::cout << \"populateworld\" << std::endl;\n \/*\n std::cout << \"Group: \" << physics->group_ << std::endl;\n std::cout << \"Mask: \" << physics->mask_ << std::endl;\n std::cout << \"Previous flags: \" << physics->body_->getCollisionFlags() << std::endl;\n *\/\n std::cout << \" dimension: \" << d << \"\\n\";\n physics->body_->activate(true);\n\n m_pWorld->addRigidBody(physics->body_, d, d);\n }\n\n auto player = ex::ComponentHandle<PlayerComponent>();\n for (ex::Entity e : es.entities_with_components(player, physics)) {\n\n btTransform temp;\n physics->body_->getMotionState()->getWorldTransform(temp);\n btVector3 playerMin = temp.getOrigin();\n btVector3 btTo(playerMin.x(), -500.0f, playerMin.z());\n\n btCollisionWorld::ClosestRayResultCallback res(playerMin, btTo);\n\n m_pWorld->rayTest(playerMin, btTo, res);\n\n if (res.hasHit()) {\n\n\n btTo = res.m_hitPointWorld;\n btScalar p = playerMin.distance(btTo);\n\n player->distance_to_bottom_ = physics->height_;\n\n std::cout << \"Distance to bottom: \" << p << std::endl;\n\n\n }\n\n }\n }\n\n\n ~PhysicsSystem() {\n delete m_pWorld;\n delete debugDrawer_;\n delete m_pBroadphase;\n delete m_pDispatcher;\n delete m_pCollisionConfiguration;\n delete m_pSolver;\n }\n\n\n void update(entityx::EntityManager &entityManager, entityx::EventManager &eventManager, entityx::TimeDelta dt) {\n if (will_update_current_bodies_) {\n \/*std::cout << \"Will update bitches\\n\";\n auto dimension = ex::ComponentHandle<DimensionComponent>();\n auto physics = ex::ComponentHandle<PhysicsComponent>();\n for (ex::Entity e : entityManager.entities_with_components(dimension, physics)) {\n Dim d = dimension->dimension_;\n if (d == Dim::DIMENSION_BOTH)\n continue;\n if (d == dim_from_) {\n \/\/m_pWorld->removeRigidBody(physics->body_);\n physics->body_->setActivationState(ISLAND_SLEEPING);\n \/\/physics->body_->setActivationState(DISABLE_SIMULATION);\n std::cout << \"Disabled a bitch\\n\";\n }\n else {\n \/\/m_pWorld->addRigidBody(physics->body_);\n \/\/physics->body_->setActivationState(DISABLE_DEACTIVATION);\n physics->body_->activate(true);\n std::cout << \"Enabled a bitch\\n\";\n }\n }*\/\n auto physics = ex::ComponentHandle<PhysicsComponent>();\n auto dimension = ex::ComponentHandle<DimensionComponent>();\n auto player = ex::ComponentHandle<PlayerComponent>();\n\n for (ex::Entity p : entityManager.entities_with_components(player, physics, dimension)) {\n Dim d = dimension->dimension_;\n m_pWorld->removeRigidBody(physics->body_);\n m_pWorld->addRigidBody(physics->body_, d, d);\n std::cout << \"Current player dimension is: \" << d << \"\\n\";\n }\n\n will_update_current_bodies_ = false;\n }\n\n\n m_pWorld->stepSimulation(dt);\n\n if (m_debugMode) {\n m_pWorld->debugDrawWorld();\n debugDrawer_->drawLines();\n\n }\n\n\n auto player = ex::ComponentHandle<PlayerComponent>();\n auto physics = ex::ComponentHandle<PhysicsComponent>();\n\n for (ex::Entity e : entityManager.entities_with_components(player, physics)) {\n\n if (!proj_view_events_.empty()) {\n view_ = proj_view_events_.front().view_matrix_;\n camera_projection_ = proj_view_events_.front().projection_matrix_;\n\n proj_view_events_.clear();\n }\n\n if (!pickup_events_.empty()) {\n processPickupEvents(physics);\n }\n\n btTransform temp;\n btVector3 tempVec;\n btVector3 playerMin;\n\n physics->body_->getMotionState()->getWorldTransform(temp);\n\n playerMin = temp.getOrigin();\n\n playerMin.setY(playerMin.getY() - (physics->height_));\n\n \/\/std::cout << \"playerMin: \" << playerMin.getY() << std::endl;\n\n btVector3 btTo(playerMin.x(), -500.0f, playerMin.z());\n\n btCollisionWorld::ClosestRayResultCallback res(playerMin, btTo);\n\n \/\/btCollisionWorld::ClosestConvexResultCallback\n\n m_pWorld->rayTest(playerMin, btTo, res);\n\n res.m_flags |= btTriangleRaycastCallback::kF_FilterBackfaces;\n\n res.m_flags |= btTriangleRaycastCallback::kF_KeepUnflippedNormal;\n\n\n if (res.hasHit()) {\n\n btTo = res.m_hitPointWorld;\n btVector3 normal = res.m_hitNormalWorld;\n\n btScalar p = playerMin.distance(btTo);\n\n \/\/sw::printMatVec(\"Collision, p: \", p);\n\n \/\/sw::printMatVec(\"Playermin: \", playerMin);\n\n \/\/std::cout << \"Distance to collision point: \" << p << std::endl;\n\n \/\/std::cout << \"p: \" << p << \" ,distance_to_bottom_: \" << player->distance_to_bottom_ << std::endl;\n\n if (p > 0.05 && std::abs(physics->body_->getLinearVelocity().getY()) > 0.0) {\n player->state_ = STATE_AIRBOURNE;\n } else {\n player->state_ = STATE_STANDING;\n }\n }\n }\n\n \/\/std::cout << \"Player speed: \" << physics->body_->getLinearVelocity().getY() << std::endl;\n }\n\n \/\/ Process pickup events generated this frame\n void processPickupEvents(ex::ComponentHandle<PhysicsComponent> physics) {\n\n pickup_events_.clear();\n\n glm::mat4 inverted_view = glm::inverse(view_);\n\n glm::vec4 lookAtInViewSpace(0, 0, -1,\n 1); \/\/ Forward vector (use 0, 0, -1 if you have a right-handed coordinate system)\n glm::vec4 lookAtInWorldSpaceTemp = lookAtInViewSpace * inverted_view; \/\/ Transform into world space.\n\n glm::vec3 lookAtInWorldSpace = glm::vec3(lookAtInWorldSpaceTemp);\n\n lookAtInWorldSpace = lookAtInWorldSpace * 1000.0f;\n\n \/\/ The player's position\n btTransform temp;\n physics->body_->getMotionState()->getWorldTransform(temp);\n btVector3 bt_out_origin = temp.getOrigin();\n\n \/\/ The ray's direction\n btVector3 bt_out_direction = sw::vec3_to_btVector3(lookAtInWorldSpace);\n\n printMatVec(\"View: \", view_);\n printMatVec(\"Origin: \", bt_out_origin);\n printMatVec(\"Direction\", bt_out_direction);\n\n btCollisionWorld::ClosestRayResultCallback RayCallback(bt_out_origin, bt_out_direction);\n RayCallback.m_flags |= btTriangleRaycastCallback::kF_FilterBackfaces;\n RayCallback.m_flags |= btTriangleRaycastCallback::kF_KeepUnflippedNormal;\n\n m_pWorld->rayTest(bt_out_origin, bt_out_direction, RayCallback);\n\n std::string message;\n\n \/\/ If the ray hit something, set the object's linear velocity and print its position\n if (RayCallback.hasHit()) {\n btRigidBody *temp_body = (btRigidBody *) RayCallback.m_collisionObject->getUserPointer();\n int colFlag = temp_body->getCollisionFlags();\n int angFac = temp_body->getAngularFactor().getX();\n if(!is_lifting && colFlag != 1 && angFac != 0.f) {\n std::ostringstream oss;\n oss << \"hit\";\n btTransform transA, transB;\n bool useLinearReferenceFrameA = true;\n transA.setIdentity();\n transB.setIdentity();\n bt_out_direction.setY(0.5f);\n transB.setOrigin(bt_out_direction \/ 1000.f);\n cons = new btGeneric6DofConstraint(*temp_body, *physics->body_, transA,\n transB, useLinearReferenceFrameA);\n m_pWorld->addConstraint(cons);\n temp_body->setAngularFactor(0.f);\n temp_body->setActivationState(DISABLE_DEACTIVATION);\n is_lifting = true;\n return;\n }\n \/\/ printMatVec(temp_body->getWorldTransform().getOrigin());\n } else {\n message = \"background\";\n }\n if (is_lifting) {\n cons->getRigidBodyA().setAngularFactor(1.f);\n cons->getRigidBodyA().setActivationState(ACTIVE_TAG);\n cons->getRigidBodyA().removeConstraintRef(cons);\n cons->getRigidBodyB().removeConstraintRef(cons);\n m_pWorld->removeConstraint(cons);\n delete cons;\n is_lifting = false;\n }\n\n std::cout << message << std::endl;\n\n\n }\n\n void receive(const DimensionChangeInProgressEvent &dimChange) {\n if (last_dim_change_num == dimChange.NUM_)\n return;\n\n if (dimChange.completion_factor_ >= 0.5f) {\n dim_from_ = dimChange.dim_from_;\n last_dim_change_num = dimChange.NUM_;\n\n \/\/ The dimension change has occurred\n will_update_current_bodies_ = true;\n }\n }\n\n\n void receive(const DebugdrawerEvent &debugdraw) {\n m_debugMode = debugdraw.debugMode_;\n }\n\n void receive(const ProjectionViewEvent &proj_view_event) {\n proj_view_events_.push_back(proj_view_event);\n }\n\n\n void receive(const PickUpObjectEvent &pickUpObjectEvent) {\n pickup_events_.push_back(pickUpObjectEvent);\n }\n\n void receive(const GravityChangeEvent &gravityChangeEvent){\n if (gravityChangeEvent.gravityChange_){\n for (int n=0;n<m_pWorld->getCollisionObjectArray().size();n++) {\n m_pWorld->getCollisionObjectArray().at(n)->setActivationState(DISABLE_DEACTIVATION);\n }\n m_pWorld->setGravity(btVector3(0.f,0.1f,0.f));\n }\n else{\n for (int n=0;n<m_pWorld->getCollisionObjectArray().size();n++) {\n m_pWorld->getCollisionObjectArray().at(n)->setActivationState(ACTIVE_TAG);\n }\n m_pWorld->setGravity(btVector3(0.f,-10.,0.f));\n }\n }\n\n private:\n btBroadphaseInterface *m_pBroadphase;\n\n btCollisionDispatcher *m_pDispatcher;\n btSequentialImpulseConstraintSolver *m_pSolver;\n btDefaultCollisionConfiguration *m_pCollisionConfiguration;\n btDynamicsWorld *m_pWorld;\n\n MyDebugDrawer *debugDrawer_;\n\n std::vector<PickUpObjectEvent> pickup_events_;\n std::vector<ProjectionViewEvent> proj_view_events_;\n\n glm::mat4 camera_projection_;\n glm::mat4 view_;\n\n\n bool m_debugMode = false;\n\n bool is_lifting = false;\n btGeneric6DofConstraint *cons;\n\n\n \/* DIMENSION CHANGE *\/\n Dim dim_from_;\n bool will_update_current_bodies_;\n int last_dim_change_num;\n\n\n };\n\n}<|endoftext|>"} {"text":"<commit_before>#ifndef TWISTEDCPP_PROTOCOL_CORE\n#define TWISTEDCPP_PROTOCOL_CORE\n\n#include \"detail\/sockets.hpp\"\n\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/asio\/steady_timer.hpp>\n#include <boost\/optional.hpp>\n#include <boost\/asio\/spawn.hpp>\n#include <boost\/asio\/write.hpp>\n#include <boost\/ref.hpp>\n\n#ifndef NDEBUG\n#include <iostream>\n#endif\n\nnamespace twisted {\n\ntemplate <typename ChildProtocol, typename BufferType>\nclass protocol_core : public std::enable_shared_from_this<ChildProtocol> {\npublic:\n typedef detail::socket_base socket_type;\n typedef boost::asio::steady_timer timer_type;\n typedef boost::asio::io_service::strand strand_type;\n typedef BufferType buffer_type;\n typedef typename buffer_type::iterator buffer_iterator;\n typedef typename buffer_type::const_iterator const_buffer_iterator;\n\n protocol_core() = default;\n protocol_core(protocol_core&&) = default;\n protocol_core& operator=(protocol_core&&) = default;\n\n void set_socket(std::unique_ptr<socket_type> socket) {\n _socket = std::move(socket);\n _strand = boost::in_place(boost::ref(_socket->get_io_service()));\n }\n\n void run_protocol() {\n auto self = this_protocol().shared_from_this();\n boost::asio::spawn(*_strand,\n [this, self](boost::asio::yield_context yield) {\n _yield = boost::in_place(yield);\n\n try {\n _socket->do_handshake(*_yield);\n\n while (_socket->is_open()) {\n auto bytes_read =\n _socket->async_read_some(asio_buffer(), yield);\n this_protocol().on_message(\n buffer_begin(), std::next(buffer_begin(), bytes_read));\n }\n }\n catch (boost::system::system_error& connection_error) {\n handle_network_error(connection_error);\n }\n catch (...) {\n handle_user_error(std::current_exception());\n }\n });\n }\n\n template <typename Iter>\n void send_message(Iter begin, Iter end) {\n _socket->async_write(\n boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);\n }\n\n void send_buffers(const std::array<boost::asio::const_buffer, 2>& buffers) {\n _socket->async_write(buffers, *_yield);\n }\n\n \/*\n * @brief default on_disconnect implementation; does nothing\n *\/\n void on_disconnect() {}\n\n \/*\n * @brief default on_error implementation; swallows everything\n *\/\n void on_error(std::exception_ptr eptr) {\n try {\n std::rethrow_exception(eptr);\n }\n catch (const std::exception& excep) {\n print_exception_what(excep);\n }\n }\n\n void lose_connection() { _socket->close(); }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n ChildProtocol& this_protocol() {\n return *static_cast<ChildProtocol*>(this);\n }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n const ChildProtocol& this_protocol() const {\n return *static_cast<ChildProtocol*>(this);\n }\n\nprivate:\n#ifdef NDEBUG\n void handle_network_error(boost::system::system_error&) {\n#else\n void handle_network_error(boost::system::system_error& connection_error) {\n print_connection_error(connection_error);\n#endif\n this_protocol().on_disconnect();\n }\n\n void handle_user_error(const std::exception_ptr& excep) {\n this_protocol().on_error(excep);\n }\n\n void print_connection_error(\n const boost::system::system_error& connection_error) const {\n std::cerr << \"Client disconnected with code \" << connection_error.what()\n << std::endl;\n }\n\n void print_exception_what(const std::exception& excep) {\n std::cerr << \"Killing connection, exception in client handler: \"\n << excep.what() << std::endl;\n }\n\n buffer_iterator buffer_begin() {\n return this_protocol().read_buffer().begin();\n }\n\n buffer_iterator buffer_begin() const {\n return this_protocol().read_buffer().begin();\n }\n\n buffer_iterator buffer_end() { return this_protocol().read_buffer().end(); }\n\n buffer_iterator buffer_end() const {\n return this_protocol().read_buffer().end();\n }\n\n boost::asio::mutable_buffers_1 asio_buffer() {\n return boost::asio::buffer(&*buffer_begin(),\n std::distance(buffer_begin(), buffer_end()));\n }\n\nprivate:\n boost::optional<boost::asio::yield_context> _yield;\n std::unique_ptr<socket_type> _socket;\n boost::optional<strand_type> _strand;\n};\n\n} \/\/ namespace twisted\n\n#endif\n<commit_msg>added wait_for function to protocol_core<commit_after>#ifndef TWISTEDCPP_PROTOCOL_CORE\n#define TWISTEDCPP_PROTOCOL_CORE\n\n#include \"detail\/sockets.hpp\"\n\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/asio\/steady_timer.hpp>\n#include <boost\/optional.hpp>\n#include <boost\/asio\/spawn.hpp>\n#include <boost\/asio\/write.hpp>\n#include <boost\/asio\/high_resolution_timer.hpp>\n#include <boost\/ref.hpp>\n\n#ifndef NDEBUG\n#include <iostream>\n#endif\n\nnamespace twisted {\n\ntemplate <typename ChildProtocol, typename BufferType>\nclass protocol_core : public std::enable_shared_from_this<ChildProtocol> {\npublic:\n typedef detail::socket_base socket_type;\n typedef boost::asio::steady_timer timer_type;\n typedef boost::asio::io_service::strand strand_type;\n typedef BufferType buffer_type;\n typedef typename buffer_type::iterator buffer_iterator;\n typedef typename buffer_type::const_iterator const_buffer_iterator;\n\n protocol_core() = default;\n protocol_core(protocol_core&&) = default;\n protocol_core& operator=(protocol_core&&) = default;\n\n void set_socket(std::unique_ptr<socket_type> socket) {\n _socket = std::move(socket);\n _strand = boost::in_place(boost::ref(_socket->get_io_service()));\n }\n\n void run_protocol() {\n auto self = this_protocol().shared_from_this();\n boost::asio::spawn(*_strand,\n [this, self](boost::asio::yield_context yield) {\n _yield = boost::in_place(yield);\n\n try {\n _socket->do_handshake(*_yield);\n\n while (_socket->is_open()) {\n auto bytes_read =\n _socket->async_read_some(asio_buffer(), yield);\n this_protocol().on_message(\n buffer_begin(), std::next(buffer_begin(), bytes_read));\n }\n }\n catch (boost::system::system_error& connection_error) {\n handle_network_error(connection_error);\n }\n catch (...) {\n handle_user_error(std::current_exception());\n }\n });\n }\n\n template <typename Duration>\n void wait_for(const Duration& duration) const {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(*_yield);\n }\n\n template <typename Iter>\n void send_message(Iter begin, Iter end) {\n _socket->async_write(\n boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);\n }\n\n void send_buffers(const std::array<boost::asio::const_buffer, 2>& buffers) {\n _socket->async_write(buffers, *_yield);\n }\n\n \/*\n * @brief default on_disconnect implementation; does nothing\n *\/\n void on_disconnect() {}\n\n \/*\n * @brief default on_error implementation; swallows everything\n *\/\n void on_error(std::exception_ptr eptr) {\n try {\n std::rethrow_exception(eptr);\n }\n catch (const std::exception& excep) {\n print_exception_what(excep);\n }\n }\n\n void lose_connection() { _socket->close(); }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n ChildProtocol& this_protocol() {\n return *static_cast<ChildProtocol*>(this);\n }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n const ChildProtocol& this_protocol() const {\n return *static_cast<ChildProtocol*>(this);\n }\n\nprivate:\n#ifdef NDEBUG\n void handle_network_error(boost::system::system_error&) {\n#else\n void handle_network_error(boost::system::system_error& connection_error) {\n print_connection_error(connection_error);\n#endif\n this_protocol().on_disconnect();\n }\n\n void handle_user_error(const std::exception_ptr& excep) {\n this_protocol().on_error(excep);\n }\n\n void print_connection_error(\n const boost::system::system_error& connection_error) const {\n std::cerr << \"Client disconnected with code \" << connection_error.what()\n << std::endl;\n }\n\n void print_exception_what(const std::exception& excep) {\n std::cerr << \"Killing connection, exception in client handler: \"\n << excep.what() << std::endl;\n }\n\n buffer_iterator buffer_begin() {\n return this_protocol().read_buffer().begin();\n }\n\n buffer_iterator buffer_begin() const {\n return this_protocol().read_buffer().begin();\n }\n\n buffer_iterator buffer_end() { return this_protocol().read_buffer().end(); }\n\n buffer_iterator buffer_end() const {\n return this_protocol().read_buffer().end();\n }\n\n boost::asio::mutable_buffers_1 asio_buffer() {\n return boost::asio::buffer(&*buffer_begin(),\n std::distance(buffer_begin(), buffer_end()));\n }\n\nprivate:\n boost::optional<boost::asio::yield_context> _yield;\n std::unique_ptr<socket_type> _socket;\n boost::optional<strand_type> _strand;\n};\n\n} \/\/ namespace twisted\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"estimators.hpp\"\n\nnamespace mfem\n{\n\nvoid ZienkiewiczZhuEstimator::ComputeEstimates()\n{\n flux_space->Update(false);\n \/\/ In parallel, 'flux' can be a GridFunction, as long as 'flux_space' is a\n \/\/ ParFiniteElementSpace and 'solution' is a ParGridFunction.\n GridFunction flux(flux_space);\n\n if (!anisotropic) { aniso_flags.SetSize(0); }\n total_error = ZZErrorEstimator(*integ, *solution, flux, error_estimates,\n anisotropic ? &aniso_flags : NULL,\n flux_averaging,\n with_coeff);\n\n current_sequence = solution->FESpace()->GetMesh()->GetSequence();\n}\n\n\n#ifdef MFEM_USE_MPI\n\nvoid L2ZienkiewiczZhuEstimator::ComputeEstimates()\n{\n flux_space->Update(false);\n smooth_flux_space->Update(false);\n\n \/\/ TODO: move these parameters in the class, and add Set* methods.\n const double solver_tol = 1e-12;\n const int solver_max_it = 200;\n total_error = L2ZZErrorEstimator(*integ, *solution, *smooth_flux_space,\n *flux_space, error_estimates,\n local_norm_p, solver_tol, solver_max_it);\n\n current_sequence = solution->FESpace()->GetMesh()->GetSequence();\n}\n\nvoid KellyErrorEstimator::ComputeEstimates()\n{\n \/\/ Remarks:\n \/\/ For some context you may have to consult the documentation of\n \/\/ the FaceInfo class [1]. Also, the FaceElementTransformations\n \/\/ documentation [2] may be helpful to grasp what is going on. Note\n \/\/ that the FaceElementTransformations also works in the non-\n \/\/ conforming case to transfer the gauss points from the slave to\n \/\/ the master element.\n \/\/ [1]\n \/\/ https:\/\/github.com\/mfem\/mfem\/blob\/02d0bfe9c18ce049c3c93a6a4208080fcfc96991\/mesh\/mesh.hpp#L94\n \/\/ [2]\n \/\/ https:\/\/github.com\/mfem\/mfem\/blob\/02d0bfe9c18ce049c3c93a6a4208080fcfc96991\/fem\/eltrans.hpp#L435\n flux_space->Update(false);\n\n auto xfes = solution->ParFESpace();\n auto pmesh = xfes->GetParMesh();\n\n this->error_estimates.SetSize(xfes->GetNE());\n this->error_estimates = 0.0;\n\n \/\/ 1. Compute fluxes in discontinuous space\n ParGridFunction flux(flux_space);\n flux = 0.0;\n\n Array<int> xdofs, fdofs;\n Vector el_x, el_f;\n for (int e = 0; e < xfes->GetNE(); e++)\n {\n auto attr = xfes->GetAttribute(e);\n if (attributes.Size() && attributes.Find(attr) == -1)\n {\n continue;\n }\n\n xfes->GetElementVDofs(e, xdofs);\n solution->GetSubVector(xdofs, el_x);\n\n ElementTransformation* Transf = xfes->GetElementTransformation(e);\n flux_integrator->ComputeElementFlux(*xfes->GetFE(e), *Transf, el_x,\n *flux_space->GetFE(e), el_f, true);\n\n flux_space->GetElementVDofs(e, fdofs);\n flux.AddElementVector(fdofs, el_f);\n }\n\n \/\/ 2. Add error contribution from local interior faces\n auto int_rules = IntegrationRules();\n for (int f = 0; f < pmesh->GetNumFaces(); f++)\n {\n auto FT = pmesh->GetFaceElementTransformations(f);\n\n const auto int_rule =\n int_rules.Get(FT->FaceGeom, 2 * xfes->GetFaceOrder(f));\n const auto nip = int_rule.GetNPoints();\n\n if (pmesh->FaceIsInterior(f))\n {\n int Inf1, Inf2, NCFace;\n pmesh->GetFaceInfos(f, &Inf1, &Inf2, &NCFace);\n\n \/\/ Convention\n \/\/ * Conforming face: Face side with smaller element id handles\n \/\/ the integration\n \/\/ * Non-conforming face: The slave handles the integration.\n \/\/ See FaceInfo documentation for details.\n bool isNCSlave = FT->Elem2No >= 0 && NCFace >= 0;\n bool isConforming = FT->Elem2No >= 0 && NCFace == -1;\n if ((FT->Elem1No < FT->Elem2No && isConforming) || isNCSlave)\n {\n if (attributes.Size() &&\n (attributes.Find(FT->Elem1->Attribute) == -1\n || attributes.Find(FT->Elem2->Attribute) == -1))\n {\n continue;\n }\n\n IntegrationRule eir;\n Vector jumps(nip);\n\n \/\/ Integral over local half face on the side of e₁\n \/\/ i.e. the numerical integration of ∫ flux ⋅ n dS₁\n for (int i = 0; i < nip; i++)\n {\n \/\/ Evaluate flux at IP\n auto fip = int_rule.IntPoint(i);\n IntegrationPoint ip;\n FT->Loc1.Transform(fip, ip);\n\n Vector val(flux_space->GetVDim());\n flux.GetVectorValue(FT->Elem1No, ip, val);\n\n \/\/ And build scalar product with normal\n Vector normal(pmesh->SpaceDimension());\n FT->Face->SetIntPoint(&fip);\n if (pmesh->Dimension() == pmesh->SpaceDimension())\n {\n CalcOrtho(FT->Face->Jacobian(), normal);\n }\n else\n {\n Vector ref_normal(pmesh->Dimension());\n FT->Loc1.Transf.SetIntPoint(&fip);\n CalcOrtho(FT->Loc1.Transf.Jacobian(), ref_normal);\n auto &e1 = FT->GetElement1Transformation();\n e1.AdjugateJacobian().MultTranspose(ref_normal, normal);\n normal \/= e1.Weight();\n }\n jumps(i) = val * normal * fip.weight * FT->Face->Weight();\n }\n\n \/\/ Subtract integral over half face of e₂\n \/\/ i.e. the numerical integration of ∫ flux ⋅ n dS₂\n for (int i = 0; i < nip; i++)\n {\n \/\/ Evaluate flux vector at IP\n auto fip = int_rule.IntPoint(i);\n IntegrationPoint ip;\n FT->Loc2.Transform(fip, ip);\n\n Vector val(flux_space->GetVDim());\n flux.GetVectorValue(FT->Elem2No, ip, val);\n\n \/\/ And build scalar product with normal\n Vector normal(pmesh->SpaceDimension());\n FT->Face->SetIntPoint(&fip);\n if (pmesh->Dimension() == pmesh->SpaceDimension())\n {\n CalcOrtho(FT->Face->Jacobian(), normal);\n }\n else\n {\n Vector ref_normal(pmesh->Dimension());\n FT->Loc1.Transf.SetIntPoint(&fip);\n CalcOrtho(FT->Loc1.Transf.Jacobian(), ref_normal);\n auto &e1 = FT->GetElement1Transformation();\n e1.AdjugateJacobian().MultTranspose(ref_normal, normal);\n normal \/= e1.Weight();\n }\n normal.Neg();\n\n jumps(i) -= val * normal * fip.weight * FT->Face->Weight();\n }\n\n \/\/ Finalize \"local\" L₂ contribution\n for (int i = 0; i < nip; i++)\n {\n jumps(i) *= jumps(i);\n }\n auto h_k_face = compute_face_coefficient(pmesh, f, false);\n double jump_integral = h_k_face*jumps.Sum();\n\n \/\/ A local face is shared between two local elements, so we\n \/\/ can get away with integrating the jump only once and add\n \/\/ it to both elements. To minimize communication, the jump\n \/\/ of shared faces is computed locally by each process.\n error_estimates(FT->Elem1No) += jump_integral;\n error_estimates(FT->Elem2No) += jump_integral;\n }\n }\n }\n\n \/\/ 3. Add error contribution from shared interior faces\n \/\/ Synchronize face data.\n flux.ExchangeFaceNbrData();\n\n for (int sf = 0; sf < pmesh->GetNSharedFaces(); sf++)\n {\n auto FT = pmesh->GetSharedFaceTransformations(sf, true);\n if (attributes.Size() &&\n (attributes.Find(FT->Elem1->Attribute) == -1\n || attributes.Find(FT->Elem2->Attribute) == -1))\n {\n continue;\n }\n\n const auto int_rule =\n int_rules.Get(FT->FaceGeom, 2 * xfes->GetFaceOrder(0));\n const auto nip = int_rule.GetNPoints();\n\n IntegrationRule eir;\n Vector jumps(nip);\n\n \/\/ Integral over local half face on the side of e₁\n \/\/ i.e. the numerical integration of ∫ flux ⋅ n dS₁\n for (int i = 0; i < nip; i++)\n {\n \/\/ Evaluate flux vector at integration point\n auto fip = int_rule.IntPoint(i);\n IntegrationPoint ip;\n FT->Loc1.Transform(fip, ip);\n\n Vector val(flux_space->GetVDim());\n flux.GetVectorValue(FT->Elem1No, ip, val);\n\n Vector normal(pmesh->SpaceDimension());\n FT->Face->SetIntPoint(&fip);\n if (pmesh->Dimension() == pmesh->SpaceDimension())\n {\n CalcOrtho(FT->Face->Jacobian(), normal);\n }\n else\n {\n Vector ref_normal(pmesh->Dimension());\n FT->Loc1.Transf.SetIntPoint(&fip);\n CalcOrtho(FT->Loc1.Transf.Jacobian(), ref_normal);\n auto &e1 = FT->GetElement1Transformation();\n e1.AdjugateJacobian().MultTranspose(ref_normal, normal);\n normal \/= e1.Weight();\n }\n\n jumps(i) = val * normal * fip.weight * FT->Face->Weight();\n }\n\n \/\/ Subtract integral over non-local half face of e₂\n \/\/ i.e. the numerical integration of ∫ flux ⋅ n dS₂\n for (int i = 0; i < nip; i++)\n {\n \/\/ Evaluate flux vector at integration point\n auto fip = int_rule.IntPoint(i);\n IntegrationPoint ip;\n FT->Loc2.Transform(fip, ip);\n\n Vector val(flux_space->GetVDim());\n flux.GetVectorValue(FT->Elem2No, ip, val);\n\n \/\/ Evaluate gauss point\n Vector normal(pmesh->SpaceDimension());\n FT->Face->SetIntPoint(&fip);\n if (pmesh->Dimension() == pmesh->SpaceDimension())\n {\n CalcOrtho(FT->Face->Jacobian(), normal);\n }\n else\n {\n Vector ref_normal(pmesh->Dimension());\n CalcOrtho(FT->Loc1.Transf.Jacobian(), ref_normal);\n auto &e1 = FT->GetElement1Transformation();\n e1.AdjugateJacobian().MultTranspose(ref_normal, normal);\n normal \/= e1.Weight();\n }\n normal.Neg();\n\n jumps(i) -= val * normal * fip.weight * FT->Face->Weight();\n }\n\n \/\/ Finalize \"local\" L₂ contribution\n for (int i = 0; i < nip; i++)\n {\n jumps(i) *= jumps(i);\n }\n auto h_k_face = compute_face_coefficient(pmesh, sf, true);\n double jump_integral = h_k_face*jumps.Sum();\n\n error_estimates(FT->Elem1No) += jump_integral;\n \/\/ We skip \"error_estimates(FT->Elem2No) += jump_integral\"\n \/\/ because the error is stored on the remote process and\n \/\/ recomputed there.\n }\n\n \/\/ Finalize element errors\n for (int e = 0; e < xfes->GetNE(); e++)\n {\n auto factor = compute_element_coefficient(pmesh, e);\n \/\/ The sqrt belongs to the norm and hₑ to the indicator.\n error_estimates(e) = sqrt(factor * error_estimates(e));\n }\n\n current_sequence = solution->FESpace()->GetMesh()->GetSequence();\n\n \/\/ Finish by computing the global error.\n double process_local_error = error_estimates.Sum();\n MPI_Allreduce(&process_local_error, &total_error, 1, MPI_DOUBLE,\n MPI_SUM, xfes->GetComm());\n}\n\n#endif \/\/ MFEM_USE_MPI\n\nvoid LpErrorEstimator::ComputeEstimates()\n{\n MFEM_VERIFY(coef != NULL || vcoef != NULL,\n \"LpErrorEstimator has no coefficient! Call SetCoef first.\");\n\n error_estimates.SetSize(sol->FESpace()->GetMesh()->GetNE());\n if (coef)\n {\n sol->ComputeElementLpErrors(local_norm_p, *coef, error_estimates);\n }\n else\n {\n sol->ComputeElementLpErrors(local_norm_p, *vcoef, error_estimates);\n }\n current_sequence = sol->FESpace()->GetMesh()->GetSequence();\n}\n\n} \/\/ namespace mfem\n<commit_msg>Add error message.<commit_after>\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"estimators.hpp\"\n\nnamespace mfem\n{\n\nvoid ZienkiewiczZhuEstimator::ComputeEstimates()\n{\n flux_space->Update(false);\n \/\/ In parallel, 'flux' can be a GridFunction, as long as 'flux_space' is a\n \/\/ ParFiniteElementSpace and 'solution' is a ParGridFunction.\n GridFunction flux(flux_space);\n\n if (!anisotropic) { aniso_flags.SetSize(0); }\n total_error = ZZErrorEstimator(*integ, *solution, flux, error_estimates,\n anisotropic ? &aniso_flags : NULL,\n flux_averaging,\n with_coeff);\n\n current_sequence = solution->FESpace()->GetMesh()->GetSequence();\n}\n\n\n#ifdef MFEM_USE_MPI\n\nvoid L2ZienkiewiczZhuEstimator::ComputeEstimates()\n{\n flux_space->Update(false);\n smooth_flux_space->Update(false);\n\n \/\/ TODO: move these parameters in the class, and add Set* methods.\n const double solver_tol = 1e-12;\n const int solver_max_it = 200;\n total_error = L2ZZErrorEstimator(*integ, *solution, *smooth_flux_space,\n *flux_space, error_estimates,\n local_norm_p, solver_tol, solver_max_it);\n\n current_sequence = solution->FESpace()->GetMesh()->GetSequence();\n}\n\nvoid KellyErrorEstimator::ComputeEstimates()\n{\n \/\/ Remarks:\n \/\/ For some context you may have to consult the documentation of\n \/\/ the FaceInfo class [1]. Also, the FaceElementTransformations\n \/\/ documentation [2] may be helpful to grasp what is going on. Note\n \/\/ that the FaceElementTransformations also works in the non-\n \/\/ conforming case to transfer the gauss points from the slave to\n \/\/ the master element.\n \/\/ [1]\n \/\/ https:\/\/github.com\/mfem\/mfem\/blob\/02d0bfe9c18ce049c3c93a6a4208080fcfc96991\/mesh\/mesh.hpp#L94\n \/\/ [2]\n \/\/ https:\/\/github.com\/mfem\/mfem\/blob\/02d0bfe9c18ce049c3c93a6a4208080fcfc96991\/fem\/eltrans.hpp#L435\n flux_space->Update(false);\n\n auto xfes = solution->ParFESpace();\n MFEM_ASSERT(xfes->GetVDim() == 1, \"Estimation for vector-valued problems not implemented yet.\");\n auto pmesh = xfes->GetParMesh();\n\n this->error_estimates.SetSize(xfes->GetNE());\n this->error_estimates = 0.0;\n\n \/\/ 1. Compute fluxes in discontinuous space\n ParGridFunction flux(flux_space);\n flux = 0.0;\n\n Array<int> xdofs, fdofs;\n Vector el_x, el_f;\n for (int e = 0; e < xfes->GetNE(); e++)\n {\n auto attr = xfes->GetAttribute(e);\n if (attributes.Size() && attributes.Find(attr) == -1)\n {\n continue;\n }\n\n xfes->GetElementVDofs(e, xdofs);\n solution->GetSubVector(xdofs, el_x);\n\n ElementTransformation* Transf = xfes->GetElementTransformation(e);\n flux_integrator->ComputeElementFlux(*xfes->GetFE(e), *Transf, el_x,\n *flux_space->GetFE(e), el_f, true);\n\n flux_space->GetElementVDofs(e, fdofs);\n flux.AddElementVector(fdofs, el_f);\n }\n\n \/\/ 2. Add error contribution from local interior faces\n auto int_rules = IntegrationRules();\n for (int f = 0; f < pmesh->GetNumFaces(); f++)\n {\n auto FT = pmesh->GetFaceElementTransformations(f);\n\n const auto int_rule =\n int_rules.Get(FT->FaceGeom, 2 * xfes->GetFaceOrder(f));\n const auto nip = int_rule.GetNPoints();\n\n if (pmesh->FaceIsInterior(f))\n {\n int Inf1, Inf2, NCFace;\n pmesh->GetFaceInfos(f, &Inf1, &Inf2, &NCFace);\n\n \/\/ Convention\n \/\/ * Conforming face: Face side with smaller element id handles\n \/\/ the integration\n \/\/ * Non-conforming face: The slave handles the integration.\n \/\/ See FaceInfo documentation for details.\n bool isNCSlave = FT->Elem2No >= 0 && NCFace >= 0;\n bool isConforming = FT->Elem2No >= 0 && NCFace == -1;\n if ((FT->Elem1No < FT->Elem2No && isConforming) || isNCSlave)\n {\n if (attributes.Size() &&\n (attributes.Find(FT->Elem1->Attribute) == -1\n || attributes.Find(FT->Elem2->Attribute) == -1))\n {\n continue;\n }\n\n IntegrationRule eir;\n Vector jumps(nip);\n\n \/\/ Integral over local half face on the side of e₁\n \/\/ i.e. the numerical integration of ∫ flux ⋅ n dS₁\n for (int i = 0; i < nip; i++)\n {\n \/\/ Evaluate flux at IP\n auto fip = int_rule.IntPoint(i);\n IntegrationPoint ip;\n FT->Loc1.Transform(fip, ip);\n\n Vector val(flux_space->GetVDim());\n flux.GetVectorValue(FT->Elem1No, ip, val);\n\n \/\/ And build scalar product with normal\n Vector normal(pmesh->SpaceDimension());\n FT->Face->SetIntPoint(&fip);\n if (pmesh->Dimension() == pmesh->SpaceDimension())\n {\n CalcOrtho(FT->Face->Jacobian(), normal);\n }\n else\n {\n Vector ref_normal(pmesh->Dimension());\n FT->Loc1.Transf.SetIntPoint(&fip);\n CalcOrtho(FT->Loc1.Transf.Jacobian(), ref_normal);\n auto &e1 = FT->GetElement1Transformation();\n e1.AdjugateJacobian().MultTranspose(ref_normal, normal);\n normal \/= e1.Weight();\n }\n jumps(i) = val * normal * fip.weight * FT->Face->Weight();\n }\n\n \/\/ Subtract integral over half face of e₂\n \/\/ i.e. the numerical integration of ∫ flux ⋅ n dS₂\n for (int i = 0; i < nip; i++)\n {\n \/\/ Evaluate flux vector at IP\n auto fip = int_rule.IntPoint(i);\n IntegrationPoint ip;\n FT->Loc2.Transform(fip, ip);\n\n Vector val(flux_space->GetVDim());\n flux.GetVectorValue(FT->Elem2No, ip, val);\n\n \/\/ And build scalar product with normal\n Vector normal(pmesh->SpaceDimension());\n FT->Face->SetIntPoint(&fip);\n if (pmesh->Dimension() == pmesh->SpaceDimension())\n {\n CalcOrtho(FT->Face->Jacobian(), normal);\n }\n else\n {\n Vector ref_normal(pmesh->Dimension());\n FT->Loc1.Transf.SetIntPoint(&fip);\n CalcOrtho(FT->Loc1.Transf.Jacobian(), ref_normal);\n auto &e1 = FT->GetElement1Transformation();\n e1.AdjugateJacobian().MultTranspose(ref_normal, normal);\n normal \/= e1.Weight();\n }\n normal.Neg();\n\n jumps(i) -= val * normal * fip.weight * FT->Face->Weight();\n }\n\n \/\/ Finalize \"local\" L₂ contribution\n for (int i = 0; i < nip; i++)\n {\n jumps(i) *= jumps(i);\n }\n auto h_k_face = compute_face_coefficient(pmesh, f, false);\n double jump_integral = h_k_face*jumps.Sum();\n\n \/\/ A local face is shared between two local elements, so we\n \/\/ can get away with integrating the jump only once and add\n \/\/ it to both elements. To minimize communication, the jump\n \/\/ of shared faces is computed locally by each process.\n error_estimates(FT->Elem1No) += jump_integral;\n error_estimates(FT->Elem2No) += jump_integral;\n }\n }\n }\n\n \/\/ 3. Add error contribution from shared interior faces\n \/\/ Synchronize face data.\n flux.ExchangeFaceNbrData();\n\n for (int sf = 0; sf < pmesh->GetNSharedFaces(); sf++)\n {\n auto FT = pmesh->GetSharedFaceTransformations(sf, true);\n if (attributes.Size() &&\n (attributes.Find(FT->Elem1->Attribute) == -1\n || attributes.Find(FT->Elem2->Attribute) == -1))\n {\n continue;\n }\n\n const auto int_rule =\n int_rules.Get(FT->FaceGeom, 2 * xfes->GetFaceOrder(0));\n const auto nip = int_rule.GetNPoints();\n\n IntegrationRule eir;\n Vector jumps(nip);\n\n \/\/ Integral over local half face on the side of e₁\n \/\/ i.e. the numerical integration of ∫ flux ⋅ n dS₁\n for (int i = 0; i < nip; i++)\n {\n \/\/ Evaluate flux vector at integration point\n auto fip = int_rule.IntPoint(i);\n IntegrationPoint ip;\n FT->Loc1.Transform(fip, ip);\n\n Vector val(flux_space->GetVDim());\n flux.GetVectorValue(FT->Elem1No, ip, val);\n\n Vector normal(pmesh->SpaceDimension());\n FT->Face->SetIntPoint(&fip);\n if (pmesh->Dimension() == pmesh->SpaceDimension())\n {\n CalcOrtho(FT->Face->Jacobian(), normal);\n }\n else\n {\n Vector ref_normal(pmesh->Dimension());\n FT->Loc1.Transf.SetIntPoint(&fip);\n CalcOrtho(FT->Loc1.Transf.Jacobian(), ref_normal);\n auto &e1 = FT->GetElement1Transformation();\n e1.AdjugateJacobian().MultTranspose(ref_normal, normal);\n normal \/= e1.Weight();\n }\n\n jumps(i) = val * normal * fip.weight * FT->Face->Weight();\n }\n\n \/\/ Subtract integral over non-local half face of e₂\n \/\/ i.e. the numerical integration of ∫ flux ⋅ n dS₂\n for (int i = 0; i < nip; i++)\n {\n \/\/ Evaluate flux vector at integration point\n auto fip = int_rule.IntPoint(i);\n IntegrationPoint ip;\n FT->Loc2.Transform(fip, ip);\n\n Vector val(flux_space->GetVDim());\n flux.GetVectorValue(FT->Elem2No, ip, val);\n\n \/\/ Evaluate gauss point\n Vector normal(pmesh->SpaceDimension());\n FT->Face->SetIntPoint(&fip);\n if (pmesh->Dimension() == pmesh->SpaceDimension())\n {\n CalcOrtho(FT->Face->Jacobian(), normal);\n }\n else\n {\n Vector ref_normal(pmesh->Dimension());\n CalcOrtho(FT->Loc1.Transf.Jacobian(), ref_normal);\n auto &e1 = FT->GetElement1Transformation();\n e1.AdjugateJacobian().MultTranspose(ref_normal, normal);\n normal \/= e1.Weight();\n }\n normal.Neg();\n\n jumps(i) -= val * normal * fip.weight * FT->Face->Weight();\n }\n\n \/\/ Finalize \"local\" L₂ contribution\n for (int i = 0; i < nip; i++)\n {\n jumps(i) *= jumps(i);\n }\n auto h_k_face = compute_face_coefficient(pmesh, sf, true);\n double jump_integral = h_k_face*jumps.Sum();\n\n error_estimates(FT->Elem1No) += jump_integral;\n \/\/ We skip \"error_estimates(FT->Elem2No) += jump_integral\"\n \/\/ because the error is stored on the remote process and\n \/\/ recomputed there.\n }\n\n \/\/ Finalize element errors\n for (int e = 0; e < xfes->GetNE(); e++)\n {\n auto factor = compute_element_coefficient(pmesh, e);\n \/\/ The sqrt belongs to the norm and hₑ to the indicator.\n error_estimates(e) = sqrt(factor * error_estimates(e));\n }\n\n current_sequence = solution->FESpace()->GetMesh()->GetSequence();\n\n \/\/ Finish by computing the global error.\n double process_local_error = error_estimates.Sum();\n MPI_Allreduce(&process_local_error, &total_error, 1, MPI_DOUBLE,\n MPI_SUM, xfes->GetComm());\n}\n\n#endif \/\/ MFEM_USE_MPI\n\nvoid LpErrorEstimator::ComputeEstimates()\n{\n MFEM_VERIFY(coef != NULL || vcoef != NULL,\n \"LpErrorEstimator has no coefficient! Call SetCoef first.\");\n\n error_estimates.SetSize(sol->FESpace()->GetMesh()->GetNE());\n if (coef)\n {\n sol->ComputeElementLpErrors(local_norm_p, *coef, error_estimates);\n }\n else\n {\n sol->ComputeElementLpErrors(local_norm_p, *vcoef, error_estimates);\n }\n current_sequence = sol->FESpace()->GetMesh()->GetSequence();\n}\n\n} \/\/ namespace mfem\n<|endoftext|>"} {"text":"<commit_before>#ifndef VSMC_CORE_STATE_TUPLE_HPP\n#define VSMC_CORE_STATE_TUPLE_HPP\n\n#include <vsmc\/core\/single_particle.hpp>\n#include <tuple>\n#include <vector>\n\n#define VSMC_RUNTIME_ASSERT_CORE_STATE_TUPLE_COPY_SIZE_MISMATCH \\\n VSMC_RUNTIME_ASSERT((N == static_cast<size_type>(this->size())), \\\n (\"**StateTuple::copy** SIZE MISMATCH\"))\n\nnamespace vsmc {\n\n\/\/\/ \\brief Base type of StateTuple\n\/\/\/ \\ingroup Core\ntemplate <MatrixOrder Order, typename T, typename... Types>\nclass StateTupleBase\n{\n public :\n\n typedef std::size_t size_type;\n typedef std::tuple<T, Types...> state_tuple_type;\n typedef std::tuple<T *, Types *...> state_tuple_ptr_type;\n typedef std::tuple<const T *, const Types *...> state_tuple_cptr_type;\n\n template <std::size_t Pos> struct state_type\n {typedef typename std::tuple_element<Pos, state_tuple_type>::type type;};\n\n struct state_pack_type\n {\n state_pack_type () {}\n\n state_pack_type (const state_pack_type &other) : data_(other.data_) {}\n\n state_pack_type &operator= (const state_pack_type &other)\n {data_ = other.data_; return *this;}\n\n#if VSMC_HAS_CXX11_RVALUE_REFERENCES\n state_pack_type (state_pack_type &&other) VSMC_NOEXCEPT :\n data_(cxx11::move(other.data_)) {}\n\n state_pack_type &operator= (state_pack_type &&other) VSMC_NOEXCEPT\n {data_ = cxx11::move(other.data_); return *this;}\n#endif\n\n state_pack_type (const state_tuple_type &data) : data_(data) {}\n\n operator state_tuple_type () {return data_;}\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &get ()\n {return std::get<Pos>(data_);}\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &get () const\n {return std::get<Pos>(data_);}\n\n template <typename Archive>\n void serialize (Archive &ar, const unsigned)\n {serialize(ar, Position<0>());}\n\n template <typename Archive>\n void serialize (Archive &ar, const unsigned) const\n {serialize(ar, Position<0>());}\n\n private :\n\n state_tuple_type data_;\n static VSMC_CONSTEXPR const std::size_t dim_ = sizeof...(Types) + 1;\n\n template <typename Archive, std::size_t Pos>\n void serialize (Archive &ar, Position<Pos>)\n {\n ar & std::get<Pos>(data_);\n serialize(ar, Position<Pos + 1>());\n }\n\n template <typename Archive>\n void serialize (Archive &, Position<dim_>) {}\n\n template <typename Archive, std::size_t Pos>\n void serialize (Archive &ar, Position<Pos>) const\n {\n ar & std::get<Pos>(data_);\n serialize(ar, Position<Pos + 1>());\n }\n\n template <typename Archive>\n void serialize (Archive &, Position<dim_>) const {}\n }; \/\/ struct state_pack_type\n\n template <typename S>\n struct single_particle_type : public SingleParticleBase<S>\n {\n single_particle_type (typename Particle<S>::size_type id,\n Particle<S> *particle_ptr) :\n SingleParticleBase<S>(id, particle_ptr) {}\n\n static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &state (Position<Pos>) const\n {\n return this->mutable_particle_ptr()->value().\n state(this->id(), Position<Pos>());\n }\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &state () const\n {return this->state(Position<Pos>());}\n }; \/\/ struct single_particle_type\n\n template <typename S>\n struct const_single_particle_type : public ConstSingleParticleBase<S>\n {\n const_single_particle_type (typename Particle<S>::size_type id,\n const Particle<S> *particle_ptr) :\n ConstSingleParticleBase<S>(id, particle_ptr) {}\n\n static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &state (Position<Pos>) const\n {\n return this->particle_ptr()->value().\n state(this->id(), Position<Pos>());\n }\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &state () const\n {return this->state(Position<Pos>());}\n }; \/\/ struct const_single_particle_type\n\n size_type size () const {return size_;}\n\n static VSMC_CONSTEXPR std::size_t dim () {return dim_;}\n\n state_pack_type state_pack (size_type id) const\n {\n state_pack_type pack;\n pack_particle(id, pack, Position<0>());\n\n return pack;\n }\n\n void state_unpack (size_type id, const state_pack_type &pack)\n {unpack_particle(id, pack, Position<0>());}\n\n template <typename IntType>\n void copy (size_type N, const IntType *copy_from)\n {\n VSMC_RUNTIME_ASSERT_CORE_STATE_TUPLE_COPY_SIZE_MISMATCH;\n\n for (size_type to = 0; to != N; ++to)\n copy_particle(copy_from[to], to);\n }\n\n template <std::size_t Pos, typename OutputIter>\n OutputIter read_state (Position<Pos>, OutputIter first) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n for (size_type i = 0; i != size_; ++i, ++first)\n *first = sptr->state(i, Position<Pos>());\n\n return first;\n }\n\n template <std::size_t Pos, typename OutputIter>\n OutputIter read_state (OutputIter first) const\n {return read_state(Position<Pos>(), first);}\n\n template <typename CharT, typename Traits>\n std::basic_ostream<CharT, Traits> &print (\n std::basic_ostream<CharT, Traits> &os, std::size_t iter = 0,\n char sepchar = ' ', char eolchar = '\\n') const\n {\n for (size_type i = 0; i != size_; ++i) {\n os << iter << sepchar;\n print_particle(os, i, sepchar, eolchar, Position<0>());\n }\n\n return os;\n }\n\n protected :\n\n explicit StateTupleBase (size_type N) : size_(N) {}\n\n void copy_particle (size_type from, size_type to)\n {\n if (from != to)\n copy_particle(from, to, Position<0>());\n }\n\n private :\n\n size_type size_;\n static VSMC_CONSTEXPR const std::size_t dim_ = sizeof...(Types) + 1;\n\n template <std::size_t Pos>\n void pack_particle (size_type id, state_pack_type &pack,\n Position<Pos>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n pack.template get<Pos>() = sptr->state(id, Position<Pos>());\n pack_particle(id, pack, Position<Pos + 1>());\n }\n\n void pack_particle (size_type, state_pack_type &,\n Position<dim_>) const {}\n\n template <std::size_t Pos>\n void unpack_particle (size_type id, const state_pack_type &pack,\n Position<Pos>)\n {\n StateTuple<Order, T, Types...> *sptr =\n static_cast<StateTuple<Order, T, Types...> *>(this);\n sptr->state(id, Position<Pos>()) = pack.template get<Pos>();\n unpack_particle(id, pack, Position<Pos + 1>());\n }\n\n void unpack_particle (size_type, const state_pack_type &,\n Position<dim_>) {}\n\n template <std::size_t Pos>\n void copy_particle (size_type from, size_type to, Position<Pos>)\n {\n StateTuple<Order, T, Types...> *sptr =\n static_cast<StateTuple<Order, T, Types...> *>(this);\n sptr->state(to, Position<Pos>()) = sptr->state(from, Position<Pos>());\n copy_particle(from, to, Position<Pos + 1>());\n }\n\n void copy_particle (size_type, size_type, Position<dim_>) {}\n\n template <std::size_t Pos, typename CharT, typename Traits>\n void print_particle (std::basic_ostream<CharT, Traits> &os, size_type id,\n char sepchar, char eolchar, Position<Pos>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n os << sptr->state(id, Position<Pos>()) << sepchar;\n print_particle(os, id, sepchar, eolchar, Position<Pos + 1>());\n }\n\n template <typename CharT, typename Traits>\n void print_particle (std::basic_ostream<CharT, Traits> &os, size_type id,\n char, char eolchar, Position<dim_ - 1>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n os << sptr->state(id, Position<dim_ - 1>()) << eolchar;\n }\n}; \/\/ class StateTupleBase\n\n\/\/\/ \\brief Particle::value_type subtype\n\/\/\/ \\ingroup Core\ntemplate <typename T, typename... Types>\nclass StateTuple<RowMajor, T, Types...> :\n public StateTupleBase<RowMajor, T, Types...>\n{\n public :\n\n typedef StateTupleBase<RowMajor, T, Types...>\n state_tuple_base_type;\n typedef typename state_tuple_base_type::size_type size_type;\n\n explicit StateTuple (size_type N) : state_tuple_base_type(N), state_(N) {}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>)\n {return std::get<Pos>(state_[id]);}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>) const\n {return std::get<Pos>(state_[id]);}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id)\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id) const\n {return state(id, Position<Pos>());}\n\n const typename state_tuple_base_type::state_tuple_type *data () const\n {return &state_[0];}\n\n private :\n\n static VSMC_CONSTEXPR const std::size_t dim_ = sizeof...(Types) + 1;\n std::vector<std::tuple<T, Types...> > state_;\n}; \/\/ StateTuple\n\n\/\/\/ \\brief Particle::value_type subtype\n\/\/\/ \\ingroup Core\ntemplate <typename T, typename... Types>\nclass StateTuple<ColMajor, T, Types...> :\n public StateTupleBase<ColMajor, T, Types...>\n{\n public :\n\n typedef StateTupleBase<ColMajor, T, Types...>\n state_tuple_base_type;\n typedef typename state_tuple_base_type::size_type size_type;\n\n explicit StateTuple (size_type N) : state_tuple_base_type(N)\n {init_state(N, Position<0>());}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>)\n {return std::get<Pos>(state_)[id];}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>) const\n {return std::get<Pos>(state_)[id];}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id)\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id) const\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n *data (Position<Pos>) const {return &std::get<Pos>(state_)[0];}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n *data () const {return &std::get<Pos>(state_)[0];}\n\n typename state_tuple_base_type::state_tuple_cptr_type data () const\n {\n typename state_tuple_base_type::state_tuple_cptr_type dptr;\n insert_data(dptr, Position<0>());\n\n return dptr;\n }\n\n private :\n\n static VSMC_CONSTEXPR const std::size_t dim_ = sizeof...(Types) + 1;\n std::tuple<std::vector<T>, std::vector<Types>...> state_;\n\n template <std::size_t Pos>\n void init_state (size_type N, Position<Pos>)\n {\n std::get<Pos>(state_).resize(N);\n init_state(N, Position<Pos + 1>());\n }\n\n void init_state (size_type N, Position<sizeof...(Types)>)\n {std::get<sizeof...(Types)>(state_).resize(N);}\n\n template <std::size_t Pos>\n void insert_data (\n typename state_tuple_base_type::state_tuple_cptr_type &dptr,\n Position<Pos>) const\n {\n std::get<Pos>(dptr) = data<Pos>();\n insert_data(dptr, Position<Pos + 1>());\n }\n\n void insert_data (\n typename state_tuple_base_type::state_tuple_cptr_type &dptr,\n Position<sizeof...(Types)>) const\n {std::get<sizeof...(Types)>(dptr) = data<sizeof...(Types)>();}\n}; \/\/ class StateTuple\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_CORE_STATE_TUPLE_HPP\n<commit_msg>add mutable data pointer to state tuple<commit_after>#ifndef VSMC_CORE_STATE_TUPLE_HPP\n#define VSMC_CORE_STATE_TUPLE_HPP\n\n#include <vsmc\/core\/single_particle.hpp>\n#include <tuple>\n#include <vector>\n\n#define VSMC_RUNTIME_ASSERT_CORE_STATE_TUPLE_COPY_SIZE_MISMATCH \\\n VSMC_RUNTIME_ASSERT((N == static_cast<size_type>(this->size())), \\\n (\"**StateTuple::copy** SIZE MISMATCH\"))\n\nnamespace vsmc {\n\n\/\/\/ \\brief Base type of StateTuple\n\/\/\/ \\ingroup Core\ntemplate <MatrixOrder Order, typename T, typename... Types>\nclass StateTupleBase\n{\n public :\n\n typedef std::size_t size_type;\n typedef std::tuple<T, Types...> state_tuple_type;\n typedef std::tuple<T *, Types *...> state_tuple_ptr_type;\n typedef std::tuple<const T *, const Types *...> state_tuple_cptr_type;\n\n template <std::size_t Pos> struct state_type\n {typedef typename std::tuple_element<Pos, state_tuple_type>::type type;};\n\n struct state_pack_type\n {\n state_pack_type () {}\n\n state_pack_type (const state_pack_type &other) : data_(other.data_) {}\n\n state_pack_type &operator= (const state_pack_type &other)\n {data_ = other.data_; return *this;}\n\n#if VSMC_HAS_CXX11_RVALUE_REFERENCES\n state_pack_type (state_pack_type &&other) VSMC_NOEXCEPT :\n data_(cxx11::move(other.data_)) {}\n\n state_pack_type &operator= (state_pack_type &&other) VSMC_NOEXCEPT\n {data_ = cxx11::move(other.data_); return *this;}\n#endif\n\n state_pack_type (const state_tuple_type &data) : data_(data) {}\n\n operator state_tuple_type () {return data_;}\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &get ()\n {return std::get<Pos>(data_);}\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &get () const\n {return std::get<Pos>(data_);}\n\n template <typename Archive>\n void serialize (Archive &ar, const unsigned)\n {serialize(ar, Position<0>());}\n\n template <typename Archive>\n void serialize (Archive &ar, const unsigned) const\n {serialize(ar, Position<0>());}\n\n private :\n\n state_tuple_type data_;\n static VSMC_CONSTEXPR const std::size_t dim_ = sizeof...(Types) + 1;\n\n template <typename Archive, std::size_t Pos>\n void serialize (Archive &ar, Position<Pos>)\n {\n ar & std::get<Pos>(data_);\n serialize(ar, Position<Pos + 1>());\n }\n\n template <typename Archive>\n void serialize (Archive &, Position<dim_>) {}\n\n template <typename Archive, std::size_t Pos>\n void serialize (Archive &ar, Position<Pos>) const\n {\n ar & std::get<Pos>(data_);\n serialize(ar, Position<Pos + 1>());\n }\n\n template <typename Archive>\n void serialize (Archive &, Position<dim_>) const {}\n }; \/\/ struct state_pack_type\n\n template <typename S>\n struct single_particle_type : public SingleParticleBase<S>\n {\n single_particle_type (typename Particle<S>::size_type id,\n Particle<S> *particle_ptr) :\n SingleParticleBase<S>(id, particle_ptr) {}\n\n static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &state (Position<Pos>) const\n {\n return this->mutable_particle_ptr()->value().\n state(this->id(), Position<Pos>());\n }\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &state () const\n {return this->state(Position<Pos>());}\n }; \/\/ struct single_particle_type\n\n template <typename S>\n struct const_single_particle_type : public ConstSingleParticleBase<S>\n {\n const_single_particle_type (typename Particle<S>::size_type id,\n const Particle<S> *particle_ptr) :\n ConstSingleParticleBase<S>(id, particle_ptr) {}\n\n static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &state (Position<Pos>) const\n {\n return this->particle_ptr()->value().\n state(this->id(), Position<Pos>());\n }\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &state () const\n {return this->state(Position<Pos>());}\n }; \/\/ struct const_single_particle_type\n\n size_type size () const {return size_;}\n\n static VSMC_CONSTEXPR std::size_t dim () {return dim_;}\n\n state_pack_type state_pack (size_type id) const\n {\n state_pack_type pack;\n pack_particle(id, pack, Position<0>());\n\n return pack;\n }\n\n void state_unpack (size_type id, const state_pack_type &pack)\n {unpack_particle(id, pack, Position<0>());}\n\n template <typename IntType>\n void copy (size_type N, const IntType *copy_from)\n {\n VSMC_RUNTIME_ASSERT_CORE_STATE_TUPLE_COPY_SIZE_MISMATCH;\n\n for (size_type to = 0; to != N; ++to)\n copy_particle(copy_from[to], to);\n }\n\n template <std::size_t Pos, typename OutputIter>\n OutputIter read_state (Position<Pos>, OutputIter first) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n for (size_type i = 0; i != size_; ++i, ++first)\n *first = sptr->state(i, Position<Pos>());\n\n return first;\n }\n\n template <std::size_t Pos, typename OutputIter>\n OutputIter read_state (OutputIter first) const\n {return read_state(Position<Pos>(), first);}\n\n template <typename CharT, typename Traits>\n std::basic_ostream<CharT, Traits> &print (\n std::basic_ostream<CharT, Traits> &os, std::size_t iter = 0,\n char sepchar = ' ', char eolchar = '\\n') const\n {\n for (size_type i = 0; i != size_; ++i) {\n os << iter << sepchar;\n print_particle(os, i, sepchar, eolchar, Position<0>());\n }\n\n return os;\n }\n\n protected :\n\n explicit StateTupleBase (size_type N) : size_(N) {}\n\n void copy_particle (size_type from, size_type to)\n {\n if (from != to)\n copy_particle(from, to, Position<0>());\n }\n\n private :\n\n size_type size_;\n static VSMC_CONSTEXPR const std::size_t dim_ = sizeof...(Types) + 1;\n\n template <std::size_t Pos>\n void pack_particle (size_type id, state_pack_type &pack,\n Position<Pos>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n pack.template get<Pos>() = sptr->state(id, Position<Pos>());\n pack_particle(id, pack, Position<Pos + 1>());\n }\n\n void pack_particle (size_type, state_pack_type &,\n Position<dim_>) const {}\n\n template <std::size_t Pos>\n void unpack_particle (size_type id, const state_pack_type &pack,\n Position<Pos>)\n {\n StateTuple<Order, T, Types...> *sptr =\n static_cast<StateTuple<Order, T, Types...> *>(this);\n sptr->state(id, Position<Pos>()) = pack.template get<Pos>();\n unpack_particle(id, pack, Position<Pos + 1>());\n }\n\n void unpack_particle (size_type, const state_pack_type &,\n Position<dim_>) {}\n\n template <std::size_t Pos>\n void copy_particle (size_type from, size_type to, Position<Pos>)\n {\n StateTuple<Order, T, Types...> *sptr =\n static_cast<StateTuple<Order, T, Types...> *>(this);\n sptr->state(to, Position<Pos>()) = sptr->state(from, Position<Pos>());\n copy_particle(from, to, Position<Pos + 1>());\n }\n\n void copy_particle (size_type, size_type, Position<dim_>) {}\n\n template <std::size_t Pos, typename CharT, typename Traits>\n void print_particle (std::basic_ostream<CharT, Traits> &os, size_type id,\n char sepchar, char eolchar, Position<Pos>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n os << sptr->state(id, Position<Pos>()) << sepchar;\n print_particle(os, id, sepchar, eolchar, Position<Pos + 1>());\n }\n\n template <typename CharT, typename Traits>\n void print_particle (std::basic_ostream<CharT, Traits> &os, size_type id,\n char, char eolchar, Position<dim_ - 1>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n os << sptr->state(id, Position<dim_ - 1>()) << eolchar;\n }\n}; \/\/ class StateTupleBase\n\n\/\/\/ \\brief Particle::value_type subtype\n\/\/\/ \\ingroup Core\ntemplate <typename T, typename... Types>\nclass StateTuple<RowMajor, T, Types...> :\n public StateTupleBase<RowMajor, T, Types...>\n{\n public :\n\n typedef StateTupleBase<RowMajor, T, Types...>\n state_tuple_base_type;\n typedef typename state_tuple_base_type::size_type size_type;\n\n explicit StateTuple (size_type N) : state_tuple_base_type(N), state_(N) {}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>)\n {return std::get<Pos>(state_[id]);}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>) const\n {return std::get<Pos>(state_[id]);}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id)\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id) const\n {return state(id, Position<Pos>());}\n\n typename state_tuple_base_type::state_tuple_type *data ()\n {return &state_[0];}\n\n const typename state_tuple_base_type::state_tuple_type *data () const\n {return &state_[0];}\n\n private :\n\n static VSMC_CONSTEXPR const std::size_t dim_ = sizeof...(Types) + 1;\n std::vector<std::tuple<T, Types...> > state_;\n}; \/\/ StateTuple\n\n\/\/\/ \\brief Particle::value_type subtype\n\/\/\/ \\ingroup Core\ntemplate <typename T, typename... Types>\nclass StateTuple<ColMajor, T, Types...> :\n public StateTupleBase<ColMajor, T, Types...>\n{\n public :\n\n typedef StateTupleBase<ColMajor, T, Types...>\n state_tuple_base_type;\n typedef typename state_tuple_base_type::size_type size_type;\n\n explicit StateTuple (size_type N) : state_tuple_base_type(N)\n {init_state(N, Position<0>());}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>)\n {return std::get<Pos>(state_)[id];}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>) const\n {return std::get<Pos>(state_)[id];}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id)\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id) const\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n *data (Position<Pos>) {return &std::get<Pos>(state_)[0];}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n *data (Position<Pos>) const {return &std::get<Pos>(state_)[0];}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n *data () {return &std::get<Pos>(state_)[0];}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n *data () const {return &std::get<Pos>(state_)[0];}\n\n typename state_tuple_base_type::state_tuple_cptr_type data () const\n {\n typename state_tuple_base_type::state_tuple_cptr_type dptr;\n insert_data(dptr, Position<0>());\n\n return dptr;\n }\n\n private :\n\n static VSMC_CONSTEXPR const std::size_t dim_ = sizeof...(Types) + 1;\n std::tuple<std::vector<T>, std::vector<Types>...> state_;\n\n template <std::size_t Pos>\n void init_state (size_type N, Position<Pos>)\n {\n std::get<Pos>(state_).resize(N);\n init_state(N, Position<Pos + 1>());\n }\n\n void init_state (size_type N, Position<sizeof...(Types)>)\n {std::get<sizeof...(Types)>(state_).resize(N);}\n\n template <std::size_t Pos>\n void insert_data (\n typename state_tuple_base_type::state_tuple_cptr_type &dptr,\n Position<Pos>) const\n {\n std::get<Pos>(dptr) = data<Pos>();\n insert_data(dptr, Position<Pos + 1>());\n }\n\n void insert_data (\n typename state_tuple_base_type::state_tuple_cptr_type &dptr,\n Position<sizeof...(Types)>) const\n {std::get<sizeof...(Types)>(dptr) = data<sizeof...(Types)>();}\n}; \/\/ class StateTuple\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_CORE_STATE_TUPLE_HPP\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n#include <vector>\n#include \"Suffstats.h\"\n#include \"RandomNumberGenerator.h\"\n#include \"utils.h\"\n\nusing namespace std;\n\ntypedef Suffstats<double> suffD;\n\nint main(int argc, char** argv) { \n cout << endl << \"Begin:: test_suffstats\" << endl;\n RandomNumberGenerator rng;\n\n \/\/ test settings\n int max_randi = 30;\n int num_values_to_test = 10;\n double precision = 1E-10;\n\n \/\/ generate all the random data to use\n \/\/\n \/\/ initial parameters\n double r0 = rng.nexti(max_randi) * rng.next();\n double nu0 = rng.nexti(max_randi) * rng.next();\n double s0 = rng.nexti(max_randi) * rng.next();\n double mu0 = rng.nexti(max_randi) * rng.next();\n \/\/\n \/\/ elements to add\n vector<double> values_to_test;\n for(int i=0; i<num_values_to_test; i++) {\n double rand_value = rng.nexti(max_randi) * rng.next();\n values_to_test.push_back(rand_value);\n }\n \/\/ remove in a reversed order and a different order\n vector<double> values_to_test_reversed = values_to_test;\n std::reverse(values_to_test_reversed.begin(), values_to_test_reversed.end());\n vector<double> values_to_test_shuffled = values_to_test;\n std::random_shuffle(values_to_test_shuffled.begin(), values_to_test_shuffled.end());\n\n \/\/ print generated values\n \/\/\n cout << endl << \"initial parameters: \" << \"\\t\";\n cout << \"r0: \" << r0 << \"\\t\";\n cout << \"nu0: \" << nu0 << \"\\t\";\n cout << \"s0: \" << s0 << \"\\t\";\n cout << \"mu0: \" << mu0 << endl;\n cout << \"values_to_test: \" << values_to_test << endl;\n cout << \"values_to_test_shuffled: \" << values_to_test_shuffled << endl;\n\n \/\/ FIXME: should compare with a fixed dataset with known \n \/\/ post-update hyper values and score\n\n \/\/ FIXME: should be manually calling numerics:: functions\n \/\/ to compare suffstats results with\n \n \/\/ create the suffstats object\n \/\/\n \/\/ r, nu, s, mu\n suffD sd(r0, nu0, s0, mu0);\n cout << endl << \"initial suffstats object\" << endl;\n cout << sd << endl;\n \/\/\n print_defaults();\n\n \/\/ verify initial parameters\n \/\/\n int count;\n double sum_x, sum_x_sq;\n double r, nu, s, mu;\n sd.get_suffstats(count, sum_x, sum_x_sq);\n sd.get_hypers(r, nu, s, mu);\n assert(count==0);\n assert(is_almost(sum_x, 0, precision));\n assert(is_almost(sum_x_sq, 0, precision));\n assert(is_almost(r, r0, precision));\n assert(is_almost(nu, nu0, precision));\n assert(is_almost(s, s0, precision));\n assert(is_almost(mu, mu0, precision));\n assert(is_almost(sd.get_score(), 0, precision));\n\n \/\/ push data into suffstats\n for(vector<double>::iterator it=values_to_test.begin(); it!=values_to_test.end(); it++) {\n sd.insert_el(*it);\n }\n cout << endl << \"suffstats after insertion of data\" << endl;\n cout << sd << endl;\n \/\/ ensure count is proper\n assert(sd.get_count()==num_values_to_test);\n \/\/ remove data from suffstats in REVERSED order\n for(vector<double>::iterator it=values_to_test_reversed.begin(); it!=values_to_test_reversed.end(); it++) {\n sd.remove_el(*it);\n }\n cout << endl << \"suffstats after removal of data in reversed order\" << endl;\n cout << sd << endl;\n \/\/ ensure initial values are recovered\n sd.get_suffstats(count, sum_x, sum_x_sq);\n sd.get_hypers(r, nu, s, mu);\n assert(count==0);\n assert(is_almost(sum_x, 0, precision));\n assert(is_almost(sum_x_sq, 0, precision));\n assert(is_almost(r, r0, precision));\n assert(is_almost(nu, nu0, precision));\n assert(is_almost(s, s0, precision));\n assert(is_almost(mu, mu0, precision));\n assert(is_almost(sd.get_score(), 0, precision));\n\n \/\/ push data into suffstats\n for(vector<double>::iterator it=values_to_test.begin(); it!=values_to_test.end(); it++) {\n sd.insert_el(*it);\n }\n cout << endl << \"suffstats after insertion of data\" << endl;\n cout << sd << endl;\n \/\/ ensure count is proper\n assert(sd.get_count()==num_values_to_test);\n \/\/ remove data from suffstats in SHUFFLED order\n for(vector<double>::iterator it=values_to_test_shuffled.begin(); it!=values_to_test_shuffled.end(); it++) {\n sd.remove_el(*it);\n }\n cout << endl << \"suffstats after removal of data in shuffled order\" << endl;\n cout << sd << endl;\n \/\/ ensure initial values are recovered\n sd.get_suffstats(count, sum_x, sum_x_sq);\n sd.get_hypers(r, nu, s, mu);\n assert(count==0);\n assert(is_almost(sum_x, 0, precision));\n assert(is_almost(sum_x_sq, 0, precision));\n assert(is_almost(r, r0, precision));\n assert(is_almost(nu, nu0, precision));\n assert(is_almost(s, s0, precision));\n assert(is_almost(mu, mu0, precision));\n assert(is_almost(sd.get_score(), 0, precision));\n\n cout << \"Stop:: test_suffstats\" << endl;\n}\n<commit_msg>create helpers for inserting, removing multiple els<commit_after>#include <iostream>\n#include <algorithm>\n#include <vector>\n#include \"Suffstats.h\"\n#include \"RandomNumberGenerator.h\"\n#include \"utils.h\"\n\nusing namespace std;\n\ntypedef Suffstats<double> suffD;\n\nvoid insert_els(Suffstats<double> &sd, vector<double> els) {\n for(vector<double>::iterator it=els.begin(); it!=els.end(); it++)\n sd.insert_el(*it);\n}\n\nvoid remove_els(Suffstats<double> &sd, vector<double> els) {\n for(vector<double>::iterator it=els.begin(); it!=els.end(); it++)\n sd.remove_el(*it);\n}\n\nint main(int argc, char** argv) { \n cout << endl << \"Begin:: test_suffstats\" << endl;\n RandomNumberGenerator rng;\n\n \/\/ test settings\n int max_randi = 30;\n int num_values_to_test = 10;\n double precision = 1E-10;\n\n \/\/ generate all the random data to use\n \/\/\n \/\/ initial parameters\n double r0 = rng.nexti(max_randi) * rng.next();\n double nu0 = rng.nexti(max_randi) * rng.next();\n double s0 = rng.nexti(max_randi) * rng.next();\n double mu0 = rng.nexti(max_randi) * rng.next();\n \/\/\n \/\/ elements to add\n vector<double> values_to_test;\n for(int i=0; i<num_values_to_test; i++) {\n double rand_value = rng.nexti(max_randi) * rng.next();\n values_to_test.push_back(rand_value);\n }\n \/\/ remove in a reversed order and a different order\n vector<double> values_to_test_reversed = values_to_test;\n std::reverse(values_to_test_reversed.begin(), values_to_test_reversed.end());\n vector<double> values_to_test_shuffled = values_to_test;\n std::random_shuffle(values_to_test_shuffled.begin(), values_to_test_shuffled.end());\n\n \/\/ print generated values\n \/\/\n cout << endl << \"initial parameters: \" << \"\\t\";\n cout << \"r0: \" << r0 << \"\\t\";\n cout << \"nu0: \" << nu0 << \"\\t\";\n cout << \"s0: \" << s0 << \"\\t\";\n cout << \"mu0: \" << mu0 << endl;\n cout << \"values_to_test: \" << values_to_test << endl;\n cout << \"values_to_test_shuffled: \" << values_to_test_shuffled << endl;\n\n \/\/ FIXME: should compare with a fixed dataset with known \n \/\/ post-update hyper values and score\n\n \/\/ FIXME: should be manually calling numerics:: functions\n \/\/ to compare suffstats results with\n \n \/\/ create the suffstats object\n \/\/\n \/\/ r, nu, s, mu\n suffD sd(r0, nu0, s0, mu0);\n cout << endl << \"initial suffstats object\" << endl;\n cout << sd << endl;\n \/\/\n print_defaults();\n\n \/\/ verify initial parameters\n \/\/\n int count;\n double sum_x, sum_x_sq;\n double r, nu, s, mu;\n sd.get_suffstats(count, sum_x, sum_x_sq);\n sd.get_hypers(r, nu, s, mu);\n assert(count==0);\n assert(is_almost(sum_x, 0, precision));\n assert(is_almost(sum_x_sq, 0, precision));\n assert(is_almost(r, r0, precision));\n assert(is_almost(nu, nu0, precision));\n assert(is_almost(s, s0, precision));\n assert(is_almost(mu, mu0, precision));\n assert(is_almost(sd.get_score(), 0, precision));\n\n \/\/ push data into suffstats\n insert_els(sd, values_to_test);\n cout << endl << \"suffstats after insertion of data\" << endl;\n cout << sd << endl;\n \/\/ ensure count is proper\n assert(sd.get_count()==num_values_to_test);\n \/\/ remove data from suffstats in REVERSED order\n remove_els(sd, values_to_test_reversed);\n cout << endl << \"suffstats after removal of data in reversed order\" << endl;\n cout << sd << endl;\n \/\/ ensure initial values are recovered\n sd.get_suffstats(count, sum_x, sum_x_sq);\n sd.get_hypers(r, nu, s, mu);\n assert(count==0);\n assert(is_almost(sum_x, 0, precision));\n assert(is_almost(sum_x_sq, 0, precision));\n assert(is_almost(r, r0, precision));\n assert(is_almost(nu, nu0, precision));\n assert(is_almost(s, s0, precision));\n assert(is_almost(mu, mu0, precision));\n assert(is_almost(sd.get_score(), 0, precision));\n\n \/\/ push data into suffstats\n insert_els(sd, values_to_test);\n cout << endl << \"suffstats after insertion of data\" << endl;\n cout << sd << endl;\n \/\/ ensure count is proper\n assert(sd.get_count()==num_values_to_test);\n \/\/ remove data from suffstats in SHUFFLED order\n remove_els(sd, values_to_test_shuffled);\n cout << endl << \"suffstats after removal of data in shuffled order\" << endl;\n cout << sd << endl;\n \/\/ ensure initial values are recovered\n sd.get_suffstats(count, sum_x, sum_x_sq);\n sd.get_hypers(r, nu, s, mu);\n assert(count==0);\n assert(is_almost(sum_x, 0, precision));\n assert(is_almost(sum_x_sq, 0, precision));\n assert(is_almost(r, r0, precision));\n assert(is_almost(nu, nu0, precision));\n assert(is_almost(s, s0, precision));\n assert(is_almost(mu, mu0, precision));\n assert(is_almost(sd.get_score(), 0, precision));\n\n cout << \"Stop:: test_suffstats\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/http:\/\/lx.lanqiao.org\/problem.page?gpid=T30\n\/*\n连号区间数\n\n问题描述\n小明这些天一直在思考这样一个奇怪而有趣的问题:\n\n在1~N的某个全排列中有多少个连号区间呢?这里所说的连号区间的定义是:\n\n如果区间[L, R] 里的所有元素(即此排列的第L个到第R个元素)递增排序后能得到一个长度为R-L+1的“连续”数列,则称这个区间连号区间。\n\n当N很小的时候,小明可以很快地算出答案,但是当N变大的时候,问题就不是那么简单了,现在小明需要你的帮助。\n\n输入格式\n第一行是一个正整数N (1 <= N <= 50000), 表示全排列的规模。\n\n第二行是N个不同的数字Pi(1 <= Pi <= N), 表示这N个数字的某一全排列。\n\n输出格式\n输出一个整数,表示不同连号区间的数目。\n\n样例输入1\n4\n3 2 4 1\n样例输出1\n7\n样例输入2\n5\n3 4 2 5 1\n样例输出2\n9\n*\/\n\n\/\/Because the last part use a disjoint set, it is near linear time.\n\n\n#include <stdio.h>\n#include <string.h>\n#define N 60000\nint n, in[N], ind[N];\nint stk[N], top;\nint LH[N], RH[N];\nint LL[N], RL[N], MX[N];\n\nint print_arr(int s[], int n) {\n for(int i = 0; i < n; ++i) printf(\"%d \", s[i]); puts(\"\");\n}\n\nint getfat(int bc[], int x) {\n if(bc[x] == -1) return x;\n return bc[x] = getfat(bc, bc[x]);\n}\n\nvoid uni(int bc[], int x, int y) {\n x = getfat(bc, x);\n y = getfat(bc, y);\n if(x == y) return;\n bc[x] = y;\n}\n\nvoid push(int x) {\n LL[x] = top;\n stk[top++] = x;\n}\n\nint count(int x) {\n int y = getfat(RL, x + 1);\n return top - LL[y] - 1;\n}\n\nvoid clear(int x) {\n while(top > 0 && stk[top - 1] <= x) {\n uni(RL, stk[top - 1], stk[top - 2]);\n --top;\n }\n}\n\nint main() {\n while(scanf(\"%d\", &n) != EOF) {\n for(int i = 1; i <= n; ++i) {\n scanf(\"%d\", in + i);\n ind[in[i]] = i;\n MX[i] = i;\n }\n\n top = 0; \n for(int i = 1; i <= n; ++i) {\n while(top > 0 && stk[top - 1] > in[i]) {\n int j = stk[top - 1];\n RL[j] = i - 1;\n --top;\n }\n if(top == 0) LL[in[i]] = 1;\n else LL[in[i]] = ind[stk[top - 1]] + 1;\n stk[top++] = in[i];\n }\n while(top > 0) {\n int j = stk[top - 1];\n RL[j] = n;\n --top;\n }\n \n top = 0; \n for(int i = 1; i <= n; ++i) {\n while(top > 0 && stk[top - 1] < in[i]) {\n int j = stk[top - 1];\n RH[j] = in[i];\n --top;\n }\n if(top == 0) LH[in[i]] = n + 1;\n else LH[in[i]] = stk[top - 1];\n stk[top++] = in[i];\n }\n while(top > 0) {\n int j = stk[top - 1];\n RH[j] = n + 1;\n --top;\n }\n \n \/\/for(int i = 1; i <= n; ++i) printf(\"%d %d %d %d %d\\n\", i, LL[i], RL[i], LH[i], RH[i]);\n\n for(int i = N - 1; i >= 1; --i) {\n int j = i + 1;\n while(LL[i] <= ind[j] && ind[j] <= RL[i]) {\n j = MX[j] + 1;\n if(j > n) break;\n }\n MX[i] = j - 1;\n }\n \n \/\/for(int i = 1; i <= n; ++i) printf(\"%d %d\\n\", i, MX[i]);\n \n memset(RL, -1, sizeof(RL[0]) * (n + 10));\n \n top = 0;\n \n int ans = 1;\n push(n + 1);\n push(n);\n \n for(int i = n - 1; i >= 1; --i) {\n int tmp = (ind[i + 1] < ind[i] ? LH[i] : RH[i]) - 1;\n clear(tmp);\n push(i);\n \/\/print_arr(stk, top);\n \/\/printf(\"i %d %d %d %d\\n\", i, tmp, count(MX[i]), ans);\n ans += count(MX[i]);\n }\n printf(\"%d\\n\", ans);\n }\n return 0;\n}\n<commit_msg>Update lanqiao_T30.cpp<commit_after>\/\/http:\/\/lx.lanqiao.org\/problem.page?gpid=T30\n\/*\n连号区间数\n\n问题描述\n小明这些天一直在思考这样一个奇怪而有趣的问题:\n\n在1~N的某个全排列中有多少个连号区间呢?这里所说的连号区间的定义是:\n\n如果区间[L, R] 里的所有元素(即此排列的第L个到第R个元素)递增排序后能得到一个长度为R-L+1的“连续”数列,则称这个区间连号区间。\n\n当N很小的时候,小明可以很快地算出答案,但是当N变大的时候,问题就不是那么简单了,现在小明需要你的帮助。\n\n输入格式\n第一行是一个正整数N (1 <= N <= 50000), 表示全排列的规模。\n\n第二行是N个不同的数字Pi(1 <= Pi <= N), 表示这N个数字的某一全排列。\n\n输出格式\n输出一个整数,表示不同连号区间的数目。\n\n样例输入1\n4\n3 2 4 1\n样例输出1\n7\n样例输入2\n5\n3 4 2 5 1\n样例输出2\n9\n*\/\n\n\/\/Because the last part use a disjoint set, it is near linear time.\n\n\n#include <stdio.h>\n#include <string.h>\n#define N 60000\nint n, in[N], ind[N];\nint stk[N], top;\nint LH[N], RH[N];\nint LL[N], RL[N], MX[N];\n\nint print_arr(int s[], int n) {\n for(int i = 0; i < n; ++i) printf(\"%d \", s[i]); puts(\"\");\n}\n\nint getfat(int bc[], int x) {\n if(bc[x] == -1) return x;\n return bc[x] = getfat(bc, bc[x]);\n}\n\nvoid uni(int bc[], int x, int y) {\n x = getfat(bc, x);\n y = getfat(bc, y);\n if(x == y) return;\n bc[x] = y;\n}\n\nvoid push(int x) {\n LL[x] = top;\n stk[top++] = x;\n}\n\nint count(int x) {\n int y = getfat(RL, x + 1);\n return top - LL[y] - 1;\n}\n\nvoid clear(int x) {\n while(top > 0 && stk[top - 1] <= x) {\n uni(RL, stk[top - 1], stk[top - 2]);\n --top;\n }\n}\n\nint main() {\n while(scanf(\"%d\", &n) != EOF) {\n for(int i = 1; i <= n; ++i) {\n scanf(\"%d\", in + i);\n ind[in[i]] = i;\n MX[i] = i;\n }\n\n top = 0; \n for(int i = 1; i <= n; ++i) {\n while(top > 0 && stk[top - 1] > in[i]) {\n int j = stk[top - 1];\n RL[j] = i - 1;\n --top;\n }\n if(top == 0) LL[in[i]] = 1;\n else LL[in[i]] = ind[stk[top - 1]] + 1;\n stk[top++] = in[i];\n }\n while(top > 0) {\n int j = stk[top - 1];\n RL[j] = n;\n --top;\n }\n \n top = 0; \n for(int i = 1; i <= n; ++i) {\n while(top > 0 && stk[top - 1] < in[i]) {\n int j = stk[top - 1];\n RH[j] = in[i];\n --top;\n }\n if(top == 0) LH[in[i]] = n + 1;\n else LH[in[i]] = stk[top - 1];\n stk[top++] = in[i];\n }\n while(top > 0) {\n int j = stk[top - 1];\n RH[j] = n + 1;\n --top;\n }\n \n \/\/for(int i = 1; i <= n; ++i) printf(\"%d %d %d %d %d\\n\", i, LL[i], RL[i], LH[i], RH[i]);\n\n for(int i = n - 1; i >= 1; --i) {\n int j = i + 1;\n while(LL[i] <= ind[j] && ind[j] <= RL[i]) {\n j = MX[j] + 1;\n if(j > n) break;\n }\n MX[i] = j - 1;\n }\n \n \/\/for(int i = 1; i <= n; ++i) printf(\"%d %d\\n\", i, MX[i]);\n \n memset(RL, -1, sizeof(RL[0]) * (n + 10));\n \n top = 0;\n \n int ans = 1;\n push(n + 1);\n push(n);\n \n for(int i = n - 1; i >= 1; --i) {\n int tmp = (ind[i + 1] < ind[i] ? LH[i] : RH[i]) - 1;\n clear(tmp);\n push(i);\n \/\/print_arr(stk, top);\n \/\/printf(\"i %d %d %d %d\\n\", i, tmp, count(MX[i]), ans);\n ans += count(MX[i]);\n }\n printf(\"%d\\n\", ans);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 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\/\/ This test only works with the GPU backend.\n\n#include \"gm\/gm.h\"\n#include \"include\/core\/SkBitmap.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColor.h\"\n#include \"include\/core\/SkMatrix.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkRect.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/effects\/SkGradientShader.h\"\n#include \"include\/private\/GrTypesPriv.h\"\n#include \"include\/private\/SkTArray.h\"\n#include \"src\/gpu\/GrContextPriv.h\"\n#include \"src\/gpu\/GrProxyProvider.h\"\n#include \"src\/gpu\/GrRenderTargetContext.h\"\n#include \"src\/gpu\/GrRenderTargetContextPriv.h\"\n#include \"src\/gpu\/GrSamplerState.h\"\n#include \"src\/gpu\/GrTextureProxy.h\"\n#include \"tools\/gpu\/TestOps.h\"\n\n#include <memory>\n#include <utility>\n\nnamespace skiagm {\n\/**\n * This GM directly exercises GrTextureEffect::MakeTexelSubset.\n *\/\nclass TextureDomainEffect : public GpuGM {\npublic:\n TextureDomainEffect(GrSamplerState::Filter filter) : fFilter(filter) {\n this->setBGColor(0xFFFFFFFF);\n }\n\nprotected:\n SkString onShortName() override {\n SkString name(\"texture_domain_effect\");\n if (fFilter == GrSamplerState::Filter::kBilerp) {\n name.append(\"_bilerp\");\n } else if (fFilter == GrSamplerState::Filter::kMipMap) {\n name.append(\"_mipmap\");\n }\n return name;\n }\n\n SkISize onISize() override {\n const SkScalar canvasWidth =\n kDrawPad + 2 * ((kTargetWidth + 2 * kDrawPad) * GrSamplerState::kWrapModeCount +\n kTestPad * GrSamplerState::kWrapModeCount);\n return SkISize::Make(SkScalarCeilToInt(canvasWidth), 800);\n }\n\n void onOnceBeforeDraw() override {\n fBitmap.allocN32Pixels(kTargetWidth, kTargetHeight);\n SkCanvas canvas(fBitmap);\n canvas.clear(0x00000000);\n SkPaint paint;\n\n SkColor colors1[] = { SK_ColorCYAN, SK_ColorLTGRAY, SK_ColorGRAY };\n paint.setShader(SkGradientShader::MakeSweep(65.f, 75.f, colors1, nullptr,\n SK_ARRAY_COUNT(colors1)));\n canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f),\n paint);\n\n SkColor colors2[] = { SK_ColorMAGENTA, SK_ColorLTGRAY, SK_ColorYELLOW };\n paint.setShader(SkGradientShader::MakeSweep(45.f, 55.f, colors2, nullptr,\n SK_ARRAY_COUNT(colors2)));\n paint.setBlendMode(SkBlendMode::kDarken);\n canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f),\n paint);\n\n SkColor colors3[] = { SK_ColorBLUE, SK_ColorLTGRAY, SK_ColorGREEN };\n paint.setShader(SkGradientShader::MakeSweep(25.f, 35.f, colors3, nullptr,\n SK_ARRAY_COUNT(colors3)));\n paint.setBlendMode(SkBlendMode::kLighten);\n canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f),\n paint);\n }\n\n DrawResult onDraw(GrContext* context, GrRenderTargetContext* renderTargetContext,\n SkCanvas* canvas, SkString* errorMsg) override {\n GrProxyProvider* proxyProvider = context->priv().proxyProvider();\n sk_sp<GrTextureProxy> proxy;\n GrMipMapped mipMapped = fFilter == GrSamplerState::Filter::kMipMap &&\n context->priv().caps()->mipMapSupport()\n ? GrMipMapped::kYes : GrMipMapped::kNo;\n proxy = proxyProvider->createProxyFromBitmap(fBitmap, mipMapped);\n if (!proxy) {\n *errorMsg = \"Failed to create proxy.\";\n return DrawResult::kFail;\n }\n\n SkTArray<SkMatrix> textureMatrices;\n textureMatrices.push_back() = SkMatrix::I();\n textureMatrices.push_back() = SkMatrix::MakeScale(1.5f, 0.85f);\n textureMatrices.push_back();\n textureMatrices.back().setRotate(45.f, proxy->width() \/ 2.f, proxy->height() \/ 2.f);\n\n const SkIRect texelDomains[] = {\n fBitmap.bounds(),\n SkIRect::MakeXYWH(fBitmap.width() \/ 4 - 1, fBitmap.height() \/ 4 - 1,\n fBitmap.width() \/ 2 + 2, fBitmap.height() \/ 2 + 2),\n };\n\n SkRect localRect = SkRect::Make(fBitmap.bounds()).makeOutset(kDrawPad, kDrawPad);\n\n SkScalar y = kDrawPad + kTestPad;\n for (int tm = 0; tm < textureMatrices.count(); ++tm) {\n for (size_t d = 0; d < SK_ARRAY_COUNT(texelDomains); ++d) {\n SkScalar x = kDrawPad + kTestPad;\n for (int m = 0; m < GrSamplerState::kWrapModeCount; ++m) {\n auto wm = static_cast<GrSamplerState::WrapMode>(m);\n if (fFilter != GrSamplerState::Filter::kNearest &&\n (wm == GrSamplerState::WrapMode::kRepeat ||\n wm == GrSamplerState::WrapMode::kMirrorRepeat)) {\n \/\/ [Mirror] Repeat mode doesn't produce correct results with bilerp\n \/\/ filtering\n continue;\n }\n GrSamplerState sampler(wm, fFilter);\n const auto& caps = *context->priv().caps();\n auto fp1 = GrTextureEffect::MakeTexelSubset(proxy,\n fBitmap.alphaType(),\n textureMatrices[tm],\n sampler,\n texelDomains[d],\n caps);\n if (!fp1) {\n continue;\n }\n auto fp2 = fp1->clone();\n SkASSERT(fp2);\n auto drawRect = localRect.makeOffset(x, y);\n if (auto op = sk_gpu_test::test_ops::MakeRect(\n context, std::move(fp1), drawRect, localRect)) {\n renderTargetContext->priv().testingOnly_addDrawOp(std::move(op));\n }\n x += localRect.width() + kTestPad;\n \/\/ Draw again with a translated local rect and compensating translate matrix.\n drawRect = localRect.makeOffset(x, y);\n static constexpr SkVector kT = {-100, 300};\n\n if (auto op = sk_gpu_test::test_ops::MakeRect(context,\n std::move(fp2),\n drawRect,\n localRect.makeOffset(kT),\n SkMatrix::MakeTrans(-kT))) {\n renderTargetContext->priv().testingOnly_addDrawOp(std::move(op));\n }\n x += localRect.width() + kTestPad;\n }\n y += localRect.height() + kTestPad;\n }\n }\n return DrawResult::kOk;\n }\n\nprivate:\n static constexpr SkScalar kDrawPad = 10.f;\n static constexpr SkScalar kTestPad = 10.f;\n static constexpr int kTargetWidth = 100;\n static constexpr int kTargetHeight = 100;\n SkBitmap fBitmap;\n GrSamplerState::Filter fFilter;\n\n typedef GM INHERITED;\n};\n\nDEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kNearest);)\nDEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kBilerp);)\nDEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kMipMap);)\n\n}\n<commit_msg>Revert \"Revert \"Use bitmap subset for comparison in texture_domain_effect GMs.\"\"<commit_after>\/*\n * Copyright 2014 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\/\/ This test only works with the GPU backend.\n\n#include \"gm\/gm.h\"\n#include \"include\/core\/SkBitmap.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColor.h\"\n#include \"include\/core\/SkMatrix.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkRect.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/effects\/SkGradientShader.h\"\n#include \"include\/private\/GrTypesPriv.h\"\n#include \"include\/private\/SkTArray.h\"\n#include \"src\/gpu\/GrContextPriv.h\"\n#include \"src\/gpu\/GrProxyProvider.h\"\n#include \"src\/gpu\/GrRenderTargetContext.h\"\n#include \"src\/gpu\/GrRenderTargetContextPriv.h\"\n#include \"src\/gpu\/GrSamplerState.h\"\n#include \"src\/gpu\/GrTextureProxy.h\"\n#include \"tools\/gpu\/TestOps.h\"\n\n#include <memory>\n#include <utility>\n\nnamespace skiagm {\n\/**\n * This GM directly exercises GrTextureEffect::MakeTexelSubset.\n *\/\nclass TextureDomainEffect : public GpuGM {\npublic:\n TextureDomainEffect(GrSamplerState::Filter filter) : fFilter(filter) {\n this->setBGColor(0xFFFFFFFF);\n }\n\nprotected:\n SkString onShortName() override {\n SkString name(\"texture_domain_effect\");\n if (fFilter == GrSamplerState::Filter::kBilerp) {\n name.append(\"_bilerp\");\n } else if (fFilter == GrSamplerState::Filter::kMipMap) {\n name.append(\"_mipmap\");\n }\n return name;\n }\n\n SkISize onISize() override {\n const SkScalar canvasWidth =\n kDrawPad + 2 * ((kTargetWidth + 2 * kDrawPad) * GrSamplerState::kWrapModeCount +\n kTestPad * GrSamplerState::kWrapModeCount);\n return SkISize::Make(SkScalarCeilToInt(canvasWidth), 800);\n }\n\n void onOnceBeforeDraw() override {\n fBitmap.allocN32Pixels(kTargetWidth, kTargetHeight);\n SkCanvas canvas(fBitmap);\n canvas.clear(0x00000000);\n SkPaint paint;\n\n SkColor colors1[] = { SK_ColorCYAN, SK_ColorLTGRAY, SK_ColorGRAY };\n paint.setShader(SkGradientShader::MakeSweep(65.f, 75.f, colors1, nullptr,\n SK_ARRAY_COUNT(colors1)));\n canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f),\n paint);\n\n SkColor colors2[] = { SK_ColorMAGENTA, SK_ColorLTGRAY, SK_ColorYELLOW };\n paint.setShader(SkGradientShader::MakeSweep(45.f, 55.f, colors2, nullptr,\n SK_ARRAY_COUNT(colors2)));\n paint.setBlendMode(SkBlendMode::kDarken);\n canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f),\n paint);\n\n SkColor colors3[] = { SK_ColorBLUE, SK_ColorLTGRAY, SK_ColorGREEN };\n paint.setShader(SkGradientShader::MakeSweep(25.f, 35.f, colors3, nullptr,\n SK_ARRAY_COUNT(colors3)));\n paint.setBlendMode(SkBlendMode::kLighten);\n canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f),\n paint);\n }\n\n DrawResult onDraw(GrContext* context, GrRenderTargetContext* renderTargetContext,\n SkCanvas* canvas, SkString* errorMsg) override {\n GrProxyProvider* proxyProvider = context->priv().proxyProvider();\n sk_sp<GrTextureProxy> proxy;\n GrMipMapped mipMapped = fFilter == GrSamplerState::Filter::kMipMap &&\n context->priv().caps()->mipMapSupport()\n ? GrMipMapped::kYes : GrMipMapped::kNo;\n proxy = proxyProvider->createProxyFromBitmap(fBitmap, mipMapped);\n if (!proxy) {\n *errorMsg = \"Failed to create proxy.\";\n return DrawResult::kFail;\n }\n\n SkTArray<SkMatrix> textureMatrices;\n textureMatrices.push_back() = SkMatrix::I();\n textureMatrices.push_back() = SkMatrix::MakeScale(1.5f, 0.85f);\n textureMatrices.push_back();\n textureMatrices.back().setRotate(45.f, proxy->width() \/ 2.f, proxy->height() \/ 2.f);\n\n const SkIRect texelDomains[] = {\n fBitmap.bounds(),\n SkIRect::MakeXYWH(fBitmap.width() \/ 4 - 1, fBitmap.height() \/ 4 - 1,\n fBitmap.width() \/ 2 + 2, fBitmap.height() \/ 2 + 2),\n };\n\n sk_sp<GrTextureProxy> subsetProxies[SK_ARRAY_COUNT(texelDomains)];\n for (size_t d = 0; d < SK_ARRAY_COUNT(texelDomains); ++d) {\n SkBitmap subset;\n fBitmap.extractSubset(&subset, texelDomains[d]);\n subsetProxies[d] = proxyProvider->createProxyFromBitmap(subset, mipMapped);\n }\n\n SkRect localRect = SkRect::Make(fBitmap.bounds()).makeOutset(kDrawPad, kDrawPad);\n\n SkScalar y = kDrawPad + kTestPad;\n for (int tm = 0; tm < textureMatrices.count(); ++tm) {\n for (size_t d = 0; d < SK_ARRAY_COUNT(texelDomains); ++d) {\n SkScalar x = kDrawPad + kTestPad;\n for (int m = 0; m < GrSamplerState::kWrapModeCount; ++m) {\n auto wm = static_cast<GrSamplerState::WrapMode>(m);\n if (fFilter != GrSamplerState::Filter::kNearest &&\n (wm == GrSamplerState::WrapMode::kRepeat ||\n wm == GrSamplerState::WrapMode::kMirrorRepeat)) {\n \/\/ [Mirror] Repeat mode doesn't produce correct results with bilerp\n \/\/ filtering\n continue;\n }\n GrSamplerState sampler(wm, fFilter);\n const auto& caps = *context->priv().caps();\n auto fp1 = GrTextureEffect::MakeTexelSubset(proxy,\n fBitmap.alphaType(),\n textureMatrices[tm],\n sampler,\n texelDomains[d],\n caps);\n if (!fp1) {\n continue;\n }\n auto drawRect = localRect.makeOffset(x, y);\n \/\/ Throw a translate in the local matrix just to test having something other\n \/\/ than identity. Compensate with an offset local rect.\n static constexpr SkVector kT = {-100, 300};\n if (auto op = sk_gpu_test::test_ops::MakeRect(context,\n std::move(fp1),\n drawRect,\n localRect.makeOffset(kT),\n SkMatrix::MakeTrans(-kT))) {\n renderTargetContext->priv().testingOnly_addDrawOp(std::move(op));\n }\n x += localRect.width() + kTestPad;\n\n SkMatrix subsetTextureMatrix = SkMatrix::Concat(\n SkMatrix::MakeTrans(-texelDomains[d].topLeft()), textureMatrices[tm]);\n\n \/\/ Now draw with a subsetted proxy using fixed function texture sampling rather\n \/\/ than a texture subset as a comparison.\n drawRect = localRect.makeOffset(x, y);\n auto fp2 = GrTextureEffect::Make(subsetProxies[d], fBitmap.alphaType(),\n subsetTextureMatrix,\n GrSamplerState(wm, fFilter), caps);\n if (auto op = sk_gpu_test::test_ops::MakeRect(context, std::move(fp2), drawRect,\n localRect)) {\n renderTargetContext->priv().testingOnly_addDrawOp(std::move(op));\n }\n x += localRect.width() + kTestPad;\n }\n y += localRect.height() + kTestPad;\n }\n }\n return DrawResult::kOk;\n }\n\nprivate:\n static constexpr SkScalar kDrawPad = 10.f;\n static constexpr SkScalar kTestPad = 10.f;\n static constexpr int kTargetWidth = 100;\n static constexpr int kTargetHeight = 100;\n SkBitmap fBitmap;\n GrSamplerState::Filter fFilter;\n\n typedef GM INHERITED;\n};\n\nDEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kNearest);)\nDEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kBilerp);)\nDEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kMipMap);)\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <reactive\/bridge.hpp>\n#include <reactive\/ptr_observable.hpp>\n#include <reactive\/buffer.hpp>\n#include <reactive\/generate.hpp>\n#include <reactive\/tuple.hpp>\n#include <reactive\/transform.hpp>\n#include <reactive\/while.hpp>\n#include <reactive\/finite_state_machine.hpp>\n#include <reactive\/filter.hpp>\n#include <reactive\/timer.hpp>\n#include <reactive\/total_consumer.hpp>\n#include <SDL2\/SDL.h>\n#include <boost\/system\/system_error.hpp>\n#include <boost\/scope_exit.hpp>\n#include <boost\/variant.hpp>\n#include <boost\/asio.hpp>\n\nnamespace\n{\n\tvoid throw_error()\n\t{\n\t\tthrow std::runtime_error(std::string(\"SDL error :\") + SDL_GetError());\n\t}\n\n\tvoid check_sdl(int rc)\n\t{\n\t\tif (rc < 0)\n\t\t{\n\t\t\tthrow_error();\n\t\t}\n\t}\n\n\tstruct window_destructor\n\t{\n\t\tvoid operator()(SDL_Window *w) const\n\t\t{\n\t\t\tSDL_DestroyWindow(w);\n\t\t}\n\t};\n\n\tstruct renderer_destructor\n\t{\n\t\tvoid operator()(SDL_Renderer *r) const\n\t\t{\n\t\t\tSDL_DestroyRenderer(r);\n\t\t}\n\t};\n\n\tstruct draw_filled_rect\n\t{\n\t\tSDL_Color color;\n\t\tSDL_Rect where;\n\t};\n\n\ttypedef boost::variant<\n\t\tdraw_filled_rect\n\t> draw_operation;\n\n\tstruct frame\n\t{\n\t\tstd::vector<draw_operation> operations;\n\t};\n\n\tSDL_Color make_color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha)\n\t{\n\t\tSDL_Color result;\n\t\tresult.r = red;\n\t\tresult.g = green;\n\t\tresult.b = blue;\n\t\tresult.a = alpha;\n\t\treturn result;\n\t}\n\n\tSDL_Rect make_rect(int x, int y, int w, int h)\n\t{\n\t\tSDL_Rect result;\n\t\tresult.x = x;\n\t\tresult.y = y;\n\t\tresult.w = w;\n\t\tresult.h = h;\n\t\treturn result;\n\t}\n\n\tstruct game_state\n\t{\n\t\tint x = 100;\n\t\tint y = 100;\n\t\tint count = 1;\n\t};\n\n\tint const max_rect_count = 5;\n\n\tframe draw_game_state(game_state const &state)\n\t{\n\t\tstd::vector<draw_operation> operations;\n\t\tfor (int i = 0; i < state.count; ++i)\n\t\t{\n\t\t\tint const max_width = 80;\n\t\t\tint const single_offset = (max_width \/ 2) \/ max_rect_count;\n\t\t\tint const total_offset = single_offset * i;\n\t\t\tint const width = max_width - total_offset * 2;\n\t\t\toperations.emplace_back(draw_filled_rect{make_color(0xff, 0x00, 0x00, 0xff), make_rect(state.x + total_offset, state.y + total_offset, width, width)});\n\t\t}\n\t\treturn frame\n\t\t{\n\t\t\tstd::move(operations)\n\t\t};\n\t}\n\n\tgame_state step_game_state(game_state previous, SDL_Event event_)\n\t{\n\t\tswitch (event_.type)\n\t\t{\n\t\tcase SDL_KEYUP:\n\t\t\t{\n\t\t\t\tswitch (event_.key.keysym.sym)\n\t\t\t\t{\n\t\t\t\tcase SDLK_LEFT:\n\t\t\t\t\tprevious.x -= 10;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_RIGHT:\n\t\t\t\t\tprevious.x += 10;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_UP:\n\t\t\t\t\tprevious.y -= 10;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_DOWN:\n\t\t\t\t\tprevious.y += 10;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_PLUS:\n\t\t\t\t\tprevious.count = std::min(max_rect_count, previous.count + 1);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_MINUS:\n\t\t\t\t\tprevious.count = std::max(1, previous.count - 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn previous;\n\t}\n\n\ttemplate <class Events>\n\tauto make_frames(Events &&input)\n\t{\n\t\tgame_state initial_state;\n\t\tauto interesting_input = rx::filter(std::forward<Events>(input), [](SDL_Event const &event_)\n\t\t{\n\t\t\treturn event_.type == SDL_KEYUP;\n\t\t});\n\t\treturn rx::transform(rx::make_finite_state_machine(interesting_input, initial_state, step_game_state), draw_game_state);\n\t}\n\n\tvoid set_render_draw_color(SDL_Renderer &renderer, SDL_Color color)\n\t{\n\t\tSDL_SetRenderDrawColor(&renderer, color.r, color.g, color.b, color.a);\n\t}\n\n\tstruct draw_operation_renderer : boost::static_visitor<>\n\t{\n\t\texplicit draw_operation_renderer(SDL_Renderer &sdl)\n\t\t\t: sdl(&sdl)\n\t\t{\n\t\t}\n\n\t\tvoid operator()(draw_filled_rect const &operation) const\n\t\t{\n\t\t\tset_render_draw_color(*sdl, operation.color);\n\t\t\tSDL_RenderDrawRect(sdl, &operation.where);\n\t\t}\n\n\tprivate:\n\n\t\tSDL_Renderer *sdl;\n\t};\n\n\tvoid render_frame(SDL_Renderer &sdl, frame const &frame_)\n\t{\n\t\tset_render_draw_color(sdl, make_color(0, 0, 0, 0xff));\n\t\tSDL_RenderClear(&sdl);\n\t\tfor (auto const &operation : frame_.operations)\n\t\t{\n\t\t\tboost::apply_visitor(draw_operation_renderer{sdl}, operation);\n\t\t}\n\t\tSDL_RenderPresent(&sdl);\n\t}\n\n\tstruct frame_renderer : rx::observer<frame>\n\t{\n\t\texplicit frame_renderer(SDL_Renderer &sdl)\n\t\t\t: sdl(&sdl)\n\t\t{\n\t\t}\n\n\t\tvirtual void got_element(frame value) SILICIUM_OVERRIDE\n\t\t{\n\t\t\trender_frame(*sdl, value);\n\t\t}\n\n\t\tvirtual void ended() SILICIUM_OVERRIDE\n\t\t{\n\t\t}\n\n\tprivate:\n\n\t\tSDL_Renderer *sdl;\n\t};\n\n\tstruct quitting\n\t{\n\t};\n\n\tstruct frame_rendered\n\t{\n\t};\n}\n\nint main()\n{\n\tcheck_sdl(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS));\n\tBOOST_SCOPE_EXIT(void)\n\t{\n\t\tSDL_Quit();\n\t}\n\tBOOST_SCOPE_EXIT_END;\n\n\tstd::unique_ptr<SDL_Window, window_destructor> window(SDL_CreateWindow(\"Silicium react.cpp\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, 0));\n\tif (!window)\n\t{\n\t\tthrow_error();\n\t\treturn 1;\n\t}\n\n\tstd::unique_ptr<SDL_Renderer, renderer_destructor> renderer(SDL_CreateRenderer(window.get(), -1, 0));\n\n\trx::bridge<SDL_Event> frame_events;\n\tauto frames = rx::wrap<frame>(make_frames(while_(rx::ref(frame_events), [](SDL_Event const &event_)\n\t{\n\t\tbool continue_ = event_.type != SDL_QUIT;\n\t\treturn continue_;\n\t})));\n\n\tboost::asio::io_service io;\n\n\tframe_renderer frame_renderer_(*renderer);\n\trx::timer frame_rate_limiter(io, boost::posix_time::milliseconds(16));\n\n\tauto all_rendered = make_total_consumer(rx::transform(rx::make_tuple(rx::ref(frame_rate_limiter), frames), [&renderer, &frame_events](std::tuple<rx::timer_elapsed, frame> const &ready_frame)\n\t{\n\t\tSDL_Event event;\n\t\twhile (frame_events.is_waiting() &&\n\t\t\t SDL_PollEvent(&event))\n\t\t{\n\t\t\tframe_events.got_element(event);\n\t\t}\n\n\t\trender_frame(*renderer, std::get<1>(ready_frame));\n\t\treturn frame_rendered{};\n\t}));\n\tall_rendered.start();\n\n\tio.run();\n}\n<commit_msg>remove an unused, empty struct<commit_after>#include <reactive\/bridge.hpp>\n#include <reactive\/ptr_observable.hpp>\n#include <reactive\/buffer.hpp>\n#include <reactive\/generate.hpp>\n#include <reactive\/tuple.hpp>\n#include <reactive\/transform.hpp>\n#include <reactive\/while.hpp>\n#include <reactive\/finite_state_machine.hpp>\n#include <reactive\/filter.hpp>\n#include <reactive\/timer.hpp>\n#include <reactive\/total_consumer.hpp>\n#include <SDL2\/SDL.h>\n#include <boost\/system\/system_error.hpp>\n#include <boost\/scope_exit.hpp>\n#include <boost\/variant.hpp>\n#include <boost\/asio.hpp>\n\nnamespace\n{\n\tvoid throw_error()\n\t{\n\t\tthrow std::runtime_error(std::string(\"SDL error :\") + SDL_GetError());\n\t}\n\n\tvoid check_sdl(int rc)\n\t{\n\t\tif (rc < 0)\n\t\t{\n\t\t\tthrow_error();\n\t\t}\n\t}\n\n\tstruct window_destructor\n\t{\n\t\tvoid operator()(SDL_Window *w) const\n\t\t{\n\t\t\tSDL_DestroyWindow(w);\n\t\t}\n\t};\n\n\tstruct renderer_destructor\n\t{\n\t\tvoid operator()(SDL_Renderer *r) const\n\t\t{\n\t\t\tSDL_DestroyRenderer(r);\n\t\t}\n\t};\n\n\tstruct draw_filled_rect\n\t{\n\t\tSDL_Color color;\n\t\tSDL_Rect where;\n\t};\n\n\ttypedef boost::variant<\n\t\tdraw_filled_rect\n\t> draw_operation;\n\n\tstruct frame\n\t{\n\t\tstd::vector<draw_operation> operations;\n\t};\n\n\tSDL_Color make_color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha)\n\t{\n\t\tSDL_Color result;\n\t\tresult.r = red;\n\t\tresult.g = green;\n\t\tresult.b = blue;\n\t\tresult.a = alpha;\n\t\treturn result;\n\t}\n\n\tSDL_Rect make_rect(int x, int y, int w, int h)\n\t{\n\t\tSDL_Rect result;\n\t\tresult.x = x;\n\t\tresult.y = y;\n\t\tresult.w = w;\n\t\tresult.h = h;\n\t\treturn result;\n\t}\n\n\tstruct game_state\n\t{\n\t\tint x = 100;\n\t\tint y = 100;\n\t\tint count = 1;\n\t};\n\n\tint const max_rect_count = 5;\n\n\tframe draw_game_state(game_state const &state)\n\t{\n\t\tstd::vector<draw_operation> operations;\n\t\tfor (int i = 0; i < state.count; ++i)\n\t\t{\n\t\t\tint const max_width = 80;\n\t\t\tint const single_offset = (max_width \/ 2) \/ max_rect_count;\n\t\t\tint const total_offset = single_offset * i;\n\t\t\tint const width = max_width - total_offset * 2;\n\t\t\toperations.emplace_back(draw_filled_rect{make_color(0xff, 0x00, 0x00, 0xff), make_rect(state.x + total_offset, state.y + total_offset, width, width)});\n\t\t}\n\t\treturn frame\n\t\t{\n\t\t\tstd::move(operations)\n\t\t};\n\t}\n\n\tgame_state step_game_state(game_state previous, SDL_Event event_)\n\t{\n\t\tswitch (event_.type)\n\t\t{\n\t\tcase SDL_KEYUP:\n\t\t\t{\n\t\t\t\tswitch (event_.key.keysym.sym)\n\t\t\t\t{\n\t\t\t\tcase SDLK_LEFT:\n\t\t\t\t\tprevious.x -= 10;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_RIGHT:\n\t\t\t\t\tprevious.x += 10;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_UP:\n\t\t\t\t\tprevious.y -= 10;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_DOWN:\n\t\t\t\t\tprevious.y += 10;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_PLUS:\n\t\t\t\t\tprevious.count = std::min(max_rect_count, previous.count + 1);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDLK_MINUS:\n\t\t\t\t\tprevious.count = std::max(1, previous.count - 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn previous;\n\t}\n\n\ttemplate <class Events>\n\tauto make_frames(Events &&input)\n\t{\n\t\tgame_state initial_state;\n\t\tauto interesting_input = rx::filter(std::forward<Events>(input), [](SDL_Event const &event_)\n\t\t{\n\t\t\treturn event_.type == SDL_KEYUP;\n\t\t});\n\t\treturn rx::transform(rx::make_finite_state_machine(interesting_input, initial_state, step_game_state), draw_game_state);\n\t}\n\n\tvoid set_render_draw_color(SDL_Renderer &renderer, SDL_Color color)\n\t{\n\t\tSDL_SetRenderDrawColor(&renderer, color.r, color.g, color.b, color.a);\n\t}\n\n\tstruct draw_operation_renderer : boost::static_visitor<>\n\t{\n\t\texplicit draw_operation_renderer(SDL_Renderer &sdl)\n\t\t\t: sdl(&sdl)\n\t\t{\n\t\t}\n\n\t\tvoid operator()(draw_filled_rect const &operation) const\n\t\t{\n\t\t\tset_render_draw_color(*sdl, operation.color);\n\t\t\tSDL_RenderDrawRect(sdl, &operation.where);\n\t\t}\n\n\tprivate:\n\n\t\tSDL_Renderer *sdl;\n\t};\n\n\tvoid render_frame(SDL_Renderer &sdl, frame const &frame_)\n\t{\n\t\tset_render_draw_color(sdl, make_color(0, 0, 0, 0xff));\n\t\tSDL_RenderClear(&sdl);\n\t\tfor (auto const &operation : frame_.operations)\n\t\t{\n\t\t\tboost::apply_visitor(draw_operation_renderer{sdl}, operation);\n\t\t}\n\t\tSDL_RenderPresent(&sdl);\n\t}\n\n\tstruct frame_renderer : rx::observer<frame>\n\t{\n\t\texplicit frame_renderer(SDL_Renderer &sdl)\n\t\t\t: sdl(&sdl)\n\t\t{\n\t\t}\n\n\t\tvirtual void got_element(frame value) SILICIUM_OVERRIDE\n\t\t{\n\t\t\trender_frame(*sdl, value);\n\t\t}\n\n\t\tvirtual void ended() SILICIUM_OVERRIDE\n\t\t{\n\t\t}\n\n\tprivate:\n\n\t\tSDL_Renderer *sdl;\n\t};\n\n\tstruct frame_rendered\n\t{\n\t};\n}\n\nint main()\n{\n\tcheck_sdl(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS));\n\tBOOST_SCOPE_EXIT(void)\n\t{\n\t\tSDL_Quit();\n\t}\n\tBOOST_SCOPE_EXIT_END;\n\n\tstd::unique_ptr<SDL_Window, window_destructor> window(SDL_CreateWindow(\"Silicium react.cpp\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, 0));\n\tif (!window)\n\t{\n\t\tthrow_error();\n\t\treturn 1;\n\t}\n\n\tstd::unique_ptr<SDL_Renderer, renderer_destructor> renderer(SDL_CreateRenderer(window.get(), -1, 0));\n\n\trx::bridge<SDL_Event> frame_events;\n\tauto frames = rx::wrap<frame>(make_frames(while_(rx::ref(frame_events), [](SDL_Event const &event_)\n\t{\n\t\tbool continue_ = event_.type != SDL_QUIT;\n\t\treturn continue_;\n\t})));\n\n\tboost::asio::io_service io;\n\n\tframe_renderer frame_renderer_(*renderer);\n\trx::timer frame_rate_limiter(io, boost::posix_time::milliseconds(16));\n\n\tauto all_rendered = make_total_consumer(rx::transform(rx::make_tuple(rx::ref(frame_rate_limiter), frames), [&renderer, &frame_events](std::tuple<rx::timer_elapsed, frame> const &ready_frame)\n\t{\n\t\tSDL_Event event;\n\t\twhile (frame_events.is_waiting() &&\n\t\t\t SDL_PollEvent(&event))\n\t\t{\n\t\t\tframe_events.got_element(event);\n\t\t}\n\n\t\trender_frame(*renderer, std::get<1>(ready_frame));\n\t\treturn frame_rendered{};\n\t}));\n\tall_rendered.start();\n\n\tio.run();\n}\n<|endoftext|>"} {"text":"<commit_before>\n\n#pragma pack(push,1)\nstruct FILE_Object3dHeader\n{\n int32_t Version;\n int32_t NumberOfVertexes;\n int32_t NumberOfPrimitives;\n int32_t OffsetToSelectionPrimitive;\/\/Appears to be index into primitive array\n int32_t XFromParent;\n int32_t YFromParent;\n int32_t ZFromParent;\n int32_t OffsetToObjectName;\n int32_t Always_0;\n int32_t OffsetToVertexArray;\n int32_t OffsetToPrimitiveArray;\n int32_t OffsetToSiblingObject;\n int32_t OffsetToChildObject;\n};\n\nstruct FILE_Object3dVertex\n{\n int32_t x;\n int32_t y;\n int32_t z;\n};\n\nstruct FILE_Object3dPrimitive\n{\n int32_t ColorIndex;\n int32_t NumberOfVertexIndexes;\n int32_t Always_0;\n int32_t OffsetToVertexIndexArray;\n int32_t OffsetToTextureName;\n \/\/Apparently Cavedog editor specific:\n int32_t Unknown_1;\n int32_t Unknown_2;\n int32_t Unknown_3; \n};\n#pragma pack(pop)\n\n\nstruct Position3d\n{\n double X,Y,Z;\n};\n\nstruct Object3d\n{\n char * Name;\n Object3d * Children;\n int NumberOfChildren;\n Position3d Position;\n int NumberOfPrimitives;\n struct Object3dPrimitive * Primitives;\n int NumberOfVertices;\n GLfloat * Vertices;\n GLuint VertexBuffer;\n int NumTriangles;\n};\n\nstruct Object3dPrimitive\n{\n Texture * Texture;\n int NumberOfVertices;\n int ColorIndex;\n int * VertexIndexes;\n};\n\n\n\nvoid FillObject3dData(GLfloat * Data, int CurrentTriangle,int * VertexIndices,GLfloat * UV, Texture * Texture, Object3d * Object, Object3dPrimitive * Primitive)\n{\n int Offset=CurrentTriangle*(3+2+3)*3;\n Data+=Offset;\n\n for(int i=0;i<3;i++)\n {\n\tData[i*8+0]=Object->Vertices[Primitive->VertexIndexes[VertexIndices[i]]*3+0];\n\tData[i*8+1]=Object->Vertices[Primitive->VertexIndexes[VertexIndices[i]]*3+1];\n\tData[i*8+2]=Object->Vertices[Primitive->VertexIndexes[VertexIndices[i]]*3+2];\n\n\tData[i*8+3]=Texture->U+Texture->Width*UV[i*2+0];\n\tData[i*8+4]=Texture->V+Texture->Height*UV[i*2+1];\n\t\n\n\tData[i*8+5]=(uint8_t)PaletteData[Primitive->ColorIndex*3+0]\/255.0;\n\tData[i*8+6]=(uint8_t)PaletteData[Primitive->ColorIndex*3+1]\/255.0;\n\tData[i*8+7]=(uint8_t)PaletteData[Primitive->ColorIndex*3+2]\/255.0;\n }\n}\n\nTexture NoTexture={\"\",0,-2,-2,-1,-1,0};\n\nbool32 PrepareObject3dForRendering(Object3d * Object)\n{\n if(Object->VertexBuffer)\n {\n\tglDeleteVertexArrays(1,&Object->VertexBuffer);\n }\n\n Object->NumTriangles=0;\n for(int i=0;i<Object->NumberOfPrimitives;i++)\n {\n\tObject->NumTriangles += Object->Primitives[i].NumberOfVertices-2>0?Object->Primitives[i].NumberOfVertices-2:0;\n }\n GLfloat Data[Object->NumTriangles * (3+2+3)*3];\/\/3 coord, 2 tex, 3 color\n \/\/NOTE: signal no texture in some way, perhaps negative texture coords?\n int CurrentTriangle=0;\n for(int PrimitiveIndex=0;PrimitiveIndex<Object->NumberOfPrimitives;PrimitiveIndex++)\n {\n\tObject3dPrimitive * CurrentPrimitive=&Object->Primitives[PrimitiveIndex];\n\tTexture * Texture=CurrentPrimitive->Texture;\n\tif(!Texture)\n\t Texture=&NoTexture;\n\tswitch(CurrentPrimitive->NumberOfVertices)\n\t{\n\tcase 1:\n\tcase 2:\n\t LogDebug(\"ignoring line or point (%d) in %s\",CurrentPrimitive->NumberOfVertices,Object->Name);\n\t break;\n\tcase 3:\n\t{\n\t GLfloat UVCoords[]={0,1, 1,1, 0,0};\n\t int Vertexes[]={0,1,2};\n\t FillObject3dData(Data,CurrentTriangle,Vertexes,UVCoords,Texture,Object,CurrentPrimitive);\n\t CurrentTriangle++;\n\t}\n\t break;\n\tcase 4:\n\t{\n\t GLfloat UVCoords1[]={1,0, 0,1, 1,1};\n\t int Vertexes1[]={0,2,3};\n\t FillObject3dData(Data,CurrentTriangle,Vertexes1,UVCoords1,Texture,Object,CurrentPrimitive);\n\t CurrentTriangle++;\n\t GLfloat UVCoords2[]={1,0, 0,0, 0,1};\n\t int Vertexes2[]={0,1,2};\n\t FillObject3dData(Data,CurrentTriangle,Vertexes2,UVCoords2,Texture,Object,CurrentPrimitive);\n\t CurrentTriangle++;\n\t}\n\t break;\n\tdefault:\n\t{\n\t GLfloat UVCoords[6];\n\t \/\/Map sin\/cos unit circle at (0,0) onto 1\/2 unit circle at (0.5,0.5)\n\t UVCoords[2*2]=0.5f*(1-(sin((2.0f*(CurrentPrimitive->NumberOfVertices-1)+1)*PI\/float(CurrentPrimitive->NumberOfVertices))\/cos(PI\/CurrentPrimitive->NumberOfVertices)));\n\t UVCoords[2*2+1]=0.5f*(1-(cos(PI\/CurrentPrimitive->NumberOfVertices*(2.0f*(CurrentPrimitive->NumberOfVertices-1)+1))\/cos(PI\/CurrentPrimitive->NumberOfVertices)));\n\n\t for(int i=0;i<CurrentPrimitive->NumberOfVertices-2;i++)\n\t {\n\t\tint Vertexes[]={i,i+1,CurrentPrimitive->NumberOfVertices-1};\n\t\t\t\n\t\tfor(int j=0;j<2;j++)\n\t\t{\n\t\t \/\/Map sin\/cos unit circle at (0,0) onto 1\/2 unit circle at (0.5,0.5)\n\t\t UVCoords[j*2]=0.5f*(1-(sin((2.0f*(i+j)+1)*PI\/float(CurrentPrimitive->NumberOfVertices))\/cos(PI\/CurrentPrimitive->NumberOfVertices)));\n\t\t UVCoords[j*2+1]=0.5f*(1-(cos(PI\/CurrentPrimitive->NumberOfVertices*(2.0f*(i+j)+1))\/cos(PI\/CurrentPrimitive->NumberOfVertices)));\n\t\t}\n\t\tFillObject3dData(Data,CurrentTriangle,Vertexes,UVCoords,Texture,Object,CurrentPrimitive);\n\t\tCurrentTriangle++;\n\t }\n\t}\n\t break;\n\t}\n }\n \n glGenVertexArrays(1,&Object->VertexBuffer);\n glBindVertexArray(Object->VertexBuffer);\n\n GLuint VertexBuffer;\n glGenBuffers(1,&VertexBuffer);\n\n glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer);\n glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*Object->NumTriangles*(3+2+3)*3,Data,GL_STATIC_DRAW);\n glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),0);\n glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),(GLvoid*)(sizeof(GLfloat)*3));\n\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n\n glVertexAttribPointer(2,3,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),(GLvoid*)(sizeof(GLfloat)*5));\n glEnableVertexAttribArray(2);\n\n glBindVertexArray(0);\n \/\/glDeleteBuffers(1,&VertexBuffer);\n\n for(int i=0;i<Object->NumberOfChildren;i++)\n {\n\tif(!PrepareObject3dForRendering(&Object->Children[i]))\n\t return 0;\n }\n\t \n \n return 1;\n}\n\nstruct Object3dTransformationDetails\n{\n \n};\n\nMatrix Identity={{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}};\nvoid RenderObject3d(Object3d * Object,Object3dTransformationDetails * TransformationDetails,GLuint ModelMatrixLocation, Matrix ParentMatrix=Identity)\n{\n \/\/TODO(Christof): Actually make use of TransformationDetails\n Matrix CurrentMatrix;\n SetTranslationMatrix(Object->Position.X,Object->Position.Y,Object->Position.Z,&CurrentMatrix);\n CurrentMatrix = CurrentMatrix * ParentMatrix;\n\n for(int i=0;i<Object->NumberOfChildren;i++)\n {\n\tRenderObject3d(&Object->Children[i],TransformationDetails,ModelMatrixLocation,CurrentMatrix);\n }\n UploadMatrix(&CurrentMatrix,ModelMatrixLocation);\n glBindVertexArray(Object->VertexBuffer);\n glDrawArrays(GL_TRIANGLES, 0, Object->NumTriangles*3);\n GLenum ErrorValue = glGetError();\n if(ErrorValue!=GL_NO_ERROR)\n {\n\tLogError(\"failed to render : %s\",gluErrorString(ErrorValue));\n }\n}\n\n\n\n\n\n\/\/TODO(Christof): Load Primitives from file to memory\n\/\/TODO(Christof): Generate Collision Meshes from Primitives?\n\/\/TODO(Christof): Generate Render Data from Primitives\n\n\n\/*TODO(Christof): Figure out if we can\/need to use bindless textures or something similar for rendering, for now lets just go with the simple solution\n Probably just load all the textures into one big (1024x1024 or 2048x2048 - will need to check what size we need) texture and use offsets, since the textures are all quite small*\/\n\nint Count3DOChildren(char * Buffer,FILE_Object3dHeader * header)\n{\n int NumChildren = 0;\n if(header->OffsetToChildObject)\n {\n\tNumChildren=1;\n\theader = (FILE_Object3dHeader *)(Buffer+header->OffsetToChildObject);\n\twhile(header->OffsetToSiblingObject)\n\t{\n\t header = (FILE_Object3dHeader *)(Buffer+header->OffsetToSiblingObject);\n\t NumChildren++;\n\t}\n }\n return NumChildren;\n}\n\n\nconst double TA_TO_GL_SCALE=1.0f\/2500000.0f;\n\nbool32 Load3DOFromBuffer(char * Buffer, Object3d * Object, int Offset=0)\n{\n FILE_Object3dHeader * header = (FILE_Object3dHeader *)(Buffer+Offset);\n if(header->Version != 1)\n {\n\tLogError(\"Unknown Version in 3DO file: %d\",header->Version);\n\treturn 0;\n }\n if(header->OffsetToSiblingObject && !Offset)\n {\n\tLogError(\"Top Level 3DO Objects should not have siblings!\");\n\treturn 0;\n }\n\n int NameLength=strlen(Buffer + header->OffsetToObjectName)+1;\n Object->Name = (char *)malloc(NameLength);\n memcpy(Object->Name,Buffer+header->OffsetToObjectName,NameLength);\n LogDebug(Object->Name);\n Object->Position.X=header->XFromParent*TA_TO_GL_SCALE;\n Object->Position.Y=header->YFromParent*TA_TO_GL_SCALE;\n Object->Position.Z=header->ZFromParent*TA_TO_GL_SCALE;\n\n FILE_Object3dPrimitive * Primitives=(FILE_Object3dPrimitive*)(Buffer+header->OffsetToPrimitiveArray);\n FILE_Object3dPrimitive * CurrentPrimitive = Primitives;\n Object->NumberOfPrimitives = header->NumberOfPrimitives;\n Object->Primitives = (Object3dPrimitive *)malloc(sizeof(Object3dPrimitive)*Object->NumberOfPrimitives);\n for(int i=0;i<header->NumberOfPrimitives;i++)\n {\n\tif(CurrentPrimitive->OffsetToTextureName)\n\t{\n\t Object->Primitives[i].Texture = GetTexture(Buffer+CurrentPrimitive->OffsetToTextureName,0);\n\t if(!Object->Primitives[i].Texture)\n\t {\n\t\tLogError(\"Could not get texture for primitive %d in %s, %s\",i,Object->Name,Buffer+CurrentPrimitive->OffsetToTextureName);\n\t }\n\t}\n\telse\n\t{\n\t Object->Primitives[i].Texture=0;\n\t}\n\tObject->Primitives[i].NumberOfVertices = CurrentPrimitive->NumberOfVertexIndexes;\n\tObject->Primitives[i].VertexIndexes = (int *)malloc(sizeof(int)*Object->Primitives[i].NumberOfVertices);\n\tint16_t * VertexIndexes = (int16_t *)(Buffer + CurrentPrimitive->OffsetToVertexIndexArray);\n\tfor(int j=0;j<Object->Primitives[i].NumberOfVertices;j++)\n\t Object->Primitives[i].VertexIndexes[j]=VertexIndexes[j];\n\t\n\tObject->Primitives[i].ColorIndex = CurrentPrimitive->ColorIndex&0xFF;\n\n\tCurrentPrimitive++;\n }\n\n Object->NumberOfVertices = header->NumberOfVertexes;\n Object->Vertices = (float *)malloc(sizeof(float)*3*Object->NumberOfVertices);\n\n FILE_Object3dVertex * Vertices= (FILE_Object3dVertex *)(Buffer + header->OffsetToVertexArray);\n for(int i=0;i<Object->NumberOfVertices;i++)\n {\n\tObject->Vertices[i*3+0]=Vertices[i].x*TA_TO_GL_SCALE;\n\tObject->Vertices[i*3+1]=Vertices[i].y*TA_TO_GL_SCALE;\n\tObject->Vertices[i*3+2]=Vertices[i].z*TA_TO_GL_SCALE;\n }\n \n \n\n Object->NumberOfChildren = Count3DOChildren(Buffer,header);\n Object->Children = (Object3d *)malloc(sizeof(Object3d)*Object->NumberOfChildren);\n int ChildOffset=header->OffsetToChildObject;\n for(int i=0;i<Object->NumberOfChildren;i++)\n {\n\tLoad3DOFromBuffer(Buffer, &(Object->Children[i]),ChildOffset);\n\theader = (FILE_Object3dHeader *)(Buffer+ChildOffset);\n\tChildOffset=header->OffsetToSiblingObject;\n }\n\n return 1;\n}\n\n\/**\n Frees all contents allocated by loading the object, leaving it in a state to be reused for loading without memory leaks\n **\/\nvoid Unload3DO(Object3d * Object)\n{\n if(!Object)\n\treturn;\n if(Object->Name)\n\tfree(Object->Name);\n if(Object->Vertices)\n\tfree(Object->Vertices);\n if(Object->Primitives)\n {\n\tfor(int i=0;i<Object->NumberOfPrimitives;i++)\n\t free(Object->Primitives[i].VertexIndexes);\n\tfree(Object->Primitives);\n }\n for(int i=0;i<Object->NumberOfChildren;i++)\n {\n\tUnload3DO(&Object->Children[i]);\n }\n if(Object->Children)\n\tfree(Object->Children);\n}\n<commit_msg>Fix color rendering<commit_after>\n\n#pragma pack(push,1)\nstruct FILE_Object3dHeader\n{\n int32_t Version;\n int32_t NumberOfVertexes;\n int32_t NumberOfPrimitives;\n int32_t OffsetToSelectionPrimitive;\/\/Appears to be index into primitive array\n int32_t XFromParent;\n int32_t YFromParent;\n int32_t ZFromParent;\n int32_t OffsetToObjectName;\n int32_t Always_0;\n int32_t OffsetToVertexArray;\n int32_t OffsetToPrimitiveArray;\n int32_t OffsetToSiblingObject;\n int32_t OffsetToChildObject;\n};\n\nstruct FILE_Object3dVertex\n{\n int32_t x;\n int32_t y;\n int32_t z;\n};\n\nstruct FILE_Object3dPrimitive\n{\n int32_t ColorIndex;\n int32_t NumberOfVertexIndexes;\n int32_t Always_0;\n int32_t OffsetToVertexIndexArray;\n int32_t OffsetToTextureName;\n \/\/Apparently Cavedog editor specific:\n int32_t Unknown_1;\n int32_t Unknown_2;\n int32_t Unknown_3; \n};\n#pragma pack(pop)\n\n\nstruct Position3d\n{\n double X,Y,Z;\n};\n\nstruct Object3d\n{\n char * Name;\n Object3d * Children;\n int NumberOfChildren;\n Position3d Position;\n int NumberOfPrimitives;\n struct Object3dPrimitive * Primitives;\n int NumberOfVertices;\n GLfloat * Vertices;\n GLuint VertexBuffer;\n int NumTriangles;\n};\n\nstruct Object3dPrimitive\n{\n Texture * Texture;\n int NumberOfVertices;\n int ColorIndex;\n int * VertexIndexes;\n};\n\n\n\nvoid FillObject3dData(GLfloat * Data, int CurrentTriangle,int * VertexIndices,GLfloat * UV, Texture * Texture, Object3d * Object, Object3dPrimitive * Primitive)\n{\n int Offset=CurrentTriangle*(3+2+3)*3;\n Data+=Offset;\n\n for(int i=0;i<3;i++)\n {\n\tData[i*8+0]=Object->Vertices[Primitive->VertexIndexes[VertexIndices[i]]*3+0];\n\tData[i*8+1]=Object->Vertices[Primitive->VertexIndexes[VertexIndices[i]]*3+1];\n\tData[i*8+2]=Object->Vertices[Primitive->VertexIndexes[VertexIndices[i]]*3+2];\n\n\tData[i*8+3]=Texture->U+Texture->Width*UV[i*2+0];\n\tData[i*8+4]=Texture->V+Texture->Height*UV[i*2+1];\n\t\n\n\tData[i*8+5]=(uint8_t)PaletteData[Primitive->ColorIndex*4+0]\/255.0;\n\tData[i*8+6]=(uint8_t)PaletteData[Primitive->ColorIndex*4+1]\/255.0;\n\tData[i*8+7]=(uint8_t)PaletteData[Primitive->ColorIndex*4+2]\/255.0;\n }\n}\n\nTexture NoTexture={\"\",0,-2,-2,-1,-1,0};\n\nbool32 PrepareObject3dForRendering(Object3d * Object)\n{\n if(Object->VertexBuffer)\n {\n\tglDeleteVertexArrays(1,&Object->VertexBuffer);\n }\n\n Object->NumTriangles=0;\n for(int i=0;i<Object->NumberOfPrimitives;i++)\n {\n\tObject->NumTriangles += Object->Primitives[i].NumberOfVertices-2>0?Object->Primitives[i].NumberOfVertices-2:0;\n }\n GLfloat Data[Object->NumTriangles * (3+2+3)*3];\/\/3 coord, 2 tex, 3 color\n \/\/NOTE: signal no texture in some way, perhaps negative texture coords?\n int CurrentTriangle=0;\n for(int PrimitiveIndex=0;PrimitiveIndex<Object->NumberOfPrimitives;PrimitiveIndex++)\n {\n\tObject3dPrimitive * CurrentPrimitive=&Object->Primitives[PrimitiveIndex];\n\tTexture * Texture=CurrentPrimitive->Texture;\n\tif(!Texture)\n\t Texture=&NoTexture;\n\tswitch(CurrentPrimitive->NumberOfVertices)\n\t{\n\tcase 1:\n\tcase 2:\n\t LogDebug(\"ignoring line or point (%d) in %s\",CurrentPrimitive->NumberOfVertices,Object->Name);\n\t break;\n\tcase 3:\n\t{\n\t GLfloat UVCoords[]={0,1, 1,1, 0,0};\n\t int Vertexes[]={0,1,2};\n\t FillObject3dData(Data,CurrentTriangle,Vertexes,UVCoords,Texture,Object,CurrentPrimitive);\n\t CurrentTriangle++;\n\t}\n\t break;\n\tcase 4:\n\t{\n\t GLfloat UVCoords1[]={1,0, 0,1, 1,1};\n\t int Vertexes1[]={0,2,3};\n\t FillObject3dData(Data,CurrentTriangle,Vertexes1,UVCoords1,Texture,Object,CurrentPrimitive);\n\t CurrentTriangle++;\n\t GLfloat UVCoords2[]={1,0, 0,0, 0,1};\n\t int Vertexes2[]={0,1,2};\n\t FillObject3dData(Data,CurrentTriangle,Vertexes2,UVCoords2,Texture,Object,CurrentPrimitive);\n\t CurrentTriangle++;\n\t}\n\t break;\n\tdefault:\n\t{\n\t GLfloat UVCoords[6];\n\t \/\/Map sin\/cos unit circle at (0,0) onto 1\/2 unit circle at (0.5,0.5)\n\t UVCoords[2*2]=0.5f*(1-(sin((2.0f*(CurrentPrimitive->NumberOfVertices-1)+1)*PI\/float(CurrentPrimitive->NumberOfVertices))\/cos(PI\/CurrentPrimitive->NumberOfVertices)));\n\t UVCoords[2*2+1]=0.5f*(1-(cos(PI\/CurrentPrimitive->NumberOfVertices*(2.0f*(CurrentPrimitive->NumberOfVertices-1)+1))\/cos(PI\/CurrentPrimitive->NumberOfVertices)));\n\n\t for(int i=0;i<CurrentPrimitive->NumberOfVertices-2;i++)\n\t {\n\t\tint Vertexes[]={i,i+1,CurrentPrimitive->NumberOfVertices-1};\n\t\t\t\n\t\tfor(int j=0;j<2;j++)\n\t\t{\n\t\t \/\/Map sin\/cos unit circle at (0,0) onto 1\/2 unit circle at (0.5,0.5)\n\t\t UVCoords[j*2]=0.5f*(1-(sin((2.0f*(i+j)+1)*PI\/float(CurrentPrimitive->NumberOfVertices))\/cos(PI\/CurrentPrimitive->NumberOfVertices)));\n\t\t UVCoords[j*2+1]=0.5f*(1-(cos(PI\/CurrentPrimitive->NumberOfVertices*(2.0f*(i+j)+1))\/cos(PI\/CurrentPrimitive->NumberOfVertices)));\n\t\t}\n\t\tFillObject3dData(Data,CurrentTriangle,Vertexes,UVCoords,Texture,Object,CurrentPrimitive);\n\t\tCurrentTriangle++;\n\t }\n\t}\n\t break;\n\t}\n }\n \n glGenVertexArrays(1,&Object->VertexBuffer);\n glBindVertexArray(Object->VertexBuffer);\n\n GLuint VertexBuffer;\n glGenBuffers(1,&VertexBuffer);\n\n glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer);\n glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*Object->NumTriangles*(3+2+3)*3,Data,GL_STATIC_DRAW);\n glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),0);\n glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),(GLvoid*)(sizeof(GLfloat)*3));\n\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n\n glVertexAttribPointer(2,3,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),(GLvoid*)(sizeof(GLfloat)*5));\n glEnableVertexAttribArray(2);\n\n glBindVertexArray(0);\n \/\/glDeleteBuffers(1,&VertexBuffer);\n\n for(int i=0;i<Object->NumberOfChildren;i++)\n {\n\tif(!PrepareObject3dForRendering(&Object->Children[i]))\n\t return 0;\n }\n\t \n \n return 1;\n}\n\nstruct Object3dTransformationDetails\n{\n \n};\n\nMatrix Identity={{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}};\nvoid RenderObject3d(Object3d * Object,Object3dTransformationDetails * TransformationDetails,GLuint ModelMatrixLocation, Matrix ParentMatrix=Identity)\n{\n \/\/TODO(Christof): Actually make use of TransformationDetails\n Matrix CurrentMatrix;\n SetTranslationMatrix(Object->Position.X,Object->Position.Y,Object->Position.Z,&CurrentMatrix);\n CurrentMatrix = CurrentMatrix * ParentMatrix;\n\n for(int i=0;i<Object->NumberOfChildren;i++)\n {\n\tRenderObject3d(&Object->Children[i],TransformationDetails,ModelMatrixLocation,CurrentMatrix);\n }\n UploadMatrix(&CurrentMatrix,ModelMatrixLocation);\n glBindVertexArray(Object->VertexBuffer);\n glDrawArrays(GL_TRIANGLES, 0, Object->NumTriangles*3);\n GLenum ErrorValue = glGetError();\n if(ErrorValue!=GL_NO_ERROR)\n {\n\tLogError(\"failed to render : %s\",gluErrorString(ErrorValue));\n }\n}\n\n\n\n\n\n\/\/TODO(Christof): Load Primitives from file to memory\n\/\/TODO(Christof): Generate Collision Meshes from Primitives?\n\/\/TODO(Christof): Generate Render Data from Primitives\n\n\n\/*TODO(Christof): Figure out if we can\/need to use bindless textures or something similar for rendering, for now lets just go with the simple solution\n Probably just load all the textures into one big (1024x1024 or 2048x2048 - will need to check what size we need) texture and use offsets, since the textures are all quite small*\/\n\nint Count3DOChildren(char * Buffer,FILE_Object3dHeader * header)\n{\n int NumChildren = 0;\n if(header->OffsetToChildObject)\n {\n\tNumChildren=1;\n\theader = (FILE_Object3dHeader *)(Buffer+header->OffsetToChildObject);\n\twhile(header->OffsetToSiblingObject)\n\t{\n\t header = (FILE_Object3dHeader *)(Buffer+header->OffsetToSiblingObject);\n\t NumChildren++;\n\t}\n }\n return NumChildren;\n}\n\n\nconst double TA_TO_GL_SCALE=1.0f\/2500000.0f;\n\nbool32 Load3DOFromBuffer(char * Buffer, Object3d * Object, int Offset=0)\n{\n FILE_Object3dHeader * header = (FILE_Object3dHeader *)(Buffer+Offset);\n if(header->Version != 1)\n {\n\tLogError(\"Unknown Version in 3DO file: %d\",header->Version);\n\treturn 0;\n }\n if(header->OffsetToSiblingObject && !Offset)\n {\n\tLogError(\"Top Level 3DO Objects should not have siblings!\");\n\treturn 0;\n }\n\n int NameLength=strlen(Buffer + header->OffsetToObjectName)+1;\n Object->Name = (char *)malloc(NameLength);\n memcpy(Object->Name,Buffer+header->OffsetToObjectName,NameLength);\n Object->Position.X=header->XFromParent*TA_TO_GL_SCALE;\n Object->Position.Y=header->YFromParent*TA_TO_GL_SCALE;\n Object->Position.Z=header->ZFromParent*TA_TO_GL_SCALE;\n\n FILE_Object3dPrimitive * Primitives=(FILE_Object3dPrimitive*)(Buffer+header->OffsetToPrimitiveArray);\n FILE_Object3dPrimitive * CurrentPrimitive = Primitives;\n Object->NumberOfPrimitives = header->NumberOfPrimitives;\n Object->Primitives = (Object3dPrimitive *)malloc(sizeof(Object3dPrimitive)*Object->NumberOfPrimitives);\n for(int i=0;i<header->NumberOfPrimitives;i++)\n {\n\tif(CurrentPrimitive->OffsetToTextureName)\n\t{\n\t Object->Primitives[i].Texture = GetTexture(Buffer+CurrentPrimitive->OffsetToTextureName,0);\n\t if(!Object->Primitives[i].Texture)\n\t {\n\t\tLogError(\"Could not get texture for primitive %d in %s, %s\",i,Object->Name,Buffer+CurrentPrimitive->OffsetToTextureName);\n\t }\n\t}\n\telse\n\t{\n\t Object->Primitives[i].Texture=0;\n\t}\n\tObject->Primitives[i].NumberOfVertices = CurrentPrimitive->NumberOfVertexIndexes;\n\tObject->Primitives[i].VertexIndexes = (int *)malloc(sizeof(int)*Object->Primitives[i].NumberOfVertices);\n\tint16_t * VertexIndexes = (int16_t *)(Buffer + CurrentPrimitive->OffsetToVertexIndexArray);\n\tfor(int j=0;j<Object->Primitives[i].NumberOfVertices;j++)\n\t Object->Primitives[i].VertexIndexes[j]=VertexIndexes[j];\n\t\n\tObject->Primitives[i].ColorIndex = CurrentPrimitive->ColorIndex & 255;\n\n\tCurrentPrimitive++;\n }\n\n Object->NumberOfVertices = header->NumberOfVertexes;\n Object->Vertices = (float *)malloc(sizeof(float)*3*Object->NumberOfVertices);\n\n FILE_Object3dVertex * Vertices= (FILE_Object3dVertex *)(Buffer + header->OffsetToVertexArray);\n for(int i=0;i<Object->NumberOfVertices;i++)\n {\n\tObject->Vertices[i*3+0]=Vertices[i].x*TA_TO_GL_SCALE;\n\tObject->Vertices[i*3+1]=Vertices[i].y*TA_TO_GL_SCALE;\n\tObject->Vertices[i*3+2]=Vertices[i].z*TA_TO_GL_SCALE;\n }\n \n \n\n Object->NumberOfChildren = Count3DOChildren(Buffer,header);\n Object->Children = (Object3d *)malloc(sizeof(Object3d)*Object->NumberOfChildren);\n int ChildOffset=header->OffsetToChildObject;\n for(int i=0;i<Object->NumberOfChildren;i++)\n {\n\tLoad3DOFromBuffer(Buffer, &(Object->Children[i]),ChildOffset);\n\theader = (FILE_Object3dHeader *)(Buffer+ChildOffset);\n\tChildOffset=header->OffsetToSiblingObject;\n }\n\n return 1;\n}\n\n\/**\n Frees all contents allocated by loading the object, leaving it in a state to be reused for loading without memory leaks\n **\/\nvoid Unload3DO(Object3d * Object)\n{\n if(!Object)\n\treturn;\n if(Object->Name)\n\tfree(Object->Name);\n if(Object->Vertices)\n\tfree(Object->Vertices);\n if(Object->Primitives)\n {\n\tfor(int i=0;i<Object->NumberOfPrimitives;i++)\n\t free(Object->Primitives[i].VertexIndexes);\n\tfree(Object->Primitives);\n }\n for(int i=0;i<Object->NumberOfChildren;i++)\n {\n\tUnload3DO(&Object->Children[i]);\n }\n if(Object->Children)\n\tfree(Object->Children);\n}\n<|endoftext|>"} {"text":"<commit_before>class Solution {\npublic:\n \/**\n * @param digits a number represented as an array of digits\n * @return the result\n *\/\n vector<int> plusOne(vector<int>& digits) {\n \/\/ Write your code here\n int i,j,k,n=digits.size();\n int tmp,s_tmp,jw=0;\n std::vector<int> vRev(digits.rbegin(),digits.rend());\n for (auto &s:vRev){\n \tcout<<s<<\" \";\n \ts_tmp=jw+s+1;\n \ts=s_tmp%10;\n \tcout<<s<<\";\";\n \tjw=s_tmp\/10; \t\n }\n if (jw>1) vRev.push_back(jw);\n\n std::vector<int> rt_v(vRev.rbegin(),vRev.rend());\n return rt_v;\n }\n};<commit_msg>Submit again<commit_after>class Solution {\npublic:\n \/**\n * @param digits a number represented as an array of digits\n * @return the result\n *\/\n vector<int> plusOne(vector<int>& digits) {\n \/\/ Write your code here\n int i,j,k,n=digits.size();\n int tmp,s_tmp,jw=0;\n std::vector<int> vRev(digits.rbegin(),digits.rend());\n for (auto &s:vRev){\n \t\/\/ cout<<s<<\" \";\n \ts_tmp=jw+s+1;\n \ts=s_tmp%10;\n \t\/\/ cout<<s<<\";\";\n \tjw=s_tmp\/10; \n \t\/\/ cout<<jw; \t\n }\n if (jw>=1) vRev.push_back(jw);\n\n std::vector<int> rt_v(vRev.rbegin(),vRev.rend());\n return rt_v;\n }\n};<|endoftext|>"} {"text":"<commit_before>class Solution {\npublic:\n \/**\n * @param s A string\n * @return whether the string is a valid parentheses\n *\/\n bool isValidParentheses(string& s) {\n \/\/ Write your code here\n }\n};<commit_msg>solving 423<commit_after>class Solution {\npublic:\n \/**\n * @param s A string\n * @return whether the string is a valid parentheses\n *\/\n\n deque<int> que1;\n map<char,int> baseOfPar;\n bool isValidParentheses(string& s) {\n \/\/ Write your code here\n\n \/\/init \n int i,j,k,l_s=s.size();\n string s_tem=s;\n\n baseOfPar['(']=1; baseOfPar[')']=4;\n baseOfPar['[']=2; baseOfPar[']']=5;\n baseOfPar['{']=3; baseOfPar['}']=6;\n\n \/\/loop\n for (i=0;i<l_s;i++){\n \tif \n }\n }\n\n};<|endoftext|>"} {"text":"<commit_before><commit_msg>Use OpenSSL return values for client_hello_cb<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma comment(lib,\"opengl32\")\n#define _USE_MATH_DEFINES\n#include <GL\\glew.h>\n#include <Windows.h>\n#include <CaveLib\\texture.h>\n#include <CaveLib\\model.h>\n#include \"App.h\"\n#include <glm\/gtc\/type_ptr.hpp>\n#include <functional>\n\nApp::App(WiiMoteWrapper* w)\n{\n\twiiMoteWrapper = w;\n}\nApp::~App(void){\n\tglUseProgram(0);\n\tglDeleteTextures(1, &fbo.fboTextureID);\n\tglDeleteTextures(1, &fbo.rboTextureID);\n\tglDeleteFramebuffers(1, &fbo.fboID);\n\tglDeleteRenderbuffers(1, &fbo.rboID);\n}\n\n\nvoid App::init(void)\n{\n\tscreenSize = glm::vec2(Kernel::getInstance()->getWindowWidth(), Kernel::getInstance()->getWindowHeight());\n\tm_pDebugDrawer = new DebugDrawer();\n\tm_pDebugDrawer->setDebugMode(3);\n\theadDevice.init(\"MainUserHead\");\n\tcameraDevice.init(\"CameraPosition\");\n\tphysics.bullet3Init();\n\tcube_model = CaveLib::loadModel(\"data\/aerial-pace-vr\/models\/cube.obj\", new ModelLoadOptions(300.0f));\n\tcheckers_model = CaveLib::loadModel(\"data\/aerial-pace-vr\/models\/checkers_sphere.obj\", new ModelLoadOptions(10.0f));\n\tsun_model = CaveLib::loadModel(\"data\/aerial-pace-vr\/models\/checkers_sphere.obj\", new ModelLoadOptions(10.0f));\n\tracetrack_model = CaveLib::loadModel(\"data\/aerial-pace-vr\/models\/racetrack.obj\", new ModelLoadOptions(100.0f));\n\tnormals_texture = CaveLib::loadTexture(\"data\/aerial-pace-vr\/textures\/normalmap3a.png\", new TextureLoadOptions(GL_FALSE));\n\tpointLight.position = glm::vec3(60.0f, 20.0f, -10.0f);\n\tpointLight.intensities = glm::vec3(1.0f, 1.0f, 1.0f);\n\tpointLight.ambientCoefficient = 0.6f;\n\tpointLight.attentuation = 0.2f;\n\tphysics.addFloor(racetrack_model);\n\n\tsimpleShader = new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/simple.vert\", \"data\/aerial-pace-vr\/shaders\/simple.frag\");\n\tsimpleShader->link();\n\n\tnoiseShader = new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/perlinnoise.vert\", \"data\/aerial-pace-vr\/shaders\/perlinnoise.frag\");\n\tnoiseShader->link();\n\n\tsunShader = new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/sunshader.vert\", \"data\/aerial-pace-vr\/shaders\/sunshader.frag\");\n\tsunShader->link();\n\n\tairnoiseShader = new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/airnoise.vert\", \"data\/aerial-pace-vr\/shaders\/airnoise.frag\");\n\tairnoiseShader->link();\n\n\tstd::vector<string> shaders;\n\tshaders.push_back(\"normalpostprocess\");\n\tshaders.push_back(\"blur\");\n\t\/\/shaders.push_back(\"threshold\");\n\tshaders.push_back(\"mirror1\");\n\tshaders.push_back(\"mirror2\"); \n\tshaders.push_back(\"mirror3\");\n\t\/\/shaders.push_back(\"draaien\");\n\tshaders.push_back(\"shining\");\n\n\tfor each (string shader in shaders)\n\t\tfbo.fboShaders.push_back(new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/fbo\/\"+shader+\".vert\", \"data\/aerial-pace-vr\/shaders\/fbo\/\"+shader+\".frag\"));\n\tfor each (ShaderProgram* program in fbo.fboShaders)\n\t{\n\t\tprogram->link();\n\t\tprogram->setUniformInt(\"s_texture\", 0);\n\t}\n\n\tphysics.world->setDebugDrawer(m_pDebugDrawer);\n\n\tglEnable(GL_DEPTH_TEST);\n\tglEnable(GL_CULL_FACE);\n\n\t\/\/fbo\n\tglGenTextures(1, &fbo.fboID);\n\tglBindTexture(GL_TEXTURE_2D, fbo.fboTextureID);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\tglGenFramebuffers(1, &fbo.fboID);\n\tglBindFramebuffer(GL_FRAMEBUFFER, fbo.fboID);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, screenSize.x, screenSize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo.fboTextureID, 0);\n\tglGenRenderbuffers(1, &fbo.rboID);\n\tglGenTextures(1, &fbo.rboTextureID);\n\tglBindTexture(1, fbo.rboTextureID);\n\tglBindRenderbuffer(GL_RENDERBUFFER, fbo.rboID);\n\tglRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, screenSize.x, screenSize.y);\n\tglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo.rboID);\t\n\t\/\/auto b = glewGetErrorString(glGetError());\n\tGLenum e = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);\n\tif (e != GL_FRAMEBUFFER_COMPLETE)\n\t\tprintf(\"There is a problem with the FBO\\n\");\n}\n\nvoid App::preFrame(double frameTime, double totalTime)\n{\n\t\/\/ timer\n\tclock_t clock_end = clock();\n\tGLfloat timeFctr = GLfloat(clock_end - clock_start) \/ CLOCKS_PER_SEC; \/\/ calculate time(s) elapsed since last frame\n\tfps = int(1 \/ timeFctr);\n\tclock_start = clock();\n\tif (GetAsyncKeyState(82) != 0){\n\t\t\/\/physics.addCar();\n\t}\n\n\tif (GetAsyncKeyState(VK_RIGHT)){\n\t\tif (nextTimeToCheck < clock()){\n\t\t\tfbo.currentShader++;\n\t\t\tfbo.currentShader %= fbo.fboShaders.size();\n\t\t\tnextTimeToCheck = clock() + 130;\n\t\t}\n\t}\n\n\tif (GetAsyncKeyState(VK_LEFT)){\n\t\tif (nextTimeToCheck < clock()){\n\t\t\tfbo.currentShader--;\n\t\t\tif (fbo.currentShader == -1)\n\t\t\t\tfbo.currentShader = fbo.fboShaders.size() - 1;\n\t\t\tnextTimeToCheck = clock() + 130;\n\t\t}\n\t}\n\n\t\/\/Check I\n\tif (GetAsyncKeyState(73) != 0)\n\t{\n\t\t\/\/wiiMoteWrapper->buttonOne = true;\n\t}\n\telse\n\t\t\/\/wiiMoteWrapper->buttonOne = false;\n\t\/\/Check J\n\tif (GetAsyncKeyState(74) != 0)\n\t{\n\t\t\/\/wiiMoteWrapper->degrees = -30;\n\t}\n\t\/\/Check K\n\tif (GetAsyncKeyState(75) != 0)\n\t{\n\t\t\/\/wiiMoteWrapper->buttonTwo = true;\n\t}\n\telse\n\t\t\/\/wiiMoteWrapper->buttonTwo = false;\n\t\/\/Check L\n\tif (GetAsyncKeyState(76) != 0)\n\t{\n\t\t\/\/wiiMoteWrapper->degrees = 30;\n\t}\n\tif (GetAsyncKeyState(74) == 0 && GetAsyncKeyState(76) == 0)\n\t\t\/\/wiiMoteWrapper->degrees = 0;\n\tphysics.updateCar(timeFctr,wiiMoteWrapper);\n}\n\nvoid App::draw(const glm::mat4 &projectionMatrix, const glm::mat4 &modelViewMatrix)\n{\n\tglBindFramebuffer(GL_FRAMEBUFFER, fbo.fboID);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglEnable(GL_TEXTURE_2D);\n\tglEnable(GL_COLOR_MATERIAL);\n\n\tfloat mvpRaw[16];\n\tphysics.realCar->getWorldTransform().getOpenGLMatrix(mvpRaw);\n\n\t\/\/ Car\n\tbtVector3 carTranslation = physics.realCar->getWorldTransform().getOrigin();\n\tglm::vec3 cameraPosition(0, 0, 10.0f);\n\tglm::vec3 glmCarTranslation(-carTranslation.x(), -carTranslation.y() - 2, -carTranslation.z());\n\n\t\/\/ Devices\n\tglm::mat4 headData = headDevice.getData();\n\tglm::mat4 viewMatrix = modelViewMatrix * headData;\n\n\t\/\/ Update the uniform time variable.\n\tGLfloat time = GLfloat(clock()) \/ GLfloat(CLOCKS_PER_SEC);\n\n\t\/\/ Mvp\n\tglm::mat4 mvp = projectionMatrix * viewMatrix; \/\/ glm::mat4 mvp = projectionMatrix * modelViewMatrix;\n\tmvp = glm::rotate(mvp, -physics.realCar->getWorldTransform().getRotation().getAngle(), glm::vec3(0, 1, 0));\n\tmvp = glm::translate(mvp, glmCarTranslation);\n\n\t\/\/ Sun\n\tfloat scale = 0.3f;\n\tglm::mat4 sunMat4 = mvp;\n\tsunMat4 = glm::translate(sunMat4, pointLight.position);\n\tsunMat4 = glm::scale(sunMat4, glm::vec3(scale, scale, scale));\n\t\n\t\/\/ Cube Model (Air)\n\tairnoiseShader->use();\n\tairnoiseShader->setUniformFloat(\"time\", time);\n\tairnoiseShader->setUniformMatrix4(\"modelViewProjectionMatrix\", glm::translate(mvp, glm::vec3(-150.0f, -100.0f, 150.0f)));\n\tcube_model->draw(airnoiseShader);\n\n\t\/\/ Checkers Model\n\tsimpleShader->use();\n\tsimpleShader->setUniformInt(\"s_texture\", 0);\n\tglUniform1i(simpleShader->getUniformLocation(\"s_normals\"), 1);\n\tglBindTexture(GL_TEXTURE_2D, normals_texture->tid());\n\tsimpleShader->setUniformMatrix4(\"modelViewMatrix\", modelViewMatrix);\n\tsimpleShader->setUniformVec3(\"light.position\", pointLight.position);\n\tsimpleShader->setUniformVec3(\"light.intensities\", pointLight.intensities);\n\tsimpleShader->setUniformFloat(\"light.attenuation\", pointLight.attentuation);\n\tsimpleShader->setUniformFloat(\"light.ambientCoefficient\", pointLight.ambientCoefficient);\n\tsimpleShader->setUniformFloat(\"time\", time);\n\tsimpleShader->setUniformVec3(\"materialSpecularColor\", glm::vec3(1.0f, 1.0f, 1.0f));\n\tsimpleShader->setUniformFloat(\"materialShininess\", 5.0f);\n\tsimpleShader->setUniformVec3(\"cameraPosition\", extractCameraPosition(mvp));\n\tsimpleShader->setUniformMatrix4(\"modelViewProjectionMatrix\", mvp);\n\tcheckers_model->draw(simpleShader);\n\n\t\/\/ Sun\n\tsunShader->use();\n\tsunShader->setUniformMatrix4(\"modelViewMatrix\", modelViewMatrix);\n\tsunShader->setUniformFloat(\"time\", time);\n\tsunShader->setUniformMatrix4(\"modelViewProjectionMatrix\", sunMat4);\n\tsunShader->setUniformVec2(\"screenSize\", screenSize);\n\tsunShader->setUniformVec3(\"lightPosition\", pointLight.position);\n\tsun_model->draw(sunShader);\n\n\t\/\/ Racetrack\n\tnoiseShader->use();\n\tglUniform1i(noiseShader->getUniformLocation(\"s_normals\"), 0);\n\tglBindTexture(GL_TEXTURE_2D, normals_texture->tid());\n\tnoiseShader->setUniformMatrix4(\"modelViewMatrix\", modelViewMatrix);\n\tnoiseShader->setUniformVec3(\"light.position\", pointLight.position);\n\tnoiseShader->setUniformVec3(\"light.intensities\", pointLight.intensities);\n\tnoiseShader->setUniformFloat(\"light.attenuation\", pointLight.attentuation);\n\tnoiseShader->setUniformFloat(\"light.ambientCoefficient\", pointLight.ambientCoefficient);\n\tnoiseShader->setUniformFloat(\"time\", time);\n\tnoiseShader->setUniformVec3(\"materialSpecularColor\", glm::vec3(1.0f, 1.0f, 1.0f));\n\tnoiseShader->setUniformVec3(\"cameraPosition\", extractCameraPosition(mvp));\n\tnoiseShader->setUniformFloat(\"materialShininess\", 5.0f);\n\tnoiseShader->setUniformMatrix4(\"modelViewProjectionMatrix\", mvp);\n\tracetrack_model->draw(noiseShader);\n\tphysics.world->debugDrawWorld();\n\n\tglBindFramebuffer(GL_FRAMEBUFFER, 0);\n\tglViewport(0, 0, screenSize.x, screenSize.y);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tstd::vector<glm::vec2> verts;\n\tverts.push_back(glm::vec2(-1, -1));\n\tverts.push_back(glm::vec2(1, -1));\n\tverts.push_back(glm::vec2(1, 1));\n\tverts.push_back(glm::vec2(-1, 1));\n\n\t\/\/glBindBuffer(GL_ARRAY_BUFFER, 0);\n\tShaderProgram* curFBOShader = fbo.fboShaders[fbo.currentShader];\n\tcurFBOShader->use();\n\tcurFBOShader->setUniformFloat(\"time\", time);\n\tcurFBOShader->setUniformVec2(\"screenSize\", screenSize);\n\tcurFBOShader->setUniformVec3(\"lightPosition\", pointLight.position);\n\tcurFBOShader->setUniformMatrix4(\"mvp\", modelViewMatrix);\n\t\/\/curFBOShader->setUniformInt(\"s_texture\", 0);\n\tglBindVertexArray(0);\n\tglEnableVertexAttribArray(0);\t\t\t\t\t\t\t\/\/ en vertex attribute 1\n\tglDisableVertexAttribArray(1);\t\t\t\t\t\t\t\/\/ disable vertex attribute 1\n\tglDisableVertexAttribArray(2);\t\t\t\t\t\t\t\/\/ disable vertex attribute 1\n\tglBindTexture(GL_TEXTURE_2D, fbo.fboTextureID);\n\tglVertexAttribPointer(0, 2, GL_FLOAT, false, 2 * 4, &verts[0]);\t\t\t\t\t\t\t\t\t\/\/geef aan dat de posities op deze locatie zitten\n\tglDrawArrays(GL_QUADS, 0, verts.size());\n\tglBindTexture(GL_TEXTURE_2D, 0);\n\tglDisableVertexAttribArray(0);\n\tglUseProgram(0);\n}\n\n\/\/ No Scaling\nglm::vec3 App::extractCameraPosition(const glm::mat4 &modelView)\n{\n\tglm::mat3 rotMat = glm::mat3(modelView);\n\tglm::vec3 d(modelView[3]);\n\treturn -d * rotMat;\n}\n<commit_msg>oculus rift support<commit_after>#pragma comment(lib,\"opengl32\")\n#define _USE_MATH_DEFINES\n#include <GL\\glew.h>\n#include <Windows.h>\n#include <CaveLib\\texture.h>\n#include <CaveLib\\model.h>\n#include \"App.h\"\n#include <glm\/gtc\/type_ptr.hpp>\n#include <functional>\n\nApp::App(WiiMoteWrapper* w)\n{\n\twiiMoteWrapper = w;\n}\nApp::~App(void){\n\tglUseProgram(0);\n\tglDeleteTextures(1, &fbo.fboTextureID);\n\tglDeleteTextures(1, &fbo.rboTextureID);\n\tglDeleteFramebuffers(1, &fbo.fboID);\n\tglDeleteRenderbuffers(1, &fbo.rboID);\n}\n\n\nvoid App::init(void)\n{\n\tscreenSize = glm::vec2(Kernel::getInstance()->getWindowWidth(), Kernel::getInstance()->getWindowHeight());\n\tm_pDebugDrawer = new DebugDrawer();\n\tm_pDebugDrawer->setDebugMode(3);\n\theadDevice.init(\"MainUserHead\");\n\tcameraDevice.init(\"CameraPosition\");\n\tphysics.bullet3Init();\n\tcube_model = CaveLib::loadModel(\"data\/aerial-pace-vr\/models\/cube.obj\", new ModelLoadOptions(300.0f));\n\tcheckers_model = CaveLib::loadModel(\"data\/aerial-pace-vr\/models\/checkers_sphere.obj\", new ModelLoadOptions(10.0f));\n\tsun_model = CaveLib::loadModel(\"data\/aerial-pace-vr\/models\/checkers_sphere.obj\", new ModelLoadOptions(10.0f));\n\tracetrack_model = CaveLib::loadModel(\"data\/aerial-pace-vr\/models\/racetrack.obj\", new ModelLoadOptions(100.0f));\n\tnormals_texture = CaveLib::loadTexture(\"data\/aerial-pace-vr\/textures\/normalmap3a.png\", new TextureLoadOptions(GL_FALSE));\n\tpointLight.position = glm::vec3(60.0f, 20.0f, -10.0f);\n\tpointLight.intensities = glm::vec3(1.0f, 1.0f, 1.0f);\n\tpointLight.ambientCoefficient = 0.6f;\n\tpointLight.attentuation = 0.2f;\n\tphysics.addFloor(racetrack_model);\n\n\tsimpleShader = new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/simple.vert\", \"data\/aerial-pace-vr\/shaders\/simple.frag\");\n\tsimpleShader->link();\n\n\tnoiseShader = new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/perlinnoise.vert\", \"data\/aerial-pace-vr\/shaders\/perlinnoise.frag\");\n\tnoiseShader->link();\n\n\tsunShader = new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/sunshader.vert\", \"data\/aerial-pace-vr\/shaders\/sunshader.frag\");\n\tsunShader->link();\n\n\tairnoiseShader = new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/airnoise.vert\", \"data\/aerial-pace-vr\/shaders\/airnoise.frag\");\n\tairnoiseShader->link();\n\n\tstd::vector<string> shaders;\n\tshaders.push_back(\"normalpostprocess\");\n\tshaders.push_back(\"blur\");\n\t\/\/shaders.push_back(\"threshold\");\n\tshaders.push_back(\"mirror1\");\n\tshaders.push_back(\"mirror2\"); \n\tshaders.push_back(\"mirror3\");\n\t\/\/shaders.push_back(\"draaien\");\n\tshaders.push_back(\"shining\");\n\t\/\/shaders.push_back(\"sunprocessing\");\n\n\tfor each (string shader in shaders)\n\t\tfbo.fboShaders.push_back(new ShaderProgram(\"data\/aerial-pace-vr\/shaders\/fbo\/\"+shader+\".vert\", \"data\/aerial-pace-vr\/shaders\/fbo\/\"+shader+\".frag\"));\n\tfor each (ShaderProgram* program in fbo.fboShaders)\n\t{\n\t\tprogram->link();\n\t\tprogram->setUniformInt(\"s_texture\", 0);\n\t}\n\n\tphysics.world->setDebugDrawer(m_pDebugDrawer);\n\n\tglEnable(GL_DEPTH_TEST);\n\tglEnable(GL_CULL_FACE);\n\n\t\/\/fbo\n\tGLint oldFbo;\n\tglGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFbo);\n\tglGenTextures(1, &fbo.fboID);\n\tglBindTexture(GL_TEXTURE_2D, fbo.fboTextureID);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\tglGenFramebuffers(1, &fbo.fboID);\n\tglBindFramebuffer(GL_FRAMEBUFFER, fbo.fboID);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, screenSize.x, screenSize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo.fboTextureID, 0);\n\tglGenRenderbuffers(1, &fbo.rboID);\n\tglGenTextures(1, &fbo.rboTextureID);\n\tglBindTexture(1, fbo.rboTextureID);\n\tglBindRenderbuffer(GL_RENDERBUFFER, fbo.rboID);\n\tglRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, screenSize.x, screenSize.y);\n\tglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo.rboID);\t\n\t\/\/auto b = glewGetErrorString(glGetError());\n\tGLenum e = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);\n\tif (e != GL_FRAMEBUFFER_COMPLETE)\n\t\tprintf(\"There is a problem with the FBO\\n\");\n\tglBindFramebuffer(GL_FRAMEBUFFER, oldFbo);\n}\n\nvoid App::preFrame(double frameTime, double totalTime)\n{\n\t\/\/ timer\n\tclock_t clock_end = clock();\n\tGLfloat timeFctr = GLfloat(clock_end - clock_start) \/ CLOCKS_PER_SEC; \/\/ calculate time(s) elapsed since last frame\n\tfps = int(1 \/ timeFctr);\n\tclock_start = clock();\n\tif (GetAsyncKeyState(82) != 0){\n\t\t\/\/physics.addCar();\n\t}\n\n\tif (GetAsyncKeyState(VK_RIGHT)){\n\t\tif (nextTimeToCheck < clock()){\n\t\t\tfbo.currentShader++;\n\t\t\tfbo.currentShader %= fbo.fboShaders.size();\n\t\t\tnextTimeToCheck = clock() + 200;\n\t\t}\n\t}\n\n\tif (GetAsyncKeyState(VK_LEFT)){\n\t\tif (nextTimeToCheck < clock()){\n\t\t\tfbo.currentShader--;\n\t\t\tif (fbo.currentShader == -1)\n\t\t\t\tfbo.currentShader = fbo.fboShaders.size() - 1;\n\t\t\tnextTimeToCheck = clock() + 200;\n\t\t}\n\t}\n\n\t\/\/Check I\n\tif (GetAsyncKeyState(73) != 0)\n\t{\n\t\twiiMoteWrapper->buttonOne = true;\n\t}\n\telse\n\t\twiiMoteWrapper->buttonOne = false;\n\t\/\/Check J\n\tif (GetAsyncKeyState(74) != 0)\n\t{\n\t\twiiMoteWrapper->degrees = -30;\n\t}\n\t\/\/Check K\n\tif (GetAsyncKeyState(75) != 0)\n\t{\n\t\twiiMoteWrapper->buttonTwo = true;\n\t}\n\telse\n\t\twiiMoteWrapper->buttonTwo = false;\n\t\/\/Check L\n\tif (GetAsyncKeyState(76) != 0)\n\t{\n\t\twiiMoteWrapper->degrees = 30;\n\t}\n\tif (GetAsyncKeyState(74) == 0 && GetAsyncKeyState(76) == 0)\n\t\twiiMoteWrapper->degrees = 0;\n\tphysics.updateCar(timeFctr,wiiMoteWrapper);\n}\n\nvoid App::draw(const glm::mat4 &projectionMatrix, const glm::mat4 &modelViewMatrix)\n{\n\tGLint oldFbo;\n\tglGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFbo);\n\n\tGLint viewport[4];\n\tglGetIntegerv(GL_VIEWPORT, viewport);\n\t\/\/if (viewport[0] == viewport[2]){\t\tviewport[2] = screenSize.x;\t}\n\t\/\/glBindFramebuffer(GL_FRAMEBUFFER, fbo.fboID);\n \t\/\/glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tglViewport(viewport[0], viewport[1], viewport[2], viewport[3]);\n\n\tglEnable(GL_TEXTURE_2D);\n\tglEnable(GL_COLOR_MATERIAL);\n\n\tfloat mvpRaw[16];\n\tphysics.realCar->getWorldTransform().getOpenGLMatrix(mvpRaw);\n\n\t\/\/ Car\n\tbtVector3 carTranslation = physics.realCar->getWorldTransform().getOrigin();\n\tglm::vec3 cameraPosition(0, 0, 10.0f);\n\tglm::vec3 glmCarTranslation(-carTranslation.x(), -carTranslation.y() - 2, -carTranslation.z());\n\n\t\/\/ Devices\n\tglm::mat4 headData = headDevice.getData();\n\tglm::mat4 viewMatrix = modelViewMatrix * headData;\n\n\t\/\/ Update the uniform time variable.\n\tGLfloat time = GLfloat(clock()) \/ GLfloat(CLOCKS_PER_SEC);\n\n\t\/\/ Mvp\n\tglm::mat4 mvp = projectionMatrix * viewMatrix; \/\/ glm::mat4 mvp = projectionMatrix * modelViewMatrix;\n\tmvp = glm::rotate(mvp, -physics.realCar->getWorldTransform().getRotation().getAngle(), glm::vec3(0, 1, 0));\n\tmvp = glm::translate(mvp, glmCarTranslation);\n\n\t\/\/ Sun\n\tfloat scale = 0.3f;\n\tglm::mat4 sunMat4 = mvp;\n\tsunMat4 = glm::translate(sunMat4, pointLight.position);\n\tsunMat4 = glm::scale(sunMat4, glm::vec3(scale, scale, scale));\n\n\t\/\/ Cube Model (Air)\n\tairnoiseShader->use();\n\tairnoiseShader->setUniformFloat(\"time\", time);\n\tairnoiseShader->setUniformMatrix4(\"modelViewProjectionMatrix\", glm::translate(mvp, glm::vec3(-150.0f, -100.0f, 150.0f)));\n\tcube_model->draw(airnoiseShader);\n\n\t\/\/ Checkers Model\n\tsimpleShader->use();\n\tsimpleShader->setUniformInt(\"s_texture\", 0);\n\tglUniform1i(simpleShader->getUniformLocation(\"s_normals\"), 1);\n\tglBindTexture(GL_TEXTURE_2D, normals_texture->tid());\n\tsimpleShader->setUniformMatrix4(\"modelViewMatrix\", modelViewMatrix);\n\tsimpleShader->setUniformVec3(\"light.position\", pointLight.position);\n\tsimpleShader->setUniformVec3(\"light.intensities\", pointLight.intensities);\n\tsimpleShader->setUniformFloat(\"light.attenuation\", pointLight.attentuation);\n\tsimpleShader->setUniformFloat(\"light.ambientCoefficient\", pointLight.ambientCoefficient);\n\tsimpleShader->setUniformFloat(\"time\", time);\n\tsimpleShader->setUniformVec3(\"materialSpecularColor\", glm::vec3(1.0f, 1.0f, 1.0f));\n\tsimpleShader->setUniformFloat(\"materialShininess\", 5.0f);\n\tsimpleShader->setUniformVec3(\"cameraPosition\", extractCameraPosition(mvp));\n\tsimpleShader->setUniformMatrix4(\"modelViewProjectionMatrix\", mvp);\n\tcheckers_model->draw(simpleShader);\n\n\t\/\/ Sun\n\tsunShader->use();\n\tsunShader->setUniformMatrix4(\"modelViewMatrix\", modelViewMatrix);\n\tsunShader->setUniformFloat(\"time\", time);\n\tsunShader->setUniformMatrix4(\"modelViewProjectionMatrix\", sunMat4);\n\tsunShader->setUniformVec2(\"screenSize\", screenSize);\n\tsunShader->setUniformVec3(\"lightPosition\", pointLight.position);\n\tsun_model->draw(sunShader);\n\n\t\/\/ Racetrack\n\tnoiseShader->use();\n\tglUniform1i(noiseShader->getUniformLocation(\"s_normals\"), 0);\n\tglBindTexture(GL_TEXTURE_2D, normals_texture->tid());\n\tnoiseShader->setUniformMatrix4(\"modelViewMatrix\", modelViewMatrix);\n\tnoiseShader->setUniformVec3(\"light.position\", pointLight.position);\n\tnoiseShader->setUniformVec3(\"light.intensities\", pointLight.intensities);\n\tnoiseShader->setUniformFloat(\"light.attenuation\", pointLight.attentuation);\n\tnoiseShader->setUniformFloat(\"light.ambientCoefficient\", pointLight.ambientCoefficient);\n\tnoiseShader->setUniformFloat(\"time\", time);\n\tnoiseShader->setUniformVec3(\"materialSpecularColor\", glm::vec3(1.0f, 1.0f, 1.0f));\n\tnoiseShader->setUniformVec3(\"cameraPosition\", extractCameraPosition(mvp));\n\tnoiseShader->setUniformFloat(\"materialShininess\", 5.0f);\n\tnoiseShader->setUniformMatrix4(\"modelViewProjectionMatrix\", mvp);\n\tracetrack_model->draw(noiseShader);\n\tphysics.world->debugDrawWorld();\n\n\t\/\/glBindFramebuffer(GL_FRAMEBUFFER, oldFbo);\n\t\/\/glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);\n\t\/\/glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\t\/\/std::vector<glm::vec2> verts;\n\t\/\/verts.push_back(glm::vec2(-1, -1));\n\t\/\/verts.push_back(glm::vec2(1, -1));\n\t\/\/verts.push_back(glm::vec2(1, 1));\n\t\/\/verts.push_back(glm::vec2(-1, 1));\n\n\t\/\/\/\/glBindBuffer(GL_ARRAY_BUFFER, 0);\n\t\/\/ShaderProgram* curFBOShader = fbo.fboShaders[fbo.currentShader];\n\t\/\/curFBOShader->use();\n\t\/\/curFBOShader->setUniformFloat(\"time\", time);\n\t\/\/curFBOShader->setUniformVec2(\"screenSize\", screenSize);\n\t\/\/curFBOShader->setUniformVec3(\"lightPosition\", pointLight.position);\n\t\/\/\/\/curFBOShader->setUniformInt(\"s_texture\", 0);\n\t\/\/glBindVertexArray(0);\n\t\/\/glEnableVertexAttribArray(0); \/\/ en vertex attribute 1\n\t\/\/glDisableVertexAttribArray(1); \/\/ disable vertex attribute 1\n\t\/\/glDisableVertexAttribArray(2); \/\/ disable vertex attribute 1\n\t\/\/glBindTexture(GL_TEXTURE_2D, fbo.fboTextureID);\n\t\/\/glVertexAttribPointer(0, 2, GL_FLOAT, false, 2 * 4, &verts[0]); \/\/geef aan dat de posities op deze locatie zitten\n\t\/\/glDrawArrays(GL_QUADS, 0, verts.size());\n\t\/\/glBindTexture(GL_TEXTURE_2D, 0);\n\t\/\/glDisableVertexAttribArray(0);\n\tglUseProgram(0);\n}\n\n\/\/ No Scaling\nglm::vec3 App::extractCameraPosition(const glm::mat4 &modelView)\n{\n\tglm::mat3 rotMat = glm::mat3(modelView);\n\tglm::vec3 d(modelView[3]);\n\treturn -d * rotMat;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n*\tCar.cpp\n*\/\n#include \"Smartcar.h\"\n\/* --- CAR --- *\/\n\nconst unsigned short Car::DEFAULT_PID_LOOP_INTERVAL = 80;\nconst unsigned short Car::STANDARD = 1;\nconst unsigned short Car::INVERTED = 0; \nconst float Car::DEFAULT_KP = 5.0;\nconst float Car::DEFAULT_KI = 0.0;\nconst float Car::DEFAULT_KD = 10.0;\n\nconst unsigned short BACKWARD = 0;\nconst unsigned short FORWARD = 1;\nconst unsigned short IDLE = 2;\n\nconst int IDLE_RAW_SPEED = 0;\nconst int MAX_FRONT_RAW_SPEED = 255;\nconst int MAX_BACK_RAW_SPEED = -255;\nconst float MAX_BACK_CRUISE_SPEED = -3.0;\nconst float MAX_FRONT_CRUISE_SPEED = 3.0;\nconst int STRAIGHT_WHEELS = 90;\nconst int STRAIGHT_ANGLE = 0;\nconst int MAX_RIGHT_DEGREES = 180;\nconst int MAX_LEFT_DEGREES = 0;\nconst float GO_CRUISE_SPEED = 1.3;\nconst int GO_RAW_SPEED = 200;\nconst int MAX_RIGHT_STEERING_ANGLE = MAX_RIGHT_DEGREES - STRAIGHT_WHEELS;\nconst int MAX_LEFT_STEERING_ANGLE = MAX_LEFT_DEGREES - STRAIGHT_WHEELS;\n\nCar::Car(const unsigned short setup){\n\t_cruiseControl = false;\n\t_speed = IDLE_RAW_SPEED;\n\t_angle = STRAIGHT_WHEELS;\n\t_numOfEncoders = 0;\n\tif (setup == STANDARD){ \/\/the default motor setup, where right is right\n\t\tMOTOR_LEFT1_PIN = 8;\n\t\tMOTOR_LEFT_EN_PIN = 9;\n\t\tMOTOR_LEFT2_PIN = 10;\n\t\tMOTOR_RIGHT_EN_PIN = 11;\n\t\tMOTOR_RIGHT1_PIN = 12;\n\t\tMOTOR_RIGHT2_PIN = 13;\n\t}else{ \/\/the reversed motor setup, where right is left\n\t\tMOTOR_RIGHT1_PIN = 8;\n\t\tMOTOR_RIGHT_EN_PIN = 9;\n\t\tMOTOR_RIGHT2_PIN = 10;\n\t\tMOTOR_LEFT_EN_PIN = 11;\n\t\tMOTOR_LEFT1_PIN = 12;\n\t\tMOTOR_LEFT2_PIN = 13;\n\t}\n}\n\nvoid Car::begin(){\n\tfor (uint8_t i = MOTOR_LEFT1_PIN; i <= MOTOR_RIGHT2_PIN; i++) {\n\t\tpinMode(i, OUTPUT); \/\/declare pins as outputs\n\t}\n\tsetSpeed(IDLE_RAW_SPEED);\n\tsetAngle(STRAIGHT_ANGLE);\n}\n\nvoid Car::begin(Odometer encoder){\n\t_encoders[0] = encoder;\n\t_numOfEncoders = 1;\n\tbegin();\n}\n\nvoid Car::begin(Gyroscope gyro){\n\t_gyro = gyro;\n\tbegin();\n}\n\nvoid Car::begin(Odometer encoder, Gyroscope gyro){\n\t_encoders[0] = encoder;\n\t_numOfEncoders = 1;\n\t_gyro = gyro;\n\tbegin();\n}\n\nvoid Car::begin(Odometer encoder1, Odometer encoder2){\n\t_encoders[0] = encoder1;\n\t_encoders[1] = encoder2;\n\t_numOfEncoders = 2;\n\tbegin();\n}\n\nvoid Car::begin(Odometer encoder1, Odometer encoder2, Gyroscope gyro){\n\t_encoders[0] = encoder1;\n\t_encoders[1] = encoder2;\n\t_numOfEncoders = 2;\n\t_gyro = gyro;\n\tbegin();\n}\n\nvoid Car::setSpeed(float newSpeed){\n\tif (cruiseControlEnabled()){\n\t\tif (_speed && (_speed != IDLE_RAW_SPEED) && (newSpeed * _speed) <= 0) stop(); \/\/if the speeds are signed differently, stop the car and then set the new speed. Ignore this if the speed is already 0 and if speed is at the idle raw speed i.e. leftovers from non-cruise control mode (if IDLE_RAW_SPEED is not 0, it makes sense)\n\t\t_speed = constrain(newSpeed, MAX_BACK_CRUISE_SPEED, MAX_FRONT_CRUISE_SPEED);\n\t}else{\n\t\t_speed = constrain(int(newSpeed), MAX_BACK_RAW_SPEED, MAX_FRONT_RAW_SPEED);\n\t\tsetMotors(_speed, getAngle());\n\t}\n}\n\nvoid Car::updateMotors(){\n\tif (cruiseControlEnabled() && (millis() > _lastMotorUpdate + _pidLoopInterval)){\n\t\tif (_speed){ \/\/if _speed is 0, we have already made sure the car is stopped. don't try to adjust if car is just drifting\n\t\t\tfloat measuredSpeed = getGroundSpeed(); \/\/speed in cm\/milliseconds\n\t\t\tmeasuredSpeed *= 10; \/\/transform it into m\/seconds, divide by 100 to turn cm into m and multiply by 1000, to turn ms to sec\n\t\t\tif (_speed < 0) measuredSpeed *= -1; \/\/if we are going reverse, illustrate that in the value of measuredSpeed\n\t\t\tint controlledSpeed = motorPIDcontrol(_previousControlledSpeed, _speed, measuredSpeed);\n\t\t\tsetMotors(controlledSpeed, getAngle());\n\t\t\t_previousControlledSpeed = controlledSpeed;\n\t\t}\n\t\t_lastMotorUpdate = millis();\n\t}\n}\n\nint Car::motorPIDcontrol(const int previousSpeed, const float targetSpeed, const float actualSpeed){\n\tfloat correction = 0;\n\tfloat error = targetSpeed - actualSpeed;\n\t_integratedError += error;\n\tcorrection = (_Kp * error) + (_Ki * _integratedError) + (_Kd * (error - _previousError)); \n\t_previousError = error;\n\treturn constrain(previousSpeed + int(correction), MAX_BACK_RAW_SPEED, MAX_FRONT_RAW_SPEED);\n}\n\nfloat Car::getGroundSpeed(){\n\tunsigned long currentDistance = getEncoderDistance();\n\tunsigned long dX = currentDistance - _previousDistance;\n\t_previousDistance = currentDistance;\n\tunsigned long dT = millis() - _lastMotorUpdate;\n\tfloat velocity = float(dX)\/ float(dT);\n\treturn velocity;\t\n}\n\nvoid Car::setMotors(int rawSpeed, int angle){ \/\/platform specific method\n\tif (rawSpeed < 0){\n\t\tsetDirection(BACKWARD);\t\n\t}else if (rawSpeed > 0){\n\t\tsetDirection(FORWARD);\n\t}else{\n\t\tsetDirection(IDLE);\n\t}\n\trawSpeed = abs(rawSpeed);\n\tfloat ratio = (STRAIGHT_WHEELS - abs(angle));\n\tratio \/= STRAIGHT_WHEELS;\n\tif (angle>0){ \/\/going to the right\n\t\tanalogWrite(MOTOR_LEFT_EN_PIN, rawSpeed);\n\t\tanalogWrite(MOTOR_RIGHT_EN_PIN, int(rawSpeed * ratio));\n\t}else{ \/\/going to the left or straight\n\t\tanalogWrite(MOTOR_RIGHT_EN_PIN, rawSpeed);\n\t\tanalogWrite(MOTOR_LEFT_EN_PIN, int(rawSpeed * ratio));\n\t}\n\t\n\t \n}\n\nvoid Car::setDirection(const unsigned short direction){ \/\/platform specific method\n\tif (direction == BACKWARD){\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, HIGH);\n\t}else if (direction == FORWARD){\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, LOW);\t\n\t}else{\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, LOW);\t\n\t}\n}\n\nvoid Car::setAngle(int angle){ \/\/platform specific method\n\t_angle = constrain(angle, MAX_LEFT_DEGREES - STRAIGHT_WHEELS, MAX_RIGHT_DEGREES - STRAIGHT_WHEELS); \/\/constrain the value to the permitted valued the user is allowed to supply\n\tsetMotors(getSpeed(), getAngle()); \/\/pass the human-readable value that was just supplied\n}\n\nvoid Car::stop(){ \/\/platform specific method\n\tif (getSpeed()>0){\n\t\tsetMotors(-100, getAngle());\n\t}else if(getSpeed()<0){\n\t\tsetMotors(100, getAngle());\n\t}\n\tdelay(80); \/\/go the opposite direction for a few milliseconds, to make sure we are stopped\n\tif (cruiseControlEnabled()){\n\t\tsetMotors(0,getAngle()); \/\/shut the engines down, we should be stopped by now\n\t\tenableCruiseControl(_Kp,_Ki,_Kd); \/\/re-initialize the cruise control, se we get rid of previous error and pid output\n\t\t_speed = 0.0;\n\t}else{\n\t\tsetSpeed(0); \/\/no circular dependency between stop and setSpeed due to the cruiseControlEnabled switching between who uses what\n\t}\n}\n\nfloat Car::getSpeed(){\n\tif (cruiseControlEnabled()) return getGroundSpeed(); \/\/return speed in meters per second\n\treturn _speed; \/\/return speed in PWM output\n}\n\nint Car::getAngle(){\n\treturn _angle; \/\/return what the user supplied\n}\n\nvoid Car::enableCruiseControl(float Kp, float Ki, float Kd, unsigned short pidLoopInterval){\n\t_cruiseControl = true;\n\t_pidLoopInterval = pidLoopInterval;\n\t_lastMotorUpdate = 0;\n\t_previousControlledSpeed = IDLE_RAW_SPEED;\n\t_previousDistance = getEncoderDistance();\n\t_integratedError = 0;\n\t_Kp = Kp;\n\t_Ki = Ki;\n\t_Kd = Kd;\n}\n\nvoid Car::disableCruiseControl(){\n\t_cruiseControl = false;\n\t_speed = _previousControlledSpeed; \/\/update the speed with the PWM equivalent\n}\n\nboolean Car::cruiseControlEnabled(){\n\treturn _cruiseControl;\n}\n\nunsigned long Car::getEncoderDistance(){\n\tunsigned long averageDistance = 0;\n\tfor (int i = 0; i < _numOfEncoders; i++){\n\t\taverageDistance += _encoders[i].getDistance() \/ _numOfEncoders;\n\t}\n\treturn averageDistance;\n}\n\nvoid Car::initializeEncoders(){\n\tfor (int i = 0; i < _numOfEncoders; i++){\n\t\t_encoders[i].begin();\n\t}\n}\n\nvoid Car::go(int centimeters){\n\tunsigned long initialDistance = getEncoderDistance(); \/\/save the current distance the car has covered\n\tfloat initialSpeed = getSpeed(); \/\/save the current speed (so we restore it later)\n\tint initialAngle = getAngle(); \/\/save the current angle (so we restore it later)\n\tunsigned long targetDistance = initialDistance + abs(centimeters); \/\/how much the car should move, always a positive number\n\tif (initialDistance > targetDistance){ \/\/this will occur only if the unsigned long variable overflows\n\t\tinitializeEncoders(); \/\/reinitialize the encoders counter to 0\n\t\ttargetDistance = abs(centimeters); \/\/now the new target is just the centimeters (since the encoder distance is 0)\n\t}\n\tsetAngle(STRAIGHT_ANGLE); \/\/set the angle straight\n\tshort direction = 1;\n\tif (centimeters < 0) direction = -1; \/\/if the user supplied a negative argument, means they want to move backwards\n\tif (cruiseControlEnabled()){ \/\/depending on whether the cruise control is enabled set the speed\n\t\tsetSpeed(direction * GO_CRUISE_SPEED);\n\t}else{\n\t\tsetSpeed(direction * GO_RAW_SPEED);\n\t}\n\twhile (getEncoderDistance() < targetDistance){ \/\/while we haven't reached the target distance, keep moving\n\t\tif (cruiseControlEnabled()) updateMotors(); \/\/otherwise the pid for the motors won't work\n\t}\n\tsetSpeed(initialSpeed); \/\/restore to the initial speed\n\tsetAngle(initialAngle); \/\/restore to the inital angle\t\n}\nvoid Car::rotate(int targetDegrees){\n\t_gyro.begin(); \/\/initialize the gyro\n\tfloat initialSpeed = getSpeed(); \/\/save the current speed (so we restore it later)\n\tint initialAngle = getAngle(); \/\/save the current angle (so we restore it later)\n\tif (targetDegrees > 0){ \/\/we should turn to the right (clockwise)\n\t\tsetAngle(MAX_RIGHT_STEERING_ANGLE); \/\/turn right as steep as you can\n\t}else{ \/\/turn left (counterclockwise)\n\t\tsetAngle(MAX_LEFT_STEERING_ANGLE); \/\/turn left as steep as you can\n\t}\n\tif (cruiseControlEnabled()){ \/\/depending on whether the cruise control is enabled set the speed\n\t\tsetSpeed(GO_CRUISE_SPEED);\n\t}else{\n\t\tsetSpeed(GO_RAW_SPEED);\n\t}\n\twhile (abs(_gyro.getAngularDisplacement()) < abs(targetDegrees)){ \/\/while the absolute displacement hasn't reached the (absolute) target, keep turning\n\t\tif (cruiseControlEnabled()) updateMotors(); \/\/otherwise the pid for the motors won't work\n\t\t_gyro.update(); \/\/update to integrate the latest gyroscope readings\n\t}\n\tsetSpeed(initialSpeed); \/\/restore to the initial speed\n\tsetAngle(initialAngle); \/\/restore to the inital angle\n}\n\nvoid Car::setMotorSpeed(int leftMotorSpeed, int rightMotorSpeed){ \/\/will set the speed manual to each motor, use with caution\n\tif (cruiseControlEnabled()) return; \/\/we don't want to be manually messing with the speed, during cruise control\n\tleftMotorSpeed = constrain(leftMotorSpeed, MAX_BACK_RAW_SPEED, MAX_FRONT_RAW_SPEED); \/\/constrain the speed within the allowed limits\n\trightMotorSpeed = constrain(rightMotorSpeed, MAX_BACK_RAW_SPEED, MAX_FRONT_RAW_SPEED);\n\tif (leftMotorSpeed<0){ \/\/set left direction backwards\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, HIGH);\n\t}else{ \/\/front\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, LOW);\t\n\t}\n\t\tanalogWrite(MOTOR_LEFT_EN_PIN, abs(leftMotorSpeed));\/\/write left speed\n\tif (rightMotorSpeed<0){ \/\/set right direction backwards\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, HIGH);\n\t}else{ \/\/front\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, LOW);\t\t\n\t}\n\t\tanalogWrite(MOTOR_RIGHT_EN_PIN, abs(rightMotorSpeed));\/\/write right speed\n}\n<commit_msg>go works only if encoders were attached)<commit_after>\/*\n*\tCar.cpp\n*\/\n#include \"Smartcar.h\"\n\/* --- CAR --- *\/\n\nconst unsigned short Car::DEFAULT_PID_LOOP_INTERVAL = 80;\nconst unsigned short Car::STANDARD = 1;\nconst unsigned short Car::INVERTED = 0; \nconst float Car::DEFAULT_KP = 5.0;\nconst float Car::DEFAULT_KI = 0.0;\nconst float Car::DEFAULT_KD = 10.0;\n\nconst unsigned short BACKWARD = 0;\nconst unsigned short FORWARD = 1;\nconst unsigned short IDLE = 2;\n\nconst int IDLE_RAW_SPEED = 0;\nconst int MAX_FRONT_RAW_SPEED = 255;\nconst int MAX_BACK_RAW_SPEED = -255;\nconst float MAX_BACK_CRUISE_SPEED = -3.0;\nconst float MAX_FRONT_CRUISE_SPEED = 3.0;\nconst int STRAIGHT_WHEELS = 90;\nconst int STRAIGHT_ANGLE = 0;\nconst int MAX_RIGHT_DEGREES = 180;\nconst int MAX_LEFT_DEGREES = 0;\nconst float GO_CRUISE_SPEED = 1.3;\nconst int GO_RAW_SPEED = 200;\nconst int MAX_RIGHT_STEERING_ANGLE = MAX_RIGHT_DEGREES - STRAIGHT_WHEELS;\nconst int MAX_LEFT_STEERING_ANGLE = MAX_LEFT_DEGREES - STRAIGHT_WHEELS;\n\nCar::Car(const unsigned short setup){\n\t_cruiseControl = false;\n\t_speed = IDLE_RAW_SPEED;\n\t_angle = STRAIGHT_WHEELS;\n\t_numOfEncoders = 0;\n\tif (setup == STANDARD){ \/\/the default motor setup, where right is right\n\t\tMOTOR_LEFT1_PIN = 8;\n\t\tMOTOR_LEFT_EN_PIN = 9;\n\t\tMOTOR_LEFT2_PIN = 10;\n\t\tMOTOR_RIGHT_EN_PIN = 11;\n\t\tMOTOR_RIGHT1_PIN = 12;\n\t\tMOTOR_RIGHT2_PIN = 13;\n\t}else{ \/\/the reversed motor setup, where right is left\n\t\tMOTOR_RIGHT1_PIN = 8;\n\t\tMOTOR_RIGHT_EN_PIN = 9;\n\t\tMOTOR_RIGHT2_PIN = 10;\n\t\tMOTOR_LEFT_EN_PIN = 11;\n\t\tMOTOR_LEFT1_PIN = 12;\n\t\tMOTOR_LEFT2_PIN = 13;\n\t}\n}\n\nvoid Car::begin(){\n\tfor (uint8_t i = MOTOR_LEFT1_PIN; i <= MOTOR_RIGHT2_PIN; i++) {\n\t\tpinMode(i, OUTPUT); \/\/declare pins as outputs\n\t}\n\tsetSpeed(IDLE_RAW_SPEED);\n\tsetAngle(STRAIGHT_ANGLE);\n}\n\nvoid Car::begin(Odometer encoder){\n\t_encoders[0] = encoder;\n\t_numOfEncoders = 1;\n\tbegin();\n}\n\nvoid Car::begin(Gyroscope gyro){\n\t_gyro = gyro;\n\tbegin();\n}\n\nvoid Car::begin(Odometer encoder, Gyroscope gyro){\n\t_encoders[0] = encoder;\n\t_numOfEncoders = 1;\n\t_gyro = gyro;\n\tbegin();\n}\n\nvoid Car::begin(Odometer encoder1, Odometer encoder2){\n\t_encoders[0] = encoder1;\n\t_encoders[1] = encoder2;\n\t_numOfEncoders = 2;\n\tbegin();\n}\n\nvoid Car::begin(Odometer encoder1, Odometer encoder2, Gyroscope gyro){\n\t_encoders[0] = encoder1;\n\t_encoders[1] = encoder2;\n\t_numOfEncoders = 2;\n\t_gyro = gyro;\n\tbegin();\n}\n\nvoid Car::setSpeed(float newSpeed){\n\tif (cruiseControlEnabled()){\n\t\tif (_speed && (_speed != IDLE_RAW_SPEED) && (newSpeed * _speed) <= 0) stop(); \/\/if the speeds are signed differently, stop the car and then set the new speed. Ignore this if the speed is already 0 and if speed is at the idle raw speed i.e. leftovers from non-cruise control mode (if IDLE_RAW_SPEED is not 0, it makes sense)\n\t\t_speed = constrain(newSpeed, MAX_BACK_CRUISE_SPEED, MAX_FRONT_CRUISE_SPEED);\n\t}else{\n\t\t_speed = constrain(int(newSpeed), MAX_BACK_RAW_SPEED, MAX_FRONT_RAW_SPEED);\n\t\tsetMotors(_speed, getAngle());\n\t}\n}\n\nvoid Car::updateMotors(){\n\tif (cruiseControlEnabled() && (millis() > _lastMotorUpdate + _pidLoopInterval)){\n\t\tif (_speed){ \/\/if _speed is 0, we have already made sure the car is stopped. don't try to adjust if car is just drifting\n\t\t\tfloat measuredSpeed = getGroundSpeed(); \/\/speed in cm\/milliseconds\n\t\t\tmeasuredSpeed *= 10; \/\/transform it into m\/seconds, divide by 100 to turn cm into m and multiply by 1000, to turn ms to sec\n\t\t\tif (_speed < 0) measuredSpeed *= -1; \/\/if we are going reverse, illustrate that in the value of measuredSpeed\n\t\t\tint controlledSpeed = motorPIDcontrol(_previousControlledSpeed, _speed, measuredSpeed);\n\t\t\tsetMotors(controlledSpeed, getAngle());\n\t\t\t_previousControlledSpeed = controlledSpeed;\n\t\t}\n\t\t_lastMotorUpdate = millis();\n\t}\n}\n\nint Car::motorPIDcontrol(const int previousSpeed, const float targetSpeed, const float actualSpeed){\n\tfloat correction = 0;\n\tfloat error = targetSpeed - actualSpeed;\n\t_integratedError += error;\n\tcorrection = (_Kp * error) + (_Ki * _integratedError) + (_Kd * (error - _previousError)); \n\t_previousError = error;\n\treturn constrain(previousSpeed + int(correction), MAX_BACK_RAW_SPEED, MAX_FRONT_RAW_SPEED);\n}\n\nfloat Car::getGroundSpeed(){\n\tunsigned long currentDistance = getEncoderDistance();\n\tunsigned long dX = currentDistance - _previousDistance;\n\t_previousDistance = currentDistance;\n\tunsigned long dT = millis() - _lastMotorUpdate;\n\tfloat velocity = float(dX)\/ float(dT);\n\treturn velocity;\t\n}\n\nvoid Car::setMotors(int rawSpeed, int angle){ \/\/platform specific method\n\tif (rawSpeed < 0){\n\t\tsetDirection(BACKWARD);\t\n\t}else if (rawSpeed > 0){\n\t\tsetDirection(FORWARD);\n\t}else{\n\t\tsetDirection(IDLE);\n\t}\n\trawSpeed = abs(rawSpeed);\n\tfloat ratio = (STRAIGHT_WHEELS - abs(angle));\n\tratio \/= STRAIGHT_WHEELS;\n\tif (angle>0){ \/\/going to the right\n\t\tanalogWrite(MOTOR_LEFT_EN_PIN, rawSpeed);\n\t\tanalogWrite(MOTOR_RIGHT_EN_PIN, int(rawSpeed * ratio));\n\t}else{ \/\/going to the left or straight\n\t\tanalogWrite(MOTOR_RIGHT_EN_PIN, rawSpeed);\n\t\tanalogWrite(MOTOR_LEFT_EN_PIN, int(rawSpeed * ratio));\n\t}\n\t\n\t \n}\n\nvoid Car::setDirection(const unsigned short direction){ \/\/platform specific method\n\tif (direction == BACKWARD){\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, HIGH);\n\t}else if (direction == FORWARD){\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, LOW);\t\n\t}else{\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, LOW);\t\n\t}\n}\n\nvoid Car::setAngle(int angle){ \/\/platform specific method\n\t_angle = constrain(angle, MAX_LEFT_DEGREES - STRAIGHT_WHEELS, MAX_RIGHT_DEGREES - STRAIGHT_WHEELS); \/\/constrain the value to the permitted valued the user is allowed to supply\n\tsetMotors(getSpeed(), getAngle()); \/\/pass the human-readable value that was just supplied\n}\n\nvoid Car::stop(){ \/\/platform specific method\n\tif (getSpeed()>0){\n\t\tsetMotors(-100, getAngle());\n\t}else if(getSpeed()<0){\n\t\tsetMotors(100, getAngle());\n\t}\n\tdelay(80); \/\/go the opposite direction for a few milliseconds, to make sure we are stopped\n\tif (cruiseControlEnabled()){\n\t\tsetMotors(0,getAngle()); \/\/shut the engines down, we should be stopped by now\n\t\tenableCruiseControl(_Kp,_Ki,_Kd); \/\/re-initialize the cruise control, se we get rid of previous error and pid output\n\t\t_speed = 0.0;\n\t}else{\n\t\tsetSpeed(0); \/\/no circular dependency between stop and setSpeed due to the cruiseControlEnabled switching between who uses what\n\t}\n}\n\nfloat Car::getSpeed(){\n\tif (cruiseControlEnabled()) return getGroundSpeed(); \/\/return speed in meters per second\n\treturn _speed; \/\/return speed in PWM output\n}\n\nint Car::getAngle(){\n\treturn _angle; \/\/return what the user supplied\n}\n\nvoid Car::enableCruiseControl(float Kp, float Ki, float Kd, unsigned short pidLoopInterval){\n\t_cruiseControl = true;\n\t_pidLoopInterval = pidLoopInterval;\n\t_lastMotorUpdate = 0;\n\t_previousControlledSpeed = IDLE_RAW_SPEED;\n\t_previousDistance = getEncoderDistance();\n\t_integratedError = 0;\n\t_Kp = Kp;\n\t_Ki = Ki;\n\t_Kd = Kd;\n}\n\nvoid Car::disableCruiseControl(){\n\t_cruiseControl = false;\n\t_speed = _previousControlledSpeed; \/\/update the speed with the PWM equivalent\n}\n\nboolean Car::cruiseControlEnabled(){\n\treturn _cruiseControl;\n}\n\nunsigned long Car::getEncoderDistance(){\n\tunsigned long averageDistance = 0;\n\tfor (int i = 0; i < _numOfEncoders; i++){\n\t\taverageDistance += _encoders[i].getDistance() \/ _numOfEncoders;\n\t}\n\treturn averageDistance;\n}\n\nvoid Car::initializeEncoders(){\n\tfor (int i = 0; i < _numOfEncoders; i++){\n\t\t_encoders[i].begin();\n\t}\n}\n\nvoid Car::go(int centimeters){\n\tif (_numOfEncoders){ \/\/do this, only if encoders were attached\n\t\tunsigned long initialDistance = getEncoderDistance(); \/\/save the current distance the car has covered\n\t\tfloat initialSpeed = getSpeed(); \/\/save the current speed (so we restore it later)\n\t\tint initialAngle = getAngle(); \/\/save the current angle (so we restore it later)\n\t\tunsigned long targetDistance = initialDistance + abs(centimeters); \/\/how much the car should move, always a positive number\n\t\tif (initialDistance > targetDistance){ \/\/this will occur only if the unsigned long variable overflows\n\t\t\tinitializeEncoders(); \/\/reinitialize the encoders counter to 0\n\t\t\ttargetDistance = abs(centimeters); \/\/now the new target is just the centimeters (since the encoder distance is 0)\n\t\t}\n\t\tsetAngle(STRAIGHT_ANGLE); \/\/set the angle straight\n\t\tshort direction = 1;\n\t\tif (centimeters < 0) direction = -1; \/\/if the user supplied a negative argument, means they want to move backwards\n\t\tif (cruiseControlEnabled()){ \/\/depending on whether the cruise control is enabled set the speed\n\t\t\tsetSpeed(direction * GO_CRUISE_SPEED);\n\t\t}else{\n\t\t\tsetSpeed(direction * GO_RAW_SPEED);\n\t\t}\n\t\twhile (getEncoderDistance() < targetDistance){ \/\/while we haven't reached the target distance, keep moving\n\t\t\tif (cruiseControlEnabled()) updateMotors(); \/\/otherwise the pid for the motors won't work\n\t\t}\n\t\tsetSpeed(initialSpeed); \/\/restore to the initial speed\n\t\tsetAngle(initialAngle); \/\/restore to the inital angle\n\t}\t\n}\nvoid Car::rotate(int targetDegrees){\n\t_gyro.begin(); \/\/initialize the gyro\n\tfloat initialSpeed = getSpeed(); \/\/save the current speed (so we restore it later)\n\tint initialAngle = getAngle(); \/\/save the current angle (so we restore it later)\n\tif (targetDegrees > 0){ \/\/we should turn to the right (clockwise)\n\t\tsetAngle(MAX_RIGHT_STEERING_ANGLE); \/\/turn right as steep as you can\n\t}else{ \/\/turn left (counterclockwise)\n\t\tsetAngle(MAX_LEFT_STEERING_ANGLE); \/\/turn left as steep as you can\n\t}\n\tif (cruiseControlEnabled()){ \/\/depending on whether the cruise control is enabled set the speed\n\t\tsetSpeed(GO_CRUISE_SPEED);\n\t}else{\n\t\tsetSpeed(GO_RAW_SPEED);\n\t}\n\twhile (abs(_gyro.getAngularDisplacement()) < abs(targetDegrees)){ \/\/while the absolute displacement hasn't reached the (absolute) target, keep turning\n\t\tif (cruiseControlEnabled()) updateMotors(); \/\/otherwise the pid for the motors won't work\n\t\t_gyro.update(); \/\/update to integrate the latest gyroscope readings\n\t}\n\tsetSpeed(initialSpeed); \/\/restore to the initial speed\n\tsetAngle(initialAngle); \/\/restore to the inital angle\n}\n\nvoid Car::setMotorSpeed(int leftMotorSpeed, int rightMotorSpeed){ \/\/will set the speed manual to each motor, use with caution\n\tif (cruiseControlEnabled()) return; \/\/we don't want to be manually messing with the speed, during cruise control\n\tleftMotorSpeed = constrain(leftMotorSpeed, MAX_BACK_RAW_SPEED, MAX_FRONT_RAW_SPEED); \/\/constrain the speed within the allowed limits\n\trightMotorSpeed = constrain(rightMotorSpeed, MAX_BACK_RAW_SPEED, MAX_FRONT_RAW_SPEED);\n\tif (leftMotorSpeed<0){ \/\/set left direction backwards\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, HIGH);\n\t}else{ \/\/front\n\t\tdigitalWrite(MOTOR_LEFT1_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_LEFT2_PIN, LOW);\t\n\t}\n\t\tanalogWrite(MOTOR_LEFT_EN_PIN, abs(leftMotorSpeed));\/\/write left speed\n\tif (rightMotorSpeed<0){ \/\/set right direction backwards\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, LOW);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, HIGH);\n\t}else{ \/\/front\n\t\tdigitalWrite(MOTOR_RIGHT1_PIN, HIGH);\n\t\tdigitalWrite(MOTOR_RIGHT2_PIN, LOW);\t\t\n\t}\n\t\tanalogWrite(MOTOR_RIGHT_EN_PIN, abs(rightMotorSpeed));\/\/write right speed\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n\nvoid trim_out_of_range(void);\nint shift_right(const int idx, const int sum = 0);\nint shift_down(const int idx, const int sum = 0);\n\nint *list;\nint size;\nint sum;\n\nint main(void)\n{\n printf(\"Enter n= \"); scanf(\"%d\", &size);\n\n list = (int *)malloc(sizeof(int) * size);\n for(int i = 0; i < size; i++)\n {\n printf(\"Enter list[%d]= \", i); scanf(\"%d\", &list[i]);\n }\n\n printf(\"Enter k= \"); scanf(\"%d\", &sum);\n\n trim_out_of_range();\n printf(\"Result: %d\\n\", shift_right(size - 1));\n\n free(list);\n\n return 0;\n}\n\nvoid trim_out_of_range(void)\n{\n for(int i = size - 1; i >= 0; i--)\n if(list[i] > sum)\n {\n for(int j = i; j < size; j++) list[j] = list[j + 1];\n size--;\n }\n}\n\nint shift_right(const int idx, const int sum)\n{\n if(idx < 0 && sum == ::sum) return 1;\n if(idx < 0) return 0;\n\n return shift_right(idx - 1, sum + list[idx]) + shift_down(idx, sum);\n}\n\nint shift_down(const int idx, const int sum)\n{\n if(idx - 1 < 0) return 0;\n return shift_right(idx - 1, sum);\n}\n<commit_msg>Fix the error which is printing invalid result<commit_after>#include <stdio.h>\n#include <stdlib.h>\n\nvoid trim_out_of_range(void);\nint shift_right(const int idx, const int sum = 0);\nint shift_down(const int idx, const int sum = 0);\n\nint *list;\nint size;\nint sum;\n\nint main(void)\n{\n printf(\"Enter n= \"); scanf(\"%d\", &size);\n\n list = (int *)malloc(sizeof(int) * size);\n for(int i = 0; i < size; i++)\n {\n printf(\"Enter list[%d]= \", i); scanf(\"%d\", &list[i]);\n }\n\n printf(\"Enter k= \"); scanf(\"%d\", &sum);\n\n trim_out_of_range();\n printf(\"Result: %d\\n\", shift_right(size - 1));\n\n free(list);\n\n return 0;\n}\n\nvoid trim_out_of_range(void)\n{\n for(int i = size - 1; i >= 0; i--)\n if(list[i] > sum)\n {\n for(int j = i; j < size; j++) list[j] = list[j + 1];\n size--;\n }\n}\n\nint shift_right(const int idx, const int sum)\n{\n if(idx < 0 && sum == ::sum) return 1;\n if(idx < 0) return 0;\n\n return shift_right(idx - 1, sum + list[idx]) + shift_down(idx, sum);\n}\n\nint shift_down(const int idx, const int sum)\n{\n if(idx - 1 < 0 && sum == ::sum) return 1;\n if(idx - 1 < 0) return 0;\n\n return shift_right(idx - 1, sum);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file binary_space_tree.hpp\n * @author Ryan Curtin\n *\n * Include all the necessary files to use the BinarySpaceTree class.\n *\/\n#ifndef __MLPACK_CORE_TREE_BINARY_SPACE_TREE_HPP\n#define __MLPACK_CORE_TREE_BINARY_SPACE_TREE_HPP\n\n#include \"bounds.hpp\"\n#include \"binary_space_tree\/binary_space_tree.hpp\"\n#include \"binary_space_tree\/single_tree_traverser.hpp\"\n#include \"binary_space_tree\/single_tree_traverser_impl.hpp\"\n#include \"binary_space_tree\/dual_tree_traverser.hpp\"\n#include \"binary_space_tree\/dual_tree_traverser_impl.hpp\"\n#include \"binary_space_tree\/traits.hpp\"\n\n#endif\n<commit_msg>Here's the file I forgot -- include the BreadthFirstDualTreeTraverser class definition.<commit_after>\/**\n * @file binary_space_tree.hpp\n * @author Ryan Curtin\n *\n * Include all the necessary files to use the BinarySpaceTree class.\n *\/\n#ifndef __MLPACK_CORE_TREE_BINARY_SPACE_TREE_HPP\n#define __MLPACK_CORE_TREE_BINARY_SPACE_TREE_HPP\n\n#include \"bounds.hpp\"\n#include \"binary_space_tree\/binary_space_tree.hpp\"\n#include \"binary_space_tree\/single_tree_traverser.hpp\"\n#include \"binary_space_tree\/single_tree_traverser_impl.hpp\"\n#include \"binary_space_tree\/dual_tree_traverser.hpp\"\n#include \"binary_space_tree\/dual_tree_traverser_impl.hpp\"\n#include \"binary_space_tree\/breadth_first_dual_tree_traverser.hpp\"\n#include \"binary_space_tree\/breadth_first_dual_tree_traverser_impl.hpp\"\n#include \"binary_space_tree\/traits.hpp\"\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file trainer.hpp\n * @author Marcus Edel\n *\n * Definition and implementation of a trainer that trains the parameters of a\n * neural network according to a supervised dataset.\n *\/\n#ifndef __MLPACK_METHODS_ANN_TRAINER_TRAINER_HPP\n#define __MLPACK_METHODS_ANN_TRAINER_TRAINER_HPP\n\n#include <mlpack\/core.hpp>\n\n#include <mlpack\/methods\/ann\/network_traits.hpp>\n#include <mlpack\/methods\/ann\/layer\/layer_traits.hpp>\n\nnamespace mlpack {\nnamespace ann \/** Artificial Neural Network. *\/ {\n\n\/**\n * Trainer that trains the parameters of a neural network according to a\n * supervised dataset.\n *\n * @tparam NetworkType The type of network which should be trained and\n * evaluated.\n * @tparam MaType Type of the error type (arma::mat or arma::sp_mat).\n *\/\ntemplate<\n typename NetworkType,\n typename MatType = arma::mat\n>\nclass Trainer\n{\n public:\n \/**\n * Construct the Trainer object, which will be used to train a neural\n * network according to a supervised dataset by backpropagating the errors.\n *\n * If batchSize is greater 1 the trainer will take a mean gradient step over\n * this many samples and will update the parameters only at the end of\n * each epoch (Default 1).\n *\n * @param net The network that should be trained.\n * @param maxEpochs The number of maximal trained iterations (0 means no\n * limit).\n * @param batchSize The batch size used to train the network.\n * @param tolerance Train the network until it converges against\n * the specified threshold.\n * @param shuffle If true, the order of the training set is shuffled;\n * otherwise, each data is visited in linear order.\n *\/\n Trainer(NetworkType& net,\n const size_t maxEpochs = 0,\n const size_t batchSize = 1,\n const double tolerance = 0.0001,\n const bool shuffle = true) :\n net(net),\n maxEpochs(maxEpochs),\n batchSize(batchSize),\n tolerance(tolerance),\n shuffle(shuffle)\n {\n \/\/ Nothing to do here.\n }\n\n \/**\n * Train the network on the given datasets until the network converges. If\n * maxEpochs is greater than zero that many epochs are maximal trained.\n *\n * @param trainingData Data used to train the network.\n * @param trainingLabels Labels used to train the network.\n * @param validationData Data used to evaluate the network.\n * @tparam validationLabels Labels used to evaluate the network.\n *\/\n template<typename InputType, typename OutputType>\n void Train(InputType& trainingData,\n OutputType& trainingLabels,\n InputType& validationData,\n OutputType& validationLabels)\n {\n \/\/ This generates [0 1 2 3 ... (ElementCount(trainingData) - 1)]. The\n \/\/ sequence will be used to iterate through the training data.\n index = arma::linspace<arma::Col<size_t> >(0,\n ElementCount(trainingData) - 1, ElementCount(trainingData));\n epoch = 0;\n\n while(true)\n {\n if (shuffle)\n index = arma::shuffle(index);\n\n Train<InputType, OutputType, NetworkType>(\n trainingData, trainingLabels);\n Evaluate<InputType, OutputType, NetworkType>(\n validationData, validationLabels);\n\n if (validationError <= tolerance)\n break;\n\n if (maxEpochs > 0 && ++epoch >= maxEpochs)\n break;\n }\n }\n\n \/\/! Get the training error.\n double TrainingError() const { return trainingError; }\n\n \/\/! Get the validation error.\n double ValidationError() const { return validationError; }\n\n \/\/! Get whether or not the individual inputs are shuffled.\n bool Shuffle() const { return shuffle; }\n \/\/! Modify whether or not the individual inputs are shuffled.\n bool& Shuffle() { return shuffle; }\n\n \/\/! Get the batch size.\n size_t StepSize() const { return batchSize; }\n \/\/! Modify the batch size.\n size_t& StepSize() { return batchSize; }\n\n \/\/! Get the maximum number of iterations (0 indicates no limit).\n size_t MaxEpochs() const { return maxEpochs; }\n \/\/! Modify the maximum number of iterations (0 indicates no limit).\n size_t& MaxEpochs() { return maxEpochs; }\n\n \/\/! Get the tolerance for termination.\n double Tolerance() const { return tolerance; }\n \/\/! Modify the tolerance for termination.\n double& Tolerance() { return tolerance; }\n\n private:\n \/**\n * Train the network on the given dataset.\n *\n * @param data Data used to train the network.\n * @param target Labels used to train the network.\n *\/\n template<typename InputType, typename OutputType, typename ModelType>\n typename std::enable_if<!NetworkTraits<ModelType>::IsSAE, void>::type\n Train(InputType& data, OutputType& target)\n {\n \/\/ Reset the training error.\n trainingError = 0;\n\n for (size_t i = 0; i < index.n_elem; i++)\n {\n net.FeedForward(Element(data, index(i)),\n Element(target, index(i)), error);\n\n trainingError += net.Error();\n net.FeedBackward(Element(data, index(i)), error);\n\n if (((i + 1) % batchSize) == 0)\n net.ApplyGradients();\n }\n\n if ((index.n_elem % batchSize) != 0)\n net.ApplyGradients();\n\n trainingError \/= index.n_elem;\n }\n\n \/**\n * Train the sparse autoencoder on the given dataset.\n *\n * @param data Data used to train the network.\n *\/\n template<typename InputType, typename OutputType, typename ModelType>\n typename std::enable_if<NetworkTraits<ModelType>::IsSAE, void>::type\n Train(InputType& data, OutputType& \/* unused *\/)\n {\n \/\/ Reset the training error.\n trainingError = 0;\n\n arma::uvec indices(batchSize);\n\n if (index.n_elem > batchSize)\n {\n for (size_t i = 0; i < index.n_elem; i += batchSize)\n {\n for (size_t j = 0; j < batchSize; j++)\n indices(j) = index(j + i);\n\n MatType input = data.rows(indices);\n net.FeedForward(input, input, error);\n\n trainingError += net.Error();\n net.FeedBackward(input, error);\n net.ApplyGradients();\n }\n\n trainingError \/= (index.n_elem \/ batchSize);\n }\n else\n {\n net.FeedForward(data, data, error);\n trainingError += net.Error();\n net.FeedBackward(data, error);\n net.ApplyGradients();\n }\n }\n\n \/**\n * Evaluate the network on the given dataset.\n *\n * @param data Data used to train the network.\n * @param target Labels used to train the network.\n *\/\n template<typename InputType, typename OutputType, typename ModelType>\n typename std::enable_if<!NetworkTraits<ModelType>::IsSAE, void>::type\n Evaluate(InputType& data, OutputType& target)\n {\n \/\/ Reset the validation error.\n validationError = 0;\n\n for (size_t i = 0; i < ElementCount(data); i++)\n {\n validationError += net.Evaluate(Element(data, i),\n Element(target, i), error);\n }\n\n validationError \/= ElementCount(data);\n }\n\n template<typename InputType, typename OutputType, typename ModelType>\n typename std::enable_if<NetworkTraits<ModelType>::IsSAE, void>::type\n Evaluate(InputType& data, OutputType& target) { \/* Nothing to do here *\/ }\n\n \/*\n * Create a Col object which uses memory from an existing matrix object.\n * (This approach is currently not alias safe)\n *\n * @param data The reference data.\n * @param sliceNum Provide a Col object of the specified index.\n *\/\n template<typename eT>\n arma::Mat<eT> Element(arma::Mat<eT>& input, const size_t colNum)\n {\n return arma::Mat<eT>(input.colptr(colNum), input.n_rows, 1, false, true);\n }\n\n \/*\n * Provide the reference to the matrix representing a single slice.\n *\n * @param data The reference data.\n * @param sliceNum Provide a single slice of the specified index.\n *\/\n template<typename eT>\n const arma::Cube<eT> Element(arma::Cube<eT>& input, const size_t sliceNum)\n {\n return input.slices(sliceNum, sliceNum);\n }\n\n \/*\n * Get the number of elements.\n *\n * @param data The reference data.\n *\/\n template<typename eT>\n size_t ElementCount(const arma::Mat<eT>& data) const\n {\n return data.n_cols;\n }\n\n \/*\n * Get the number of elements.\n *\n * @param data The reference data.\n *\/\n template<typename eT>\n size_t ElementCount(const arma::Cube<eT>& data) const\n {\n return data.n_slices;\n }\n\n \/\/! The network which should be trained and evaluated.\n NetworkType& net;\n\n \/\/! The current network error of a single input.\n MatType error;\n\n \/\/! The current epoch if maxEpochs is set.\n size_t epoch;\n\n \/\/! The maximal epochs that should be used.\n size_t maxEpochs;\n\n \/\/! The size until a update is performed.\n size_t batchSize;\n\n \/\/! The shuffel sequence index used to train the network.\n arma::Col<size_t> index;\n\n \/\/! The overall traing error.\n double trainingError;\n\n \/\/! The overall validation error.\n double validationError;\n\n \/\/! The tolerance for termination.\n double tolerance;\n\n \/\/! Controls whether or not the individual inputs are shuffled when\n \/\/! iterating.\n bool shuffle;\n}; \/\/ class Trainer\n\n} \/\/ namespace ann\n} \/\/ namespace mlpack\n\n#endif\n<commit_msg>Remove unused parameter.<commit_after>\/**\n * @file trainer.hpp\n * @author Marcus Edel\n *\n * Definition and implementation of a trainer that trains the parameters of a\n * neural network according to a supervised dataset.\n *\/\n#ifndef __MLPACK_METHODS_ANN_TRAINER_TRAINER_HPP\n#define __MLPACK_METHODS_ANN_TRAINER_TRAINER_HPP\n\n#include <mlpack\/core.hpp>\n\n#include <mlpack\/methods\/ann\/network_traits.hpp>\n#include <mlpack\/methods\/ann\/layer\/layer_traits.hpp>\n\nnamespace mlpack {\nnamespace ann \/** Artificial Neural Network. *\/ {\n\n\/**\n * Trainer that trains the parameters of a neural network according to a\n * supervised dataset.\n *\n * @tparam NetworkType The type of network which should be trained and\n * evaluated.\n * @tparam MaType Type of the error type (arma::mat or arma::sp_mat).\n *\/\ntemplate<\n typename NetworkType,\n typename MatType = arma::mat\n>\nclass Trainer\n{\n public:\n \/**\n * Construct the Trainer object, which will be used to train a neural\n * network according to a supervised dataset by backpropagating the errors.\n *\n * If batchSize is greater 1 the trainer will take a mean gradient step over\n * this many samples and will update the parameters only at the end of\n * each epoch (Default 1).\n *\n * @param net The network that should be trained.\n * @param maxEpochs The number of maximal trained iterations (0 means no\n * limit).\n * @param batchSize The batch size used to train the network.\n * @param tolerance Train the network until it converges against\n * the specified threshold.\n * @param shuffle If true, the order of the training set is shuffled;\n * otherwise, each data is visited in linear order.\n *\/\n Trainer(NetworkType& net,\n const size_t maxEpochs = 0,\n const size_t batchSize = 1,\n const double tolerance = 0.0001,\n const bool shuffle = true) :\n net(net),\n maxEpochs(maxEpochs),\n batchSize(batchSize),\n tolerance(tolerance),\n shuffle(shuffle)\n {\n \/\/ Nothing to do here.\n }\n\n \/**\n * Train the network on the given datasets until the network converges. If\n * maxEpochs is greater than zero that many epochs are maximal trained.\n *\n * @param trainingData Data used to train the network.\n * @param trainingLabels Labels used to train the network.\n * @param validationData Data used to evaluate the network.\n * @tparam validationLabels Labels used to evaluate the network.\n *\/\n template<typename InputType, typename OutputType>\n void Train(InputType& trainingData,\n OutputType& trainingLabels,\n InputType& validationData,\n OutputType& validationLabels)\n {\n \/\/ This generates [0 1 2 3 ... (ElementCount(trainingData) - 1)]. The\n \/\/ sequence will be used to iterate through the training data.\n index = arma::linspace<arma::Col<size_t> >(0,\n ElementCount(trainingData) - 1, ElementCount(trainingData));\n epoch = 0;\n\n while(true)\n {\n if (shuffle)\n index = arma::shuffle(index);\n\n Train<InputType, OutputType, NetworkType>(\n trainingData, trainingLabels);\n Evaluate<InputType, OutputType, NetworkType>(\n validationData, validationLabels);\n\n if (validationError <= tolerance)\n break;\n\n if (maxEpochs > 0 && ++epoch >= maxEpochs)\n break;\n }\n }\n\n \/\/! Get the training error.\n double TrainingError() const { return trainingError; }\n\n \/\/! Get the validation error.\n double ValidationError() const { return validationError; }\n\n \/\/! Get whether or not the individual inputs are shuffled.\n bool Shuffle() const { return shuffle; }\n \/\/! Modify whether or not the individual inputs are shuffled.\n bool& Shuffle() { return shuffle; }\n\n \/\/! Get the batch size.\n size_t StepSize() const { return batchSize; }\n \/\/! Modify the batch size.\n size_t& StepSize() { return batchSize; }\n\n \/\/! Get the maximum number of iterations (0 indicates no limit).\n size_t MaxEpochs() const { return maxEpochs; }\n \/\/! Modify the maximum number of iterations (0 indicates no limit).\n size_t& MaxEpochs() { return maxEpochs; }\n\n \/\/! Get the tolerance for termination.\n double Tolerance() const { return tolerance; }\n \/\/! Modify the tolerance for termination.\n double& Tolerance() { return tolerance; }\n\n private:\n \/**\n * Train the network on the given dataset.\n *\n * @param data Data used to train the network.\n * @param target Labels used to train the network.\n *\/\n template<typename InputType, typename OutputType, typename ModelType>\n typename std::enable_if<!NetworkTraits<ModelType>::IsSAE, void>::type\n Train(InputType& data, OutputType& target)\n {\n \/\/ Reset the training error.\n trainingError = 0;\n\n for (size_t i = 0; i < index.n_elem; i++)\n {\n net.FeedForward(Element(data, index(i)),\n Element(target, index(i)), error);\n\n trainingError += net.Error();\n net.FeedBackward(Element(data, index(i)), error);\n\n if (((i + 1) % batchSize) == 0)\n net.ApplyGradients();\n }\n\n if ((index.n_elem % batchSize) != 0)\n net.ApplyGradients();\n\n trainingError \/= index.n_elem;\n }\n\n \/**\n * Train the sparse autoencoder on the given dataset.\n *\n * @param data Data used to train the network.\n *\/\n template<typename InputType, typename OutputType, typename ModelType>\n typename std::enable_if<NetworkTraits<ModelType>::IsSAE, void>::type\n Train(InputType& data, OutputType& \/* unused *\/)\n {\n \/\/ Reset the training error.\n trainingError = 0;\n\n arma::uvec indices(batchSize);\n\n if (index.n_elem > batchSize)\n {\n for (size_t i = 0; i < index.n_elem; i += batchSize)\n {\n for (size_t j = 0; j < batchSize; j++)\n indices(j) = index(j + i);\n\n MatType input = data.rows(indices);\n net.FeedForward(input, input, error);\n\n trainingError += net.Error();\n net.FeedBackward(input, error);\n net.ApplyGradients();\n }\n\n trainingError \/= (index.n_elem \/ batchSize);\n }\n else\n {\n net.FeedForward(data, data, error);\n trainingError += net.Error();\n net.FeedBackward(data, error);\n net.ApplyGradients();\n }\n }\n\n \/**\n * Evaluate the network on the given dataset.\n *\n * @param data Data used to train the network.\n * @param target Labels used to train the network.\n *\/\n template<typename InputType, typename OutputType, typename ModelType>\n typename std::enable_if<!NetworkTraits<ModelType>::IsSAE, void>::type\n Evaluate(InputType& data, OutputType& target)\n {\n \/\/ Reset the validation error.\n validationError = 0;\n\n for (size_t i = 0; i < ElementCount(data); i++)\n {\n validationError += net.Evaluate(Element(data, i),\n Element(target, i), error);\n }\n\n validationError \/= ElementCount(data);\n }\n\n template<typename InputType, typename OutputType, typename ModelType>\n typename std::enable_if<NetworkTraits<ModelType>::IsSAE, void>::type\n Evaluate(InputType& \/* unused *\/, OutputType& \/* unused *\/) { \/* Nothing to do here *\/ }\n\n \/*\n * Create a Col object which uses memory from an existing matrix object.\n * (This approach is currently not alias safe)\n *\n * @param data The reference data.\n * @param sliceNum Provide a Col object of the specified index.\n *\/\n template<typename eT>\n arma::Mat<eT> Element(arma::Mat<eT>& input, const size_t colNum)\n {\n return arma::Mat<eT>(input.colptr(colNum), input.n_rows, 1, false, true);\n }\n\n \/*\n * Provide the reference to the matrix representing a single slice.\n *\n * @param data The reference data.\n * @param sliceNum Provide a single slice of the specified index.\n *\/\n template<typename eT>\n const arma::Cube<eT> Element(arma::Cube<eT>& input, const size_t sliceNum)\n {\n return input.slices(sliceNum, sliceNum);\n }\n\n \/*\n * Get the number of elements.\n *\n * @param data The reference data.\n *\/\n template<typename eT>\n size_t ElementCount(const arma::Mat<eT>& data) const\n {\n return data.n_cols;\n }\n\n \/*\n * Get the number of elements.\n *\n * @param data The reference data.\n *\/\n template<typename eT>\n size_t ElementCount(const arma::Cube<eT>& data) const\n {\n return data.n_slices;\n }\n\n \/\/! The network which should be trained and evaluated.\n NetworkType& net;\n\n \/\/! The current network error of a single input.\n MatType error;\n\n \/\/! The current epoch if maxEpochs is set.\n size_t epoch;\n\n \/\/! The maximal epochs that should be used.\n size_t maxEpochs;\n\n \/\/! The size until a update is performed.\n size_t batchSize;\n\n \/\/! The shuffel sequence index used to train the network.\n arma::Col<size_t> index;\n\n \/\/! The overall traing error.\n double trainingError;\n\n \/\/! The overall validation error.\n double validationError;\n\n \/\/! The tolerance for termination.\n double tolerance;\n\n \/\/! Controls whether or not the individual inputs are shuffled when\n \/\/! iterating.\n bool shuffle;\n}; \/\/ class Trainer\n\n} \/\/ namespace ann\n} \/\/ namespace mlpack\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Copyright (c) 2016, Acer Yun-Tse Yang 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 met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ******************************************************************************\/\n#include \"gtest\/gtest.h\"\n#include \"sqlite3cpp.h\"\n#include <iostream>\n#include <limits>\n\nstruct DBTest : ::testing::Test {\n DBTest()\n {}\n\n virtual ~DBTest() {}\n\n virtual void SetUp() {\n m_basic_dataset.reset(new sqlite3cpp::database(\":memory:\"));\n\n auto c = basic_dataset().make_cursor();\n c.executescript(\n \"begin;\"\n \"create table T (a INTEGER, b TEXT);\"\n \"insert into T values(1, 'test1');\"\n \"insert into T values(2, 'test2');\"\n \"insert into T values(2, 'abc');\"\n \"insert into T values(3, 'test3');\"\n \"commit;\"\n );\n }\n\n virtual void TearDown() {\n m_basic_dataset.reset();\n }\n\n sqlite3cpp::database &basic_dataset() {\n return *m_basic_dataset;\n }\n\nprivate:\n std::unique_ptr<sqlite3cpp::database> m_basic_dataset;\n};\n\nTEST(basic, construct) {\n using namespace sqlite3cpp;\n database d(\":memory:\");\n}\n\nTEST_F(DBTest, row_iter) {\n using namespace sqlite3cpp;\n\n auto c = basic_dataset().make_cursor();\n\n c.executescript(\"create table Empty (a);\");\n c.execute(\"select * from Empty\");\n\n EXPECT_EQ(c.begin(), c.end());\n\n c.execute(\"insert into Empty values(?)\", 123);\n c.execute(\"select * from Empty\");\n\n EXPECT_NE(c.begin(), c.end());\n EXPECT_EQ(++c.begin(), c.end());\n EXPECT_EQ(c.begin(), c.end());\n}\n\nTEST_F(DBTest, bind_null) {\n auto c = basic_dataset().make_cursor();\n\n c.execute(\"create table T2 (a);\");\n c.execute(\"insert into T2 values(?)\", nullptr);\n c.execute(\"select count(*) from T2 where a is NULL\");\n\n int cnt = 0;\n std::tie(cnt) = c.begin()->to<int>();\n EXPECT_EQ(1, cnt);\n}\n\nTEST_F(DBTest, query) {\n using namespace sqlite3cpp;\n auto c = basic_dataset().make_cursor();\n char const *query = \"select * from T where a > ? and a < ? and b like ?\";\n std::string pattern = \"test%\";\n\n int idx = 0;\n for(auto const &row : c.execute(query, 1, 3, \"test%\")) {\n int a; std::string b;\n std::tie(a, b) = row.to<int, std::string>();\n\n EXPECT_EQ(2, a);\n EXPECT_STREQ(\"test2\", b.c_str());\n }\n}\n\n\nTEST(basic, wrap_function) {\n using namespace sqlite3cpp;\n using namespace std;\n using namespace std::placeholders;\n\n function<int(int)> c;\n auto f = detail::make_invoker(move(c));\n\n struct functor {\n void step(int x){ }\n int finalize(){\n return 0;\n }\n };\n functor fr;\n detail::bind_this(&functor::step, &fr);\n}\n\n\nTEST_F(DBTest, create_scalar) {\n using namespace sqlite3cpp;\n auto c = basic_dataset().make_cursor();\n\n struct minus_x {\n minus_x(int x) : m_x(x) {}\n int operator()(int input) const {\n return input - m_x;\n }\n int m_x;\n };\n basic_dataset().create_scalar(\"minus123\", minus_x(123));\n\n int x = 123;\n basic_dataset().create_scalar(\"plus123\", [x](int input) {\n return x + input;\n });\n\n basic_dataset().create_scalar(\"mutiply\", [](int x, int y) {\n return x * y;\n });\n\n basic_dataset().create_scalar(\"strcat123\", [](std::string val) {\n return val + \"_123\";\n });\n\n char const *query = \"select plus123(a), mutiply(a,a), minus123(a), strcat123(a) from T;\";\n\n int idx = 0;\n struct {\n int plus, mul, min;\n char const *cat;\n } expected[4] = {\n { 123+1, 1*1, 1 - 123, \"1_123\" },\n { 123+2, 2*2, 2 - 123, \"2_123\" },\n { 123+2, 2*2, 2 - 123, \"2_123\" },\n { 123+3, 3*3, 3 - 123, \"3_123\" }\n };\n\n for(auto const &row : c.execute(query)) {\n int a, b, c;\n std::string d;\n\n std::tie(a, b, c, d) = row.to<int, int, int, std::string>();\n EXPECT_EQ(expected[idx].plus, a);\n EXPECT_EQ(expected[idx].mul, b);\n EXPECT_EQ(expected[idx].min, c);\n EXPECT_EQ(expected[idx].cat, d);\n idx++;\n }\n}\n\nTEST_F(DBTest, max_int64) {\n auto c = basic_dataset().make_cursor();\n\n basic_dataset().create_scalar(\"maxint64\", [](){\n return std::numeric_limits<int64_t>::max();\n });\n\n for(auto const &row : c.execute(\"select maxint64()\")) {\n EXPECT_EQ(std::numeric_limits<int64_t>::max(),\n std::get<0>(row.to<int64_t>()));\n }\n}\n\nTEST_F(DBTest, create_aggregate) {\n\n using namespace sqlite3cpp;\n\n struct stdev {\n void step(int val) {\n m_cnt ++;\n m_sum += val;\n m_sq_sum += val * val;\n\n }\n double finalize() {\n auto avg = (double)m_sum \/ m_cnt;\n return std::sqrt((double)(m_sq_sum - avg * avg * m_cnt) \/ (m_cnt -1));\n }\n size_t m_cnt = 0;\n int m_sum = 0,\n m_sq_sum = 0;\n };\n\n basic_dataset().create_aggregate<stdev>(\"stdev\");\n auto c = basic_dataset().make_cursor();\n\n char const *query = \"select stdev(a) from T\";\n for(auto const &row : c.execute(query)) {\n double a;\n std::tie(a) = row.to<double>();\n \/\/ XXX Platfomr dependant\n EXPECT_DOUBLE_EQ(0.81649658092772603, a);\n }\n}\n\nTEST_F(DBTest, error_handle) {\n using namespace sqlite3cpp;\n\n auto c = basic_dataset().make_cursor();\n\n try {\n c.execute(\"invalid sql\");\n FAIL() << \"Expect throw\";\n } catch(error const &e) {\n EXPECT_EQ(SQLITE_ERROR, e.code);\n EXPECT_STREQ(\"SQL logic error or missing database\", e.what());\n } catch(...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n try {\n c.executescript(\"invalid sql\");\n FAIL() << \"Expect throw\";\n } catch(error const &e) {\n EXPECT_EQ(SQLITE_ERROR, e.code);\n EXPECT_STREQ(\"SQL logic error or missing database\", e.what());\n } catch(...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n try {\n c.execute(\"select * from T\", 123); \/\/ invalid bind\n } catch(error const &e) {\n EXPECT_EQ(SQLITE_RANGE, e.code);\n EXPECT_STREQ(\"bind or column index out of range\", e.what());\n } catch(...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n}\n\nTEST_F(DBTest, throw_in_custom_function) {\n\n auto c = basic_dataset().make_cursor();\n\n basic_dataset().create_scalar(\"bad_alloc\", [](){\n throw std::bad_alloc();\n });\n\n try {\n c.execute(\"select bad_alloc();\");\n } catch(sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_NOMEM, e.code);\n EXPECT_STREQ(\"out of memory\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n basic_dataset().create_scalar(\"length_error\", [](){\n throw std::length_error(\"len err\");\n });\n\n try {\n c.execute(\"select length_error();\");\n } catch(sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_ABORT, e.code);\n EXPECT_STREQ(\"callback requested query abort\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n}\n\nTEST_F(DBTest, logic_error_in_aggregate) {\n\n auto c = basic_dataset().make_cursor();\n\n struct throw_in_step {\n void step(int a) {\n throw std::out_of_range(\"oops\");\n }\n int finalize() {\n return 0;\n }\n };\n\n basic_dataset().create_aggregate<throw_in_step>(\"throw_in_step\");\n\n try {\n c.execute(\"select throw_in_step(a) from T\");\n } catch (sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_ABORT, e.code);\n EXPECT_STREQ(\"callback requested query abort\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n struct throw_in_final {\n void step(int a){}\n int finalize() {\n throw std::out_of_range(\"oops\");\n return 0;\n }\n };\n\n basic_dataset().create_aggregate<throw_in_final>(\"throw_in_final\");\n\n try {\n c.execute(\"select throw_in_final(a) from T\");\n } catch (sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_ABORT, e.code);\n EXPECT_STREQ(\"callback requested query abort\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n}\n\nTEST_F(DBTest, bad_alloc_in_aggregate) {\n\n auto c = basic_dataset().make_cursor();\n\n struct throw_in_step {\n void step(int a) {\n throw std::bad_alloc();\n }\n int finalize() {\n return 0;\n }\n };\n\n basic_dataset().create_aggregate<throw_in_step>(\"throw_in_step\");\n\n try {\n c.execute(\"select throw_in_step(a) from T\");\n } catch (sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_NOMEM, e.code);\n EXPECT_STREQ(\"out of memory\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n struct throw_in_final {\n void step(int a){}\n int finalize() {\n throw std::bad_alloc();\n return 0;\n }\n };\n\n basic_dataset().create_aggregate<throw_in_final>(\"throw_in_final\");\n\n try {\n c.execute(\"select throw_in_final(a) from T\");\n } catch (sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_NOMEM, e.code);\n EXPECT_STREQ(\"out of memory\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n}\n\n# include \"version.h\"\n\nTEST_F(DBTest, version) {\n\n EXPECT_STREQ(SQLITE3CPP_VERSION_STRING, basic_dataset().version().c_str());\n}\n<commit_msg>Add string_ref test.<commit_after>\/*****************************************************************************\n * Copyright (c) 2016, Acer Yun-Tse Yang 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 met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ******************************************************************************\/\n#include \"gtest\/gtest.h\"\n#include \"sqlite3cpp.h\"\n#include <iostream>\n#include <limits>\n\nstruct DBTest : ::testing::Test {\n DBTest()\n {}\n\n virtual ~DBTest() {}\n\n virtual void SetUp() {\n m_basic_dataset.reset(new sqlite3cpp::database(\":memory:\"));\n\n auto c = basic_dataset().make_cursor();\n c.executescript(\n \"begin;\"\n \"create table T (a INTEGER, b TEXT);\"\n \"insert into T values(1, 'test1');\"\n \"insert into T values(2, 'test2');\"\n \"insert into T values(2, 'abc');\"\n \"insert into T values(3, 'test3');\"\n \"commit;\"\n );\n }\n\n virtual void TearDown() {\n m_basic_dataset.reset();\n }\n\n sqlite3cpp::database &basic_dataset() {\n return *m_basic_dataset;\n }\n\nprivate:\n std::unique_ptr<sqlite3cpp::database> m_basic_dataset;\n};\n\nTEST(basic, construct) {\n using namespace sqlite3cpp;\n database d(\":memory:\");\n}\n\nTEST_F(DBTest, row_iter) {\n using namespace sqlite3cpp;\n\n auto c = basic_dataset().make_cursor();\n\n c.executescript(\"create table Empty (a);\");\n c.execute(\"select * from Empty\");\n\n EXPECT_EQ(c.begin(), c.end());\n\n c.execute(\"insert into Empty values(?)\", 123);\n c.execute(\"select * from Empty\");\n\n EXPECT_NE(c.begin(), c.end());\n EXPECT_EQ(++c.begin(), c.end());\n EXPECT_EQ(c.begin(), c.end());\n}\n\nTEST_F(DBTest, bind_null) {\n auto c = basic_dataset().make_cursor();\n\n c.execute(\"create table T2 (a);\");\n c.execute(\"insert into T2 values(?)\", nullptr);\n c.execute(\"select count(*) from T2 where a is NULL\");\n\n int cnt = 0;\n std::tie(cnt) = c.begin()->to<int>();\n EXPECT_EQ(1, cnt);\n}\n\nTEST_F(DBTest, query) {\n using namespace sqlite3cpp;\n auto c = basic_dataset().make_cursor();\n char const *query = \"select * from T where a > ? and a < ? and b like ?\";\n std::string pattern = \"test%\";\n\n int idx = 0;\n for(auto const &row : c.execute(query, 1, 3, \"test%\")) {\n int a; std::string b;\n std::tie(a, b) = row.to<int, std::string>();\n\n EXPECT_EQ(2, a);\n EXPECT_STREQ(\"test2\", b.c_str());\n }\n}\n\nTEST_F(DBTest, query_with_string_ref) {\n using namespace sqlite3cpp;\n\n auto c = basic_dataset().make_cursor();\n char const *query = \"select * from T where a > ? and a < ? and b like ?\";\n std::string pattern = \"test%\";\n\n int idx = 0;\n for(auto const &row : c.execute(query, 1, 3, \"test%\")) {\n int a; string_ref b;\n std::tie(a, b) = row.to<int, string_ref>();\n\n EXPECT_EQ(2, a);\n EXPECT_STREQ(\"test2\", b.data());\n }\n}\n\nTEST(basic, wrap_function) {\n using namespace sqlite3cpp;\n using namespace std;\n using namespace std::placeholders;\n\n function<int(int)> c;\n auto f = detail::make_invoker(move(c));\n\n struct functor {\n void step(int x){ }\n int finalize(){\n return 0;\n }\n };\n functor fr;\n detail::bind_this(&functor::step, &fr);\n}\n\n\nTEST_F(DBTest, create_scalar) {\n using namespace sqlite3cpp;\n auto c = basic_dataset().make_cursor();\n\n struct minus_x {\n minus_x(int x) : m_x(x) {}\n int operator()(int input) const {\n return input - m_x;\n }\n int m_x;\n };\n basic_dataset().create_scalar(\"minus123\", minus_x(123));\n\n int x = 123;\n basic_dataset().create_scalar(\"plus123\", [x](int input) {\n return x + input;\n });\n\n basic_dataset().create_scalar(\"mutiply\", [](int x, int y) {\n return x * y;\n });\n\n basic_dataset().create_scalar(\"strcat123\", [](std::string val) {\n return val + \"_123\";\n });\n\n char const *query = \"select plus123(a), mutiply(a,a), minus123(a), strcat123(a) from T;\";\n\n int idx = 0;\n struct {\n int plus, mul, min;\n char const *cat;\n } expected[4] = {\n { 123+1, 1*1, 1 - 123, \"1_123\" },\n { 123+2, 2*2, 2 - 123, \"2_123\" },\n { 123+2, 2*2, 2 - 123, \"2_123\" },\n { 123+3, 3*3, 3 - 123, \"3_123\" }\n };\n\n for(auto const &row : c.execute(query)) {\n int a, b, c;\n std::string d;\n\n std::tie(a, b, c, d) = row.to<int, int, int, std::string>();\n EXPECT_EQ(expected[idx].plus, a);\n EXPECT_EQ(expected[idx].mul, b);\n EXPECT_EQ(expected[idx].min, c);\n EXPECT_EQ(expected[idx].cat, d);\n idx++;\n }\n}\n\nTEST_F(DBTest, max_int64) {\n auto c = basic_dataset().make_cursor();\n\n basic_dataset().create_scalar(\"maxint64\", [](){\n return std::numeric_limits<int64_t>::max();\n });\n\n for(auto const &row : c.execute(\"select maxint64()\")) {\n EXPECT_EQ(std::numeric_limits<int64_t>::max(),\n std::get<0>(row.to<int64_t>()));\n }\n}\n\nTEST_F(DBTest, create_aggregate) {\n\n using namespace sqlite3cpp;\n\n struct stdev {\n void step(int val) {\n m_cnt ++;\n m_sum += val;\n m_sq_sum += val * val;\n\n }\n double finalize() {\n auto avg = (double)m_sum \/ m_cnt;\n return std::sqrt((double)(m_sq_sum - avg * avg * m_cnt) \/ (m_cnt -1));\n }\n size_t m_cnt = 0;\n int m_sum = 0,\n m_sq_sum = 0;\n };\n\n basic_dataset().create_aggregate<stdev>(\"stdev\");\n auto c = basic_dataset().make_cursor();\n\n char const *query = \"select stdev(a) from T\";\n for(auto const &row : c.execute(query)) {\n double a;\n std::tie(a) = row.to<double>();\n \/\/ XXX Platfomr dependant\n EXPECT_DOUBLE_EQ(0.81649658092772603, a);\n }\n}\n\nTEST_F(DBTest, error_handle) {\n using namespace sqlite3cpp;\n\n auto c = basic_dataset().make_cursor();\n\n try {\n c.execute(\"invalid sql\");\n FAIL() << \"Expect throw\";\n } catch(error const &e) {\n EXPECT_EQ(SQLITE_ERROR, e.code);\n EXPECT_STREQ(\"SQL logic error or missing database\", e.what());\n } catch(...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n try {\n c.executescript(\"invalid sql\");\n FAIL() << \"Expect throw\";\n } catch(error const &e) {\n EXPECT_EQ(SQLITE_ERROR, e.code);\n EXPECT_STREQ(\"SQL logic error or missing database\", e.what());\n } catch(...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n try {\n c.execute(\"select * from T\", 123); \/\/ invalid bind\n } catch(error const &e) {\n EXPECT_EQ(SQLITE_RANGE, e.code);\n EXPECT_STREQ(\"bind or column index out of range\", e.what());\n } catch(...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n}\n\nTEST_F(DBTest, throw_in_custom_function) {\n\n auto c = basic_dataset().make_cursor();\n\n basic_dataset().create_scalar(\"bad_alloc\", [](){\n throw std::bad_alloc();\n });\n\n try {\n c.execute(\"select bad_alloc();\");\n } catch(sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_NOMEM, e.code);\n EXPECT_STREQ(\"out of memory\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n basic_dataset().create_scalar(\"length_error\", [](){\n throw std::length_error(\"len err\");\n });\n\n try {\n c.execute(\"select length_error();\");\n } catch(sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_ABORT, e.code);\n EXPECT_STREQ(\"callback requested query abort\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n}\n\nTEST_F(DBTest, logic_error_in_aggregate) {\n\n auto c = basic_dataset().make_cursor();\n\n struct throw_in_step {\n void step(int a) {\n throw std::out_of_range(\"oops\");\n }\n int finalize() {\n return 0;\n }\n };\n\n basic_dataset().create_aggregate<throw_in_step>(\"throw_in_step\");\n\n try {\n c.execute(\"select throw_in_step(a) from T\");\n } catch (sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_ABORT, e.code);\n EXPECT_STREQ(\"callback requested query abort\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n struct throw_in_final {\n void step(int a){}\n int finalize() {\n throw std::out_of_range(\"oops\");\n return 0;\n }\n };\n\n basic_dataset().create_aggregate<throw_in_final>(\"throw_in_final\");\n\n try {\n c.execute(\"select throw_in_final(a) from T\");\n } catch (sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_ABORT, e.code);\n EXPECT_STREQ(\"callback requested query abort\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n}\n\nTEST_F(DBTest, bad_alloc_in_aggregate) {\n\n auto c = basic_dataset().make_cursor();\n\n struct throw_in_step {\n void step(int a) {\n throw std::bad_alloc();\n }\n int finalize() {\n return 0;\n }\n };\n\n basic_dataset().create_aggregate<throw_in_step>(\"throw_in_step\");\n\n try {\n c.execute(\"select throw_in_step(a) from T\");\n } catch (sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_NOMEM, e.code);\n EXPECT_STREQ(\"out of memory\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n\n struct throw_in_final {\n void step(int a){}\n int finalize() {\n throw std::bad_alloc();\n return 0;\n }\n };\n\n basic_dataset().create_aggregate<throw_in_final>(\"throw_in_final\");\n\n try {\n c.execute(\"select throw_in_final(a) from T\");\n } catch (sqlite3cpp::error const &e) {\n EXPECT_EQ(SQLITE_NOMEM, e.code);\n EXPECT_STREQ(\"out of memory\", e.what());\n } catch (...) {\n FAIL() << \"sqlite3cpp::error should be caught\";\n }\n}\n\n# include \"version.h\"\n\nTEST_F(DBTest, version) {\n\n EXPECT_STREQ(SQLITE3CPP_VERSION_STRING, basic_dataset().version().c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015, Google Inc.\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:\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 disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. 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 *\/\n\n#include <string.h>\n\n#include <node.h>\n#include <nan.h>\n#include \"grpc\/grpc.h\"\n#include \"grpc\/byte_buffer_reader.h\"\n#include \"grpc\/support\/slice.h\"\n#include \"grpc\/support\/log.h\"\n\n#include \"byte_buffer.h\"\n\nnamespace grpc {\nnamespace node {\n\n\nusing v8::Context;\nusing v8::Function;\nusing v8::Local;\nusing v8::Object;\nusing v8::Number;\nusing v8::Value;\n\ngrpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {\n Nan::HandleScope scope;\n int length = ::node::Buffer::Length(buffer);\n char *data = ::node::Buffer::Data(buffer);\n gpr_slice slice = gpr_slice_malloc(length);\n memcpy(GPR_SLICE_START_PTR(slice), data, length);\n grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));\n gpr_slice_unref(slice);\n return byte_buffer;\n}\n\nnamespace {\nvoid delete_buffer(char *data, void *hint) { delete[] data; }\n}\n\nLocal<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {\n Nan::EscapableHandleScope scope;\n if (buffer == NULL) {\n return scope.Escape(Nan::Null());\n }\n gpr_log(GPR_DEBUG, \"Compressed size: %d\", grpc_byte_buffer_length(buffer));\n grpc_byte_buffer_reader reader;\n grpc_byte_buffer_reader_init(&reader, buffer);\n gpr_slice slice = grpc_byte_buffer_reader_readall(&reader);\n size_t length = GPR_SLICE_LENGTH(slice);\n char *result = new char[length];\n memcpy(result, GPR_SLICE_START_PTR(slice), length);\n return scope.Escape(MakeFastBuffer(\n Nan::NewBuffer(result, length, delete_buffer, NULL).ToLocalChecked()));\n}\n\nLocal<Value> MakeFastBuffer(Local<Value> slowBuffer) {\n Nan::EscapableHandleScope scope;\n Local<Object> globalObj = Nan::GetCurrentContext()->Global();\n Local<Function> bufferConstructor = Local<Function>::Cast(\n globalObj->Get(Nan::New(\"Buffer\").ToLocalChecked()));\n Local<Value> consArgs[3] = {\n slowBuffer,\n Nan::New<Number>(::node::Buffer::Length(slowBuffer)),\n Nan::New<Number>(0)\n };\n Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);\n return scope.Escape(fastBuffer);\n}\n} \/\/ namespace node\n} \/\/ namespace grpc\n<commit_msg>Remove extraneous logging code<commit_after>\/*\n *\n * Copyright 2015, Google Inc.\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:\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 disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. 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 *\/\n\n#include <string.h>\n\n#include <node.h>\n#include <nan.h>\n#include \"grpc\/grpc.h\"\n#include \"grpc\/byte_buffer_reader.h\"\n#include \"grpc\/support\/slice.h\"\n\n#include \"byte_buffer.h\"\n\nnamespace grpc {\nnamespace node {\n\n\nusing v8::Context;\nusing v8::Function;\nusing v8::Local;\nusing v8::Object;\nusing v8::Number;\nusing v8::Value;\n\ngrpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {\n Nan::HandleScope scope;\n int length = ::node::Buffer::Length(buffer);\n char *data = ::node::Buffer::Data(buffer);\n gpr_slice slice = gpr_slice_malloc(length);\n memcpy(GPR_SLICE_START_PTR(slice), data, length);\n grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));\n gpr_slice_unref(slice);\n return byte_buffer;\n}\n\nnamespace {\nvoid delete_buffer(char *data, void *hint) { delete[] data; }\n}\n\nLocal<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {\n Nan::EscapableHandleScope scope;\n if (buffer == NULL) {\n return scope.Escape(Nan::Null());\n }\n grpc_byte_buffer_reader reader;\n grpc_byte_buffer_reader_init(&reader, buffer);\n gpr_slice slice = grpc_byte_buffer_reader_readall(&reader);\n size_t length = GPR_SLICE_LENGTH(slice);\n char *result = new char[length];\n memcpy(result, GPR_SLICE_START_PTR(slice), length);\n return scope.Escape(MakeFastBuffer(\n Nan::NewBuffer(result, length, delete_buffer, NULL).ToLocalChecked()));\n}\n\nLocal<Value> MakeFastBuffer(Local<Value> slowBuffer) {\n Nan::EscapableHandleScope scope;\n Local<Object> globalObj = Nan::GetCurrentContext()->Global();\n Local<Function> bufferConstructor = Local<Function>::Cast(\n globalObj->Get(Nan::New(\"Buffer\").ToLocalChecked()));\n Local<Value> consArgs[3] = {\n slowBuffer,\n Nan::New<Number>(::node::Buffer::Length(slowBuffer)),\n Nan::New<Number>(0)\n };\n Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);\n return scope.Escape(fastBuffer);\n}\n} \/\/ namespace node\n} \/\/ namespace grpc\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2016 Rhys Ulerich\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include <iterator>\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <descendu\/hexmap.hpp>\n#include <descendu\/tile.hpp>\n\nusing namespace descendu;\n\nTEST_CASE( \"hexmap\" ) {\n\n hexmap<tile> m;\n typedef hexmap<tile>::key_type key_type;\n\n SECTION( \"conjure\" ) {\n \/\/ Empty on construction\n REQUIRE( m.cbegin() == m.cend() );\n\n \/\/ Insertion with explicit type\n m.conjure(key_type(0, 0));\n auto a = m.cbegin();\n std::advance(a, 1);\n REQUIRE( a == m.cend() );\n REQUIRE( 1 == m.size() );\n\n \/\/ Idempotent re-insertion\n m.conjure(key_type(0, 0));\n auto b = m.cbegin();\n std::advance(b, 1);\n REQUIRE( b == m.cend() );\n REQUIRE( 1 == m.size() );\n\n \/\/ Insertion with nicety provided by hex\n m.conjure(key_type(1, 0));\n auto c = m.cbegin();\n std::advance(c, 2);\n REQUIRE( c == m.cend() );\n REQUIRE( 2 == m.size() );\n }\n\n SECTION( \"mutable\" ) {\n auto& a = m.conjure({0, 0});\n a.cannon.increase(1);\n REQUIRE( a.cannon.total() == 1 );\n\n auto& b = m.lookup({0, 0}).value();\n REQUIRE( b.cannon.total() == 1 );\n\n \/\/ No clobber of existing entry\n auto& c = m.conjure({0, 0});\n REQUIRE( c.cannon.total() == 1 );\n }\n\n SECTION( \"not_found\" ) {\n REQUIRE( !m.lookup({0, 0}).has_value() );\n REQUIRE( !m.lookup({0, 0}) );\n }\n\n}\n\nTEST_CASE( \"breadth_first_search\" ) {\n\n hexmap<int> m;\n typedef hexmap<tile>::key_type key_type;\n\n SECTION( \"origin_in_map\" ) {\n \/\/ Add origin\n m.conjure({0, 0});\n \/\/ Search\n const auto& retval = breadth_first_search(\n m,\n key_type(0, 0),\n [](const auto&) { return search_result::include; },\n 555);\n \/\/ Considered origin\n REQUIRE( retval.size() == 1 );\n \/\/ Origin considered and provides self-referencing path\n REQUIRE( retval.lookup({0, 0}) );\n REQUIRE( retval.lookup({0, 0}).value() == key_type(0, 0) );\n\n }\n\n SECTION( \"origin_not_in_map\" ) {\n \/\/ Origin not added\n \/\/ Search\n const auto& retval = breadth_first_search(\n m,\n key_type(0, 0),\n [](const auto&) { return search_result::include; },\n 555);\n \/\/ Considered origin\n REQUIRE( retval.size() == 1 );\n \/\/ Considered origin involves and empty optional\n REQUIRE( !retval.lookup({0, 0}).value() );\n }\n\n SECTION( \"linear\" ) {\n m.conjure({+0, +0});\n m.conjure({+0, -1});\n m.conjure({+0, -2});\n const auto& retval = breadth_first_search(\n m,\n key_type(0, 0),\n [](const auto&) { return search_result::include; },\n 555);\n REQUIRE( retval.size() == 3 );\n REQUIRE( retval.lookup({+0, -2}).value() == key_type(+0, -1) );\n REQUIRE( retval.lookup({+0, -1}).value() == key_type(+0, +0) );\n REQUIRE( retval.lookup({+0, +0}).value() == key_type(+0, +0) );\n }\n\n SECTION( \"outward\" ) {\n m.conjure({+0, +0});\n m.conjure({+0, -1});\n m.conjure({+1, -1});\n m.conjure({+1, +0});\n m.conjure({+0, +1});\n m.conjure({-1, +1});\n m.conjure({-1, +0});\n const auto& retval = breadth_first_search(\n m,\n key_type(0, 0),\n [](const auto&) { return search_result::include; },\n 555);\n REQUIRE( retval.size() == 7 );\n REQUIRE( retval.lookup({+0, +0}).value() == key_type(+0, +0) );\n \/\/ TODO FIXME\n \/\/ REQUIRE( retval.lookup({+0, -1}).value().value() == key_type(+0, +0) );\n \/\/ REQUIRE( retval.lookup({+1, -1}).value().value() == key_type(+0, +0) );\n \/\/ REQUIRE( retval.lookup({+1, +0}).value().value() == key_type(+0, +0) );\n \/\/ REQUIRE( retval.lookup({+0, +1}).value().value() == key_type(+0, +0) );\n \/\/ REQUIRE( retval.lookup({-1, +1}).value().value() == key_type(+0, +0) );\n \/\/ REQUIRE( retval.lookup({-1, +0}).value().value() == key_type(+0, +0) );\n }\n\n}\n<commit_msg>Beef up line search testing<commit_after>\/*\n * Copyright (C) 2016 Rhys Ulerich\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include <iterator>\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <descendu\/hexmap.hpp>\n#include <descendu\/tile.hpp>\n\nusing namespace descendu;\n\nTEST_CASE( \"hexmap\" ) {\n\n hexmap<tile> m;\n typedef hexmap<tile>::key_type key_type;\n\n SECTION( \"conjure\" ) {\n \/\/ Empty on construction\n REQUIRE( m.cbegin() == m.cend() );\n\n \/\/ Insertion with explicit type\n m.conjure(key_type(0, 0));\n auto a = m.cbegin();\n std::advance(a, 1);\n REQUIRE( a == m.cend() );\n REQUIRE( 1 == m.size() );\n\n \/\/ Idempotent re-insertion\n m.conjure(key_type(0, 0));\n auto b = m.cbegin();\n std::advance(b, 1);\n REQUIRE( b == m.cend() );\n REQUIRE( 1 == m.size() );\n\n \/\/ Insertion with nicety provided by hex\n m.conjure(key_type(1, 0));\n auto c = m.cbegin();\n std::advance(c, 2);\n REQUIRE( c == m.cend() );\n REQUIRE( 2 == m.size() );\n }\n\n SECTION( \"mutable\" ) {\n auto& a = m.conjure({0, 0});\n a.cannon.increase(1);\n REQUIRE( a.cannon.total() == 1 );\n\n auto& b = m.lookup({0, 0}).value();\n REQUIRE( b.cannon.total() == 1 );\n\n \/\/ No clobber of existing entry\n auto& c = m.conjure({0, 0});\n REQUIRE( c.cannon.total() == 1 );\n }\n\n SECTION( \"not_found\" ) {\n REQUIRE( !m.lookup({0, 0}).has_value() );\n REQUIRE( !m.lookup({0, 0}) );\n }\n\n}\n\nTEST_CASE( \"breadth_first_search\" ) {\n\n hexmap<int> m;\n typedef hexmap<tile>::key_type key_type;\n\n SECTION( \"origin_in_map\" ) {\n \/\/ Add origin\n m.conjure({0, 0});\n \/\/ Search\n const auto& retval = breadth_first_search(\n m,\n key_type(0, 0),\n [](const auto&) { return search_result::include; },\n 555);\n \/\/ Considered origin\n REQUIRE( retval.size() == 1 );\n \/\/ Origin considered and provides self-referencing path\n REQUIRE( retval.lookup({0, 0}) );\n REQUIRE( retval.lookup({0, 0}).value() == key_type(0, 0) );\n\n }\n\n SECTION( \"origin_not_in_map\" ) {\n \/\/ Origin not added\n \/\/ Search\n const auto& retval = breadth_first_search(\n m,\n key_type(0, 0),\n [](const auto&) { return search_result::include; },\n 555);\n \/\/ Considered origin\n REQUIRE( retval.size() == 1 );\n \/\/ Considered origin involves and empty optional\n REQUIRE( !retval.lookup({0, 0}).value() );\n }\n\n SECTION( \"linear_one_direction\" ) {\n m.conjure({+0, +0});\n m.conjure({+0, -1});\n m.conjure({+0, -2});\n const auto& retval = breadth_first_search(\n m,\n key_type(0, 0),\n [](const auto&) { return search_result::include; },\n 555);\n REQUIRE( retval.size() == 3 );\n REQUIRE( retval.lookup({+0, -2}).value() == key_type(+0, -1) );\n REQUIRE( retval.lookup({+0, -1}).value() == key_type(+0, +0) );\n REQUIRE( retval.lookup({+0, +0}).value() == key_type(+0, +0) );\n }\n\n SECTION( \"linear_all_directions\" ) {\n const auto& p0 = key_type(+3, +3);\n const std::vector<int> directions = {0, 1, 2, 3, 4, 5};\n for (const auto direction : directions) {\n \/\/ Construct 4 edges in the given direction\n hexmap<int> o;\n o.conjure(p0);\n const auto& p1 = p0.neighbor(direction);\n o.conjure(p1);\n const auto& p2 = p1.neighbor(direction);\n o.conjure(p2);\n const auto& p3 = p2.neighbor(direction);\n o.conjure(p3);\n const auto& p4 = p3.neighbor(direction);\n o.conjure(p4);\n \/\/ Search three edges in the direction\n const auto& retval = breadth_first_search(\n o,\n p0,\n [](const auto&) { return search_result::include; },\n 3);\n \/\/ Origin plus 3 close-enough edges\n REQUIRE( retval.size() == 4 );\n REQUIRE( retval.lookup(p3).value().value() == p2 );\n REQUIRE( retval.lookup(p2).value().value() == p1 );\n REQUIRE( retval.lookup(p1).value().value() == p0 );\n REQUIRE( retval.lookup(p0).value().value() == p0 );\n \/\/ Fourth edge was too far\n REQUIRE( !retval.lookup(p4) );\n }\n }\n\n\/\/ SECTION( \"outward\" ) {\n\/\/ m.conjure({+0, +0});\n\/\/ m.conjure({+1, +0});\n\/\/ m.conjure({+1, -1});\n\/\/ m.conjure({+0, -1});\n\/\/ m.conjure({-1, +0});\n\/\/ m.conjure({-1, +1});\n\/\/ m.conjure({+0, +1});\n\/\/ const auto& retval = breadth_first_search(\n\/\/ m,\n\/\/ key_type(0, 0),\n\/\/ [](const auto&) { return search_result::include; },\n\/\/ 555);\n\/\/ REQUIRE( retval.size() == 7 );\n\/\/ REQUIRE( retval.lookup({+0, +0}).value() == key_type(+0, +0) );\n\/\/ REQUIRE( retval.lookup({+1, +0}).value().value() == key_type(+0, +0) );\n\/\/ REQUIRE( retval.lookup({+1, -1}).value().value() == key_type(+0, +0) );\n\/\/ REQUIRE( retval.lookup({+0, -1}).value().value() == key_type(+0, +0) );\n\/\/ REQUIRE( retval.lookup({-1, +0}).value().value() == key_type(+0, +0) );\n\/\/ REQUIRE( retval.lookup({-1, +1}).value().value() == key_type(+0, +0) );\n\/\/ REQUIRE( retval.lookup({+0, +1}).value().value() == key_type(+0, +0) );\n\/\/ }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Reminder program of C++ fundamentals.\n#include <iostream>\n\nint main()\n{\n std::cout << \"Hello World!\";\n}\n<commit_msg>Terminating newline.<commit_after>\/\/ Reminder program of C++ fundamentals.\n#include <iostream>\n\nint main()\n{\n std::cout << \"Hello World!\" << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Register adjacent HiRes images to each other,\n\/\/ initialised by loaded transforms from previous registration\n\n#include \"boost\/filesystem.hpp\"\n#include \"boost\/program_options.hpp\"\n\n\/\/ my files\n#include \"Stack.hpp\"\n#include \"RegistrationBuilder.hpp\"\n#include \"StackIOHelpers.hpp\"\n#include \"IOHelpers.hpp\"\n#include \"StackTransforms.hpp\"\n#include \"Dirs.hpp\"\n#include \"OptimizerConfig.hpp\"\n#include \"ScaleImages.hpp\"\n#include \"SimpleTransformWriter.hpp\"\n#include \"MetricValueWriter.hpp\"\n\nusing namespace boost::filesystem;\nnamespace po = boost::program_options;\nusing namespace boost;\n\n\/\/ function declarations\npo::variables_map parse_arguments(int argc, char *argv[]);\n\nint main(int argc, char *argv[]) {\n po::variables_map vm = parse_arguments(argc, argv);\n \n \/\/ Process command line arguments\n Dirs::SetDataSet(argv[1]);\n Dirs::SetOutputDirName(argv[2]);\n string transform = vm[\"transform\"].as<string>();\n string roi = vm.count(\"roi\") ? vm[\"roi\"].as<string>() : \"ROI\";\n \n \/\/ for globally available registrationParameters(),\n \/\/ used in e.g. OptimizerConfig\n Dirs::SetParamsFile( Dirs::ConfigDir() + \"HiRes_pair_parameters.yml\" );\n \n \/\/ construct basenames and paths\n vector< string > basenames = getBasenames(Dirs::ImageList());\n vector< string > paths = constructPaths(Dirs::SliceDir(), basenames, \".bmp\");\n \n \/\/ initialise stack with correct spacings, sizes, basenames etc\n typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;\n StackType::SliceVectorType originalImages = readImages< StackType::SliceType >(paths);\n scaleImages< StackType::SliceType >(originalImages, getSpacings<2>(\"HiRes\"));\n shared_ptr< StackType > originalStack = make_shared< StackType >(originalImages, getSpacings<3>(\"LoRes\"), getSize(roi));\n originalStack->SetBasenames(basenames);\n \n Load(*originalStack, Dirs::HiResTransformsDir() + transform + \"\/\");\n \n \/\/ move stack origins to ROI\n itk::Vector< double, 2 > translation = StackTransforms::GetLoResTranslation(roi) - StackTransforms::GetLoResTranslation(\"whole_heart\");\n StackTransforms::Translate(*originalStack, translation);\n \n \/\/ generate images\n originalStack->updateVolumes();\n \n \/\/ construct 2 stacks from resampled images: 1:n-1 and 2:n\n StackType::SliceVectorType resampledImages = originalStack->GetResampledSlices();\n StackType::SliceVectorType fixedImages(++resampledImages.begin(), resampledImages.end());\n StackType::SliceVectorType movingImages(resampledImages.begin(), --resampledImages.end());\n StackType::MaskVectorType2D resampledMasks = originalStack->GetResampled2DMasks();\n StackType::MaskVectorType2D fixedMasks(++resampledMasks.begin(), resampledMasks.end());\n StackType::MaskVectorType2D movingMasks(resampledMasks.begin(), --resampledMasks.end());\n shared_ptr< StackType > fixedStack = make_shared< StackType >(fixedImages, fixedMasks, getSpacings<3>(\"LoRes\"), getSize(roi));\n shared_ptr< StackType > movingStack = make_shared< StackType >(movingImages, movingMasks, getSpacings<3>(\"LoRes\"), getSize(roi));\n\n \/\/ Build registration\n typedef RegistrationBuilder< StackType > RegistrationBuilderType;\n RegistrationBuilderType registrationBuilder;\n RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();\n \n \/\/ Initialize both stacks with CenteredRigid2DTransform\n StackTransforms::InitializeToCommonCentre(*fixedStack);\n StackTransforms::InitializeToCommonCentre(*movingStack);\n \n \/\/ Configure moving centre and optimiser scales\n StackTransforms::SetMovingStackCenterWithFixedStack( *fixedStack, *movingStack );\n \n \/\/ Convert moving CenteredRigid2DTransform to AffineTransform\n typedef itk::CenteredAffineTransform< double, 2 > AffineTransformType;\n StackTransforms::InitializeFromCurrentTransforms< StackType, AffineTransformType >(*movingStack);\n \n OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );\n \n fixedStack->updateVolumes();\n movingStack->updateVolumes();\n string outputDir = Dirs::ResultsDir() + \"HiResPairs\/\";\n create_directory( outputDir );\n writeImage< StackType::VolumeType >( movingStack->GetVolume(), outputDir + \"moving_before.mha\");\n \n \/\/ Get number of slices for registration and transform basenames\n unsigned int number_of_slices = fixedStack->GetSize();\n \n \/\/ Build movingStack's basenames\n vector< string > transformBasenames;\n for(unsigned int slice_number=0; slice_number < number_of_slices; ++slice_number)\n {\n \/\/ construct basenames e.g. \"0001_0002\"\n transformBasenames.push_back(basenames[slice_number] + \"_\" + basenames[slice_number + 1]);\n }\n movingStack->SetBasenames(transformBasenames);\n \n \/\/ Configure intermediate transform writer\n SimpleTransformWriter::Pointer simpleTransformWriter = SimpleTransformWriter::New();\n string intermediateTransformsDir = outputDir + \"IntermediateTransforms\/\" + transform + \"\/\";\n remove_all( intermediateTransformsDir );\n simpleTransformWriter->setOutputRootDir(intermediateTransformsDir);\n simpleTransformWriter->setStack(movingStack.get());\n registration->GetOptimizer()->AddObserver( itk::IterationEvent(), simpleTransformWriter );\n \n \/\/ Configure metric value writer\n MetricValueWriter::Pointer metricValueWriter = MetricValueWriter::New();\n string metricValueDir = outputDir + \"MetricValues\/\" + transforms + \"\/\";\n remove_all(metricValueDir);\n metricValueWriter->setOutputRootDir(metricValueDir);\n metricValueWriter->setStack(movingStack.get());\n registration->GetOptimizer()->AddObserver( itk::IterationEvent(), metricValueWriter );\n \n \/\/ Perform registration\n for(unsigned int slice_number=0; slice_number < number_of_slices; ++slice_number)\n {\n cout << \"Registering slices \" << basenames[slice_number] <<\n \" and \" << basenames[slice_number + 1] << \"...\" << endl;\n \n simpleTransformWriter->setSliceNumber(slice_number);\n metricValueWriter->setSliceNumber(slice_number);\n \n registration->SetFixedImage( fixedStack->GetOriginalImage(slice_number) );\n registration->SetMovingImage( movingStack->GetOriginalImage(slice_number) );\n registration->GetMetric()->SetFixedImageMask( fixedStack->GetOriginal2DMask(slice_number) );\n registration->GetMetric()->SetMovingImageMask( movingStack->GetOriginal2DMask(slice_number) );\n registration->SetTransform( movingStack->GetTransform(slice_number) );\n registration->SetInitialTransformParameters( movingStack->GetTransform(slice_number)->GetParameters() );\n \n try { registration->Update(); }\n catch( itk::ExceptionObject & err )\n { \n std::cerr << \"ExceptionObject caught !\" << std::endl;\n std::cerr << err << std::endl;\n return EXIT_FAILURE;\n }\n }\n \n \/\/ Save transforms and inverse transforms\n string transformsDir = outputDir + \"FinalTransforms\/\";\n create_directory(transformsDir);\n Save(*movingStack, transformsDir);\n \n \/\/ Write images\n fixedStack->updateVolumes();\n movingStack->updateVolumes();\n writeImage< StackType::VolumeType >( originalStack->GetVolume(), outputDir + \"original.mha\");\n writeImage< StackType::VolumeType >( fixedStack->GetVolume(), outputDir + \"fixed.mha\");\n writeImage< StackType::VolumeType >( movingStack->GetVolume(), outputDir + \"moving_after.mha\");\n writeImage< StackType::MaskVolumeType >( fixedStack->Get3DMask()->GetImage(), outputDir + \"fixed_mask.mha\");\n writeImage< StackType::MaskVolumeType >( movingStack->Get3DMask()->GetImage(), outputDir + \"moving_mask.mha\");\n \n return EXIT_SUCCESS;\n}\n\npo::variables_map parse_arguments(int argc, char *argv[])\n{\n \/\/ Declare the supported options.\n po::options_description opts(\"Options\");\n opts.add_options()\n (\"help,h\", \"produce help message\")\n (\"dataSet\", po::value<string>(), \"which rat to use\")\n (\"outputDir\", po::value<string>(), \"directory to place results\")\n (\"transform\", po::value<string>(), \"Type of ITK transform to start from\")\n (\"roi\", po::value<string>(), \"region of interest e.g. papillary_insertion\")\n (\"fixedBasename\", po::value<string>(), \"basename of fixed slice e.g. 0196\")\n (\"movingBasename\", po::value<string>(), \"basename of moving slice e.g. 0197\")\n ;\n \n po::positional_options_description p;\n p.add(\"dataSet\", 1)\n .add(\"outputDir\", 1)\n .add(\"transform\", 1)\n .add(\"roi\", 1);\n \n \/\/ parse command line\n po::variables_map vm;\n\ttry\n\t{\n po::store(po::command_line_parser(argc, argv)\n .options(opts)\n .positional(p)\n .run(),\n vm);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t cerr << \"caught command-line parsing error\" << endl;\n std::cerr << e.what() << std::endl;\n exit(EXIT_FAILURE);\n }\n po::notify(vm);\n \n \/\/ if help is specified, or positional args aren't present\n if(vm.count(\"help\") ||\n !vm.count(\"dataSet\") ||\n !vm.count(\"outputDir\") ||\n !vm.count(\"transform\") ||\n (vm.count(\"fixedBasename\") != vm.count(\"movingBasename\")) )\n {\n cerr << \"Usage: \"\n << argv[0]\n << \" [--dataSet=]RatX [--outputDir=]my_dir\"\n << \" [--transform=]CenteredAffineTransform\"\n << \" [Options]\"\n << endl << endl;\n cerr << opts << \"\\n\";\n exit(EXIT_FAILURE);\n }\n \n return vm;\n}\n<commit_msg>Ignore identical adjacent slices<commit_after>\/\/ Register adjacent HiRes images to each other,\n\/\/ initialised by loaded transforms from previous registration\n\n#include \"boost\/filesystem.hpp\"\n#include \"boost\/program_options.hpp\"\n\n\/\/ my files\n#include \"Stack.hpp\"\n#include \"RegistrationBuilder.hpp\"\n#include \"StackIOHelpers.hpp\"\n#include \"IOHelpers.hpp\"\n#include \"StackTransforms.hpp\"\n#include \"Dirs.hpp\"\n#include \"OptimizerConfig.hpp\"\n#include \"ScaleImages.hpp\"\n#include \"SimpleTransformWriter.hpp\"\n#include \"MetricValueWriter.hpp\"\n\nusing namespace boost::filesystem;\nnamespace po = boost::program_options;\nusing namespace boost;\n\n\/\/ function declarations\npo::variables_map parse_arguments(int argc, char *argv[]);\n\nint main(int argc, char *argv[]) {\n po::variables_map vm = parse_arguments(argc, argv);\n \n \/\/ Process command line arguments\n Dirs::SetDataSet(argv[1]);\n Dirs::SetOutputDirName(argv[2]);\n string transform = vm[\"transform\"].as<string>();\n string roi = vm.count(\"roi\") ? vm[\"roi\"].as<string>() : \"ROI\";\n \n \/\/ for globally available registrationParameters(),\n \/\/ used in e.g. OptimizerConfig\n Dirs::SetParamsFile( Dirs::ConfigDir() + \"HiRes_pair_parameters.yml\" );\n \n \/\/ construct basenames and paths\n vector< string > basenames = getBasenames(Dirs::ImageList());\n vector< string > paths = constructPaths(Dirs::SliceDir(), basenames, \".bmp\");\n \n \/\/ initialise stack with correct spacings, sizes, basenames etc\n typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;\n StackType::SliceVectorType originalImages = readImages< StackType::SliceType >(paths);\n scaleImages< StackType::SliceType >(originalImages, getSpacings<2>(\"HiRes\"));\n shared_ptr< StackType > originalStack = make_shared< StackType >(originalImages, getSpacings<3>(\"LoRes\"), getSize(roi));\n originalStack->SetBasenames(basenames);\n \n Load(*originalStack, Dirs::HiResTransformsDir() + transform + \"\/\");\n \n \/\/ move stack origins to ROI\n itk::Vector< double, 2 > translation = StackTransforms::GetLoResTranslation(roi) - StackTransforms::GetLoResTranslation(\"whole_heart\");\n StackTransforms::Translate(*originalStack, translation);\n \n \/\/ generate images\n originalStack->updateVolumes();\n \n \/\/ construct 2 stacks from resampled images: 1:n-1 and 2:n\n StackType::SliceVectorType resampledImages = originalStack->GetResampledSlices();\n StackType::SliceVectorType fixedImages(++resampledImages.begin(), resampledImages.end());\n StackType::SliceVectorType movingImages(resampledImages.begin(), --resampledImages.end());\n StackType::MaskVectorType2D resampledMasks = originalStack->GetResampled2DMasks();\n StackType::MaskVectorType2D fixedMasks(++resampledMasks.begin(), resampledMasks.end());\n StackType::MaskVectorType2D movingMasks(resampledMasks.begin(), --resampledMasks.end());\n shared_ptr< StackType > fixedStack = make_shared< StackType >(fixedImages, fixedMasks, getSpacings<3>(\"LoRes\"), getSize(roi));\n shared_ptr< StackType > movingStack = make_shared< StackType >(movingImages, movingMasks, getSpacings<3>(\"LoRes\"), getSize(roi));\n\n \/\/ Build registration\n typedef RegistrationBuilder< StackType > RegistrationBuilderType;\n RegistrationBuilderType registrationBuilder;\n RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();\n \n \/\/ Initialize both stacks with CenteredRigid2DTransform\n StackTransforms::InitializeToCommonCentre(*fixedStack);\n StackTransforms::InitializeToCommonCentre(*movingStack);\n \n \/\/ Configure moving centre and optimiser scales\n StackTransforms::SetMovingStackCenterWithFixedStack( *fixedStack, *movingStack );\n \n \/\/ Convert moving CenteredRigid2DTransform to AffineTransform\n typedef itk::CenteredAffineTransform< double, 2 > AffineTransformType;\n StackTransforms::InitializeFromCurrentTransforms< StackType, AffineTransformType >(*movingStack);\n \n OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );\n \n fixedStack->updateVolumes();\n movingStack->updateVolumes();\n string outputDir = Dirs::ResultsDir() + \"HiResPairs\/\";\n create_directory( outputDir );\n writeImage< StackType::VolumeType >( movingStack->GetVolume(), outputDir + \"moving_before.mha\");\n \n \/\/ Get number of slices for registration and transform basenames\n unsigned int number_of_slices = fixedStack->GetSize();\n \n \/\/ Build movingStack's basenames\n vector< string > transformBasenames;\n for(unsigned int slice_number=0; slice_number < number_of_slices; ++slice_number)\n {\n \/\/ construct basenames e.g. \"0001_0002\"\n transformBasenames.push_back(basenames[slice_number] + \"_\" + basenames[slice_number + 1]);\n }\n movingStack->SetBasenames(transformBasenames);\n \n \/\/ Configure intermediate transform writer\n SimpleTransformWriter::Pointer simpleTransformWriter = SimpleTransformWriter::New();\n string intermediateTransformsDir = outputDir + \"IntermediateTransforms\/\" + transform + \"\/\";\n remove_all( intermediateTransformsDir );\n simpleTransformWriter->setOutputRootDir(intermediateTransformsDir);\n simpleTransformWriter->setStack(movingStack.get());\n registration->GetOptimizer()->AddObserver( itk::IterationEvent(), simpleTransformWriter );\n \n \/\/ Configure metric value writer\n MetricValueWriter::Pointer metricValueWriter = MetricValueWriter::New();\n string metricValueDir = outputDir + \"MetricValues\/\" + transform + \"\/\";\n remove_all(metricValueDir);\n metricValueWriter->setOutputRootDir(metricValueDir);\n metricValueWriter->setStack(movingStack.get());\n registration->GetOptimizer()->AddObserver( itk::IterationEvent(), metricValueWriter );\n\n \/\/ Perform registration\n for(unsigned int slice_number=0; slice_number < number_of_slices; ++slice_number)\n {\n if(basenames[slice_number] != basenames[slice_number + 1])\n {\n cout << \"Registering slices \" << basenames[slice_number] <<\n \" and \" << basenames[slice_number + 1] << \"...\" << endl;\n \n simpleTransformWriter->setSliceNumber(slice_number);\n metricValueWriter->setSliceNumber(slice_number);\n \n registration->SetFixedImage( fixedStack->GetOriginalImage(slice_number) );\n registration->SetMovingImage( movingStack->GetOriginalImage(slice_number) );\n registration->GetMetric()->SetFixedImageMask( fixedStack->GetOriginal2DMask(slice_number) );\n registration->GetMetric()->SetMovingImageMask( movingStack->GetOriginal2DMask(slice_number) );\n registration->SetTransform( movingStack->GetTransform(slice_number) );\n registration->SetInitialTransformParameters( movingStack->GetTransform(slice_number)->GetParameters() );\n \n try { registration->Update(); }\n catch( itk::ExceptionObject & err )\n { \n std::cerr << \"ExceptionObject caught !\" << std::endl;\n std::cerr << err << std::endl;\n return EXIT_FAILURE;\n }\n }\n else\n {\n cout << \"Skipping identical slice pair \"\n << basenames[slice_number] << \" and \"\n << basenames[slice_number + 1]\n << \"...\" << endl;\n }\n }\n \n \/\/ Save transforms and inverse transforms\n string transformsDir = outputDir + \"FinalTransforms\/\";\n create_directory(transformsDir);\n Save(*movingStack, transformsDir);\n \n \/\/ Write images\n fixedStack->updateVolumes();\n movingStack->updateVolumes();\n writeImage< StackType::VolumeType >( originalStack->GetVolume(), outputDir + \"original.mha\");\n writeImage< StackType::VolumeType >( fixedStack->GetVolume(), outputDir + \"fixed.mha\");\n writeImage< StackType::VolumeType >( movingStack->GetVolume(), outputDir + \"moving_after.mha\");\n writeImage< StackType::MaskVolumeType >( fixedStack->Get3DMask()->GetImage(), outputDir + \"fixed_mask.mha\");\n writeImage< StackType::MaskVolumeType >( movingStack->Get3DMask()->GetImage(), outputDir + \"moving_mask.mha\");\n \n return EXIT_SUCCESS;\n}\n\npo::variables_map parse_arguments(int argc, char *argv[])\n{\n \/\/ Declare the supported options.\n po::options_description opts(\"Options\");\n opts.add_options()\n (\"help,h\", \"produce help message\")\n (\"dataSet\", po::value<string>(), \"which rat to use\")\n (\"outputDir\", po::value<string>(), \"directory to place results\")\n (\"transform\", po::value<string>(), \"Type of ITK transform to start from\")\n (\"roi\", po::value<string>(), \"region of interest e.g. papillary_insertion\")\n (\"fixedBasename\", po::value<string>(), \"basename of fixed slice e.g. 0196\")\n (\"movingBasename\", po::value<string>(), \"basename of moving slice e.g. 0197\")\n ;\n \n po::positional_options_description p;\n p.add(\"dataSet\", 1)\n .add(\"outputDir\", 1)\n .add(\"transform\", 1)\n .add(\"roi\", 1);\n \n \/\/ parse command line\n po::variables_map vm;\n\ttry\n\t{\n po::store(po::command_line_parser(argc, argv)\n .options(opts)\n .positional(p)\n .run(),\n vm);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t cerr << \"caught command-line parsing error\" << endl;\n std::cerr << e.what() << std::endl;\n exit(EXIT_FAILURE);\n }\n po::notify(vm);\n \n \/\/ if help is specified, or positional args aren't present\n if(vm.count(\"help\") ||\n !vm.count(\"dataSet\") ||\n !vm.count(\"outputDir\") ||\n !vm.count(\"transform\") ||\n (vm.count(\"fixedBasename\") != vm.count(\"movingBasename\")) )\n {\n cerr << \"Usage: \"\n << argv[0]\n << \" [--dataSet=]RatX [--outputDir=]my_dir\"\n << \" [--transform=]CenteredAffineTransform\"\n << \" [Options]\"\n << endl << endl;\n cerr << opts << \"\\n\";\n exit(EXIT_FAILURE);\n }\n \n return vm;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2014 Tavendo 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\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <map>\n#include <memory>\n#include <iostream>\n\n#define BOOST_THREAD_PROVIDES_FUTURE\n#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION\n#define BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY\n#include <boost\/thread\/future.hpp>\n#include <boost\/asio.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n\nstruct rpcsvc {\n\n rpcsvc (asio::io_service& io) : m_io(io), m_call_id(0) {\n }\n\n struct Call {\n std::shared_ptr<asio::deadline_timer> m_timer;\n promise<float> m_promise;\n };\n\n future<float> slowsquare(float x, int delay) {\n\n m_call_id += 1;\n m_calls[m_call_id] = Call();\n\n std::shared_ptr<asio::deadline_timer>\n timer(new asio::deadline_timer(m_io, posix_time::seconds(delay)));\n\n m_calls[m_call_id].m_timer = timer;\n\n int call_id = m_call_id;\n\n timer->async_wait(\n [=](system::error_code ec) { \n if (!ec) {\n\n \/\/ Question 1:\n \/\/\n \/\/ m_call_id seems to be captured by value, though we\n \/\/ said [=] in the lambda .. why? We workaround by\n \/\/ using a local var in the enclosing method body.\n \/\/\n cout << m_call_id << \" - \" << call_id << endl;\n\n this->m_calls[call_id].m_promise.set_value(x * x);\n this->m_calls.erase(call_id);\n } else {\n cout << \"Error in timer: \" << ec << endl;\n }\n }\n );\n\n cout << \"call \" << m_call_id << \" issued\" << endl;\n\n return m_calls[m_call_id].m_promise.get_future();\n }\n\n asio::io_service& m_io;\n int m_call_id;\n map<int, Call> m_calls;\n};\n\n\nint main () {\n\n try {\n asio::io_service io;\n\n rpcsvc rpc(io);\n\n auto f1 = rpc.slowsquare(2, 2).then([](future<float> f) {\n cout << \"call 1 returned\" << endl;\n cout << \"result 1: \" << f.get() << endl;\n });\n\n auto f2 = rpc.slowsquare(3, 1).then([](future<float> f) {\n cout << \"call 2 returned\" << endl;\n cout << \"result 2: \" << f.get() << endl;\n });\n\n auto f3 = when_all(std::move(f1), std::move(f2));\n auto f4 = f3.then([](decltype(f3)) {\n cout << \"done.\" << endl;\n });\n\n io.run();\n\n \/\/ Question 2:\n \/\/\n \/\/ Neither f3 nor f4 \"induce\" any work on ASIO reactor ..\n \/\/ so ASIO will end it's loop though the continuation\n \/\/ hasn't been executed yet. we workaround by \"manually\"\n \/\/ waiting .. but that seems suboptimal ..\n \/\/\n f4.get();\n\n }\n catch (std::exception& e) {\n cerr << e.what() << endl;\n return 1;\n }\n return 0;\n}\n<commit_msg>extend test case<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2014 Tavendo 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\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <map>\n#include <memory>\n#include <iostream>\n\n#define BOOST_THREAD_PROVIDES_FUTURE\n#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION\n#define BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY\n#include <boost\/thread\/future.hpp>\n#include <boost\/asio.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n\nstruct rpcsvc {\n\n rpcsvc (asio::io_service& io) : m_io(io), m_call_id(0) {\n }\n\n struct Call {\n std::shared_ptr<asio::deadline_timer> m_timer;\n promise<float> m_promise;\n };\n\n future<float> slowsquare(float x, float delay) {\n\n m_call_id += 1;\n m_calls[m_call_id] = Call();\n\n std::shared_ptr<asio::deadline_timer>\n timer(new asio::deadline_timer(m_io, posix_time::seconds(delay)));\n\n m_calls[m_call_id].m_timer = timer;\n\n int call_id = m_call_id;\n\n timer->async_wait(\n [=](system::error_code ec) { \n if (!ec) {\n\n \/\/ Question 1:\n \/\/\n \/\/ m_call_id seems to be captured by value, though we\n \/\/ said [=] in the lambda .. why? We workaround by\n \/\/ using a local var in the enclosing method body.\n \/\/\n cout << m_call_id << \" - \" << call_id << endl;\n\n this->m_calls[call_id].m_promise.set_value(x * x);\n this->m_calls.erase(call_id);\n } else {\n cout << \"Error in timer: \" << ec << endl;\n }\n }\n );\n\n cout << \"call \" << m_call_id << \" issued\" << endl;\n\n return m_calls[m_call_id].m_promise.get_future();\n }\n\n asio::io_service& m_io;\n int m_call_id;\n map<int, Call> m_calls;\n};\n\n\nint main () {\n\n try {\n asio::io_service io;\n\n rpcsvc rpc(io);\n\n auto f1 = rpc.slowsquare(2, 2).then([](future<float> f) {\n cout << \"call 1 returned\" << endl;\n cout << \"result 1: \" << f.get() << endl;\n });\n\n auto f2 = rpc.slowsquare(3, 1.1).then([](future<float> f) {\n cout << \"call 2 returned\" << endl;\n cout << \"result 2: \" << f.get() << endl;\n });\n\n auto f3 = rpc.slowsquare(4, 1).then([](future<float> f) {\n cout << \"call 3 returned\" << endl;\n cout << \"result 3: \" << f.get() << endl;\n });\n\n auto f12 = when_all(std::move(f1), std::move(f2));\n auto f12d = f12.then([](decltype(f12)) {\n cout << \"call 1\/2 done\" << endl;\n });\n\n\/*\n auto f23 = when_all(std::move(f2), std::move(f3));\n auto f23d = f23.then([](decltype(f23)) {\n cout << \"call 2\/3 done\" << endl;\n });\n\n auto f123 = when_all(std::move(f12d), std::move(f23d));\n auto f123d = f123.then([](decltype(f123)) {\n cout << \"all calls done\" << endl;\n });\n*\/\n io.run();\n\n \/\/ Question 2:\n \/\/\n \/\/ Neither f12 nor f12d (and etc) \"induce\" any work on\n \/\/ ASIO reactor .. so ASIO will end it's loop though the\n \/\/ continuation hasn't been executed yet. we workaround\n \/\/ by \"manually\" waiting .. but that seems suboptimal ..\n \/\/\n f12d.get();\n\n\n \/\/ Question 3:\n \/\/\n \/\/ When above f23,f23d,f123,f123d and the line below\n \/\/ is commented in, the program will deadlock somehow.\n \/\/ Why? And is there a safe (\"fool proof\") way to avoid\n \/\/ this kind of issues?\n \/\/f123d.get();\n }\n catch (std::exception& e) {\n cerr << e.what() << endl;\n return 1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"tls-cert-verifier-op.h\"\n\n#include <TelepathyQt\/PendingVariantMap>\n\n#include <KDebug>\n\nTlsCertVerifierOp::TlsCertVerifierOp(const Tp::AccountPtr &account,\n const Tp::ConnectionPtr &connection,\n const Tp::ChannelPtr &channel)\n : Tp::PendingOperation(channel),\n m_account(account),\n m_connection(connection),\n m_channel(channel)\n{\n QDBusObjectPath certificatePath = qdbus_cast<QDBusObjectPath>(channel->immutableProperties().value(\n TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(\".ServerCertificate\")));\n m_hostname = qdbus_cast<QString>(channel->immutableProperties().value(\n TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(\".Hostname\")));\n m_referenceIdentities = qdbus_cast<QStringList>(channel->immutableProperties().value(\n TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(\".ReferenceIdentities\")));\n\n m_authTLSCertificateIface = new Tp::Client::AuthenticationTLSCertificateInterface(\n channel->dbusConnection(), channel->busName(), certificatePath.path());\n connect(m_authTLSCertificateIface->requestAllProperties(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(gotProperties(Tp::PendingOperation*)));\n}\n\nTlsCertVerifierOp::~TlsCertVerifierOp()\n{\n}\n\nvoid TlsCertVerifierOp::gotProperties(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Unable to retrieve properties from AuthenticationTLSCertificate object at\" <<\n m_authTLSCertificateIface->path();\n m_channel->requestClose();\n setFinishedWithError(op->errorName(), op->errorMessage());\n return;\n }\n\n \/\/ everything ok, we can return from handleChannels now\n Q_EMIT ready(this);\n\n Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);\n QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());\n m_certType = qdbus_cast<QString>(props.value(QLatin1String(\"CertificateType\")));\n m_certData = qdbus_cast<CertificateDataList>(props.value(QLatin1String(\"CertificateChainData\")));\n\n \/\/ FIXME: verify cert\n setFinished();\n}\n\n#include \"tls-cert-verifier-op.moc\"\n<commit_msg>Very minimal prompt accept\/reject certificate<commit_after>\/*\n * Copyright (C) 2011 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"tls-cert-verifier-op.h\"\n\n#include <TelepathyQt\/PendingVariantMap>\n\n#include <KMessageBox>\n#include <KLocalizedString>\n#include <KDebug>\n\n#include <QSslCertificate>\n\nTlsCertVerifierOp::TlsCertVerifierOp(const Tp::AccountPtr &account,\n const Tp::ConnectionPtr &connection,\n const Tp::ChannelPtr &channel)\n : Tp::PendingOperation(channel),\n m_account(account),\n m_connection(connection),\n m_channel(channel)\n{\n QDBusObjectPath certificatePath = qdbus_cast<QDBusObjectPath>(channel->immutableProperties().value(\n TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(\".ServerCertificate\")));\n m_hostname = qdbus_cast<QString>(channel->immutableProperties().value(\n TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(\".Hostname\")));\n m_referenceIdentities = qdbus_cast<QStringList>(channel->immutableProperties().value(\n TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(\".ReferenceIdentities\")));\n\n m_authTLSCertificateIface = new Tp::Client::AuthenticationTLSCertificateInterface(\n channel->dbusConnection(), channel->busName(), certificatePath.path());\n connect(m_authTLSCertificateIface->requestAllProperties(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(gotProperties(Tp::PendingOperation*)));\n}\n\nTlsCertVerifierOp::~TlsCertVerifierOp()\n{\n}\n\nvoid TlsCertVerifierOp::gotProperties(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Unable to retrieve properties from AuthenticationTLSCertificate object at\" <<\n m_authTLSCertificateIface->path();\n m_channel->requestClose();\n setFinishedWithError(op->errorName(), op->errorMessage());\n return;\n }\n\n \/\/ everything ok, we can return from handleChannels now\n Q_EMIT ready(this);\n\n Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);\n QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());\n m_certType = qdbus_cast<QString>(props.value(QLatin1String(\"CertificateType\")));\n m_certData = qdbus_cast<CertificateDataList>(props.value(QLatin1String(\"CertificateChainData\")));\n\n if(m_certType.compare(QLatin1String(\"x509\"), Qt::CaseInsensitive)) {\n kWarning() << \"This is not an x509 certificate\";\n }\n\n Q_FOREACH (const QByteArray &data, m_certData) {\n \/\/ FIXME How to chech if it is QSsl::Pem or QSsl::Der? QSsl::Der works for kdetalk\n QList<QSslCertificate> certs = QSslCertificate::fromData(data, QSsl::Der);\n Q_FOREACH (const QSslCertificate &cert, certs) {\n kDebug() << cert;\n }\n }\n\n \/\/TODO Show a nice dialog\n if (KMessageBox::questionYesNo(0,\n i18n(\"<b>Accept this certificate?<\/b><br \/>%1\").arg(QString::fromLatin1(m_certData.first().toHex())),\n i18n(\"Untrusted certificate\")) == KMessageBox::Yes) {\n \/\/ TODO Remember value\n m_authTLSCertificateIface->Accept().waitForFinished();\n setFinished();\n } else {\n Tp::TLSCertificateRejectionList rejections;\n \/\/ TODO Add reason\n m_authTLSCertificateIface->Reject(rejections);\n m_channel->requestClose();\n setFinishedWithError(QLatin1String(\"Cert.Untrusted\"),\n QLatin1String(\"Certificate rejected by the user\"));\n }\n}\n\n#include \"tls-cert-verifier-op.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\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#include \"ModuleOutline.h\"\n\n#include \"DataSource.h\"\n#include \"Utilities.h\"\n#include \"pqProxiesWidget.h\"\n#include \"vtkNew.h\"\n#include \"vtkSMParaViewPipelineControllerWithRendering.h\"\n#include \"vtkSMProperty.h\"\n#include \"vtkSMPropertyHelper.h\"\n#include \"vtkSMSessionProxyManager.h\"\n#include \"vtkSMSourceProxy.h\"\n#include \"vtkSMViewProxy.h\"\n#include \"vtkSmartPointer.h\"\n#include <pqColorChooserButton.h>\n#include <vtkGridAxes3DActor.h>\n#include <vtkPVRenderView.h>\n#include <vtkProperty.h>\n#include <vtkRenderer.h>\n#include <vtkTextProperty.h>\n\n#include <QCheckBox>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QVBoxLayout>\n\nnamespace tomviz {\n\nusing pugi::xml_attribute;\nusing pugi::xml_node;\n\nModuleOutline::ModuleOutline(QObject* parentObject) : Superclass(parentObject)\n{\n}\n\nModuleOutline::~ModuleOutline()\n{\n this->finalize();\n}\n\nQIcon ModuleOutline::icon() const\n{\n return QIcon(\":\/icons\/pqProbeLocation.png\");\n}\n\nbool ModuleOutline::initialize(DataSource* data, vtkSMViewProxy* vtkView)\n{\n if (!this->Superclass::initialize(data, vtkView)) {\n return false;\n }\n\n vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n\n vtkSMSessionProxyManager* pxm = data->producer()->GetSessionProxyManager();\n\n \/\/ Create the outline filter.\n vtkSmartPointer<vtkSMProxy> proxy;\n proxy.TakeReference(pxm->NewProxy(\"filters\", \"OutlineFilter\"));\n\n this->OutlineFilter = vtkSMSourceProxy::SafeDownCast(proxy);\n Q_ASSERT(this->OutlineFilter);\n controller->PreInitializeProxy(this->OutlineFilter);\n vtkSMPropertyHelper(this->OutlineFilter, \"Input\").Set(data->producer());\n controller->PostInitializeProxy(this->OutlineFilter);\n controller->RegisterPipelineProxy(this->OutlineFilter);\n\n \/\/ Create the representation for it.\n this->OutlineRepresentation =\n controller->Show(this->OutlineFilter, 0, vtkView);\n vtkSMPropertyHelper(this->OutlineRepresentation, \"Position\")\n .Set(data->displayPosition(), 3);\n Q_ASSERT(this->OutlineRepresentation);\n \/\/ vtkSMPropertyHelper(this->OutlineRepresentation,\n \/\/ \"Representation\").Set(\"Outline\");\n this->OutlineRepresentation->UpdateVTKObjects();\n\n \/\/ Give the proxy a friendly name for the GUI\/Python world.\n if (auto p = convert<pqProxy*>(proxy)) {\n p->rename(label());\n }\n\n \/\/ Init the grid axes\n initializeGridAxes(data, vtkView);\n updateGridAxesColor(offWhite);\n\n return true;\n}\n\nbool ModuleOutline::finalize()\n{\n vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n controller->UnRegisterProxy(this->OutlineRepresentation);\n controller->UnRegisterProxy(this->OutlineFilter);\n\n if (m_view) {\n m_view->GetRenderer()->RemoveActor(m_gridAxes.Get());\n }\n\n this->OutlineFilter = nullptr;\n this->OutlineRepresentation = nullptr;\n return true;\n}\n\nbool ModuleOutline::serialize(pugi::xml_node& ns) const\n{\n xml_node rootNode = ns.append_child(\"properties\");\n\n xml_node visibilityNode = rootNode.append_child(\"visibility\");\n visibilityNode.append_attribute(\"enabled\") = visibility();\n\n xml_node gridAxesNode = rootNode.append_child(\"grid_axes\");\n gridAxesNode.append_attribute(\"enabled\") = m_gridAxes->GetVisibility() > 0;\n gridAxesNode.append_attribute(\"grid\") = m_gridAxes->GetGenerateGrid();\n\n xml_node color = gridAxesNode.append_child(\"color\");\n double rgb[3];\n m_gridAxes->GetProperty()->GetDiffuseColor(rgb);\n color.append_attribute(\"r\") = rgb[0];\n color.append_attribute(\"g\") = rgb[1];\n color.append_attribute(\"b\") = rgb[2];\n\n return true;\n}\n\nbool ModuleOutline::deserialize(const pugi::xml_node& ns)\n{\n xml_node rootNode = ns.child(\"properties\");\n if (!rootNode) {\n return false;\n }\n\n xml_node node = rootNode.child(\"visibility\");\n if (node) {\n xml_attribute att = node.attribute(\"enabled\");\n if (att) {\n setVisibility(att.as_bool());\n }\n }\n\n node = rootNode.child(\"grid_axes\");\n if (node) {\n xml_attribute att = node.attribute(\"enabled\");\n if (att) {\n m_gridAxes->SetVisibility(att.as_bool() ? 1 : 0);\n }\n att = node.attribute(\"grid\");\n if (att) {\n m_gridAxes->SetGenerateGrid(att.as_bool());\n }\n xml_node color = node.child(\"color\");\n if (color) {\n double rgb[3];\n att = color.attribute(\"r\");\n if (att) {\n rgb[0] = att.as_double();\n }\n att = color.attribute(\"g\");\n if (att) {\n rgb[1] = att.as_double();\n }\n att = color.attribute(\"b\");\n if (att) {\n rgb[2] = att.as_double();\n }\n updateGridAxesColor(rgb);\n }\n }\n\n return Module::deserialize(ns);\n}\n\nbool ModuleOutline::setVisibility(bool val)\n{\n Q_ASSERT(this->OutlineRepresentation);\n vtkSMPropertyHelper(this->OutlineRepresentation, \"Visibility\")\n .Set(val ? 1 : 0);\n this->OutlineRepresentation->UpdateVTKObjects();\n m_gridAxes->SetVisibility(val ? 1 : 0);\n return true;\n}\n\nbool ModuleOutline::visibility() const\n{\n if (this->OutlineRepresentation) {\n return vtkSMPropertyHelper(this->OutlineRepresentation, \"Visibility\")\n .GetAsInt() != 0;\n } else {\n return false;\n }\n}\n\nvoid ModuleOutline::addToPanel(QWidget* panel)\n{\n Q_ASSERT(panel && this->OutlineRepresentation);\n\n if (panel->layout()) {\n delete panel->layout();\n }\n\n QHBoxLayout* layout = new QHBoxLayout;\n QLabel* label = new QLabel(\"Color\");\n layout->addWidget(label);\n layout->addStretch();\n pqColorChooserButton* colorSelector = new pqColorChooserButton(panel);\n colorSelector->setShowAlphaChannel(false);\n layout->addWidget(colorSelector);\n\n \/\/ Show Grid?\n QHBoxLayout* showGridLayout = new QHBoxLayout;\n QCheckBox* showGrid = new QCheckBox(QString(\"Show Grid\"));\n showGrid->setChecked(m_gridAxes->GetGenerateGrid());\n\n connect(showGrid, &QCheckBox::stateChanged, this, [this](int state) {\n this->m_gridAxes->SetGenerateGrid(state == Qt::Checked);\n emit this->renderNeeded();\n });\n\n showGridLayout->addWidget(showGrid);\n\n \/\/ Show Axes?\n QHBoxLayout* showAxesLayout = new QHBoxLayout;\n QCheckBox* showAxes = new QCheckBox(QString(\"Show Axes\"));\n showAxes->setChecked(m_gridAxes->GetVisibility());\n \/\/ Disable \"Show Grid\" if axes not enabled\n if (!showAxes->isChecked()) {\n showGrid->setEnabled(false);\n }\n connect(showAxes, &QCheckBox::stateChanged, this,\n [this, showGrid](int state) {\n this->m_gridAxes->SetVisibility(state == Qt::Checked);\n \/\/ Uncheck \"Show Grid\" and disable it\n if (state == Qt::Unchecked) {\n showGrid->setChecked(false);\n showGrid->setEnabled(false);\n } else {\n showGrid->setEnabled(true);\n }\n\n emit this->renderNeeded();\n });\n showAxesLayout->addWidget(showAxes);\n\n QVBoxLayout* panelLayout = new QVBoxLayout;\n panelLayout->addItem(layout);\n panelLayout->addItem(showAxesLayout);\n panelLayout->addItem(showGridLayout);\n panelLayout->addStretch();\n panel->setLayout(panelLayout);\n\n m_links.addPropertyLink(\n colorSelector, \"chosenColorRgbF\", SIGNAL(chosenColorChanged(const QColor&)),\n this->OutlineRepresentation,\n this->OutlineRepresentation->GetProperty(\"DiffuseColor\"));\n\n this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged,\n [this](const QColor& color) {\n double rgb[3];\n rgb[0] = color.redF();\n rgb[1] = color.greenF();\n rgb[2] = color.blueF();\n updateGridAxesColor(rgb);\n\n });\n this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, this,\n &ModuleOutline::dataUpdated);\n}\n\nvoid ModuleOutline::dataUpdated()\n{\n m_links.accept();\n emit this->renderNeeded();\n}\n\nvoid ModuleOutline::dataSourceMoved(double newX, double newY, double newZ)\n{\n double pos[3] = { newX, newY, newZ };\n vtkSMPropertyHelper(this->OutlineRepresentation, \"Position\").Set(pos, 3);\n this->OutlineRepresentation->UpdateVTKObjects();\n this->m_gridAxes->SetPosition(newX, newY, newZ);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleOutline::isProxyPartOfModule(vtkSMProxy* proxy)\n{\n return (proxy == this->OutlineFilter.Get()) ||\n (proxy == this->OutlineRepresentation.Get());\n}\n\nstd::string ModuleOutline::getStringForProxy(vtkSMProxy* proxy)\n{\n if (proxy == this->OutlineFilter.Get()) {\n return \"Outline\";\n } else if (proxy == this->OutlineRepresentation.Get()) {\n return \"Representation\";\n } else {\n qWarning(\"Unknown proxy passed to module outline in save animation\");\n return \"\";\n }\n}\n\nvtkSMProxy* ModuleOutline::getProxyForString(const std::string& str)\n{\n if (str == \"Outline\") {\n return this->OutlineFilter.Get();\n } else if (str == \"Representation\") {\n return this->OutlineRepresentation.Get();\n } else {\n return nullptr;\n }\n}\n\nvoid ModuleOutline::updateGridAxesBounds(DataSource* dataSource)\n{\n Q_ASSERT(dataSource);\n double bounds[6];\n dataSource->getBounds(bounds);\n m_gridAxes->SetGridBounds(bounds);\n}\nvoid ModuleOutline::initializeGridAxes(DataSource* data,\n vtkSMViewProxy* vtkView)\n{\n\n updateGridAxesBounds(data);\n m_gridAxes->SetVisibility(0);\n m_gridAxes->SetGenerateGrid(false);\n\n \/\/ Work around a bug in vtkGridAxes3DActor. GetProperty() returns the\n \/\/ vtkProperty associated with a single face, so to get a property associated\n \/\/ with all the faces, we need to create a new one and set it.\n vtkNew<vtkProperty> prop;\n prop->DeepCopy(m_gridAxes->GetProperty());\n this->m_gridAxes->SetProperty(prop.Get());\n\n \/\/ Set the titles\n updateGridAxesUnit(data);\n\n m_view = vtkPVRenderView::SafeDownCast(vtkView->GetClientSideView());\n m_view->GetRenderer()->AddActor(m_gridAxes.Get());\n\n connect(data, &DataSource::dataPropertiesChanged, this, [this]() {\n auto dataSource = qobject_cast<DataSource*>(sender());\n this->updateGridAxesBounds(dataSource);\n this->updateGridAxesUnit(dataSource);\n dataSource->producer()->MarkModified(nullptr);\n dataSource->producer()->UpdatePipeline();\n emit this->renderNeeded();\n\n });\n}\n\nvoid ModuleOutline::updateGridAxesColor(double* color)\n{\n for (int i = 0; i < 6; i++) {\n vtkNew<vtkTextProperty> prop;\n prop->SetColor(color);\n m_gridAxes->SetTitleTextProperty(i, prop.Get());\n m_gridAxes->SetLabelTextProperty(i, prop.Get());\n }\n m_gridAxes->GetProperty()->SetDiffuseColor(color);\n vtkSMPropertyHelper(this->OutlineRepresentation, \"DiffuseColor\")\n .Set(color, 3);\n this->OutlineRepresentation->UpdateVTKObjects();\n}\n\nvoid ModuleOutline::updateGridAxesUnit(DataSource* dataSource)\n{\n QString xTitle = QString(\"X (%1)\").arg(dataSource->getUnits(0));\n QString yTitle = QString(\"Y (%1)\").arg(dataSource->getUnits(1));\n QString zTitle = QString(\"Z (%1)\").arg(dataSource->getUnits(2));\n m_gridAxes->SetXTitle(xTitle.toUtf8().data());\n m_gridAxes->SetYTitle(yTitle.toUtf8().data());\n m_gridAxes->SetZTitle(zTitle.toUtf8().data());\n}\n\n} \/\/ end of namespace tomviz\n<commit_msg>Enable front face culling<commit_after>\/******************************************************************************\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\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#include \"ModuleOutline.h\"\n\n#include \"DataSource.h\"\n#include \"Utilities.h\"\n#include \"pqProxiesWidget.h\"\n#include \"vtkNew.h\"\n#include \"vtkSMParaViewPipelineControllerWithRendering.h\"\n#include \"vtkSMProperty.h\"\n#include \"vtkSMPropertyHelper.h\"\n#include \"vtkSMSessionProxyManager.h\"\n#include \"vtkSMSourceProxy.h\"\n#include \"vtkSMViewProxy.h\"\n#include \"vtkSmartPointer.h\"\n#include <pqColorChooserButton.h>\n#include <vtkGridAxes3DActor.h>\n#include <vtkPVRenderView.h>\n#include <vtkProperty.h>\n#include <vtkRenderer.h>\n#include <vtkTextProperty.h>\n\n#include <QCheckBox>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QVBoxLayout>\n\nnamespace tomviz {\n\nusing pugi::xml_attribute;\nusing pugi::xml_node;\n\nModuleOutline::ModuleOutline(QObject* parentObject) : Superclass(parentObject)\n{\n}\n\nModuleOutline::~ModuleOutline()\n{\n this->finalize();\n}\n\nQIcon ModuleOutline::icon() const\n{\n return QIcon(\":\/icons\/pqProbeLocation.png\");\n}\n\nbool ModuleOutline::initialize(DataSource* data, vtkSMViewProxy* vtkView)\n{\n if (!this->Superclass::initialize(data, vtkView)) {\n return false;\n }\n\n vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n\n vtkSMSessionProxyManager* pxm = data->producer()->GetSessionProxyManager();\n\n \/\/ Create the outline filter.\n vtkSmartPointer<vtkSMProxy> proxy;\n proxy.TakeReference(pxm->NewProxy(\"filters\", \"OutlineFilter\"));\n\n this->OutlineFilter = vtkSMSourceProxy::SafeDownCast(proxy);\n Q_ASSERT(this->OutlineFilter);\n controller->PreInitializeProxy(this->OutlineFilter);\n vtkSMPropertyHelper(this->OutlineFilter, \"Input\").Set(data->producer());\n controller->PostInitializeProxy(this->OutlineFilter);\n controller->RegisterPipelineProxy(this->OutlineFilter);\n\n \/\/ Create the representation for it.\n this->OutlineRepresentation =\n controller->Show(this->OutlineFilter, 0, vtkView);\n vtkSMPropertyHelper(this->OutlineRepresentation, \"Position\")\n .Set(data->displayPosition(), 3);\n Q_ASSERT(this->OutlineRepresentation);\n \/\/ vtkSMPropertyHelper(this->OutlineRepresentation,\n \/\/ \"Representation\").Set(\"Outline\");\n this->OutlineRepresentation->UpdateVTKObjects();\n\n \/\/ Give the proxy a friendly name for the GUI\/Python world.\n if (auto p = convert<pqProxy*>(proxy)) {\n p->rename(label());\n }\n\n \/\/ Init the grid axes\n initializeGridAxes(data, vtkView);\n updateGridAxesColor(offWhite);\n\n return true;\n}\n\nbool ModuleOutline::finalize()\n{\n vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n controller->UnRegisterProxy(this->OutlineRepresentation);\n controller->UnRegisterProxy(this->OutlineFilter);\n\n if (m_view) {\n m_view->GetRenderer()->RemoveActor(m_gridAxes.Get());\n }\n\n this->OutlineFilter = nullptr;\n this->OutlineRepresentation = nullptr;\n return true;\n}\n\nbool ModuleOutline::serialize(pugi::xml_node& ns) const\n{\n xml_node rootNode = ns.append_child(\"properties\");\n\n xml_node visibilityNode = rootNode.append_child(\"visibility\");\n visibilityNode.append_attribute(\"enabled\") = visibility();\n\n xml_node gridAxesNode = rootNode.append_child(\"grid_axes\");\n gridAxesNode.append_attribute(\"enabled\") = m_gridAxes->GetVisibility() > 0;\n gridAxesNode.append_attribute(\"grid\") = m_gridAxes->GetGenerateGrid();\n\n xml_node color = gridAxesNode.append_child(\"color\");\n double rgb[3];\n m_gridAxes->GetProperty()->GetDiffuseColor(rgb);\n color.append_attribute(\"r\") = rgb[0];\n color.append_attribute(\"g\") = rgb[1];\n color.append_attribute(\"b\") = rgb[2];\n\n return true;\n}\n\nbool ModuleOutline::deserialize(const pugi::xml_node& ns)\n{\n xml_node rootNode = ns.child(\"properties\");\n if (!rootNode) {\n return false;\n }\n\n xml_node node = rootNode.child(\"visibility\");\n if (node) {\n xml_attribute att = node.attribute(\"enabled\");\n if (att) {\n setVisibility(att.as_bool());\n }\n }\n\n node = rootNode.child(\"grid_axes\");\n if (node) {\n xml_attribute att = node.attribute(\"enabled\");\n if (att) {\n m_gridAxes->SetVisibility(att.as_bool() ? 1 : 0);\n }\n att = node.attribute(\"grid\");\n if (att) {\n m_gridAxes->SetGenerateGrid(att.as_bool());\n }\n xml_node color = node.child(\"color\");\n if (color) {\n double rgb[3];\n att = color.attribute(\"r\");\n if (att) {\n rgb[0] = att.as_double();\n }\n att = color.attribute(\"g\");\n if (att) {\n rgb[1] = att.as_double();\n }\n att = color.attribute(\"b\");\n if (att) {\n rgb[2] = att.as_double();\n }\n updateGridAxesColor(rgb);\n }\n }\n\n return Module::deserialize(ns);\n}\n\nbool ModuleOutline::setVisibility(bool val)\n{\n Q_ASSERT(this->OutlineRepresentation);\n vtkSMPropertyHelper(this->OutlineRepresentation, \"Visibility\")\n .Set(val ? 1 : 0);\n this->OutlineRepresentation->UpdateVTKObjects();\n m_gridAxes->SetVisibility(val ? 1 : 0);\n return true;\n}\n\nbool ModuleOutline::visibility() const\n{\n if (this->OutlineRepresentation) {\n return vtkSMPropertyHelper(this->OutlineRepresentation, \"Visibility\")\n .GetAsInt() != 0;\n } else {\n return false;\n }\n}\n\nvoid ModuleOutline::addToPanel(QWidget* panel)\n{\n Q_ASSERT(panel && this->OutlineRepresentation);\n\n if (panel->layout()) {\n delete panel->layout();\n }\n\n QHBoxLayout* layout = new QHBoxLayout;\n QLabel* label = new QLabel(\"Color\");\n layout->addWidget(label);\n layout->addStretch();\n pqColorChooserButton* colorSelector = new pqColorChooserButton(panel);\n colorSelector->setShowAlphaChannel(false);\n layout->addWidget(colorSelector);\n\n \/\/ Show Grid?\n QHBoxLayout* showGridLayout = new QHBoxLayout;\n QCheckBox* showGrid = new QCheckBox(QString(\"Show Grid\"));\n showGrid->setChecked(m_gridAxes->GetGenerateGrid());\n\n connect(showGrid, &QCheckBox::stateChanged, this, [this](int state) {\n this->m_gridAxes->SetGenerateGrid(state == Qt::Checked);\n emit this->renderNeeded();\n });\n\n showGridLayout->addWidget(showGrid);\n\n \/\/ Show Axes?\n QHBoxLayout* showAxesLayout = new QHBoxLayout;\n QCheckBox* showAxes = new QCheckBox(QString(\"Show Axes\"));\n showAxes->setChecked(m_gridAxes->GetVisibility());\n \/\/ Disable \"Show Grid\" if axes not enabled\n if (!showAxes->isChecked()) {\n showGrid->setEnabled(false);\n }\n connect(showAxes, &QCheckBox::stateChanged, this,\n [this, showGrid](int state) {\n this->m_gridAxes->SetVisibility(state == Qt::Checked);\n \/\/ Uncheck \"Show Grid\" and disable it\n if (state == Qt::Unchecked) {\n showGrid->setChecked(false);\n showGrid->setEnabled(false);\n } else {\n showGrid->setEnabled(true);\n }\n\n emit this->renderNeeded();\n });\n showAxesLayout->addWidget(showAxes);\n\n QVBoxLayout* panelLayout = new QVBoxLayout;\n panelLayout->addItem(layout);\n panelLayout->addItem(showAxesLayout);\n panelLayout->addItem(showGridLayout);\n panelLayout->addStretch();\n panel->setLayout(panelLayout);\n\n m_links.addPropertyLink(\n colorSelector, \"chosenColorRgbF\", SIGNAL(chosenColorChanged(const QColor&)),\n this->OutlineRepresentation,\n this->OutlineRepresentation->GetProperty(\"DiffuseColor\"));\n\n this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged,\n [this](const QColor& color) {\n double rgb[3];\n rgb[0] = color.redF();\n rgb[1] = color.greenF();\n rgb[2] = color.blueF();\n updateGridAxesColor(rgb);\n\n });\n this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, this,\n &ModuleOutline::dataUpdated);\n}\n\nvoid ModuleOutline::dataUpdated()\n{\n m_links.accept();\n emit this->renderNeeded();\n}\n\nvoid ModuleOutline::dataSourceMoved(double newX, double newY, double newZ)\n{\n double pos[3] = { newX, newY, newZ };\n vtkSMPropertyHelper(this->OutlineRepresentation, \"Position\").Set(pos, 3);\n this->OutlineRepresentation->UpdateVTKObjects();\n this->m_gridAxes->SetPosition(newX, newY, newZ);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleOutline::isProxyPartOfModule(vtkSMProxy* proxy)\n{\n return (proxy == this->OutlineFilter.Get()) ||\n (proxy == this->OutlineRepresentation.Get());\n}\n\nstd::string ModuleOutline::getStringForProxy(vtkSMProxy* proxy)\n{\n if (proxy == this->OutlineFilter.Get()) {\n return \"Outline\";\n } else if (proxy == this->OutlineRepresentation.Get()) {\n return \"Representation\";\n } else {\n qWarning(\"Unknown proxy passed to module outline in save animation\");\n return \"\";\n }\n}\n\nvtkSMProxy* ModuleOutline::getProxyForString(const std::string& str)\n{\n if (str == \"Outline\") {\n return this->OutlineFilter.Get();\n } else if (str == \"Representation\") {\n return this->OutlineRepresentation.Get();\n } else {\n return nullptr;\n }\n}\n\nvoid ModuleOutline::updateGridAxesBounds(DataSource* dataSource)\n{\n Q_ASSERT(dataSource);\n double bounds[6];\n dataSource->getBounds(bounds);\n m_gridAxes->SetGridBounds(bounds);\n}\nvoid ModuleOutline::initializeGridAxes(DataSource* data,\n vtkSMViewProxy* vtkView)\n{\n\n updateGridAxesBounds(data);\n m_gridAxes->SetVisibility(0);\n m_gridAxes->SetGenerateGrid(false);\n\n \/\/ Work around a bug in vtkGridAxes3DActor. GetProperty() returns the\n \/\/ vtkProperty associated with a single face, so to get a property associated\n \/\/ with all the faces, we need to create a new one and set it.\n vtkNew<vtkProperty> prop;\n prop->DeepCopy(m_gridAxes->GetProperty());\n this->m_gridAxes->SetProperty(prop.Get());\n\n \/\/ Enable front face culling\n prop->SetFrontfaceCulling(1);\n\n \/\/ Set the titles\n updateGridAxesUnit(data);\n\n m_view = vtkPVRenderView::SafeDownCast(vtkView->GetClientSideView());\n m_view->GetRenderer()->AddActor(m_gridAxes.Get());\n\n connect(data, &DataSource::dataPropertiesChanged, this, [this]() {\n auto dataSource = qobject_cast<DataSource*>(sender());\n this->updateGridAxesBounds(dataSource);\n this->updateGridAxesUnit(dataSource);\n dataSource->producer()->MarkModified(nullptr);\n dataSource->producer()->UpdatePipeline();\n emit this->renderNeeded();\n\n });\n}\n\nvoid ModuleOutline::updateGridAxesColor(double* color)\n{\n for (int i = 0; i < 6; i++) {\n vtkNew<vtkTextProperty> prop;\n prop->SetColor(color);\n m_gridAxes->SetTitleTextProperty(i, prop.Get());\n m_gridAxes->SetLabelTextProperty(i, prop.Get());\n }\n m_gridAxes->GetProperty()->SetDiffuseColor(color);\n vtkSMPropertyHelper(this->OutlineRepresentation, \"DiffuseColor\")\n .Set(color, 3);\n this->OutlineRepresentation->UpdateVTKObjects();\n}\n\nvoid ModuleOutline::updateGridAxesUnit(DataSource* dataSource)\n{\n QString xTitle = QString(\"X (%1)\").arg(dataSource->getUnits(0));\n QString yTitle = QString(\"Y (%1)\").arg(dataSource->getUnits(1));\n QString zTitle = QString(\"Z (%1)\").arg(dataSource->getUnits(2));\n m_gridAxes->SetXTitle(xTitle.toUtf8().data());\n m_gridAxes->SetYTitle(yTitle.toUtf8().data());\n m_gridAxes->SetZTitle(zTitle.toUtf8().data());\n}\n\n} \/\/ end of namespace tomviz\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2014 Marcus Soll\n All rights reserved.\n\n You may use this file under the terms of BSD license as follows:\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Jolla Ltd nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY 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\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cornercore.h\"\n#include \"assemblyaihelper.h\"\n\nusing AssemblyAI::opponent;\n\nCornerCore::CornerCore()\n{\n}\n\nbool CornerCore::retirement(Gameboard board, int player)\n{\n \/\/ The core should retrire when neither the player nor the opponent can get a corner\n return !(board.play(0,0,opponent(player),true) || board.play(7,0,opponent(player),true) || board.play(0,7,opponent(player),true) || board.play(7,7,opponent(player),true))\n && !(board.play(0,0,player,true) || board.play(7,0,player,true) || board.play(0,7,player,true) || board.play(7,7,player,true));\n}\n\nbool CornerCore::mistrust(float const* const* const vote, Gameboard board, int player)\n{\n \/\/ Mistrust if you can get a corner but the proposal doesn't consider it\n\n if(!(vote[0][0] <= 0) && board.play(0,0,player,true))\n {\n return true;\n }\n else if(!(vote[0][7] <= 0) && board.play(0,7,player,true))\n {\n return true;\n }\n else if(!(vote[7][0] <= 0) && board.play(7,0,player,true))\n {\n return true;\n }\n else if(!(vote[7][7] <= 0) && board.play(7,7,player,true))\n {\n return true;\n }\n\n \/\/ Mistrust if a play is proposed where the opponent could get a corner\n for(int x = 0; x < 8; ++x)\n {\n for(int y = 0; y < 8; ++y)\n {\n if(vote[x][y] > 0 && !((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))\n {\n Gameboard testboard = board;\n testboard.play(x,y,player,false);\n if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))\n {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nvoid CornerCore::propose(float ** const vote, Gameboard board, int player)\n{\n \/\/ Try to get corners\n if(board.play(0,0,player,true))\n {\n vote[0][0] = 1;\n }\n if(board.play(0,7,player,true))\n {\n vote[0][7] = 1;\n }\n if(board.play(7,0,player,true))\n {\n vote[7][0] = 1;\n }\n if(board.play(7,7,player,true))\n {\n vote[7][7] = 1;\n }\n\n \/\/ Propose plays where the opponent can't get a corner\n for(int x = 0; x < 8; ++x)\n {\n for(int y = 0; y < 8; ++y)\n {\n if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))\n {\n Gameboard testboard = board;\n testboard.play(x,y,opponent(player),false);\n if(!(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true)))\n {\n vote[x][y] = 0.1;\n }\n }\n }\n }\n AssemblyAI::ensureOnePossibleMove(vote,board,player);\n}\n\nvoid CornerCore::correct(float ** const vote, Gameboard board, int player)\n{\n \/\/ Give Corners a high priority\n vote[0][0] *= Core::_factorLarge;\n vote[0][7] *= Core::_factorLarge;\n vote[7][0] *= Core::_factorLarge;\n vote[7][7] *= Core::_factorLarge;\n\n \/\/ Give plays where an opponent can get a corner a low priority\n for(int x = 0; x < 8; ++x)\n {\n for(int y = 0; y < 8; ++y)\n {\n if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))\n {\n Gameboard testboard = board;\n testboard.play(x,y,opponent(player),false);\n if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))\n {\n vote[x][y] \/= Core::_factorLarge;\n }\n }\n }\n }\n}\n\nQString CornerCore::name() const\n{\n return \"Corner Core\";\n}\n<commit_msg>Hopefully fixed \"Corner Core\"<commit_after>\/*\n Copyright (C) 2014 Marcus Soll\n All rights reserved.\n\n You may use this file under the terms of BSD license as follows:\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Jolla Ltd nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY 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\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cornercore.h\"\n#include \"assemblyaihelper.h\"\n\nusing AssemblyAI::opponent;\n\nCornerCore::CornerCore()\n{\n}\n\nbool CornerCore::retirement(Gameboard board, int player)\n{\n \/\/ Do not retrire if you can get a corner\n\n if(board.play(0,0,player,true))\n {\n return false;\n }\n else if(board.play(0,7,player,true))\n {\n return false;\n }\n else if(board.play(7,0,player,true))\n {\n return false;\n }\n else if(board.play(7,7,player,true))\n {\n return false;\n }\n\n\n \/\/ Do not retrire if there is a play where the opponent could get a corner\n for(int x = 0; x < 8; ++x)\n {\n for(int y = 0; y < 8; ++y)\n {\n if(!((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))\n {\n Gameboard testboard = board;\n testboard.play(x,y,player,false);\n if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))\n {\n return false;\n }\n }\n }\n }\n \/\/ Else retrire\n return true;\n}\n\nbool CornerCore::mistrust(float const* const* const vote, Gameboard board, int player)\n{\n \/\/ Mistrust if you can get a corner but the proposal doesn't consider it\n\n if(!(vote[0][0] <= 0) && board.play(0,0,player,true))\n {\n return true;\n }\n else if(!(vote[0][7] <= 0) && board.play(0,7,player,true))\n {\n return true;\n }\n else if(!(vote[7][0] <= 0) && board.play(7,0,player,true))\n {\n return true;\n }\n else if(!(vote[7][7] <= 0) && board.play(7,7,player,true))\n {\n return true;\n }\n\n \/\/ Mistrust if a play is proposed where the opponent could get a corner\n for(int x = 0; x < 8; ++x)\n {\n for(int y = 0; y < 8; ++y)\n {\n if(vote[x][y] > 0 && !((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))\n {\n Gameboard testboard = board;\n testboard.play(x,y,player,false);\n if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))\n {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nvoid CornerCore::propose(float ** const vote, Gameboard board, int player)\n{\n \/\/ Try to get corners\n if(board.play(0,0,player,true))\n {\n vote[0][0] = 1;\n }\n if(board.play(0,7,player,true))\n {\n vote[0][7] = 1;\n }\n if(board.play(7,0,player,true))\n {\n vote[7][0] = 1;\n }\n if(board.play(7,7,player,true))\n {\n vote[7][7] = 1;\n }\n\n \/\/ Propose plays where the opponent can't get a corner\n for(int x = 0; x < 8; ++x)\n {\n for(int y = 0; y < 8; ++y)\n {\n if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))\n {\n Gameboard testboard = board;\n testboard.play(x,y,opponent(player),false);\n if(!(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true)))\n {\n vote[x][y] = 0.1;\n }\n }\n }\n }\n AssemblyAI::ensureOnePossibleMove(vote,board,player);\n}\n\nvoid CornerCore::correct(float ** const vote, Gameboard board, int player)\n{\n \/\/ Give Corners a high priority\n vote[0][0] *= Core::_factorLarge;\n vote[0][7] *= Core::_factorLarge;\n vote[7][0] *= Core::_factorLarge;\n vote[7][7] *= Core::_factorLarge;\n\n \/\/ Give plays where an opponent can get a corner a low priority\n for(int x = 0; x < 8; ++x)\n {\n for(int y = 0; y < 8; ++y)\n {\n if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))\n {\n Gameboard testboard = board;\n testboard.play(x,y,opponent(player),false);\n if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))\n {\n vote[x][y] \/= Core::_factorLarge;\n }\n }\n }\n }\n}\n\nQString CornerCore::name() const\n{\n return \"Corner Core\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- Error.cpp - system_error extensions for obj2yaml ---------*- C++ -*-===\/\/\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#include \"Error.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n\nusing namespace llvm;\n\nnamespace {\nclass _obj2yaml_error_category : public std::error_category {\npublic:\n const char *name() const LLVM_NOEXCEPT override;\n std::string message(int ev) const override;\n};\n} \/\/ namespace\n\nconst char *_obj2yaml_error_category::name() const { return \"obj2yaml\"; }\n\nstd::string _obj2yaml_error_category::message(int ev) const {\n switch (static_cast<obj2yaml_error>(ev)) {\n case obj2yaml_error::success:\n return \"Success\";\n case obj2yaml_error::file_not_found:\n return \"No such file.\";\n case obj2yaml_error::unrecognized_file_format:\n return \"Unrecognized file type.\";\n case obj2yaml_error::unsupported_obj_file_format:\n return \"Unsupported object file format.\";\n }\n llvm_unreachable(\"An enumerator of obj2yaml_error does not have a message \"\n \"defined.\");\n}\n\nnamespace llvm {\n const std::error_category &obj2yaml_category() {\n static _obj2yaml_error_category o;\n return o;\n}\n} \/\/ namespace llvm\n<commit_msg>Added missing LLVM_NOEXCEPT to the definition of _obj2yaml_error_category::name<commit_after>\/\/===- Error.cpp - system_error extensions for obj2yaml ---------*- C++ -*-===\/\/\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#include \"Error.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n\nusing namespace llvm;\n\nnamespace {\nclass _obj2yaml_error_category : public std::error_category {\npublic:\n const char *name() const LLVM_NOEXCEPT override;\n std::string message(int ev) const override;\n};\n} \/\/ namespace\n\nconst char *_obj2yaml_error_category::name() const LLVM_NOEXCEPT {\n return \"obj2yaml\";\n}\n\nstd::string _obj2yaml_error_category::message(int ev) const {\n switch (static_cast<obj2yaml_error>(ev)) {\n case obj2yaml_error::success:\n return \"Success\";\n case obj2yaml_error::file_not_found:\n return \"No such file.\";\n case obj2yaml_error::unrecognized_file_format:\n return \"Unrecognized file type.\";\n case obj2yaml_error::unsupported_obj_file_format:\n return \"Unsupported object file format.\";\n }\n llvm_unreachable(\"An enumerator of obj2yaml_error does not have a message \"\n \"defined.\");\n}\n\nnamespace llvm {\n const std::error_category &obj2yaml_category() {\n static _obj2yaml_error_category o;\n return o;\n}\n} \/\/ namespace llvm\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright (c) 2015 LinBox\n * This file is part of the library LinBox. See COPYING for license info.\n * Written by bds.\n *\/\n\/** @file tests\/checker.C\n@brief script to run LinBox tests\n\nChecker is compiled and run by the check macro invoked by \"make fullcheck\" in the top source dir or in tests\/.\n\nRun without args, \neach test is build and run, with a one line report of success or failure.\nA summary at the end reports number of test failing to compile, failing at runtime, and skipped.\nThere should be a 1-1 correspondence between files tests\/test-*.C and report lines\n\nA LinBox unit\/regresssion test has a default behaviour -- when there are no command line file names -- in which nothing is written to any output stream and the return value is 0 for a passing test, nonzero for any failure.\n\nThe current convention is that (1) linbox' checker.C, runs the tests with no command line parameters at all, and (2) if there is a command line file name, verbose diagnostic output is written to that file and more terse output may be written to standard output streams. The second feature is intended to assist debugging with individual tests.\n\n*\/\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <map>\n#include <set>\n#include <vector>\n\/\/#include <iomanip>\nusing namespace std;\n#include \"linbox-config.h\"\n\/\/#include \"linbox\/linbox-config.h\"\n\/\/#include \"fflas-ffpack\/fflas-ffpack.h\"\n\n\/\/ globals\n\/\/map< string, string> skip_note;\nmap< string, string> warn_note;\nset< string> skips;\nset< string> hides;\nvoid warn(const string& t, const string& w) { warn_note[t] = w; }\nvoid skip(const string& t, const string& w) { warn_note[t] = w; skips.insert(t); }\nvoid hide(const string& t, const string& w) { warn_note[t] = w; hides.insert(t); }\n\nint main(int argc, char* argv[]) {\n\tint arg;\n\tbool force_build = false, reporting = true, honor_skips = true;\n\tfor (arg = 1; arg < argc; ++arg)\n\t\tfor (char * i = argv[arg]; *i != 0; ++i){\n\t\t\tif (*i == 'r') force_build = true;\n\t\t\tif (*i == 's') reporting = false;\n\t\t\tif (*i == 'a') honor_skips = false;\n\t\t}\n if (argc > 1 and not force_build and reporting and honor_skips){ \/\/ bogus arg\n\t\tcout << \"usage: \" << argv[0] << \" [-][r][s][a]\" << endl;\n\t\tcout << \" -r Force recompilation of each test.\"<< endl;\n\t\tcout << \" -s Summary only: 3 lines printed. (Default is one line per test.)\" << endl;\n\t\tcout << \" -a Build and run all. (Ignore skip and hide commands.)\" << endl;\n\t\treturn 0;\n\t}\n\n\/\/ fullcheck customization: warnings, skips, hides, optional package dependencies\n\n\/\/\/\/ notes section (customize fullcheck here) \/\/\/\/\n\nif (honor_skips) {\nhide(\"test-block-ring\", \"non commutative rings not supported\");\n\/\/hide(\"test-ffpack\", \"testTURBO fails, move to ffpack tests?\");\nhide(\"test-ftrmm\", \"should move to attic\");\nskip(\"test-givaro-fields\", \"may fail on small fields because of supposed non-randomness or failure to find a non trivial element\");\nhide(\"test-image-field\", \"deprecated\");\n\/\/skip(\"test-isposdef\", \"intermittent inf loop\");\n\/\/skip(\"test-ispossemidef\", \"intermittent inf loop\");\nhide(\"test-la-block-lanczos\", \"not maintained. operator >> missing\");\nhide(\"test-mg-block-lanczos\", \"not maintained\");\nhide(\"test-modular\", \"deprecated\");\nhide(\"test-modular-byte\", \"deprecated\");\nhide(\"test-modular-short\", \"deprecated\");\n\/\/skip(\"test-modular-balanced-int\", \"test and modular-balanced disagree on init\/convert\");\n\/\/skip(\"test-modular-balanced-double\", \"test and modular-balanced disagree on init\/convert\");\n\/\/skip(\"test-moore-penrose\", \"inf loop\");\nskip(\"test-optimization\", \"not in test form\");\nskip(\"test-quad-matrix\", \"depends on out-of-date blackbox\/zo.h\");\n\/\/skip(\"test-rational-reconstruction-base\", \"inf loop\");\nskip(\"test-rat-charpoly\", \"inf loop\");\nskip(\"test-rat-minpoly\", \"stale test. solns over QQ need fresh tests\"); \/\/ \"intermittent failures\")\nskip(\"test-rat-solve\", \"stale test. solns over QQ need fresh tests\"); \/\/ \"infinite loop\")\nskip(\"test-poly-det\", \"incomplete test (if still relevant)\");\nskip(\"test-sparse-map-map\", \"const issue in givranditer, curious use of nonexistant next() in Extension\");\n\/\/Tests requiring further development\nskip(\"test-tutorial\", \"incomplete test\");\nskip(\"test-dense-zero-one\", \"half baked, bds responsible\");\n}\n\n\/\/warn(\"test-echelon-form\", \"new\");\nwarn(\"test-fibb\", \"incomplete\");\n\/\/warn(\"test-matrix-domain\", \"intermittent row permutation failure\");\nwarn(\"test-param-fuzzy\", \"Noncompliant field\");\n\/\/\t\ttemplate <class F2Field> BitVector (const F2Field&) {}\n\/\/warn(\"test-qlup\", \"GF2 fails to compile\");\n\/\/warn(\"test-rank-u32\", \"intermittent failure\"\/*, \"vector (bb) responsible\"*\/);\nwarn(\"test-rat-charpoly\", \"stale test. solns over QQ need fresh tests\");\/\/, \"infinite loop, cp responsible?\")\nwarn(\"test-rat-solve\", \"infinite loop\");\n\/\/warn(\"test-smith-form-local\", \"bds, intermittent failures\");\nwarn(\"test-solve\", \"most of the tests are commented out\");\nwarn(\"test-toom-cook\", \"one method does not work\");\n\/\/warn(\"test-transpose\", \"sometimes fails on Sparsematrix\/getEntry\");\nwarn(\"test-quad-matrix\", \"half baked, bds responsible\");\n\n\n\/\/\/\/ optional package dependency section \/\/\/\/\n\tset< string> ntl_tests;\n\tntl_tests.insert(\"test-ntl-hankel\");\n\tntl_tests.insert(\"test-ntl-lzz_p\");\n\tntl_tests.insert(\"test-ntl-lzz_pe\");\n\tntl_tests.insert(\"test-ntl-lzz_px\");\n\tntl_tests.insert(\"test-ntl-lzz_pex\");\n\twarn(\"test-toeplitz-det\", \"we should have a non NTL version.\");\n\tntl_tests.insert(\"test-toeplitz-det\");\n\twarn(\"test-ntl-rr\", \"floating point equality\");\n\tntl_tests.insert(\"test-ntl-rr\");\n\tntl_tests.insert(\"test-ntl-sylvester\");\n\tntl_tests.insert(\"test-ntl-toeplitz\");\n\tntl_tests.insert(\"test-ntl-zz_p\");\n\n\t\/\/ are these really ntl dependent?\n\tntl_tests.insert(\"test-smith-form\");\n\tntl_tests.insert(\"test-smith-form-adaptive\");\n\tntl_tests.insert(\"test-smith-form-iliopoulos\");\n\tset< string> ocl_tests;\n\tocl_tests.insert(\"test-opencl-domain\");\n\n\/\/\/\/ Things are automatic from here onward. \/\/\/\/\n\n\t\/\/ process optional dependencies \n\t#ifndef LINBOX_HAVE_OCL\n for (set< string>::iterator i = ocl_tests.begin(); i != ocl_tests.end(); ++i) \n\t\tskip(*i, \"OpenCL not present\");\n\t#endif\n\t#ifndef __LINBOX_HAVE_NTL\n for (set< string>::iterator i = ntl_tests.begin(); i != ntl_tests.end(); ++i) \n\t\tskip(*i, \"NTL not present\");\n\t#endif\n\/\/ build and run the tests section\n\tstring t, cmd;\n\tsystem(\"ls test-*C >.tmp-tests\");\n\tifstream tests(\".tmp-tests\");\n\tint buildfail = 0, runfail = 0, skipped = 0, pass = 0; \/\/ counts\n\tvector<string> all_tests;\n\twhile (tests >> t) {t.resize(t.size()-2); all_tests.push_back(t);}\n\/\/#ifdef LINBOX_HAVE_OPENMP\n\/\/#pragma omp parallel for \n\/\/PARFOR1D(i, 0, all_tests.size(), SPLITTER(),\n\/\/#endif\n\tfor (size_t i = 0; i < all_tests.size(); ++i) \n\t{\n\t\tt = all_tests[i];\n\t\tif (hides.count(t) > 0) continue; \/\/ ignore entirely\n\t\tstringstream report;\n\t\treport.width(35);\n\t\treport << left << t;\n\t\tif (skips.count(t) > 0) { \/\/ print skip message\n\t\t\treport << \"skipped, \" + warn_note[t];\n\t\t\tskipped++;\n\t\t} else { \/\/ do build\n\t\t\tif (force_build) {\n\t\t\t\tcmd = \"touch \" + t + \".C\";\n\t\t\t\tsystem(cmd.c_str());\n\t\t\t}\n\t\t\t\/\/ build\n\t\t\tcmd = \"make \" + t + \" 2> \/dev\/null > \/dev\/null\";\n\t\t\treport << \"build \";\n\t\t\tint status = system(cmd.c_str());\n\/\/\t\t\t#ifndef LINBOX_HAVE_OPENMP\n\/\/\t\t\tif (status == 2) break; \n\/\/\t\t\t#endif\n\t\t\tif (status != 0) { \/\/ build failure\n\t\t\t\tbuildfail++;\n\t\t\t\treport << \"FAIL \";\n\t\t\t} else {\/\/ do run\n\t\t\t\treport << \"OK, run \";\n\t\t\t\tstd::ostringstream prog ;\n\t\t\t\tprog << \".\/\" << t ;\n\t\t\t\tstatus = system(prog.str().c_str());\n\/\/\t\t\t\t#ifndef LINBOX_HAVE_OPENMP\n\/\/\t\t\t\tif (status == 2) break;\n\/\/\t\t\t\t#endif\n\t\t\t\tif (status == 0) {\n\t\t\t\t\treport << \"OK. \" + warn_note[t];\n\t\t\t\t\tpass++;\n\t\t\t\t} else {\n\t\t\t\t\trunfail++;\n\t\t\t\t\treport << \"FAIL\" + warn_note[t];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (reporting) cout << report.str() << endl;\n\t} \/\/ for i\n\t\/\/); \/\/ parfor\n\n\t\/\/\/\/ summary \/\/\/\/\n\tcout << \"--------------------------------------------------------------------\" << endl;\n\tint total = pass + buildfail + runfail + skipped;\n\tif (buildfail || runfail)\n\t\tcout << \"Of \" << total << \" tests, \"\n\t\t << pass << \" passed, \"\n\t\t\t<< buildfail << \" failed to compile, \"\n\t\t\t<< runfail << \" failed at runtime, \" \n\t\t\t<< \" and \" << skipped << \" were skipped.\" << endl;\n\telse\n\t\tcout << endl << \"All \" << total - skipped << \" tests pass.\"\n\t\t\t<< \" (There were \" << skipped << \" skipped tests.)\" << endl;\n\tcout << \"--------------------------------------------------------------------\" << endl;\n\n\treturn buildfail || runfail ? -1 : 0;\n} \/\/ main\n<commit_msg>linbox\/linbox-config.h<commit_after>\n\/*\n * Copyright (c) 2015 LinBox\n * This file is part of the library LinBox. See COPYING for license info.\n * Written by bds.\n *\/\n\/** @file tests\/checker.C\n@brief script to run LinBox tests\n\nChecker is compiled and run by the check macro invoked by \"make fullcheck\" in the top source dir or in tests\/.\n\nRun without args, \neach test is build and run, with a one line report of success or failure.\nA summary at the end reports number of test failing to compile, failing at runtime, and skipped.\nThere should be a 1-1 correspondence between files tests\/test-*.C and report lines\n\nA LinBox unit\/regresssion test has a default behaviour -- when there are no command line file names -- in which nothing is written to any output stream and the return value is 0 for a passing test, nonzero for any failure.\n\nThe current convention is that (1) linbox' checker.C, runs the tests with no command line parameters at all, and (2) if there is a command line file name, verbose diagnostic output is written to that file and more terse output may be written to standard output streams. The second feature is intended to assist debugging with individual tests.\n\n*\/\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <map>\n#include <set>\n#include <vector>\n\/\/#include <iomanip>\nusing namespace std;\n\/\/#include \"linbox-config.h\"\n#include \"linbox\/linbox-config.h\"\n\/\/#include \"fflas-ffpack\/fflas-ffpack.h\"\n\n\/\/ globals\n\/\/map< string, string> skip_note;\nmap< string, string> warn_note;\nset< string> skips;\nset< string> hides;\nvoid warn(const string& t, const string& w) { warn_note[t] = w; }\nvoid skip(const string& t, const string& w) { warn_note[t] = w; skips.insert(t); }\nvoid hide(const string& t, const string& w) { warn_note[t] = w; hides.insert(t); }\n\nint main(int argc, char* argv[]) {\n\tint arg;\n\tbool force_build = false, reporting = true, honor_skips = true;\n\tfor (arg = 1; arg < argc; ++arg)\n\t\tfor (char * i = argv[arg]; *i != 0; ++i){\n\t\t\tif (*i == 'r') force_build = true;\n\t\t\tif (*i == 's') reporting = false;\n\t\t\tif (*i == 'a') honor_skips = false;\n\t\t}\n if (argc > 1 and not force_build and reporting and honor_skips){ \/\/ bogus arg\n\t\tcout << \"usage: \" << argv[0] << \" [-][r][s][a]\" << endl;\n\t\tcout << \" -r Force recompilation of each test.\"<< endl;\n\t\tcout << \" -s Summary only: 3 lines printed. (Default is one line per test.)\" << endl;\n\t\tcout << \" -a Build and run all. (Ignore skip and hide commands.)\" << endl;\n\t\treturn 0;\n\t}\n\n\/\/ fullcheck customization: warnings, skips, hides, optional package dependencies\n\n\/\/\/\/ notes section (customize fullcheck here) \/\/\/\/\n\nif (honor_skips) {\nhide(\"test-block-ring\", \"non commutative rings not supported\");\n\/\/hide(\"test-ffpack\", \"testTURBO fails, move to ffpack tests?\");\nhide(\"test-ftrmm\", \"should move to attic\");\nskip(\"test-givaro-fields\", \"may fail on small fields because of supposed non-randomness or failure to find a non trivial element\");\nhide(\"test-image-field\", \"deprecated\");\n\/\/skip(\"test-isposdef\", \"intermittent inf loop\");\n\/\/skip(\"test-ispossemidef\", \"intermittent inf loop\");\nhide(\"test-la-block-lanczos\", \"not maintained. operator >> missing\");\nhide(\"test-mg-block-lanczos\", \"not maintained\");\nhide(\"test-modular\", \"deprecated\");\nhide(\"test-modular-byte\", \"deprecated\");\nhide(\"test-modular-short\", \"deprecated\");\n\/\/skip(\"test-modular-balanced-int\", \"test and modular-balanced disagree on init\/convert\");\n\/\/skip(\"test-modular-balanced-double\", \"test and modular-balanced disagree on init\/convert\");\n\/\/skip(\"test-moore-penrose\", \"inf loop\");\nskip(\"test-optimization\", \"not in test form\");\nskip(\"test-quad-matrix\", \"depends on out-of-date blackbox\/zo.h\");\n\/\/skip(\"test-rational-reconstruction-base\", \"inf loop\");\nskip(\"test-rat-charpoly\", \"inf loop\");\nskip(\"test-rat-minpoly\", \"stale test. solns over QQ need fresh tests\"); \/\/ \"intermittent failures\")\nskip(\"test-rat-solve\", \"stale test. solns over QQ need fresh tests\"); \/\/ \"infinite loop\")\nskip(\"test-poly-det\", \"incomplete test (if still relevant)\");\nskip(\"test-sparse-map-map\", \"const issue in givranditer, curious use of nonexistant next() in Extension\");\n\/\/Tests requiring further development\nskip(\"test-tutorial\", \"incomplete test\");\nskip(\"test-dense-zero-one\", \"half baked, bds responsible\");\n}\n\n\/\/warn(\"test-echelon-form\", \"new\");\nwarn(\"test-fibb\", \"incomplete\");\n\/\/warn(\"test-matrix-domain\", \"intermittent row permutation failure\");\nwarn(\"test-param-fuzzy\", \"Noncompliant field\");\n\/\/\t\ttemplate <class F2Field> BitVector (const F2Field&) {}\n\/\/warn(\"test-qlup\", \"GF2 fails to compile\");\n\/\/warn(\"test-rank-u32\", \"intermittent failure\"\/*, \"vector (bb) responsible\"*\/);\nwarn(\"test-rat-charpoly\", \"stale test. solns over QQ need fresh tests\");\/\/, \"infinite loop, cp responsible?\")\nwarn(\"test-rat-solve\", \"infinite loop\");\n\/\/warn(\"test-smith-form-local\", \"bds, intermittent failures\");\nwarn(\"test-solve\", \"most of the tests are commented out\");\nwarn(\"test-toom-cook\", \"one method does not work\");\n\/\/warn(\"test-transpose\", \"sometimes fails on Sparsematrix\/getEntry\");\nwarn(\"test-quad-matrix\", \"half baked, bds responsible\");\n\n\n\/\/\/\/ optional package dependency section \/\/\/\/\n\tset< string> ntl_tests;\n\tntl_tests.insert(\"test-ntl-hankel\");\n\tntl_tests.insert(\"test-ntl-lzz_p\");\n\tntl_tests.insert(\"test-ntl-lzz_pe\");\n\tntl_tests.insert(\"test-ntl-lzz_px\");\n\tntl_tests.insert(\"test-ntl-lzz_pex\");\n\twarn(\"test-toeplitz-det\", \"we should have a non NTL version.\");\n\tntl_tests.insert(\"test-toeplitz-det\");\n\twarn(\"test-ntl-rr\", \"floating point equality\");\n\tntl_tests.insert(\"test-ntl-rr\");\n\tntl_tests.insert(\"test-ntl-sylvester\");\n\tntl_tests.insert(\"test-ntl-toeplitz\");\n\tntl_tests.insert(\"test-ntl-zz_p\");\n\n\t\/\/ are these really ntl dependent?\n\tntl_tests.insert(\"test-smith-form\");\n\tntl_tests.insert(\"test-smith-form-adaptive\");\n\tntl_tests.insert(\"test-smith-form-iliopoulos\");\n\tset< string> ocl_tests;\n\tocl_tests.insert(\"test-opencl-domain\");\n\n\/\/\/\/ Things are automatic from here onward. \/\/\/\/\n\n\t\/\/ process optional dependencies \n\t#ifndef LINBOX_HAVE_OCL\n for (set< string>::iterator i = ocl_tests.begin(); i != ocl_tests.end(); ++i) \n\t\tskip(*i, \"OpenCL not present\");\n\t#endif\n\t#ifndef __LINBOX_HAVE_NTL\n for (set< string>::iterator i = ntl_tests.begin(); i != ntl_tests.end(); ++i) \n\t\tskip(*i, \"NTL not present\");\n\t#endif\n\/\/ build and run the tests section\n\tstring t, cmd;\n\tsystem(\"ls test-*C >.tmp-tests\");\n\tifstream tests(\".tmp-tests\");\n\tint buildfail = 0, runfail = 0, skipped = 0, pass = 0; \/\/ counts\n\tvector<string> all_tests;\n\twhile (tests >> t) {t.resize(t.size()-2); all_tests.push_back(t);}\n\/\/#ifdef LINBOX_HAVE_OPENMP\n\/\/#pragma omp parallel for \n\/\/PARFOR1D(i, 0, all_tests.size(), SPLITTER(),\n\/\/#endif\n\tfor (size_t i = 0; i < all_tests.size(); ++i) \n\t{\n\t\tt = all_tests[i];\n\t\tif (hides.count(t) > 0) continue; \/\/ ignore entirely\n\t\tstringstream report;\n\t\treport.width(35);\n\t\treport << left << t;\n\t\tif (skips.count(t) > 0) { \/\/ print skip message\n\t\t\treport << \"skipped, \" + warn_note[t];\n\t\t\tskipped++;\n\t\t} else { \/\/ do build\n\t\t\tif (force_build) {\n\t\t\t\tcmd = \"touch \" + t + \".C\";\n\t\t\t\tsystem(cmd.c_str());\n\t\t\t}\n\t\t\t\/\/ build\n\t\t\tcmd = \"make \" + t + \" 2> \/dev\/null > \/dev\/null\";\n\t\t\treport << \"build \";\n\t\t\tint status = system(cmd.c_str());\n\/\/\t\t\t#ifndef LINBOX_HAVE_OPENMP\n\/\/\t\t\tif (status == 2) break; \n\/\/\t\t\t#endif\n\t\t\tif (status != 0) { \/\/ build failure\n\t\t\t\tbuildfail++;\n\t\t\t\treport << \"FAIL \";\n\t\t\t} else {\/\/ do run\n\t\t\t\treport << \"OK, run \";\n\t\t\t\tstd::ostringstream prog ;\n\t\t\t\tprog << \".\/\" << t ;\n\t\t\t\tstatus = system(prog.str().c_str());\n\/\/\t\t\t\t#ifndef LINBOX_HAVE_OPENMP\n\/\/\t\t\t\tif (status == 2) break;\n\/\/\t\t\t\t#endif\n\t\t\t\tif (status == 0) {\n\t\t\t\t\treport << \"OK. \" + warn_note[t];\n\t\t\t\t\tpass++;\n\t\t\t\t} else {\n\t\t\t\t\trunfail++;\n\t\t\t\t\treport << \"FAIL\" + warn_note[t];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (reporting) cout << report.str() << endl;\n\t} \/\/ for i\n\t\/\/); \/\/ parfor\n\n\t\/\/\/\/ summary \/\/\/\/\n\tcout << \"--------------------------------------------------------------------\" << endl;\n\tint total = pass + buildfail + runfail + skipped;\n\tif (buildfail || runfail)\n\t\tcout << \"Of \" << total << \" tests, \"\n\t\t << pass << \" passed, \"\n\t\t\t<< buildfail << \" failed to compile, \"\n\t\t\t<< runfail << \" failed at runtime, \" \n\t\t\t<< \" and \" << skipped << \" were skipped.\" << endl;\n\telse\n\t\tcout << endl << \"All \" << total - skipped << \" tests pass.\"\n\t\t\t<< \" (There were \" << skipped << \" skipped tests.)\" << endl;\n\tcout << \"--------------------------------------------------------------------\" << endl;\n\n\treturn buildfail || runfail ? -1 : 0;\n} \/\/ main\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 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\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\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** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"makestep.h\"\n#include \"ui_makestep.h\"\n\n#include \"qt4project.h\"\n#include \"qt4target.h\"\n#include \"qt4buildconfiguration.h\"\n#include \"qt4projectmanagerconstants.h\"\n#include \"qtparser.h\"\n\n#include <projectexplorer\/toolchain.h>\n#include <projectexplorer\/buildsteplist.h>\n#include <projectexplorer\/projectexplorer.h>\n#include <projectexplorer\/projectexplorerconstants.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <utils\/qtcprocess.h>\n\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n\nusing ExtensionSystem::PluginManager;\nusing namespace Qt4ProjectManager;\nusing namespace Qt4ProjectManager::Internal;\n\nnamespace {\nconst char * const MAKESTEP_BS_ID(\"Qt4ProjectManager.MakeStep\");\n\nconst char * const MAKE_ARGUMENTS_KEY(\"Qt4ProjectManager.MakeStep.MakeArguments\");\nconst char * const MAKE_COMMAND_KEY(\"Qt4ProjectManager.MakeStep.MakeCommand\");\nconst char * const CLEAN_KEY(\"Qt4ProjectManager.MakeStep.Clean\");\n}\n\nMakeStep::MakeStep(ProjectExplorer::BuildStepList *bsl) :\n AbstractProcessStep(bsl, QLatin1String(MAKESTEP_BS_ID)),\n m_clean(false)\n{\n ctor();\n}\n\nMakeStep::MakeStep(ProjectExplorer::BuildStepList *bsl, MakeStep *bs) :\n AbstractProcessStep(bsl, bs),\n m_clean(bs->m_clean),\n m_userArgs(bs->m_userArgs),\n m_makeCmd(bs->m_makeCmd)\n{\n ctor();\n}\n\nMakeStep::MakeStep(ProjectExplorer::BuildStepList *bsl, const QString &id) :\n AbstractProcessStep(bsl, id),\n m_clean(false)\n{\n ctor();\n}\n\nvoid MakeStep::ctor()\n{\n setDefaultDisplayName(tr(\"Make\", \"Qt4 MakeStep display name.\"));\n}\n\nMakeStep::~MakeStep()\n{\n}\n\nQt4BuildConfiguration *MakeStep::qt4BuildConfiguration() const\n{\n return static_cast<Qt4BuildConfiguration *>(buildConfiguration());\n}\n\nvoid MakeStep::setClean(bool clean)\n{\n m_clean = clean;\n}\n\nbool MakeStep::isClean() const\n{\n return m_clean;\n}\n\nQVariantMap MakeStep::toMap() const\n{\n QVariantMap map(ProjectExplorer::AbstractProcessStep::toMap());\n map.insert(QLatin1String(MAKE_ARGUMENTS_KEY), m_userArgs);\n map.insert(QLatin1String(MAKE_COMMAND_KEY), m_makeCmd);\n map.insert(QLatin1String(CLEAN_KEY), m_clean);\n return map;\n}\n\nbool MakeStep::fromMap(const QVariantMap &map)\n{\n m_makeCmd = map.value(QLatin1String(MAKE_COMMAND_KEY)).toString();\n m_userArgs = map.value(QLatin1String(MAKE_ARGUMENTS_KEY)).toString();\n m_clean = map.value(QLatin1String(CLEAN_KEY)).toBool();\n\n return ProjectExplorer::AbstractProcessStep::fromMap(map);\n}\n\nbool MakeStep::init()\n{\n Qt4BuildConfiguration *bc = qt4BuildConfiguration();\n\n m_tasks.clear();\n if (!bc->toolChain()) {\n m_tasks.append(ProjectExplorer::Task(ProjectExplorer::Task::Error,\n tr(\"Qt Creator needs a tool chain set up to build. Please configure a tool chain in Project mode.\"),\n QString(), -1,\n QLatin1String(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));\n }\n\n ProjectExplorer::ProcessParameters *pp = processParameters();\n pp->setMacroExpander(bc->macroExpander());\n\n Utils::Environment environment = bc->environment();\n pp->setEnvironment(environment);\n\n QString workingDirectory;\n if (bc->subNodeBuild())\n workingDirectory = bc->subNodeBuild()->buildDir();\n else\n workingDirectory = bc->buildDirectory();\n pp->setWorkingDirectory(workingDirectory);\n\n QString makeCmd = bc->makeCommand();\n if (!m_makeCmd.isEmpty())\n makeCmd = m_makeCmd;\n pp->setCommand(makeCmd);\n\n \/\/ If we are cleaning, then make can fail with a error code, but that doesn't mean\n \/\/ we should stop the clean queue\n \/\/ That is mostly so that rebuild works on a already clean project\n setIgnoreReturnValue(m_clean);\n\n QString args;\n\n ProjectExplorer::ToolChain *toolchain = bc->toolChain();\n\n if (bc->subNodeBuild()) {\n QString makefile = bc->subNodeBuild()->makefile();\n if(!makefile.isEmpty()) {\n Utils::QtcProcess::addArg(&args, QLatin1String(\"-f\"));\n Utils::QtcProcess::addArg(&args, makefile);\n m_makeFileToCheck = QDir(workingDirectory).filePath(makefile);\n } else {\n m_makeFileToCheck = QDir(workingDirectory).filePath(\"Makefile\");\n }\n } else {\n if (!bc->makefile().isEmpty()) {\n Utils::QtcProcess::addArg(&args, QLatin1String(\"-f\"));\n Utils::QtcProcess::addArg(&args, bc->makefile());\n m_makeFileToCheck = QDir(workingDirectory).filePath(bc->makefile());\n } else {\n m_makeFileToCheck = QDir(workingDirectory).filePath(\"Makefile\");\n }\n }\n\n Utils::QtcProcess::addArgs(&args, m_userArgs);\n\n if (!isClean()) {\n if (!bc->defaultMakeTarget().isEmpty())\n Utils::QtcProcess::addArg(&args, bc->defaultMakeTarget());\n }\n \/\/ -w option enables \"Enter\"\/\"Leaving directory\" messages, which we need for detecting the\n \/\/ absolute file path\n \/\/ FIXME doing this without the user having a way to override this is rather bad\n \/\/ so we only do it for unix and if the user didn't override the make command\n \/\/ but for now this is the least invasive change\n if (toolchain\n && toolchain->targetAbi().binaryFormat() != ProjectExplorer::Abi::PEFormat\n && m_makeCmd.isEmpty())\n Utils::QtcProcess::addArg(&args, QLatin1String(\"-w\"));\n\n setEnabled(true);\n pp->setArguments(args);\n\n ProjectExplorer::IOutputParser *parser = bc->qtVersion()->createOutputParser();\n Q_ASSERT(parser);\n parser->appendOutputParser(new QtParser);\n if (toolchain)\n parser->appendOutputParser(toolchain->outputParser());\n\n parser->setWorkingDirectory(workingDirectory);\n\n setOutputParser(parser);\n\n return AbstractProcessStep::init();\n}\n\nvoid MakeStep::run(QFutureInterface<bool> & fi)\n{\n if (qt4BuildConfiguration()->qt4Target()->qt4Project()->rootProjectNode()->projectType() == ScriptTemplate) {\n fi.reportResult(true);\n return;\n }\n\n if (!QFileInfo(m_makeFileToCheck).exists()) {\n if (!m_clean)\n emit addOutput(tr(\"Makefile not found. Please check your build settings\"), BuildStep::MessageOutput);\n fi.reportResult(m_clean);\n return;\n }\n\n \/\/ Warn on common error conditions:\n bool canContinue = true;\n foreach (const ProjectExplorer::Task &t, m_tasks) {\n addTask(t);\n if (t.type == ProjectExplorer::Task::Error)\n canContinue = false;\n }\n if (!canContinue) {\n emit addOutput(tr(\"Configuration is faulty, please check the Build Issues view for details.\"), BuildStep::MessageOutput);\n fi.reportResult(false);\n return;\n }\n\n AbstractProcessStep::run(fi);\n}\n\nbool MakeStep::processSucceeded(int exitCode, QProcess::ExitStatus status)\n{\n \/\/ Symbian does retun 0, even on failed makes! So we check for fatal make errors here.\n if (outputParser() && outputParser()->hasFatalErrors())\n return false;\n\n return AbstractProcessStep::processSucceeded(exitCode, status);\n}\n\nbool MakeStep::immutable() const\n{\n return false;\n}\n\nProjectExplorer::BuildStepConfigWidget *MakeStep::createConfigWidget()\n{\n return new MakeStepConfigWidget(this);\n}\n\nQString MakeStep::userArguments()\n{\n return m_userArgs;\n}\n\nvoid MakeStep::setUserArguments(const QString &arguments)\n{\n m_userArgs = arguments;\n emit userArgumentsChanged();\n}\n\nMakeStepConfigWidget::MakeStepConfigWidget(MakeStep *makeStep)\n : BuildStepConfigWidget(), m_ui(new Ui::MakeStep), m_makeStep(makeStep), m_ignoreChange(false)\n{\n m_ui->setupUi(this);\n\n m_ui->makePathChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);\n m_ui->makePathChooser->setBaseDirectory(Utils::PathChooser::homePath());\n\n connect(m_ui->makePathChooser, SIGNAL(changed(QString)),\n this, SLOT(makeEdited()));\n connect(m_ui->makeArgumentsLineEdit, SIGNAL(textEdited(QString)),\n this, SLOT(makeArgumentsLineEdited()));\n\n connect(makeStep, SIGNAL(userArgumentsChanged()),\n this, SLOT(userArgumentsChanged()));\n connect(makeStep->buildConfiguration(), SIGNAL(buildDirectoryChanged()),\n this, SLOT(updateDetails()));\n\n connect(makeStep->qt4BuildConfiguration(), SIGNAL(qtVersionChanged()),\n this, SLOT(qtVersionChanged()));\n\n connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),\n this, SLOT(updateMakeOverrideLabel()));\n connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),\n this, SLOT(updateDetails()));\n}\n\nMakeStepConfigWidget::~MakeStepConfigWidget()\n{\n delete m_ui;\n}\n\nvoid MakeStepConfigWidget::qtVersionChanged()\n{\n updateMakeOverrideLabel();\n updateDetails();\n}\n\nvoid MakeStepConfigWidget::updateMakeOverrideLabel()\n{\n Qt4BuildConfiguration *qt4bc = m_makeStep->qt4BuildConfiguration();\n m_ui->makeLabel->setText(tr(\"Override %1:\").arg(qt4bc->makeCommand()));\n}\n\nvoid MakeStepConfigWidget::updateDetails()\n{\n Qt4BuildConfiguration *bc = m_makeStep->qt4BuildConfiguration();\n\n ProjectExplorer::ProcessParameters param;\n param.setMacroExpander(bc->macroExpander());\n param.setWorkingDirectory(bc->buildDirectory());\n param.setEnvironment(bc->environment());\n QString makeCmd = bc->makeCommand();\n if (!m_makeStep->m_makeCmd.isEmpty())\n makeCmd = m_makeStep->m_makeCmd;\n param.setCommand(makeCmd);\n if (param.commandMissing()) {\n m_summaryText = tr(\"<b>Make:<\/b> %1 not found in the environment.\").arg(makeCmd);\n emit updateSummary();\n return;\n }\n\n QString args = m_makeStep->userArguments();\n if (!m_makeStep->isClean()) {\n if (!bc->defaultMakeTarget().isEmpty())\n Utils::QtcProcess::addArg(&args, bc->defaultMakeTarget());\n }\n \/\/ -w option enables \"Enter\"\/\"Leaving directory\" messages, which we need for detecting the\n \/\/ absolute file path\n \/\/ FIXME doing this without the user having a way to override this is rather bad\n \/\/ so we only do it for unix and if the user didn't override the make command\n \/\/ but for now this is the least invasive change\n ProjectExplorer::ToolChain *toolChain = bc->toolChain();\n if (toolChain\n && toolChain->targetAbi().binaryFormat() != ProjectExplorer::Abi::PEFormat\n && m_makeStep->m_makeCmd.isEmpty())\n Utils::QtcProcess::addArg(&args, QLatin1String(\"-w\"));\n param.setArguments(args);\n m_summaryText = param.summaryInWorkdir(displayName());\n emit updateSummary();\n}\n\nQString MakeStepConfigWidget::summaryText() const\n{\n return m_summaryText;\n}\n\nQString MakeStepConfigWidget::displayName() const\n{\n return m_makeStep->displayName();\n}\n\nvoid MakeStepConfigWidget::userArgumentsChanged()\n{\n if (m_ignoreChange)\n return;\n m_ui->makeArgumentsLineEdit->setText(m_makeStep->userArguments());\n updateDetails();\n}\n\nvoid MakeStepConfigWidget::init()\n{\n updateMakeOverrideLabel();\n\n const QString &makeCmd = m_makeStep->m_makeCmd;\n m_ui->makePathChooser->setPath(makeCmd);\n\n m_ui->makeArgumentsLineEdit->setText(m_makeStep->userArguments());\n updateDetails();\n}\n\nvoid MakeStepConfigWidget::makeEdited()\n{\n m_makeStep->m_makeCmd = m_ui->makePathChooser->rawPath();\n updateDetails();\n}\n\nvoid MakeStepConfigWidget::makeArgumentsLineEdited()\n{\n m_ignoreChange = true;\n m_makeStep->setUserArguments(m_ui->makeArgumentsLineEdit->text());\n m_ignoreChange = false;\n updateDetails();\n}\n\n\/\/\/\n\/\/ MakeStepFactory\n\/\/\/\n\nMakeStepFactory::MakeStepFactory(QObject *parent) :\n ProjectExplorer::IBuildStepFactory(parent)\n{\n}\n\nMakeStepFactory::~MakeStepFactory()\n{\n}\n\nbool MakeStepFactory::canCreate(ProjectExplorer::BuildStepList *parent, const QString &id) const\n{\n if (parent->target()->project()->id() != QLatin1String(Constants::QT4PROJECT_ID))\n return false;\n return (id == QLatin1String(MAKESTEP_BS_ID));\n}\n\nProjectExplorer::BuildStep *MakeStepFactory::create(ProjectExplorer::BuildStepList *parent, const QString &id)\n{\n if (!canCreate(parent, id))\n return 0;\n return new MakeStep(parent);\n}\n\nbool MakeStepFactory::canClone(ProjectExplorer::BuildStepList *parent, ProjectExplorer::BuildStep *source) const\n{\n return canCreate(parent, source->id());\n}\n\nProjectExplorer::BuildStep *MakeStepFactory::clone(ProjectExplorer::BuildStepList *parent, ProjectExplorer::BuildStep *source)\n{\n if (!canClone(parent, source))\n return 0;\n return new MakeStep(parent, static_cast<MakeStep *>(source));\n}\n\nbool MakeStepFactory::canRestore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map) const\n{\n QString id(ProjectExplorer::idFromMap(map));\n return canCreate(parent, id);\n}\n\nProjectExplorer::BuildStep *MakeStepFactory::restore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map)\n{\n if (!canRestore(parent, map))\n return 0;\n MakeStep *bs(new MakeStep(parent));\n if (bs->fromMap(map))\n return bs;\n delete bs;\n return 0;\n}\n\nQStringList MakeStepFactory::availableCreationIds(ProjectExplorer::BuildStepList *parent) const\n{\n if (parent->target()->project()->id() == QLatin1String(Constants::QT4PROJECT_ID))\n return QStringList() << QLatin1String(MAKESTEP_BS_ID);\n return QStringList();\n}\n\nQString MakeStepFactory::displayNameForId(const QString &id) const\n{\n if (id == QLatin1String(MAKESTEP_BS_ID))\n return tr(\"Make\");\n return QString();\n}\n<commit_msg>Update makestep on toolchain changes<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 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\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\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** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"makestep.h\"\n#include \"ui_makestep.h\"\n\n#include \"qt4project.h\"\n#include \"qt4target.h\"\n#include \"qt4buildconfiguration.h\"\n#include \"qt4projectmanagerconstants.h\"\n#include \"qtparser.h\"\n\n#include <projectexplorer\/toolchain.h>\n#include <projectexplorer\/buildsteplist.h>\n#include <projectexplorer\/projectexplorer.h>\n#include <projectexplorer\/projectexplorerconstants.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <utils\/qtcprocess.h>\n\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n\nusing ExtensionSystem::PluginManager;\nusing namespace Qt4ProjectManager;\nusing namespace Qt4ProjectManager::Internal;\n\nnamespace {\nconst char * const MAKESTEP_BS_ID(\"Qt4ProjectManager.MakeStep\");\n\nconst char * const MAKE_ARGUMENTS_KEY(\"Qt4ProjectManager.MakeStep.MakeArguments\");\nconst char * const MAKE_COMMAND_KEY(\"Qt4ProjectManager.MakeStep.MakeCommand\");\nconst char * const CLEAN_KEY(\"Qt4ProjectManager.MakeStep.Clean\");\n}\n\nMakeStep::MakeStep(ProjectExplorer::BuildStepList *bsl) :\n AbstractProcessStep(bsl, QLatin1String(MAKESTEP_BS_ID)),\n m_clean(false)\n{\n ctor();\n}\n\nMakeStep::MakeStep(ProjectExplorer::BuildStepList *bsl, MakeStep *bs) :\n AbstractProcessStep(bsl, bs),\n m_clean(bs->m_clean),\n m_userArgs(bs->m_userArgs),\n m_makeCmd(bs->m_makeCmd)\n{\n ctor();\n}\n\nMakeStep::MakeStep(ProjectExplorer::BuildStepList *bsl, const QString &id) :\n AbstractProcessStep(bsl, id),\n m_clean(false)\n{\n ctor();\n}\n\nvoid MakeStep::ctor()\n{\n setDefaultDisplayName(tr(\"Make\", \"Qt4 MakeStep display name.\"));\n}\n\nMakeStep::~MakeStep()\n{\n}\n\nQt4BuildConfiguration *MakeStep::qt4BuildConfiguration() const\n{\n return static_cast<Qt4BuildConfiguration *>(buildConfiguration());\n}\n\nvoid MakeStep::setClean(bool clean)\n{\n m_clean = clean;\n}\n\nbool MakeStep::isClean() const\n{\n return m_clean;\n}\n\nQVariantMap MakeStep::toMap() const\n{\n QVariantMap map(ProjectExplorer::AbstractProcessStep::toMap());\n map.insert(QLatin1String(MAKE_ARGUMENTS_KEY), m_userArgs);\n map.insert(QLatin1String(MAKE_COMMAND_KEY), m_makeCmd);\n map.insert(QLatin1String(CLEAN_KEY), m_clean);\n return map;\n}\n\nbool MakeStep::fromMap(const QVariantMap &map)\n{\n m_makeCmd = map.value(QLatin1String(MAKE_COMMAND_KEY)).toString();\n m_userArgs = map.value(QLatin1String(MAKE_ARGUMENTS_KEY)).toString();\n m_clean = map.value(QLatin1String(CLEAN_KEY)).toBool();\n\n return ProjectExplorer::AbstractProcessStep::fromMap(map);\n}\n\nbool MakeStep::init()\n{\n Qt4BuildConfiguration *bc = qt4BuildConfiguration();\n\n m_tasks.clear();\n if (!bc->toolChain()) {\n m_tasks.append(ProjectExplorer::Task(ProjectExplorer::Task::Error,\n tr(\"Qt Creator needs a tool chain set up to build. Please configure a tool chain in Project mode.\"),\n QString(), -1,\n QLatin1String(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));\n }\n\n ProjectExplorer::ProcessParameters *pp = processParameters();\n pp->setMacroExpander(bc->macroExpander());\n\n Utils::Environment environment = bc->environment();\n pp->setEnvironment(environment);\n\n QString workingDirectory;\n if (bc->subNodeBuild())\n workingDirectory = bc->subNodeBuild()->buildDir();\n else\n workingDirectory = bc->buildDirectory();\n pp->setWorkingDirectory(workingDirectory);\n\n QString makeCmd = bc->makeCommand();\n if (!m_makeCmd.isEmpty())\n makeCmd = m_makeCmd;\n pp->setCommand(makeCmd);\n\n \/\/ If we are cleaning, then make can fail with a error code, but that doesn't mean\n \/\/ we should stop the clean queue\n \/\/ That is mostly so that rebuild works on a already clean project\n setIgnoreReturnValue(m_clean);\n\n QString args;\n\n ProjectExplorer::ToolChain *toolchain = bc->toolChain();\n\n if (bc->subNodeBuild()) {\n QString makefile = bc->subNodeBuild()->makefile();\n if(!makefile.isEmpty()) {\n Utils::QtcProcess::addArg(&args, QLatin1String(\"-f\"));\n Utils::QtcProcess::addArg(&args, makefile);\n m_makeFileToCheck = QDir(workingDirectory).filePath(makefile);\n } else {\n m_makeFileToCheck = QDir(workingDirectory).filePath(\"Makefile\");\n }\n } else {\n if (!bc->makefile().isEmpty()) {\n Utils::QtcProcess::addArg(&args, QLatin1String(\"-f\"));\n Utils::QtcProcess::addArg(&args, bc->makefile());\n m_makeFileToCheck = QDir(workingDirectory).filePath(bc->makefile());\n } else {\n m_makeFileToCheck = QDir(workingDirectory).filePath(\"Makefile\");\n }\n }\n\n Utils::QtcProcess::addArgs(&args, m_userArgs);\n\n if (!isClean()) {\n if (!bc->defaultMakeTarget().isEmpty())\n Utils::QtcProcess::addArg(&args, bc->defaultMakeTarget());\n }\n \/\/ -w option enables \"Enter\"\/\"Leaving directory\" messages, which we need for detecting the\n \/\/ absolute file path\n \/\/ FIXME doing this without the user having a way to override this is rather bad\n \/\/ so we only do it for unix and if the user didn't override the make command\n \/\/ but for now this is the least invasive change\n if (toolchain\n && toolchain->targetAbi().binaryFormat() != ProjectExplorer::Abi::PEFormat\n && m_makeCmd.isEmpty())\n Utils::QtcProcess::addArg(&args, QLatin1String(\"-w\"));\n\n setEnabled(true);\n pp->setArguments(args);\n\n ProjectExplorer::IOutputParser *parser = bc->qtVersion()->createOutputParser();\n Q_ASSERT(parser);\n parser->appendOutputParser(new QtParser);\n if (toolchain)\n parser->appendOutputParser(toolchain->outputParser());\n\n parser->setWorkingDirectory(workingDirectory);\n\n setOutputParser(parser);\n\n return AbstractProcessStep::init();\n}\n\nvoid MakeStep::run(QFutureInterface<bool> & fi)\n{\n if (qt4BuildConfiguration()->qt4Target()->qt4Project()->rootProjectNode()->projectType() == ScriptTemplate) {\n fi.reportResult(true);\n return;\n }\n\n if (!QFileInfo(m_makeFileToCheck).exists()) {\n if (!m_clean)\n emit addOutput(tr(\"Makefile not found. Please check your build settings\"), BuildStep::MessageOutput);\n fi.reportResult(m_clean);\n return;\n }\n\n \/\/ Warn on common error conditions:\n bool canContinue = true;\n foreach (const ProjectExplorer::Task &t, m_tasks) {\n addTask(t);\n if (t.type == ProjectExplorer::Task::Error)\n canContinue = false;\n }\n if (!canContinue) {\n emit addOutput(tr(\"Configuration is faulty, please check the Build Issues view for details.\"), BuildStep::MessageOutput);\n fi.reportResult(false);\n return;\n }\n\n AbstractProcessStep::run(fi);\n}\n\nbool MakeStep::processSucceeded(int exitCode, QProcess::ExitStatus status)\n{\n \/\/ Symbian does retun 0, even on failed makes! So we check for fatal make errors here.\n if (outputParser() && outputParser()->hasFatalErrors())\n return false;\n\n return AbstractProcessStep::processSucceeded(exitCode, status);\n}\n\nbool MakeStep::immutable() const\n{\n return false;\n}\n\nProjectExplorer::BuildStepConfigWidget *MakeStep::createConfigWidget()\n{\n return new MakeStepConfigWidget(this);\n}\n\nQString MakeStep::userArguments()\n{\n return m_userArgs;\n}\n\nvoid MakeStep::setUserArguments(const QString &arguments)\n{\n m_userArgs = arguments;\n emit userArgumentsChanged();\n}\n\nMakeStepConfigWidget::MakeStepConfigWidget(MakeStep *makeStep)\n : BuildStepConfigWidget(), m_ui(new Ui::MakeStep), m_makeStep(makeStep), m_ignoreChange(false)\n{\n m_ui->setupUi(this);\n\n m_ui->makePathChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);\n m_ui->makePathChooser->setBaseDirectory(Utils::PathChooser::homePath());\n\n connect(m_ui->makePathChooser, SIGNAL(changed(QString)),\n this, SLOT(makeEdited()));\n connect(m_ui->makeArgumentsLineEdit, SIGNAL(textEdited(QString)),\n this, SLOT(makeArgumentsLineEdited()));\n\n connect(makeStep, SIGNAL(userArgumentsChanged()),\n this, SLOT(userArgumentsChanged()));\n connect(makeStep->buildConfiguration(), SIGNAL(buildDirectoryChanged()),\n this, SLOT(updateDetails()));\n connect(makeStep->buildConfiguration(), SIGNAL(toolChainChanged()),\n this, SLOT(updateDetails()));\n\n connect(makeStep->qt4BuildConfiguration(), SIGNAL(qtVersionChanged()),\n this, SLOT(qtVersionChanged()));\n\n connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),\n this, SLOT(updateMakeOverrideLabel()));\n connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),\n this, SLOT(updateDetails()));\n}\n\nMakeStepConfigWidget::~MakeStepConfigWidget()\n{\n delete m_ui;\n}\n\nvoid MakeStepConfigWidget::qtVersionChanged()\n{\n updateMakeOverrideLabel();\n updateDetails();\n}\n\nvoid MakeStepConfigWidget::updateMakeOverrideLabel()\n{\n Qt4BuildConfiguration *qt4bc = m_makeStep->qt4BuildConfiguration();\n m_ui->makeLabel->setText(tr(\"Override %1:\").arg(qt4bc->makeCommand()));\n}\n\nvoid MakeStepConfigWidget::updateDetails()\n{\n Qt4BuildConfiguration *bc = m_makeStep->qt4BuildConfiguration();\n\n ProjectExplorer::ProcessParameters param;\n param.setMacroExpander(bc->macroExpander());\n param.setWorkingDirectory(bc->buildDirectory());\n param.setEnvironment(bc->environment());\n QString makeCmd = bc->makeCommand();\n if (!m_makeStep->m_makeCmd.isEmpty())\n makeCmd = m_makeStep->m_makeCmd;\n param.setCommand(makeCmd);\n if (param.commandMissing()) {\n m_summaryText = tr(\"<b>Make:<\/b> %1 not found in the environment.\").arg(makeCmd);\n emit updateSummary();\n return;\n }\n\n QString args = m_makeStep->userArguments();\n if (!m_makeStep->isClean()) {\n if (!bc->defaultMakeTarget().isEmpty())\n Utils::QtcProcess::addArg(&args, bc->defaultMakeTarget());\n }\n \/\/ -w option enables \"Enter\"\/\"Leaving directory\" messages, which we need for detecting the\n \/\/ absolute file path\n \/\/ FIXME doing this without the user having a way to override this is rather bad\n \/\/ so we only do it for unix and if the user didn't override the make command\n \/\/ but for now this is the least invasive change\n ProjectExplorer::ToolChain *toolChain = bc->toolChain();\n if (toolChain\n && toolChain->targetAbi().binaryFormat() != ProjectExplorer::Abi::PEFormat\n && m_makeStep->m_makeCmd.isEmpty())\n Utils::QtcProcess::addArg(&args, QLatin1String(\"-w\"));\n param.setArguments(args);\n m_summaryText = param.summaryInWorkdir(displayName());\n emit updateSummary();\n}\n\nQString MakeStepConfigWidget::summaryText() const\n{\n return m_summaryText;\n}\n\nQString MakeStepConfigWidget::displayName() const\n{\n return m_makeStep->displayName();\n}\n\nvoid MakeStepConfigWidget::userArgumentsChanged()\n{\n if (m_ignoreChange)\n return;\n m_ui->makeArgumentsLineEdit->setText(m_makeStep->userArguments());\n updateDetails();\n}\n\nvoid MakeStepConfigWidget::init()\n{\n updateMakeOverrideLabel();\n\n const QString &makeCmd = m_makeStep->m_makeCmd;\n m_ui->makePathChooser->setPath(makeCmd);\n\n m_ui->makeArgumentsLineEdit->setText(m_makeStep->userArguments());\n updateDetails();\n}\n\nvoid MakeStepConfigWidget::makeEdited()\n{\n m_makeStep->m_makeCmd = m_ui->makePathChooser->rawPath();\n updateDetails();\n}\n\nvoid MakeStepConfigWidget::makeArgumentsLineEdited()\n{\n m_ignoreChange = true;\n m_makeStep->setUserArguments(m_ui->makeArgumentsLineEdit->text());\n m_ignoreChange = false;\n updateDetails();\n}\n\n\/\/\/\n\/\/ MakeStepFactory\n\/\/\/\n\nMakeStepFactory::MakeStepFactory(QObject *parent) :\n ProjectExplorer::IBuildStepFactory(parent)\n{\n}\n\nMakeStepFactory::~MakeStepFactory()\n{\n}\n\nbool MakeStepFactory::canCreate(ProjectExplorer::BuildStepList *parent, const QString &id) const\n{\n if (parent->target()->project()->id() != QLatin1String(Constants::QT4PROJECT_ID))\n return false;\n return (id == QLatin1String(MAKESTEP_BS_ID));\n}\n\nProjectExplorer::BuildStep *MakeStepFactory::create(ProjectExplorer::BuildStepList *parent, const QString &id)\n{\n if (!canCreate(parent, id))\n return 0;\n return new MakeStep(parent);\n}\n\nbool MakeStepFactory::canClone(ProjectExplorer::BuildStepList *parent, ProjectExplorer::BuildStep *source) const\n{\n return canCreate(parent, source->id());\n}\n\nProjectExplorer::BuildStep *MakeStepFactory::clone(ProjectExplorer::BuildStepList *parent, ProjectExplorer::BuildStep *source)\n{\n if (!canClone(parent, source))\n return 0;\n return new MakeStep(parent, static_cast<MakeStep *>(source));\n}\n\nbool MakeStepFactory::canRestore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map) const\n{\n QString id(ProjectExplorer::idFromMap(map));\n return canCreate(parent, id);\n}\n\nProjectExplorer::BuildStep *MakeStepFactory::restore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map)\n{\n if (!canRestore(parent, map))\n return 0;\n MakeStep *bs(new MakeStep(parent));\n if (bs->fromMap(map))\n return bs;\n delete bs;\n return 0;\n}\n\nQStringList MakeStepFactory::availableCreationIds(ProjectExplorer::BuildStepList *parent) const\n{\n if (parent->target()->project()->id() == QLatin1String(Constants::QT4PROJECT_ID))\n return QStringList() << QLatin1String(MAKESTEP_BS_ID);\n return QStringList();\n}\n\nQString MakeStepFactory::displayNameForId(const QString &id) const\n{\n if (id == QLatin1String(MAKESTEP_BS_ID))\n return tr(\"Make\");\n return QString();\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 1992-$THISYEAR$ $TROLLTECH$. All rights reserved.\n**\n** This file is part of the $MODULE$ of the Qt Toolkit.\n**\n** $TROLLTECH_DUAL_LICENSE$\n**\n** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n**\n****************************************************************************\/\n\n#include \"qml.h\"\n#include \"qmlviewer.h\"\n#include <QWidget>\n#include <QDir>\n#include <QApplication>\n#include <QTranslator>\n#include <QDebug>\n\nvoid usage()\n{\n qWarning(\"Usage: qmlviewer [options] <filename>\");\n qWarning(\" \");\n qWarning(\" options:\");\n qWarning(\" -v, -version ............................. display version\");\n qWarning(\" -frameless ............................... run with no window frame\");\n qWarning(\" -skin <qvfbskindir> ...................... run with a skin window frame\");\n qWarning(\" -recordfile <output> ..................... set video recording file\");\n qWarning(\" - ImageMagick 'convert' for GIF)\");\n qWarning(\" - png file for raw frames\");\n qWarning(\" - 'ffmpeg' for other formats\");\n qWarning(\" -recorddither ordered|threshold|floyd .... set GIF dither recording mode\");\n qWarning(\" -recordperiod <milliseconds> ............. set time between recording frames\");\n qWarning(\" -record arg .............................. add a recording process argument\");\n qWarning(\" -autorecord [from-]<tomilliseconds> ...... set recording to start and stop\");\n qWarning(\" -devicekeys .............................. use numeric keys (see F1)\");\n qWarning(\" -netcache <size> ......................... set disk cache to size bytes\");\n qWarning(\" -recordtest <directory> .................. record an autotest\");\n qWarning(\" -runtest <directory> ..................... run a previously recorded test\");\n qWarning(\" -translation <translationfile> ........... set the language to run in\");\n qWarning(\" -L <directory> ........................... prepend to the library search path\");\n qWarning(\" \");\n qWarning(\" Press F1 for interactive help\");\n exit(1);\n}\n\nint main(int argc, char ** argv)\n{\n \/\/### default to using raster graphics backend for now\n bool gsSpecified = false;\n for (int i = 0; i < argc; ++i) {\n QString arg = argv[i];\n if (arg == \"-graphicssystem\") {\n gsSpecified = true;\n break;\n }\n }\n if (!gsSpecified)\n QApplication::setGraphicsSystem(\"raster\");\n\n QApplication app(argc, argv);\n app.setApplicationName(\"viewer\");\n\n bool frameless = false;\n QString fileName;\n int period = 0;\n int autorecord_from = 0;\n int autorecord_to = 0;\n QString dither = \"none\";\n QString recordfile;\n QStringList recordargs;\n QStringList libraries;\n QString skin;\n bool devkeys = false;\n int cache = 0;\n QString translationFile;\n\n for (int i = 1; i < argc; ++i) {\n QString arg = argv[i];\n if (arg == \"-frameless\") {\n frameless = true;\n } else if (arg == \"-skin\") {\n skin = QString(argv[++i]);\n } else if (arg == \"-netcache\") {\n cache = QString(argv[++i]).toInt();\n } else if (arg == \"-recordperiod\") {\n period = QString(argv[++i]).toInt();\n } else if (arg == \"-recordfile\") {\n recordfile = QString(argv[++i]);\n } else if (arg == \"-record\") {\n recordargs << QString(argv[++i]);\n } else if (arg == \"-recorddither\") {\n dither = QString(argv[++i]);\n } else if (arg == \"-autorecord\") {\n QString range = QString(argv[++i]);\n int dash = range.indexOf('-');\n if (dash > 0)\n autorecord_from = range.left(dash).toInt();\n autorecord_to = range.mid(dash+1).toInt();\n } else if (arg == \"-devicekeys\") {\n devkeys = true;\n } else if (arg == QLatin1String(\"-v\") || arg == QLatin1String(\"-version\")) {\n fprintf(stderr, \"Qt Declarative UI Viewer version %s\\n\", QT_VERSION_STR);\n return 0;\n } else if (arg == \"-translation\") {\n if(i + 1 >= argc)\n usage();\n translationFile = argv[i + 1];\n ++i;\n } else if (arg == \"-L\") {\n libraries << QString(argv[++i]);\n } else if (arg[0] != '-') {\n fileName = arg;\n } else if (1 || arg == \"-help\") {\n usage();\n }\n }\n\n QTranslator qmlTranslator;\n if (!translationFile.isEmpty()) {\n qmlTranslator.load(translationFile);\n app.installTranslator(&qmlTranslator);\n }\n\n QmlViewer viewer(0, frameless ? Qt::FramelessWindowHint : Qt::Widget);\n foreach (QString lib, libraries)\n viewer.addLibraryPath(lib);\n viewer.setNetworkCacheSize(cache);\n viewer.setRecordFile(recordfile);\n if (period>0)\n viewer.setRecordPeriod(period);\n if (autorecord_to)\n viewer.setAutoRecord(autorecord_from,autorecord_to);\n if (!skin.isEmpty() && QDir(skin).exists())\n viewer.setSkin(skin);\n if (devkeys)\n viewer.setDeviceKeys(true);\n viewer.setRecordDither(dither);\n viewer.setRecordArgs(recordargs);\n if (!fileName.isEmpty()) {\n viewer.openQml(fileName);\n viewer.show();\n } else {\n viewer.show();\n viewer.open();\n }\n\n return app.exec();\n}\n<commit_msg>Update docs (no recordtest\/runtest now)<commit_after>\/****************************************************************************\n**\n** Copyright (C) 1992-$THISYEAR$ $TROLLTECH$. All rights reserved.\n**\n** This file is part of the $MODULE$ of the Qt Toolkit.\n**\n** $TROLLTECH_DUAL_LICENSE$\n**\n** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n**\n****************************************************************************\/\n\n#include \"qml.h\"\n#include \"qmlviewer.h\"\n#include <QWidget>\n#include <QDir>\n#include <QApplication>\n#include <QTranslator>\n#include <QDebug>\n\nvoid usage()\n{\n qWarning(\"Usage: qmlviewer [options] <filename>\");\n qWarning(\" \");\n qWarning(\" options:\");\n qWarning(\" -v, -version ............................. display version\");\n qWarning(\" -frameless ............................... run with no window frame\");\n qWarning(\" -skin <qvfbskindir> ...................... run with a skin window frame\");\n qWarning(\" -recordfile <output> ..................... set video recording file\");\n qWarning(\" - ImageMagick 'convert' for GIF)\");\n qWarning(\" - png file for raw frames\");\n qWarning(\" - 'ffmpeg' for other formats\");\n qWarning(\" -recorddither ordered|threshold|floyd .... set GIF dither recording mode\");\n qWarning(\" -recordperiod <milliseconds> ............. set time between recording frames\");\n qWarning(\" -record arg .............................. add a recording process argument\");\n qWarning(\" -autorecord [from-]<tomilliseconds> ...... set recording to start and stop\");\n qWarning(\" -devicekeys .............................. use numeric keys (see F1)\");\n qWarning(\" -netcache <size> ......................... set disk cache to size bytes\");\n qWarning(\" -translation <translationfile> ........... set the language to run in\");\n qWarning(\" -L <directory> ........................... prepend to the library search path\");\n qWarning(\" \");\n qWarning(\" Press F1 for interactive help\");\n exit(1);\n}\n\nint main(int argc, char ** argv)\n{\n \/\/### default to using raster graphics backend for now\n bool gsSpecified = false;\n for (int i = 0; i < argc; ++i) {\n QString arg = argv[i];\n if (arg == \"-graphicssystem\") {\n gsSpecified = true;\n break;\n }\n }\n if (!gsSpecified)\n QApplication::setGraphicsSystem(\"raster\");\n\n QApplication app(argc, argv);\n app.setApplicationName(\"viewer\");\n\n bool frameless = false;\n QString fileName;\n int period = 0;\n int autorecord_from = 0;\n int autorecord_to = 0;\n QString dither = \"none\";\n QString recordfile;\n QStringList recordargs;\n QStringList libraries;\n QString skin;\n bool devkeys = false;\n int cache = 0;\n QString translationFile;\n\n for (int i = 1; i < argc; ++i) {\n QString arg = argv[i];\n if (arg == \"-frameless\") {\n frameless = true;\n } else if (arg == \"-skin\") {\n skin = QString(argv[++i]);\n } else if (arg == \"-netcache\") {\n cache = QString(argv[++i]).toInt();\n } else if (arg == \"-recordperiod\") {\n period = QString(argv[++i]).toInt();\n } else if (arg == \"-recordfile\") {\n recordfile = QString(argv[++i]);\n } else if (arg == \"-record\") {\n recordargs << QString(argv[++i]);\n } else if (arg == \"-recorddither\") {\n dither = QString(argv[++i]);\n } else if (arg == \"-autorecord\") {\n QString range = QString(argv[++i]);\n int dash = range.indexOf('-');\n if (dash > 0)\n autorecord_from = range.left(dash).toInt();\n autorecord_to = range.mid(dash+1).toInt();\n } else if (arg == \"-devicekeys\") {\n devkeys = true;\n } else if (arg == QLatin1String(\"-v\") || arg == QLatin1String(\"-version\")) {\n fprintf(stderr, \"Qt Declarative UI Viewer version %s\\n\", QT_VERSION_STR);\n return 0;\n } else if (arg == \"-translation\") {\n if(i + 1 >= argc)\n usage();\n translationFile = argv[i + 1];\n ++i;\n } else if (arg == \"-L\") {\n libraries << QString(argv[++i]);\n } else if (arg[0] != '-') {\n fileName = arg;\n } else if (1 || arg == \"-help\") {\n usage();\n }\n }\n\n QTranslator qmlTranslator;\n if (!translationFile.isEmpty()) {\n qmlTranslator.load(translationFile);\n app.installTranslator(&qmlTranslator);\n }\n\n QmlViewer viewer(0, frameless ? Qt::FramelessWindowHint : Qt::Widget);\n foreach (QString lib, libraries)\n viewer.addLibraryPath(lib);\n viewer.setNetworkCacheSize(cache);\n viewer.setRecordFile(recordfile);\n if (period>0)\n viewer.setRecordPeriod(period);\n if (autorecord_to)\n viewer.setAutoRecord(autorecord_from,autorecord_to);\n if (!skin.isEmpty() && QDir(skin).exists())\n viewer.setSkin(skin);\n if (devkeys)\n viewer.setDeviceKeys(true);\n viewer.setRecordDither(dither);\n viewer.setRecordArgs(recordargs);\n if (!fileName.isEmpty()) {\n viewer.openQml(fileName);\n viewer.show();\n } else {\n viewer.show();\n viewer.open();\n }\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Toru Niina 2017.\n\/\/ Distributed under the MIT License.\n#ifndef TOML11_TRAITS_HPP\n#define TOML11_TRAITS_HPP\n#include <type_traits>\n#include <utility>\n#include <chrono>\n#include <tuple>\n#include <string>\n#if __cplusplus >= 201703L\n#if __has_include(<string_view>)\n#include <string_view>\n#endif \/\/ has_include(<string_view>)\n#endif \/\/ cplusplus >= C++17\n\nnamespace toml\n{\ntemplate<typename C, template<typename ...> class T, template<typename ...> class A>\nclass basic_value;\n\nnamespace detail\n{\n\/\/ ---------------------------------------------------------------------------\n\/\/ check whether type T is a kind of container\/map class\n\nstruct has_iterator_impl\n{\n template<typename T> static std::true_type check(typename T::iterator*);\n template<typename T> static std::false_type check(...);\n};\nstruct has_value_type_impl\n{\n template<typename T> static std::true_type check(typename T::value_type*);\n template<typename T> static std::false_type check(...);\n};\nstruct has_key_type_impl\n{\n template<typename T> static std::true_type check(typename T::key_type*);\n template<typename T> static std::false_type check(...);\n};\nstruct has_mapped_type_impl\n{\n template<typename T> static std::true_type check(typename T::mapped_type*);\n template<typename T> static std::false_type check(...);\n};\nstruct has_resize_method_impl\n{\n constexpr static std::size_t dummy=0;\n template<typename T> static std::true_type check(decltype(std::declval<T>().resize(dummy))*);\n template<typename T> static std::false_type check(...);\n};\n\nstruct is_comparable_impl\n{\n template<typename T> static std::true_type check(decltype(std::declval<T>() < std::declval<T>())*);\n template<typename T> static std::false_type check(...);\n};\n\nstruct has_from_toml_method_impl\n{\n template<typename T, typename C,\n template<typename ...> class Tb, template<typename ...> class A>\n static std::true_type check(\n decltype(std::declval<T>().from_toml(\n std::declval<::toml::basic_value<C, Tb, A>>()))*);\n\n template<typename T, typename C,\n template<typename ...> class Tb, template<typename ...> class A>\n static std::false_type check(...);\n};\nstruct has_into_toml_method_impl\n{\n template<typename T>\n static std::true_type check(decltype(std::declval<T>().into_toml())*);\n template<typename T>\n static std::false_type check(...);\n};\n\n\/\/\/ Intel C++ compiler can not use decltype in parent class declaration, here\n\/\/\/ is a hack to work around it. https:\/\/stackoverflow.com\/a\/23953090\/4692076\n#ifdef __INTEL_COMPILER\n#define decltype(...) std::enable_if<true, decltype(__VA_ARGS__)>::type\n#endif\n\ntemplate<typename T>\nstruct has_iterator : decltype(has_iterator_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_value_type : decltype(has_value_type_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_key_type : decltype(has_key_type_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_mapped_type : decltype(has_mapped_type_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_resize_method : decltype(has_resize_method_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct is_comparable : decltype(is_comparable_impl::check<T>(nullptr)){};\n\ntemplate<typename T, typename C,\n template<typename ...> class Tb, template<typename ...> class A>\nstruct has_from_toml_method\n: decltype(has_from_toml_method_impl::check<T, C, Tb, A>(nullptr)){};\n\ntemplate<typename T>\nstruct has_into_toml_method\n: decltype(has_into_toml_method_impl::check<T>(nullptr)){};\n\n#ifdef __INTEL_COMPILER\n#undef decltype\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++17 and\/or\/not\n\n#if __cplusplus >= 201703L\n\nusing std::conjunction;\nusing std::disjunction;\nusing std::negation;\n\n#else\n\ntemplate<typename ...> struct conjunction : std::true_type{};\ntemplate<typename T> struct conjunction<T> : T{};\ntemplate<typename T, typename ... Ts>\nstruct conjunction<T, Ts...> :\n std::conditional<static_cast<bool>(T::value), conjunction<Ts...>, T>::type\n{};\n\ntemplate<typename ...> struct disjunction : std::false_type{};\ntemplate<typename T> struct disjunction<T> : T {};\ntemplate<typename T, typename ... Ts>\nstruct disjunction<T, Ts...> :\n std::conditional<static_cast<bool>(T::value), T, disjunction<Ts...>>::type\n{};\n\ntemplate<typename T>\nstruct negation : std::integral_constant<bool, !static_cast<bool>(T::value)>{};\n\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ type checkers\n\ntemplate<typename T> struct is_std_pair : std::false_type{};\ntemplate<typename T1, typename T2>\nstruct is_std_pair<std::pair<T1, T2>> : std::true_type{};\n\ntemplate<typename T> struct is_std_tuple : std::false_type{};\ntemplate<typename ... Ts>\nstruct is_std_tuple<std::tuple<Ts...>> : std::true_type{};\n\ntemplate<typename T> struct is_chrono_duration: std::false_type{};\ntemplate<typename Rep, typename Period>\nstruct is_chrono_duration<std::chrono::duration<Rep, Period>>: std::true_type{};\n\ntemplate<typename T>\nstruct is_map : conjunction< \/\/ map satisfies all the following conditions\n has_iterator<T>, \/\/ has T::iterator\n has_value_type<T>, \/\/ has T::value_type\n has_key_type<T>, \/\/ has T::key_type\n has_mapped_type<T> \/\/ has T::mapped_type\n >{};\ntemplate<typename T> struct is_map<T&> : is_map<T>{};\ntemplate<typename T> struct is_map<T const&> : is_map<T>{};\ntemplate<typename T> struct is_map<T volatile&> : is_map<T>{};\ntemplate<typename T> struct is_map<T const volatile&> : is_map<T>{};\n\ntemplate<typename T>\nstruct is_container : conjunction<\n negation<is_map<T>>, \/\/ not a map\n negation<std::is_same<T, std::string>>, \/\/ not a std::string\n#if __cplusplus >= 201703L\n negation<std::is_same<T, std::string_view>>, \/\/ not a std::string_view\n#endif\n has_iterator<T>, \/\/ has T::iterator\n has_value_type<T> \/\/ has T::value_type\n >{};\ntemplate<typename T> struct is_container<T&> : is_container<T>{};\ntemplate<typename T> struct is_container<T const&> : is_container<T>{};\ntemplate<typename T> struct is_container<T volatile&> : is_container<T>{};\ntemplate<typename T> struct is_container<T const volatile&> : is_container<T>{};\n\ntemplate<typename T>\nstruct is_basic_value: std::false_type{};\ntemplate<typename T> struct is_basic_value<T&> : is_basic_value<T>{};\ntemplate<typename T> struct is_basic_value<T const&> : is_basic_value<T>{};\ntemplate<typename T> struct is_basic_value<T volatile&> : is_basic_value<T>{};\ntemplate<typename T> struct is_basic_value<T const volatile&> : is_basic_value<T>{};\ntemplate<typename C, template<typename ...> class M, template<typename ...> class V>\nstruct is_basic_value<::toml::basic_value<C, M, V>>: std::true_type{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++14 index_sequence\n\n#if __cplusplus >= 201402L\n\nusing std::index_sequence;\nusing std::make_index_sequence;\n\n#else\n\ntemplate<std::size_t ... Ns> struct index_sequence{};\n\ntemplate<typename IS, std::size_t N> struct push_back_index_sequence{};\ntemplate<std::size_t N, std::size_t ... Ns>\nstruct push_back_index_sequence<index_sequence<Ns...>, N>\n{\n typedef index_sequence<Ns..., N> type;\n};\n\ntemplate<std::size_t N>\nstruct index_sequence_maker\n{\n typedef typename push_back_index_sequence<\n typename index_sequence_maker<N-1>::type, N>::type type;\n};\ntemplate<>\nstruct index_sequence_maker<0>\n{\n typedef index_sequence<0> type;\n};\ntemplate<std::size_t N>\nusing make_index_sequence = typename index_sequence_maker<N-1>::type;\n\n#endif \/\/ __cplusplus >= 2014\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++14 enable_if_t\n\n#if __cplusplus >= 201402L\n\nusing std::enable_if_t;\n\n#else\n\ntemplate<bool B, typename T>\nusing enable_if_t = typename std::enable_if<B, T>::type;\n\n#endif \/\/ __cplusplus >= 2014\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ return_type_of_t\n\n#if __cplusplus >= 201703L\n\ntemplate<typename F, typename ... Args>\nusing return_type_of_t = std::invoke_result_t<F, Args...>;\n\n#else\n\/\/ result_of is deprecated after C++17\ntemplate<typename F, typename ... Args>\nusing return_type_of_t = typename std::result_of<F(Args...)>::type;\n\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ is_string_literal\n\/\/\n\/\/ to use this, pass `typename remove_reference<T>::type` to T.\n\ntemplate<typename T>\nstruct is_string_literal:\ndisjunction<\n std::is_same<const char*, T>,\n conjunction<\n std::is_array<T>,\n std::is_same<const char, typename std::remove_extent<T>::type>\n >\n >{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++20 remove_cvref_t\n\ntemplate<typename T>\nstruct remove_cvref\n{\n using type = typename std::remove_cv<\n typename std::remove_reference<T>::type>::type;\n};\n\ntemplate<typename T>\nusing remove_cvref_t = typename remove_cvref<T>::type;\n\n}\/\/ detail\n}\/\/toml\n#endif \/\/ TOML_TRAITS\n<commit_msg>feat: add meta funcs, has_reserve\/push_back_method<commit_after>\/\/ Copyright Toru Niina 2017.\n\/\/ Distributed under the MIT License.\n#ifndef TOML11_TRAITS_HPP\n#define TOML11_TRAITS_HPP\n#include <type_traits>\n#include <utility>\n#include <chrono>\n#include <tuple>\n#include <string>\n#if __cplusplus >= 201703L\n#if __has_include(<string_view>)\n#include <string_view>\n#endif \/\/ has_include(<string_view>)\n#endif \/\/ cplusplus >= C++17\n\nnamespace toml\n{\ntemplate<typename C, template<typename ...> class T, template<typename ...> class A>\nclass basic_value;\n\nnamespace detail\n{\n\/\/ ---------------------------------------------------------------------------\n\/\/ check whether type T is a kind of container\/map class\n\nstruct has_iterator_impl\n{\n template<typename T> static std::true_type check(typename T::iterator*);\n template<typename T> static std::false_type check(...);\n};\nstruct has_value_type_impl\n{\n template<typename T> static std::true_type check(typename T::value_type*);\n template<typename T> static std::false_type check(...);\n};\nstruct has_key_type_impl\n{\n template<typename T> static std::true_type check(typename T::key_type*);\n template<typename T> static std::false_type check(...);\n};\nstruct has_mapped_type_impl\n{\n template<typename T> static std::true_type check(typename T::mapped_type*);\n template<typename T> static std::false_type check(...);\n};\nstruct has_reserve_method_impl\n{\n template<typename T> static std::false_type check(...);\n template<typename T> static std::true_type check(\n decltype(std::declval<T>().reserve(std::declval<std::size_t>()))*);\n};\nstruct has_push_back_method_impl\n{\n template<typename T> static std::false_type check(...);\n template<typename T> static std::true_type check(\n decltype(std::declval<T>().push_back(std::declval<typename T::value_type>()))*);\n};\nstruct is_comparable_impl\n{\n template<typename T> static std::false_type check(...);\n template<typename T> static std::true_type check(\n decltype(std::declval<T>() < std::declval<T>())*);\n};\n\nstruct has_from_toml_method_impl\n{\n template<typename T, typename C,\n template<typename ...> class Tb, template<typename ...> class A>\n static std::true_type check(\n decltype(std::declval<T>().from_toml(\n std::declval<::toml::basic_value<C, Tb, A>>()))*);\n\n template<typename T, typename C,\n template<typename ...> class Tb, template<typename ...> class A>\n static std::false_type check(...);\n};\nstruct has_into_toml_method_impl\n{\n template<typename T>\n static std::true_type check(decltype(std::declval<T>().into_toml())*);\n template<typename T>\n static std::false_type check(...);\n};\n\n\/\/\/ Intel C++ compiler can not use decltype in parent class declaration, here\n\/\/\/ is a hack to work around it. https:\/\/stackoverflow.com\/a\/23953090\/4692076\n#ifdef __INTEL_COMPILER\n#define decltype(...) std::enable_if<true, decltype(__VA_ARGS__)>::type\n#endif\n\ntemplate<typename T>\nstruct has_iterator : decltype(has_iterator_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_value_type : decltype(has_value_type_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_key_type : decltype(has_key_type_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_mapped_type : decltype(has_mapped_type_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_reserve_method : decltype(has_reserve_method_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct has_push_back_method : decltype(has_push_back_method_impl::check<T>(nullptr)){};\ntemplate<typename T>\nstruct is_comparable : decltype(is_comparable_impl::check<T>(nullptr)){};\n\ntemplate<typename T, typename C,\n template<typename ...> class Tb, template<typename ...> class A>\nstruct has_from_toml_method\n: decltype(has_from_toml_method_impl::check<T, C, Tb, A>(nullptr)){};\n\ntemplate<typename T>\nstruct has_into_toml_method\n: decltype(has_into_toml_method_impl::check<T>(nullptr)){};\n\n#ifdef __INTEL_COMPILER\n#undef decltype\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++17 and\/or\/not\n\n#if __cplusplus >= 201703L\n\nusing std::conjunction;\nusing std::disjunction;\nusing std::negation;\n\n#else\n\ntemplate<typename ...> struct conjunction : std::true_type{};\ntemplate<typename T> struct conjunction<T> : T{};\ntemplate<typename T, typename ... Ts>\nstruct conjunction<T, Ts...> :\n std::conditional<static_cast<bool>(T::value), conjunction<Ts...>, T>::type\n{};\n\ntemplate<typename ...> struct disjunction : std::false_type{};\ntemplate<typename T> struct disjunction<T> : T {};\ntemplate<typename T, typename ... Ts>\nstruct disjunction<T, Ts...> :\n std::conditional<static_cast<bool>(T::value), T, disjunction<Ts...>>::type\n{};\n\ntemplate<typename T>\nstruct negation : std::integral_constant<bool, !static_cast<bool>(T::value)>{};\n\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ type checkers\n\ntemplate<typename T> struct is_std_pair : std::false_type{};\ntemplate<typename T1, typename T2>\nstruct is_std_pair<std::pair<T1, T2>> : std::true_type{};\n\ntemplate<typename T> struct is_std_tuple : std::false_type{};\ntemplate<typename ... Ts>\nstruct is_std_tuple<std::tuple<Ts...>> : std::true_type{};\n\ntemplate<typename T> struct is_chrono_duration: std::false_type{};\ntemplate<typename Rep, typename Period>\nstruct is_chrono_duration<std::chrono::duration<Rep, Period>>: std::true_type{};\n\ntemplate<typename T>\nstruct is_map : conjunction< \/\/ map satisfies all the following conditions\n has_iterator<T>, \/\/ has T::iterator\n has_value_type<T>, \/\/ has T::value_type\n has_key_type<T>, \/\/ has T::key_type\n has_mapped_type<T> \/\/ has T::mapped_type\n >{};\ntemplate<typename T> struct is_map<T&> : is_map<T>{};\ntemplate<typename T> struct is_map<T const&> : is_map<T>{};\ntemplate<typename T> struct is_map<T volatile&> : is_map<T>{};\ntemplate<typename T> struct is_map<T const volatile&> : is_map<T>{};\n\ntemplate<typename T>\nstruct is_container : conjunction<\n negation<is_map<T>>, \/\/ not a map\n negation<std::is_same<T, std::string>>, \/\/ not a std::string\n#if __cplusplus >= 201703L\n negation<std::is_same<T, std::string_view>>, \/\/ not a std::string_view\n#endif\n has_iterator<T>, \/\/ has T::iterator\n has_value_type<T> \/\/ has T::value_type\n >{};\ntemplate<typename T> struct is_container<T&> : is_container<T>{};\ntemplate<typename T> struct is_container<T const&> : is_container<T>{};\ntemplate<typename T> struct is_container<T volatile&> : is_container<T>{};\ntemplate<typename T> struct is_container<T const volatile&> : is_container<T>{};\n\ntemplate<typename T>\nstruct is_basic_value: std::false_type{};\ntemplate<typename T> struct is_basic_value<T&> : is_basic_value<T>{};\ntemplate<typename T> struct is_basic_value<T const&> : is_basic_value<T>{};\ntemplate<typename T> struct is_basic_value<T volatile&> : is_basic_value<T>{};\ntemplate<typename T> struct is_basic_value<T const volatile&> : is_basic_value<T>{};\ntemplate<typename C, template<typename ...> class M, template<typename ...> class V>\nstruct is_basic_value<::toml::basic_value<C, M, V>>: std::true_type{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++14 index_sequence\n\n#if __cplusplus >= 201402L\n\nusing std::index_sequence;\nusing std::make_index_sequence;\n\n#else\n\ntemplate<std::size_t ... Ns> struct index_sequence{};\n\ntemplate<typename IS, std::size_t N> struct push_back_index_sequence{};\ntemplate<std::size_t N, std::size_t ... Ns>\nstruct push_back_index_sequence<index_sequence<Ns...>, N>\n{\n typedef index_sequence<Ns..., N> type;\n};\n\ntemplate<std::size_t N>\nstruct index_sequence_maker\n{\n typedef typename push_back_index_sequence<\n typename index_sequence_maker<N-1>::type, N>::type type;\n};\ntemplate<>\nstruct index_sequence_maker<0>\n{\n typedef index_sequence<0> type;\n};\ntemplate<std::size_t N>\nusing make_index_sequence = typename index_sequence_maker<N-1>::type;\n\n#endif \/\/ __cplusplus >= 2014\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++14 enable_if_t\n\n#if __cplusplus >= 201402L\n\nusing std::enable_if_t;\n\n#else\n\ntemplate<bool B, typename T>\nusing enable_if_t = typename std::enable_if<B, T>::type;\n\n#endif \/\/ __cplusplus >= 2014\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ return_type_of_t\n\n#if __cplusplus >= 201703L\n\ntemplate<typename F, typename ... Args>\nusing return_type_of_t = std::invoke_result_t<F, Args...>;\n\n#else\n\/\/ result_of is deprecated after C++17\ntemplate<typename F, typename ... Args>\nusing return_type_of_t = typename std::result_of<F(Args...)>::type;\n\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ is_string_literal\n\/\/\n\/\/ to use this, pass `typename remove_reference<T>::type` to T.\n\ntemplate<typename T>\nstruct is_string_literal:\ndisjunction<\n std::is_same<const char*, T>,\n conjunction<\n std::is_array<T>,\n std::is_same<const char, typename std::remove_extent<T>::type>\n >\n >{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++20 remove_cvref_t\n\ntemplate<typename T>\nstruct remove_cvref\n{\n using type = typename std::remove_cv<\n typename std::remove_reference<T>::type>::type;\n};\n\ntemplate<typename T>\nusing remove_cvref_t = typename remove_cvref<T>::type;\n\n}\/\/ detail\n}\/\/toml\n#endif \/\/ TOML_TRAITS\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_LINEARFORM\n#define MFEM_LINEARFORM\n\n#include \"..\/config\/config.hpp\"\n#include \"lininteg.hpp\"\n#include \"gridfunc.hpp\"\n\nnamespace mfem\n{\n\n\/\/\/ Class for linear form - Vector with associated FE space and LFIntegrators.\nclass LinearForm : public Vector\n{\nprivate:\n \/\/\/ FE space on which LF lives.\n FiniteElementSpace * fes;\n\n \/\/\/ Set of Domain Integrators to be applied.\n Array<LinearFormIntegrator*> dlfi;\n\n \/\/\/ Separate array for integrators with delta function coefficients.\n Array<DeltaLFIntegrator*> dlfi_delta;\n\n \/\/\/ Set of Boundary Integrators to be applied.\n Array<LinearFormIntegrator*> blfi;\n\n \/\/\/ Set of Boundary Face Integrators to be applied.\n Array<LinearFormIntegrator*> flfi;\n Array<Array<int>*> flfi_marker;\n\n \/\/\/ The element ids where the centers of the delta functions lie\n Array<int> dlfi_delta_elem_id;\n\n \/\/\/ The reference coordinates where the centers of the delta functions lie\n Array<IntegrationPoint> dlfi_delta_ip;\n\n \/\/\/ If true, the delta locations are not (re)computed during assembly.\n bool HaveDeltaLocations() { return (dlfi_delta_elem_id.Size() != 0); }\n\n \/\/\/ Force (re)computation of delta locations.\n void ResetDeltaLocations() { dlfi_delta_elem_id.SetSize(0); }\n\npublic:\n \/\/\/ Creates linear form associated with FE space *f.\n LinearForm (FiniteElementSpace * f) : Vector (f -> GetVSize())\n { fes = f; }\n\n LinearForm() { fes = NULL; }\n\n \/\/\/ (DEPRECATED) Return the FE space associated with the LinearForm.\n \/** @deprecated Use FESpace() instead. *\/\n FiniteElementSpace * GetFES() { return fes; }\n\n \/\/\/ Read+write access to the associated FiniteElementSpace.\n FiniteElementSpace *FESpace() { return fes; }\n \/\/\/ Read-only access to the associated FiniteElementSpace.\n const FiniteElementSpace *FESpace() const { return fes; }\n\n \/\/\/ Adds new Domain Integrator.\n void AddDomainIntegrator (LinearFormIntegrator * lfi);\n\n \/\/\/ Adds new Boundary Integrator.\n void AddBoundaryIntegrator (LinearFormIntegrator * lfi);\n\n \/\/\/ Adds new Boundary Face Integrator.\n void AddBdrFaceIntegrator (LinearFormIntegrator * lfi);\n\n \/** @brief Add new Boundary Face Integrator, restricted to the given boundary\n attributes. *\/\n void AddBdrFaceIntegrator(LinearFormIntegrator *lfi,\n Array<int> &bdr_attr_marker);\n\n \/\/\/ Assembles the linear form i.e. sums over all domain\/bdr integrators.\n void Assemble();\n\n \/\/\/ Assembles delta functions of the linear form\n void AssembleDelta();\n\n void Update() { SetSize(fes->GetVSize()); ResetDeltaLocations(); }\n\n void Update(FiniteElementSpace *f)\n { fes = f; SetSize(f->GetVSize()); ResetDeltaLocations(); }\n\n void Update(FiniteElementSpace *f, Vector &v, int v_offset);\n\n \/\/\/ Return the action of the LinearForm as a linear mapping.\n \/** Linear forms are linear functionals which map GridFunctions to\n the real numbers. This method performs this mapping which in\n this case is equivalent as an inner product of the LinearForm\n and GridFunction. *\/\n double operator()(const GridFunction &gf) const { return (*this)*gf; }\n\n \/\/\/ Destroys linear form.\n ~LinearForm();\n};\n\n}\n\n#endif\n<commit_msg>Adding LinearForm constructor which takes a data array<commit_after>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_LINEARFORM\n#define MFEM_LINEARFORM\n\n#include \"..\/config\/config.hpp\"\n#include \"lininteg.hpp\"\n#include \"gridfunc.hpp\"\n\nnamespace mfem\n{\n\n\/\/\/ Class for linear form - Vector with associated FE space and LFIntegrators.\nclass LinearForm : public Vector\n{\nprivate:\n \/\/\/ FE space on which LF lives.\n FiniteElementSpace * fes;\n\n \/\/\/ Set of Domain Integrators to be applied.\n Array<LinearFormIntegrator*> dlfi;\n\n \/\/\/ Separate array for integrators with delta function coefficients.\n Array<DeltaLFIntegrator*> dlfi_delta;\n\n \/\/\/ Set of Boundary Integrators to be applied.\n Array<LinearFormIntegrator*> blfi;\n\n \/\/\/ Set of Boundary Face Integrators to be applied.\n Array<LinearFormIntegrator*> flfi;\n Array<Array<int>*> flfi_marker;\n\n \/\/\/ The element ids where the centers of the delta functions lie\n Array<int> dlfi_delta_elem_id;\n\n \/\/\/ The reference coordinates where the centers of the delta functions lie\n Array<IntegrationPoint> dlfi_delta_ip;\n\n \/\/\/ If true, the delta locations are not (re)computed during assembly.\n bool HaveDeltaLocations() { return (dlfi_delta_elem_id.Size() != 0); }\n\n \/\/\/ Force (re)computation of delta locations.\n void ResetDeltaLocations() { dlfi_delta_elem_id.SetSize(0); }\n\npublic:\n \/\/\/ Creates linear form associated with FE space *f.\n LinearForm (FiniteElementSpace * f) : Vector (f -> GetVSize())\n { fes = f; }\n\n \/\/\/ Construct a GridFunction using previously allocated array @a data.\n \/** The GridFunction does not assume ownership of @a data which is assumed to\n be of size at least `f->GetVSize()`. Similar to the Vector constructor\n for externally allocated array, the pointer @a data can be NULL. The data\n array can be replaced later using the method SetData().\n *\/\n LinearForm(FiniteElementSpace *f, double *data) : Vector(data, f->GetVSize())\n { fes = f; }\n\n LinearForm() { fes = NULL; }\n\n \/\/\/ (DEPRECATED) Return the FE space associated with the LinearForm.\n \/** @deprecated Use FESpace() instead. *\/\n FiniteElementSpace * GetFES() { return fes; }\n\n \/\/\/ Read+write access to the associated FiniteElementSpace.\n FiniteElementSpace *FESpace() { return fes; }\n \/\/\/ Read-only access to the associated FiniteElementSpace.\n const FiniteElementSpace *FESpace() const { return fes; }\n\n \/\/\/ Adds new Domain Integrator.\n void AddDomainIntegrator (LinearFormIntegrator * lfi);\n\n \/\/\/ Adds new Boundary Integrator.\n void AddBoundaryIntegrator (LinearFormIntegrator * lfi);\n\n \/\/\/ Adds new Boundary Face Integrator.\n void AddBdrFaceIntegrator (LinearFormIntegrator * lfi);\n\n \/** @brief Add new Boundary Face Integrator, restricted to the given boundary\n attributes. *\/\n void AddBdrFaceIntegrator(LinearFormIntegrator *lfi,\n Array<int> &bdr_attr_marker);\n\n \/\/\/ Assembles the linear form i.e. sums over all domain\/bdr integrators.\n void Assemble();\n\n \/\/\/ Assembles delta functions of the linear form\n void AssembleDelta();\n\n void Update() { SetSize(fes->GetVSize()); ResetDeltaLocations(); }\n\n void Update(FiniteElementSpace *f)\n { fes = f; SetSize(f->GetVSize()); ResetDeltaLocations(); }\n\n void Update(FiniteElementSpace *f, Vector &v, int v_offset);\n\n \/\/\/ Return the action of the LinearForm as a linear mapping.\n \/** Linear forms are linear functionals which map GridFunctions to\n the real numbers. This method performs this mapping which in\n this case is equivalent as an inner product of the LinearForm\n and GridFunction. *\/\n double operator()(const GridFunction &gf) const { return (*this)*gf; }\n\n \/\/\/ Destroys linear form.\n ~LinearForm();\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"PID.h\"\n\n\/**\n * A PID Controller is a method of system control in which a correctional output\n * is generated to guide the system toward a desired setpoint (aka target).\n * The PID Controller calculates the output based on the following factors:\n *\n * Gains (proportional, integral, and derivative)\n * Target\n * Feedback\n *\n * The gain values act as multipliers for their corresponding components of PID\n * (more detail later). The target is the value which the system strives to\n * reach by manipulating the output. The feedback is the system's actual\n * position or status in regards to the physical world.\n * Another important term in PID is \"error\", which refers to the difference\n * between the target and the feedback.\n *\n * Each of the three components of PID contributes a unique behavior to the\n * system.\n *\n * The Proportional component introduces a linear relationship between the\n * error (target minus feedback) and the output. This means that as the\n * feedback grows further away from the target, the output grows\n * proportionally stronger.\n *\n * Proportional component = (P Gain) * (target - feedback)\n *\n * The Integral component is designed to give a very precise approach of the\n * feedback to the target. Depending on the scale of the physical system\n * and the precision of feedback (e.g. sensors), the proportional component\n * alone is likely not sufficient to provide adequate power (e.g. to motors)\n * to guide the system in regards to small-scale correction. The Integral\n * component integrates the error of the system (target - feedback) over\n * time. If the system reaches a point where it is close but not exactly\n * on top of the target, the integration will slowly build until it is\n * powerful enough to overcome static resistances and move the system\n * preciesly to the target.\n *\n * Integral component = (I Gain) * Integral of error over time\n *\n * *In this implementation, Integral is calculated with a running\n * summation of the system's error, updated at each tick.\n *\n * The Derivative component measures the rate of change of the feedback.\n * It can reduce the strength of the output if the feedback is approaching\n * the target too quickly or if the feedback is moving away from the target.\n *\n * Derivative component = (D Gain) * ((error - lastError) \/ time - lastTime)\n *\n * The output generated by the PID Controller is the sum of the three\n * components.\n *\n * PID output = Proportional component + Integral component + Derivative component\n *\/\nPIDController::PIDController(double p, double i, double d, int (*pidSource)(), void (*pidOutput)(int output))\n{\n _p = p;\n _i = i;\n _d = d;\n target = 0;\n output = 0;\n currentFeedback = 0;\n lastFeedback = 0;\n lastError = 0;\n currentTime = 0L;\n lastTime = 0L;\n integralCumulation = 0;\n maxCumulation = 30000;\n inputBounded = false;\n outputBounded = false;\n inputLowerBound = 0;\n inputUpperBound = 0;\n outputBounded = false;\n outputLowerBound = 0;\n outputUpperBound = 0;\n timeFunctionRegistered = false;\n _pidSource = pidSource;\n _pidOutput = pidOutput;\n}\n\n\/**\n * This method uses the established function pointers to retrieve system\n * feedback, calculate the PID output, and deliver the correction value\n * to the parent of this PIDController. This method should be run as\n * fast as the source of the feedback in order to provide the highest\n * resolution of control (for example, to be placed in the loop() method).\n *\/\nvoid PIDController::tick()\n{\n \/\/Retrieve system feedback from user callback.\n currentFeedback = _pidSource();\n\n \/\/Apply input bounds if necessary.\n if(inputBounded)\n {\n if(currentFeedback > inputUpperBound) currentFeedback = inputUpperBound;\n if(currentFeedback < inputLowerBound) currentFeedback = inputLowerBound;\n }\n\n \/\/Calculate the error between the feedback and the target.\n error = target - currentFeedback;\n\n \/\/If we have a registered way to retrieve the system time, use time in PID calculations.\n if(timeFunctionRegistered)\n {\n \/\/Retrieve system time\n currentTime = _getSystemTime();\n\n \/\/Calculate time since last tick() cycle.\n long deltaTime = currentTime - lastTime;\n\n \/\/Calculate the integral of the feedback data since last cycle.\n int cycleIntegral = (lastError + error \/ 2) * deltaTime;\n\n \/\/Add this cycle's integral to the integral cumulation.\n integralCumulation += cycleIntegral;\n\n \/\/Calculate the slope of the line with data from the current and last cycles.\n cycleDerivative = (error - lastError) \/ deltaTime;\n\n \/\/Save time data for next iteration.\n lastTime = currentTime;\n }\n \/\/If we have no way to retrieve system time, estimate calculations.\n else\n {\n integralCumulation += error;\n cycleDerivative = (error - lastError);\n }\n\n \/\/Prevent the integral cumulation from becoming overwhelmingly huge.\n if(integralCumulation > maxCumulation) integralCumulation = maxCumulation;\n if(integralCumulation < -maxCumulation) integralCumulation = -maxCumulation;\n\n \/\/Calculate the system output based on data and PID gains.\n output = (int) ((error * _p) + (integralCumulation * _i) + (cycleDerivative * _d));\n\n \/\/Save a record of this iteration's data.\n lastFeedback = currentFeedback;\n lastError = error;\n\n \/\/Trim the output to the bounds if needed.\n if(outputBounded)\n {\n if(output > outputUpperBound) output = outputUpperBound;\n if(output < outputLowerBound) output = outputLowerBound;\n }\n\n _pidOutput(output);\n}\n\n\/**\n * Sets the target of this PIDController. This system will generate\n * correction outputs indended to guide the feedback variable (such\n * as position, velocity, etc.) toward the established target.\n *\/\nvoid PIDController::setTarget(int t)\n{\n target = t;\n}\n\n\/**\n * Returns the current target of this PIDController.\n * @return The current target of this PIDController.\n *\/\nint PIDController::getTarget()\n{\n return target;\n}\n\n\/**\n * Returns the latest output generated by this PIDController. This value is\n * also delivered to the parent systems via the PIDOutput function pointer\n * provided in the constructor of this PIDController.\n * @return The latest output generated by this PIDController.\n *\/\nint PIDController::getOutput()\n{\n return output;\n}\n\n\/**\n * Returns the last read feedback of this PIDController.\n *\/\nint PIDController::getFeedback()\n{\n return currentFeedback;\n}\n\n\/**\n * Returns the value that the Proportional component is contributing to the output.\n * @return The value that the Proportional component is contributing to the output.\n *\/\nint PIDController::getProportionalComponent()\n{\n return (int) (error * _p);\n}\n\n\/**\n * Returns the value that the Integral component is contributing to the output.\n * @return The value that the Integral component is contributing to the output.\n *\/\nint PIDController::getIntegralComponent()\n{\n return (int) (integralCumulation * _i);\n}\n\n\/**\n * Returns the value that the Derivative component is contributing to the output.\n * @return The value that the Derivative component is contributing to the output.\n *\/\nint PIDController::getDerivativeComponent()\n{\n return (int) (cycleDerivative * _d);\n}\n\n\/**\n * Sets the maximum value that the integral cumulation can reach.\n * @param max The maximum value of the integral cumulation.\n *\/\nvoid PIDController::setMaxIntegralCumulation(int max)\n{\n \/\/If the new max value is less than 0, invert to make positive.\n if(max < 0)\n {\n max = -max;\n }\n\n \/\/If the new max is not more than 1 then the cumulation is useless.\n if(max > 1)\n {\n maxCumulation = max;\n }\n}\n\n\/**\n * Returns the maximum value that the integral value can cumulate to.\n * @return The maximum value that the integral value can cumulate to.\n *\/\nint PIDController::getMaxIntegralCumulation()\n{\n return maxCumulation;\n}\n\n\/**\n * Returns the current cumulative integral value in this PIDController.\n * @return The current cumulative integral value in this PIDController.\n *\/\nint PIDController::getIntegralCumulation()\n{\n return integralCumulation;\n}\n\n\/**\n * Enables or disables bounds on the input. Bounds limit the upper and\n * lower values that this PIDController will ever accept as input.\n * Outlying values will be trimmed to the upper or lower bound as necessary.\n * @param bounded True to enable input bounds, False to disable.\n *\/\nvoid PIDController::setInputBounded(bool bounded)\n{\n inputBounded = bounded;\n}\n\n\/**\n * Enables or disables bounds on the output. Bounds limit the upper and lower\n * values that this PIDController will ever generate as output.\n * @param bounded True to enable output bounds, False to disable.\n *\/\nvoid PIDController::setOutputBounded(bool bounded)\n{\n outputBounded = bounded;\n}\n\n\/**\n * Returns whether the input of this PIDController is being bounded.\n * @return True if the input of this PIDController is being bounded.\n *\/\nbool PIDController::isInputBounded()\n{\n return inputBounded;\n}\n\n\/**\n * Returns whether the output of this PIDController is being bounded.\n * @return True if the output of this PIDController is being bounded.\n *\/\nbool PIDController::isOutputBounded()\n{\n return outputBounded;\n}\n\n\/**\n * Sets bounds which limit the lower and upper extremes that this PIDController\n * accepts as inputs. Outliers are trimmed to the lower and upper bounds.\n * Setting input bounds automatically enables input bounds.\n * @param lower The lower input bound.\n * @param upper The upper input bound.\n *\/\nvoid PIDController::setInputBounds(int lower, int upper)\n{\n if(upper > lower)\n {\n inputBounded = true;\n inputUpperBound = upper;\n inputLowerBound = lower;\n }\n}\n\n\/**\n * Sets bounds which limit the lower and upper extremes that this PIDController\n * will ever generate as output. Setting output bounds automatically enables\n * output bounds.\n * @param lower The lower output bound.\n * @param upper The upper output bound.\n *\/\nvoid PIDController::setOutputBounds(int lower, int upper)\n{\n if(upper > lower)\n {\n outputBounded = true;\n outputLowerBound = lower;\n outputUpperBound = upper;\n }\n}\n\n\/**\n * Returns the lower input bound of this PIDController.\n * @return The lower input bound of this PIDController.\n *\/\nint PIDController::getInputLowerBound()\n{\n return inputLowerBound;\n}\n\n\/**\n * Returns the upper input bound of this PIDController.\n * @return The upper input bound of this PIDController.\n *\/\nint PIDController::getInputUpperBound()\n{\n return inputUpperBound;\n}\n\n\/**\n * Returns the lower output bound of this PIDController.\n * @return The lower output bound of this PIDController.\n *\/\nint PIDController::getOutputLowerBound()\n{\n return outputLowerBound;\n}\n\n\/**\n * Returns the upper output bound of this PIDController.\n * @return The upper output bound of this PIDController.\n *\/\nint PIDController::getOutputUpperBound()\n{\n return outputUpperBound;\n}\n\n\/**\n * Sets new values for all PID Gains.\n * @param p The new proportional gain.\n * @param i The new integral gain.\n * @param d The new derivative gain.\n *\/\nvoid PIDController::setPID(double p, double i, double d)\n{\n _p = p;\n _i = i;\n _d = d;\n}\n\n\/**\n * Sets a new value for the proportional gain.\n * @param p The new proportional gain.\n *\/\nvoid PIDController::setP(double p)\n{\n _p = p;\n}\n\n\/**\n * Sets a new value for the integral gain.\n * @param i The new integral gain.\n *\/\nvoid PIDController::setI(double i)\n{\n _i = i;\n}\n\n\/**\n * Sets a new value for the derivative gain.\n * @param d The new derivative gain.\n *\/\nvoid PIDController::setD(double d)\n{\n _d = d;\n}\n\n\/**\n * Returns the proportional gain.\n * @return The proportional gain.\n *\/\ndouble PIDController::getP()\n{\n return _p;\n}\n\n\/**\n * Returns the integral gain.\n * @return The integral gain.\n *\/\ndouble PIDController::getI()\n{\n return _i;\n}\n\n\/**\n * Returns the derivative gain.\n * @return The derivative gain.\n *\/\ndouble PIDController::getD()\n{\n return _d;\n}\n\n\/**\n * Sets the function pointer to the PID Source. A PID Source\n * is a function which returns a value to be used as the PIDController's\n * control feedback. This value can be a reading from a sensor or other\n * data source that contains information regarding the system's actual\n * state.\n * Below is an example of using a PIDSource:\n *\n * int pidSource()\n * {\n * return mySensor.getValue();\n * }\n * myPIDController.setPIDSource(pidSource);\n *\n * @param (*getFeedback) A function pointer that retrieves system feedback.\n *\/\nvoid PIDController::setPIDSource(int (*pidSource)())\n{\n _pidSource = pidSource;\n}\n\n\/**\n * Sets the function pointer to the PID Output. A PID Output\n * is a function which delivers a value to the parent system in order to guide\n * the system based on the PID loop's result. This value can be delivered\n * directly to motors, to a variable that directs steering, or other means of\n * influencing the system.\n * Below is an example of using a PIDOutput:\n *\n * void pidOutput(int output)\n * {\n * myMotor.write(output);\n * }\n * myPIDController.setPIDOutput(pidOutput);\n *\n * @param (*onUpdate) A function pointer that delivers system output.\n *\/\nvoid PIDController::setPIDOutput(void (*pidOutput)(int output))\n{\n _pidOutput = pidOutput;\n}\n\n\/**\n * Use this to add a hook into the PID Controller that allows it to\n * read the system time no matter what platform this library is run\n * on. Though developed for an arduino project, there is no code\n * tying this library to the arduino project. To use the arduino\n * clock, however, register the time-getting function (millis())\n * like this:\n *\n * myPIDController.registerTimeInput(millis);\n * *Note that in this example, millis has no parentheses.\n *\n * @param (*getSystemTime) Pointer to a function that returns system time.\n *\/\nvoid PIDController::registerTimeFunction(unsigned long (*getSystemTime)())\n{\n _getSystemTime = getSystemTime;\n timeFunctionRegistered = true;\n}\n<commit_msg>Added author and moved intro doc above include<commit_after>\/**\n * @author Nick Mosher, <codewhisperer97@gmail.com>\n *\n * A PID Controller is a method of system control in which a correctional output\n * is generated to guide the system toward a desired setpoint (aka target).\n * The PID Controller calculates the output based on the following factors:\n *\n * Gains (proportional, integral, and derivative)\n * Target\n * Feedback\n *\n * The gain values act as multipliers for their corresponding components of PID\n * (more detail later). The target is the value which the system strives to\n * reach by manipulating the output. The feedback is the system's actual\n * position or status in regards to the physical world.\n * Another important term in PID is \"error\", which refers to the difference\n * between the target and the feedback.\n *\n * Each of the three components of PID contributes a unique behavior to the\n * system.\n *\n * The Proportional component introduces a linear relationship between the\n * error (target minus feedback) and the output. This means that as the\n * feedback grows further away from the target, the output grows\n * proportionally stronger.\n *\n * Proportional component = (P Gain) * (target - feedback)\n *\n * The Integral component is designed to give a very precise approach of the\n * feedback to the target. Depending on the scale of the physical system\n * and the precision of feedback (e.g. sensors), the proportional component\n * alone is likely not sufficient to provide adequate power (e.g. to motors)\n * to guide the system in regards to small-scale corrections. The Integral\n * component integrates the error of the system (target - feedback) over\n * time. If the system reaches a point where it is close but not exactly\n * on top of the target, the integration will slowly build until it is\n * powerful enough to overcome static resistances and move the system\n * preciesly to the target.\n *\n * Integral component = (I Gain) * Integral of error over time\n *\n * *In this implementation, Integral is calculated with a running\n * summation of the system's error, updated at each tick.\n *\n * The Derivative component measures the rate of change of the feedback.\n * It can reduce the strength of the output if the feedback is approaching\n * the target too quickly or if the feedback is moving away from the target.\n *\n * Derivative component = (D Gain) * ((error - lastError) \/ time - lastTime)\n *\n * The output generated by the PID Controller is the sum of the three\n * components.\n *\n * PID output = Proportional component + Integral component + Derivative component\n *\/\n\n#include \"PID.h\"\n\n\/**\n * Constructs the PIDController object with PID Gains and function pointers\n * for retrieving feedback (pidSource) and delivering output (pidOutput).\n * All PID gains should be positive, otherwise the system will violently diverge\n * from the target.\n * @param p The Proportional gain.\n * @param i The Integral gain.\n * @param d The Derivative gain.\n * @param (*pidSource) The function pointer for retrieving system feedback.\n * @param (*pidOutput) The function pointer for delivering system output.\n *\/\nPIDController::PIDController(double p, double i, double d, int (*pidSource)(), void (*pidOutput)(int output))\n{\n _p = p;\n _i = i;\n _d = d;\n target = 0;\n output = 0;\n currentFeedback = 0;\n lastFeedback = 0;\n lastError = 0;\n currentTime = 0L;\n lastTime = 0L;\n integralCumulation = 0;\n maxCumulation = 30000;\n inputBounded = false;\n outputBounded = false;\n inputLowerBound = 0;\n inputUpperBound = 0;\n outputBounded = false;\n outputLowerBound = 0;\n outputUpperBound = 0;\n timeFunctionRegistered = false;\n _pidSource = pidSource;\n _pidOutput = pidOutput;\n}\n\n\/**\n * This method uses the established function pointers to retrieve system\n * feedback, calculate the PID output, and deliver the correction value\n * to the parent of this PIDController. This method should be run as\n * fast as the source of the feedback in order to provide the highest\n * resolution of control (for example, to be placed in the loop() method).\n *\/\nvoid PIDController::tick()\n{\n \/\/Retrieve system feedback from user callback.\n currentFeedback = _pidSource();\n\n \/\/Apply input bounds if necessary.\n if(inputBounded)\n {\n if(currentFeedback > inputUpperBound) currentFeedback = inputUpperBound;\n if(currentFeedback < inputLowerBound) currentFeedback = inputLowerBound;\n }\n\n \/\/Calculate the error between the feedback and the target.\n error = target - currentFeedback;\n\n \/\/If we have a registered way to retrieve the system time, use time in PID calculations.\n if(timeFunctionRegistered)\n {\n \/\/Retrieve system time\n currentTime = _getSystemTime();\n\n \/\/Calculate time since last tick() cycle.\n long deltaTime = currentTime - lastTime;\n\n \/\/Calculate the integral of the feedback data since last cycle.\n int cycleIntegral = (lastError + error \/ 2) * deltaTime;\n\n \/\/Add this cycle's integral to the integral cumulation.\n integralCumulation += cycleIntegral;\n\n \/\/Calculate the slope of the line with data from the current and last cycles.\n cycleDerivative = (error - lastError) \/ deltaTime;\n\n \/\/Save time data for next iteration.\n lastTime = currentTime;\n }\n \/\/If we have no way to retrieve system time, estimate calculations.\n else\n {\n integralCumulation += error;\n cycleDerivative = (error - lastError);\n }\n\n \/\/Prevent the integral cumulation from becoming overwhelmingly huge.\n if(integralCumulation > maxCumulation) integralCumulation = maxCumulation;\n if(integralCumulation < -maxCumulation) integralCumulation = -maxCumulation;\n\n \/\/Calculate the system output based on data and PID gains.\n output = (int) ((error * _p) + (integralCumulation * _i) + (cycleDerivative * _d));\n\n \/\/Save a record of this iteration's data.\n lastFeedback = currentFeedback;\n lastError = error;\n\n \/\/Trim the output to the bounds if needed.\n if(outputBounded)\n {\n if(output > outputUpperBound) output = outputUpperBound;\n if(output < outputLowerBound) output = outputLowerBound;\n }\n\n _pidOutput(output);\n}\n\n\/**\n * Sets the target of this PIDController. This system will generate\n * correction outputs indended to guide the feedback variable (such\n * as position, velocity, etc.) toward the established target.\n *\/\nvoid PIDController::setTarget(int t)\n{\n target = t;\n}\n\n\/**\n * Returns the current target of this PIDController.\n * @return The current target of this PIDController.\n *\/\nint PIDController::getTarget()\n{\n return target;\n}\n\n\/**\n * Returns the latest output generated by this PIDController. This value is\n * also delivered to the parent systems via the PIDOutput function pointer\n * provided in the constructor of this PIDController.\n * @return The latest output generated by this PIDController.\n *\/\nint PIDController::getOutput()\n{\n return output;\n}\n\n\/**\n * Returns the last read feedback of this PIDController.\n *\/\nint PIDController::getFeedback()\n{\n return currentFeedback;\n}\n\n\/**\n * Returns the value that the Proportional component is contributing to the output.\n * @return The value that the Proportional component is contributing to the output.\n *\/\nint PIDController::getProportionalComponent()\n{\n return (int) (error * _p);\n}\n\n\/**\n * Returns the value that the Integral component is contributing to the output.\n * @return The value that the Integral component is contributing to the output.\n *\/\nint PIDController::getIntegralComponent()\n{\n return (int) (integralCumulation * _i);\n}\n\n\/**\n * Returns the value that the Derivative component is contributing to the output.\n * @return The value that the Derivative component is contributing to the output.\n *\/\nint PIDController::getDerivativeComponent()\n{\n return (int) (cycleDerivative * _d);\n}\n\n\/**\n * Sets the maximum value that the integral cumulation can reach.\n * @param max The maximum value of the integral cumulation.\n *\/\nvoid PIDController::setMaxIntegralCumulation(int max)\n{\n \/\/If the new max value is less than 0, invert to make positive.\n if(max < 0)\n {\n max = -max;\n }\n\n \/\/If the new max is not more than 1 then the cumulation is useless.\n if(max > 1)\n {\n maxCumulation = max;\n }\n}\n\n\/**\n * Returns the maximum value that the integral value can cumulate to.\n * @return The maximum value that the integral value can cumulate to.\n *\/\nint PIDController::getMaxIntegralCumulation()\n{\n return maxCumulation;\n}\n\n\/**\n * Returns the current cumulative integral value in this PIDController.\n * @return The current cumulative integral value in this PIDController.\n *\/\nint PIDController::getIntegralCumulation()\n{\n return integralCumulation;\n}\n\n\/**\n * Enables or disables bounds on the input. Bounds limit the upper and\n * lower values that this PIDController will ever accept as input.\n * Outlying values will be trimmed to the upper or lower bound as necessary.\n * @param bounded True to enable input bounds, False to disable.\n *\/\nvoid PIDController::setInputBounded(bool bounded)\n{\n inputBounded = bounded;\n}\n\n\/**\n * Enables or disables bounds on the output. Bounds limit the upper and lower\n * values that this PIDController will ever generate as output.\n * @param bounded True to enable output bounds, False to disable.\n *\/\nvoid PIDController::setOutputBounded(bool bounded)\n{\n outputBounded = bounded;\n}\n\n\/**\n * Returns whether the input of this PIDController is being bounded.\n * @return True if the input of this PIDController is being bounded.\n *\/\nbool PIDController::isInputBounded()\n{\n return inputBounded;\n}\n\n\/**\n * Returns whether the output of this PIDController is being bounded.\n * @return True if the output of this PIDController is being bounded.\n *\/\nbool PIDController::isOutputBounded()\n{\n return outputBounded;\n}\n\n\/**\n * Sets bounds which limit the lower and upper extremes that this PIDController\n * accepts as inputs. Outliers are trimmed to the lower and upper bounds.\n * Setting input bounds automatically enables input bounds.\n * @param lower The lower input bound.\n * @param upper The upper input bound.\n *\/\nvoid PIDController::setInputBounds(int lower, int upper)\n{\n if(upper > lower)\n {\n inputBounded = true;\n inputUpperBound = upper;\n inputLowerBound = lower;\n }\n}\n\n\/**\n * Sets bounds which limit the lower and upper extremes that this PIDController\n * will ever generate as output. Setting output bounds automatically enables\n * output bounds.\n * @param lower The lower output bound.\n * @param upper The upper output bound.\n *\/\nvoid PIDController::setOutputBounds(int lower, int upper)\n{\n if(upper > lower)\n {\n outputBounded = true;\n outputLowerBound = lower;\n outputUpperBound = upper;\n }\n}\n\n\/**\n * Returns the lower input bound of this PIDController.\n * @return The lower input bound of this PIDController.\n *\/\nint PIDController::getInputLowerBound()\n{\n return inputLowerBound;\n}\n\n\/**\n * Returns the upper input bound of this PIDController.\n * @return The upper input bound of this PIDController.\n *\/\nint PIDController::getInputUpperBound()\n{\n return inputUpperBound;\n}\n\n\/**\n * Returns the lower output bound of this PIDController.\n * @return The lower output bound of this PIDController.\n *\/\nint PIDController::getOutputLowerBound()\n{\n return outputLowerBound;\n}\n\n\/**\n * Returns the upper output bound of this PIDController.\n * @return The upper output bound of this PIDController.\n *\/\nint PIDController::getOutputUpperBound()\n{\n return outputUpperBound;\n}\n\n\/**\n * Sets new values for all PID Gains.\n * @param p The new proportional gain.\n * @param i The new integral gain.\n * @param d The new derivative gain.\n *\/\nvoid PIDController::setPID(double p, double i, double d)\n{\n _p = p;\n _i = i;\n _d = d;\n}\n\n\/**\n * Sets a new value for the proportional gain.\n * @param p The new proportional gain.\n *\/\nvoid PIDController::setP(double p)\n{\n _p = p;\n}\n\n\/**\n * Sets a new value for the integral gain.\n * @param i The new integral gain.\n *\/\nvoid PIDController::setI(double i)\n{\n _i = i;\n}\n\n\/**\n * Sets a new value for the derivative gain.\n * @param d The new derivative gain.\n *\/\nvoid PIDController::setD(double d)\n{\n _d = d;\n}\n\n\/**\n * Returns the proportional gain.\n * @return The proportional gain.\n *\/\ndouble PIDController::getP()\n{\n return _p;\n}\n\n\/**\n * Returns the integral gain.\n * @return The integral gain.\n *\/\ndouble PIDController::getI()\n{\n return _i;\n}\n\n\/**\n * Returns the derivative gain.\n * @return The derivative gain.\n *\/\ndouble PIDController::getD()\n{\n return _d;\n}\n\n\/**\n * Sets the function pointer to the PID Source. A PID Source\n * is a function which returns a value to be used as the PIDController's\n * control feedback. This value can be a reading from a sensor or other\n * data source that contains information regarding the system's actual\n * state.\n * Below is an example of using a PIDSource:\n *\n * int pidSource()\n * {\n * return mySensor.getValue();\n * }\n * myPIDController.setPIDSource(pidSource);\n *\n * @param (*getFeedback) A function pointer that retrieves system feedback.\n *\/\nvoid PIDController::setPIDSource(int (*pidSource)())\n{\n _pidSource = pidSource;\n}\n\n\/**\n * Sets the function pointer to the PID Output. A PID Output\n * is a function which delivers a value to the parent system in order to guide\n * the system based on the PID loop's result. This value can be delivered\n * directly to motors, to a variable that directs steering, or other means of\n * influencing the system.\n * Below is an example of using a PIDOutput:\n *\n * void pidOutput(int output)\n * {\n * myMotor.write(output);\n * }\n * myPIDController.setPIDOutput(pidOutput);\n *\n * @param (*onUpdate) A function pointer that delivers system output.\n *\/\nvoid PIDController::setPIDOutput(void (*pidOutput)(int output))\n{\n _pidOutput = pidOutput;\n}\n\n\/**\n * Use this to add a hook into the PID Controller that allows it to\n * read the system time no matter what platform this library is run\n * on. Though developed for an arduino project, there is no code\n * tying this library to the arduino project. To use the arduino\n * clock, however, register the time-getting function (millis())\n * like this:\n *\n * myPIDController.registerTimeInput(millis);\n * *Note that in this example, millis has no parentheses.\n *\n * @param (*getSystemTime) Pointer to a function that returns system time.\n *\/\nvoid PIDController::registerTimeFunction(unsigned long (*getSystemTime)())\n{\n _getSystemTime = getSystemTime;\n timeFunctionRegistered = true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include <cstring>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"caffe\/caffe.hpp\"\n\nusing caffe::Blob;\nusing caffe::Caffe;\nusing caffe::Net;\nusing caffe::Layer;\nusing caffe::shared_ptr;\nusing caffe::Timer;\nusing caffe::vector;\n\n\n\/\/ Used in device query\nDEFINE_int32(device_id, 0,\n \"[device_query,time] The device id to use.\");\n\/\/ Used in training\nDEFINE_string(solver_proto_file, \"\",\n \"[train] The protobuf containing the solver definition.\");\nDEFINE_string(net_proto_file, \"\",\n \"[time] The net proto file to use.\");\nDEFINE_string(resume_point_file, \"\",\n \"[train] (optional) The snapshot from which to resume training.\");\nDEFINE_string(pretrained_net_file, \"\",\n \"[train] (optional) A pretrained network to run finetune from. \"\n \"Cannot be set simultaneously with resume_point_file.\");\nDEFINE_int32(run_iterations, 50,\n \"[time] The number of iterations to run.\");\nDEFINE_bool(time_with_gpu, false,\n \"[time] Test the model with GPU.\");\n\n\/\/ A simple registry for caffe commands.\ntypedef int (*BrewFunction)();\ntypedef std::map<caffe::string, BrewFunction> BrewMap;\nBrewMap g_brew_map;\n\n#define RegisterBrewFunction(func) \\\nnamespace { \\\nclass __Registerer_##func { \\\n public: \/* NOLINT *\/ \\\n __Registerer_##func() { \\\n g_brew_map[#func] = &func; \\\n } \\\n}; \\\n__Registerer_##func g_registerer_##func; \\\n}\n\nstatic BrewFunction GetBrewFunction(const caffe::string& name) {\n if (g_brew_map.count(name)) {\n return g_brew_map[name];\n } else {\n LOG(ERROR) << \"Available caffe actions:\";\n for (BrewMap::iterator it = g_brew_map.begin();\n it != g_brew_map.end(); ++it) {\n LOG(ERROR) << \"\\t\" << it->first;\n }\n LOG(FATAL) << \"Unknown action: \" << name;\n return NULL; \/\/ not reachable, just to suppress old compiler warnings.\n }\n}\n\n\/\/ caffe actions that could be called in the form\n\/\/ caffe.bin action\n\/\/ To do so, define actions as \"int action()\" functions, and register it with\n\/\/ RegisterBrewFunction(action);\n\nint device_query() {\n LOG(INFO) << \"Querying device_id = \" << FLAGS_device_id;\n caffe::Caffe::SetDevice(FLAGS_device_id);\n caffe::Caffe::DeviceQuery();\n return 0;\n}\nRegisterBrewFunction(device_query);\n\nint train() {\n CHECK_GT(FLAGS_solver_proto_file.size(), 0);\n\n caffe::SolverParameter solver_param;\n caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);\n\n LOG(INFO) << \"Starting Optimization\";\n caffe::SGDSolver<float> solver(solver_param);\n if (FLAGS_resume_point_file.size()) {\n LOG(INFO) << \"Resuming from \" << FLAGS_resume_point_file;\n solver.Solve(FLAGS_resume_point_file);\n } else if (FLAGS_pretrained_net_file.size()) {\n LOG(INFO) << \"Finetuning from \" << FLAGS_pretrained_net_file;\n solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);\n solver.Solve();\n } else {\n solver.Solve();\n }\n LOG(INFO) << \"Optimization Done.\";\n return 0;\n}\nRegisterBrewFunction(train);\n\nint time() {\n \/\/ Set device id and mode\n if (FLAGS_time_with_gpu) {\n LOG(INFO) << \"Use GPU with device id \" << FLAGS_device_id;\n Caffe::SetDevice(FLAGS_device_id);\n Caffe::set_mode(Caffe::GPU);\n } else {\n LOG(INFO) << \"Use CPU.\";\n Caffe::set_mode(Caffe::CPU);\n }\n \/\/ Instantiate the caffe net.\n Caffe::set_phase(Caffe::TRAIN);\n Net<float> caffe_net(FLAGS_net_proto_file);\n\n \/\/ Do a clean forward and backward pass, so that memory allocation are done\n \/\/ and future iterations will be more stable.\n LOG(INFO) << \"Performing Forward\";\n \/\/ Note that for the speed benchmark, we will assume that the network does\n \/\/ not take any input blobs.\n float initial_loss;\n caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);\n LOG(INFO) << \"Initial loss: \" << initial_loss;\n LOG(INFO) << \"Performing Backward\";\n caffe_net.Backward();\n\n const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();\n vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();\n vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();\n const vector<vector<bool> >& bottom_need_backward =\n caffe_net.bottom_need_backward();\n LOG(INFO) << \"*** Benchmark begins ***\";\n LOG(INFO) << \"Testing for \" << FLAGS_run_iterations << \" iterations.\";\n Timer total_timer;\n total_timer.Start();\n Timer forward_timer;\n forward_timer.Start();\n Timer timer;\n for (int i = 0; i < layers.size(); ++i) {\n const caffe::string& layername = layers[i]->layer_param().name();\n timer.Start();\n for (int j = 0; j < FLAGS_run_iterations; ++j) {\n layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);\n }\n LOG(INFO) << layername << \"\\tforward: \" << timer.MilliSeconds() <<\n \" milli seconds.\";\n }\n LOG(INFO) << \"Forward pass: \" << forward_timer.MilliSeconds() <<\n \" milli seconds.\";\n Timer backward_timer;\n backward_timer.Start();\n for (int i = layers.size() - 1; i >= 0; --i) {\n const caffe::string& layername = layers[i]->layer_param().name();\n timer.Start();\n for (int j = 0; j < FLAGS_run_iterations; ++j) {\n layers[i]->Backward(top_vecs[i], bottom_need_backward[i],\n &bottom_vecs[i]);\n }\n LOG(INFO) << layername << \"\\tbackward: \"\n << timer.MilliSeconds() << \" milli seconds.\";\n }\n LOG(INFO) << \"Backward pass: \" << backward_timer.MilliSeconds() <<\n \" milli seconds.\";\n LOG(INFO) << \"Total Time: \" << total_timer.MilliSeconds() <<\n \" milli seconds.\";\n LOG(INFO) << \"*** Benchmark ends ***\";\n return 0;\n}\nRegisterBrewFunction(time);\n\nint main(int argc, char** argv) {\n caffe::GlobalInit(&argc, &argv);\n CHECK_EQ(argc, 2);\n return GetBrewFunction(caffe::string(argv[1]))();\n}\n<commit_msg>consolidaet GPU flag for caffe cli<commit_after>#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include <cstring>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"caffe\/caffe.hpp\"\n\nusing caffe::Blob;\nusing caffe::Caffe;\nusing caffe::Net;\nusing caffe::Layer;\nusing caffe::shared_ptr;\nusing caffe::Timer;\nusing caffe::vector;\n\n\n\/\/ Used in device query\nDEFINE_int32(device_id, 0,\n \"[device_query,time] The device id to use.\");\n\/\/ Used in training\nDEFINE_string(solver_proto_file, \"\",\n \"[train] The protobuf containing the solver definition.\");\nDEFINE_string(net_proto_file, \"\",\n \"[time] The net proto file to use.\");\nDEFINE_string(resume_point_file, \"\",\n \"[train] (optional) The snapshot from which to resume training.\");\nDEFINE_string(pretrained_net_file, \"\",\n \"[train] (optional) A pretrained network to run finetune from. \"\n \"Cannot be set simultaneously with resume_point_file.\");\nDEFINE_int32(run_iterations, 50,\n \"[time] The number of iterations to run.\");\nDEFINE_bool(gpu, false,\n \"[time] Run in GPU mode when true.\");\n\n\/\/ A simple registry for caffe commands.\ntypedef int (*BrewFunction)();\ntypedef std::map<caffe::string, BrewFunction> BrewMap;\nBrewMap g_brew_map;\n\n#define RegisterBrewFunction(func) \\\nnamespace { \\\nclass __Registerer_##func { \\\n public: \/* NOLINT *\/ \\\n __Registerer_##func() { \\\n g_brew_map[#func] = &func; \\\n } \\\n}; \\\n__Registerer_##func g_registerer_##func; \\\n}\n\nstatic BrewFunction GetBrewFunction(const caffe::string& name) {\n if (g_brew_map.count(name)) {\n return g_brew_map[name];\n } else {\n LOG(ERROR) << \"Available caffe actions:\";\n for (BrewMap::iterator it = g_brew_map.begin();\n it != g_brew_map.end(); ++it) {\n LOG(ERROR) << \"\\t\" << it->first;\n }\n LOG(FATAL) << \"Unknown action: \" << name;\n return NULL; \/\/ not reachable, just to suppress old compiler warnings.\n }\n}\n\n\/\/ caffe actions that could be called in the form\n\/\/ caffe.bin action\n\/\/ To do so, define actions as \"int action()\" functions, and register it with\n\/\/ RegisterBrewFunction(action);\n\nint device_query() {\n LOG(INFO) << \"Querying device_id = \" << FLAGS_device_id;\n caffe::Caffe::SetDevice(FLAGS_device_id);\n caffe::Caffe::DeviceQuery();\n return 0;\n}\nRegisterBrewFunction(device_query);\n\nint train() {\n CHECK_GT(FLAGS_solver_proto_file.size(), 0);\n\n caffe::SolverParameter solver_param;\n caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);\n\n LOG(INFO) << \"Starting Optimization\";\n caffe::SGDSolver<float> solver(solver_param);\n if (FLAGS_resume_point_file.size()) {\n LOG(INFO) << \"Resuming from \" << FLAGS_resume_point_file;\n solver.Solve(FLAGS_resume_point_file);\n } else if (FLAGS_pretrained_net_file.size()) {\n LOG(INFO) << \"Finetuning from \" << FLAGS_pretrained_net_file;\n solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);\n solver.Solve();\n } else {\n solver.Solve();\n }\n LOG(INFO) << \"Optimization Done.\";\n return 0;\n}\nRegisterBrewFunction(train);\n\nint time() {\n \/\/ Set device id and mode\n if (FLAGS_gpu) {\n LOG(INFO) << \"Use GPU with device id \" << FLAGS_device_id;\n Caffe::SetDevice(FLAGS_device_id);\n Caffe::set_mode(Caffe::GPU);\n } else {\n LOG(INFO) << \"Use CPU.\";\n Caffe::set_mode(Caffe::CPU);\n }\n \/\/ Instantiate the caffe net.\n Caffe::set_phase(Caffe::TRAIN);\n Net<float> caffe_net(FLAGS_net_proto_file);\n\n \/\/ Do a clean forward and backward pass, so that memory allocation are done\n \/\/ and future iterations will be more stable.\n LOG(INFO) << \"Performing Forward\";\n \/\/ Note that for the speed benchmark, we will assume that the network does\n \/\/ not take any input blobs.\n float initial_loss;\n caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);\n LOG(INFO) << \"Initial loss: \" << initial_loss;\n LOG(INFO) << \"Performing Backward\";\n caffe_net.Backward();\n\n const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();\n vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();\n vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();\n const vector<vector<bool> >& bottom_need_backward =\n caffe_net.bottom_need_backward();\n LOG(INFO) << \"*** Benchmark begins ***\";\n LOG(INFO) << \"Testing for \" << FLAGS_run_iterations << \" iterations.\";\n Timer total_timer;\n total_timer.Start();\n Timer forward_timer;\n forward_timer.Start();\n Timer timer;\n for (int i = 0; i < layers.size(); ++i) {\n const caffe::string& layername = layers[i]->layer_param().name();\n timer.Start();\n for (int j = 0; j < FLAGS_run_iterations; ++j) {\n layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);\n }\n LOG(INFO) << layername << \"\\tforward: \" << timer.MilliSeconds() <<\n \" milli seconds.\";\n }\n LOG(INFO) << \"Forward pass: \" << forward_timer.MilliSeconds() <<\n \" milli seconds.\";\n Timer backward_timer;\n backward_timer.Start();\n for (int i = layers.size() - 1; i >= 0; --i) {\n const caffe::string& layername = layers[i]->layer_param().name();\n timer.Start();\n for (int j = 0; j < FLAGS_run_iterations; ++j) {\n layers[i]->Backward(top_vecs[i], bottom_need_backward[i],\n &bottom_vecs[i]);\n }\n LOG(INFO) << layername << \"\\tbackward: \"\n << timer.MilliSeconds() << \" milli seconds.\";\n }\n LOG(INFO) << \"Backward pass: \" << backward_timer.MilliSeconds() <<\n \" milli seconds.\";\n LOG(INFO) << \"Total Time: \" << total_timer.MilliSeconds() <<\n \" milli seconds.\";\n LOG(INFO) << \"*** Benchmark ends ***\";\n return 0;\n}\nRegisterBrewFunction(time);\n\nint main(int argc, char** argv) {\n caffe::GlobalInit(&argc, &argv);\n CHECK_EQ(argc, 2);\n return GetBrewFunction(caffe::string(argv[1]))();\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n \n TTL2C - LV2 Port Enum Generator\n\n This program reads an RDF file (in the Turtle syntax) describing\n an LV2 plugin and generates a C header file with data structures\n that contain information about the plugin.\n \n Copyright (C) 2006-2007 Lars Luthman <lars.luthman@gmail.com>\n \n Modified 2012 Michael Fisher <mfisher31@gmail.com>\n - renamed to ttl2c to avoid conflict with lv2-c++-tools\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; either version 3 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. 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, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA\n\n****************************************************************************\/\n\n#include <cfloat>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"turtleparser.hpp\"\n#include \"query.hpp\"\n#include \"namespaces.hpp\"\n\n#ifndef VERSION\n#define VERSION \"UNKNOWNVERSION\"\n#endif\n\n\nusing namespace std;\nusing namespace PAQ;\n\n\nstruct PortInfo {\n PortInfo() \n : min(-FLT_MAX), \n max(FLT_MAX), \n default_value(min),\n toggled(false),\n integer(false),\n logarithmic(false) { }\n string name;\n float min;\n float max;\n float default_value;\n bool toggled;\n bool integer;\n bool logarithmic;\n};\n\n\nint main(int argc, char** argv) {\n \n for (int i = 1; i < argc; ++i) {\n if (string(argv[i]) == \"-V\" || string(argv[i]) == \"--version\") {\n cout<<\"ttl2c \"<<VERSION<<\" by Lars Luthman <lars.luthman@gmail.com>\"\n <<endl;\n return 0;\n }\n }\n \n if (argc < 3) {\n cerr<<\"Usage: ttl2c <input file> <output file> \"<<endl;\n return -1;\n }\n \n \/\/ parse turtle file\n TurtleParser tp;\n RDFData data;\n if (!tp.parse_ttl_file(argv[1], data)) {\n cerr<<\"Could not parse input. Not valid Turtle syntax.\"<<endl;\n return -1;\n }\n \n \/\/ find all plugins in the file\n Namespace lv2(\"<http:\/\/lv2plug.in\/ns\/lv2core#>\");\n Namespace cx(\"<http:\/\/ll-plugins.nongnu.org\/lv2\/dev\/contexts\/1#>\");\n Namespace ll(\"<http:\/\/ll-plugins.nongnu.org\/lv2\/namespace#>\");\n Variable plugin, pegname;\n vector<QueryResult> qr =\n select(plugin, pegname)\n .where(plugin, ll(\"pegName\"), pegname)\n .where(plugin, rdf(\"type\"), lv2(\"Plugin\"))\n .run(data);\n map<string, string> plugins;\n for (unsigned i = 0; i < qr.size(); ++i)\n plugins[qr[i][plugin]->name] = qr[i][pegname]->name;\n \n \/\/ iterate over all plugins\n map<string, map<int, PortInfo> > info;\n map<string, string>::const_iterator plug_iter;\n for (plug_iter = plugins.begin(); plug_iter != plugins.end(); ++plug_iter) {\n\n \/\/ query the plugin ports\n Variable port, index, symbol;\n qr = select(index, symbol)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"symbol\"), symbol)\n .run(data);\n \n \/\/ put ports in a map so they get sorted\n map<int, PortInfo> ports;\n for (size_t i = 0; i < qr.size(); ++i) {\n int port_index = atoi(qr[i][index]->name.c_str());\n if (ports.find(port_index) != ports.end()) {\n\tcerr<<\"Index \"<<port_index<<\" is used for more than one port\"<<endl;\n\treturn -1;\n }\n ports[port_index].name = qr[i][symbol]->name;\n }\n\n \/\/ query the context ports\n Variable cx_pred, context;\n qr = select(index, symbol)\n .where(plug_iter->first, cx_pred, context)\n .where(context, cx(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"symbol\"), symbol)\n .filter(or_filter(cx_pred == cx(\"optionalContext\"),\n\t\t\tcx_pred == cx(\"requiredContext\")))\n .run(data);\n \n \/\/ put them in the map too\n for (size_t i = 0; i < qr.size(); ++i) {\n int port_index = atoi(qr[i][index]->name.c_str());\n if (ports.find(port_index) != ports.end()) {\n\tcerr<<\"Index \"<<port_index<<\" is used for more than one port\"<<endl;\n\treturn -1;\n }\n ports[port_index].name = qr[i][symbol]->name;\n }\n \n \/\/ check that the port indices are OK\n map<int, PortInfo>::const_iterator iter;\n int next = 0;\n for (iter = ports.begin(); iter != ports.end(); ++iter) {\n if (iter->first != next) {\n cerr<<\"There was no description of port \"<<next\n <<\" in plugin \"<<plug_iter->first<<endl;\n return -1;\n }\n ++next;\n }\n \n \/\/ get min values\n Variable value;\n qr = select(index, value)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"minimum\"), value)\n .run(data);\n for (unsigned i = 0; i < qr.size(); ++i)\n ports[atoi(qr[i][index]->name.c_str())].min =\n atof(qr[i][value]->name.c_str());\n\n \/\/ get max values\n qr = select(index, value)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"maximum\"), value)\n .run(data);\n for (unsigned i = 0; i < qr.size(); ++i)\n ports[atoi(qr[i][index]->name.c_str())].max =\n atof(qr[i][value]->name.c_str());\n \n \/\/ get default values\n qr = select(index, value)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"default\"), value)\n .run(data);\n for (unsigned i = 0; i < qr.size(); ++i)\n ports[atoi(qr[i][index]->name.c_str())].default_value =\n atof(qr[i][value]->name.c_str());\n \n \/\/ get port hints\n Variable hint;\n qr = select(index, hint)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"portHint\"), hint)\n .run(data);\n for (unsigned i = 0; i < qr.size(); ++i) {\n if (qr[i][hint]->name == lv2(\"toggled\"))\n ports[atoi(qr[i][index]->name.c_str())].toggled = true;\n if (qr[i][hint]->name == lv2(\"integer\"))\n ports[atoi(qr[i][index]->name.c_str())].integer = true;\n if (qr[i][hint]->name == lv2(\"logarithmic\"))\n ports[atoi(qr[i][index]->name.c_str())].logarithmic = true;\n }\n \n info[plug_iter->first] = ports;\n\n }\n\n \/\/ write the header file\n string header_guard = argv[2];\n for (size_t i = 0; i < header_guard.size(); ++i) {\n char& c = header_guard[i];\n if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_')))\n header_guard[i] = '_';\n }\n ofstream fout(argv[2]);\n fout<<\"#ifndef \"<<header_guard<<endl\n <<\"#define \"<<header_guard<<endl<<endl<<endl;\n\n \/\/ define data structure\n fout<<\"#ifndef PEG_STRUCT\"<<endl\n <<\"#define PEG_STRUCT\"<<endl\n <<\"typedef struct {\"<<endl\n <<\" float min;\"<<endl\n <<\" float max;\"<<endl\n <<\" float default_value;\"<<endl\n <<\" char toggled;\"<<endl\n <<\" char integer;\"<<endl\n <<\" char logarithmic;\"<<endl\n <<\"} peg_data_t;\"<<endl\n <<\"#endif\"<<endl<<endl;\n\n map<string, map<int, PortInfo> >::const_iterator piter;\n for (piter = info.begin(); piter != info.end(); ++piter) {\n fout<<\"\/* \"<<piter->first<<\" *\/\"<<endl<<endl;\n \n \/\/ write the URI\n fout<<\"static const char \"<<plugins[piter->first]<<\"_uri[] = \\\"\"\n <<piter->first.substr(1, piter->first.size() - 2)<<\"\\\";\"<<endl<<endl;\n \n \/\/ write port labels\n fout<<\"enum \"<<plugins[piter->first]<<\"_port_enum {\"<<endl;\n map<int, PortInfo>::const_iterator iter;\n for (iter = piter->second.begin(); iter != piter->second.end(); ++iter)\n fout<<\" \"<<plugins[piter->first]<<\"_\"<<iter->second.name<<\",\"<<endl;\n fout<<\" \"<<plugins[piter->first]<<\"_n_ports\"<<endl\n <<\"};\"<<endl<<endl;\n \n \/\/ write port info\n fout<<\"static const peg_data_t \"\n <<plugins[piter->first]<<\"_ports[] = {\"<<endl;\n for (iter = piter->second.begin(); iter != piter->second.end(); ++iter) {\n fout<<\" { \"\n <<iter->second.min<<\", \"\n <<iter->second.max<<\", \"\n <<iter->second.default_value<<\", \"\n <<(iter->second.toggled ? \"1\" : \"0\")<<\", \"\n <<(iter->second.integer ? \"1\" : \"0\")<<\", \"\n <<(iter->second.logarithmic ? \"1\" : \"0\")<<\" }, \"<<endl;\n }\n fout<<\"};\"<<endl<<endl<<endl;\n \n }\n \n fout<<\"#endif \/* \"<<header_guard<<\" *\/\"<<endl;\n \n return 0;\n}\n<commit_msg>ttl2c looks for portProperty instead of portHint<commit_after>\/****************************************************************************\n \n TTL2C - LV2 Port Enum Generator\n\n This program reads an RDF file (in the Turtle syntax) describing\n an LV2 plugin and generates a C header file with data structures\n that contain information about the plugin.\n \n Copyright (C) 2006-2007 Lars Luthman <lars.luthman@gmail.com>\n \n Modified 2012 Michael Fisher <mfisher31@gmail.com>\n - renamed to ttl2c to avoid conflict with lv2-c++-tools\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; either version 3 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. 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, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA\n\n****************************************************************************\/\n\n#include <cfloat>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"turtleparser.hpp\"\n#include \"query.hpp\"\n#include \"namespaces.hpp\"\n\n#ifndef VERSION\n#define VERSION \"UNKNOWNVERSION\"\n#endif\n\n\nusing namespace std;\nusing namespace PAQ;\n\n\nstruct PortInfo {\n PortInfo() \n : min(-FLT_MAX), \n max(FLT_MAX), \n default_value(min),\n toggled(false),\n integer(false),\n logarithmic(false) { }\n string name;\n float min;\n float max;\n float default_value;\n bool toggled;\n bool integer;\n bool logarithmic;\n};\n\n\nint main(int argc, char** argv) {\n \n for (int i = 1; i < argc; ++i) {\n if (string(argv[i]) == \"-V\" || string(argv[i]) == \"--version\") {\n cout<<\"ttl2c \"<<VERSION<<\" by Lars Luthman <lars.luthman@gmail.com>\"\n <<endl;\n return 0;\n }\n }\n \n if (argc < 3) {\n cerr<<\"Usage: ttl2c <input file> <output file> \"<<endl;\n return -1;\n }\n \n \/\/ parse turtle file\n TurtleParser tp;\n RDFData data;\n if (!tp.parse_ttl_file(argv[1], data)) {\n cerr<<\"Could not parse input. Not valid Turtle syntax.\"<<endl;\n return -1;\n }\n \n \/\/ find all plugins in the file\n Namespace lv2(\"<http:\/\/lv2plug.in\/ns\/lv2core#>\");\n Namespace cx(\"<http:\/\/ll-plugins.nongnu.org\/lv2\/dev\/contexts\/1#>\");\n Namespace ll(\"<http:\/\/ll-plugins.nongnu.org\/lv2\/namespace#>\");\n Namespace pprops(\"<http:\/\/lv2plug.in\/ns\/ext\/port-props#>\");\n Variable plugin, pegname;\n vector<QueryResult> qr =\n select(plugin, pegname)\n .where(plugin, ll(\"pegName\"), pegname)\n .where(plugin, rdf(\"type\"), lv2(\"Plugin\"))\n .run(data);\n map<string, string> plugins;\n for (unsigned i = 0; i < qr.size(); ++i)\n plugins[qr[i][plugin]->name] = qr[i][pegname]->name;\n \n \/\/ iterate over all plugins\n map<string, map<int, PortInfo> > info;\n map<string, string>::const_iterator plug_iter;\n for (plug_iter = plugins.begin(); plug_iter != plugins.end(); ++plug_iter) {\n\n \/\/ query the plugin ports\n Variable port, index, symbol;\n qr = select(index, symbol)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"symbol\"), symbol)\n .run(data);\n \n \/\/ put ports in a map so they get sorted\n map<int, PortInfo> ports;\n for (size_t i = 0; i < qr.size(); ++i) {\n int port_index = atoi(qr[i][index]->name.c_str());\n if (ports.find(port_index) != ports.end()) {\n\tcerr<<\"Index \"<<port_index<<\" is used for more than one port\"<<endl;\n\treturn -1;\n }\n ports[port_index].name = qr[i][symbol]->name;\n }\n\n \/\/ query the context ports\n Variable cx_pred, context;\n qr = select(index, symbol)\n .where(plug_iter->first, cx_pred, context)\n .where(context, cx(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"symbol\"), symbol)\n .filter(or_filter(cx_pred == cx(\"optionalContext\"),\n\t\t\tcx_pred == cx(\"requiredContext\")))\n .run(data);\n \n \/\/ put them in the map too\n for (size_t i = 0; i < qr.size(); ++i) {\n int port_index = atoi(qr[i][index]->name.c_str());\n if (ports.find(port_index) != ports.end()) {\n\tcerr<<\"Index \"<<port_index<<\" is used for more than one port\"<<endl;\n\treturn -1;\n }\n ports[port_index].name = qr[i][symbol]->name;\n }\n \n \/\/ check that the port indices are OK\n map<int, PortInfo>::const_iterator iter;\n int next = 0;\n for (iter = ports.begin(); iter != ports.end(); ++iter) {\n if (iter->first != next) {\n cerr<<\"There was no description of port \"<<next\n <<\" in plugin \"<<plug_iter->first<<endl;\n return -1;\n }\n ++next;\n }\n \n \/\/ get min values\n Variable value;\n qr = select(index, value)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"minimum\"), value)\n .run(data);\n for (unsigned i = 0; i < qr.size(); ++i)\n ports[atoi(qr[i][index]->name.c_str())].min =\n atof(qr[i][value]->name.c_str());\n\n \/\/ get max values\n qr = select(index, value)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"maximum\"), value)\n .run(data);\n for (unsigned i = 0; i < qr.size(); ++i)\n ports[atoi(qr[i][index]->name.c_str())].max =\n atof(qr[i][value]->name.c_str());\n \n \/\/ get default values\n qr = select(index, value)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"default\"), value)\n .run(data);\n for (unsigned i = 0; i < qr.size(); ++i)\n ports[atoi(qr[i][index]->name.c_str())].default_value =\n atof(qr[i][value]->name.c_str());\n \n \/\/ get port properties\n Variable property;\n qr = select(index, property)\n .where(plug_iter->first, lv2(\"port\"), port)\n .where(port, lv2(\"index\"), index)\n .where(port, lv2(\"portProperty\"), property)\n .run(data);\n for (unsigned i = 0; i < qr.size(); ++i) {\n if (qr[i][property]->name == lv2(\"toggled\"))\n ports[atoi(qr[i][index]->name.c_str())].toggled = true;\n if (qr[i][property]->name == lv2(\"integer\"))\n ports[atoi(qr[i][index]->name.c_str())].integer = true;\n if (qr[i][property]->name == pprops(\"logarithmic\"))\n ports[atoi(qr[i][index]->name.c_str())].logarithmic = true;\n }\n \n info[plug_iter->first] = ports;\n\n }\n\n \/\/ write the header file\n string header_guard = argv[2];\n for (size_t i = 0; i < header_guard.size(); ++i) {\n char& c = header_guard[i];\n if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_')))\n header_guard[i] = '_';\n }\n ofstream fout(argv[2]);\n fout<<\"#ifndef \"<<header_guard<<endl\n <<\"#define \"<<header_guard<<endl<<endl<<endl;\n\n \/\/ define data structure\n fout<<\"#ifndef PEG_STRUCT\"<<endl\n <<\"#define PEG_STRUCT\"<<endl\n <<\"typedef struct {\"<<endl\n <<\" float min;\"<<endl\n <<\" float max;\"<<endl\n <<\" float default_value;\"<<endl\n <<\" char toggled;\"<<endl\n <<\" char integer;\"<<endl\n <<\" char logarithmic;\"<<endl\n <<\"} peg_data_t;\"<<endl\n <<\"#endif\"<<endl<<endl;\n\n map<string, map<int, PortInfo> >::const_iterator piter;\n for (piter = info.begin(); piter != info.end(); ++piter) {\n fout<<\"\/* \"<<piter->first<<\" *\/\"<<endl<<endl;\n \n \/\/ write the URI\n fout<<\"static const char \"<<plugins[piter->first]<<\"_uri[] = \\\"\"\n <<piter->first.substr(1, piter->first.size() - 2)<<\"\\\";\"<<endl<<endl;\n \n \/\/ write port labels\n fout<<\"enum \"<<plugins[piter->first]<<\"_port_enum {\"<<endl;\n map<int, PortInfo>::const_iterator iter;\n for (iter = piter->second.begin(); iter != piter->second.end(); ++iter)\n fout<<\" \"<<plugins[piter->first]<<\"_\"<<iter->second.name<<\",\"<<endl;\n fout<<\" \"<<plugins[piter->first]<<\"_n_ports\"<<endl\n <<\"};\"<<endl<<endl;\n \n \/\/ write port info\n fout<<\"static const peg_data_t \"\n <<plugins[piter->first]<<\"_ports[] = {\"<<endl;\n for (iter = piter->second.begin(); iter != piter->second.end(); ++iter) {\n fout<<\" { \"\n <<iter->second.min<<\", \"\n <<iter->second.max<<\", \"\n <<iter->second.default_value<<\", \"\n <<(iter->second.toggled ? \"1\" : \"0\")<<\", \"\n <<(iter->second.integer ? \"1\" : \"0\")<<\", \"\n <<(iter->second.logarithmic ? \"1\" : \"0\")<<\" }, \"<<endl;\n }\n fout<<\"};\"<<endl<<endl<<endl;\n \n }\n \n fout<<\"#endif \/* \"<<header_guard<<\" *\/\"<<endl;\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-2012, AOYAMA Kazuharu\r\n * All rights reserved.\r\n *\r\n * This software may be used and distributed according to the terms of\r\n * the New BSD License, which is incorporated herein by reference.\r\n *\/\r\n\r\n#include <QtCore>\r\n#include <QSysInfo>\r\n#include <TWebApplication>\r\n#include <TSystemGlobal>\r\n#include \"servermanager.h\"\r\n#include \"processinfo.h\"\r\n\r\n#ifdef Q_OS_UNIX\r\n# include <sys\/utsname.h>\r\n#endif\r\n\r\nnamespace TreeFrog {\r\n\r\n#ifdef Q_OS_WIN\r\nextern void WINAPI winServiceMain(DWORD argc, LPTSTR *argv);\r\n#endif\r\n\r\nenum CommandOption {\r\n Invalid = 0,\r\n EnvironmentSpecified,\r\n SocketSpecified,\r\n PrintVersion,\r\n PrintUsage,\r\n DaemonMode,\r\n WindowsServiceMode,\r\n SendSignal,\r\n};\r\n\r\ntypedef QHash<int, QString> VersionHash;\r\n\r\n#ifdef Q_OS_WIN\r\nQ_GLOBAL_STATIC_WITH_INITIALIZER(VersionHash, winVersion,\r\n{\r\n x->insert(QSysInfo::WV_XP, \"Windows XP\");\r\n x->insert(QSysInfo::WV_2003, \"Windows Server 2003\");\r\n x->insert(QSysInfo::WV_VISTA, \"Windows Vista or Windows Server 2008\");\r\n x->insert(QSysInfo::WV_WINDOWS7, \"Windows 7 or Windows Server 2008 R2\");\r\n})\r\n#endif\r\n\r\n#ifdef Q_OS_DARWIN\r\nQ_GLOBAL_STATIC_WITH_INITIALIZER(VersionHash, macVersion,\r\n{\r\n x->insert(QSysInfo::MV_10_3, \"Mac OS X 10.3 Panther\");\r\n x->insert(QSysInfo::MV_10_4, \"Mac OS X 10.4 Tiger\");\r\n x->insert(QSysInfo::MV_10_5, \"Mac OS X 10.5 Leopard\");\r\n x->insert(QSysInfo::MV_10_6, \"Mac OS X 10.6 Snow Leopard\");\r\n#if QT_VERSION >= 0x040800\r\n x->insert(QSysInfo::MV_10_7, \"Mac OS X 10.7 Lion\");\r\n x->insert(QSysInfo::MV_10_8, \"Mac OS X 10.8 Mountain Lion\");\r\n#endif\r\n})\r\n#endif\r\n\r\ntypedef QHash<QString, int> OptionHash;\r\nQ_GLOBAL_STATIC_WITH_INITIALIZER(OptionHash, options,\r\n{\r\n x->insert(\"-e\", EnvironmentSpecified);\r\n x->insert(\"-s\", SocketSpecified);\r\n x->insert(\"-v\", PrintVersion);\r\n x->insert(\"-h\", PrintUsage);\r\n x->insert(\"-d\", DaemonMode);\r\n x->insert(\"-w\", WindowsServiceMode);\r\n x->insert(\"-k\", SendSignal);\r\n})\r\n\r\n\r\nstatic void usage()\r\n{\r\n char text[] =\r\n \"Usage: %1 [-d] [-e environment] [application-directory]\\n\" \\\r\n \"Usage: %1 [-k stop|abort|restart] [application-directory]\\n\" \\\r\n \"Options:\\n\" \\\r\n \" -d : run as a daemon process\\n\" \\\r\n \" -e environment : specify an environment of the database settings\\n\" \\\r\n \" -k : send signal to a manager process\\n\\n\" \\\r\n \"Type '%1 -h' to show this information.\\n\" \\\r\n \"Type '%1 -v' to show the program version.\";\r\n \r\n QString cmd = QFileInfo(QCoreApplication::applicationFilePath()).fileName();\r\n puts(qPrintable(QString(text).arg(cmd)));\r\n}\r\n\r\n\r\nstatic bool checkArguments()\r\n{\r\n for (QStringListIterator i(QCoreApplication::arguments()); i.hasNext(); ) {\r\n const QString &arg = i.next();\r\n if (arg.startsWith('-') && options()->value(arg, Invalid) == Invalid) {\r\n fprintf(stderr, \"invalid argument\\n\");\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\n\r\nstatic bool startDaemon()\r\n{\r\n bool success;\r\n QStringList args = QCoreApplication::arguments();\r\n args.removeAll(\"-d\");\r\n#ifdef Q_OS_WIN\r\n PROCESS_INFORMATION pinfo;\r\n STARTUPINFOW startupInfo = { sizeof(STARTUPINFO), 0, 0, 0,\r\n (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,\r\n (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,\r\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\r\n };\r\n success = CreateProcess(0, (wchar_t*)args.join(\" \").utf16(),\r\n 0, 0, FALSE, CREATE_UNICODE_ENVIRONMENT, 0,\r\n (wchar_t*)QDir::currentPath().utf16(),\r\n &startupInfo, &pinfo);\r\n if (success) {\r\n CloseHandle(pinfo.hThread);\r\n CloseHandle(pinfo.hProcess);\r\n }\r\n#else\r\n args.removeFirst(); \/\/ Removes the program name\r\n success = QProcess::startDetached(QCoreApplication::applicationFilePath(), args, QDir::currentPath());\r\n#endif\r\n\r\n return success;\r\n}\r\n\r\n\r\nstatic void writeStartupLog()\r\n{\r\n tSystemInfo(\"TreeFrog Framework version \" TF_VERSION_STR);\r\n\r\n QString qtversion = \"Qt \" QT_VERSION_STR;\r\n#if defined(Q_OS_WIN)\r\n qtversion += QLatin1String(\" \/ \") + winVersion()->value(QSysInfo::WindowsVersion, \"Windows\");\r\n#elif defined(Q_OS_DARWIN)\r\n qtversion += QLatin1String(\" \/ \") + macVersion()->value(QSysInfo::MacintoshVersion, \"Mac OS X\");\r\n#elif defined(Q_OS_UNIX)\r\n struct utsname uts;\r\n if (uname(&uts) == 0) {\r\n qtversion += QString(\" \/ %1 %2\").arg(uts.sysname).arg(uts.release);\r\n }\r\n#endif\r\n tSystemInfo(\"%s\", qtversion.toLatin1().data()); \r\n}\r\n\r\n\r\nstatic QString pidFilePath()\r\n{\r\n QString base = QFileInfo(QCoreApplication::applicationFilePath()).baseName();\r\n return Tf::app()->tmpPath() + base + \".pid\";\r\n}\r\n\r\n\r\nstatic qint64 readPidFileOfApplication()\r\n{\r\n QFile pidf(pidFilePath());\r\n if (pidf.open(QIODevice::ReadOnly)) {\r\n qint64 pid = pidf.readLine(100).toLongLong();\r\n if (pid > 0) {\r\n return pid;\r\n }\r\n }\r\n return -1;\r\n}\r\n\r\n\r\nstatic qint64 runningApplicationPid()\r\n{\r\n qint64 pid = readPidFileOfApplication();\r\n if (pid > 0) {\r\n QString name = ProcessInfo(pid).processName().toLower();\r\n if (name == \"treefrog\" || name == \"treefrogd\")\r\n return pid;\r\n }\r\n return -1;\r\n}\r\n\r\n\r\nstatic int killTreeFrogProcess(const QString &cmd)\r\n{\r\n qint64 pid = runningApplicationPid();\r\n if (pid < 0) {\r\n printf(\"TreeFrog server not running\\n\");\r\n return 1;\r\n }\r\n\r\n ProcessInfo pi(pid);\r\n\r\n if (cmd == \"stop\") { \/\/ stop command\r\n pi.terminate();\r\n if (pi.waitForTerminated()) {\r\n printf(\"TreeFrog application servers shutdown completed\\n\");\r\n } else {\r\n fprintf(stderr, \"TreeFrog application servers shutdown failed\\n\");\r\n }\r\n\r\n } else if (cmd == \"abort\") { \/\/ abort command\r\n pi.kill();\r\n tSystemInfo(\"Killed TreeFrog manager process pid:%ld\", (long)pid);\r\n ::unlink(pidFilePath().toLatin1().data());\r\n\r\n \/\/ kill all 'tadpole' processes\r\n#if defined(Q_OS_WIN) && !defined(TF_NO_DEBUG)\r\n ProcessInfo::killProcesses(\"tadpoled\");\r\n#else\r\n ProcessInfo::killProcesses(\"tadpole\");\r\n#endif\r\n tSystemInfo(\"Killed TreeFrog application server processes\");\r\n printf(\"Killed TreeFrog application server processes\\n\");\r\n\r\n } else if (cmd == \"restart\") { \/\/ restart command\r\n pi.restart();\r\n printf(\"Sent a restart request\\n\");\r\n\r\n } else {\r\n usage();\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\n\r\nint managerMain(int argc, char *argv[])\r\n{\r\n TWebApplication app(argc, argv);\r\n\r\n \/\/ Creates the semaphore for system log\r\n QSystemSemaphore semaphore(\"TreeFrogSystemLog\", 1, QSystemSemaphore::Create);\r\n tSetupSystemLoggers();\r\n\r\n#if defined(Q_OS_UNIX)\r\n app.watchUnixSignal(SIGTERM);\r\n app.watchUnixSignal(SIGINT);\r\n app.watchUnixSignal(SIGHUP);\r\n#elif defined(Q_OS_WIN)\r\n app.watchConsoleSignal();\r\n#endif\r\n\r\n \/\/ Sets codec\r\n QTextCodec *codec = QTextCodec::codecForName(\"UTF-8\");\r\n QTextCodec::setCodecForLocale(codec);\r\n \r\n if (!checkArguments()) {\r\n return 1;\r\n }\r\n\r\n bool daemonMode = false;\r\n QString signalCmd;\r\n\r\n QStringList args = QCoreApplication::arguments();\r\n args.removeFirst();\r\n for (QStringListIterator i(args); i.hasNext(); ) {\r\n const QString &arg = i.next();\r\n int cmd = options()->value(arg, Invalid);\r\n switch (cmd) {\r\n case PrintVersion:\r\n printf(\"%s version \" TF_VERSION_STR \" (r%d) (built on %s)\\n\", qPrintable(QFileInfo(argv[0]).baseName()), TF_SRC_REVISION, __DATE__);\r\n return 0;\r\n break;\r\n\r\n case PrintUsage:\r\n usage();\r\n return 0;\r\n break;\r\n\r\n case DaemonMode:\r\n daemonMode = true;\r\n break;\r\n\r\n case WindowsServiceMode:\r\n \/\/ ignore\r\n break;\r\n\r\n case SendSignal:\r\n signalCmd = i.next(); \/\/ assign a command\r\n break;\r\n\r\n default:\r\n \/\/ do nothing\r\n break;\r\n }\r\n }\r\n\r\n if (!app.appSettingsFileExists()) {\r\n fprintf(stderr, \"INI file not found [%s]\\n\\n\", qPrintable(app.appSettingsFilePath()));\r\n return 1;\r\n }\r\n\r\n if (!signalCmd.isEmpty()) {\r\n return killTreeFrogProcess(signalCmd);\r\n }\r\n\r\n \/\/ Check TreeFrog processes are running\r\n qint64 pid = runningApplicationPid();\r\n if (pid > 0) {\r\n fprintf(stderr, \"Already running pid:%ld\\n\", (long)pid);\r\n return 1;\r\n }\r\n\r\n if (!app.isValidDatabaseSettings()) {\r\n tSystemError(\"Database settings not found [environment: %s]\", qPrintable(app.databaseEnvironment()));\r\n fprintf(stderr, \"database settings not found [environment: %s]\\n\\n\", qPrintable(app.databaseEnvironment()));\r\n usage();\r\n return 1;\r\n }\r\n\r\n \/\/ Check a port number\r\n quint16 listenPort = 0;\r\n QString svrname = app.appSettings().value(\"ListenPort\").toString();\r\n if (svrname.startsWith(\"unix:\", Qt::CaseInsensitive)) {\r\n svrname.remove(0, 5);\r\n } else {\r\n int port = svrname.toInt();\r\n if (port <= 0 || port > USHRT_MAX) {\r\n tSystemError(\"Invalid port number: %d\", port);\r\n return 1;\r\n }\r\n listenPort = port;\r\n svrname.clear();\r\n }\r\n\r\n \/\/ start daemon process\r\n if (daemonMode) {\r\n if ( !startDaemon() ) {\r\n fprintf(stderr, \"Failed to create process\\n\\n\");\r\n return 1;\r\n }\r\n return 0;\r\n }\r\n\r\n int ret = 0;\r\n QFile pidfile;\r\n \r\n for (;;) {\r\n ServerManager *manager = 0;\r\n switch ( app.multiProcessingModule() ) {\r\n case TWebApplication::Thread: {\r\n manager = new ServerManager(1, 1, 0, &app);\r\n break; }\r\n \r\n case TWebApplication::Prefork: {\r\n int max = app.appSettings().value(\"MPM.prefork.MaxServers\").toInt();\r\n int min = app.appSettings().value(\"MPM.prefork.MinServers\").toInt();\r\n int spare = app.appSettings().value(\"MPM.prefork.SpareServers\").toInt();\r\n manager = new ServerManager(max, min, spare, &app);\r\n break; }\r\n \r\n default:\r\n tSystemError(\"Invalid MPM specified\");\r\n return 1;\r\n }\r\n \r\n \/\/ Startup\r\n writeStartupLog();\r\n bool started;\r\n if (listenPort > 0) {\r\n \/\/ TCP\/IP\r\n started = manager->start(QHostAddress::Any, listenPort);\r\n } else {\r\n \/\/ UNIX domain\r\n started = manager->start(svrname);\r\n }\r\n \r\n if (!started) {\r\n tSystemError(\"TreeFrog application server startup failed\");\r\n fprintf(stderr, \"TreeFrog application server startup failed\\n\\n\");\r\n return 1;\r\n }\r\n \r\n \/\/ tmp directory\r\n QDir tmpDir(app.tmpPath());\r\n if (!tmpDir.exists()) {\r\n tmpDir.mkpath(\".\");\r\n }\r\n \r\n \/\/ Writes the PID\r\n pidfile.setFileName(pidFilePath());\r\n if (pidfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {\r\n pid = QCoreApplication::applicationPid();\r\n pidfile.write( QString::number(pid).toLatin1() );\r\n pidfile.close();\r\n } else {\r\n tSystemError(\"File open failed: %s\", qPrintable(pidfile.fileName()));\r\n }\r\n \r\n ret = app.exec();\r\n tSystemDebug(\"tfmanager returnCode:%d\", ret);\r\n manager->stop();\r\n \r\n if (ret == 1) { \/\/ means SIGHUP\r\n tSystemDebug(\"Restarts TreeFrog application servers\");\r\n \/\/continue;\r\n } else {\r\n break;\r\n }\r\n }\r\n \r\n if (!svrname.isEmpty()) { \/\/ UNIX domain file\r\n QFile(svrname).remove();\r\n }\r\n pidfile.remove(); \/\/ Removes the PID file\r\n return 0;\r\n}\r\n\r\n} \/\/ namespace TreeFrog\r\n\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n#ifdef Q_OS_WIN\r\n for (int i = 1; i < argc; ++i) {\r\n if (strcmp(argv[i], \"-w\") == 0) {\r\n \/\/ Windows service mode\r\n SERVICE_TABLE_ENTRY entry[] = { { (LPTSTR)TEXT(\"\"), TreeFrog::winServiceMain }, { 0, 0 } };\r\n StartServiceCtrlDispatcher(entry);\r\n return 0;\r\n }\r\n }\r\n#endif\r\n return TreeFrog::managerMain(argc, argv);\r\n}\r\n<commit_msg>changed CRLF -> LF.<commit_after>\/* Copyright (c) 2010-2012, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include <QtCore>\n#include <QSysInfo>\n#include <TWebApplication>\n#include <TSystemGlobal>\n#include \"servermanager.h\"\n#include \"processinfo.h\"\n\n#ifdef Q_OS_UNIX\n# include <sys\/utsname.h>\n#endif\n\nnamespace TreeFrog {\n\n#ifdef Q_OS_WIN\nextern void WINAPI winServiceMain(DWORD argc, LPTSTR *argv);\n#endif\n\nenum CommandOption {\n Invalid = 0,\n EnvironmentSpecified,\n SocketSpecified,\n PrintVersion,\n PrintUsage,\n DaemonMode,\n WindowsServiceMode,\n SendSignal,\n};\n\ntypedef QHash<int, QString> VersionHash;\n\n#ifdef Q_OS_WIN\nQ_GLOBAL_STATIC_WITH_INITIALIZER(VersionHash, winVersion,\n{\n x->insert(QSysInfo::WV_XP, \"Windows XP\");\n x->insert(QSysInfo::WV_2003, \"Windows Server 2003\");\n x->insert(QSysInfo::WV_VISTA, \"Windows Vista or Windows Server 2008\");\n x->insert(QSysInfo::WV_WINDOWS7, \"Windows 7 or Windows Server 2008 R2\");\n})\n#endif\n\n#ifdef Q_OS_DARWIN\nQ_GLOBAL_STATIC_WITH_INITIALIZER(VersionHash, macVersion,\n{\n x->insert(QSysInfo::MV_10_3, \"Mac OS X 10.3 Panther\");\n x->insert(QSysInfo::MV_10_4, \"Mac OS X 10.4 Tiger\");\n x->insert(QSysInfo::MV_10_5, \"Mac OS X 10.5 Leopard\");\n x->insert(QSysInfo::MV_10_6, \"Mac OS X 10.6 Snow Leopard\");\n#if QT_VERSION >= 0x040800\n x->insert(QSysInfo::MV_10_7, \"Mac OS X 10.7 Lion\");\n x->insert(QSysInfo::MV_10_8, \"Mac OS X 10.8 Mountain Lion\");\n#endif\n})\n#endif\n\ntypedef QHash<QString, int> OptionHash;\nQ_GLOBAL_STATIC_WITH_INITIALIZER(OptionHash, options,\n{\n x->insert(\"-e\", EnvironmentSpecified);\n x->insert(\"-s\", SocketSpecified);\n x->insert(\"-v\", PrintVersion);\n x->insert(\"-h\", PrintUsage);\n x->insert(\"-d\", DaemonMode);\n x->insert(\"-w\", WindowsServiceMode);\n x->insert(\"-k\", SendSignal);\n})\n\n\nstatic void usage()\n{\n char text[] =\n \"Usage: %1 [-d] [-e environment] [application-directory]\\n\" \\\n \"Usage: %1 [-k stop|abort|restart] [application-directory]\\n\" \\\n \"Options:\\n\" \\\n \" -d : run as a daemon process\\n\" \\\n \" -e environment : specify an environment of the database settings\\n\" \\\n \" -k : send signal to a manager process\\n\\n\" \\\n \"Type '%1 -h' to show this information.\\n\" \\\n \"Type '%1 -v' to show the program version.\";\n \n QString cmd = QFileInfo(QCoreApplication::applicationFilePath()).fileName();\n puts(qPrintable(QString(text).arg(cmd)));\n}\n\n\nstatic bool checkArguments()\n{\n for (QStringListIterator i(QCoreApplication::arguments()); i.hasNext(); ) {\n const QString &arg = i.next();\n if (arg.startsWith('-') && options()->value(arg, Invalid) == Invalid) {\n fprintf(stderr, \"invalid argument\\n\");\n return false;\n }\n }\n return true;\n}\n\n\nstatic bool startDaemon()\n{\n bool success;\n QStringList args = QCoreApplication::arguments();\n args.removeAll(\"-d\");\n#ifdef Q_OS_WIN\n PROCESS_INFORMATION pinfo;\n STARTUPINFOW startupInfo = { sizeof(STARTUPINFO), 0, 0, 0,\n (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,\n (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n };\n success = CreateProcess(0, (wchar_t*)args.join(\" \").utf16(),\n 0, 0, FALSE, CREATE_UNICODE_ENVIRONMENT, 0,\n (wchar_t*)QDir::currentPath().utf16(),\n &startupInfo, &pinfo);\n if (success) {\n CloseHandle(pinfo.hThread);\n CloseHandle(pinfo.hProcess);\n }\n#else\n args.removeFirst(); \/\/ Removes the program name\n success = QProcess::startDetached(QCoreApplication::applicationFilePath(), args, QDir::currentPath());\n#endif\n\n return success;\n}\n\n\nstatic void writeStartupLog()\n{\n tSystemInfo(\"TreeFrog Framework version \" TF_VERSION_STR);\n\n QString qtversion = \"Qt \" QT_VERSION_STR;\n#if defined(Q_OS_WIN)\n qtversion += QLatin1String(\" \/ \") + winVersion()->value(QSysInfo::WindowsVersion, \"Windows\");\n#elif defined(Q_OS_DARWIN)\n qtversion += QLatin1String(\" \/ \") + macVersion()->value(QSysInfo::MacintoshVersion, \"Mac OS X\");\n#elif defined(Q_OS_UNIX)\n struct utsname uts;\n if (uname(&uts) == 0) {\n qtversion += QString(\" \/ %1 %2\").arg(uts.sysname).arg(uts.release);\n }\n#endif\n tSystemInfo(\"%s\", qtversion.toLatin1().data()); \n}\n\n\nstatic QString pidFilePath()\n{\n QString base = QFileInfo(QCoreApplication::applicationFilePath()).baseName();\n return Tf::app()->tmpPath() + base + \".pid\";\n}\n\n\nstatic qint64 readPidFileOfApplication()\n{\n QFile pidf(pidFilePath());\n if (pidf.open(QIODevice::ReadOnly)) {\n qint64 pid = pidf.readLine(100).toLongLong();\n if (pid > 0) {\n return pid;\n }\n }\n return -1;\n}\n\n\nstatic qint64 runningApplicationPid()\n{\n qint64 pid = readPidFileOfApplication();\n if (pid > 0) {\n QString name = ProcessInfo(pid).processName().toLower();\n if (name == \"treefrog\" || name == \"treefrogd\")\n return pid;\n }\n return -1;\n}\n\n\nstatic int killTreeFrogProcess(const QString &cmd)\n{\n qint64 pid = runningApplicationPid();\n if (pid < 0) {\n printf(\"TreeFrog server not running\\n\");\n return 1;\n }\n\n ProcessInfo pi(pid);\n\n if (cmd == \"stop\") { \/\/ stop command\n pi.terminate();\n if (pi.waitForTerminated()) {\n printf(\"TreeFrog application servers shutdown completed\\n\");\n } else {\n fprintf(stderr, \"TreeFrog application servers shutdown failed\\n\");\n }\n\n } else if (cmd == \"abort\") { \/\/ abort command\n pi.kill();\n tSystemInfo(\"Killed TreeFrog manager process pid:%ld\", (long)pid);\n ::unlink(pidFilePath().toLatin1().data());\n\n \/\/ kill all 'tadpole' processes\n#if defined(Q_OS_WIN) && !defined(TF_NO_DEBUG)\n ProcessInfo::killProcesses(\"tadpoled\");\n#else\n ProcessInfo::killProcesses(\"tadpole\");\n#endif\n tSystemInfo(\"Killed TreeFrog application server processes\");\n printf(\"Killed TreeFrog application server processes\\n\");\n\n } else if (cmd == \"restart\") { \/\/ restart command\n pi.restart();\n printf(\"Sent a restart request\\n\");\n\n } else {\n usage();\n return 1;\n }\n return 0;\n}\n\n\nint managerMain(int argc, char *argv[])\n{\n TWebApplication app(argc, argv);\n\n \/\/ Creates the semaphore for system log\n QSystemSemaphore semaphore(\"TreeFrogSystemLog\", 1, QSystemSemaphore::Create);\n tSetupSystemLoggers();\n\n#if defined(Q_OS_UNIX)\n app.watchUnixSignal(SIGTERM);\n app.watchUnixSignal(SIGINT);\n app.watchUnixSignal(SIGHUP);\n#elif defined(Q_OS_WIN)\n app.watchConsoleSignal();\n#endif\n\n \/\/ Sets codec\n QTextCodec *codec = QTextCodec::codecForName(\"UTF-8\");\n QTextCodec::setCodecForLocale(codec);\n \n if (!checkArguments()) {\n return 1;\n }\n\n bool daemonMode = false;\n QString signalCmd;\n\n QStringList args = QCoreApplication::arguments();\n args.removeFirst();\n for (QStringListIterator i(args); i.hasNext(); ) {\n const QString &arg = i.next();\n int cmd = options()->value(arg, Invalid);\n switch (cmd) {\n case PrintVersion:\n printf(\"%s version \" TF_VERSION_STR \" (r%d) (built on %s)\\n\", qPrintable(QFileInfo(argv[0]).baseName()), TF_SRC_REVISION, __DATE__);\n return 0;\n break;\n\n case PrintUsage:\n usage();\n return 0;\n break;\n\n case DaemonMode:\n daemonMode = true;\n break;\n\n case WindowsServiceMode:\n \/\/ ignore\n break;\n\n case SendSignal:\n signalCmd = i.next(); \/\/ assign a command\n break;\n\n default:\n \/\/ do nothing\n break;\n }\n }\n\n if (!app.appSettingsFileExists()) {\n fprintf(stderr, \"INI file not found [%s]\\n\\n\", qPrintable(app.appSettingsFilePath()));\n return 1;\n }\n\n if (!signalCmd.isEmpty()) {\n return killTreeFrogProcess(signalCmd);\n }\n\n \/\/ Check TreeFrog processes are running\n qint64 pid = runningApplicationPid();\n if (pid > 0) {\n fprintf(stderr, \"Already running pid:%ld\\n\", (long)pid);\n return 1;\n }\n\n if (!app.isValidDatabaseSettings()) {\n tSystemError(\"Database settings not found [environment: %s]\", qPrintable(app.databaseEnvironment()));\n fprintf(stderr, \"database settings not found [environment: %s]\\n\\n\", qPrintable(app.databaseEnvironment()));\n usage();\n return 1;\n }\n\n \/\/ Check a port number\n quint16 listenPort = 0;\n QString svrname = app.appSettings().value(\"ListenPort\").toString();\n if (svrname.startsWith(\"unix:\", Qt::CaseInsensitive)) {\n svrname.remove(0, 5);\n } else {\n int port = svrname.toInt();\n if (port <= 0 || port > USHRT_MAX) {\n tSystemError(\"Invalid port number: %d\", port);\n return 1;\n }\n listenPort = port;\n svrname.clear();\n }\n\n \/\/ start daemon process\n if (daemonMode) {\n if ( !startDaemon() ) {\n fprintf(stderr, \"Failed to create process\\n\\n\");\n return 1;\n }\n return 0;\n }\n\n int ret = 0;\n QFile pidfile;\n \n for (;;) {\n ServerManager *manager = 0;\n switch ( app.multiProcessingModule() ) {\n case TWebApplication::Thread: {\n manager = new ServerManager(1, 1, 0, &app);\n break; }\n \n case TWebApplication::Prefork: {\n int max = app.appSettings().value(\"MPM.prefork.MaxServers\").toInt();\n int min = app.appSettings().value(\"MPM.prefork.MinServers\").toInt();\n int spare = app.appSettings().value(\"MPM.prefork.SpareServers\").toInt();\n manager = new ServerManager(max, min, spare, &app);\n break; }\n \n default:\n tSystemError(\"Invalid MPM specified\");\n return 1;\n }\n \n \/\/ Startup\n writeStartupLog();\n bool started;\n if (listenPort > 0) {\n \/\/ TCP\/IP\n started = manager->start(QHostAddress::Any, listenPort);\n } else {\n \/\/ UNIX domain\n started = manager->start(svrname);\n }\n \n if (!started) {\n tSystemError(\"TreeFrog application server startup failed\");\n fprintf(stderr, \"TreeFrog application server startup failed\\n\\n\");\n return 1;\n }\n \n \/\/ tmp directory\n QDir tmpDir(app.tmpPath());\n if (!tmpDir.exists()) {\n tmpDir.mkpath(\".\");\n }\n \n \/\/ Writes the PID\n pidfile.setFileName(pidFilePath());\n if (pidfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {\n pid = QCoreApplication::applicationPid();\n pidfile.write( QString::number(pid).toLatin1() );\n pidfile.close();\n } else {\n tSystemError(\"File open failed: %s\", qPrintable(pidfile.fileName()));\n }\n \n ret = app.exec();\n tSystemDebug(\"tfmanager returnCode:%d\", ret);\n manager->stop();\n \n if (ret == 1) { \/\/ means SIGHUP\n tSystemDebug(\"Restarts TreeFrog application servers\");\n \/\/continue;\n } else {\n break;\n }\n }\n \n if (!svrname.isEmpty()) { \/\/ UNIX domain file\n QFile(svrname).remove();\n }\n pidfile.remove(); \/\/ Removes the PID file\n return 0;\n}\n\n} \/\/ namespace TreeFrog\n\n\nint main(int argc, char *argv[])\n{\n#ifdef Q_OS_WIN\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i], \"-w\") == 0) {\n \/\/ Windows service mode\n SERVICE_TABLE_ENTRY entry[] = { { (LPTSTR)TEXT(\"\"), TreeFrog::winServiceMain }, { 0, 0 } };\n StartServiceCtrlDispatcher(entry);\n return 0;\n }\n }\n#endif\n return TreeFrog::managerMain(argc, argv);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * Copyright (C) 2011-2013 by Paul-Louis Ageneau *\n * paul-louis (at) ageneau (dot) org *\n * *\n * This file is part of Teapotnet. *\n * *\n * Teapotnet is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of *\n * the License, or (at your option) any later version. *\n * *\n * Teapotnet is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Affero General Public License for more details. *\n * *\n * You should have received a copy of the GNU Affero General Public *\n * License along with Teapotnet. *\n * If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n *************************************************************************\/\n\n#ifndef TPN_INCLUDE_H\n#define TPN_INCLUDE_H\n\n\/\/#define DEBUG\t\t\t1\n#define APPNAME\t\t\t\"Teapotnet\"\n#define APPVERSION\t\t\"0.10.1\"\n#define APPMAGIC\t\t 0x54504f54 \/\/ \"TPOT\"\n#define APPAUTHOR\t\t\"Paul-Louis Ageneau\"\n#define APPLINK\t\t\t\"https:\/\/teapotnet.org\/\"\n#define SOURCELINK\t\t\"https:\/\/teapotnet.org\/source\"\n#define HELPLINK\t\t\"https:\/\/teapotnet.org\/help\"\n#define DOWNLOADURL\t\t\"https:\/\/teapotnet.org\/download\"\n#define BUGSLINK\t\t\"mailto:bugs@teapotnet.org\"\n\n#include \"pla\/include.hpp\"\n#include \"pla\/string.hpp\"\n#include \"pla\/binarystring.hpp\"\n\nusing namespace pla;\n\nnamespace tpn\n{\n\ttypedef BinaryString Identifier;\n\ttypedef std::pair<Identifier, Identifier> IdentifierPair;\n}\n\n#endif\n\n<commit_msg>Removed useless debug flag, version 0.10.1 ready<commit_after>\/*************************************************************************\n * Copyright (C) 2011-2013 by Paul-Louis Ageneau *\n * paul-louis (at) ageneau (dot) org *\n * *\n * This file is part of Teapotnet. *\n * *\n * Teapotnet is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of *\n * the License, or (at your option) any later version. *\n * *\n * Teapotnet is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Affero General Public License for more details. *\n * *\n * You should have received a copy of the GNU Affero General Public *\n * License along with Teapotnet. *\n * If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n *************************************************************************\/\n\n#ifndef TPN_INCLUDE_H\n#define TPN_INCLUDE_H\n\n#define APPNAME\t\t\t\"Teapotnet\"\n#define APPVERSION\t\t\"0.10.1\"\n#define APPMAGIC\t\t 0x54504f54 \/\/ \"TPOT\"\n#define APPAUTHOR\t\t\"Paul-Louis Ageneau\"\n#define APPLINK\t\t\t\"https:\/\/teapotnet.org\/\"\n#define SOURCELINK\t\t\"https:\/\/teapotnet.org\/source\"\n#define HELPLINK\t\t\"https:\/\/teapotnet.org\/help\"\n#define DOWNLOADURL\t\t\"https:\/\/teapotnet.org\/download\"\n#define BUGSLINK\t\t\"mailto:bugs@teapotnet.org\"\n\n#include \"pla\/include.hpp\"\n#include \"pla\/string.hpp\"\n#include \"pla\/binarystring.hpp\"\n\nusing namespace pla;\n\nnamespace tpn\n{\n\ttypedef BinaryString Identifier;\n\ttypedef std::pair<Identifier, Identifier> IdentifierPair;\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"application.h\"\n#include \"TimeAlarms.h\"\n#include \"Adafruit_LEDBackpack.h\"\n#include \"Adafruit_GFX.h\"\n#undef now()\n\nbool isDST(int dayOfMonth, int month, int dayOfWeek, String rule);\nvoid refreshDisplayTime();\n\nAdafruit_7segment display = Adafruit_7segment();\n\nconst int ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;\nunsigned long lastSync = millis();\nint timeZone = -8; \/\/UTC time zone offset TODO: Must be set\/recieved from web\/cloud\nString DSTRule = \"US\"; \/\/US, EU, or OFF TODO: Must be set\/recieved from web\/cloud\nint DSTJumpHour; \/\/When DST takes effect\nint hourFormat = 12; \/\/12 or 24 TODO: Must be set\/recieved from web\/cloud\n\nvoid setup() {\n if(DSTRule == \"US\") {\n DSTJumpHour = 2;\n } else if(DSTRule == \"EU\") {\n DSTJumpHour = 1+timeZone;\n } else {\n DSTJumpHour = 0;\n }\n\n \/\/Set the proper time zone according to DST status\n Time.zone(isDST(Time.day(), Time.month(), Time.weekday(), DSTRule) ? timeZone+1 : timeZone);\n\n \/\/Setup the 7-segment display\n display.begin(0x70);\n display.setBrightness(15); \/\/TODO: adjust brightness to optimize for veneer\/time\n}\n\nvoid loop() {\n \/\/Request time synchronization from the Spark Cloud every 24 hours\n if (millis() - lastSync > ONE_DAY_MILLIS) {\n \/\/Spark.syncTime();\n lastSync = millis();\n }\n\n \/\/Update time zone at DSTJumpHour incase DST is now in effect\n if(Time.hour() == DSTJumpHour && Time.minute() == 0) {\n Time.zone(isDST(Time.day(), Time.month(), Time.weekday(), DSTRule) ? timeZone+1 : timeZone);\n }\n\n refreshDisplayTime();\n\n \/\/Delay for checking alarms\/timers\n Alarm.delay(500);\n}\n\n\/\/Return true if DST is currently observed\nbool isDST(int dayOfMonth, int month, int dayOfWeek, String rule) {\n if(rule == \"US\") {\n \/\/Month quick check\n if (month < 3 || month > 11) {\n return false;\n } else if (month > 3 && month < 11) {\n return true;\n }\n \/\/The US observes DST from the first Sunday of March\n \/\/The US observes DST until the first Sunday of November\n int previousSunday = dayOfMonth - dayOfWeek + 1;\n if (month == 3) {\n return previousSunday >= 1;\n } else {\n return previousSunday <= 0;\n }\n } else if(rule == \"EU\") {\n \/\/Month quick check\n if (month < 3 || month > 10) {\n return false;\n } else if (month > 3 && month < 10) {\n return true;\n }\n \/\/The EU observes DST from the last Sunday of March\n \/\/The EU observes DST until the last Sunday of November\n int previousSunday = dayOfMonth - dayOfWeek + 1;\n if(month == 3) {\n if(previousSunday+7>31) {\n return true;\n } else {\n return false;\n }\n } else {\n if(previousSunday+7>31) {\n return false;\n } else {\n return true;\n }\n }\n } else {\n return false;\n }\n}\n\n\/\/display the current time on the 7-segment display\nvoid refreshDisplayTime() {\n unsigned long currentTime = Time.now();\n int minute = Time.minute(currentTime);\n int hour;\n \n if(hourFormat == 12) {\n hour = Time.hourFormat12(currentTime);\n } else {\n hour = Time.hour(currentTime);\n }\n\n display.drawColon(true);\n if(hour\/10 != 0) {\n display.writeDigitNum(0, hour\/10);\n }\n display.writeDigitNum(1, hour%10);\n display.writeDigitNum(2, minute\/10);\n display.writeDigitNum(3, minute%10);\n display.writeDisplay();\n}\n<commit_msg>Fixes 7-Segment Display Issues<commit_after>#include \"application.h\"\n#include \"TimeAlarms.h\"\n#include \"Adafruit_LEDBackpack.h\"\n#include \"Adafruit_GFX.h\"\n#undef now()\n\nbool isDST(int dayOfMonth, int month, int dayOfWeek, String rule);\nvoid refreshDisplayTime();\n\nAdafruit_7segment display = Adafruit_7segment();\n\nconst int ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;\nunsigned long lastSync = millis();\nint timeZone = -8; \/\/UTC time zone offset TODO: Must be set\/recieved from web\/cloud\nString DSTRule = \"US\"; \/\/US, EU, or OFF TODO: Must be set\/recieved from web\/cloud\nint DSTJumpHour; \/\/When DST takes effect\nint hourFormat = 12; \/\/12 or 24 TODO: Must be set\/recieved from web\/cloud\n\nvoid setup() {\n if(DSTRule == \"US\") {\n DSTJumpHour = 2;\n } else if(DSTRule == \"EU\") {\n DSTJumpHour = 1+timeZone;\n } else {\n DSTJumpHour = 0;\n }\n\n \/\/Set the proper time zone according to DST status\n Time.zone(isDST(Time.day(), Time.month(), Time.weekday(), DSTRule) ? timeZone+1 : timeZone);\n\n \/\/Setup the 7-segment display\n display.begin(0x70);\n display.setBrightness(15); \/\/TODO: adjust brightness to optimize for veneer\/time\n}\n\nvoid loop() {\n \/\/Request time synchronization from the Spark Cloud every 24 hours\n if (millis() - lastSync > ONE_DAY_MILLIS) {\n Spark.syncTime();\n lastSync = millis();\n }\n\n \/\/Update time zone at DSTJumpHour incase DST is now in effect\n if(Time.hour() == DSTJumpHour && Time.minute() == 0) {\n Time.zone(isDST(Time.day(), Time.month(), Time.weekday(), DSTRule) ? timeZone+1 : timeZone);\n }\n\n refreshDisplayTime();\n\n \/\/Delay for checking alarms\/timers\n Alarm.delay(500);\n}\n\n\/\/Return true if DST is currently observed\nbool isDST(int dayOfMonth, int month, int dayOfWeek, String rule) {\n if(rule == \"US\") {\n \/\/Month quick check\n if (month < 3 || month > 11) {\n return false;\n } else if (month > 3 && month < 11) {\n return true;\n }\n \/\/The US observes DST from the first Sunday of March\n \/\/The US observes DST until the first Sunday of November\n int previousSunday = dayOfMonth - dayOfWeek + 1;\n if (month == 3) {\n return previousSunday >= 1;\n } else {\n return previousSunday <= 0;\n }\n } else if(rule == \"EU\") {\n \/\/Month quick check\n if (month < 3 || month > 10) {\n return false;\n } else if (month > 3 && month < 10) {\n return true;\n }\n \/\/The EU observes DST from the last Sunday of March\n \/\/The EU observes DST until the last Sunday of November\n int previousSunday = dayOfMonth - dayOfWeek + 1;\n if(month == 3) {\n if(previousSunday+7>31) {\n return true;\n } else {\n return false;\n }\n } else {\n if(previousSunday+7>31) {\n return false;\n } else {\n return true;\n }\n }\n } else {\n return false;\n }\n}\n\n\/\/display the current time on the 7-segment display\nvoid refreshDisplayTime() {\n unsigned long currentTime = Time.now();\n int minute = Time.minute(currentTime);\n int hour;\n int digits;\n\n if(hourFormat == 12) {\n hour = Time.hourFormat12(currentTime);\n } else {\n hour = Time.hour(currentTime);\n }\n\n digits = hour\/10*1000 + hour%10*100 + minute\/10*10 + minute%10;\n\n display.print(digits);\n display.drawColon(true);\n display.writeDisplay();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\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#include <folly\/Executor.h>\n\n#include <stdexcept>\n\n#include <glog\/logging.h>\n\n#include <folly\/ExceptionString.h>\n#include <folly\/Portability.h>\n#include <folly\/lang\/Exception.h>\n\nnamespace folly {\n\nvoid Executor::invokeCatchingExnsLog(\n char const* const prefix, std::exception const* const ex) {\n auto const message = \" threw unhandled \";\n if (ex) {\n LOG(ERROR) << prefix << message << exceptionStr(*ex);\n } else {\n auto ep = std::current_exception();\n LOG(ERROR) << prefix << message << exceptionStr(ep);\n }\n}\n\nvoid Executor::addWithPriority(Func, int8_t \/* priority *\/) {\n throw std::runtime_error(\n \"addWithPriority() is not implemented for this Executor\");\n}\n\nbool Executor::keepAliveAcquire() noexcept {\n return false;\n}\n\nvoid Executor::keepAliveRelease() noexcept {\n LOG(FATAL) << __func__ << \"() should not be called for folly::Executor types \"\n << \"which do not override keepAliveAcquire()\";\n}\n\n\/\/ Base case of permitting with no termination to avoid nullptr tests\nstatic ExecutorBlockingList emptyList{nullptr, {false, false, {}}};\n\n#if defined(FOLLY_TLS)\n\nextern constexpr bool const executor_blocking_list_enabled = true;\nthread_local ExecutorBlockingList* executor_blocking_list = &emptyList;\n\n#else\n\nextern constexpr bool const executor_blocking_list_enabled = false;\nExecutorBlockingList* executor_blocking_list = &emptyList;\n\n#endif\n\nOptional<ExecutorBlockingContext> getExecutorBlockingContext() noexcept {\n return \/\/\n !executor_blocking_list->curr.forbid ? none : \/\/\n make_optional(executor_blocking_list->curr);\n}\n\nExecutorBlockingGuard::ExecutorBlockingGuard(PermitTag) noexcept\n : list_{*executor_blocking_list} {\n if (executor_blocking_list_enabled) {\n list_.prev = executor_blocking_list;\n list_.curr.forbid = false;\n list_.curr.name = {};\n executor_blocking_list = &list_;\n }\n}\n\nExecutorBlockingGuard::ExecutorBlockingGuard(\n TrackTag, StringPiece name) noexcept\n : list_{*executor_blocking_list} {\n if (executor_blocking_list_enabled) {\n list_.prev = executor_blocking_list;\n list_.curr.forbid = true;\n list_.curr.name = name;\n executor_blocking_list = &list_;\n }\n}\n\nExecutorBlockingGuard::ExecutorBlockingGuard(\n ProhibitTag, StringPiece name) noexcept\n : list_{*executor_blocking_list} {\n if (executor_blocking_list_enabled) {\n list_.prev = executor_blocking_list;\n list_.curr.forbid = true;\n list_.curr.allowTerminationOnBlocking = true;\n list_.curr.name = name;\n executor_blocking_list = &list_;\n }\n}\n\nExecutorBlockingGuard::~ExecutorBlockingGuard() {\n if (executor_blocking_list_enabled) {\n if (executor_blocking_list != &list_) {\n terminate_with<std::logic_error>(\"dtor mismatch\");\n }\n executor_blocking_list = list_.prev;\n }\n}\n\n} \/\/ namespace folly\n<commit_msg>assume thread_local in Executor<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\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#include <folly\/Executor.h>\n\n#include <stdexcept>\n\n#include <glog\/logging.h>\n\n#include <folly\/ExceptionString.h>\n#include <folly\/Portability.h>\n#include <folly\/lang\/Exception.h>\n\nnamespace folly {\n\nvoid Executor::invokeCatchingExnsLog(\n char const* const prefix, std::exception const* const ex) {\n auto const message = \" threw unhandled \";\n if (ex) {\n LOG(ERROR) << prefix << message << exceptionStr(*ex);\n } else {\n auto ep = std::current_exception();\n LOG(ERROR) << prefix << message << exceptionStr(ep);\n }\n}\n\nvoid Executor::addWithPriority(Func, int8_t \/* priority *\/) {\n throw std::runtime_error(\n \"addWithPriority() is not implemented for this Executor\");\n}\n\nbool Executor::keepAliveAcquire() noexcept {\n return false;\n}\n\nvoid Executor::keepAliveRelease() noexcept {\n LOG(FATAL) << __func__ << \"() should not be called for folly::Executor types \"\n << \"which do not override keepAliveAcquire()\";\n}\n\n\/\/ Base case of permitting with no termination to avoid nullptr tests\nstatic ExecutorBlockingList emptyList{nullptr, {false, false, {}}};\n\nthread_local ExecutorBlockingList* executor_blocking_list = &emptyList;\n\nOptional<ExecutorBlockingContext> getExecutorBlockingContext() noexcept {\n return \/\/\n kIsMobile || !executor_blocking_list->curr.forbid ? none : \/\/\n make_optional(executor_blocking_list->curr);\n}\n\nExecutorBlockingGuard::ExecutorBlockingGuard(PermitTag) noexcept {\n if (!kIsMobile) {\n list_ = *executor_blocking_list;\n list_.prev = executor_blocking_list;\n list_.curr.forbid = false;\n list_.curr.name = {};\n executor_blocking_list = &list_;\n }\n}\n\nExecutorBlockingGuard::ExecutorBlockingGuard(\n TrackTag, StringPiece name) noexcept {\n if (!kIsMobile) {\n list_ = *executor_blocking_list;\n list_.prev = executor_blocking_list;\n list_.curr.forbid = true;\n list_.curr.name = name;\n executor_blocking_list = &list_;\n }\n}\n\nExecutorBlockingGuard::ExecutorBlockingGuard(\n ProhibitTag, StringPiece name) noexcept {\n if (!kIsMobile) {\n list_ = *executor_blocking_list;\n list_.prev = executor_blocking_list;\n list_.curr.forbid = true;\n list_.curr.allowTerminationOnBlocking = true;\n list_.curr.name = name;\n executor_blocking_list = &list_;\n }\n}\n\nExecutorBlockingGuard::~ExecutorBlockingGuard() {\n if (!kIsMobile) {\n if (executor_blocking_list != &list_) {\n terminate_with<std::logic_error>(\"dtor mismatch\");\n }\n executor_blocking_list = list_.prev;\n }\n}\n\n} \/\/ namespace folly\n<|endoftext|>"} {"text":"<commit_before>#include \"forth_common.th\"\n\n.global INBUF .global INPOS .global INLEN\n.L_INBUF_before:\nINBUF:\n#if TEST_LOOKUP\n .word 5 .utf32 \"words\"\n#endif\n .word 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n.L_INBUF_after:\nINPOS: .word 0\nINLEN: .word .L_INBUF_after - .L_INBUF_before\n\n.set link, 0\nhead(start,start): .word\n @NOOP\n\ntop: .word\n#if TEST_LOOKUP\n @TIB, @TO_IN, @FETCH, @ADD,\n @FIND,\n @LITERAL, @find_word, @RELOC, @SET_IP,\n#endif\n\n @TIB, @DUP, @TO_IN, @SWAP, @SUB, \/\/ tib used\n @IN_LEN, @SWAP, @SUB, \/\/ tib left\n @ACCEPT \/\/ count\n\nstrip_spaces: .word\n @TIB, @TO_IN, @FETCH, @ADD,\n @FETCHR, @BL, @CMP_EQ,\n IFNOT0(advance,done_stripping)\nadvance: .word\n @LITERAL, 1, @CHARS, @TO_IN, @ADDMEM,\n @LITERAL, @strip_spaces, @RELOC, @SET_IP\n\ndone_stripping: .word\n @TIB, @TO_IN, @FETCH, @ADD,\n @FETCHR, @EMIT,\n @EXIT\nfind_word: .word\n @TIB, @TO_IN, @FETCH, @ADD,\n @FIND,\n IFNOT0(found,notfound)\nnotfound: .word\n \/\/ TODO complain\n @LITERAL, 'X', @EMIT,\n @LITERAL, '\\n', @EMIT,\n @ABORT\n\nfound: .word\n \/\/@DROP, \/\/ drop flag for now, assume found\n @DUP, @EMIT_UNSIGNED, @BL, @EMIT, @LITERAL, ':', @EMIT, @BL, @EMIT, @CR,\n @DUP, @RELOC, @EMIT_UNSIGNED, @BL, @EMIT, @LITERAL, ':', @EMIT, @BL, @EMIT, @CR,\n @RELOC, @EXECUTE,\n\t\/\/@EXIT,\n\n \/\/ example of a computed branch\n @LITERAL, 0,\n IFNOT0(top,bottom)\nbottom: .word\n @NOOP\n\nwordstart: .word\n @KEY,\n @DUP, @LITERAL, '\\n', @CMP_EQ,\n IFNOT0(linedone,checkspace)\ncheckspace: .word\n @DUP, @BL, @CMP_EQ,\n IFNOT0(worddone,regular),\n @NOOP\nregular: .word\n @EMIT,\n @LITERAL, @wordstart, @RELOC, @SET_IP\nworddone: .word\n @DROP,\n @CR,\n @LITERAL, @wordstart, @RELOC, @SET_IP\nlinedone: .word\n @CR,\n @EXIT\n\n\/\/------------------------------------------------------------------------------\n\/\/ TODO explicit echoing\nhead(ACCEPT,ACCEPT): .word \/\/ ( c-addr +n1 -- +n2 )\n @ENTER,\n\n @OVER, @SWAP \/\/ C-addr c-addr n1\nL_ACCEPT_key: .word\n @KEY, \/\/ C-addr c-addr n1 c\n @DUP, @LITERAL, '\\n', @CMP_EQ, \/\/ C-addr c-addr n1 c flag\n IFNOT0(L_ACCEPT_exit,L_ACCEPT_regular)\nL_ACCEPT_regular: .word\n @ROT, \/\/ C-addr n1 c c-addr\n @TUCK, \/\/ C-addr n1 c-addr c c-addr\n @STOCHR, \/\/ C-addr n1 c-addr\n @LITERAL, 1, @CHARS, @ADD, \/\/ C-addr n1 c-addr++\n @SWAP, \/\/ C-addr c-addr n1\n @SUB_1, \/\/ C-addr c-addr n1--\n @DUP, @EQZ, \/\/ C-addr c-addr n1 flag\n IFNOT0(L_ACCEPT_done,L_ACCEPT_key)\nL_ACCEPT_exit: .word\n @DROP \/\/ C-addr c-addr n1\nL_ACCEPT_done: .word\n @DROP, \/\/ C-addr c-addr\n @SWAP, @SUB, \/\/ n2\n @EXIT\n\n\/\/------------------------------------------------------------------------------\n\nhead(IN_LEN,IN_LEN): .word\n @ENTER,\n @LITERAL, @INLEN, @RELOC, @FETCH,\n @EXIT\n\nhead(MASK4BITS,MASK4BITS): .word\n @ENTER,\n @LITERAL, 15, @AND,\n @EXIT\n\nhead(HEXTABLE,HEXTABLE): .word\n @ENTER,\n @LITERAL, @hexchars, @RELOC,\n @EXIT\n\nhexchars:\n .word '0','1','2','3','4','5','6','7',\n '8','9','A','B','C','D','E','F'\n\nhead(TOHEXCHAR,>HEXCHAR): .word\n @ENTER,\n @HEXTABLE, @ADD, @FETCHR,\n @EXIT\n\nhead(PUTS,PUTS): .word\n @ENTER,\n \/\/ TODO\n @EXIT\n\nhead(SET_IP,SET_IP): .word . + 1\n S <- S + 1\n I <- [S]\n goto(NEXT)\n\nhead(GET_IP,GET_IP): .word . + 1\n I -> [S]\n S <- S - 1\n goto(NEXT)\n\nhead(GET_PSP,GET_PSP): .word . + 1\n S -> [S]\n S <- S - 1\n goto(NEXT)\n\nhead(GET_RSP,GET_RSP): .word . + 1\n R -> [S]\n S <- S - 1\n goto(NEXT)\n\nhead(RELOC,RELOC): .word . + 1\n W <- [S + 1]\n W <- rel(W)\n W -> [S + 1]\n goto(NEXT)\n\n<commit_msg>Use new WORD<commit_after>#include \"forth_common.th\"\n#define TEST_LOOKUP 1\n\n.global INBUF .global INPOS .global INLEN\n.L_INBUF_before:\nINBUF:\n#if TEST_LOOKUP\n .utf32 \"words \"\n#endif\n .utf32 \" \"\n .utf32 \" \"\n.L_INBUF_after:\nINPOS: .word 0\nINLEN: .word .L_INBUF_after - .L_INBUF_before\n\n.set link, 0\nhead(start,start): .word\n @NOOP\n\ntop: .word\n#if TEST_LOOKUP\n @TIB, @TO_IN, @FETCH, @ADD,\n @BL, @WORD,\n @FIND,\n IFNOT0(found,notfound),\n#endif\n\n @TIB, @DUP, @TO_IN, @SWAP, @SUB, \/\/ tib used\n @IN_LEN, @SWAP, @SUB, \/\/ tib left\n @ACCEPT \/\/ count\n\nstrip_spaces: .word\n @TIB, @TO_IN, @FETCH, @ADD,\n @FETCHR, @BL, @CMP_EQ,\n IFNOT0(advance,done_stripping)\nadvance: .word\n @LITERAL, 1, @CHARS, @TO_IN, @ADDMEM,\n @LITERAL, @strip_spaces, @RELOC, @SET_IP\n\ndone_stripping: .word\n @TIB, @TO_IN, @FETCH, @ADD,\n @FETCHR, @EMIT,\n @EXIT\nfind_word: .word\n @TIB, @TO_IN, @FETCH, @ADD,\n @FIND,\n IFNOT0(found,notfound)\nnotfound: .word\n \/\/ TODO complain\n @LITERAL, 'X', @EMIT,\n @LITERAL, '\\n', @EMIT,\n @ABORT\n\nfound: .word\n \/\/@DROP, \/\/ drop flag for now, assume found\n @DUP, @EMIT_UNSIGNED, @BL, @EMIT, @LITERAL, ':', @EMIT, @BL, @EMIT, @CR,\n @DUP, @RELOC, @EMIT_UNSIGNED, @BL, @EMIT, @LITERAL, ':', @EMIT, @BL, @EMIT, @CR,\n @RELOC, @EXECUTE,\n\t\/\/@EXIT,\n\n \/\/ example of a computed branch\n @LITERAL, 0,\n IFNOT0(top,bottom)\nbottom: .word\n @NOOP\n\nwordstart: .word\n @KEY,\n @DUP, @LITERAL, '\\n', @CMP_EQ,\n IFNOT0(linedone,checkspace)\ncheckspace: .word\n @DUP, @BL, @CMP_EQ,\n IFNOT0(worddone,regular),\n @NOOP\nregular: .word\n @EMIT,\n @LITERAL, @wordstart, @RELOC, @SET_IP\nworddone: .word\n @DROP,\n @CR,\n @LITERAL, @wordstart, @RELOC, @SET_IP\nlinedone: .word\n @CR,\n @EXIT\n\n\/\/------------------------------------------------------------------------------\n\/\/ TODO explicit echoing\nhead(ACCEPT,ACCEPT): .word \/\/ ( c-addr +n1 -- +n2 )\n @ENTER,\n\n @OVER, @SWAP \/\/ C-addr c-addr n1\nL_ACCEPT_key: .word\n @KEY, \/\/ C-addr c-addr n1 c\n @DUP, @LITERAL, '\\n', @CMP_EQ, \/\/ C-addr c-addr n1 c flag\n IFNOT0(L_ACCEPT_exit,L_ACCEPT_regular)\nL_ACCEPT_regular: .word\n @ROT, \/\/ C-addr n1 c c-addr\n @TUCK, \/\/ C-addr n1 c-addr c c-addr\n @STOCHR, \/\/ C-addr n1 c-addr\n @LITERAL, 1, @CHARS, @ADD, \/\/ C-addr n1 c-addr++\n @SWAP, \/\/ C-addr c-addr n1\n @SUB_1, \/\/ C-addr c-addr n1--\n @DUP, @EQZ, \/\/ C-addr c-addr n1 flag\n IFNOT0(L_ACCEPT_done,L_ACCEPT_key)\nL_ACCEPT_exit: .word\n @DROP \/\/ C-addr c-addr n1\nL_ACCEPT_done: .word\n @DROP, \/\/ C-addr c-addr\n @SWAP, @SUB, \/\/ n2\n @EXIT\n\n\/\/------------------------------------------------------------------------------\n\nhead(IN_LEN,IN_LEN): .word\n @ENTER,\n @LITERAL, @INLEN, @RELOC, @FETCH,\n @EXIT\n\nhead(MASK4BITS,MASK4BITS): .word\n @ENTER,\n @LITERAL, 15, @AND,\n @EXIT\n\nhead(HEXTABLE,HEXTABLE): .word\n @ENTER,\n @LITERAL, @hexchars, @RELOC,\n @EXIT\n\nhexchars:\n .word '0','1','2','3','4','5','6','7',\n '8','9','A','B','C','D','E','F'\n\nhead(TOHEXCHAR,>HEXCHAR): .word\n @ENTER,\n @HEXTABLE, @ADD, @FETCHR,\n @EXIT\n\nhead(PUTS,PUTS): .word\n @ENTER,\n \/\/ TODO\n @EXIT\n\nhead(SET_IP,SET_IP): .word . + 1\n S <- S + 1\n I <- [S]\n goto(NEXT)\n\nhead(GET_IP,GET_IP): .word . + 1\n I -> [S]\n S <- S - 1\n goto(NEXT)\n\nhead(GET_PSP,GET_PSP): .word . + 1\n S -> [S]\n S <- S - 1\n goto(NEXT)\n\nhead(GET_RSP,GET_RSP): .word . + 1\n R -> [S]\n S <- S - 1\n goto(NEXT)\n\nhead(RELOC,RELOC): .word . + 1\n W <- [S + 1]\n W <- rel(W)\n W -> [S + 1]\n goto(NEXT)\n\nhead(SAYTOP,SAYTOP): .word\n @ENTER,\n @DUP, @EMIT_UNSIGNED, @CR,\n @EXIT\n\n<|endoftext|>"} {"text":"<commit_before>#include \"SshSetupHandler.hpp\"\n\n#include <sys\/wait.h>\n\nnamespace et {\nstring SshSetupHandler::SetupSsh(string user, string host, string host_alias,\n int port, string jumphost, int jport,\n bool kill) {\n string CLIENT_TERM(getenv(\"TERM\"));\n FILE *passkey_p = popen(\n \"env LC_ALL=C tr -dc \\\"a-zA-Z0-9\\\" < \/dev\/urandom | head -c 32\", \"r\");\n if (!passkey_p) {\n LOG(FATAL) << \"cannot generate passkey!\";\n exit(1);\n }\n char passkey_buffer[1024];\n fgets(passkey_buffer, sizeof(passkey_buffer), passkey_p);\n pclose(passkey_p);\n string passkey = string(passkey_buffer);\n\n FILE *id_p = popen(\n \"env LC_ALL=C tr -dc \\\"a-zA-Z0-9\\\" < \/dev\/urandom | head -c 16\", \"r\");\n if (!id_p) {\n LOG(FATAL) << \"cannot generate id!\";\n exit(1);\n }\n char id_buffer[1024];\n fgets(id_buffer, sizeof(id_buffer), id_p);\n pclose(id_p);\n string id = string(id_buffer);\n string SSH_SCRIPT_PREFIX{\n \"SERVER_TMP_DIR=${TMPDIR:-${TMP:-${TEMP:-\/tmp}}};\"\n \"TMPFILE=$(mktemp $SERVER_TMP_DIR\/et-server.XXXXXXXXXXXX);\"\n \"PASSKEY=\" +\n passkey +\n \";\"\n \"ID=\" +\n id +\n \";\"\n \"printf \\\"%s\/%s\\\\n\\\" \\\"$ID\\\" \\\"$PASSKEY\\\" > \\\"${TMPFILE}\\\";\"\n \"export TERM=\" +\n CLIENT_TERM +\n \";\"\n \"etserver --idpasskeyfile=\\\"${TMPFILE}\\\"\"};\n\n \/\/ Kill old ET sessions of the user\n if (kill && user != \"root\") {\n SSH_SCRIPT_PREFIX = \"pkill etserver -u \" + user + \";\" + SSH_SCRIPT_PREFIX;\n }\n string SSH_SCRIPT_DST = SSH_SCRIPT_PREFIX + \";true\";\n\n int link_client[2];\n char buf_client[4096];\n if (pipe(link_client) == -1) {\n LOG(FATAL) << \"pipe\";\n exit(1);\n }\n\n pid_t pid = fork();\n string SSH_USER_PREFIX = \"\";\n if (!user.empty()) {\n SSH_USER_PREFIX += user + \"@\";\n }\n if (!pid) {\n \/\/ start etserver daemon on dst.\n dup2(link_client[1], 1);\n close(link_client[0]);\n close(link_client[1]);\n if (!jumphost.empty()) {\n execl(\"\/usr\/bin\/ssh\", \"\/usr\/bin\/ssh\", \"-J\",\n (SSH_USER_PREFIX + jumphost).c_str(),\n (SSH_USER_PREFIX + host_alias).c_str(), (SSH_SCRIPT_DST).c_str(),\n NULL);\n } else {\n execl(\"\/usr\/bin\/ssh\", \"\/usr\/bin\/ssh\",\n (SSH_USER_PREFIX + host_alias).c_str(), (SSH_SCRIPT_DST).c_str(),\n NULL);\n }\n\n LOG(INFO) << \"execl error\";\n exit(1);\n } else if (pid < 0) {\n LOG(INFO) << \"Failed to fork\";\n exit(1);\n } else {\n close(link_client[1]);\n wait(NULL);\n int nbytes = read(link_client[0], buf_client, sizeof(buf_client));\n try {\n if (nbytes <= 0 || split(string(buf_client), ':').size() != 2 ||\n split(string(buf_client), ':')[0] != \"IDPASSKEY\") {\n cout << \"Error: The Eternal Terminal daemon is not running. \"\n \"Please (re)start the et daemon on the server.\"\n << endl;\n exit(1);\n }\n auto idpasskey = split(string(buf_client), ':')[1];\n idpasskey = idpasskey.substr(0, 16 + 1 + 32);\n auto idpasskey_splited = split(idpasskey, '\/');\n string returned_id = idpasskey_splited[0];\n string returned_passkey = idpasskey_splited[1];\n if (returned_id == id && returned_passkey == passkey) {\n LOG(INFO) << \"etserver started\";\n } else {\n LOG(FATAL) << \"client\/server idpasskey doesn't match: \" << id\n << \" != \" << returned_id << \" or \" << passkey\n << \" != \" << returned_passkey;\n }\n } catch (const runtime_error &err) {\n cout << \"Error initializing connection\" << err.what() << endl;\n }\n \/\/ start jumpclient daemon on jumphost.\n if (!jumphost.empty()) {\n \/* If jumphost is set, we need to pass dst host and port to jumphost\n * and connect to jumphost here *\/\n int link_jump[2];\n char buf_jump[4096];\n if (pipe(link_jump) == -1) {\n LOG(FATAL) << \"pipe\";\n exit(1);\n }\n pid_t pid_jump = fork();\n if (pid_jump < 0) {\n LOG(FATAL) << \"Failed to fork\";\n exit(1);\n } else if (pid_jump == 0) {\n dup2(link_jump[1], 1);\n close(link_jump[0]);\n close(link_jump[1]);\n string cmdoptions = \"\";\n cmdoptions +=\n \" --jump --dsthost=\" + host + \" --dstport=\" + to_string(port);\n string SSH_SCRIPT_JUMP = SSH_SCRIPT_PREFIX + cmdoptions + \";true\";\n execl(\"\/usr\/bin\/ssh\", \"\/usr\/bin\/ssh\", jumphost.c_str(),\n (SSH_SCRIPT_JUMP).c_str(), NULL);\n } else {\n close(link_jump[1]);\n wait(NULL);\n int nbytes = read(link_jump[0], buf_jump, sizeof(buf_jump));\n if (nbytes <= 0) {\n LOG(FATAL) << \"etserver jumpclient failed to start\";\n exit(1);\n }\n try {\n auto idpasskey = split(string(buf_jump), ':')[1];\n idpasskey.erase(idpasskey.find_last_not_of(\" \\n\\r\\t\") + 1);\n idpasskey = idpasskey.substr(0, 16 + 1 + 32);\n auto idpasskey_splited = split(idpasskey, '\/');\n string returned_id = idpasskey_splited[0];\n string returned_passkey = idpasskey_splited[1];\n if (returned_id == id && returned_passkey == passkey) {\n LOG(INFO) << \"jump client started.\";\n } else {\n LOG(INFO) << \"ID \" << id;\n LOG(INFO) << \"Received ID \" << returned_id;\n LOG(INFO) << \"PASSKEY \" << passkey;\n LOG(INFO) << \"Received PASSKEY \" << returned_passkey;\n LOG(INFO) << \"client\/server idpasskey doesn't match\";\n exit(1);\n }\n } catch (const runtime_error &err) {\n cout << \"Error initializing connection\" << err.what() << endl;\n }\n }\n }\n }\n return id + \"\/\" + passkey;\n}\n} \/\/ namespace et\n<commit_msg>use ssh in PATH instead hardcoded<commit_after>#include \"SshSetupHandler.hpp\"\n\n#include <sys\/wait.h>\n\nnamespace et {\nstring SshSetupHandler::SetupSsh(string user, string host, string host_alias,\n int port, string jumphost, int jport,\n bool kill) {\n string CLIENT_TERM(getenv(\"TERM\"));\n FILE *passkey_p = popen(\n \"env LC_ALL=C tr -dc \\\"a-zA-Z0-9\\\" < \/dev\/urandom | head -c 32\", \"r\");\n if (!passkey_p) {\n LOG(FATAL) << \"cannot generate passkey!\";\n exit(1);\n }\n char passkey_buffer[1024];\n fgets(passkey_buffer, sizeof(passkey_buffer), passkey_p);\n pclose(passkey_p);\n string passkey = string(passkey_buffer);\n\n FILE *id_p = popen(\n \"env LC_ALL=C tr -dc \\\"a-zA-Z0-9\\\" < \/dev\/urandom | head -c 16\", \"r\");\n if (!id_p) {\n LOG(FATAL) << \"cannot generate id!\";\n exit(1);\n }\n char id_buffer[1024];\n fgets(id_buffer, sizeof(id_buffer), id_p);\n pclose(id_p);\n string id = string(id_buffer);\n string SSH_SCRIPT_PREFIX{\n \"SERVER_TMP_DIR=${TMPDIR:-${TMP:-${TEMP:-\/tmp}}};\"\n \"TMPFILE=$(mktemp $SERVER_TMP_DIR\/et-server.XXXXXXXXXXXX);\"\n \"PASSKEY=\" +\n passkey +\n \";\"\n \"ID=\" +\n id +\n \";\"\n \"printf \\\"%s\/%s\\\\n\\\" \\\"$ID\\\" \\\"$PASSKEY\\\" > \\\"${TMPFILE}\\\";\"\n \"export TERM=\" +\n CLIENT_TERM +\n \";\"\n \"etserver --idpasskeyfile=\\\"${TMPFILE}\\\"\"};\n\n \/\/ Kill old ET sessions of the user\n if (kill && user != \"root\") {\n SSH_SCRIPT_PREFIX = \"pkill etserver -u \" + user + \";\" + SSH_SCRIPT_PREFIX;\n }\n string SSH_SCRIPT_DST = SSH_SCRIPT_PREFIX + \";true\";\n\n int link_client[2];\n char buf_client[4096];\n if (pipe(link_client) == -1) {\n LOG(FATAL) << \"pipe\";\n exit(1);\n }\n\n pid_t pid = fork();\n string SSH_USER_PREFIX = \"\";\n if (!user.empty()) {\n SSH_USER_PREFIX += user + \"@\";\n }\n if (!pid) {\n \/\/ start etserver daemon on dst.\n dup2(link_client[1], 1);\n close(link_client[0]);\n close(link_client[1]);\n if (!jumphost.empty()) {\n execlp(\"ssh\", \"ssh\", \"-J\", (SSH_USER_PREFIX + jumphost).c_str(),\n (SSH_USER_PREFIX + host_alias).c_str(), (SSH_SCRIPT_DST).c_str(),\n NULL);\n } else {\n execlp(\"ssh\", \"ssh\", (SSH_USER_PREFIX + host_alias).c_str(),\n (SSH_SCRIPT_DST).c_str(), NULL);\n }\n\n LOG(INFO) << \"execl error\";\n exit(1);\n } else if (pid < 0) {\n LOG(INFO) << \"Failed to fork\";\n exit(1);\n } else {\n close(link_client[1]);\n wait(NULL);\n int nbytes = read(link_client[0], buf_client, sizeof(buf_client));\n try {\n if (nbytes <= 0 || split(string(buf_client), ':').size() != 2 ||\n split(string(buf_client), ':')[0] != \"IDPASSKEY\") {\n cout << \"Error: The Eternal Terminal daemon is not running. \"\n \"Please (re)start the et daemon on the server.\"\n << endl;\n exit(1);\n }\n auto idpasskey = split(string(buf_client), ':')[1];\n idpasskey = idpasskey.substr(0, 16 + 1 + 32);\n auto idpasskey_splited = split(idpasskey, '\/');\n string returned_id = idpasskey_splited[0];\n string returned_passkey = idpasskey_splited[1];\n if (returned_id == id && returned_passkey == passkey) {\n LOG(INFO) << \"etserver started\";\n } else {\n LOG(FATAL) << \"client\/server idpasskey doesn't match: \" << id\n << \" != \" << returned_id << \" or \" << passkey\n << \" != \" << returned_passkey;\n }\n } catch (const runtime_error &err) {\n cout << \"Error initializing connection\" << err.what() << endl;\n }\n \/\/ start jumpclient daemon on jumphost.\n if (!jumphost.empty()) {\n \/* If jumphost is set, we need to pass dst host and port to jumphost\n * and connect to jumphost here *\/\n int link_jump[2];\n char buf_jump[4096];\n if (pipe(link_jump) == -1) {\n LOG(FATAL) << \"pipe\";\n exit(1);\n }\n pid_t pid_jump = fork();\n if (pid_jump < 0) {\n LOG(FATAL) << \"Failed to fork\";\n exit(1);\n } else if (pid_jump == 0) {\n dup2(link_jump[1], 1);\n close(link_jump[0]);\n close(link_jump[1]);\n string cmdoptions = \"\";\n cmdoptions +=\n \" --jump --dsthost=\" + host + \" --dstport=\" + to_string(port);\n string SSH_SCRIPT_JUMP = SSH_SCRIPT_PREFIX + cmdoptions + \";true\";\n execlp(\"ssh\", \"ssh\", jumphost.c_str(), (SSH_SCRIPT_JUMP).c_str(), NULL);\n } else {\n close(link_jump[1]);\n wait(NULL);\n int nbytes = read(link_jump[0], buf_jump, sizeof(buf_jump));\n if (nbytes <= 0) {\n LOG(FATAL) << \"etserver jumpclient failed to start\";\n exit(1);\n }\n try {\n auto idpasskey = split(string(buf_jump), ':')[1];\n idpasskey.erase(idpasskey.find_last_not_of(\" \\n\\r\\t\") + 1);\n idpasskey = idpasskey.substr(0, 16 + 1 + 32);\n auto idpasskey_splited = split(idpasskey, '\/');\n string returned_id = idpasskey_splited[0];\n string returned_passkey = idpasskey_splited[1];\n if (returned_id == id && returned_passkey == passkey) {\n LOG(INFO) << \"jump client started.\";\n } else {\n LOG(INFO) << \"ID \" << id;\n LOG(INFO) << \"Received ID \" << returned_id;\n LOG(INFO) << \"PASSKEY \" << passkey;\n LOG(INFO) << \"Received PASSKEY \" << returned_passkey;\n LOG(INFO) << \"client\/server idpasskey doesn't match\";\n exit(1);\n }\n } catch (const runtime_error &err) {\n cout << \"Error initializing connection\" << err.what() << endl;\n }\n }\n }\n }\n return id + \"\/\" + passkey;\n}\n} \/\/ namespace et\n<|endoftext|>"} {"text":"<commit_before>\n#include \"ev3api.h\"\n#include \"Clock.h\"\n#include \"app.h\"\n#include \"SerialData.h\"\n#include \"SerialSendTask.h\"\n#include \"SerialReceiveTask.h\"\n#include \"InOutManager.h\"\n#include \"Strategy.h\"\n#include \"StrategyManager.h\"\n#include \"BlockMoveStrategy.h\"\n#include \"ETSumoStrategy.h\"\n#include \"SelfPositionManager.h\"\n#include \"BlockMoveManager.h\"\n#include \"SoundPlayTask.h\"\n#include \"HSLColor.h\"\n#include \"FieldMap.h\"\n\nusing ev3api::Clock;\n\n\/\/ C++からC言語ライブラリをインクルードするため\nextern \"C\"{\n\t#include \"image.h\"\n}\n\n\n\/\/#include \"libcpp-test.h\"\n\n#define DEBUG\n\n#ifdef DEBUG\n#define _debug(x) (x)\n#else\n#define _debug(x)\n#endif\n\nimageData_t* image;\nuint32_t sleepTime = 0;\n\nvoid Draw()\n{\n static char buf[256];\n \n InOutManager* IOManager = InOutManager::GetInstance();\n\n sprintf(buf, \"Power: %4d, %4d, S:%d\",IOManager->OutputData.LeftMotorPower, IOManager->OutputData.RightMotorPower, sleepTime);\n ev3_lcd_draw_string(buf, 0, 0);\n\n SelfPositionManager* SpManager = SelfPositionManager::GetInstance();\n sprintf(buf, \"X:%4.1f, Y:%5.1f. A:%3.1f \",SpManager->RobotPoint.X, SpManager->RobotPoint.Y, SpManager->RobotAngle);\n ev3_lcd_draw_string(buf, 0, 12);\n\n sprintf(buf, \"P: %2.1f, D: %4.1f \", CurrentPID.PGain, CurrentPID.DGain);\n ev3_lcd_draw_string(buf, 0, 24);\n\n BlockMoveManager * BmManager = BlockMoveManager::GetInstance();\n sprintf(buf, \"C:%d src:%2d, dst:%2d, Ang:%3d \", \n BmManager->CurrentCommand.BlockColor,\n BmManager->CurrentCommand.SourceBlockPosition,\n BmManager->CurrentCommand.DestinationBlockPosition,\n BmManager->GetSrcWaypointAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y));\n ev3_lcd_draw_string(buf, 0, 36);\n\n auto src = BmManager->GetSrcWaypoint();\n sprintf(buf, \"W* No:%d srcX:%2d, srcY:%2d \", \n BmManager->CurrentCommand.ApproachWayPoint[BmManager->CurrentSrcWaypointNo],\n (int)src->X,\n (int)src->Y);\n ev3_lcd_draw_string(buf, 0, 48);\n\n RGBColor rgbMap = FieldMap::GetInstance()->GetRGBColor(\n SpManager->RobotPoint.X, SpManager->RobotPoint.Y);\n HSLColor hslMap = HSLColor::FromRGB(rgbMap.R, rgbMap.G, rgbMap.B);\n\n sprintf(buf, \"MAP-H:%3.2f,S:%3.2f,L%3.2f\",\n hslMap.Hue,\n hslMap.Saturation,\n hslMap.Luminosity);\n ev3_lcd_draw_string(buf, 0, 60);\n\n sprintf(buf, \"SEN-H:%3.2f,S:%3.2f,L%3.2f \" ,IOManager->HSLValue.Hue,\n IOManager->HSLValue.Saturation,\n IOManager->HSLValue.Luminosity);\n ev3_lcd_draw_string(buf, 0, 72);\n \n sprintf(buf, \"LFood: %1.4f\", ColorDecision::GetLikelihoodLuminosity(hslMap.Luminosity, IOManager->HSLValue.Luminosity));\n ev3_lcd_draw_string(buf, 0, 84);\n \n}\n\nvoid Refresh()\n{\n InOutManager* IOManager = InOutManager::GetInstance();\n IOManager->ReadInputSensor();\n\n SelfPositionManager* SpManager = SelfPositionManager::GetInstance();\n SpManager->UpdatePosition(IOManager->InputData.LeftMotorAngle, IOManager->InputData.RightMotorAngle); \n Draw();\n}\n\nvoid main_task(intptr_t unused) \n{\n PlaySound(SensorInitialStart);\n InOutManager* IOManager = InOutManager::GetInstance();\n FieldMap * Map = FieldMap::GetInstance();\n Map->ReadImage(\"\/ev3rt\/image\/Field.bmp\");\n\n \n StrategyManager *StManager = new StrategyManager();\n PlaySound(SensorInitialEnd); \n \nRESTART_:\n \/\/ 初期位置\n SelfPositionData pData;\n\/*\n pData.Angle = 0;\n pData.PositionX = 1360;\n pData.PositionY = 2900;\n*\/\n \/\/ 初期位置(ライントレース)\n pData.Angle = 270;\n pData.PositionX = 5190;\n pData.PositionY = 380;\n\n SelfPositionManager* SpManager = SelfPositionManager::GetInstance();\n SpManager->ResetPosition(pData);\n\n int i = 0;\n while(IOManager->InputData.TouchSensor == 0){\n Refresh();\n\t\tdly_tsk(10);\n }\n\n while(IOManager->InputData.TouchSensor == 1){\n Refresh();\n\t\tdly_tsk(10);\n }\n\n ev3_lcd_fill_rect(0, 0, EV3_LCD_WIDTH, EV3_LCD_HEIGHT, EV3_LCD_WHITE);\n \n \/\/ StManager->SetStrategy(new BlockMoveStrategy(StManager));\n\n \/\/ ET相撲NEO確認用\n\/\/ StManager->SetStrategy(new ETSumoStrategy(StManager));\n\n \/\/ 初期値をラインの中心として格納\n auto lts = new LineTraceStrategy(StManager);\n\/\/ lts->CenterValue = IOManager->InputData.ReflectLight;\n lts->CenterValue = 120;\n\n \/\/ ライントレース戦略にて動作開始\n StManager->SetStrategy(lts);\n Clock* clock = new Clock();\n while(1)\n {\n uint32_t baseTime = clock->now();\n \n \/\/ 入力情報更新\n Refresh();\n\n StManager->Run();\n \n if(i > 200) {\n i = 0;\n ev3_lcd_fill_rect(0, 0, EV3_LCD_WIDTH, EV3_LCD_HEIGHT, EV3_LCD_WHITE);\n }\n\n i++;\n \n \/\/ ボタン押されたらリスタート\n if(IOManager->InputData.TouchSensor == 1){\n IOManager->OutputData.LeftMotorPower = 0;\n IOManager->OutputData.RightMotorPower = 0;\n IOManager->DownARMMotor();\n IOManager->WriteOutputMotor();\n\n while(IOManager->InputData.TouchSensor == 1) {\n Refresh(); \n dly_tsk(10);\n }\n goto RESTART_;\n }\n \/\/ 出力情報更新\n IOManager->WriteOutputMotor();\n sleepTime = clock->now() - baseTime;\n\t\tdly_tsk(50 - sleepTime);\n }\n}\n<commit_msg>ログ表示機能を追加<commit_after>\n#include \"ev3api.h\"\n#include \"Clock.h\"\n#include \"app.h\"\n#include \"SerialData.h\"\n#include \"SerialSendTask.h\"\n#include \"SerialReceiveTask.h\"\n#include \"InOutManager.h\"\n#include \"Strategy.h\"\n#include \"StrategyManager.h\"\n#include \"BlockMoveStrategy.h\"\n#include \"ETSumoStrategy.h\"\n#include \"SelfPositionManager.h\"\n#include \"BlockMoveManager.h\"\n#include \"SoundPlayTask.h\"\n#include \"HSLColor.h\"\n#include \"FieldMap.h\"\n\nusing ev3api::Clock;\n\n\/\/ C++からC言語ライブラリをインクルードするため\nextern \"C\"{\n\t#include \"image.h\"\n}\n\n\n\/\/#include \"libcpp-test.h\"\n\n#define DEBUG\n\n#ifdef DEBUG\n#define _debug(x) (x)\n#else\n#define _debug(x)\n#endif\n\nimageData_t* image;\nuint32_t sleepTime = 0;\n\nvoid Draw()\n{\n static char buf[256];\n \n InOutManager* IOManager = InOutManager::GetInstance();\n\n sprintf(buf, \"Power: %4d, %4d, S:%d \",IOManager->OutputData.LeftMotorPower, IOManager->OutputData.RightMotorPower, sleepTime);\n ev3_lcd_draw_string(buf, 0, 0);\n\n SelfPositionManager* SpManager = SelfPositionManager::GetInstance();\n sprintf(buf, \"X:%4.1f, Y:%5.1f. A:%3.1f \",SpManager->RobotPoint.X, SpManager->RobotPoint.Y, SpManager->RobotAngle);\n ev3_lcd_draw_string(buf, 0, 12);\n\n sprintf(buf, \"P: %2.1f, D: %4.1f \", CurrentPID.PGain, CurrentPID.DGain);\n ev3_lcd_draw_string(buf, 0, 24);\n\n BlockMoveManager * BmManager = BlockMoveManager::GetInstance();\n sprintf(buf, \"C:%d src:%2d, dst:%2d, Ang:%3d \", \n BmManager->CurrentCommand.BlockColor,\n BmManager->CurrentCommand.SourceBlockPosition,\n BmManager->CurrentCommand.DestinationBlockPosition,\n BmManager->GetSrcWaypointAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y));\n ev3_lcd_draw_string(buf, 0, 36);\n\n auto src = BmManager->GetSrcWaypoint();\n sprintf(buf, \"W* No:%d srcX:%2d, srcY:%2d \", \n BmManager->CurrentCommand.ApproachWayPoint[BmManager->CurrentSrcWaypointNo],\n (int)src->X,\n (int)src->Y);\n ev3_lcd_draw_string(buf, 0, 48);\n\n RGBColor rgbMap = FieldMap::GetInstance()->GetRGBColor(\n SpManager->RobotPoint.X, SpManager->RobotPoint.Y);\n HSLColor hslMap = HSLColor::FromRGB(rgbMap.R, rgbMap.G, rgbMap.B);\n\n sprintf(buf, \"MAP-H:%3.2f,S:%3.2f,L%3.2f\",\n hslMap.Hue,\n hslMap.Saturation,\n hslMap.Luminosity);\n ev3_lcd_draw_string(buf, 0, 60);\n\n sprintf(buf, \"SEN-H:%3.2f,S:%3.2f,L%3.2f \" ,IOManager->HSLValue.Hue,\n IOManager->HSLValue.Saturation,\n IOManager->HSLValue.Luminosity);\n ev3_lcd_draw_string(buf, 0, 72);\n \n sprintf(buf, \"LFood: %1.4f\", ColorDecision::GetLikelihoodLuminosity(hslMap.Luminosity, IOManager->HSLValue.Luminosity));\n ev3_lcd_draw_string(buf, 0, 84);\n \n}\n\nvoid Refresh()\n{\n InOutManager* IOManager = InOutManager::GetInstance();\n IOManager->ReadInputSensor();\n\n SelfPositionManager* SpManager = SelfPositionManager::GetInstance();\n SpManager->UpdatePosition(IOManager->InputData.LeftMotorAngle, IOManager->InputData.RightMotorAngle); \n Draw();\n}\n\nvoid main_task(intptr_t unused) \n{\n PlaySound(SensorInitialStart);\n InOutManager* IOManager = InOutManager::GetInstance();\n FieldMap * Map = FieldMap::GetInstance();\n Map->ReadImage(\"\/ev3rt\/image\/Field.bmp\");\n StrategyManager *StManager = new StrategyManager();\n PlaySound(SensorInitialEnd); \n \nRESTART_:\n \/\/ 初期位置\n SelfPositionData pData;\n\/*\n pData.Angle = 0;\n pData.PositionX = 1360;\n pData.PositionY = 2900;\n*\/\n \/\/ 初期位置(ライントレース)\n pData.Angle = 270;\n pData.PositionX = 5190;\n pData.PositionY = 380;\n\n SelfPositionManager* SpManager = SelfPositionManager::GetInstance();\n SpManager->ResetPosition(pData);\n\n int i = 0;\n while(IOManager->InputData.TouchSensor == 0){\n Refresh();\n\t\tdly_tsk(10);\n }\n\n while(IOManager->InputData.TouchSensor == 1){\n Refresh();\n\t\tdly_tsk(10);\n }\n\n ev3_lcd_fill_rect(0, 0, EV3_LCD_WIDTH, EV3_LCD_HEIGHT, EV3_LCD_WHITE);\n \n \/\/ StManager->SetStrategy(new BlockMoveStrategy(StManager));\n\n \/\/ ET相撲NEO確認用\n\/\/ StManager->SetStrategy(new ETSumoStrategy(StManager));\n\n \/\/ 初期値をラインの中心として格納\n auto lts = new LineTraceStrategy(StManager);\n\/\/ lts->CenterValue = IOManager->InputData.ReflectLight;\n lts->CenterValue = 120;\n\n \/\/ ライントレース戦略にて動作開始\n StManager->SetStrategy(lts);\n Clock* clock = new Clock();\n while(1)\n {\n uint32_t baseTime = clock->now();\n \n \/\/ 入力情報更新\n Refresh();\n\n StManager->Run();\n \n if(i > 200) {\n i = 0;\n ev3_lcd_fill_rect(0, 0, EV3_LCD_WIDTH, EV3_LCD_HEIGHT, EV3_LCD_WHITE);\n }\n\n i++;\n \n \/\/ ボタン押されたらリスタート\n if(IOManager->InputData.TouchSensor == 1){\n IOManager->OutputData.LeftMotorPower = 0;\n IOManager->OutputData.RightMotorPower = 0;\n IOManager->DownARMMotor();\n IOManager->WriteOutputMotor();\n\n while(IOManager->InputData.TouchSensor == 1) {\n Refresh(); \n dly_tsk(10);\n }\n goto RESTART_;\n }\n \/\/ 出力情報更新\n IOManager->WriteOutputMotor();\n sleepTime = clock->now() - baseTime;\n\t\tdly_tsk(50 - sleepTime);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 BrewPi\/Elco Jacobs\/Matthew McGowan.\n *\n * This file is part of BrewPi.\n *\n * BrewPi 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 3 of the License, or\n * (at your option) any later version.\n *\n * BrewPi 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 BrewPi. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"Brewpi.h\"\n#include \"fixstl.h\"\n#include \"UI.h\"\n#include \"Buzzer.h\"\n#include \"eGuiSettings.h\"\n#include \"ConnectedDevicesManager.h\"\n#include \"PiLink.h\"\n#include \"Display.h\"\n#include \"UIController.h\"\n#include \"Actuator.h\"\n#include \"Board.h\"\n\n#include \"..\/eGUI_screens\/devicetest\/device_test_screen.h\"\n#include \"..\/eGUI_screens\/controller\/controller_screen.h\"\n#include \"..\/eGUI_screens\/startup\/startup_screen.h\"\n#include \"..\/eGUI_screens\/screen_model.h\"\n\n\nextern \"C\" {\n#include \"d4d.h\"\n}\n\nDisplayType realDisplay;\nDisplayType DISPLAY_REF display = realDisplay;\n\n\neGuiSettingsClass eGuiSettings;\n\nuint8_t UI::init() {\n eGuiSettings.init();\n display.init();\n\n if (!D4D_Init(NULL))\n return 1;\n\n D4D_SetOrientation(D4D_ORIENT_LANDSCAPE);\n #if BREWPI_BUZZER\n\tbuzzer.init(!shieldIsV2());\n\tbuzzer.beep(2, 100);\n #endif\n\n return 0;\n}\n\nuint32_t UI::showStartupPage()\n{\n \/\/ Check if touch screen has been calibrated\n if (!eGuiSettings.loadTouchCalib()) {\n \/\/ could not load valid settings from flash memory\n calibrateTouchScreen();\n }\n\n uiController.beginStartup();\n return 0;\n}\n\n\/**\n * Since the startup page waits for the user, it has variable duration. This allows\n * the main loop to continue running while the startup screen is displayed.\n *\/\nvoid UI::showControllerPage() {\n display.printStationaryText();\n display.printState();\n}\n\nextern ValueActuator alarm;\nvoid UI::ticks()\n{\n D4D_TimeTickPut();\n D4D_CheckTouchScreen();\n D4D_Poll();\n\n #if BREWPI_BUZZER\n\tbuzzer.setActive(alarm.isActive() && !buzzer.isActive());\n #endif\n}\n\nUIController uiController;\n\nvoid UI::update()\n{\n uiController.updateScreen();\n\n display.printState();\n display.printAllTemperatures();\n display.printMode();\n display.updateBacklight();\n}\n\n\nTimer* timer = nullptr;\n\nvoid cancelCalibration()\n{\n D4D_InterruptCalibrationScreen();\n}\n\nvoid createTimer()\n{\n timer = new Timer(3*1000, cancelCalibration);\n if (timer)\n timer->start();\n}\n\nvoid destroyTimer()\n{\n delete timer;\n timer = NULL;\n}\n\n\n\/**\n * Show touch screen calibration screen store settings afterwards\n *\/\nvoid calibrateTouchScreen() {\n\n createTimer();\n D4D_CalibrateTouchScreen();\n destroyTimer();\n eGuiSettings.storeTouchCalib();\n\n}\n\nbool UI::inStartup() {\n return uiController.inStartup();\n}\n<commit_msg>increase timeout from 3s to 60s.<commit_after>\/*\n * Copyright 2015 BrewPi\/Elco Jacobs\/Matthew McGowan.\n *\n * This file is part of BrewPi.\n *\n * BrewPi 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 3 of the License, or\n * (at your option) any later version.\n *\n * BrewPi 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 BrewPi. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"Brewpi.h\"\n#include \"fixstl.h\"\n#include \"UI.h\"\n#include \"Buzzer.h\"\n#include \"eGuiSettings.h\"\n#include \"ConnectedDevicesManager.h\"\n#include \"PiLink.h\"\n#include \"Display.h\"\n#include \"UIController.h\"\n#include \"Actuator.h\"\n#include \"Board.h\"\n\n#include \"..\/eGUI_screens\/devicetest\/device_test_screen.h\"\n#include \"..\/eGUI_screens\/controller\/controller_screen.h\"\n#include \"..\/eGUI_screens\/startup\/startup_screen.h\"\n#include \"..\/eGUI_screens\/screen_model.h\"\n\n\nextern \"C\" {\n#include \"d4d.h\"\n}\n\nDisplayType realDisplay;\nDisplayType DISPLAY_REF display = realDisplay;\n\n\neGuiSettingsClass eGuiSettings;\n\nuint8_t UI::init() {\n eGuiSettings.init();\n display.init();\n\n if (!D4D_Init(NULL))\n return 1;\n\n D4D_SetOrientation(D4D_ORIENT_LANDSCAPE);\n #if BREWPI_BUZZER\n\tbuzzer.init(!shieldIsV2());\n\tbuzzer.beep(2, 100);\n #endif\n\n return 0;\n}\n\nuint32_t UI::showStartupPage()\n{\n \/\/ Check if touch screen has been calibrated\n if (!eGuiSettings.loadTouchCalib()) {\n \/\/ could not load valid settings from flash memory\n calibrateTouchScreen();\n }\n\n uiController.beginStartup();\n return 0;\n}\n\n\/**\n * Since the startup page waits for the user, it has variable duration. This allows\n * the main loop to continue running while the startup screen is displayed.\n *\/\nvoid UI::showControllerPage() {\n display.printStationaryText();\n display.printState();\n}\n\nextern ValueActuator alarm;\nvoid UI::ticks()\n{\n D4D_TimeTickPut();\n D4D_CheckTouchScreen();\n D4D_Poll();\n\n #if BREWPI_BUZZER\n\tbuzzer.setActive(alarm.isActive() && !buzzer.isActive());\n #endif\n}\n\nUIController uiController;\n\nvoid UI::update()\n{\n uiController.updateScreen();\n\n display.printState();\n display.printAllTemperatures();\n display.printMode();\n display.updateBacklight();\n}\n\n\nTimer* timer = nullptr;\n\nvoid cancelCalibration()\n{\n D4D_InterruptCalibrationScreen();\n}\n\nvoid createTimer()\n{\n timer = new Timer(60*1000, cancelCalibration);\n if (timer)\n timer->start();\n}\n\nvoid destroyTimer()\n{\n delete timer;\n timer = NULL;\n}\n\n\n\/**\n * Show touch screen calibration screen store settings afterwards\n *\/\nvoid calibrateTouchScreen() {\n\n createTimer();\n D4D_CalibrateTouchScreen();\n destroyTimer();\n eGuiSettings.storeTouchCalib();\n\n}\n\nbool UI::inStartup() {\n return uiController.inStartup();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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 * @file\n * @brief Predicate --- Standard Predicate Implementation\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n *\/\n\n#include <ironbee\/predicate\/standard_predicate.hpp>\n\n#include <ironbee\/predicate\/call_factory.hpp>\n#include <ironbee\/predicate\/call_helpers.hpp>\n#include <ironbee\/predicate\/functional.hpp>\n#include <ironbee\/predicate\/merge_graph.hpp>\n#include <ironbee\/predicate\/validate.hpp>\n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\nnamespace Standard {\n\nnamespace {\n\nconst string CALL_NAME_ISLITERAL(\"isLiteral\");\nconst string CALL_FINISH_ALL(\"finishAll\");\nconst string CALL_FINISH_SOME(\"finishAny\");\n\n\/\/! Scoped Memory Pool Lite\nstatic ScopedMemoryPoolLite s_mpl;\n\/\/! True Value\nstatic const Value c_true_value =\n Value::create_string(s_mpl, ByteString::create(s_mpl, \"\"));\n\/\/! True literal.\nstatic const node_p c_true(new Literal(c_true_value));\n\/\/! False literal.\nstatic const node_p c_false(new Literal());\n\n\/**\n * Is argument a literal?\n **\/\nclass IsLiteral :\n public Call\n{\npublic:\n \/\/! See Call::name()\n const std::string& name() const\n {\n return CALL_NAME_ISLITERAL;\n }\n\n \/**\n * See Node::transform().\n *\n * Will replace self with true or false based on child.\n **\/\n bool transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n )\n {\n node_p me = shared_from_this();\n node_p replacement = c_false;\n if (children().front()->is_literal()) {\n replacement = c_true;\n }\n merge_graph.replace(me, replacement);\n\n return true;\n }\n\n \/\/! See Node::eval_calculate()\n void eval_calculate(GraphEvalState&, EvalContext) const\n {\n BOOST_THROW_EXCEPTION(\n einval() << errinfo_what(\n \"IsLiteral evaluated. Did you not transform?\"\n )\n );\n }\n\n \/\/! See Node::validate().\n bool validate(NodeReporter reporter) const\n {\n return Validate::n_children(reporter, 1);\n }\n};\n\n\/**\n * Is argument finished?\n **\/\nclass IsFinished :\n public Functional::Primary\n{\npublic:\n \/\/! Constructor.\n IsFinished() : Functional::Primary(0, 1) {}\n\nprotected:\n \/\/! See Functional::Primary::eval_primary().\n void eval_primary(\n MemoryManager mm,\n const node_cp& me,\n boost::any& substate,\n NodeEvalState& my_state,\n const Functional::value_vec_t& secondary_args,\n const NodeEvalState& primary_arg\n ) const\n {\n if (primary_arg.is_finished()) {\n my_state.finish(c_true_value);\n }\n }\n};\n\n\/**\n * Is primary argument a list longer than specified length.\n **\/\nclass IsLonger :\n public Functional::Primary\n{\npublic:\n \/\/! Constructor.\n IsLonger() : Functional::Primary(0, 2) {}\n\nprotected:\n \/\/! See Functional::Base::validate_argument().\n void validate_argument(\n int n,\n Value v,\n NodeReporter reporter\n ) const\n {\n if (n == 0) {\n Validate::value_is_type(v, Value::NUMBER, reporter);\n }\n }\n\n \/\/! See Functional::Primary::eval_primary().\n void eval_primary(\n MemoryManager mm,\n const node_cp& me,\n boost::any& substate,\n NodeEvalState& my_state,\n const Functional::value_vec_t& secondary_args,\n const NodeEvalState& primary_arg\n ) const\n {\n if (! primary_arg.value()) {\n return;\n }\n if (primary_arg.value().type() != Value::LIST) {\n my_state.finish();\n return;\n }\n if (\n primary_arg.value().as_list().size() >\n size_t(secondary_args[0].as_number())\n ) {\n my_state.finish(c_true_value);\n return;\n }\n if (primary_arg.is_finished()) {\n my_state.finish();\n }\n }\n};\n\n\/**\n * Is argument a list?\n **\/\nclass IsList :\n public Functional::Primary\n{\npublic:\n \/\/! Constructor.\n IsList() : Functional::Primary(0, 1) {}\n\nprotected:\n \/\/! See Functional::Primary::eval_primary().\n void eval_primary(\n MemoryManager mm,\n const node_cp& me,\n boost::any& substate,\n NodeEvalState& my_state,\n const Functional::value_vec_t& secondary_args,\n const NodeEvalState& primary_arg\n ) const\n {\n if (! primary_arg.value().is_null()) {\n if (primary_arg.value().type() == Value::LIST) {\n my_state.finish(c_true_value);\n }\n else {\n my_state.finish();\n }\n }\n }\n};\n\n\/**\n * Finish with the value of the first child that finishes.\n *\n * This is unlike OR in that the requirements are less. A node only need\n * finish, not finish true.\n **\/\n class FinishAny :\n public Call\n{\npublic:\n \/\/! See Call:name()\n virtual const std::string& name() const;\n\n \/\/! See Node::validate()\n virtual bool validate(NodeReporter reporter) const;\n\n \/**\n * If any node is a literal or transformed to finished,\n * this node replaces itself with that node.\n *\n * @sa See Node::trasform()\n *\/\n virtual bool transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n );\n\nprotected:\n virtual void eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n ) const;\n};\n\n\/**\n * Finish with a list of the values. This finishes when all values are finished.\n *\n * This is effectively list.\n **\/\n class FinishAll :\n public Call\n{\npublic:\n \/\/! See Call:name()\n virtual const std::string& name() const;\n\n \/\/! See Node::validate()\n virtual bool validate(NodeReporter reporter) const;\n\n \/**\n * If all nodesa are a literal or transformed to finished,\n * this node replaces itself with a constant list of those values.\n *\n * @sa See Node::trasform()\n *\/\n virtual bool transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n );\n\nprotected:\n\n virtual void eval_initialize(\n GraphEvalState& graph_eval_state,\n EvalContext context\n ) const;\n\n virtual void eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n ) const;\n};\n\nbool FinishAll::transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n)\n{\n node_p me = shared_from_this();\n\n if (children().size() == 0) {\n node_p replacement(new Literal());\n merge_graph.replace(me, replacement);\n return true;\n }\n\n {\n boost::shared_ptr<ScopedMemoryPoolLite> mpl(\n new ScopedMemoryPoolLite()\n );\n IronBee::List<Value> my_value = IronBee::List<Value>::create(*mpl);\n bool replace = true;\n\n BOOST_FOREACH(const node_p& child, children()) {\n if (! child->is_literal()) {\n replace = false;\n break;\n }\n Value v = literal_value(child);\n my_value.push_back(v);\n }\n\n if (replace) {\n node_p replacement(new Literal(mpl,\n Value::alias_list(*mpl, my_value)\n ));\n merge_graph.replace(me, replacement);\n return true;\n }\n }\n\n return false;\n}\n\nconst std::string& FinishAll::name() const\n{\n return CALL_FINISH_ALL;\n}\n\nbool FinishAll::validate(NodeReporter reporter) const\n{\n return true;\n}\n\nvoid FinishAll::eval_initialize(\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n NodeEvalState& my_state = graph_eval_state[index()];\n node_list_t::const_iterator last_unfinished = children().begin();\n my_state.state() = last_unfinished;\n my_state.setup_local_list(context.memory_manager());\n}\n\nvoid FinishAll::eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n NodeEvalState& my_state = graph_eval_state[index()];\n\n node_list_t::const_iterator last_unfinished =\n boost::any_cast<node_list_t::const_iterator>(my_state.state());\n while (last_unfinished != children().end()) {\n size_t index = (*last_unfinished)->index();\n graph_eval_state.eval(*last_unfinished, context);\n Value v = graph_eval_state.value((*last_unfinished)->index());\n if (! graph_eval_state.is_finished(index)) {\n break;\n }\n\n my_state.append_to_list(v);\n ++last_unfinished;\n }\n\n if (last_unfinished == children().end()) {\n my_state.finish();\n }\n\n my_state.state() = last_unfinished;\n}\n\nbool FinishAny::transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n)\n{\n node_p me = shared_from_this();\n\n if (children().size() == 0) {\n node_p replacement(new Literal());\n merge_graph.replace(me, replacement);\n return true;\n }\n\n BOOST_FOREACH(const node_p& child, children()) {\n if (child->is_literal()) {\n node_p c(child);\n merge_graph.replace(me, c);\n return true;\n }\n }\n\n return false;\n}\n\nconst std::string& FinishAny::name() const\n{\n return CALL_FINISH_SOME;\n}\n\nbool FinishAny::validate(NodeReporter reporter) const\n{\n return true;\n}\n\nvoid FinishAny::eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n for (\n node_list_t::const_iterator i = children().begin();\n i != children().end();\n ++i\n )\n {\n graph_eval_state.eval(*i, context);\n\n if (graph_eval_state.is_finished((*i)->index())) {\n Value v = graph_eval_state.value((*i)->index());\n NodeEvalState& my_state = graph_eval_state[index()];\n my_state.finish(v);\n return;\n }\n }\n}\n\n} \/\/ Anonymous\n\nvoid load_predicate(CallFactory& to)\n{\n to\n .add<IsLiteral>()\n .add<FinishAll>()\n .add<FinishAny>()\n .add(\"isFinished\", Functional::generate<IsFinished>)\n .add(\"isLonger\", Functional::generate<IsLonger>)\n .add(\"isList\", Functional::generate<IsList>)\n ;\n}\n\n} \/\/ Standard\n} \/\/ Predicate\n} \/\/ IronBee\n<commit_msg>standard_predicate.cpp: FinishAll incorrectly did not attempt to finish nodes past the first-unfinished node. This change corrects that.<commit_after>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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 * @file\n * @brief Predicate --- Standard Predicate Implementation\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n *\/\n\n#include <ironbee\/predicate\/standard_predicate.hpp>\n\n#include <ironbee\/predicate\/call_factory.hpp>\n#include <ironbee\/predicate\/call_helpers.hpp>\n#include <ironbee\/predicate\/functional.hpp>\n#include <ironbee\/predicate\/merge_graph.hpp>\n#include <ironbee\/predicate\/validate.hpp>\n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\nnamespace Standard {\n\nnamespace {\n\nconst string CALL_NAME_ISLITERAL(\"isLiteral\");\nconst string CALL_FINISH_ALL(\"finishAll\");\nconst string CALL_FINISH_SOME(\"finishAny\");\n\n\/\/! Scoped Memory Pool Lite\nstatic ScopedMemoryPoolLite s_mpl;\n\/\/! True Value\nstatic const Value c_true_value =\n Value::create_string(s_mpl, ByteString::create(s_mpl, \"\"));\n\/\/! True literal.\nstatic const node_p c_true(new Literal(c_true_value));\n\/\/! False literal.\nstatic const node_p c_false(new Literal());\n\n\/**\n * Is argument a literal?\n **\/\nclass IsLiteral :\n public Call\n{\npublic:\n \/\/! See Call::name()\n const std::string& name() const\n {\n return CALL_NAME_ISLITERAL;\n }\n\n \/**\n * See Node::transform().\n *\n * Will replace self with true or false based on child.\n **\/\n bool transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n )\n {\n node_p me = shared_from_this();\n node_p replacement = c_false;\n if (children().front()->is_literal()) {\n replacement = c_true;\n }\n merge_graph.replace(me, replacement);\n\n return true;\n }\n\n \/\/! See Node::eval_calculate()\n void eval_calculate(GraphEvalState&, EvalContext) const\n {\n BOOST_THROW_EXCEPTION(\n einval() << errinfo_what(\n \"IsLiteral evaluated. Did you not transform?\"\n )\n );\n }\n\n \/\/! See Node::validate().\n bool validate(NodeReporter reporter) const\n {\n return Validate::n_children(reporter, 1);\n }\n};\n\n\/**\n * Is argument finished?\n **\/\nclass IsFinished :\n public Functional::Primary\n{\npublic:\n \/\/! Constructor.\n IsFinished() : Functional::Primary(0, 1) {}\n\nprotected:\n \/\/! See Functional::Primary::eval_primary().\n void eval_primary(\n MemoryManager mm,\n const node_cp& me,\n boost::any& substate,\n NodeEvalState& my_state,\n const Functional::value_vec_t& secondary_args,\n const NodeEvalState& primary_arg\n ) const\n {\n if (primary_arg.is_finished()) {\n my_state.finish(c_true_value);\n }\n }\n};\n\n\/**\n * Is primary argument a list longer than specified length.\n **\/\nclass IsLonger :\n public Functional::Primary\n{\npublic:\n \/\/! Constructor.\n IsLonger() : Functional::Primary(0, 2) {}\n\nprotected:\n \/\/! See Functional::Base::validate_argument().\n void validate_argument(\n int n,\n Value v,\n NodeReporter reporter\n ) const\n {\n if (n == 0) {\n Validate::value_is_type(v, Value::NUMBER, reporter);\n }\n }\n\n \/\/! See Functional::Primary::eval_primary().\n void eval_primary(\n MemoryManager mm,\n const node_cp& me,\n boost::any& substate,\n NodeEvalState& my_state,\n const Functional::value_vec_t& secondary_args,\n const NodeEvalState& primary_arg\n ) const\n {\n if (! primary_arg.value()) {\n return;\n }\n if (primary_arg.value().type() != Value::LIST) {\n my_state.finish();\n return;\n }\n if (\n primary_arg.value().as_list().size() >\n size_t(secondary_args[0].as_number())\n ) {\n my_state.finish(c_true_value);\n return;\n }\n if (primary_arg.is_finished()) {\n my_state.finish();\n }\n }\n};\n\n\/**\n * Is argument a list?\n **\/\nclass IsList :\n public Functional::Primary\n{\npublic:\n \/\/! Constructor.\n IsList() : Functional::Primary(0, 1) {}\n\nprotected:\n \/\/! See Functional::Primary::eval_primary().\n void eval_primary(\n MemoryManager mm,\n const node_cp& me,\n boost::any& substate,\n NodeEvalState& my_state,\n const Functional::value_vec_t& secondary_args,\n const NodeEvalState& primary_arg\n ) const\n {\n if (! primary_arg.value().is_null()) {\n if (primary_arg.value().type() == Value::LIST) {\n my_state.finish(c_true_value);\n }\n else {\n my_state.finish();\n }\n }\n }\n};\n\n\/**\n * Finish with the value of the first child that finishes.\n *\n * This is unlike OR in that the requirements are less. A node only need\n * finish, not finish true.\n **\/\n class FinishAny :\n public Call\n{\npublic:\n \/\/! See Call:name()\n virtual const std::string& name() const;\n\n \/\/! See Node::validate()\n virtual bool validate(NodeReporter reporter) const;\n\n \/**\n * If any node is a literal or transformed to finished,\n * this node replaces itself with that node.\n *\n * @sa See Node::trasform()\n *\/\n virtual bool transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n );\n\nprotected:\n virtual void eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n ) const;\n};\n\n\/**\n * Finish with a list of the values. This finishes when all values are finished.\n *\n * This is effectively list.\n **\/\n class FinishAll :\n public Call\n{\npublic:\n \/\/! See Call:name()\n virtual const std::string& name() const;\n\n \/\/! See Node::validate()\n virtual bool validate(NodeReporter reporter) const;\n\n \/**\n * If all nodesa are a literal or transformed to finished,\n * this node replaces itself with a constant list of those values.\n *\n * @sa See Node::trasform()\n *\/\n virtual bool transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n );\n\nprotected:\n\n virtual void eval_initialize(\n GraphEvalState& graph_eval_state,\n EvalContext context\n ) const;\n\n virtual void eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n ) const;\n};\n\nbool FinishAll::transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n)\n{\n node_p me = shared_from_this();\n\n if (children().size() == 0) {\n node_p replacement(new Literal());\n merge_graph.replace(me, replacement);\n return true;\n }\n\n {\n boost::shared_ptr<ScopedMemoryPoolLite> mpl(\n new ScopedMemoryPoolLite()\n );\n IronBee::List<Value> my_value = IronBee::List<Value>::create(*mpl);\n bool replace = true;\n\n BOOST_FOREACH(const node_p& child, children()) {\n if (! child->is_literal()) {\n replace = false;\n break;\n }\n Value v = literal_value(child);\n my_value.push_back(v);\n }\n\n if (replace) {\n node_p replacement(new Literal(mpl,\n Value::alias_list(*mpl, my_value)\n ));\n merge_graph.replace(me, replacement);\n return true;\n }\n }\n\n return false;\n}\n\nconst std::string& FinishAll::name() const\n{\n return CALL_FINISH_ALL;\n}\n\nbool FinishAll::validate(NodeReporter reporter) const\n{\n return true;\n}\n\nvoid FinishAll::eval_initialize(\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n NodeEvalState& my_state = graph_eval_state[index()];\n node_list_t::const_iterator last_unfinished = children().begin();\n my_state.state() = last_unfinished;\n my_state.setup_local_list(context.memory_manager());\n}\n\nvoid FinishAll::eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n NodeEvalState& my_state = graph_eval_state[index()];\n\n node_list_t::const_iterator last_unfinished = children().end();\n\n for (\n node_list_t::const_iterator i =\n boost::any_cast<node_list_t::const_iterator>(my_state.state());\n i != children().end();\n ++i\n )\n {\n size_t index = (*i)->index();\n\n \/\/ We may re-check a node that is already done on subsequent evals.\n if (graph_eval_state.is_finished(index)) {\n continue;\n }\n\n \/\/ If the node is not finished, eval it.\n graph_eval_state.eval(*i, context);\n\n \/\/ If the value is finished, record its value.\n if (graph_eval_state.is_finished(index)) {\n Value v = graph_eval_state.value(index);\n my_state.append_to_list(v);\n }\n \/\/ If i is not finished and last_unfinished == end, update it.\n else if (last_unfinished == children().end()) {\n last_unfinished = i;\n }\n }\n\n \/\/ If last_unfinished was never updated to an unfinished i, we are done!\n if (last_unfinished == children().end()) {\n my_state.finish();\n }\n\n \/\/ Record where we observed the first unfinished node.\n my_state.state() = last_unfinished;\n}\n\nbool FinishAny::transform(\n MergeGraph& merge_graph,\n const CallFactory& call_factory,\n Environment environment,\n NodeReporter reporter\n)\n{\n node_p me = shared_from_this();\n\n if (children().size() == 0) {\n node_p replacement(new Literal());\n merge_graph.replace(me, replacement);\n return true;\n }\n\n BOOST_FOREACH(const node_p& child, children()) {\n if (child->is_literal()) {\n node_p c(child);\n merge_graph.replace(me, c);\n return true;\n }\n }\n\n return false;\n}\n\nconst std::string& FinishAny::name() const\n{\n return CALL_FINISH_SOME;\n}\n\nbool FinishAny::validate(NodeReporter reporter) const\n{\n return true;\n}\n\nvoid FinishAny::eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n for (\n node_list_t::const_iterator i = children().begin();\n i != children().end();\n ++i\n )\n {\n graph_eval_state.eval(*i, context);\n\n if (graph_eval_state.is_finished((*i)->index())) {\n Value v = graph_eval_state.value((*i)->index());\n NodeEvalState& my_state = graph_eval_state[index()];\n my_state.finish(v);\n return;\n }\n }\n}\n\n} \/\/ Anonymous\n\nvoid load_predicate(CallFactory& to)\n{\n to\n .add<IsLiteral>()\n .add<FinishAll>()\n .add<FinishAny>()\n .add(\"isFinished\", Functional::generate<IsFinished>)\n .add(\"isLonger\", Functional::generate<IsLonger>)\n .add(\"isList\", Functional::generate<IsList>)\n ;\n}\n\n} \/\/ Standard\n} \/\/ Predicate\n} \/\/ IronBee\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <string>\n\nnamespace csi{\n\t\/\/ The control sequence introducer string which prefixes every control sequence.\n\tconst std::string prefix = \"\\033[\";\n\n\t\/\/ Enums for style codes.\n\tenum class style_code{\n\t\tbold = 1,\n\t\titalics = 3,\n\t\tunderlined = 4,\n\t\tstrikethrough = 9,\n\t\tinverse = 7,\n\t\tenable_offset = 0, \/\/ e.g. bold on is 1 and italics on is 3.\n\t\tdisable_offset = 20 \/\/ e.g. bold off is 21 and italics off is 23.\n\t};\n\n\t\/\/ Return a control sequence string which enables a text style.\n\tstd::string enable(style_code style);\n\n\t\/\/ Return a control sequence string which disables a text style.\n\tstd::string disable(style_code style);\n\n\t\/\/ Return a control sequence string which enables or disables any text styles.\n\tstd::string style(\n\t\tbool bold = false,\n\t\tbool italics = false,\n\t\tbool underlined = false,\n\t\tbool strikethrough = false\n\t);\n\n\t\/\/ Enums for color codes.\n\tenum class color_code{\n\t\tnone = 9, \/\/ The terminal's default colors.\n\t\tblack = 0,\n\t\tred = 1,\n\t\tgreen = 2,\n\t\tyellow = 3,\n\t\tblue = 4,\n\t\tmagenta = 5,\n\t\tcyan = 6,\n\t\twhite = 7,\n\t\tforeground_offset = 30, \/\/ e.g. green foreground is 32.\n\t\tbackground_offset = 40 \/\/ e.g. green background is 42.\n\t};\n\n\t\/\/ Returns a control sequence string which sets the text color.\n\tstd::string foreground(color_code color = color_code::none);\n\n\t\/\/ Returns a control sequence string which sets the text background color.\n\tstd::string background(color_code color = color_code::none);\n\n\t\/* Return a control sequence string which selects foreground and background\n\t * text colors.\n\t * Additionally, the colors can be inverted to make the text appear\n\t * highlighted. *\/\n\tstd::string color(\n\t\tcolor_code foreground = color_code::none,\n\t\tcolor_code background = color_code::none,\n\t\tbool inverse = false\n\t);\n\n\t\/\/ Returns a control sequence string which moves the cursor up.\n\tstd::string cursor_up(int rows = 1);\n\n\t\/\/ Returns a control sequence string which moves the cursor down.\n\tstd::string cursor_down(int rows = 1);\n\n\t\/\/ Returns a control sequence string which moves the cursor forward.\n\tstd::string cursor_forward(int columns = 1);\n\n\t\/\/ Returns a control sequence string which moves the cursor back.\n\tstd::string cursor_back(int columns = 1);\n\n\t\/* Returns a control sequence string which moves the cursor to.\n\t * the first column of the next line *\/\n\tstd::string cursor_next_line(int lines = 1);\n\n\t\/* Returns a control sequence string which moves the cursor to.\n\t * the first column of the previous line *\/\n\tstd::string cursor_previous_line(int lines = 1);\n\n\t\/\/ Returns a control sequence string which moves the cursor anywhere.\n\tstd::string cursor_position(int row = 1, int column = 1);\n\n\t\/\/ Enums for all the erase modes\n\tenum class erase_mode{\n\t\tto_end = 0, \/\/ Erase from the cursor to end of the line\/display\n\t\tto_beginning = 1, \/\/ Erase from the cursor to beginning of the line\/display\n\t\tall = 2 \/\/ Erase the entire line\/display\n\t};\n\n\t\/\/ Returns a control sequence string which erases the display\n\tstd::string erase_display(erase_mode mode = erase_mode::all);\n\n\t\/\/ Returns a control sequence string which erases the current line\n\tstd::string erase_line(erase_mode mode = erase_mode::all);\n\n\t\/\/ Returns a control sequence string which scrolls the display up\n\tstd::string scroll_up(int lines = 1);\n\n\t\/\/ Returns a control sequence string which scrolls the display down\n\tstd::string scroll_down(int lines = 1);\n\n\t\/* Returns a control sequence string which selects a graphics setting\n\t * with a code manually *\/\n\tstd::string select_graphic_rendition(int code = 0);\n\n\t\/\/ Control sequence string which saves the cursor position\n\tconst std::string save_cursor_position = prefix + \"s\";\n\n\t\/\/ Control sequence string which restores the cursor position\n\tconst std::string restore_cursor_position = prefix + \"u\";\n};\n<commit_msg>Improve consistency<commit_after>#pragma once\n\n#include <string>\n\nnamespace csi{\n\t\/\/ Control sequence introducer string which prefixes every control sequence.\n\tconst std::string prefix = \"\\033[\";\n\n\t\/\/ Enum for style codes.\n\tenum class style_code{\n\t\tbold = 1,\n\t\titalics = 3,\n\t\tunderlined = 4,\n\t\tstrikethrough = 9,\n\t\tinverse = 7,\n\t\tenable_offset = 0, \/\/ e.g. enable bold is 1 and enable italics is 3.\n\t\tdisable_offset = 20 \/\/ e.g. disable bold is 21 and disable italics is 23.\n\t};\n\n\t\/\/ Return a control sequence string which enables a text style.\n\tstd::string enable(style_code style);\n\n\t\/\/ Return a control sequence string which disables a text style.\n\tstd::string disable(style_code style);\n\n\t\/\/ Return a control sequence string which enables or disables text styles.\n\tstd::string style(\n\t\tbool bold = false,\n\t\tbool italics = false,\n\t\tbool underlined = false,\n\t\tbool strikethrough = false\n\t);\n\n\t\/\/ Enum for color codes.\n\tenum class color_code{\n\t\tnone = 9, \/\/ The terminal's default colors.\n\t\tblack = 0,\n\t\tred = 1,\n\t\tgreen = 2,\n\t\tyellow = 3,\n\t\tblue = 4,\n\t\tmagenta = 5,\n\t\tcyan = 6,\n\t\twhite = 7,\n\t\tforeground_offset = 30, \/\/ e.g. green foreground is 32.\n\t\tbackground_offset = 40 \/\/ e.g. green background is 42.\n\t};\n\n\t\/\/ Return a control sequence string which sets the text color.\n\tstd::string foreground(color_code color = color_code::none);\n\n\t\/\/ Return a control sequence string which sets the text background color.\n\tstd::string background(color_code color = color_code::none);\n\n\t\/* Return a control sequence string which selects foreground and background\n\t * text colors.\n\t * Additionally, the colors can be inverted to make the text appear\n\t * highlighted. *\/\n\tstd::string color(\n\t\tcolor_code foreground = color_code::none,\n\t\tcolor_code background = color_code::none,\n\t\tbool inverse = false\n\t);\n\n\t\/\/ Return a control sequence string which moves the cursor up.\n\tstd::string cursor_up(int rows = 1);\n\n\t\/\/ Return a control sequence string which moves the cursor down.\n\tstd::string cursor_down(int rows = 1);\n\n\t\/\/ Return a control sequence string which moves the cursor forward.\n\tstd::string cursor_forward(int columns = 1);\n\n\t\/\/ Return a control sequence string which moves the cursor back.\n\tstd::string cursor_back(int columns = 1);\n\n\t\/* Return a control sequence string which moves the cursor to.\n\t * the first column of the next line *\/\n\tstd::string cursor_next_line(int lines = 1);\n\n\t\/* Return a control sequence string which moves the cursor to.\n\t * the first column of the previous line *\/\n\tstd::string cursor_previous_line(int lines = 1);\n\n\t\/\/ Return a control sequence string which moves the cursor anywhere.\n\tstd::string cursor_position(int row = 1, int column = 1);\n\n\t\/\/ Enum for all the erase modes.\n\tenum class erase_mode{\n\t\tto_end = 0, \/\/ Erase from the cursor to end of the line\/display.\n\t\tto_beginning = 1, \/\/ Erase from the cursor to beginning of the line\/display.\n\t\tall = 2 \/\/ Erase the entire line\/display.\n\t};\n\n\t\/\/ Return a control sequence string which erases the display.\n\tstd::string erase_display(erase_mode mode = erase_mode::all);\n\n\t\/\/ Return a control sequence string which erases the current line.\n\tstd::string erase_line(erase_mode mode = erase_mode::all);\n\n\t\/\/ Return a control sequence string which scrolls the display up.\n\tstd::string scroll_up(int lines = 1);\n\n\t\/\/ Return a control sequence string which scrolls the display down.\n\tstd::string scroll_down(int lines = 1);\n\n\t\/* Return a control sequence string which selects a graphics setting.\n\t * Check online for SGR codes. *\/\n\tstd::string select_graphic_rendition(int code = 0);\n\n\t\/\/ Control sequence string which saves the cursor position.\n\tconst std::string save_cursor_position = prefix + \"s\";\n\n\t\/\/ Control sequence string which restores the cursor position.\n\tconst std::string restore_cursor_position = prefix + \"u\";\n};\n<|endoftext|>"} {"text":"<commit_before>\r\n#include \"xlsx_num_format_context.h\"\r\n#include \"xlsx_complex_number_format.h\"\r\n\r\n#include <sstream>\r\n#include <map>\r\n\r\n#include \"..\\odf\\odfcontext.h\"\r\n\r\n\r\nnamespace cpdoccore {\r\nnamespace oox {\r\n\r\n\r\nclass num_format_context::Impl2\r\n{\r\npublic:\r\n complex_number_format complex_number_format_;\r\n};\r\n\r\nclass num_format_context::Impl\r\n{\r\npublic:\r\n Impl(): in_convert_style_(false)\r\n {}\r\n\r\npublic:\r\n std::wstring current_style_name_;\r\n std::wstringstream stream_;\r\n\r\n void reset_current()\r\n {\r\n current_style_name_ = L\"\";\r\n stream_.str(std::wstring()); \r\n in_convert_style_ = false;\r\n }\r\n\r\n std::wstring last_format_;\r\n\r\n bool in_convert_style_;\r\n};\r\n\r\nnum_format_context::num_format_context(odf_reader::odf_read_context & odfContext): odf_context_(odfContext), impl_(new Impl()), impl2_(new Impl2())\r\n{\r\n}\r\n\r\nnum_format_context::~num_format_context()\r\n{\r\n}\r\n\r\nvoid num_format_context::start_format(const std::wstring & style_name)\r\n{\r\n impl_->reset_current();\r\n impl_->current_style_name_ = style_name;\r\n impl_->in_convert_style_ = true;\r\n}\r\n\r\nstd::wostream & num_format_context::output()\r\n{\r\n return impl_->stream_;\r\n}\r\n\r\nvoid num_format_context::end_format()\r\n{ \r\n impl_->last_format_ = impl_->stream_.str();\r\n impl_->reset_current();\r\n}\r\n\r\nstd::wstring num_format_context::get_last_format() const\r\n{\r\n return impl_->last_format_;\r\n}\r\n\r\nvoid num_format_context::start_complex_format()\r\n{\r\n impl2_->complex_number_format_.reset();\r\n}\r\n\r\nvoid num_format_context::add_format(std::wstring const & cond, std::wstring const & format)\r\n{\r\n impl2_->complex_number_format_.add_format(cond, format);\r\n}\r\n\r\nvoid num_format_context::end_complex_format()\r\n{\r\n impl_->last_format_ = impl2_->complex_number_format_.result_value();\r\n}\r\n\r\n}\r\n}\r\n<commit_msg>fix linux build<commit_after>\r\n#include \"xlsx_num_format_context.h\"\r\n#include \"xlsx_complex_number_format.h\"\r\n\r\n#include <sstream>\r\n#include <map>\r\n\r\n#include \"..\/odf\/odfcontext.h\"\r\n\r\n\r\nnamespace cpdoccore {\r\nnamespace oox {\r\n\r\n\r\nclass num_format_context::Impl2\r\n{\r\npublic:\r\n complex_number_format complex_number_format_;\r\n};\r\n\r\nclass num_format_context::Impl\r\n{\r\npublic:\r\n Impl(): in_convert_style_(false)\r\n {}\r\n\r\npublic:\r\n std::wstring current_style_name_;\r\n std::wstringstream stream_;\r\n\r\n void reset_current()\r\n {\r\n current_style_name_ = L\"\";\r\n stream_.str(std::wstring()); \r\n in_convert_style_ = false;\r\n }\r\n\r\n std::wstring last_format_;\r\n\r\n bool in_convert_style_;\r\n};\r\n\r\nnum_format_context::num_format_context(odf_reader::odf_read_context & odfContext): odf_context_(odfContext), impl_(new Impl()), impl2_(new Impl2())\r\n{\r\n}\r\n\r\nnum_format_context::~num_format_context()\r\n{\r\n}\r\n\r\nvoid num_format_context::start_format(const std::wstring & style_name)\r\n{\r\n impl_->reset_current();\r\n impl_->current_style_name_ = style_name;\r\n impl_->in_convert_style_ = true;\r\n}\r\n\r\nstd::wostream & num_format_context::output()\r\n{\r\n return impl_->stream_;\r\n}\r\n\r\nvoid num_format_context::end_format()\r\n{ \r\n impl_->last_format_ = impl_->stream_.str();\r\n impl_->reset_current();\r\n}\r\n\r\nstd::wstring num_format_context::get_last_format() const\r\n{\r\n return impl_->last_format_;\r\n}\r\n\r\nvoid num_format_context::start_complex_format()\r\n{\r\n impl2_->complex_number_format_.reset();\r\n}\r\n\r\nvoid num_format_context::add_format(std::wstring const & cond, std::wstring const & format)\r\n{\r\n impl2_->complex_number_format_.add_format(cond, format);\r\n}\r\n\r\nvoid num_format_context::end_complex_format()\r\n{\r\n impl_->last_format_ = impl2_->complex_number_format_.result_value();\r\n}\r\n\r\n}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"SUPPORT\/generate2.h\"\n#include \"SUPPORT\/window.h\"\n#include \"SUPPORT\/geometricObject2.h\"\n#include \"SUPPORT\/delone10.h\"\n#include \"SUPPORT\/betaSet.h\"\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <list>\n#include <mpi.h>\n#include <string>\n#include <chrono>\n\n#define MASTER 0 \/* task ID of master task *\/\n\ntypedef betaSet numberType;\ntypedef rhombus windowType;\n\nint main (int argc, char* argv[])\n{\n \/\/ time measuring\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n \n int\ttaskid;\t \n int numtasks; \n int nodeid;\n int nodes;\n int rc;\n \n std::string buffer;\n std::string send_buffer;\n int length;\n \n std::list<std::string> res;\n std::list<std::string> data;\n std::list<std::string>::iterator iterator;\n \n MPI_Status status;\n \n \n \n \/\/ initialize\n numberType winSize(1, 0, 2);\n Cpoint<numberType> origin( numberType::get(0,0), numberType::get(0,0) );\n \n std::string clipTileStr = \"(0+1*beta)\/2,(-1+2*beta)\/2 (0+0*beta)\/2,(0+1*beta)\/1 (-1+2*beta)\/2,(0+1*beta)\/2 (0-1*beta)\/2,(-1+2*beta)\/2 (0+1*beta)\/1,(0+0*beta)\/4 (1-2*beta)\/2,(0+1*beta)\/2 (0+0*beta)\/4,(0+0*beta)\/4 (-1+2*beta)\/2,(0-1*beta)\/2 (0-1*beta)\/1,(0+0*beta)\/4 (0+1*beta)\/2,(1-2*beta)\/2 (1-2*beta)\/2,(0-1*beta)\/2 (0+0*beta)\/2,(0-1*beta)\/1 (0-1*beta)\/2,(1-2*beta)\/2 \";\n \n windowType win( winSize );\n win.center( origin );\n \n \/\/ hyperquasicrystal\n \/\/rhombus *circ = dynamic_cast<rhombus*> ( win.circumscribed() );\n rhombus *circ = new rhombus(winSize*betaSet::get(4,0,3));\n \n \n \/\/ hypoquasicrystal\n \/\/rhombus *insc = dynamic_cast<rhombus*> ( win.inscribed() );\n rhombus *insc = new rhombus(winSize*betaSet::get(2,0,3));\n \n betaSet S = circ->Xwindow().Small();\n betaSet L = insc->Xwindow().Large();\n \n betaSet coveringR = numberType::get(161, -43)*L;\n \n \/\/ size of rhumbus circumscribed to covering radius disc\n betaSet lengthToCover = numberType::get(8, 0)*coveringR;\n \n CvoronoiCell<numberType>::large = numberType::get(2, 0)*coveringR;\n \n \/\/ find out the word length by testing\n int wordLength = 1;\n do\n {\n ++wordLength;\n } while ( minWord(language(circ->Xwindow(), wordLength), circ->Xwindow()) < lengthToCover );\n \n wordLength = 5;\n \n \/* Obtain number of tasks and task ID *\/\n MPI_Init(&argc,&argv);\n MPI_Comm_size(MPI_COMM_WORLD,&numtasks);\n MPI_Comm_rank(MPI_COMM_WORLD,&taskid);\n \n std::cout << std::string(4, ' ') << \"MPI task \" << taskid << \" has started...\" << std::endl;\n \n nodes = numtasks-1;\n nodeid = taskid-1;\n \n \n if (taskid != MASTER) \/\/ NODE ----------------------------------------\n {\n CvoronoiCell<numberType> clipTile;\n clipTile.load(clipTileStr);\n *clipTile.CarrierSet = *clipTile.CarrierSet*numberType(0,1);\n \n do \n {\n MPI_Probe(MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n \n MPI_Get_count(&status, MPI_CHAR, &length);\n char *cache = new char[length];\n \n MPI_Recv(cache, length, MPI_CHAR, MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n buffer = std::string(cache, length);\n delete [] cache;\n \n \/\/std::cout << std::string(4, ' ') << taskid << \": received \" << buffer << \" status: \" << status.MPI_TAG << std::endl;\n \n \/\/std::cout << \" node \" << taskid << \" data received\" << std::endl;\n \n if (status.MPI_TAG == 0)\n {\n \n \n \/\/ process data ------------------------------------------------\n std::string word1 = buffer.substr(0, buffer.length()\/2);\n std::string word2 = buffer.substr(buffer.length()\/2);\n CdeloneSet10<numberType> delone = quasicrystal2D10(circ->Xwindow(), word1, word2);\n \n delone << *clipTile.CarrierSet;\n \n delone.setPackingR();\n delone.setCoveringR(numberType::get(2, 0)*coveringR);\n delone.setDescription(word1+word2);\n delone.sortPotentialByDistance();\n \n delone.sortByDistance();\n \n std::list<CdeloneSet10<numberType> > delones;\n std::list<CvoronoiCell<numberType> > cells;\n delones.push_back(delone);\n \n for (std::list<CdeloneSet10<numberType> >::iterator it = delones.begin(); it != delones.end(); it = delones.begin())\n {\n \/\/std::cout << \"SIZE POTENTIAL: \" << it->sizePotential() << std::endl;\n \/\/it->filterPotentialByWindow(win);\n \n CvoronoiCell<numberType> voronoi;\n \n *(voronoi.CarrierSet) = *it;\n \n voronoi.CarrierSet->sort();\n voronoi.CarrierSet->unique();\n \n voronoi.CarrierSet->sortByDistance();\n voronoi.CarrierSet->setPackingR();\n voronoi.CarrierSet->setCoveringR(CvoronoiCell<numberType>::large);\n voronoi.setCenter(origin);\n voronoi.construct();\n voronoi.filterSet();\n \n std::list<Cpoint<numberType> > potential;\n potential = it->getPotential();\n voronoi.filterSetPotential( &potential );\n it->clearPotential();\n it->addPotential(potential);\n \n \/\/std::cout << \"SIZE POTENTIAL: \" << it->sizePotential() << '\\t' << \"SIZE DELONES: \" << delones.size() << std::endl;\n \n \/\/ deal with potential\n while (it->isPotential()) \n {\n Cpoint<numberType> cache = it->popPotential();\n \n delone = *it;\n delone << cache;\n delones.push_back(delone);\n }\n \n \n cells.push_back( voronoi );\n \n delones.erase(it);\n \n delones.sort();\n delones.unique();\n \n \/\/std::cout << \" node \" << taskid << \" delones: \" << delones.size() << std::endl;\n }\n \n cells.sort();\n cells.unique();\n \n std::list<std::string> list;\n \n for (std::list<CvoronoiCell<numberType> >::iterator it = cells.begin(); it != cells.end(); ++it)\n {\n list.push_back(it->save());\n }\n \n list.sort();\n list.unique();\n \/\/ end ---------------------------------------------------------\n \n \n \/\/std::cout << \" node \" << taskid << \" sending back: \" << list.size() << std::endl;\n \n for (std::list<std::string>::iterator it = list.begin(); it != --list.end(); ++it)\n {\n send_buffer = *it;\n \/\/ return result\n MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, MASTER, 0, MPI_COMM_WORLD);\n }\n \n send_buffer = *list.rbegin();\n \/\/ return result\n MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, MASTER, 1, MPI_COMM_WORLD);\n }\n } while (status.MPI_TAG == 0); \n }\n else \/\/ MASTER -------------------------------------------------------\n {\n \/\/ create data -----------------------------------------------------\n std::cout << \"Load data\" << std::endl;\n \n std::list<std::string> lang = language( insc->Xwindow(), circ->Xwindow(), wordLength );\n for ( std::list<std::string>::iterator it = lang.begin(); it != lang.end(); ++it )\n {\n for ( std::list<std::string>::iterator ot = lang.begin(); ot != lang.end(); ++ot )\n {\n data.push_back(*it+*ot);\n }\n }\n \n std::cout << \"tasks: \" << data.size() << std::endl;\n std::cout << \"word length: \" << wordLength << std::endl;\n \n iterator = data.begin();\n \n int count = 0;\n \/\/ send initial load of data\n std::cout << \"Send initial load of data\" << std::endl;\n for (int it = 0; it < nodes; ++it)\n {\n send_buffer = *(iterator++);\n \n \/\/std::cout << std::string(4, ' ') << \"MASTER sending: \" << iterator << \"\/168\" << std::endl;\n \n MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, it+1, 0, MPI_COMM_WORLD);\n count++;\n }\n \n \/\/ gather data while processing\n std::cout << \"distribute the rest on demand\" << std::endl;\n while (iterator != data.end())\n {\n \/\/std::cout << \"waiting\" << std::endl;\n MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n \n MPI_Get_count(&status, MPI_CHAR, &length);\n char *cache = new char[length];\n MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n buffer = std::string(cache, length);\n delete [] cache;\n \n \/\/ save result\n res.push_back(buffer);\n \/\/std::cout << \"finished: \" << res.size() << std::endl;\n \n while (status.MPI_TAG == 0)\n {\n MPI_Probe(status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n \n MPI_Get_count(&status, MPI_CHAR, &length);\n char *cache = new char[length];\n MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n buffer = std::string(cache, length);\n delete [] cache;\n \n \/\/ save result\n res.push_back(buffer);\n \/\/std::cout << \"finished: \" << res.size() << std::endl;\n }\n \n \/\/std::cout << std::string(4, ' ') << \"MASTER received from: \" << status.MPI_SOURCE << \" sending: \" << iterator << std::endl;\n \n send_buffer = *(iterator++);\n \n MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, status.MPI_SOURCE, 0, MPI_COMM_WORLD);\n \n count++;\n if ((20*count)%data.size() == 0)\n {\n std::cout << \"processed \" << count << \"\/\" << data.size() << \" <=> \" << 10*count\/data.size() << \"0%\" << std::endl;\n }\n }\n \n \/\/ terminate processes\n std::cout << \"termination\" << std::endl;\n for (int it = 0; it < nodes; ++it)\n {\n MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n \n MPI_Get_count(&status, MPI_CHAR, &length);\n char *cache = new char[length];\n MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n buffer = std::string(cache, length);\n delete [] cache;\n \n \/\/ save result\n res.push_back(buffer);\n std::cout << \"finished: \" << res.size() << std::endl;\n \n \/\/std::cout << std::string(4, ' ') << \"MASTER received from: \" << status.MPI_SOURCE << \" - \" << buffer << std::endl;\n \n send_buffer = std::to_string(0);\n \n rc = MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, it+1, 1, MPI_COMM_WORLD);\n }\n \n \n \/\/ write to file\n std::ostringstream convert;\n convert << argv[1] << \"_\" << wordLength << \"_\";\n printFile(convert, winSize);\n \n std::ofstream output(convert.str().c_str());\n res.sort();\n res.unique();\n \n print(output, winSize);\n output << std::endl;\n for (std::list<std::string>::iterator it = res.begin(); it != res.end(); ++it)\n {\n output << *it << std::endl;\n }\n output.close();\n }\n \n std::cout << std::string(4, ' ') << \"... MPI task \" << taskid << \" is closing\" << std::endl;\n MPI_Finalize();\n \n \/\/ time measuring\n std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();\n auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();\n std::cout << \"microseconds: \" << duration << \" (\" << std::round(duration\/100000.0)\/10.0 << \"s)\" << std::endl;\n \n return 0;\n}\n<commit_msg>minor adjustment<commit_after>#include \"SUPPORT\/generate2.h\"\n#include \"SUPPORT\/window.h\"\n#include \"SUPPORT\/geometricObject2.h\"\n#include \"SUPPORT\/delone10.h\"\n#include \"SUPPORT\/betaSet.h\"\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <list>\n#include <mpi.h>\n#include <string>\n#include <chrono>\n\n#define MASTER 0 \/* task ID of master task *\/\n\ntypedef betaSet numberType;\ntypedef rhombus windowType;\n\nint main (int argc, char* argv[])\n{\n \/\/ time measuring\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n \n int\ttaskid;\t \n int numtasks; \n int nodeid;\n int nodes;\n int rc;\n \n std::string buffer;\n std::string send_buffer;\n int length;\n \n std::list<std::string> res;\n std::list<std::string> data;\n std::list<std::string>::iterator iterator;\n \n MPI_Status status;\n \n \n \n \/\/ initialize\n numberType winSize(1, 0, 2);\n Cpoint<numberType> origin( numberType::get(0,0), numberType::get(0,0) );\n \n std::string clipTileStr = \"(0+1*beta)\/2,(-1+2*beta)\/2 (0+0*beta)\/2,(0+1*beta)\/1 (-1+2*beta)\/2,(0+1*beta)\/2 (0-1*beta)\/2,(-1+2*beta)\/2 (0+1*beta)\/1,(0+0*beta)\/4 (1-2*beta)\/2,(0+1*beta)\/2 (0+0*beta)\/4,(0+0*beta)\/4 (-1+2*beta)\/2,(0-1*beta)\/2 (0-1*beta)\/1,(0+0*beta)\/4 (0+1*beta)\/2,(1-2*beta)\/2 (1-2*beta)\/2,(0-1*beta)\/2 (0+0*beta)\/2,(0-1*beta)\/1 (0-1*beta)\/2,(1-2*beta)\/2 \";\n \n windowType win( winSize );\n win.center( origin );\n \n \/\/ hyperquasicrystal\n \/\/rhombus *circ = dynamic_cast<rhombus*> ( win.circumscribed() );\n rhombus *circ = new rhombus(winSize*betaSet::get(4,0,3));\n \n \n \/\/ hypoquasicrystal\n \/\/rhombus *insc = dynamic_cast<rhombus*> ( win.inscribed() );\n rhombus *insc = new rhombus(winSize*betaSet::get(2,0,3));\n \n betaSet S = circ->Xwindow().Small();\n betaSet L = insc->Xwindow().Large();\n \n betaSet coveringR = numberType::get(161, -43)*L;\n \n \/\/ size of rhumbus circumscribed to covering radius disc\n betaSet lengthToCover = numberType::get(8, 0)*coveringR;\n \n CvoronoiCell<numberType>::large = numberType::get(2, 0)*coveringR;\n \n \/\/ find out the word length by testing\n int wordLength = 1;\n do\n {\n ++wordLength;\n } while ( minWord(language(circ->Xwindow(), wordLength), circ->Xwindow()) < lengthToCover );\n \n \/\/wordLength = 5;\n \n \/* Obtain number of tasks and task ID *\/\n MPI_Init(&argc,&argv);\n MPI_Comm_size(MPI_COMM_WORLD,&numtasks);\n MPI_Comm_rank(MPI_COMM_WORLD,&taskid);\n \n std::cout << std::string(4, ' ') << \"MPI task \" << taskid << \" has started...\" << std::endl;\n \n nodes = numtasks-1;\n nodeid = taskid-1;\n \n \n if (taskid != MASTER) \/\/ NODE ----------------------------------------\n {\n CvoronoiCell<numberType> clipTile;\n clipTile.load(clipTileStr);\n *clipTile.CarrierSet = *clipTile.CarrierSet*numberType(0,1);\n \n do \n {\n MPI_Probe(MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n \n MPI_Get_count(&status, MPI_CHAR, &length);\n char *cache = new char[length];\n \n MPI_Recv(cache, length, MPI_CHAR, MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n buffer = std::string(cache, length);\n delete [] cache;\n \n \/\/std::cout << std::string(4, ' ') << taskid << \": received \" << buffer << \" status: \" << status.MPI_TAG << std::endl;\n \n \/\/std::cout << \" node \" << taskid << \" data received\" << std::endl;\n \n if (status.MPI_TAG == 0)\n {\n \n \n \/\/ process data ------------------------------------------------\n std::string word1 = buffer.substr(0, buffer.length()\/2);\n std::string word2 = buffer.substr(buffer.length()\/2);\n CdeloneSet10<numberType> delone = quasicrystal2D10(circ->Xwindow(), word1, word2);\n \n delone << *clipTile.CarrierSet;\n \n delone.setPackingR();\n delone.setCoveringR(numberType::get(2, 0)*coveringR);\n delone.setDescription(word1+word2);\n delone.sortPotentialByDistance();\n \n delone.sortByDistance();\n \n std::list<CdeloneSet10<numberType> > delones;\n std::list<CvoronoiCell<numberType> > cells;\n delones.push_back(delone);\n \n for (std::list<CdeloneSet10<numberType> >::iterator it = delones.begin(); it != delones.end(); it = delones.begin())\n {\n \/\/std::cout << \"SIZE POTENTIAL: \" << it->sizePotential() << std::endl;\n \/\/it->filterPotentialByWindow(win);\n \n CvoronoiCell<numberType> voronoi;\n \n *(voronoi.CarrierSet) = *it;\n \n voronoi.CarrierSet->sort();\n voronoi.CarrierSet->unique();\n \n voronoi.CarrierSet->sortByDistance();\n voronoi.CarrierSet->setPackingR();\n voronoi.CarrierSet->setCoveringR(CvoronoiCell<numberType>::large);\n voronoi.setCenter(origin);\n voronoi.construct();\n voronoi.filterSet();\n \n std::list<Cpoint<numberType> > potential;\n potential = it->getPotential();\n voronoi.filterSetPotential( &potential );\n it->clearPotential();\n it->addPotential(potential);\n \n \/\/std::cout << \"SIZE POTENTIAL: \" << it->sizePotential() << '\\t' << \"SIZE DELONES: \" << delones.size() << std::endl;\n \n \/\/ deal with potential\n while (it->isPotential()) \n {\n Cpoint<numberType> cache = it->popPotential();\n \n delone = *it;\n delone << cache;\n delones.push_back(delone);\n }\n \n \n cells.push_back( voronoi );\n \n delones.erase(it);\n \n delones.sort();\n delones.unique();\n \n \/\/std::cout << \" node \" << taskid << \" delones: \" << delones.size() << std::endl;\n }\n \n cells.sort();\n cells.unique();\n \n std::list<std::string> list;\n \n for (std::list<CvoronoiCell<numberType> >::iterator it = cells.begin(); it != cells.end(); ++it)\n {\n list.push_back(it->save());\n }\n \n list.sort();\n list.unique();\n \/\/ end ---------------------------------------------------------\n \n \n \/\/std::cout << \" node \" << taskid << \" sending back: \" << list.size() << std::endl;\n \n for (std::list<std::string>::iterator it = list.begin(); it != --list.end(); ++it)\n {\n send_buffer = *it;\n \/\/ return result\n MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, MASTER, 0, MPI_COMM_WORLD);\n }\n \n send_buffer = *list.rbegin();\n \/\/ return result\n MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, MASTER, 1, MPI_COMM_WORLD);\n }\n } while (status.MPI_TAG == 0); \n }\n else \/\/ MASTER -------------------------------------------------------\n {\n \/\/ create data -----------------------------------------------------\n std::cout << \"Load data\" << std::endl;\n \n std::list<std::string> lang = language( insc->Xwindow(), circ->Xwindow(), wordLength );\n for ( std::list<std::string>::iterator it = lang.begin(); it != lang.end(); ++it )\n {\n for ( std::list<std::string>::iterator ot = lang.begin(); ot != lang.end(); ++ot )\n {\n data.push_back(*it+*ot);\n }\n }\n \n std::cout << \"tasks: \" << data.size() << std::endl;\n std::cout << \"word length: \" << wordLength << std::endl;\n \n iterator = data.begin();\n \n int count = 0;\n \/\/ send initial load of data\n std::cout << \"Send initial load of data\" << std::endl;\n for (int it = 0; it < nodes; ++it)\n {\n send_buffer = *(iterator++);\n \n \/\/std::cout << std::string(4, ' ') << \"MASTER sending: \" << iterator << \"\/168\" << std::endl;\n \n MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, it+1, 0, MPI_COMM_WORLD);\n count++;\n }\n \n \/\/ gather data while processing\n std::cout << \"distribute the rest on demand\" << std::endl;\n while (iterator != data.end())\n {\n \/\/std::cout << \"waiting\" << std::endl;\n MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n \n MPI_Get_count(&status, MPI_CHAR, &length);\n char *cache = new char[length];\n MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n buffer = std::string(cache, length);\n delete [] cache;\n \n \/\/ save result\n res.push_back(buffer);\n \/\/std::cout << \"finished: \" << res.size() << std::endl;\n \n while (status.MPI_TAG == 0)\n {\n MPI_Probe(status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n \n MPI_Get_count(&status, MPI_CHAR, &length);\n char *cache = new char[length];\n MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n buffer = std::string(cache, length);\n delete [] cache;\n \n \/\/ save result\n res.push_back(buffer);\n \/\/std::cout << \"finished: \" << res.size() << std::endl;\n }\n \n \/\/std::cout << std::string(4, ' ') << \"MASTER received from: \" << status.MPI_SOURCE << \" sending: \" << iterator << std::endl;\n \n send_buffer = *(iterator++);\n \n MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, status.MPI_SOURCE, 0, MPI_COMM_WORLD);\n \n count++;\n if ((20*count)%data.size() == 0)\n {\n std::cout << \"processed \" << count << \"\/\" << data.size() << \" <=> \" << 10*count\/data.size() << \"0%\" << std::endl;\n }\n }\n \n \/\/ terminate processes\n std::cout << \"termination\" << std::endl;\n for (int it = 0; it < nodes; ++it)\n {\n MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n \n MPI_Get_count(&status, MPI_CHAR, &length);\n char *cache = new char[length];\n MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n buffer = std::string(cache, length);\n delete [] cache;\n \n \/\/ save result\n res.push_back(buffer);\n std::cout << \"finished: \" << res.size() << std::endl;\n \n \/\/std::cout << std::string(4, ' ') << \"MASTER received from: \" << status.MPI_SOURCE << \" - \" << buffer << std::endl;\n \n send_buffer = std::to_string(0);\n \n rc = MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, it+1, 1, MPI_COMM_WORLD);\n }\n \n \n \/\/ write to file\n std::ostringstream convert;\n convert << argv[1] << \"_\" << wordLength << \"_\";\n printFile(convert, winSize);\n \n std::ofstream output(convert.str().c_str());\n res.sort();\n res.unique();\n \n print(output, winSize);\n output << std::endl;\n for (std::list<std::string>::iterator it = res.begin(); it != res.end(); ++it)\n {\n output << *it << std::endl;\n }\n output.close();\n }\n \n std::cout << std::string(4, ' ') << \"... MPI task \" << taskid << \" is closing\" << std::endl;\n MPI_Finalize();\n \n \/\/ time measuring\n std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();\n auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();\n std::cout << \"microseconds: \" << duration << \" (\" << std::round(duration\/100000.0)\/10.0 << \"s)\" << std::endl;\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <thrift\/lib\/cpp\/concurrency\/Mutex-impl.h>\n\n#include <gtest\/gtest.h>\n#include \"common\/concurrency\/Timeout.h\"\n#include \"common\/time\/TimeConstants.h\"\n#include <thrift\/lib\/cpp\/concurrency\/Util.h>\n#include <thread>\n#include <condition_variable>\n#include <vector>\n\nusing namespace std;\nusing namespace facebook;\nusing namespace apache::thrift::concurrency;\n\n\nconst int kTimeoutUsec = 10*kUsecPerMs; \/\/ 10ms\nconst int kTimeoutMs = kTimeoutUsec \/ kUsecPerMs;\nconst int kMaxReaders = 10;\nconst int kMicroSecInMilliSec = 1000;\n\/\/ user operation time on the lock in milliseconds\nconst int kOpTimeInMs = 100;\n\nTEST(RWMutexTest, Max_Readers ) {\n ReadWriteMutex l;\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n }\n\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n}\n\nTEST(RWMutexTest, Writer_Wait_Readers ) {\n ReadWriteMutex l;\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n }\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n }\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n l.release();\n\n \/\/ Testing timeout\n vector<std::thread> threads_;\n for (int i = 0; i < kMaxReaders; ++i) {\n threads_.push_back(std::thread([this, &l] {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n }));\n }\n \/\/ make sure reader lock the lock first\n usleep(1000);\n\n \/\/ wait shorter than the operation time will timeout\n std::thread thread1 = std::thread([this, &l] {\n EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));\n });\n\n \/\/ wait longer than the operation time will success\n std::thread thread2 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));\n l.release();\n });\n\n for (auto& t : threads_) {\n t.join();\n }\n thread1.join();\n thread2.join();\n}\n\nTEST(RWMutexTest, Readers_Wait_Writer) {\n ReadWriteMutex l;\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_FALSE(l.timedRead(kTimeoutMs));\n }\n\n l.release();\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n }\n\n for (int i = 0; i < kMaxReaders; ++i) {\n l.release();\n }\n\n \/\/ Testing Timeout\n std::thread wrThread = std::thread([&l] {\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n });\n\n \/\/ make sure wrThread lock the lock first\n usleep(1000);\n\n vector<std::thread> threads_;\n for (int i = 0; i < kMaxReaders; ++i) {\n \/\/ wait shorter than the operation time will timeout\n threads_.push_back(std::thread([&l] {\n EXPECT_FALSE(l.timedRead(0.5 * kOpTimeInMs));\n }));\n\n \/\/ wait longer than the operation time will success\n threads_.push_back(std::thread([&l] {\n EXPECT_TRUE(l.timedRead(1.5 * kOpTimeInMs));\n l.release();\n }));\n }\n\n for (auto& t : threads_) {\n t.join();\n }\n wrThread.join();\n}\n\nTEST(RWMutexTest, Writer_Wait_Writer) {\n ReadWriteMutex l;\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n\n \/\/ Testing Timeout\n std::thread wrThread1 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n });\n\n \/\/ make sure wrThread lock the lock first\n usleep(1000);\n\n \/\/ wait shorter than the operation time will timeout\n std::thread wrThread2 = std::thread([this, &l] {\n EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));\n });\n\n \/\/ wait longer than the operation time will success\n std::thread wrThread3 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));\n l.release();\n });\n\n wrThread1.join();\n wrThread2.join();\n wrThread3.join();\n}\n\nTEST(RWMutexTest, Read_Holders) {\n ReadWriteMutex l;\n\n RWGuard guard(l, false);\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n l.release();\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n}\n\nTEST(RWMutexTest, Write_Holders) {\n ReadWriteMutex l;\n\n RWGuard guard(l, true);\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedRead(kTimeoutMs));\n}\n\nTEST(MutexTest, Recursive_Holders) {\n Mutex mutex(Mutex::RECURSIVE_INITIALIZER);\n Guard g1(mutex);\n {\n Guard g2(mutex);\n }\n Guard g2(mutex);\n}\n\nTEST(NoStarveRWMutexTest, Max_Readers ) {\n NoStarveReadWriteMutex l;\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n }\n\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n}\n\nTEST(NoStarveRWMutexTest, Writer_Wait_Readers ) {\n NoStarveReadWriteMutex l;\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n }\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n }\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n l.release();\n\n std::condition_variable cv;\n std::mutex cv_m;\n int readers = 0;\n\n \/\/ Testing timeout\n vector<std::thread> threads_;\n for (int i = 0; i < kMaxReaders; ++i) {\n threads_.push_back(std::thread([&, this] {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n {\n std::lock_guard<std::mutex> lk(cv_m);\n readers++;\n cv.notify_one();\n }\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n }));\n }\n\n {\n std::unique_lock<std::mutex> lk(cv_m);\n cv.wait(lk, [&] {return readers == kMaxReaders;});\n }\n\n \/\/ wait shorter than the operation time will timeout\n std::thread thread1 = std::thread([this, &l] {\n EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));\n });\n\n \/\/ wait longer than the operation time will success\n std::thread thread2 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));\n l.release();\n });\n\n for (auto& t : threads_) {\n t.join();\n }\n thread1.join();\n thread2.join();\n}\n\nTEST(NoStarveRWMutexTest, Readers_Wait_Writer) {\n NoStarveReadWriteMutex l;\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_FALSE(l.timedRead(kTimeoutMs));\n }\n\n l.release();\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n }\n\n for (int i = 0; i < kMaxReaders; ++i) {\n l.release();\n }\n\n \/\/ Testing Timeout\n std::thread wrThread = std::thread([&l] {\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n });\n\n \/\/ make sure wrThread lock the lock first\n usleep(1000);\n\n vector<std::thread> threads_;\n for (int i = 0; i < kMaxReaders; ++i) {\n \/\/ wait shorter than the operation time will timeout\n threads_.push_back(std::thread([&l] {\n EXPECT_FALSE(l.timedRead(0.5 * kOpTimeInMs));\n }));\n\n \/\/ wait longer than the operation time will success\n threads_.push_back(std::thread([&l] {\n EXPECT_TRUE(l.timedRead(1.5 * kOpTimeInMs));\n l.release();\n }));\n }\n\n for (auto& t : threads_) {\n t.join();\n }\n wrThread.join();\n}\n\nTEST(NoStarveRWMutexTest, Writer_Wait_Writer) {\n NoStarveReadWriteMutex l;\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n\n \/\/ Testing Timeout\n std::thread wrThread1 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n });\n\n \/\/ make sure wrThread lock the lock first\n usleep(1000);\n\n \/\/ wait shorter than the operation time will timeout\n std::thread wrThread2 = std::thread([this, &l] {\n EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));\n });\n\n \/\/ wait longer than the operation time will success\n std::thread wrThread3 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));\n l.release();\n });\n\n wrThread1.join();\n wrThread2.join();\n wrThread3.join();\n}\n\nTEST(NoStarveRWMutexTest, Read_Holders) {\n NoStarveReadWriteMutex l;\n\n RWGuard guard(l, false);\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n l.release();\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n}\n\nTEST(NoStarveRWMutexTest, Write_Holders) {\n NoStarveReadWriteMutex l;\n\n RWGuard guard(l, true);\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedRead(kTimeoutMs));\n}\n<commit_msg>Fix RWMutexTest-NoStarveRWMutexTest.Readers_Wait_Writer<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <thrift\/lib\/cpp\/concurrency\/Mutex-impl.h>\n\n#include <gtest\/gtest.h>\n#include \"common\/concurrency\/Timeout.h\"\n#include \"common\/time\/TimeConstants.h\"\n#include <thrift\/lib\/cpp\/concurrency\/Util.h>\n#include <thread>\n#include <condition_variable>\n#include <vector>\n\nusing namespace std;\nusing namespace facebook;\nusing namespace apache::thrift::concurrency;\n\n\nconst int kTimeoutUsec = 10*kUsecPerMs; \/\/ 10ms\nconst int kTimeoutMs = kTimeoutUsec \/ kUsecPerMs;\nconst int kMaxReaders = 10;\nconst int kMicroSecInMilliSec = 1000;\n\/\/ user operation time on the lock in milliseconds\nconst int kOpTimeInMs = 200;\n\nTEST(RWMutexTest, Max_Readers ) {\n ReadWriteMutex l;\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n }\n\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n}\n\nTEST(RWMutexTest, Writer_Wait_Readers ) {\n ReadWriteMutex l;\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n }\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n }\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n l.release();\n\n \/\/ Testing timeout\n vector<std::thread> threads_;\n for (int i = 0; i < kMaxReaders; ++i) {\n threads_.push_back(std::thread([this, &l] {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n }));\n }\n \/\/ make sure reader lock the lock first\n usleep(1000);\n\n \/\/ wait shorter than the operation time will timeout\n std::thread thread1 = std::thread([this, &l] {\n EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));\n });\n\n \/\/ wait longer than the operation time will success\n std::thread thread2 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));\n l.release();\n });\n\n for (auto& t : threads_) {\n t.join();\n }\n thread1.join();\n thread2.join();\n}\n\nTEST(RWMutexTest, Readers_Wait_Writer) {\n ReadWriteMutex l;\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_FALSE(l.timedRead(kTimeoutMs));\n }\n\n l.release();\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n }\n\n for (int i = 0; i < kMaxReaders; ++i) {\n l.release();\n }\n\n \/\/ Testing Timeout\n std::thread wrThread = std::thread([&l] {\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n });\n\n \/\/ make sure wrThread lock the lock first\n usleep(1000);\n\n vector<std::thread> threads_;\n for (int i = 0; i < kMaxReaders; ++i) {\n \/\/ wait shorter than the operation time will timeout\n threads_.push_back(std::thread([&l] {\n EXPECT_FALSE(l.timedRead(0.5 * kOpTimeInMs));\n }));\n\n \/\/ wait longer than the operation time will success\n threads_.push_back(std::thread([&l] {\n EXPECT_TRUE(l.timedRead(1.5 * kOpTimeInMs));\n l.release();\n }));\n }\n\n for (auto& t : threads_) {\n t.join();\n }\n wrThread.join();\n}\n\nTEST(RWMutexTest, Writer_Wait_Writer) {\n ReadWriteMutex l;\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n\n \/\/ Testing Timeout\n std::thread wrThread1 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n });\n\n \/\/ make sure wrThread lock the lock first\n usleep(1000);\n\n \/\/ wait shorter than the operation time will timeout\n std::thread wrThread2 = std::thread([this, &l] {\n EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));\n });\n\n \/\/ wait longer than the operation time will success\n std::thread wrThread3 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));\n l.release();\n });\n\n wrThread1.join();\n wrThread2.join();\n wrThread3.join();\n}\n\nTEST(RWMutexTest, Read_Holders) {\n ReadWriteMutex l;\n\n RWGuard guard(l, false);\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n l.release();\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n}\n\nTEST(RWMutexTest, Write_Holders) {\n ReadWriteMutex l;\n\n RWGuard guard(l, true);\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedRead(kTimeoutMs));\n}\n\nTEST(MutexTest, Recursive_Holders) {\n Mutex mutex(Mutex::RECURSIVE_INITIALIZER);\n Guard g1(mutex);\n {\n Guard g2(mutex);\n }\n Guard g2(mutex);\n}\n\nTEST(NoStarveRWMutexTest, Max_Readers ) {\n NoStarveReadWriteMutex l;\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n }\n\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n}\n\nTEST(NoStarveRWMutexTest, Writer_Wait_Readers ) {\n NoStarveReadWriteMutex l;\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n }\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n }\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n l.release();\n\n std::condition_variable cv;\n std::mutex cv_m;\n int readers = 0;\n\n \/\/ Testing timeout\n vector<std::thread> threads_;\n for (int i = 0; i < kMaxReaders; ++i) {\n threads_.push_back(std::thread([&, this] {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n {\n std::lock_guard<std::mutex> lk(cv_m);\n readers++;\n cv.notify_one();\n }\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n }));\n }\n\n {\n std::unique_lock<std::mutex> lk(cv_m);\n cv.wait(lk, [&] {return readers == kMaxReaders;});\n }\n\n \/\/ wait shorter than the operation time will timeout\n std::thread thread1 = std::thread([this, &l] {\n EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));\n });\n\n \/\/ wait longer than the operation time will success\n std::thread thread2 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));\n l.release();\n });\n\n for (auto& t : threads_) {\n t.join();\n }\n thread1.join();\n thread2.join();\n}\n\nTEST(NoStarveRWMutexTest, Readers_Wait_Writer) {\n NoStarveReadWriteMutex l;\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_FALSE(l.timedRead(kTimeoutMs));\n }\n\n l.release();\n\n for (int i = 0; i < kMaxReaders; ++i) {\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n }\n\n for (int i = 0; i < kMaxReaders; ++i) {\n l.release();\n }\n\n std::condition_variable cv;\n std::mutex cv_m;\n bool writer = false;\n\n \/\/ Testing Timeout\n std::thread wrThread = std::thread([&] {\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n {\n std::lock_guard<std::mutex> lk(cv_m);\n writer = true;\n cv.notify_all();\n }\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n });\n\n vector<std::thread> threads_;\n for (int i = 0; i < kMaxReaders; ++i) {\n \/\/ wait shorter than the operation time will timeout\n threads_.push_back(std::thread([&] {\n {\n std::unique_lock<std::mutex> lk(cv_m);\n cv.wait(lk, [&] { return writer; });\n }\n EXPECT_FALSE(l.timedRead(0.5 * kOpTimeInMs));\n }));\n\n \/\/ wait longer than the operation time will success\n threads_.push_back(std::thread([&l] {\n EXPECT_TRUE(l.timedRead(1.5 * kOpTimeInMs));\n l.release();\n }));\n }\n\n for (auto& t : threads_) {\n t.join();\n }\n wrThread.join();\n}\n\nTEST(NoStarveRWMutexTest, Writer_Wait_Writer) {\n NoStarveReadWriteMutex l;\n\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n l.release();\n\n \/\/ Testing Timeout\n std::thread wrThread1 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(kTimeoutMs));\n usleep(kOpTimeInMs * kMicroSecInMilliSec);\n l.release();\n });\n\n \/\/ make sure wrThread lock the lock first\n usleep(1000);\n\n \/\/ wait shorter than the operation time will timeout\n std::thread wrThread2 = std::thread([this, &l] {\n EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));\n });\n\n \/\/ wait longer than the operation time will success\n std::thread wrThread3 = std::thread([this, &l] {\n EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));\n l.release();\n });\n\n wrThread1.join();\n wrThread2.join();\n wrThread3.join();\n}\n\nTEST(NoStarveRWMutexTest, Read_Holders) {\n NoStarveReadWriteMutex l;\n\n RWGuard guard(l, false);\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n EXPECT_TRUE(l.timedRead(kTimeoutMs));\n l.release();\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n}\n\nTEST(NoStarveRWMutexTest, Write_Holders) {\n NoStarveReadWriteMutex l;\n\n RWGuard guard(l, true);\n EXPECT_FALSE(l.timedWrite(kTimeoutMs));\n EXPECT_FALSE(l.timedRead(kTimeoutMs));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- swift_indent_main.cpp - Swift code formatting tool ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Extracts a Symbol Graph from a .swiftmodule file.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/DiagnosticsFrontend.h\"\n#include \"swift\/Basic\/LLVM.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/Basic\/Version.h\"\n#include \"swift\/Frontend\/Frontend.h\"\n#include \"swift\/Frontend\/PrintingDiagnosticConsumer.h\"\n#include \"swift\/SymbolGraphGen\/SymbolGraphGen.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\nusing namespace swift;\nusing namespace llvm::opt;\n\nnamespace options {\nstatic llvm::cl::OptionCategory Category(\"swift-symbolgraph-extract Options\");\n\nstatic llvm::cl::opt<std::string>\nModuleName(\"module-name\", llvm::cl::desc(\"Name of the module to extract\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::list<std::string>\nFrameworkSearchPaths(\"F\", llvm::cl::desc(\"add a directory to the framework search paths\"), llvm::cl::ZeroOrMore,\n llvm::cl::cat(Category));\n\nstatic llvm::cl::list<std::string>\nLibrarySearchPaths(\"L\", llvm::cl::desc(\"Add a directory to the library search paths\"), llvm::cl::ZeroOrMore,\n llvm::cl::cat(Category));\n\nstatic llvm::cl::list<std::string>\nImportSearchPaths(\"I\", llvm::cl::desc(\"Add directory to the import search paths\"), llvm::cl::ZeroOrMore,\n llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nModuleCachePath(\"module-cache-path\", llvm::cl::desc(\"Specifies a path to cache modules\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nSDK(\"sdk\", llvm::cl::desc(\"Path to the SDK\"),\n llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nTarget(\"target\", llvm::cl::desc(\"Target triple\"),\n llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nSwiftVersion(\"swift-version\", llvm::cl::desc(\"Interpret input according to a specific Swift language version number\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<bool>\nPrettyPrint(\"pretty-print\", llvm::cl::desc(\"Pretty-print the resulting Symbol Graph JSON\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nMinimumAccessLevel(\"minimum-access-level\", llvm::cl::desc(\"Include symbols with this access level or more\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nOutputPath(\"o\", llvm::cl::desc(\"Symbol Graph JSON Output Path\"), llvm::cl::cat(Category));\n} \/\/ end namespace options\n\nint swift_symbolgraph_extract_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr) {\n INITIALIZE_LLVM();\n\n llvm::cl::HideUnrelatedOptions(options::Category);\n\n \/\/ LLVM Command Line expects to trim off argv[0].\n SmallVector<const char *, 8> ArgsWithArgv0 { Argv0 };\n ArgsWithArgv0.append(Args.begin(), Args.end());\n\n llvm::cl::ParseCommandLineOptions(ArgsWithArgv0.size(),\n llvm::makeArrayRef(ArgsWithArgv0).data(), \"Swift Symbol Graph Extractor\\n\");\n\n CompilerInvocation Invocation;\n\n Invocation.setMainExecutablePath(\n llvm::sys::fs::getMainExecutable(Argv0, MainAddr));\n Invocation.setModuleName(\"swift_symbolgraph_extract\");\n Invocation.setSDKPath(options::SDK);\n Invocation.setTargetTriple(options::Target);\n\n std::vector<SearchPathOptions::FrameworkSearchPath> FrameworkSearchPaths;\n for (const auto &Path : options::FrameworkSearchPaths) {\n FrameworkSearchPaths.push_back({ Path, \/*isSystem*\/ false});\n }\n Invocation.setFrameworkSearchPaths(FrameworkSearchPaths);\n Invocation.getSearchPathOptions().LibrarySearchPaths = options::LibrarySearchPaths;\n Invocation.setImportSearchPaths(options::ImportSearchPaths);\n\n Invocation.getLangOptions().EnableObjCInterop = llvm::Triple(options::Target).isOSDarwin();\n Invocation.getLangOptions().DebuggerSupport = true;\n\n Invocation.getFrontendOptions().EnableLibraryEvolution = true;\n\n Invocation.setClangModuleCachePath(options::ModuleCachePath);\n Invocation.getClangImporterOptions().ModuleCachePath = options::ModuleCachePath;\n\n if (!options::SwiftVersion.empty()) {\n using version::Version;\n bool isValid = false;\n if (auto Version = Version::parseVersionString(options::SwiftVersion,\n SourceLoc(), nullptr)) {\n if (auto Effective = Version.getValue().getEffectiveLanguageVersion()) {\n Invocation.getLangOptions().EffectiveLanguageVersion = *Effective;\n isValid = true;\n }\n }\n if (!isValid) {\n llvm::errs() << \"Unsupported Swift Version.\\n\";\n return EXIT_FAILURE;\n }\n }\n\n symbolgraphgen::SymbolGraphOptions Options {\n options::OutputPath,\n llvm::Triple(options::Target),\n options::PrettyPrint,\n AccessLevel::Public,\n };\n\n if (!options::MinimumAccessLevel.empty()) {\n Options.MinimumAccessLevel =\n llvm::StringSwitch<AccessLevel>(options::MinimumAccessLevel)\n .Case(\"open\", AccessLevel::Open) \n .Case(\"public\", AccessLevel::Public) \n .Case(\"internal\", AccessLevel::Internal) \n .Case(\"fileprivate\", AccessLevel::FilePrivate) \n .Case(\"private\", AccessLevel::Private) \n .Default(AccessLevel::Public);\n }\n\n PrintingDiagnosticConsumer DiagPrinter;\n\n CompilerInstance CI;\n CI.getDiags().addConsumer(DiagPrinter);\n\n if (CI.setup(Invocation)) {\n llvm::outs() << \"Failed to setup compiler instance\\n\";\n return EXIT_FAILURE;\n }\n\n auto M = CI.getASTContext().getModuleByName(options::ModuleName);\n if (!M) {\n llvm::errs()\n << \"Couldn't load module '\" << options::ModuleName << '\\''\n << \" in the current SDK and search paths.\\n\";\n SmallVector<Identifier, 32> VisibleModuleNames;\n CI.getASTContext().getVisibleTopLevelModuleNames(VisibleModuleNames);\n\n if (VisibleModuleNames.empty()) {\n llvm::errs() << \"Could not find any modules.\\n\";\n } else {\n std::sort(VisibleModuleNames.begin(), VisibleModuleNames.end(),\n [](const Identifier &A, const Identifier &B) -> bool {\n return A.str() < B.str();\n });\n llvm::errs() << \"Current visible modules:\\n\";\n for (const auto &ModuleName : VisibleModuleNames) {\n llvm::errs() << ModuleName.str() << \"\\n\";\n }\n }\n return EXIT_FAILURE;\n }\n\n return symbolgraphgen::emitSymbolGraphForModule(M,\n Options);\n}\n<commit_msg>swift-symbolgraph-extract: Mark required args<commit_after>\/\/===--- swift_indent_main.cpp - Swift code formatting tool ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Extracts a Symbol Graph from a .swiftmodule file.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/DiagnosticsFrontend.h\"\n#include \"swift\/Basic\/LLVM.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/Basic\/Version.h\"\n#include \"swift\/Frontend\/Frontend.h\"\n#include \"swift\/Frontend\/PrintingDiagnosticConsumer.h\"\n#include \"swift\/SymbolGraphGen\/SymbolGraphGen.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\nusing namespace swift;\nusing namespace llvm::opt;\n\nnamespace options {\nstatic llvm::cl::OptionCategory Category(\"swift-symbolgraph-extract Options\");\n\nstatic llvm::cl::opt<std::string>\nModuleName(\"module-name\", llvm::cl::desc(\"Name of the module to extract (Required)\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::list<std::string>\nFrameworkSearchPaths(\"F\", llvm::cl::desc(\"Add a directory to the framework search paths\"), llvm::cl::ZeroOrMore,\n llvm::cl::cat(Category));\n\nstatic llvm::cl::list<std::string>\nLibrarySearchPaths(\"L\", llvm::cl::desc(\"Add a directory to the library search paths\"), llvm::cl::ZeroOrMore,\n llvm::cl::cat(Category));\n\nstatic llvm::cl::list<std::string>\nImportSearchPaths(\"I\", llvm::cl::desc(\"Add directory to the import search paths\"), llvm::cl::ZeroOrMore,\n llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nModuleCachePath(\"module-cache-path\", llvm::cl::desc(\"Specifies a path to cache modules\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nSDK(\"sdk\", llvm::cl::desc(\"Path to the SDK\"),\n llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nTarget(\"target\", llvm::cl::desc(\"Target triple (Required)\"),\n llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nSwiftVersion(\"swift-version\", llvm::cl::desc(\"Interpret input according to a specific Swift language version number\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<bool>\nPrettyPrint(\"pretty-print\", llvm::cl::desc(\"Pretty-print the resulting Symbol Graph JSON\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nMinimumAccessLevel(\"minimum-access-level\", llvm::cl::desc(\"Include symbols with this access level or more\"), llvm::cl::cat(Category));\n\nstatic llvm::cl::opt<std::string>\nOutputPath(\"o\", llvm::cl::desc(\"Symbol Graph JSON Output Path (Required)\"), llvm::cl::cat(Category));\n} \/\/ end namespace options\n\nstatic bool argumentsAreValid() {\n bool Valid = true;\n if (options::Target.empty()) {\n llvm::errs() << \"Required -target option is missing\\n\";\n Valid = false;\n }\n\n if (options::ModuleName.empty()) {\n llvm::errs() << \"Required -module-name argument is missing\\n\";\n Valid = false;\n }\n\n if (options::OutputPath.empty()) {\n llvm::errs() << \"Required -o argument is missing\\n\";\n Valid = false;\n }\n\n return Valid;\n}\n\nint swift_symbolgraph_extract_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr) {\n INITIALIZE_LLVM();\n\n llvm::cl::HideUnrelatedOptions(options::Category);\n\n \/\/ LLVM Command Line expects to trim off argv[0].\n SmallVector<const char *, 8> ArgsWithArgv0 { Argv0 };\n ArgsWithArgv0.append(Args.begin(), Args.end());\n\n if (Args.empty()) {\n ArgsWithArgv0.push_back(\"-help\");\n }\n\n llvm::cl::ParseCommandLineOptions(ArgsWithArgv0.size(),\n llvm::makeArrayRef(ArgsWithArgv0).data(),\n \"Swift Symbol Graph Extractor\\n\");\n\n if (!argumentsAreValid()) {\n llvm::cl::PrintHelpMessage();\n return EXIT_FAILURE;\n }\n\n CompilerInvocation Invocation;\n\n Invocation.setMainExecutablePath(\n llvm::sys::fs::getMainExecutable(Argv0, MainAddr));\n Invocation.setModuleName(\"swift_symbolgraph_extract\");\n Invocation.setSDKPath(options::SDK);\n Invocation.setTargetTriple(options::Target);\n\n std::vector<SearchPathOptions::FrameworkSearchPath> FrameworkSearchPaths;\n for (const auto &Path : options::FrameworkSearchPaths) {\n FrameworkSearchPaths.push_back({ Path, \/*isSystem*\/ false});\n }\n Invocation.setFrameworkSearchPaths(FrameworkSearchPaths);\n Invocation.getSearchPathOptions().LibrarySearchPaths = options::LibrarySearchPaths;\n Invocation.setImportSearchPaths(options::ImportSearchPaths);\n\n Invocation.getLangOptions().EnableObjCInterop = llvm::Triple(options::Target).isOSDarwin();\n Invocation.getLangOptions().DebuggerSupport = true;\n\n Invocation.getFrontendOptions().EnableLibraryEvolution = true;\n\n Invocation.setClangModuleCachePath(options::ModuleCachePath);\n Invocation.getClangImporterOptions().ModuleCachePath = options::ModuleCachePath;\n\n if (!options::SwiftVersion.empty()) {\n using version::Version;\n bool isValid = false;\n if (auto Version = Version::parseVersionString(options::SwiftVersion,\n SourceLoc(), nullptr)) {\n if (auto Effective = Version.getValue().getEffectiveLanguageVersion()) {\n Invocation.getLangOptions().EffectiveLanguageVersion = *Effective;\n isValid = true;\n }\n }\n if (!isValid) {\n llvm::errs() << \"Unsupported Swift Version.\\n\";\n return EXIT_FAILURE;\n }\n }\n\n symbolgraphgen::SymbolGraphOptions Options {\n options::OutputPath,\n llvm::Triple(options::Target),\n options::PrettyPrint,\n AccessLevel::Public,\n };\n\n if (!options::MinimumAccessLevel.empty()) {\n Options.MinimumAccessLevel =\n llvm::StringSwitch<AccessLevel>(options::MinimumAccessLevel)\n .Case(\"open\", AccessLevel::Open) \n .Case(\"public\", AccessLevel::Public) \n .Case(\"internal\", AccessLevel::Internal) \n .Case(\"fileprivate\", AccessLevel::FilePrivate) \n .Case(\"private\", AccessLevel::Private) \n .Default(AccessLevel::Public);\n }\n\n PrintingDiagnosticConsumer DiagPrinter;\n\n CompilerInstance CI;\n CI.getDiags().addConsumer(DiagPrinter);\n\n if (CI.setup(Invocation)) {\n llvm::outs() << \"Failed to setup compiler instance\\n\";\n return EXIT_FAILURE;\n }\n\n auto M = CI.getASTContext().getModuleByName(options::ModuleName);\n if (!M) {\n llvm::errs()\n << \"Couldn't load module '\" << options::ModuleName << '\\''\n << \" in the current SDK and search paths.\\n\";\n SmallVector<Identifier, 32> VisibleModuleNames;\n CI.getASTContext().getVisibleTopLevelModuleNames(VisibleModuleNames);\n\n if (VisibleModuleNames.empty()) {\n llvm::errs() << \"Could not find any modules.\\n\";\n } else {\n std::sort(VisibleModuleNames.begin(), VisibleModuleNames.end(),\n [](const Identifier &A, const Identifier &B) -> bool {\n return A.str() < B.str();\n });\n llvm::errs() << \"Current visible modules:\\n\";\n for (const auto &ModuleName : VisibleModuleNames) {\n llvm::errs() << ModuleName.str() << \"\\n\";\n }\n }\n return EXIT_FAILURE;\n }\n\n return symbolgraphgen::emitSymbolGraphForModule(M,\n Options);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreETCCodec.h\"\n#include \"OgreImage.h\"\n\n#define FOURCC(c0, c1, c2, c3) (c0 | (c1 << 8) | (c2 << 16) | (c3 << 24))\n#define KTX_ENDIAN_REF (0x04030201)\n#define KTX_ENDIAN_REF_REV (0x01020304)\n\n\/\/ In a PKM-file, the codecs are stored using the following identifiers\n\/\/\n\/\/ identifier value codec\n\/\/ --------------------------------------------------------------------\n\/\/ ETC1_RGB_NO_MIPMAPS 0 GL_ETC1_RGB8_OES\n\/\/ ETC2PACKAGE_RGB_NO_MIPMAPS 1 GL_COMPRESSED_RGB8_ETC2\n\/\/ ETC2PACKAGE_RGBA_NO_MIPMAPS_OLD 2, not used -\n\/\/ ETC2PACKAGE_RGBA_NO_MIPMAPS 3 GL_COMPRESSED_RGBA8_ETC2_EAC\n\/\/ ETC2PACKAGE_RGBA1_NO_MIPMAPS 4 GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2\n\/\/ ETC2PACKAGE_R_NO_MIPMAPS 5 GL_COMPRESSED_R11_EAC\n\/\/ ETC2PACKAGE_RG_NO_MIPMAPS 6 GL_COMPRESSED_RG11_EAC\n\/\/ ETC2PACKAGE_R_SIGNED_NO_MIPMAPS 7 GL_COMPRESSED_SIGNED_R11_EAC\n\/\/ ETC2PACKAGE_RG_SIGNED_NO_MIPMAPS 8 GL_COMPRESSED_SIGNED_RG11_EAC\n\nnamespace Ogre {\n\n const uint32 PKM_MAGIC = FOURCC('P', 'K', 'M', ' ');\n const uint32 KTX_MAGIC = FOURCC(0xAB, 0x4B, 0x54, 0x58);\n\n typedef struct {\n uint8 name[4];\n uint8 version[2];\n uint8 iTextureTypeMSB;\n uint8 iTextureTypeLSB;\n uint8 iPaddedWidthMSB;\n uint8 iPaddedWidthLSB;\n uint8 iPaddedHeightMSB;\n uint8 iPaddedHeightLSB;\n uint8 iWidthMSB;\n uint8 iWidthLSB;\n uint8 iHeightMSB;\n uint8 iHeightLSB;\n } PKMHeader;\n \n typedef struct {\n uint8 identifier[12];\n uint32 endianness;\n uint32 glType;\n uint32 glTypeSize;\n uint32 glFormat;\n uint32 glInternalFormat;\n uint32 glBaseInternalFormat;\n uint32 pixelWidth;\n uint32 pixelHeight;\n uint32 pixelDepth;\n uint32 numberOfArrayElements;\n uint32 numberOfFaces;\n uint32 numberOfMipmapLevels;\n uint32 bytesOfKeyValueData;\n } KTXHeader;\n\n \/\/---------------------------------------------------------------------\n ETCCodec* ETCCodec::msPKMInstance = 0;\n ETCCodec* ETCCodec::msKTXInstance = 0;\n \/\/---------------------------------------------------------------------\n void ETCCodec::startup(void)\n {\n if (!msPKMInstance)\n {\n msPKMInstance = OGRE_NEW ETCCodec(\"pkm\");\n Codec::registerCodec(msPKMInstance);\n }\n\n if (!msKTXInstance)\n {\n msKTXInstance = OGRE_NEW ETCCodec(\"ktx\");\n Codec::registerCodec(msKTXInstance);\n }\n\n LogManager::getSingleton().logMessage(LML_NORMAL,\n \"ETC codec registering\");\n }\n \/\/---------------------------------------------------------------------\n void ETCCodec::shutdown(void)\n {\n if(msPKMInstance)\n {\n Codec::unregisterCodec(msPKMInstance);\n OGRE_DELETE msPKMInstance;\n msPKMInstance = 0;\n }\n\n if(msKTXInstance)\n {\n Codec::unregisterCodec(msKTXInstance);\n OGRE_DELETE msKTXInstance;\n msKTXInstance = 0;\n }\n }\n \/\/---------------------------------------------------------------------\n ETCCodec::ETCCodec(const String &type):\n mType(type)\n { \n }\n \/\/---------------------------------------------------------------------\n DataStreamPtr ETCCodec::encode(const MemoryDataStreamPtr& input,\n const Codec::CodecDataPtr& pData) const\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,\n \"ETC encoding not supported\",\n \"ETCCodec::encode\" ) ;\n }\n \/\/---------------------------------------------------------------------\n void ETCCodec::encodeToFile(const MemoryDataStreamPtr& input, const String& outFileName,\n const Codec::CodecDataPtr& pData) const\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,\n \"ETC encoding not supported\",\n \"ETCCodec::encodeToFile\" ) ;\n }\n \/\/---------------------------------------------------------------------\n Codec::DecodeResult ETCCodec::decode(const DataStreamPtr& stream) const\n {\n DecodeResult ret;\n if (decodeKTX(stream, ret))\n return ret;\n\n stream->seek(0);\n if (decodePKM(stream, ret))\n return ret;\n\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,\n \"This is not a valid ETC file!\", \"ETCCodec::decode\");\n }\n \/\/--------------------------------------------------------------------- \n String ETCCodec::getType() const \n {\n return mType;\n }\n \/\/--------------------------------------------------------------------- \n void ETCCodec::flipEndian(void * pData, size_t size, size_t count)\n {\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n\t\tBitwise::bswapChunks(pData, size, count);\n#endif\n }\n \/\/--------------------------------------------------------------------- \n void ETCCodec::flipEndian(void * pData, size_t size)\n {\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n Bitwise::bswapBuffer(pData, size);\n#endif\n }\n \/\/--------------------------------------------------------------------- \n String ETCCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const\n {\n if (maxbytes >= sizeof(uint32))\n {\n uint32 fileType;\n memcpy(&fileType, magicNumberPtr, sizeof(uint32));\n\t\t\tflipEndian(&fileType, sizeof(uint32));\n\n if (PKM_MAGIC == fileType)\n return String(\"pkm\");\n \n if (KTX_MAGIC == fileType)\n return String(\"ktx\");\n }\n\n return BLANKSTRING;\n }\n \/\/---------------------------------------------------------------------\n bool ETCCodec::decodePKM(const DataStreamPtr& stream, DecodeResult& result) const\n {\n PKMHeader header;\n\n \/\/ Read the ETC header\n stream->read(&header, sizeof(PKMHeader));\n\n if (PKM_MAGIC != FOURCC(header.name[0], header.name[1], header.name[2], header.name[3]) ) \/\/ \"PKM 10\"\n return false;\n\n uint16 width = (header.iWidthMSB << 8) | header.iWidthLSB;\n uint16 height = (header.iHeightMSB << 8) | header.iHeightLSB;\n uint16 paddedWidth = (header.iPaddedWidthMSB << 8) | header.iPaddedWidthLSB;\n uint16 paddedHeight = (header.iPaddedHeightMSB << 8) | header.iPaddedHeightLSB;\n uint16 type = (header.iTextureTypeMSB << 8) | header.iTextureTypeLSB;\n\n ImageData *imgData = OGRE_NEW ImageData();\n imgData->depth = 1;\n imgData->width = width;\n imgData->height = height;\n\n \/\/ File version 2.0 supports ETC2 in addition to ETC1\n if(header.version[0] == '2' && header.version[1] == '0')\n {\n switch (type) {\n case 0:\n imgData->format = PF_ETC1_RGB8;\n break;\n\n \/\/ GL_COMPRESSED_RGB8_ETC2\n case 1:\n imgData->format = PF_ETC2_RGB8;\n break;\n\n \/\/ GL_COMPRESSED_RGBA8_ETC2_EAC\n case 3:\n imgData->format = PF_ETC2_RGBA8;\n break;\n\n \/\/ GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2\n case 4:\n imgData->format = PF_ETC2_RGB8A1;\n break;\n\n \/\/ Default case is ETC1\n default:\n imgData->format = PF_ETC1_RGB8;\n break;\n }\n }\n else\n imgData->format = PF_ETC1_RGB8;\n\n \/\/ ETC has no support for mipmaps - malideveloper.com has a example\n \/\/ where the load mipmap levels from different external files\n imgData->num_mipmaps = 0;\n\n \/\/ ETC is a compressed format\n imgData->flags |= IF_COMPRESSED;\n\n \/\/ Calculate total size from number of mipmaps, faces and size\n imgData->size = (paddedWidth * paddedHeight) >> 1;\n\n \/\/ Bind output buffer\n MemoryDataStreamPtr output(OGRE_NEW MemoryDataStream(imgData->size));\n\n \/\/ Now deal with the data\n void *destPtr = output->getPtr();\n stream->read(destPtr, imgData->size);\n destPtr = static_cast<void*>(static_cast<uchar*>(destPtr));\n \n DecodeResult ret;\n ret.first = output;\n ret.second = CodecDataPtr(imgData);\n\n return true;\n }\n \/\/---------------------------------------------------------------------\n bool ETCCodec::decodeKTX(const DataStreamPtr& stream, DecodeResult& result) const\n {\n KTXHeader header;\n \/\/ Read the ETC1 header\n stream->read(&header, sizeof(KTXHeader));\n\n const uint8 KTXFileIdentifier[12] = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A };\n if (memcmp(KTXFileIdentifier, &header.identifier, sizeof(KTXFileIdentifier)) != 0 )\n return false;\n\n if (header.endianness == KTX_ENDIAN_REF_REV)\n\t\t\tflipEndian(&header.glType, sizeof(uint32));\n\n ImageData *imgData = OGRE_NEW ImageData();\n imgData->depth = 1;\n imgData->width = header.pixelWidth;\n imgData->height = header.pixelHeight;\n imgData->num_mipmaps = static_cast<uint8>(header.numberOfMipmapLevels - 1);\n\n switch(header.glInternalFormat)\n {\n case 37492: \/\/ GL_COMPRESSED_RGB8_ETC2\n imgData->format = PF_ETC2_RGB8;\n break;\n case 37496:\/\/ GL_COMPRESSED_RGBA8_ETC2_EAC\n imgData->format = PF_ETC2_RGBA8;\n break;\n case 37494: \/\/ GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2\n imgData->format = PF_ETC2_RGB8A1;\n break;\n case 35986: \/\/ ATC_RGB\n imgData->format = PF_ATC_RGB;\n break;\n case 35987: \/\/ ATC_RGB_Explicit\n imgData->format = PF_ATC_RGBA_EXPLICIT_ALPHA;\n break;\n case 34798: \/\/ ATC_RGB_Interpolated\n imgData->format = PF_ATC_RGBA_INTERPOLATED_ALPHA;\n break;\n case 33777: \/\/ DXT 1\n imgData->format = PF_DXT1;\n break;\n case 33778: \/\/ DXT 3\n imgData->format = PF_DXT3;\n break;\n case 33779: \/\/ DXT 5\n imgData->format = PF_DXT5;\n break;\n case 0x8c00: \/\/ COMPRESSED_RGB_PVRTC_4BPPV1_IMG\n imgData->format = PF_PVRTC_RGB4;\n break;\n case 0x8c01: \/\/ COMPRESSED_RGB_PVRTC_2BPPV1_IMG\n imgData->format = PF_PVRTC_RGB2;\n break;\n case 0x8c02: \/\/ COMPRESSED_RGBA_PVRTC_4BPPV1_IMG\n imgData->format = PF_PVRTC_RGBA4;\n break;\n case 0x8c03: \/\/ COMPRESSED_RGBA_PVRTC_2BPPV1_IMG\n imgData->format = PF_PVRTC_RGBA2;\n break;\n default: \n imgData->format = PF_ETC1_RGB8;\n break;\n }\n \n imgData->flags = 0;\n if (header.glType == 0 || header.glFormat == 0)\n imgData->flags |= IF_COMPRESSED;\n\n\t\tsize_t numFaces = header.numberOfFaces;\n\t\tif (numFaces > 1)\n\t\t\timgData->flags |= IF_CUBEMAP;\n \/\/ Calculate total size from number of mipmaps, faces and size\n imgData->size = Image::calculateSize(imgData->num_mipmaps, numFaces,\n imgData->width, imgData->height, imgData->depth, imgData->format);\n\n stream->skip(header.bytesOfKeyValueData);\n\n \/\/ Bind output buffer\n MemoryDataStreamPtr output(OGRE_NEW MemoryDataStream(imgData->size));\n\n \/\/ Now deal with the data\n uchar* destPtr = output->getPtr();\n uint32 mipOffset = 0;\n for (uint32 level = 0; level < header.numberOfMipmapLevels; ++level)\n {\n uint32 imageSize = 0;\n stream->read(&imageSize, sizeof(uint32));\n\n for(uint32 face = 0; face < numFaces; ++face)\n {\n uchar* placePtr = destPtr + ((imgData->size)\/numFaces)*face + mipOffset; \/\/ shuffle mip and face\n stream->read(placePtr, imageSize);\n }\n mipOffset += imageSize;\n }\n\n result.first = output;\n result.second = CodecDataPtr(imgData);\n \n return true;\n }\n}\n<commit_msg>OgreETCCodec: convert tabs to spaces<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreETCCodec.h\"\n#include \"OgreImage.h\"\n\n#define FOURCC(c0, c1, c2, c3) (c0 | (c1 << 8) | (c2 << 16) | (c3 << 24))\n#define KTX_ENDIAN_REF (0x04030201)\n#define KTX_ENDIAN_REF_REV (0x01020304)\n\n\/\/ In a PKM-file, the codecs are stored using the following identifiers\n\/\/\n\/\/ identifier value codec\n\/\/ --------------------------------------------------------------------\n\/\/ ETC1_RGB_NO_MIPMAPS 0 GL_ETC1_RGB8_OES\n\/\/ ETC2PACKAGE_RGB_NO_MIPMAPS 1 GL_COMPRESSED_RGB8_ETC2\n\/\/ ETC2PACKAGE_RGBA_NO_MIPMAPS_OLD 2, not used -\n\/\/ ETC2PACKAGE_RGBA_NO_MIPMAPS 3 GL_COMPRESSED_RGBA8_ETC2_EAC\n\/\/ ETC2PACKAGE_RGBA1_NO_MIPMAPS 4 GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2\n\/\/ ETC2PACKAGE_R_NO_MIPMAPS 5 GL_COMPRESSED_R11_EAC\n\/\/ ETC2PACKAGE_RG_NO_MIPMAPS 6 GL_COMPRESSED_RG11_EAC\n\/\/ ETC2PACKAGE_R_SIGNED_NO_MIPMAPS 7 GL_COMPRESSED_SIGNED_R11_EAC\n\/\/ ETC2PACKAGE_RG_SIGNED_NO_MIPMAPS 8 GL_COMPRESSED_SIGNED_RG11_EAC\n\nnamespace Ogre {\n\n const uint32 PKM_MAGIC = FOURCC('P', 'K', 'M', ' ');\n const uint32 KTX_MAGIC = FOURCC(0xAB, 0x4B, 0x54, 0x58);\n\n typedef struct {\n uint8 name[4];\n uint8 version[2];\n uint8 iTextureTypeMSB;\n uint8 iTextureTypeLSB;\n uint8 iPaddedWidthMSB;\n uint8 iPaddedWidthLSB;\n uint8 iPaddedHeightMSB;\n uint8 iPaddedHeightLSB;\n uint8 iWidthMSB;\n uint8 iWidthLSB;\n uint8 iHeightMSB;\n uint8 iHeightLSB;\n } PKMHeader;\n\n typedef struct {\n uint8 identifier[12];\n uint32 endianness;\n uint32 glType;\n uint32 glTypeSize;\n uint32 glFormat;\n uint32 glInternalFormat;\n uint32 glBaseInternalFormat;\n uint32 pixelWidth;\n uint32 pixelHeight;\n uint32 pixelDepth;\n uint32 numberOfArrayElements;\n uint32 numberOfFaces;\n uint32 numberOfMipmapLevels;\n uint32 bytesOfKeyValueData;\n } KTXHeader;\n\n \/\/---------------------------------------------------------------------\n ETCCodec* ETCCodec::msPKMInstance = 0;\n ETCCodec* ETCCodec::msKTXInstance = 0;\n \/\/---------------------------------------------------------------------\n void ETCCodec::startup(void)\n {\n if (!msPKMInstance)\n {\n msPKMInstance = OGRE_NEW ETCCodec(\"pkm\");\n Codec::registerCodec(msPKMInstance);\n }\n\n if (!msKTXInstance)\n {\n msKTXInstance = OGRE_NEW ETCCodec(\"ktx\");\n Codec::registerCodec(msKTXInstance);\n }\n\n LogManager::getSingleton().logMessage(LML_NORMAL,\n \"ETC codec registering\");\n }\n \/\/---------------------------------------------------------------------\n void ETCCodec::shutdown(void)\n {\n if(msPKMInstance)\n {\n Codec::unregisterCodec(msPKMInstance);\n OGRE_DELETE msPKMInstance;\n msPKMInstance = 0;\n }\n\n if(msKTXInstance)\n {\n Codec::unregisterCodec(msKTXInstance);\n OGRE_DELETE msKTXInstance;\n msKTXInstance = 0;\n }\n }\n \/\/---------------------------------------------------------------------\n ETCCodec::ETCCodec(const String &type):\n mType(type)\n {\n }\n \/\/---------------------------------------------------------------------\n DataStreamPtr ETCCodec::encode(const MemoryDataStreamPtr& input,\n const Codec::CodecDataPtr& pData) const\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,\n \"ETC encoding not supported\",\n \"ETCCodec::encode\" ) ;\n }\n \/\/---------------------------------------------------------------------\n void ETCCodec::encodeToFile(const MemoryDataStreamPtr& input, const String& outFileName,\n const Codec::CodecDataPtr& pData) const\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,\n \"ETC encoding not supported\",\n \"ETCCodec::encodeToFile\" ) ;\n }\n \/\/---------------------------------------------------------------------\n Codec::DecodeResult ETCCodec::decode(const DataStreamPtr& stream) const\n {\n DecodeResult ret;\n if (decodeKTX(stream, ret))\n return ret;\n\n stream->seek(0);\n if (decodePKM(stream, ret))\n return ret;\n\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,\n \"This is not a valid ETC file!\", \"ETCCodec::decode\");\n }\n \/\/---------------------------------------------------------------------\n String ETCCodec::getType() const\n {\n return mType;\n }\n \/\/---------------------------------------------------------------------\n void ETCCodec::flipEndian(void * pData, size_t size, size_t count)\n {\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n Bitwise::bswapChunks(pData, size, count);\n#endif\n }\n \/\/---------------------------------------------------------------------\n void ETCCodec::flipEndian(void * pData, size_t size)\n {\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n Bitwise::bswapBuffer(pData, size);\n#endif\n }\n \/\/---------------------------------------------------------------------\n String ETCCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const\n {\n if (maxbytes >= sizeof(uint32))\n {\n uint32 fileType;\n memcpy(&fileType, magicNumberPtr, sizeof(uint32));\n flipEndian(&fileType, sizeof(uint32));\n\n if (PKM_MAGIC == fileType)\n return String(\"pkm\");\n\n if (KTX_MAGIC == fileType)\n return String(\"ktx\");\n }\n\n return BLANKSTRING;\n }\n \/\/---------------------------------------------------------------------\n bool ETCCodec::decodePKM(const DataStreamPtr& stream, DecodeResult& result) const\n {\n PKMHeader header;\n\n \/\/ Read the ETC header\n stream->read(&header, sizeof(PKMHeader));\n\n if (PKM_MAGIC != FOURCC(header.name[0], header.name[1], header.name[2], header.name[3]) ) \/\/ \"PKM 10\"\n return false;\n\n uint16 width = (header.iWidthMSB << 8) | header.iWidthLSB;\n uint16 height = (header.iHeightMSB << 8) | header.iHeightLSB;\n uint16 paddedWidth = (header.iPaddedWidthMSB << 8) | header.iPaddedWidthLSB;\n uint16 paddedHeight = (header.iPaddedHeightMSB << 8) | header.iPaddedHeightLSB;\n uint16 type = (header.iTextureTypeMSB << 8) | header.iTextureTypeLSB;\n\n ImageData *imgData = OGRE_NEW ImageData();\n imgData->depth = 1;\n imgData->width = width;\n imgData->height = height;\n\n \/\/ File version 2.0 supports ETC2 in addition to ETC1\n if(header.version[0] == '2' && header.version[1] == '0')\n {\n switch (type) {\n case 0:\n imgData->format = PF_ETC1_RGB8;\n break;\n\n \/\/ GL_COMPRESSED_RGB8_ETC2\n case 1:\n imgData->format = PF_ETC2_RGB8;\n break;\n\n \/\/ GL_COMPRESSED_RGBA8_ETC2_EAC\n case 3:\n imgData->format = PF_ETC2_RGBA8;\n break;\n\n \/\/ GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2\n case 4:\n imgData->format = PF_ETC2_RGB8A1;\n break;\n\n \/\/ Default case is ETC1\n default:\n imgData->format = PF_ETC1_RGB8;\n break;\n }\n }\n else\n imgData->format = PF_ETC1_RGB8;\n\n \/\/ ETC has no support for mipmaps - malideveloper.com has a example\n \/\/ where the load mipmap levels from different external files\n imgData->num_mipmaps = 0;\n\n \/\/ ETC is a compressed format\n imgData->flags |= IF_COMPRESSED;\n\n \/\/ Calculate total size from number of mipmaps, faces and size\n imgData->size = (paddedWidth * paddedHeight) >> 1;\n\n \/\/ Bind output buffer\n MemoryDataStreamPtr output(OGRE_NEW MemoryDataStream(imgData->size));\n\n \/\/ Now deal with the data\n void *destPtr = output->getPtr();\n stream->read(destPtr, imgData->size);\n destPtr = static_cast<void*>(static_cast<uchar*>(destPtr));\n\n DecodeResult ret;\n ret.first = output;\n ret.second = CodecDataPtr(imgData);\n\n return true;\n }\n \/\/---------------------------------------------------------------------\n bool ETCCodec::decodeKTX(const DataStreamPtr& stream, DecodeResult& result) const\n {\n KTXHeader header;\n \/\/ Read the ETC1 header\n stream->read(&header, sizeof(KTXHeader));\n\n const uint8 KTXFileIdentifier[12] = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A };\n if (memcmp(KTXFileIdentifier, &header.identifier, sizeof(KTXFileIdentifier)) != 0 )\n return false;\n\n if (header.endianness == KTX_ENDIAN_REF_REV)\n flipEndian(&header.glType, sizeof(uint32));\n\n ImageData *imgData = OGRE_NEW ImageData();\n imgData->depth = 1;\n imgData->width = header.pixelWidth;\n imgData->height = header.pixelHeight;\n imgData->num_mipmaps = static_cast<uint8>(header.numberOfMipmapLevels - 1);\n\n switch(header.glInternalFormat)\n {\n case 37492: \/\/ GL_COMPRESSED_RGB8_ETC2\n imgData->format = PF_ETC2_RGB8;\n break;\n case 37496:\/\/ GL_COMPRESSED_RGBA8_ETC2_EAC\n imgData->format = PF_ETC2_RGBA8;\n break;\n case 37494: \/\/ GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2\n imgData->format = PF_ETC2_RGB8A1;\n break;\n case 35986: \/\/ ATC_RGB\n imgData->format = PF_ATC_RGB;\n break;\n case 35987: \/\/ ATC_RGB_Explicit\n imgData->format = PF_ATC_RGBA_EXPLICIT_ALPHA;\n break;\n case 34798: \/\/ ATC_RGB_Interpolated\n imgData->format = PF_ATC_RGBA_INTERPOLATED_ALPHA;\n break;\n case 33777: \/\/ DXT 1\n imgData->format = PF_DXT1;\n break;\n case 33778: \/\/ DXT 3\n imgData->format = PF_DXT3;\n break;\n case 33779: \/\/ DXT 5\n imgData->format = PF_DXT5;\n break;\n case 0x8c00: \/\/ COMPRESSED_RGB_PVRTC_4BPPV1_IMG\n imgData->format = PF_PVRTC_RGB4;\n break;\n case 0x8c01: \/\/ COMPRESSED_RGB_PVRTC_2BPPV1_IMG\n imgData->format = PF_PVRTC_RGB2;\n break;\n case 0x8c02: \/\/ COMPRESSED_RGBA_PVRTC_4BPPV1_IMG\n imgData->format = PF_PVRTC_RGBA4;\n break;\n case 0x8c03: \/\/ COMPRESSED_RGBA_PVRTC_2BPPV1_IMG\n imgData->format = PF_PVRTC_RGBA2;\n break;\n default:\n imgData->format = PF_ETC1_RGB8;\n break;\n }\n\n imgData->flags = 0;\n if (header.glType == 0 || header.glFormat == 0)\n imgData->flags |= IF_COMPRESSED;\n\n size_t numFaces = header.numberOfFaces;\n if (numFaces > 1)\n imgData->flags |= IF_CUBEMAP;\n \/\/ Calculate total size from number of mipmaps, faces and size\n imgData->size = Image::calculateSize(imgData->num_mipmaps, numFaces,\n imgData->width, imgData->height, imgData->depth, imgData->format);\n\n stream->skip(header.bytesOfKeyValueData);\n\n \/\/ Bind output buffer\n MemoryDataStreamPtr output(OGRE_NEW MemoryDataStream(imgData->size));\n\n \/\/ Now deal with the data\n uchar* destPtr = output->getPtr();\n uint32 mipOffset = 0;\n for (uint32 level = 0; level < header.numberOfMipmapLevels; ++level)\n {\n uint32 imageSize = 0;\n stream->read(&imageSize, sizeof(uint32));\n\n for(uint32 face = 0; face < numFaces; ++face)\n {\n uchar* placePtr = destPtr + ((imgData->size)\/numFaces)*face + mipOffset; \/\/ shuffle mip and face\n stream->read(placePtr, imageSize);\n }\n mipOffset += imageSize;\n }\n\n result.first = output;\n result.second = CodecDataPtr(imgData);\n\n return true;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/_________________________________________________________________________\n\/\/ Implementation version 1 of the clusterization algorithm \n\/\/ \n\/\/*-- Author: Yves Schutz (SUBATECH) \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ --- ROOT system ---\n\n#include \"TMath.h\" \n\n\/\/ --- Standard library ---\n\n#include <iostream.h>\n\n\/\/ --- AliRoot header files ---\n\n#include \"AliPHOSClusterizerv1.h\"\n#include \"AliPHOSDigit.h\"\n#include \"AliPHOSEmcRecPoint.h\"\n#include \"AliPHOSPpsdRecPoint.h\"\n#include \"AliPHOSv0.h\" \n#include \"AliRun.h\" \n\nClassImp(AliPHOSClusterizerv1)\n\n\/\/____________________________________________________________________________\nAliPHOSClusterizerv1::AliPHOSClusterizerv1()\n{\n \/\/ default ctor (to be used)\n\n fA = 0.;\n fB = 0.01 ;\n fGeom = AliPHOSGeometry::GetInstance();\n fNumberOfEmcClusters = 0 ; \n fNumberOfPpsdClusters = 0 ; \n fEmcClusteringThreshold = 0.1; \n fEmcEnergyThreshold = 0.01; \n fPpsdClusteringThreshold = 0.00000015; \n fPpsdEnergyThreshold = 0.0000001; \n fW0 = 4.5 ;\n fLocMaxCut = 0.06 ;\n}\n\n\/\/____________________________________________________________________________\nInt_t AliPHOSClusterizerv1::AreNeighbours(AliPHOSDigit * d1, AliPHOSDigit * d2)\n{\n \/\/ Gives the neighbourness of two digits = 0 are not neighbour but continue searching \n \/\/ = 1 are neighbour\n \/\/ = 2 are not neighbour but do not continue searching\n \/\/ neighbours are defined as digits having at least common vertex\n \/\/ The order of d1 and d2 is important: first (d1) should be a digit already in a cluster \n \/\/ which is compared to a digit (d2) not yet in a cluster \n\n Int_t rv = 0 ; \n\n Int_t relid1[4] ; \n fGeom->AbsToRelNumbering(d1->GetId(), relid1) ; \n\n Int_t relid2[4] ; \n fGeom->AbsToRelNumbering(d2->GetId(), relid2) ; \n \n if ( (relid1[0] == relid2[0]) && (relid1[1]==relid2[1]) ) { \/\/ inside the same PHOS module and the same PPSD Module \n Int_t rowdiff = TMath::Abs( relid1[2] - relid2[2] ) ; \n Int_t coldiff = TMath::Abs( relid1[3] - relid2[3] ) ; \n \n if (( coldiff <= 1 ) && ( rowdiff <= 1 )){\n rv = 1 ; \n }\n else {\n if((relid2[2] > relid1[2]) && (relid2[3] > relid1[3]+1)) \n\trv = 2; \/\/ Difference in row numbers is too large to look further \n }\n\n } \n else {\n \n if( (relid1[0] < relid2[0]) || (relid1[1] < relid2[1]) ) \n rv=2 ;\n\n }\n if((relid1[1]>0) && (relid1[1]<16) ) rv = 2 ; \/\/Do NOT clusterize upper PPSD \n return rv ; \n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSClusterizerv1::FillandSort(const DigitsList * dl, TObjArray * tl) \n{\n \/\/ Copies the digits with energy above thershold and sorts the list\n \/\/ according to increasing Id number\n\n Int_t relid[4] ; \n \n TIter next(dl) ; \n AliPHOSDigit * digit ;\n \n \n \n\n while ( (digit = (AliPHOSDigit *)next()) ) { \n\n\/\/ cout << \" clusterizerv1 \" << endl ;\n\/\/ int nprim = digit->GetNprimary() ;\n\/\/ int * aprim = digit->GetPrimary() ;\n\/\/ for ( int ii = 0 ; ii < nprim ; ii++)\n\/\/ cout << ii << \" prim = \" << aprim[ii] << endl ;\n\n Int_t id = digit->GetId() ; \n Float_t ene = Calibrate(digit->GetAmp()) ; \n fGeom->AbsToRelNumbering(id, relid) ;\n if(relid[1]==0){ \/\/ EMC\n if ( ene > fEmcEnergyThreshold )\n\ttl->Add(digit) ;\n }\n\n else { \/\/Ppsd\n if ( ene > fPpsdEnergyThreshold )\n\ttl->Add(digit) ; \n }\n\n }\n tl->Sort() ; \n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSClusterizerv1:: GetNumberOfClustersFound(Int_t * numb) \n{\n \/\/ Fills numb with the number of EMC (numb[0]) clusters found\n \/\/ PPSD (numb[1]) clusters found\n\n numb[0] = fNumberOfEmcClusters ; \n numb[1] = fNumberOfPpsdClusters ; \n}\n\n\/\/____________________________________________________________________________\nBool_t AliPHOSClusterizerv1::IsInEmc(AliPHOSDigit * digit) \n{\n \/\/ Tells if (true) or not (false) the digit is in a PHOS-EMC module\n \n Bool_t rv = kFALSE ; \n\n Int_t relid[4] ; \n fGeom->AbsToRelNumbering(digit->GetId(), relid) ; \n\n if ( relid[1] == 0 )\n rv = kTRUE; \n\n return rv ; \n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSClusterizerv1::MakeClusters(const DigitsList * dl, \n\t\t\t\t\tAliPHOSRecPoint::RecPointsList * emcl, \n\t\t\t\t\tAliPHOSRecPoint::RecPointsList * ppsdl)\n{\n \/\/ Steering method to construct the clusters stored in a list of Reconstructed Points\n \/\/ A cluster is defined as a list of neighbour digits\n\n fNumberOfEmcClusters = 0 ;\n fNumberOfPpsdClusters = 0 ;\n\n \/\/ Fill and sort the working digits list\n TObjArray tempodigitslist( dl->GetEntries() ) ;\n FillandSort(dl, &tempodigitslist) ; \n\n \/\/ Clusterization starts \n TIter nextdigit(&tempodigitslist) ; \n AliPHOSDigit * digit ; \n Bool_t notremoved = kTRUE ;\n\n while ( (digit = (AliPHOSDigit *)nextdigit()) ) { \/\/ scan over the list of digits\n AliPHOSRecPoint * clu ; \n\n AliPHOSDigit ** clusterdigitslist = new AliPHOSDigit*[dl->GetEntries()] ; \n Int_t index ;\n if (( ( IsInEmc(digit) ) && ( Calibrate(digit->GetAmp() ) > fEmcClusteringThreshold ) ) || \n ( ( !IsInEmc(digit) ) && ( Calibrate(digit->GetAmp() ) > fPpsdClusteringThreshold ) ) ) {\n \n Int_t iDigitInCluster = 0 ; \n\n if ( IsInEmc(digit) ) { \n\t\/\/ start a new EMC RecPoint\n\tif(fNumberOfEmcClusters >= emcl->GetSize())\n\t emcl->Expand(2*fNumberOfEmcClusters+1) ;\n\t(*emcl)[fNumberOfEmcClusters] = new AliPHOSEmcRecPoint(fW0, fLocMaxCut) ;\n\tclu = (AliPHOSEmcRecPoint *) emcl->At(fNumberOfEmcClusters) ; \n\tfNumberOfEmcClusters++ ; \n\tclu->AddDigit(*digit, Calibrate(digit->GetAmp())) ; \n\tclusterdigitslist[iDigitInCluster] = digit ;\t\n\tiDigitInCluster++ ; \n\ttempodigitslist.Remove(digit) ; \n\n }\n\n else { \n\t\n\t\/\/ start a new PPSD cluster\n\tif(fNumberOfPpsdClusters >= ppsdl->GetSize())\n\t ppsdl->Expand(2*fNumberOfPpsdClusters) ;\n\t\n\t(*ppsdl)[fNumberOfPpsdClusters] = new AliPHOSPpsdRecPoint() ;\n\tclu = (AliPHOSPpsdRecPoint *) ppsdl->At(fNumberOfPpsdClusters) ; \n\tfNumberOfPpsdClusters++ ; \n\tclu->AddDigit(*digit, Calibrate(digit->GetAmp()) ) ;\t\n\tclusterdigitslist[iDigitInCluster] = digit ;\t\n\tiDigitInCluster++ ; \n\ttempodigitslist.Remove(digit) ; \n nextdigit.Reset() ;\n\t\n\t\/\/ Here we remove resting EMC digits, which cannot make cluster\n\n if( notremoved ) { \n\t \n\t while( ( digit = (AliPHOSDigit *)nextdigit() ) ) {\n\t \n if( IsInEmc(digit) ) \n\t tempodigitslist.Remove(digit) ;\n else \n\t break ;\n\t \n\t } \/\/ while digit \n\t \n\t} \/\/ if notremoved \n\t\n } \/\/ else \n \n nextdigit.Reset() ;\n\n AliPHOSDigit * digitN ; \n index = 0 ;\n while (index < iDigitInCluster){ \/\/ scan over digits already in cluster \n\tdigit = clusterdigitslist[index] ; \n\tindex++ ; \n while ( (digitN = (AliPHOSDigit *)nextdigit()) ) { \/\/ scan over the reduced list of digits \n\t Int_t ineb = AreNeighbours(digit, digitN); \/\/ call (digit,digitN) in THAT oder !!!!!\n switch (ineb ) {\n case 0 : \/\/ not a neighbour\n\t break ;\t \n\t case 1 : \/\/ are neighbours \n\t clu->AddDigit(*digitN, Calibrate( digitN->GetAmp() ) ) ;\n\t clusterdigitslist[iDigitInCluster] = digitN ; \n\t iDigitInCluster++ ; \n\t tempodigitslist.Remove(digitN) ;\n\t break ;\n case 2 : \/\/ too far from each other\n\t goto endofloop; \n\t } \/\/ switch\n\t \n\t} \/\/ while digitN\n\n endofloop: ;\n\tnextdigit.Reset() ; \n\t\n } \/\/ loop over cluster \n } \/\/below energy theshold \n \n delete[] clusterdigitslist ; \n \n } \/\/ while digit\n\n tempodigitslist.Clear() ; \n\n ppsdl->Sort() ;\n Int_t index ;\n for(index = 0; index < ppsdl->GetEntries(); index++)\n ((AliPHOSPpsdRecPoint *)ppsdl->At(index))->SetIndexInList(index) ;\n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSClusterizerv1::PrintParameters() \n{\n \/\/ Print the energy thresholds \n\n cout << \"PHOS Clusterizer version 1 :\" << endl \n << \" EMC Clustering threshold = \" << fEmcClusteringThreshold << endl\n << \" EMC Energy threshold = \" << fEmcEnergyThreshold << endl \n << \" PPSD Clustering threshold = \" << fPpsdClusteringThreshold << endl\n << \" PPSD Energy threshold = \" << fPpsdEnergyThreshold << endl ; \n}\n<commit_msg>A bug with expansion of PPSD RPointlist is corrected<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/_________________________________________________________________________\n\/\/ Implementation version 1 of the clusterization algorithm \n\/\/ \n\/\/*-- Author: Yves Schutz (SUBATECH) \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ --- ROOT system ---\n\n#include \"TMath.h\" \n\n\/\/ --- Standard library ---\n\n#include <iostream.h>\n\n\/\/ --- AliRoot header files ---\n\n#include \"AliPHOSClusterizerv1.h\"\n#include \"AliPHOSDigit.h\"\n#include \"AliPHOSEmcRecPoint.h\"\n#include \"AliPHOSPpsdRecPoint.h\"\n#include \"AliPHOSv0.h\" \n#include \"AliRun.h\" \n\nClassImp(AliPHOSClusterizerv1)\n\n\/\/____________________________________________________________________________\nAliPHOSClusterizerv1::AliPHOSClusterizerv1()\n{\n \/\/ default ctor (to be used)\n\n fA = 0.;\n fB = 0.01 ;\n fGeom = AliPHOSGeometry::GetInstance();\n fNumberOfEmcClusters = 0 ; \n fNumberOfPpsdClusters = 0 ; \n fEmcClusteringThreshold = 0.1; \n fEmcEnergyThreshold = 0.01; \n fPpsdClusteringThreshold = 0.00000015; \n fPpsdEnergyThreshold = 0.0000001; \n fW0 = 4.5 ;\n fLocMaxCut = 0.06 ;\n}\n\n\/\/____________________________________________________________________________\nInt_t AliPHOSClusterizerv1::AreNeighbours(AliPHOSDigit * d1, AliPHOSDigit * d2)\n{\n \/\/ Gives the neighbourness of two digits = 0 are not neighbour but continue searching \n \/\/ = 1 are neighbour\n \/\/ = 2 are not neighbour but do not continue searching\n \/\/ neighbours are defined as digits having at least common vertex\n \/\/ The order of d1 and d2 is important: first (d1) should be a digit already in a cluster \n \/\/ which is compared to a digit (d2) not yet in a cluster \n\n Int_t rv = 0 ; \n\n Int_t relid1[4] ; \n fGeom->AbsToRelNumbering(d1->GetId(), relid1) ; \n\n Int_t relid2[4] ; \n fGeom->AbsToRelNumbering(d2->GetId(), relid2) ; \n \n if ( (relid1[0] == relid2[0]) && (relid1[1]==relid2[1]) ) { \/\/ inside the same PHOS module and the same PPSD Module \n Int_t rowdiff = TMath::Abs( relid1[2] - relid2[2] ) ; \n Int_t coldiff = TMath::Abs( relid1[3] - relid2[3] ) ; \n \n if (( coldiff <= 1 ) && ( rowdiff <= 1 )){\n rv = 1 ; \n }\n else {\n if((relid2[2] > relid1[2]) && (relid2[3] > relid1[3]+1)) \n\trv = 2; \/\/ Difference in row numbers is too large to look further \n }\n\n } \n else {\n \n if( (relid1[0] < relid2[0]) || (relid1[1] < relid2[1]) ) \n rv=2 ;\n\n }\n if((relid1[1]>0) && (relid1[1]<16) ) rv = 2 ; \/\/Do NOT clusterize upper PPSD \n return rv ; \n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSClusterizerv1::FillandSort(const DigitsList * dl, TObjArray * tl) \n{\n \/\/ Copies the digits with energy above thershold and sorts the list\n \/\/ according to increasing Id number\n\n Int_t relid[4] ; \n \n TIter next(dl) ; \n AliPHOSDigit * digit ;\n \n \n \n\n while ( (digit = (AliPHOSDigit *)next()) ) { \n\n\/\/ cout << \" clusterizerv1 \" << endl ;\n\/\/ int nprim = digit->GetNprimary() ;\n\/\/ int * aprim = digit->GetPrimary() ;\n\/\/ for ( int ii = 0 ; ii < nprim ; ii++)\n\/\/ cout << ii << \" prim = \" << aprim[ii] << endl ;\n\n Int_t id = digit->GetId() ; \n Float_t ene = Calibrate(digit->GetAmp()) ; \n fGeom->AbsToRelNumbering(id, relid) ;\n if(relid[1]==0){ \/\/ EMC\n if ( ene > fEmcEnergyThreshold )\n\ttl->Add(digit) ;\n }\n\n else { \/\/Ppsd\n if ( ene > fPpsdEnergyThreshold )\n\ttl->Add(digit) ; \n }\n\n }\n tl->Sort() ; \n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSClusterizerv1:: GetNumberOfClustersFound(Int_t * numb) \n{\n \/\/ Fills numb with the number of EMC (numb[0]) clusters found\n \/\/ PPSD (numb[1]) clusters found\n\n numb[0] = fNumberOfEmcClusters ; \n numb[1] = fNumberOfPpsdClusters ; \n}\n\n\/\/____________________________________________________________________________\nBool_t AliPHOSClusterizerv1::IsInEmc(AliPHOSDigit * digit) \n{\n \/\/ Tells if (true) or not (false) the digit is in a PHOS-EMC module\n \n Bool_t rv = kFALSE ; \n\n Int_t relid[4] ; \n fGeom->AbsToRelNumbering(digit->GetId(), relid) ; \n\n if ( relid[1] == 0 )\n rv = kTRUE; \n\n return rv ; \n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSClusterizerv1::MakeClusters(const DigitsList * dl, \n\t\t\t\t\tAliPHOSRecPoint::RecPointsList * emcl, \n\t\t\t\t\tAliPHOSRecPoint::RecPointsList * ppsdl)\n{\n \/\/ Steering method to construct the clusters stored in a list of Reconstructed Points\n \/\/ A cluster is defined as a list of neighbour digits\n\n fNumberOfEmcClusters = 0 ;\n fNumberOfPpsdClusters = 0 ;\n\n \/\/ Fill and sort the working digits list\n TObjArray tempodigitslist( dl->GetEntries() ) ;\n FillandSort(dl, &tempodigitslist) ; \n\n \/\/ Clusterization starts \n TIter nextdigit(&tempodigitslist) ; \n AliPHOSDigit * digit ; \n Bool_t notremoved = kTRUE ;\n\n while ( (digit = (AliPHOSDigit *)nextdigit()) ) { \/\/ scan over the list of digits\n AliPHOSRecPoint * clu ; \n\n AliPHOSDigit ** clusterdigitslist = new AliPHOSDigit*[dl->GetEntries()] ; \n Int_t index ;\n if (( ( IsInEmc(digit) ) && ( Calibrate(digit->GetAmp() ) > fEmcClusteringThreshold ) ) || \n ( ( !IsInEmc(digit) ) && ( Calibrate(digit->GetAmp() ) > fPpsdClusteringThreshold ) ) ) {\n \n Int_t iDigitInCluster = 0 ; \n\n if ( IsInEmc(digit) ) { \n\t\/\/ start a new EMC RecPoint\n\tif(fNumberOfEmcClusters >= emcl->GetSize())\n\t emcl->Expand(2*fNumberOfEmcClusters+1) ;\n\t(*emcl)[fNumberOfEmcClusters] = new AliPHOSEmcRecPoint(fW0, fLocMaxCut) ;\n\tclu = (AliPHOSEmcRecPoint *) emcl->At(fNumberOfEmcClusters) ; \n\tfNumberOfEmcClusters++ ; \n\tclu->AddDigit(*digit, Calibrate(digit->GetAmp())) ; \n\tclusterdigitslist[iDigitInCluster] = digit ;\t\n\tiDigitInCluster++ ; \n\ttempodigitslist.Remove(digit) ; \n\n }\n\n else { \n\t\n\t\/\/ start a new PPSD cluster\n\tif(fNumberOfPpsdClusters >= ppsdl->GetSize())\n\t ppsdl->Expand(2*fNumberOfPpsdClusters+1) ;\n\t\n\t(*ppsdl)[fNumberOfPpsdClusters] = new AliPHOSPpsdRecPoint() ;\n\tclu = (AliPHOSPpsdRecPoint *) ppsdl->At(fNumberOfPpsdClusters) ; \n\tfNumberOfPpsdClusters++ ; \n\tclu->AddDigit(*digit, Calibrate(digit->GetAmp()) ) ;\t\n\tclusterdigitslist[iDigitInCluster] = digit ;\t\n\tiDigitInCluster++ ; \n\ttempodigitslist.Remove(digit) ; \n nextdigit.Reset() ;\n\t\n\t\/\/ Here we remove resting EMC digits, which cannot make cluster\n\n if( notremoved ) { \n\t \n\t while( ( digit = (AliPHOSDigit *)nextdigit() ) ) {\n\t \n if( IsInEmc(digit) ) \n\t tempodigitslist.Remove(digit) ;\n else \n\t break ;\n\t \n\t } \/\/ while digit \n\t \n\t} \/\/ if notremoved \n\t\n } \/\/ else \n \n nextdigit.Reset() ;\n\n AliPHOSDigit * digitN ; \n index = 0 ;\n while (index < iDigitInCluster){ \/\/ scan over digits already in cluster \n\tdigit = clusterdigitslist[index] ; \n\tindex++ ; \n while ( (digitN = (AliPHOSDigit *)nextdigit()) ) { \/\/ scan over the reduced list of digits \n\t Int_t ineb = AreNeighbours(digit, digitN); \/\/ call (digit,digitN) in THAT oder !!!!!\n switch (ineb ) {\n case 0 : \/\/ not a neighbour\n\t break ;\t \n\t case 1 : \/\/ are neighbours \n\t clu->AddDigit(*digitN, Calibrate( digitN->GetAmp() ) ) ;\n\t clusterdigitslist[iDigitInCluster] = digitN ; \n\t iDigitInCluster++ ; \n\t tempodigitslist.Remove(digitN) ;\n\t break ;\n case 2 : \/\/ too far from each other\n\t goto endofloop; \n\t } \/\/ switch\n\t \n\t} \/\/ while digitN\n\n endofloop: ;\n\tnextdigit.Reset() ; \n\t\n } \/\/ loop over cluster \n } \/\/below energy theshold \n \n delete[] clusterdigitslist ; \n \n } \/\/ while digit\n\n tempodigitslist.Clear() ; \n\n ppsdl->Sort() ;\n Int_t index ;\n for(index = 0; index < ppsdl->GetEntries(); index++)\n ((AliPHOSPpsdRecPoint *)ppsdl->At(index))->SetIndexInList(index) ;\n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSClusterizerv1::PrintParameters() \n{\n \/\/ Print the energy thresholds \n\n cout << \"PHOS Clusterizer version 1 :\" << endl \n << \" EMC Clustering threshold = \" << fEmcClusteringThreshold << endl\n << \" EMC Energy threshold = \" << fEmcEnergyThreshold << endl \n << \" PPSD Clustering threshold = \" << fPpsdClusteringThreshold << endl\n << \" PPSD Energy threshold = \" << fPpsdEnergyThreshold << endl ; \n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMPIController.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkMPIController.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkOutputWindow.h\"\n\n#include \"vtkMPI.h\"\n\nint vtkMPIController::Initialized = 0;\nchar vtkMPIController::ProcessorName[MPI_MAX_PROCESSOR_NAME] = \"\";\n\n\/\/ Output window which prints out the process id\n\/\/ with the error or warning messages\nclass VTK_PARALLEL_EXPORT vtkMPIOutputWindow : public vtkOutputWindow\n{\npublic:\n vtkTypeRevisionMacro(vtkMPIOutputWindow,vtkOutputWindow);\n\n void DisplayText(const char* t)\n {\n if (this->Controller)\n {\n cout << \"Process id: \" << this->Controller->GetLocalProcessId()\n << \" >> \";\n }\n cout << t;\n }\n\n vtkMPIOutputWindow()\n {\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkMPIOutputWindow\");\n if (ret)\n ret->Delete();\n this->Controller = 0;\n }\n\n friend class vtkMPIController;\n\nprotected:\n\n vtkMPIController* Controller;\n vtkMPIOutputWindow(const vtkMPIOutputWindow&);\n void operator=(const vtkMPIOutputWindow&);\n\n};\n\nvoid vtkMPIController::CreateOutputWindow()\n{\n vtkMPIOutputWindow* window = new vtkMPIOutputWindow;\n window->Controller = this;\n this->OutputWindow = window;\n vtkOutputWindow::SetInstance(this->OutputWindow);\n}\n\nvtkCxxRevisionMacro(vtkMPIOutputWindow, \"1.18\");\n\nvtkCxxRevisionMacro(vtkMPIController, \"1.18\");\nvtkStandardNewMacro(vtkMPIController);\n\n\/\/----------------------------------------------------------------------------\nvtkMPIController::vtkMPIController()\n{\n \/\/ If MPI was already initialized obtain rank and size.\n if (vtkMPIController::Initialized)\n {\n this->InitializeCommunicator(vtkMPICommunicator::GetWorldCommunicator());\n \/\/ Copy vtkMPIController::WorldRMICommunicataor which is created when\n \/\/ MPI is initialized\n vtkMPICommunicator* comm = vtkMPICommunicator::New();\n comm->CopyFrom(vtkMPIController::WorldRMICommunicator);\n this->RMICommunicator = comm;\n }\n\n this->OutputWindow = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMPIController::~vtkMPIController()\n{\n this->SetCommunicator(0);\n if (this->RMICommunicator)\n {\n this->RMICommunicator->Delete();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMPIController::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n os << indent << \"Initialized: \" << ( vtkMPIController::Initialized ? \"(yes)\" : \"(no)\" ) << endl;\n}\n\n\/\/ Set the number of processes and maximum number of processes\n\/\/ to the size obtained from MPI.\nint vtkMPIController::InitializeNumberOfProcesses()\n{\n int err;\n\n this->Modified();\n\n vtkMPICommunicator* comm = (vtkMPICommunicator*)this->Communicator;\n if ( (err = MPI_Comm_size(*(comm->Comm->Handle), \n &(this->MaximumNumberOfProcesses))) \n != MPI_SUCCESS )\n {\n char *msg = vtkMPIController::ErrorString(err);\n vtkErrorMacro(\"MPI error occured: \" << msg);\n delete[] msg;\n return 0;\n }\n\n if (this->MaximumNumberOfProcesses > MAX_PROCESSES)\n {\n vtkWarningMacro(\"Maximum of \" << MAX_PROCESSES);\n this->MaximumNumberOfProcesses = MAX_PROCESSES;\n }\n \n this->NumberOfProcesses = this->MaximumNumberOfProcesses;\n \n if ( (err = MPI_Comm_rank(*(comm->Comm->Handle),&(this->LocalProcessId))) \n != MPI_SUCCESS)\n {\n char *msg = vtkMPIController::ErrorString(err);\n vtkErrorMacro(\"MPI error occured: \" << msg);\n delete[] msg;\n return 0;\n }\n return 1;\n}\n\nvtkMPICommunicator* vtkMPIController::WorldRMICommunicator=0;\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMPIController::Initialize(int* argc, char*** argv, \n int initializedExternally)\n{\n if (vtkMPIController::Initialized)\n {\n vtkWarningMacro(\"Already initialized.\");\n return;\n }\n \n \/\/ Can be done once in the program.\n vtkMPIController::Initialized = 1;\n if (initializedExternally == 0)\n {\n MPI_Init(argc, argv);\n }\n this->InitializeCommunicator(vtkMPICommunicator::GetWorldCommunicator());\n this->InitializeNumberOfProcesses();\n\n int tmp;\n MPI_Get_processor_name(ProcessorName, &tmp);\n \/\/ Make a copy of MPI_COMM_WORLD creating a new context.\n \/\/ This is used in the creating of the communicators after\n \/\/ Initialize() has been called. It has to be done here\n \/\/ because for this to work, all processes have to call\n \/\/ MPI_Comm_dup and this is the only method which is\n \/\/ guaranteed to be called by all processes.\n vtkMPIController::WorldRMICommunicator = vtkMPICommunicator::New();\n vtkMPIController::WorldRMICommunicator->Duplicate((vtkMPICommunicator*)this->Communicator);\n this->RMICommunicator = vtkMPIController::WorldRMICommunicator;\n \/\/ Since we use Delete to get rid of the reference, we should use NULL to register.\n this->RMICommunicator->Register(NULL);\n\n this->Modified();\n}\n\nconst char* vtkMPIController::GetProcessorName()\n{\n return ProcessorName;\n}\n\n\/\/ Good-bye world\n\/\/ There should be no MPI calls after this.\n\/\/ (Except maybe MPI_XXX_free()) unless finalized externally.\nvoid vtkMPIController::Finalize(int finalizedExternally)\n{\n if (vtkMPIController::Initialized)\n { \n vtkMPIController::WorldRMICommunicator->Delete();\n vtkMPIController::WorldRMICommunicator = 0;\n vtkMPICommunicator::WorldCommunicator->Delete();\n this->SetCommunicator(0);\n if (this->RMICommunicator)\n {\n this->RMICommunicator->Delete();\n this->RMICommunicator = 0;\n }\n if (finalizedExternally == 0)\n {\n MPI_Finalize();\n }\n vtkMPIController::Initialized = 0;\n this->Modified();\n } \n \n}\n\n\/\/ Called by SetCommunicator and constructor. It frees but does \n\/\/ not set RMIHandle (which should not be set by using MPI_Comm_dup\n\/\/ during construction).\nvoid vtkMPIController::InitializeCommunicator(vtkMPICommunicator* comm)\n{\n if (this->Communicator != comm) \n { \n if (this->Communicator != 0) \n { \n this->Communicator->UnRegister(this); \n }\n this->Communicator = comm; \n if (this->Communicator != 0) \n { \n this->Communicator->Register(this); \n } \n\n if (comm && comm->Comm->Handle)\n {\n this->InitializeNumberOfProcesses();\n }\n this->Modified(); \n } \n\n\n}\n\n\/\/ Delete the previous RMI communicator and creates a new one\n\/\/ by duplicating the user communicator.\nvoid vtkMPIController::InitializeRMICommunicator()\n{\n if ( this->RMICommunicator )\n {\n this->RMICommunicator->Delete();\n this->RMICommunicator = 0;\n }\n if (this->Communicator)\n {\n this->RMICommunicator = vtkMPICommunicator::New();\n ((vtkMPICommunicator*)this->RMICommunicator)->Duplicate((vtkMPICommunicator*)this->Communicator);\n }\n}\n\nvoid vtkMPIController::SetCommunicator(vtkMPICommunicator* comm)\n{\n this->InitializeCommunicator(comm);\n this->InitializeRMICommunicator();\n}\n\n \nvoid vtkMPIController::Barrier()\n{\n vtkMPICommunicator* comm = (vtkMPICommunicator*)this->Communicator;\n int err;\n if ( (err = MPI_Barrier(*(comm->Comm->Handle)) ) \n != MPI_SUCCESS ) \n {\n char *msg = vtkMPIController::ErrorString(err);\n vtkErrorMacro(\"MPI error occured: \" << msg);\n delete[] msg;\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Execute the method set as the SingleMethod.\nvoid vtkMPIController::SingleMethodExecute()\n{\n if(!vtkMPIController::Initialized)\n {\n vtkWarningMacro(\"MPI has to be initialized first.\");\n return;\n }\n\n if (this->LocalProcessId < this->NumberOfProcesses)\n {\n if (this->SingleMethod)\n {\n vtkMultiProcessController::SetGlobalController(this);\n (this->SingleMethod)(this, this->SingleData);\n }\n else\n {\n vtkWarningMacro(\"SingleMethod not set.\");\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Execute the methods set as the MultipleMethods.\nvoid vtkMPIController::MultipleMethodExecute()\n{\n if(!vtkMPIController::Initialized)\n {\n vtkWarningMacro(\"MPI has to be initialized first.\");\n return;\n }\n\n int i = this->LocalProcessId;\n \n if (this->LocalProcessId < this->NumberOfProcesses)\n {\n if (this->MultipleMethod[i])\n {\n vtkMultiProcessController::SetGlobalController(this);\n (this->MultipleMethod[i])(this, this->MultipleData[i]);\n }\n else\n {\n vtkWarningMacro(\"MultipleMethod \" << i << \" not set.\");\n }\n }\n}\n\nchar* vtkMPIController::ErrorString(int err)\n{\n char* buffer = new char[MPI_MAX_ERROR_STRING];\n int resLen;\n MPI_Error_string(err, buffer, &resLen);\n return buffer;\n}\n\n<commit_msg>Fixed indentation<commit_after>\/*=========================================================================\n\nProgram: Visualization Toolkit\nModule: vtkMPIController.cxx\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen\nAll rights reserved.\nSee Copyright.txt or http:\/\/www.kitware.com\/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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkMPIController.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkOutputWindow.h\"\n\n#include \"vtkMPI.h\"\n\nint vtkMPIController::Initialized = 0;\nchar vtkMPIController::ProcessorName[MPI_MAX_PROCESSOR_NAME] = \"\";\n\n\/\/ Output window which prints out the process id\n\/\/ with the error or warning messages\nclass VTK_PARALLEL_EXPORT vtkMPIOutputWindow : public vtkOutputWindow\n{\npublic:\n vtkTypeRevisionMacro(vtkMPIOutputWindow,vtkOutputWindow);\n\n void DisplayText(const char* t)\n {\n if (this->Controller)\n {\n cout << \"Process id: \" << this->Controller->GetLocalProcessId()\n << \" >> \";\n }\n cout << t;\n }\n\n vtkMPIOutputWindow()\n {\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkMPIOutputWindow\");\n if (ret)\n ret->Delete();\n this->Controller = 0;\n }\n\n friend class vtkMPIController;\n\nprotected:\n\n vtkMPIController* Controller;\n vtkMPIOutputWindow(const vtkMPIOutputWindow&);\n void operator=(const vtkMPIOutputWindow&);\n\n};\n\nvoid vtkMPIController::CreateOutputWindow()\n{\n vtkMPIOutputWindow* window = new vtkMPIOutputWindow;\n window->Controller = this;\n this->OutputWindow = window;\n vtkOutputWindow::SetInstance(this->OutputWindow);\n}\n\nvtkCxxRevisionMacro(vtkMPIOutputWindow, \"1.19\");\n\nvtkCxxRevisionMacro(vtkMPIController, \"1.19\");\nvtkStandardNewMacro(vtkMPIController);\n\n\/\/----------------------------------------------------------------------------\nvtkMPIController::vtkMPIController()\n{\n \/\/ If MPI was already initialized obtain rank and size.\n if (vtkMPIController::Initialized)\n {\n this->InitializeCommunicator(vtkMPICommunicator::GetWorldCommunicator());\n \/\/ Copy vtkMPIController::WorldRMICommunicataor which is created when\n \/\/ MPI is initialized\n vtkMPICommunicator* comm = vtkMPICommunicator::New();\n comm->CopyFrom(vtkMPIController::WorldRMICommunicator);\n this->RMICommunicator = comm;\n }\n\n this->OutputWindow = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMPIController::~vtkMPIController()\n{\n this->SetCommunicator(0);\n if (this->RMICommunicator)\n {\n this->RMICommunicator->Delete();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMPIController::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n os << indent << \"Initialized: \" << ( vtkMPIController::Initialized ? \"(yes)\" : \"(no)\" ) << endl;\n}\n\n\/\/ Set the number of processes and maximum number of processes\n\/\/ to the size obtained from MPI.\nint vtkMPIController::InitializeNumberOfProcesses()\n{\n int err;\n\n this->Modified();\n\n vtkMPICommunicator* comm = (vtkMPICommunicator*)this->Communicator;\n if ( (err = MPI_Comm_size(*(comm->Comm->Handle), \n &(this->MaximumNumberOfProcesses))) \n != MPI_SUCCESS )\n {\n char *msg = vtkMPIController::ErrorString(err);\n vtkErrorMacro(\"MPI error occured: \" << msg);\n delete[] msg;\n return 0;\n }\n\n if (this->MaximumNumberOfProcesses > MAX_PROCESSES)\n {\n vtkWarningMacro(\"Maximum of \" << MAX_PROCESSES);\n this->MaximumNumberOfProcesses = MAX_PROCESSES;\n }\n \n this->NumberOfProcesses = this->MaximumNumberOfProcesses;\n \n if ( (err = MPI_Comm_rank(*(comm->Comm->Handle),&(this->LocalProcessId))) \n != MPI_SUCCESS)\n {\n char *msg = vtkMPIController::ErrorString(err);\n vtkErrorMacro(\"MPI error occured: \" << msg);\n delete[] msg;\n return 0;\n }\n return 1;\n}\n\nvtkMPICommunicator* vtkMPIController::WorldRMICommunicator=0;\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMPIController::Initialize(int* argc, char*** argv, \n int initializedExternally)\n{\n if (vtkMPIController::Initialized)\n {\n vtkWarningMacro(\"Already initialized.\");\n return;\n }\n \n \/\/ Can be done once in the program.\n vtkMPIController::Initialized = 1;\n if (initializedExternally == 0)\n {\n MPI_Init(argc, argv);\n }\n this->InitializeCommunicator(vtkMPICommunicator::GetWorldCommunicator());\n this->InitializeNumberOfProcesses();\n\n int tmp;\n MPI_Get_processor_name(ProcessorName, &tmp);\n \/\/ Make a copy of MPI_COMM_WORLD creating a new context.\n \/\/ This is used in the creating of the communicators after\n \/\/ Initialize() has been called. It has to be done here\n \/\/ because for this to work, all processes have to call\n \/\/ MPI_Comm_dup and this is the only method which is\n \/\/ guaranteed to be called by all processes.\n vtkMPIController::WorldRMICommunicator = vtkMPICommunicator::New();\n vtkMPIController::WorldRMICommunicator->Duplicate((vtkMPICommunicator*)this->Communicator);\n this->RMICommunicator = vtkMPIController::WorldRMICommunicator;\n \/\/ Since we use Delete to get rid of the reference, we should use NULL to register.\n this->RMICommunicator->Register(NULL);\n\n this->Modified();\n}\n\nconst char* vtkMPIController::GetProcessorName()\n{\n return ProcessorName;\n}\n\n\/\/ Good-bye world\n\/\/ There should be no MPI calls after this.\n\/\/ (Except maybe MPI_XXX_free()) unless finalized externally.\nvoid vtkMPIController::Finalize(int finalizedExternally)\n{\n if (vtkMPIController::Initialized)\n { \n vtkMPIController::WorldRMICommunicator->Delete();\n vtkMPIController::WorldRMICommunicator = 0;\n vtkMPICommunicator::WorldCommunicator->Delete();\n this->SetCommunicator(0);\n if (this->RMICommunicator)\n {\n this->RMICommunicator->Delete();\n this->RMICommunicator = 0;\n }\n if (finalizedExternally == 0)\n {\n MPI_Finalize();\n }\n vtkMPIController::Initialized = 0;\n this->Modified();\n } \n \n}\n\n\/\/ Called by SetCommunicator and constructor. It frees but does \n\/\/ not set RMIHandle (which should not be set by using MPI_Comm_dup\n\/\/ during construction).\nvoid vtkMPIController::InitializeCommunicator(vtkMPICommunicator* comm)\n{\n if (this->Communicator != comm) \n { \n if (this->Communicator != 0) \n { \n this->Communicator->UnRegister(this); \n }\n this->Communicator = comm; \n if (this->Communicator != 0) \n { \n this->Communicator->Register(this); \n } \n\n if (comm && comm->Comm->Handle)\n {\n this->InitializeNumberOfProcesses();\n }\n this->Modified(); \n } \n\n\n}\n\n\/\/ Delete the previous RMI communicator and creates a new one\n\/\/ by duplicating the user communicator.\nvoid vtkMPIController::InitializeRMICommunicator()\n{\n if ( this->RMICommunicator )\n {\n this->RMICommunicator->Delete();\n this->RMICommunicator = 0;\n }\n if (this->Communicator)\n {\n this->RMICommunicator = vtkMPICommunicator::New();\n ((vtkMPICommunicator*)this->RMICommunicator)->Duplicate((vtkMPICommunicator*)this->Communicator);\n }\n}\n\nvoid vtkMPIController::SetCommunicator(vtkMPICommunicator* comm)\n{\n this->InitializeCommunicator(comm);\n this->InitializeRMICommunicator();\n}\n\n \nvoid vtkMPIController::Barrier()\n{\n vtkMPICommunicator* comm = (vtkMPICommunicator*)this->Communicator;\n int err;\n if ( (err = MPI_Barrier(*(comm->Comm->Handle)) ) \n != MPI_SUCCESS ) \n {\n char *msg = vtkMPIController::ErrorString(err);\n vtkErrorMacro(\"MPI error occured: \" << msg);\n delete[] msg;\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Execute the method set as the SingleMethod.\nvoid vtkMPIController::SingleMethodExecute()\n{\n if(!vtkMPIController::Initialized)\n {\n vtkWarningMacro(\"MPI has to be initialized first.\");\n return;\n }\n\n if (this->LocalProcessId < this->NumberOfProcesses)\n {\n if (this->SingleMethod)\n {\n vtkMultiProcessController::SetGlobalController(this);\n (this->SingleMethod)(this, this->SingleData);\n }\n else\n {\n vtkWarningMacro(\"SingleMethod not set.\");\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Execute the methods set as the MultipleMethods.\nvoid vtkMPIController::MultipleMethodExecute()\n{\n if(!vtkMPIController::Initialized)\n {\n vtkWarningMacro(\"MPI has to be initialized first.\");\n return;\n }\n\n int i = this->LocalProcessId;\n \n if (this->LocalProcessId < this->NumberOfProcesses)\n {\n if (this->MultipleMethod[i])\n {\n vtkMultiProcessController::SetGlobalController(this);\n (this->MultipleMethod[i])(this, this->MultipleData[i]);\n }\n else\n {\n vtkWarningMacro(\"MultipleMethod \" << i << \" not set.\");\n }\n }\n}\n\nchar* vtkMPIController::ErrorString(int err)\n{\n char* buffer = new char[MPI_MAX_ERROR_STRING];\n int resLen;\n MPI_Error_string(err, buffer, &resLen);\n return buffer;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Disallow calls to render device unless mocked<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>added pe70<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS rt13 (1.3.8); FILE MERGED 2005\/12\/07 17:24:00 np 1.3.8.1: #i58717#<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Remove the black line from the bottom of the status bubble.<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MCMC_HMC_NUTS_DIAG_E_XHMC_HPP\n#define STAN_MCMC_HMC_NUTS_DIAG_E_NUTS_HPP_E_XHMC_HPP\n\n#include <stan\/mcmc\/hmc\/xhmc\/base_xhmc.hpp>\n#include <stan\/mcmc\/hmc\/hamiltonians\/diag_e_point.hpp>\n#include <stan\/mcmc\/hmc\/hamiltonians\/diag_e_metric.hpp>\n#include <stan\/mcmc\/hmc\/integrators\/expl_leapfrog.hpp>\n\nnamespace stan {\n namespace mcmc {\n \/**\n * Exhausive Hamiltonian Monte Carlo (XHMC) with multinomial sampling\n * with a Gaussian-Euclidean disintegration and diagonal metric\n *\/\n template <class Model, class BaseRNG>\n class diag_e_xhmc\n : public base_xhmc<Model, diag_e_metric,\n expl_leapfrog, BaseRNG> {\n public:\n diag_e_xhmc(const Model& model, BaseRNG& rng)\n : base_xhmc<Model, diag_e_metric, expl_leapfrog,\n BaseRNG>(model, rng) { }\n };\n\n } \/\/ mcmc\n} \/\/ stan\n#endif\n<commit_msg>Fix header guard<commit_after>#ifndef STAN_MCMC_HMC_NUTS_DIAG_E_XHMC_HPP\n#define STAN_MCMC_HMC_NUTS_DIAG_E_XHMC_HPP\n\n#include <stan\/mcmc\/hmc\/xhmc\/base_xhmc.hpp>\n#include <stan\/mcmc\/hmc\/hamiltonians\/diag_e_point.hpp>\n#include <stan\/mcmc\/hmc\/hamiltonians\/diag_e_metric.hpp>\n#include <stan\/mcmc\/hmc\/integrators\/expl_leapfrog.hpp>\n\nnamespace stan {\n namespace mcmc {\n \/**\n * Exhausive Hamiltonian Monte Carlo (XHMC) with multinomial sampling\n * with a Gaussian-Euclidean disintegration and diagonal metric\n *\/\n template <class Model, class BaseRNG>\n class diag_e_xhmc\n : public base_xhmc<Model, diag_e_metric,\n expl_leapfrog, BaseRNG> {\n public:\n diag_e_xhmc(const Model& model, BaseRNG& rng)\n : base_xhmc<Model, diag_e_metric, expl_leapfrog,\n BaseRNG>(model, rng) { }\n };\n\n } \/\/ mcmc\n} \/\/ stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ infoware - C++ System information Library\n\/\/\n\/\/ Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>\n\/\/\n\/\/ To the extent possible under law, the author(s) have dedicated all copyright and related\n\/\/ and neighboring rights to this software to the public domain worldwide. This software is\n\/\/ distributed without any warranty.\n\/\/\n\/\/ You should have received a copy of the CC0 Public Domain Dedication along with this software.\n\/\/ If not, see <http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/>\n\n\n#ifndef _WIN32\n\n\n#include \"infoware\/system.hpp\"\n#include <cstdlib>\n#include <cstring>\n#include <sys\/utsname.h>\n\n\niware::system::kernel_info_t iware::system::kernel_info() noexcept {\n\tutsname uts;\n\tuname(&uts);\n\n\tchar* marker = uts.release;\n\tconst unsigned int major = std::strtoul(marker, &marker, 10);\n\tconst unsigned int minor = std::strtoul(marker + 1, &marker, 10);\n\tconst unsigned int patch = std::strtoul(marker + 1, &marker, 10);\n\tconst unsigned int build_number = std::strtoul(marker + 1, nullptr, 10);\n\n\tauto kernel = iware::system::kernel_t::unknown;\n\tif(!std::strcmp(uts.sysname, \"Linux\"))\n\t\tkernel = iware::system::kernel_t::linux;\n\telse if(!std::strcmp(uts.sysname, \"Darwin\"))\n\t\tkernel = iware::system::kernel_t::darwin;\n\n\treturn {iware::system::kernel_t::linux, major, minor, patch, build_number};\n}\n\n\n#endif\n<commit_msg>Fix unused verbol<commit_after>\/\/ infoware - C++ System information Library\n\/\/\n\/\/ Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>\n\/\/\n\/\/ To the extent possible under law, the author(s) have dedicated all copyright and related\n\/\/ and neighboring rights to this software to the public domain worldwide. This software is\n\/\/ distributed without any warranty.\n\/\/\n\/\/ You should have received a copy of the CC0 Public Domain Dedication along with this software.\n\/\/ If not, see <http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/>\n\n\n#ifndef _WIN32\n\n\n#include \"infoware\/system.hpp\"\n#include <cstdlib>\n#include <cstring>\n#include <sys\/utsname.h>\n\n\niware::system::kernel_info_t iware::system::kernel_info() noexcept {\n\tutsname uts;\n\tuname(&uts);\n\n\tchar* marker = uts.release;\n\tconst unsigned int major = std::strtoul(marker, &marker, 10);\n\tconst unsigned int minor = std::strtoul(marker + 1, &marker, 10);\n\tconst unsigned int patch = std::strtoul(marker + 1, &marker, 10);\n\tconst unsigned int build_number = std::strtoul(marker + 1, nullptr, 10);\n\n\tauto kernel = iware::system::kernel_t::unknown;\n\tif(!std::strcmp(uts.sysname, \"Linux\"))\n\t\tkernel = iware::system::kernel_t::linux;\n\telse if(!std::strcmp(uts.sysname, \"Darwin\"))\n\t\tkernel = iware::system::kernel_t::darwin;\n\n\treturn {kernel, major, minor, patch, build_number};\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2020 The ANGLE Project 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\/\/ TracePerf:\n\/\/ Performance test for ANGLE replaying traces.\n\/\/\n\n#include <gtest\/gtest.h>\n#include \"common\/PackedEnums.h\"\n#include \"common\/system_utils.h\"\n#include \"tests\/perf_tests\/ANGLEPerfTest.h\"\n#include \"tests\/perf_tests\/DrawCallPerfParams.h\"\n#include \"util\/egl_loader_autogen.h\"\n#include \"util\/frame_capture_test_utils.h\"\n#include \"util\/png_utils.h\"\n\n#include \"restricted_traces\/restricted_traces_autogen.h\"\n\n#include <cassert>\n#include <functional>\n#include <sstream>\n\nusing namespace angle;\nusing namespace egl_platform;\n\nnamespace\n{\nstruct TracePerfParams final : public RenderTestParams\n{\n \/\/ Common default options\n TracePerfParams()\n {\n majorVersion = 3;\n minorVersion = 0;\n trackGpuTime = true;\n\n \/\/ Display the frame after every drawBenchmark invocation\n iterationsPerStep = 1;\n }\n\n std::string story() const override\n {\n std::stringstream strstr;\n strstr << RenderTestParams::story() << \"_\" << GetTraceInfo(testID).name;\n return strstr.str();\n }\n\n RestrictedTraceID testID;\n};\n\nstd::ostream &operator<<(std::ostream &os, const TracePerfParams ¶ms)\n{\n os << params.backendAndStory().substr(1);\n return os;\n}\n\nclass TracePerfTest : public ANGLERenderTest, public ::testing::WithParamInterface<TracePerfParams>\n{\n public:\n TracePerfTest();\n\n void initializeBenchmark() override;\n void destroyBenchmark() override;\n void drawBenchmark() override;\n\n void onReplayFramebufferChange(GLenum target, GLuint framebuffer);\n\n uint32_t mStartFrame;\n uint32_t mEndFrame;\n\n double getHostTimeFromGLTime(GLint64 glTime);\n\n private:\n struct QueryInfo\n {\n GLuint beginTimestampQuery;\n GLuint endTimestampQuery;\n GLuint framebuffer;\n };\n\n struct TimeSample\n {\n GLint64 glTime;\n double hostTime;\n };\n\n void sampleTime();\n void saveScreenshot(const std::string &screenshotName) override;\n\n \/\/ For tracking RenderPass\/FBO change timing.\n QueryInfo mCurrentQuery = {};\n std::vector<QueryInfo> mRunningQueries;\n std::vector<TimeSample> mTimeline;\n\n std::string mStartingDirectory;\n};\n\nTracePerfTest::TracePerfTest()\n : ANGLERenderTest(\"TracePerf\", GetParam()), mStartFrame(0), mEndFrame(0)\n{\n const TracePerfParams ¶m = GetParam();\n\n \/\/ TODO: http:\/\/anglebug.com\/4533 This fails after the upgrade to the 26.20.100.7870 driver.\n if (IsWindows() && IsIntel() && param.getRenderer() == EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE &&\n param.testID == RestrictedTraceID::manhattan_10)\n {\n mSkipTest = true;\n }\n\n \/\/ TODO: http:\/\/anglebug.com\/4731 Fails on older Intel drivers. Passes in newer.\n if (IsWindows() && IsIntel() && param.driver != GLESDriverType::AngleEGL &&\n param.testID == RestrictedTraceID::angry_birds_2_1500)\n {\n mSkipTest = true;\n }\n\n \/\/ We already swap in TracePerfTest::drawBenchmark, no need to swap again in the harness.\n disableTestHarnessSwap();\n}\n\nvoid TracePerfTest::initializeBenchmark()\n{\n const auto ¶ms = GetParam();\n\n mStartingDirectory = angle::GetCWD().value();\n\n \/\/ To load the trace data path correctly we set the CWD to the executable dir.\n if (!IsAndroid())\n {\n std::string exeDir = angle::GetExecutableDirectory();\n angle::SetCWD(exeDir.c_str());\n }\n\n const TraceInfo &traceInfo = GetTraceInfo(params.testID);\n mStartFrame = traceInfo.startFrame;\n mEndFrame = traceInfo.endFrame;\n SetBinaryDataDecompressCallback(params.testID, DecompressBinaryData);\n\n std::stringstream testDataDirStr;\n testDataDirStr << ANGLE_TRACE_DATA_DIR << \"\/\" << traceInfo.name;\n std::string testDataDir = testDataDirStr.str();\n SetBinaryDataDir(params.testID, testDataDir.c_str());\n\n if (IsAndroid())\n {\n \/\/ On Android, set the orientation used by the app, based on width\/height\n getWindow()->setOrientation(mTestParams.windowWidth, mTestParams.windowHeight);\n }\n\n \/\/ Potentially slow. Can load a lot of resources.\n SetupReplay(params.testID);\n glFinish();\n\n ASSERT_TRUE(mEndFrame > mStartFrame);\n\n getWindow()->setVisible(true);\n}\n\n#undef TRACE_TEST_CASE\n\nvoid TracePerfTest::destroyBenchmark()\n{\n \/\/ In order for the next test to load, restore the working directory\n angle::SetCWD(mStartingDirectory.c_str());\n}\n\nvoid TracePerfTest::sampleTime()\n{\n if (mIsTimestampQueryAvailable)\n {\n GLint64 glTime;\n \/\/ glGetInteger64vEXT is exported by newer versions of the timer query extensions.\n \/\/ Unfortunately only the core EP is exposed by some desktop drivers (e.g. NVIDIA).\n if (glGetInteger64vEXT)\n {\n glGetInteger64vEXT(GL_TIMESTAMP_EXT, &glTime);\n }\n else\n {\n glGetInteger64v(GL_TIMESTAMP_EXT, &glTime);\n }\n mTimeline.push_back({glTime, angle::GetHostTimeSeconds()});\n }\n}\n\nvoid TracePerfTest::drawBenchmark()\n{\n \/\/ Add a time sample from GL and the host.\n sampleTime();\n\n startGpuTimer();\n\n for (uint32_t frame = mStartFrame; frame <= mEndFrame; ++frame)\n {\n char frameName[32];\n sprintf(frameName, \"Frame %u\", frame);\n beginInternalTraceEvent(frameName);\n\n ReplayFrame(GetParam().testID, frame);\n getGLWindow()->swap();\n\n endInternalTraceEvent(frameName);\n }\n\n ResetReplay(GetParam().testID);\n\n \/\/ Process any running queries once per iteration.\n for (size_t queryIndex = 0; queryIndex < mRunningQueries.size();)\n {\n const QueryInfo &query = mRunningQueries[queryIndex];\n\n GLuint endResultAvailable = 0;\n glGetQueryObjectuivEXT(query.endTimestampQuery, GL_QUERY_RESULT_AVAILABLE,\n &endResultAvailable);\n\n if (endResultAvailable == GL_TRUE)\n {\n char fboName[32];\n sprintf(fboName, \"FBO %u\", query.framebuffer);\n\n GLint64 beginTimestamp = 0;\n glGetQueryObjecti64vEXT(query.beginTimestampQuery, GL_QUERY_RESULT, &beginTimestamp);\n glDeleteQueriesEXT(1, &query.beginTimestampQuery);\n double beginHostTime = getHostTimeFromGLTime(beginTimestamp);\n beginGLTraceEvent(fboName, beginHostTime);\n\n GLint64 endTimestamp = 0;\n glGetQueryObjecti64vEXT(query.endTimestampQuery, GL_QUERY_RESULT, &endTimestamp);\n glDeleteQueriesEXT(1, &query.endTimestampQuery);\n double endHostTime = getHostTimeFromGLTime(endTimestamp);\n endGLTraceEvent(fboName, endHostTime);\n\n mRunningQueries.erase(mRunningQueries.begin() + queryIndex);\n }\n else\n {\n queryIndex++;\n }\n }\n\n stopGpuTimer();\n}\n\n\/\/ Converts a GL timestamp into a host-side CPU time aligned with \"GetHostTimeSeconds\".\n\/\/ This check is necessary to line up sampled trace events in a consistent timeline.\n\/\/ Uses a linear interpolation from a series of samples. We do a blocking call to sample\n\/\/ both host and GL time once per swap. We then find the two closest GL timestamps and\n\/\/ interpolate the host times between them to compute our result. If we are past the last\n\/\/ GL timestamp we sample a new data point pair.\ndouble TracePerfTest::getHostTimeFromGLTime(GLint64 glTime)\n{\n \/\/ Find two samples to do a lerp.\n size_t firstSampleIndex = mTimeline.size() - 1;\n while (firstSampleIndex > 0)\n {\n if (mTimeline[firstSampleIndex].glTime < glTime)\n {\n break;\n }\n firstSampleIndex--;\n }\n\n \/\/ Add an extra sample if we're missing an ending sample.\n if (firstSampleIndex == mTimeline.size() - 1)\n {\n sampleTime();\n }\n\n const TimeSample &start = mTimeline[firstSampleIndex];\n const TimeSample &end = mTimeline[firstSampleIndex + 1];\n\n \/\/ Note: we have observed in some odd cases later timestamps producing values that are\n \/\/ smaller than preceding timestamps. This bears further investigation.\n\n \/\/ Compute the scaling factor for the lerp.\n double glDelta = static_cast<double>(glTime - start.glTime);\n double glRange = static_cast<double>(end.glTime - start.glTime);\n double t = glDelta \/ glRange;\n\n \/\/ Lerp(t1, t2, t)\n double hostRange = end.hostTime - start.hostTime;\n return mTimeline[firstSampleIndex].hostTime + hostRange * t;\n}\n\n\/\/ Triggered when the replay calls glBindFramebuffer.\nvoid TracePerfTest::onReplayFramebufferChange(GLenum target, GLuint framebuffer)\n{\n if (!mIsTimestampQueryAvailable)\n return;\n\n if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER)\n return;\n\n \/\/ We have at most one active timestamp query at a time. This code will end the current\n \/\/ query and immediately start a new one.\n if (mCurrentQuery.beginTimestampQuery != 0)\n {\n glGenQueriesEXT(1, &mCurrentQuery.endTimestampQuery);\n glQueryCounterEXT(mCurrentQuery.endTimestampQuery, GL_TIMESTAMP_EXT);\n mRunningQueries.push_back(mCurrentQuery);\n mCurrentQuery = {};\n }\n\n ASSERT(mCurrentQuery.beginTimestampQuery == 0);\n\n glGenQueriesEXT(1, &mCurrentQuery.beginTimestampQuery);\n glQueryCounterEXT(mCurrentQuery.beginTimestampQuery, GL_TIMESTAMP_EXT);\n mCurrentQuery.framebuffer = framebuffer;\n}\n\nvoid TracePerfTest::saveScreenshot(const std::string &screenshotName)\n{\n \/\/ Render a single frame.\n RestrictedTraceID testID = GetParam().testID;\n const TraceInfo &traceInfo = GetTraceInfo(testID);\n ReplayFrame(testID, traceInfo.startFrame);\n\n \/\/ RGBA 4-byte data.\n uint32_t pixelCount = mTestParams.windowWidth * mTestParams.windowHeight;\n std::vector<uint8_t> pixelData(pixelCount * 4);\n\n glBindFramebuffer(GL_FRAMEBUFFER, 0);\n glReadPixels(0, 0, mTestParams.windowWidth, mTestParams.windowHeight, GL_RGBA, GL_UNSIGNED_BYTE,\n pixelData.data());\n\n \/\/ Convert to RGB and flip y.\n std::vector<uint8_t> rgbData(pixelCount * 3);\n for (EGLint y = 0; y < mTestParams.windowHeight; ++y)\n {\n for (EGLint x = 0; x < mTestParams.windowWidth; ++x)\n {\n EGLint srcPixel = x + y * mTestParams.windowWidth;\n EGLint dstPixel = x + (mTestParams.windowHeight - y - 1) * mTestParams.windowWidth;\n memcpy(&rgbData[dstPixel * 3], &pixelData[srcPixel * 4], 3);\n }\n }\n\n angle::SavePNGRGB(screenshotName.c_str(), \"ANGLE Screenshot\", mTestParams.windowWidth,\n mTestParams.windowHeight, rgbData);\n\n \/\/ Finish the frame loop.\n for (uint32_t nextFrame = traceInfo.startFrame + 1; nextFrame < traceInfo.endFrame; ++nextFrame)\n {\n ReplayFrame(testID, nextFrame);\n }\n getGLWindow()->swap();\n glFinish();\n}\n\nTEST_P(TracePerfTest, Run)\n{\n run();\n}\n\nTracePerfParams CombineTestID(const TracePerfParams &in, RestrictedTraceID id)\n{\n const TraceInfo &traceInfo = GetTraceInfo(id);\n\n TracePerfParams out = in;\n out.testID = id;\n out.windowWidth = traceInfo.drawSurfaceWidth;\n out.windowHeight = traceInfo.drawSurfaceHeight;\n return out;\n}\n\nusing namespace params;\nusing P = TracePerfParams;\n\nstd::vector<P> gTestsWithID =\n CombineWithValues({P()}, AllEnums<RestrictedTraceID>(), CombineTestID);\nstd::vector<P> gTestsWithRenderer = CombineWithFuncs(gTestsWithID, {Vulkan<P>, Native<P>});\nANGLE_INSTANTIATE_TEST_ARRAY(TracePerfTest, gTestsWithRenderer);\n\n} \/\/ anonymous namespace\n<commit_msg>Disable GPU time tracking in trace tests.<commit_after>\/\/\n\/\/ Copyright 2020 The ANGLE Project 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\/\/ TracePerf:\n\/\/ Performance test for ANGLE replaying traces.\n\/\/\n\n#include <gtest\/gtest.h>\n#include \"common\/PackedEnums.h\"\n#include \"common\/system_utils.h\"\n#include \"tests\/perf_tests\/ANGLEPerfTest.h\"\n#include \"tests\/perf_tests\/DrawCallPerfParams.h\"\n#include \"util\/egl_loader_autogen.h\"\n#include \"util\/frame_capture_test_utils.h\"\n#include \"util\/png_utils.h\"\n\n#include \"restricted_traces\/restricted_traces_autogen.h\"\n\n#include <cassert>\n#include <functional>\n#include <sstream>\n\nusing namespace angle;\nusing namespace egl_platform;\n\nnamespace\n{\nstruct TracePerfParams final : public RenderTestParams\n{\n \/\/ Common default options\n TracePerfParams()\n {\n majorVersion = 3;\n minorVersion = 0;\n\n \/\/ Tracking GPU time adds overhead to native traces. http:\/\/anglebug.com\/4879\n trackGpuTime = false;\n\n \/\/ Display the frame after every drawBenchmark invocation\n iterationsPerStep = 1;\n }\n\n std::string story() const override\n {\n std::stringstream strstr;\n strstr << RenderTestParams::story() << \"_\" << GetTraceInfo(testID).name;\n return strstr.str();\n }\n\n RestrictedTraceID testID;\n};\n\nstd::ostream &operator<<(std::ostream &os, const TracePerfParams ¶ms)\n{\n os << params.backendAndStory().substr(1);\n return os;\n}\n\nclass TracePerfTest : public ANGLERenderTest, public ::testing::WithParamInterface<TracePerfParams>\n{\n public:\n TracePerfTest();\n\n void initializeBenchmark() override;\n void destroyBenchmark() override;\n void drawBenchmark() override;\n\n void onReplayFramebufferChange(GLenum target, GLuint framebuffer);\n\n uint32_t mStartFrame;\n uint32_t mEndFrame;\n\n double getHostTimeFromGLTime(GLint64 glTime);\n\n private:\n struct QueryInfo\n {\n GLuint beginTimestampQuery;\n GLuint endTimestampQuery;\n GLuint framebuffer;\n };\n\n struct TimeSample\n {\n GLint64 glTime;\n double hostTime;\n };\n\n void sampleTime();\n void saveScreenshot(const std::string &screenshotName) override;\n\n \/\/ For tracking RenderPass\/FBO change timing.\n QueryInfo mCurrentQuery = {};\n std::vector<QueryInfo> mRunningQueries;\n std::vector<TimeSample> mTimeline;\n\n std::string mStartingDirectory;\n};\n\nTracePerfTest::TracePerfTest()\n : ANGLERenderTest(\"TracePerf\", GetParam()), mStartFrame(0), mEndFrame(0)\n{\n const TracePerfParams ¶m = GetParam();\n\n \/\/ TODO: http:\/\/anglebug.com\/4533 This fails after the upgrade to the 26.20.100.7870 driver.\n if (IsWindows() && IsIntel() && param.getRenderer() == EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE &&\n param.testID == RestrictedTraceID::manhattan_10)\n {\n mSkipTest = true;\n }\n\n \/\/ TODO: http:\/\/anglebug.com\/4731 Fails on older Intel drivers. Passes in newer.\n if (IsWindows() && IsIntel() && param.driver != GLESDriverType::AngleEGL &&\n param.testID == RestrictedTraceID::angry_birds_2_1500)\n {\n mSkipTest = true;\n }\n\n \/\/ We already swap in TracePerfTest::drawBenchmark, no need to swap again in the harness.\n disableTestHarnessSwap();\n}\n\nvoid TracePerfTest::initializeBenchmark()\n{\n const auto ¶ms = GetParam();\n\n mStartingDirectory = angle::GetCWD().value();\n\n \/\/ To load the trace data path correctly we set the CWD to the executable dir.\n if (!IsAndroid())\n {\n std::string exeDir = angle::GetExecutableDirectory();\n angle::SetCWD(exeDir.c_str());\n }\n\n const TraceInfo &traceInfo = GetTraceInfo(params.testID);\n mStartFrame = traceInfo.startFrame;\n mEndFrame = traceInfo.endFrame;\n SetBinaryDataDecompressCallback(params.testID, DecompressBinaryData);\n\n std::stringstream testDataDirStr;\n testDataDirStr << ANGLE_TRACE_DATA_DIR << \"\/\" << traceInfo.name;\n std::string testDataDir = testDataDirStr.str();\n SetBinaryDataDir(params.testID, testDataDir.c_str());\n\n if (IsAndroid())\n {\n \/\/ On Android, set the orientation used by the app, based on width\/height\n getWindow()->setOrientation(mTestParams.windowWidth, mTestParams.windowHeight);\n }\n\n \/\/ Potentially slow. Can load a lot of resources.\n SetupReplay(params.testID);\n glFinish();\n\n ASSERT_TRUE(mEndFrame > mStartFrame);\n\n getWindow()->setVisible(true);\n}\n\n#undef TRACE_TEST_CASE\n\nvoid TracePerfTest::destroyBenchmark()\n{\n \/\/ In order for the next test to load, restore the working directory\n angle::SetCWD(mStartingDirectory.c_str());\n}\n\nvoid TracePerfTest::sampleTime()\n{\n if (mIsTimestampQueryAvailable)\n {\n GLint64 glTime;\n \/\/ glGetInteger64vEXT is exported by newer versions of the timer query extensions.\n \/\/ Unfortunately only the core EP is exposed by some desktop drivers (e.g. NVIDIA).\n if (glGetInteger64vEXT)\n {\n glGetInteger64vEXT(GL_TIMESTAMP_EXT, &glTime);\n }\n else\n {\n glGetInteger64v(GL_TIMESTAMP_EXT, &glTime);\n }\n mTimeline.push_back({glTime, angle::GetHostTimeSeconds()});\n }\n}\n\nvoid TracePerfTest::drawBenchmark()\n{\n \/\/ Add a time sample from GL and the host.\n sampleTime();\n\n startGpuTimer();\n\n for (uint32_t frame = mStartFrame; frame <= mEndFrame; ++frame)\n {\n char frameName[32];\n sprintf(frameName, \"Frame %u\", frame);\n beginInternalTraceEvent(frameName);\n\n ReplayFrame(GetParam().testID, frame);\n getGLWindow()->swap();\n\n endInternalTraceEvent(frameName);\n }\n\n ResetReplay(GetParam().testID);\n\n \/\/ Process any running queries once per iteration.\n for (size_t queryIndex = 0; queryIndex < mRunningQueries.size();)\n {\n const QueryInfo &query = mRunningQueries[queryIndex];\n\n GLuint endResultAvailable = 0;\n glGetQueryObjectuivEXT(query.endTimestampQuery, GL_QUERY_RESULT_AVAILABLE,\n &endResultAvailable);\n\n if (endResultAvailable == GL_TRUE)\n {\n char fboName[32];\n sprintf(fboName, \"FBO %u\", query.framebuffer);\n\n GLint64 beginTimestamp = 0;\n glGetQueryObjecti64vEXT(query.beginTimestampQuery, GL_QUERY_RESULT, &beginTimestamp);\n glDeleteQueriesEXT(1, &query.beginTimestampQuery);\n double beginHostTime = getHostTimeFromGLTime(beginTimestamp);\n beginGLTraceEvent(fboName, beginHostTime);\n\n GLint64 endTimestamp = 0;\n glGetQueryObjecti64vEXT(query.endTimestampQuery, GL_QUERY_RESULT, &endTimestamp);\n glDeleteQueriesEXT(1, &query.endTimestampQuery);\n double endHostTime = getHostTimeFromGLTime(endTimestamp);\n endGLTraceEvent(fboName, endHostTime);\n\n mRunningQueries.erase(mRunningQueries.begin() + queryIndex);\n }\n else\n {\n queryIndex++;\n }\n }\n\n stopGpuTimer();\n}\n\n\/\/ Converts a GL timestamp into a host-side CPU time aligned with \"GetHostTimeSeconds\".\n\/\/ This check is necessary to line up sampled trace events in a consistent timeline.\n\/\/ Uses a linear interpolation from a series of samples. We do a blocking call to sample\n\/\/ both host and GL time once per swap. We then find the two closest GL timestamps and\n\/\/ interpolate the host times between them to compute our result. If we are past the last\n\/\/ GL timestamp we sample a new data point pair.\ndouble TracePerfTest::getHostTimeFromGLTime(GLint64 glTime)\n{\n \/\/ Find two samples to do a lerp.\n size_t firstSampleIndex = mTimeline.size() - 1;\n while (firstSampleIndex > 0)\n {\n if (mTimeline[firstSampleIndex].glTime < glTime)\n {\n break;\n }\n firstSampleIndex--;\n }\n\n \/\/ Add an extra sample if we're missing an ending sample.\n if (firstSampleIndex == mTimeline.size() - 1)\n {\n sampleTime();\n }\n\n const TimeSample &start = mTimeline[firstSampleIndex];\n const TimeSample &end = mTimeline[firstSampleIndex + 1];\n\n \/\/ Note: we have observed in some odd cases later timestamps producing values that are\n \/\/ smaller than preceding timestamps. This bears further investigation.\n\n \/\/ Compute the scaling factor for the lerp.\n double glDelta = static_cast<double>(glTime - start.glTime);\n double glRange = static_cast<double>(end.glTime - start.glTime);\n double t = glDelta \/ glRange;\n\n \/\/ Lerp(t1, t2, t)\n double hostRange = end.hostTime - start.hostTime;\n return mTimeline[firstSampleIndex].hostTime + hostRange * t;\n}\n\n\/\/ Triggered when the replay calls glBindFramebuffer.\nvoid TracePerfTest::onReplayFramebufferChange(GLenum target, GLuint framebuffer)\n{\n if (!mIsTimestampQueryAvailable)\n return;\n\n if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER)\n return;\n\n \/\/ We have at most one active timestamp query at a time. This code will end the current\n \/\/ query and immediately start a new one.\n if (mCurrentQuery.beginTimestampQuery != 0)\n {\n glGenQueriesEXT(1, &mCurrentQuery.endTimestampQuery);\n glQueryCounterEXT(mCurrentQuery.endTimestampQuery, GL_TIMESTAMP_EXT);\n mRunningQueries.push_back(mCurrentQuery);\n mCurrentQuery = {};\n }\n\n ASSERT(mCurrentQuery.beginTimestampQuery == 0);\n\n glGenQueriesEXT(1, &mCurrentQuery.beginTimestampQuery);\n glQueryCounterEXT(mCurrentQuery.beginTimestampQuery, GL_TIMESTAMP_EXT);\n mCurrentQuery.framebuffer = framebuffer;\n}\n\nvoid TracePerfTest::saveScreenshot(const std::string &screenshotName)\n{\n \/\/ Render a single frame.\n RestrictedTraceID testID = GetParam().testID;\n const TraceInfo &traceInfo = GetTraceInfo(testID);\n ReplayFrame(testID, traceInfo.startFrame);\n\n \/\/ RGBA 4-byte data.\n uint32_t pixelCount = mTestParams.windowWidth * mTestParams.windowHeight;\n std::vector<uint8_t> pixelData(pixelCount * 4);\n\n glBindFramebuffer(GL_FRAMEBUFFER, 0);\n glReadPixels(0, 0, mTestParams.windowWidth, mTestParams.windowHeight, GL_RGBA, GL_UNSIGNED_BYTE,\n pixelData.data());\n\n \/\/ Convert to RGB and flip y.\n std::vector<uint8_t> rgbData(pixelCount * 3);\n for (EGLint y = 0; y < mTestParams.windowHeight; ++y)\n {\n for (EGLint x = 0; x < mTestParams.windowWidth; ++x)\n {\n EGLint srcPixel = x + y * mTestParams.windowWidth;\n EGLint dstPixel = x + (mTestParams.windowHeight - y - 1) * mTestParams.windowWidth;\n memcpy(&rgbData[dstPixel * 3], &pixelData[srcPixel * 4], 3);\n }\n }\n\n angle::SavePNGRGB(screenshotName.c_str(), \"ANGLE Screenshot\", mTestParams.windowWidth,\n mTestParams.windowHeight, rgbData);\n\n \/\/ Finish the frame loop.\n for (uint32_t nextFrame = traceInfo.startFrame + 1; nextFrame < traceInfo.endFrame; ++nextFrame)\n {\n ReplayFrame(testID, nextFrame);\n }\n getGLWindow()->swap();\n glFinish();\n}\n\nTEST_P(TracePerfTest, Run)\n{\n run();\n}\n\nTracePerfParams CombineTestID(const TracePerfParams &in, RestrictedTraceID id)\n{\n const TraceInfo &traceInfo = GetTraceInfo(id);\n\n TracePerfParams out = in;\n out.testID = id;\n out.windowWidth = traceInfo.drawSurfaceWidth;\n out.windowHeight = traceInfo.drawSurfaceHeight;\n return out;\n}\n\nusing namespace params;\nusing P = TracePerfParams;\n\nstd::vector<P> gTestsWithID =\n CombineWithValues({P()}, AllEnums<RestrictedTraceID>(), CombineTestID);\nstd::vector<P> gTestsWithRenderer = CombineWithFuncs(gTestsWithID, {Vulkan<P>, Native<P>});\nANGLE_INSTANTIATE_TEST_ARRAY(TracePerfTest, gTestsWithRenderer);\n\n} \/\/ anonymous namespace\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"streamreader.h\"\n\n#include <QtCore\/QDebug>\n#define d qDebug() << Q_FUNC_INFO << \": \"\n\nQT_BEGIN_NAMESPACE\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\nnamespace Phonon\n{\nnamespace Gstreamer\n{\n\nStreamReader::StreamReader(const Phonon::MediaSource &source, MediaObject *parent)\n : m_pos(0)\n , m_size(0)\n , m_eos(false)\n , m_seekable(false)\n , m_mediaObject(parent)\n{\n connectToSource(source);\n}\n\nint StreamReader::currentBufferSize() const\n{\n d << m_buffer.size();\n return m_buffer.size();\n}\n\nvoid StreamReader::writeData(const QByteArray &data) {\n d << \"getting ze data and other plunder\";\n QMutexLocker locker(&m_mutex);\n\n m_buffer.append(data);\n\n m_waitingForData.wakeAll();\n\n#warning enoughData sometimes locks any furhter needata?\n\/\/ if (m_mediaObject->state() != Phonon::BufferingState &&\n\/\/ m_mediaObject->state() != Phonon::LoadingState) {\n\/\/ d << \"we haz had enuogh, kthxbai!\";\n\/\/ enoughData();\n\/\/ }\n}\n\nvoid StreamReader::setCurrentPos(qint64 pos)\n{\n QMutexLocker locker(&m_mutex);\n\n m_pos = pos;\n seekStream(pos);\n m_buffer.clear();\n}\n\nquint64 StreamReader::currentPos() const\n{\n return m_pos;\n}\n\nGstFlowReturn StreamReader::read(quint64 pos, int length, char *buffer)\n{\n QMutexLocker locker(&m_mutex);\n\n if (currentPos() != pos) {\n if (!streamSeekable()) {\n return GST_FLOW_NOT_SUPPORTED;\n }\n#warning ret something\n setCurrentPos(pos);\n }\n\n while (currentBufferSize() < length) {\n d << \"whiling\";\n int oldSize = currentBufferSize();\n needData();\n\n m_waitingForData.wait(&m_mutex);\n\n if (oldSize == currentBufferSize()) {\n \/\/ We didn't get any data.\n if (m_eos) {\n return GST_FLOW_UNEXPECTED;\n } else {\n return GST_FLOW_ERROR;\n }\n }\n }\n\/\/ enoughData();\n\n d << \"filling up that stinky old buffer\";\n qMemCopy(buffer, m_buffer.data(), length);\n m_pos += length;\n \/\/truncate the buffer\n m_buffer = m_buffer.mid(length);\n return GST_FLOW_OK;\n}\n\nvoid StreamReader::endOfData()\n{\n d << \"out of the data!!!\";\n QMutexLocker locker(&m_mutex);\n m_eos = true;\n m_waitingForData.wakeAll();\n}\n\nvoid StreamReader::start()\n{\n d;\n QMutexLocker locker(&m_mutex);\n m_buffer.clear();\n m_eos = false;\n m_pos = 0;\n m_seekable = false;\n m_size = 0;\n reset();\n}\n\nvoid StreamReader::stop()\n{\n#ifdef __GNUC__\n#warning implications of stop on still working read????\n#endif\n d << \"stopping!\";\n enoughData();\n\/\/ m_waitingForData.wakeAll();\n}\n\nvoid StreamReader::unlock()\n{\n QMutexLocker locker(&m_mutex);\n d << \"lock lock I shall unlock...\";\n\/\/ enoughData();\n\/\/ m_waitingForData.wakeAll();\n}\n\nvoid StreamReader::unlockStop()\n{\n QMutexLocker locker(&m_mutex);\n}\n\nvoid StreamReader::setStreamSize(qint64 newSize) {\n d << \"setting der streamsize to - \" << newSize;\n m_size = newSize;\n}\n\nqint64 StreamReader::streamSize() const {\n return m_size;\n}\n\nvoid StreamReader::setStreamSeekable(bool seekable) {\n d << seekable;\n m_seekable = seekable;\n}\n\nbool StreamReader::streamSeekable() const {\n d << m_seekable;\n return false;\n return m_seekable;\n}\n\n}\n}\n#endif \/\/QT_NO_PHONON_ABSTRACTMEDIASTREAM\n\nQT_END_NAMESPACE\n<commit_msg>stop and unlock appropriately, lockup after enoughData remains though :S<commit_after>\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"streamreader.h\"\n\n#include <QtCore\/QDebug>\n#define d qDebug() << Q_FUNC_INFO << \": \"\n\nQT_BEGIN_NAMESPACE\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\nnamespace Phonon\n{\nnamespace Gstreamer\n{\n\nStreamReader::StreamReader(const Phonon::MediaSource &source, MediaObject *parent)\n : m_pos(0)\n , m_size(0)\n , m_eos(false)\n , m_seekable(false)\n , m_mediaObject(parent)\n{\n connectToSource(source);\n}\n\nint StreamReader::currentBufferSize() const\n{\n d << m_buffer.size();\n return m_buffer.size();\n}\n\nvoid StreamReader::writeData(const QByteArray &data) {\n d << \"getting ze data and other plunder\";\n QMutexLocker locker(&m_mutex);\n\n m_buffer.append(data);\n\n m_waitingForData.wakeAll();\n\n#warning enoughData sometimes locks any furhter needata?\n\/\/ if (m_mediaObject->state() != Phonon::BufferingState &&\n\/\/ m_mediaObject->state() != Phonon::LoadingState) {\n\/\/ d << \"we haz had enuogh, kthxbai!\";\n\/\/ enoughData();\n\/\/ }\n}\n\nvoid StreamReader::setCurrentPos(qint64 pos)\n{\n QMutexLocker locker(&m_mutex);\n\n m_pos = pos;\n seekStream(pos);\n m_buffer.clear();\n}\n\nquint64 StreamReader::currentPos() const\n{\n return m_pos;\n}\n\nGstFlowReturn StreamReader::read(quint64 pos, int length, char *buffer)\n{\n QMutexLocker locker(&m_mutex);\n\n if (currentPos() != pos) {\n if (!streamSeekable()) {\n return GST_FLOW_NOT_SUPPORTED;\n }\n#warning ret something\n setCurrentPos(pos);\n }\n\n while (currentBufferSize() < length) {\n d << \"whiling\";\n int oldSize = currentBufferSize();\n needData();\n\n m_waitingForData.wait(&m_mutex);\n\n if (oldSize == currentBufferSize()) {\n \/\/ We didn't get any data.\n if (m_eos) {\n return GST_FLOW_UNEXPECTED;\n } else {\n return GST_FLOW_ERROR;\n }\n }\n }\n\/\/ enoughData();\n\n d << \"filling up that stinky old buffer\";\n qMemCopy(buffer, m_buffer.data(), length);\n m_pos += length;\n \/\/truncate the buffer\n m_buffer = m_buffer.mid(length);\n return GST_FLOW_OK;\n}\n\nvoid StreamReader::endOfData()\n{\n d << \"out of the data!!!\";\n QMutexLocker locker(&m_mutex);\n m_eos = true;\n m_waitingForData.wakeAll();\n}\n\nvoid StreamReader::start()\n{\n d;\n QMutexLocker locker(&m_mutex);\n m_buffer.clear();\n m_eos = false;\n m_pos = 0;\n m_seekable = false;\n m_size = 0;\n reset();\n}\n\nvoid StreamReader::stop()\n{\n#ifdef __GNUC__\n#warning implications of stop on still working read????\n#endif\n d << \"stopping!\";\n enoughData();\n m_waitingForData.wakeAll();\n}\n\nvoid StreamReader::unlock()\n{\n QMutexLocker locker(&m_mutex);\n d << \"lock lock I shall unlock...\";\n enoughData();\n m_waitingForData.wakeAll();\n}\n\nvoid StreamReader::unlockStop()\n{\n QMutexLocker locker(&m_mutex);\n}\n\nvoid StreamReader::setStreamSize(qint64 newSize) {\n d << \"setting der streamsize to - \" << newSize;\n m_size = newSize;\n}\n\nqint64 StreamReader::streamSize() const {\n return m_size;\n}\n\nvoid StreamReader::setStreamSeekable(bool seekable) {\n d << seekable;\n m_seekable = seekable;\n}\n\nbool StreamReader::streamSeekable() const {\n d << m_seekable;\n return false;\n return m_seekable;\n}\n\n}\n}\n#endif \/\/QT_NO_PHONON_ABSTRACTMEDIASTREAM\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*\nHighly Optimized Object-oriented Many-particle Dynamics -- Blue Edition\n(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory\nIowa State University and The Regents of the University of Michigan All rights\nreserved.\n\nHOOMD-blue may contain modifications (\"Contributions\") provided, and to which\ncopyright is held, by various Contributors who have granted The Regents of the\nUniversity of Michigan the right to modify and\/or distribute such Contributions.\n\nRedistribution and use of HOOMD-blue, in source and binary forms, with or\nwithout modification, are permitted, provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright notice, this\nlist of conditions, and the following disclaimer.\n\n* Redistributions 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\n* Neither the name of the copyright holder nor the names of HOOMD-blue's\ncontributors may be used to endorse or promote products derived from this\nsoftware without specific prior written permission.\n\nDisclaimer\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\/OR\nANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.\n\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ $Id: TwoStepNVEGPU.cc 2331 2009-11-19 15:30:00Z ndtrung $\n\/\/ $URL: https:\/\/codeblue.umich.edu\/hoomd-blue\/svn\/branches\/rigid-bodies\/src\/updaters_gpu\/TwoStepNVERigidGPU.cc $\n\/\/ Maintainer: joaander\n\n#ifdef WIN32\n#pragma warning( push )\n#pragma warning( disable : 4244 )\n#endif\n\n#include <boost\/python.hpp>\nusing namespace boost::python;\n#include <boost\/bind.hpp>\nusing namespace boost;\n\n#include \"TwoStepNVERigidGPU.h\"\n#include \"TwoStepNVERigidGPU.cuh\"\n\n\/*! \\file TwoStepNVERigidGPU.h\n \\brief Contains code for the TwoStepNVERigidGPU class\n*\/\n\n\/*! \\param sysdef SystemDefinition this method will act on. Must not be NULL.\n \\param group The group of particles this integration method is to work on\n*\/\nTwoStepNVERigidGPU::TwoStepNVERigidGPU(boost::shared_ptr<SystemDefinition> sysdef,\n boost::shared_ptr<ParticleGroup> group)\n : TwoStepNVERigid(sysdef, group)\n {\n \/\/ only one GPU is supported\n if (exec_conf.gpu.size() != 1)\n {\n cerr << endl << \"***Error! Creating a TwoStepNVEGPU with 0 or more than one GPUs\" << endl << endl;\n throw std::runtime_error(\"Error initializing TwoStepNVEGPU\");\n }\n }\n\n\/*! \\param timestep Current time step\n \\post Particle positions are moved forward to timestep+1 and velocities to timestep+1\/2 per the velocity verlet\n method.\n*\/\nvoid TwoStepNVERigidGPU::integrateStepOne(unsigned int timestep)\n {\n \/\/ profile this step\n if (m_prof)\n m_prof->push(exec_conf, \"NVE step 1\");\n \n if (m_first_step)\n {\n setup();\n m_first_step = false;\n }\n \n \/\/ access all the needed data\n vector<gpu_pdata_arrays>& d_pdata = m_pdata->acquireReadWriteGPU();\n gpu_boxsize box = m_pdata->getBoxGPU();\n ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);\n unsigned int group_size = m_group->getIndexArray().getNumElements();\n \n \/\/ get the rigid data from SystemDefinition\n boost::shared_ptr<RigidData> rigid_data = m_sysdef->getRigidData();\n\n\tArrayHandle<Scalar> body_mass_handle(rigid_data->getBodyMass(), access_location::device, access_mode::read);\n\tArrayHandle<Scalar4> moment_inertia_handle(rigid_data->getMomentInertia(), access_location::device, access_mode::read);\n\tArrayHandle<Scalar4> com_handle(rigid_data->getCOM(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> vel_handle(rigid_data->getVel(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> angvel_handle(rigid_data->getAngVel(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> angmom_handle(rigid_data->getAngMom(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> orientation_handle(rigid_data->getOrientation(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> ex_space_handle(rigid_data->getExSpace(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> ey_space_handle(rigid_data->getEySpace(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> ez_space_handle(rigid_data->getEzSpace(), access_location::device, access_mode::readwrite);\n ArrayHandle<int> body_imagex_handle(rigid_data->getBodyImagex(), access_location::device, access_mode::readwrite);\n ArrayHandle<int> body_imagey_handle(rigid_data->getBodyImagey(), access_location::device, access_mode::readwrite);\n ArrayHandle<int> body_imagez_handle(rigid_data->getBodyImagez(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> particle_pos_handle(rigid_data->getParticlePos(), access_location::device, access_mode::read);\n ArrayHandle<unsigned int> particle_indices_handle(rigid_data->getParticleIndices(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> force_handle(rigid_data->getForce(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> torque_handle(rigid_data->getTorque(), access_location::device, access_mode::read);\n \n gpu_rigid_data_arrays d_rdata;\n d_rdata.n_bodies = rigid_data->getNumBodies();\n d_rdata.nmax = rigid_data->getNmax();\n d_rdata.local_beg = 0;\n d_rdata.local_num = d_rdata.n_bodies;\n d_rdata.body_mass = body_mass_handle.data;\n d_rdata.moment_inertia = moment_inertia_handle.data;\n d_rdata.com = com_handle.data;\n d_rdata.vel = vel_handle.data;\n d_rdata.angvel = angvel_handle.data;\n d_rdata.angmom = angmom_handle.data;\n d_rdata.orientation = orientation_handle.data;\n d_rdata.ex_space = ex_space_handle.data;\n d_rdata.ey_space = ey_space_handle.data;\n d_rdata.ez_space = ez_space_handle.data;\n d_rdata.body_imagex = body_imagex_handle.data;\n d_rdata.body_imagey = body_imagey_handle.data;\n d_rdata.body_imagez = body_imagez_handle.data;\n d_rdata.particle_pos = particle_pos_handle.data;\n d_rdata.particle_indices = particle_indices_handle.data;\n d_rdata.force = force_handle.data;\n d_rdata.torque = torque_handle.data;\n \n \/\/ perform the update on the GPU\n exec_conf.tagAll(__FILE__, __LINE__);\t\n exec_conf.gpu[0]->call(bind(gpu_nve_rigid_step_one, \n d_pdata[0],\n d_rdata, \n\t\t\t\t\t\t\t\td_index_array.data,\n\t\t\t\t\t\t\t\tgroup_size,\n\t\t\t\t\t\t\t\tbox,\n\t\t\t\t\t\t\t\tm_deltaT));\n\n\t\n m_pdata->release();\n \n \/\/ done profiling\n if (m_prof)\n m_prof->pop(exec_conf);\n }\n \n\/*! \\param timestep Current time step\n \\post particle velocities are moved forward to timestep+1 on the GPU\n*\/\nvoid TwoStepNVERigidGPU::integrateStepTwo(unsigned int timestep)\n {\n const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce();\n \n \/\/ profile this step\n if (m_prof)\n m_prof->push(exec_conf, \"NVE step 2\");\n \n vector<gpu_pdata_arrays>& d_pdata = m_pdata->acquireReadWriteGPU();\n gpu_boxsize box = m_pdata->getBoxGPU();\n ArrayHandle<Scalar4> d_net_force(net_force, access_location::device, access_mode::read);\n ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);\n unsigned int group_size = m_group->getIndexArray().getNumElements();\n \n \/\/ get the rigid data from SystemDefinition\n boost::shared_ptr<RigidData> rigid_data = m_sysdef->getRigidData();\n\n ArrayHandle<Scalar> body_mass_handle(rigid_data->getBodyMass(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> moment_inertia_handle(rigid_data->getMomentInertia(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> com_handle(rigid_data->getCOM(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> vel_handle(rigid_data->getVel(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> angvel_handle(rigid_data->getAngVel(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> angmom_handle(rigid_data->getAngMom(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> ex_space_handle(rigid_data->getExSpace(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> ey_space_handle(rigid_data->getEySpace(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> ez_space_handle(rigid_data->getEzSpace(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> particle_pos_handle(rigid_data->getParticlePos(), access_location::device, access_mode::read);\n ArrayHandle<unsigned int> particle_indices_handle(rigid_data->getParticleIndices(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> force_handle(rigid_data->getForce(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> torque_handle(rigid_data->getTorque(), access_location::device, access_mode::readwrite);\n \n gpu_rigid_data_arrays d_rdata;\n d_rdata.n_bodies = rigid_data->getNumBodies();\n d_rdata.nmax = rigid_data->getNmax();\n d_rdata.local_beg = 0;\n d_rdata.local_num = d_rdata.n_bodies;\n d_rdata.body_mass = body_mass_handle.data;\n d_rdata.moment_inertia = moment_inertia_handle.data;\n\td_rdata.com = com_handle.data;\n d_rdata.vel = vel_handle.data;\n d_rdata.angvel = angvel_handle.data;\n d_rdata.angmom = angmom_handle.data;\n d_rdata.ex_space = ex_space_handle.data;\n d_rdata.ey_space = ey_space_handle.data;\n d_rdata.ez_space = ez_space_handle.data;\n d_rdata.particle_pos = particle_pos_handle.data;\n d_rdata.particle_indices = particle_indices_handle.data;\n d_rdata.force = force_handle.data;\n d_rdata.torque = torque_handle.data;\n \n\t\/\/ perform the update on the GPU\n exec_conf.tagAll(__FILE__, __LINE__);\n exec_conf.gpu[0]->call(bind(gpu_nve_rigid_step_two, \n\t\t\t\t\t\t\t\td_pdata[0], \n d_rdata, \n\t\t\t\t\t\t\t\td_index_array.data,\n\t\t\t\t\t\t\t\tgroup_size,\n d_net_force.data,\n box, \n\t\t\t\t\t\t\t\tm_deltaT,\n m_zero_force)); \n \n \n m_pdata->release();\n \n \/\/ done profiling\n if (m_prof)\n m_prof->pop(exec_conf);\n }\n\nvoid export_TwoStepNVERigidGPU()\n {\n class_<TwoStepNVERigidGPU, boost::shared_ptr<TwoStepNVERigidGPU>, bases<TwoStepNVERigid>, boost::noncopyable>\n (\"TwoStepNVERigidGPU\", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<ParticleGroup> >())\n ;\n }\n\n#ifdef WIN32\n#pragma warning( pop )\n#endif\n\n<commit_msg>update two-step NVE rigid body integrator on GPU<commit_after>\/*\nHighly Optimized Object-oriented Many-particle Dynamics -- Blue Edition\n(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory\nIowa State University and The Regents of the University of Michigan All rights\nreserved.\n\nHOOMD-blue may contain modifications (\"Contributions\") provided, and to which\ncopyright is held, by various Contributors who have granted The Regents of the\nUniversity of Michigan the right to modify and\/or distribute such Contributions.\n\nRedistribution and use of HOOMD-blue, in source and binary forms, with or\nwithout modification, are permitted, provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright notice, this\nlist of conditions, and the following disclaimer.\n\n* Redistributions 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\n* Neither the name of the copyright holder nor the names of HOOMD-blue's\ncontributors may be used to endorse or promote products derived from this\nsoftware without specific prior written permission.\n\nDisclaimer\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\/OR\nANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.\n\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ $Id: TwoStepNVEGPU.cc 2331 2009-11-19 15:30:00Z ndtrung $\n\/\/ $URL: https:\/\/codeblue.umich.edu\/hoomd-blue\/svn\/branches\/rigid-bodies\/src\/updaters_gpu\/TwoStepNVERigidGPU.cc $\n\/\/ Maintainer: joaander\n\n#ifdef WIN32\n#pragma warning( push )\n#pragma warning( disable : 4244 )\n#endif\n\n#include <boost\/python.hpp>\nusing namespace boost::python;\n#include <boost\/bind.hpp>\nusing namespace boost;\n\n#include \"TwoStepNVERigidGPU.h\"\n#include \"TwoStepNVERigidGPU.cuh\"\n\n\/*! \\file TwoStepNVERigidGPU.h\n \\brief Contains code for the TwoStepNVERigidGPU class\n*\/\n\n\/*! \\param sysdef SystemDefinition this method will act on. Must not be NULL.\n \\param group The group of particles this integration method is to work on\n*\/\nTwoStepNVERigidGPU::TwoStepNVERigidGPU(boost::shared_ptr<SystemDefinition> sysdef,\n boost::shared_ptr<ParticleGroup> group)\n : TwoStepNVERigid(sysdef, group)\n {\n \/\/ only one GPU is supported\n if (exec_conf.gpu.size() != 1)\n {\n cerr << endl << \"***Error! Creating a TwoStepNVEGPU with 0 or more than one GPUs\" << endl << endl;\n throw std::runtime_error(\"Error initializing TwoStepNVEGPU\");\n }\n }\n\n\/*! \\param timestep Current time step\n \\post Particle positions are moved forward to timestep+1 and velocities to timestep+1\/2 per the velocity verlet\n method.\n*\/\nvoid TwoStepNVERigidGPU::integrateStepOne(unsigned int timestep)\n {\n if (m_first_step)\n {\n setup();\n m_first_step = false;\n }\n \n \/\/ profile this step\n if (m_prof)\n m_prof->push(exec_conf, \"NVE rigid step 1\");\n \n \/\/ access all the needed data\n vector<gpu_pdata_arrays>& d_pdata = m_pdata->acquireReadWriteGPU();\n gpu_boxsize box = m_pdata->getBoxGPU();\n ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);\n unsigned int group_size = m_group->getIndexArray().getNumElements();\n \n \/\/ get the rigid data from SystemDefinition\n boost::shared_ptr<RigidData> rigid_data = m_sysdef->getRigidData();\n\n\tArrayHandle<Scalar> body_mass_handle(rigid_data->getBodyMass(), access_location::device, access_mode::read);\n\tArrayHandle<Scalar4> moment_inertia_handle(rigid_data->getMomentInertia(), access_location::device, access_mode::read);\n\tArrayHandle<Scalar4> com_handle(rigid_data->getCOM(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> vel_handle(rigid_data->getVel(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> angvel_handle(rigid_data->getAngVel(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> angmom_handle(rigid_data->getAngMom(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> orientation_handle(rigid_data->getOrientation(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> ex_space_handle(rigid_data->getExSpace(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> ey_space_handle(rigid_data->getEySpace(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> ez_space_handle(rigid_data->getEzSpace(), access_location::device, access_mode::readwrite);\n ArrayHandle<int> body_imagex_handle(rigid_data->getBodyImagex(), access_location::device, access_mode::readwrite);\n ArrayHandle<int> body_imagey_handle(rigid_data->getBodyImagey(), access_location::device, access_mode::readwrite);\n ArrayHandle<int> body_imagez_handle(rigid_data->getBodyImagez(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> particle_pos_handle(rigid_data->getParticlePos(), access_location::device, access_mode::read);\n ArrayHandle<unsigned int> particle_indices_handle(rigid_data->getParticleIndices(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> force_handle(rigid_data->getForce(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> torque_handle(rigid_data->getTorque(), access_location::device, access_mode::read);\n \n gpu_rigid_data_arrays d_rdata;\n d_rdata.n_bodies = rigid_data->getNumBodies();\n d_rdata.nmax = rigid_data->getNmax();\n d_rdata.local_beg = 0;\n d_rdata.local_num = d_rdata.n_bodies;\n d_rdata.body_mass = body_mass_handle.data;\n d_rdata.moment_inertia = moment_inertia_handle.data;\n d_rdata.com = com_handle.data;\n d_rdata.vel = vel_handle.data;\n d_rdata.angvel = angvel_handle.data;\n d_rdata.angmom = angmom_handle.data;\n d_rdata.orientation = orientation_handle.data;\n d_rdata.ex_space = ex_space_handle.data;\n d_rdata.ey_space = ey_space_handle.data;\n d_rdata.ez_space = ez_space_handle.data;\n d_rdata.body_imagex = body_imagex_handle.data;\n d_rdata.body_imagey = body_imagey_handle.data;\n d_rdata.body_imagez = body_imagez_handle.data;\n d_rdata.particle_pos = particle_pos_handle.data;\n d_rdata.particle_indices = particle_indices_handle.data;\n d_rdata.force = force_handle.data;\n d_rdata.torque = torque_handle.data;\n \n \/\/ perform the update on the GPU\n exec_conf.tagAll(__FILE__, __LINE__);\t\n exec_conf.gpu[0]->call(bind(gpu_nve_rigid_step_one, \n d_pdata[0],\n d_rdata, \n\t\t\t\t\t\t\t\td_index_array.data,\n\t\t\t\t\t\t\t\tgroup_size,\n\t\t\t\t\t\t\t\tbox,\n\t\t\t\t\t\t\t\tm_deltaT));\n\n\t\n m_pdata->release();\n \n \/\/ done profiling\n if (m_prof)\n m_prof->pop(exec_conf);\n }\n \n\/*! \\param timestep Current time step\n \\post particle velocities are moved forward to timestep+1 on the GPU\n*\/\nvoid TwoStepNVERigidGPU::integrateStepTwo(unsigned int timestep)\n {\n const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce();\n \n \/\/ profile this step\n if (m_prof)\n m_prof->push(exec_conf, \"NVE rigid step 2\");\n \n vector<gpu_pdata_arrays>& d_pdata = m_pdata->acquireReadWriteGPU();\n gpu_boxsize box = m_pdata->getBoxGPU();\n ArrayHandle<Scalar4> d_net_force(net_force, access_location::device, access_mode::read);\n ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);\n unsigned int group_size = m_group->getIndexArray().getNumElements();\n \n \/\/ get the rigid data from SystemDefinition\n boost::shared_ptr<RigidData> rigid_data = m_sysdef->getRigidData();\n\n ArrayHandle<Scalar> body_mass_handle(rigid_data->getBodyMass(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> moment_inertia_handle(rigid_data->getMomentInertia(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> com_handle(rigid_data->getCOM(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> vel_handle(rigid_data->getVel(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> angvel_handle(rigid_data->getAngVel(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> angmom_handle(rigid_data->getAngMom(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> ex_space_handle(rigid_data->getExSpace(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> ey_space_handle(rigid_data->getEySpace(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> ez_space_handle(rigid_data->getEzSpace(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> particle_pos_handle(rigid_data->getParticlePos(), access_location::device, access_mode::read);\n ArrayHandle<unsigned int> particle_indices_handle(rigid_data->getParticleIndices(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> force_handle(rigid_data->getForce(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> torque_handle(rigid_data->getTorque(), access_location::device, access_mode::readwrite);\n \n gpu_rigid_data_arrays d_rdata;\n d_rdata.n_bodies = rigid_data->getNumBodies();\n d_rdata.nmax = rigid_data->getNmax();\n d_rdata.local_beg = 0;\n d_rdata.local_num = d_rdata.n_bodies;\n d_rdata.body_mass = body_mass_handle.data;\n d_rdata.moment_inertia = moment_inertia_handle.data;\n\td_rdata.com = com_handle.data;\n d_rdata.vel = vel_handle.data;\n d_rdata.angvel = angvel_handle.data;\n d_rdata.angmom = angmom_handle.data;\n d_rdata.ex_space = ex_space_handle.data;\n d_rdata.ey_space = ey_space_handle.data;\n d_rdata.ez_space = ez_space_handle.data;\n d_rdata.particle_pos = particle_pos_handle.data;\n d_rdata.particle_indices = particle_indices_handle.data;\n d_rdata.force = force_handle.data;\n d_rdata.torque = torque_handle.data;\n \n\t\/\/ perform the update on the GPU\n exec_conf.tagAll(__FILE__, __LINE__);\n exec_conf.gpu[0]->call(bind(gpu_nve_rigid_step_two, \n\t\t\t\t\t\t\t\td_pdata[0], \n d_rdata, \n\t\t\t\t\t\t\t\td_index_array.data,\n\t\t\t\t\t\t\t\tgroup_size,\n d_net_force.data,\n box, \n\t\t\t\t\t\t\t\tm_deltaT,\n m_zero_force)); \n \n \n m_pdata->release();\n \n \/\/ done profiling\n if (m_prof)\n m_prof->pop(exec_conf);\n }\n\nvoid export_TwoStepNVERigidGPU()\n {\n class_<TwoStepNVERigidGPU, boost::shared_ptr<TwoStepNVERigidGPU>, bases<TwoStepNVERigid>, boost::noncopyable>\n (\"TwoStepNVERigidGPU\", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<ParticleGroup> >())\n ;\n }\n\n#ifdef WIN32\n#pragma warning( pop )\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2018 Taras Kushnir <kushnirTV@gmail.com>\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"updatehelpers.h\"\n#include <QProcess>\n#include <QStringList>\n#include <QDir>\n#include <QCoreApplication>\n#include <QFileInfo>\n#include \"..\/Common\/defines.h\"\n\n#ifdef Q_OS_OSX\n\nvoid launchOSXdmg(const QString &dmgPath) {\n QStringList arguments;\n arguments << dmgPath;\n\n QProcess::startDetached(\"open\", arguments);\n}\n\n#endif\n\n#ifdef Q_OS_WIN\n\nQString getLogFilenameForMinistaller() {\n QString time = QDateTime::currentDateTimeUtc().toString(\"ddMMyyyy-hhmmss-zzz\");\n QString logFilename = QString(\"ministaller-%1.log\").arg(time);\n return logFilename;\n}\n\nvoid launchWindowsInstaller(Common::ISystemEnvironment &environment, const QString &pathToUpdate) {\n LOG_DEBUG << \"#\";\n QString ministallerPath = environment.filepath(\"ministaller.exe\");\n\n if (!QFileInfo(ministallerPath).exists()) {\n LOG_WARNING << \"Updater not found!\" << ministallerPath;\n return;\n }\n\n QString installerLogName = getLogFilenameForMinistaller();\n QString installerLogPath = environment.fileInDir(installerLogName, \"logs\");\n QStringList arguments;\n arguments << \"-force-update\" << \"-gui\" <<\n \"-install-path\" << environment.root() <<\n \"-l\" << installerLogPath <<\n \"-launch-exe\" << \"Xpiks.exe\" <<\n \"-package-path\" << pathToUpdate <<\n \"-stdout\";\n\n QProcess::startDetached(ministallerPath, arguments);\n}\n\n#endif\n\nnamespace Helpers {\n void installUpdate(Common::ISystemEnvironment &environment, const QString &updatePath) {\n#if defined(Q_OS_OSX)\n launchOSXdmg(updatePath);\n#elif defined(Q_OS_WIN)\n launchWindowsInstaller(environment, updatePath);\n#endif\n }\n}\n<commit_msg>Fixes for env improvement in Windows<commit_after>\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2018 Taras Kushnir <kushnirTV@gmail.com>\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"updatehelpers.h\"\n#include <QProcess>\n#include <QStringList>\n#include <QDir>\n#include <QCoreApplication>\n#include <QFileInfo>\n#include \"..\/Common\/defines.h\"\n\n#ifdef Q_OS_OSX\n\nvoid launchOSXdmg(const QString &dmgPath) {\n QStringList arguments;\n arguments << dmgPath;\n\n QProcess::startDetached(\"open\", arguments);\n}\n\n#endif\n\n#ifdef Q_OS_WIN\n\nQString getLogFilenameForMinistaller() {\n QString time = QDateTime::currentDateTimeUtc().toString(\"ddMMyyyy-hhmmss-zzz\");\n QString logFilename = QString(\"ministaller-%1.log\").arg(time);\n return logFilename;\n}\n\nvoid launchWindowsInstaller(Common::ISystemEnvironment &environment, const QString &pathToUpdate) {\n LOG_DEBUG << \"#\";\n QString ministallerPath = environment.path({\"ministaller.exe\"});\n\n if (!QFileInfo(ministallerPath).exists()) {\n LOG_WARNING << \"Updater not found!\" << ministallerPath;\n return;\n }\n\n QString installerLogName = getLogFilenameForMinistaller();\n QString installerLogPath = environment.path({\"logs\", installerLogName});\n QStringList arguments;\n arguments << \"-force-update\" << \"-gui\" <<\n \"-install-path\" << environment.root() <<\n \"-l\" << installerLogPath <<\n \"-launch-exe\" << \"Xpiks.exe\" <<\n \"-package-path\" << pathToUpdate <<\n \"-stdout\";\n\n QProcess::startDetached(ministallerPath, arguments);\n}\n\n#endif\n\nnamespace Helpers {\n void installUpdate(Common::ISystemEnvironment &environment, const QString &updatePath) {\n#if defined(Q_OS_OSX)\n launchOSXdmg(updatePath);\n#elif defined(Q_OS_WIN)\n launchWindowsInstaller(environment, updatePath);\n#endif\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Qore Programming Language Qt4 Module\n\n Copyright 2009 Qore Technologies sro\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include <QByteArray>\n\n#include \"qoresmokeglobal.h\"\n#include \"qoreqtdynamicmethod.h\"\n#include \"commonqoremethod.h\"\n\n\nint QoreQtDynamicMethod::identifyTypes(SmokeTypeList &typeList, const char *sig, const char *p, ExceptionSink *xsink) {\n \/\/printd(0, \"QoreQtDynamicMethod::identifyTypes sig=%s p=%s\\n\", sig, p);\n while (*p && isblank(*p))\n ++p;\n if (*p != ')')\n while (*p) {\n const char *e = p + 1;\n char paren = 0;\n while (paren || (*e != ')' && *e != ',')) {\n assert(*e);\n switch (*e) {\n case '<':\n case '(':\n case '[':\n if (!paren)\n paren = *e;\n break;\n case '>':\n case ')':\n case ']':\n if (*e == paren)\n paren = 0;\n break;\n }\n ++e;\n }\n addType(typeList, p, e - p, sig, xsink);\n if (*e == ')')\n break;\n p = e + 1;\n }\n return *xsink ? -1 : 0;\n}\n\nint QoreQtDynamicMethod::addType(SmokeTypeList &typeList, const char *b, int len, const char *sig, ExceptionSink *xsink) {\n QByteArray tmp(b, len);\n QString tn(tmp);\n tn = tn.simplified();\n if (tn.endsWith(\" &\"))\n tn.replace(\" &\", \"&\");\n if (tn.endsWith(\" *\"))\n tn.replace(\" *\", \"*\");\n \/\/printd(0, \"QoreQtDynamicMethod::addType() processing type '%s'\\n\", tn.constData());\n\n Smoke::Type t;\n t.classId = -1;\n\n if (tn == \"int\") {\n t.name = \"int\";\n t.flags = Smoke::t_int | Smoke::tf_stack;\n } else if (tn == \"bool\") {\n t.name = \"bool\";\n t.flags = Smoke::t_bool | Smoke::tf_stack;\n } else if (tn == \"uint\") {\n t.name = \"uint\";\n t.flags = Smoke::t_uint | Smoke::tf_stack;\n } else if (tn == \"long\") {\n t.name = \"long\";\n t.flags = Smoke::t_long | Smoke::tf_stack;\n } else if (tn == \"ulong\") {\n t.name = \"ulong\";\n t.flags = Smoke::t_ulong | Smoke::tf_stack;\n } else if (tn == \"double\") {\n t.name = \"double\";\n t.flags = Smoke::t_double | Smoke::tf_stack;\n } else if (tn == \"char*\" ) {\n t.name = \"char*\";\n t.flags = Smoke::t_voidp | Smoke::tf_ptr;\n } else if (tn == \"qreal\") {\n t.name = \"qreal\";\n t.flags = Smoke::t_double | Smoke::tf_stack;\n } else if (tn.contains(\"QString\")) {\n t.name = \"QString&\";\n t.flags = Smoke::t_voidp | Smoke::tf_ref;\n }\n \/\/ everything else should be pointer to object\n else {\n \/\/ TODO\/FIXME: there should be a better way! But it looks like it is\n \/\/ not implemented in Smoke\n bool found = false;\n Smoke::Type st;\n for (int i = 0; i < qt_Smoke->numTypes; ++i) {\n st = qt_Smoke->types[i];\n if (tn == st.name) {\n \/\/printd(0, \"QoreQtDynamicMethod::addType() found object\/ref to %s\\n\", st.name);\n t.name = st.name;\n t.flags = st.flags;\n t.classId = st.classId;\n found = true;\n break;\n }\n }\n if (!found) {\n xsink->raiseException(\"DYNAMIC-METHOD-ERROR\", \"cannot handle argument type '%s' in '%s'\", tn.constData(), sig);\n return -1;\n }\n }\n\n typeList.push_back(t);\n return 0;\n}\n\nvoid QoreQtDynamicMethod::qtToQore(const Smoke::Type &t, void *arg, QoreListNode *args) {\n assert(t.name);\n Smoke::StackItem si;\n\n int typ = t.flags & Smoke::tf_ref;\n assert(typ);\n\n if (typ == Smoke::tf_ref && !strcmp(t.name, \"QString&\"))\n si.s_voidp = arg;\n else\n switch (t.flags & Smoke::tf_elem) {\n case Smoke::t_voidp:\n si.s_voidp = arg;\n break;\n case Smoke::t_bool:\n si.s_bool = * reinterpret_cast<bool*>(arg);\n break;\n case Smoke::t_int:\n si.s_int = * reinterpret_cast<int*>(arg);\n break;\n case Smoke::t_uint:\n si.s_uint = * reinterpret_cast<uint*>(arg);\n break;\n case Smoke::t_long:\n si.s_long = * reinterpret_cast<long*>(arg);\n break;\n case Smoke::t_ulong:\n si.s_ulong = * reinterpret_cast<ulong*>(arg);\n break;\n case Smoke::t_double:\n si.s_double = * reinterpret_cast<double*>(arg);\n break;\n case Smoke::t_float:\n si.s_float = * reinterpret_cast<float*>(arg);\n break;\n case Smoke::t_enum:\n si.s_enum = * reinterpret_cast<int*>(arg);\n break;\n case Smoke::t_class:\n\t \/\/printd(0, \"QoreQtDynamicMethod::qtToQore() type=%s flags=0x%x, const=%s type=0x%x arg=%p\\n\", t.name, t.flags, t.flags & 0x40 ? \"true\" : \"false\", t.flags & 0x30, arg);\n\t si.s_class = t.flags & Smoke::tf_ptr ? *((void **)arg) : arg;\n\t \/\/si.s_class = arg;\n break;\n\n default:\n\t \/\/printd(0, \"QoreQtDynamicMethod::qtToQore type=%s flags=%d\\n\", t.name, t.flags);\n Q_ASSERT_X(false, \"sig\/slot\", \"missing qt to qore handling\");\n }\n\n\/\/ if ((t.flags & Smoke::tf_elem) == Smoke::t_bool) {\n\/\/ bool *ptr = reinterpret_cast<bool *>(arg);\n\/\/ args->push(get_bool_node(*ptr));\n\/\/ } else if ((t.flags & Smoke::tf_elem) == Smoke::t_int) {\n\/\/ int *ptr = reinterpret_cast<int *>(arg);\n\/\/ args->push(new QoreBigIntNode(*ptr));\n\/\/ } else\n\/\/ assert(false);\n\n ExceptionSink xsink;\n AbstractQoreNode *newNode = Marshalling::stackToQore(t, si, &xsink);\n printd(0, \"QoreQtDynamicMethod::qtToQore() type: %s s_class=%p rv=%p\\n\", t.name, si.s_class, newNode);\n if (!newNode)\n xsink.handleExceptions();\n args->push(newNode);\n}\n\nstatic void doDefaultValue(const Smoke::Type &t, Smoke::StackItem &si, ExceptionSink *xsink) {\n#ifdef DEBUG\n int tid = t.flags & Smoke::tf_elem;\n int flags = t.flags & 0x30;\n \/\/bool iconst = t.flags & Smoke::tf_const;\n\n \/\/printd(0, \"qtType.flags=%x const=%d tid=%d name=%s\\n\", flags, iconst, tid, t.name);\n\n assert(tid == Smoke::t_class);\n assert(flags == Smoke::tf_stack);\n#endif\n\n \/\/ find and execute constructor\n CommonQoreMethod cqm(0, 0, t.name, t.name, 0, xsink);\n\n si.s_class = cqm.callConstructor();\n}\n\nvoid QoreQtDynamicMethod::qoreToQt(ExceptionSink *xsink, const Smoke::Type &qtType, Smoke::StackItem &si, void *&ptr, void *&save, const AbstractQoreNode *val, const char *cname, const char *mname, int index, bool value_required) {\n save = 0;\n ptr = 0;\n\/\/ printd(0, \"qoreToQt() ptr=%p save=%p, val=%p (%s) typename=%s\\n\", ptr, save, val, val ? val->getTypeName() : \"n\/a\", qtType.name);\n\n \/\/QByteArray bname(qtType.name);\n if (CommonQoreMethod::qoreToStackStatic(xsink, si, cname, mname, qtType, val, index) == -1) {\n \n \/\/ setup default value on stack if required (ex: slot return value), otherwise return\n if (value_required)\n\t doDefaultValue(qtType, si, xsink);\n else\n\t return;\n }\n\n switch (qtType.flags & Smoke::tf_elem) {\n case Smoke::t_voidp:\n save = si.s_voidp;\n break;\n case Smoke::t_bool:\n save = \/*(void *)*\/&si.s_bool;\n break;\n case Smoke::t_char:\n save = \/*(void *)*\/&si.s_char;\n break;\n case Smoke::t_uchar:\n save = \/*(void *)*\/&si.s_uchar;\n break;\n case Smoke::t_short:\n save = \/*(void *)*\/&si.s_short;\n break;\n case Smoke::t_ushort:\n save = \/*(void *)*\/&si.s_ushort;\n break;\n case Smoke::t_int:\n save = \/*(void *)*\/&si.s_int;\n break;\n case Smoke::t_uint:\n save = \/*(void *)*\/&si.s_uint;\n break;\n case Smoke::t_long:\n save = \/*(void *)*\/&si.s_long;\n break;\n case Smoke::t_ulong:\n save = \/*(void *)*\/&si.s_ulong;\n break;\n case Smoke::t_float:\n save = \/*(void *)*\/&si.s_float;\n break;\n case Smoke::t_double:\n save = \/*(void *)*\/&si.s_double;\n break;\n case Smoke::t_enum:\n save = \/*(void *)*\/&si.s_enum;\n break;\n case Smoke::t_class:\n save = si.s_class;\n break;\n default:\n Q_ASSERT_X(false, \"sig\/slot\", \"missing qore to qt handling\");\n }\n ptr = save;\n}\n\nvoid QoreQtDynamicMethod::qoreToQtDirect(const Smoke::Type &qtType, void *&ptr, const AbstractQoreNode *val, const char *cname, const char *mname) {\n \/\/printd(0, \"qoreToQtDirect() ptr=%p val=%p (%s)\\n\", ptr, val, val ? val->getTypeName() : \"n\/a\");\n void * save;\n Smoke::StackItem si;\n ExceptionSink xsink;\n qoreToQt(&xsink, qtType, si, ptr, save, val, cname, mname, -1, true);\n}\n\nQoreQtDynamicSlot::QoreQtDynamicSlot(const QoreObject *qo, const QoreMethod *meth, const char *sig, ExceptionSink *xsink) : qore_obj(const_cast<QoreObject *>(qo)), method(meth) {\n returnType.name = 0;\n\n \/\/printd(5, \"QoreQtDynamicSlot::QoreQtDynamicSlot() registering method '%s'\\n\", meth->getName());\n\n const char *p = strchr(sig, '(');\n if (!p)\n return;\n ++p;\n while (*p && isblank(*p))\n ++p;\n if (*p != ')')\n identifyAndAddTypes(sig, p, xsink);\n}\n\nvoid QoreQtDynamicSlot::call(QoreObject *self, void **arguments) const {\n ExceptionSink xsink;\n\n \/\/printd(0, \"QoreQtDynamicSlot::call(self=%p, arguments=%p) %s() num_args=%d\\n\", self, arguments, method->getName(), typeList.size());\n \/\/ create Qore argument list\n ReferenceHolder<QoreListNode> args(typeList.empty() ? 0 : new QoreListNode, &xsink);\n for (int i = 0, e = typeList.size(); i < e; ++i) {\n printd(0, \"%s() arg %d: %s %p\\n\", method->getName(), i + 1, typeList[i].name, arguments[i + 1]);\n qtToQore(typeList[i], arguments[i + 1], *args);\n }\n\n \/\/ call Qore user method\n ReferenceHolder<AbstractQoreNode> rv(qore_obj->evalMethod(*method, *args, &xsink), &xsink);\n\n \/\/ process return value\n if (returnType.name)\n qoreToQtDirect(returnType, arguments[0], *rv, qore_obj->getClassName(), method->getName());\n}\n\nQoreQtDynamicSignal::QoreQtDynamicSignal(const char *sig, ExceptionSink *xsink) {\n const char *p = strchr(sig, '(');\n\n if (!p) {\n xsink->raiseException(\"DYNAMIC-SIGNAL-ERROR\", \"invalid signal signature '%s'\", sig);\n return;\n }\n ++p;\n\n identifyAndAddTypes(sig, p, xsink);\n}\n\nvoid QoreQtDynamicSignal::emitSignal(QObject *obj, int id, const QoreListNode *args, ExceptionSink *xsink) {\n int num_args = typeList.size();\n void *sig_args[num_args + 1];\n void *save_args[num_args];\n Smoke::StackItem si[num_args];\n\n \/\/ set return value to 0\n sig_args[0] = 0;\n\n \/\/ iterate through signal parameters to build argument list\n for (int i = 0; i < num_args; ++i) {\n \/\/ get argument QoreNode\n const AbstractQoreNode *n = args ? args->retrieve_entry(i + 1) : 0;\n\n qoreToQt(xsink, typeList[i], si[i], sig_args[i + 1], save_args[i], n, \"QObject\", \"emit\", i + 1);\n\tif (*xsink)\n\t return;\n }\n QMetaObject::activate(obj, id, id, sig_args);\n\n \/\/ iterate through signal parameters to delete temporary values\n \/\/for (int i = 0; i < num_args; ++i)\n \/\/ type_list[i]->del_arg(save_args[i]);\n}\n\n\n<commit_msg>fixed typo in last commit regarding signal\/slot args<commit_after>\/*\n Qore Programming Language Qt4 Module\n\n Copyright 2009 Qore Technologies sro\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include <QByteArray>\n\n#include \"qoresmokeglobal.h\"\n#include \"qoreqtdynamicmethod.h\"\n#include \"commonqoremethod.h\"\n\n\nint QoreQtDynamicMethod::identifyTypes(SmokeTypeList &typeList, const char *sig, const char *p, ExceptionSink *xsink) {\n \/\/printd(0, \"QoreQtDynamicMethod::identifyTypes sig=%s p=%s\\n\", sig, p);\n while (*p && isblank(*p))\n ++p;\n if (*p != ')')\n while (*p) {\n const char *e = p + 1;\n char paren = 0;\n while (paren || (*e != ')' && *e != ',')) {\n assert(*e);\n switch (*e) {\n case '<':\n case '(':\n case '[':\n if (!paren)\n paren = *e;\n break;\n case '>':\n case ')':\n case ']':\n if (*e == paren)\n paren = 0;\n break;\n }\n ++e;\n }\n addType(typeList, p, e - p, sig, xsink);\n if (*e == ')')\n break;\n p = e + 1;\n }\n return *xsink ? -1 : 0;\n}\n\nint QoreQtDynamicMethod::addType(SmokeTypeList &typeList, const char *b, int len, const char *sig, ExceptionSink *xsink) {\n QByteArray tmp(b, len);\n QString tn(tmp);\n tn = tn.simplified();\n if (tn.endsWith(\" &\"))\n tn.replace(\" &\", \"&\");\n if (tn.endsWith(\" *\"))\n tn.replace(\" *\", \"*\");\n \/\/printd(0, \"QoreQtDynamicMethod::addType() processing type '%s'\\n\", tn.constData());\n\n Smoke::Type t;\n t.classId = -1;\n\n if (tn == \"int\") {\n t.name = \"int\";\n t.flags = Smoke::t_int | Smoke::tf_stack;\n } else if (tn == \"bool\") {\n t.name = \"bool\";\n t.flags = Smoke::t_bool | Smoke::tf_stack;\n } else if (tn == \"uint\") {\n t.name = \"uint\";\n t.flags = Smoke::t_uint | Smoke::tf_stack;\n } else if (tn == \"long\") {\n t.name = \"long\";\n t.flags = Smoke::t_long | Smoke::tf_stack;\n } else if (tn == \"ulong\") {\n t.name = \"ulong\";\n t.flags = Smoke::t_ulong | Smoke::tf_stack;\n } else if (tn == \"double\") {\n t.name = \"double\";\n t.flags = Smoke::t_double | Smoke::tf_stack;\n } else if (tn == \"char*\" ) {\n t.name = \"char*\";\n t.flags = Smoke::t_voidp | Smoke::tf_ptr;\n } else if (tn == \"qreal\") {\n t.name = \"qreal\";\n t.flags = Smoke::t_double | Smoke::tf_stack;\n } else if (tn.contains(\"QString\")) {\n t.name = \"QString&\";\n t.flags = Smoke::t_voidp | Smoke::tf_ref;\n }\n \/\/ everything else should be pointer to object\n else {\n \/\/ TODO\/FIXME: there should be a better way! But it looks like it is\n \/\/ not implemented in Smoke\n bool found = false;\n Smoke::Type st;\n for (int i = 0; i < qt_Smoke->numTypes; ++i) {\n st = qt_Smoke->types[i];\n if (tn == st.name) {\n \/\/printd(0, \"QoreQtDynamicMethod::addType() found object\/ref to %s\\n\", st.name);\n t.name = st.name;\n t.flags = st.flags;\n t.classId = st.classId;\n found = true;\n break;\n }\n }\n if (!found) {\n xsink->raiseException(\"DYNAMIC-METHOD-ERROR\", \"cannot handle argument type '%s' in '%s'\", tn.constData(), sig);\n return -1;\n }\n }\n\n typeList.push_back(t);\n return 0;\n}\n\nvoid QoreQtDynamicMethod::qtToQore(const Smoke::Type &t, void *arg, QoreListNode *args) {\n assert(t.name);\n Smoke::StackItem si;\n\n int typ = t.flags & Smoke::tf_ref;\n assert(typ);\n\n if (typ == Smoke::tf_ref && !strcmp(t.name, \"QString&\"))\n si.s_voidp = arg;\n else\n switch (t.flags & Smoke::tf_elem) {\n case Smoke::t_voidp:\n si.s_voidp = arg;\n break;\n case Smoke::t_bool:\n si.s_bool = * reinterpret_cast<bool*>(arg);\n break;\n case Smoke::t_int:\n si.s_int = * reinterpret_cast<int*>(arg);\n break;\n case Smoke::t_uint:\n si.s_uint = * reinterpret_cast<uint*>(arg);\n break;\n case Smoke::t_long:\n si.s_long = * reinterpret_cast<long*>(arg);\n break;\n case Smoke::t_ulong:\n si.s_ulong = * reinterpret_cast<ulong*>(arg);\n break;\n case Smoke::t_double:\n si.s_double = * reinterpret_cast<double*>(arg);\n break;\n case Smoke::t_float:\n si.s_float = * reinterpret_cast<float*>(arg);\n break;\n case Smoke::t_enum:\n si.s_enum = * reinterpret_cast<int*>(arg);\n break;\n case Smoke::t_class:\n\t printd(0, \"QoreQtDynamicMethod::qtToQore() type=%s flags=0x%x, const=%s type=0x%x arg=%p\\n\", t.name, t.flags, t.flags & 0x40 ? \"true\" : \"false\", t.flags & 0x30, arg);\n\t si.s_class = typ == Smoke::tf_ptr ? *((void **)arg) : arg;\n\t \/\/si.s_class = arg;\n break;\n\n default:\n\t \/\/printd(0, \"QoreQtDynamicMethod::qtToQore type=%s flags=%d\\n\", t.name, t.flags);\n Q_ASSERT_X(false, \"sig\/slot\", \"missing qt to qore handling\");\n }\n\n\/\/ if ((t.flags & Smoke::tf_elem) == Smoke::t_bool) {\n\/\/ bool *ptr = reinterpret_cast<bool *>(arg);\n\/\/ args->push(get_bool_node(*ptr));\n\/\/ } else if ((t.flags & Smoke::tf_elem) == Smoke::t_int) {\n\/\/ int *ptr = reinterpret_cast<int *>(arg);\n\/\/ args->push(new QoreBigIntNode(*ptr));\n\/\/ } else\n\/\/ assert(false);\n\n ExceptionSink xsink;\n AbstractQoreNode *newNode = Marshalling::stackToQore(t, si, &xsink);\n printd(0, \"QoreQtDynamicMethod::qtToQore() type: %s s_class=%p rv=%p\\n\", t.name, si.s_class, newNode);\n if (!newNode)\n xsink.handleExceptions();\n args->push(newNode);\n}\n\nstatic void doDefaultValue(const Smoke::Type &t, Smoke::StackItem &si, ExceptionSink *xsink) {\n#ifdef DEBUG\n int tid = t.flags & Smoke::tf_elem;\n int flags = t.flags & 0x30;\n \/\/bool iconst = t.flags & Smoke::tf_const;\n\n \/\/printd(0, \"qtType.flags=%x const=%d tid=%d name=%s\\n\", flags, iconst, tid, t.name);\n\n assert(tid == Smoke::t_class);\n assert(flags == Smoke::tf_stack);\n#endif\n\n \/\/ find and execute constructor\n CommonQoreMethod cqm(0, 0, t.name, t.name, 0, xsink);\n\n si.s_class = cqm.callConstructor();\n}\n\nvoid QoreQtDynamicMethod::qoreToQt(ExceptionSink *xsink, const Smoke::Type &qtType, Smoke::StackItem &si, void *&ptr, void *&save, const AbstractQoreNode *val, const char *cname, const char *mname, int index, bool value_required) {\n save = 0;\n ptr = 0;\n\/\/ printd(0, \"qoreToQt() ptr=%p save=%p, val=%p (%s) typename=%s\\n\", ptr, save, val, val ? val->getTypeName() : \"n\/a\", qtType.name);\n\n \/\/QByteArray bname(qtType.name);\n if (CommonQoreMethod::qoreToStackStatic(xsink, si, cname, mname, qtType, val, index) == -1) {\n \n \/\/ setup default value on stack if required (ex: slot return value), otherwise return\n if (value_required)\n\t doDefaultValue(qtType, si, xsink);\n else\n\t return;\n }\n\n switch (qtType.flags & Smoke::tf_elem) {\n case Smoke::t_voidp:\n save = si.s_voidp;\n break;\n case Smoke::t_bool:\n save = \/*(void *)*\/&si.s_bool;\n break;\n case Smoke::t_char:\n save = \/*(void *)*\/&si.s_char;\n break;\n case Smoke::t_uchar:\n save = \/*(void *)*\/&si.s_uchar;\n break;\n case Smoke::t_short:\n save = \/*(void *)*\/&si.s_short;\n break;\n case Smoke::t_ushort:\n save = \/*(void *)*\/&si.s_ushort;\n break;\n case Smoke::t_int:\n save = \/*(void *)*\/&si.s_int;\n break;\n case Smoke::t_uint:\n save = \/*(void *)*\/&si.s_uint;\n break;\n case Smoke::t_long:\n save = \/*(void *)*\/&si.s_long;\n break;\n case Smoke::t_ulong:\n save = \/*(void *)*\/&si.s_ulong;\n break;\n case Smoke::t_float:\n save = \/*(void *)*\/&si.s_float;\n break;\n case Smoke::t_double:\n save = \/*(void *)*\/&si.s_double;\n break;\n case Smoke::t_enum:\n save = \/*(void *)*\/&si.s_enum;\n break;\n case Smoke::t_class:\n save = si.s_class;\n break;\n default:\n Q_ASSERT_X(false, \"sig\/slot\", \"missing qore to qt handling\");\n }\n ptr = save;\n}\n\nvoid QoreQtDynamicMethod::qoreToQtDirect(const Smoke::Type &qtType, void *&ptr, const AbstractQoreNode *val, const char *cname, const char *mname) {\n \/\/printd(0, \"qoreToQtDirect() ptr=%p val=%p (%s)\\n\", ptr, val, val ? val->getTypeName() : \"n\/a\");\n void * save;\n Smoke::StackItem si;\n ExceptionSink xsink;\n qoreToQt(&xsink, qtType, si, ptr, save, val, cname, mname, -1, true);\n}\n\nQoreQtDynamicSlot::QoreQtDynamicSlot(const QoreObject *qo, const QoreMethod *meth, const char *sig, ExceptionSink *xsink) : qore_obj(const_cast<QoreObject *>(qo)), method(meth) {\n returnType.name = 0;\n\n \/\/printd(5, \"QoreQtDynamicSlot::QoreQtDynamicSlot() registering method '%s'\\n\", meth->getName());\n\n const char *p = strchr(sig, '(');\n if (!p)\n return;\n ++p;\n while (*p && isblank(*p))\n ++p;\n if (*p != ')')\n identifyAndAddTypes(sig, p, xsink);\n}\n\nvoid QoreQtDynamicSlot::call(QoreObject *self, void **arguments) const {\n ExceptionSink xsink;\n\n \/\/printd(0, \"QoreQtDynamicSlot::call(self=%p, arguments=%p) %s() num_args=%d\\n\", self, arguments, method->getName(), typeList.size());\n \/\/ create Qore argument list\n ReferenceHolder<QoreListNode> args(typeList.empty() ? 0 : new QoreListNode, &xsink);\n for (int i = 0, e = typeList.size(); i < e; ++i) {\n printd(0, \"%s() arg %d: %s %p\\n\", method->getName(), i + 1, typeList[i].name, arguments[i + 1]);\n qtToQore(typeList[i], arguments[i + 1], *args);\n }\n\n \/\/ call Qore user method\n ReferenceHolder<AbstractQoreNode> rv(qore_obj->evalMethod(*method, *args, &xsink), &xsink);\n\n \/\/ process return value\n if (returnType.name)\n qoreToQtDirect(returnType, arguments[0], *rv, qore_obj->getClassName(), method->getName());\n}\n\nQoreQtDynamicSignal::QoreQtDynamicSignal(const char *sig, ExceptionSink *xsink) {\n const char *p = strchr(sig, '(');\n\n if (!p) {\n xsink->raiseException(\"DYNAMIC-SIGNAL-ERROR\", \"invalid signal signature '%s'\", sig);\n return;\n }\n ++p;\n\n identifyAndAddTypes(sig, p, xsink);\n}\n\nvoid QoreQtDynamicSignal::emitSignal(QObject *obj, int id, const QoreListNode *args, ExceptionSink *xsink) {\n int num_args = typeList.size();\n void *sig_args[num_args + 1];\n void *save_args[num_args];\n Smoke::StackItem si[num_args];\n\n \/\/ set return value to 0\n sig_args[0] = 0;\n\n \/\/ iterate through signal parameters to build argument list\n for (int i = 0; i < num_args; ++i) {\n \/\/ get argument QoreNode\n const AbstractQoreNode *n = args ? args->retrieve_entry(i + 1) : 0;\n\n qoreToQt(xsink, typeList[i], si[i], sig_args[i + 1], save_args[i], n, \"QObject\", \"emit\", i + 1);\n\tif (*xsink)\n\t return;\n }\n QMetaObject::activate(obj, id, id, sig_args);\n\n \/\/ iterate through signal parameters to delete temporary values\n \/\/for (int i = 0; i < num_args; ++i)\n \/\/ type_list[i]->del_arg(save_args[i]);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef G2_FIELD_CORE_INCLUDE_FIELD_CONSTANTS_HH_\n#define G2_FIELD_CORE_INCLUDE_FIELD_CONSTANTS_HH_\n\n\/*===========================================================================*\\\n\nauthor: Matthias W. Smith\nemail: mwsmith2@uw.edu\nfile: field_constants.hh\n\nabout: A header file for constant parameters used across field team\n software.\n\n\\*===========================================================================*\/\n\n\n\/\/ NMR literals\n#define NMR_NUM_FIXED_PROBES 378\n#define NMR_FID_LENGTH_ONLINE 100000\n#define NMR_FID_LENGTH_RECORD 10000\n#define NMR_KHZ_TO_PPM 61790.0 * 1.0e-6\n#define NMR_SAMPLE_PERIOD 0.0001\n\n\/\/Trolley literals\n#define TRLY_NMR_LENGTH 24000\n#define TRLY_BARCODE_LENGTH 3000 \/\/ALL CHANNELS\n#define TRLY_BARCODE_CHANNELS 6\n#define TRLY_MONITOR_LENGTH 3000\n\nnamespace g2field {\n\n\/\/ General constants\nconstexpr double kMagicRadius = 7112.0;\nconstexpr double kPoleGapZ = 180.0;\n\n\/\/ NMR constants\nconstexpr int kNmrNumFixedProbes = NMR_NUM_FIXED_PROBES;\nconstexpr int kNmrFidLengthOnline = NMR_FID_LENGTH_ONLINE;\nconstexpr int kNmrFidLengthRecord = NMR_FID_LENGTH_RECORD;\nconstexpr double kNmrKhzToPpm = NMR_KHZ_TO_PPM;\nconstexpr double kNmrSamplePeriod = NMR_SAMPLE_PERIOD;\n\n\/\/ Trolley constants\nconstexpr int kNumTrolleyProbes = 17;\nconstexpr double kTrolleyRadius = 3.5;\n\n} \/\/ ::g2field\n\n#endif\n<commit_msg>adding root include<commit_after>#ifndef G2_FIELD_CORE_INCLUDE_FIELD_CONSTANTS_HH_\n#define G2_FIELD_CORE_INCLUDE_FIELD_CONSTANTS_HH_\n\n\/*===========================================================================*\\\n\nauthor: Matthias W. Smith\nemail: mwsmith2@uw.edu\nfile: field_constants.hh\n\nabout: A header file for constant parameters used across field team\n software.\n\n\\*===========================================================================*\/\n\n#include \"TROOT.h\"\n\n\/\/ NMR literals\n#define NMR_NUM_FIXED_PROBES 378\n#define NMR_FID_LENGTH_ONLINE 100000\n#define NMR_FID_LENGTH_RECORD 10000\n#define NMR_KHZ_TO_PPM 61790.0 * 1.0e-6\n#define NMR_SAMPLE_PERIOD 0.0001\n\n\/\/Trolley literals\n#define TRLY_NMR_LENGTH 24000\n#define TRLY_BARCODE_LENGTH 3000 \/\/ALL CHANNELS\n#define TRLY_BARCODE_CHANNELS 6\n#define TRLY_MONITOR_LENGTH 3000\n\nnamespace g2field {\n\n\/\/ General constants\nconstexpr double kMagicRadius = 7112.0;\nconstexpr double kPoleGapZ = 180.0;\n\n\/\/ NMR constants\nconstexpr int kNmrNumFixedProbes = NMR_NUM_FIXED_PROBES;\nconstexpr int kNmrFidLengthOnline = NMR_FID_LENGTH_ONLINE;\nconstexpr int kNmrFidLengthRecord = NMR_FID_LENGTH_RECORD;\nconstexpr double kNmrKhzToPpm = NMR_KHZ_TO_PPM;\nconstexpr double kNmrSamplePeriod = NMR_SAMPLE_PERIOD;\n\n\/\/ Trolley constants\nconstexpr int kNumTrolleyProbes = 17;\nconstexpr double kTrolleyRadius = 3.5;\n\n} \/\/ ::g2field\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*!\n \\file record.inl\n \\brief Logging record inline implementation\n \\author Ivan Shynkarenka\n \\date 08.07.2016\n \\copyright MIT License\n*\/\n\nnamespace CppLogging {\n\n\/\/! @cond INTERNALS\nnamespace Internals {\n\ntemplate <typename Char, typename T>\nstd::size_t CalculateExtraSize(const fmt::internal::Arg& arg)\n{\n std::size_t result = 0;\n\n if (arg.type == fmt::internal::Arg::CSTRING)\n result = sizeof(std::size_t) + (std::strlen(arg.string.value) + 1) * sizeof(char);\n else if (arg.type == fmt::internal::Arg::STRING)\n result = sizeof(std::size_t) + arg.string.size * sizeof(char);\n else if (arg.type == fmt::internal::Arg::WSTRING)\n result = sizeof(std::size_t) + arg.wstring.size * sizeof(wchar_t);\n else if (arg.type == fmt::internal::Arg::CUSTOM)\n result = sizeof(T);\n\n return result;\n}\n\ntemplate <typename Char>\nunsigned CalculateBufferSize(std::size_t&)\n{\n return 0;\n}\n\ntemplate <typename Char, typename T>\nunsigned CalculateBufferSize(std::size_t& extra_size, const T& argument)\n{\n fmt::internal::MakeArg<fmt::BasicFormatter<Char>> arg(argument);\n extra_size += CalculateExtraSize<Char, T>(arg);\n return 1;\n}\n\ntemplate <typename Char, typename T>\nunsigned CalculateBufferSize(std::size_t& extra_size, const fmt::internal::NamedArgWithType<Char, T>& argument)\n{\n extra_size += sizeof(fmt::internal::NamedArgWithType<Char, T>) + sizeof(std::size_t) + argument.name.size() * sizeof(Char) + CalculateExtraSize<Char, fmt::internal::NamedArgWithType<Char, T>>(argument);\n return 1;\n}\n\ntemplate <typename Char, typename T, typename... Args>\nunsigned CalculateBufferSize(std::size_t& extra_size, const T& argument, const Args&... args)\n{\n unsigned count = 0;\n count += CalculateBufferSize<Char>(extra_size, argument);\n count += CalculateBufferSize<Char>(extra_size, args...);\n return count;\n}\n\ntemplate <typename Char, typename T>\nvoid SerializeExtraData(uint8_t*& data_buffer, fmt::internal::Arg::Type type, const fmt::internal::Value& value)\n{\n \/\/ Serialize extra data\n if (type == fmt::internal::Arg::CSTRING)\n {\n std::size_t size = (std::strlen(value.string.value) + 1) * sizeof(char);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, value.string.value, size);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::STRING)\n {\n std::size_t size = value.string.size * sizeof(char);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, value.string.value, size);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::WSTRING)\n {\n std::size_t size = value.wstring.size * sizeof(wchar_t);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, value.wstring.value, size);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::CUSTOM)\n {\n std::size_t size = sizeof(T);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, value.custom.value, size);\n data_buffer += size;\n }\n}\n\ntemplate <typename Char, typename T>\nvoid SerializeExtraData(uint8_t*& data_buffer, const fmt::internal::NamedArgWithType<Char, T>& named)\n{\n std::memcpy(data_buffer, &named, sizeof(fmt::internal::NamedArgWithType<Char, T>));\n data_buffer += sizeof(fmt::internal::NamedArgWithType<Char, T>);\n std::size_t size = named.name.size() * sizeof(Char);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, named.name.data(), size);\n data_buffer += size;\n SerializeExtraData<Char, T>(data_buffer, named.type, named);\n}\n\ntemplate <typename Char>\nvoid SerializeArguments(std::size_t, uint8_t*&, uint8_t*&)\n{\n}\n\ntemplate <typename Char, typename T>\nvoid SerializeArguments(std::size_t item_size, uint8_t*& base_buffer, uint8_t*& data_buffer, const T& argument)\n{\n \/\/ Serialize argument\n fmt::internal::MakeArg<fmt::BasicFormatter<Char>> arg(argument);\n std::memcpy(base_buffer, &arg, item_size);\n base_buffer += item_size;\n \/\/ Serialize extra data\n SerializeExtraData<Char, T>(data_buffer, arg.type, arg);\n}\n\ntemplate <typename Char, typename T>\nvoid SerializeArguments(std::size_t item_size, uint8_t*& base_buffer, uint8_t*& data_buffer, const fmt::internal::NamedArgWithType<Char, T>& argument)\n{\n \/\/ Serialize argument\n const fmt::internal::Arg& arg = argument;\n std::memcpy(base_buffer, &arg, item_size);\n base_buffer += item_size;\n \/\/ Serialize extra data\n SerializeExtraData<Char, T>(data_buffer, argument);\n}\n\ntemplate <typename Char, typename T, typename... Args>\nvoid SerializeArguments(std::size_t item_size, uint8_t*& base_buffer, uint8_t*& data_buffer, const T& argument, const Args&... args)\n{\n SerializeArguments<Char>(item_size, base_buffer, data_buffer, argument);\n SerializeArguments<Char>(item_size, base_buffer, data_buffer, args...);\n}\n\ntemplate <typename Char, typename... Args>\nvoid Serialize(std::vector<uint8_t>& buffer, const Args&... args)\n{\n std::size_t extra_size = 0;\n unsigned count = CalculateBufferSize<Char>(extra_size, args...);\n\n \/\/ Special check for none format arguments\n if (count == 0)\n return;\n\n \/\/ Caclulate base & full buffer sizes\n std::size_t item_size = (count > fmt::ArgList::MAX_PACKED_ARGS) ? sizeof(fmt::internal::Arg) : sizeof(fmt::internal::Value);\n std::size_t base_size = sizeof(unsigned) + sizeof(std::size_t) + sizeof(fmt::ULongLong) + count * item_size;\n std::size_t full_size = base_size + extra_size;\n\n \/\/ Resize buffer to fit all format arguments\n buffer.resize(full_size);\n\n uint8_t* base_buffer = buffer.data();\n uint8_t* data_buffer = base_buffer + base_size;\n\n \/\/ Serialize the count of format arguments\n std::memcpy(base_buffer, &count, sizeof(unsigned));\n base_buffer += sizeof(unsigned);\n\n \/\/ Serialize the base buffer size\n std::memcpy(base_buffer, &base_size, sizeof(std::size_t));\n base_buffer += sizeof(std::size_t);\n\n \/\/ Serialize types of format arguments\n fmt::ULongLong types = fmt::internal::make_type(args...);\n std::memcpy(base_buffer, &types, sizeof(fmt::ULongLong));\n base_buffer += sizeof(fmt::ULongLong);\n\n \/\/ Serialize values of format arguments\n SerializeArguments<Char>(item_size, base_buffer, data_buffer, args...);\n}\n\ntemplate <typename Char>\nvoid DeserializeExtraData(uint8_t*& data_buffer, fmt::internal::Arg::Type type, fmt::internal::Value& value)\n{\n \/\/ Deserialize extra data\n if (type == fmt::internal::Arg::NAMED_ARG)\n {\n fmt::internal::NamedArg<Char>* named = reinterpret_cast<fmt::internal::NamedArg<Char>*>(data_buffer);\n value.pointer = named;\n data_buffer += sizeof(fmt::internal::NamedArg<Char>);\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n named->name = fmt::BasicStringRef<Char>(reinterpret_cast<const Char*>(data_buffer), size);\n data_buffer += size;\n DeserializeExtraData<Char>(data_buffer, named->type, *named);\n }\n else if (type == fmt::internal::Arg::CSTRING)\n {\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n value.string.value = reinterpret_cast<const char*>(data_buffer);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::STRING)\n {\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n value.string.value = reinterpret_cast<const char*>(data_buffer);\n value.string.size = size \/ sizeof(char);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::WSTRING)\n {\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n value.wstring.value = reinterpret_cast<const wchar_t*>(data_buffer);\n value.wstring.size = size \/ sizeof(wchar_t);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::CUSTOM)\n {\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n value.custom.value = data_buffer;\n data_buffer += size;\n }\n}\n\ntemplate <typename Char>\nfmt::ArgList Deserialize(std::vector<uint8_t>& buffer)\n{\n \/\/ Special check for empty format arguments list\n if (buffer.empty())\n return fmt::ArgList();\n\n uint8_t* base_buffer = buffer.data();\n uint8_t* data_buffer = base_buffer;\n\n \/\/ Deserialize the count of format arguments\n unsigned count;\n std::memcpy(&count, base_buffer, sizeof(unsigned));\n base_buffer += sizeof(unsigned);\n\n \/\/ Deserialize the base buffer size\n std::size_t base_size;\n std::memcpy(&base_size, base_buffer, sizeof(std::size_t));\n base_buffer += sizeof(std::size_t);\n\n \/\/ Update the data buffer offset\n data_buffer += base_size;\n\n \/\/ Deserialize types of format arguments\n fmt::ULongLong types;\n std::memcpy(&types, base_buffer, sizeof(fmt::ULongLong));\n base_buffer += sizeof(fmt::ULongLong);\n\n \/\/ Calculate the item size\n std::size_t item_size = (count > fmt::ArgList::MAX_PACKED_ARGS) ? sizeof(fmt::internal::Arg) : sizeof(fmt::internal::Value);\n\n \/\/ Deserialize values of format arguments\n uint8_t* local_buffer = base_buffer;\n for (unsigned i = 0; i < count; ++i)\n {\n \/\/ Deserialize argument\n fmt::internal::Value* value = reinterpret_cast<fmt::internal::Value*>(local_buffer);\n local_buffer += item_size;\n \/\/ Deserialize extra data\n DeserializeExtraData<Char>(data_buffer, fmt::ArgList::type(types, i), *value);\n }\n\n \/\/ Prepare and return arguments list stored in the provided buffer\n return (count > fmt::ArgList::MAX_PACKED_ARGS) ?\n fmt::ArgList(types, reinterpret_cast<const fmt::internal::Arg*>(base_buffer)) :\n fmt::ArgList(types, reinterpret_cast<const fmt::internal::Value*>(base_buffer));\n}\n\n} \/\/ namespace Internals\n\/\/! @endcond\n\ninline Record::Record()\n : timestamp(CppCommon::Timestamp::utc()),\n thread(CppCommon::Thread::CurrentThreadId()),\n level(Level::INFO)\n{\n logger.reserve(32);\n message.reserve(512);\n buffer.reserve(1024);\n format.reserve(128);\n raw.reserve(512);\n}\n\ntemplate <typename... Args>\ninline void Record::FormatSerialize(const char* pattern, const Args&... args)\n{\n \/\/ Save the format pattern\n message = pattern;\n\n \/\/ Serialize arguments list\n Internals::Serialize<char>(format, args...);\n}\n\ninline void Record::FormatDeserialize()\n{\n \/\/ Special check for empty format arguments list\n if (format.empty())\n return;\n\n \/\/ Format the message filed of the logging record\n fmt::ArgList args = Internals::Deserialize<char>(format);\n message = fmt::format(message.c_str(), args);\n\n \/\/ Clear format buffer\n format.clear();\n}\n\ninline void Record::Clear()\n{\n timestamp = 0;\n thread = 0;\n level = Level::NONE;\n logger.clear();\n message.clear();\n buffer.clear();\n format.clear();\n raw.clear();\n}\n\ninline void Record::swap(Record& record) noexcept\n{\n using std::swap;\n swap(timestamp, record.timestamp);\n swap(thread, record.thread);\n swap(level, record.level);\n swap(logger, record.logger);\n swap(message, record.message);\n swap(buffer, record.buffer);\n swap(format, record.format);\n swap(raw, record.raw);\n}\n\ninline void swap(Record& record1, Record& record2) noexcept\n{\n record1.swap(record2);\n}\n\n} \/\/ namespace CppLogging\n<commit_msg>build<commit_after>\/*!\n \\file record.inl\n \\brief Logging record inline implementation\n \\author Ivan Shynkarenka\n \\date 08.07.2016\n \\copyright MIT License\n*\/\n\nnamespace CppLogging {\n\n\/\/! @cond INTERNALS\nnamespace Internals {\n\ntemplate <typename Char, typename T>\nstd::size_t CalculateExtraSize(const fmt::internal::Arg& arg)\n{\n std::size_t result = 0;\n\n if (arg.type == fmt::internal::Arg::CSTRING)\n result = sizeof(std::size_t) + (std::strlen(arg.string.value) + 1) * sizeof(char);\n else if (arg.type == fmt::internal::Arg::STRING)\n result = sizeof(std::size_t) + arg.string.size * sizeof(char);\n else if (arg.type == fmt::internal::Arg::WSTRING)\n result = sizeof(std::size_t) + arg.wstring.size * sizeof(wchar_t);\n else if (arg.type == fmt::internal::Arg::CUSTOM)\n result = sizeof(T);\n\n return result;\n}\n\ntemplate <typename Char>\nunsigned CalculateBufferSize(std::size_t&)\n{\n return 0;\n}\n\ntemplate <typename Char, typename T>\nunsigned CalculateBufferSize(std::size_t& extra_size, const T& argument)\n{\n fmt::internal::MakeArg<fmt::BasicFormatter<Char>> arg(argument);\n extra_size += CalculateExtraSize<Char, T>(arg);\n return 1;\n}\n\ntemplate <typename Char, typename T>\nunsigned CalculateBufferSize(std::size_t& extra_size, const fmt::internal::NamedArgWithType<Char, T>& argument)\n{\n extra_size += sizeof(fmt::internal::NamedArgWithType<Char, T>) + sizeof(std::size_t) + argument.name.size() * sizeof(Char) + CalculateExtraSize<Char, fmt::internal::NamedArgWithType<Char, T>>(argument);\n return 1;\n}\n\ntemplate <typename Char, typename T, typename... Args>\nunsigned CalculateBufferSize(std::size_t& extra_size, const T& argument, const Args&... args)\n{\n unsigned count = 0;\n count += CalculateBufferSize<Char>(extra_size, argument);\n count += CalculateBufferSize<Char>(extra_size, args...);\n return count;\n}\n\ntemplate <typename Char, typename T>\nvoid SerializeExtraData(uint8_t*& data_buffer, fmt::internal::Arg::Type type, const fmt::internal::Value& value)\n{\n \/\/ Serialize extra data\n if (type == fmt::internal::Arg::CSTRING)\n {\n std::size_t size = (std::strlen(value.string.value) + 1) * sizeof(char);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, value.string.value, size);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::STRING)\n {\n std::size_t size = value.string.size * sizeof(char);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, value.string.value, size);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::WSTRING)\n {\n std::size_t size = value.wstring.size * sizeof(wchar_t);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, value.wstring.value, size);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::CUSTOM)\n {\n std::size_t size = sizeof(T);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, value.custom.value, size);\n data_buffer += size;\n }\n}\n\ntemplate <typename Char, typename T>\nvoid SerializeExtraData(uint8_t*& data_buffer, const fmt::internal::NamedArgWithType<Char, T>& named)\n{\n std::memcpy(data_buffer, &named, sizeof(fmt::internal::NamedArgWithType<Char, T>));\n data_buffer += sizeof(fmt::internal::NamedArgWithType<Char, T>);\n std::size_t size = named.name.size() * sizeof(Char);\n std::memcpy(data_buffer, &size, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n std::memcpy(data_buffer, named.name.data(), size);\n data_buffer += size;\n SerializeExtraData<Char, T>(data_buffer, named.type, named);\n}\n\ntemplate <typename Char>\nvoid SerializeArguments(std::size_t, uint8_t*&, uint8_t*&)\n{\n}\n\ntemplate <typename Char, typename T>\nvoid SerializeArguments(std::size_t item_size, uint8_t*& base_buffer, uint8_t*& data_buffer, const T& argument)\n{\n \/\/ Serialize argument\n fmt::internal::MakeArg<fmt::BasicFormatter<Char>> arg(argument);\n std::memcpy(base_buffer, &arg, item_size);\n base_buffer += item_size;\n \/\/ Serialize extra data\n SerializeExtraData<Char, T>(data_buffer, arg.type, arg);\n}\n\ntemplate <typename Char, typename T>\nvoid SerializeArguments(std::size_t item_size, uint8_t*& base_buffer, uint8_t*& data_buffer, const fmt::internal::NamedArgWithType<Char, T>& argument)\n{\n \/\/ Serialize argument\n const fmt::internal::Arg& arg = argument;\n std::memcpy(base_buffer, &arg, item_size);\n base_buffer += item_size;\n \/\/ Serialize extra data\n SerializeExtraData<Char, T>(data_buffer, argument);\n}\n\ntemplate <typename Char, typename T, typename... Args>\nvoid SerializeArguments(std::size_t item_size, uint8_t*& base_buffer, uint8_t*& data_buffer, const T& argument, const Args&... args)\n{\n SerializeArguments<Char>(item_size, base_buffer, data_buffer, argument);\n SerializeArguments<Char>(item_size, base_buffer, data_buffer, args...);\n}\n\ntemplate <typename Char, typename... Args>\nvoid Serialize(std::vector<uint8_t>& buffer, const Args&... args)\n{\n std::size_t extra_size = 0;\n unsigned count = CalculateBufferSize<Char>(extra_size, args...);\n\n \/\/ Special check for none format arguments\n if (count == 0)\n return;\n\n \/\/ Caclulate base & full buffer sizes\n std::size_t item_size = (count > fmt::ArgList::MAX_PACKED_ARGS) ? sizeof(fmt::internal::Arg) : sizeof(fmt::internal::Value);\n std::size_t base_size = sizeof(unsigned) + sizeof(std::size_t) + sizeof(fmt::ULongLong) + count * item_size;\n std::size_t full_size = base_size + extra_size;\n\n \/\/ Resize buffer to fit all format arguments\n buffer.resize(full_size);\n\n uint8_t* base_buffer = buffer.data();\n uint8_t* data_buffer = base_buffer + base_size;\n\n \/\/ Serialize the count of format arguments\n std::memcpy(base_buffer, &count, sizeof(unsigned));\n base_buffer += sizeof(unsigned);\n\n \/\/ Serialize the base buffer size\n std::memcpy(base_buffer, &base_size, sizeof(std::size_t));\n base_buffer += sizeof(std::size_t);\n\n \/\/ Serialize types of format arguments\n fmt::ULongLong types = fmt::internal::make_type(args...);\n std::memcpy(base_buffer, &types, sizeof(fmt::ULongLong));\n base_buffer += sizeof(fmt::ULongLong);\n\n \/\/ Serialize values of format arguments\n SerializeArguments<Char>(item_size, base_buffer, data_buffer, args...);\n}\n\ntemplate <typename Char>\nvoid DeserializeExtraData(uint8_t*& data_buffer, fmt::internal::Arg::Type type, fmt::internal::Value& value)\n{\n \/\/ Deserialize extra data\n if (type == fmt::internal::Arg::NAMED_ARG)\n {\n fmt::internal::NamedArg<Char>* named = (fmt::internal::NamedArg<Char>*)data_buffer;\n value.pointer = named;\n data_buffer += sizeof(fmt::internal::NamedArg<Char>);\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n named->name = fmt::BasicStringRef<Char>((const Char*)data_buffer, size);\n data_buffer += size;\n DeserializeExtraData<Char>(data_buffer, named->type, *named);\n }\n else if (type == fmt::internal::Arg::CSTRING)\n {\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n value.string.value = (const char*)data_buffer;\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::STRING)\n {\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n value.string.value = (const char*)data_buffer;\n value.string.size = size \/ sizeof(char);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::WSTRING)\n {\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n value.wstring.value = (const wchar_t*)data_buffer;\n value.wstring.size = size \/ sizeof(wchar_t);\n data_buffer += size;\n }\n else if (type == fmt::internal::Arg::CUSTOM)\n {\n std::size_t size;\n std::memcpy(&size, data_buffer, sizeof(std::size_t));\n data_buffer += sizeof(std::size_t);\n value.custom.value = data_buffer;\n data_buffer += size;\n }\n}\n\ntemplate <typename Char>\nfmt::ArgList Deserialize(std::vector<uint8_t>& buffer)\n{\n \/\/ Special check for empty format arguments list\n if (buffer.empty())\n return fmt::ArgList();\n\n uint8_t* base_buffer = buffer.data();\n uint8_t* data_buffer = base_buffer;\n\n \/\/ Deserialize the count of format arguments\n unsigned count;\n std::memcpy(&count, base_buffer, sizeof(unsigned));\n base_buffer += sizeof(unsigned);\n\n \/\/ Deserialize the base buffer size\n std::size_t base_size;\n std::memcpy(&base_size, base_buffer, sizeof(std::size_t));\n base_buffer += sizeof(std::size_t);\n\n \/\/ Update the data buffer offset\n data_buffer += base_size;\n\n \/\/ Deserialize types of format arguments\n fmt::ULongLong types;\n std::memcpy(&types, base_buffer, sizeof(fmt::ULongLong));\n base_buffer += sizeof(fmt::ULongLong);\n\n \/\/ Calculate the item size\n std::size_t item_size = (count > fmt::ArgList::MAX_PACKED_ARGS) ? sizeof(fmt::internal::Arg) : sizeof(fmt::internal::Value);\n\n \/\/ Deserialize values of format arguments\n uint8_t* local_buffer = base_buffer;\n for (unsigned i = 0; i < count; ++i)\n {\n \/\/ Deserialize argument\n fmt::internal::Value* value = (fmt::internal::Value*)local_buffer;\n local_buffer += item_size;\n \/\/ Deserialize extra data\n DeserializeExtraData<Char>(data_buffer, fmt::ArgList::type(types, i), *value);\n }\n\n \/\/ Prepare and return arguments list stored in the provided buffer\n return (count > fmt::ArgList::MAX_PACKED_ARGS) ?\n fmt::ArgList(types, (const fmt::internal::Arg*)base_buffer) :\n fmt::ArgList(types, (const fmt::internal::Value*)base_buffer);\n}\n\n} \/\/ namespace Internals\n\/\/! @endcond\n\ninline Record::Record()\n : timestamp(CppCommon::Timestamp::utc()),\n thread(CppCommon::Thread::CurrentThreadId()),\n level(Level::INFO)\n{\n logger.reserve(32);\n message.reserve(512);\n buffer.reserve(1024);\n format.reserve(128);\n raw.reserve(512);\n}\n\ntemplate <typename... Args>\ninline void Record::FormatSerialize(const char* pattern, const Args&... args)\n{\n \/\/ Save the format pattern\n message = pattern;\n\n \/\/ Serialize arguments list\n Internals::Serialize<char>(format, args...);\n}\n\ninline void Record::FormatDeserialize()\n{\n \/\/ Special check for empty format arguments list\n if (format.empty())\n return;\n\n \/\/ Format the message filed of the logging record\n fmt::ArgList args = Internals::Deserialize<char>(format);\n message = fmt::format(message.c_str(), args);\n\n \/\/ Clear format buffer\n format.clear();\n}\n\ninline void Record::Clear()\n{\n timestamp = 0;\n thread = 0;\n level = Level::NONE;\n logger.clear();\n message.clear();\n buffer.clear();\n format.clear();\n raw.clear();\n}\n\ninline void Record::swap(Record& record) noexcept\n{\n using std::swap;\n swap(timestamp, record.timestamp);\n swap(thread, record.thread);\n swap(level, record.level);\n swap(logger, record.logger);\n swap(message, record.message);\n swap(buffer, record.buffer);\n swap(format, record.format);\n swap(raw, record.raw);\n}\n\ninline void swap(Record& record1, Record& record2) noexcept\n{\n record1.swap(record2);\n}\n\n} \/\/ namespace CppLogging\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: feature.hpp 40 2005-04-13 20:20:46Z pavlenko $\n\n#ifndef FEATURE_HPP\n#define FEATURE_HPP\n\/\/ mapnik\n#include <mapnik\/value.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/raster.hpp>\n\/\/ boost\n#include <boost\/property_map.hpp>\n#include <boost\/utility.hpp>\n#include <boost\/shared_ptr.hpp>\n\/\/ stl\n#include <map>\n\nnamespace mapnik {\n typedef boost::shared_ptr<raster> raster_ptr; \n typedef boost::associative_property_map<\n std::map<std::string,value\n > > properties;\n \n template <typename T1,typename T2>\n struct feature : public properties,\n private boost::noncopyable\n {\n public:\n typedef T1 geometry_type;\n typedef T2 raster_type;\n typedef std::map<std::string,value>::value_type value_type;\n typedef std::map<std::string,value>::size_type size_type;\n \n private:\n int id_;\n boost::ptr_vector<geometry_type> geom_cont_;\n raster_type raster_;\n std::map<std::string,value> props_;\n public:\n typedef std::map<std::string,value>::iterator iterator;\n explicit feature(int id)\n : properties(props_),\n id_(id),\n geom_cont_(),\n raster_() {}\n \n \/\/feature(int id,const geometry_type& geom)\n \/\/ : properties(props_),\n \/\/ id_(id),\n \/\/ geom_(geom),\n \/\/ raster_() {}\n \n int id() const \n {\n return id_;\n }\n \n void add_geometry(geometry_type * geom)\n {\n geom_cont_.push_back(geom);\n }\n \n unsigned num_geometries() const\n {\n return geom_cont_.size();\n }\n \n geometry_type const& get_geometry(unsigned index) const\n {\n return geom_cont_[index];\n }\n \n geometry_type& get_geometry(unsigned index)\n {\n return geom_cont_[index];\n }\n\n Envelope<double> envelope() const\n {\n Envelope<double> result;\n for (unsigned i=0;i<num_geometries();++i)\n {\n geometry2d const& geom = get_geometry(i);\n if (i==0)\n {\n Envelope<double> box = geom.envelope();\n result.init(box.minx(),box.miny(),box.maxx(),box.maxy());\n }\n else\n {\n result.expand_to_include(geom.envelope());\n }\n }\n return result;\n }\n\n const raster_type& get_raster() const\n {\n return raster_;\n }\n \n void set_raster(raster_type const& raster)\n {\n raster_=raster;\n }\n \n std::map<std::string,value> const& props() const \n {\n return props_;\n }\n \n iterator begin() const\n {\n return props_.begin();\n }\n \n iterator end() const\n {\n return props_.end();\n }\n \n std::string to_string() const\n {\n std::stringstream ss;\n ss << \"feature (\" << std::endl;\n for (std::map<std::string,value>::const_iterator itr=props_.begin();\n itr != props_.end();++itr)\n {\n ss << \" \" << itr->first << \":\" << itr->second << std::endl;\n }\n ss << \")\" << std::endl;\n return ss.str();\n }\n };\n \n typedef feature<geometry2d,raster_ptr> Feature;\n \n inline std::ostream& operator<< (std::ostream & out,Feature const& f)\n {\n out << f.to_string();\n return out;\n }\n}\n\n#endif \/\/FEATURE_HPP\n<commit_msg>avoid deprecation warnings with boost 1_40 related to location of property_map.hpp<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: feature.hpp 40 2005-04-13 20:20:46Z pavlenko $\n\n#ifndef FEATURE_HPP\n#define FEATURE_HPP\n\/\/ mapnik\n#include <mapnik\/value.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/raster.hpp>\n\n\/\/ boost\n#include <boost\/version.hpp>\n#if BOOST_VERSION >= 104000\n#include <boost\/property_map\/property_map.hpp>\n#else\n#include <boost\/property_map.hpp>\n#endif\n\n#include <boost\/utility.hpp>\n#include <boost\/shared_ptr.hpp>\n\/\/ stl\n#include <map>\n\nnamespace mapnik {\n typedef boost::shared_ptr<raster> raster_ptr; \n typedef boost::associative_property_map<\n std::map<std::string,value\n > > properties;\n \n template <typename T1,typename T2>\n struct feature : public properties,\n private boost::noncopyable\n {\n public:\n typedef T1 geometry_type;\n typedef T2 raster_type;\n typedef std::map<std::string,value>::value_type value_type;\n typedef std::map<std::string,value>::size_type size_type;\n \n private:\n int id_;\n boost::ptr_vector<geometry_type> geom_cont_;\n raster_type raster_;\n std::map<std::string,value> props_;\n public:\n typedef std::map<std::string,value>::iterator iterator;\n explicit feature(int id)\n : properties(props_),\n id_(id),\n geom_cont_(),\n raster_() {}\n \n \/\/feature(int id,const geometry_type& geom)\n \/\/ : properties(props_),\n \/\/ id_(id),\n \/\/ geom_(geom),\n \/\/ raster_() {}\n \n int id() const \n {\n return id_;\n }\n \n void add_geometry(geometry_type * geom)\n {\n geom_cont_.push_back(geom);\n }\n \n unsigned num_geometries() const\n {\n return geom_cont_.size();\n }\n \n geometry_type const& get_geometry(unsigned index) const\n {\n return geom_cont_[index];\n }\n \n geometry_type& get_geometry(unsigned index)\n {\n return geom_cont_[index];\n }\n\n Envelope<double> envelope() const\n {\n Envelope<double> result;\n for (unsigned i=0;i<num_geometries();++i)\n {\n geometry2d const& geom = get_geometry(i);\n if (i==0)\n {\n Envelope<double> box = geom.envelope();\n result.init(box.minx(),box.miny(),box.maxx(),box.maxy());\n }\n else\n {\n result.expand_to_include(geom.envelope());\n }\n }\n return result;\n }\n\n const raster_type& get_raster() const\n {\n return raster_;\n }\n \n void set_raster(raster_type const& raster)\n {\n raster_=raster;\n }\n \n std::map<std::string,value> const& props() const \n {\n return props_;\n }\n \n iterator begin() const\n {\n return props_.begin();\n }\n \n iterator end() const\n {\n return props_.end();\n }\n \n std::string to_string() const\n {\n std::stringstream ss;\n ss << \"feature (\" << std::endl;\n for (std::map<std::string,value>::const_iterator itr=props_.begin();\n itr != props_.end();++itr)\n {\n ss << \" \" << itr->first << \":\" << itr->second << std::endl;\n }\n ss << \")\" << std::endl;\n return ss.str();\n }\n };\n \n typedef feature<geometry2d,raster_ptr> Feature;\n \n inline std::ostream& operator<< (std::ostream & out,Feature const& f)\n {\n out << f.to_string();\n return out;\n }\n}\n\n#endif \/\/FEATURE_HPP\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <glm\/glm.hpp>\n#include <array>\n#include <map>\n\nnamespace mos {\nnamespace gfx {\n\n\/** Rendering camera view. *\/\nclass Camera final {\npublic:\n Camera();\n Camera(const glm::vec3 &position,\n const glm::vec3 ¢er,\n const glm::mat4 &projection,\n const glm::vec3 &up = glm::vec3(0.0f, 0.0f, 1.0f));\n ~Camera() = default;\n\n glm::vec3 up() const;\n\n \/** Set up vector. *\/\n void up(const glm::vec3 &up);\n\n glm::vec3 position() const;\n\n \/** Set position. *\/\n void position(const glm::vec3 &position);\n\n glm::vec3 center() const;\n\n \/** Set center\/focus point. *\/\n void center(const glm::vec3 ¢er);\n\n glm::vec3 direction() const;\n\n \/** Set direction. *\/\n void direction(const glm::vec3 &direction);\n\n float aspect_ratio() const;\n\n bool in_frustum(const glm::vec3 & point, const float radius) const;\n\n glm::mat4 projection;\n glm::mat4 view;\n\nprivate:\n void calculate_view();\n void calculate_frustum();\n std::array<glm::vec4, 6> frustum_planes_;\n glm::vec3 up_;\n glm::vec3 center_;\n glm::vec3 position_;\n};\n}\n}<commit_msg>check<commit_after>#pragma once\n\n#include <glm\/glm.hpp>\n#include <array>\n#include <map>\n\nnamespace mos {\nnamespace gfx {\n\n\/** Rendering camera view. *\/\nclass Camera final {\npublic:\n Camera(const glm::vec3 &position = glm::vec3(0.0f),\n const glm::vec3 ¢er = glm::vec3(0.0f),\n const glm::mat4 &projection = glm::mat4(1.0f),\n const glm::vec3 &up = glm::vec3(0.0f, 0.0f, 1.0f));\n ~Camera() = default;\n\n glm::vec3 up() const;\n\n \/** Set up vector. *\/\n void up(const glm::vec3 &up);\n\n glm::vec3 position() const;\n\n \/** Set position. *\/\n void position(const glm::vec3 &position);\n\n glm::vec3 center() const;\n\n \/** Set center\/focus point. *\/\n void center(const glm::vec3 ¢er);\n\n glm::vec3 direction() const;\n\n \/** Set direction. *\/\n void direction(const glm::vec3 &direction);\n\n float aspect_ratio() const;\n\n bool in_frustum(const glm::vec3 & point, const float radius) const;\n\n glm::mat4 projection;\n glm::mat4 view;\n\nprivate:\n void calculate_view();\n void calculate_frustum();\n std::array<glm::vec4, 6> frustum_planes_;\n glm::vec3 up_;\n glm::vec3 center_;\n glm::vec3 position_;\n};\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef LIBTEN_SHARED_POOL_HH\n#define LIBTEN_SHARED_POOL_HH\n\n#include \"task\/rendez.hh\"\n#include \"ten\/logging.hh\"\n#include \"ten\/optional.hh\"\n\n#include <deque>\n#include <unordered_set>\n#include <unordered_map>\n#include <memory>\n#include <chrono>\n#include <type_traits>\n\nnamespace ten {\n\nnamespace detail {\ntemplate <typename T> class scoped_resource;\n}\n\n\/\/! thread and task safe pool of shared resources\n\/\/! useful for connection pools and other types of shared resources\ntemplate <typename ResourceT, typename ScopeT = detail::scoped_resource<ResourceT>>\nclass shared_pool {\n friend class detail::scoped_resource<ResourceT>;\n\npublic:\n using resource_type = ResourceT;\n using scoped_resource = ScopeT; \/\/ use this type to RAII resources from the pool\n\nprotected:\n using res_ptr = std::shared_ptr<resource_type>;\n using creator_type = std::function<res_ptr ()>;\n\n struct pool_impl {\n using queue_type = std::deque<res_ptr>;\n using set_type = std::unordered_set<res_ptr>;\n\n qutex mut;\n rendez not_empty;\n queue_type avail;\n set_type set;\n std::string name;\n creator_type new_resource;\n optional<size_t> max_resources;\n\n size_t size() const {\n std::lock_guard<qutex> lk(mut);\n return set.size();\n }\n\n bool has_avail() const {\n std::lock_guard<qutex> lk(mut);\n return !avail.empty();\n }\n\n void clear() {\n std::lock_guard<qutex> lk(mut);\n avail.clear();\n set.clear();\n }\n\n res_ptr acquire() {\n std::unique_lock<qutex> lk(mut);\n while (avail.empty()) {\n if (!max_resources || set.size() < *max_resources) {\n \/\/ need to create a new resource\n return new_with_lock(lk);\n }\n \/\/ can't create anymore we're at max, try waiting\n \/\/ we don't use a predicate here because\n \/\/ we might be woken up from destroy()\n \/\/ in which case we might not be at max anymore\n not_empty.sleep(lk);\n }\n\n CHECK(!avail.empty());\n \/\/ pop resource from front of queue\n res_ptr c{std::move(avail.front())};\n avail.pop_front();\n CHECK(c) << \"acquire shared resource failed in pool: \" << name;\n return c;\n }\n\n res_ptr new_with_lock(std::unique_lock<qutex> &lk) {\n if (lk)\n lk.unlock(); \/\/ unlock while newing resource\n res_ptr c;\n try {\n c = new_resource();\n } catch (std::exception &e) {\n LOG(ERROR) << \"exception creating new resource for pool: \" << name << \" \" << e.what();\n throw;\n }\n CHECK(c) << \"new_resource failed for pool: \" << name;\n DVLOG(4) << \"inserting to shared_pool(\" << name << \"): \" << c;\n lk.lock(); \/\/ re-lock before inserting to set\n set.insert(c);\n return c;\n }\n\n void destroy(res_ptr &c) { discard(c, false); }\n void release(res_ptr &c) { discard(c, true); }\n\n void discard(res_ptr &c, bool can_keep) {\n if (!c)\n return;\n\n std::unique_lock<qutex> lk(mut);\n\n if (!can_keep)\n set.erase(c);\n else if (!set.count(c))\n can_keep = false; \/\/ it must have exceeded lifetime\n\n const auto i = std::find(begin(avail), end(avail), c);\n if (i != end(avail)) \/\/ should never happen\n avail.erase(i);\n if (can_keep)\n avail.push_front(c);\n\n \/\/ give waiting threads a chance to reuse or create resource\n not_empty.wakeup();\n lk.unlock();\n\n c.reset();\n if (!can_keep)\n LOG(WARNING) << \"destroyed shared resource from pool \" << name;\n }\n };\n\n \/\/ this thread safety supports possible swapping of impl objects someday\n std::shared_ptr<pool_impl> _impl() const {\n std::lock_guard<std::mutex> lock(_im_mutex);\n return _im;\n }\n void _impl(std::shared_ptr<pool_impl> im) {\n std::lock_guard<std::mutex> lock(_im_mutex);\n _im = std::move(im);\n }\n\nprivate:\n std::shared_ptr<pool_impl> _im;\n mutable std::mutex _im_mutex;\n\npublic:\n shared_pool(const std::string &name_,\n const creator_type &alloc_,\n decltype((_im->max_resources)) max_ = {})\n {\n auto m = std::make_shared<pool_impl>();\n m->name = name_;\n m->new_resource = alloc_;\n m->max_resources = max_;\n _im = std::move(m);\n }\n\n \/\/! no copy\n shared_pool(const shared_pool &) = delete;\n shared_pool &operator =(const shared_pool &) = delete;\n\n \/\/! yes move\n shared_pool(shared_pool &&) = default;\n shared_pool &operator =(shared_pool &&) = default;\n\n \/\/! accessors\n const std::string &name() const { return _impl()->name; }\n size_t size() const { return _impl()->size(); }\n void clear() { _impl()->clear(); }\n};\n\nnamespace detail {\n\n\/\/ do not use this class directly, instead use your shared_pool<>::scoped_resource\ntemplate <typename T>\nclass scoped_resource {\nprotected:\n using pool_type = shared_pool<T>;\n using pool_ref = typename std::add_lvalue_reference<pool_type>::type;\n using pool_impl = typename pool_type::pool_impl;\n using res_ptr = typename pool_type::res_ptr;\n\n std::shared_ptr<pool_impl> _pm; \/\/ no mutex here <- no contention\n res_ptr _c;\n bool _success;\n\npublic:\n \/\/! RAII\n explicit scoped_resource(pool_ref p)\n : _pm{p._impl()},\n _c{_pm->acquire()},\n _success{}\n {}\n\n \/\/! do not copy\n scoped_resource(const scoped_resource &) = delete;\n scoped_resource & operator =(const scoped_resource &) = delete;\n\n \/\/! move is ok\n scoped_resource(scoped_resource &&) = default;\n scoped_resource & operator =(scoped_resource &&) = default;\n\n \/\/! must call done() to return the resource to the pool\n \/\/! otherwise we destroy it because a timeout or other exception\n \/\/! could have occured causing the resource state to be in transition\n ~scoped_resource() {\n _pm->discard(_c, _success);\n }\n\n \/\/! call this to allow resource reuse\n void done() {\n DCHECK(!_success);\n _success = true;\n }\n\n \/\/! access resource\n T *get() const {\n if (!_c) throw std::runtime_error(\"null pointer\");\n return _c.get();\n }\n T * operator -> () const { return get(); }\n T & operator * () const { return *get(); }\n};\n\n} \/\/ end detail namespace\n\n} \/\/ end namespace ten\n\n#endif \/\/ LIBTEN_SHARED_POOL_HH\n<commit_msg>tweak logging in shared_pool<commit_after>#ifndef LIBTEN_SHARED_POOL_HH\n#define LIBTEN_SHARED_POOL_HH\n\n#include \"task\/rendez.hh\"\n#include \"ten\/logging.hh\"\n#include \"ten\/optional.hh\"\n\n#include <deque>\n#include <unordered_set>\n#include <unordered_map>\n#include <memory>\n#include <chrono>\n#include <type_traits>\n\nnamespace ten {\n\nnamespace detail {\ntemplate <typename T> class scoped_resource;\n}\n\n\/\/! thread and task safe pool of shared resources\n\/\/! useful for connection pools and other types of shared resources\ntemplate <typename ResourceT, typename ScopeT = detail::scoped_resource<ResourceT>>\nclass shared_pool {\n friend class detail::scoped_resource<ResourceT>;\n\npublic:\n using resource_type = ResourceT;\n using scoped_resource = ScopeT; \/\/ use this type to RAII resources from the pool\n\nprotected:\n using res_ptr = std::shared_ptr<resource_type>;\n using creator_type = std::function<res_ptr ()>;\n\n struct pool_impl {\n using queue_type = std::deque<res_ptr>;\n using set_type = std::unordered_set<res_ptr>;\n\n qutex mut;\n rendez not_empty;\n queue_type avail;\n set_type set;\n std::string name;\n creator_type new_resource;\n optional<size_t> max_resources;\n\n size_t size() const {\n std::lock_guard<qutex> lk(mut);\n return set.size();\n }\n\n bool has_avail() const {\n std::lock_guard<qutex> lk(mut);\n return !avail.empty();\n }\n\n void clear() {\n std::lock_guard<qutex> lk(mut);\n avail.clear();\n set.clear();\n }\n\n res_ptr acquire() {\n std::unique_lock<qutex> lk(mut);\n while (avail.empty()) {\n if (!max_resources || set.size() < *max_resources) {\n \/\/ need to create a new resource\n return new_with_lock(lk);\n }\n \/\/ can't create anymore we're at max, try waiting\n \/\/ we don't use a predicate here because\n \/\/ we might be woken up from destroy()\n \/\/ in which case we might not be at max anymore\n not_empty.sleep(lk);\n }\n\n CHECK(!avail.empty());\n \/\/ pop resource from front of queue\n res_ptr c{std::move(avail.front())};\n avail.pop_front();\n CHECK(c) << \"acquire shared resource failed in pool \" << name;\n return c;\n }\n\n res_ptr new_with_lock(std::unique_lock<qutex> &lk) {\n if (lk)\n lk.unlock(); \/\/ unlock while newing resource\n res_ptr c;\n try {\n c = new_resource();\n } catch (std::exception &e) {\n LOG(ERROR) << \"exception creating new resource for pool \" << name << \": \" << e.what();\n throw;\n }\n CHECK(c) << \"new_resource failed for pool \" << name;\n VLOG(3) << \"adding shared resource to pool \" << name << \": \" << c;\n lk.lock(); \/\/ re-lock before inserting to set\n set.insert(c);\n return c;\n }\n\n void destroy(res_ptr &c) { discard(c, false); }\n void release(res_ptr &c) { discard(c, true); }\n\n void discard(res_ptr &c, bool can_keep) {\n if (!c)\n return;\n\n std::unique_lock<qutex> lk(mut);\n\n if (!can_keep)\n set.erase(c);\n else if (!set.count(c))\n can_keep = false; \/\/ it must have exceeded lifetime\n\n const auto i = std::find(begin(avail), end(avail), c);\n if (i != end(avail)) \/\/ should never happen\n avail.erase(i);\n if (can_keep)\n avail.push_front(c);\n\n \/\/ give waiting threads a chance to reuse or create resource\n not_empty.wakeup();\n lk.unlock();\n\n const void * const addr = c.get();\n c.reset();\n if (!can_keep)\n VLOG(3) << \"destroyed shared resource from pool \" << name << \": \" << addr;\n }\n };\n\n \/\/ this thread safety supports possible swapping of impl objects someday\n std::shared_ptr<pool_impl> _impl() const {\n std::lock_guard<std::mutex> lock(_im_mutex);\n return _im;\n }\n void _impl(std::shared_ptr<pool_impl> im) {\n std::lock_guard<std::mutex> lock(_im_mutex);\n _im = std::move(im);\n }\n\nprivate:\n std::shared_ptr<pool_impl> _im;\n mutable std::mutex _im_mutex;\n\npublic:\n shared_pool(const std::string &name_,\n const creator_type &alloc_,\n decltype((_im->max_resources)) max_ = {})\n {\n auto m = std::make_shared<pool_impl>();\n m->name = name_;\n m->new_resource = alloc_;\n m->max_resources = max_;\n _im = std::move(m);\n }\n\n \/\/! no copy\n shared_pool(const shared_pool &) = delete;\n shared_pool &operator =(const shared_pool &) = delete;\n\n \/\/! yes move\n shared_pool(shared_pool &&) = default;\n shared_pool &operator =(shared_pool &&) = default;\n\n \/\/! accessors\n const std::string &name() const { return _impl()->name; }\n size_t size() const { return _impl()->size(); }\n void clear() { _impl()->clear(); }\n};\n\nnamespace detail {\n\n\/\/ do not use this class directly, instead use your shared_pool<>::scoped_resource\ntemplate <typename T>\nclass scoped_resource {\nprotected:\n using pool_type = shared_pool<T>;\n using pool_ref = typename std::add_lvalue_reference<pool_type>::type;\n using pool_impl = typename pool_type::pool_impl;\n using res_ptr = typename pool_type::res_ptr;\n\n std::shared_ptr<pool_impl> _pm; \/\/ no mutex here <- no contention\n res_ptr _c;\n bool _success;\n\npublic:\n \/\/! RAII\n explicit scoped_resource(pool_ref p)\n : _pm{p._impl()},\n _c{_pm->acquire()},\n _success{}\n {}\n\n \/\/! do not copy\n scoped_resource(const scoped_resource &) = delete;\n scoped_resource & operator =(const scoped_resource &) = delete;\n\n \/\/! move is ok\n scoped_resource(scoped_resource &&) = default;\n scoped_resource & operator =(scoped_resource &&) = default;\n\n \/\/! must call done() to return the resource to the pool\n \/\/! otherwise we destroy it because a timeout or other exception\n \/\/! could have occured causing the resource state to be in transition\n ~scoped_resource() {\n _pm->discard(_c, _success);\n }\n\n \/\/! call this to allow resource reuse\n void done() {\n DCHECK(!_success);\n _success = true;\n }\n\n \/\/! access resource\n T *get() const {\n if (!_c) throw std::runtime_error(\"null pointer\");\n return _c.get();\n }\n T * operator -> () const { return get(); }\n T & operator * () const { return *get(); }\n};\n\n} \/\/ end detail namespace\n\n} \/\/ end namespace ten\n\n#endif \/\/ LIBTEN_SHARED_POOL_HH\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *\n* *\n* Distributed under the terms of the BSD 3-Clause License. *\n* *\n* The full license is in the file LICENSE, distributed with this software. *\n****************************************************************************\/\n\n#ifndef XARRAY_HPP\n#define XARRAY_HPP\n\n#include <initializer_list>\n#include <utility>\n#include <vector>\n#include <algorithm>\n\n#include \"xcontainer.hpp\"\n#include \"xsemantic.hpp\"\n\nnamespace xt\n{\n\n \/**********************\n * xarray declaration *\n **********************\/\n\n template <class T>\n class xarray;\n\n template <class T>\n struct xcontainer_inner_types<xarray<T>>\n {\n using container_type = std::vector<T>;\n using shape_type = std::vector<typename container_type::size_type>;\n using strides_type = shape_type;\n using temporary_type = xarray<T>;\n };\n\n \/**\n * @class xarray\n * @brief Dense multidimensional container with tensor\n * semantic.\n *\n * The xarray class implements a dense multidimensional container\n * with tensor semantic.\n *\n * @tparam T The type of objects stored in the container.\n *\/\n template <class T>\n class xarray : public xcontainer<xarray<T>>,\n public xcontainer_semantic<xarray<T>>\n {\n\n public:\n\n using self_type = xarray<T>;\n using base_type = xcontainer<self_type>;\n using semantic_base = xcontainer_semantic<self_type>;\n using container_type = typename base_type::container_type;\n using value_type = typename base_type::value_type;\n using reference = typename base_type::reference;\n using const_reference = typename base_type::const_reference;\n using pointer = typename base_type::pointer;\n using const_pointer = typename base_type::const_pointer;\n using shape_type = typename base_type::shape_type;\n using strides_type = typename base_type::strides_type;\n\n using closure_type = const self_type&;\n\n xarray();\n explicit xarray(const shape_type& shape, layout l = layout::row_major);\n explicit xarray(const shape_type& shape, const_reference value, layout l = layout::row_major);\n explicit xarray(const shape_type& shape, const strides_type& strides);\n explicit xarray(const shape_type& shape, const strides_type& strides, const_reference value);\n\n xarray(const value_type& t);\n xarray(std::initializer_list<T> t);\n xarray(std::initializer_list<std::initializer_list<T>> t);\n xarray(std::initializer_list<std::initializer_list<std::initializer_list<T>>> t);\n xarray(std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<T>>>> t);\n xarray(std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<T>>>>> t);\n\n ~xarray() = default;\n\n xarray(const xarray&) = default;\n xarray& operator=(const xarray&) = default;\n\n xarray(xarray&&) = default;\n xarray& operator=(xarray&&) = default;\n\n template <class E>\n xarray(const xexpression<E>& e);\n\n template <class E>\n xarray& operator=(const xexpression<E>& e);\n\n private:\n\n container_type m_data;\n\n container_type& data_impl() noexcept;\n const container_type& data_impl() const noexcept;\n\n friend class xcontainer<xarray<T>>;\n };\n\n \/******************************\n * xarray_adaptor declaration *\n ******************************\/\n\n template <class C>\n class xarray_adaptor;\n\n template <class C>\n struct xcontainer_inner_types<xarray_adaptor<C>>\n {\n using container_type = C;\n using shape_type = std::vector<typename container_type::size_type>;\n using strides_type = shape_type;\n using temporary_type = xarray<typename C::value_type>;\n };\n\n \/**\n * @class xarray_adaptor\n * @brief Dense multidimensional container adaptor with\n * tensor semantic.\n *\n * The xarray_adaptor class implements a dense multidimensional\n * container adaptor with tensor semantic. It is used to provide\n * a multidimensional container semantic and a tensor semantic to\n * stl-like containers.\n *\n * @tparam C The container type to adapt.\n *\/\n template <class C>\n class xarray_adaptor : public xcontainer<xarray_adaptor<C>>,\n public xadaptor_semantic<xarray_adaptor<C>>\n {\n\n public:\n\n using self_type = xarray_adaptor<C>;\n using base_type = xcontainer<self_type>;\n using semantic_base = xadaptor_semantic<self_type>;\n using container_type = typename base_type::container_type;\n using shape_type = typename base_type::shape_type;\n using strides_type = typename base_type::strides_type;\n\n using closure_type = const self_type&;\n\n xarray_adaptor(container_type& data);\n xarray_adaptor(container_type& data, const shape_type& shape, layout l = layout::row_major);\n xarray_adaptor(container_type& data, const shape_type& shape, const strides_type& strides);\n\n ~xarray_adaptor() = default;\n\n xarray_adaptor(const xarray_adaptor&) = default;\n xarray_adaptor& operator=(const xarray_adaptor&);\n\n xarray_adaptor(xarray_adaptor&&) = default;\n xarray_adaptor& operator=(xarray_adaptor&&);\n\n template <class E>\n xarray_adaptor& operator=(const xexpression<E>& e);\n\n private:\n\n container_type& m_data;\n\n container_type& data_impl() noexcept;\n const container_type& data_impl() const noexcept;\n\n using temporary_type = typename xcontainer_inner_types<self_type>::temporary_type;\n void assign_temporary_impl(temporary_type& tmp);\n\n friend class xcontainer<xarray_adaptor<C>>;\n friend class xadaptor_semantic<xarray_adaptor<C>>;\n };\n\n \/*************************\n * xarray implementation *\n *************************\/\n\n \/**\n * @name Constructors\n *\/\n \/\/@{\n \/**\n * Allocates an uninitialized xarray that holds 0 element.\n *\/\n template <class T>\n inline xarray<T>::xarray()\n : base_type(), m_data(1, value_type())\n {\n }\n\n \/**\n * Allocates an uninitialized xarray with the specified shape and\n * layout.\n * @param shape the shape of the xarray\n * @param l the layout of the xarray\n *\/\n template <class T>\n inline xarray<T>::xarray(const shape_type& shape, layout l)\n : base_type()\n {\n base_type::reshape(shape, l);\n }\n\n \/**\n * Allocates an xarray with the specified shape and layout. Elements\n * are initialized to the specified value.\n * @param shape the shape of the xarray\n * @param value the value of the elements\n * @param l the layout of the xarray\n *\/\n template <class T>\n inline xarray<T>::xarray(const shape_type& shape, const_reference value, layout l)\n : base_type()\n {\n base_type::reshape(shape, l);\n std::fill(m_data.begin(), m_data.end(), value);\n }\n\n \/**\n * Allocates an uninitialized xarray with the specified shape and strides.\n * @param shape the shape of the xarray\n * @param strides the strides of the xarray\n *\/\n template <class T>\n inline xarray<T>::xarray(const shape_type& shape, const strides_type& strides)\n : base_type()\n {\n base_type::reshape(shape, strides);\n }\n\n \/**\n * Allocates an uninitialized xarray with the specified shape and strides.\n * Elements are initialized to the specified value.\n * @param shape the shape of the xarray\n * @param strides the strides of the xarray\n * @param value the value of the elements\n *\/\n template <class T>\n inline xarray<T>::xarray(const shape_type& shape, const strides_type& strides, const_reference value)\n : base_type()\n {\n base_type::reshape(shape, strides);\n std::fill(m_data.begin(), m_data.end(), value);\n }\n\n \/**\n * Allocates an xarray that holds a single element initialized to the\n * specified value.\n * @param t the value of the element\n *\/\n template <class T>\n inline xarray<T>::xarray(const value_type& t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n \/\/@}\n\n \/**\n * @name Constructors from initializer list\n *\/\n \/\/@{\n \/**\n * Allocates a one-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T>\n inline xarray<T>::xarray(std::initializer_list<T> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n\n \/**\n * Allocates a two-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T>\n inline xarray<T>::xarray(std::initializer_list<std::initializer_list<T>> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n\n \/**\n * Allocates a three-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T>\n inline xarray<T>::xarray(std::initializer_list<std::initializer_list<std::initializer_list<T>>> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n\n \/**\n * Allocates a four-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T>\n inline xarray<T>::xarray(std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<T>>>> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n\n \/**\n * Allocates a five-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T>\n inline xarray<T>::xarray(std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<T>>>>> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n \/\/@}\n\n \/**\n * @name Extended copy semantic\n *\/\n \/\/@{\n \/**\n * The extended copy constructor.\n *\/\n template <class T>\n template <class E>\n inline xarray<T>::xarray(const xexpression<E>& e)\n : base_type()\n {\n semantic_base::assign(e);\n }\n\n \/**\n * The extended assignment operator.\n *\/\n template <class T>\n template <class E>\n inline auto xarray<T>::operator=(const xexpression<E>& e) -> self_type&\n {\n return semantic_base::operator=(e);\n }\n \/\/@}\n\n template <class T>\n inline auto xarray<T>::data_impl() noexcept -> container_type&\n {\n return m_data;\n }\n\n template <class T>\n inline auto xarray<T>::data_impl() const noexcept -> const container_type&\n {\n return m_data;\n }\n\n \/******************\n * xarray_adaptor *\n ******************\/\n\n \/**\n * @name Constructors\n *\/\n \/\/@{\n \/**\n * Constructs an xarray_adaptor of the given stl-like container.\n * @param data the container to adapt\n *\/\n template <class C>\n inline xarray_adaptor<C>::xarray_adaptor(container_type& data)\n : base_type(), m_data(data)\n {\n }\n\n \/**\n * Constructs an xarray_adaptor of the given stl-like container,\n * with the specified shape and layout.\n * @param data the container to adapt\n * @param shape the shape of the xarray_adaptor\n * @param l the layout of the xarray_adaptor\n *\/\n template <class C>\n inline xarray_adaptor<C>::xarray_adaptor(container_type& data, const shape_type& shape, layout l)\n : base_type(), m_data(data)\n {\n base_type::reshape(shape, l);\n }\n\n \/**\n * Constructs an xarray_adaptor of the given stl-like container,\n * with the specified shape and strides.\n * @param data the container to adapt\n * @param shape the shape of the xarray_adaptor\n * @param strides the strides of the xarray_adaptor\n *\/\n template <class C>\n inline xarray_adaptor<C>::xarray_adaptor(container_type& data, const shape_type& shape, const strides_type& strides)\n : base_type(), m_data(data)\n {\n base_type::reshape(shape, strides);\n }\n \/\/@}\n\n template <class C>\n inline xarray_adaptor<C>& xarray_adaptor<C>::operator=(const xarray_adaptor& rhs)\n {\n base_type::operator=(rhs);\n m_data = rhs.m_data;\n return *this;\n }\n\n template <class C>\n inline xarray_adaptor<C>& xarray_adaptor<C>::operator=(xarray_adaptor&& rhs)\n {\n base_type::operator=(std::move(rhs));\n m_data = rhs.m_data;\n return *this;\n }\n\n \/**\n * @name Extended copy semantic\n *\/\n \/\/@{\n \/**\n * The extended assignment operator.\n *\/\n template <class C>\n template <class E>\n inline auto xarray_adaptor<C>::operator=(const xexpression<E>& e) -> self_type&\n {\n return semantic_base::operator=(e);\n }\n \/\/@}\n\n template <class C>\n inline auto xarray_adaptor<C>::data_impl() noexcept -> container_type&\n {\n return m_data;\n }\n\n template <class C>\n inline auto xarray_adaptor<C>::data_impl() const noexcept -> const container_type&\n {\n return m_data;\n }\n\n template <class C>\n inline void xarray_adaptor<C>::assign_temporary_impl(temporary_type& tmp)\n {\n \/\/ TODO (performance improvement) : consider moving tmps\n \/\/ shape and strides\n base_type::get_shape() = tmp.shape();\n base_type::get_strides() = tmp.strides();\n base_type::get_backstrides() = tmp.backstrides();\n m_data.resize(tmp.size());\n std::copy(tmp.data().cbegin(), tmp.data().cend(), m_data.begin());\n }\n}\n\n#endif\n\n<commit_msg>support custom allocators for xarrays<commit_after>\/***************************************************************************\n* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *\n* *\n* Distributed under the terms of the BSD 3-Clause License. *\n* *\n* The full license is in the file LICENSE, distributed with this software. *\n****************************************************************************\/\n\n#ifndef XARRAY_HPP\n#define XARRAY_HPP\n\n#include <initializer_list>\n#include <utility>\n#include <vector>\n#include <algorithm>\n#include <memory>\n\n#include \"xcontainer.hpp\"\n#include \"xsemantic.hpp\"\n\nnamespace xt\n{\n\n \/**********************\n * xarray declaration *\n **********************\/\n\n template <class T, class EA = std::allocator<T>, class SA = std::allocator<typename std::vector<T, EA>::size_type>>\n class xarray;\n\n template <class T, class EA, class SA>\n struct xcontainer_inner_types<xarray<T, EA, SA>>\n {\n using container_type = std::vector<T, EA>;\n using shape_type = std::vector<typename container_type::size_type, SA>;\n using strides_type = shape_type;\n using temporary_type = xarray<T, EA, SA>;\n };\n\n \/**\n * @class xarray\n * @brief Dense multidimensional container with tensor\n * semantic.\n *\n * The xarray class implements a dense multidimensional container\n * with tensor semantic.\n *\n * @tparam T The type of objects stored in the container.\n *\/\n template <class T, class EA, class SA>\n class xarray : public xcontainer<xarray<T, EA, SA>>,\n public xcontainer_semantic<xarray<T, EA, SA>>\n {\n\n public:\n\n using self_type = xarray<T, EA, SA>;\n using base_type = xcontainer<self_type>;\n using semantic_base = xcontainer_semantic<self_type>;\n using container_type = typename base_type::container_type;\n using value_type = typename base_type::value_type;\n using reference = typename base_type::reference;\n using const_reference = typename base_type::const_reference;\n using pointer = typename base_type::pointer;\n using const_pointer = typename base_type::const_pointer;\n using shape_type = typename base_type::shape_type;\n using strides_type = typename base_type::strides_type;\n\n using closure_type = const self_type&;\n\n xarray();\n explicit xarray(const shape_type& shape, layout l = layout::row_major);\n explicit xarray(const shape_type& shape, const_reference value, layout l = layout::row_major);\n explicit xarray(const shape_type& shape, const strides_type& strides);\n explicit xarray(const shape_type& shape, const strides_type& strides, const_reference value);\n\n xarray(const value_type& t);\n xarray(std::initializer_list<T> t);\n xarray(std::initializer_list<std::initializer_list<T>> t);\n xarray(std::initializer_list<std::initializer_list<std::initializer_list<T>>> t);\n xarray(std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<T>>>> t);\n xarray(std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<T>>>>> t);\n\n ~xarray() = default;\n\n xarray(const xarray&) = default;\n xarray& operator=(const xarray&) = default;\n\n xarray(xarray&&) = default;\n xarray& operator=(xarray&&) = default;\n\n template <class E>\n xarray(const xexpression<E>& e);\n\n template <class E>\n xarray& operator=(const xexpression<E>& e);\n\n private:\n\n container_type m_data;\n\n container_type& data_impl() noexcept;\n const container_type& data_impl() const noexcept;\n\n friend class xcontainer<xarray<T, EA, SA>>;\n };\n\n \/******************************\n * xarray_adaptor declaration *\n ******************************\/\n\n template <class C, class EA = std::allocator<typename C::value_type>, class SA = std::allocator<typename C::size_type>>\n class xarray_adaptor;\n\n template <class C, class EA, class SA>\n struct xcontainer_inner_types<xarray_adaptor<C, EA, SA>>\n {\n using container_type = C;\n using shape_type = std::vector<typename container_type::size_type, SA>;\n using strides_type = shape_type;\n using temporary_type = xarray<typename C::value_type, EA, SA>;\n };\n\n \/**\n * @class xarray_adaptor\n * @brief Dense multidimensional container adaptor with\n * tensor semantic.\n *\n * The xarray_adaptor class implements a dense multidimensional\n * container adaptor with tensor semantic. It is used to provide\n * a multidimensional container semantic and a tensor semantic to\n * stl-like containers.\n *\n * @tparam C The container type to adapt.\n *\/\n template <class C, class EA, class SA>\n class xarray_adaptor : public xcontainer<xarray_adaptor<C, EA, SA>>,\n public xadaptor_semantic<xarray_adaptor<C, EA, SA>>\n {\n\n public:\n\n using self_type = xarray_adaptor<C, EA, SA>;\n using base_type = xcontainer<self_type>;\n using semantic_base = xadaptor_semantic<self_type>;\n using container_type = typename base_type::container_type;\n using shape_type = typename base_type::shape_type;\n using strides_type = typename base_type::strides_type;\n\n using closure_type = const self_type&;\n\n xarray_adaptor(container_type& data);\n xarray_adaptor(container_type& data, const shape_type& shape, layout l = layout::row_major);\n xarray_adaptor(container_type& data, const shape_type& shape, const strides_type& strides);\n\n ~xarray_adaptor() = default;\n\n xarray_adaptor(const xarray_adaptor&) = default;\n xarray_adaptor& operator=(const xarray_adaptor&);\n\n xarray_adaptor(xarray_adaptor&&) = default;\n xarray_adaptor& operator=(xarray_adaptor&&);\n\n template <class E>\n xarray_adaptor& operator=(const xexpression<E>& e);\n\n private:\n\n container_type& m_data;\n\n container_type& data_impl() noexcept;\n const container_type& data_impl() const noexcept;\n\n using temporary_type = typename xcontainer_inner_types<self_type>::temporary_type;\n void assign_temporary_impl(temporary_type& tmp);\n\n friend class xcontainer<xarray_adaptor<C, EA, SA>>;\n friend class xadaptor_semantic<xarray_adaptor<C, EA, SA>>;\n };\n\n \/*************************\n * xarray implementation *\n *************************\/\n\n \/**\n * @name Constructors\n *\/\n \/\/@{\n \/**\n * Allocates an uninitialized xarray that holds 0 element.\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray()\n : base_type(), m_data(1, value_type())\n {\n }\n\n \/**\n * Allocates an uninitialized xarray with the specified shape and\n * layout.\n * @param shape the shape of the xarray\n * @param l the layout of the xarray\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(const shape_type& shape, layout l)\n : base_type()\n {\n base_type::reshape(shape, l);\n }\n\n \/**\n * Allocates an xarray with the specified shape and layout. Elements\n * are initialized to the specified value.\n * @param shape the shape of the xarray\n * @param value the value of the elements\n * @param l the layout of the xarray\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(const shape_type& shape, const_reference value, layout l)\n : base_type()\n {\n base_type::reshape(shape, l);\n std::fill(m_data.begin(), m_data.end(), value);\n }\n\n \/**\n * Allocates an uninitialized xarray with the specified shape and strides.\n * @param shape the shape of the xarray\n * @param strides the strides of the xarray\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(const shape_type& shape, const strides_type& strides)\n : base_type()\n {\n base_type::reshape(shape, strides);\n }\n\n \/**\n * Allocates an uninitialized xarray with the specified shape and strides.\n * Elements are initialized to the specified value.\n * @param shape the shape of the xarray\n * @param strides the strides of the xarray\n * @param value the value of the elements\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(const shape_type& shape, const strides_type& strides, const_reference value)\n : base_type()\n {\n base_type::reshape(shape, strides);\n std::fill(m_data.begin(), m_data.end(), value);\n }\n\n \/**\n * Allocates an xarray that holds a single element initialized to the\n * specified value.\n * @param t the value of the element\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(const value_type& t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n \/\/@}\n\n \/**\n * @name Constructors from initializer list\n *\/\n \/\/@{\n \/**\n * Allocates a one-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(std::initializer_list<T> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n\n \/**\n * Allocates a two-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(std::initializer_list<std::initializer_list<T>> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n\n \/**\n * Allocates a three-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(std::initializer_list<std::initializer_list<std::initializer_list<T>>> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n\n \/**\n * Allocates a four-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<T>>>> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n\n \/**\n * Allocates a five-dimensional xarray.\n * @param t the elements of the xarray\n *\/\n template <class T, class EA, class SA>\n inline xarray<T, EA, SA>::xarray(std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<std::initializer_list<T>>>>> t)\n : base_type()\n {\n base_type::reshape(xt::shape<shape_type>(t), layout::row_major);\n nested_copy(m_data.begin(), t);\n }\n \/\/@}\n\n\n \/**\n * @name Extended copy semantic\n *\/\n \/\/@{\n \/**\n * The extended copy constructor.\n *\/\n template <class T, class EA, class SA>\n template <class E>\n inline xarray<T, EA, SA>::xarray(const xexpression<E>& e)\n : base_type()\n {\n semantic_base::assign(e);\n }\n\n \/**\n * The extended assignment operator.\n *\/\n template <class T, class EA, class SA>\n template <class E>\n inline auto xarray<T, EA, SA>::operator=(const xexpression<E>& e) -> self_type&\n {\n return semantic_base::operator=(e);\n }\n \/\/@}\n\n template <class T, class EA, class SA>\n inline auto xarray<T, EA, SA>::data_impl() noexcept -> container_type&\n {\n return m_data;\n }\n\n template <class T, class EA, class SA>\n inline auto xarray<T, EA, SA>::data_impl() const noexcept -> const container_type&\n {\n return m_data;\n }\n\n \/******************\n * xarray_adaptor *\n ******************\/\n\n \/**\n * @name Constructors\n *\/\n \/\/@{\n \/**\n * Constructs an xarray_adaptor of the given stl-like container.\n * @param data the container to adapt\n *\/\n template <class C, class EA, class SA>\n inline xarray_adaptor<C, EA, SA>::xarray_adaptor(container_type& data)\n : base_type(), m_data(data)\n {\n }\n\n \/**\n * Constructs an xarray_adaptor of the given stl-like container,\n * with the specified shape and layout.\n * @param data the container to adapt\n * @param shape the shape of the xarray_adaptor\n * @param l the layout of the xarray_adaptor\n *\/\n template <class C, class EA, class SA>\n inline xarray_adaptor<C, EA, SA>::xarray_adaptor(container_type& data, const shape_type& shape, layout l)\n : base_type(), m_data(data)\n {\n base_type::reshape(shape, l);\n }\n\n \/**\n * Constructs an xarray_adaptor of the given stl-like container,\n * with the specified shape and strides.\n * @param data the container to adapt\n * @param shape the shape of the xarray_adaptor\n * @param strides the strides of the xarray_adaptor\n *\/\n template <class C, class EA, class SA>\n inline xarray_adaptor<C, EA, SA>::xarray_adaptor(container_type& data, const shape_type& shape, const strides_type& strides)\n : base_type(), m_data(data)\n {\n base_type::reshape(shape, strides);\n }\n \/\/@}\n\n template <class C, class EA, class SA>\n inline xarray_adaptor<C, EA, SA>& xarray_adaptor<C, EA, SA>::operator=(const xarray_adaptor& rhs)\n {\n base_type::operator=(rhs);\n m_data = rhs.m_data;\n return *this;\n }\n\n template <class C, class EA, class SA>\n inline xarray_adaptor<C, EA, SA>& xarray_adaptor<C, EA, SA>::operator=(xarray_adaptor&& rhs)\n {\n base_type::operator=(std::move(rhs));\n m_data = rhs.m_data;\n return *this;\n }\n\n \/**\n * @name Extended copy semantic\n *\/\n \/\/@{\n \/**\n * The extended assignment operator.\n *\/\n template <class C, class EA, class SA>\n template <class E>\n inline auto xarray_adaptor<C, EA, SA>::operator=(const xexpression<E>& e) -> self_type&\n {\n return semantic_base::operator=(e);\n }\n \/\/@}\n\n template <class C, class EA, class SA>\n inline auto xarray_adaptor<C, EA, SA>::data_impl() noexcept -> container_type&\n {\n return m_data;\n }\n\n template <class C, class EA, class SA>\n inline auto xarray_adaptor<C, EA, SA>::data_impl() const noexcept -> const container_type&\n {\n return m_data;\n }\n\n template <class C, class EA, class SA>\n inline void xarray_adaptor<C, EA, SA>::assign_temporary_impl(temporary_type& tmp)\n {\n \/\/ TODO (performance improvement) : consider moving tmps\n \/\/ shape and strides\n base_type::get_shape() = tmp.shape();\n base_type::get_strides() = tmp.strides();\n base_type::get_backstrides() = tmp.backstrides();\n m_data.resize(tmp.size());\n std::copy(tmp.data().cbegin(), tmp.data().cend(), m_data.begin());\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ example of TGraphTime\n\/\/Author: Rene Brun 14\/07\/2009\n \n#include \"TCanvas.h\"\n#include \"TRandom3.h\"\n#include \"TMath.h\"\n#include \"TText.h\"\n#include \"TArrow.h\"\n#include \"TGraphTime.h\"\n#include \"TROOT.h\"\n \nvoid gtime(Int_t nsteps = 500, Int_t np=100) {\n if (np > 1000) np = 1000;\n Int_t color[1000];\n Double_t rr[1000], phi[1000], dr[1000], size[1000];\n TRandom3 r;\n Double_t xmin = -10, xmax = 10, ymin = -10, ymax = 10;\n TGraphTime *g = new TGraphTime(nsteps,xmin,ymin,xmax,ymax);\n Int_t i,s;\n for (i=0;i<np;i++) { \/\/calculate some object parameters\n rr[i] = r.Uniform(0.1*xmax,0.2*xmax);\n phi[i] = r.Uniform(0,2*TMath::Pi());\n dr[i] = r.Uniform(0,1)*0.9*xmax\/Double_t(nsteps);\n Double_t rc = r.Rndm();\n color[i] = kRed;\n if (rc > 0.3) color[i] = kBlue;\n if (rc > 0.7) color[i] = kYellow;\n size[i] = r.Uniform(0.5,6);\n }\n for (s=0;s<nsteps;s++) { \/\/fill the TGraphTime step by step\n for (i=0;i<np;i++) {\n Double_t newr = rr[i]+dr[i]*s;\n Double_t newsize = 0.2+size[i]*TMath::Abs(TMath::Sin(newr+10));\n Double_t newphi = phi[i] + 0.01*s;\n Double_t xx = newr*TMath::Cos(newphi);\n Double_t yy = newr*TMath::Sin(newphi);\n TMarker *m = new TMarker(xx,yy,20);\n m->SetMarkerColor(color[i]);\n m->SetMarkerSize(newsize);\n g->Add(m,s);\n if (i==np-1) g->Add(new TArrow(xmin,ymax,xx,yy,0.02,\"-|>\"), s);\n }\n }\n g->Draw(\"time\");\n \n \/\/save object to a file\n TFile f(\"gtime.root\",\"recreate\");\n g->Write(\"g\");\n \/\/to view this object in another session do\n \/\/ TFile f(\"gtime.root\");\n \/\/ g.Draw(\"time\");\n}\n \n \n \n<commit_msg>Add a TPaveLabel in the list of objects . The label shows the time step number.<commit_after>\/\/ example of TGraphTime\n\/\/Author: Rene Brun 14\/07\/2009\n \n#include \"TCanvas.h\"\n#include \"TRandom3.h\"\n#include \"TMath.h\"\n#include \"TText.h\"\n#include \"TArrow.h\"\n#include \"TGraphTime.h\"\n#include \"TROOT.h\"\n \nvoid gtime(Int_t nsteps = 500, Int_t np=100) {\n if (np > 1000) np = 1000;\n Int_t color[1000];\n Double_t rr[1000], phi[1000], dr[1000], size[1000];\n TRandom3 r;\n Double_t xmin = -10, xmax = 10, ymin = -10, ymax = 10;\n TGraphTime *g = new TGraphTime(nsteps,xmin,ymin,xmax,ymax);\n Int_t i,s;\n for (i=0;i<np;i++) { \/\/calculate some object parameters\n rr[i] = r.Uniform(0.1*xmax,0.2*xmax);\n phi[i] = r.Uniform(0,2*TMath::Pi());\n dr[i] = r.Uniform(0,1)*0.9*xmax\/Double_t(nsteps);\n Double_t rc = r.Rndm();\n color[i] = kRed;\n if (rc > 0.3) color[i] = kBlue;\n if (rc > 0.7) color[i] = kYellow;\n size[i] = r.Uniform(0.5,6);\n }\n for (s=0;s<nsteps;s++) { \/\/fill the TGraphTime step by step\n for (i=0;i<np;i++) {\n Double_t newr = rr[i]+dr[i]*s;\n Double_t newsize = 0.2+size[i]*TMath::Abs(TMath::Sin(newr+10));\n Double_t newphi = phi[i] + 0.01*s;\n Double_t xx = newr*TMath::Cos(newphi);\n Double_t yy = newr*TMath::Sin(newphi);\n TMarker *m = new TMarker(xx,yy,20);\n m->SetMarkerColor(color[i]);\n m->SetMarkerSize(newsize);\n g->Add(m,s);\n if (i==np-1) g->Add(new TArrow(xmin,ymax,xx,yy,0.02,\"-|>\"), s);\n }\n g->Add(new TPaveLabel(.90,.92,.98,.97,Form(\"%d\",s+1),\"brNDC\"),s);\n }\n g->Draw();\n \n \/\/save object to a file\n TFile f(\"gtime.root\",\"recreate\");\n g->Write(\"g\");\n \/\/to view this object in another session do\n \/\/ TFile f(\"gtime.root\");\n \/\/ g.Draw(\"time\");\n}\n \n \n \n<|endoftext|>"} {"text":"<commit_before>\/\/ tutorial illustrating the use of TMath::Permute\n\/\/ can be run with:\n\/\/ root > .x permute.C\n\/\/ root > .x permute.C+ with ACLIC\n\/\/Author: Federico Carminati\n \n#include <TMath.h>\n\nint permuteSimple1 () \n{\n printf(\"\\nTMath::Permute simple test\\n\");\n printf(\"==========================\\n\");\n char aa='a';\n Int_t a[4];\n Int_t i;\n Int_t icount=0;\n for(i=0; i<4; i++) a[i]=i;\n do { \n icount++;\n for(Int_t i=0;i<4;printf(\"%c\",static_cast<char>(aa+a[i++])))\n ;\n printf(\"\\n\");\n \n } while(TMath::Permute(4,a));\n printf(\"Found %d permutations = 4!\\n\",icount);\n return 0;\n}\n\nint permuteSimple2 () \n{\n printf(\"\\nTMath::Permute simple test with repetition\\n\");\n printf(\"==========================================\\n\");\n char aa='a'-1;\n Int_t a[6];\n Int_t i;\n Int_t icount=0;\n for(i=0; i<6; i++) a[i]=(i+2)\/2;\n do { \n icount++;\n for(Int_t i=0;i<5;printf(\"%c\",static_cast<char>(aa+a[i++])))\n ;\n printf(\"\\n\");\n \n } while(TMath::Permute(5,a));\n printf(\"Found %d permutations = 5!\/(2! 2!)\\n\",icount);\n return 0;\n}\n\nInt_t permuteFancy() \n{\n Int_t a[10];\n Int_t &n=a[0], &i=a[1];\n Int_t &e=a[2], &t=a[3];\n Int_t &h=a[4], &r=a[5];\n Int_t &f=a[6], &o=a[7];\n Int_t &s=a[8], &u=a[9];\n Int_t nine, three, neuf, trois;\n\n printf(\"\\nTMath::Permute fancy test\\n\");\n printf(\"=========================\\n\");\n printf(\"This is a program to calculate the solution to the following problem\\n\");\n printf(\"Find the equivalence between letters and numbers so that\\n\\n\");\n printf(\" NINE*THREE = NEUF*TROIS\\n\\n\");\n for(Int_t ii=0; ii<10; ii++) a[ii]=ii;\n do {\n nine=((n*10+i)*10+n)*10+e;\n neuf=((n*10+e)*10+u)*10+f;\n three=(((t*10+h)*10+r)*10+e)*10+e;\n trois=(((t*10+r)*10+o)*10+i)*10+s;\n if(nine*three==neuf*trois) {\n printf(\"Solution found!\\n\\n\");\n printf(\"T=%d N=%d E=%d S=%d F=%d H=%d R=%d I=%d O=%d U=%d\\n\",t,n,e,s,f,h,r,i,o,u);\n printf(\"NINE=%d THREE=%d NEUF=%d TROIS=%d\\n\",nine,three,neuf,trois);\n printf(\"NINE*THREE = NEUF*TROIS = %d\\n\",neuf*trois);\n return 0;\n }\n } while(TMath::Permute(10,a));\n printf(\"No solutions found -- something is wrong here!\\n\");\n return 0;\n}\n\nvoid permute() {\n permuteSimple1();\n permuteSimple2();\n permuteFancy();\n}\n<commit_msg>Hm, not so funny actually :)<commit_after>\/\/ tutorial illustrating the use of TMath::Permute\n\/\/ can be run with:\n\/\/ root > .x permute.C\n\/\/ root > .x permute.C+ with ACLIC\n\/\/Author: Federico Carminati\n \n#include <TMath.h>\n\nint permuteSimple1 () \n{\n printf(\"\\nTMath::Permute simple test\\n\");\n printf(\"==========================\\n\");\n char aa='a';\n Int_t a[4];\n Int_t i;\n Int_t icount=0;\n for(i=0; i<4; i++) a[i]=i;\n do { \n icount++;\n for(Int_t i=0;i<4;printf(\"%c\",static_cast<char>(aa+a[i++])));\n printf(\"\\n\");\n \n } while(TMath::Permute(4,a));\n printf(\"Found %d permutations = 4!\\n\",icount);\n return 0;\n}\n\nint permuteSimple2 () \n{\n printf(\"\\nTMath::Permute simple test with repetition\\n\");\n printf(\"==========================================\\n\");\n char aa='a'-1;\n Int_t a[6];\n Int_t i;\n Int_t icount=0;\n for(i=0; i<6; i++) a[i]=(i+2)\/2;\n do { \n icount++;\n for(Int_t i=0;i<5;printf(\"%c\",static_cast<char>(aa+a[i++])));\n printf(\"\\n\");\n \n } while(TMath::Permute(5,a));\n printf(\"Found %d permutations = 5!\/(2! 2!)\\n\",icount);\n return 0;\n}\n\nInt_t permuteFancy() \n{\n Int_t a[10];\n Int_t &n=a[0], &i=a[1];\n Int_t &e=a[2], &t=a[3];\n Int_t &h=a[4], &r=a[5];\n Int_t &f=a[6], &o=a[7];\n Int_t &s=a[8], &u=a[9];\n Int_t nine, three, neuf, trois;\n\n printf(\"\\nTMath::Permute fancy test\\n\");\n printf(\"=========================\\n\");\n printf(\"This is a program to calculate the solution to the following problem\\n\");\n printf(\"Find the equivalence between letters and numbers so that\\n\\n\");\n printf(\" NINE*THREE = NEUF*TROIS\\n\\n\");\n for(Int_t ii=0; ii<10; ii++) a[ii]=ii;\n do {\n nine=((n*10+i)*10+n)*10+e;\n neuf=((n*10+e)*10+u)*10+f;\n three=(((t*10+h)*10+r)*10+e)*10+e;\n trois=(((t*10+r)*10+o)*10+i)*10+s;\n if(nine*three==neuf*trois) {\n printf(\"Solution found!\\n\\n\");\n printf(\"T=%d N=%d E=%d S=%d F=%d H=%d R=%d I=%d O=%d U=%d\\n\",t,n,e,s,f,h,r,i,o,u);\n printf(\"NINE=%d THREE=%d NEUF=%d TROIS=%d\\n\",nine,three,neuf,trois);\n printf(\"NINE*THREE = NEUF*TROIS = %d\\n\",neuf*trois);\n return 0;\n }\n } while(TMath::Permute(10,a));\n printf(\"No solutions found -- something is wrong here!\\n\");\n return 0;\n}\n\nvoid permute() {\n permuteSimple1();\n permuteSimple2();\n permuteFancy();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * 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\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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file ir_constant_expression.cpp\n * Evaluate and process constant valued expressions\n *\n * In GLSL, constant valued expressions are used in several places. These\n * must be processed and evaluated very early in the compilation process.\n *\n * * Sizes of arrays\n * * Initializers for uniforms\n * * Initializers for \\c const variables\n *\/\n\n#define NULL 0\n#include \"ir.h\"\n#include \"ir_visitor.h\"\n#include \"glsl_types.h\"\n\n\/**\n * Visitor class for evaluating constant expressions\n *\/\nclass ir_constant_visitor : public ir_visitor {\npublic:\n ir_constant_visitor()\n : value(NULL)\n {\n \/* empty *\/\n }\n\n virtual ~ir_constant_visitor()\n {\n \/* empty *\/\n }\n\n \/**\n * \\name Visit methods\n *\n * As typical for the visitor pattern, there must be one \\c visit method for\n * each concrete subclass of \\c ir_instruction. Virtual base classes within\n * the hierarchy should not have \\c visit methods.\n *\/\n \/*@{*\/\n virtual void visit(ir_variable *);\n virtual void visit(ir_label *);\n virtual void visit(ir_function_signature *);\n virtual void visit(ir_function *);\n virtual void visit(ir_expression *);\n virtual void visit(ir_swizzle *);\n virtual void visit(ir_dereference *);\n virtual void visit(ir_assignment *);\n virtual void visit(ir_constant *);\n virtual void visit(ir_call *);\n virtual void visit(ir_return *);\n virtual void visit(ir_if *);\n \/*@}*\/\n\n \/**\n * Value of the constant expression.\n *\n * \\note\n * This field will be \\c NULL if the expression is not constant valued.\n *\/\n \/* FINIHSME: This cannot hold values for constant arrays or structures. *\/\n ir_constant *value;\n};\n\n\nir_constant *\nir_instruction::constant_expression_value()\n{\n ir_constant_visitor visitor;\n\n this->accept(& visitor);\n return visitor.value;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_variable *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_label *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_function_signature *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_function *ir)\n{\n (void) ir;\n value = NULL;\n}\n\nvoid\nir_constant_visitor::visit(ir_expression *ir)\n{\n value = NULL;\n ir_constant *op[2];\n unsigned int operand, c;\n unsigned u[16];\n int i[16];\n float f[16];\n bool b[16];\n const glsl_type *type = NULL;\n\n for (operand = 0; operand < ir->get_num_operands(); operand++) {\n op[operand] = ir->operands[operand]->constant_expression_value();\n if (!op[operand])\n\t return;\n }\n\n switch (ir->operation) {\n case ir_unop_logic_not:\n type = ir->operands[0]->type;\n assert(type->base_type == GLSL_TYPE_BOOL);\n for (c = 0; c < ir->operands[0]->type->components(); c++)\n\t b[c] = !op[0]->value.b[c];\n break;\n case ir_binop_add:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = ir->operands[0]->type;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t u[c] = op[0]->value.u[c] + op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t i[c] = op[0]->value.i[c] + op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t f[c] = op[0]->value.f[c] + op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_sub:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = ir->operands[0]->type;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t u[c] = op[0]->value.u[c] - op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t i[c] = op[0]->value.i[c] - op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t f[c] = op[0]->value.f[c] - op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_mul:\n if (ir->operands[0]->type == ir->operands[1]->type &&\n\t !ir->operands[0]->type->is_matrix()) {\n\t type = ir->operands[0]->type;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t u[c] = op[0]->value.u[c] * op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t i[c] = op[0]->value.i[c] * op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t f[c] = op[0]->value.f[c] * op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_div:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = ir->operands[0]->type;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t u[c] = op[0]->value.u[c] \/ op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t i[c] = op[0]->value.i[c] \/ op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t f[c] = op[0]->value.f[c] \/ op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_logic_and:\n type = ir->operands[0]->type;\n assert(type->base_type == GLSL_TYPE_BOOL);\n for (c = 0; c < ir->operands[0]->type->components(); c++)\n\t b[c] = op[0]->value.b[c] && op[1]->value.b[c];\n break;\n case ir_binop_logic_xor:\n type = ir->operands[0]->type;\n assert(type->base_type == GLSL_TYPE_BOOL);\n for (c = 0; c < ir->operands[0]->type->components(); c++)\n\t b[c] = op[0]->value.b[c] ^ op[1]->value.b[c];\n break;\n case ir_binop_logic_or:\n type = ir->operands[0]->type;\n assert(type->base_type == GLSL_TYPE_BOOL);\n for (c = 0; c < ir->operands[0]->type->components(); c++)\n\t b[c] = op[0]->value.b[c] || op[1]->value.b[c];\n break;\n\n case ir_binop_less:\n type = glsl_type::bool_type;\n switch (ir->operands[0]->type->base_type) {\n case GLSL_TYPE_UINT:\n\t b[0] = op[0]->value.u[0] < op[1]->value.u[0];\n\t break;\n case GLSL_TYPE_INT:\n\t b[0] = op[0]->value.i[0] < op[1]->value.i[0];\n\t break;\n case GLSL_TYPE_FLOAT:\n\t b[0] = op[0]->value.f[0] < op[1]->value.f[0];\n\t break;\n default:\n\t assert(0);\n }\n break;\n case ir_binop_greater:\n type = glsl_type::bool_type;\n switch (ir->operands[0]->type->base_type) {\n case GLSL_TYPE_UINT:\n\t b[0] = op[0]->value.u[0] > op[1]->value.u[0];\n\t break;\n case GLSL_TYPE_INT:\n\t b[0] = op[0]->value.i[0] > op[1]->value.i[0];\n\t break;\n case GLSL_TYPE_FLOAT:\n\t b[0] = op[0]->value.f[0] > op[1]->value.f[0];\n\t break;\n default:\n\t assert(0);\n }\n break;\n case ir_binop_lequal:\n type = glsl_type::bool_type;\n switch (ir->operands[0]->type->base_type) {\n case GLSL_TYPE_UINT:\n\t b[0] = op[0]->value.u[0] <= op[1]->value.u[0];\n\t break;\n case GLSL_TYPE_INT:\n\t b[0] = op[0]->value.i[0] <= op[1]->value.i[0];\n\t break;\n case GLSL_TYPE_FLOAT:\n\t b[0] = op[0]->value.f[0] <= op[1]->value.f[0];\n\t break;\n default:\n\t assert(0);\n }\n break;\n case ir_binop_gequal:\n type = glsl_type::bool_type;\n switch (ir->operands[0]->type->base_type) {\n case GLSL_TYPE_UINT:\n\t b[0] = op[0]->value.u[0] >= op[1]->value.u[0];\n\t break;\n case GLSL_TYPE_INT:\n\t b[0] = op[0]->value.i[0] >= op[1]->value.i[0];\n\t break;\n case GLSL_TYPE_FLOAT:\n\t b[0] = op[0]->value.f[0] >= op[1]->value.f[0];\n\t break;\n default:\n\t assert(0);\n }\n break;\n\n case ir_binop_equal:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = glsl_type::bool_type;\n\t b[0] = true;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t b[0] = b[0] && op[0]->value.u[c] == op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t b[0] = b[0] && op[0]->value.i[c] == op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t b[0] = b[0] && op[0]->value.f[c] == op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_nequal:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = glsl_type::bool_type;\n\t b[0] = false;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t b[0] = b[0] || op[0]->value.u[c] != op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t b[0] = b[0] || op[0]->value.i[c] != op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t b[0] = b[0] || op[0]->value.f[c] != op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n\n default:\n break;\n }\n\n if (type) {\n switch (type->base_type) {\n case GLSL_TYPE_UINT:\n\t value = new ir_constant(type, u);\n\t break;\n case GLSL_TYPE_INT:\n\t value = new ir_constant(type, i);\n\t break;\n case GLSL_TYPE_FLOAT:\n\t value = new ir_constant(type, f);\n\t break;\n case GLSL_TYPE_BOOL:\n\t value = new ir_constant(type, b);\n\t break;\n }\n }\n}\n\n\nvoid\nir_constant_visitor::visit(ir_swizzle *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_dereference *ir)\n{\n value = NULL;\n\n if (ir->mode == ir_dereference::ir_reference_variable) {\n ir_variable *var = ir->var->as_variable();\n if (var && var->constant_value) {\n\t value = new ir_constant(ir->type, &var->constant_value->value);\n }\n }\n \/* FINISHME: Other dereference modes. *\/\n}\n\n\nvoid\nir_constant_visitor::visit(ir_assignment *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_constant *ir)\n{\n value = ir;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_call *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_return *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_if *ir)\n{\n (void) ir;\n value = NULL;\n}\n<commit_msg>Add float\/int conversion to ir_constant_expression.cpp.<commit_after>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * 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\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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file ir_constant_expression.cpp\n * Evaluate and process constant valued expressions\n *\n * In GLSL, constant valued expressions are used in several places. These\n * must be processed and evaluated very early in the compilation process.\n *\n * * Sizes of arrays\n * * Initializers for uniforms\n * * Initializers for \\c const variables\n *\/\n\n#define NULL 0\n#include \"ir.h\"\n#include \"ir_visitor.h\"\n#include \"glsl_types.h\"\n\n\/**\n * Visitor class for evaluating constant expressions\n *\/\nclass ir_constant_visitor : public ir_visitor {\npublic:\n ir_constant_visitor()\n : value(NULL)\n {\n \/* empty *\/\n }\n\n virtual ~ir_constant_visitor()\n {\n \/* empty *\/\n }\n\n \/**\n * \\name Visit methods\n *\n * As typical for the visitor pattern, there must be one \\c visit method for\n * each concrete subclass of \\c ir_instruction. Virtual base classes within\n * the hierarchy should not have \\c visit methods.\n *\/\n \/*@{*\/\n virtual void visit(ir_variable *);\n virtual void visit(ir_label *);\n virtual void visit(ir_function_signature *);\n virtual void visit(ir_function *);\n virtual void visit(ir_expression *);\n virtual void visit(ir_swizzle *);\n virtual void visit(ir_dereference *);\n virtual void visit(ir_assignment *);\n virtual void visit(ir_constant *);\n virtual void visit(ir_call *);\n virtual void visit(ir_return *);\n virtual void visit(ir_if *);\n \/*@}*\/\n\n \/**\n * Value of the constant expression.\n *\n * \\note\n * This field will be \\c NULL if the expression is not constant valued.\n *\/\n \/* FINIHSME: This cannot hold values for constant arrays or structures. *\/\n ir_constant *value;\n};\n\n\nir_constant *\nir_instruction::constant_expression_value()\n{\n ir_constant_visitor visitor;\n\n this->accept(& visitor);\n return visitor.value;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_variable *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_label *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_function_signature *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_function *ir)\n{\n (void) ir;\n value = NULL;\n}\n\nvoid\nir_constant_visitor::visit(ir_expression *ir)\n{\n value = NULL;\n ir_constant *op[2];\n unsigned int operand, c;\n unsigned u[16];\n int i[16];\n float f[16];\n bool b[16];\n const glsl_type *type = NULL;\n\n for (operand = 0; operand < ir->get_num_operands(); operand++) {\n op[operand] = ir->operands[operand]->constant_expression_value();\n if (!op[operand])\n\t return;\n }\n\n switch (ir->operation) {\n case ir_unop_logic_not:\n type = ir->operands[0]->type;\n assert(type->base_type == GLSL_TYPE_BOOL);\n for (c = 0; c < ir->operands[0]->type->components(); c++)\n\t b[c] = !op[0]->value.b[c];\n break;\n\n case ir_unop_f2i:\n assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);\n type = ir->type;\n for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t i[c] = op[0]->value.f[c];\n }\n break;\n case ir_unop_i2f:\n assert(op[0]->type->base_type == GLSL_TYPE_UINT ||\n\t op[0]->type->base_type == GLSL_TYPE_INT);\n type = ir->type;\n for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t if (op[0]->type->base_type == GLSL_TYPE_INT)\n\t f[c] = op[0]->value.i[c];\n\t else\n\t f[c] = op[0]->value.u[c];\n }\n break;\n\n case ir_binop_add:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = ir->operands[0]->type;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t u[c] = op[0]->value.u[c] + op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t i[c] = op[0]->value.i[c] + op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t f[c] = op[0]->value.f[c] + op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_sub:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = ir->operands[0]->type;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t u[c] = op[0]->value.u[c] - op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t i[c] = op[0]->value.i[c] - op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t f[c] = op[0]->value.f[c] - op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_mul:\n if (ir->operands[0]->type == ir->operands[1]->type &&\n\t !ir->operands[0]->type->is_matrix()) {\n\t type = ir->operands[0]->type;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t u[c] = op[0]->value.u[c] * op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t i[c] = op[0]->value.i[c] * op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t f[c] = op[0]->value.f[c] * op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_div:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = ir->operands[0]->type;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t u[c] = op[0]->value.u[c] \/ op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t i[c] = op[0]->value.i[c] \/ op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t f[c] = op[0]->value.f[c] \/ op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_logic_and:\n type = ir->operands[0]->type;\n assert(type->base_type == GLSL_TYPE_BOOL);\n for (c = 0; c < ir->operands[0]->type->components(); c++)\n\t b[c] = op[0]->value.b[c] && op[1]->value.b[c];\n break;\n case ir_binop_logic_xor:\n type = ir->operands[0]->type;\n assert(type->base_type == GLSL_TYPE_BOOL);\n for (c = 0; c < ir->operands[0]->type->components(); c++)\n\t b[c] = op[0]->value.b[c] ^ op[1]->value.b[c];\n break;\n case ir_binop_logic_or:\n type = ir->operands[0]->type;\n assert(type->base_type == GLSL_TYPE_BOOL);\n for (c = 0; c < ir->operands[0]->type->components(); c++)\n\t b[c] = op[0]->value.b[c] || op[1]->value.b[c];\n break;\n\n case ir_binop_less:\n type = glsl_type::bool_type;\n switch (ir->operands[0]->type->base_type) {\n case GLSL_TYPE_UINT:\n\t b[0] = op[0]->value.u[0] < op[1]->value.u[0];\n\t break;\n case GLSL_TYPE_INT:\n\t b[0] = op[0]->value.i[0] < op[1]->value.i[0];\n\t break;\n case GLSL_TYPE_FLOAT:\n\t b[0] = op[0]->value.f[0] < op[1]->value.f[0];\n\t break;\n default:\n\t assert(0);\n }\n break;\n case ir_binop_greater:\n type = glsl_type::bool_type;\n switch (ir->operands[0]->type->base_type) {\n case GLSL_TYPE_UINT:\n\t b[0] = op[0]->value.u[0] > op[1]->value.u[0];\n\t break;\n case GLSL_TYPE_INT:\n\t b[0] = op[0]->value.i[0] > op[1]->value.i[0];\n\t break;\n case GLSL_TYPE_FLOAT:\n\t b[0] = op[0]->value.f[0] > op[1]->value.f[0];\n\t break;\n default:\n\t assert(0);\n }\n break;\n case ir_binop_lequal:\n type = glsl_type::bool_type;\n switch (ir->operands[0]->type->base_type) {\n case GLSL_TYPE_UINT:\n\t b[0] = op[0]->value.u[0] <= op[1]->value.u[0];\n\t break;\n case GLSL_TYPE_INT:\n\t b[0] = op[0]->value.i[0] <= op[1]->value.i[0];\n\t break;\n case GLSL_TYPE_FLOAT:\n\t b[0] = op[0]->value.f[0] <= op[1]->value.f[0];\n\t break;\n default:\n\t assert(0);\n }\n break;\n case ir_binop_gequal:\n type = glsl_type::bool_type;\n switch (ir->operands[0]->type->base_type) {\n case GLSL_TYPE_UINT:\n\t b[0] = op[0]->value.u[0] >= op[1]->value.u[0];\n\t break;\n case GLSL_TYPE_INT:\n\t b[0] = op[0]->value.i[0] >= op[1]->value.i[0];\n\t break;\n case GLSL_TYPE_FLOAT:\n\t b[0] = op[0]->value.f[0] >= op[1]->value.f[0];\n\t break;\n default:\n\t assert(0);\n }\n break;\n\n case ir_binop_equal:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = glsl_type::bool_type;\n\t b[0] = true;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t b[0] = b[0] && op[0]->value.u[c] == op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t b[0] = b[0] && op[0]->value.i[c] == op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t b[0] = b[0] && op[0]->value.f[c] == op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n case ir_binop_nequal:\n if (ir->operands[0]->type == ir->operands[1]->type) {\n\t type = glsl_type::bool_type;\n\t b[0] = false;\n\t for (c = 0; c < ir->operands[0]->type->components(); c++) {\n\t switch (ir->operands[0]->type->base_type) {\n\t case GLSL_TYPE_UINT:\n\t b[0] = b[0] || op[0]->value.u[c] != op[1]->value.u[c];\n\t break;\n\t case GLSL_TYPE_INT:\n\t b[0] = b[0] || op[0]->value.i[c] != op[1]->value.i[c];\n\t break;\n\t case GLSL_TYPE_FLOAT:\n\t b[0] = b[0] || op[0]->value.f[c] != op[1]->value.f[c];\n\t break;\n\t default:\n\t assert(0);\n\t }\n\t }\n }\n break;\n\n default:\n break;\n }\n\n if (type) {\n switch (type->base_type) {\n case GLSL_TYPE_UINT:\n\t value = new ir_constant(type, u);\n\t break;\n case GLSL_TYPE_INT:\n\t value = new ir_constant(type, i);\n\t break;\n case GLSL_TYPE_FLOAT:\n\t value = new ir_constant(type, f);\n\t break;\n case GLSL_TYPE_BOOL:\n\t value = new ir_constant(type, b);\n\t break;\n }\n }\n}\n\n\nvoid\nir_constant_visitor::visit(ir_swizzle *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_dereference *ir)\n{\n value = NULL;\n\n if (ir->mode == ir_dereference::ir_reference_variable) {\n ir_variable *var = ir->var->as_variable();\n if (var && var->constant_value) {\n\t value = new ir_constant(ir->type, &var->constant_value->value);\n }\n }\n \/* FINISHME: Other dereference modes. *\/\n}\n\n\nvoid\nir_constant_visitor::visit(ir_assignment *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_constant *ir)\n{\n value = ir;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_call *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_return *ir)\n{\n (void) ir;\n value = NULL;\n}\n\n\nvoid\nir_constant_visitor::visit(ir_if *ir)\n{\n (void) ir;\n value = NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-file-style: \"gnu\" -*-\n *\n * This file is part of KMail, the KDE mail client.\n *\n * Copyright (c) 2002-2003 Carsten Pfeiffer <pfeiffer@kde.org>\n * Copyright (c) 2003 Zack Rusin <zack@kde.org>\n *\n * KMail is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License, version 2, as\n * published by the Free Software Foundation.\n *\n * KMail is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * In addition, as a special exception, the copyright holders give\n * permission to link the code of this program with any edition of\n * the Qt library by Trolltech AS, Norway (or with modified versions\n * of Qt that use the same license as Qt), and distribute linked\n * combinations including the two. You must obey the GNU General\n * Public License in all respects for all of the code used other than\n * Qt. If you modify this file, you may extend this exception to\n * your version of the file, but you are not obligated to do so. If\n * you do not wish to do so, delete this exception statement from\n * your version.\n *\/\n#include \"mailsourceviewer.h\"\n#include <QApplication>\n#include <QIcon>\n#include <kwindowsystem.h>\n\n#include <QRegExp>\n#include <QShortcut>\n#include <kiconloader.h>\n\nnamespace KMail {\n\nvoid MailSourceHighlighter::highlightBlock ( const QString & text ) {\n QRegExp regexp( \"^([\\\\w-]+:\\\\s)\" );\n if( regexp.indexIn( text ) != -1 ) {\n QFont font = document()->defaultFont ();\n font.setBold( true );\n setFormat( 0, regexp.matchedLength(), font );\n }\n}\n\nMailSourceViewer::MailSourceViewer( QWidget *parent )\n : KTextBrowser( parent ), mSourceHighLighter( 0 )\n{\n setAttribute( Qt::WA_DeleteOnClose );\n setLineWrapMode( QTextEdit::NoWrap );\n setTextInteractionFlags( Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard );\n\n \/\/ combining the shortcuts in one qkeysequence() did not work...\n QShortcut* shortcut = new QShortcut( this );\n shortcut->setKey( Qt::Key_Escape );\n connect( shortcut, SIGNAL( activated() ), SLOT( close() ) );\n\n shortcut = new QShortcut( this );\n shortcut->setKey( Qt::Key_W+Qt::CTRL );\n connect( shortcut, SIGNAL( activated() ), SLOT( close() ) );\n KWindowSystem::setIcons( winId(),\n qApp->windowIcon().pixmap( IconSize( KIconLoader::Desktop ),\n IconSize( KIconLoader::Desktop ) ),\n qApp->windowIcon().pixmap( IconSize( KIconLoader::Small ),\n IconSize( KIconLoader::Small ) ) );\n mSourceHighLighter = new MailSourceHighlighter( this );\n}\n\nMailSourceViewer::~MailSourceViewer()\n{\n delete mSourceHighLighter; mSourceHighLighter = 0;\n}\n\n}\n<commit_msg>BUG: 88271 BUG: 152707<commit_after>\/* -*- mode: C++; c-file-style: \"gnu\" -*-\n *\n * This file is part of KMail, the KDE mail client.\n *\n * Copyright (c) 2002-2003 Carsten Pfeiffer <pfeiffer@kde.org>\n * Copyright (c) 2003 Zack Rusin <zack@kde.org>\n *\n * KMail is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License, version 2, as\n * published by the Free Software Foundation.\n *\n * KMail is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * In addition, as a special exception, the copyright holders give\n * permission to link the code of this program with any edition of\n * the Qt library by Trolltech AS, Norway (or with modified versions\n * of Qt that use the same license as Qt), and distribute linked\n * combinations including the two. You must obey the GNU General\n * Public License in all respects for all of the code used other than\n * Qt. If you modify this file, you may extend this exception to\n * your version of the file, but you are not obligated to do so. If\n * you do not wish to do so, delete this exception statement from\n * your version.\n *\/\n#include \"mailsourceviewer.h\"\n#include <QApplication>\n#include <QIcon>\n#include <kwindowsystem.h>\n\n#include <QRegExp>\n#include <QShortcut>\n#include <kiconloader.h>\n\nnamespace KMail {\n\nvoid MailSourceHighlighter::highlightBlock ( const QString & text ) {\n \/\/ all visible ascii except space and :\n const QRegExp regexp( \"^([\\\\x21-9;-\\\\x7E]+:\\\\s)\" );\n const int headersState = -1; \/\/ Also the initial State\n const int bodyState = 0;\n\n \/\/ keep the previous state\n setCurrentBlockState( previousBlockState() );\n \/\/ If a header is found\n if( regexp.indexIn( text ) != -1 )\n {\n \/\/ Content- header starts a new mime part, and therefore new headers\n \/\/ If a Content-* header is found, change State to headers until a blank line is found.\n if ( text.startsWith( \"Content-\" ) )\n {\n setCurrentBlockState( headersState );\n }\n \/\/ highligth it if in headers state\n if( ( currentBlockState() == headersState ) )\n {\n QFont font = document()->defaultFont ();\n font.setBold( true );\n setFormat( 0, regexp.matchedLength(), font );\n }\n }\n \/\/ Change to body state\n else if (text.isEmpty())\n {\n setCurrentBlockState( bodyState );\n }\n}\n\nMailSourceViewer::MailSourceViewer( QWidget *parent )\n : KTextBrowser( parent ), mSourceHighLighter( 0 )\n{\n setAttribute( Qt::WA_DeleteOnClose );\n setLineWrapMode( QTextEdit::NoWrap );\n setTextInteractionFlags( Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard );\n\n \/\/ combining the shortcuts in one qkeysequence() did not work...\n QShortcut* shortcut = new QShortcut( this );\n shortcut->setKey( Qt::Key_Escape );\n connect( shortcut, SIGNAL( activated() ), SLOT( close() ) );\n\n shortcut = new QShortcut( this );\n shortcut->setKey( Qt::Key_W+Qt::CTRL );\n connect( shortcut, SIGNAL( activated() ), SLOT( close() ) );\n KWindowSystem::setIcons( winId(),\n qApp->windowIcon().pixmap( IconSize( KIconLoader::Desktop ),\n IconSize( KIconLoader::Desktop ) ),\n qApp->windowIcon().pixmap( IconSize( KIconLoader::Small ),\n IconSize( KIconLoader::Small ) ) );\n mSourceHighLighter = new MailSourceHighlighter( this );\n}\n\nMailSourceViewer::~MailSourceViewer()\n{\n delete mSourceHighLighter; mSourceHighLighter = 0;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * The Kernel-Machine Library *\n * Copyright (C) 2004, 2005 by Rutger W. ter Borg *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (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. 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, write to the Free Software *\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 *\n ***************************************************************************\/\n\n#ifndef ONLINE_DETERMINATE_HPP\n#define ONLINE_DETERMINATE_HPP\n\n#include <boost\/call_traits.hpp>\n#include <boost\/range\/begin.hpp>\n#include <boost\/range\/end.hpp>\n#include <boost\/range\/const_iterator.hpp>\n#include <kml\/determinate.hpp>\n\nnamespace kml {\n\n\n\ntemplate< typename Input,typename Output,template<typename,int> class Kernel >\nclass online_determinate: public determinate<Input,Output,Kernel> {\npublic:\n typedef Kernel<Input,0> kernel_type;\n typedef typename kernel_result<kernel_type>::type result_type;\n typedef determinate<Input,Output,Kernel> base_type;\n typedef Input input_type;\n typedef Output output_type;\n\n \/\/ constructor\n online_determinate( typename boost::call_traits<kernel_type>::param_type k ):\n base_type::determinate(k)\t{}\n\n \/\/ works for any Single Pass Range\n template<typename InputRange, typename OutputRange>\n void learn( InputRange const &input, OutputRange const &output ) {\n typename boost::range_const_iterator<InputRange>::type input_iter( boost::const_begin(input) );\n typename boost::range_const_iterator<OutputRange>::type output_iter( boost::const_begin(output) );\n for( ; input_iter != boost::const_end(input); ++input_iter, ++output_iter )\n push_back( *input_iter, *output_iter );\n }\n\n \/\/ pure virtual\n virtual void push_back( input_type const &input, output_type const &output ) = 0;\n\n};\n\n\n\n\n\n\n\n\n\n}\n\n#endif\n\n<commit_msg>Fixed a bug in online_determinate<commit_after>\/***************************************************************************\n * The Kernel-Machine Library *\n * Copyright (C) 2004, 2005 by Rutger W. ter Borg *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (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. 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, write to the Free Software *\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 *\n ***************************************************************************\/\n\n#ifndef ONLINE_DETERMINATE_HPP\n#define ONLINE_DETERMINATE_HPP\n\n#include <boost\/call_traits.hpp>\n#include <boost\/range\/begin.hpp>\n#include <boost\/range\/end.hpp>\n#include <boost\/range\/const_iterator.hpp>\n#include <kml\/determinate.hpp>\n\nnamespace kml {\n\n\n\ntemplate< typename Input,typename Output,template<typename,int> class Kernel >\nclass online_determinate: public determinate<Input,Output,Kernel> {\npublic:\n typedef Kernel<Input,0> kernel_type;\n typedef typename kernel_result<kernel_type>::type result_type;\n typedef determinate<Input,Output,Kernel> base_type;\n typedef Input input_type;\n typedef Output output_type;\n\n \/\/ constructor\n online_determinate( typename boost::call_traits<kernel_type>::param_type k ):\n base_type(k) {}\n\n \/\/ works for any Single Pass Range\n template<typename InputRange, typename OutputRange>\n void learn( InputRange const &input, OutputRange const &output ) {\n typename boost::range_const_iterator<InputRange>::type input_iter( boost::const_begin(input) );\n typename boost::range_const_iterator<OutputRange>::type output_iter( boost::const_begin(output) );\n for( ; input_iter != boost::const_end(input); ++input_iter, ++output_iter )\n push_back( *input_iter, *output_iter );\n }\n\n \/\/ pure virtual\n virtual void push_back( input_type const &input, output_type const &output ) = 0;\n\n};\n\n\n\n\n\n\n\n\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* KPilot\n**\n** Copyright (C) 2001 by Dan Pilone\n** Copyright (C) 2001,2002,2003,2004 by Adriaan de Groot\n**\n** This is the main program for kpilotTest, which shows a SyncLog and\n** exercises the KPilotDeviceLink class. It's intended to test if the\n** Palm hardware and the KPilot software are functioning correctly to\n** some extent.\n*\/\n\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; 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. 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 in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n** MA 02110-1301, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org.\n*\/\nstatic const char *test_id =\n\t\"$Id$\";\n\n#include \"options.h\"\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n\n#include <qpushbutton.h>\n#include <qhbox.h>\n#include <qtimer.h>\n\n#include <kapplication.h>\n#include <klocale.h>\n#include <kaboutdata.h>\n#include <kcmdlineargs.h>\n#include <kservice.h>\n#include <kservicetype.h>\n#include <kuserprofile.h>\n\n#include <pi-version.h>\n\n#include \"logWidget.h\"\n#include \"kpilotConfig.h\"\n#include \"syncStack.h\"\n#include \"hotSync.h\"\n#include \"interactiveSync.h\"\n\nstatic KCmdLineOptions kpilotoptions[] = {\n\t{\"p\",0,0},\n\t{\"port <device>\",\n\t\tI18N_NOOP(\"Path to Pilot device node\"),\n\t\t\"\/dev\/pilot\"},\n\t{\"l\",0,0},\n\t{\"list\", I18N_NOOP(\"List DBs (default)\"), 0},\n\t{\"b\",0,0},\n\t{\"backup\", I18N_NOOP(\"Backup instead of list DBs\"), 0},\n\t{\"r\",0,0},\n\t{\"restore\", I18N_NOOP(\"Restore Pilot from backup\"), 0},\n\t{\"L\",0,0},\n\t{ \"conduit-list\", I18N_NOOP(\"List available conduits\"), 0},\n\t{\"E\",0,0},\n\t{ \"conduit-exec <filename>\",\n\t\tI18N_NOOP(\"Run conduit from desktop file <filename>\"),\n\t\t0 },\n\t{ \"T\",0,0},\n\t{ \"notest\",\n\t\tI18N_NOOP(\"*Really* run the conduit, not in test mode.\"),\n\t\t0 } ,\n\t{ \"F\",0,0},\n\t{ \"local\",\n\t\tI18N_NOOP(\"Run the conduit in file-test mode.\"),\n\t\t0 } ,\n\t{ \"HHtoPC\",\n\t\tI18N_NOOP(\"Copy Pilot to Desktop.\"),\n\t\t0 } ,\n\t{ \"PCtoHH\",\n\t\tI18N_NOOP(\"Copy Desktop to Pilot.\"),\n\t\t0 } ,\n\t{ \"test-timeout\",\n\t\tI18N_NOOP(\"Run conduit specially designed to timeout.\"),\n\t\t0 } ,\n\t{ \"test-usercheck\",\n\t\tI18N_NOOP(\"Run conduit just for user check.\"),\n\t\t0 } ,\n\t{ \"dump-calendar\",\n\t\tI18N_NOOP(\"Dump calendar to stdout.\"),\n\t\t0 } ,\n#ifdef DEBUG\n\t{\"debug <level>\", I18N_NOOP(\"Set debugging level\"), \"0\"},\n#endif\n\tKCmdLineLastOption\n};\n\n\nstatic LogWidget *logWidget = 0L;\nstatic QPushButton *resetButton = 0L;\n\n\n\n\/**\n*** Conduits - sync actions - for testing specific scenarios.\n**\/\n\nclass TimeoutAction : public SyncAction\n{\npublic:\n\tTimeoutAction(KPilotDeviceLink *p) ;\nprotected:\n\tvirtual bool exec();\n} ;\n\nTimeoutAction::TimeoutAction(KPilotDeviceLink *p) :\n\tSyncAction(p)\n{\n\tFUNCTIONSETUP;\n}\n\nbool TimeoutAction::exec()\n{\n\tFUNCTIONSETUP;\n\n\tfor (int i = 0; i<3; i++)\n\t{\n\t\tlogMessage( CSL1(\"Hup two %1\").arg(i) );\n\t\tfHandle->tickle();\n\t\tqApp->processEvents();\n\t\tsleep(1);\n\t}\n\n\tlogMessage( CSL1(\"Now sleeping 65\") );\n\tqApp->processEvents();\n\tsleep(65);\n\treturn delayDone();\n}\n\n\n\n\n\n\n\nvoid createLogWidget()\n{\n\tLogWidget *w = new LogWidget(0L);\n\n\tw->resize(300, 300);\n\tw->show();\n\tw->setShowTime(true);\n\tkapp->setMainWidget(w);\n\tlogWidget = w;\n\n\tresetButton = new QPushButton(i18n(\"Reset\"),w->buttonBox());\n}\n\nstatic KPilotDeviceLink *deviceLink = 0L;\n\nvoid createLink()\n{\n\tFUNCTIONSETUP;\n\n\tdeviceLink = new KPilotDeviceLink(0, \"deviceLink\");\n\n\tQObject::connect(deviceLink, SIGNAL(logError(const QString &)),\n\t\tlogWidget, SLOT(addError(const QString &)));\n\tQObject::connect(deviceLink, SIGNAL(logMessage(const QString &)),\n\t\tlogWidget, SLOT(addMessage(const QString &)));\n\tQObject::connect(deviceLink,SIGNAL(logProgress(const QString &,int)),\n\t\tlogWidget, SLOT(addProgress(const QString &,int)));\n\n}\n\nstatic ActionQueue *syncStack = 0L;\n\nvoid connectStack()\n{\n\tFUNCTIONSETUP;\n\n\tQObject::connect(syncStack, SIGNAL(logError(const QString &)),\n\t\tlogWidget, SLOT(addError(const QString &)));\n\tQObject::connect(syncStack, SIGNAL(logMessage(const QString &)),\n\t\tlogWidget, SLOT(addMessage(const QString &)));\n\tQObject::connect(syncStack,SIGNAL(logProgress(const QString &,int)),\n\t\tlogWidget, SLOT(addProgress(const QString &,int)));\n\n\tQObject::connect(deviceLink, SIGNAL(deviceReady(KPilotDeviceLink*)), syncStack, SLOT(execConduit()));\n\n\tQObject::connect(syncStack, SIGNAL(syncDone(SyncAction *)),\n\t\tlogWidget, SLOT(syncDone()));\n\tQObject::connect(syncStack, SIGNAL(syncDone(SyncAction *)),\n\t\tdeviceLink, SLOT(close()));\n\n\tQObject::connect(resetButton,SIGNAL(clicked()),deviceLink,SLOT(reset()));\n}\n\nvoid createConnection(KCmdLineArgs *p)\n{\n\tFUNCTIONSETUP;\n\n\tQString devicePath = p->getOption(\"port\");\n\n\tif (devicePath.isEmpty())\n\t{\n\t\tdevicePath = \"\/dev\/pilot\";\n\t}\n\n\tdeviceLink->reset(devicePath);\n}\n\nint syncTest(KCmdLineArgs *p)\n{\n\tFUNCTIONSETUP;\n\n\tcreateLogWidget();\n\tcreateLink();\n\n\tsyncStack = new ActionQueue(deviceLink);\n\n\tif (p->isSet(\"backup\"))\n\t{\n\t\tsyncStack->queueInit();\n\t\tsyncStack->addAction(new BackupAction(deviceLink,true));\n\t}\n\telse if (p->isSet(\"restore\"))\n\t{\n\t\tsyncStack->queueInit(0);\n\t\tsyncStack->addAction(new RestoreAction(deviceLink));\n\t}\n\telse if (p->isSet(\"test-timeout\"))\n\t{\n\t\tsyncStack->queueInit();\n\t\tsyncStack->addAction( new TimeoutAction(deviceLink) );\n\t\tsyncStack->addAction( new TimeoutAction(deviceLink) );\n\t}\n\telse\n\t{\n\t\tsyncStack->queueInit(p->isSet(\"test-usercheck\") \/* whether to run usercheck *\/);\n\t\tsyncStack->addAction(new TestLink(deviceLink));\n\t}\n\tsyncStack->queueCleanup();\n\n\tconnectStack();\n\tcreateConnection(p);\n\treturn kapp->exec();\n}\n\nint execConduit(KCmdLineArgs *p)\n{\n\tFUNCTIONSETUP;\n\n\t\/\/ get --exec-conduit value\n\tQString s = p->getOption(\"conduit-exec\");\n\tif (s.isEmpty()) return 1;\n\tQStringList l;\n\tl.append(s);\n\n\tcreateLogWidget();\n\tcreateLink();\n\n\tSyncAction::SyncMode::Mode syncMode = SyncAction::SyncMode::eHotSync;\n\tif (p->isSet(\"HHtoPC\")) syncMode = SyncAction::SyncMode::eCopyHHToPC;\n\tif (p->isSet(\"PCtoHH\")) syncMode = SyncAction::SyncMode::eCopyPCToHH;\n\n\tSyncAction::SyncMode mode(syncMode,p->isSet(\"test\"),p->isSet(\"local\"));\n\tsyncStack = new ActionQueue(deviceLink);\n\tsyncStack->queueInit();\n\tsyncStack->queueConduits(l,mode,false);\n\tsyncStack->queueCleanup();\n\n\tconnectStack();\n\tcreateConnection(p);\n\n\treturn kapp->exec();\n}\n\nint listConduits(KCmdLineArgs *)\n{\n\tFUNCTIONSETUP;\n\n\tKServiceTypeProfile::OfferList offers =\n\t\tKServiceTypeProfile::offers(CSL1(\"KPilotConduit\"));\n\n\t\/\/ Now actually fill the two list boxes, just make\n\t\/\/ sure that nothing gets listed in both.\n\t\/\/\n\t\/\/\n\tQValueListIterator < KServiceOffer > availList(offers.begin());\n\twhile (availList != offers.end())\n\t{\n\t\tKSharedPtr < KService > o = (*availList).service();\n\n\t\tstd::cout << o->desktopEntryName().latin1() << std::endl;\n\t\tstd::cout << \"\\t\" << o->name().latin1() << std::endl;\n\t\tif (!o->library().isEmpty())\n\t\t{\n\t\t\tstd::cout << \"\\tIn \"\n\t\t\t\t<< o->library().latin1()\n\t\t\t\t<< std::endl;\n\t\t}\n\n\t\t++availList;\n\t}\n\n\treturn 0;\n}\n\nint main(int argc, char **argv)\n{\n\tFUNCTIONSETUP;\n\tKAboutData about(\"kpilotTest\",\n\t\tI18N_NOOP(\"KPilotTest\"),\n\t\tKPILOT_VERSION,\n\t\t\"KPilot Tester\",\n\t\tKAboutData::License_GPL, \"(C) 2001-2004, Adriaan de Groot\");\n\tabout.addAuthor(\"Adriaan de Groot\",\n\t\tI18N_NOOP(\"KPilot Maintainer\"),\n\t\t\"groot@kde.org\", \"http:\/\/www.cs.kun.nl\/~adridg\/kpilot\/\");\n\n\tKCmdLineArgs::init(argc, argv, &about);\n\tKCmdLineArgs::addCmdLineOptions(kpilotoptions, \"kpilottest\");\n\tKApplication::addCmdLineOptions();\n\n\tKCmdLineArgs *p = KCmdLineArgs::parsedArgs();\n\n\n\tKApplication a;\n#ifdef DEBUG\n\tKPilotConfig::getDebugLevel(p);\n#endif\n\n\tif ( p->isSet(\"backup\") ||\n\t\tp->isSet(\"restore\") ||\n\t\tp->isSet(\"list\") ||\n\t\tp->isSet(\"test-timeout\") ||\n\t\tp->isSet(\"test-usercheck\") )\n\t{\n\t\treturn syncTest(p);\n\t}\n\n\tif (p->isSet(\"conduit-list\"))\n\t{\n\t\treturn listConduits(p);\n\t}\n\n\tif (p->isSet(\"conduit-exec\"))\n\t{\n\t\treturn execConduit(p);\n\t}\n\n\t\/\/ The default is supposed to be \"list\"\n\treturn syncTest(p);\n\t\/* NOTREACHED *\/\n\t(void) test_id;\n}\n\n\n<commit_msg>Start supporting --local again. You can mix --local with --exec-conduit and it won't crash immediately.<commit_after>\/* KPilot\n**\n** Copyright (C) 2001 by Dan Pilone\n** Copyright (C) 2001,2002,2003,2004 by Adriaan de Groot\n**\n** This is the main program for kpilotTest, which shows a SyncLog and\n** exercises the KPilotDeviceLink class. It's intended to test if the\n** Palm hardware and the KPilot software are functioning correctly to\n** some extent.\n*\/\n\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; 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. 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 in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n** MA 02110-1301, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org.\n*\/\nstatic const char *test_id =\n\t\"$Id$\";\n\n#include \"options.h\"\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n\n#include <qpushbutton.h>\n#include <qhbox.h>\n#include <qtimer.h>\n\n#include <kapplication.h>\n#include <klocale.h>\n#include <kaboutdata.h>\n#include <kcmdlineargs.h>\n#include <kservice.h>\n#include <kservicetype.h>\n#include <kuserprofile.h>\n\n#include <pi-version.h>\n\n#include \"logWidget.h\"\n#include \"kpilotConfig.h\"\n#include \"syncStack.h\"\n#include \"hotSync.h\"\n#include \"interactiveSync.h\"\n\nstatic KCmdLineOptions kpilotoptions[] = {\n\t{\"p\",0,0},\n\t{\"port <device>\",\n\t\tI18N_NOOP(\"Path to Pilot device node\"),\n\t\t\"\/dev\/pilot\"},\n\t{\"l\",0,0},\n\t{\"list\", I18N_NOOP(\"List DBs (default)\"), 0},\n\t{\"b\",0,0},\n\t{\"backup\", I18N_NOOP(\"Backup instead of list DBs\"), 0},\n\t{\"r\",0,0},\n\t{\"restore\", I18N_NOOP(\"Restore Pilot from backup\"), 0},\n\t{\"L\",0,0},\n\t{ \"conduit-list\", I18N_NOOP(\"List available conduits\"), 0},\n\t{\"E\",0,0},\n\t{ \"conduit-exec <filename>\",\n\t\tI18N_NOOP(\"Run conduit from desktop file <filename>\"),\n\t\t0 },\n\t{ \"T\",0,0},\n\t{ \"notest\",\n\t\tI18N_NOOP(\"*Really* run the conduit, not in test mode.\"),\n\t\t0 } ,\n\t{ \"F\",0,0},\n\t{ \"local\",\n\t\tI18N_NOOP(\"Run the conduit in file-test mode.\"),\n\t\t0 } ,\n\t{ \"HHtoPC\",\n\t\tI18N_NOOP(\"Copy Pilot to Desktop.\"),\n\t\t0 } ,\n\t{ \"PCtoHH\",\n\t\tI18N_NOOP(\"Copy Desktop to Pilot.\"),\n\t\t0 } ,\n\t{ \"test-timeout\",\n\t\tI18N_NOOP(\"Run conduit specially designed to timeout.\"),\n\t\t0 } ,\n\t{ \"test-usercheck\",\n\t\tI18N_NOOP(\"Run conduit just for user check.\"),\n\t\t0 } ,\n\t{ \"dump-calendar\",\n\t\tI18N_NOOP(\"Dump calendar to stdout.\"),\n\t\t0 } ,\n#ifdef DEBUG\n\t{\"debug <level>\", I18N_NOOP(\"Set debugging level\"), \"0\"},\n#endif\n\tKCmdLineLastOption\n};\n\n\nstatic LogWidget *logWidget = 0L;\nstatic QPushButton *resetButton = 0L;\n\n\n\n\/**\n*** Conduits - sync actions - for testing specific scenarios.\n**\/\n\nclass TimeoutAction : public SyncAction\n{\npublic:\n\tTimeoutAction(KPilotDeviceLink *p) ;\nprotected:\n\tvirtual bool exec();\n} ;\n\nTimeoutAction::TimeoutAction(KPilotDeviceLink *p) :\n\tSyncAction(p)\n{\n\tFUNCTIONSETUP;\n}\n\nbool TimeoutAction::exec()\n{\n\tFUNCTIONSETUP;\n\n\tfor (int i = 0; i<3; i++)\n\t{\n\t\tlogMessage( CSL1(\"Hup two %1\").arg(i) );\n\t\tfHandle->tickle();\n\t\tqApp->processEvents();\n\t\tsleep(1);\n\t}\n\n\tlogMessage( CSL1(\"Now sleeping 65\") );\n\tqApp->processEvents();\n\tsleep(65);\n\treturn delayDone();\n}\n\n\n\n\n\n\n\nvoid createLogWidget()\n{\n\tLogWidget *w = new LogWidget(0L);\n\n\tw->resize(300, 300);\n\tw->show();\n\tw->setShowTime(true);\n\tkapp->setMainWidget(w);\n\tlogWidget = w;\n\n\tresetButton = new QPushButton(i18n(\"Reset\"),w->buttonBox());\n}\n\nstatic KPilotDeviceLink *deviceLink = 0L;\n\nvoid createLink()\n{\n\tFUNCTIONSETUP;\n\n\tdeviceLink = new KPilotDeviceLink(0, \"deviceLink\");\n\n\tQObject::connect(deviceLink, SIGNAL(logError(const QString &)),\n\t\tlogWidget, SLOT(addError(const QString &)));\n\tQObject::connect(deviceLink, SIGNAL(logMessage(const QString &)),\n\t\tlogWidget, SLOT(addMessage(const QString &)));\n\tQObject::connect(deviceLink,SIGNAL(logProgress(const QString &,int)),\n\t\tlogWidget, SLOT(addProgress(const QString &,int)));\n\n}\n\nstatic ActionQueue *syncStack = 0L;\n\nvoid connectStack()\n{\n\tFUNCTIONSETUP;\n\n\tQObject::connect(syncStack, SIGNAL(logError(const QString &)),\n\t\tlogWidget, SLOT(addError(const QString &)));\n\tQObject::connect(syncStack, SIGNAL(logMessage(const QString &)),\n\t\tlogWidget, SLOT(addMessage(const QString &)));\n\tQObject::connect(syncStack,SIGNAL(logProgress(const QString &,int)),\n\t\tlogWidget, SLOT(addProgress(const QString &,int)));\n\tQObject::connect(syncStack, SIGNAL(syncDone(SyncAction *)),\n\t\tlogWidget, SLOT(syncDone()));\n\n\tif (deviceLink)\n\t{\n\t\tQObject::connect(syncStack, SIGNAL(syncDone(SyncAction *)),\n\t\t\tdeviceLink, SLOT(close()));\n\t\tQObject::connect(deviceLink, SIGNAL(deviceReady(KPilotDeviceLink*)), syncStack, SLOT(execConduit()));\n\t\tQObject::connect(resetButton,SIGNAL(clicked()),deviceLink,SLOT(reset()));\n\t}\n}\n\nvoid createConnection(KCmdLineArgs *p)\n{\n\tFUNCTIONSETUP;\n\n\tQString devicePath = p->getOption(\"port\");\n\n\tif (devicePath.isEmpty())\n\t{\n\t\tdevicePath = \"\/dev\/pilot\";\n\t}\n\n\tdeviceLink->reset(devicePath);\n}\n\nint syncTest(KCmdLineArgs *p)\n{\n\tFUNCTIONSETUP;\n\n\tcreateLogWidget();\n\tcreateLink();\n\n\tsyncStack = new ActionQueue(deviceLink);\n\n\tif (p->isSet(\"backup\"))\n\t{\n\t\tsyncStack->queueInit();\n\t\tsyncStack->addAction(new BackupAction(deviceLink,true));\n\t}\n\telse if (p->isSet(\"restore\"))\n\t{\n\t\tsyncStack->queueInit(0);\n\t\tsyncStack->addAction(new RestoreAction(deviceLink));\n\t}\n\telse if (p->isSet(\"test-timeout\"))\n\t{\n\t\tsyncStack->queueInit();\n\t\tsyncStack->addAction( new TimeoutAction(deviceLink) );\n\t\tsyncStack->addAction( new TimeoutAction(deviceLink) );\n\t}\n\telse\n\t{\n\t\tsyncStack->queueInit(p->isSet(\"test-usercheck\") \/* whether to run usercheck *\/);\n\t\tsyncStack->addAction(new TestLink(deviceLink));\n\t}\n\tsyncStack->queueCleanup();\n\n\tconnectStack();\n\tcreateConnection(p);\n\treturn kapp->exec();\n}\n\nint execConduit(KCmdLineArgs *p)\n{\n\tFUNCTIONSETUP;\n\n\t\/\/ get --exec-conduit value\n\tQString s = p->getOption(\"conduit-exec\");\n\tif (s.isEmpty()) return 1;\n\tQStringList l;\n\tl.append(s);\n\n\tcreateLogWidget();\n\n\tSyncAction::SyncMode::Mode syncMode = SyncAction::SyncMode::eHotSync;\n\tif (p->isSet(\"HHtoPC\")) syncMode = SyncAction::SyncMode::eCopyHHToPC;\n\tif (p->isSet(\"PCtoHH\")) syncMode = SyncAction::SyncMode::eCopyPCToHH;\n\tSyncAction::SyncMode mode(syncMode,p->isSet(\"test\"),p->isSet(\"local\"));\n\n\tif (!p->isSet(\"local\"))\n\t{\n\t\tcreateLink();\n\n\t\tsyncStack = new ActionQueue(deviceLink);\n\t\tsyncStack->queueInit();\n\t\tsyncStack->queueConduits(l,mode,false);\n\t\tsyncStack->queueCleanup();\n\t\tconnectStack();\n\t\tcreateConnection(p);\n\t}\n\telse\n\t{\n\t\tsyncStack = new ActionQueue( 0L );\n\t\tsyncStack->queueInit();\n\t\tsyncStack->queueConduits(l,mode,false);\n\t\tsyncStack->queueCleanup();\n\t\tconnectStack();\n\t\tQTimer::singleShot(100,syncStack,SLOT(execConduit()));\n\t}\n\n\n\treturn kapp->exec();\n}\n\nint listConduits(KCmdLineArgs *)\n{\n\tFUNCTIONSETUP;\n\n\tKServiceTypeProfile::OfferList offers =\n\t\tKServiceTypeProfile::offers(CSL1(\"KPilotConduit\"));\n\n\t\/\/ Now actually fill the two list boxes, just make\n\t\/\/ sure that nothing gets listed in both.\n\t\/\/\n\t\/\/\n\tQValueListIterator < KServiceOffer > availList(offers.begin());\n\twhile (availList != offers.end())\n\t{\n\t\tKSharedPtr < KService > o = (*availList).service();\n\n\t\tstd::cout << o->desktopEntryName().latin1() << std::endl;\n\t\tstd::cout << \"\\t\" << o->name().latin1() << std::endl;\n\t\tif (!o->library().isEmpty())\n\t\t{\n\t\t\tstd::cout << \"\\tIn \"\n\t\t\t\t<< o->library().latin1()\n\t\t\t\t<< std::endl;\n\t\t}\n\n\t\t++availList;\n\t}\n\n\treturn 0;\n}\n\nint main(int argc, char **argv)\n{\n\tFUNCTIONSETUP;\n\tKAboutData about(\"kpilotTest\",\n\t\tI18N_NOOP(\"KPilotTest\"),\n\t\tKPILOT_VERSION,\n\t\t\"KPilot Tester\",\n\t\tKAboutData::License_GPL, \"(C) 2001-2004, Adriaan de Groot\");\n\tabout.addAuthor(\"Adriaan de Groot\",\n\t\tI18N_NOOP(\"KPilot Maintainer\"),\n\t\t\"groot@kde.org\", \"http:\/\/www.cs.kun.nl\/~adridg\/kpilot\/\");\n\n\tKCmdLineArgs::init(argc, argv, &about);\n\tKCmdLineArgs::addCmdLineOptions(kpilotoptions, \"kpilottest\");\n\tKApplication::addCmdLineOptions();\n\n\tKCmdLineArgs *p = KCmdLineArgs::parsedArgs();\n\n\n\tKApplication a;\n#ifdef DEBUG\n\tKPilotConfig::getDebugLevel(p);\n#endif\n\n\tif ( p->isSet(\"backup\") ||\n\t\tp->isSet(\"restore\") ||\n\t\tp->isSet(\"list\") ||\n\t\tp->isSet(\"test-timeout\") ||\n\t\tp->isSet(\"test-usercheck\") )\n\t{\n\t\treturn syncTest(p);\n\t}\n\n\tif (p->isSet(\"conduit-list\"))\n\t{\n\t\treturn listConduits(p);\n\t}\n\n\tif (p->isSet(\"conduit-exec\"))\n\t{\n\t\treturn execConduit(p);\n\t}\n\n\t\/\/ The default is supposed to be \"list\"\n\treturn syncTest(p);\n\t\/* NOTREACHED *\/\n\t(void) test_id;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/==-- llvm\/Support\/ThreadPool.cpp - A ThreadPool implementation -*- C++ -*-==\/\/\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\/\/ This file implements a crude C++11 based thread pool.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/ThreadPool.h\"\n\n#include \"llvm\/Config\/llvm-config.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\n#if LLVM_ENABLE_THREADS\n\n\/\/ Default to std::thread::hardware_concurrency\nThreadPool::ThreadPool() : ThreadPool(std::thread::hardware_concurrency()) {}\n\nThreadPool::ThreadPool(unsigned ThreadCount)\n : ActiveThreads(0), EnableFlag(true) {\n \/\/ Create ThreadCount threads that will loop forever, wait on QueueCondition\n \/\/ for tasks to be queued or the Pool to be destroyed.\n Threads.reserve(ThreadCount);\n for (unsigned ThreadID = 0; ThreadID < ThreadCount; ++ThreadID) {\n Threads.emplace_back([&] {\n while (true) {\n PackagedTaskTy Task;\n {\n std::unique_lock<std::mutex> LockGuard(QueueLock);\n \/\/ Wait for tasks to be pushed in the queue\n QueueCondition.wait(LockGuard,\n [&] { return !EnableFlag || !Tasks.empty(); });\n \/\/ Exit condition\n if (!EnableFlag && Tasks.empty())\n return;\n \/\/ Yeah, we have a task, grab it and release the lock on the queue\n\n \/\/ We first need to signal that we are active before popping the queue\n \/\/ in order for wait() to properly detect that even if the queue is\n \/\/ empty, there is still a task in flight.\n {\n ++ActiveThreads;\n std::unique_lock<std::mutex> LockGuard(CompletionLock);\n }\n Task = std::move(Tasks.front());\n Tasks.pop();\n }\n \/\/ Run the task we just grabbed\n#ifndef _MSC_VER\n Task();\n#else\n Task(\/* unused *\/ false);\n#endif\n\n {\n \/\/ Adjust `ActiveThreads`, in case someone waits on ThreadPool::wait()\n std::unique_lock<std::mutex> LockGuard(CompletionLock);\n --ActiveThreads;\n }\n\n \/\/ Notify task completion, in case someone waits on ThreadPool::wait()\n CompletionCondition.notify_all();\n }\n });\n }\n}\n\nvoid ThreadPool::wait() {\n \/\/ Wait for all threads to complete and the queue to be empty\n std::unique_lock<std::mutex> LockGuard(CompletionLock);\n \/\/ The order of the checks for ActiveThreads and Tasks.empty() matters because\n \/\/ any active threads might be modifying the Tasks queue, and this would be a\n \/\/ race.\n CompletionCondition.wait(LockGuard,\n [&] { return !ActiveThreads && Tasks.empty(); });\n}\n\nstd::shared_future<ThreadPool::VoidTy> ThreadPool::asyncImpl(TaskTy Task) {\n \/\/\/ Wrap the Task in a packaged_task to return a future object.\n PackagedTaskTy PackagedTask(std::move(Task));\n auto Future = PackagedTask.get_future();\n {\n \/\/ Lock the queue and push the new task\n std::unique_lock<std::mutex> LockGuard(QueueLock);\n\n \/\/ Don't allow enqueueing after disabling the pool\n assert(EnableFlag && \"Queuing a thread during ThreadPool destruction\");\n\n Tasks.push(std::move(PackagedTask));\n }\n QueueCondition.notify_one();\n return Future.share();\n}\n\n\/\/ The destructor joins all threads, waiting for completion.\nThreadPool::~ThreadPool() {\n {\n std::unique_lock<std::mutex> LockGuard(QueueLock);\n EnableFlag = false;\n }\n QueueCondition.notify_all();\n for (auto &Worker : Threads)\n Worker.join();\n}\n\n#else \/\/ LLVM_ENABLE_THREADS Disabled\n\nThreadPool::ThreadPool() : ThreadPool(0) {}\n\n\/\/ No threads are launched, issue a warning if ThreadCount is not 0\nThreadPool::ThreadPool(unsigned ThreadCount)\n : ActiveThreads(0) {\n if (ThreadCount) {\n errs() << \"Warning: request a ThreadPool with \" << ThreadCount\n << \" threads, but LLVM_ENABLE_THREADS has been turned off\\n\";\n }\n}\n\nvoid ThreadPool::wait() {\n \/\/ Sequential implementation running the tasks\n while (!Tasks.empty()) {\n auto Task = std::move(Tasks.front());\n Tasks.pop();\n#ifndef _MSC_VER\n Task();\n#else\n Task(\/* unused *\/ false);\n#endif\n }\n}\n\nstd::shared_future<ThreadPool::VoidTy> ThreadPool::asyncImpl(TaskTy Task) {\n#ifndef _MSC_VER\n \/\/ Get a Future with launch::deferred execution using std::async\n auto Future = std::async(std::launch::deferred, std::move(Task)).share();\n \/\/ Wrap the future so that both ThreadPool::wait() can operate and the\n \/\/ returned future can be sync'ed on.\n PackagedTaskTy PackagedTask([Future]() { Future.get(); });\n#else\n auto Future = std::async(std::launch::deferred, std::move(Task), false).share();\n PackagedTaskTy PackagedTask([Future](bool) -> bool { Future.get(); return false; });\n#endif\n Tasks.push(std::move(PackagedTask));\n return Future;\n}\n\nThreadPool::~ThreadPool() {\n wait();\n}\n\n#endif\n<commit_msg>Add whitespace to check commit access<commit_after>\/\/==-- llvm\/Support\/ThreadPool.cpp - A ThreadPool implementation -*- C++ -*-==\/\/\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\/\/ This file implements a crude C++11 based thread pool.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/ThreadPool.h\"\n\n#include \"llvm\/Config\/llvm-config.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\n#if LLVM_ENABLE_THREADS\n\n\/\/ Default to std::thread::hardware_concurrency\nThreadPool::ThreadPool() : ThreadPool(std::thread::hardware_concurrency()) {}\n\nThreadPool::ThreadPool(unsigned ThreadCount)\n : ActiveThreads(0), EnableFlag(true) {\n \/\/ Create ThreadCount threads that will loop forever, wait on QueueCondition\n \/\/ for tasks to be queued or the Pool to be destroyed.\n Threads.reserve(ThreadCount);\n for (unsigned ThreadID = 0; ThreadID < ThreadCount; ++ThreadID) {\n Threads.emplace_back([&] {\n while (true) {\n PackagedTaskTy Task;\n {\n std::unique_lock<std::mutex> LockGuard(QueueLock);\n \/\/ Wait for tasks to be pushed in the queue\n QueueCondition.wait(LockGuard,\n [&] { return !EnableFlag || !Tasks.empty(); });\n \/\/ Exit condition\n if (!EnableFlag && Tasks.empty())\n return;\n \/\/ Yeah, we have a task, grab it and release the lock on the queue\n\n \/\/ We first need to signal that we are active before popping the queue\n \/\/ in order for wait() to properly detect that even if the queue is\n \/\/ empty, there is still a task in flight.\n {\n ++ActiveThreads;\n std::unique_lock<std::mutex> LockGuard(CompletionLock);\n }\n Task = std::move(Tasks.front());\n Tasks.pop();\n }\n \/\/ Run the task we just grabbed\n#ifndef _MSC_VER\n Task();\n#else\n Task(\/* unused *\/ false);\n#endif\n\n {\n \/\/ Adjust `ActiveThreads`, in case someone waits on ThreadPool::wait()\n std::unique_lock<std::mutex> LockGuard(CompletionLock);\n --ActiveThreads;\n }\n\n \/\/ Notify task completion, in case someone waits on ThreadPool::wait()\n CompletionCondition.notify_all();\n }\n });\n }\n}\n\nvoid ThreadPool::wait() {\n \/\/ Wait for all threads to complete and the queue to be empty\n std::unique_lock<std::mutex> LockGuard(CompletionLock);\n \/\/ The order of the checks for ActiveThreads and Tasks.empty() matters because\n \/\/ any active threads might be modifying the Tasks queue, and this would be a\n \/\/ race.\n CompletionCondition.wait(LockGuard,\n [&] { return !ActiveThreads && Tasks.empty(); });\n}\n\nstd::shared_future<ThreadPool::VoidTy> ThreadPool::asyncImpl(TaskTy Task) {\n \/\/\/ Wrap the Task in a packaged_task to return a future object.\n PackagedTaskTy PackagedTask(std::move(Task));\n auto Future = PackagedTask.get_future();\n {\n \/\/ Lock the queue and push the new task\n std::unique_lock<std::mutex> LockGuard(QueueLock);\n\n \/\/ Don't allow enqueueing after disabling the pool\n assert(EnableFlag && \"Queuing a thread during ThreadPool destruction\");\n\n Tasks.push(std::move(PackagedTask));\n }\n QueueCondition.notify_one();\n return Future.share();\n}\n\n\/\/ The destructor joins all threads, waiting for completion.\nThreadPool::~ThreadPool() {\n {\n std::unique_lock<std::mutex> LockGuard(QueueLock);\n EnableFlag = false;\n }\n QueueCondition.notify_all();\n for (auto &Worker : Threads)\n Worker.join();\n}\n\n#else \/\/ LLVM_ENABLE_THREADS Disabled\n\nThreadPool::ThreadPool() : ThreadPool(0) {}\n\n\/\/ No threads are launched, issue a warning if ThreadCount is not 0\nThreadPool::ThreadPool(unsigned ThreadCount)\n : ActiveThreads(0) {\n if (ThreadCount) {\n errs() << \"Warning: request a ThreadPool with \" << ThreadCount\n << \" threads, but LLVM_ENABLE_THREADS has been turned off\\n\";\n }\n}\n\nvoid ThreadPool::wait() {\n \/\/ Sequential implementation running the tasks\n while (!Tasks.empty()) {\n auto Task = std::move(Tasks.front());\n Tasks.pop();\n#ifndef _MSC_VER\n Task();\n#else\n Task(\/* unused *\/ false);\n#endif\n }\n}\n\nstd::shared_future<ThreadPool::VoidTy> ThreadPool::asyncImpl(TaskTy Task) {\n#ifndef _MSC_VER\n \/\/ Get a Future with launch::deferred execution using std::async\n auto Future = std::async(std::launch::deferred, std::move(Task)).share();\n \/\/ Wrap the future so that both ThreadPool::wait() can operate and the\n \/\/ returned future can be sync'ed on.\n PackagedTaskTy PackagedTask([Future]() { Future.get(); });\n#else\n auto Future = std::async(std::launch::deferred, std::move(Task), false).share();\n PackagedTaskTy PackagedTask([Future](bool) -> bool { Future.get(); return false; });\n#endif\n Tasks.push(std::move(PackagedTask));\n return Future;\n}\n\nThreadPool::~ThreadPool() {\n wait();\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n This is an example file shipped by 'Aleph - A Library for Exploring\n Persistent Homology'.\n\n This example demonstrates how to create random persistence diagrams\n that may be used to compare topological algorithms with each other,\n such as persistence indicator functions and Wasserstein distances.\n\n Demonstrated classes:\n\n - aleph::distances::Euclidean\n - aleph::geometry::BruteForce\n - aleph::PersistenceDiagram\n\n Demonstrated functions:\n\n - aleph::calculatePersistenceDiagrams\n - aleph::geometry::buildVietorisRipsComplex\n - aleph::geometry::makeSphere\n - aleph::geometry::makeTorus\n - aleph::geometry::sphereSampling\n - aleph::geometry::torusRejectionSampling\n\n Original author: Bastian Rieck\n*\/\n\n#include <aleph\/geometry\/BruteForce.hh>\n#include <aleph\/geometry\/SphereSampling.hh>\n#include <aleph\/geometry\/TorusSampling.hh>\n#include <aleph\/geometry\/VietorisRipsComplex.hh>\n\n#include <aleph\/geometry\/distances\/Euclidean.hh>\n\n#include <aleph\/persistenceDiagrams\/PersistenceDiagram.hh>\n\n#include <aleph\/persistentHomology\/Calculation.hh>\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <limits>\n#include <random>\n#include <sstream>\n#include <vector>\n\n#include <cmath>\n\n#include <getopt.h>\n\n\/\/ We first have to specify the data type of the persistence diagram,\n\/\/ i.e. the type that is used by its individual points.\nusing DataType = double;\nusing Distance = aleph::geometry::distances::Euclidean<DataType>;\nusing PointCloud = aleph::containers::PointCloud<DataType>;\nusing PersistenceDiagram = aleph::PersistenceDiagram<DataType>;\n\n\/**\n Auxiliary function for creating a random persistence diagram. Points\n are drawn from a uniform distribution on [0,1]. The function ensures\n that all points are situated _above_ the diagonal.\n*\/\n\nPersistenceDiagram createRandomPersistenceDiagram( unsigned n )\n{\n std::random_device rd;\n std::default_random_engine rng( rd() );\n std::uniform_real_distribution<DataType> distribution( DataType(0), DataType( std::nextafter( DataType(1), std::numeric_limits<DataType>::max() ) ) );\n\n PersistenceDiagram D;\n\n for( unsigned i = 0; i < n; i++ )\n {\n auto x = distribution( rng );\n auto y = distribution( rng );\n\n if( x > y )\n std::swap( x,y );\n\n D.add( x,y );\n }\n\n return D;\n}\n\n\/**\n Auxiliary function for creating random persistence diagrams based on\n random samples from a box with a given length.\n\n Note that this function automatically handles Vietoris--Rips\n expansion.\n*\/\n\nstd::vector<PersistenceDiagram> createRandomBoxPersistenceDiagrams( DataType r, unsigned n, unsigned d = 3 )\n{\n std::random_device rd;\n std::default_random_engine rng( rd() );\n std::uniform_real_distribution<DataType> distribution( DataType(0), DataType( std::nextafter( DataType(r), std::numeric_limits<DataType>::max() ) ) );\n\n PointCloud pointCloud( n, 3 );\n\n for( unsigned i = 0; i < n; i++ )\n {\n auto x = distribution( rng );\n auto y = distribution( rng );\n auto z = distribution( rng );\n\n std::vector<DataType> p = {x,y,z};\n pointCloud.set( i, p.begin(), p.end() );\n }\n\n aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );\n\n auto K\n = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper, 0.7 * r, d );\n\n auto diagrams\n = aleph::calculatePersistenceDiagrams( K );\n\n for( auto&& diagram : diagrams )\n diagram.removeDiagonal();\n\n return diagrams;\n}\n\n\/**\n Auxiliary function for creating a random persistence diagram based on\n random samples from a torus. The torus is described by two radii, one\n for the outer part, the other for the inner part.\n\n Due to the sampling technique used, the specified number is merely an\n upper bound for the number of points that are to be sampled. Moreover\n the function will automatically handle Vietoris--Rips expansion.\n*\/\n\nPersistenceDiagram createRandomTorusPersistenceDiagram( DataType R, DataType r, unsigned n )\n{\n auto pointCloud = aleph::geometry::makeTorus(\n aleph::geometry::torusRejectionSampling( R, r, n ),\n R, r\n );\n\n aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );\n\n auto K\n = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper, 0.5 * R, 2 );\n\n auto diagrams\n = aleph::calculatePersistenceDiagrams( K );\n\n diagrams.at(1).removeDiagonal();\n\n \/\/ We are only interested in the one-dimensional persistent homology\n \/\/ of the samples.\n return diagrams.at(1);\n}\n\n\/**\n Auxiliary function for creating a random persistence diagram based on\n random samples from a sphere with a given radius.\n\n Note that this function automatically handles Vietoris--Rips\n expansion.\n*\/\n\nPersistenceDiagram createRandomSpherePersistenceDiagram( DataType r, unsigned n )\n{\n auto pointCloud = aleph::geometry::makeSphere(\n aleph::geometry::sphereSampling<DataType>( n ),\n r\n );\n\n aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );\n\n auto K\n = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper, r, 2 );\n\n auto diagrams\n = aleph::calculatePersistenceDiagrams( K );\n\n diagrams.at(1).removeDiagonal();\n\n \/\/ We are only interested in the one-dimensional persistent homology\n \/\/ of the samples.\n return diagrams.at(1);\n}\n\nint main( int argc, char** argv )\n{\n static option commandLineOptions[] = {\n { \"m\" , required_argument, nullptr, 'm' },\n { \"n\" , required_argument, nullptr, 'n' },\n { \"R\" , required_argument, nullptr, 'R' },\n { \"r\" , required_argument, nullptr, 'r' },\n { \"d\" , required_argument, nullptr, 'd' },\n { \"box\" , no_argument , nullptr, 'b' },\n { \"sphere\", no_argument , nullptr, 's' },\n { \"torus\" , no_argument , nullptr, 't' },\n { \"output\", no_argument , nullptr, 'o' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n\n unsigned d = 3; \/\/ default dimension to use for expansion\n unsigned m = 50;\n unsigned n = 50;\n DataType R = DataType(0.50);\n DataType r = DataType(0.25);\n\n bool sampleFromBox = false;\n bool sampleFromSphere = false;\n bool sampleFromTorus = false;\n\n bool output = false;\n\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"d:m:n:R:r:bsto\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'd':\n d = static_cast<unsigned>( std::stoul(optarg) );\n break;\n case 'm':\n m = static_cast<unsigned>( std::stoul(optarg) );\n break;\n case 'n':\n n = static_cast<unsigned>( std::stoul(optarg) );\n break;\n case 'R':\n R = static_cast<DataType>( std::stod(optarg) );\n break;\n case 'r':\n r = static_cast<DataType>( std::stod(optarg) );\n break;\n case 'b':\n sampleFromBox = true;\n sampleFromSphere = false;\n sampleFromTorus = false;\n break;\n case 's':\n sampleFromBox = false;\n sampleFromSphere = true;\n sampleFromTorus = false;\n break;\n case 't':\n sampleFromBox = false;\n sampleFromSphere = false;\n sampleFromTorus = true;\n break;\n case 'o':\n output = true;\n break;\n default:\n break;\n }\n }\n\n std::cerr << \"* Sampling \" << n << \" persistence diagrams\\n\";\n if( sampleFromBox )\n std::cerr << \"* Sampling \" << m << \" points from a box with a=\" << r << \"\\n\";\n else if( sampleFromSphere )\n std::cerr << \"* Sampling \" << m << \" points from a sphere with r=\" << r << \"\\n\";\n else if( sampleFromTorus )\n std::cerr << \"* Sampling \" << m << \" points from a torus with R=\" << R << \" and r=\" << r << \"\\n\";\n else\n std::cerr << \"* Generating \" << m << \" random points per diagram\\n\";\n\n for( unsigned i = 0; i < n; i++ )\n {\n std::vector<PersistenceDiagram> pds;\n PersistenceDiagram pd;\n\n if( sampleFromBox )\n pds = createRandomBoxPersistenceDiagrams(r, m, d);\n else if( sampleFromSphere )\n pd = createRandomSpherePersistenceDiagram(r, m);\n else if( sampleFromTorus )\n pd = createRandomTorusPersistenceDiagram(R, r, m);\n else\n pd = createRandomPersistenceDiagram(m);\n\n if( output )\n {\n if( !pds.empty() )\n {\n for( auto&& pd : pds )\n {\n std::stringstream stream;\n stream << \"\/tmp\/\";\n stream << std::setw( static_cast<int>( std::floor( std::log10(n)+1 ) ) ) << std::setfill( '0' ) << i << \"_d\" << pd.dimension();\n stream << \".txt\";\n\n std::ofstream out( stream.str() );\n out << pd << \"\\n\";\n }\n }\n else\n {\n std::stringstream stream;\n stream << \"\/tmp\/\";\n stream << std::setw( static_cast<int>( std::floor( std::log10(n)+1 ) ) ) << std::setfill( '0' ) << i;\n stream << \".txt\";\n\n std::ofstream out( stream.str() );\n out << pd << \"\\n\";\n }\n }\n }\n}\n<commit_msg>Removed obsolete line<commit_after>\/*\n This is an example file shipped by 'Aleph - A Library for Exploring\n Persistent Homology'.\n\n This example demonstrates how to create random persistence diagrams\n that may be used to compare topological algorithms with each other,\n such as persistence indicator functions and Wasserstein distances.\n\n Demonstrated classes:\n\n - aleph::distances::Euclidean\n - aleph::geometry::BruteForce\n - aleph::PersistenceDiagram\n\n Demonstrated functions:\n\n - aleph::calculatePersistenceDiagrams\n - aleph::geometry::buildVietorisRipsComplex\n - aleph::geometry::makeSphere\n - aleph::geometry::makeTorus\n - aleph::geometry::sphereSampling\n - aleph::geometry::torusRejectionSampling\n\n Original author: Bastian Rieck\n*\/\n\n#include <aleph\/geometry\/BruteForce.hh>\n#include <aleph\/geometry\/SphereSampling.hh>\n#include <aleph\/geometry\/TorusSampling.hh>\n#include <aleph\/geometry\/VietorisRipsComplex.hh>\n\n#include <aleph\/geometry\/distances\/Euclidean.hh>\n\n#include <aleph\/persistenceDiagrams\/PersistenceDiagram.hh>\n\n#include <aleph\/persistentHomology\/Calculation.hh>\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <limits>\n#include <random>\n#include <sstream>\n#include <vector>\n\n#include <cmath>\n\n#include <getopt.h>\n\n\/\/ We first have to specify the data type of the persistence diagram,\n\/\/ i.e. the type that is used by its individual points.\nusing DataType = double;\nusing Distance = aleph::geometry::distances::Euclidean<DataType>;\nusing PointCloud = aleph::containers::PointCloud<DataType>;\nusing PersistenceDiagram = aleph::PersistenceDiagram<DataType>;\n\n\/**\n Auxiliary function for creating a random persistence diagram. Points\n are drawn from a uniform distribution on [0,1]. The function ensures\n that all points are situated _above_ the diagonal.\n*\/\n\nPersistenceDiagram createRandomPersistenceDiagram( unsigned n )\n{\n std::random_device rd;\n std::default_random_engine rng( rd() );\n std::uniform_real_distribution<DataType> distribution( DataType(0), DataType( std::nextafter( DataType(1), std::numeric_limits<DataType>::max() ) ) );\n\n PersistenceDiagram D;\n\n for( unsigned i = 0; i < n; i++ )\n {\n auto x = distribution( rng );\n auto y = distribution( rng );\n\n if( x > y )\n std::swap( x,y );\n\n D.add( x,y );\n }\n\n return D;\n}\n\n\/**\n Auxiliary function for creating random persistence diagrams based on\n random samples from a box with a given length.\n\n Note that this function automatically handles Vietoris--Rips\n expansion.\n*\/\n\nstd::vector<PersistenceDiagram> createRandomBoxPersistenceDiagrams( DataType r, unsigned n, unsigned d = 3 )\n{\n std::random_device rd;\n std::default_random_engine rng( rd() );\n std::uniform_real_distribution<DataType> distribution( DataType(0), DataType( std::nextafter( DataType(r), std::numeric_limits<DataType>::max() ) ) );\n\n PointCloud pointCloud( n, 3 );\n\n for( unsigned i = 0; i < n; i++ )\n {\n auto x = distribution( rng );\n auto y = distribution( rng );\n auto z = distribution( rng );\n\n std::vector<DataType> p = {x,y,z};\n pointCloud.set( i, p.begin(), p.end() );\n }\n\n aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );\n\n auto K\n = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper, 0.7 * r, d );\n\n auto diagrams\n = aleph::calculatePersistenceDiagrams( K );\n\n for( auto&& diagram : diagrams )\n diagram.removeDiagonal();\n\n return diagrams;\n}\n\n\/**\n Auxiliary function for creating a random persistence diagram based on\n random samples from a torus. The torus is described by two radii, one\n for the outer part, the other for the inner part.\n\n Due to the sampling technique used, the specified number is merely an\n upper bound for the number of points that are to be sampled. Moreover\n the function will automatically handle Vietoris--Rips expansion.\n*\/\n\nPersistenceDiagram createRandomTorusPersistenceDiagram( DataType R, DataType r, unsigned n )\n{\n auto pointCloud = aleph::geometry::makeTorus(\n aleph::geometry::torusRejectionSampling( R, r, n ),\n R, r\n );\n\n aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );\n\n auto K\n = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper, 0.5 * R, 2 );\n\n auto diagrams\n = aleph::calculatePersistenceDiagrams( K );\n\n diagrams.at(1).removeDiagonal();\n\n \/\/ We are only interested in the one-dimensional persistent homology\n \/\/ of the samples.\n return diagrams.at(1);\n}\n\n\/**\n Auxiliary function for creating a random persistence diagram based on\n random samples from a sphere with a given radius.\n\n Note that this function automatically handles Vietoris--Rips\n expansion.\n*\/\n\nPersistenceDiagram createRandomSpherePersistenceDiagram( DataType r, unsigned n )\n{\n auto pointCloud = aleph::geometry::makeSphere(\n aleph::geometry::sphereSampling<DataType>( n ),\n r\n );\n\n aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );\n\n auto K\n = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper, r, 2 );\n\n auto diagrams\n = aleph::calculatePersistenceDiagrams( K );\n\n diagrams.at(1).removeDiagonal();\n\n \/\/ We are only interested in the one-dimensional persistent homology\n \/\/ of the samples.\n return diagrams.at(1);\n}\n\nint main( int argc, char** argv )\n{\n static option commandLineOptions[] = {\n { \"m\" , required_argument, nullptr, 'm' },\n { \"n\" , required_argument, nullptr, 'n' },\n { \"R\" , required_argument, nullptr, 'R' },\n { \"r\" , required_argument, nullptr, 'r' },\n { \"d\" , required_argument, nullptr, 'd' },\n { \"box\" , no_argument , nullptr, 'b' },\n { \"sphere\", no_argument , nullptr, 's' },\n { \"torus\" , no_argument , nullptr, 't' },\n { \"output\", no_argument , nullptr, 'o' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n unsigned d = 3; \/\/ default dimension to use for expansion\n unsigned m = 50;\n unsigned n = 50;\n DataType R = DataType(0.50);\n DataType r = DataType(0.25);\n\n bool sampleFromBox = false;\n bool sampleFromSphere = false;\n bool sampleFromTorus = false;\n\n bool output = false;\n\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"d:m:n:R:r:bsto\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'd':\n d = static_cast<unsigned>( std::stoul(optarg) );\n break;\n case 'm':\n m = static_cast<unsigned>( std::stoul(optarg) );\n break;\n case 'n':\n n = static_cast<unsigned>( std::stoul(optarg) );\n break;\n case 'R':\n R = static_cast<DataType>( std::stod(optarg) );\n break;\n case 'r':\n r = static_cast<DataType>( std::stod(optarg) );\n break;\n case 'b':\n sampleFromBox = true;\n sampleFromSphere = false;\n sampleFromTorus = false;\n break;\n case 's':\n sampleFromBox = false;\n sampleFromSphere = true;\n sampleFromTorus = false;\n break;\n case 't':\n sampleFromBox = false;\n sampleFromSphere = false;\n sampleFromTorus = true;\n break;\n case 'o':\n output = true;\n break;\n default:\n break;\n }\n }\n\n std::cerr << \"* Sampling \" << n << \" persistence diagrams\\n\";\n if( sampleFromBox )\n std::cerr << \"* Sampling \" << m << \" points from a box with a=\" << r << \"\\n\";\n else if( sampleFromSphere )\n std::cerr << \"* Sampling \" << m << \" points from a sphere with r=\" << r << \"\\n\";\n else if( sampleFromTorus )\n std::cerr << \"* Sampling \" << m << \" points from a torus with R=\" << R << \" and r=\" << r << \"\\n\";\n else\n std::cerr << \"* Generating \" << m << \" random points per diagram\\n\";\n\n for( unsigned i = 0; i < n; i++ )\n {\n std::vector<PersistenceDiagram> pds;\n PersistenceDiagram pd;\n\n if( sampleFromBox )\n pds = createRandomBoxPersistenceDiagrams(r, m, d);\n else if( sampleFromSphere )\n pd = createRandomSpherePersistenceDiagram(r, m);\n else if( sampleFromTorus )\n pd = createRandomTorusPersistenceDiagram(R, r, m);\n else\n pd = createRandomPersistenceDiagram(m);\n\n if( output )\n {\n if( !pds.empty() )\n {\n for( auto&& pd : pds )\n {\n std::stringstream stream;\n stream << \"\/tmp\/\";\n stream << std::setw( static_cast<int>( std::floor( std::log10(n)+1 ) ) ) << std::setfill( '0' ) << i << \"_d\" << pd.dimension();\n stream << \".txt\";\n\n std::ofstream out( stream.str() );\n out << pd << \"\\n\";\n }\n }\n else\n {\n std::stringstream stream;\n stream << \"\/tmp\/\";\n stream << std::setw( static_cast<int>( std::floor( std::log10(n)+1 ) ) ) << std::setfill( '0' ) << i;\n stream << \".txt\";\n\n std::ofstream out( stream.str() );\n out << pd << \"\\n\";\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef VEXCL_PROFILER_HPP\n#define VEXCL_PROFILER_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file profiler.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief Simple OpenCL\/Host profiler.\n *\/\n\n#if defined(_MSC_VER) && ( defined(min) || defined(max) )\n# error Please define NOMINMAX macro globally in your project\n#endif\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <map>\n#include <memory>\n#include <stack>\n#include <vector>\n#include <cassert>\n\n#if defined(_MSC_VER) && (_MSC_VER < 1700)\n# define VEXCL_USE_BOOST_CHRONO\n# include <boost\/chrono.hpp>\n#else\n# include <chrono>\n#endif\n\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/ordered_index.hpp>\n#include <boost\/multi_index\/sequenced_index.hpp>\n#include <boost\/multi_index\/global_fun.hpp>\n#include <boost\/io\/ios_state.hpp>\n\n#include <boost\/accumulators\/accumulators.hpp>\n#include <boost\/accumulators\/statistics\/stats.hpp>\n#include <boost\/accumulators\/statistics\/count.hpp>\n#include <boost\/accumulators\/statistics\/sum.hpp>\n#include <boost\/accumulators\/statistics\/mean.hpp>\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4244)\n#endif\n#include <boost\/accumulators\/statistics\/median.hpp>\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n#include <vexcl\/backend.hpp>\n\n\nnamespace vex {\n\n\/\/\/ A stopwatch that computes the median and mean of individual timings.\n\/**\n * \\param Clock class that provides interface compatible with either\n * boost::chrono or std::chrono clocks.\n *\/\ntemplate <\n#ifdef VEXCL_USE_BOOST_CHRONO\n class Clock = boost::chrono::high_resolution_clock\n#else\n class Clock = std::chrono::high_resolution_clock\n#endif\n >\nclass stopwatch {\n boost::accumulators::accumulator_set<\n double,\n boost::accumulators::stats<\n boost::accumulators::tag::count,\n boost::accumulators::tag::sum,\n boost::accumulators::tag::mean,\n boost::accumulators::tag::median(boost::accumulators::with_p_square_quantile)\n >\n > acc;\n\n public:\n stopwatch() { tic(); }\n\n \/\/\/ Start timer.\n inline void tic() {\n start = Clock::now();\n }\n\n \/\/\/ Stop timer, return elapsed time in seconds.\n inline double toc() {\n const double delta = seconds(start, Clock::now());\n\n acc(delta);\n\n return delta;\n }\n\n \/\/\/ Average time across tics.\n inline double average() const {\n namespace ba = boost::accumulators;\n\n return ba::count(acc) >= 3 ? ba::median(acc) : ba::mean(acc);\n }\n\n \/\/\/ Total time spent in the timer.\n inline double total() const {\n return boost::accumulators::sum(acc);\n }\n\n \/\/\/ Number of tics.\n inline size_t tics() const {\n return boost::accumulators::count(acc);\n }\n private:\n static double seconds(typename Clock::time_point begin, typename Clock::time_point end) {\n return typename Clock::duration(end - begin).count() *\n static_cast<double>(Clock::duration::period::num) \/\n Clock::duration::period::den;\n }\n\n typename Clock::time_point start;\n};\n\n\/\/\/ Class for gathering and printing OpenCL and Host profiling info.\n\/**\n * \\param Clock class that provides interface compatible with either\n * boost::chrono or std::chrono clocks.\n * \\param Avg Kind of averaging used. AvgMedian is more stable, but may\n * have high overhead when profiling is made in a loop.\n *\/\ntemplate <\n#ifdef VEXCL_USE_BOOST_CHRONO\n class Clock = boost::chrono::high_resolution_clock\n#else\n class Clock = std::chrono::high_resolution_clock\n#endif\n >\nclass profiler {\n private:\n class profile_unit {\n public:\n profile_unit(std::string name) : watch(), name(name), children() {}\n virtual ~profile_unit() {}\n\n stopwatch<Clock> watch;\n std::string name;\n\n static std::string _name(const std::shared_ptr<profile_unit> &u) {\n return u->name;\n }\n\n boost::multi_index_container<\n std::shared_ptr<profile_unit>,\n boost::multi_index::indexed_by<\n boost::multi_index::sequenced<>,\n boost::multi_index::ordered_unique<boost::multi_index::global_fun<\n const std::shared_ptr<profile_unit> &, std::string, profiler::profile_unit::_name>>\n >\n > children;\n\n virtual void tic() {\n watch.tic();\n }\n\n virtual double toc() {\n return watch.toc();\n }\n\n double children_time() const {\n double tm = 0;\n\n for(auto c = children.begin(); c != children.end(); c++)\n tm += (*c)->watch.total();\n\n return tm;\n }\n\n size_t max_line_width(size_t level) const {\n size_t w = name.size() + level;\n\n for(auto c = children.begin(); c != children.end(); c++)\n w = std::max(w, (*c)->max_line_width(level + shift_width));\n\n return w;\n }\n\n void print(std::ostream &out,\n size_t level, double total, size_t width) const\n {\n using namespace std;\n print_line(out, name, watch.total(), 100 * watch.total() \/ total, width, level);\n\n if (watch.tics() > 1) {\n out << \" (\" << setw(6) << watch.tics()\n << \"x; avg: \" << setprecision(6) << scientific\n << (watch.average() * 1e6) << \" usec.)\";\n }\n\n out << endl;\n\n if (!children.empty()) {\n double sec = watch.total() - children_time();\n double perc = 100 * sec \/ total;\n if(perc > 1e-1) {\n print_line(out, \"self\", sec, perc, width, level + 1);\n out << endl;\n }\n }\n\n for(auto c = children.begin(); c != children.end(); c++)\n (*c)->print(out, level + shift_width, total, width);\n }\n\n void print_line(std::ostream &out, const std::string &name,\n double time, double perc, size_t width, size_t indent) const {\n using namespace std;\n out << \"[\" << setw(indent) << \"\" << name << \":\"\n << setw(width - indent - name.size()) << \"\"\n << fixed << setw(10) << setprecision(3) << time << \" sec.\"\n << \"] (\" << setprecision(2) << setw(6) << perc << \"%)\";\n }\n\n private:\n static const size_t shift_width = 2U;\n };\n\n class cl_profile_unit : public profile_unit {\n public:\n cl_profile_unit(const std::string &name, std::vector<backend::command_queue> &queue)\n : profile_unit(name), queue(queue) {}\n\n void tic() {\n for(auto q = queue.begin(); q != queue.end(); ++q)\n q->finish();\n\n profile_unit::tic();\n }\n\n double toc() {\n for(auto q = queue.begin(); q != queue.end(); ++q)\n q->finish();\n\n return profile_unit::toc();\n }\n private:\n std::vector<backend::command_queue> &queue;\n };\n\n public:\n \/\/\/ Constructor.\n \/**\n * \\param queue vector of command queues.\n * \\param name Optional name to be used when profiling info is printed.\n *\/\n profiler(\n const std::vector<backend::command_queue> &queue = std::vector<backend::command_queue>(),\n const std::string &name = \"Profile\"\n ) : queue(queue)\n {\n auto root = std::shared_ptr<profile_unit>(new profile_unit(name));\n root->tic();\n stack.push_back(root);\n }\n\n private:\n void tic(profile_unit *u) {\n assert(!stack.empty());\n auto top = stack.back();\n auto new_unit = std::shared_ptr<profile_unit>(u);\n auto unit = *top->children.push_back(new_unit).first;\n unit->tic();\n stack.push_back(unit);\n }\n\n public:\n \/\/\/ Starts a CPU timer.\n \/**\n * Also pushes named interval to the top of the profiler hierarchy.\n * \\param name name of the measured interval.\n *\/\n void tic_cpu(const std::string &name) {\n tic(new profile_unit(name));\n }\n\n \/\/\/ Enqueues a marker into each of the provided queues.\n \/**\n * Also pushes named interval to the top of the profiler hierarchy.\n * \\param name name of the measured interval.\n *\/\n void tic_cl(const std::string &name) {\n assert(!queue.empty());\n tic(new cl_profile_unit(name, queue));\n }\n\n \/\/\/ Returns time since last tic.\n \/**\n * Also removes interval from the top of the profiler hierarchy.\n *\/\n double toc(const std::string &) {\n assert(stack.size() > 1);\n\n double delta = stack.back()->toc();\n stack.pop_back();\n\n return delta;\n }\n\n \/\/\/ Outputs profile to the provided stream.\n void print(std::ostream &out) {\n boost::io::ios_all_saver stream_state(out);\n\n if(stack.size() != 1)\n out << \"Warning! Profile is incomplete.\" << std::endl;\n\n auto root = stack.front();\n double length = root->toc();\n out << std::endl;\n root->print(out, 0, length, root->max_line_width(0));\n }\n\n private:\n std::vector<backend::command_queue> queue;\n std::deque<std::shared_ptr<profile_unit>> stack;\n};\n\n} \/\/ namespace vex\n\nnamespace std {\n\n\/\/\/ Sends the profiler summary to the output stream.\ntemplate <class Clock>\ninline std::ostream& operator<<(std::ostream &os, vex::profiler<Clock> &prof) {\n prof.print(os);\n return os;\n}\n\n}\n\n#endif\n<commit_msg>Implement profiler::reset<commit_after>#ifndef VEXCL_PROFILER_HPP\n#define VEXCL_PROFILER_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file profiler.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief Simple OpenCL\/Host profiler.\n *\/\n\n#if defined(_MSC_VER) && ( defined(min) || defined(max) )\n# error Please define NOMINMAX macro globally in your project\n#endif\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <map>\n#include <memory>\n#include <stack>\n#include <vector>\n#include <cassert>\n\n#if defined(_MSC_VER) && (_MSC_VER < 1700)\n# define VEXCL_USE_BOOST_CHRONO\n# include <boost\/chrono.hpp>\n#else\n# include <chrono>\n#endif\n\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/ordered_index.hpp>\n#include <boost\/multi_index\/sequenced_index.hpp>\n#include <boost\/multi_index\/global_fun.hpp>\n#include <boost\/io\/ios_state.hpp>\n\n#include <boost\/accumulators\/accumulators.hpp>\n#include <boost\/accumulators\/statistics\/stats.hpp>\n#include <boost\/accumulators\/statistics\/count.hpp>\n#include <boost\/accumulators\/statistics\/sum.hpp>\n#include <boost\/accumulators\/statistics\/mean.hpp>\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4244)\n#endif\n#include <boost\/accumulators\/statistics\/median.hpp>\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n#include <vexcl\/backend.hpp>\n\n\nnamespace vex {\n\n\/\/\/ A stopwatch that computes the median and mean of individual timings.\n\/**\n * \\param Clock class that provides interface compatible with either\n * boost::chrono or std::chrono clocks.\n *\/\ntemplate <\n#ifdef VEXCL_USE_BOOST_CHRONO\n class Clock = boost::chrono::high_resolution_clock\n#else\n class Clock = std::chrono::high_resolution_clock\n#endif\n >\nclass stopwatch {\n boost::accumulators::accumulator_set<\n double,\n boost::accumulators::stats<\n boost::accumulators::tag::count,\n boost::accumulators::tag::sum,\n boost::accumulators::tag::mean,\n boost::accumulators::tag::median(boost::accumulators::with_p_square_quantile)\n >\n > acc;\n\n public:\n stopwatch() { tic(); }\n\n \/\/\/ Start timer.\n inline void tic() {\n start = Clock::now();\n }\n\n \/\/\/ Stop timer, return elapsed time in seconds.\n inline double toc() {\n const double delta = seconds(start, Clock::now());\n\n acc(delta);\n\n return delta;\n }\n\n \/\/\/ Average time across tics.\n inline double average() const {\n namespace ba = boost::accumulators;\n\n return ba::count(acc) >= 3 ? ba::median(acc) : ba::mean(acc);\n }\n\n \/\/\/ Total time spent in the timer.\n inline double total() const {\n return boost::accumulators::sum(acc);\n }\n\n \/\/\/ Number of tics.\n inline size_t tics() const {\n return boost::accumulators::count(acc);\n }\n private:\n static double seconds(typename Clock::time_point begin, typename Clock::time_point end) {\n return typename Clock::duration(end - begin).count() *\n static_cast<double>(Clock::duration::period::num) \/\n Clock::duration::period::den;\n }\n\n typename Clock::time_point start;\n};\n\n\/\/\/ Class for gathering and printing OpenCL and Host profiling info.\n\/**\n * \\param Clock class that provides interface compatible with either\n * boost::chrono or std::chrono clocks.\n * \\param Avg Kind of averaging used. AvgMedian is more stable, but may\n * have high overhead when profiling is made in a loop.\n *\/\ntemplate <\n#ifdef VEXCL_USE_BOOST_CHRONO\n class Clock = boost::chrono::high_resolution_clock\n#else\n class Clock = std::chrono::high_resolution_clock\n#endif\n >\nclass profiler {\n private:\n class profile_unit {\n public:\n profile_unit(std::string name) : watch(), name(name), children() {}\n virtual ~profile_unit() {}\n\n stopwatch<Clock> watch;\n std::string name;\n\n static std::string _name(const std::shared_ptr<profile_unit> &u) {\n return u->name;\n }\n\n boost::multi_index_container<\n std::shared_ptr<profile_unit>,\n boost::multi_index::indexed_by<\n boost::multi_index::sequenced<>,\n boost::multi_index::ordered_unique<boost::multi_index::global_fun<\n const std::shared_ptr<profile_unit> &, std::string, profiler::profile_unit::_name>>\n >\n > children;\n\n virtual void tic() {\n watch.tic();\n }\n\n virtual double toc() {\n return watch.toc();\n }\n\n double children_time() const {\n double tm = 0;\n\n for(auto c = children.begin(); c != children.end(); c++)\n tm += (*c)->watch.total();\n\n return tm;\n }\n\n size_t max_line_width(size_t level) const {\n size_t w = name.size() + level;\n\n for(auto c = children.begin(); c != children.end(); c++)\n w = std::max(w, (*c)->max_line_width(level + shift_width));\n\n return w;\n }\n\n void print(std::ostream &out,\n size_t level, double total, size_t width) const\n {\n using namespace std;\n print_line(out, name, watch.total(), 100 * watch.total() \/ total, width, level);\n\n if (watch.tics() > 1) {\n out << \" (\" << setw(6) << watch.tics()\n << \"x; avg: \" << setprecision(6) << scientific\n << (watch.average() * 1e6) << \" usec.)\";\n }\n\n out << endl;\n\n if (!children.empty()) {\n double sec = watch.total() - children_time();\n double perc = 100 * sec \/ total;\n if(perc > 1e-1) {\n print_line(out, \"self\", sec, perc, width, level + 1);\n out << endl;\n }\n }\n\n for(auto c = children.begin(); c != children.end(); c++)\n (*c)->print(out, level + shift_width, total, width);\n }\n\n void print_line(std::ostream &out, const std::string &name,\n double time, double perc, size_t width, size_t indent) const {\n using namespace std;\n out << \"[\" << setw(indent) << \"\" << name << \":\"\n << setw(width - indent - name.size()) << \"\"\n << fixed << setw(10) << setprecision(3) << time << \" sec.\"\n << \"] (\" << setprecision(2) << setw(6) << perc << \"%)\";\n }\n\n private:\n static const size_t shift_width = 2U;\n };\n\n class cl_profile_unit : public profile_unit {\n public:\n cl_profile_unit(const std::string &name, std::vector<backend::command_queue> &queue)\n : profile_unit(name), queue(queue) {}\n\n void tic() {\n for(auto q = queue.begin(); q != queue.end(); ++q)\n q->finish();\n\n profile_unit::tic();\n }\n\n double toc() {\n for(auto q = queue.begin(); q != queue.end(); ++q)\n q->finish();\n\n return profile_unit::toc();\n }\n private:\n std::vector<backend::command_queue> &queue;\n };\n\n public:\n \/\/\/ Constructor.\n \/**\n * \\param queue vector of command queues.\n * \\param name Optional name to be used when profiling info is printed.\n *\/\n profiler(\n const std::vector<backend::command_queue> &queue = std::vector<backend::command_queue>(),\n const std::string &name = \"Profile\"\n ) : queue(queue)\n {\n auto root = std::shared_ptr<profile_unit>(new profile_unit(name));\n root->tic();\n stack.push_back(root);\n }\n\n void reset() {\n auto root = std::shared_ptr<profile_unit>(new profile_unit(stack.front()->name));\n stack.clear();\n root->tic();\n stack.push_back(root);\n }\n\n private:\n void tic(profile_unit *u) {\n assert(!stack.empty());\n auto top = stack.back();\n auto new_unit = std::shared_ptr<profile_unit>(u);\n auto unit = *top->children.push_back(new_unit).first;\n unit->tic();\n stack.push_back(unit);\n }\n\n public:\n \/\/\/ Starts a CPU timer.\n \/**\n * Also pushes named interval to the top of the profiler hierarchy.\n * \\param name name of the measured interval.\n *\/\n void tic_cpu(const std::string &name) {\n tic(new profile_unit(name));\n }\n\n \/\/\/ Enqueues a marker into each of the provided queues.\n \/**\n * Also pushes named interval to the top of the profiler hierarchy.\n * \\param name name of the measured interval.\n *\/\n void tic_cl(const std::string &name) {\n assert(!queue.empty());\n tic(new cl_profile_unit(name, queue));\n }\n\n \/\/\/ Returns time since last tic.\n \/**\n * Also removes interval from the top of the profiler hierarchy.\n *\/\n double toc(const std::string &) {\n assert(stack.size() > 1);\n\n double delta = stack.back()->toc();\n stack.pop_back();\n\n return delta;\n }\n\n \/\/\/ Outputs profile to the provided stream.\n void print(std::ostream &out) {\n boost::io::ios_all_saver stream_state(out);\n\n if(stack.size() != 1)\n out << \"Warning! Profile is incomplete.\" << std::endl;\n\n auto root = stack.front();\n double length = root->toc();\n out << std::endl;\n root->print(out, 0, length, root->max_line_width(0));\n }\n\n private:\n std::vector<backend::command_queue> queue;\n std::deque<std::shared_ptr<profile_unit>> stack;\n};\n\n} \/\/ namespace vex\n\nnamespace std {\n\n\/\/\/ Sends the profiler summary to the output stream.\ntemplate <class Clock>\ninline std::ostream& operator<<(std::ostream &os, vex::profiler<Clock> &prof) {\n prof.print(os);\n return os;\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <ParameterMgrFullConnector.h>\n#include <Tokenizer.h>\n#include <Utility.h>\n\n#include <iostream>\n#include <sstream>\n#include <memory>\n#include <string>\n#include <limits>\n#include <algorithm>\n#include <stdexcept>\n\nusing std::string;\n\nclass MyLogger final : public CParameterMgrFullConnector::ILogger\n{\npublic:\n void info(const std::string &log) override { std::cerr << \"Info: \" << log << std::endl; }\n\n void warning(const std::string &log) override { std::cerr << \"Warning: \" << log << std::endl; }\n};\n\nclass XmlGenerator\n{\npublic:\n using Exception = std::runtime_error;\n\n XmlGenerator(const string &toplevelConfig, bool validate, bool verbose, string schemasDir)\n : mConnector(toplevelConfig), mCommandHandler(mConnector.createCommandHandler())\n {\n if (verbose) {\n mLogger.reset(new MyLogger);\n mConnector.setLogger(mLogger.get());\n }\n\n mConnector.setSchemaUri(schemasDir);\n mConnector.setValidateSchemasOnStart(validate);\n\n \/\/ Disable irrelevant failure conditions\n mConnector.setFailureOnMissingSubsystem(false);\n mConnector.setFailureOnFailedSettingsLoad(false);\n\n \/\/ Disable the remote interface because we don't need it and it might\n \/\/ get in the way (e.g. the port is already in use)\n mConnector.setForceNoRemoteInterface(true);\n }\n\n \/** Reads each line of the input stream and takes an action accordingly\n *\n * Returns when the input stream reaches end of file\n *\n * The commands are the usual PF tunning commands and some additional specials.\n * Special commands:\n * - `createSelectionCriterion inclusive|exclusive <name> <value> [value, ...]`\n * Create a criterion with the given properties.\n * - `start` start the Parameter Framework. All criteria must have been created.\n *\n * @param[in] input The input stream to read from\n *\n * @return the number of error that occurred\n *\/\n size_t parse(std::istream &input);\n\n \/** Prints the Parameter Framework's instance configuration\n *\n * @param[out] output The stream to which output the configuration\n *\/\n void exportDomains(std::ostream &output);\n\nprivate:\n void addCriteria(std::vector<string> &tokens);\n void start();\n\n CParameterMgrFullConnector mConnector;\n std::unique_ptr<MyLogger> mLogger;\n std::unique_ptr<CommandHandlerInterface> mCommandHandler;\n};\n\nvoid XmlGenerator::addCriteria(std::vector<string> &tokens)\n{\n if (tokens.size() < 3) {\n throw Exception(\"Not enough arguments to criterion creation request\");\n }\n\n auto inclusiveness = tokens.front() == \"inclusive\";\n tokens.erase(begin(tokens));\n\n auto name = tokens.front();\n tokens.erase(begin(tokens));\n\n auto criterionType = mConnector.createSelectionCriterionType(inclusiveness);\n if (criterionType == nullptr) {\n throw Exception(\"Failed to create an \" +\n string(inclusiveness ? \"inclusive\" : \"exclusive\") + \" criterion type\");\n }\n\n int index = 0;\n for (const auto &literalValue : tokens) {\n \/\/ inclusive criteria are bitfields\n int numericalValue = inclusiveness ? 1 << index : index;\n string error;\n bool success = criterionType->addValuePair(numericalValue, literalValue, error);\n\n if (not success) {\n std::ostringstream message;\n message << \"Valuepair (\" << numericalValue << \", '\" << literalValue\n << \"') rejected for \" << name << \": \" << error;\n throw Exception(message.str());\n }\n index++;\n }\n\n \/\/ We don't need to keep a reference to the criterion - no need to store\n \/\/ the returned pointer.\n if (mConnector.createSelectionCriterion(name, criterionType) == nullptr) {\n throw Exception(\"Failed to create criterion '\" + name + \"'\");\n }\n}\n\nsize_t XmlGenerator::parse(std::istream &input)\n{\n string line;\n size_t errorNb = 0;\n while (not input.eof()) {\n std::getline(std::cin, line);\n\n auto tokens = Tokenizer(line, string(1, '\\0')).split();\n if (tokens.empty()) {\n continue;\n }\n auto command = tokens.front();\n tokens.erase(begin(tokens)); \/\/ drop the command name\n\n if (command == \"createSelectionCriterion\") {\n addCriteria(tokens);\n } else if (command == \"start\") {\n start();\n } else {\n string output;\n if (not mCommandHandler->process(command, tokens, output)) {\n errorNb++;\n std::cerr << \"Failed to executing command: \"\n << utility::join<string>(begin(tokens), end(tokens),\n [](string l, string r) { return l + ' ' + r; })\n << std::endl\n << output << std::endl;\n }\n }\n }\n return errorNb;\n}\n\nvoid XmlGenerator::start()\n{\n string error;\n if (not mConnector.start(error)) {\n throw Exception(\"Start failed: \" + error);\n }\n\n error.clear();\n \/\/ Switch to tunning mode as the tunning commands\n \/\/ are the only commands possible with this connector.\n if (not mConnector.setTuningMode(true, error)) {\n throw Exception(\"Failed to turn tuning mode on: \" + error);\n }\n}\n\nvoid XmlGenerator::exportDomains(std::ostream &output)\n{\n string error;\n string domains;\n if (not mConnector.exportDomainsXml(domains, true, false, error)) {\n throw Exception(\"Export failed: \" + error);\n } else {\n output << domains;\n }\n}\n\nstatic const char *usage =\n R\"(Usage: domainGeneratorConnector <top-level config> <verbose> <validate> <path>\n\n <verbose> '1': verbose, else: terse\n <validate> '1' validate, else: don't validate\n <path> path to the schemas' directory\n\nAll arguments are mandatory. If no validation is required,\nthe path to the schemas can be an empty string.\n\nExit with the number of (recoverable or not error) that occured.\n\nThis program is not intended to be used standalone but rather called through\ndomainGenerator.py)\";\n\n\/** On linux at least, a program can not exit with a value greater than 255.\n * @return min(code, 255);\n *\/\ntemplate <class T>\nstatic inline int normalizeExitCode(T code)\n{\n return int(std::min<T>(code, std::numeric_limits<uint8_t>::max()));\n}\n\nint main(int argc, char *argv[])\n{\n using std::endl;\n\n if (argc <= 4) {\n std::cerr << usage << std::endl;\n return 1;\n }\n\n string toplevelConfig = argv[1];\n bool verbose = string(argv[2]) == \"verbose\";\n bool validate = string(argv[3]) == \"validate\";\n string schemasDir = argv[4];\n\n if (verbose) {\n std::cerr << \"Domain generator config:\" << endl\n << \" toplevelConfig=\" << toplevelConfig << endl\n << \" verbose=\" << verbose << endl\n << \" validate=\" << validate << endl\n << \" schemasDir=\" << schemasDir << endl;\n }\n\n try {\n XmlGenerator xmlGenerator(toplevelConfig, validate, verbose, schemasDir);\n auto errorNb = xmlGenerator.parse(std::cin);\n \/\/ TODO: add a check for conflicting elements\n xmlGenerator.exportDomains(std::cout);\n\n return normalizeExitCode(errorNb);\n } catch (std::exception &e) {\n std::cerr << e.what() << std::endl;\n return 1;\n }\n}\n<commit_msg>domainGeneratorConnector: correct the 'usage' message<commit_after>\/*\n * Copyright (c) 2015, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <ParameterMgrFullConnector.h>\n#include <Tokenizer.h>\n#include <Utility.h>\n\n#include <iostream>\n#include <sstream>\n#include <memory>\n#include <string>\n#include <limits>\n#include <algorithm>\n#include <stdexcept>\n\nusing std::string;\n\nclass MyLogger final : public CParameterMgrFullConnector::ILogger\n{\npublic:\n void info(const std::string &log) override { std::cerr << \"Info: \" << log << std::endl; }\n\n void warning(const std::string &log) override { std::cerr << \"Warning: \" << log << std::endl; }\n};\n\nclass XmlGenerator\n{\npublic:\n using Exception = std::runtime_error;\n\n XmlGenerator(const string &toplevelConfig, bool validate, bool verbose, string schemasDir)\n : mConnector(toplevelConfig), mCommandHandler(mConnector.createCommandHandler())\n {\n if (verbose) {\n mLogger.reset(new MyLogger);\n mConnector.setLogger(mLogger.get());\n }\n\n mConnector.setSchemaUri(schemasDir);\n mConnector.setValidateSchemasOnStart(validate);\n\n \/\/ Disable irrelevant failure conditions\n mConnector.setFailureOnMissingSubsystem(false);\n mConnector.setFailureOnFailedSettingsLoad(false);\n\n \/\/ Disable the remote interface because we don't need it and it might\n \/\/ get in the way (e.g. the port is already in use)\n mConnector.setForceNoRemoteInterface(true);\n }\n\n \/** Reads each line of the input stream and takes an action accordingly\n *\n * Returns when the input stream reaches end of file\n *\n * The commands are the usual PF tunning commands and some additional specials.\n * Special commands:\n * - `createSelectionCriterion inclusive|exclusive <name> <value> [value, ...]`\n * Create a criterion with the given properties.\n * - `start` start the Parameter Framework. All criteria must have been created.\n *\n * @param[in] input The input stream to read from\n *\n * @return the number of error that occurred\n *\/\n size_t parse(std::istream &input);\n\n \/** Prints the Parameter Framework's instance configuration\n *\n * @param[out] output The stream to which output the configuration\n *\/\n void exportDomains(std::ostream &output);\n\nprivate:\n void addCriteria(std::vector<string> &tokens);\n void start();\n\n CParameterMgrFullConnector mConnector;\n std::unique_ptr<MyLogger> mLogger;\n std::unique_ptr<CommandHandlerInterface> mCommandHandler;\n};\n\nvoid XmlGenerator::addCriteria(std::vector<string> &tokens)\n{\n if (tokens.size() < 3) {\n throw Exception(\"Not enough arguments to criterion creation request\");\n }\n\n auto inclusiveness = tokens.front() == \"inclusive\";\n tokens.erase(begin(tokens));\n\n auto name = tokens.front();\n tokens.erase(begin(tokens));\n\n auto criterionType = mConnector.createSelectionCriterionType(inclusiveness);\n if (criterionType == nullptr) {\n throw Exception(\"Failed to create an \" +\n string(inclusiveness ? \"inclusive\" : \"exclusive\") + \" criterion type\");\n }\n\n int index = 0;\n for (const auto &literalValue : tokens) {\n \/\/ inclusive criteria are bitfields\n int numericalValue = inclusiveness ? 1 << index : index;\n string error;\n bool success = criterionType->addValuePair(numericalValue, literalValue, error);\n\n if (not success) {\n std::ostringstream message;\n message << \"Valuepair (\" << numericalValue << \", '\" << literalValue\n << \"') rejected for \" << name << \": \" << error;\n throw Exception(message.str());\n }\n index++;\n }\n\n \/\/ We don't need to keep a reference to the criterion - no need to store\n \/\/ the returned pointer.\n if (mConnector.createSelectionCriterion(name, criterionType) == nullptr) {\n throw Exception(\"Failed to create criterion '\" + name + \"'\");\n }\n}\n\nsize_t XmlGenerator::parse(std::istream &input)\n{\n string line;\n size_t errorNb = 0;\n while (not input.eof()) {\n std::getline(std::cin, line);\n\n auto tokens = Tokenizer(line, string(1, '\\0')).split();\n if (tokens.empty()) {\n continue;\n }\n auto command = tokens.front();\n tokens.erase(begin(tokens)); \/\/ drop the command name\n\n if (command == \"createSelectionCriterion\") {\n addCriteria(tokens);\n } else if (command == \"start\") {\n start();\n } else {\n string output;\n if (not mCommandHandler->process(command, tokens, output)) {\n errorNb++;\n std::cerr << \"Failed to executing command: \"\n << utility::join<string>(begin(tokens), end(tokens),\n [](string l, string r) { return l + ' ' + r; })\n << std::endl\n << output << std::endl;\n }\n }\n }\n return errorNb;\n}\n\nvoid XmlGenerator::start()\n{\n string error;\n if (not mConnector.start(error)) {\n throw Exception(\"Start failed: \" + error);\n }\n\n error.clear();\n \/\/ Switch to tunning mode as the tunning commands\n \/\/ are the only commands possible with this connector.\n if (not mConnector.setTuningMode(true, error)) {\n throw Exception(\"Failed to turn tuning mode on: \" + error);\n }\n}\n\nvoid XmlGenerator::exportDomains(std::ostream &output)\n{\n string error;\n string domains;\n if (not mConnector.exportDomainsXml(domains, true, false, error)) {\n throw Exception(\"Export failed: \" + error);\n } else {\n output << domains;\n }\n}\n\nstatic const char *usage =\n R\"(Usage: domainGeneratorConnector <top-level config> <verbose> <validate> <path>\n\n <verbose> 'verbose': verbose, else: terse\n <validate> 'validate': validate, else: don't validate\n <path> path to the schemas' directory\n\nAll arguments are mandatory. If no validation is required,\nthe path to the schemas can be an empty string.\n\nExit with the number of (recoverable or not error) that occured.\n\nThis program is not intended to be used standalone but rather called through\ndomainGenerator.py)\";\n\n\/** On linux at least, a program can not exit with a value greater than 255.\n * @return min(code, 255);\n *\/\ntemplate <class T>\nstatic inline int normalizeExitCode(T code)\n{\n return int(std::min<T>(code, std::numeric_limits<uint8_t>::max()));\n}\n\nint main(int argc, char *argv[])\n{\n using std::endl;\n\n if (argc <= 4) {\n std::cerr << usage << std::endl;\n return 1;\n }\n\n string toplevelConfig = argv[1];\n bool verbose = string(argv[2]) == \"verbose\";\n bool validate = string(argv[3]) == \"validate\";\n string schemasDir = argv[4];\n\n if (verbose) {\n std::cerr << \"Domain generator config:\" << endl\n << \" toplevelConfig=\" << toplevelConfig << endl\n << \" verbose=\" << verbose << endl\n << \" validate=\" << validate << endl\n << \" schemasDir=\" << schemasDir << endl;\n }\n\n try {\n XmlGenerator xmlGenerator(toplevelConfig, validate, verbose, schemasDir);\n auto errorNb = xmlGenerator.parse(std::cin);\n \/\/ TODO: add a check for conflicting elements\n xmlGenerator.exportDomains(std::cout);\n\n return normalizeExitCode(errorNb);\n } catch (std::exception &e) {\n std::cerr << e.what() << std::endl;\n return 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include<bits\/stdc++.h>\nusing namespace std;\n\nint main(){\n char numbers[] = \"0123456789\";\n for(int i=1;i<1000000;i++)\n next_permutation(numbers,numbers+10); \n cout << numbers << endl;\n}\n<commit_msg>Update solution_1.cpp<commit_after>#include<bits\/stdc++.h>\nusing namespace std;\n\nint main(){\n char numbers[] = \"0123456789\";\n for(int i=1;i<1000000;i++){\n next_permutation(numbers,numbers+10); \n }\n cout << numbers << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright (c) 2014-2015 Leandro T. C. Melo (ltcmelo@gmail.com)\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\n * USA\n *****************************************************************************\/\n\n\/*--------------------------*\/\n\/*--- The UaiSo! Project ---*\/\n\/*--------------------------*\/\n\n#include \"Python\/PyIncrementalLexer.h\"\n\nusing namespace uaiso;\n\nPyIncrementalLexer::PyIncrementalLexer()\n{}\n\nPyIncrementalLexer::~PyIncrementalLexer()\n{}\n\nvoid PyIncrementalLexer::lex(const std::string& source)\n{}\n<commit_msg>Py: Incremental lexer<commit_after>\/******************************************************************************\n * Copyright (c) 2014-2015 Leandro T. C. Melo (ltcmelo@gmail.com)\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\n * USA\n *****************************************************************************\/\n\n\/*--------------------------*\/\n\/*--- The UaiSo! Project ---*\/\n\/*--------------------------*\/\n\n#include \"Python\/PyIncrementalLexer.h\"\n#include \"Python\/PyLexer.h\"\n#include \"Parsing\/ParsingContext.h\"\n#include \"Parsing\/IncrementalLexer__.h\"\n\nusing namespace uaiso;\n\nPyIncrementalLexer::PyIncrementalLexer()\n{\n P->context_.reset(new ParsingContext);\n P->context_->setAllowComments(true);\n}\n\nPyIncrementalLexer::~PyIncrementalLexer()\n{}\n\nvoid PyIncrementalLexer::lex(const std::string& source)\n{\n P->phrasing_.reset(new Phrasing);\n P->context_->collectPhrasing(P->phrasing_.get());\n\n PyLexer lexer;\n lexer.setContext(P->context_.get());\n lexer.setBuffer(source.c_str(), source.size());\n\n Token tk;\n do {\n tk = lexer.lex();\n } while (tk != TK_EOP);\n std::cout << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"shared.h\"\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char *argv[]) {\n\n\n\n sink(_strdup(getenv(\"VAR\")));\n sink(strdup(getenv(\"VAR\")));\n sink(unmodeled_function(getenv(\"VAR\")));\n\n char untainted_buf[100] = \"\";\n char buf[100] = \"VAR = \";\n sink(strcat(buf, getenv(\"VAR\")));\n\n sink(buf);\n sink(untainted_buf); \/\/ the two buffers would be conflated if we added flow through all partial chi inputs\n\n return 0;\n}\n\ntypedef unsigned int inet_addr_retval;\ninet_addr_retval inet_addr(const char *dotted_address);\nvoid sink(inet_addr_retval);\n\nvoid test_indirect_arg_to_model() {\n \/\/ This test is non-sensical but carefully arranged so we get data flow into\n \/\/ inet_addr not through the function argument but through its associated\n \/\/ read side effect.\n void *env_pointer = getenv(\"VAR\"); \/\/ env_pointer is tainted, not its data.\n inet_addr_retval a = inet_addr((const char *)&env_pointer);\n sink(a);\n}\n\nclass B {\n public:\n virtual void f(const char*) = 0;\n};\n\nclass D1 : public B {};\n\nclass D2 : public D1 {\n public:\n void f(const char* p) override {}\n};\n\nclass D3 : public D2 {\n public:\n void f(const char* p) override {\n sink(p);\n }\n};\n\nvoid test_dynamic_cast() {\n B* b = new D3();\n b->f(getenv(\"VAR\")); \/\/ tainted\n\n ((D2*)b)->f(getenv(\"VAR\")); \/\/ tainted\n static_cast<D2*>(b)->f(getenv(\"VAR\")); \/\/ tainted\n dynamic_cast<D2*>(b)->f(getenv(\"VAR\")); \/\/ tainted\n reinterpret_cast<D2*>(b)->f(getenv(\"VAR\")); \/\/ tainted\n\n B* b2 = new D2();\n b2->f(getenv(\"VAR\"));\n\n ((D2*)b2)->f(getenv(\"VAR\"));\n static_cast<D2*>(b2)->f(getenv(\"VAR\"));\n dynamic_cast<D2*>(b2)->f(getenv(\"VAR\"));\n reinterpret_cast<D2*>(b2)->f(getenv(\"VAR\"));\n\n dynamic_cast<D3*>(b2)->f(getenv(\"VAR\")); \/\/ tainted [FALSE POSITIVE]\n}\n\nnamespace std {\n template< class T >\n T&& move( T&& t ) noexcept;\n}\n\nvoid test_std_move() {\n sink(std::move(getenv(\"VAR\")));\n}\n\nvoid flow_to_outparam(char ** ret, char *arg) {\n *ret = arg; \n}\n\nvoid test_outparams() {\n char *p2 = nullptr;\n flow_to_outparam(&p2, getenv(\"VAR\"));\n sink(p2); \/\/ tainted\n}\n\n\n\n\nstruct XY {\n int x;\n int y;\n};\n\nvoid taint_y(XY *xyp) {\n int tainted = getenv(\"VAR\")[0];\n xyp->y = tainted;\n}\n\nvoid test_conflated_fields3() {\n XY xy;\n xy.x = 0;\n taint_y(&xy);\n sink(xy.x); \/\/ not tainted\n}\n\nstruct Point {\n int x;\n int y;\n\n void callSink() {\n sink(this->x); \/\/ tainted\n sink(this->y); \/\/ not tainted\n }\n};\n\nvoid test_conflated_fields1() {\n Point p;\n p.x = getenv(\"VAR\")[0];\n sink(p.x); \/\/ tainted\n sink(p.y); \/\/ not tainted\n p.callSink();\n}\n\nvoid taint_x(Point *pp) {\n pp->x = getenv(\"VAR\")[0];\n}\n\nvoid y_to_sink(Point *pp) {\n sink(pp->y); \/\/ not tainted\n}\n\nvoid test_conflated_fields2() {\n Point p;\n taint_x(&p);\n y_to_sink(&p);\n}\n\nvoid sink(Point*);\nvoid sink(Point);\n\nvoid test_field_to_obj_taint_object(Point p) {\n p.x = getenv(\"VAR\")[0];\n sink(p); \/\/ not tainted\n sink(p.x); \/\/ tainted\n}\n\nvoid test_field_to_obj_taint_object_addrof(Point p) {\n taint_x(&p);\n sink(p); \/\/ tainted\n sink(&p); \/\/ tainted\n sink(p.x); \/\/ tainted\n}\n\nvoid test_field_to_obj_taint_pointer(Point* pp) {\n pp->x = getenv(\"VAR\")[0];\n sink(pp); \/\/ tainted\n sink(*pp); \/\/ not tainted\n}\n\nvoid call_sink_on_object(Point* pp) {\n sink(pp); \/\/ tainted\n sink(*pp); \/\/ tainted\n}\n\nvoid test_field_to_obj_taint_call_sink(Point* pp) {\n pp->x = getenv(\"VAR\")[0];\n call_sink_on_object(pp);\n}\n\nvoid test_field_to_obj_taint_through_setter(Point* pp) {\n taint_x(pp);\n sink(pp); \/\/ tainted\n sink(*pp); \/\/ not tainted\n}\n\nPoint* getPoint();\n\nvoid test_field_to_obj_local_variable() {\n Point* pp = getPoint();\n pp->x = getenv(\"VAR\")[0];\n sink(pp); \/\/ not tainted\n sink(*pp); \/\/ not tainted\n}\n\nvoid test_field_to_obj_taint_array(Point* pp, int i) {\n pp[0].x = getenv(\"VAR\")[0];\n sink(pp[i]); \/\/ not tainted\n sink(pp); \/\/ tainted\n sink(*pp); \/\/ not tainted\n}\n\nvoid test_field_to_obj_test_pointer_arith(Point* pp) {\n (pp + sizeof(*pp))->x = getenv(\"VAR\")[0];\n sink(pp); \/\/ tainted\n sink(pp + sizeof(*pp)); \/\/ tainted\n}<commit_msg>C++: Add annotations describing whether the flow is an instance of field-to-object flow<commit_after>#include \"shared.h\"\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char *argv[]) {\n\n\n\n sink(_strdup(getenv(\"VAR\")));\n sink(strdup(getenv(\"VAR\")));\n sink(unmodeled_function(getenv(\"VAR\")));\n\n char untainted_buf[100] = \"\";\n char buf[100] = \"VAR = \";\n sink(strcat(buf, getenv(\"VAR\")));\n\n sink(buf);\n sink(untainted_buf); \/\/ the two buffers would be conflated if we added flow through all partial chi inputs\n\n return 0;\n}\n\ntypedef unsigned int inet_addr_retval;\ninet_addr_retval inet_addr(const char *dotted_address);\nvoid sink(inet_addr_retval);\n\nvoid test_indirect_arg_to_model() {\n \/\/ This test is non-sensical but carefully arranged so we get data flow into\n \/\/ inet_addr not through the function argument but through its associated\n \/\/ read side effect.\n void *env_pointer = getenv(\"VAR\"); \/\/ env_pointer is tainted, not its data.\n inet_addr_retval a = inet_addr((const char *)&env_pointer);\n sink(a);\n}\n\nclass B {\n public:\n virtual void f(const char*) = 0;\n};\n\nclass D1 : public B {};\n\nclass D2 : public D1 {\n public:\n void f(const char* p) override {}\n};\n\nclass D3 : public D2 {\n public:\n void f(const char* p) override {\n sink(p);\n }\n};\n\nvoid test_dynamic_cast() {\n B* b = new D3();\n b->f(getenv(\"VAR\")); \/\/ tainted\n\n ((D2*)b)->f(getenv(\"VAR\")); \/\/ tainted\n static_cast<D2*>(b)->f(getenv(\"VAR\")); \/\/ tainted\n dynamic_cast<D2*>(b)->f(getenv(\"VAR\")); \/\/ tainted\n reinterpret_cast<D2*>(b)->f(getenv(\"VAR\")); \/\/ tainted\n\n B* b2 = new D2();\n b2->f(getenv(\"VAR\"));\n\n ((D2*)b2)->f(getenv(\"VAR\"));\n static_cast<D2*>(b2)->f(getenv(\"VAR\"));\n dynamic_cast<D2*>(b2)->f(getenv(\"VAR\"));\n reinterpret_cast<D2*>(b2)->f(getenv(\"VAR\"));\n\n dynamic_cast<D3*>(b2)->f(getenv(\"VAR\")); \/\/ tainted [FALSE POSITIVE]\n}\n\nnamespace std {\n template< class T >\n T&& move( T&& t ) noexcept;\n}\n\nvoid test_std_move() {\n sink(std::move(getenv(\"VAR\")));\n}\n\nvoid flow_to_outparam(char ** ret, char *arg) {\n *ret = arg; \n}\n\nvoid test_outparams() {\n char *p2 = nullptr;\n flow_to_outparam(&p2, getenv(\"VAR\"));\n sink(p2); \/\/ tainted\n}\n\n\n\n\nstruct XY {\n int x;\n int y;\n};\n\nvoid taint_y(XY *xyp) {\n int tainted = getenv(\"VAR\")[0];\n xyp->y = tainted;\n}\n\nvoid test_conflated_fields3() {\n XY xy;\n xy.x = 0;\n taint_y(&xy);\n sink(xy.x); \/\/ not tainted\n}\n\nstruct Point {\n int x;\n int y;\n\n void callSink() {\n sink(this->x); \/\/ tainted\n sink(this->y); \/\/ not tainted\n }\n};\n\nvoid test_conflated_fields1() {\n Point p;\n p.x = getenv(\"VAR\")[0];\n sink(p.x); \/\/ tainted\n sink(p.y); \/\/ not tainted\n p.callSink();\n}\n\nvoid taint_x(Point *pp) {\n pp->x = getenv(\"VAR\")[0];\n}\n\nvoid y_to_sink(Point *pp) {\n sink(pp->y); \/\/ not tainted\n}\n\nvoid test_conflated_fields2() {\n Point p;\n taint_x(&p);\n y_to_sink(&p);\n}\n\nvoid sink(Point*);\nvoid sink(Point);\n\nvoid test_field_to_obj_taint_object(Point p) {\n p.x = getenv(\"VAR\")[0];\n sink(p); \/\/ not tainted\n sink(p.x); \/\/ tainted\n}\n\nvoid test_field_to_obj_taint_object_addrof(Point p) {\n taint_x(&p);\n sink(p); \/\/ tainted [field -> object]\n sink(&p); \/\/ tainted [field -> object]\n sink(p.x); \/\/ tainted\n}\n\nvoid test_field_to_obj_taint_pointer(Point* pp) {\n pp->x = getenv(\"VAR\")[0];\n sink(pp); \/\/ tainted [field -> object]\n sink(*pp); \/\/ not tainted\n}\n\nvoid call_sink_on_object(Point* pp) {\n sink(pp); \/\/ tainted [field -> object]\n sink(*pp); \/\/ tainted [field -> object]\n}\n\nvoid test_field_to_obj_taint_call_sink(Point* pp) {\n pp->x = getenv(\"VAR\")[0];\n call_sink_on_object(pp);\n}\n\nvoid test_field_to_obj_taint_through_setter(Point* pp) {\n taint_x(pp);\n sink(pp); \/\/ tainted [field -> object]\n sink(*pp); \/\/ not tainted\n}\n\nPoint* getPoint();\n\nvoid test_field_to_obj_local_variable() {\n Point* pp = getPoint();\n pp->x = getenv(\"VAR\")[0];\n sink(pp); \/\/ not tainted\n sink(*pp); \/\/ not tainted\n}\n\nvoid test_field_to_obj_taint_array(Point* pp, int i) {\n pp[0].x = getenv(\"VAR\")[0];\n sink(pp[i]); \/\/ not tainted\n sink(pp); \/\/ tainted [field -> object]\n sink(*pp); \/\/ not tainted\n}\n\nvoid test_field_to_obj_test_pointer_arith(Point* pp) {\n (pp + sizeof(*pp))->x = getenv(\"VAR\")[0];\n sink(pp); \/\/ tainted [field -> object]\n sink(pp + sizeof(*pp)); \/\/ tainted [field -> object]\n}<|endoftext|>"} {"text":"<commit_before>#include \"RulerWidget.h\"\n#include \"QtGlSliceView.h\"\n#include <Qt>\n#include <QtOpenGL\/qgl.h>\n#include <QMouseEvent>\n#include <QGuiApplication>\n#include <cmath>\n#include \"itkMath.h\"\n\nbool operator< (std::unique_ptr< RulerToolMetaData > const& lhs, std::unique_ptr< RulerToolMetaData > const& rhs) {\n return lhs->sortId < rhs->sortId;\n}\n\nRainbowMetaDataGenerator::RainbowMetaDataGenerator() { \n curColor = colors.begin(); \n}\n\nstd::unique_ptr< RulerToolMetaData > RainbowMetaDataGenerator::operator()(void) {\n std::string name = std::to_string(curId);\n QColor color = QColor(QString(curColor->c_str()));\n int id = curId;\n\n \/\/ wrap around to the beginning of the color list if at end\n ++curColor;\n if (curColor == colors.end()) {\n curColor = colors.begin();\n }\n\n ++curId;\n return std::unique_ptr< RulerToolMetaData >(new RulerToolMetaData{ id, name, color });\n}\n\nstd::unique_ptr< RulerToolMetaData > ONSDMetaDataGenerator::operator()(void) {\n std::string name = flipper ? \"R1\" : \"ONSD\";\n QColor color = QColor(colors[(int)flipper].c_str());\n int id = curId;\n\n flipper = !flipper;\n ++curId;\n\n return std::unique_ptr< RulerToolMetaData >(new RulerToolMetaData{ id, name, color });\n}\n\n\nRulerToolMetaDataFactory::RulerToolMetaDataFactory(std::unique_ptr< MetaDataGenerator > generator) : generator{ std::move(generator) } { }\n\nstd::unique_ptr< RulerToolMetaData > RulerToolMetaDataFactory::getNext() {\n std::unique_ptr< RulerToolMetaData > ans;\n if (refunds.size() > 0) {\n ans = std::move(*(refunds.begin()));\n refunds.erase(refunds.begin());\n }\n else {\n ans = (*generator)();\n }\n return ans;\n}\n\nvoid RulerToolMetaDataFactory::refund(std::unique_ptr< RulerToolMetaData > ruler_meta) {\n refunds.push_back(std::move(ruler_meta));\n std::sort(refunds.begin(), refunds.end());\n}\n\nRulerTool::RulerTool(QtGlSliceView* parent0, PointType3D &index0, std::unique_ptr< RulerToolMetaData > metaData) :\n parent{ parent0 }, indices{ index0, index0 }, points{ parent0->indexToPhysicalPoint(index0), parent0->indexToPhysicalPoint(index0) }, metaData{ std::move(metaData) }, clickRadius{ 10.0 }, state{ RulerToolState::drawing }, floatingIndex{ 1 }, crossStart{ 18 }, crossEnd{ 3 }, lineWidth{ 4 }\n{\n\n}\n\nRulerTool::~RulerTool() {}\n\nint RulerTool::isOver(double index[]) const {\n int ans = -1;\n auto screenPt = parent->indexToScreenPoint(PointType3D(index));\n if (screenPt.EuclideanDistanceTo(parent->indexToScreenPoint(indices[0])) < clickRadius) {\n ans = 0;\n }\n else if (screenPt.EuclideanDistanceTo(parent->indexToScreenPoint(indices[1])) < clickRadius) {\n ans = 1;\n }\n return ans;\n}\n\nvoid RulerTool::updateFloatingIndex(double index[]) {\n this->indices[this->floatingIndex] = PointType3D(index);\n this->points[this->floatingIndex] = this->parent->indexToPhysicalPoint(index);\n}\n\n\nvoid RulerTool::setFloatingIndex(int id) {\n this->floatingIndex = id;\n}\n\nint RulerTool::getFloatingIndex() const {\n return this->floatingIndex;\n}\n\ndouble RulerTool::length() {\n return this->points[0].EuclideanDistanceTo(this->points[1]);\n}\n\nvoid RulerTool::paint() { \n\n QPainter painter(this->parent);\n QPen pen;\n\n \/\/ could optimize this by memoization and catching parent stage changes\n PointType2D screen0 = parent->indexToScreenPoint(indices[0]);\n PointType2D screen1 = parent->indexToScreenPoint(indices[1]);\n\n QColor color = metaData->color;\n color.setAlphaF(0.7);\n pen.setWidth(lineWidth);\n pen.setColor(color);\n painter.setPen(pen);\n\n \/\/ TODO make line dotted\n\n \/\/ crosshair1\n painter.drawLine(QLine(screen0[0] - crossStart, screen0[1] - crossStart, screen0[0] - crossEnd, screen0[1] - crossEnd));\n painter.drawLine(QLine(screen0[0] + crossStart, screen0[1] + crossStart, screen0[0] + crossEnd, screen0[1] + crossEnd));\n painter.drawLine(QLine(screen0[0] - crossStart, screen0[1] + crossStart, screen0[0] - crossEnd, screen0[1] + crossEnd));\n painter.drawLine(QLine(screen0[0] + crossStart, screen0[1] - crossStart, screen0[0] + crossEnd, screen0[1] - crossEnd));\n\n\n \/\/ crosshair2\n painter.drawLine(QLine(screen1[0] - crossStart, screen1[1] - crossStart, screen1[0] - crossEnd, screen1[1] - crossEnd));\n painter.drawLine(QLine(screen1[0] + crossStart, screen1[1] + crossStart, screen1[0] + crossEnd, screen1[1] + crossEnd));\n painter.drawLine(QLine(screen1[0] - crossStart, screen1[1] + crossStart, screen1[0] - crossEnd, screen1[1] + crossEnd));\n painter.drawLine(QLine(screen1[0] + crossStart, screen1[1] - crossStart, screen1[0] + crossEnd, screen1[1] - crossEnd));\n\n QPen pen2;\n pen2.setWidth(lineWidth);\n pen2.setColor(color);\n pen2.setStyle(Qt::DashDotLine);\n painter.setPen(pen2);\n\n \/\/line\n painter.drawLine(QLine(screen0[0], screen0[1], screen1[0], screen1[1]));\n\n}\n\nstd::string RulerTool::toJson() {\n char txt[256];\n\n int n = snprintf(txt, sizeof(txt),\n \"{ \\\"name\\\" : \\\"%s\\\", \\\"indices\\\" : [ [%.4f, %.4f, %.4f], [%.4f, %.4f, %.4f] ], \\\"points\\\" : [ [%.4f, %.4f, %.4f], [%.4f, %.4f, %.4f] ], \\\"distance\\\" : %.4f}\",\n metaData->name.c_str(),\n indices[0].GetElement(0),\n indices[0].GetElement(1),\n indices[0].GetElement(2),\n indices[1].GetElement(0),\n indices[1].GetElement(1),\n indices[1].GetElement(2),\n points[0].GetElement(0),\n points[0].GetElement(1),\n points[0].GetElement(2),\n points[1].GetElement(0),\n points[1].GetElement(1),\n points[1].GetElement(2),\n points[0].EuclideanDistanceTo(points[1]));\n\n if (n >= sizeof(txt)) {\n throw \"RulerTool::toJson tried to write too big of string\";\n }\n return std::string(txt);\n}\n\nRulerToolCollection::RulerToolCollection(QtGlSliceView* parent, std::shared_ptr< RulerToolMetaDataFactory > metaDataFactory, unsigned short axis, unsigned int slice)\n : parent{ parent }, metaDataFactory{ metaDataFactory }, axis{ axis }, slice{ slice }, currentId { -1 }, state { RulerToolState::standing }\n{\n\n}\n\nRulerToolCollection::~RulerToolCollection() {}\n\nvoid RulerToolCollection::handleMouseEvent(QMouseEvent* event, double index[]) {\n\n int over = -1;\n switch (this->state) {\n case RulerToolState::standing:\n over = isOver(index);\n if (over >= 0) {\n if (QGuiApplication::overrideCursor() == nullptr) {\n QGuiApplication::setOverrideCursor(Qt::OpenHandCursor);\n }\n if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::RightButton) { \/\/ we're over a ruler and have right-clicked to move the crosshair\n this->currentId = over;\n RulerTool* r = rulers[currentId].get();\n r->setFloatingIndex(r->isOver(index));\n this->state = RulerToolState::drawing;\n r->paint();\n }\n }\n else {\n QGuiApplication::restoreOverrideCursor();\n }\n\n \/\/ we're idle and we're clicking to create a new ruler\n if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::LeftButton) {\n \/\/ blank click on screen, make a ruler\n\n std::unique_ptr< RulerTool > r(new RulerTool(this->parent, RulerTool::PointType3D(index), metaDataFactory->getNext()));\n this->rulers.push_back(std::move(r));\n this->currentId = this->rulers.size() - 1;\n this->state = RulerToolState::drawing;\n this->paint();\n }\n break;\n case RulerToolState::drawing:\n if (QGuiApplication::overrideCursor() != nullptr) {\n QGuiApplication::restoreOverrideCursor(); \/\/ if we are drawing go back to a normal cursor, even if we're over a ruler\n }\n \/\/ we have one free end of the ruler and we are clicking to set it\n if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::LeftButton) {\n RulerTool* r = rulers[currentId].get();\n r->updateFloatingIndex(index);\n this->state = RulerToolState::standing;\n }\n \/\/ actively moving the free end\n else if (event->type() == QEvent::MouseMove) {\n RulerTool* r = rulers[currentId].get();\n r->updateFloatingIndex(index);\n }\n else if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::RightButton) { \/\/ delete and go back to standing\n metaDataFactory->refund(std::move(rulers[currentId]->metaData));\n rulers.erase(rulers.begin() + currentId);\n currentId = rulers.size() > 0 ? 0 : -1;\n this->state = RulerToolState::standing;\n }\n break;\n }\n\n}\n\nvoid RulerToolCollection::setMetaDataFactory(std::shared_ptr< RulerToolMetaDataFactory > factory) {\n metaDataFactory = factory;\n}\n\nvoid RulerToolCollection::paint() {\n for (auto &r : this->rulers) {\n r->paint();\n }\n}\n\nint RulerToolCollection::isOver(double index[]) {\n for (int i=0; i < rulers.size(); ++i) {\n auto r = rulers[i].get();\n int x = r->isOver(index);\n if (x >= 0) {\n return i; \/\/ return the index of the ruler (different than RulerTool::isOver() which returns the index of the ruler point covered)\n }\n }\n return -1;\n}\n\nRulerTool* RulerToolCollection::getActive() {\n return currentId >= 0 ? rulers[currentId].get() : nullptr;\n}\n\nstd::string RulerToolCollection::toJson() {\n std::string ans = \"{ \\\"axis\\\" : \" + std::to_string(axis) + \", \\\"slice\\\" : \" + std::to_string(slice) + \", \\\"rulers\\\" : [\";\n if (rulers.size() > 0) {\n ans += rulers[0]->toJson();\n }\n for (auto iter = rulers.begin() + 1; iter != rulers.end(); ++iter) {\n ans += \",\" + (*iter)->toJson();\n }\n ans += \"]}\";\n return ans;\n}<commit_msg>Fix RulerTool constructor<commit_after>#include \"RulerWidget.h\"\n#include \"QtGlSliceView.h\"\n#include <Qt>\n#include <QtOpenGL\/qgl.h>\n#include <QMouseEvent>\n#include <QGuiApplication>\n#include <cmath>\n#include \"itkMath.h\"\n\nbool operator< (std::unique_ptr< RulerToolMetaData > const& lhs, std::unique_ptr< RulerToolMetaData > const& rhs) {\n return lhs->sortId < rhs->sortId;\n}\n\nRainbowMetaDataGenerator::RainbowMetaDataGenerator() { \n curColor = colors.begin(); \n}\n\nstd::unique_ptr< RulerToolMetaData > RainbowMetaDataGenerator::operator()(void) {\n std::string name = std::to_string(curId);\n QColor color = QColor(QString(curColor->c_str()));\n int id = curId;\n\n \/\/ wrap around to the beginning of the color list if at end\n ++curColor;\n if (curColor == colors.end()) {\n curColor = colors.begin();\n }\n\n ++curId;\n return std::unique_ptr< RulerToolMetaData >(new RulerToolMetaData{ id, name, color });\n}\n\nstd::unique_ptr< RulerToolMetaData > ONSDMetaDataGenerator::operator()(void) {\n std::string name = flipper ? \"R1\" : \"ONSD\";\n QColor color = QColor(colors[(int)flipper].c_str());\n int id = curId;\n\n flipper = !flipper;\n ++curId;\n\n return std::unique_ptr< RulerToolMetaData >(new RulerToolMetaData{ id, name, color });\n}\n\n\nRulerToolMetaDataFactory::RulerToolMetaDataFactory(std::unique_ptr< MetaDataGenerator > generator) : generator{ std::move(generator) } { }\n\nstd::unique_ptr< RulerToolMetaData > RulerToolMetaDataFactory::getNext() {\n std::unique_ptr< RulerToolMetaData > ans;\n if (refunds.size() > 0) {\n ans = std::move(*(refunds.begin()));\n refunds.erase(refunds.begin());\n }\n else {\n ans = (*generator)();\n }\n return ans;\n}\n\nvoid RulerToolMetaDataFactory::refund(std::unique_ptr< RulerToolMetaData > ruler_meta) {\n refunds.push_back(std::move(ruler_meta));\n std::sort(refunds.begin(), refunds.end());\n}\n\nRulerTool::RulerTool(QtGlSliceView* parent0, PointType3D index0, std::unique_ptr< RulerToolMetaData > metaData) :\n parent{ parent0 }, indices{ index0, index0 }, points{ parent0->indexToPhysicalPoint(index0), parent0->indexToPhysicalPoint(index0) }, metaData{ std::move(metaData) }, clickRadius{ 10.0 }, state{ RulerToolState::drawing }, floatingIndex{ 1 }, crossStart{ 18 }, crossEnd{ 3 }, lineWidth{ 4 }\n{\n\n}\n\nRulerTool::~RulerTool() {}\n\nint RulerTool::isOver(double index[]) const {\n int ans = -1;\n auto screenPt = parent->indexToScreenPoint(PointType3D(index));\n if (screenPt.EuclideanDistanceTo(parent->indexToScreenPoint(indices[0])) < clickRadius) {\n ans = 0;\n }\n else if (screenPt.EuclideanDistanceTo(parent->indexToScreenPoint(indices[1])) < clickRadius) {\n ans = 1;\n }\n return ans;\n}\n\nvoid RulerTool::updateFloatingIndex(double index[]) {\n this->indices[this->floatingIndex] = PointType3D(index);\n this->points[this->floatingIndex] = this->parent->indexToPhysicalPoint(index);\n}\n\n\nvoid RulerTool::setFloatingIndex(int id) {\n this->floatingIndex = id;\n}\n\nint RulerTool::getFloatingIndex() const {\n return this->floatingIndex;\n}\n\ndouble RulerTool::length() {\n return this->points[0].EuclideanDistanceTo(this->points[1]);\n}\n\nvoid RulerTool::paint() { \n\n QPainter painter(this->parent);\n QPen pen;\n\n \/\/ could optimize this by memoization and catching parent stage changes\n PointType2D screen0 = parent->indexToScreenPoint(indices[0]);\n PointType2D screen1 = parent->indexToScreenPoint(indices[1]);\n\n QColor color = metaData->color;\n color.setAlphaF(0.7);\n pen.setWidth(lineWidth);\n pen.setColor(color);\n painter.setPen(pen);\n\n \/\/ TODO make line dotted\n\n \/\/ crosshair1\n painter.drawLine(QLine(screen0[0] - crossStart, screen0[1] - crossStart, screen0[0] - crossEnd, screen0[1] - crossEnd));\n painter.drawLine(QLine(screen0[0] + crossStart, screen0[1] + crossStart, screen0[0] + crossEnd, screen0[1] + crossEnd));\n painter.drawLine(QLine(screen0[0] - crossStart, screen0[1] + crossStart, screen0[0] - crossEnd, screen0[1] + crossEnd));\n painter.drawLine(QLine(screen0[0] + crossStart, screen0[1] - crossStart, screen0[0] + crossEnd, screen0[1] - crossEnd));\n\n\n \/\/ crosshair2\n painter.drawLine(QLine(screen1[0] - crossStart, screen1[1] - crossStart, screen1[0] - crossEnd, screen1[1] - crossEnd));\n painter.drawLine(QLine(screen1[0] + crossStart, screen1[1] + crossStart, screen1[0] + crossEnd, screen1[1] + crossEnd));\n painter.drawLine(QLine(screen1[0] - crossStart, screen1[1] + crossStart, screen1[0] - crossEnd, screen1[1] + crossEnd));\n painter.drawLine(QLine(screen1[0] + crossStart, screen1[1] - crossStart, screen1[0] + crossEnd, screen1[1] - crossEnd));\n\n QPen pen2;\n pen2.setWidth(lineWidth);\n pen2.setColor(color);\n pen2.setStyle(Qt::DashDotLine);\n painter.setPen(pen2);\n\n \/\/line\n painter.drawLine(QLine(screen0[0], screen0[1], screen1[0], screen1[1]));\n\n}\n\nstd::string RulerTool::toJson() {\n char txt[256];\n\n int n = snprintf(txt, sizeof(txt),\n \"{ \\\"name\\\" : \\\"%s\\\", \\\"indices\\\" : [ [%.4f, %.4f, %.4f], [%.4f, %.4f, %.4f] ], \\\"points\\\" : [ [%.4f, %.4f, %.4f], [%.4f, %.4f, %.4f] ], \\\"distance\\\" : %.4f}\",\n metaData->name.c_str(),\n indices[0].GetElement(0),\n indices[0].GetElement(1),\n indices[0].GetElement(2),\n indices[1].GetElement(0),\n indices[1].GetElement(1),\n indices[1].GetElement(2),\n points[0].GetElement(0),\n points[0].GetElement(1),\n points[0].GetElement(2),\n points[1].GetElement(0),\n points[1].GetElement(1),\n points[1].GetElement(2),\n points[0].EuclideanDistanceTo(points[1]));\n\n if (n >= sizeof(txt)) {\n throw \"RulerTool::toJson tried to write too big of string\";\n }\n return std::string(txt);\n}\n\nRulerToolCollection::RulerToolCollection(QtGlSliceView* parent, std::shared_ptr< RulerToolMetaDataFactory > metaDataFactory, unsigned short axis, unsigned int slice)\n : parent{ parent }, metaDataFactory{ metaDataFactory }, axis{ axis }, slice{ slice }, currentId { -1 }, state { RulerToolState::standing }\n{\n\n}\n\nRulerToolCollection::~RulerToolCollection() {}\n\nvoid RulerToolCollection::handleMouseEvent(QMouseEvent* event, double index[]) {\n\n int over = -1;\n switch (this->state) {\n case RulerToolState::standing:\n over = isOver(index);\n if (over >= 0) {\n if (QGuiApplication::overrideCursor() == nullptr) {\n QGuiApplication::setOverrideCursor(Qt::OpenHandCursor);\n }\n if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::RightButton) { \/\/ we're over a ruler and have right-clicked to move the crosshair\n this->currentId = over;\n RulerTool* r = rulers[currentId].get();\n r->setFloatingIndex(r->isOver(index));\n this->state = RulerToolState::drawing;\n r->paint();\n }\n }\n else {\n QGuiApplication::restoreOverrideCursor();\n }\n\n \/\/ we're idle and we're clicking to create a new ruler\n if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::LeftButton) {\n \/\/ blank click on screen, make a ruler\n\n std::unique_ptr< RulerTool > r(new RulerTool(this->parent, RulerTool::PointType3D(index), metaDataFactory->getNext()));\n this->rulers.push_back(std::move(r));\n this->currentId = this->rulers.size() - 1;\n this->state = RulerToolState::drawing;\n this->paint();\n }\n break;\n case RulerToolState::drawing:\n if (QGuiApplication::overrideCursor() != nullptr) {\n QGuiApplication::restoreOverrideCursor(); \/\/ if we are drawing go back to a normal cursor, even if we're over a ruler\n }\n \/\/ we have one free end of the ruler and we are clicking to set it\n if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::LeftButton) {\n RulerTool* r = rulers[currentId].get();\n r->updateFloatingIndex(index);\n this->state = RulerToolState::standing;\n }\n \/\/ actively moving the free end\n else if (event->type() == QEvent::MouseMove) {\n RulerTool* r = rulers[currentId].get();\n r->updateFloatingIndex(index);\n }\n else if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::RightButton) { \/\/ delete and go back to standing\n metaDataFactory->refund(std::move(rulers[currentId]->metaData));\n rulers.erase(rulers.begin() + currentId);\n currentId = rulers.size() > 0 ? 0 : -1;\n this->state = RulerToolState::standing;\n }\n break;\n }\n\n}\n\nvoid RulerToolCollection::setMetaDataFactory(std::shared_ptr< RulerToolMetaDataFactory > factory) {\n metaDataFactory = factory;\n}\n\nvoid RulerToolCollection::paint() {\n for (auto &r : this->rulers) {\n r->paint();\n }\n}\n\nint RulerToolCollection::isOver(double index[]) {\n for (int i=0; i < rulers.size(); ++i) {\n auto r = rulers[i].get();\n int x = r->isOver(index);\n if (x >= 0) {\n return i; \/\/ return the index of the ruler (different than RulerTool::isOver() which returns the index of the ruler point covered)\n }\n }\n return -1;\n}\n\nRulerTool* RulerToolCollection::getActive() {\n return currentId >= 0 ? rulers[currentId].get() : nullptr;\n}\n\nstd::string RulerToolCollection::toJson() {\n std::string ans = \"{ \\\"axis\\\" : \" + std::to_string(axis) + \", \\\"slice\\\" : \" + std::to_string(slice) + \", \\\"rulers\\\" : [\";\n if (rulers.size() > 0) {\n ans += rulers[0]->toJson();\n }\n for (auto iter = rulers.begin() + 1; iter != rulers.end(); ++iter) {\n ans += \",\" + (*iter)->toJson();\n }\n ans += \"]}\";\n return ans;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * By: ulises-jeremias\n * From: https:\/\/uva.onlinejudge.org\/index.php?option=onlinejudge&page=show_problem&problem=417\n * Name: Points in Figures: Rectangles\n * Date: 20\/11\/2017\n *\/\n\n#include <iostream>\n#include <utility>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\n#define EPS 1e-9\n#define INF 1 << 30\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> ii;\n\nstruct point_i\n{\n int x, y;\n\n point_i () {\n x = y = 0;\n }\n\n point_i (int _x, int _y) : x(_x), y(_y) {\n };\n};\n\nstruct point\n{\n double x, y;\n\n point () {\n x = y = 0.0;\n }\n\n point (double _x, double _y) : x(_x), y(_y) {\n };\n};\n\nstruct shape\n{\n vector<point> points;\n double radius;\n int sh;\n\n shape(point upper_left, point lower_right)\n {\n sh = 1;\n\n points.push_back(point(upper_left.x, upper_left.y));\n points.push_back(point(upper_left.x, lower_right.y));\n points.push_back(point(lower_right.x, lower_right.y));\n points.push_back(point(lower_right.x, upper_left.y));\n points.push_back(point(upper_left.x, upper_left.y));\n }\n\n shape(point center, double radius)\n {\n sh = 2;\n\n points.push_back(center);\n this->radius = radius;\n }\n};\n\nint n, np;\nchar op;\ndouble radius;\npoint upper_left, lower_right, center, p;\nvector<shape> shapes;\n\ndouble dist_point (const point &a, const point &b) {\n return hypot(a.x-b.x, a.y-b.y);\n}\n\npoint to_vec(const point &a, const point &b)\n{\n return point(a.x - b.x, a.y - b.y);\n}\n\ndouble cross(point a, point b)\n{\n return (double) ((a.x * b.y) - (b.x * a.y));\n}\n\nbool ccw(point a, point b, point p)\n{\n return cross(to_vec(a, p), to_vec(b, p)) > 0.0;\n}\n\nbool is_inside_box(int idx)\n{\n shape rectangle = shapes[idx];\n\n for (int i = 0; i < 4; i++) {\n if (!ccw(rectangle.points[i], rectangle.points[i + 1], p)) {\n return false;\n }\n }\n\n return true;\n}\n\nbool is_inside_circle(int idx)\n{\n return (dist_point(shapes[idx].points[0], p) < shapes[idx].radius);\n}\n\nbool is_inside(int idx)\n{\n if (shapes[idx].sh == 1) {\n return is_inside_box(idx);\n } else {\n return is_inside_circle(idx);\n }\n}\n\nint main(int argc, char const *argv[]) {\n \/*#ifndef ONLINE_JUDGE\n #define ONLINE_JUDGE\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n #endif*\/\n\n int i;\n\n n = 0;\n while (scanf(\" %c\", &op), op != '*') {\n if (op == 'r') {\n scanf(\"%lf %lf\", &upper_left.x, &upper_left.y);\n scanf(\"%lf %lf\", &lower_right.x, &lower_right.y);\n\n shapes.push_back(shape(upper_left, lower_right));\n } else {\n scanf(\"%lf %lf\", ¢er.x, ¢er.y);\n scanf(\"%lf\", &radius);\n\n shapes.push_back(shape(center, radius));\n }\n\n n++;\n }\n\n np = 1;\n while (scanf(\"%lf %lf\", &p.x, &p.y), !((fabs(p.x - 9999.9) < EPS) && (fabs(p.y - 9999.9) < EPS))) {\n\n bool any = false;\n for (i = 0; i < n; i++) {\n if (is_inside(i)) {\n printf(\"Point %d is contained in figure %d\\n\", np, i + 1);\n any = true;\n }\n }\n\n if (!any) {\n printf(\"Point %d is not contained in any figure\\n\", np);\n }\n\n np++;\n }\n\n return 0;\n}\n<commit_msg>Solved<commit_after>\/*\n * By: ulises-jeremias\n * From: https:\/\/uva.onlinejudge.org\/index.php?option=onlinejudge&page=show_problem&problem=417\n * Name: Points in Figures: Rectangles\n * Date: 20\/11\/2017\n *\/\n\n#include <iostream>\n#include <utility>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\n#define EPS 1e-9\n#define INF 1 << 30\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> ii;\n\nstruct point_i\n{\n int x, y;\n\n point_i () {\n x = y = 0;\n }\n\n point_i (int _x, int _y) : x(_x), y(_y) {\n };\n};\n\nstruct point\n{\n double x, y;\n\n point () {\n x = y = 0.0;\n }\n\n point (double _x, double _y) : x(_x), y(_y) {\n };\n};\n\nstruct shape\n{\n vector<point> points;\n double radius;\n int sh;\n\n shape(point upper_left, point lower_right)\n {\n sh = 1;\n\n points.push_back(point(upper_left.x, upper_left.y));\n points.push_back(point(upper_left.x, lower_right.y));\n points.push_back(point(lower_right.x, lower_right.y));\n points.push_back(point(lower_right.x, upper_left.y));\n points.push_back(point(upper_left.x, upper_left.y));\n }\n\n shape(point center, double radius)\n {\n sh = 2;\n\n points.push_back(center);\n this->radius = radius;\n }\n};\n\nint n, np;\nchar op;\ndouble radius;\npoint upper_left, lower_right, center, p;\nvector<shape> shapes;\n\ndouble dist_point (const point &a, const point &b) {\n return hypot(a.x-b.x, a.y-b.y);\n}\n\npoint to_vec(const point &a, const point &b)\n{\n return point(a.x - b.x, a.y - b.y);\n}\n\ndouble cross(point a, point b)\n{\n return (double) ((a.x * b.y) - (b.x * a.y));\n}\n\nbool ccw(point a, point b, point p)\n{\n return cross(to_vec(a, p), to_vec(b, p)) > 0.0;\n}\n\nbool is_inside_box(int idx)\n{\n shape rectangle = shapes[idx];\n\n for (int i = 0; i < 4; i++) {\n if (!ccw(rectangle.points[i], rectangle.points[i + 1], p)) {\n return false;\n }\n }\n\n return true;\n}\n\nbool is_inside_circle(int idx)\n{\n return (dist_point(shapes[idx].points[0], p) < shapes[idx].radius);\n}\n\nbool is_inside(int idx)\n{\n if (shapes[idx].sh == 1) {\n return is_inside_box(idx);\n } else {\n return is_inside_circle(idx);\n }\n}\n\nint main(int argc, char const *argv[]) {\n #ifndef ONLINE_JUDGE\n #define ONLINE_JUDGE\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n #endif\n\n int i;\n\n n = 0;\n while (scanf(\" %c\", &op), op != '*') {\n if (op == 'r') {\n scanf(\"%lf %lf\", &upper_left.x, &upper_left.y);\n scanf(\"%lf %lf\", &lower_right.x, &lower_right.y);\n\n shapes.push_back(shape(upper_left, lower_right));\n } else {\n scanf(\"%lf %lf\", ¢er.x, ¢er.y);\n scanf(\"%lf\", &radius);\n\n shapes.push_back(shape(center, radius));\n }\n\n n++;\n }\n\n np = 1;\n while (scanf(\"%lf %lf\", &p.x, &p.y), !((fabs(p.x - 9999.9) < EPS) && (fabs(p.y - 9999.9) < EPS))) {\n\n bool any = false;\n for (i = 0; i < n; i++) {\n if (is_inside(i)) {\n printf(\"Point %d is contained in figure %d\\n\", np, i + 1);\n any = true;\n }\n }\n\n if (!any) {\n printf(\"Point %d is not contained in any figure\\n\", np);\n }\n\n np++;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stan\/math\/functions\/fdim.hpp\"\r\n#include <gtest\/gtest.h>\r\n\r\nTEST(MathFunctions, fdim_double) {\r\n using stan::math::fdim;\r\n\r\n EXPECT_FLOAT_EQ(1.0, fdim(3.0,2.0));\r\n EXPECT_FLOAT_EQ(0.0, fdim(2.0,3.0));\r\n\r\n EXPECT_FLOAT_EQ(2.5, fdim(4.5,2.0));\r\n}\r\n\r\nTEST(MathFunctions, fdim_int) {\r\n using stan::math::fdim;\r\n \r\n \/\/ promotes results to double\r\n EXPECT_FLOAT_EQ(1.0, fdim(int(3),int(2)));\r\n EXPECT_FLOAT_EQ(0.0, fdim(int(2),int(3)));\r\n}\r\n<commit_msg>adding failing fdim test<commit_after>#include <stan\/math\/functions\/fdim.hpp>\n#include <boost\/math\/special_functions\/fpclassify.hpp>\n#include <gtest\/gtest.h>\n\nTEST(MathFunctions, fdim_double) {\n using stan::math::fdim;\n\n EXPECT_FLOAT_EQ(1.0, fdim(3.0,2.0));\n EXPECT_FLOAT_EQ(0.0, fdim(2.0,3.0));\n\n EXPECT_FLOAT_EQ(2.5, fdim(4.5,2.0));\n}\n\nTEST(MathFunctions, fdim_int) {\n using stan::math::fdim;\n\n \/\/ promotes results to double\n EXPECT_FLOAT_EQ(1.0, fdim(int(3),int(2)));\n EXPECT_FLOAT_EQ(0.0, fdim(int(2),int(3)));\n}\n\nTEST(MathFunctions, fdim_nan) {\n double nan = std::numeric_limits<double>::quiet_NaN();\n\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::fdim(3.0, nan));\n\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::fdim(nan, 3.0));\n\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::fdim(nan, nan));\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <stdlib.h>\n#include <stdio.h>\n#include <memory.h>\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\n#include \"TiStore\/TiFS.h\"\n#include \"TiStore\/TiStore.h\"\n#include \"TiStore\/fs\/Initor.h\"\n#include \"TiStore\/traits.h\"\n#include \"TiStore\/kv\/BloomFilter.h\"\n#include \"TiStore\/kv\/SkipList.h\"\n#include \"TiStore\/lang\/TypeInfo.h\"\n\n#include \"stop_watch.h\"\n#include \"test.h\"\n\nusing namespace TiStore;\n\nstatic const int kVerbose = 1;\nstatic const int kIterators = 10000000;\n\n#define TEST_VERIFY_BOOL(value, format, var) \\\n printf(format, var, bool_to_string(!!(value)).c_str());\n\nstatic inline std::string bool_to_string(bool value)\n{\n if (value)\n return \"true\";\n else\n return \"false\";\n}\n\nvoid test_bloomfilter_hash_impl(const char key[])\n{\n StopWatch sw;\n \/**\/ volatile \/**\/ uint32_t hash;\n StandardBloomFilter sbf(8192, 10);\n Slice skey(key);\n printf(\"key = %s\\n\\n\", skey.toString().c_str());\n\n hash = 0;\n sw.start();\n for (int i = 0; i < kIterators; ++i) {\n hash += sbf.maybe_match(skey);\n }\n sw.stop();\n printf(\"sbf.maybe_match() time spent: %8.3f ms, hash: 0x%08X\\n\", sw.getElapsedMillisec(), hash);\n\n hash = 0;\n sw.start();\n for (int i = 0; i < kIterators; ++i) {\n hash += sbf.rocksdb_maybe_match(skey);\n }\n sw.stop();\n printf(\"sbf.rocksdb_maybe_match() time spent: %8.3f ms, hash: 0x%08X\\n\", sw.getElapsedMillisec(), hash);\n\n hash = 0;\n sw.start();\n for (int i = 0; i < kIterators; ++i) {\n hash += sbf.maybe_match2(skey);\n }\n sw.stop();\n printf(\"sbf.maybe_match2() time spent: %8.3f ms, hash: 0x%08X\\n\", sw.getElapsedMillisec(), hash);\n\n hash = 0;\n sw.start();\n for (int i = 0; i < kIterators; ++i) {\n hash += sbf.maybe_match_openssl(skey);\n }\n sw.stop();\n printf(\"sbf.maybe_match_openssl() time spent: %8.3f ms, hash: 0x%08X\\n\\n\", sw.getElapsedMillisec(), hash);\n}\n\nvoid test_bloomfilter_hash()\n{\n test_bloomfilter_hash_impl(\"This is a hash test.\");\n test_bloomfilter_hash_impl(\"This is a hash test...\");\n}\n\nvoid test_bloomfilter_impl()\n{\n StandardBloomFilter sbf(8192, 10);\n bool isMatch;\n\n Slice skey(\"abc\");\n sbf.setVerbose(true);\n\n sbf.addKey(skey);\n sbf.addKey(\"skyinno\");\n sbf.addKey(\"bigdata\");\n printf(\"\\n\");\n\n isMatch = sbf.maybeMatch(skey);\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", skey.data());\n\n isMatch = sbf.maybeMatch(\"skyinno\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"skyinno\");\n\n isMatch = sbf.maybeMatch(\"bigdata\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"bigdata\");\n printf(\"\\n\");\n\n isMatch = sbf.maybeMatch(\"ambari\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"ambari\");\n\n isMatch = sbf.maybeMatch(\"Karazhan\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"Karazhan\");\n\n isMatch = sbf.maybeMatch(\"pokemon go\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"pokemon go\");\n\n printf(\"\\n\");\n}\n\nstatic Slice MemIntegerKey(int i, char * buffer) {\n ::memcpy(buffer, &i, sizeof(i));\n return Slice(buffer, sizeof(i));\n}\n\nstatic int NextLength(int length) {\n if (length < 10) {\n length += 1;\n }\n else if (length < 100) {\n length += 10;\n }\n else if (length < 1000) {\n length += 100;\n }\n else if (length < 10000) {\n length += 1000;\n }\n else {\n length += 5000;\n }\n return length;\n}\n\ntemplate <typename T>\ndouble getFalsePositiveRate(T const & bloom_filter, int length) {\n char buffer[sizeof(int)];\n int result = 0;\n \/\/int max_length = (length <= 10000) ? 10000 : length;\n int max_length = length;\n for (int i = 0; i < 10000; ++i) {\n if (bloom_filter.maybeMatch(MemIntegerKey(i + 1000000000, buffer))) {\n result++;\n }\n }\n return (double)result \/ 10000.0;\n}\n\nvoid test_bloomfilter_standard_false_positive_rate()\n{\n char buffer[sizeof(int)];\n\n \/\/ Count number of filters that significantly exceed the false positive rate\n int mediocre_filters = 0;\n int good_filters = 0;\n bool isMatch;\n\n std::cout << \"----------------------------------\" << std::endl;\n std::cout << \"StandardBloomFilter Test\" << std::endl;\n std::cout << \"----------------------------------\" << std::endl;\n std::cout << std::endl;\n\n StandardBloomFilter bloomfilter(10000, 14, true);\n\n for (int length = 1; length <= 10000; length = NextLength(length)) {\n bloomfilter.setOption(length, 14, false);\n bloomfilter.reset();\n for (int i = 0; i < length; i++) {\n bloomfilter.addKey(MemIntegerKey(i, buffer));\n }\n\n \/\/ All added keys must match\n for (int i = 0; i < length; ++i) {\n isMatch = bloomfilter.maybeMatch(MemIntegerKey(i, buffer));\n if (!isMatch) {\n std::cout << \"[Not Match], Length = \" << length << \"; key = \" << i << std::endl;\n }\n }\n\n \/\/ Check false positive rate\n double rate = getFalsePositiveRate(bloomfilter, length);\n if (kVerbose >= 1) {\n fprintf(stderr, \"False positive rates: %5.2f%% @ length = %6d ; bytes = %6d ; used_bits = %d\\n\",\n rate * 100.0, length, (int)bloomfilter.getFilterSize(), (int)bloomfilter.getUsedBits());\n }\n if (rate > 0.0125)\n mediocre_filters++; \/\/ Allowed, but not too often\n else\n good_filters++;\n }\n if (kVerbose >= 1) {\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"Filters: %d good, %d mediocre\\n\",\n good_filters, mediocre_filters);\n }\n \/\/TEST_ASSERT_LE(mediocre_filters, good_filters \/ 5);\n\n fprintf(stderr, \"\\n\");\n}\n\nvoid test_bloomfilter_full_false_positive_rate()\n{\n char buffer[sizeof(int)];\n\n \/\/ Count number of filters that significantly exceed the false positive rate\n int mediocre_filters = 0;\n int good_filters = 0;\n bool isMatch;\n\n std::cout << \"----------------------------------\" << std::endl;\n std::cout << \"FullBloomFilter Test\" << std::endl;\n std::cout << \"----------------------------------\" << std::endl;\n std::cout << std::endl;\n\n FullBloomFilter bloomfilter(10000, 10, true);\n\n for (int length = 1; length <= 10000; length = NextLength(length)) {\n bloomfilter.setOption(length, 10, false);\n bloomfilter.reset();\n for (int i = 0; i < length; i++) {\n bloomfilter.addKey(MemIntegerKey(i, buffer));\n }\n\n \/\/ All added keys must match\n for (int i = 0; i < length; ++i) {\n isMatch = bloomfilter.maybeMatch(MemIntegerKey(i, buffer));\n if (!isMatch) {\n std::cout << \"[Not Match], Length = \" << length << \"; key = \" << i << std::endl;\n }\n }\n\n \/\/ Check false positive rate\n double rate = getFalsePositiveRate(bloomfilter, length);\n if (kVerbose >= 1) {\n fprintf(stderr, \"False positive rates: %5.2f%% @ length = %6d ; bytes = %6d ; used_bits = %d\\n\",\n rate * 100.0, length, (int)bloomfilter.getFilterSize(), (int)bloomfilter.getUsedBits());\n }\n if (rate > 0.0125)\n mediocre_filters++; \/\/ Allowed, but not too often\n else\n good_filters++;\n }\n if (kVerbose >= 1) {\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"Filters: %d good, %d mediocre\\n\",\n good_filters, mediocre_filters);\n }\n \/\/TEST_ASSERT_LE(mediocre_filters, good_filters \/ 5);\n\n fprintf(stderr, \"\\n\");\n}\n\nvoid test_bloomfilter()\n{\n test_bloomfilter_impl();\n test_bloomfilter_hash();\n\n stop_watch sw;\n sw.start();\n test_bloomfilter_standard_false_positive_rate();\n sw.stop();\n\n printf(\"time spent: %0.3f ms.\\n\\n\", sw.getElapsedMillisec());\n\n sw.start();\n test_bloomfilter_full_false_positive_rate();\n sw.stop();\n\n printf(\"time spent: %0.3f ms.\\n\\n\", sw.getElapsedMillisec());\n}\n\nint main(int argc, char * argv[])\n{\n printf(\"\\n\");\n\n TiStore::fs::Initor initor;\n\n TiStore::fs::File file;\n file.open(\"C:\\\\test.bin\");\n if (file.is_open()) {\n file.close();\n }\n\n TiStore::fs::File file1(\"C:\\\\test.bin\");\n file1.close();\n\n test_skiplist();\n test_property();\n \/\/test_traist();\n test_stl_iterator();\n\n \/\/test_bloomfilter();\n \/\/test_typeinfo_module();\n\n \/\/printf(\"\\n\");\n\n#ifdef _WIN32\n ::system(\"pause\");\n#endif\n return 0;\n}\n<commit_msg>打开一些单元测试<commit_after>\n#include <stdlib.h>\n#include <stdio.h>\n#include <memory.h>\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\n#include \"TiStore\/TiFS.h\"\n#include \"TiStore\/TiStore.h\"\n#include \"TiStore\/fs\/Initor.h\"\n#include \"TiStore\/traits.h\"\n#include \"TiStore\/kv\/BloomFilter.h\"\n#include \"TiStore\/kv\/SkipList.h\"\n#include \"TiStore\/lang\/TypeInfo.h\"\n\n#include \"stop_watch.h\"\n#include \"test.h\"\n\nusing namespace TiStore;\n\nstatic const int kVerbose = 1;\nstatic const int kIterators = 10000000;\n\n#define TEST_VERIFY_BOOL(value, format, var) \\\n printf(format, var, bool_to_string(!!(value)).c_str());\n\nstatic inline std::string bool_to_string(bool value)\n{\n if (value)\n return \"true\";\n else\n return \"false\";\n}\n\nvoid test_bloomfilter_hash_impl(const char key[])\n{\n StopWatch sw;\n \/**\/ volatile \/**\/ uint32_t hash;\n StandardBloomFilter sbf(8192, 10);\n Slice skey(key);\n printf(\"key = %s\\n\\n\", skey.toString().c_str());\n\n hash = 0;\n sw.start();\n for (int i = 0; i < kIterators; ++i) {\n hash += sbf.maybe_match(skey);\n }\n sw.stop();\n printf(\"sbf.maybe_match() time spent: %8.3f ms, hash: 0x%08X\\n\", sw.getElapsedMillisec(), hash);\n\n hash = 0;\n sw.start();\n for (int i = 0; i < kIterators; ++i) {\n hash += sbf.rocksdb_maybe_match(skey);\n }\n sw.stop();\n printf(\"sbf.rocksdb_maybe_match() time spent: %8.3f ms, hash: 0x%08X\\n\", sw.getElapsedMillisec(), hash);\n\n hash = 0;\n sw.start();\n for (int i = 0; i < kIterators; ++i) {\n hash += sbf.maybe_match2(skey);\n }\n sw.stop();\n printf(\"sbf.maybe_match2() time spent: %8.3f ms, hash: 0x%08X\\n\", sw.getElapsedMillisec(), hash);\n\n hash = 0;\n sw.start();\n for (int i = 0; i < kIterators; ++i) {\n hash += sbf.maybe_match_openssl(skey);\n }\n sw.stop();\n printf(\"sbf.maybe_match_openssl() time spent: %8.3f ms, hash: 0x%08X\\n\\n\", sw.getElapsedMillisec(), hash);\n}\n\nvoid test_bloomfilter_hash()\n{\n test_bloomfilter_hash_impl(\"This is a hash test.\");\n test_bloomfilter_hash_impl(\"This is a hash test...\");\n}\n\nvoid test_bloomfilter_impl()\n{\n StandardBloomFilter sbf(8192, 10);\n bool isMatch;\n\n Slice skey(\"abc\");\n sbf.setVerbose(true);\n\n sbf.addKey(skey);\n sbf.addKey(\"skyinno\");\n sbf.addKey(\"bigdata\");\n printf(\"\\n\");\n\n isMatch = sbf.maybeMatch(skey);\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", skey.data());\n\n isMatch = sbf.maybeMatch(\"skyinno\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"skyinno\");\n\n isMatch = sbf.maybeMatch(\"bigdata\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"bigdata\");\n printf(\"\\n\");\n\n isMatch = sbf.maybeMatch(\"ambari\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"ambari\");\n\n isMatch = sbf.maybeMatch(\"Karazhan\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"Karazhan\");\n\n isMatch = sbf.maybeMatch(\"pokemon go\");\n TEST_VERIFY_BOOL(isMatch, \"maybeMatch(\\\"%s\\\"): %s\\n\", \"pokemon go\");\n\n printf(\"\\n\");\n}\n\nstatic Slice MemIntegerKey(int i, char * buffer) {\n ::memcpy(buffer, &i, sizeof(i));\n return Slice(buffer, sizeof(i));\n}\n\nstatic int NextLength(int length) {\n if (length < 10) {\n length += 1;\n }\n else if (length < 100) {\n length += 10;\n }\n else if (length < 1000) {\n length += 100;\n }\n else if (length < 10000) {\n length += 1000;\n }\n else {\n length += 5000;\n }\n return length;\n}\n\ntemplate <typename T>\ndouble getFalsePositiveRate(T const & bloom_filter, int length) {\n char buffer[sizeof(int)];\n int result = 0;\n \/\/int max_length = (length <= 10000) ? 10000 : length;\n int max_length = length;\n for (int i = 0; i < 10000; ++i) {\n if (bloom_filter.maybeMatch(MemIntegerKey(i + 1000000000, buffer))) {\n result++;\n }\n }\n return (double)result \/ 10000.0;\n}\n\nvoid test_bloomfilter_standard_false_positive_rate()\n{\n char buffer[sizeof(int)];\n\n \/\/ Count number of filters that significantly exceed the false positive rate\n int mediocre_filters = 0;\n int good_filters = 0;\n bool isMatch;\n\n std::cout << \"----------------------------------\" << std::endl;\n std::cout << \"StandardBloomFilter Test\" << std::endl;\n std::cout << \"----------------------------------\" << std::endl;\n std::cout << std::endl;\n\n StandardBloomFilter bloomfilter(10000, 14, true);\n\n for (int length = 1; length <= 10000; length = NextLength(length)) {\n bloomfilter.setOption(length, 14, false);\n bloomfilter.reset();\n for (int i = 0; i < length; i++) {\n bloomfilter.addKey(MemIntegerKey(i, buffer));\n }\n\n \/\/ All added keys must match\n for (int i = 0; i < length; ++i) {\n isMatch = bloomfilter.maybeMatch(MemIntegerKey(i, buffer));\n if (!isMatch) {\n std::cout << \"[Not Match], Length = \" << length << \"; key = \" << i << std::endl;\n }\n }\n\n \/\/ Check false positive rate\n double rate = getFalsePositiveRate(bloomfilter, length);\n if (kVerbose >= 1) {\n fprintf(stderr, \"False positive rates: %5.2f%% @ length = %6d ; bytes = %6d ; used_bits = %d\\n\",\n rate * 100.0, length, (int)bloomfilter.getFilterSize(), (int)bloomfilter.getUsedBits());\n }\n if (rate > 0.0125)\n mediocre_filters++; \/\/ Allowed, but not too often\n else\n good_filters++;\n }\n if (kVerbose >= 1) {\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"Filters: %d good, %d mediocre\\n\",\n good_filters, mediocre_filters);\n }\n \/\/TEST_ASSERT_LE(mediocre_filters, good_filters \/ 5);\n\n fprintf(stderr, \"\\n\");\n}\n\nvoid test_bloomfilter_full_false_positive_rate()\n{\n char buffer[sizeof(int)];\n\n \/\/ Count number of filters that significantly exceed the false positive rate\n int mediocre_filters = 0;\n int good_filters = 0;\n bool isMatch;\n\n std::cout << \"----------------------------------\" << std::endl;\n std::cout << \"FullBloomFilter Test\" << std::endl;\n std::cout << \"----------------------------------\" << std::endl;\n std::cout << std::endl;\n\n FullBloomFilter bloomfilter(10000, 10, true);\n\n for (int length = 1; length <= 10000; length = NextLength(length)) {\n bloomfilter.setOption(length, 10, false);\n bloomfilter.reset();\n for (int i = 0; i < length; i++) {\n bloomfilter.addKey(MemIntegerKey(i, buffer));\n }\n\n \/\/ All added keys must match\n for (int i = 0; i < length; ++i) {\n isMatch = bloomfilter.maybeMatch(MemIntegerKey(i, buffer));\n if (!isMatch) {\n std::cout << \"[Not Match], Length = \" << length << \"; key = \" << i << std::endl;\n }\n }\n\n \/\/ Check false positive rate\n double rate = getFalsePositiveRate(bloomfilter, length);\n if (kVerbose >= 1) {\n fprintf(stderr, \"False positive rates: %5.2f%% @ length = %6d ; bytes = %6d ; used_bits = %d\\n\",\n rate * 100.0, length, (int)bloomfilter.getFilterSize(), (int)bloomfilter.getUsedBits());\n }\n if (rate > 0.0125)\n mediocre_filters++; \/\/ Allowed, but not too often\n else\n good_filters++;\n }\n if (kVerbose >= 1) {\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"Filters: %d good, %d mediocre\\n\",\n good_filters, mediocre_filters);\n }\n \/\/TEST_ASSERT_LE(mediocre_filters, good_filters \/ 5);\n\n fprintf(stderr, \"\\n\");\n}\n\nvoid test_bloomfilter()\n{\n test_bloomfilter_impl();\n test_bloomfilter_hash();\n\n stop_watch sw;\n sw.start();\n test_bloomfilter_standard_false_positive_rate();\n sw.stop();\n\n printf(\"time spent: %0.3f ms.\\n\\n\", sw.getElapsedMillisec());\n\n sw.start();\n test_bloomfilter_full_false_positive_rate();\n sw.stop();\n\n printf(\"time spent: %0.3f ms.\\n\\n\", sw.getElapsedMillisec());\n}\n\nint main(int argc, char * argv[])\n{\n printf(\"\\n\");\n\n TiStore::fs::Initor initor;\n\n TiStore::fs::File file;\n file.open(\"C:\\\\test.bin\");\n if (file.is_open()) {\n file.close();\n }\n\n TiStore::fs::File file1(\"C:\\\\test.bin\");\n file1.close();\n\n test_skiplist();\n test_property();\n test_traist();\n test_stl_iterator();\n\n test_bloomfilter();\n test_typeinfo_module();\n\n \/\/printf(\"\\n\");\n\n#ifdef _WIN32\n ::system(\"pause\");\n#endif\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include <alloy\/runtime\/debug_info.h>\n\nusing namespace alloy;\nusing namespace alloy::runtime;\n\n\nDebugInfo::DebugInfo() :\n source_disasm_(0),\n raw_hir_disasm_(0),\n hir_disasm_(0),\n machine_code_disasm_(0),\n source_map_count_(0),\n source_map_(NULL) {\n}\n\nDebugInfo::~DebugInfo() {\n xe_free(source_map_);\n xe_free(source_disasm_);\n xe_free(raw_hir_disasm_);\n xe_free(hir_disasm_);\n xe_free(machine_code_disasm_);\n}\n\nvoid DebugInfo::InitializeSourceMap(size_t source_map_count,\n SourceMapEntry* source_map) {\n source_map_count_ = source_map_count;\n source_map_ = source_map;\n\n \/\/ TODO(benvanik): ensure sorted in some way? MC offset?\n}\n\nSourceMapEntry* DebugInfo::LookupSourceOffset(uint64_t offset) {\n \/\/ TODO(benvanik): binary search? We know the list is sorted by code order.\n for (size_t n = 0; n < source_map_count_; n++) {\n auto entry = &source_map_[n];\n if (entry->source_offset == offset) {\n return entry;\n }\n }\n return NULL;\n}\n\nSourceMapEntry* DebugInfo::LookupHIROffset(uint64_t offset) {\n \/\/ TODO(benvanik): binary search? We know the list is sorted by code order.\n for (size_t n = 0; n < source_map_count_; n++) {\n auto entry = &source_map_[n];\n if (entry->hir_offset >= offset) {\n return entry;\n }\n }\n return NULL;\n}\n\nSourceMapEntry* DebugInfo::LookupCodeOffset(uint64_t offset) {\n \/\/ TODO(benvanik): binary search? We know the list is sorted by code order.\n for (size_t n = 0; n < source_map_count_; n++) {\n auto entry = &source_map_[n];\n if (entry->code_offset >= offset) {\n return entry;\n }\n }\n return 0;\n}\n<commit_msg>Fixing source offsets.<commit_after>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include <alloy\/runtime\/debug_info.h>\n\nusing namespace alloy;\nusing namespace alloy::runtime;\n\n\nDebugInfo::DebugInfo() :\n source_disasm_(0),\n raw_hir_disasm_(0),\n hir_disasm_(0),\n machine_code_disasm_(0),\n source_map_count_(0),\n source_map_(NULL) {\n}\n\nDebugInfo::~DebugInfo() {\n xe_free(source_map_);\n xe_free(source_disasm_);\n xe_free(raw_hir_disasm_);\n xe_free(hir_disasm_);\n xe_free(machine_code_disasm_);\n}\n\nvoid DebugInfo::InitializeSourceMap(size_t source_map_count,\n SourceMapEntry* source_map) {\n source_map_count_ = source_map_count;\n source_map_ = source_map;\n\n \/\/ TODO(benvanik): ensure sorted in some way? MC offset?\n}\n\nSourceMapEntry* DebugInfo::LookupSourceOffset(uint64_t offset) {\n \/\/ TODO(benvanik): binary search? We know the list is sorted by code order.\n for (size_t n = 0; n < source_map_count_; n++) {\n auto entry = &source_map_[n];\n if (entry->source_offset == offset) {\n return entry;\n }\n }\n return NULL;\n}\n\nSourceMapEntry* DebugInfo::LookupHIROffset(uint64_t offset) {\n \/\/ TODO(benvanik): binary search? We know the list is sorted by code order.\n for (size_t n = 0; n < source_map_count_; n++) {\n auto entry = &source_map_[n];\n if (entry->hir_offset >= offset) {\n return entry;\n }\n }\n return NULL;\n}\n\nSourceMapEntry* DebugInfo::LookupCodeOffset(uint64_t offset) {\n \/\/ TODO(benvanik): binary search? We know the list is sorted by code order.\n for (int n = source_map_count_ - 1; n >= 0; n--) {\n auto entry = &source_map_[n];\n if (entry->code_offset <= offset) {\n return entry;\n }\n }\n return NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"analyser_dtsc.h\"\n#include <mist\/h264.h>\n\nvoid AnalyserDTSC::init(Util::Config &conf){\n Analyser::init(conf);\n}\n\nAnalyserDTSC::AnalyserDTSC(Util::Config &conf) : Analyser(conf){\n conn = Socket::Connection(0, fileno(stdin));\n totalBytes = 0;\n}\n\nbool AnalyserDTSC::parsePacket(){\n P.reInit(conn);\n if (conn && !P){\n FAIL_MSG(\"Invalid DTSC packet @ byte %llu\", totalBytes)\n return false;\n }\n if (!conn && !P){\n stop();\n return false;\n }\n\n switch (P.getVersion()){\n case DTSC::DTSC_V1:{\n if (detail >= 2){\n std::cout << \"DTSCv1 packet: \" << P.getScan().toPrettyString() << std::endl;\n }\n break;\n }\n case DTSC::DTSC_V2:{\n mediaTime = P.getTime();\n if (detail >= 2){\n std::cout << \"DTSCv2 packet (Track \" << P.getTrackId() << \", time \" << P.getTime()\n << \"): \" << P.getScan().toPrettyString() << std::endl;\n }\n break;\n }\n case DTSC::DTSC_HEAD:{\n if (detail >= 3){\n std::cout << \"DTSC header: \";\n DTSC::Meta(P).toPrettyString(std::cout, 0, (detail == 3 ? 0 : (detail == 4 ? 0x01 : (detail == 5 ? 0x03 : 0x07))));\n }\n if (detail == 2){std::cout << \"DTSC header: \" << P.getScan().toPrettyString() << std::endl;}\n if (detail == 1){\n bool hasH264 = false;\n bool hasAAC = false;\n JSON::Value result;\n std::stringstream issues;\n DTSC::Meta M(P);\n for (std::map<unsigned int, DTSC::Track>::iterator it = M.tracks.begin();\n it != M.tracks.end(); it++){\n JSON::Value track;\n track[\"kbits\"] = (long long)((double)it->second.bps * 8 \/ 1024);\n track[\"codec\"] = it->second.codec;\n uint32_t shrtest_key = 0xFFFFFFFFul;\n uint32_t longest_key = 0;\n uint32_t shrtest_prt = 0xFFFFFFFFul;\n uint32_t longest_prt = 0;\n uint32_t shrtest_cnt = 0xFFFFFFFFul;\n uint32_t longest_cnt = 0;\n for (std::deque<DTSC::Key>::iterator k = it->second.keys.begin();\n k != it->second.keys.end(); k++){\n if (!k->getLength()){continue;}\n if (k->getLength() > longest_key){longest_key = k->getLength();}\n if (k->getLength() < shrtest_key){shrtest_key = k->getLength();}\n if (k->getParts() > longest_cnt){longest_cnt = k->getParts();}\n if (k->getParts() < shrtest_cnt){shrtest_cnt = k->getParts();}\n if (k->getParts()){\n if ((k->getLength() \/ k->getParts()) > longest_prt){\n longest_prt = (k->getLength() \/ k->getParts());\n }\n if ((k->getLength() \/ k->getParts()) < shrtest_prt){\n shrtest_prt = (k->getLength() \/ k->getParts());\n }\n }\n }\n track[\"keys\"][\"ms_min\"] = (long long)shrtest_key;\n track[\"keys\"][\"ms_max\"] = (long long)longest_key;\n track[\"keys\"][\"frame_ms_min\"] = (long long)shrtest_prt;\n track[\"keys\"][\"frame_ms_max\"] = (long long)longest_prt;\n track[\"keys\"][\"frames_min\"] = (long long)shrtest_cnt;\n track[\"keys\"][\"frames_max\"] = (long long)longest_cnt;\n if (longest_prt > 500){\n issues << \"unstable connection (\" << longest_prt << \"ms \" << it->second.codec\n << \" frame)! \";\n }\n if (shrtest_cnt < 6){\n issues << \"unstable connection (\" << shrtest_cnt << \" \" << it->second.codec\n << \" frames in key)! \";\n }\n if (it->second.codec == \"AAC\"){hasAAC = true;}\n if (it->second.codec == \"H264\"){hasH264 = true;}\n if (it->second.type == \"video\"){\n track[\"width\"] = (long long)it->second.width;\n track[\"height\"] = (long long)it->second.height;\n track[\"fpks\"] = it->second.fpks;\n if (it->second.codec == \"H264\"){\n h264::sequenceParameterSet sps;\n sps.fromDTSCInit(it->second.init);\n h264::SPSMeta spsData = sps.getCharacteristics();\n track[\"h264\"][\"profile\"] = spsData.profile;\n track[\"h264\"][\"level\"] = spsData.level;\n }\n }\n result[it->second.getWritableIdentifier()] = track;\n }\n if ((hasAAC || hasH264) && M.tracks.size() > 1){\n if (!hasAAC){issues << \"HLS no audio!\";}\n if (!hasH264){issues << \"HLS no video!\";}\n }\n if (issues.str().size()){result[\"issues\"] = issues.str();}\n std::cout << result.toString() << std::endl;\n stop();\n }\n break;\n }\n case DTSC::DTCM:{\n if (detail >= 2){std::cout << \"DTCM command: \" << P.getScan().toPrettyString() << std::endl;}\n break;\n }\n default: FAIL_MSG(\"Invalid DTSC packet @ byte %llu\", totalBytes); break;\n }\n\n totalBytes += P.getDataLen();\n return true;\n}\n\n<commit_msg>Added raw data payload printing in hex to DTSC analyser<commit_after>#include \"analyser_dtsc.h\"\n#include <mist\/h264.h>\n#include <iomanip>\n\nvoid AnalyserDTSC::init(Util::Config &conf){\n Analyser::init(conf);\n}\n\nAnalyserDTSC::AnalyserDTSC(Util::Config &conf) : Analyser(conf){\n conn = Socket::Connection(0, fileno(stdin));\n totalBytes = 0;\n}\n\nbool AnalyserDTSC::parsePacket(){\n P.reInit(conn);\n if (conn && !P){\n FAIL_MSG(\"Invalid DTSC packet @ byte %llu\", totalBytes)\n return false;\n }\n if (!conn && !P){\n stop();\n return false;\n }\n\n switch (P.getVersion()){\n case DTSC::DTSC_V1:{\n if (detail >= 2){\n std::cout << \"DTSCv1 packet: \" << P.getScan().toPrettyString() << std::endl;\n }\n break;\n }\n case DTSC::DTSC_V2:{\n mediaTime = P.getTime();\n if (detail >= 2){\n std::cout << \"DTSCv2 packet (Track \" << P.getTrackId() << \", time \" << P.getTime()\n << \"): \" << P.getScan().toPrettyString() << std::endl;\n }\n if (detail >= 8){\n char * payDat;\n unsigned int payLen;\n P.getString(\"data\", payDat, payLen);\n for (uint64_t i = 0; i < payLen; ++i){\n if ((i % 32) == 0){std::cout << std::endl;}\n std::cout << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)payDat[i];\n }\n }\n break;\n }\n case DTSC::DTSC_HEAD:{\n if (detail >= 3){\n std::cout << \"DTSC header: \";\n DTSC::Meta(P).toPrettyString(std::cout, 0, (detail == 3 ? 0 : (detail == 4 ? 0x01 : (detail == 5 ? 0x03 : 0x07))));\n }\n if (detail == 2){std::cout << \"DTSC header: \" << P.getScan().toPrettyString() << std::endl;}\n if (detail == 1){\n bool hasH264 = false;\n bool hasAAC = false;\n JSON::Value result;\n std::stringstream issues;\n DTSC::Meta M(P);\n for (std::map<unsigned int, DTSC::Track>::iterator it = M.tracks.begin();\n it != M.tracks.end(); it++){\n JSON::Value track;\n track[\"kbits\"] = (long long)((double)it->second.bps * 8 \/ 1024);\n track[\"codec\"] = it->second.codec;\n uint32_t shrtest_key = 0xFFFFFFFFul;\n uint32_t longest_key = 0;\n uint32_t shrtest_prt = 0xFFFFFFFFul;\n uint32_t longest_prt = 0;\n uint32_t shrtest_cnt = 0xFFFFFFFFul;\n uint32_t longest_cnt = 0;\n for (std::deque<DTSC::Key>::iterator k = it->second.keys.begin();\n k != it->second.keys.end(); k++){\n if (!k->getLength()){continue;}\n if (k->getLength() > longest_key){longest_key = k->getLength();}\n if (k->getLength() < shrtest_key){shrtest_key = k->getLength();}\n if (k->getParts() > longest_cnt){longest_cnt = k->getParts();}\n if (k->getParts() < shrtest_cnt){shrtest_cnt = k->getParts();}\n if (k->getParts()){\n if ((k->getLength() \/ k->getParts()) > longest_prt){\n longest_prt = (k->getLength() \/ k->getParts());\n }\n if ((k->getLength() \/ k->getParts()) < shrtest_prt){\n shrtest_prt = (k->getLength() \/ k->getParts());\n }\n }\n }\n track[\"keys\"][\"ms_min\"] = (long long)shrtest_key;\n track[\"keys\"][\"ms_max\"] = (long long)longest_key;\n track[\"keys\"][\"frame_ms_min\"] = (long long)shrtest_prt;\n track[\"keys\"][\"frame_ms_max\"] = (long long)longest_prt;\n track[\"keys\"][\"frames_min\"] = (long long)shrtest_cnt;\n track[\"keys\"][\"frames_max\"] = (long long)longest_cnt;\n if (longest_prt > 500){\n issues << \"unstable connection (\" << longest_prt << \"ms \" << it->second.codec\n << \" frame)! \";\n }\n if (shrtest_cnt < 6){\n issues << \"unstable connection (\" << shrtest_cnt << \" \" << it->second.codec\n << \" frames in key)! \";\n }\n if (it->second.codec == \"AAC\"){hasAAC = true;}\n if (it->second.codec == \"H264\"){hasH264 = true;}\n if (it->second.type == \"video\"){\n track[\"width\"] = (long long)it->second.width;\n track[\"height\"] = (long long)it->second.height;\n track[\"fpks\"] = it->second.fpks;\n if (it->second.codec == \"H264\"){\n h264::sequenceParameterSet sps;\n sps.fromDTSCInit(it->second.init);\n h264::SPSMeta spsData = sps.getCharacteristics();\n track[\"h264\"][\"profile\"] = spsData.profile;\n track[\"h264\"][\"level\"] = spsData.level;\n }\n }\n result[it->second.getWritableIdentifier()] = track;\n }\n if ((hasAAC || hasH264) && M.tracks.size() > 1){\n if (!hasAAC){issues << \"HLS no audio!\";}\n if (!hasH264){issues << \"HLS no video!\";}\n }\n if (issues.str().size()){result[\"issues\"] = issues.str();}\n std::cout << result.toString() << std::endl;\n stop();\n }\n break;\n }\n case DTSC::DTCM:{\n if (detail >= 2){std::cout << \"DTCM command: \" << P.getScan().toPrettyString() << std::endl;}\n break;\n }\n default: FAIL_MSG(\"Invalid DTSC packet @ byte %llu\", totalBytes); break;\n }\n\n totalBytes += P.getDataLen();\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ \\file dtsc_analyser.cpp\n\/\/\/ Reads an DTSC file and prints all readable data about it\n\n#include <string>\n#include <iostream>\n#include <sstream>\n\n#include <mist\/dtsc.h>\n#include <mist\/json.h>\n#include <mist\/config.h>\n#include <mist\/defines.h>\n\n\/\/\/\\brief Holds everything unique to the analysers. \nnamespace Analysers {\n \/\/\/\\brief Debugging tool for DTSC data.\n \/\/\/\n \/\/\/ Expects DTSC data in a file given on the command line, outputs human-readable information to stderr.\n \/\/\/\\param conf The configuration parsed from the commandline.\n \/\/\/\\return The return code of the analyser.\n int analyseDTSC(Util::Config conf){\n DTSC::File F(conf.getString(\"filename\"));\n std::stringstream meta;\n F.getMeta().toPrettyString(meta,0, 0x03);\n std::cout << meta.str() << std::endl;\n\n int bPos = 0;\n F.seek_bpos(0);\n F.parseNext();\n JSON::Value tmp;\n std::string tmpStr;\n while (F.getPacket()){\n tmpStr = std::string(F.getPacket().getData(), F.getPacket().getDataLen());\n switch (F.getPacket().getVersion()){\n case DTSC::DTSC_V1: {\n unsigned int i = 8;\n JSON::fromDTMI((const unsigned char*)tmpStr.data(), tmpStr.size(), i, tmp);\n break;\n }\n case DTSC::DTSC_V2: {\n unsigned int i = 8;\n JSON::fromDTMI2((const unsigned char*)tmpStr.data(), tmpStr.size(), i, tmp);\n break;\n }\n default:\n DEBUG_MSG(DLVL_WARN,\"Invalid dtsc packet @ bpos %d\", bPos);\n break;\n }\n std::cout << tmp.toPrettyString() << std::endl;\n bPos = F.getBytePos();\n F.parseNext();\n }\n return 0;\n }\n}\n\n\/\/\/ Reads an DTSC file and prints all readable data about it\nint main(int argc, char ** argv){\n Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION);\n conf.addOption(\"filename\", JSON::fromString(\"{\\\"arg_num\\\":1, \\\"arg\\\":\\\"string\\\", \\\"help\\\":\\\"Filename of the DTSC file to analyse.\\\"}\"));\n conf.parseArgs(argc, argv);\n return Analysers::analyseDTSC(conf);\n} \/\/main\n<commit_msg>Updates to the DTSC analyser - not fully complete, but still nice.<commit_after>\/\/\/ \\file dtsc_analyser.cpp\n\/\/\/ Reads an DTSC file and prints all readable data about it\n\n#include <string>\n#include <iostream>\n#include <sstream>\n\n#include <mist\/dtsc.h>\n#include <mist\/json.h>\n#include <mist\/config.h>\n#include <mist\/defines.h>\n\n\/\/\/\\brief Holds everything unique to the analysers. \nnamespace Analysers {\n \/\/\/\\brief Debugging tool for DTSC data.\n \/\/\/\n \/\/\/ Expects DTSC data in a file given on the command line, outputs human-readable information to stderr.\n \/\/\/\\param conf The configuration parsed from the commandline.\n \/\/\/\\return The return code of the analyser.\n int analyseDTSC(Util::Config conf){\n DTSC::File F(conf.getString(\"filename\"));\n F.getMeta().toPrettyString(std::cout,0, 0x03);\n\n int bPos = 0;\n F.seek_bpos(0);\n F.parseNext();\n JSON::Value tmp;\n std::string tmpStr;\n while (F.getPacket()){\n switch (F.getPacket().getVersion()){\n case DTSC::DTSC_V1: {\n std::cout << \"DTSCv1 packet: \" << F.getPacket().getScan().toPrettyString() << std::endl;\n break;\n }\n case DTSC::DTSC_V2: {\n std::cout << \"DTSCv2 packet: \" << F.getPacket().getScan().toPrettyString() << std::endl;\n break;\n }\n default:\n DEBUG_MSG(DLVL_WARN,\"Invalid dtsc packet @ bpos %d\", bPos);\n break;\n }\n std::cout << tmp.toPrettyString() << std::endl;\n bPos = F.getBytePos();\n F.parseNext();\n }\n return 0;\n }\n}\n\n\/\/\/ Reads an DTSC file and prints all readable data about it\nint main(int argc, char ** argv){\n Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION);\n conf.addOption(\"filename\", JSON::fromString(\"{\\\"arg_num\\\":1, \\\"arg\\\":\\\"string\\\", \\\"help\\\":\\\"Filename of the DTSC file to analyse.\\\"}\"));\n conf.parseArgs(argc, argv);\n return Analysers::analyseDTSC(conf);\n} \/\/main\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#include \"arch\/runtime\/message_hub.hpp\"\n\n#include <math.h>\n#include <unistd.h>\n#include <algorithm>\n\n#include \"config\/args.hpp\"\n#include \"arch\/runtime\/event_queue.hpp\"\n#include \"arch\/runtime\/thread_pool.hpp\"\n#include \"logger.hpp\"\n\n\/\/ Set this to 1 if you would like some \"unordered\" messages to be unordered.\n#ifndef NDEBUG\n#define RDB_RELOOP_MESSAGES 0\n#endif\n\nlinux_message_hub_t::linux_message_hub_t(linux_event_queue_t *queue,\n linux_thread_pool_t *thread_pool,\n threadnum_t current_thread)\n : queue_(queue),\n thread_pool_(thread_pool),\n is_woken_up_(false),\n current_thread_(current_thread) {\n\n#ifndef NDEBUG\n if(MESSAGE_SCHEDULER_GRANULARITY < (1 >> (MESSAGE_SCHEDULER_MAX_PRIORITY\n - MESSAGE_SCHEDULER_MIN_PRIORITY\n + 1))) {\n logWRN(\"MESSAGE_SCHEDULER_GRANULARITY is too small to honor some of the \"\n \"lower priorities\");\n }\n#endif\n\n queue_->watch_resource(event_.get_notify_fd(), poll_event_in, this);\n}\n\nlinux_message_hub_t::~linux_message_hub_t() {\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n guarantee(queues_[i].msg_local_list.empty());\n }\n for (int p = MESSAGE_SCHEDULER_MIN_PRIORITY;\n p <= MESSAGE_SCHEDULER_MAX_PRIORITY;\n ++p) {\n\n guarantee(get_priority_msg_list(p).empty());\n }\n\n guarantee(incoming_messages_.empty());\n}\n\nvoid linux_message_hub_t::do_store_message(threadnum_t nthread, linux_thread_message_t *msg) {\n rassert(0 <= nthread.threadnum && nthread.threadnum < thread_pool_->n_threads);\n queues_[nthread.threadnum].msg_local_list.push_back(msg);\n}\n\n\/\/ Collects a message for a given thread onto a local list.\nvoid linux_message_hub_t::store_message_ordered(threadnum_t nthread,\n linux_thread_message_t *msg) {\n rassert(!msg->is_ordered); \/\/ Each message object can only be enqueued once,\n \/\/ and once it is removed, is_ordered is reset to false.\n#ifndef NDEBUG\n#if RDB_RELOOP_MESSAGES\n \/\/ We default to 1, not zero, to allow store_message_sometime messages to sometimes jump ahead of\n \/\/ store_message messages.\n msg->reloop_count_ = 1;\n#else\n msg->reloop_count_ = 0;\n#endif\n#endif \/\/ NDEBUG\n msg->is_ordered = true;\n do_store_message(nthread, msg);\n}\n\nint rand_reloop_count() {\n int x;\n frexp(randint(10000) \/ 10000.0, &x);\n int ret = -x;\n rassert(ret >= 0);\n return ret;\n}\n\nvoid linux_message_hub_t::store_message_sometime(threadnum_t nthread, linux_thread_message_t *msg) {\n#ifndef NDEBUG\n#if RDB_RELOOP_MESSAGES\n msg->reloop_count_ = rand_reloop_count();\n#else\n msg->reloop_count_ = 0;\n#endif\n#endif \/\/ NDEBUG\n do_store_message(nthread, msg);\n}\n\n\nvoid linux_message_hub_t::insert_external_message(linux_thread_message_t *msg) {\n bool do_wake_up;\n {\n spinlock_acq_t acq(&incoming_messages_lock_);\n do_wake_up = !check_and_set_is_woken_up();\n incoming_messages_.push_back(msg);\n }\n\n \/\/ Wakey wakey eggs and bakey\n if (do_wake_up) {\n event_.wakey_wakey();\n }\n}\n\nlinux_message_hub_t::msg_list_t &linux_message_hub_t::get_priority_msg_list(int priority) {\n rassert(priority >= MESSAGE_SCHEDULER_MIN_PRIORITY);\n rassert(priority <= MESSAGE_SCHEDULER_MAX_PRIORITY);\n return priority_msg_lists_[priority - MESSAGE_SCHEDULER_MIN_PRIORITY];\n}\n\nvoid linux_message_hub_t::on_event(int events) {\n if (events != poll_event_in) {\n logERR(\"Unexpected event mask: %d\", events);\n }\n\n \/\/ You must read wakey-wakeys so that the pipe-based implementation doesn't fill\n \/\/ up and so that poll-based event triggering doesn't infinite-loop.\n event_.consume_wakey_wakeys();\n\n#ifndef NDEBUG\n start_watchdog(); \/\/ Initialize watchdog before handling messages\n#endif\n\n const int num_priorities = MESSAGE_SCHEDULER_MAX_PRIORITY\n - MESSAGE_SCHEDULER_MIN_PRIORITY\n + 1;\n\n \/\/ Loop until we have processed at least the initial batch of messages.\n size_t num_initial_msgs_left_to_process[num_priorities];\n bool initial_batch_has_been_processed = false;\n bool initial_pass = true;\n do {\n if (!initial_pass) {\n \/\/ Other threads will automatically push their messages\n \/\/ for us into the incoming queue, even while\n \/\/ we are in this loop. However we still have to pick up\n \/\/ our local messages, since this->push_messages() is not\n \/\/ going to be called while we are still running on_event()\n deliver_local_messages();\n }\n\n \/\/ We guarantee to process all messages that are delivered\n \/\/ before the first pass. We do not guarantee to deliver\n \/\/ incoming messages delivered during !initial_pass!\n \/\/ As a consequence, we must reset is_woken_up_ in the first\n \/\/ pass, so later incoming messages wake us up again.\n const bool reset_is_woken_up = initial_pass;\n sort_incoming_messages_by_priority(reset_is_woken_up);\n\n \/\/ We store how many messages we have initially for each priority.\n \/\/ Those are the messages that we *definitely* have to process during\n \/\/ this call to `on_event()`.\n \/\/ We *may* process more messages than this, such that more recent\n \/\/ messages with a high-priority can bypass older messages with lower\n \/\/ priority.\n if (initial_pass) {\n for (int i = 0; i < num_priorities; ++i) {\n num_initial_msgs_left_to_process[i] = priority_msg_lists_[i].size();\n }\n initial_pass = false;\n }\n\n \/\/ Compute how many messages of MESSAGE_SCHEDULER_MAX_PRIORITY we process\n \/\/ before we check the incoming queues for new messages.\n \/\/ We call this the granularity of the message scheduler, and it is\n \/\/ MESSAGE_SCHEDULER_GRANULARITY or smaller.\n size_t total_pending_msgs = 0;\n for (int i = 0; i < num_priorities; ++i) {\n total_pending_msgs += priority_msg_lists_[i].size();\n }\n const size_t effective_granularity = std::min(total_pending_msgs,\n MESSAGE_SCHEDULER_GRANULARITY);\n\n \/\/ Process a certain number of messages from each priority\n for (int current_priority = MESSAGE_SCHEDULER_MAX_PRIORITY;\n current_priority >= MESSAGE_SCHEDULER_MIN_PRIORITY; --current_priority) {\n\n \/\/ Compute how many messages of `current_priority` we want to process\n \/\/ in this pass.\n \/\/ The priority has an exponential effect on how many messages\n \/\/ get processed, i.e. if we process 8 messages of priority 1 per pass,\n \/\/ we are going to process up to 16 messages of priority 2, 32 of\n \/\/ priority 3 and so on.\n \/\/ However, we process at least one message of each priority level per\n \/\/ pass (in case the granularity is too small).\n int priority_exponent = MESSAGE_SCHEDULER_MAX_PRIORITY - current_priority;\n size_t to_process_from_priority = std::max(1ul, effective_granularity >> priority_exponent);\n\n while (linux_thread_message_t *m = get_priority_msg_list(current_priority).head()) {\n if (to_process_from_priority == 0) break;\n\n get_priority_msg_list(current_priority).remove(m);\n --to_process_from_priority;\n if (num_initial_msgs_left_to_process[current_priority - MESSAGE_SCHEDULER_MIN_PRIORITY] > 0) {\n \/\/ About to process one of the initial messages\n --num_initial_msgs_left_to_process[current_priority - MESSAGE_SCHEDULER_MIN_PRIORITY];\n }\n\n#ifndef NDEBUG\n if (m->reloop_count_ > 0) {\n --m->reloop_count_;\n do_store_message(current_thread_, m);\n continue;\n }\n#endif\n\n m->on_thread_switch();\n\n#ifndef NDEBUG\n pet_watchdog(); \/\/ Verify that each message completes in the acceptable time range\n#endif\n }\n }\n\n \/\/ Check if we have to continue in order to fulfill our guarantee\n \/\/ to at least process all of the initial messages.\n initial_batch_has_been_processed = true;\n for (int i = 0; i < num_priorities; ++i) {\n if (num_initial_msgs_left_to_process[i] > 0) {\n initial_batch_has_been_processed = false;\n break;\n }\n }\n } while (!initial_batch_has_been_processed);\n}\n\nvoid linux_message_hub_t::sort_incoming_messages_by_priority(bool reset_is_woken_up) {\n \/\/ We do this in two steps to release the spinlock faster.\n \/\/ append_and_clear is a very cheap operation, while\n \/\/ assigning each message to a different priority queue\n \/\/ is more expensive.\n\n \/\/ 1. Pull the messages\n msg_list_t new_messages;\n {\n spinlock_acq_t acq(&incoming_messages_lock_);\n new_messages.append_and_clear(&incoming_messages_);\n if (reset_is_woken_up) {\n is_woken_up_ = false;\n }\n }\n\n \/\/ 2. Sort the messages into their respective priority queues\n while (linux_thread_message_t *m = new_messages.head()) {\n new_messages.remove(m);\n int effective_priority = m->priority;\n if (m->is_ordered) {\n \/\/ Ordered messages are treated as if they had\n \/\/ priority MESSAGE_SCHEDULER_ORDERED_PRIORITY.\n \/\/ This ensures that they can never bypass another\n \/\/ ordered message.\n effective_priority = MESSAGE_SCHEDULER_ORDERED_PRIORITY;\n m->is_ordered = false;\n }\n get_priority_msg_list(effective_priority).push_back(m);\n }\n}\n\nvoid linux_message_hub_t::deliver_local_messages() {\n const int local_thread = thread_pool_->thread_id;\n\n if (!queues_[local_thread].msg_local_list.empty()) {\n bool do_wake_up;\n {\n spinlock_acq_t acq(&incoming_messages_lock_);\n incoming_messages_.append_and_clear(&queues_[local_thread].msg_local_list);\n do_wake_up = !check_and_set_is_woken_up();\n }\n if (do_wake_up) {\n \/\/ Wake ourselves up for another round.\n \/\/ While this might seem risky w.r.t. dead-locks when the event pipe\n \/\/ is full, it is actually ok because the is_woken_up() flag guarantees\n \/\/ that we only ever write one event onto this.\n event_.wakey_wakey();\n }\n }\n}\n\nbool linux_message_hub_t::check_and_set_is_woken_up() {\n const bool was_woken_up = is_woken_up_;\n is_woken_up_ = true;\n return was_woken_up;\n}\n\n\/\/ Pushes messages collected locally global lists available to all\n\/\/ threads.\nvoid linux_message_hub_t::push_messages() {\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n \/\/ Append the local list for ith thread to that thread's global\n \/\/ message list.\n thread_queue_t *queue = &queues_[i];\n if (!queue->msg_local_list.empty()) {\n \/\/ Transfer messages to the other core\n\n bool do_wake_up;\n {\n spinlock_acq_t acq(&thread_pool_->threads[i]->message_hub.incoming_messages_lock_);\n\n \/\/ We only need to do a wake up if we're the first people to do a\n \/\/ wake up.\n do_wake_up =\n !thread_pool_->threads[i]->message_hub.check_and_set_is_woken_up();\n\n thread_pool_->threads[i]->message_hub.incoming_messages_.append_and_clear(&queue->msg_local_list);\n }\n\n \/\/ Wakey wakey, perhaps eggs and bakey\n if (do_wake_up) {\n thread_pool_->threads[i]->message_hub.event_.wakey_wakey();\n }\n }\n }\n}\n<commit_msg>Removed unnecessary include<commit_after>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#include \"arch\/runtime\/message_hub.hpp\"\n\n#include <math.h>\n#include <unistd.h>\n\n#include \"config\/args.hpp\"\n#include \"arch\/runtime\/event_queue.hpp\"\n#include \"arch\/runtime\/thread_pool.hpp\"\n#include \"logger.hpp\"\n\n\/\/ Set this to 1 if you would like some \"unordered\" messages to be unordered.\n#ifndef NDEBUG\n#define RDB_RELOOP_MESSAGES 0\n#endif\n\nlinux_message_hub_t::linux_message_hub_t(linux_event_queue_t *queue,\n linux_thread_pool_t *thread_pool,\n threadnum_t current_thread)\n : queue_(queue),\n thread_pool_(thread_pool),\n is_woken_up_(false),\n current_thread_(current_thread) {\n\n#ifndef NDEBUG\n if(MESSAGE_SCHEDULER_GRANULARITY < (1 >> (MESSAGE_SCHEDULER_MAX_PRIORITY\n - MESSAGE_SCHEDULER_MIN_PRIORITY\n + 1))) {\n logWRN(\"MESSAGE_SCHEDULER_GRANULARITY is too small to honor some of the \"\n \"lower priorities\");\n }\n#endif\n\n queue_->watch_resource(event_.get_notify_fd(), poll_event_in, this);\n}\n\nlinux_message_hub_t::~linux_message_hub_t() {\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n guarantee(queues_[i].msg_local_list.empty());\n }\n for (int p = MESSAGE_SCHEDULER_MIN_PRIORITY;\n p <= MESSAGE_SCHEDULER_MAX_PRIORITY;\n ++p) {\n\n guarantee(get_priority_msg_list(p).empty());\n }\n\n guarantee(incoming_messages_.empty());\n}\n\nvoid linux_message_hub_t::do_store_message(threadnum_t nthread, linux_thread_message_t *msg) {\n rassert(0 <= nthread.threadnum && nthread.threadnum < thread_pool_->n_threads);\n queues_[nthread.threadnum].msg_local_list.push_back(msg);\n}\n\n\/\/ Collects a message for a given thread onto a local list.\nvoid linux_message_hub_t::store_message_ordered(threadnum_t nthread,\n linux_thread_message_t *msg) {\n rassert(!msg->is_ordered); \/\/ Each message object can only be enqueued once,\n \/\/ and once it is removed, is_ordered is reset to false.\n#ifndef NDEBUG\n#if RDB_RELOOP_MESSAGES\n \/\/ We default to 1, not zero, to allow store_message_sometime messages to sometimes jump ahead of\n \/\/ store_message messages.\n msg->reloop_count_ = 1;\n#else\n msg->reloop_count_ = 0;\n#endif\n#endif \/\/ NDEBUG\n msg->is_ordered = true;\n do_store_message(nthread, msg);\n}\n\nint rand_reloop_count() {\n int x;\n frexp(randint(10000) \/ 10000.0, &x);\n int ret = -x;\n rassert(ret >= 0);\n return ret;\n}\n\nvoid linux_message_hub_t::store_message_sometime(threadnum_t nthread, linux_thread_message_t *msg) {\n#ifndef NDEBUG\n#if RDB_RELOOP_MESSAGES\n msg->reloop_count_ = rand_reloop_count();\n#else\n msg->reloop_count_ = 0;\n#endif\n#endif \/\/ NDEBUG\n do_store_message(nthread, msg);\n}\n\n\nvoid linux_message_hub_t::insert_external_message(linux_thread_message_t *msg) {\n bool do_wake_up;\n {\n spinlock_acq_t acq(&incoming_messages_lock_);\n do_wake_up = !check_and_set_is_woken_up();\n incoming_messages_.push_back(msg);\n }\n\n \/\/ Wakey wakey eggs and bakey\n if (do_wake_up) {\n event_.wakey_wakey();\n }\n}\n\nlinux_message_hub_t::msg_list_t &linux_message_hub_t::get_priority_msg_list(int priority) {\n rassert(priority >= MESSAGE_SCHEDULER_MIN_PRIORITY);\n rassert(priority <= MESSAGE_SCHEDULER_MAX_PRIORITY);\n return priority_msg_lists_[priority - MESSAGE_SCHEDULER_MIN_PRIORITY];\n}\n\nvoid linux_message_hub_t::on_event(int events) {\n if (events != poll_event_in) {\n logERR(\"Unexpected event mask: %d\", events);\n }\n\n \/\/ You must read wakey-wakeys so that the pipe-based implementation doesn't fill\n \/\/ up and so that poll-based event triggering doesn't infinite-loop.\n event_.consume_wakey_wakeys();\n\n#ifndef NDEBUG\n start_watchdog(); \/\/ Initialize watchdog before handling messages\n#endif\n\n const int num_priorities = MESSAGE_SCHEDULER_MAX_PRIORITY\n - MESSAGE_SCHEDULER_MIN_PRIORITY\n + 1;\n\n \/\/ Loop until we have processed at least the initial batch of messages.\n size_t num_initial_msgs_left_to_process[num_priorities];\n bool initial_batch_has_been_processed = false;\n bool initial_pass = true;\n do {\n if (!initial_pass) {\n \/\/ Other threads will automatically push their messages\n \/\/ for us into the incoming queue, even while\n \/\/ we are in this loop. However we still have to pick up\n \/\/ our local messages, since this->push_messages() is not\n \/\/ going to be called while we are still running on_event()\n deliver_local_messages();\n }\n\n \/\/ We guarantee to process all messages that are delivered\n \/\/ before the first pass. We do not guarantee to deliver\n \/\/ incoming messages delivered during !initial_pass!\n \/\/ As a consequence, we must reset is_woken_up_ in the first\n \/\/ pass, so later incoming messages wake us up again.\n const bool reset_is_woken_up = initial_pass;\n sort_incoming_messages_by_priority(reset_is_woken_up);\n\n \/\/ We store how many messages we have initially for each priority.\n \/\/ Those are the messages that we *definitely* have to process during\n \/\/ this call to `on_event()`.\n \/\/ We *may* process more messages than this, such that more recent\n \/\/ messages with a high-priority can bypass older messages with lower\n \/\/ priority.\n if (initial_pass) {\n for (int i = 0; i < num_priorities; ++i) {\n num_initial_msgs_left_to_process[i] = priority_msg_lists_[i].size();\n }\n initial_pass = false;\n }\n\n \/\/ Compute how many messages of MESSAGE_SCHEDULER_MAX_PRIORITY we process\n \/\/ before we check the incoming queues for new messages.\n \/\/ We call this the granularity of the message scheduler, and it is\n \/\/ MESSAGE_SCHEDULER_GRANULARITY or smaller.\n size_t total_pending_msgs = 0;\n for (int i = 0; i < num_priorities; ++i) {\n total_pending_msgs += priority_msg_lists_[i].size();\n }\n const size_t effective_granularity = std::min(total_pending_msgs,\n MESSAGE_SCHEDULER_GRANULARITY);\n\n \/\/ Process a certain number of messages from each priority\n for (int current_priority = MESSAGE_SCHEDULER_MAX_PRIORITY;\n current_priority >= MESSAGE_SCHEDULER_MIN_PRIORITY; --current_priority) {\n\n \/\/ Compute how many messages of `current_priority` we want to process\n \/\/ in this pass.\n \/\/ The priority has an exponential effect on how many messages\n \/\/ get processed, i.e. if we process 8 messages of priority 1 per pass,\n \/\/ we are going to process up to 16 messages of priority 2, 32 of\n \/\/ priority 3 and so on.\n \/\/ However, we process at least one message of each priority level per\n \/\/ pass (in case the granularity is too small).\n int priority_exponent = MESSAGE_SCHEDULER_MAX_PRIORITY - current_priority;\n size_t to_process_from_priority = std::max(1ul, effective_granularity >> priority_exponent);\n\n while (linux_thread_message_t *m = get_priority_msg_list(current_priority).head()) {\n if (to_process_from_priority == 0) break;\n\n get_priority_msg_list(current_priority).remove(m);\n --to_process_from_priority;\n if (num_initial_msgs_left_to_process[current_priority - MESSAGE_SCHEDULER_MIN_PRIORITY] > 0) {\n \/\/ About to process one of the initial messages\n --num_initial_msgs_left_to_process[current_priority - MESSAGE_SCHEDULER_MIN_PRIORITY];\n }\n\n#ifndef NDEBUG\n if (m->reloop_count_ > 0) {\n --m->reloop_count_;\n do_store_message(current_thread_, m);\n continue;\n }\n#endif\n\n m->on_thread_switch();\n\n#ifndef NDEBUG\n pet_watchdog(); \/\/ Verify that each message completes in the acceptable time range\n#endif\n }\n }\n\n \/\/ Check if we have to continue in order to fulfill our guarantee\n \/\/ to at least process all of the initial messages.\n initial_batch_has_been_processed = true;\n for (int i = 0; i < num_priorities; ++i) {\n if (num_initial_msgs_left_to_process[i] > 0) {\n initial_batch_has_been_processed = false;\n break;\n }\n }\n } while (!initial_batch_has_been_processed);\n}\n\nvoid linux_message_hub_t::sort_incoming_messages_by_priority(bool reset_is_woken_up) {\n \/\/ We do this in two steps to release the spinlock faster.\n \/\/ append_and_clear is a very cheap operation, while\n \/\/ assigning each message to a different priority queue\n \/\/ is more expensive.\n\n \/\/ 1. Pull the messages\n msg_list_t new_messages;\n {\n spinlock_acq_t acq(&incoming_messages_lock_);\n new_messages.append_and_clear(&incoming_messages_);\n if (reset_is_woken_up) {\n is_woken_up_ = false;\n }\n }\n\n \/\/ 2. Sort the messages into their respective priority queues\n while (linux_thread_message_t *m = new_messages.head()) {\n new_messages.remove(m);\n int effective_priority = m->priority;\n if (m->is_ordered) {\n \/\/ Ordered messages are treated as if they had\n \/\/ priority MESSAGE_SCHEDULER_ORDERED_PRIORITY.\n \/\/ This ensures that they can never bypass another\n \/\/ ordered message.\n effective_priority = MESSAGE_SCHEDULER_ORDERED_PRIORITY;\n m->is_ordered = false;\n }\n get_priority_msg_list(effective_priority).push_back(m);\n }\n}\n\nvoid linux_message_hub_t::deliver_local_messages() {\n const int local_thread = thread_pool_->thread_id;\n\n if (!queues_[local_thread].msg_local_list.empty()) {\n bool do_wake_up;\n {\n spinlock_acq_t acq(&incoming_messages_lock_);\n incoming_messages_.append_and_clear(&queues_[local_thread].msg_local_list);\n do_wake_up = !check_and_set_is_woken_up();\n }\n if (do_wake_up) {\n \/\/ Wake ourselves up for another round.\n \/\/ While this might seem risky w.r.t. dead-locks when the event pipe\n \/\/ is full, it is actually ok because the is_woken_up() flag guarantees\n \/\/ that we only ever write one event onto this.\n event_.wakey_wakey();\n }\n }\n}\n\nbool linux_message_hub_t::check_and_set_is_woken_up() {\n const bool was_woken_up = is_woken_up_;\n is_woken_up_ = true;\n return was_woken_up;\n}\n\n\/\/ Pushes messages collected locally global lists available to all\n\/\/ threads.\nvoid linux_message_hub_t::push_messages() {\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n \/\/ Append the local list for ith thread to that thread's global\n \/\/ message list.\n thread_queue_t *queue = &queues_[i];\n if (!queue->msg_local_list.empty()) {\n \/\/ Transfer messages to the other core\n\n bool do_wake_up;\n {\n spinlock_acq_t acq(&thread_pool_->threads[i]->message_hub.incoming_messages_lock_);\n\n \/\/ We only need to do a wake up if we're the first people to do a\n \/\/ wake up.\n do_wake_up =\n !thread_pool_->threads[i]->message_hub.check_and_set_is_woken_up();\n\n thread_pool_->threads[i]->message_hub.incoming_messages_.append_and_clear(&queue->msg_local_list);\n }\n\n \/\/ Wakey wakey, perhaps eggs and bakey\n if (do_wake_up) {\n thread_pool_->threads[i]->message_hub.event_.wakey_wakey();\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: numberingtypelistbox.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: os $ $Date: 2002-11-21 09:29: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#ifdef PRECOMPILED\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#ifndef _NUMBERINGTYPELISTBOX_HXX\n#include <numberingtypelistbox.hxx>\n#endif\n#ifndef _MISC_HRC\n#include <misc.hrc>\n#endif\n#ifndef _CNTTAB_HXX\n#include <cnttab.hxx>\n#endif\n#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_\n#include <com\/sun\/star\/style\/NumberingType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_TEXT_XDEFAULTNUMBERINGPROVIDER_HPP_\n#include <com\/sun\/star\/text\/XDefaultNumberingProvider.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _COM_SUN_STAR_TEXT_XNUMBERINGTYPEINFO_HPP_\n#include <com\/sun\/star\/text\/XNumberingTypeInfo.hpp>\n#endif\n#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX\n#include <svtools\/languageoptions.hxx>\n#endif\n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::text;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::style;\nusing namespace rtl;\n\n#define C2S(cChar) UniString::CreateFromAscii(cChar)\n\/* -----------------------------01.03.01 16:04--------------------------------\n\n ---------------------------------------------------------------------------*\/\nstruct SwNumberingTypeListBox_Impl\n{\n Reference<XNumberingTypeInfo> xInfo;\n};\n\/* -----------------------------01.03.01 14:46--------------------------------\n\n ---------------------------------------------------------------------------*\/\nSwNumberingTypeListBox::SwNumberingTypeListBox( Window* pWin, const ResId& rResId,\n USHORT nTypeFlags ) :\n ListBox(pWin, rResId),\n pImpl(new SwNumberingTypeListBox_Impl)\n{\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n Reference < XInterface > xI = xMSF->createInstance(\n ::rtl::OUString::createFromAscii( \"com.sun.star.text.DefaultNumberingProvider\" ) );\n Reference<XDefaultNumberingProvider> xDefNum(xI, UNO_QUERY);\n DBG_ASSERT(xDefNum.is(), \"service missing: \\\"com.sun.star.text.DefaultNumberingProvider\\\"\")\n\n pImpl->xInfo = Reference<XNumberingTypeInfo>(xDefNum, UNO_QUERY);\n Reload(nTypeFlags);\n}\n\/* -----------------------------01.03.01 14:46--------------------------------\n\n ---------------------------------------------------------------------------*\/\nSwNumberingTypeListBox::~SwNumberingTypeListBox()\n{\n delete pImpl;\n}\n\/* -----------------------------01.03.01 16:02--------------------------------\n\n ---------------------------------------------------------------------------*\/\nvoid SwNumberingTypeListBox::Reload(USHORT nTypeFlags)\n{\n Clear();\n SwOLENames aNames(SW_RES(STRRES_NUMTYPES));\n ResStringArray& rNames = aNames.GetNames();\n for(sal_uInt16 i = 0; i < rNames.Count(); i++)\n {\n long nValue = rNames.GetValue(i);\n sal_Bool bInsert = sal_True;\n USHORT nPos = LISTBOX_APPEND;\n switch(nValue)\n {\n case NumberingType::NUMBER_NONE:\n bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_NO_NUMBERING);\n nPos = 0;\n break;\n case NumberingType::CHAR_SPECIAL: bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BULLET); break;\n case NumberingType::PAGE_DESCRIPTOR:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING); break;\n case NumberingType::BITMAP:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BITMAP ); break;\n }\n if(bInsert)\n {\n USHORT nEntry = InsertEntry(rNames.GetString(i), nPos);\n SetEntryData( nEntry, (void*)nValue );\n }\n }\n \/\/#104079# extended numberings are only insert when CJK support is switched on\n SvtLanguageOptions aLangOpt;\n if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) &&\n (aLangOpt.IsCJKFontEnabled() || aLangOpt.IsCTLFontEnabled()))\n {\n if(pImpl->xInfo.is())\n {\n Sequence<sal_Int16> aTypes = pImpl->xInfo->getSupportedNumberingTypes( );\n const sal_Int16* pTypes = aTypes.getConstArray();\n for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)\n {\n sal_Int16 nCurrent = pTypes[nType];\n if(nCurrent > NumberingType::CHARS_LOWER_LETTER_N)\n {\n if(LISTBOX_ENTRY_NOTFOUND == GetEntryPos((void*)(ULONG)nCurrent))\n {\n OUString aIdent = pImpl->xInfo->getNumberingIdentifier( nCurrent );\n USHORT nPos = InsertEntry(aIdent);\n SetEntryData(nPos,(void*)(ULONG)nCurrent);\n }\n }\n }\n }\n SelectEntryPos(0);\n }\n}\n\/* -----------------------------01.03.01 14:46--------------------------------\n\n ---------------------------------------------------------------------------*\/\nsal_Int16 SwNumberingTypeListBox::GetSelectedNumberingType()\n{\n sal_Int16 nRet = 0;\n USHORT nSelPos = GetSelectEntryPos();\n if(LISTBOX_ENTRY_NOTFOUND != nSelPos)\n nRet = (sal_Int16)(ULONG)GetEntryData(nSelPos);\n#ifdef DBG_UTIL\n else\n DBG_ERROR(\"SwNumberingTypeListBox not selected\")\n#endif\n return nRet;\n}\n\/* -----------------------------01.03.01 14:46--------------------------------\n\n ---------------------------------------------------------------------------*\/\nsal_Bool SwNumberingTypeListBox::SelectNumberingType(sal_Int16 nType)\n{\n USHORT nPos = GetEntryPos((void*)(ULONG)nType);\n SelectEntryPos( nPos );\n return LISTBOX_ENTRY_NOTFOUND != nPos;\n}\n\n<commit_msg>INTEGRATION: CWS os8 (1.5.138); FILE MERGED 2003\/04\/03 07:14:46 os 1.5.138.1: #108583# precompiled headers removed<commit_after>\/*************************************************************************\n *\n * $RCSfile: numberingtypelistbox.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 15:37:15 $\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#pragma hdrstop\n\n#ifndef _NUMBERINGTYPELISTBOX_HXX\n#include <numberingtypelistbox.hxx>\n#endif\n#ifndef _MISC_HRC\n#include <misc.hrc>\n#endif\n#ifndef _CNTTAB_HXX\n#include <cnttab.hxx>\n#endif\n#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_\n#include <com\/sun\/star\/style\/NumberingType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_TEXT_XDEFAULTNUMBERINGPROVIDER_HPP_\n#include <com\/sun\/star\/text\/XDefaultNumberingProvider.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _COM_SUN_STAR_TEXT_XNUMBERINGTYPEINFO_HPP_\n#include <com\/sun\/star\/text\/XNumberingTypeInfo.hpp>\n#endif\n#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX\n#include <svtools\/languageoptions.hxx>\n#endif\n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::text;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::style;\nusing namespace rtl;\n\n#define C2S(cChar) UniString::CreateFromAscii(cChar)\n\/* -----------------------------01.03.01 16:04--------------------------------\n\n ---------------------------------------------------------------------------*\/\nstruct SwNumberingTypeListBox_Impl\n{\n Reference<XNumberingTypeInfo> xInfo;\n};\n\/* -----------------------------01.03.01 14:46--------------------------------\n\n ---------------------------------------------------------------------------*\/\nSwNumberingTypeListBox::SwNumberingTypeListBox( Window* pWin, const ResId& rResId,\n USHORT nTypeFlags ) :\n ListBox(pWin, rResId),\n pImpl(new SwNumberingTypeListBox_Impl)\n{\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n Reference < XInterface > xI = xMSF->createInstance(\n ::rtl::OUString::createFromAscii( \"com.sun.star.text.DefaultNumberingProvider\" ) );\n Reference<XDefaultNumberingProvider> xDefNum(xI, UNO_QUERY);\n DBG_ASSERT(xDefNum.is(), \"service missing: \\\"com.sun.star.text.DefaultNumberingProvider\\\"\")\n\n pImpl->xInfo = Reference<XNumberingTypeInfo>(xDefNum, UNO_QUERY);\n Reload(nTypeFlags);\n}\n\/* -----------------------------01.03.01 14:46--------------------------------\n\n ---------------------------------------------------------------------------*\/\nSwNumberingTypeListBox::~SwNumberingTypeListBox()\n{\n delete pImpl;\n}\n\/* -----------------------------01.03.01 16:02--------------------------------\n\n ---------------------------------------------------------------------------*\/\nvoid SwNumberingTypeListBox::Reload(USHORT nTypeFlags)\n{\n Clear();\n SwOLENames aNames(SW_RES(STRRES_NUMTYPES));\n ResStringArray& rNames = aNames.GetNames();\n for(sal_uInt16 i = 0; i < rNames.Count(); i++)\n {\n long nValue = rNames.GetValue(i);\n sal_Bool bInsert = sal_True;\n USHORT nPos = LISTBOX_APPEND;\n switch(nValue)\n {\n case NumberingType::NUMBER_NONE:\n bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_NO_NUMBERING);\n nPos = 0;\n break;\n case NumberingType::CHAR_SPECIAL: bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BULLET); break;\n case NumberingType::PAGE_DESCRIPTOR:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING); break;\n case NumberingType::BITMAP:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BITMAP ); break;\n }\n if(bInsert)\n {\n USHORT nEntry = InsertEntry(rNames.GetString(i), nPos);\n SetEntryData( nEntry, (void*)nValue );\n }\n }\n \/\/#104079# extended numberings are only insert when CJK support is switched on\n SvtLanguageOptions aLangOpt;\n if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) &&\n (aLangOpt.IsCJKFontEnabled() || aLangOpt.IsCTLFontEnabled()))\n {\n if(pImpl->xInfo.is())\n {\n Sequence<sal_Int16> aTypes = pImpl->xInfo->getSupportedNumberingTypes( );\n const sal_Int16* pTypes = aTypes.getConstArray();\n for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)\n {\n sal_Int16 nCurrent = pTypes[nType];\n if(nCurrent > NumberingType::CHARS_LOWER_LETTER_N)\n {\n if(LISTBOX_ENTRY_NOTFOUND == GetEntryPos((void*)(ULONG)nCurrent))\n {\n OUString aIdent = pImpl->xInfo->getNumberingIdentifier( nCurrent );\n USHORT nPos = InsertEntry(aIdent);\n SetEntryData(nPos,(void*)(ULONG)nCurrent);\n }\n }\n }\n }\n SelectEntryPos(0);\n }\n}\n\/* -----------------------------01.03.01 14:46--------------------------------\n\n ---------------------------------------------------------------------------*\/\nsal_Int16 SwNumberingTypeListBox::GetSelectedNumberingType()\n{\n sal_Int16 nRet = 0;\n USHORT nSelPos = GetSelectEntryPos();\n if(LISTBOX_ENTRY_NOTFOUND != nSelPos)\n nRet = (sal_Int16)(ULONG)GetEntryData(nSelPos);\n#ifdef DBG_UTIL\n else\n DBG_ERROR(\"SwNumberingTypeListBox not selected\")\n#endif\n return nRet;\n}\n\/* -----------------------------01.03.01 14:46--------------------------------\n\n ---------------------------------------------------------------------------*\/\nsal_Bool SwNumberingTypeListBox::SelectNumberingType(sal_Int16 nType)\n{\n USHORT nPos = GetEntryPos((void*)(ULONG)nType);\n SelectEntryPos( nPos );\n return LISTBOX_ENTRY_NOTFOUND != nPos;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2011 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n\/\/\/ \\file disparitydebug.cc\n\/\/\/\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#ifdef NDEBUG\n#undef NDEBUG\n#endif\n\n#include <stdlib.h>\n\n#include <vw\/FileIO.h>\n#include <vw\/Image.h>\n#include <vw\/Stereo\/DisparityMap.h>\n#include <vw\/tools\/Common.h>\n#include <asp\/Core\/Macros.h>\n#include <asp\/Core\/Common.h>\nusing namespace vw;\nusing namespace vw::stereo;\n\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nstruct Options : asp::BaseOptions {\n \/\/ Input\n std::string input_file_name;\n\n \/\/ Output\n std::string output_prefix, output_file_type;\n};\n\nvoid handle_arguments( int argc, char *argv[], Options& opt ) {\n po::options_description general_options(\"\");\n general_options.add_options()\n (\"output-prefix,o\", po::value(&opt.output_prefix), \"Specify the output prefix\")\n (\"output-filetype,t\", po::value(&opt.output_file_type)->default_value(\"tif\"), \"Specify the output file\");\n general_options.add( asp::BaseOptionsDescription(opt) );\n\n po::options_description positional(\"\");\n positional.add_options()\n (\"input-file\", po::value(&opt.input_file_name), \"Input disparity map\");\n\n po::positional_options_description positional_desc;\n positional_desc.add(\"input-file\", 1);\n\n std::string usage(\"[options] <input disparity map>\");\n po::variables_map vm =\n asp::check_command_line( argc, argv, opt, general_options,\n positional, positional_desc, usage );\n\n if ( opt.input_file_name.empty() )\n vw_throw( ArgumentErr() << \"Missing input file!\\n\"\n << usage << general_options );\n if ( opt.output_prefix.empty() )\n opt.output_prefix = fs::path(opt.input_file_name).stem();\n}\n\ntemplate <class PixelT>\nvoid do_disparity_visualization(Options& opt) {\n DiskImageView<PixelT > disk_disparity_map(opt.input_file_name);\n\n vw_out() << \"\\t--> Computing disparity range \\n\";\n BBox2 disp_range = get_disparity_range(disk_disparity_map);\n vw_out() << \"\\t Horizontal - [\" << disp_range.min().x()\n << \" \" << disp_range.max().x() << \"] Vertical: [\"\n << disp_range.min().y() << \" \" << disp_range.max().y() << \"]\\n\";\n\n typedef typename PixelChannelType<PixelT>::type ChannelT;\n ImageViewRef<ChannelT> horizontal =\n apply_mask(copy_mask(clamp(normalize(select_channel(disk_disparity_map,0),\n disp_range.min().x(), disp_range.max().x(),\n ChannelRange<ChannelT>::min(),ChannelRange<ChannelT>::max())),\n disk_disparity_map));\n ImageViewRef<ChannelT> vertical =\n apply_mask(copy_mask(clamp(normalize(select_channel(disk_disparity_map,1),\n disp_range.min().y(), disp_range.max().y(),\n ChannelRange<ChannelT>::min(),ChannelRange<ChannelT>::max())),\n disk_disparity_map));\n\n vw_out() << \"\\t--> Saving disparity debug images\\n\";\n block_write_gdal_image( opt.output_prefix+\"-H.\"+opt.output_file_type,\n channel_cast_rescale<uint8>(horizontal),\n opt, TerminalProgressCallback(\"asp\",\"\\t Left : \"));\n block_write_gdal_image( opt.output_prefix + \"-V.\" + opt.output_file_type,\n channel_cast_rescale<uint8>(vertical),\n opt, TerminalProgressCallback(\"asp\",\"\\t Right : \"));\n}\n\nint main( int argc, char *argv[] ) {\n\n Options opt;\n try {\n handle_arguments( argc, argv, opt );\n\n vw_out() << \"Opening \" << opt.input_file_name << \"\\n\";\n ImageFormat fmt = tools::taste_image(opt.input_file_name);\n\n switch(fmt.pixel_format) {\n case VW_PIXEL_GENERIC_2_CHANNEL:\n switch (fmt.channel_type) {\n case VW_CHANNEL_INT32:\n do_disparity_visualization<Vector2i>(opt); break;\n default:\n do_disparity_visualization<Vector2f>(opt); break;\n } break;\n case VW_PIXEL_RGB:\n case VW_PIXEL_GENERIC_3_CHANNEL:\n switch (fmt.channel_type) {\n case VW_CHANNEL_INT32:\n do_disparity_visualization<PixelMask<Vector2i> >(opt); break;\n default:\n do_disparity_visualization<PixelMask<Vector2f> >(opt); break;\n } break;\n default:\n vw_throw( ArgumentErr() << \"Unsupported pixel format. Expected GENERIC 2 or 3 CHANNEL image.\" );\n }\n\n } ASP_STANDARD_CATCHES;\n\n return 0;\n}\n<commit_msg>Speed up disparity debug range calculation<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2011 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n\/\/\/ \\file disparitydebug.cc\n\/\/\/\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#ifdef NDEBUG\n#undef NDEBUG\n#endif\n\n#include <stdlib.h>\n\n#include <vw\/FileIO.h>\n#include <vw\/Image.h>\n#include <vw\/Stereo\/DisparityMap.h>\n#include <vw\/tools\/Common.h>\n#include <asp\/Core\/Macros.h>\n#include <asp\/Core\/Common.h>\nusing namespace vw;\nusing namespace vw::stereo;\n\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nstruct Options : asp::BaseOptions {\n \/\/ Input\n std::string input_file_name;\n\n \/\/ Output\n std::string output_prefix, output_file_type;\n};\n\nvoid handle_arguments( int argc, char *argv[], Options& opt ) {\n po::options_description general_options(\"\");\n general_options.add_options()\n (\"output-prefix,o\", po::value(&opt.output_prefix), \"Specify the output prefix\")\n (\"output-filetype,t\", po::value(&opt.output_file_type)->default_value(\"tif\"), \"Specify the output file\");\n general_options.add( asp::BaseOptionsDescription(opt) );\n\n po::options_description positional(\"\");\n positional.add_options()\n (\"input-file\", po::value(&opt.input_file_name), \"Input disparity map\");\n\n po::positional_options_description positional_desc;\n positional_desc.add(\"input-file\", 1);\n\n std::string usage(\"[options] <input disparity map>\");\n po::variables_map vm =\n asp::check_command_line( argc, argv, opt, general_options,\n positional, positional_desc, usage );\n\n if ( opt.input_file_name.empty() )\n vw_throw( ArgumentErr() << \"Missing input file!\\n\"\n << usage << general_options );\n if ( opt.output_prefix.empty() )\n opt.output_prefix = fs::path(opt.input_file_name).stem();\n}\n\ntemplate <class PixelT>\nvoid do_disparity_visualization(Options& opt) {\n DiskImageView<PixelT > disk_disparity_map(opt.input_file_name);\n\n vw_out() << \"\\t--> Computing disparity range \\n\";\n\n \/\/ We don't want to sample every pixel as the image might be very\n \/\/ large. Let's subsample the image so that it is rough 1000x1000\n \/\/ samples.\n float subsample_amt =\n float(disk_disparity_map.cols())*float(disk_disparity_map.rows()) \/ ( 1000.f * 1000.f );\n BBox2 disp_range =\n get_disparity_range(subsample(disk_disparity_map,\n subsample_amt > 1 ? subsample_amt : 1));\n\n vw_out() << \"\\t Horizontal - [\" << disp_range.min().x()\n << \" \" << disp_range.max().x() << \"] Vertical: [\"\n << disp_range.min().y() << \" \" << disp_range.max().y() << \"]\\n\";\n\n typedef typename PixelChannelType<PixelT>::type ChannelT;\n ImageViewRef<ChannelT> horizontal =\n apply_mask(copy_mask(clamp(normalize(select_channel(disk_disparity_map,0),\n disp_range.min().x(), disp_range.max().x(),\n ChannelRange<ChannelT>::min(),ChannelRange<ChannelT>::max())),\n disk_disparity_map));\n ImageViewRef<ChannelT> vertical =\n apply_mask(copy_mask(clamp(normalize(select_channel(disk_disparity_map,1),\n disp_range.min().y(), disp_range.max().y(),\n ChannelRange<ChannelT>::min(),ChannelRange<ChannelT>::max())),\n disk_disparity_map));\n\n vw_out() << \"\\t--> Saving disparity debug images\\n\";\n block_write_gdal_image( opt.output_prefix+\"-H.\"+opt.output_file_type,\n channel_cast_rescale<uint8>(horizontal),\n opt, TerminalProgressCallback(\"asp\",\"\\t Left : \"));\n block_write_gdal_image( opt.output_prefix + \"-V.\" + opt.output_file_type,\n channel_cast_rescale<uint8>(vertical),\n opt, TerminalProgressCallback(\"asp\",\"\\t Right : \"));\n}\n\nint main( int argc, char *argv[] ) {\n\n Options opt;\n try {\n handle_arguments( argc, argv, opt );\n\n vw_out() << \"Opening \" << opt.input_file_name << \"\\n\";\n ImageFormat fmt = tools::taste_image(opt.input_file_name);\n\n switch(fmt.pixel_format) {\n case VW_PIXEL_GENERIC_2_CHANNEL:\n switch (fmt.channel_type) {\n case VW_CHANNEL_INT32:\n do_disparity_visualization<Vector2i>(opt); break;\n default:\n do_disparity_visualization<Vector2f>(opt); break;\n } break;\n case VW_PIXEL_RGB:\n case VW_PIXEL_GENERIC_3_CHANNEL:\n switch (fmt.channel_type) {\n case VW_CHANNEL_INT32:\n do_disparity_visualization<PixelMask<Vector2i> >(opt); break;\n default:\n do_disparity_visualization<PixelMask<Vector2f> >(opt); break;\n } break;\n default:\n vw_throw( ArgumentErr() << \"Unsupported pixel format. Expected GENERIC 2 or 3 CHANNEL image.\" );\n }\n\n } ASP_STANDARD_CATCHES;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- COFFAsmParser.cpp - COFF Assembly Parser ---------------------------===\/\/\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#include \"llvm\/MC\/MCParser\/MCAsmParserExtension.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCParser\/MCAsmLexer.h\"\n#include \"llvm\/MC\/MCSectionCOFF.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/Support\/COFF.h\"\nusing namespace llvm;\n\nnamespace {\n\nclass COFFAsmParser : public MCAsmParserExtension {\n template<bool (COFFAsmParser::*Handler)(StringRef, SMLoc)>\n void AddDirectiveHandler(StringRef Directive) {\n getParser().AddDirectiveHandler(this, Directive,\n HandleDirective<COFFAsmParser, Handler>);\n }\n\n bool ParseSectionSwitch(StringRef Section,\n unsigned Characteristics,\n SectionKind Kind);\n\n virtual void Initialize(MCAsmParser &Parser) {\n \/\/ Call the base implementation.\n MCAsmParserExtension::Initialize(Parser);\n\n AddDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveText>(\".text\");\n AddDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveData>(\".data\");\n AddDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveBSS>(\".bss\");\n AddDirectiveHandler<&COFFAsmParser::ParseDirectiveDef>(\".def\");\n AddDirectiveHandler<&COFFAsmParser::ParseDirectiveScl>(\".scl\");\n AddDirectiveHandler<&COFFAsmParser::ParseDirectiveType>(\".type\");\n AddDirectiveHandler<&COFFAsmParser::ParseDirectiveEndef>(\".endef\");\n\n \/\/ Win64 EH directives.\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartProc>(\n \".seh_proc\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProc>(\n \".seh_endproc\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartChained>(\n \".seh_startchained\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndChained>(\n \".seh_endchained\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandler>(\n \".seh_handler\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandlerData>(\n \".seh_handlerdata\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushReg>(\n \".seh_pushreg\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSetFrame>(\n \".seh_setframe\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveAllocStack>(\n \".seh_stackalloc\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveReg>(\n \".seh_savereg\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveXMM>(\n \".seh_savexmm\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushFrame>(\n \".seh_pushframe\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProlog>(\n \".seh_endprologue\");\n }\n\n bool ParseSectionDirectiveText(StringRef, SMLoc) {\n return ParseSectionSwitch(\".text\",\n COFF::IMAGE_SCN_CNT_CODE\n | COFF::IMAGE_SCN_MEM_EXECUTE\n | COFF::IMAGE_SCN_MEM_READ,\n SectionKind::getText());\n }\n bool ParseSectionDirectiveData(StringRef, SMLoc) {\n return ParseSectionSwitch(\".data\",\n COFF::IMAGE_SCN_CNT_INITIALIZED_DATA\n | COFF::IMAGE_SCN_MEM_READ\n | COFF::IMAGE_SCN_MEM_WRITE,\n SectionKind::getDataRel());\n }\n bool ParseSectionDirectiveBSS(StringRef, SMLoc) {\n return ParseSectionSwitch(\".bss\",\n COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA\n | COFF::IMAGE_SCN_MEM_READ\n | COFF::IMAGE_SCN_MEM_WRITE,\n SectionKind::getBSS());\n }\n\n bool ParseDirectiveDef(StringRef, SMLoc);\n bool ParseDirectiveScl(StringRef, SMLoc);\n bool ParseDirectiveType(StringRef, SMLoc);\n bool ParseDirectiveEndef(StringRef, SMLoc);\n\n \/\/ Win64 EH directives.\n bool ParseSEHDirectiveStartProc(StringRef, SMLoc);\n bool ParseSEHDirectiveEndProc(StringRef, SMLoc);\n bool ParseSEHDirectiveStartChained(StringRef, SMLoc);\n bool ParseSEHDirectiveEndChained(StringRef, SMLoc);\n bool ParseSEHDirectiveHandler(StringRef, SMLoc);\n bool ParseSEHDirectiveHandlerData(StringRef, SMLoc);\n bool ParseSEHDirectivePushReg(StringRef, SMLoc L);\n bool ParseSEHDirectiveSetFrame(StringRef, SMLoc L);\n bool ParseSEHDirectiveAllocStack(StringRef, SMLoc L);\n bool ParseSEHDirectiveSaveReg(StringRef, SMLoc L);\n bool ParseSEHDirectiveSaveXMM(StringRef, SMLoc L);\n bool ParseSEHDirectivePushFrame(StringRef, SMLoc L);\n bool ParseSEHDirectiveEndProlog(StringRef, SMLoc);\n\n bool ParseAtUnwindOrAtExcept(bool &unwind, bool &except);\npublic:\n COFFAsmParser() {}\n};\n\n} \/\/ end annonomous namespace.\n\nbool COFFAsmParser::ParseSectionSwitch(StringRef Section,\n unsigned Characteristics,\n SectionKind Kind) {\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in section switching directive\");\n Lex();\n\n getStreamer().SwitchSection(getContext().getCOFFSection(\n Section, Characteristics, Kind));\n\n return false;\n}\n\nbool COFFAsmParser::ParseDirectiveDef(StringRef, SMLoc) {\n StringRef SymbolName;\n\n if (getParser().ParseIdentifier(SymbolName))\n return TokError(\"expected identifier in directive\");\n\n MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);\n\n getStreamer().BeginCOFFSymbolDef(Sym);\n\n Lex();\n return false;\n}\n\nbool COFFAsmParser::ParseDirectiveScl(StringRef, SMLoc) {\n int64_t SymbolStorageClass;\n if (getParser().ParseAbsoluteExpression(SymbolStorageClass))\n return true;\n\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitCOFFSymbolStorageClass(SymbolStorageClass);\n return false;\n}\n\nbool COFFAsmParser::ParseDirectiveType(StringRef, SMLoc) {\n int64_t Type;\n if (getParser().ParseAbsoluteExpression(Type))\n return true;\n\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitCOFFSymbolType(Type);\n return false;\n}\n\nbool COFFAsmParser::ParseDirectiveEndef(StringRef, SMLoc) {\n Lex();\n getStreamer().EndCOFFSymbolDef();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveStartProc(StringRef, SMLoc) {\n const MCExpr *e;\n const MCSymbolRefExpr *funcExpr;\n SMLoc startLoc = getLexer().getLoc();\n if (getParser().ParseExpression(e))\n return true;\n\n if (!(funcExpr = dyn_cast<MCSymbolRefExpr>(e)))\n return Error(startLoc, \"expected symbol\");\n\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitWin64EHStartProc(&funcExpr->getSymbol());\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveEndProc(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHEndProc();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveStartChained(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHStartChained();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveEndChained(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHEndChained();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveHandler(StringRef, SMLoc) {\n const MCExpr *e;\n const MCSymbolRefExpr *funcExpr;\n SMLoc startLoc = getLexer().getLoc();\n if (getParser().ParseExpression(e))\n return true;\n\n if (!(funcExpr = dyn_cast<MCSymbolRefExpr>(e)))\n return Error(startLoc, \"expected symbol\");\n\n bool unwind = false, except = false;\n if (!ParseAtUnwindOrAtExcept(unwind, except))\n return true;\n if (getLexer().is(AsmToken::Comma)) {\n Lex();\n if (!ParseAtUnwindOrAtExcept(unwind, except))\n return true;\n }\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitWin64EHHandler(&funcExpr->getSymbol(), unwind, except);\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveHandlerData(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHHandlerData();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectivePushReg(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectiveSetFrame(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectiveAllocStack(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectiveSaveReg(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectiveSaveXMM(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectivePushFrame(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectiveEndProlog(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHEndProlog();\n return false;\n}\n\nbool COFFAsmParser::ParseAtUnwindOrAtExcept(bool &unwind, bool &except) {\n StringRef identifier;\n SMLoc startLoc = getLexer().getLoc();\n if (!getParser().ParseIdentifier(identifier))\n return Error(startLoc, \"expected @unwind or @except\");\n if (identifier == \"@unwind\")\n unwind = true;\n else if (identifier == \"@except\")\n except = true;\n else\n return Error(startLoc, \"expected @unwind or @except\");\n return false;\n}\n\nnamespace llvm {\n\nMCAsmParserExtension *createCOFFAsmParser() {\n return new COFFAsmParser;\n}\n\n}\n<commit_msg>Implement .seh_stackalloc and .seh_pushframe parsing.<commit_after>\/\/===- COFFAsmParser.cpp - COFF Assembly Parser ---------------------------===\/\/\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#include \"llvm\/MC\/MCParser\/MCAsmParserExtension.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCParser\/MCAsmLexer.h\"\n#include \"llvm\/MC\/MCSectionCOFF.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/Support\/COFF.h\"\nusing namespace llvm;\n\nnamespace {\n\nclass COFFAsmParser : public MCAsmParserExtension {\n template<bool (COFFAsmParser::*Handler)(StringRef, SMLoc)>\n void AddDirectiveHandler(StringRef Directive) {\n getParser().AddDirectiveHandler(this, Directive,\n HandleDirective<COFFAsmParser, Handler>);\n }\n\n bool ParseSectionSwitch(StringRef Section,\n unsigned Characteristics,\n SectionKind Kind);\n\n virtual void Initialize(MCAsmParser &Parser) {\n \/\/ Call the base implementation.\n MCAsmParserExtension::Initialize(Parser);\n\n AddDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveText>(\".text\");\n AddDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveData>(\".data\");\n AddDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveBSS>(\".bss\");\n AddDirectiveHandler<&COFFAsmParser::ParseDirectiveDef>(\".def\");\n AddDirectiveHandler<&COFFAsmParser::ParseDirectiveScl>(\".scl\");\n AddDirectiveHandler<&COFFAsmParser::ParseDirectiveType>(\".type\");\n AddDirectiveHandler<&COFFAsmParser::ParseDirectiveEndef>(\".endef\");\n\n \/\/ Win64 EH directives.\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartProc>(\n \".seh_proc\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProc>(\n \".seh_endproc\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartChained>(\n \".seh_startchained\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndChained>(\n \".seh_endchained\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandler>(\n \".seh_handler\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandlerData>(\n \".seh_handlerdata\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushReg>(\n \".seh_pushreg\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSetFrame>(\n \".seh_setframe\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveAllocStack>(\n \".seh_stackalloc\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveReg>(\n \".seh_savereg\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveXMM>(\n \".seh_savexmm\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushFrame>(\n \".seh_pushframe\");\n AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProlog>(\n \".seh_endprologue\");\n }\n\n bool ParseSectionDirectiveText(StringRef, SMLoc) {\n return ParseSectionSwitch(\".text\",\n COFF::IMAGE_SCN_CNT_CODE\n | COFF::IMAGE_SCN_MEM_EXECUTE\n | COFF::IMAGE_SCN_MEM_READ,\n SectionKind::getText());\n }\n bool ParseSectionDirectiveData(StringRef, SMLoc) {\n return ParseSectionSwitch(\".data\",\n COFF::IMAGE_SCN_CNT_INITIALIZED_DATA\n | COFF::IMAGE_SCN_MEM_READ\n | COFF::IMAGE_SCN_MEM_WRITE,\n SectionKind::getDataRel());\n }\n bool ParseSectionDirectiveBSS(StringRef, SMLoc) {\n return ParseSectionSwitch(\".bss\",\n COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA\n | COFF::IMAGE_SCN_MEM_READ\n | COFF::IMAGE_SCN_MEM_WRITE,\n SectionKind::getBSS());\n }\n\n bool ParseDirectiveDef(StringRef, SMLoc);\n bool ParseDirectiveScl(StringRef, SMLoc);\n bool ParseDirectiveType(StringRef, SMLoc);\n bool ParseDirectiveEndef(StringRef, SMLoc);\n\n \/\/ Win64 EH directives.\n bool ParseSEHDirectiveStartProc(StringRef, SMLoc);\n bool ParseSEHDirectiveEndProc(StringRef, SMLoc);\n bool ParseSEHDirectiveStartChained(StringRef, SMLoc);\n bool ParseSEHDirectiveEndChained(StringRef, SMLoc);\n bool ParseSEHDirectiveHandler(StringRef, SMLoc);\n bool ParseSEHDirectiveHandlerData(StringRef, SMLoc);\n bool ParseSEHDirectivePushReg(StringRef, SMLoc L);\n bool ParseSEHDirectiveSetFrame(StringRef, SMLoc L);\n bool ParseSEHDirectiveAllocStack(StringRef, SMLoc L);\n bool ParseSEHDirectiveSaveReg(StringRef, SMLoc L);\n bool ParseSEHDirectiveSaveXMM(StringRef, SMLoc L);\n bool ParseSEHDirectivePushFrame(StringRef, SMLoc L);\n bool ParseSEHDirectiveEndProlog(StringRef, SMLoc);\n\n bool ParseAtUnwindOrAtExcept(bool &unwind, bool &except);\npublic:\n COFFAsmParser() {}\n};\n\n} \/\/ end annonomous namespace.\n\nbool COFFAsmParser::ParseSectionSwitch(StringRef Section,\n unsigned Characteristics,\n SectionKind Kind) {\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in section switching directive\");\n Lex();\n\n getStreamer().SwitchSection(getContext().getCOFFSection(\n Section, Characteristics, Kind));\n\n return false;\n}\n\nbool COFFAsmParser::ParseDirectiveDef(StringRef, SMLoc) {\n StringRef SymbolName;\n\n if (getParser().ParseIdentifier(SymbolName))\n return TokError(\"expected identifier in directive\");\n\n MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);\n\n getStreamer().BeginCOFFSymbolDef(Sym);\n\n Lex();\n return false;\n}\n\nbool COFFAsmParser::ParseDirectiveScl(StringRef, SMLoc) {\n int64_t SymbolStorageClass;\n if (getParser().ParseAbsoluteExpression(SymbolStorageClass))\n return true;\n\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitCOFFSymbolStorageClass(SymbolStorageClass);\n return false;\n}\n\nbool COFFAsmParser::ParseDirectiveType(StringRef, SMLoc) {\n int64_t Type;\n if (getParser().ParseAbsoluteExpression(Type))\n return true;\n\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitCOFFSymbolType(Type);\n return false;\n}\n\nbool COFFAsmParser::ParseDirectiveEndef(StringRef, SMLoc) {\n Lex();\n getStreamer().EndCOFFSymbolDef();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveStartProc(StringRef, SMLoc) {\n const MCExpr *e;\n const MCSymbolRefExpr *funcExpr;\n SMLoc startLoc = getLexer().getLoc();\n if (getParser().ParseExpression(e))\n return true;\n\n if (!(funcExpr = dyn_cast<MCSymbolRefExpr>(e)))\n return Error(startLoc, \"expected symbol\");\n\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitWin64EHStartProc(&funcExpr->getSymbol());\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveEndProc(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHEndProc();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveStartChained(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHStartChained();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveEndChained(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHEndChained();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveHandler(StringRef, SMLoc) {\n const MCExpr *e;\n const MCSymbolRefExpr *funcExpr;\n SMLoc startLoc = getLexer().getLoc();\n if (getParser().ParseExpression(e))\n return true;\n\n if (!(funcExpr = dyn_cast<MCSymbolRefExpr>(e)))\n return Error(startLoc, \"expected symbol\");\n\n bool unwind = false, except = false;\n if (!ParseAtUnwindOrAtExcept(unwind, except))\n return true;\n if (getLexer().is(AsmToken::Comma)) {\n Lex();\n if (!ParseAtUnwindOrAtExcept(unwind, except))\n return true;\n }\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitWin64EHHandler(&funcExpr->getSymbol(), unwind, except);\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveHandlerData(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHHandlerData();\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectivePushReg(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectiveSetFrame(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectiveAllocStack(StringRef, SMLoc) {\n int64_t Size;\n if (getParser().ParseAbsoluteExpression(Size))\n return true;\n\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitWin64EHAllocStack(Size);\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveSaveReg(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectiveSaveXMM(StringRef, SMLoc L) {\n return Error(L, \"not implemented yet\");\n}\n\nbool COFFAsmParser::ParseSEHDirectivePushFrame(StringRef, SMLoc) {\n bool Code;\n StringRef CodeID;\n SMLoc startLoc = getLexer().getLoc();\n if (!getParser().ParseIdentifier(CodeID)) {\n if (CodeID != \"@code\")\n return Error(startLoc, \"expected @code\");\n Code = true;\n }\n\n if (getLexer().isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in directive\");\n\n Lex();\n getStreamer().EmitWin64EHPushFrame(Code);\n return false;\n}\n\nbool COFFAsmParser::ParseSEHDirectiveEndProlog(StringRef, SMLoc) {\n Lex();\n getStreamer().EmitWin64EHEndProlog();\n return false;\n}\n\nbool COFFAsmParser::ParseAtUnwindOrAtExcept(bool &unwind, bool &except) {\n StringRef identifier;\n SMLoc startLoc = getLexer().getLoc();\n if (!getParser().ParseIdentifier(identifier))\n return Error(startLoc, \"expected @unwind or @except\");\n if (identifier == \"@unwind\")\n unwind = true;\n else if (identifier == \"@except\")\n except = true;\n else\n return Error(startLoc, \"expected @unwind or @except\");\n return false;\n}\n\nnamespace llvm {\n\nMCAsmParserExtension *createCOFFAsmParser() {\n return new COFFAsmParser;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- MipsInstrInfo.cpp - Mips Instruction Information ------------------===\/\/\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\/\/ This file contains the Mips implementation of the TargetInstrInfo class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"MipsInstrInfo.h\"\n#include \"InstPrinter\/MipsInstPrinter.h\"\n#include \"MipsAnalyzeImmediate.h\"\n#include \"MipsMachineFunction.h\"\n#include \"MipsTargetMachine.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n\n#define GET_INSTRINFO_CTOR\n#include \"MipsGenInstrInfo.inc\"\n\nusing namespace llvm;\n\nMipsInstrInfo::MipsInstrInfo(MipsTargetMachine &tm, unsigned UncondBr)\n : MipsGenInstrInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),\n TM(tm), UncondBrOpc(UncondBr) {}\n\nconst MipsInstrInfo *MipsInstrInfo::create(MipsTargetMachine &TM) {\n if (TM.getSubtargetImpl()->inMips16Mode())\n return llvm::createMips16InstrInfo(TM);\n\n return llvm::createMipsSEInstrInfo(TM);\n}\n\nbool MipsInstrInfo::isZeroImm(const MachineOperand &op) const {\n return op.isImm() && op.getImm() == 0;\n}\n\n\/\/\/ insertNoop - If data hazard condition is found insert the target nop\n\/\/\/ instruction.\nvoid MipsInstrInfo::\ninsertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const\n{\n DebugLoc DL;\n BuildMI(MBB, MI, DL, get(Mips::NOP));\n}\n\nMachineMemOperand *MipsInstrInfo::GetMemOperand(MachineBasicBlock &MBB, int FI,\n unsigned Flag) const {\n MachineFunction &MF = *MBB.getParent();\n MachineFrameInfo &MFI = *MF.getFrameInfo();\n unsigned Align = MFI.getObjectAlignment(FI);\n\n return MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), Flag,\n MFI.getObjectSize(FI), Align);\n}\n\nMachineInstr*\nMipsInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF, int FrameIx,\n uint64_t Offset, const MDNode *MDPtr,\n DebugLoc DL) const {\n MachineInstrBuilder MIB = BuildMI(MF, DL, get(Mips::DBG_VALUE))\n .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);\n return &*MIB;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Branch Analysis\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid MipsInstrInfo::AnalyzeCondBr(const MachineInstr *Inst, unsigned Opc,\n MachineBasicBlock *&BB,\n SmallVectorImpl<MachineOperand> &Cond) const {\n assert(GetAnalyzableBrOpc(Opc) && \"Not an analyzable branch\");\n int NumOp = Inst->getNumExplicitOperands();\n\n \/\/ for both int and fp branches, the last explicit operand is the\n \/\/ MBB.\n BB = Inst->getOperand(NumOp-1).getMBB();\n Cond.push_back(MachineOperand::CreateImm(Opc));\n\n for (int i=0; i<NumOp-1; i++)\n Cond.push_back(Inst->getOperand(i));\n}\n\nbool MipsInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,\n MachineBasicBlock *&TBB,\n MachineBasicBlock *&FBB,\n SmallVectorImpl<MachineOperand> &Cond,\n bool AllowModify) const {\n SmallVector<MachineInstr*, 2> BranchInstrs;\n BranchType BT = AnalyzeBranch(MBB, TBB, FBB, Cond, AllowModify, BranchInstrs);\n\n return (BT == BT_None) || (BT == BT_Indirect);\n}\n\nvoid MipsInstrInfo::BuildCondBr(MachineBasicBlock &MBB,\n MachineBasicBlock *TBB, DebugLoc DL,\n const SmallVectorImpl<MachineOperand>& Cond)\n const {\n unsigned Opc = Cond[0].getImm();\n const MCInstrDesc &MCID = get(Opc);\n MachineInstrBuilder MIB = BuildMI(&MBB, DL, MCID);\n\n for (unsigned i = 1; i < Cond.size(); ++i) {\n if (Cond[i].isReg())\n MIB.addReg(Cond[i].getReg());\n else if (Cond[i].isImm())\n MIB.addImm(Cond[i].getImm());\n else\n assert(true && \"Cannot copy operand\");\n }\n MIB.addMBB(TBB);\n}\n\nunsigned MipsInstrInfo::\nInsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,\n MachineBasicBlock *FBB,\n const SmallVectorImpl<MachineOperand> &Cond,\n DebugLoc DL) const {\n \/\/ Shouldn't be a fall through.\n assert(TBB && \"InsertBranch must not be told to insert a fallthrough\");\n\n \/\/ # of condition operands:\n \/\/ Unconditional branches: 0\n \/\/ Floating point branches: 1 (opc)\n \/\/ Int BranchZero: 2 (opc, reg)\n \/\/ Int Branch: 3 (opc, reg0, reg1)\n assert((Cond.size() <= 3) &&\n \"# of Mips branch conditions must be <= 3!\");\n\n \/\/ Two-way Conditional branch.\n if (FBB) {\n BuildCondBr(MBB, TBB, DL, Cond);\n BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(FBB);\n return 2;\n }\n\n \/\/ One way branch.\n \/\/ Unconditional branch.\n if (Cond.empty())\n BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(TBB);\n else \/\/ Conditional branch.\n BuildCondBr(MBB, TBB, DL, Cond);\n return 1;\n}\n\nunsigned MipsInstrInfo::\nRemoveBranch(MachineBasicBlock &MBB) const\n{\n MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();\n MachineBasicBlock::reverse_iterator FirstBr;\n unsigned removed;\n\n \/\/ Skip all the debug instructions.\n while (I != REnd && I->isDebugValue())\n ++I;\n\n FirstBr = I;\n\n \/\/ Up to 2 branches are removed.\n \/\/ Note that indirect branches are not removed.\n for(removed = 0; I != REnd && removed < 2; ++I, ++removed)\n if (!GetAnalyzableBrOpc(I->getOpcode()))\n break;\n\n MBB.erase(I.base(), FirstBr.base());\n\n return removed;\n}\n\n\/\/\/ ReverseBranchCondition - Return the inverse opcode of the\n\/\/\/ specified Branch instruction.\nbool MipsInstrInfo::\nReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const\n{\n assert( (Cond.size() && Cond.size() <= 3) &&\n \"Invalid Mips branch condition!\");\n Cond[0].setImm(GetOppositeBranchOpc(Cond[0].getImm()));\n return false;\n}\n\nMipsInstrInfo::BranchType MipsInstrInfo::\nAnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,\n MachineBasicBlock *&FBB, SmallVectorImpl<MachineOperand> &Cond,\n bool AllowModify,\n SmallVectorImpl<MachineInstr*> &BranchInstrs) const {\n\n MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();\n\n \/\/ Skip all the debug instructions.\n while (I != REnd && I->isDebugValue())\n ++I;\n\n if (I == REnd || !isUnpredicatedTerminator(&*I)) {\n \/\/ This block ends with no branches (it just falls through to its succ).\n \/\/ Leave TBB\/FBB null.\n TBB = FBB = NULL;\n return BT_NoBranch;\n }\n\n MachineInstr *LastInst = &*I;\n unsigned LastOpc = LastInst->getOpcode();\n BranchInstrs.push_back(LastInst);\n\n \/\/ Not an analyzable branch (e.g., indirect jump).\n if (!GetAnalyzableBrOpc(LastOpc))\n return LastInst->isIndirectBranch() ? BT_Indirect : BT_None;\n\n \/\/ Get the second to last instruction in the block.\n unsigned SecondLastOpc = 0;\n MachineInstr *SecondLastInst = NULL;\n\n if (++I != REnd) {\n SecondLastInst = &*I;\n SecondLastOpc = GetAnalyzableBrOpc(SecondLastInst->getOpcode());\n\n \/\/ Not an analyzable branch (must be an indirect jump).\n if (isUnpredicatedTerminator(SecondLastInst) && !SecondLastOpc)\n return BT_None;\n }\n\n BranchInstrs.insert(BranchInstrs.begin(), SecondLastInst);\n\n \/\/ If there is only one terminator instruction, process it.\n if (!SecondLastOpc) {\n \/\/ Unconditional branch\n if (LastOpc == UncondBrOpc) {\n TBB = LastInst->getOperand(0).getMBB();\n return BT_Uncond;\n }\n\n \/\/ Conditional branch\n AnalyzeCondBr(LastInst, LastOpc, TBB, Cond);\n return BT_Cond;\n }\n\n \/\/ If we reached here, there are two branches.\n \/\/ If there are three terminators, we don't know what sort of block this is.\n if (++I != REnd && isUnpredicatedTerminator(&*I))\n return BT_None;\n\n \/\/ If second to last instruction is an unconditional branch,\n \/\/ analyze it and remove the last instruction.\n if (SecondLastOpc == UncondBrOpc) {\n \/\/ Return if the last instruction cannot be removed.\n if (!AllowModify)\n return BT_None;\n\n TBB = SecondLastInst->getOperand(0).getMBB();\n LastInst->eraseFromParent();\n BranchInstrs.pop_back();\n return BT_Uncond;\n }\n\n \/\/ Conditional branch followed by an unconditional branch.\n \/\/ The last one must be unconditional.\n if (LastOpc != UncondBrOpc)\n return BT_None;\n\n AnalyzeCondBr(SecondLastInst, SecondLastOpc, TBB, Cond);\n FBB = LastInst->getOperand(0).getMBB();\n\n return BT_CondUncond;\n}\n\n\/\/\/ Return the number of bytes of code the specified instruction may be.\nunsigned MipsInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {\n switch (MI->getOpcode()) {\n default:\n return MI->getDesc().getSize();\n case TargetOpcode::INLINEASM: { \/\/ Inline Asm: Variable size.\n const MachineFunction *MF = MI->getParent()->getParent();\n const char *AsmStr = MI->getOperand(0).getSymbolName();\n return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());\n }\n }\n}\n<commit_msg>[mips] Do not add SecondLastInst to list BranchInstrs if there is only one terminator.<commit_after>\/\/===-- MipsInstrInfo.cpp - Mips Instruction Information ------------------===\/\/\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\/\/ This file contains the Mips implementation of the TargetInstrInfo class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"MipsInstrInfo.h\"\n#include \"InstPrinter\/MipsInstPrinter.h\"\n#include \"MipsAnalyzeImmediate.h\"\n#include \"MipsMachineFunction.h\"\n#include \"MipsTargetMachine.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n\n#define GET_INSTRINFO_CTOR\n#include \"MipsGenInstrInfo.inc\"\n\nusing namespace llvm;\n\nMipsInstrInfo::MipsInstrInfo(MipsTargetMachine &tm, unsigned UncondBr)\n : MipsGenInstrInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),\n TM(tm), UncondBrOpc(UncondBr) {}\n\nconst MipsInstrInfo *MipsInstrInfo::create(MipsTargetMachine &TM) {\n if (TM.getSubtargetImpl()->inMips16Mode())\n return llvm::createMips16InstrInfo(TM);\n\n return llvm::createMipsSEInstrInfo(TM);\n}\n\nbool MipsInstrInfo::isZeroImm(const MachineOperand &op) const {\n return op.isImm() && op.getImm() == 0;\n}\n\n\/\/\/ insertNoop - If data hazard condition is found insert the target nop\n\/\/\/ instruction.\nvoid MipsInstrInfo::\ninsertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const\n{\n DebugLoc DL;\n BuildMI(MBB, MI, DL, get(Mips::NOP));\n}\n\nMachineMemOperand *MipsInstrInfo::GetMemOperand(MachineBasicBlock &MBB, int FI,\n unsigned Flag) const {\n MachineFunction &MF = *MBB.getParent();\n MachineFrameInfo &MFI = *MF.getFrameInfo();\n unsigned Align = MFI.getObjectAlignment(FI);\n\n return MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), Flag,\n MFI.getObjectSize(FI), Align);\n}\n\nMachineInstr*\nMipsInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF, int FrameIx,\n uint64_t Offset, const MDNode *MDPtr,\n DebugLoc DL) const {\n MachineInstrBuilder MIB = BuildMI(MF, DL, get(Mips::DBG_VALUE))\n .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);\n return &*MIB;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Branch Analysis\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid MipsInstrInfo::AnalyzeCondBr(const MachineInstr *Inst, unsigned Opc,\n MachineBasicBlock *&BB,\n SmallVectorImpl<MachineOperand> &Cond) const {\n assert(GetAnalyzableBrOpc(Opc) && \"Not an analyzable branch\");\n int NumOp = Inst->getNumExplicitOperands();\n\n \/\/ for both int and fp branches, the last explicit operand is the\n \/\/ MBB.\n BB = Inst->getOperand(NumOp-1).getMBB();\n Cond.push_back(MachineOperand::CreateImm(Opc));\n\n for (int i=0; i<NumOp-1; i++)\n Cond.push_back(Inst->getOperand(i));\n}\n\nbool MipsInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,\n MachineBasicBlock *&TBB,\n MachineBasicBlock *&FBB,\n SmallVectorImpl<MachineOperand> &Cond,\n bool AllowModify) const {\n SmallVector<MachineInstr*, 2> BranchInstrs;\n BranchType BT = AnalyzeBranch(MBB, TBB, FBB, Cond, AllowModify, BranchInstrs);\n\n return (BT == BT_None) || (BT == BT_Indirect);\n}\n\nvoid MipsInstrInfo::BuildCondBr(MachineBasicBlock &MBB,\n MachineBasicBlock *TBB, DebugLoc DL,\n const SmallVectorImpl<MachineOperand>& Cond)\n const {\n unsigned Opc = Cond[0].getImm();\n const MCInstrDesc &MCID = get(Opc);\n MachineInstrBuilder MIB = BuildMI(&MBB, DL, MCID);\n\n for (unsigned i = 1; i < Cond.size(); ++i) {\n if (Cond[i].isReg())\n MIB.addReg(Cond[i].getReg());\n else if (Cond[i].isImm())\n MIB.addImm(Cond[i].getImm());\n else\n assert(true && \"Cannot copy operand\");\n }\n MIB.addMBB(TBB);\n}\n\nunsigned MipsInstrInfo::\nInsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,\n MachineBasicBlock *FBB,\n const SmallVectorImpl<MachineOperand> &Cond,\n DebugLoc DL) const {\n \/\/ Shouldn't be a fall through.\n assert(TBB && \"InsertBranch must not be told to insert a fallthrough\");\n\n \/\/ # of condition operands:\n \/\/ Unconditional branches: 0\n \/\/ Floating point branches: 1 (opc)\n \/\/ Int BranchZero: 2 (opc, reg)\n \/\/ Int Branch: 3 (opc, reg0, reg1)\n assert((Cond.size() <= 3) &&\n \"# of Mips branch conditions must be <= 3!\");\n\n \/\/ Two-way Conditional branch.\n if (FBB) {\n BuildCondBr(MBB, TBB, DL, Cond);\n BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(FBB);\n return 2;\n }\n\n \/\/ One way branch.\n \/\/ Unconditional branch.\n if (Cond.empty())\n BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(TBB);\n else \/\/ Conditional branch.\n BuildCondBr(MBB, TBB, DL, Cond);\n return 1;\n}\n\nunsigned MipsInstrInfo::\nRemoveBranch(MachineBasicBlock &MBB) const\n{\n MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();\n MachineBasicBlock::reverse_iterator FirstBr;\n unsigned removed;\n\n \/\/ Skip all the debug instructions.\n while (I != REnd && I->isDebugValue())\n ++I;\n\n FirstBr = I;\n\n \/\/ Up to 2 branches are removed.\n \/\/ Note that indirect branches are not removed.\n for(removed = 0; I != REnd && removed < 2; ++I, ++removed)\n if (!GetAnalyzableBrOpc(I->getOpcode()))\n break;\n\n MBB.erase(I.base(), FirstBr.base());\n\n return removed;\n}\n\n\/\/\/ ReverseBranchCondition - Return the inverse opcode of the\n\/\/\/ specified Branch instruction.\nbool MipsInstrInfo::\nReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const\n{\n assert( (Cond.size() && Cond.size() <= 3) &&\n \"Invalid Mips branch condition!\");\n Cond[0].setImm(GetOppositeBranchOpc(Cond[0].getImm()));\n return false;\n}\n\nMipsInstrInfo::BranchType MipsInstrInfo::\nAnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,\n MachineBasicBlock *&FBB, SmallVectorImpl<MachineOperand> &Cond,\n bool AllowModify,\n SmallVectorImpl<MachineInstr*> &BranchInstrs) const {\n\n MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();\n\n \/\/ Skip all the debug instructions.\n while (I != REnd && I->isDebugValue())\n ++I;\n\n if (I == REnd || !isUnpredicatedTerminator(&*I)) {\n \/\/ This block ends with no branches (it just falls through to its succ).\n \/\/ Leave TBB\/FBB null.\n TBB = FBB = NULL;\n return BT_NoBranch;\n }\n\n MachineInstr *LastInst = &*I;\n unsigned LastOpc = LastInst->getOpcode();\n BranchInstrs.push_back(LastInst);\n\n \/\/ Not an analyzable branch (e.g., indirect jump).\n if (!GetAnalyzableBrOpc(LastOpc))\n return LastInst->isIndirectBranch() ? BT_Indirect : BT_None;\n\n \/\/ Get the second to last instruction in the block.\n unsigned SecondLastOpc = 0;\n MachineInstr *SecondLastInst = NULL;\n\n if (++I != REnd) {\n SecondLastInst = &*I;\n SecondLastOpc = GetAnalyzableBrOpc(SecondLastInst->getOpcode());\n\n \/\/ Not an analyzable branch (must be an indirect jump).\n if (isUnpredicatedTerminator(SecondLastInst) && !SecondLastOpc)\n return BT_None;\n }\n\n \/\/ If there is only one terminator instruction, process it.\n if (!SecondLastOpc) {\n \/\/ Unconditional branch\n if (LastOpc == UncondBrOpc) {\n TBB = LastInst->getOperand(0).getMBB();\n return BT_Uncond;\n }\n\n \/\/ Conditional branch\n AnalyzeCondBr(LastInst, LastOpc, TBB, Cond);\n return BT_Cond;\n }\n\n \/\/ If we reached here, there are two branches.\n \/\/ If there are three terminators, we don't know what sort of block this is.\n if (++I != REnd && isUnpredicatedTerminator(&*I))\n return BT_None;\n\n BranchInstrs.insert(BranchInstrs.begin(), SecondLastInst);\n\n \/\/ If second to last instruction is an unconditional branch,\n \/\/ analyze it and remove the last instruction.\n if (SecondLastOpc == UncondBrOpc) {\n \/\/ Return if the last instruction cannot be removed.\n if (!AllowModify)\n return BT_None;\n\n TBB = SecondLastInst->getOperand(0).getMBB();\n LastInst->eraseFromParent();\n BranchInstrs.pop_back();\n return BT_Uncond;\n }\n\n \/\/ Conditional branch followed by an unconditional branch.\n \/\/ The last one must be unconditional.\n if (LastOpc != UncondBrOpc)\n return BT_None;\n\n AnalyzeCondBr(SecondLastInst, SecondLastOpc, TBB, Cond);\n FBB = LastInst->getOperand(0).getMBB();\n\n return BT_CondUncond;\n}\n\n\/\/\/ Return the number of bytes of code the specified instruction may be.\nunsigned MipsInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {\n switch (MI->getOpcode()) {\n default:\n return MI->getDesc().getSize();\n case TargetOpcode::INLINEASM: { \/\/ Inline Asm: Variable size.\n const MachineFunction *MF = MI->getParent()->getParent();\n const char *AsmStr = MI->getOperand(0).getSymbolName();\n return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- X86ISelPattern.cpp - A pattern matching inst selector for X86 -----===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines a pattern matching instruction selector for X86.\n\/\/\n\/\/ FIXME: we could allocate one big array of unsigneds to use as the backing\n\/\/ store for all of the nodes costs arrays.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ NOTE: This whole selector is completely disabled. This is only retained\n\/\/\/ for historical interest and future work. It will probably change \n\/\/\/ substantially in the future.\n#if 0\n\n#include \"X86.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/SSARegMap.h\"\n#include \"X86RegisterInfo.h\"\n#include <iostream>\n\n\/\/ Include the generated instruction selector...\n#include \"X86GenInstrSelector.inc\"\nusing namespace llvm;\n\nnamespace {\n struct ISel : public FunctionPass, SelectionDAGTargetBuilder {\n TargetMachine &TM;\n ISel(TargetMachine &tm) : TM(tm) {}\n int VarArgsFrameIndex; \/\/ FrameIndex for start of varargs area\n\n bool runOnFunction(Function &Fn) {\n MachineFunction &MF = MachineFunction::construct(&Fn, TM);\n SelectionDAG DAG(MF, TM, *this);\n\n std::cerr << \"\\n\\n\\n=== \"\n << DAG.getMachineFunction().getFunction()->getName() << \"\\n\";\n\n DAG.dump();\n X86ISel(DAG).generateCode();\n std::cerr << \"\\n\\n\\n\";\n return true;\n }\n\n public: \/\/ Implementation of the SelectionDAGTargetBuilder class...\n \/\/\/ expandArguments - Add nodes to the DAG to indicate how to load arguments\n \/\/\/ off of the X86 stack.\n void expandArguments(SelectionDAG &SD);\n void expandCall(SelectionDAG &SD, CallInst &CI);\n };\n}\n\n\nvoid ISel::expandArguments(SelectionDAG &SD) {\n\n \/\/ Add DAG nodes to load the arguments... On entry to a function on the X86,\n \/\/ the stack frame looks like this:\n \/\/\n \/\/ [ESP] -- return address\n \/\/ [ESP + 4] -- first argument (leftmost lexically)\n \/\/ [ESP + 8] -- second argument, if first argument is four bytes in size\n \/\/ ... \n \/\/\n MachineFunction &F = SD.getMachineFunction();\n MachineFrameInfo *MFI = F.getFrameInfo();\n const Function &Fn = *F.getFunction();\n \n unsigned ArgOffset = 0; \/\/ Frame mechanisms handle retaddr slot\n for (Function::const_aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {\n MVT::ValueType ObjectVT = SD.getValueType(I->getType());\n unsigned ArgIncrement = 4;\n unsigned ObjSize;\n switch (ObjectVT) {\n default: assert(0 && \"Unhandled argument type!\");\n case MVT::i8: ObjSize = 1; break;\n case MVT::i16: ObjSize = 2; break;\n case MVT::i32: ObjSize = 4; break;\n case MVT::i64: ObjSize = ArgIncrement = 8; break;\n case MVT::f32: ObjSize = 4; break;\n case MVT::f64: ObjSize = ArgIncrement = 8; break;\n }\n \/\/ Create the frame index object for this incoming parameter...\n int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);\n \n \/\/ Create the SelectionDAG nodes corresponding to a load from this parameter\n SelectionDAGNode *FIN = new SelectionDAGNode(ISD::FrameIndex, MVT::i32);\n FIN->addValue(new ReducedValue_FrameIndex_i32(FI));\n\n SelectionDAGNode *Arg\n = new SelectionDAGNode(ISD::Load, ObjectVT, F.begin(), FIN);\n\n \/\/ Add the SelectionDAGNodes to the SelectionDAG... note that there is no\n \/\/ reason to add chain nodes here. We know that no loads ore stores will\n \/\/ ever alias these loads, so we are free to perform the load at any time in\n \/\/ the function\n SD.addNode(FIN);\n SD.addNodeForValue(Arg, I);\n\n ArgOffset += ArgIncrement; \/\/ Move on to the next argument...\n }\n\n \/\/ If the function takes variable number of arguments, make a frame index for\n \/\/ the start of the first vararg value... for expansion of llvm.va_start.\n if (Fn.getFunctionType()->isVarArg())\n VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);\n}\n\nvoid ISel::expandCall(SelectionDAG &SD, CallInst &CI) {\n assert(0 && \"ISel::expandCall not implemented!\");\n}\n\n\/\/\/ createX86PatternInstructionSelector - This pass converts an LLVM function\n\/\/\/ into a machine code representation using pattern matching and a machine\n\/\/\/ description file.\n\/\/\/\nFunctionPass *llvm::createX86PatternInstructionSelector(TargetMachine &TM) {\n return new ISel(TM); \n}\n\n#endif\n<commit_msg>This file is now dead.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ $Id: quadrature_build.C,v 1.9 2006-03-22 19:26:33 roystgnr Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ includes\n\n\n\n\/\/ Local includes\n#include \"quadrature_gauss.h\"\n#include \"quadrature_jacobi.h\"\n#include \"quadrature_simpson.h\"\n#include \"quadrature_trap.h\"\n\n\n\nAutoPtr<QBase> QBase::build(const QuadratureType _qt,\n\t\t\t const unsigned int _dim,\n\t\t\t const Order _order)\n{\n switch (_qt)\n {\n \n case QGAUSS:\n {\n\n#ifdef DEBUG\n\tif (_order > FORTYTHIRD)\n\t {\n\t std::cout << \"WARNING: Gauss quadrature implemented\" << std::endl\n\t\t << \" up to FORTYTHIRD order.\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QGauss(_dim, _order));\n\treturn ap;\n }\n\n case QJACOBI_1_0:\n {\n\n#ifdef DEBUG\n\tif (_order > TWENTYTHIRD)\n\t {\n\t std::cout << \"WARNING: Jacobi(1,0) quadrature implemented\" << std::endl\n\t\t << \" up to TWENTYTHIRD order.\" << std::endl;\n\t }\n\n\tif (_dim > 1)\n\t {\n\t std::cout << \"WARNING: Jacobi(1,0) quadrature implemented\" << std::endl\n\t\t << \" in 1D only.\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QJacobi(_dim, _order, 1, 0));\n\treturn ap;\n }\n\n case QJACOBI_2_0:\n {\n\n#ifdef DEBUG\n\tif (_order > TWENTYTHIRD)\n\t {\n\t std::cout << \"WARNING: Jacobi(2,0) quadrature implemented\" << std::endl\n\t\t << \" up to TWENTYTHIRD order.\" << std::endl;\n\t }\n\n\tif (_dim > 1)\n\t {\n\t std::cout << \"WARNING: Jacobi(2,0) quadrature implemented\" << std::endl\n\t\t << \" in 1D only.\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QJacobi(_dim, _order, 2, 0));\n\treturn ap;\n }\n\n case QSIMPSON:\n {\n\n#ifdef DEBUG\n\tif (_order > THIRD)\n\t {\n\t std::cout << \"WARNING: Simpson rule provides only\" << std::endl\n\t\t << \" THIRD order!\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QSimpson(_dim));\n\treturn ap;\n }\n\n case QTRAP:\n {\n\n#ifdef DEBUG\n\tif (_order > FIRST)\n\t {\n\t std::cout << \"WARNING: Trapezoidal rule provides only\" << std::endl\n\t\t << \" FIRST order!\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QTrap(_dim));\n\treturn ap;\n }\n\n\n default:\n { \n\tstd::cerr << \"ERROR: Bad qt=\" << _qt << std::endl;\n\terror();\n }\n }\n\n\n error();\n AutoPtr<QBase> ap(NULL);\n return ap;\n}\n\n<commit_msg>Added Clough option to QBase::build()<commit_after>\/\/ $Id: quadrature_build.C,v 1.10 2006-03-27 23:50:42 roystgnr Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ includes\n\n\n\n\/\/ Local includes\n#include \"quadrature_clough.h\"\n#include \"quadrature_gauss.h\"\n#include \"quadrature_jacobi.h\"\n#include \"quadrature_simpson.h\"\n#include \"quadrature_trap.h\"\n\n\n\nAutoPtr<QBase> QBase::build(const QuadratureType _qt,\n\t\t\t const unsigned int _dim,\n\t\t\t const Order _order)\n{\n switch (_qt)\n {\n \n case QCLOUGH:\n {\n#ifdef DEBUG\n\tif (_order > TWENTYTHIRD)\n\t {\n\t std::cout << \"WARNING: Clough quadrature implemented\" << std::endl\n\t\t << \" up to TWENTYTHIRD order.\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QClough(_dim, _order));\n\treturn ap;\n }\n\n case QGAUSS:\n {\n\n#ifdef DEBUG\n\tif (_order > FORTYTHIRD)\n\t {\n\t std::cout << \"WARNING: Gauss quadrature implemented\" << std::endl\n\t\t << \" up to FORTYTHIRD order.\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QGauss(_dim, _order));\n\treturn ap;\n }\n\n case QJACOBI_1_0:\n {\n\n#ifdef DEBUG\n\tif (_order > TWENTYTHIRD)\n\t {\n\t std::cout << \"WARNING: Jacobi(1,0) quadrature implemented\" << std::endl\n\t\t << \" up to TWENTYTHIRD order.\" << std::endl;\n\t }\n\n\tif (_dim > 1)\n\t {\n\t std::cout << \"WARNING: Jacobi(1,0) quadrature implemented\" << std::endl\n\t\t << \" in 1D only.\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QJacobi(_dim, _order, 1, 0));\n\treturn ap;\n }\n\n case QJACOBI_2_0:\n {\n\n#ifdef DEBUG\n\tif (_order > TWENTYTHIRD)\n\t {\n\t std::cout << \"WARNING: Jacobi(2,0) quadrature implemented\" << std::endl\n\t\t << \" up to TWENTYTHIRD order.\" << std::endl;\n\t }\n\n\tif (_dim > 1)\n\t {\n\t std::cout << \"WARNING: Jacobi(2,0) quadrature implemented\" << std::endl\n\t\t << \" in 1D only.\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QJacobi(_dim, _order, 2, 0));\n\treturn ap;\n }\n\n case QSIMPSON:\n {\n\n#ifdef DEBUG\n\tif (_order > THIRD)\n\t {\n\t std::cout << \"WARNING: Simpson rule provides only\" << std::endl\n\t\t << \" THIRD order!\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QSimpson(_dim));\n\treturn ap;\n }\n\n case QTRAP:\n {\n\n#ifdef DEBUG\n\tif (_order > FIRST)\n\t {\n\t std::cout << \"WARNING: Trapezoidal rule provides only\" << std::endl\n\t\t << \" FIRST order!\" << std::endl;\n\t }\n#endif\n\n\tAutoPtr<QBase> ap(new QTrap(_dim));\n\treturn ap;\n }\n\n\n default:\n { \n\tstd::cerr << \"ERROR: Bad qt=\" << _qt << std::endl;\n\terror();\n }\n }\n\n\n error();\n AutoPtr<QBase> ap(NULL);\n return ap;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Halide tutorial lesson 10: AOT compilation part 1\n\n\/\/ This lesson demonstrates how to use Halide as an more traditional\n\/\/ ahead-of-time (AOT) compiler.\n\n\/\/ This lesson is split across two files. The first (this one), builds\n\/\/ a Halide pipeline and compiles it to an object file and header. The\n\/\/ second (lesson_10_aot_compilation_run.cpp), uses that object file\n\/\/ to actually run the pipeline. This means that compiling this code\n\/\/ is a multi-step process.\n\n\/\/ On linux, you can compile and run it like so:\n\/\/ g++ lesson_10*generate.cpp -g -std=c++11 -I ..\/include -L ..\/bin -lHalide -lpthread -ldl -o lesson_10_generate\n\/\/ LD_LIBRARY_PATH=..\/bin .\/lesson_10_generate\n\/\/ g++ lesson_10*run.cpp lesson_10_halide.o -lpthread -o lesson_10_run\n\/\/ .\/lesson_10_run\n\n\/\/ On os x:\n\/\/ g++ lesson_10*generate.cpp -g -std=c++11 -I ..\/include -L ..\/bin -lHalide -o lesson_10_generate\n\/\/ DYLD_LIBRARY_PATH=..\/bin .\/lesson_10_generate\n\/\/ g++ lesson_10*run.cpp lesson_10_halide.o -o lesson_10_run\n\/\/ .\/lesson_10_run\n\n\/\/ The benefits of this approach are that the final program:\n\/\/ - Doesn't do any jit compilation at runtime, so it's fast.\n\/\/ - Doesn't depend on libHalide at all, so it's a small, easy-to-deploy binary.\n\n\/\/ If you have the entire Halide source tree, you can also build it by\n\/\/ running:\n\/\/ make tutorial_lesson_10_aot_compilation_run\n\/\/ in a shell with the current directory at the top of the halide\n\/\/ source tree.\n\n#include \"Halide.h\"\n#include <stdio.h>\nusing namespace Halide;\n\nint main(int argc, char **argv) {\n\n \/\/ We'll define a simple one-stage pipeline:\n Func brighter;\n Var x, y;\n\n \/\/ The pipeline will depend on one scalar parameter.\n Param<uint8_t> offset;\n\n \/\/ And take one grayscale 8-bit input buffer. The first\n \/\/ constructor argument gives the type of a pixel, and the second\n \/\/ specifies the number of dimensions (not the number of\n \/\/ channels!). For a grayscale image this is two; for a color\n \/\/ image it's three. Currently, four dimensions is the maximum for\n \/\/ inputs and outputs.\n ImageParam input(type_of<uint8_t>(), 2);\n\n \/\/ If we were jit-compiling, these would just be an int and an\n \/\/ Image, but because we want to compile the pipeline once and\n \/\/ have it work for any value of the parameter, we need to make a\n \/\/ Param object, which can be used like an Expr, and an ImageParam\n \/\/ object, which can be used like an Image.\n\n \/\/ Define the Func.\n brighter(x, y) = input(x, y) + offset;\n\n \/\/ Schedule it.\n brighter.vectorize(x, 16).parallel(y);\n\n \/\/ This time, instead of calling brighter.realize(...), which\n \/\/ would compile and run the pipeline immediately, we'll call a\n \/\/ method that compiles the pipeline to a static library and header.\n \/\/\n \/\/ For AOT-compiled code, we need to explicitly declare the\n \/\/ arguments to the routine. This routine takes two. Arguments are\n \/\/ usually Params or ImageParams.\n std::vector<Argument> args = {input, offset};\n brighter.compile_to_static_library(\"lesson_10_halide\", args);\n\n \/\/ If you're using C++11, you can just say:\n \/\/ brighter.compile_to_static_library(\"lesson_10_halide\", {input, offset});\n\n printf(\"Halide pipeline compiled, but not yet run.\\n\");\n\n \/\/ To continue this lesson, look in the file lesson_10_aot_compilation_run.cpp\n\n return 0;\n}\n<commit_msg>Fix comment in lesson 10<commit_after>\/\/ Halide tutorial lesson 10: AOT compilation part 1\n\n\/\/ This lesson demonstrates how to use Halide as an more traditional\n\/\/ ahead-of-time (AOT) compiler.\n\n\/\/ This lesson is split across two files. The first (this one), builds\n\/\/ a Halide pipeline and compiles it to an object file and header. The\n\/\/ second (lesson_10_aot_compilation_run.cpp), uses that object file\n\/\/ to actually run the pipeline. This means that compiling this code\n\/\/ is a multi-step process.\n\n\/\/ On linux, you can compile and run it like so:\n\/\/ g++ lesson_10*generate.cpp -g -std=c++11 -I ..\/include -L ..\/bin -lHalide -lpthread -ldl -o lesson_10_generate\n\/\/ LD_LIBRARY_PATH=..\/bin .\/lesson_10_generate\n\/\/ g++ lesson_10*run.cpp lesson_10_halide.o -lpthread -ldl -o lesson_10_run\n\/\/ .\/lesson_10_run\n\n\/\/ On os x:\n\/\/ g++ lesson_10*generate.cpp -g -std=c++11 -I ..\/include -L ..\/bin -lHalide -o lesson_10_generate\n\/\/ DYLD_LIBRARY_PATH=..\/bin .\/lesson_10_generate\n\/\/ g++ lesson_10*run.cpp lesson_10_halide.o -o lesson_10_run\n\/\/ .\/lesson_10_run\n\n\/\/ The benefits of this approach are that the final program:\n\/\/ - Doesn't do any jit compilation at runtime, so it's fast.\n\/\/ - Doesn't depend on libHalide at all, so it's a small, easy-to-deploy binary.\n\n\/\/ If you have the entire Halide source tree, you can also build it by\n\/\/ running:\n\/\/ make tutorial_lesson_10_aot_compilation_run\n\/\/ in a shell with the current directory at the top of the halide\n\/\/ source tree.\n\n#include \"Halide.h\"\n#include <stdio.h>\nusing namespace Halide;\n\nint main(int argc, char **argv) {\n\n \/\/ We'll define a simple one-stage pipeline:\n Func brighter;\n Var x, y;\n\n \/\/ The pipeline will depend on one scalar parameter.\n Param<uint8_t> offset;\n\n \/\/ And take one grayscale 8-bit input buffer. The first\n \/\/ constructor argument gives the type of a pixel, and the second\n \/\/ specifies the number of dimensions (not the number of\n \/\/ channels!). For a grayscale image this is two; for a color\n \/\/ image it's three. Currently, four dimensions is the maximum for\n \/\/ inputs and outputs.\n ImageParam input(type_of<uint8_t>(), 2);\n\n \/\/ If we were jit-compiling, these would just be an int and an\n \/\/ Image, but because we want to compile the pipeline once and\n \/\/ have it work for any value of the parameter, we need to make a\n \/\/ Param object, which can be used like an Expr, and an ImageParam\n \/\/ object, which can be used like an Image.\n\n \/\/ Define the Func.\n brighter(x, y) = input(x, y) + offset;\n\n \/\/ Schedule it.\n brighter.vectorize(x, 16).parallel(y);\n\n \/\/ This time, instead of calling brighter.realize(...), which\n \/\/ would compile and run the pipeline immediately, we'll call a\n \/\/ method that compiles the pipeline to a static library and header.\n \/\/\n \/\/ For AOT-compiled code, we need to explicitly declare the\n \/\/ arguments to the routine. This routine takes two. Arguments are\n \/\/ usually Params or ImageParams.\n std::vector<Argument> args = {input, offset};\n brighter.compile_to_static_library(\"lesson_10_halide\", args);\n\n \/\/ If you're using C++11, you can just say:\n \/\/ brighter.compile_to_static_library(\"lesson_10_halide\", {input, offset});\n\n printf(\"Halide pipeline compiled, but not yet run.\\n\");\n\n \/\/ To continue this lesson, look in the file lesson_10_aot_compilation_run.cpp\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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 <netinet\/tcp.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <unistd.h>\n#include <cstdio>\n#include <cerrno>\n#include <netdb.h>\n#include <iostream>\n#include <string>\n\n#include \"io\/validation.h\"\n#include \"io\/ClientSocket.h\"\n\n\nstd::string Socket::HOSTNAME = Socket::getMyHostName(0);\n\n\nSocket::Socket(const std::string &hostname, const uint16_t port,\n\t\tconst uint16_t listeners = -1) :\n\t\trequested_hostname_(hostname), port_(port), addr_info_(0), socket_file_descriptor_(\n\t\t\t\t-1), socket_max_(0), listeners_(listeners), canonical_hostname_(\"\") {\n\tlogger_ = Logger::getLogger();\n\tFD_ZERO(&total_list_);\n\tFD_ZERO(&read_fds_);\n\n}\n\nSocket::Socket(const std::string &hostname, const uint16_t port) :\n\t\t::Socket(hostname, port, 0) {\n\n}\n\nSocket::Socket(const Socket &&other) :\n\t\trequested_hostname_(std::move(other.requested_hostname_)), port_(\n\t\t\t\tstd::move(other.port_)), addr_info_(std::move(other.addr_info_)), socket_file_descriptor_(\n\t\t\t\tother.socket_file_descriptor_), socket_max_(\n\t\t\t\tother.socket_max_.load()), listeners_(other.listeners_), total_list_(\n\t\t\t\tother.total_list_), read_fds_(other.read_fds_), canonical_hostname_(\n\t\t\t\tstd::move(other.canonical_hostname_)) {\n\tlogger_ = Logger::getLogger();\n\n}\n\nSocket::~Socket() {\n\tcloseStream();\n}\n\nvoid Socket::closeStream()\n{\n if (0 != addr_info_) {\n\t freeaddrinfo(addr_info_);\n\t addr_info_=0;\n }\n\n if (socket_file_descriptor_ >= 0)\n {\n\t close(socket_file_descriptor_);\n\t socket_file_descriptor_ = -1;\n }\n}\n\nint8_t Socket::createConnection(const addrinfo *p) {\n\tif ((socket_file_descriptor_ = socket(p->ai_family, p->ai_socktype,\n\t\t\tp->ai_protocol)) == -1) {\n\t\tlogger_->log_error(\"error while connecting to server socket\");\n\t\treturn -1;\n\t}\n\n\tsetSocketOptions(socket_file_descriptor_);\n\n\tif (listeners_ > 0) {\n\n\t\tstruct sockaddr_in *sa_loc = (struct sockaddr_in*) p->ai_addr;\n\t\tsa_loc->sin_family = AF_INET;\n\t\tsa_loc->sin_port = htons(port_);\n\t\tsa_loc->sin_addr.s_addr = htonl(INADDR_ANY);\n\n\t\tif (bind(socket_file_descriptor_, p->ai_addr, p->ai_addrlen) == -1) {\n\t\t\tlogger_->log_error(\"Could not bind to socket\", strerror(errno));\n\t\t\treturn -1;\n\t\t}\n\t}\n\t{\n\t if (listeners_ <=0 )\n\t {\n\t\tstruct sockaddr_in *sa_loc = (struct sockaddr_in*) p->ai_addr;\n\t\tsa_loc->sin_family = AF_INET;\n\t\t\/\/sa_loc->sin_port = htons(port);\n\t\tsa_loc->sin_port = htons(port_);\n\t\t\/\/ use any address if you are connecting to the local machine for testing\n\t\t\/\/ otherwise we must use the requested hostname\n\t\tif (IsNullOrEmpty(requested_hostname_) || requested_hostname_==\"localhost\")\n\t\t sa_loc->sin_addr.s_addr = htonl(INADDR_ANY);\n\t\telse\n\t\t sa_loc->sin_addr.s_addr = inet_addr(requested_hostname_.c_str());\n\t\tif (connect(socket_file_descriptor_, p->ai_addr, p->ai_addrlen) == -1) {\n\t\t\t close(socket_file_descriptor_);\n\t\t\t\tsocket_file_descriptor_ = -1;\n\t\t\t\tlogger_->log_warn(\"Could not connect to socket, error:%s\", strerror(errno));\n\t\t\t\treturn -1;\n\n\t\t}\n\t }\n\t}\n\n\t\/\/ listen\n\tif (listeners_ > 0) {\n\t\tif (listen(socket_file_descriptor_, listeners_) == -1) {\n\t\t\tlogger_->log_warn(\"attempted connection, saw %s\", strerror(errno));\n\t\t\treturn -1;\n\t\t}\n\n\t}\n\t\/\/ add the listener to the total set\n\tFD_SET(socket_file_descriptor_, &total_list_);\n\tsocket_max_ = socket_file_descriptor_;\n\treturn 0;\n}\n\nshort Socket::initialize() {\n\n\tstruct sockaddr_in servAddr;\n\n\taddrinfo hints = { sizeof(addrinfo) };\n\tmemset(&hints, 0, sizeof hints); \/\/ make sure the struct is empty\n\thints.ai_family = AF_UNSPEC;\n\thints.ai_socktype = SOCK_STREAM;\n\thints.ai_flags = AI_CANONNAME;\n\tif (listeners_ > 0)\n\t hints.ai_flags |= AI_PASSIVE;\n\n\thints.ai_protocol = 0; \/* any protocol *\/\n\n\tint errcode = getaddrinfo(requested_hostname_.c_str(), 0, &hints, &addr_info_);\n\n\tif (errcode != 0) {\n\t\tlogger_->log_error(\"Saw error during getaddrinfo, error: %s\",strerror(errno));\n\t\treturn -1;\n\t}\n\n\tsocket_file_descriptor_ = -1;\n\n\tauto p = addr_info_;\n\tfor (; p != NULL; p = p->ai_next) {\n\t\tif (IsNullOrEmpty(canonical_hostname_)) {\n\t\t\tif (!IsNullOrEmpty(p) && !IsNullOrEmpty(p->ai_canonname))\n\t\t\t\tcanonical_hostname_ = p->ai_canonname;\n\t\t}\n\n\t\t\/\/we've successfully connected\n\t\tif (port_ > 0 && createConnection(p) >= 0)\n\t\t{\n\t\t\treturn 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn -1;\n\n}\n\nshort Socket::select_descriptor(const uint16_t msec) {\n\tstruct timeval tv;\n\tint retval;\n\n\tread_fds_ = total_list_;\n\n\ttv.tv_sec = msec \/ 1000;\n\ttv.tv_usec = (msec % 1000) * 1000;\n\n\tstd::lock_guard<std::recursive_mutex> guard(selection_mutex_);\n\n\tif (msec > 0)\n\t\tretval = select(socket_max_ + 1, &read_fds_, NULL, NULL, &tv);\n\telse\n\t\tretval = select(socket_max_ + 1, &read_fds_, NULL, NULL, NULL);\n\n\tif (retval < 0) {\n\t\tlogger_->log_error(\"Saw error during selection, error:%i %s\",retval,strerror(errno));\n\t\treturn retval;\n\t}\n\n\tfor (int i = 0; i <= socket_max_; i++) {\n\t\tif (FD_ISSET(i, &read_fds_)) {\n\n\t\t\tif (i == socket_file_descriptor_) {\n\t\t\t if (listeners_ > 0)\n\t\t\t {\n\t\t\t\tstruct sockaddr_storage remoteaddr; \/\/ client address\n\t\t\t\tsocklen_t addrlen = sizeof remoteaddr;\n\t\t\t\tint newfd = accept(socket_file_descriptor_,\n\t\t\t\t\t\t(struct sockaddr *) &remoteaddr, &addrlen);\n\t\t\t\tFD_SET(newfd, &total_list_); \/\/ add to master set\n\t\t\t\tif (newfd > socket_max_) { \/\/ keep track of the max\n\t\t\t\t\tsocket_max_ = newfd;\n\t\t\t\t}\n\t\t\t\treturn newfd;\n\n\n\n\t\t\t }\n\t\t\t else{\n\t\t\t return socket_file_descriptor_;\n\t\t\t }\n\t\t\t\t\/\/ we have a new connection\n\t\t\t} else {\n\t\t\t\t\/\/ data to be received on i\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn -1;\n}\n\nshort Socket::setSocketOptions(const int sock) {\n\tint opt = 1;\n\tbool nagle_off = true;\n#ifndef __MACH__\n\tif (nagle_off) {\n\t\tif (setsockopt(sock, SOL_TCP, TCP_NODELAY, (void *) &opt, sizeof(opt))\n\t\t\t\t< 0) {\n\t\t\tlogger_->log_error(\"setsockopt() TCP_NODELAY failed\");\n\t\t\tclose(sock);\n\t\t\treturn -1;\n\t\t}\n\t\tif (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &opt,\n\t\t\t\t\t\tsizeof(opt)) < 0) {\n\t\t\tlogger_->log_error(\"setsockopt() SO_REUSEADDR failed\");\n\t\t\tclose(sock);\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tint sndsize = 256 * 1024;\n\tif (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *) &sndsize,\n\t\t\t\t\t(int) sizeof(sndsize)) < 0) {\n\t\tlogger_->log_error(\"setsockopt() SO_SNDBUF failed\");\n\t\tclose(sock);\n\t\treturn -1;\n\t}\n\n#else\n\tif (listeners_ > 0) {\n\t\t\/\/ lose the pesky \"address already in use\" error message\n\t\tif (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &opt,\n\t\t\t\tsizeof(opt)) < 0) {\n\t\t\tlogger_->log_error(\"setsockopt() SO_REUSEADDR failed\");\n\t\t\tclose(sock);\n\t\t\treturn -1;\n\t\t}\n\t}\n#endif\n\treturn 0;\n}\n\nstd::string Socket::getHostname() const {\n\treturn canonical_hostname_;\n}\n\nint Socket::writeData(std::vector<uint8_t> &buf, int buflen) {\n\n\tif (buf.capacity() < buflen)\n\t\treturn -1;\n\treturn writeData((uint8_t*) &buf[0], buflen);\n}\n\n\/\/ data stream overrides\n\nint Socket::writeData(uint8_t *value, int size) {\n\n\tint ret = 0, bytes = 0;\n\n\twhile (bytes < size) {\n\n\n\n\t\tret = send(socket_file_descriptor_, value + bytes, size - bytes, 0);\n\t\t\/\/check for errors\n\t\tif (ret <= 0) {\n\t\t\tclose(socket_file_descriptor_);\n\t\t\tlogger_->log_error(\"Could not send to %d, error: %s\",socket_file_descriptor_, strerror(errno));\n\t\t\treturn ret;\n\t\t}\n\t\tbytes += ret;\n\n\t}\n\n\tif (ret)\n\t\tlogger_->log_debug(\"Send data size %d over socket %d\", size,\n\t\t\t\tsocket_file_descriptor_);\n\n\treturn bytes;\n\n}\n\ntemplate<typename T>\ninline std::vector<uint8_t> Socket::readBuffer(const T& t) {\n\tstd::vector<uint8_t> buf;\n\tbuf.resize(sizeof t);\n\treadData((uint8_t*) &buf[0], sizeof(t));\n\treturn buf;\n}\n\n\nint Socket::write(uint64_t base_value, bool is_little_endian){\n\n return Serializable::write(base_value,this,is_little_endian);\n}\n\n\nint Socket::write(uint32_t base_value, bool is_little_endian){\n return Serializable::write(base_value,this,is_little_endian);\n}\n\nint Socket::write(uint16_t base_value, bool is_little_endian){\n return Serializable::write(base_value,this,is_little_endian);\n}\n\n\nint Socket::read(uint64_t &value, bool is_little_endian) {\n\n\tauto buf = readBuffer(value);\n\n\tif (is_little_endian) {\n\t\tvalue = ((uint64_t) buf[0] << 56) | ((uint64_t) (buf[1] & 255) << 48)\n\t\t\t\t| ((uint64_t) (buf[2] & 255) << 40)\n\t\t\t\t| ((uint64_t) (buf[3] & 255) << 32)\n\t\t\t\t| ((uint64_t) (buf[4] & 255) << 24)\n\t\t\t\t| ((uint64_t) (buf[5] & 255) << 16)\n\t\t\t\t| ((uint64_t) (buf[6] & 255) << 8)\n\t\t\t\t| ((uint64_t) (buf[7] & 255) << 0);\n\t} else {\n\t\tvalue = ((uint64_t) buf[0] << 0) | ((uint64_t) (buf[1] & 255) << 8)\n\t\t\t\t| ((uint64_t) (buf[2] & 255) << 16)\n\t\t\t\t| ((uint64_t) (buf[3] & 255) << 24)\n\t\t\t\t| ((uint64_t) (buf[4] & 255) << 32)\n\t\t\t\t| ((uint64_t) (buf[5] & 255) << 40)\n\t\t\t\t| ((uint64_t) (buf[6] & 255) << 48)\n\t\t\t\t| ((uint64_t) (buf[7] & 255) << 56);\n\t}\n\treturn sizeof(value);\n}\n\nint Socket::read(uint32_t &value, bool is_little_endian) {\n\n\tauto buf = readBuffer(value);\n\n\tif (is_little_endian) {\n\t\tvalue = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];\n\t} else {\n\t\tvalue = buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24;\n\n\t}\n\n\treturn sizeof(value);\n}\n\nint Socket::read(uint16_t &value, bool is_little_endian) {\n\n\tauto buf = readBuffer(value);\n\n\tif (is_little_endian) {\n\t\tvalue = (buf[0] << 8) | buf[1];\n\t} else {\n\t\tvalue = buf[0] | buf[1] << 8;\n\n\t}\n\treturn sizeof(value);\n}\n\nint Socket::readData(std::vector<uint8_t> &buf, int buflen) {\n\n\tif (buf.capacity() < buflen)\n\t{\n\t buf.resize(buflen);\n\t}\n\treturn readData((uint8_t*) &buf[0], buflen);\n}\n\nint Socket::readData(uint8_t *buf, int buflen) {\n\n\tint total_read = 0;\n\twhile (buflen) {\n\t\tshort fd = select_descriptor(1000);\n\t\tif (fd < 0) {\n\n\t\t\tlogger_->log_info(\"fd close %i\",buflen);\n\t\t\tclose(socket_file_descriptor_);\n\t\t\treturn -1;\n\t\t}\n\n\t\tint bytes_read = recv(fd, buf, buflen, 0);\n\t\tif (bytes_read <= 0) {\n\t\t\tif (bytes_read == 0)\n\t\t\t\tlogger_->log_info(\"Other side hung up on %d\", fd);\n\t\t\telse {\n\t\t\t\tlogger_->log_error(\"Could not recv on %d, error: %s\",fd, strerror(errno));\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\n\n\t\tbuflen -= bytes_read;\n\t\tbuf += bytes_read;\n\t\ttotal_read += bytes_read;\n\t}\n\n\treturn total_read;\n}\n<commit_msg>MINIFI-235: Add curly braces per review<commit_after>\/**\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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 <netinet\/tcp.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <unistd.h>\n#include <cstdio>\n#include <cerrno>\n#include <netdb.h>\n#include <iostream>\n#include <string>\n\n#include \"io\/validation.h\"\n#include \"io\/ClientSocket.h\"\n\n\nstd::string Socket::HOSTNAME = Socket::getMyHostName(0);\n\n\nSocket::Socket(const std::string &hostname, const uint16_t port,\n\t\tconst uint16_t listeners = -1) :\n\t\trequested_hostname_(hostname), port_(port), addr_info_(0), socket_file_descriptor_(\n\t\t\t\t-1), socket_max_(0), listeners_(listeners), canonical_hostname_(\"\") {\n\tlogger_ = Logger::getLogger();\n\tFD_ZERO(&total_list_);\n\tFD_ZERO(&read_fds_);\n\n}\n\nSocket::Socket(const std::string &hostname, const uint16_t port) :\n\t\t::Socket(hostname, port, 0) {\n\n}\n\nSocket::Socket(const Socket &&other) :\n\t\trequested_hostname_(std::move(other.requested_hostname_)), port_(\n\t\t\t\tstd::move(other.port_)), addr_info_(std::move(other.addr_info_)), socket_file_descriptor_(\n\t\t\t\tother.socket_file_descriptor_), socket_max_(\n\t\t\t\tother.socket_max_.load()), listeners_(other.listeners_), total_list_(\n\t\t\t\tother.total_list_), read_fds_(other.read_fds_), canonical_hostname_(\n\t\t\t\tstd::move(other.canonical_hostname_)) {\n\tlogger_ = Logger::getLogger();\n\n}\n\nSocket::~Socket() {\n\tcloseStream();\n}\n\nvoid Socket::closeStream()\n{\n if (0 != addr_info_) {\n\t freeaddrinfo(addr_info_);\n\t addr_info_=0;\n }\n\n if (socket_file_descriptor_ >= 0)\n {\n\t close(socket_file_descriptor_);\n\t socket_file_descriptor_ = -1;\n }\n}\n\nint8_t Socket::createConnection(const addrinfo *p) {\n\tif ((socket_file_descriptor_ = socket(p->ai_family, p->ai_socktype,\n\t\t\tp->ai_protocol)) == -1) {\n\t\tlogger_->log_error(\"error while connecting to server socket\");\n\t\treturn -1;\n\t}\n\n\tsetSocketOptions(socket_file_descriptor_);\n\n\tif (listeners_ > 0) {\n\n\t\tstruct sockaddr_in *sa_loc = (struct sockaddr_in*) p->ai_addr;\n\t\tsa_loc->sin_family = AF_INET;\n\t\tsa_loc->sin_port = htons(port_);\n\t\tsa_loc->sin_addr.s_addr = htonl(INADDR_ANY);\n\n\t\tif (bind(socket_file_descriptor_, p->ai_addr, p->ai_addrlen) == -1) {\n\t\t\tlogger_->log_error(\"Could not bind to socket\", strerror(errno));\n\t\t\treturn -1;\n\t\t}\n\t}\n\t{\n\t if (listeners_ <=0 )\n\t {\n\t\tstruct sockaddr_in *sa_loc = (struct sockaddr_in*) p->ai_addr;\n\t\tsa_loc->sin_family = AF_INET;\n\t\t\/\/sa_loc->sin_port = htons(port);\n\t\tsa_loc->sin_port = htons(port_);\n\t\t\/\/ use any address if you are connecting to the local machine for testing\n\t\t\/\/ otherwise we must use the requested hostname\n\t\tif (IsNullOrEmpty(requested_hostname_) || requested_hostname_==\"localhost\")\n\t\t{\n\t\t sa_loc->sin_addr.s_addr = htonl(INADDR_ANY);\n\t\t}\n\t\telse\n\t\t{\n\t\t sa_loc->sin_addr.s_addr = inet_addr(requested_hostname_.c_str());\n\t\t}\n\t\tif (connect(socket_file_descriptor_, p->ai_addr, p->ai_addrlen) == -1) {\n\t\t\t close(socket_file_descriptor_);\n\t\t\t\tsocket_file_descriptor_ = -1;\n\t\t\t\tlogger_->log_warn(\"Could not connect to socket, error:%s\", strerror(errno));\n\t\t\t\treturn -1;\n\n\t\t}\n\t }\n\t}\n\n\t\/\/ listen\n\tif (listeners_ > 0) {\n\t\tif (listen(socket_file_descriptor_, listeners_) == -1) {\n\t\t\tlogger_->log_warn(\"attempted connection, saw %s\", strerror(errno));\n\t\t\treturn -1;\n\t\t}\n\n\t}\n\t\/\/ add the listener to the total set\n\tFD_SET(socket_file_descriptor_, &total_list_);\n\tsocket_max_ = socket_file_descriptor_;\n\treturn 0;\n}\n\nshort Socket::initialize() {\n\n\tstruct sockaddr_in servAddr;\n\n\taddrinfo hints = { sizeof(addrinfo) };\n\tmemset(&hints, 0, sizeof hints); \/\/ make sure the struct is empty\n\thints.ai_family = AF_UNSPEC;\n\thints.ai_socktype = SOCK_STREAM;\n\thints.ai_flags = AI_CANONNAME;\n\tif (listeners_ > 0)\n\t hints.ai_flags |= AI_PASSIVE;\n\n\thints.ai_protocol = 0; \/* any protocol *\/\n\n\tint errcode = getaddrinfo(requested_hostname_.c_str(), 0, &hints, &addr_info_);\n\n\tif (errcode != 0) {\n\t\tlogger_->log_error(\"Saw error during getaddrinfo, error: %s\",strerror(errno));\n\t\treturn -1;\n\t}\n\n\tsocket_file_descriptor_ = -1;\n\n\tauto p = addr_info_;\n\tfor (; p != NULL; p = p->ai_next) {\n\t\tif (IsNullOrEmpty(canonical_hostname_)) {\n\t\t\tif (!IsNullOrEmpty(p) && !IsNullOrEmpty(p->ai_canonname))\n\t\t\t\tcanonical_hostname_ = p->ai_canonname;\n\t\t}\n\n\t\t\/\/we've successfully connected\n\t\tif (port_ > 0 && createConnection(p) >= 0)\n\t\t{\n\t\t\treturn 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn -1;\n\n}\n\nshort Socket::select_descriptor(const uint16_t msec) {\n\tstruct timeval tv;\n\tint retval;\n\n\tread_fds_ = total_list_;\n\n\ttv.tv_sec = msec \/ 1000;\n\ttv.tv_usec = (msec % 1000) * 1000;\n\n\tstd::lock_guard<std::recursive_mutex> guard(selection_mutex_);\n\n\tif (msec > 0)\n\t\tretval = select(socket_max_ + 1, &read_fds_, NULL, NULL, &tv);\n\telse\n\t\tretval = select(socket_max_ + 1, &read_fds_, NULL, NULL, NULL);\n\n\tif (retval < 0) {\n\t\tlogger_->log_error(\"Saw error during selection, error:%i %s\",retval,strerror(errno));\n\t\treturn retval;\n\t}\n\n\tfor (int i = 0; i <= socket_max_; i++) {\n\t\tif (FD_ISSET(i, &read_fds_)) {\n\n\t\t\tif (i == socket_file_descriptor_) {\n\t\t\t if (listeners_ > 0)\n\t\t\t {\n\t\t\t\tstruct sockaddr_storage remoteaddr; \/\/ client address\n\t\t\t\tsocklen_t addrlen = sizeof remoteaddr;\n\t\t\t\tint newfd = accept(socket_file_descriptor_,\n\t\t\t\t\t\t(struct sockaddr *) &remoteaddr, &addrlen);\n\t\t\t\tFD_SET(newfd, &total_list_); \/\/ add to master set\n\t\t\t\tif (newfd > socket_max_) { \/\/ keep track of the max\n\t\t\t\t\tsocket_max_ = newfd;\n\t\t\t\t}\n\t\t\t\treturn newfd;\n\n\n\n\t\t\t }\n\t\t\t else{\n\t\t\t return socket_file_descriptor_;\n\t\t\t }\n\t\t\t\t\/\/ we have a new connection\n\t\t\t} else {\n\t\t\t\t\/\/ data to be received on i\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn -1;\n}\n\nshort Socket::setSocketOptions(const int sock) {\n\tint opt = 1;\n\tbool nagle_off = true;\n#ifndef __MACH__\n\tif (nagle_off) {\n\t\tif (setsockopt(sock, SOL_TCP, TCP_NODELAY, (void *) &opt, sizeof(opt))\n\t\t\t\t< 0) {\n\t\t\tlogger_->log_error(\"setsockopt() TCP_NODELAY failed\");\n\t\t\tclose(sock);\n\t\t\treturn -1;\n\t\t}\n\t\tif (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &opt,\n\t\t\t\t\t\tsizeof(opt)) < 0) {\n\t\t\tlogger_->log_error(\"setsockopt() SO_REUSEADDR failed\");\n\t\t\tclose(sock);\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tint sndsize = 256 * 1024;\n\tif (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *) &sndsize,\n\t\t\t\t\t(int) sizeof(sndsize)) < 0) {\n\t\tlogger_->log_error(\"setsockopt() SO_SNDBUF failed\");\n\t\tclose(sock);\n\t\treturn -1;\n\t}\n\n#else\n\tif (listeners_ > 0) {\n\t\t\/\/ lose the pesky \"address already in use\" error message\n\t\tif (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &opt,\n\t\t\t\tsizeof(opt)) < 0) {\n\t\t\tlogger_->log_error(\"setsockopt() SO_REUSEADDR failed\");\n\t\t\tclose(sock);\n\t\t\treturn -1;\n\t\t}\n\t}\n#endif\n\treturn 0;\n}\n\nstd::string Socket::getHostname() const {\n\treturn canonical_hostname_;\n}\n\nint Socket::writeData(std::vector<uint8_t> &buf, int buflen) {\n\n\tif (buf.capacity() < buflen)\n\t\treturn -1;\n\treturn writeData((uint8_t*) &buf[0], buflen);\n}\n\n\/\/ data stream overrides\n\nint Socket::writeData(uint8_t *value, int size) {\n\n\tint ret = 0, bytes = 0;\n\n\twhile (bytes < size) {\n\n\n\n\t\tret = send(socket_file_descriptor_, value + bytes, size - bytes, 0);\n\t\t\/\/check for errors\n\t\tif (ret <= 0) {\n\t\t\tclose(socket_file_descriptor_);\n\t\t\tlogger_->log_error(\"Could not send to %d, error: %s\",socket_file_descriptor_, strerror(errno));\n\t\t\treturn ret;\n\t\t}\n\t\tbytes += ret;\n\n\t}\n\n\tif (ret)\n\t\tlogger_->log_debug(\"Send data size %d over socket %d\", size,\n\t\t\t\tsocket_file_descriptor_);\n\n\treturn bytes;\n\n}\n\ntemplate<typename T>\ninline std::vector<uint8_t> Socket::readBuffer(const T& t) {\n\tstd::vector<uint8_t> buf;\n\tbuf.resize(sizeof t);\n\treadData((uint8_t*) &buf[0], sizeof(t));\n\treturn buf;\n}\n\n\nint Socket::write(uint64_t base_value, bool is_little_endian){\n\n return Serializable::write(base_value,this,is_little_endian);\n}\n\n\nint Socket::write(uint32_t base_value, bool is_little_endian){\n return Serializable::write(base_value,this,is_little_endian);\n}\n\nint Socket::write(uint16_t base_value, bool is_little_endian){\n return Serializable::write(base_value,this,is_little_endian);\n}\n\n\nint Socket::read(uint64_t &value, bool is_little_endian) {\n\n\tauto buf = readBuffer(value);\n\n\tif (is_little_endian) {\n\t\tvalue = ((uint64_t) buf[0] << 56) | ((uint64_t) (buf[1] & 255) << 48)\n\t\t\t\t| ((uint64_t) (buf[2] & 255) << 40)\n\t\t\t\t| ((uint64_t) (buf[3] & 255) << 32)\n\t\t\t\t| ((uint64_t) (buf[4] & 255) << 24)\n\t\t\t\t| ((uint64_t) (buf[5] & 255) << 16)\n\t\t\t\t| ((uint64_t) (buf[6] & 255) << 8)\n\t\t\t\t| ((uint64_t) (buf[7] & 255) << 0);\n\t} else {\n\t\tvalue = ((uint64_t) buf[0] << 0) | ((uint64_t) (buf[1] & 255) << 8)\n\t\t\t\t| ((uint64_t) (buf[2] & 255) << 16)\n\t\t\t\t| ((uint64_t) (buf[3] & 255) << 24)\n\t\t\t\t| ((uint64_t) (buf[4] & 255) << 32)\n\t\t\t\t| ((uint64_t) (buf[5] & 255) << 40)\n\t\t\t\t| ((uint64_t) (buf[6] & 255) << 48)\n\t\t\t\t| ((uint64_t) (buf[7] & 255) << 56);\n\t}\n\treturn sizeof(value);\n}\n\nint Socket::read(uint32_t &value, bool is_little_endian) {\n\n\tauto buf = readBuffer(value);\n\n\tif (is_little_endian) {\n\t\tvalue = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];\n\t} else {\n\t\tvalue = buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24;\n\n\t}\n\n\treturn sizeof(value);\n}\n\nint Socket::read(uint16_t &value, bool is_little_endian) {\n\n\tauto buf = readBuffer(value);\n\n\tif (is_little_endian) {\n\t\tvalue = (buf[0] << 8) | buf[1];\n\t} else {\n\t\tvalue = buf[0] | buf[1] << 8;\n\n\t}\n\treturn sizeof(value);\n}\n\nint Socket::readData(std::vector<uint8_t> &buf, int buflen) {\n\n\tif (buf.capacity() < buflen)\n\t{\n\t buf.resize(buflen);\n\t}\n\treturn readData((uint8_t*) &buf[0], buflen);\n}\n\nint Socket::readData(uint8_t *buf, int buflen) {\n\n\tint total_read = 0;\n\twhile (buflen) {\n\t\tshort fd = select_descriptor(1000);\n\t\tif (fd < 0) {\n\n\t\t\tlogger_->log_info(\"fd close %i\",buflen);\n\t\t\tclose(socket_file_descriptor_);\n\t\t\treturn -1;\n\t\t}\n\n\t\tint bytes_read = recv(fd, buf, buflen, 0);\n\t\tif (bytes_read <= 0) {\n\t\t\tif (bytes_read == 0)\n\t\t\t\tlogger_->log_info(\"Other side hung up on %d\", fd);\n\t\t\telse {\n\t\t\t\tlogger_->log_error(\"Could not recv on %d, error: %s\",fd, strerror(errno));\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\n\n\t\tbuflen -= bytes_read;\n\t\tbuf += bytes_read;\n\t\ttotal_read += bytes_read;\n\t}\n\n\treturn total_read;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include \"src\/metamethod_p.hpp\"\n#include <qimessaging\/metamethod.hpp>\n\nnamespace qi {\n\n MetaMethod::MetaMethod()\n {\n _p = new MetaMethodPrivate();\n }\n\n MetaMethod::MetaMethod(const std::string &sig, const qi::Functor *functor)\n {\n _p = new MetaMethodPrivate(sig, functor);\n }\n\n MetaMethod::MetaMethod(const MetaMethod &other)\n {\n _p = new MetaMethodPrivate();\n *_p = *(other._p);\n }\n\n MetaMethod& MetaMethod::operator=(const MetaMethod &other)\n {\n _p = new MetaMethodPrivate();\n *_p = *(other._p);\n return (*this);\n }\n\n MetaMethod::~MetaMethod()\n {\n delete _p;\n }\n\n const std::string &MetaMethod::signature() const\n {\n return _p->signature();\n }\n\n const qi::Functor *MetaMethod::functor() const\n {\n return _p->_functor;\n }\n\n unsigned int MetaMethod::index() const\n {\n return _p->index();\n }\n\n};<commit_msg>metamethod: fix operator=<commit_after>\/*\n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include \"src\/metamethod_p.hpp\"\n#include <qimessaging\/metamethod.hpp>\n\nnamespace qi {\n\n MetaMethod::MetaMethod()\n : _p(new MetaMethodPrivate())\n {\n }\n\n MetaMethod::MetaMethod(const std::string &sig, const qi::Functor *functor)\n : _p(new MetaMethodPrivate(sig, functor))\n {\n }\n\n MetaMethod::MetaMethod(const MetaMethod &other)\n : _p(new MetaMethodPrivate())\n {\n *_p = *(other._p);\n }\n\n MetaMethod& MetaMethod::operator=(const MetaMethod &other)\n {\n *_p = *(other._p);\n return (*this);\n }\n\n MetaMethod::~MetaMethod()\n {\n delete _p;\n }\n\n const std::string &MetaMethod::signature() const\n {\n return _p->signature();\n }\n\n const qi::Functor *MetaMethod::functor() const\n {\n return _p->_functor;\n }\n\n unsigned int MetaMethod::index() const\n {\n return _p->index();\n }\n\n};\n<|endoftext|>"} {"text":"<commit_before>#include <robocup2Dsim\/server\/monitor.hpp>\n#include <gtest\/gtest.h>\n\nnamespace rse = robocup2Dsim::server;\n\nTEST(clock_monitor_test, record_transmit_basic)\n{\n rse::clock_monitor monitor(5);\n monitor.record_transmit();\n monitor.record_transmit();\n monitor.record_transmit();\n monitor.record_transmit();\n monitor.record_transmit();\n EXPECT_EQ(5, monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n monitor.record_transmit();\n EXPECT_EQ(5, monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n monitor.record_transmit();\n EXPECT_EQ(5, monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n}\n<commit_msg>adding more test cases<commit_after>#include <robocup2Dsim\/server\/monitor.hpp>\n\n#include <beam\/internet\/endpoint.hpp>\n#include <gtest\/gtest.h>\n\nnamespace bin = beam::internet;\nnamespace rse = robocup2Dsim::server;\n\nTEST(clock_monitor_test, record_transmit_basic)\n{\n rse::clock_monitor monitor(5);\n\n std::uint16_t seq1 = monitor.record_transmit();\n std::uint16_t seq2 = monitor.record_transmit();\n std::uint16_t seq3 = monitor.record_transmit();\n std::uint16_t seq4 = monitor.record_transmit();\n std::uint16_t seq5 = monitor.record_transmit();\n\n EXPECT_EQ(monitor.target_sample_size(), monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n EXPECT_EQ(seq1 + 1, seq2) << \"The sequence number is not increasing on next transmit\";\n EXPECT_EQ(seq2 + 1, seq3) << \"The sequence number is not increasing on next transmit\";\n EXPECT_EQ(seq3 + 1, seq4) << \"The sequence number is not increasing on next transmit\";\n EXPECT_EQ(seq4 + 1, seq5) << \"The sequence number is not increasing on next transmit\";\n\n monitor.record_transmit();\n EXPECT_EQ(monitor.target_sample_size(), monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n\n monitor.record_transmit();\n EXPECT_EQ(monitor.target_sample_size(), monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n}\n\nTEST(clock_monitor_test, record_receive_basic)\n{\n const bin::endpoint_id endpoint(99);\n rse::clock_monitor monitor(5);\n\n monitor.record_receive(endpoint, 1, std::chrono::steady_clock::now());\n monitor.record_receive(endpoint, 2, std::chrono::steady_clock::now());\n monitor.record_receive(endpoint, 3, std::chrono::steady_clock::now());\n monitor.record_receive(endpoint, 4, std::chrono::steady_clock::now());\n monitor.record_receive(endpoint, 5, std::chrono::steady_clock::now());\n\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(1, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n\n monitor.record_receive(endpoint, 6, std::chrono::steady_clock::now());\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(2, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n\n monitor.record_receive(endpoint, 7, std::chrono::steady_clock::now());\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(3, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n}\n\nTEST(clock_monitor_test, needed_sequence_kept_single_client)\n{\n const bin::endpoint_id endpoint(99);\n rse::clock_monitor monitor(5);\n\n std::uint16_t seq1 = monitor.record_transmit();\n std::uint16_t seq2 = monitor.record_transmit();\n std::uint16_t seq3 = monitor.record_transmit();\n std::uint16_t seq4 = monitor.record_transmit();\n std::uint16_t seq5 = monitor.record_transmit();\n monitor.record_receive(endpoint, seq1, std::chrono::steady_clock::now());\n monitor.record_receive(endpoint, seq2, std::chrono::steady_clock::now());\n monitor.record_receive(endpoint, seq3, std::chrono::steady_clock::now());\n monitor.record_receive(endpoint, seq4, std::chrono::steady_clock::now());\n monitor.record_receive(endpoint, seq5, std::chrono::steady_clock::now());\n\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(seq1, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n\n std::uint16_t seq6 = monitor.record_transmit();\n EXPECT_EQ(monitor.target_sample_size() + 1, monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(seq1, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n\n std::uint16_t seq7 = monitor.record_transmit();\n EXPECT_EQ(monitor.target_sample_size() + 2, monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(seq1, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n\n monitor.record_receive(endpoint, seq6, std::chrono::steady_clock::now());\n EXPECT_EQ(monitor.target_sample_size() + 2, monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(seq2, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n\n monitor.record_receive(endpoint, seq7, std::chrono::steady_clock::now());\n EXPECT_EQ(monitor.target_sample_size() + 2, monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(seq3, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n\n std::uint16_t seq8 = monitor.record_transmit();\n EXPECT_EQ(seq7 + 1, seq8) << \"Wrong next sequence number\";\n EXPECT_EQ(monitor.target_sample_size() + 1, monitor.transmit_sample_size()) << \"The number of recorded transmits is wrong\";\n EXPECT_EQ(monitor.target_sample_size(), monitor.receive_sample_size(endpoint)) << \"The number of recorded receives is wrong\";\n EXPECT_EQ(seq3, monitor.oldest_receive()) << \"The oldest receive calculation is wrong\";\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"config.h\"\n#define _XOPEN_SOURCE_EXTENDED 1\n#include <locale.h>\n\n#if defined HAVE_NCURSESW_CURSES_H\n# include <ncursesw\/curses.h>\n#elif defined HAVE_NCURSESW_H\n# include <ncursesw.h>\n#elif defined HAVE_NCURSES_CURSES_H\n# include <ncurses\/curses.h>\n#elif defined HAVE_NCURSES_H\n# include <ncurses.h>\n#elif defined HAVE_CURSES_H\n# include <curses.h>\n#else\n# error \"SysV or X\/Open-compatible Curses header file required\"\n#endif\n\nint main(int argc, char *argv[])\n{\n setlocale(LC_ALL, \"\");\n\n WINDOW *stdscr = initscr();\n cbreak();\n char buf[1024];\n FILE *file = fopen(argv[1], \"r\");\n int row = 0;\n while (!feof(file)) {\n if (0 < fgets(buf, sizeof(buf), file)) {\n mvwaddstr(stdscr, row++, 0, buf);\n }\n }\n getch();\n endwin();\n}\n<commit_msg>[tests] fix an issue with the last commit<commit_after>\n#include \"config.h\"\n#define _XOPEN_SOURCE_EXTENDED 1\n#include <locale.h>\n\n#if defined HAVE_NCURSESW_CURSES_H\n# include <ncursesw\/curses.h>\n#elif defined HAVE_NCURSESW_H\n# include <ncursesw.h>\n#elif defined HAVE_NCURSES_CURSES_H\n# include <ncurses\/curses.h>\n#elif defined HAVE_NCURSES_H\n# include <ncurses.h>\n#elif defined HAVE_CURSES_H\n# include <curses.h>\n#else\n# error \"SysV or X\/Open-compatible Curses header file required\"\n#endif\n\nint main(int argc, char *argv[])\n{\n setlocale(LC_ALL, \"\");\n\n WINDOW *stdscr = initscr();\n cbreak();\n char buf[1024];\n FILE *file = fopen(argv[1], \"r\");\n int row = 0;\n while (!feof(file)) {\n if (fgets(buf, sizeof(buf), file) != nullptr) {\n mvwaddstr(stdscr, row++, 0, buf);\n }\n }\n getch();\n endwin();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n#include <almath\/types\/alpose2d.h>\n#include <almath\/tools\/altrigonometry.h>\n#include <gtest\/gtest.h>\n\nTEST(ALPose2DTest, basicOperator)\n{\n AL::Math::Pose2D pPos2D = AL::Math::Pose2D();\n AL::Math::Pose2D pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n AL::Math::Pose2D pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n\n \/\/ operator !=\n EXPECT_FALSE(pPos2D1 != pPos2D2);\n EXPECT_TRUE(pPos2D1 != AL::Math::Pose2D());\n\n \/\/ operator ==\n EXPECT_TRUE(pPos2D1 == pPos2D2);\n EXPECT_FALSE(pPos2D1 == AL::Math::Pose2D());\n\n \/\/ operator + (a+b)\n pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D = pPos2D1 + pPos2D2;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(1.0f, -0.6f, 0.2f), 0.001f));\n\n \/\/ operator + (+a)\n pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D = AL::Math::Pose2D();\n pPos2D = +pPos2D1;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(0.5f, -0.3f, 0.1f), 0.001f));\n\n \/\/ operator +=\n pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D1 += pPos2D2;\n EXPECT_TRUE(pPos2D1.isNear(AL::Math::Pose2D(1.0f, -0.6f, 0.2f), 0.001f));\n\n pPos2D1 = AL::Math::Pose2D(1.0f, 0.7f, 0.5f);\n pPos2D2 = pPos2D1;\n pPos2D2 += pPos2D1;\n pPos2D1 += pPos2D1;\n EXPECT_TRUE(pPos2D2.isNear(pPos2D1));\n\n \/\/ operator - (a-b)\n pPos2D1 = AL::Math::Pose2D(0.5f, +0.3f, 0.1f);\n pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D = pPos2D2 - pPos2D1;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(0.0f, -0.6f, 0.0f), 0.001f));\n\n \/\/ operator - (-a)\n pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D = AL::Math::Pose2D();\n pPos2D = - pPos2D1;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(-0.5f, 0.3f, -0.1f), 0.001f));\n\n \/\/ operator -=\n pPos2D1 = AL::Math::Pose2D(0.6f, -0.4f, 0.2f);\n pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D1 -= pPos2D2;\n EXPECT_TRUE(pPos2D1.isNear(AL::Math::Pose2D(0.1f, -0.1f, 0.1f), 0.001f));\n\n \/\/ operator *\n pPos2D1 = AL::Math::Pose2D(1.0f, 0.0f, 0.0f);\n pPos2D2 = AL::Math::Pose2D(0.0f, 1.0f, 0.2f);\n pPos2D = pPos2D1*pPos2D2;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(1.0f, 1.0f, 0.2f), 0.001f));\n\n\/\/ \/\/ operator *\n\/\/ pPos2D1 = AL::Math::Pose2D(-0.13027f, 0.348845f, 3.14151f);\n\/\/ pPos2D2 = AL::Math::Pose2D(0.1f, 0.0f, 0.0f);\n\/\/ pPos2D = pPos2D1*pPos2D2;\n\/\/ EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(-0.212624f, 0.349525f, 3.14155f), 0.001f));\n\n \/\/ operator *=\n pPos2D1 = AL::Math::Pose2D(1.0f, 0.0f, 0.0f);\n pPos2D2 = AL::Math::Pose2D(0.0f, 1.0f, 0.2f);\n pPos2D1 *= pPos2D2;\n EXPECT_TRUE(pPos2D1.isNear(AL::Math::Pose2D(1.0f, 1.0f, 0.2f), 0.001f));\n\n pPos2D1 = AL::Math::Pose2D(1.0f, 0.7f, 0.5f);\n pPos2D2 = pPos2D1;\n pPos2D2 *= pPos2D1;\n pPos2D1 *= pPos2D1;\n EXPECT_TRUE(pPos2D2.isNear(pPos2D1));\n}\n\n\nTEST(ALPose2DTest, isNear)\n{\n AL::Math::Pose2D pPos2D = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(0.5f, -0.3f, 0.1f), 0.0001f));\n EXPECT_FALSE(pPos2D.isNear(AL::Math::Pose2D(0.4f, -0.3f, 0.1f), 0.0001f));\n EXPECT_FALSE(pPos2D.isNear(AL::Math::Pose2D(0.5f, -0.4f, 0.1f), 0.0001f));\n EXPECT_FALSE(pPos2D.isNear(AL::Math::Pose2D(0.5f, -0.3f, 0.2f), 0.0001f));\n}\n\nTEST(ALPose2DTest, distance)\n{\n AL::Math::Pose2D pPos2D = AL::Math::Pose2D(1.0f, 2.0f, 3.0f);\n EXPECT_NEAR(pPos2D.distance(AL::Math::Pose2D(1.0f, 1.0f, 1.0f)), 1.0f, 0.0001f);\n}\n\nTEST(ALPose2DTest, distanceSquared)\n{\n AL::Math::Pose2D pPos2D = AL::Math::Pose2D(1.0f, 2.0f, 3.0f);\n EXPECT_NEAR(pPos2D.distanceSquared(AL::Math::Pose2D(0.0f, 0.0f, 0.0f)), 5.0f, 0.0001f);\n}\n\nTEST(ALPose2DTest, pose2DInverse)\n{\n AL::Math::Pose2D pPose2D = AL::Math::Pose2D(0.1f, -0.1f, -0.5f);\n AL::Math::Pose2D pResult = AL::Math::Pose2D(-0.135701f, 0.0398157f, 0.5f);\n AL::Math::Pose2D pInverse = pPose2D.inverse();\n EXPECT_TRUE(pInverse.isNear(pResult, 0.0001f));\n EXPECT_TRUE((pInverse*pPose2D).isNear(AL::Math::Pose2D(), 0.0001f));\n\n pInverse = AL::Math::Pose2D();\n pInverse = AL::Math::pose2DInverse(pPose2D);\n EXPECT_TRUE(pInverse.isNear(pResult, 0.0001f));\n EXPECT_TRUE((pInverse*pPose2D).isNear(AL::Math::Pose2D(), 0.0001f));\n\n pInverse = AL::Math::Pose2D();\n AL::Math::pose2DInverse(pPose2D, pInverse);\n EXPECT_TRUE(pInverse.isNear(pResult, 0.0001f));\n EXPECT_TRUE((pInverse*pPose2D).isNear(AL::Math::Pose2D(), 0.0001f));\n}\n\nTEST(ALPose2DTest, pose2dInvertInPlace)\n{\n \/\/ We use pose2dInverse, previously tested\n AL::Math::Pose2D pIn = AL::Math::Pose2D(0.2f, -2.1f, 35.0*AL::Math::TO_RAD);\n AL::Math::Pose2D pCopy = pIn;\n AL::Math::Pose2D pInverse = AL::Math::pose2DInverse(pIn);\n\n AL::Math::pose2dInvertInPlace(pIn);\n\n EXPECT_TRUE(pIn.isNear(pInverse, 0.0001f));\n EXPECT_TRUE((pIn*pCopy).isNear(AL::Math::Pose2D(), 0.0001f));\n}\n\nTEST(ALPose2DTest, pose2dDiff)\n{\n \/\/ We use pose2dInverse, previously tested\n \/\/inverse(pPos1)*pPos2\n AL::Math::Pose2D pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0*AL::Math::TO_RAD);\n AL::Math::Pose2D pPos2 = pPos1;\n AL::Math::Pose2D pResult = AL::Math::pose2dDiff(pPos2, pPos1);\n\n EXPECT_TRUE(pResult.isNear(AL::Math::Pose2D(), 0.0001f));\n\n pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0*AL::Math::TO_RAD);\n pPos2 = AL::Math::Pose2D(-1.2f, 0.1f, -10.0*AL::Math::TO_RAD);\n pResult = AL::Math::pose2dDiff(pPos1, pPos2);\n\n AL::Math::Pose2D pExpected = AL::Math::pose2DInverse(pPos1)*pPos2;\n EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n}\n\n\nTEST(ALPose2DTest, diff)\n{\n \/\/ We use pose2dInverse, previously tested\n \/\/inverse(pPos1)*pPos2\n AL::Math::Pose2D pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0*AL::Math::TO_RAD);\n AL::Math::Pose2D pPos2 = pPos1;\n AL::Math::Pose2D pResult = pPos1.diff(pPos2);\n\n EXPECT_TRUE(pResult.isNear(AL::Math::Pose2D(), 0.0001f));\n\n pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0*AL::Math::TO_RAD);\n pPos2 = AL::Math::Pose2D(-1.2f, 0.1f, -10.0*AL::Math::TO_RAD);\n pResult = pPos1.diff(pPos2);\n\n AL::Math::Pose2D pExpected = AL::Math::pose2DInverse(pPos1)*pPos2;\n EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n}\n\nTEST(ALPose2DTest, pinv)\n{\n \/\/ We use pose2dInverse, previously tested\n \/\/inverse(pPos1)*pPos2\n AL::Math::Pose2D pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0*AL::Math::TO_RAD);\n AL::Math::Pose2D pPos2 = AL::Math::pinv(pPos1);\n AL::Math::Pose2D pResult = pPos2*pPos1;\n EXPECT_TRUE(pResult.isNear(AL::Math::Pose2D(), 0.0001f));\n\n pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0*AL::Math::TO_RAD);\n pResult = AL::Math::pinv(pPos1);\n AL::Math::Pose2D pExpected = AL::Math::pose2DInverse(pPos1);\n\n EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n}\n<commit_msg>ALMATH: fix warning<commit_after>\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n#include <almath\/types\/alpose2d.h>\n#include <almath\/tools\/altrigonometry.h>\n#include <gtest\/gtest.h>\n\nTEST(ALPose2DTest, basicOperator)\n{\n AL::Math::Pose2D pPos2D = AL::Math::Pose2D();\n AL::Math::Pose2D pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n AL::Math::Pose2D pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n\n \/\/ operator !=\n EXPECT_FALSE(pPos2D1 != pPos2D2);\n EXPECT_TRUE(pPos2D1 != AL::Math::Pose2D());\n\n \/\/ operator ==\n EXPECT_TRUE(pPos2D1 == pPos2D2);\n EXPECT_FALSE(pPos2D1 == AL::Math::Pose2D());\n\n \/\/ operator + (a+b)\n pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D = pPos2D1 + pPos2D2;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(1.0f, -0.6f, 0.2f), 0.001f));\n\n \/\/ operator + (+a)\n pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D = AL::Math::Pose2D();\n pPos2D = +pPos2D1;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(0.5f, -0.3f, 0.1f), 0.001f));\n\n \/\/ operator +=\n pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D1 += pPos2D2;\n EXPECT_TRUE(pPos2D1.isNear(AL::Math::Pose2D(1.0f, -0.6f, 0.2f), 0.001f));\n\n pPos2D1 = AL::Math::Pose2D(1.0f, 0.7f, 0.5f);\n pPos2D2 = pPos2D1;\n pPos2D2 += pPos2D1;\n pPos2D1 += pPos2D1;\n EXPECT_TRUE(pPos2D2.isNear(pPos2D1));\n\n \/\/ operator - (a-b)\n pPos2D1 = AL::Math::Pose2D(0.5f, +0.3f, 0.1f);\n pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D = pPos2D2 - pPos2D1;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(0.0f, -0.6f, 0.0f), 0.001f));\n\n \/\/ operator - (-a)\n pPos2D1 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D = AL::Math::Pose2D();\n pPos2D = - pPos2D1;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(-0.5f, 0.3f, -0.1f), 0.001f));\n\n \/\/ operator -=\n pPos2D1 = AL::Math::Pose2D(0.6f, -0.4f, 0.2f);\n pPos2D2 = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n pPos2D1 -= pPos2D2;\n EXPECT_TRUE(pPos2D1.isNear(AL::Math::Pose2D(0.1f, -0.1f, 0.1f), 0.001f));\n\n \/\/ operator *\n pPos2D1 = AL::Math::Pose2D(1.0f, 0.0f, 0.0f);\n pPos2D2 = AL::Math::Pose2D(0.0f, 1.0f, 0.2f);\n pPos2D = pPos2D1*pPos2D2;\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(1.0f, 1.0f, 0.2f), 0.001f));\n\n\/\/ \/\/ operator *\n\/\/ pPos2D1 = AL::Math::Pose2D(-0.13027f, 0.348845f, 3.14151f);\n\/\/ pPos2D2 = AL::Math::Pose2D(0.1f, 0.0f, 0.0f);\n\/\/ pPos2D = pPos2D1*pPos2D2;\n\/\/ EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(-0.212624f, 0.349525f, 3.14155f), 0.001f));\n\n \/\/ operator *=\n pPos2D1 = AL::Math::Pose2D(1.0f, 0.0f, 0.0f);\n pPos2D2 = AL::Math::Pose2D(0.0f, 1.0f, 0.2f);\n pPos2D1 *= pPos2D2;\n EXPECT_TRUE(pPos2D1.isNear(AL::Math::Pose2D(1.0f, 1.0f, 0.2f), 0.001f));\n\n pPos2D1 = AL::Math::Pose2D(1.0f, 0.7f, 0.5f);\n pPos2D2 = pPos2D1;\n pPos2D2 *= pPos2D1;\n pPos2D1 *= pPos2D1;\n EXPECT_TRUE(pPos2D2.isNear(pPos2D1));\n}\n\n\nTEST(ALPose2DTest, isNear)\n{\n AL::Math::Pose2D pPos2D = AL::Math::Pose2D(0.5f, -0.3f, 0.1f);\n\n EXPECT_TRUE(pPos2D.isNear(AL::Math::Pose2D(0.5f, -0.3f, 0.1f), 0.0001f));\n EXPECT_FALSE(pPos2D.isNear(AL::Math::Pose2D(0.4f, -0.3f, 0.1f), 0.0001f));\n EXPECT_FALSE(pPos2D.isNear(AL::Math::Pose2D(0.5f, -0.4f, 0.1f), 0.0001f));\n EXPECT_FALSE(pPos2D.isNear(AL::Math::Pose2D(0.5f, -0.3f, 0.2f), 0.0001f));\n}\n\nTEST(ALPose2DTest, distance)\n{\n AL::Math::Pose2D pPos2D = AL::Math::Pose2D(1.0f, 2.0f, 3.0f);\n EXPECT_NEAR(pPos2D.distance(AL::Math::Pose2D(1.0f, 1.0f, 1.0f)), 1.0f, 0.0001f);\n}\n\nTEST(ALPose2DTest, distanceSquared)\n{\n AL::Math::Pose2D pPos2D = AL::Math::Pose2D(1.0f, 2.0f, 3.0f);\n EXPECT_NEAR(pPos2D.distanceSquared(AL::Math::Pose2D(0.0f, 0.0f, 0.0f)), 5.0f, 0.0001f);\n}\n\nTEST(ALPose2DTest, pose2DInverse)\n{\n AL::Math::Pose2D pPose2D = AL::Math::Pose2D(0.1f, -0.1f, -0.5f);\n AL::Math::Pose2D pResult = AL::Math::Pose2D(-0.135701f, 0.0398157f, 0.5f);\n AL::Math::Pose2D pInverse = pPose2D.inverse();\n EXPECT_TRUE(pInverse.isNear(pResult, 0.0001f));\n EXPECT_TRUE((pInverse*pPose2D).isNear(AL::Math::Pose2D(), 0.0001f));\n\n pInverse = AL::Math::Pose2D();\n pInverse = AL::Math::pose2DInverse(pPose2D);\n EXPECT_TRUE(pInverse.isNear(pResult, 0.0001f));\n EXPECT_TRUE((pInverse*pPose2D).isNear(AL::Math::Pose2D(), 0.0001f));\n\n pInverse = AL::Math::Pose2D();\n AL::Math::pose2DInverse(pPose2D, pInverse);\n EXPECT_TRUE(pInverse.isNear(pResult, 0.0001f));\n EXPECT_TRUE((pInverse*pPose2D).isNear(AL::Math::Pose2D(), 0.0001f));\n}\n\nTEST(ALPose2DTest, pose2dInvertInPlace)\n{\n \/\/ We use pose2dInverse, previously tested\n AL::Math::Pose2D pIn = AL::Math::Pose2D(0.2f, -2.1f, 35.0f*AL::Math::TO_RAD);\n AL::Math::Pose2D pCopy = pIn;\n AL::Math::Pose2D pInverse = AL::Math::pose2DInverse(pIn);\n\n AL::Math::pose2dInvertInPlace(pIn);\n\n EXPECT_TRUE(pIn.isNear(pInverse, 0.0001f));\n EXPECT_TRUE((pIn*pCopy).isNear(AL::Math::Pose2D(), 0.0001f));\n}\n\nTEST(ALPose2DTest, pose2dDiff)\n{\n \/\/ We use pose2dInverse, previously tested\n \/\/inverse(pPos1)*pPos2\n AL::Math::Pose2D pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0f*AL::Math::TO_RAD);\n AL::Math::Pose2D pPos2 = pPos1;\n AL::Math::Pose2D pResult = AL::Math::pose2dDiff(pPos2, pPos1);\n\n EXPECT_TRUE(pResult.isNear(AL::Math::Pose2D(), 0.0001f));\n\n pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0f*AL::Math::TO_RAD);\n pPos2 = AL::Math::Pose2D(-1.2f, 0.1f, -10.0f*AL::Math::TO_RAD);\n pResult = AL::Math::pose2dDiff(pPos1, pPos2);\n\n AL::Math::Pose2D pExpected = AL::Math::pose2DInverse(pPos1)*pPos2;\n EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n}\n\n\nTEST(ALPose2DTest, diff)\n{\n \/\/ We use pose2dInverse, previously tested\n \/\/inverse(pPos1)*pPos2\n AL::Math::Pose2D pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0f*AL::Math::TO_RAD);\n AL::Math::Pose2D pPos2 = pPos1;\n AL::Math::Pose2D pResult = pPos1.diff(pPos2);\n\n EXPECT_TRUE(pResult.isNear(AL::Math::Pose2D(), 0.0001f));\n\n pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0f*AL::Math::TO_RAD);\n pPos2 = AL::Math::Pose2D(-1.2f, 0.1f, -10.0f*AL::Math::TO_RAD);\n pResult = pPos1.diff(pPos2);\n\n AL::Math::Pose2D pExpected = AL::Math::pose2DInverse(pPos1)*pPos2;\n EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n}\n\nTEST(ALPose2DTest, pinv)\n{\n \/\/ We use pose2dInverse, previously tested\n \/\/inverse(pPos1)*pPos2\n AL::Math::Pose2D pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0f*AL::Math::TO_RAD);\n AL::Math::Pose2D pPos2 = AL::Math::pinv(pPos1);\n AL::Math::Pose2D pResult = pPos2*pPos1;\n EXPECT_TRUE(pResult.isNear(AL::Math::Pose2D(), 0.0001f));\n\n pPos1 = AL::Math::Pose2D(0.2f, -2.1f, 35.0f*AL::Math::TO_RAD);\n pResult = AL::Math::pinv(pPos1);\n AL::Math::Pose2D pExpected = AL::Math::pose2DInverse(pPos1);\n\n EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#define EIGEN_DEBUG_ASSIGN\n#include \"main.h\"\n#include <typeinfo>\n\nstd::string demangle_traversal(int t)\n{\n if(t==DefaultTraversal) return \"DefaultTraversal\";\n if(t==LinearTraversal) return \"LinearTraversal\";\n if(t==InnerVectorizedTraversal) return \"InnerVectorizedTraversal\";\n if(t==LinearVectorizedTraversal) return \"LinearVectorizedTraversal\";\n if(t==SliceVectorizedTraversal) return \"SliceVectorizedTraversal\";\n return \"?\";\n}\nstd::string demangle_unrolling(int t)\n{\n if(t==NoUnrolling) return \"NoUnrolling\";\n if(t==InnerUnrolling) return \"InnerUnrolling\";\n if(t==CompleteUnrolling) return \"CompleteUnrolling\";\n return \"?\";\n}\n\ntemplate<typename Dst, typename Src>\nbool test_assign(const Dst&, const Src&, int traversal, int unrolling)\n{\n internal::assign_traits<Dst,Src>::debug();\n bool res = internal::assign_traits<Dst,Src>::Traversal==traversal\n && internal::assign_traits<Dst,Src>::Unrolling==unrolling;\n if(!res)\n {\n std::cerr << \" Expected Traversal == \" << demangle_traversal(traversal)\n << \" got \" << demangle_traversal(internal::assign_traits<Dst,Src>::Traversal) << \"\\n\";\n std::cerr << \" Expected Unrolling == \" << demangle_unrolling(unrolling)\n << \" got \" << demangle_unrolling(internal::assign_traits<Dst,Src>::Unrolling) << \"\\n\";\n }\n return res;\n}\n\ntemplate<typename Dst, typename Src>\nbool test_assign(int traversal, int unrolling)\n{\n internal::assign_traits<Dst,Src>::debug();\n bool res = internal::assign_traits<Dst,Src>::Traversal==traversal\n && internal::assign_traits<Dst,Src>::Unrolling==unrolling;\n if(!res)\n {\n std::cerr << \" Expected Traversal == \" << demangle_traversal(traversal)\n << \" got \" << demangle_traversal(internal::assign_traits<Dst,Src>::Traversal) << \"\\n\";\n std::cerr << \" Expected Unrolling == \" << demangle_unrolling(unrolling)\n << \" got \" << demangle_unrolling(internal::assign_traits<Dst,Src>::Unrolling) << \"\\n\";\n }\n return res;\n}\n\ntemplate<typename Xpr>\nbool test_redux(const Xpr&, int traversal, int unrolling)\n{\n typedef internal::redux_traits<internal::scalar_sum_op<typename Xpr::Scalar>,Xpr> traits;\n bool res = traits::Traversal==traversal && traits::Unrolling==unrolling;\n if(!res)\n {\n std::cerr << \" Expected Traversal == \" << demangle_traversal(traversal)\n << \" got \" << demangle_traversal(traits::Traversal) << \"\\n\";\n std::cerr << \" Expected Unrolling == \" << demangle_unrolling(unrolling)\n << \" got \" << demangle_unrolling(traits::Unrolling) << \"\\n\";\n }\n return res;\n}\n\ntemplate<typename Scalar, bool Enable = internal::packet_traits<Scalar>::Vectorizable> struct vectorization_logic\n{\n enum {\n PacketSize = internal::packet_traits<Scalar>::size\n };\n static void run()\n {\n \n typedef Matrix<Scalar,PacketSize,1> Vector1;\n typedef Matrix<Scalar,Dynamic,1> VectorX;\n typedef Matrix<Scalar,Dynamic,Dynamic> MatrixXX;\n typedef Matrix<Scalar,PacketSize,PacketSize> Matrix11;\n typedef Matrix<Scalar,2*PacketSize,2*PacketSize> Matrix22;\n typedef Matrix<Scalar,(Matrix11::Flags&RowMajorBit)?16:4*PacketSize,(Matrix11::Flags&RowMajorBit)?4*PacketSize:16> Matrix44;\n typedef Matrix<Scalar,(Matrix11::Flags&RowMajorBit)?16:4*PacketSize,(Matrix11::Flags&RowMajorBit)?4*PacketSize:16,DontAlign|EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION> Matrix44u;\n typedef Matrix<Scalar,4*PacketSize,4*PacketSize,ColMajor> Matrix44c;\n typedef Matrix<Scalar,4*PacketSize,4*PacketSize,RowMajor> Matrix44r;\n\n typedef Matrix<Scalar,\n (PacketSize==8 ? 4 : PacketSize==4 ? 2 : PacketSize==2 ? 1 : \/*PacketSize==1 ?*\/ 1),\n (PacketSize==8 ? 2 : PacketSize==4 ? 2 : PacketSize==2 ? 2 : \/*PacketSize==1 ?*\/ 1)\n > Matrix1;\n\n typedef Matrix<Scalar,\n (PacketSize==8 ? 4 : PacketSize==4 ? 2 : PacketSize==2 ? 1 : \/*PacketSize==1 ?*\/ 1),\n (PacketSize==8 ? 2 : PacketSize==4 ? 2 : PacketSize==2 ? 2 : \/*PacketSize==1 ?*\/ 1),\n DontAlign|((Matrix1::Flags&RowMajorBit)?RowMajor:ColMajor)> Matrix1u;\n\n \/\/ this type is made such that it can only be vectorized when viewed as a linear 1D vector\n typedef Matrix<Scalar,\n (PacketSize==8 ? 4 : PacketSize==4 ? 6 : PacketSize==2 ? ((Matrix11::Flags&RowMajorBit)?2:3) : \/*PacketSize==1 ?*\/ 1),\n (PacketSize==8 ? 6 : PacketSize==4 ? 2 : PacketSize==2 ? ((Matrix11::Flags&RowMajorBit)?3:2) : \/*PacketSize==1 ?*\/ 3)\n > Matrix3;\n \n #if !EIGEN_GCC_AND_ARCH_DOESNT_WANT_STACK_ALIGNMENT\n VERIFY(test_assign(Vector1(),Vector1(),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1()+Vector1(),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1().cwiseProduct(Vector1()),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1().template cast<Scalar>(),\n InnerVectorizedTraversal,CompleteUnrolling));\n\n\n VERIFY(test_assign(Vector1(),Vector1(),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1()+Vector1(),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1().cwiseProduct(Vector1()),\n InnerVectorizedTraversal,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix44(),Matrix44()+Matrix44(),\n InnerVectorizedTraversal,InnerUnrolling));\n\n VERIFY(test_assign(Matrix44u(),Matrix44()+Matrix44(),\n LinearTraversal,NoUnrolling));\n\n VERIFY(test_assign(Matrix1u(),Matrix1()+Matrix1(),\n LinearTraversal,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix44c().col(1),Matrix44c().col(2)+Matrix44c().col(3),\n InnerVectorizedTraversal,CompleteUnrolling));\n \n VERIFY(test_assign(Matrix44r().row(2),Matrix44r().row(1)+Matrix44r().row(1),\n InnerVectorizedTraversal,CompleteUnrolling));\n \n if(PacketSize>1)\n {\n typedef Matrix<Scalar,3,3,ColMajor> Matrix33c;\n VERIFY(test_assign(Matrix33c().row(2),Matrix33c().row(1)+Matrix33c().row(1),\n LinearTraversal,CompleteUnrolling));\n VERIFY(test_assign(Matrix33c().col(0),Matrix33c().col(1)+Matrix33c().col(1),\n LinearTraversal,CompleteUnrolling));\n \n VERIFY(test_assign(Matrix3(),Matrix3().cwiseQuotient(Matrix3()),\n LinearVectorizedTraversal,CompleteUnrolling));\n \n VERIFY(test_assign(Matrix<Scalar,17,17>(),Matrix<Scalar,17,17>()+Matrix<Scalar,17,17>(),\n LinearTraversal,NoUnrolling));\n \n VERIFY(test_assign(Matrix11(),Matrix<Scalar,17,17>().template block<PacketSize,PacketSize>(2,3)+Matrix<Scalar,17,17>().template block<PacketSize,PacketSize>(8,4),\n DefaultTraversal,PacketSize>4?InnerUnrolling:CompleteUnrolling));\n }\n \n VERIFY(test_redux(Matrix3(),\n LinearVectorizedTraversal,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix44(),\n LinearVectorizedTraversal,NoUnrolling));\n\n VERIFY(test_redux(Matrix44().template block<(Matrix1::Flags&RowMajorBit)?4:PacketSize,(Matrix1::Flags&RowMajorBit)?PacketSize:4>(1,2),\n DefaultTraversal,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix44c().template block<2*PacketSize,1>(1,2),\n LinearVectorizedTraversal,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix44r().template block<1,2*PacketSize>(2,1),\n LinearVectorizedTraversal,CompleteUnrolling));\n\n VERIFY((test_assign<\n Map<Matrix22, Aligned, OuterStride<3*PacketSize> >,\n Matrix22\n >(InnerVectorizedTraversal,CompleteUnrolling)));\n\n VERIFY((test_assign<\n Map<Matrix<Scalar,EIGEN_PLAIN_ENUM_MAX(2,PacketSize),EIGEN_PLAIN_ENUM_MAX(2,PacketSize)>, Aligned, InnerStride<3*PacketSize> >,\n Matrix<Scalar,EIGEN_PLAIN_ENUM_MAX(2,PacketSize),EIGEN_PLAIN_ENUM_MAX(2,PacketSize)>\n >(DefaultTraversal,CompleteUnrolling)));\n\n VERIFY((test_assign(Matrix11(), Matrix<Scalar,PacketSize,EIGEN_PLAIN_ENUM_MIN(2,PacketSize)>()*Matrix<Scalar,EIGEN_PLAIN_ENUM_MIN(2,PacketSize),PacketSize>(),\n PacketSize>=EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD?DefaultTraversal:InnerVectorizedTraversal, CompleteUnrolling)));\n #endif\n\n VERIFY(test_assign(MatrixXX(10,10),MatrixXX(20,20).block(10,10,2,3),\n SliceVectorizedTraversal,NoUnrolling));\n\n VERIFY(test_redux(VectorX(10),\n LinearVectorizedTraversal,NoUnrolling));\n\n \n }\n};\n\ntemplate<typename Scalar> struct vectorization_logic<Scalar,false>\n{\n static void run() {}\n};\n\nvoid test_vectorization_logic()\n{\n\n#ifdef EIGEN_VECTORIZE\n\n CALL_SUBTEST( vectorization_logic<float>::run() );\n CALL_SUBTEST( vectorization_logic<double>::run() );\n CALL_SUBTEST( vectorization_logic<std::complex<float> >::run() );\n CALL_SUBTEST( vectorization_logic<std::complex<double> >::run() );\n \n if(internal::packet_traits<float>::Vectorizable)\n {\n VERIFY(test_assign(Matrix<float,3,3>(),Matrix<float,3,3>()+Matrix<float,3,3>(),\n LinearTraversal,CompleteUnrolling));\n \n VERIFY(test_redux(Matrix<float,5,2>(),\n DefaultTraversal,CompleteUnrolling));\n }\n \n if(internal::packet_traits<double>::Vectorizable)\n {\n VERIFY(test_assign(Matrix<double,3,3>(),Matrix<double,3,3>()+Matrix<double,3,3>(),\n LinearTraversal,CompleteUnrolling));\n \n VERIFY(test_redux(Matrix<double,7,3>(),\n DefaultTraversal,CompleteUnrolling));\n }\n#endif \/\/ EIGEN_VECTORIZE\n\n}\n<commit_msg>Test vectorization logic for int<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#define EIGEN_DEBUG_ASSIGN\n#include \"main.h\"\n#include <typeinfo>\n\nstd::string demangle_traversal(int t)\n{\n if(t==DefaultTraversal) return \"DefaultTraversal\";\n if(t==LinearTraversal) return \"LinearTraversal\";\n if(t==InnerVectorizedTraversal) return \"InnerVectorizedTraversal\";\n if(t==LinearVectorizedTraversal) return \"LinearVectorizedTraversal\";\n if(t==SliceVectorizedTraversal) return \"SliceVectorizedTraversal\";\n return \"?\";\n}\nstd::string demangle_unrolling(int t)\n{\n if(t==NoUnrolling) return \"NoUnrolling\";\n if(t==InnerUnrolling) return \"InnerUnrolling\";\n if(t==CompleteUnrolling) return \"CompleteUnrolling\";\n return \"?\";\n}\n\ntemplate<typename Dst, typename Src>\nbool test_assign(const Dst&, const Src&, int traversal, int unrolling)\n{\n internal::assign_traits<Dst,Src>::debug();\n bool res = internal::assign_traits<Dst,Src>::Traversal==traversal\n && internal::assign_traits<Dst,Src>::Unrolling==unrolling;\n if(!res)\n {\n std::cerr << \" Expected Traversal == \" << demangle_traversal(traversal)\n << \" got \" << demangle_traversal(internal::assign_traits<Dst,Src>::Traversal) << \"\\n\";\n std::cerr << \" Expected Unrolling == \" << demangle_unrolling(unrolling)\n << \" got \" << demangle_unrolling(internal::assign_traits<Dst,Src>::Unrolling) << \"\\n\";\n }\n return res;\n}\n\ntemplate<typename Dst, typename Src>\nbool test_assign(int traversal, int unrolling)\n{\n internal::assign_traits<Dst,Src>::debug();\n bool res = internal::assign_traits<Dst,Src>::Traversal==traversal\n && internal::assign_traits<Dst,Src>::Unrolling==unrolling;\n if(!res)\n {\n std::cerr << \" Expected Traversal == \" << demangle_traversal(traversal)\n << \" got \" << demangle_traversal(internal::assign_traits<Dst,Src>::Traversal) << \"\\n\";\n std::cerr << \" Expected Unrolling == \" << demangle_unrolling(unrolling)\n << \" got \" << demangle_unrolling(internal::assign_traits<Dst,Src>::Unrolling) << \"\\n\";\n }\n return res;\n}\n\ntemplate<typename Xpr>\nbool test_redux(const Xpr&, int traversal, int unrolling)\n{\n typedef internal::redux_traits<internal::scalar_sum_op<typename Xpr::Scalar>,Xpr> traits;\n bool res = traits::Traversal==traversal && traits::Unrolling==unrolling;\n if(!res)\n {\n std::cerr << \" Expected Traversal == \" << demangle_traversal(traversal)\n << \" got \" << demangle_traversal(traits::Traversal) << \"\\n\";\n std::cerr << \" Expected Unrolling == \" << demangle_unrolling(unrolling)\n << \" got \" << demangle_unrolling(traits::Unrolling) << \"\\n\";\n }\n return res;\n}\n\ntemplate<typename Scalar, bool Enable = internal::packet_traits<Scalar>::Vectorizable> struct vectorization_logic\n{\n typedef internal::packet_traits<Scalar> PacketTraits;\n enum {\n PacketSize = PacketTraits::size\n };\n static void run()\n {\n \n typedef Matrix<Scalar,PacketSize,1> Vector1;\n typedef Matrix<Scalar,Dynamic,1> VectorX;\n typedef Matrix<Scalar,Dynamic,Dynamic> MatrixXX;\n typedef Matrix<Scalar,PacketSize,PacketSize> Matrix11;\n typedef Matrix<Scalar,2*PacketSize,2*PacketSize> Matrix22;\n typedef Matrix<Scalar,(Matrix11::Flags&RowMajorBit)?16:4*PacketSize,(Matrix11::Flags&RowMajorBit)?4*PacketSize:16> Matrix44;\n typedef Matrix<Scalar,(Matrix11::Flags&RowMajorBit)?16:4*PacketSize,(Matrix11::Flags&RowMajorBit)?4*PacketSize:16,DontAlign|EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION> Matrix44u;\n typedef Matrix<Scalar,4*PacketSize,4*PacketSize,ColMajor> Matrix44c;\n typedef Matrix<Scalar,4*PacketSize,4*PacketSize,RowMajor> Matrix44r;\n\n typedef Matrix<Scalar,\n (PacketSize==8 ? 4 : PacketSize==4 ? 2 : PacketSize==2 ? 1 : \/*PacketSize==1 ?*\/ 1),\n (PacketSize==8 ? 2 : PacketSize==4 ? 2 : PacketSize==2 ? 2 : \/*PacketSize==1 ?*\/ 1)\n > Matrix1;\n\n typedef Matrix<Scalar,\n (PacketSize==8 ? 4 : PacketSize==4 ? 2 : PacketSize==2 ? 1 : \/*PacketSize==1 ?*\/ 1),\n (PacketSize==8 ? 2 : PacketSize==4 ? 2 : PacketSize==2 ? 2 : \/*PacketSize==1 ?*\/ 1),\n DontAlign|((Matrix1::Flags&RowMajorBit)?RowMajor:ColMajor)> Matrix1u;\n\n \/\/ this type is made such that it can only be vectorized when viewed as a linear 1D vector\n typedef Matrix<Scalar,\n (PacketSize==8 ? 4 : PacketSize==4 ? 6 : PacketSize==2 ? ((Matrix11::Flags&RowMajorBit)?2:3) : \/*PacketSize==1 ?*\/ 1),\n (PacketSize==8 ? 6 : PacketSize==4 ? 2 : PacketSize==2 ? ((Matrix11::Flags&RowMajorBit)?3:2) : \/*PacketSize==1 ?*\/ 3)\n > Matrix3;\n \n #if !EIGEN_GCC_AND_ARCH_DOESNT_WANT_STACK_ALIGNMENT\n VERIFY(test_assign(Vector1(),Vector1(),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1()+Vector1(),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1().cwiseProduct(Vector1()),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1().template cast<Scalar>(),\n InnerVectorizedTraversal,CompleteUnrolling));\n\n\n VERIFY(test_assign(Vector1(),Vector1(),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1()+Vector1(),\n InnerVectorizedTraversal,CompleteUnrolling));\n VERIFY(test_assign(Vector1(),Vector1().cwiseProduct(Vector1()),\n InnerVectorizedTraversal,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix44(),Matrix44()+Matrix44(),\n InnerVectorizedTraversal,InnerUnrolling));\n\n VERIFY(test_assign(Matrix44u(),Matrix44()+Matrix44(),\n LinearTraversal,NoUnrolling));\n\n VERIFY(test_assign(Matrix1u(),Matrix1()+Matrix1(),\n LinearTraversal,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix44c().col(1),Matrix44c().col(2)+Matrix44c().col(3),\n InnerVectorizedTraversal,CompleteUnrolling));\n \n VERIFY(test_assign(Matrix44r().row(2),Matrix44r().row(1)+Matrix44r().row(1),\n InnerVectorizedTraversal,CompleteUnrolling));\n \n if(PacketSize>1)\n {\n typedef Matrix<Scalar,3,3,ColMajor> Matrix33c;\n VERIFY(test_assign(Matrix33c().row(2),Matrix33c().row(1)+Matrix33c().row(1),\n LinearTraversal,CompleteUnrolling));\n VERIFY(test_assign(Matrix33c().col(0),Matrix33c().col(1)+Matrix33c().col(1),\n LinearTraversal,CompleteUnrolling));\n \n VERIFY(test_assign(Matrix3(),Matrix3().cwiseQuotient(Matrix3()),\n PacketTraits::HasDiv ? LinearVectorizedTraversal : LinearTraversal,CompleteUnrolling));\n \n VERIFY(test_assign(Matrix<Scalar,17,17>(),Matrix<Scalar,17,17>()+Matrix<Scalar,17,17>(),\n LinearTraversal,NoUnrolling));\n \n VERIFY(test_assign(Matrix11(),Matrix<Scalar,17,17>().template block<PacketSize,PacketSize>(2,3)+Matrix<Scalar,17,17>().template block<PacketSize,PacketSize>(8,4),\n DefaultTraversal,PacketSize>4?InnerUnrolling:CompleteUnrolling));\n }\n \n VERIFY(test_redux(Matrix3(),\n LinearVectorizedTraversal,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix44(),\n LinearVectorizedTraversal,NoUnrolling));\n\n VERIFY(test_redux(Matrix44().template block<(Matrix1::Flags&RowMajorBit)?4:PacketSize,(Matrix1::Flags&RowMajorBit)?PacketSize:4>(1,2),\n DefaultTraversal,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix44c().template block<2*PacketSize,1>(1,2),\n LinearVectorizedTraversal,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix44r().template block<1,2*PacketSize>(2,1),\n LinearVectorizedTraversal,CompleteUnrolling));\n\n VERIFY((test_assign<\n Map<Matrix22, Aligned, OuterStride<3*PacketSize> >,\n Matrix22\n >(InnerVectorizedTraversal,CompleteUnrolling)));\n\n VERIFY((test_assign<\n Map<Matrix<Scalar,EIGEN_PLAIN_ENUM_MAX(2,PacketSize),EIGEN_PLAIN_ENUM_MAX(2,PacketSize)>, Aligned, InnerStride<3*PacketSize> >,\n Matrix<Scalar,EIGEN_PLAIN_ENUM_MAX(2,PacketSize),EIGEN_PLAIN_ENUM_MAX(2,PacketSize)>\n >(DefaultTraversal,CompleteUnrolling)));\n\n VERIFY((test_assign(Matrix11(), Matrix<Scalar,PacketSize,EIGEN_PLAIN_ENUM_MIN(2,PacketSize)>()*Matrix<Scalar,EIGEN_PLAIN_ENUM_MIN(2,PacketSize),PacketSize>(),\n PacketSize>=EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD?DefaultTraversal:InnerVectorizedTraversal, CompleteUnrolling)));\n #endif\n\n VERIFY(test_assign(MatrixXX(10,10),MatrixXX(20,20).block(10,10,2,3),\n SliceVectorizedTraversal,NoUnrolling));\n\n VERIFY(test_redux(VectorX(10),\n LinearVectorizedTraversal,NoUnrolling));\n\n \n }\n};\n\ntemplate<typename Scalar> struct vectorization_logic<Scalar,false>\n{\n static void run() {}\n};\n\nvoid test_vectorization_logic()\n{\n\n#ifdef EIGEN_VECTORIZE\n\n CALL_SUBTEST( vectorization_logic<int>::run() );\n CALL_SUBTEST( vectorization_logic<float>::run() );\n CALL_SUBTEST( vectorization_logic<double>::run() );\n CALL_SUBTEST( vectorization_logic<std::complex<float> >::run() );\n CALL_SUBTEST( vectorization_logic<std::complex<double> >::run() );\n \n if(internal::packet_traits<float>::Vectorizable)\n {\n VERIFY(test_assign(Matrix<float,3,3>(),Matrix<float,3,3>()+Matrix<float,3,3>(),\n LinearTraversal,CompleteUnrolling));\n \n VERIFY(test_redux(Matrix<float,5,2>(),\n DefaultTraversal,CompleteUnrolling));\n }\n \n if(internal::packet_traits<double>::Vectorizable)\n {\n VERIFY(test_assign(Matrix<double,3,3>(),Matrix<double,3,3>()+Matrix<double,3,3>(),\n LinearTraversal,CompleteUnrolling));\n \n VERIFY(test_redux(Matrix<double,7,3>(),\n DefaultTraversal,CompleteUnrolling));\n }\n#endif \/\/ EIGEN_VECTORIZE\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * StructureZoneComponent.cpp\n *\n * Created on: Apr 15, 2012\n * Author: TragD\n *\/\n\n#include \"server\/zone\/objects\/scene\/components\/ZoneComponent.h\"\n#include \"StructureZoneComponent.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/managers\/planet\/PlanetManager.h\"\n#include \"server\/zone\/objects\/area\/ActiveArea.h\"\n#include \"server\/zone\/templates\/tangible\/SharedStructureObjectTemplate.h\"\n\nvoid StructureZoneComponent::notifyInsertToZone(SceneObject* sceneObject, Zone* zone) {\n\tZoneComponent::notifyInsertToZone(sceneObject, zone);\n\n}\n\nvoid StructureZoneComponent::notifyRemoveFromZone(SceneObject* sceneObject) {\n\tZoneComponent::notifyRemoveFromZone(sceneObject);\n\n\t\/\/moved to StructureManager::destroyStructure\n}\n<commit_msg>(unstable) [fixed] Missing file from commit 6270 - prevented NPC from spawning<commit_after>\/*\n * StructureZoneComponent.cpp\n *\n * Created on: Apr 15, 2012\n * Author: TragD\n *\/\n\n#include \"server\/zone\/objects\/scene\/components\/ZoneComponent.h\"\n#include \"StructureZoneComponent.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/managers\/planet\/PlanetManager.h\"\n#include \"server\/zone\/objects\/area\/ActiveArea.h\"\n#include \"server\/zone\/templates\/tangible\/SharedStructureObjectTemplate.h\"\n#include \"server\/zone\/objects\/building\/BuildingObject.h\"\nvoid StructureZoneComponent::notifyInsertToZone(SceneObject* sceneObject, Zone* zone) {\n\tZoneComponent::notifyInsertToZone(sceneObject, zone);\n\n\tif(sceneObject->isGCWBase()){\n\t\tManagedReference<BuildingObject*> building = cast<BuildingObject*>(sceneObject);\n\t\tif(building->hasChildCreatures())\n\t\t\tbuilding->spawnChildCreatures();\n\t}\n}\n\nvoid StructureZoneComponent::notifyRemoveFromZone(SceneObject* sceneObject) {\n\tZoneComponent::notifyRemoveFromZone(sceneObject);\n\n\t\/\/moved to StructureManager::destroyStructure\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * For conditions of distribution and use, see copyright notice in license.txt\n *\n * @file EC_SkyX.cpp\n * @brief A sky component using SkyX, http:\/\/www.ogre3d.org\/tikiwiki\/SkyX\n *\/\n\n#define OGRE_INTEROP\n\n#include \"DebugOperatorNew.h\"\n\n#include \"EC_SkyX.h\"\n\n#include \"Scene.h\"\n#include \"Framework.h\"\n#include \"FrameAPI.h\"\n#include \"OgreWorld.h\"\n#include \"Renderer.h\"\n#include \"EC_Camera.h\"\n#include \"LoggingFunctions.h\"\n#include \"OgreConversionUtils.h\"\n\n#include <Ogre.h>\n\n#include <SkyX.h>\n\n#include \"MemoryLeakCheck.h\"\n\nstruct EC_SkyXImpl\n{\n EC_SkyXImpl() : skyX(0), sunlight(0), cloudLayer(0) {}\n ~EC_SkyXImpl()\n {\n if (skyX)\n {\n skyX->remove();\n if (sunlight)\n skyX->getSceneManager()->destroyLight(sunlight);\n }\n\n sunlight = 0;\n SAFE_DELETE(skyX)\n }\n\n SkyX::SkyX *skyX;\n Ogre::Light *sunlight;\n SkyX::CloudLayer *cloudLayer; \/\/\/< Currently just once cloud layer used.\n};\n\nEC_SkyX::EC_SkyX(Scene* scene) :\n IComponent(scene),\n volumetricClouds(this, \"Volumetric clouds\", false),\n timeMultiplier(this, \"Time multiplier\", 0.0f),\n time(this, \"Time\", float3(14.f, 7.5f, 20.5f)),\n weather(this, \"Weather (volumetric clouds only)\", float2(1.f, 1.f)),\n\/\/ windSpeed(this, \"Wind speed\", 0.0f),\n windDirection(this, \"Wind direction\", 0.0f),\n impl(0)\n{\n OgreWorldPtr w = scene->GetWorld<OgreWorld>();\n if (!w)\n {\n LogError(\"EC_SkyX: no OgreWorld available. Cannot be created.\");\n return;\n }\n\n connect(w.get(), SIGNAL(ActiveCameraChanged(EC_Camera *)), SLOT(OnActiveCameraChanged(EC_Camera*)));\n connect(this, SIGNAL(ParentEntitySet()), SLOT(Create()));\n}\n\nEC_SkyX::~EC_SkyX()\n{\n if (ParentScene() && ParentScene()->GetWorld<OgreWorld>())\n delete impl;\n}\n\nfloat3 EC_SkyX::SunPosition() const\n{\n if (impl->skyX)\n return impl->skyX->getAtmosphereManager()->getSunPosition();\n return float3();\n}\n\nvoid EC_SkyX::CreateSunlight()\n{\n if (impl)\n {\n OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>();\n Ogre::SceneManager *sm = w->GetSceneManager();\n impl->sunlight = sm->createLight(w->GetRenderer()->GetUniqueObjectName(\"SkyXSunlight\"));\n impl->sunlight->setType(Ogre::Light::LT_DIRECTIONAL);\n impl->sunlight->setDiffuseColour(1.f, 1.f, 1.f);\n impl->sunlight->setSpecularColour(0.f,0.f,0.f);\n impl->sunlight->setDirection(-1.f, -1.f, -1.f);\n impl->sunlight->setCastShadows(true);\n\n sm->setAmbientLight(Ogre::ColourValue(1.f, 1.f, 1.f));\n }\n}\n\nvoid EC_SkyX::Create()\n{\n SAFE_DELETE(impl);\n\n try\n {\n if (!ParentScene())\n {\n LogError(\"EC_SkyX: no parent scene. Cannot be created.\");\n return;\n }\n\n OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>();\n assert(w);\n\n if (!w->GetRenderer() || !w->GetRenderer()->GetActiveCamera())\n return; \/\/ Can't create SkyX just yet, no main camera set.\n\n Ogre::SceneManager *sm = w->GetSceneManager();\n\n impl = new EC_SkyXImpl();\n\n \/\/ Create Sky\n impl->skyX = new SkyX::SkyX(sm, static_cast<EC_Camera *>(w->GetRenderer()->GetActiveCamera())->GetCamera());\n impl->skyX->create();\n\n \/\/ A little change to default atmosphere settings.\n SkyX::AtmosphereManager::Options atOpt = impl->skyX->getAtmosphereManager()->getOptions();\n atOpt.RayleighMultiplier = 0.0045f;\n impl->skyX->getAtmosphereManager()->setOptions(atOpt);\n\n UpdateAttribute(&volumetricClouds);\n UpdateAttribute(&timeMultiplier);\n UpdateAttribute(&time);\n\n connect(framework->Frame(), SIGNAL(PostFrameUpdate(float)), SLOT(Update(float)), Qt::UniqueConnection);\n connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(UpdateAttribute(IAttribute*)), Qt::UniqueConnection);\n }\n catch(Ogre::Exception &e)\n {\n \/\/ Currently if we try to create more than one SkyX component we end up here due to Ogre internal name collision.\n LogError(\"Could not create EC_SkyX: \" + std::string(e.what()));\n }\n}\n\nvoid EC_SkyX::OnActiveCameraChanged(EC_Camera *newActiveCamera)\n{\n \/\/ If we haven't yet initialized, do a full init.\n if (!impl)\n Create();\n else \/\/ Otherwise, update the camera to an existing initialized SkyX instance.\n if (impl && impl->skyX)\n impl->skyX->setCamera(newActiveCamera->GetCamera());\n}\n\nvoid EC_SkyX::UpdateAttribute(IAttribute *attr)\n{\n if (!impl->skyX)\n return;\n\n if (attr == &volumetricClouds)\n {\n if (volumetricClouds.Get())\n {\n impl->skyX->getCloudsManager()->removeAll();\n impl->skyX->getVCloudsManager()->create();\n }\n else\n {\n impl->skyX->getVCloudsManager()->remove();\n impl->skyX->getCloudsManager()->removeAll();\n impl->cloudLayer = impl->skyX->getCloudsManager()->add(SkyX::CloudLayer::Options());\n }\n }\n else if (attr == &timeMultiplier)\n {\n impl->skyX->setTimeMultiplier((Ogre::Real)timeMultiplier.Get());\n }\n else if (attr == &time)\n {\n SkyX::AtmosphereManager::Options atOpt = impl->skyX->getAtmosphereManager()->getOptions();\n atOpt.Time = time.Get();\n impl->skyX->getAtmosphereManager()->setOptions(atOpt);\n }\n else if (attr == &weather)\n {\n if (volumetricClouds.Get())\n {\n \/\/Negative value for humidity causes crash within SkyX, so clamp value to min 0.\n float humidity = (weather.Get().x >= 0) ? weather.Get().x : 0.f;\n impl->skyX->getVCloudsManager()->getVClouds()->setWheater(humidity, weather.Get().y, 2);\n }\n }\n\/*\n else if (attr == &windSpeed)\n {\n if (volumetricClouds.Get())\n impl->skyX->getVCloudsManager()->setWindSpeed(0.f);\n else\n ;\n }\n*\/\n else if (attr == &windDirection)\n {\n if (volumetricClouds.Get())\n {\n impl->skyX->getVCloudsManager()->getVClouds()->setWindDirection(Ogre::Radian(DegToRad(windDirection.Get())));\n }\n else\n {\n SkyX::CloudLayer::Options options = impl->cloudLayer->getOptions();\n Ogre::Radian r1(Ogre::Degree(windDirection.Get())), r2(Ogre::Degree(windDirection.Get()));\n options.WindDirection = Ogre::Vector2(Ogre::Math::Cos(r1), Ogre::Math::Sin(r2));\n impl->skyX->getCloudsManager()->removeAll();\n impl->skyX->getCloudsManager()->add(options);\n }\n }\n}\n\nvoid EC_SkyX::Update(float frameTime)\n{\n if (impl && impl->skyX)\n {\n if (impl->sunlight)\n impl->sunlight->setDirection(impl->skyX->getAtmosphereManager()->getSunDirection());\n impl->skyX->update(frameTime);\n \/\/ Do not trigger AttributeChanged for time as SkyX internals are authorative for it.\n settime(impl->skyX->getAtmosphereManager()->getOptions().Time);\n }\n}\n<commit_msg>Delete SkyX pimpl always in EC_SkyX dtor, not only if parent entity is available.<commit_after>\/**\n * For conditions of distribution and use, see copyright notice in license.txt\n *\n * @file EC_SkyX.cpp\n * @brief A sky component using SkyX, http:\/\/www.ogre3d.org\/tikiwiki\/SkyX\n *\/\n\n#define OGRE_INTEROP\n\n#include \"DebugOperatorNew.h\"\n\n#include \"EC_SkyX.h\"\n\n#include \"Scene.h\"\n#include \"Framework.h\"\n#include \"FrameAPI.h\"\n#include \"OgreWorld.h\"\n#include \"Renderer.h\"\n#include \"EC_Camera.h\"\n#include \"LoggingFunctions.h\"\n#include \"OgreConversionUtils.h\"\n\n#include <Ogre.h>\n\n#include <SkyX.h>\n\n#include \"MemoryLeakCheck.h\"\n\nstruct EC_SkyXImpl\n{\n EC_SkyXImpl() : skyX(0), sunlight(0), cloudLayer(0) {}\n ~EC_SkyXImpl()\n {\n if (skyX)\n {\n skyX->remove();\n if (sunlight && skyX->getSceneManager())\n skyX->getSceneManager()->destroyLight(sunlight);\n }\n\n sunlight = 0;\n SAFE_DELETE(skyX)\n }\n\n SkyX::SkyX *skyX;\n Ogre::Light *sunlight;\n SkyX::CloudLayer *cloudLayer; \/\/\/< Currently just one cloud layer used.\n};\n\nEC_SkyX::EC_SkyX(Scene* scene) :\n IComponent(scene),\n volumetricClouds(this, \"Volumetric clouds\", false),\n timeMultiplier(this, \"Time multiplier\", 0.0f),\n time(this, \"Time\", float3(14.f, 7.5f, 20.5f)),\n weather(this, \"Weather (volumetric clouds only)\", float2(1.f, 1.f)),\n\/\/ windSpeed(this, \"Wind speed\", 0.0f),\n windDirection(this, \"Wind direction\", 0.0f),\n impl(0)\n{\n OgreWorldPtr w = scene->GetWorld<OgreWorld>();\n if (!w)\n {\n LogError(\"EC_SkyX: no OgreWorld available. Cannot be created.\");\n return;\n }\n\n connect(w.get(), SIGNAL(ActiveCameraChanged(EC_Camera *)), SLOT(OnActiveCameraChanged(EC_Camera*)));\n connect(this, SIGNAL(ParentEntitySet()), SLOT(Create()));\n}\n\nEC_SkyX::~EC_SkyX()\n{\n SAFE_DELETE(impl);\n}\n\nfloat3 EC_SkyX::SunPosition() const\n{\n if (impl->skyX)\n return impl->skyX->getAtmosphereManager()->getSunPosition();\n return float3();\n}\n\nvoid EC_SkyX::CreateSunlight()\n{\n if (impl)\n {\n OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>();\n Ogre::SceneManager *sm = w->GetSceneManager();\n impl->sunlight = sm->createLight(w->GetRenderer()->GetUniqueObjectName(\"SkyXSunlight\"));\n impl->sunlight->setType(Ogre::Light::LT_DIRECTIONAL);\n impl->sunlight->setDiffuseColour(1.f, 1.f, 1.f);\n impl->sunlight->setSpecularColour(0.f,0.f,0.f);\n impl->sunlight->setDirection(-1.f, -1.f, -1.f);\n impl->sunlight->setCastShadows(true);\n\n sm->setAmbientLight(Ogre::ColourValue(1.f, 1.f, 1.f));\n }\n}\n\nvoid EC_SkyX::Create()\n{\n SAFE_DELETE(impl);\n\n try\n {\n if (!ParentScene())\n {\n LogError(\"EC_SkyX: no parent scene. Cannot be created.\");\n return;\n }\n\n OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>();\n assert(w);\n\n if (!w->GetRenderer() || !w->GetRenderer()->GetActiveCamera())\n return; \/\/ Can't create SkyX just yet, no main camera set.\n\n Ogre::SceneManager *sm = w->GetSceneManager();\n\n impl = new EC_SkyXImpl();\n\n \/\/ Create Sky\n impl->skyX = new SkyX::SkyX(sm, static_cast<EC_Camera *>(w->GetRenderer()->GetActiveCamera())->GetCamera());\n impl->skyX->create();\n\n \/\/ A little change to default atmosphere settings.\n SkyX::AtmosphereManager::Options atOpt = impl->skyX->getAtmosphereManager()->getOptions();\n atOpt.RayleighMultiplier = 0.0045f;\n impl->skyX->getAtmosphereManager()->setOptions(atOpt);\n\n UpdateAttribute(&volumetricClouds);\n UpdateAttribute(&timeMultiplier);\n UpdateAttribute(&time);\n\n connect(framework->Frame(), SIGNAL(PostFrameUpdate(float)), SLOT(Update(float)), Qt::UniqueConnection);\n connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(UpdateAttribute(IAttribute*)), Qt::UniqueConnection);\n }\n catch(Ogre::Exception &e)\n {\n \/\/ Currently if we try to create more than one SkyX component we end up here due to Ogre internal name collision.\n LogError(\"Could not create EC_SkyX: \" + std::string(e.what()));\n }\n}\n\nvoid EC_SkyX::OnActiveCameraChanged(EC_Camera *newActiveCamera)\n{\n \/\/ If we haven't yet initialized, do a full init.\n if (!impl)\n Create();\n else \/\/ Otherwise, update the camera to an existing initialized SkyX instance.\n if (impl && impl->skyX)\n impl->skyX->setCamera(newActiveCamera->GetCamera());\n}\n\nvoid EC_SkyX::UpdateAttribute(IAttribute *attr)\n{\n if (!impl->skyX)\n return;\n\n if (attr == &volumetricClouds)\n {\n if (volumetricClouds.Get())\n {\n impl->skyX->getCloudsManager()->removeAll();\n impl->skyX->getVCloudsManager()->create();\n }\n else\n {\n impl->skyX->getVCloudsManager()->remove();\n impl->skyX->getCloudsManager()->removeAll();\n impl->cloudLayer = impl->skyX->getCloudsManager()->add(SkyX::CloudLayer::Options());\n }\n }\n else if (attr == &timeMultiplier)\n {\n impl->skyX->setTimeMultiplier((Ogre::Real)timeMultiplier.Get());\n }\n else if (attr == &time)\n {\n SkyX::AtmosphereManager::Options atOpt = impl->skyX->getAtmosphereManager()->getOptions();\n atOpt.Time = time.Get();\n impl->skyX->getAtmosphereManager()->setOptions(atOpt);\n }\n else if (attr == &weather)\n {\n if (volumetricClouds.Get())\n {\n \/\/Negative value for humidity causes crash within SkyX, so clamp value to min 0.\n float humidity = (weather.Get().x >= 0) ? weather.Get().x : 0.f;\n impl->skyX->getVCloudsManager()->getVClouds()->setWheater(humidity, weather.Get().y, 2);\n }\n }\n\/*\n else if (attr == &windSpeed)\n {\n if (volumetricClouds.Get())\n impl->skyX->getVCloudsManager()->setWindSpeed(0.f);\n else\n ;\n }\n*\/\n else if (attr == &windDirection)\n {\n if (volumetricClouds.Get())\n {\n impl->skyX->getVCloudsManager()->getVClouds()->setWindDirection(Ogre::Radian(DegToRad(windDirection.Get())));\n }\n else\n {\n SkyX::CloudLayer::Options options = impl->cloudLayer->getOptions();\n Ogre::Radian r1(Ogre::Degree(windDirection.Get())), r2(Ogre::Degree(windDirection.Get()));\n options.WindDirection = Ogre::Vector2(Ogre::Math::Cos(r1), Ogre::Math::Sin(r2));\n impl->skyX->getCloudsManager()->removeAll();\n impl->skyX->getCloudsManager()->add(options);\n }\n }\n}\n\nvoid EC_SkyX::Update(float frameTime)\n{\n if (impl && impl->skyX)\n {\n if (impl->sunlight)\n impl->sunlight->setDirection(impl->skyX->getAtmosphereManager()->getSunDirection());\n impl->skyX->update(frameTime);\n \/\/ Do not trigger AttributeChanged for time as SkyX internals are authorative for it.\n settime(impl->skyX->getAtmosphereManager()->getOptions().Time);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright NumFOCUS\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 * https:\/\/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#include \"itkWin32Header.h\"\n\n#include <fstream>\n\n#include \"itkImageToNeighborhoodSampleAdaptor.h\"\n#include \"itkSubsample.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkZeroFluxNeumannBoundaryCondition.h\"\n\n#include \"itkUniformRandomSpatialNeighborSubsampler.h\"\n#include \"itkTestingMacros.h\"\n\nint\nitkUniformRandomSpatialNeighborSubsamplerTest(int argc, char * argv[])\n{\n if (argc < 2)\n {\n std::cerr << \"Missing Parameters.\" << std::endl;\n std::cerr << \"Usage: \" << itkNameOfTestExecutableMacro(argv) << \" useClockForSeed [outFileName]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n constexpr unsigned int Dimension = 2;\n\n using FloatImage = itk::Image<float, Dimension>;\n using RegionType = FloatImage::RegionType;\n using IndexType = FloatImage::IndexType;\n using SizeType = FloatImage::SizeType;\n using BoundaryCondition = itk::ZeroFluxNeumannBoundaryCondition<FloatImage>;\n using AdaptorType = itk::Statistics::ImageToNeighborhoodSampleAdaptor<FloatImage, BoundaryCondition>;\n using SamplerType = itk::Statistics::UniformRandomSpatialNeighborSubsampler<AdaptorType, RegionType>;\n using WriterType = itk::ImageFileWriter<FloatImage>;\n\n auto inImage = FloatImage::New();\n SizeType sz;\n sz.Fill(35);\n IndexType idx;\n idx.Fill(0);\n RegionType region;\n region.SetSize(sz);\n region.SetIndex(idx);\n\n inImage->SetRegions(region);\n inImage->Allocate(true); \/\/ initialize buffer to zero\n\n auto sample = AdaptorType::New();\n sample->SetImage(inImage);\n\n auto samplerOrig = SamplerType::New();\n\n ITK_EXERCISE_BASIC_OBJECT_METHODS(samplerOrig, UniformRandomSpatialNeighborSubsampler, SpatialNeighborSubsampler);\n\n samplerOrig->SetSample(sample);\n samplerOrig->SetSampleRegion(region);\n samplerOrig->SetRadius(20);\n samplerOrig->SetNumberOfResultsRequested(50);\n samplerOrig->SetSeed(100);\n samplerOrig->CanSelectQueryOff();\n\n\n auto useClockForSeed = static_cast<bool>(std::stoi(argv[1]));\n ITK_TEST_SET_GET_BOOLEAN(samplerOrig, UseClockForSeed, useClockForSeed);\n\n \/\/ Test clone mechanism\n SamplerType::Pointer sampler = samplerOrig->Clone().GetPointer();\n\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetSample(), sampler->GetSample());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetSampleRegion(), sampler->GetSampleRegion());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetRadius(), sampler->GetRadius());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetNumberOfResultsRequested(), sampler->GetNumberOfResultsRequested());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetSeed(), sampler->GetSeed());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetCanSelectQuery(), sampler->GetCanSelectQuery());\n\n SamplerType::SubsamplePointer subsample = SamplerType::SubsampleType::New();\n sampler->Search(612, subsample);\n\n for (SamplerType::SubsampleConstIterator sIt = subsample->Begin(); sIt != subsample->End(); ++sIt)\n {\n IndexType index;\n index = sIt.GetMeasurementVector()[0].GetIndex();\n inImage->SetPixel(index, 255);\n }\n\n\n if (argc > 2)\n {\n const std::string outFileName(argv[2]);\n\n auto writer = WriterType::New();\n writer->SetFileName(outFileName);\n writer->SetInput(inImage);\n\n ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update());\n }\n\n std::cout << \"Test finished.\" << std::endl;\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: Increase `itk::UniformRandomSpatialNeighborSubsampler` coverage<commit_after>\/*=========================================================================\n *\n * Copyright NumFOCUS\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 * https:\/\/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#include \"itkWin32Header.h\"\n\n#include <fstream>\n\n#include \"itkImageToNeighborhoodSampleAdaptor.h\"\n#include \"itkSubsample.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkZeroFluxNeumannBoundaryCondition.h\"\n\n#include \"itkUniformRandomSpatialNeighborSubsampler.h\"\n#include \"itkTestingMacros.h\"\n\nint\nitkUniformRandomSpatialNeighborSubsamplerTest(int argc, char * argv[])\n{\n if (argc < 2)\n {\n std::cerr << \"Missing Parameters.\" << std::endl;\n std::cerr << \"Usage: \" << itkNameOfTestExecutableMacro(argv) << \" useClockForSeed [outFileName]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n constexpr unsigned int Dimension = 2;\n\n using FloatImage = itk::Image<float, Dimension>;\n using RegionType = FloatImage::RegionType;\n using IndexType = FloatImage::IndexType;\n using SizeType = FloatImage::SizeType;\n using BoundaryCondition = itk::ZeroFluxNeumannBoundaryCondition<FloatImage>;\n using AdaptorType = itk::Statistics::ImageToNeighborhoodSampleAdaptor<FloatImage, BoundaryCondition>;\n using SamplerType = itk::Statistics::UniformRandomSpatialNeighborSubsampler<AdaptorType, RegionType>;\n using WriterType = itk::ImageFileWriter<FloatImage>;\n\n auto inImage = FloatImage::New();\n typename SizeType::value_type regionSizeVal = 35;\n SizeType sz;\n sz.Fill(regionSizeVal);\n IndexType idx;\n idx.Fill(0);\n RegionType region;\n region.SetSize(sz);\n region.SetIndex(idx);\n\n inImage->SetRegions(region);\n inImage->Allocate(true); \/\/ initialize buffer to zero\n\n auto sample = AdaptorType::New();\n sample->SetImage(inImage);\n\n auto samplerOrig = SamplerType::New();\n\n ITK_EXERCISE_BASIC_OBJECT_METHODS(samplerOrig, UniformRandomSpatialNeighborSubsampler, SpatialNeighborSubsampler);\n\n\n SamplerType::InstanceIdentifier query(612);\n SamplerType::SubsamplePointer subsample = SamplerType::SubsampleType::New();\n\n \/\/ Test exceptions\n ITK_TRY_EXPECT_EXCEPTION(samplerOrig->Search(query, subsample));\n\n samplerOrig->SetRadius(20);\n\n ITK_TRY_EXPECT_EXCEPTION(samplerOrig->Search(query, subsample));\n\n samplerOrig->SetSampleRegion(region);\n\n samplerOrig->SetSample(sample);\n\n \/\/ Expect a warning about the index being outside the given image region and an empty result\n query = std::pow(regionSizeVal, Dimension);\n samplerOrig->Search(query, subsample);\n\n typename SamplerType::SubsampleType::TotalAbsoluteFrequencyType expectedTotalFrequency = 0;\n ITK_TEST_EXPECT_EQUAL(expectedTotalFrequency, subsample->GetTotalFrequency());\n size_t expectedIdHolderSize = 0;\n ITK_TEST_EXPECT_EQUAL(expectedIdHolderSize, subsample->GetIdHolder().size());\n\n samplerOrig->CanSelectQueryOn();\n query = std::pow(regionSizeVal, Dimension) - 1;\n samplerOrig->Search(query, subsample);\n\n expectedTotalFrequency = 441;\n ITK_TEST_EXPECT_EQUAL(expectedTotalFrequency, subsample->GetTotalFrequency());\n expectedIdHolderSize = 441;\n ITK_TEST_EXPECT_EQUAL(expectedIdHolderSize, subsample->GetIdHolder().size());\n\n samplerOrig->SetNumberOfResultsRequested(50);\n samplerOrig->SetSeed(100);\n samplerOrig->CanSelectQueryOff();\n\n auto useClockForSeed = static_cast<bool>(std::stoi(argv[1]));\n ITK_TEST_SET_GET_BOOLEAN(samplerOrig, UseClockForSeed, useClockForSeed);\n\n \/\/ Test clone mechanism\n SamplerType::Pointer sampler = samplerOrig->Clone().GetPointer();\n\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetSample(), sampler->GetSample());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetSampleRegion(), sampler->GetSampleRegion());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetRadius(), sampler->GetRadius());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetNumberOfResultsRequested(), sampler->GetNumberOfResultsRequested());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetSeed(), sampler->GetSeed());\n ITK_TEST_SET_GET_VALUE(samplerOrig->GetCanSelectQuery(), sampler->GetCanSelectQuery());\n\n query = 612;\n sampler->Search(query, subsample);\n\n for (SamplerType::SubsampleConstIterator sIt = subsample->Begin(); sIt != subsample->End(); ++sIt)\n {\n IndexType index;\n index = sIt.GetMeasurementVector()[0].GetIndex();\n inImage->SetPixel(index, 255);\n }\n\n\n if (argc > 2)\n {\n const std::string outFileName(argv[2]);\n\n auto writer = WriterType::New();\n writer->SetFileName(outFileName);\n writer->SetInput(inImage);\n\n ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update());\n }\n\n std::cout << \"Test finished.\" << std::endl;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ ---------------------------------------------------\n\/\/ The FDiffDelete Project\n\/\/ Github: https:\/\/github.com\/shishir993\/fdiffdelete\n\/\/ Author: Shishir Bhat\n\/\/ The MIT License (MIT)\n\/\/ Copyright (c) 2014\n\/\/\n\n#include \"HashFactory.h\"\n#include <WinCrypt.h>\n\n#define MBYTES (1024 * 1024)\n\nstatic HRESULT _HashFileOneShot(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ DWORD cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash);\nstatic HRESULT _HashFilePieceMeal(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ INT64 cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash);\n\n\nHRESULT HashFactoryInit(_Out_ HCRYPTPROV *phCrypt)\n{\n HRESULT hr = S_OK;\n\n *phCrypt = NULL;\n\n HCRYPTPROV hCrypt = NULL;\n if (CryptAcquireContext(\n &hCrypt,\/\/ handle out\n NULL, \/\/ container\n NULL, \/\/ provider\n PROV_DSS, \/\/ provider type\n CRYPT_VERIFYCONTEXT)) \/\/ flags\n {\n *phCrypt = hCrypt;\n }\n else\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptAcquireContext() failed.\");\n }\n return hr;\n}\n\nvoid HashFactoryDestroy(_In_ HCRYPTPROV hCrypt)\n{\n SB_ASSERT(hCrypt != NULL);\n CryptReleaseContext(hCrypt, 0);\n}\n\nHRESULT CalculateSHA1(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)\n{\n SB_ASSERT(hCrypt != NULL);\n\n HRESULT hr = S_OK;\n LARGE_INTEGER fileSize = {};\n\n if (!GetFileSizeEx(hFile, &fileSize))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"GetFileSizeEx failed, hr: %x\", hr);\n goto fend;\n }\n \n if ((200 * MBYTES) <= fileSize.QuadPart)\n {\n hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);\n logerr(L\"File too big\");\n goto fend;\n }\n\n hr = _HashFileOneShot(hCrypt, hFile, fileSize.LowPart, pbHash);\n\n#ifdef _DEBUG\n CHAR szHash[STRLEN_SHA1];\n HashValueToString(pbHash, szHash);\n logdbg(L\"Hash string = [%S]\", szHash);\n#endif\n\nfend:\n return hr;\n}\n\nvoid HashValueToString(_In_bytecount_c_(HASHLEN_SHA1) PBYTE pbHash, _Inout_z_ PSTR pszHashValue)\n{\n for (int i = 0; i < HASHLEN_SHA1; ++i)\n {\n sprintf_s(pszHashValue + (i << 1), STRLEN_SHA1 - (i << 1), \"%02x\", pbHash[i]);\n }\n pszHashValue[STRLEN_SHA1 - 1] = 0;\n}\n\nHRESULT _HashFileOneShot(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ DWORD cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)\n{\n HRESULT hr = S_OK;\n HCRYPTHASH hHash = NULL;\n HANDLE hMapObj = NULL;\n HANDLE hMapView = NULL;\n DWORD dwHashSize = HASHLEN_SHA1;\n\n hr = CHL_GnCreateMemMapOfFile(hFile, PAGE_READONLY, &hMapObj, &hMapView);\n if (FAILED(hr))\n {\n logerr(L\"Failed to mem-map file, hr: %x\", hr);\n goto fend;\n }\n\n if (!CryptCreateHash(hCrypt, CALG_SHA1, NULL, 0, &hHash))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptCreateHash() failed\");\n goto fend;\n }\n\n if (!CryptHashData(hHash, (PBYTE)hMapView, cbFile, 0))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptHashData failed, hr: %x\", hr);\n goto fend;\n }\n\n if (!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &dwHashSize, 0))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptGetHashParam failed, hr: %x\", hr);\n goto fend;\n }\n\nfend:\n if (hHash != NULL)\n {\n CryptDestroyHash(hHash);\n hHash = NULL;\n }\n\n if (hMapView != NULL)\n {\n UnmapViewOfFile(hMapView);\n hMapView = NULL;\n }\n\n if (hMapObj != NULL)\n {\n CloseHandle(hMapObj);\n hMapObj = NULL;\n }\n\n return hr;\n}\n\nHRESULT _HashFilePieceMeal(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ INT64 cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)\n{\n return E_NOTIMPL;\n}\n<commit_msg>Fix #25 Enable hashing of large files<commit_after>\n\/\/ ---------------------------------------------------\n\/\/ The FDiffDelete Project\n\/\/ Github: https:\/\/github.com\/shishir993\/fdiffdelete\n\/\/ Author: Shishir Bhat\n\/\/ The MIT License (MIT)\n\/\/ Copyright (c) 2014\n\/\/\n\n#include \"HashFactory.h\"\n#include <WinCrypt.h>\n\n#define MBYTES (1024 * 1024)\n\nstatic HRESULT _HashFileOneShot(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ DWORD cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash);\nstatic HRESULT _HashFilePieceMeal(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ UINT64 cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash);\n\n\nHRESULT HashFactoryInit(_Out_ HCRYPTPROV *phCrypt)\n{\n HRESULT hr = S_OK;\n\n *phCrypt = NULL;\n\n HCRYPTPROV hCrypt = NULL;\n if (CryptAcquireContext(\n &hCrypt,\/\/ handle out\n NULL, \/\/ container\n NULL, \/\/ provider\n PROV_DSS, \/\/ provider type\n CRYPT_VERIFYCONTEXT)) \/\/ flags\n {\n *phCrypt = hCrypt;\n }\n else\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptAcquireContext() failed.\");\n }\n return hr;\n}\n\nvoid HashFactoryDestroy(_In_ HCRYPTPROV hCrypt)\n{\n SB_ASSERT(hCrypt != NULL);\n CryptReleaseContext(hCrypt, 0);\n}\n\nHRESULT CalculateSHA1(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)\n{\n SB_ASSERT(hCrypt != NULL);\n\n HRESULT hr = S_OK;\n LARGE_INTEGER fileSize = {};\n\n if (!GetFileSizeEx(hFile, &fileSize))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"GetFileSizeEx failed, hr: %x\", hr);\n goto fend;\n }\n \n if ((200 * MBYTES) <= fileSize.QuadPart)\n {\n hr = _HashFilePieceMeal(hCrypt, hFile, fileSize.QuadPart, pbHash);\n }\n else\n {\n hr = _HashFileOneShot(hCrypt, hFile, fileSize.LowPart, pbHash);\n }\n\n if (SUCCEEDED(hr))\n {\n#ifdef _DEBUG\n CHAR szHash[STRLEN_SHA1];\n HashValueToString(pbHash, szHash);\n logdbg(L\"Hash string = [%S]\", szHash);\n#endif\n }\n\nfend:\n return hr;\n}\n\nvoid HashValueToString(_In_bytecount_c_(HASHLEN_SHA1) PBYTE pbHash, _Inout_z_ PSTR pszHashValue)\n{\n for (int i = 0; i < HASHLEN_SHA1; ++i)\n {\n sprintf_s(pszHashValue + (i << 1), STRLEN_SHA1 - (i << 1), \"%02x\", pbHash[i]);\n }\n pszHashValue[STRLEN_SHA1 - 1] = 0;\n}\n\nHRESULT _HashFileOneShot(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ DWORD cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)\n{\n HRESULT hr = S_OK;\n HCRYPTHASH hHash = NULL;\n HANDLE hMapObj = NULL;\n HANDLE hMapView = NULL;\n DWORD dwHashSize = HASHLEN_SHA1;\n\n hr = CHL_GnCreateMemMapOfFile(hFile, PAGE_READONLY, &hMapObj, &hMapView);\n if (FAILED(hr))\n {\n logerr(L\"Failed to mem-map file, hr: %x\", hr);\n goto fend;\n }\n\n if (!CryptCreateHash(hCrypt, CALG_SHA1, NULL, 0, &hHash))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptCreateHash() failed\");\n goto fend;\n }\n\n if (!CryptHashData(hHash, (PBYTE)hMapView, cbFile, 0))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptHashData failed, hr: %x\", hr);\n goto fend;\n }\n\n if (!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &dwHashSize, 0))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptGetHashParam failed, hr: %x\", hr);\n goto fend;\n }\n\nfend:\n if (hHash != NULL)\n {\n CryptDestroyHash(hHash);\n hHash = NULL;\n }\n\n if (hMapView != NULL)\n {\n UnmapViewOfFile(hMapView);\n hMapView = NULL;\n }\n\n if (hMapObj != NULL)\n {\n CloseHandle(hMapObj);\n hMapObj = NULL;\n }\n\n return hr;\n}\n\nHRESULT _HashFilePieceMeal(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ UINT64 cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)\n{\n HRESULT hr = S_OK;\n void* pBuffer = NULL;\n UINT64 cbRemaining = cbFile;\n const DWORD cbBuf = 16 * MBYTES;\n\n HCRYPTHASH hHash = NULL;\n DWORD dwHashSize = HASHLEN_SHA1;\n\n hr = CHL_MmAlloc(&pBuffer, cbBuf, NULL);\n if (FAILED(hr))\n {\n goto fend;\n }\n\n if (!CryptCreateHash(hCrypt, CALG_SHA1, NULL, 0, &hHash))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptCreateHash() failed\");\n goto fend;\n }\n\n while (0 < cbRemaining)\n {\n DWORD cbRead = 0;\n DWORD cbToRead = (DWORD)(min(cbRemaining, cbBuf));\n if (!ReadFile(hFile, pBuffer, cbToRead, &cbRead, NULL))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"ReadFile failed, hr: %x\", hr);\n goto fend;\n }\n\n if (cbRead != cbToRead)\n {\n hr = E_UNEXPECTED;\n goto fend;\n }\n\n cbRemaining -= cbRead;\n\n if (!CryptHashData(hHash, (LPCBYTE)pBuffer, cbRead, 0))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptHashData failed, hr: %x\", hr);\n goto fend;\n }\n }\n\n if (!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &dwHashSize, 0))\n {\n hr = HRESULT_FROM_WIN32(GetLastError());\n logerr(L\"CryptGetHashParam failed, hr: %x\", hr);\n goto fend;\n }\n\nfend:\n if (hHash != NULL)\n {\n CryptDestroyHash(hHash);\n hHash = NULL;\n }\n CHL_MmFree(&pBuffer);\n return hr;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Model.h\"\n\n#include <iostream>\n\nModel_Data :: Model_Data (GLuint vao,\n GLuint vertexPosId,\n GLuint uvCoordsId,\n size_t vertexCount)\n: vao (vao )\n, vertexPosId (vertexPosId)\n, uvCoordsId (uvCoordsId)\n, vertexCount (vertexCount)\n{ }\n\nModel :: Model(const Model_Data& data)\n: m_glData (data)\n{ }\n\nvoid Model::addData (const Model_Data& data)\n{\n deleteData ();\n m_glData = data;\n}\n\nvoid Model::bind () const\n{\n glBindVertexArray (m_glData.vao);\n}\n\nvoid Model::unbind () const\n{\n glBindVertexArray (0);\n}\n\n\nGLuint Model :: getVertexCount() const\n{\n return m_glData.vertexCount;\n}\n\nModel :: ~Model ()\n{\n deleteData ();\n}\n\nvoid Model :: deleteData ()\n{\n glDeleteVertexArrays (1, &m_glData.vao);\n\n glDeleteBuffers (1, &m_glData.vertexPosId);\n glDeleteBuffers (1, &m_glData.uvCoordsId);\n}\n<commit_msg>Reformat model class source<commit_after>#include \"Model.h\"\n\n#include <iostream>\n\nModel_Data::Model_Data (GLuint vao,\n GLuint vertexPosId,\n GLuint uvCoordsId,\n size_t vertexCount)\n: vao (vao )\n, vertexPosId (vertexPosId)\n, uvCoordsId (uvCoordsId)\n, vertexCount (vertexCount)\n{ }\n\nModel::Model(const Model_Data& data)\n: m_glData (data)\n{ }\n\nvoid Model::addData (const Model_Data& data)\n{\n deleteData ();\n m_glData = data;\n}\n\nvoid Model::bind () const\n{\n glBindVertexArray (m_glData.vao);\n}\n\nvoid Model::unbind () const\n{\n glBindVertexArray (0);\n}\n\n\nGLuint Model::getVertexCount() const\n{\n return m_glData.vertexCount;\n}\n\nModel::~Model ()\n{\n deleteData ();\n}\n\nvoid Model::deleteData ()\n{\n glDeleteVertexArrays (1, &m_glData.vao);\n\n glDeleteBuffers (1, &m_glData.vertexPosId);\n glDeleteBuffers (1, &m_glData.uvCoordsId);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Guard.cpp\n\/\/ Created by Matt Kaufmann on 02\/06\/14.\n\/\/\n\n#include \"ExampleGame\/Components\/GameScripts\/UnitCustomizers\/Definitions.h\"\n#include \"ExampleGame\/Components\/GameScripts\/Units\/Guard.h\"\n#include \"ExampleGame\/Components\/Grid\/GameGrid.h\"\n#include \"ExampleGame\/Components\/Grid\/GridManager.h\"\n#include \"ExampleGame\/GameSingletons\/GameSingletons.h\"\n#include \"ExampleGame\/Messages\/Declarations.h\"\n#include \"Libraries\/glm\/gtx\/vector_angle.hpp\"\n#include \"Vajra\/Engine\/Components\/DerivedComponents\/Transform\/Transform.h\"\n#include \"Vajra\/Engine\/Core\/Engine.h\"\n#include \"Vajra\/Engine\/MessageHub\/MessageHub.h\"\n#include \"Vajra\/Engine\/SceneGraph\/SceneGraph3D.h\"\n#include \"Vajra\/Engine\/Timer\/Timer.h\"\n#include \"Vajra\/Utilities\/MathUtilities.h\"\n\n\/\/ Wait time to return to idle after losing sight of players\n#define GUARD_COOLDOWN_TIME 1.0f\n\/\/ Wait time for guards to attack\n#define GUARD_ATTACK_TIME 1.0f\n\/\/ Range within which guards will attack players\n#define ATTACK_RANGE 2.5f\n\/\/ Angle at which the guard's attack can hit the player\n#define ATTACK_ANGLE (15.0f inRadians)\n\/\/ Guards can't be harmed if attacked from the front\n#define INVINCIBLE_ANGLE (50.0f inRadians)\n\nGuard::Guard() : EnemyUnit() {\n\tthis->init();\n}\n\nGuard::Guard(Object* object_) : EnemyUnit(object_) {\n\tthis->init();\n}\n\nGuard::~Guard() {\n\tthis->destroy();\n}\n\nvoid Guard::init() {\n\tthis->numPlayerUnitsSpotted = 0;\n\tthis->cooldownTimer = GUARD_COOLDOWN_TIME;\n\tthis->attackTimer = GUARD_ATTACK_TIME;\n\tthis->targetId = OBJECT_ID_INVALID;\n\tthis->weaponObjId = OBJECT_ID_INVALID;\n\tthis->shieldObjId = OBJECT_ID_INVALID;\n\n\tthis->addSubscriptionToMessageType(MESSAGE_TYPE_ANIMATION_ENDED_EVENT, this->GetTypeId(), true);\n\tthis->addSubscriptionToMessageType(MESSAGE_TYPE_SCENE_START, this->GetTypeId(), true);\n}\n\nvoid Guard::destroy() {\n\n}\n\nvoid Guard::HandleMessage(MessageChunk messageChunk) {\n\tEnemyUnit::HandleMessage(messageChunk);\n\n\tswitch (messageChunk->GetMessageType()) {\n\t\tcase MESSAGE_TYPE_ANIMATION_ENDED_EVENT:\n\t\t\tthis->onAnimationEnded(messageChunk->messageData.s);\n\t\t\tbreak;\n\t}\n}\n\nvoid Guard::SwitchActionState(UnitActionState newState) {\n\tif(newState != this->GetUnitActionState()) {\n\t\tUnitActionState oldState = this->GetUnitActionState();\n\t\tMessageChunk messageChunk = ENGINE->GetMessageHub()->GetOneFreeMessage();\n\t\tmessageChunk->SetMessageType(MESSAGE_TYPE_UNIT_ACTION_STATE_CHANGED);\n\t\tmessageChunk->messageData.iv1.x = oldState;\n\t\tmessageChunk->messageData.iv1.y = newState;\n\t\tif (this->weaponObjId != OBJECT_ID_INVALID) {\n\t\t\tENGINE->GetMessageHub()->SendPointcastMessage(messageChunk, this->weaponObjId, this->GetObject()->GetId());\n\t\t}\n\t\tif (this->shieldObjId != OBJECT_ID_INVALID) {\n\t\t\tENGINE->GetMessageHub()->SendPointcastMessage(messageChunk, this->shieldObjId, this->GetObject()->GetId());\n\t\t}\n\t}\n\n\tBaseUnit::SwitchActionState(newState);\n}\n\nbool Guard::CanBeKilledBy(ObjectIdType id, glm::vec3 \/*source*\/) {\n\tGameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);\n\tif (gObj != nullptr) {\n\t\tBaseUnit* unit = gObj->GetComponent<BaseUnit>();\n\t\tif (unit != nullptr) {\n\t\t\tif ((unit->GetUnitType() >= FIRST_PLAYER_UNIT_TYPE) && (unit->GetUnitType() <= LAST_PLAYER_UNIT_TYPE)) {\n\t\t\t\t\/\/ Guards can only be killed if they are unaware.\n\t\t\t\tauto iter = std::find(this->knownPlayers.begin(), this->knownPlayers.end(), id);\n\t\t\t\treturn (iter == this->knownPlayers.end());\n\t\t\t\t\/*\n\t\t\t\t\/\/ Guards are invincible from the front, so check the angle of the attack.\n\t\t\t\tglm::vec3 dir = source - this->gameObjectRef->GetTransform()->GetPositionWorld();\n\t\t\t\tglm::vec3 forward = QuaternionForwardVector(this->gameObjectRef->GetTransform()->GetOrientationWorld());\n\t\t\t\t\/\/ Don't use glm's vector angle function because it never returns an angle greater than PI\/2\n\t\t\t\tfloat angle = acos(glm::clamp(glm::dot(dir, forward), -1.0f, 1.0f));\n\t\t\t\tif (angle >= INVINCIBLE_ANGLE) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t*\/\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid Guard::start() {\n\tstd::list<ObjectIdType> childIds = this->gameObjectRef->GetChildren();\n\tfor (ObjectIdType childId : childIds) {\n\t\tGameObject* childObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(childId);\n\t\tif (childObj != nullptr) {\n\t\t\tif (childObj->HasTag(\"Weapon\")) {\n\t\t\t\tthis->weaponObjId = childId;\n\t\t\t}\n\t\t\tif (childObj->HasTag(\"Shield\")) {\n\t\t\t\tthis->shieldObjId = childId;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Guard::determineBrainState() {\n\tif (this->brainState == ENEMY_BRAIN_CALM) {\n\t\tif (this->knownPlayers.size() > 0) {\n\t\t\tthis->setBrainState(ENEMY_BRAIN_CAUTIOUS);\n\t\t}\n\t}\n\telse if (this->brainState == ENEMY_BRAIN_CAUTIOUS) {\n\t\tif (this->cooldownTimer <= 0.0f) {\n\t\t\tthis->setBrainState(ENEMY_BRAIN_CALM);\n\t\t}\n\t}\n}\n\nvoid Guard::onBrainBecameCalm() {\n\tEnemyUnit::onBrainBecameCalm();\n\tthis->SwitchActionState(UNIT_ACTION_STATE_IDLE);\n}\n\nvoid Guard::onBrainBecameCautious() {\n\tEnemyUnit::onBrainBecameCautious();\n\tthis->attackTimer = GUARD_ATTACK_TIME;\n\tthis->cooldownTimer = GUARD_COOLDOWN_TIME;\n\tthis->SwitchActionState(UNIT_ACTION_STATE_PRE_BLOCK);\n\tthis->gridNavRef->HaltMovement();\n}\n\nvoid Guard::onBrainBecameAggressive() {\n\tEnemyUnit::onBrainBecameAggressive();\n\tthis->SwitchActionState(UNIT_ACTION_STATE_DOING_SPECIAL);\n}\n\nvoid Guard::cautiousUpdate() {\n\tfloat dt = ENGINE->GetTimer()->GetDeltaFrameTime();\n\n\tthis->attackTimer -= dt;\n\n\tif (this->knownPlayers.size() > 0) {\n\t\tthis->cooldownTimer = GUARD_COOLDOWN_TIME;\n\t}\n\telse {\n\t\tthis->targetId = OBJECT_ID_INVALID;\n\t\tthis->cooldownTimer -= dt;\n\t\tif (this->cooldownTimer <= 0.0f) {\n\t\t\tthis->setBrainState(ENEMY_BRAIN_CALM);\n\t\t}\n\t}\n\n\tglm::vec3 myLocation = this->GetObject()->GetComponent<Transform>()->GetPositionWorld();\n\tfloat minDistance = 100.0f;\n\tGameObject* targetObj = nullptr;\n\tfor (auto iter = this->knownPlayers.begin(); iter != this->knownPlayers.end(); ++iter) {\n\t\tGameObject* playerObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(*iter);\n\t\tglm::vec3 unitLocation = playerObj->GetTransform()->GetPositionWorld();\n\t\tfloat distance = glm::distance(myLocation, unitLocation);\n\t\tif (distance < minDistance) {\n\t\t\tthis->targetId = *iter;\n\t\t\ttargetObj = playerObj;\n\t\t\tminDistance = distance;\n\t\t}\n\t}\n\n\tif (targetObj != nullptr) {\n\t\t\/\/ Turn to face towards the target\n\t\tthis->gridNavRef->SetLookTarget(targetObj->GetTransform()->GetPositionWorld());\n\n\t\t\/\/ Attack the target if it's in range or it's doing a special.\n\t\tBaseUnit* targetUnit = targetObj->GetComponent<BaseUnit>();\n\t\tif (((minDistance <= ATTACK_RANGE) && (this->GetUnitActionState() == UNIT_ACTION_STATE_BLOCK_IDLE))\n\t\t\t\t|| (targetUnit->GetUnitActionState() == UNIT_ACTION_STATE_DOING_SPECIAL)) {\n\t\t\tthis->setBrainState(ENEMY_BRAIN_AGGRESSIVE);\n\t\t}\n\t}\n}\n\nvoid Guard::aggressiveUpdate() {\n\t\/\/ Keep turning towards the target\n\tGameObject* targetObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(this->targetId);\n\tif (targetObj != nullptr) {\n\t\tthis->gridNavRef->SetLookTarget(targetObj->GetTransform()->GetPositionWorld());\n\t}\n}\n\nvoid Guard::onSightedPlayerUnit(ObjectIdType id) {\n\tthis->numPlayerUnitsSpotted++;\n\tthis->knownPlayers.push_back(id);\n\n\tif ((this->brainState == ENEMY_BRAIN_CALM) && (this->numPlayerUnitsSpotted > 0)) {\n\t\tthis->setBrainState(ENEMY_BRAIN_CAUTIOUS);\n\t}\n}\n\nvoid Guard::onLostSightOfPlayerUnit(ObjectIdType id) {\n\tthis->numPlayerUnitsSpotted--;\n\tthis->knownPlayers.remove(id);\n}\n\nvoid Guard::onAnimationEnded(std::string animName) {\n\tif (animName == UNIT_ANIMATION_CLIP_NAME_block) {\n\t\tthis->SwitchActionState(UNIT_ACTION_STATE_BLOCK_IDLE);\n\t}\n\telse if (animName == UNIT_ANIMATION_CLIP_NAME_doingspecial) {\n\t\tthis->SwitchActionState(UNIT_ACTION_STATE_POST_SPECIAL);\n\t\tthis->performAttack();\n\t}\n\telse if (animName == UNIT_ANIMATION_CLIP_NAME_postspecial) {\n\t\tthis->setBrainState(ENEMY_BRAIN_CAUTIOUS);\n\t}\n}\n\nvoid Guard::performAttack() {\n\tGameObject* targetObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(this->targetId);\n\tif (targetObj != nullptr) {\n\t\t\/\/ Verify that the target is within reach\n\t\tglm::vec3 myPosition = this->gameObjectRef->GetTransform()->GetPositionWorld();\n\t\tglm::vec3 targetPosition = targetObj->GetTransform()->GetPositionWorld();\n\t\tfloat dist = glm::distance(targetPosition, myPosition);\n\t\tglm::vec3 forward = QuaternionForwardVector(this->gameObjectRef->GetTransform()->GetOrientationWorld());\n\t\t\/\/ Don't use glm's vector angle function because it never returns an angle greater than PI\/2\n\t\tfloat angle = acos(glm::clamp(glm::dot(forward, targetPosition - myPosition), -1.0f, 1.0f));\n\t\tif ((dist <= ATTACK_RANGE) && (angle <= ATTACK_ANGLE)) {\n\t\t\tGridCell* cell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(targetPosition);\n\t\t\tif (cell != nullptr) {\n\t\t\t\tint elevation = SINGLETONS->GetGridManager()->GetGrid()->GetElevationFromWorldY(myPosition.y);\n\n\t\t\t\t\/\/ Attack the intended target\n\t\t\t\tMessageChunk attackMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();\n\t\t\t\tattackMessage->SetMessageType(MESSAGE_TYPE_UNIT_SPECIAL_HIT);\n\t\t\t\tattackMessage->messageData.iv1.x = cell->x;\n\t\t\t\tattackMessage->messageData.iv1.y = elevation;\n\t\t\t\tattackMessage->messageData.iv1.z = cell->z;\n\t\t\t\tattackMessage->messageData.fv1 = this->gameObjectRef->GetTransform()->GetPositionWorld();\n\t\t\t\tENGINE->GetMessageHub()->SendMulticastMessage(attackMessage, this->GetObject()->GetId());\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Added a hook to Guard for an attack sound<commit_after>\/\/\n\/\/ Guard.cpp\n\/\/ Created by Matt Kaufmann on 02\/06\/14.\n\/\/\n\n#include \"ExampleGame\/Components\/GameScripts\/UnitCustomizers\/Definitions.h\"\n#include \"ExampleGame\/Components\/GameScripts\/Units\/Guard.h\"\n#include \"ExampleGame\/Components\/Grid\/GameGrid.h\"\n#include \"ExampleGame\/Components\/Grid\/GridManager.h\"\n#include \"ExampleGame\/GameSingletons\/GameSingletons.h\"\n#include \"ExampleGame\/Messages\/Declarations.h\"\n#include \"Libraries\/glm\/gtx\/vector_angle.hpp\"\n#include \"Vajra\/Engine\/Components\/DerivedComponents\/Audio\/AudioSource.h\"\n#include \"Vajra\/Engine\/Components\/DerivedComponents\/Transform\/Transform.h\"\n#include \"Vajra\/Engine\/Core\/Engine.h\"\n#include \"Vajra\/Engine\/MessageHub\/MessageHub.h\"\n#include \"Vajra\/Engine\/SceneGraph\/SceneGraph3D.h\"\n#include \"Vajra\/Engine\/Timer\/Timer.h\"\n#include \"Vajra\/Utilities\/MathUtilities.h\"\n\n\/\/ Wait time to return to idle after losing sight of players\n#define GUARD_COOLDOWN_TIME 1.0f\n\/\/ Wait time for guards to attack\n#define GUARD_ATTACK_TIME 1.0f\n\/\/ Range within which guards will attack players\n#define ATTACK_RANGE 2.5f\n\/\/ Angle at which the guard's attack can hit the player\n#define ATTACK_ANGLE (15.0f inRadians)\n\/\/ Guards can't be harmed if attacked from the front\n#define INVINCIBLE_ANGLE (50.0f inRadians)\n\nGuard::Guard() : EnemyUnit() {\n\tthis->init();\n}\n\nGuard::Guard(Object* object_) : EnemyUnit(object_) {\n\tthis->init();\n}\n\nGuard::~Guard() {\n\tthis->destroy();\n}\n\nvoid Guard::init() {\n\tthis->numPlayerUnitsSpotted = 0;\n\tthis->cooldownTimer = GUARD_COOLDOWN_TIME;\n\tthis->attackTimer = GUARD_ATTACK_TIME;\n\tthis->targetId = OBJECT_ID_INVALID;\n\tthis->weaponObjId = OBJECT_ID_INVALID;\n\tthis->shieldObjId = OBJECT_ID_INVALID;\n\n\tthis->addSubscriptionToMessageType(MESSAGE_TYPE_ANIMATION_ENDED_EVENT, this->GetTypeId(), true);\n\tthis->addSubscriptionToMessageType(MESSAGE_TYPE_SCENE_START, this->GetTypeId(), true);\n}\n\nvoid Guard::destroy() {\n\n}\n\nvoid Guard::HandleMessage(MessageChunk messageChunk) {\n\tEnemyUnit::HandleMessage(messageChunk);\n\n\tswitch (messageChunk->GetMessageType()) {\n\t\tcase MESSAGE_TYPE_ANIMATION_ENDED_EVENT:\n\t\t\tthis->onAnimationEnded(messageChunk->messageData.s);\n\t\t\tbreak;\n\t}\n}\n\nvoid Guard::SwitchActionState(UnitActionState newState) {\n\tif(newState != this->GetUnitActionState()) {\n\t\tUnitActionState oldState = this->GetUnitActionState();\n\t\tMessageChunk messageChunk = ENGINE->GetMessageHub()->GetOneFreeMessage();\n\t\tmessageChunk->SetMessageType(MESSAGE_TYPE_UNIT_ACTION_STATE_CHANGED);\n\t\tmessageChunk->messageData.iv1.x = oldState;\n\t\tmessageChunk->messageData.iv1.y = newState;\n\t\tif (this->weaponObjId != OBJECT_ID_INVALID) {\n\t\t\tENGINE->GetMessageHub()->SendPointcastMessage(messageChunk, this->weaponObjId, this->GetObject()->GetId());\n\t\t}\n\t\tif (this->shieldObjId != OBJECT_ID_INVALID) {\n\t\t\tENGINE->GetMessageHub()->SendPointcastMessage(messageChunk, this->shieldObjId, this->GetObject()->GetId());\n\t\t}\n\t}\n\n\tBaseUnit::SwitchActionState(newState);\n}\n\nbool Guard::CanBeKilledBy(ObjectIdType id, glm::vec3 \/*source*\/) {\n\tGameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);\n\tif (gObj != nullptr) {\n\t\tBaseUnit* unit = gObj->GetComponent<BaseUnit>();\n\t\tif (unit != nullptr) {\n\t\t\tif ((unit->GetUnitType() >= FIRST_PLAYER_UNIT_TYPE) && (unit->GetUnitType() <= LAST_PLAYER_UNIT_TYPE)) {\n\t\t\t\t\/\/ Guards can only be killed if they are unaware.\n\t\t\t\tauto iter = std::find(this->knownPlayers.begin(), this->knownPlayers.end(), id);\n\t\t\t\treturn (iter == this->knownPlayers.end());\n\t\t\t\t\/*\n\t\t\t\t\/\/ Guards are invincible from the front, so check the angle of the attack.\n\t\t\t\tglm::vec3 dir = source - this->gameObjectRef->GetTransform()->GetPositionWorld();\n\t\t\t\tglm::vec3 forward = QuaternionForwardVector(this->gameObjectRef->GetTransform()->GetOrientationWorld());\n\t\t\t\t\/\/ Don't use glm's vector angle function because it never returns an angle greater than PI\/2\n\t\t\t\tfloat angle = acos(glm::clamp(glm::dot(dir, forward), -1.0f, 1.0f));\n\t\t\t\tif (angle >= INVINCIBLE_ANGLE) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t*\/\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid Guard::start() {\n\tstd::list<ObjectIdType> childIds = this->gameObjectRef->GetChildren();\n\tfor (ObjectIdType childId : childIds) {\n\t\tGameObject* childObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(childId);\n\t\tif (childObj != nullptr) {\n\t\t\tif (childObj->HasTag(\"Weapon\")) {\n\t\t\t\tthis->weaponObjId = childId;\n\t\t\t}\n\t\t\tif (childObj->HasTag(\"Shield\")) {\n\t\t\t\tthis->shieldObjId = childId;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Guard::determineBrainState() {\n\tif (this->brainState == ENEMY_BRAIN_CALM) {\n\t\tif (this->knownPlayers.size() > 0) {\n\t\t\tthis->setBrainState(ENEMY_BRAIN_CAUTIOUS);\n\t\t}\n\t}\n\telse if (this->brainState == ENEMY_BRAIN_CAUTIOUS) {\n\t\tif (this->cooldownTimer <= 0.0f) {\n\t\t\tthis->setBrainState(ENEMY_BRAIN_CALM);\n\t\t}\n\t}\n}\n\nvoid Guard::onBrainBecameCalm() {\n\tEnemyUnit::onBrainBecameCalm();\n\tthis->SwitchActionState(UNIT_ACTION_STATE_IDLE);\n}\n\nvoid Guard::onBrainBecameCautious() {\n\tEnemyUnit::onBrainBecameCautious();\n\tthis->attackTimer = GUARD_ATTACK_TIME;\n\tthis->cooldownTimer = GUARD_COOLDOWN_TIME;\n\tthis->SwitchActionState(UNIT_ACTION_STATE_PRE_BLOCK);\n\tthis->gridNavRef->HaltMovement();\n}\n\nvoid Guard::onBrainBecameAggressive() {\n\tEnemyUnit::onBrainBecameAggressive();\n\tthis->SwitchActionState(UNIT_ACTION_STATE_DOING_SPECIAL);\n}\n\nvoid Guard::cautiousUpdate() {\n\tfloat dt = ENGINE->GetTimer()->GetDeltaFrameTime();\n\n\tthis->attackTimer -= dt;\n\n\tif (this->knownPlayers.size() > 0) {\n\t\tthis->cooldownTimer = GUARD_COOLDOWN_TIME;\n\t}\n\telse {\n\t\tthis->targetId = OBJECT_ID_INVALID;\n\t\tthis->cooldownTimer -= dt;\n\t\tif (this->cooldownTimer <= 0.0f) {\n\t\t\tthis->setBrainState(ENEMY_BRAIN_CALM);\n\t\t}\n\t}\n\n\tglm::vec3 myLocation = this->GetObject()->GetComponent<Transform>()->GetPositionWorld();\n\tfloat minDistance = 100.0f;\n\tGameObject* targetObj = nullptr;\n\tfor (auto iter = this->knownPlayers.begin(); iter != this->knownPlayers.end(); ++iter) {\n\t\tGameObject* playerObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(*iter);\n\t\tglm::vec3 unitLocation = playerObj->GetTransform()->GetPositionWorld();\n\t\tfloat distance = glm::distance(myLocation, unitLocation);\n\t\tif (distance < minDistance) {\n\t\t\tthis->targetId = *iter;\n\t\t\ttargetObj = playerObj;\n\t\t\tminDistance = distance;\n\t\t}\n\t}\n\n\tif (targetObj != nullptr) {\n\t\t\/\/ Turn to face towards the target\n\t\tthis->gridNavRef->SetLookTarget(targetObj->GetTransform()->GetPositionWorld());\n\n\t\t\/\/ Attack the target if it's in range or it's doing a special.\n\t\tBaseUnit* targetUnit = targetObj->GetComponent<BaseUnit>();\n\t\tif (((minDistance <= ATTACK_RANGE) && (this->GetUnitActionState() == UNIT_ACTION_STATE_BLOCK_IDLE))\n\t\t\t\t|| (targetUnit->GetUnitActionState() == UNIT_ACTION_STATE_DOING_SPECIAL)) {\n\t\t\tthis->setBrainState(ENEMY_BRAIN_AGGRESSIVE);\n\t\t}\n\t}\n}\n\nvoid Guard::aggressiveUpdate() {\n\t\/\/ Keep turning towards the target\n\tGameObject* targetObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(this->targetId);\n\tif (targetObj != nullptr) {\n\t\tthis->gridNavRef->SetLookTarget(targetObj->GetTransform()->GetPositionWorld());\n\t}\n}\n\nvoid Guard::onSightedPlayerUnit(ObjectIdType id) {\n\tthis->numPlayerUnitsSpotted++;\n\tthis->knownPlayers.push_back(id);\n\n\tif ((this->brainState == ENEMY_BRAIN_CALM) && (this->numPlayerUnitsSpotted > 0)) {\n\t\tthis->setBrainState(ENEMY_BRAIN_CAUTIOUS);\n\t}\n}\n\nvoid Guard::onLostSightOfPlayerUnit(ObjectIdType id) {\n\tthis->numPlayerUnitsSpotted--;\n\tthis->knownPlayers.remove(id);\n}\n\nvoid Guard::onAnimationEnded(std::string animName) {\n\tif (animName == UNIT_ANIMATION_CLIP_NAME_block) {\n\t\tthis->SwitchActionState(UNIT_ACTION_STATE_BLOCK_IDLE);\n\t}\n\telse if (animName == UNIT_ANIMATION_CLIP_NAME_doingspecial) {\n\t\tthis->SwitchActionState(UNIT_ACTION_STATE_POST_SPECIAL);\n\t\tthis->performAttack();\n\t}\n\telse if (animName == UNIT_ANIMATION_CLIP_NAME_postspecial) {\n\t\tthis->setBrainState(ENEMY_BRAIN_CAUTIOUS);\n\t}\n}\n\nvoid Guard::performAttack() {\n\tGameObject* targetObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(this->targetId);\n\tif (targetObj != nullptr) {\n\t\t\/\/ Verify that the target is within reach\n\t\tglm::vec3 myPosition = this->gameObjectRef->GetTransform()->GetPositionWorld();\n\t\tglm::vec3 targetPosition = targetObj->GetTransform()->GetPositionWorld();\n\t\tfloat dist = glm::distance(targetPosition, myPosition);\n\t\tglm::vec3 forward = QuaternionForwardVector(this->gameObjectRef->GetTransform()->GetOrientationWorld());\n\t\t\/\/ Don't use glm's vector angle function because it never returns an angle greater than PI\/2\n\t\tfloat angle = acos(glm::clamp(glm::dot(forward, targetPosition - myPosition), -1.0f, 1.0f));\n\t\tif ((dist <= ATTACK_RANGE) && (angle <= ATTACK_ANGLE)) {\n\t\t\tGridCell* cell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(targetPosition);\n\t\t\tif (cell != nullptr) {\n\t\t\t\tint elevation = SINGLETONS->GetGridManager()->GetGrid()->GetElevationFromWorldY(myPosition.y);\n\n\t\t\t\t\/\/ Attack the intended target\n\t\t\t\tMessageChunk attackMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();\n\t\t\t\tattackMessage->SetMessageType(MESSAGE_TYPE_UNIT_SPECIAL_HIT);\n\t\t\t\tattackMessage->messageData.iv1.x = cell->x;\n\t\t\t\tattackMessage->messageData.iv1.y = elevation;\n\t\t\t\tattackMessage->messageData.iv1.z = cell->z;\n\t\t\t\tattackMessage->messageData.fv1 = this->gameObjectRef->GetTransform()->GetPositionWorld();\n\t\t\t\tENGINE->GetMessageHub()->SendMulticastMessage(attackMessage, this->GetObject()->GetId());\n\n\t\t\t\tAudioSource* audioSource = this->gameObjectRef->GetComponent<AudioSource>();\n\t\t\t\tif (audioSource != nullptr) {\n\t\t\t\t\taudioSource->Play(\"specialStart\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of fteproxy.\n\/\/\n\/\/ fteproxy 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 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ fteproxy 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 fteproxy. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <rank_unrank.h>\n\n#include \"re2\/re2.h\"\n#include \"re2\/regexp.h\"\n#include \"re2\/prog.h\"\n\n\n\/*\n * Please see rank_unrank.h for a detailed explantion of the\n * methods in this file and their purpose.\n *\/\n\n\n\/\/ Helper fuction. Given a string and a token, performs a python .split()\n\/\/ Returns a list of string delimnated on the token\narray_type_string_t1 tokenize( std::string line, char delim ) {\n array_type_string_t1 retval;\n\n std::istringstream iss(line);\n std::string fragment;\n while(std::getline(iss, fragment, delim))\n retval.push_back(fragment);\n\n return retval;\n}\n\n\/\/ Exceptions\nstatic class _invalid_fst_format: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Invalid FST format.\";\n }\n} invalid_fst_format;\n\nstatic class _invalid_fst_exception_state_name: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Invalid DFA format: DFA has N states, and a state that is not in the range 0,1,...,N-1.\";\n }\n} invalid_fst_exception_state_name;\n\nstatic class _invalid_fst_exception_symbol_name: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Invalid DFA format: DFA has symbol that is not in the range 0,1,...,255.\";\n }\n} invalid_fst_exception_symbol_name;\n\n\nstatic class _invalid_input_exception_not_in_final_states: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Please verify your input, the string does not result in an accepting path in the DFA.\";\n }\n} invalid_input_exception_not_in_final_states;\n\nstatic class _symbol_not_in_sigma: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Please verify your input, it contains a symbol not in the sigma of the DFA.\";\n }\n} symbol_not_in_sigma;\n\n\/*\n * Parameters:\n * dfa_str: a minimized ATT FST formatted DFA, see: http:\/\/www2.research.att.com\/~fsmtools\/fsm\/man4\/fsm.5.html\n * max_len: the maxium length to compute DFA::buildTable\n *\/\nDFA::DFA(const std::string dfa_str, const uint32_t max_len)\n : _fixed_slice(max_len),\n _start_state(0),\n _num_states(0),\n _num_symbols(0)\n{\n \/\/ construct the _start_state, _final_states and symbols\/states of our DFA\n bool startStateIsntSet = true;\n std::string line;\n std::istringstream my_str_stream(dfa_str);\n while ( getline (my_str_stream,line) )\n {\n if (line.empty()) break;\n\n array_type_string_t1 split_vec = tokenize( line, '\\t' );\n if (split_vec.size() == 4) {\n uint32_t current_state = strtol(split_vec.at(0).c_str(),NULL,10);\n uint32_t symbol = strtol(split_vec.at(2).c_str(),NULL,10);\n if (find(_states.begin(), _states.end(), current_state)==_states.end()) {\n _states.push_back( current_state );\n }\n\n if (find(_symbols.begin(), _symbols.end(), symbol)==_symbols.end()) {\n _symbols.push_back( symbol );\n }\n\n if ( startStateIsntSet ) {\n _start_state = current_state;\n startStateIsntSet = false;\n }\n } else if (split_vec.size()==1) {\n uint32_t final_state = strtol(split_vec.at(0).c_str(),NULL,10);\n if (find(_final_states.begin(), _final_states.end(), final_state)==_final_states.end()) {\n _final_states.push_back( final_state );\n }\n if (find(_states.begin(), _states.end(), final_state)==_states.end()) {\n _states.push_back( final_state );\n }\n } else {\n throw invalid_fst_format;\n }\n\n }\n _states.push_back( _states.size() ); \/\/ extra for the \"dead\" state\n\n _num_symbols = _symbols.size();\n _num_states = _states.size();\n\n \/\/ build up our sigma\/sigma_reverse tables which enable mappings between\n \/\/ bytes\/integers\n uint32_t j, k;\n for (j=0; j<_num_symbols; j++) {\n _sigma.insert( std::pair<uint32_t,char>( j, (char)(_symbols.at(j))) );\n _sigma_reverse.insert( std::pair<char,uint32_t>((char)(_symbols.at(j)), j) );\n }\n\n \/\/ intialize all transitions in our DFA to our dead state\n _delta.resize(_num_states);\n for (j=0; j<_num_states; j++) {\n _delta.at(j).resize(_num_symbols);\n for (k=0; k < _num_symbols; k++) {\n _delta.at(j).at(k) = _num_states - 1;\n }\n }\n\n \/\/ fill our our transition function delta\n std::istringstream my_str_stream2(dfa_str);\n while ( getline (my_str_stream2,line) )\n {\n array_type_string_t1 split_vec = tokenize( line, '\\t' );\n if (split_vec.size() == 4) {\n uint32_t current_state = strtol(split_vec.at(0).c_str(),NULL,10);\n uint32_t symbol = strtol(split_vec.at(2).c_str(),NULL,10);\n uint32_t new_state = strtol(split_vec.at(1).c_str(),NULL,10);\n\n symbol = _sigma_reverse.at(symbol);\n\n _delta.at(current_state).at(symbol) = new_state;\n }\n }\n\n _delta_dense.resize(_num_states);\n uint32_t q, a;\n for (q=0; q < _num_states; q++ ) {\n _delta_dense.at(q) = true;\n for (a=1; a < _num_symbols; a++) {\n if (_delta.at(q).at(a-1) != _delta.at(q).at(a)) {\n _delta_dense.at(q) = false;\n break;\n }\n }\n }\n\n DFA::_validate();\n\n \/\/ perform our precalculation to speed up (un)ranking\n DFA::_buildTable();\n}\n\n\nvoid DFA::_validate() {\n \/\/ ensure DFA has at least one state\n assert(_states.length()>0);\n\n \/\/ ensure DFA has at least one symbol\n assert(_sigma.length()>0);\n assert(_sigma_reverse.length()>0);\n\n \/\/ ensure we have N states, labeled 0,1,..N-1\n array_type_uint32_t1::iterator state;\n for (state=_states.begin(); state!=_states.end(); state++) {\n if (*state >= _states.size()) {\n throw invalid_fst_exception_state_name;\n }\n }\n\n \/\/ ensure all symbols are in the range 0,1,...,255\n for (uint32_t i = 0; i < _symbols.size(); i++) {\n if (_symbols.at(i) > 256 || _symbols.at(i) < 0) {\n throw invalid_fst_exception_symbol_name;\n }\n }\n}\n\nvoid DFA::_buildTable() {\n uint32_t i;\n uint32_t q;\n uint32_t a;\n\n \/\/ ensure our table _T is the correct size\n _T.resize(_num_states);\n for (q=0; q<_num_states; q++) {\n _T.at(q).resize(_fixed_slice+1);\n for (i=0; i<=_fixed_slice; i++) {\n _T.at(q).at(i) = 0;\n }\n }\n\n \/\/ set all _T.at(q).at(0) = 1 for all states in _final_states\n array_type_uint32_t1::iterator state;\n for (state=_final_states.begin(); state!=_final_states.end(); state++) {\n _T.at(*state).at(0) = 1;\n }\n\n \/\/ walk through our table _T\n \/\/ we want each entry _T.at(q).at(i) to contain the number of strings that start\n \/\/ from state q, terminate in a final state, and are of length i\n for (i=1; i<=_fixed_slice; i++) {\n for (q=0; q<_delta.size(); q++) {\n for (a=0; a<_delta.at(0).size(); a++) {\n uint32_t state = _delta.at(q).at(a);\n _T.at(q).at(i) += _T.at(state).at(i-1);\n }\n }\n }\n}\n\n\nstd::string DFA::unrank( const mpz_class c_in ) {\n std::string retval;\n\n \/\/ throw exception if input integer is not in range of pre-computed value\n mpz_class words_in_slice = getNumWordsInLanguage( _fixed_slice, _fixed_slice );\n assert( c_in < words_in_slice );\n\n \/\/ walk the DFA subtracting values from c until we have our n symbols\n mpz_class c = c_in;\n uint32_t n = _fixed_slice;\n uint32_t i, q = _start_state;\n uint32_t chars_left, char_cursor, state_cursor;\n uint32_t sigma_zero = _sigma.at(0);\n mpz_class char_index;\n for (i=1; i<=n; i++) {\n chars_left = n-i;\n if (_delta_dense.at(q)) {\n \/\/ our optimized version, when _delta[q][i] is equal to n for all symbols i\n q = _delta.at(q).at(0);\n if (_T.at(q).at(chars_left)!=0) {\n char_index = (c \/ _T.at(q).at(chars_left));\n char_cursor = char_index.get_ui();\n retval = retval + _sigma.at(char_cursor);\n c = c % _T.at(q).at(chars_left);\n } else {\n retval += sigma_zero;\n }\n } else {\n \/\/ traditional goldberg-sipser ranking\n char_cursor = 0;\n state_cursor = _delta.at(q).at(char_cursor);\n while (c >= _T.at(state_cursor).at(chars_left)) {\n c -= _T.at(state_cursor).at(chars_left);\n char_cursor += 1;\n state_cursor =_delta.at(q).at(char_cursor);\n }\n retval += _sigma.at(char_cursor);\n q = state_cursor;\n }\n }\n\n \/\/ bail if our last state q is not in _final_states\n if (find(_final_states.begin(),\n _final_states.end(), q)==_final_states.end()) {\n throw invalid_input_exception_not_in_final_states;\n }\n\n return retval;\n}\n\nmpz_class DFA::rank( const std::string X_in ) {\n mpz_class retval = 0;\n\n \/\/ verify len(X) == _fixe_slice\n assert(X_in.length()==_fixed_slice);\n\n \/\/ walk the DFA, adding values from _T to c\n uint32_t i;\n uint32_t j;\n uint32_t n = X_in.size();\n uint32_t symbol_as_int;\n uint32_t q = _start_state;\n uint32_t state;\n for (i=1; i<=n; i++) {\n try {\n symbol_as_int = _sigma_reverse.at(X_in.at(i-1));\n } catch (int e) {\n throw symbol_not_in_sigma;\n }\n\n if (_delta_dense.at(q)) {\n \/\/ our optimized version, when _delta[q][i] is equal to n for all symbols i\n state = _delta.at(q).at(0);\n retval += (_T.at(state).at(n-i) * symbol_as_int);\n } else {\n \/\/ traditional goldberg-sipser ranking\n for (j=1; j<=symbol_as_int; j++) {\n state = _delta.at(q).at(j-1);\n retval += _T.at(state).at(n-i);\n }\n }\n q = _delta.at(q).at(symbol_as_int);\n }\n\n \/\/ bail if our last state q is not in _final_states\n if (find(_final_states.begin(),\n _final_states.end(), q)==_final_states.end()) {\n throw invalid_input_exception_not_in_final_states;\n }\n\n return retval;\n}\n\nmpz_class DFA::getNumWordsInLanguage( const uint32_t min_word_length,\n const uint32_t max_word_length )\n{\n \/\/ verify min_word_length <= max_word_length <= _fixed_slice\n assert(0<=min_word_length);\n assert(min_word_length<=max_word_length);\n assert(max_word_length<=_fixed_slice);\n\n \/\/ count the number of words in the language of length\n \/\/ at least min_word_length and no greater than max_word_length\n mpz_class num_words = 0;\n for (uint32_t word_length = min_word_length;\n word_length <= max_word_length;\n word_length++) {\n num_words += _T.at(_start_state).at(word_length);\n }\n return num_words;\n}\n\nstd::string attFstFromRegex( const std::string regex )\n{\n std::string retval;\n\n \/\/ specify compile flags for re2\n re2::Regexp::ParseFlags re_flags;\n re_flags = re2::Regexp::ClassNL;\n re_flags = re_flags | re2::Regexp::OneLine;\n re_flags = re_flags | re2::Regexp::PerlClasses;\n re_flags = re_flags | re2::Regexp::PerlB;\n re_flags = re_flags | re2::Regexp::PerlX;\n re_flags = re_flags | re2::Regexp::Latin1;\n\n re2::RegexpStatus status;\n\n \/\/ compile regex to DFA\n re2::Regexp* re = NULL;\n re2::Prog* prog = NULL;\n\n try {\n RE2::Options opt;\n re2::Regexp* re = re2::Regexp::Parse( regex, re_flags, &status );\n re2::Prog* prog = re->CompileToProg( opt.max_mem() );\n retval = prog->PrintEntireDFA( re2::Prog::kFullMatch );\n } catch (int e) {\n \/\/ do nothing, we return the empty string\n }\n\n \/\/ cleanup\n if (prog!=NULL)\n delete prog;\n if (re!=NULL)\n re->Decref();\n\n return retval;\n}\n<commit_msg>Issue #24: Change asserts to if-then-exception<commit_after>\/\/ This file is part of fteproxy.\n\/\/\n\/\/ fteproxy 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 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ fteproxy 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 fteproxy. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <rank_unrank.h>\n\n#include \"re2\/re2.h\"\n#include \"re2\/regexp.h\"\n#include \"re2\/prog.h\"\n\n\n\/*\n * Please see rank_unrank.h for a detailed explantion of the\n * methods in this file and their purpose.\n *\/\n\n\n\/\/ Helper fuction. Given a string and a token, performs a python .split()\n\/\/ Returns a list of string delimnated on the token\narray_type_string_t1 tokenize( std::string line, char delim ) {\n array_type_string_t1 retval;\n\n std::istringstream iss(line);\n std::string fragment;\n while(std::getline(iss, fragment, delim))\n retval.push_back(fragment);\n\n return retval;\n}\n\n\/\/ Exceptions\nstatic class _invalid_rank_input: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Invalid rank input: ensure integer is within the correct range.\";\n }\n} invalid_rank_input;\n\nstatic class _invalid_unrank_input: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Invalid unrank input: ensure string is exactly fixed length sizee.\";\n }\n} invalid_unrank_input;\n\nstatic class _invalid_fst_format: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Invalid FST format.\";\n }\n} invalid_fst_format;\n\nstatic class _invalid_fst_exception_state_name: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Invalid DFA format: DFA has N states, and a state that is not in the range 0,1,...,N-1.\";\n }\n} invalid_fst_exception_state_name;\n\nstatic class _invalid_fst_exception_symbol_name: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Invalid DFA format: DFA has symbol that is not in the range 0,1,...,255.\";\n }\n} invalid_fst_exception_symbol_name;\n\n\nstatic class _invalid_input_exception_not_in_final_states: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Please verify your input, the string does not result in an accepting path in the DFA.\";\n }\n} invalid_input_exception_not_in_final_states;\n\nstatic class _symbol_not_in_sigma: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Please verify your input, it contains a symbol not in the sigma of the DFA.\";\n }\n} symbol_not_in_sigma;\n\n\/*\n * Parameters:\n * dfa_str: a minimized ATT FST formatted DFA, see: http:\/\/www2.research.att.com\/~fsmtools\/fsm\/man4\/fsm.5.html\n * max_len: the maxium length to compute DFA::buildTable\n *\/\nDFA::DFA(const std::string dfa_str, const uint32_t max_len)\n : _fixed_slice(max_len),\n _start_state(0),\n _num_states(0),\n _num_symbols(0)\n{\n \/\/ construct the _start_state, _final_states and symbols\/states of our DFA\n bool startStateIsntSet = true;\n std::string line;\n std::istringstream my_str_stream(dfa_str);\n while ( getline (my_str_stream,line) )\n {\n if (line.empty()) break;\n\n array_type_string_t1 split_vec = tokenize( line, '\\t' );\n if (split_vec.size() == 4) {\n uint32_t current_state = strtol(split_vec.at(0).c_str(),NULL,10);\n uint32_t symbol = strtol(split_vec.at(2).c_str(),NULL,10);\n if (find(_states.begin(), _states.end(), current_state)==_states.end()) {\n _states.push_back( current_state );\n }\n\n if (find(_symbols.begin(), _symbols.end(), symbol)==_symbols.end()) {\n _symbols.push_back( symbol );\n }\n\n if ( startStateIsntSet ) {\n _start_state = current_state;\n startStateIsntSet = false;\n }\n } else if (split_vec.size()==1) {\n uint32_t final_state = strtol(split_vec.at(0).c_str(),NULL,10);\n if (find(_final_states.begin(), _final_states.end(), final_state)==_final_states.end()) {\n _final_states.push_back( final_state );\n }\n if (find(_states.begin(), _states.end(), final_state)==_states.end()) {\n _states.push_back( final_state );\n }\n } else {\n throw invalid_fst_format;\n }\n\n }\n _states.push_back( _states.size() ); \/\/ extra for the \"dead\" state\n\n _num_symbols = _symbols.size();\n _num_states = _states.size();\n\n \/\/ build up our sigma\/sigma_reverse tables which enable mappings between\n \/\/ bytes\/integers\n uint32_t j, k;\n for (j=0; j<_num_symbols; j++) {\n _sigma.insert( std::pair<uint32_t,char>( j, (char)(_symbols.at(j))) );\n _sigma_reverse.insert( std::pair<char,uint32_t>((char)(_symbols.at(j)), j) );\n }\n\n \/\/ intialize all transitions in our DFA to our dead state\n _delta.resize(_num_states);\n for (j=0; j<_num_states; j++) {\n _delta.at(j).resize(_num_symbols);\n for (k=0; k < _num_symbols; k++) {\n _delta.at(j).at(k) = _num_states - 1;\n }\n }\n\n \/\/ fill our our transition function delta\n std::istringstream my_str_stream2(dfa_str);\n while ( getline (my_str_stream2,line) )\n {\n array_type_string_t1 split_vec = tokenize( line, '\\t' );\n if (split_vec.size() == 4) {\n uint32_t current_state = strtol(split_vec.at(0).c_str(),NULL,10);\n uint32_t symbol = strtol(split_vec.at(2).c_str(),NULL,10);\n uint32_t new_state = strtol(split_vec.at(1).c_str(),NULL,10);\n\n symbol = _sigma_reverse.at(symbol);\n\n _delta.at(current_state).at(symbol) = new_state;\n }\n }\n\n _delta_dense.resize(_num_states);\n uint32_t q, a;\n for (q=0; q < _num_states; q++ ) {\n _delta_dense.at(q) = true;\n for (a=1; a < _num_symbols; a++) {\n if (_delta.at(q).at(a-1) != _delta.at(q).at(a)) {\n _delta_dense.at(q) = false;\n break;\n }\n }\n }\n\n DFA::_validate();\n\n \/\/ perform our precalculation to speed up (un)ranking\n DFA::_buildTable();\n}\n\n\nvoid DFA::_validate() {\n \/\/ ensure DFA has at least one state\n if (_states.length()==0)\n throw invalid_fst_format;\n\n \/\/ ensure DFA has at least one symbol\n if (_sigma.length()==0)\n throw invalid_fst_format;\n if (_sigma_reverse.length()>0)\n throw invalid_fst_format;\n\n \/\/ ensure we have N states, labeled 0,1,..N-1\n array_type_uint32_t1::iterator state;\n for (state=_states.begin(); state!=_states.end(); state++) {\n if (*state >= _states.size()) {\n throw invalid_fst_exception_state_name;\n }\n }\n\n \/\/ ensure all symbols are in the range 0,1,...,255\n for (uint32_t i = 0; i < _symbols.size(); i++) {\n if (_symbols.at(i) > 256 || _symbols.at(i) < 0) {\n throw invalid_fst_exception_symbol_name;\n }\n }\n}\n\nvoid DFA::_buildTable() {\n uint32_t i;\n uint32_t q;\n uint32_t a;\n\n \/\/ ensure our table _T is the correct size\n _T.resize(_num_states);\n for (q=0; q<_num_states; q++) {\n _T.at(q).resize(_fixed_slice+1);\n for (i=0; i<=_fixed_slice; i++) {\n _T.at(q).at(i) = 0;\n }\n }\n\n \/\/ set all _T.at(q).at(0) = 1 for all states in _final_states\n array_type_uint32_t1::iterator state;\n for (state=_final_states.begin(); state!=_final_states.end(); state++) {\n _T.at(*state).at(0) = 1;\n }\n\n \/\/ walk through our table _T\n \/\/ we want each entry _T.at(q).at(i) to contain the number of strings that start\n \/\/ from state q, terminate in a final state, and are of length i\n for (i=1; i<=_fixed_slice; i++) {\n for (q=0; q<_delta.size(); q++) {\n for (a=0; a<_delta.at(0).size(); a++) {\n uint32_t state = _delta.at(q).at(a);\n _T.at(q).at(i) += _T.at(state).at(i-1);\n }\n }\n }\n}\n\n\nstd::string DFA::unrank( const mpz_class c_in ) {\n std::string retval;\n\n \/\/ throw exception if input integer is not in range of pre-computed value\n mpz_class words_in_slice = getNumWordsInLanguage( _fixed_slice, _fixed_slice );\n if ( c_in > words_in_slice )\n throw invalid_unrank_input;\n\n \/\/ walk the DFA subtracting values from c until we have our n symbols\n mpz_class c = c_in;\n uint32_t n = _fixed_slice;\n uint32_t i, q = _start_state;\n uint32_t chars_left, char_cursor, state_cursor;\n uint32_t sigma_zero = _sigma.at(0);\n mpz_class char_index;\n for (i=1; i<=n; i++) {\n chars_left = n-i;\n if (_delta_dense.at(q)) {\n \/\/ our optimized version, when _delta[q][i] is equal to n for all symbols i\n q = _delta.at(q).at(0);\n if (_T.at(q).at(chars_left)!=0) {\n char_index = (c \/ _T.at(q).at(chars_left));\n char_cursor = char_index.get_ui();\n retval = retval + _sigma.at(char_cursor);\n c = c % _T.at(q).at(chars_left);\n } else {\n retval += sigma_zero;\n }\n } else {\n \/\/ traditional goldberg-sipser ranking\n char_cursor = 0;\n state_cursor = _delta.at(q).at(char_cursor);\n while (c >= _T.at(state_cursor).at(chars_left)) {\n c -= _T.at(state_cursor).at(chars_left);\n char_cursor += 1;\n state_cursor =_delta.at(q).at(char_cursor);\n }\n retval += _sigma.at(char_cursor);\n q = state_cursor;\n }\n }\n\n \/\/ bail if our last state q is not in _final_states\n if (find(_final_states.begin(),\n _final_states.end(), q)==_final_states.end()) {\n throw invalid_input_exception_not_in_final_states;\n }\n\n return retval;\n}\n\nmpz_class DFA::rank( const std::string X_in ) {\n mpz_class retval = 0;\n\n \/\/ verify len(X) == _fixe_slice\n if (X_in.length()!=_fixed_slice);\n throw invalid_rank_input;\n\n \/\/ walk the DFA, adding values from _T to c\n uint32_t i;\n uint32_t j;\n uint32_t n = X_in.size();\n uint32_t symbol_as_int;\n uint32_t q = _start_state;\n uint32_t state;\n for (i=1; i<=n; i++) {\n try {\n symbol_as_int = _sigma_reverse.at(X_in.at(i-1));\n } catch (int e) {\n throw symbol_not_in_sigma;\n }\n\n if (_delta_dense.at(q)) {\n \/\/ our optimized version, when _delta[q][i] is equal to n for all symbols i\n state = _delta.at(q).at(0);\n retval += (_T.at(state).at(n-i) * symbol_as_int);\n } else {\n \/\/ traditional goldberg-sipser ranking\n for (j=1; j<=symbol_as_int; j++) {\n state = _delta.at(q).at(j-1);\n retval += _T.at(state).at(n-i);\n }\n }\n q = _delta.at(q).at(symbol_as_int);\n }\n\n \/\/ bail if our last state q is not in _final_states\n if (find(_final_states.begin(),\n _final_states.end(), q)==_final_states.end()) {\n throw invalid_input_exception_not_in_final_states;\n }\n\n return retval;\n}\n\nmpz_class DFA::getNumWordsInLanguage( const uint32_t min_word_length,\n const uint32_t max_word_length )\n{\n \/\/ verify min_word_length <= max_word_length <= _fixed_slice\n assert(0<=min_word_length);\n assert(min_word_length<=max_word_length);\n assert(max_word_length<=_fixed_slice);\n\n \/\/ count the number of words in the language of length\n \/\/ at least min_word_length and no greater than max_word_length\n mpz_class num_words = 0;\n for (uint32_t word_length = min_word_length;\n word_length <= max_word_length;\n word_length++) {\n num_words += _T.at(_start_state).at(word_length);\n }\n return num_words;\n}\n\nstd::string attFstFromRegex( const std::string regex )\n{\n std::string retval;\n\n \/\/ specify compile flags for re2\n re2::Regexp::ParseFlags re_flags;\n re_flags = re2::Regexp::ClassNL;\n re_flags = re_flags | re2::Regexp::OneLine;\n re_flags = re_flags | re2::Regexp::PerlClasses;\n re_flags = re_flags | re2::Regexp::PerlB;\n re_flags = re_flags | re2::Regexp::PerlX;\n re_flags = re_flags | re2::Regexp::Latin1;\n\n re2::RegexpStatus status;\n\n \/\/ compile regex to DFA\n re2::Regexp* re = NULL;\n re2::Prog* prog = NULL;\n\n try {\n RE2::Options opt;\n re2::Regexp* re = re2::Regexp::Parse( regex, re_flags, &status );\n re2::Prog* prog = re->CompileToProg( opt.max_mem() );\n retval = prog->PrintEntireDFA( re2::Prog::kFullMatch );\n } catch (int e) {\n \/\/ do nothing, we return the empty string\n }\n\n \/\/ cleanup\n if (prog!=NULL)\n delete prog;\n if (re!=NULL)\n re->Decref();\n\n return retval;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef BOOST_TEST_DYN_LINK\n#define BOOST_TEST_DYN_LINK\n#endif\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <stdlib.h>\n#include <time.h>\n\n#include <boost\/make_shared.hpp>\n\n#include \"..\/simulation\/world.hpp\"\n#include \"..\/simulation\/worldGenerator.hpp\"\n#include \"..\/simulation\/anthill.hpp\"\n#include \"..\/simulation\/ant.hpp\"\n\nnamespace WorldGeneratorTest\n{\n \nstruct Fixture \n{\n Fixture() { srand(time(NULL)); }\n World world;\n}; \n\nBOOST_FIXTURE_TEST_CASE(test_placeAnthill_shouldBeAnthill, Fixture)\n{\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Anthill>().size(), 0);\n AnthillParams params;\n params.quantity = 1; \n WorldGenerator::placeAnthill(&world, params);\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Anthill>().size(), 1);\n BOOST_CHECK_EQUAL(world.getEntityPtrs().size(), 1);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_placeAnts_shouldBeAnts, Fixture)\n{\n WorldGenerator::placeAnthill(&world); \n \n BOOST_CHECK_EQUAL(world.getSimulationObjects<Creature>().size(), 0); \n AntsParams params;\n params.quantity = 10;\n params.min_dist_from_anthill = 2;\n params.max_dist_from_anthill = 5;\n WorldGenerator::placeAnts(&world, params);\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Creature>().size(), 10);\n BOOST_CHECK_EQUAL(world.getEntityPtrs().size(), 11); \/\/ (+ anthill)\n}\n\nBOOST_FIXTURE_TEST_CASE(test_placeObstacles_shouldBeObstacles, Fixture)\n{\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Obstacle>().size(), 0); \n ObstaclesParams params;\n params.quantity = 5;\n WorldGenerator::placeObstacles(&world, params);\n BOOST_CHECK(world.getSimulationObjects<Obstacle>().size() > 0);\n BOOST_CHECK(world.getEntityPtrs().size() > 0);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_placeFoods_shouldBeFoods, Fixture)\n{\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Food>().size(), 0); \n FoodsParams params;\n params.quantity = 5;\n WorldGenerator::placeFoods(&world, params);\n BOOST_CHECK(world.getSimulationObjects<Food>().size() > 0);\n BOOST_CHECK(world.getEntityPtrs().size() > 0);\n}\n\n} \/\/ namespace WorldGeneratorTest<commit_msg>fixed world generator tests<commit_after>#ifndef BOOST_TEST_DYN_LINK\n#define BOOST_TEST_DYN_LINK\n#endif\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <stdlib.h>\n#include <time.h>\n\n#include <boost\/make_shared.hpp>\n\n#include \"..\/simulation\/world.hpp\"\n#include \"..\/simulation\/worldGenerator.hpp\"\n#include \"..\/simulation\/anthill.hpp\"\n#include \"..\/simulation\/ant.hpp\"\n\nnamespace WorldGeneratorTest\n{\n \nstruct Fixture \n{\n Fixture() { srand(time(NULL)); }\n World world;\n}; \n\nBOOST_FIXTURE_TEST_CASE(test_placeAnthill_shouldBeAnthill, Fixture)\n{\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Anthill>().size(), 0);\n AnthillParams params;\n params.quantity = 1; \n WorldGenerator::placeAnthill(&world, params);\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Anthill>().size(), 1);\n BOOST_CHECK_EQUAL(world.getEntityPtrs().size(), 1);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_placeAnts_shouldBeAnts, Fixture)\n{\n WorldGenerator::placeAnthill(&world); \n \n BOOST_CHECK_EQUAL(world.getSimulationObjects<Creature>().size(), 0); \n AntsParams params;\n params.quantity = 10;\n params.min_dist_from_anthill = 2;\n params.max_dist_from_anthill = 5;\n WorldGenerator::placeAnts(&world, params);\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Creature>().size(), 10);\n BOOST_CHECK_EQUAL(world.getEntityPtrs().size(), 11); \/\/ (+ anthill)\n}\n\nBOOST_FIXTURE_TEST_CASE(test_placeObstacles_shouldBeObstacles, Fixture)\n{\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Obstacle>().size(), 0); \n ObstaclesParams params;\n params.quantity_per_100_by_100 = 5;\n WorldGenerator::placeObstacles(&world, params);\n BOOST_CHECK(world.getSimulationObjects<Obstacle>().size() > 0);\n BOOST_CHECK(world.getEntityPtrs().size() > 0);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_placeFoods_shouldBeFoods, Fixture)\n{\n BOOST_CHECK_EQUAL(world.getSimulationObjects<Food>().size(), 0); \n FoodsParams params;\n params.quantity_per_100_by_100 = 5;\n WorldGenerator::placeFoods(&world, params);\n BOOST_CHECK(world.getSimulationObjects<Food>().size() > 0);\n BOOST_CHECK(world.getEntityPtrs().size() > 0);\n}\n\n} \/\/ namespace WorldGeneratorTest<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n#include <sstream>\r\n#include <cstdlib>\r\n#include <cctype>\r\n\r\n#include \"dictionary.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid lower(string& s);\r\nstring stripPunct(const string& s);\r\nvoid checkSpelling(ifstream& in, Dictionary& dict);\r\n\r\n\r\nint main(int argc, char* argv[]) \r\n{\r\n\t\/\/ Output usage message if improper command line args were given.\r\n\tif (argc != 3)\r\n {\r\n\t\tcerr << \"Usage: \" << argv[0] << \" wordlist_filename input_file\\n\";\r\n\t\treturn EXIT_FAILURE;\r\n\t}\r\n\r\n\tifstream inf(argv[2]);\r\n\tif (! inf) \r\n {\r\n\t\tcerr << \"Could not open \" << argv[2] << \"\\n\";\r\n\t\treturn EXIT_FAILURE;\r\n\t}\r\n\r\n\t\/\/ Read dictionary, but let user know what we are working on.\r\n\tcout << \"Loading dictionary, this may take awhile...\\n\";\r\n\r\n\tDictionary d(argv[1]);\r\n\r\n\tcheckSpelling(inf, d);\r\n\r\n\tinf.close();\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n\r\nvoid checkSpelling(ifstream& in, Dictionary& dict) \r\n{\r\n\tint line_number = 0;\r\n\r\n\twhile (in) \r\n {\r\n\t\t++line_number;\r\n\r\n\t\tstring line;\r\n\t\tgetline(in, line);\r\n\r\n \t stringstream ss (stringstream::in | stringstream::out);\r\n\t\tss << line;\r\n\r\n\t\tstring word;\r\n\t\twhile (ss >> word)\r\n {\r\n\t\t\t\/\/ If the word does not exits\r\n\t\t\t\/\/ So, it is misspelled\r\n\t\t\tif (!dict.search(word))\r\n\t\t\t{\r\n\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid lower(string& s) \r\n{\r\n \/\/ Ensures that a word is lowercase\r\n\tfor (int i = 0; i < s.length(); ++i) \r\n {\r\n\t\ts[i] = tolower(s[i]);\r\n\t}\r\n}\r\n\r\nstring stripPunct(const string& s) \r\n{\r\n\t\/\/ Remove any single trailing\r\n\t\/\/ punctuation character from a word. \r\n\tif (ispunct(s[s.length() - 1])) \r\n\t\treturn s.substr (0, s.length() - 1);\r\n\t\r\n return s;\r\n}\r\n<commit_msg>Completed Spellchecking assignment<commit_after>\/**\r\n * @author Nikita Marinosyan\r\n * @date 26.04.2017\r\n * Higher School of Economics,\r\n * Faculty of Computer Science\r\n *\/\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n#include <sstream>\r\n#include <cstdlib>\r\n#include <cctype>\r\n#include <algorithm>\r\n\r\n#include \"dictionary.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid lower(string& s);\r\nstring stripPunct(const string& s);\r\nvoid checkSpelling(ifstream& in, Dictionary& dict);\r\n\r\nstring swapWithNext(string misspelled, size_t i);\r\nstring eraseCharacter(string misspelled, size_t i);\r\nstring replaceCharacter(string misspelled, size_t toBeReplaced, char replacing);\r\nstring insertCharacter(string misspelled, size_t placeToInsertBefore, char toBeInserted);\r\n\r\nvoid suggestTransposing(string misspelled, Dictionary& dict, HashSet<string, hash_function, equality>& suggestions);\r\nvoid suggestRemoval(string misspelled, Dictionary& dict, HashSet<string, hash_function, equality>& suggestions);\r\nvoid suggestReplacement(string misspelled, Dictionary& dict, HashSet<string, hash_function, equality>& suggestions);\r\nvoid suggestInserting(string misspelled, Dictionary& dict, HashSet<string, hash_function, equality>& suggestions);\r\n\r\n\r\nint main(int argc, char* argv[]) \r\n{\r\n\t\/\/ Output usage message if improper command line args were given.\r\n\tif (argc != 3)\r\n {\r\n\t\tcerr << \"Usage: \" << argv[0] << \" wordlist_filename input_file\\n\";\r\n\t\treturn EXIT_FAILURE;\r\n\t}\r\n\r\n\tifstream inf(argv[2]);\r\n\tif (! inf) \r\n {\r\n\t\tcerr << \"Could not open \" << argv[2] << \"\\n\";\r\n\t\treturn EXIT_FAILURE;\r\n\t}\r\n\r\n\t\/\/ Read dictionary, but let user know what we are working on.\r\n\tcout << \"Loading dictionary, this may take awhile...\\n\";\r\n\r\n\tDictionary d(argv[1]);\r\n\r\n\tcheckSpelling(inf, d);\r\n\r\n\tinf.close();\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n\r\nvoid checkSpelling(ifstream& in, Dictionary& dict) \r\n{\r\n\tint line_number = 0;\r\n\twhile (in) \r\n {\r\n\t\t++line_number;\r\n\r\n\t\tstring line;\r\n\t\tgetline(in, line);\r\n\r\n \t stringstream ss (stringstream::in | stringstream::out);\r\n\t\tss << line;\r\n\r\n\t\tstring word;\r\n\t\twhile (ss >> word)\r\n {\r\n\t\t\t\/\/ Ensure the word is\r\n\t\t\t\/\/ written in lowercase\r\n\t\t\tlower(word);\r\n\r\n\t\t\t\/\/ Ensure there is no\r\n\t\t\t\/\/ trailing punctuation character\r\n\t\t\tword = stripPunct(word);\r\n\r\n\t\t\t\/\/ If the word does not exits\r\n\t\t\t\/\/ So, it is misspelled\r\n\t\t\tif (!dict.search(word))\r\n\t\t\t{\r\n\t\t\t\t\/\/ Create hash set to control\r\n\t\t\t\t\/\/ the duplication of suggestions\r\n\t\t\t\tHashSet<string, hash_function, equality> suggestions;\r\n\r\n\t\t\t\t\/\/ Output the suggestions header\r\n\t\t\t\tcout << \"line \" << line_number << \": '\" << word << \"'\" << endl;\r\n\t\t\t\tcout << \" suggestions:\" << endl;\r\n\r\n\t\t\t\tsuggestTransposing(word, dict, suggestions);\r\n\t\t\t\tsuggestRemoval(word, dict, suggestions);\r\n\t\t\t\tsuggestReplacement(word, dict, suggestions);\r\n\t\t\t\tsuggestInserting(word, dict, suggestions);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\/*\r\n * Utility method to swap\r\n * adjacent characters\r\n *\/\r\nstring swapWithNext(string misspelled, size_t i)\r\n{\r\n\tswap(misspelled[i], misspelled[i + 1]);\r\n\treturn misspelled;\r\n}\r\n\r\n\/*\r\n * Method to find the suggestions\r\n * by transposing adjacent characters\r\n *\/\r\nvoid suggestTransposing(string misspelled, Dictionary& dict, HashSet<string, hash_function, equality>& suggestions)\r\n{\r\n\tfor (size_t i = 0; i < misspelled.length() - 1; ++i)\r\n\t{\r\n\t\tstring suggestion = swapWithNext(misspelled, i);\r\n\t\tif (dict.search(suggestion))\r\n\t\t{\r\n\t\t\t\/\/ Check if the word\r\n\t\t\t\/\/ was not suggested yet\r\n\t\t\tif (!suggestions.search(suggestion))\r\n\t\t\t{\r\n\t\t\t\t\/\/ Add it to the suggestions\r\n\t\t\t\tsuggestions.insert(suggestion);\r\n\r\n\t\t\t\t\/\/ Output the new suggestion\r\n\t\t\t\tcout << \" \" << suggestion << endl;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\/*\r\n * Utility method to erase\r\n * one character from the word\r\n *\/\r\nstring eraseCharacter(string misspelled, size_t i)\r\n{\r\n\treturn misspelled.erase(i, 1);\r\n}\r\n\r\n\/*\r\n * Method to find the suggestions\r\n * by removing one character from the word\r\n *\/\r\nvoid suggestRemoval(string misspelled, Dictionary& dict, HashSet<string, hash_function, equality>& suggestions)\r\n{\r\n\tfor (size_t i = 0; i < misspelled.length(); ++i)\r\n\t{\r\n\t\tstring suggestion = eraseCharacter(misspelled, i);\r\n\t\tif (dict.search(suggestion))\r\n\t\t{\r\n \/\/ Check if the word\r\n \/\/ was not suggested yet\r\n if (!suggestions.search(suggestion))\r\n {\r\n \/\/ Add it to the suggestions\r\n suggestions.insert(suggestion);\r\n\r\n \/\/ Output the new suggestion\r\n cout << \" \" << suggestion << endl;\r\n }\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\/*\r\n * Utility method to replace\r\n * one character with another\r\n *\/\r\nstring replaceCharacter(string misspelled, size_t toBeReplaced, char replacing)\r\n{\r\n return misspelled.replace(toBeReplaced, 1, 1, replacing);\r\n}\r\n\r\n\/*\r\n * Method to find the suggestions\r\n * by replacing the characters\r\n *\/\r\nvoid suggestReplacement(string misspelled, Dictionary& dict, HashSet<string, hash_function, equality>& suggestions)\r\n{\r\n for (size_t i = 0; i < misspelled.length(); ++i)\r\n {\r\n for (char c = 'a'; c <= 'z'; ++c)\r\n {\r\n string suggestion = replaceCharacter(misspelled, i, c);\r\n if (dict.search(suggestion))\r\n {\r\n \/\/ Check if the word\r\n \/\/ was not suggested yet\r\n if (!suggestions.search(suggestion))\r\n {\r\n \/\/ Add it to the suggestions\r\n suggestions.insert(suggestion);\r\n\r\n \/\/ Output the new suggestion\r\n cout << \" \" << suggestion << endl;\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\n\/*\r\n * Utility method to insert\r\n * one character into the word\r\n *\/\r\nstring insertCharacter(string misspelled, size_t placeToInsertBefore, char toBeInserted)\r\n{\r\n return misspelled.insert(placeToInsertBefore, 1, toBeInserted);\r\n}\r\n\r\n\/*\r\n * Method to find the suggestions\r\n * by inserting the characters\r\n *\/\r\nvoid suggestInserting(string misspelled, Dictionary& dict, HashSet<string, hash_function, equality>& suggestions)\r\n{\r\n for (size_t i = 0; i <= misspelled.length(); ++i)\r\n {\r\n for (char c = 'a'; c <= 'z'; ++c)\r\n {\r\n string suggestion = insertCharacter(misspelled, i, c);\r\n if (dict.search(suggestion))\r\n {\r\n \/\/ Check if the word\r\n \/\/ was not suggested yet\r\n if (!suggestions.search(suggestion))\r\n {\r\n \/\/ Add it to the suggestions\r\n suggestions.insert(suggestion);\r\n\r\n \/\/ Output the new suggestion\r\n cout << \" \" << suggestion << endl;\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid lower(string& s) \r\n{\r\n \/\/ Ensures that a word is lowercase\r\n\tfor (int i = 0; i < s.length(); ++i)\r\n\t\ts[i] = (char) tolower(s[i]);\r\n}\r\n\r\nstring stripPunct(const string& s) \r\n{\r\n\t\/\/ Remove any single trailing\r\n\t\/\/ punctuation character from a word. \r\n\tif (ispunct(s[s.length() - 1])) \r\n\t\treturn s.substr (0, s.length() - 1);\r\n\t\r\n return s;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"consoleui.h\"\n#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nconsoleUI::consoleUI()\n{\n\n}\n\nconsoleUI::consoleUI(int chooseNumber)\n{\n _chooseNumber = chooseNumber;\n}\n\nvoid consoleUI::run()\n{\n int chooseNumber = 0;\n\n cout << \"---------------------------------------\" << endl;\n cout << \"------- Database for Scientist --------\" << endl;\n cout << \"1: Display entire list. *\" << endl;\n cout << \"2: Search by name. *\" << endl;\n cout << \"3: Search if alive. *\" << endl;\n cout << \"4: Search for award. *\" << endl;\n cout << \"5: Add new scientist. *\" << endl;\n cout << \"6: Enter Function. *\" << endl;\n cout << \"7: Enter Function. *\" << endl;\n cout << \"8: Enter Function. *\" << endl;\n cout << \"9: Enter Function. *\" << endl;\n cout << \"10: Enter Function. *\" << endl;\n cout << \"---------------------------------------\" << endl;\n cout << \"Enter number: \";\n\n cin >> chooseNumber;\n\n switch (chooseNumber)\n {\n case 1:\n \/\/vector <scientistList> scientists = _scientist.();\n break;\n case 2:\n int firstOrLast;\n cout << \"choose 1 for firstname or 2 for lastname\" << endl;\n cin >> firstOrLast;\n if(firstOrLast == 1)\n {\n string firstName;\n cout << \"Enter firstname\";\n cin >> firstName;\n \/\/searchfirstname\n }\n else\n {\n string lastName;\n cout << \"Enter lastname:\";\n cin >> lastName;\n\n }\n break;\n case 3:\n \/\/sortAlive\n {\n listServices scientists;\n scientists.changeTo(_scientist.sortByAlive());\n cout << \"An organized list starting with the oldest living scientist\" << endl;\n for(unsigned int i = 0 ; i < scientists.getSize(); i++)\n {\n cout.width(15);\n cout << scientists.getFirstNameFromList(i) << left << scientists.getLastNameFromList(i) << endl;\n\n }\n }\n break;\n case 4:\n \/\/sortAward\n break;\n\n case 5:\n {\n \/\/addNew\n string firstName;\n string lastName;\n char gender;\n int birthYear;\n char isAlive;\n int deathYear;\n char isWinner;\n int awardYear;\n\n cout << \"Please enter the scientist's first name: \";\n cin >> firstName;\n cout << \"Please enter the scientist's last name: \";\n cin >> lastName;\n cout << \"Enter the scientist's gender (m\/f) : \";\n cin >> gender;\n cout << \"Enter the scientist's birth year: \";\n cin >> birthYear;\n cout << \"Is the scientist still alive? (y\/n) \";\n cin >> isAlive;\n if(isAlive == 'n')\n {\n cout << \"Enter the scientist's year of death: \";\n cin >> deathYear;\n }\n else if(isAlive == 'y')\n {\n deathYear = 0;\n }\n else\n {\n \"Invalid entry. Please enter either y (yes) or n (no)\";\n }\n cout << \"Did the scientist win a Turing award? (y\/n)\";\n cin >> isWinner;\n if(isWinner == 'y')\n {\n cout << \"Enter the year the scientist won: \";\n cin >> awardYear;\n }\n else if(isWinner == 'n')\n {\n awardYear = 0;\n }\n else\n {\n \"Invalid entry. Please enter either y (yes) or n (no)\";\n }\n\n _scientist.addNew(firstName, lastName, gender, birthYear, deathYear, awardYear);\n }\n break;\n\n }\n}\n\n\n<commit_msg>working on case 2<commit_after>#include \"consoleui.h\"\n#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nconsoleUI::consoleUI()\n{\n\n}\n\nconsoleUI::consoleUI(int chooseNumber)\n{\n _chooseNumber = chooseNumber;\n}\n\nvoid consoleUI::run()\n{\n int chooseNumber = 0;\n\n cout << \"---------------------------------------\" << endl;\n cout << \"------- Database for Scientist --------\" << endl;\n cout << \"1: Display entire list. *\" << endl;\n cout << \"2: Search by name. *\" << endl;\n cout << \"3: Search if alive. *\" << endl;\n cout << \"4: Search for award. *\" << endl;\n cout << \"5: Add new scientist. *\" << endl;\n cout << \"6: Enter Function. *\" << endl;\n cout << \"7: Enter Function. *\" << endl;\n cout << \"8: Enter Function. *\" << endl;\n cout << \"9: Enter Function. *\" << endl;\n cout << \"10: Enter Function. *\" << endl;\n cout << \"---------------------------------------\" << endl;\n cout << \"Enter number: \";\n\n cin >> chooseNumber;\n\n switch (chooseNumber)\n {\n case 1:\n \/\/vector <scientistList> scientists = _scientist.();\n break;\n case 2:\n \/\/\n int firstOrLast;\n cout << \"choose 1 for firstname or 2 for lastname\" << endl;\n cin >> firstOrLast;\n if(firstOrLast == 1)\n {\n string firstName;\n cout << \"Enter firstname\";\n cin >> firstName;\n \/\/searchfirstname\n }\n else\n {\n string lastName;\n cout << \"Enter lastname:\";\n cin >> lastName;\n\n }\n break;\n case 3:\n \/\/sortAlive\n {\n listServices scientists;\n scientists.changeTo(_scientist.sortByAlive());\n cout << \"An organized list starting with the oldest living scientist\" << endl;\n for(unsigned int i = 0 ; i < scientists.getSize(); i++)\n {\n cout.width(15);\n cout << scientists.getFirstNameFromList(i) << left << scientists.getLastNameFromList(i) << endl;\n\n }\n }\n break;\n case 4:\n \/\/sortAward\n break;\n\n case 5:\n {\n \/\/addNew\n string firstName;\n string lastName;\n char gender;\n int birthYear;\n char isAlive;\n int deathYear;\n char isWinner;\n int awardYear;\n\n cout << \"Please enter the scientist's first name: \";\n cin >> firstName;\n cout << \"Please enter the scientist's last name: \";\n cin >> lastName;\n cout << \"Enter the scientist's gender (m\/f) : \";\n cin >> gender;\n cout << \"Enter the scientist's birth year: \";\n cin >> birthYear;\n cout << \"Is the scientist still alive? (y\/n) \";\n cin >> isAlive;\n if(isAlive == 'n')\n {\n cout << \"Enter the scientist's year of death: \";\n cin >> deathYear;\n }\n else if(isAlive == 'y')\n {\n deathYear = 0;\n }\n else\n {\n \"Invalid entry. Please enter either y (yes) or n (no)\";\n }\n cout << \"Did the scientist win a Turing award? (y\/n)\";\n cin >> isWinner;\n if(isWinner == 'y')\n {\n cout << \"Enter the year the scientist won: \";\n cin >> awardYear;\n }\n else if(isWinner == 'n')\n {\n awardYear = 0;\n }\n else\n {\n \"Invalid entry. Please enter either y (yes) or n (no)\";\n }\n\n _scientist.addNew(firstName, lastName, gender, birthYear, deathYear, awardYear);\n }\n break;\n\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <catch2\/catch.hpp>\n\n#include \"libslic3r\/Model.hpp\"\n#include \"libslic3r\/Format\/3mf.hpp\"\n#include \"libslic3r\/Format\/stl.hpp\"\n\n#include <boost\/filesystem\/operations.hpp>\n\nusing namespace Slic3r;\n\nSCENARIO(\"Reading 3mf file\", \"[3mf]\") {\n GIVEN(\"umlauts in the path of the file\") {\n Model model;\n WHEN(\"3mf model is read\") {\n \tstd::string path = std::string(TEST_DATA_DIR) + \"\/test_3mf\/Geräte\/Büchse.3mf\";\n \tDynamicPrintConfig config;\n bool ret = load_3mf(path.c_str(), &config, &model, false);\n THEN(\"load should succeed\") {\n REQUIRE(ret);\n }\n }\n }\n}\n\nSCENARIO(\"Export+Import geometry to\/from 3mf file cycle\", \"[3mf]\") {\n GIVEN(\"world vertices coordinates before save\") {\n \/\/ load a model from stl file\n Model src_model;\n std::string src_file = std::string(TEST_DATA_DIR) + \"\/test_3mf\/prusa.stl\";\n load_stl(src_file.c_str(), &src_model);\n src_model.add_default_instances();\n\n ModelObject* src_object = src_model.objects[0];\n\n \/\/ apply generic transformation to the 1st volume\n Geometry::Transformation src_volume_transform;\n src_volume_transform.set_offset(Vec3d(10.0, 20.0, 0.0));\n src_volume_transform.set_rotation(Vec3d(Geometry::deg2rad(25.0), Geometry::deg2rad(35.0), Geometry::deg2rad(45.0)));\n src_volume_transform.set_scaling_factor(Vec3d(1.1, 1.2, 1.3));\n src_volume_transform.set_mirror(Vec3d(-1.0, 1.0, -1.0));\n src_object->volumes[0]->set_transformation(src_volume_transform);\n\n \/\/ apply generic transformation to the 1st instance\n Geometry::Transformation src_instance_transform;\n src_instance_transform.set_offset(Vec3d(5.0, 10.0, 0.0));\n src_instance_transform.set_rotation(Vec3d(Geometry::deg2rad(12.0), Geometry::deg2rad(13.0), Geometry::deg2rad(14.0)));\n src_instance_transform.set_scaling_factor(Vec3d(0.9, 0.8, 0.7));\n src_instance_transform.set_mirror(Vec3d(1.0, -1.0, -1.0));\n src_object->instances[0]->set_transformation(src_instance_transform);\n\n WHEN(\"model is saved+loaded to\/from 3mf file\") {\n \/\/ save the model to 3mf file\n std::string test_file = std::string(TEST_DATA_DIR) + \"\/test_3mf\/prusa.3mf\";\n store_3mf(test_file.c_str(), &src_model, nullptr);\n\n \/\/ load back the model from the 3mf file\n Model dst_model;\n DynamicPrintConfig dst_config;\n load_3mf(test_file.c_str(), &dst_config, &dst_model, false);\n boost::filesystem::remove(test_file);\n\n \/\/ compare meshes\n TriangleMesh src_mesh = src_model.mesh();\n src_mesh.repair();\n\n TriangleMesh dst_mesh = dst_model.mesh();\n dst_mesh.repair();\n\n bool res = src_mesh.its.vertices.size() == dst_mesh.its.vertices.size();\n if (res)\n {\n for (size_t i = 0; i < dst_mesh.its.vertices.size(); ++i)\n {\n res &= dst_mesh.its.vertices[i].isApprox(src_mesh.its.vertices[i]);\n if (!res)\n {\n Vec3f diff = dst_mesh.its.vertices[i] - src_mesh.its.vertices[i];\n std::cout << i << \": diff \" << to_string((Vec3d)diff.cast<double>()) << \"\\n\";\n }\n }\n }\n THEN(\"world vertices coordinates after load match\") {\n REQUIRE(res);\n }\n }\n }\n}\n<commit_msg>Follow-up of c790e2ff7c925252b1f83d54154cf858d6eb5afa -> Fixed include<commit_after>#include <catch2\/catch.hpp>\n\n#include \"libslic3r\/Model.hpp\"\n#include \"libslic3r\/Format\/3mf.hpp\"\n#include \"libslic3r\/Format\/STL.hpp\"\n\n#include <boost\/filesystem\/operations.hpp>\n\nusing namespace Slic3r;\n\nSCENARIO(\"Reading 3mf file\", \"[3mf]\") {\n GIVEN(\"umlauts in the path of the file\") {\n Model model;\n WHEN(\"3mf model is read\") {\n \tstd::string path = std::string(TEST_DATA_DIR) + \"\/test_3mf\/Geräte\/Büchse.3mf\";\n \tDynamicPrintConfig config;\n bool ret = load_3mf(path.c_str(), &config, &model, false);\n THEN(\"load should succeed\") {\n REQUIRE(ret);\n }\n }\n }\n}\n\nSCENARIO(\"Export+Import geometry to\/from 3mf file cycle\", \"[3mf]\") {\n GIVEN(\"world vertices coordinates before save\") {\n \/\/ load a model from stl file\n Model src_model;\n std::string src_file = std::string(TEST_DATA_DIR) + \"\/test_3mf\/prusa.stl\";\n load_stl(src_file.c_str(), &src_model);\n src_model.add_default_instances();\n\n ModelObject* src_object = src_model.objects[0];\n\n \/\/ apply generic transformation to the 1st volume\n Geometry::Transformation src_volume_transform;\n src_volume_transform.set_offset(Vec3d(10.0, 20.0, 0.0));\n src_volume_transform.set_rotation(Vec3d(Geometry::deg2rad(25.0), Geometry::deg2rad(35.0), Geometry::deg2rad(45.0)));\n src_volume_transform.set_scaling_factor(Vec3d(1.1, 1.2, 1.3));\n src_volume_transform.set_mirror(Vec3d(-1.0, 1.0, -1.0));\n src_object->volumes[0]->set_transformation(src_volume_transform);\n\n \/\/ apply generic transformation to the 1st instance\n Geometry::Transformation src_instance_transform;\n src_instance_transform.set_offset(Vec3d(5.0, 10.0, 0.0));\n src_instance_transform.set_rotation(Vec3d(Geometry::deg2rad(12.0), Geometry::deg2rad(13.0), Geometry::deg2rad(14.0)));\n src_instance_transform.set_scaling_factor(Vec3d(0.9, 0.8, 0.7));\n src_instance_transform.set_mirror(Vec3d(1.0, -1.0, -1.0));\n src_object->instances[0]->set_transformation(src_instance_transform);\n\n WHEN(\"model is saved+loaded to\/from 3mf file\") {\n \/\/ save the model to 3mf file\n std::string test_file = std::string(TEST_DATA_DIR) + \"\/test_3mf\/prusa.3mf\";\n store_3mf(test_file.c_str(), &src_model, nullptr);\n\n \/\/ load back the model from the 3mf file\n Model dst_model;\n DynamicPrintConfig dst_config;\n load_3mf(test_file.c_str(), &dst_config, &dst_model, false);\n boost::filesystem::remove(test_file);\n\n \/\/ compare meshes\n TriangleMesh src_mesh = src_model.mesh();\n src_mesh.repair();\n\n TriangleMesh dst_mesh = dst_model.mesh();\n dst_mesh.repair();\n\n bool res = src_mesh.its.vertices.size() == dst_mesh.its.vertices.size();\n if (res)\n {\n for (size_t i = 0; i < dst_mesh.its.vertices.size(); ++i)\n {\n res &= dst_mesh.its.vertices[i].isApprox(src_mesh.its.vertices[i]);\n if (!res)\n {\n Vec3f diff = dst_mesh.its.vertices[i] - src_mesh.its.vertices[i];\n std::cout << i << \": diff \" << to_string((Vec3d)diff.cast<double>()) << \"\\n\";\n }\n }\n }\n THEN(\"world vertices coordinates after load match\") {\n REQUIRE(res);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nvector < string > GetWords (string s, char delim)\n{\n vector < string > words;\n if (s.find (delim) == string::npos) {\n words.push_back (s);\n return words;\n }\n else {\n stringstream ss (s);\n string word;\n while (getline (ss, word, delim)) {\n words.push_back (word);\n }\n\n return words;\n }\n}\n\nstring\nLongestWord (string sen)\n{\n if (sen == \"\")\n return \"\";\n\n if (sen[0] == ' ')\n sen = sen.substr (1);\n\n if (sen[sen.length () - 1] == ' ')\n sen = sen.substr (0, sen.length () - 1);\n\n vector < string > words = GetWords (sen, ' ');\n\n size_t index = 0;\n int longestWord = 0;\n bool found = false;\n\n for (int i = words.size () - 1; i >= 0; i--) {\n int length = words[i].length ();\n if (length >= longestWord) {\n longestWord = length;\n index = i;\n found = true;\n }\n }\n\n return (found ? words[index] : \"\");\n}\n\nint\nmain ()\n{\n size_t tests = 7;\n string test[tests][2] = { {\"\", \"\"},\n {\" \", \"\"},\n {\"A\", \"A\"},\n {\" A \", \"A\"},\n {\"A AB\", \"AB\"},\n {\"AA AA A B\", \"AA\"},\n {\"%!#!@ ###3###\", \"###3###\"}\n };\n string input;\n string actual;\n string expected;\n\n for (size_t i = 0; i < tests; i++) {\n input = test[i][0];\n actual = LongestWord (input);\n expected = test[i][1];\n cout << \"Case #\" << i +\n 1 << \" input: '\" << input << \"' expected: '\" << expected <<\n \"' actual: '\" << actual << \"'\" << endl;\n if (actual != expected) {\n cout << actual << \" did not match \" << expected << \"; Test failed!\" <<\n\tendl;\n }\n else {\n cout << actual << \" did match \" << expected << \": Test passed!\" << endl;\n }\n cout << endl;\n }\n\n return 0;\n}\n<commit_msg>Adds another test case<commit_after>#include <iostream>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nvector < string > GetWords (string s, char delim)\n{\n vector < string > words;\n if (s.find (delim) == string::npos) {\n words.push_back (s);\n return words;\n }\n else {\n stringstream ss (s);\n string word;\n while (getline (ss, word, delim)) {\n words.push_back (word);\n }\n\n return words;\n }\n}\n\nstring\nLongestWord (string sen)\n{\n if (sen == \"\")\n return \"\";\n\n if (sen[0] == ' ')\n sen = sen.substr (1);\n\n if (sen[sen.length () - 1] == ' ')\n sen = sen.substr (0, sen.length () - 1);\n\n vector < string > words = GetWords (sen, ' ');\n\n size_t index = 0;\n int longestWord = 0;\n bool found = false;\n\n for (int i = words.size () - 1; i >= 0; i--) {\n int length = words[i].length ();\n if (length >= longestWord) {\n longestWord = length;\n index = i;\n found = true;\n }\n }\n\n return (found ? words[index] : \"\");\n}\n\nint\nmain ()\n{\n size_t tests = 8;\n string test[tests][2] = { {\"\", \"\"},\n {\" \", \"\"},\n {\"A\", \"A\"},\n {\" A \", \"A\"},\n {\"A AB\", \"AB\"},\n {\"AA AA A B\", \"AA\"},\n {\"%!#!@ ###3###\", \"###3###\"},\n {\" A B CC A\", \"CC\"}\n };\n string input;\n string actual;\n string expected;\n\n for (size_t i = 0; i < tests; i++) {\n input = test[i][0];\n actual = LongestWord (input);\n expected = test[i][1];\n cout << \"Case #\" << i +\n 1 << \" input: '\" << input << \"' expected: '\" << expected <<\n \"' actual: '\" << actual << \"'\" << endl;\n if (actual != expected) {\n cout << actual << \" did not match \" << expected << \"; Test failed!\" <<\n\tendl;\n }\n else {\n cout << actual << \" did match \" << expected << \": Test passed!\" << endl;\n }\n cout << endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/gl:$Name: $:$Id: TGLUtil.cxx,v 1.9 2005\/08\/10 16:26:35 brun Exp $\n\/\/ Author: Richard Maunder 25\/05\/2005\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/ TODO: Function descriptions\n\/\/ TODO: Class def - same as header!!!\n\n#include \"TGLUtil.h\"\n#include \"TGLIncludes.h\"\n#include \"TError.h\"\n#include \"Riostream.h\"\n\nClassImp(TGLVertex3)\n\n\/\/______________________________________________________________________________\nTGLVertex3::TGLVertex3()\n{\n Fill(0.0);\n}\n\n\/\/______________________________________________________________________________\nTGLVertex3::TGLVertex3(Double_t x, Double_t y, Double_t z)\n{\n Set(x,y,z);\n}\n\n\/\/______________________________________________________________________________\nTGLVertex3::TGLVertex3(const TGLVertex3 & other)\n{\n Set(other);\n}\n\n\/\/______________________________________________________________________________\nTGLVertex3::~TGLVertex3()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TGLVertex3::Shift(TGLVector3 & shift)\n{\n fVals[0] += shift[0];\n fVals[1] += shift[1];\n fVals[2] += shift[2];\n}\n\n\/\/______________________________________________________________________________\nvoid TGLVertex3::Shift(Double_t xDelta, Double_t yDelta, Double_t zDelta)\n{\n fVals[0] += xDelta;\n fVals[1] += yDelta;\n fVals[2] += zDelta;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLVertex3::Dump() const\n{\n std::cout << \"(\" << fVals[0] << \",\" << fVals[1] << \",\" << fVals[2] << \")\" << std::endl;\n}\n\nClassImp(TGLVector3)\n\n\/\/______________________________________________________________________________\nTGLVector3::TGLVector3() :\n TGLVertex3()\n{\n}\n\n\/\/______________________________________________________________________________\nTGLVector3::TGLVector3(Double_t x, Double_t y, Double_t z) :\n TGLVertex3(x, y, z)\n{\n}\n\n\/\/______________________________________________________________________________\nTGLVector3::TGLVector3(const TGLVector3 & other) :\n TGLVertex3(other.fVals[0], other.fVals[1], other.fVals[2])\n{\n}\n\n\/\/______________________________________________________________________________\nTGLVector3::~TGLVector3()\n{\n}\n\nClassImp(TGLRect)\n\n\/\/______________________________________________________________________________\nTGLRect::TGLRect() :\n fX(0), fY(0), fWidth(0), fHeight(0)\n{\n}\n\n\/\/______________________________________________________________________________\nTGLRect::TGLRect(Int_t x, Int_t y, UInt_t width, UInt_t height) :\n fX(x), fY(y), fWidth(width), fHeight(height)\n{\n}\n\n\/\/______________________________________________________________________________\nTGLRect::~TGLRect()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TGLRect::Expand(Int_t x, Int_t y)\n{\n Int_t delX = x - fX;\n Int_t delY = y - fY;\n\n if (delX>static_cast<Int_t>(fWidth)) {\n fWidth = delX;\n }\n if (delY>static_cast<Int_t>(fHeight)) {\n fHeight = delY;\n }\n\n if (delX<0) {\n fX = x;\n fWidth += -delX;\n }\n if (delY<0) {\n fY = y;\n fHeight += -delY;\n }\n}\n\n\/\/______________________________________________________________________________\nDouble_t TGLRect::Aspect() const\n{\n if (fHeight == 0) {\n return 0.0;\n } else {\n return static_cast<Double_t>(fWidth) \/ static_cast<Double_t>(fHeight);\n }\n}\n\n\/\/______________________________________________________________________________\nEOverlap TGLRect::Overlap(const TGLRect & other) const\n{\n if ((fX <= other.fX) && (fX + fWidth >= other.fX + other.fWidth) &&\n (fY <= other.fY) && (fY +fHeight >= other.fY + other.fHeight)) {\n return kInside;\n }\n else if ((fX >= other.fX + static_cast<Int_t>(other.fWidth)) ||\n (fX + static_cast<Int_t>(fWidth) <= other.fX) ||\n (fY >= other.fY + static_cast<Int_t>(other.fHeight)) ||\n (fY + static_cast<Int_t>(fHeight) <= other.fY)) {\n return kOutside;\n } else {\n return kPartial;\n }\n}\n\nClassImp(TGLPlane)\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane()\n{\n \/\/ Construct a default plane of x + y + z = 0\n Set(1.0, 1.0, 1.0, 0.0);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(const TGLPlane & other)\n{\n Set(other);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(Double_t a, Double_t b, Double_t c, Double_t d)\n{\n \/\/ Construct plane with equation a.x + b.y + c.z + d = 0\n \/\/ with optional normalisation\n Set(a, b, c, d);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(Double_t eq[4])\n{\n \/\/ Construct plane with equation eq[0].x + eq[1].y + eq[2].z + eq[3] = 0\n \/\/ with optional normalisation\n Set(eq);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(const TGLVertex3 & p1, const TGLVertex3 & p2, \n const TGLVertex3 & p3)\n{\n \/\/ Construct plane passing through 3 supplied points\n \/\/ with optional normalisation\n Set(p1, p2, p3);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(const TGLVector3 & v, const TGLVertex3 & p)\n{\n \/\/ Construct plane with supplied normal vector, passing through point\n \/\/ with optional normalisation\n Set(v, p);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::~TGLPlane()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlane::Dump() const\n{\n std::cout.precision(6);\n \tstd::cout << \"Plane : \" << fVals[0] << \"x + \" << fVals[1] << \"y + \" << fVals[2] << \"z + \" << fVals[3] <<\n\tstd::endl;\n }\n\nClassImp(TGLMatrix)\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix()\n{\n SetIdentity();\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(Double_t x, Double_t y, Double_t z)\n{\n SetIdentity();\n Set(x, y, z);\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(const TGLVertex3 & translation)\n{\n SetIdentity();\n Set(translation);\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(const TGLVertex3 & origin, const TGLVector3 & zAxis)\n{\n SetIdentity();\n Set(origin, zAxis);\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(const Double_t vals[16])\n{\n Set(vals);\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(const TGLMatrix & other)\n{\n *this = other;\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::~TGLMatrix()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Set(Double_t x, Double_t y, Double_t z)\n{\n Set(TGLVertex3(x,y,z));\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Set(const TGLVertex3 & translation)\n{\n \/\/ Set the translation component of matirx - rest left unaffected\n fVals[12] = translation[0];\n fVals[13] = translation[1];\n fVals[14] = translation[2];\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Set(const TGLVertex3 & origin, const TGLVector3 & z)\n{\n \/\/ Establish matrix transformation which when applied puts local origin at \n \/\/ passed 'origin' and the local Z axis in direction 'z'. Both\n \/\/ 'origin' and 'zAxisVec' are expressed in the parent frame\n TGLVector3 zAxis(z);\n zAxis.Normalise();\n TGLVector3 axis; \n if (fabsf(zAxis.X()) <= fabsf(zAxis.Y()) && fabsf(zAxis.X()) <= fabsf(zAxis.Z())) {\n axis.Set(1, 0, 0); \n } else if (fabsf(zAxis.Y()) <= fabsf(zAxis.X()) && fabsf(zAxis.Y()) <= fabsf(zAxis.Z())) {\n axis.Set(0, 1, 0); \n } else { \n axis.Set(0, 0, 1);\n }\n\n TGLVector3 xAxis = Cross(zAxis, axis);\n xAxis.Normalise();\n TGLVector3 yAxis = Cross(zAxis, xAxis);\n\n fVals[0] = xAxis.X(); fVals[4] = yAxis.X(); fVals[8 ] = zAxis.X(); fVals[12] = origin.X();\n fVals[1] = xAxis.Y(); fVals[5] = yAxis.Y(); fVals[9 ] = zAxis.Y(); fVals[13] = origin.Y();\n fVals[2] = xAxis.Z(); fVals[6] = yAxis.Z(); fVals[10] = zAxis.Z(); fVals[14] = origin.Z();\n fVals[3] = 0.0; fVals[7] = 0.0; fVals[11] = 0.0; fVals[15] = 1.0;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Set(const Double_t vals[16])\n{\n for (UInt_t i=0; i < 16; i++) {\n fVals[i] = vals[i];\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::SetIdentity()\n{\n fVals[0] = 1.0; fVals[4] = 0.0; fVals[8 ] = 0.0; fVals[12] = 0.0;\n fVals[1] = 0.0; fVals[5] = 1.0; fVals[9 ] = 0.0; fVals[13] = 0.0;\n fVals[2] = 0.0; fVals[6] = 0.0; fVals[10] = 1.0; fVals[14] = 0.0;\n fVals[3] = 0.0; fVals[7] = 0.0; fVals[11] = 0.0; fVals[15] = 1.0;\n}\n\n\/\/______________________________________________________________________________\nTGLVertex3 TGLMatrix::Translation() const\n{\n return TGLVertex3(fVals[12], fVals[13], fVals[14]);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Shift(const TGLVector3 & shift)\n{\n fVals[12] += shift[0];\n fVals[13] += shift[1];\n fVals[14] += shift[2];\n}\n\n\/\/______________________________________________________________________________\nTGLVector3 TGLMatrix::Scale() const\n{\n \/\/ Get local axis scaling factors\n TGLVector3 x(fVals[0], fVals[1], fVals[2]);\n TGLVector3 y(fVals[4], fVals[5], fVals[6]);\n TGLVector3 z(fVals[8], fVals[9], fVals[10]);\n return TGLVector3(x.Mag(), y.Mag(), z.Mag());\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::SetScale(const TGLVector3 & scale)\n{\n\n \/\/ Set local axis scaling factors\n TGLVector3 currentScale = Scale();\n \n \/\/ x\n if (currentScale[0] != 0.0) {\n fVals[0] *= scale[0]\/currentScale[0];\n fVals[1] *= scale[0]\/currentScale[0];\n fVals[2] *= scale[0]\/currentScale[0];\n } else {\n Error(\"TGLMatrix::SetScale()\", \"zero scale div by zero\");\n }\n \/\/ y\n if (currentScale[1] != 0.0) {\n fVals[4] *= scale[1]\/currentScale[1];\n fVals[5] *= scale[1]\/currentScale[1];\n fVals[6] *= scale[1]\/currentScale[1];\n } else {\n Error(\"TGLMatrix::SetScale()\", \"zero scale div by zero\");\n }\n \/\/ z\n if (currentScale[2] != 0.0) {\n fVals[8] *= scale[2]\/currentScale[2];\n fVals[9] *= scale[2]\/currentScale[2];\n fVals[10] *= scale[2]\/currentScale[2];\n } else {\n Error(\"TGLMatrix::SetScale()\", \"zero scale div by zero\");\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Transpose3x3()\n{\n \/\/ Transpose the top left 3x3 matrix component along major diagonal\n\n \/\/ TODO: Move this fix to the TBuffer3D filling side and remove\n\n \/\/ 0 4 8 12\n \/\/ 1 5 9 13\n \/\/ 2 6 10 14\n \/\/ 3 7 11 15\n\n Double_t temp = fVals[4];\n\tfVals[4] = fVals[1];\n\tfVals[1] = temp;\n\ttemp = fVals[8];\n\tfVals[8] = fVals[2];\n\tfVals[2] = temp;\n\ttemp = fVals[9];\n\tfVals[9] = fVals[6];\n\tfVals[6] = temp;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::TransformVertex(TGLVertex3 & vertex) const\n{\n TGLVertex3 orig = vertex;\n for (UInt_t i = 0; i < 3; i++) {\n vertex[i] = orig[0] * fVals[0+i] + orig[1] * fVals[4+i] +\n orig[2] * fVals[8+i] + fVals[12+i];\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Dump() const\n{\n std::cout.precision(6);\n for (Int_t x = 0; x < 4; x++) {\n std::cout << \"[ \";\n for (Int_t y = 0; y < 4; y++) {\n std::cout << fVals[y*4 + x] << \" \";\n }\n std::cout << \"]\" << std::endl;\n }\n}\n\nClassImp(TGLUtil)\n\n\/\/______________________________________________________________________________\nvoid TGLUtil::CheckError()\n{\n GLenum errCode;\n const GLubyte *errString;\n\n if ((errCode = glGetError()) != GL_NO_ERROR) {\n errString = gluErrorString(errCode);\n Error(\"TGLUtil::CheckError\", (const char *)errString);\n }\n}\n<commit_msg>From Richard: Fix Solaris compilation problem - hopefully.<commit_after>\/\/ @(#)root\/gl:$Name: $:$Id: TGLUtil.cxx,v 1.10 2005\/10\/03 15:19:35 brun Exp $\n\/\/ Author: Richard Maunder 25\/05\/2005\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/ TODO: Function descriptions\n\/\/ TODO: Class def - same as header!!!\n\n#include \"TGLUtil.h\"\n#include \"TGLIncludes.h\"\n#include \"TError.h\"\n#include \"Riostream.h\"\n\nClassImp(TGLVertex3)\n\n\/\/______________________________________________________________________________\nTGLVertex3::TGLVertex3()\n{\n Fill(0.0);\n}\n\n\/\/______________________________________________________________________________\nTGLVertex3::TGLVertex3(Double_t x, Double_t y, Double_t z)\n{\n Set(x,y,z);\n}\n\n\/\/______________________________________________________________________________\nTGLVertex3::TGLVertex3(const TGLVertex3 & other)\n{\n Set(other);\n}\n\n\/\/______________________________________________________________________________\nTGLVertex3::~TGLVertex3()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TGLVertex3::Shift(TGLVector3 & shift)\n{\n fVals[0] += shift[0];\n fVals[1] += shift[1];\n fVals[2] += shift[2];\n}\n\n\/\/______________________________________________________________________________\nvoid TGLVertex3::Shift(Double_t xDelta, Double_t yDelta, Double_t zDelta)\n{\n fVals[0] += xDelta;\n fVals[1] += yDelta;\n fVals[2] += zDelta;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLVertex3::Dump() const\n{\n std::cout << \"(\" << fVals[0] << \",\" << fVals[1] << \",\" << fVals[2] << \")\" << std::endl;\n}\n\nClassImp(TGLVector3)\n\n\/\/______________________________________________________________________________\nTGLVector3::TGLVector3() :\n TGLVertex3()\n{\n}\n\n\/\/______________________________________________________________________________\nTGLVector3::TGLVector3(Double_t x, Double_t y, Double_t z) :\n TGLVertex3(x, y, z)\n{\n}\n\n\/\/______________________________________________________________________________\nTGLVector3::TGLVector3(const TGLVector3 & other) :\n TGLVertex3(other.fVals[0], other.fVals[1], other.fVals[2])\n{\n}\n\n\/\/______________________________________________________________________________\nTGLVector3::~TGLVector3()\n{\n}\n\nClassImp(TGLRect)\n\n\/\/______________________________________________________________________________\nTGLRect::TGLRect() :\n fX(0), fY(0), fWidth(0), fHeight(0)\n{\n}\n\n\/\/______________________________________________________________________________\nTGLRect::TGLRect(Int_t x, Int_t y, UInt_t width, UInt_t height) :\n fX(x), fY(y), fWidth(width), fHeight(height)\n{\n}\n\n\/\/______________________________________________________________________________\nTGLRect::~TGLRect()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TGLRect::Expand(Int_t x, Int_t y)\n{\n Int_t delX = x - fX;\n Int_t delY = y - fY;\n\n if (delX>static_cast<Int_t>(fWidth)) {\n fWidth = delX;\n }\n if (delY>static_cast<Int_t>(fHeight)) {\n fHeight = delY;\n }\n\n if (delX<0) {\n fX = x;\n fWidth += -delX;\n }\n if (delY<0) {\n fY = y;\n fHeight += -delY;\n }\n}\n\n\/\/______________________________________________________________________________\nDouble_t TGLRect::Aspect() const\n{\n if (fHeight == 0) {\n return 0.0;\n } else {\n return static_cast<Double_t>(fWidth) \/ static_cast<Double_t>(fHeight);\n }\n}\n\n\/\/______________________________________________________________________________\nEOverlap TGLRect::Overlap(const TGLRect & other) const\n{\n if ((fX <= other.fX) && (fX + fWidth >= other.fX + other.fWidth) &&\n (fY <= other.fY) && (fY +fHeight >= other.fY + other.fHeight)) {\n return kInside;\n }\n else if ((fX >= other.fX + static_cast<Int_t>(other.fWidth)) ||\n (fX + static_cast<Int_t>(fWidth) <= other.fX) ||\n (fY >= other.fY + static_cast<Int_t>(other.fHeight)) ||\n (fY + static_cast<Int_t>(fHeight) <= other.fY)) {\n return kOutside;\n } else {\n return kPartial;\n }\n}\n\nClassImp(TGLPlane)\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane()\n{\n \/\/ Construct a default plane of x + y + z = 0\n Set(1.0, 1.0, 1.0, 0.0);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(const TGLPlane & other)\n{\n Set(other);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(Double_t a, Double_t b, Double_t c, Double_t d)\n{\n \/\/ Construct plane with equation a.x + b.y + c.z + d = 0\n \/\/ with optional normalisation\n Set(a, b, c, d);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(Double_t eq[4])\n{\n \/\/ Construct plane with equation eq[0].x + eq[1].y + eq[2].z + eq[3] = 0\n \/\/ with optional normalisation\n Set(eq);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(const TGLVertex3 & p1, const TGLVertex3 & p2, \n const TGLVertex3 & p3)\n{\n \/\/ Construct plane passing through 3 supplied points\n \/\/ with optional normalisation\n Set(p1, p2, p3);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::TGLPlane(const TGLVector3 & v, const TGLVertex3 & p)\n{\n \/\/ Construct plane with supplied normal vector, passing through point\n \/\/ with optional normalisation\n Set(v, p);\n}\n\n\/\/______________________________________________________________________________\nTGLPlane::~TGLPlane()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlane::Dump() const\n{\n std::cout.precision(6);\n \tstd::cout << \"Plane : \" << fVals[0] << \"x + \" << fVals[1] << \"y + \" << fVals[2] << \"z + \" << fVals[3] <<\n\tstd::endl;\n }\n\nClassImp(TGLMatrix)\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix()\n{\n SetIdentity();\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(Double_t x, Double_t y, Double_t z)\n{\n SetIdentity();\n Set(x, y, z);\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(const TGLVertex3 & translation)\n{\n SetIdentity();\n Set(translation);\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(const TGLVertex3 & origin, const TGLVector3 & zAxis)\n{\n SetIdentity();\n Set(origin, zAxis);\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(const Double_t vals[16])\n{\n Set(vals);\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::TGLMatrix(const TGLMatrix & other)\n{\n *this = other;\n}\n\n\/\/______________________________________________________________________________\nTGLMatrix::~TGLMatrix()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Set(Double_t x, Double_t y, Double_t z)\n{\n Set(TGLVertex3(x,y,z));\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Set(const TGLVertex3 & translation)\n{\n \/\/ Set the translation component of matirx - rest left unaffected\n fVals[12] = translation[0];\n fVals[13] = translation[1];\n fVals[14] = translation[2];\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Set(const TGLVertex3 & origin, const TGLVector3 & z)\n{\n \/\/ Establish matrix transformation which when applied puts local origin at \n \/\/ passed 'origin' and the local Z axis in direction 'z'. Both\n \/\/ 'origin' and 'zAxisVec' are expressed in the parent frame\n TGLVector3 zAxis(z);\n zAxis.Normalise();\n TGLVector3 axis; \n if (fabs(zAxis.X()) <= fabs(zAxis.Y()) && fabs(zAxis.X()) <= fabs(zAxis.Z())) {\n axis.Set(1, 0, 0); \n } else if (fabs(zAxis.Y()) <= fabs(zAxis.X()) && fabs(zAxis.Y()) <= fabs(zAxis.Z())) {\n axis.Set(0, 1, 0); \n } else { \n axis.Set(0, 0, 1);\n }\n\n TGLVector3 xAxis = Cross(zAxis, axis);\n xAxis.Normalise();\n TGLVector3 yAxis = Cross(zAxis, xAxis);\n\n fVals[0] = xAxis.X(); fVals[4] = yAxis.X(); fVals[8 ] = zAxis.X(); fVals[12] = origin.X();\n fVals[1] = xAxis.Y(); fVals[5] = yAxis.Y(); fVals[9 ] = zAxis.Y(); fVals[13] = origin.Y();\n fVals[2] = xAxis.Z(); fVals[6] = yAxis.Z(); fVals[10] = zAxis.Z(); fVals[14] = origin.Z();\n fVals[3] = 0.0; fVals[7] = 0.0; fVals[11] = 0.0; fVals[15] = 1.0;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Set(const Double_t vals[16])\n{\n for (UInt_t i=0; i < 16; i++) {\n fVals[i] = vals[i];\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::SetIdentity()\n{\n fVals[0] = 1.0; fVals[4] = 0.0; fVals[8 ] = 0.0; fVals[12] = 0.0;\n fVals[1] = 0.0; fVals[5] = 1.0; fVals[9 ] = 0.0; fVals[13] = 0.0;\n fVals[2] = 0.0; fVals[6] = 0.0; fVals[10] = 1.0; fVals[14] = 0.0;\n fVals[3] = 0.0; fVals[7] = 0.0; fVals[11] = 0.0; fVals[15] = 1.0;\n}\n\n\/\/______________________________________________________________________________\nTGLVertex3 TGLMatrix::Translation() const\n{\n return TGLVertex3(fVals[12], fVals[13], fVals[14]);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Shift(const TGLVector3 & shift)\n{\n fVals[12] += shift[0];\n fVals[13] += shift[1];\n fVals[14] += shift[2];\n}\n\n\/\/______________________________________________________________________________\nTGLVector3 TGLMatrix::Scale() const\n{\n \/\/ Get local axis scaling factors\n TGLVector3 x(fVals[0], fVals[1], fVals[2]);\n TGLVector3 y(fVals[4], fVals[5], fVals[6]);\n TGLVector3 z(fVals[8], fVals[9], fVals[10]);\n return TGLVector3(x.Mag(), y.Mag(), z.Mag());\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::SetScale(const TGLVector3 & scale)\n{\n\n \/\/ Set local axis scaling factors\n TGLVector3 currentScale = Scale();\n \n \/\/ x\n if (currentScale[0] != 0.0) {\n fVals[0] *= scale[0]\/currentScale[0];\n fVals[1] *= scale[0]\/currentScale[0];\n fVals[2] *= scale[0]\/currentScale[0];\n } else {\n Error(\"TGLMatrix::SetScale()\", \"zero scale div by zero\");\n }\n \/\/ y\n if (currentScale[1] != 0.0) {\n fVals[4] *= scale[1]\/currentScale[1];\n fVals[5] *= scale[1]\/currentScale[1];\n fVals[6] *= scale[1]\/currentScale[1];\n } else {\n Error(\"TGLMatrix::SetScale()\", \"zero scale div by zero\");\n }\n \/\/ z\n if (currentScale[2] != 0.0) {\n fVals[8] *= scale[2]\/currentScale[2];\n fVals[9] *= scale[2]\/currentScale[2];\n fVals[10] *= scale[2]\/currentScale[2];\n } else {\n Error(\"TGLMatrix::SetScale()\", \"zero scale div by zero\");\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Transpose3x3()\n{\n \/\/ Transpose the top left 3x3 matrix component along major diagonal\n\n \/\/ TODO: Move this fix to the TBuffer3D filling side and remove\n\n \/\/ 0 4 8 12\n \/\/ 1 5 9 13\n \/\/ 2 6 10 14\n \/\/ 3 7 11 15\n\n Double_t temp = fVals[4];\n\tfVals[4] = fVals[1];\n\tfVals[1] = temp;\n\ttemp = fVals[8];\n\tfVals[8] = fVals[2];\n\tfVals[2] = temp;\n\ttemp = fVals[9];\n\tfVals[9] = fVals[6];\n\tfVals[6] = temp;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::TransformVertex(TGLVertex3 & vertex) const\n{\n TGLVertex3 orig = vertex;\n for (UInt_t i = 0; i < 3; i++) {\n vertex[i] = orig[0] * fVals[0+i] + orig[1] * fVals[4+i] +\n orig[2] * fVals[8+i] + fVals[12+i];\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLMatrix::Dump() const\n{\n std::cout.precision(6);\n for (Int_t x = 0; x < 4; x++) {\n std::cout << \"[ \";\n for (Int_t y = 0; y < 4; y++) {\n std::cout << fVals[y*4 + x] << \" \";\n }\n std::cout << \"]\" << std::endl;\n }\n}\n\nClassImp(TGLUtil)\n\n\/\/______________________________________________________________________________\nvoid TGLUtil::CheckError()\n{\n GLenum errCode;\n const GLubyte *errString;\n\n if ((errCode = glGetError()) != GL_NO_ERROR) {\n errString = gluErrorString(errCode);\n Error(\"TGLUtil::CheckError\", (const char *)errString);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ OpenGL Mathematics (glm.g-truc.net)\n\/\/\/\n\/\/\/ Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)\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\/\/\/ @ref gtc_random\n\/\/\/ @file glm\/gtc\/random.hpp\n\/\/\/ @date 2011-09-18 \/ 2011-09-18\n\/\/\/ @author Christophe Riccio\n\/\/\/\n\/\/\/ @see core (dependence)\n\/\/\/ @see gtc_half_float (dependence)\n\/\/\/ @see gtx_random (extended)\n\/\/\/\n\/\/\/ @defgroup gtc_random GLM_GTC_random: Random number generation\n\/\/\/ @ingroup gtc\n\/\/\/ \n\/\/\/ @brief Generate random number from various distribution methods\n\/\/\/ \n\/\/\/ <glm\/gtc\/random.hpp> need to be included to use these functionalities.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef GLM_GTC_random\n#define GLM_GTC_random GLM_VERSION\n\n\/\/ Dependency:\n#include \"..\/glm.hpp\"\n#include \"..\/gtc\/half_float.hpp\"\n\n#if(defined(GLM_MESSAGES) && !defined(glm_ext))\n#\tpragma message(\"GLM: GLM_GTC_random extension included\")\n#endif\n\nnamespace glm\n{\n\t\/\/\/ @addtogroup gtc_random\n\t\/\/\/ @{\n\n\t\/\/\/ Generate a random number in the interval [-1, 1], according a linear distribution.\n\t\/\/\/ From GLM_GTC_random extension.\n template <typename T> T signedRand1();\n\n\t\/\/\/ @}\n}\/\/namespace glm\n\n#include \"random.inl\"\n\n#endif\/\/GLM_GTC_random\n<commit_msg>Added new GTC API for random<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ OpenGL Mathematics (glm.g-truc.net)\n\/\/\/\n\/\/\/ Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)\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\/\/\/ @ref gtc_random\n\/\/\/ @file glm\/gtc\/random.hpp\n\/\/\/ @date 2011-09-18 \/ 2011-09-18\n\/\/\/ @author Christophe Riccio\n\/\/\/\n\/\/\/ @see core (dependence)\n\/\/\/ @see gtc_half_float (dependence)\n\/\/\/ @see gtx_random (extended)\n\/\/\/\n\/\/\/ @defgroup gtc_random GLM_GTC_random: Random number generation\n\/\/\/ @ingroup gtc\n\/\/\/ \n\/\/\/ @brief Generate random number from various distribution methods\n\/\/\/ \n\/\/\/ <glm\/gtc\/random.hpp> need to be included to use these functionalities.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef GLM_GTC_random\n#define GLM_GTC_random GLM_VERSION\n\n\/\/ Dependency:\n#include \"..\/glm.hpp\"\n#include \"..\/gtc\/half_float.hpp\"\n\n#if(defined(GLM_MESSAGES) && !defined(glm_ext))\n#\tpragma message(\"GLM: GLM_GTC_random extension included\")\n#endif\n\nnamespace glm\n{\n\t\/\/\/ @addtogroup gtc_random\n\t\/\/\/ @{\n\t\n\t\/\/\/ Generate random numbers in the interval [Min, Max], according a linear distribution \n\t\/\/\/ \n\t\/\/\/ @param Min \n\t\/\/\/ @param Max \n\t\/\/\/ @tparam genType Value type. Currently supported: half (not recommanded), float or double scalars and vectors.\n\t\/\/\/ @see gtc_random\n\ttemplate <typename genType> \n\tgenType linearRand(\n\t\tgenType const & Min, \n\t\tgenType const & Max);\n\n\t\/\/\/ Generate random numbers in the interval [Min, Max], according a gaussian distribution \n\t\/\/\/ (From GLM_GTX_random extension)\n\ttemplate <typename T, template <typename> class vecType> \n\tvecType<T> gaussRand(\n\t\tvecType<T> const & Mean, \n\t\tvecType<T> const & Deviation);\n\t\n\t\/\/\/ Generate a random 2D vector which coordinates are regulary distributed on a circle of a given radius\n\t\/\/\/ (From GLM_GTX_random extension)\n\ttemplate <typename T> \n\tdetail::tvec2<T> circularRand(T const & Radius); \n\t\n\t\/\/\/ Generate a random 3D vector which coordinates are regulary distributed on a sphere of a given radius\n\t\/\/\/ (From GLM_GTX_random extension)\n\ttemplate <typename T> \n\tdetail::tvec3<T> sphericalRand(T const & Radius); \n\t\n\t\/\/\/ @}\n}\/\/namespace glm\n\n#include \"random.inl\"\n\n#endif\/\/GLM_GTC_random\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2009 NVIDIA Corporation\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#include <thrust\/detail\/raw_buffer.h>\n#include <thrust\/distance.h>\n#include <thrust\/copy.h>\n\n\nnamespace thrust\n{\n\nnamespace detail\n{\n\n\ntemplate<typename T, typename Space>\n raw_buffer<T,Space>\n ::raw_buffer(size_type n)\n{\n m_begin = m_allocator.allocate(n);\n m_end = m_begin + n;\n} \/\/ end raw_buffer::raw_buffer()\n\n\ntemplate<typename T, typename Space>\n template<typename InputIterator>\n raw_buffer<T,Space>\n ::raw_buffer(InputIterator first, InputIterator last)\n{\n size_type n = thrust::distance(first,last);\n m_begin = m_allocator.allocate(n);\n m_end = m_begin + n;\n thrust::copy(first, last, begin());\n} \/\/ end raw_buffer::raw_buffer()\n\n\ntemplate<typename T, typename Space>\n raw_buffer<T,Space>\n ::~raw_buffer(void)\n{\n if(size() > 0)\n {\n m_allocator.deallocate(&*m_begin, size());\n m_begin = m_end = pointer(static_cast<T*>(0));\n } \/\/ end if\n} \/\/ end raw_buffer::~raw_buffer()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::size_type raw_buffer<T,Space>\n ::size(void) const\n{\n return m_end - m_begin;\n} \/\/ end raw_buffer::size()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::iterator raw_buffer<T,Space>\n ::begin(void)\n{\n return m_begin;\n} \/\/ end raw_buffer::begin()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>\n ::begin(void) const\n{\n return m_begin;\n} \/\/ end raw_buffer::begin()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>\n ::cbegin(void) const\n{\n return m_begin;\n} \/\/ end raw_buffer::cbegin()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::iterator raw_buffer<T,Space>\n ::end(void)\n{\n return m_end;\n} \/\/ end raw_buffer::end()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>\n ::end(void) const\n{\n return m_end;\n} \/\/ end raw_buffer::end()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>\n ::cend(void) const\n{\n return m_end;\n} \/\/ end raw_buffer::cend()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::reference raw_buffer<T,Space>\n ::operator[](size_type n)\n{\n return m_begin[n];\n} \/\/ end raw_buffer::operator[]()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_reference raw_buffer<T,Space>\n ::operator[](size_type n) const\n{\n return m_begin[n];\n} \/\/ end raw_buffer::operator[]()\n\n\n} \/\/ end detail\n\n} \/\/ end thrust\n\n<commit_msg>Simplify raw_buffer's destructor just a tad.<commit_after>\/*\n * Copyright 2008-2009 NVIDIA Corporation\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#include <thrust\/detail\/raw_buffer.h>\n#include <thrust\/distance.h>\n#include <thrust\/copy.h>\n\n\nnamespace thrust\n{\n\nnamespace detail\n{\n\n\ntemplate<typename T, typename Space>\n raw_buffer<T,Space>\n ::raw_buffer(size_type n)\n{\n m_begin = m_allocator.allocate(n);\n m_end = m_begin + n;\n} \/\/ end raw_buffer::raw_buffer()\n\n\ntemplate<typename T, typename Space>\n template<typename InputIterator>\n raw_buffer<T,Space>\n ::raw_buffer(InputIterator first, InputIterator last)\n{\n size_type n = thrust::distance(first,last);\n m_begin = m_allocator.allocate(n);\n m_end = m_begin + n;\n thrust::copy(first, last, begin());\n} \/\/ end raw_buffer::raw_buffer()\n\n\ntemplate<typename T, typename Space>\n raw_buffer<T,Space>\n ::~raw_buffer(void)\n{\n if(size() > 0)\n {\n m_allocator.deallocate(&*m_begin, size());\n m_end = m_begin;\n } \/\/ end if\n} \/\/ end raw_buffer::~raw_buffer()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::size_type raw_buffer<T,Space>\n ::size(void) const\n{\n return m_end - m_begin;\n} \/\/ end raw_buffer::size()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::iterator raw_buffer<T,Space>\n ::begin(void)\n{\n return m_begin;\n} \/\/ end raw_buffer::begin()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>\n ::begin(void) const\n{\n return m_begin;\n} \/\/ end raw_buffer::begin()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>\n ::cbegin(void) const\n{\n return m_begin;\n} \/\/ end raw_buffer::cbegin()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::iterator raw_buffer<T,Space>\n ::end(void)\n{\n return m_end;\n} \/\/ end raw_buffer::end()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>\n ::end(void) const\n{\n return m_end;\n} \/\/ end raw_buffer::end()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>\n ::cend(void) const\n{\n return m_end;\n} \/\/ end raw_buffer::cend()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::reference raw_buffer<T,Space>\n ::operator[](size_type n)\n{\n return m_begin[n];\n} \/\/ end raw_buffer::operator[]()\n\n\ntemplate<typename T, typename Space>\n typename raw_buffer<T,Space>::const_reference raw_buffer<T,Space>\n ::operator[](size_type n) const\n{\n return m_begin[n];\n} \/\/ end raw_buffer::operator[]()\n\n\n} \/\/ end detail\n\n} \/\/ end thrust\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2009 NVIDIA Corporation\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\/*! \\file arch.inl\n * \\brief Inline file for arch.h.\n *\/\n\n#include <string>\n#include <algorithm>\n\n#include <thrust\/detail\/util\/blocking.h>\n\n\/\/ #include this for make_uint3\n#include <vector_functions.h>\n\n\/\/ #include this for runtime_error\n#include <stdexcept>\n\nnamespace thrust\n{\nnamespace experimental\n{\nnamespace arch\n{\nnamespace detail\n{\n\ninline void checked_get_current_device_properties(cudaDeviceProp &props)\n{\n int current_device = -1;\n\n cudaError_t error = cudaGetDevice(¤t_device);\n\n if(error)\n throw std::runtime_error(std::string(\"CUDA error: \") + std::string(cudaGetErrorString(error)));\n\n if(current_device < 0)\n throw std::runtime_error(std::string(\"No CUDA device found.\"));\n \n error = cudaGetDeviceProperties(&props, current_device);\n\n if(error != cudaSuccess)\n throw std::runtime_error(std::string(\"CUDA error: \") + std::string(cudaGetErrorString(error)));\n} \/\/ end checked_get_current_device_properties()\n\ntemplate <typename KernelFunction>\nvoid checked_get_function_attributes(cudaFuncAttributes& attributes, KernelFunction kernel)\n{\n cudaError_t error = cudaFuncGetAttributes(&attributes, kernel);\n\n if(error != cudaSuccess)\n throw std::runtime_error(std::string(\"CUDA error: \") + std::string(cudaGetErrorString(error)));\n} \/\/ end checked_get_function_attributes()\n\n} \/\/ end detail\n\n\nsize_t num_multiprocessors(const cudaDeviceProp& properties)\n{\n return properties.multiProcessorCount;\n} \/\/ end num_multiprocessors()\n\n\nsize_t max_active_threads_per_multiprocessor(const cudaDeviceProp& properties)\n{\n \/\/ index this array by [major, minor] revision\n \/\/ \\see NVIDIA_CUDA_Programming_Guide_2.1.pdf pp 82--83\n static const size_t max_active_threads_by_compute_capability[2][4] = \\\n {{ 0, 0, 0, 0},\n { 768, 768, 1024, 1024}};\n\n \/\/ produce valid results for new, unknown devices\n if (properties.major > 1 || properties.minor > 3)\n return max_active_threads_by_compute_capability[1][3];\n else\n return max_active_threads_by_compute_capability[properties.major][properties.minor];\n} \/\/ end max_active_threads_per_multiprocessor()\n\n\nsize_t max_active_threads(const cudaDeviceProp& properties)\n{\n return num_multiprocessors(properties) * max_active_threads_per_multiprocessor(properties);\n} \/\/ end max_active_threads()\n\n\ndim3 max_grid_dimensions(const cudaDeviceProp& properties)\n{\n return make_uint3(properties.maxGridSize[0], properties.maxGridSize[1], properties.maxGridSize[2]);\n} \/\/ end max_grid_dimensions()\n \n\nsize_t max_active_blocks_per_multiprocessor(const cudaDeviceProp& properties,\n const cudaFuncAttributes& attributes,\n size_t CTA_SIZE,\n size_t dynamic_smem_bytes)\n{\n \/\/ Determine the maximum number of CTAs that can be run simultaneously per SM\n \/\/ This is equivalent to the calculation done in the CUDA Occupancy Calculator spreadsheet\n const size_t regAllocationUnit = (properties.major < 2 && properties.minor < 2) ? 256 : 512; \/\/ in registers\n const size_t warpAllocationMultiple = 2;\n const size_t smemAllocationUnit = 512; \/\/ in bytes\n const size_t maxThreadsPerSM = max_active_threads_per_multiprocessor(properties); \/\/ 768, 1024, etc.\n const size_t maxBlocksPerSM = 8;\n\n \/\/ Number of warps (round up to nearest whole multiple of warp size & warp allocation multiple)\n const size_t numWarps = thrust::detail::util::round_i(thrust::detail::util::divide_ri(CTA_SIZE, properties.warpSize), warpAllocationMultiple);\n\n \/\/ Number of regs is regs per thread times number of warps times warp size\n const size_t regsPerCTA = thrust::detail::util::round_i(attributes.numRegs * properties.warpSize * numWarps, regAllocationUnit);\n\n const size_t smemBytes = attributes.sharedSizeBytes + dynamic_smem_bytes;\n const size_t smemPerCTA = thrust::detail::util::round_i(smemBytes, smemAllocationUnit);\n\n const size_t ctaLimitRegs = regsPerCTA > 0 ? properties.regsPerBlock \/ regsPerCTA : maxBlocksPerSM;\n const size_t ctaLimitSMem = smemPerCTA > 0 ? properties.sharedMemPerBlock \/ smemPerCTA : maxBlocksPerSM;\n const size_t ctaLimitThreads = maxThreadsPerSM \/ CTA_SIZE;\n\n return std::min<size_t>(ctaLimitRegs, std::min<size_t>(ctaLimitSMem, std::min<size_t>(ctaLimitThreads, maxBlocksPerSM)));\n}\n\n\n\n\/\/ Functions that query the runtime for device properties\n\nsize_t num_multiprocessors(void)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n return num_multiprocessors(properties);\n} \/\/ end num_multiprocessors()\n\nsize_t max_active_threads_per_multiprocessor(void)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n return max_active_threads_per_multiprocessor(properties);\n}\n\nsize_t max_active_threads(void)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n return max_active_threads(properties);\n}\n\ndim3 max_grid_dimensions(void)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n return max_grid_dimensions(properties);\n}\n\ntemplate <typename KernelFunction>\nsize_t max_active_blocks(KernelFunction kernel, const size_t CTA_SIZE, const size_t dynamic_smem_bytes)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n\n cudaFuncAttributes attributes;\n detail::checked_get_function_attributes(attributes, kernel);\n\n return num_multiprocessors(properties) * max_active_blocks_per_multiprocessor(properties, attributes, CTA_SIZE, dynamic_smem_bytes);\n}\n\nsize_t max_blocksize_with_highest_occupancy(const cudaDeviceProp& properties,\n const cudaFuncAttributes& attributes,\n size_t dynamic_smem_bytes_per_thread)\n{\n size_t max_occupancy = max_active_threads_per_multiprocessor(properties);\n\n size_t largest_blocksize = std::min(properties.maxThreadsPerBlock, attributes.maxThreadsPerBlock);\n size_t granularity = 32;\n\n size_t max_blocksize = 0;\n size_t highest_occupancy = 0;\n\n for(size_t blocksize = largest_blocksize; blocksize != 0; blocksize -= granularity)\n {\n size_t occupancy = blocksize * max_active_blocks_per_multiprocessor(properties, attributes, blocksize, dynamic_smem_bytes_per_thread * blocksize);\n\n if (occupancy > highest_occupancy)\n {\n max_blocksize = blocksize;\n highest_occupancy = occupancy;\n }\n\n \/\/ early out, can't do better\n if (highest_occupancy == max_occupancy)\n return max_blocksize;\n }\n\n return max_blocksize;\n}\n\ntemplate <typename KernelFunction>\nsize_t max_blocksize_with_highest_occupancy(KernelFunction kernel, size_t dynamic_smem_bytes_per_thread)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n\n cudaFuncAttributes attributes;\n detail::checked_get_function_attributes(attributes, kernel);\n\n return max_blocksize_with_highest_occupancy(properties, attributes, dynamic_smem_bytes_per_thread);\n}\n\n\n\/\/ TODO unify this with max_blocksize_with_highest_occupancy\nsize_t max_blocksize(const cudaDeviceProp& properties,\n const cudaFuncAttributes& attributes,\n size_t dynamic_smem_bytes_per_thread)\n{\n size_t max_occupancy = max_active_threads_per_multiprocessor(properties);\n\n size_t largest_blocksize = std::min(properties.maxThreadsPerBlock, attributes.maxThreadsPerBlock);\n size_t granularity = 32;\n\n for(size_t blocksize = largest_blocksize; blocksize != 0; blocksize -= granularity)\n {\n if(0 < max_active_blocks_per_multiprocessor(properties, attributes, blocksize, dynamic_smem_bytes_per_thread * blocksize))\n return blocksize;\n }\n\n return 0;\n}\n\ntemplate <typename KernelFunction>\nsize_t max_blocksize(KernelFunction kernel, size_t dynamic_smem_bytes_per_thread)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n\n cudaFuncAttributes attributes;\n detail::checked_get_function_attributes(attributes, kernel);\n\n return max_blocksize(properties, attributes, dynamic_smem_bytes_per_thread);\n}\n\n} \/\/ end namespace arch\n} \/\/ end namespace experimental\n} \/\/ end namespace thrust\n\n<commit_msg>Eliminate unused variable from arch::max_blocksize<commit_after>\/*\n * Copyright 2008-2009 NVIDIA Corporation\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\/*! \\file arch.inl\n * \\brief Inline file for arch.h.\n *\/\n\n#include <string>\n#include <algorithm>\n\n#include <thrust\/detail\/util\/blocking.h>\n\n\/\/ #include this for make_uint3\n#include <vector_functions.h>\n\n\/\/ #include this for runtime_error\n#include <stdexcept>\n\nnamespace thrust\n{\nnamespace experimental\n{\nnamespace arch\n{\nnamespace detail\n{\n\ninline void checked_get_current_device_properties(cudaDeviceProp &props)\n{\n int current_device = -1;\n\n cudaError_t error = cudaGetDevice(¤t_device);\n\n if(error)\n throw std::runtime_error(std::string(\"CUDA error: \") + std::string(cudaGetErrorString(error)));\n\n if(current_device < 0)\n throw std::runtime_error(std::string(\"No CUDA device found.\"));\n \n error = cudaGetDeviceProperties(&props, current_device);\n\n if(error != cudaSuccess)\n throw std::runtime_error(std::string(\"CUDA error: \") + std::string(cudaGetErrorString(error)));\n} \/\/ end checked_get_current_device_properties()\n\ntemplate <typename KernelFunction>\nvoid checked_get_function_attributes(cudaFuncAttributes& attributes, KernelFunction kernel)\n{\n cudaError_t error = cudaFuncGetAttributes(&attributes, kernel);\n\n if(error != cudaSuccess)\n throw std::runtime_error(std::string(\"CUDA error: \") + std::string(cudaGetErrorString(error)));\n} \/\/ end checked_get_function_attributes()\n\n} \/\/ end detail\n\n\nsize_t num_multiprocessors(const cudaDeviceProp& properties)\n{\n return properties.multiProcessorCount;\n} \/\/ end num_multiprocessors()\n\n\nsize_t max_active_threads_per_multiprocessor(const cudaDeviceProp& properties)\n{\n \/\/ index this array by [major, minor] revision\n \/\/ \\see NVIDIA_CUDA_Programming_Guide_2.1.pdf pp 82--83\n static const size_t max_active_threads_by_compute_capability[2][4] = \\\n {{ 0, 0, 0, 0},\n { 768, 768, 1024, 1024}};\n\n \/\/ produce valid results for new, unknown devices\n if (properties.major > 1 || properties.minor > 3)\n return max_active_threads_by_compute_capability[1][3];\n else\n return max_active_threads_by_compute_capability[properties.major][properties.minor];\n} \/\/ end max_active_threads_per_multiprocessor()\n\n\nsize_t max_active_threads(const cudaDeviceProp& properties)\n{\n return num_multiprocessors(properties) * max_active_threads_per_multiprocessor(properties);\n} \/\/ end max_active_threads()\n\n\ndim3 max_grid_dimensions(const cudaDeviceProp& properties)\n{\n return make_uint3(properties.maxGridSize[0], properties.maxGridSize[1], properties.maxGridSize[2]);\n} \/\/ end max_grid_dimensions()\n \n\nsize_t max_active_blocks_per_multiprocessor(const cudaDeviceProp& properties,\n const cudaFuncAttributes& attributes,\n size_t CTA_SIZE,\n size_t dynamic_smem_bytes)\n{\n \/\/ Determine the maximum number of CTAs that can be run simultaneously per SM\n \/\/ This is equivalent to the calculation done in the CUDA Occupancy Calculator spreadsheet\n const size_t regAllocationUnit = (properties.major < 2 && properties.minor < 2) ? 256 : 512; \/\/ in registers\n const size_t warpAllocationMultiple = 2;\n const size_t smemAllocationUnit = 512; \/\/ in bytes\n const size_t maxThreadsPerSM = max_active_threads_per_multiprocessor(properties); \/\/ 768, 1024, etc.\n const size_t maxBlocksPerSM = 8;\n\n \/\/ Number of warps (round up to nearest whole multiple of warp size & warp allocation multiple)\n const size_t numWarps = thrust::detail::util::round_i(thrust::detail::util::divide_ri(CTA_SIZE, properties.warpSize), warpAllocationMultiple);\n\n \/\/ Number of regs is regs per thread times number of warps times warp size\n const size_t regsPerCTA = thrust::detail::util::round_i(attributes.numRegs * properties.warpSize * numWarps, regAllocationUnit);\n\n const size_t smemBytes = attributes.sharedSizeBytes + dynamic_smem_bytes;\n const size_t smemPerCTA = thrust::detail::util::round_i(smemBytes, smemAllocationUnit);\n\n const size_t ctaLimitRegs = regsPerCTA > 0 ? properties.regsPerBlock \/ regsPerCTA : maxBlocksPerSM;\n const size_t ctaLimitSMem = smemPerCTA > 0 ? properties.sharedMemPerBlock \/ smemPerCTA : maxBlocksPerSM;\n const size_t ctaLimitThreads = maxThreadsPerSM \/ CTA_SIZE;\n\n return std::min<size_t>(ctaLimitRegs, std::min<size_t>(ctaLimitSMem, std::min<size_t>(ctaLimitThreads, maxBlocksPerSM)));\n}\n\n\n\n\/\/ Functions that query the runtime for device properties\n\nsize_t num_multiprocessors(void)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n return num_multiprocessors(properties);\n} \/\/ end num_multiprocessors()\n\nsize_t max_active_threads_per_multiprocessor(void)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n return max_active_threads_per_multiprocessor(properties);\n}\n\nsize_t max_active_threads(void)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n return max_active_threads(properties);\n}\n\ndim3 max_grid_dimensions(void)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n return max_grid_dimensions(properties);\n}\n\ntemplate <typename KernelFunction>\nsize_t max_active_blocks(KernelFunction kernel, const size_t CTA_SIZE, const size_t dynamic_smem_bytes)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n\n cudaFuncAttributes attributes;\n detail::checked_get_function_attributes(attributes, kernel);\n\n return num_multiprocessors(properties) * max_active_blocks_per_multiprocessor(properties, attributes, CTA_SIZE, dynamic_smem_bytes);\n}\n\nsize_t max_blocksize_with_highest_occupancy(const cudaDeviceProp& properties,\n const cudaFuncAttributes& attributes,\n size_t dynamic_smem_bytes_per_thread)\n{\n size_t max_occupancy = max_active_threads_per_multiprocessor(properties);\n\n size_t largest_blocksize = std::min(properties.maxThreadsPerBlock, attributes.maxThreadsPerBlock);\n size_t granularity = 32;\n\n size_t max_blocksize = 0;\n size_t highest_occupancy = 0;\n\n for(size_t blocksize = largest_blocksize; blocksize != 0; blocksize -= granularity)\n {\n size_t occupancy = blocksize * max_active_blocks_per_multiprocessor(properties, attributes, blocksize, dynamic_smem_bytes_per_thread * blocksize);\n\n if (occupancy > highest_occupancy)\n {\n max_blocksize = blocksize;\n highest_occupancy = occupancy;\n }\n\n \/\/ early out, can't do better\n if (highest_occupancy == max_occupancy)\n return max_blocksize;\n }\n\n return max_blocksize;\n}\n\ntemplate <typename KernelFunction>\nsize_t max_blocksize_with_highest_occupancy(KernelFunction kernel, size_t dynamic_smem_bytes_per_thread)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n\n cudaFuncAttributes attributes;\n detail::checked_get_function_attributes(attributes, kernel);\n\n return max_blocksize_with_highest_occupancy(properties, attributes, dynamic_smem_bytes_per_thread);\n}\n\n\n\/\/ TODO unify this with max_blocksize_with_highest_occupancy\nsize_t max_blocksize(const cudaDeviceProp& properties,\n const cudaFuncAttributes& attributes,\n size_t dynamic_smem_bytes_per_thread)\n{\n size_t largest_blocksize = std::min(properties.maxThreadsPerBlock, attributes.maxThreadsPerBlock);\n size_t granularity = 32;\n\n for(size_t blocksize = largest_blocksize; blocksize != 0; blocksize -= granularity)\n {\n if(0 < max_active_blocks_per_multiprocessor(properties, attributes, blocksize, dynamic_smem_bytes_per_thread * blocksize))\n return blocksize;\n }\n\n return 0;\n}\n\ntemplate <typename KernelFunction>\nsize_t max_blocksize(KernelFunction kernel, size_t dynamic_smem_bytes_per_thread)\n{\n cudaDeviceProp properties; \n detail::checked_get_current_device_properties(properties);\n\n cudaFuncAttributes attributes;\n detail::checked_get_function_attributes(attributes, kernel);\n\n return max_blocksize(properties, attributes, dynamic_smem_bytes_per_thread);\n}\n\n} \/\/ end namespace arch\n} \/\/ end namespace experimental\n} \/\/ end namespace thrust\n\n<|endoftext|>"} {"text":"<commit_before>#include \"tools\/cabana\/chartswidget.h\"\n\n#include <QGraphicsLayout>\n#include <QLabel>\n#include <QPushButton>\n#include <QRubberBand>\n#include <QStackedLayout>\n#include <QtCharts\/QLineSeries>\n#include <QtCharts\/QValueAxis>\n\nint64_t get_raw_value(uint8_t *data, size_t data_size, const Signal &sig) {\n int64_t ret = 0;\n\n int i = sig.msb \/ 8;\n int bits = sig.size;\n while (i >= 0 && i < data_size && bits > 0) {\n int lsb = (int)(sig.lsb \/ 8) == i ? sig.lsb : i * 8;\n int msb = (int)(sig.msb \/ 8) == i ? sig.msb : (i + 1) * 8 - 1;\n int size = msb - lsb + 1;\n\n uint64_t d = (data[i] >> (lsb - (i * 8))) & ((1ULL << size) - 1);\n ret |= d << (bits - size);\n\n bits -= size;\n i = sig.is_little_endian ? i - 1 : i + 1;\n }\n return ret;\n}\n\nChartsWidget::ChartsWidget(QWidget *parent) : QWidget(parent) {\n main_layout = new QVBoxLayout(this);\n main_layout->setContentsMargins(0, 0, 0, 0);\n connect(parser, &Parser::showPlot, this, &ChartsWidget::addChart);\n connect(parser, &Parser::hidePlot, this, &ChartsWidget::removeChart);\n connect(parser, &Parser::signalRemoved, this, &ChartsWidget::removeChart);\n}\n\nvoid ChartsWidget::addChart(const QString &id, const QString &sig_name) {\n const QString char_name = id + sig_name;\n if (charts.find(char_name) == charts.end()) {\n auto chart = new ChartWidget(id, sig_name, this);\n main_layout->insertWidget(0, chart);\n charts[char_name] = chart;\n }\n}\n\nvoid ChartsWidget::removeChart(const QString &id, const QString &sig_name) {\n if (auto it = charts.find(id + sig_name); it != charts.end()) {\n it->second->deleteLater();\n charts.erase(it);\n }\n}\n\nChartWidget::ChartWidget(const QString &id, const QString &sig_name, QWidget *parent) : id(id), sig_name(sig_name), QWidget(parent) {\n QStackedLayout *stacked = new QStackedLayout(this);\n stacked->setStackingMode(QStackedLayout::StackAll);\n\n QWidget *chart_widget = new QWidget(this);\n QVBoxLayout *chart_layout = new QVBoxLayout(chart_widget);\n chart_layout->setSpacing(0);\n chart_layout->setContentsMargins(0, 0, 0, 0);\n\n QWidget *header = new QWidget(this);\n header->setStyleSheet(\"background-color:white\");\n QHBoxLayout *header_layout = new QHBoxLayout(header);\n header_layout->setContentsMargins(11, 11, 11, 0);\n auto title = new QLabel(tr(\"%1 %2\").arg(parser->getMsg(id)->name.c_str()).arg(id));\n header_layout->addWidget(title);\n header_layout->addStretch();\n zoom_label = new QLabel(\"\", this);\n header_layout->addWidget(zoom_label);\n QPushButton *zoom_in = new QPushButton(\"↺\", this);\n zoom_in->setToolTip(tr(\"reset zoom\"));\n QObject::connect(zoom_in, &QPushButton::clicked, []() { parser->resetRange(); });\n header_layout->addWidget(zoom_in);\n\n QPushButton *remove_btn = new QPushButton(\"✖\", this);\n QObject::connect(remove_btn, &QPushButton::clicked, [=]() {\n emit parser->hidePlot(id, sig_name);\n });\n header_layout->addWidget(remove_btn);\n chart_layout->addWidget(header);\n\n QLineSeries *series = new QLineSeries();\n series->setUseOpenGL(true);\n auto chart = new QChart();\n chart->setTitle(sig_name);\n chart->addSeries(series);\n chart->createDefaultAxes();\n chart->legend()->hide();\n QFont font;\n font.setBold(true);\n chart->setTitleFont(font);\n chart->setMargins({0, 0, 0, 0});\n chart->layout()->setContentsMargins(0, 0, 0, 0);\n QObject::connect(dynamic_cast<QValueAxis *>(chart->axisX()), &QValueAxis::rangeChanged, parser, &Parser::setRange);\n\n chart_view = new QChartView(chart);\n chart_view->setFixedHeight(300);\n chart_view->setRenderHint(QPainter::Antialiasing);\n chart_view->setRubberBand(QChartView::HorizontalRubberBand);\n if (auto rubber = chart_view->findChild<QRubberBand *>()) {\n QPalette pal;\n pal.setBrush(QPalette::Base, QColor(0, 0, 0, 80));\n rubber->setPalette(pal);\n }\n chart_layout->addWidget(chart_view);\n chart_layout->addStretch();\n\n stacked->addWidget(chart_widget);\n line_marker = new LineMarker(chart, this);\n stacked->addWidget(line_marker);\n line_marker->setAttribute(Qt::WA_TransparentForMouseEvents, true);\n line_marker->raise();\n\n setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n QObject::connect(parser, &Parser::updated, this, &ChartWidget::updateState);\n QObject::connect(parser, &Parser::rangeChanged, this, &ChartWidget::rangeChanged);\n QObject::connect(parser, &Parser::eventsMerged, this, &ChartWidget::updateSeries);\n\n updateSeries();\n}\n\nvoid ChartWidget::updateState() {\n line_marker->update();\n}\n\nvoid ChartWidget::updateSeries() {\n const Signal *sig = parser->getSig(id, sig_name);\n auto events = parser->replay->events();\n if (!sig || !events) return;\n\n auto l = id.split(':');\n int bus = l[0].toInt();\n uint32_t address = l[1].toUInt(nullptr, 16);\n\n vals.clear();\n vals.reserve(3 * 60 * 100);\n uint64_t route_start_time = parser->replay->routeStartTime();\n for (auto &evt : *events) {\n if (evt->which == cereal::Event::Which::CAN) {\n for (auto c : evt->event.getCan()) {\n if (bus == c.getSrc() && address == c.getAddress()) {\n auto dat = c.getDat();\n int64_t val = get_raw_value((uint8_t *)dat.begin(), dat.size(), *sig);\n if (sig->is_signed) {\n val -= ((val >> (sig->size - 1)) & 0x1) ? (1ULL << sig->size) : 0;\n }\n double value = val * sig->factor + sig->offset;\n double ts = (evt->mono_time - route_start_time) \/ (double)1e9; \/\/ seconds\n vals.push_back({ts, value});\n }\n }\n }\n }\n QLineSeries *series = (QLineSeries *)chart_view->chart()->series()[0];\n series->replace(vals);\n auto [begin, end] = parser->range();\n chart_view->chart()->axisX()->setRange(begin, end);\n}\n\nvoid ChartWidget::rangeChanged(qreal min, qreal max) {\n auto axis_x = dynamic_cast<QValueAxis *>(chart_view->chart()->axisX());\n if (axis_x->min() != min || axis_x->max() != max) {\n axis_x->setRange(min, max);\n }\n \/\/ auto zoom on yaxis\n double min_y = 0, max_y = 0;\n for (auto &p : vals) {\n if (p.x() > max) break;\n\n if (p.x() >= min) {\n if (p.y() < min_y) min_y = p.y();\n if (p.y() > max_y) max_y = p.y();\n }\n }\n chart_view->chart()->axisY()->setRange(min_y * 0.95, max_y * 1.05);\n}\n\nLineMarker::LineMarker(QChart *chart, QWidget *parent) : chart(chart), QWidget(parent) {}\n\nvoid LineMarker::paintEvent(QPaintEvent *event) {\n auto axis_x = dynamic_cast<QValueAxis *>(chart->axisX());\n if (axis_x->max() <= axis_x->min()) return;\n\n double x = chart->plotArea().left() + chart->plotArea().width() * (parser->currentSec() - axis_x->min()) \/ (axis_x->max() - axis_x->min());\n QPainter p(this);\n QPen pen = QPen(Qt::black);\n pen.setWidth(2);\n p.setPen(pen);\n p.drawLine(QPointF{x, 50.}, QPointF{x, (qreal)height() - 11});\n}\n<commit_msg>cabana: Fix the incorrect Y axis (#25984)<commit_after>#include \"tools\/cabana\/chartswidget.h\"\n\n#include <QGraphicsLayout>\n#include <QLabel>\n#include <QPushButton>\n#include <QRubberBand>\n#include <QStackedLayout>\n#include <QtCharts\/QLineSeries>\n#include <QtCharts\/QValueAxis>\n\nint64_t get_raw_value(uint8_t *data, size_t data_size, const Signal &sig) {\n int64_t ret = 0;\n\n int i = sig.msb \/ 8;\n int bits = sig.size;\n while (i >= 0 && i < data_size && bits > 0) {\n int lsb = (int)(sig.lsb \/ 8) == i ? sig.lsb : i * 8;\n int msb = (int)(sig.msb \/ 8) == i ? sig.msb : (i + 1) * 8 - 1;\n int size = msb - lsb + 1;\n\n uint64_t d = (data[i] >> (lsb - (i * 8))) & ((1ULL << size) - 1);\n ret |= d << (bits - size);\n\n bits -= size;\n i = sig.is_little_endian ? i - 1 : i + 1;\n }\n return ret;\n}\n\nChartsWidget::ChartsWidget(QWidget *parent) : QWidget(parent) {\n main_layout = new QVBoxLayout(this);\n main_layout->setContentsMargins(0, 0, 0, 0);\n connect(parser, &Parser::showPlot, this, &ChartsWidget::addChart);\n connect(parser, &Parser::hidePlot, this, &ChartsWidget::removeChart);\n connect(parser, &Parser::signalRemoved, this, &ChartsWidget::removeChart);\n}\n\nvoid ChartsWidget::addChart(const QString &id, const QString &sig_name) {\n const QString char_name = id + sig_name;\n if (charts.find(char_name) == charts.end()) {\n auto chart = new ChartWidget(id, sig_name, this);\n main_layout->insertWidget(0, chart);\n charts[char_name] = chart;\n }\n}\n\nvoid ChartsWidget::removeChart(const QString &id, const QString &sig_name) {\n if (auto it = charts.find(id + sig_name); it != charts.end()) {\n it->second->deleteLater();\n charts.erase(it);\n }\n}\n\nChartWidget::ChartWidget(const QString &id, const QString &sig_name, QWidget *parent) : id(id), sig_name(sig_name), QWidget(parent) {\n QStackedLayout *stacked = new QStackedLayout(this);\n stacked->setStackingMode(QStackedLayout::StackAll);\n\n QWidget *chart_widget = new QWidget(this);\n QVBoxLayout *chart_layout = new QVBoxLayout(chart_widget);\n chart_layout->setSpacing(0);\n chart_layout->setContentsMargins(0, 0, 0, 0);\n\n QWidget *header = new QWidget(this);\n header->setStyleSheet(\"background-color:white\");\n QHBoxLayout *header_layout = new QHBoxLayout(header);\n header_layout->setContentsMargins(11, 11, 11, 0);\n auto title = new QLabel(tr(\"%1 %2\").arg(parser->getMsg(id)->name.c_str()).arg(id));\n header_layout->addWidget(title);\n header_layout->addStretch();\n zoom_label = new QLabel(\"\", this);\n header_layout->addWidget(zoom_label);\n QPushButton *zoom_in = new QPushButton(\"↺\", this);\n zoom_in->setToolTip(tr(\"reset zoom\"));\n QObject::connect(zoom_in, &QPushButton::clicked, []() { parser->resetRange(); });\n header_layout->addWidget(zoom_in);\n\n QPushButton *remove_btn = new QPushButton(\"✖\", this);\n QObject::connect(remove_btn, &QPushButton::clicked, [=]() {\n emit parser->hidePlot(id, sig_name);\n });\n header_layout->addWidget(remove_btn);\n chart_layout->addWidget(header);\n\n QLineSeries *series = new QLineSeries();\n series->setUseOpenGL(true);\n auto chart = new QChart();\n chart->setTitle(sig_name);\n chart->addSeries(series);\n chart->createDefaultAxes();\n chart->legend()->hide();\n QFont font;\n font.setBold(true);\n chart->setTitleFont(font);\n chart->setMargins({0, 0, 0, 0});\n chart->layout()->setContentsMargins(0, 0, 0, 0);\n QObject::connect(dynamic_cast<QValueAxis *>(chart->axisX()), &QValueAxis::rangeChanged, parser, &Parser::setRange);\n\n chart_view = new QChartView(chart);\n chart_view->setFixedHeight(300);\n chart_view->setRenderHint(QPainter::Antialiasing);\n chart_view->setRubberBand(QChartView::HorizontalRubberBand);\n if (auto rubber = chart_view->findChild<QRubberBand *>()) {\n QPalette pal;\n pal.setBrush(QPalette::Base, QColor(0, 0, 0, 80));\n rubber->setPalette(pal);\n }\n chart_layout->addWidget(chart_view);\n chart_layout->addStretch();\n\n stacked->addWidget(chart_widget);\n line_marker = new LineMarker(chart, this);\n stacked->addWidget(line_marker);\n line_marker->setAttribute(Qt::WA_TransparentForMouseEvents, true);\n line_marker->raise();\n\n setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n QObject::connect(parser, &Parser::updated, this, &ChartWidget::updateState);\n QObject::connect(parser, &Parser::rangeChanged, this, &ChartWidget::rangeChanged);\n QObject::connect(parser, &Parser::eventsMerged, this, &ChartWidget::updateSeries);\n\n updateSeries();\n}\n\nvoid ChartWidget::updateState() {\n line_marker->update();\n}\n\nvoid ChartWidget::updateSeries() {\n const Signal *sig = parser->getSig(id, sig_name);\n auto events = parser->replay->events();\n if (!sig || !events) return;\n\n auto l = id.split(':');\n int bus = l[0].toInt();\n uint32_t address = l[1].toUInt(nullptr, 16);\n\n vals.clear();\n vals.reserve(3 * 60 * 100);\n double min_y = 0, max_y = 0;\n uint64_t route_start_time = parser->replay->routeStartTime();\n for (auto &evt : *events) {\n if (evt->which == cereal::Event::Which::CAN) {\n for (auto c : evt->event.getCan()) {\n if (bus == c.getSrc() && address == c.getAddress()) {\n auto dat = c.getDat();\n int64_t val = get_raw_value((uint8_t *)dat.begin(), dat.size(), *sig);\n if (sig->is_signed) {\n val -= ((val >> (sig->size - 1)) & 0x1) ? (1ULL << sig->size) : 0;\n }\n double value = val * sig->factor + sig->offset;\n if (value < min_y) min_y = value;\n if (value > max_y) max_y = value;\n\n double ts = (evt->mono_time - route_start_time) \/ (double)1e9; \/\/ seconds\n vals.push_back({ts, value});\n }\n }\n }\n }\n QLineSeries *series = (QLineSeries *)chart_view->chart()->series()[0];\n series->replace(vals);\n auto [begin, end] = parser->range();\n chart_view->chart()->axisX()->setRange(begin, end);\n chart_view->chart()->axisY()->setRange(min_y * 0.95, max_y * 1.05);\n}\n\nvoid ChartWidget::rangeChanged(qreal min, qreal max) {\n auto axis_x = dynamic_cast<QValueAxis *>(chart_view->chart()->axisX());\n if (axis_x->min() != min || axis_x->max() != max) {\n axis_x->setRange(min, max);\n }\n \/\/ auto zoom on yaxis\n double min_y = 0, max_y = 0;\n for (auto &p : vals) {\n if (p.x() > max) break;\n\n if (p.x() >= min) {\n if (p.y() < min_y) min_y = p.y();\n if (p.y() > max_y) max_y = p.y();\n }\n }\n chart_view->chart()->axisY()->setRange(min_y * 0.95, max_y * 1.05);\n}\n\nLineMarker::LineMarker(QChart *chart, QWidget *parent) : chart(chart), QWidget(parent) {}\n\nvoid LineMarker::paintEvent(QPaintEvent *event) {\n auto axis_x = dynamic_cast<QValueAxis *>(chart->axisX());\n if (axis_x->max() <= axis_x->min()) return;\n\n double x = chart->plotArea().left() + chart->plotArea().width() * (parser->currentSec() - axis_x->min()) \/ (axis_x->max() - axis_x->min());\n QPainter p(this);\n QPen pen = QPen(Qt::black);\n pen.setWidth(2);\n p.setPen(pen);\n p.drawLine(QPointF{x, 50.}, QPointF{x, (qreal)height() - 11});\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/ui\/views\/menu_bar.h\"\n\n#include <memory>\n#include <set>\n#include <sstream>\n\n#include \"atom\/browser\/ui\/views\/submenu_button.h\"\n#include \"atom\/common\/keyboard_util.h\"\n#include \"ui\/base\/models\/menu_model.h\"\n#include \"ui\/views\/background.h\"\n#include \"ui\/views\/layout\/box_layout.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\n#if defined(USE_X11)\n#include \"chrome\/browser\/ui\/libgtkui\/gtk_util.h\"\n#endif\n\n#if defined(OS_WIN)\n#include \"ui\/gfx\/color_utils.h\"\n#endif\n\nnamespace atom {\n\nnamespace {\n\n\/\/ Default color of the menu bar.\nconst SkColor kDefaultColor = SkColorSetARGB(255, 233, 233, 233);\n\n} \/\/ namespace\n\nconst char MenuBar::kViewClassName[] = \"ElectronMenuBar\";\n\nMenuBarColorUpdater::MenuBarColorUpdater(MenuBar* menu_bar)\n : menu_bar_(menu_bar) {}\n\nMenuBarColorUpdater::~MenuBarColorUpdater() {}\n\nvoid MenuBarColorUpdater::OnDidChangeFocus(views::View* focused_before,\n views::View* focused_now) {\n if (menu_bar_) {\n \/\/ if we've changed window focus, update menu bar colors\n const auto had_focus = menu_bar_->has_focus_;\n menu_bar_->has_focus_ = focused_now != nullptr;\n if (menu_bar_->has_focus_ != had_focus)\n menu_bar_->UpdateViewColors();\n }\n}\n\nMenuBar::MenuBar(RootView* window)\n : background_color_(kDefaultColor),\n window_(window),\n color_updater_(new MenuBarColorUpdater(this)) {\n RefreshColorCache();\n UpdateViewColors();\n SetFocusBehavior(FocusBehavior::ALWAYS);\n SetLayoutManager(\n std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal));\n window_->GetFocusManager()->AddFocusChangeListener(color_updater_.get());\n}\n\nMenuBar::~MenuBar() {\n window_->GetFocusManager()->RemoveFocusChangeListener(color_updater_.get());\n}\n\nvoid MenuBar::SetMenu(AtomMenuModel* model) {\n menu_model_ = model;\n RebuildChildren();\n}\n\nvoid MenuBar::SetAcceleratorVisibility(bool visible) {\n for (auto* child : GetChildrenInZOrder())\n static_cast<SubmenuButton*>(child)->SetAcceleratorVisibility(visible);\n}\n\nMenuBar::View* MenuBar::FindAccelChild(base::char16 key) {\n for (auto* child : GetChildrenInZOrder()) {\n if (static_cast<SubmenuButton*>(child)->accelerator() == key)\n return child;\n }\n return nullptr;\n}\n\nbool MenuBar::HasAccelerator(base::char16 key) {\n return FindAccelChild(key) != nullptr;\n}\n\nvoid MenuBar::ActivateAccelerator(base::char16 key) {\n auto* child = FindAccelChild(key);\n if (child)\n static_cast<SubmenuButton*>(child)->Activate(nullptr);\n}\n\nint MenuBar::GetItemCount() const {\n return menu_model_ ? menu_model_->GetItemCount() : 0;\n}\n\nbool MenuBar::GetMenuButtonFromScreenPoint(const gfx::Point& screenPoint,\n AtomMenuModel** menu_model,\n views::MenuButton** button) {\n if (!GetBoundsInScreen().Contains(screenPoint))\n return false;\n\n auto children = GetChildrenInZOrder();\n for (int i = 0, n = children.size(); i < n; ++i) {\n if (children[i]->GetBoundsInScreen().Contains(screenPoint) &&\n (menu_model_->GetTypeAt(i) == AtomMenuModel::TYPE_SUBMENU)) {\n *menu_model = menu_model_->GetSubmenuModelAt(i);\n *button = static_cast<views::MenuButton*>(children[i]);\n return true;\n }\n }\n\n return false;\n}\n\nvoid MenuBar::OnBeforeExecuteCommand() {\n RemovePaneFocus();\n window_->RestoreFocus();\n}\n\nvoid MenuBar::OnMenuClosed() {\n SetAcceleratorVisibility(true);\n}\n\nbool MenuBar::AcceleratorPressed(const ui::Accelerator& accelerator) {\n views::View* focused_view = GetFocusManager()->GetFocusedView();\n if (!ContainsForFocusSearch(this, focused_view))\n return false;\n\n switch (accelerator.key_code()) {\n case ui::VKEY_MENU:\n case ui::VKEY_ESCAPE: {\n RemovePaneFocus();\n window_->RestoreFocus();\n return true;\n }\n case ui::VKEY_LEFT:\n GetFocusManager()->AdvanceFocus(true);\n return true;\n case ui::VKEY_RIGHT:\n GetFocusManager()->AdvanceFocus(false);\n return true;\n case ui::VKEY_HOME:\n GetFocusManager()->SetFocusedViewWithReason(\n GetFirstFocusableChild(), views::FocusManager::kReasonFocusTraversal);\n return true;\n case ui::VKEY_END:\n GetFocusManager()->SetFocusedViewWithReason(\n GetLastFocusableChild(), views::FocusManager::kReasonFocusTraversal);\n return true;\n default: {\n auto children = GetChildrenInZOrder();\n for (int i = 0, n = children.size(); i < n; ++i) {\n auto* button = static_cast<SubmenuButton*>(children[i]);\n bool shifted = false;\n auto keycode =\n atom::KeyboardCodeFromCharCode(button->accelerator(), &shifted);\n\n if (keycode == accelerator.key_code()) {\n const gfx::Point p(0, 0);\n auto event = accelerator.ToKeyEvent();\n OnMenuButtonClicked(button, p, &event);\n return true;\n }\n }\n\n return false;\n }\n }\n}\n\nbool MenuBar::SetPaneFocus(views::View* initial_focus) {\n bool result = views::AccessiblePaneView::SetPaneFocus(initial_focus);\n\n if (result) {\n auto children = GetChildrenInZOrder();\n std::set<ui::KeyboardCode> reg;\n for (int i = 0, n = children.size(); i < n; ++i) {\n auto* button = static_cast<SubmenuButton*>(children[i]);\n bool shifted = false;\n auto keycode =\n atom::KeyboardCodeFromCharCode(button->accelerator(), &shifted);\n\n \/\/ We want the menu items to activate if the user presses the accelerator\n \/\/ key, even without alt, since we are now focused on the menu bar\n if (keycode != ui::VKEY_UNKNOWN && reg.find(keycode) != reg.end()) {\n reg.insert(keycode);\n focus_manager()->RegisterAccelerator(\n ui::Accelerator(keycode, ui::EF_NONE),\n ui::AcceleratorManager::kNormalPriority, this);\n }\n }\n\n \/\/ We want to remove focus \/ hide menu bar when alt is pressed again\n focus_manager()->RegisterAccelerator(\n ui::Accelerator(ui::VKEY_MENU, ui::EF_ALT_DOWN),\n ui::AcceleratorManager::kNormalPriority, this);\n }\n\n return result;\n}\n\nvoid MenuBar::RemovePaneFocus() {\n views::AccessiblePaneView::RemovePaneFocus();\n SetAcceleratorVisibility(false);\n\n auto children = GetChildrenInZOrder();\n std::set<ui::KeyboardCode> unreg;\n for (int i = 0, n = children.size(); i < n; ++i) {\n auto* button = static_cast<SubmenuButton*>(children[i]);\n bool shifted = false;\n auto keycode =\n atom::KeyboardCodeFromCharCode(button->accelerator(), &shifted);\n\n if (keycode != ui::VKEY_UNKNOWN && unreg.find(keycode) != unreg.end()) {\n unreg.insert(keycode);\n focus_manager()->UnregisterAccelerator(\n ui::Accelerator(keycode, ui::EF_NONE), this);\n }\n }\n\n focus_manager()->UnregisterAccelerator(\n ui::Accelerator(ui::VKEY_MENU, ui::EF_ALT_DOWN), this);\n}\n\nconst char* MenuBar::GetClassName() const {\n return kViewClassName;\n}\n\nvoid MenuBar::OnMenuButtonClicked(views::MenuButton* source,\n const gfx::Point& point,\n const ui::Event* event) {\n \/\/ Hide the accelerator when a submenu is activated.\n SetAcceleratorVisibility(false);\n\n if (!menu_model_)\n return;\n\n if (!window_->HasFocus())\n window_->RequestFocus();\n\n int id = source->tag();\n AtomMenuModel::ItemType type = menu_model_->GetTypeAt(id);\n if (type != AtomMenuModel::TYPE_SUBMENU) {\n menu_model_->ActivatedAt(id, 0);\n return;\n }\n\n GetFocusManager()->SetFocusedViewWithReason(\n source, views::FocusManager::kReasonFocusTraversal);\n\n \/\/ Deleted in MenuDelegate::OnMenuClosed\n MenuDelegate* menu_delegate = new MenuDelegate(this);\n menu_delegate->RunMenu(menu_model_->GetSubmenuModelAt(id), source,\n event != nullptr && event->IsKeyEvent()\n ? ui::MENU_SOURCE_KEYBOARD\n : ui::MENU_SOURCE_MOUSE);\n menu_delegate->AddObserver(this);\n}\n\nvoid MenuBar::RefreshColorCache(const ui::NativeTheme* theme) {\n if (!theme)\n theme = ui::NativeTheme::GetInstanceForNativeUi();\n if (theme) {\n#if defined(USE_X11)\n background_color_ = libgtkui::GetBgColor(\"GtkMenuBar#menubar\");\n enabled_color_ = libgtkui::GetFgColor(\n \"GtkMenuBar#menubar GtkMenuItem#menuitem GtkLabel\");\n disabled_color_ = libgtkui::GetFgColor(\n \"GtkMenuBar#menubar GtkMenuItem#menuitem:disabled GtkLabel\");\n#else\n background_color_ =\n theme->GetSystemColor(ui::NativeTheme::kColorId_MenuBackgroundColor);\n#endif\n }\n#if defined(OS_WIN)\n background_color_ = color_utils::GetSysSkColor(COLOR_MENUBAR);\n#endif\n}\n\nvoid MenuBar::OnNativeThemeChanged(const ui::NativeTheme* theme) {\n RefreshColorCache(theme);\n UpdateViewColors();\n}\n\nvoid MenuBar::RebuildChildren() {\n RemoveAllChildViews(true);\n for (int i = 0, n = GetItemCount(); i < n; ++i) {\n auto* button =\n new SubmenuButton(menu_model_->GetLabelAt(i), this, background_color_);\n button->set_tag(i);\n AddChildView(button);\n }\n UpdateViewColors();\n}\n\nvoid MenuBar::UpdateViewColors() {\n \/\/ set menubar background color\n SetBackground(views::CreateSolidBackground(background_color_));\n\n \/\/ set child colors\n if (menu_model_ == nullptr)\n return;\n#if defined(USE_X11)\n const auto& textColor = has_focus_ ? enabled_color_ : disabled_color_;\n for (auto* child : GetChildrenInZOrder()) {\n auto* button = static_cast<SubmenuButton*>(child);\n button->SetTextColor(views::Button::STATE_NORMAL, textColor);\n button->SetTextColor(views::Button::STATE_DISABLED, disabled_color_);\n button->SetTextColor(views::Button::STATE_PRESSED, enabled_color_);\n button->SetTextColor(views::Button::STATE_HOVERED, textColor);\n button->SetUnderlineColor(textColor);\n }\n#elif defined(OS_WIN)\n for (auto* child : GetChildrenInZOrder()) {\n auto* button = static_cast<SubmenuButton*>(child);\n button->SetUnderlineColor(color_utils::GetSysSkColor(COLOR_MENUTEXT));\n }\n#endif\n}\n\n} \/\/ namespace atom\n<commit_msg>fix: check the root window in MenuBar::SetPanelFocus (#16581)<commit_after>\/\/ Copyright (c) 2014 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/ui\/views\/menu_bar.h\"\n\n#include <memory>\n#include <set>\n#include <sstream>\n\n#include \"atom\/browser\/ui\/views\/submenu_button.h\"\n#include \"atom\/common\/keyboard_util.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/models\/menu_model.h\"\n#include \"ui\/views\/background.h\"\n#include \"ui\/views\/layout\/box_layout.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\n#if defined(USE_X11)\n#include \"chrome\/browser\/ui\/libgtkui\/gtk_util.h\"\n#endif\n\n#if defined(OS_WIN)\n#include \"ui\/gfx\/color_utils.h\"\n#endif\n\nnamespace atom {\n\nnamespace {\n\n\/\/ Default color of the menu bar.\nconst SkColor kDefaultColor = SkColorSetARGB(255, 233, 233, 233);\n\n} \/\/ namespace\n\nconst char MenuBar::kViewClassName[] = \"ElectronMenuBar\";\n\nMenuBarColorUpdater::MenuBarColorUpdater(MenuBar* menu_bar)\n : menu_bar_(menu_bar) {}\n\nMenuBarColorUpdater::~MenuBarColorUpdater() {}\n\nvoid MenuBarColorUpdater::OnDidChangeFocus(views::View* focused_before,\n views::View* focused_now) {\n if (menu_bar_) {\n \/\/ if we've changed window focus, update menu bar colors\n const auto had_focus = menu_bar_->has_focus_;\n menu_bar_->has_focus_ = focused_now != nullptr;\n if (menu_bar_->has_focus_ != had_focus)\n menu_bar_->UpdateViewColors();\n }\n}\n\nMenuBar::MenuBar(RootView* window)\n : background_color_(kDefaultColor),\n window_(window),\n color_updater_(new MenuBarColorUpdater(this)) {\n RefreshColorCache();\n UpdateViewColors();\n SetFocusBehavior(FocusBehavior::ALWAYS);\n SetLayoutManager(\n std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal));\n window_->GetFocusManager()->AddFocusChangeListener(color_updater_.get());\n}\n\nMenuBar::~MenuBar() {\n window_->GetFocusManager()->RemoveFocusChangeListener(color_updater_.get());\n}\n\nvoid MenuBar::SetMenu(AtomMenuModel* model) {\n menu_model_ = model;\n RebuildChildren();\n}\n\nvoid MenuBar::SetAcceleratorVisibility(bool visible) {\n for (auto* child : GetChildrenInZOrder())\n static_cast<SubmenuButton*>(child)->SetAcceleratorVisibility(visible);\n}\n\nMenuBar::View* MenuBar::FindAccelChild(base::char16 key) {\n for (auto* child : GetChildrenInZOrder()) {\n if (static_cast<SubmenuButton*>(child)->accelerator() == key)\n return child;\n }\n return nullptr;\n}\n\nbool MenuBar::HasAccelerator(base::char16 key) {\n return FindAccelChild(key) != nullptr;\n}\n\nvoid MenuBar::ActivateAccelerator(base::char16 key) {\n auto* child = FindAccelChild(key);\n if (child)\n static_cast<SubmenuButton*>(child)->Activate(nullptr);\n}\n\nint MenuBar::GetItemCount() const {\n return menu_model_ ? menu_model_->GetItemCount() : 0;\n}\n\nbool MenuBar::GetMenuButtonFromScreenPoint(const gfx::Point& screenPoint,\n AtomMenuModel** menu_model,\n views::MenuButton** button) {\n if (!GetBoundsInScreen().Contains(screenPoint))\n return false;\n\n auto children = GetChildrenInZOrder();\n for (int i = 0, n = children.size(); i < n; ++i) {\n if (children[i]->GetBoundsInScreen().Contains(screenPoint) &&\n (menu_model_->GetTypeAt(i) == AtomMenuModel::TYPE_SUBMENU)) {\n *menu_model = menu_model_->GetSubmenuModelAt(i);\n *button = static_cast<views::MenuButton*>(children[i]);\n return true;\n }\n }\n\n return false;\n}\n\nvoid MenuBar::OnBeforeExecuteCommand() {\n RemovePaneFocus();\n window_->RestoreFocus();\n}\n\nvoid MenuBar::OnMenuClosed() {\n SetAcceleratorVisibility(true);\n}\n\nbool MenuBar::AcceleratorPressed(const ui::Accelerator& accelerator) {\n views::View* focused_view = GetFocusManager()->GetFocusedView();\n if (!ContainsForFocusSearch(this, focused_view))\n return false;\n\n switch (accelerator.key_code()) {\n case ui::VKEY_MENU:\n case ui::VKEY_ESCAPE: {\n RemovePaneFocus();\n window_->RestoreFocus();\n return true;\n }\n case ui::VKEY_LEFT:\n GetFocusManager()->AdvanceFocus(true);\n return true;\n case ui::VKEY_RIGHT:\n GetFocusManager()->AdvanceFocus(false);\n return true;\n case ui::VKEY_HOME:\n GetFocusManager()->SetFocusedViewWithReason(\n GetFirstFocusableChild(), views::FocusManager::kReasonFocusTraversal);\n return true;\n case ui::VKEY_END:\n GetFocusManager()->SetFocusedViewWithReason(\n GetLastFocusableChild(), views::FocusManager::kReasonFocusTraversal);\n return true;\n default: {\n auto children = GetChildrenInZOrder();\n for (int i = 0, n = children.size(); i < n; ++i) {\n auto* button = static_cast<SubmenuButton*>(children[i]);\n bool shifted = false;\n auto keycode =\n atom::KeyboardCodeFromCharCode(button->accelerator(), &shifted);\n\n if (keycode == accelerator.key_code()) {\n const gfx::Point p(0, 0);\n auto event = accelerator.ToKeyEvent();\n OnMenuButtonClicked(button, p, &event);\n return true;\n }\n }\n\n return false;\n }\n }\n}\n\nbool MenuBar::SetPaneFocus(views::View* initial_focus) {\n \/\/ TODO(zcbenz): Submit patch to upstream Chromium to fix the crash.\n \/\/\n \/\/ Without this check, Electron would crash when running tests.\n \/\/\n \/\/ Check failed: rules_->CanFocusWindow(window, nullptr).\n \/\/ logging::LogMessage::~LogMessage\n \/\/ wm::FocusController::SetFocusedWindow\n \/\/ wm::FocusController::ResetFocusWithinActiveWindow\n \/\/ views::View::OnFocus\n \/\/ views::Button::OnFocus\n \/\/ views::LabelButton::OnFocus\n \/\/ views::View::Focus\n \/\/ views::FocusManager::SetFocusedViewWithReason\n \/\/ views::AccessiblePaneView::SetPaneFocus\n \/\/ atom::MenuBar::SetPaneFocus\n if (initial_focus && initial_focus->GetWidget()) {\n aura::Window* window = initial_focus->GetWidget()->GetNativeWindow();\n if (!window || !window->GetRootWindow())\n return false;\n }\n\n bool result = views::AccessiblePaneView::SetPaneFocus(initial_focus);\n\n if (result) {\n auto children = GetChildrenInZOrder();\n std::set<ui::KeyboardCode> reg;\n for (int i = 0, n = children.size(); i < n; ++i) {\n auto* button = static_cast<SubmenuButton*>(children[i]);\n bool shifted = false;\n auto keycode =\n atom::KeyboardCodeFromCharCode(button->accelerator(), &shifted);\n\n \/\/ We want the menu items to activate if the user presses the accelerator\n \/\/ key, even without alt, since we are now focused on the menu bar\n if (keycode != ui::VKEY_UNKNOWN && reg.find(keycode) != reg.end()) {\n reg.insert(keycode);\n focus_manager()->RegisterAccelerator(\n ui::Accelerator(keycode, ui::EF_NONE),\n ui::AcceleratorManager::kNormalPriority, this);\n }\n }\n\n \/\/ We want to remove focus \/ hide menu bar when alt is pressed again\n focus_manager()->RegisterAccelerator(\n ui::Accelerator(ui::VKEY_MENU, ui::EF_ALT_DOWN),\n ui::AcceleratorManager::kNormalPriority, this);\n }\n\n return result;\n}\n\nvoid MenuBar::RemovePaneFocus() {\n views::AccessiblePaneView::RemovePaneFocus();\n SetAcceleratorVisibility(false);\n\n auto children = GetChildrenInZOrder();\n std::set<ui::KeyboardCode> unreg;\n for (int i = 0, n = children.size(); i < n; ++i) {\n auto* button = static_cast<SubmenuButton*>(children[i]);\n bool shifted = false;\n auto keycode =\n atom::KeyboardCodeFromCharCode(button->accelerator(), &shifted);\n\n if (keycode != ui::VKEY_UNKNOWN && unreg.find(keycode) != unreg.end()) {\n unreg.insert(keycode);\n focus_manager()->UnregisterAccelerator(\n ui::Accelerator(keycode, ui::EF_NONE), this);\n }\n }\n\n focus_manager()->UnregisterAccelerator(\n ui::Accelerator(ui::VKEY_MENU, ui::EF_ALT_DOWN), this);\n}\n\nconst char* MenuBar::GetClassName() const {\n return kViewClassName;\n}\n\nvoid MenuBar::OnMenuButtonClicked(views::MenuButton* source,\n const gfx::Point& point,\n const ui::Event* event) {\n \/\/ Hide the accelerator when a submenu is activated.\n SetAcceleratorVisibility(false);\n\n if (!menu_model_)\n return;\n\n if (!window_->HasFocus())\n window_->RequestFocus();\n\n int id = source->tag();\n AtomMenuModel::ItemType type = menu_model_->GetTypeAt(id);\n if (type != AtomMenuModel::TYPE_SUBMENU) {\n menu_model_->ActivatedAt(id, 0);\n return;\n }\n\n GetFocusManager()->SetFocusedViewWithReason(\n source, views::FocusManager::kReasonFocusTraversal);\n\n \/\/ Deleted in MenuDelegate::OnMenuClosed\n MenuDelegate* menu_delegate = new MenuDelegate(this);\n menu_delegate->RunMenu(menu_model_->GetSubmenuModelAt(id), source,\n event != nullptr && event->IsKeyEvent()\n ? ui::MENU_SOURCE_KEYBOARD\n : ui::MENU_SOURCE_MOUSE);\n menu_delegate->AddObserver(this);\n}\n\nvoid MenuBar::RefreshColorCache(const ui::NativeTheme* theme) {\n if (!theme)\n theme = ui::NativeTheme::GetInstanceForNativeUi();\n if (theme) {\n#if defined(USE_X11)\n background_color_ = libgtkui::GetBgColor(\"GtkMenuBar#menubar\");\n enabled_color_ = libgtkui::GetFgColor(\n \"GtkMenuBar#menubar GtkMenuItem#menuitem GtkLabel\");\n disabled_color_ = libgtkui::GetFgColor(\n \"GtkMenuBar#menubar GtkMenuItem#menuitem:disabled GtkLabel\");\n#else\n background_color_ =\n theme->GetSystemColor(ui::NativeTheme::kColorId_MenuBackgroundColor);\n#endif\n }\n#if defined(OS_WIN)\n background_color_ = color_utils::GetSysSkColor(COLOR_MENUBAR);\n#endif\n}\n\nvoid MenuBar::OnNativeThemeChanged(const ui::NativeTheme* theme) {\n RefreshColorCache(theme);\n UpdateViewColors();\n}\n\nvoid MenuBar::RebuildChildren() {\n RemoveAllChildViews(true);\n for (int i = 0, n = GetItemCount(); i < n; ++i) {\n auto* button =\n new SubmenuButton(menu_model_->GetLabelAt(i), this, background_color_);\n button->set_tag(i);\n AddChildView(button);\n }\n UpdateViewColors();\n}\n\nvoid MenuBar::UpdateViewColors() {\n \/\/ set menubar background color\n SetBackground(views::CreateSolidBackground(background_color_));\n\n \/\/ set child colors\n if (menu_model_ == nullptr)\n return;\n#if defined(USE_X11)\n const auto& textColor = has_focus_ ? enabled_color_ : disabled_color_;\n for (auto* child : GetChildrenInZOrder()) {\n auto* button = static_cast<SubmenuButton*>(child);\n button->SetTextColor(views::Button::STATE_NORMAL, textColor);\n button->SetTextColor(views::Button::STATE_DISABLED, disabled_color_);\n button->SetTextColor(views::Button::STATE_PRESSED, enabled_color_);\n button->SetTextColor(views::Button::STATE_HOVERED, textColor);\n button->SetUnderlineColor(textColor);\n }\n#elif defined(OS_WIN)\n for (auto* child : GetChildrenInZOrder()) {\n auto* button = static_cast<SubmenuButton*>(child);\n button->SetUnderlineColor(color_utils::GetSysSkColor(COLOR_MENUTEXT));\n }\n#endif\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"CommandProfiling.h\"\n\n#if defined(__unix__) || defined(__APPLE__)\n#include <signal.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#endif\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <sstream>\n\n#include \"Debug.h\"\n\nnamespace {\n\npid_t spawn(const std::string& cmd) {\n#ifdef _POSIX_VERSION\n auto child = fork();\n always_assert_log(child != -1, \"Failed to fork\");\n if (child != 0) {\n return child;\n } else {\n int ret = execl(\"\/bin\/sh\", \"\/bin\/sh\", \"-c\", cmd.c_str(), nullptr);\n always_assert_log(ret != -1, \"exec of command failed: %s\", strerror(errno));\n not_reached();\n }\n#else\n std::cerr << \"spawn() is a no-op on non-POSIX systems\" << std::endl;\n return 0;\n#endif\n}\n\n\/*\n * Appends the PID of the current process to :cmd and invokes it.\n *\/\npid_t spawn_profiler(const std::string& cmd) {\n#ifdef _POSIX_VERSION\n auto parent = getpid();\n std::ostringstream ss;\n ss << cmd << \" \" << parent;\n auto full_cmd = ss.str();\n return spawn(full_cmd);\n#else\n std::cerr << \"spawn_profiler() is a no-op on non-POSIX systems\" << std::endl;\n return 0;\n#endif\n}\n\npid_t kill_and_wait(pid_t pid, int sig) {\n#ifdef _POSIX_VERSION\n kill(pid, sig);\n return waitpid(pid, nullptr, 0);\n#else\n std::cerr << \"kill_and_wait() is a no-op on non-POSIX systems\" << std::endl;\n return 0;\n#endif\n}\n\nvoid run_and_wait(const std::string& cmd) {\n#ifdef _POSIX_VERSION\n auto child = spawn(cmd);\n if (child == 0) {\n return;\n }\n\n int status;\n pid_t wpid = waitpid(child, &status, 0);\n always_assert_log(wpid != -1, \"Failed to waitpid: %s\", strerror(errno));\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {\n std::cerr << \"Failed cmd \" << cmd << std::endl;\n }\n#else\n std::cerr << \"run_and_wait() is a no-op on non-POSIX systems\" << std::endl;\n#endif\n}\n\n} \/\/ namespace\n\nScopedCommandProfiling::ScopedCommandProfiling(\n const std::string& cmd,\n boost::optional<std::string> shutdown_cmd,\n boost::optional<std::string> post_cmd,\n const char* log_str) {\n m_shutdown_cmd = std::move(shutdown_cmd);\n m_post_cmd = std::move(post_cmd);\n if (log_str != nullptr) {\n std::cerr << \"Running profiler \" << log_str << \"...\" << std::endl;\n } else {\n std::cerr << \"Running profiler...\" << std::endl;\n }\n m_profiler = spawn_profiler(cmd);\n}\n\nScopedCommandProfiling::~ScopedCommandProfiling() {\n if (m_profiler != -1) {\n std::cerr << \"Waiting for profiler to finish...\" << std::endl;\n if (m_shutdown_cmd) {\n run_and_wait(*m_shutdown_cmd);\n } else {\n kill_and_wait(m_profiler, SIGINT);\n }\n if (m_post_cmd) {\n run_and_wait(*m_post_cmd + \" perf.data\");\n }\n }\n}\n\nScopedCommandProfiling::ScopedCommandProfiling(\n ScopedCommandProfiling&& other) noexcept {\n *this = std::move(other);\n}\n\nScopedCommandProfiling& ScopedCommandProfiling::operator=(\n ScopedCommandProfiling&& rhs) noexcept {\n m_profiler = rhs.m_profiler;\n m_shutdown_cmd = std::move(rhs.m_shutdown_cmd);\n m_post_cmd = std::move(rhs.m_post_cmd);\n\n rhs.m_profiler = -1;\n\n return *this;\n}\n\nboost::optional<ScopedCommandProfiling::ProfilerInfo>\nScopedCommandProfiling::maybe_info_from_env(const std::string& prefix) {\n auto get_env_str =\n [](const std::string& key) -> boost::optional<std::string> {\n auto val = getenv(key.c_str());\n if (val == nullptr) {\n return boost::none;\n }\n return std::string(val);\n };\n\n std::string profiler_key = prefix + \"PROFILE_COMMAND\";\n if (getenv(profiler_key.c_str()) == nullptr) {\n return boost::none;\n }\n\n return boost::make_optional<ProfilerInfo>(\n ProfilerInfo{getenv(profiler_key.c_str()),\n get_env_str(prefix + \"PROFILE_SHUTDOWN_COMMAND\"),\n get_env_str(prefix + \"PROFILE_POST_COMMAND\")});\n}\n\ntemplate <typename T>\nboost::optional<ScopedCommandProfiling> ScopedCommandProfiling::maybe_from_info(\n const boost::optional<ProfilerInfo>& info, const T* log_str) {\n if (!info) {\n return boost::none;\n }\n return ScopedCommandProfiling(*info, log_str);\n}\ntemplate boost::optional<ScopedCommandProfiling>\nScopedCommandProfiling::maybe_from_info<>(\n const boost::optional<ProfilerInfo>& info, const std::string* log_str);\ntemplate boost::optional<ScopedCommandProfiling>\nScopedCommandProfiling::maybe_from_info<>(\n const boost::optional<ProfilerInfo>& info, const char* log_str);\n<commit_msg>Add sleep to profiling<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"CommandProfiling.h\"\n\n#if defined(__unix__) || defined(__APPLE__)\n#include <signal.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#endif\n#include <chrono>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <sstream>\n#include <thread>\n\n#include \"Debug.h\"\n\nnamespace {\n\nusing namespace std::chrono_literals;\n\npid_t spawn(const std::string& cmd) {\n#ifdef _POSIX_VERSION\n auto child = fork();\n always_assert_log(child != -1, \"Failed to fork\");\n if (child != 0) {\n \/\/ Wait a little bit to let the spawn catch up.\n std::this_thread::sleep_for(250ms);\n return child;\n } else {\n int ret = execl(\"\/bin\/sh\", \"\/bin\/sh\", \"-c\", cmd.c_str(), nullptr);\n always_assert_log(ret != -1, \"exec of command failed: %s\", strerror(errno));\n not_reached();\n }\n#else\n std::cerr << \"spawn() is a no-op on non-POSIX systems\" << std::endl;\n return 0;\n#endif\n}\n\n\/*\n * Appends the PID of the current process to :cmd and invokes it.\n *\/\npid_t spawn_profiler(const std::string& cmd) {\n#ifdef _POSIX_VERSION\n auto parent = getpid();\n std::ostringstream ss;\n ss << cmd << \" \" << parent;\n auto full_cmd = ss.str();\n return spawn(full_cmd);\n#else\n std::cerr << \"spawn_profiler() is a no-op on non-POSIX systems\" << std::endl;\n return 0;\n#endif\n}\n\npid_t kill_and_wait(pid_t pid, int sig) {\n#ifdef _POSIX_VERSION\n kill(pid, sig);\n return waitpid(pid, nullptr, 0);\n#else\n std::cerr << \"kill_and_wait() is a no-op on non-POSIX systems\" << std::endl;\n return 0;\n#endif\n}\n\nvoid run_and_wait(const std::string& cmd) {\n#ifdef _POSIX_VERSION\n auto child = spawn(cmd);\n if (child == 0) {\n return;\n }\n\n int status;\n pid_t wpid = waitpid(child, &status, 0);\n always_assert_log(wpid != -1, \"Failed to waitpid: %s\", strerror(errno));\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {\n std::cerr << \"Failed cmd \" << cmd << std::endl;\n }\n#else\n std::cerr << \"run_and_wait() is a no-op on non-POSIX systems\" << std::endl;\n#endif\n}\n\n} \/\/ namespace\n\nScopedCommandProfiling::ScopedCommandProfiling(\n const std::string& cmd,\n boost::optional<std::string> shutdown_cmd,\n boost::optional<std::string> post_cmd,\n const char* log_str) {\n m_shutdown_cmd = std::move(shutdown_cmd);\n m_post_cmd = std::move(post_cmd);\n if (log_str != nullptr) {\n std::cerr << \"Running profiler \" << log_str << \"...\" << std::endl;\n } else {\n std::cerr << \"Running profiler...\" << std::endl;\n }\n m_profiler = spawn_profiler(cmd);\n}\n\nScopedCommandProfiling::~ScopedCommandProfiling() {\n if (m_profiler != -1) {\n std::cerr << \"Waiting for profiler to finish...\" << std::endl;\n if (m_shutdown_cmd) {\n run_and_wait(*m_shutdown_cmd);\n } else {\n kill_and_wait(m_profiler, SIGINT);\n }\n if (m_post_cmd) {\n run_and_wait(*m_post_cmd + \" perf.data\");\n }\n }\n}\n\nScopedCommandProfiling::ScopedCommandProfiling(\n ScopedCommandProfiling&& other) noexcept {\n *this = std::move(other);\n}\n\nScopedCommandProfiling& ScopedCommandProfiling::operator=(\n ScopedCommandProfiling&& rhs) noexcept {\n m_profiler = rhs.m_profiler;\n m_shutdown_cmd = std::move(rhs.m_shutdown_cmd);\n m_post_cmd = std::move(rhs.m_post_cmd);\n\n rhs.m_profiler = -1;\n\n return *this;\n}\n\nboost::optional<ScopedCommandProfiling::ProfilerInfo>\nScopedCommandProfiling::maybe_info_from_env(const std::string& prefix) {\n auto get_env_str =\n [](const std::string& key) -> boost::optional<std::string> {\n auto val = getenv(key.c_str());\n if (val == nullptr) {\n return boost::none;\n }\n return std::string(val);\n };\n\n std::string profiler_key = prefix + \"PROFILE_COMMAND\";\n if (getenv(profiler_key.c_str()) == nullptr) {\n return boost::none;\n }\n\n return boost::make_optional<ProfilerInfo>(\n ProfilerInfo{getenv(profiler_key.c_str()),\n get_env_str(prefix + \"PROFILE_SHUTDOWN_COMMAND\"),\n get_env_str(prefix + \"PROFILE_POST_COMMAND\")});\n}\n\ntemplate <typename T>\nboost::optional<ScopedCommandProfiling> ScopedCommandProfiling::maybe_from_info(\n const boost::optional<ProfilerInfo>& info, const T* log_str) {\n if (!info) {\n return boost::none;\n }\n return ScopedCommandProfiling(*info, log_str);\n}\ntemplate boost::optional<ScopedCommandProfiling>\nScopedCommandProfiling::maybe_from_info<>(\n const boost::optional<ProfilerInfo>& info, const std::string* log_str);\ntemplate boost::optional<ScopedCommandProfiling>\nScopedCommandProfiling::maybe_from_info<>(\n const boost::optional<ProfilerInfo>& info, const char* log_str);\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <unistd.h>\n\n#include \"benchmark.h\"\n#include \"simdjson.h\"\n\n\/\/ #define RAPIDJSON_SSE2 \/\/ bad\n\/\/ #define RAPIDJSON_SSE42 \/\/ bad\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/reader.h\" \/\/ you have to check in the submodule\n#include \"rapidjson\/stringbuffer.h\"\n#include \"rapidjson\/writer.h\"\n#include \"sajson.h\"\n\nusing namespace simdjson;\nusing namespace rapidjson;\n\nstd::string rapid_stringme_insitu(char *json) {\n Document d;\n d.ParseInsitu(json);\n if (d.HasParseError()) {\n std::cerr << \"problem!\" << std::endl;\n return \"\"; \/\/ should do something\n }\n StringBuffer buffer;\n Writer<StringBuffer> writer(buffer);\n d.Accept(writer);\n return buffer.GetString();\n}\n\nstd::string rapid_stringme(char *json) {\n Document d;\n d.Parse(json);\n if (d.HasParseError()) {\n std::cerr << \"problem!\" << std::endl;\n return \"\"; \/\/ should do something\n }\n StringBuffer buffer;\n Writer<StringBuffer> writer(buffer);\n d.Accept(writer);\n return buffer.GetString();\n}\n\nint main(int argc, char *argv[]) {\n int c;\n bool verbose = false;\n bool just_data = false;\n\n while ((c = getopt(argc, argv, \"vt\")) != -1)\n switch (c) {\n case 't':\n just_data = true;\n break;\n case 'v':\n verbose = true;\n break;\n default:\n abort();\n }\n if (optind >= argc) {\n std::cerr << \"Usage: \" << argv[0] << \" <jsonfile>\" << std::endl;\n exit(1);\n }\n const char *filename = argv[optind];\n auto [p, error] = simdjson::padded_string::load(filename);\n if (error) {\n std::cerr << \"Could not load the file \" << filename << std::endl;\n return EXIT_FAILURE;\n }\n if (verbose) {\n std::cout << \"Input has \";\n if (p.size() > 1024 * 1024)\n std::cout << p.size() \/ (1024 * 1024) << \" MB \";\n else if (p.size() > 1024)\n std::cout << p.size() \/ 1024 << \" KB \";\n else\n std::cout << p.size() << \" B \";\n std::cout << std::endl;\n }\n char *buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);\n memcpy(buffer, p.data(), p.size());\n buffer[p.size()] = '\\0';\n\n int repeat = 50;\n int volume = p.size();\n if (just_data) {\n printf(\n \"name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \\n\");\n }\n size_t strlength = rapid_stringme((char *)p.data()).size();\n if (verbose)\n std::cout << \"input length is \" << p.size() << \" stringified length is \"\n << strlength << std::endl;\n BEST_TIME_NOCHECK(\"despacing with RapidJSON\",\n rapid_stringme((char *)p.data()), , repeat, volume,\n !just_data);\n BEST_TIME_NOCHECK(\n \"despacing with RapidJSON Insitu\", rapid_stringme_insitu((char *)buffer),\n memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);\n memcpy(buffer, p.data(), p.size());\n size_t outlength;\n uint8_t *cbuffer = (uint8_t *)buffer;\n for (auto imple : simdjson::available_implementations) {\n BEST_TIME((std::string(\"simdjson->minify+\")+imple->name()).c_str(), (imple->minify(cbuffer, p.size(), cbuffer, outlength), outlength),\n outlength, memcpy(buffer, p.data(), p.size()), repeat, volume,\n !just_data);\n }\n\n printf(\"minisize = %zu, original size = %zu (minified down to %.2f percent \"\n \"of original) \\n\",\n outlength, p.size(), outlength * 100.0 \/ p.size());\n\n \/***\n * Is it worth it to minify before parsing?\n ***\/\n rapidjson::Document d;\n BEST_TIME(\"RapidJSON Insitu orig\", d.ParseInsitu(buffer).HasParseError(),\n false, memcpy(buffer, p.data(), p.size()), repeat, volume,\n !just_data);\n\n char *mini_buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);\n size_t minisize;\n simdjson::active_implementation->minify((const uint8_t *)p.data(), p.size(),\n (uint8_t *)mini_buffer, minisize);\n mini_buffer[minisize] = '\\0';\n\n BEST_TIME(\"RapidJSON Insitu despaced\", d.ParseInsitu(buffer).HasParseError(),\n false, memcpy(buffer, mini_buffer, p.size()), repeat, volume,\n !just_data);\n\n size_t ast_buffer_size = p.size() * 2;\n size_t *ast_buffer = (size_t *)malloc(ast_buffer_size * sizeof(size_t));\n\n BEST_TIME(\n \"sajson orig\",\n sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),\n sajson::mutable_string_view(p.size(), buffer))\n .is_valid(),\n true, memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);\n\n BEST_TIME(\n \"sajson despaced\",\n sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),\n sajson::mutable_string_view(minisize, buffer))\n .is_valid(),\n true, memcpy(buffer, mini_buffer, p.size()), repeat, volume, !just_data);\n\n simdjson::ParsedJson pj;\n bool is_alloc_ok = pj.allocate_capacity(p.size(), 1024);\n if (!is_alloc_ok) {\n fprintf(stderr, \"failed to allocate memory\\n\");\n return EXIT_FAILURE;\n }\n bool automated_reallocation = false;\n BEST_TIME(\"simdjson orig\",\n simdjson::json_parse((const uint8_t *)buffer, p.size(), pj,\n automated_reallocation),\n simdjson::SUCCESS, memcpy(buffer, p.data(), p.size()), repeat, volume,\n !just_data);\n\n simdjson::ParsedJson pj2;\n bool is_alloc_ok2 = pj2.allocate_capacity(p.size(), 1024);\n if (!is_alloc_ok2) {\n fprintf(stderr, \"failed to allocate memory\\n\");\n return EXIT_FAILURE;\n }\n automated_reallocation = false;\n BEST_TIME(\"simdjson despaced\",\n simdjson::json_parse((const uint8_t *)buffer, minisize, pj2,\n automated_reallocation),\n simdjson::SUCCESS, memcpy(buffer, mini_buffer, p.size()), repeat, volume,\n !just_data);\n\n free(buffer);\n free(ast_buffer);\n free(mini_buffer);\n}\n<commit_msg>migrating minifier competition to new API (#597)<commit_after>#include <iostream>\n#include <unistd.h>\n\n#include \"benchmark.h\"\n#include \"simdjson.h\"\n\n\/\/ #define RAPIDJSON_SSE2 \/\/ bad\n\/\/ #define RAPIDJSON_SSE42 \/\/ bad\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/reader.h\" \/\/ you have to check in the submodule\n#include \"rapidjson\/stringbuffer.h\"\n#include \"rapidjson\/writer.h\"\n#include \"sajson.h\"\n\nusing namespace simdjson;\nusing namespace rapidjson;\n\nstd::string rapid_stringme_insitu(char *json) {\n Document d;\n d.ParseInsitu(json);\n if (d.HasParseError()) {\n std::cerr << \"problem!\" << std::endl;\n return \"\"; \/\/ should do something\n }\n StringBuffer buffer;\n Writer<StringBuffer> writer(buffer);\n d.Accept(writer);\n return buffer.GetString();\n}\n\nstd::string rapid_stringme(char *json) {\n Document d;\n d.Parse(json);\n if (d.HasParseError()) {\n std::cerr << \"problem!\" << std::endl;\n return \"\"; \/\/ should do something\n }\n StringBuffer buffer;\n Writer<StringBuffer> writer(buffer);\n d.Accept(writer);\n return buffer.GetString();\n}\n\nint main(int argc, char *argv[]) {\n int c;\n bool verbose = false;\n bool just_data = false;\n\n while ((c = getopt(argc, argv, \"vt\")) != -1)\n switch (c) {\n case 't':\n just_data = true;\n break;\n case 'v':\n verbose = true;\n break;\n default:\n abort();\n }\n if (optind >= argc) {\n std::cerr << \"Usage: \" << argv[0] << \" <jsonfile>\" << std::endl;\n exit(1);\n }\n const char *filename = argv[optind];\n auto [p, error] = simdjson::padded_string::load(filename);\n if (error) {\n std::cerr << \"Could not load the file \" << filename << std::endl;\n return EXIT_FAILURE;\n }\n if (verbose) {\n std::cout << \"Input has \";\n if (p.size() > 1024 * 1024)\n std::cout << p.size() \/ (1024 * 1024) << \" MB \";\n else if (p.size() > 1024)\n std::cout << p.size() \/ 1024 << \" KB \";\n else\n std::cout << p.size() << \" B \";\n std::cout << std::endl;\n }\n char *buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);\n memcpy(buffer, p.data(), p.size());\n buffer[p.size()] = '\\0';\n\n int repeat = 50;\n int volume = p.size();\n if (just_data) {\n printf(\n \"name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \\n\");\n }\n size_t strlength = rapid_stringme((char *)p.data()).size();\n if (verbose)\n std::cout << \"input length is \" << p.size() << \" stringified length is \"\n << strlength << std::endl;\n BEST_TIME_NOCHECK(\"despacing with RapidJSON\",\n rapid_stringme((char *)p.data()), , repeat, volume,\n !just_data);\n BEST_TIME_NOCHECK(\n \"despacing with RapidJSON Insitu\", rapid_stringme_insitu((char *)buffer),\n memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);\n memcpy(buffer, p.data(), p.size());\n size_t outlength;\n uint8_t *cbuffer = (uint8_t *)buffer;\n for (auto imple : simdjson::available_implementations) {\n BEST_TIME((std::string(\"simdjson->minify+\")+imple->name()).c_str(), (imple->minify(cbuffer, p.size(), cbuffer, outlength), outlength),\n outlength, memcpy(buffer, p.data(), p.size()), repeat, volume,\n !just_data);\n }\n\n printf(\"minisize = %zu, original size = %zu (minified down to %.2f percent \"\n \"of original) \\n\",\n outlength, p.size(), outlength * 100.0 \/ p.size());\n\n \/***\n * Is it worth it to minify before parsing?\n ***\/\n rapidjson::Document d;\n BEST_TIME(\"RapidJSON Insitu orig\", d.ParseInsitu(buffer).HasParseError(),\n false, memcpy(buffer, p.data(), p.size()), repeat, volume,\n !just_data);\n\n char *mini_buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);\n size_t minisize;\n simdjson::active_implementation->minify((const uint8_t *)p.data(), p.size(),\n (uint8_t *)mini_buffer, minisize);\n mini_buffer[minisize] = '\\0';\n\n BEST_TIME(\"RapidJSON Insitu despaced\", d.ParseInsitu(buffer).HasParseError(),\n false, memcpy(buffer, mini_buffer, p.size()), repeat, volume,\n !just_data);\n\n size_t ast_buffer_size = p.size() * 2;\n size_t *ast_buffer = (size_t *)malloc(ast_buffer_size * sizeof(size_t));\n\n BEST_TIME(\n \"sajson orig\",\n sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),\n sajson::mutable_string_view(p.size(), buffer))\n .is_valid(),\n true, memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);\n\n BEST_TIME(\n \"sajson despaced\",\n sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),\n sajson::mutable_string_view(minisize, buffer))\n .is_valid(),\n true, memcpy(buffer, mini_buffer, p.size()), repeat, volume, !just_data);\n\n simdjson::document::parser parser;\n bool automated_reallocation = false;\n BEST_TIME(\"simdjson orig\",\n parser.parse((const uint8_t *)buffer, p.size(),\n automated_reallocation).error(),\n simdjson::SUCCESS, memcpy(buffer, p.data(), p.size()), repeat, volume,\n !just_data);\n BEST_TIME(\"simdjson despaced\",\n parser.parse((const uint8_t *)buffer, minisize,\n automated_reallocation).error(),\n simdjson::SUCCESS, memcpy(buffer, mini_buffer, p.size()), repeat, volume,\n !just_data);\n\n free(buffer);\n free(ast_buffer);\n free(mini_buffer);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by andreanistico on 06\/02\/17.\n\/\/\n\n#include <iostream>\n#include \"include\/Lander\/StatesClasses.hpp\"\n#include \"Lander\/Lander.h\"\n#include \"parameters.h\"\n\nLander::Lander()\n : _horizontaErr((double)0) , _tauHold((double)0), _tauLost((double)0), _tauErr((double)0), _NHold(0),\n _NLost(0),_NComp(0), _initS(&_machine), _holdS(&_machine) , _asceS(&_machine) , _descS(&_machine),_compS(&_machine),\n _rtolS(&_machine),_landS(&_machine), _err(0,0,0), _err_int(0,0,0), _err_diff(0,0,0), _dt(0), _prevTime(0), _actualTime(0),_actualState(0),_prevState(0),\n _verticalErr(0), _holdPIDX(params_automatic::KpHold,0,params_automatic::KiHold), _holdPIDY(params_automatic::KdHold,0,params_automatic::KiHold)\n{\n\n initStateMachine();\n _actualState = _machine.getActualNodeId();\n _err_prev = _err;\n\n}\n\nvoid Lander::setState(MavState pose) {\n _state = pose;\n}\n\nMavState Lander::getState() {\n return _state;\n}\n\nMavState Lander::getCommand() {\n return _setPoint;\n}\n\nvoid Lander::initStateMachine() {\n\n \/\/Link signals\n _machine._horizontaErr = &_horizontaErr;\n _machine._verticalErr = &_verticalErr;\n _machine._tauErr = &_tauErr;\n _machine._tauHold = &_tauHold;\n _machine._tauLost = &_tauLost;\n _machine._NLost = &_NLost;\n _machine._NHold = &_NHold;\n _machine._NComp = &_NComp;\n _machine._state = &_state;\n _machine._setPoint = &_setPoint;\n\n \/\/Link states\n _initS._nextState = &_holdS;\n\n _holdS._nextAscState = &_asceS;\n _holdS._nextDesState = &_descS;\n _holdS._nextState = &_rtolS;\n\n _asceS._nextState = &_holdS;\n\n _descS._nextState = &_holdS;\n\n _rtolS._nextComState = &_compS;\n _rtolS._nextState = &_holdS;\n\n _compS._nextState = &_asceS;\n _compS._nextLanState = &_landS;\n\n _landS._nextState = &_asceS;\n\n _machine.setStatePtr(&_initS);\n\n _tauHold = 0.5 * params_automatic::platformLenght;\n _tauLost = params_automatic::platformLenght * 0.7;\n\n \/\/Print actual state\n std::cout << \"Actual state: \" << _machine.getActualNodeId() << std::endl;\n\n}\n\nvoid Lander::setPlatformState(const MavState platformState) {\n _platformState = platformState;\n}\n\nvoid Lander::updateSignals() {\n\n \/\/Compute horizontal error\n double xTemp = _state.getX();\n double yTemp = _state.getY();\n double zTemp = _state.getZ();\n double xPlatTemp = _platformState.getX();\n double yPlatTemp = _platformState.getY();\n double zPlatTemp = _platformState.getZ();\n\n double dx = xPlatTemp - xTemp;\n double dy = yPlatTemp - yTemp;\n double dz = zPlatTemp - zTemp + PLATFORM_OFFSET;\n\n _err[0] = dx;\n _err[1] = dy;\n _err[2] = 0; \/\/Trick, used to calculate horizontal error\n\n _horizontaErr = _err.norm();\n _err[2] = dz;\n _verticalErr = _err[2];\n\n if( _actualState == AbstractLandState::states::HOLD ||\n _actualState == AbstractLandState::states::ASCE ||\n _actualState == AbstractLandState::states::DESC ||\n _actualState == AbstractLandState::states::COMP ||\n _actualState == AbstractLandState::states::R2LA ){\n\n \/\/Increment N if needed\n if (_horizontaErr < _tauHold) {\n _NLost = 0;\n _NHold++;\n }\n else if (_horizontaErr > _tauLost) {\n _NHold = 0;\n _NComp = 0;\n _NLost++;\n }\n\n if(_actualState == AbstractLandState::states::R2LA || _actualState == AbstractLandState::states::COMP){\n\n if(_prevState == AbstractLandState::states::HOLD) _NComp = 0;\n \/\/Check whether we are on place to land\n if (_horizontaErr < _tauHold * 0.5) {\n _NComp++;\n } else{\n _NComp = 0;\n }\n }\n\n _err_prev = _err;\n }\n\n#ifdef DEBUG\n\n std::cout << \"**********************************\" << std::endl;\n std::cout << \"STATE: \" << _actualState<< std::endl;\n std::cout << \"HERRO: \" << _horizontaErr<< std::endl;\n std::cout << \"HERRV: \" << _verticalErr<< std::endl;\n std::cout << \"NHOLD: \" << _NHold<< std::endl;\n std::cout << \"NLOST: \" << _NLost<< std::endl;\n std::cout << \"NCOMP: \" << _NComp<< std::endl;\n std::cout << \"INTEX: \" << _err_int[0] << std::endl;\n std::cout << \"INTEY: \" << _err_int[1] << std::endl;\n std::cout << \"**********************************\" << std::endl;\n#endif\n\n}\n\nvoid Lander::handleMachine() {\n\n updateSignals();\n _machine.handle();\n}\n\nint Lander::getActualMachineState() {\n return _machine.getActualNodeId();\n}\n\nvoid Lander::run() {\n\n handleMachine();\n _actualState = _machine.getActualNodeId();\n managetime();\n\n static bool initDone = false;\n switch (_actualState){\n\n case (AbstractLandState::states::INIT):\n if(!initDone){\n init();\n initDone = true;\n }\n break;\n\n case (AbstractLandState::states::HOLD):\n initDone = false;\n clampZSP();\n hold();\n break;\n case (AbstractLandState::states::DESC):\n\n desc();\n clampZSP();\n break;\n case (AbstractLandState::states::ASCE):\n\n asce();\n clampZSP();\n\n break;\n\n case (AbstractLandState::states::R2LA):\n clampZSP();\n hold();\n break;\n\n case (AbstractLandState::states::COMP):\n hold();\n comp();\n break;\n case (AbstractLandState::states::LAND):\n land();\n break;\n\n default:\n hold();\n break;\n\n }\n _prevState = _actualState;\n\n}\n\nvoid Lander::resetSetPoint() {\n\n _setPoint = _state;\n _setPoint.setType(MavState::type::POSITION);\n\n}\n\nvoid Lander::updateIntegrals() {\n\n _err_int[0] += _dt * _err[0];\n _err_int[1] += _dt * _err[1];\n\n double tempx,tempy;\n\n tempx = common::clamp(_err_int[0],params_automatic::minIntValue,params_automatic::maxIntValue);\n tempy = common::clamp(_err_int[1],params_automatic::minIntValue,params_automatic::maxIntValue);\n\n _err_int[0] = tempx;\n _err_int[1] = tempy;\n\n}\n\nvoid Lander::managetime() {\n\n _actualTime = common::time::getTimeMilliSecond();\n double dt = _prevTime != 0 ? (_actualTime - _prevTime) * (double)MILLI2SECS : 0.0;\n _prevTime = _actualTime;\n _dt = dt;\n\n}\n\nvoid Lander::resetIntegrals() {\n\n _err_int[0] = 0;\n _err_int[1] = 0;\n\n}\n\nvoid Lander::init() {\n\n \/\/Set point to my position\n resetSetPoint();\n\n \/\/Go to max tracking height\n _setPoint.setZ(params_automatic::zMax);\n\n}\n\nvoid Lander::hold() {\n\n \/\/This function is purely tracking, nothing more\n\n \/*\n * Tracking is performed by POSITION control, issuing the position setpoint\n * in order to achieve the desired velocity calculated by:\n *\n * Vdes = K * ep + Vplat\n * or\n * Psp = Pplat + K * Vplat\n *\n * where:\n *\n * Vdes = desired velocity, K = proportional gain, ep = position error, Vplat = paltform velocity\n *\/\n\n Eigen::Vector2d tempVel(_platformState.getVx(),_platformState.getVy());\n\n double xTarget = _holdPIDX.getOutput(_state.getX(), _platformState.getX());\n double yTarget = _holdPIDY.getOutput(_state.getY(), _platformState.getY());\n Eigen::Vector2d targetVect(xTarget,yTarget);\n\n\n updateIntegrals();\n \/\/PosSP = PlatPos + K * Vplat\n targetVect += params_automatic::KpHoldV * tempVel;\n\n \/\/Fill right fields\n _setPoint.setPosition(targetVect(0),targetVect(1),_setPoint.getZ());\n _setPoint.setType(MavState::POSITION);\n\n}\n\nvoid Lander::asce() {\n\n resetIntegrals();\n _setPoint.setZ(_setPoint.getZ() + 0.1);\n\n}\n\nvoid Lander::desc() {\n\n\n _setPoint.setZ(_setPoint.getZ() - 0.1);\n}\n\nvoid Lander::comp() {\n\n \/\/Calculate desired vertical velocity in order to compensate oscillations\n double dz = - _state.getZ() + _platformState.getZ() + PLATFORM_OFFSET;\n double desc = common::interpolate(fabs(dz), DRATE_MAX, DRATE_MIN, TMAX, TMIN);\n double z_target_v = _platformState.getVz() - desc;\n\n double err_v = z_target_v - _state.getVz();\n\n double corr = 1;\n\n if(_platformState.getVz() > 0) corr = 1.2;\n\n z_target_v += corr * params_automatic::KPCompV * (err_v);\n\n \/\/Now we need to transform this velocity in a position setpoint since in Firmware:\n \/\/ VelSP = Kp * PosError then PosSP = ( VelSP \/ Kp ) + RobotPos\n\n _setPoint.setZ((z_target_v) + _state.getZ());\n\n}\n\nvoid Lander::clampZSP() {\n\n double temp;\n temp = common::clamp(_setPoint.getZ(),params_automatic::zMin,params_automatic::zMax);\n\n _setPoint.setZ(temp);\n}\n\nvoid Lander::land() {\n\n resetSetPoint();\n _setPoint.setZ(_state.getZ()-10);\n\n}\n\n\n\n\n\n\n\n\n\n\n<commit_msg>fix pid constructor<commit_after>\/\/\n\/\/ Created by andreanistico on 06\/02\/17.\n\/\/\n\n#include <iostream>\n#include \"include\/Lander\/StatesClasses.hpp\"\n#include \"Lander\/Lander.h\"\n#include \"parameters.h\"\n\nLander::Lander()\n : _horizontaErr((double)0) , _tauHold((double)0), _tauLost((double)0), _tauErr((double)0), _NHold(0),\n _NLost(0),_NComp(0), _initS(&_machine), _holdS(&_machine) , _asceS(&_machine) , _descS(&_machine),_compS(&_machine),\n _rtolS(&_machine),_landS(&_machine), _err(0,0,0), _err_int(0,0,0), _err_diff(0,0,0), _dt(0), _prevTime(0), _actualTime(0),_actualState(0),_prevState(0),\n _verticalErr(0), _holdPIDX(params_automatic::KpHold,params_automatic::KiHold,0), _holdPIDY(params_automatic::KdHold,params_automatic::KiHold,0)\n{\n\n initStateMachine();\n _actualState = _machine.getActualNodeId();\n _err_prev = _err;\n\n}\n\nvoid Lander::setState(MavState pose) {\n _state = pose;\n}\n\nMavState Lander::getState() {\n return _state;\n}\n\nMavState Lander::getCommand() {\n return _setPoint;\n}\n\nvoid Lander::initStateMachine() {\n\n \/\/Link signals\n _machine._horizontaErr = &_horizontaErr;\n _machine._verticalErr = &_verticalErr;\n _machine._tauErr = &_tauErr;\n _machine._tauHold = &_tauHold;\n _machine._tauLost = &_tauLost;\n _machine._NLost = &_NLost;\n _machine._NHold = &_NHold;\n _machine._NComp = &_NComp;\n _machine._state = &_state;\n _machine._setPoint = &_setPoint;\n\n \/\/Link states\n _initS._nextState = &_holdS;\n\n _holdS._nextAscState = &_asceS;\n _holdS._nextDesState = &_descS;\n _holdS._nextState = &_rtolS;\n\n _asceS._nextState = &_holdS;\n\n _descS._nextState = &_holdS;\n\n _rtolS._nextComState = &_compS;\n _rtolS._nextState = &_holdS;\n\n _compS._nextState = &_asceS;\n _compS._nextLanState = &_landS;\n\n _landS._nextState = &_asceS;\n\n _machine.setStatePtr(&_initS);\n\n _tauHold = 0.5 * params_automatic::platformLenght;\n _tauLost = params_automatic::platformLenght * 0.7;\n\n \/\/Print actual state\n std::cout << \"Actual state: \" << _machine.getActualNodeId() << std::endl;\n\n}\n\nvoid Lander::setPlatformState(const MavState platformState) {\n _platformState = platformState;\n}\n\nvoid Lander::updateSignals() {\n\n \/\/Compute horizontal error\n double xTemp = _state.getX();\n double yTemp = _state.getY();\n double zTemp = _state.getZ();\n double xPlatTemp = _platformState.getX();\n double yPlatTemp = _platformState.getY();\n double zPlatTemp = _platformState.getZ();\n\n double dx = xPlatTemp - xTemp;\n double dy = yPlatTemp - yTemp;\n double dz = zPlatTemp - zTemp + PLATFORM_OFFSET;\n\n _err[0] = dx;\n _err[1] = dy;\n _err[2] = 0; \/\/Trick, used to calculate horizontal error\n\n _horizontaErr = _err.norm();\n _err[2] = dz;\n _verticalErr = _err[2];\n\n if( _actualState == AbstractLandState::states::HOLD ||\n _actualState == AbstractLandState::states::ASCE ||\n _actualState == AbstractLandState::states::DESC ||\n _actualState == AbstractLandState::states::COMP ||\n _actualState == AbstractLandState::states::R2LA ){\n\n \/\/Increment N if needed\n if (_horizontaErr < _tauHold) {\n _NLost = 0;\n _NHold++;\n }\n else if (_horizontaErr > _tauLost) {\n _NHold = 0;\n _NComp = 0;\n _NLost++;\n }\n\n if(_actualState == AbstractLandState::states::R2LA || _actualState == AbstractLandState::states::COMP){\n\n if(_prevState == AbstractLandState::states::HOLD) _NComp = 0;\n \/\/Check whether we are on place to land\n if (_horizontaErr < _tauHold * 0.5) {\n _NComp++;\n } else{\n _NComp = 0;\n }\n }\n\n _err_prev = _err;\n }\n\n#ifdef DEBUG\n\n std::cout << \"**********************************\" << std::endl;\n std::cout << \"STATE: \" << _actualState<< std::endl;\n std::cout << \"HERRO: \" << _horizontaErr<< std::endl;\n std::cout << \"HERRV: \" << _verticalErr<< std::endl;\n std::cout << \"NHOLD: \" << _NHold<< std::endl;\n std::cout << \"NLOST: \" << _NLost<< std::endl;\n std::cout << \"NCOMP: \" << _NComp<< std::endl;\n std::cout << \"INTEX: \" << _err_int[0] << std::endl;\n std::cout << \"INTEY: \" << _err_int[1] << std::endl;\n std::cout << \"**********************************\" << std::endl;\n#endif\n\n}\n\nvoid Lander::handleMachine() {\n\n updateSignals();\n _machine.handle();\n}\n\nint Lander::getActualMachineState() {\n return _machine.getActualNodeId();\n}\n\nvoid Lander::run() {\n\n handleMachine();\n _actualState = _machine.getActualNodeId();\n managetime();\n\n static bool initDone = false;\n switch (_actualState){\n\n case (AbstractLandState::states::INIT):\n if(!initDone){\n init();\n initDone = true;\n }\n break;\n\n case (AbstractLandState::states::HOLD):\n initDone = false;\n clampZSP();\n hold();\n break;\n case (AbstractLandState::states::DESC):\n\n desc();\n clampZSP();\n break;\n case (AbstractLandState::states::ASCE):\n\n asce();\n clampZSP();\n\n break;\n\n case (AbstractLandState::states::R2LA):\n clampZSP();\n hold();\n break;\n\n case (AbstractLandState::states::COMP):\n hold();\n comp();\n break;\n case (AbstractLandState::states::LAND):\n land();\n break;\n\n default:\n hold();\n break;\n\n }\n _prevState = _actualState;\n\n}\n\nvoid Lander::resetSetPoint() {\n\n _setPoint = _state;\n _setPoint.setType(MavState::type::POSITION);\n\n}\n\nvoid Lander::updateIntegrals() {\n\n _err_int[0] += _dt * _err[0];\n _err_int[1] += _dt * _err[1];\n\n double tempx,tempy;\n\n tempx = common::clamp(_err_int[0],params_automatic::minIntValue,params_automatic::maxIntValue);\n tempy = common::clamp(_err_int[1],params_automatic::minIntValue,params_automatic::maxIntValue);\n\n _err_int[0] = tempx;\n _err_int[1] = tempy;\n\n}\n\nvoid Lander::managetime() {\n\n _actualTime = common::time::getTimeMilliSecond();\n double dt = _prevTime != 0 ? (_actualTime - _prevTime) * (double)MILLI2SECS : 0.0;\n _prevTime = _actualTime;\n _dt = dt;\n\n}\n\nvoid Lander::resetIntegrals() {\n\n _err_int[0] = 0;\n _err_int[1] = 0;\n\n}\n\nvoid Lander::init() {\n\n \/\/Set point to my position\n resetSetPoint();\n\n \/\/Go to max tracking height\n _setPoint.setZ(params_automatic::zMax);\n\n}\n\nvoid Lander::hold() {\n\n \/\/This function is purely tracking, nothing more\n\n \/*\n * Tracking is performed by POSITION control, issuing the position setpoint\n * in order to achieve the desired velocity calculated by:\n *\n * Vdes = K * ep + Vplat\n * or\n * Psp = Pplat + K * Vplat\n *\n * where:\n *\n * Vdes = desired velocity, K = proportional gain, ep = position error, Vplat = paltform velocity\n *\/\n\n Eigen::Vector2d tempVel(_platformState.getVx(),_platformState.getVy());\n\n double xTarget = _holdPIDX.getOutput(_state.getX(), _platformState.getX());\n double yTarget = _holdPIDY.getOutput(_state.getY(), _platformState.getY());\n Eigen::Vector2d targetVect(xTarget,yTarget);\n\n\n updateIntegrals();\n \/\/PosSP = PlatPos + K * Vplat\n targetVect += params_automatic::KpHoldV * tempVel;\n\n \/\/Fill right fields\n _setPoint.setPosition(targetVect(0),targetVect(1),_setPoint.getZ());\n _setPoint.setType(MavState::POSITION);\n\n}\n\nvoid Lander::asce() {\n\n resetIntegrals();\n _setPoint.setZ(_setPoint.getZ() + 0.1);\n\n}\n\nvoid Lander::desc() {\n\n\n _setPoint.setZ(_setPoint.getZ() - 0.1);\n}\n\nvoid Lander::comp() {\n\n \/\/Calculate desired vertical velocity in order to compensate oscillations\n double dz = - _state.getZ() + _platformState.getZ() + PLATFORM_OFFSET;\n double desc = common::interpolate(fabs(dz), DRATE_MAX, DRATE_MIN, TMAX, TMIN);\n double z_target_v = _platformState.getVz() - desc;\n\n double err_v = z_target_v - _state.getVz();\n\n double corr = 1;\n\n if(_platformState.getVz() > 0) corr = 1.2;\n\n z_target_v += corr * params_automatic::KPCompV * (err_v);\n\n \/\/Now we need to transform this velocity in a position setpoint since in Firmware:\n \/\/ VelSP = Kp * PosError then PosSP = ( VelSP \/ Kp ) + RobotPos\n\n _setPoint.setZ((z_target_v) + _state.getZ());\n\n}\n\nvoid Lander::clampZSP() {\n\n double temp;\n temp = common::clamp(_setPoint.getZ(),params_automatic::zMin,params_automatic::zMax);\n\n _setPoint.setZ(temp);\n}\n\nvoid Lander::land() {\n\n resetSetPoint();\n _setPoint.setZ(_state.getZ()-10);\n\n}\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <MyHeaders\\SocketClient.h>\n\nSocketClient::SocketClient()\n{\n\tSocket = 0;\n}\n\nSocketClient::SocketClient(SOCKET con)\n{\n\tSocket = con;\n}\n\nSocketClient::SocketClient(const unsigned int major, const unsigned int minor)\n{\n\tSocket = 0;\n\tInit(major, minor);\n}\n\nbool SocketClient::WinsockInitialized()\n{\n\tSOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tif (s == INVALID_SOCKET && WSAGetLastError() == WSANOTINITIALISED)\n\t\treturn false;\n\n\tclosesocket(s);\n\treturn true;\n}\n\nSocketClient::operator SOCKET()\n{\n\treturn Socket;\n}\n\nbool SocketClient::Init(const unsigned int major, const unsigned int minor)\n{\n\tif (!WinsockInitialized())\n\t\treturn WSAStartup(MAKEWORD(major, minor), &wsaData) == 0;\n\n\treturn false;\n}\n\nbool SocketClient::Connect(const TCHAR *host, const TCHAR *port)\n{\n\tADDRINFOT *res;\n\tADDRINFOT *ptr;\n\tADDRINFOT hints;\n\n\tmemset(&hints, 0, sizeof(hints));\n\n\thints.ai_family = AF_UNSPEC;\n\thints.ai_socktype = SOCK_STREAM;\n\n\tif (GetAddrInfo(host, port, &hints, &res))\n\t{\n\t\tClose();\n\t\treturn false;\n\t}\n\n\tSocket = 0;\n\n\tfor (ptr = res; ptr != NULL; ptr = ptr->ai_next)\n\t{\n\t\tSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);\n\n\t\tif (Socket == INVALID_SOCKET)\n\t\t{\n\t\t\tSocket = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (connect(Socket, ptr->ai_addr, ptr->ai_addrlen) == SOCKET_ERROR)\n\t\t{\n\t\t\tclosesocket(Socket);\n\t\t\tSocket = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tFreeAddrInfo(res);\n\n\treturn Socket != 0;\n}\n\nint SocketClient::Send(const void *buffer, const unsigned int len, const SCSFlag flags)\n{\n\tint res;\n\tif ((res = send(Socket, (const char*)buffer, len, flags)) == SOCKET_ERROR)\n\t{\n\t\tClose();\n\t\treturn 0;\n\t}\n\n\treturn res;\n}\n\nint SocketClient::Recieve(void *buffer, const unsigned int len, const SCRFlag flags)\n{\n\tint res;\n\tif ((res = recv(Socket, (char*)buffer, len, flags)) == SOCKET_ERROR)\n\t{\n\t\tClose();\n\t\treturn 0;\n\t}\n\n\treturn res;\n}\n\nbool SocketClient::SetBlockingState(const bool blocking)\n{\n\tu_long iMode = blocking ? 1 : 0;\n\treturn ioctlsocket(Socket, FIONBIO, &iMode) == 0;\n}\nbool SocketClient::CheckReadability(const unsigned int secs, const unsigned int microsecs)\n{\n\ttimeval tv = { secs, microsecs };\n\tfd_set fd;\n\tFD_ZERO(&fd);\n\tFD_SET(Socket, &fd);\n\treturn select(Socket, &fd, 0, 0, &tv) > 0;\n}\nbool SocketClient::CheckWritability(const unsigned int secs, const unsigned int microsecs)\n{\n\ttimeval tv = { secs, microsecs };\n\tfd_set fd;\n\tFD_ZERO(&fd);\n\tFD_SET(Socket, &fd);\n\treturn select(Socket, 0, &fd, 0, &tv) > 0;\n}\n\nbool SocketClient::ShutDownRcv()\n{\n\tif (shutdown(Socket, SD_RECEIVE) == SOCKET_ERROR)\n\t{\n\t\tClose();\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool SocketClient::ShutDownSnd()\n{\n\tif (shutdown(Socket, SD_SEND) == SOCKET_ERROR)\n\t{\n\t\tClose();\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nunsigned int SocketClient::GetPendingDataSize()\n{\n\tunsigned long int size = 0;\n\tif (ioctlsocket(Socket, FIONREAD, &size) != 0)\n\t\treturn 0;\n\n\treturn size;\n}\n\nvoid SocketClient::Close()\n{\n\tif (Socket)\n\t{\n\t\tclosesocket(Socket);\n\t\tSocket = 0;\n\t}\n}\n\nbool SocketClient::Clean()\n{\n\tif (WinsockInitialized())\n\t{\n\t\tif (WSACleanup() == 0)\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nSocketClient::~SocketClient()\n{\n\tClose();\n}<commit_msg>Minor change<commit_after>#include <MyHeaders\\SocketClient.h>\n\nSocketClient::SocketClient()\n{\n\tSocket = 0;\n}\n\nSocketClient::SocketClient(SOCKET con)\n{\n\tSocket = con;\n}\n\nSocketClient::SocketClient(const unsigned int major, const unsigned int minor)\n{\n\tSocket = 0;\n\tInit(major, minor);\n}\n\nbool SocketClient::WinsockInitialized()\n{\n\tSOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tif (s == INVALID_SOCKET && WSAGetLastError() == WSANOTINITIALISED)\n\t\treturn false;\n\n\tclosesocket(s);\n\treturn true;\n}\n\nSocketClient::operator SOCKET()\n{\n\treturn Socket;\n}\n\nbool SocketClient::Init(const unsigned int major, const unsigned int minor)\n{\n\tif (!WinsockInitialized())\n\t\treturn WSAStartup(MAKEWORD(major, minor), &wsaData) == 0;\n\n\treturn false;\n}\n\nbool SocketClient::Connect(const TCHAR *host, const TCHAR *port)\n{\n\tADDRINFOT *res;\n\tADDRINFOT *ptr;\n\tADDRINFOT hints;\n\n\tmemset(&hints, 0, sizeof(hints));\n\n\thints.ai_family = AF_UNSPEC;\n\thints.ai_socktype = SOCK_STREAM;\n\n\tif (GetAddrInfo(host, port, &hints, &res))\n\t{\n\t\tClose();\n\t\treturn false;\n\t}\n\n\tSocket = 0;\n\n\tfor (ptr = res; ptr != NULL; ptr = ptr->ai_next)\n\t{\n\t\tSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);\n\n\t\tif (Socket == INVALID_SOCKET)\n\t\t{\n\t\t\tSocket = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (connect(Socket, ptr->ai_addr, ptr->ai_addrlen) == SOCKET_ERROR)\n\t\t{\n\t\t\tclosesocket(Socket);\n\t\t\tSocket = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tFreeAddrInfo(res);\n\n\treturn Socket != 0;\n}\n\nint SocketClient::Send(const void *buffer, const unsigned int len, const SCSFlag flags)\n{\n\tint res;\n\tif ((res = send(Socket, (const char*)buffer, len, flags)) == SOCKET_ERROR)\n\t{\n\t\tClose();\n\t\treturn 0;\n\t}\n\n\treturn res;\n}\n\nint SocketClient::Recieve(void *buffer, const unsigned int len, const SCRFlag flags)\n{\n\tint res;\n\tif ((res = recv(Socket, (char*)buffer, len, flags)) == SOCKET_ERROR)\n\t{\n\t\tClose();\n\t\treturn 0;\n\t}\n\n\treturn res;\n}\n\nbool SocketClient::SetBlockingState(const bool blocking)\n{\n\tu_long iMode = blocking ? 1 : 0;\n\treturn ioctlsocket(Socket, FIONBIO, &iMode) == 0;\n}\nbool SocketClient::CheckReadability(const unsigned int secs, const unsigned int microsecs)\n{\n\ttimeval tv = { secs, microsecs };\n\tfd_set fd;\n\tFD_ZERO(&fd);\n\tFD_SET(Socket, &fd);\n\treturn select(Socket, &fd, 0, 0, &tv) > 0;\n}\nbool SocketClient::CheckWritability(const unsigned int secs, const unsigned int microsecs)\n{\n\ttimeval tv = { secs, microsecs };\n\tfd_set fd;\n\tFD_ZERO(&fd);\n\tFD_SET(Socket, &fd);\n\treturn select(Socket, 0, &fd, 0, &tv) > 0;\n}\n\nbool SocketClient::ShutDownRcv()\n{\n\tif (shutdown(Socket, SD_RECEIVE) == SOCKET_ERROR)\n\t{\n\t\tClose();\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool SocketClient::ShutDownSnd()\n{\n\tif (shutdown(Socket, SD_SEND) == SOCKET_ERROR)\n\t{\n\t\tClose();\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nunsigned int SocketClient::GetPendingDataSize()\n{\n\tunsigned long int size = 0;\n\tif (ioctlsocket(Socket, FIONREAD, &size) != 0)\n\t\treturn 0;\n\n\treturn size;\n}\n\nvoid SocketClient::Close()\n{\n\tif (Socket)\n\t{\n\t\tclosesocket(Socket);\n\t\tSocket = 0;\n\t}\n}\n\nbool SocketClient::Clean()\n{\n\tif (WinsockInitialized())\n\t{\n\t\treturn WSACleanup() == 0;\n\t}\n\n\treturn false;\n}\n\nSocketClient::~SocketClient()\n{\n\tClose();\n}<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2012, Stuart W Baker\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 met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file HwInit.cxx\n * This file represents the hardware initialization for the TI Tiva MCU.\n *\n * @author Stuart W. Baker\n * @date 5 January 2013\n *\/\n\n#include <new>\n#include <cstdint>\n\n#include \"inc\/hw_types.h\"\n#include \"inc\/hw_memmap.h\"\n#include \"inc\/hw_ints.h\"\n#include \"driverlib\/rom.h\"\n#include \"driverlib\/rom_map.h\"\n#include \"driverlib\/sysctl.h\"\n#include \"driverlib\/gpio.h\"\n#include \"driverlib\/timer.h\"\n#include \"driverlib\/interrupt.h\"\n#include \"driverlib\/pin_map.h\"\n#include \"os\/OS.hxx\"\n#include \"TivaDev.hxx\"\n#include \"hardware.hxx\"\n#include \"DccHardware.hxx\"\n#include \"TivaDCC.hxx\"\n\nstruct Debug {\n \/\/ High between start_cutout and end_cutout from the TivaRailcom driver.\n typedef DummyPin RailcomDriverCutout;\n \/\/ Flips every time an uart byte is received error.\n typedef DummyPin RailcomError;\n \/\/ Flips every time an 'E0' byte is received in the railcom driver.\n typedef DummyPin RailcomE0;\n};\n#include \"TivaRailcom.hxx\"\n\n\n\/** override stdin *\/\nconst char *STDIN_DEVICE = \"\/dev\/ser0\";\n\n\/** override stdout *\/\nconst char *STDOUT_DEVICE = \"\/dev\/ser0\";\n\n\/** override stderr *\/\nconst char *STDERR_DEVICE = \"\/dev\/ser0\";\n\n\/** USB Device CDC serial driver instance *\/\nstatic TivaCdc cdc0(\"\/dev\/serUSB0\", INT_RESOLVE(INT_USB0_, 0));\n\n\/** UART 0 serial driver instance *\/\nstatic TivaUart uart0(\"\/dev\/ser0\", UART0_BASE, INT_RESOLVE(INT_UART0_, 0));\n\n\/** CAN 0 CAN driver instance *\/\nstatic TivaCan can0(\"\/dev\/can0\", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));\n\n\/\/ Bit storing whether our dcc output is enabled or not.\nstatic bool g_dcc_on = false;\n\nTivaRailcomDriver<RailcomDefs> railcom_driver(\"\/dev\/railcom\");\nTivaDCC<DccHwDefs> dcc_hw(\"\/dev\/mainline\", &railcom_driver);\n\nextern \"C\" {\n\nvoid hw_set_to_safe(void)\n{\n dcc_hw.disable_output();\n}\n\nvoid timer1a_interrupt_handler(void)\n{\n dcc_hw.interrupt_handler();\n}\n\nvoid timer0a_interrupt_handler(void)\n{\n dcc_hw.os_interrupt_handler();\n}\n\nvoid uart1_interrupt_handler(void)\n{\n railcom_driver.os_interrupt_handler();\n}\n\n\/** Blink LED *\/\nuint32_t blinker_pattern = 0;\nstatic uint32_t rest_pattern = 0;\n\nvoid resetblink(uint32_t pattern)\n{\n blinker_pattern = pattern;\n \/* make a timer event trigger immediately *\/\n}\n\nvoid setblink(uint32_t pattern)\n{\n resetblink(pattern);\n}\n\nvoid timer5a_interrupt_handler(void)\n{\n \/\/\n \/\/ Clear the timer interrupt.\n \/\/\n MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);\n \/\/ Set output LED.\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1,\n (rest_pattern & 1) ? GPIO_PIN_1 : 0);\n \/\/ Shift and maybe reset pattern.\n rest_pattern >>= 1;\n if (!rest_pattern)\n rest_pattern = blinker_pattern;\n}\n\nvoid diewith(uint32_t pattern)\n{\n hw_set_to_safe();\n vPortClearInterruptMask(0x20);\n asm(\"cpsie i\\n\");\n\n resetblink(pattern);\n while (1)\n ;\n}\n\n\/** Configures a GPIO pin to directly drive a LED (with 8mA output drive). *\/\nvoid set_gpio_led(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0xff);\n MAP_GPIOPinTypeGPIOOutput(port, pin); \n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_8MA_SC, GPIO_PIN_TYPE_STD); \n MAP_GPIOPinWrite(port, pin, 0xff);\n}\n\n\/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). *\/\nvoid set_gpio_drive_low(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0);\n MAP_GPIOPinTypeGPIOOutput(port, pin); \n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD); \n MAP_GPIOPinWrite(port, pin, 0);\n}\n\n\/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). *\/\nvoid set_gpio_drive_high(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0xff);\n MAP_GPIOPinTypeGPIOOutput(port, pin); \n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD); \n MAP_GPIOPinWrite(port, pin, 0xff);\n}\n\n\/** Configures a gpio pin for input with external pullup. *\/\nvoid set_gpio_extinput(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0);\n MAP_GPIOPinTypeGPIOInput(port, pin);\n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);\n}\n\n\/** Configures a gpio pin for input with internal pullup. *\/\nvoid set_gpio_puinput(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0);\n MAP_GPIOPinTypeGPIOInput(port, pin);\n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);\n}\n\nvoid enable_dcc() {\n g_dcc_on = true;\n MAP_GPIOPinWrite(LED_BLUE, 0xff);\n dcc_hw.enable_output();\n}\n\nvoid disable_dcc() {\n dcc_hw.disable_output();\n g_dcc_on = false;\n MAP_GPIOPinWrite(LED_BLUE, 0);\n}\n\nbool query_dcc() {\n return g_dcc_on;\n}\n\n\/** Initialize the processor hardware.\n *\/\nvoid hw_preinit(void)\n{\n \/* Globally disables interrupts until the FreeRTOS scheduler is up. *\/\n asm(\"cpsid i\\n\");\n\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n\n \/\/ Sets DCC hardware to safe state.\n \/\/ These pins are parallel-connected to the outputs.\n set_gpio_extinput(GPIO_PORTD_BASE, GPIO_PIN_0 | GPIO_PIN_1);\n \/* Initialize the DCC Timers and GPIO outputs *\/\n dcc_hw.hw_init();\n disable_dcc();\n\n \/* Setup the system clock. *\/\n MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |\n SYSCTL_XTAL_16MHZ);\n\n \/* Red LED pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n set_gpio_led(LED_RED);\n\n \/* Blinker timer initialization. *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);\n MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);\n MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() \/ 8);\n MAP_IntEnable(INT_TIMER5A);\n\n \/* This interrupt should hit even during kernel operations. *\/\n MAP_IntPrioritySet(INT_TIMER5A, 0);\n MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);\n MAP_TimerEnable(TIMER5_BASE, TIMER_A);\n\n \/* UART0 pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);\n MAP_GPIOPinConfigure(GPIO_PA0_U0RX);\n MAP_GPIOPinConfigure(GPIO_PA1_U0TX);\n MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);\n\n \/* USB0 pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);\n MAP_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4);\n\n \/* CAN pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);\n MAP_GPIOPinConfigure(GPIO_PE4_CAN0RX);\n MAP_GPIOPinConfigure(GPIO_PE5_CAN0TX);\n MAP_GPIOPinTypeCAN(GPIO_PORTE_BASE, GPIO_PIN_4 | GPIO_PIN_5);\n\n \/* Blue LED pin initialization *\/\n set_gpio_led(LED_BLUE);\n set_gpio_led(LED_GREEN);\n MAP_GPIOPinWrite(LED_GREEN, 0);\n MAP_GPIOPinWrite(LED_RED, 0);\n MAP_GPIOPinWrite(LED_BLUE, 0);\n\n \/* USB interrupt priority *\/\n MAP_IntPrioritySet(INT_USB0, 0xff); \/\/ USB interrupt low priority\n\n\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER1);\n}\n\n} \/\/ extern \"C\"\n<commit_msg>Fixes broken build when debug pins changed.<commit_after>\/** \\copyright\n * Copyright (c) 2012, Stuart W Baker\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 met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file HwInit.cxx\n * This file represents the hardware initialization for the TI Tiva MCU.\n *\n * @author Stuart W. Baker\n * @date 5 January 2013\n *\/\n\n#include <new>\n#include <cstdint>\n\n#include \"inc\/hw_types.h\"\n#include \"inc\/hw_memmap.h\"\n#include \"inc\/hw_ints.h\"\n#include \"driverlib\/rom.h\"\n#include \"driverlib\/rom_map.h\"\n#include \"driverlib\/sysctl.h\"\n#include \"driverlib\/gpio.h\"\n#include \"driverlib\/timer.h\"\n#include \"driverlib\/interrupt.h\"\n#include \"driverlib\/pin_map.h\"\n#include \"os\/OS.hxx\"\n#include \"TivaDev.hxx\"\n#include \"hardware.hxx\"\n#include \"DccHardware.hxx\"\n#include \"TivaDCC.hxx\"\n\nstruct Debug {\n \/\/ High between start_cutout and end_cutout from the TivaRailcom driver.\n typedef DummyPin RailcomDriverCutout;\n \/\/ Flips every time an uart byte is received error.\n typedef DummyPin RailcomError;\n \/\/ Flips every time an 'E0' byte is received in the railcom driver.\n typedef DummyPin RailcomE0;\n typedef DummyPin RailcomDataReceived;\n typedef DummyPin RailcomAnyData;\n typedef DummyPin RailcomPackets;\n};\n#include \"TivaRailcom.hxx\"\n\n\n\/** override stdin *\/\nconst char *STDIN_DEVICE = \"\/dev\/ser0\";\n\n\/** override stdout *\/\nconst char *STDOUT_DEVICE = \"\/dev\/ser0\";\n\n\/** override stderr *\/\nconst char *STDERR_DEVICE = \"\/dev\/ser0\";\n\n\/** USB Device CDC serial driver instance *\/\nstatic TivaCdc cdc0(\"\/dev\/serUSB0\", INT_RESOLVE(INT_USB0_, 0));\n\n\/** UART 0 serial driver instance *\/\nstatic TivaUart uart0(\"\/dev\/ser0\", UART0_BASE, INT_RESOLVE(INT_UART0_, 0));\n\n\/** CAN 0 CAN driver instance *\/\nstatic TivaCan can0(\"\/dev\/can0\", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));\n\n\/\/ Bit storing whether our dcc output is enabled or not.\nstatic bool g_dcc_on = false;\n\nTivaRailcomDriver<RailcomDefs> railcom_driver(\"\/dev\/railcom\");\nTivaDCC<DccHwDefs> dcc_hw(\"\/dev\/mainline\", &railcom_driver);\n\nextern \"C\" {\n\nvoid hw_set_to_safe(void)\n{\n dcc_hw.disable_output();\n}\n\nvoid timer1a_interrupt_handler(void)\n{\n dcc_hw.interrupt_handler();\n}\n\nvoid timer0a_interrupt_handler(void)\n{\n dcc_hw.os_interrupt_handler();\n}\n\nvoid uart1_interrupt_handler(void)\n{\n railcom_driver.os_interrupt_handler();\n}\n\n\/** Blink LED *\/\nuint32_t blinker_pattern = 0;\nstatic uint32_t rest_pattern = 0;\n\nvoid resetblink(uint32_t pattern)\n{\n blinker_pattern = pattern;\n \/* make a timer event trigger immediately *\/\n}\n\nvoid setblink(uint32_t pattern)\n{\n resetblink(pattern);\n}\n\nvoid timer5a_interrupt_handler(void)\n{\n \/\/\n \/\/ Clear the timer interrupt.\n \/\/\n MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);\n \/\/ Set output LED.\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1,\n (rest_pattern & 1) ? GPIO_PIN_1 : 0);\n \/\/ Shift and maybe reset pattern.\n rest_pattern >>= 1;\n if (!rest_pattern)\n rest_pattern = blinker_pattern;\n}\n\nvoid diewith(uint32_t pattern)\n{\n hw_set_to_safe();\n vPortClearInterruptMask(0x20);\n asm(\"cpsie i\\n\");\n\n resetblink(pattern);\n while (1)\n ;\n}\n\n\/** Configures a GPIO pin to directly drive a LED (with 8mA output drive). *\/\nvoid set_gpio_led(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0xff);\n MAP_GPIOPinTypeGPIOOutput(port, pin); \n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_8MA_SC, GPIO_PIN_TYPE_STD); \n MAP_GPIOPinWrite(port, pin, 0xff);\n}\n\n\/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). *\/\nvoid set_gpio_drive_low(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0);\n MAP_GPIOPinTypeGPIOOutput(port, pin); \n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD); \n MAP_GPIOPinWrite(port, pin, 0);\n}\n\n\/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). *\/\nvoid set_gpio_drive_high(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0xff);\n MAP_GPIOPinTypeGPIOOutput(port, pin); \n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD); \n MAP_GPIOPinWrite(port, pin, 0xff);\n}\n\n\/** Configures a gpio pin for input with external pullup. *\/\nvoid set_gpio_extinput(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0);\n MAP_GPIOPinTypeGPIOInput(port, pin);\n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);\n}\n\n\/** Configures a gpio pin for input with internal pullup. *\/\nvoid set_gpio_puinput(uint32_t port, uint32_t pin) {\n MAP_GPIOPinWrite(port, pin, 0);\n MAP_GPIOPinTypeGPIOInput(port, pin);\n MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);\n}\n\nvoid enable_dcc() {\n g_dcc_on = true;\n MAP_GPIOPinWrite(LED_BLUE, 0xff);\n dcc_hw.enable_output();\n}\n\nvoid disable_dcc() {\n dcc_hw.disable_output();\n g_dcc_on = false;\n MAP_GPIOPinWrite(LED_BLUE, 0);\n}\n\nbool query_dcc() {\n return g_dcc_on;\n}\n\n\/** Initialize the processor hardware.\n *\/\nvoid hw_preinit(void)\n{\n \/* Globally disables interrupts until the FreeRTOS scheduler is up. *\/\n asm(\"cpsid i\\n\");\n\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n\n \/\/ Sets DCC hardware to safe state.\n \/\/ These pins are parallel-connected to the outputs.\n set_gpio_extinput(GPIO_PORTD_BASE, GPIO_PIN_0 | GPIO_PIN_1);\n \/* Initialize the DCC Timers and GPIO outputs *\/\n dcc_hw.hw_init();\n disable_dcc();\n\n \/* Setup the system clock. *\/\n MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |\n SYSCTL_XTAL_16MHZ);\n\n \/* Red LED pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n set_gpio_led(LED_RED);\n\n \/* Blinker timer initialization. *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);\n MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);\n MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() \/ 8);\n MAP_IntEnable(INT_TIMER5A);\n\n \/* This interrupt should hit even during kernel operations. *\/\n MAP_IntPrioritySet(INT_TIMER5A, 0);\n MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);\n MAP_TimerEnable(TIMER5_BASE, TIMER_A);\n\n \/* UART0 pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);\n MAP_GPIOPinConfigure(GPIO_PA0_U0RX);\n MAP_GPIOPinConfigure(GPIO_PA1_U0TX);\n MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);\n\n \/* USB0 pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);\n MAP_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4);\n\n \/* CAN pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);\n MAP_GPIOPinConfigure(GPIO_PE4_CAN0RX);\n MAP_GPIOPinConfigure(GPIO_PE5_CAN0TX);\n MAP_GPIOPinTypeCAN(GPIO_PORTE_BASE, GPIO_PIN_4 | GPIO_PIN_5);\n\n \/* Blue LED pin initialization *\/\n set_gpio_led(LED_BLUE);\n set_gpio_led(LED_GREEN);\n MAP_GPIOPinWrite(LED_GREEN, 0);\n MAP_GPIOPinWrite(LED_RED, 0);\n MAP_GPIOPinWrite(LED_BLUE, 0);\n\n \/* USB interrupt priority *\/\n MAP_IntPrioritySet(INT_USB0, 0xff); \/\/ USB interrupt low priority\n\n\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER1);\n}\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com)\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#include \"stdafx.h\"\n#include \"D3D11GraphicsDriver.hpp\"\n#include \"D3D11DynamicRegistration.hpp\"\n\n#include \"Events\/SceneObjectSelectedEvent.hpp\"\n#include \"Events\/SceneObjectFocusedEvent.hpp\"\n#include \"Events\/Events\/MouseButtonInputEvent.hpp\"\n\n#include \"Utilities\/ColorPicker.hpp\"\n\n#include \"Widgets\/MainStatusBar.hpp\"\n#include \"Widgets\/MainWindow.hpp\"\n#include \"Widgets\/ContentFrame.hpp\"\n#include \"Widgets\/SceneFrame.hpp\"\n#include \"Widgets\/SceneTree.hpp\"\n#include \"Widgets\/Properties\/Renderables\/RenderableDisplay.hpp\"\n\n#include \"Gizmos\/Axis\/AxisGizmo.hpp\"\n#include \"Gizmos\/Axis\/AxisComponentGizmo.hpp\"\n#include \"Graphics\/Texture\/NoiseTexture2D.hpp\"\n#include \"Graphics\/Texture\/TextureSavers\/TextureResourceSaver_PNG.hpp\"\n#include \"Math\/Noise\/PerlinNoise.hpp\"\n#include \"Math\/Noise\/SimplexNoise.hpp\"\n#include \"Math\/Noise\/WaveletNoise.hpp\"\n#include \"OcularEngine.hpp\"\n#include <regex>\n\n\/\/------------------------------------------------------------------------------------------\n\nnamespace Ocular\n{\n namespace Editor\n {\n \/\/----------------------------------------------------------------------------------\n \/\/ CONSTRUCTORS\n \/\/----------------------------------------------------------------------------------\n \n Editor& Editor::get()\n {\n static Editor instance;\n return instance;\n }\n\n Editor::Editor()\n : AEventListener(),\n m_MainWindow(nullptr),\n m_EditorCamera(nullptr),\n m_SelectedObject(nullptr),\n m_FocusedObject(nullptr)\n {\n \n }\n\n Editor::~Editor()\n {\n delete m_MainWindow;\n delete m_QtApp;\n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PUBLIC METHODS\n \/\/----------------------------------------------------------------------------------\n \n \/\/----------------------------------------------------------------------------------\n \/\/ Core Lifetime Methods\n \/\/----------------------------------------------------------------------------------\n\n bool Editor::initialize(int argc, char** argv)\n {\n bool result = false;\n\n m_QtApp = new QApplication(argc, argv);\n\n if(OcularEngine.initialize(new Ocular::Graphics::D3D11GraphicsDriver()))\n {\n OcularEvents->registerListener(this, Core::Priority::Low);\n\n m_MainWindow = new MainWindow();\n m_MainWindow->show();\n m_MainWindow->showMaximized();\n\n if(OcularGraphics->initialize())\n {\n OcularResources->initialize(); \/\/ \\todo really bad work around. trying to create default resources before driver is ready otherwise\n\n if(setupEditorCamera())\n {\n setupAxis();\n setupGizmos();\n\n result = true;\n OcularLogger->info(\"Successfully initialized \", OCULAR_VERSION);\n }\n else\n {\n OcularLogger->error(\"Failed to initialize Ocular Editor: failed to setup Editor cameras\");\n }\n }\n else\n {\n OcularLogger->error(\"Failed to initialize Ocular Editor: failed to initialize Ocular Graphics system\");\n }\n }\n else\n {\n OcularLogger->error(\"Failed to initialize Ocular Editor: failed to initialize Ocular Engine\");\n }\n\n return result;\n }\n\n void Editor::shutdown()\n {\n OcularEngine.shutdown();\n }\n\n bool Editor::run()\n {\n bool result = false;\n\n Ocular::Graphics::TextureDescriptor descriptor;\n descriptor.width = 512;\n descriptor.height = 512;\n\n std::shared_ptr<Ocular::Math::Noise::PerlinNoise> noise = std::make_shared<Ocular::Math::Noise::PerlinNoise>();\n noise->setOctaves(6);\n noise->setPersistence(0.5f);\n noise->setScale(0.01f);\n\n Ocular::Graphics::NoiseTexture2D* texture = new Ocular::Graphics::NoiseTexture2D(descriptor, noise);\n\n OcularEngine.ResourceManager()->saveResource(texture, Ocular::Core::File(\"TestOutput\/PerlinNoise.png\"));\n\n delete texture;\n texture = nullptr;\n\n if(OcularEngine.run())\n {\n m_MainWindow->update();\n m_QtApp->processEvents();\n \n result = true;\n }\n\n return result;\n }\n\n bool Editor::onEvent(std::shared_ptr<Core::AEvent> event)\n {\n if(event->isType<SceneObjectSelectedEvent>())\n {\n SceneObjectSelectedEvent* cast = dynamic_cast<SceneObjectSelectedEvent*>(event.get());\n m_SelectedObject = cast->object;\n }\n else if(event->isType<SceneObjectFocusedEvent>())\n {\n SceneObjectFocusedEvent* cast = dynamic_cast<SceneObjectFocusedEvent*>(event.get());\n m_FocusedObject = cast->object;\n }\n else if(event->isType<Core::MouseButtonInputEvent>())\n {\n Core::MouseButtonInputEvent* cast = dynamic_cast<Core::MouseButtonInputEvent*>(event.get());\n\n if(cast->button == Core::MouseButtons::Left)\n {\n \/\/ Check if alt key is down (we assume a rotation around target if it is down)\n if(!OcularInput->isKeyboardKeyDown(Core::KeyboardKeys::AltLeft))\n {\n performMousePick(cast->state);\n }\n }\n }\n\n return true;\n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ Primary Getters\n \/\/----------------------------------------------------------------------------------\n\n MainWindow* Editor::getMainWindow() const\n {\n return m_MainWindow;\n }\n\n Core::Camera* Editor::getEditorCamera() const\n {\n return m_EditorCamera;\n }\n\n void Editor::setSelectedObject(Core::SceneObject* object, bool ignoreNormalObject, bool ignoreGizmoObject)\n {\n std::shared_ptr<Core::AEvent> event = nullptr;\n\n m_GizmoTranslate->setSelected(false);\n\n if(object)\n {\n m_GizmoTranslate->setActive(true);\n\n Gizmo* gizmo = dynamic_cast<Gizmo*>(object);\n\n if(gizmo)\n {\n \/\/ If the selected object was a gizmo (or part of a gizmo), we can not \n \/\/ set it as the selected object for obvious reasons.\n\n \/\/ Instead we notify the gizmo that it has been selected (so that it can\n \/\/ handle dragging, etc.) and maintain the current selected object.\n\n if(!ignoreGizmoObject)\n {\n gizmo->setSelected(true);\n }\n }\n else\n {\n if(!ignoreNormalObject)\n {\n m_SelectedObject = object;\n\n m_MainWindow->getContentFrame()->getSceneFrame()->getSceneTree()->selectObject(m_SelectedObject);\n m_SelectedObject->addChild(m_GizmoTranslate, false);\n\n event = std::make_shared<SceneObjectSelectedEvent>(m_SelectedObject);\n }\n }\n }\n else\n {\n \/\/ Deselect\n\n m_GizmoTranslate->setActive(false);\n m_GizmoTranslate->setParent(nullptr, false);\n\n m_MainWindow->getContentFrame()->getSceneFrame()->getSceneTree()->selectObject(nullptr);\n\n event = std::make_shared<SceneObjectSelectedEvent>(nullptr);\n }\n\n if(event)\n {\n OcularEvents->queueEvent(event);\n }\n }\n\n Core::SceneObject* Editor::getSelectedObject() const\n {\n return m_SelectedObject;\n }\n\n Core::SceneObject* Editor::getFocusedObject() const\n {\n return m_FocusedObject;\n }\n \n \/\/----------------------------------------------------------------------------------\n \/\/ Misc Methods\n \/\/----------------------------------------------------------------------------------\n\n void Editor::setStatusNormal(std::string const& message)\n {\n auto statusBar = m_MainWindow->getMainStatusBar();\n\n if(statusBar)\n {\n statusBar->addWidget(new QLabel(message.c_str()));\n }\n }\n\n void Editor::setStatusPermanent(std::string const& message)\n {\n auto statusBar = m_MainWindow->getMainStatusBar();\n\n if(statusBar)\n {\n statusBar->setPermanentMessage(message.c_str());\n }\n }\n\n void Editor::setStatusTemporary(std::string const& message, uint32_t const lifetime)\n {\n auto statusBar = m_MainWindow->getMainStatusBar();\n\n if(statusBar)\n {\n statusBar->showMessage(message.c_str(), lifetime);\n }\n }\n\n void Editor::setStatusNormalProgress(std::string const& message, uint32_t const progress)\n {\n throw std::exception(\"implement me\");\n }\n \n \/\/----------------------------------------------------------------------------------\n \/\/ Widget Factories\n \/\/----------------------------------------------------------------------------------\n\n PropertyWidget* Editor::createPropertyWidget(std::string const& displayName, std::string const& type)\n {\n PropertyWidget* result = m_PropertyWidgetFactory.createComponent(type);\n\n if(result)\n {\n result->setDisplayName(displayName);\n }\n\n return result;\n }\n\n Core::ComponentFactory<PropertyWidget>& Editor::getPropertyWidgetFactory()\n {\n return m_PropertyWidgetFactory;\n }\n\n PropertiesDisplayBox* Editor::createCustomDisplay(std::string const& type)\n {\n PropertiesDisplayBox* result = m_CustomDisplayFactory.createComponent(type);\n\n if(result)\n {\n result->setTitle(type.c_str());\n }\n\n return result;\n }\n\n Core::ComponentFactory<PropertiesDisplayBox>& Editor::getCustomDisplayFactory()\n {\n return m_CustomDisplayFactory;\n }\n\n RenderableDisplay* Editor::createRenderableDisplay(std::string const& type)\n {\n RenderableDisplay* result = m_RenderableDisplayFactory.createComponent(type);\n\n if(result)\n {\n result->setTitle(type.c_str());\n }\n\n return result;\n }\n\n Core::ComponentFactory<RenderableDisplay>& Editor::getRenderableDisplayFactory()\n {\n return m_RenderableDisplayFactory;\n }\n \n \/\/----------------------------------------------------------------------------------\n \/\/ Static Methods\n \/\/----------------------------------------------------------------------------------\n\n bool Editor::IsCommonName(std::string const& name)\n {\n bool result = false;\n\n static std::string CommonNames[8] =\n {\n \"m_IsActive\",\n \"m_Name\",\n \"m_Position\",\n \"m_Rotation\",\n \"m_Scale\",\n \"m_Class\",\n \"m_IsStatic\",\n \"m_ForcedVisible\"\n };\n\n for(auto commonName : CommonNames)\n {\n if(Utils::String::IsEqual(name, commonName))\n {\n result = true;\n break;\n }\n }\n\n return result;\n }\n\n std::string Editor::FormatName(std::string const& name)\n {\n std::string result = name;\n\n \/\/------------------------------------------------------------\n \/\/ Remove any \"m_\"\n\n \/\/ Do regex instead!\n\n if((result.size() > 2) && (result[0] == 'm') && (result[1] == '_'))\n {\n result = result.substr(2);\n }\n \n \/\/------------------------------------------------------------\n \/\/ Split apart camel case\n\n const std::regex caseExp(\"([a-z0-9])([A-Z])\");\n result = std::regex_replace(result, caseExp, \"$1 $2\");\n\n return result;\n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PROTECTED METHODS\n \/\/----------------------------------------------------------------------------------\n \n \/\/----------------------------------------------------------------------------------\n \/\/ PRIVATE METHODS\n \/\/----------------------------------------------------------------------------------\n\n bool Editor::setupEditorCamera()\n {\n bool result = false;\n\n m_EditorCamera = OcularScene->createObject<Core::Camera>(\"OCULAR_INTERNAL_EDITOR_CAMERA\", nullptr);\n \n if(m_EditorCamera)\n {\n Core::PerspectiveProjection projection = m_EditorCamera->getPerspectiveProjection();\n projection.farClip = 10000.0f;\n\n m_EditorCamera->setProjectionPerspective(projection);\n m_EditorCamera->setPersistent(true);\n m_EditorCamera->setPosition(0.0f, 0.2f, 0.5f);\n m_EditorCamera->addRoutine(\"EditorCameraController\");\n\n result = true;\n }\n\n return result;\n }\n\n void Editor::setupAxis()\n {\n const float length = 10000.0f;\n \n OcularGraphics->drawDebugLine(Math::Vector3f(0.0f, 0.0f, 0.0f), Math::Vector3f(length, 0.0f, 0.0f), Core::Color::Red(), 0);\n OcularGraphics->drawDebugLine(Math::Vector3f(0.0f, 0.0f, 0.0f), Math::Vector3f(0.0f, length, 0.0f), Core::Color::Green(), 0);\n OcularGraphics->drawDebugLine(Math::Vector3f(0.0f, 0.0f, 0.0f), Math::Vector3f(0.0f, 0.0f, length), Core::Color::Blue(), 0);\n }\n\n void Editor::setupGizmos()\n {\n m_GizmoTranslate = new AxisGizmo();\n m_GizmoTranslate->setName(\"OCULAR_INTERNAL_EDITOR_GIZMO_TRANSLATE\");\n m_GizmoTranslate->setActive(false);\n }\n\n void Editor::performMousePick(Core::KeyState const state)\n {\n auto mousePos = OcularInput->getMousePosition();\n auto editorCamera = OcularEditor.getEditorCamera();\n\n if(editorCamera)\n {\n auto ray = editorCamera->getPickRay(mousePos);\n \/\/OcularGraphics->drawDebugLine(ray.getOrigin(), ray.getPointAlong(100.0f), Core::Color::Yellow(), 15000);\n \n std::vector<std::pair<Core::SceneObject*, float>> intersections;\n\n OcularScene->getIntersections(ray, intersections);\n\n if(intersections.size())\n {\n if(state == Core::KeyState::Released)\n {\n \/\/ On mouse up, we only care about picking normal (non-gizmo) objects\n setSelectedObject(intersections[0].first, false, true);\n }\n else\n {\n \/\/ On mouse down, we only care about picking gizmo objects\n auto gizmo = pickedGizmo(intersections);\n\n if(gizmo)\n {\n setSelectedObject(gizmo, true, false);\n }\n }\n }\n else\n {\n \/\/ If the currently selected object is a gizmo, we simply de-select the gizmo but keep the parent object selected\n if(m_GizmoTranslate->isSelected())\n {\n m_GizmoTranslate->setSelected(false);\n }\n else\n {\n \/\/ No object selected. Treat it as a de-select.\n setSelectedObject(nullptr, false, true);\n }\n }\n }\n }\n\n Core::SceneObject* Editor::pickedGizmo(std::vector<std::pair<Core::SceneObject*, float>> const& intersections) const\n {\n \/\/ Check if among the picked items is a gizmo object. If so, we will assume that was the intended pick target.\n Core::SceneObject* result = nullptr;\n\n for(auto pair : intersections)\n {\n auto object = pair.first;\n\n if(object)\n {\n if(OcularString->IsEqual(object->getClass(), OCULAR_TYPE_NAME(AxisComponentGizmo)))\n {\n result = object;\n break;\n }\n }\n }\n\n return result;\n }\n }\n}<commit_msg>Removing old test code<commit_after>\/**\n * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com)\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#include \"stdafx.h\"\n#include \"D3D11GraphicsDriver.hpp\"\n#include \"D3D11DynamicRegistration.hpp\"\n\n#include \"Events\/SceneObjectSelectedEvent.hpp\"\n#include \"Events\/SceneObjectFocusedEvent.hpp\"\n#include \"Events\/Events\/MouseButtonInputEvent.hpp\"\n\n#include \"Utilities\/ColorPicker.hpp\"\n\n#include \"Widgets\/MainStatusBar.hpp\"\n#include \"Widgets\/MainWindow.hpp\"\n#include \"Widgets\/ContentFrame.hpp\"\n#include \"Widgets\/SceneFrame.hpp\"\n#include \"Widgets\/SceneTree.hpp\"\n#include \"Widgets\/Properties\/Renderables\/RenderableDisplay.hpp\"\n\n#include \"Gizmos\/Axis\/AxisGizmo.hpp\"\n#include \"Gizmos\/Axis\/AxisComponentGizmo.hpp\"\n#include \"Graphics\/Texture\/NoiseTexture2D.hpp\"\n#include \"Graphics\/Texture\/TextureSavers\/TextureResourceSaver_PNG.hpp\"\n#include \"Math\/Noise\/PerlinNoise.hpp\"\n#include \"Math\/Noise\/SimplexNoise.hpp\"\n#include \"Math\/Noise\/WaveletNoise.hpp\"\n#include \"OcularEngine.hpp\"\n#include <regex>\n\n\/\/------------------------------------------------------------------------------------------\n\nnamespace Ocular\n{\n namespace Editor\n {\n \/\/----------------------------------------------------------------------------------\n \/\/ CONSTRUCTORS\n \/\/----------------------------------------------------------------------------------\n \n Editor& Editor::get()\n {\n static Editor instance;\n return instance;\n }\n\n Editor::Editor()\n : AEventListener(),\n m_MainWindow(nullptr),\n m_EditorCamera(nullptr),\n m_SelectedObject(nullptr),\n m_FocusedObject(nullptr)\n {\n \n }\n\n Editor::~Editor()\n {\n delete m_MainWindow;\n delete m_QtApp;\n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PUBLIC METHODS\n \/\/----------------------------------------------------------------------------------\n \n \/\/----------------------------------------------------------------------------------\n \/\/ Core Lifetime Methods\n \/\/----------------------------------------------------------------------------------\n\n bool Editor::initialize(int argc, char** argv)\n {\n bool result = false;\n\n m_QtApp = new QApplication(argc, argv);\n\n if(OcularEngine.initialize(new Ocular::Graphics::D3D11GraphicsDriver()))\n {\n OcularEvents->registerListener(this, Core::Priority::Low);\n\n m_MainWindow = new MainWindow();\n m_MainWindow->show();\n m_MainWindow->showMaximized();\n\n if(OcularGraphics->initialize())\n {\n OcularResources->initialize(); \/\/ \\todo really bad work around. trying to create default resources before driver is ready otherwise\n\n if(setupEditorCamera())\n {\n setupAxis();\n setupGizmos();\n\n result = true;\n OcularLogger->info(\"Successfully initialized \", OCULAR_VERSION);\n }\n else\n {\n OcularLogger->error(\"Failed to initialize Ocular Editor: failed to setup Editor cameras\");\n }\n }\n else\n {\n OcularLogger->error(\"Failed to initialize Ocular Editor: failed to initialize Ocular Graphics system\");\n }\n }\n else\n {\n OcularLogger->error(\"Failed to initialize Ocular Editor: failed to initialize Ocular Engine\");\n }\n\n return result;\n }\n\n void Editor::shutdown()\n {\n OcularEngine.shutdown();\n }\n\n bool Editor::run()\n {\n bool result = false;\n\n if(OcularEngine.run())\n {\n m_MainWindow->update();\n m_QtApp->processEvents();\n \n result = true;\n }\n\n return result;\n }\n\n bool Editor::onEvent(std::shared_ptr<Core::AEvent> event)\n {\n if(event->isType<SceneObjectSelectedEvent>())\n {\n SceneObjectSelectedEvent* cast = dynamic_cast<SceneObjectSelectedEvent*>(event.get());\n m_SelectedObject = cast->object;\n }\n else if(event->isType<SceneObjectFocusedEvent>())\n {\n SceneObjectFocusedEvent* cast = dynamic_cast<SceneObjectFocusedEvent*>(event.get());\n m_FocusedObject = cast->object;\n }\n else if(event->isType<Core::MouseButtonInputEvent>())\n {\n Core::MouseButtonInputEvent* cast = dynamic_cast<Core::MouseButtonInputEvent*>(event.get());\n\n if(cast->button == Core::MouseButtons::Left)\n {\n \/\/ Check if alt key is down (we assume a rotation around target if it is down)\n if(!OcularInput->isKeyboardKeyDown(Core::KeyboardKeys::AltLeft))\n {\n performMousePick(cast->state);\n }\n }\n }\n\n return true;\n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ Primary Getters\n \/\/----------------------------------------------------------------------------------\n\n MainWindow* Editor::getMainWindow() const\n {\n return m_MainWindow;\n }\n\n Core::Camera* Editor::getEditorCamera() const\n {\n return m_EditorCamera;\n }\n\n void Editor::setSelectedObject(Core::SceneObject* object, bool ignoreNormalObject, bool ignoreGizmoObject)\n {\n std::shared_ptr<Core::AEvent> event = nullptr;\n\n m_GizmoTranslate->setSelected(false);\n\n if(object)\n {\n m_GizmoTranslate->setActive(true);\n\n Gizmo* gizmo = dynamic_cast<Gizmo*>(object);\n\n if(gizmo)\n {\n \/\/ If the selected object was a gizmo (or part of a gizmo), we can not \n \/\/ set it as the selected object for obvious reasons.\n\n \/\/ Instead we notify the gizmo that it has been selected (so that it can\n \/\/ handle dragging, etc.) and maintain the current selected object.\n\n if(!ignoreGizmoObject)\n {\n gizmo->setSelected(true);\n }\n }\n else\n {\n if(!ignoreNormalObject)\n {\n m_SelectedObject = object;\n\n m_MainWindow->getContentFrame()->getSceneFrame()->getSceneTree()->selectObject(m_SelectedObject);\n m_SelectedObject->addChild(m_GizmoTranslate, false);\n\n event = std::make_shared<SceneObjectSelectedEvent>(m_SelectedObject);\n }\n }\n }\n else\n {\n \/\/ Deselect\n\n m_GizmoTranslate->setActive(false);\n m_GizmoTranslate->setParent(nullptr, false);\n\n m_MainWindow->getContentFrame()->getSceneFrame()->getSceneTree()->selectObject(nullptr);\n\n event = std::make_shared<SceneObjectSelectedEvent>(nullptr);\n }\n\n if(event)\n {\n OcularEvents->queueEvent(event);\n }\n }\n\n Core::SceneObject* Editor::getSelectedObject() const\n {\n return m_SelectedObject;\n }\n\n Core::SceneObject* Editor::getFocusedObject() const\n {\n return m_FocusedObject;\n }\n \n \/\/----------------------------------------------------------------------------------\n \/\/ Misc Methods\n \/\/----------------------------------------------------------------------------------\n\n void Editor::setStatusNormal(std::string const& message)\n {\n auto statusBar = m_MainWindow->getMainStatusBar();\n\n if(statusBar)\n {\n statusBar->addWidget(new QLabel(message.c_str()));\n }\n }\n\n void Editor::setStatusPermanent(std::string const& message)\n {\n auto statusBar = m_MainWindow->getMainStatusBar();\n\n if(statusBar)\n {\n statusBar->setPermanentMessage(message.c_str());\n }\n }\n\n void Editor::setStatusTemporary(std::string const& message, uint32_t const lifetime)\n {\n auto statusBar = m_MainWindow->getMainStatusBar();\n\n if(statusBar)\n {\n statusBar->showMessage(message.c_str(), lifetime);\n }\n }\n\n void Editor::setStatusNormalProgress(std::string const& message, uint32_t const progress)\n {\n throw std::exception(\"implement me\");\n }\n \n \/\/----------------------------------------------------------------------------------\n \/\/ Widget Factories\n \/\/----------------------------------------------------------------------------------\n\n PropertyWidget* Editor::createPropertyWidget(std::string const& displayName, std::string const& type)\n {\n PropertyWidget* result = m_PropertyWidgetFactory.createComponent(type);\n\n if(result)\n {\n result->setDisplayName(displayName);\n }\n\n return result;\n }\n\n Core::ComponentFactory<PropertyWidget>& Editor::getPropertyWidgetFactory()\n {\n return m_PropertyWidgetFactory;\n }\n\n PropertiesDisplayBox* Editor::createCustomDisplay(std::string const& type)\n {\n PropertiesDisplayBox* result = m_CustomDisplayFactory.createComponent(type);\n\n if(result)\n {\n result->setTitle(type.c_str());\n }\n\n return result;\n }\n\n Core::ComponentFactory<PropertiesDisplayBox>& Editor::getCustomDisplayFactory()\n {\n return m_CustomDisplayFactory;\n }\n\n RenderableDisplay* Editor::createRenderableDisplay(std::string const& type)\n {\n RenderableDisplay* result = m_RenderableDisplayFactory.createComponent(type);\n\n if(result)\n {\n result->setTitle(type.c_str());\n }\n\n return result;\n }\n\n Core::ComponentFactory<RenderableDisplay>& Editor::getRenderableDisplayFactory()\n {\n return m_RenderableDisplayFactory;\n }\n \n \/\/----------------------------------------------------------------------------------\n \/\/ Static Methods\n \/\/----------------------------------------------------------------------------------\n\n bool Editor::IsCommonName(std::string const& name)\n {\n bool result = false;\n\n static std::string CommonNames[8] =\n {\n \"m_IsActive\",\n \"m_Name\",\n \"m_Position\",\n \"m_Rotation\",\n \"m_Scale\",\n \"m_Class\",\n \"m_IsStatic\",\n \"m_ForcedVisible\"\n };\n\n for(auto commonName : CommonNames)\n {\n if(Utils::String::IsEqual(name, commonName))\n {\n result = true;\n break;\n }\n }\n\n return result;\n }\n\n std::string Editor::FormatName(std::string const& name)\n {\n std::string result = name;\n\n \/\/------------------------------------------------------------\n \/\/ Remove any \"m_\"\n\n \/\/ Do regex instead!\n\n if((result.size() > 2) && (result[0] == 'm') && (result[1] == '_'))\n {\n result = result.substr(2);\n }\n \n \/\/------------------------------------------------------------\n \/\/ Split apart camel case\n\n const std::regex caseExp(\"([a-z0-9])([A-Z])\");\n result = std::regex_replace(result, caseExp, \"$1 $2\");\n\n return result;\n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PROTECTED METHODS\n \/\/----------------------------------------------------------------------------------\n \n \/\/----------------------------------------------------------------------------------\n \/\/ PRIVATE METHODS\n \/\/----------------------------------------------------------------------------------\n\n bool Editor::setupEditorCamera()\n {\n bool result = false;\n\n m_EditorCamera = OcularScene->createObject<Core::Camera>(\"OCULAR_INTERNAL_EDITOR_CAMERA\", nullptr);\n \n if(m_EditorCamera)\n {\n Core::PerspectiveProjection projection = m_EditorCamera->getPerspectiveProjection();\n projection.farClip = 10000.0f;\n\n m_EditorCamera->setProjectionPerspective(projection);\n m_EditorCamera->setPersistent(true);\n m_EditorCamera->setPosition(0.0f, 0.2f, 0.5f);\n m_EditorCamera->addRoutine(\"EditorCameraController\");\n\n result = true;\n }\n\n return result;\n }\n\n void Editor::setupAxis()\n {\n const float length = 10000.0f;\n \n OcularGraphics->drawDebugLine(Math::Vector3f(0.0f, 0.0f, 0.0f), Math::Vector3f(length, 0.0f, 0.0f), Core::Color::Red(), 0);\n OcularGraphics->drawDebugLine(Math::Vector3f(0.0f, 0.0f, 0.0f), Math::Vector3f(0.0f, length, 0.0f), Core::Color::Green(), 0);\n OcularGraphics->drawDebugLine(Math::Vector3f(0.0f, 0.0f, 0.0f), Math::Vector3f(0.0f, 0.0f, length), Core::Color::Blue(), 0);\n }\n\n void Editor::setupGizmos()\n {\n m_GizmoTranslate = new AxisGizmo();\n m_GizmoTranslate->setName(\"OCULAR_INTERNAL_EDITOR_GIZMO_TRANSLATE\");\n m_GizmoTranslate->setActive(false);\n }\n\n void Editor::performMousePick(Core::KeyState const state)\n {\n auto mousePos = OcularInput->getMousePosition();\n auto editorCamera = OcularEditor.getEditorCamera();\n\n if(editorCamera)\n {\n auto ray = editorCamera->getPickRay(mousePos);\n \/\/OcularGraphics->drawDebugLine(ray.getOrigin(), ray.getPointAlong(100.0f), Core::Color::Yellow(), 15000);\n \n std::vector<std::pair<Core::SceneObject*, float>> intersections;\n\n OcularScene->getIntersections(ray, intersections);\n\n if(intersections.size())\n {\n if(state == Core::KeyState::Released)\n {\n \/\/ On mouse up, we only care about picking normal (non-gizmo) objects\n setSelectedObject(intersections[0].first, false, true);\n }\n else\n {\n \/\/ On mouse down, we only care about picking gizmo objects\n auto gizmo = pickedGizmo(intersections);\n\n if(gizmo)\n {\n setSelectedObject(gizmo, true, false);\n }\n }\n }\n else\n {\n \/\/ If the currently selected object is a gizmo, we simply de-select the gizmo but keep the parent object selected\n if(m_GizmoTranslate->isSelected())\n {\n m_GizmoTranslate->setSelected(false);\n }\n else\n {\n \/\/ No object selected. Treat it as a de-select.\n setSelectedObject(nullptr, false, true);\n }\n }\n }\n }\n\n Core::SceneObject* Editor::pickedGizmo(std::vector<std::pair<Core::SceneObject*, float>> const& intersections) const\n {\n \/\/ Check if among the picked items is a gizmo object. If so, we will assume that was the intended pick target.\n Core::SceneObject* result = nullptr;\n\n for(auto pair : intersections)\n {\n auto object = pair.first;\n\n if(object)\n {\n if(OcularString->IsEqual(object->getClass(), OCULAR_TYPE_NAME(AxisComponentGizmo)))\n {\n result = object;\n break;\n }\n }\n }\n\n return result;\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>#include \"TRCFileAdapter.h\"\n#include <fstream>\n\nnamespace OpenSim {\n\nconst std::string TRCFileAdapter::_markers{\"markers\"};\nconst std::string TRCFileAdapter::_delimiterWrite{\"\\t\"};\nconst std::string TRCFileAdapter::_delimitersRead{\" \\t\"};\nconst std::string TRCFileAdapter::_frameNumColumnLabel{\"Frame#\"};\nconst std::string TRCFileAdapter::_timeColumnLabel{\"Time\"};\nconst std::string TRCFileAdapter::_xLabel{\"X\"};\nconst std::string TRCFileAdapter::_yLabel{\"Y\"};\nconst std::string TRCFileAdapter::_zLabel{\"Z\"};\nconst std::string TRCFileAdapter::_numMarkersLabel{\"NumMarkers\"};\nconst std::string TRCFileAdapter::_numFramesLabel{\"NumFrames\"};\nconst unsigned TRCFileAdapter::_dataStartsAtLine{6};\nconst std::vector<std::string> TRCFileAdapter::_metadataKeys{\"DataRate\", \n \"CameraRate\", \"NumFrames\", \"NumMarkers\", \"Units\", \"OrigDataRate\", \n \"OrigDataStartFrame\", \"OrigNumFrames\"};\n\nTRCFileAdapter* \nTRCFileAdapter::clone() const {\n return new TRCFileAdapter{*this};\n}\n\nTimeSeriesTableVec3\nTRCFileAdapter::read(const std::string& fileName) const {\n auto abs_table = extendRead(fileName).at(_markers);\n return static_cast<TimeSeriesTableVec3&>(*abs_table);\n}\n\nvoid \nTRCFileAdapter::write(const TimeSeriesTableVec3& table, \n const std::string& fileName) const {\n InputTables tables{};\n tables.emplace(_markers, &table);\n extendWrite(tables, fileName);\n}\n\nTRCFileAdapter::OutputTables\nTRCFileAdapter::extendRead(const std::string& fileName) const {\n OPENSIM_THROW_IF(fileName.empty(),\n EmptyFileName);\n\n std::ifstream in_stream{fileName};\n OPENSIM_THROW_IF(!in_stream.good(),\n FileDoesNotExist,\n fileName);\n\n auto table = std::make_shared<TimeSeriesTableVec3>();\n\n \/\/ Callable to get the next line in form of vector of tokens.\n auto nextLine = [&] {\n return getNextLine(in_stream, _delimitersRead);\n };\n\n \/\/ First line of the stream is considered the header.\n std::string header{};\n std::getline(in_stream, header);\n auto header_tokens = tokenize(header, _delimitersRead);\n OPENSIM_THROW_IF(header_tokens.empty(),\n FileIsEmpty,\n fileName); \n OPENSIM_THROW_IF(header_tokens.at(0) != \"PathFileType\",\n MissingHeader);\n table->updTableMetaData().setValueForKey(\"header\", header);\n\n \/\/ Read the line containing metadata keys.\n auto keys = nextLine();\n OPENSIM_THROW_IF(keys.size() != _metadataKeys.size(),\n IncorrectNumMetaDataKeys,\n fileName,\n _metadataKeys.size(), \n keys.size());\n\n for(size_t i = 0; i < keys.size(); ++i)\n OPENSIM_THROW_IF(keys[i] != _metadataKeys[i],\n UnexpectedMetaDataKey,\n fileName,\n _metadataKeys[i],\n keys[i]);\n\n \/\/ Read the line containing metadata values.\n auto values = nextLine();\n OPENSIM_THROW_IF(keys.size() != values.size(),\n MetaDataLengthMismatch,\n fileName,\n keys.size(),\n values.size());\n\n \/\/ Fill up the metadata container.\n for(std::size_t i = 0; i < keys.size(); ++i)\n table->updTableMetaData().setValueForKey(keys[i], values[i]);\n\n auto num_markers_expected = \n std::stoul(table->\n getTableMetaData().\n getValueForKey(_numMarkersLabel).\n template getValue<std::string>());\n\n \/\/ Read the line containing column labels and fill up the column labels\n \/\/ container.\n auto column_labels = nextLine();\n OPENSIM_THROW_IF(column_labels.size() != num_markers_expected + 2,\n IncorrectNumColumnLabels,\n fileName,\n num_markers_expected + 2,\n column_labels.size());\n\n \/\/ Column 0 should be the frame number. Check and get rid of it as it is\n \/\/ not used. The whole column is discarded as the data is read in.\n OPENSIM_THROW_IF(column_labels[0] != _frameNumColumnLabel,\n UnexpectedColumnLabel,\n fileName,\n _frameNumColumnLabel,\n column_labels[0]);\n column_labels.erase(column_labels.begin());\n\n \/\/ Column 0 (originally column 1 before removing frame number) should\n \/\/ now be the time column. Check and get rid of it. The data in this\n \/\/ column is maintained separately from rest of the data.\n OPENSIM_THROW_IF(column_labels[0] != _timeColumnLabel,\n UnexpectedColumnLabel,\n fileName,\n _timeColumnLabel,\n column_labels[0]);\n column_labels.erase(column_labels.begin());\n\n \/\/ Read in the next line of column labels containing (Xdd, Ydd, Zdd)\n \/\/ tuples where dd is a 1 or 2 digit subscript. For example --\n \/\/ X1, Y1, Z1, X2, Y2, Z2, ... so on.\n \/\/ Check and ignore these labels.\n auto xyz_labels_found = nextLine();\n for(int i = 1; i <= num_markers_expected; ++i) {\n size_t j = 0;\n for(auto& letter : {_xLabel, _yLabel, _zLabel}) {\n const size_t ind = ((i - 1) * 3) + j++;\n const std::string expected{letter + std::to_string(i)};\n OPENSIM_THROW_IF(xyz_labels_found.at(ind) != expected,\n UnexpectedColumnLabel,\n fileName,\n expected,\n xyz_labels_found.at(ind));\n }\n }\n\n \/\/ Read the rows one at a time and fill up the time column container and\n \/\/ the data container.\n std::size_t line_num{_dataStartsAtLine - 1};\n auto row = nextLine();\n while(!row.empty()) {\n ++line_num;\n size_t expected{column_labels.size() * 3 + 2};\n OPENSIM_THROW_IF(row.size() != expected,\n RowLengthMismatch,\n fileName,\n line_num,\n expected,\n row.size());\n\n \/\/ Columns 2 till the end are data.\n TimeSeriesTableVec3::RowVector \n row_vector{static_cast<int>(num_markers_expected)};\n size_t ind{0};\n for(std::size_t c = 2; c < column_labels.size() * 3 + 2; c += 3)\n row_vector[ind++] = SimTK::Vec3{std::stod(row.at(c)),\n std::stod(row.at(c+1)),\n std::stod(row.at(c+2))};\n\n \/\/ Column 1 is time.\n table->appendRow(std::stod(row.at(1)), std::move(row_vector));\n\n row = nextLine();\n }\n\n \/\/ Set the column labels of the table.\n ValueArray<std::string> value_array{};\n for(const auto& cl : column_labels)\n value_array.upd().push_back(SimTK::Value<std::string>{cl});\n TimeSeriesTableVec3::DependentsMetaData dep_metadata{};\n dep_metadata.setValueArrayForKey(\"labels\", value_array);\n table->setDependentsMetaData(dep_metadata);\n\n OutputTables output_tables{};\n output_tables.emplace(_markers, table);\n\n return output_tables;\n}\n\nvoid\nTRCFileAdapter::extendWrite(const InputTables& absTables, \n const std::string& fileName) const {\n OPENSIM_THROW_IF(absTables.empty(),\n NoTableFound);\n\n const TimeSeriesTableVec3* table{};\n try {\n auto abs_table = absTables.at(_markers);\n table = dynamic_cast<const TimeSeriesTableVec3*>(abs_table);\n } catch(std::out_of_range) {\n OPENSIM_THROW(KeyMissing,\n _markers);\n } catch(std::bad_cast&) {\n OPENSIM_THROW(IncorrectTableType);\n }\n\n OPENSIM_THROW_IF(fileName.empty(),\n EmptyFileName);\n\n std::ofstream out_stream{fileName};\n\n \/\/ First line of the stream is the header.\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(\"header\").\n getValue<std::string>() << \"\\n\";\n } catch(KeyNotFound&) {\n out_stream << \"PathFileType\\t4\\t(X\/Y\/Z)\\t\" << fileName << \"\\n\";\n }\n\n \/\/ Line containing metadata keys.\n out_stream << _metadataKeys[0];\n for(unsigned i = 1; i < _metadataKeys.size(); ++i)\n out_stream << _delimiterWrite << _metadataKeys[i];\n out_stream << \"\\n\";\n\n \/\/ Line containing metadata values.\n std::string datarate;\n try {\n datarate = table->\n getTableMetaData().\n getValueForKey(_metadataKeys[0]).\n getValue<std::string>();\n } catch(KeyNotFound&) {\n OPENSIM_THROW(MissingMetaData,\n \"DataRate\");\n }\n out_stream << datarate << _delimiterWrite;\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[1]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << datarate << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[2]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << table->getNumRows() << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[3]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << table->getNumColumns() << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[4]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n OPENSIM_THROW(MissingMetaData,\n \"Units\");\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[5]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << datarate << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[6]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << 0 << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[7]).\n getValue<std::string>();\n } catch(KeyNotFound&) {\n out_stream << table->getNumRows();\n }\n out_stream << \"\\n\";\n\n \/\/ Line containing column labels.\n out_stream << _frameNumColumnLabel << _delimiterWrite\n << _timeColumnLabel << _delimiterWrite;\n for(unsigned col = 0; col < table->getNumColumns(); ++col)\n out_stream << table->\n getDependentsMetaData().\n getValueArrayForKey(\"labels\")[col].\n getValue<std::string>()\n << _delimiterWrite << _delimiterWrite << _delimiterWrite;\n out_stream << \"\\n\";\n\n \/\/ Line containing xyz component labels for each marker.\n out_stream << _delimiterWrite << _delimiterWrite;\n for(unsigned col = 1; col <= table->getNumColumns(); ++col)\n for(auto& letter : {_xLabel, _yLabel, _zLabel})\n out_stream << (letter + std::to_string(col)) << _delimiterWrite;\n out_stream << \"\\n\";\n\n \/\/ Empty line.\n out_stream << \"\\n\";\n\n \/\/ Data rows.\n for(unsigned row = 0; row < table->getNumRows(); ++row) {\n constexpr auto prec = std::numeric_limits<double>::digits10 + 1;\n out_stream << row + 1 << _delimiterWrite\n << std::setprecision(prec) \n << table->getIndependentColumn()[row] << _delimiterWrite;\n const auto& row_r = table->getRowAtIndex(row);\n for(unsigned col = 0; col < table->getNumColumns(); ++col) {\n const auto& elt = row_r[col];\n out_stream << std::setprecision(prec) \n << elt[0] << _delimiterWrite\n << elt[1] << _delimiterWrite\n << elt[2] << _delimiterWrite;\n }\n out_stream << \"\\n\";\n }\n}\n\n}\n<commit_msg>Change to int to avoid warning.<commit_after>#include \"TRCFileAdapter.h\"\n#include <fstream>\n\nnamespace OpenSim {\n\nconst std::string TRCFileAdapter::_markers{\"markers\"};\nconst std::string TRCFileAdapter::_delimiterWrite{\"\\t\"};\nconst std::string TRCFileAdapter::_delimitersRead{\" \\t\"};\nconst std::string TRCFileAdapter::_frameNumColumnLabel{\"Frame#\"};\nconst std::string TRCFileAdapter::_timeColumnLabel{\"Time\"};\nconst std::string TRCFileAdapter::_xLabel{\"X\"};\nconst std::string TRCFileAdapter::_yLabel{\"Y\"};\nconst std::string TRCFileAdapter::_zLabel{\"Z\"};\nconst std::string TRCFileAdapter::_numMarkersLabel{\"NumMarkers\"};\nconst std::string TRCFileAdapter::_numFramesLabel{\"NumFrames\"};\nconst unsigned TRCFileAdapter::_dataStartsAtLine{6};\nconst std::vector<std::string> TRCFileAdapter::_metadataKeys{\"DataRate\", \n \"CameraRate\", \"NumFrames\", \"NumMarkers\", \"Units\", \"OrigDataRate\", \n \"OrigDataStartFrame\", \"OrigNumFrames\"};\n\nTRCFileAdapter* \nTRCFileAdapter::clone() const {\n return new TRCFileAdapter{*this};\n}\n\nTimeSeriesTableVec3\nTRCFileAdapter::read(const std::string& fileName) const {\n auto abs_table = extendRead(fileName).at(_markers);\n return static_cast<TimeSeriesTableVec3&>(*abs_table);\n}\n\nvoid \nTRCFileAdapter::write(const TimeSeriesTableVec3& table, \n const std::string& fileName) const {\n InputTables tables{};\n tables.emplace(_markers, &table);\n extendWrite(tables, fileName);\n}\n\nTRCFileAdapter::OutputTables\nTRCFileAdapter::extendRead(const std::string& fileName) const {\n OPENSIM_THROW_IF(fileName.empty(),\n EmptyFileName);\n\n std::ifstream in_stream{fileName};\n OPENSIM_THROW_IF(!in_stream.good(),\n FileDoesNotExist,\n fileName);\n\n auto table = std::make_shared<TimeSeriesTableVec3>();\n\n \/\/ Callable to get the next line in form of vector of tokens.\n auto nextLine = [&] {\n return getNextLine(in_stream, _delimitersRead);\n };\n\n \/\/ First line of the stream is considered the header.\n std::string header{};\n std::getline(in_stream, header);\n auto header_tokens = tokenize(header, _delimitersRead);\n OPENSIM_THROW_IF(header_tokens.empty(),\n FileIsEmpty,\n fileName); \n OPENSIM_THROW_IF(header_tokens.at(0) != \"PathFileType\",\n MissingHeader);\n table->updTableMetaData().setValueForKey(\"header\", header);\n\n \/\/ Read the line containing metadata keys.\n auto keys = nextLine();\n OPENSIM_THROW_IF(keys.size() != _metadataKeys.size(),\n IncorrectNumMetaDataKeys,\n fileName,\n _metadataKeys.size(), \n keys.size());\n\n for(size_t i = 0; i < keys.size(); ++i)\n OPENSIM_THROW_IF(keys[i] != _metadataKeys[i],\n UnexpectedMetaDataKey,\n fileName,\n _metadataKeys[i],\n keys[i]);\n\n \/\/ Read the line containing metadata values.\n auto values = nextLine();\n OPENSIM_THROW_IF(keys.size() != values.size(),\n MetaDataLengthMismatch,\n fileName,\n keys.size(),\n values.size());\n\n \/\/ Fill up the metadata container.\n for(std::size_t i = 0; i < keys.size(); ++i)\n table->updTableMetaData().setValueForKey(keys[i], values[i]);\n\n auto num_markers_expected = \n std::stoul(table->\n getTableMetaData().\n getValueForKey(_numMarkersLabel).\n template getValue<std::string>());\n\n \/\/ Read the line containing column labels and fill up the column labels\n \/\/ container.\n auto column_labels = nextLine();\n OPENSIM_THROW_IF(column_labels.size() != num_markers_expected + 2,\n IncorrectNumColumnLabels,\n fileName,\n num_markers_expected + 2,\n column_labels.size());\n\n \/\/ Column 0 should be the frame number. Check and get rid of it as it is\n \/\/ not used. The whole column is discarded as the data is read in.\n OPENSIM_THROW_IF(column_labels[0] != _frameNumColumnLabel,\n UnexpectedColumnLabel,\n fileName,\n _frameNumColumnLabel,\n column_labels[0]);\n column_labels.erase(column_labels.begin());\n\n \/\/ Column 0 (originally column 1 before removing frame number) should\n \/\/ now be the time column. Check and get rid of it. The data in this\n \/\/ column is maintained separately from rest of the data.\n OPENSIM_THROW_IF(column_labels[0] != _timeColumnLabel,\n UnexpectedColumnLabel,\n fileName,\n _timeColumnLabel,\n column_labels[0]);\n column_labels.erase(column_labels.begin());\n\n \/\/ Read in the next line of column labels containing (Xdd, Ydd, Zdd)\n \/\/ tuples where dd is a 1 or 2 digit subscript. For example --\n \/\/ X1, Y1, Z1, X2, Y2, Z2, ... so on.\n \/\/ Check and ignore these labels.\n auto xyz_labels_found = nextLine();\n for(int i = 1; i <= num_markers_expected; ++i) {\n size_t j = 0;\n for(auto& letter : {_xLabel, _yLabel, _zLabel}) {\n const size_t ind = ((i - 1) * 3) + j++;\n const std::string expected{letter + std::to_string(i)};\n OPENSIM_THROW_IF(xyz_labels_found.at(ind) != expected,\n UnexpectedColumnLabel,\n fileName,\n expected,\n xyz_labels_found.at(ind));\n }\n }\n\n \/\/ Read the rows one at a time and fill up the time column container and\n \/\/ the data container.\n std::size_t line_num{_dataStartsAtLine - 1};\n auto row = nextLine();\n while(!row.empty()) {\n ++line_num;\n size_t expected{column_labels.size() * 3 + 2};\n OPENSIM_THROW_IF(row.size() != expected,\n RowLengthMismatch,\n fileName,\n line_num,\n expected,\n row.size());\n\n \/\/ Columns 2 till the end are data.\n TimeSeriesTableVec3::RowVector \n row_vector{static_cast<int>(num_markers_expected)};\n int ind{0};\n for(std::size_t c = 2; c < column_labels.size() * 3 + 2; c += 3)\n row_vector[ind++] = SimTK::Vec3{std::stod(row.at(c)),\n std::stod(row.at(c+1)),\n std::stod(row.at(c+2))};\n\n \/\/ Column 1 is time.\n table->appendRow(std::stod(row.at(1)), std::move(row_vector));\n\n row = nextLine();\n }\n\n \/\/ Set the column labels of the table.\n ValueArray<std::string> value_array{};\n for(const auto& cl : column_labels)\n value_array.upd().push_back(SimTK::Value<std::string>{cl});\n TimeSeriesTableVec3::DependentsMetaData dep_metadata{};\n dep_metadata.setValueArrayForKey(\"labels\", value_array);\n table->setDependentsMetaData(dep_metadata);\n\n OutputTables output_tables{};\n output_tables.emplace(_markers, table);\n\n return output_tables;\n}\n\nvoid\nTRCFileAdapter::extendWrite(const InputTables& absTables, \n const std::string& fileName) const {\n OPENSIM_THROW_IF(absTables.empty(),\n NoTableFound);\n\n const TimeSeriesTableVec3* table{};\n try {\n auto abs_table = absTables.at(_markers);\n table = dynamic_cast<const TimeSeriesTableVec3*>(abs_table);\n } catch(std::out_of_range) {\n OPENSIM_THROW(KeyMissing,\n _markers);\n } catch(std::bad_cast&) {\n OPENSIM_THROW(IncorrectTableType);\n }\n\n OPENSIM_THROW_IF(fileName.empty(),\n EmptyFileName);\n\n std::ofstream out_stream{fileName};\n\n \/\/ First line of the stream is the header.\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(\"header\").\n getValue<std::string>() << \"\\n\";\n } catch(KeyNotFound&) {\n out_stream << \"PathFileType\\t4\\t(X\/Y\/Z)\\t\" << fileName << \"\\n\";\n }\n\n \/\/ Line containing metadata keys.\n out_stream << _metadataKeys[0];\n for(unsigned i = 1; i < _metadataKeys.size(); ++i)\n out_stream << _delimiterWrite << _metadataKeys[i];\n out_stream << \"\\n\";\n\n \/\/ Line containing metadata values.\n std::string datarate;\n try {\n datarate = table->\n getTableMetaData().\n getValueForKey(_metadataKeys[0]).\n getValue<std::string>();\n } catch(KeyNotFound&) {\n OPENSIM_THROW(MissingMetaData,\n \"DataRate\");\n }\n out_stream << datarate << _delimiterWrite;\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[1]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << datarate << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[2]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << table->getNumRows() << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[3]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << table->getNumColumns() << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[4]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n OPENSIM_THROW(MissingMetaData,\n \"Units\");\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[5]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << datarate << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[6]).\n getValue<std::string>()\n << _delimiterWrite;\n } catch(KeyNotFound&) {\n out_stream << 0 << _delimiterWrite;\n }\n try {\n out_stream << table->\n getTableMetaData().\n getValueForKey(_metadataKeys[7]).\n getValue<std::string>();\n } catch(KeyNotFound&) {\n out_stream << table->getNumRows();\n }\n out_stream << \"\\n\";\n\n \/\/ Line containing column labels.\n out_stream << _frameNumColumnLabel << _delimiterWrite\n << _timeColumnLabel << _delimiterWrite;\n for(unsigned col = 0; col < table->getNumColumns(); ++col)\n out_stream << table->\n getDependentsMetaData().\n getValueArrayForKey(\"labels\")[col].\n getValue<std::string>()\n << _delimiterWrite << _delimiterWrite << _delimiterWrite;\n out_stream << \"\\n\";\n\n \/\/ Line containing xyz component labels for each marker.\n out_stream << _delimiterWrite << _delimiterWrite;\n for(unsigned col = 1; col <= table->getNumColumns(); ++col)\n for(auto& letter : {_xLabel, _yLabel, _zLabel})\n out_stream << (letter + std::to_string(col)) << _delimiterWrite;\n out_stream << \"\\n\";\n\n \/\/ Empty line.\n out_stream << \"\\n\";\n\n \/\/ Data rows.\n for(unsigned row = 0; row < table->getNumRows(); ++row) {\n constexpr auto prec = std::numeric_limits<double>::digits10 + 1;\n out_stream << row + 1 << _delimiterWrite\n << std::setprecision(prec) \n << table->getIndependentColumn()[row] << _delimiterWrite;\n const auto& row_r = table->getRowAtIndex(row);\n for(unsigned col = 0; col < table->getNumColumns(); ++col) {\n const auto& elt = row_r[col];\n out_stream << std::setprecision(prec) \n << elt[0] << _delimiterWrite\n << elt[1] << _delimiterWrite\n << elt[2] << _delimiterWrite;\n }\n out_stream << \"\\n\";\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions 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 copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\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 * HOLDER 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\n#include \"Loops.h\"\n\nusing namespace choreograph;\nusing namespace cinder;\n\nvoid Loops::setup()\n{\n float left = 100.0f;\n float right = app::getWindowWidth() - left;\n PhraseRef<vec2> leftToRight = makeRamp( vec2( left, 0.0f ), vec2( right, 0.0f ), 1.0f, EaseInOutQuad() );\n\n \/\/=====================================================\n \/\/ Looping Motions. Use for things that loop \"forever.\"\n \/\/=====================================================\n\n Output<vec2> loopTarget;\n timeline().apply( &loopTarget, leftToRight )\n .finishFn( [] ( Motion<vec2> &m ) {\n m.resetTime();\n } ); \/\/ Motion should play forever.\n\n\n Output<vec2> pingPongTarget;\n timeline().apply( &pingPongTarget, leftToRight )\n .finishFn( [] ( Motion<vec2> &m ) {\n \/\/ reverse Motion direction on finish.\n m.setPlaybackSpeed( m.getPlaybackSpeed() * -1 );\n \/\/ Start each cycle from \"zero\" to keep in sync with loopTarget timing.\n m.resetTime();\n } );\n\n Output<vec2> pingPongSlowerTarget;\n timeline().apply( &pingPongSlowerTarget, leftToRight )\n .finishFn( [] ( Motion<vec2> &m ) {\n \/\/ Reverse and slow Motion on finish.\n m.setPlaybackSpeed( m.getPlaybackSpeed() * -0.9f );\n \/\/ If we're unbearably slow, stop looping.\n if( std::abs( m.getPlaybackSpeed() ) < 0.2f ) {\n m.finishFn( [] ( Motion<vec2> &m ) {} );\n }\n else {\n m.resetTime();\n }\n } );\n\n \/\/==========================================================\n \/\/ Looping Motion Group. Use for separate motions that loop\n \/\/ with each other, but have different durations.\n \/\/==========================================================\n\n SequenceRef<vec2> positionSequence = createSequence( vec2( app::getWindowSize() ) * vec2( 0.66, 1 ) + vec2( 0, 50 ) );\n SequenceRef<vec3> rotationSequence = createSequence( vec3( M_PI \/ 2, 0, 0 ) );\n\n rotationSequence->then<RampTo>( vec3( 4 * M_PI, 2 * M_PI, 0 ), 1.0f, EaseOutQuint() );\n positionSequence->then<RampTo>( vec2( app::getWindowSize() ) * vec2( 0.66, 0.5 ), 0.5f, EaseOutAtan() );\n\n auto group = std::make_shared<MotionGroup>();\n group->add( positionSequence, &_position );\n group->add( rotationSequence, &_rotation );\n group->setStartTime( 0.5f ); \/\/ start all motions after a 0.5 second hold on their start values.\n group->setFinishFn( [] ( MotionGroup &group ) {\n group.setPlaybackSpeed( group.getPlaybackSpeed() * -1 );\n group.resetTime();\n } );\n\n timeline().add( group );\n\n \/\/=====================================================\n \/\/ Looping Phrases. Use for a finite number of loops.\n \/\/=====================================================\n\n Output<vec2> loopPhraseTarget;\n timeline().apply( &loopPhraseTarget ).then( makeRepeat( leftToRight, 7.5f ) );\n\n Output<vec2> pingPongPhraseTarget;\n timeline().apply( &pingPongPhraseTarget ).then( makePingPong( leftToRight, 7.5f ) );\n\n mTargets.push_back( { loopTarget, Color( 1, 0, 1 ) } );\n mTargets.push_back( { pingPongTarget, Color( 1, 0, 1 ) } );\n mTargets.push_back( { pingPongSlowerTarget, Color( 0, 1, 1 ) } );\n mTargets.push_back( { loopPhraseTarget, Color( 1, 1, 0 ) } );\n mTargets.push_back( { pingPongPhraseTarget, Color( 1, 1, 0 ) } );\n}\n\nvoid Loops::update( double dt )\n{\n timeline().step( dt );\n}\n\nvoid Loops::draw()\n{\n gl::ScopedModelMatrix matrix;\n gl::setMatricesWindowPersp( app::getWindowSize() );\n\n {\n gl::ScopedModelMatrix singleDotMatrix;\n\n const float y_step = 100.0f;\n gl::translate( vec2( 0, (app::getWindowHeight() - y_step * mTargets.size()) \/ 2 ) );\n\n for( auto &target : mTargets ) {\n gl::ScopedColor color( target._color );\n gl::drawSolidCircle( target._position, 25.0f );\n gl::translate( vec2( 0, y_step ) );\n }\n }\n\n gl::ScopedColor color( Color( CM_HSV, 0.575f, 1.0f, 1.0f ) );\n gl::translate( _position );\n gl::multModelMatrix( glm::eulerAngleYXZ( _rotation().y, _rotation().x, _rotation().z ) );\n gl::drawSolidCircle( vec2( 0 ), 30.0f );\n}\n<commit_msg>Grouping updates.<commit_after>\/*\n * Copyright (c) 2014 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions 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 copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\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 * HOLDER 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\n#include \"Loops.h\"\n\nusing namespace choreograph;\nusing namespace cinder;\n\nvoid Loops::setup()\n{\n float left = 100.0f;\n float right = app::getWindowWidth() - left;\n PhraseRef<vec2> leftToRight = makeRamp( vec2( left, 0.0f ), vec2( right, 0.0f ), 1.0f, EaseInOutQuad() );\n\n \/\/=====================================================\n \/\/ Looping Motions. Use for things that loop \"forever.\"\n \/\/=====================================================\n\n Output<vec2> loopTarget;\n timeline().apply( &loopTarget, leftToRight )\n .finishFn( [] ( Motion<vec2> &m ) {\n m.resetTime();\n } ); \/\/ Motion should play forever.\n\n\n Output<vec2> pingPongTarget;\n timeline().apply( &pingPongTarget, leftToRight )\n .finishFn( [] ( Motion<vec2> &m ) {\n \/\/ reverse Motion direction on finish.\n m.setPlaybackSpeed( m.getPlaybackSpeed() * -1 );\n \/\/ Start each cycle from \"zero\" to keep in sync with loopTarget timing.\n m.resetTime();\n } );\n\n Output<vec2> pingPongSlowerTarget;\n timeline().apply( &pingPongSlowerTarget, leftToRight )\n .finishFn( [] ( Motion<vec2> &m ) {\n \/\/ Reverse and slow Motion on finish.\n m.setPlaybackSpeed( m.getPlaybackSpeed() * -0.9f );\n \/\/ If we're unbearably slow, stop looping.\n if( std::abs( m.getPlaybackSpeed() ) < 0.2f ) {\n m.finishFn( [] ( Motion<vec2> &m ) {} );\n }\n else {\n m.resetTime();\n }\n } );\n\n \/\/==========================================================\n \/\/ Looping Motion Group. Use for separate motions that loop\n \/\/ with each other, but have different durations.\n \/\/==========================================================\n\n SequenceRef<vec2> positionSequence = createSequence( vec2( app::getWindowSize() ) * vec2( 0.66, 1 ) + vec2( 0, 50 ) );\n SequenceRef<vec3> rotationSequence = createSequence( vec3( M_PI \/ 2, 0, 0 ) );\n\n rotationSequence->then<RampTo>( vec3( 4 * M_PI, 2 * M_PI, 0 ), 1.0f, EaseOutQuint() );\n positionSequence->then<RampTo>( vec2( app::getWindowSize() ) * vec2( 0.66, 0.5 ), 0.5f, EaseOutAtan() );\n\n auto group = std::make_shared<MotionGroup>();\n group->add( positionSequence, &_position );\n group->add( rotationSequence, &_rotation );\n \/\/ start grouped motions after a 0.5 second hold on their start values.\n group->setStartTime( 0.5f );\n group->setFinishFn( [] ( MotionGroup &group ) {\n group.setPlaybackSpeed( group.getPlaybackSpeed() * -1 );\n group.resetTime();\n } );\n\n timeline().add( group );\n\n \/\/=====================================================\n \/\/ Looping Phrases. Use for a finite number of loops.\n \/\/=====================================================\n\n Output<vec2> loopPhraseTarget;\n timeline().apply( &loopPhraseTarget ).then( makeRepeat( leftToRight, 7.5f ) );\n\n Output<vec2> pingPongPhraseTarget;\n timeline().apply( &pingPongPhraseTarget ).then( makePingPong( leftToRight, 7.5f ) );\n\n mTargets.push_back( { loopTarget, Color( 1, 0, 1 ) } );\n mTargets.push_back( { pingPongTarget, Color( 1, 0, 1 ) } );\n mTargets.push_back( { pingPongSlowerTarget, Color( 0, 1, 1 ) } );\n mTargets.push_back( { loopPhraseTarget, Color( 1, 1, 0 ) } );\n mTargets.push_back( { pingPongPhraseTarget, Color( 1, 1, 0 ) } );\n}\n\nvoid Loops::update( double dt )\n{\n timeline().step( dt );\n}\n\nvoid Loops::draw()\n{\n gl::ScopedModelMatrix matrix;\n gl::setMatricesWindowPersp( app::getWindowSize() );\n\n {\n gl::ScopedModelMatrix singleDotMatrix;\n\n const float y_step = 100.0f;\n gl::translate( vec2( 0, (app::getWindowHeight() - y_step * mTargets.size()) \/ 2 ) );\n\n for( auto &target : mTargets ) {\n gl::ScopedColor color( target._color );\n gl::drawSolidCircle( target._position, 24.0f );\n gl::translate( vec2( 0, y_step ) );\n }\n }\n\n gl::ScopedColor color( Color( CM_HSV, 0.575f, 1.0f, 1.0f ) );\n gl::translate( _position );\n gl::multModelMatrix( glm::eulerAngleYXZ( _rotation().y, _rotation().x, _rotation().z ) );\n gl::drawSolidCircle( vec2( 0 ), 36.0f );\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * LFU\n * ===\n *\n * Cache: Least frequently used in O(1) time (if no map conflicts & rehashing).\n *\n * head_ tail_\n * | |\n * v v\n * | prev_; LinkedHashSet; next_; | | | | | | | |\n *\n * Note: Compile with -std=c++11.\n *\/\n\n#include <iostream>\n#include <unordered_map>\n#include <list>\n\ntemplate <typename K> class freq;\n\ntemplate <typename K>\nclass freq_node {\npublic:\n freq_node(int f, freq_node *prev, freq_node *next)\n : f_(f), prev_(prev), next_(next) { \/* nop *\/ }\n ~freq_node() { \/* nop *\/ }\n\n \/\/ No copy and move.\n freq_node(const freq_node&) = delete;\n freq_node& operator=(const freq_node&) = delete;\n freq_node(freq_node&&) = delete;\n freq_node& operator=(freq_node&&) = delete;\n\n friend freq<K>;\n\n void\n add_key(K k)\n {\n kq_.emplace_back(k);\n auto it = kq_.end();\n if (!kq_.empty()) --it;\n kis_.emplace(k, it);\n }\n\n void\n remove_key(K k)\n {\n auto it = kis_[k];\n kis_.erase(k);\n kq_.erase(it);\n }\n\n void\n remove_last_key()\n {\n K k = kq_.front();\n kis_.erase(k);\n kq_.pop_front();\n }\nprivate:\n int f_;\n freq_node<K> *prev_;\n freq_node<K> *next_;\n \/\/ list + unordered_map = LinkedHashSet in Java.\n std::list<K> kq_;\n std::unordered_map<K, typename std::list<K>::iterator> kis_;\n};\n\ntemplate <typename K>\nclass freq {\npublic:\n freq() : head_(NULL), tail_(NULL) { \/* nop *\/ };\n ~freq() { \/* nop *\/ }\n\n \/\/ No copy and move.\n freq(const freq&) = delete;\n freq& operator=(const freq&) = delete;\n freq(freq&&) = delete;\n freq& operator=(freq&&) = delete;\n\n void\n add_last(K k)\n {\n if (tail_ == NULL) head_ = tail_ = new freq_node<K>(1, NULL, NULL);\n if (tail_->f_ != 1) {\n auto temp = new freq_node<K>(1, tail_, NULL);\n tail_->next_ = temp;\n tail_ = temp;\n }\n tail_->add_key(k);\n kfs_.emplace(k, tail_);\n }\n\n void\n inc(K k)\n {\n auto n = kfs_[k];\n n->remove_key(k);\n kfs_.erase(k);\n\n if (head_ == n) {\n auto temp = new freq_node<K>(n->f_ + 1, NULL, head_);\n head_->prev_ = temp;\n head_ = temp;\n kfs_.emplace(k, head_);\n head_->add_key(k);\n } else if (n->prev_->f_ != n->f_ + 1) {\n auto temp = new freq_node<K>(n->f_ + 1, n->prev_, n);\n n->prev_ = temp;\n n->prev_->next_ = temp;\n kfs_.emplace(k, temp);\n temp->add_key(k);\n } else {\n kfs_.emplace(k, n->prev_);\n n->prev_->add_key(k);\n }\n\n if (n->kq_.empty()) {\n if (n == tail_) {\n tail_ = n->prev_;\n tail_->next_ = NULL;\n } else {\n n->prev_->next_ = n->next_;\n n->next_->prev_ = n->prev_;\n }\n delete n;\n }\n }\n\n void\n remove_last()\n {\n if (tail_->kq_.size() > 1) tail_->remove_last_key();\n else {\n tail_ = tail_->prev_;\n delete tail_->next_;\n tail_->next_ = NULL;\n }\n }\nprivate:\n freq_node<K> *head_;\n freq_node<K> *tail_;\n std::unordered_map<K, freq_node<K>*> kfs_; \/\/ key-frequency store\n};\n\ntemplate <typename K, typename V>\nclass lfu {\npublic:\n lfu() : capacity_(2) { \/* nop *\/ }\n explicit lfu(int capacity) : capacity_(capacity) { \/* nop *\/ }\n ~lfu() { \/* nop *\/ }\n\n \/\/ No copy and move.\n lfu(const lfu&) = delete;\n lfu& operator=(const lfu&) = delete;\n lfu(lfu&&) = delete;\n lfu& operator=(lfu&&) = delete;\n\n unsigned size() const { return siz_; }\n\n V\n get(K k)\n {\n V v = kvs_[k];\n fq_.inc(k);\n return v;\n }\n\n void\n set(K k, V v)\n {\n auto q = kvs_.find(k);\n\n if (q == kvs_.end()) {\n fq_.add_last(k);\n kvs_.emplace(k, v);\n } else kvs_[k] = v;\n\n if (siz_ + 1 > capacity_) fq_.remove_last();\n else ++siz_;\n }\nprivate:\n unsigned siz_{0};\n unsigned capacity_;\n std::unordered_map<K, V> kvs_;\n freq<K> fq_;\n};\n\nint\nmain(int argc, const char *argv[])\n{\n lfu<int, int> cache{4};\n\n cache.set(1, 42);\n cache.set(2, 3);\n cache.set(3, 4);\n cache.set(4, 5);\n\n std::cout << cache.get(1) << std::endl;\n\n cache.set(5, 6);\n std::cout << cache.get(3) << std::endl;\n \/\/ std::cout << cache.get(2) << std::endl; \/\/ now {2: 3} has gone\n\n \/\/ cache.get(6);\n\n return 0;\n}\n<commit_msg>fixed lfu error handling<commit_after>\/**\n * LFU\n * ===\n *\n * Cache: Least frequently used in O(1) time (if no map conflicts & rehashing).\n *\n * head_ tail_\n * | |\n * v v\n * | prev_; LinkedHashSet; next_; | | | | | | | |\n *\n * Note: Compile with -std=c++11.\n *\/\n\n#include <iostream>\n#include <unordered_map>\n#include <list>\n\ntemplate <typename K> class freq;\n\ntemplate <typename K>\nclass freq_node {\npublic:\n freq_node(int f, freq_node *prev, freq_node *next)\n : f_(f), prev_(prev), next_(next) { \/* nop *\/ }\n ~freq_node() { \/* nop *\/ }\n\n \/\/ No copy and move.\n freq_node(const freq_node&) = delete;\n freq_node& operator=(const freq_node&) = delete;\n freq_node(freq_node&&) = delete;\n freq_node& operator=(freq_node&&) = delete;\n\n friend freq<K>;\n\n void\n add_key(K k)\n {\n kq_.emplace_back(k);\n auto it = kq_.end();\n if (!kq_.empty()) --it;\n kis_.emplace(k, it);\n }\n\n void\n remove_key(K k)\n {\n auto it = kis_[k];\n kis_.erase(k);\n kq_.erase(it);\n }\n\n K\n remove_last_key()\n {\n K k = kq_.front();\n kis_.erase(k);\n kq_.pop_front();\n return k;\n }\nprivate:\n int f_;\n freq_node<K> *prev_;\n freq_node<K> *next_;\n \/\/ list + unordered_map = LinkedHashSet in Java.\n std::list<K> kq_;\n std::unordered_map<K, typename std::list<K>::iterator> kis_;\n};\n\ntemplate <typename K>\nclass freq {\npublic:\n freq() : head_(NULL), tail_(NULL) { \/* nop *\/ };\n ~freq() { \/* nop *\/ }\n\n \/\/ No copy and move.\n freq(const freq&) = delete;\n freq& operator=(const freq&) = delete;\n freq(freq&&) = delete;\n freq& operator=(freq&&) = delete;\n\n void\n add_last(K k)\n {\n if (head_ == NULL) head_ = tail_ = new freq_node<K>(1, NULL, NULL);\n if (tail_->f_ != 1) {\n auto temp = new freq_node<K>(1, tail_, NULL);\n tail_->next_ = temp;\n tail_ = temp;\n }\n tail_->add_key(k);\n kfs_.emplace(k, tail_);\n }\n\n void\n inc(K k)\n {\n auto n = kfs_[k];\n n->remove_key(k);\n kfs_.erase(k);\n\n if (head_ == n) {\n auto temp = new freq_node<K>(n->f_ + 1, NULL, head_);\n head_->prev_ = temp;\n head_ = temp;\n kfs_.emplace(k, head_);\n head_->add_key(k);\n } else if (n->prev_->f_ != n->f_ + 1) {\n auto temp = new freq_node<K>(n->f_ + 1, n->prev_, n);\n n->prev_ = temp;\n n->prev_->next_ = temp;\n kfs_.emplace(k, temp);\n temp->add_key(k);\n } else {\n kfs_.emplace(k, n->prev_);\n n->prev_->add_key(k);\n }\n\n if (n->kq_.empty()) {\n if (n == tail_) {\n tail_ = n->prev_;\n tail_->next_ = NULL;\n } else {\n n->prev_->next_ = n->next_;\n n->next_->prev_ = n->prev_;\n }\n delete n;\n }\n }\n\n K\n remove_last()\n {\n K k = tail_->remove_last_key();\n if (tail_->kq_.empty()) {\n tail_ = tail_->prev_;\n delete tail_->next_;\n tail_->next_ = NULL;\n }\n return k;\n }\nprivate:\n freq_node<K> *head_;\n freq_node<K> *tail_;\n std::unordered_map<K, freq_node<K>*> kfs_;\n};\n\ntemplate <typename K, typename V>\nclass lfu {\npublic:\n lfu() : capacity_(2) { \/* nop *\/ }\n explicit lfu(int capacity) : capacity_(capacity) { \/* nop *\/ }\n ~lfu() { \/* nop *\/ }\n\n \/\/ No copy and move.\n lfu(const lfu&) = delete;\n lfu& operator=(const lfu&) = delete;\n lfu(lfu&&) = delete;\n lfu& operator=(lfu&&) = delete;\n\n unsigned size() const { return siz_; }\n\n V\n get(K k)\n {\n if (kvs_.find(k) == kvs_.end()) {\n throw std::runtime_error(\"key not found\");\n } else {\n V v = kvs_[k];\n fq_.inc(k);\n return v;\n }\n }\n\n void\n set(K k, V v)\n {\n auto q = kvs_.find(k);\n\n if (q == kvs_.end()) {\n fq_.add_last(k);\n kvs_.emplace(k, v);\n } else kvs_[k] = v;\n\n if (siz_ + 1 > capacity_) {\n K k = fq_.remove_last();\n kvs_.erase(k);\n } else ++siz_;\n }\nprivate:\n unsigned siz_{0};\n unsigned capacity_;\n std::unordered_map<K, V> kvs_;\n freq<K> fq_;\n};\n\nint\nmain(int argc, const char *argv[])\n{\n lfu<int, int> cache{4};\n\n cache.set(1, 42);\n cache.set(2, 3);\n cache.set(3, 4);\n std::cout << \"size=\" << cache.size() << std::endl;\n cache.set(4, 5);\n std::cout << cache.get(1) << std::endl;\n\n cache.set(5, 6);\n try {\n std::cout << cache.get(2) << std::endl; \/\/ now {2: 3} has gone\n } catch (const std::exception& e) {\n std::cout << \"key `2': \" << e.what() << std::endl;\n }\n\n \/\/ Key simply not found.\n cache.get(6);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * conversationdelegate.cpp\n *\n * copyright (c) Aron Bostrom <Aron.Bostrom at gmail.com>, 2006 \n *\n * this library 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 * This library is distributed in the hope that it will be useful, but\n * 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, MA 02111-1307 USA\n *\/\n \n#include <QPainter>\n#include <QStyleOptionViewItem>\n#include <QModelIndex>\n#include <QStyle>\n#include <QBrush>\n#include <QSize>\n#include <QDateTime>\n#include <QtDebug>\n\n#include \"conversationdelegate.h\"\n\nConversationDelegate::ConversationDelegate(DummyKonadiAdapter &adapter, QObject *parent) : QAbstractItemDelegate(parent)\n{\n backend = adapter;\n lineWidth = 510;\n authorBaseWidth = 175;\n margin = 5;\n}\n\nConversationDelegate::~ConversationDelegate()\n{\n}\n\nvoid ConversationDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n int lineHeight = option.fontMetrics.height() + 2;\n painter->setRenderHint(QPainter::Antialiasing);\n painter->setPen(Qt::NoPen);\n\n if (option.state & QStyle::State_Selected)\n painter->setBrush(option.palette.highlight());\n else\n painter->setBrush(Qt::white);\n painter->drawRect(option.rect);\n\n if (option.state & QStyle::State_Selected) {\n painter->setBrush(option.palette.highlightedText());\n painter->setPen(QPen(option.palette.highlightedText().color())); \n } else {\n painter->setBrush(Qt::black);\n painter->setPen(Qt::black);\n }\n painter->setFont(option.font);\n DummyKonadiConversation c = backend.conversation(index.row());\n QString ctitle = c.conversationTitle();\n QString ctime = c.arrivalTimeInText();\n QString cauthors = c.author(0);\n int messageCount = c.count();\n for (int count = 1; count < messageCount; ++count) {\n cauthors.append(\", \");\n cauthors.append(c.author(count));\n }\n\n QString messageCountText = QString(\"(%L1)\").arg(messageCount);\n int messageCountWidth = option.fontMetrics.width(messageCountText);\n\n int linePos = index.row() * lineHeight;\n int authorWidth = qMin(authorBaseWidth - (messageCount > 1 ? messageCountWidth + margin : 0), \n lineWidth - (messageCount > 1 ? messageCountWidth + 2*margin : 0) - margin);\n int authorPos = margin;\n painter->drawText(authorPos, linePos, authorWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignTop|Qt::TextSingleLine, cauthors);\n\/\/ Add ...'s\n\n if (messageCount > 1) {\n int messageCountPos = qMin(2*margin + authorWidth, lineWidth - messageCountWidth - margin);\n painter->drawText(messageCountPos, linePos, messageCountWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignTop|Qt::TextSingleLine, messageCountText);\n }\n\n int subjectPos = authorBaseWidth + 2*margin;\n int timeWidth = option.fontMetrics.width(ctime);\n int subjectWidth = lineWidth - subjectPos - timeWidth - 2*margin;\n painter->drawText(subjectPos, linePos, subjectWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignVCenter|Qt::TextSingleLine, ctitle);\n\/\/ Add ...'s\n\n int timePos = qMax(lineWidth - margin - timeWidth, authorBaseWidth + 2*margin);\n timeWidth = qMax(lineWidth - (timePos + margin), 0);\n painter->drawText(timePos, linePos, timeWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignVCenter|Qt::TextSingleLine, ctime);\n\/\/ Add ...'s\n}\n\nQSize ConversationDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const\n{\n int lineHeight = option.fontMetrics.height() + 2;\n return QSize(lineWidth, lineHeight);\n}\n\nvoid ConversationDelegate::updateWidth(int pos, int \/*nouse*\/)\n{\n lineWidth = pos;\n}\n<commit_msg>SoC<commit_after>\/*\n * conversationdelegate.cpp\n *\n * copyright (c) Aron Bostrom <Aron.Bostrom at gmail.com>, 2006 \n *\n * this library 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 * This library is distributed in the hope that it will be useful, but\n * 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, MA 02111-1307 USA\n *\/\n \n#include <QPainter>\n#include <QStyleOptionViewItem>\n#include <QModelIndex>\n#include <QStyle>\n#include <QBrush>\n#include <QSize>\n#include <QDateTime>\n#include <QtDebug>\n\n#include \"conversationdelegate.h\"\n\nConversationDelegate::ConversationDelegate(DummyKonadiAdapter &adapter, QObject *parent) : QAbstractItemDelegate(parent)\n{\n backend = adapter;\n lineWidth = 510;\n authorBaseWidth = 175;\n margin = 5;\n}\n\nConversationDelegate::~ConversationDelegate()\n{\n}\n\nvoid ConversationDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n int lineHeight = option.fontMetrics.height() + 2;\n painter->setRenderHint(QPainter::Antialiasing);\n painter->setPen(Qt::NoPen);\n\n if (option.state & QStyle::State_Selected)\n painter->setBrush(option.palette.highlight());\n else\n painter->setBrush(Qt::white);\n painter->drawRect(option.rect);\n\n if (option.state & QStyle::State_Selected) {\n painter->setBrush(option.palette.highlightedText());\n painter->setPen(QPen(option.palette.highlightedText().color())); \n } else {\n painter->setBrush(Qt::black);\n painter->setPen(Qt::black);\n }\n painter->setFont(option.font);\n DummyKonadiConversation c = backend.conversation(index.row());\n QString ctitle = c.conversationTitle();\n QString ctime = c.arrivalTimeInText();\n QString cauthors = c.author(0);\n int messageCount = c.count();\n for (int count = 1; count < messageCount; ++count) {\n cauthors.append(\", \");\n cauthors.append(c.author(count));\n }\n\n int dotsWidth = option.fontMetrics.width(\"...\");\n\n QString messageCountText = QString(\"(%L1)\").arg(messageCount);\n int messageCountWidth = option.fontMetrics.width(messageCountText);\n\n int linePos = index.row() * lineHeight;\n int authorWidth = qMin(authorBaseWidth - (messageCount > 1 ? messageCountWidth + margin : 0), \n lineWidth - (messageCount > 1 ? messageCountWidth + 2*margin : 0) - margin);\n int authorPos = margin;\n int tmpAuthorWidth = authorWidth;\n if (option.fontMetrics.width(cauthors) > authorWidth && authorWidth > dotsWidth) {\n tmpAuthorWidth = authorWidth - dotsWidth;\n painter->drawText(authorPos+tmpAuthorWidth, linePos, dotsWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignTop|Qt::TextSingleLine, \"...\");\n }\n painter->drawText(authorPos, linePos, tmpAuthorWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignTop|Qt::TextSingleLine, cauthors);\n\n if (messageCount > 1) {\n int messageCountPos = qMin(2*margin + authorWidth, lineWidth - messageCountWidth - margin);\n painter->drawText(messageCountPos, linePos, messageCountWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignTop|Qt::TextSingleLine, messageCountText);\n }\n\n int subjectPos = authorBaseWidth + 2*margin;\n int timeWidth = option.fontMetrics.width(ctime);\n int subjectWidth = lineWidth - subjectPos - timeWidth - 2*margin;\n int tmpSubjectWidth = subjectWidth;\n if (option.fontMetrics.width(ctitle) > subjectWidth && subjectWidth > dotsWidth) {\n tmpSubjectWidth = subjectWidth - dotsWidth;\n painter->drawText(subjectPos+tmpSubjectWidth, linePos, dotsWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignTop|Qt::TextSingleLine, \"...\");\n }\n painter->drawText(subjectPos, linePos, tmpSubjectWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignVCenter|Qt::TextSingleLine, ctitle);\n\n int timePos = qMax(lineWidth - margin - timeWidth, authorBaseWidth + 2*margin);\n timeWidth = qMax(lineWidth - (timePos + margin), 0);\n int tmpTimeWidth = timeWidth;\n if (option.fontMetrics.width(ctime) > timeWidth && timeWidth > dotsWidth) {\n tmpTimeWidth = timeWidth - dotsWidth;\n painter->drawText(timePos+tmpTimeWidth, linePos, dotsWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignTop|Qt::TextSingleLine, \"...\");\n }\n painter->drawText(timePos, linePos, tmpTimeWidth, option.fontMetrics.height(), Qt::AlignLeft|Qt::AlignVCenter|Qt::TextSingleLine, ctime);\n}\n\nQSize ConversationDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const\n{\n int lineHeight = option.fontMetrics.height() + 2;\n return QSize(lineWidth, lineHeight);\n}\n\nvoid ConversationDelegate::updateWidth(int pos, int \/*nouse*\/)\n{\n lineWidth = pos;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file.\n#include \"XercesDOMPrintWriter.hpp\"\n\n\n\n#include <cassert>\n\n\n\n#include <XalanDOM\/XalanDOMString.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/TextOutputStream.hpp>\n\n\n\nXercesDOMPrintWriter::XercesDOMPrintWriter(\n\t\t\tTextOutputStream&\ttheOutputStream,\n\t\t\tbool\t\t\t\tfAutoFlush) :\n\tPrintWriter(fAutoFlush),\n\tm_OutputStream(theOutputStream)\n{\n}\n\n\n\nXercesDOMPrintWriter::~XercesDOMPrintWriter()\n{\n\tflush();\n}\n\n\n\nbool\nXercesDOMPrintWriter::checkError() const\n{\n\treturn false;\n}\n\n\n\nvoid\nXercesDOMPrintWriter::close()\n{\n}\n\n\nvoid\nXercesDOMPrintWriter::flush()\n{\n\tm_OutputStream.flush();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::write(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheOffset,\n\t\t\tunsigned int\ttheLength)\n{\n\twrite(DOMString(s), theOffset, theLength);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::write(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheOffset,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\tassert(length(s) == 0 || theOffset < length(s));\n\n\tif (theLength == -1)\n\t{\n\t\tif (theOffset == 0)\n\t\t{\n\t\t\tm_OutputStream.write(s);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_OutputStream.write(s + theOffset);\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst long\ttheStopIndex = theOffset + theLength;\n\n\t\tfor (long i = theOffset; i < theStopIndex; i++)\n\t\t{\n\t\t\tm_OutputStream.write(s[i]);\n\t\t}\n\t}\n}\n\n\n\nvoid\nXercesDOMPrintWriter::write(XMLCh\tc)\n{\n\tm_OutputStream.write(c);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::write(\n\t\t\tconst DOMString&\ts,\n\t\t\tunsigned int\t\ttheOffset,\n\t\t\tunsigned int\t\ttheLength)\n{\n\twrite(c_wstr(s), theOffset, theLength);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(bool\tb)\n{\n\tif (b == true)\n\t{\n\t\tprint(XALAN_STATIC_UCODE_STRING(\"true\"));\n\t}\n\telse\n\t{\n\t\tprint(XALAN_STATIC_UCODE_STRING(\"false\"));\n\t}\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(char\tc)\n{\n\twrite(c);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\twrite(s,\n\t\t 0,\n\t\t theLength);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\tassert(theLength >= 0 || theLength == -1);\n\n\twrite(s,\n\t\t 0,\n\t\t theLength);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(double\td)\n{\n\tm_OutputStream.write(c_wstr(DoubleToDOMString(d)));\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(int\ti)\n{\n\tm_OutputStream.write(c_wstr(LongToDOMString(i)));\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(long\tl)\n{\n\tm_OutputStream.write(c_wstr(LongToDOMString(l)));\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(const DOMString&\ts)\n{\n\tm_OutputStream.write(c_wstr(s));\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println()\n{\n\tm_OutputStream.write(XMLCh('\\n'));\n\n\tflush();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(bool\tb)\n{\n\tprint(b);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(char\tc)\n{\n\tprint(c);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tprint(s, theLength);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tprint(s, theLength);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(double\td)\n{\n\tprint(d);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(int\t\ti)\n{\n\tprint(i);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(long\tl)\n{\n\tprint(l);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(const DOMString&\ts)\n{\n\tprint(s);\n\n\tprintln();\n}\n<commit_msg>Fixed newline problem on Linux.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file.\n#include \"XercesDOMPrintWriter.hpp\"\n\n\n\n#include <cassert>\n\n\n\n#include <XalanDOM\/XalanDOMString.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/TextOutputStream.hpp>\n\n\n\nXercesDOMPrintWriter::XercesDOMPrintWriter(\n\t\t\tTextOutputStream&\ttheOutputStream,\n\t\t\tbool\t\t\t\tfAutoFlush) :\n\tPrintWriter(fAutoFlush),\n\tm_OutputStream(theOutputStream)\n{\n}\n\n\n\nXercesDOMPrintWriter::~XercesDOMPrintWriter()\n{\n\tflush();\n}\n\n\n\nbool\nXercesDOMPrintWriter::checkError() const\n{\n\treturn false;\n}\n\n\n\nvoid\nXercesDOMPrintWriter::close()\n{\n}\n\n\nvoid\nXercesDOMPrintWriter::flush()\n{\n\tm_OutputStream.flush();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::write(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheOffset,\n\t\t\tunsigned int\ttheLength)\n{\n\twrite(DOMString(s), theOffset, theLength);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::write(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheOffset,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\tassert(length(s) == 0 || theOffset < length(s));\n\n\tif (theLength == -1)\n\t{\n\t\tif (theOffset == 0)\n\t\t{\n\t\t\tm_OutputStream.write(s);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_OutputStream.write(s + theOffset);\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst long\ttheStopIndex = theOffset + theLength;\n\n\t\tfor (long i = theOffset; i < theStopIndex; i++)\n\t\t{\n\t\t\tm_OutputStream.write(s[i]);\n\t\t}\n\t}\n}\n\n\n\nvoid\nXercesDOMPrintWriter::write(XMLCh\tc)\n{\n\tm_OutputStream.write(c);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::write(\n\t\t\tconst DOMString&\ts,\n\t\t\tunsigned int\t\ttheOffset,\n\t\t\tunsigned int\t\ttheLength)\n{\n\twrite(c_wstr(s), theOffset, theLength);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(bool\tb)\n{\n\tif (b == true)\n\t{\n\t\tprint(XALAN_STATIC_UCODE_STRING(\"true\"));\n\t}\n\telse\n\t{\n\t\tprint(XALAN_STATIC_UCODE_STRING(\"false\"));\n\t}\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(char\tc)\n{\n\twrite(c);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\twrite(s,\n\t\t 0,\n\t\t theLength);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tassert(s != 0);\n\tassert(theLength >= 0 || theLength == -1);\n\n\twrite(s,\n\t\t 0,\n\t\t theLength);\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(double\td)\n{\n\tm_OutputStream.write(c_wstr(DoubleToDOMString(d)));\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(int\ti)\n{\n\tm_OutputStream.write(c_wstr(LongToDOMString(i)));\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(long\tl)\n{\n\tm_OutputStream.write(c_wstr(LongToDOMString(l)));\n}\n\n\n\nvoid\nXercesDOMPrintWriter::print(const DOMString&\ts)\n{\n\tm_OutputStream.write(c_wstr(s));\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println()\n{\n\tm_OutputStream.write(c_wstr(XALAN_STATIC_UCODE_STRING(\"\\n\")));\n\n\tflush();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(bool\tb)\n{\n\tprint(b);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(char\tc)\n{\n\tprint(c);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(\n\t\t\tconst char*\t\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tprint(s, theLength);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(\n\t\t\tconst XMLCh*\ts,\n\t\t\tunsigned int\ttheLength)\n{\n\tprint(s, theLength);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(double\td)\n{\n\tprint(d);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(int\t\ti)\n{\n\tprint(i);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(long\tl)\n{\n\tprint(l);\n\n\tprintln();\n}\n\n\n\nvoid\nXercesDOMPrintWriter::println(const DOMString&\ts)\n{\n\tprint(s);\n\n\tprintln();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"DrakeCollision.h\"\n#include \"BulletModel.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace DrakeCollision\n{\n BulletElement::BulletElement(const Matrix4d& T_elem_to_link, Shape shape, \n const vector<double>& params,\n const string& group_name)\n : T_elem_to_link(T_elem_to_link),shape(shape)\n {\n setGroupName(group_name);\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: START\" << std::endl;\n \/\/END_DEBUG\n btCollisionShape* bt_shape;\n switch (shape) {\n case BOX:\n {\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Create BOX ...\" << std::endl;\n \/\/END_DEBUG\n btBoxShape bt_box( btVector3(params[0]\/2,params[1]\/2,params[2]\/2) );\n \/* Strange things happen to the collision-normals when we use the\n * convex interface to the btBoxShape. Instead, we'll explicitly create\n * a btConvexHullShape.\n *\/\n bt_shape = new btConvexHullShape();\n bt_shape->setMargin(0.05);\n for (int i=0; i<8; ++i){\n btVector3 vtx;\n bt_box.getVertex(i,vtx);\n dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(vtx);\n }\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Created BOX\" << std::endl;\n \/\/END_DEBUG\n }\n break;\n case SPHERE:\n if (true || params[0] != 0) {\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Create SPHERE ...\" << std::endl;\n \/\/END_DEBUG\n bt_shape = new btSphereShape(params[0]) ;\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Created SPHERE\" << std::endl;\n \/\/END_DEBUG\n } else {\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: THROW\" << std::endl;\n \/\/END_DEBUG\n throw zeroRadiusSphereException();\n }\n break;\n case CYLINDER:\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Create CYLINDER ...\" << std::endl;\n \/\/END_DEBUG\n bt_shape = new btCylinderShapeZ( btVector3(params[0],params[0],params[1]\/2) );\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Created CYLINDER ...\" << std::endl;\n \/\/END_DEBUG\n break;\n case MESH:\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Create MESH ...\" << std::endl;\n \/\/END_DEBUG\n \/\/bt_shape = new btConvexHullShape( (btScalar*) params.data(), \n \/\/params.size()\/3,\n \/\/(int) 3*sizeof(double) );\n bt_shape = new btConvexHullShape();\n bt_shape->setMargin(0.05);\n for (int i=0; i<params.size(); i+=3){\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Adding point \" << i\/3 + 1 << std::endl;\n \/\/END_DEBUG\n dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(params[i],params[i+1],params[i+2]));\n }\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Created MESH ...\" << std::endl;\n \/\/END_DEBUG\n break;\n case CAPSULE:\n bt_shape = new btConvexHullShape();\n dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,-params[1]\/2));\n dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,params[1]\/2));\n bt_shape->setMargin(params[0]);\n break;\n default:\n cerr << \"Warning: Collision element has an unknown type \" << shape << endl;\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: THROW\" << std::endl;\n \/\/END_DEBUG\n throw unknownShapeException(shape);\n break;\n }\n \/\/DEBUG\n \/\/cout << \"BulletElement::BulletElement: Creating btCollisionObject\" << endl;\n \/\/END_DEBUG\n bt_obj = make_shared<btCollisionObject>();\n \/\/DEBUG\n \/\/cout << \"BulletElement::BulletElement: Setting bt_shape for bt_ob\" << endl;\n \/\/END_DEBUG\n bt_obj->setCollisionShape(bt_shape);\n \/\/DEBUG\n \/\/cout << \"BulletElement::BulletElement: Setting world transform for bt_ob\" << endl;\n \/\/END_DEBUG\n setWorldTransform(Matrix4d::Identity());\n \/\/DEBUG\n \/\/cout << \"BulletElement::BulletElement: END\" << std::endl;\n \/\/END_DEBUG\n }\n \n const Matrix4d& BulletElement::getWorldTransform() const\n {\n return T_elem_to_world;\n }\n\n const Matrix4d& BulletElement::getLinkTransform() const\n {\n return T_elem_to_link;\n }\n\n const Shape& BulletElement::getShape() const\n {\n return shape;\n }\n\n void BulletElement::updateWorldTransform(const Matrix4d& T_link_to_world)\n {\n setWorldTransform(T_link_to_world*(this->T_elem_to_link));\n }\n \n void BulletElement::setWorldTransform(const Matrix4d& T)\n {\n this->T_elem_to_world = T_elem_to_world;\n\n btMatrix3x3 rot;\n btVector3 pos;\n btTransform btT;\n\n rot.setValue( T(0,0), T(0,1), T(0,2),\n T(1,0), T(1,1), T(1,2),\n T(2,0), T(2,1), T(2,2) );\n btT.setBasis(rot);\n pos.setValue( T(0,3), T(1,3), T(2,3) );\n btT.setOrigin(pos);\n\n bt_obj->setWorldTransform(btT);\n }\n\n const string& BulletElement::getGroupName() const\n {\n return group_name;\n }\n\n void BulletElement::setGroupName(const string& group_name)\n {\n this->group_name = group_name;\n }\n}\n<commit_msg>Taking away margins entirely<commit_after>#include <iostream>\n\n#include \"DrakeCollision.h\"\n#include \"BulletModel.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace DrakeCollision\n{\n BulletElement::BulletElement(const Matrix4d& T_elem_to_link, Shape shape, \n const vector<double>& params,\n const string& group_name)\n : T_elem_to_link(T_elem_to_link),shape(shape)\n {\n setGroupName(group_name);\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: START\" << std::endl;\n \/\/END_DEBUG\n btCollisionShape* bt_shape;\n switch (shape) {\n case BOX:\n {\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Create BOX ...\" << std::endl;\n \/\/END_DEBUG\n btBoxShape bt_box( btVector3(params[0]\/2,params[1]\/2,params[2]\/2) );\n \/* Strange things happen to the collision-normals when we use the\n * convex interface to the btBoxShape. Instead, we'll explicitly create\n * a btConvexHullShape.\n *\/\n bt_shape = new btConvexHullShape();\n bt_shape->setMargin(0.00);\n for (int i=0; i<8; ++i){\n btVector3 vtx;\n bt_box.getVertex(i,vtx);\n dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(vtx);\n }\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Created BOX\" << std::endl;\n \/\/END_DEBUG\n }\n break;\n case SPHERE:\n if (true || params[0] != 0) {\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Create SPHERE ...\" << std::endl;\n \/\/END_DEBUG\n bt_shape = new btSphereShape(params[0]) ;\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Created SPHERE\" << std::endl;\n \/\/END_DEBUG\n } else {\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: THROW\" << std::endl;\n \/\/END_DEBUG\n throw zeroRadiusSphereException();\n }\n break;\n case CYLINDER:\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Create CYLINDER ...\" << std::endl;\n \/\/END_DEBUG\n bt_shape = new btCylinderShapeZ( btVector3(params[0],params[0],params[1]\/2) );\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Created CYLINDER ...\" << std::endl;\n \/\/END_DEBUG\n break;\n case MESH:\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Create MESH ...\" << std::endl;\n \/\/END_DEBUG\n \/\/bt_shape = new btConvexHullShape( (btScalar*) params.data(), \n \/\/params.size()\/3,\n \/\/(int) 3*sizeof(double) );\n bt_shape = new btConvexHullShape();\n bt_shape->setMargin(0.00);\n for (int i=0; i<params.size(); i+=3){\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Adding point \" << i\/3 + 1 << std::endl;\n \/\/END_DEBUG\n dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(params[i],params[i+1],params[i+2]));\n }\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: Created MESH ...\" << std::endl;\n \/\/END_DEBUG\n break;\n case CAPSULE:\n bt_shape = new btConvexHullShape();\n dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,-params[1]\/2));\n dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,params[1]\/2));\n bt_shape->setMargin(params[0]);\n break;\n default:\n cerr << \"Warning: Collision element has an unknown type \" << shape << endl;\n \/\/DEBUG\n \/\/std::cout << \"BulletElement::BulletElement: THROW\" << std::endl;\n \/\/END_DEBUG\n throw unknownShapeException(shape);\n break;\n }\n \/\/DEBUG\n \/\/cout << \"BulletElement::BulletElement: Creating btCollisionObject\" << endl;\n \/\/END_DEBUG\n bt_obj = make_shared<btCollisionObject>();\n \/\/DEBUG\n \/\/cout << \"BulletElement::BulletElement: Setting bt_shape for bt_ob\" << endl;\n \/\/END_DEBUG\n bt_obj->setCollisionShape(bt_shape);\n \/\/DEBUG\n \/\/cout << \"BulletElement::BulletElement: Setting world transform for bt_ob\" << endl;\n \/\/END_DEBUG\n setWorldTransform(Matrix4d::Identity());\n \/\/DEBUG\n \/\/cout << \"BulletElement::BulletElement: END\" << std::endl;\n \/\/END_DEBUG\n }\n \n const Matrix4d& BulletElement::getWorldTransform() const\n {\n return T_elem_to_world;\n }\n\n const Matrix4d& BulletElement::getLinkTransform() const\n {\n return T_elem_to_link;\n }\n\n const Shape& BulletElement::getShape() const\n {\n return shape;\n }\n\n void BulletElement::updateWorldTransform(const Matrix4d& T_link_to_world)\n {\n setWorldTransform(T_link_to_world*(this->T_elem_to_link));\n }\n \n void BulletElement::setWorldTransform(const Matrix4d& T)\n {\n this->T_elem_to_world = T_elem_to_world;\n\n btMatrix3x3 rot;\n btVector3 pos;\n btTransform btT;\n\n rot.setValue( T(0,0), T(0,1), T(0,2),\n T(1,0), T(1,1), T(1,2),\n T(2,0), T(2,1), T(2,2) );\n btT.setBasis(rot);\n pos.setValue( T(0,3), T(1,3), T(2,3) );\n btT.setOrigin(pos);\n\n bt_obj->setWorldTransform(btT);\n }\n\n const string& BulletElement::getGroupName() const\n {\n return group_name;\n }\n\n void BulletElement::setGroupName(const string& group_name)\n {\n this->group_name = group_name;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\r\n#include <cstdlib>\r\n\r\n#include <GL\/glew.h>\r\n#include <SDL2\/SDL.h>\r\n\r\n#include \"FileUtil.h\"\r\n\r\n#define WINDOW_SIZE 640\r\n\r\nint\r\nmain(int argc, char** argv) {\r\n (void) argc;\r\n (void) argv;\r\n\r\n int retval = SDL_Init(SDL_INIT_VIDEO);\r\n if (retval != 0) {\r\n fprintf(stderr, \"SDL_Init() failed: %s\\n\", SDL_GetError());\r\n exit(EXIT_FAILURE);\r\n }\r\n \r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\r\n SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\r\n SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\r\n\r\n SDL_ClearError();\r\n SDL_Window* mainWindow = SDL_CreateWindow(\"Compiling a Shader\",\r\n SDL_WINDOWPOS_CENTERED,\r\n SDL_WINDOWPOS_CENTERED,\r\n WINDOW_SIZE,\r\n WINDOW_SIZE,\r\n SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);\r\n if (mainWindow == NULL) {\r\n fprintf(stderr, \"SDL_CreateWindow() failed: %s\\n\", SDL_GetError());\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n SDL_GLContext mainContext = SDL_GL_CreateContext(mainWindow);\r\n if (mainContext == NULL) {\r\n fprintf(stderr, \"SDL_GL_CreateContext() failed: %s\\n\", SDL_GetError());\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n GLenum err = glewInit();\r\n if (err != GLEW_OK) {\r\n fprintf(stderr, \"Error Initializing GLEW: %s\\n\", glewGetErrorString(err));\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n GLuint vertShader = glCreateShader(GL_VERTEX_SHADER);\r\n if (vertShader == 0) {\r\n fprintf(stderr, \"Error creating vertex shader.\\n\");\r\n exit(EXIT_FAILURE);\r\n }\r\n const GLchar* shaderCode = FileUtil::loadFileAsString(\"basic.vert\");\r\n glShaderSource(vertShader, 1, &shaderCode, NULL);\r\n delete [] shaderCode;\r\n glCompileShader(vertShader);\r\n\r\n GLint result;\r\n glGetShaderiv(vertShader, GL_COMPILE_STATUS, &result);\r\n if (result == GL_FALSE) {\r\n fprintf(stderr, \"Vertex shader compilation failed!\\n\");\r\n\r\n GLint logLength;\r\n glGetShaderiv(vertShader, GL_INFO_LOG_LENGTH, &logLength);\r\n if (logLength > 0) {\r\n char* logBuffer = new char[logLength];\r\n GLsizei bytesCopied;\r\n glGetShaderInfoLog(vertShader, logLength, &bytesCopied, logBuffer);\r\n fprintf(stderr, \"Shader info log:\\n%s\\n\", logBuffer);\r\n delete [] logBuffer;\r\n exit(EXIT_FAILURE);\r\n }\r\n }\r\n \r\n SDL_GL_DeleteContext(mainContext);\r\n SDL_DestroyWindow(mainWindow);\r\n SDL_Quit();\r\n\r\n return 0;\r\n}\r\n<commit_msg>Finished recipe on 15.<commit_after>#include <cstdio>\r\n#include <cstdlib>\r\n\r\n#include <GL\/glew.h>\r\n#include <SDL2\/SDL.h>\r\n\r\n#include \"FileUtil.h\"\r\n\r\n#define WINDOW_SIZE 640\r\n\r\nvoid printShaderInfoLog(GLuint shaderHandle) {\r\n GLint logLength;\r\n glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &logLength);\r\n if (logLength > 0) {\r\n char* logBuffer = new char[logLength];\r\n GLsizei bytesCopied;\r\n glGetShaderInfoLog(shaderHandle, logLength, &bytesCopied, logBuffer);\r\n (void)fprintf(stderr, \"Shader info log:\\n%s\\n\", logBuffer);\r\n delete [] logBuffer;\r\n exit(EXIT_FAILURE);\r\n }\r\n}\r\n\r\nint\r\nmain(int argc, char** argv) {\r\n (void)argc;\r\n (void)argv;\r\n\r\n int retval = SDL_Init(SDL_INIT_VIDEO);\r\n if (retval != 0) {\r\n (void)fprintf(stderr, \"SDL_Init() failed: %s\\n\", SDL_GetError());\r\n exit(EXIT_FAILURE);\r\n }\r\n \r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\r\n SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\r\n SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\r\n\r\n SDL_ClearError();\r\n SDL_Window* mainWindow = SDL_CreateWindow(\"Compiling a Shader\",\r\n SDL_WINDOWPOS_CENTERED,\r\n SDL_WINDOWPOS_CENTERED,\r\n WINDOW_SIZE,\r\n WINDOW_SIZE,\r\n SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);\r\n if (mainWindow == NULL) {\r\n (void)fprintf(stderr, \"SDL_CreateWindow() failed: %s\\n\", SDL_GetError());\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n SDL_GLContext mainContext = SDL_GL_CreateContext(mainWindow);\r\n if (mainContext == NULL) {\r\n (void)fprintf(stderr, \"SDL_GL_CreateContext() failed: %s\\n\", SDL_GetError());\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n GLenum err = glewInit();\r\n if (err != GLEW_OK) {\r\n (void)fprintf(stderr, \"Error Initializing GLEW: %s\\n\", glewGetErrorString(err));\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n GLuint vertShader = glCreateShader(GL_VERTEX_SHADER);\r\n if (vertShader == 0) {\r\n (void)fprintf(stderr, \"Error creating vertex shader.\\n\");\r\n exit(EXIT_FAILURE);\r\n }\r\n const GLchar* shaderCode = FileUtil::loadFileAsString(\"basic.vert\");\r\n glShaderSource(vertShader, 1, &shaderCode, NULL);\r\n delete [] shaderCode;\r\n glCompileShader(vertShader);\r\n\r\n GLint result;\r\n glGetShaderiv(vertShader, GL_COMPILE_STATUS, &result);\r\n if (result == GL_FALSE) {\r\n (void)fprintf(stderr, \"Vertex shader compilation failed!\\n\");\r\n printShaderInfoLog(vertShader);\r\n } else {\r\n (void)printf(\"Shader compiled successfully!\\n\");\r\n \/\/ Print warnings, if available\r\n printShaderInfoLog(vertShader);\r\n }\r\n \r\n SDL_GL_DeleteContext(mainContext);\r\n SDL_DestroyWindow(mainWindow);\r\n SDL_Quit();\r\n\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/data\/service\/server_lib.h\"\n\n#include \"tensorflow\/core\/data\/service\/credentials_factory.h\"\n#include \"tensorflow\/core\/data\/service\/grpc_dispatcher_impl.h\"\n#include \"tensorflow\/core\/data\/service\/grpc_util.h\"\n#include \"tensorflow\/core\/data\/service\/grpc_worker_impl.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n\nnamespace tensorflow {\nnamespace data {\n\nnamespace {\nconstexpr char kPortPlaceholder[] = \"%port%\";\n}\n\nGrpcDataServerBase::GrpcDataServerBase(int port, const std::string& protocol,\n const std::string server_type)\n : requested_port_(port),\n protocol_(protocol),\n server_type_(server_type),\n bound_port_(port) {}\n\nStatus GrpcDataServerBase::Start() {\n if (stopped_) {\n return errors::FailedPrecondition(\n \"Server cannot be started after it has been stopped.\");\n }\n if (started_) {\n return Status::OK();\n }\n ::grpc::ServerBuilder builder;\n std::shared_ptr<::grpc::ServerCredentials> credentials;\n TF_RETURN_IF_ERROR(\n CredentialsFactory::CreateServerCredentials(protocol_, &credentials));\n builder.AddListeningPort(strings::StrCat(\"0.0.0.0:\", requested_port_),\n credentials, &bound_port_);\n builder.SetMaxReceiveMessageSize(-1);\n\n AddDataServiceToBuilder(builder);\n AddProfilerServiceToBuilder(builder);\n server_ = builder.BuildAndStart();\n if (!server_) {\n return errors::Internal(\"Could not start gRPC server\");\n }\n\n TF_RETURN_IF_ERROR(StartServiceInternal());\n\n started_ = true;\n LOG(INFO) << \"Started tf.data \" << server_type_\n << \" running at 0.0.0.0:\" << BoundPort();\n return Status::OK();\n}\n\nvoid GrpcDataServerBase::Stop() {\n if (stopped_) {\n return;\n }\n if (server_) {\n StopServiceInternal();\n server_->Shutdown();\n LOG(INFO) << \"Shut down \" << server_type_ << \" server running at port \"\n << BoundPort();\n }\n stopped_ = true;\n}\n\nvoid GrpcDataServerBase::Join() { server_->Wait(); }\n\nint GrpcDataServerBase::BoundPort() { return bound_port(); }\n\nvoid GrpcDataServerBase::AddProfilerServiceToBuilder(\n ::grpc::ServerBuilder& builder) {\n profiler_service_ = profiler::CreateProfilerService();\n builder.RegisterService(profiler_service_.get());\n}\n\nDispatchGrpcDataServer::DispatchGrpcDataServer(\n const experimental::DispatcherConfig& config)\n : GrpcDataServerBase(config.port(), config.protocol(), \"DispatchServer\"),\n config_(config) {}\n\nDispatchGrpcDataServer::~DispatchGrpcDataServer() { delete service_; }\n\nvoid DispatchGrpcDataServer::AddDataServiceToBuilder(\n ::grpc::ServerBuilder& builder) {\n service_ = absl::make_unique<GrpcDispatcherImpl>(config_, builder).release();\n}\n\nStatus DispatchGrpcDataServer::StartServiceInternal() {\n return service_->Start();\n}\n\nStatus DispatchGrpcDataServer::NumWorkers(int* num_workers) {\n GetWorkersRequest req;\n GetWorkersResponse resp;\n ::grpc::ServerContext ctx;\n ::grpc::Status s = service_->GetWorkers(&ctx, &req, &resp);\n if (!s.ok()) {\n return grpc_util::WrapError(\"Failed to get workers\", s);\n }\n *num_workers = resp.workers_size();\n return Status::OK();\n}\n\nsize_t DispatchGrpcDataServer::NumActiveJobs() {\n return service_->NumActiveJobs();\n}\n\nWorkerGrpcDataServer::WorkerGrpcDataServer(\n const experimental::WorkerConfig& config)\n : GrpcDataServerBase(config.port(), config.protocol(), \"WorkerServer\"),\n config_(config) {}\n\nWorkerGrpcDataServer::~WorkerGrpcDataServer() { delete service_; }\n\nvoid WorkerGrpcDataServer::AddDataServiceToBuilder(\n ::grpc::ServerBuilder& builder) {\n service_ = absl::make_unique<GrpcWorkerImpl>(config_, builder).release();\n}\n\nStatus WorkerGrpcDataServer::StartServiceInternal() {\n std::string base_address = config_.worker_address();\n if (base_address.empty()) {\n base_address = absl::StrCat(\"localhost:\", kPortPlaceholder);\n }\n std::string worker_address = str_util::StringReplace(\n base_address, kPortPlaceholder, absl::StrCat(bound_port()),\n \/*replace_all=*\/false);\n std::string transfer_address = worker_address;\n std::string transfer_protocol = config_.data_transfer_protocol();\n if (!transfer_protocol.empty() && transfer_protocol != \"grpc\") {\n TF_RETURN_IF_ERROR(DataTransferServer::Build(\n transfer_protocol, service_->get_element_getter(), &transfer_server_));\n TF_RETURN_IF_ERROR(transfer_server_->Start());\n LOG(INFO) << \"Data transfer server started at 0.0.0.0:\"\n << transfer_server_->get_port();\n transfer_address = str_util::StringReplace(\n config_.data_transfer_address(), kPortPlaceholder,\n absl::StrCat(transfer_server_->get_port()),\n \/*replace_all=*\/false);\n }\n TF_RETURN_IF_ERROR(service_->Start(worker_address, transfer_address));\n return Status::OK();\n}\n\nvoid WorkerGrpcDataServer::StopServiceInternal() { service_->Stop(); }\n\nStatus WorkerGrpcDataServer::NumTasks(int* num_tasks) {\n GetWorkerTasksRequest req;\n GetWorkerTasksResponse resp;\n ::grpc::ServerContext ctx;\n ::grpc::Status s = service_->GetWorkerTasks(&ctx, &req, &resp);\n if (!s.ok()) {\n return grpc_util::WrapError(\"Failed to get tasks\", s);\n }\n *num_tasks = resp.tasks_size();\n return Status::OK();\n}\n\nStatus NewDispatchServer(const experimental::DispatcherConfig& config,\n std::unique_ptr<DispatchGrpcDataServer>& out_server) {\n out_server = absl::make_unique<DispatchGrpcDataServer>(config);\n return Status::OK();\n}\n\nStatus NewWorkerServer(const experimental::WorkerConfig& config,\n std::unique_ptr<WorkerGrpcDataServer>& out_server) {\n out_server = absl::make_unique<WorkerGrpcDataServer>(config);\n return Status::OK();\n}\n\n} \/\/ namespace data\n} \/\/ namespace tensorflow\n<commit_msg>#tf-data-service #codehealth [22\/25] Fix ClangTidy error.<commit_after>\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/data\/service\/server_lib.h\"\n\n#include <memory>\n#include <string>\n\n#include \"tensorflow\/core\/data\/service\/credentials_factory.h\"\n#include \"tensorflow\/core\/data\/service\/grpc_dispatcher_impl.h\"\n#include \"tensorflow\/core\/data\/service\/grpc_util.h\"\n#include \"tensorflow\/core\/data\/service\/grpc_worker_impl.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n\nnamespace tensorflow {\nnamespace data {\n\nnamespace {\nconstexpr char kPortPlaceholder[] = \"%port%\";\n}\n\nGrpcDataServerBase::GrpcDataServerBase(int port, const std::string& protocol,\n const std::string server_type)\n : requested_port_(port),\n protocol_(protocol),\n server_type_(server_type),\n bound_port_(port) {}\n\nStatus GrpcDataServerBase::Start() {\n if (stopped_) {\n return errors::FailedPrecondition(\n \"Server cannot be started after it has been stopped.\");\n }\n if (started_) {\n return Status::OK();\n }\n ::grpc::ServerBuilder builder;\n std::shared_ptr<::grpc::ServerCredentials> credentials;\n TF_RETURN_IF_ERROR(\n CredentialsFactory::CreateServerCredentials(protocol_, &credentials));\n builder.AddListeningPort(strings::StrCat(\"0.0.0.0:\", requested_port_),\n credentials, &bound_port_);\n builder.SetMaxReceiveMessageSize(-1);\n\n AddDataServiceToBuilder(builder);\n AddProfilerServiceToBuilder(builder);\n server_ = builder.BuildAndStart();\n if (!server_) {\n return errors::Internal(\"Could not start gRPC server\");\n }\n\n TF_RETURN_IF_ERROR(StartServiceInternal());\n\n started_ = true;\n LOG(INFO) << \"Started tf.data \" << server_type_\n << \" running at 0.0.0.0:\" << BoundPort();\n return Status::OK();\n}\n\nvoid GrpcDataServerBase::Stop() {\n if (stopped_) {\n return;\n }\n if (server_) {\n StopServiceInternal();\n server_->Shutdown();\n LOG(INFO) << \"Shut down \" << server_type_ << \" server running at port \"\n << BoundPort();\n }\n stopped_ = true;\n}\n\nvoid GrpcDataServerBase::Join() { server_->Wait(); }\n\nint GrpcDataServerBase::BoundPort() { return bound_port(); }\n\nvoid GrpcDataServerBase::AddProfilerServiceToBuilder(\n ::grpc::ServerBuilder& builder) {\n profiler_service_ = profiler::CreateProfilerService();\n builder.RegisterService(profiler_service_.get());\n}\n\nDispatchGrpcDataServer::DispatchGrpcDataServer(\n const experimental::DispatcherConfig& config)\n : GrpcDataServerBase(config.port(), config.protocol(), \"DispatchServer\"),\n config_(config) {}\n\nDispatchGrpcDataServer::~DispatchGrpcDataServer() { delete service_; }\n\nvoid DispatchGrpcDataServer::AddDataServiceToBuilder(\n ::grpc::ServerBuilder& builder) {\n service_ = absl::make_unique<GrpcDispatcherImpl>(config_, builder).release();\n}\n\nStatus DispatchGrpcDataServer::StartServiceInternal() {\n return service_->Start();\n}\n\nStatus DispatchGrpcDataServer::NumWorkers(int* num_workers) {\n GetWorkersRequest req;\n GetWorkersResponse resp;\n ::grpc::ServerContext ctx;\n ::grpc::Status s = service_->GetWorkers(&ctx, &req, &resp);\n if (!s.ok()) {\n return grpc_util::WrapError(\"Failed to get workers\", s);\n }\n *num_workers = resp.workers_size();\n return Status::OK();\n}\n\nsize_t DispatchGrpcDataServer::NumActiveJobs() {\n return service_->NumActiveJobs();\n}\n\nWorkerGrpcDataServer::WorkerGrpcDataServer(\n const experimental::WorkerConfig& config)\n : GrpcDataServerBase(config.port(), config.protocol(), \"WorkerServer\"),\n config_(config) {}\n\nWorkerGrpcDataServer::~WorkerGrpcDataServer() { delete service_; }\n\nvoid WorkerGrpcDataServer::AddDataServiceToBuilder(\n ::grpc::ServerBuilder& builder) {\n service_ = absl::make_unique<GrpcWorkerImpl>(config_, builder).release();\n}\n\nStatus WorkerGrpcDataServer::StartServiceInternal() {\n std::string base_address = config_.worker_address();\n if (base_address.empty()) {\n base_address = absl::StrCat(\"localhost:\", kPortPlaceholder);\n }\n std::string worker_address = str_util::StringReplace(\n base_address, kPortPlaceholder, absl::StrCat(bound_port()),\n \/*replace_all=*\/false);\n std::string transfer_address = worker_address;\n std::string transfer_protocol = config_.data_transfer_protocol();\n if (!transfer_protocol.empty() && transfer_protocol != \"grpc\") {\n TF_RETURN_IF_ERROR(DataTransferServer::Build(\n transfer_protocol, service_->get_element_getter(), &transfer_server_));\n TF_RETURN_IF_ERROR(transfer_server_->Start());\n LOG(INFO) << \"Data transfer server started at 0.0.0.0:\"\n << transfer_server_->get_port();\n transfer_address = str_util::StringReplace(\n config_.data_transfer_address(), kPortPlaceholder,\n absl::StrCat(transfer_server_->get_port()),\n \/*replace_all=*\/false);\n }\n TF_RETURN_IF_ERROR(service_->Start(worker_address, transfer_address));\n return Status::OK();\n}\n\nvoid WorkerGrpcDataServer::StopServiceInternal() { service_->Stop(); }\n\nStatus WorkerGrpcDataServer::NumTasks(int* num_tasks) {\n GetWorkerTasksRequest req;\n GetWorkerTasksResponse resp;\n ::grpc::ServerContext ctx;\n ::grpc::Status s = service_->GetWorkerTasks(&ctx, &req, &resp);\n if (!s.ok()) {\n return grpc_util::WrapError(\"Failed to get tasks\", s);\n }\n *num_tasks = resp.tasks_size();\n return Status::OK();\n}\n\nStatus NewDispatchServer(const experimental::DispatcherConfig& config,\n std::unique_ptr<DispatchGrpcDataServer>& out_server) {\n out_server = absl::make_unique<DispatchGrpcDataServer>(config);\n return Status::OK();\n}\n\nStatus NewWorkerServer(const experimental::WorkerConfig& config,\n std::unique_ptr<WorkerGrpcDataServer>& out_server) {\n out_server = absl::make_unique<WorkerGrpcDataServer>(config);\n return Status::OK();\n}\n\n} \/\/ namespace data\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/util\/events_writer.h\"\n\n#include <math.h>\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/io\/record_reader.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/protobuf.h\"\n#include \"tensorflow\/core\/platform\/protobuf.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n#include \"tensorflow\/core\/public\/env.h\"\n#include \"tensorflow\/core\/public\/status.h\"\n#include \"tensorflow\/core\/util\/event.pb.h\"\n\nnamespace tensorflow {\nnamespace {\n\n\/\/ shorthand\nEnv* env() { return Env::Default(); }\n\nvoid WriteSimpleValue(EventsWriter* writer, double wall_time, int64 step,\n const string& tag, float simple_value) {\n Event event;\n event.set_wall_time(wall_time);\n event.set_step(step);\n Summary::Value* summ_val = event.mutable_summary()->add_value();\n summ_val->set_tag(tag);\n summ_val->set_simple_value(simple_value);\n writer->WriteEvent(event);\n}\n\nvoid WriteFile(EventsWriter* writer) {\n WriteSimpleValue(writer, 1234, 34, \"foo\", 3.14159);\n WriteSimpleValue(writer, 2345, 35, \"bar\", -42);\n}\n\nstatic bool ReadEventProto(io::RecordReader* reader, uint64* offset,\n Event* proto) {\n string record;\n Status s = reader->ReadRecord(offset, &record);\n if (!s.ok()) {\n return false;\n }\n return ParseProtoUnlimited(proto, record);\n}\n\nvoid VerifyFile(const string& filename) {\n CHECK(env()->FileExists(filename));\n RandomAccessFile* event_file;\n TF_CHECK_OK(env()->NewRandomAccessFile(filename, &event_file));\n io::RecordReader* reader = new io::RecordReader(event_file);\n\n uint64 offset = 0;\n\n Event actual;\n CHECK(ReadEventProto(reader, &offset, &actual));\n VLOG(1) << actual.ShortDebugString();\n \/\/ Wall time should be within 5s of now.\n\n double current_time = env()->NowMicros() \/ 1000000.0;\n EXPECT_LT(fabs(actual.wall_time() - current_time), 5);\n \/\/ Should have the current version number.\n EXPECT_EQ(actual.file_version(),\n strings::StrCat(EventsWriter::kVersionPrefix,\n EventsWriter::kCurrentVersion));\n\n Event expected;\n CHECK(ReadEventProto(reader, &offset, &actual));\n VLOG(1) << actual.ShortDebugString();\n ASSERT_TRUE(protobuf::TextFormat::ParseFromString(\n \"wall_time: 1234 step: 34 \"\n \"summary { value { tag: 'foo' simple_value: 3.14159 } }\",\n &expected));\n \/\/ TODO(keveman): Enable this check\n \/\/ EXPECT_THAT(expected, EqualsProto(actual));\n\n CHECK(ReadEventProto(reader, &offset, &actual));\n VLOG(1) << actual.ShortDebugString();\n ASSERT_TRUE(protobuf::TextFormat::ParseFromString(\n \"wall_time: 2345 step: 35 \"\n \"summary { value { tag: 'bar' simple_value: -42 } }\",\n &expected));\n \/\/ TODO(keveman): Enable this check\n \/\/ EXPECT_THAT(expected, EqualsProto(actual));\n\n TF_CHECK_OK(env()->DeleteFile(filename));\n\n delete reader;\n delete event_file;\n}\n\nstring GetDirName(const string& suffix) {\n return io::JoinPath(testing::TmpDir(), suffix);\n}\n\nTEST(EventWriter, WriteFlush) {\n string file_prefix = GetDirName(\"\/writeflush_test\");\n EventsWriter writer(file_prefix);\n WriteFile(&writer);\n EXPECT_TRUE(writer.Flush());\n string filename = writer.FileName();\n VerifyFile(filename);\n}\n\nTEST(EventWriter, WriteClose) {\n string file_prefix = GetDirName(\"\/writeclose_test\");\n EventsWriter writer(file_prefix);\n WriteFile(&writer);\n EXPECT_TRUE(writer.Close());\n string filename = writer.FileName();\n VerifyFile(filename);\n}\n\nTEST(EventWriter, WriteDelete) {\n string file_prefix = GetDirName(\"\/writedelete_test\");\n EventsWriter* writer = new EventsWriter(file_prefix);\n WriteFile(writer);\n string filename = writer->FileName();\n delete writer;\n VerifyFile(filename);\n}\n\nTEST(EventWriter, FailFlush) {\n string file_prefix = GetDirName(\"\/failflush_test\");\n EventsWriter writer(file_prefix);\n string filename = writer.FileName();\n WriteFile(&writer);\n EXPECT_TRUE(env()->FileExists(filename));\n env()->DeleteFile(filename);\n EXPECT_FALSE(env()->FileExists(filename));\n EXPECT_FALSE(writer.Flush());\n EXPECT_FALSE(env()->FileExists(filename));\n}\n\nTEST(EventWriter, FailClose) {\n string file_prefix = GetDirName(\"\/failclose_test\");\n EventsWriter writer(file_prefix);\n string filename = writer.FileName();\n WriteFile(&writer);\n EXPECT_TRUE(env()->FileExists(filename));\n env()->DeleteFile(filename);\n EXPECT_FALSE(env()->FileExists(filename));\n EXPECT_FALSE(writer.Close());\n EXPECT_FALSE(env()->FileExists(filename));\n}\n\nTEST(EventWriter, InitWriteClose) {\n string file_prefix = GetDirName(\"\/initwriteclose_test\");\n EventsWriter writer(file_prefix);\n EXPECT_TRUE(writer.Init());\n string filename0 = writer.FileName();\n EXPECT_TRUE(env()->FileExists(filename0));\n WriteFile(&writer);\n EXPECT_TRUE(writer.Close());\n string filename1 = writer.FileName();\n EXPECT_EQ(filename0, filename1);\n VerifyFile(filename1);\n}\n\nTEST(EventWriter, NameWriteClose) {\n string file_prefix = GetDirName(\"\/namewriteclose_test\");\n EventsWriter writer(file_prefix);\n string filename = writer.FileName();\n EXPECT_TRUE(env()->FileExists(filename));\n WriteFile(&writer);\n EXPECT_TRUE(writer.Close());\n VerifyFile(filename);\n}\n\nTEST(EventWriter, NameClose) {\n string file_prefix = GetDirName(\"\/nameclose_test\");\n EventsWriter writer(file_prefix);\n string filename = writer.FileName();\n EXPECT_TRUE(writer.Close());\n EXPECT_TRUE(env()->FileExists(filename));\n env()->DeleteFile(filename);\n}\n\nTEST(EventWriter, FileDeletionBeforeWriting) {\n string file_prefix = GetDirName(\"\/fdbw_test\");\n EventsWriter writer(file_prefix);\n string filename0 = writer.FileName();\n EXPECT_TRUE(env()->FileExists(filename0));\n env()->SleepForMicroseconds(\n 2000000); \/\/ To make sure timestamp part of filename will differ.\n env()->DeleteFile(filename0);\n EXPECT_TRUE(writer.Init()); \/\/ Init should reopen file.\n WriteFile(&writer);\n EXPECT_TRUE(writer.Flush());\n string filename1 = writer.FileName();\n EXPECT_NE(filename0, filename1);\n VerifyFile(filename1);\n}\n\n} \/\/ namespace\n} \/\/ namespace tensorflow\n<commit_msg>Delete duplicate #include. Change: 112846648<commit_after>\/* Copyright 2015 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/util\/events_writer.h\"\n\n#include <math.h>\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/io\/record_reader.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/protobuf.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n#include \"tensorflow\/core\/public\/env.h\"\n#include \"tensorflow\/core\/public\/status.h\"\n#include \"tensorflow\/core\/util\/event.pb.h\"\n\nnamespace tensorflow {\nnamespace {\n\n\/\/ shorthand\nEnv* env() { return Env::Default(); }\n\nvoid WriteSimpleValue(EventsWriter* writer, double wall_time, int64 step,\n const string& tag, float simple_value) {\n Event event;\n event.set_wall_time(wall_time);\n event.set_step(step);\n Summary::Value* summ_val = event.mutable_summary()->add_value();\n summ_val->set_tag(tag);\n summ_val->set_simple_value(simple_value);\n writer->WriteEvent(event);\n}\n\nvoid WriteFile(EventsWriter* writer) {\n WriteSimpleValue(writer, 1234, 34, \"foo\", 3.14159);\n WriteSimpleValue(writer, 2345, 35, \"bar\", -42);\n}\n\nstatic bool ReadEventProto(io::RecordReader* reader, uint64* offset,\n Event* proto) {\n string record;\n Status s = reader->ReadRecord(offset, &record);\n if (!s.ok()) {\n return false;\n }\n return ParseProtoUnlimited(proto, record);\n}\n\nvoid VerifyFile(const string& filename) {\n CHECK(env()->FileExists(filename));\n RandomAccessFile* event_file;\n TF_CHECK_OK(env()->NewRandomAccessFile(filename, &event_file));\n io::RecordReader* reader = new io::RecordReader(event_file);\n\n uint64 offset = 0;\n\n Event actual;\n CHECK(ReadEventProto(reader, &offset, &actual));\n VLOG(1) << actual.ShortDebugString();\n \/\/ Wall time should be within 5s of now.\n\n double current_time = env()->NowMicros() \/ 1000000.0;\n EXPECT_LT(fabs(actual.wall_time() - current_time), 5);\n \/\/ Should have the current version number.\n EXPECT_EQ(actual.file_version(),\n strings::StrCat(EventsWriter::kVersionPrefix,\n EventsWriter::kCurrentVersion));\n\n Event expected;\n CHECK(ReadEventProto(reader, &offset, &actual));\n VLOG(1) << actual.ShortDebugString();\n ASSERT_TRUE(protobuf::TextFormat::ParseFromString(\n \"wall_time: 1234 step: 34 \"\n \"summary { value { tag: 'foo' simple_value: 3.14159 } }\",\n &expected));\n \/\/ TODO(keveman): Enable this check\n \/\/ EXPECT_THAT(expected, EqualsProto(actual));\n\n CHECK(ReadEventProto(reader, &offset, &actual));\n VLOG(1) << actual.ShortDebugString();\n ASSERT_TRUE(protobuf::TextFormat::ParseFromString(\n \"wall_time: 2345 step: 35 \"\n \"summary { value { tag: 'bar' simple_value: -42 } }\",\n &expected));\n \/\/ TODO(keveman): Enable this check\n \/\/ EXPECT_THAT(expected, EqualsProto(actual));\n\n TF_CHECK_OK(env()->DeleteFile(filename));\n\n delete reader;\n delete event_file;\n}\n\nstring GetDirName(const string& suffix) {\n return io::JoinPath(testing::TmpDir(), suffix);\n}\n\nTEST(EventWriter, WriteFlush) {\n string file_prefix = GetDirName(\"\/writeflush_test\");\n EventsWriter writer(file_prefix);\n WriteFile(&writer);\n EXPECT_TRUE(writer.Flush());\n string filename = writer.FileName();\n VerifyFile(filename);\n}\n\nTEST(EventWriter, WriteClose) {\n string file_prefix = GetDirName(\"\/writeclose_test\");\n EventsWriter writer(file_prefix);\n WriteFile(&writer);\n EXPECT_TRUE(writer.Close());\n string filename = writer.FileName();\n VerifyFile(filename);\n}\n\nTEST(EventWriter, WriteDelete) {\n string file_prefix = GetDirName(\"\/writedelete_test\");\n EventsWriter* writer = new EventsWriter(file_prefix);\n WriteFile(writer);\n string filename = writer->FileName();\n delete writer;\n VerifyFile(filename);\n}\n\nTEST(EventWriter, FailFlush) {\n string file_prefix = GetDirName(\"\/failflush_test\");\n EventsWriter writer(file_prefix);\n string filename = writer.FileName();\n WriteFile(&writer);\n EXPECT_TRUE(env()->FileExists(filename));\n env()->DeleteFile(filename);\n EXPECT_FALSE(env()->FileExists(filename));\n EXPECT_FALSE(writer.Flush());\n EXPECT_FALSE(env()->FileExists(filename));\n}\n\nTEST(EventWriter, FailClose) {\n string file_prefix = GetDirName(\"\/failclose_test\");\n EventsWriter writer(file_prefix);\n string filename = writer.FileName();\n WriteFile(&writer);\n EXPECT_TRUE(env()->FileExists(filename));\n env()->DeleteFile(filename);\n EXPECT_FALSE(env()->FileExists(filename));\n EXPECT_FALSE(writer.Close());\n EXPECT_FALSE(env()->FileExists(filename));\n}\n\nTEST(EventWriter, InitWriteClose) {\n string file_prefix = GetDirName(\"\/initwriteclose_test\");\n EventsWriter writer(file_prefix);\n EXPECT_TRUE(writer.Init());\n string filename0 = writer.FileName();\n EXPECT_TRUE(env()->FileExists(filename0));\n WriteFile(&writer);\n EXPECT_TRUE(writer.Close());\n string filename1 = writer.FileName();\n EXPECT_EQ(filename0, filename1);\n VerifyFile(filename1);\n}\n\nTEST(EventWriter, NameWriteClose) {\n string file_prefix = GetDirName(\"\/namewriteclose_test\");\n EventsWriter writer(file_prefix);\n string filename = writer.FileName();\n EXPECT_TRUE(env()->FileExists(filename));\n WriteFile(&writer);\n EXPECT_TRUE(writer.Close());\n VerifyFile(filename);\n}\n\nTEST(EventWriter, NameClose) {\n string file_prefix = GetDirName(\"\/nameclose_test\");\n EventsWriter writer(file_prefix);\n string filename = writer.FileName();\n EXPECT_TRUE(writer.Close());\n EXPECT_TRUE(env()->FileExists(filename));\n env()->DeleteFile(filename);\n}\n\nTEST(EventWriter, FileDeletionBeforeWriting) {\n string file_prefix = GetDirName(\"\/fdbw_test\");\n EventsWriter writer(file_prefix);\n string filename0 = writer.FileName();\n EXPECT_TRUE(env()->FileExists(filename0));\n env()->SleepForMicroseconds(\n 2000000); \/\/ To make sure timestamp part of filename will differ.\n env()->DeleteFile(filename0);\n EXPECT_TRUE(writer.Init()); \/\/ Init should reopen file.\n WriteFile(&writer);\n EXPECT_TRUE(writer.Flush());\n string filename1 = writer.FileName();\n EXPECT_NE(filename0, filename1);\n VerifyFile(filename1);\n}\n\n} \/\/ namespace\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008-2014 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)\n *\n * This file is part of coinpp.\n *\n * coinpp is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see 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 Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <iostream>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <database\/entry.hpp>\n#include <database\/logger.hpp>\n#include <database\/query.hpp>\n#include <database\/storage.hpp>\n#include <database\/utility.hpp>\n\nusing namespace database;\n\nstorage::storage(boost::asio::io_service & ios)\n : io_service_(ios)\n , strand_(ios)\n , timer_(ios)\n{\n \/\/ ...\n}\n\nvoid storage::start()\n{\n \/**\n * Start the expire timer.\n *\/\n timer_.expires_from_now(std::chrono::seconds(5));\n timer_.async_wait(\n strand_.wrap(std::bind(&storage::tick, this, std::placeholders::_1))\n );\n}\n\nvoid storage::stop()\n{\n \/**\n * Cancel the timer.\n *\/\n timer_.cancel();\n \n std::lock_guard<std::recursive_mutex> l(mutex_);\n \n auto it = m_entries.begin();\n \n while (it != m_entries.end())\n {\n if (*it)\n {\n (*it)->stop();\n }\n else\n {\n \/\/ ...\n }\n \n it = m_entries.erase(it);\n }\n}\n\nvoid storage::store(const std::shared_ptr<entry> e)\n{\n \/**\n * Allocate the query.\n *\/\n query q(e->query_string());\n \n for (auto & i : q.pairs())\n {\n if (utility::string::starts_with(i.first, \"_\"))\n {\n continue;\n }\n \n e->pairs().insert(std::make_pair(i.first, i.second));\n }\n \n std::lock_guard<std::recursive_mutex> l(mutex_);\n \n auto it = m_entries.begin();\n\n for (; it != m_entries.end();)\n {\n auto index1 = 0, index2 = 0;\n \n std::string qs1, qs2;\n \n auto it1 = e->pairs().begin();\n \n for (; it1 != e->pairs().end(); ++it1)\n {\n if (utility::string::starts_with(it1->first, \"_\"))\n {\n index1++;\n \n continue;\n }\n \n qs1 += it1->first + \"=\" + it1->second;\n\n if (index1++ < (e->pairs().size() - 1))\n {\n qs1.append(\"&\", strlen(\"&\"));\n }\n }\n \n auto it2 = (*it)->pairs().begin();\n \n for (; it2 != (*it)->pairs().end(); ++it2)\n {\n if (utility::string::starts_with(it2->first, \"_\"))\n {\n index2++;\n \n continue;\n }\n \n qs2 += it2->first + \"=\" + it2->second;\n \n if (index2++ < ((*it)->pairs().size() - 1))\n {\n qs2.append(\"&\", strlen(\"&\"));\n }\n }\n \n if (boost::iequals(qs1, qs2))\n {\n \/**\n * Copy the timestamp from the older entry.\n *\/\n e->set_timestamp((*it)->timestamp());\n \n \/**\n * Stop the older entry.\n *\/\n (*it)->stop();\n \n \/**\n * Erase the older entry.\n *\/\n it = m_entries.erase(it);\n \n \/**\n * Because of this logic there shouldn't be any more matches.\n *\/\n break;\n }\n else\n {\n ++it;\n }\n }\n\n \/**\n * Insert the entry.\n *\/\n m_entries.push_back(e);\n \n \/**\n * Start the entry.\n *\/\n e->start();\n}\n\nconst std::vector< std::shared_ptr<entry> > storage::find(\n const std::string & query_string\n )\n{\n std::lock_guard<std::recursive_mutex> l(mutex_);\n\n std::vector< std::shared_ptr<entry> > ret;\n\n \/**\n * Allocate the query.\n *\/\n query q(query_string);\n\n for (auto & i : m_entries)\n {\n bool matches = true;\n \n for (auto & j : q.pairs())\n {\n if (utility::string::starts_with(j.first, \"_\"))\n {\n continue;\n }\n \n \/**\n * Make sure the each key from the query is found in the entry, \n * otherwise it is a record mismatch.\n *\/\n bool found = false;\n \n for (auto & k : i->pairs())\n {\n if (boost::iequals(j.first, k.first))\n {\n found = true;\n break;\n }\n }\n \n if (!found)\n {\n matches = false;\n break;\n }\n \n for (auto & k : i->pairs())\n {\n \/\/log_debug(j.first << \":\" << k.first);\n \n if (utility::string::starts_with(k.first, \"_\"))\n {\n continue;\n }\n\n \/\/ key == key\n if (boost::iequals(j.first, k.first))\n {\n log_debug(j.second << \":\" << k.second);\n \n \/\/matches |= boost::iequals(j.second, k.second);\n \n \/\/ value == value\n if (boost::iequals(j.second, k.second))\n {\n \/\/matches = true;\n }\n else\n {\n matches = false;\n }\n \n log_debug(\"matches = \" << matches);\n }\n \n if (!matches)\n {\n break;\n }\n }\n }\n \n if (matches\/* && !mismatch*\/)\n {\n log_debug(\"Insert result= \" << i->query_string());\n \n ret.push_back(i);\n }\n }\n\n return ret;\n}\n\nvoid storage::tick(const boost::system::error_code & ec)\n{\n if (ec)\n {\n \/\/ ...\n }\n else\n {\n std::lock_guard<std::recursive_mutex> l(mutex_);\n\n auto it = m_entries.begin();\n \n while (it != m_entries.end())\n {\n if (*it && (*it)->expired())\n {\n log_debug(\"Entry \" << (*it)->query_string() << \" expired.\");\n \n (*it)->stop();\n \n it = m_entries.erase(it);\n }\n else if (*it)\n {\n ++it;\n }\n else\n {\n it = m_entries.erase(it);\n }\n }\n \n \/**\n * Start the expire timer.\n *\/\n timer_.expires_from_now(std::chrono::seconds(5));\n timer_.async_wait(\n strand_.wrap(std::bind(&storage::tick, this,\n std::placeholders::_1))\n );\n }\n}\n\nconst std::vector< std::shared_ptr<entry> > & storage::entries() const\n{\n return m_entries;\n}\n\nint storage::run_test()\n{\n std::vector<std::string> pairs1;\n \n boost::split(pairs1, \"fruit=apple&color=red\", boost::is_any_of(\"&\"));\n\n std::cerr << pairs1.size() << std::endl;\n \n assert(pairs1.size() == 2);\n \n std::map<std::string, std::string> pairs3;\n \n for (auto & i : pairs1)\n {\n std::vector<std::string> pairs2;\n \n boost::split(pairs2, i, boost::is_any_of(\"=\"));\n \n pairs3[pairs2[0]] = pairs2[1];\n }\n \n std::cerr << pairs3.size() << std::endl;\n \n assert(pairs3.size() == 2);\n \n for (auto & i : pairs3)\n {\n std::cerr << i.first << std::endl;\n std::cerr << i.second << std::endl;\n }\n\n return 0;\n}\n<commit_msg>Cleanup old code.<commit_after>\/*\n * Copyright (c) 2008-2014 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)\n *\n * This file is part of coinpp.\n *\n * coinpp is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see 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 Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <iostream>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <database\/entry.hpp>\n#include <database\/logger.hpp>\n#include <database\/query.hpp>\n#include <database\/storage.hpp>\n#include <database\/utility.hpp>\n\nusing namespace database;\n\nstorage::storage(boost::asio::io_service & ios)\n : io_service_(ios)\n , strand_(ios)\n , timer_(ios)\n{\n \/\/ ...\n}\n\nvoid storage::start()\n{\n \/**\n * Start the expire timer.\n *\/\n timer_.expires_from_now(std::chrono::seconds(5));\n timer_.async_wait(\n strand_.wrap(std::bind(&storage::tick, this, std::placeholders::_1))\n );\n}\n\nvoid storage::stop()\n{\n \/**\n * Cancel the timer.\n *\/\n timer_.cancel();\n \n std::lock_guard<std::recursive_mutex> l(mutex_);\n \n auto it = m_entries.begin();\n \n while (it != m_entries.end())\n {\n if (*it)\n {\n (*it)->stop();\n }\n else\n {\n \/\/ ...\n }\n \n it = m_entries.erase(it);\n }\n}\n\nvoid storage::store(const std::shared_ptr<entry> e)\n{\n \/**\n * Allocate the query.\n *\/\n query q(e->query_string());\n \n for (auto & i : q.pairs())\n {\n if (utility::string::starts_with(i.first, \"_\"))\n {\n continue;\n }\n \n e->pairs().insert(std::make_pair(i.first, i.second));\n }\n \n std::lock_guard<std::recursive_mutex> l(mutex_);\n \n auto it = m_entries.begin();\n\n for (; it != m_entries.end();)\n {\n auto index1 = 0, index2 = 0;\n \n std::string qs1, qs2;\n \n auto it1 = e->pairs().begin();\n \n for (; it1 != e->pairs().end(); ++it1)\n {\n if (utility::string::starts_with(it1->first, \"_\"))\n {\n index1++;\n \n continue;\n }\n \n qs1 += it1->first + \"=\" + it1->second;\n\n if (index1++ < (e->pairs().size() - 1))\n {\n qs1.append(\"&\", strlen(\"&\"));\n }\n }\n \n auto it2 = (*it)->pairs().begin();\n \n for (; it2 != (*it)->pairs().end(); ++it2)\n {\n if (utility::string::starts_with(it2->first, \"_\"))\n {\n index2++;\n \n continue;\n }\n \n qs2 += it2->first + \"=\" + it2->second;\n \n if (index2++ < ((*it)->pairs().size() - 1))\n {\n qs2.append(\"&\", strlen(\"&\"));\n }\n }\n \n if (boost::iequals(qs1, qs2))\n {\n \/**\n * Copy the timestamp from the older entry.\n *\/\n e->set_timestamp((*it)->timestamp());\n \n \/**\n * Stop the older entry.\n *\/\n (*it)->stop();\n \n \/**\n * Erase the older entry.\n *\/\n it = m_entries.erase(it);\n \n \/**\n * Because of this logic there shouldn't be any more matches.\n *\/\n break;\n }\n else\n {\n ++it;\n }\n }\n\n \/**\n * Insert the entry.\n *\/\n m_entries.push_back(e);\n \n \/**\n * Start the entry.\n *\/\n e->start();\n}\n\nconst std::vector< std::shared_ptr<entry> > storage::find(\n const std::string & query_string\n )\n{\n std::lock_guard<std::recursive_mutex> l(mutex_);\n\n std::vector< std::shared_ptr<entry> > ret;\n\n \/**\n * Allocate the query.\n *\/\n query q(query_string);\n\n for (auto & i : m_entries)\n {\n bool matches = true;\n \n for (auto & j : q.pairs())\n {\n if (utility::string::starts_with(j.first, \"_\"))\n {\n continue;\n }\n \n \/**\n * Make sure the each key from the query is found in the entry, \n * otherwise it is a record mismatch.\n *\/\n bool found = false;\n \n for (auto & k : i->pairs())\n {\n if (boost::iequals(j.first, k.first))\n {\n found = true;\n break;\n }\n }\n \n if (!found)\n {\n matches = false;\n break;\n }\n \n for (auto & k : i->pairs())\n {\n \/\/log_debug(j.first << \":\" << k.first);\n \n if (utility::string::starts_with(k.first, \"_\"))\n {\n continue;\n }\n\n if (boost::iequals(j.first, k.first))\n {\n log_debug(j.second << \":\" << k.second);\n\n if (boost::iequals(j.second, k.second))\n {\n\n }\n else\n {\n matches = false;\n }\n \n log_debug(\"matches = \" << matches);\n }\n \n if (!matches)\n {\n break;\n }\n }\n }\n \n if (matches)\n {\n log_debug(\"Insert result= \" << i->query_string());\n \n ret.push_back(i);\n }\n }\n\n return ret;\n}\n\nvoid storage::tick(const boost::system::error_code & ec)\n{\n if (ec)\n {\n \/\/ ...\n }\n else\n {\n std::lock_guard<std::recursive_mutex> l(mutex_);\n\n auto it = m_entries.begin();\n \n while (it != m_entries.end())\n {\n if (*it && (*it)->expired())\n {\n log_debug(\"Entry \" << (*it)->query_string() << \" expired.\");\n \n (*it)->stop();\n \n it = m_entries.erase(it);\n }\n else if (*it)\n {\n ++it;\n }\n else\n {\n it = m_entries.erase(it);\n }\n }\n \n \/**\n * Start the expire timer.\n *\/\n timer_.expires_from_now(std::chrono::seconds(5));\n timer_.async_wait(\n strand_.wrap(std::bind(&storage::tick, this,\n std::placeholders::_1))\n );\n }\n}\n\nconst std::vector< std::shared_ptr<entry> > & storage::entries() const\n{\n return m_entries;\n}\n\nint storage::run_test()\n{\n std::vector<std::string> pairs1;\n \n boost::split(pairs1, \"fruit=apple&color=red\", boost::is_any_of(\"&\"));\n\n std::cerr << pairs1.size() << std::endl;\n \n assert(pairs1.size() == 2);\n \n std::map<std::string, std::string> pairs3;\n \n for (auto & i : pairs1)\n {\n std::vector<std::string> pairs2;\n \n boost::split(pairs2, i, boost::is_any_of(\"=\"));\n \n pairs3[pairs2[0]] = pairs2[1];\n }\n \n std::cerr << pairs3.size() << std::endl;\n \n assert(pairs3.size() == 2);\n \n for (auto & i : pairs3)\n {\n std::cerr << i.first << std::endl;\n std::cerr << i.second << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"webkit\/glue\/plugins\/pepper_device_context_2d.h\"\n\n#include \"base\/logging.h\"\n#include \"gfx\/point.h\"\n#include \"gfx\/rect.h\"\n#include \"skia\/ext\/platform_canvas.h\"\n#include \"third_party\/ppapi\/c\/pp_module.h\"\n#include \"third_party\/ppapi\/c\/pp_rect.h\"\n#include \"third_party\/ppapi\/c\/pp_resource.h\"\n#include \"third_party\/ppapi\/c\/ppb_device_context_2d.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"webkit\/glue\/plugins\/pepper_image_data.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_module.h\"\n#include \"webkit\/glue\/plugins\/pepper_resource_tracker.h\"\n\n#if defined(OS_MACOSX)\n#include \"base\/mac_util.h\"\n#include \"base\/scoped_cftyperef.h\"\n#endif\n\nnamespace pepper {\n\nnamespace {\n\nPP_Resource Create(PP_Module module_id, int32_t width, int32_t height) {\n PluginModule* module = PluginModule::FromPPModule(module_id);\n if (!module)\n return NullPPResource();\n\n scoped_refptr<DeviceContext2D> context(new DeviceContext2D(module));\n if (!context->Init(width, height))\n return NullPPResource();\n context->AddRef(); \/\/ AddRef for the caller.\n return context->GetResource();\n}\n\nvoid PaintImageData(PP_Resource device_context,\n PP_Resource image,\n int32_t x, int32_t y,\n const PP_Rect* dirty,\n uint32_t dirty_rect_count,\n PPB_DeviceContext2D_PaintCallback callback,\n void* callback_data) {\n scoped_refptr<Resource> device_resource =\n ResourceTracker::Get()->GetResource(device_context);\n if (!device_resource.get())\n return;\n DeviceContext2D* context = device_resource->AsDeviceContext2D();\n if (!context)\n return;\n context->PaintImageData(image, x, y, dirty, dirty_rect_count,\n callback, callback_data);\n}\n\nconst PPB_DeviceContext2D ppb_devicecontext2d = {\n &Create,\n &PaintImageData,\n};\n\n} \/\/ namespace\n\nDeviceContext2D::DeviceContext2D(PluginModule* module) : Resource(module) {\n}\n\nDeviceContext2D::~DeviceContext2D() {\n}\n\n\/\/ static\nconst PPB_DeviceContext2D* DeviceContext2D::GetInterface() {\n return &ppb_devicecontext2d;\n}\n\nbool DeviceContext2D::Init(int width, int height) {\n image_data_.reset(new ImageData(module()));\n if (!image_data_->Init(PP_IMAGEDATAFORMAT_BGRA_PREMUL, width, height) ||\n !image_data_->Map()) {\n image_data_.reset();\n return false;\n }\n\n return true;\n}\n\nvoid DeviceContext2D::PaintImageData(PP_Resource image,\n int32_t x, int32_t y,\n const PP_Rect* dirty,\n uint32_t dirty_rect_count,\n PPB_DeviceContext2D_PaintCallback callback,\n void* callback_data) {\n scoped_refptr<Resource> image_resource =\n ResourceTracker::Get()->GetResource(image);\n if (!image_resource.get())\n return;\n ImageData* new_image_data = image_resource->AsImageData();\n if (!new_image_data)\n return;\n\n const SkBitmap& new_image_bitmap = new_image_data->GetMappedBitmap();\n\n \/\/ TODO(brettw) handle multiple dirty rects.\n DCHECK(dirty_rect_count == 1);\n\n \/\/ Draw the bitmap to the backing store.\n SkIRect src_rect;\n if (dirty->point.x == 0 && dirty->point.y == 0 &&\n dirty->size.width == 0 && dirty->size.height == 0) {\n \/\/ Default to the entire bitmap.\n src_rect.fLeft = 0;\n src_rect.fTop = 0;\n src_rect.fRight = new_image_bitmap.width();\n src_rect.fBottom = new_image_bitmap.height();\n } else {\n src_rect.fLeft = dirty->point.x;\n src_rect.fTop = dirty->point.y;\n src_rect.fRight = dirty->point.x + dirty->size.width;\n src_rect.fBottom = dirty->point.y + dirty->size.height;\n }\n SkRect dest_rect = { SkIntToScalar(src_rect.fLeft),\n SkIntToScalar(src_rect.fTop),\n SkIntToScalar(src_rect.fRight),\n SkIntToScalar(src_rect.fBottom) };\n\n \/\/ We're guaranteed to have a mapped canvas since we mapped it in Init().\n skia::PlatformCanvas* backing_canvas = image_data_->mapped_canvas();\n\n \/\/ We want to replace the contents of the bitmap rather than blend.\n SkPaint paint;\n paint.setXfermodeMode(SkXfermode::kSrc_Mode);\n backing_canvas->drawBitmapRect(new_image_bitmap,\n &src_rect, dest_rect, &paint);\n\n \/\/ TODO(brettw) implement invalidate and callbacks!\n\n \/\/ Cause the updated part of the screen to be repainted. This will happen\n \/\/ asynchronously.\n \/*\n gfx::Rect dest_gfx_rect(dirty->left, dirty->top,\n dirty->right - dirty->left,\n dirty->bottom - dirty->top);\n\n plugin_delegate_->instance()->webplugin()->InvalidateRect(dest_gfx_rect);\n\n \/\/ Save the callback to execute later. See |unpainted_flush_callbacks_| in\n \/\/ the header file.\n if (callback) {\n unpainted_flush_callbacks_.push_back(\n FlushCallbackData(callback, id, context, user_data));\n }\n*\/\n}\n\nvoid DeviceContext2D::Paint(WebKit::WebCanvas* canvas,\n const gfx::Rect& plugin_rect,\n const gfx::Rect& paint_rect) {\n \/\/ We're guaranteed to have a mapped canvas since we mapped it in Init().\n const SkBitmap& backing_bitmap = image_data_->GetMappedBitmap();\n\n#if defined(OS_MACOSX)\n SkAutoLockPixels lock(backing_bitmap);\n\n scoped_cftyperef<CGDataProviderRef> data_provider(\n CGDataProviderCreateWithData(\n NULL, backing_bitmap.getAddr32(0, 0),\n backing_bitmap.rowBytes() * backing_bitmap.height(), NULL));\n scoped_cftyperef<CGImageRef> image(\n CGImageCreate(\n backing_bitmap.width(), backing_bitmap.height(),\n 8, 32, backing_bitmap.rowBytes(),\n mac_util::GetSystemColorSpace(),\n kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host,\n data_provider, NULL, false, kCGRenderingIntentDefault));\n\n \/\/ Flip the transform\n CGContextSaveGState(canvas);\n float window_height = static_cast<float>(CGBitmapContextGetHeight(canvas));\n CGContextTranslateCTM(canvas, 0, window_height);\n CGContextScaleCTM(canvas, 1.0, -1.0);\n\n CGRect bounds;\n bounds.origin.x = plugin_rect.origin().x();\n bounds.origin.y = window_height - plugin_rect.origin().y() -\n backing_bitmap.height();\n bounds.size.width = backing_bitmap.width();\n bounds.size.height = backing_bitmap.height();\n\n CGContextDrawImage(canvas, bounds, image);\n CGContextRestoreGState(canvas);\n#else\n gfx::Point origin(plugin_rect.origin().x(), plugin_rect.origin().y());\n canvas->drawBitmap(backing_bitmap,\n SkIntToScalar(plugin_rect.origin().x()),\n SkIntToScalar(plugin_rect.origin().y()));\n#endif\n}\n\n} \/\/ namespace pepper\n<commit_msg>Update NULL rect handling. I updated the API but forgot to change the Chrome side, resulting in a crash when you try to paint the entire plugin.<commit_after>\/\/ Copyright (c) 2010 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 \"webkit\/glue\/plugins\/pepper_device_context_2d.h\"\n\n#include \"base\/logging.h\"\n#include \"gfx\/point.h\"\n#include \"gfx\/rect.h\"\n#include \"skia\/ext\/platform_canvas.h\"\n#include \"third_party\/ppapi\/c\/pp_module.h\"\n#include \"third_party\/ppapi\/c\/pp_rect.h\"\n#include \"third_party\/ppapi\/c\/pp_resource.h\"\n#include \"third_party\/ppapi\/c\/ppb_device_context_2d.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"webkit\/glue\/plugins\/pepper_image_data.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_module.h\"\n#include \"webkit\/glue\/plugins\/pepper_resource_tracker.h\"\n\n#if defined(OS_MACOSX)\n#include \"base\/mac_util.h\"\n#include \"base\/scoped_cftyperef.h\"\n#endif\n\nnamespace pepper {\n\nnamespace {\n\nPP_Resource Create(PP_Module module_id, int32_t width, int32_t height) {\n PluginModule* module = PluginModule::FromPPModule(module_id);\n if (!module)\n return NullPPResource();\n\n scoped_refptr<DeviceContext2D> context(new DeviceContext2D(module));\n if (!context->Init(width, height))\n return NullPPResource();\n context->AddRef(); \/\/ AddRef for the caller.\n return context->GetResource();\n}\n\nvoid PaintImageData(PP_Resource device_context,\n PP_Resource image,\n int32_t x, int32_t y,\n const PP_Rect* dirty,\n uint32_t dirty_rect_count,\n PPB_DeviceContext2D_PaintCallback callback,\n void* callback_data) {\n scoped_refptr<Resource> device_resource =\n ResourceTracker::Get()->GetResource(device_context);\n if (!device_resource.get())\n return;\n DeviceContext2D* context = device_resource->AsDeviceContext2D();\n if (!context)\n return;\n context->PaintImageData(image, x, y, dirty, dirty_rect_count,\n callback, callback_data);\n}\n\nconst PPB_DeviceContext2D ppb_devicecontext2d = {\n &Create,\n &PaintImageData,\n};\n\n} \/\/ namespace\n\nDeviceContext2D::DeviceContext2D(PluginModule* module) : Resource(module) {\n}\n\nDeviceContext2D::~DeviceContext2D() {\n}\n\n\/\/ static\nconst PPB_DeviceContext2D* DeviceContext2D::GetInterface() {\n return &ppb_devicecontext2d;\n}\n\nbool DeviceContext2D::Init(int width, int height) {\n image_data_.reset(new ImageData(module()));\n if (!image_data_->Init(PP_IMAGEDATAFORMAT_BGRA_PREMUL, width, height) ||\n !image_data_->Map()) {\n image_data_.reset();\n return false;\n }\n\n return true;\n}\n\nvoid DeviceContext2D::PaintImageData(PP_Resource image,\n int32_t x, int32_t y,\n const PP_Rect* dirty,\n uint32_t dirty_rect_count,\n PPB_DeviceContext2D_PaintCallback callback,\n void* callback_data) {\n scoped_refptr<Resource> image_resource =\n ResourceTracker::Get()->GetResource(image);\n if (!image_resource.get())\n return;\n ImageData* new_image_data = image_resource->AsImageData();\n if (!new_image_data)\n return;\n\n const SkBitmap& new_image_bitmap = new_image_data->GetMappedBitmap();\n\n \/\/ TODO(brettw) handle multiple dirty rects.\n DCHECK(dirty_rect_count <= 1);\n\n \/\/ Draw the bitmap to the backing store.\n SkIRect src_rect;\n if (dirty_rect_count == 0 || !dirty) {\n \/\/ Default to the entire bitmap.\n src_rect.fLeft = 0;\n src_rect.fTop = 0;\n src_rect.fRight = new_image_bitmap.width();\n src_rect.fBottom = new_image_bitmap.height();\n } else {\n src_rect.fLeft = dirty->point.x;\n src_rect.fTop = dirty->point.y;\n src_rect.fRight = dirty->point.x + dirty->size.width;\n src_rect.fBottom = dirty->point.y + dirty->size.height;\n }\n SkRect dest_rect = { SkIntToScalar(src_rect.fLeft),\n SkIntToScalar(src_rect.fTop),\n SkIntToScalar(src_rect.fRight),\n SkIntToScalar(src_rect.fBottom) };\n\n \/\/ We're guaranteed to have a mapped canvas since we mapped it in Init().\n skia::PlatformCanvas* backing_canvas = image_data_->mapped_canvas();\n\n \/\/ We want to replace the contents of the bitmap rather than blend.\n SkPaint paint;\n paint.setXfermodeMode(SkXfermode::kSrc_Mode);\n backing_canvas->drawBitmapRect(new_image_bitmap,\n &src_rect, dest_rect, &paint);\n\n \/\/ TODO(brettw) implement invalidate and callbacks!\n\n \/\/ Cause the updated part of the screen to be repainted. This will happen\n \/\/ asynchronously.\n \/*\n gfx::Rect dest_gfx_rect(dirty->left, dirty->top,\n dirty->right - dirty->left,\n dirty->bottom - dirty->top);\n\n plugin_delegate_->instance()->webplugin()->InvalidateRect(dest_gfx_rect);\n\n \/\/ Save the callback to execute later. See |unpainted_flush_callbacks_| in\n \/\/ the header file.\n if (callback) {\n unpainted_flush_callbacks_.push_back(\n FlushCallbackData(callback, id, context, user_data));\n }\n*\/\n}\n\nvoid DeviceContext2D::Paint(WebKit::WebCanvas* canvas,\n const gfx::Rect& plugin_rect,\n const gfx::Rect& paint_rect) {\n \/\/ We're guaranteed to have a mapped canvas since we mapped it in Init().\n const SkBitmap& backing_bitmap = image_data_->GetMappedBitmap();\n\n#if defined(OS_MACOSX)\n SkAutoLockPixels lock(backing_bitmap);\n\n scoped_cftyperef<CGDataProviderRef> data_provider(\n CGDataProviderCreateWithData(\n NULL, backing_bitmap.getAddr32(0, 0),\n backing_bitmap.rowBytes() * backing_bitmap.height(), NULL));\n scoped_cftyperef<CGImageRef> image(\n CGImageCreate(\n backing_bitmap.width(), backing_bitmap.height(),\n 8, 32, backing_bitmap.rowBytes(),\n mac_util::GetSystemColorSpace(),\n kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host,\n data_provider, NULL, false, kCGRenderingIntentDefault));\n\n \/\/ Flip the transform\n CGContextSaveGState(canvas);\n float window_height = static_cast<float>(CGBitmapContextGetHeight(canvas));\n CGContextTranslateCTM(canvas, 0, window_height);\n CGContextScaleCTM(canvas, 1.0, -1.0);\n\n CGRect bounds;\n bounds.origin.x = plugin_rect.origin().x();\n bounds.origin.y = window_height - plugin_rect.origin().y() -\n backing_bitmap.height();\n bounds.size.width = backing_bitmap.width();\n bounds.size.height = backing_bitmap.height();\n\n CGContextDrawImage(canvas, bounds, image);\n CGContextRestoreGState(canvas);\n#else\n gfx::Point origin(plugin_rect.origin().x(), plugin_rect.origin().y());\n canvas->drawBitmap(backing_bitmap,\n SkIntToScalar(plugin_rect.origin().x()),\n SkIntToScalar(plugin_rect.origin().y()));\n#endif\n}\n\n} \/\/ namespace pepper\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode: c++; coding: utf-8 -*-\n#pragma once\n#ifndef IOSTR_HPP_\n#define IOSTR_HPP_\n\n#include <cstring>\n#include <cerrno>\n#include <cassert>\n#include <cstdarg>\n#include <ctime>\n\n#include <stdexcept>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\n#include <string>\n#include <vector>\n#include <map>\n#include <unordered_map>\n#include <set>\n#include <algorithm>\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\/\/ prior declaration\n\nnamespace wtl {\ntemplate <class T> extern\nstd::string str_join(const T& v,\n const std::string& sep=\",\",\n const unsigned int digits=std::cout.precision(),\n const bool fixed=false);\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\/\/ global operator<< for containers\n\ntemplate <class T> inline\nstd::ostream& operator<< (std::ostream& ost, const std::vector<T>& v) {\n return ost << '[' << wtl::str_join(v, \", \", ost.precision()) << ']';\n}\n\ntemplate <> inline\nstd::ostream& operator<< (std::ostream& ost, const std::vector<std::string>& v) {\n if (v.empty()) {return ost << \"[]\";}\n return ost << \"['\" << wtl::str_join(v, \"', '\") << \"']\";\n}\n\ntemplate <class T> inline\nstd::ostream& operator<< (std::ostream& ost, const std::set<T>& v) {\n return ost << \"set([\" << wtl::str_join(v, \", \", ost.precision()) << \"])\";\n}\n\ntemplate <class F, class S> inline\nstd::ostream& operator<< (std::ostream& ost, const std::pair<F, S>& p) {\n return ost << '(' << std::get<0>(p)\n << \": \" << std::get<1>(p) << ')';\n}\n\nnamespace wtl { namespace detail {\n template <class Map> inline\n std::ostream& operator_ost_map(std::ostream& ost, const Map& m) {\n ost << '{';\n if (!m.empty()) {\n auto it(begin(m));\n ost << std::get<0>(*it) << \": \" << std::get<1>(*it);\n while (++it != end(m)) {\n ost << \", \" << std::get<0>(*it) << \": \" << std::get<1>(*it);\n }\n }\n return ost << '}';\n }\n}} \/\/ namespace\n\n\/\/ map\ntemplate <class Key, class T, class Comp> inline\nstd::ostream& operator<< (std::ostream& ost, const std::map<Key, T, Comp>& m) {\n return wtl::detail::operator_ost_map(ost, m);\n}\n\n\/\/ unordered_map\ntemplate <class Key, class T, class Hash> inline\nstd::ostream& operator<< (std::ostream& ost, const std::unordered_map<Key, T, Hash>& m) {\n return wtl::detail::operator_ost_map(ost, m);\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\nnamespace wtl {\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\nstruct identity {\n template<class T>\n constexpr T operator()(T&& x) const noexcept {\n return std::forward<T>(x);\n }\n};\n\ntemplate <class Iter, class Func=identity> inline\nstd::ostream& ost_join(std::ostream& ost, Iter begin_, const Iter end_,\n const std::string& sep=\",\", Func func=Func()) {\n if (begin_ == end_) return ost;\n ost << func(*begin_);\n while (++begin_ != end_) {ost << sep << func(*begin_);}\n return ost;\n}\n\ntemplate <class T, class Func=identity> inline\nstd::ostream& ost_join(std::ostream& ost, const T& v,\n const std::string& sep=\",\", Func func=Func()) {\n return ost_join(ost, begin(v), end(v), sep, func);\n}\n\ntemplate <class Iter, class Func=identity> inline\nstd::string oss_join(Iter begin_, const Iter end_, const std::string& sep=\",\", Func func=Func()) {\n std::ostringstream oss;\n ost_join(oss, begin_, end_, sep, func);\n return oss.str();\n}\n\ntemplate <class T, class Func=identity> inline\nstd::string oss_join(const T& v, const std::string& sep=\",\", Func func=Func()) {\n std::ostringstream oss;\n ost_join(oss, v, sep, func);\n return oss.str();\n}\n\ntemplate <class Iter> inline\nstd::string str_join(Iter begin_, const Iter end_, const std::string& sep=\",\",\n const unsigned int digits=std::cout.precision(), const bool fixed=false) {\n if (begin_ == end_) return \"\";\n std::ostringstream oss;\n oss.precision(digits);\n if (fixed) {oss << std::fixed;}\n oss << *begin_;\n while (++begin_ != end_) {oss << sep << *begin_;}\n return oss.str();\n}\n\ntemplate <class T> inline\nstd::string str_join(const T& v, const std::string& sep,\n const unsigned int digits, const bool fixed) {\n return str_join(begin(v), end(v), sep, digits, fixed);\n}\n\ntemplate <class T> inline\nstd::string str_matrix(const T& m, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n std::string s;\n for (const auto& row: m) {\n s += str_join(row, sep, digits);\n s += '\\n';\n }\n return s;\n}\n\ntemplate <class T> inline\nstd::string str_map(const T& m, const unsigned int digits=std::cout.precision()) {\n std::ostringstream oss;\n oss.precision(digits);\n oss << m;\n return oss.str();\n}\n\ntemplate <int N, class Iter> inline\nstd::string str_pairs(Iter begin_, const Iter end_, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n if (begin_ == end_) return \"\";\n std::ostringstream oss;\n oss.precision(digits);\n oss << std::get<N>(*begin_);\n while (++begin_ != end_) {oss << sep << std::get<N>(*begin_);}\n return oss.str();\n}\ntemplate <int N, class Map> inline\nstd::string str_pairs(const Map& m, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n return str_pairs<N>(begin(m), end(m), sep, digits);\n}\n\ntemplate <class Map> inline\nstd::string str_pair_rows(const Map& m, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n std::string s = str_pairs<0>(m, sep, digits);\n s += '\\n';\n s += str_pairs<1>(m, sep, digits);\n return s += '\\n';\n}\n\ntemplate <class Map> inline\nstd::string str_pair_cols(const Map& m, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n std::ostringstream oss;\n oss.precision(digits);\n for (const auto& p: m) {\n oss << std::get<0>(p) << sep << std::get<1>(p) << '\\n';\n }\n return oss.str();\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\/\/ std::string manipulation\n\ninline std::vector<std::string> split_algorithm(const std::string& src, const std::string& delimiter=\" \\t\\n\") {\n std::vector<std::string> dst;\n for (auto delim_pos=begin(src), start=delim_pos; delim_pos!=end(src); ) {\n delim_pos = std::find_first_of(start, end(src), begin(delimiter), end(delimiter));\n dst.push_back(std::string(start, delim_pos));\n ++(start = delim_pos);\n }\n return dst;\n}\n\ninline std::vector<std::string>\nsplit(const std::string& src, const std::string& delimiter=\" \\t\\n\") {\n std::vector<std::string> dst;\n size_t start = 0, offset = 0;\n while (true) {\n offset = src.find_first_of(delimiter, start);\n offset -= start;\n dst.push_back(src.substr(start, offset));\n start += offset;\n if (start == src.npos) break;\n ++start;\n }\n return dst;\n}\n\ninline std::string rstrip(std::string src, const std::string& chars=\" \") {\n size_t pos(src.find_last_not_of(chars));\n if (pos == std::string::npos) {\n src.clear();\n } else {\n src.erase(++pos);\n }\n return src;\n}\n\ninline std::string lstrip(std::string src, const std::string& chars=\" \") {\n const size_t pos(src.find_first_not_of(chars));\n if (pos == std::string::npos) {\n src.clear();\n } else {\n src.erase(0, pos);\n }\n return src;\n}\n\ninline std::string strip(std::string src, const std::string& chars=\" \") {\n return rstrip(lstrip(src, chars), chars);\n}\n\ninline bool startswith(const std::string& full, const std::string& sub) {\n const size_t full_size = full.size();\n const size_t sub_size = sub.size();\n if (full_size > sub_size) {\n return full.compare(0, sub_size, sub) == 0;\n } else {\n return false;\n }\n}\n\ninline bool endswith(const std::string& full, const std::string& sub) {\n const size_t full_size = full.size();\n const size_t sub_size = sub.size();\n if (full_size > sub_size) {\n return full.compare(full_size - sub_size, sub_size, sub) == 0;\n } else {\n return false;\n }\n}\n\ninline std::string replace_all(const std::string& patt, const std::string& repl, const std::string& src) {\n std::string result;\n std::string::size_type pos_before(0);\n std::string::size_type pos(0);\n std::string::size_type len(patt.size());\n while ((pos = src.find(patt, pos)) != std::string::npos) {\n result.append(src, pos_before, pos-pos_before);\n result.append(repl);\n pos += len;\n pos_before = pos;\n }\n result.append(src, pos_before, src.size()-pos_before);\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\ninline std::string strprintf(const char* const format, ...) {\n assert(format);\n va_list args;\n std::string buffer;\n va_start(args, format);\n const int length = std::vsnprintf(nullptr, 0, format, args) ;\n va_end(args);\n if (length < 0) throw std::runtime_error(format);\n buffer.resize(length + 1);\n va_start(args, format);\n const int result = std::vsnprintf(&buffer[0], length + 1, format, args);\n va_end(args);\n if (result < 0) throw std::runtime_error(format);\n buffer.pop_back();\n return buffer;\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n\/\/ default is the same as ctime(): Thu Aug 23 14:55:02 2001\n\/\/ which is equivalent to \"%a %b %d %T %Y\"\ninline std::string strftime(const std::string& format=\"%c\") {\n char cstr[80];\n const time_t rawtime = time(nullptr);\n const struct tm* t = localtime(&rawtime);\n std::strftime(cstr, sizeof(cstr), format.c_str(), t);\n return std::string(cstr);\n}\ninline std::string iso8601date(const std::string& sep=\"-\") {\n std::ostringstream oss;\n oss << \"%Y\" << sep << \"%m\" << sep << \"%d\";\n return strftime(oss.str());\n}\ninline std::string iso8601time(const std::string& sep=\":\") {\n std::ostringstream oss;\n oss << \"%H\" << sep << \"%M\" << sep << \"%S\";\n return strftime(oss.str());\n}\ninline std::string iso8601datetime() {return strftime(\"%FT%T%z\");}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\/\/ fstream wrapper for binary mode and exceptions\n\/\/ boost::serialization requires binary mode\n\nclass Fin: public std::ifstream {\n public:\n explicit Fin(const std::string& filepath,\n const std::ios::openmode mode=std::ios::in):\n std::ifstream(filepath.c_str(), mode | std::ios::binary)\n {exceptions(std::ios::badbit);}\n\n std::string readline(const char delimiter='\\n') {\n std::string buffer;\n std::getline(*this, buffer, delimiter);\n return buffer;\n }\n\n std::vector<std::string> readlines(const char delimiter='\\n') {\n std::vector<std::string> lines;\n std::string buffer;\n while (std::getline(*this, buffer, delimiter)) {\n lines.push_back(buffer);\n }\n return lines;\n }\n\n std::string read(const char delimiter='\\0') {return readline(delimiter);}\n};\n\nclass Fout: public std::ofstream {\n public:\n explicit Fout(const std::string& filepath,\n const std::ios::openmode mode=std::ios::out):\n std::ofstream(filepath.c_str(), mode | std::ios::binary)\n {exceptions(std::ios::failbit);}\n\n template <class Iter>\n Fout& writelines(Iter begin_, const Iter end_, const char sep='\\n') {\n if (begin_ == end_) return *this;\n *this << *begin_;\n while (++begin_ != end_) {*this << sep << *begin_;}\n return *this;\n }\n\n template <class V>\n Fout& writelines(const V& lines, const char sep='\\n') {\n return writelines(begin(lines), end(lines), sep);\n }\n};\n\ninline std::vector<std::pair<std::string, std::string> >\nread_ini(const std::string& filename) {\n std::vector<std::string> lines = Fin(filename).readlines();\n std::vector<std::pair<std::string, std::string> > dst;\n dst.reserve(lines.size());\n for (auto line_: lines) {\n line_ = strip(line_);\n if (startswith(line_, \"[\")) {continue;} \/\/ TODO\n auto pair_ = split(line_, \":=\"); \/\/ TODO\n if (pair_.size() < 2) {continue;}\n dst.emplace_back(rstrip(pair_[0]), lstrip(pair_[1]));\n }\n return dst;\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n} \/\/ namespace wtl\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n#endif \/* IOSTR_HPP_ *\/\n<commit_msg>Add operator<< for std::unordered_set<commit_after>\/\/ -*- mode: c++; coding: utf-8 -*-\n#pragma once\n#ifndef IOSTR_HPP_\n#define IOSTR_HPP_\n\n#include <cstring>\n#include <cerrno>\n#include <cassert>\n#include <cstdarg>\n#include <ctime>\n\n#include <stdexcept>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\n#include <string>\n#include <vector>\n#include <map>\n#include <unordered_map>\n#include <set>\n#include <unordered_set>\n#include <algorithm>\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\/\/ prior declaration\n\nnamespace wtl {\ntemplate <class T> extern\nstd::string str_join(const T& v,\n const std::string& sep=\",\",\n const unsigned int digits=std::cout.precision(),\n const bool fixed=false);\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\/\/ global operator<< for containers\n\ntemplate <class T> inline\nstd::ostream& operator<< (std::ostream& ost, const std::vector<T>& v) {\n return ost << '[' << wtl::str_join(v, \", \", ost.precision()) << ']';\n}\n\ntemplate <> inline\nstd::ostream& operator<< (std::ostream& ost, const std::vector<std::string>& v) {\n if (v.empty()) {return ost << \"[]\";}\n return ost << \"['\" << wtl::str_join(v, \"', '\") << \"']\";\n}\n\ntemplate <class T> inline\nstd::ostream& operator<< (std::ostream& ost, const std::set<T>& v) {\n return ost << \"set([\" << wtl::str_join(v, \", \", ost.precision()) << \"])\";\n}\n\ntemplate <class T> inline\nstd::ostream& operator<< (std::ostream& ost, const std::unordered_set<T>& v) {\n return ost << \"set([\" << wtl::str_join(v, \", \", ost.precision()) << \"])\";\n}\n\ntemplate <class F, class S> inline\nstd::ostream& operator<< (std::ostream& ost, const std::pair<F, S>& p) {\n return ost << '(' << std::get<0>(p)\n << \": \" << std::get<1>(p) << ')';\n}\n\nnamespace wtl { namespace detail {\n template <class Map> inline\n std::ostream& operator_ost_map(std::ostream& ost, const Map& m) {\n ost << '{';\n if (!m.empty()) {\n auto it(begin(m));\n ost << std::get<0>(*it) << \": \" << std::get<1>(*it);\n while (++it != end(m)) {\n ost << \", \" << std::get<0>(*it) << \": \" << std::get<1>(*it);\n }\n }\n return ost << '}';\n }\n}} \/\/ namespace\n\n\/\/ map\ntemplate <class Key, class T, class Comp> inline\nstd::ostream& operator<< (std::ostream& ost, const std::map<Key, T, Comp>& m) {\n return wtl::detail::operator_ost_map(ost, m);\n}\n\n\/\/ unordered_map\ntemplate <class Key, class T, class Hash> inline\nstd::ostream& operator<< (std::ostream& ost, const std::unordered_map<Key, T, Hash>& m) {\n return wtl::detail::operator_ost_map(ost, m);\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\nnamespace wtl {\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\nstruct identity {\n template<class T>\n constexpr T operator()(T&& x) const noexcept {\n return std::forward<T>(x);\n }\n};\n\ntemplate <class Iter, class Func=identity> inline\nstd::ostream& ost_join(std::ostream& ost, Iter begin_, const Iter end_,\n const std::string& sep=\",\", Func func=Func()) {\n if (begin_ == end_) return ost;\n ost << func(*begin_);\n while (++begin_ != end_) {ost << sep << func(*begin_);}\n return ost;\n}\n\ntemplate <class T, class Func=identity> inline\nstd::ostream& ost_join(std::ostream& ost, const T& v,\n const std::string& sep=\",\", Func func=Func()) {\n return ost_join(ost, begin(v), end(v), sep, func);\n}\n\ntemplate <class Iter, class Func=identity> inline\nstd::string oss_join(Iter begin_, const Iter end_, const std::string& sep=\",\", Func func=Func()) {\n std::ostringstream oss;\n ost_join(oss, begin_, end_, sep, func);\n return oss.str();\n}\n\ntemplate <class T, class Func=identity> inline\nstd::string oss_join(const T& v, const std::string& sep=\",\", Func func=Func()) {\n std::ostringstream oss;\n ost_join(oss, v, sep, func);\n return oss.str();\n}\n\ntemplate <class Iter> inline\nstd::string str_join(Iter begin_, const Iter end_, const std::string& sep=\",\",\n const unsigned int digits=std::cout.precision(), const bool fixed=false) {\n if (begin_ == end_) return \"\";\n std::ostringstream oss;\n oss.precision(digits);\n if (fixed) {oss << std::fixed;}\n oss << *begin_;\n while (++begin_ != end_) {oss << sep << *begin_;}\n return oss.str();\n}\n\ntemplate <class T> inline\nstd::string str_join(const T& v, const std::string& sep,\n const unsigned int digits, const bool fixed) {\n return str_join(begin(v), end(v), sep, digits, fixed);\n}\n\ntemplate <class T> inline\nstd::string str_matrix(const T& m, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n std::string s;\n for (const auto& row: m) {\n s += str_join(row, sep, digits);\n s += '\\n';\n }\n return s;\n}\n\ntemplate <class T> inline\nstd::string str_map(const T& m, const unsigned int digits=std::cout.precision()) {\n std::ostringstream oss;\n oss.precision(digits);\n oss << m;\n return oss.str();\n}\n\ntemplate <int N, class Iter> inline\nstd::string str_pairs(Iter begin_, const Iter end_, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n if (begin_ == end_) return \"\";\n std::ostringstream oss;\n oss.precision(digits);\n oss << std::get<N>(*begin_);\n while (++begin_ != end_) {oss << sep << std::get<N>(*begin_);}\n return oss.str();\n}\ntemplate <int N, class Map> inline\nstd::string str_pairs(const Map& m, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n return str_pairs<N>(begin(m), end(m), sep, digits);\n}\n\ntemplate <class Map> inline\nstd::string str_pair_rows(const Map& m, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n std::string s = str_pairs<0>(m, sep, digits);\n s += '\\n';\n s += str_pairs<1>(m, sep, digits);\n return s += '\\n';\n}\n\ntemplate <class Map> inline\nstd::string str_pair_cols(const Map& m, const std::string& sep=\",\", const unsigned int digits=std::cout.precision()) {\n std::ostringstream oss;\n oss.precision(digits);\n for (const auto& p: m) {\n oss << std::get<0>(p) << sep << std::get<1>(p) << '\\n';\n }\n return oss.str();\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\/\/ std::string manipulation\n\ninline std::vector<std::string> split_algorithm(const std::string& src, const std::string& delimiter=\" \\t\\n\") {\n std::vector<std::string> dst;\n for (auto delim_pos=begin(src), start=delim_pos; delim_pos!=end(src); ) {\n delim_pos = std::find_first_of(start, end(src), begin(delimiter), end(delimiter));\n dst.push_back(std::string(start, delim_pos));\n ++(start = delim_pos);\n }\n return dst;\n}\n\ninline std::vector<std::string>\nsplit(const std::string& src, const std::string& delimiter=\" \\t\\n\") {\n std::vector<std::string> dst;\n size_t start = 0, offset = 0;\n while (true) {\n offset = src.find_first_of(delimiter, start);\n offset -= start;\n dst.push_back(src.substr(start, offset));\n start += offset;\n if (start == src.npos) break;\n ++start;\n }\n return dst;\n}\n\ninline std::string rstrip(std::string src, const std::string& chars=\" \") {\n size_t pos(src.find_last_not_of(chars));\n if (pos == std::string::npos) {\n src.clear();\n } else {\n src.erase(++pos);\n }\n return src;\n}\n\ninline std::string lstrip(std::string src, const std::string& chars=\" \") {\n const size_t pos(src.find_first_not_of(chars));\n if (pos == std::string::npos) {\n src.clear();\n } else {\n src.erase(0, pos);\n }\n return src;\n}\n\ninline std::string strip(std::string src, const std::string& chars=\" \") {\n return rstrip(lstrip(src, chars), chars);\n}\n\ninline bool startswith(const std::string& full, const std::string& sub) {\n const size_t full_size = full.size();\n const size_t sub_size = sub.size();\n if (full_size > sub_size) {\n return full.compare(0, sub_size, sub) == 0;\n } else {\n return false;\n }\n}\n\ninline bool endswith(const std::string& full, const std::string& sub) {\n const size_t full_size = full.size();\n const size_t sub_size = sub.size();\n if (full_size > sub_size) {\n return full.compare(full_size - sub_size, sub_size, sub) == 0;\n } else {\n return false;\n }\n}\n\ninline std::string replace_all(const std::string& patt, const std::string& repl, const std::string& src) {\n std::string result;\n std::string::size_type pos_before(0);\n std::string::size_type pos(0);\n std::string::size_type len(patt.size());\n while ((pos = src.find(patt, pos)) != std::string::npos) {\n result.append(src, pos_before, pos-pos_before);\n result.append(repl);\n pos += len;\n pos_before = pos;\n }\n result.append(src, pos_before, src.size()-pos_before);\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\ninline std::string strprintf(const char* const format, ...) {\n assert(format);\n va_list args;\n std::string buffer;\n va_start(args, format);\n const int length = std::vsnprintf(nullptr, 0, format, args) ;\n va_end(args);\n if (length < 0) throw std::runtime_error(format);\n buffer.resize(length + 1);\n va_start(args, format);\n const int result = std::vsnprintf(&buffer[0], length + 1, format, args);\n va_end(args);\n if (result < 0) throw std::runtime_error(format);\n buffer.pop_back();\n return buffer;\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n\/\/ default is the same as ctime(): Thu Aug 23 14:55:02 2001\n\/\/ which is equivalent to \"%a %b %d %T %Y\"\ninline std::string strftime(const std::string& format=\"%c\") {\n char cstr[80];\n const time_t rawtime = time(nullptr);\n const struct tm* t = localtime(&rawtime);\n std::strftime(cstr, sizeof(cstr), format.c_str(), t);\n return std::string(cstr);\n}\ninline std::string iso8601date(const std::string& sep=\"-\") {\n std::ostringstream oss;\n oss << \"%Y\" << sep << \"%m\" << sep << \"%d\";\n return strftime(oss.str());\n}\ninline std::string iso8601time(const std::string& sep=\":\") {\n std::ostringstream oss;\n oss << \"%H\" << sep << \"%M\" << sep << \"%S\";\n return strftime(oss.str());\n}\ninline std::string iso8601datetime() {return strftime(\"%FT%T%z\");}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\/\/ fstream wrapper for binary mode and exceptions\n\/\/ boost::serialization requires binary mode\n\nclass Fin: public std::ifstream {\n public:\n explicit Fin(const std::string& filepath,\n const std::ios::openmode mode=std::ios::in):\n std::ifstream(filepath.c_str(), mode | std::ios::binary)\n {exceptions(std::ios::badbit);}\n\n std::string readline(const char delimiter='\\n') {\n std::string buffer;\n std::getline(*this, buffer, delimiter);\n return buffer;\n }\n\n std::vector<std::string> readlines(const char delimiter='\\n') {\n std::vector<std::string> lines;\n std::string buffer;\n while (std::getline(*this, buffer, delimiter)) {\n lines.push_back(buffer);\n }\n return lines;\n }\n\n std::string read(const char delimiter='\\0') {return readline(delimiter);}\n};\n\nclass Fout: public std::ofstream {\n public:\n explicit Fout(const std::string& filepath,\n const std::ios::openmode mode=std::ios::out):\n std::ofstream(filepath.c_str(), mode | std::ios::binary)\n {exceptions(std::ios::failbit);}\n\n template <class Iter>\n Fout& writelines(Iter begin_, const Iter end_, const char sep='\\n') {\n if (begin_ == end_) return *this;\n *this << *begin_;\n while (++begin_ != end_) {*this << sep << *begin_;}\n return *this;\n }\n\n template <class V>\n Fout& writelines(const V& lines, const char sep='\\n') {\n return writelines(begin(lines), end(lines), sep);\n }\n};\n\ninline std::vector<std::pair<std::string, std::string> >\nread_ini(const std::string& filename) {\n std::vector<std::string> lines = Fin(filename).readlines();\n std::vector<std::pair<std::string, std::string> > dst;\n dst.reserve(lines.size());\n for (auto line_: lines) {\n line_ = strip(line_);\n if (startswith(line_, \"[\")) {continue;} \/\/ TODO\n auto pair_ = split(line_, \":=\"); \/\/ TODO\n if (pair_.size() < 2) {continue;}\n dst.emplace_back(rstrip(pair_[0]), lstrip(pair_[1]));\n }\n return dst;\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n} \/\/ namespace wtl\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n#endif \/* IOSTR_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"infer.hpp\"\n#include \"ast.hpp\"\n#include \"package.hpp\"\n\n#include <sstream>\n\nnamespace type {\n\n template<class Func>\n static void iter_rows(mono self, Func func) {\n assert(self.kind() == kind::row());\n self.match\n ([&](const app& self) {\n const auto e = extension::unpack(self);\n func(e.attr, e.head);\n iter_rows(e.tail, func);\n }, [](const mono& ) { });\n }\n \n \n struct let {\n const ::list<ast::bind> defs;\n const ast::expr body;\n\n static symbol fix() { return \"__fix__\"; }\n \n \/\/ rewrite let as non-recursive let + fix **when defining functions**\n static let rewrite(const ast::let& self) {\n using ::list;\n const list<ast::bind> defs = map(self.defs, [](ast::bind self) {\n return self.value.match<ast::bind>\n ([&](const ast::abs& abs) { \n return ast::bind{self.name,\n ast::app{ast::var{fix()},\n ast::abs{self.name >>= list<ast::abs::arg>(),\n self.value}\n >>= list<ast::expr>()}};\n }, \n [&](const ast::expr& expr) { return self; });\n });\n\n return {defs, *self.body};\n }\n };\n\n\n \/\/ rewrite app as nested unary applications\n static ast::app rewrite(const ast::app& self) {\n const ast::expr& init = *self.func;\n return foldl(init, self.args, [](ast::expr func, ast::expr arg) {\n return ast::app(func, arg >>= list<ast::expr>());\n }).cast<ast::app>();\n }\n\n\n \n \/\/ reconstruct actual type from reified type: ... -> (type 'a) yields 'a\n \/\/ note: t must be substituted\n static mono reconstruct(ref<state> s, mono t) {\n \/\/ std::clog << \"reconstructing: \" << s->generalize(t) << std::endl;\n \n if(auto self = t.get<app>()) {\n \/\/ std::clog << \"ctor: \" << s->generalize((*self)->ctor) << std::endl;\n \n if((*self)->ctor == ty) {\n return (*self)->arg;\n }\n }\n \n auto from = s->fresh();\n auto to = s->fresh();\n \n s->unify(from >>= to, t);\n return reconstruct(s, s->substitute(to));\n }\n\n\n \/\/ obtain constructor for a monotype\n static cst constructor(mono t) {\n if(auto self = t.get<app>()) {\n return constructor((*self)->ctor);\n }\n\n if(auto self = t.get<cst>()) {\n return *self;\n }\n\n \/\/ TODO restrictive?\n throw error(\"constructor must be a constant\");\n }\n\n\n template<class T>\n static mono infer(const ref<T>& s, const T& self) {\n throw std::logic_error(\"infer unimplemented: \" + tool::type_name(typeid(T)));\n }\n\n \n \/\/ var\n static mono infer(const ref<state>& s, const ast::var& self) {\n try {\n return s->instantiate(s->vars->find(self.name));\n } catch(std::out_of_range& e) {\n throw error(\"unbound variable \" + tool::quote(self.name.get()));\n }\n }\n\n \/\/ abs\n static mono infer(const ref<state>& s, const ast::abs& self) {\n \/\/ function scope\n const auto sub = scope(s);\n\n \/\/ construct function type\n const mono result = s->fresh();\n \n const mono res = foldr(result, self.args, [&](ast::abs::arg arg, mono tail) {\n const mono sig = arg.match<mono>([&](symbol self) {\n \/\/ untyped arguments: trivial signature\n const mono a = sub->fresh();\n return a;\n },\n [&](ast::abs::typed self) {\n \/\/ obtain reified type from annoatation\n const mono t = infer(s, self.type);\n\n \/\/ extract actual type from reified\n const mono r = reconstruct(s, s->substitute(t));\n\n \/\/ obtain type constructor from type\n const cst c = constructor(r);\n\n try {\n \/\/ fetch associated signature, if any\n const auto sig = s->sigs->at(c);\n\n \/\/ instantiate signature\n return sub->instantiate(sig);\n \n } catch(std::out_of_range&) {\n throw error(\"unknown signature \" + tool::quote(c->name.get()));\n }\n });\n \n const mono outer = s->fresh();\n const mono inner = sub->fresh();\n \n sub->unify(outer >>= inner, sig);\n sub->def(arg.name(), outer);\n\n \/\/ std::clog << \"inner: \" << sub->vars->find(arg.name()) << std::endl;\n \n return outer >>= tail;\n });\n \n \/\/ infer lambda body with augmented environment\n s->unify(result, infer(sub, *self.body));\n \n return res;\n }\n\n \n \n\n \/\/ app\n static mono infer(const ref<state>& s, const ast::app& self) {\n \/\/ normalize application as unary\n const ast::app rw = rewrite(self);\n assert(size(rw.args) == 1);\n\n \/\/ infer func\/arg types for application\n const auto with_inferred = [&](auto cont) {\n const mono func = infer(s, *rw.func);\n const mono arg = infer(s, rw.args->head);\n\n return cont(func, arg);\n };\n\n \/\/ obtain inner type from a type with associated signature\n const auto inner_type = [&](mono t) {\n \/\/ obtain type constructor from argument type\n const cst c = constructor(s->substitute(t));\n\n try {\n auto sig = s->sigs->at(c);\n \n const mono inner = s->fresh();\n s->unify(t >>= inner, s->instantiate(sig));\n \n return inner;\n } catch(std::out_of_range&) {\n throw error(\"unknown signature\");\n }\n };\n\n \/\/ check if application works with given func\/arg type\n const auto check = [&](mono func, mono arg) {\n const mono ret = s->fresh();\n s->unify(func , arg >>= ret);\n return ret;\n };\n\n \/\/ TODO find a less stupid way of trying all cases?\n try {\n \/\/ normal case\n return with_inferred([&](mono func, mono arg) {\n return check(func, arg);\n });\n \n } catch(error& e) {\n\n try {\n \/\/ open func type and retry\n return with_inferred([&](mono func, mono arg) {\n const mono inner_func = inner_type(func);\n return check(inner_func, arg);\n });\n }\n catch(error& ) { }\n\n try {\n \/\/ open arg type and retry \n return with_inferred([&](mono func, mono arg) {\n const mono inner_arg = inner_type(arg);\n return check(func, inner_arg);\n });\n }\n catch(error& ) { }\n\n try {\n \/\/ open both func and arg types and retry \n return with_inferred([&](mono func, mono arg) {\n const mono inner_func = inner_type(func); \n const mono inner_arg = inner_type(arg);\n return check(inner_func, inner_arg);\n });\n }\n catch(error& ) { }\n \n throw e;\n }\n \n }\n\n\n \/\/ non-recursive let\n static mono infer(const ref<state>& s, const let& self) {\n auto sub = scope(s);\n\n for(ast::bind def : self.defs) {\n sub->vars->locals.emplace(def.name, s->generalize(infer(s, def.value)));\n }\n \n return infer(sub, self.body);\n }\n\n \n \/\/ recursive let\n static mono infer(const ref<state>& s, const ast::let& self) {\n auto sub = scope(s);\n\n const mono a = sub->fresh();\n sub->def(let::fix(), (a >>= a) >>= a);\n \n return infer(sub, let::rewrite(self));\n }\n\n\n \/\/ sel\n static mono infer(const ref<state>& s, const ast::sel& self) {\n const mono tail = s->fresh(kind::row());\n const mono head = s->fresh(kind::term());\n \n const mono row = ext(self.name)(head)(tail);\n return record(row) >>= head;\n }\n\n \n \/\/ record\n static mono infer(const ref<state>& s, const ast::record& self) {\n const mono init = empty;\n const mono row = foldr(init, self.attrs, [&](ast::record::attr attr, mono tail) {\n return ext(attr.name)(infer(s, attr.value))(tail);\n });\n\n return record(row);\n }\n\n \n\n\n \/\/ make\n static mono infer(const ref<state>& s, const ast::make& self) {\n \/\/ get signature type\n const poly sig = s->vars->find(self.type);\n\n auto sub = scope(s);\n \n const mono outer = s->fresh();\n const mono inner = sub->fresh();\n\n \/\/ instantiate signature at sub level prevents generalization of\n \/\/ contravariant side (variables only appearing in the covariant side will\n \/\/ be generalized)\n s->unify(ty(outer) >>= ty(inner), sub->instantiate(sig));\n \n \/\/ vanilla covariant type\n const poly reference = sub->generalize(inner);\n \n \/\/ build provided type\n const mono init = empty;\n const mono provided =\n record(foldr(init, self.attrs,\n [&](const ast::record::attr attr, mono tail) {\n return row(attr.name, infer(sub, attr.value)) |= tail;\n }));\n\n \/\/ now also unify inner with provided type\n s->unify(inner, provided);\n\n \/\/ now generalize the provided type\n const poly gen = sub->generalize(inner);\n\n \/\/ generalization check: quantified variables in reference\/gen should\n \/\/ substitute to the same variables\n std::set<var> quantified;\n for(const var& v : gen.forall) {\n assert(sub->substitute(v) == v);\n quantified.insert(v);\n }\n\n \/\/ make sure all reference quantified references substitute to quantified\n \/\/ variables\n for(const var& v : reference.forall) {\n const mono vs = sub->substitute(v);\n if(auto u = vs.get<var>()) {\n auto it = quantified.find(*u);\n if(it != quantified.end()) {\n continue;\n }\n }\n\n std::stringstream ss;\n logger(ss) << \"failed to generalize \" << gen \n << \" as \" << reference;\n \n throw error(ss.str());\n }\n\n return outer;\n }\n \n\n \/\/ cond\n static mono infer(const ref<state>& s, const ast::cond& self) {\n const mono test = infer(s, *self.test);\n s->unify(test, boolean);\n\n const mono conseq = infer(s, *self.conseq);\n const mono alt = infer(s, *self.alt); \n\n const mono result = s->fresh();\n s->unify(result, conseq);\n s->unify(result, alt);\n\n return result; \n }\n\n \n \/\/ def\n static mono infer(const ref<state>& s, const ast::def& self) {\n const mono value =\n infer(s, ast::let(ast::bind{self.name, *self.value} >>= list<ast::bind>(),\n ast::var{self.name}));\n try {\n s->def(self.name, value);\n return io(unit);\n } catch(std::runtime_error& e) {\n throw error(e.what());\n }\n }\n\n\n \/\/ use\n static mono infer(const ref<state>& s, const ast::use& self) {\n \/\/ infer value type\n const mono value = infer(s, *self.env);\n\n \/\/ make sure value type is a record\n const mono row = s->fresh(kind::row());\n s->unify(value, record(row));\n\n auto sub = scope(s);\n \n \/\/ fill sub scope with record contents\n iter_rows(s->substitute(row), [&](symbol attr, mono t) {\n \/\/ TODO generalization issue?\n sub->def(attr, t);\n });\n\n return infer(sub, *self.body);\n }\n\n\n \/\/ import\n static mono infer(const ref<state>& s, const ast::import& self) {\n auto it = s->vars->locals.find(self.package);\n if(it != s->vars->locals.end()) {\n throw error(\"variable \" + tool::quote(self.package.get()) + \" already defined\");\n }\n \n const package pkg = package::import(self.package);\n \n s->vars->locals.emplace(self.package, pkg.sig());\n return io(unit);\n }\n \n \n \/\/ lit\n static mono infer(const ref<state>&, const ast::lit<::boolean>& self) {\n return boolean;\n }\n\n static mono infer(const ref<state>&, const ast::lit<::integer>& self) {\n return integer;\n }\n\n static mono infer(const ref<state>&, const ast::lit<::real>& self) {\n return real;\n }\n \n\n \n \n struct infer_visitor {\n using type = mono;\n \n template<class T>\n mono operator()(const T& self, const ref<state>& s) const {\n return infer(s, self);\n }\n \n };\n \n\n mono infer(const ref<state>& s, const ast::expr& self) {\n return self.visit(infer_visitor(), s);\n }\n\n \n}\n<commit_msg>cleaner + fixed bug<commit_after>#include \"infer.hpp\"\n#include \"ast.hpp\"\n#include \"package.hpp\"\n\n#include <sstream>\n\nnamespace type {\n\n\n \/\/ try to open type `self` from signatures in `s`\n static mono open(const ref<state>& s, const mono& self);\n\n \n template<class Func>\n static void iter_rows(mono self, Func func) {\n assert(self.kind() == kind::row());\n self.match\n ([&](const app& self) {\n const auto e = extension::unpack(self);\n func(e.attr, e.head);\n iter_rows(e.tail, func);\n }, [](const mono& ) { });\n }\n \n \n struct let {\n const ::list<ast::bind> defs;\n const ast::expr body;\n\n static symbol fix() { return \"__fix__\"; }\n \n \/\/ rewrite let as non-recursive let + fix **when defining functions**\n static let rewrite(const ast::let& self) {\n using ::list;\n const list<ast::bind> defs = map(self.defs, [](ast::bind self) {\n return self.value.match<ast::bind>\n ([&](const ast::abs& abs) { \n return ast::bind{self.name,\n ast::app{ast::var{fix()},\n ast::abs{self.name >>= list<ast::abs::arg>(),\n self.value}\n >>= list<ast::expr>()}};\n }, \n [&](const ast::expr& expr) { return self; });\n });\n\n return {defs, *self.body};\n }\n };\n\n\n \/\/ rewrite app as nested unary applications\n static ast::app rewrite(const ast::app& self) {\n const ast::expr& init = *self.func;\n return foldl(init, self.args, [](ast::expr func, ast::expr arg) {\n return ast::app(func, arg >>= list<ast::expr>());\n }).cast<ast::app>();\n }\n\n\n \n \/\/ reconstruct actual type from reified type: ... -> (type 'a) yields 'a\n \/\/ note: t must be substituted\n static mono reconstruct(ref<state> s, mono t) {\n \/\/ std::clog << \"reconstructing: \" << s->generalize(t) << std::endl;\n \n if(auto self = t.get<app>()) {\n \/\/ std::clog << \"ctor: \" << s->generalize((*self)->ctor) << std::endl;\n \n if((*self)->ctor == ty) {\n return (*self)->arg;\n }\n }\n \n auto from = s->fresh();\n auto to = s->fresh();\n \n s->unify(from >>= to, t);\n return reconstruct(s, s->substitute(to));\n }\n\n\n \/\/ obtain constructor for a monotype\n static cst constructor(mono t) {\n if(auto self = t.get<app>()) {\n return constructor((*self)->ctor);\n }\n\n if(auto self = t.get<cst>()) {\n return *self;\n }\n\n \/\/ TODO restrictive?\n throw error(\"constructor must be a constant\");\n }\n\n \n \/\/ try to open type `self` from signatures in `s`\n static mono open(const ref<state>& s, const mono& self) {\n \/\/ obtain type constructor from argument type\n const cst c = constructor(s->substitute(self));\n \n try {\n auto sig = s->sigs->at(c);\n \n const mono inner = s->fresh();\n s->unify(self >>= inner, s->instantiate(sig));\n \n return inner;\n } catch(std::out_of_range&) {\n std::stringstream ss;\n ss << \"constructor \" << tool::quote(c->name.get()) << \" has not associated signature\";\n throw error(ss.str());\n }\n }\n \n\n \n\n template<class T>\n static mono infer(const ref<T>& s, const T& self) {\n throw std::logic_error(\"infer unimplemented: \" + tool::type_name(typeid(T)));\n }\n\n \n \/\/ var\n static mono infer(const ref<state>& s, const ast::var& self) {\n try {\n return s->instantiate(s->vars->find(self.name));\n } catch(std::out_of_range& e) {\n throw error(\"unbound variable \" + tool::quote(self.name.get()));\n }\n }\n\n \/\/ abs\n static mono infer(const ref<state>& s, const ast::abs& self) {\n \/\/ function scope\n const auto sub = scope(s);\n\n \/\/ construct function type\n const mono result = s->fresh();\n \n const mono res = foldr(result, self.args, [&](ast::abs::arg arg, mono tail) {\n const mono type = arg.match<mono>([&](symbol self) {\n return s->fresh();\n },\n [&](ast::abs::typed self) {\n \/\/ obtain reified type from annoatation\n const mono reified = infer(s, self.type);\n\n \/\/ TODO do we need gen\/inst here?\n \n \/\/ extract concrete type from reified type\n const mono concrete = reconstruct(s, s->substitute(reified));\n \n return concrete;\n });\n \n sub->def(arg.name(), type);\n return type >>= tail;\n });\n \n \/\/ infer lambda body with augmented environment\n s->unify(result, infer(sub, *self.body));\n \n return res;\n }\n \n \n\n\n \/\/ app\n static mono infer(const ref<state>& s, const ast::app& self) {\n \/\/ normalize application as unary\n const ast::app rw = rewrite(self);\n assert(size(rw.args) == 1);\n\n \/\/ infer func\/arg types for application\n const auto with_inferred = [&](auto cont) {\n const mono func = infer(s, *rw.func);\n const mono arg = infer(s, rw.args->head);\n\n return cont(func, arg);\n };\n\n \/\/ check if application works with given func\/arg type\n const auto check = [&](mono func, mono arg) {\n const mono ret = s->fresh();\n s->unify(func , arg >>= ret);\n return ret;\n };\n\n \/\/ TODO find a less stupid way of trying all cases?\n try {\n \/\/ normal case\n return with_inferred([&](mono func, mono arg) {\n return check(func, arg);\n });\n \n } catch(error& e) {\n\n try {\n \/\/ open func type and retry\n return with_inferred([&](mono func, mono arg) {\n return check(open(s, func), arg);\n });\n }\n catch(error& ) { }\n\n try {\n \/\/ open arg type and retry \n return with_inferred([&](mono func, mono arg) {\n return check(func, open(s, arg));\n });\n }\n catch(error& ) { }\n\n try {\n \/\/ open both func and arg types and retry \n return with_inferred([&](mono func, mono arg) {\n return check(open(s, func), open(s, arg));\n });\n }\n catch(error& ) { }\n \n throw e;\n }\n \n }\n\n\n \/\/ non-recursive let\n static mono infer(const ref<state>& s, const let& self) {\n auto sub = scope(s);\n\n for(ast::bind def : self.defs) {\n sub->vars->locals.emplace(def.name, s->generalize(infer(s, def.value)));\n }\n \n return infer(sub, self.body);\n }\n\n \n \/\/ recursive let\n static mono infer(const ref<state>& s, const ast::let& self) {\n auto sub = scope(s);\n\n const mono a = sub->fresh();\n sub->def(let::fix(), (a >>= a) >>= a);\n \n return infer(sub, let::rewrite(self));\n }\n\n\n \/\/ sel\n static mono infer(const ref<state>& s, const ast::sel& self) {\n const mono tail = s->fresh(kind::row());\n const mono head = s->fresh(kind::term());\n \n const mono row = ext(self.name)(head)(tail);\n return record(row) >>= head;\n }\n\n \n \/\/ record\n static mono infer(const ref<state>& s, const ast::record& self) {\n const mono init = empty;\n const mono row = foldr(init, self.attrs, [&](ast::record::attr attr, mono tail) {\n return ext(attr.name)(infer(s, attr.value))(tail);\n });\n\n return record(row);\n }\n\n \n\n\n \/\/ make\n static mono infer(const ref<state>& s, const ast::make& self) {\n \/\/ get signature type\n const poly sig = s->vars->find(self.type);\n\n auto sub = scope(s);\n \n const mono outer = s->fresh();\n const mono inner = sub->fresh();\n\n \/\/ instantiate signature at sub level prevents generalization of\n \/\/ contravariant side (variables only appearing in the covariant side will\n \/\/ be generalized)\n s->unify(ty(outer) >>= ty(inner), sub->instantiate(sig));\n \n \/\/ vanilla covariant type\n const poly reference = sub->generalize(inner);\n \n \/\/ build provided type\n const mono init = empty;\n const mono provided =\n record(foldr(init, self.attrs,\n [&](const ast::record::attr attr, mono tail) {\n return row(attr.name, infer(sub, attr.value)) |= tail;\n }));\n\n \/\/ now also unify inner with provided type\n s->unify(inner, provided);\n\n \/\/ now generalize the provided type\n const poly gen = sub->generalize(inner);\n\n \/\/ generalization check: quantified variables in reference\/gen should\n \/\/ substitute to the same variables\n std::set<var> quantified;\n for(const var& v : gen.forall) {\n assert(sub->substitute(v) == v);\n quantified.insert(v);\n }\n\n \/\/ make sure all reference quantified references substitute to quantified\n \/\/ variables\n for(const var& v : reference.forall) {\n const mono vs = sub->substitute(v);\n if(auto u = vs.get<var>()) {\n auto it = quantified.find(*u);\n if(it != quantified.end()) {\n continue;\n }\n }\n\n std::stringstream ss;\n logger(ss) << \"failed to generalize \" << gen \n << \" as \" << reference;\n \n throw error(ss.str());\n }\n\n return outer;\n }\n \n\n \/\/ cond\n static mono infer(const ref<state>& s, const ast::cond& self) {\n const mono test = infer(s, *self.test);\n s->unify(test, boolean);\n\n const mono conseq = infer(s, *self.conseq);\n const mono alt = infer(s, *self.alt); \n\n const mono result = s->fresh();\n s->unify(result, conseq);\n s->unify(result, alt);\n\n return result; \n }\n\n \n \/\/ def\n static mono infer(const ref<state>& s, const ast::def& self) {\n const mono value =\n infer(s, ast::let(ast::bind{self.name, *self.value} >>= list<ast::bind>(),\n ast::var{self.name}));\n try {\n s->def(self.name, value);\n return io(unit);\n } catch(std::runtime_error& e) {\n throw error(e.what());\n }\n }\n\n\n \/\/ use\n static mono infer(const ref<state>& s, const ast::use& self) {\n \/\/ infer value type\n const mono value = infer(s, *self.env);\n\n \/\/ make sure value type is a record\n const mono row = s->fresh(kind::row());\n s->unify(value, record(row));\n\n auto sub = scope(s);\n \n \/\/ fill sub scope with record contents\n iter_rows(s->substitute(row), [&](symbol attr, mono t) {\n \/\/ TODO generalization issue?\n sub->def(attr, t);\n });\n\n return infer(sub, *self.body);\n }\n\n\n \/\/ import\n static mono infer(const ref<state>& s, const ast::import& self) {\n auto it = s->vars->locals.find(self.package);\n if(it != s->vars->locals.end()) {\n throw error(\"variable \" + tool::quote(self.package.get()) + \" already defined\");\n }\n \n const package pkg = package::import(self.package);\n \n s->vars->locals.emplace(self.package, pkg.sig());\n return io(unit);\n }\n \n \n \/\/ lit\n static mono infer(const ref<state>&, const ast::lit<::boolean>& self) {\n return boolean;\n }\n\n static mono infer(const ref<state>&, const ast::lit<::integer>& self) {\n return integer;\n }\n\n static mono infer(const ref<state>&, const ast::lit<::real>& self) {\n return real;\n }\n \n\n \n \n struct infer_visitor {\n using type = mono;\n \n template<class T>\n mono operator()(const T& self, const ref<state>& s) const {\n return infer(s, self);\n }\n \n };\n \n\n mono infer(const ref<state>& s, const ast::expr& self) {\n return self.visit(infer_visitor(), s);\n }\n\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n** Author: Zach Colbert\n** Date: 30 November 2017\n** Description: Library class\n*********************************************************************\/\n\n\/*********************************************************************\n** Includes\n*********************************************************************\/\n\n#include \"Library.hpp\"\n\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nLibrary::Library()\n{\n \/\/ Initialize the relative date of the library\n currentDate = 0;\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nvoid Library::addBook(Book* newBook)\n{\n \/\/ vector::push_back will add Book* to the end of the vector\n holdings.push_back(newBook);\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nvoid Library::addPatron(Patron* newPatron)\n{\n \/\/ vector::push_back will add Patron* to the end of the vector\n members.push_back(newPatron);\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nstd::string Library::checkOutBook(std::string pID, std::string bID)\n{\n \/\/ if the specified Book is not in the Library, return \"book not found\"\n\n Book* chkBook = getBook(bID);\n\n if (chkBook == nullptr)\n {\n return \"book not found\";\n }\n\n \/\/ if the specified Patron is not in the Library, return \"patron not found\"\n\n Patron* chkPatron = getPatron(pID);\n\n if(chkPatron == nullptr)\n {\n return \"patron not found\";\n }\n\n \/\/ if the specified Book is already checked out, return \"book already checked out\"\n if ((*chkBook).getCheckedOutBy() != nullptr)\n {\n return \"book already checked out\";\n }\n\n \/\/ if the specified Book is on hold by another Patron, return \"book on hold by other patron\"\n if ((*chkBook).getRequestedBy() != nullptr)\n {\n return \"book on hold by other patron\";\n }\n\n \/\/ otherwise update the Book's checkedOutBy, dateCheckedOut and Location; if the Book was on hold for this Patron, update requestedBy; update the Patron's checkedOutBooks; return \"check out successful\"\n (*chkBook).setCheckedOutBy(chkPatron);\n (*chkBook).setDateCheckedOut(currentDate);\n (*chkBook).setLocation(CHECKED_OUT);\n\n if ((*chkBook).getRequestedBy() == (*chkBook).getCheckedOutBy())\n {\n (*chkBook).setRequestedBy(nullptr);\n }\n\n (*chkPatron).addBook(chkBook);\n\n return \"check out successful\";\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nstd::string Library::returnBook(std::string bID)\n{\n \/\/ if the specified Book is not in the Library, return \"book not found\"\n Book* chkBook = getBook(bID);\n\n if (chkBook == nullptr)\n {\n return \"book not found\";\n }\n\n \/\/ if the Book is not checked out, return \"book already in library\"\n if ((*chkBook).getCheckedOutBy() == nullptr)\n {\n return \"book already in library\";\n }\n\n \/\/ update the Patron's checkedOutBooks; update the Book's location depending on whether another Patron has requested it; update the Book's checkedOutBy; return \"return successful\"\n (*(*chkBook).getCheckedOutBy()).removeBook(chkBook);\n \n \/\/ If the book is not on hold, location goes to ON_SHELF\n if ((*chkBook).getRequestedBy() == nullptr)\n {\n (*chkBook).setLocation(ON_SHELF);\n }\n \/\/ Otherwise, it is on hold and goes to ON_HOLD_SHELF\n else\n {\n (*chkBook).setLocation(ON_HOLD_SHELF);\n }\n\n (*chkBook).setCheckedOutBy(nullptr);\n\n return \"return successful\";\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nstd::string Library::requestBook(std::string pID, std::string bID)\n{\n \/\/ if the specified Book is not in the Library, return \"book not found\"\n Book* chkBook = getBook(bID);\n\n if (chkBook == nullptr)\n {\n return \"book not found\";\n }\n\n \/\/ if the specified Patron is not in the Library, return \"patron not found\"\n Patron* chkPatron = getPatron(pID);\n\n if (chkPatron == nullptr)\n {\n return \"patron not found\";\n }\n\n \/\/ if the specified Book is already requested, return \"book already on hold\"\n if ((*chkBook).getRequestedBy() != nullptr)\n {\n return \"book already on hold\";\n }\n\n \/\/ update the Book's requestedBy; if the Book is on the shelf, update its location to on hold; return \"request successful\"\n (*chkBook).setRequestedBy(chkPatron);\n \n if ((*chkBook).getLocation() == ON_SHELF)\n {\n (*chkBook).setLocation(ON_HOLD_SHELF);\n }\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nstd::string Library::payFine(std::string pID, double payment)\n{\n \/\/ takes as a parameter the amount that is being paid (not the negative of that amount)\n if (payment < 0)\n {\n return \"invalid payment amount\";\n }\n\n \/\/ if the specified Patron is not in the Library, return \"patron not found\"\n Patron* chkPatron = getPatron(pID);\n\n if (chkPatron == nullptr)\n {\n return \"patron not found\";\n }\n\n \/\/ use amendFine to update the Patron's fine; return \"payment successful\"\n (*chkPatron).amendFine(payment);\n\n return \"payment successful\";\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nvoid Library::incrementCurrentDate()\n{\n currentDate++;\n}\n\n\n\/\/ Description\nPatron* Library::getPatron(std::string pID)\n{\n bool patronFound = false;\n int patronIndex = -1;\n\n for (Patron* chkPatron : members)\n {\n patronIndex++;\n if ((*chkPatron).getIdNum() == pID)\n {\n patronFound = true;\n break;\n }\n }\n\n if (patronFound == false)\n {\n return nullptr;\n }\n else\n {\n return members[patronIndex];\n }\n}\n\n\n\/\/ Description\nBook* Library::getBook(std::string bID)\n{\n bool bookFound = false;\n int bookIndex = -1;\n\n for (Book* chkBook : holdings)\n {\n bookIndex++;\n if ((*chkBook).getIdCode() == bID)\n {\n bookFound = true;\n break;\n }\n }\n\n if (bookFound == false)\n {\n return nullptr;\n }\n else\n {\n return holdings[bookIndex];\n }\n}<commit_msg>Second draft<commit_after>\/*********************************************************************\n** Author: Zach Colbert\n** Date: 30 November 2017\n** Description: Library class\n*********************************************************************\/\n\n\/*********************************************************************\n** Includes\n*********************************************************************\/\n\n#include \"Library.hpp\"\n\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nLibrary::Library()\n{\n \/\/ Initialize the relative date of the library\n currentDate = 0;\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nvoid Library::addBook(Book* newBook)\n{\n \/\/ vector::push_back will add Book* to the end of the vector\n holdings.push_back(newBook);\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nvoid Library::addPatron(Patron* newPatron)\n{\n \/\/ vector::push_back will add Patron* to the end of the vector\n members.push_back(newPatron);\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nstd::string Library::checkOutBook(std::string pID, std::string bID)\n{\n \/\/ if the specified Book is not in the Library, return \"book not found\"\n\n Book* chkBook = getBook(bID);\n\n if (chkBook == nullptr)\n {\n return \"book not found\";\n }\n\n \/\/ if the specified Patron is not in the Library, return \"patron not found\"\n\n Patron* chkPatron = getPatron(pID);\n\n if(chkPatron == nullptr)\n {\n return \"patron not found\";\n }\n\n \/\/ if the specified Book is already checked out, return \"book already checked out\"\n if ((*chkBook).getCheckedOutBy() != nullptr)\n {\n return \"book already checked out\";\n }\n\n \/\/ if the specified Book is on hold by another Patron, return \"book on hold by other patron\"\n if ((*chkBook).getRequestedBy() != nullptr)\n {\n return \"book on hold by other patron\";\n }\n\n \/\/ otherwise update the Book's checkedOutBy, dateCheckedOut and Location; if the Book was on hold for this Patron, update requestedBy; update the Patron's checkedOutBooks; return \"check out successful\"\n (*chkBook).setCheckedOutBy(chkPatron);\n (*chkBook).setDateCheckedOut(currentDate);\n (*chkBook).setLocation(CHECKED_OUT);\n\n if ((*chkBook).getRequestedBy() == (*chkBook).getCheckedOutBy())\n {\n (*chkBook).setRequestedBy(nullptr);\n }\n\n (*chkPatron).addBook(chkBook);\n\n return \"check out successful\";\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nstd::string Library::returnBook(std::string bID)\n{\n \/\/ if the specified Book is not in the Library, return \"book not found\"\n Book* chkBook = getBook(bID);\n\n if (chkBook == nullptr)\n {\n return \"book not found\";\n }\n\n \/\/ if the Book is not checked out, return \"book already in library\"\n if ((*chkBook).getCheckedOutBy() == nullptr)\n {\n return \"book already in library\";\n }\n\n \/\/ update the Patron's checkedOutBooks; update the Book's location depending on whether another Patron has requested it; update the Book's checkedOutBy; return \"return successful\"\n (*(*chkBook).getCheckedOutBy()).removeBook(chkBook);\n \n \/\/ If the book is not on hold, location goes to ON_SHELF\n if ((*chkBook).getRequestedBy() == nullptr)\n {\n (*chkBook).setLocation(ON_SHELF);\n }\n \/\/ Otherwise, it is on hold and goes to ON_HOLD_SHELF\n else\n {\n (*chkBook).setLocation(ON_HOLD_SHELF);\n }\n\n (*chkBook).setCheckedOutBy(nullptr);\n\n return \"return successful\";\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nstd::string Library::requestBook(std::string pID, std::string bID)\n{\n \/\/ if the specified Book is not in the Library, return \"book not found\"\n Book* chkBook = getBook(bID);\n\n if (chkBook == nullptr)\n {\n return \"book not found\";\n }\n\n \/\/ if the specified Patron is not in the Library, return \"patron not found\"\n Patron* chkPatron = getPatron(pID);\n\n if (chkPatron == nullptr)\n {\n return \"patron not found\";\n }\n\n \/\/ if the specified Book is already requested, return \"book already on hold\"\n if ((*chkBook).getRequestedBy() != nullptr)\n {\n return \"book already on hold\";\n }\n\n \/\/ update the Book's requestedBy; if the Book is on the shelf, update its location to on hold; return \"request successful\"\n (*chkBook).setRequestedBy(chkPatron);\n \n if ((*chkBook).getLocation() == ON_SHELF)\n {\n (*chkBook).setLocation(ON_HOLD_SHELF);\n }\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nstd::string Library::payFine(std::string pID, double payment)\n{\n \/\/ takes as a parameter the amount that is being paid (not the negative of that amount)\n if (payment < 0)\n {\n return \"invalid payment amount\";\n }\n\n \/\/ if the specified Patron is not in the Library, return \"patron not found\"\n Patron* chkPatron = getPatron(pID);\n\n if (chkPatron == nullptr)\n {\n return \"patron not found\";\n }\n\n \/\/ use amendFine to update the Patron's fine; return \"payment successful\"\n (*chkPatron).amendFine(-1.0 * payment);\n\n return \"payment successful\";\n\n}\n\n\n\/*********************************************************************\n** Description:\n*********************************************************************\/\nvoid Library::incrementCurrentDate()\n{\n currentDate++;\n}\n\n\n\/\/ Description\nPatron* Library::getPatron(std::string pID)\n{\n bool patronFound = false;\n int patronIndex = -1;\n\n for (Patron* chkPatron : members)\n {\n patronIndex++;\n if ((*chkPatron).getIdNum() == pID)\n {\n patronFound = true;\n break;\n }\n }\n\n if (patronFound == false)\n {\n return nullptr;\n }\n else\n {\n return members[patronIndex];\n }\n}\n\n\n\/\/ Description\nBook* Library::getBook(std::string bID)\n{\n bool bookFound = false;\n int bookIndex = -1;\n\n for (Book* chkBook : holdings)\n {\n bookIndex++;\n if ((*chkBook).getIdCode() == bID)\n {\n bookFound = true;\n break;\n }\n }\n\n if (bookFound == false)\n {\n return nullptr;\n }\n else\n {\n return holdings[bookIndex];\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * SuiPageData.cpp\n *\n * Created on: Nov 7, 2013\n * Author: crush\n *\/\n\n\n#include \"SuiPageData.h\"\n#include \"SuiCommand.h\"\n#include \"server\/zone\/ZoneClientSession.h\"\n#include \"server\/zone\/packets\/ui\/SuiCreatePageMessage.h\"\n#include \"server\/zone\/packets\/ui\/SuiUpdatePageMessage.h\"\n#include \"server\/zone\/objects\/player\/PlayerObject.h\"\n\nvoid SuiPageData::setProperty(const String& widget, const String& property, const UnicodeString& value) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_setProperty);\n\tcommand->addWideParameter(value);\n\tcommand->addNarrowParameter(widget);\n\tcommand->addNarrowParameter(property);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::addDataItem(const String& widget, const String& property, const UnicodeString& value) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_addDataItem);\n\tcommand->addWideParameter(value);\n\tcommand->addNarrowParameter(widget);\n\tcommand->addNarrowParameter(property);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::clearDataSource(const String& dataSource) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_clearDataSource);\n\tcommand->addNarrowParameter(dataSource);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::addDataSourceContainer(const String& parent, const String& name) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_addDataSourceContainer);\n\tcommand->addNarrowParameter(parent);\n\tcommand->addNarrowParameter(name);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::clearDataSourceContainer(const String& dataSourceContainer) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_clearDataSourceContainer);\n\tcommand->addNarrowParameter(dataSourceContainer);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::addChildWidget(const String& parent, const String& type, const String& name) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_addChildWidget);\n\tcommand->addNarrowParameter(parent);\n\tcommand->addNarrowParameter(type);\n\tcommand->addNarrowParameter(name);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::subscribeToEvent(const byte& eventType, const String& parent, const String& callback) {\n\tif (callbacks.contains(eventType)) {\n\t\twarning(\"SuiPageData::addCommand attempt to add duplicate SCT_subscribeToEvent command.\");\n\t\treturn;\n\t}\n\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_subscribeToEvent);\n\tcommand->addNarrowParameter(parent);\n\n StringBuffer eventTypeBuffer;\n eventTypeBuffer.append((char)eventType);\n\n command->addNarrowParameter(eventTypeBuffer.toString());\n\tcommand->addNarrowParameter(callback);\n\n\tcallbacks.put(eventType, command);\n\tcommands.add(command);\n}\n\nvoid SuiPageData::subscribeToPropertyForEvent(const byte& eventType, const String& widget, const String& property) {\n\tReference<SuiCommand*> command = callbacks.get(eventType);\n\n\tif (command == NULL) {\n\t\twarning(\"Attempted to add properties for event without subscribing a callback first.\");\n\t\treturn;\n\t}\n\n\tcommand->addNarrowParameter(widget);\n\tcommand->addNarrowParameter(property);\n}\n\nbool SuiPageData::toBinaryStream(ObjectOutputStream* stream) {\n\tstream->writeInt(id);\n\trootPage.toBinaryStream(stream);\n\tstream->writeInt(commands.size());\n\n\tfor (int i = 0; i < commands.size(); ++i)\n\t\tcommands.get(i)->toBinaryStream(stream);\n\n\tstream->writeLong(targetNetworkId);\n\tstream->writeFloat(forceCloseDistance);\n\tstream->writeLong(unknownNetworkId);\n\n\treturn true;\n}\n\nbool SuiPageData::parseFromBinaryStream(ObjectInputStream* stream) {\n\tid = stream->readInt();\n\trootPage.parseFromBinaryStream(stream);\n\n\tint size = stream->readInt();\n\n\tfor (int i = 0; i < size; ++i) {\n\t\tSuiCommand* command = new SuiCommand();\n\t\tcommand->parseFromBinaryStream(stream);\n\n\t\tif (command->getCommandType() == SuiCommand::SCT_subscribeToEvent) {\n\t\t\t\/\/callbacks.put(); \/\/TODO: Register subscribes again...\n\t\t}\n\n\t\tcommands.add(command);\n\t}\n\n\ttargetNetworkId = stream->readLong();\n\tforceCloseDistance = stream->readFloat();\n\tunknownNetworkId = stream->readLong();\n\n\treturn true;\n}\n\nvoid SuiPageData::sendTo(CreatureObject* creo) {\n\tPlayerObject* playerObject = creo->getPlayerObject();\n\n\tif (playerObject != NULL) {\n\t\tcreo->getClient()->sendMessage(new SuiCreatePageMessage(this));\n\t}\n}\n\nvoid SuiPageData::sendUpdateTo(CreatureObject* creo) {\n\tPlayerObject* playerObject = creo->getPlayerObject();\n\n\tif (playerObject != NULL) {\n\t\tcreo->getClient()->sendMessage(new SuiUpdatePageMessage(this));\n\t}\n}\n<commit_msg>[Fixed] stability issue<commit_after>\/*\n * SuiPageData.cpp\n *\n * Created on: Nov 7, 2013\n * Author: crush\n *\/\n\n\n#include \"SuiPageData.h\"\n#include \"SuiCommand.h\"\n#include \"server\/zone\/ZoneClientSession.h\"\n#include \"server\/zone\/packets\/ui\/SuiCreatePageMessage.h\"\n#include \"server\/zone\/packets\/ui\/SuiUpdatePageMessage.h\"\n#include \"server\/zone\/objects\/player\/PlayerObject.h\"\n\nvoid SuiPageData::setProperty(const String& widget, const String& property, const UnicodeString& value) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_setProperty);\n\tcommand->addWideParameter(value);\n\tcommand->addNarrowParameter(widget);\n\tcommand->addNarrowParameter(property);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::addDataItem(const String& widget, const String& property, const UnicodeString& value) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_addDataItem);\n\tcommand->addWideParameter(value);\n\tcommand->addNarrowParameter(widget);\n\tcommand->addNarrowParameter(property);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::clearDataSource(const String& dataSource) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_clearDataSource);\n\tcommand->addNarrowParameter(dataSource);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::addDataSourceContainer(const String& parent, const String& name) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_addDataSourceContainer);\n\tcommand->addNarrowParameter(parent);\n\tcommand->addNarrowParameter(name);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::clearDataSourceContainer(const String& dataSourceContainer) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_clearDataSourceContainer);\n\tcommand->addNarrowParameter(dataSourceContainer);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::addChildWidget(const String& parent, const String& type, const String& name) {\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_addChildWidget);\n\tcommand->addNarrowParameter(parent);\n\tcommand->addNarrowParameter(type);\n\tcommand->addNarrowParameter(name);\n\n\tcommands.add(command);\n}\n\nvoid SuiPageData::subscribeToEvent(const byte& eventType, const String& parent, const String& callback) {\n\tif (callbacks.contains(eventType)) {\n\t\twarning(\"SuiPageData::addCommand attempt to add duplicate SCT_subscribeToEvent command.\");\n\t\treturn;\n\t}\n\n\tSuiCommand* command = new SuiCommand(SuiCommand::SCT_subscribeToEvent);\n\tcommand->addNarrowParameter(parent);\n\n StringBuffer eventTypeBuffer;\n eventTypeBuffer.append((char)eventType);\n\n command->addNarrowParameter(eventTypeBuffer.toString());\n\tcommand->addNarrowParameter(callback);\n\n\tcallbacks.put(eventType, command);\n\tcommands.add(command);\n}\n\nvoid SuiPageData::subscribeToPropertyForEvent(const byte& eventType, const String& widget, const String& property) {\n\tReference<SuiCommand*> command = callbacks.get(eventType);\n\n\tif (command == NULL) {\n\t\twarning(\"Attempted to add properties for event without subscribing a callback first.\");\n\t\treturn;\n\t}\n\n\tcommand->addNarrowParameter(widget);\n\tcommand->addNarrowParameter(property);\n}\n\nbool SuiPageData::toBinaryStream(ObjectOutputStream* stream) {\n\tstream->writeInt(id);\n\trootPage.toBinaryStream(stream);\n\tstream->writeInt(commands.size());\n\n\tfor (int i = 0; i < commands.size(); ++i)\n\t\tcommands.get(i)->toBinaryStream(stream);\n\n\tstream->writeLong(targetNetworkId);\n\tstream->writeFloat(forceCloseDistance);\n\tstream->writeLong(unknownNetworkId);\n\n\treturn true;\n}\n\nbool SuiPageData::parseFromBinaryStream(ObjectInputStream* stream) {\n\tid = stream->readInt();\n\trootPage.parseFromBinaryStream(stream);\n\n\tint size = stream->readInt();\n\n\tfor (int i = 0; i < size; ++i) {\n\t\tSuiCommand* command = new SuiCommand();\n\t\tcommand->parseFromBinaryStream(stream);\n\n\t\tif (command->getCommandType() == SuiCommand::SCT_subscribeToEvent) {\n\t\t\t\/\/callbacks.put(); \/\/TODO: Register subscribes again...\n\t\t}\n\n\t\tcommands.add(command);\n\t}\n\n\ttargetNetworkId = stream->readLong();\n\tforceCloseDistance = stream->readFloat();\n\tunknownNetworkId = stream->readLong();\n\n\treturn true;\n}\n\nvoid SuiPageData::sendTo(CreatureObject* creo) {\n\tPlayerObject* playerObject = creo->getPlayerObject();\n\n\tif (playerObject != NULL) {\n\t\tcreo->getClient()->sendMessage(new SuiCreatePageMessage(this));\n\t}\n}\n\nvoid SuiPageData::sendUpdateTo(CreatureObject* creo) {\n\tPlayerObject* playerObject = creo->getPlayerObject();\n\tZoneClientSession* client = creo->getClient();\n\n\tif (playerObject != NULL && client != NULL) {\n\t\tclient->sendMessage(new SuiUpdatePageMessage(this));\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright (c) 2019, Open Source Robotics Foundation, Inc.\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 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 the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. 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 \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <gtest\/gtest.h>\n#include <realtime_tools\/realtime_server_goal_handle.h>\n#include <actionlib\/client\/simple_action_client.h>\n#include <actionlib\/TwoIntsAction.h>\n#include <chrono>\n#include <memory>\n#include <mutex>\n#include <thread>\n\nusing realtime_tools::RealtimeServerGoalHandle;\n\nconst size_t ATTEMPTS = 10;\nconst std::chrono::milliseconds DELAY(250);\n\nstruct ActionCallback\n{\n using GoalHandle = actionlib::ActionServer<actionlib::TwoIntsAction>::GoalHandle;\n bool have_handle_ = false;\n GoalHandle handle_;\n std::mutex mtx_;\n\n void goal_callback(GoalHandle handle)\n {\n std::unique_lock<std::mutex> lock(mtx_);\n handle_ = handle;\n handle_.setAccepted();\n have_handle_ = true;\n }\n\n void cancel_callback(GoalHandle handle)\n {\n }\n\n bool wait_for_handle()\n {\n for (size_t i = 0; i < ATTEMPTS; ++i) {\n ros::spinOnce();\n std::this_thread::sleep_for(DELAY);\n std::unique_lock<std::mutex> lock(mtx_);\n if (have_handle_) {\n break;\n }\n }\n std::unique_lock<std::mutex> lock(mtx_);\n return have_handle_;\n }\n};\n\nstruct FeedbackCallback\n{\n bool have_feedback_ = false;\n std::mutex mtx_;\n\n using FeedbackConstPtr = actionlib::ActionServer<actionlib::TwoIntsAction>::FeedbackConstPtr;\n void feedback_callback(const FeedbackConstPtr &)\n {\n std::unique_lock<std::mutex> lock(mtx_);\n have_feedback_ = true;\n }\n\n bool wait_for_feedback()\n {\n for (size_t i = 0; i < ATTEMPTS; ++i) {\n ros::spinOnce();\n std::this_thread::sleep_for(DELAY);\n std::unique_lock<std::mutex> lock(mtx_);\n if (have_feedback_) {\n break;\n }\n }\n std::unique_lock<std::mutex> lock(mtx_);\n return have_feedback_;\n }\n};\n\nstd::shared_ptr<actionlib::SimpleActionClient<actionlib::TwoIntsAction>>\nsend_goal(\n const std::string & server_name,\n FeedbackCallback * cb = nullptr)\n{\n std::shared_ptr<actionlib::SimpleActionClient<actionlib::TwoIntsAction>> ac;\n ac.reset(new actionlib::SimpleActionClient<actionlib::TwoIntsAction>(server_name, true));\n\n for (size_t i = 0; i < ATTEMPTS && !ac->isServerConnected(); ++i) {\n ros::spinOnce();\n std::this_thread::sleep_for(DELAY);\n }\n if (!ac->isServerConnected()) {\n ac.reset();\n } else {\n actionlib::TwoIntsGoal goal;\n goal.a = 2;\n goal.b = 3;\n ac->sendGoal(\n goal,\n actionlib::SimpleActionClient<actionlib::TwoIntsAction>::SimpleDoneCallback(),\n actionlib::SimpleActionClient<actionlib::TwoIntsAction>::SimpleActiveCallback(),\n boost::bind(&FeedbackCallback::feedback_callback, cb, _1));\n }\n return ac;\n}\n\nbool wait_for_result(std::shared_ptr<actionlib::SimpleActionClient<actionlib::TwoIntsAction>> ac)\n{\n for (int i = 0; i < ATTEMPTS; ++i) {\n ros::spinOnce();\n if (ac->getState().isDone()) {\n return true;\n }\n std::this_thread::sleep_for(DELAY);\n }\n return false;\n}\n\nstd::shared_ptr<actionlib::ActionServer<actionlib::TwoIntsAction>>\nmake_server(const std::string & server_name, ActionCallback & callbacks)\n{\n ros::NodeHandle nh;\n std::shared_ptr<actionlib::ActionServer<actionlib::TwoIntsAction>> as;\n as.reset(new actionlib::ActionServer<actionlib::TwoIntsAction>(\n nh, server_name,\n boost::bind(&ActionCallback::goal_callback, &callbacks, _1),\n boost::bind(&ActionCallback::cancel_callback, &callbacks, _1), false));\n as->start();\n return as;\n}\n\nTEST(RealtimeServerGoalHandle, set_aborted)\n{\n ActionCallback callbacks;\n const std::string server_name(\"set_aborted\");\n auto as = make_server(server_name, callbacks);\n\n auto client = send_goal(server_name);\n ASSERT_NE(nullptr, client.get());\n\n ASSERT_TRUE(callbacks.wait_for_handle());\n RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);\n ASSERT_TRUE(rt_handle.valid());\n\n {\n actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);\n result->sum = 42;\n rt_handle.setAborted(result);\n rt_handle.runNonRealtime(ros::TimerEvent());\n }\n\n ASSERT_TRUE(wait_for_result(client));\n auto state = client->getState();\n EXPECT_EQ(state, actionlib::SimpleClientGoalState::ABORTED) << state.toString();\n auto result = client->getResult();\n ASSERT_NE(nullptr, result.get());\n EXPECT_EQ(42, result->sum);\n}\n\nTEST(RealtimeServerGoalHandle, set_canceled)\n{\n ActionCallback callbacks;\n const std::string server_name(\"set_canceled\");\n auto as = make_server(server_name, callbacks);\n\n auto client = send_goal(server_name);\n ASSERT_NE(nullptr, client.get());\n\n ASSERT_TRUE(callbacks.wait_for_handle());\n RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);\n ASSERT_TRUE(rt_handle.valid());\n\n \/\/ Cancel and wait for server to learn about that\n client->cancelGoal();\n for (size_t i = 0; i < ATTEMPTS; ++i) {\n actionlib_msgs::GoalStatus gs = callbacks.handle_.getGoalStatus();\n if (gs.status == actionlib_msgs::GoalStatus::PREEMPTING) {\n break;\n }\n ros::spinOnce();\n std::this_thread::sleep_for(DELAY);\n }\n ASSERT_EQ(callbacks.handle_.getGoalStatus().status, actionlib_msgs::GoalStatus::PREEMPTING);\n\n {\n actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);\n result->sum = 1234;\n rt_handle.setCanceled(result);\n rt_handle.runNonRealtime(ros::TimerEvent());\n }\n\n ASSERT_TRUE(wait_for_result(client));\n auto state = client->getState();\n EXPECT_EQ(state, actionlib::SimpleClientGoalState::PREEMPTED) << state.toString();\n auto result = client->getResult();\n ASSERT_NE(nullptr, result.get());\n EXPECT_EQ(1234, result->sum);\n}\n\nTEST(RealtimeServerGoalHandle, set_succeeded)\n{\n ActionCallback callbacks;\n const std::string server_name(\"set_succeeded\");\n auto as = make_server(server_name, callbacks);\n\n auto client = send_goal(server_name);\n ASSERT_NE(nullptr, client.get());\n\n ASSERT_TRUE(callbacks.wait_for_handle());\n RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);\n ASSERT_TRUE(rt_handle.valid());\n\n {\n actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);\n result->sum = 321;\n rt_handle.setSucceeded(result);\n rt_handle.runNonRealtime(ros::TimerEvent());\n }\n\n ASSERT_TRUE(wait_for_result(client));\n auto state = client->getState();\n EXPECT_EQ(state, actionlib::SimpleClientGoalState::SUCCEEDED) << state.toString();\n auto result = client->getResult();\n ASSERT_NE(nullptr, result.get());\n EXPECT_EQ(321, result->sum);\n}\n\nTEST(RealtimeServerGoalHandle, send_feedback)\n{\n ActionCallback callbacks;\n FeedbackCallback client_callbacks;\n const std::string server_name(\"send_feedback\");\n auto as = make_server(server_name, callbacks);\n\n auto client = send_goal(server_name, &client_callbacks);\n ASSERT_NE(nullptr, client.get());\n\n ASSERT_TRUE(callbacks.wait_for_handle());\n RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);\n ASSERT_TRUE(rt_handle.valid());\n\n {\n actionlib::TwoIntsFeedback::Ptr fb(new actionlib::TwoIntsFeedback());\n rt_handle.setFeedback(fb);\n rt_handle.runNonRealtime(ros::TimerEvent());\n }\n\n EXPECT_TRUE(client_callbacks.wait_for_feedback());\n}\n\nint main(int argc, char ** argv) {\n ::testing::InitGoogleTest(&argc, argv);\n ros::init(argc, argv, \"realtime_server_goal_handle_tests\");\n return RUN_ALL_TESTS();\n}\n<commit_msg>Remove unnecessary whitespace<commit_after>\/*\n * Copyright (c) 2019, Open Source Robotics Foundation, Inc.\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 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 the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. 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 \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <gtest\/gtest.h>\n#include <realtime_tools\/realtime_server_goal_handle.h>\n#include <actionlib\/client\/simple_action_client.h>\n#include <actionlib\/TwoIntsAction.h>\n#include <chrono>\n#include <memory>\n#include <mutex>\n#include <thread>\n\nusing realtime_tools::RealtimeServerGoalHandle;\n\nconst size_t ATTEMPTS = 10;\nconst std::chrono::milliseconds DELAY(250);\n\nstruct ActionCallback\n{\n using GoalHandle = actionlib::ActionServer<actionlib::TwoIntsAction>::GoalHandle;\n bool have_handle_ = false;\n GoalHandle handle_;\n std::mutex mtx_;\n\n void goal_callback(GoalHandle handle)\n {\n std::unique_lock<std::mutex> lock(mtx_);\n handle_ = handle;\n handle_.setAccepted();\n have_handle_ = true;\n }\n\n void cancel_callback(GoalHandle handle)\n {\n }\n\n bool wait_for_handle()\n {\n for (size_t i = 0; i < ATTEMPTS; ++i) {\n ros::spinOnce();\n std::this_thread::sleep_for(DELAY);\n std::unique_lock<std::mutex> lock(mtx_);\n if (have_handle_) {\n break;\n }\n }\n std::unique_lock<std::mutex> lock(mtx_);\n return have_handle_;\n }\n};\n\nstruct FeedbackCallback\n{\n bool have_feedback_ = false;\n std::mutex mtx_;\n\n using FeedbackConstPtr = actionlib::ActionServer<actionlib::TwoIntsAction>::FeedbackConstPtr;\n void feedback_callback(const FeedbackConstPtr &)\n {\n std::unique_lock<std::mutex> lock(mtx_);\n have_feedback_ = true;\n }\n\n bool wait_for_feedback()\n {\n for (size_t i = 0; i < ATTEMPTS; ++i) {\n ros::spinOnce();\n std::this_thread::sleep_for(DELAY);\n std::unique_lock<std::mutex> lock(mtx_);\n if (have_feedback_) {\n break;\n }\n }\n std::unique_lock<std::mutex> lock(mtx_);\n return have_feedback_;\n }\n};\n\nstd::shared_ptr<actionlib::SimpleActionClient<actionlib::TwoIntsAction>>\nsend_goal(\n const std::string & server_name,\n FeedbackCallback * cb = nullptr)\n{\n std::shared_ptr<actionlib::SimpleActionClient<actionlib::TwoIntsAction>> ac;\n ac.reset(new actionlib::SimpleActionClient<actionlib::TwoIntsAction>(server_name, true));\n\n for (size_t i = 0; i < ATTEMPTS && !ac->isServerConnected(); ++i) {\n ros::spinOnce();\n std::this_thread::sleep_for(DELAY);\n }\n if (!ac->isServerConnected()) {\n ac.reset();\n } else {\n actionlib::TwoIntsGoal goal;\n goal.a = 2;\n goal.b = 3;\n ac->sendGoal(\n goal,\n actionlib::SimpleActionClient<actionlib::TwoIntsAction>::SimpleDoneCallback(),\n actionlib::SimpleActionClient<actionlib::TwoIntsAction>::SimpleActiveCallback(),\n boost::bind(&FeedbackCallback::feedback_callback, cb, _1));\n }\n return ac;\n}\n\nbool wait_for_result(std::shared_ptr<actionlib::SimpleActionClient<actionlib::TwoIntsAction>> ac)\n{\n for (int i = 0; i < ATTEMPTS; ++i) {\n ros::spinOnce();\n if (ac->getState().isDone()) {\n return true;\n }\n std::this_thread::sleep_for(DELAY);\n }\n return false;\n}\n\nstd::shared_ptr<actionlib::ActionServer<actionlib::TwoIntsAction>>\nmake_server(const std::string & server_name, ActionCallback & callbacks)\n{\n ros::NodeHandle nh;\n std::shared_ptr<actionlib::ActionServer<actionlib::TwoIntsAction>> as;\n as.reset(new actionlib::ActionServer<actionlib::TwoIntsAction>(\n nh, server_name,\n boost::bind(&ActionCallback::goal_callback, &callbacks, _1),\n boost::bind(&ActionCallback::cancel_callback, &callbacks, _1), false));\n as->start();\n return as;\n}\n\nTEST(RealtimeServerGoalHandle, set_aborted)\n{\n ActionCallback callbacks;\n const std::string server_name(\"set_aborted\");\n auto as = make_server(server_name, callbacks);\n\n auto client = send_goal(server_name);\n ASSERT_NE(nullptr, client.get());\n\n ASSERT_TRUE(callbacks.wait_for_handle());\n RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);\n ASSERT_TRUE(rt_handle.valid());\n\n {\n actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);\n result->sum = 42;\n rt_handle.setAborted(result);\n rt_handle.runNonRealtime(ros::TimerEvent());\n }\n\n ASSERT_TRUE(wait_for_result(client));\n auto state = client->getState();\n EXPECT_EQ(state, actionlib::SimpleClientGoalState::ABORTED) << state.toString();\n auto result = client->getResult();\n ASSERT_NE(nullptr, result.get());\n EXPECT_EQ(42, result->sum);\n}\n\nTEST(RealtimeServerGoalHandle, set_canceled)\n{\n ActionCallback callbacks;\n const std::string server_name(\"set_canceled\");\n auto as = make_server(server_name, callbacks);\n\n auto client = send_goal(server_name);\n ASSERT_NE(nullptr, client.get());\n\n ASSERT_TRUE(callbacks.wait_for_handle());\n RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);\n ASSERT_TRUE(rt_handle.valid());\n\n \/\/ Cancel and wait for server to learn about that\n client->cancelGoal();\n for (size_t i = 0; i < ATTEMPTS; ++i) {\n actionlib_msgs::GoalStatus gs = callbacks.handle_.getGoalStatus();\n if (gs.status == actionlib_msgs::GoalStatus::PREEMPTING) {\n break;\n }\n ros::spinOnce();\n std::this_thread::sleep_for(DELAY);\n }\n ASSERT_EQ(callbacks.handle_.getGoalStatus().status, actionlib_msgs::GoalStatus::PREEMPTING);\n\n {\n actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);\n result->sum = 1234;\n rt_handle.setCanceled(result);\n rt_handle.runNonRealtime(ros::TimerEvent());\n }\n\n ASSERT_TRUE(wait_for_result(client));\n auto state = client->getState();\n EXPECT_EQ(state, actionlib::SimpleClientGoalState::PREEMPTED) << state.toString();\n auto result = client->getResult();\n ASSERT_NE(nullptr, result.get());\n EXPECT_EQ(1234, result->sum);\n}\n\nTEST(RealtimeServerGoalHandle, set_succeeded)\n{\n ActionCallback callbacks;\n const std::string server_name(\"set_succeeded\");\n auto as = make_server(server_name, callbacks);\n\n auto client = send_goal(server_name);\n ASSERT_NE(nullptr, client.get());\n\n ASSERT_TRUE(callbacks.wait_for_handle());\n RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);\n ASSERT_TRUE(rt_handle.valid());\n\n {\n actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);\n result->sum = 321;\n rt_handle.setSucceeded(result);\n rt_handle.runNonRealtime(ros::TimerEvent());\n }\n\n ASSERT_TRUE(wait_for_result(client));\n auto state = client->getState();\n EXPECT_EQ(state, actionlib::SimpleClientGoalState::SUCCEEDED) << state.toString();\n auto result = client->getResult();\n ASSERT_NE(nullptr, result.get());\n EXPECT_EQ(321, result->sum);\n}\n\nTEST(RealtimeServerGoalHandle, send_feedback)\n{\n ActionCallback callbacks;\n FeedbackCallback client_callbacks;\n const std::string server_name(\"send_feedback\");\n auto as = make_server(server_name, callbacks);\n\n auto client = send_goal(server_name, &client_callbacks);\n ASSERT_NE(nullptr, client.get());\n\n ASSERT_TRUE(callbacks.wait_for_handle());\n RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);\n ASSERT_TRUE(rt_handle.valid());\n\n {\n actionlib::TwoIntsFeedback::Ptr fb(new actionlib::TwoIntsFeedback());\n rt_handle.setFeedback(fb);\n rt_handle.runNonRealtime(ros::TimerEvent());\n }\n\n EXPECT_TRUE(client_callbacks.wait_for_feedback());\n}\n\nint main(int argc, char ** argv) {\n ::testing::InitGoogleTest(&argc, argv);\n ros::init(argc, argv, \"realtime_server_goal_handle_tests\");\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ParallelPartitionCoarsening.cpp\n *\n * Created on: 28.01.2014\n * Author: cls\n *\/\n\n#include \"ParallelPartitionCoarsening.h\"\n#include <omp.h>\n#include \"..\/auxiliary\/Timer.h\"\n#include \"..\/auxiliary\/Log.h\"\n\nnamespace NetworKit {\n\n\nstd::pair<Graph, std::vector<node> > NetworKit::ParallelPartitionCoarsening::run(const Graph& G, const Partition& zeta) {\n\n\tAux::Timer timer;\n\ttimer.start();\n\n\tstd::vector<node> subsetToSuperNode(zeta.upperBound(), none); \/\/ there is one supernode for each subset\n\n\tDEBUG(\"populate map subset -> supernode\");\n\tnode nextNodeId = 0;\n\tG.forNodes([&](node v){\n\t\tindex c = zeta.subsetOf(v);\n\t\tif (subsetToSuperNode[c] == none) {\n\t\t\tsubsetToSuperNode[c] = nextNodeId++;\n\t\t}\n\t});\n\tGraph Ginit(nextNodeId, true); \/\/ initial graph containing supernodes\n\n\tindex z = G.upperNodeIdBound();\n\tstd::vector<node> nodeToSuperNode(z, none);\n\n\t\/\/ set entries node -> supernode\n\tDEBUG(\"set entries node -> supernode\");\n\tG.parallelForNodes([&](node v){\n\t\tnodeToSuperNode[v] = subsetToSuperNode[zeta.subsetOf(v)];\n\t});\n\n\t\/\/ make copies of initial graph\n\tcount nThreads = omp_get_max_threads();\n\tstd::vector<Graph> localGraphs(nThreads, Ginit); \/\/ thread-local graphs\n\n\n\t\/\/ iterate over edges of G and create edges in coarse graph or update edge and node weights in Gcon\n\tDEBUG(\"create edges in coarse graphs\");\n\tG.parallelForWeightedEdges([&](node u, node v, edgeweight ew) {\n\t\tindex t = omp_get_thread_num();\n\n\t\tnode su = nodeToSuperNode[u];\n\t\tnode sv = nodeToSuperNode[v];\n\t\tlocalGraphs.at(t).increaseWeight(su, sv, ew);\n\n\t});\n\n\t\/\/ DEBUG\n\tfor (Graph G : localGraphs) {\n\t\tINFO(\"local graph: \", G.toString());\n\t}\n\t\/\/ DEBUG\n\n\tAux::Timer timer2;\n\ttimer2.start();\n\t\/\/ combine local graphs in parallel\n\tGraph Gcombined(Ginit.numberOfNodes(), true); \/\/\n\n\tstd::vector<count> numEdges(nThreads);\n\n\n\t\/\/ access internals of Graph to write adjacencies\n\tauto threadSafeIncreaseWeight = [&](node u, node v, edgeweight ew) {\n\n\t\tindex vi = Gcombined.indexInOutEdgeArray(u, v);\n\t\tif (vi == none) {\n\t\t\tindex t = omp_get_thread_num();\n\t\t\tif (u == v) {\n\t\t\t\tnumEdges[t] += 2;\n\t\t\t} else {\n\t\t\t\tnumEdges[t] += 1; \/\/ normal edges count half\n\t\t\t}\n\t\t\tGcombined.outDeg[u]++;\n\t\t\tGcombined.outEdges[u].push_back(v);\n\t\t\tGcombined.outEdgeWeights[u].push_back(ew);\n\t\t} else {\n\t\t\tGcombined.outEdgeWeights[u][vi] += ew;\n\t\t}\n\n\t};\n\n\tDEBUG(\"combining graphs\");\n\tGcombined.parallelForNodes([&](node u) {\n\t\tfor (index l = 0; l < nThreads; ++l) {\n\t\t\tlocalGraphs.at(l).forEdgesOf(u, [&](node u, node v) {\n\t\t\t\tTRACE(\"increasing weight of (\", u, v, \") to\", localsGraphs.at(l).weight(u, v));\n\t\t\t\tthreadSafeIncreaseWeight(u, v, localGraphs.at(l).weight(u, v));\n\t\t\t});\n\t\t}\n\t});\n\n\n\t\/\/ ensure consistency of data structure\n\tDEBUG(\"numEdges: \", numEdges);\n\tcount twiceM = std::accumulate(numEdges.begin(), numEdges.end(), 0);\n\tassert (twiceM % 2 == 0);\n\tGcombined.m = (twiceM \/ 2);\n\n\tassert (G.consistencyCheck());\n\n\ttimer2.stop();\n\tINFO(\"combining coarse graphs took \", timer2.elapsedTag());\n\n\ttimer.stop();\n\tINFO(\"parallel coarsening took \", timer.elapsedTag());\n\n\treturn std::make_pair(Gcombined, nodeToSuperNode);\n\n}\n\n} \/* namespace NetworKit *\/\n<commit_msg>minor improvements<commit_after>\/*\n * ParallelPartitionCoarsening.cpp\n *\n * Created on: 28.01.2014\n * Author: cls\n *\/\n\n#include \"ParallelPartitionCoarsening.h\"\n#include <omp.h>\n#include \"..\/auxiliary\/Timer.h\"\n#include \"..\/auxiliary\/Log.h\"\n\nnamespace NetworKit {\n\n\nstd::pair<Graph, std::vector<node> > NetworKit::ParallelPartitionCoarsening::run(const Graph& G, const Partition& zeta) {\n\n\tAux::Timer timer;\n\ttimer.start();\n\n\tstd::vector<node> subsetToSuperNode(zeta.upperBound(), none); \/\/ there is one supernode for each subset\n\n\tDEBUG(\"populate map subset -> supernode\");\n\tnode nextNodeId = 0;\n\tG.forNodes([&](node v){\n\t\tindex c = zeta.subsetOf(v);\n\t\tif (subsetToSuperNode[c] == none) {\n\t\t\tsubsetToSuperNode[c] = nextNodeId++;\n\t\t}\n\t});\n\tGraph Ginit(nextNodeId, true); \/\/ initial graph containing supernodes\n\n\tindex z = G.upperNodeIdBound();\n\tstd::vector<node> nodeToSuperNode(z, none);\n\n\t\/\/ set entries node -> supernode\n\tDEBUG(\"set entries node -> supernode\");\n\tG.parallelForNodes([&](node v){\n\t\tnodeToSuperNode[v] = subsetToSuperNode[zeta.subsetOf(v)];\n\t});\n\n\t\/\/ make copies of initial graph\n\tcount nThreads = omp_get_max_threads();\n\tstd::vector<Graph> localGraphs(nThreads, Ginit); \/\/ thread-local graphs\n\n\n\t\/\/ iterate over edges of G and create edges in coarse graph or update edge and node weights in Gcon\n\tDEBUG(\"create edges in coarse graphs\");\n\tG.parallelForWeightedEdges([&](node u, node v, edgeweight ew) {\n\t\tindex t = omp_get_thread_num();\n\n\t\tnode su = nodeToSuperNode[u];\n\t\tnode sv = nodeToSuperNode[v];\n\t\tlocalGraphs.at(t).increaseWeight(su, sv, ew);\n\n\t});\n\n\t\/\/ TODO: this will destroy any reasonable timing-results, consider replacing INFO() with DEBUG()\n\t\/\/ DEBUG\n\tfor (Graph G : localGraphs) {\n\t\tINFO(\"local graph: \", G.toString());\n\t}\n\t\/\/ DEBUG\n\n\tAux::Timer timer2;\n\ttimer2.start();\n\t\/\/ combine local graphs in parallel\n\tGraph Gcombined(Ginit.numberOfNodes(), true); \/\/\n\n\tstd::vector<count> numEdges(nThreads);\n\n\n\t\/\/ access internals of Graph to write adjacencies\n\tauto threadSafeIncreaseWeight = [&](node u, node v, edgeweight ew) {\n\n\t\tindex vi = Gcombined.indexInOutEdgeArray(u, v);\n\t\tif (vi == none) {\n\t\t\tindex t = omp_get_thread_num();\n\t\t\tif (u == v) {\n\t\t\t\tnumEdges[t] += 2;\n\t\t\t} else {\n\t\t\t\tnumEdges[t] += 1; \/\/ normal edges count half\n\t\t\t}\n\t\t\tGcombined.outDeg[u]++;\n\t\t\tGcombined.outEdges[u].push_back(v);\n\t\t\tGcombined.outEdgeWeights[u].push_back(ew);\n\t\t} else {\n\t\t\tGcombined.outEdgeWeights[u][vi] += ew;\n\t\t}\n\n\t};\n\n\tDEBUG(\"combining graphs\");\n\tGcombined.parallelForNodes([&](node u) {\n\t\tfor (index l = 0; l < nThreads; ++l) {\n\t\t\tlocalGraphs.at(l).forEdgesOf(u, [&](node u, node v) {\n\t\t\t\tTRACE(\"increasing weight of (\", u, v, \") to\", localGraphs.at(l).weight(u, v));\n\t\t\t\tthreadSafeIncreaseWeight(u, v, localGraphs.at(l).weight(u, v));\n\t\t\t});\n\t\t}\n\t});\n\n\n\t\/\/ ensure consistency of data structure\n\tDEBUG(\"numEdges: \", numEdges);\n\tcount twiceM = std::accumulate(numEdges.begin(), numEdges.end(), 0);\n\tassert (twiceM % 2 == 0);\n\tGcombined.m = (twiceM \/ 2);\n\n\tassert (G.consistencyCheck());\n\n\t\/\/ stop both timers before printing\n\ttimer2.stop();\n\ttimer.stop();\n\tINFO(\"combining coarse graphs took \", timer2.elapsedTag());\n\tINFO(\"parallel coarsening took \", timer.elapsedTag());\n\n\treturn {std::move(Gcombined), std::move(nodeToSuperNode)};\n\n}\n\n} \/* namespace NetworKit *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Presentation.cpp\n *\n * Copyright (C) 2009-14 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"Presentation.hpp\"\n\n#include <boost\/regex.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\n#include <core\/FileSerializer.hpp>\n\nusing namespace core;\n\nnamespace session {\nnamespace modules { \nnamespace rmarkdown {\nnamespace presentation {\n\nnamespace {\n\nstruct SlideNavigationItem\n{\n SlideNavigationItem(const std::string& title,\n int indent,\n int index,\n int line)\n : title(title), indent(indent), index(index), line(line)\n {\n }\n\n std::string title;\n int indent;\n int index;\n int line;\n};\n\njson::Value itemAsJson(const SlideNavigationItem& item)\n{\n json::Object slideJson;\n slideJson[\"title\"] = item.title;\n slideJson[\"indent\"] = item.indent;\n slideJson[\"index\"] = item.index;\n slideJson[\"line\"] = item.line;\n return slideJson;\n}\n\n} \/\/ anonymous namespace\n\n\nvoid ammendResults(const std::string& formatName,\n core::FilePath& targetFile,\n int sourceLine,\n json::Object* pResultJson)\n{\n \/\/ provide slide navigation for ioslides_presentation\n if (formatName != \"ioslides_presentation\")\n return;\n\n \/\/ alias for nicer map syntax\n json::Object& resultJson = *pResultJson;\n\n \/\/ read the input file\n std::vector<std::string> lines;\n Error error = core::readStringVectorFromFile(targetFile, &lines, false);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n \/\/ scan the input file looking for headers and slide breaks\n int totalSlides = 0;\n std::vector<SlideNavigationItem> slideNavigationItems;\n bool inCode = false;\n bool inYaml = false;\n bool haveTitle = false;\n boost::regex reYaml(\"^\\\\-{3}\\\\s*$\");\n boost::regex reTitle(\"^title\\\\:(.*)$\");\n boost::regex reCode(\"^`{3,}.*$\");\n boost::regex reTitledSlide(\"^#(#)?([^|\\\\{]+).*$\");\n boost::regex reUntitledSlide(\"^(\\\\-{4,}|\\\\*{4,})\\\\w*$\");\n for (int i = 0; i<lines.size(); i++)\n {\n \/\/ alias line\n const std::string& line = lines.at(i);\n\n \/\/ toggle code state\n if (boost::regex_search(line, reCode))\n inCode = !inCode;\n\n \/\/ bail if we are in code\n if (inCode)\n continue;\n\n \/\/ toggle yaml state\n if (boost::regex_search(line, reYaml))\n {\n if (!inYaml)\n {\n inYaml = true;\n }\n else if (inYaml && !haveTitle) \/\/ no title found in first\n \/\/ yaml block, bail\n {\n break;\n }\n }\n\n \/\/ look for a title if we don't have one\n if (!haveTitle)\n {\n \/\/ titles only valid in yaml\n if (inYaml)\n {\n boost::smatch match;\n if (boost::regex_search(line, match, reTitle))\n {\n std::string title = match[1];\n boost::algorithm::trim(title);\n string_utils::stripQuotes(&title);\n if (title.empty())\n title = \"Untitled Slide\";\n SlideNavigationItem item(title, 0, totalSlides++, 1);\n slideNavigationItems.push_back(item);\n haveTitle = true;\n\n }\n }\n }\n \/\/ if we already have the title look for slides\n else\n {\n \/\/ titled slides\n boost::smatch match;\n if (boost::regex_search(line, match, reTitledSlide))\n {\n std::string title = match[2];\n boost::algorithm::trim(title);\n if (title.empty())\n title = \"Untitled Slide\";\n\n int indent = std::string(match[1]).empty() ? 0 : 1;\n SlideNavigationItem item(title, indent, totalSlides++, i+1);\n slideNavigationItems.push_back(item);\n }\n \/\/ untitled slides\n else if (boost::regex_search(line, reUntitledSlide))\n {\n SlideNavigationItem item(\"Untitled Slide\", 1, totalSlides++, i+1);\n slideNavigationItems.push_back(item);\n }\n }\n }\n\n \/\/ did we find slides?\n if (totalSlides > 0)\n {\n \/\/ determine which slide the cursor is on\n int previewSlide = 1;\n for (int i = (slideNavigationItems.size()-1); i>=0; i--)\n {\n const SlideNavigationItem& item = slideNavigationItems.at(i);\n if (sourceLine >= item.line)\n {\n previewSlide = item.index + 1;\n break;\n }\n }\n\n \/\/ return as json\n resultJson[\"preview_slide\"] = previewSlide;\n json::Array jsonSlideNavigationItems;\n std::transform(slideNavigationItems.begin(),\n slideNavigationItems.end(),\n std::back_inserter(jsonSlideNavigationItems),\n itemAsJson);\n json::Object jsonSlideNavigation;\n jsonSlideNavigation[\"total_slides\"] = totalSlides;\n jsonSlideNavigation[\"items\"] = jsonSlideNavigationItems;\n resultJson[\"slide_navigation\"] = jsonSlideNavigation;\n }\n}\n\n\n} \/\/ namespace presentation\n} \/\/ namepsace rmarkdown\n} \/\/ namespace modules\n} \/\/ namesapce session\n\n<commit_msg>quiet compiler warning on gcc<commit_after>\/*\n * Presentation.cpp\n *\n * Copyright (C) 2009-14 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"Presentation.hpp\"\n\n#include <boost\/regex.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\n#include <core\/FileSerializer.hpp>\n\nusing namespace core;\n\nnamespace session {\nnamespace modules { \nnamespace rmarkdown {\nnamespace presentation {\n\nnamespace {\n\nstruct SlideNavigationItem\n{\n SlideNavigationItem(const std::string& title,\n int indent,\n int index,\n int line)\n : title(title), indent(indent), index(index), line(line)\n {\n }\n\n std::string title;\n int indent;\n int index;\n int line;\n};\n\njson::Value itemAsJson(const SlideNavigationItem& item)\n{\n json::Object slideJson;\n slideJson[\"title\"] = item.title;\n slideJson[\"indent\"] = item.indent;\n slideJson[\"index\"] = item.index;\n slideJson[\"line\"] = item.line;\n return slideJson;\n}\n\n} \/\/ anonymous namespace\n\n\nvoid ammendResults(const std::string& formatName,\n core::FilePath& targetFile,\n int sourceLine,\n json::Object* pResultJson)\n{\n \/\/ provide slide navigation for ioslides_presentation\n if (formatName != \"ioslides_presentation\")\n return;\n\n \/\/ alias for nicer map syntax\n json::Object& resultJson = *pResultJson;\n\n \/\/ read the input file\n std::vector<std::string> lines;\n Error error = core::readStringVectorFromFile(targetFile, &lines, false);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n \/\/ scan the input file looking for headers and slide breaks\n int totalSlides = 0;\n std::vector<SlideNavigationItem> slideNavigationItems;\n bool inCode = false;\n bool inYaml = false;\n bool haveTitle = false;\n boost::regex reYaml(\"^\\\\-{3}\\\\s*$\");\n boost::regex reTitle(\"^title\\\\:(.*)$\");\n boost::regex reCode(\"^`{3,}.*$\");\n boost::regex reTitledSlide(\"^#(#)?([^|\\\\{]+).*$\");\n boost::regex reUntitledSlide(\"^(\\\\-{4,}|\\\\*{4,})\\\\w*$\");\n for (unsigned i = 0; i<lines.size(); i++)\n {\n \/\/ alias line\n const std::string& line = lines.at(i);\n\n \/\/ toggle code state\n if (boost::regex_search(line, reCode))\n inCode = !inCode;\n\n \/\/ bail if we are in code\n if (inCode)\n continue;\n\n \/\/ toggle yaml state\n if (boost::regex_search(line, reYaml))\n {\n if (!inYaml)\n {\n inYaml = true;\n }\n else if (inYaml && !haveTitle) \/\/ no title found in first\n \/\/ yaml block, bail\n {\n break;\n }\n }\n\n \/\/ look for a title if we don't have one\n if (!haveTitle)\n {\n \/\/ titles only valid in yaml\n if (inYaml)\n {\n boost::smatch match;\n if (boost::regex_search(line, match, reTitle))\n {\n std::string title = match[1];\n boost::algorithm::trim(title);\n string_utils::stripQuotes(&title);\n if (title.empty())\n title = \"Untitled Slide\";\n SlideNavigationItem item(title, 0, totalSlides++, 1);\n slideNavigationItems.push_back(item);\n haveTitle = true;\n\n }\n }\n }\n \/\/ if we already have the title look for slides\n else\n {\n \/\/ titled slides\n boost::smatch match;\n if (boost::regex_search(line, match, reTitledSlide))\n {\n std::string title = match[2];\n boost::algorithm::trim(title);\n if (title.empty())\n title = \"Untitled Slide\";\n\n int indent = std::string(match[1]).empty() ? 0 : 1;\n SlideNavigationItem item(title, indent, totalSlides++, i+1);\n slideNavigationItems.push_back(item);\n }\n \/\/ untitled slides\n else if (boost::regex_search(line, reUntitledSlide))\n {\n SlideNavigationItem item(\"Untitled Slide\", 1, totalSlides++, i+1);\n slideNavigationItems.push_back(item);\n }\n }\n }\n\n \/\/ did we find slides?\n if (totalSlides > 0)\n {\n \/\/ determine which slide the cursor is on\n int previewSlide = 1;\n for (int i = (slideNavigationItems.size()-1); i>=0; i--)\n {\n const SlideNavigationItem& item = slideNavigationItems.at(i);\n if (sourceLine >= item.line)\n {\n previewSlide = item.index + 1;\n break;\n }\n }\n\n \/\/ return as json\n resultJson[\"preview_slide\"] = previewSlide;\n json::Array jsonSlideNavigationItems;\n std::transform(slideNavigationItems.begin(),\n slideNavigationItems.end(),\n std::back_inserter(jsonSlideNavigationItems),\n itemAsJson);\n json::Object jsonSlideNavigation;\n jsonSlideNavigation[\"total_slides\"] = totalSlides;\n jsonSlideNavigation[\"items\"] = jsonSlideNavigationItems;\n resultJson[\"slide_navigation\"] = jsonSlideNavigation;\n }\n}\n\n\n} \/\/ namespace presentation\n} \/\/ namepsace rmarkdown\n} \/\/ namespace modules\n} \/\/ namesapce session\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ rbtree.cpp\n\/\/ rbtree\n\/\/\n\/\/ Created by Sunil on 3\/22\/17.\n\/\/ Copyright © 2017 Sunil. All rights reserved.\n\/\/\n\n#include \"rbtree.hpp\"\n\n#include <list>\n#include <tuple>\n#include <stack>\n#include <queue>\n#include <iostream>\n\nusing namespace std;\n\nrbtree::rbtree() {\n root = nullptr;\n}\n\nrbtree::~rbtree() {\n remove_all(root);\n}\n\nvoid rbtree::remove_all(rbnode* node) {\n if (!node) {\n \/\/ no node to delete\n return;\n }\n \n if (node->left)\n remove_all(node->left);\n if (node->right)\n remove_all(node->right);\n \n delete node;\n}\n\nbool rbtree::violates(bool constraint) {\n \/\/ just negate the constraint and return\n return !constraint;\n}\n\nvoid rbtree::insert(int key) {\n auto node = new rbnode(key, rbcolor::black);\n if (!root) {\n \/\/ empty tree. first node to add.\n \/\/ create a black node and add it to the rbtree.\n root = node;\n return;\n }\n \n auto temp = root;\n rbnode* parent = nullptr;\n \n \/\/ add node as you would in a BST.\n while(temp) {\n parent = temp;\n if (key > temp->key)\n temp = temp->right;\n else\n temp = temp->left;\n }\n \n \/\/ parent shouldn't be nullptr at this point.\n node->parent = parent;\n if (key > parent->key)\n parent->right = node;\n else\n parent->left = node;\n \n \/\/ adding node would have disturbed the rb tree.\n \/\/ Retore the it's properties by rebalancing it.\n balance(node);\n}\n\nbool rbtree::has_only_red_black_nodes(rbnode* node) {\n if (!node) {\n \/\/ no nodes, no color.\n return false;\n }\n \n \/\/ use any tree traversal and check the color\n \n \/\/ everynode has to be red or black.\n if (!node->is_red_node() && !node->is_black_node()) {\n \/\/ this node is neither red nor black. It's a invalid rb tree.\n return false;\n }\n \n \/\/ node has red\/black color but doesn't have left or right subtree.\n if (!node->left && !node->right) {\n return true;\n }\n \n \/\/ only right subtree is available.\n if (!node->left && node->right) {\n return has_only_red_black_nodes(node->right);\n }\n \n \/\/ only left subtree is available.\n if (!node->right && node->left) {\n return has_only_red_black_nodes(node->left);\n }\n \n \/\/ Both left \"and\" right subtree should have only red\/black nodes.\n return (\n has_only_red_black_nodes(node->left) && has_only_red_black_nodes(node->right)\n );\n}\n\nbool rbtree::rednode_has_black_children(rbnode* parent) {\n if (!parent) {\n \/\/ no node, no children. Nothing to check\n return false;\n }\n \n \/\/ if node is red, then check it's children\n if (parent->is_red_node()) {\n \n \/\/ if left and right children are null treat them as black.\n if (!parent->left && !parent->right) {\n return true;\n }\n \n \/\/ both left and right are available.\n if ((parent->left && parent->left->is_red_node())\n || (parent->right && parent->right->is_red_node())) {\n return false;\n }\n \n \/\/ left child is not null. make sure its color is black\n if (parent->left && parent->left->is_red_node()) {\n \/\/ left child is not black.\n return false;\n }\n \n \/\/ right child is not null. make sure its color is black\n if (parent->right && parent->right->is_red_node()) {\n \/\/ right child is not black.\n return false;\n }\n }\n \n \n \/\/ only right subtree is available.\n if (!parent->left && parent->right) {\n return has_only_red_black_nodes(parent->right);\n }\n \n \/\/ only left subtree is available.\n if (!parent->right && parent->left) {\n return has_only_red_black_nodes(parent->left);\n }\n \n \/\/ Both left \"and\" right subtree\n return (\n has_only_red_black_nodes(parent->left) && has_only_red_black_nodes(parent->right)\n );\n}\n\nbool rbtree::has_equal_black_nodes_all_path(rbnode* parent) {\n \/\/ do a depth first search traversal and count the black nodes\n \/\/ along all path from root to leaf node.\n if (!parent) {\n \/\/ no nodes. return true or false ?\n return true;\n }\n \/\/ stack of tuple of (node, count of black nodes) pair.\n stack<tuple<rbnode*, int>> stk;\n list<int> paths;\n \n auto count_if_black = [](rbnode* node) {\n return (node->is_black_node() ? 1 : 0);\n };\n \n stk.push(make_tuple(parent, count_if_black(parent)));\n \n while (!stk.empty()) {\n auto pair = stk.top();\n stk.pop();\n \n auto node = std::get<0>(pair);\n auto count = std::get<1>(pair);\n \n if (node->right) {\n auto right = node->right;\n stk.push(make_tuple(right, count + count_if_black(right)));\n } else {\n \/\/ right child is null. count it as a black node.\n paths.push_front(count + 1);\n }\n \n if (node->left) {\n auto left = node->left;\n stk.push(make_tuple(left, count + count_if_black(left)));\n } else {\n \/\/ left child is null. count it as a black node.\n paths.push_front(count + 1);\n }\n }\n \n \/\/ now check if black node count on all paths are same.\n auto first = paths.front();\n \n#if DEBUG\n for (auto count : paths) cout << count << \"|\";\n cout << endl;\n#endif\n \n for (auto count : paths) {\n if (count != first)\n return false;\n }\n \n \n return true;\n}\n\nbool rbtree::is_valid_rbtree() {\n \/\/ rb tree properties:\n \/\/ P.1: every node is red\/black.\n \/\/ P.2: root is always black.\n \/\/ P.3: leaf nodes are black.\n \/\/ P.4: red node should have only black children.\n \/\/ P.5: for any node x, # of black nodes along all\n \/\/ paths from x to leaf nodes should be the same.\n \n if (!root) {\n \/\/ no nodes in the tree, is a valid RB tree\n return true;\n }\n \n \/\/ P.1: check if all nodes are red\/ black.\n if (violates(has_only_red_black_nodes(root))) {\n \/\/ some nodes are of different color. It's not a red black tree\n return false;\n }\n \n \/\/ P.2: If root is not black then it's invalid.\n if (violates(root->is_black_node()))\n return false;\n \n \/\/ P.3: I take all null nodes to be black.\n \/\/ I treat all null nodes as black. So I don't have to\n \/\/ check for black null nodes.\n \n \/\/ P.4: all red nodes should have black children.\n if (violates(rednode_has_black_children(root))) {\n \/\/ some\/all of red nodes doesn't have a black children\n return false;\n }\n \n \/\/ P.5: check #black nodes along all possible path from root\n \/\/ to leaf nodes.\n if (violates(has_equal_black_nodes_all_path(root))) {\n \/\/ unequal number of black nodes.\n return false;\n }\n \n return true;\n}\n\nrbnode* rbtree::search(int key) {\n if (!root) {\n \/\/ no nodes.\n return nullptr;\n }\n auto node = root;\n while(node) {\n if (node->key == key)\n return node;\n else if (key < node->key)\n node = node->left;\n else\n node = node->right;\n }\n \n return nullptr;\n}\n\nvoid rbtree::bfs() {\n \/\/ breadth first search traversal.\n if (!root) {\n cout << \"rb tree is empty\" << endl;\n return;\n }\n \n deque<rbnode*> queue;\n queue.push_back(root);\n \n while(!queue.empty()) {\n auto node = queue.front();\n queue.pop_front();\n \n cout << node->key << endl;\n \n if (node->left) {\n queue.push_back(node->left);\n }\n \n if (node->right) {\n queue.push_back(node->right);\n }\n }\n \n}\n\nvoid rbtree::dfs() {\n \/\/ depth first search traversal.\n if (!root) {\n cout << \"rb tree is empty!\" << endl;\n return;\n }\n \n stack<rbnode*> stk;\n stk.push(root);\n \n while (!stk.empty()) {\n auto node = stk.top();\n stk.pop();\n \n cout << node->key << endl;\n \n if (node->right) {\n auto right = node->right;\n stk.push(right);\n }\n \n if (node->left) {\n auto left = node->left;\n stk.push(left);\n }\n }\n}\n\nvoid rbtree::prune(int min, int max) {\n throw new runtime_error(\"not implemented\");\n}\n\nvoid rbtree::balance(rbnode* node) {\n throw new runtime_error(\"not implemented\");\n}\n\nvoid rbtree::right_rotate(rbnode* y) {\n \/*\n y x\n \/ \\ right rotate around y \/ \\\n x c -----------------------> a y\n \/ \\ \/ \\\n a b b c\n \n *\/\n \n auto x = y->left;\n auto c = y->right;\n \n \/\/ get right subtree of x if available.\n \/\/ otherwise set it to nullptr.\n auto b = x ? x->right : nullptr;\n \n \/\/ turn x's right subtree into a y's left subtree.\n y->left = b;\n \n if (b) {\n b->parent = y;\n }\n \n \/\/ set parent of x to y's parent.\n x->parent = y->parent;\n \n \/\/ if y doesn't have a parent, make x as root.\n if (!y->parent) {\n root = x;\n }\n \/\/ parent is not null, see if y is to left\/right of parent.\n else if (y->parent->left == y) {\n y->parent->left = x;\n }\n else {\n y->parent->right = x;\n }\n \n y->left = b;\n y->parent = x;\n}\n\nvoid rbtree::left_rotate(rbnode* x) {\n \/*\n x y\n \/ \\ left rotate around x \/ \\\n a y ------------------------> x c\n \/ \\ \/ \\\n b c a b\n *\/\n \n auto y = x->right;\n auto a = x->left;\n \n \/\/ get left subtree of y if available.\n \/\/ otherwise set it to nullptr.\n auto b = y ? y->left : nullptr;\n \n \/\/ no need to get c, as it stays unaffected by left rotation.\n \n \/\/ turn y's left subtree into a x's right subtree.\n x->right = b;\n if (b) {\n b->parent = x;\n }\n \n \/\/ set parent of y to x's parent.\n y->parent = x->parent;\n \n \/\/ if x doesn't have a parent, make y as root.\n if (!x->parent) {\n root = y;\n }\n \/\/ parent is not null, see if x is to left\/right of parent.\n else if (x->parent->left == x) {\n x->parent->left = y;\n }\n else {\n x->parent->right = y;\n }\n \n x->left = a;\n x->parent = y;\n}\n\nvoid rbtree::remove(int key) {\n \/\/ TODO: after removing the node, rebalance the tree.\n throw new runtime_error(\"not implemented\");\n}\n<commit_msg>bug fix for right rotation of tree<commit_after>\/\/\n\/\/ rbtree.cpp\n\/\/ rbtree\n\/\/\n\/\/ Created by Sunil on 3\/22\/17.\n\/\/ Copyright © 2017 Sunil. All rights reserved.\n\/\/\n\n#include \"rbtree.hpp\"\n\n#include <list>\n#include <tuple>\n#include <stack>\n#include <queue>\n#include <iostream>\n\nusing namespace std;\n\nrbtree::rbtree() {\n root = nullptr;\n}\n\nrbtree::~rbtree() {\n remove_all(root);\n}\n\nvoid rbtree::remove_all(rbnode* node) {\n if (!node) {\n \/\/ no node to delete\n return;\n }\n \n if (node->left)\n remove_all(node->left);\n if (node->right)\n remove_all(node->right);\n \n delete node;\n}\n\nbool rbtree::violates(bool constraint) {\n \/\/ just negate the constraint and return\n return !constraint;\n}\n\nvoid rbtree::insert(int key) {\n auto node = new rbnode(key, rbcolor::black);\n if (!root) {\n \/\/ empty tree. first node to add.\n \/\/ create a black node and add it to the rbtree.\n root = node;\n return;\n }\n \n auto temp = root;\n rbnode* parent = nullptr;\n \n \/\/ add node as you would in a BST.\n while(temp) {\n parent = temp;\n if (key > temp->key)\n temp = temp->right;\n else\n temp = temp->left;\n }\n \n \/\/ parent shouldn't be nullptr at this point.\n node->parent = parent;\n if (key > parent->key)\n parent->right = node;\n else\n parent->left = node;\n \n \/\/ adding node would have disturbed the rb tree.\n \/\/ Retore the it's properties by rebalancing it.\n balance(node);\n}\n\nbool rbtree::has_only_red_black_nodes(rbnode* node) {\n if (!node) {\n \/\/ no nodes, no color.\n return false;\n }\n \n \/\/ use any tree traversal and check the color\n \n \/\/ everynode has to be red or black.\n if (!node->is_red_node() && !node->is_black_node()) {\n \/\/ this node is neither red nor black. It's a invalid rb tree.\n return false;\n }\n \n \/\/ node has red\/black color but doesn't have left or right subtree.\n if (!node->left && !node->right) {\n return true;\n }\n \n \/\/ only right subtree is available.\n if (!node->left && node->right) {\n return has_only_red_black_nodes(node->right);\n }\n \n \/\/ only left subtree is available.\n if (!node->right && node->left) {\n return has_only_red_black_nodes(node->left);\n }\n \n \/\/ Both left \"and\" right subtree should have only red\/black nodes.\n return (\n has_only_red_black_nodes(node->left) && has_only_red_black_nodes(node->right)\n );\n}\n\nbool rbtree::rednode_has_black_children(rbnode* parent) {\n if (!parent) {\n \/\/ no node, no children. Nothing to check\n return false;\n }\n \n \/\/ if node is red, then check it's children\n if (parent->is_red_node()) {\n \n \/\/ if left and right children are null treat them as black.\n if (!parent->left && !parent->right) {\n return true;\n }\n \n \/\/ both left and right are available.\n if ((parent->left && parent->left->is_red_node())\n || (parent->right && parent->right->is_red_node())) {\n return false;\n }\n \n \/\/ left child is not null. make sure its color is black\n if (parent->left && parent->left->is_red_node()) {\n \/\/ left child is not black.\n return false;\n }\n \n \/\/ right child is not null. make sure its color is black\n if (parent->right && parent->right->is_red_node()) {\n \/\/ right child is not black.\n return false;\n }\n }\n \n \n \/\/ only right subtree is available.\n if (!parent->left && parent->right) {\n return has_only_red_black_nodes(parent->right);\n }\n \n \/\/ only left subtree is available.\n if (!parent->right && parent->left) {\n return has_only_red_black_nodes(parent->left);\n }\n \n \/\/ Both left \"and\" right subtree\n return (\n has_only_red_black_nodes(parent->left) && has_only_red_black_nodes(parent->right)\n );\n}\n\nbool rbtree::has_equal_black_nodes_all_path(rbnode* parent) {\n \/\/ do a depth first search traversal and count the black nodes\n \/\/ along all path from root to leaf node.\n if (!parent) {\n \/\/ no nodes. return true or false ?\n return true;\n }\n \/\/ stack of tuple of (node, count of black nodes) pair.\n stack<tuple<rbnode*, int>> stk;\n list<int> paths;\n \n auto count_if_black = [](rbnode* node) {\n return (node->is_black_node() ? 1 : 0);\n };\n \n stk.push(make_tuple(parent, count_if_black(parent)));\n \n while (!stk.empty()) {\n auto pair = stk.top();\n stk.pop();\n \n auto node = std::get<0>(pair);\n auto count = std::get<1>(pair);\n \n if (node->right) {\n auto right = node->right;\n stk.push(make_tuple(right, count + count_if_black(right)));\n } else {\n \/\/ right child is null. count it as a black node.\n paths.push_front(count + 1);\n }\n \n if (node->left) {\n auto left = node->left;\n stk.push(make_tuple(left, count + count_if_black(left)));\n } else {\n \/\/ left child is null. count it as a black node.\n paths.push_front(count + 1);\n }\n }\n \n \/\/ now check if black node count on all paths are same.\n auto first = paths.front();\n \n#if DEBUG\n for (auto count : paths) cout << count << \"|\";\n cout << endl;\n#endif\n \n for (auto count : paths) {\n if (count != first)\n return false;\n }\n \n \n return true;\n}\n\nbool rbtree::is_valid_rbtree() {\n \/\/ rb tree properties:\n \/\/ P.1: every node is red\/black.\n \/\/ P.2: root is always black.\n \/\/ P.3: leaf nodes are black.\n \/\/ P.4: red node should have only black children.\n \/\/ P.5: for any node x, # of black nodes along all\n \/\/ paths from x to leaf nodes should be the same.\n \n if (!root) {\n \/\/ no nodes in the tree, is a valid RB tree\n return true;\n }\n \n \/\/ P.1: check if all nodes are red\/ black.\n if (violates(has_only_red_black_nodes(root))) {\n \/\/ some nodes are of different color. It's not a red black tree\n return false;\n }\n \n \/\/ P.2: If root is not black then it's invalid.\n if (violates(root->is_black_node()))\n return false;\n \n \/\/ P.3: I take all null nodes to be black.\n \/\/ I treat all null nodes as black. So I don't have to\n \/\/ check for black null nodes.\n \n \/\/ P.4: all red nodes should have black children.\n if (violates(rednode_has_black_children(root))) {\n \/\/ some\/all of red nodes doesn't have a black children\n return false;\n }\n \n \/\/ P.5: check #black nodes along all possible path from root\n \/\/ to leaf nodes.\n if (violates(has_equal_black_nodes_all_path(root))) {\n \/\/ unequal number of black nodes.\n return false;\n }\n \n return true;\n}\n\nrbnode* rbtree::search(int key) {\n if (!root) {\n \/\/ no nodes.\n return nullptr;\n }\n auto node = root;\n while(node) {\n if (node->key == key)\n return node;\n else if (key < node->key)\n node = node->left;\n else\n node = node->right;\n }\n \n return nullptr;\n}\n\nvoid rbtree::bfs() {\n \/\/ breadth first search traversal.\n if (!root) {\n cout << \"rb tree is empty\" << endl;\n return;\n }\n \n deque<rbnode*> queue;\n queue.push_back(root);\n \n while(!queue.empty()) {\n auto node = queue.front();\n queue.pop_front();\n \n cout << node->key << endl;\n \n if (node->left) {\n queue.push_back(node->left);\n }\n \n if (node->right) {\n queue.push_back(node->right);\n }\n }\n \n}\n\nvoid rbtree::dfs() {\n \/\/ depth first search traversal.\n if (!root) {\n cout << \"rb tree is empty!\" << endl;\n return;\n }\n \n stack<rbnode*> stk;\n stk.push(root);\n \n while (!stk.empty()) {\n auto node = stk.top();\n stk.pop();\n \n cout << node->key << endl;\n \n if (node->right) {\n auto right = node->right;\n stk.push(right);\n }\n \n if (node->left) {\n auto left = node->left;\n stk.push(left);\n }\n }\n}\n\nvoid rbtree::prune(int min, int max) {\n throw new runtime_error(\"not implemented\");\n}\n\nvoid rbtree::balance(rbnode* node) {\n throw new runtime_error(\"not implemented\");\n}\n\nvoid rbtree::right_rotate(rbnode* y) {\n \/*\n y x\n \/ \\ right rotate around y \/ \\\n x c -----------------------> a y\n \/ \\ \/ \\\n a b b c\n \n *\/\n \n auto x = y->left;\n \n \/\/ get right subtree of x if available.\n \/\/ otherwise set it to nullptr.\n auto b = x ? x->right : nullptr;\n \n \/\/ turn x's right subtree into a y's left subtree.\n y->left = b;\n \n if (b) {\n b->parent = y;\n }\n \n \/\/ set parent of x to y's parent.\n x->parent = y->parent;\n \n \/\/ if y doesn't have a parent, make x as root.\n if (!y->parent) {\n root = x;\n }\n \/\/ parent is not null, see if y is to left\/right of parent.\n else if (y->parent->left == y) {\n y->parent->left = x;\n }\n else {\n y->parent->right = x;\n }\n \n x->right = y;\n y->parent = x;\n}\n\nvoid rbtree::left_rotate(rbnode* x) {\n \/*\n x y\n \/ \\ left rotate around x \/ \\\n a y ------------------------> x c\n \/ \\ \/ \\\n b c a b\n *\/\n \n auto y = x->right;\n \n \/\/ get left subtree of y if available.\n \/\/ otherwise set it to nullptr.\n auto b = y ? y->left : nullptr;\n \n \/\/ no need to get c, as it stays unaffected by left rotation.\n \n \/\/ turn y's left subtree into a x's right subtree.\n x->right = b;\n if (b) {\n b->parent = x;\n }\n \n \/\/ set parent of y to x's parent.\n y->parent = x->parent;\n \n \/\/ if x doesn't have a parent, make y as root.\n if (!x->parent) {\n root = y;\n }\n \/\/ parent is not null, see if x is to left\/right of parent.\n else if (x->parent->left == x) {\n x->parent->left = y;\n }\n else {\n x->parent->right = y;\n }\n \n y->left = x;\n x->parent = y;\n}\n\nvoid rbtree::remove(int key) {\n \/\/ TODO: after removing the node, rebalance the tree.\n throw new runtime_error(\"not implemented\");\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef __PX4_NUTTX\n\n#include \"gpio.h\"\n\nconstexpr uint32_t CameraInterfaceGPIO::_gpios[6];\n\nCameraInterfaceGPIO::CameraInterfaceGPIO():\n\tCameraInterface(),\n\t_polarity(0)\n{\n\t_p_polarity = param_find(\"TRIG_POLARITY\");\n\tparam_get(_p_polarity, &_polarity);\n\n\tget_pins();\n\tsetup();\n}\n\nCameraInterfaceGPIO::~CameraInterfaceGPIO()\n{\n}\n\nvoid CameraInterfaceGPIO::setup()\n{\n\tfor (unsigned i = 0; i < arraySize(_pins); i++) {\n\t\t\/\/ Pin range is ranges from 1 to 6\n\t\tif (_pins[i] > 0 && _pins[i] < (int)arraySize(_gpios)) {\n\t\t\tpx4_arch_configgpio(_gpios[_pins[i]]);\n\t\t\tpx4_arch_gpiowrite(_gpios[_pins[i]], !_polarity);\n\t\t}\n\t}\n}\n\nvoid CameraInterfaceGPIO::trigger(bool enable)\n{\n\tif (enable) {\n\t\tfor (unsigned i = 0; i < arraySize(_pins); i++) {\n\t\t\tif (_pins[i] >= 0) {\n\t\t\t\t\/\/ ACTIVE_LOW == 1\n\t\t\t\tpx4_arch_gpiowrite(_gpios[_pins[i]], _polarity);\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tfor (unsigned i = 0; i < arraySize(_pins); i++) {\n\t\t\tif (_pins[i] >= 0) {\n\t\t\t\t\/\/ ACTIVE_LOW == 1\n\t\t\t\tpx4_arch_gpiowrite(_gpios[_pins[i]], !_polarity);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CameraInterfaceGPIO::info()\n{\n\tPX4_INFO(\"GPIO trigger mode, pins enabled : [%d][%d][%d][%d][%d][%d], polarity : %s\",\n\t\t _pins[5], _pins[4], _pins[3], _pins[2], _pins[1], _pins[0],\n\t\t _polarity ? \"ACTIVE_HIGH\" : \"ACTIVE_LOW\");\n}\n\n#endif \/* ifdef __PX4_NUTTX *\/\n<commit_msg>fix camera_trigger gpio: _pins[i] == 0 is valid<commit_after>#ifdef __PX4_NUTTX\n\n#include \"gpio.h\"\n\nconstexpr uint32_t CameraInterfaceGPIO::_gpios[6];\n\nCameraInterfaceGPIO::CameraInterfaceGPIO():\n\tCameraInterface(),\n\t_polarity(0)\n{\n\t_p_polarity = param_find(\"TRIG_POLARITY\");\n\tparam_get(_p_polarity, &_polarity);\n\n\tget_pins();\n\tsetup();\n}\n\nCameraInterfaceGPIO::~CameraInterfaceGPIO()\n{\n}\n\nvoid CameraInterfaceGPIO::setup()\n{\n\tfor (unsigned i = 0; i < arraySize(_pins); i++) {\n\t\t\/\/ Pin range is from 0 to 5\n\t\tif (_pins[i] >= 0 && _pins[i] < (int)arraySize(_gpios)) {\n\t\t\tpx4_arch_configgpio(_gpios[_pins[i]]);\n\t\t\tpx4_arch_gpiowrite(_gpios[_pins[i]], !_polarity);\n\t\t}\n\t}\n}\n\nvoid CameraInterfaceGPIO::trigger(bool enable)\n{\n\tif (enable) {\n\t\tfor (unsigned i = 0; i < arraySize(_pins); i++) {\n\t\t\tif (_pins[i] >= 0 && _pins[i] < (int)arraySize(_gpios)) {\n\t\t\t\t\/\/ ACTIVE_LOW == 1\n\t\t\t\tpx4_arch_gpiowrite(_gpios[_pins[i]], _polarity);\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tfor (unsigned i = 0; i < arraySize(_pins); i++) {\n\t\t\tif (_pins[i] >= 0 && _pins[i] < (int)arraySize(_gpios)) {\n\t\t\t\t\/\/ ACTIVE_LOW == 1\n\t\t\t\tpx4_arch_gpiowrite(_gpios[_pins[i]], !_polarity);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CameraInterfaceGPIO::info()\n{\n\tPX4_INFO(\"GPIO trigger mode, pins enabled : [%d][%d][%d][%d][%d][%d], polarity : %s\",\n\t\t _pins[5], _pins[4], _pins[3], _pins[2], _pins[1], _pins[0],\n\t\t _polarity ? \"ACTIVE_HIGH\" : \"ACTIVE_LOW\");\n}\n\n#endif \/* ifdef __PX4_NUTTX *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef GROUP__BY__HPP\n#define GROUP__BY__HPP\n\n#include \"iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n\n template <typename Container, typename KeyFunc>\n class GroupBy;\n\n template <typename Container, typename KeyFunc>\n GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);\n\n template <typename T, typename KeyFunc>\n GroupBy<std::initializer_list<T>, KeyFunc> groupby(\n std::initializer_list<T>, KeyFunc);\n\n template <typename Container, typename KeyFunc>\n class GroupBy {\n private:\n Container container;\n KeyFunc key_func;\n\n friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);\n\n template <typename T, typename KF>\n friend GroupBy<std::initializer_list<T>, KF> groupby(\n std::initializer_list<T>, KF);\n\n using key_func_ret =\n decltype(std::declval<KeyFunc>()(\n std::declval<iterator_deref<Container>>()));\n\n GroupBy(Container container, KeyFunc key_func)\n : container(std::forward<Container>(container)),\n key_func(key_func)\n { }\n\n public:\n GroupBy() = delete;\n GroupBy(const GroupBy&) = delete;\n GroupBy& operator=(const GroupBy&) = delete;\n GroupBy& operator=(GroupBy&&) = delete;\n\n GroupBy(GroupBy&&) = default;\n\n class Iterator;\n class Group;\n\n class Iterator {\n private:\n iterator_type<Container> sub_iter;\n iterator_type<Container> sub_iter_peek;\n const iterator_type<Container> sub_end;\n KeyFunc key_func;\n\n using KeyGroupPair =\n std::pair<key_func_ret, Group>;\n\n public:\n Iterator (iterator_type<Container> si,\n iterator_type<Container> end,\n KeyFunc key_func)\n : sub_iter{si},\n sub_end{end},\n key_func(key_func)\n { }\n\n KeyGroupPair operator*() {\n return KeyGroupPair(\n this->key_func(*this->sub_iter),\n Group(\n *this, \n this->key_func(*this->sub_iter)));\n }\n\n Iterator& operator++() { \n return *this;\n }\n\n bool operator!=(const Iterator&) const {\n return !this->exhausted();\n }\n\n void increment_iterator() {\n if (this->sub_iter != this->sub_end) {\n ++this->sub_iter;\n }\n }\n\n bool exhausted() const {\n return this->sub_iter == this->sub_end;\n }\n\n iterator_deref<Container> current() const {\n return *this->sub_iter;\n }\n\n key_func_ret next_key() const {\n return this->key_func(*this->sub_iter);\n }\n };\n\n\n class Group {\n private:\n friend Iterator;\n friend class GroupIterator;\n Iterator& owner;\n key_func_ret key;\n\n \/\/ completed is set if a Group is iterated through\n \/\/ completely. It is checked in the destructor, and\n \/\/ if the Group has not been completed, the destructor\n \/\/ exhausts it. This ensures that the next Group starts\n \/\/ at the correct position when the user short-circuits\n \/\/ iteration over a Group.\n \/\/ The move constructor sets the rvalue's completed\n \/\/ attribute to true, so its destructor doesn't do anything\n \/\/ when called.\n mutable bool completed = false;\n\n Group(Iterator& owner, key_func_ret key) :\n owner(owner),\n key(key)\n { }\n\n public:\n ~Group() {\n if (!this->completed) {\n for (auto iter = this->begin(), end = this->end();\n iter != end;\n ++iter) { }\n }\n }\n \n \/\/ movable, non-copyable\n Group() = delete;\n Group(const Group&) = delete;\n Group& operator=(const Group&) = delete;\n Group& operator=(Group&&) = delete;\n\n Group(Group&& other)\n : owner{other.owner},\n key{other.key},\n completed{other.completed} {\n other.completed = true;\n }\n\n class GroupIterator {\n private:\n const key_func_ret key;\n const Group& group;\n\n bool not_at_end() const {\n return !this->group.owner.exhausted()&&\n this->group.owner.next_key() == this->key;\n }\n\n public:\n GroupIterator(const Group& group,\n key_func_ret key)\n : key{key},\n group{group}\n { }\n\n GroupIterator(const GroupIterator&) = default;\n\n bool operator!=(const GroupIterator&) const {\n if (this->not_at_end()) {\n return true;\n } else {\n this->group.completed = true;\n return false;\n }\n }\n\n GroupIterator& operator++() {\n this->group.owner.increment_iterator();\n return *this;\n }\n\n iterator_deref<Container> operator*() const {\n return this->group.owner.current();\n }\n };\n\n GroupIterator begin() {\n return {*this, key};\n }\n\n GroupIterator end() {\n return {*this, key};\n }\n\n };\n\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->key_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->key_func};\n }\n\n };\n\n \/\/ Takes something and returns it, used for default key of comparing\n \/\/ items in the sequence directly\n template <typename Container>\n class ItemReturner {\n public:\n ItemReturner() = default;\n iterator_deref<Container> operator() (\n iterator_deref<Container> item) const {\n return item;\n }\n };\n\n\n template <typename Container, typename KeyFunc>\n GroupBy<Container, KeyFunc> groupby(\n Container&& container, KeyFunc key_func) {\n return {std::forward<Container>(container), key_func};\n }\n\n\n template <typename Container>\n auto groupby(Container&& container) ->\n decltype(groupby(std::forward<Container>(container),\n ItemReturner<Container>())) {\n return groupby(std::forward<Container>(container),\n ItemReturner<Container>());\n }\n\n \n template <typename T, typename KeyFunc>\n GroupBy<std::initializer_list<T>, KeyFunc> groupby(\n std::initializer_list<T> il, KeyFunc key_func) {\n return {std::move(il), key_func};\n }\n\n\n template <typename T>\n auto groupby(std::initializer_list<T> il) ->\n decltype(groupby(std::move(il),\n ItemReturner<std::initializer_list<T>>())) {\n return groupby(\n std::move(il),\n ItemReturner<std::initializer_list<T>>());\n }\n\n}\n\n\n#endif \/\/#ifndef GROUP__BY__HPP\n<commit_msg>const correctness<commit_after>#ifndef GROUP__BY__HPP\n#define GROUP__BY__HPP\n\n#include \"iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n\n template <typename Container, typename KeyFunc>\n class GroupBy;\n\n template <typename Container, typename KeyFunc>\n GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);\n\n template <typename T, typename KeyFunc>\n GroupBy<std::initializer_list<T>, KeyFunc> groupby(\n std::initializer_list<T>, KeyFunc);\n\n template <typename Container, typename KeyFunc>\n class GroupBy {\n private:\n Container container;\n KeyFunc key_func;\n\n friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);\n\n template <typename T, typename KF>\n friend GroupBy<std::initializer_list<T>, KF> groupby(\n std::initializer_list<T>, KF);\n\n using key_func_ret =\n decltype(std::declval<KeyFunc>()(\n std::declval<iterator_deref<Container>>()));\n\n GroupBy(Container container, KeyFunc key_func)\n : container(std::forward<Container>(container)),\n key_func(key_func)\n { }\n\n public:\n GroupBy() = delete;\n GroupBy(const GroupBy&) = delete;\n GroupBy& operator=(const GroupBy&) = delete;\n GroupBy& operator=(GroupBy&&) = delete;\n\n GroupBy(GroupBy&&) = default;\n\n class Iterator;\n class Group;\n\n class Iterator {\n private:\n iterator_type<Container> sub_iter;\n iterator_type<Container> sub_iter_peek;\n const iterator_type<Container> sub_end;\n KeyFunc key_func;\n\n using KeyGroupPair =\n std::pair<key_func_ret, Group>;\n\n public:\n Iterator (iterator_type<Container> si,\n iterator_type<Container> end,\n KeyFunc key_func)\n : sub_iter{si},\n sub_end{end},\n key_func(key_func)\n { }\n\n KeyGroupPair operator*() {\n return KeyGroupPair(\n this->key_func(*this->sub_iter),\n Group(\n *this, \n this->key_func(*this->sub_iter)));\n }\n\n Iterator& operator++() { \n return *this;\n }\n\n bool operator!=(const Iterator&) const {\n return !this->exhausted();\n }\n\n void increment_iterator() {\n if (this->sub_iter != this->sub_end) {\n ++this->sub_iter;\n }\n }\n\n bool exhausted() const {\n return this->sub_iter == this->sub_end;\n }\n\n iterator_deref<Container> current() {\n return *this->sub_iter;\n }\n\n key_func_ret next_key() const {\n return this->key_func(*this->sub_iter);\n }\n };\n\n\n class Group {\n private:\n friend Iterator;\n friend class GroupIterator;\n Iterator& owner;\n key_func_ret key;\n\n \/\/ completed is set if a Group is iterated through\n \/\/ completely. It is checked in the destructor, and\n \/\/ if the Group has not been completed, the destructor\n \/\/ exhausts it. This ensures that the next Group starts\n \/\/ at the correct position when the user short-circuits\n \/\/ iteration over a Group.\n \/\/ The move constructor sets the rvalue's completed\n \/\/ attribute to true, so its destructor doesn't do anything\n \/\/ when called.\n mutable bool completed = false;\n\n Group(Iterator& owner, key_func_ret key) :\n owner(owner),\n key(key)\n { }\n\n public:\n ~Group() {\n if (!this->completed) {\n for (auto iter = this->begin(), end = this->end();\n iter != end;\n ++iter) { }\n }\n }\n \n \/\/ movable, non-copyable\n Group() = delete;\n Group(const Group&) = delete;\n Group& operator=(const Group&) = delete;\n Group& operator=(Group&&) = delete;\n\n Group(Group&& other)\n : owner{other.owner},\n key{other.key},\n completed{other.completed} {\n other.completed = true;\n }\n\n class GroupIterator {\n private:\n const key_func_ret key;\n const Group& group;\n\n bool not_at_end() const {\n return !this->group.owner.exhausted()&&\n this->group.owner.next_key() == this->key;\n }\n\n public:\n GroupIterator(const Group& group,\n key_func_ret key)\n : key{key},\n group{group}\n { }\n\n GroupIterator(const GroupIterator&) = default;\n\n bool operator!=(const GroupIterator&) const {\n if (this->not_at_end()) {\n return true;\n } else {\n this->group.completed = true;\n return false;\n }\n }\n\n GroupIterator& operator++() {\n this->group.owner.increment_iterator();\n return *this;\n }\n\n iterator_deref<Container> operator*() {\n return this->group.owner.current();\n }\n };\n\n GroupIterator begin() {\n return {*this, key};\n }\n\n GroupIterator end() {\n return {*this, key};\n }\n\n };\n\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->key_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->key_func};\n }\n\n };\n\n \/\/ Takes something and returns it, used for default key of comparing\n \/\/ items in the sequence directly\n template <typename Container>\n class ItemReturner {\n public:\n ItemReturner() = default;\n iterator_deref<Container> operator() (\n iterator_deref<Container> item) const {\n return item;\n }\n };\n\n\n template <typename Container, typename KeyFunc>\n GroupBy<Container, KeyFunc> groupby(\n Container&& container, KeyFunc key_func) {\n return {std::forward<Container>(container), key_func};\n }\n\n\n template <typename Container>\n auto groupby(Container&& container) ->\n decltype(groupby(std::forward<Container>(container),\n ItemReturner<Container>())) {\n return groupby(std::forward<Container>(container),\n ItemReturner<Container>());\n }\n\n \n template <typename T, typename KeyFunc>\n GroupBy<std::initializer_list<T>, KeyFunc> groupby(\n std::initializer_list<T> il, KeyFunc key_func) {\n return {std::move(il), key_func};\n }\n\n\n template <typename T>\n auto groupby(std::initializer_list<T> il) ->\n decltype(groupby(std::move(il),\n ItemReturner<std::initializer_list<T>>())) {\n return groupby(\n std::move(il),\n ItemReturner<std::initializer_list<T>>());\n }\n\n}\n\n\n#endif \/\/#ifndef GROUP__BY__HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ This program test streaming through ports.\n\n#include \"mpi.h\"\n#include \"vtkImageReader.h\"\n#include \"vtkSynchronizedTemplates3D.h\"\n#include \"vtkPolyDataCollector.h\"\n#include \"vtkUpStreamPort.h\"\n#include \"vtkDownStreamPort.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkConeSource.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkActor.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkMath.h\"\n#include \"vtkDataInformation.h\"\n\n\n\n\/\/ callback to test streaming \/ ports by seeing what extents are being read in.\nvoid reader_start_callback(void *arg)\n{\n vtkImageReader *reader = (vtkImageReader*)(arg);\n int *e;\n \n e = reader->GetOutput()->GetUpdateExtent();\n \n cerr << \"Reading: \" << e[0] << \", \" << e[1] << \", \" << e[2] << \", \" \n << e[3] << \", \" << e[4] << \", \" << e[5] << endl; \n}\n\n\n\/\/ callback to see if iso has data\nvoid iso_end_callback(void *arg)\n{\n vtkPolyData *out = (vtkPolyData*)(arg);\n \n cerr << \"iso out: \" << *out << endl;\n}\n\n\n\/\/ call back to exit program\n\/\/ This should really be embedded in the controller.\nvoid exit_callback(void *arg, int id)\n{ \n \/\/ clean up controller ?\n exit(0);\n}\n\n\n\nVTK_THREAD_RETURN_TYPE process_a( void *vtkNotUsed(arg) )\n{\n vtkMultiProcessController *controller;\n vtkImageReader *reader;\n vtkSynchronizedTemplates3D *iso;\n \n controller = vtkMultiProcessController::RegisterAndGetGlobalController(NULL);\n \n reader = vtkImageReader::New();\n reader->SetDataByteOrderToLittleEndian();\n reader->SetDataExtent(0, 127, 0, 127, 1, 93);\n reader->SetFilePrefix(\"..\/..\/..\/vtkdata\/headsq\/half\");\n reader->SetDataSpacing(1.6, 1.6, 1.5);\n reader->SetStartMethod(reader_start_callback, (void*)(reader));\n \n iso = vtkSynchronizedTemplates3D::New();\n iso->SetInput(reader->GetOutput());\n iso->SetValue(0, 500);\n iso->ComputeScalarsOff();\n iso->ComputeGradientsOff();\n \/\/iso->SetEndMethod(iso_end_callback, (void*)(iso->GetOutput()));\n \/\/ This should be automatically determined by controller.\n iso->SetNumberOfThreads(1);\n\n \/\/ Send data throug port.\n vtkUpStreamPort *upPort = vtkUpStreamPort::New();\n upPort->SetInput(iso->GetOutput());\n upPort->SetTag(999);\n \n \/\/ last, set up a RMI call backs.\n controller->AddRMI(exit_callback, (void *)iso, 666);\n \n \/\/ wait for the call back to execute.\n upPort->WaitForUpdate();\n \n \/\/ last call never returns, but ...\n upPort->Delete();\n\n return VTK_THREAD_RETURN_VALUE;\n}\n\n\nVTK_THREAD_RETURN_TYPE process_b( void *vtkNotUsed(arg) )\n{\n vtkMultiProcessController *controller;\n vtkDownStreamPort *downPort;\n vtkPolyDataCollector *collector = vtkPolyDataCollector::New();\n vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();\n vtkActor *actor = vtkActor::New();\n vtkRenderer *ren = vtkRenderer::New();\n vtkRenderWindow *renWindow = vtkRenderWindow::New();\n vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();\n vtkCamera *cam = vtkCamera::New();\n int myid, otherid;\n \n controller = vtkMultiProcessController::RegisterAndGetGlobalController(NULL);\n myid = controller->GetLocalProcessId();\n otherid = ( ! myid);\n \n downPort = vtkDownStreamPort::New();\n downPort->SetUpStreamProcessId(otherid);\n downPort->SetTag(999);\n \n collector->SetInput(downPort->GetPolyDataOutput());\n collector->SetInputMemoryLimit(1000);\n \n mapper->SetInput(collector->GetOutput());\n actor->SetMapper(mapper);\n \n putenv(\"DISPLAY=:0.0\");\n \n renWindow->AddRenderer(ren);\n iren->SetRenderWindow(renWindow);\n ren->SetBackground(0.9, 0.9, 0.9);\n renWindow->SetSize( 400, 400);\n \n \/\/ assign our actor to the renderer\n ren->AddActor(actor);\n \n cam->SetFocalPoint(100, 100, 65);\n cam->SetPosition(100, 450, 65);\n cam->SetViewUp(0, 0, -1);\n cam->SetViewAngle(30);\n cam->ComputeViewPlaneNormal();\n \/\/ this was causing an update.\n \/\/ren->ResetCameraClippingRange();\n \/\/{\n \/\/double *range = ren->GetActiveCamera()->GetClippingRange();\n \/\/cerr << range[0] << \", \" << range[1] << endl;\n \/\/}\n cam->SetClippingRange(177.0, 536.0);\n ren->SetActiveCamera(cam);\n \n collector->Update();\n collector->Update();\n cerr << \"WholeMemorySize: \" \n << collector->GetOutput()->GetDataInformation()->GetEstimatedWholeMemorySize()\n << endl;\n \n renWindow->Render();\n \n \/\/ just exit\n \/\/controller->TriggerRMI(otherid, 666); \n \/\/exit(0);\n \n \/\/ Begin mouse interaction\n iren->Start();\n \n \/\/ Clean up\n collector->Delete();\n ren->Delete();\n renWindow->Delete();\n iren->Delete();\n mapper->Delete();\n actor->Delete();\n \n \/\/ clean up objects in all processes.\n controller->UnRegister(NULL);\n\n return VTK_THREAD_RETURN_VALUE;\n}\n\n\nvoid main( int argc, char *argv[] )\n{\n vtkMultiProcessController *controller;\n \n controller = vtkMultiProcessController::RegisterAndGetGlobalController(NULL);\n\n controller->Initialize(argc, argv);\n controller->SetNumberOfProcesses(2);\n controller->SetMultipleMethod(1, process_a, NULL);\n controller->SetMultipleMethod(0, process_b, NULL);\n controller->MultipleMethodExecute();\n\n controller->UnRegister(NULL);\n}\n\n \n\n\n\n\n<commit_msg>input\/output (not up\/down)<commit_after>\/\/ This program test streaming through ports.\n\n#include \"mpi.h\"\n#include \"vtkImageReader.h\"\n#include \"vtkSynchronizedTemplates3D.h\"\n#include \"vtkPolyDataCollector.h\"\n#include \"vtkOutputPort.h\"\n#include \"vtkInputPort.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkConeSource.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkActor.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkMath.h\"\n#include \"vtkDataInformation.h\"\n\n\n\n\/\/ callback to test streaming \/ ports by seeing what extents are being read in.\nvoid reader_start_callback(void *arg)\n{\n vtkImageReader *reader = (vtkImageReader*)(arg);\n int *e;\n \n e = reader->GetOutput()->GetUpdateExtent();\n \n cerr << \"Reading: \" << e[0] << \", \" << e[1] << \", \" << e[2] << \", \" \n << e[3] << \", \" << e[4] << \", \" << e[5] << endl; \n}\n\n\n\/\/ callback to see if iso has data\nvoid iso_end_callback(void *arg)\n{\n vtkPolyData *out = (vtkPolyData*)(arg);\n \n cerr << \"iso out: \" << *out << endl;\n}\n\n\n\/\/ call back to exit program\n\/\/ This should really be embedded in the controller.\nvoid exit_callback(void *arg, int id)\n{ \n \/\/ clean up controller ?\n exit(0);\n}\n\n\n\nVTK_THREAD_RETURN_TYPE process_a( void *vtkNotUsed(arg) )\n{\n vtkMultiProcessController *controller;\n vtkImageReader *reader;\n vtkSynchronizedTemplates3D *iso;\n \n controller = vtkMultiProcessController::RegisterAndGetGlobalController(NULL);\n \n reader = vtkImageReader::New();\n reader->SetDataByteOrderToLittleEndian();\n reader->SetDataExtent(0, 127, 0, 127, 1, 93);\n reader->SetFilePrefix(\"..\/..\/..\/vtkdata\/headsq\/half\");\n reader->SetDataSpacing(1.6, 1.6, 1.5);\n reader->SetStartMethod(reader_start_callback, (void*)(reader));\n \n iso = vtkSynchronizedTemplates3D::New();\n iso->SetInput(reader->GetOutput());\n iso->SetValue(0, 500);\n iso->ComputeScalarsOff();\n iso->ComputeGradientsOff();\n \/\/iso->SetEndMethod(iso_end_callback, (void*)(iso->GetOutput()));\n \/\/ This should be automatically determined by controller.\n iso->SetNumberOfThreads(1);\n\n \/\/ Send data throug port.\n vtkOutputPort *upPort = vtkOutputPort::New();\n upPort->SetInput(iso->GetOutput());\n upPort->SetTag(999);\n \n \/\/ last, set up a RMI call backs.\n controller->AddRMI(exit_callback, (void *)iso, 666);\n \n \/\/ wait for the call back to execute.\n upPort->WaitForUpdate();\n \n \/\/ last call never returns, but ...\n upPort->Delete();\n\n return VTK_THREAD_RETURN_VALUE;\n}\n\n\nVTK_THREAD_RETURN_TYPE process_b( void *vtkNotUsed(arg) )\n{\n vtkMultiProcessController *controller;\n vtkInputPort *downPort;\n vtkPolyDataCollector *collector = vtkPolyDataCollector::New();\n vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();\n vtkActor *actor = vtkActor::New();\n vtkRenderer *ren = vtkRenderer::New();\n vtkRenderWindow *renWindow = vtkRenderWindow::New();\n vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();\n vtkCamera *cam = vtkCamera::New();\n int myid, otherid;\n \n controller = vtkMultiProcessController::RegisterAndGetGlobalController(NULL);\n myid = controller->GetLocalProcessId();\n otherid = ( ! myid);\n \n downPort = vtkInputPort::New();\n downPort->SetRemoteProcessId(otherid);\n downPort->SetTag(999);\n \n collector->SetInput(downPort->GetPolyDataOutput());\n collector->SetInputMemoryLimit(1000);\n \n mapper->SetInput(collector->GetOutput());\n actor->SetMapper(mapper);\n \n putenv(\"DISPLAY=:0.0\");\n \n renWindow->AddRenderer(ren);\n iren->SetRenderWindow(renWindow);\n ren->SetBackground(0.9, 0.9, 0.9);\n renWindow->SetSize( 400, 400);\n \n \/\/ assign our actor to the renderer\n ren->AddActor(actor);\n \n cam->SetFocalPoint(100, 100, 65);\n cam->SetPosition(100, 450, 65);\n cam->SetViewUp(0, 0, -1);\n cam->SetViewAngle(30);\n cam->ComputeViewPlaneNormal();\n \/\/ this was causing an update.\n \/\/ren->ResetCameraClippingRange();\n \/\/{\n \/\/double *range = ren->GetActiveCamera()->GetClippingRange();\n \/\/cerr << range[0] << \", \" << range[1] << endl;\n \/\/}\n cam->SetClippingRange(177.0, 536.0);\n ren->SetActiveCamera(cam);\n \n collector->Update();\n collector->Update();\n cerr << \"WholeMemorySize: \" \n << collector->GetOutput()->GetDataInformation()->GetEstimatedWholeMemorySize()\n << endl;\n \n renWindow->Render();\n \n \/\/ just exit\n \/\/controller->TriggerRMI(otherid, 666); \n \/\/exit(0);\n \n \/\/ Begin mouse interaction\n iren->Start();\n \n \/\/ Clean up\n collector->Delete();\n ren->Delete();\n renWindow->Delete();\n iren->Delete();\n mapper->Delete();\n actor->Delete();\n \n \/\/ clean up objects in all processes.\n controller->UnRegister(NULL);\n\n return VTK_THREAD_RETURN_VALUE;\n}\n\n\nvoid main( int argc, char *argv[] )\n{\n vtkMultiProcessController *controller;\n \n controller = vtkMultiProcessController::RegisterAndGetGlobalController(NULL);\n\n controller->Initialize(argc, argv);\n controller->SetNumberOfProcesses(2);\n controller->SetMultipleMethod(1, process_a, NULL);\n controller->SetMultipleMethod(0, process_b, NULL);\n controller->MultipleMethodExecute();\n\n controller->UnRegister(NULL);\n}\n\n \n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITER_GROUP_BY_HPP_\n#define ITER_GROUP_BY_HPP_\n\n#include \"iterbase.hpp\"\n\n#include <type_traits>\n#include <utility>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n\n template <typename Container, typename KeyFunc>\n class GroupBy;\n\n template <typename Container, typename KeyFunc>\n GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);\n\n template <typename T, typename KeyFunc>\n GroupBy<std::initializer_list<T>, KeyFunc> groupby(\n std::initializer_list<T>, KeyFunc);\n\n template <typename Container, typename KeyFunc>\n class GroupBy {\n private:\n Container container;\n KeyFunc key_func;\n\n friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);\n\n template <typename T, typename KF>\n friend GroupBy<std::initializer_list<T>, KF> groupby(\n std::initializer_list<T>, KF);\n\n using key_func_ret = typename\n std::result_of<KeyFunc(iterator_deref<Container>)>::type;\n\n GroupBy(Container&& container, KeyFunc key_func)\n : container(std::forward<Container>(container)),\n key_func(key_func)\n { }\n\n public:\n GroupBy() = delete;\n GroupBy(const GroupBy&) = delete;\n GroupBy& operator=(const GroupBy&) = delete;\n GroupBy& operator=(GroupBy&&) = delete;\n\n GroupBy(GroupBy&&) = default;\n\n class Iterator;\n class Group;\n\n private:\n using KeyGroupPair =\n std::pair<key_func_ret, Group>;\n public:\n\n class Iterator \n : public std::iterator<std::input_iterator_tag, KeyGroupPair>\n {\n private:\n iterator_type<Container> sub_iter;\n iterator_type<Container> sub_end;\n DerefHolder<iterator_deref<Container>> item;\n KeyFunc *key_func;\n\n public:\n Iterator(iterator_type<Container>&& si,\n iterator_type<Container>&& end,\n KeyFunc& key_func)\n : sub_iter{std::move(si)},\n sub_end{std::move(end)},\n key_func(&key_func)\n {\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n KeyGroupPair operator*() {\n \/\/ FIXME double deref\n return {\n (*this->key_func)(this->item.get()),\n Group{*this, (*this->key_func)(this->item.get())}\n };\n }\n\n Iterator& operator++() { \n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n void increment_iterator() {\n if (this->sub_iter != this->sub_end) {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n }\n\n bool exhausted() const {\n return !(this->sub_iter != this->sub_end);\n }\n\n iterator_deref<Container> pull() {\n return this->item.pull();\n }\n\n \/\/ FIXME double deref. Two deref holders?\n key_func_ret next_key() {\n return (*this->key_func)(this->item.get());\n }\n };\n\n\n class Group {\n private:\n friend Iterator;\n friend class GroupIterator;\n Iterator& owner;\n key_func_ret key;\n\n \/\/ completed is set if a Group is iterated through\n \/\/ completely. It is checked in the destructor, and\n \/\/ if the Group has not been completed, the destructor\n \/\/ exhausts it. This ensures that the next Group starts\n \/\/ at the correct position when the user short-circuits\n \/\/ iteration over a Group.\n \/\/ The move constructor sets the rvalue's completed\n \/\/ attribute to true, so its destructor doesn't do anything\n \/\/ when called.\n bool completed = false;\n\n Group(Iterator& owner, key_func_ret key) :\n owner(owner),\n key(key)\n { }\n\n public:\n ~Group() {\n if (!this->completed) {\n for (auto iter = this->begin(), end = this->end();\n iter != end;\n ++iter) { }\n }\n }\n \n \/\/ move-constructible, non-copy-constructible,\n \/\/ non-assignable\n Group() = delete;\n Group(const Group&) = delete;\n Group& operator=(const Group&) = delete;\n Group& operator=(Group&&) = delete;\n\n Group(Group&& other)\n : owner{other.owner},\n key{other.key},\n completed{other.completed} {\n other.completed = true;\n }\n\n class GroupIterator \n : public std::iterator<std::input_iterator_tag,\n iterator_traits_deref<Container>>\n {\n private:\n typename std::remove_reference<key_func_ret>::type *key;\n Group *group_p;\n\n bool not_at_end() {\n return !this->group_p->owner.exhausted()&&\n this->group_p->owner.next_key() == *this->key;\n }\n\n public:\n GroupIterator(Group *in_group_p,\n key_func_ret& key)\n : key{&key},\n group_p{in_group_p}\n { }\n\n bool operator!=(const GroupIterator& other) const {\n return !(*this == other);\n }\n\n bool operator==(const GroupIterator& other) const {\n return this->group_p == other.group_p;\n }\n\n GroupIterator& operator++() {\n this->group_p->owner.increment_iterator();\n if (!this->not_at_end()) {\n this->group_p->completed = true;\n this->group_p = nullptr;\n }\n return *this;\n }\n\n GroupIterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n iterator_deref<Container> operator*() {\n return this->group_p->owner.pull();\n }\n };\n\n GroupIterator begin() {\n return {this, key};\n }\n\n GroupIterator end() {\n return {nullptr, key};\n }\n\n };\n\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->key_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->key_func};\n }\n\n };\n\n \/\/ Takes something and returns it, used for default key of comparing\n \/\/ items in the sequence directly\n template <typename Container>\n class ItemReturner {\n public:\n iterator_deref<Container> operator() (\n iterator_deref<Container> item) const {\n return item;\n }\n };\n\n\n template <typename Container, typename KeyFunc>\n GroupBy<Container, KeyFunc> groupby(\n Container&& container, KeyFunc key_func) {\n return {std::forward<Container>(container), key_func};\n }\n\n\n template <typename Container>\n auto groupby(Container&& container) ->\n decltype(groupby(std::forward<Container>(container),\n ItemReturner<Container>())) {\n return groupby(std::forward<Container>(container),\n ItemReturner<Container>());\n }\n\n \n template <typename T, typename KeyFunc>\n GroupBy<std::initializer_list<T>, KeyFunc> groupby(\n std::initializer_list<T> il, KeyFunc key_func) {\n return {std::move(il), key_func};\n }\n\n\n template <typename T>\n auto groupby(std::initializer_list<T> il) ->\n decltype(groupby(std::move(il),\n ItemReturner<std::initializer_list<T>>())) {\n return groupby(\n std::move(il),\n ItemReturner<std::initializer_list<T>>());\n }\n\n}\n\n\n#endif\n<commit_msg>eliminates shadow warnings from groupby<commit_after>#ifndef ITER_GROUP_BY_HPP_\n#define ITER_GROUP_BY_HPP_\n\n#include \"iterbase.hpp\"\n\n#include <type_traits>\n#include <utility>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n\n template <typename Container, typename KeyFunc>\n class GroupBy;\n\n template <typename Container, typename KeyFunc>\n GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);\n\n template <typename T, typename KeyFunc>\n GroupBy<std::initializer_list<T>, KeyFunc> groupby(\n std::initializer_list<T>, KeyFunc);\n\n template <typename Container, typename KeyFunc>\n class GroupBy {\n private:\n Container container;\n KeyFunc key_func;\n\n friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);\n\n template <typename T, typename KF>\n friend GroupBy<std::initializer_list<T>, KF> groupby(\n std::initializer_list<T>, KF);\n\n using key_func_ret = typename\n std::result_of<KeyFunc(iterator_deref<Container>)>::type;\n\n GroupBy(Container&& in_container, KeyFunc in_key_func)\n : container(std::forward<Container>(in_container)),\n key_func(in_key_func)\n { }\n\n public:\n GroupBy() = delete;\n GroupBy(const GroupBy&) = delete;\n GroupBy& operator=(const GroupBy&) = delete;\n GroupBy& operator=(GroupBy&&) = delete;\n\n GroupBy(GroupBy&&) = default;\n\n class Iterator;\n class Group;\n\n private:\n using KeyGroupPair =\n std::pair<key_func_ret, Group>;\n public:\n\n class Iterator \n : public std::iterator<std::input_iterator_tag, KeyGroupPair>\n {\n private:\n iterator_type<Container> sub_iter;\n iterator_type<Container> sub_end;\n DerefHolder<iterator_deref<Container>> item;\n KeyFunc *key_func;\n\n public:\n Iterator(iterator_type<Container>&& si,\n iterator_type<Container>&& end,\n KeyFunc& in_key_func)\n : sub_iter{std::move(si)},\n sub_end{std::move(end)},\n key_func(&in_key_func)\n {\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n KeyGroupPair operator*() {\n \/\/ FIXME double deref\n return {\n (*this->key_func)(this->item.get()),\n Group{*this, (*this->key_func)(this->item.get())}\n };\n }\n\n Iterator& operator++() { \n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n void increment_iterator() {\n if (this->sub_iter != this->sub_end) {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n }\n\n bool exhausted() const {\n return !(this->sub_iter != this->sub_end);\n }\n\n iterator_deref<Container> pull() {\n return this->item.pull();\n }\n\n \/\/ FIXME double deref. Two deref holders?\n key_func_ret next_key() {\n return (*this->key_func)(this->item.get());\n }\n };\n\n\n class Group {\n private:\n friend Iterator;\n friend class GroupIterator;\n Iterator& owner;\n key_func_ret key;\n\n \/\/ completed is set if a Group is iterated through\n \/\/ completely. It is checked in the destructor, and\n \/\/ if the Group has not been completed, the destructor\n \/\/ exhausts it. This ensures that the next Group starts\n \/\/ at the correct position when the user short-circuits\n \/\/ iteration over a Group.\n \/\/ The move constructor sets the rvalue's completed\n \/\/ attribute to true, so its destructor doesn't do anything\n \/\/ when called.\n bool completed = false;\n\n Group(Iterator& in_owner, key_func_ret in_key) :\n owner(in_owner),\n key(in_key)\n { }\n\n public:\n ~Group() {\n if (!this->completed) {\n for (auto iter = this->begin(), end = this->end();\n iter != end;\n ++iter) { }\n }\n }\n \n \/\/ move-constructible, non-copy-constructible,\n \/\/ non-assignable\n Group() = delete;\n Group(const Group&) = delete;\n Group& operator=(const Group&) = delete;\n Group& operator=(Group&&) = delete;\n\n Group(Group&& other)\n : owner{other.owner},\n key{other.key},\n completed{other.completed} {\n other.completed = true;\n }\n\n class GroupIterator \n : public std::iterator<std::input_iterator_tag,\n iterator_traits_deref<Container>>\n {\n private:\n typename std::remove_reference<key_func_ret>::type *key;\n Group *group_p;\n\n bool not_at_end() {\n return !this->group_p->owner.exhausted()&&\n this->group_p->owner.next_key() == *this->key;\n }\n\n public:\n GroupIterator(Group *in_group_p,\n key_func_ret& in_key)\n : key{&in_key},\n group_p{in_group_p}\n { }\n\n bool operator!=(const GroupIterator& other) const {\n return !(*this == other);\n }\n\n bool operator==(const GroupIterator& other) const {\n return this->group_p == other.group_p;\n }\n\n GroupIterator& operator++() {\n this->group_p->owner.increment_iterator();\n if (!this->not_at_end()) {\n this->group_p->completed = true;\n this->group_p = nullptr;\n }\n return *this;\n }\n\n GroupIterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n iterator_deref<Container> operator*() {\n return this->group_p->owner.pull();\n }\n };\n\n GroupIterator begin() {\n return {this, key};\n }\n\n GroupIterator end() {\n return {nullptr, key};\n }\n\n };\n\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->key_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->key_func};\n }\n\n };\n\n \/\/ Takes something and returns it, used for default key of comparing\n \/\/ items in the sequence directly\n template <typename Container>\n class ItemReturner {\n public:\n iterator_deref<Container> operator() (\n iterator_deref<Container> item) const {\n return item;\n }\n };\n\n\n template <typename Container, typename KeyFunc>\n GroupBy<Container, KeyFunc> groupby(\n Container&& container, KeyFunc key_func) {\n return {std::forward<Container>(container), key_func};\n }\n\n\n template <typename Container>\n auto groupby(Container&& container) ->\n decltype(groupby(std::forward<Container>(container),\n ItemReturner<Container>())) {\n return groupby(std::forward<Container>(container),\n ItemReturner<Container>());\n }\n\n \n template <typename T, typename KeyFunc>\n GroupBy<std::initializer_list<T>, KeyFunc> groupby(\n std::initializer_list<T> il, KeyFunc key_func) {\n return {std::move(il), key_func};\n }\n\n\n template <typename T>\n auto groupby(std::initializer_list<T> il) ->\n decltype(groupby(std::move(il),\n ItemReturner<std::initializer_list<T>>())) {\n return groupby(\n std::move(il),\n ItemReturner<std::initializer_list<T>>());\n }\n\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_init.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_init.C\n\/\/\/ @brief Wrapper that initializes or resets the OCC complex.\n\/\/\/\n\/\/ *HWP HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP HWP Backup Owner : Prasad BG Ranganath <prasadbgr@in.ibm.com>\n\/\/ *HWP FW Owner : Prem S Jha <premjha2@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 3\n\/\/ *HWP Consumed by : HS\n\n\/\/\/\n\/\/\/ High-level procedure flow:\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/\n\/\/\/ PM_INIT\n\/\/\/ Initialize Cores and Quads\n\/\/\/ Initialize OCB channels\n\/\/\/ Initialize PSS\n\/\/\/ Set the OCC FIR actions\n\/\/\/ Set the CME, PPM and PBA FIR actions\n\/\/\/ Initialize Stop GPE\n\/\/\/ Initialize Pstate GPE\n\/\/\/ Clear off pending Special Wakeup requests on all configured EX chiplets\n\/\/\/ Disable special wakeup of all the EX chiplets\n\/\/\/ Start OCC PPC405\n\/\/\/\n\/\/\/ PM_RESET\n\/\/\/ Invoke \"p9_pm_reset()\" to reset the PM OCC complex (Cores, Quads, CMEs,\n\/\/\/ OCB channels, PBA bus, PSS, PPC405 and GPEs)\n\/\/\/\n\/\/\/ @endverbatim\n\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Includes\n\/\/ -----------------------------------------------------------------------------\n#include <p9_pm_init.H>\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Function prototypes\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\n\/\/\/ @brief Call underlying unit procedures to initialize the PM complex.\n\/\/\/\n\/\/\/ @param[in] i_target Chip target\n\/\/\/\n\/\/\/ @return FAPI2_RC_SUCCESS on success, else error code.\n\/\/\/\nfapi2::ReturnCode pm_init(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n void* i_pHomerImage);\n\n\/\/\/\n\/\/\/ @brief Clears OCC special wake-up on all configured EX chiplets\n\/\/\/\n\/\/\/ @param[in] i_target Chip target\n\/\/\/\n\/\/\/ @return FAPI2_RC_SUCCESS on success, else error code.\n\/\/\/\nfapi2::ReturnCode clear_occ_special_wakeups(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/ -----------------------------------------------------------------------------\n\nfapi2::ReturnCode p9_pm_init(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n const p9pm::PM_FLOW_MODE i_mode,\n void* i_pHomerImage = NULL)\n{\n FAPI_INF(\"Entering p9_pm_init ...\");\n\n fapi2::ReturnCode l_rc;\n\n if (i_mode == p9pm::PM_INIT)\n {\n FAPI_DBG(\"Initialize the OCC Complex.\");\n FAPI_TRY(pm_init(i_target, i_pHomerImage),\n \"ERROR: Failed to initialize OCC Complex\");\n }\n else if (i_mode == p9pm::PM_RESET)\n {\n FAPI_DBG(\"Reset the OCC Complex.\");\n FAPI_EXEC_HWP(l_rc, p9_pm_reset, i_target, i_pHomerImage);\n FAPI_TRY(l_rc, \"ERROR: Failed to reset OCC complex\");\n }\n else\n {\n FAPI_ASSERT(false, fapi2::PM_INIT_BAD_MODE().set_BADMODE(i_mode),\n \"ERROR; Unknown mode passed to p9_pm_init. Mode %x\",\n i_mode);\n }\n\nfapi_try_exit:\n FAPI_INF(\"Exiting p9_pm_init...\");\n return fapi2::current_err;\n}\n\nfapi2::ReturnCode pm_init(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n void* i_pHomerImage)\n{\n FAPI_INF(\"Entering pm_init...\");\n\n fapi2::ReturnCode l_rc;\n\n \/\/ ************************************************************************\n \/\/ Initialize Cores and Quads\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_corequad_init to initialize cores & quads\");\n FAPI_EXEC_HWP(l_rc, p9_pm_corequad_init,\n i_target,\n p9pm::PM_INIT,\n 0,\/\/CME FIR MASK for reset\n 0,\/\/Core Error Mask for reset\n 0 \/\/Quad Error Mask for reset\n );\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize cores & quads\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After cores & quads init\"));\n\n \/\/ ************************************************************************\n \/\/ Issue init to OCB\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_ocb_init to initialize OCB channels\");\n FAPI_EXEC_HWP(l_rc, p9_pm_ocb_init,\n i_target,\n p9pm::PM_INIT,\/\/ Channel setup type\n p9ocb::OCB_CHAN1,\/\/ Channel\n p9ocb:: OCB_TYPE_NULL,\/\/ Channel type\n 0,\/\/ Channel base address\n 0,\/\/ Push\/Pull queue length\n p9ocb::OCB_Q_OUFLOW_NULL,\/\/ Channel flow control\n p9ocb::OCB_Q_ITPTYPE_NULL\/\/ Channel interrupt control\n );\n FAPI_TRY(l_rc,\n \"ERROR: Failed to initialize channel 1\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After OCB channels init\"));\n\n \/\/ ************************************************************************\n \/\/ Initializes P2S and HWC logic\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_pss_init to initialize P2S and HWC logic\");\n FAPI_EXEC_HWP(l_rc, p9_pm_pss_init, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize PSS & HWC\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After PSS & HWC init\"));\n\n \/\/ ************************************************************************\n \/\/ Set the OCC FIR actions\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_occ_firinit to set FIR actions.\");\n FAPI_EXEC_HWP(l_rc, p9_pm_occ_firinit, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to set OCC FIR actions.\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After setting FIRs\"));\n\n \/\/ ************************************************************************\n \/\/ Set the FIR actions\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_firinit to set PBA, PPM, CME FIR actions\");\n FAPI_EXEC_HWP(l_rc, p9_pm_firinit, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to set PPM, PBA & CME FIRs.\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After setting FIRs\"));\n\n \/\/ ************************************************************************\n \/\/ Initialize the STOP GPE Engine\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_stop_gpe_init to initialize SGPE\");\n FAPI_EXEC_HWP(l_rc, p9_pm_stop_gpe_init, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize SGPE\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After SGPE initialization\"));\n\n \/\/ ************************************************************************\n \/\/ Initialize the PSTATE GPE Engine\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_pstate_gpe_init to initialize PGPE\");\n FAPI_EXEC_HWP(l_rc, p9_pm_pstate_gpe_init, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize PGPE\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After PGPE initialization\"));\n\n \/\/ ************************************************************************\n \/\/ Set up the configuration content in HOMER for the 24x7 function\n \/\/ ************************************************************************\n if (i_pHomerImage != NULL)\n {\n FAPI_DBG(\"Executing p9_check_proc_config to create configuration settings for 24x7\");\n FAPI_EXEC_HWP(l_rc, p9_check_proc_config, i_target, i_pHomerImage);\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize 24x7 configuration\");\n }\n\n \/\/ ************************************************************************\n \/\/ Switch off OCC initiated special wakeup on EX to allowSTOP functionality\n \/\/ ************************************************************************\n FAPI_DBG(\"Clear off the wakeup\");\n FAPI_TRY(clear_occ_special_wakeups(i_target),\n \"ERROR: Failed to clear off the wakeup\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"EX targets off special wakeup\"));\n\n \/\/ ************************************************************************\n \/\/ Take all EX chiplets out of special wakeup\n \/\/ ************************************************************************\n FAPI_DBG(\"Disable special wakeup for all functional EX targets.\");\n FAPI_TRY(special_wakeup_all(i_target,\n false),\/\/Disable splwkup\n \"ERROR: Failed to remove EX chiplets from special wakeup\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After EX out of special wakeup\"));\n\n \/\/ ************************************************************************\n \/\/ Start OCC PPC405\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_occ_control to start OCC PPC405\");\n FAPI_EXEC_HWP(l_rc, p9_pm_occ_control, i_target,\n p9occ_ctrl::PPC405_START,\/\/ Operation on PPC405\n p9occ_ctrl::PPC405_BOOT_MEM \/\/ PPC405 boot location\n );\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize OCC PPC405\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After OCC PPC405 init\"));\n\nfapi_try_exit:\n\n return fapi2::current_err;\n\n}\n\nfapi2::ReturnCode clear_occ_special_wakeups(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_INF(\"Entering clear_occ_special_wakeups...\");\n fapi2::buffer<uint64_t> l_data64;\n\n auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX>\n (fapi2::TARGET_STATE_FUNCTIONAL);\n\n FAPI_DBG(\"No. of functional EX chiplets: %u \", l_exChiplets.size());\n\n \/\/ Iterate through the EX chiplets\n for (auto l_ex_chplt : l_exChiplets)\n {\n FAPI_DBG(\"Clear OCC special wakeup on ex chiplet 0x%08X\", l_ex_chplt);\n FAPI_TRY(fapi2::getScom(i_target, EX_PPM_SPWKUP_OCC, l_data64),\n \"ERROR: Failed to read OCC Spl wkup on EX 0x%08X\", l_ex_chplt);\n l_data64.clearBit<0>();\n FAPI_TRY(fapi2::putScom(i_target, EX_PPM_SPWKUP_OCC, l_data64),\n \"ERROR: Failed to clear OCC Spl wkup on EX 0x%08X\", l_ex_chplt);\n }\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n<commit_msg>IPL Time Checkstop Analysis: Bypass OCC Bootloader<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_init.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\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 *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_init.C\n\/\/\/ @brief Wrapper that initializes or resets the OCC complex.\n\/\/\/\n\/\/ *HWP HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP HWP Backup Owner : Prasad BG Ranganath <prasadbgr@in.ibm.com>\n\/\/ *HWP FW Owner : Prem S Jha <premjha2@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 3\n\/\/ *HWP Consumed by : HS\n\n\/\/\/\n\/\/\/ High-level procedure flow:\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/\n\/\/\/ PM_INIT\n\/\/\/ Initialize Cores and Quads\n\/\/\/ Initialize OCB channels\n\/\/\/ Initialize PSS\n\/\/\/ Set the OCC FIR actions\n\/\/\/ Set the CME, PPM and PBA FIR actions\n\/\/\/ Initialize Stop GPE\n\/\/\/ Initialize Pstate GPE\n\/\/\/ Clear off pending Special Wakeup requests on all configured EX chiplets\n\/\/\/ Disable special wakeup of all the EX chiplets\n\/\/\/ Start OCC PPC405\n\/\/\/\n\/\/\/ PM_RESET\n\/\/\/ Invoke \"p9_pm_reset()\" to reset the PM OCC complex (Cores, Quads, CMEs,\n\/\/\/ OCB channels, PBA bus, PSS, PPC405 and GPEs)\n\/\/\/\n\/\/\/ @endverbatim\n\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Includes\n\/\/ -----------------------------------------------------------------------------\n#include <p9_pm_init.H>\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Function prototypes\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\n\/\/\/ @brief Call underlying unit procedures to initialize the PM complex.\n\/\/\/\n\/\/\/ @param[in] i_target Chip target\n\/\/\/\n\/\/\/ @return FAPI2_RC_SUCCESS on success, else error code.\n\/\/\/\nfapi2::ReturnCode pm_init(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n void* i_pHomerImage);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/ -----------------------------------------------------------------------------\n\nfapi2::ReturnCode p9_pm_init(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n const p9pm::PM_FLOW_MODE i_mode,\n void* i_pHomerImage = NULL)\n{\n FAPI_INF(\"Entering p9_pm_init ...\");\n\n fapi2::ReturnCode l_rc;\n\n if (i_mode == p9pm::PM_INIT)\n {\n FAPI_DBG(\"Initialize the OCC Complex.\");\n FAPI_TRY(pm_init(i_target, i_pHomerImage),\n \"ERROR: Failed to initialize OCC Complex\");\n }\n else if (i_mode == p9pm::PM_RESET)\n {\n FAPI_DBG(\"Reset the OCC Complex.\");\n FAPI_EXEC_HWP(l_rc, p9_pm_reset, i_target, i_pHomerImage);\n FAPI_TRY(l_rc, \"ERROR: Failed to reset OCC complex\");\n }\n else\n {\n FAPI_ASSERT(false, fapi2::PM_INIT_BAD_MODE().set_BADMODE(i_mode),\n \"ERROR; Unknown mode passed to p9_pm_init. Mode %x\",\n i_mode);\n }\n\nfapi_try_exit:\n FAPI_INF(\"Exiting p9_pm_init...\");\n return fapi2::current_err;\n}\n\nfapi2::ReturnCode pm_init(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n void* i_pHomerImage)\n{\n FAPI_INF(\"Entering pm_init...\");\n\n fapi2::ReturnCode l_rc;\n\n \/\/ ************************************************************************\n \/\/ Initialize Cores and Quads\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_corequad_init to initialize cores & quads\");\n FAPI_EXEC_HWP(l_rc, p9_pm_corequad_init,\n i_target,\n p9pm::PM_INIT,\n 0,\/\/CME FIR MASK for reset\n 0,\/\/Core Error Mask for reset\n 0 \/\/Quad Error Mask for reset\n );\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize cores & quads\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After cores & quads init\"));\n\n \/\/ ************************************************************************\n \/\/ Issue init to OCB\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_ocb_init to initialize OCB channels\");\n FAPI_EXEC_HWP(l_rc, p9_pm_ocb_init,\n i_target,\n p9pm::PM_INIT,\/\/ Channel setup type\n p9ocb::OCB_CHAN1,\/\/ Channel\n p9ocb:: OCB_TYPE_NULL,\/\/ Channel type\n 0,\/\/ Channel base address\n 0,\/\/ Push\/Pull queue length\n p9ocb::OCB_Q_OUFLOW_NULL,\/\/ Channel flow control\n p9ocb::OCB_Q_ITPTYPE_NULL\/\/ Channel interrupt control\n );\n FAPI_TRY(l_rc,\n \"ERROR: Failed to initialize channel 1\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After OCB channels init\"));\n\n \/\/ ************************************************************************\n \/\/ Initializes P2S and HWC logic\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_pss_init to initialize P2S and HWC logic\");\n FAPI_EXEC_HWP(l_rc, p9_pm_pss_init, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize PSS & HWC\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After PSS & HWC init\"));\n\n \/\/ ************************************************************************\n \/\/ Set the OCC FIR actions\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_occ_firinit to set FIR actions.\");\n FAPI_EXEC_HWP(l_rc, p9_pm_occ_firinit, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to set OCC FIR actions.\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After setting FIRs\"));\n\n \/\/ ************************************************************************\n \/\/ Set the FIR actions\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_firinit to set PBA, PPM, CME FIR actions\");\n FAPI_EXEC_HWP(l_rc, p9_pm_firinit, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to set PPM, PBA & CME FIRs.\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After setting FIRs\"));\n\n \/\/ ************************************************************************\n \/\/ Initialize the STOP GPE Engine\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_stop_gpe_init to initialize SGPE\");\n FAPI_EXEC_HWP(l_rc, p9_pm_stop_gpe_init, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize SGPE\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After SGPE initialization\"));\n\n \/\/ ************************************************************************\n \/\/ Initialize the PSTATE GPE Engine\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_pstate_gpe_init to initialize PGPE\");\n FAPI_EXEC_HWP(l_rc, p9_pm_pstate_gpe_init, i_target, p9pm::PM_INIT);\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize PGPE\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After PGPE initialization\"));\n\n \/\/ ************************************************************************\n \/\/ Set up the configuration content in HOMER for the 24x7 function\n \/\/ ************************************************************************\n if (i_pHomerImage != NULL)\n {\n FAPI_DBG(\"Executing p9_check_proc_config to create configuration settings for 24x7\");\n FAPI_EXEC_HWP(l_rc, p9_check_proc_config, i_target, i_pHomerImage);\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize 24x7 configuration\");\n }\n\n \/\/ ************************************************************************\n \/\/ Switch off OCC initiated special wakeup on EX to allowSTOP functionality\n \/\/ ************************************************************************\n FAPI_DBG(\"Clear off the wakeup\");\n FAPI_TRY(clear_occ_special_wakeups(i_target),\n \"ERROR: Failed to clear off the wakeup\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"EX targets off special wakeup\"));\n\n \/\/ ************************************************************************\n \/\/ Take all EX chiplets out of special wakeup\n \/\/ ************************************************************************\n FAPI_DBG(\"Disable special wakeup for all functional EX targets.\");\n FAPI_TRY(special_wakeup_all(i_target,\n false),\/\/Disable splwkup\n \"ERROR: Failed to remove EX chiplets from special wakeup\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After EX out of special wakeup\"));\n\n \/\/ ************************************************************************\n \/\/ Start OCC PPC405\n \/\/ ************************************************************************\n FAPI_DBG(\"Executing p9_pm_occ_control to start OCC PPC405\");\n FAPI_EXEC_HWP(l_rc, p9_pm_occ_control, i_target,\n p9occ_ctrl::PPC405_START,\/\/ Operation on PPC405\n p9occ_ctrl::PPC405_BOOT_MEM, \/\/ PPC405 boot location\n 0 \/\/Jump to 405 main instruction - not used here\n );\n FAPI_TRY(l_rc, \"ERROR: Failed to initialize OCC PPC405\");\n FAPI_TRY(p9_pm_glob_fir_trace(i_target, \"After OCC PPC405 init\"));\n\nfapi_try_exit:\n\n return fapi2::current_err;\n\n}\n\nfapi2::ReturnCode clear_occ_special_wakeups(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_INF(\"Entering clear_occ_special_wakeups...\");\n fapi2::buffer<uint64_t> l_data64;\n\n auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX>\n (fapi2::TARGET_STATE_FUNCTIONAL);\n\n FAPI_DBG(\"No. of functional EX chiplets: %u \", l_exChiplets.size());\n\n \/\/ Iterate through the EX chiplets\n for (auto l_ex_chplt : l_exChiplets)\n {\n FAPI_DBG(\"Clear OCC special wakeup on ex chiplet 0x%08X\", l_ex_chplt);\n FAPI_TRY(fapi2::getScom(i_target, EX_PPM_SPWKUP_OCC, l_data64),\n \"ERROR: Failed to read OCC Spl wkup on EX 0x%08X\", l_ex_chplt);\n l_data64.clearBit<0>();\n FAPI_TRY(fapi2::putScom(i_target, EX_PPM_SPWKUP_OCC, l_data64),\n \"ERROR: Failed to clear OCC Spl wkup on EX 0x%08X\", l_ex_chplt);\n }\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fixed GEMM conversion (#4412)<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>[localization] formatting<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tグラフィックス・カラー定義\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n\nnamespace graphics {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\t基本カラー定数\n\t\t@param[in]\tT\t\tピクセル型(uint16_t、uint32_t)\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <typename T>\n\tclass base_color {\n\n\t\tstatic constexpr uint32_t rgb888_(uint8_t r, uint8_t g, uint8_t b)\n\t\t{\n\t\t\treturn\n\t\t\t\t(static_cast<uint32_t>(r) << 16)\n\t\t\t | (static_cast<uint32_t>(g) << 8)\n\t\t\t | static_cast<uint32_t>(b);\n\t\t}\n\n\n\t\tstatic constexpr uint16_t rgb565_(uint8_t r, uint8_t g, uint8_t b)\n\t\t{\n\t\t\treturn\n\t\t\t\t(static_cast<uint16_t>(r & 0xf8) << 8)\n\t\t\t | (static_cast<uint16_t>(g & 0xfc) << 3)\n\t\t\t | (static_cast<uint16_t>(b & 0xf8) >> 3);\n\t\t}\n\n\n\t\tstatic constexpr T rgb_(uint8_t r, uint8_t g, uint8_t b)\n\t\t{\n\t\t\tif(sizeof(T) == 1) {\n\t\t\t\treturn (r & 0b11100000) | ((g & 0b11100000) >> 3) | ((b & 0b11000000) >> 6);\n\t\t\t} else if(sizeof(T) == 2) return rgb565_(r, g, b);\n\t\t\telse if(sizeof(T) == 4) return rgb888_(r, g, b);\n\t\t\telse return 0;\n\t\t}\n\n\n\tpublic:\n\t\t\/\/ https:\/\/jonasjacek.github.io\/colors\/\n\t\tstatic constexpr T Black = rgb_( 0, 0, 0);\n\t\tstatic constexpr T Maroon = rgb_(128, 0, 0);\n\t\tstatic constexpr T Green = rgb_( 0, 128, 0);\n\t\tstatic constexpr T Olive = rgb_(128, 128, 0);\n\t\tstatic constexpr T Navy = rgb_( 0, 0, 128);\n\t\tstatic constexpr T Purple = rgb_(128, 0, 128);\n\t\tstatic constexpr T Teal = rgb_( 0, 128, 128);\n\t\tstatic constexpr T Silver = rgb_(192, 192, 192);\n\t\tstatic constexpr T Grey = rgb_(128, 128, 128);\n\t\tstatic constexpr T Red = rgb_(255, 0, 0);\n\t\tstatic constexpr T Lime = rgb_( 0, 255, 0);\n\t\tstatic constexpr T Yellow = rgb_(255, 255, 0);\n\t\tstatic constexpr T Blue = rgb_( 0, 0, 255);\n\t\tstatic constexpr T Fuchsi = rgb_(255, 0, 255);\n\t\tstatic constexpr T Aqua = rgb_( 0, 255, 255);\n\t\tstatic constexpr T White = rgb_(255, 255, 255);\n\t};\n}\n<commit_msg>update: add API<commit_after>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tグラフィックス・カラー定義\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n\nnamespace graphics {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\t基本カラー定数\n\t\t@param[in]\tT\t\tピクセル型(uint16_t、uint32_t)\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <typename T>\n\tclass base_color {\n\n\t\tstatic constexpr uint32_t rgb888_(uint8_t r, uint8_t g, uint8_t b)\n\t\t{\n\t\t\treturn\n\t\t\t\t(static_cast<uint32_t>(r) << 16)\n\t\t\t | (static_cast<uint32_t>(g) << 8)\n\t\t\t | static_cast<uint32_t>(b);\n\t\t}\n\n\n\t\tstatic constexpr uint16_t rgb565_(uint8_t r, uint8_t g, uint8_t b)\n\t\t{\n\t\t\treturn\n\t\t\t\t(static_cast<uint16_t>(r & 0xf8) << 8)\n\t\t\t | (static_cast<uint16_t>(g & 0xfc) << 3)\n\t\t\t | (static_cast<uint16_t>(b & 0xf8) >> 3);\n\t\t}\n\n\n\t\tstatic constexpr T rgb_(uint8_t r, uint8_t g, uint8_t b)\n\t\t{\n\t\t\tif(sizeof(T) == 1) {\n\t\t\t\treturn (r & 0b11100000) | ((g & 0b11100000) >> 3) | ((b & 0b11000000) >> 6);\n\t\t\t} else if(sizeof(T) == 2) return rgb565_(r, g, b);\n\t\t\telse if(sizeof(T) == 4) return rgb888_(r, g, b);\n\t\t\telse return 0;\n\t\t}\n\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tRGB 値から、パックされた RGB 値に変換\n\t\t\t@param[in]\tr\tR 値\n\t\t\t@param[in]\tg\tG 値\n\t\t\t@param[in]\tb\tB 値\n\t\t\t@return パックされた RGB 値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tT rgb(uint8_t r, uint8_t g, uint8_t b) const noexcept { return rgb_(r, g, b); }\n\n\n\t\t\/\/ https:\/\/jonasjacek.github.io\/colors\/\n\t\tstatic constexpr T Black = rgb_( 0, 0, 0);\n\t\tstatic constexpr T Maroon = rgb_(128, 0, 0);\n\t\tstatic constexpr T Green = rgb_( 0, 128, 0);\n\t\tstatic constexpr T Olive = rgb_(128, 128, 0);\n\t\tstatic constexpr T Navy = rgb_( 0, 0, 128);\n\t\tstatic constexpr T Purple = rgb_(128, 0, 128);\n\t\tstatic constexpr T Teal = rgb_( 0, 128, 128);\n\t\tstatic constexpr T Silver = rgb_(192, 192, 192);\n\t\tstatic constexpr T Gray = rgb_(128, 128, 128); \/\/ 米国\n\t\tstatic constexpr T Grey = rgb_(128, 128, 128); \/\/ 英国\n\t\tstatic constexpr T Red = rgb_(255, 0, 0);\n\t\tstatic constexpr T Lime = rgb_( 0, 255, 0);\n\t\tstatic constexpr T Yellow = rgb_(255, 255, 0);\n\t\tstatic constexpr T Blue = rgb_( 0, 0, 255);\n\t\tstatic constexpr T Fuchsi = rgb_(255, 0, 255);\n\t\tstatic constexpr T Aqua = rgb_( 0, 255, 255);\n\t\tstatic constexpr T White = rgb_(255, 255, 255);\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fix for compilation error on HPUX<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/layoutUI\/CVisParameters.cpp,v $\n\/\/ $Revision: 1.9 $\n\/\/ $Name: $\n\/\/ $Author: urost $\n\/\/ $Date: 2007\/10\/29 10:09:19 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \"CVisParameters.h\"\n\nconst C_FLOAT64 CVisParameters::EPSILON = 1.2E-15f;\n\nconst C_INT16 CVisParameters::GLOBAL_SCALING = 0;\nconst C_INT16 CVisParameters::INDIVIDUAL_SCALING = 1;\n\nconst C_INT16 CVisParameters::COLOR_MODE = 0;\nconst C_INT16 CVisParameters::SIZE_DIAMETER_MODE = 1;\nconst C_INT16 CVisParameters::SIZE_AREA_MODE = 2;\n\nCVisParameters::CVisParameters()\n{\n init();\n}\n\nvoid CVisParameters::init()\n{\n minNodeSize = 10.0;\n maxNodeSize = 100.0;\n \/\/numberOfSteps = 0;\n stepsPerSecond = 10;\n scalingMode = CVisParameters::INDIVIDUAL_SCALING;\n mappingMode = CVisParameters::SIZE_DIAMETER_MODE;\n \/\/mappingMode = CVisParameters::COLOR_MODE;\n animationRunning = false;\n}\n<commit_msg>*** empty log message ***<commit_after>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/layoutUI\/CVisParameters.cpp,v $\n\/\/ $Revision: 1.10 $\n\/\/ $Name: $\n\/\/ $Author: urost $\n\/\/ $Date: 2007\/10\/29 10:19:14 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \"CVisParameters.h\"\n\nconst C_FLOAT64 CVisParameters::EPSILON = 1.0E-15f;\n\nconst C_INT16 CVisParameters::GLOBAL_SCALING = 0;\nconst C_INT16 CVisParameters::INDIVIDUAL_SCALING = 1;\n\nconst C_INT16 CVisParameters::COLOR_MODE = 0;\nconst C_INT16 CVisParameters::SIZE_DIAMETER_MODE = 1;\nconst C_INT16 CVisParameters::SIZE_AREA_MODE = 2;\n\nCVisParameters::CVisParameters()\n{\n init();\n}\n\nvoid CVisParameters::init()\n{\n minNodeSize = 10.0;\n maxNodeSize = 100.0;\n \/\/numberOfSteps = 0;\n stepsPerSecond = 10;\n scalingMode = CVisParameters::INDIVIDUAL_SCALING;\n mappingMode = CVisParameters::SIZE_DIAMETER_MODE;\n \/\/mappingMode = CVisParameters::COLOR_MODE;\n animationRunning = false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: optaccessibility.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2005-01-21 16:43:24 $\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#ifdef SVX_DLLIMPLEMENTATION\n#undef SVX_DLLIMPLEMENTATION\n#endif\n\n#ifndef _SVX_OPTACCESSIBILITY_HXX\n#include <optaccessibility.hxx>\n#endif\n#include <optaccessibility.hrc>\n#include <dialmgr.hxx>\n#include \"dialogs.hrc\"\n#ifndef INCLUDED_SVTOOLS_ACCESSIBILITYOPTIONS_HXX\n#include <svtools\/accessibilityoptions.hxx>\n#endif\n#ifndef _SV_SETTINGS_HXX\n#include <vcl\/settings.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\nstatic void MovePosY( Window& _rWin, long _nDelta )\n{\n Point aPoint = _rWin.GetPosPixel();\n aPoint.Y() += _nDelta;\n\n _rWin.SetPosPixel( aPoint );\n}\n\nstruct SvxAccessibilityOptionsTabPage_Impl\n{\n SvtAccessibilityOptions m_aConfig;\n SvxAccessibilityOptionsTabPage_Impl()\n : m_aConfig(){}\n};\n\nSvxAccessibilityOptionsTabPage::SvxAccessibilityOptionsTabPage( Window* pParent, const SfxItemSet& rSet )\n :SfxTabPage(pParent, ResId( RID_SVXPAGE_ACCESSIBILITYCONFIG, DIALOG_MGR() ), rSet)\n ,m_aMiscellaneousLabel (this, ResId(FL_MISCELLANEOUS ))\n ,m_aAccessibilityTool (this, ResId(CB_ACCESSIBILITY_TOOL ))\n ,m_aTextSelectionInReadonly (this, ResId(CB_TEXTSELECTION ))\n ,m_aAnimatedGraphics (this, ResId(CB_ANIMATED_GRAPHICS ))\n ,m_aAnimatedTexts (this, ResId(CB_ANIMATED_TEXTS ))\n ,m_aTipHelpCB (this, ResId(CB_TIPHELP ))\n ,m_aTipHelpNF (this, ResId(NF_TIPHELP ))\n ,m_aTipHelpFT (this, ResId(FT_TIPHELP ))\n ,m_aHCOptionsLabel (this, ResId(FL_HC_OPTIONS ))\n ,m_aAutoDetectHC (this, ResId(CB_AUTO_DETECT_HC ))\n ,m_aAutomaticFontColor (this, ResId(CB_AUTOMATIC_FONT_COLOR))\n ,m_aPagePreviews (this, ResId(CB_PAGE_PREVIEWS ))\n ,m_pImpl(new SvxAccessibilityOptionsTabPage_Impl)\n{\n FreeResource();\n m_aTipHelpCB.SetClickHdl(LINK(this, SvxAccessibilityOptionsTabPage, TipHelpHdl));\n\n long nHeightDelta = 0; \/\/ to correct positions _under_ m_aAccessibilityTool\n\n#ifdef UNX\n {\n \/\/ UNIX: read the gconf2 setting instead to use the checkbox\n m_aAccessibilityTool.Hide();\n nHeightDelta = -( ROWA_2 - ROWA_1 );\n }\n#else\n \/\/ calculate the height of the checkbox. Do we need two (default in resource) or only one line\n String aText = m_aAccessibilityTool.GetText();\n long nWidth = m_aAccessibilityTool.GetTextWidth( aText );\n long nCtrlWidth = m_aAccessibilityTool.GetSizePixel().Width() - ( COL2 - COL1 );\n if ( nWidth > nCtrlWidth )\n {\n long nDelta = 2 * RSC_CD_FIXEDLINE_HEIGHT + LINESPACE - RSC_CD_CHECKBOX_HEIGHT;\n nHeightDelta = nDelta;\n Size aSize = m_aAccessibilityTool.LogicToPixel( Size( 0, nDelta ), MAP_APPFONT );\n nDelta = aSize.Height();\n aSize = m_aAccessibilityTool.GetSizePixel();\n aSize.Height() += nDelta;\n m_aAccessibilityTool.SetSizePixel( aSize );\n }\n#endif\n\n if( nHeightDelta )\n { \/\/adjust positions of controls under m_aAccessibilityTool\n Size aSize = m_aAccessibilityTool.LogicToPixel( Size( 0, nHeightDelta ), MAP_APPFONT );\n nHeightDelta = aSize.Height();\n\n MovePosY( m_aTextSelectionInReadonly, nHeightDelta );\n MovePosY( m_aAnimatedGraphics, nHeightDelta );\n MovePosY( m_aAnimatedTexts, nHeightDelta );\n MovePosY( m_aTipHelpCB, nHeightDelta );\n MovePosY( m_aTipHelpNF, nHeightDelta );\n MovePosY( m_aTipHelpFT, nHeightDelta );\n MovePosY( m_aHCOptionsLabel, nHeightDelta );\n MovePosY( m_aAutoDetectHC, nHeightDelta );\n MovePosY( m_aAutomaticFontColor, nHeightDelta );\n MovePosY( m_aPagePreviews, nHeightDelta );\n }\n}\n\nSvxAccessibilityOptionsTabPage::~SvxAccessibilityOptionsTabPage()\n{\n delete m_pImpl;\n}\n\nSfxTabPage* SvxAccessibilityOptionsTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet )\n{\n return new SvxAccessibilityOptionsTabPage(pParent, rAttrSet);\n}\n\nBOOL SvxAccessibilityOptionsTabPage::FillItemSet( SfxItemSet& rSet )\n{\n \/\/aConfig.Set... from controls\n\n m_pImpl->m_aConfig.SetIsForPagePreviews( m_aPagePreviews.IsChecked() );\n m_pImpl->m_aConfig.SetIsHelpTipsDisappear( m_aTipHelpCB.IsChecked() );\n m_pImpl->m_aConfig.SetHelpTipSeconds( (short)m_aTipHelpNF.GetValue() );\n m_pImpl->m_aConfig.SetIsAllowAnimatedGraphics( m_aAnimatedGraphics.IsChecked() );\n m_pImpl->m_aConfig.SetIsAllowAnimatedText( m_aAnimatedTexts.IsChecked() );\n m_pImpl->m_aConfig.SetIsAutomaticFontColor( m_aAutomaticFontColor.IsChecked() );\n m_pImpl->m_aConfig.SetSelectionInReadonly( m_aTextSelectionInReadonly.IsChecked());\n m_pImpl->m_aConfig.SetAutoDetectSystemHC( m_aAutoDetectHC.IsChecked());\n\n if(m_pImpl->m_aConfig.IsModified())\n m_pImpl->m_aConfig.Commit();\n\n#ifndef UNX\n AllSettings aAllSettings = Application::GetSettings();\n MiscSettings aMiscSettings = aAllSettings.GetMiscSettings();\n aMiscSettings.SetEnableATToolSupport( m_aAccessibilityTool.IsChecked() );\n aAllSettings.SetMiscSettings(aMiscSettings);\n Application::SetSettings(aAllSettings);\n Application::MergeSystemSettings( aAllSettings );\n#endif\n\n return FALSE;\n}\n\nvoid SvxAccessibilityOptionsTabPage::Reset( const SfxItemSet& rSet )\n{\n \/\/set controls from aConfig.Get...\n\n m_aPagePreviews.Check( m_pImpl->m_aConfig.GetIsForPagePreviews() );\n EnableTipHelp( m_pImpl->m_aConfig.GetIsHelpTipsDisappear() );\n m_aTipHelpNF.SetValue( m_pImpl->m_aConfig.GetHelpTipSeconds() );\n m_aAnimatedGraphics.Check( m_pImpl->m_aConfig.GetIsAllowAnimatedGraphics() );\n m_aAnimatedTexts.Check( m_pImpl->m_aConfig.GetIsAllowAnimatedText() );\n m_aAutomaticFontColor.Check( m_pImpl->m_aConfig.GetIsAutomaticFontColor() );\n\/\/ m_aSystemFont.Check( m_pImpl->m_aConfig.GetIsSystemFont() );\n m_aTextSelectionInReadonly.Check( m_pImpl->m_aConfig.IsSelectionInReadonly() );\n m_aAutoDetectHC.Check( m_pImpl->m_aConfig.GetAutoDetectSystemHC() );\n\n\n AllSettings aAllSettings = Application::GetSettings();\n MiscSettings aMiscSettings = aAllSettings.GetMiscSettings();\n m_aAccessibilityTool.Check( aMiscSettings.GetEnableATToolSupport() );\n}\n\nIMPL_LINK(SvxAccessibilityOptionsTabPage, TipHelpHdl, CheckBox*, pBox)\n{\n sal_Bool bChecked = pBox->IsChecked();\n m_aTipHelpNF.Enable(bChecked);\n return 0;\n}\n\nvoid SvxAccessibilityOptionsTabPage::EnableTipHelp(sal_Bool bCheck)\n{\n m_aTipHelpCB.Check(bCheck);\n m_aTipHelpNF.Enable(bCheck);\n}\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.430); FILE MERGED 2005\/09\/05 14:21:26 rt 1.4.430.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: optaccessibility.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:38: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#ifdef SVX_DLLIMPLEMENTATION\n#undef SVX_DLLIMPLEMENTATION\n#endif\n\n#ifndef _SVX_OPTACCESSIBILITY_HXX\n#include <optaccessibility.hxx>\n#endif\n#include <optaccessibility.hrc>\n#include <dialmgr.hxx>\n#include \"dialogs.hrc\"\n#ifndef INCLUDED_SVTOOLS_ACCESSIBILITYOPTIONS_HXX\n#include <svtools\/accessibilityoptions.hxx>\n#endif\n#ifndef _SV_SETTINGS_HXX\n#include <vcl\/settings.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\nstatic void MovePosY( Window& _rWin, long _nDelta )\n{\n Point aPoint = _rWin.GetPosPixel();\n aPoint.Y() += _nDelta;\n\n _rWin.SetPosPixel( aPoint );\n}\n\nstruct SvxAccessibilityOptionsTabPage_Impl\n{\n SvtAccessibilityOptions m_aConfig;\n SvxAccessibilityOptionsTabPage_Impl()\n : m_aConfig(){}\n};\n\nSvxAccessibilityOptionsTabPage::SvxAccessibilityOptionsTabPage( Window* pParent, const SfxItemSet& rSet )\n :SfxTabPage(pParent, ResId( RID_SVXPAGE_ACCESSIBILITYCONFIG, DIALOG_MGR() ), rSet)\n ,m_aMiscellaneousLabel (this, ResId(FL_MISCELLANEOUS ))\n ,m_aAccessibilityTool (this, ResId(CB_ACCESSIBILITY_TOOL ))\n ,m_aTextSelectionInReadonly (this, ResId(CB_TEXTSELECTION ))\n ,m_aAnimatedGraphics (this, ResId(CB_ANIMATED_GRAPHICS ))\n ,m_aAnimatedTexts (this, ResId(CB_ANIMATED_TEXTS ))\n ,m_aTipHelpCB (this, ResId(CB_TIPHELP ))\n ,m_aTipHelpNF (this, ResId(NF_TIPHELP ))\n ,m_aTipHelpFT (this, ResId(FT_TIPHELP ))\n ,m_aHCOptionsLabel (this, ResId(FL_HC_OPTIONS ))\n ,m_aAutoDetectHC (this, ResId(CB_AUTO_DETECT_HC ))\n ,m_aAutomaticFontColor (this, ResId(CB_AUTOMATIC_FONT_COLOR))\n ,m_aPagePreviews (this, ResId(CB_PAGE_PREVIEWS ))\n ,m_pImpl(new SvxAccessibilityOptionsTabPage_Impl)\n{\n FreeResource();\n m_aTipHelpCB.SetClickHdl(LINK(this, SvxAccessibilityOptionsTabPage, TipHelpHdl));\n\n long nHeightDelta = 0; \/\/ to correct positions _under_ m_aAccessibilityTool\n\n#ifdef UNX\n {\n \/\/ UNIX: read the gconf2 setting instead to use the checkbox\n m_aAccessibilityTool.Hide();\n nHeightDelta = -( ROWA_2 - ROWA_1 );\n }\n#else\n \/\/ calculate the height of the checkbox. Do we need two (default in resource) or only one line\n String aText = m_aAccessibilityTool.GetText();\n long nWidth = m_aAccessibilityTool.GetTextWidth( aText );\n long nCtrlWidth = m_aAccessibilityTool.GetSizePixel().Width() - ( COL2 - COL1 );\n if ( nWidth > nCtrlWidth )\n {\n long nDelta = 2 * RSC_CD_FIXEDLINE_HEIGHT + LINESPACE - RSC_CD_CHECKBOX_HEIGHT;\n nHeightDelta = nDelta;\n Size aSize = m_aAccessibilityTool.LogicToPixel( Size( 0, nDelta ), MAP_APPFONT );\n nDelta = aSize.Height();\n aSize = m_aAccessibilityTool.GetSizePixel();\n aSize.Height() += nDelta;\n m_aAccessibilityTool.SetSizePixel( aSize );\n }\n#endif\n\n if( nHeightDelta )\n { \/\/adjust positions of controls under m_aAccessibilityTool\n Size aSize = m_aAccessibilityTool.LogicToPixel( Size( 0, nHeightDelta ), MAP_APPFONT );\n nHeightDelta = aSize.Height();\n\n MovePosY( m_aTextSelectionInReadonly, nHeightDelta );\n MovePosY( m_aAnimatedGraphics, nHeightDelta );\n MovePosY( m_aAnimatedTexts, nHeightDelta );\n MovePosY( m_aTipHelpCB, nHeightDelta );\n MovePosY( m_aTipHelpNF, nHeightDelta );\n MovePosY( m_aTipHelpFT, nHeightDelta );\n MovePosY( m_aHCOptionsLabel, nHeightDelta );\n MovePosY( m_aAutoDetectHC, nHeightDelta );\n MovePosY( m_aAutomaticFontColor, nHeightDelta );\n MovePosY( m_aPagePreviews, nHeightDelta );\n }\n}\n\nSvxAccessibilityOptionsTabPage::~SvxAccessibilityOptionsTabPage()\n{\n delete m_pImpl;\n}\n\nSfxTabPage* SvxAccessibilityOptionsTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet )\n{\n return new SvxAccessibilityOptionsTabPage(pParent, rAttrSet);\n}\n\nBOOL SvxAccessibilityOptionsTabPage::FillItemSet( SfxItemSet& rSet )\n{\n \/\/aConfig.Set... from controls\n\n m_pImpl->m_aConfig.SetIsForPagePreviews( m_aPagePreviews.IsChecked() );\n m_pImpl->m_aConfig.SetIsHelpTipsDisappear( m_aTipHelpCB.IsChecked() );\n m_pImpl->m_aConfig.SetHelpTipSeconds( (short)m_aTipHelpNF.GetValue() );\n m_pImpl->m_aConfig.SetIsAllowAnimatedGraphics( m_aAnimatedGraphics.IsChecked() );\n m_pImpl->m_aConfig.SetIsAllowAnimatedText( m_aAnimatedTexts.IsChecked() );\n m_pImpl->m_aConfig.SetIsAutomaticFontColor( m_aAutomaticFontColor.IsChecked() );\n m_pImpl->m_aConfig.SetSelectionInReadonly( m_aTextSelectionInReadonly.IsChecked());\n m_pImpl->m_aConfig.SetAutoDetectSystemHC( m_aAutoDetectHC.IsChecked());\n\n if(m_pImpl->m_aConfig.IsModified())\n m_pImpl->m_aConfig.Commit();\n\n#ifndef UNX\n AllSettings aAllSettings = Application::GetSettings();\n MiscSettings aMiscSettings = aAllSettings.GetMiscSettings();\n aMiscSettings.SetEnableATToolSupport( m_aAccessibilityTool.IsChecked() );\n aAllSettings.SetMiscSettings(aMiscSettings);\n Application::SetSettings(aAllSettings);\n Application::MergeSystemSettings( aAllSettings );\n#endif\n\n return FALSE;\n}\n\nvoid SvxAccessibilityOptionsTabPage::Reset( const SfxItemSet& rSet )\n{\n \/\/set controls from aConfig.Get...\n\n m_aPagePreviews.Check( m_pImpl->m_aConfig.GetIsForPagePreviews() );\n EnableTipHelp( m_pImpl->m_aConfig.GetIsHelpTipsDisappear() );\n m_aTipHelpNF.SetValue( m_pImpl->m_aConfig.GetHelpTipSeconds() );\n m_aAnimatedGraphics.Check( m_pImpl->m_aConfig.GetIsAllowAnimatedGraphics() );\n m_aAnimatedTexts.Check( m_pImpl->m_aConfig.GetIsAllowAnimatedText() );\n m_aAutomaticFontColor.Check( m_pImpl->m_aConfig.GetIsAutomaticFontColor() );\n\/\/ m_aSystemFont.Check( m_pImpl->m_aConfig.GetIsSystemFont() );\n m_aTextSelectionInReadonly.Check( m_pImpl->m_aConfig.IsSelectionInReadonly() );\n m_aAutoDetectHC.Check( m_pImpl->m_aConfig.GetAutoDetectSystemHC() );\n\n\n AllSettings aAllSettings = Application::GetSettings();\n MiscSettings aMiscSettings = aAllSettings.GetMiscSettings();\n m_aAccessibilityTool.Check( aMiscSettings.GetEnableATToolSupport() );\n}\n\nIMPL_LINK(SvxAccessibilityOptionsTabPage, TipHelpHdl, CheckBox*, pBox)\n{\n sal_Bool bChecked = pBox->IsChecked();\n m_aTipHelpNF.Enable(bChecked);\n return 0;\n}\n\nvoid SvxAccessibilityOptionsTabPage::EnableTipHelp(sal_Bool bCheck)\n{\n m_aTipHelpCB.Check(bCheck);\n m_aTipHelpNF.Enable(bCheck);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- safestack.cc ------------------------------------------------------===\/\/\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\/\/ This file implements the runtime support for the safe stack protection\n\/\/ mechanism. The runtime manages allocation\/deallocation of the unsafe stack\n\/\/ for the main thread, as well as all pthreads that are created\/destroyed\n\/\/ during program execution.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <limits.h>\n#include <pthread.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <sys\/resource.h>\n#include <sys\/user.h>\n\n#include \"interception\/interception.h\"\n#include \"sanitizer_common\/sanitizer_common.h\"\n\n\/\/ TODO: The runtime library does not currently protect the safe stack beyond\n\/\/ relying on the system-enforced ASLR. The protection of the (safe) stack can\n\/\/ be provided by three alternative features:\n\/\/\n\/\/ 1) Protection via hardware segmentation on x86-32 and some x86-64\n\/\/ architectures: the (safe) stack segment (implicitly accessed via the %ss\n\/\/ segment register) can be separated from the data segment (implicitly\n\/\/ accessed via the %ds segment register). Dereferencing a pointer to the safe\n\/\/ segment would result in a segmentation fault.\n\/\/\n\/\/ 2) Protection via software fault isolation: memory writes that are not meant\n\/\/ to access the safe stack can be prevented from doing so through runtime\n\/\/ instrumentation. One way to do it is to allocate the safe stack(s) in the\n\/\/ upper half of the userspace and bitmask the corresponding upper bit of the\n\/\/ memory addresses of memory writes that are not meant to access the safe\n\/\/ stack.\n\/\/\n\/\/ 3) Protection via information hiding on 64 bit architectures: the location\n\/\/ of the safe stack(s) can be randomized through secure mechanisms, and the\n\/\/ leakage of the stack pointer can be prevented. Currently, libc can leak the\n\/\/ stack pointer in several ways (e.g. in longjmp, signal handling, user-level\n\/\/ context switching related functions, etc.). These can be fixed in libc and\n\/\/ in other low-level libraries, by either eliminating the escaping\/dumping of\n\/\/ the stack pointer (i.e., %rsp) when that's possible, or by using\n\/\/ encryption\/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret\n\/\/ we control and protect better, as is already done for setjmp in glibc.)\n\/\/ Furthermore, a static machine code level verifier can be ran after code\n\/\/ generation to make sure that the stack pointer is never written to memory,\n\/\/ or if it is, its written on the safe stack.\n\/\/\n\/\/ Finally, while the Unsafe Stack pointer is currently stored in a thread\n\/\/ local variable, with libc support it could be stored in the TCB (thread\n\/\/ control block) as well, eliminating another level of indirection and making\n\/\/ such accesses faster. Alternatively, dedicating a separate register for\n\/\/ storing it would also be possible.\n\n\/\/\/ Minimum stack alignment for the unsafe stack.\nconst unsigned kStackAlign = 16;\n\n\/\/\/ Default size of the unsafe stack. This value is only used if the stack\n\/\/\/ size rlimit is set to infinity.\nconst unsigned kDefaultUnsafeStackSize = 0x2800000;\n\n\/\/ TODO: To make accessing the unsafe stack pointer faster, we plan to\n\/\/ eventually store it directly in the thread control block data structure on\n\/\/ platforms where this structure is pointed to by %fs or %gs. This is exactly\n\/\/ the same mechanism as currently being used by the traditional stack\n\/\/ protector pass to store the stack guard (see getStackCookieLocation()\n\/\/ function above). Doing so requires changing the tcbhead_t struct in glibc\n\/\/ on Linux and tcb struct in libc on FreeBSD.\n\/\/\n\/\/ For now, store it in a thread-local variable.\nextern \"C\" {\n__attribute__((visibility(\n \"default\"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;\n}\n\n\/\/ Per-thread unsafe stack information. It's not frequently accessed, so there\n\/\/ it can be kept out of the tcb in normal thread-local variables.\nstatic __thread void *unsafe_stack_start = nullptr;\nstatic __thread size_t unsafe_stack_size = 0;\nstatic __thread size_t unsafe_stack_guard = 0;\n\nstatic inline void *unsafe_stack_alloc(size_t size, size_t guard) {\n CHECK_GE(size + guard, size);\n void *addr = MmapOrDie(size + guard, \"unsafe_stack_alloc\");\n MprotectNoAccess((uptr)addr, (uptr)guard);\n return (char *)addr + guard;\n}\n\nstatic inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {\n CHECK_GE((char *)start + size, (char *)start);\n CHECK_GE((char *)start + guard, (char *)start);\n void *stack_ptr = (char *)start + size;\n CHECK_EQ((((size_t)stack_ptr) & (kStackAlign - 1)), 0);\n\n __safestack_unsafe_stack_ptr = stack_ptr;\n unsafe_stack_start = start;\n unsafe_stack_size = size;\n unsafe_stack_guard = guard;\n}\n\nstatic void unsafe_stack_free() {\n if (unsafe_stack_start) {\n UnmapOrDie((char *)unsafe_stack_start - unsafe_stack_guard,\n unsafe_stack_size + unsafe_stack_guard);\n }\n unsafe_stack_start = nullptr;\n}\n\n\/\/\/ Thread data for the cleanup handler\nstatic pthread_key_t thread_cleanup_key;\n\n\/\/\/ Safe stack per-thread information passed to the thread_start function\nstruct tinfo {\n void *(*start_routine)(void *);\n void *start_routine_arg;\n\n void *unsafe_stack_start;\n size_t unsafe_stack_size;\n size_t unsafe_stack_guard;\n};\n\n\/\/\/ Wrap the thread function in order to deallocate the unsafe stack when the\n\/\/\/ thread terminates by returning from its main function.\nstatic void *thread_start(void *arg) {\n struct tinfo *tinfo = (struct tinfo *)arg;\n\n void *(*start_routine)(void *) = tinfo->start_routine;\n void *start_routine_arg = tinfo->start_routine_arg;\n\n \/\/ Setup the unsafe stack; this will destroy tinfo content\n unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,\n tinfo->unsafe_stack_guard);\n\n \/\/ Make sure out thread-specific destructor will be called\n \/\/ FIXME: we can do this only any other specific key is set by\n \/\/ intercepting the pthread_setspecific function itself\n pthread_setspecific(thread_cleanup_key, (void *)1);\n\n return start_routine(start_routine_arg);\n}\n\n\/\/\/ Thread-specific data destructor\nstatic void thread_cleanup_handler(void *_iter) {\n \/\/ We want to free the unsafe stack only after all other destructors\n \/\/ have already run. We force this function to be called multiple times.\n \/\/ User destructors that might run more then PTHREAD_DESTRUCTOR_ITERATIONS-1\n \/\/ times might still end up executing after the unsafe stack is deallocated.\n size_t iter = (size_t)_iter;\n if (iter < PTHREAD_DESTRUCTOR_ITERATIONS) {\n pthread_setspecific(thread_cleanup_key, (void *)(iter + 1));\n } else {\n \/\/ This is the last iteration\n unsafe_stack_free();\n }\n}\n\n\/\/\/ Intercept thread creation operation to allocate and setup the unsafe stack\nINTERCEPTOR(int, pthread_create, pthread_t *thread,\n const pthread_attr_t *attr,\n void *(*start_routine)(void*), void *arg) {\n\n size_t size = 0;\n size_t guard = 0;\n\n if (attr != NULL) {\n pthread_attr_getstacksize(attr, &size);\n pthread_attr_getguardsize(attr, &guard);\n } else {\n \/\/ get pthread default stack size\n pthread_attr_t tmpattr;\n pthread_attr_init(&tmpattr);\n pthread_attr_getstacksize(&tmpattr, &size);\n pthread_attr_getguardsize(&tmpattr, &guard);\n pthread_attr_destroy(&tmpattr);\n }\n\n CHECK_NE(size, 0);\n CHECK_EQ((size & (kStackAlign - 1)), 0);\n CHECK_EQ((guard & (PAGE_SIZE - 1)), 0);\n\n void *addr = unsafe_stack_alloc(size, guard);\n struct tinfo *tinfo =\n (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));\n tinfo->start_routine = start_routine;\n tinfo->start_routine_arg = arg;\n tinfo->unsafe_stack_start = addr;\n tinfo->unsafe_stack_size = size;\n tinfo->unsafe_stack_guard = guard;\n\n return REAL(pthread_create)(thread, attr, thread_start, tinfo);\n}\n\nextern \"C\" __attribute__((visibility(\"default\")))\n#if !SANITIZER_CAN_USE_PREINIT_ARRAY\n\/\/ On ELF platforms, the constructor is invoked using .preinit_array (see below)\n__attribute__((constructor(0)))\n#endif\nvoid __safestack_init() {\n \/\/ Determine the stack size for the main thread.\n size_t size = kDefaultUnsafeStackSize;\n size_t guard = 4096;\n\n struct rlimit limit;\n if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)\n size = limit.rlim_cur;\n\n \/\/ Allocate unsafe stack for main thread\n void *addr = unsafe_stack_alloc(size, guard);\n\n unsafe_stack_setup(addr, size, guard);\n\n \/\/ Initialize pthread interceptors for thread allocation\n INTERCEPT_FUNCTION(pthread_create);\n\n \/\/ Setup the cleanup handler\n pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);\n}\n\n#if SANITIZER_CAN_USE_PREINIT_ARRAY\n\/\/ On ELF platforms, run safestack initialization before any other constructors.\n\/\/ On other platforms we use the constructor attribute to arrange to run our\n\/\/ initialization early.\nextern \"C\" {\n__attribute__((section(\".preinit_array\"),\n used)) void (*__safestack_preinit)(void) = __safestack_init;\n}\n#endif\n\nextern \"C\"\n __attribute__((visibility(\"default\"))) void *__get_unsafe_stack_start() {\n return unsafe_stack_start;\n}\n\nextern \"C\"\n __attribute__((visibility(\"default\"))) void *__get_unsafe_stack_ptr() {\n return __safestack_unsafe_stack_ptr;\n}\n<commit_msg>SafeStack: Add another missing header to try to fix FreeBSD build.<commit_after>\/\/===-- safestack.cc ------------------------------------------------------===\/\/\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\/\/ This file implements the runtime support for the safe stack protection\n\/\/ mechanism. The runtime manages allocation\/deallocation of the unsafe stack\n\/\/ for the main thread, as well as all pthreads that are created\/destroyed\n\/\/ during program execution.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <limits.h>\n#include <pthread.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <sys\/resource.h>\n#include <sys\/types.h>\n#include <sys\/user.h>\n\n#include \"interception\/interception.h\"\n#include \"sanitizer_common\/sanitizer_common.h\"\n\n\/\/ TODO: The runtime library does not currently protect the safe stack beyond\n\/\/ relying on the system-enforced ASLR. The protection of the (safe) stack can\n\/\/ be provided by three alternative features:\n\/\/\n\/\/ 1) Protection via hardware segmentation on x86-32 and some x86-64\n\/\/ architectures: the (safe) stack segment (implicitly accessed via the %ss\n\/\/ segment register) can be separated from the data segment (implicitly\n\/\/ accessed via the %ds segment register). Dereferencing a pointer to the safe\n\/\/ segment would result in a segmentation fault.\n\/\/\n\/\/ 2) Protection via software fault isolation: memory writes that are not meant\n\/\/ to access the safe stack can be prevented from doing so through runtime\n\/\/ instrumentation. One way to do it is to allocate the safe stack(s) in the\n\/\/ upper half of the userspace and bitmask the corresponding upper bit of the\n\/\/ memory addresses of memory writes that are not meant to access the safe\n\/\/ stack.\n\/\/\n\/\/ 3) Protection via information hiding on 64 bit architectures: the location\n\/\/ of the safe stack(s) can be randomized through secure mechanisms, and the\n\/\/ leakage of the stack pointer can be prevented. Currently, libc can leak the\n\/\/ stack pointer in several ways (e.g. in longjmp, signal handling, user-level\n\/\/ context switching related functions, etc.). These can be fixed in libc and\n\/\/ in other low-level libraries, by either eliminating the escaping\/dumping of\n\/\/ the stack pointer (i.e., %rsp) when that's possible, or by using\n\/\/ encryption\/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret\n\/\/ we control and protect better, as is already done for setjmp in glibc.)\n\/\/ Furthermore, a static machine code level verifier can be ran after code\n\/\/ generation to make sure that the stack pointer is never written to memory,\n\/\/ or if it is, its written on the safe stack.\n\/\/\n\/\/ Finally, while the Unsafe Stack pointer is currently stored in a thread\n\/\/ local variable, with libc support it could be stored in the TCB (thread\n\/\/ control block) as well, eliminating another level of indirection and making\n\/\/ such accesses faster. Alternatively, dedicating a separate register for\n\/\/ storing it would also be possible.\n\n\/\/\/ Minimum stack alignment for the unsafe stack.\nconst unsigned kStackAlign = 16;\n\n\/\/\/ Default size of the unsafe stack. This value is only used if the stack\n\/\/\/ size rlimit is set to infinity.\nconst unsigned kDefaultUnsafeStackSize = 0x2800000;\n\n\/\/ TODO: To make accessing the unsafe stack pointer faster, we plan to\n\/\/ eventually store it directly in the thread control block data structure on\n\/\/ platforms where this structure is pointed to by %fs or %gs. This is exactly\n\/\/ the same mechanism as currently being used by the traditional stack\n\/\/ protector pass to store the stack guard (see getStackCookieLocation()\n\/\/ function above). Doing so requires changing the tcbhead_t struct in glibc\n\/\/ on Linux and tcb struct in libc on FreeBSD.\n\/\/\n\/\/ For now, store it in a thread-local variable.\nextern \"C\" {\n__attribute__((visibility(\n \"default\"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;\n}\n\n\/\/ Per-thread unsafe stack information. It's not frequently accessed, so there\n\/\/ it can be kept out of the tcb in normal thread-local variables.\nstatic __thread void *unsafe_stack_start = nullptr;\nstatic __thread size_t unsafe_stack_size = 0;\nstatic __thread size_t unsafe_stack_guard = 0;\n\nstatic inline void *unsafe_stack_alloc(size_t size, size_t guard) {\n CHECK_GE(size + guard, size);\n void *addr = MmapOrDie(size + guard, \"unsafe_stack_alloc\");\n MprotectNoAccess((uptr)addr, (uptr)guard);\n return (char *)addr + guard;\n}\n\nstatic inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {\n CHECK_GE((char *)start + size, (char *)start);\n CHECK_GE((char *)start + guard, (char *)start);\n void *stack_ptr = (char *)start + size;\n CHECK_EQ((((size_t)stack_ptr) & (kStackAlign - 1)), 0);\n\n __safestack_unsafe_stack_ptr = stack_ptr;\n unsafe_stack_start = start;\n unsafe_stack_size = size;\n unsafe_stack_guard = guard;\n}\n\nstatic void unsafe_stack_free() {\n if (unsafe_stack_start) {\n UnmapOrDie((char *)unsafe_stack_start - unsafe_stack_guard,\n unsafe_stack_size + unsafe_stack_guard);\n }\n unsafe_stack_start = nullptr;\n}\n\n\/\/\/ Thread data for the cleanup handler\nstatic pthread_key_t thread_cleanup_key;\n\n\/\/\/ Safe stack per-thread information passed to the thread_start function\nstruct tinfo {\n void *(*start_routine)(void *);\n void *start_routine_arg;\n\n void *unsafe_stack_start;\n size_t unsafe_stack_size;\n size_t unsafe_stack_guard;\n};\n\n\/\/\/ Wrap the thread function in order to deallocate the unsafe stack when the\n\/\/\/ thread terminates by returning from its main function.\nstatic void *thread_start(void *arg) {\n struct tinfo *tinfo = (struct tinfo *)arg;\n\n void *(*start_routine)(void *) = tinfo->start_routine;\n void *start_routine_arg = tinfo->start_routine_arg;\n\n \/\/ Setup the unsafe stack; this will destroy tinfo content\n unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,\n tinfo->unsafe_stack_guard);\n\n \/\/ Make sure out thread-specific destructor will be called\n \/\/ FIXME: we can do this only any other specific key is set by\n \/\/ intercepting the pthread_setspecific function itself\n pthread_setspecific(thread_cleanup_key, (void *)1);\n\n return start_routine(start_routine_arg);\n}\n\n\/\/\/ Thread-specific data destructor\nstatic void thread_cleanup_handler(void *_iter) {\n \/\/ We want to free the unsafe stack only after all other destructors\n \/\/ have already run. We force this function to be called multiple times.\n \/\/ User destructors that might run more then PTHREAD_DESTRUCTOR_ITERATIONS-1\n \/\/ times might still end up executing after the unsafe stack is deallocated.\n size_t iter = (size_t)_iter;\n if (iter < PTHREAD_DESTRUCTOR_ITERATIONS) {\n pthread_setspecific(thread_cleanup_key, (void *)(iter + 1));\n } else {\n \/\/ This is the last iteration\n unsafe_stack_free();\n }\n}\n\n\/\/\/ Intercept thread creation operation to allocate and setup the unsafe stack\nINTERCEPTOR(int, pthread_create, pthread_t *thread,\n const pthread_attr_t *attr,\n void *(*start_routine)(void*), void *arg) {\n\n size_t size = 0;\n size_t guard = 0;\n\n if (attr != NULL) {\n pthread_attr_getstacksize(attr, &size);\n pthread_attr_getguardsize(attr, &guard);\n } else {\n \/\/ get pthread default stack size\n pthread_attr_t tmpattr;\n pthread_attr_init(&tmpattr);\n pthread_attr_getstacksize(&tmpattr, &size);\n pthread_attr_getguardsize(&tmpattr, &guard);\n pthread_attr_destroy(&tmpattr);\n }\n\n CHECK_NE(size, 0);\n CHECK_EQ((size & (kStackAlign - 1)), 0);\n CHECK_EQ((guard & (PAGE_SIZE - 1)), 0);\n\n void *addr = unsafe_stack_alloc(size, guard);\n struct tinfo *tinfo =\n (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));\n tinfo->start_routine = start_routine;\n tinfo->start_routine_arg = arg;\n tinfo->unsafe_stack_start = addr;\n tinfo->unsafe_stack_size = size;\n tinfo->unsafe_stack_guard = guard;\n\n return REAL(pthread_create)(thread, attr, thread_start, tinfo);\n}\n\nextern \"C\" __attribute__((visibility(\"default\")))\n#if !SANITIZER_CAN_USE_PREINIT_ARRAY\n\/\/ On ELF platforms, the constructor is invoked using .preinit_array (see below)\n__attribute__((constructor(0)))\n#endif\nvoid __safestack_init() {\n \/\/ Determine the stack size for the main thread.\n size_t size = kDefaultUnsafeStackSize;\n size_t guard = 4096;\n\n struct rlimit limit;\n if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)\n size = limit.rlim_cur;\n\n \/\/ Allocate unsafe stack for main thread\n void *addr = unsafe_stack_alloc(size, guard);\n\n unsafe_stack_setup(addr, size, guard);\n\n \/\/ Initialize pthread interceptors for thread allocation\n INTERCEPT_FUNCTION(pthread_create);\n\n \/\/ Setup the cleanup handler\n pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);\n}\n\n#if SANITIZER_CAN_USE_PREINIT_ARRAY\n\/\/ On ELF platforms, run safestack initialization before any other constructors.\n\/\/ On other platforms we use the constructor attribute to arrange to run our\n\/\/ initialization early.\nextern \"C\" {\n__attribute__((section(\".preinit_array\"),\n used)) void (*__safestack_preinit)(void) = __safestack_init;\n}\n#endif\n\nextern \"C\"\n __attribute__((visibility(\"default\"))) void *__get_unsafe_stack_start() {\n return unsafe_stack_start;\n}\n\nextern \"C\"\n __attribute__((visibility(\"default\"))) void *__get_unsafe_stack_ptr() {\n return __safestack_unsafe_stack_ptr;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>tools: Fix small bug in ProtoFileToDotProto am: a5221eeff1 am: a9a2fd14c9 am: 7995163897<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * \\file AddTaskHighPtReducedEventCreator.C\n * \\brief Add macro for the reduced event creator task\n * \\author Markus Fasel <markus.fasel@cern.ch>, Lawrence Berkeley National Laboratory\n * \\date Apr 16, 2015\n *\/\n# if !defined __CINT__ || defined __MAKECINT__\n#include <TList.h>\n#include <TROOT.h>\n#include <TString.h>\n#include <TSystem.h>\n#include <TTree.h>\n\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisDataContainer.h\"\n#include \"AliAODInputHandler.h\"\n#include \"AliReducedHighPtEventCreator.h\"\n#endif\n\n\/**\n * Configure reduced event creator task and add it to the analysis manager\n * \\param isMC Flag for MC analysis\n * \\param isPythia Flag for pythia hard analysis\n * \\param trackContainer Name of the track container\n * \\param clusterContainer Name of the cluster container\n * \\param triggerContainer Name of the trigger container\n * \\return Fully configured tree selector task\n *\/\nHighPtTracks::AliReducedHighPtEventCreator *AddTaskHighPtReducedEventCreator(\n Bool_t isMC = kFALSE,\n Bool_t isPythia = kFALSE,\n const char *trackContainer = \"\",\n const char *clusterContainer = \"\",\n const char *triggerContainer = \"\",\n const char *outputfilename = \"\"\n ){\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n \/\/ Create task, make event specific settings\n TString taskname = \"ReducedEventCreator\";\n TString outputname = outputfilename;\n if(outputname.Length){\n taskname = outputname(0, outputname.Index(\".root\"));\n }\n HighPtTracks::AliReducedHighPtEventCreator *reducedEventCreator = new HighPtTracks::AliReducedHighPtEventCreator(taskname.Data());\n if(isPythia) reducedEventCreator->SetIsPythia(kTRUE);\n if(isMC) reducedEventCreator->SetSwapTriggerThresholds(kTRUE);\n reducedEventCreator->AddParticleContainer(trackContainer);\n reducedEventCreator->AddClusterContainer(clusterContainer);\n reducedEventCreator->SetCaloTriggerPatchInfoName(triggerContainer);\n\n \/\/ Set kinematic range for tracks and particles\n reducedEventCreator->SetEtaRange(-0.8, 0.8);\n reducedEventCreator->SetPtRange(0.1,100);\n reducedEventCreator->SetClusterEnergyCut(2., 100.);\n\n \/\/ Handle track selection, outsourced to a different macro\n gROOT->LoadMacro(Form(\"%s\/PWGJE\/EMCALJetTasks\/macros\/ReducedEventCutVariation.C\", gSystem->Getenv(\"ALICE_PHYSICS\")));\n ReducedEventCutVariation(reducedEventCreator, mgr->GetInputEventHandler()->IsA() == AliAODInputHandler::Class());\n\n TString commonoutput = TString(mgr->GetCommonFileName()) + \":\" + taskname;\n TString treeoutputfile = \"ReducedHighPtEvent.root\";\n if(outputname.Length()) treeoutputfile = outputname;\n mgr->ConnectInput(reducedEventCreator, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(reducedEventCreator, 1, mgr->CreateContainer(reducedEventCreator->GetName(), TList::Class(), AliAnalysisManager::kOutputContainer, commonoutput.Data()));\n mgr->ConnectOutput(reducedEventCreator, 2, mgr->CreateContainer(\"ReducedEvent\", TTree::Class(), AliAnalysisManager::kOutputContainer, treeoutputfile.Data()));\n\n return reducedEventCreator;\n}\n<commit_msg>Fix typo<commit_after>\/**\n * \\file AddTaskHighPtReducedEventCreator.C\n * \\brief Add macro for the reduced event creator task\n * \\author Markus Fasel <markus.fasel@cern.ch>, Lawrence Berkeley National Laboratory\n * \\date Apr 16, 2015\n *\/\n# if !defined __CINT__ || defined __MAKECINT__\n#include <TList.h>\n#include <TROOT.h>\n#include <TString.h>\n#include <TSystem.h>\n#include <TTree.h>\n\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisDataContainer.h\"\n#include \"AliAODInputHandler.h\"\n#include \"AliReducedHighPtEventCreator.h\"\n#endif\n\n\/**\n * Configure reduced event creator task and add it to the analysis manager\n * \\param isMC Flag for MC analysis\n * \\param isPythia Flag for pythia hard analysis\n * \\param trackContainer Name of the track container\n * \\param clusterContainer Name of the cluster container\n * \\param triggerContainer Name of the trigger container\n * \\return Fully configured tree selector task\n *\/\nHighPtTracks::AliReducedHighPtEventCreator *AddTaskHighPtReducedEventCreator(\n Bool_t isMC = kFALSE,\n Bool_t isPythia = kFALSE,\n const char *trackContainer = \"\",\n const char *clusterContainer = \"\",\n const char *triggerContainer = \"\",\n const char *outputfilename = \"\"\n ){\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n \/\/ Create task, make event specific settings\n TString taskname = \"ReducedEventCreator\";\n TString outputname = outputfilename;\n if(outputname.Length()){\n taskname = outputname(0, outputname.Index(\".root\"));\n }\n HighPtTracks::AliReducedHighPtEventCreator *reducedEventCreator = new HighPtTracks::AliReducedHighPtEventCreator(taskname.Data());\n if(isPythia) reducedEventCreator->SetIsPythia(kTRUE);\n if(isMC) reducedEventCreator->SetSwapTriggerThresholds(kTRUE);\n reducedEventCreator->AddParticleContainer(trackContainer);\n reducedEventCreator->AddClusterContainer(clusterContainer);\n reducedEventCreator->SetCaloTriggerPatchInfoName(triggerContainer);\n\n \/\/ Set kinematic range for tracks and particles\n reducedEventCreator->SetEtaRange(-0.8, 0.8);\n reducedEventCreator->SetPtRange(0.1,100);\n reducedEventCreator->SetClusterEnergyCut(2., 100.);\n\n \/\/ Handle track selection, outsourced to a different macro\n gROOT->LoadMacro(Form(\"%s\/PWGJE\/EMCALJetTasks\/macros\/ReducedEventCutVariation.C\", gSystem->Getenv(\"ALICE_PHYSICS\")));\n ReducedEventCutVariation(reducedEventCreator, mgr->GetInputEventHandler()->IsA() == AliAODInputHandler::Class());\n\n TString commonoutput = TString(mgr->GetCommonFileName()) + \":\" + taskname;\n TString treeoutputfile = \"ReducedHighPtEvent.root\";\n if(outputname.Length()) treeoutputfile = outputname;\n mgr->ConnectInput(reducedEventCreator, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(reducedEventCreator, 1, mgr->CreateContainer(reducedEventCreator->GetName(), TList::Class(), AliAnalysisManager::kOutputContainer, commonoutput.Data()));\n mgr->ConnectOutput(reducedEventCreator, 2, mgr->CreateContainer(\"ReducedEvent\", TTree::Class(), AliAnalysisManager::kOutputContainer, treeoutputfile.Data()));\n\n return reducedEventCreator;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ParticleSwarmOptimization.h\n\n#pragma once\n\n#include \"..\/Stdafx.h\"\n#include \"Particle.hpp\"\n#include \"Function.hpp\"\nusing namespace ParticleSwarmOptimization;\n\nnamespace ParticleSwarmOptimization {\n\n\tclass StandardParticle : public Particle {\n\tpublic:\n\t explicit StandardParticle(int dimensions) : dimensions_(dimensions)\n\t\t{\n\t\t\tpersonal_best_ = make_tuple(std::vector<double>(2), std::numeric_limits<double>::infinity());\n\t\t}\n\n\t\tvoid init_location() override\n\t\t{\n\t\t\tstd::vector<double> location(dimensions_);\n\t\t\t\/\/ this probably should go to static field or we should create ParticlesFactory responsible \n\t\t\t\/\/ for generating particles with proper distribution of location and in specific limits\n\t\t\tstd::uniform_real_distribution<float> distribution(0.0f, 10.0f); \n\t\t\tstd::mt19937 engine; \/\/ Mersenne twister MT19937\n\t\t\tauto generator = bind(distribution, engine);\n\t\t\tgenerate(location.begin(), location.end(), generator); \n\t\t\t\/\/ to remove after improving generation logic\n\t\t\tif (bounds_.size() == dimensions_) {\n\t\t\t\ttransform(location.begin(), location.end(), bounds_.begin(), location.begin(), &clamp);\n\t\t\t}\n\t\t\tlocation_ = location;\n\t\t}\n\n\t\tvoid init_velocity() override\n\t\t{\n\t\t\tstd::vector<double> velocity(dimensions_);\n\t\t\tstd::uniform_real_distribution<float> distribution(0.0f, 2.0f); \/\/Values between 0 and 2\n\t\t\tstd::mt19937 engine; \/\/ Mersenne twister MT19937\n\t\t\tauto generator = std::bind(distribution, engine);\n\t\t\tgenerate(velocity.begin(), velocity.end(), generator);\n\t\t\tvelocity_ = velocity;\n\t\t}\n\n\t\tstd::tuple<std::vector<double>, double> update_personal_best(Function *function) override\n\t\t{\n\t\t\tauto value = function->evaluate(location_);\n\t\t\treturn std::get<1>(personal_best_) > value ?\n\t\t\t\t(personal_best_ = make_tuple(location_, value)) : personal_best_;\n\t\t}\n\n\t\tvoid update_neighborhood(std::vector<Particle*> all_particles) override\n\t\t{\n\t\t\tif (neighborhood_.size() <= 0 )\n\t\t\t{\n\t\t\t\tneighborhood_ = all_particles;\n\t\t\t}\n\t\t}\n\n\t\tvoid update_velocity() override\n\t\t{\n\t\t\tstd::tuple<std::vector<double>, double> global_best = personal_best_;\n\n\t\t\tfor (int i = 0; i < neighborhood_.size(); ++i)\n\t\t\t{\n\t\t\t\tif (std::get<1>(neighborhood_[i]->get_personal_best()) > std::get<1>(global_best))\n\t\t\t\t\tglobal_best = neighborhood_[i]->get_personal_best();\n\t\t\t}\n\n\t\t\tstd::vector<double> to_personal_best(dimensions_);\n\t\t\tstd::vector<double> to_global_best(dimensions_);\n\n\t\t\ttransform(std::get<0>(personal_best_).begin(), std::get<0>(personal_best_).end(), \n\t\t\t\tlocation_.begin(), to_personal_best.begin(), std::minus<double>());\n\n\t\t\ttransform(std::get<0>(global_best).begin(), std::get<0>(global_best).end(), location_.begin(), to_global_best.begin(),\n\t\t\t\tstd::minus<double>());\n\n\t\t\tstd::random_device rd;\n\t\t\tstd::default_random_engine e1(rd());\n\t\t\tstd::uniform_real_distribution<float> uniform_dist(0.0f, 1.4f);\n\t\t\tdouble phi1 = uniform_dist(e1);\n\t\t\tdouble phi2 = uniform_dist(e1);\n\t\t\tdouble omega = 0.64;\n\t\t\t\/\/1.4, 1.4, 0.64\n\t\t\ttransform(to_personal_best.begin(), to_personal_best.end(), to_personal_best.begin(),\n\t\t\t\tbind1st(std::multiplies<double>(), phi1));\n\n\t\t\ttransform(to_global_best.begin(), to_global_best.end(), to_global_best.begin(),\n\t\t\t\tbind1st(std::multiplies<double>(), phi2));\n\t\t\t\/\/przemnozyc przez omege\n\t\t\ttransform(velocity_.begin(), velocity_.end(), velocity_.begin(), bind1st(std::multiplies<double>(), omega));\n\n\t\t\ttransform(velocity_.begin(), velocity_.end(), to_global_best.begin(), velocity_.begin(), std::plus<double>());\n\t\t\ttransform(velocity_.begin(), velocity_.end(), to_personal_best.begin(), velocity_.begin(), std::plus<double>());\n\t\t}\n\n\t\tvoid translate() override\n\t\t{\n\t\t\ttransform(location_.begin(), location_.end(), velocity_.begin(),\n\t\t\t\tlocation_.begin(), std::plus<double>());\n\t\t\tif (bounds_.size() == dimensions_) {\n\t\t\t\ttransform(location_.begin(), location_.end(), bounds_.begin(), location_.begin(), &clamp);\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tint dimensions_;\n\t};\n}\n<commit_msg>particle restart<commit_after>\/\/ ParticleSwarmOptimization.h\n\n#pragma once\n\n#include \"..\/Stdafx.h\"\n#include \"Particle.hpp\"\n#include \"Function.hpp\"\nusing namespace ParticleSwarmOptimization;\n\nnamespace ParticleSwarmOptimization {\n\n\tclass StandardParticle : public Particle {\n\tprivate:\n\t\tint iters_from_last_best_change;\n\t\tconst int restart_iters = 100;\n\n\tpublic:\n\t explicit StandardParticle(int dimensions) : dimensions_(dimensions)\n\t\t{\n\t\t\titers_from_last_best_change = 0;\n\t\t\tpersonal_best_ = make_tuple(std::vector<double>(2), std::numeric_limits<double>::infinity());\n\t\t}\n\n\t\tvoid init_location() override\n\t\t{\n\t\t\tstd::vector<double> location(dimensions_);\n\t\t\t\/\/ this probably should go to static field or we should create ParticlesFactory responsible \n\t\t\t\/\/ for generating particles with proper distribution of location and in specific limits\n\t\t\tstd::uniform_real_distribution<float> distribution(0.0f, 10.0f); \n\t\t\tstd::mt19937 engine; \/\/ Mersenne twister MT19937\n\t\t\tauto generator = bind(distribution, engine);\n\t\t\tgenerate(location.begin(), location.end(), generator); \n\t\t\t\/\/ to remove after improving generation logic\n\t\t\tif (bounds_.size() == dimensions_) {\n\t\t\t\ttransform(location.begin(), location.end(), bounds_.begin(), location.begin(), &clamp);\n\t\t\t}\n\t\t\tlocation_ = location;\n\t\t}\n\n\t\tvoid init_velocity() override\n\t\t{\n\t\t\tstd::vector<double> velocity(dimensions_);\n\t\t\tstd::uniform_real_distribution<float> distribution(0.0f, 2.0f); \/\/Values between 0 and 2\n\t\t\tstd::mt19937 engine; \/\/ Mersenne twister MT19937\n\t\t\tauto generator = std::bind(distribution, engine);\n\t\t\tgenerate(velocity.begin(), velocity.end(), generator);\n\t\t\tvelocity_ = velocity;\n\t\t}\n\n\t\tstd::tuple<std::vector<double>, double> update_personal_best(Function *function) override\n\t\t{\n\t\t\tauto value = function->evaluate(location_);\n\n\t\t\tif (std::get<1>(personal_best_)>value)\n\t\t\t{\n\t\t\t\tpersonal_best_ = make_tuple(location_, value);\n\t\t\t\titers_from_last_best_change = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (++iters_from_last_best_change>restart_iters)\n\t\t\t\t{\n\t\t\t\t\titers_from_last_best_change = 0;\n\t\t\t\t\tinit_location();\n\t\t\t\t\t\/\/init_velocity();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn personal_best_;\n\t\t}\n\n\t\tvoid update_neighborhood(std::vector<Particle*> all_particles) override\n\t\t{\n\t\t\tif (neighborhood_.size() <= 0 )\n\t\t\t{\n\t\t\t\tneighborhood_ = all_particles;\n\t\t\t}\n\t\t}\n\n\t\tvoid update_velocity() override\n\t\t{\n\t\t\tstd::tuple<std::vector<double>, double> global_best = personal_best_;\n\n\t\t\tfor (int i = 0; i < neighborhood_.size(); ++i)\n\t\t\t{\n\t\t\t\tif (std::get<1>(neighborhood_[i]->get_personal_best()) > std::get<1>(global_best))\n\t\t\t\t\tglobal_best = neighborhood_[i]->get_personal_best();\n\t\t\t}\n\n\t\t\tstd::vector<double> to_personal_best(dimensions_);\n\t\t\tstd::vector<double> to_global_best(dimensions_);\n\n\t\t\ttransform(std::get<0>(personal_best_).begin(), std::get<0>(personal_best_).end(), \n\t\t\t\tlocation_.begin(), to_personal_best.begin(), std::minus<double>());\n\n\t\t\ttransform(std::get<0>(global_best).begin(), std::get<0>(global_best).end(), location_.begin(), to_global_best.begin(),\n\t\t\t\tstd::minus<double>());\n\n\t\t\tstd::random_device rd;\n\t\t\tstd::default_random_engine e1(rd());\n\t\t\tstd::uniform_real_distribution<float> uniform_dist(0.0f, 1.4f);\n\t\t\tdouble phi1 = uniform_dist(e1);\n\t\t\tdouble phi2 = uniform_dist(e1);\n\t\t\tdouble omega = 0.64;\n\t\t\t\/\/1.4, 1.4, 0.64\n\t\t\ttransform(to_personal_best.begin(), to_personal_best.end(), to_personal_best.begin(),\n\t\t\t\tbind1st(std::multiplies<double>(), phi1));\n\n\t\t\ttransform(to_global_best.begin(), to_global_best.end(), to_global_best.begin(),\n\t\t\t\tbind1st(std::multiplies<double>(), phi2));\n\t\t\t\/\/przemnozyc przez omege\n\t\t\ttransform(velocity_.begin(), velocity_.end(), velocity_.begin(), bind1st(std::multiplies<double>(), omega));\n\n\t\t\ttransform(velocity_.begin(), velocity_.end(), to_global_best.begin(), velocity_.begin(), std::plus<double>());\n\t\t\ttransform(velocity_.begin(), velocity_.end(), to_personal_best.begin(), velocity_.begin(), std::plus<double>());\n\t\t}\n\n\t\tvoid translate() override\n\t\t{\n\t\t\ttransform(location_.begin(), location_.end(), velocity_.begin(),\n\t\t\t\tlocation_.begin(), std::plus<double>());\n\t\t\tif (bounds_.size() == dimensions_) {\n\t\t\t\ttransform(location_.begin(), location_.end(), bounds_.begin(), location_.begin(), &clamp);\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tint dimensions_;\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/$$ newmat1.cpp Matrix type functions\n\n\/\/ Copyright (C) 1991,2,3,4: R B Davies\n\n\/\/#define WANT_STREAM\n\n#ifndef __GNUC__\n#error fish\n#elif defined(__APPLE__)\n#error fish\n#elif (__GNUC_MINOR__>0) && (__GNUC_MINOR__<3)\n#error fish\n#endif\n\n#include \"newmat.h\"\n\n#ifdef use_namespace\nnamespace NEWMAT {\n#endif\n\n#ifdef DO_REPORT\n#define REPORT { static ExeCounter ExeCount(__LINE__,1); ++ExeCount; }\n#else\n#define REPORT {}\n#endif\n\n\n\/************************* MatrixType functions *****************************\/\n\n\n\/\/ all operations to return MatrixTypes which correspond to valid types\n\/\/ of matrices.\n\/\/ Eg: if it has the Diagonal attribute, then it must also have\n\/\/ Upper, Lower, Band and Symmetric.\n\n\nMatrixType MatrixType::operator*(const MatrixType& mt) const\n{\n REPORT\n int a = attribute & mt.attribute & ~Symmetric;\n a |= (a & Diagonal) * 31; \/\/ recognise diagonal\n return MatrixType(a);\n}\n\nMatrixType MatrixType::SP(const MatrixType& mt) const\n\/\/ elementwise product\n\/\/ Lower, Upper, Diag, Band if only one is\n\/\/ Symmetric, Ones, Valid (and Real) if both are\n\/\/ Need to include Lower & Upper => Diagonal\n\/\/ Will need to include both Skew => Symmetric\n{\n REPORT\n int a = ((attribute | mt.attribute) & ~(Symmetric + Valid + Ones))\n | (attribute & mt.attribute);\n if ((a & Lower) != 0 && (a & Upper) != 0) a |= Diagonal;\n a |= (a & Diagonal) * 31; \/\/ recognise diagonal\n return MatrixType(a);\n}\n\nMatrixType MatrixType::KP(const MatrixType& mt) const\n\/\/ Kronecker product\n\/\/ Lower, Upper, Diag, Symmetric, Band, Valid if both are\n\/\/ Do not treat Band separately\n\/\/ Ones is complicated so leave this out\n{\n REPORT\n int a = (attribute & mt.attribute) & ~Ones;\n return MatrixType(a);\n}\n\nMatrixType MatrixType::i() const \/\/ type of inverse\n{\n REPORT\n int a = attribute & ~(Band+LUDeco);\n a |= (a & Diagonal) * 31; \/\/ recognise diagonal\n return MatrixType(a);\n}\n\nMatrixType MatrixType::t() const\n\/\/ swap lower and upper attributes\n\/\/ assume Upper is in bit above Lower\n{\n REPORT\n int a = attribute;\n a ^= (((a >> 1) ^ a) & Lower) * 3;\n return MatrixType(a);\n}\n\nMatrixType MatrixType::MultRHS() const\n{\n REPORT\n \/\/ remove symmetric attribute unless diagonal\n return (attribute >= Dg) ? attribute : (attribute & ~Symmetric);\n}\n\nbool Rectangular(MatrixType a, MatrixType b, MatrixType c)\n{\n REPORT\n return\n ((a.attribute | b.attribute | c.attribute) & ~MatrixType::Valid) == 0;\n}\n\nconst char* MatrixType::Value() const\n{\n\/\/ make a string with the name of matrix with the given attributes\n switch (attribute)\n {\n case Valid: REPORT return \"Rect \";\n case Valid+Symmetric: REPORT return \"Sym \";\n case Valid+Band: REPORT return \"Band \";\n case Valid+Symmetric+Band: REPORT return \"SmBnd\";\n case Valid+Upper: REPORT return \"UT \";\n case Valid+Diagonal+Symmetric+Band+Upper+Lower:\n REPORT return \"Diag \";\n case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones:\n REPORT return \"Ident\";\n case Valid+Band+Upper: REPORT return \"UpBnd\";\n case Valid+Lower: REPORT return \"LT \";\n case Valid+Band+Lower: REPORT return \"LwBnd\";\n default:\n REPORT\n if (!(attribute & Valid)) return \"UnSp \";\n if (attribute & LUDeco)\n return (attribute & Band) ? \"BndLU\" : \"Crout\";\n return \"?????\";\n }\n}\n\n\nGeneralMatrix* MatrixType::New(int nr, int nc, BaseMatrix* bm) const\n{\n\/\/ make a new matrix with the given attributes\n\n Tracer tr(\"New\"); GeneralMatrix* gm=0; \/\/ initialised to keep gnu happy\n switch (attribute)\n {\n case Valid:\n REPORT\n if (nc==1) { gm = new ColumnVector(nr); break; }\n if (nr==1) { gm = new RowVector(nc); break; }\n gm = new Matrix(nr, nc); break;\n\n case Valid+Symmetric:\n REPORT gm = new SymmetricMatrix(nr); break;\n\n case Valid+Band:\n {\n REPORT\n MatrixBandWidth bw = bm->BandWidth();\n gm = new BandMatrix(nr,bw.lower,bw.upper); break;\n }\n\n case Valid+Symmetric+Band:\n REPORT gm = new SymmetricBandMatrix(nr,bm->BandWidth().lower); break;\n\n case Valid+Upper:\n REPORT gm = new UpperTriangularMatrix(nr); break;\n\n case Valid+Diagonal+Symmetric+Band+Upper+Lower:\n REPORT gm = new DiagonalMatrix(nr); break;\n\n case Valid+Band+Upper:\n REPORT gm = new UpperBandMatrix(nr,bm->BandWidth().upper); break;\n\n case Valid+Lower:\n REPORT gm = new LowerTriangularMatrix(nr); break;\n\n case Valid+Band+Lower:\n REPORT gm = new LowerBandMatrix(nr,bm->BandWidth().lower); break;\n\n case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones:\n REPORT gm = new IdentityMatrix(nr); break;\n\n default:\n Throw(ProgramException(\"Invalid matrix type\"));\n }\n \n MatrixErrorNoSpace(gm); gm->Protect(); return gm;\n}\n\n\n#ifdef use_namespace\n}\n#endif\n\n<commit_msg>r4612\/sofa-dev : <commit_after>\/\/$$ newmat1.cpp Matrix type functions\n\n\/\/ Copyright (C) 1991,2,3,4: R B Davies\n\n\/\/#define WANT_STREAM\n\n#error fish\n\n#include \"newmat.h\"\n\n#ifdef use_namespace\nnamespace NEWMAT {\n#endif\n\n#ifdef DO_REPORT\n#define REPORT { static ExeCounter ExeCount(__LINE__,1); ++ExeCount; }\n#else\n#define REPORT {}\n#endif\n\n\n\/************************* MatrixType functions *****************************\/\n\n\n\/\/ all operations to return MatrixTypes which correspond to valid types\n\/\/ of matrices.\n\/\/ Eg: if it has the Diagonal attribute, then it must also have\n\/\/ Upper, Lower, Band and Symmetric.\n\n\nMatrixType MatrixType::operator*(const MatrixType& mt) const\n{\n REPORT\n int a = attribute & mt.attribute & ~Symmetric;\n a |= (a & Diagonal) * 31; \/\/ recognise diagonal\n return MatrixType(a);\n}\n\nMatrixType MatrixType::SP(const MatrixType& mt) const\n\/\/ elementwise product\n\/\/ Lower, Upper, Diag, Band if only one is\n\/\/ Symmetric, Ones, Valid (and Real) if both are\n\/\/ Need to include Lower & Upper => Diagonal\n\/\/ Will need to include both Skew => Symmetric\n{\n REPORT\n int a = ((attribute | mt.attribute) & ~(Symmetric + Valid + Ones))\n | (attribute & mt.attribute);\n if ((a & Lower) != 0 && (a & Upper) != 0) a |= Diagonal;\n a |= (a & Diagonal) * 31; \/\/ recognise diagonal\n return MatrixType(a);\n}\n\nMatrixType MatrixType::KP(const MatrixType& mt) const\n\/\/ Kronecker product\n\/\/ Lower, Upper, Diag, Symmetric, Band, Valid if both are\n\/\/ Do not treat Band separately\n\/\/ Ones is complicated so leave this out\n{\n REPORT\n int a = (attribute & mt.attribute) & ~Ones;\n return MatrixType(a);\n}\n\nMatrixType MatrixType::i() const \/\/ type of inverse\n{\n REPORT\n int a = attribute & ~(Band+LUDeco);\n a |= (a & Diagonal) * 31; \/\/ recognise diagonal\n return MatrixType(a);\n}\n\nMatrixType MatrixType::t() const\n\/\/ swap lower and upper attributes\n\/\/ assume Upper is in bit above Lower\n{\n REPORT\n int a = attribute;\n a ^= (((a >> 1) ^ a) & Lower) * 3;\n return MatrixType(a);\n}\n\nMatrixType MatrixType::MultRHS() const\n{\n REPORT\n \/\/ remove symmetric attribute unless diagonal\n return (attribute >= Dg) ? attribute : (attribute & ~Symmetric);\n}\n\nbool Rectangular(MatrixType a, MatrixType b, MatrixType c)\n{\n REPORT\n return\n ((a.attribute | b.attribute | c.attribute) & ~MatrixType::Valid) == 0;\n}\n\nconst char* MatrixType::Value() const\n{\n\/\/ make a string with the name of matrix with the given attributes\n switch (attribute)\n {\n case Valid: REPORT return \"Rect \";\n case Valid+Symmetric: REPORT return \"Sym \";\n case Valid+Band: REPORT return \"Band \";\n case Valid+Symmetric+Band: REPORT return \"SmBnd\";\n case Valid+Upper: REPORT return \"UT \";\n case Valid+Diagonal+Symmetric+Band+Upper+Lower:\n REPORT return \"Diag \";\n case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones:\n REPORT return \"Ident\";\n case Valid+Band+Upper: REPORT return \"UpBnd\";\n case Valid+Lower: REPORT return \"LT \";\n case Valid+Band+Lower: REPORT return \"LwBnd\";\n default:\n REPORT\n if (!(attribute & Valid)) return \"UnSp \";\n if (attribute & LUDeco)\n return (attribute & Band) ? \"BndLU\" : \"Crout\";\n return \"?????\";\n }\n}\n\n\nGeneralMatrix* MatrixType::New(int nr, int nc, BaseMatrix* bm) const\n{\n\/\/ make a new matrix with the given attributes\n\n Tracer tr(\"New\"); GeneralMatrix* gm=0; \/\/ initialised to keep gnu happy\n switch (attribute)\n {\n case Valid:\n REPORT\n if (nc==1) { gm = new ColumnVector(nr); break; }\n if (nr==1) { gm = new RowVector(nc); break; }\n gm = new Matrix(nr, nc); break;\n\n case Valid+Symmetric:\n REPORT gm = new SymmetricMatrix(nr); break;\n\n case Valid+Band:\n {\n REPORT\n MatrixBandWidth bw = bm->BandWidth();\n gm = new BandMatrix(nr,bw.lower,bw.upper); break;\n }\n\n case Valid+Symmetric+Band:\n REPORT gm = new SymmetricBandMatrix(nr,bm->BandWidth().lower); break;\n\n case Valid+Upper:\n REPORT gm = new UpperTriangularMatrix(nr); break;\n\n case Valid+Diagonal+Symmetric+Band+Upper+Lower:\n REPORT gm = new DiagonalMatrix(nr); break;\n\n case Valid+Band+Upper:\n REPORT gm = new UpperBandMatrix(nr,bm->BandWidth().upper); break;\n\n case Valid+Lower:\n REPORT gm = new LowerTriangularMatrix(nr); break;\n\n case Valid+Band+Lower:\n REPORT gm = new LowerBandMatrix(nr,bm->BandWidth().lower); break;\n\n case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones:\n REPORT gm = new IdentityMatrix(nr); break;\n\n default:\n Throw(ProgramException(\"Invalid matrix type\"));\n }\n \n MatrixErrorNoSpace(gm); gm->Protect(); return gm;\n}\n\n\n#ifdef use_namespace\n}\n#endif\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Avoid breaking up short lines<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ quicksort.cpp\n\/\/ DataStructs_Practice\n\/\/\n\/\/ Created by Jay Patel on 2016-01-30.\n\/\/ Copyright © 2016 jay. All rights reserved.\n\/\/\n\n#include <iostream>\n#include <vector>\n#include <stdlib.h>\n\n\nlong partitionStep(std::vector<int>&, long, long);\n\nvoid recur(std::vector<int>&, long, long);\n\n\nvoid printVector(std::vector<int>&);\n\nint ctr(0);\n\nint main() {\n \n srand(time(0));\n \n std::vector<int> structToSort {43,43,43453,-673474,352528,393,79,36,134,16,62,255,-3452,-51};\n \n recur(structToSort, 0, structToSort.size()-1);\n \n \n printVector(structToSort);\n \n \n \n \n \n \n return 0;\n \n}\n\n\n\/\/the partition step\nlong partitionStep(std::vector<int>& a, long s, long e) {\n unsigned int pivotI = (rand()%(e - s)) + s, l(s), r(e);\n int pivotVal = a.at(pivotI);\n \n \n while(l < r) {\n bool lismet, rismet; lismet = rismet = false;\n while (!lismet) {\n if (a[l] >= pivotVal)\n lismet = true;\n else\n l++;\n };\n while (!rismet) {\n if (a[r] <= pivotVal)\n rismet = true;\n else\n r--;\n };\n \n if (a[l] == a[r])\n l++;\n else{\n \/\/switch the two\n int tempLHolder = a.at(l);\n a[l] = a[r];\n a[r] = tempLHolder;\n };\n \n };\n \n \n \n return r;\n};\n\n\/\/the recursive quicksort call\nvoid recur(std::vector<int>& a, long s, long e) {\n if (s < e) {\n long pIndex = partitionStep(a, s, e);\n recur(a, s, pIndex-1);\n recur(a, pIndex+1, e);\n };\n};\n\n\n\nvoid printVector(std::vector<int>& v) {\n std::cout << \"-----------------------------------------\\n\";\n for (long i = v.size(); i > 0; i--) {\n std::cout << v[i-1] << \", \";\n }\n std::cout << \"Done\\n-----------------------------------------\\n\";\n};<commit_msg>Update quicksort.cpp<commit_after>\/\/\n\/\/ quicksort.cpp\n\/\/ DataStructs_Practice\n\/\/\n\/\/ Created by Jay Patel on 2016-01-30.\n\/\/ Copyright © 2016 jay. All rights reserved.\n\/\/\n\n#include <iostream>\n#include <vector>\n#include <stdlib.h>\n\n\nlong partitionStep(std::vector<int>&, long, long);\n\nvoid recur(std::vector<int>&, long, long);\n\n\nvoid printVector(std::vector<int>&);\n\n\nint main() {\n \n srand(time(0));\n \n std::vector<int> structToSort {43,43,43453,-673474,352528,393,79,36,134,16,62,255,-3452,-51};\n \n recur(structToSort, 0, structToSort.size()-1);\n \n \n printVector(structToSort);\n \n \n \n \n \n \n return 0;\n \n}\n\n\n\/\/the partition step\nlong partitionStep(std::vector<int>& a, long s, long e) {\n unsigned int pivotI = (rand()%(e - s)) + s, l(s), r(e);\n int pivotVal = a.at(pivotI);\n \n \n while(l < r) {\n bool lismet, rismet; lismet = rismet = false;\n while (!lismet) {\n if (a[l] >= pivotVal)\n lismet = true;\n else\n l++;\n };\n while (!rismet) {\n if (a[r] <= pivotVal)\n rismet = true;\n else\n r--;\n };\n \n if (a[l] == a[r])\n l++;\n else{\n \/\/switch the two\n int tempLHolder = a.at(l);\n a[l] = a[r];\n a[r] = tempLHolder;\n };\n \n };\n \n \n \n return r;\n};\n\n\/\/the recursive quicksort call\nvoid recur(std::vector<int>& a, long s, long e) {\n if (s < e) {\n long pIndex = partitionStep(a, s, e);\n recur(a, s, pIndex-1);\n recur(a, pIndex+1, e);\n };\n};\n\n\n\nvoid printVector(std::vector<int>& v) {\n std::cout << \"-----------------------------------------\\n\";\n for (long i = v.size(); i > 0; i--) {\n std::cout << v[i-1] << \", \";\n }\n std::cout << \"Done\\n-----------------------------------------\\n\";\n};\n<|endoftext|>"} {"text":"<commit_before>#include <agency\/new_executor_traits.hpp>\n#include <cassert>\n#include <iostream>\n\n#include \"test_executors.hpp\"\n\ntemplate<class Executor>\nvoid test()\n{\n using executor_type = Executor;\n\n {\n \/\/ void -> void\n executor_type exec;\n\n auto void_future = agency::when_all();\n\n int set_me_to_thirteen = 0;\n\n auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&]\n {\n set_me_to_thirteen = 13;\n },\n void_future);\n\n f.wait();\n\n assert(set_me_to_thirteen == 13);\n assert(exec.valid());\n }\n\n {\n \/\/ void -> int\n executor_type exec;\n\n auto void_future = agency::when_all();\n\n auto f = agency::new_executor_traits<executor_type>::then_execute(exec, []\n {\n return 13;\n },\n void_future);\n\n assert(f.get() == 13);\n assert(exec.valid());\n }\n\n {\n \/\/ int -> void\n executor_type exec;\n\n auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13);\n\n int set_me_to_thirteen = 0;\n\n auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&](int& x)\n {\n set_me_to_thirteen = x;\n },\n int_future);\n\n f.wait();\n\n assert(set_me_to_thirteen == 13);\n assert(exec.valid());\n }\n\n {\n \/\/ int -> float\n executor_type exec;\n\n auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13);\n\n auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [](int &x)\n {\n return float(x) + 1.f;\n },\n int_future);\n\n assert(f.get() == 14.f);\n assert(exec.valid());\n }\n}\n\nint main()\n{\n using namespace test_executors;\n\n test<empty_executor>();\n test<single_agent_when_all_execute_and_select_executor>();\n test<multi_agent_when_all_execute_and_select_executor>();\n test<single_agent_then_execute_executor>();\n\n test<multi_agent_execute_returning_user_defined_container_executor>();\n test<multi_agent_execute_returning_default_container_executor>();\n test<multi_agent_execute_returning_void_executor>();\n\n test<multi_agent_async_execute_returning_user_defined_container_executor>();\n\n std::cout << \"OK\" << std::endl;\n\n return 0;\n}\n\n<commit_msg>Test multi_agent_async_execute_returning_default_container_executor with test_single_agent_then_execute.cpp.<commit_after>#include <agency\/new_executor_traits.hpp>\n#include <cassert>\n#include <iostream>\n\n#include \"test_executors.hpp\"\n\ntemplate<class Executor>\nvoid test()\n{\n using executor_type = Executor;\n\n {\n \/\/ void -> void\n executor_type exec;\n\n auto void_future = agency::when_all();\n\n int set_me_to_thirteen = 0;\n\n auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&]\n {\n set_me_to_thirteen = 13;\n },\n void_future);\n\n f.wait();\n\n assert(set_me_to_thirteen == 13);\n assert(exec.valid());\n }\n\n {\n \/\/ void -> int\n executor_type exec;\n\n auto void_future = agency::when_all();\n\n auto f = agency::new_executor_traits<executor_type>::then_execute(exec, []\n {\n return 13;\n },\n void_future);\n\n assert(f.get() == 13);\n assert(exec.valid());\n }\n\n {\n \/\/ int -> void\n executor_type exec;\n\n auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13);\n\n int set_me_to_thirteen = 0;\n\n auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&](int& x)\n {\n set_me_to_thirteen = x;\n },\n int_future);\n\n f.wait();\n\n assert(set_me_to_thirteen == 13);\n assert(exec.valid());\n }\n\n {\n \/\/ int -> float\n executor_type exec;\n\n auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13);\n\n auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [](int &x)\n {\n return float(x) + 1.f;\n },\n int_future);\n\n assert(f.get() == 14.f);\n assert(exec.valid());\n }\n}\n\nint main()\n{\n using namespace test_executors;\n\n test<empty_executor>();\n test<single_agent_when_all_execute_and_select_executor>();\n test<multi_agent_when_all_execute_and_select_executor>();\n test<single_agent_then_execute_executor>();\n\n test<multi_agent_execute_returning_user_defined_container_executor>();\n test<multi_agent_execute_returning_default_container_executor>();\n test<multi_agent_execute_returning_void_executor>();\n\n test<multi_agent_async_execute_returning_user_defined_container_executor>();\n test<multi_agent_async_execute_returning_default_container_executor>();\n\n std::cout << \"OK\" << std::endl;\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef DKN_HPP_\n#define DKN_HPP_\n#include \"basics.hpp\"\n\n#include <vector>\n#include <flann\/flann.hpp>\n\ntemplate <typename Distance>\nstd::vector<typename Distance::ResultType> DKN(\n flann::Index<Distance> &index,\n const flann::Matrix<typename Distance::ElementType> &query,\n int k = 3,\n const flann::SearchParams &search_params = flann::SearchParams())\n{ \/* Get the distances to the k-th nearest neighbor of each element in query\n * using the passed index and search params.\n *\/\n using std::vector;\n using flann::Matrix;\n\n typedef typename Distance::ResultType DistanceType;\n\n \/\/ matrices to store the results\n Matrix<int> indices(new int[query.rows*k], query.rows, k);\n Matrix<DistanceType> dists(new DistanceType[query.rows*k], query.rows, k);\n\n \/\/ build the index if necessary\n index.buildIndex();\n\n \/\/ search!\n index.knnSearch(query, indices, dists, k, search_params);\n\n \/\/ get out just the results we want\n vector<DistanceType> dkn;\n dkn.reserve(query.rows);\n for (size_t i = 0; i < query.rows; i++) {\n dkn.push_back(dists[i][k-1]);\n }\n\n delete[] indices.ptr();\n delete[] dists.ptr();\n\n return dkn;\n}\n\n#endif\n<commit_msg>flann::L2 is the *squared* euclidean distance, silly<commit_after>#ifndef DKN_HPP_\n#define DKN_HPP_\n#include \"basics.hpp\"\n\n#include <cmath>\n#include <vector>\n#include <flann\/flann.hpp>\n\ntemplate <typename Distance>\nstd::vector<typename Distance::ResultType> DKN(\n flann::Index<Distance> &index,\n const flann::Matrix<typename Distance::ElementType> &query,\n int k = 3,\n const flann::SearchParams &search_params = flann::SearchParams(),\n bool take_sqrt = true)\n{ \/* Get the distances to the k-th nearest neighbor of each element in query\n * using the passed index and search params.\n *\n * Because flann::L2 is actually the squared Euclidean distance, this\n * function by default square-roots the results. Pass take_sqrt=false to\n * avoid this.\n * *\/\n using std::vector;\n using flann::Matrix;\n\n typedef typename Distance::ResultType DistanceType;\n\n \/\/ matrices to store the results\n Matrix<int> indices(new int[query.rows*k], query.rows, k);\n Matrix<DistanceType> dists(new DistanceType[query.rows*k], query.rows, k);\n\n \/\/ build the index if necessary\n index.buildIndex();\n\n \/\/ search!\n index.knnSearch(query, indices, dists, k, search_params);\n\n \/\/ get out just the results we want\n vector<DistanceType> dkn;\n dkn.reserve(query.rows);\n if (take_sqrt)\n for (size_t i = 0; i < query.rows; i++)\n dkn.push_back(std::sqrt(dists[i][k-1]));\n else\n for (size_t i = 0; i < query.rows; i++)\n dkn.push_back(dists[i][k-1]);\n\n delete[] indices.ptr();\n delete[] dists.ptr();\n\n return dkn;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Runtime\/Metadata.h\"\n#include \"swift\/Demangling\/ManglingMacros.h\"\n\nusing namespace swift;\n\n\/\/ Placeholders for Swift functions that the C++ runtime references\n\/\/ but that the test code does not link to.\n\n\/\/ AnyHashable\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_makeAnyHashableUsingDefaultRepresentation(\n const OpaqueValue *value,\n const void *anyHashableResultPointer,\n const Metadata *T,\n const WitnessTable *hashableWT\n) {\n abort();\n}\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss11AnyHashableVMn[1] = {0};\n\n\/\/ SwiftHashableSupport\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_stdlib_Hashable_isEqual_indirect(\n const void *lhsValue, const void *rhsValue, const Metadata *type,\n const void *wt) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nintptr_t _swift_stdlib_Hashable_hashValue_indirect(\n const void *value, const Metadata *type, const void *wt) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_convertToAnyHashableIndirect(\n OpaqueValue *source, OpaqueValue *destination, const Metadata *sourceType,\n const void *sourceConformance) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_anyHashableDownCastConditionalIndirect(\n OpaqueValue *source, OpaqueValue *destination, const Metadata *targetType) {\n abort();\n}\n\n\/\/ Casting\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_arrayDownCastIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceValueType,\n const Metadata *targetValueType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceValueType,\n const Metadata *targetValueType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_setDownCastIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceValueType,\n const Metadata *targetValueType,\n const void *sourceValueHashable,\n const void *targetValueHashable) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceValueType,\n const Metadata *targetValueType,\n const void *sourceValueHashable,\n const void *targetValueHashable) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_dictionaryDownCastIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceKeyType,\n const Metadata *sourceValueType,\n const Metadata *targetKeyType,\n const Metadata *targetValueType,\n const void *sourceKeyHashable,\n const void *targetKeyHashable) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceKeyType,\n const Metadata *sourceValueType,\n const Metadata *targetKeyType,\n const Metadata *targetValueType,\n const void *sourceKeyHashable,\n const void *targetKeyHashable) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _bridgeNonVerbatimBoxedValue(const OpaqueValue *sourceValue,\n OpaqueValue *destValue,\n const Metadata *nativeType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _bridgeNonVerbatimFromObjectiveCToAny(HeapObject *sourceValue,\n OpaqueValue *destValue) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool swift_unboxFromSwiftValueWithType(OpaqueValue *source,\n OpaqueValue *result,\n const Metadata *destinationType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool swift_swiftValueConformsTo(const Metadata *destinationType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API\nHeapObject *$ss27_bridgeAnythingToObjectiveCyyXlxlF(OpaqueValue *src, const Metadata *srcType) {\n abort();\n}\n\n\/\/ ErrorObject\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nint $ss13_getErrorCodeySiSPyxGs0B0RzlF(void *) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid *$ss23_getErrorDomainNSStringyyXlSPyxGs0B0RzlF(void *) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid *$ss29_getErrorUserInfoNSDictionaryyyXlSgSPyxGs0B0RzlF(void *) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid *$ss32_getErrorEmbeddedNSErrorIndirectyyXlSgSPyxGs0B0RzlF(void *) {\n abort();\n}\n\n\/\/ Hashable\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $SkMp[1] = {0};\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $sSHMp[1] = {0};\n\n\/\/ Array\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $sSaMn[1] = {0};\n\n\/\/ Dictionary\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ssSdVMn[1] = {0};\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $sSDMn[1] = {0};\n\n\/\/ Set\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ssSeVMn[1] = {0};\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $sShMn[1] = {0};\n\n\/\/ Mirror\n\n\/\/ protocol witness table for Swift._ClassSuperMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss17_ClassSuperMirrorVs01_C0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._ClassSuperMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss17_ClassSuperMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._MetatypeMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss15_MetatypeMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._MetatypeMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss15_MetatypeMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._EnumMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss11_EnumMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._EnumMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss11_EnumMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._OpaqueMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss13_OpaqueMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._OpaqueMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss13_OpaqueMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._StructMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss13_StructMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._StructMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss13_StructMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._TupleMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss12_TupleMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._TupleMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss12_TupleMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._ClassMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss12_ClassMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._ClassMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss12_ClassMirrorVMa[1] = {0};\n\n\/\/ KeyPath\n\nSWIFT_RUNTIME_STDLIB_SPI\nconst HeapObject *swift_getKeyPathImpl(const void *p,\n const void *e,\n const void *a) {\n abort();\n}\n\n\/\/ playground print hook\n\nstruct swift_closure {\n void *fptr;\n HeapObject *context;\n};\nSWIFT_RUNTIME_STDLIB_API SWIFT_CC(swift) swift_closure\nMANGLE_SYM(s20_playgroundPrintHookySScSgvg)() {\n return {nullptr, nullptr};\n}\n\n\/\/ ObjectiveC Bridgeable\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss21_ObjectiveCBridgeableMp[1] = {0};\n\n<commit_msg>tests: stub out more of the stdlib<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Runtime\/Metadata.h\"\n#include \"swift\/Demangling\/ManglingMacros.h\"\n\nusing namespace swift;\n\n\/\/ Placeholders for Swift functions that the C++ runtime references\n\/\/ but that the test code does not link to.\n\n\/\/ AnyHashable\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_makeAnyHashableUsingDefaultRepresentation(\n const OpaqueValue *value,\n const void *anyHashableResultPointer,\n const Metadata *T,\n const WitnessTable *hashableWT\n) {\n abort();\n}\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss11AnyHashableVMn[1] = {0};\n\n\/\/ SwiftHashableSupport\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_stdlib_Hashable_isEqual_indirect(\n const void *lhsValue, const void *rhsValue, const Metadata *type,\n const void *wt) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nintptr_t _swift_stdlib_Hashable_hashValue_indirect(\n const void *value, const Metadata *type, const void *wt) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_convertToAnyHashableIndirect(\n OpaqueValue *source, OpaqueValue *destination, const Metadata *sourceType,\n const void *sourceConformance) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_anyHashableDownCastConditionalIndirect(\n OpaqueValue *source, OpaqueValue *destination, const Metadata *targetType) {\n abort();\n}\n\n\/\/ Casting\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_arrayDownCastIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceValueType,\n const Metadata *targetValueType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceValueType,\n const Metadata *targetValueType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_setDownCastIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceValueType,\n const Metadata *targetValueType,\n const void *sourceValueHashable,\n const void *targetValueHashable) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceValueType,\n const Metadata *targetValueType,\n const void *sourceValueHashable,\n const void *targetValueHashable) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _swift_dictionaryDownCastIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceKeyType,\n const Metadata *sourceValueType,\n const Metadata *targetKeyType,\n const Metadata *targetValueType,\n const void *sourceKeyHashable,\n const void *targetKeyHashable) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,\n OpaqueValue *source,\n const Metadata *sourceKeyType,\n const Metadata *sourceValueType,\n const Metadata *targetKeyType,\n const Metadata *targetValueType,\n const void *sourceKeyHashable,\n const void *targetKeyHashable) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _bridgeNonVerbatimBoxedValue(const OpaqueValue *sourceValue,\n OpaqueValue *destValue,\n const Metadata *nativeType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid _bridgeNonVerbatimFromObjectiveCToAny(HeapObject *sourceValue,\n OpaqueValue *destValue) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool swift_unboxFromSwiftValueWithType(OpaqueValue *source,\n OpaqueValue *result,\n const Metadata *destinationType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nbool swift_swiftValueConformsTo(const Metadata *destinationType) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API\nHeapObject *$ss27_bridgeAnythingToObjectiveCyyXlxlF(OpaqueValue *src, const Metadata *srcType) {\n abort();\n}\n\n\/\/ ErrorObject\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nint $ss13_getErrorCodeySiSPyxGs0B0RzlF(void *) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid *$ss23_getErrorDomainNSStringyyXlSPyxGs0B0RzlF(void *) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid *$ss29_getErrorUserInfoNSDictionaryyyXlSgSPyxGs0B0RzlF(void *) {\n abort();\n}\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL\nvoid *$ss32_getErrorEmbeddedNSErrorIndirectyyXlSgSPyxGs0B0RzlF(void *) {\n abort();\n}\n\n\/\/ Hashable\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $SkMp[1] = {0};\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $sSHMp[1] = {0};\n\n\/\/ Array\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $sSaMn[1] = {0};\n\n\/\/ Dictionary\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ssSdVMn[1] = {0};\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $sSDMn[1] = {0};\n\n\/\/ Set\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ssSeVMn[1] = {0};\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $sShMn[1] = {0};\n\n\/\/ Mirror\n\n\/\/ protocol witness table for Swift._ClassSuperMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss17_ClassSuperMirrorVs01_C0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._ClassSuperMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss17_ClassSuperMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._MetatypeMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss15_MetatypeMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._MetatypeMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss15_MetatypeMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._EnumMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss11_EnumMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._EnumMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss11_EnumMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._OpaqueMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss13_OpaqueMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._OpaqueMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss13_OpaqueMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._StructMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss13_StructMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._StructMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss13_StructMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._TupleMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss12_TupleMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._TupleMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss12_TupleMirrorVMa[1] = {0};\n\n\/\/ protocol witness table for Swift._ClassMirror : Swift._Mirror in Swift\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss12_ClassMirrorVs01_B0sWP[1] = {0};\n\n\/\/ type metadata accessor for Swift._ClassMirror\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss12_ClassMirrorVMa[1] = {0};\n\n\/\/ KeyPath\n\nSWIFT_RUNTIME_STDLIB_SPI\nconst HeapObject *swift_getKeyPathImpl(const void *p,\n const void *e,\n const void *a) {\n abort();\n}\n\n\/\/ playground print hook\n\nstruct swift_closure {\n void *fptr;\n HeapObject *context;\n};\nSWIFT_RUNTIME_STDLIB_API SWIFT_CC(swift) swift_closure\nMANGLE_SYM(s20_playgroundPrintHookySScSgvg)() {\n return {nullptr, nullptr};\n}\n\n\/\/ ObjectiveC Bridgeable\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss21_ObjectiveCBridgeableMp[1] = {0};\n\n\/\/ Key Path\n\nSWIFT_RUNTIME_STDLIB_INTERNAL\nconst long long $ss7KeyPathCMo[1] = {0};\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix enabling timelineSemaphore feature<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * qi_rfprofile.cpp\n *\n * Copyright (c) 2017 Tobias Wood.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include \"Eigen\/Core\"\n\n#include <unsupported\/Eigen\/Splines>\n\n#include \"Args.h\"\n#include \"ImageIO.h\"\n#include \"ImageTypes.h\"\n#include \"JSON.h\"\n#include \"Monitor.h\"\n#include \"Spline.h\"\n#include \"Util.h\"\n#include \"itkImageMomentsCalculator.h\"\n#include \"itkImageSliceIteratorWithIndex.h\"\n#include \"itkImageSource.h\"\n\nnamespace itk {\n\nclass ProfileImage : public ImageSource<QI::VolumeF> {\n public:\n using Self = ProfileImage;\n using Superclass = ImageSource<QI::VectorVolumeF>;\n using TRegion = QI::VectorVolumeF::RegionType;\n using Pointer = SmartPointer<Self>;\n\n itkNewMacro(Self);\n itkTypeMacro(Self, ImageSource);\n\n void SetReference(const SmartPointer<QI::VolumeF> ref) { m_reference = ref; }\n void SetDebug(const bool d) { m_debug = d; }\n void SetDim(const int d) {\n if ((m_dim < 0) || (m_dim > 2)) {\n QI::Fail(\"Invalid dimension for RF profile, must be 0-2\");\n }\n m_dim = d;\n }\n void SetRF(const Eigen::ArrayXd pos, const Eigen::ArrayXd vals) {\n m_spline = QI::SplineInterpolator(pos, vals);\n QI::Log(m_debug, \"{}\", m_spline);\n }\n\n void SetMask(const QI::VolumeF *mask) { this->SetNthInput(1, const_cast<QI::VolumeF *>(mask)); }\n void SetCenterMask(const bool cm) { this->m_centerMask = cm; }\n typename QI::VolumeF::ConstPointer GetMask() const {\n return static_cast<const QI::VolumeF *>(this->ProcessObject::GetInput(1));\n }\n\n void GenerateOutputInformation() ITK_OVERRIDE {\n auto output = this->GetOutput();\n output->SetRegions(m_reference->GetLargestPossibleRegion());\n output->SetSpacing(m_reference->GetSpacing());\n output->SetDirection(m_reference->GetDirection());\n output->SetOrigin(m_reference->GetOrigin());\n output->Allocate();\n }\n\n protected:\n SmartPointer<QI::VolumeF> m_reference;\n QI::SplineInterpolator m_spline;\n bool m_debug = false, m_centerMask = false;\n int m_dim = 0;\n\n ProfileImage() {}\n ~ProfileImage() {}\n void DynamicThreadedGenerateData(const TRegion ®ion) ITK_OVERRIDE {\n auto output = this->GetOutput();\n ImageSliceIteratorWithIndex<QI::VolumeF> imageIt(output, region);\n imageIt.SetFirstDirection((m_dim + 1) % 3);\n imageIt.SetSecondDirection((m_dim + 2) % 3);\n imageIt.GoToBegin();\n ImageSliceIteratorWithIndex<QI::VolumeF> it_B1(m_reference, region);\n it_B1.SetFirstDirection((m_dim + 1) % 3);\n it_B1.SetSecondDirection((m_dim + 2) % 3);\n it_B1.GoToBegin();\n\n const auto mask = this->GetMask();\n ImageSliceConstIteratorWithIndex<QI::VolumeF> maskIter;\n if (mask) {\n maskIter = ImageSliceConstIteratorWithIndex<QI::VolumeF>(mask, region);\n maskIter.SetFirstDirection(0);\n maskIter.SetSecondDirection(1);\n maskIter.GoToBegin();\n }\n\n QI::VectorVolumeF::PointType pt_center;\n if (mask && m_centerMask) {\n auto moments = itk::ImageMomentsCalculator<QI::VolumeF>::New();\n moments->SetImage(mask);\n moments->Compute();\n QI::Log(m_debug, \"Mask CoG is: {}\", moments->GetCenterOfGravity());\n pt_center = moments->GetCenterOfGravity();\n } else {\n \/\/ Calculate geometric center\n QI::VectorVolumeF::IndexType idx_center;\n for (int i = 0; i < 3; i++) {\n idx_center[i] = m_reference->GetLargestPossibleRegion().GetSize()[i] \/ 2;\n }\n m_reference->TransformIndexToPhysicalPoint(idx_center, pt_center);\n }\n\n while (!imageIt.IsAtEnd()) {\n QI::VectorVolumeF::PointType pt, pt_rf;\n m_reference->TransformIndexToPhysicalPoint(imageIt.GetIndex(), pt);\n pt_rf = pt - pt_center;\n float val = m_spline(pt_rf[m_dim]);\n QI::Log(m_debug,\n \"Slice co-ordinate: {} Spline Point: {} Value: {}\",\n pt_rf,\n pt_rf[m_dim],\n val);\n while (!imageIt.IsAtEndOfSlice()) {\n while (!imageIt.IsAtEndOfLine()) {\n if (!mask || maskIter.Get()) {\n imageIt.Set(val * it_B1.Get());\n } else {\n imageIt.Set(0.);\n }\n ++imageIt;\n ++it_B1;\n if (mask) {\n ++maskIter;\n }\n }\n imageIt.NextLine();\n it_B1.NextLine();\n if (mask)\n maskIter.NextLine();\n }\n imageIt.NextSlice();\n it_B1.NextSlice();\n if (mask) {\n maskIter.NextSlice();\n }\n }\n }\n\n private:\n ProfileImage(const Self &);\n void operator=(const Self &);\n};\n\n} \/\/ End namespace itk\n\nint main(int argc, char **argv) {\n Eigen::initParallel();\n args::ArgumentParser parser(\"Generates a relative B1 map from a B1+ and RF profile.\\nInput is \"\n \"the B1+ map.\\nhttp:\/\/github.com\/spinicist\/QUIT\");\n args::Positional<std::string> b1plus_path(parser, \"B1+_FILE\", \"Input B1+ file\");\n args::Positional<std::string> output_path(parser, \"B1_FILE\", \"Output relative B1 file\");\n\n args::HelpFlag help(parser, \"HELP\", \"Show this help menu\", {'h', \"help\"});\n args::Flag verbose(parser, \"VERBOSE\", \"Print more information\", {'v', \"verbose\"});\n args::ValueFlag<int> threads(parser,\n \"THREADS\",\n \"Use N threads (default=4, 0=hardware limit)\",\n {'T', \"threads\"},\n QI::GetDefaultThreads());\n args::ValueFlag<std::string> mask(\n parser, \"MASK\", \"Only process voxels within the mask\", {'m', \"mask\"});\n args::Flag centerMask(parser,\n \"CENTER ON MASK\",\n \"Set the center of the slab to the center of the mask\",\n {'c', \"center\"});\n args::ValueFlag<std::string> subregion(\n parser,\n \"REGION\",\n \"Process subregion starting at voxel I,J,K with size SI,SJ,SK\",\n {'s', \"subregion\"});\n args::ValueFlag<int> dimension(\n parser, \"DIMENSION\", \"Which dimension to calculate the profile over\", {\"dim\"}, 2);\n args::ValueFlag<std::string> infile(\n parser, \"FILE\", \"Read JSON input from file instead of stdin\", {\"json\"});\n QI::ParseArgs(parser, argc, argv, verbose, threads);\n\n auto reference = QI::ReadImage(QI::CheckPos(b1plus_path), verbose);\n\n QI::Log(verbose, \"Reading slab profile\");\n json input = infile ? QI::ReadJSON(infile.Get()) : QI::ReadJSON(std::cin);\n auto rf_pos = QI::ArrayFromJSON(input, \"rf_pos\");\n auto rf_vals = QI::ArrayFromJSON(input, \"rf_vals\");\n\n QI::Log(verbose, \"Profile points = {}\", rf_pos.rows());\n QI::Log(verbose, \"Generating image...\");\n auto image = itk::ProfileImage::New();\n image->SetReference(reference);\n image->SetRF(rf_pos, rf_vals);\n image->SetDim(dimension.Get());\n image->SetCenterMask(centerMask);\n image->SetDebug(true);\n if (mask)\n image->SetMask(QI::ReadImage(mask.Get(), verbose));\n if (verbose) {\n auto monitor = QI::GenericMonitor::New();\n image->AddObserver(itk::ProgressEvent(), monitor);\n }\n image->Update();\n QI::WriteImage(image->GetOutput(), QI::CheckPos(output_path), verbose);\n return EXIT_SUCCESS;\n}\n<commit_msg>BUG Fixes RF profiles for obliqued images<commit_after>\/*\n * qi_rfprofile.cpp\n *\n * Copyright (c) 2017 Tobias Wood.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include \"Eigen\/Core\"\n\n#include <unsupported\/Eigen\/Splines>\n\n#include \"Args.h\"\n#include \"ImageIO.h\"\n#include \"ImageTypes.h\"\n#include \"JSON.h\"\n#include \"Monitor.h\"\n#include \"Spline.h\"\n#include \"Util.h\"\n#include \"itkImageMomentsCalculator.h\"\n#include \"itkImageSliceIteratorWithIndex.h\"\n#include \"itkImageSource.h\"\n\nnamespace itk {\n\nclass ProfileImage : public ImageSource<QI::VolumeF> {\n public:\n using Self = ProfileImage;\n using Superclass = ImageSource<QI::VectorVolumeF>;\n using TRegion = QI::VectorVolumeF::RegionType;\n using Pointer = SmartPointer<Self>;\n\n itkNewMacro(Self);\n itkTypeMacro(Self, ImageSource);\n\n void SetReference(const SmartPointer<QI::VolumeF> ref) { m_reference = ref; }\n void SetDebug(const bool d) { m_debug = d; }\n void SetDim(const int d) {\n if ((m_dim < 0) || (m_dim > 2)) {\n QI::Fail(\"Invalid dimension for RF profile, must be 0-2\");\n }\n m_dim = d;\n }\n void SetRF(const Eigen::ArrayXd pos, const Eigen::ArrayXd vals) {\n m_spline = QI::SplineInterpolator(pos, vals);\n QI::Log(m_debug, \"{}\", m_spline);\n }\n\n void SetMask(const QI::VolumeF *mask) { this->SetNthInput(1, const_cast<QI::VolumeF *>(mask)); }\n void SetCenterMask(const bool cm) { this->m_centerMask = cm; }\n typename QI::VolumeF::ConstPointer GetMask() const {\n return static_cast<const QI::VolumeF *>(this->ProcessObject::GetInput(1));\n }\n\n void GenerateOutputInformation() ITK_OVERRIDE {\n auto output = this->GetOutput();\n output->SetRegions(m_reference->GetLargestPossibleRegion());\n output->SetSpacing(m_reference->GetSpacing());\n output->SetDirection(m_reference->GetDirection());\n output->SetOrigin(m_reference->GetOrigin());\n output->Allocate();\n }\n\n protected:\n SmartPointer<QI::VolumeF> m_reference;\n QI::SplineInterpolator m_spline;\n bool m_debug = false, m_centerMask = false;\n int m_dim = 0;\n\n ProfileImage() {}\n ~ProfileImage() {}\n void DynamicThreadedGenerateData(const TRegion ®ion) ITK_OVERRIDE {\n auto const output = this->GetOutput();\n auto const mask = this->GetMask();\n auto const dim1 = (m_dim + 1) % 3;\n auto const dim2 = (m_dim + 2) % 3;\n\n ImageSliceIteratorWithIndex<QI::VolumeF> imageIt(output, region);\n imageIt.SetFirstDirection(dim1);\n imageIt.SetSecondDirection(dim2);\n\n ImageSliceIteratorWithIndex<QI::VolumeF> it_B1(m_reference, region);\n it_B1.SetFirstDirection(dim1);\n it_B1.SetSecondDirection(dim2);\n\n ImageSliceConstIteratorWithIndex<QI::VolumeF> maskIter;\n if (mask) {\n maskIter = ImageSliceConstIteratorWithIndex<QI::VolumeF>(mask, region);\n maskIter.SetFirstDirection(dim1);\n maskIter.SetSecondDirection(dim2);\n maskIter.GoToBegin();\n }\n\n QI::VectorVolumeF::PointType pt_center;\n if (mask && m_centerMask) {\n auto moments = itk::ImageMomentsCalculator<QI::VolumeF>::New();\n moments->SetImage(mask);\n moments->Compute();\n QI::Log(m_debug, \"Mask CoG is: {}\", moments->GetCenterOfGravity());\n pt_center = moments->GetCenterOfGravity();\n } else {\n \/\/ Calculate geometric center\n QI::VectorVolumeF::IndexType idx_center;\n for (int i = 0; i < 3; i++) {\n idx_center[i] = m_reference->GetLargestPossibleRegion().GetSize()[i] \/ 2;\n }\n m_reference->TransformIndexToPhysicalPoint(idx_center, pt_center);\n }\n\n \/\/ Now get physical space index to deal with obliqued scans\n QI::VectorVolumeF::IndexType index1, index2;\n index1.Fill(0);\n index2.Fill(0);\n index2[m_dim] = 1;\n QI::VectorVolumeF::PointType pt1, pt2;\n m_reference->TransformIndexToPhysicalPoint(index1, pt1);\n m_reference->TransformIndexToPhysicalPoint(index2, pt2);\n auto const diff = pt2 - pt1;\n int phys_dim = 0;\n if (fabs(diff[1]) > fabs(diff[0])) {\n if (fabs(diff[2]) > fabs(diff[1])) {\n phys_dim = 2;\n }\n phys_dim = 1;\n }\n QI::Log(m_debug, \"Physical dimension: {}\", phys_dim);\n\n while (!imageIt.IsAtEnd()) {\n QI::VectorVolumeF::PointType pt, pt_rf;\n m_reference->TransformIndexToPhysicalPoint(imageIt.GetIndex(), pt);\n pt_rf = pt - pt_center;\n float val = m_spline(pt_rf[phys_dim]);\n QI::Log(m_debug, \"Absolute co-ord: {} Relative co-ord: {} Value: {}\", pt, pt_rf, val);\n while (!imageIt.IsAtEndOfSlice()) {\n while (!imageIt.IsAtEndOfLine()) {\n if (!mask || maskIter.Get()) {\n imageIt.Set(val * it_B1.Get());\n } else {\n imageIt.Set(0.);\n }\n ++imageIt;\n ++it_B1;\n if (mask) {\n ++maskIter;\n }\n }\n imageIt.NextLine();\n it_B1.NextLine();\n if (mask)\n maskIter.NextLine();\n }\n imageIt.NextSlice();\n it_B1.NextSlice();\n if (mask) {\n maskIter.NextSlice();\n }\n }\n }\n\n private:\n ProfileImage(const Self &);\n void operator=(const Self &);\n};\n\n} \/\/ End namespace itk\n\nint main(int argc, char **argv) {\n Eigen::initParallel();\n args::ArgumentParser parser(\"Generates a relative B1 map from a B1+ and RF profile.\\nInput is \"\n \"the B1+ map.\\nhttp:\/\/github.com\/spinicist\/QUIT\");\n args::Positional<std::string> b1plus_path(parser, \"B1+_FILE\", \"Input B1+ file\");\n args::Positional<std::string> output_path(parser, \"B1_FILE\", \"Output relative B1 file\");\n\n args::HelpFlag help(parser, \"HELP\", \"Show this help menu\", {'h', \"help\"});\n args::Flag verbose(parser, \"VERBOSE\", \"Print more information\", {'v', \"verbose\"});\n args::ValueFlag<int> threads(parser,\n \"THREADS\",\n \"Use N threads (default=4, 0=hardware limit)\",\n {'T', \"threads\"},\n QI::GetDefaultThreads());\n args::ValueFlag<std::string> mask(\n parser, \"MASK\", \"Only process voxels within the mask\", {'m', \"mask\"});\n args::Flag centerMask(parser,\n \"CENTER ON MASK\",\n \"Set the center of the slab to the center of the mask\",\n {'c', \"center\"});\n args::ValueFlag<std::string> subregion(\n parser,\n \"REGION\",\n \"Process subregion starting at voxel I,J,K with size SI,SJ,SK\",\n {'s', \"subregion\"});\n args::ValueFlag<int> dimension(\n parser, \"DIMENSION\", \"Which dimension to calculate the profile over\", {\"dim\"}, 2);\n args::ValueFlag<std::string> infile(\n parser, \"FILE\", \"Read JSON input from file instead of stdin\", {\"json\"});\n QI::ParseArgs(parser, argc, argv, verbose, threads);\n\n auto reference = QI::ReadImage(QI::CheckPos(b1plus_path), verbose);\n\n QI::Log(verbose, \"Reading slab profile\");\n json input = infile ? QI::ReadJSON(infile.Get()) : QI::ReadJSON(std::cin);\n auto rf_pos = QI::ArrayFromJSON(input, \"rf_pos\");\n auto rf_vals = QI::ArrayFromJSON(input, \"rf_vals\");\n\n QI::Log(verbose, \"Profile points = {}\", rf_pos.rows());\n QI::Log(verbose, \"Generating image...\");\n auto image = itk::ProfileImage::New();\n image->SetReference(reference);\n image->SetRF(rf_pos, rf_vals);\n image->SetDim(dimension.Get());\n image->SetDebug(verbose);\n if (mask) {\n image->SetMask(QI::ReadImage(mask.Get(), verbose));\n image->SetCenterMask(centerMask);\n }\n if (verbose) {\n auto monitor = QI::GenericMonitor::New();\n image->AddObserver(itk::ProgressEvent(), monitor);\n }\n image->Update();\n QI::WriteImage(image->GetOutput(), QI::CheckPos(output_path), verbose);\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/include\/rapid-cxx-test\/unit_test.hpp\"\n\nTEST_SUITE(basic_example)\n\nTEST_CASE(compiler_not_useless)\n{\n int x = 0;\n AT_RTIME_EQ(x, 0);\n x = 1;\n AT_RTIME_EQ(x, 1);\n}\n\nTEST_SUITE_END()\n<commit_msg>remove old example<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/gui:$Name: $:$Id: TGIcon.cxx,v 1.11 2006\/04\/24 13:51:06 antcheva Exp $\n\/\/ Author: Fons Rademakers 05\/01\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\/**************************************************************************\n\n This source is based on Xclass95, a Win95-looking GUI toolkit.\n Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.\n\n Xclass95 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**************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGIcon \/\/\n\/\/ \/\/\n\/\/ This class handles GUI icons. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGIcon.h\"\n#include \"TGPicture.h\"\n#include \"TSystem.h\"\n#include \"TImage.h\"\n#include \"Riostream.h\"\n#include \"TMath.h\"\n#include \"TGFileDialog.h\"\n#include \"TGMsgBox.h\"\n#include \"TVirtualDragManager.h\"\n\n\nClassImp(TGIcon)\n\n\/\/______________________________________________________________________________\nTGIcon::TGIcon(const TGWindow *p, const char *image) : TGFrame(p, 1, 1)\n{\n \/\/ Create icon.\n\n fPic = 0;\n char *path;\n\n if (!image) {\n const char *rootsys = gSystem->ExpandPathName(\"$ROOTSYS\");\n path = gSystem->ConcatFileName(rootsys, \"icons\/bld_rgb.xpm\");\n }\n fPath = gSystem->DirName(path);\n\n fImage = TImage::Open(path);\n fPic = fClient->GetPicturePool()->GetPicture(Form(\"%s_%dx%d\", gSystem->BaseName(path), \n fImage->GetWidth(), fImage->GetHeight()),\n fImage->GetPixmap(), fImage->GetMask());\n TGFrame::Resize(fImage->GetWidth(), fImage->GetHeight());\n SetWindowName();\n delete path;\n}\n\n\/\/______________________________________________________________________________\nTGIcon::~TGIcon()\n{\n \/\/ Delete icon and free picture.\n\n if (fPic) fClient->FreePicture(fPic);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::SetPicture(const TGPicture *pic)\n{\n \/\/ Set icon picture.\n\n fPic = pic;\n gVirtualX->ClearWindow(fId);\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::SetImage(const char *img)\n{\n \/\/ Set icon image.\n\n \/\/delete fImage;\n TImage *i = TImage::Open(img);\n fPath = gSystem->DirName(img);\n\n SetImage(i);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::SetImage(TImage *img)\n{\n \/\/ Change icon image.\n\n if (!img) {\n return;\n }\n\n \/\/delete fImage; !! mem.leak!!\n fImage = img;\n Resize(fImage->GetWidth(), fImage->GetHeight());\n}\n\n\/\/______________________________________________________________________________\nTGDimension TGIcon::GetDefaultSize() const\n{\n \/\/ Return size of icon.\n\n return TGDimension((fPic) ? fPic->GetWidth() : fWidth,\n (fPic) ? fPic->GetHeight() : fHeight);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::DoRedraw()\n{\n \/\/ Redraw picture.\n\n Bool_t border = (GetOptions() & kRaisedFrame) || \n (GetOptions() & kSunkenFrame) ||\n (GetOptions() & kDoubleBorder);\n\n if (fPic) fPic->Draw(fId, GetBckgndGC()(), border, border);\n DrawBorder();\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::Resize(UInt_t w, UInt_t h)\n{\n \/\/ Resize.\n\n \/\/if (fImage && (TMath::Abs(Int_t(fImage->GetWidth() - w)) < 5) && \n \/\/ (TMath::Abs(Int_t(fImage->GetHeight() - h)) < 5)) {\n \/\/ return;\n \/\/}\n\n gVirtualX->ClearWindow(fId);\n TGFrame::Resize(w, h);\n\n if (!fImage) {\n fImage = TImage::Create();\n if (fPic) fImage->SetImage(fPic->GetPicture(), fPic->GetMask());\n }\n if (fPic) {\n fClient->FreePicture(fPic);\n }\n Bool_t border = (GetOptions() & kRaisedFrame) || \n (GetOptions() & kSunkenFrame) ||\n (GetOptions() & kDoubleBorder);\n\n fImage->Scale(w - 2*border, h - 2*border);\n fPic = fClient->GetPicturePool()->GetPicture(Form(\"%s_%dx%d\", fImage->GetName(), \n fImage->GetWidth(), fImage->GetHeight()),\n fImage->GetPixmap(), fImage->GetMask());\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h)\n{\n \/\/ Move icon to (x,y) and resize it to (w,h). \n\n Move(x, y);\n Resize(w, h);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::Reset()\n{\n \/\/ Reset icon to original image. It can be used only via context menu.\n\n if (!fImage || !fClient->IsEditable()) return;\n\n TString name = fImage->GetName();\n name.Chop();\n char *path = gSystem->ConcatFileName(fPath.Data(), name.Data());\n SetImage(path);\n\n delete path;\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::ChangeImage()\n{\n \/\/ Invoke file dialog to assign a new image.\n\n static const char *gImageTypes[] = {\"XPM\", \"*.xpm\", \n \"GIF\", \"*.gif\",\n \"PNG\", \"*.png\", \n \"JPEG\", \"*.jpg\",\n \"TARGA\", \"*.tga\", \n \"ICO\", \"*.ico\", \n \"XCF\", \"*.xcf\", \n \"CURSORS\", \"*.cur\",\n \"PPM\", \"*.ppm\", \n \"PNM\", \"*.pnm\", \n \"XBM\", \"*.xbm\", \n \"TIFF\", \"*.tiff\", \n \"BMP\", \"*.bmp\",\n \"Enacapsulated PostScript\", \"*.eps\", \n \"PostScript\", \"*.ps\", \n \"PDF\", \"*.pdf\", \n \"ASImage XML\",\"*.xml\",\n \"All files\", \"*\",\n 0, 0 };\n\n TGFileInfo fi;\n static TString dir(\".\");\n static Bool_t overwr = kFALSE;\n const char *fname;\n\n fi.fFileTypes = gImageTypes;\n fi.fIniDir = StrDup(dir);\n fi.fOverwrite = overwr;\n\n TGWindow *root = (TGWindow*)fClient->GetRoot();\n gDragManager->SetEditable(kFALSE);\n\n new TGFileDialog(fClient->GetDefaultRoot(), this, kFDOpen, &fi);\n\n if (!fi.fFilename) {\n root->SetEditable(kTRUE);\n gDragManager->SetEditable(kTRUE);\n return;\n }\n\n dir = fi.fIniDir;\n overwr = fi.fOverwrite;\n fname = fi.fFilename;\n\n fImage = TImage::Open(fname);\n\n if (!fImage) {\n Int_t retval;\n new TGMsgBox(fClient->GetDefaultRoot(), this, \"Error...\",\n Form(\"Cannot read image file (%s)\", fname),\n kMBIconExclamation, kMBRetry | kMBCancel, &retval);\n\n if (retval == kMBRetry) {\n ChangeImage();\n }\n } else {\n SetImage(fImage);\n }\n root->SetEditable(kTRUE);\n gDragManager->SetEditable(kTRUE);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save an icon widget as a C++ statement(s) on output stream out.\n\n char quote = '\"';\n\n if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);\n\n if (!fPic) {\n Error(\"SavePrimitive()\", \"icon pixmap not found \");\n return;\n }\n\n const char *picname = fPic->GetName();\n\n out <<\" TGIcon *\";\n out << GetName() << \" = new TGIcon(\" << fParent->GetName()\n << \",gClient->GetPicture(\" << quote\n << gSystem->ExpandPathName(gSystem->UnixPathName(picname)) \/\/ if no path\n << quote << \")\" << \",\" << GetWidth() << \",\" << GetHeight();\n\n if (fBackground == GetDefaultFrameBackground()) {\n if (!GetOptions()) {\n out <<\");\" << endl;\n } else {\n out << \",\" << GetOptionString() <<\");\" << endl;\n }\n } else {\n out << \",\" << GetOptionString() << \",ucolor);\" << endl;\n }\n}\n<commit_msg>From Bertrand: - Fix TGIcon layout problem introduced recently<commit_after>\/\/ @(#)root\/gui:$Name: $:$Id: TGIcon.cxx,v 1.12 2006\/04\/25 08:47:30 antcheva Exp $\n\/\/ Author: Fons Rademakers 05\/01\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\/**************************************************************************\n\n This source is based on Xclass95, a Win95-looking GUI toolkit.\n Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.\n\n Xclass95 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**************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGIcon \/\/\n\/\/ \/\/\n\/\/ This class handles GUI icons. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGIcon.h\"\n#include \"TGPicture.h\"\n#include \"TSystem.h\"\n#include \"TImage.h\"\n#include \"Riostream.h\"\n#include \"TMath.h\"\n#include \"TGFileDialog.h\"\n#include \"TGMsgBox.h\"\n#include \"TVirtualDragManager.h\"\n\n\nClassImp(TGIcon)\n\n\/\/______________________________________________________________________________\nTGIcon::TGIcon(const TGWindow *p, const char *image) : TGFrame(p, 1, 1)\n{\n \/\/ Create icon.\n\n fPic = 0;\n char *path;\n\n if (!image) {\n const char *rootsys = gSystem->ExpandPathName(\"$ROOTSYS\");\n path = gSystem->ConcatFileName(rootsys, \"icons\/bld_rgb.xpm\");\n } else {\n path = strdup(image);\n }\n fPath = gSystem->DirName(path);\n\n fImage = TImage::Open(path);\n fPic = fClient->GetPicturePool()->GetPicture(gSystem->BaseName(path), \n fImage->GetPixmap(), fImage->GetMask());\n TGFrame::Resize(fImage->GetWidth(), fImage->GetHeight());\n SetWindowName();\n delete path;\n}\n\n\/\/______________________________________________________________________________\nTGIcon::~TGIcon()\n{\n \/\/ Delete icon and free picture.\n\n if (fPic) fClient->FreePicture(fPic);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::SetPicture(const TGPicture *pic)\n{\n \/\/ Set icon picture.\n\n fPic = pic;\n gVirtualX->ClearWindow(fId);\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::SetImage(const char *img)\n{\n \/\/ Set icon image.\n\n \/\/delete fImage;\n TImage *i = TImage::Open(img);\n fPath = gSystem->DirName(img);\n\n SetImage(i);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::SetImage(TImage *img)\n{\n \/\/ Change icon image.\n\n if (!img) {\n return;\n }\n\n \/\/delete fImage; !! mem.leak!!\n fImage = img;\n Resize(fImage->GetWidth(), fImage->GetHeight());\n}\n\n\/\/______________________________________________________________________________\nTGDimension TGIcon::GetDefaultSize() const\n{\n \/\/ Return size of icon.\n\n return TGDimension((fPic) ? fPic->GetWidth() : fWidth,\n (fPic) ? fPic->GetHeight() : fHeight);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::DoRedraw()\n{\n \/\/ Redraw picture.\n\n Bool_t border = (GetOptions() & kRaisedFrame) || \n (GetOptions() & kSunkenFrame) ||\n (GetOptions() & kDoubleBorder);\n\n if (fPic) fPic->Draw(fId, GetBckgndGC()(), border, border);\n if (border) DrawBorder();\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::Resize(UInt_t w, UInt_t h)\n{\n \/\/ Resize.\n\n TGFrame::Resize(w, h);\n\n \/\/ allow dynamic resize of icon during guibuilding\n if (!fClient->IsEditable()) {\n return;\n }\n gVirtualX->ClearWindow(fId);\n\n if (!fImage) {\n fImage = TImage::Create();\n if (fPic) {\n fImage->SetName(fPic->GetName());\n fImage->SetImage(fPic->GetPicture(), fPic->GetMask());\n }\n }\n if (fPic) {\n fClient->FreePicture(fPic);\n }\n Bool_t border = (GetOptions() & kRaisedFrame) || \n (GetOptions() & kSunkenFrame) ||\n (GetOptions() & kDoubleBorder);\n\n fImage->Scale(w - 2*border, h - 2*border);\n fPic = fClient->GetPicturePool()->GetPicture(fImage->GetName(),\n fImage->GetPixmap(), fImage->GetMask());\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h)\n{\n \/\/ Move icon to (x,y) and resize it to (w,h). \n\n Move(x, y);\n Resize(w, h);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::Reset()\n{\n \/\/ Reset icon to original image. It can be used only via context menu.\n\n if (!fImage || !fClient->IsEditable()) return;\n\n TString name = fImage->GetName();\n name.Chop();\n char *path = gSystem->ConcatFileName(fPath.Data(), name.Data());\n SetImage(path);\n\n delete path;\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::ChangeImage()\n{\n \/\/ Invoke file dialog to assign a new image.\n \/\/ This method is activated via context menu during guibuilding.\n\n static const char *gImageTypes[] = {\"All files\", \"*\",\n \"XPM\", \"*.xpm\",\n \"GIF\", \"*.gif\",\n \"PNG\", \"*.png\",\n \"JPEG\", \"*.jpg\",\n \"TARGA\", \"*.tga\",\n \"BMP\", \"*.bmp\",\n \"ICO\", \"*.ico\",\n \"XCF\", \"*.xcf\",\n \"CURSORS\", \"*.cur\",\n \"PPM\", \"*.ppm\",\n \"PNM\", \"*.pnm\",\n \"XBM\", \"*.xbm\",\n \"TIFF\", \"*.tiff\",\n \"Enacapsulated PostScript\", \"*.eps\",\n \"PostScript\", \"*.ps\",\n \"PDF\", \"*.pdf\",\n \"ASImage XML\",\"*.xml\",\n 0, 0 };\n\n TGFileInfo fi;\n static TString dir(\".\");\n static Bool_t overwr = kFALSE;\n const char *fname;\n\n fi.fFileTypes = gImageTypes;\n fi.fIniDir = StrDup(dir);\n fi.fOverwrite = overwr;\n\n TGWindow *root = (TGWindow*)fClient->GetRoot();\n gDragManager->SetEditable(kFALSE);\n\n new TGFileDialog(fClient->GetDefaultRoot(), this, kFDOpen, &fi);\n\n if (!fi.fFilename) {\n root->SetEditable(kTRUE);\n gDragManager->SetEditable(kTRUE);\n return;\n }\n\n dir = fi.fIniDir;\n overwr = fi.fOverwrite;\n fname = fi.fFilename;\n\n fImage = TImage::Open(fname);\n\n if (!fImage) {\n Int_t retval;\n new TGMsgBox(fClient->GetDefaultRoot(), this, \"Error...\",\n Form(\"Cannot read image file (%s)\", fname),\n kMBIconExclamation, kMBRetry | kMBCancel, &retval);\n\n if (retval == kMBRetry) {\n ChangeImage();\n }\n } else {\n SetImage(fImage);\n }\n root->SetEditable(kTRUE);\n gDragManager->SetEditable(kTRUE);\n}\n\n\/\/______________________________________________________________________________\nvoid TGIcon::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save an icon widget as a C++ statement(s) on output stream out.\n\n char quote = '\"';\n\n if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);\n\n if (!fPic) {\n Error(\"SavePrimitive()\", \"icon pixmap not found \");\n return;\n }\n\n const char *picname = fPic->GetName();\n\n out <<\" TGIcon *\";\n out << GetName() << \" = new TGIcon(\" << fParent->GetName()\n << \",gClient->GetPicture(\" << quote\n << gSystem->ExpandPathName(gSystem->UnixPathName(picname)) \/\/ if no path\n << quote << \")\" << \",\" << GetWidth() << \",\" << GetHeight();\n\n if (fBackground == GetDefaultFrameBackground()) {\n if (!GetOptions()) {\n out <<\");\" << endl;\n } else {\n out << \",\" << GetOptionString() <<\");\" << endl;\n }\n } else {\n out << \",\" << GetOptionString() << \",ucolor);\" << endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (C) 2020 The Falco Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include <json\/json.h>\n\n#include \"formats.h\"\n#include \"falco_engine.h\"\n#include \"banned.h\" \/\/ This raises a compilation error when certain functions are used\n\nsinsp *falco_formats::s_inspector = NULL;\nfalco_engine *falco_formats::s_engine = NULL;\nbool falco_formats::s_json_output = false;\nbool falco_formats::s_json_include_output_property = true;\nsinsp_evt_formatter_cache *falco_formats::s_formatters = NULL;\n\nconst static struct luaL_reg ll_falco[] =\n\t{\n\t\t{\"formatter\", &falco_formats::lua_formatter},\n\t\t{\"free_formatter\", &falco_formats::lua_free_formatter},\n\t\t{NULL, NULL}};\n\nvoid falco_formats::init(sinsp *inspector,\n\t\t\t falco_engine *engine,\n\t\t\t lua_State *ls,\n\t\t\t bool json_output,\n\t\t\t bool json_include_output_property)\n{\n\ts_inspector = inspector;\n\ts_engine = engine;\n\ts_json_output = json_output;\n\ts_json_include_output_property = json_include_output_property;\n\tif(!s_formatters)\n\t{\n\t\ts_formatters = new sinsp_evt_formatter_cache(s_inspector);\n\t}\n\n\tluaL_openlib(ls, \"formats\", ll_falco, 0);\n}\n\nint falco_formats::lua_formatter(lua_State *ls)\n{\n\tstring source = luaL_checkstring(ls, -2);\n\tstring format = luaL_checkstring(ls, -1);\n\n\ttry\n\t{\n\t\tif(source == \"syscall\")\n\t\t{\n\t\t\tsinsp_evt_formatter *formatter;\n\t\t\tformatter = new sinsp_evt_formatter(s_inspector, format);\n\t\t\tlua_pushlightuserdata(ls, formatter);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tjson_event_formatter *formatter;\n\t\t\tformatter = new json_event_formatter(s_engine->json_factory(), format);\n\t\t\tlua_pushlightuserdata(ls, formatter);\n\t\t}\n\t}\n\tcatch(sinsp_exception &e)\n\t{\n\t\tluaL_error(ls, \"Invalid output format '%s': '%s'\", format.c_str(), e.what());\n\t}\n\tcatch(falco_exception &e)\n\t{\n\t\tluaL_error(ls, \"Invalid output format '%s': '%s'\", format.c_str(), e.what());\n\t}\n\n\treturn 1;\n}\n\nint falco_formats::lua_free_formatter(lua_State *ls)\n{\n\tif(!lua_islightuserdata(ls, -1) ||\n\t !lua_isstring(ls, -2))\n\n\t{\n\t\tluaL_error(ls, \"Invalid argument passed to free_formatter\");\n\t}\n\n\tstring source = luaL_checkstring(ls, -2);\n\n\tif(source == \"syscall\")\n\t{\n\t\tsinsp_evt_formatter *formatter = (sinsp_evt_formatter *)lua_topointer(ls, -1);\n\t\tdelete(formatter);\n\t}\n\telse\n\t{\n\t\tjson_event_formatter *formatter = (json_event_formatter *)lua_topointer(ls, -1);\n\t\tdelete(formatter);\n\t}\n\n\treturn 0;\n}\n\nstring falco_formats::format_event(const gen_event *evt, const std::string &rule, const std::string &source,\n\t\t\t\t const std::string &level, const std::string &format)\n{\n\n\tstring line;\n\tstring json_line;\n\tstring sformat = format;\n\n\tif(strcmp(source.c_str(), \"syscall\") == 0)\n\t{\n\t\t\/\/ This is \"output\"\n\t\ts_formatters->tostring((sinsp_evt *)evt, sformat, &line);\n\n\t\tif(s_json_output)\n\t\t{\n\t\t\tsinsp_evt::param_fmt cur_fmt = s_inspector->get_buffer_format();\n\t\t\tswitch(cur_fmt)\n\t\t\t{\n\t\t\tcase sinsp_evt::PF_NORMAL:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSON);\n\t\t\t\tbreak;\n\t\t\tcase sinsp_evt::PF_EOLS:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSONEOLS);\n\t\t\t\tbreak;\n\t\t\tcase sinsp_evt::PF_HEX:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSONHEX);\n\t\t\t\tbreak;\n\t\t\tcase sinsp_evt::PF_HEXASCII:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSONHEXASCII);\n\t\t\t\tbreak;\n\t\t\tcase sinsp_evt::PF_BASE64:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSONBASE64);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/ do nothing\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\/\/ This is output fields\n\t\t\ts_formatters->tostring((sinsp_evt *)evt, sformat, &json_line);\n\n\t\t\t\/\/ The formatted string might have a leading newline. If it does, remove it.\n\t\t\tif(json_line[0] == '\\n')\n\t\t\t{\n\t\t\t\tjson_line.erase(0, 1);\n\t\t\t}\n\t\t\ts_inspector->set_buffer_format(cur_fmt);\n\t\t}\n\t}\n\telse\n\t{\n\t\tjson_event_formatter formatter(s_engine->json_factory(), sformat);\n\n\t\tline = formatter.tostring((json_event *)evt);\n\n\t\tif(s_json_output)\n\t\t{\n\t\t\tjson_line = formatter.tojson((json_event *)evt);\n\t\t}\n\t}\n\n\t\/\/ For JSON output, the formatter returned a json-as-text\n\t\/\/ object containing all the fields in the original format\n\t\/\/ message as well as the event time in ns. Use this to build\n\t\/\/ a more detailed object containing the event time, rule,\n\t\/\/ severity, full output, and fields.\n\tif(s_json_output)\n\t{\n\t\tJson::Value event;\n\t\tJson::FastWriter writer;\n\t\tstring full_line;\n\n\t\t\/\/ Convert the time-as-nanoseconds to a more json-friendly ISO8601.\n\t\ttime_t evttime = evt->get_ts() \/ 1000000000;\n\t\tchar time_sec[20]; \/\/ sizeof \"YYYY-MM-DDTHH:MM:SS\"\n\t\tchar time_ns[12]; \/\/ sizeof \".sssssssssZ\"\n\t\tstring iso8601evttime;\n\n\t\tstrftime(time_sec, sizeof(time_sec), \"%FT%T\", gmtime(&evttime));\n\t\tsnprintf(time_ns, sizeof(time_ns), \".%09luZ\", evt->get_ts() % 1000000000);\n\t\tiso8601evttime = time_sec;\n\t\tiso8601evttime += time_ns;\n\t\tevent[\"time\"] = iso8601evttime;\n\t\tevent[\"rule\"] = rule;\n\t\tevent[\"priority\"] = level;\n\n\t\tif(s_json_include_output_property)\n\t\t{\n\t\t\t\/\/ This is the filled-in output line.\n\t\t\tevent[\"output\"] = line;\n\t\t}\n\n\t\tfull_line = writer.write(event);\n\n\t\t\/\/ Json::FastWriter may add a trailing newline. If it\n\t\t\/\/ does, remove it.\n\t\tif(full_line[full_line.length() - 1] == '\\n')\n\t\t{\n\t\t\tfull_line.resize(full_line.length() - 1);\n\t\t}\n\n\t\t\/\/ Cheat-graft the output from the formatter into this\n\t\t\/\/ string. Avoids an unnecessary json parse just to\n\t\t\/\/ merge the formatted fields at the object level.\n\t\tfull_line.pop_back();\n\t\tfull_line.append(\", \\\"output_fields\\\": \");\n\t\tfull_line.append(json_line);\n\t\tfull_line.append(\"}\");\n\t\tline = full_line;\n\t}\n\n\treturn line.c_str();\n}\n\nmap<string, string> falco_formats::resolve_tokens(const gen_event *evt, const std::string &source, const std::string &format)\n{\n\tstring sformat = format;\n\tmap<string, string> values;\n\tif(source == \"syscall\")\n\t{\n\t\ts_formatters->resolve_tokens((sinsp_evt *)evt, sformat, values);\n\t}\n\t\/\/ k8s_audit\n\telse\n\t{\n\t\tjson_event_formatter json_formatter(s_engine->json_factory(), sformat);\n\t\tvalues = json_formatter.tomap((json_event *)evt);\n\t}\n\treturn values;\n}\n<commit_msg>fix(userspace\/engine): free formatters, if any<commit_after>\/*\nCopyright (C) 2020 The Falco Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include <json\/json.h>\n\n#include \"formats.h\"\n#include \"falco_engine.h\"\n#include \"banned.h\" \/\/ This raises a compilation error when certain functions are used\n\nsinsp *falco_formats::s_inspector = NULL;\nfalco_engine *falco_formats::s_engine = NULL;\nbool falco_formats::s_json_output = false;\nbool falco_formats::s_json_include_output_property = true;\nsinsp_evt_formatter_cache *falco_formats::s_formatters = NULL;\n\nconst static struct luaL_reg ll_falco[] =\n\t{\n\t\t{\"formatter\", &falco_formats::lua_formatter},\n\t\t{\"free_formatter\", &falco_formats::lua_free_formatter},\n\t\t{NULL, NULL}};\n\nvoid falco_formats::init(sinsp *inspector,\n\t\t\t falco_engine *engine,\n\t\t\t lua_State *ls,\n\t\t\t bool json_output,\n\t\t\t bool json_include_output_property)\n{\n\ts_inspector = inspector;\n\ts_engine = engine;\n\ts_json_output = json_output;\n\ts_json_include_output_property = json_include_output_property;\n\tif(!s_formatters)\n\t{\n\t\tdelete(s_formatters);\n\t}\n\ts_formatters = new sinsp_evt_formatter_cache(s_inspector);\n\n\tluaL_openlib(ls, \"formats\", ll_falco, 0);\n}\n\nint falco_formats::lua_formatter(lua_State *ls)\n{\n\tstring source = luaL_checkstring(ls, -2);\n\tstring format = luaL_checkstring(ls, -1);\n\n\ttry\n\t{\n\t\tif(source == \"syscall\")\n\t\t{\n\t\t\tsinsp_evt_formatter *formatter;\n\t\t\tformatter = new sinsp_evt_formatter(s_inspector, format);\n\t\t\tlua_pushlightuserdata(ls, formatter);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tjson_event_formatter *formatter;\n\t\t\tformatter = new json_event_formatter(s_engine->json_factory(), format);\n\t\t\tlua_pushlightuserdata(ls, formatter);\n\t\t}\n\t}\n\tcatch(sinsp_exception &e)\n\t{\n\t\tluaL_error(ls, \"Invalid output format '%s': '%s'\", format.c_str(), e.what());\n\t}\n\tcatch(falco_exception &e)\n\t{\n\t\tluaL_error(ls, \"Invalid output format '%s': '%s'\", format.c_str(), e.what());\n\t}\n\n\treturn 1;\n}\n\nint falco_formats::lua_free_formatter(lua_State *ls)\n{\n\tif(!lua_islightuserdata(ls, -1) ||\n\t !lua_isstring(ls, -2))\n\n\t{\n\t\tluaL_error(ls, \"Invalid argument passed to free_formatter\");\n\t}\n\n\tstring source = luaL_checkstring(ls, -2);\n\n\tif(source == \"syscall\")\n\t{\n\t\tsinsp_evt_formatter *formatter = (sinsp_evt_formatter *)lua_topointer(ls, -1);\n\t\tdelete(formatter);\n\t}\n\telse\n\t{\n\t\tjson_event_formatter *formatter = (json_event_formatter *)lua_topointer(ls, -1);\n\t\tdelete(formatter);\n\t}\n\n\treturn 0;\n}\n\nstring falco_formats::format_event(const gen_event *evt, const std::string &rule, const std::string &source,\n\t\t\t\t const std::string &level, const std::string &format)\n{\n\n\tstring line;\n\tstring json_line;\n\tstring sformat = format;\n\n\tif(strcmp(source.c_str(), \"syscall\") == 0)\n\t{\n\t\t\/\/ This is \"output\"\n\t\ts_formatters->tostring((sinsp_evt *)evt, sformat, &line);\n\n\t\tif(s_json_output)\n\t\t{\n\t\t\tsinsp_evt::param_fmt cur_fmt = s_inspector->get_buffer_format();\n\t\t\tswitch(cur_fmt)\n\t\t\t{\n\t\t\tcase sinsp_evt::PF_NORMAL:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSON);\n\t\t\t\tbreak;\n\t\t\tcase sinsp_evt::PF_EOLS:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSONEOLS);\n\t\t\t\tbreak;\n\t\t\tcase sinsp_evt::PF_HEX:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSONHEX);\n\t\t\t\tbreak;\n\t\t\tcase sinsp_evt::PF_HEXASCII:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSONHEXASCII);\n\t\t\t\tbreak;\n\t\t\tcase sinsp_evt::PF_BASE64:\n\t\t\t\ts_inspector->set_buffer_format(sinsp_evt::PF_JSONBASE64);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/ do nothing\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\/\/ This is output fields\n\t\t\ts_formatters->tostring((sinsp_evt *)evt, sformat, &json_line);\n\n\t\t\t\/\/ The formatted string might have a leading newline. If it does, remove it.\n\t\t\tif(json_line[0] == '\\n')\n\t\t\t{\n\t\t\t\tjson_line.erase(0, 1);\n\t\t\t}\n\t\t\ts_inspector->set_buffer_format(cur_fmt);\n\t\t}\n\t}\n\telse\n\t{\n\t\tjson_event_formatter formatter(s_engine->json_factory(), sformat);\n\n\t\tline = formatter.tostring((json_event *)evt);\n\n\t\tif(s_json_output)\n\t\t{\n\t\t\tjson_line = formatter.tojson((json_event *)evt);\n\t\t}\n\t}\n\n\t\/\/ For JSON output, the formatter returned a json-as-text\n\t\/\/ object containing all the fields in the original format\n\t\/\/ message as well as the event time in ns. Use this to build\n\t\/\/ a more detailed object containing the event time, rule,\n\t\/\/ severity, full output, and fields.\n\tif(s_json_output)\n\t{\n\t\tJson::Value event;\n\t\tJson::FastWriter writer;\n\t\tstring full_line;\n\n\t\t\/\/ Convert the time-as-nanoseconds to a more json-friendly ISO8601.\n\t\ttime_t evttime = evt->get_ts() \/ 1000000000;\n\t\tchar time_sec[20]; \/\/ sizeof \"YYYY-MM-DDTHH:MM:SS\"\n\t\tchar time_ns[12]; \/\/ sizeof \".sssssssssZ\"\n\t\tstring iso8601evttime;\n\n\t\tstrftime(time_sec, sizeof(time_sec), \"%FT%T\", gmtime(&evttime));\n\t\tsnprintf(time_ns, sizeof(time_ns), \".%09luZ\", evt->get_ts() % 1000000000);\n\t\tiso8601evttime = time_sec;\n\t\tiso8601evttime += time_ns;\n\t\tevent[\"time\"] = iso8601evttime;\n\t\tevent[\"rule\"] = rule;\n\t\tevent[\"priority\"] = level;\n\n\t\tif(s_json_include_output_property)\n\t\t{\n\t\t\t\/\/ This is the filled-in output line.\n\t\t\tevent[\"output\"] = line;\n\t\t}\n\n\t\tfull_line = writer.write(event);\n\n\t\t\/\/ Json::FastWriter may add a trailing newline. If it\n\t\t\/\/ does, remove it.\n\t\tif(full_line[full_line.length() - 1] == '\\n')\n\t\t{\n\t\t\tfull_line.resize(full_line.length() - 1);\n\t\t}\n\n\t\t\/\/ Cheat-graft the output from the formatter into this\n\t\t\/\/ string. Avoids an unnecessary json parse just to\n\t\t\/\/ merge the formatted fields at the object level.\n\t\tfull_line.pop_back();\n\t\tfull_line.append(\", \\\"output_fields\\\": \");\n\t\tfull_line.append(json_line);\n\t\tfull_line.append(\"}\");\n\t\tline = full_line;\n\t}\n\n\treturn line.c_str();\n}\n\nmap<string, string> falco_formats::resolve_tokens(const gen_event *evt, const std::string &source, const std::string &format)\n{\n\tstring sformat = format;\n\tmap<string, string> values;\n\tif(source == \"syscall\")\n\t{\n\t\ts_formatters->resolve_tokens((sinsp_evt *)evt, sformat, values);\n\t}\n\t\/\/ k8s_audit\n\telse\n\t{\n\t\tjson_event_formatter json_formatter(s_engine->json_factory(), sformat);\n\t\tvalues = json_formatter.tomap((json_event *)evt);\n\t}\n\treturn values;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"semilinSetNdd.h\"\n\nint static_i = 0;\n\nbool SemilinSetNdd::genepi_init(std::string pluginname, int number_of_variables)\n{\n genepi_loader_init();\n genepi_loader_load_default_plugins();\n plugin = genepi_loader_get_plugin(pluginname.c_str());\n std::cout << \"Plugin: \" << genepi_plugin_get_name(plugin) << std::endl;\n \/\/ TODO: use of cache???\n solver = genepi_solver_create(plugin, 0, 0, 0);\n k = number_of_variables;\n return true; \/\/ TODO: return correct value!\n}\n\nbool SemilinSetNdd::genepi_dealloc() {\n genepi_solver_delete(solver);\n genepi_plugin_del_reference(plugin);\n genepi_loader_terminate();\n return true;\n}\n\nSemilinSetNdd::SemilinSetNdd() : set(Genepi(solver, k, false)) {\n}\n\nSemilinSetNdd::SemilinSetNdd(int zero) : set(Genepi(solver, k, false)) {\n assert(zero == 0);\n}\n\nSemilinSetNdd::SemilinSetNdd(VarId var) : SemilinSetNdd(var, 1) {\n}\n\nSemilinSetNdd::SemilinSetNdd(VarId var, int cnt) {\n auto v = var_map.find(var);\n if(v == var_map.end())\n {\n var_map.insert(std::make_pair(var, var_map.size()));\n v = var_map.find(var);\n }\n\n int position = v->second; \/\/ which position is this variable on?\n std::vector<int> alpha(k);\n alpha.at(position) = cnt;\n\n this->set = Genepi(solver, alpha, false);\n this->offsets.insert(this->offsets.end(), std::vector<int>(k));\n this->offsets.at(0).at(position) = cnt;\n}\nSemilinSetNdd::SemilinSetNdd(Genepi set, std::vector<std::vector<int>> offsets) : set(set), offsets(offsets){\n}\n\nSemilinSetNdd::SemilinSetNdd(const SemilinSetNdd& expr) : set(expr.set), offsets(expr.offsets) {\n}\n\nSemilinSetNdd::~SemilinSetNdd() {\n}\n\nSemilinSetNdd SemilinSetNdd::operator=(const SemilinSetNdd& term) {\n this->set = term.set;\n this->offsets = term.offsets;\n return *this;\n}\n\nSemilinSetNdd SemilinSetNdd::operator+=(const SemilinSetNdd& term) {\n this->set = this->set.union_op(term.set);\n this->offsets.insert(this->offsets.begin(), term.offsets.begin(), term.offsets.end());\n return *this;\n}\n\n\nSemilinSetNdd SemilinSetNdd::operator*=(const SemilinSetNdd& term) {\n std::vector<int> sel_a(3*k, 1);\n std::vector<int> sel_b(3*k, 1);\n std::vector<int> sel_res(3*k, 1);\n for(int i = 0; i < k; i++)\n {\n sel_a[3*i] = 0;\n sel_b[3*i+1] = 0;\n sel_res[3*i+2] = 0;\n }\n\n \/\/ inverse projection from original dimensions to an extended version, which is intersected with the natural numbers\n Genepi a_ext(this->set.invproject(sel_a).intersect(Genepi(solver, 3*k, true)));\n Genepi b_ext(term.set.invproject(sel_b).intersect(Genepi(solver, 3*k, true)));\n\n std::vector<int> generic_alpha = {1, 1, -1}; \/\/ 1*a[i]+1*b[i]-1*c[i]=0\n Genepi generic_sum(solver, generic_alpha, 0);\n\n std::vector<int> component_selection(3*k, 1);\n\n \/\/ initialize the result automaton with (a_i,b_i,N) for i in 0..k-1\n Genepi result(solver, 3*k, true); \/\/ natural numbers\n result = result.intersect(a_ext).intersect(b_ext);\n\n \/\/ one run for each variable\n for(int i = 0; i < k; i++)\n {\n \/\/ TODO: figure out, if precalculating this and apply inv_project has better complexity\n \/\/ than always create a new sum automaton for different components\n component_selection[3*i] = 0;\n component_selection[3*i+1] = 0;\n component_selection[3*i+2] = 0;\n \/\/ inverse projection on generic sum automaton to create automaton for component i\n Genepi component_sum(generic_sum.invproject(component_selection));\n \/\/ use this sum automaton on the intermediate result\n result = result.intersect(component_sum);\n\n component_selection[3*i] = 1; \/\/ reset component_selection\n component_selection[3*i+1] = 1;\n component_selection[3*i+2] = 1;\n this->offsets.insert(this->offsets.begin(), term.offsets.begin(), term.offsets.end());\n }\n\n this->set = result.project(sel_res);\n return *this;\n\n}\n\nbool SemilinSetNdd::operator < (const SemilinSetNdd& term) const {\n return this->set < term.set;\n}\nbool SemilinSetNdd::operator == (const SemilinSetNdd& term) const {\n return this->set == term.set;\n}\nSemilinSetNdd SemilinSetNdd::star () const {\n SemilinSetNdd offset_star = one();\n for(auto offset : this->offsets) {\n offset_star *= SemilinSetNdd(Genepi(this->solver, offset, true),{}); \/\/ offsets are used and converted to generators\n }\n\n SemilinSetNdd result = one();\n\n for(int i = 0; i < k; i++) {\n SemilinSetNdd temp = *this;\n \/\/ TODO: this is a very naive version of calculating temp^i (there are better methods...)\n for(int j = 0; j < i; j++) {\n temp *= *this;\n }\n if(i > 1) {\n temp *= offset_star;\n }\n result += temp;\n }\n return result;\n}\n\nSemilinSetNdd SemilinSetNdd::null() {\n if(!SemilinSetNdd::elem_null)\n SemilinSetNdd::elem_null = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd());\n return *SemilinSetNdd::elem_null;\n}\n\nSemilinSetNdd SemilinSetNdd::one() {\n if(!SemilinSetNdd::elem_one)\n SemilinSetNdd::elem_one = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd(Genepi(solver, std::vector<int>(k,0), false), {}));\n return *SemilinSetNdd::elem_one;\n}\n\nstd::string SemilinSetNdd::string() const {\n \/\/ TODO: is there a better way to express the automaton than producing a graph?\n return this->set.output(\"result\", static_i++, \"\");\n}\n\nconst bool SemilinSetNdd::is_idempotent = true;\nconst bool SemilinSetNdd::is_commutative = true;\nstd::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_null;\nstd::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_one;\ngenepi_solver* SemilinSetNdd::solver;\ngenepi_plugin* SemilinSetNdd::plugin;\nstd::unordered_map<VarId, int> SemilinSetNdd::var_map;\nint SemilinSetNdd::k = 0;\n<commit_msg>fixed a bug in semilinsetndd...<commit_after>#include <iostream>\n#include \"semilinSetNdd.h\"\n\nint static_i = 0;\n\n\/\/ insert an offset if it is unique in offsets\nstd::vector<std::vector<int>>& insert_offset(std::vector<std::vector<int>>& offsets, const std::vector<int>& offset) {\n if(std::find(offsets.begin(), offsets.end(), offset) == offsets.end())\n {\n offsets.push_back(offset);\n }\n return offsets;\n}\n\nstd::vector<std::vector<int>> multiply_offsets(const std::vector<std::vector<int>>& offsets1, const std::vector<std::vector<int>>& offsets2) {\n std::vector<std::vector<int>> offsets;\n for(auto o1 : offsets1) {\n for(auto o2 : offsets2) {\n assert(o1.size() == o2.size());\n std::vector<int> o(o1.size());\n for(int i=0; i<o1.size(); ++i) {\n o.at(i) = o1.at(i) + o2.at(i);\n }\n offsets = insert_offset(offsets, o);\n }\n }\n return offsets;\n}\n\nbool SemilinSetNdd::genepi_init(std::string pluginname, int number_of_variables)\n{\n genepi_loader_init();\n genepi_loader_load_default_plugins();\n plugin = genepi_loader_get_plugin(pluginname.c_str());\n std::cout << \"Plugin: \" << genepi_plugin_get_name(plugin) << std::endl;\n \/\/ TODO: use of cache???\n solver = genepi_solver_create(plugin, 0, 0, 0);\n k = number_of_variables;\n return true; \/\/ TODO: return correct value!\n}\n\nbool SemilinSetNdd::genepi_dealloc() {\n genepi_solver_delete(solver);\n genepi_plugin_del_reference(plugin);\n genepi_loader_terminate();\n return true;\n}\n\nSemilinSetNdd::SemilinSetNdd() : set(Genepi(solver, k, false)) {\n}\n\nSemilinSetNdd::SemilinSetNdd(int zero) : set(Genepi(solver, k, false)) {\n assert(zero == 0);\n}\n\nSemilinSetNdd::SemilinSetNdd(VarId var) : SemilinSetNdd(var, 1) {\n}\n\nSemilinSetNdd::SemilinSetNdd(VarId var, int cnt) {\n auto v = var_map.find(var);\n if(v == var_map.end())\n {\n var_map.insert(std::make_pair(var, var_map.size()));\n v = var_map.find(var);\n }\n\n int position = v->second; \/\/ which position is this variable on?\n std::vector<int> alpha(k);\n alpha.at(position) = cnt;\n\n this->set = Genepi(solver, alpha, false);\n this->offsets.push_back(std::vector<int>(k,0));\n this->offsets.at(0).at(position) = cnt;\n}\nSemilinSetNdd::SemilinSetNdd(Genepi set, std::vector<std::vector<int>> offsets) : set(set), offsets(offsets){\n}\n\nSemilinSetNdd::SemilinSetNdd(const SemilinSetNdd& expr) : set(expr.set), offsets(expr.offsets) {\n}\n\nSemilinSetNdd::~SemilinSetNdd() {\n}\n\nSemilinSetNdd SemilinSetNdd::operator=(const SemilinSetNdd& term) {\n this->set = term.set;\n this->offsets = term.offsets;\n return *this;\n}\n\nSemilinSetNdd SemilinSetNdd::operator+=(const SemilinSetNdd& term) {\n this->set = this->set.union_op(term.set);\n for(auto offset : term.offsets)\n insert_offset(this->offsets, offset);\n return *this;\n}\n\n\nSemilinSetNdd SemilinSetNdd::operator*=(const SemilinSetNdd& term) {\n std::vector<int> sel_a(3*k, 1);\n std::vector<int> sel_b(3*k, 1);\n std::vector<int> sel_res(3*k, 1);\n for(int i = 0; i < k; i++)\n {\n sel_a[3*i] = 0;\n sel_b[3*i+1] = 0;\n sel_res[3*i+2] = 0;\n }\n\n \/\/ inverse projection from original dimensions to an extended version, which is intersected with the natural numbers\n Genepi a_ext(this->set.invproject(sel_a).intersect(Genepi(solver, 3*k, true)));\n Genepi b_ext(term.set.invproject(sel_b).intersect(Genepi(solver, 3*k, true)));\n\n std::vector<int> generic_alpha = {1, 1, -1}; \/\/ 1*a[i]+1*b[i]-1*c[i]=0\n Genepi generic_sum(solver, generic_alpha, 0);\n\n std::vector<int> component_selection(3*k, 1);\n\n \/\/ initialize the result automaton with (a_i,b_i,N) for i in 0..k-1\n Genepi result(solver, 3*k, true); \/\/ natural numbers\n result = result.intersect(a_ext).intersect(b_ext);\n\n \/\/ one run for each variable\n for(int i = 0; i < k; i++)\n {\n \/\/ TODO: figure out, if precalculating this and apply inv_project has better complexity\n \/\/ than always create a new sum automaton for different components\n component_selection[3*i] = 0;\n component_selection[3*i+1] = 0;\n component_selection[3*i+2] = 0;\n \/\/ inverse projection on generic sum automaton to create automaton for component i\n Genepi component_sum(generic_sum.invproject(component_selection));\n \/\/ use this sum automaton on the intermediate result\n result = result.intersect(component_sum);\n\n component_selection[3*i] = 1; \/\/ reset component_selection\n component_selection[3*i+1] = 1;\n component_selection[3*i+2] = 1;\n }\n this->offsets = multiply_offsets(this->offsets, term.offsets);\n this->set = result.project(sel_res);\n return *this;\n\n}\n\nbool SemilinSetNdd::operator < (const SemilinSetNdd& term) const {\n return this->set < term.set;\n}\nbool SemilinSetNdd::operator == (const SemilinSetNdd& term) const {\n return this->set == term.set;\n}\nSemilinSetNdd SemilinSetNdd::star () const {\n SemilinSetNdd offset_star = one();\n for(auto offset : this->offsets) {\n offset_star *= SemilinSetNdd(Genepi(this->solver, offset, true),{}); \/\/ offsets are used and converted to generators\n }\n\n SemilinSetNdd result = one(); \/\/ result = 1\n\n for(int i = 1; i <= k; i++) { \/\/ 1..k\n SemilinSetNdd temp = *this; \/\/ S^1\n \/\/ TODO: this is a very naive version of calculating S^i (there are better methods...)\n for(int j = 1; j < i; j++) { \/\/ 1..j-1: j=2 1..1 -> S^2, j=3 1..2 -> S^3\n temp *= *this;\n }\n \/\/ temp = S^i\n temp *= offset_star; \/\/ S^i * offset_star\n result += temp;\n }\n return result;\n}\n\nSemilinSetNdd SemilinSetNdd::null() {\n if(!SemilinSetNdd::elem_null)\n SemilinSetNdd::elem_null = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd());\n return *SemilinSetNdd::elem_null;\n}\n\nSemilinSetNdd SemilinSetNdd::one() {\n if(!SemilinSetNdd::elem_one)\n SemilinSetNdd::elem_one = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd(Genepi(solver, std::vector<int>(k,0), false), {std::vector<int>(k,0)}));\n return *SemilinSetNdd::elem_one;\n}\n\nstd::string SemilinSetNdd::string() const {\n \/\/ TODO: is there a better way to express the automaton than producing a graph?\n return this->set.output(\"result\", static_i++, \"\");\n}\n\nconst bool SemilinSetNdd::is_idempotent = true;\nconst bool SemilinSetNdd::is_commutative = true;\nstd::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_null;\nstd::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_one;\ngenepi_solver* SemilinSetNdd::solver;\ngenepi_plugin* SemilinSetNdd::plugin;\nstd::unordered_map<VarId, int> SemilinSetNdd::var_map;\nint SemilinSetNdd::k = 0;\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"rubberbandselectionmanipulator.h\"\n\n#include \"formeditorscene.h\"\n\nnamespace QmlDesigner {\n\nRubberBandSelectionManipulator::RubberBandSelectionManipulator(LayerItem *layerItem, FormEditorView *editorView)\n : m_selectionRectangleElement(layerItem),\n m_editorView(editorView),\n m_beginFormEditorItem(0),\n m_isActive(false)\n{\n m_selectionRectangleElement.hide();\n}\n\nvoid RubberBandSelectionManipulator::clear()\n{\n m_selectionRectangleElement.clear();\n m_isActive = false;\n m_beginPoint = QPointF();\n m_itemList.clear();\n m_oldSelectionList.clear();\n}\n\nFormEditorItem *RubberBandSelectionManipulator::topFormEditorItem(const QList<QGraphicsItem*> &itemList)\n{\n foreach (QGraphicsItem *item, itemList) {\n FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);\n\n if (formEditorItem)\n {\n return formEditorItem;\n }\n }\n\n return m_editorView->scene()->rootFormEditorItem();\n}\n\nvoid RubberBandSelectionManipulator::begin(const QPointF& beginPoint)\n{\n m_beginPoint = beginPoint;\n m_selectionRectangleElement.setRect(m_beginPoint, m_beginPoint);\n m_selectionRectangleElement.show();\n m_isActive = true;\n m_beginFormEditorItem = topFormEditorItem(m_editorView->scene()->items(beginPoint));\n m_oldSelectionList = toQmlItemNodeList(m_editorView->selectedModelNodes());\n}\n\nvoid RubberBandSelectionManipulator::update(const QPointF& updatePoint)\n{\n m_selectionRectangleElement.setRect(m_beginPoint, updatePoint);\n}\n\nvoid RubberBandSelectionManipulator::end()\n{\n m_oldSelectionList.clear();\n m_selectionRectangleElement.hide();\n m_isActive = false;\n}\n\nvoid RubberBandSelectionManipulator::select(SelectionType selectionType)\n{\n if (!m_beginFormEditorItem)\n return;\n\n QList<QGraphicsItem*> itemList = m_editorView->scene()->items(m_selectionRectangleElement.rect(), Qt::IntersectsItemShape);\n QList<QmlItemNode> newNodeList;\n\n foreach (QGraphicsItem* item, itemList)\n {\n FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);\n\n if (formEditorItem\n && formEditorItem->qmlItemNode().isValid()\n && m_beginFormEditorItem->childItems().contains(formEditorItem)\n && formEditorItem->qmlItemNode().instanceIsMovable()\n && !formEditorItem->qmlItemNode().instanceIsInLayoutable())\n {\n newNodeList.append(formEditorItem->qmlItemNode());\n }\n }\n\n if (newNodeList.isEmpty()\n && m_beginFormEditorItem->qmlItemNode().isValid()\n && m_beginFormEditorItem->qmlItemNode().instanceIsMovable()\n && !m_beginFormEditorItem->qmlItemNode().instanceIsInLayoutable())\n newNodeList.append(m_beginFormEditorItem->qmlItemNode());\n\n QList<QmlItemNode> nodeList;\n\n switch (selectionType) {\n case AddToSelection: {\n nodeList.append(m_oldSelectionList);\n nodeList.append(newNodeList);\n }\n break;\n case ReplaceSelection: {\n nodeList.append(newNodeList);\n }\n break;\n case RemoveFromSelection: {\n QSet<QmlItemNode> oldSelectionSet(m_oldSelectionList.toSet());\n QSet<QmlItemNode> newSelectionSet(newNodeList.toSet());\n nodeList.append(oldSelectionSet.subtract(newSelectionSet).toList());\n }\n }\n\n m_editorView->setSelectedModelNodes(toModelNodeList(nodeList));\n}\n\n\nvoid RubberBandSelectionManipulator::setItems(const QList<FormEditorItem*> &itemList)\n{\n m_itemList = itemList;\n}\n\nQPointF RubberBandSelectionManipulator::beginPoint() const\n{\n return m_beginPoint;\n}\n\nbool RubberBandSelectionManipulator::isActive() const\n{\n return m_isActive;\n}\n\n}\n<commit_msg>QmlDesigner: Items should be only selected if the have no xy binding<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"rubberbandselectionmanipulator.h\"\n\n#include \"formeditorscene.h\"\n\nnamespace QmlDesigner {\n\nRubberBandSelectionManipulator::RubberBandSelectionManipulator(LayerItem *layerItem, FormEditorView *editorView)\n : m_selectionRectangleElement(layerItem),\n m_editorView(editorView),\n m_beginFormEditorItem(0),\n m_isActive(false)\n{\n m_selectionRectangleElement.hide();\n}\n\nvoid RubberBandSelectionManipulator::clear()\n{\n m_selectionRectangleElement.clear();\n m_isActive = false;\n m_beginPoint = QPointF();\n m_itemList.clear();\n m_oldSelectionList.clear();\n}\n\nFormEditorItem *RubberBandSelectionManipulator::topFormEditorItem(const QList<QGraphicsItem*> &itemList)\n{\n foreach (QGraphicsItem *item, itemList) {\n FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);\n\n if (formEditorItem)\n {\n return formEditorItem;\n }\n }\n\n return m_editorView->scene()->rootFormEditorItem();\n}\n\nvoid RubberBandSelectionManipulator::begin(const QPointF& beginPoint)\n{\n m_beginPoint = beginPoint;\n m_selectionRectangleElement.setRect(m_beginPoint, m_beginPoint);\n m_selectionRectangleElement.show();\n m_isActive = true;\n m_beginFormEditorItem = topFormEditorItem(m_editorView->scene()->items(beginPoint));\n m_oldSelectionList = toQmlItemNodeList(m_editorView->selectedModelNodes());\n}\n\nvoid RubberBandSelectionManipulator::update(const QPointF& updatePoint)\n{\n m_selectionRectangleElement.setRect(m_beginPoint, updatePoint);\n}\n\nvoid RubberBandSelectionManipulator::end()\n{\n m_oldSelectionList.clear();\n m_selectionRectangleElement.hide();\n m_isActive = false;\n}\n\nvoid RubberBandSelectionManipulator::select(SelectionType selectionType)\n{\n if (!m_beginFormEditorItem)\n return;\n\n QList<QGraphicsItem*> itemList = m_editorView->scene()->items(m_selectionRectangleElement.rect(), Qt::IntersectsItemShape);\n QList<QmlItemNode> newNodeList;\n\n foreach (QGraphicsItem* item, itemList)\n {\n FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);\n\n if (formEditorItem\n && formEditorItem->qmlItemNode().isValid()\n && m_beginFormEditorItem->childItems().contains(formEditorItem)\n && formEditorItem->qmlItemNode().instanceIsMovable()\n && formEditorItem->qmlItemNode().modelIsMovable()\n && !formEditorItem->qmlItemNode().instanceIsInLayoutable())\n {\n newNodeList.append(formEditorItem->qmlItemNode());\n }\n }\n\n if (newNodeList.isEmpty()\n && m_beginFormEditorItem->qmlItemNode().isValid()\n && m_beginFormEditorItem->qmlItemNode().instanceIsMovable()\n && m_beginFormEditorItem->qmlItemNode().modelIsMovable()\n && !m_beginFormEditorItem->qmlItemNode().instanceIsInLayoutable())\n newNodeList.append(m_beginFormEditorItem->qmlItemNode());\n\n QList<QmlItemNode> nodeList;\n\n switch (selectionType) {\n case AddToSelection: {\n nodeList.append(m_oldSelectionList);\n nodeList.append(newNodeList);\n }\n break;\n case ReplaceSelection: {\n nodeList.append(newNodeList);\n }\n break;\n case RemoveFromSelection: {\n QSet<QmlItemNode> oldSelectionSet(m_oldSelectionList.toSet());\n QSet<QmlItemNode> newSelectionSet(newNodeList.toSet());\n nodeList.append(oldSelectionSet.subtract(newSelectionSet).toList());\n }\n }\n\n m_editorView->setSelectedModelNodes(toModelNodeList(nodeList));\n}\n\n\nvoid RubberBandSelectionManipulator::setItems(const QList<FormEditorItem*> &itemList)\n{\n m_itemList = itemList;\n}\n\nQPointF RubberBandSelectionManipulator::beginPoint() const\n{\n return m_beginPoint;\n}\n\nbool RubberBandSelectionManipulator::isActive() const\n{\n return m_isActive;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtSystems module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 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\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\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**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtTest\/QtTest>\n#include \"qvaluespace.h\"\n#include \"qvaluespacepublisher.h\"\n#include \"qvaluespacesubscriber.h\"\n\nQT_USE_NAMESPACE\n\nclass tst_QValueSpace : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void initTestCase();\n\n void tst_availableLayers();\n\n void tst_PublisherPath_data();\n void tst_PublisherPath();\n\n void tst_PublishSubscribe_data();\n void tst_PublishSubscribe();\n};\n\nvoid tst_QValueSpace::initTestCase()\n{\n QValueSpace::initValueSpaceServer();\n}\n\nvoid tst_QValueSpace::tst_availableLayers()\n{\n QList<QUuid> layers = QValueSpace::availableLayers();\n\n if (layers.size() == 0)\n QSKIP(\"No value space layer available, thus skip all the test cases.\");\n\n#if defined(Q_OS_LINUX)\n#if !defined(QT_NO_GCONFLAYER)\n QVERIFY(layers.contains(QVALUESPACE_GCONF_LAYER));\n#endif\n#if !defined(QT_NO_CONTEXTKIT)\n QVERIFY(layers.contains(QVALUESPACE_CONTEXTKITNONCORE_LAYER));\n QVERIFY(layers.contains(QVALUESPACE_CONTEXTKITCORE_LAYER));\n#endif\n#if !defined(QT_NO_JSONDBLAYER)\n QVERIFY(layers.contains(QVALUESPACE_JSONDB_LAYER));\n#endif\n#elif defined(Q_OS_WIN)\n QVERIFY(layers.contains(QVALUESPACE_VOLATILEREGISTRY_LAYER));\n QVERIFY(layers.contains(QVALUESPACE_NONVOLATILEREGISTRY_LAYER));\n#else\n QVERIFY(layers.contains(QVALUESPACE_SHAREDMEMORY_LAYER));\n#endif\n}\n\nvoid tst_QValueSpace::tst_PublisherPath_data()\n{\n QTest::addColumn<QString>(\"path\");\n\n QTest::newRow(\"root\") << QString::fromAscii(\"\/\");\n QTest::newRow(\"non existing path\") << QString::fromAscii(\"\/a\/path\/that\/doesnt\/exist\");\n}\n\nvoid tst_QValueSpace::tst_PublisherPath()\n{\n if (QValueSpace::availableLayers().size() == 0)\n QSKIP(\"No value space layer available, thus skip all the test cases.\");\n\n QFETCH(QString, path);\n\n QValueSpacePublisher publisher(path);\n QVERIFY(publisher.isConnected());\n QCOMPARE(publisher.path(), path);\n}\n\nvoid tst_QValueSpace::tst_PublishSubscribe_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<QString>(\"name\");\n QTest::addColumn<QVariant>(\"value\");\n\n QTest::newRow(\"root\") << QString::fromAscii(\"\/\") << QString::fromAscii(\"myName\") << QVariant::fromValue(QString::fromAscii(\"myValue\"));\n QTest::newRow(\"non existing path\") << QString::fromAscii(\"\/a\/path\/that\/doesnt\/exist\") << QString::fromAscii(\"propertyName\") << QVariant::fromValue(QString::fromAscii(\"propertyValue\"));\n}\n\nvoid tst_QValueSpace::tst_PublishSubscribe()\n{\n if (QValueSpace::availableLayers().size() == 0)\n QSKIP(\"No value space layer available, thus skip all the test cases.\");\n\n QFETCH(QString, path);\n QFETCH(QString, name);\n QFETCH(QVariant, value);\n\n QValueSpacePublisher publisher(path);\n QVERIFY(publisher.isConnected());\n publisher.setValue(name, value);\n publisher.sync();\n\n QValueSpaceSubscriber subscriber(path);\n QVERIFY(subscriber.isConnected());\n QCOMPARE(subscriber.value(name), value);\n\n subscriber.cd(name);\n QCOMPARE(subscriber.value(), value);\n\n publisher.resetValue(name);\n publisher.sync();\n}\n\nQTEST_MAIN(tst_QValueSpace)\n#include \"tst_qvaluespace.moc\"\n<commit_msg>Disabled unit tests if JSON DB backend is in use.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtSystems module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 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\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\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**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtTest\/QtTest>\n#include \"qvaluespace.h\"\n#include \"qvaluespacepublisher.h\"\n#include \"qvaluespacesubscriber.h\"\n\nQT_USE_NAMESPACE\n\nclass tst_QValueSpace : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void initTestCase();\n\n void tst_availableLayers();\n\n void tst_PublisherPath_data();\n void tst_PublisherPath();\n\n void tst_PublishSubscribe_data();\n void tst_PublishSubscribe();\n};\n\nvoid tst_QValueSpace::initTestCase()\n{\n QValueSpace::initValueSpaceServer();\n}\n\nvoid tst_QValueSpace::tst_availableLayers()\n{\n QList<QUuid> layers = QValueSpace::availableLayers();\n\n if (layers.size() == 0)\n QSKIP(\"No value space layer available, thus skip all the test cases.\");\n\n#if defined(Q_OS_LINUX)\n#if !defined(QT_NO_GCONFLAYER)\n QVERIFY(layers.contains(QVALUESPACE_GCONF_LAYER));\n#endif\n#if !defined(QT_NO_CONTEXTKIT)\n QVERIFY(layers.contains(QVALUESPACE_CONTEXTKITNONCORE_LAYER));\n QVERIFY(layers.contains(QVALUESPACE_CONTEXTKITCORE_LAYER));\n#endif\n#if !defined(QT_NO_JSONDBLAYER)\n QVERIFY(layers.contains(QVALUESPACE_JSONDB_LAYER));\n#endif\n#elif defined(Q_OS_WIN)\n QVERIFY(layers.contains(QVALUESPACE_VOLATILEREGISTRY_LAYER));\n QVERIFY(layers.contains(QVALUESPACE_NONVOLATILEREGISTRY_LAYER));\n#else\n QVERIFY(layers.contains(QVALUESPACE_SHAREDMEMORY_LAYER));\n#endif\n}\n\nvoid tst_QValueSpace::tst_PublisherPath_data()\n{\n QTest::addColumn<QString>(\"path\");\n\n QTest::newRow(\"root\") << QString::fromAscii(\"\/\");\n QTest::newRow(\"non existing path\") << QString::fromAscii(\"\/a\/path\/that\/doesnt\/exist\");\n}\n\nvoid tst_QValueSpace::tst_PublisherPath()\n{\n if (QValueSpace::availableLayers().size() == 0)\n QSKIP(\"No value space layer available, thus skip all the test cases.\");\n\n QFETCH(QString, path);\n\n QValueSpacePublisher publisher(path);\n QVERIFY(publisher.isConnected());\n QCOMPARE(publisher.path(), path);\n}\n\nvoid tst_QValueSpace::tst_PublishSubscribe_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<QString>(\"name\");\n QTest::addColumn<QVariant>(\"value\");\n\n QTest::newRow(\"root\") << QString::fromAscii(\"\/\") << QString::fromAscii(\"myName\") << QVariant::fromValue(QString::fromAscii(\"myValue\"));\n QTest::newRow(\"non existing path\") << QString::fromAscii(\"\/a\/path\/that\/doesnt\/exist\") << QString::fromAscii(\"propertyName\") << QVariant::fromValue(QString::fromAscii(\"propertyValue\"));\n}\n\nvoid tst_QValueSpace::tst_PublishSubscribe()\n{\n if (QValueSpace::availableLayers().size() == 0)\n QSKIP(\"No value space layer available, thus skip all the test cases.\");\n\n if (QValueSpace::availableLayers().contains(QVALUESPACE_JSONDB_LAYER))\n QSKIP(\"Unit tests for JSON DB layer are currently unsupported!.\");\n\n QFETCH(QString, path);\n QFETCH(QString, name);\n QFETCH(QVariant, value);\n\n QValueSpacePublisher publisher(path);\n QVERIFY(publisher.isConnected());\n publisher.setValue(name, value);\n publisher.sync();\n\n QValueSpaceSubscriber subscriber(path);\n QVERIFY(subscriber.isConnected());\n QCOMPARE(subscriber.value(name), value);\n\n subscriber.cd(name);\n QCOMPARE(subscriber.value(), value);\n\n publisher.resetValue(name);\n publisher.sync();\n}\n\nQTEST_MAIN(tst_QValueSpace)\n#include \"tst_qvaluespace.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/data\/buffer_chain_manager.hpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_DATA_BUFFER_CHAIN_MANAGER_HEADER\n#define C7A_DATA_BUFFER_CHAIN_MANAGER_HEADER\n\n#include <map>\n#include \"buffer_chain.hpp\"\n\nnamespace c7a {\nnamespace data {\n\n\/\/! Identification for buffer Chains\ntypedef size_t ChainId;\n\n\/\/! Holds instances of BlockChains and addresses them with IDs\n\/\/!\n\/\/! Required for DIAs and for incoming net channels.\n\/\/! This cannot be in the DataManger, because that would cause cyclic dependencies\nclass BufferChainManager\n{\npublic:\n \/\/! Allocates the next BufferChain.\n \/\/! Calls to this method alter the internal state -> order of call is\n \/\/! important and must be deterministic\n ChainId AllocateNext() {\n ChainId result = next_id_;\n if (!Contains(next_id_))\n Allocate(next_id_++);\n return result;\n }\n\n \/\/! Allocates a BufferChain with the given ID\n \/\/! Use this only for internal stuff.\n \/\/! \\param id id of the chain to retrieve\n \/\/! \\exception std::runtime_error if id is not contained\n ChainId Allocate(ChainId id) {\n if (Contains(id)) {\n throw new std::runtime_error(\"duplicate chain allocation with explicit id\");\n }\n chains_[id] = std::make_shared<BufferChain>();\n return id;\n }\n\n \/\/! Indicates if a Bufferchain exists with the given ID\n bool Contains(ChainId id) {\n return chains_.find(id) != chains_.end();\n }\n\n \/\/! Returns the BufferChain with the given ID\n \/\/! \\param id id of the chain to retrieve\n \/\/! \\exception std::runtime_error if id is not contained\n std::shared_ptr<BufferChain> Chain(ChainId id) {\n if (!Contains(id)) {\n throw new std::runtime_error(\"chain id is unknown\");\n }\n\n return chains_[id];\n }\n\nprivate:\n ChainId next_id_;\n std::map<ChainId, std::shared_ptr<BufferChain> > chains_;\n};\n\n} \/\/ namespace data\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_DATA_BUFFER_CHAIN_MANAGER_HEADER\n\n\/******************************************************************************\/\n<commit_msg>initialize id with 0<commit_after>\/*******************************************************************************\n * c7a\/data\/buffer_chain_manager.hpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_DATA_BUFFER_CHAIN_MANAGER_HEADER\n#define C7A_DATA_BUFFER_CHAIN_MANAGER_HEADER\n\n#include <map>\n#include \"buffer_chain.hpp\"\n\nnamespace c7a {\nnamespace data {\n\n\/\/! Identification for buffer Chains\ntypedef size_t ChainId;\n\n\/\/! Holds instances of BlockChains and addresses them with IDs\n\/\/!\n\/\/! Required for DIAs and for incoming net channels.\n\/\/! This cannot be in the DataManger, because that would cause cyclic dependencies\nclass BufferChainManager\n{\npublic:\n\n BufferChainManager() : next_id_(0) { }\n\n \/\/! Allocates the next BufferChain.\n \/\/! Calls to this method alter the internal state -> order of call is\n \/\/! important and must be deterministic\n ChainId AllocateNext() {\n ChainId result = next_id_;\n if (!Contains(next_id_))\n Allocate(next_id_++);\n return result;\n }\n\n \/\/! Allocates a BufferChain with the given ID\n \/\/! Use this only for internal stuff.\n \/\/! \\param id id of the chain to retrieve\n \/\/! \\exception std::runtime_error if id is not contained\n ChainId Allocate(ChainId id) {\n if (Contains(id)) {\n throw new std::runtime_error(\"duplicate chain allocation with explicit id\");\n }\n chains_[id] = std::make_shared<BufferChain>();\n return id;\n }\n\n \/\/! Indicates if a Bufferchain exists with the given ID\n bool Contains(ChainId id) {\n return chains_.find(id) != chains_.end();\n }\n\n \/\/! Returns the BufferChain with the given ID\n \/\/! \\param id id of the chain to retrieve\n \/\/! \\exception std::runtime_error if id is not contained\n std::shared_ptr<BufferChain> Chain(ChainId id) {\n if (!Contains(id)) {\n throw new std::runtime_error(\"chain id is unknown\");\n }\n\n return chains_[id];\n }\n\nprivate:\n ChainId next_id_;\n std::map<ChainId, std::shared_ptr<BufferChain> > chains_;\n};\n\n} \/\/ namespace data\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_DATA_BUFFER_CHAIN_MANAGER_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>#include \"builtin\/dir.hpp\"\n#include \"vm.hpp\"\n#include \"objectmemory.hpp\"\n#include \"builtin\/array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/string.hpp\"\n\n#include \"object_utils.hpp\"\n\n#include \"ontology.hpp\"\n\n#include <sys\/types.h>\n#include <dirent.h>\n\nnamespace rubinius {\n void Dir::init(STATE) {\n GO(dir).set(ontology::new_class(state, \"Dir\", G(object)));\n G(dir)->set_object_type(state, DirType);\n }\n\n Dir* Dir::create(STATE) {\n Dir* d = state->new_object<Dir>(G(dir));\n d->os_ = 0;\n\n state->memory()->needs_finalization(d, (FinalizerFunction)&Dir::finalize);\n\n return d;\n }\n\n Dir* Dir::allocate(STATE, Object* self) {\n Dir* dir = create(state);\n\n if(Class* cls = try_as<Class>(self)) {\n dir->klass(state, cls);\n }\n\n return dir;\n }\n\n void Dir::finalize(STATE, Dir* dir) {\n if(dir->os_) {\n closedir(dir->os_);\n dir->os_ = 0;\n }\n }\n\n void Dir::guard(STATE) {\n if(!os_) {\n Exception::io_error(state, \"closed directory\");\n }\n }\n\n Object* Dir::open(STATE, String* path) {\n if(os_) closedir(os_);\n\n os_ = opendir(path->c_str_null_safe(state));\n\n if(!os_) {\n Exception::errno_error(state, \"Unable to open directory\", errno, path->c_str(state));\n return 0;\n }\n\n this->path(state, path);\n\n return cTrue;\n }\n\n Object* Dir::close(STATE) {\n guard(state);\n\n if(os_) {\n closedir(os_);\n os_ = 0;\n }\n\n return cNil;\n }\n\n Object* Dir::closed_p(STATE) {\n return RBOOL(!os_);\n }\n\n Object* Dir::read(STATE) {\n guard(state);\n\n struct dirent *ent = readdir(os_);\n\n if(!ent) return cNil;\n\n return String::create(state, ent->d_name);\n }\n\n Object* Dir::control(STATE, Fixnum* kind, Integer* pos) {\n guard(state);\n\n switch(kind->to_native()) {\n case 0:\n seekdir(os_, pos->to_native());\n return cTrue;\n case 1:\n rewinddir(os_);\n return cTrue;\n case 2:\n return Integer::from(state, telldir(os_));\n }\n return cNil;\n }\n}\n<commit_msg>Use thread safe readdir_r instread of readdir<commit_after>#include \"builtin\/dir.hpp\"\n#include \"vm.hpp\"\n#include \"objectmemory.hpp\"\n#include \"builtin\/array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/string.hpp\"\n\n#include \"object_utils.hpp\"\n\n#include \"ontology.hpp\"\n\n#include <sys\/types.h>\n#include <dirent.h>\n\nnamespace rubinius {\n void Dir::init(STATE) {\n GO(dir).set(ontology::new_class(state, \"Dir\", G(object)));\n G(dir)->set_object_type(state, DirType);\n }\n\n Dir* Dir::create(STATE) {\n Dir* d = state->new_object<Dir>(G(dir));\n d->os_ = 0;\n\n state->memory()->needs_finalization(d, (FinalizerFunction)&Dir::finalize);\n\n return d;\n }\n\n Dir* Dir::allocate(STATE, Object* self) {\n Dir* dir = create(state);\n\n if(Class* cls = try_as<Class>(self)) {\n dir->klass(state, cls);\n }\n\n return dir;\n }\n\n void Dir::finalize(STATE, Dir* dir) {\n if(dir->os_) {\n closedir(dir->os_);\n dir->os_ = 0;\n }\n }\n\n void Dir::guard(STATE) {\n if(!os_) {\n Exception::io_error(state, \"closed directory\");\n }\n }\n\n Object* Dir::open(STATE, String* path) {\n if(os_) closedir(os_);\n\n os_ = opendir(path->c_str_null_safe(state));\n\n if(!os_) {\n Exception::errno_error(state, \"Unable to open directory\", errno, path->c_str(state));\n return 0;\n }\n\n this->path(state, path);\n\n return cTrue;\n }\n\n Object* Dir::close(STATE) {\n guard(state);\n\n if(os_) {\n closedir(os_);\n os_ = 0;\n }\n\n return cNil;\n }\n\n Object* Dir::closed_p(STATE) {\n return RBOOL(!os_);\n }\n\n Object* Dir::read(STATE) {\n guard(state);\n\n struct dirent ent;\n struct dirent* entp = &ent;\n readdir_r(os_, entp, &entp);\n\n if(!entp) return cNil;\n return String::create(state, ent.d_name);\n }\n\n Object* Dir::control(STATE, Fixnum* kind, Integer* pos) {\n guard(state);\n\n switch(kind->to_native()) {\n case 0:\n seekdir(os_, pos->to_native());\n return cTrue;\n case 1:\n rewinddir(os_);\n return cTrue;\n case 2:\n return Integer::from(state, telldir(os_));\n }\n return cNil;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"environment.hpp\"\n#include \"object.hpp\"\n#include \"type_info.hpp\"\n#include \"builtin\/task.hpp\"\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace rubinius;\n\nstatic void load_root(Environment& env, std::string root) {\n std::string dirs = root + \"\/index\";\n std::ifstream stream(dirs.c_str());\n if(!stream) {\n std::cout << \"It appears that \" << root << \"\/index is missing.\\n\";\n exit(1);\n }\n\n while(!stream.eof()) {\n std::string line;\n\n stream >> line;\n stream.get(); \/\/ eat newline\n\n \/\/ skip empty lines\n if(line.size() == 0) continue;\n\n std::string path = root + \"\/\" + line;\n std::cout << \"Loading directory: \" << path << \"\\n\";\n env.load_directory(path);\n }\n}\n\nint main(int argc, char** argv) {\n Environment env;\n env.load_argv(argc, argv);\n\n try {\n char* e = getenv(\"ROOT\");\n if(e) {\n std::string root = std::string(e);\n\n env.set_rubinius_constants();\n\n std::cout << \"Loading platform.conf: \" << root << \"\\n\";\n env.load_platform_conf(root);\n\n load_root(env, std::string(root));\n }\n\n if(argc < 2) {\n std::cout << \"Usage: file.rbc\" << std::endl;\n return 1;\n }\n\n std::string str(argv[1]);\n std::cout << \"Loading: \" << str << std::endl;\n\n env.run_file(str);\n return 0;\n\n } catch(ObjectBoundsExceeded &e) {\n TypeInfo* info = env.state->find_type(e.obj->obj_type); \/\/ HACK use object\n\n std::cout << \"Bounds of object exceeded:\" << std::endl;\n std::cout << \" type: \" << info->type_name << \", fields: \" <<\n e.obj->field_count << \", accessed: \" << e.index << std::endl;\n e.print_backtrace();\n } catch(Assertion &e) {\n std::cout << \"VM Assertion:\" << std::endl;\n std::cout << \" \" << e.reason << std::endl;\n e.print_backtrace();\n\n std::cout << \"Ruby backtrace:\" << std::endl;\n env.state->print_backtrace();\n } catch(TypeError &e) {\n std::cout << \"Type Error detected:\" << std::endl;\n TypeInfo* wanted = env.state->find_type(e.type);\n\n if(!e.object->reference_p()) {\n std::cout << \" Tried to use non-reference value \" << e.object;\n } else {\n TypeInfo* was = env.state->find_type(e.object->obj_type);\n std::cout << \" Tried to use object of type \" <<\n was->type_name << \" (\" << was->type << \")\";\n }\n\n std::cout << \" as type \" << wanted->type_name << \" (\" <<\n wanted->type << \")\" << std::endl;\n\n e.print_backtrace();\n\n std::cout << \"Ruby backtrace:\" << std::endl;\n env.state->print_backtrace();\n } catch(std::runtime_error& e) {\n std::cout << \"Runtime exception: \" << e.what() << std::endl;\n } catch(ArgumentError &e) {\n std::cout << \"Argument error: expected \" << e.expected << \", given \" <<\n e.given << std::endl;\n env.state->print_backtrace();\n } catch(VMException &e) {\n std::cout << \"Unknown VM exception detected.\" << std::endl;\n e.print_backtrace();\n } catch(std::string e) {\n std::cout << e << std::endl;\n } catch(...) {\n std::cout << \"Unknown exception detected.\" << std::endl;\n }\n}\n<commit_msg>Require ROOT to run vm, now that core loads<commit_after>#include <iostream>\n#include \"environment.hpp\"\n#include \"object.hpp\"\n#include \"type_info.hpp\"\n#include \"builtin\/task.hpp\"\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace rubinius;\n\nstatic void load_root(Environment& env, std::string root) {\n std::string dirs = root + \"\/index\";\n std::ifstream stream(dirs.c_str());\n if(!stream) {\n std::cout << \"It appears that \" << root << \"\/index is missing.\\n\";\n exit(1);\n }\n\n while(!stream.eof()) {\n std::string line;\n\n stream >> line;\n stream.get(); \/\/ eat newline\n\n \/\/ skip empty lines\n if(line.size() == 0) continue;\n\n std::string path = root + \"\/\" + line;\n std::cout << \"Loading directory: \" << path << \"\\n\";\n env.load_directory(path);\n }\n}\n\nint main(int argc, char** argv) {\n Environment env;\n env.load_argv(argc, argv);\n\n try {\n char* e = getenv(\"ROOT\");\n\n if(!e) {\n Assertion::raise(\"set ROOT to runtime (or equiv)\");\n }\n\n std::string root = std::string(e);\n env.set_rubinius_constants();\n\n std::cout << \"Loading platform.conf: \" << root << \"\\n\";\n env.load_platform_conf(root);\n\n load_root(env, std::string(root));\n\n std::string loader = root + \"\/loader.rbc\";\n\n env.run_file(loader);\n return 0;\n\n } catch(ObjectBoundsExceeded &e) {\n TypeInfo* info = env.state->find_type(e.obj->obj_type); \/\/ HACK use object\n\n std::cout << \"Bounds of object exceeded:\" << std::endl;\n std::cout << \" type: \" << info->type_name << \", fields: \" <<\n e.obj->field_count << \", accessed: \" << e.index << std::endl;\n e.print_backtrace();\n } catch(Assertion &e) {\n std::cout << \"VM Assertion:\" << std::endl;\n std::cout << \" \" << e.reason << std::endl;\n e.print_backtrace();\n\n std::cout << \"Ruby backtrace:\" << std::endl;\n env.state->print_backtrace();\n } catch(TypeError &e) {\n std::cout << \"Type Error detected:\" << std::endl;\n TypeInfo* wanted = env.state->find_type(e.type);\n\n if(!e.object->reference_p()) {\n std::cout << \" Tried to use non-reference value \" << e.object;\n } else {\n TypeInfo* was = env.state->find_type(e.object->obj_type);\n std::cout << \" Tried to use object of type \" <<\n was->type_name << \" (\" << was->type << \")\";\n }\n\n std::cout << \" as type \" << wanted->type_name << \" (\" <<\n wanted->type << \")\" << std::endl;\n\n e.print_backtrace();\n\n std::cout << \"Ruby backtrace:\" << std::endl;\n env.state->print_backtrace();\n } catch(std::runtime_error& e) {\n std::cout << \"Runtime exception: \" << e.what() << std::endl;\n } catch(ArgumentError &e) {\n std::cout << \"Argument error: expected \" << e.expected << \", given \" <<\n e.given << std::endl;\n env.state->print_backtrace();\n } catch(VMException &e) {\n std::cout << \"Unknown VM exception detected.\" << std::endl;\n e.print_backtrace();\n } catch(std::string e) {\n std::cout << e << std::endl;\n } catch(...) {\n std::cout << \"Unknown exception detected.\" << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\/*\n * Main authors:\n * Christopher Mears <chris.mears@monash.edu>\n *\n * Copyright:\n * Christopher Mears, 2012\n *\n * Last modified:\n * $Date$ by $Author$\n * $Revision$\n *\n * This file is part of Gecode, the generic constraint\n * development environment:\n * http:\/\/www.gecode.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#ifndef __GECODE_SET_LDSB_HH__\n#define __GECODE_SET_LDSB_HH__\n\n#include <gecode\/set.hh>\n#include <gecode\/int\/ldsb.hh>\n\n\/**\n * \\namespace Gecode::Set::LDSB\n * \\brief Symmetry breaking for set variables\n *\/\nnamespace Gecode { namespace Set { namespace LDSB {\n\n using namespace Int::LDSB;\n \n \/**\n * \\brief Symmetry-breaking brancher with generic view and value\n * selection\n *\n * Implements view-based branching for an array of views (of type\n * \\a View) on set variables and value (of type \\a Val).\n *\n *\/\n template<class View, int n, class Val, unsigned int a>\n class LDSBSetBrancher : public LDSBBrancher<View,n,Val,a> {\n public:\n \/\/\/ Function type for printing variable and value selection\n typedef void (*VarValPrint)(const Space& home, unsigned int a,\n typename View::VarType x, int i,\n const Val& n,\n std::ostream& o);\n \/\/\/ Position of previous variable that was branched on\n int _prevPos;\n \/\/\/ Number of non-value symmetries\n int _nNonValueSymmetries;\n \/\/\/ Number of value symmetries\n int _nValueSymmetries;\n \/\/\/ Copy of value symmetries from the first node where the current\n \/\/\/ variable was branched on.\n ValueSymmetryImp<View>** _copiedSyms;\n \/\/\/ Number of copied symmetries\n int _nCopiedSyms;\n \/\/\/ Set of values used on left branches for the current variable\n IntSet _leftBranchValues;\n \/**\n * \\brief Is the state of the brancher \"stable\"?\n * \n * The brancher is unstable if we are about to run either \"choice\"\n * or \"commit\", but \"updatePart1\" has not been run. After\n * \"updatePart1\" has been run the brancher is stable, until the\n * second part of the update is done (in commit).\n *\/\n bool _stable;\n \n \/\/\/ Constructor for cloning \\a b\n LDSBSetBrancher(Space& home, bool share, LDSBSetBrancher& b);\n \/\/\/ Constructor for creation\n LDSBSetBrancher(Home home, \n ViewArray<View>& x,\n ViewSel<View>* vs[n], \n ValSelCommitBase<View,Val>* vsc,\n SymmetryImp<View>** syms, int nsyms,\n SetBranchFilter bf,\n VarValPrint vvp);\n \/\/\/ Return choice\n virtual const Choice* choice(Space& home);\n \/\/\/ Perform commit for choice \\a c and alternative \\a b\n virtual ExecStatus commit(Space& home, const Choice& c, unsigned int b);\n \/\/\/ Perform cloning\n virtual Actor* copy(Space& home, bool share);\n \/\/\/ Brancher post function\n static BrancherHandle post(Home home, \n ViewArray<View>& x,\n ViewSel<View>* vs[n],\n ValSelCommitBase<View,Val>* vsc,\n SymmetryImp<View>** _syms,\n int _nsyms,\n SetBranchFilter bf,\n VarValPrint vvp);\n\n \/**\n * \\brief Part one of the update phase\n *\n * If the branching is at a new variable, restore previously\n * copied value symmetries, do bulk update of values used on left\n * branches for the previous variable, and make fresh copy of\n * resulting value symmetries.\n *\/\n void updatePart1(Space& home, int choicePos);\n };\n\n}}}\n\nnamespace Gecode { namespace Int { namespace LDSB {\n template <>\n ArgArray<Literal>\n VariableSequenceSymmetryImp<Set::SetView>\n ::symmetric(Literal l, const ViewArray<Set::SetView>& x) const;\n}}}\n\n#include <gecode\/set\/ldsb\/brancher.hpp>\n\n#endif\n\n\/\/ STATISTICS: set-branch\n<commit_msg>GCC fixes<commit_after>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\/*\n * Main authors:\n * Christopher Mears <chris.mears@monash.edu>\n *\n * Copyright:\n * Christopher Mears, 2012\n *\n * Last modified:\n * $Date$ by $Author$\n * $Revision$\n *\n * This file is part of Gecode, the generic constraint\n * development environment:\n * http:\/\/www.gecode.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#ifndef __GECODE_SET_LDSB_HH__\n#define __GECODE_SET_LDSB_HH__\n\n#include <gecode\/set.hh>\n#include <gecode\/int\/ldsb.hh>\n\n\/**\n * \\namespace Gecode::Set::LDSB\n * \\brief Symmetry breaking for set variables\n *\/\nnamespace Gecode { namespace Set { namespace LDSB {\n\n using namespace Int::LDSB;\n \n \/**\n * \\brief Symmetry-breaking brancher with generic view and value\n * selection\n *\n * Implements view-based branching for an array of views (of type\n * \\a View) on set variables and value (of type \\a Val).\n *\n *\/\n template<class View, int n, class Val, unsigned int a>\n class LDSBSetBrancher : public LDSBBrancher<View,n,Val,a> {\n public:\n \/\/\/ Function type for printing variable and value selection\n typedef void (*VarValPrint)(const Space& home, unsigned int b,\n typename View::VarType x, int i,\n const Val& m,\n std::ostream& o);\n \/\/\/ Position of previous variable that was branched on\n int _prevPos;\n \/\/\/ Number of non-value symmetries\n int _nNonValueSymmetries;\n \/\/\/ Number of value symmetries\n int _nValueSymmetries;\n \/\/\/ Copy of value symmetries from the first node where the current\n \/\/\/ variable was branched on.\n ValueSymmetryImp<View>** _copiedSyms;\n \/\/\/ Number of copied symmetries\n int _nCopiedSyms;\n \/\/\/ Set of values used on left branches for the current variable\n IntSet _leftBranchValues;\n \/**\n * \\brief Is the state of the brancher \"stable\"?\n * \n * The brancher is unstable if we are about to run either \"choice\"\n * or \"commit\", but \"updatePart1\" has not been run. After\n * \"updatePart1\" has been run the brancher is stable, until the\n * second part of the update is done (in commit).\n *\/\n bool _stable;\n \n \/\/\/ Constructor for cloning \\a b\n LDSBSetBrancher(Space& home, bool share, LDSBSetBrancher& b);\n \/\/\/ Constructor for creation\n LDSBSetBrancher(Home home, \n ViewArray<View>& x,\n ViewSel<View>* vs[n], \n ValSelCommitBase<View,Val>* vsc,\n SymmetryImp<View>** syms, int nsyms,\n SetBranchFilter bf,\n VarValPrint vvp);\n \/\/\/ Return choice\n virtual const Choice* choice(Space& home);\n \/\/\/ Perform commit for choice \\a c and alternative \\a b\n virtual ExecStatus commit(Space& home, const Choice& c, unsigned int b);\n \/\/\/ Perform cloning\n virtual Actor* copy(Space& home, bool share);\n \/\/\/ Brancher post function\n static BrancherHandle post(Home home, \n ViewArray<View>& x,\n ViewSel<View>* vs[n],\n ValSelCommitBase<View,Val>* vsc,\n SymmetryImp<View>** _syms,\n int _nsyms,\n SetBranchFilter bf,\n VarValPrint vvp);\n\n \/**\n * \\brief Part one of the update phase\n *\n * If the branching is at a new variable, restore previously\n * copied value symmetries, do bulk update of values used on left\n * branches for the previous variable, and make fresh copy of\n * resulting value symmetries.\n *\/\n void updatePart1(Space& home, int choicePos);\n };\n\n}}}\n\nnamespace Gecode { namespace Int { namespace LDSB {\n template <>\n ArgArray<Literal>\n VariableSequenceSymmetryImp<Set::SetView>\n ::symmetric(Literal l, const ViewArray<Set::SetView>& x) const;\n}}}\n\n#include <gecode\/set\/ldsb\/brancher.hpp>\n\n#endif\n\n\/\/ STATISTICS: set-branch\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <exception>\n#include <iostream>\n#include <array>\n#include <vector>\n#include \"days.hpp\"\n\nstatic std::vector<int> read_program(std::istream &input) {\n\tstd::vector<int> program{};\n\tfor (int current; input >> current; input.ignore()) {\n\t\tprogram.push_back(current);\n\t}\n\n\treturn program;\n}\n\nstatic int run_program(std::vector<int> &program) {\n\tfor (int ip = 0; ip < program.size(); ip += 4) {\n\t\tswitch (program[ip]) {\n\t\t\tcase 1:\n\t\t\t\tprogram[program[ip + 3]] = program[program[ip + 1]] + program[program[ip + 2]];\n\t\t\t\tbreak;\n\n\t\t\tcase 2:\n\t\t\t\tprogram[program[ip + 3]] = program[program[ip + 1]] * program[program[ip + 2]];\n\t\t\t\tbreak;\n\n\t\t\tcase 99:\n\t\t\t\treturn program[0];\n\n\t\t\tdefault:\n\t\t\t\tchar buffer[30];\n\t\t\t\tstd::snprintf(buffer, sizeof(buffer), \"Invalid opcode: %d\", program[ip]);\n\n\t\t\t\tthrow std::domain_error(buffer);\n\t\t}\n\t}\n\tthrow std::out_of_range(\"Program read out of bounds\");\n}\n\nvoid aoc2019::day02_part1(std::istream &input, std::ostream &output) {\n\tauto program = read_program(input);\n\tprogram[1] = 12;\n\tprogram[2] = 2;\n\toutput << run_program(program) << std::endl;\n}\n\nvoid aoc2019::day02_part2(std::istream &input, std::ostream &output) {\n\tconst auto program = read_program(input);\n\n\tfor (int noun = 0; noun < 100; ++noun) {\n\t\tfor (int verb = 0; verb < 100; ++verb) {\n\t\t\tauto program_copy = program;\n\t\t\tprogram_copy[1] = noun;\n\t\t\tprogram_copy[2] = verb;\n\t\t\tif (run_program(program_copy) == 19690720) {\n\t\t\t\toutput << 100 * noun + verb << std::endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tthrow std::domain_error(\"No valid solution.\");\n}\n<commit_msg>Better use of move and copy constructors.<commit_after>#include <cstdio>\n#include <exception>\n#include <iostream>\n#include <array>\n#include <vector>\n#include \"days.hpp\"\n\nstatic std::vector<int> read_program(std::istream &input) {\n\tstd::vector<int> program{};\n\tfor (int current; input >> current; input.ignore()) {\n\t\tprogram.push_back(current);\n\t}\n\n\treturn program;\n}\n\nstatic int run_program(std::vector<int> program) {\n\tfor (int ip = 0; ip < program.size(); ip += 4) {\n\t\tswitch (program[ip]) {\n\t\t\tcase 1:\n\t\t\t\tprogram[program[ip + 3]] = program[program[ip + 1]] + program[program[ip + 2]];\n\t\t\t\tbreak;\n\n\t\t\tcase 2:\n\t\t\t\tprogram[program[ip + 3]] = program[program[ip + 1]] * program[program[ip + 2]];\n\t\t\t\tbreak;\n\n\t\t\tcase 99:\n\t\t\t\treturn program[0];\n\n\t\t\tdefault:\n\t\t\t\tchar buffer[30];\n\t\t\t\tstd::snprintf(buffer, sizeof(buffer), \"Invalid opcode: %d\", program[ip]);\n\n\t\t\t\tthrow std::domain_error(buffer);\n\t\t}\n\t}\n\tthrow std::out_of_range(\"Program read out of bounds\");\n}\n\nvoid aoc2019::day02_part1(std::istream &input, std::ostream &output) {\n\tauto program = read_program(input);\n\tprogram[1] = 12;\n\tprogram[2] = 2;\n\toutput << run_program(std::move(program)) << std::endl;\n}\n\nvoid aoc2019::day02_part2(std::istream &input, std::ostream &output) {\n\tauto program = read_program(input);\n\n\tfor (int noun = 0; noun < 100; ++noun) {\n\t\tfor (int verb = 0; verb < 100; ++verb) {\n\t\t\tprogram[1] = noun;\n\t\t\tprogram[2] = verb;\n\t\t\tif (run_program(program) == 19690720) {\n\t\t\t\toutput << 100 * noun + verb << std::endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tthrow std::domain_error(\"No valid solution.\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#include \"..\/general\/okina.hpp\"\n\n\/\/ *****************************************************************************\nnamespace mfem\n{\n\n\/\/ *****************************************************************************\n\/\/ * cudaDeviceSetup will set: gpu_count, dev, cuDevice, cuContext & cuStream\n\/\/ *****************************************************************************\nvoid config::CudaDeviceSetup(const int device)\n{\n#ifdef __NVCC__\n cudaGetDeviceCount(&ngpu);\n MFEM_ASSERT(ngpu>0, \"No CUDA device found!\");\n cuInit(0);\n dev = device;\n cuDeviceGet(&cuDevice,dev);\n cuCtxCreate(&cuContext, CU_CTX_SCHED_AUTO, cuDevice);\n cuStream = new CUstream;\n MFEM_ASSERT(cuStream, \"CUDA stream could not be created!\");\n cuStreamCreate(cuStream, CU_STREAM_DEFAULT);\n#else\n MFEM_ABORT(\"CUDA requested but no GPU support has been built!\");\n#endif\n}\n\n\/\/ *****************************************************************************\n\/\/ * RajaDeviceSetup will set: gpu_count, dev, cuDevice, cuContext & cuStream\n\/\/ *****************************************************************************\nvoid config::RajaDeviceSetup(const int device)\n{\n#ifdef __NVCC__\n cudaGetDeviceCount(&ngpu);\n MFEM_ASSERT(ngpu>0, \"No CUDA device found!\");\n cuInit(0);\n dev = device;\n cuDeviceGet(&cuDevice,dev);\n cuCtxCreate(&cuContext, CU_CTX_SCHED_AUTO, cuDevice);\n cuStream = new CUstream;\n MFEM_ASSERT(cuStream, \"CUDA stream could not be created!\");\n cuStreamCreate(cuStream, CU_STREAM_DEFAULT);\n#else\n MFEM_ABORT(\"CUDA requested for RAJA but no GPU support has been built!\");\n#endif\n}\n\n\/\/ *****************************************************************************\n\/\/ * OCCA Settings: device, paths & kernels\n\/\/ *****************************************************************************\nvoid config::OccaDeviceSetup(CUdevice cu_dev, CUcontext cu_ctx)\n{\n#ifdef __OCCA__\n if (cuda)\n {\n occaDevice = occaWrapDevice(cu_dev, cu_ctx);\n }\n else\n {\n occaDevice.setup(\"mode: 'Serial'\");\n }\n const std::string mfem_dir = occa::io::dirname(__FILE__) + \"..\/\";\n occa::io::addLibraryPath(\"fem\", mfem_dir + \"fem\/kernels\");\n occa::io::addLibraryPath(\"general\", mfem_dir + \"general\/kernels\");\n occa::io::addLibraryPath(\"linalg\", mfem_dir + \"linalg\/kernels\");\n occa::io::addLibraryPath(\"mesh\", mfem_dir + \"mesh\/kernels\");\n occa::loadKernels();\n occa::loadKernels(\"fem\");\n occa::loadKernels(\"general\");\n occa::loadKernels(\"linalg\");\n occa::loadKernels(\"mesh\");\n#else\n MFEM_ABORT(\"OCCA requested but no support has been built!\");\n#endif\n}\n\n\/\/ *****************************************************************************\n\/\/ * We initialize CUDA first so OccaDeviceSetup() can reuse\n\/\/ * the same initialized cuDevice and cuContext objects\n\/\/ *****************************************************************************\nvoid config::MfemDeviceSetup(const int dev)\n{\n MFEM_ASSERT(ngpu==-1, \"Only one MfemDeviceSetup allowed\");\n ngpu = 0;\n if (cuda) { CudaDeviceSetup(dev); }\n if (raja) { RajaDeviceSetup(dev); }\n if (occa) { OccaDeviceSetup(cuDevice, cuContext); }\n if (cuda && ngpu==0)\n {\n MFEM_ABORT(\"CUDA requested but no GPU has been initialized!\");\n }\n}\n\n\/\/ *****************************************************************************\n\/\/ * Destructor\n\/\/ *****************************************************************************\nconfig::~config()\n{\n if (raja || cuda) { delete[] cuStream; }\n}\n\n} \/\/ mfem\n<commit_msg>fixed RAJA device setup - no need if a gpu is not being used<commit_after>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#include \"..\/general\/okina.hpp\"\n\n\/\/ *****************************************************************************\nnamespace mfem\n{\n\n\/\/ *****************************************************************************\n\/\/ * cudaDeviceSetup will set: gpu_count, dev, cuDevice, cuContext & cuStream\n\/\/ *****************************************************************************\nvoid config::CudaDeviceSetup(const int device)\n{\n#ifdef __NVCC__\n cudaGetDeviceCount(&ngpu);\n MFEM_ASSERT(ngpu>0, \"No CUDA device found!\");\n cuInit(0);\n dev = device;\n cuDeviceGet(&cuDevice,dev);\n cuCtxCreate(&cuContext, CU_CTX_SCHED_AUTO, cuDevice);\n cuStream = new CUstream;\n MFEM_ASSERT(cuStream, \"CUDA stream could not be created!\");\n cuStreamCreate(cuStream, CU_STREAM_DEFAULT);\n#else\n MFEM_ABORT(\"CUDA requested but no GPU support has been built!\");\n#endif\n}\n\n\/\/ *****************************************************************************\n\/\/ * RajaDeviceSetup will set: gpu_count, dev, cuDevice, cuContext & cuStream\n\/\/ *****************************************************************************\nvoid config::RajaDeviceSetup(const int device)\n{\n#if defined(__NVCC__) && defined(MFEM_USE_RAJA)\n cudaGetDeviceCount(&ngpu);\n MFEM_ASSERT(ngpu>0, \"No CUDA device found!\");\n cuInit(0);\n dev = device;\n cuDeviceGet(&cuDevice,dev);\n cuCtxCreate(&cuContext, CU_CTX_SCHED_AUTO, cuDevice);\n cuStream = new CUstream;\n MFEM_ASSERT(cuStream, \"CUDA stream could not be created!\");\n cuStreamCreate(cuStream, CU_STREAM_DEFAULT);\n#elif !defined(MFEM_USE_RAJA)\n MFEM_ABORT(\"RAJA requested but no RAJA support has been built!\");\n#endif\n}\n\n\/\/ *****************************************************************************\n\/\/ * OCCA Settings: device, paths & kernels\n\/\/ *****************************************************************************\nvoid config::OccaDeviceSetup(CUdevice cu_dev, CUcontext cu_ctx)\n{\n#ifdef __OCCA__\n if (cuda)\n {\n occaDevice = occaWrapDevice(cu_dev, cu_ctx);\n }\n else\n {\n occaDevice.setup(\"mode: 'Serial'\");\n }\n const std::string mfem_dir = occa::io::dirname(__FILE__) + \"..\/\";\n occa::io::addLibraryPath(\"fem\", mfem_dir + \"fem\/kernels\");\n occa::io::addLibraryPath(\"general\", mfem_dir + \"general\/kernels\");\n occa::io::addLibraryPath(\"linalg\", mfem_dir + \"linalg\/kernels\");\n occa::io::addLibraryPath(\"mesh\", mfem_dir + \"mesh\/kernels\");\n occa::loadKernels();\n occa::loadKernels(\"fem\");\n occa::loadKernels(\"general\");\n occa::loadKernels(\"linalg\");\n occa::loadKernels(\"mesh\");\n#else\n MFEM_ABORT(\"OCCA requested but no support has been built!\");\n#endif\n}\n\n\/\/ *****************************************************************************\n\/\/ * We initialize CUDA first so OccaDeviceSetup() can reuse\n\/\/ * the same initialized cuDevice and cuContext objects\n\/\/ *****************************************************************************\nvoid config::MfemDeviceSetup(const int dev)\n{\n MFEM_ASSERT(ngpu==-1, \"Only one MfemDeviceSetup allowed\");\n ngpu = 0;\n if (cuda) { CudaDeviceSetup(dev); }\n if (raja) { RajaDeviceSetup(dev); }\n if (occa) { OccaDeviceSetup(cuDevice, cuContext); }\n if (cuda && ngpu==0)\n {\n MFEM_ABORT(\"CUDA requested but no GPU has been initialized!\");\n }\n}\n\n\/\/ *****************************************************************************\n\/\/ * Destructor\n\/\/ *****************************************************************************\nconfig::~config()\n{\n if (raja || cuda) { delete[] cuStream; }\n}\n\n} \/\/ mfem\n<|endoftext|>"} {"text":"<commit_before>\/\/ ---------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 2004 - 2015 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n\n\/\/ test the various extract_subvector_to functions for\n\/\/ parallel vectors and block vectors\n\n#include \"..\/tests.h\"\n#include <deal.II\/lac\/generic_linear_algebra.h>\n#include <deal.II\/base\/index_set.h>\n#include <deal.II\/lac\/parallel_block_vector.h>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n\n\ntemplate <typename VectorType>\nvoid set (VectorType &vector)\n{\n for (unsigned int i=0; i<vector.size(); ++i)\n if (vector.locally_owned_elements().is_element(i))\n vector(i) = i;\n vector.compress (VectorOperation::insert);\n}\n\n\ntemplate <typename VectorType>\nvoid test (VectorType &vector)\n{\n const unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);\n\n \/\/ select every other element\n std::vector<typename VectorType::size_type> indices;\n for (unsigned int j=0; j<vector.size()\/2; ++j)\n indices.push_back (2*j);\n\n \/\/ do the extraction with the function that takes indices, then\n \/\/ assert correctness\n std::vector<typename VectorType::value_type> values1 (indices.size());\n vector.extract_subvector_to (indices, values1);\n for (unsigned int j=0; j<vector.size()\/2; ++j)\n AssertThrow (values1[j] == 2*j, ExcInternalError());\n\n \/\/ do the same with the version of the function that takes iterators\n std::vector<typename VectorType::value_type> values2 (indices.size());\n vector.extract_subvector_to (indices.begin(),\n indices.end(),\n values2.begin());\n for (unsigned int j=0; j<vector.size()\/2; ++j)\n AssertThrow (values2[j] == 2*j, ExcInternalError());\n\n \/\/ done\n if (myid==0)\n deallog << \"OK\" << std::endl;\n}\n\n\n\nint main (int argc, char **argv)\n{\n Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);\n MPILogInitAll log;\n const unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);\n {\n IndexSet local (10);\n if (myid==0)\n local.add_range(0,5);\n if (myid==1)\n local.add_range(5,10);\n\n IndexSet dense_local (10);\n dense_local.add_range(0,10);\n\n {\n deallog.push(\"deal.II\");\n parallel::distributed::Vector<double> w(local, MPI_COMM_WORLD);\n set (w);\n parallel::distributed::Vector<double> v(local, dense_local, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n {\n deallog.push(\"PETSc\");\n PETScWrappers::MPI::Vector w(local, MPI_COMM_WORLD);\n set (w);\n PETScWrappers::MPI::Vector v(local, dense_local, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n {\n deallog.push(\"Trilinos\");\n TrilinosWrappers::MPI::Vector w(local, MPI_COMM_WORLD);\n set (w);\n TrilinosWrappers::MPI::Vector v(local, dense_local, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n\n std::vector<IndexSet> partitioning;\n {\n IndexSet block1(10);\n if (myid==0)\n block1.add_range(0,7);\n if (myid==1)\n block1.add_range(7,10);\n\n IndexSet block2(6);\n if (myid==0)\n block2.add_range(0,2);\n if (myid==1)\n block2.add_range(2,6);\n\n partitioning.push_back(block1);\n partitioning.push_back(block2);\n }\n\n std::vector<IndexSet> dense_partitioning;\n {\n IndexSet block1(10);\n block1.add_range(0,10);\n\n IndexSet block2(6);\n block2.add_range(0,6);\n\n dense_partitioning.push_back(block1);\n dense_partitioning.push_back(block2);\n }\n\n\n {\n deallog.push(\"deal.II\");\n parallel::distributed::BlockVector<double> w(partitioning, MPI_COMM_WORLD);\n set (w);\n parallel::distributed::BlockVector<double> v(partitioning, dense_partitioning, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n {\n deallog.push(\"PETSc\");\n PETScWrappers::MPI::BlockVector w(partitioning, MPI_COMM_WORLD);\n set (w);\n PETScWrappers::MPI::BlockVector v(partitioning, dense_partitioning, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n {\n deallog.push(\"Trilinos\");\n TrilinosWrappers::MPI::BlockVector w(partitioning, MPI_COMM_WORLD);\n set (w);\n TrilinosWrappers::MPI::BlockVector v(partitioning, dense_partitioning, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n }\n\n}\n<commit_msg>extend gla\/extract_subvector_to_parallel to complex-valued PETSc<commit_after>\/\/ ---------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 2004 - 2015 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n\n\/\/ test the various extract_subvector_to functions for\n\/\/ parallel vectors and block vectors\n\n#include \"..\/tests.h\"\n#include <deal.II\/lac\/generic_linear_algebra.h>\n#include <deal.II\/base\/index_set.h>\n#include <deal.II\/lac\/parallel_block_vector.h>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n\n\ntemplate <typename VectorType>\nvoid set (VectorType &vector)\n{\n for (unsigned int i=0; i<vector.size(); ++i)\n if (vector.locally_owned_elements().is_element(i))\n vector(i) = i;\n vector.compress (VectorOperation::insert);\n}\n\n\ntemplate <typename VectorType>\nvoid test (VectorType &vector)\n{\n const unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);\n\n \/\/ select every other element\n std::vector<typename VectorType::size_type> indices;\n for (unsigned int j=0; j<vector.size()\/2; ++j)\n indices.push_back (2*j);\n\n \/\/ do the extraction with the function that takes indices, then\n \/\/ assert correctness\n std::vector<typename VectorType::value_type> values1 (indices.size());\n vector.extract_subvector_to (indices, values1);\n for (unsigned int j=0; j<vector.size()\/2; ++j)\n AssertThrow (get_real_assert_zero_imag(values1[j]) == 2*j, ExcInternalError());\n\n \/\/ do the same with the version of the function that takes iterators\n std::vector<typename VectorType::value_type> values2 (indices.size());\n vector.extract_subvector_to (indices.begin(),\n indices.end(),\n values2.begin());\n for (unsigned int j=0; j<vector.size()\/2; ++j)\n AssertThrow (get_real_assert_zero_imag(values2[j]) == 2*j, ExcInternalError());\n\n \/\/ done\n if (myid==0)\n deallog << \"OK\" << std::endl;\n}\n\n\n\nint main (int argc, char **argv)\n{\n Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);\n MPILogInitAll log;\n const unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);\n {\n IndexSet local (10);\n if (myid==0)\n local.add_range(0,5);\n if (myid==1)\n local.add_range(5,10);\n\n IndexSet dense_local (10);\n dense_local.add_range(0,10);\n\n {\n deallog.push(\"deal.II\");\n parallel::distributed::Vector<double> w(local, MPI_COMM_WORLD);\n set (w);\n parallel::distributed::Vector<double> v(local, dense_local, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n {\n deallog.push(\"PETSc\");\n PETScWrappers::MPI::Vector w(local, MPI_COMM_WORLD);\n set (w);\n PETScWrappers::MPI::Vector v(local, dense_local, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n {\n deallog.push(\"Trilinos\");\n TrilinosWrappers::MPI::Vector w(local, MPI_COMM_WORLD);\n set (w);\n TrilinosWrappers::MPI::Vector v(local, dense_local, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n\n std::vector<IndexSet> partitioning;\n {\n IndexSet block1(10);\n if (myid==0)\n block1.add_range(0,7);\n if (myid==1)\n block1.add_range(7,10);\n\n IndexSet block2(6);\n if (myid==0)\n block2.add_range(0,2);\n if (myid==1)\n block2.add_range(2,6);\n\n partitioning.push_back(block1);\n partitioning.push_back(block2);\n }\n\n std::vector<IndexSet> dense_partitioning;\n {\n IndexSet block1(10);\n block1.add_range(0,10);\n\n IndexSet block2(6);\n block2.add_range(0,6);\n\n dense_partitioning.push_back(block1);\n dense_partitioning.push_back(block2);\n }\n\n\n {\n deallog.push(\"deal.II\");\n parallel::distributed::BlockVector<double> w(partitioning, MPI_COMM_WORLD);\n set (w);\n parallel::distributed::BlockVector<double> v(partitioning, dense_partitioning, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n {\n deallog.push(\"PETSc\");\n PETScWrappers::MPI::BlockVector w(partitioning, MPI_COMM_WORLD);\n set (w);\n PETScWrappers::MPI::BlockVector v(partitioning, dense_partitioning, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n {\n deallog.push(\"Trilinos\");\n TrilinosWrappers::MPI::BlockVector w(partitioning, MPI_COMM_WORLD);\n set (w);\n TrilinosWrappers::MPI::BlockVector v(partitioning, dense_partitioning, MPI_COMM_WORLD);\n v = w; \/\/ get copy of vector including ghost elements\n test (v);\n deallog.pop();\n }\n\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Program WinMenu.cpp\n\/\/ COMP 3980, Final Project\n\/\/ Tim Makimov, A009031109\n\n#define STRICT\n\n#include <stdio.h>\n\n#include \"Command.h\"\n#include \"Connect.h\"\n\n#pragma warning (disable: 4096)\n#pragma comment(linker,\"\\\"\/manifestdependency:type='win32' \\\nname='Microsoft.Windows.Common-Controls' version='6.0.0.0' \\\nprocessorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n\n\n\nint WINAPI WinMain(HINSTANCE hInst, HINSTANCE hprevInstance,\n\tLPSTR lspszCmdParam, int nCmdShow)\n{\n\tMSG Msg;\n\thInstance = hInst;\n\tgenerateViews(hInst, nCmdShow);\n\twhile (GetMessage(&Msg, NULL, 0, 0))\n\t{\n\t\tTranslateMessage(&Msg);\n\t\tDispatchMessage(&Msg);\n\t}\n\treturn Msg.wParam;\n}\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT Message,\n\tWPARAM wParam, LPARAM lParam)\n{\n\tHDC hdc = NULL;\n\tPAINTSTRUCT paintstruct;\n\n\t\/\/availableCOM(hwnd);\n\n\tswitch (Message)\n\t{\n\tcase WM_COMMAND:\n\n\t\tif ((HWND)lParam == hConnectButton)\n\t\t{\n\t\t\tstartConnnection(comPort, hwnd);\n\t\t\tEnableWindow(hConnectButton, false);\n\t\t\tEnableWindow(hDisconnectButton, true);\n\t\t\t\/\/connect(hComm, comPort, connected);\n\t\t\tbreak;\n\t\t}\n\t\tif ((HWND)lParam == hDisconnectButton)\n\t\t{\n\t\t\tstopConnnection();\n\t\t\tEnableWindow(hConnectButton, true);\n\t\t\tEnableWindow(hDisconnectButton, false);\n\t\t\t\/\/disconnect(hComm, connected, comPort);\n\t\t\tbreak;\n\t\t}\n\t\tif ((HWND)lParam == browseButton)\n\t\t{\n\t\t\tattach();\n\t\t\tbreak;\n\t\t}\n\t\tswitch (LOWORD(wParam))\n\t\t{\n\t\tcase IDM_NEWCONNECT:\n\t\t\tDialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc); \/\/ a dialog for the list of available com port.\n\t\t\tbreak;\n\n\t\tcase IDM_PROPERTIES: \/\/ popup a dialog for changing the properties of selected com port.\n\t\t\t\/\/selectCommPort(hComm, comPort, hwnd, connected);\n\t\t\tbreak;\n\n\t\tcase IDM_HELP:\n\t\t\tMessageBox(NULL, \n\t\t\t\t\t\"Click CONNECT to connect to the default COMM port or select a COMM port from settings and then click CONNECT.\", \n\t\t\t\t\t\"\", MB_OK);\n\t\t\tbreak;\n\t\tcase IDM_Exit:\n\t\t\tPostQuitMessage(0);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase WM_CHAR:\t\/\/ Process keystroke\n\t\tif (wParam == 27)\n\t\t{\n\t\t\t\/\/disconnect(hComm, connected, lpszCommName);\n\t\t}\n\t\tbreak;\n\n\tcase WM_PAINT:\t\t\/\/ Process a repaint message\n\t\thdc = BeginPaint(hwnd, &paintstruct); \/\/ Acquire DC\n\t\tTextOut(hdc, 0, 0, str, strlen(str)); \/\/ output character\n\t\tEndPaint(hwnd, &paintstruct); \/\/ Release DC\n\t\tbreak;\n\n\tcase WM_DESTROY:\t\/\/ Terminate program\n\t\tPostQuitMessage(0);\n\t\tbreak;\n\tdefault:\n\t\treturn DefWindowProc(hwnd, Message, wParam, lParam);\n\t}\n\treturn 0;\n}\n\nvoid generateViews(HINSTANCE hInst, int nCmdShow)\n{\n\tHWND hwnd;\n\tWNDCLASSEX Wcl;\n\n\tWcl.cbSize = sizeof(WNDCLASSEX);\n\tWcl.style = CS_HREDRAW | CS_VREDRAW;\n\tWcl.hIcon = LoadIcon(NULL, IDI_APPLICATION); \/\/ large icon \n\tWcl.hIconSm = NULL; \/\/ use small version of large icon\n\tWcl.hCursor = LoadCursor(NULL, IDC_ARROW); \/\/ cursor style\n\n\tWcl.lpfnWndProc = WndProc;\n\tWcl.hInstance = hInst;\n\tWcl.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); \/\/white background\n\tWcl.lpszClassName = Name;\n\n\tWcl.lpszMenuName = \"MYMENU\"; \/\/ The menu Class\n\tWcl.cbClsExtra = 0; \/\/ no extra memory needed\n\tWcl.cbWndExtra = 0;\n\n\tif (!RegisterClassEx(&Wcl))\n\t\treturn;\n\n\thwnd = CreateWindow(Name, \n\t\t\t\t\t\tName, \n\t\t\t\t\t\tWS_OVERLAPPEDWINDOW ^ WS_THICKFRAME,\t\t\t\n\t\t\t\t\t\tCW_USEDEFAULT, CW_USEDEFAULT,\n\t\t\t\t\t\tWIN_WIDTH, WIN_LENGTH,\n\t\t\t\t\t\tNULL, \/\/parent of window\n\t\t\t\t\t\tNULL, \/\/menu bar\n\t\t\t\t\t\thInst, \/\/ first aparam in WinMain\n\t\t\t\t\t\tNULL);\n\t\n\tShowWindow(hwnd, nCmdShow);\n\tUpdateWindow(hwnd);\n\tcreateUIWindows(hwnd);\n\tDialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc); \/\/ a dialog for the list of available com port.\n}\n\n\/\/void selectCommPort(HANDLE hComm, LPCSTR lpszCommName, HWND hwnd, bool &connected)\n\/\/{\n\/\/\tCOMMCONFIG\tcc;\n\/\/\tcc.dwSize = sizeof(COMMCONFIG);\n\/\/\tcc.wVersion = 0x100;\n\/\/\tGetCommConfig(hComm, &cc, &cc.dwSize);\n\/\/\tif (!CommConfigDialog(lpszCommName, hwnd, &cc))\n\/\/\t{\n\/\/\t\tMessageBox(NULL, \"Error connecting to COMM port\", lpszCommName, MB_OK);\n\/\/\t\treturn;\n\/\/\t}\n\/\/\telse\n\/\/\t{\n\/\/\t\t\/\/connect(hComm, lpszCommName, connected);\n\/\/\t}\n\/\/\tif ((SetCommState(hComm, &cc.dcb)) == FALSE)\n\/\/\t{\n\/\/\t\treturn;\n\/\/\t}\n\/\/}\n\n\n\/\/void connect(HANDLE &commPort, LPCSTR CommName, bool &connection)\n\/\/{\n\/\/\tif (connection == false)\n\/\/\t{\n\/\/\t\t\/\/if startConnection = false\n\/\/\t\tif ((commPort = CreateFile(CommName, GENERIC_READ | GENERIC_WRITE, 0,\n\/\/\t\t\tNULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL))\n\/\/\t\t\t== INVALID_HANDLE_VALUE)\n\/\/\t\t{\n\/\/\t\t\tMessageBox(NULL, \"Error opening COM port\", CommName, MB_OK);\n\/\/\t\t\t\/\/invoke HANDLE CONNECTION ERRORS\n\/\/\t\t}\n\/\/\t\telse\n\/\/\t\t{\n\/\/\t\t\tMessageBox(NULL, \"Conected to port\", CommName, MB_OK);\n\/\/\t\t\tconnection = true;\n\/\/\t\t\tEnableWindow(hConnectButton, !connection);\n\/\/\t\t\tEnableWindow(hDisconnectButton, connection);\n\/\/\t\t}\n\/\/\t}\n\/\/\telse\n\/\/\t{\n\/\/\t\treturn;\n\/\/\t}\n\/\/}\n\n\n\/\/\n\n\nvoid createUIWindows(HWND hwnd)\n{\n\tuserInputTextBox = CreateWindow(\"STATIC\",\n\t\tNULL,\n\t\tWS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED,\n\t\tUSERINPUT_TEXTBOX_START_X,\n\t\tUSERINPUT_TEXTBOX_START_Y,\n\t\tTEXTBOX_WIDTH,\n\t\tTEXTBOX_HEIGTH,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\treadInputTextBox = CreateWindow(\n\t\t\"STATIC\",\n\t\tNULL,\n\t\tWS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED, \n\t\tREADINPUT_TEXTBOX_START_X,\n\t\tREADINPUT_TEXTBOX_START_Y,\n\t\tTEXTBOX_WIDTH,\n\t\tTEXTBOX_HEIGTH,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\tstatsTextBox = CreateWindow(\n\t\t\"STATIC\",\n\t\tNULL,\n\t\tWS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED,\n\t\tSTATS_TEXTBOX_START_X,\n\t\tSTATS_TEXTBOX_START_Y,\n\t\t60,\n\t\tTEXTBOX_HEIGTH,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\thConnectButton = CreateWindow(\n\t\t\"BUTTON\",\n\t\t\"CONNECT\",\n\t\tWS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,\n\t\tCONNECT_BUTTON_X,\n\t\tCONNECT_BUTTON_Y,\n\t\tBUTTON_WIDTH,\n\t\tBUTTON_HEIGHT,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\thDisconnectButton = CreateWindow(\n\t\t\"BUTTON\",\n\t\t\"DISCONNECT\",\n\t\tWS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | WS_DISABLED,\n\t\tDISCONNECT_BUTTON_X,\n\t\tDISCONNECT_BUTTON_Y,\n\t\tBUTTON_WIDTH,\n\t\tBUTTON_HEIGHT,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\tbrowseButton = CreateWindow(\n\t\t\"BUTTON\",\n\t\t\"ATTACH\",\n\t\tWS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,\n\t\tATTACH_BUTTON_X,\n\t\tATTACH_BUTTON_Y,\n\t\tBUTTON_WIDTH,\n\t\tBUTTON_HEIGHT,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n}\n\n\nvoid attach()\n{\n\t\/\/ open a file name\n\tZeroMemory(&ofn, sizeof(ofn));\n\tofn.lStructSize = sizeof(ofn);\n\tofn.hwndOwner = NULL;\n\tofn.lpstrFile = szFile;\n\tofn.lpstrFile[0] = '\\0';\n\tofn.nMaxFile = sizeof(szFile);\n\tofn.lpstrFilter = \"All\\0*.*\\0Text\\0*.TXT\\0\";\n\tofn.nFilterIndex = 1;\n\tofn.lpstrFileTitle = NULL;\n\tofn.nMaxFileTitle = 0;\n\tofn.lpstrInitialDir = NULL;\n\tofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;\n\n\tif (GetOpenFileName(&ofn))\n\t{\n\t\tfilePath = ofn.lpstrFile;\n\t\t\n\t\t\/\/ Now simply display the file name \n\t\tMessageBox(NULL, filePath, \"File Name\", MB_OK);\n\t}\n}\n\nvoid availableCOM(HWND hwnd) {\n\tTCHAR szDevices[65535];\n\tunsigned long dwChars = QueryDosDevice(NULL, szDevices, 65535); \/\/ get all available devices.\n\tTCHAR *ptr = szDevices;\n\n\twhile (dwChars)\n\t{\n\t\tint port;\n\t\tif (sscanf_s(ptr, \"COM%d\", &port) == 1 || sscanf_s(ptr, \"\\\\\\\\.\\\\COM%d\", &port) == 1) \/\/ if the availbel device name begins with COM,\n\t\t{\n\t\t\tSendDlgItemMessage(hwnd, IDM_COM_COMBOBOX, CB_ADDSTRING, 0, (LPARAM)ptr); \/\/ populates the combobox with the device name.\n\t\t}\n\t\tTCHAR *temp_ptr = strchr(ptr, 0);\n\t\tdwChars -= (DWORD)((temp_ptr - ptr) \/ sizeof(TCHAR) + 1);\n\t\tptr = temp_ptr + 1; \/\/ point to next device.\n\t}\n\tSendDlgItemMessage(hwnd, IDM_COM_COMBOBOX, CB_SETCURSEL, (WPARAM)0, 0L); \/\/ set focus on the first item in the list.\n}\n\n\nINT_PTR CALLBACK comDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {\n\tswitch (message) {\n\tcase WM_INITDIALOG:\n\t\tavailableCOM(hDlg); \/\/ Check the list of available com ports and populate the combobox with it.\n\t\tbreak;\n\n\tcase WM_COMMAND:\n\t\tswitch (wParam) {\n\t\tcase IDM_CANCEL:\n\t\t\tEndDialog(hDlg, 0); \/\/ close dialog\n\t\t\treturn TRUE;\n\t\tcase IDM_OK:\n\t\t\tGetDlgItemText(hDlg, IDM_COM_COMBOBOX, comPort, sizeof(comPort)); \/\/ get selected port name from the list.\n\t\t\t\/\/session.initilize(comPort); \/\/ initilize the session for the selected com port.\n\t\t\tEndDialog(hDlg, 0); \/\/ close dialog\n\t\t\treturn TRUE;\n\t\t}\n\t\tbreak;\n\n\tcase WM_SETFOCUS:\n\t\treturn TRUE;\n\t}\n\treturn FALSE;\n}\n\n\/\/void selectComport() {\n\/\/\tDialogBox(hInst, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc); \/\/ a dialog for the list of available com port.\n\/\/}<commit_msg>TM: modified constants<commit_after>\/\/ Program WinMenu.cpp\n\/\/ COMP 3980, Final Project\n\/\/ Tim Makimov, A009031109\n\n#define STRICT\n\n#include <stdio.h>\n\n#include \"Command.h\"\n#pragma warning (disable: 4096)\n#pragma comment(linker,\"\\\"\/manifestdependency:type='win32' \\\nname='Microsoft.Windows.Common-Controls' version='6.0.0.0' \\\nprocessorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n\n\n\nint WINAPI WinMain(HINSTANCE hInst, HINSTANCE hprevInstance,\n\tLPSTR lspszCmdParam, int nCmdShow)\n{\n\tMSG Msg;\n\thInstance = hInst;\n\tgenerateViews(hInst, nCmdShow);\n\twhile (GetMessage(&Msg, NULL, 0, 0))\n\t{\n\t\tTranslateMessage(&Msg);\n\t\tDispatchMessage(&Msg);\n\t}\n\treturn Msg.wParam;\n}\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT Message,\n\tWPARAM wParam, LPARAM lParam)\n{\n\tHDC hdc = NULL;\n\tPAINTSTRUCT paintstruct;\n\n\tswitch (Message)\n\t{\n\tcase WM_COMMAND:\n\n\t\tif ((HWND)lParam == hConnectButton)\n\t\t{\n\t\t\tif (comPort[0] == 0)\n\t\t\t{\n\t\t\t\tDialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc);\n\t\t\t\tstartConnnection(comPort, hwnd);\n\t\t\t\tEnableWindow(hConnectButton, isConnected);\n\t\t\t\tEnableWindow(hDisconnectButton, !isConnected);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstartConnnection(comPort, hwnd);\n\t\t\t\tEnableWindow(hConnectButton, isConnected);\n\t\t\t\tEnableWindow(hDisconnectButton, !isConnected);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif ((HWND)lParam == hDisconnectButton)\n\t\t{\n\t\t\tstopConnnection();\n\t\t\tEnableWindow(hConnectButton, !isConnected);\n\t\t\tEnableWindow(hDisconnectButton, isConnected);\n\t\t\tbreak;\n\t\t}\n\t\tif ((HWND)lParam == browseButton)\n\t\t{\n\t\t\tattach();\n\t\t\tbreak;\n\t\t}\n\t\tswitch (LOWORD(wParam))\n\t\t{\n\t\tcase IDM_NEWCONNECT:\n\t\t\tDialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc); \/\/ a dialog for the list of available com port.\n\t\t\tbreak;\n\n\t\tcase IDM_PROPERTIES: \/\/ popup a dialog for changing the properties of selected com port.\n\t\t\tselectCommPort(hComm, comPort, hwnd, isConnected);\n\t\t\tbreak;\n\n\t\tcase IDM_HELP:\n\t\t\tMessageBox(NULL, \n\t\t\t\t\t\"Click CONNECT to connect to the default COMM port or select a COMM port from settings and then click CONNECT.\", \n\t\t\t\t\t\"\", MB_OK);\n\t\t\tbreak;\n\t\tcase IDM_Exit:\n\t\t\tPostQuitMessage(0);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase WM_CHAR:\t\/\/ Process keystroke\n\t\tif (wParam == 27)\n\t\t{\n\t\t\tstopConnnection();\n\t\t\tEnableWindow(hConnectButton, !isConnected);\n\t\t\tEnableWindow(hDisconnectButton, isConnected);\n\t\t}\n\t\tbreak;\n\n\tcase WM_PAINT:\t\t\/\/ Process a repaint message\n\t\thdc = BeginPaint(hwnd, &paintstruct); \/\/ Acquire DC\n\t\tTextOut(hdc, 0, 0, str, strlen(str)); \/\/ output character\n\t\tEndPaint(hwnd, &paintstruct); \/\/ Release DC\n\t\tbreak;\n\n\tcase WM_DESTROY:\t\/\/ Terminate program\n\t\tPostQuitMessage(0);\n\t\tbreak;\n\tdefault:\n\t\treturn DefWindowProc(hwnd, Message, wParam, lParam);\n\t}\n\treturn 0;\n}\n\nvoid generateViews(HINSTANCE hInst, int nCmdShow)\n{\n\tHWND hwnd;\n\tWNDCLASSEX Wcl;\n\n\tWcl.cbSize = sizeof(WNDCLASSEX);\n\tWcl.style = CS_HREDRAW | CS_VREDRAW;\n\tWcl.hIcon = LoadIcon(NULL, IDI_APPLICATION); \/\/ large icon \n\tWcl.hIconSm = NULL; \/\/ use small version of large icon\n\tWcl.hCursor = LoadCursor(NULL, IDC_ARROW); \/\/ cursor style\n\n\tWcl.lpfnWndProc = WndProc;\n\tWcl.hInstance = hInst;\n\tWcl.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); \/\/white background\n\tWcl.lpszClassName = Name;\n\n\tWcl.lpszMenuName = \"MYMENU\"; \/\/ The menu Class\n\tWcl.cbClsExtra = 0; \/\/ no extra memory needed\n\tWcl.cbWndExtra = 0;\n\n\tif (!RegisterClassEx(&Wcl))\n\t\treturn;\n\n\thwnd = CreateWindow(Name, \n\t\t\t\t\t\tName, \n\t\t\t\t\t\tWS_OVERLAPPEDWINDOW ^ WS_THICKFRAME,\t\t\t\n\t\t\t\t\t\tCW_USEDEFAULT, CW_USEDEFAULT,\n\t\t\t\t\t\tWIN_WIDTH, WIN_LENGTH,\n\t\t\t\t\t\tNULL, \/\/parent of window\n\t\t\t\t\t\tNULL, \/\/menu bar\n\t\t\t\t\t\thInst, \/\/ first aparam in WinMain\n\t\t\t\t\t\tNULL);\n\t\n\tShowWindow(hwnd, nCmdShow);\n\tUpdateWindow(hwnd);\n\tcreateUIWindows(hwnd);\n\tDialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc); \/\/ a dialog for the list of available com port.\n}\n\nvoid selectCommPort(HANDLE hComm, LPCSTR lpszCommName, HWND hwnd, bool &connected)\n{\n\tCOMMCONFIG\tcc;\n\tcc.dwSize = sizeof(COMMCONFIG);\n\tcc.wVersion = 0x100;\n\tGetCommConfig(hComm, &cc, &cc.dwSize);\n\tif (!CommConfigDialog(lpszCommName, hwnd, &cc))\n\t{\n\t\tMessageBox(NULL, \"Error connecting to COMM port\", lpszCommName, MB_OK);\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tstartConnnection(comPort, hwnd);\n\t}\n\tif ((SetCommState(hComm, &cc.dcb)) == FALSE)\n\t{\n\t\treturn;\n\t}\n}\n\n\nvoid createUIWindows(HWND hwnd)\n{\n\tuserInputTextBox = CreateWindow(\"STATIC\",\n\t\tNULL,\n\t\tWS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED,\n\t\tUSERINPUT_TEXTBOX_START_X,\n\t\tUSERINPUT_TEXTBOX_START_Y,\n\t\tTEXTBOX_WIDTH,\n\t\tTEXTBOX_HEIGTH,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\treadInputTextBox = CreateWindow(\n\t\t\"STATIC\",\n\t\tNULL,\n\t\tWS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED, \n\t\tREADINPUT_TEXTBOX_START_X,\n\t\tREADINPUT_TEXTBOX_START_Y,\n\t\tTEXTBOX_WIDTH,\n\t\tTEXTBOX_HEIGTH,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\t\/\/add brush http:\/\/stackoverflow.com\/questions\/10063604\/after-createwindow-how-to-give-the-window-a-color\n\tstatsTextBox = CreateWindow(\n\t\t\"EDIT\",\n\t\tNULL,\n\t\tWS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED,\n\t\tSTATS_TEXTBOX_START_X,\n\t\tSTATS_TEXTBOX_START_Y,\n\t\t210,\n\t\tTEXTBOX_HEIGTH,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\n\thConnectButton = CreateWindow(\n\t\t\"BUTTON\",\n\t\t\"CONNECT\",\n\t\tWS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,\n\t\tCONNECT_BUTTON_X,\n\t\tCONNECT_BUTTON_Y,\n\t\tBUTTON_WIDTH,\n\t\tBUTTON_HEIGHT,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\thDisconnectButton = CreateWindow(\n\t\t\"BUTTON\",\n\t\t\"DISCONNECT\",\n\t\tWS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | WS_DISABLED,\n\t\tDISCONNECT_BUTTON_X,\n\t\tDISCONNECT_BUTTON_Y,\n\t\tBUTTON_WIDTH,\n\t\tBUTTON_HEIGHT,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\tbrowseButton = CreateWindow(\n\t\t\"BUTTON\",\n\t\t\"ATTACH\",\n\t\tWS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,\n\t\tATTACH_BUTTON_X,\n\t\tATTACH_BUTTON_Y,\n\t\tBUTTON_WIDTH,\n\t\tBUTTON_HEIGHT,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\n\t\/\/Change these to static final \n\tint x, w, y, h;\n\ty = 200; h = 20;\n\tx = 0; w = 50;\n\t\n\tx += w; w = 60;\n\tlabel2 = CreateWindow(\n\t\t\"edit\",\n\t\tNULL,\n\t\tWS_CHILD | WS_VISIBLE | WS_TABSTOP,\n\t\tx,\n\t\ty,\n\t\tw,\n\t\th,\n\t\thwnd,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL\n\t);\n\t\t\n\tSetWindowText(label2, \"STATS:\");\n\n}\n\n\nvoid attach()\n{\n\t\/\/ open a file name\n\tZeroMemory(&ofn, sizeof(ofn));\n\tofn.lStructSize = sizeof(ofn);\n\tofn.hwndOwner = NULL;\n\tofn.lpstrFile = szFile;\n\tofn.lpstrFile[0] = '\\0';\n\tofn.nMaxFile = sizeof(szFile);\n\tofn.lpstrFilter = \"All\\0*.*\\0Text\\0*.TXT\\0\";\n\tofn.nFilterIndex = 1;\n\tofn.lpstrFileTitle = NULL;\n\tofn.nMaxFileTitle = 0;\n\tofn.lpstrInitialDir = NULL;\n\tofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;\n\n\tif (GetOpenFileName(&ofn))\n\t{\n\t\tfilePath = ofn.lpstrFile;\n\t\t\n\t\t\/\/ Now simply display the file name \n\t\tMessageBox(NULL, filePath, \"File Name\", MB_OK);\n\t}\n}\n\nvoid availableCOM(HWND hwnd) {\n\tTCHAR szDevices[65535];\n\tunsigned long dwChars = QueryDosDevice(NULL, szDevices, 65535); \/\/ get all available devices.\n\tTCHAR *ptr = szDevices;\n\n\twhile (dwChars)\n\t{\n\t\tint port;\n\t\tif (sscanf_s(ptr, \"COM%d\", &port) == 1 || sscanf_s(ptr, \"\\\\\\\\.\\\\COM%d\", &port) == 1) \/\/ if the availbel device name begins with COM,\n\t\t{\n\t\t\tSendDlgItemMessage(hwnd, IDM_COM_COMBOBOX, CB_ADDSTRING, 0, (LPARAM)ptr); \/\/ populates the combobox with the device name.\n\t\t}\n\t\tTCHAR *temp_ptr = strchr(ptr, 0);\n\t\tdwChars -= (DWORD)((temp_ptr - ptr) \/ sizeof(TCHAR) + 1);\n\t\tptr = temp_ptr + 1; \/\/ point to next device.\n\t}\n\tSendDlgItemMessage(hwnd, IDM_COM_COMBOBOX, CB_SETCURSEL, (WPARAM)0, 0L); \/\/ set focus on the first item in the list.\n}\n\n\nINT_PTR CALLBACK comDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {\n\tswitch (message) {\n\tcase WM_INITDIALOG:\n\t\tavailableCOM(hDlg); \/\/ Check the list of available com ports and populate the combobox with it.\n\t\tbreak;\n\n\tcase WM_COMMAND:\n\t\tswitch (wParam) {\n\t\tcase IDM_CANCEL:\n\t\t\tEndDialog(hDlg, 0); \/\/ close dialog\n\t\t\treturn TRUE;\n\t\tcase IDM_OK:\n\t\t\tGetDlgItemText(hDlg, IDM_COM_COMBOBOX, comPort, sizeof(comPort)); \/\/ get selected port name from the list.\n\t\t\t\/\/session.initilize(comPort); \/\/ initilize the session for the selected com port.\n\t\t\tEndDialog(hDlg, 0); \/\/ close dialog\n\t\t\treturn TRUE;\n\t\t}\n\t\tbreak;\n\n\tcase WM_SETFOCUS:\n\t\treturn TRUE;\n\t}\n\treturn FALSE;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Made text widget edit field resize when dialog is resized<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: cursor.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2003-12-01 13:32:38 $\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#define _SV_CURSOR_CXX\n\n#ifndef _SV_SVAPP_HXX\n#include <svapp.hxx>\n#endif\n#ifndef _SV_TIMER_HXX\n#include <timer.hxx>\n#endif\n#ifndef _SV_SETTINGS_HXX\n#include <settings.hxx>\n#endif\n#ifndef _SV_WINDOW_HXX\n#include <window.hxx>\n#endif\n#ifndef _SV_WINDOW_H\n#include <window.h>\n#endif\n#ifndef _SV_POLY_HXX\n#include <poly.hxx>\n#endif\n#ifndef _SV_CURSOR_HXX\n#include <cursor.hxx>\n#endif\n\n\n\/\/ =======================================================================\n\nstruct ImplCursorData\n{\n AutoTimer maTimer; \/\/ Timer\n Point maPixPos; \/\/ Pixel-Position\n Point maPixRotOff; \/\/ Pixel-Offset-Position\n Size maPixSize; \/\/ Pixel-Size\n long mnPixSlant; \/\/ Pixel-Slant\n short mnOrientation; \/\/ Pixel-Orientation\n unsigned char mnDirection; \/\/ indicates writing direction\n USHORT mnStyle; \/\/ Cursor-Style\n BOOL mbCurVisible; \/\/ Ist Cursor aktuell sichtbar\n Window* mpWindow; \/\/ Zugeordnetes Windows\n};\n\n\/\/ =======================================================================\n\nstatic void ImplCursorInvert( ImplCursorData* pData )\n{\n Window* pWindow = pData->mpWindow;\n BOOL bMapMode = pWindow->IsMapModeEnabled();\n pWindow->EnableMapMode( FALSE );\n USHORT nInvertStyle;\n if ( pData->mnStyle & CURSOR_SHADOW )\n nInvertStyle = INVERT_50;\n else\n nInvertStyle = 0;\n\n Rectangle aRect( pData->maPixPos, pData->maPixSize );\n if ( pData->mnDirection || pData->mnOrientation || pData->mnPixSlant )\n {\n Polygon aPoly( aRect );\n if( aPoly.GetSize() == 5 )\n {\n aPoly[1].X() += 1; \/\/ include the right border\n aPoly[2].X() += 1;\n if ( pData->mnPixSlant )\n {\n Point aPoint = aPoly.GetPoint( 0 );\n aPoint.X() += pData->mnPixSlant;\n aPoly.SetPoint( aPoint, 0 );\n aPoly.SetPoint( aPoint, 4 );\n aPoint = aPoly.GetPoint( 1 );\n aPoint.X() += pData->mnPixSlant;\n aPoly.SetPoint( aPoint, 1 );\n }\n\n \/\/ apply direction flag after slant to use the correct shape\n if ( pData->mnDirection )\n {\n Point pAry[7];\n int delta = 3*aRect.getWidth()+1;\n if( pData->mnDirection == CURSOR_DIRECTION_LTR )\n {\n \/\/ left-to-right\n pAry[0] = aPoly.GetPoint( 0 );\n pAry[1] = aPoly.GetPoint( 1 );\n pAry[2] = pAry[1];\n pAry[2].X() += delta;\n pAry[3] = pAry[1];\n pAry[3].Y() += delta;\n pAry[4] = aPoly.GetPoint( 2 );\n pAry[5] = aPoly.GetPoint( 3 );\n pAry[6] = aPoly.GetPoint( 4 );\n }\n else if( pData->mnDirection == CURSOR_DIRECTION_RTL )\n {\n \/\/ right-to-left\n pAry[0] = aPoly.GetPoint( 0 );\n pAry[1] = aPoly.GetPoint( 1 );\n pAry[2] = aPoly.GetPoint( 2 );\n pAry[3] = aPoly.GetPoint( 3 );\n pAry[4] = pAry[0];\n pAry[4].Y() += delta;\n pAry[5] = pAry[0];\n pAry[5].X() -= delta;\n pAry[6] = aPoly.GetPoint( 4 );\n }\n aPoly = Polygon( 7, pAry);\n }\n\n if ( pData->mnOrientation )\n aPoly.Rotate( pData->maPixRotOff, pData->mnOrientation );\n pWindow->Invert( aPoly, nInvertStyle );\n }\n }\n else\n pWindow->Invert( aRect, nInvertStyle );\n pWindow->EnableMapMode( bMapMode );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplDraw()\n{\n if ( mpData && mpData->mpWindow && !mpData->mbCurVisible )\n {\n Window* pWindow = mpData->mpWindow;\n mpData->maPixPos = pWindow->LogicToPixel( maPos );\n mpData->maPixSize = pWindow->LogicToPixel( maSize );\n mpData->mnPixSlant = pWindow->LogicToPixel( Size( mnSlant, 0 ) ).Width();\n mpData->mnOrientation = mnOrientation;\n mpData->mnDirection = mnDirection;\n long nOffsetY = pWindow->LogicToPixel( Size( 0, mnOffsetY ) ).Height();\n\n \/\/ Position um den Offset korrigieren\n mpData->maPixPos.Y() -= nOffsetY;\n mpData->maPixRotOff = mpData->maPixPos;\n mpData->maPixRotOff.Y() += nOffsetY;\n\n \/\/ Wenn groesse 0 ist, nehmen wir die breite, die in den\n \/\/ Settings eingestellt ist\n if ( !mpData->maPixSize.Width() )\n mpData->maPixSize.Width() = pWindow->GetSettings().GetStyleSettings().GetCursorSize();\n\n \/\/ Ausgabeflaeche berechnen und ausgeben\n ImplCursorInvert( mpData );\n mpData->mbCurVisible = TRUE;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplRestore()\n{\n if ( mpData && mpData->mbCurVisible )\n {\n ImplCursorInvert( mpData );\n mpData->mbCurVisible = FALSE;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplShow( BOOL bDrawDirect )\n{\n if ( mbVisible )\n {\n Window* pWindow;\n if ( mpWindow )\n pWindow = mpWindow;\n else\n {\n \/\/ Gibt es ein aktives Fenster und ist der Cursor in dieses Fenster\n \/\/ selektiert, dann zeige den Cursor an\n pWindow = Application::GetFocusWindow();\n if ( !pWindow || (pWindow->mpCursor != this) || pWindow->mbInPaint\n || !pWindow->mpFrameData->mbHasFocus )\n pWindow = NULL;\n }\n\n if ( pWindow )\n {\n if ( !mpData )\n {\n mpData = new ImplCursorData;\n mpData->mbCurVisible = FALSE;\n mpData->maTimer.SetTimeoutHdl( LINK( this, Cursor, ImplTimerHdl ) );\n }\n\n mpData->mpWindow = pWindow;\n mpData->mnStyle = mnStyle;\n if ( bDrawDirect )\n ImplDraw();\n\n if ( !mpWindow )\n {\n mpData->maTimer.SetTimeout( pWindow->GetSettings().GetStyleSettings().GetCursorBlinkTime() );\n if ( mpData->maTimer.GetTimeout() != STYLE_CURSOR_NOBLINKTIME )\n mpData->maTimer.Start();\n else if ( !mpData->mbCurVisible )\n ImplDraw();\n }\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplHide()\n{\n if ( mpData && mpData->mpWindow )\n {\n if ( mpData->mbCurVisible )\n ImplRestore();\n\n mpData->maTimer.Stop();\n mpData->mpWindow = NULL;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplNew()\n{\n if ( mbVisible && mpData && mpData->mpWindow )\n {\n if ( mpData->mbCurVisible )\n ImplRestore();\n\n ImplDraw();\n if ( !mpWindow )\n {\n if ( mpData->maTimer.GetTimeout() != STYLE_CURSOR_NOBLINKTIME )\n mpData->maTimer.Start();\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK( Cursor, ImplTimerHdl, AutoTimer*, EMPTYARG )\n{\n if ( mpData->mbCurVisible )\n ImplRestore();\n else\n ImplDraw();\n return 0;\n}\n\n\/\/ =======================================================================\n\nCursor::Cursor()\n{\n mpData = NULL;\n mpWindow = NULL;\n mnSlant = 0;\n mnOffsetY = 0;\n mnOrientation = 0;\n mnDirection = 0;\n mnStyle = 0;\n mbVisible = FALSE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nCursor::Cursor( const Cursor& rCursor ) :\n maPos( rCursor.maPos ),\n maSize( rCursor.maSize )\n{\n mpData = NULL;\n mpWindow = NULL;\n mnSlant = rCursor.mnSlant;\n mnOrientation = rCursor.mnOrientation;\n mnDirection = rCursor.mnDirection;\n mnStyle = 0;\n mbVisible = rCursor.mbVisible;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nCursor::~Cursor()\n{\n if ( mpData )\n {\n if ( mpData->mbCurVisible )\n ImplRestore();\n\n delete mpData;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetStyle( USHORT nStyle )\n{\n if ( mnStyle != nStyle )\n {\n mnStyle = nStyle;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::Show()\n{\n if ( !mbVisible )\n {\n mbVisible = TRUE;\n ImplShow();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::Hide()\n{\n if ( mbVisible )\n {\n mbVisible = FALSE;\n ImplHide();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetWindow( Window* pWindow )\n{\n if ( mpWindow != pWindow )\n {\n mpWindow = pWindow;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetPos( const Point& rPoint )\n{\n if ( maPos != rPoint )\n {\n maPos = rPoint;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetOffsetY( long nNewOffsetY )\n{\n if ( mnOffsetY != nNewOffsetY )\n {\n mnOffsetY = nNewOffsetY;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetSize( const Size& rSize )\n{\n if ( maSize != rSize )\n {\n maSize = rSize;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetWidth( long nNewWidth )\n{\n if ( maSize.Width() != nNewWidth )\n {\n maSize.Width() = nNewWidth;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetHeight( long nNewHeight )\n{\n if ( maSize.Height() != nNewHeight )\n {\n maSize.Height() = nNewHeight;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetSlant( long nNewSlant )\n{\n if ( mnSlant != nNewSlant )\n {\n mnSlant = nNewSlant;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetOrientation( short nNewOrientation )\n{\n if ( mnOrientation != nNewOrientation )\n {\n mnOrientation = nNewOrientation;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetDirection( unsigned char nNewDirection )\n{\n if ( mnDirection != nNewDirection )\n {\n mnDirection = nNewDirection;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nCursor& Cursor::operator=( const Cursor& rCursor )\n{\n maPos = rCursor.maPos;\n maSize = rCursor.maSize;\n mnSlant = rCursor.mnSlant;\n mnOrientation = rCursor.mnOrientation;\n mnDirection = rCursor.mnDirection;\n mbVisible = rCursor.mbVisible;\n ImplNew();\n\n return *this;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Cursor::operator==( const Cursor& rCursor ) const\n{\n if ( (maPos == rCursor.maPos) &&\n (maSize == rCursor.maSize) &&\n (mnSlant == rCursor.mnSlant) &&\n (mnOrientation == rCursor.mnOrientation) &&\n (mnDirection == rCursor.mnDirection) &&\n (mbVisible == rCursor.mbVisible) )\n return TRUE;\n else\n return FALSE;\n}\n<commit_msg>INTEGRATION: CWS vclcleanup02 (1.5.208); FILE MERGED 2003\/12\/17 16:05:29 mt 1.5.208.4: #i23061# header cleanup, remove #ifdef ???_CXX and #define ???_CXX, also removed .impl files and fixed soke windows compiler warnings 2003\/12\/10 15:59:35 mt 1.5.208.3: #i23061# VCL cleanup, removed headers, methods and types... 2003\/12\/05 16:34:48 mt 1.5.208.2: RESYNC: (1.5-1.6); FILE MERGED 2003\/12\/05 13:28:44 mt 1.5.208.1: #i23061# Code cleanups, fixed gcc WAll warnings, removed unused variables and unused code<commit_after>\/*************************************************************************\n *\n * $RCSfile: cursor.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2004-01-06 14:05:26 $\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 _SV_SVAPP_HXX\n#include <svapp.hxx>\n#endif\n#ifndef _SV_TIMER_HXX\n#include <timer.hxx>\n#endif\n#ifndef _SV_SETTINGS_HXX\n#include <settings.hxx>\n#endif\n#ifndef _SV_WINDOW_HXX\n#include <window.hxx>\n#endif\n#ifndef _SV_WINDOW_H\n#include <window.h>\n#endif\n#ifndef _TL_POLY_HXX\n#include <tools\/poly.hxx>\n#endif\n#ifndef _SV_CURSOR_HXX\n#include <cursor.hxx>\n#endif\n\n\n\/\/ =======================================================================\n\nstruct ImplCursorData\n{\n AutoTimer maTimer; \/\/ Timer\n Point maPixPos; \/\/ Pixel-Position\n Point maPixRotOff; \/\/ Pixel-Offset-Position\n Size maPixSize; \/\/ Pixel-Size\n long mnPixSlant; \/\/ Pixel-Slant\n short mnOrientation; \/\/ Pixel-Orientation\n unsigned char mnDirection; \/\/ indicates writing direction\n USHORT mnStyle; \/\/ Cursor-Style\n BOOL mbCurVisible; \/\/ Ist Cursor aktuell sichtbar\n Window* mpWindow; \/\/ Zugeordnetes Windows\n};\n\n\/\/ =======================================================================\n\nstatic void ImplCursorInvert( ImplCursorData* pData )\n{\n Window* pWindow = pData->mpWindow;\n BOOL bMapMode = pWindow->IsMapModeEnabled();\n pWindow->EnableMapMode( FALSE );\n USHORT nInvertStyle;\n if ( pData->mnStyle & CURSOR_SHADOW )\n nInvertStyle = INVERT_50;\n else\n nInvertStyle = 0;\n\n Rectangle aRect( pData->maPixPos, pData->maPixSize );\n if ( pData->mnDirection || pData->mnOrientation || pData->mnPixSlant )\n {\n Polygon aPoly( aRect );\n if( aPoly.GetSize() == 5 )\n {\n aPoly[1].X() += 1; \/\/ include the right border\n aPoly[2].X() += 1;\n if ( pData->mnPixSlant )\n {\n Point aPoint = aPoly.GetPoint( 0 );\n aPoint.X() += pData->mnPixSlant;\n aPoly.SetPoint( aPoint, 0 );\n aPoly.SetPoint( aPoint, 4 );\n aPoint = aPoly.GetPoint( 1 );\n aPoint.X() += pData->mnPixSlant;\n aPoly.SetPoint( aPoint, 1 );\n }\n\n \/\/ apply direction flag after slant to use the correct shape\n if ( pData->mnDirection )\n {\n Point pAry[7];\n int delta = 3*aRect.getWidth()+1;\n if( pData->mnDirection == CURSOR_DIRECTION_LTR )\n {\n \/\/ left-to-right\n pAry[0] = aPoly.GetPoint( 0 );\n pAry[1] = aPoly.GetPoint( 1 );\n pAry[2] = pAry[1];\n pAry[2].X() += delta;\n pAry[3] = pAry[1];\n pAry[3].Y() += delta;\n pAry[4] = aPoly.GetPoint( 2 );\n pAry[5] = aPoly.GetPoint( 3 );\n pAry[6] = aPoly.GetPoint( 4 );\n }\n else if( pData->mnDirection == CURSOR_DIRECTION_RTL )\n {\n \/\/ right-to-left\n pAry[0] = aPoly.GetPoint( 0 );\n pAry[1] = aPoly.GetPoint( 1 );\n pAry[2] = aPoly.GetPoint( 2 );\n pAry[3] = aPoly.GetPoint( 3 );\n pAry[4] = pAry[0];\n pAry[4].Y() += delta;\n pAry[5] = pAry[0];\n pAry[5].X() -= delta;\n pAry[6] = aPoly.GetPoint( 4 );\n }\n aPoly = Polygon( 7, pAry);\n }\n\n if ( pData->mnOrientation )\n aPoly.Rotate( pData->maPixRotOff, pData->mnOrientation );\n pWindow->Invert( aPoly, nInvertStyle );\n }\n }\n else\n pWindow->Invert( aRect, nInvertStyle );\n pWindow->EnableMapMode( bMapMode );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplDraw()\n{\n if ( mpData && mpData->mpWindow && !mpData->mbCurVisible )\n {\n Window* pWindow = mpData->mpWindow;\n mpData->maPixPos = pWindow->LogicToPixel( maPos );\n mpData->maPixSize = pWindow->LogicToPixel( maSize );\n mpData->mnPixSlant = pWindow->LogicToPixel( Size( mnSlant, 0 ) ).Width();\n mpData->mnOrientation = mnOrientation;\n mpData->mnDirection = mnDirection;\n long nOffsetY = pWindow->LogicToPixel( Size( 0, mnOffsetY ) ).Height();\n\n \/\/ Position um den Offset korrigieren\n mpData->maPixPos.Y() -= nOffsetY;\n mpData->maPixRotOff = mpData->maPixPos;\n mpData->maPixRotOff.Y() += nOffsetY;\n\n \/\/ Wenn groesse 0 ist, nehmen wir die breite, die in den\n \/\/ Settings eingestellt ist\n if ( !mpData->maPixSize.Width() )\n mpData->maPixSize.Width() = pWindow->GetSettings().GetStyleSettings().GetCursorSize();\n\n \/\/ Ausgabeflaeche berechnen und ausgeben\n ImplCursorInvert( mpData );\n mpData->mbCurVisible = TRUE;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplRestore()\n{\n if ( mpData && mpData->mbCurVisible )\n {\n ImplCursorInvert( mpData );\n mpData->mbCurVisible = FALSE;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplShow( BOOL bDrawDirect )\n{\n if ( mbVisible )\n {\n Window* pWindow;\n if ( mpWindow )\n pWindow = mpWindow;\n else\n {\n \/\/ Gibt es ein aktives Fenster und ist der Cursor in dieses Fenster\n \/\/ selektiert, dann zeige den Cursor an\n pWindow = Application::GetFocusWindow();\n if ( !pWindow || (pWindow->mpCursor != this) || pWindow->mbInPaint\n || !pWindow->mpFrameData->mbHasFocus )\n pWindow = NULL;\n }\n\n if ( pWindow )\n {\n if ( !mpData )\n {\n mpData = new ImplCursorData;\n mpData->mbCurVisible = FALSE;\n mpData->maTimer.SetTimeoutHdl( LINK( this, Cursor, ImplTimerHdl ) );\n }\n\n mpData->mpWindow = pWindow;\n mpData->mnStyle = mnStyle;\n if ( bDrawDirect )\n ImplDraw();\n\n if ( !mpWindow )\n {\n mpData->maTimer.SetTimeout( pWindow->GetSettings().GetStyleSettings().GetCursorBlinkTime() );\n if ( mpData->maTimer.GetTimeout() != STYLE_CURSOR_NOBLINKTIME )\n mpData->maTimer.Start();\n else if ( !mpData->mbCurVisible )\n ImplDraw();\n }\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplHide()\n{\n if ( mpData && mpData->mpWindow )\n {\n if ( mpData->mbCurVisible )\n ImplRestore();\n\n mpData->maTimer.Stop();\n mpData->mpWindow = NULL;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::ImplNew()\n{\n if ( mbVisible && mpData && mpData->mpWindow )\n {\n if ( mpData->mbCurVisible )\n ImplRestore();\n\n ImplDraw();\n if ( !mpWindow )\n {\n if ( mpData->maTimer.GetTimeout() != STYLE_CURSOR_NOBLINKTIME )\n mpData->maTimer.Start();\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK( Cursor, ImplTimerHdl, AutoTimer*, EMPTYARG )\n{\n if ( mpData->mbCurVisible )\n ImplRestore();\n else\n ImplDraw();\n return 0;\n}\n\n\/\/ =======================================================================\n\nCursor::Cursor()\n{\n mpData = NULL;\n mpWindow = NULL;\n mnSlant = 0;\n mnOffsetY = 0;\n mnOrientation = 0;\n mnDirection = 0;\n mnStyle = 0;\n mbVisible = FALSE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nCursor::Cursor( const Cursor& rCursor ) :\n maSize( rCursor.maSize ),\n maPos( rCursor.maPos )\n{\n mpData = NULL;\n mpWindow = NULL;\n mnSlant = rCursor.mnSlant;\n mnOrientation = rCursor.mnOrientation;\n mnDirection = rCursor.mnDirection;\n mnStyle = 0;\n mbVisible = rCursor.mbVisible;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nCursor::~Cursor()\n{\n if ( mpData )\n {\n if ( mpData->mbCurVisible )\n ImplRestore();\n\n delete mpData;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetStyle( USHORT nStyle )\n{\n if ( mnStyle != nStyle )\n {\n mnStyle = nStyle;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::Show()\n{\n if ( !mbVisible )\n {\n mbVisible = TRUE;\n ImplShow();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::Hide()\n{\n if ( mbVisible )\n {\n mbVisible = FALSE;\n ImplHide();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetWindow( Window* pWindow )\n{\n if ( mpWindow != pWindow )\n {\n mpWindow = pWindow;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetPos( const Point& rPoint )\n{\n if ( maPos != rPoint )\n {\n maPos = rPoint;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetOffsetY( long nNewOffsetY )\n{\n if ( mnOffsetY != nNewOffsetY )\n {\n mnOffsetY = nNewOffsetY;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetSize( const Size& rSize )\n{\n if ( maSize != rSize )\n {\n maSize = rSize;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetWidth( long nNewWidth )\n{\n if ( maSize.Width() != nNewWidth )\n {\n maSize.Width() = nNewWidth;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetHeight( long nNewHeight )\n{\n if ( maSize.Height() != nNewHeight )\n {\n maSize.Height() = nNewHeight;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetSlant( long nNewSlant )\n{\n if ( mnSlant != nNewSlant )\n {\n mnSlant = nNewSlant;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetOrientation( short nNewOrientation )\n{\n if ( mnOrientation != nNewOrientation )\n {\n mnOrientation = nNewOrientation;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid Cursor::SetDirection( unsigned char nNewDirection )\n{\n if ( mnDirection != nNewDirection )\n {\n mnDirection = nNewDirection;\n ImplNew();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nCursor& Cursor::operator=( const Cursor& rCursor )\n{\n maPos = rCursor.maPos;\n maSize = rCursor.maSize;\n mnSlant = rCursor.mnSlant;\n mnOrientation = rCursor.mnOrientation;\n mnDirection = rCursor.mnDirection;\n mbVisible = rCursor.mbVisible;\n ImplNew();\n\n return *this;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Cursor::operator==( const Cursor& rCursor ) const\n{\n if ( (maPos == rCursor.maPos) &&\n (maSize == rCursor.maSize) &&\n (mnSlant == rCursor.mnSlant) &&\n (mnOrientation == rCursor.mnOrientation) &&\n (mnDirection == rCursor.mnDirection) &&\n (mbVisible == rCursor.mbVisible) )\n return TRUE;\n else\n return FALSE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: scrwnd.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 12:20:32 $\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\n#include <math.h>\n#include <limits.h>\n\n#ifndef _TOOLS_TIME_HXX\n#include <tools\/time.hxx>\n#endif\n#include <tools\/debug.hxx>\n\n#ifndef _SV_SVIDS_HRC\n#include <svids.hrc>\n#endif\n#ifndef _SV_SVDATA_HXX\n#include <svdata.hxx>\n#endif\n#ifndef _VCL_TIMER_HXX\n#include <timer.hxx>\n#endif\n#ifndef _VCL_EVENT_HXX\n#include <event.hxx>\n#endif\n#ifndef _VCL_SCRWND_HXX\n#include <scrwnd.hxx>\n#endif\n\n\/\/ -----------\n\/\/ - Defines -\n\/\/ -----------\n\n#define WHEEL_WIDTH 25\n#define WHEEL_RADIUS ((WHEEL_WIDTH) >> 1 )\n#define MAX_TIME 300\n#define MIN_TIME 20\n#define DEF_TIMEOUT 50\n\n\/\/ -------------------\n\/\/ - ImplWheelWindow -\n\/\/ -------------------\n\nImplWheelWindow::ImplWheelWindow( Window* pParent ) :\n FloatingWindow ( pParent, 0 ),\n mnRepaintTime ( 1UL ),\n mnTimeout ( DEF_TIMEOUT ),\n mnWheelMode ( WHEELMODE_NONE ),\n mnActDist ( 0UL ),\n mnActDeltaX ( 0L ),\n mnActDeltaY ( 0L )\n{\n \/\/ we need a parent\n DBG_ASSERT( pParent, \"ImplWheelWindow::ImplWheelWindow(): Parent not set!\" );\n\n const Size aSize( pParent->GetOutputSizePixel() );\n const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;\n const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;\n const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;\n\n \/\/ calculate maximum speed distance\n mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) );\n\n \/\/ create wheel window\n SetTitleType( FLOATWIN_TITLE_NONE );\n ImplCreateImageList();\n ResMgr* pResMgr = ImplGetResMgr();\n Bitmap aBmp;\n if( pResMgr )\n aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, ImplGetResMgr() ) );\n ImplSetRegion( aBmp );\n\n \/\/ set wheel mode\n if( bHorz && bVert )\n ImplSetWheelMode( WHEELMODE_VH );\n else if( bHorz )\n ImplSetWheelMode( WHEELMODE_H );\n else\n ImplSetWheelMode( WHEELMODE_V );\n\n \/\/ init timer\n mpTimer = new Timer;\n mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) );\n mpTimer->SetTimeout( mnTimeout );\n mpTimer->Start();\n\n CaptureMouse();\n}\n\n\/\/ ------------------------------------------------------------------------\n\nImplWheelWindow::~ImplWheelWindow()\n{\n ReleaseMouse();\n mpTimer->Stop();\n delete mpTimer;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp )\n{\n Point aPos( GetPointerPosPixel() );\n const Size aSize( rRegionBmp.GetSizePixel() );\n Point aPoint;\n const Rectangle aRect( aPoint, aSize );\n\n maCenter = maLastMousePos = aPos;\n aPos.X() -= aSize.Width() >> 1;\n aPos.Y() -= aSize.Height() >> 1;\n\n SetPosSizePixel( aPos, aSize );\n SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplCreateImageList()\n{\n Bitmap aImgBmp;\n ResMgr* pResMgr = ImplGetResMgr();\n if( pResMgr )\n aImgBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLBMP, pResMgr ) );\n maImgList = ImageList( aImgBmp, 6 );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode )\n{\n if( nWheelMode != mnWheelMode )\n {\n mnWheelMode = nWheelMode;\n\n if( WHEELMODE_NONE == mnWheelMode )\n {\n if( IsVisible() )\n Hide();\n }\n else\n {\n if( !IsVisible() )\n Show();\n\n ImplDrawWheel();\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplDrawWheel()\n{\n USHORT nId;\n\n switch( mnWheelMode )\n {\n case( WHEELMODE_VH ): nId = 1; break;\n case( WHEELMODE_V ): nId = 2; break;\n case( WHEELMODE_H ): nId = 3; break;\n case( WHEELMODE_SCROLL_VH ):nId = 4; break;\n case( WHEELMODE_SCROLL_V ): nId = 5; break;\n case( WHEELMODE_SCROLL_H ): nId = 6; break;\n default: nId = 0; break;\n }\n\n if( nId )\n DrawImage( Point(), maImgList.GetImage( nId ) );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplRecalcScrollValues()\n{\n if( mnActDist < WHEEL_RADIUS )\n {\n mnActDeltaX = mnActDeltaY = 0L;\n mnTimeout = DEF_TIMEOUT;\n }\n else\n {\n ULONG nCurTime;\n\n \/\/ calc current time\n if( mnMaxWidth )\n {\n const double fExp = ( (double) mnActDist \/ mnMaxWidth ) * log10( (double) MAX_TIME \/ MIN_TIME );\n nCurTime = (ULONG) ( MAX_TIME \/ pow( 10., fExp ) );\n }\n else\n nCurTime = MAX_TIME;\n\n if( !nCurTime )\n nCurTime = 1UL;\n\n if( mnRepaintTime <= nCurTime )\n mnTimeout = nCurTime - mnRepaintTime;\n else\n {\n long nMult = mnRepaintTime \/ nCurTime;\n\n if( !( mnRepaintTime % nCurTime ) )\n mnTimeout = 0UL;\n else\n mnTimeout = ++nMult * nCurTime - mnRepaintTime;\n\n double fValX = (double) mnActDeltaX * nMult;\n double fValY = (double) mnActDeltaY * nMult;\n\n if( fValX > LONG_MAX )\n mnActDeltaX = LONG_MAX;\n else if( fValX < LONG_MIN )\n mnActDeltaX = LONG_MIN;\n else\n mnActDeltaX = (long) fValX;\n\n if( fValY > LONG_MAX )\n mnActDeltaY = LONG_MAX;\n else if( fValY < LONG_MIN )\n mnActDeltaY = LONG_MIN;\n else\n mnActDeltaY = (long) fValY;\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nPointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY )\n{\n PointerStyle eStyle;\n const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;\n const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;\n const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;\n\n if( bHorz || bVert )\n {\n if( mnActDist < WHEEL_RADIUS )\n {\n if( bHorz && bVert )\n eStyle = POINTER_AUTOSCROLL_NSWE;\n else if( bHorz )\n eStyle = POINTER_AUTOSCROLL_WE;\n else\n eStyle = POINTER_AUTOSCROLL_NS;\n }\n else\n {\n double fAngle = atan2( (double) -nDistY, nDistX ) \/ F_PI180;\n\n if( fAngle < 0.0 )\n fAngle += 360.;\n\n if( bHorz && bVert )\n {\n if( fAngle >= 22.5 && fAngle <= 67.5 )\n eStyle = POINTER_AUTOSCROLL_NE;\n else if( fAngle >= 67.5 && fAngle <= 112.5 )\n eStyle = POINTER_AUTOSCROLL_N;\n else if( fAngle >= 112.5 && fAngle <= 157.5 )\n eStyle = POINTER_AUTOSCROLL_NW;\n else if( fAngle >= 157.5 && fAngle <= 202.5 )\n eStyle = POINTER_AUTOSCROLL_W;\n else if( fAngle >= 202.5 && fAngle <= 247.5 )\n eStyle = POINTER_AUTOSCROLL_SW;\n else if( fAngle >= 247.5 && fAngle <= 292.5 )\n eStyle = POINTER_AUTOSCROLL_S;\n else if( fAngle >= 292.5 && fAngle <= 337.5 )\n eStyle = POINTER_AUTOSCROLL_SE;\n else\n eStyle = POINTER_AUTOSCROLL_E;\n }\n else if( bHorz )\n {\n if( fAngle >= 270. || fAngle <= 90. )\n eStyle = POINTER_AUTOSCROLL_E;\n else\n eStyle = POINTER_AUTOSCROLL_W;\n }\n else\n {\n if( fAngle >= 0. && fAngle <= 180. )\n eStyle = POINTER_AUTOSCROLL_N;\n else\n eStyle = POINTER_AUTOSCROLL_S;\n }\n }\n }\n else\n eStyle = POINTER_ARROW;\n\n return eStyle;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::Paint( const Rectangle& )\n{\n ImplDrawWheel();\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::MouseMove( const MouseEvent& rMEvt )\n{\n FloatingWindow::MouseMove( rMEvt );\n\n const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) );\n const long nDistX = aMousePos.X() - maCenter.X();\n const long nDistY = aMousePos.Y() - maCenter.Y();\n\n mnActDist = (ULONG) hypot( (double) nDistX, nDistY );\n\n const PointerStyle eActStyle = ImplGetMousePointer( nDistX, nDistY );\n const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;\n const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;\n const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;\n const BOOL bOuter = mnActDist > WHEEL_RADIUS;\n\n if( bOuter && ( maLastMousePos != aMousePos ) )\n {\n switch( eActStyle )\n {\n case( POINTER_AUTOSCROLL_N ): mnActDeltaX = +0L, mnActDeltaY = +1L; break;\n case( POINTER_AUTOSCROLL_S ): mnActDeltaX = +0L, mnActDeltaY = -1L; break;\n case( POINTER_AUTOSCROLL_W ): mnActDeltaX = +1L, mnActDeltaY = +0L; break;\n case( POINTER_AUTOSCROLL_E ): mnActDeltaX = -1L, mnActDeltaY = +0L; break;\n case( POINTER_AUTOSCROLL_NW ): mnActDeltaX = +1L, mnActDeltaY = +1L; break;\n case( POINTER_AUTOSCROLL_NE ): mnActDeltaX = -1L, mnActDeltaY = +1L; break;\n case( POINTER_AUTOSCROLL_SW ): mnActDeltaX = +1L, mnActDeltaY = -1L; break;\n case( POINTER_AUTOSCROLL_SE ): mnActDeltaX = -1L, mnActDeltaY = -1L; break;\n\n default:\n break;\n }\n }\n\n ImplRecalcScrollValues();\n maLastMousePos = aMousePos;\n SetPointer( eActStyle );\n\n if( bHorz && bVert )\n ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH );\n else if( bHorz )\n ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H );\n else\n ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt )\n{\n if( mnActDist > WHEEL_RADIUS )\n GetParent()->EndAutoScroll();\n else\n FloatingWindow::MouseButtonUp( rMEvt );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nIMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG )\n{\n if ( mnActDeltaX || mnActDeltaY )\n {\n Window* pWindow = GetParent();\n const Point aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) );\n Point aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) );\n CommandScrollData aScrollData( mnActDeltaX, mnActDeltaY );\n CommandEvent aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData );\n NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt );\n\n if ( !ImplCallPreNotify( aNCmdEvt ) )\n {\n const ULONG nTime = Time::GetSystemTicks();\n pWindow->Command( aCEvt );\n mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL );\n ImplRecalcScrollValues();\n }\n }\n\n if ( mnTimeout != mpTimer->GetTimeout() )\n mpTimer->SetTimeout( mnTimeout );\n mpTimer->Start();\n\n return 0L;\n}\n<commit_msg>INTEGRATION: CWS vcl77 (1.8.192); FILE MERGED 2007\/03\/29 09:31:46 pl 1.8.192.1: #i75284# clean up srcoll window destruction<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: scrwnd.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: ihi $ $Date: 2007-04-16 14:21:57 $\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\n#include <math.h>\n#include <limits.h>\n\n#ifndef _TOOLS_TIME_HXX\n#include <tools\/time.hxx>\n#endif\n#include <tools\/debug.hxx>\n\n#ifndef _SV_SVIDS_HRC\n#include <svids.hrc>\n#endif\n#ifndef _SV_SVDATA_HXX\n#include <svdata.hxx>\n#endif\n#ifndef _VCL_TIMER_HXX\n#include <timer.hxx>\n#endif\n#ifndef _VCL_EVENT_HXX\n#include <event.hxx>\n#endif\n#ifndef _VCL_SCRWND_HXX\n#include <scrwnd.hxx>\n#endif\n\n\/\/ -----------\n\/\/ - Defines -\n\/\/ -----------\n\n#define WHEEL_WIDTH 25\n#define WHEEL_RADIUS ((WHEEL_WIDTH) >> 1 )\n#define MAX_TIME 300\n#define MIN_TIME 20\n#define DEF_TIMEOUT 50\n\n\/\/ -------------------\n\/\/ - ImplWheelWindow -\n\/\/ -------------------\n\nImplWheelWindow::ImplWheelWindow( Window* pParent ) :\n FloatingWindow ( pParent, 0 ),\n mnRepaintTime ( 1UL ),\n mnTimeout ( DEF_TIMEOUT ),\n mnWheelMode ( WHEELMODE_NONE ),\n mnActDist ( 0UL ),\n mnActDeltaX ( 0L ),\n mnActDeltaY ( 0L )\n{\n \/\/ we need a parent\n DBG_ASSERT( pParent, \"ImplWheelWindow::ImplWheelWindow(): Parent not set!\" );\n\n const Size aSize( pParent->GetOutputSizePixel() );\n const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;\n const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;\n const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;\n\n \/\/ calculate maximum speed distance\n mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) );\n\n \/\/ create wheel window\n SetTitleType( FLOATWIN_TITLE_NONE );\n ImplCreateImageList();\n ResMgr* pResMgr = ImplGetResMgr();\n Bitmap aBmp;\n if( pResMgr )\n aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, ImplGetResMgr() ) );\n ImplSetRegion( aBmp );\n\n \/\/ set wheel mode\n if( bHorz && bVert )\n ImplSetWheelMode( WHEELMODE_VH );\n else if( bHorz )\n ImplSetWheelMode( WHEELMODE_H );\n else\n ImplSetWheelMode( WHEELMODE_V );\n\n \/\/ init timer\n mpTimer = new Timer;\n mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) );\n mpTimer->SetTimeout( mnTimeout );\n mpTimer->Start();\n\n CaptureMouse();\n}\n\n\/\/ ------------------------------------------------------------------------\n\nImplWheelWindow::~ImplWheelWindow()\n{\n ImplStop();\n delete mpTimer;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplStop()\n{\n ReleaseMouse();\n mpTimer->Stop();\n Show(FALSE);\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp )\n{\n Point aPos( GetPointerPosPixel() );\n const Size aSize( rRegionBmp.GetSizePixel() );\n Point aPoint;\n const Rectangle aRect( aPoint, aSize );\n\n maCenter = maLastMousePos = aPos;\n aPos.X() -= aSize.Width() >> 1;\n aPos.Y() -= aSize.Height() >> 1;\n\n SetPosSizePixel( aPos, aSize );\n SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplCreateImageList()\n{\n Bitmap aImgBmp;\n ResMgr* pResMgr = ImplGetResMgr();\n if( pResMgr )\n aImgBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLBMP, pResMgr ) );\n maImgList = ImageList( aImgBmp, 6 );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode )\n{\n if( nWheelMode != mnWheelMode )\n {\n mnWheelMode = nWheelMode;\n\n if( WHEELMODE_NONE == mnWheelMode )\n {\n if( IsVisible() )\n Hide();\n }\n else\n {\n if( !IsVisible() )\n Show();\n\n ImplDrawWheel();\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplDrawWheel()\n{\n USHORT nId;\n\n switch( mnWheelMode )\n {\n case( WHEELMODE_VH ): nId = 1; break;\n case( WHEELMODE_V ): nId = 2; break;\n case( WHEELMODE_H ): nId = 3; break;\n case( WHEELMODE_SCROLL_VH ):nId = 4; break;\n case( WHEELMODE_SCROLL_V ): nId = 5; break;\n case( WHEELMODE_SCROLL_H ): nId = 6; break;\n default: nId = 0; break;\n }\n\n if( nId )\n DrawImage( Point(), maImgList.GetImage( nId ) );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::ImplRecalcScrollValues()\n{\n if( mnActDist < WHEEL_RADIUS )\n {\n mnActDeltaX = mnActDeltaY = 0L;\n mnTimeout = DEF_TIMEOUT;\n }\n else\n {\n ULONG nCurTime;\n\n \/\/ calc current time\n if( mnMaxWidth )\n {\n const double fExp = ( (double) mnActDist \/ mnMaxWidth ) * log10( (double) MAX_TIME \/ MIN_TIME );\n nCurTime = (ULONG) ( MAX_TIME \/ pow( 10., fExp ) );\n }\n else\n nCurTime = MAX_TIME;\n\n if( !nCurTime )\n nCurTime = 1UL;\n\n if( mnRepaintTime <= nCurTime )\n mnTimeout = nCurTime - mnRepaintTime;\n else\n {\n long nMult = mnRepaintTime \/ nCurTime;\n\n if( !( mnRepaintTime % nCurTime ) )\n mnTimeout = 0UL;\n else\n mnTimeout = ++nMult * nCurTime - mnRepaintTime;\n\n double fValX = (double) mnActDeltaX * nMult;\n double fValY = (double) mnActDeltaY * nMult;\n\n if( fValX > LONG_MAX )\n mnActDeltaX = LONG_MAX;\n else if( fValX < LONG_MIN )\n mnActDeltaX = LONG_MIN;\n else\n mnActDeltaX = (long) fValX;\n\n if( fValY > LONG_MAX )\n mnActDeltaY = LONG_MAX;\n else if( fValY < LONG_MIN )\n mnActDeltaY = LONG_MIN;\n else\n mnActDeltaY = (long) fValY;\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nPointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY )\n{\n PointerStyle eStyle;\n const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;\n const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;\n const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;\n\n if( bHorz || bVert )\n {\n if( mnActDist < WHEEL_RADIUS )\n {\n if( bHorz && bVert )\n eStyle = POINTER_AUTOSCROLL_NSWE;\n else if( bHorz )\n eStyle = POINTER_AUTOSCROLL_WE;\n else\n eStyle = POINTER_AUTOSCROLL_NS;\n }\n else\n {\n double fAngle = atan2( (double) -nDistY, nDistX ) \/ F_PI180;\n\n if( fAngle < 0.0 )\n fAngle += 360.;\n\n if( bHorz && bVert )\n {\n if( fAngle >= 22.5 && fAngle <= 67.5 )\n eStyle = POINTER_AUTOSCROLL_NE;\n else if( fAngle >= 67.5 && fAngle <= 112.5 )\n eStyle = POINTER_AUTOSCROLL_N;\n else if( fAngle >= 112.5 && fAngle <= 157.5 )\n eStyle = POINTER_AUTOSCROLL_NW;\n else if( fAngle >= 157.5 && fAngle <= 202.5 )\n eStyle = POINTER_AUTOSCROLL_W;\n else if( fAngle >= 202.5 && fAngle <= 247.5 )\n eStyle = POINTER_AUTOSCROLL_SW;\n else if( fAngle >= 247.5 && fAngle <= 292.5 )\n eStyle = POINTER_AUTOSCROLL_S;\n else if( fAngle >= 292.5 && fAngle <= 337.5 )\n eStyle = POINTER_AUTOSCROLL_SE;\n else\n eStyle = POINTER_AUTOSCROLL_E;\n }\n else if( bHorz )\n {\n if( fAngle >= 270. || fAngle <= 90. )\n eStyle = POINTER_AUTOSCROLL_E;\n else\n eStyle = POINTER_AUTOSCROLL_W;\n }\n else\n {\n if( fAngle >= 0. && fAngle <= 180. )\n eStyle = POINTER_AUTOSCROLL_N;\n else\n eStyle = POINTER_AUTOSCROLL_S;\n }\n }\n }\n else\n eStyle = POINTER_ARROW;\n\n return eStyle;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::Paint( const Rectangle& )\n{\n ImplDrawWheel();\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::MouseMove( const MouseEvent& rMEvt )\n{\n FloatingWindow::MouseMove( rMEvt );\n\n const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) );\n const long nDistX = aMousePos.X() - maCenter.X();\n const long nDistY = aMousePos.Y() - maCenter.Y();\n\n mnActDist = (ULONG) hypot( (double) nDistX, nDistY );\n\n const PointerStyle eActStyle = ImplGetMousePointer( nDistX, nDistY );\n const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;\n const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;\n const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;\n const BOOL bOuter = mnActDist > WHEEL_RADIUS;\n\n if( bOuter && ( maLastMousePos != aMousePos ) )\n {\n switch( eActStyle )\n {\n case( POINTER_AUTOSCROLL_N ): mnActDeltaX = +0L, mnActDeltaY = +1L; break;\n case( POINTER_AUTOSCROLL_S ): mnActDeltaX = +0L, mnActDeltaY = -1L; break;\n case( POINTER_AUTOSCROLL_W ): mnActDeltaX = +1L, mnActDeltaY = +0L; break;\n case( POINTER_AUTOSCROLL_E ): mnActDeltaX = -1L, mnActDeltaY = +0L; break;\n case( POINTER_AUTOSCROLL_NW ): mnActDeltaX = +1L, mnActDeltaY = +1L; break;\n case( POINTER_AUTOSCROLL_NE ): mnActDeltaX = -1L, mnActDeltaY = +1L; break;\n case( POINTER_AUTOSCROLL_SW ): mnActDeltaX = +1L, mnActDeltaY = -1L; break;\n case( POINTER_AUTOSCROLL_SE ): mnActDeltaX = -1L, mnActDeltaY = -1L; break;\n\n default:\n break;\n }\n }\n\n ImplRecalcScrollValues();\n maLastMousePos = aMousePos;\n SetPointer( eActStyle );\n\n if( bHorz && bVert )\n ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH );\n else if( bHorz )\n ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H );\n else\n ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt )\n{\n if( mnActDist > WHEEL_RADIUS )\n GetParent()->EndAutoScroll();\n else\n FloatingWindow::MouseButtonUp( rMEvt );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nIMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG )\n{\n if ( mnActDeltaX || mnActDeltaY )\n {\n Window* pWindow = GetParent();\n const Point aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) );\n Point aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) );\n CommandScrollData aScrollData( mnActDeltaX, mnActDeltaY );\n CommandEvent aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData );\n NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt );\n\n if ( !ImplCallPreNotify( aNCmdEvt ) )\n {\n const ULONG nTime = Time::GetSystemTicks();\n ImplDelData aDel( this );\n pWindow->Command( aCEvt );\n if( aDel.IsDead() )\n return 0;\n mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL );\n ImplRecalcScrollValues();\n }\n }\n\n if ( mnTimeout != mpTimer->GetTimeout() )\n mpTimer->SetTimeout( mnTimeout );\n mpTimer->Start();\n\n return 0L;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef VEXCL_VEXCL_HPP\n#define VEXCL_VEXCL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file vexcl.hpp\n * \\author Denis Demidov <ddemidov@ksu.ru>\n * \\brief Vector expression template library for OpenCL.\n *\/\n\n#include <vexcl\/devlist.hpp>\n#include <vexcl\/constants.hpp>\n#include <vexcl\/element_index.hpp>\n#include <vexcl\/vector.hpp>\n#include <vexcl\/vector_view.hpp>\n#include <vexcl\/tagged_terminal.hpp>\n#include <vexcl\/temporary.hpp>\n#include <vexcl\/cast.hpp>\n#include <vexcl\/multivector.hpp>\n#include <vexcl\/reductor.hpp>\n#include <vexcl\/spmat.hpp>\n#include <vexcl\/stencil.hpp>\n#include <vexcl\/gather.hpp>\n#include <vexcl\/random.hpp>\n#include <vexcl\/fft.hpp>\n#include <vexcl\/mba.hpp>\n#include <vexcl\/generator.hpp>\n#include <vexcl\/mba.hpp>\n#include <vexcl\/profiler.hpp>\n\n#endif\n<commit_msg>Include <vexcl\/vector_pointer.hpp> by default<commit_after>#ifndef VEXCL_VEXCL_HPP\n#define VEXCL_VEXCL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file vexcl.hpp\n * \\author Denis Demidov <ddemidov@ksu.ru>\n * \\brief Vector expression template library for OpenCL.\n *\/\n\n#include <vexcl\/devlist.hpp>\n#include <vexcl\/constants.hpp>\n#include <vexcl\/element_index.hpp>\n#include <vexcl\/vector.hpp>\n#include <vexcl\/vector_view.hpp>\n#include <vexcl\/vector_pointer.hpp>\n#include <vexcl\/tagged_terminal.hpp>\n#include <vexcl\/temporary.hpp>\n#include <vexcl\/cast.hpp>\n#include <vexcl\/multivector.hpp>\n#include <vexcl\/reductor.hpp>\n#include <vexcl\/spmat.hpp>\n#include <vexcl\/stencil.hpp>\n#include <vexcl\/gather.hpp>\n#include <vexcl\/random.hpp>\n#include <vexcl\/fft.hpp>\n#include <vexcl\/mba.hpp>\n#include <vexcl\/generator.hpp>\n#include <vexcl\/mba.hpp>\n#include <vexcl\/profiler.hpp>\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: langselect.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 17:09:40 $\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#include <list>\n#include <sal\/types.h>\n#include <tools\/string.hxx>\n#include <tools\/lang.hxx>\n#include <rtl\/ustring.hxx>\n#include <tools\/resid.hxx>\n#include <vcl\/dialog.hxx>\n#include <vcl\/lstbox.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/button.hxx>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <svtools\/languageoptions.hxx>\n\nnamespace desktop\n{\n\nclass LanguageSelection\n{\nprivate:\n static const rtl::OUString usFallbackLanguage;\n static rtl::OUString aFoundLanguage;\n static sal_Bool bFoundLanguage;\n\n static com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >\n getConfigAccess(const sal_Char* pPath, sal_Bool bUpdate=sal_False);\n static com::sun::star::uno::Sequence< rtl::OUString > getInstalledLanguages();\n static sal_Bool isInstalledLanguage(rtl::OUString& usLocale, sal_Bool bExact=sal_False);\n static rtl::OUString getFirstInstalledLanguage();\n static rtl::OUString getUserLanguage();\n static rtl::OUString getSystemLanguage();\n static void resetUserLanguage();\n static void setDefaultLocale(const rtl::OUString&);\n\npublic:\n static com::sun::star::lang::Locale IsoStringToLocale(const rtl::OUString& str);\n static rtl::OUString getLanguageString();\n static bool prepareLanguage();\n};\n\n} \/\/namespace desktop\n<commit_msg>INTEGRATION: CWS internatiodel (1.9.102); FILE MERGED 2006\/02\/10 19:29:40 er 1.9.102.1: #i52115# move LangIDs and ISO conversion from tools to i18npool; introduce class MsLangId and libi18nisolang<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: langselect.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: vg $ $Date: 2006-04-07 14:44:20 $\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#include <list>\n#include <sal\/types.h>\n#include <tools\/string.hxx>\n#include <rtl\/ustring.hxx>\n#include <tools\/resid.hxx>\n#include <vcl\/dialog.hxx>\n#include <vcl\/lstbox.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/button.hxx>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <svtools\/languageoptions.hxx>\n\nnamespace desktop\n{\n\nclass LanguageSelection\n{\nprivate:\n static const rtl::OUString usFallbackLanguage;\n static rtl::OUString aFoundLanguage;\n static sal_Bool bFoundLanguage;\n\n static com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >\n getConfigAccess(const sal_Char* pPath, sal_Bool bUpdate=sal_False);\n static com::sun::star::uno::Sequence< rtl::OUString > getInstalledLanguages();\n static sal_Bool isInstalledLanguage(rtl::OUString& usLocale, sal_Bool bExact=sal_False);\n static rtl::OUString getFirstInstalledLanguage();\n static rtl::OUString getUserLanguage();\n static rtl::OUString getSystemLanguage();\n static void resetUserLanguage();\n static void setDefaultLocale(const rtl::OUString&);\n\npublic:\n static com::sun::star::lang::Locale IsoStringToLocale(const rtl::OUString& str);\n static rtl::OUString getLanguageString();\n static bool prepareLanguage();\n};\n\n} \/\/namespace desktop\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2003,2004 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 * $Id$\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \"MemoryMonitor.hpp\"\n#if defined(XERCES_NEW_IOSTREAMS)\n#include <iostream>\n#include <fstream>\n#else\n#include <iostream.h>\n#include <fstream.h>\n#endif\n#include <assert.h>\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/OutOfMemoryException.hpp>\n\nvoid* MemoryMonitor::allocate(size_t size)\n{\n void *key = ::operator new(size);\n fHashTable->put(key, (unsigned int)size);\n return key;\n}\n\nvoid MemoryMonitor::deallocate(void* p)\n{\n \/\/ if fHashTable doesn't contain p, then this memory manager\n \/\/ didn't allocate that memory--a segfault waiting to happen...\n assert(p == 0 || fHashTable->get(p) != 0);\n if (p != 0)\n fHashTable->removeKey(p);\n ::operator delete(p);\n}\n\nunsigned int MemoryMonitor::getTotalMemory() \n{\n unsigned int total = 0;\n ValueHashTableOfEnumerator<unsigned int> *memEnum = \n new ValueHashTableOfEnumerator<unsigned int>(fHashTable);\n while(memEnum->hasMoreElements()) {\n total += memEnum->nextElement();\n }\n delete memEnum;\n return total;\n}\n\nstatic void usage()\n{\n XERCES_STD_QUALIFIER cout << \"\\nUsage:\\n\"\n \" MemHandlerTest [options] <XML file | List file>\\n\\n\"\n \"This program invokes the XercesDOMParser, DOMLSParser, SAXParser ,\\n\"\n \"and the SAX2XMLReader, and ensures that MemoryManagers set on these\\n\"\n \"domBuilders are called to delete just as many bytes as they allocate.\\n\"\n \"This is done for each XML file, and each file is processed\\n\"\n \"as many times as indicated.\\n\"\n \"Options:\\n\"\n \" -l Indicate the input file is a List File that has a list of xml files.\\n\"\n \" Default to off (Input file is an XML file).\\n\"\n \" -v=xxx Validation scheme [always | never | auto*].\\n\"\n \" -n Enable namespace processing. Defaults to off.\\n\"\n \" -s Enable schema processing. Defaults to off.\\n\"\n \" -f Enable full schema constraint checking. Defaults to off.\\n\"\n \" -r=n Run file through domBuilders n times.\\n\" \n\t\t \" -? Show this help.\\n\\n\"\n \" * = Default if not provided explicitly.\\n\"\n << XERCES_STD_QUALIFIER endl;\n}\n\nclass DOMLSParserHandler : public DOMErrorHandler \n{\npublic:\n DOMLSParserHandler() {};\n ~DOMLSParserHandler() {};\n bool handleError(const DOMError &error) \n {\n char *message = 0;\n XERCES_STD_QUALIFIER cerr << \"Error occurred in DOMBuilder! Message: \" << \n (message = XMLString::transcode(error.getMessage())) << \" of severity \" << error.getSeverity() << \".\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&message);\n return true;\n }\n};\n\nclass SAXErrorHandler : public ErrorHandler \n{\npublic:\n SAXErrorHandler() {};\n ~SAXErrorHandler() {};\n void warning(const SAXParseException &exc )\n {\n char *message = 0;\n XERCES_STD_QUALIFIER cerr << \"SAX warning received! Text: \" <<\n (message = XMLString::transcode(exc.getMessage())) << \".\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&message);\n }\n void error(const SAXParseException &exc )\n {\n char *message = 0;\n XERCES_STD_QUALIFIER cerr << \"SAX error received! Text: \" <<\n (message = XMLString::transcode(exc.getMessage())) << \".\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&message);\n }\n void fatalError(const SAXParseException &exc )\n {\n char *message = 0;\n XERCES_STD_QUALIFIER cerr << \"SAX fatalError received! Text: \" <<\n (message = XMLString::transcode(exc.getMessage())) << \".\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&message);\n }\n\n \/\/ no state so no body\n void resetErrors() {};\n};\n\n\/**\n * This utility takes similar parameters as DOMCount,\n * with similar meanings. The only difference is that it runs\n * the file(s) in question through a DOMParser, a DOMBuilder, a SAXParser and\n * a SAX2XMLReader, setting options as appropriate. It does this\n * sequentially, n times per file with a single domBuilder\n * object, and reports what it finds in terms of memory\n * allocations\/deallocations.\n *\/\n\nint main (int argC, char *argV[]) \n{\n\n MemoryMonitor *staticMemMonitor = new MemoryMonitor();\n\n \/\/ Initialize the XML4C system\n try\n {\n XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, staticMemMonitor);\n }\n catch (const XMLException& toCatch)\n {\n char *msg = XMLString::transcode(toCatch.getMessage());\n XERCES_STD_QUALIFIER cerr << \"Error during initialization! :\\n\"\n << msg << XERCES_STD_QUALIFIER endl;\n XMLString::release(&msg);\n return 1;\n }\n\n \/\/ Check command line and extract arguments.\n if (argC < 2)\n {\n usage();\n return 1;\n }\n\n const char* xmlFile = 0;\n AbstractDOMParser::ValSchemes domBuilderValScheme = AbstractDOMParser::Val_Auto;\n bool doNamespaces = false;\n bool doSchema = false;\n bool schemaFullChecking = false;\n bool doList = false;\n int numReps =1;\n\n int argInd;\n for (argInd = 1; argInd < argC; argInd++)\n {\n \/\/ Break out on first parm not starting with a dash\n if (argV[argInd][0] != '-')\n break;\n\n \/\/ Watch for special case help request\n if (!strcmp(argV[argInd], \"-?\"))\n {\n usage();\n return 2;\n }\n else if (!strncmp(argV[argInd], \"-v=\", 3)\n || !strncmp(argV[argInd], \"-V=\", 3))\n {\n const char* const parm = &argV[argInd][3];\n\n if (!strcmp(parm, \"never\"))\n domBuilderValScheme = AbstractDOMParser::Val_Never;\n else if (!strcmp(parm, \"auto\"))\n domBuilderValScheme = AbstractDOMParser::Val_Auto;\n else if (!strcmp(parm, \"always\"))\n domBuilderValScheme = AbstractDOMParser::Val_Always;\n else\n {\n XERCES_STD_QUALIFIER cerr << \"Unknown -v= value: \" << parm << XERCES_STD_QUALIFIER endl;\n return 2;\n }\n }\n else if (!strcmp(argV[argInd], \"-n\")\n || !strcmp(argV[argInd], \"-N\"))\n {\n doNamespaces = true;\n }\n else if (!strcmp(argV[argInd], \"-s\")\n || !strcmp(argV[argInd], \"-S\"))\n {\n doSchema = true;\n }\n else if (!strcmp(argV[argInd], \"-f\")\n || !strcmp(argV[argInd], \"-F\"))\n {\n schemaFullChecking = true;\n }\n else if (!strcmp(argV[argInd], \"-l\")\n || !strcmp(argV[argInd], \"-L\"))\n {\n doList = true;\n }\n else if (!strncmp(argV[argInd], \"-r=\", 3)\n || !strncmp(argV[argInd], \"-R=\", 3))\n {\n const char* const numStr = &argV[argInd][3];\n XMLCh* numXStr = XMLString::transcode(numStr);\n numReps = XMLString::parseInt(numXStr);\n XMLString::release(&numXStr);\n }\n else\n {\n XERCES_STD_QUALIFIER cerr << \"Unknown option '\" << argV[argInd]\n << \"', ignoring it\\n\" << XERCES_STD_QUALIFIER endl;\n }\n }\n\n \/\/\n \/\/ There should be only one and only one parameter left, and that\n \/\/ should be the file name.\n \/\/\n if (argInd != argC - 1)\n {\n usage();\n return 1;\n }\n\n \/\/ Instantiate the DOM domBuilder with its memory manager.\n MemoryMonitor *domBuilderMemMonitor = new MemoryMonitor();\n static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };\n DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);\n DOMLSParser *domBuilder = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0, domBuilderMemMonitor);\n DOMLSParserHandler domBuilderHandler;\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, &domBuilderHandler);\n\n \/\/ Instantiate the SAX2 parser with its memory manager.\n MemoryMonitor *sax2MemMonitor = new MemoryMonitor();\n SAX2XMLReader *sax2parser = XMLReaderFactory::createXMLReader(sax2MemMonitor);\n SAXErrorHandler saxErrorHandler;\n sax2parser->setErrorHandler(&saxErrorHandler);\n\n \/\/ Instantiate the SAX 1 parser with its memory manager.\n MemoryMonitor *sax1MemMonitor = new MemoryMonitor();\n SAXParser *saxParser = new (sax1MemMonitor) SAXParser(0, sax1MemMonitor);\n saxParser->setErrorHandler(&saxErrorHandler);\n\n \/\/ set features \n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, doNamespaces);\n sax2parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces);\n saxParser->setDoNamespaces(doNamespaces);\n\n domBuilder->getDomConfig()->setParameter(XMLUni::fgXercesSchema, doSchema);\n sax2parser->setFeature(XMLUni::fgXercesSchema, doSchema);\n saxParser->setDoSchema(doSchema);\n\n domBuilder->getDomConfig()->setParameter(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);\n sax2parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);\n saxParser->setValidationSchemaFullChecking(schemaFullChecking);\n\n if (domBuilderValScheme == AbstractDOMParser::Val_Auto)\n {\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMValidateIfSchema, true);\n sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, true);\n sax2parser->setFeature(XMLUni::fgXercesDynamic, true);\n saxParser->setValidationScheme(SAXParser::Val_Auto);\n }\n else if (domBuilderValScheme == AbstractDOMParser::Val_Never)\n {\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMValidate, false);\n sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, false);\n saxParser->setValidationScheme(SAXParser::Val_Never);\n }\n else if (domBuilderValScheme == AbstractDOMParser::Val_Always)\n {\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true);\n sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, true);\n sax2parser->setFeature(XMLUni::fgXercesDynamic, false);\n saxParser->setValidationScheme(SAXParser::Val_Always);\n }\n\n \/\/ enable datatype normalization - default is off\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMDatatypeNormalization, true);\n\n XERCES_STD_QUALIFIER ifstream fin;\n bool more = true;\n\n \/\/ the input is a list file\n if (doList)\n fin.open(argV[argInd]);\n\n if (fin.fail()) {\n XERCES_STD_QUALIFIER cerr <<\"Cannot open the list file: \" << argV[argInd] << XERCES_STD_QUALIFIER endl;\n return 2;\n }\n\n while (more)\n {\n char fURI[1000];\n \/\/initialize the array to zeros\n memset(fURI,0,sizeof(fURI));\n\n if (doList) {\n if (! fin.eof() ) {\n fin.getline (fURI, sizeof(fURI));\n if (!*fURI)\n continue;\n else {\n xmlFile = fURI;\n XERCES_STD_QUALIFIER cerr << \"==Parsing== \" << xmlFile << XERCES_STD_QUALIFIER endl;\n }\n }\n else\n break;\n }\n else {\n xmlFile = argV[argInd];\n more = false;\n }\n\n \/\/ parse numReps times (in case we need it for some reason)\n for (int i=0; i<numReps; i++)\n {\n\n XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc = 0;\n\n try\n {\n \/\/ reset document pool\n domBuilder->resetDocumentPool();\n\n doc = domBuilder->parseURI(xmlFile);\n sax2parser->parse(xmlFile);\n saxParser->parse(xmlFile);\n }\n catch (const OutOfMemoryException&)\n {\n XERCES_STD_QUALIFIER cerr << \"OutOfMemoryException during parsing: '\" << xmlFile << \"'\\n\" << XERCES_STD_QUALIFIER endl;;\n continue;\n }\n catch (const XMLException& toCatch)\n {\n char *msg = XMLString::transcode(toCatch.getMessage()); \n XERCES_STD_QUALIFIER cerr << \"\\nError during parsing: '\" << xmlFile << \"'\\n\"\n << \"Exception message is: \\n\"\n << msg << \"\\n\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&msg);\n continue;\n }\n catch (const DOMException& toCatch)\n {\n const unsigned int maxChars = 2047;\n XMLCh errText[maxChars + 1];\n\n XERCES_STD_QUALIFIER cerr << \"\\nDOM Error during parsing: '\" << xmlFile << \"'\\n\"\n << \"DOMException code is: \" << toCatch.code << XERCES_STD_QUALIFIER endl;\n\n if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars))\n {\n char * msg = XMLString::transcode(errText); \n XERCES_STD_QUALIFIER cerr << \"Message is: \" << msg << XERCES_STD_QUALIFIER endl;\n\n continue;\n }\n }\n catch (...)\n {\n XERCES_STD_QUALIFIER cerr << \"\\nUnexpected exception during parsing: '\" << xmlFile << \"'\\n\";\n continue;\n }\n\n }\n }\n\n \/\/\n \/\/ Delete the domBuilder itself. Must be done prior to calling Terminate, below.\n \/\/\n domBuilder->release();\n delete sax2parser;\n delete saxParser;\n\n XERCES_STD_QUALIFIER cout << \"At destruction, domBuilderMemMonitor has \" << domBuilderMemMonitor->getTotalMemory() << \" bytes.\" << XERCES_STD_QUALIFIER endl;\n XERCES_STD_QUALIFIER cout << \"At destruction, sax2MemMonitor has \" << sax2MemMonitor->getTotalMemory() << \" bytes.\" << XERCES_STD_QUALIFIER endl;\n XERCES_STD_QUALIFIER cout << \"At destruction, sax1MemMonitor has \" << sax1MemMonitor->getTotalMemory() << \" bytes.\" << XERCES_STD_QUALIFIER endl;\n delete domBuilderMemMonitor;\n delete sax2MemMonitor;\n delete sax1MemMonitor;\n\n XMLPlatformUtils::Terminate();\n XERCES_STD_QUALIFIER cout << \"At destruction, staticMemMonitor has \" << staticMemMonitor->getTotalMemory() << \" bytes.\" << XERCES_STD_QUALIFIER endl;\n delete staticMemMonitor;\n return 0;\n}\n\n<commit_msg>Added missing #include<commit_after>\/*\n * Copyright 2003,2004 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 * $Id$\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \"MemoryMonitor.hpp\"\n#if defined(XERCES_NEW_IOSTREAMS)\n#include <iostream>\n#include <fstream>\n#else\n#include <iostream.h>\n#include <fstream.h>\n#endif\n#include <assert.h>\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/OutOfMemoryException.hpp>\n#include <xercesc\/dom\/DOM.hpp>\n\nvoid* MemoryMonitor::allocate(size_t size)\n{\n void *key = ::operator new(size);\n fHashTable->put(key, (unsigned int)size);\n return key;\n}\n\nvoid MemoryMonitor::deallocate(void* p)\n{\n \/\/ if fHashTable doesn't contain p, then this memory manager\n \/\/ didn't allocate that memory--a segfault waiting to happen...\n assert(p == 0 || fHashTable->get(p) != 0);\n if (p != 0)\n fHashTable->removeKey(p);\n ::operator delete(p);\n}\n\nunsigned int MemoryMonitor::getTotalMemory() \n{\n unsigned int total = 0;\n ValueHashTableOfEnumerator<unsigned int> *memEnum = \n new ValueHashTableOfEnumerator<unsigned int>(fHashTable);\n while(memEnum->hasMoreElements()) {\n total += memEnum->nextElement();\n }\n delete memEnum;\n return total;\n}\n\nstatic void usage()\n{\n XERCES_STD_QUALIFIER cout << \"\\nUsage:\\n\"\n \" MemHandlerTest [options] <XML file | List file>\\n\\n\"\n \"This program invokes the XercesDOMParser, DOMLSParser, SAXParser ,\\n\"\n \"and the SAX2XMLReader, and ensures that MemoryManagers set on these\\n\"\n \"domBuilders are called to delete just as many bytes as they allocate.\\n\"\n \"This is done for each XML file, and each file is processed\\n\"\n \"as many times as indicated.\\n\"\n \"Options:\\n\"\n \" -l Indicate the input file is a List File that has a list of xml files.\\n\"\n \" Default to off (Input file is an XML file).\\n\"\n \" -v=xxx Validation scheme [always | never | auto*].\\n\"\n \" -n Enable namespace processing. Defaults to off.\\n\"\n \" -s Enable schema processing. Defaults to off.\\n\"\n \" -f Enable full schema constraint checking. Defaults to off.\\n\"\n \" -r=n Run file through domBuilders n times.\\n\" \n\t\t \" -? Show this help.\\n\\n\"\n \" * = Default if not provided explicitly.\\n\"\n << XERCES_STD_QUALIFIER endl;\n}\n\nclass DOMLSParserHandler : public DOMErrorHandler \n{\npublic:\n DOMLSParserHandler() {};\n ~DOMLSParserHandler() {};\n bool handleError(const DOMError &error) \n {\n char *message = 0;\n XERCES_STD_QUALIFIER cerr << \"Error occurred in DOMBuilder! Message: \" << \n (message = XMLString::transcode(error.getMessage())) << \" of severity \" << error.getSeverity() << \".\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&message);\n return true;\n }\n};\n\nclass SAXErrorHandler : public ErrorHandler \n{\npublic:\n SAXErrorHandler() {};\n ~SAXErrorHandler() {};\n void warning(const SAXParseException &exc )\n {\n char *message = 0;\n XERCES_STD_QUALIFIER cerr << \"SAX warning received! Text: \" <<\n (message = XMLString::transcode(exc.getMessage())) << \".\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&message);\n }\n void error(const SAXParseException &exc )\n {\n char *message = 0;\n XERCES_STD_QUALIFIER cerr << \"SAX error received! Text: \" <<\n (message = XMLString::transcode(exc.getMessage())) << \".\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&message);\n }\n void fatalError(const SAXParseException &exc )\n {\n char *message = 0;\n XERCES_STD_QUALIFIER cerr << \"SAX fatalError received! Text: \" <<\n (message = XMLString::transcode(exc.getMessage())) << \".\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&message);\n }\n\n \/\/ no state so no body\n void resetErrors() {};\n};\n\n\/**\n * This utility takes similar parameters as DOMCount,\n * with similar meanings. The only difference is that it runs\n * the file(s) in question through a DOMParser, a DOMBuilder, a SAXParser and\n * a SAX2XMLReader, setting options as appropriate. It does this\n * sequentially, n times per file with a single domBuilder\n * object, and reports what it finds in terms of memory\n * allocations\/deallocations.\n *\/\n\nint main (int argC, char *argV[]) \n{\n\n MemoryMonitor *staticMemMonitor = new MemoryMonitor();\n\n \/\/ Initialize the XML4C system\n try\n {\n XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, staticMemMonitor);\n }\n catch (const XMLException& toCatch)\n {\n char *msg = XMLString::transcode(toCatch.getMessage());\n XERCES_STD_QUALIFIER cerr << \"Error during initialization! :\\n\"\n << msg << XERCES_STD_QUALIFIER endl;\n XMLString::release(&msg);\n return 1;\n }\n\n \/\/ Check command line and extract arguments.\n if (argC < 2)\n {\n usage();\n return 1;\n }\n\n const char* xmlFile = 0;\n AbstractDOMParser::ValSchemes domBuilderValScheme = AbstractDOMParser::Val_Auto;\n bool doNamespaces = false;\n bool doSchema = false;\n bool schemaFullChecking = false;\n bool doList = false;\n int numReps =1;\n\n int argInd;\n for (argInd = 1; argInd < argC; argInd++)\n {\n \/\/ Break out on first parm not starting with a dash\n if (argV[argInd][0] != '-')\n break;\n\n \/\/ Watch for special case help request\n if (!strcmp(argV[argInd], \"-?\"))\n {\n usage();\n return 2;\n }\n else if (!strncmp(argV[argInd], \"-v=\", 3)\n || !strncmp(argV[argInd], \"-V=\", 3))\n {\n const char* const parm = &argV[argInd][3];\n\n if (!strcmp(parm, \"never\"))\n domBuilderValScheme = AbstractDOMParser::Val_Never;\n else if (!strcmp(parm, \"auto\"))\n domBuilderValScheme = AbstractDOMParser::Val_Auto;\n else if (!strcmp(parm, \"always\"))\n domBuilderValScheme = AbstractDOMParser::Val_Always;\n else\n {\n XERCES_STD_QUALIFIER cerr << \"Unknown -v= value: \" << parm << XERCES_STD_QUALIFIER endl;\n return 2;\n }\n }\n else if (!strcmp(argV[argInd], \"-n\")\n || !strcmp(argV[argInd], \"-N\"))\n {\n doNamespaces = true;\n }\n else if (!strcmp(argV[argInd], \"-s\")\n || !strcmp(argV[argInd], \"-S\"))\n {\n doSchema = true;\n }\n else if (!strcmp(argV[argInd], \"-f\")\n || !strcmp(argV[argInd], \"-F\"))\n {\n schemaFullChecking = true;\n }\n else if (!strcmp(argV[argInd], \"-l\")\n || !strcmp(argV[argInd], \"-L\"))\n {\n doList = true;\n }\n else if (!strncmp(argV[argInd], \"-r=\", 3)\n || !strncmp(argV[argInd], \"-R=\", 3))\n {\n const char* const numStr = &argV[argInd][3];\n XMLCh* numXStr = XMLString::transcode(numStr);\n numReps = XMLString::parseInt(numXStr);\n XMLString::release(&numXStr);\n }\n else\n {\n XERCES_STD_QUALIFIER cerr << \"Unknown option '\" << argV[argInd]\n << \"', ignoring it\\n\" << XERCES_STD_QUALIFIER endl;\n }\n }\n\n \/\/\n \/\/ There should be only one and only one parameter left, and that\n \/\/ should be the file name.\n \/\/\n if (argInd != argC - 1)\n {\n usage();\n return 1;\n }\n\n \/\/ Instantiate the DOM domBuilder with its memory manager.\n MemoryMonitor *domBuilderMemMonitor = new MemoryMonitor();\n static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };\n DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);\n DOMLSParser *domBuilder = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0, domBuilderMemMonitor);\n DOMLSParserHandler domBuilderHandler;\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, &domBuilderHandler);\n\n \/\/ Instantiate the SAX2 parser with its memory manager.\n MemoryMonitor *sax2MemMonitor = new MemoryMonitor();\n SAX2XMLReader *sax2parser = XMLReaderFactory::createXMLReader(sax2MemMonitor);\n SAXErrorHandler saxErrorHandler;\n sax2parser->setErrorHandler(&saxErrorHandler);\n\n \/\/ Instantiate the SAX 1 parser with its memory manager.\n MemoryMonitor *sax1MemMonitor = new MemoryMonitor();\n SAXParser *saxParser = new (sax1MemMonitor) SAXParser(0, sax1MemMonitor);\n saxParser->setErrorHandler(&saxErrorHandler);\n\n \/\/ set features \n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, doNamespaces);\n sax2parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces);\n saxParser->setDoNamespaces(doNamespaces);\n\n domBuilder->getDomConfig()->setParameter(XMLUni::fgXercesSchema, doSchema);\n sax2parser->setFeature(XMLUni::fgXercesSchema, doSchema);\n saxParser->setDoSchema(doSchema);\n\n domBuilder->getDomConfig()->setParameter(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);\n sax2parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);\n saxParser->setValidationSchemaFullChecking(schemaFullChecking);\n\n if (domBuilderValScheme == AbstractDOMParser::Val_Auto)\n {\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMValidateIfSchema, true);\n sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, true);\n sax2parser->setFeature(XMLUni::fgXercesDynamic, true);\n saxParser->setValidationScheme(SAXParser::Val_Auto);\n }\n else if (domBuilderValScheme == AbstractDOMParser::Val_Never)\n {\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMValidate, false);\n sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, false);\n saxParser->setValidationScheme(SAXParser::Val_Never);\n }\n else if (domBuilderValScheme == AbstractDOMParser::Val_Always)\n {\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true);\n sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, true);\n sax2parser->setFeature(XMLUni::fgXercesDynamic, false);\n saxParser->setValidationScheme(SAXParser::Val_Always);\n }\n\n \/\/ enable datatype normalization - default is off\n domBuilder->getDomConfig()->setParameter(XMLUni::fgDOMDatatypeNormalization, true);\n\n XERCES_STD_QUALIFIER ifstream fin;\n bool more = true;\n\n \/\/ the input is a list file\n if (doList)\n fin.open(argV[argInd]);\n\n if (fin.fail()) {\n XERCES_STD_QUALIFIER cerr <<\"Cannot open the list file: \" << argV[argInd] << XERCES_STD_QUALIFIER endl;\n return 2;\n }\n\n while (more)\n {\n char fURI[1000];\n \/\/initialize the array to zeros\n memset(fURI,0,sizeof(fURI));\n\n if (doList) {\n if (! fin.eof() ) {\n fin.getline (fURI, sizeof(fURI));\n if (!*fURI)\n continue;\n else {\n xmlFile = fURI;\n XERCES_STD_QUALIFIER cerr << \"==Parsing== \" << xmlFile << XERCES_STD_QUALIFIER endl;\n }\n }\n else\n break;\n }\n else {\n xmlFile = argV[argInd];\n more = false;\n }\n\n \/\/ parse numReps times (in case we need it for some reason)\n for (int i=0; i<numReps; i++)\n {\n\n XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc = 0;\n\n try\n {\n \/\/ reset document pool\n domBuilder->resetDocumentPool();\n\n doc = domBuilder->parseURI(xmlFile);\n if(doc && doc->getDocumentElement())\n {\n XERCES_CPP_NAMESPACE_QUALIFIER DOMNodeList *list=NULL;\n if(doNamespaces)\n list=doc->getElementsByTagNameNS(doc->getDocumentElement()->getNamespaceURI(), doc->getDocumentElement()->getLocalName());\n else\n list=doc->getElementsByTagName(doc->getDocumentElement()->getNodeName());\n if(list==NULL)\n XERCES_STD_QUALIFIER cout << \"getElementsByTagName didn't return a valid DOMNodeList.\" << XERCES_STD_QUALIFIER endl;\n else if(list->item(0)!=doc->getDocumentElement())\n XERCES_STD_QUALIFIER cout << \"getElementsByTagName didn't find the root element.\" << XERCES_STD_QUALIFIER endl;\n }\n sax2parser->parse(xmlFile);\n saxParser->parse(xmlFile);\n }\n catch (const OutOfMemoryException&)\n {\n XERCES_STD_QUALIFIER cerr << \"OutOfMemoryException during parsing: '\" << xmlFile << \"'\\n\" << XERCES_STD_QUALIFIER endl;;\n continue;\n }\n catch (const XMLException& toCatch)\n {\n char *msg = XMLString::transcode(toCatch.getMessage()); \n XERCES_STD_QUALIFIER cerr << \"\\nError during parsing: '\" << xmlFile << \"'\\n\"\n << \"Exception message is: \\n\"\n << msg << \"\\n\" << XERCES_STD_QUALIFIER endl;\n XMLString::release(&msg);\n continue;\n }\n catch (const DOMException& toCatch)\n {\n const unsigned int maxChars = 2047;\n XMLCh errText[maxChars + 1];\n\n XERCES_STD_QUALIFIER cerr << \"\\nDOM Error during parsing: '\" << xmlFile << \"'\\n\"\n << \"DOMException code is: \" << toCatch.code << XERCES_STD_QUALIFIER endl;\n\n if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars))\n {\n char * msg = XMLString::transcode(errText); \n XERCES_STD_QUALIFIER cerr << \"Message is: \" << msg << XERCES_STD_QUALIFIER endl;\n\n continue;\n }\n }\n catch (...)\n {\n XERCES_STD_QUALIFIER cerr << \"\\nUnexpected exception during parsing: '\" << xmlFile << \"'\\n\";\n continue;\n }\n\n }\n }\n\n \/\/\n \/\/ Delete the domBuilder itself. Must be done prior to calling Terminate, below.\n \/\/\n domBuilder->release();\n delete sax2parser;\n delete saxParser;\n\n XERCES_STD_QUALIFIER cout << \"At destruction, domBuilderMemMonitor has \" << domBuilderMemMonitor->getTotalMemory() << \" bytes.\" << XERCES_STD_QUALIFIER endl;\n XERCES_STD_QUALIFIER cout << \"At destruction, sax2MemMonitor has \" << sax2MemMonitor->getTotalMemory() << \" bytes.\" << XERCES_STD_QUALIFIER endl;\n XERCES_STD_QUALIFIER cout << \"At destruction, sax1MemMonitor has \" << sax1MemMonitor->getTotalMemory() << \" bytes.\" << XERCES_STD_QUALIFIER endl;\n delete domBuilderMemMonitor;\n delete sax2MemMonitor;\n delete sax1MemMonitor;\n\n XMLPlatformUtils::Terminate();\n XERCES_STD_QUALIFIER cout << \"At destruction, staticMemMonitor has \" << staticMemMonitor->getTotalMemory() << \" bytes.\" << XERCES_STD_QUALIFIER endl;\n delete staticMemMonitor;\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"builtin\/object.hpp\"\n#include \"builtin\/array.hpp\"\n#include \"builtin\/block_environment.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/compiledmethod.hpp\"\n#include \"builtin\/contexts.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/sendsite.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/symbol.hpp\"\n#include \"builtin\/task.hpp\"\n#include \"builtin\/tuple.hpp\"\n#include \"builtin\/iseq.hpp\"\n#include \"builtin\/staticscope.hpp\"\n\n#include \"jit_state.h\"\n#include \"objectmemory.hpp\"\n\nusing namespace rubinius;\n\n#define OP(name, args...) void name(Task* task, struct jit_state* const js, ## args)\n#define OP2(type, name, args...) type name(Task* task, struct jit_state* const js, ## args)\n\/\/ HACK: sassert is stack protection\n#define stack_push(val) sassert(val); *++js->stack = val\n#define stack_pop() *js->stack--\n#define stack_top() *js->stack\n#define stack_back(count) *(js->stack - count)\n#define stack_set_top(val) *js->stack = (val)\n\n#define SHOW(obj) (((NormalObject*)(obj))->show(state))\n\n#define state task->state\n\n#define I2N(num) APPLY_TAG(num, TAG_FIXNUM)\n#define both_fixnum_p(_p1, _p2) ((intptr_t)_p1 & (intptr_t)_p2 & TAG_FIXNUM)\n\n#define cache_ip()\n\nextern \"C\" {\n bool send_slowly(Task* task, struct jit_state* const js, SYMBOL name, size_t args);\n\n#ruby <<CODE\nrequire 'stringio'\nrequire 'vm\/instructions.rb'\nsi = Instructions.new\nimpl = si.decode_methods\nio = StringIO.new\nsi.generate_functions impl, io\nputs io.string\nCODE\n\n\/*\n OP2(bool, fixed_args_prelude, size_t required) {\n Message* const msg = task->msg;\n\n if(msg->args != required) {\n return false;\n }\n\n MethodContext* ctx = MethodContext::create(state, msg->recv, original.get());\n task->make_active(ctx);\n\n for(size_t i = 0; i < required; i++) {\n ctx->stack->put(task->state, i, msg->get_argument(i));\n }\n\n return true;\n }\n\n OP2(bool, zero_args_prelude) {\n Message* const msg = task->msg;\n if(task->msg.args != 0) return false;\n\n MethodContext* ctx = MethodContext::create(state, msg->recv, original.get());\n task->make_active(ctx);\n return true;\n }\n\n OP2(bool, full_prelude) {\n task->import_arguments(task->ctx, *task->msg);\n }\n\n *\/\n\n OP2(bool, jit_goto_if_false) {\n OBJECT val = stack_pop();\n return !RTEST(val);\n }\n \n OP2(bool, jit_goto_if_true) {\n OBJECT val = stack_pop();\n return RTEST(val);\n }\n\n OP2(bool, jit_goto_if_defined) {\n OBJECT val = stack_pop();\n return val != Qundef;\n }\n\n bool send_slowly(Task* task, struct jit_state* const js, SYMBOL name, size_t args) {\n Message& msg = *task->msg;\n msg.recv = stack_back(args);\n msg.import_arguments(state, task, args);\n msg.name = name;\n msg.lookup_from = msg.recv->lookup_begin(state);\n msg.block = Qnil;\n msg.stack = args + 1;\n\n bool res = task->send_message_slowly(msg);\n msg.reset();\n return res;\n }\n}\n\n\/* A simple interface to the instructions by directly\n * executing an opcode stream. This is used primarly to\n * debug instructions. *\/\n\n#define next_op() *stream++\n#define next_int (opcode)(next_op())\n\nvoid rubinius::Task::execute_stream(opcode* stream) {\n opcode op;\n Task* task = this;\n struct jit_state* js = &active->js;\n\n op = next_op();\n\n#ruby <<CODE\nio = StringIO.new\nsi.generate_decoder_switch impl, io\nputs io.string\nCODE\n\n}\n\n\/* Use a simplier next_int *\/\n#undef next_int\n#define next_int ((opcode)(stream[ctx->ip++]))\n\nvoid VMMethod::resume(Task* task, MethodContext* ctx) {\n opcode* stream = ctx->vmm->opcodes;\n struct jit_state* js = &ctx->js;\n opcode op;\n\n for(;;) {\n op = stream[ctx->ip++];\n#if 0\n printf(\"%-22s+%3d: %-30s %10d %10p\\n\",\n ctx->cm->name->to_str(state)->c_str(),\n ctx->ip, InstructionSequence::get_instruction_name(op),\n js->stack - ctx->stk, *js->stack);\n#endif\n\n#ruby <<CODE\nio = StringIO.new\nsi.generate_decoder_switch impl, io, true\nputs io.string\nCODE\n }\n\n}\n<commit_msg>Adjust field widths to be more sane<commit_after>\n#include \"builtin\/object.hpp\"\n#include \"builtin\/array.hpp\"\n#include \"builtin\/block_environment.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/compiledmethod.hpp\"\n#include \"builtin\/contexts.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/sendsite.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/symbol.hpp\"\n#include \"builtin\/task.hpp\"\n#include \"builtin\/tuple.hpp\"\n#include \"builtin\/iseq.hpp\"\n#include \"builtin\/staticscope.hpp\"\n\n#include \"jit_state.h\"\n#include \"objectmemory.hpp\"\n\nusing namespace rubinius;\n\n#define OP(name, args...) void name(Task* task, struct jit_state* const js, ## args)\n#define OP2(type, name, args...) type name(Task* task, struct jit_state* const js, ## args)\n\/\/ HACK: sassert is stack protection\n#define stack_push(val) sassert(val); *++js->stack = val\n#define stack_pop() *js->stack--\n#define stack_top() *js->stack\n#define stack_back(count) *(js->stack - count)\n#define stack_set_top(val) *js->stack = (val)\n\n#define SHOW(obj) (((NormalObject*)(obj))->show(state))\n\n#define state task->state\n\n#define I2N(num) APPLY_TAG(num, TAG_FIXNUM)\n#define both_fixnum_p(_p1, _p2) ((intptr_t)_p1 & (intptr_t)_p2 & TAG_FIXNUM)\n\n#define cache_ip()\n\nextern \"C\" {\n bool send_slowly(Task* task, struct jit_state* const js, SYMBOL name, size_t args);\n\n#ruby <<CODE\nrequire 'stringio'\nrequire 'vm\/instructions.rb'\nsi = Instructions.new\nimpl = si.decode_methods\nio = StringIO.new\nsi.generate_functions impl, io\nputs io.string\nCODE\n\n\/*\n OP2(bool, fixed_args_prelude, size_t required) {\n Message* const msg = task->msg;\n\n if(msg->args != required) {\n return false;\n }\n\n MethodContext* ctx = MethodContext::create(state, msg->recv, original.get());\n task->make_active(ctx);\n\n for(size_t i = 0; i < required; i++) {\n ctx->stack->put(task->state, i, msg->get_argument(i));\n }\n\n return true;\n }\n\n OP2(bool, zero_args_prelude) {\n Message* const msg = task->msg;\n if(task->msg.args != 0) return false;\n\n MethodContext* ctx = MethodContext::create(state, msg->recv, original.get());\n task->make_active(ctx);\n return true;\n }\n\n OP2(bool, full_prelude) {\n task->import_arguments(task->ctx, *task->msg);\n }\n\n *\/\n\n OP2(bool, jit_goto_if_false) {\n OBJECT val = stack_pop();\n return !RTEST(val);\n }\n \n OP2(bool, jit_goto_if_true) {\n OBJECT val = stack_pop();\n return RTEST(val);\n }\n\n OP2(bool, jit_goto_if_defined) {\n OBJECT val = stack_pop();\n return val != Qundef;\n }\n\n bool send_slowly(Task* task, struct jit_state* const js, SYMBOL name, size_t args) {\n Message& msg = *task->msg;\n msg.recv = stack_back(args);\n msg.import_arguments(state, task, args);\n msg.name = name;\n msg.lookup_from = msg.recv->lookup_begin(state);\n msg.block = Qnil;\n msg.stack = args + 1;\n\n bool res = task->send_message_slowly(msg);\n msg.reset();\n return res;\n }\n}\n\n\/* A simple interface to the instructions by directly\n * executing an opcode stream. This is used primarly to\n * debug instructions. *\/\n\n#define next_op() *stream++\n#define next_int (opcode)(next_op())\n\nvoid rubinius::Task::execute_stream(opcode* stream) {\n opcode op;\n Task* task = this;\n struct jit_state* js = &active->js;\n\n op = next_op();\n\n#ruby <<CODE\nio = StringIO.new\nsi.generate_decoder_switch impl, io\nputs io.string\nCODE\n\n}\n\n\/* Use a simplier next_int *\/\n#undef next_int\n#define next_int ((opcode)(stream[ctx->ip++]))\n\nvoid VMMethod::resume(Task* task, MethodContext* ctx) {\n opcode* stream = ctx->vmm->opcodes;\n struct jit_state* js = &ctx->js;\n opcode op;\n\n for(;;) {\n op = stream[ctx->ip++];\n#if 0\n printf(\"%-27s+%4d: %-30s %4d %10p\\n\",\n ctx->cm->name->to_str(state)->c_str(),\n ctx->ip, InstructionSequence::get_instruction_name(op),\n js->stack - ctx->stk, *js->stack);\n#endif\n\n#ruby <<CODE\nio = StringIO.new\nsi.generate_decoder_switch impl, io, true\nputs io.string\nCODE\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2009, Willow Garage, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice,\n * 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 names of Stanford University or Willow Garage, Inc. 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 \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"ros\/spinner.h\"\n#include \"ros\/ros.h\"\n#include \"ros\/callback_queue.h\"\n\n#include <boost\/thread\/thread.hpp>\n\nnamespace ros\n{\n\nextern CallbackQueue g_global_queue;\n\nvoid SingleThreadedSpinner::spin(CallbackQueue* queue)\n{\n ros::WallDuration d(0.01f);\n\n if (!queue)\n {\n queue = &g_global_queue;\n }\n\n ros::NodeHandle n;\n while (n.ok())\n {\n queue->callAvailable();\n }\n}\n\nMultiThreadedSpinner::MultiThreadedSpinner(uint32_t thread_count)\n{\n if (thread_count == 0)\n {\n thread_count = boost::thread::hardware_concurrency();\n\n if (thread_count == 0)\n {\n thread_count = 1;\n }\n }\n\n thread_count_ = thread_count;\n}\n\nvoid spinThreadFunc(CallbackQueue* queue)\n{\n disableAllSignalsInThisThread();\n\n ros::WallDuration d(0.01f);\n\n ros::NodeHandle n;\n while (n.ok())\n {\n queue->callOne();\n }\n}\n\nvoid MultiThreadedSpinner::spin(CallbackQueue* queue)\n{\n if (!queue)\n {\n queue = &g_global_queue;\n }\n\n boost::thread_group tg;\n for (uint32_t i = 0; i < thread_count_; ++i)\n {\n tg.create_thread(boost::bind(spinThreadFunc, queue));\n }\n\n tg.join_all();\n}\n\nclass AsyncSpinnerImpl\n{\npublic:\n AsyncSpinnerImpl(uint32_t thread_count, CallbackQueue* queue);\n ~AsyncSpinnerImpl();\n void start();\n void stop();\n\nprivate:\n void threadFunc();\n\n boost::mutex mutex_;\n boost::thread_group threads_;\n\n uint32_t thread_count_;\n CallbackQueue* callback_queue_;\n\n volatile bool continue_;\n\n ros::NodeHandle nh_;\n};\n\nAsyncSpinnerImpl::AsyncSpinnerImpl(uint32_t thread_count, CallbackQueue* queue)\n: thread_count_(thread_count)\n, callback_queue_(queue)\n, continue_(false)\n{\n if (thread_count == 0)\n {\n thread_count_ = boost::thread::hardware_concurrency();\n }\n\n if (!queue)\n {\n callback_queue_ = &g_global_queue;\n }\n}\n\nAsyncSpinnerImpl::~AsyncSpinnerImpl()\n{\n stop();\n}\n\nvoid AsyncSpinnerImpl::start()\n{\n boost::mutex::scoped_lock lock(mutex_);\n if (continue_)\n {\n return;\n }\n\n continue_ = true;\n\n for (uint32_t i = 0; i < thread_count_; ++i)\n {\n threads_.create_thread(boost::bind(&AsyncSpinnerImpl::threadFunc, this));\n }\n}\n\nvoid AsyncSpinnerImpl::stop()\n{\n boost::mutex::scoped_lock lock(mutex_);\n if (!continue_)\n {\n return;\n }\n\n continue_ = false;\n threads_.join_all();\n}\n\nvoid AsyncSpinnerImpl::threadFunc()\n{\n CallbackQueue* queue = callback_queue_;\n bool use_call_available = thread_count_ == 1;\n WallDuration timeout(0.01);\n\n while (continue_ && nh_.ok())\n {\n if (use_call_available)\n {\n queue->callAvailable(timeout);\n }\n else\n {\n queue->callOne(timeout);\n }\n }\n}\n\nAsyncSpinner::AsyncSpinner(uint32_t thread_count)\n: impl_(new AsyncSpinnerImpl(thread_count, 0))\n{\n}\n\nAsyncSpinner::AsyncSpinner(uint32_t thread_count, CallbackQueue* queue)\n: impl_(new AsyncSpinnerImpl(thread_count, queue))\n{\n}\n\nvoid AsyncSpinner::start()\n{\n impl_->start();\n}\n\nvoid AsyncSpinner::stop()\n{\n impl_->stop();\n}\n\n}\n<commit_msg>Reimplement MultiThreadedSpinner in terms of AsyncSpinner<commit_after>\/*\n * Copyright (C) 2009, Willow Garage, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice,\n * 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 names of Stanford University or Willow Garage, Inc. 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 \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"ros\/spinner.h\"\n#include \"ros\/ros.h\"\n#include \"ros\/callback_queue.h\"\n\n#include <boost\/thread\/thread.hpp>\n\nnamespace ros\n{\n\nextern CallbackQueue g_global_queue;\n\nvoid SingleThreadedSpinner::spin(CallbackQueue* queue)\n{\n ros::WallDuration d(0.01f);\n\n if (!queue)\n {\n queue = &g_global_queue;\n }\n\n ros::NodeHandle n;\n while (n.ok())\n {\n queue->callAvailable();\n }\n}\n\nMultiThreadedSpinner::MultiThreadedSpinner(uint32_t thread_count)\n: thread_count_(thread_count)\n{\n}\n\nvoid MultiThreadedSpinner::spin(CallbackQueue* queue)\n{\n AsyncSpinner s(thread_count_, queue);\n s.start();\n\n ros::waitForShutdown();\n}\n\nclass AsyncSpinnerImpl\n{\npublic:\n AsyncSpinnerImpl(uint32_t thread_count, CallbackQueue* queue);\n ~AsyncSpinnerImpl();\n void start();\n void stop();\n\nprivate:\n void threadFunc();\n\n boost::mutex mutex_;\n boost::thread_group threads_;\n\n uint32_t thread_count_;\n CallbackQueue* callback_queue_;\n\n volatile bool continue_;\n\n ros::NodeHandle nh_;\n};\n\nAsyncSpinnerImpl::AsyncSpinnerImpl(uint32_t thread_count, CallbackQueue* queue)\n: thread_count_(thread_count)\n, callback_queue_(queue)\n, continue_(false)\n{\n if (thread_count == 0)\n {\n thread_count_ = boost::thread::hardware_concurrency();\n\n if (thread_count_ == 0)\n {\n thread_count_ = 1;\n }\n }\n\n if (!queue)\n {\n callback_queue_ = &g_global_queue;\n }\n}\n\nAsyncSpinnerImpl::~AsyncSpinnerImpl()\n{\n stop();\n}\n\nvoid AsyncSpinnerImpl::start()\n{\n boost::mutex::scoped_lock lock(mutex_);\n if (continue_)\n {\n return;\n }\n\n continue_ = true;\n\n for (uint32_t i = 0; i < thread_count_; ++i)\n {\n threads_.create_thread(boost::bind(&AsyncSpinnerImpl::threadFunc, this));\n }\n}\n\nvoid AsyncSpinnerImpl::stop()\n{\n boost::mutex::scoped_lock lock(mutex_);\n if (!continue_)\n {\n return;\n }\n\n continue_ = false;\n threads_.join_all();\n}\n\nvoid AsyncSpinnerImpl::threadFunc()\n{\n disableAllSignalsInThisThread();\n\n CallbackQueue* queue = callback_queue_;\n bool use_call_available = thread_count_ == 1;\n WallDuration timeout(0.01);\n\n while (continue_ && nh_.ok())\n {\n if (use_call_available)\n {\n queue->callAvailable(timeout);\n }\n else\n {\n queue->callOne(timeout);\n }\n }\n}\n\nAsyncSpinner::AsyncSpinner(uint32_t thread_count)\n: impl_(new AsyncSpinnerImpl(thread_count, 0))\n{\n}\n\nAsyncSpinner::AsyncSpinner(uint32_t thread_count, CallbackQueue* queue)\n: impl_(new AsyncSpinnerImpl(thread_count, queue))\n{\n}\n\nvoid AsyncSpinner::start()\n{\n impl_->start();\n}\n\nvoid AsyncSpinner::stop()\n{\n impl_->stop();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"charttest.hxx\"\n\n#include <com\/sun\/star\/chart\/ErrorBarStyle.hpp>\n#include <com\/sun\/star\/chart2\/XRegressionCurveContainer.hpp>\n#include <com\/sun\/star\/lang\/XServiceName.hpp>\n\nusing uno::Reference;\nusing beans::XPropertySet;\n\nclass Chart2ExportTest : public ChartTest\n{\npublic:\n void test();\n void testErrorBarXLSX();\n void testTrendline();\n\n CPPUNIT_TEST_SUITE(Chart2ExportTest);\n CPPUNIT_TEST(test);\n CPPUNIT_TEST(testErrorBarXLSX);\n CPPUNIT_TEST(testTrendline);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n};\n\nvoid Chart2ExportTest::test()\n{\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"simple_export_chart.ods\");\n reload(\"Calc Office Open XML\");\n}\n\nnamespace {\n\nvoid testErrorBar( Reference< XPropertySet > xErrorBar )\n{\n sal_Int32 nErrorBarStyle;\n CPPUNIT_ASSERT(\n xErrorBar->getPropertyValue(\"ErrorBarStyle\") >>= nErrorBarStyle);\n CPPUNIT_ASSERT_EQUAL(nErrorBarStyle, chart::ErrorBarStyle::RELATIVE);\n bool bShowPositive = bool(), bShowNegative = bool();\n CPPUNIT_ASSERT(\n xErrorBar->getPropertyValue(\"ShowPositiveError\") >>= bShowPositive);\n CPPUNIT_ASSERT(bShowPositive);\n CPPUNIT_ASSERT(\n xErrorBar->getPropertyValue(\"ShowNegativeError\") >>= bShowNegative);\n CPPUNIT_ASSERT(bShowNegative);\n double nVal = 0.0;\n CPPUNIT_ASSERT(xErrorBar->getPropertyValue(\"PositiveError\") >>= nVal);\n CPPUNIT_ASSERT_DOUBLES_EQUAL(nVal, 10.0, 1e-10);\n}\n\nvoid checkCommonTrendline(\n Reference<chart2::XRegressionCurve> xCurve,\n double aExpectedExtrapolateForward, double aExpectedExtrapolateBackward,\n sal_Bool aExpectedForceIntercept, double aExpectedInterceptValue,\n sal_Bool aExpectedShowEquation, sal_Bool aExpectedR2)\n{\n Reference<XPropertySet> xProperties( xCurve , uno::UNO_QUERY );\n CPPUNIT_ASSERT(xProperties.is());\n\n double aExtrapolateForward = 0.0;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"ExtrapolateForward\") >>= aExtrapolateForward);\n CPPUNIT_ASSERT_EQUAL(aExpectedExtrapolateForward, aExtrapolateForward);\n\n double aExtrapolateBackward = 0.0;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"ExtrapolateBackward\") >>= aExtrapolateBackward);\n CPPUNIT_ASSERT_EQUAL(aExpectedExtrapolateBackward, aExtrapolateBackward);\n\n sal_Bool aForceIntercept = false;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"ForceIntercept\") >>= aForceIntercept);\n CPPUNIT_ASSERT_EQUAL(aExpectedForceIntercept, aForceIntercept);\n\n if (aForceIntercept)\n {\n double aInterceptValue = 0.0;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"InterceptValue\") >>= aInterceptValue);\n CPPUNIT_ASSERT_EQUAL(aExpectedInterceptValue, aInterceptValue);\n }\n\n Reference< XPropertySet > xEquationProperties( xCurve->getEquationProperties() );\n CPPUNIT_ASSERT(xEquationProperties.is());\n\n sal_Bool aShowEquation = false;\n CPPUNIT_ASSERT(xEquationProperties->getPropertyValue(\"ShowEquation\") >>= aShowEquation);\n CPPUNIT_ASSERT_EQUAL(aExpectedShowEquation, aShowEquation);\n\n sal_Bool aShowCorrelationCoefficient = false;\n CPPUNIT_ASSERT(xEquationProperties->getPropertyValue(\"ShowCorrelationCoefficient\") >>= aShowCorrelationCoefficient);\n CPPUNIT_ASSERT_EQUAL(aExpectedR2, aShowCorrelationCoefficient);\n}\n\nvoid checkNameAndType(Reference<XPropertySet> xProperties, OUString aExpectedName, OUString aExpectedServiceName)\n{\n Reference< lang::XServiceName > xServiceName( xProperties, UNO_QUERY );\n CPPUNIT_ASSERT(xServiceName.is());\n\n OUString aServiceName = xServiceName->getServiceName();\n CPPUNIT_ASSERT_EQUAL(aExpectedServiceName, aServiceName);\n\n OUString aCurveName;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"CurveName\") >>= aCurveName);\n CPPUNIT_ASSERT_EQUAL(aExpectedName, aCurveName);\n}\n\nvoid checkLinearTrendline(\n Reference<chart2::XRegressionCurve> xCurve, OUString aExpectedName,\n double aExpectedExtrapolateForward, double aExpectedExtrapolateBackward,\n sal_Bool aExpectedForceIntercept, double aExpectedInterceptValue,\n sal_Bool aExpectedShowEquation, sal_Bool aExpectedR2)\n{\n Reference<XPropertySet> xProperties( xCurve , uno::UNO_QUERY );\n CPPUNIT_ASSERT(xProperties.is());\n\n checkNameAndType(xProperties, aExpectedName, \"com.sun.star.chart2.LinearRegressionCurve\");\n\n checkCommonTrendline(\n xCurve,\n aExpectedExtrapolateForward, aExpectedExtrapolateBackward,\n aExpectedForceIntercept, aExpectedInterceptValue,\n aExpectedShowEquation, aExpectedR2);\n}\n\nvoid checkPolynomialTrendline(\n Reference<chart2::XRegressionCurve> xCurve, OUString aExpectedName,\n sal_Int32 aExpectedDegree,\n double aExpectedExtrapolateForward, double aExpectedExtrapolateBackward,\n sal_Bool aExpectedForceIntercept, double aExpectedInterceptValue,\n sal_Bool aExpectedShowEquation, sal_Bool aExpectedR2)\n{\n Reference<XPropertySet> xProperties( xCurve , uno::UNO_QUERY );\n CPPUNIT_ASSERT(xProperties.is());\n\n checkNameAndType(xProperties, aExpectedName, \"com.sun.star.chart2.PolynomialRegressionCurve\");\n\n sal_Int32 aDegree = 2;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"PolynomialDegree\") >>= aDegree);\n CPPUNIT_ASSERT_EQUAL(aExpectedDegree, aDegree);\n\n checkCommonTrendline(\n xCurve,\n aExpectedExtrapolateForward, aExpectedExtrapolateBackward,\n aExpectedForceIntercept, aExpectedInterceptValue,\n aExpectedShowEquation, aExpectedR2);\n}\n\nvoid checkMovingAverageTrendline(\n Reference<chart2::XRegressionCurve> xCurve, OUString aExpectedName, sal_Int32 aExpectedPeriod)\n{\n Reference<XPropertySet> xProperties( xCurve , uno::UNO_QUERY );\n CPPUNIT_ASSERT(xProperties.is());\n\n checkNameAndType(xProperties, aExpectedName, \"com.sun.star.chart2.MovingAverageRegressionCurve\");\n\n sal_Int32 aPeriod = 2;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"MovingAveragePeriod\") >>= aPeriod);\n CPPUNIT_ASSERT_EQUAL(aExpectedPeriod, aPeriod);\n}\n\nvoid checkTrendlinesInChart(uno::Reference< chart2::XChartDocument > xChartDoc)\n{\n CPPUNIT_ASSERT(xChartDoc.is());\n\n Reference< chart2::XDataSeries > xDataSeries = getDataSeriesFromDoc( xChartDoc, 0 );\n CPPUNIT_ASSERT( xDataSeries.is() );\n\n Reference< chart2::XRegressionCurveContainer > xRegressionCurveContainer( xDataSeries, UNO_QUERY );\n CPPUNIT_ASSERT( xRegressionCurveContainer.is() );\n\n Sequence< Reference< chart2::XRegressionCurve > > xRegressionCurveSequence = xRegressionCurveContainer->getRegressionCurves();\n CPPUNIT_ASSERT_EQUAL(3, xRegressionCurveSequence.getLength());\n\n Reference<chart2::XRegressionCurve> xCurve;\n\n xCurve = xRegressionCurveSequence[0];\n CPPUNIT_ASSERT(xCurve.is());\n checkPolynomialTrendline(xCurve, \"col2_poly\", 3, 0.1, -0.1, true, -1.0, true, true);\n\n xCurve = xRegressionCurveSequence[1];\n CPPUNIT_ASSERT(xCurve.is());\n checkLinearTrendline(xCurve, \"col2_linear\", -0.5, -0.5, false, 0.0, true, false);\n\n xCurve = xRegressionCurveSequence[2];\n CPPUNIT_ASSERT(xCurve.is());\n checkMovingAverageTrendline(xCurve, \"col2_moving_avg\", 3);\n}\n\n}\n\n\/\/ improve the test\nvoid Chart2ExportTest::testErrorBarXLSX()\n{\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"error_bar.ods\");\n {\n \/\/ make sure the ODS import was successful\n uno::Reference< chart2::XChartDocument > xChartDoc = getChartDocFromSheet( 0, mxComponent );\n CPPUNIT_ASSERT(xChartDoc.is());\n\n Reference< chart2::XDataSeries > xDataSeries = getDataSeriesFromDoc( xChartDoc, 0 );\n CPPUNIT_ASSERT( xDataSeries.is() );\n\n Reference< beans::XPropertySet > xPropSet( xDataSeries, UNO_QUERY_THROW );\n CPPUNIT_ASSERT( xPropSet.is() );\n\n \/\/ test that y error bars are there\n Reference< beans::XPropertySet > xErrorBarYProps;\n xPropSet->getPropertyValue(\"ErrorBarY\") >>= xErrorBarYProps;\n testErrorBar(xErrorBarYProps);\n }\n\n reload(\"Calc Office Open XML\");\n {\n uno::Reference< chart2::XChartDocument > xChartDoc = getChartDocFromSheet( 0, mxComponent );\n CPPUNIT_ASSERT(xChartDoc.is());\n\n Reference< chart2::XDataSeries > xDataSeries = getDataSeriesFromDoc( xChartDoc, 0 );\n CPPUNIT_ASSERT( xDataSeries.is() );\n\n Reference< beans::XPropertySet > xPropSet( xDataSeries, UNO_QUERY_THROW );\n CPPUNIT_ASSERT( xPropSet.is() );\n\n \/\/ test that y error bars are there\n Reference< beans::XPropertySet > xErrorBarYProps;\n xPropSet->getPropertyValue(\"ErrorBarY\") >>= xErrorBarYProps;\n testErrorBar(xErrorBarYProps);\n }\n}\n\n\/\/ This method tests the preservation of properties for trendlines \/ regression curves\n\/\/ in an export -> import cycle using different file formats - ODS, XLS and XLSX.\nvoid Chart2ExportTest::testTrendline()\n{\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"trendline.ods\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n reload(\"calc8\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"trendline.ods\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n reload(\"Calc Office Open XML\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"trendline.ods\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n reload(\"MS Excel 97\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(Chart2ExportTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Blind fix for sal_Int32\/int confusion<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"charttest.hxx\"\n\n#include <com\/sun\/star\/chart\/ErrorBarStyle.hpp>\n#include <com\/sun\/star\/chart2\/XRegressionCurveContainer.hpp>\n#include <com\/sun\/star\/lang\/XServiceName.hpp>\n\nusing uno::Reference;\nusing beans::XPropertySet;\n\nclass Chart2ExportTest : public ChartTest\n{\npublic:\n void test();\n void testErrorBarXLSX();\n void testTrendline();\n\n CPPUNIT_TEST_SUITE(Chart2ExportTest);\n CPPUNIT_TEST(test);\n CPPUNIT_TEST(testErrorBarXLSX);\n CPPUNIT_TEST(testTrendline);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n};\n\nvoid Chart2ExportTest::test()\n{\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"simple_export_chart.ods\");\n reload(\"Calc Office Open XML\");\n}\n\nnamespace {\n\nvoid testErrorBar( Reference< XPropertySet > xErrorBar )\n{\n sal_Int32 nErrorBarStyle;\n CPPUNIT_ASSERT(\n xErrorBar->getPropertyValue(\"ErrorBarStyle\") >>= nErrorBarStyle);\n CPPUNIT_ASSERT_EQUAL(nErrorBarStyle, chart::ErrorBarStyle::RELATIVE);\n bool bShowPositive = bool(), bShowNegative = bool();\n CPPUNIT_ASSERT(\n xErrorBar->getPropertyValue(\"ShowPositiveError\") >>= bShowPositive);\n CPPUNIT_ASSERT(bShowPositive);\n CPPUNIT_ASSERT(\n xErrorBar->getPropertyValue(\"ShowNegativeError\") >>= bShowNegative);\n CPPUNIT_ASSERT(bShowNegative);\n double nVal = 0.0;\n CPPUNIT_ASSERT(xErrorBar->getPropertyValue(\"PositiveError\") >>= nVal);\n CPPUNIT_ASSERT_DOUBLES_EQUAL(nVal, 10.0, 1e-10);\n}\n\nvoid checkCommonTrendline(\n Reference<chart2::XRegressionCurve> xCurve,\n double aExpectedExtrapolateForward, double aExpectedExtrapolateBackward,\n sal_Bool aExpectedForceIntercept, double aExpectedInterceptValue,\n sal_Bool aExpectedShowEquation, sal_Bool aExpectedR2)\n{\n Reference<XPropertySet> xProperties( xCurve , uno::UNO_QUERY );\n CPPUNIT_ASSERT(xProperties.is());\n\n double aExtrapolateForward = 0.0;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"ExtrapolateForward\") >>= aExtrapolateForward);\n CPPUNIT_ASSERT_EQUAL(aExpectedExtrapolateForward, aExtrapolateForward);\n\n double aExtrapolateBackward = 0.0;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"ExtrapolateBackward\") >>= aExtrapolateBackward);\n CPPUNIT_ASSERT_EQUAL(aExpectedExtrapolateBackward, aExtrapolateBackward);\n\n sal_Bool aForceIntercept = false;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"ForceIntercept\") >>= aForceIntercept);\n CPPUNIT_ASSERT_EQUAL(aExpectedForceIntercept, aForceIntercept);\n\n if (aForceIntercept)\n {\n double aInterceptValue = 0.0;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"InterceptValue\") >>= aInterceptValue);\n CPPUNIT_ASSERT_EQUAL(aExpectedInterceptValue, aInterceptValue);\n }\n\n Reference< XPropertySet > xEquationProperties( xCurve->getEquationProperties() );\n CPPUNIT_ASSERT(xEquationProperties.is());\n\n sal_Bool aShowEquation = false;\n CPPUNIT_ASSERT(xEquationProperties->getPropertyValue(\"ShowEquation\") >>= aShowEquation);\n CPPUNIT_ASSERT_EQUAL(aExpectedShowEquation, aShowEquation);\n\n sal_Bool aShowCorrelationCoefficient = false;\n CPPUNIT_ASSERT(xEquationProperties->getPropertyValue(\"ShowCorrelationCoefficient\") >>= aShowCorrelationCoefficient);\n CPPUNIT_ASSERT_EQUAL(aExpectedR2, aShowCorrelationCoefficient);\n}\n\nvoid checkNameAndType(Reference<XPropertySet> xProperties, OUString aExpectedName, OUString aExpectedServiceName)\n{\n Reference< lang::XServiceName > xServiceName( xProperties, UNO_QUERY );\n CPPUNIT_ASSERT(xServiceName.is());\n\n OUString aServiceName = xServiceName->getServiceName();\n CPPUNIT_ASSERT_EQUAL(aExpectedServiceName, aServiceName);\n\n OUString aCurveName;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"CurveName\") >>= aCurveName);\n CPPUNIT_ASSERT_EQUAL(aExpectedName, aCurveName);\n}\n\nvoid checkLinearTrendline(\n Reference<chart2::XRegressionCurve> xCurve, OUString aExpectedName,\n double aExpectedExtrapolateForward, double aExpectedExtrapolateBackward,\n sal_Bool aExpectedForceIntercept, double aExpectedInterceptValue,\n sal_Bool aExpectedShowEquation, sal_Bool aExpectedR2)\n{\n Reference<XPropertySet> xProperties( xCurve , uno::UNO_QUERY );\n CPPUNIT_ASSERT(xProperties.is());\n\n checkNameAndType(xProperties, aExpectedName, \"com.sun.star.chart2.LinearRegressionCurve\");\n\n checkCommonTrendline(\n xCurve,\n aExpectedExtrapolateForward, aExpectedExtrapolateBackward,\n aExpectedForceIntercept, aExpectedInterceptValue,\n aExpectedShowEquation, aExpectedR2);\n}\n\nvoid checkPolynomialTrendline(\n Reference<chart2::XRegressionCurve> xCurve, OUString aExpectedName,\n sal_Int32 aExpectedDegree,\n double aExpectedExtrapolateForward, double aExpectedExtrapolateBackward,\n sal_Bool aExpectedForceIntercept, double aExpectedInterceptValue,\n sal_Bool aExpectedShowEquation, sal_Bool aExpectedR2)\n{\n Reference<XPropertySet> xProperties( xCurve , uno::UNO_QUERY );\n CPPUNIT_ASSERT(xProperties.is());\n\n checkNameAndType(xProperties, aExpectedName, \"com.sun.star.chart2.PolynomialRegressionCurve\");\n\n sal_Int32 aDegree = 2;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"PolynomialDegree\") >>= aDegree);\n CPPUNIT_ASSERT_EQUAL(aExpectedDegree, aDegree);\n\n checkCommonTrendline(\n xCurve,\n aExpectedExtrapolateForward, aExpectedExtrapolateBackward,\n aExpectedForceIntercept, aExpectedInterceptValue,\n aExpectedShowEquation, aExpectedR2);\n}\n\nvoid checkMovingAverageTrendline(\n Reference<chart2::XRegressionCurve> xCurve, OUString aExpectedName, sal_Int32 aExpectedPeriod)\n{\n Reference<XPropertySet> xProperties( xCurve , uno::UNO_QUERY );\n CPPUNIT_ASSERT(xProperties.is());\n\n checkNameAndType(xProperties, aExpectedName, \"com.sun.star.chart2.MovingAverageRegressionCurve\");\n\n sal_Int32 aPeriod = 2;\n CPPUNIT_ASSERT(xProperties->getPropertyValue(\"MovingAveragePeriod\") >>= aPeriod);\n CPPUNIT_ASSERT_EQUAL(aExpectedPeriod, aPeriod);\n}\n\nvoid checkTrendlinesInChart(uno::Reference< chart2::XChartDocument > xChartDoc)\n{\n CPPUNIT_ASSERT(xChartDoc.is());\n\n Reference< chart2::XDataSeries > xDataSeries = getDataSeriesFromDoc( xChartDoc, 0 );\n CPPUNIT_ASSERT( xDataSeries.is() );\n\n Reference< chart2::XRegressionCurveContainer > xRegressionCurveContainer( xDataSeries, UNO_QUERY );\n CPPUNIT_ASSERT( xRegressionCurveContainer.is() );\n\n Sequence< Reference< chart2::XRegressionCurve > > xRegressionCurveSequence = xRegressionCurveContainer->getRegressionCurves();\n CPPUNIT_ASSERT_EQUAL((sal_Int32) 3, xRegressionCurveSequence.getLength());\n\n Reference<chart2::XRegressionCurve> xCurve;\n\n xCurve = xRegressionCurveSequence[0];\n CPPUNIT_ASSERT(xCurve.is());\n checkPolynomialTrendline(xCurve, \"col2_poly\", 3, 0.1, -0.1, true, -1.0, true, true);\n\n xCurve = xRegressionCurveSequence[1];\n CPPUNIT_ASSERT(xCurve.is());\n checkLinearTrendline(xCurve, \"col2_linear\", -0.5, -0.5, false, 0.0, true, false);\n\n xCurve = xRegressionCurveSequence[2];\n CPPUNIT_ASSERT(xCurve.is());\n checkMovingAverageTrendline(xCurve, \"col2_moving_avg\", 3);\n}\n\n}\n\n\/\/ improve the test\nvoid Chart2ExportTest::testErrorBarXLSX()\n{\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"error_bar.ods\");\n {\n \/\/ make sure the ODS import was successful\n uno::Reference< chart2::XChartDocument > xChartDoc = getChartDocFromSheet( 0, mxComponent );\n CPPUNIT_ASSERT(xChartDoc.is());\n\n Reference< chart2::XDataSeries > xDataSeries = getDataSeriesFromDoc( xChartDoc, 0 );\n CPPUNIT_ASSERT( xDataSeries.is() );\n\n Reference< beans::XPropertySet > xPropSet( xDataSeries, UNO_QUERY_THROW );\n CPPUNIT_ASSERT( xPropSet.is() );\n\n \/\/ test that y error bars are there\n Reference< beans::XPropertySet > xErrorBarYProps;\n xPropSet->getPropertyValue(\"ErrorBarY\") >>= xErrorBarYProps;\n testErrorBar(xErrorBarYProps);\n }\n\n reload(\"Calc Office Open XML\");\n {\n uno::Reference< chart2::XChartDocument > xChartDoc = getChartDocFromSheet( 0, mxComponent );\n CPPUNIT_ASSERT(xChartDoc.is());\n\n Reference< chart2::XDataSeries > xDataSeries = getDataSeriesFromDoc( xChartDoc, 0 );\n CPPUNIT_ASSERT( xDataSeries.is() );\n\n Reference< beans::XPropertySet > xPropSet( xDataSeries, UNO_QUERY_THROW );\n CPPUNIT_ASSERT( xPropSet.is() );\n\n \/\/ test that y error bars are there\n Reference< beans::XPropertySet > xErrorBarYProps;\n xPropSet->getPropertyValue(\"ErrorBarY\") >>= xErrorBarYProps;\n testErrorBar(xErrorBarYProps);\n }\n}\n\n\/\/ This method tests the preservation of properties for trendlines \/ regression curves\n\/\/ in an export -> import cycle using different file formats - ODS, XLS and XLSX.\nvoid Chart2ExportTest::testTrendline()\n{\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"trendline.ods\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n reload(\"calc8\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"trendline.ods\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n reload(\"Calc Office Open XML\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n\n load(\"\/chart2\/qa\/extras\/data\/ods\/\", \"trendline.ods\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n reload(\"MS Excel 97\");\n checkTrendlinesInChart(getChartDocFromSheet( 0, mxComponent));\n\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(Chart2ExportTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\n#include <videocore\/filters\/Custom\/GreyscaleVideoFilter.h>\n\n#include <TargetConditionals.h>\n\n\n#ifdef TARGET_OS_IPHONE\n\n#include <OpenGLES\/ES2\/gl.h>\n#include <OpenGLES\/ES3\/gl.h>\n#include <videocore\/sources\/iOS\/GLESUtil.h>\n#include <videocore\/filters\/FilterFactory.h>\n\n#endif\n\nnamespace videocore { namespace filters {\n \n bool GreyscaleVideoFilter::s_registered = GreyscaleVideoFilter::registerFilter();\n \n bool\n GreyscaleVideoFilter::registerFilter()\n {\n FilterFactory::_register(\"com.videocore.filters.greyscale\", []() { return new GreyscaleVideoFilter(); });\n return true;\n }\n \n GreyscaleVideoFilter::GreyscaleVideoFilter()\n : IVideoFilter(), m_initialized(false), m_bound(false)\n {\n \n }\n GreyscaleVideoFilter::~GreyscaleVideoFilter()\n {\n glDeleteProgram(m_program);\n glDeleteVertexArrays(1, &m_vao);\n }\n \n const char * const\n GreyscaleVideoFilter::vertexKernel() const\n {\n \n KERNEL(GL_ES2_3, m_language,\n attribute vec2 aPos;\n attribute vec2 aCoord;\n varying vec2 vCoord;\n uniform mat4 uMat;\n void main(void) {\n gl_Position = uMat * vec4(aPos,0.,1.);\n vCoord = aCoord;\n }\n )\n \n return nullptr;\n }\n \n const char * const\n GreyscaleVideoFilter::pixelKernel() const\n {\n \n KERNEL(GL_ES2_3, m_language,\n precision mediump float;\n varying vec2 vCoord;\n uniform sampler2D uTex0;\n void main(void) {\n \/\/ gl_FragData[0] = texture2D(uTex0, vCoord);\n vec4 color = texture2D(uTex0, vCoord);\n float gray = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(gray, gray, gray, color.a);\n }\n )\n \n return nullptr;\n }\n void\n GreyscaleVideoFilter::initialize()\n {\n switch(m_language) {\n case GL_ES2_3:\n case GL_2: {\n setProgram(build_program(vertexKernel(), pixelKernel()));\n glGenVertexArrays(1, &m_vao);\n glBindVertexArray(m_vao);\n m_uMatrix = glGetUniformLocation(m_program, \"uMat\");\n int attrpos = glGetAttribLocation(m_program, \"aPos\");\n int attrtex = glGetAttribLocation(m_program, \"aCoord\");\n int unitex = glGetUniformLocation(m_program, \"uTex0\");\n glUniform1i(unitex, 0);\n glEnableVertexAttribArray(attrpos);\n glEnableVertexAttribArray(attrtex);\n glVertexAttribPointer(attrpos, BUFFER_SIZE_POSITION, GL_FLOAT, GL_FALSE, BUFFER_STRIDE, BUFFER_OFFSET_POSITION);\n glVertexAttribPointer(attrtex, BUFFER_SIZE_POSITION, GL_FLOAT, GL_FALSE, BUFFER_STRIDE, BUFFER_OFFSET_TEXTURE);\n m_initialized = true;\n }\n break;\n case GL_3:\n break;\n }\n }\n void\n GreyscaleVideoFilter::bind()\n {\n switch(m_language) {\n case GL_ES2_3:\n case GL_2:\n if(!m_bound) {\n if(!initialized()) {\n initialize();\n }\n glUseProgram(m_program);\n glBindVertexArray(m_vao);\n }\n glUniformMatrix4fv(m_uMatrix, 1, GL_FALSE, &m_matrix[0][0]);\n break;\n case GL_3:\n break;\n }\n }\n void\n GreyscaleVideoFilter::unbind()\n {\n m_bound = false;\n }\n}\n}<commit_msg>removing commented out default filter<commit_after>\n#include <videocore\/filters\/Custom\/GreyscaleVideoFilter.h>\n\n#include <TargetConditionals.h>\n\n\n#ifdef TARGET_OS_IPHONE\n\n#include <OpenGLES\/ES2\/gl.h>\n#include <OpenGLES\/ES3\/gl.h>\n#include <videocore\/sources\/iOS\/GLESUtil.h>\n#include <videocore\/filters\/FilterFactory.h>\n\n#endif\n\nnamespace videocore { namespace filters {\n \n bool GreyscaleVideoFilter::s_registered = GreyscaleVideoFilter::registerFilter();\n \n bool\n GreyscaleVideoFilter::registerFilter()\n {\n FilterFactory::_register(\"com.videocore.filters.greyscale\", []() { return new GreyscaleVideoFilter(); });\n return true;\n }\n \n GreyscaleVideoFilter::GreyscaleVideoFilter()\n : IVideoFilter(), m_initialized(false), m_bound(false)\n {\n \n }\n GreyscaleVideoFilter::~GreyscaleVideoFilter()\n {\n glDeleteProgram(m_program);\n glDeleteVertexArrays(1, &m_vao);\n }\n \n const char * const\n GreyscaleVideoFilter::vertexKernel() const\n {\n \n KERNEL(GL_ES2_3, m_language,\n attribute vec2 aPos;\n attribute vec2 aCoord;\n varying vec2 vCoord;\n uniform mat4 uMat;\n void main(void) {\n gl_Position = uMat * vec4(aPos,0.,1.);\n vCoord = aCoord;\n }\n )\n \n return nullptr;\n }\n \n const char * const\n GreyscaleVideoFilter::pixelKernel() const\n {\n \n KERNEL(GL_ES2_3, m_language,\n precision mediump float;\n varying vec2 vCoord;\n uniform sampler2D uTex0;\n void main(void) {\n vec4 color = texture2D(uTex0, vCoord);\n float gray = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(gray, gray, gray, color.a);\n }\n )\n \n return nullptr;\n }\n void\n GreyscaleVideoFilter::initialize()\n {\n switch(m_language) {\n case GL_ES2_3:\n case GL_2: {\n setProgram(build_program(vertexKernel(), pixelKernel()));\n glGenVertexArrays(1, &m_vao);\n glBindVertexArray(m_vao);\n m_uMatrix = glGetUniformLocation(m_program, \"uMat\");\n int attrpos = glGetAttribLocation(m_program, \"aPos\");\n int attrtex = glGetAttribLocation(m_program, \"aCoord\");\n int unitex = glGetUniformLocation(m_program, \"uTex0\");\n glUniform1i(unitex, 0);\n glEnableVertexAttribArray(attrpos);\n glEnableVertexAttribArray(attrtex);\n glVertexAttribPointer(attrpos, BUFFER_SIZE_POSITION, GL_FLOAT, GL_FALSE, BUFFER_STRIDE, BUFFER_OFFSET_POSITION);\n glVertexAttribPointer(attrtex, BUFFER_SIZE_POSITION, GL_FLOAT, GL_FALSE, BUFFER_STRIDE, BUFFER_OFFSET_TEXTURE);\n m_initialized = true;\n }\n break;\n case GL_3:\n break;\n }\n }\n void\n GreyscaleVideoFilter::bind()\n {\n switch(m_language) {\n case GL_ES2_3:\n case GL_2:\n if(!m_bound) {\n if(!initialized()) {\n initialize();\n }\n glUseProgram(m_program);\n glBindVertexArray(m_vao);\n }\n glUniformMatrix4fv(m_uMatrix, 1, GL_FALSE, &m_matrix[0][0]);\n break;\n case GL_3:\n break;\n }\n }\n void\n GreyscaleVideoFilter::unbind()\n {\n m_bound = false;\n }\n}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Facebook, Inc.\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#include <gtest\/gtest.h>\n\n#include <boost\/thread\/barrier.hpp>\n\n#include <folly\/futures\/Future.h>\n\n#include <vector>\n\nusing namespace folly;\n\ntypedef FutureException eggs_t;\nstatic eggs_t eggs(\"eggs\");\n\nTEST(Window, basic) {\n \/\/ int -> Future<int>\n auto fn = [](std::vector<int> input, size_t window_size, size_t expect) {\n auto res = reduce(\n window(\n input,\n [](int i) { return makeFuture(i); },\n 2),\n 0,\n [](int sum, const Try<int>& b) {\n return sum + *b;\n }).get();\n EXPECT_EQ(expect, res);\n };\n {\n \/\/ 2 in-flight at a time\n std::vector<int> input = {1, 2, 3};\n fn(input, 2, 6);\n }\n {\n \/\/ 4 in-flight at a time\n std::vector<int> input = {1, 2, 3};\n fn(input, 4, 6);\n }\n {\n \/\/ empty inpt\n std::vector<int> input;\n fn(input, 1, 0);\n }\n {\n \/\/ int -> Future<Unit>\n auto res = reduce(\n window(\n std::vector<int>({1, 2, 3}),\n [](int i) { return makeFuture(); },\n 2),\n 0,\n [](int sum, const Try<Unit>& b) {\n EXPECT_TRUE(b.hasValue());\n return sum + 1;\n }).get();\n EXPECT_EQ(3, res);\n }\n {\n \/\/ string -> return Future<int>\n auto res = reduce(\n window(\n std::vector<std::string>{\"1\", \"2\", \"3\"},\n [](std::string s) { return makeFuture<int>(folly::to<int>(s)); },\n 2),\n 0,\n [](int sum, const Try<int>& b) {\n return sum + *b;\n }).get();\n EXPECT_EQ(6, res);\n }\n}\n\nTEST(Window, parallel) {\n std::vector<int> input;\n std::vector<Promise<int>> ps(10);\n for (size_t i = 0; i < ps.size(); i++) {\n input.emplace_back(i);\n }\n auto f = collect(window(input, [&](int i) {\n return ps[i].getFuture();\n }, 3));\n\n std::vector<std::thread> ts;\n boost::barrier barrier(ps.size() + 1);\n for (size_t i = 0; i < ps.size(); i++) {\n ts.emplace_back([&ps, &barrier, i]() {\n barrier.wait();\n ps[i].setValue(i);\n });\n }\n\n barrier.wait();\n\n for (size_t i = 0; i < ps.size(); i++) {\n ts[i].join();\n }\n\n EXPECT_TRUE(f.isReady());\n for (size_t i = 0; i < ps.size(); i++) {\n EXPECT_EQ(i, f.value()[i]);\n }\n}\n\nTEST(Window, parallelWithError) {\n std::vector<int> input;\n std::vector<Promise<int>> ps(10);\n for (size_t i = 0; i < ps.size(); i++) {\n input.emplace_back(i);\n }\n auto f = collect(window(input, [&](int i) {\n return ps[i].getFuture();\n }, 3));\n\n std::vector<std::thread> ts;\n boost::barrier barrier(ps.size() + 1);\n for (size_t i = 0; i < ps.size(); i++) {\n ts.emplace_back([&ps, &barrier, i]() {\n barrier.wait();\n if (i == (ps.size()\/2)) {\n ps[i].setException(eggs);\n } else {\n ps[i].setValue(i);\n }\n });\n }\n\n barrier.wait();\n\n for (size_t i = 0; i < ps.size(); i++) {\n ts[i].join();\n }\n\n EXPECT_TRUE(f.isReady());\n EXPECT_THROW(f.value(), eggs_t);\n}\n\nTEST(Window, allParallelWithError) {\n std::vector<int> input;\n std::vector<Promise<int>> ps(10);\n for (size_t i = 0; i < ps.size(); i++) {\n input.emplace_back(i);\n }\n auto f = collectAll(window(input, [&](int i) {\n return ps[i].getFuture();\n }, 3));\n\n std::vector<std::thread> ts;\n boost::barrier barrier(ps.size() + 1);\n for (size_t i = 0; i < ps.size(); i++) {\n ts.emplace_back([&ps, &barrier, i]() {\n barrier.wait();\n if (i == (ps.size()\/2)) {\n ps[i].setException(eggs);\n } else {\n ps[i].setValue(i);\n }\n });\n }\n\n barrier.wait();\n\n for (size_t i = 0; i < ps.size(); i++) {\n ts[i].join();\n }\n\n EXPECT_TRUE(f.isReady());\n for (size_t i = 0; i < ps.size(); i++) {\n if (i == (ps.size()\/2)) {\n EXPECT_THROW(f.value()[i].value(), eggs_t);\n } else {\n EXPECT_TRUE(f.value()[i].hasValue());\n EXPECT_EQ(i, f.value()[i].value());\n }\n }\n}\n<commit_msg>(Wangle) window, fix test<commit_after>\/*\n * Copyright 2015 Facebook, Inc.\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#include <gtest\/gtest.h>\n\n#include <boost\/thread\/barrier.hpp>\n\n#include <folly\/futures\/Future.h>\n\n#include <vector>\n\nusing namespace folly;\n\ntypedef FutureException eggs_t;\nstatic eggs_t eggs(\"eggs\");\n\nTEST(Window, basic) {\n \/\/ int -> Future<int>\n auto fn = [](std::vector<int> input, size_t window_size, size_t expect) {\n auto res = reduce(\n window(\n input,\n [](int i) { return makeFuture(i); },\n window_size),\n 0,\n [](int sum, const Try<int>& b) {\n return sum + *b;\n }).get();\n EXPECT_EQ(expect, res);\n };\n {\n \/\/ 2 in-flight at a time\n std::vector<int> input = {1, 2, 3};\n fn(input, 2, 6);\n }\n {\n \/\/ 4 in-flight at a time\n std::vector<int> input = {1, 2, 3};\n fn(input, 4, 6);\n }\n {\n \/\/ empty input\n std::vector<int> input;\n fn(input, 1, 0);\n }\n {\n \/\/ int -> Future<Unit>\n auto res = reduce(\n window(\n std::vector<int>({1, 2, 3}),\n [](int i) { return makeFuture(); },\n 2),\n 0,\n [](int sum, const Try<Unit>& b) {\n EXPECT_TRUE(b.hasValue());\n return sum + 1;\n }).get();\n EXPECT_EQ(3, res);\n }\n {\n \/\/ string -> return Future<int>\n auto res = reduce(\n window(\n std::vector<std::string>{\"1\", \"2\", \"3\"},\n [](std::string s) { return makeFuture<int>(folly::to<int>(s)); },\n 2),\n 0,\n [](int sum, const Try<int>& b) {\n return sum + *b;\n }).get();\n EXPECT_EQ(6, res);\n }\n}\n\nTEST(Window, parallel) {\n std::vector<int> input;\n std::vector<Promise<int>> ps(10);\n for (size_t i = 0; i < ps.size(); i++) {\n input.emplace_back(i);\n }\n auto f = collect(window(input, [&](int i) {\n return ps[i].getFuture();\n }, 3));\n\n std::vector<std::thread> ts;\n boost::barrier barrier(ps.size() + 1);\n for (size_t i = 0; i < ps.size(); i++) {\n ts.emplace_back([&ps, &barrier, i]() {\n barrier.wait();\n ps[i].setValue(i);\n });\n }\n\n barrier.wait();\n\n for (size_t i = 0; i < ps.size(); i++) {\n ts[i].join();\n }\n\n EXPECT_TRUE(f.isReady());\n for (size_t i = 0; i < ps.size(); i++) {\n EXPECT_EQ(i, f.value()[i]);\n }\n}\n\nTEST(Window, parallelWithError) {\n std::vector<int> input;\n std::vector<Promise<int>> ps(10);\n for (size_t i = 0; i < ps.size(); i++) {\n input.emplace_back(i);\n }\n auto f = collect(window(input, [&](int i) {\n return ps[i].getFuture();\n }, 3));\n\n std::vector<std::thread> ts;\n boost::barrier barrier(ps.size() + 1);\n for (size_t i = 0; i < ps.size(); i++) {\n ts.emplace_back([&ps, &barrier, i]() {\n barrier.wait();\n if (i == (ps.size()\/2)) {\n ps[i].setException(eggs);\n } else {\n ps[i].setValue(i);\n }\n });\n }\n\n barrier.wait();\n\n for (size_t i = 0; i < ps.size(); i++) {\n ts[i].join();\n }\n\n EXPECT_TRUE(f.isReady());\n EXPECT_THROW(f.value(), eggs_t);\n}\n\nTEST(Window, allParallelWithError) {\n std::vector<int> input;\n std::vector<Promise<int>> ps(10);\n for (size_t i = 0; i < ps.size(); i++) {\n input.emplace_back(i);\n }\n auto f = collectAll(window(input, [&](int i) {\n return ps[i].getFuture();\n }, 3));\n\n std::vector<std::thread> ts;\n boost::barrier barrier(ps.size() + 1);\n for (size_t i = 0; i < ps.size(); i++) {\n ts.emplace_back([&ps, &barrier, i]() {\n barrier.wait();\n if (i == (ps.size()\/2)) {\n ps[i].setException(eggs);\n } else {\n ps[i].setValue(i);\n }\n });\n }\n\n barrier.wait();\n\n for (size_t i = 0; i < ps.size(); i++) {\n ts[i].join();\n }\n\n EXPECT_TRUE(f.isReady());\n for (size_t i = 0; i < ps.size(); i++) {\n if (i == (ps.size()\/2)) {\n EXPECT_THROW(f.value()[i].value(), eggs_t);\n } else {\n EXPECT_TRUE(f.value()[i].hasValue());\n EXPECT_EQ(i, f.value()[i].value());\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ZLib serialization compression\n\n#include \"gen-cpp\/radio_observation_types.h\"\n#include <thrift\/transport\/TSimpleFileTransport.h>\n#include <thrift\/transport\/TZlibTransport.h>\n#include <thrift\/protocol\/TBinaryProtocol.h>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n#include <iostream>\n\nusing namespace apache::thrift::transport;\nusing namespace apache::thrift::protocol;\nusing namespace radio_observation;\nusing boost::make_shared;\nusing boost::shared_ptr;\n\nvoid DumpRadioObservation(const RadioObservation & ro) {\n auto it = _RadioObservationSystem_VALUES_TO_NAMES.find(ro.system);\n auto psystem = (std::end(_RadioObservationSystem_VALUES_TO_NAMES) == it) ? \"\" : it->second;\n std::cout << \"\\nRadio Observation\"\n << \"\\n-------------------------\"\n << \"\\nTelescope Count: \" << ro.telescope_count \n << \"\\nSystem : \" << psystem\n << \"\\nTime : \" << ro.time \n << \"\\nPosition : \";\n if (ro.pos.__isset.icrfpos) {\n std::cout << ro.pos.icrfpos.declination << \" dec - \" \n << ro.pos.icrfpos.right_ascension << \" ra [\";\n if (ro.pos.icrfpos.__isset.ecliptic_year)\n std::cout << ro.pos.icrfpos.ecliptic_year;\n std::cout << \"]\";\n }\n std::cout << \"\\nFrequency Magnitude\\n\";\n for (auto it : ro.freq_amp) \n std::cout << \" \" << it.first << \" \" << it.second << \"\\n\";\n std::cout << \"Size of bmp: \" << ((ro.__isset.sky_bmp) ? ro.sky_bmp.length() : 0) << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n std::cout << \"usage: \" << argv[0] << \" <filename>\" << std::endl;\n return -1;\n }\n try {\n std::cout << \"Reading from uncompressed file: \" << argv[1] << std::endl;\n shared_ptr<TTransport> trans =\n make_shared<TSimpleFileTransport>(argv[1], true, true);\n auto proto = make_shared<TBinaryProtocol>(trans);\n trans->open();\n RadioObservation ro;\n ro.read(proto.get());\n trans->close();\n DumpRadioObservation(ro);\n\n std::string out_file(argv[1]); out_file += \".z\";\n std::cout << \"\\nWritting to compressed file: \" << out_file << std::endl;\n trans.reset(new TSimpleFileTransport(out_file, true, true));\n trans.reset(new TZlibTransport(trans, 1024, 1024, 1024, 1024, 9));\n proto.reset(new TBinaryProtocol(trans));\n trans->open();\n ro.write(proto.get());\n trans->flush();\n trans->close();\n\n std::cout << \"\\nVerifying compressed file: \" << out_file << std::endl;\n trans.reset(new TSimpleFileTransport(out_file, true, true));\n trans.reset(new TZlibTransport(trans));\n proto.reset(new TBinaryProtocol(trans));\n trans->open();\n RadioObservation ro_check;\n ro_check.read(proto.get());\n trans->close();\n DumpRadioObservation(ro_check);\n } catch (std::exception ex) {\n std::cerr << \"Error: \" << ex.what() << std::endl;\n }\n}\n\n<commit_msg>cleaned up C++ ZLib code<commit_after>\/\/ ZLib serialization compression\n\n#include \"gen-cpp\/radio_observation_types.h\"\n#include <thrift\/transport\/TSimpleFileTransport.h>\n#include <thrift\/transport\/TZlibTransport.h>\n#include <thrift\/protocol\/TBinaryProtocol.h>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n#include <iostream>\n\nusing namespace apache::thrift::transport;\nusing namespace apache::thrift::protocol;\nusing namespace radio_observation;\nusing boost::make_shared;\nusing boost::shared_ptr;\n\nvoid DumpRadioObservation(const RadioObservation & ro) {\n auto it0 = _RadioObservationSystem_VALUES_TO_NAMES.find(ro.system);\n auto psystem = (std::end(_RadioObservationSystem_VALUES_TO_NAMES) == it0) ? \"\" : it0->second;\n std::cout << \"\\nRadio Observation\"\n << \"\\n-------------------------\"\n << \"\\nTelescope Count: \" << ro.telescope_count \n << \"\\nSystem : \" << psystem\n << \"\\nTime : \" << ro.time \n << \"\\nPosition : \";\n if (ro.pos.__isset.icrfpos) {\n std::cout << ro.pos.icrfpos.declination << \" dec - \" \n << ro.pos.icrfpos.right_ascension << \" ra [\";\n if (ro.pos.icrfpos.__isset.ecliptic_year)\n std::cout << ro.pos.icrfpos.ecliptic_year;\n std::cout << \"]\";\n }\n std::cout << \"\\nFrequency Magnitude\\n\";\n for (auto it : ro.freq_amp) \n std::cout << \" \" << it.first << \" \" << it.second << \"\\n\";\n std::cout << \"Size of bmp: \" << ((ro.__isset.sky_bmp) ? ro.sky_bmp.length() : 0) << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n std::cout << \"usage: \" << argv[0] << \" <filename>\" << std::endl;\n return -1;\n }\n try {\n std::cout << \"Reading from uncompressed file: \" << argv[1] << std::endl;\n shared_ptr<TTransport> trans =\n make_shared<TSimpleFileTransport>(argv[1], true, true);\n auto proto = make_shared<TBinaryProtocol>(trans);\n trans->open();\n RadioObservation ro;\n ro.read(proto.get());\n trans->close();\n DumpRadioObservation(ro);\n\n std::string out_file(argv[1]); out_file += \".z\";\n std::cout << \"\\nWritting to compressed file: \" << out_file << std::endl;\n trans = make_shared<TSimpleFileTransport>(out_file, true, true);\n trans = make_shared<TZlibTransport>(trans, 1024, 1024, 1024, 1024, 9);\n proto = make_shared<TBinaryProtocol>(trans);\n trans->open();\n ro.write(proto.get());\n trans->flush();\n trans->close();\n\n std::cout << \"\\nVerifying compressed file: \" << out_file << std::endl;\n trans = make_shared<TSimpleFileTransport>(out_file, true, true);\n trans = make_shared<TZlibTransport>(trans);\n proto = make_shared<TBinaryProtocol>(trans);\n trans->open();\n RadioObservation ro_check;\n ro_check.read(proto.get());\n trans->close();\n DumpRadioObservation(ro_check);\n } catch (std::exception ex) {\n std::cerr << \"Error: \" << ex.what() << std::endl;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"ofApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n\tofSetVerticalSync(true);\n\t\n\tint num = 1500;\n\tp.assign(num, demoParticle());\n\tcurrentMode = PARTICLE_MODE_ATTRACT;\n\n\tcurrentModeStr = \"1 - PARTICLE_MODE_ATTRACT: attracts to mouse\"; \n\n\tresetParticles();\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 to false just so it has a value\n\tdebugging = false;\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::resetParticles(){\n\n\t\/\/these are the attraction points used in the forth demo \n\tattractPoints.clear();\n\tfor(int i = 0; i < 4; i++){\n\t\tattractPoints.push_back( ofPoint( ofMap(i, 0, 4, 100, ofGetWidth()-100) , ofRandom(100, ofGetHeight()-100) ) );\n\t}\n\t\n\tattractPointsWithMovement = attractPoints;\n\t\n\tfor(unsigned int i = 0; i < p.size(); i++){\n\t\tp[i].setMode(currentMode);\t\t\n\t\tp[i].setAttractPoints(&attractPointsWithMovement);;\n\t\tp[i].reset();\n\t}\t\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\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\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Particles\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tfor(unsigned int i = 0; i < p.size(); i++){\n\t\tp[i].setMode(currentMode);\n\t\tp[i].update();\n\t}\n\t\n\t\/\/lets add a bit of movement to the attract points\n\tfor(unsigned int i = 0; i < attractPointsWithMovement.size(); i++){\n\t\tattractPointsWithMovement[i].x = attractPoints[i].x + ofSignedNoise(i * 10, ofGetElapsedTimef() * 0.7) * 12.0;\n\t\tattractPointsWithMovement[i].y = attractPoints[i].y + ofSignedNoise(i * -10, ofGetElapsedTimef() * 0.7) * 12.0;\n\t}\t\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n ofBackgroundGradient(ofColor(60,60,60), ofColor(10,10,10));\n\n\tfor(unsigned int i = 0; i < p.size(); i++){\n\t\tp[i].draw();\n\t}\n\t\n\tofSetColor(190);\n\tif( currentMode == PARTICLE_MODE_NEAREST_POINTS ){\n\t\tfor(unsigned int i = 0; i < attractPoints.size(); i++){\n\t\t\tofNoFill();\n\t\t\tofDrawCircle(attractPointsWithMovement[i], 10);\n\t\t\tofFill();\n\t\t\tofDrawCircle(attractPointsWithMovement[i], 4);\n\t\t}\n\t}\n\n\tofSetColor(230);\t\n\tofDrawBitmapString(currentModeStr + \"\\n\\nSpacebar to reset. \\nKeys 1-4 to change mode.\", 10, 20);\n\n\tofPushStyle();\n\t\/\/TODO: move these hardcoded numbers into GUI\n\tofEnableBlendMode(OF_BLENDMODE_SCREEN);\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\n\t\t\/\/TODO: add debug instrcutions gui & text\n\t\t\/\/ change color settings\n\t\t\/\/ set mode to debugging\n\t}\n\tofPopStyle();\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n\tswitch (key) {\n\n\tcase '1':\n\t\tcurrentMode = PARTICLE_MODE_ATTRACT;\n\t\tcurrentModeStr = \"1 - PARTICLE_MODE_ATTRACT: attracts to mouse\";\n\t\tbreak;\n\n\tcase '2':\n\t\tcurrentMode = PARTICLE_MODE_REPEL;\n\t\tcurrentModeStr = \"2 - PARTICLE_MODE_REPEL: repels from mouse\";\n\t\tbreak;\n\n\tcase '3':\n\t\tcurrentMode = PARTICLE_MODE_NEAREST_POINTS;\n\t\tcurrentModeStr = \"3 - PARTICLE_MODE_NEAREST_POINTS: hold 'f' to disable force\";\n\t\tbreak;\n\n\tcase '4':\n\t\tcurrentMode = PARTICLE_MODE_NOISE;\n\t\tcurrentModeStr = \"4 - PARTICLE_MODE_NOISE: snow particle simulation\";\n\t\tresetParticles();\n\t\tbreak;\n\n\tcase ' ':\n\t\tresetParticles();\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\tofToggleFullscreen();\n\t\tbreak;\n\n\tdefault :\n\t\tbreak;\n\t}\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y ){\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<commit_msg>Slew of TODOs and commen cleanup.<commit_after>#include \"ofApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n\tofSetVerticalSync(true);\n\t\n\tint num = 1500; \/\/TODO: move hard coded values into GUI\n\tp.assign(num, demoParticle());\n\tcurrentMode = PARTICLE_MODE_ATTRACT;\/\/TODO: move hard coded values into GUI\n\n\tcurrentModeStr = \"1 - PARTICLE_MODE_ATTRACT: attracts to mouse\"; \/\/TODO: move hard coded values into GUI\n\n\tresetParticles();\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 to false just so it has a value\n\tdebugging = false;\/\/TODO: move hard coded values into GUI\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::resetParticles(){\n\n\t\/\/these are the attraction points used in the forth demo \n\tattractPoints.clear();\n\tfor(int i = 0; i < 4; i++){ \/\/TODO: move hard coded values into GUI\n\t\tattractPoints.push_back( ofPoint( ofMap(i, 0, 4, 100, ofGetWidth()-100) , ofRandom(100, ofGetHeight()-100) ) );\n\t}\n\t\n\tattractPointsWithMovement = attractPoints;\n\t\n\tfor(unsigned int i = 0; i < p.size(); i++){\n\t\tp[i].setMode(currentMode);\t\t\n\t\tp[i].setAttractPoints(&attractPointsWithMovement);;\n\t\tp[i].reset();\n\t}\t\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Kinect\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tkinect.update();\n\n\t\/\/Getting joint positions (skeleton tracking)\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\n\t\/\/Getting bones (connected joints)\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\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Particles\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tfor(unsigned int i = 0; i < p.size(); i++){\n\t\tp[i].setMode(currentMode);\n\t\tp[i].update();\n\t}\n\t\n\t\/\/lets add a bit of movement to the attract points\n\tfor(unsigned int i = 0; i < attractPointsWithMovement.size(); i++){\n\t\tattractPointsWithMovement[i].x = attractPoints[i].x + ofSignedNoise(i * 10, ofGetElapsedTimef() * 0.7) * 12.0;\/\/TODO: move hard coded values into GUI\n\t\tattractPointsWithMovement[i].y = attractPoints[i].y + ofSignedNoise(i * -10, ofGetElapsedTimef() * 0.7) * 12.0;\/\/TODO: move hard coded values into GUI\n\t}\t\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n ofBackgroundGradient(ofColor(60,60,60), ofColor(10,10,10));\/\/TODO: move hard coded values into GUI\n\n\tfor(unsigned int i = 0; i < p.size(); i++){\n\t\tp[i].draw();\n\t}\n\t\n\tofSetColor(190);\n\tif( currentMode == PARTICLE_MODE_NEAREST_POINTS ){\n\t\tfor(unsigned int i = 0; i < attractPoints.size(); i++){\n\t\t\tofNoFill();\n\t\t\tofDrawCircle(attractPointsWithMovement[i], 10);\/\/TODO: move hard coded values into GUI\n\t\t\tofFill();\n\t\t\tofDrawCircle(attractPointsWithMovement[i], 4);\/\/TODO: move hard coded values into GUI\n\t\t}\n\t}\n\n\tofSetColor(230);\t\/\/TODO: move hard coded values into GUI\n\tofDrawBitmapString(currentModeStr + \"\\n\\nSpacebar to reset. \\nKeys 1-4 to change mode.\", 10, 20);\/\/TODO: move hard coded values into GUI\n\n\tofPushStyle();\n\t\/\/TODO: move these hardcoded numbers into GUI\n\tofEnableBlendMode(OF_BLENDMODE_SCREEN);\/\/TODO: move hard coded values into GUI\n\tofSetColor(127);\/\/TODO: move hard coded values into GUI\n\tif (debugging) {\/\/TODO: move hard coded values into GUI\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\n\t\t\/\/TODO: add debug instrcutions gui & text\n\t\t\/\/ change color settings\n\t\t\/\/ set mode to debugging\n\t}\n\tofPopStyle();\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){ \/\/TODO: move key presses into GUI\n\tswitch (key) {\n\n\tcase '1':\n\t\tcurrentMode = PARTICLE_MODE_ATTRACT;\n\t\tcurrentModeStr = \"1 - PARTICLE_MODE_ATTRACT: attracts to mouse\";\n\t\tbreak;\n\n\tcase '2':\n\t\tcurrentMode = PARTICLE_MODE_REPEL;\n\t\tcurrentModeStr = \"2 - PARTICLE_MODE_REPEL: repels from mouse\";\n\t\tbreak;\n\n\tcase '3':\n\t\tcurrentMode = PARTICLE_MODE_NEAREST_POINTS;\n\t\tcurrentModeStr = \"3 - PARTICLE_MODE_NEAREST_POINTS: hold 'f' to disable force\";\n\t\tbreak;\n\n\tcase '4':\n\t\tcurrentMode = PARTICLE_MODE_NOISE;\n\t\tcurrentModeStr = \"4 - PARTICLE_MODE_NOISE: snow particle simulation\";\n\t\tresetParticles();\n\t\tbreak;\n\n\tcase ' ':\n\t\tresetParticles();\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\tofToggleFullscreen();\n\t\tbreak;\n\n\tdefault :\n\t\tbreak;\n\t}\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y ){\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;\/\/TODO: move hard coded values into GUI\n\tpreviewHeight = ofGetWindowHeight() \/ 2;\/\/TODO: move hard coded values into GUI\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){ \n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include <rapidcheck\/gtest.h>\n\n#include <string>\n\n\/\/ http:\/\/www.programcreek.com\/2013\/02\/longest-substring-which-contains-2-unique-characters\/\n\/\/ Given a string, find the longest substring that contains only two unique characters.\n\/\/ For example, given \"abcbbbbcccbdddadacb\", the longest substring that contains 2 unique character is \"bcbbbbcccb\".\n\n\/\/ Algorithm to be tested:\n\/\/ std::size_t longest_size(std::string const& in);\n\n\/\/ Running tests\n\nTEST(TEST_NAME, EmptyString)\n{\n ASSERT_EQ(0, longest_size(\"\"));\n}\n\nTEST(TEST_NAME, UniqueCharacter)\n{\n ASSERT_EQ(5, longest_size(\"aaaaa\"));\n}\n\nTEST(TEST_NAME, TwoCharacters)\n{\n ASSERT_EQ(7, longest_size(\"abbaaba\"));\n}\n\nTEST(TEST_NAME, SubstringOfMainString)\n{\n ASSERT_EQ(10, longest_size(\"abcbbbbcccbdddadacb\"));\n}\n\nRC_GTEST_PROP(TEST_NAME, RandomData, (char c1, char c2))\n{\n RC_PRE(c1 != c2);\n \n char moved_c1 = c1, moved_c2 = c2;\n std::string answer_str = *rc::gen::apply(\n [](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }\n , rc::gen::container<std::vector<char>>(rc::gen::element<char>(std::move(moved_c1), std::move(moved_c2))))\n .as(\"longest part with 2 different chars\");\n RC_PRE(answer_str.find(c1) != std::string::npos);\n RC_PRE(answer_str.find(c2) != std::string::npos);\n \n std::size_t pre_length = *rc::gen::inRange<std::size_t>(0, answer_str.size())\n .as(\"length for the part before longest\");\n std::string pre_str = *rc::gen::apply(\n [](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }\n , rc::gen::container<std::vector<char>>(pre_length, rc::gen::arbitrary<char>()))\n .as(\"before longest chars\");\n RC_PRE(pre_str.size() == std::size_t() || (pre_str.back() != c1 && pre_str.back() != c2));\n RC_PRE(pre_str.size() < std::size_t(2) || pre_str[pre_str.size() -1] != pre_str[pre_str.size() -2]);\n \n std::size_t post_length = *rc::gen::inRange<std::size_t>(0, answer_str.size())\n .as(\"length of the part after longest\");\n std::string post_str = *rc::gen::apply(\n [](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }\n , rc::gen::container<std::vector<char>>(post_length, rc::gen::arbitrary<char>()))\n .as(\"after longest chars\");\n RC_PRE(post_str.size() == std::size_t() || (post_str.front() != c1 && post_str.front() != c2));\n RC_PRE(post_str.size() < std::size_t(2) || post_str[0] != post_str[1]);\n \n std::string data = pre_str + answer_str + post_str;\n RC_ASSERT(answer_str.size() == longest_size(data));\n}\n\n<commit_msg>[longest-substr-2-uniques] Fix tests.hpp<commit_after>#include \"gtest\/gtest.h\"\n#include <rapidcheck\/gtest.h>\n\n#include <string>\n\n\/\/ http:\/\/www.programcreek.com\/2013\/02\/longest-substring-which-contains-2-unique-characters\/\n\/\/ Given a string, find the longest substring that contains only two unique characters.\n\/\/ For example, given \"abcbbbbcccbdddadacb\", the longest substring that contains 2 unique character is \"bcbbbbcccb\".\n\n\/\/ Algorithm to be tested:\n\/\/ std::size_t longest_size(std::string const& in);\n\n\/\/ Running tests\n\nTEST(TEST_NAME, EmptyString)\n{\n ASSERT_EQ(0, longest_size(\"\"));\n}\n\nTEST(TEST_NAME, UniqueCharacter)\n{\n ASSERT_EQ(5, longest_size(\"aaaaa\"));\n}\n\nTEST(TEST_NAME, TwoCharacters)\n{\n ASSERT_EQ(7, longest_size(\"abbaaba\"));\n}\n\nTEST(TEST_NAME, SubstringOfMainString)\n{\n ASSERT_EQ(10, longest_size(\"abcbbbbcccbdddadacb\"));\n}\n\nRC_GTEST_PROP(TEST_NAME, RandomData, (char c1, char c2))\n{\n RC_PRE(c1 != c2);\n \n char moved_c1 = c1, moved_c2 = c2;\n std::string answer_str = *rc::gen::apply(\n [](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }\n , rc::gen::container<std::vector<char>>(rc::gen::element<char>(std::move(moved_c1), std::move(moved_c2))))\n .as(\"longest part with 2 different chars\");\n RC_PRE(answer_str.find(c1) != std::string::npos);\n RC_PRE(answer_str.find(c2) != std::string::npos);\n \n std::size_t pre_length = *rc::gen::inRange<std::size_t>(0, answer_str.size())\n .as(\"length for the part before longest\");\n std::string pre_str = *rc::gen::apply(\n [](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }\n , rc::gen::container<std::vector<char>>(pre_length, rc::gen::arbitrary<char>()))\n .as(\"before longest chars\");\n if (! pre_str.empty())\n {\n RC_PRE(pre_str.back() != c1 && pre_str.back() != c2);\n }\n if (pre_str.size() >= std::size_t(2))\n {\n RC_PRE(pre_str[pre_str.size() -1] != pre_str[pre_str.size() -2]);\n }\n \n std::size_t post_length = *rc::gen::inRange<std::size_t>(0, answer_str.size())\n .as(\"length of the part after longest\");\n std::string post_str = *rc::gen::apply(\n [](auto&& vs) { return std::string(std::begin(vs), std::end(vs)); }\n , rc::gen::container<std::vector<char>>(post_length, rc::gen::arbitrary<char>()))\n .as(\"after longest chars\");\n if (! post_str.empty())\n {\n RC_PRE(post_str.front() != c1 && post_str.front() != c2);\n }\n if (post_str.size() >= std::size_t(2))\n {\n RC_PRE(post_str[0] != post_str[1]);\n }\n \n std::string data = pre_str + answer_str + post_str;\n RC_ASSERT(answer_str.size() == longest_size(data));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Original code has been submitted by Liu Liu. Here is the copyright.\n----------------------------------------------------------------------------------\n * An OpenCV Implementation of SURF\n * Further Information Refer to \"SURF: Speed-Up Robust Feature\"\n * Author: Liu Liu\n * liuliu.1987+opencv@gmail.com\n *\n * There are still serveral lacks for this experimental implementation:\n * 1.The interpolation of sub-pixel mentioned in article was not implemented yet;\n * 2.A comparision with original libSurf.so shows that the hessian detector is not a 100% match to their implementation;\n * 3.Due to above reasons, I recommanded the original one for study and reuse;\n *\n * However, the speed of this implementation is something comparable to original one.\n *\n * Copyright© 2008, Liu Liu All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n * \tRedistributions of source code must retain the above\n * \tcopyright notice, this list of conditions and the following\n * \tdisclaimer.\n * \tRedistributions in binary form must reproduce the above\n * \tcopyright notice, this list of conditions and the following\n * \tdisclaimer in the documentation and\/or other materials\n * \tprovided with the distribution.\n * \tThe name of Contributor may not be used to endorse or\n * \tpromote products derived from this software without\n * \tspecific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n * CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n * OF SUCH DAMAGE.\n *\/\n\n#include \"precomp.hpp\"\n\nusing namespace cv;\n\n\n\nCV_IMPL CvSURFParams cvSURFParams(double threshold, int extended)\n{\n CvSURFParams params;\n params.hessianThreshold = threshold;\n params.extended = extended;\n params.upright = 0;\n params.nOctaves = 4;\n params.nOctaveLayers = 2;\n return params;\n}\n\nCV_IMPL void\ncvExtractSURF( const CvArr* _img, const CvArr* _mask,\n CvSeq** _keypoints, CvSeq** _descriptors,\n CvMemStorage* storage, CvSURFParams params,\n int useProvidedKeyPts)\n{\n Mat img = cvarrToMat(_img), mask;\n if(_mask)\n mask = cvarrToMat(_mask);\n vector<KeyPoint> kpt;\n Mat descr;\n \n Ptr<Feature2D> surf = Algorithm::create<Feature2D>(\"Feature2D.SURF\");\n if( surf.empty() )\n CV_Error(CV_StsNotImplemented, \"OpenCV was built without SURF support\");\n \n surf->set(\"hessianThreshold\", params.hessianThreshold);\n surf->set(\"nOctaves\", params.nOctaves);\n surf->set(\"nOctaveLayers\", params.nOctaveLayers);\n surf->set(\"upright\", params.upright != 0);\n surf->set(\"extended\", params.extended != 0);\n \n surf->operator()(img, mask, kpt, _descriptors ? _OutputArray(descr) : noArray(),\n useProvidedKeyPts != 0);\n \n if( _keypoints )\n *_keypoints = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvSURFPoint), storage);\n \n if( _descriptors )\n *_descriptors = cvCreateSeq(0, sizeof(CvSeq), descr.cols*descr.elemSize(), storage);\n \n for( size_t i = 0; i < kpt.size(); i++ )\n {\n if( _keypoints )\n {\n CvSURFPoint pt = cvSURFPoint(kpt[i].pt, kpt[i].class_id, cvRound(kpt[i].size), kpt[i].angle, kpt[i].response);\n cvSeqPush(*_keypoints, &pt);\n }\n if( _descriptors )\n cvSeqPush(*_descriptors, descr.ptr((int)i));\n }\n}\n\nCV_IMPL CvSeq*\ncvGetStarKeypoints( const CvArr* _img, CvMemStorage* storage,\n CvStarDetectorParams params )\n{\n Ptr<StarDetector> star = new StarDetector(params.maxSize, params.responseThreshold,\n params.lineThresholdProjected,\n params.lineThresholdBinarized,\n params.suppressNonmaxSize);\n vector<KeyPoint> kpts;\n star->detect(cvarrToMat(_img), kpts, Mat());\n \n CvSeq* seq = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvStarKeypoint), storage);\n for( size_t i = 0; i < kpts.size(); i++ )\n {\n CvStarKeypoint kpt = cvStarKeypoint(kpts[i].pt, cvRound(kpts[i].size), kpts[i].response);\n cvSeqPush(seq, &kpt);\n }\n return seq;\n}\n\n\n<commit_msg>Fixed cvExtractSURF in case of no keypoints found #2076<commit_after>\/* Original code has been submitted by Liu Liu. Here is the copyright.\n----------------------------------------------------------------------------------\n * An OpenCV Implementation of SURF\n * Further Information Refer to \"SURF: Speed-Up Robust Feature\"\n * Author: Liu Liu\n * liuliu.1987+opencv@gmail.com\n *\n * There are still serveral lacks for this experimental implementation:\n * 1.The interpolation of sub-pixel mentioned in article was not implemented yet;\n * 2.A comparision with original libSurf.so shows that the hessian detector is not a 100% match to their implementation;\n * 3.Due to above reasons, I recommanded the original one for study and reuse;\n *\n * However, the speed of this implementation is something comparable to original one.\n *\n * Copyright© 2008, Liu Liu All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n * Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the following\n * 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\n * provided with the distribution.\n * The name of Contributor may not be used to endorse or\n * promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n * CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n * OF SUCH DAMAGE.\n *\/\n\n#include \"precomp.hpp\"\n\nusing namespace cv;\n\n\n\nCV_IMPL CvSURFParams cvSURFParams(double threshold, int extended)\n{\n CvSURFParams params;\n params.hessianThreshold = threshold;\n params.extended = extended;\n params.upright = 0;\n params.nOctaves = 4;\n params.nOctaveLayers = 2;\n return params;\n}\n\nCV_IMPL void\ncvExtractSURF( const CvArr* _img, const CvArr* _mask,\n CvSeq** _keypoints, CvSeq** _descriptors,\n CvMemStorage* storage, CvSURFParams params,\n int useProvidedKeyPts)\n{\n Mat img = cvarrToMat(_img), mask;\n if(_mask)\n mask = cvarrToMat(_mask);\n vector<KeyPoint> kpt;\n Mat descr;\n\n Ptr<Feature2D> surf = Algorithm::create<Feature2D>(\"Feature2D.SURF\");\n if( surf.empty() )\n CV_Error(CV_StsNotImplemented, \"OpenCV was built without SURF support\");\n\n surf->set(\"hessianThreshold\", params.hessianThreshold);\n surf->set(\"nOctaves\", params.nOctaves);\n surf->set(\"nOctaveLayers\", params.nOctaveLayers);\n surf->set(\"upright\", params.upright != 0);\n surf->set(\"extended\", params.extended != 0);\n\n surf->operator()(img, mask, kpt, _descriptors ? _OutputArray(descr) : noArray(),\n useProvidedKeyPts != 0);\n\n if( _keypoints )\n *_keypoints = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvSURFPoint), storage);\n\n if( _descriptors )\n *_descriptors = cvCreateSeq(0, sizeof(CvSeq), surf->descriptorSize() * CV_ELEM_SIZE(surf->descriptorType()), storage);\n\n for( size_t i = 0; i < kpt.size(); i++ )\n {\n if( _keypoints )\n {\n CvSURFPoint pt = cvSURFPoint(kpt[i].pt, kpt[i].class_id, cvRound(kpt[i].size), kpt[i].angle, kpt[i].response);\n cvSeqPush(*_keypoints, &pt);\n }\n if( _descriptors )\n cvSeqPush(*_descriptors, descr.ptr((int)i));\n }\n}\n\nCV_IMPL CvSeq*\ncvGetStarKeypoints( const CvArr* _img, CvMemStorage* storage,\n CvStarDetectorParams params )\n{\n Ptr<StarDetector> star = new StarDetector(params.maxSize, params.responseThreshold,\n params.lineThresholdProjected,\n params.lineThresholdBinarized,\n params.suppressNonmaxSize);\n vector<KeyPoint> kpts;\n star->detect(cvarrToMat(_img), kpts, Mat());\n\n CvSeq* seq = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvStarKeypoint), storage);\n for( size_t i = 0; i < kpts.size(); i++ )\n {\n CvStarKeypoint kpt = cvStarKeypoint(kpts[i].pt, cvRound(kpts[i].size), kpts[i].response);\n cvSeqPush(seq, &kpt);\n }\n return seq;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"models\/profile.h\"\n#include <QDir>\n#include <QFile>\n#include <QJsonArray>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include \"commands\/commands.h\"\n#include \"models\/site.h\"\n\n\nProfile::Profile()\n\t: m_settings(nullptr), m_commands(nullptr)\n{}\nProfile::Profile(QSettings *settings, const QList<Favorite> &favorites, const QStringList &keptForLater, const QString &path)\n\t: m_path(path), m_settings(settings), m_favorites(favorites), m_keptForLater(keptForLater), m_commands(nullptr)\n{}\nProfile::Profile(const QString &path)\n\t: m_path(path)\n{\n\tm_settings = new QSettings(m_path + \"\/settings.ini\", QSettings::IniFormat);\n\n\t\/\/ Load sources\n\tQStringList dirs = QDir(m_path + \"\/sites\/\").entryList(QDir::Dirs | QDir::NoDotAndDotDot);\n\tfor (const QString &dir : dirs)\n\t{\n\t\tSource *source = new Source(this, m_path + \"\/sites\/\" + dir);\n\t\tm_sources.insert(source->getName(), source);\n\n\t\tfor (Site *site : source->getSites())\n\t\t\tm_sites.insert(site->url(), site);\n\t}\n\n\t\/\/ Load favorites\n\tQSet<QString> unique;\n\tQFile fileFavorites(m_path + \"\/favorites.txt\");\n\tif (fileFavorites.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString favs = fileFavorites.readAll();\n\t\tfileFavorites.close();\n\n\t\tQStringList words = favs.split(\"\\n\", QString::SkipEmptyParts);\n\t\tm_favorites.reserve(words.count());\n\t\tfor (const QString &word : words)\n\t\t{\n\t\t\tFavorite fav = Favorite::fromString(m_path, word);\n\t\t\tif (!unique.contains(fav.getName()))\n\t\t\t{\n\t\t\t\tunique.insert(fav.getName());\n\t\t\t\tm_favorites.append(fav);\n\t\t\t}\n\t\t}\n\t}\n\tQFile fileFavoritesJson(m_path + \"\/favorites.json\");\n\tif (fileFavoritesJson.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQByteArray data = fileFavoritesJson.readAll();\n\t\tQJsonDocument loadDoc = QJsonDocument::fromJson(data);\n\t\tQJsonObject object = loadDoc.object();\n\n\t\tQJsonArray favorites = object[\"favorites\"].toArray();\n\t\tfor (auto favoriteJson : favorites)\n\t\t{\n\t\t\tFavorite fav = Favorite::fromJson(m_path, favoriteJson.toObject(), m_sites);\n\t\t\tif (!unique.contains(fav.getName()))\n\t\t\t{\n\t\t\t\tunique.insert(fav.getName());\n\t\t\t\tm_favorites.append(fav);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Load view it later\n\tQFile fileKfl(m_path + \"\/viewitlater.txt\");\n\tif (fileKfl.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString vil = fileKfl.readAll();\n\t\tfileKfl.close();\n\n\t\tm_keptForLater = vil.split(\"\\n\", QString::SkipEmptyParts);\n\t}\n\n\t\/\/ Load ignored\n\tQFile fileIgnored(m_path + \"\/ignore.txt\");\n\tif (fileIgnored.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString ign = fileIgnored.readAll();\n\t\tfileIgnored.close();\n\n\t\tm_ignored = ign.split(\"\\n\", QString::SkipEmptyParts);\n\t}\n\n\t\/\/ Load MD5s\n\tQFile fileMD5(m_path + \"\/md5s.txt\");\n\tif (fileMD5.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString line;\n\t\twhile (!(line = fileMD5.readLine()).isEmpty())\n\t\t\tm_md5s.insert(line.left(32), line.mid(32).trimmed());\n\n\t\tfileMD5.close();\n\t}\n\n\t\/\/ Load auto-complete\n\tQFile fileAutoComplete(m_path + \"\/words.txt\");\n\tif (fileAutoComplete.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString line;\n\t\twhile (!(line = fileAutoComplete.readLine()).isEmpty())\n\t\t\tm_autoComplete.append(line.trimmed().split(\" \", QString::SkipEmptyParts));\n\n\t\tfileAutoComplete.close();\n\t}\n\n\t\/\/ Load custom auto-complete\n\tQFile fileCustomAutoComplete(m_path + \"\/wordsc.txt\");\n\tif (fileCustomAutoComplete.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString line;\n\t\twhile (!(line = fileCustomAutoComplete.readLine()).isEmpty())\n\t\t\tm_customAutoComplete.append(line.trimmed().split(\" \", QString::SkipEmptyParts));\n\n\t\tfileCustomAutoComplete.close();\n\t}\n\n\tm_commands = new Commands(this);\n\n\t\/\/ Blacklisted tags\n\tm_blacklistedTags = m_settings->value(\"blacklistedtags\").toString().split(' ', QString::SkipEmptyParts);\n}\n\nProfile::~Profile()\n{\n\tsync();\n\n\tif (m_settings != nullptr)\n\t\tm_settings->deleteLater();\n\n\tqDeleteAll(m_sources);\n\tdelete m_commands;\n}\n\n\nvoid Profile::sync()\n{\n\tif (m_path.isEmpty())\n\t\treturn;\n\n\tsyncFavorites();\n\tsyncKeptForLater();\n\tsyncIgnored();\n\n\t\/\/ MD5s\n\tQFile fileMD5(m_path + \"\/md5s.txt\");\n\tif (fileMD5.open(QFile::WriteOnly | QFile::Truncate))\n\t{\n\t\tQStringList md5s = m_md5s.keys();\n\t\tQStringList paths = m_md5s.values();\n\t\tfor (int i = 0; i < md5s.size(); i++)\n\t\t\tfileMD5.write(QString(md5s[i] + paths[i] + \"\\n\").toUtf8());\n\n\t\tfileMD5.close();\n\t}\n\n\t\/\/ Custom auto-complete\n\tQFile fileCustomAutoComplete(m_path + \"\/wordsc.txt\");\n\tif (fileCustomAutoComplete.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))\n\t{\n\t\tfileCustomAutoComplete.write(m_customAutoComplete.join(\"\\r\\n\").toUtf8());\n\t\tfileCustomAutoComplete.close();\n\t}\n\n\t\/\/ Update commands settings\n\tauto *oldCommands = m_commands;\n\tauto *newCommands = new Commands(this);\n\tm_commands = newCommands;\n\tdelete oldCommands;\n\n\t\/\/ Blacklisted tags\n\tm_settings->setValue(\"blacklistedtags\", m_blacklistedTags.join(' '));\n\n\t\/\/ Sync settings\n\tif (m_settings != nullptr)\n\t\tm_settings->sync();\n}\nvoid Profile::syncFavorites()\n{\n\tQFile fileFavorites(m_path + \"\/favorites.json\");\n\tif (fileFavorites.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))\n\t{\n\t\t\/\/ Generate JSON array\n\t\tQJsonArray favoritesJson;\n\t\tfor (const Favorite &fav : m_favorites)\n\t\t{\n\t\t\tQJsonObject unique;\n\t\t\tfav.toJson(unique);\n\t\t\tfavoritesJson.append(unique);\n\t\t}\n\n\t\t\/\/ Generate result\n\t\tQJsonObject full;\n\t\tfull[\"version\"] = 1;\n\t\tfull[\"favorites\"] = favoritesJson;\n\n\t\t\/\/ Write result\n\t\tQJsonDocument saveDoc(full);\n\t\tfileFavorites.write(saveDoc.toJson());\n\t\tfileFavorites.close();\n\t}\n\tQFile::remove(m_path + \"\/favorites.txt\");\n}\nvoid Profile::syncKeptForLater()\n{\n\tQFile fileKfl(m_path + \"\/viewitlater.txt\");\n\tif (fileKfl.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))\n\t{\n\t\tfileKfl.write(m_keptForLater.join(\"\\r\\n\").toUtf8());\n\t\tfileKfl.close();\n\t}\n}\nvoid Profile::syncIgnored()\n{\n\tQFile fileIgnored(m_path + \"\/ignore.txt\");\n\tif (fileIgnored.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))\n\t{\n\t\tfileIgnored.write(m_ignored.join(\"\\r\\n\").toUtf8());\n\t\tfileIgnored.close();\n\t}\n}\n\nQString Profile::tempPath() const\n{\n\tQString tmp = QDir::tempPath();\n\tQString subDir = \"Grabber\";\n\tQDir(tmp).mkpath(subDir);\n\treturn tmp + QDir::separator() + subDir;\n}\n\nvoid Profile::addFavorite(const Favorite &fav)\n{\n\tm_favorites.removeAll(fav);\n\tm_favorites.append(fav);\n\n\tsyncFavorites();\n\temit favoritesChanged();\n}\nvoid Profile::removeFavorite(const Favorite &fav)\n{\n\tm_favorites.removeAll(fav);\n\n\tif (QFile::exists(m_path + \"\/thumbs\/\" + fav.getName(true) + \".png\"))\n\t\tQFile::remove(m_path + \"\/thumbs\/\" + fav.getName(true) + \".png\");\n\n\tsyncFavorites();\n\temit favoritesChanged();\n}\nvoid Profile::emitFavorite()\n{\n\tsyncFavorites();\n\temit favoritesChanged();\n}\n\nvoid Profile::addKeptForLater(const QString &tag)\n{\n\tm_keptForLater.removeAll(tag);\n\tm_keptForLater.append(tag);\n\n\tsyncKeptForLater();\n\temit keptForLaterChanged();\n}\nvoid Profile::removeKeptForLater(const QString &tag)\n{\n\tm_keptForLater.removeAll(tag);\n\n\tsyncKeptForLater();\n\temit keptForLaterChanged();\n}\n\nvoid Profile::addIgnored(const QString &tag)\n{\n\tm_ignored.removeAll(tag);\n\tm_ignored.append(tag);\n\n\tsyncIgnored();\n\temit ignoredChanged();\n}\nvoid Profile::removeIgnored(const QString &tag)\n{\n\tm_ignored.removeAll(tag);\n\n\tsyncIgnored();\n\temit ignoredChanged();\n}\n\nQPair<QString, QString> Profile::md5Action(const QString &md5)\n{\n\tQString action = m_settings->value(\"Save\/md5Duplicates\", \"save\").toString();\n\tbool keepDeleted = m_settings->value(\"Save\/keepDeletedMd5\", false).toBool();\n\n\tbool contains = !md5.isEmpty() && m_md5s.contains(md5);\n\tQString path = contains ? m_md5s[md5] : QString();\n\tbool exists = contains && QFile::exists(path);\n\n\tif (contains && !exists)\n\t{\n\t\tif (!keepDeleted)\n\t\t{\n\t\t\tremoveMd5(md5);\n\t\t\tpath = QString();\n\t\t}\n\t\telse\n\t\t{ action = \"ignore\"; }\n\t}\n\n\treturn QPair<QString, QString>(action, path);\n}\n\n\/**\n * Check if a file with this md5 already exists;\n * @param\tmd5\t\tThe md5 that needs to be checked.\n * @return\t\t\tA QString containing the path to the already existing file, an empty QString if the md5 does not already exists.\n *\/\nQString Profile::md5Exists(const QString &md5)\n{\n\tif (m_md5s.contains(md5))\n\t{\n\t\tif (QFile::exists(m_md5s[md5]))\n\t\t\treturn m_md5s[md5];\n\n\t\tif (!m_settings->value(\"Save\/keepDeletedMd5\", false).toBool())\n\t\t\tremoveMd5(md5);\n\t}\n\treturn QString();\n}\n\n\/**\n * Adds a md5 to the _md5 map and adds it to the md5 file.\n * @param\tmd5\t\tThe md5 to add.\n * @param\tpath\tThe path to the image with this md5.\n *\/\nvoid Profile::addMd5(const QString &md5, const QString &path)\n{\n\tif (!md5.isEmpty())\n\t{ m_md5s.insert(md5, path); }\n}\n\n\/**\n * Set a md5 to the _md5 map changing the file it is pointing to.\n * @param\tmd5\t\tThe md5 to add.\n * @param\tpath\tThe path to the image with this md5.\n *\/\nvoid Profile::setMd5(const QString &md5, const QString &path)\n{\n\tm_md5s[md5] = path;\n}\n\n\/**\n * Removes a md5 from the _md5 map and removes it from the md5 file.\n * @param\tmd5\t\tThe md5 to remove.\n *\/\nvoid Profile::removeMd5(const QString &md5)\n{\n\tm_md5s.remove(md5);\n}\n\n\nvoid Profile::addAutoComplete(const QString &tag)\n{\n\tm_customAutoComplete.append(tag);\n}\n\n\nvoid Profile::addSite(Site *site)\n{\n\tm_sites.insert(site->url(), site);\n\temit sitesChanged();\n}\n\nvoid Profile::removeSite(Site *site)\n{\n\tm_sites.remove(site->url());\n\temit siteDeleted(site);\n\temit sitesChanged();\n}\n\n\nvoid Profile::setBlacklistedTags(const QStringList &tags)\n{\n\tm_blacklistedTags = tags;\n\temit blacklistChanged();\n}\n\nvoid Profile::addBlacklistedTag(const QString &tag)\n{\n\tm_blacklistedTags.append(tag);\n\temit blacklistChanged();\n}\n\nvoid Profile::removeBlacklistedTag(const QString &tag)\n{\n\tm_blacklistedTags.removeAll(tag);\n\temit blacklistChanged();\n}\n\n\nQString Profile::getPath() const\t\t\t\t{ return m_path;\t\t\t\t}\nQSettings *Profile::getSettings() const\t\t\t{ return m_settings;\t\t\t}\nQList<Favorite> &Profile::getFavorites()\t\t{ return m_favorites;\t\t\t}\nQStringList &Profile::getKeptForLater()\t\t\t{ return m_keptForLater;\t\t}\nQStringList &Profile::getIgnored()\t\t\t\t{ return m_ignored;\t\t\t\t}\nCommands &Profile::getCommands()\t\t\t\t{ return *m_commands;\t\t\t}\nQStringList &Profile::getAutoComplete()\t\t\t{ return m_autoComplete;\t\t}\nQStringList &Profile::getCustomAutoComplete()\t{ return m_customAutoComplete;\t}\nQStringList &Profile::getBlacklist()\t\t\t{ return m_blacklistedTags;\t\t}\nconst QMap<QString, Source*> &Profile::getSources() const\t{ return m_sources;\t}\nconst QMap<QString, Site*> &Profile::getSites() const\t\t{ return m_sites;\t}\n\nQList<Site*> Profile::getFilteredSites(const QStringList &urls) const\n{\n\tQList<Site*> ret;\n\tfor (const QString &url : urls)\n\t\tif (m_sites.contains(url))\n\t\t\tret.append(m_sites.value(url));\n\treturn ret;\n}\n<commit_msg>Keep favorites.txt after conversion in case of issues<commit_after>#include \"models\/profile.h\"\n#include <QDir>\n#include <QFile>\n#include <QJsonArray>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include \"commands\/commands.h\"\n#include \"models\/site.h\"\n\n\nProfile::Profile()\n\t: m_settings(nullptr), m_commands(nullptr)\n{}\nProfile::Profile(QSettings *settings, const QList<Favorite> &favorites, const QStringList &keptForLater, const QString &path)\n\t: m_path(path), m_settings(settings), m_favorites(favorites), m_keptForLater(keptForLater), m_commands(nullptr)\n{}\nProfile::Profile(const QString &path)\n\t: m_path(path)\n{\n\tm_settings = new QSettings(m_path + \"\/settings.ini\", QSettings::IniFormat);\n\n\t\/\/ Load sources\n\tQStringList dirs = QDir(m_path + \"\/sites\/\").entryList(QDir::Dirs | QDir::NoDotAndDotDot);\n\tfor (const QString &dir : dirs)\n\t{\n\t\tSource *source = new Source(this, m_path + \"\/sites\/\" + dir);\n\t\tm_sources.insert(source->getName(), source);\n\n\t\tfor (Site *site : source->getSites())\n\t\t\tm_sites.insert(site->url(), site);\n\t}\n\n\t\/\/ Load favorites\n\tQSet<QString> unique;\n\tQFile fileFavoritesJson(m_path + \"\/favorites.json\");\n\tif (fileFavoritesJson.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQByteArray data = fileFavoritesJson.readAll();\n\t\tQJsonDocument loadDoc = QJsonDocument::fromJson(data);\n\t\tQJsonObject object = loadDoc.object();\n\n\t\tQJsonArray favorites = object[\"favorites\"].toArray();\n\t\tfor (auto favoriteJson : favorites)\n\t\t{\n\t\t\tFavorite fav = Favorite::fromJson(m_path, favoriteJson.toObject(), m_sites);\n\t\t\tif (!unique.contains(fav.getName()))\n\t\t\t{\n\t\t\t\tunique.insert(fav.getName());\n\t\t\t\tm_favorites.append(fav);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tQFile fileFavorites(m_path + \"\/favorites.txt\");\n\t\tif (fileFavorites.open(QFile::ReadOnly | QFile::Text))\n\t\t{\n\t\t\tQString favs = fileFavorites.readAll();\n\t\t\tfileFavorites.close();\n\n\t\t\tQStringList words = favs.split(\"\\n\", QString::SkipEmptyParts);\n\t\t\tm_favorites.reserve(words.count());\n\t\t\tfor (const QString &word : words)\n\t\t\t{\n\t\t\t\tFavorite fav = Favorite::fromString(m_path, word);\n\t\t\t\tif (!unique.contains(fav.getName()))\n\t\t\t\t{\n\t\t\t\t\tunique.insert(fav.getName());\n\t\t\t\t\tm_favorites.append(fav);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Load view it later\n\tQFile fileKfl(m_path + \"\/viewitlater.txt\");\n\tif (fileKfl.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString vil = fileKfl.readAll();\n\t\tfileKfl.close();\n\n\t\tm_keptForLater = vil.split(\"\\n\", QString::SkipEmptyParts);\n\t}\n\n\t\/\/ Load ignored\n\tQFile fileIgnored(m_path + \"\/ignore.txt\");\n\tif (fileIgnored.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString ign = fileIgnored.readAll();\n\t\tfileIgnored.close();\n\n\t\tm_ignored = ign.split(\"\\n\", QString::SkipEmptyParts);\n\t}\n\n\t\/\/ Load MD5s\n\tQFile fileMD5(m_path + \"\/md5s.txt\");\n\tif (fileMD5.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString line;\n\t\twhile (!(line = fileMD5.readLine()).isEmpty())\n\t\t\tm_md5s.insert(line.left(32), line.mid(32).trimmed());\n\n\t\tfileMD5.close();\n\t}\n\n\t\/\/ Load auto-complete\n\tQFile fileAutoComplete(m_path + \"\/words.txt\");\n\tif (fileAutoComplete.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString line;\n\t\twhile (!(line = fileAutoComplete.readLine()).isEmpty())\n\t\t\tm_autoComplete.append(line.trimmed().split(\" \", QString::SkipEmptyParts));\n\n\t\tfileAutoComplete.close();\n\t}\n\n\t\/\/ Load custom auto-complete\n\tQFile fileCustomAutoComplete(m_path + \"\/wordsc.txt\");\n\tif (fileCustomAutoComplete.open(QFile::ReadOnly | QFile::Text))\n\t{\n\t\tQString line;\n\t\twhile (!(line = fileCustomAutoComplete.readLine()).isEmpty())\n\t\t\tm_customAutoComplete.append(line.trimmed().split(\" \", QString::SkipEmptyParts));\n\n\t\tfileCustomAutoComplete.close();\n\t}\n\n\tm_commands = new Commands(this);\n\n\t\/\/ Blacklisted tags\n\tm_blacklistedTags = m_settings->value(\"blacklistedtags\").toString().split(' ', QString::SkipEmptyParts);\n}\n\nProfile::~Profile()\n{\n\tsync();\n\n\tif (m_settings != nullptr)\n\t\tm_settings->deleteLater();\n\n\tqDeleteAll(m_sources);\n\tdelete m_commands;\n}\n\n\nvoid Profile::sync()\n{\n\tif (m_path.isEmpty())\n\t\treturn;\n\n\tsyncFavorites();\n\tsyncKeptForLater();\n\tsyncIgnored();\n\n\t\/\/ MD5s\n\tQFile fileMD5(m_path + \"\/md5s.txt\");\n\tif (fileMD5.open(QFile::WriteOnly | QFile::Truncate))\n\t{\n\t\tQStringList md5s = m_md5s.keys();\n\t\tQStringList paths = m_md5s.values();\n\t\tfor (int i = 0; i < md5s.size(); i++)\n\t\t\tfileMD5.write(QString(md5s[i] + paths[i] + \"\\n\").toUtf8());\n\n\t\tfileMD5.close();\n\t}\n\n\t\/\/ Custom auto-complete\n\tQFile fileCustomAutoComplete(m_path + \"\/wordsc.txt\");\n\tif (fileCustomAutoComplete.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))\n\t{\n\t\tfileCustomAutoComplete.write(m_customAutoComplete.join(\"\\r\\n\").toUtf8());\n\t\tfileCustomAutoComplete.close();\n\t}\n\n\t\/\/ Update commands settings\n\tauto *oldCommands = m_commands;\n\tauto *newCommands = new Commands(this);\n\tm_commands = newCommands;\n\tdelete oldCommands;\n\n\t\/\/ Blacklisted tags\n\tm_settings->setValue(\"blacklistedtags\", m_blacklistedTags.join(' '));\n\n\t\/\/ Sync settings\n\tif (m_settings != nullptr)\n\t\tm_settings->sync();\n}\nvoid Profile::syncFavorites()\n{\n\tQFile fileFavorites(m_path + \"\/favorites.json\");\n\tif (fileFavorites.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))\n\t{\n\t\t\/\/ Generate JSON array\n\t\tQJsonArray favoritesJson;\n\t\tfor (const Favorite &fav : m_favorites)\n\t\t{\n\t\t\tQJsonObject unique;\n\t\t\tfav.toJson(unique);\n\t\t\tfavoritesJson.append(unique);\n\t\t}\n\n\t\t\/\/ Generate result\n\t\tQJsonObject full;\n\t\tfull[\"version\"] = 1;\n\t\tfull[\"favorites\"] = favoritesJson;\n\n\t\t\/\/ Write result\n\t\tQJsonDocument saveDoc(full);\n\t\tfileFavorites.write(saveDoc.toJson());\n\t\tfileFavorites.close();\n\t}\n}\nvoid Profile::syncKeptForLater()\n{\n\tQFile fileKfl(m_path + \"\/viewitlater.txt\");\n\tif (fileKfl.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))\n\t{\n\t\tfileKfl.write(m_keptForLater.join(\"\\r\\n\").toUtf8());\n\t\tfileKfl.close();\n\t}\n}\nvoid Profile::syncIgnored()\n{\n\tQFile fileIgnored(m_path + \"\/ignore.txt\");\n\tif (fileIgnored.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))\n\t{\n\t\tfileIgnored.write(m_ignored.join(\"\\r\\n\").toUtf8());\n\t\tfileIgnored.close();\n\t}\n}\n\nQString Profile::tempPath() const\n{\n\tQString tmp = QDir::tempPath();\n\tQString subDir = \"Grabber\";\n\tQDir(tmp).mkpath(subDir);\n\treturn tmp + QDir::separator() + subDir;\n}\n\nvoid Profile::addFavorite(const Favorite &fav)\n{\n\tm_favorites.removeAll(fav);\n\tm_favorites.append(fav);\n\n\tsyncFavorites();\n\temit favoritesChanged();\n}\nvoid Profile::removeFavorite(const Favorite &fav)\n{\n\tm_favorites.removeAll(fav);\n\n\tif (QFile::exists(m_path + \"\/thumbs\/\" + fav.getName(true) + \".png\"))\n\t\tQFile::remove(m_path + \"\/thumbs\/\" + fav.getName(true) + \".png\");\n\n\tsyncFavorites();\n\temit favoritesChanged();\n}\nvoid Profile::emitFavorite()\n{\n\tsyncFavorites();\n\temit favoritesChanged();\n}\n\nvoid Profile::addKeptForLater(const QString &tag)\n{\n\tm_keptForLater.removeAll(tag);\n\tm_keptForLater.append(tag);\n\n\tsyncKeptForLater();\n\temit keptForLaterChanged();\n}\nvoid Profile::removeKeptForLater(const QString &tag)\n{\n\tm_keptForLater.removeAll(tag);\n\n\tsyncKeptForLater();\n\temit keptForLaterChanged();\n}\n\nvoid Profile::addIgnored(const QString &tag)\n{\n\tm_ignored.removeAll(tag);\n\tm_ignored.append(tag);\n\n\tsyncIgnored();\n\temit ignoredChanged();\n}\nvoid Profile::removeIgnored(const QString &tag)\n{\n\tm_ignored.removeAll(tag);\n\n\tsyncIgnored();\n\temit ignoredChanged();\n}\n\nQPair<QString, QString> Profile::md5Action(const QString &md5)\n{\n\tQString action = m_settings->value(\"Save\/md5Duplicates\", \"save\").toString();\n\tbool keepDeleted = m_settings->value(\"Save\/keepDeletedMd5\", false).toBool();\n\n\tbool contains = !md5.isEmpty() && m_md5s.contains(md5);\n\tQString path = contains ? m_md5s[md5] : QString();\n\tbool exists = contains && QFile::exists(path);\n\n\tif (contains && !exists)\n\t{\n\t\tif (!keepDeleted)\n\t\t{\n\t\t\tremoveMd5(md5);\n\t\t\tpath = QString();\n\t\t}\n\t\telse\n\t\t{ action = \"ignore\"; }\n\t}\n\n\treturn QPair<QString, QString>(action, path);\n}\n\n\/**\n * Check if a file with this md5 already exists;\n * @param\tmd5\t\tThe md5 that needs to be checked.\n * @return\t\t\tA QString containing the path to the already existing file, an empty QString if the md5 does not already exists.\n *\/\nQString Profile::md5Exists(const QString &md5)\n{\n\tif (m_md5s.contains(md5))\n\t{\n\t\tif (QFile::exists(m_md5s[md5]))\n\t\t\treturn m_md5s[md5];\n\n\t\tif (!m_settings->value(\"Save\/keepDeletedMd5\", false).toBool())\n\t\t\tremoveMd5(md5);\n\t}\n\treturn QString();\n}\n\n\/**\n * Adds a md5 to the _md5 map and adds it to the md5 file.\n * @param\tmd5\t\tThe md5 to add.\n * @param\tpath\tThe path to the image with this md5.\n *\/\nvoid Profile::addMd5(const QString &md5, const QString &path)\n{\n\tif (!md5.isEmpty())\n\t{ m_md5s.insert(md5, path); }\n}\n\n\/**\n * Set a md5 to the _md5 map changing the file it is pointing to.\n * @param\tmd5\t\tThe md5 to add.\n * @param\tpath\tThe path to the image with this md5.\n *\/\nvoid Profile::setMd5(const QString &md5, const QString &path)\n{\n\tm_md5s[md5] = path;\n}\n\n\/**\n * Removes a md5 from the _md5 map and removes it from the md5 file.\n * @param\tmd5\t\tThe md5 to remove.\n *\/\nvoid Profile::removeMd5(const QString &md5)\n{\n\tm_md5s.remove(md5);\n}\n\n\nvoid Profile::addAutoComplete(const QString &tag)\n{\n\tm_customAutoComplete.append(tag);\n}\n\n\nvoid Profile::addSite(Site *site)\n{\n\tm_sites.insert(site->url(), site);\n\temit sitesChanged();\n}\n\nvoid Profile::removeSite(Site *site)\n{\n\tm_sites.remove(site->url());\n\temit siteDeleted(site);\n\temit sitesChanged();\n}\n\n\nvoid Profile::setBlacklistedTags(const QStringList &tags)\n{\n\tm_blacklistedTags = tags;\n\temit blacklistChanged();\n}\n\nvoid Profile::addBlacklistedTag(const QString &tag)\n{\n\tm_blacklistedTags.append(tag);\n\temit blacklistChanged();\n}\n\nvoid Profile::removeBlacklistedTag(const QString &tag)\n{\n\tm_blacklistedTags.removeAll(tag);\n\temit blacklistChanged();\n}\n\n\nQString Profile::getPath() const\t\t\t\t{ return m_path;\t\t\t\t}\nQSettings *Profile::getSettings() const\t\t\t{ return m_settings;\t\t\t}\nQList<Favorite> &Profile::getFavorites()\t\t{ return m_favorites;\t\t\t}\nQStringList &Profile::getKeptForLater()\t\t\t{ return m_keptForLater;\t\t}\nQStringList &Profile::getIgnored()\t\t\t\t{ return m_ignored;\t\t\t\t}\nCommands &Profile::getCommands()\t\t\t\t{ return *m_commands;\t\t\t}\nQStringList &Profile::getAutoComplete()\t\t\t{ return m_autoComplete;\t\t}\nQStringList &Profile::getCustomAutoComplete()\t{ return m_customAutoComplete;\t}\nQStringList &Profile::getBlacklist()\t\t\t{ return m_blacklistedTags;\t\t}\nconst QMap<QString, Source*> &Profile::getSources() const\t{ return m_sources;\t}\nconst QMap<QString, Site*> &Profile::getSites() const\t\t{ return m_sites;\t}\n\nQList<Site*> Profile::getFilteredSites(const QStringList &urls) const\n{\n\tQList<Site*> ret;\n\tfor (const QString &url : urls)\n\t\tif (m_sites.contains(url))\n\t\t\tret.append(m_sites.value(url));\n\treturn ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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\/browser\/js_modal_dialog.h\"\n\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"ipc\/ipc_message.h\"\n\nJavaScriptAppModalDialog::JavaScriptAppModalDialog(\n JavaScriptMessageBoxClient* client,\n const std::wstring& title,\n int dialog_flags,\n const std::wstring& message_text,\n const std::wstring& default_prompt_text,\n bool display_suppress_checkbox,\n bool is_before_unload_dialog,\n IPC::Message* reply_msg)\n : AppModalDialog(client->AsTabContents(), title),\n client_(client),\n extension_host_(client->AsExtensionHost()),\n dialog_flags_(dialog_flags),\n message_text_(message_text),\n default_prompt_text_(default_prompt_text),\n display_suppress_checkbox_(display_suppress_checkbox),\n is_before_unload_dialog_(is_before_unload_dialog),\n reply_msg_(reply_msg) {\n DCHECK((tab_contents_ != NULL) != (extension_host_ != NULL));\n}\n\nJavaScriptAppModalDialog::~JavaScriptAppModalDialog() {\n}\n\nvoid JavaScriptAppModalDialog::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (skip_this_dialog_)\n return;\n\n if (NotificationType::EXTENSION_HOST_DESTROYED == type &&\n Details<ExtensionHost>(extension_host_) != details)\n return;\n\n \/\/ If we reach here, we know the notification is relevant to us, either\n \/\/ because we're only observing applicable sources or because we passed the\n \/\/ check above. Both of those indicate that we should ignore this dialog.\n \/\/ Also clear the client, since it's now invalid.\n skip_this_dialog_ = true;\n client_ = NULL;\n CloseModalDialog();\n}\n\nvoid JavaScriptAppModalDialog::InitNotifications() {\n \/\/ Make sure we get relevant navigation notifications so we know when our\n \/\/ parent contents will disappear or navigate to a different page.\n if (tab_contents_) {\n registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,\n Source<NavigationController>(&tab_contents_->controller()));\n registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,\n Source<TabContents>(tab_contents_));\n } else if (extension_host_) {\n \/\/ EXTENSION_HOST_DESTROYED uses the Profile as its source, but we care\n \/\/ about the ExtensionHost (which is passed in the details).\n registrar_.Add(this, NotificationType::EXTENSION_HOST_DESTROYED,\n NotificationService::AllSources());\n } else {\n NOTREACHED();\n }\n}\n\nvoid JavaScriptAppModalDialog::OnCancel() {\n \/\/ We need to do this before WM_DESTROY (WindowClosing()) as any parent frame\n \/\/ will receive its activation messages before this dialog receives\n \/\/ WM_DESTROY. The parent frame would then try to activate any modal dialogs\n \/\/ that were still open in the ModalDialogQueue, which would send activation\n \/\/ back to this one. The framework should be improved to handle this, so this\n \/\/ is a temporary workaround.\n CompleteDialog();\n\n if (!skip_this_dialog_) {\n client_->OnMessageBoxClosed(reply_msg_, false, std::wstring());\n }\n\n Cleanup();\n}\n\nvoid JavaScriptAppModalDialog::OnAccept(const std::wstring& prompt_text,\n bool suppress_js_messages) {\n CompleteDialog();\n\n if (!skip_this_dialog_) {\n client_->OnMessageBoxClosed(reply_msg_, true, prompt_text);\n if (suppress_js_messages)\n client_->SetSuppressMessageBoxes(true);\n }\n\n Cleanup();\n}\n\nvoid JavaScriptAppModalDialog::OnClose() {\n Cleanup();\n}\n\nvoid JavaScriptAppModalDialog::Cleanup() {\n if (skip_this_dialog_) {\n \/\/ We can't use the client_, because we might be in the process of\n \/\/ destroying it.\n if (tab_contents_)\n tab_contents_->OnMessageBoxClosed(reply_msg_, false, L\"\");\n\/\/ The extension_host_ will always be a dirty pointer on OS X because the alert\n\/\/ window will cause the extension popup to close since it is resigning its key\n\/\/ state, destroying the host. http:\/\/crbug.com\/29355\n#if !defined(OS_MACOSX)\n else if (extension_host_)\n extension_host_->OnMessageBoxClosed(reply_msg_, false, L\"\");\n else\n NOTREACHED();\n#endif\n }\n AppModalDialog::Cleanup();\n}\n\n<commit_msg>Fixed regression due to refactoring change from http:\/\/codereview.chromium.org\/560030\/show<commit_after>\/\/ Copyright (c) 2010 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\/browser\/js_modal_dialog.h\"\n\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"ipc\/ipc_message.h\"\n\nJavaScriptAppModalDialog::JavaScriptAppModalDialog(\n JavaScriptMessageBoxClient* client,\n const std::wstring& title,\n int dialog_flags,\n const std::wstring& message_text,\n const std::wstring& default_prompt_text,\n bool display_suppress_checkbox,\n bool is_before_unload_dialog,\n IPC::Message* reply_msg)\n : AppModalDialog(client->AsTabContents(), title),\n client_(client),\n extension_host_(client->AsExtensionHost()),\n dialog_flags_(dialog_flags),\n message_text_(message_text),\n default_prompt_text_(default_prompt_text),\n display_suppress_checkbox_(display_suppress_checkbox),\n is_before_unload_dialog_(is_before_unload_dialog),\n reply_msg_(reply_msg) {\n DCHECK((tab_contents_ != NULL) != (extension_host_ != NULL));\n InitNotifications();\n}\n\nJavaScriptAppModalDialog::~JavaScriptAppModalDialog() {\n}\n\nvoid JavaScriptAppModalDialog::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (skip_this_dialog_)\n return;\n\n if (NotificationType::EXTENSION_HOST_DESTROYED == type &&\n Details<ExtensionHost>(extension_host_) != details)\n return;\n\n \/\/ If we reach here, we know the notification is relevant to us, either\n \/\/ because we're only observing applicable sources or because we passed the\n \/\/ check above. Both of those indicate that we should ignore this dialog.\n \/\/ Also clear the client, since it's now invalid.\n skip_this_dialog_ = true;\n client_ = NULL;\n CloseModalDialog();\n}\n\nvoid JavaScriptAppModalDialog::InitNotifications() {\n \/\/ Make sure we get relevant navigation notifications so we know when our\n \/\/ parent contents will disappear or navigate to a different page.\n if (tab_contents_) {\n registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,\n Source<NavigationController>(&tab_contents_->controller()));\n registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,\n Source<TabContents>(tab_contents_));\n } else if (extension_host_) {\n \/\/ EXTENSION_HOST_DESTROYED uses the Profile as its source, but we care\n \/\/ about the ExtensionHost (which is passed in the details).\n registrar_.Add(this, NotificationType::EXTENSION_HOST_DESTROYED,\n NotificationService::AllSources());\n } else {\n NOTREACHED();\n }\n}\n\nvoid JavaScriptAppModalDialog::OnCancel() {\n \/\/ We need to do this before WM_DESTROY (WindowClosing()) as any parent frame\n \/\/ will receive its activation messages before this dialog receives\n \/\/ WM_DESTROY. The parent frame would then try to activate any modal dialogs\n \/\/ that were still open in the ModalDialogQueue, which would send activation\n \/\/ back to this one. The framework should be improved to handle this, so this\n \/\/ is a temporary workaround.\n CompleteDialog();\n\n if (!skip_this_dialog_) {\n client_->OnMessageBoxClosed(reply_msg_, false, std::wstring());\n }\n\n Cleanup();\n}\n\nvoid JavaScriptAppModalDialog::OnAccept(const std::wstring& prompt_text,\n bool suppress_js_messages) {\n CompleteDialog();\n\n if (!skip_this_dialog_) {\n client_->OnMessageBoxClosed(reply_msg_, true, prompt_text);\n if (suppress_js_messages)\n client_->SetSuppressMessageBoxes(true);\n }\n\n Cleanup();\n}\n\nvoid JavaScriptAppModalDialog::OnClose() {\n Cleanup();\n}\n\nvoid JavaScriptAppModalDialog::Cleanup() {\n if (skip_this_dialog_) {\n \/\/ We can't use the client_, because we might be in the process of\n \/\/ destroying it.\n if (tab_contents_)\n tab_contents_->OnMessageBoxClosed(reply_msg_, false, L\"\");\n\/\/ The extension_host_ will always be a dirty pointer on OS X because the alert\n\/\/ window will cause the extension popup to close since it is resigning its key\n\/\/ state, destroying the host. http:\/\/crbug.com\/29355\n#if !defined(OS_MACOSX)\n else if (extension_host_)\n extension_host_->OnMessageBoxClosed(reply_msg_, false, L\"\");\n else\n NOTREACHED();\n#endif\n }\n AppModalDialog::Cleanup();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"chrome\/browser\/net\/url_fetcher.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/net\/url_request_context_getter.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nstatic const int kBufferSize = 4096;\n\nbool URLFetcher::g_interception_enabled = false;\n\nclass URLFetcher::Core\n : public base::RefCountedThreadSafe<URLFetcher::Core>,\n public URLRequest::Delegate {\n public:\n \/\/ For POST requests, set |content_type| to the MIME type of the content\n \/\/ and set |content| to the data to upload. |flags| are flags to apply to\n \/\/ the load operation--these should be one or more of the LOAD_* flags\n \/\/ defined in url_request.h.\n Core(URLFetcher* fetcher,\n const GURL& original_url,\n RequestType request_type,\n URLFetcher::Delegate* d);\n\n \/\/ Starts the load. It's important that this not happen in the constructor\n \/\/ because it causes the IO thread to begin AddRef()ing and Release()ing\n \/\/ us. If our caller hasn't had time to fully construct us and take a\n \/\/ reference, the IO thread could interrupt things, run a task, Release()\n \/\/ us, and destroy us, leaving the caller with an already-destroyed object\n \/\/ when construction finishes.\n void Start();\n\n \/\/ Stops any in-progress load and ensures no callback will happen. It is\n \/\/ safe to call this multiple times.\n void Stop();\n\n \/\/ URLRequest::Delegate implementations\n virtual void OnResponseStarted(URLRequest* request);\n virtual void OnReadCompleted(URLRequest* request, int bytes_read);\n\n URLFetcher::Delegate* delegate() const { return delegate_; }\n\n private:\n friend class base::RefCountedThreadSafe<URLFetcher::Core>;\n\n ~Core() {}\n\n \/\/ Wrapper functions that allow us to ensure actions happen on the right\n \/\/ thread.\n void StartURLRequest();\n void CancelURLRequest();\n void OnCompletedURLRequest(const URLRequestStatus& status);\n\n URLFetcher* fetcher_; \/\/ Corresponding fetcher object\n GURL original_url_; \/\/ The URL we were asked to fetch\n GURL url_; \/\/ The URL we eventually wound up at\n RequestType request_type_; \/\/ What type of request is this?\n URLFetcher::Delegate* delegate_; \/\/ Object to notify on completion\n MessageLoop* delegate_loop_; \/\/ Message loop of the creating thread\n URLRequest* request_; \/\/ The actual request this wraps\n int load_flags_; \/\/ Flags for the load operation\n int response_code_; \/\/ HTTP status code for the request\n std::string data_; \/\/ Results of the request\n scoped_refptr<net::IOBuffer> buffer_;\n \/\/ Read buffer\n scoped_refptr<URLRequestContextGetter> request_context_getter_;\n \/\/ Cookie\/cache info for the request\n ResponseCookies cookies_; \/\/ Response cookies\n std::string extra_request_headers_;\/\/ Extra headers for the request, if any\n scoped_refptr<net::HttpResponseHeaders> response_headers_;\n\n std::string upload_content_; \/\/ HTTP POST payload\n std::string upload_content_type_; \/\/ MIME type of POST payload\n\n \/\/ The overload protection entry for this URL. This is used to\n \/\/ incrementally back off how rapidly we'll send requests to a particular\n \/\/ URL, to avoid placing too much demand on the remote resource. We update\n \/\/ this with the status of all requests as they return, and in turn use it\n \/\/ to determine how long to wait before making another request.\n URLFetcherProtectEntry* protect_entry_;\n \/\/ |num_retries_| indicates how many times we've failed to successfully\n \/\/ fetch this URL. Once this value exceeds the maximum number of retries\n \/\/ specified by the protection manager, we'll give up.\n int num_retries_;\n\n friend class URLFetcher;\n DISALLOW_COPY_AND_ASSIGN(Core);\n};\n\n\/\/ static\nURLFetcher::Factory* URLFetcher::factory_ = NULL;\n\nURLFetcher::URLFetcher(const GURL& url,\n RequestType request_type,\n Delegate* d)\n : ALLOW_THIS_IN_INITIALIZER_LIST(\n core_(new Core(this, url, request_type, d))) {\n}\n\nURLFetcher::~URLFetcher() {\n core_->Stop();\n}\n\n\/\/ static\nURLFetcher* URLFetcher::Create(int id, const GURL& url,\n RequestType request_type, Delegate* d) {\n return factory_ ? factory_->CreateURLFetcher(id, url, request_type, d) :\n new URLFetcher(url, request_type, d);\n}\n\nURLFetcher::Core::Core(URLFetcher* fetcher,\n const GURL& original_url,\n RequestType request_type,\n URLFetcher::Delegate* d)\n : fetcher_(fetcher),\n original_url_(original_url),\n request_type_(request_type),\n delegate_(d),\n delegate_loop_(MessageLoop::current()),\n request_(NULL),\n load_flags_(net::LOAD_NORMAL),\n response_code_(-1),\n buffer_(new net::IOBuffer(kBufferSize)),\n protect_entry_(URLFetcherProtectManager::GetInstance()->Register(\n original_url_.host())),\n num_retries_(0) {\n}\n\nvoid URLFetcher::Core::Start() {\n DCHECK(delegate_loop_);\n DCHECK(request_context_getter_) << \"We need an URLRequestContext!\";\n ChromeThread::PostDelayedTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &Core::StartURLRequest),\n protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SEND));\n}\n\nvoid URLFetcher::Core::Stop() {\n DCHECK_EQ(MessageLoop::current(), delegate_loop_);\n delegate_ = NULL;\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &Core::CancelURLRequest));\n}\n\nvoid URLFetcher::Core::OnResponseStarted(URLRequest* request) {\n DCHECK(request == request_);\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n if (request_->status().is_success()) {\n response_code_ = request_->GetResponseCode();\n response_headers_ = request_->response_headers();\n }\n\n int bytes_read = 0;\n \/\/ Some servers may treat HEAD requests as GET requests. To free up the\n \/\/ network connection as soon as possible, signal that the request has\n \/\/ completed immediately, without trying to read any data back (all we care\n \/\/ about is the response code and headers, which we already have).\n if (request_->status().is_success() && (request_type_ != HEAD))\n request_->Read(buffer_, kBufferSize, &bytes_read);\n OnReadCompleted(request_, bytes_read);\n}\n\nvoid URLFetcher::Core::OnReadCompleted(URLRequest* request, int bytes_read) {\n DCHECK(request == request_);\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n url_ = request->url();\n\n do {\n if (!request_->status().is_success() || bytes_read <= 0)\n break;\n data_.append(buffer_->data(), bytes_read);\n } while (request_->Read(buffer_, kBufferSize, &bytes_read));\n\n if (request_->status().is_success())\n request_->GetResponseCookies(&cookies_);\n\n \/\/ See comments re: HEAD requests in OnResponseStarted().\n if (!request_->status().is_io_pending() || (request_type_ == HEAD)) {\n delegate_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &Core::OnCompletedURLRequest, request_->status()));\n delete request_;\n request_ = NULL;\n }\n}\n\nvoid URLFetcher::Core::StartURLRequest() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n DCHECK(!request_);\n\n request_ = new URLRequest(original_url_, this);\n int flags = request_->load_flags() | load_flags_;\n if (!g_interception_enabled) {\n flags = flags | net::LOAD_DISABLE_INTERCEPT;\n }\n request_->set_load_flags(flags);\n request_->set_context(request_context_getter_->GetURLRequestContext());\n\n switch (request_type_) {\n case GET:\n break;\n\n case POST:\n DCHECK(!upload_content_.empty());\n DCHECK(!upload_content_type_.empty());\n\n request_->set_method(\"POST\");\n if (!extra_request_headers_.empty())\n extra_request_headers_ += \"\\r\\n\";\n StringAppendF(&extra_request_headers_,\n \"Content-Type: %s\", upload_content_type_.c_str());\n request_->AppendBytesToUpload(upload_content_.data(),\n static_cast<int>(upload_content_.size()));\n break;\n\n case HEAD:\n request_->set_method(\"HEAD\");\n break;\n\n default:\n NOTREACHED();\n }\n\n if (!extra_request_headers_.empty())\n request_->SetExtraRequestHeaders(extra_request_headers_);\n\n request_->Start();\n}\n\nvoid URLFetcher::Core::CancelURLRequest() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n if (request_) {\n request_->Cancel();\n delete request_;\n request_ = NULL;\n }\n \/\/ Release the reference to the request context. There could be multiple\n \/\/ references to URLFetcher::Core at this point so it may take a while to\n \/\/ delete the object, but we cannot delay the destruction of the request\n \/\/ context.\n request_context_getter_ = NULL;\n}\n\nvoid URLFetcher::Core::OnCompletedURLRequest(const URLRequestStatus& status) {\n DCHECK(MessageLoop::current() == delegate_loop_);\n\n \/\/ Checks the response from server.\n if (response_code_ >= 500) {\n \/\/ When encountering a server error, we will send the request again\n \/\/ after backoff time.\n const int64 wait =\n protect_entry_->UpdateBackoff(URLFetcherProtectEntry::FAILURE);\n ++num_retries_;\n \/\/ Restarts the request if we still need to notify the delegate.\n if (delegate_) {\n if (num_retries_ <= protect_entry_->max_retries()) {\n ChromeThread::PostDelayedTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &Core::StartURLRequest), wait);\n } else {\n delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_,\n cookies_, data_);\n }\n }\n } else {\n protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SUCCESS);\n if (delegate_)\n delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_,\n cookies_, data_);\n }\n}\n\nvoid URLFetcher::set_upload_data(const std::string& upload_content_type,\n const std::string& upload_content) {\n core_->upload_content_type_ = upload_content_type;\n core_->upload_content_ = upload_content;\n}\n\nvoid URLFetcher::set_load_flags(int load_flags) {\n core_->load_flags_ = load_flags;\n}\n\nint URLFetcher::load_flags() const {\n return core_->load_flags_;\n}\n\nvoid URLFetcher::set_extra_request_headers(\n const std::string& extra_request_headers) {\n core_->extra_request_headers_ = extra_request_headers;\n}\n\nvoid URLFetcher::set_request_context(\n URLRequestContextGetter* request_context_getter) {\n core_->request_context_getter_ = request_context_getter;\n}\n\nnet::HttpResponseHeaders* URLFetcher::response_headers() const {\n return core_->response_headers_;\n}\n\nvoid URLFetcher::Start() {\n core_->Start();\n}\n\nconst GURL& URLFetcher::url() const {\n return core_->url_;\n}\n\nURLFetcher::Delegate* URLFetcher::delegate() const {\n return core_->delegate();\n}\n<commit_msg>Add instrumentation to track down a crash.<commit_after>\/\/ 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 \"chrome\/browser\/net\/url_fetcher.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/net\/url_request_context_getter.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nstatic const int kBufferSize = 4096;\n\nbool URLFetcher::g_interception_enabled = false;\n\nclass URLFetcher::Core\n : public base::RefCountedThreadSafe<URLFetcher::Core>,\n public URLRequest::Delegate {\n public:\n \/\/ For POST requests, set |content_type| to the MIME type of the content\n \/\/ and set |content| to the data to upload. |flags| are flags to apply to\n \/\/ the load operation--these should be one or more of the LOAD_* flags\n \/\/ defined in url_request.h.\n Core(URLFetcher* fetcher,\n const GURL& original_url,\n RequestType request_type,\n URLFetcher::Delegate* d);\n\n \/\/ Starts the load. It's important that this not happen in the constructor\n \/\/ because it causes the IO thread to begin AddRef()ing and Release()ing\n \/\/ us. If our caller hasn't had time to fully construct us and take a\n \/\/ reference, the IO thread could interrupt things, run a task, Release()\n \/\/ us, and destroy us, leaving the caller with an already-destroyed object\n \/\/ when construction finishes.\n void Start();\n\n \/\/ Stops any in-progress load and ensures no callback will happen. It is\n \/\/ safe to call this multiple times.\n void Stop();\n\n \/\/ URLRequest::Delegate implementations\n virtual void OnResponseStarted(URLRequest* request);\n virtual void OnReadCompleted(URLRequest* request, int bytes_read);\n\n URLFetcher::Delegate* delegate() const { return delegate_; }\n\n private:\n friend class base::RefCountedThreadSafe<URLFetcher::Core>;\n\n ~Core() {}\n\n \/\/ Wrapper functions that allow us to ensure actions happen on the right\n \/\/ thread.\n void StartURLRequest();\n void CancelURLRequest();\n void OnCompletedURLRequest(const URLRequestStatus& status);\n\n URLFetcher* fetcher_; \/\/ Corresponding fetcher object\n GURL original_url_; \/\/ The URL we were asked to fetch\n GURL url_; \/\/ The URL we eventually wound up at\n RequestType request_type_; \/\/ What type of request is this?\n URLFetcher::Delegate* delegate_; \/\/ Object to notify on completion\n MessageLoop* delegate_loop_; \/\/ Message loop of the creating thread\n URLRequest* request_; \/\/ The actual request this wraps\n int load_flags_; \/\/ Flags for the load operation\n int response_code_; \/\/ HTTP status code for the request\n std::string data_; \/\/ Results of the request\n scoped_refptr<net::IOBuffer> buffer_;\n \/\/ Read buffer\n scoped_refptr<URLRequestContextGetter> request_context_getter_;\n \/\/ Cookie\/cache info for the request\n ResponseCookies cookies_; \/\/ Response cookies\n std::string extra_request_headers_;\/\/ Extra headers for the request, if any\n scoped_refptr<net::HttpResponseHeaders> response_headers_;\n\n std::string upload_content_; \/\/ HTTP POST payload\n std::string upload_content_type_; \/\/ MIME type of POST payload\n\n \/\/ The overload protection entry for this URL. This is used to\n \/\/ incrementally back off how rapidly we'll send requests to a particular\n \/\/ URL, to avoid placing too much demand on the remote resource. We update\n \/\/ this with the status of all requests as they return, and in turn use it\n \/\/ to determine how long to wait before making another request.\n URLFetcherProtectEntry* protect_entry_;\n \/\/ |num_retries_| indicates how many times we've failed to successfully\n \/\/ fetch this URL. Once this value exceeds the maximum number of retries\n \/\/ specified by the protection manager, we'll give up.\n int num_retries_;\n\n \/\/ Temporary member variable to test whether requests are being started\n \/\/ after they have already been cancelled.\n \/\/ TODO(eroman): Remove this after done investigating 27074.\n bool was_cancelled_;\n\n friend class URLFetcher;\n DISALLOW_COPY_AND_ASSIGN(Core);\n};\n\n\/\/ static\nURLFetcher::Factory* URLFetcher::factory_ = NULL;\n\nURLFetcher::URLFetcher(const GURL& url,\n RequestType request_type,\n Delegate* d)\n : ALLOW_THIS_IN_INITIALIZER_LIST(\n core_(new Core(this, url, request_type, d))) {\n}\n\nURLFetcher::~URLFetcher() {\n core_->Stop();\n}\n\n\/\/ static\nURLFetcher* URLFetcher::Create(int id, const GURL& url,\n RequestType request_type, Delegate* d) {\n return factory_ ? factory_->CreateURLFetcher(id, url, request_type, d) :\n new URLFetcher(url, request_type, d);\n}\n\nURLFetcher::Core::Core(URLFetcher* fetcher,\n const GURL& original_url,\n RequestType request_type,\n URLFetcher::Delegate* d)\n : fetcher_(fetcher),\n original_url_(original_url),\n request_type_(request_type),\n delegate_(d),\n delegate_loop_(MessageLoop::current()),\n request_(NULL),\n load_flags_(net::LOAD_NORMAL),\n response_code_(-1),\n buffer_(new net::IOBuffer(kBufferSize)),\n protect_entry_(URLFetcherProtectManager::GetInstance()->Register(\n original_url_.host())),\n num_retries_(0),\n was_cancelled_(false) {\n}\n\nvoid URLFetcher::Core::Start() {\n DCHECK(delegate_loop_);\n CHECK(request_context_getter_) << \"We need an URLRequestContext!\";\n ChromeThread::PostDelayedTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &Core::StartURLRequest),\n protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SEND));\n}\n\nvoid URLFetcher::Core::Stop() {\n DCHECK_EQ(MessageLoop::current(), delegate_loop_);\n delegate_ = NULL;\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &Core::CancelURLRequest));\n}\n\nvoid URLFetcher::Core::OnResponseStarted(URLRequest* request) {\n DCHECK(request == request_);\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n if (request_->status().is_success()) {\n response_code_ = request_->GetResponseCode();\n response_headers_ = request_->response_headers();\n }\n\n int bytes_read = 0;\n \/\/ Some servers may treat HEAD requests as GET requests. To free up the\n \/\/ network connection as soon as possible, signal that the request has\n \/\/ completed immediately, without trying to read any data back (all we care\n \/\/ about is the response code and headers, which we already have).\n if (request_->status().is_success() && (request_type_ != HEAD))\n request_->Read(buffer_, kBufferSize, &bytes_read);\n OnReadCompleted(request_, bytes_read);\n}\n\nvoid URLFetcher::Core::OnReadCompleted(URLRequest* request, int bytes_read) {\n DCHECK(request == request_);\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n url_ = request->url();\n\n do {\n if (!request_->status().is_success() || bytes_read <= 0)\n break;\n data_.append(buffer_->data(), bytes_read);\n } while (request_->Read(buffer_, kBufferSize, &bytes_read));\n\n if (request_->status().is_success())\n request_->GetResponseCookies(&cookies_);\n\n \/\/ See comments re: HEAD requests in OnResponseStarted().\n if (!request_->status().is_io_pending() || (request_type_ == HEAD)) {\n delegate_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &Core::OnCompletedURLRequest, request_->status()));\n delete request_;\n request_ = NULL;\n }\n}\n\nvoid URLFetcher::Core::StartURLRequest() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n CHECK(!was_cancelled_);\n CHECK(request_context_getter_);\n CHECK(!request_);\n\n request_ = new URLRequest(original_url_, this);\n int flags = request_->load_flags() | load_flags_;\n if (!g_interception_enabled) {\n flags = flags | net::LOAD_DISABLE_INTERCEPT;\n }\n request_->set_load_flags(flags);\n request_->set_context(request_context_getter_->GetURLRequestContext());\n\n switch (request_type_) {\n case GET:\n break;\n\n case POST:\n DCHECK(!upload_content_.empty());\n DCHECK(!upload_content_type_.empty());\n\n request_->set_method(\"POST\");\n if (!extra_request_headers_.empty())\n extra_request_headers_ += \"\\r\\n\";\n StringAppendF(&extra_request_headers_,\n \"Content-Type: %s\", upload_content_type_.c_str());\n request_->AppendBytesToUpload(upload_content_.data(),\n static_cast<int>(upload_content_.size()));\n break;\n\n case HEAD:\n request_->set_method(\"HEAD\");\n break;\n\n default:\n NOTREACHED();\n }\n\n if (!extra_request_headers_.empty())\n request_->SetExtraRequestHeaders(extra_request_headers_);\n\n request_->Start();\n}\n\nvoid URLFetcher::Core::CancelURLRequest() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n if (request_) {\n request_->Cancel();\n delete request_;\n request_ = NULL;\n }\n \/\/ Release the reference to the request context. There could be multiple\n \/\/ references to URLFetcher::Core at this point so it may take a while to\n \/\/ delete the object, but we cannot delay the destruction of the request\n \/\/ context.\n request_context_getter_ = NULL;\n was_cancelled_ = true;\n}\n\nvoid URLFetcher::Core::OnCompletedURLRequest(const URLRequestStatus& status) {\n DCHECK(MessageLoop::current() == delegate_loop_);\n\n \/\/ Checks the response from server.\n if (response_code_ >= 500) {\n \/\/ When encountering a server error, we will send the request again\n \/\/ after backoff time.\n const int64 wait =\n protect_entry_->UpdateBackoff(URLFetcherProtectEntry::FAILURE);\n ++num_retries_;\n \/\/ Restarts the request if we still need to notify the delegate.\n if (delegate_) {\n if (num_retries_ <= protect_entry_->max_retries()) {\n ChromeThread::PostDelayedTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &Core::StartURLRequest), wait);\n } else {\n delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_,\n cookies_, data_);\n }\n }\n } else {\n protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SUCCESS);\n if (delegate_)\n delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_,\n cookies_, data_);\n }\n}\n\nvoid URLFetcher::set_upload_data(const std::string& upload_content_type,\n const std::string& upload_content) {\n core_->upload_content_type_ = upload_content_type;\n core_->upload_content_ = upload_content;\n}\n\nvoid URLFetcher::set_load_flags(int load_flags) {\n core_->load_flags_ = load_flags;\n}\n\nint URLFetcher::load_flags() const {\n return core_->load_flags_;\n}\n\nvoid URLFetcher::set_extra_request_headers(\n const std::string& extra_request_headers) {\n core_->extra_request_headers_ = extra_request_headers;\n}\n\nvoid URLFetcher::set_request_context(\n URLRequestContextGetter* request_context_getter) {\n core_->request_context_getter_ = request_context_getter;\n}\n\nnet::HttpResponseHeaders* URLFetcher::response_headers() const {\n return core_->response_headers_;\n}\n\nvoid URLFetcher::Start() {\n core_->Start();\n}\n\nconst GURL& URLFetcher::url() const {\n return core_->url_;\n}\n\nURLFetcher::Delegate* URLFetcher::delegate() const {\n return core_->delegate();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Insight Segmentation & Registration Toolkit\nModule: itkGoodnessOfFitMixtureModelCostFunctionTest.cxx\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) 2002 Insight Consortium. All rights reserved.\nSee ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/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#include \"itkWin32Header.h\"\n\n#include <fstream>\n\n#include \"itkPoint.h\"\n#include \"itkPointSet.h\"\n#include \"itkArray.h\"\n\n#include \"itkPointSetToListAdaptor.h\"\n#include \"itkHistogram.h\"\n#include \"itkSubsample.h\"\n#include \"itkListSampleToHistogramFilter.h\"\n#include \"itkGaussianGoodnessOfFitComponent.h\"\n#include \"itkLogLikelihoodGoodnessOfFitFunction.h\"\n#include \"itkNormalVariateGenerator.h\"\n#include \"itkOnePlusOneEvolutionaryOptimizer.h\"\n#include \"itkGoodnessOfFitMixtureModelCostFunction.h\"\n\n#define NO_OF_DIMENSIONS 2\ntypedef double ValueType ;\n\nint itkGoodnessOfFitMixtureModelCostFunctionTest(int argc, char** argv)\n{\n namespace stat = itk::Statistics ;\n \n if (argc < 2)\n {\n std::cout << \"ERROR: data file name argument missing.\" \n << std::endl ;\n return EXIT_FAILURE;\n }\n\n int i ;\n char* dataFileName = argv[1] ;\n double minStandardDeviation =28.54746 ;\n\n std::vector< double > trueParams(6) ;\n trueParams[0] = 99.261 ;\n trueParams[1] = 100.078 ;\n trueParams[2] = 28.59448 ;\n trueParams[3] = 200.1 ;\n trueParams[4] = 201.3 ;\n trueParams[5] = 29.32210 ;\n \n std::vector< double > initialParams(6) ;\n initialParams[0] = 90.0 ;\n initialParams[1] = 90.0 ;\n initialParams[2] = 28.59448 ;\n \/\/initialParams[2] = 15 ;\n initialParams[3] = 190.0 ;\n initialParams[4] = 190.0;\n initialParams[5] = 29.32210 ;\n \/\/initialParams[5] = 15 ;\n\n std::vector< double > standardDeviations ;\n int maxIteration = 400 ;\n int dataSize = 2000 ;\n double histogramOverlap = 0.75 ;\n double histogramExtent = 1.5 ;\n double histogramUseEquiProbableBins = true ;\n float minimumGoodnessOfFitValue = -40 ;\n int numberOfClasses = 2 ;\n\n \/* Loading point data *\/\n typedef itk::PointSet< double, 2 > PointSetType ;\n PointSetType::Pointer pointSet = PointSetType::New() ;\n PointSetType::PointsContainerPointer pointsContainer = \n PointSetType::PointsContainer::New() ;\n pointsContainer->Reserve(dataSize) ;\n pointSet->SetPoints(pointsContainer.GetPointer()) ;\n\n PointSetType::PointsContainerIterator p_iter = pointsContainer->Begin() ;\n PointSetType::PointType point ;\n double temp ;\n std::ifstream dataStream(dataFileName) ;\n if ( !dataStream )\n {\n std::cout << \"ERROR: fail to open the data file.\" << std::endl ;\n return EXIT_FAILURE ;\n }\n\n while (p_iter != pointsContainer->End())\n {\n for ( i = 0 ; i < PointSetType::PointDimension ; i++)\n {\n dataStream >> temp ;\n point[i] = temp ;\n }\n p_iter.Value() = point ;\n ++p_iter ;\n }\n\n dataStream.close() ;\n\n \/* Importing the point set to the sample *\/\n typedef stat::PointSetToListAdaptor< PointSetType >\n DataSampleType;\n\n DataSampleType::Pointer sample =\n DataSampleType::New() ;\n \n sample->SetPointSet(pointSet);\n\n \/* =============================================== *\/\n typedef stat::GoodnessOfFitMixtureModelCostFunction< DataSampleType > \n CostFunctionType ;\n \n CostFunctionType::Pointer costFunction = CostFunctionType::New() ;\n\n \/\/ costFunction->SetInputSample(histogram.GetPointer()) ;\n\n typedef stat::GaussianGoodnessOfFitComponent< DataSampleType >\n ComponentType ;\n\n std::vector< ComponentType::Pointer > components(numberOfClasses) ;\n\n for (int i = 0 ; i < numberOfClasses ; i++)\n {\n components[i] = ComponentType::New() ;\n components[i]->SetHistogramNumberOfBins(6) ;\n components[i]->SetHistogramExtent(histogramExtent) ;\n components[i]->SetInputSample(sample) ;\n\n costFunction->AddComponent(components[i].GetPointer()) ;\n }\n\n \/* Initializing the goodness of fit function *\/\n typedef ComponentType::HistogramType ObservedHistogramType ;\n\n typedef stat::LogLikelihoodGoodnessOfFitFunction< ComponentType::HistogramType > FunctionType ;\n \n FunctionType::Pointer function = FunctionType::New() ;\n \n costFunction->SetFunction(function.GetPointer()) ;\n\n typedef stat::NormalVariateGenerator \n RandomVariateGeneratorType ;\n RandomVariateGeneratorType::Pointer randomGenerator = \n RandomVariateGeneratorType::New() ;\n randomGenerator->Initialize(3024) ;\n\n typedef itk::OnePlusOneEvolutionaryOptimizer\n OptimizerType ;\n \n unsigned int paramSize = costFunction->GetNumberOfParameters() ;\n CostFunctionType::ParametersType params(paramSize) ;\n\n for ( int i = 0 ; i < paramSize ; i++ )\n {\n params[i] = initialParams[i] ;\n }\n\n double initStepSize = 1.02 ;\n double grow = 1.05 ;\n double shrink = pow(grow, -0.25) ;\n OptimizerType::ScalesType scales(paramSize) ;\n scales.Fill(1.0) ;\n for ( int i = 0 ; i < paramSize ; i++)\n {\n if ( i % (NO_OF_DIMENSIONS + 1) == 2 )\n {\n scales[i] = 100.0 ;\n }\n }\n\n OptimizerType::Pointer optimizer = OptimizerType::New() ;\n optimizer->SetCostFunction(costFunction.GetPointer()) ;\n optimizer->Initialize(initStepSize, grow, shrink) ;\n optimizer->SetMaximumIteration(maxIteration) ;\n optimizer->SetNormalVariateGenerator(randomGenerator.GetPointer()) ;\n optimizer->SetInitialPosition(params) ;\n optimizer->SetScales(scales) ;\n optimizer->SetEpsilon(1.0e-6) ;\n\n \/* Optimizing *\/\n optimizer->StartOptimization() ;\n\n std::cout << \"DEBUG: current iteration = \" \n << optimizer->GetCurrentIteration() << std::endl ;\n\n bool passed = true ;\n double displacement ;\n int paramIndex = 0 ;\n for (unsigned int i = 0 ; i < numberOfClasses ; i++)\n {\n std::cout << \"Cluster[\" << i << \"]\" << std::endl ;\n std::cout << \" Parameters:\" << std::endl ;\n std::cout << \" \" << (components[i])->GetFullParameters() << std::endl ;\n displacement = 0.0 ;\n for (unsigned int j = 0 ; j < DataSampleType::MeasurementVectorSize ;\n j++)\n {\n temp = (components[i])->GetFullParameters()[j] - trueParams[paramIndex] ;\n displacement += (temp * temp) ;\n paramIndex++ ;\n }\n paramIndex++ ;\n displacement = sqrt(displacement) ;\n std::cout << \" Mean displacement: \" << std::endl ;\n std::cout << \" \" << displacement \n << std::endl << std::endl ;\n if ( displacement > (minStandardDeviation \/ 100.0) * 10 )\n {\n passed = false ;\n }\n }\n\n if( !passed )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n}\n<commit_msg><commit_after>\/*=========================================================================\n\nProgram: Insight Segmentation & Registration Toolkit\nModule: itkGoodnessOfFitMixtureModelCostFunctionTest.cxx\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) 2002 Insight Consortium. All rights reserved.\nSee ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/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#include \"itkWin32Header.h\"\n\n#include <fstream>\n\n#include \"itkPoint.h\"\n#include \"itkPointSet.h\"\n#include \"itkArray.h\"\n\n#include \"itkPointSetToListAdaptor.h\"\n#include \"itkHistogram.h\"\n#include \"itkSubsample.h\"\n#include \"itkListSampleToHistogramFilter.h\"\n#include \"itkGaussianGoodnessOfFitComponent.h\"\n#include \"itkLogLikelihoodGoodnessOfFitFunction.h\"\n#include \"itkNormalVariateGenerator.h\"\n#include \"itkOnePlusOneEvolutionaryOptimizer.h\"\n#include \"itkGoodnessOfFitMixtureModelCostFunction.h\"\n\n#define NO_OF_DIMENSIONS 2\ntypedef double ValueType ;\n\nint itkGoodnessOfFitMixtureModelCostFunctionTest(int argc, char** argv)\n{\n namespace stat = itk::Statistics ;\n \n if (argc < 2)\n {\n std::cout << \"ERROR: data file name argument missing.\" \n << std::endl ;\n return EXIT_FAILURE;\n }\n\n unsigned int i, j ;\n char* dataFileName = argv[1] ;\n double minStandardDeviation =28.54746 ;\n\n std::vector< double > trueParams(6) ;\n trueParams[0] = 99.261 ;\n trueParams[1] = 100.078 ;\n trueParams[2] = 28.59448 ;\n trueParams[3] = 200.1 ;\n trueParams[4] = 201.3 ;\n trueParams[5] = 29.32210 ;\n \n std::vector< double > initialParams(6) ;\n initialParams[0] = 90.0 ;\n initialParams[1] = 90.0 ;\n initialParams[2] = 28.59448 ;\n \/\/initialParams[2] = 15 ;\n initialParams[3] = 190.0 ;\n initialParams[4] = 190.0;\n initialParams[5] = 29.32210 ;\n \/\/initialParams[5] = 15 ;\n\n std::vector< double > standardDeviations ;\n int maxIteration = 400 ;\n int dataSize = 2000 ;\n double histogramOverlap = 0.75 ;\n unsigned int numberOfClasses = 2 ;\n\n \/* Loading point data *\/\n typedef itk::PointSet< double, 2 > PointSetType ;\n PointSetType::Pointer pointSet = PointSetType::New() ;\n PointSetType::PointsContainerPointer pointsContainer = \n PointSetType::PointsContainer::New() ;\n pointsContainer->Reserve(dataSize) ;\n pointSet->SetPoints(pointsContainer.GetPointer()) ;\n\n PointSetType::PointsContainerIterator p_iter = pointsContainer->Begin() ;\n PointSetType::PointType point ;\n double temp ;\n std::ifstream dataStream(dataFileName) ;\n if ( !dataStream )\n {\n std::cout << \"ERROR: fail to open the data file.\" << std::endl ;\n return EXIT_FAILURE ;\n }\n\n while (p_iter != pointsContainer->End())\n {\n for ( i = 0 ; i < PointSetType::PointDimension ; i++)\n {\n dataStream >> temp ;\n point[i] = temp ;\n }\n p_iter.Value() = point ;\n ++p_iter ;\n }\n\n dataStream.close() ;\n\n \/* Importing the point set to the sample *\/\n typedef stat::PointSetToListAdaptor< PointSetType >\n DataSampleType;\n\n DataSampleType::Pointer sample =\n DataSampleType::New() ;\n \n sample->SetPointSet(pointSet);\n\n \/* =============================================== *\/\n typedef stat::GoodnessOfFitMixtureModelCostFunction< DataSampleType > \n CostFunctionType ;\n \n CostFunctionType::Pointer costFunction = CostFunctionType::New() ;\n\n \/\/ costFunction->SetInputSample(histogram.GetPointer()) ;\n\n typedef stat::GaussianGoodnessOfFitComponent< DataSampleType >\n ComponentType ;\n\n std::vector< ComponentType::Pointer > components(numberOfClasses) ;\n\n for (int i = 0 ; i < numberOfClasses ; i++)\n {\n components[i] = ComponentType::New() ;\n components[i]->SetHistogramNumberOfBins(6) ;\n components[i]->SetHistogramExtent(histogramExtent) ;\n components[i]->SetInputSample(sample) ;\n\n costFunction->AddComponent(components[i].GetPointer()) ;\n }\n\n \/* Initializing the goodness of fit function *\/\n typedef ComponentType::HistogramType ObservedHistogramType ;\n\n typedef stat::LogLikelihoodGoodnessOfFitFunction< ComponentType::HistogramType > FunctionType ;\n \n FunctionType::Pointer function = FunctionType::New() ;\n \n costFunction->SetFunction(function.GetPointer()) ;\n\n typedef stat::NormalVariateGenerator \n RandomVariateGeneratorType ;\n RandomVariateGeneratorType::Pointer randomGenerator = \n RandomVariateGeneratorType::New() ;\n randomGenerator->Initialize(3024) ;\n\n typedef itk::OnePlusOneEvolutionaryOptimizer\n OptimizerType ;\n \n unsigned int paramSize = costFunction->GetNumberOfParameters() ;\n CostFunctionType::ParametersType params(paramSize) ;\n\n for ( i = 0 ; i < paramSize ; i++ )\n {\n params[i] = initialParams[i] ;\n }\n\n double initStepSize = 1.02 ;\n double grow = 1.05 ;\n double shrink = pow(grow, -0.25) ;\n OptimizerType::ScalesType scales(paramSize) ;\n scales.Fill(1.0) ;\n for ( i = 0 ; i < paramSize ; i++)\n {\n if ( i % (NO_OF_DIMENSIONS + 1) == 2 )\n {\n scales[i] = 100.0 ;\n }\n }\n\n OptimizerType::Pointer optimizer = OptimizerType::New() ;\n optimizer->SetCostFunction(costFunction.GetPointer()) ;\n optimizer->Initialize(initStepSize, grow, shrink) ;\n optimizer->SetMaximumIteration(maxIteration) ;\n optimizer->SetNormalVariateGenerator(randomGenerator.GetPointer()) ;\n optimizer->SetInitialPosition(params) ;\n optimizer->SetScales(scales) ;\n optimizer->SetEpsilon(1.0e-6) ;\n\n \/* Optimizing *\/\n optimizer->StartOptimization() ;\n\n std::cout << \"DEBUG: current iteration = \" \n << optimizer->GetCurrentIteration() << std::endl ;\n\n bool passed = true ;\n double displacement ;\n int paramIndex = 0 ;\n for ( i = 0 ; i < numberOfClasses ; i++)\n {\n std::cout << \"Cluster[\" << i << \"]\" << std::endl ;\n std::cout << \" Parameters:\" << std::endl ;\n std::cout << \" \" << (components[i])->GetFullParameters() << std::endl ;\n displacement = 0.0 ;\n for ( j = 0 ; j < DataSampleType::MeasurementVectorSize ;\n j++)\n {\n temp = (components[i])->GetFullParameters()[j] - trueParams[paramIndex] ;\n displacement += (temp * temp) ;\n paramIndex++ ;\n }\n paramIndex++ ;\n displacement = sqrt(displacement) ;\n std::cout << \" Mean displacement: \" << std::endl ;\n std::cout << \" \" << displacement \n << std::endl << std::endl ;\n if ( displacement > (minStandardDeviation \/ 100.0) * 10 )\n {\n passed = false ;\n }\n }\n\n if( !passed )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/framework\/allocator.h\"\n\n#include \"tensorflow\/core\/framework\/allocator_registry.h\"\n#include \"tensorflow\/core\/framework\/log_memory.h\"\n#include \"tensorflow\/core\/framework\/tracking_allocator.h\"\n#include \"tensorflow\/core\/lib\/strings\/stringprintf.h\"\n#include \"tensorflow\/core\/platform\/mem.h\"\n#include \"tensorflow\/core\/platform\/mutex.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n\nnamespace tensorflow {\n\nvoid AllocatorStats::Clear() {\n this->num_allocs = 0;\n this->bytes_in_use = 0;\n this->max_bytes_in_use = 0;\n this->max_alloc_size = 0;\n this->bytes_limit = 0;\n}\n\nstring AllocatorStats::DebugString() const {\n return strings::Printf(\n \"Limit: %20lld\\n\"\n \"InUse: %20lld\\n\"\n \"MaxInUse: %20lld\\n\"\n \"NumAllocs: %20lld\\n\"\n \"MaxAllocSize: %20lld\\n\",\n this->bytes_limit, this->bytes_in_use, this->max_bytes_in_use,\n this->num_allocs, this->max_alloc_size);\n}\n\nconstexpr size_t Allocator::kAllocatorAlignment;\n\nAllocator::~Allocator() {}\n\nvoid RunResourceCtor(ResourceHandle* p, size_t n) {\n for (size_t i = 0; i < n; ++p, ++i) new (p) ResourceHandle();\n}\n\nvoid RunResourceDtor(ResourceHandle* p, size_t n) {\n for (size_t i = 0; i < n; ++p, ++i) p->~ResourceHandle();\n}\n\n\/\/ If true, cpu allocator collects more stats.\nstatic bool cpu_allocator_collect_stats = false;\n\/\/ If true, cpu allocator collects full stats.\nstatic bool cpu_allocator_collect_full_stats = false;\n\nvoid EnableCPUAllocatorStats(bool enable) {\n cpu_allocator_collect_stats = enable;\n}\nvoid EnableCPUAllocatorFullStats(bool enable) {\n cpu_allocator_collect_full_stats = enable;\n}\n\nclass CPUAllocator : public Allocator {\n public:\n CPUAllocator() {}\n\n ~CPUAllocator() override {}\n\n string Name() override { return \"cpu\"; }\n\n void* AllocateRaw(size_t alignment, size_t num_bytes) override {\n void* p = port::AlignedMalloc(num_bytes, alignment);\n if (cpu_allocator_collect_stats) {\n const std::size_t alloc_size = port::MallocExtension_GetAllocatedSize(p);\n mutex_lock l(mu_);\n ++stats_.num_allocs;\n stats_.bytes_in_use += alloc_size;\n stats_.max_bytes_in_use =\n std::max<int64>(stats_.max_bytes_in_use, stats_.bytes_in_use);\n stats_.max_alloc_size =\n std::max<int64>(stats_.max_alloc_size, alloc_size);\n }\n return p;\n }\n\n void DeallocateRaw(void* ptr) override {\n if (cpu_allocator_collect_stats) {\n const std::size_t alloc_size =\n port::MallocExtension_GetAllocatedSize(ptr);\n mutex_lock l(mu_);\n stats_.bytes_in_use -= alloc_size;\n }\n port::AlignedFree(ptr);\n }\n\n void GetStats(AllocatorStats* stats) override {\n mutex_lock l(mu_);\n *stats = stats_;\n }\n\n size_t AllocatedSizeSlow(void* ptr) override {\n return port::MallocExtension_GetAllocatedSize(ptr);\n }\n\n private:\n mutex mu_;\n AllocatorStats stats_ GUARDED_BY(mu_);\n\n TF_DISALLOW_COPY_AND_ASSIGN(CPUAllocator);\n};\n\nnamespace {\nAllocator* MakeCpuAllocator() {\n Allocator* allocator = new CPUAllocator;\n if (cpu_allocator_collect_full_stats || LogMemory::IsEnabled()) {\n allocator = new TrackingAllocator(allocator, true);\n }\n return allocator;\n}\n} \/\/ namespace\n\nAllocator* cpu_allocator() {\n static Allocator* cpu_alloc = AllocatorRegistry::Global()->GetAllocator();\n if (cpu_allocator_collect_full_stats && !cpu_alloc->TracksAllocationSizes()) {\n cpu_alloc = new TrackingAllocator(cpu_alloc, true);\n }\n return cpu_alloc;\n}\n\nREGISTER_MEM_ALLOCATOR(\"DefaultCPUAllocator\", 100, CPUAllocator);\n\n} \/\/ namespace tensorflow\n<commit_msg>remove unused cpu allocator factory<commit_after>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/framework\/allocator.h\"\n\n#include \"tensorflow\/core\/framework\/allocator_registry.h\"\n#include \"tensorflow\/core\/framework\/log_memory.h\"\n#include \"tensorflow\/core\/framework\/tracking_allocator.h\"\n#include \"tensorflow\/core\/lib\/strings\/stringprintf.h\"\n#include \"tensorflow\/core\/platform\/mem.h\"\n#include \"tensorflow\/core\/platform\/mutex.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n\nnamespace tensorflow {\n\nvoid AllocatorStats::Clear() {\n this->num_allocs = 0;\n this->bytes_in_use = 0;\n this->max_bytes_in_use = 0;\n this->max_alloc_size = 0;\n this->bytes_limit = 0;\n}\n\nstring AllocatorStats::DebugString() const {\n return strings::Printf(\n \"Limit: %20lld\\n\"\n \"InUse: %20lld\\n\"\n \"MaxInUse: %20lld\\n\"\n \"NumAllocs: %20lld\\n\"\n \"MaxAllocSize: %20lld\\n\",\n this->bytes_limit, this->bytes_in_use, this->max_bytes_in_use,\n this->num_allocs, this->max_alloc_size);\n}\n\nconstexpr size_t Allocator::kAllocatorAlignment;\n\nAllocator::~Allocator() {}\n\nvoid RunResourceCtor(ResourceHandle* p, size_t n) {\n for (size_t i = 0; i < n; ++p, ++i) new (p) ResourceHandle();\n}\n\nvoid RunResourceDtor(ResourceHandle* p, size_t n) {\n for (size_t i = 0; i < n; ++p, ++i) p->~ResourceHandle();\n}\n\n\/\/ If true, cpu allocator collects more stats.\nstatic bool cpu_allocator_collect_stats = false;\n\/\/ If true, cpu allocator collects full stats.\nstatic bool cpu_allocator_collect_full_stats = false;\n\nvoid EnableCPUAllocatorStats(bool enable) {\n cpu_allocator_collect_stats = enable;\n}\nvoid EnableCPUAllocatorFullStats(bool enable) {\n cpu_allocator_collect_full_stats = enable;\n}\n\nclass CPUAllocator : public Allocator {\n public:\n CPUAllocator() {}\n\n ~CPUAllocator() override {}\n\n string Name() override { return \"cpu\"; }\n\n void* AllocateRaw(size_t alignment, size_t num_bytes) override {\n void* p = port::AlignedMalloc(num_bytes, alignment);\n if (cpu_allocator_collect_stats) {\n const std::size_t alloc_size = port::MallocExtension_GetAllocatedSize(p);\n mutex_lock l(mu_);\n ++stats_.num_allocs;\n stats_.bytes_in_use += alloc_size;\n stats_.max_bytes_in_use =\n std::max<int64>(stats_.max_bytes_in_use, stats_.bytes_in_use);\n stats_.max_alloc_size =\n std::max<int64>(stats_.max_alloc_size, alloc_size);\n }\n return p;\n }\n\n void DeallocateRaw(void* ptr) override {\n if (cpu_allocator_collect_stats) {\n const std::size_t alloc_size =\n port::MallocExtension_GetAllocatedSize(ptr);\n mutex_lock l(mu_);\n stats_.bytes_in_use -= alloc_size;\n }\n port::AlignedFree(ptr);\n }\n\n void GetStats(AllocatorStats* stats) override {\n mutex_lock l(mu_);\n *stats = stats_;\n }\n\n size_t AllocatedSizeSlow(void* ptr) override {\n return port::MallocExtension_GetAllocatedSize(ptr);\n }\n\n private:\n mutex mu_;\n AllocatorStats stats_ GUARDED_BY(mu_);\n\n TF_DISALLOW_COPY_AND_ASSIGN(CPUAllocator);\n};\n\nAllocator* cpu_allocator() {\n static Allocator* cpu_alloc = AllocatorRegistry::Global()->GetAllocator();\n if (cpu_allocator_collect_full_stats && !cpu_alloc->TracksAllocationSizes()) {\n cpu_alloc = new TrackingAllocator(cpu_alloc, true);\n }\n return cpu_alloc;\n}\n\nREGISTER_MEM_ALLOCATOR(\"DefaultCPUAllocator\", 100, CPUAllocator);\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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#if defined(OS_WIN)\n#include <windows.h>\n#endif\n\n#include \"chrome\/gpu\/gpu_watchdog_thread.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"build\/build_config.h\"\n\nnamespace {\nconst int64 kCheckPeriod = 2000;\n\nvoid DoNothing() {\n}\n}\n\nGpuWatchdogThread::GpuWatchdogThread(int timeout)\n : base::Thread(\"Watchdog\"),\n watched_message_loop_(MessageLoop::current()),\n timeout_(timeout),\n armed_(false),\n#if defined(OS_WIN)\n watched_thread_handle_(0),\n arm_time_(0),\n#endif\n ALLOW_THIS_IN_INITIALIZER_LIST(task_observer_(this)) {\n DCHECK(timeout >= 0);\n\n#if defined(OS_WIN)\n \/\/ GetCurrentThread returns a pseudo-handle that cannot be used by one thread\n \/\/ to identify another. DuplicateHandle creates a \"real\" handle that can be\n \/\/ used for this purpose.\n BOOL result = DuplicateHandle(GetCurrentProcess(),\n GetCurrentThread(),\n GetCurrentProcess(),\n &watched_thread_handle_,\n THREAD_QUERY_INFORMATION,\n FALSE,\n 0);\n DCHECK(result);\n#endif\n\n watched_message_loop_->AddTaskObserver(&task_observer_);\n}\n\nGpuWatchdogThread::~GpuWatchdogThread() {\n \/\/ Verify that the thread was explicitly stopped. If the thread is stopped\n \/\/ implicitly by the destructor, CleanUp() will not be called.\n DCHECK(!method_factory_.get());\n\n#if defined(OS_WIN)\n CloseHandle(watched_thread_handle_);\n#endif\n\n watched_message_loop_->RemoveTaskObserver(&task_observer_);\n}\n\nvoid GpuWatchdogThread::PostAcknowledge() {\n \/\/ Called on the monitored thread. Responds with OnAcknowledge. Cannot use\n \/\/ the method factory. Rely on reference counting instead.\n message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(this, &GpuWatchdogThread::OnAcknowledge));\n}\n\nvoid GpuWatchdogThread::Init() {\n \/\/ The method factory must be created on the watchdog thread.\n method_factory_.reset(new MethodFactory(this));\n\n \/\/ Schedule the first check.\n OnCheck();\n}\n\nvoid GpuWatchdogThread::CleanUp() {\n \/\/ The method factory must be destroyed on the watchdog thread.\n method_factory_->RevokeAll();\n method_factory_.reset();\n}\n\nGpuWatchdogThread::GpuWatchdogTaskObserver::GpuWatchdogTaskObserver(\n GpuWatchdogThread* watchdog)\n : watchdog_(watchdog) {\n}\n\nGpuWatchdogThread::GpuWatchdogTaskObserver::~GpuWatchdogTaskObserver() {\n}\n\nvoid GpuWatchdogThread::GpuWatchdogTaskObserver::WillProcessTask(\n const Task* task)\n{\n CheckArmed();\n}\n\nvoid GpuWatchdogThread::GpuWatchdogTaskObserver::DidProcessTask(\n const Task* task)\n{\n CheckArmed();\n}\n\nvoid GpuWatchdogThread::GpuWatchdogTaskObserver::CheckArmed()\n{\n \/\/ Acknowledge the watchdog if it has armed itself. The watchdog will not\n \/\/ change its armed state until it is acknowledged.\n if (watchdog_->armed()) {\n watchdog_->PostAcknowledge();\n }\n}\n\nvoid GpuWatchdogThread::OnAcknowledge() {\n \/\/ The check has already been acknowledged and another has already been\n \/\/ scheduled by a previous call to OnAcknowledge. It is normal for a\n \/\/ watched thread to see armed_ being true multiple times before\n \/\/ the OnAcknowledge task is run on the watchdog thread.\n if (!armed_)\n return;\n\n \/\/ Revoke any pending OnExit.\n method_factory_->RevokeAll();\n armed_ = false;\n\n \/\/ The monitored thread has responded. Post a task to check it again.\n message_loop()->PostDelayedTask(\n FROM_HERE,\n method_factory_->NewRunnableMethod(&GpuWatchdogThread::OnCheck),\n kCheckPeriod);\n}\n\n#if defined(OS_WIN)\nint64 GpuWatchdogThread::GetWatchedThreadTime() {\n FILETIME creation_time;\n FILETIME exit_time;\n FILETIME user_time;\n FILETIME kernel_time;\n BOOL result = GetThreadTimes(watched_thread_handle_,\n &creation_time,\n &exit_time,\n &kernel_time,\n &user_time);\n DCHECK(result);\n\n ULARGE_INTEGER user_time64;\n user_time64.HighPart = user_time.dwHighDateTime;\n user_time64.LowPart = user_time.dwLowDateTime;\n\n ULARGE_INTEGER kernel_time64;\n kernel_time64.HighPart = kernel_time.dwHighDateTime;\n kernel_time64.LowPart = kernel_time.dwLowDateTime;\n\n \/\/ Time is reported in units of 100 nanoseconds. Kernel and user time are\n \/\/ summed to deal with to kinds of hangs. One is where the GPU process is\n \/\/ stuck in user level, never calling into the kernel and kernel time is\n \/\/ not increasing. The other is where either the kernel hangs and never\n \/\/ returns to user level or where user level code\n \/\/ calls into kernel level repeatedly, giving up its quanta before it is\n \/\/ tracked, for example a loop that repeatedly Sleeps.\n return static_cast<int64>(\n (user_time64.QuadPart + kernel_time64.QuadPart) \/ 10000);\n}\n#endif\n\nvoid GpuWatchdogThread::OnCheck() {\n if (armed_)\n return;\n\n \/\/ Must set armed before posting the task. This task might be the only task\n \/\/ that will activate the TaskObserver on the watched thread and it must not\n \/\/ miss the false -> true transition.\n armed_ = true;\n\n#if defined(OS_WIN)\n arm_time_ = GetWatchedThreadTime();\n#endif\n\n \/\/ Post a task to the monitored thread that does nothing but wake up the\n \/\/ TaskObserver. Any other tasks that are pending on the watched thread will\n \/\/ also wake up the observer. This simply ensures there is at least one.\n watched_message_loop_->PostTask(\n FROM_HERE,\n NewRunnableFunction(DoNothing));\n\n \/\/ Post a task to the watchdog thread to exit if the monitored thread does\n \/\/ not respond in time.\n message_loop()->PostDelayedTask(\n FROM_HERE,\n method_factory_->NewRunnableMethod(&GpuWatchdogThread::OnExit),\n timeout_);\n}\n\n\/\/ Use the --disable-gpu-watchdog command line switch to disable this.\nvoid GpuWatchdogThread::OnExit() {\n#if defined(OS_WIN)\n \/\/ Defer termination until a certain amount of user time has elapsed.\n int64 time_since_arm = GetWatchedThreadTime() - arm_time_;\n if (time_since_arm < timeout_) {\n message_loop()->PostDelayedTask(\n FROM_HERE,\n method_factory_->NewRunnableMethod(&GpuWatchdogThread::OnExit),\n timeout_ - time_since_arm);\n return;\n }\n#endif\n\n \/\/ Make sure the timeout period is on the stack before crashing.\n volatile int timeout = timeout_;\n\n \/\/ For minimal developer annoyance, don't keep crashing.\n static bool crashed = false;\n if (crashed)\n return;\n\n#if defined(OS_WIN)\n if (IsDebuggerPresent())\n return;\n#endif\n\n LOG(ERROR) << \"The GPU process hung. Restarting after \"\n << timeout_ << \" seconds.\";\n\n volatile int* null_pointer = NULL;\n *null_pointer = timeout;\n\n crashed = true;\n}\n<commit_msg>Corrected GPU watchdog termination error message.<commit_after>\/\/ Copyright (c) 2010 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#if defined(OS_WIN)\n#include <windows.h>\n#endif\n\n#include \"chrome\/gpu\/gpu_watchdog_thread.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"build\/build_config.h\"\n\nnamespace {\nconst int64 kCheckPeriod = 2000;\n\nvoid DoNothing() {\n}\n}\n\nGpuWatchdogThread::GpuWatchdogThread(int timeout)\n : base::Thread(\"Watchdog\"),\n watched_message_loop_(MessageLoop::current()),\n timeout_(timeout),\n armed_(false),\n#if defined(OS_WIN)\n watched_thread_handle_(0),\n arm_time_(0),\n#endif\n ALLOW_THIS_IN_INITIALIZER_LIST(task_observer_(this)) {\n DCHECK(timeout >= 0);\n\n#if defined(OS_WIN)\n \/\/ GetCurrentThread returns a pseudo-handle that cannot be used by one thread\n \/\/ to identify another. DuplicateHandle creates a \"real\" handle that can be\n \/\/ used for this purpose.\n BOOL result = DuplicateHandle(GetCurrentProcess(),\n GetCurrentThread(),\n GetCurrentProcess(),\n &watched_thread_handle_,\n THREAD_QUERY_INFORMATION,\n FALSE,\n 0);\n DCHECK(result);\n#endif\n\n watched_message_loop_->AddTaskObserver(&task_observer_);\n}\n\nGpuWatchdogThread::~GpuWatchdogThread() {\n \/\/ Verify that the thread was explicitly stopped. If the thread is stopped\n \/\/ implicitly by the destructor, CleanUp() will not be called.\n DCHECK(!method_factory_.get());\n\n#if defined(OS_WIN)\n CloseHandle(watched_thread_handle_);\n#endif\n\n watched_message_loop_->RemoveTaskObserver(&task_observer_);\n}\n\nvoid GpuWatchdogThread::PostAcknowledge() {\n \/\/ Called on the monitored thread. Responds with OnAcknowledge. Cannot use\n \/\/ the method factory. Rely on reference counting instead.\n message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(this, &GpuWatchdogThread::OnAcknowledge));\n}\n\nvoid GpuWatchdogThread::Init() {\n \/\/ The method factory must be created on the watchdog thread.\n method_factory_.reset(new MethodFactory(this));\n\n \/\/ Schedule the first check.\n OnCheck();\n}\n\nvoid GpuWatchdogThread::CleanUp() {\n \/\/ The method factory must be destroyed on the watchdog thread.\n method_factory_->RevokeAll();\n method_factory_.reset();\n}\n\nGpuWatchdogThread::GpuWatchdogTaskObserver::GpuWatchdogTaskObserver(\n GpuWatchdogThread* watchdog)\n : watchdog_(watchdog) {\n}\n\nGpuWatchdogThread::GpuWatchdogTaskObserver::~GpuWatchdogTaskObserver() {\n}\n\nvoid GpuWatchdogThread::GpuWatchdogTaskObserver::WillProcessTask(\n const Task* task)\n{\n CheckArmed();\n}\n\nvoid GpuWatchdogThread::GpuWatchdogTaskObserver::DidProcessTask(\n const Task* task)\n{\n CheckArmed();\n}\n\nvoid GpuWatchdogThread::GpuWatchdogTaskObserver::CheckArmed()\n{\n \/\/ Acknowledge the watchdog if it has armed itself. The watchdog will not\n \/\/ change its armed state until it is acknowledged.\n if (watchdog_->armed()) {\n watchdog_->PostAcknowledge();\n }\n}\n\nvoid GpuWatchdogThread::OnAcknowledge() {\n \/\/ The check has already been acknowledged and another has already been\n \/\/ scheduled by a previous call to OnAcknowledge. It is normal for a\n \/\/ watched thread to see armed_ being true multiple times before\n \/\/ the OnAcknowledge task is run on the watchdog thread.\n if (!armed_)\n return;\n\n \/\/ Revoke any pending OnExit.\n method_factory_->RevokeAll();\n armed_ = false;\n\n \/\/ The monitored thread has responded. Post a task to check it again.\n message_loop()->PostDelayedTask(\n FROM_HERE,\n method_factory_->NewRunnableMethod(&GpuWatchdogThread::OnCheck),\n kCheckPeriod);\n}\n\n#if defined(OS_WIN)\nint64 GpuWatchdogThread::GetWatchedThreadTime() {\n FILETIME creation_time;\n FILETIME exit_time;\n FILETIME user_time;\n FILETIME kernel_time;\n BOOL result = GetThreadTimes(watched_thread_handle_,\n &creation_time,\n &exit_time,\n &kernel_time,\n &user_time);\n DCHECK(result);\n\n ULARGE_INTEGER user_time64;\n user_time64.HighPart = user_time.dwHighDateTime;\n user_time64.LowPart = user_time.dwLowDateTime;\n\n ULARGE_INTEGER kernel_time64;\n kernel_time64.HighPart = kernel_time.dwHighDateTime;\n kernel_time64.LowPart = kernel_time.dwLowDateTime;\n\n \/\/ Time is reported in units of 100 nanoseconds. Kernel and user time are\n \/\/ summed to deal with to kinds of hangs. One is where the GPU process is\n \/\/ stuck in user level, never calling into the kernel and kernel time is\n \/\/ not increasing. The other is where either the kernel hangs and never\n \/\/ returns to user level or where user level code\n \/\/ calls into kernel level repeatedly, giving up its quanta before it is\n \/\/ tracked, for example a loop that repeatedly Sleeps.\n return static_cast<int64>(\n (user_time64.QuadPart + kernel_time64.QuadPart) \/ 10000);\n}\n#endif\n\nvoid GpuWatchdogThread::OnCheck() {\n if (armed_)\n return;\n\n \/\/ Must set armed before posting the task. This task might be the only task\n \/\/ that will activate the TaskObserver on the watched thread and it must not\n \/\/ miss the false -> true transition.\n armed_ = true;\n\n#if defined(OS_WIN)\n arm_time_ = GetWatchedThreadTime();\n#endif\n\n \/\/ Post a task to the monitored thread that does nothing but wake up the\n \/\/ TaskObserver. Any other tasks that are pending on the watched thread will\n \/\/ also wake up the observer. This simply ensures there is at least one.\n watched_message_loop_->PostTask(\n FROM_HERE,\n NewRunnableFunction(DoNothing));\n\n \/\/ Post a task to the watchdog thread to exit if the monitored thread does\n \/\/ not respond in time.\n message_loop()->PostDelayedTask(\n FROM_HERE,\n method_factory_->NewRunnableMethod(&GpuWatchdogThread::OnExit),\n timeout_);\n}\n\n\/\/ Use the --disable-gpu-watchdog command line switch to disable this.\nvoid GpuWatchdogThread::OnExit() {\n#if defined(OS_WIN)\n \/\/ Defer termination until a certain amount of user time has elapsed.\n int64 time_since_arm = GetWatchedThreadTime() - arm_time_;\n if (time_since_arm < timeout_) {\n message_loop()->PostDelayedTask(\n FROM_HERE,\n method_factory_->NewRunnableMethod(&GpuWatchdogThread::OnExit),\n timeout_ - time_since_arm);\n return;\n }\n#endif\n\n \/\/ Make sure the timeout period is on the stack before crashing.\n volatile int timeout = timeout_;\n\n \/\/ For minimal developer annoyance, don't keep crashing.\n static bool crashed = false;\n if (crashed)\n return;\n\n#if defined(OS_WIN)\n if (IsDebuggerPresent())\n return;\n#endif\n\n LOG(ERROR) << \"The GPU process hung. Terminating after \"\n << timeout_ << \" ms.\";\n\n volatile int* null_pointer = NULL;\n *null_pointer = timeout;\n\n crashed = true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ MaxDelaySensor.cc\n\n#include \"lib.h\"\n#include \"MaxDelaySensor.h\"\n#include \"DelaySensor.h\"\n#include \"CommandOutput.h\"\n#include \"StateSensor.h\"\n\nusing namespace std;\n\nMaxDelaySensor::MaxDelaySensor(DelaySensor * newDelay, StateSensor * newState,\n MinDelaySensor *newminDelay)\n : maximum(0, 0.01)\n , delay(newDelay)\n , state(newState)\n , mindelay(newminDelay)\n{\n}\n\nvoid MaxDelaySensor::localSend(PacketInfo *)\n{\n}\n\nvoid MaxDelaySensor::localAck(PacketInfo * packet)\n{\n int current = delay->getLastDelay();\n \/*\n * We assume that the minimum delay is transmission delay plus the\n * propagation delay. Thus, any additional time is from queueing.\n * Thus, queueingDelay = maxDelay - minDelay\n * BUT - the latency we feed to dummynet is the whole time spend in the\n * dummynet queue, so we have to include the 'forward' part of the min delay\n * in our calculation.\n *\/\n int minimumDelay = mindelay->getMinDelay();\n int queueingDelay = current - (minimumDelay\/2);\n logWrite(SENSOR, \"current=%d,min=%d,queueing=%d,saturated=%d\", current,\n minimumDelay, queueingDelay, state->isSaturated());\n if (queueingDelay < 0) {\n logWrite(ERROR,\"Queueing delay is less than zero!\");\n }\n if (queueingDelay > maximum && current != 0) && state->isSaturated())\n {\n ostringstream buffer;\n buffer << \"MAXINQ=\" << queueingDelay;\n maximum.reset(queueingDelay);\n global::output->eventMessage(buffer.str(), packet->elab);\n }\n else\n {\n maximum.decay();\n }\n}\n<commit_msg>Fix a syntax error. I don't know how I let that one slip in!<commit_after>\/\/ MaxDelaySensor.cc\n\n#include \"lib.h\"\n#include \"MaxDelaySensor.h\"\n#include \"DelaySensor.h\"\n#include \"CommandOutput.h\"\n#include \"StateSensor.h\"\n\nusing namespace std;\n\nMaxDelaySensor::MaxDelaySensor(DelaySensor * newDelay, StateSensor * newState,\n MinDelaySensor *newminDelay)\n : maximum(0, 0.01)\n , delay(newDelay)\n , state(newState)\n , mindelay(newminDelay)\n{\n}\n\nvoid MaxDelaySensor::localSend(PacketInfo *)\n{\n}\n\nvoid MaxDelaySensor::localAck(PacketInfo * packet)\n{\n int current = delay->getLastDelay();\n \/*\n * We assume that the minimum delay is transmission delay plus the\n * propagation delay. Thus, any additional time is from queueing.\n * Thus, queueingDelay = maxDelay - minDelay\n * BUT - the latency we feed to dummynet is the whole time spend in the\n * dummynet queue, so we have to include the 'forward' part of the min delay\n * in our calculation.\n *\/\n int minimumDelay = mindelay->getMinDelay();\n int queueingDelay = current - (minimumDelay\/2);\n logWrite(SENSOR, \"current=%d,min=%d,queueing=%d,saturated=%d\", current,\n minimumDelay, queueingDelay, state->isSaturated());\n if (queueingDelay < 0) {\n logWrite(ERROR,\"Queueing delay is less than zero!\");\n }\n if ((queueingDelay > maximum) && (current != 0) && state->isSaturated())\n {\n ostringstream buffer;\n buffer << \"MAXINQ=\" << queueingDelay;\n maximum.reset(queueingDelay);\n global::output->eventMessage(buffer.str(), packet->elab);\n }\n else\n {\n maximum.decay();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2020 The XLS Authors\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 \"xls\/ir\/function.h\"\n\n#include \"absl\/status\/statusor.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/str_format.h\"\n#include \"absl\/strings\/str_join.h\"\n#include \"xls\/common\/logging\/logging.h\"\n#include \"xls\/common\/status\/ret_check.h\"\n#include \"xls\/common\/status\/status_macros.h\"\n#include \"xls\/ir\/node_iterator.h\"\n#include \"xls\/ir\/package.h\"\n\nnamespace xls {\n\nFunctionType* Function::GetType() {\n std::vector<Type*> arg_types;\n for (Param* param : params()) {\n arg_types.push_back(param->GetType());\n }\n XLS_CHECK(return_value() != nullptr);\n return package_->GetFunctionType(arg_types, return_value()->GetType());\n}\n\nstd::string Function::DumpIr() const {\n std::string res = \"fn \" + name() + \"(\";\n std::vector<std::string> param_strings;\n for (Param* param : params_) {\n param_strings.push_back(\n absl::StrFormat(\"%s: %s\", param->name(), param->GetType()->ToString()));\n }\n absl::StrAppend(&res, absl::StrJoin(param_strings, \", \"));\n absl::StrAppend(&res, \") -> \");\n\n if (return_value() != nullptr) {\n absl::StrAppend(&res, return_value()->GetType()->ToString());\n }\n absl::StrAppend(&res, \" {\\n\");\n\n for (Node* node : TopoSort(const_cast<Function*>(this))) {\n if (node->op() == Op::kParam && node == return_value()) {\n absl::StrAppendFormat(&res, \" ret %s: %s = param(name=%s)\\n\",\n node->GetName(), node->GetType()->ToString(),\n node->As<Param>()->name());\n continue;\n }\n if (node->op() == Op::kParam) {\n continue; \/\/ Already accounted for in the signature.\n }\n absl::StrAppend(&res, \" \", node == return_value() ? \"ret \" : \"\",\n node->ToString(), \"\\n\");\n }\n\n absl::StrAppend(&res, \"}\\n\");\n return res;\n}\n\nabsl::StatusOr<Function*> Function::Clone(\n absl::string_view new_name, Package* target_package,\n const absl::flat_hash_map<const Function*, Function*>& call_remapping)\n const {\n absl::flat_hash_map<Node*, Node*> original_to_clone;\n if (target_package == nullptr) {\n target_package = package();\n }\n Function* cloned_function = target_package->AddFunction(\n std::make_unique<Function>(new_name, target_package));\n for (Node* node : TopoSort(const_cast<Function*>(this))) {\n std::vector<Node*> cloned_operands;\n for (Node* operand : node->operands()) {\n cloned_operands.push_back(original_to_clone.at(operand));\n }\n\n switch (node->op()) {\n \/\/ Remap CountedFor body.\n case Op::kCountedFor: {\n CountedFor* src = node->As<CountedFor>();\n Function* body = call_remapping.contains(src->body())\n ? call_remapping.at(src->body())\n : src->body();\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[node],\n cloned_function->MakeNodeWithName<CountedFor>(\n src->loc(), cloned_operands[0],\n absl::Span<Node*>(cloned_operands).subspan(1),\n src->trip_count(), src->stride(), body, src->GetName()));\n break;\n }\n \/\/ Remap Map to_apply.\n case Op::kMap: {\n Map* src = node->As<Map>();\n Function* to_apply = call_remapping.contains(src->to_apply())\n ? call_remapping.at(src->to_apply())\n : src->to_apply();\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[node],\n cloned_function->MakeNodeWithName<Map>(\n src->loc(), cloned_operands[0], to_apply, src->GetName()));\n break;\n }\n \/\/ Remap Invoke to_apply.\n case Op::kInvoke: {\n Invoke* src = node->As<Invoke>();\n Function* to_apply = call_remapping.contains(src->to_apply())\n ? call_remapping.at(src->to_apply())\n : src->to_apply();\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[node],\n cloned_function->MakeNodeWithName<Invoke>(\n src->loc(), cloned_operands, to_apply, src->GetName()));\n break;\n }\n \/\/ Default clone.\n default: {\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[node],\n node->CloneInNewFunction(cloned_operands, cloned_function));\n break;\n }\n }\n }\n XLS_RETURN_IF_ERROR(\n cloned_function->set_return_value(original_to_clone.at(return_value())));\n return cloned_function;\n}\n\n\/\/ Helper function for IsDefinitelyEqualTo. Recursively compares 'node' and\n\/\/ 'other_node' and their operands using Node::IsDefinitelyEqualTo.\n\/\/ 'matched_pairs' is used to memoize the result of the comparison.\nstatic bool IsEqualRecurse(\n const Node* node, const Node* other_node,\n absl::flat_hash_map<const Node*, const Node*>* matched_pairs) {\n auto it = matched_pairs->find(node);\n if (it != matched_pairs->end()) {\n return it->second == other_node;\n }\n\n if (!node->IsDefinitelyEqualTo(other_node)) {\n XLS_VLOG(2) << absl::StrFormat(\"Function %s != %s: node %s != %s\",\n node->function_base()->name(),\n other_node->function_base()->name(),\n node->GetName(), other_node->GetName());\n return false;\n }\n\n for (int64_t i = 0; i < node->operand_count(); ++i) {\n if (!IsEqualRecurse(node->operand(i), other_node->operand(i),\n matched_pairs)) {\n return false;\n }\n }\n (*matched_pairs)[node] = other_node;\n return true;\n}\n\nbool Function::IsDefinitelyEqualTo(const Function* other) const {\n if (this == other) {\n XLS_VLOG(2) << absl::StrFormat(\"Function %s == %s: same pointer\", name(),\n other->name());\n return true;\n }\n\n \/\/ Must have the types of parameters in the same order.\n if (params().size() != other->params().size()) {\n XLS_VLOG(2) << absl::StrFormat(\n \"Function %s != %s: different number of parameters (%d vs %d)\", name(),\n other->name(), params().size(), other->params().size());\n return false;\n }\n\n absl::flat_hash_map<const Node*, const Node*> matched_pairs;\n for (int64_t i = 0; i < params().size(); ++i) {\n \/\/ All we care about is the type (not the name) of the parameter so don't\n \/\/ use Param::IsDefinitelyEqualTo.\n if (!param(i)->GetType()->IsEqualTo(other->param(i)->GetType())) {\n XLS_VLOG(2) << absl::StrFormat(\n \"Function %s != %s: type of parameter %d not the same (%s vs %s)\",\n name(), other->name(), i, param(i)->GetType()->ToString(),\n other->param(i)->GetType()->ToString());\n return false;\n }\n matched_pairs[param(i)] = other->param(i);\n }\n\n bool result =\n IsEqualRecurse(return_value(), other->return_value(), &matched_pairs);\n XLS_VLOG_IF(2, result) << absl::StrFormat(\"Function %s is equal to %s\",\n name(), other->name());\n return result;\n}\n\n} \/\/ namespace xls\n<commit_msg>Ensure parameters are cloned in-order in Function::Clone<commit_after>\/\/ Copyright 2020 The XLS Authors\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 \"xls\/ir\/function.h\"\n\n#include \"absl\/status\/statusor.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/str_format.h\"\n#include \"absl\/strings\/str_join.h\"\n#include \"xls\/common\/logging\/logging.h\"\n#include \"xls\/common\/status\/ret_check.h\"\n#include \"xls\/common\/status\/status_macros.h\"\n#include \"xls\/ir\/node_iterator.h\"\n#include \"xls\/ir\/package.h\"\n\nnamespace xls {\n\nFunctionType* Function::GetType() {\n std::vector<Type*> arg_types;\n for (Param* param : params()) {\n arg_types.push_back(param->GetType());\n }\n XLS_CHECK(return_value() != nullptr);\n return package_->GetFunctionType(arg_types, return_value()->GetType());\n}\n\nstd::string Function::DumpIr() const {\n std::string res = \"fn \" + name() + \"(\";\n std::vector<std::string> param_strings;\n for (Param* param : params_) {\n param_strings.push_back(\n absl::StrFormat(\"%s: %s\", param->name(), param->GetType()->ToString()));\n }\n absl::StrAppend(&res, absl::StrJoin(param_strings, \", \"));\n absl::StrAppend(&res, \") -> \");\n\n if (return_value() != nullptr) {\n absl::StrAppend(&res, return_value()->GetType()->ToString());\n }\n absl::StrAppend(&res, \" {\\n\");\n\n for (Node* node : TopoSort(const_cast<Function*>(this))) {\n if (node->op() == Op::kParam && node == return_value()) {\n absl::StrAppendFormat(&res, \" ret %s: %s = param(name=%s)\\n\",\n node->GetName(), node->GetType()->ToString(),\n node->As<Param>()->name());\n continue;\n }\n if (node->op() == Op::kParam) {\n continue; \/\/ Already accounted for in the signature.\n }\n absl::StrAppend(&res, \" \", node == return_value() ? \"ret \" : \"\",\n node->ToString(), \"\\n\");\n }\n\n absl::StrAppend(&res, \"}\\n\");\n return res;\n}\n\nabsl::StatusOr<Function*> Function::Clone(\n absl::string_view new_name, Package* target_package,\n const absl::flat_hash_map<const Function*, Function*>& call_remapping)\n const {\n absl::flat_hash_map<Node*, Node*> original_to_clone;\n if (target_package == nullptr) {\n target_package = package();\n }\n Function* cloned_function = target_package->AddFunction(\n std::make_unique<Function>(new_name, target_package));\n \/\/ Clone parameters over first.\n for (Param* param : (const_cast<Function*>(this))->params()) {\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[param],\n param->CloneInNewFunction({}, cloned_function));\n }\n for (Node* node : TopoSort(const_cast<Function*>(this))) {\n if (node->Is<Param>()) { \/\/ Params were already copied.\n continue;\n }\n std::vector<Node*> cloned_operands;\n for (Node* operand : node->operands()) {\n cloned_operands.push_back(original_to_clone.at(operand));\n }\n\n switch (node->op()) {\n \/\/ Remap CountedFor body.\n case Op::kCountedFor: {\n CountedFor* src = node->As<CountedFor>();\n Function* body = call_remapping.contains(src->body())\n ? call_remapping.at(src->body())\n : src->body();\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[node],\n cloned_function->MakeNodeWithName<CountedFor>(\n src->loc(), cloned_operands[0],\n absl::Span<Node*>(cloned_operands).subspan(1),\n src->trip_count(), src->stride(), body, src->GetName()));\n break;\n }\n \/\/ Remap Map to_apply.\n case Op::kMap: {\n Map* src = node->As<Map>();\n Function* to_apply = call_remapping.contains(src->to_apply())\n ? call_remapping.at(src->to_apply())\n : src->to_apply();\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[node],\n cloned_function->MakeNodeWithName<Map>(\n src->loc(), cloned_operands[0], to_apply, src->GetName()));\n break;\n }\n \/\/ Remap Invoke to_apply.\n case Op::kInvoke: {\n Invoke* src = node->As<Invoke>();\n Function* to_apply = call_remapping.contains(src->to_apply())\n ? call_remapping.at(src->to_apply())\n : src->to_apply();\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[node],\n cloned_function->MakeNodeWithName<Invoke>(\n src->loc(), cloned_operands, to_apply, src->GetName()));\n break;\n }\n \/\/ Default clone.\n default: {\n XLS_ASSIGN_OR_RETURN(\n original_to_clone[node],\n node->CloneInNewFunction(cloned_operands, cloned_function));\n break;\n }\n }\n }\n XLS_RETURN_IF_ERROR(\n cloned_function->set_return_value(original_to_clone.at(return_value())));\n return cloned_function;\n}\n\n\/\/ Helper function for IsDefinitelyEqualTo. Recursively compares 'node' and\n\/\/ 'other_node' and their operands using Node::IsDefinitelyEqualTo.\n\/\/ 'matched_pairs' is used to memoize the result of the comparison.\nstatic bool IsEqualRecurse(\n const Node* node, const Node* other_node,\n absl::flat_hash_map<const Node*, const Node*>* matched_pairs) {\n auto it = matched_pairs->find(node);\n if (it != matched_pairs->end()) {\n return it->second == other_node;\n }\n\n if (!node->IsDefinitelyEqualTo(other_node)) {\n XLS_VLOG(2) << absl::StrFormat(\"Function %s != %s: node %s != %s\",\n node->function_base()->name(),\n other_node->function_base()->name(),\n node->GetName(), other_node->GetName());\n return false;\n }\n\n for (int64_t i = 0; i < node->operand_count(); ++i) {\n if (!IsEqualRecurse(node->operand(i), other_node->operand(i),\n matched_pairs)) {\n return false;\n }\n }\n (*matched_pairs)[node] = other_node;\n return true;\n}\n\nbool Function::IsDefinitelyEqualTo(const Function* other) const {\n if (this == other) {\n XLS_VLOG(2) << absl::StrFormat(\"Function %s == %s: same pointer\", name(),\n other->name());\n return true;\n }\n\n \/\/ Must have the types of parameters in the same order.\n if (params().size() != other->params().size()) {\n XLS_VLOG(2) << absl::StrFormat(\n \"Function %s != %s: different number of parameters (%d vs %d)\", name(),\n other->name(), params().size(), other->params().size());\n return false;\n }\n\n absl::flat_hash_map<const Node*, const Node*> matched_pairs;\n for (int64_t i = 0; i < params().size(); ++i) {\n \/\/ All we care about is the type (not the name) of the parameter so don't\n \/\/ use Param::IsDefinitelyEqualTo.\n if (!param(i)->GetType()->IsEqualTo(other->param(i)->GetType())) {\n XLS_VLOG(2) << absl::StrFormat(\n \"Function %s != %s: type of parameter %d not the same (%s vs %s)\",\n name(), other->name(), i, param(i)->GetType()->ToString(),\n other->param(i)->GetType()->ToString());\n return false;\n }\n matched_pairs[param(i)] = other->param(i);\n }\n\n bool result =\n IsEqualRecurse(return_value(), other->return_value(), &matched_pairs);\n XLS_VLOG_IF(2, result) << absl::StrFormat(\"Function %s is equal to %s\",\n name(), other->name());\n return result;\n}\n\n} \/\/ namespace xls\n<|endoftext|>"} {"text":"<commit_before>\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.\n\/\/ Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ @Authors\n\/\/ Fangfang Bai, fangfang@multicorewareinc.com\n\/\/ Jin Ma, jin@multicorewareinc.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors as is and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n#include \"perf_precomp.hpp\"\n\nusing namespace perf;\nusing std::tr1::tuple;\nusing std::tr1::get;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ WarpAffine \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef Size_MatType WarpAffineFixture;\n\nPERF_TEST_P(WarpAffineFixture, WarpAffine,\n ::testing::Combine(OCL_TYPICAL_MAT_SIZES,\n OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))\n{\n static const double coeffs[2][3] =\n {\n { cos(CV_PI \/ 6), -sin(CV_PI \/ 6), 100.0 },\n { sin(CV_PI \/ 6), cos(CV_PI \/ 6), -100.0 }\n };\n Mat M(2, 3, CV_64F, (void *)coeffs);\n const int interpolation = INTER_NEAREST;\n\n const Size_MatType_t params = GetParam();\n const Size srcSize = get<0>(params);\n const int type = get<1>(params);\n\n Mat src(srcSize, type), dst(srcSize, type);\n declare.in(src, WARMUP_RNG).out(dst);\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclSrc(src), oclDst(srcSize, type);\n\n OCL_TEST_CYCLE() cv::ocl::warpAffine(oclSrc, oclDst, M, srcSize, interpolation);\n\n oclDst.download(dst);\n\n SANITY_CHECK(dst);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() cv::warpAffine(src, dst, M, srcSize, interpolation);\n\n SANITY_CHECK(dst);\n }\n else\n OCL_PERF_ELSE\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ WarpPerspective \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef Size_MatType WarpPerspectiveFixture;\n\nPERF_TEST_P(WarpPerspectiveFixture, WarpPerspective,\n ::testing::Combine(OCL_TYPICAL_MAT_SIZES,\n OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))\n{\n static const double coeffs[3][3] =\n {\n {cos(CV_PI \/ 6), -sin(CV_PI \/ 6), 100.0},\n {sin(CV_PI \/ 6), cos(CV_PI \/ 6), -100.0},\n {0.0, 0.0, 1.0}\n };\n Mat M(3, 3, CV_64F, (void *)coeffs);\n const int interpolation = INTER_LINEAR;\n\n const Size_MatType_t params = GetParam();\n const Size srcSize = get<0>(params);\n const int type = get<1>(params);\n\n Mat src(srcSize, type), dst(srcSize, type);\n declare.in(src, WARMUP_RNG).out(dst)\n .time(srcSize == OCL_SIZE_4000 ? 18 : srcSize == OCL_SIZE_2000 ? 5 : 2);\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclSrc(src), oclDst(srcSize, type);\n\n OCL_TEST_CYCLE() cv::ocl::warpPerspective(oclSrc, oclDst, M, srcSize, interpolation);\n\n oclDst.download(dst);\n\n SANITY_CHECK(dst);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() cv::warpPerspective(src, dst, M, srcSize, interpolation);\n\n SANITY_CHECK(dst);\n }\n else\n OCL_PERF_ELSE\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ resize \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCV_ENUM(resizeInterType, INTER_NEAREST, INTER_LINEAR)\n\ntypedef tuple<Size, MatType, resizeInterType, double> resizeParams;\ntypedef TestBaseWithParam<resizeParams> resizeFixture;\n\nPERF_TEST_P(resizeFixture, resize,\n ::testing::Combine(OCL_TYPICAL_MAT_SIZES,\n OCL_PERF_ENUM(CV_8UC1, CV_8UC4),\n resizeInterType::all(),\n ::testing::Values(0.5, 2.0)))\n{\n const resizeParams params = GetParam();\n const Size srcSize = get<0>(params);\n const int type = get<1>(params), interType = get<2>(params);\n double scale = get<3>(params);\n\n Mat src(srcSize, type), dst;\n const Size dstSize(cvRound(srcSize.width * scale), cvRound(srcSize.height * scale));\n dst.create(dstSize, type);\n declare.in(src, WARMUP_RNG).out(dst);\n if (interType == INTER_LINEAR && type == CV_8UC4 && OCL_SIZE_4000 == srcSize)\n declare.time(11);\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclSrc(src), oclDst(dstSize, type);\n\n OCL_TEST_CYCLE() cv::ocl::resize(oclSrc, oclDst, Size(), scale, scale, interType);\n\n oclDst.download(dst);\n\n SANITY_CHECK(dst, 1 + DBL_EPSILON);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() cv::resize(src, dst, Size(), scale, scale, interType);\n\n SANITY_CHECK(dst, 1 + DBL_EPSILON);\n }\n else\n OCL_PERF_ELSE\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ remap\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCV_ENUM(RemapInterType, INTER_NEAREST, INTER_LINEAR)\n\ntypedef tuple<Size, MatType, RemapInterType> remapParams;\ntypedef TestBaseWithParam<remapParams> remapFixture;\n\nPERF_TEST_P(remapFixture, remap,\n ::testing::Combine(OCL_TYPICAL_MAT_SIZES,\n OCL_PERF_ENUM(CV_8UC1, CV_8UC4),\n RemapInterType::all()))\n{\n const remapParams params = GetParam();\n const Size srcSize = get<0>(params);\n const int type = get<1>(params), interpolation = get<2>(params);\n\n Mat src(srcSize, type), dst(srcSize, type);\n declare.in(src, WARMUP_RNG).out(dst);\n\n if (srcSize == OCL_SIZE_4000 && interpolation == INTER_LINEAR)\n declare.time(9);\n\n Mat xmap, ymap;\n xmap.create(srcSize, CV_32FC1);\n ymap.create(srcSize, CV_32FC1);\n\n for (int i = 0; i < srcSize.height; ++i)\n {\n float * const xmap_row = xmap.ptr<float>(i);\n float * const ymap_row = ymap.ptr<float>(i);\n\n for (int j = 0; j < srcSize.width; ++j)\n {\n xmap_row[j] = (j - srcSize.width * 0.5f) * 0.75f + srcSize.width * 0.5f;\n ymap_row[j] = (i - srcSize.height * 0.5f) * 0.75f + srcSize.height * 0.5f;\n }\n }\n\n const int borderMode = BORDER_CONSTANT;\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclSrc(src), oclDst(srcSize, type);\n ocl::oclMat oclXMap(xmap), oclYMap(ymap);\n\n OCL_TEST_CYCLE() cv::ocl::remap(oclSrc, oclDst, oclXMap, oclYMap, interpolation, borderMode);\n\n oclDst.download(dst);\n\n SANITY_CHECK(dst, 1 + DBL_EPSILON);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() cv::remap(src, dst, xmap, ymap, interpolation, borderMode);\n\n SANITY_CHECK(dst, 1 + DBL_EPSILON);\n }\n else\n OCL_PERF_ELSE\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ buildWarpPerspectiveMaps \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void buildWarpPerspectiveMaps(const Mat &M, bool inverse, Size dsize, Mat &xmap, Mat &ymap)\n{\n CV_Assert(M.rows == 3 && M.cols == 3);\n CV_Assert(dsize.area() > 0);\n\n xmap.create(dsize, CV_32FC1);\n ymap.create(dsize, CV_32FC1);\n\n float coeffs[3 * 3];\n Mat coeffsMat(3, 3, CV_32F, (void *)coeffs);\n\n if (inverse)\n M.convertTo(coeffsMat, coeffsMat.type());\n else\n {\n cv::Mat iM;\n invert(M, iM);\n iM.convertTo(coeffsMat, coeffsMat.type());\n }\n\n for (int y = 0; y < dsize.height; ++y)\n {\n float * const xmap_ptr = xmap.ptr<float>(y);\n float * const ymap_ptr = ymap.ptr<float>(y);\n\n for (int x = 0; x < dsize.width; ++x)\n {\n float coeff = 1.0f \/ (x * coeffs[6] + y * coeffs[7] + coeffs[8]);\n xmap_ptr[x] = (x * coeffs[0] + y * coeffs[1] + coeffs[2]) * coeff;\n ymap_ptr[x] = (x * coeffs[3] + y * coeffs[4] + coeffs[5]) * coeff;\n }\n }\n}\n\ntypedef TestBaseWithParam<Size> buildWarpPerspectiveMapsFixture;\n\nPERF_TEST_P(buildWarpPerspectiveMapsFixture, Inverse, OCL_TYPICAL_MAT_SIZES)\n{\n static const double coeffs[3][3] =\n {\n {cos(CV_PI \/ 6), -sin(CV_PI \/ 6), 100.0},\n {sin(CV_PI \/ 6), cos(CV_PI \/ 6), -100.0},\n {0.0, 0.0, 1.0}\n };\n Mat M(3, 3, CV_64F, (void *)coeffs);\n const Size dsize = GetParam();\n\n Mat xmap(dsize, CV_32FC1), ymap(dsize, CV_32FC1);\n declare.in(M).out(xmap, ymap);\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclXMap(dsize, CV_32FC1), oclYMap(dsize, CV_32FC1);\n\n OCL_TEST_CYCLE() cv::ocl::buildWarpPerspectiveMaps(M, true, dsize, oclXMap, oclYMap);\n\n oclXMap.download(xmap);\n oclYMap.download(ymap);\n\n SANITY_CHECK(xmap);\n SANITY_CHECK(ymap);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() buildWarpPerspectiveMaps(M, true, dsize, xmap, ymap);\n\n SANITY_CHECK(xmap);\n SANITY_CHECK(ymap);\n }\n else\n OCL_PERF_ELSE\n}\n<commit_msg>added eps to ocl::buildWarpPerspectiveMaps perf test<commit_after>\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.\n\/\/ Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ @Authors\n\/\/ Fangfang Bai, fangfang@multicorewareinc.com\n\/\/ Jin Ma, jin@multicorewareinc.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors as is and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n#include \"perf_precomp.hpp\"\n\nusing namespace perf;\nusing std::tr1::tuple;\nusing std::tr1::get;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ WarpAffine \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef Size_MatType WarpAffineFixture;\n\nPERF_TEST_P(WarpAffineFixture, WarpAffine,\n ::testing::Combine(OCL_TYPICAL_MAT_SIZES,\n OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))\n{\n static const double coeffs[2][3] =\n {\n { cos(CV_PI \/ 6), -sin(CV_PI \/ 6), 100.0 },\n { sin(CV_PI \/ 6), cos(CV_PI \/ 6), -100.0 }\n };\n Mat M(2, 3, CV_64F, (void *)coeffs);\n const int interpolation = INTER_NEAREST;\n\n const Size_MatType_t params = GetParam();\n const Size srcSize = get<0>(params);\n const int type = get<1>(params);\n\n Mat src(srcSize, type), dst(srcSize, type);\n declare.in(src, WARMUP_RNG).out(dst);\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclSrc(src), oclDst(srcSize, type);\n\n OCL_TEST_CYCLE() cv::ocl::warpAffine(oclSrc, oclDst, M, srcSize, interpolation);\n\n oclDst.download(dst);\n\n SANITY_CHECK(dst);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() cv::warpAffine(src, dst, M, srcSize, interpolation);\n\n SANITY_CHECK(dst);\n }\n else\n OCL_PERF_ELSE\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ WarpPerspective \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef Size_MatType WarpPerspectiveFixture;\n\nPERF_TEST_P(WarpPerspectiveFixture, WarpPerspective,\n ::testing::Combine(OCL_TYPICAL_MAT_SIZES,\n OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))\n{\n static const double coeffs[3][3] =\n {\n {cos(CV_PI \/ 6), -sin(CV_PI \/ 6), 100.0},\n {sin(CV_PI \/ 6), cos(CV_PI \/ 6), -100.0},\n {0.0, 0.0, 1.0}\n };\n Mat M(3, 3, CV_64F, (void *)coeffs);\n const int interpolation = INTER_LINEAR;\n\n const Size_MatType_t params = GetParam();\n const Size srcSize = get<0>(params);\n const int type = get<1>(params);\n\n Mat src(srcSize, type), dst(srcSize, type);\n declare.in(src, WARMUP_RNG).out(dst)\n .time(srcSize == OCL_SIZE_4000 ? 18 : srcSize == OCL_SIZE_2000 ? 5 : 2);\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclSrc(src), oclDst(srcSize, type);\n\n OCL_TEST_CYCLE() cv::ocl::warpPerspective(oclSrc, oclDst, M, srcSize, interpolation);\n\n oclDst.download(dst);\n\n SANITY_CHECK(dst);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() cv::warpPerspective(src, dst, M, srcSize, interpolation);\n\n SANITY_CHECK(dst);\n }\n else\n OCL_PERF_ELSE\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ resize \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCV_ENUM(resizeInterType, INTER_NEAREST, INTER_LINEAR)\n\ntypedef tuple<Size, MatType, resizeInterType, double> resizeParams;\ntypedef TestBaseWithParam<resizeParams> resizeFixture;\n\nPERF_TEST_P(resizeFixture, resize,\n ::testing::Combine(OCL_TYPICAL_MAT_SIZES,\n OCL_PERF_ENUM(CV_8UC1, CV_8UC4),\n resizeInterType::all(),\n ::testing::Values(0.5, 2.0)))\n{\n const resizeParams params = GetParam();\n const Size srcSize = get<0>(params);\n const int type = get<1>(params), interType = get<2>(params);\n double scale = get<3>(params);\n\n Mat src(srcSize, type), dst;\n const Size dstSize(cvRound(srcSize.width * scale), cvRound(srcSize.height * scale));\n dst.create(dstSize, type);\n declare.in(src, WARMUP_RNG).out(dst);\n if (interType == INTER_LINEAR && type == CV_8UC4 && OCL_SIZE_4000 == srcSize)\n declare.time(11);\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclSrc(src), oclDst(dstSize, type);\n\n OCL_TEST_CYCLE() cv::ocl::resize(oclSrc, oclDst, Size(), scale, scale, interType);\n\n oclDst.download(dst);\n\n SANITY_CHECK(dst, 1 + DBL_EPSILON);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() cv::resize(src, dst, Size(), scale, scale, interType);\n\n SANITY_CHECK(dst, 1 + DBL_EPSILON);\n }\n else\n OCL_PERF_ELSE\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ remap\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCV_ENUM(RemapInterType, INTER_NEAREST, INTER_LINEAR)\n\ntypedef tuple<Size, MatType, RemapInterType> remapParams;\ntypedef TestBaseWithParam<remapParams> remapFixture;\n\nPERF_TEST_P(remapFixture, remap,\n ::testing::Combine(OCL_TYPICAL_MAT_SIZES,\n OCL_PERF_ENUM(CV_8UC1, CV_8UC4),\n RemapInterType::all()))\n{\n const remapParams params = GetParam();\n const Size srcSize = get<0>(params);\n const int type = get<1>(params), interpolation = get<2>(params);\n\n Mat src(srcSize, type), dst(srcSize, type);\n declare.in(src, WARMUP_RNG).out(dst);\n\n if (srcSize == OCL_SIZE_4000 && interpolation == INTER_LINEAR)\n declare.time(9);\n\n Mat xmap, ymap;\n xmap.create(srcSize, CV_32FC1);\n ymap.create(srcSize, CV_32FC1);\n\n for (int i = 0; i < srcSize.height; ++i)\n {\n float * const xmap_row = xmap.ptr<float>(i);\n float * const ymap_row = ymap.ptr<float>(i);\n\n for (int j = 0; j < srcSize.width; ++j)\n {\n xmap_row[j] = (j - srcSize.width * 0.5f) * 0.75f + srcSize.width * 0.5f;\n ymap_row[j] = (i - srcSize.height * 0.5f) * 0.75f + srcSize.height * 0.5f;\n }\n }\n\n const int borderMode = BORDER_CONSTANT;\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclSrc(src), oclDst(srcSize, type);\n ocl::oclMat oclXMap(xmap), oclYMap(ymap);\n\n OCL_TEST_CYCLE() cv::ocl::remap(oclSrc, oclDst, oclXMap, oclYMap, interpolation, borderMode);\n\n oclDst.download(dst);\n\n SANITY_CHECK(dst, 1 + DBL_EPSILON);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() cv::remap(src, dst, xmap, ymap, interpolation, borderMode);\n\n SANITY_CHECK(dst, 1 + DBL_EPSILON);\n }\n else\n OCL_PERF_ELSE\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ buildWarpPerspectiveMaps \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void buildWarpPerspectiveMaps(const Mat &M, bool inverse, Size dsize, Mat &xmap, Mat &ymap)\n{\n CV_Assert(M.rows == 3 && M.cols == 3);\n CV_Assert(dsize.area() > 0);\n\n xmap.create(dsize, CV_32FC1);\n ymap.create(dsize, CV_32FC1);\n\n float coeffs[3 * 3];\n Mat coeffsMat(3, 3, CV_32F, (void *)coeffs);\n\n if (inverse)\n M.convertTo(coeffsMat, coeffsMat.type());\n else\n {\n cv::Mat iM;\n invert(M, iM);\n iM.convertTo(coeffsMat, coeffsMat.type());\n }\n\n for (int y = 0; y < dsize.height; ++y)\n {\n float * const xmap_ptr = xmap.ptr<float>(y);\n float * const ymap_ptr = ymap.ptr<float>(y);\n\n for (int x = 0; x < dsize.width; ++x)\n {\n float coeff = 1.0f \/ (x * coeffs[6] + y * coeffs[7] + coeffs[8]);\n xmap_ptr[x] = (x * coeffs[0] + y * coeffs[1] + coeffs[2]) * coeff;\n ymap_ptr[x] = (x * coeffs[3] + y * coeffs[4] + coeffs[5]) * coeff;\n }\n }\n}\n\ntypedef TestBaseWithParam<Size> buildWarpPerspectiveMapsFixture;\n\nPERF_TEST_P(buildWarpPerspectiveMapsFixture, Inverse, OCL_TYPICAL_MAT_SIZES)\n{\n static const double coeffs[3][3] =\n {\n {cos(CV_PI \/ 6), -sin(CV_PI \/ 6), 100.0},\n {sin(CV_PI \/ 6), cos(CV_PI \/ 6), -100.0},\n {0.0, 0.0, 1.0}\n };\n Mat M(3, 3, CV_64F, (void *)coeffs);\n const Size dsize = GetParam();\n const double eps = 5e-4;\n\n Mat xmap(dsize, CV_32FC1), ymap(dsize, CV_32FC1);\n declare.in(M).out(xmap, ymap);\n\n if (RUN_OCL_IMPL)\n {\n ocl::oclMat oclXMap(dsize, CV_32FC1), oclYMap(dsize, CV_32FC1);\n\n OCL_TEST_CYCLE() cv::ocl::buildWarpPerspectiveMaps(M, true, dsize, oclXMap, oclYMap);\n\n oclXMap.download(xmap);\n oclYMap.download(ymap);\n\n SANITY_CHECK(xmap, eps);\n SANITY_CHECK(ymap, eps);\n }\n else if (RUN_PLAIN_IMPL)\n {\n TEST_CYCLE() buildWarpPerspectiveMaps(M, true, dsize, xmap, ymap);\n\n SANITY_CHECK(xmap, eps);\n SANITY_CHECK(ymap, eps);\n }\n else\n OCL_PERF_ELSE\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: c++; c-default-style: \"google\"; indent-tabs-mode: nil -*- *\/\n\/* -------------------------------------------------------------------------\nATS\n\nLicense: see $ATS_DIR\/COPYRIGHT\nAuthor: Ethan Coon\n\nDerived MPC for flow and energy. This couples using a block-diagonal coupler.\n------------------------------------------------------------------------- *\/\n\n#include \"wrm_richards_evaluator.hh\"\n#include \"mpc_frozen_prec_coupled_flow_energy.hh\"\n\nnamespace Amanzi {\n\n#define DEBUG_FLAG 0\n\nRegisteredPKFactory<MPCFrozenCoupledFlowEnergy> MPCFrozenCoupledFlowEnergy::reg_(\"frozen energy-flow preconditioner coupled\");\n\nbool MPCFrozenCoupledFlowEnergy::modify_predictor(double h, Teuchos::RCP<TreeVector> u) {\n Teuchos::RCP<CompositeVector> temp_guess = u->SubVector(\"energy\")->data();\n Epetra_MultiVector& guess_cells = *temp_guess->ViewComponent(\"cell\",false);\n Epetra_MultiVector& guess_faces = *temp_guess->ViewComponent(\"face\",false);\n\n Teuchos::RCP<const CompositeVector> temp = S_next_->GetFieldData(\"temperature\");\n const Epetra_MultiVector& temp_cells = *temp->ViewComponent(\"cell\",false);\n\n bool update_faces(false);\n\n#if DEBUG_FLAG\n std::cout << \"--- Modifying Guess: ---\" << std::cout;\n#endif\n\n int ncells = temp->size(\"cell\",false);\n std::vector<bool> changed(ncells, false);\n for (int c=0; c!=ncells; ++c) {\n if (temp_cells[0][c] >= 273.15 && guess_cells[0][c] < 273.15) {\n \/\/ freezing\n guess_cells[0][c] = 273.15 - 1.e-4;\n changed[c] = true;\n update_faces = true;\n } else if (temp_cells[0][c] <= 273.15 && guess_cells[0][c] > 273.15) {\n \/\/ thawing\n guess_cells[0][c] = 273.15 - 1.e-3;\n changed[c] = true;\n update_faces = true;\n } else if (273.15 > temp_cells[0][c] &&\n temp_cells[0][c] >= 273.1 &&\n (temp_cells[0][c] - guess_cells[0][c]) > 1.e-2) {\n \/\/ catch the 2nd step in freezing -- after the 2nd step the\n \/\/ extrapolation should be ok?\n guess_cells[0][c] = temp_cells[0][c];\n changed[c] = true;\n update_faces = true;\n }\n }\n\n \/\/ unclear... could do an AllReduce() on update_faces and not communicate if\n \/\/ not necessary, but AllReduces() suck... maybe more than extra Scatters?\n temp_guess->ScatterMasterToGhosted(\"cell\");\n if (update_faces) {\n AmanziMesh::Entity_ID_List cells;\n\n int f_owned = temp_guess->size(\"face\");\n for (int f=0; f!=f_owned; ++f) {\n cells.clear();\n temp_guess->mesh()->face_get_cells(f, AmanziMesh::USED, &cells);\n if (cells.size() == 2) {\n if (changed[cells[0]] || changed[cells[1]]) {\n guess_faces[0][f] = (guess_cells[0][cells[0]]\n + guess_cells[0][cells[1]]) \/ 2.0;\n }\n }\n }\n return true;\n }\n return false;\n}\n\nbool MPCFrozenCoupledFlowEnergy::modify_predictor_temp(double h, Teuchos::RCP<TreeVector> u) {\n \/\/ modification of the initial guess occurs by updating T using this guess,\n \/\/ then calculating the p that would be required to keep the same water\n \/\/ mass.\n\n \/\/ Stuff temperature into state\n Teuchos::RCP<TreeVector> uT = u->SubVector(\"energy\");\n sub_pks_[1]->changed_solution();\n\n#if DEBUG_FLAG\n std::cout << std::endl;\n std::cout << \"Modifying guess:\" << std::endl;\n std::cout << \" T0: \" << (*uT->data())(\"cell\",0) << std::endl;\n std::cout << \" T1: \" << (*uT->data())(\"cell\",99) << std::endl;\n#endif\n\n \/\/ update water content, which will get all the needed vals updated at the new temp.\n S_next_->GetFieldEvaluator(\"water_content\")\n ->HasFieldChanged(S_next_.ptr(), \"richards_pk\");\n\n \/\/ get the needed vals\n Teuchos::RCP<const CompositeVector> wc0 = S_inter_->GetFieldData(\"water_content\");\n Teuchos::RCP<const CompositeVector> cv = S_inter_->GetFieldData(\"cell_volume\");\n Teuchos::RCP<const CompositeVector> phi = S_next_->GetFieldData(\"porosity\");\n Teuchos::RCP<const CompositeVector> n_g = S_next_->GetFieldData(\"molar_density_gas\");\n Teuchos::RCP<const CompositeVector> omega_g = S_next_->GetFieldData(\"mol_frac_gas\");\n Teuchos::RCP<const CompositeVector> n_l = S_next_->GetFieldData(\"molar_density_liquid\");\n Teuchos::RCP<const CompositeVector> n_i = S_next_->GetFieldData(\"molar_density_ice\");\n Teuchos::RCP<const CompositeVector> one_on_A = S_next_->GetFieldData(\"wrm_permafrost_one_on_A\");\n Teuchos::RCP<const double> p_atm = S_next_->GetScalarData(\"atmospheric_pressure\");\n\n \/\/ get the WRMs\n Teuchos::RCP<FieldEvaluator> wrm_B_eval_base = S_next_->GetFieldEvaluator(\"wrm_permafrost_one_on_B\");\n Teuchos::RCP<Flow::FlowRelations::WRMRichardsEvaluator> wrm_B_eval =\n Teuchos::rcp_dynamic_cast<Flow::FlowRelations::WRMRichardsEvaluator>(wrm_B_eval_base);\n Teuchos::RCP<Flow::FlowRelations::WRMRegionPairList> wrms = wrm_B_eval->get_WRMs();\n\n\n \/\/ get the result pressure\n Teuchos::RCP<CompositeVector> pres = u->SubVector(\"flow\")->data();\n for (Flow::FlowRelations::WRMRegionPairList::iterator region=wrms->begin();\n region!=wrms->end(); ++region) {\n std::string name = region->first;\n int ncells = pres->mesh()->get_set_size(name, AmanziMesh::CELL, AmanziMesh::OWNED);\n AmanziMesh::Entity_ID_List cells(ncells);\n pres->mesh()->get_set_entities(name, AmanziMesh::CELL, AmanziMesh::OWNED, &cells);\n\n for (AmanziMesh::Entity_ID_List::iterator c=cells.begin(); c!=cells.end(); ++c) {\n double p = (*pres)(\"cell\",*c);\n double A_minus_one = (1.0\/(*one_on_A)(\"cell\",*c) - 1.0);\n\n double wc = (*wc0)(\"cell\",*c) \/ (*cv)(\"cell\",*c);\n double sstar = (wc - (*n_g)(\"cell\",*c)*(*omega_g)(\"cell\",*c)*(*phi)(\"cell\",*c)) \/\n ((*phi)(\"cell\",*c) * ((*n_l)(\"cell\",*c) - (*n_g)(\"cell\",*c)*(*omega_g)(\"cell\",*c)\n + (*n_i)(\"cell\",*c)*A_minus_one) - A_minus_one*wc);\n\n if (sstar > 0.) {\n if (*c==0) std::cout << \" A-1(0) = \" << A_minus_one << std::endl;\n if (*c==99) std::cout << \" A-1(99) = \" << A_minus_one << std::endl;\n if (*c==0) std::cout << \" S*(0) = \" << sstar << std::endl;\n if (*c==99) std::cout << \" S*(99) = \" << sstar << std::endl;\n\n double pc = region->second->capillaryPressure(sstar);\n\n if (*c==0) std::cout << \" pc(0) = \" << pc << std::endl;\n if (*c==99) std::cout << \" pc(99) = \" << pc << std::endl;\n\n (*pres)(\"cell\",*c) = *p_atm - pc;\n\n if (*c==0) std::cout << \" p(0) = \" << (*pres)(\"cell\",*c) << std::endl;\n if (*c==99) std::cout << \" p(99) = \" << (*pres)(\"cell\",*c) << std::endl;\n\n }\n }\n }\n\n AmanziMesh::Entity_ID_List cells;\n pres->ScatterMasterToGhosted(\"cell\");\n\n int f_owned = pres->size(\"face\");\n for (int f=0; f!=f_owned; ++f) {\n cells.clear();\n pres->mesh()->face_get_cells(f, AmanziMesh::USED, &cells);\n int ncells = cells.size();\n\n double face_value = 0.0;\n for (int n=0; n!=ncells; ++n) {\n face_value += (*pres)(\"cell\",cells[n]);\n }\n (*pres)(\"face\",f) = face_value \/ ncells;\n }\n\n return true;\n};\n\n} \/\/ namespace\n<commit_msg>parallel issues in freezing projection -- needs thought and rework<commit_after>\/* -*- mode: c++; c-default-style: \"google\"; indent-tabs-mode: nil -*- *\/\n\/* -------------------------------------------------------------------------\nATS\n\nLicense: see $ATS_DIR\/COPYRIGHT\nAuthor: Ethan Coon\n\nDerived MPC for flow and energy. This couples using a block-diagonal coupler.\n------------------------------------------------------------------------- *\/\n\n#include \"wrm_richards_evaluator.hh\"\n#include \"mpc_frozen_prec_coupled_flow_energy.hh\"\n\nnamespace Amanzi {\n\n#define DEBUG_FLAG 0\n\nRegisteredPKFactory<MPCFrozenCoupledFlowEnergy> MPCFrozenCoupledFlowEnergy::reg_(\"frozen energy-flow preconditioner coupled\");\n\nbool MPCFrozenCoupledFlowEnergy::modify_predictor(double h, Teuchos::RCP<TreeVector> u) {\n Teuchos::RCP<CompositeVector> temp_guess = u->SubVector(\"energy\")->data();\n Epetra_MultiVector& guess_cells = *temp_guess->ViewComponent(\"cell\",false);\n Epetra_MultiVector& guess_faces = *temp_guess->ViewComponent(\"face\",false);\n\n Teuchos::RCP<const CompositeVector> temp = S_next_->GetFieldData(\"temperature\");\n const Epetra_MultiVector& temp_cells = *temp->ViewComponent(\"cell\",false);\n\n bool update_faces(false);\n\n#if DEBUG_FLAG\n std::cout << \"--- Modifying Guess: ---\" << std::cout;\n#endif\n\n int ncells = temp->size(\"cell\",false);\n std::vector<bool> changed(ncells, false);\n for (int c=0; c!=ncells; ++c) {\n if (temp_cells[0][c] >= 273.15 && guess_cells[0][c] < 273.15) {\n \/\/ freezing\n guess_cells[0][c] = 273.15 - 1.e-3;\n changed[c] = true;\n update_faces = true;\n } else if (temp_cells[0][c] <= 273.15 && guess_cells[0][c] > 273.15) {\n \/\/ thawing\n guess_cells[0][c] = 273.15 - 1.e-3;\n changed[c] = true;\n update_faces = true;\n } else if (273.15 > temp_cells[0][c] &&\n temp_cells[0][c] >= 273.1 &&\n (temp_cells[0][c] - guess_cells[0][c]) > 1.e-2) {\n \/\/ catch the 2nd step in freezing -- after the 2nd step the\n \/\/ extrapolation should be ok?\n guess_cells[0][c] = temp_cells[0][c];\n changed[c] = true;\n update_faces = true;\n }\n }\n\n \/\/ unclear... could do an AllReduce() on update_faces and not communicate if\n \/\/ not necessary, but AllReduces() suck... maybe more than extra Scatters?\n \/*\n temp_guess->ScatterMasterToGhosted(\"cell\");\n if (update_faces) {\n AmanziMesh::Entity_ID_List cells;\n\n int f_owned = temp_guess->size(\"face\");\n for (int f=0; f!=f_owned; ++f) {\n cells.clear();\n temp_guess->mesh()->face_get_cells(f, AmanziMesh::USED, &cells);\n if (cells.size() == 2) {\n if (changed[cells[0]] || changed[cells[1]]) {\n guess_faces[0][f] = (guess_cells[0][cells[0]]\n + guess_cells[0][cells[1]]) \/ 2.0;\n }\n }\n }\n return true;\n }\n *\/\n return true;\n}\n\nbool MPCFrozenCoupledFlowEnergy::modify_predictor_temp(double h, Teuchos::RCP<TreeVector> u) {\n \/\/ modification of the initial guess occurs by updating T using this guess,\n \/\/ then calculating the p that would be required to keep the same water\n \/\/ mass.\n\n \/\/ Stuff temperature into state\n Teuchos::RCP<TreeVector> uT = u->SubVector(\"energy\");\n sub_pks_[1]->changed_solution();\n\n#if DEBUG_FLAG\n std::cout << std::endl;\n std::cout << \"Modifying guess:\" << std::endl;\n std::cout << \" T0: \" << (*uT->data())(\"cell\",0) << std::endl;\n std::cout << \" T1: \" << (*uT->data())(\"cell\",99) << std::endl;\n#endif\n\n \/\/ update water content, which will get all the needed vals updated at the new temp.\n S_next_->GetFieldEvaluator(\"water_content\")\n ->HasFieldChanged(S_next_.ptr(), \"richards_pk\");\n\n \/\/ get the needed vals\n Teuchos::RCP<const CompositeVector> wc0 = S_inter_->GetFieldData(\"water_content\");\n Teuchos::RCP<const CompositeVector> cv = S_inter_->GetFieldData(\"cell_volume\");\n Teuchos::RCP<const CompositeVector> phi = S_next_->GetFieldData(\"porosity\");\n Teuchos::RCP<const CompositeVector> n_g = S_next_->GetFieldData(\"molar_density_gas\");\n Teuchos::RCP<const CompositeVector> omega_g = S_next_->GetFieldData(\"mol_frac_gas\");\n Teuchos::RCP<const CompositeVector> n_l = S_next_->GetFieldData(\"molar_density_liquid\");\n Teuchos::RCP<const CompositeVector> n_i = S_next_->GetFieldData(\"molar_density_ice\");\n Teuchos::RCP<const CompositeVector> one_on_A = S_next_->GetFieldData(\"wrm_permafrost_one_on_A\");\n Teuchos::RCP<const double> p_atm = S_next_->GetScalarData(\"atmospheric_pressure\");\n\n \/\/ get the WRMs\n Teuchos::RCP<FieldEvaluator> wrm_B_eval_base = S_next_->GetFieldEvaluator(\"wrm_permafrost_one_on_B\");\n Teuchos::RCP<Flow::FlowRelations::WRMRichardsEvaluator> wrm_B_eval =\n Teuchos::rcp_dynamic_cast<Flow::FlowRelations::WRMRichardsEvaluator>(wrm_B_eval_base);\n Teuchos::RCP<Flow::FlowRelations::WRMRegionPairList> wrms = wrm_B_eval->get_WRMs();\n\n\n \/\/ get the result pressure\n Teuchos::RCP<CompositeVector> pres = u->SubVector(\"flow\")->data();\n for (Flow::FlowRelations::WRMRegionPairList::iterator region=wrms->begin();\n region!=wrms->end(); ++region) {\n std::string name = region->first;\n int ncells = pres->mesh()->get_set_size(name, AmanziMesh::CELL, AmanziMesh::OWNED);\n AmanziMesh::Entity_ID_List cells(ncells);\n pres->mesh()->get_set_entities(name, AmanziMesh::CELL, AmanziMesh::OWNED, &cells);\n\n for (AmanziMesh::Entity_ID_List::iterator c=cells.begin(); c!=cells.end(); ++c) {\n double p = (*pres)(\"cell\",*c);\n double A_minus_one = (1.0\/(*one_on_A)(\"cell\",*c) - 1.0);\n\n double wc = (*wc0)(\"cell\",*c) \/ (*cv)(\"cell\",*c);\n double sstar = (wc - (*n_g)(\"cell\",*c)*(*omega_g)(\"cell\",*c)*(*phi)(\"cell\",*c)) \/\n ((*phi)(\"cell\",*c) * ((*n_l)(\"cell\",*c) - (*n_g)(\"cell\",*c)*(*omega_g)(\"cell\",*c)\n + (*n_i)(\"cell\",*c)*A_minus_one) - A_minus_one*wc);\n\n if (sstar > 0.) {\n if (*c==0) std::cout << \" A-1(0) = \" << A_minus_one << std::endl;\n if (*c==99) std::cout << \" A-1(99) = \" << A_minus_one << std::endl;\n if (*c==0) std::cout << \" S*(0) = \" << sstar << std::endl;\n if (*c==99) std::cout << \" S*(99) = \" << sstar << std::endl;\n\n double pc = region->second->capillaryPressure(sstar);\n\n if (*c==0) std::cout << \" pc(0) = \" << pc << std::endl;\n if (*c==99) std::cout << \" pc(99) = \" << pc << std::endl;\n\n (*pres)(\"cell\",*c) = *p_atm - pc;\n\n if (*c==0) std::cout << \" p(0) = \" << (*pres)(\"cell\",*c) << std::endl;\n if (*c==99) std::cout << \" p(99) = \" << (*pres)(\"cell\",*c) << std::endl;\n\n }\n }\n }\n\n AmanziMesh::Entity_ID_List cells;\n pres->ScatterMasterToGhosted(\"cell\");\n\n int f_owned = pres->size(\"face\");\n for (int f=0; f!=f_owned; ++f) {\n cells.clear();\n pres->mesh()->face_get_cells(f, AmanziMesh::USED, &cells);\n int ncells = cells.size();\n\n double face_value = 0.0;\n for (int n=0; n!=ncells; ++n) {\n face_value += (*pres)(\"cell\",cells[n]);\n }\n (*pres)(\"face\",f) = face_value \/ ncells;\n }\n\n return true;\n};\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\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 ofconditions and the following disclaimer.\n\/\/\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 materialsprovided with the\n\/\/ distribution.\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 HOLDER 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#pragma once\n\n#include <string>\n#include <string_view>\n#include <Common\/Macros.hh>\n\nnamespace Tadpole {\n\nclass _Safe {};\nclass _Unsafe {};\n\nusing nil_t = std::nullptr_t;\nusing byte_t = std::uint8_t;\nusing i8_t = std::int8_t;\nusing u8_t = std::uint8_t;\nusing i16_t = std::int16_t;\nusing u16_t = std::uint16_t;\nusing i32_t = std::int32_t;\nusing u32_t = std::uint32_t;\nusing i64_t = std::int64_t;\nusing u64_t = std::uint64_t;\nusing sz_t = std::size_t;\n#if defined(TADPOLE_GNUC)\n using ssz_t = std::ssize_t;\n#else\n using ssz_t = std::int64_t;\n#endif\nusing str_t = std::string;\nusing strv_t = std::string_view;\nusing ss_t = std::stringstream;\nusing safe_t = _Safe;\nusing unsafe_t = _Unsafe;\n\n}\n<commit_msg>:construction: chore(types): updated the types<commit_after>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\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 ofconditions and the following disclaimer.\n\/\/\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 materialsprovided with the\n\/\/ distribution.\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 HOLDER 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#pragma once\n\n#include <string>\n#include <string_view>\n#include <sstream>\n#include <Common\/Macros.hh>\n\nnamespace Tadpole {\n\nclass _Safe {};\nclass _Unsafe {};\n\nusing nil_t = std::nullptr_t;\nusing byte_t = std::uint8_t;\nusing i8_t = std::int8_t;\nusing u8_t = std::uint8_t;\nusing i16_t = std::int16_t;\nusing u16_t = std::uint16_t;\nusing i32_t = std::int32_t;\nusing u32_t = std::uint32_t;\nusing i64_t = std::int64_t;\nusing u64_t = std::uint64_t;\nusing sz_t = std::size_t;\n#if defined(TADPOLE_GNUC)\n using ssz_t = std::ssize_t;\n#else\n using ssz_t = std::int64_t;\n#endif\nusing str_t = std::string;\nusing strv_t = std::string_view;\nusing ss_t = std::stringstream;\nusing safe_t = _Safe;\nusing unsafe_t = _Unsafe;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 ASMlover. 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 ofconditions and the following disclaimer.\n\/\/\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 materialsprovided with the\n\/\/ distribution.\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 HOLDER 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#include <sstream>\n#include \"..\/common\/errors.hh\"\n#include \"environment.hh\"\n#include \"interpret_helper.hh\"\n#include \"interpreter.hh\"\n#include \"callable.hh\"\n\nnamespace sage {\n\nFunction::Function(\n const FunctionStmtPtr& decl, const EnvironmentPtr& closure, bool is_ctor)\n : decl_(decl)\n , closure_(closure)\n , is_ctor_(is_ctor) {\n}\n\nstd::string Function::name(void) const {\n return decl_->name().get_literal();\n}\n\nValue Function::call(\n const InterpreterPtr& interp, const std::vector<Value>& arguments) {\n auto envp = std::make_shared<Environment>(closure_);\n auto& params = decl_->params();\n std::size_t n{params.size()};\n for (std::size_t i = 0; i < n; ++i)\n envp->define(params[i].get_literal(), arguments[i]);\n\n try {\n interp->invoke_evaluate_block(decl_->body(), envp);\n }\n catch (const Return& r) {\n if (is_ctor_)\n return closure_->get_at(0, \"self\");\n return r.value();\n }\n if (is_ctor_)\n return closure_->get_at(0, \"self\");\n return nullptr;\n}\n\nstd::size_t Function::arity(void) const {\n return decl_->params().size();\n}\n\nstd::string Function::to_string(void) const {\n return \"<script fn `\" + decl_->name().get_literal() + \"`>\";\n}\n\nFunctionPtr Function::bind(const InstancePtr& inst) {\n auto envp = std::make_shared<Environment>(closure_);\n envp->define(\"self\", Value(inst));\n return std::make_shared<Function>(decl_, envp, is_ctor_);\n}\n\nClass::Class(const std::string& name,\n const ClassPtr& superclass,\n const std::unordered_map<std::string, FunctionPtr>& methods)\n : name_(name)\n , superclass_(superclass)\n , methods_(methods) {\n}\n\nstd::string Class::name(void) const {\n return name_;\n}\n\nValue Class::call(\n const InterpreterPtr& interp, const std::vector<Value>& arguments) {\n auto inst = std::make_shared<Instance>(shared_from_this());\n auto ctor = get_method(inst, \"ctor\");\n if (ctor)\n ctor->call(interp, arguments);\n return inst;\n}\n\nstd::size_t Class::arity(void) const {\n auto method_iter = methods_.find(\"ctor\");\n if (method_iter != methods_.end())\n return method_iter->second->arity();\n return 0;\n}\n\nstd::string Class::to_string(void) const {\n return \"<script class `\" + name_ + \"`>\";\n}\n\nFunctionPtr Class::get_method(\n const InstancePtr& inst, const std::string& name) {\n auto method_iter = methods_.find(name);\n if (method_iter != methods_.end())\n return method_iter->second->bind(inst);\n return nullptr;\n}\n\nInstance::Instance(const ClassPtr& cls)\n : class_(cls) {\n}\n\nbool Instance::is_truthy(void) const {\n \/\/ TODO: default is true\n return true;\n}\n\nstd::string Instance::to_string(void) const {\n std::stringstream ss;\n ss << \"<`\" << class_->name() << \"` instance at \" << this << \">\";\n return ss.str();\n}\n\nvoid Instance::set_attribute(const Token& name, const Value& value) {\n attributes_[name.get_literal()] = value;\n}\n\nValue Instance::get_attribute(const Token& name) {\n auto attr_iter = attributes_.find(name.get_literal());\n if (attr_iter != attributes_.end())\n return attr_iter->second;\n\n auto method = class_->get_method(shared_from_this(), name.get_literal());\n if (method)\n return method;\n\n throw RuntimeError(name, \"undefined attribute `\" + name.get_literal() + \"`\");\n}\n\n}\n<commit_msg>:construction: chore(inherit): add calling inheritance methods support<commit_after>\/\/ Copyright (c) 2019 ASMlover. 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 ofconditions and the following disclaimer.\n\/\/\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 materialsprovided with the\n\/\/ distribution.\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 HOLDER 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#include <sstream>\n#include \"..\/common\/errors.hh\"\n#include \"environment.hh\"\n#include \"interpret_helper.hh\"\n#include \"interpreter.hh\"\n#include \"callable.hh\"\n\nnamespace sage {\n\nFunction::Function(\n const FunctionStmtPtr& decl, const EnvironmentPtr& closure, bool is_ctor)\n : decl_(decl)\n , closure_(closure)\n , is_ctor_(is_ctor) {\n}\n\nstd::string Function::name(void) const {\n return decl_->name().get_literal();\n}\n\nValue Function::call(\n const InterpreterPtr& interp, const std::vector<Value>& arguments) {\n auto envp = std::make_shared<Environment>(closure_);\n auto& params = decl_->params();\n std::size_t n{params.size()};\n for (std::size_t i = 0; i < n; ++i)\n envp->define(params[i].get_literal(), arguments[i]);\n\n try {\n interp->invoke_evaluate_block(decl_->body(), envp);\n }\n catch (const Return& r) {\n if (is_ctor_)\n return closure_->get_at(0, \"self\");\n return r.value();\n }\n if (is_ctor_)\n return closure_->get_at(0, \"self\");\n return nullptr;\n}\n\nstd::size_t Function::arity(void) const {\n return decl_->params().size();\n}\n\nstd::string Function::to_string(void) const {\n return \"<script fn `\" + decl_->name().get_literal() + \"`>\";\n}\n\nFunctionPtr Function::bind(const InstancePtr& inst) {\n auto envp = std::make_shared<Environment>(closure_);\n envp->define(\"self\", Value(inst));\n return std::make_shared<Function>(decl_, envp, is_ctor_);\n}\n\nClass::Class(const std::string& name,\n const ClassPtr& superclass,\n const std::unordered_map<std::string, FunctionPtr>& methods)\n : name_(name)\n , superclass_(superclass)\n , methods_(methods) {\n}\n\nstd::string Class::name(void) const {\n return name_;\n}\n\nValue Class::call(\n const InterpreterPtr& interp, const std::vector<Value>& arguments) {\n auto inst = std::make_shared<Instance>(shared_from_this());\n auto ctor = get_method(inst, \"ctor\");\n if (ctor)\n ctor->call(interp, arguments);\n return inst;\n}\n\nstd::size_t Class::arity(void) const {\n auto method_iter = methods_.find(\"ctor\");\n if (method_iter != methods_.end())\n return method_iter->second->arity();\n return 0;\n}\n\nstd::string Class::to_string(void) const {\n return \"<script class `\" + name_ + \"`>\";\n}\n\nFunctionPtr Class::get_method(\n const InstancePtr& inst, const std::string& name) {\n auto method_iter = methods_.find(name);\n if (method_iter != methods_.end())\n return method_iter->second->bind(inst);\n if (superclass_)\n return superclass_->get_method(inst, name);\n return nullptr;\n}\n\nInstance::Instance(const ClassPtr& cls)\n : class_(cls) {\n}\n\nbool Instance::is_truthy(void) const {\n \/\/ TODO: default is true\n return true;\n}\n\nstd::string Instance::to_string(void) const {\n std::stringstream ss;\n ss << \"<`\" << class_->name() << \"` instance at \" << this << \">\";\n return ss.str();\n}\n\nvoid Instance::set_attribute(const Token& name, const Value& value) {\n attributes_[name.get_literal()] = value;\n}\n\nValue Instance::get_attribute(const Token& name) {\n auto attr_iter = attributes_.find(name.get_literal());\n if (attr_iter != attributes_.end())\n return attr_iter->second;\n\n auto method = class_->get_method(shared_from_this(), name.get_literal());\n if (method)\n return method;\n\n throw RuntimeError(name, \"undefined attribute `\" + name.get_literal() + \"`\");\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <sstream>\n#include <vector>\n\n#include <queue>\n#include <map>\n#include <boost\/program_options.hpp>\n#include <boost\/shared_ptr.hpp>\n\n#include \"filelib.h\"\n#include \"alignment_io.h\"\n\nnamespace po = boost::program_options;\nusing namespace std;\n\nstruct Command {\n virtual ~Command() {}\n virtual string Name() const = 0;\n\n \/\/ returns 1 for alignment grid output [default]\n \/\/ returns 2 if Summary() should be called [for AER, etc]\n virtual int Result() const { return 1; }\n\n virtual bool RequiresTwoOperands() const { return true; }\n virtual void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) = 0;\n void EnsureSize(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n x->resize(max(a.width(), b.width()), max(a.height(), b.height()));\n }\n static bool Safe(const Array2D<bool>& a, int i, int j) {\n if (i >= 0 && j >= 0 && i < static_cast<int>(a.width()) && j < static_cast<int>(a.height()))\n return a(i,j);\n else\n return false;\n }\n virtual void Summary() { assert(!\"Summary should have been overridden\"); }\n};\n\n\/\/ compute fmeasure, second alignment is reference, first is hyp\nstruct FMeasureCommand : public Command {\n FMeasureCommand() : matches(), num_predicted(), num_in_ref() {}\n int Result() const { return 2; }\n string Name() const { return \"fmeasure\"; }\n bool RequiresTwoOperands() const { return true; }\n void Apply(const Array2D<bool>& hyp, const Array2D<bool>& ref, Array2D<bool>* x) {\n (void) x; \/\/ AER just computes statistics, not an alignment\n unsigned i_len = ref.width();\n unsigned j_len = ref.height();\n for (unsigned i = 0; i < i_len; ++i) {\n for (unsigned j = 0; j < j_len; ++j) {\n if (ref(i,j)) {\n ++num_in_ref;\n if (Safe(hyp, i, j)) ++matches;\n } \n }\n }\n for (unsigned i = 0; i < hyp.width(); ++i)\n for (unsigned j = 0; j < hyp.height(); ++j)\n if (hyp(i,j)) ++num_predicted;\n }\n void Summary() {\n if (num_predicted == 0 || num_in_ref == 0) {\n cerr << \"Insufficient statistics to compute f-measure!\\n\";\n abort();\n }\n const double prec = static_cast<double>(matches) \/ num_predicted;\n const double rec = static_cast<double>(matches) \/ num_in_ref;\n cout << \"P: \" << prec << endl;\n cout << \"R: \" << rec << endl;\n const double f = (2.0 * prec * rec) \/ (rec + prec);\n cout << \"F: \" << f << endl;\n }\n int matches;\n int num_predicted;\n int num_in_ref;\n};\n\nstruct DisplayCommand : public Command {\n string Name() const { return \"display\"; }\n bool RequiresTwoOperands() const { return false; }\n void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {\n *x = in;\n cout << *x << endl;\n }\n};\n\nstruct ConvertCommand : public Command {\n string Name() const { return \"convert\"; }\n bool RequiresTwoOperands() const { return false; }\n void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {\n *x = in;\n }\n};\n\nstruct InvertCommand : public Command {\n string Name() const { return \"invert\"; }\n bool RequiresTwoOperands() const { return false; }\n void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {\n Array2D<bool>& res = *x;\n res.resize(in.height(), in.width());\n for (unsigned i = 0; i < in.height(); ++i)\n for (unsigned j = 0; j < in.width(); ++j)\n res(i, j) = in(j, i);\n }\n};\n\nstruct IntersectCommand : public Command {\n string Name() const { return \"intersect\"; }\n bool RequiresTwoOperands() const { return true; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n EnsureSize(a, b, x);\n Array2D<bool>& res = *x;\n for (unsigned i = 0; i < a.width(); ++i)\n for (unsigned j = 0; j < a.height(); ++j)\n res(i, j) = Safe(a, i, j) && Safe(b, i, j);\n }\n};\n\nstruct UnionCommand : public Command {\n string Name() const { return \"union\"; }\n bool RequiresTwoOperands() const { return true; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n EnsureSize(a, b, x);\n Array2D<bool>& res = *x;\n for (unsigned i = 0; i < res.width(); ++i)\n for (unsigned j = 0; j < res.height(); ++j)\n res(i, j) = Safe(a, i, j) || Safe(b, i, j);\n }\n};\n\nstruct RefineCommand : public Command {\n RefineCommand() {\n neighbors_.push_back(make_pair(1,0));\n neighbors_.push_back(make_pair(-1,0));\n neighbors_.push_back(make_pair(0,1));\n neighbors_.push_back(make_pair(0,-1));\n }\n bool RequiresTwoOperands() const { return true; }\n\n void Align(unsigned i, unsigned j) {\n res_(i, j) = true;\n is_i_aligned_[i] = true;\n is_j_aligned_[j] = true;\n }\n\n bool IsNeighborAligned(int i, int j) const {\n for (unsigned k = 0; k < neighbors_.size(); ++k) {\n const int di = neighbors_[k].first;\n const int dj = neighbors_[k].second;\n if (Safe(res_, i + di, j + dj))\n return true;\n }\n return false;\n }\n\n bool IsNeitherAligned(int i, int j) const {\n return !(is_i_aligned_[i] || is_j_aligned_[j]);\n }\n\n bool IsOneOrBothUnaligned(int i, int j) const {\n return !(is_i_aligned_[i] && is_j_aligned_[j]);\n }\n\n bool KoehnAligned(int i, int j) const {\n return IsOneOrBothUnaligned(i, j) && IsNeighborAligned(i, j);\n }\n\n typedef bool (RefineCommand::*Predicate)(int i, int j) const;\n\n protected:\n void InitRefine(\n const Array2D<bool>& a,\n const Array2D<bool>& b) {\n res_.clear();\n EnsureSize(a, b, &res_);\n in_.clear(); un_.clear(); is_i_aligned_.clear(); is_j_aligned_.clear();\n EnsureSize(a, b, &in_);\n EnsureSize(a, b, &un_);\n is_i_aligned_.resize(res_.width(), false);\n is_j_aligned_.resize(res_.height(), false);\n for (unsigned i = 0; i < in_.width(); ++i)\n for (unsigned j = 0; j < in_.height(); ++j) {\n un_(i, j) = Safe(a, i, j) || Safe(b, i, j);\n in_(i, j) = Safe(a, i, j) && Safe(b, i, j);\n if (in_(i, j)) Align(i, j);\n }\n }\n \/\/ \"grow\" the resulting alignment using the points in adds\n \/\/ if they match the constraints determined by pred\n void Grow(Predicate pred, bool idempotent, const Array2D<bool>& adds) {\n if (idempotent) {\n for (unsigned i = 0; i < adds.width(); ++i)\n for (unsigned j = 0; j < adds.height(); ++j) {\n if (adds(i, j) && !res_(i, j) &&\n (this->*pred)(i, j)) Align(i, j);\n }\n return;\n }\n set<pair<int, int> > p;\n for (unsigned i = 0; i < adds.width(); ++i)\n for (unsigned j = 0; j < adds.height(); ++j)\n if (adds(i, j) && !res_(i, j))\n p.insert(make_pair(i, j));\n bool keep_going = !p.empty();\n while (keep_going) {\n keep_going = false;\n for (set<pair<int, int> >::iterator pi = p.begin();\n pi != p.end(); ++pi) {\n if ((this->*pred)(pi->first, pi->second)) {\n Align(pi->first, pi->second);\n p.erase(pi);\n keep_going = true;\n }\n }\n }\n }\n Array2D<bool> res_; \/\/ refined alignment\n Array2D<bool> in_; \/\/ intersection alignment\n Array2D<bool> un_; \/\/ union alignment\n vector<bool> is_i_aligned_;\n vector<bool> is_j_aligned_;\n vector<pair<int,int> > neighbors_;\n};\n\nstruct DiagCommand : public RefineCommand {\n DiagCommand() {\n neighbors_.push_back(make_pair(1,1));\n neighbors_.push_back(make_pair(-1,1));\n neighbors_.push_back(make_pair(1,-1));\n neighbors_.push_back(make_pair(-1,-1));\n }\n};\n\nstruct GDCommand : public DiagCommand {\n string Name() const { return \"grow-diag\"; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n InitRefine(a, b);\n Grow(&RefineCommand::KoehnAligned, false, un_);\n *x = res_;\n }\n};\n\nstruct GDFCommand : public DiagCommand {\n string Name() const { return \"grow-diag-final\"; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n InitRefine(a, b);\n Grow(&RefineCommand::KoehnAligned, false, un_);\n Grow(&RefineCommand::IsOneOrBothUnaligned, true, a);\n Grow(&RefineCommand::IsOneOrBothUnaligned, true, b);\n *x = res_;\n }\n};\n\nstruct GDFACommand : public DiagCommand {\n string Name() const { return \"grow-diag-final-and\"; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n InitRefine(a, b);\n Grow(&RefineCommand::KoehnAligned, false, un_);\n Grow(&RefineCommand::IsNeitherAligned, true, a);\n Grow(&RefineCommand::IsNeitherAligned, true, b);\n *x = res_;\n }\n};\n\nmap<string, boost::shared_ptr<Command> > commands;\n\nvoid InitCommandLine(unsigned argc, char** argv, po::variables_map* conf) {\n po::options_description opts(\"Configuration options\");\n ostringstream os;\n os << \"Operation to perform:\";\n for (map<string, boost::shared_ptr<Command> >::iterator it = commands.begin();\n it != commands.end(); ++it) {\n os << ' ' << it->first;\n }\n string cstr = os.str();\n opts.add_options()\n (\"input_1,i\", po::value<string>(), \"[REQUIRED] Alignment 1 file, - for STDIN\")\n (\"input_2,j\", po::value<string>(), \"Alignment 2 file, - for STDIN\")\n\t(\"command,c\", po::value<string>()->default_value(\"convert\"), cstr.c_str())\n (\"help,h\", \"Print this help message and exit\");\n po::options_description clo(\"Command line options\");\n po::options_description dcmdline_options;\n dcmdline_options.add(opts);\n\n po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n po::notify(*conf);\n\n if (conf->count(\"help\") || conf->count(\"input_1\") == 0 || conf->count(\"command\") == 0) {\n cerr << dcmdline_options << endl;\n exit(1);\n }\n const string cmd = (*conf)[\"command\"].as<string>();\n if (commands.count(cmd) == 0) {\n cerr << \"Don't understand command: \" << cmd << endl;\n exit(1);\n }\n if (commands[cmd]->RequiresTwoOperands()) {\n if (conf->count(\"input_2\") == 0) {\n cerr << \"Command '\" << cmd << \"' requires two alignment files\\n\";\n exit(1);\n }\n if ((*conf)[\"input_1\"].as<string>() == \"-\" && (*conf)[\"input_2\"].as<string>() == \"-\") {\n cerr << \"Both inputs STDIN, reading PAIRS of lines\\n\";\n }\n } else {\n if (conf->count(\"input_2\") != 0) {\n cerr << \"Command '\" << cmd << \"' requires only one alignment file\\n\";\n exit(1);\n }\n }\n}\n\ntemplate<class C> static void AddCommand() {\n C* c = new C;\n commands[c->Name()].reset(c);\n}\n\nint main(int argc, char **argv) {\n AddCommand<ConvertCommand>();\n AddCommand<DisplayCommand>();\n AddCommand<InvertCommand>();\n AddCommand<IntersectCommand>();\n AddCommand<UnionCommand>();\n AddCommand<GDCommand>();\n AddCommand<GDFCommand>();\n AddCommand<GDFACommand>();\n AddCommand<FMeasureCommand>();\n po::variables_map conf;\n InitCommandLine(argc, argv, &conf);\n Command& cmd = *commands[conf[\"command\"].as<string>()];\n boost::shared_ptr<ReadFile> rf1(new ReadFile(conf[\"input_1\"].as<string>()));\n boost::shared_ptr<ReadFile> rf2;\n if (cmd.RequiresTwoOperands())\n rf2.reset(new ReadFile(conf[\"input_2\"].as<string>()));\n istream* in1 = rf1->stream();\n istream* in2 = NULL;\n if (rf2) in2 = rf2->stream();\n while(*in1) {\n string line1;\n string line2;\n getline(*in1, line1);\n if (in2) {\n getline(*in2, line2);\n if ((*in1 && !*in2) || (*in2 && !*in1)) {\n cerr << \"Mismatched number of lines!\\n\";\n exit(1);\n }\n }\n if (line1.empty() && !*in1) break;\n boost::shared_ptr<Array2D<bool> > out(new Array2D<bool>);\n boost::shared_ptr<Array2D<bool> > a1 = AlignmentIO::ReadPharaohAlignmentGrid(line1);\n if (in2) {\n boost::shared_ptr<Array2D<bool> > a2 = AlignmentIO::ReadPharaohAlignmentGrid(line2);\n cmd.Apply(*a1, *a2, out.get());\n } else {\n Array2D<bool> dummy;\n cmd.Apply(*a1, dummy, out.get());\n }\n \n if (cmd.Result() == 1) {\n AlignmentIO::SerializePharaohFormat(*out, &cout);\n }\n }\n if (cmd.Result() == 2)\n cmd.Summary();\n return 0;\n}\n\n<commit_msg>fix iterator misuse<commit_after>#include <iostream>\n#include <sstream>\n#include <vector>\n\n#include <queue>\n#include <map>\n#include <boost\/program_options.hpp>\n#include <boost\/shared_ptr.hpp>\n\n#include \"filelib.h\"\n#include \"alignment_io.h\"\n\nnamespace po = boost::program_options;\nusing namespace std;\n\nstruct Command {\n virtual ~Command() {}\n virtual string Name() const = 0;\n\n \/\/ returns 1 for alignment grid output [default]\n \/\/ returns 2 if Summary() should be called [for AER, etc]\n virtual int Result() const { return 1; }\n\n virtual bool RequiresTwoOperands() const { return true; }\n virtual void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) = 0;\n void EnsureSize(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n x->resize(max(a.width(), b.width()), max(a.height(), b.height()));\n }\n static bool Safe(const Array2D<bool>& a, int i, int j) {\n if (i >= 0 && j >= 0 && i < static_cast<int>(a.width()) && j < static_cast<int>(a.height()))\n return a(i,j);\n else\n return false;\n }\n virtual void Summary() { assert(!\"Summary should have been overridden\"); }\n};\n\n\/\/ compute fmeasure, second alignment is reference, first is hyp\nstruct FMeasureCommand : public Command {\n FMeasureCommand() : matches(), num_predicted(), num_in_ref() {}\n int Result() const { return 2; }\n string Name() const { return \"fmeasure\"; }\n bool RequiresTwoOperands() const { return true; }\n void Apply(const Array2D<bool>& hyp, const Array2D<bool>& ref, Array2D<bool>* x) {\n (void) x; \/\/ AER just computes statistics, not an alignment\n unsigned i_len = ref.width();\n unsigned j_len = ref.height();\n for (unsigned i = 0; i < i_len; ++i) {\n for (unsigned j = 0; j < j_len; ++j) {\n if (ref(i,j)) {\n ++num_in_ref;\n if (Safe(hyp, i, j)) ++matches;\n } \n }\n }\n for (unsigned i = 0; i < hyp.width(); ++i)\n for (unsigned j = 0; j < hyp.height(); ++j)\n if (hyp(i,j)) ++num_predicted;\n }\n void Summary() {\n if (num_predicted == 0 || num_in_ref == 0) {\n cerr << \"Insufficient statistics to compute f-measure!\\n\";\n abort();\n }\n const double prec = static_cast<double>(matches) \/ num_predicted;\n const double rec = static_cast<double>(matches) \/ num_in_ref;\n cout << \"P: \" << prec << endl;\n cout << \"R: \" << rec << endl;\n const double f = (2.0 * prec * rec) \/ (rec + prec);\n cout << \"F: \" << f << endl;\n }\n int matches;\n int num_predicted;\n int num_in_ref;\n};\n\nstruct DisplayCommand : public Command {\n string Name() const { return \"display\"; }\n bool RequiresTwoOperands() const { return false; }\n void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {\n *x = in;\n cout << *x << endl;\n }\n};\n\nstruct ConvertCommand : public Command {\n string Name() const { return \"convert\"; }\n bool RequiresTwoOperands() const { return false; }\n void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {\n *x = in;\n }\n};\n\nstruct InvertCommand : public Command {\n string Name() const { return \"invert\"; }\n bool RequiresTwoOperands() const { return false; }\n void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {\n Array2D<bool>& res = *x;\n res.resize(in.height(), in.width());\n for (unsigned i = 0; i < in.height(); ++i)\n for (unsigned j = 0; j < in.width(); ++j)\n res(i, j) = in(j, i);\n }\n};\n\nstruct IntersectCommand : public Command {\n string Name() const { return \"intersect\"; }\n bool RequiresTwoOperands() const { return true; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n EnsureSize(a, b, x);\n Array2D<bool>& res = *x;\n for (unsigned i = 0; i < a.width(); ++i)\n for (unsigned j = 0; j < a.height(); ++j)\n res(i, j) = Safe(a, i, j) && Safe(b, i, j);\n }\n};\n\nstruct UnionCommand : public Command {\n string Name() const { return \"union\"; }\n bool RequiresTwoOperands() const { return true; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n EnsureSize(a, b, x);\n Array2D<bool>& res = *x;\n for (unsigned i = 0; i < res.width(); ++i)\n for (unsigned j = 0; j < res.height(); ++j)\n res(i, j) = Safe(a, i, j) || Safe(b, i, j);\n }\n};\n\nstruct RefineCommand : public Command {\n RefineCommand() {\n neighbors_.push_back(make_pair(1,0));\n neighbors_.push_back(make_pair(-1,0));\n neighbors_.push_back(make_pair(0,1));\n neighbors_.push_back(make_pair(0,-1));\n }\n bool RequiresTwoOperands() const { return true; }\n\n void Align(unsigned i, unsigned j) {\n res_(i, j) = true;\n is_i_aligned_[i] = true;\n is_j_aligned_[j] = true;\n }\n\n bool IsNeighborAligned(int i, int j) const {\n for (unsigned k = 0; k < neighbors_.size(); ++k) {\n const int di = neighbors_[k].first;\n const int dj = neighbors_[k].second;\n if (Safe(res_, i + di, j + dj))\n return true;\n }\n return false;\n }\n\n bool IsNeitherAligned(int i, int j) const {\n return !(is_i_aligned_[i] || is_j_aligned_[j]);\n }\n\n bool IsOneOrBothUnaligned(int i, int j) const {\n return !(is_i_aligned_[i] && is_j_aligned_[j]);\n }\n\n bool KoehnAligned(int i, int j) const {\n return IsOneOrBothUnaligned(i, j) && IsNeighborAligned(i, j);\n }\n\n typedef bool (RefineCommand::*Predicate)(int i, int j) const;\n\n protected:\n void InitRefine(\n const Array2D<bool>& a,\n const Array2D<bool>& b) {\n res_.clear();\n EnsureSize(a, b, &res_);\n in_.clear(); un_.clear(); is_i_aligned_.clear(); is_j_aligned_.clear();\n EnsureSize(a, b, &in_);\n EnsureSize(a, b, &un_);\n is_i_aligned_.resize(res_.width(), false);\n is_j_aligned_.resize(res_.height(), false);\n for (unsigned i = 0; i < in_.width(); ++i)\n for (unsigned j = 0; j < in_.height(); ++j) {\n un_(i, j) = Safe(a, i, j) || Safe(b, i, j);\n in_(i, j) = Safe(a, i, j) && Safe(b, i, j);\n if (in_(i, j)) Align(i, j);\n }\n }\n \/\/ \"grow\" the resulting alignment using the points in adds\n \/\/ if they match the constraints determined by pred\n void Grow(Predicate pred, bool idempotent, const Array2D<bool>& adds) {\n if (idempotent) {\n for (unsigned i = 0; i < adds.width(); ++i)\n for (unsigned j = 0; j < adds.height(); ++j) {\n if (adds(i, j) && !res_(i, j) &&\n (this->*pred)(i, j)) Align(i, j);\n }\n return;\n }\n set<pair<int, int> > p;\n for (unsigned i = 0; i < adds.width(); ++i)\n for (unsigned j = 0; j < adds.height(); ++j)\n if (adds(i, j) && !res_(i, j))\n p.insert(make_pair(i, j));\n bool keep_going = !p.empty();\n while (keep_going) {\n keep_going = false;\n set<pair<int, int> > added;\n for (set<pair<int, int> >::iterator pi = p.begin(); pi != p.end(); ++pi) {\n if ((this->*pred)(pi->first, pi->second)) {\n Align(pi->first, pi->second);\n added.insert(make_pair(pi->first, pi->second));\n keep_going = true;\n }\n }\n for (set<pair<int, int> >::iterator ai = added.begin(); ai != added.end(); ++ai)\n p.erase(*ai);\n }\n }\n Array2D<bool> res_; \/\/ refined alignment\n Array2D<bool> in_; \/\/ intersection alignment\n Array2D<bool> un_; \/\/ union alignment\n vector<bool> is_i_aligned_;\n vector<bool> is_j_aligned_;\n vector<pair<int,int> > neighbors_;\n};\n\nstruct DiagCommand : public RefineCommand {\n DiagCommand() {\n neighbors_.push_back(make_pair(1,1));\n neighbors_.push_back(make_pair(-1,1));\n neighbors_.push_back(make_pair(1,-1));\n neighbors_.push_back(make_pair(-1,-1));\n }\n};\n\nstruct GDCommand : public DiagCommand {\n string Name() const { return \"grow-diag\"; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n InitRefine(a, b);\n Grow(&RefineCommand::KoehnAligned, false, un_);\n *x = res_;\n }\n};\n\nstruct GDFCommand : public DiagCommand {\n string Name() const { return \"grow-diag-final\"; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n InitRefine(a, b);\n Grow(&RefineCommand::KoehnAligned, false, un_);\n Grow(&RefineCommand::IsOneOrBothUnaligned, true, a);\n Grow(&RefineCommand::IsOneOrBothUnaligned, true, b);\n *x = res_;\n }\n};\n\nstruct GDFACommand : public DiagCommand {\n string Name() const { return \"grow-diag-final-and\"; }\n void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {\n InitRefine(a, b);\n Grow(&RefineCommand::KoehnAligned, false, un_);\n Grow(&RefineCommand::IsNeitherAligned, true, a);\n Grow(&RefineCommand::IsNeitherAligned, true, b);\n *x = res_;\n }\n};\n\nmap<string, boost::shared_ptr<Command> > commands;\n\nvoid InitCommandLine(unsigned argc, char** argv, po::variables_map* conf) {\n po::options_description opts(\"Configuration options\");\n ostringstream os;\n os << \"Operation to perform:\";\n for (map<string, boost::shared_ptr<Command> >::iterator it = commands.begin();\n it != commands.end(); ++it) {\n os << ' ' << it->first;\n }\n string cstr = os.str();\n opts.add_options()\n (\"input_1,i\", po::value<string>(), \"[REQUIRED] Alignment 1 file, - for STDIN\")\n (\"input_2,j\", po::value<string>(), \"Alignment 2 file, - for STDIN\")\n\t(\"command,c\", po::value<string>()->default_value(\"convert\"), cstr.c_str())\n (\"help,h\", \"Print this help message and exit\");\n po::options_description clo(\"Command line options\");\n po::options_description dcmdline_options;\n dcmdline_options.add(opts);\n\n po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n po::notify(*conf);\n\n if (conf->count(\"help\") || conf->count(\"input_1\") == 0 || conf->count(\"command\") == 0) {\n cerr << dcmdline_options << endl;\n exit(1);\n }\n const string cmd = (*conf)[\"command\"].as<string>();\n if (commands.count(cmd) == 0) {\n cerr << \"Don't understand command: \" << cmd << endl;\n exit(1);\n }\n if (commands[cmd]->RequiresTwoOperands()) {\n if (conf->count(\"input_2\") == 0) {\n cerr << \"Command '\" << cmd << \"' requires two alignment files\\n\";\n exit(1);\n }\n if ((*conf)[\"input_1\"].as<string>() == \"-\" && (*conf)[\"input_2\"].as<string>() == \"-\") {\n cerr << \"Both inputs STDIN, reading PAIRS of lines\\n\";\n }\n } else {\n if (conf->count(\"input_2\") != 0) {\n cerr << \"Command '\" << cmd << \"' requires only one alignment file\\n\";\n exit(1);\n }\n }\n}\n\ntemplate<class C> static void AddCommand() {\n C* c = new C;\n commands[c->Name()].reset(c);\n}\n\nint main(int argc, char **argv) {\n AddCommand<ConvertCommand>();\n AddCommand<DisplayCommand>();\n AddCommand<InvertCommand>();\n AddCommand<IntersectCommand>();\n AddCommand<UnionCommand>();\n AddCommand<GDCommand>();\n AddCommand<GDFCommand>();\n AddCommand<GDFACommand>();\n AddCommand<FMeasureCommand>();\n po::variables_map conf;\n InitCommandLine(argc, argv, &conf);\n Command& cmd = *commands[conf[\"command\"].as<string>()];\n boost::shared_ptr<ReadFile> rf1(new ReadFile(conf[\"input_1\"].as<string>()));\n boost::shared_ptr<ReadFile> rf2;\n if (cmd.RequiresTwoOperands())\n rf2.reset(new ReadFile(conf[\"input_2\"].as<string>()));\n istream* in1 = rf1->stream();\n istream* in2 = NULL;\n if (rf2) in2 = rf2->stream();\n while(*in1) {\n string line1;\n string line2;\n getline(*in1, line1);\n if (in2) {\n getline(*in2, line2);\n if ((*in1 && !*in2) || (*in2 && !*in1)) {\n cerr << \"Mismatched number of lines!\\n\";\n exit(1);\n }\n }\n if (line1.empty() && !*in1) break;\n boost::shared_ptr<Array2D<bool> > out(new Array2D<bool>);\n boost::shared_ptr<Array2D<bool> > a1 = AlignmentIO::ReadPharaohAlignmentGrid(line1);\n if (in2) {\n boost::shared_ptr<Array2D<bool> > a2 = AlignmentIO::ReadPharaohAlignmentGrid(line2);\n cmd.Apply(*a1, *a2, out.get());\n } else {\n Array2D<bool> dummy;\n cmd.Apply(*a1, dummy, out.get());\n }\n \n if (cmd.Result() == 1) {\n AlignmentIO::SerializePharaohFormat(*out, &cout);\n }\n }\n if (cmd.Result() == 2)\n cmd.Summary();\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS sdk02 (1.1.32); FILE MERGED 2003\/05\/28 12:48:37 np 1.1.32.1: #108925#<commit_after><|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qmlostplugin.h\"\n#include \"qostdevice.h\"\n\n#include <private\/qdeclarativedebugserver_p.h>\n#include <private\/qpacketprotocol_p.h>\n\nQT_BEGIN_NAMESPACE\n\nstatic const TInt KQmlOstProtocolId = 0x94;\n\nclass QmlOstPluginPrivate {\npublic:\n QmlOstPluginPrivate();\n\n QOstDevice *ost;\n QPacketProtocol *protocol;\n QDeclarativeDebugServer *debugServer;\n};\n\nQmlOstPluginPrivate::QmlOstPluginPrivate() :\n ost(0),\n protocol(0),\n debugServer(0)\n{\n}\n\nQmlOstPlugin::QmlOstPlugin() :\n d_ptr(new QmlOstPluginPrivate)\n{\n}\n\nQmlOstPlugin::~QmlOstPlugin()\n{\n delete d_ptr;\n}\n\nvoid QmlOstPlugin::setServer(QDeclarativeDebugServer *server)\n{\n Q_D(QmlOstPlugin);\n d->debugServer = server;\n}\n\nbool QmlOstPlugin::isConnected() const\n{\n Q_D(const QmlOstPlugin);\n return d->ost && d->ost->isOpen();\n}\n\nvoid QmlOstPlugin::send(const QByteArray &message)\n{\n Q_D(QmlOstPlugin);\n\n if (!isConnected())\n return;\n\n QPacket pack;\n pack.writeRawData(message.data(), message.length());\n\n d->protocol->send(pack);\n \/\/d->socket->flush();\n}\n\nvoid QmlOstPlugin::disconnect()\n{\n Q_D(QmlOstPlugin);\n\n delete d->protocol;\n d->protocol = 0;\n}\n\nvoid QmlOstPlugin::waitForMessage()\n{\n Q_D(QmlOstPlugin);\n d->protocol->waitForReadyRead(-1);\n}\n\nvoid QmlOstPlugin::setPort(int port, bool block)\n{\n Q_UNUSED(port);\n Q_UNUSED(block);\n\n Q_D(QmlOstPlugin);\n\n d->ost = new QOstDevice(this);\n bool ok = d->ost->open(KQmlOstProtocolId);\n if (!ok) {\n if (d->ost->errorString().length())\n qDebug(\"Error from QOstDevice: %s\", qPrintable(d->ost->errorString()));\n qWarning(\"QDeclarativeDebugServer: Unable to listen on OST\"); \/\/ This message is part of the signalling - do not change the format!\n return;\n }\n d->protocol = new QPacketProtocol(d->ost, this);\n QObject::connect(d->protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));\n qWarning(\"QDeclarativeDebugServer: Waiting for connection via OST\"); \/\/ This message is part of the signalling - do not change the format!\n}\n\nvoid QmlOstPlugin::readyRead()\n{\n Q_D(QmlOstPlugin);\n QPacket packet = d->protocol->read();\n\n QByteArray content = packet.data();\n d->debugServer->receiveMessage(content);\n}\n\nQ_EXPORT_PLUGIN2(qmlostplugin, QmlOstPlugin)\n\nQT_END_NAMESPACE\n<commit_msg>QmlDebug: Fix QmlOstPlugin compilation failure<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qmlostplugin.h\"\n#include \"qostdevice.h\"\n\n#include <private\/qdeclarativedebugserver_p.h>\n#include <private\/qpacketprotocol_p.h>\n\nQT_BEGIN_NAMESPACE\n\nstatic const TInt KQmlOstProtocolId = 0x94;\n\nclass QmlOstPluginPrivate {\npublic:\n QmlOstPluginPrivate();\n\n QOstDevice *ost;\n QPacketProtocol *protocol;\n QDeclarativeDebugServer *debugServer;\n};\n\nQmlOstPluginPrivate::QmlOstPluginPrivate() :\n ost(0),\n protocol(0),\n debugServer(0)\n{\n}\n\nQmlOstPlugin::QmlOstPlugin() :\n d_ptr(new QmlOstPluginPrivate)\n{\n}\n\nQmlOstPlugin::~QmlOstPlugin()\n{\n delete d_ptr;\n}\n\nvoid QmlOstPlugin::setServer(QDeclarativeDebugServer *server)\n{\n Q_D(QmlOstPlugin);\n d->debugServer = server;\n}\n\nbool QmlOstPlugin::isConnected() const\n{\n Q_D(const QmlOstPlugin);\n return d->ost && d->ost->isOpen();\n}\n\nvoid QmlOstPlugin::send(const QByteArray &message)\n{\n Q_D(QmlOstPlugin);\n\n if (!isConnected())\n return;\n\n QPacket pack;\n pack.writeRawData(message.data(), message.length());\n\n d->protocol->send(pack);\n \/\/d->socket->flush();\n}\n\nvoid QmlOstPlugin::disconnect()\n{\n Q_D(QmlOstPlugin);\n\n delete d->protocol;\n d->protocol = 0;\n}\n\nbool QmlOstPlugin::waitForMessage()\n{\n Q_D(QmlOstPlugin);\n return d->protocol->waitForReadyRead(-1);\n}\n\nvoid QmlOstPlugin::setPort(int port, bool block)\n{\n Q_UNUSED(port);\n Q_UNUSED(block);\n\n Q_D(QmlOstPlugin);\n\n d->ost = new QOstDevice(this);\n bool ok = d->ost->open(KQmlOstProtocolId);\n if (!ok) {\n if (d->ost->errorString().length())\n qDebug(\"Error from QOstDevice: %s\", qPrintable(d->ost->errorString()));\n qWarning(\"QDeclarativeDebugServer: Unable to listen on OST\"); \/\/ This message is part of the signalling - do not change the format!\n return;\n }\n d->protocol = new QPacketProtocol(d->ost, this);\n QObject::connect(d->protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));\n qWarning(\"QDeclarativeDebugServer: Waiting for connection via OST\"); \/\/ This message is part of the signalling - do not change the format!\n}\n\nvoid QmlOstPlugin::readyRead()\n{\n Q_D(QmlOstPlugin);\n QPacket packet = d->protocol->read();\n\n QByteArray content = packet.data();\n d->debugServer->receiveMessage(content);\n}\n\nQ_EXPORT_PLUGIN2(qmlostplugin, QmlOstPlugin)\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ COMBINE support tests\n\/\/==============================================================================\n\n#include \"..\/..\/..\/..\/tests\/src\/testsutils.h\"\n\n\/\/==============================================================================\n\n#include \"combinearchive.h\"\n#include \"corecliutils.h\"\n#include \"tests.h\"\n\n\/\/==============================================================================\n\n#include <QtTest\/QtTest>\n\n\/\/==============================================================================\n\n#include <QXmlSchema>\n#include <QZipReader>\n\n\/\/==============================================================================\n\nvoid dummyMessageHandler(QtMsgType pType, const QMessageLogContext &pContext,\n const QString &pMessage)\n{\n Q_UNUSED(pType);\n Q_UNUSED(pContext);\n Q_UNUSED(pMessage);\n}\n\n\/\/==============================================================================\n\nvoid Tests::initTestCase()\n{\n \/\/ Quick trick to prevent warnings from Qt\n \/\/ Note: indeed, to call CombineArchive::load() calls Core::validXml(),\n \/\/ which creates a QXmlSchema object. The first time a QXmlSchema\n \/\/ object is created, Qt generates some warnings about the current\n \/\/ thread not being the object's thread and therefore not being able\n \/\/ to move to the target thread. We clearly have nothing to do with\n \/\/ those warnings and, if anything, they just pollute our test output,\n \/\/ so...\n\n qInstallMessageHandler(dummyMessageHandler);\n\n QXmlSchema schema;\n\n Q_UNUSED(schema);\n\n qInstallMessageHandler(0);\n\n \/\/ Create a simple COMBINE archive that contains various files\n\n mCombineArchive = new OpenCOR::COMBINESupport::CombineArchive(OpenCOR::Core::temporaryFileName(), true);\n\n int counter = 0;\n\n for (int i = 1; i <= 3; ++i) {\n for (int j = 1; j <= 3; ++j, ++counter) {\n mCombineArchive->addFile(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/dir0%1\/file0%2.txt\").arg(QString::number(i), QString::number(j)),\n QString(\"dir0%1\/file0%2.txt\").arg(QString::number(i), QString::number(j)),\n OpenCOR::COMBINESupport::CombineArchiveFile::Format(1+counter%5),\n !(counter%2));\n }\n }\n}\n\n\/\/==============================================================================\n\nvoid Tests::cleanupTestCase()\n{\n \/\/ Clean up after ourselves\n\n QFile::remove(mCombineArchive->fileName());\n\n \/\/ Delete some internal objects\n\n delete mCombineArchive;\n}\n\n\/\/==============================================================================\n\nvoid Tests::doBasicTests(const QString &pFileName)\n{\n \/\/ Save the given COMBINE archive to the given file\n\n QString fileName = pFileName.isEmpty()?mCombineArchive->fileName():pFileName;\n\n mCombineArchive->save(fileName);\n\n QVERIFY(QFile::exists(fileName));\n\n \/\/ Unzip our COMBINE archive and make sure that its manifest is correct and\n \/\/ that the various files are present\n\n OpenCOR::ZIPSupport::QZipReader zipReader(fileName);\n QTemporaryDir temporaryDir;\n\n QVERIFY(zipReader.extractAll(temporaryDir.path()));\n\n QCOMPARE(OpenCOR::fileContents(temporaryDir.path()+QDir::separator()+\"manifest.xml\"),\n OpenCOR::fileContents(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/manifest.xml\")));\n\n for (int i = 1; i <= 3; ++i) {\n for (int j = 1; j <= 3; ++j)\n QVERIFY(QFile::exists(temporaryDir.path()+QDir::separator()+QString(\"dir0%1\/file0%2.txt\").arg(QString::number(i), QString::number(j))));\n }\n}\n\n\/\/==============================================================================\n\nvoid Tests::basicTests()\n{\n \/\/ Some basic tests to save our COMBINE archive either directly or to a\n \/\/ different file and checking that its contents is sound\n\n QString otherFileName = OpenCOR::Core::temporaryFileName();\n\n doBasicTests();\n doBasicTests(otherFileName);\n\n \/\/ Check that we can load our other COMBINE archive and save it in yet\n \/\/ another file, and make sure that the SHA-1 of the two files is the same\n\n OpenCOR::COMBINESupport::CombineArchive otherCombineArchive(otherFileName);\n\n QString yetAnotherFileName = OpenCOR::Core::temporaryFileName();\n\n QVERIFY(otherCombineArchive.load());\n QVERIFY(otherCombineArchive.isValid());\n QVERIFY(otherCombineArchive.save(yetAnotherFileName));\n\n QByteArray otherFileContents;\n QByteArray yetAnotherFileContents;\n\n QVERIFY(OpenCOR::Core::readFileContentsFromFile(otherFileName, otherFileContents));\n QVERIFY(OpenCOR::Core::readFileContentsFromFile(yetAnotherFileName, yetAnotherFileContents));\n\n QCOMPARE(OpenCOR::Core::sha1(otherFileContents),\n OpenCOR::Core::sha1(yetAnotherFileContents));\n\n \/\/ Clean up after ourselves\n\n QFile::remove(otherFileName);\n QFile::remove(yetAnotherFileName);\n}\n\n\/\/==============================================================================\n\nvoid Tests::loadingErrorTests()\n{\n \/\/ Try to load a non-existent COMBINE archive\n\n OpenCOR::COMBINESupport::CombineArchive combineArchive(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/nonexistent.omex\"));\n\n QVERIFY(!combineArchive.load());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the archive does not exist\"));\n\n \/\/ Try to load a non-signed COMBINE archive\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/notsigned.omex\"));\n\n QVERIFY(!combineArchive.reload());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the archive is not signed\"));\n\n \/\/ Try to load a badly signed COMBINE archive\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/badlysigned.omex\"));\n\n QVERIFY(!combineArchive.reload());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the archive does not have the correct signature\"));\n\n \/\/ Try to load a COMBINE archive with no manifest\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/nomanifest.omex\"));\n\n QVERIFY(combineArchive.reload());\n QVERIFY(!combineArchive.isValid());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the archive does not have a manifest\"));\n\n \/\/ Try to load a COMBINE archive which manifest is not a valid OMEX file\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/notvalidomex.omex\"));\n\n QVERIFY(combineArchive.reload());\n QVERIFY(!combineArchive.isValid());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the manifest is not a valid OMEX file\"));\n\n \/\/ Try to load a COMBINE archive that contains a non-existent file\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/nonexistentfile.omex\"));\n\n QVERIFY(combineArchive.reload());\n QVERIFY(!combineArchive.isValid());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"<strong>nonexistentfile.txt<\/strong> could not be found\"));\n\n \/\/ Try to load a COMBINE archive which manifest doesn't reference the\n \/\/ COMBINE archive itself\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/nocombinearchivereference.omex\"));\n\n QVERIFY(combineArchive.reload());\n QVERIFY(!combineArchive.isValid());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"no reference to the COMBINE archive itself could be found\"));\n}\n\n\/\/==============================================================================\n\nQTEST_GUILESS_MAIN(Tests)\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Some minor cleaning up [ci skip].<commit_after>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ COMBINE support tests\n\/\/==============================================================================\n\n#include \"..\/..\/..\/..\/tests\/src\/testsutils.h\"\n\n\/\/==============================================================================\n\n#include \"combinearchive.h\"\n#include \"corecliutils.h\"\n#include \"tests.h\"\n\n\/\/==============================================================================\n\n#include <QtTest\/QtTest>\n\n\/\/==============================================================================\n\n#include <QXmlSchema>\n#include <QZipReader>\n\n\/\/==============================================================================\n\nvoid dummyMessageHandler(QtMsgType pType, const QMessageLogContext &pContext,\n const QString &pMessage)\n{\n Q_UNUSED(pType);\n Q_UNUSED(pContext);\n Q_UNUSED(pMessage);\n}\n\n\/\/==============================================================================\n\nvoid Tests::initTestCase()\n{\n \/\/ Quick trick to prevent warnings from Qt\n \/\/ Note: indeed, to call CombineArchive::load() calls Core::validXml(),\n \/\/ which creates a QXmlSchema object. The first time a QXmlSchema\n \/\/ object is created, Qt generates some warnings about the current\n \/\/ thread not being the object's thread and therefore not being able\n \/\/ to move to the target thread. We clearly have nothing to do with\n \/\/ those warnings and, if anything, they just pollute our test output,\n \/\/ so...\n\nqInstallMessageHandler(dummyMessageHandler);\n QXmlSchema schema;\nqInstallMessageHandler(0);\n\n Q_UNUSED(schema);\n\n \/\/ Create a simple COMBINE archive that contains various files\n\n mCombineArchive = new OpenCOR::COMBINESupport::CombineArchive(OpenCOR::Core::temporaryFileName(), true);\n\n int counter = 0;\n\n for (int i = 1; i <= 3; ++i) {\n for (int j = 1; j <= 3; ++j, ++counter) {\n mCombineArchive->addFile(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/dir0%1\/file0%2.txt\").arg(QString::number(i), QString::number(j)),\n QString(\"dir0%1\/file0%2.txt\").arg(QString::number(i), QString::number(j)),\n OpenCOR::COMBINESupport::CombineArchiveFile::Format(1+counter%5),\n !(counter%2));\n }\n }\n}\n\n\/\/==============================================================================\n\nvoid Tests::cleanupTestCase()\n{\n \/\/ Clean up after ourselves\n\n QFile::remove(mCombineArchive->fileName());\n\n \/\/ Delete some internal objects\n\n delete mCombineArchive;\n}\n\n\/\/==============================================================================\n\nvoid Tests::doBasicTests(const QString &pFileName)\n{\n \/\/ Save the given COMBINE archive to the given file\n\n QString fileName = pFileName.isEmpty()?mCombineArchive->fileName():pFileName;\n\n mCombineArchive->save(fileName);\n\n QVERIFY(QFile::exists(fileName));\n\n \/\/ Unzip our COMBINE archive and make sure that its manifest is correct and\n \/\/ that the various files are present\n\n OpenCOR::ZIPSupport::QZipReader zipReader(fileName);\n QTemporaryDir temporaryDir;\n\n QVERIFY(zipReader.extractAll(temporaryDir.path()));\n\n QCOMPARE(OpenCOR::fileContents(temporaryDir.path()+QDir::separator()+\"manifest.xml\"),\n OpenCOR::fileContents(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/manifest.xml\")));\n\n for (int i = 1; i <= 3; ++i) {\n for (int j = 1; j <= 3; ++j)\n QVERIFY(QFile::exists(temporaryDir.path()+QDir::separator()+QString(\"dir0%1\/file0%2.txt\").arg(QString::number(i), QString::number(j))));\n }\n}\n\n\/\/==============================================================================\n\nvoid Tests::basicTests()\n{\n \/\/ Some basic tests to save our COMBINE archive either directly or to a\n \/\/ different file and checking that its contents is sound\n\n QString otherFileName = OpenCOR::Core::temporaryFileName();\n\n doBasicTests();\n doBasicTests(otherFileName);\n\n \/\/ Check that we can load our other COMBINE archive and save it in yet\n \/\/ another file, and make sure that the SHA-1 of the two files is the same\n\n OpenCOR::COMBINESupport::CombineArchive otherCombineArchive(otherFileName);\n\n QString yetAnotherFileName = OpenCOR::Core::temporaryFileName();\n\n QVERIFY(otherCombineArchive.load());\n QVERIFY(otherCombineArchive.isValid());\n QVERIFY(otherCombineArchive.save(yetAnotherFileName));\n\n QByteArray otherFileContents;\n QByteArray yetAnotherFileContents;\n\n QVERIFY(OpenCOR::Core::readFileContentsFromFile(otherFileName, otherFileContents));\n QVERIFY(OpenCOR::Core::readFileContentsFromFile(yetAnotherFileName, yetAnotherFileContents));\n\n QCOMPARE(OpenCOR::Core::sha1(otherFileContents),\n OpenCOR::Core::sha1(yetAnotherFileContents));\n\n \/\/ Clean up after ourselves\n\n QFile::remove(otherFileName);\n QFile::remove(yetAnotherFileName);\n}\n\n\/\/==============================================================================\n\nvoid Tests::loadingErrorTests()\n{\n \/\/ Try to load a non-existent COMBINE archive\n\n OpenCOR::COMBINESupport::CombineArchive combineArchive(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/nonexistent.omex\"));\n\n QVERIFY(!combineArchive.load());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the archive does not exist\"));\n\n \/\/ Try to load a non-signed COMBINE archive\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/notsigned.omex\"));\n\n QVERIFY(!combineArchive.reload());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the archive is not signed\"));\n\n \/\/ Try to load a badly signed COMBINE archive\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/badlysigned.omex\"));\n\n QVERIFY(!combineArchive.reload());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the archive does not have the correct signature\"));\n\n \/\/ Try to load a COMBINE archive with no manifest\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/nomanifest.omex\"));\n\n QVERIFY(combineArchive.reload());\n QVERIFY(!combineArchive.isValid());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the archive does not have a manifest\"));\n\n \/\/ Try to load a COMBINE archive which manifest is not a valid OMEX file\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/notvalidomex.omex\"));\n\n QVERIFY(combineArchive.reload());\n QVERIFY(!combineArchive.isValid());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"the manifest is not a valid OMEX file\"));\n\n \/\/ Try to load a COMBINE archive that contains a non-existent file\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/nonexistentfile.omex\"));\n\n QVERIFY(combineArchive.reload());\n QVERIFY(!combineArchive.isValid());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"<strong>nonexistentfile.txt<\/strong> could not be found\"));\n\n \/\/ Try to load a COMBINE archive which manifest doesn't reference the\n \/\/ COMBINE archive itself\n\n combineArchive.setFileName(OpenCOR::fileName(\"src\/plugins\/support\/COMBINESupport\/tests\/data\/nocombinearchivereference.omex\"));\n\n QVERIFY(combineArchive.reload());\n QVERIFY(!combineArchive.isValid());\n QVERIFY(combineArchive.issues().count() == 1);\n QCOMPARE(combineArchive.issues().first().message(), QString(\"no reference to the COMBINE archive itself could be found\"));\n}\n\n\/\/==============================================================================\n\nQTEST_GUILESS_MAIN(Tests)\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/framework.h\"\n\nvoid ZeroTest(lc3::sim & sim)\n{\n \/\/ Setup\n for(uint32_t i = 0x7f50; i < 0x8050; i += 1) {\n sim.setPC(0x3000);\n sim.setMem(0x4000, i);\n sim.setMem(0x4001, 0x8000);\n\n \/\/ Run\n sim.setRunInstLimit(1000);\n sim.run();\n\n \/\/ Verify\n if(i >= 0x8010) {\n VERIFY(sim.getMem(0x3200) == 0x8000);\n } else {\n VERIFY(sim.getMem(0x3200) == 0x0000);\n }\n }\n}\n\nvoid testBringup(lc3::sim & sim) { }\n\nvoid testTeardown(lc3::sim & sim) { }\n\nvoid setup(void)\n{\n REGISTER_TEST(Zero, ZeroTest, 70);\n}\n<commit_msg>[grader] Update s18_lab1 grader<commit_after>#include \"..\/framework.h\"\n\nvoid Helper(lc3::sim & sim, uint32_t a, uint32_t b)\n{\n sim.setPC(0x3000);\n sim.setMem(0x4000, a);\n sim.setMem(0x4001, b);\n}\n\nvoid SimpleTest(lc3::sim & sim)\n{\n \/\/ Setup\n Helper(sim, 0x0000, 0x0000);\n\n \/\/ Run\n sim.setRunInstLimit(2000);\n sim.run();\n\n \/\/ Verify\n VERIFY(sim.getMem(0x3200) == 0x0000);\n}\n\nvoid ExampleTest1(lc3::sim & sim)\n{\n \/\/ Setup\n Helper(sim, 0x8000, 0x8000);\n\n \/\/ Run\n sim.setRunInstLimit(2000);\n sim.run();\n\n \/\/ Verify\n VERIFY(sim.getMem(0x3200) == 0x8000);\n}\n\nvoid ExampleTest2(lc3::sim & sim)\n{\n \/\/ Setup\n Helper(sim, 0x1234, 0x5678);\n\n \/\/ Run\n sim.setRunInstLimit(2000);\n sim.run();\n\n \/\/ Verify\n VERIFY(sim.getMem(0x3200) == 0x0000);\n}\n\nvoid PositiveTest(lc3::sim & sim)\n{\n \/\/ Setup\n Helper(sim, 0x7FFF, 0x7FFF);\n\n \/\/ Run\n sim.setRunInstLimit(2000);\n sim.run();\n\n \/\/ Verify\n VERIFY(sim.getMem(0x3200) == 0x8000);\n}\n\nvoid NegativeTest(lc3::sim & sim)\n{\n \/\/ Setup\n Helper(sim, 0x8000, 0xFFFF);\n\n \/\/ Run\n sim.setRunInstLimit(2000);\n sim.run();\n\n \/\/ Verify\n VERIFY(sim.getMem(0x3200) == 0x8000);\n}\n\nvoid All_Ones_Test(lc3::sim & sim)\n{\n \/\/ Setup\n Helper(sim, 0xFFFF, 0xFFFF);\n\n \/\/ Run\n sim.setRunInstLimit(2000);\n sim.run();\n\n \/\/ Verify\n VERIFY(sim.getMem(0x3200) == 0x0000);\n}\n\nvoid Add_One_Test(lc3::sim & sim)\n{\n \/\/ Setup\n Helper(sim, 0x7FFF, 0x0001);\n\n \/\/ Run\n sim.setRunInstLimit(2000);\n sim.run();\n\n \/\/ Verify\n VERIFY(sim.getMem(0x3200) == 0x8000);\n}\n\nvoid Sub_One_Test(lc3::sim & sim)\n{\n \/\/ Setup\n Helper(sim, 0x7FFF, 0xFFFF);\n\n \/\/ Run\n sim.setRunInstLimit(2000);\n sim.run();\n\n \/\/ Verify\n VERIFY(sim.getMem(0x3200) == 0x0000);\n}\n\nvoid testBringup(lc3::sim & sim) { }\n\nvoid testTeardown(lc3::sim & sim) { }\n\nvoid setup(void)\n{\n REGISTER_TEST(Zero_Case, SimpleTest, 5);\n REGISTER_RANDOM_TEST(Zero_Case_Random, SimpleTest, 5);\n REGISTER_TEST(Example1, ExampleTest1, 10);\n REGISTER_RANDOM_TEST(Example1_Random, ExampleTest1, 10);\n REGISTER_TEST(Example2, ExampleTest2, 10);\n REGISTER_RANDOM_TEST(Example2_Random, ExampleTest2, 10);\n REGISTER_TEST(Positive_Overflow,PositiveTest, 5);\n REGISTER_RANDOM_TEST(Positive_Overflow__Random, PositiveTest, 5);\n REGISTER_TEST(Negative_Overflow,NegativeTest, 5);\n REGISTER_RANDOM_TEST(Negative_Overflow_Random, NegativeTest, 5);\n REGISTER_TEST(All_Ones,All_Ones_Test, 5);\n REGISTER_RANDOM_TEST(All_Ones_Random, All_Ones_Test, 5);\n REGISTER_TEST(Add_One,Add_One_Test, 5);\n REGISTER_RANDOM_TEST(Add_One_Random, Add_One_Test, 5);\n REGISTER_TEST(Sub_One,Sub_One_Test, 5);\n REGISTER_RANDOM_TEST(Sub_One_Random, Sub_One_Test, 5);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @cond ___LICENSE___\n *\n * Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.\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 * @endcond\n *\/\n\n#include \"common\/environment.h\"\n#include \"common\/directory.h\"\n#include \"common\/path.h\"\n\n#include \"preproc\/env.h\"\n\n#include \"api\/console.h\"\n\n#include \"config.h\"\n\n#if OS_IS_WINDOWS\n# include <windows.h>\n#else\n# include <unistd.h>\n#endif\n\nnamespace Path\n{\n std::string Get( const std::string &path, Type type \/*= Type::Game *\/ )\n {\n std::string from;\n bool resolve = true;\n\n switch ( type )\n {\n case Path::Type::Program:\n from = Path::GetProgramDirectory();\n break;\n\n case Path::Type::Data:\n from = Path::GetProgramDataDirectory();\n break;\n\n case Path::Type::SharedData:\n from = Path::GetProgramSharedDataDirectory();\n break;\n\n case Path::Type::Temp:\n from = Path::GetProgramTempDirectory();\n break;\n\n case Path::Type::Editor:\n from = Path::GetProgramDirectory();\n break;\n\n case Path::Type::None:\n resolve = false;\n break;\n }\n\n return resolve ? Path::ResolveRelative( from, path ) : path;\n }\n\n std::string ResolveRelative( const std::string &from, const std::string &to, bool sameRoot \/*= true *\/ )\n {\n if ( sameRoot )\n {\n \/\/ Just add the relative path to the from path an normalise :)\n return Canonical( FixStyle( boost::filesystem::path( from ).parent_path().generic_string() ) + to );\n }\n else\n {\n \/\/ Cheers - http:\/\/stackoverflow.com\/questions\/10167382\/boostfilesystem-get-relative-path\n\n boost::filesystem::path fsFrom, fsTo, result;\n\n fsFrom = boost::filesystem::absolute( from ).parent_path();\n fsTo = boost::filesystem::absolute( to );\n\n boost::filesystem::path::const_iterator itrFrom( fsFrom.begin() ), itrTo( fsTo.begin() );\n\n \/\/ Find common base\n \/\/\/ @todo itrTo != toEnd always true\n for ( boost::filesystem::path::const_iterator toEnd( fsTo.end() ), fromEnd( fsFrom.end() ) ;\n itrTo != toEnd && itrFrom != fromEnd && *itrFrom == *itrTo; ++itrFrom, ++itrTo );\n\n \/\/ Navigate backwards in directory to reach previously found base\n for ( boost::filesystem::path::const_iterator fromEnd( fsFrom.end() ); itrFrom != fromEnd; ++itrFrom )\n {\n if ( ( *itrFrom ) != \".\" )\n {\n result \/= \"..\";\n }\n }\n\n \/\/ Now navigate down the directory branch\n for ( ; itrTo != fsTo.end() ; ++itrTo )\n {\n result \/= *itrTo;\n }\n\n return Canonical( result.generic_string() );\n }\n }\n\n\n std::string FixStyle( const std::string &filePath )\n {\n const boost::filesystem::path path( filePath );\n std::string newPath = path.generic_string();\n\n if ( !( path.has_stem() && path.has_extension() ) )\n {\n if ( path.empty() || newPath.back() != '\/' )\n {\n newPath += '\/';\n }\n }\n\n#if !(OS_IS_WINDOWS)\n std::replace( newPath.begin(), newPath.end(), L'\\\\', L'\/' );\n#endif\n return newPath;\n }\n\n std::string Canonical( const std::string &path, bool absolute \/*= false *\/ )\n {\n if ( ( path == \".\" || path == \".\/\" ) && !absolute )\n {\n return path;\n }\n\n \/\/ Again Cheers - http:\/\/stackoverflow.com\/questions\/1746136\/how-do-i-normalize-a-pathname-using-boostfilesystem\n boost::filesystem::path fsPath( path );\n\n if ( absolute )\n {\n fsPath = boost::filesystem::absolute( fsPath );\n }\n\n boost::filesystem::path result;\n\n for ( auto it = fsPath.begin(), end = fsPath.end(); it != end; ++it )\n {\n const std::string part = it->generic_string();\n\n if ( part == \"..\" )\n {\n if ( result.filename() == \"..\" )\n {\n result \/= *it;\n }\n else\n {\n if ( result != \"\" )\n {\n result = result.parent_path();\n }\n else\n {\n result \/= \"..\";\n }\n }\n }\n else if ( part == \".\" )\n {\n \/\/ Ignore\n }\n else\n {\n \/\/ Just cat other path entries\n result \/= *it;\n }\n }\n\n return FixStyle( result.generic_string() );\n }\n\n bool IsParent( const std::string &from, const std::string &to )\n {\n const std::string canFrom = Canonical( from, true );\n const std::string canTo = Canonical( to, true );\n const std::string relative = Canonical( canFrom + ResolveRelative( canFrom, canTo, false ), true );\n\n return relative.find( canFrom ) == 0;\n }\n\n std::string GetFileName( const std::string &path, const bool stripExtension \/*= false *\/ )\n {\n const boost::filesystem::path fsPath( path );\n std::string filename;\n\n if ( !stripExtension )\n {\n filename = fsPath.filename().generic_string();\n }\n else\n {\n filename = fsPath.stem().generic_string();\n }\n\n return filename;\n }\n\n std::string GetDirectory( const std::string &path )\n {\n return FixStyle( boost::filesystem::path( path ).parent_path().generic_string() );\n }\n\n std::string GetExtension( const std::string &filepath, const bool addDot \/*= false *\/ )\n {\n const std::string fullExtension = boost::filesystem::path( filepath ).extension().generic_string();\n\n return addDot || fullExtension == \"\" ? fullExtension : fullExtension.substr( 1 );\n }\n\n bool HasExtension( const std::string &filepath )\n {\n return boost::filesystem::path( filepath ).has_extension();\n }\n\n std::string GetUniqueFileName( const std::string &extension \/*= \".tmp\" *\/ )\n {\n return FixStyle( boost::filesystem::unique_path( \"%%%%-%%%%-%%%%-%%%%\" + extension ).generic_string() );\n }\n\n std::string GetUniqueDirectory()\n {\n return FixStyle( boost::filesystem::unique_path( \"%%%%-%%%%-%%%%\" ).generic_string() );\n }\n\n std::string GetTempDirectory()\n {\n return FixStyle( boost::filesystem::temp_directory_path().generic_string() );\n }\n\n std::string GetExeDirectory()\n {\n return FixStyle( boost::filesystem::path( GetExeFile() ).parent_path().generic_string() );\n }\n\n std::string GetExeFile()\n {\n#if OS_IS_WINDOWS\n char result[ MAX_PATH ];\n return Canonical( std::string( result, GetModuleFileNameA( nullptr, result, MAX_PATH ) ) );\n#elif OS_IS_LINUX\n char result[ PATH_MAX ];\n size_t count = readlink( \"\/proc\/self\/exe\", result, PATH_MAX );\n return std::string( result, ( count > 0 ) ? count : 0 );\n#else\n#error\n#endif\n }\n\n std::string GetDataDirectory()\n {\n#if OS_IS_WINDOWS\n return FixStyle( Environment::GetVariable( \"APPDATA\" ) );\n#elif OS_IS_LINUX\n return FixStyle( \"~\/local\/share\/\" );\n#elif OS_IS_MACOS\n return \"~\/Library\/Application Support\/\";\n#endif\n }\n\n std::string GetSharedDataDirectory()\n {\n#if OS_IS_WINDOWS\n return FixStyle( Environment::GetVariable( \"ALLUSERSPROFILE\" ) );\n#elif OS_IS_LINUX\n return \"\/usr\/local\/\";\n#elif OS_IS_MACOS\n return \"\/usr\/local\/\";\n#endif\n }\n\n std::string GetProgramDirectory()\n {\n return GetExeDirectory();\n }\n\n std::string GetProgramTempDirectory()\n {\n return String::Format( \"%s%s\/%s\/\", GetTempDirectory(), std::string( PROGRAM_COMPANY ), std::string( PROGRAM_NAME ) );\n }\n\n std::string GetProgramDataDirectory()\n {\n return String::Format( \"%s%s\/%s\/\", GetDataDirectory(), std::string( PROGRAM_COMPANY ), std::string( PROGRAM_NAME ) );\n }\n\n std::string GetProgramSharedDataDirectory()\n {\n return String::Format( \"%s%s\/%s\/\", GetSharedDataDirectory(),\n std::string( PROGRAM_COMPANY ),\n std::string( PROGRAM_NAME ) );\n }\n\n std::vector< boost::filesystem::path > List( const std::string &directory, bool recursive \/*= false *\/ )\n {\n std::vector< boost::filesystem::path > contents;\n\n if ( !Directory::Exists( directory ) )\n {\n return contents;\n }\n\n if ( recursive )\n {\n boost::filesystem::recursive_directory_iterator it( directory ), end;\n\n for ( ; it != end; ++it )\n {\n contents.push_back( *it );\n }\n }\n else\n {\n boost::filesystem::directory_iterator it( directory ), end;\n\n for ( ; it != end; ++it )\n {\n contents.push_back( *it );\n }\n }\n\n return contents;\n }\n\n std::vector< std::string > ListContent( const std::string &directory, bool recursive \/*= false *\/ )\n {\n const std::vector< boost::filesystem::path > contents = List( directory, recursive );\n std::vector< std::string > result;\n result.reserve( contents.size() );\n\n for ( auto it = contents.begin(), end = contents.end(); it != end; ++it )\n {\n result.push_back( FixStyle( it->generic_string() ) );\n }\n\n return result;\n }\n\n std::string GetWorkingDirectory()\n {\n return Path::FixStyle( boost::filesystem::current_path().generic_string() );\n }\n\n bool SetWorkingDirectory( const std::string &workingDirectory )\n {\n bool success = true;\n\n try\n {\n boost::filesystem::current_path( workingDirectory );\n }\n catch ( boost::filesystem::filesystem_error & )\n {\n success = false;\n }\n\n return success;\n }\n\n void DeleteAll( const std::string &path )\n {\n boost::filesystem::remove_all( path );\n }\n\n}<commit_msg>Windows to linux paths<commit_after>\/**\n * @cond ___LICENSE___\n *\n * Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.\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 * @endcond\n *\/\n\n#include \"common\/environment.h\"\n#include \"common\/directory.h\"\n#include \"common\/path.h\"\n\n#include \"preproc\/env.h\"\n\n#include \"api\/console.h\"\n\n#include \"config.h\"\n\n#if OS_IS_WINDOWS\n# include <windows.h>\n#else\n# include <unistd.h>\n#endif\n\nnamespace Path\n{\n std::string Get( const std::string &path, Type type \/*= Type::Game *\/ )\n {\n std::string from;\n bool resolve = true;\n\n switch ( type )\n {\n case Path::Type::Program:\n from = Path::GetProgramDirectory();\n break;\n\n case Path::Type::Data:\n from = Path::GetProgramDataDirectory();\n break;\n\n case Path::Type::SharedData:\n from = Path::GetProgramSharedDataDirectory();\n break;\n\n case Path::Type::Temp:\n from = Path::GetProgramTempDirectory();\n break;\n\n case Path::Type::Editor:\n from = Path::GetProgramDirectory();\n break;\n\n case Path::Type::None:\n resolve = false;\n break;\n }\n\n return resolve ? Path::ResolveRelative( from, path ) : path;\n }\n\n std::string ResolveRelative( const std::string &from, const std::string &to, bool sameRoot \/*= true *\/ )\n {\n if ( sameRoot )\n {\n \/\/ Just add the relative path to the from path an normalise :)\n return Canonical( FixStyle( boost::filesystem::path( from ).parent_path().generic_string() ) + to );\n }\n else\n {\n \/\/ Cheers - http:\/\/stackoverflow.com\/questions\/10167382\/boostfilesystem-get-relative-path\n\n boost::filesystem::path fsFrom, fsTo, result;\n\n fsFrom = boost::filesystem::absolute( from ).parent_path();\n fsTo = boost::filesystem::absolute( to );\n\n boost::filesystem::path::const_iterator itrFrom( fsFrom.begin() ), itrTo( fsTo.begin() );\n\n \/\/ Find common base\n \/\/\/ @todo itrTo != toEnd always true\n for ( boost::filesystem::path::const_iterator toEnd( fsTo.end() ), fromEnd( fsFrom.end() ) ;\n itrTo != toEnd && itrFrom != fromEnd && *itrFrom == *itrTo; ++itrFrom, ++itrTo );\n\n \/\/ Navigate backwards in directory to reach previously found base\n for ( boost::filesystem::path::const_iterator fromEnd( fsFrom.end() ); itrFrom != fromEnd; ++itrFrom )\n {\n if ( ( *itrFrom ) != \".\" )\n {\n result \/= \"..\";\n }\n }\n\n \/\/ Now navigate down the directory branch\n for ( ; itrTo != fsTo.end() ; ++itrTo )\n {\n result \/= *itrTo;\n }\n\n return Canonical( result.generic_string() );\n }\n }\n\n\n std::string FixStyle( const std::string &filePath )\n {\n const boost::filesystem::path path( filePath );\n std::string newPath = path.generic_string();\n\n if ( !( path.has_stem() && path.has_extension() ) )\n {\n if ( path.empty() || newPath.back() != '\/' )\n {\n newPath += '\/';\n }\n }\n\n#if !(OS_IS_WINDOWS)\n newPath = String::Replace( newPath, \"\\\\\", \"\/\" );\n newPath = String::Replace( newPath, \"\/\/\", \"\/\" );\n#endif\n return newPath;\n }\n\n std::string Canonical( const std::string &path, bool absolute \/*= false *\/ )\n {\n if ( ( path == \".\" || path == \".\/\" ) && !absolute )\n {\n return path;\n }\n\n \/\/ Again Cheers - http:\/\/stackoverflow.com\/questions\/1746136\/how-do-i-normalize-a-pathname-using-boostfilesystem\n boost::filesystem::path fsPath( path );\n\n if ( absolute )\n {\n fsPath = boost::filesystem::absolute( fsPath );\n }\n\n boost::filesystem::path result;\n\n for ( auto it = fsPath.begin(), end = fsPath.end(); it != end; ++it )\n {\n const std::string part = it->generic_string();\n\n if ( part == \"..\" )\n {\n if ( result.filename() == \"..\" )\n {\n result \/= *it;\n }\n else\n {\n if ( result != \"\" )\n {\n result = result.parent_path();\n }\n else\n {\n result \/= \"..\";\n }\n }\n }\n else if ( part == \".\" )\n {\n \/\/ Ignore\n }\n else\n {\n \/\/ Just cat other path entries\n result \/= *it;\n }\n }\n\n return FixStyle( result.generic_string() );\n }\n\n bool IsParent( const std::string &from, const std::string &to )\n {\n const std::string canFrom = Canonical( from, true );\n const std::string canTo = Canonical( to, true );\n const std::string relative = Canonical( canFrom + ResolveRelative( canFrom, canTo, false ), true );\n\n return relative.find( canFrom ) == 0;\n }\n\n std::string GetFileName( const std::string &path, const bool stripExtension \/*= false *\/ )\n {\n const boost::filesystem::path fsPath( path );\n std::string filename;\n\n if ( !stripExtension )\n {\n filename = fsPath.filename().generic_string();\n }\n else\n {\n filename = fsPath.stem().generic_string();\n }\n\n return filename;\n }\n\n std::string GetDirectory( const std::string &path )\n {\n return FixStyle( boost::filesystem::path( path ).parent_path().generic_string() );\n }\n\n std::string GetExtension( const std::string &filepath, const bool addDot \/*= false *\/ )\n {\n const std::string fullExtension = boost::filesystem::path( filepath ).extension().generic_string();\n\n return addDot || fullExtension == \"\" ? fullExtension : fullExtension.substr( 1 );\n }\n\n bool HasExtension( const std::string &filepath )\n {\n return boost::filesystem::path( filepath ).has_extension();\n }\n\n std::string GetUniqueFileName( const std::string &extension \/*= \".tmp\" *\/ )\n {\n return FixStyle( boost::filesystem::unique_path( \"%%%%-%%%%-%%%%-%%%%\" + extension ).generic_string() );\n }\n\n std::string GetUniqueDirectory()\n {\n return FixStyle( boost::filesystem::unique_path( \"%%%%-%%%%-%%%%\" ).generic_string() );\n }\n\n std::string GetTempDirectory()\n {\n return FixStyle( boost::filesystem::temp_directory_path().generic_string() );\n }\n\n std::string GetExeDirectory()\n {\n return FixStyle( boost::filesystem::path( GetExeFile() ).parent_path().generic_string() );\n }\n\n std::string GetExeFile()\n {\n#if OS_IS_WINDOWS\n char result[ MAX_PATH ];\n return Canonical( std::string( result, GetModuleFileNameA( nullptr, result, MAX_PATH ) ) );\n#elif OS_IS_LINUX\n char result[ PATH_MAX ];\n size_t count = readlink( \"\/proc\/self\/exe\", result, PATH_MAX );\n return std::string( result, ( count > 0 ) ? count : 0 );\n#else\n#error\n#endif\n }\n\n std::string GetDataDirectory()\n {\n#if OS_IS_WINDOWS\n return FixStyle( Environment::GetVariable( \"APPDATA\" ) );\n#elif OS_IS_LINUX\n return FixStyle( \"~\/local\/share\/\" );\n#elif OS_IS_MACOS\n return \"~\/Library\/Application Support\/\";\n#endif\n }\n\n std::string GetSharedDataDirectory()\n {\n#if OS_IS_WINDOWS\n return FixStyle( Environment::GetVariable( \"ALLUSERSPROFILE\" ) );\n#elif OS_IS_LINUX\n return \"\/usr\/local\/\";\n#elif OS_IS_MACOS\n return \"\/usr\/local\/\";\n#endif\n }\n\n std::string GetProgramDirectory()\n {\n return GetExeDirectory();\n }\n\n std::string GetProgramTempDirectory()\n {\n return String::Format( \"%s%s\/%s\/\", GetTempDirectory(), std::string( PROGRAM_COMPANY ), std::string( PROGRAM_NAME ) );\n }\n\n std::string GetProgramDataDirectory()\n {\n return String::Format( \"%s%s\/%s\/\", GetDataDirectory(), std::string( PROGRAM_COMPANY ), std::string( PROGRAM_NAME ) );\n }\n\n std::string GetProgramSharedDataDirectory()\n {\n return String::Format( \"%s%s\/%s\/\", GetSharedDataDirectory(),\n std::string( PROGRAM_COMPANY ),\n std::string( PROGRAM_NAME ) );\n }\n\n std::vector< boost::filesystem::path > List( const std::string &directory, bool recursive \/*= false *\/ )\n {\n std::vector< boost::filesystem::path > contents;\n\n if ( !Directory::Exists( directory ) )\n {\n return contents;\n }\n\n if ( recursive )\n {\n boost::filesystem::recursive_directory_iterator it( directory ), end;\n\n for ( ; it != end; ++it )\n {\n contents.push_back( *it );\n }\n }\n else\n {\n boost::filesystem::directory_iterator it( directory ), end;\n\n for ( ; it != end; ++it )\n {\n contents.push_back( *it );\n }\n }\n\n return contents;\n }\n\n std::vector< std::string > ListContent( const std::string &directory, bool recursive \/*= false *\/ )\n {\n const std::vector< boost::filesystem::path > contents = List( directory, recursive );\n std::vector< std::string > result;\n result.reserve( contents.size() );\n\n for ( auto it = contents.begin(), end = contents.end(); it != end; ++it )\n {\n result.push_back( FixStyle( it->generic_string() ) );\n }\n\n return result;\n }\n\n std::string GetWorkingDirectory()\n {\n return Path::FixStyle( boost::filesystem::current_path().generic_string() );\n }\n\n bool SetWorkingDirectory( const std::string &workingDirectory )\n {\n bool success = true;\n\n try\n {\n boost::filesystem::current_path( workingDirectory );\n }\n catch ( boost::filesystem::filesystem_error & )\n {\n success = false;\n }\n\n return success;\n }\n\n void DeleteAll( const std::string &path )\n {\n boost::filesystem::remove_all( path );\n }\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ yas_cf_ref.cpp\n\/\/\n\n#include \"yas_cf_ref.h\"\n\nusing namespace yas;\n\ncf_ref_impl::cf_ref_impl() : _obj(nullptr) {\n}\n\ncf_ref_impl::cf_ref_impl(CFTypeRef const obj) : _obj(obj) {\n CFRetain(obj);\n}\n\ncf_ref_impl::cf_ref_impl(std::nullptr_t) : _obj(nullptr) {\n}\n\ncf_ref_impl::~cf_ref_impl() {\n if (_obj) {\n CFRelease(_obj);\n _obj = nullptr;\n }\n}\n\nvoid cf_ref_impl::set_object(CFTypeRef const obj) {\n std::lock_guard<std::recursive_mutex> lock(_mutex);\n if (obj) {\n CFRetain(obj);\n }\n\n if (_obj) {\n CFRelease(_obj);\n }\n\n _obj = obj;\n}\n\nvoid cf_ref_impl::move_object(CFTypeRef const obj) {\n std::lock_guard<std::recursive_mutex> lock(_mutex);\n\n if (_obj) {\n CFRelease(_obj);\n }\n\n _obj = obj;\n}\n\nCFTypeRef cf_ref_impl::object() {\n std::lock_guard<std::recursive_mutex> lock(_mutex);\n return _obj;\n}\n\nCFTypeRef cf_ref_impl::retained_object() {\n std::lock_guard<std::recursive_mutex> lock(_mutex);\n if (_obj) {\n return CFRetain(_obj);\n }\n return nullptr;\n}\n\nCFTypeRef cf_ref_impl::autoreleased_object() {\n std::lock_guard<std::recursive_mutex> lock(_mutex);\n if (_obj) {\n return CFAutorelease(CFRetain(_obj));\n }\n return nullptr;\n}\n<commit_msg>cf_ref this<commit_after>\/\/\n\/\/ yas_cf_ref.cpp\n\/\/\n\n#include \"yas_cf_ref.h\"\n\nusing namespace yas;\n\ncf_ref_impl::cf_ref_impl() : _obj(nullptr) {\n}\n\ncf_ref_impl::cf_ref_impl(CFTypeRef const obj) : _obj(obj) {\n CFRetain(obj);\n}\n\ncf_ref_impl::cf_ref_impl(std::nullptr_t) : _obj(nullptr) {\n}\n\ncf_ref_impl::~cf_ref_impl() {\n if (this->_obj) {\n CFRelease(this->_obj);\n this->_obj = nullptr;\n }\n}\n\nvoid cf_ref_impl::set_object(CFTypeRef const obj) {\n std::lock_guard<std::recursive_mutex> lock(this->_mutex);\n if (obj) {\n CFRetain(obj);\n }\n\n if (this->_obj) {\n CFRelease(this->_obj);\n }\n\n this->_obj = obj;\n}\n\nvoid cf_ref_impl::move_object(CFTypeRef const obj) {\n std::lock_guard<std::recursive_mutex> lock(this->_mutex);\n\n if (this->_obj) {\n CFRelease(this->_obj);\n }\n\n this->_obj = obj;\n}\n\nCFTypeRef cf_ref_impl::object() {\n std::lock_guard<std::recursive_mutex> lock(this->_mutex);\n return this->_obj;\n}\n\nCFTypeRef cf_ref_impl::retained_object() {\n std::lock_guard<std::recursive_mutex> lock(this->_mutex);\n if (this->_obj) {\n return CFRetain(this->_obj);\n }\n return nullptr;\n}\n\nCFTypeRef cf_ref_impl::autoreleased_object() {\n std::lock_guard<std::recursive_mutex> lock(this->_mutex);\n if (this->_obj) {\n return CFAutorelease(CFRetain(this->_obj));\n }\n return nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dlgeps.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 15:44:09 $\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_goodies.hxx\"\n#ifndef GCC\n#endif\n\n#include <tools\/ref.hxx>\n#include <vcl\/msgbox.hxx>\n#include <svtools\/FilterConfigItem.hxx>\n#include \"dlgeps.hxx\"\n#include \"dlgeps.hrc\"\n#include \"strings.hrc\"\n\n\/*************************************************************************\n|*\n|* Ctor\n|*\n\\************************************************************************\/\n\nDlgExportEPS::DlgExportEPS( FltCallDialogParameter& rPara ) :\n ModalDialog ( rPara.pWindow, ResId( DLG_EXPORT_EPS, rPara.pResMgr ) ),\n rFltCallPara ( rPara ),\n aGrpPreview ( this, ResId( GRP_PREVIEW ) ),\n aCBPreviewTiff ( this, ResId( CB_PREVIEW_TIFF ) ),\n aCBPreviewEPSI ( this, ResId( CB_PREVIEW_EPSI ) ),\n aGrpVersion ( this, ResId( GRP_VERSION ) ),\n aRBLevel1 ( this, ResId( RB_LEVEL1 ) ),\n aRBLevel2 ( this, ResId( RB_LEVEL2 ) ),\n aGrpColor ( this, ResId( GRP_COLOR ) ),\n aRBColor ( this, ResId( RB_COLOR ) ),\n aRBGrayscale ( this, ResId( RB_GRAYSCALE ) ),\n aGrpCompression ( this, ResId( GRP_COMPRESSION ) ),\n aRBCompressionLZW ( this, ResId( RB_COMPRESSION_LZW ) ),\n aRBCompressionNone ( this, ResId( RB_COMPRESSION_NONE ) ),\n aBtnOK ( this, ResId( BTN_OK ) ),\n aBtnCancel ( this, ResId( BTN_CANCEL ) ),\n aBtnHelp ( this, ResId( BTN_HELP ) ),\n pMgr ( rPara.pResMgr )\n{\n FreeResource();\n\n String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( \"Office.Common\/Filter\/Graphic\/Export\/EPS\" ) );\n pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );\n\n \/\/ Config-Parameter lesen\n String sPreview( RTL_CONSTASCII_USTRINGPARAM( \"Preview\" ) );\n String sVersion( RTL_CONSTASCII_USTRINGPARAM( \"Version\" ) );\n String sColorFormat( RTL_CONSTASCII_USTRINGPARAM( \"ColorFormat\" ) );\n String sCompressionMode( RTL_CONSTASCII_USTRINGPARAM( \"CompressionMode\" ) );\n String sTextMode( RTL_CONSTASCII_USTRINGPARAM( \"TextMode\" ) );\n\n sal_Int32 nPreview = pConfigItem->ReadInt32( sPreview, 0 );\n sal_Int32 nVersion = pConfigItem->ReadInt32( sVersion, 2 );\n sal_Int32 nColor = pConfigItem->ReadInt32( sColorFormat, 0 );\n sal_Int32 nCompr = pConfigItem->ReadInt32( sCompressionMode, 2 );\n\n \/* SJ: The following line is not superfluous, reading the item will also #106652#\n create the corresponding FilterData Property. Since all filter\n are no longer accessing the configuration itself, we have fill the\n FilterData sequence with all available configuration items *\/\n pConfigItem->ReadInt32( sTextMode, 0 );\n\n BOOL bCheck = FALSE;\n if ( nPreview & 1 )\n bCheck = TRUE;\n aCBPreviewTiff.Check( bCheck );\n if ( nPreview & 2 )\n bCheck = TRUE;\n aCBPreviewEPSI.Check( bCheck );\n\n bCheck = FALSE;\n if ( nVersion == 1 )\n bCheck ^= TRUE;\n aRBLevel1.Check( bCheck );\n bCheck ^= TRUE;\n aRBLevel2.Check( bCheck );\n\n bCheck = FALSE;\n if ( nColor == 1 )\n bCheck ^= TRUE;\n aRBColor.Check( bCheck );\n bCheck ^= TRUE;\n aRBGrayscale.Check( bCheck );\n\n bCheck = FALSE;\n if ( nCompr == 1 )\n bCheck ^= TRUE;\n aRBCompressionLZW.Check( bCheck );\n bCheck ^= TRUE;\n aRBCompressionNone.Check( bCheck );\n\n if ( aRBLevel1.IsChecked() )\n {\n aRBColor.Disable();\n aRBGrayscale.Disable();\n aRBCompressionNone.Disable();\n aRBCompressionLZW.Disable();\n aRBCompressionNone.Disable();\n }\n\n aBtnOK.SetClickHdl( LINK( this, DlgExportEPS, OK ) );\n aRBLevel1.SetClickHdl( LINK( this, DlgExportEPS, LEVEL1 ) );\n aRBLevel2.SetClickHdl( LINK( this, DlgExportEPS, LEVEL2 ) );\n}\n\nDlgExportEPS::~DlgExportEPS()\n{\n delete pConfigItem;\n}\n\n\/*************************************************************************\n|*\n|* Speichert eingestellte Werte in ini-Datei\n|*\n\\************************************************************************\/\n\nIMPL_LINK( DlgExportEPS, OK, void *, EMPTYARG )\n{\n\n \/\/ Config-Parameter schreiben\n sal_Int32 nCheck = 0;\n if ( aCBPreviewTiff.IsChecked() )\n nCheck++;\n if ( aCBPreviewEPSI.IsChecked() )\n nCheck += 2;\n\n String sPreview( RTL_CONSTASCII_USTRINGPARAM( \"Preview\" ) );\n pConfigItem->WriteInt32( sPreview, nCheck );\n\n nCheck = 1;\n if ( aRBLevel2.IsChecked() )\n nCheck++;\n String sVersion( RTL_CONSTASCII_USTRINGPARAM( \"Version\" ) );\n pConfigItem->WriteInt32( sVersion, nCheck );\n\n nCheck = 1;\n if ( aRBGrayscale.IsChecked() )\n nCheck++;\n String sColorFormat( RTL_CONSTASCII_USTRINGPARAM( \"ColorFormat\" ) );\n pConfigItem->WriteInt32( sColorFormat, nCheck );\n\n nCheck = 1;\n if ( aRBCompressionNone.IsChecked() )\n nCheck++;\n String sCompressionMode( RTL_CONSTASCII_USTRINGPARAM( \"CompressionMode\" ) );\n pConfigItem->WriteInt32( sCompressionMode, nCheck );\n\n rFltCallPara.aFilterData = pConfigItem->GetFilterData();\n EndDialog( RET_OK );\n\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( DlgExportEPS, LEVEL1, void*, EMPTYARG )\n{\n if ( aRBLevel1.IsChecked() )\n {\n aRBColor.Disable();\n aRBGrayscale.Disable();\n aRBCompressionLZW.Disable();\n aRBCompressionNone.Disable();\n }\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( DlgExportEPS, LEVEL2, void*, EMPTYARG )\n{\n if ( aRBLevel2.IsChecked() )\n {\n aRBColor.Enable();\n aRBGrayscale.Enable();\n aRBCompressionLZW.Enable();\n aRBCompressionNone.Enable();\n }\n return 0;\n}\n<commit_msg>INTEGRATION: CWS residcleanup (1.12.72); FILE MERGED 2007\/02\/18 19:58:11 pl 1.12.72.1: #i74635# get rid of implicit global ResMgr<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dlgeps.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2007-04-26 10:01:18 $\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_goodies.hxx\"\n#ifndef GCC\n#endif\n\n#include <tools\/ref.hxx>\n#include <vcl\/msgbox.hxx>\n#include <svtools\/FilterConfigItem.hxx>\n#include \"dlgeps.hxx\"\n#include \"dlgeps.hrc\"\n#include \"strings.hrc\"\n\n\/*************************************************************************\n|*\n|* Ctor\n|*\n\\************************************************************************\/\n\nDlgExportEPS::DlgExportEPS( FltCallDialogParameter& rPara ) :\n ModalDialog ( rPara.pWindow, ResId( DLG_EXPORT_EPS, *rPara.pResMgr ) ),\n rFltCallPara ( rPara ),\n aGrpPreview ( this, ResId( GRP_PREVIEW, *rPara.pResMgr ) ),\n aCBPreviewTiff ( this, ResId( CB_PREVIEW_TIFF, *rPara.pResMgr ) ),\n aCBPreviewEPSI ( this, ResId( CB_PREVIEW_EPSI, *rPara.pResMgr ) ),\n aGrpVersion ( this, ResId( GRP_VERSION, *rPara.pResMgr ) ),\n aRBLevel1 ( this, ResId( RB_LEVEL1, *rPara.pResMgr ) ),\n aRBLevel2 ( this, ResId( RB_LEVEL2, *rPara.pResMgr ) ),\n aGrpColor ( this, ResId( GRP_COLOR, *rPara.pResMgr ) ),\n aRBColor ( this, ResId( RB_COLOR, *rPara.pResMgr ) ),\n aRBGrayscale ( this, ResId( RB_GRAYSCALE, *rPara.pResMgr ) ),\n aGrpCompression ( this, ResId( GRP_COMPRESSION, *rPara.pResMgr ) ),\n aRBCompressionLZW ( this, ResId( RB_COMPRESSION_LZW, *rPara.pResMgr ) ),\n aRBCompressionNone ( this, ResId( RB_COMPRESSION_NONE, *rPara.pResMgr ) ),\n aBtnOK ( this, ResId( BTN_OK, *rPara.pResMgr ) ),\n aBtnCancel ( this, ResId( BTN_CANCEL, *rPara.pResMgr ) ),\n aBtnHelp ( this, ResId( BTN_HELP, *rPara.pResMgr ) ),\n pMgr ( rPara.pResMgr )\n{\n FreeResource();\n\n String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( \"Office.Common\/Filter\/Graphic\/Export\/EPS\" ) );\n pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );\n\n \/\/ Config-Parameter lesen\n String sPreview( RTL_CONSTASCII_USTRINGPARAM( \"Preview\" ) );\n String sVersion( RTL_CONSTASCII_USTRINGPARAM( \"Version\" ) );\n String sColorFormat( RTL_CONSTASCII_USTRINGPARAM( \"ColorFormat\" ) );\n String sCompressionMode( RTL_CONSTASCII_USTRINGPARAM( \"CompressionMode\" ) );\n String sTextMode( RTL_CONSTASCII_USTRINGPARAM( \"TextMode\" ) );\n\n sal_Int32 nPreview = pConfigItem->ReadInt32( sPreview, 0 );\n sal_Int32 nVersion = pConfigItem->ReadInt32( sVersion, 2 );\n sal_Int32 nColor = pConfigItem->ReadInt32( sColorFormat, 0 );\n sal_Int32 nCompr = pConfigItem->ReadInt32( sCompressionMode, 2 );\n\n \/* SJ: The following line is not superfluous, reading the item will also #106652#\n create the corresponding FilterData Property. Since all filter\n are no longer accessing the configuration itself, we have fill the\n FilterData sequence with all available configuration items *\/\n pConfigItem->ReadInt32( sTextMode, 0 );\n\n BOOL bCheck = FALSE;\n if ( nPreview & 1 )\n bCheck = TRUE;\n aCBPreviewTiff.Check( bCheck );\n if ( nPreview & 2 )\n bCheck = TRUE;\n aCBPreviewEPSI.Check( bCheck );\n\n bCheck = FALSE;\n if ( nVersion == 1 )\n bCheck ^= TRUE;\n aRBLevel1.Check( bCheck );\n bCheck ^= TRUE;\n aRBLevel2.Check( bCheck );\n\n bCheck = FALSE;\n if ( nColor == 1 )\n bCheck ^= TRUE;\n aRBColor.Check( bCheck );\n bCheck ^= TRUE;\n aRBGrayscale.Check( bCheck );\n\n bCheck = FALSE;\n if ( nCompr == 1 )\n bCheck ^= TRUE;\n aRBCompressionLZW.Check( bCheck );\n bCheck ^= TRUE;\n aRBCompressionNone.Check( bCheck );\n\n if ( aRBLevel1.IsChecked() )\n {\n aRBColor.Disable();\n aRBGrayscale.Disable();\n aRBCompressionNone.Disable();\n aRBCompressionLZW.Disable();\n aRBCompressionNone.Disable();\n }\n\n aBtnOK.SetClickHdl( LINK( this, DlgExportEPS, OK ) );\n aRBLevel1.SetClickHdl( LINK( this, DlgExportEPS, LEVEL1 ) );\n aRBLevel2.SetClickHdl( LINK( this, DlgExportEPS, LEVEL2 ) );\n}\n\nDlgExportEPS::~DlgExportEPS()\n{\n delete pConfigItem;\n}\n\n\/*************************************************************************\n|*\n|* Speichert eingestellte Werte in ini-Datei\n|*\n\\************************************************************************\/\n\nIMPL_LINK( DlgExportEPS, OK, void *, EMPTYARG )\n{\n\n \/\/ Config-Parameter schreiben\n sal_Int32 nCheck = 0;\n if ( aCBPreviewTiff.IsChecked() )\n nCheck++;\n if ( aCBPreviewEPSI.IsChecked() )\n nCheck += 2;\n\n String sPreview( RTL_CONSTASCII_USTRINGPARAM( \"Preview\" ) );\n pConfigItem->WriteInt32( sPreview, nCheck );\n\n nCheck = 1;\n if ( aRBLevel2.IsChecked() )\n nCheck++;\n String sVersion( RTL_CONSTASCII_USTRINGPARAM( \"Version\" ) );\n pConfigItem->WriteInt32( sVersion, nCheck );\n\n nCheck = 1;\n if ( aRBGrayscale.IsChecked() )\n nCheck++;\n String sColorFormat( RTL_CONSTASCII_USTRINGPARAM( \"ColorFormat\" ) );\n pConfigItem->WriteInt32( sColorFormat, nCheck );\n\n nCheck = 1;\n if ( aRBCompressionNone.IsChecked() )\n nCheck++;\n String sCompressionMode( RTL_CONSTASCII_USTRINGPARAM( \"CompressionMode\" ) );\n pConfigItem->WriteInt32( sCompressionMode, nCheck );\n\n rFltCallPara.aFilterData = pConfigItem->GetFilterData();\n EndDialog( RET_OK );\n\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( DlgExportEPS, LEVEL1, void*, EMPTYARG )\n{\n if ( aRBLevel1.IsChecked() )\n {\n aRBColor.Disable();\n aRBGrayscale.Disable();\n aRBCompressionLZW.Disable();\n aRBCompressionNone.Disable();\n }\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( DlgExportEPS, LEVEL2, void*, EMPTYARG )\n{\n if ( aRBLevel2.IsChecked() )\n {\n aRBColor.Enable();\n aRBGrayscale.Enable();\n aRBCompressionLZW.Enable();\n aRBCompressionNone.Enable();\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2017 gRPC authors.\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\/* Test out pollset latencies *\/\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/useful.h>\n\nextern \"C\" {\n#include \"src\/core\/lib\/iomgr\/ev_posix.h\"\n#include \"src\/core\/lib\/iomgr\/pollset.h\"\n#include \"src\/core\/lib\/iomgr\/port.h\"\n#include \"src\/core\/lib\/iomgr\/wakeup_fd_posix.h\"\n}\n\n#include \"test\/cpp\/microbenchmarks\/helpers.h\"\n#include \"third_party\/benchmark\/include\/benchmark\/benchmark.h\"\n\n#include <string.h>\n\n#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL\n#include <sys\/epoll.h>\n#include <sys\/eventfd.h>\n#include <unistd.h>\n#endif\n\nauto& force_library_initialization = Library::get();\n\nstatic void shutdown_ps(grpc_exec_ctx* exec_ctx, void* ps, grpc_error* error) {\n grpc_pollset_destroy(exec_ctx, static_cast<grpc_pollset*>(ps));\n}\n\nstatic void BM_CreateDestroyPollset(benchmark::State& state) {\n TrackCounters track_counters;\n size_t ps_sz = grpc_pollset_size();\n grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_malloc(ps_sz));\n gpr_mu* mu;\n grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;\n grpc_closure shutdown_ps_closure;\n GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,\n grpc_schedule_on_exec_ctx);\n while (state.KeepRunning()) {\n memset(ps, 0, ps_sz);\n grpc_pollset_init(ps, &mu);\n gpr_mu_lock(mu);\n grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);\n gpr_mu_unlock(mu);\n grpc_exec_ctx_flush(&exec_ctx);\n }\n grpc_exec_ctx_finish(&exec_ctx);\n gpr_free(ps);\n track_counters.Finish(state);\n}\nBENCHMARK(BM_CreateDestroyPollset);\n\n#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL\nstatic void BM_PollEmptyPollset_SpeedOfLight(benchmark::State& state) {\n \/\/ equivalent to BM_PollEmptyPollset, but just use the OS primitives to guage\n \/\/ what the speed of light would be if we abstracted perfectly\n TrackCounters track_counters;\n int epfd = epoll_create1(0);\n GPR_ASSERT(epfd != -1);\n size_t nev = state.range(0);\n size_t nfd = state.range(1);\n epoll_event* ev = new epoll_event[nev];\n std::vector<int> fds;\n for (size_t i = 0; i < nfd; i++) {\n fds.push_back(eventfd(0, 0));\n epoll_event ev;\n ev.events = EPOLLIN;\n epoll_ctl(epfd, EPOLL_CTL_ADD, fds.back(), &ev);\n }\n while (state.KeepRunning()) {\n epoll_wait(epfd, ev, nev, 0);\n }\n for (auto fd : fds) {\n close(fd);\n }\n close(epfd);\n delete[] ev;\n track_counters.Finish(state);\n}\nBENCHMARK(BM_PollEmptyPollset_SpeedOfLight)\n ->Args({1, 0})\n ->Args({1, 1})\n ->Args({1, 10})\n ->Args({1, 100})\n ->Args({1, 1000})\n ->Args({1, 10000})\n ->Args({1, 100000})\n ->Args({10, 1})\n ->Args({100, 1})\n ->Args({1000, 1});\n#endif\n\nstatic void BM_PollEmptyPollset(benchmark::State& state) {\n TrackCounters track_counters;\n size_t ps_sz = grpc_pollset_size();\n grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));\n gpr_mu* mu;\n grpc_pollset_init(ps, &mu);\n grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;\n gpr_timespec now = gpr_time_0(GPR_CLOCK_MONOTONIC);\n gpr_timespec deadline = gpr_inf_past(GPR_CLOCK_MONOTONIC);\n gpr_mu_lock(mu);\n while (state.KeepRunning()) {\n GRPC_ERROR_UNREF(grpc_pollset_work(&exec_ctx, ps, NULL, now, deadline));\n }\n grpc_closure shutdown_ps_closure;\n GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,\n grpc_schedule_on_exec_ctx);\n grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);\n gpr_mu_unlock(mu);\n grpc_exec_ctx_finish(&exec_ctx);\n gpr_free(ps);\n track_counters.Finish(state);\n}\nBENCHMARK(BM_PollEmptyPollset);\n\nstatic void BM_PollAddFd(benchmark::State& state) {\n TrackCounters track_counters;\n size_t ps_sz = grpc_pollset_size();\n grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));\n gpr_mu* mu;\n grpc_pollset_init(ps, &mu);\n grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;\n grpc_wakeup_fd wakeup_fd;\n GPR_ASSERT(\n GRPC_LOG_IF_ERROR(\"wakeup_fd_init\", grpc_wakeup_fd_init(&wakeup_fd)));\n grpc_fd* fd = grpc_fd_create(wakeup_fd.read_fd, \"xxx\");\n while (state.KeepRunning()) {\n grpc_pollset_add_fd(&exec_ctx, ps, fd);\n grpc_exec_ctx_flush(&exec_ctx);\n }\n grpc_fd_orphan(&exec_ctx, fd, NULL, NULL, \"xxx\");\n grpc_closure shutdown_ps_closure;\n GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,\n grpc_schedule_on_exec_ctx);\n gpr_mu_lock(mu);\n grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);\n gpr_mu_unlock(mu);\n grpc_exec_ctx_finish(&exec_ctx);\n gpr_free(ps);\n track_counters.Finish(state);\n}\nBENCHMARK(BM_PollAddFd);\n\nclass Closure : public grpc_closure {\n public:\n virtual ~Closure() {}\n};\n\ntemplate <class F>\nClosure* MakeClosure(F f, grpc_closure_scheduler* scheduler) {\n struct C : public Closure {\n C(F f, grpc_closure_scheduler* scheduler) : f_(f) {\n GRPC_CLOSURE_INIT(this, C::cbfn, this, scheduler);\n }\n static void cbfn(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) {\n C* p = static_cast<C*>(arg);\n p->f_();\n }\n F f_;\n };\n return new C(f, scheduler);\n}\n\n#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL\nstatic void BM_SingleThreadPollOneFd_SpeedOfLight(benchmark::State& state) {\n \/\/ equivalent to BM_PollEmptyPollset, but just use the OS primitives to guage\n \/\/ what the speed of light would be if we abstracted perfectly\n TrackCounters track_counters;\n int epfd = epoll_create1(0);\n GPR_ASSERT(epfd != -1);\n epoll_event ev[100];\n int fd = eventfd(0, EFD_NONBLOCK);\n ev[0].events = EPOLLIN;\n epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev[0]);\n while (state.KeepRunning()) {\n int err;\n do {\n err = eventfd_write(fd, 1);\n } while (err < 0 && errno == EINTR);\n GPR_ASSERT(err == 0);\n do {\n err = epoll_wait(epfd, ev, GPR_ARRAY_SIZE(ev), 0);\n } while (err < 0 && errno == EINTR);\n GPR_ASSERT(err == 1);\n eventfd_t value;\n do {\n err = eventfd_read(fd, &value);\n } while (err < 0 && errno == EINTR);\n GPR_ASSERT(err == 0);\n }\n close(fd);\n close(epfd);\n track_counters.Finish(state);\n}\nBENCHMARK(BM_SingleThreadPollOneFd_SpeedOfLight);\n#endif\n\nstatic void BM_SingleThreadPollOneFd(benchmark::State& state) {\n TrackCounters track_counters;\n size_t ps_sz = grpc_pollset_size();\n grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));\n gpr_mu* mu;\n grpc_pollset_init(ps, &mu);\n grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;\n gpr_timespec now = gpr_time_0(GPR_CLOCK_MONOTONIC);\n gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);\n grpc_wakeup_fd wakeup_fd;\n GRPC_ERROR_UNREF(grpc_wakeup_fd_init(&wakeup_fd));\n grpc_fd* wakeup = grpc_fd_create(wakeup_fd.read_fd, \"wakeup_read\");\n grpc_pollset_add_fd(&exec_ctx, ps, wakeup);\n bool done = false;\n Closure* continue_closure = MakeClosure(\n [&]() {\n GRPC_ERROR_UNREF(grpc_wakeup_fd_consume_wakeup(&wakeup_fd));\n if (!state.KeepRunning()) {\n done = true;\n return;\n }\n GRPC_ERROR_UNREF(grpc_wakeup_fd_wakeup(&wakeup_fd));\n grpc_fd_notify_on_read(&exec_ctx, wakeup, continue_closure);\n },\n grpc_schedule_on_exec_ctx);\n GRPC_ERROR_UNREF(grpc_wakeup_fd_wakeup(&wakeup_fd));\n grpc_fd_notify_on_read(&exec_ctx, wakeup, continue_closure);\n gpr_mu_lock(mu);\n while (!done) {\n GRPC_ERROR_UNREF(grpc_pollset_work(&exec_ctx, ps, NULL, now, deadline));\n }\n grpc_fd_orphan(&exec_ctx, wakeup, NULL, NULL, \"done\");\n wakeup_fd.read_fd = 0;\n grpc_closure shutdown_ps_closure;\n GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,\n grpc_schedule_on_exec_ctx);\n grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);\n gpr_mu_unlock(mu);\n grpc_exec_ctx_finish(&exec_ctx);\n grpc_wakeup_fd_destroy(&wakeup_fd);\n gpr_free(ps);\n track_counters.Finish(state);\n delete continue_closure;\n}\nBENCHMARK(BM_SingleThreadPollOneFd);\n\nBENCHMARK_MAIN();\n<commit_msg>Update bm_pollset with the fd_orphan change<commit_after>\/*\n *\n * Copyright 2017 gRPC authors.\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\/* Test out pollset latencies *\/\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/useful.h>\n\nextern \"C\" {\n#include \"src\/core\/lib\/iomgr\/ev_posix.h\"\n#include \"src\/core\/lib\/iomgr\/pollset.h\"\n#include \"src\/core\/lib\/iomgr\/port.h\"\n#include \"src\/core\/lib\/iomgr\/wakeup_fd_posix.h\"\n}\n\n#include \"test\/cpp\/microbenchmarks\/helpers.h\"\n#include \"third_party\/benchmark\/include\/benchmark\/benchmark.h\"\n\n#include <string.h>\n\n#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL\n#include <sys\/epoll.h>\n#include <sys\/eventfd.h>\n#include <unistd.h>\n#endif\n\nauto& force_library_initialization = Library::get();\n\nstatic void shutdown_ps(grpc_exec_ctx* exec_ctx, void* ps, grpc_error* error) {\n grpc_pollset_destroy(exec_ctx, static_cast<grpc_pollset*>(ps));\n}\n\nstatic void BM_CreateDestroyPollset(benchmark::State& state) {\n TrackCounters track_counters;\n size_t ps_sz = grpc_pollset_size();\n grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_malloc(ps_sz));\n gpr_mu* mu;\n grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;\n grpc_closure shutdown_ps_closure;\n GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,\n grpc_schedule_on_exec_ctx);\n while (state.KeepRunning()) {\n memset(ps, 0, ps_sz);\n grpc_pollset_init(ps, &mu);\n gpr_mu_lock(mu);\n grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);\n gpr_mu_unlock(mu);\n grpc_exec_ctx_flush(&exec_ctx);\n }\n grpc_exec_ctx_finish(&exec_ctx);\n gpr_free(ps);\n track_counters.Finish(state);\n}\nBENCHMARK(BM_CreateDestroyPollset);\n\n#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL\nstatic void BM_PollEmptyPollset_SpeedOfLight(benchmark::State& state) {\n \/\/ equivalent to BM_PollEmptyPollset, but just use the OS primitives to guage\n \/\/ what the speed of light would be if we abstracted perfectly\n TrackCounters track_counters;\n int epfd = epoll_create1(0);\n GPR_ASSERT(epfd != -1);\n size_t nev = state.range(0);\n size_t nfd = state.range(1);\n epoll_event* ev = new epoll_event[nev];\n std::vector<int> fds;\n for (size_t i = 0; i < nfd; i++) {\n fds.push_back(eventfd(0, 0));\n epoll_event ev;\n ev.events = EPOLLIN;\n epoll_ctl(epfd, EPOLL_CTL_ADD, fds.back(), &ev);\n }\n while (state.KeepRunning()) {\n epoll_wait(epfd, ev, nev, 0);\n }\n for (auto fd : fds) {\n close(fd);\n }\n close(epfd);\n delete[] ev;\n track_counters.Finish(state);\n}\nBENCHMARK(BM_PollEmptyPollset_SpeedOfLight)\n ->Args({1, 0})\n ->Args({1, 1})\n ->Args({1, 10})\n ->Args({1, 100})\n ->Args({1, 1000})\n ->Args({1, 10000})\n ->Args({1, 100000})\n ->Args({10, 1})\n ->Args({100, 1})\n ->Args({1000, 1});\n#endif\n\nstatic void BM_PollEmptyPollset(benchmark::State& state) {\n TrackCounters track_counters;\n size_t ps_sz = grpc_pollset_size();\n grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));\n gpr_mu* mu;\n grpc_pollset_init(ps, &mu);\n grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;\n gpr_timespec now = gpr_time_0(GPR_CLOCK_MONOTONIC);\n gpr_timespec deadline = gpr_inf_past(GPR_CLOCK_MONOTONIC);\n gpr_mu_lock(mu);\n while (state.KeepRunning()) {\n GRPC_ERROR_UNREF(grpc_pollset_work(&exec_ctx, ps, NULL, now, deadline));\n }\n grpc_closure shutdown_ps_closure;\n GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,\n grpc_schedule_on_exec_ctx);\n grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);\n gpr_mu_unlock(mu);\n grpc_exec_ctx_finish(&exec_ctx);\n gpr_free(ps);\n track_counters.Finish(state);\n}\nBENCHMARK(BM_PollEmptyPollset);\n\nstatic void BM_PollAddFd(benchmark::State& state) {\n TrackCounters track_counters;\n size_t ps_sz = grpc_pollset_size();\n grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));\n gpr_mu* mu;\n grpc_pollset_init(ps, &mu);\n grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;\n grpc_wakeup_fd wakeup_fd;\n GPR_ASSERT(\n GRPC_LOG_IF_ERROR(\"wakeup_fd_init\", grpc_wakeup_fd_init(&wakeup_fd)));\n grpc_fd* fd = grpc_fd_create(wakeup_fd.read_fd, \"xxx\");\n while (state.KeepRunning()) {\n grpc_pollset_add_fd(&exec_ctx, ps, fd);\n grpc_exec_ctx_flush(&exec_ctx);\n }\n grpc_fd_orphan(&exec_ctx, fd, NULL, NULL, false \/* already_closed *\/, \"xxx\");\n grpc_closure shutdown_ps_closure;\n GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,\n grpc_schedule_on_exec_ctx);\n gpr_mu_lock(mu);\n grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);\n gpr_mu_unlock(mu);\n grpc_exec_ctx_finish(&exec_ctx);\n gpr_free(ps);\n track_counters.Finish(state);\n}\nBENCHMARK(BM_PollAddFd);\n\nclass Closure : public grpc_closure {\n public:\n virtual ~Closure() {}\n};\n\ntemplate <class F>\nClosure* MakeClosure(F f, grpc_closure_scheduler* scheduler) {\n struct C : public Closure {\n C(F f, grpc_closure_scheduler* scheduler) : f_(f) {\n GRPC_CLOSURE_INIT(this, C::cbfn, this, scheduler);\n }\n static void cbfn(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) {\n C* p = static_cast<C*>(arg);\n p->f_();\n }\n F f_;\n };\n return new C(f, scheduler);\n}\n\n#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL\nstatic void BM_SingleThreadPollOneFd_SpeedOfLight(benchmark::State& state) {\n \/\/ equivalent to BM_PollEmptyPollset, but just use the OS primitives to guage\n \/\/ what the speed of light would be if we abstracted perfectly\n TrackCounters track_counters;\n int epfd = epoll_create1(0);\n GPR_ASSERT(epfd != -1);\n epoll_event ev[100];\n int fd = eventfd(0, EFD_NONBLOCK);\n ev[0].events = EPOLLIN;\n epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev[0]);\n while (state.KeepRunning()) {\n int err;\n do {\n err = eventfd_write(fd, 1);\n } while (err < 0 && errno == EINTR);\n GPR_ASSERT(err == 0);\n do {\n err = epoll_wait(epfd, ev, GPR_ARRAY_SIZE(ev), 0);\n } while (err < 0 && errno == EINTR);\n GPR_ASSERT(err == 1);\n eventfd_t value;\n do {\n err = eventfd_read(fd, &value);\n } while (err < 0 && errno == EINTR);\n GPR_ASSERT(err == 0);\n }\n close(fd);\n close(epfd);\n track_counters.Finish(state);\n}\nBENCHMARK(BM_SingleThreadPollOneFd_SpeedOfLight);\n#endif\n\nstatic void BM_SingleThreadPollOneFd(benchmark::State& state) {\n TrackCounters track_counters;\n size_t ps_sz = grpc_pollset_size();\n grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));\n gpr_mu* mu;\n grpc_pollset_init(ps, &mu);\n grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;\n gpr_timespec now = gpr_time_0(GPR_CLOCK_MONOTONIC);\n gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);\n grpc_wakeup_fd wakeup_fd;\n GRPC_ERROR_UNREF(grpc_wakeup_fd_init(&wakeup_fd));\n grpc_fd* wakeup = grpc_fd_create(wakeup_fd.read_fd, \"wakeup_read\");\n grpc_pollset_add_fd(&exec_ctx, ps, wakeup);\n bool done = false;\n Closure* continue_closure = MakeClosure(\n [&]() {\n GRPC_ERROR_UNREF(grpc_wakeup_fd_consume_wakeup(&wakeup_fd));\n if (!state.KeepRunning()) {\n done = true;\n return;\n }\n GRPC_ERROR_UNREF(grpc_wakeup_fd_wakeup(&wakeup_fd));\n grpc_fd_notify_on_read(&exec_ctx, wakeup, continue_closure);\n },\n grpc_schedule_on_exec_ctx);\n GRPC_ERROR_UNREF(grpc_wakeup_fd_wakeup(&wakeup_fd));\n grpc_fd_notify_on_read(&exec_ctx, wakeup, continue_closure);\n gpr_mu_lock(mu);\n while (!done) {\n GRPC_ERROR_UNREF(grpc_pollset_work(&exec_ctx, ps, NULL, now, deadline));\n }\n grpc_fd_orphan(&exec_ctx, wakeup, NULL, NULL, false \/* already_closed *\/,\n \"done\");\n wakeup_fd.read_fd = 0;\n grpc_closure shutdown_ps_closure;\n GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,\n grpc_schedule_on_exec_ctx);\n grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);\n gpr_mu_unlock(mu);\n grpc_exec_ctx_finish(&exec_ctx);\n grpc_wakeup_fd_destroy(&wakeup_fd);\n gpr_free(ps);\n track_counters.Finish(state);\n delete continue_closure;\n}\nBENCHMARK(BM_SingleThreadPollOneFd);\n\nBENCHMARK_MAIN();\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\tThis file is part of qpOASES.\n *\n *\tqpOASES -- An Implementation of the Online Active Set Strategy.\n *\tCopyright (C) 2007-2014 by Hans Joachim Ferreau, Andreas Potschka,\n *\tChristian Kirches et al. All rights reserved.\n *\n *\tqpOASES is free software; you can redistribute it and\/or\n *\tmodify it under the terms of the GNU Lesser General Public\n *\tLicense as published by the Free Software Foundation; either\n *\tversion 2.1 of the License, or (at your option) any later version.\n *\n *\tqpOASES is distributed in the hope that it will be useful,\n *\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n *\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\tSee the GNU Lesser General Public License for more details.\n *\n *\tYou should have received a copy of the GNU Lesser General Public\n *\tLicense along with qpOASES; if not, write to the Free Software\n *\tFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n\n\/**\n *\t\\file testing\/cpp\/test_bench.cpp\n *\t\\author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau\n *\t\\version 3.0\n *\t\\date 2010-2014\n *\n *\tUnit test running all benchmark examples stored in problems directory.\n *\/\n\n\n\n#include <dirent.h>\n#include <cstring>\n#include <cstdlib>\n#include <qpOASES.hpp>\n#include <qpOASES\/UnitTesting.hpp>\n\n\n\/** Run benchmark examples. *\/\nint main( int argc, char *argv[] )\n{\n\tUSING_NAMESPACE_QPOASES\n\n\t\/* 1) Define benchmark arguments. *\/\n\tBooleanType isSparse = BT_FALSE;\n\t\/\/BooleanType isSparse = BT_TRUE;\n\tOptions options;\n \toptions.setToDefault();\n\t\/\/options.setToMPC();\n\t\/\/options.setToReliable();\n\t\/\/options.printLevel = PL_LOW;\n\t\/\/options.printLevel = PL_MEDIUM;\n\toptions.printLevel = PL_TABULAR;\n\n\n\tint nWSR;\n\treal_t maxCPUtime; \/* seconds *\/\n\treal_t maxStationarity = 0.0, maxFeasibility = 0.0, maxComplementarity = 0.0;\n\n\tchar OQPproblem[MAX_STRING_LENGTH];\n\tchar problem[] = \"HS268\";\n\treturnValue returnvalue;\n\n\t\n\t\/* 3) Run benchmark. *\/\n\tfprintf(stdFile, \"%-10s \", problem);\n\tfflush(stdFile);\n\n\tsnprintf(OQPproblem, MAX_STRING_LENGTH, \"..\/testing\/cpp\/data\/problems\/%s\/\", problem);\n\tmaxCPUtime = 100.0;\n\tnWSR = 100;\n\n\treturnvalue = runOQPbenchmark(\tOQPproblem, isSparse, options,\n\t\t\t\t\t\t\t\t\tnWSR, maxCPUtime, maxStationarity, maxFeasibility, maxComplementarity \n\t\t\t\t\t\t\t\t\t);\n\n\tprintf( \"\\n\" );\n\tprintf( \"stat: %e\\n\", maxStationarity );\n\tprintf( \"feas: %e\\n\", maxFeasibility );\n\tprintf( \"cmpl: %e\\n\", maxComplementarity );\n\n\tQPOASES_TEST_FOR_TOL( maxStationarity, 1e-11 );\n\tQPOASES_TEST_FOR_TOL( maxFeasibility, 1e-14 );\n\tQPOASES_TEST_FOR_TOL( maxComplementarity, 1e-14 );\n\n\n\treturn 0;\n}\n\n\n\/*\n *\tend of file\n *\/\n<commit_msg>added a check for 'returnvalue' in test_hs268<commit_after>\/*\n *\tThis file is part of qpOASES.\n *\n *\tqpOASES -- An Implementation of the Online Active Set Strategy.\n *\tCopyright (C) 2007-2014 by Hans Joachim Ferreau, Andreas Potschka,\n *\tChristian Kirches et al. All rights reserved.\n *\n *\tqpOASES is free software; you can redistribute it and\/or\n *\tmodify it under the terms of the GNU Lesser General Public\n *\tLicense as published by the Free Software Foundation; either\n *\tversion 2.1 of the License, or (at your option) any later version.\n *\n *\tqpOASES is distributed in the hope that it will be useful,\n *\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n *\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\tSee the GNU Lesser General Public License for more details.\n *\n *\tYou should have received a copy of the GNU Lesser General Public\n *\tLicense along with qpOASES; if not, write to the Free Software\n *\tFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n\n\/**\n *\t\\file testing\/cpp\/test_bench.cpp\n *\t\\author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau\n *\t\\version 3.0\n *\t\\date 2010-2014\n *\n *\tUnit test running all benchmark examples stored in problems directory.\n *\/\n\n\n\n#include <dirent.h>\n#include <cstring>\n#include <cstdlib>\n#include <qpOASES.hpp>\n#include <qpOASES\/UnitTesting.hpp>\n\n\n\/** Run benchmark examples. *\/\nint main( int argc, char *argv[] )\n{\n\tUSING_NAMESPACE_QPOASES\n\n\t\/* 1) Define benchmark arguments. *\/\n\tBooleanType isSparse = BT_FALSE;\n\t\/\/BooleanType isSparse = BT_TRUE;\n\tOptions options;\n \toptions.setToDefault();\n\t\/\/options.setToMPC();\n\t\/\/options.setToReliable();\n\t\/\/options.printLevel = PL_LOW;\n\t\/\/options.printLevel = PL_MEDIUM;\n\toptions.printLevel = PL_TABULAR;\n\n\n\tint nWSR;\n\tint npass = 0;\n\treal_t maxCPUtime; \/* seconds *\/\n\treal_t maxStationarity = 0.0, maxFeasibility = 0.0, maxComplementarity = 0.0;\n\n\tchar OQPproblem[MAX_STRING_LENGTH];\n\tchar problem[] = \"HS268\";\n\treturnValue returnvalue;\n\n\t\n\t\/* 3) Run benchmark. *\/\n\tfprintf(stdFile, \"%-10s \", problem);\n\tfflush(stdFile);\n\n\tsnprintf(OQPproblem, MAX_STRING_LENGTH, \"..\/testing\/cpp\/data\/problems\/%s\/\", problem);\n\tmaxCPUtime = 100.0;\n\tnWSR = 100;\n\n\treturnvalue = runOQPbenchmark(\tOQPproblem, isSparse, options,\n\t\t\t\t\t\t\t\t\tnWSR, maxCPUtime, maxStationarity, maxFeasibility, maxComplementarity \n\t\t\t\t\t\t\t\t\t);\n\n\tif(returnvalue == SUCCESSFUL_RETURN) {\n\t\tnpass += 1;\n\t}\n\n\tQPOASES_TEST_FOR_TRUE( npass >= 1 );\n\n\tprintf( \"\\n\" );\n\tprintf( \"stat: %e\\n\", maxStationarity );\n\tprintf( \"feas: %e\\n\", maxFeasibility );\n\tprintf( \"cmpl: %e\\n\", maxComplementarity );\n\n\tQPOASES_TEST_FOR_TOL( maxStationarity, 1e-11 );\n\tQPOASES_TEST_FOR_TOL( maxFeasibility, 1e-14 );\n\tQPOASES_TEST_FOR_TOL( maxComplementarity, 1e-14 );\n\n\n\treturn 0;\n}\n\n\n\/*\n *\tend of file\n *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- AddressSanitizerRuntime.cpp -----------------------------*- C++ -*-===\/\/\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#include \"AddressSanitizerRuntime.h\"\n\n#include \"lldb\/Breakpoint\/StoppointCallbackContext.h\"\n#include \"lldb\/Core\/Debugger.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/PluginInterface.h\"\n#include \"lldb\/Core\/PluginManager.h\"\n#include \"lldb\/Core\/RegularExpression.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Core\/StreamFile.h\"\n#include \"lldb\/Core\/ValueObject.h\"\n#include \"lldb\/Expression\/UserExpression.h\"\n#include \"lldb\/Interpreter\/CommandReturnObject.h\"\n#include \"lldb\/Symbol\/Symbol.h\"\n#include \"lldb\/Target\/InstrumentationRuntimeStopInfo.h\"\n#include \"lldb\/Target\/StopInfo.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Target\/Thread.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nlldb::InstrumentationRuntimeSP\nAddressSanitizerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {\n return InstrumentationRuntimeSP(new AddressSanitizerRuntime(process_sp));\n}\n\nvoid AddressSanitizerRuntime::Initialize() {\n PluginManager::RegisterPlugin(\n GetPluginNameStatic(), \"AddressSanitizer instrumentation runtime plugin.\",\n CreateInstance, GetTypeStatic);\n}\n\nvoid AddressSanitizerRuntime::Terminate() {\n PluginManager::UnregisterPlugin(CreateInstance);\n}\n\nlldb_private::ConstString AddressSanitizerRuntime::GetPluginNameStatic() {\n return ConstString(\"AddressSanitizer\");\n}\n\nlldb::InstrumentationRuntimeType AddressSanitizerRuntime::GetTypeStatic() {\n return eInstrumentationRuntimeTypeAddressSanitizer;\n}\n\nAddressSanitizerRuntime::~AddressSanitizerRuntime() { Deactivate(); }\n\nconst RegularExpression &\nAddressSanitizerRuntime::GetPatternForRuntimeLibrary() {\n \/\/ FIXME: This shouldn't include the \"dylib\" suffix.\n static RegularExpression regex(\n llvm::StringRef(\"libclang_rt.asan_(.*)_dynamic\\\\.dylib\"));\n return regex;\n}\n\nbool AddressSanitizerRuntime::CheckIfRuntimeIsValid(\n const lldb::ModuleSP module_sp) {\n const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(\n ConstString(\"__asan_get_alloc_stack\"), lldb::eSymbolTypeAny);\n\n return symbol != nullptr;\n}\n\n#define RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC 2 * 1000 * 1000\nconst char *address_sanitizer_retrieve_report_data_prefix = R\"(\nextern \"C\"\n{\nint __asan_report_present();\nvoid *__asan_get_report_pc();\nvoid *__asan_get_report_bp();\nvoid *__asan_get_report_sp();\nvoid *__asan_get_report_address();\nconst char *__asan_get_report_description();\nint __asan_get_report_access_type();\nsize_t __asan_get_report_access_size();\n}\n)\";\n\nconst char *address_sanitizer_retrieve_report_data_command = R\"(\nstruct {\n int present;\n int access_type;\n void *pc;\n void *bp;\n void *sp;\n void *address;\n size_t access_size;\n const char *description;\n} t;\n\nt.present = __asan_report_present();\nt.access_type = __asan_get_report_access_type();\nt.pc = __asan_get_report_pc();\nt.bp = __asan_get_report_bp();\nt.sp = __asan_get_report_sp();\nt.address = __asan_get_report_address();\nt.access_size = __asan_get_report_access_size();\nt.description = __asan_get_report_description();\nt\n)\";\n\nStructuredData::ObjectSP AddressSanitizerRuntime::RetrieveReportData() {\n ProcessSP process_sp = GetProcessSP();\n if (!process_sp)\n return StructuredData::ObjectSP();\n\n ThreadSP thread_sp =\n process_sp->GetThreadList().GetExpressionExecutionThread();\n StackFrameSP frame_sp = thread_sp->GetSelectedFrame();\n\n if (!frame_sp)\n return StructuredData::ObjectSP();\n\n EvaluateExpressionOptions options;\n options.SetUnwindOnError(true);\n options.SetTryAllThreads(true);\n options.SetStopOthers(true);\n options.SetIgnoreBreakpoints(true);\n options.SetTimeoutUsec(RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC);\n options.SetPrefix(address_sanitizer_retrieve_report_data_prefix);\n options.SetAutoApplyFixIts(false);\n options.SetLanguage(eLanguageTypeObjC_plus_plus);\n\n ValueObjectSP return_value_sp;\n ExecutionContext exe_ctx;\n Error eval_error;\n frame_sp->CalculateExecutionContext(exe_ctx);\n ExpressionResults result = UserExpression::Evaluate(\n exe_ctx, options, address_sanitizer_retrieve_report_data_command, \"\",\n return_value_sp, eval_error);\n if (result != eExpressionCompleted) {\n process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(\n \"Warning: Cannot evaluate AddressSanitizer expression:\\n%s\\n\",\n eval_error.AsCString());\n return StructuredData::ObjectSP();\n }\n\n int present = return_value_sp->GetValueForExpressionPath(\".present\")\n ->GetValueAsUnsigned(0);\n if (present != 1)\n return StructuredData::ObjectSP();\n\n addr_t pc =\n return_value_sp->GetValueForExpressionPath(\".pc\")->GetValueAsUnsigned(0);\n \/* commented out because rdar:\/\/problem\/18533301\n addr_t bp =\n return_value_sp->GetValueForExpressionPath(\".bp\")->GetValueAsUnsigned(0);\n addr_t sp =\n return_value_sp->GetValueForExpressionPath(\".sp\")->GetValueAsUnsigned(0);\n *\/\n addr_t address = return_value_sp->GetValueForExpressionPath(\".address\")\n ->GetValueAsUnsigned(0);\n addr_t access_type =\n return_value_sp->GetValueForExpressionPath(\".access_type\")\n ->GetValueAsUnsigned(0);\n addr_t access_size =\n return_value_sp->GetValueForExpressionPath(\".access_size\")\n ->GetValueAsUnsigned(0);\n addr_t description_ptr =\n return_value_sp->GetValueForExpressionPath(\".description\")\n ->GetValueAsUnsigned(0);\n std::string description;\n Error error;\n process_sp->ReadCStringFromMemory(description_ptr, description, error);\n\n StructuredData::Dictionary *dict = new StructuredData::Dictionary();\n dict->AddStringItem(\"instrumentation_class\", \"AddressSanitizer\");\n dict->AddStringItem(\"stop_type\", \"fatal_error\");\n dict->AddIntegerItem(\"pc\", pc);\n \/* commented out because rdar:\/\/problem\/18533301\n dict->AddIntegerItem(\"bp\", bp);\n dict->AddIntegerItem(\"sp\", sp);\n *\/\n dict->AddIntegerItem(\"address\", address);\n dict->AddIntegerItem(\"access_type\", access_type);\n dict->AddIntegerItem(\"access_size\", access_size);\n dict->AddStringItem(\"description\", description);\n\n return StructuredData::ObjectSP(dict);\n}\n\nstd::string\nAddressSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report) {\n std::string description = report->GetAsDictionary()\n ->GetValueForKey(\"description\")\n ->GetAsString()\n ->GetValue();\n if (description == \"heap-use-after-free\") {\n return \"Use of deallocated memory detected\";\n } else if (description == \"heap-buffer-overflow\") {\n return \"Heap buffer overflow detected\";\n } else if (description == \"stack-buffer-underflow\") {\n return \"Stack buffer underflow detected\";\n } else if (description == \"initialization-order-fiasco\") {\n return \"Initialization order problem detected\";\n } else if (description == \"stack-buffer-overflow\") {\n return \"Stack buffer overflow detected\";\n } else if (description == \"stack-use-after-return\") {\n return \"Use of returned stack memory detected\";\n } else if (description == \"use-after-poison\") {\n return \"Use of poisoned memory detected\";\n } else if (description == \"container-overflow\") {\n return \"Container overflow detected\";\n } else if (description == \"stack-use-after-scope\") {\n return \"Use of out-of-scope stack memory detected\";\n } else if (description == \"global-buffer-overflow\") {\n return \"Global buffer overflow detected\";\n } else if (description == \"unknown-crash\") {\n return \"Invalid memory access detected\";\n }\n\n \/\/ for unknown report codes just show the code\n return description;\n}\n\nbool AddressSanitizerRuntime::NotifyBreakpointHit(\n void *baton, StoppointCallbackContext *context, user_id_t break_id,\n user_id_t break_loc_id) {\n assert(baton && \"null baton\");\n if (!baton)\n return false;\n\n AddressSanitizerRuntime *const instance =\n static_cast<AddressSanitizerRuntime *>(baton);\n\n StructuredData::ObjectSP report = instance->RetrieveReportData();\n std::string description;\n if (report) {\n description = instance->FormatDescription(report);\n }\n ProcessSP process_sp = instance->GetProcessSP();\n \/\/ Make sure this is the right process\n if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {\n ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();\n if (thread_sp)\n thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::\n CreateStopReasonWithInstrumentationData(\n *thread_sp, description, report));\n\n StreamFileSP stream_sp(\n process_sp->GetTarget().GetDebugger().GetOutputFile());\n if (stream_sp) {\n stream_sp->Printf(\"AddressSanitizer report breakpoint hit. Use 'thread \"\n \"info -s' to get extended information about the \"\n \"report.\\n\");\n }\n return true; \/\/ Return true to stop the target\n } else\n return false; \/\/ Let target run\n}\n\nvoid AddressSanitizerRuntime::Activate() {\n if (IsActive())\n return;\n\n ProcessSP process_sp = GetProcessSP();\n if (!process_sp)\n return;\n\n ConstString symbol_name(\"__asan::AsanDie()\");\n const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(\n symbol_name, eSymbolTypeCode);\n\n if (symbol == NULL)\n return;\n\n if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())\n return;\n\n Target &target = process_sp->GetTarget();\n addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);\n\n if (symbol_address == LLDB_INVALID_ADDRESS)\n return;\n\n bool internal = true;\n bool hardware = false;\n Breakpoint *breakpoint =\n process_sp->GetTarget()\n .CreateBreakpoint(symbol_address, internal, hardware)\n .get();\n breakpoint->SetCallback(AddressSanitizerRuntime::NotifyBreakpointHit, this,\n true);\n breakpoint->SetBreakpointKind(\"address-sanitizer-report\");\n SetBreakpointID(breakpoint->GetID());\n\n StreamFileSP stream_sp(process_sp->GetTarget().GetDebugger().GetOutputFile());\n if (stream_sp) {\n stream_sp->Printf(\"AddressSanitizer debugger support is active. Memory \"\n \"error breakpoint has been installed and you can now use \"\n \"the 'memory history' command.\\n\");\n }\n\n SetActive(true);\n}\n\nvoid AddressSanitizerRuntime::Deactivate() {\n if (GetBreakpointID() != LLDB_INVALID_BREAK_ID) {\n ProcessSP process_sp = GetProcessSP();\n if (process_sp) {\n process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());\n SetBreakpointID(LLDB_INVALID_BREAK_ID);\n }\n }\n SetActive(false);\n}\n<commit_msg>Support more report types in AddressSanitizerRuntime.cpp, re-word existing ones.<commit_after>\/\/===-- AddressSanitizerRuntime.cpp -----------------------------*- C++ -*-===\/\/\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#include \"AddressSanitizerRuntime.h\"\n\n#include \"lldb\/Breakpoint\/StoppointCallbackContext.h\"\n#include \"lldb\/Core\/Debugger.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/PluginInterface.h\"\n#include \"lldb\/Core\/PluginManager.h\"\n#include \"lldb\/Core\/RegularExpression.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Core\/StreamFile.h\"\n#include \"lldb\/Core\/ValueObject.h\"\n#include \"lldb\/Expression\/UserExpression.h\"\n#include \"lldb\/Interpreter\/CommandReturnObject.h\"\n#include \"lldb\/Symbol\/Symbol.h\"\n#include \"lldb\/Target\/InstrumentationRuntimeStopInfo.h\"\n#include \"lldb\/Target\/StopInfo.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Target\/Thread.h\"\n\n#include \"llvm\/ADT\/StringSwitch.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nlldb::InstrumentationRuntimeSP\nAddressSanitizerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {\n return InstrumentationRuntimeSP(new AddressSanitizerRuntime(process_sp));\n}\n\nvoid AddressSanitizerRuntime::Initialize() {\n PluginManager::RegisterPlugin(\n GetPluginNameStatic(), \"AddressSanitizer instrumentation runtime plugin.\",\n CreateInstance, GetTypeStatic);\n}\n\nvoid AddressSanitizerRuntime::Terminate() {\n PluginManager::UnregisterPlugin(CreateInstance);\n}\n\nlldb_private::ConstString AddressSanitizerRuntime::GetPluginNameStatic() {\n return ConstString(\"AddressSanitizer\");\n}\n\nlldb::InstrumentationRuntimeType AddressSanitizerRuntime::GetTypeStatic() {\n return eInstrumentationRuntimeTypeAddressSanitizer;\n}\n\nAddressSanitizerRuntime::~AddressSanitizerRuntime() { Deactivate(); }\n\nconst RegularExpression &\nAddressSanitizerRuntime::GetPatternForRuntimeLibrary() {\n \/\/ FIXME: This shouldn't include the \"dylib\" suffix.\n static RegularExpression regex(\n llvm::StringRef(\"libclang_rt.asan_(.*)_dynamic\\\\.dylib\"));\n return regex;\n}\n\nbool AddressSanitizerRuntime::CheckIfRuntimeIsValid(\n const lldb::ModuleSP module_sp) {\n const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(\n ConstString(\"__asan_get_alloc_stack\"), lldb::eSymbolTypeAny);\n\n return symbol != nullptr;\n}\n\n#define RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC 2 * 1000 * 1000\nconst char *address_sanitizer_retrieve_report_data_prefix = R\"(\nextern \"C\"\n{\nint __asan_report_present();\nvoid *__asan_get_report_pc();\nvoid *__asan_get_report_bp();\nvoid *__asan_get_report_sp();\nvoid *__asan_get_report_address();\nconst char *__asan_get_report_description();\nint __asan_get_report_access_type();\nsize_t __asan_get_report_access_size();\n}\n)\";\n\nconst char *address_sanitizer_retrieve_report_data_command = R\"(\nstruct {\n int present;\n int access_type;\n void *pc;\n void *bp;\n void *sp;\n void *address;\n size_t access_size;\n const char *description;\n} t;\n\nt.present = __asan_report_present();\nt.access_type = __asan_get_report_access_type();\nt.pc = __asan_get_report_pc();\nt.bp = __asan_get_report_bp();\nt.sp = __asan_get_report_sp();\nt.address = __asan_get_report_address();\nt.access_size = __asan_get_report_access_size();\nt.description = __asan_get_report_description();\nt\n)\";\n\nStructuredData::ObjectSP AddressSanitizerRuntime::RetrieveReportData() {\n ProcessSP process_sp = GetProcessSP();\n if (!process_sp)\n return StructuredData::ObjectSP();\n\n ThreadSP thread_sp =\n process_sp->GetThreadList().GetExpressionExecutionThread();\n StackFrameSP frame_sp = thread_sp->GetSelectedFrame();\n\n if (!frame_sp)\n return StructuredData::ObjectSP();\n\n EvaluateExpressionOptions options;\n options.SetUnwindOnError(true);\n options.SetTryAllThreads(true);\n options.SetStopOthers(true);\n options.SetIgnoreBreakpoints(true);\n options.SetTimeoutUsec(RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC);\n options.SetPrefix(address_sanitizer_retrieve_report_data_prefix);\n options.SetAutoApplyFixIts(false);\n options.SetLanguage(eLanguageTypeObjC_plus_plus);\n\n ValueObjectSP return_value_sp;\n ExecutionContext exe_ctx;\n Error eval_error;\n frame_sp->CalculateExecutionContext(exe_ctx);\n ExpressionResults result = UserExpression::Evaluate(\n exe_ctx, options, address_sanitizer_retrieve_report_data_command, \"\",\n return_value_sp, eval_error);\n if (result != eExpressionCompleted) {\n process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(\n \"Warning: Cannot evaluate AddressSanitizer expression:\\n%s\\n\",\n eval_error.AsCString());\n return StructuredData::ObjectSP();\n }\n\n int present = return_value_sp->GetValueForExpressionPath(\".present\")\n ->GetValueAsUnsigned(0);\n if (present != 1)\n return StructuredData::ObjectSP();\n\n addr_t pc =\n return_value_sp->GetValueForExpressionPath(\".pc\")->GetValueAsUnsigned(0);\n \/* commented out because rdar:\/\/problem\/18533301\n addr_t bp =\n return_value_sp->GetValueForExpressionPath(\".bp\")->GetValueAsUnsigned(0);\n addr_t sp =\n return_value_sp->GetValueForExpressionPath(\".sp\")->GetValueAsUnsigned(0);\n *\/\n addr_t address = return_value_sp->GetValueForExpressionPath(\".address\")\n ->GetValueAsUnsigned(0);\n addr_t access_type =\n return_value_sp->GetValueForExpressionPath(\".access_type\")\n ->GetValueAsUnsigned(0);\n addr_t access_size =\n return_value_sp->GetValueForExpressionPath(\".access_size\")\n ->GetValueAsUnsigned(0);\n addr_t description_ptr =\n return_value_sp->GetValueForExpressionPath(\".description\")\n ->GetValueAsUnsigned(0);\n std::string description;\n Error error;\n process_sp->ReadCStringFromMemory(description_ptr, description, error);\n\n StructuredData::Dictionary *dict = new StructuredData::Dictionary();\n dict->AddStringItem(\"instrumentation_class\", \"AddressSanitizer\");\n dict->AddStringItem(\"stop_type\", \"fatal_error\");\n dict->AddIntegerItem(\"pc\", pc);\n \/* commented out because rdar:\/\/problem\/18533301\n dict->AddIntegerItem(\"bp\", bp);\n dict->AddIntegerItem(\"sp\", sp);\n *\/\n dict->AddIntegerItem(\"address\", address);\n dict->AddIntegerItem(\"access_type\", access_type);\n dict->AddIntegerItem(\"access_size\", access_size);\n dict->AddStringItem(\"description\", description);\n\n return StructuredData::ObjectSP(dict);\n}\n\nstd::string\nAddressSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report) {\n std::string description = report->GetAsDictionary()\n ->GetValueForKey(\"description\")\n ->GetAsString()\n ->GetValue();\n return llvm::StringSwitch<std::string>(description)\n .Case(\"heap-use-after-free\", \"Use of deallocated memory\")\n .Case(\"heap-buffer-overflow\", \"Heap buffer overflow\")\n .Case(\"stack-buffer-underflow\", \"Stack buffer underflow\")\n .Case(\"initialization-order-fiasco\", \"Initialization order problem\")\n .Case(\"stack-buffer-overflow\", \"Stack buffer overflow\")\n .Case(\"stack-use-after-return\", \"Use of stack memory after return\")\n .Case(\"use-after-poison\", \"Use of poisoned memory\")\n .Case(\"container-overflow\", \"Container overflow\")\n .Case(\"stack-use-after-scope\", \"Use of out-of-scope stack memory\")\n .Case(\"global-buffer-overflow\", \"Global buffer overflow\")\n .Case(\"unknown-crash\", \"Invalid memory access\")\n .Case(\"stack-overflow\", \"Stack space exhausted\")\n .Case(\"null-deref\", \"Dereference of null pointer\")\n .Case(\"wild-jump\", \"Jump to non-executable address\")\n .Case(\"wild-addr-write\", \"Write through wild pointer\")\n .Case(\"wild-addr-read\", \"Read from wild pointer\")\n .Case(\"wild-addr\", \"Access through wild pointer\")\n .Case(\"signal\", \"Deadly signal\")\n .Case(\"double-free\", \"Deallocation of freed memory\")\n .Case(\"new-delete-type-mismatch\",\n \"Deallocation size different from allocation size\")\n .Case(\"bad-free\", \"Deallocation of non-allocated memory\")\n .Case(\"alloc-dealloc-mismatch\",\n \"Mismatch between allocation and deallocation APIs\")\n .Case(\"bad-malloc_usable_size\", \"Invalid argument to malloc_usable_size\")\n .Case(\"bad-__sanitizer_get_allocated_size\",\n \"Invalid argument to __sanitizer_get_allocated_size\")\n .Case(\"param-overlap\",\n \"Call to function disallowing overlapping memory ranges\")\n .Case(\"negative-size-param\", \"Negative size used when accessing memory\")\n .Case(\"bad-__sanitizer_annotate_contiguous_container\",\n \"Invalid argument to __sanitizer_annotate_contiguous_container\")\n .Case(\"odr-violation\", \"Symbol defined in multiple translation units\")\n .Case(\n \"invalid-pointer-pair\",\n \"Comparison or arithmetic on pointers from different memory regions\")\n \/\/ for unknown report codes just show the code\n .Default(\"AddressSanitizer detected: \" + description);\n}\n\nbool AddressSanitizerRuntime::NotifyBreakpointHit(\n void *baton, StoppointCallbackContext *context, user_id_t break_id,\n user_id_t break_loc_id) {\n assert(baton && \"null baton\");\n if (!baton)\n return false;\n\n AddressSanitizerRuntime *const instance =\n static_cast<AddressSanitizerRuntime *>(baton);\n\n StructuredData::ObjectSP report = instance->RetrieveReportData();\n std::string description;\n if (report) {\n description = instance->FormatDescription(report);\n }\n ProcessSP process_sp = instance->GetProcessSP();\n \/\/ Make sure this is the right process\n if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {\n ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();\n if (thread_sp)\n thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::\n CreateStopReasonWithInstrumentationData(\n *thread_sp, description, report));\n\n StreamFileSP stream_sp(\n process_sp->GetTarget().GetDebugger().GetOutputFile());\n if (stream_sp) {\n stream_sp->Printf(\"AddressSanitizer report breakpoint hit. Use 'thread \"\n \"info -s' to get extended information about the \"\n \"report.\\n\");\n }\n return true; \/\/ Return true to stop the target\n } else\n return false; \/\/ Let target run\n}\n\nvoid AddressSanitizerRuntime::Activate() {\n if (IsActive())\n return;\n\n ProcessSP process_sp = GetProcessSP();\n if (!process_sp)\n return;\n\n ConstString symbol_name(\"__asan::AsanDie()\");\n const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(\n symbol_name, eSymbolTypeCode);\n\n if (symbol == NULL)\n return;\n\n if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())\n return;\n\n Target &target = process_sp->GetTarget();\n addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);\n\n if (symbol_address == LLDB_INVALID_ADDRESS)\n return;\n\n bool internal = true;\n bool hardware = false;\n Breakpoint *breakpoint =\n process_sp->GetTarget()\n .CreateBreakpoint(symbol_address, internal, hardware)\n .get();\n breakpoint->SetCallback(AddressSanitizerRuntime::NotifyBreakpointHit, this,\n true);\n breakpoint->SetBreakpointKind(\"address-sanitizer-report\");\n SetBreakpointID(breakpoint->GetID());\n\n StreamFileSP stream_sp(process_sp->GetTarget().GetDebugger().GetOutputFile());\n if (stream_sp) {\n stream_sp->Printf(\"AddressSanitizer debugger support is active. Memory \"\n \"error breakpoint has been installed and you can now use \"\n \"the 'memory history' command.\\n\");\n }\n\n SetActive(true);\n}\n\nvoid AddressSanitizerRuntime::Deactivate() {\n if (GetBreakpointID() != LLDB_INVALID_BREAK_ID) {\n ProcessSP process_sp = GetProcessSP();\n if (process_sp) {\n process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());\n SetBreakpointID(LLDB_INVALID_BREAK_ID);\n }\n }\n SetActive(false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * Copyright 2012-2019 Esri\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#include \"ArKitPointCloudRenderer.h\"\n#include \"ArKitWrapper.h\"\n#include <QOpenGLShaderProgram>\n\nusing namespace Esri::ArcGISRuntime::Toolkit::Internal;\n\nArKitPointCloudRenderer::ArKitPointCloudRenderer(ArKitWrapper* ArKitWrapper) :\n m_arKitWrapper(ArKitWrapper)\n{\n}\n\nArKitPointCloudRenderer::~ArKitPointCloudRenderer()\n{\n}\n\nvoid ArKitPointCloudRenderer::initGL()\n{\n initializeOpenGLFunctions();\n\n m_program.reset(new QOpenGLShaderProgram());\n m_program->addCacheableShaderFromSourceCode(QOpenGLShader::Vertex,\n \"uniform mat4 u_modelViewProjection;\"\n \"uniform vec4 u_color;\"\n \"uniform float u_pointSize;\"\n \"attribute vec4 a_position;\"\n \"varying vec4 v_color;\"\n \"void main() {\"\n \" v_color = u_color;\"\n \" vec4 position = u_modelViewProjection * vec4(a_position.xyz, 1.0);\"\n \" gl_Position = vec4(position.x, -position.y, position.z, position.w);\"\n \" gl_PointSize = u_pointSize;\"\n \"}\");\n m_program->addCacheableShaderFromSourceCode(QOpenGLShader::Fragment,\n \"precision mediump float;\"\n \"varying vec4 v_color;\"\n \"void main() {\"\n \" gl_FragColor = v_color;\"\n \"}\");\n\n m_program->link();\n m_program->bind();\n\n m_uniformModelViewProjection = m_program->uniformLocation(\"u_modelViewProjection\");\n m_uniformColor = m_program->uniformLocation(\"u_color\");\n m_uniformPointSize = m_program->uniformLocation(\"u_pointSize\");\n m_attributeVertices = m_program->attributeLocation(\"a_position\");\n\n m_program->release();\n}\n\nvoid ArKitPointCloudRenderer::render()\n{\n Q_CHECK_PTR(m_arKitWrapper);\n\n const std::vector<float> points = m_arKitWrapper->pointCloudData();\n if (points.empty())\n return;\n\n m_program->bind();\n\n glUniformMatrix4fv(m_uniformModelViewProjection, 1, GL_FALSE, m_arKitWrapper->viewProjectionMatrix().data());\n glEnableVertexAttribArray(m_attributeVertices);\n glVertexAttribPointer(m_attributeVertices, 3, GL_FLOAT, GL_FALSE, 0, points.data());\n\n \/\/ Set cyan color to the point cloud.\n glUniform4f(m_uniformColor, m_pointCloudColor.redF(), m_pointCloudColor.greenF(), m_pointCloudColor.blueF(),\n m_pointCloudColor.alphaF());\n glUniform1f(m_uniformPointSize, static_cast<float>(m_pointCloudSize));\n\n glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(points.size()));\n\n m_program->release();\n}\n\n\/\/ properties for debug mode\nQColor ArKitPointCloudRenderer::pointCloudColor() const\n{\n return m_pointCloudColor;\n}\n\nvoid ArKitPointCloudRenderer::setPointCloudColor(const QColor& pointCloudColor)\n{\n m_pointCloudColor = pointCloudColor;\n}\n\nint ArKitPointCloudRenderer::pointCloudSize() const\n{\n return m_pointCloudSize;\n}\n\nvoid ArKitPointCloudRenderer::setPointCloudSize(int pointCloudSize)\n{\n m_pointCloudSize = pointCloudSize;\n}\n<commit_msg>remove implementation for ArKitPointCloudRenderer<commit_after>\/*******************************************************************************\n * Copyright 2012-2019 Esri\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#include \"ArKitPointCloudRenderer.h\"\n#include \"ArKitWrapper.h\"\n#include <QOpenGLShaderProgram>\n\nusing namespace Esri::ArcGISRuntime::Toolkit::Internal;\n\nArKitPointCloudRenderer::ArKitPointCloudRenderer(ArKitWrapper* ArKitWrapper) :\n m_arKitWrapper(ArKitWrapper)\n{\n}\n\nArKitPointCloudRenderer::~ArKitPointCloudRenderer()\n{\n}\n\nvoid ArKitPointCloudRenderer::initGL()\n{\n initializeOpenGLFunctions();\n \/\/ not implemented\n}\n\nvoid ArKitPointCloudRenderer::render()\n{\n Q_CHECK_PTR(m_arKitWrapper);\n \/\/ not implemented\n}\n\n\/\/ properties for debug mode\nQColor ArKitPointCloudRenderer::pointCloudColor() const\n{\n return m_pointCloudColor;\n}\n\nvoid ArKitPointCloudRenderer::setPointCloudColor(const QColor& pointCloudColor)\n{\n m_pointCloudColor = pointCloudColor;\n}\n\nint ArKitPointCloudRenderer::pointCloudSize() const\n{\n return m_pointCloudSize;\n}\n\nvoid ArKitPointCloudRenderer::setPointCloudSize(int pointCloudSize)\n{\n m_pointCloudSize = pointCloudSize;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <poll.h>\n#include <unistd.h>\n#include <algorithm>\n\n#include <kms++\/kms++.h>\n#include <kms++util\/kms++util.h>\n#include <kms++util\/videodevice.h>\n\n#define CAMERA_BUF_QUEUE_SIZE 5\n\nusing namespace std;\nusing namespace kms;\n\nstatic vector<DumbFramebuffer*> s_fbs;\nstatic vector<DumbFramebuffer*> s_free_fbs;\nstatic vector<DumbFramebuffer*> s_wb_fbs;\nstatic vector<DumbFramebuffer*> s_ready_fbs;\n\nclass WBStreamer\n{\npublic:\n\tWBStreamer(VideoStreamer* streamer, Crtc* crtc, uint32_t width, uint32_t height, PixelFormat pixfmt)\n\t\t: m_capdev(*streamer)\n\t{\n\t\tm_capdev.set_port(crtc->idx());\n\t\tm_capdev.set_format(pixfmt, width, height);\n\t\tm_capdev.set_queue_size(s_fbs.size());\n\n\t\tfor (auto fb : s_free_fbs) {\n\t\t\tm_capdev.queue(fb);\n\t\t\ts_wb_fbs.push_back(fb);\n\t\t}\n\n\t\ts_free_fbs.clear();\n\t}\n\n\t~WBStreamer()\n\t{\n\t}\n\n\tWBStreamer(const WBStreamer& other) = delete;\n\tWBStreamer& operator=(const WBStreamer& other) = delete;\n\n\tint fd() const { return m_capdev.fd(); }\n\n\tvoid start_streaming()\n\t{\n\t\tm_capdev.stream_on();\n\t}\n\n\tvoid stop_streaming()\n\t{\n\t\tm_capdev.stream_off();\n\t}\n\n\tvoid Dequeue()\n\t{\n\t\tauto fb = m_capdev.dequeue();\n\n\t\tauto iter = find(s_wb_fbs.begin(), s_wb_fbs.end(), fb);\n\t\ts_wb_fbs.erase(iter);\n\n\t\ts_ready_fbs.insert(s_ready_fbs.begin(), fb);\n\t}\n\n\tvoid Queue()\n\t{\n\t\tif (s_free_fbs.size() == 0)\n\t\t\treturn;\n\n\t\tauto fb = s_free_fbs.back();\n\t\ts_free_fbs.pop_back();\n\n\t\tm_capdev.queue(fb);\n\n\t\ts_wb_fbs.insert(s_wb_fbs.begin(), fb);\n\t}\n\nprivate:\n\tVideoStreamer& m_capdev;\n};\n\nclass WBFlipState : private PageFlipHandlerBase\n{\npublic:\n\tWBFlipState(Card& card, Crtc* crtc, Plane* plane)\n\t\t: m_card(card), m_crtc(crtc), m_plane(plane)\n\t{\n\t}\n\n\tvoid setup(uint32_t x, uint32_t y, uint32_t width, uint32_t height)\n\t{\n\t\tauto fb = s_ready_fbs.back();\n\t\ts_ready_fbs.pop_back();\n\n\t\tAtomicReq req(m_card);\n\n\t\treq.add(m_plane, \"CRTC_ID\", m_crtc->id());\n\t\treq.add(m_plane, \"FB_ID\", fb->id());\n\n\t\treq.add(m_plane, \"CRTC_X\", x);\n\t\treq.add(m_plane, \"CRTC_Y\", y);\n\t\treq.add(m_plane, \"CRTC_W\", width);\n\t\treq.add(m_plane, \"CRTC_H\", height);\n\n\t\treq.add(m_plane, \"SRC_X\", 0);\n\t\treq.add(m_plane, \"SRC_Y\", 0);\n\t\treq.add(m_plane, \"SRC_W\", fb->width() << 16);\n\t\treq.add(m_plane, \"SRC_H\", fb->height() << 16);\n\n\t\tint r = req.commit_sync();\n\t\tFAIL_IF(r, \"initial plane setup failed\");\n\n\t\tm_current_fb = fb;\n\t}\n\n\tvoid queue_next()\n\t{\n\t\tif (m_queued_fb)\n\t\t\treturn;\n\n\t\tif (s_ready_fbs.size() == 0)\n\t\t\treturn;\n\n\t\tauto fb = s_ready_fbs.back();\n\t\ts_ready_fbs.pop_back();\n\n\t\tAtomicReq req(m_card);\n\t\treq.add(m_plane, \"FB_ID\", fb->id());\n\n\t\tint r = req.commit(this);\n\t\tif (r)\n\t\t\tEXIT(\"Flip commit failed: %d\\n\", r);\n\n\t\tm_queued_fb = fb;\n\t}\n\nprivate:\n\tvoid handle_page_flip(uint32_t frame, double time)\n\t{\n\t\tif (m_queued_fb) {\n\t\t\tif (m_current_fb)\n\t\t\t\ts_free_fbs.insert(s_free_fbs.begin(), m_current_fb);\n\n\t\t\tm_current_fb = m_queued_fb;\n\t\t\tm_queued_fb = nullptr;\n\t\t}\n\n\t\tqueue_next();\n\t}\n\n\tCard& m_card;\n\tCrtc* m_crtc;\n\tPlane* m_plane;\n\n\tDumbFramebuffer* m_current_fb = nullptr;\n\tDumbFramebuffer* m_queued_fb = nullptr;\n};\n\nclass BarFlipState : private PageFlipHandlerBase\n{\npublic:\n\tBarFlipState(Card& card, Crtc* crtc)\n\t\t: m_card(card), m_crtc(crtc)\n\t{\n\t\tm_plane = m_crtc->get_primary_plane();\n\n\t\tuint32_t w = m_crtc->mode().hdisplay;\n\t\tuint32_t h = m_crtc->mode().vdisplay;\n\n\t\tfor (unsigned i = 0; i < s_num_buffers; ++i)\n\t\t\tm_fbs[i] = new DumbFramebuffer(card, w, h, PixelFormat::XRGB8888);\n\t}\n\n\t~BarFlipState()\n\t{\n\t\tfor (unsigned i = 0; i < s_num_buffers; ++i)\n\t\t\tdelete m_fbs[i];\n\t}\n\n\tvoid start_flipping()\n\t{\n\t\tm_frame_num = 0;\n\t\tqueue_next();\n\t}\n\nprivate:\n\tvoid handle_page_flip(uint32_t frame, double time)\n\t{\n\t\tm_frame_num++;\n\t\tqueue_next();\n\t}\n\n\tstatic unsigned get_bar_pos(DumbFramebuffer* fb, unsigned frame_num)\n\t{\n\t\treturn (frame_num * bar_speed) % (fb->width() - bar_width + 1);\n\t}\n\n\tvoid draw_bar(DumbFramebuffer* fb, unsigned frame_num)\n\t{\n\t\tint old_xpos = frame_num < s_num_buffers ? -1 : get_bar_pos(fb, frame_num - s_num_buffers);\n\t\tint new_xpos = get_bar_pos(fb, frame_num);\n\n\t\tdraw_color_bar(*fb, old_xpos, new_xpos, bar_width);\n\t\tdraw_text(*fb, fb->width() \/ 2, 0, to_string(frame_num), RGB(255, 255, 255));\n\t}\n\n\tvoid queue_next()\n\t{\n\t\tAtomicReq req(m_card);\n\n\t\tunsigned cur = m_frame_num % s_num_buffers;\n\n\t\tauto fb = m_fbs[cur];\n\n\t\tdraw_bar(fb, m_frame_num);\n\n\t\treq.add(m_plane, {\n\t\t\t\t{ \"FB_ID\", fb->id() },\n\t\t\t});\n\n\t\tint r = req.commit(this);\n\t\tif (r)\n\t\t\tEXIT(\"Flip commit failed: %d\\n\", r);\n\t}\n\n\tstatic const unsigned s_num_buffers = 3;\n\n\tDumbFramebuffer* m_fbs[s_num_buffers];\n\n\tCard& m_card;\n\tCrtc* m_crtc;\n\tPlane* m_plane;\n\n\tunsigned m_frame_num;\n\n\tstatic const unsigned bar_width = 20;\n\tstatic const unsigned bar_speed = 8;\n};\n\nstatic const char* usage_str =\n\t\t\"Usage: wbcap [OPTIONS]\\n\\n\"\n\t\t\"Options:\\n\"\n\t\t\" -s, --src=CONN Source connector\\n\"\n\t\t\" -d, --dst=CONN Destination connector\\n\"\n\t\t\" -f, --format=4CC Format\"\n\t\t\" -h, --help Print this help\\n\"\n\t\t;\n\nint main(int argc, char** argv)\n{\n\tstring src_conn_name = \"unknown\";\n\tstring dst_conn_name = \"hdmi\";\n\tPixelFormat pixfmt = PixelFormat::XRGB8888;\n\n\tOptionSet optionset = {\n\t\tOption(\"s|src=\", [&](string s)\n\t\t{\n\t\t\tsrc_conn_name = s;\n\t\t}),\n\t\tOption(\"d|dst=\", [&](string s)\n\t\t{\n\t\t\tdst_conn_name = s;\n\t\t}),\n\t\tOption(\"f|format=\", [&](string s)\n\t\t{\n\t\t\tpixfmt = FourCCToPixelFormat(s);\n\t\t}),\n\t\tOption(\"h|help\", [&]()\n\t\t{\n\t\t\tputs(usage_str);\n\t\t\texit(-1);\n\t\t}),\n\t};\n\n\toptionset.parse(argc, argv);\n\n\tif (optionset.params().size() > 0) {\n\t\tputs(usage_str);\n\t\texit(-1);\n\t}\n\n\tVideoDevice vid(\"\/dev\/video11\");\n\n\tCard card;\n\tResourceManager resman(card);\n\n\tauto src_conn = resman.reserve_connector(src_conn_name);\n\tauto src_crtc = resman.reserve_crtc(src_conn);\n\tsrc_crtc->refresh();\n\tVideomode src_mode = src_conn->get_default_mode();\n\tDumbFramebuffer src_fb(card, src_mode.hdisplay, src_mode.vdisplay, PixelFormat::ARGB8888);\n\tsrc_crtc->set_mode(src_conn, src_fb, src_mode);\n\n\tuint32_t src_width = src_crtc->mode().hdisplay;\n\tuint32_t src_height = src_crtc->mode().vdisplay;\n\n\tprintf(\"src %s, crtc %ux%u\\n\", src_conn->fullname().c_str(), src_width, src_height);\n\n\tauto dst_conn = resman.reserve_connector(dst_conn_name);\n\tauto dst_crtc = resman.reserve_crtc(dst_conn);\n\tVideomode dst_mode = dst_conn->get_default_mode();\n\tDumbFramebuffer dst_fb(card, dst_mode.hdisplay, dst_mode.vdisplay, PixelFormat::ARGB8888);\n\tdst_crtc->set_mode(dst_conn, dst_fb, dst_mode);\n\tdst_crtc->refresh();\n\tauto dst_plane = resman.reserve_overlay_plane(dst_crtc, pixfmt);\n\tFAIL_IF(!dst_plane, \"Plane not found\");\n\n\tuint32_t dst_width = min((uint32_t)dst_crtc->mode().hdisplay, src_width);\n\tuint32_t dst_height = min((uint32_t)dst_crtc->mode().vdisplay, src_height);\n\n\tprintf(\"dst %s, crtc %ux%u, plane %ux%u\\n\", dst_conn->fullname().c_str(),\n\t dst_crtc->mode().hdisplay, dst_crtc->mode().vdisplay,\n\t dst_width, dst_height);\n\n\tfor (int i = 0; i < CAMERA_BUF_QUEUE_SIZE; ++i) {\n\t\tauto fb = new DumbFramebuffer(card, src_width, src_height, pixfmt);\n\t\ts_fbs.push_back(fb);\n\t\ts_free_fbs.push_back(fb);\n\t}\n\n\t\/\/ get one fb for initial setup\n\ts_ready_fbs.push_back(s_free_fbs.back());\n\ts_free_fbs.pop_back();\n\n\t\/\/ This draws a moving bar to SRC display\n\tBarFlipState barflipper(card, src_crtc);\n\tbarflipper.start_flipping();\n\n\t\/\/ This shows the captures SRC frames on DST display\n\tWBFlipState wbflipper(card, dst_crtc, dst_plane);\n\twbflipper.setup(0, 0, dst_width, dst_height);\n\n\tWBStreamer wb(vid.get_capture_streamer(), src_crtc, src_width, src_height, pixfmt);\n\twb.start_streaming();\n\n\tvector<pollfd> fds(3);\n\n\tfds[0].fd = 0;\n\tfds[0].events = POLLIN;\n\tfds[1].fd = wb.fd();\n\tfds[1].events = POLLIN;\n\tfds[2].fd = card.fd();\n\tfds[2].events = POLLIN;\n\n\twhile (true) {\n\t\tint r = poll(fds.data(), fds.size(), -1);\n\t\tASSERT(r > 0);\n\n\t\tif (fds[0].revents != 0)\n\t\t\tbreak;\n\n\t\tif (fds[1].revents) {\n\t\t\tfds[1].revents = 0;\n\n\t\t\twb.Dequeue();\n\t\t\twbflipper.queue_next();\n\t\t}\n\n\t\tif (fds[2].revents) {\n\t\t\tfds[2].revents = 0;\n\n\t\t\tcard.call_page_flip_handlers();\n\t\t\twb.Queue();\n\t\t}\n\t}\n\n\tprintf(\"exiting...\\n\");\n}\n<commit_msg>utils: improve wbcap<commit_after>#include <cstdio>\n#include <poll.h>\n#include <unistd.h>\n#include <algorithm>\n\n#include <kms++\/kms++.h>\n#include <kms++util\/kms++util.h>\n#include <kms++util\/videodevice.h>\n\n#define CAMERA_BUF_QUEUE_SIZE 5\n\nusing namespace std;\nusing namespace kms;\n\nstatic vector<DumbFramebuffer*> s_fbs;\nstatic vector<DumbFramebuffer*> s_free_fbs;\nstatic vector<DumbFramebuffer*> s_wb_fbs;\nstatic vector<DumbFramebuffer*> s_ready_fbs;\n\nclass WBStreamer\n{\npublic:\n\tWBStreamer(VideoStreamer* streamer, Crtc* crtc, PixelFormat pixfmt)\n\t\t: m_capdev(*streamer)\n\t{\n\t\tm_capdev.set_port(crtc->idx());\n\t\tm_capdev.set_format(pixfmt, crtc->mode().hdisplay, crtc->mode().vdisplay);\n\t\tm_capdev.set_queue_size(s_fbs.size());\n\n\t\tfor (auto fb : s_free_fbs) {\n\t\t\tm_capdev.queue(fb);\n\t\t\ts_wb_fbs.push_back(fb);\n\t\t}\n\n\t\ts_free_fbs.clear();\n\t}\n\n\t~WBStreamer()\n\t{\n\t}\n\n\tWBStreamer(const WBStreamer& other) = delete;\n\tWBStreamer& operator=(const WBStreamer& other) = delete;\n\n\tint fd() const { return m_capdev.fd(); }\n\n\tvoid start_streaming()\n\t{\n\t\tm_capdev.stream_on();\n\t}\n\n\tvoid stop_streaming()\n\t{\n\t\tm_capdev.stream_off();\n\t}\n\n\tvoid Dequeue()\n\t{\n\t\tauto fb = m_capdev.dequeue();\n\n\t\tauto iter = find(s_wb_fbs.begin(), s_wb_fbs.end(), fb);\n\t\ts_wb_fbs.erase(iter);\n\n\t\ts_ready_fbs.insert(s_ready_fbs.begin(), fb);\n\t}\n\n\tvoid Queue()\n\t{\n\t\tif (s_free_fbs.size() == 0)\n\t\t\treturn;\n\n\t\tauto fb = s_free_fbs.back();\n\t\ts_free_fbs.pop_back();\n\n\t\tm_capdev.queue(fb);\n\n\t\ts_wb_fbs.insert(s_wb_fbs.begin(), fb);\n\t}\n\nprivate:\n\tVideoStreamer& m_capdev;\n};\n\nclass WBFlipState : private PageFlipHandlerBase\n{\npublic:\n\tWBFlipState(Card& card, Crtc* crtc, Plane* plane)\n\t\t: m_card(card), m_crtc(crtc), m_plane(plane)\n\t{\n\t}\n\n\tvoid setup(uint32_t x, uint32_t y, uint32_t width, uint32_t height)\n\t{\n\t\tauto fb = s_ready_fbs.back();\n\t\ts_ready_fbs.pop_back();\n\n\t\tAtomicReq req(m_card);\n\n\t\treq.add(m_plane, \"CRTC_ID\", m_crtc->id());\n\t\treq.add(m_plane, \"FB_ID\", fb->id());\n\n\t\treq.add(m_plane, \"CRTC_X\", x);\n\t\treq.add(m_plane, \"CRTC_Y\", y);\n\t\treq.add(m_plane, \"CRTC_W\", min((uint32_t)m_crtc->mode().hdisplay, fb->width()));\n\t\treq.add(m_plane, \"CRTC_H\", min((uint32_t)m_crtc->mode().vdisplay, fb->height()));\n\n\t\treq.add(m_plane, \"SRC_X\", 0);\n\t\treq.add(m_plane, \"SRC_Y\", 0);\n\t\treq.add(m_plane, \"SRC_W\", fb->width() << 16);\n\t\treq.add(m_plane, \"SRC_H\", fb->height() << 16);\n\n\t\tint r = req.commit_sync();\n\t\tFAIL_IF(r, \"initial plane setup failed\");\n\n\t\tm_current_fb = fb;\n\t}\n\n\tvoid queue_next()\n\t{\n\t\tif (m_queued_fb)\n\t\t\treturn;\n\n\t\tif (s_ready_fbs.size() == 0)\n\t\t\treturn;\n\n\t\tauto fb = s_ready_fbs.back();\n\t\ts_ready_fbs.pop_back();\n\n\t\tAtomicReq req(m_card);\n\t\treq.add(m_plane, \"FB_ID\", fb->id());\n\n\t\tint r = req.commit(this);\n\t\tif (r)\n\t\t\tEXIT(\"Flip commit failed: %d\\n\", r);\n\n\t\tm_queued_fb = fb;\n\t}\n\nprivate:\n\tvoid handle_page_flip(uint32_t frame, double time)\n\t{\n\t\tif (m_queued_fb) {\n\t\t\tif (m_current_fb)\n\t\t\t\ts_free_fbs.insert(s_free_fbs.begin(), m_current_fb);\n\n\t\t\tm_current_fb = m_queued_fb;\n\t\t\tm_queued_fb = nullptr;\n\t\t}\n\n\t\tqueue_next();\n\t}\n\n\tCard& m_card;\n\tCrtc* m_crtc;\n\tPlane* m_plane;\n\n\tDumbFramebuffer* m_current_fb = nullptr;\n\tDumbFramebuffer* m_queued_fb = nullptr;\n};\n\nclass BarFlipState : private PageFlipHandlerBase\n{\npublic:\n\tBarFlipState(Card& card, Crtc* crtc, Plane* plane, uint32_t width, uint32_t height)\n\t\t: m_card(card), m_crtc(crtc), m_plane(plane)\n\t{\n\t\tfor (unsigned i = 0; i < s_num_buffers; ++i)\n\t\t\tm_fbs[i] = new DumbFramebuffer(card, width, height, PixelFormat::XRGB8888);\n\t}\n\n\t~BarFlipState()\n\t{\n\t\tfor (unsigned i = 0; i < s_num_buffers; ++i)\n\t\t\tdelete m_fbs[i];\n\t}\n\n\tvoid start_flipping()\n\t{\n\t\tm_frame_num = 0;\n\t\tqueue_next();\n\t}\n\nprivate:\n\tvoid handle_page_flip(uint32_t frame, double time)\n\t{\n\t\tm_frame_num++;\n\t\tqueue_next();\n\t}\n\n\tstatic unsigned get_bar_pos(DumbFramebuffer* fb, unsigned frame_num)\n\t{\n\t\treturn (frame_num * bar_speed) % (fb->width() - bar_width + 1);\n\t}\n\n\tvoid draw_bar(DumbFramebuffer* fb, unsigned frame_num)\n\t{\n\t\tint old_xpos = frame_num < s_num_buffers ? -1 : get_bar_pos(fb, frame_num - s_num_buffers);\n\t\tint new_xpos = get_bar_pos(fb, frame_num);\n\n\t\tdraw_color_bar(*fb, old_xpos, new_xpos, bar_width);\n\t\tdraw_text(*fb, fb->width() \/ 2, 0, to_string(frame_num), RGB(255, 255, 255));\n\t}\n\n\tvoid queue_next()\n\t{\n\t\tAtomicReq req(m_card);\n\n\t\tunsigned cur = m_frame_num % s_num_buffers;\n\n\t\tauto fb = m_fbs[cur];\n\n\t\tdraw_bar(fb, m_frame_num);\n\n\t\treq.add(m_plane, {\n\t\t\t\t{ \"CRTC_ID\", m_crtc->id() },\n\t\t\t\t{ \"FB_ID\", fb->id() },\n\n\t\t\t\t{ \"CRTC_X\", 0 },\n\t\t\t\t{ \"CRTC_Y\", 0 },\n\t\t\t\t{ \"CRTC_W\", min((uint32_t)m_crtc->mode().hdisplay, fb->width()) },\n\t\t\t\t{ \"CRTC_H\", min((uint32_t)m_crtc->mode().vdisplay, fb->height()) },\n\n\t\t\t\t{ \"SRC_X\", 0 },\n\t\t\t\t{ \"SRC_Y\", 0 },\n\t\t\t\t{ \"SRC_W\", fb->width() << 16 },\n\t\t\t\t{ \"SRC_H\", fb->height() << 16 },\n\t\t\t});\n\n\t\tint r = req.commit(this);\n\t\tif (r)\n\t\t\tEXIT(\"Flip commit failed: %d\\n\", r);\n\t}\n\n\tstatic const unsigned s_num_buffers = 3;\n\n\tDumbFramebuffer* m_fbs[s_num_buffers];\n\n\tCard& m_card;\n\tCrtc* m_crtc;\n\tPlane* m_plane;\n\n\tunsigned m_frame_num;\n\n\tstatic const unsigned bar_width = 20;\n\tstatic const unsigned bar_speed = 8;\n};\n\nstatic const char* usage_str =\n\t\t\"Usage: wbcap [OPTIONS]\\n\\n\"\n\t\t\"Options:\\n\"\n\t\t\" -s, --src=CONN Source connector\\n\"\n\t\t\" -d, --dst=CONN Destination connector\\n\"\n\t\t\" -f, --format=4CC Format\"\n\t\t\" -h, --help Print this help\\n\"\n\t\t;\n\nint main(int argc, char** argv)\n{\n\tstring src_conn_name;\n\tstring src_mode_name;\n\tstring dst_conn_name;\n\tstring dst_mode_name;\n\tPixelFormat pixfmt = PixelFormat::XRGB8888;\n\n\tOptionSet optionset = {\n\t\tOption(\"s|src=\", [&](string s)\n\t\t{\n\t\t\tsrc_conn_name = s;\n\t\t}),\n\t\tOption(\"m|smode=\", [&](string s)\n\t\t{\n\t\t\tsrc_mode_name = s;\n\t\t}),\n\t\tOption(\"d|dst=\", [&](string s)\n\t\t{\n\t\t\tdst_conn_name = s;\n\t\t}),\n\t\tOption(\"M|dmode=\", [&](string s)\n\t\t{\n\t\t\tdst_mode_name = s;\n\t\t}),\n\t\tOption(\"f|format=\", [&](string s)\n\t\t{\n\t\t\tpixfmt = FourCCToPixelFormat(s);\n\t\t}),\n\t\tOption(\"h|help\", [&]()\n\t\t{\n\t\t\tputs(usage_str);\n\t\t\texit(-1);\n\t\t}),\n\t};\n\n\toptionset.parse(argc, argv);\n\n\tif (optionset.params().size() > 0) {\n\t\tputs(usage_str);\n\t\texit(-1);\n\t}\n\n\tif (src_conn_name.empty())\n\t\tEXIT(\"No source connector defined\");\n\n\tif (dst_conn_name.empty())\n\t\tEXIT(\"No destination connector defined\");\n\n\tVideoDevice vid(\"\/dev\/video11\");\n\n\tCard card;\n\tResourceManager resman(card);\n\n\tcard.disable_all();\n\n\tauto src_conn = resman.reserve_connector(src_conn_name);\n\tauto src_crtc = resman.reserve_crtc(src_conn);\n\tauto src_plane = resman.reserve_generic_plane(src_crtc, pixfmt);\n\tFAIL_IF(!src_plane, \"Plane not found\");\n\tVideomode src_mode = src_mode_name.empty() ? src_conn->get_default_mode() : src_conn->get_mode(src_mode_name);\n\tsrc_crtc->set_mode(src_conn, src_mode);\n\n\n\tauto dst_conn = resman.reserve_connector(dst_conn_name);\n\tauto dst_crtc = resman.reserve_crtc(dst_conn);\n\tauto dst_plane = resman.reserve_overlay_plane(dst_crtc, pixfmt);\n\tFAIL_IF(!dst_plane, \"Plane not found\");\n\tVideomode dst_mode = dst_mode_name.empty() ? dst_conn->get_default_mode() : dst_conn->get_mode(dst_mode_name);\n\tdst_crtc->set_mode(dst_conn, dst_mode);\n\n\tuint32_t width = src_mode.hdisplay;\n\tuint32_t height = src_mode.vdisplay;\n\n\tprintf(\"src %s, crtc %s\\n\", src_conn->fullname().c_str(), src_mode.to_string().c_str());\n\n\tprintf(\"dst %s, crtc %s\\n\", dst_conn->fullname().c_str(), dst_mode.to_string().c_str());\n\n\tprintf(\"fb %ux%u\\n\", width, height);\n\n\tfor (int i = 0; i < CAMERA_BUF_QUEUE_SIZE; ++i) {\n\t\tauto fb = new DumbFramebuffer(card, width, height, pixfmt);\n\t\ts_fbs.push_back(fb);\n\t\ts_free_fbs.push_back(fb);\n\t}\n\n\t\/\/ get one fb for initial setup\n\ts_ready_fbs.push_back(s_free_fbs.back());\n\ts_free_fbs.pop_back();\n\n\t\/\/ This draws a moving bar to SRC display\n\tBarFlipState barflipper(card, src_crtc, src_plane, width, height);\n\tbarflipper.start_flipping();\n\n\t\/\/ This shows the captures SRC frames on DST display\n\tWBFlipState wbflipper(card, dst_crtc, dst_plane);\n\twbflipper.setup(0, 0, width, height);\n\n\tWBStreamer wb(vid.get_capture_streamer(), src_crtc, pixfmt);\n\twb.start_streaming();\n\n\tvector<pollfd> fds(3);\n\n\tfds[0].fd = 0;\n\tfds[0].events = POLLIN;\n\tfds[1].fd = wb.fd();\n\tfds[1].events = POLLIN;\n\tfds[2].fd = card.fd();\n\tfds[2].events = POLLIN;\n\n\twhile (true) {\n\t\tint r = poll(fds.data(), fds.size(), -1);\n\t\tASSERT(r > 0);\n\n\t\tif (fds[0].revents != 0)\n\t\t\tbreak;\n\n\t\tif (fds[1].revents) {\n\t\t\tfds[1].revents = 0;\n\n\t\t\twb.Dequeue();\n\t\t\twbflipper.queue_next();\n\t\t}\n\n\t\tif (fds[2].revents) {\n\t\t\tfds[2].revents = 0;\n\n\t\t\tcard.call_page_flip_handlers();\n\t\t\twb.Queue();\n\t\t}\n\t}\n\n\tprintf(\"exiting...\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"bct.h\"\n#include <cmath>\n#include <gsl\/gsl_matrix.h>\n#include <gsl\/gsl_vector.h>\n\n\/*\n * Returns a copy of the given matrix with each element inverted.\n *\/\ngsl_matrix* bct::invert_elements(const gsl_matrix* m) {\n\treturn pow_elements(m, -1.0);\n}\n\n\/*\n * Returns a copy of the given matrix with no loops.\n *\/\ngsl_matrix* bct::remove_loops(const gsl_matrix* m) {\n\tgsl_matrix* nl_m = copy(m);\n\tgsl_vector_view diag_nl_m = gsl_matrix_diagonal(nl_m);\n\tgsl_vector_set_zero(&diag_nl_m.vector);\n\treturn nl_m;\n}\n\n\/*\n * Returns a binary copy of the given matrix.\n *\/\ngsl_matrix* bct::to_binary(const gsl_matrix* m) {\n\treturn compare_elements(m, fp_not_equal, 0.0);\n}\n\n\/*\n * Returns a positive copy of the given matrix.\n *\/\ngsl_matrix* bct::to_positive(const gsl_matrix* m) {\n\tgsl_matrix* pos_m = gsl_matrix_alloc(m->size1, m->size2);\n\tfor (int i = 0; i < (int)m->size1; i++) {\n\t\tfor (int j = 0; j < (int)m->size2; j++) {\n\t\t\tgsl_matrix_set(pos_m, i, j, std::abs(gsl_matrix_get(m, i, j)));\n\t\t}\n\t}\n\treturn pos_m;\n}\n\n\/*\n * Returns an undirected copy of the given matrix. For every pair of nodes:\n * - If m(i, j) and m(j, i) are the same, no change is made.\n * - If m(i, j) is zero and m(j, i) is nonzero, m(i, j) is set to m(j, i).\n * - If m(i, j) is nonzero and m(j, i) is zero, m(j, i) is set to m(i, j).\n * - If m(i, j) and m(j, i) are different nonzero values, they are both set to\n * the average of these values.\n *\/\ngsl_matrix* bct::to_undirected(const gsl_matrix* m) {\n\tif (m->size1 != m->size2) throw size_exception();\n\tgsl_matrix* und_m = copy(m);\n\tfor (int i = 0; i < (int)m->size1; i++) {\n\t\tfor (int j = i; j < (int)m->size2; j++) {\n\t\t\tdouble value_ij = gsl_matrix_get(m, i, j);\n\t\t\tdouble value_ji = gsl_matrix_get(m, j, i);\n\t\t\tif (fp_zero(value_ij) && fp_nonzero(value_ji)) {\n\t\t\t\tgsl_matrix_set(und_m, i, j, value_ji);\n\t\t\t} else if (fp_nonzero(value_ij) && fp_zero(value_ji)) {\n\t\t\t\tgsl_matrix_set(und_m, j, i, value_ij);\n\t\t\t} else if (fp_not_equal(value_ij, value_ji)) {\n\t\t\t\tdouble average = (value_ij + value_ji) \/ 2.0;\n\t\t\t\tgsl_matrix_set(und_m, i, j, average);\n\t\t\t\tgsl_matrix_set(und_m, j, i, average);\n\t\t\t}\n\t\t}\n\t}\n\treturn und_m;\n}\n<commit_msg>Only invert nonzero elements in bct::invert_elements.<commit_after>#include \"bct.h\"\n#include <cmath>\n#include <gsl\/gsl_matrix.h>\n#include <gsl\/gsl_vector.h>\n\n\/*\n * Returns a copy of the given matrix with each nonzero element inverted.\n *\/\ngsl_matrix* bct::invert_elements(const gsl_matrix* m) {\n\tgsl_matrix* inv_m = gsl_matrix_alloc(m->size1, m->size2);\n\tfor (int i = 0; i < (int)m->size1; i++) {\n\t\tfor (int j = 0; j < (int)m->size2; j++) {\n\t\t\tdouble value = gsl_matrix_get(m, i, j);\n\t\t\tif (fp_nonzero(value)) {\n\t\t\t\tgsl_matrix_set(inv_m, i, j, 1.0 \/ value);\n\t\t\t} else {\n\t\t\t\tgsl_matrix_set(inv_m, i, j, 0.0);\n\t\t\t}\n\t\t}\n\t}\n\treturn inv_m;\n}\n\n\/*\n * Returns a copy of the given matrix with no loops.\n *\/\ngsl_matrix* bct::remove_loops(const gsl_matrix* m) {\n\tgsl_matrix* nl_m = copy(m);\n\tgsl_vector_view diag_nl_m = gsl_matrix_diagonal(nl_m);\n\tgsl_vector_set_zero(&diag_nl_m.vector);\n\treturn nl_m;\n}\n\n\/*\n * Returns a binary copy of the given matrix.\n *\/\ngsl_matrix* bct::to_binary(const gsl_matrix* m) {\n\treturn compare_elements(m, fp_not_equal, 0.0);\n}\n\n\/*\n * Returns a positive copy of the given matrix.\n *\/\ngsl_matrix* bct::to_positive(const gsl_matrix* m) {\n\tgsl_matrix* pos_m = gsl_matrix_alloc(m->size1, m->size2);\n\tfor (int i = 0; i < (int)m->size1; i++) {\n\t\tfor (int j = 0; j < (int)m->size2; j++) {\n\t\t\tgsl_matrix_set(pos_m, i, j, std::abs(gsl_matrix_get(m, i, j)));\n\t\t}\n\t}\n\treturn pos_m;\n}\n\n\/*\n * Returns an undirected copy of the given matrix. For every pair of nodes:\n * - If m(i, j) and m(j, i) are the same, no change is made.\n * - If m(i, j) is zero and m(j, i) is nonzero, m(i, j) is set to m(j, i).\n * - If m(i, j) is nonzero and m(j, i) is zero, m(j, i) is set to m(i, j).\n * - If m(i, j) and m(j, i) are different nonzero values, they are both set to\n * the average of these values.\n *\/\ngsl_matrix* bct::to_undirected(const gsl_matrix* m) {\n\tif (m->size1 != m->size2) throw size_exception();\n\tgsl_matrix* und_m = copy(m);\n\tfor (int i = 0; i < (int)m->size1; i++) {\n\t\tfor (int j = i; j < (int)m->size2; j++) {\n\t\t\tdouble value_ij = gsl_matrix_get(m, i, j);\n\t\t\tdouble value_ji = gsl_matrix_get(m, j, i);\n\t\t\tif (fp_zero(value_ij) && fp_nonzero(value_ji)) {\n\t\t\t\tgsl_matrix_set(und_m, i, j, value_ji);\n\t\t\t} else if (fp_nonzero(value_ij) && fp_zero(value_ji)) {\n\t\t\t\tgsl_matrix_set(und_m, j, i, value_ij);\n\t\t\t} else if (fp_not_equal(value_ij, value_ji)) {\n\t\t\t\tdouble average = (value_ij + value_ji) \/ 2.0;\n\t\t\t\tgsl_matrix_set(und_m, i, j, average);\n\t\t\t\tgsl_matrix_set(und_m, j, i, average);\n\t\t\t}\n\t\t}\n\t}\n\treturn und_m;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of gltfpack; see gltfpack.h for version\/license details\n#include \"gltfpack.h\"\n\n#include <algorithm>\n\n#include <math.h>\n#include <string.h>\n\nstatic float getDelta(const Attr& l, const Attr& r, cgltf_animation_path_type type)\n{\n\tswitch (type)\n\t{\n\tcase cgltf_animation_path_type_translation:\n\t\treturn std::max(std::max(fabsf(l.f[0] - r.f[0]), fabsf(l.f[1] - r.f[1])), fabsf(l.f[2] - r.f[2]));\n\n\tcase cgltf_animation_path_type_rotation:\n\t\treturn acosf(std::min(1.f, fabsf(l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3])));\n\n\tcase cgltf_animation_path_type_scale:\n\t\treturn std::max(std::max(fabsf(l.f[0] \/ r.f[0] - 1), fabsf(l.f[1] \/ r.f[1] - 1)), fabsf(l.f[2] \/ r.f[2] - 1));\n\n\tcase cgltf_animation_path_type_weights:\n\t\treturn fabsf(l.f[0] - r.f[0]);\n\n\tdefault:\n\t\tassert(!\"Uknown animation path\");\n\t\treturn 0;\n\t}\n}\n\nstatic float getDeltaTolerance(cgltf_animation_path_type type)\n{\n\tswitch (type)\n\t{\n\tcase cgltf_animation_path_type_translation:\n\t\treturn 0.001f; \/\/ linear\n\n\tcase cgltf_animation_path_type_rotation:\n\t\treturn 0.001f; \/\/ radians\n\n\tcase cgltf_animation_path_type_scale:\n\t\treturn 0.001f; \/\/ ratio\n\n\tcase cgltf_animation_path_type_weights:\n\t\treturn 0.001f; \/\/ linear\n\n\tdefault:\n\t\tassert(!\"Uknown animation path\");\n\t\treturn 0;\n\t}\n}\n\nstatic Attr interpolateLinear(const Attr& l, const Attr& r, float t, cgltf_animation_path_type type)\n{\n\tif (type == cgltf_animation_path_type_rotation)\n\t{\n\t\t\/\/ Approximating slerp, https:\/\/zeux.io\/2015\/07\/23\/approximating-slerp\/\n\t\t\/\/ We also handle quaternion double-cover\n\t\tfloat ca = l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3];\n\n\t\tfloat d = fabsf(ca);\n\t\tfloat A = 1.0904f + d * (-3.2452f + d * (3.55645f - d * 1.43519f));\n\t\tfloat B = 0.848013f + d * (-1.06021f + d * 0.215638f);\n\t\tfloat k = A * (t - 0.5f) * (t - 0.5f) + B;\n\t\tfloat ot = t + t * (t - 0.5f) * (t - 1) * k;\n\n\t\tfloat t0 = 1 - ot;\n\t\tfloat t1 = ca > 0 ? ot : -ot;\n\n\t\tAttr lerp = {{\n\t\t l.f[0] * t0 + r.f[0] * t1,\n\t\t l.f[1] * t0 + r.f[1] * t1,\n\t\t l.f[2] * t0 + r.f[2] * t1,\n\t\t l.f[3] * t0 + r.f[3] * t1,\n\t\t}};\n\n\t\tfloat len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);\n\n\t\tif (len > 0.f)\n\t\t{\n\t\t\tlerp.f[0] \/= len;\n\t\t\tlerp.f[1] \/= len;\n\t\t\tlerp.f[2] \/= len;\n\t\t\tlerp.f[3] \/= len;\n\t\t}\n\n\t\treturn lerp;\n\t}\n\telse\n\t{\n\t\tAttr lerp = {{\n\t\t l.f[0] * (1 - t) + r.f[0] * t,\n\t\t l.f[1] * (1 - t) + r.f[1] * t,\n\t\t l.f[2] * (1 - t) + r.f[2] * t,\n\t\t l.f[3] * (1 - t) + r.f[3] * t,\n\t\t}};\n\n\t\treturn lerp;\n\t}\n}\n\nstatic Attr interpolateHermite(const Attr& v0, const Attr& t0, const Attr& v1, const Attr& t1, float t, float dt, cgltf_animation_path_type type)\n{\n\tfloat s0 = 1 + t * t * (2 * t - 3);\n\tfloat s1 = t + t * t * (t - 2);\n\tfloat s2 = 1 - s0;\n\tfloat s3 = t * t * (t - 1);\n\n\tfloat ts1 = dt * s1;\n\tfloat ts3 = dt * s3;\n\n\tAttr lerp = {{\n\t s0 * v0.f[0] + ts1 * t0.f[0] + s2 * v1.f[0] + ts3 * t1.f[0],\n\t s0 * v0.f[1] + ts1 * t0.f[1] + s2 * v1.f[1] + ts3 * t1.f[1],\n\t s0 * v0.f[2] + ts1 * t0.f[2] + s2 * v1.f[2] + ts3 * t1.f[2],\n\t s0 * v0.f[3] + ts1 * t0.f[3] + s2 * v1.f[3] + ts3 * t1.f[3],\n\t}};\n\n\tif (type == cgltf_animation_path_type_rotation)\n\t{\n\t\tfloat len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);\n\n\t\tif (len > 0.f)\n\t\t{\n\t\t\tlerp.f[0] \/= len;\n\t\t\tlerp.f[1] \/= len;\n\t\t\tlerp.f[2] \/= len;\n\t\t\tlerp.f[3] \/= len;\n\t\t}\n\t}\n\n\treturn lerp;\n}\n\nstatic void resampleKeyframes(std::vector<Attr>& data, const std::vector<float>& input, const std::vector<Attr>& output, cgltf_animation_path_type type, cgltf_interpolation_type interpolation, size_t components, int frames, float mint, int freq)\n{\n\tsize_t cursor = 0;\n\n\tfor (int i = 0; i < frames; ++i)\n\t{\n\t\tfloat time = mint + float(i) \/ freq;\n\n\t\twhile (cursor + 1 < input.size())\n\t\t{\n\t\t\tfloat next_time = input[cursor + 1];\n\n\t\t\tif (next_time > time)\n\t\t\t\tbreak;\n\n\t\t\tcursor++;\n\t\t}\n\n\t\tif (cursor + 1 < input.size())\n\t\t{\n\t\t\tfloat cursor_time = input[cursor + 0];\n\t\t\tfloat next_time = input[cursor + 1];\n\n\t\t\tfloat range = next_time - cursor_time;\n\t\t\tfloat inv_range = (range == 0.f) ? 0.f : 1.f \/ (next_time - cursor_time);\n\t\t\tfloat t = std::max(0.f, std::min(1.f, (time - cursor_time) * inv_range));\n\n\t\t\tfor (size_t j = 0; j < components; ++j)\n\t\t\t{\n\t\t\t\tswitch (interpolation)\n\t\t\t\t{\n\t\t\t\tcase cgltf_interpolation_type_linear:\n\t\t\t\t{\n\t\t\t\t\tconst Attr& v0 = output[(cursor + 0) * components + j];\n\t\t\t\t\tconst Attr& v1 = output[(cursor + 1) * components + j];\n\t\t\t\t\tdata.push_back(interpolateLinear(v0, v1, t, type));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase cgltf_interpolation_type_step:\n\t\t\t\t{\n\t\t\t\t\tconst Attr& v = output[cursor * components + j];\n\t\t\t\t\tdata.push_back(v);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase cgltf_interpolation_type_cubic_spline:\n\t\t\t\t{\n\t\t\t\t\tconst Attr& v0 = output[(cursor * 3 + 1) * components + j];\n\t\t\t\t\tconst Attr& b0 = output[(cursor * 3 + 2) * components + j];\n\t\t\t\t\tconst Attr& a1 = output[(cursor * 3 + 3) * components + j];\n\t\t\t\t\tconst Attr& v1 = output[(cursor * 3 + 4) * components + j];\n\t\t\t\t\tdata.push_back(interpolateHermite(v0, b0, v1, a1, t, range, type));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tassert(!\"Unknown interpolation type\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsize_t offset = (interpolation == cgltf_interpolation_type_cubic_spline) ? cursor * 3 + 1 : cursor;\n\n\t\t\tfor (size_t j = 0; j < components; ++j)\n\t\t\t{\n\t\t\t\tconst Attr& v = output[offset * components + j];\n\t\t\t\tdata.push_back(v);\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic bool isTrackEqual(const std::vector<Attr>& data, cgltf_animation_path_type type, int frames, const Attr* value, size_t components)\n{\n\tassert(data.size() == frames * components);\n\n\tfloat tolerance = getDeltaTolerance(type);\n\n\tfor (int i = 0; i < frames; ++i)\n\t{\n\t\tfor (size_t j = 0; j < components; ++j)\n\t\t{\n\t\t\tfloat delta = getDelta(value[j], data[i * components + j], type);\n\n\t\t\tif (delta > tolerance)\n\t\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstatic void getBaseTransform(Attr* result, size_t components, cgltf_animation_path_type type, cgltf_node* node)\n{\n\tswitch (type)\n\t{\n\tcase cgltf_animation_path_type_translation:\n\t\tmemcpy(result->f, node->translation, 3 * sizeof(float));\n\t\tbreak;\n\n\tcase cgltf_animation_path_type_rotation:\n\t\tmemcpy(result->f, node->rotation, 4 * sizeof(float));\n\t\tbreak;\n\n\tcase cgltf_animation_path_type_scale:\n\t\tmemcpy(result->f, node->scale, 3 * sizeof(float));\n\t\tbreak;\n\n\tcase cgltf_animation_path_type_weights:\n\t\tif (node->weights_count)\n\t\t{\n\t\t\tassert(node->weights_count == components);\n\t\t\tmemcpy(result->f, node->weights, components * sizeof(float));\n\t\t}\n\t\telse if (node->mesh && node->mesh->weights_count)\n\t\t{\n\t\t\tassert(node->mesh->weights_count == components);\n\t\t\tmemcpy(result->f, node->mesh->weights, components * sizeof(float));\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tassert(!\"Unknown animation path\");\n\t}\n}\n\nvoid processAnimation(Animation& animation, const Settings& settings)\n{\n\tfloat mint = 0, maxt = 0;\n\n\tfor (size_t i = 0; i < animation.tracks.size(); ++i)\n\t{\n\t\tconst Track& track = animation.tracks[i];\n\t\tassert(!track.time.empty());\n\n\t\tmint = std::min(mint, track.time.front());\n\t\tmaxt = std::max(maxt, track.time.back());\n\t}\n\n\t\/\/ round the number of frames to nearest but favor the \"up\" direction\n\t\/\/ this means that at 10 Hz resampling, we will try to preserve the last frame <10ms\n\t\/\/ but if the last frame is <2ms we favor just removing this data\n\tint frames = 1 + int((maxt - mint) * settings.anim_freq + 0.8f);\n\n\tanimation.start = mint;\n\tanimation.frames = frames;\n\n\tstd::vector<Attr> base;\n\n\tfor (size_t i = 0; i < animation.tracks.size(); ++i)\n\t{\n\t\tTrack& track = animation.tracks[i];\n\n\t\tstd::vector<Attr> result;\n\t\tresampleKeyframes(result, track.time, track.data, track.path, track.interpolation, track.components, frames, mint, settings.anim_freq);\n\n\t\ttrack.time.clear();\n\t\ttrack.data.swap(result);\n\n\t\tif (isTrackEqual(track.data, track.path, frames, &track.data[0], track.components))\n\t\t{\n\t\t\t\/\/ track is constant (equal to first keyframe), we only need the first keyframe\n\t\t\ttrack.data.resize(track.components);\n\n\t\t\t\/\/ track.dummy is true iff track redundantly sets up the value to be equal to default node transform\n\t\t\tbase.resize(track.components);\n\t\t\tgetBaseTransform(&base[0], track.components, track.path, track.node);\n\n\t\t\ttrack.dummy = isTrackEqual(track.data, track.path, 1, &base[0], track.components);\n\t\t}\n\t}\n}\n<commit_msg>gltfpack: Fix output animation start time<commit_after>\/\/ This file is part of gltfpack; see gltfpack.h for version\/license details\n#include \"gltfpack.h\"\n\n#include <algorithm>\n\n#include <float.h>\n#include <math.h>\n#include <string.h>\n\nstatic float getDelta(const Attr& l, const Attr& r, cgltf_animation_path_type type)\n{\n\tswitch (type)\n\t{\n\tcase cgltf_animation_path_type_translation:\n\t\treturn std::max(std::max(fabsf(l.f[0] - r.f[0]), fabsf(l.f[1] - r.f[1])), fabsf(l.f[2] - r.f[2]));\n\n\tcase cgltf_animation_path_type_rotation:\n\t\treturn acosf(std::min(1.f, fabsf(l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3])));\n\n\tcase cgltf_animation_path_type_scale:\n\t\treturn std::max(std::max(fabsf(l.f[0] \/ r.f[0] - 1), fabsf(l.f[1] \/ r.f[1] - 1)), fabsf(l.f[2] \/ r.f[2] - 1));\n\n\tcase cgltf_animation_path_type_weights:\n\t\treturn fabsf(l.f[0] - r.f[0]);\n\n\tdefault:\n\t\tassert(!\"Uknown animation path\");\n\t\treturn 0;\n\t}\n}\n\nstatic float getDeltaTolerance(cgltf_animation_path_type type)\n{\n\tswitch (type)\n\t{\n\tcase cgltf_animation_path_type_translation:\n\t\treturn 0.001f; \/\/ linear\n\n\tcase cgltf_animation_path_type_rotation:\n\t\treturn 0.001f; \/\/ radians\n\n\tcase cgltf_animation_path_type_scale:\n\t\treturn 0.001f; \/\/ ratio\n\n\tcase cgltf_animation_path_type_weights:\n\t\treturn 0.001f; \/\/ linear\n\n\tdefault:\n\t\tassert(!\"Uknown animation path\");\n\t\treturn 0;\n\t}\n}\n\nstatic Attr interpolateLinear(const Attr& l, const Attr& r, float t, cgltf_animation_path_type type)\n{\n\tif (type == cgltf_animation_path_type_rotation)\n\t{\n\t\t\/\/ Approximating slerp, https:\/\/zeux.io\/2015\/07\/23\/approximating-slerp\/\n\t\t\/\/ We also handle quaternion double-cover\n\t\tfloat ca = l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3];\n\n\t\tfloat d = fabsf(ca);\n\t\tfloat A = 1.0904f + d * (-3.2452f + d * (3.55645f - d * 1.43519f));\n\t\tfloat B = 0.848013f + d * (-1.06021f + d * 0.215638f);\n\t\tfloat k = A * (t - 0.5f) * (t - 0.5f) + B;\n\t\tfloat ot = t + t * (t - 0.5f) * (t - 1) * k;\n\n\t\tfloat t0 = 1 - ot;\n\t\tfloat t1 = ca > 0 ? ot : -ot;\n\n\t\tAttr lerp = {{\n\t\t l.f[0] * t0 + r.f[0] * t1,\n\t\t l.f[1] * t0 + r.f[1] * t1,\n\t\t l.f[2] * t0 + r.f[2] * t1,\n\t\t l.f[3] * t0 + r.f[3] * t1,\n\t\t}};\n\n\t\tfloat len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);\n\n\t\tif (len > 0.f)\n\t\t{\n\t\t\tlerp.f[0] \/= len;\n\t\t\tlerp.f[1] \/= len;\n\t\t\tlerp.f[2] \/= len;\n\t\t\tlerp.f[3] \/= len;\n\t\t}\n\n\t\treturn lerp;\n\t}\n\telse\n\t{\n\t\tAttr lerp = {{\n\t\t l.f[0] * (1 - t) + r.f[0] * t,\n\t\t l.f[1] * (1 - t) + r.f[1] * t,\n\t\t l.f[2] * (1 - t) + r.f[2] * t,\n\t\t l.f[3] * (1 - t) + r.f[3] * t,\n\t\t}};\n\n\t\treturn lerp;\n\t}\n}\n\nstatic Attr interpolateHermite(const Attr& v0, const Attr& t0, const Attr& v1, const Attr& t1, float t, float dt, cgltf_animation_path_type type)\n{\n\tfloat s0 = 1 + t * t * (2 * t - 3);\n\tfloat s1 = t + t * t * (t - 2);\n\tfloat s2 = 1 - s0;\n\tfloat s3 = t * t * (t - 1);\n\n\tfloat ts1 = dt * s1;\n\tfloat ts3 = dt * s3;\n\n\tAttr lerp = {{\n\t s0 * v0.f[0] + ts1 * t0.f[0] + s2 * v1.f[0] + ts3 * t1.f[0],\n\t s0 * v0.f[1] + ts1 * t0.f[1] + s2 * v1.f[1] + ts3 * t1.f[1],\n\t s0 * v0.f[2] + ts1 * t0.f[2] + s2 * v1.f[2] + ts3 * t1.f[2],\n\t s0 * v0.f[3] + ts1 * t0.f[3] + s2 * v1.f[3] + ts3 * t1.f[3],\n\t}};\n\n\tif (type == cgltf_animation_path_type_rotation)\n\t{\n\t\tfloat len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);\n\n\t\tif (len > 0.f)\n\t\t{\n\t\t\tlerp.f[0] \/= len;\n\t\t\tlerp.f[1] \/= len;\n\t\t\tlerp.f[2] \/= len;\n\t\t\tlerp.f[3] \/= len;\n\t\t}\n\t}\n\n\treturn lerp;\n}\n\nstatic void resampleKeyframes(std::vector<Attr>& data, const std::vector<float>& input, const std::vector<Attr>& output, cgltf_animation_path_type type, cgltf_interpolation_type interpolation, size_t components, int frames, float mint, int freq)\n{\n\tsize_t cursor = 0;\n\n\tfor (int i = 0; i < frames; ++i)\n\t{\n\t\tfloat time = mint + float(i) \/ freq;\n\n\t\twhile (cursor + 1 < input.size())\n\t\t{\n\t\t\tfloat next_time = input[cursor + 1];\n\n\t\t\tif (next_time > time)\n\t\t\t\tbreak;\n\n\t\t\tcursor++;\n\t\t}\n\n\t\tif (cursor + 1 < input.size())\n\t\t{\n\t\t\tfloat cursor_time = input[cursor + 0];\n\t\t\tfloat next_time = input[cursor + 1];\n\n\t\t\tfloat range = next_time - cursor_time;\n\t\t\tfloat inv_range = (range == 0.f) ? 0.f : 1.f \/ (next_time - cursor_time);\n\t\t\tfloat t = std::max(0.f, std::min(1.f, (time - cursor_time) * inv_range));\n\n\t\t\tfor (size_t j = 0; j < components; ++j)\n\t\t\t{\n\t\t\t\tswitch (interpolation)\n\t\t\t\t{\n\t\t\t\tcase cgltf_interpolation_type_linear:\n\t\t\t\t{\n\t\t\t\t\tconst Attr& v0 = output[(cursor + 0) * components + j];\n\t\t\t\t\tconst Attr& v1 = output[(cursor + 1) * components + j];\n\t\t\t\t\tdata.push_back(interpolateLinear(v0, v1, t, type));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase cgltf_interpolation_type_step:\n\t\t\t\t{\n\t\t\t\t\tconst Attr& v = output[cursor * components + j];\n\t\t\t\t\tdata.push_back(v);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase cgltf_interpolation_type_cubic_spline:\n\t\t\t\t{\n\t\t\t\t\tconst Attr& v0 = output[(cursor * 3 + 1) * components + j];\n\t\t\t\t\tconst Attr& b0 = output[(cursor * 3 + 2) * components + j];\n\t\t\t\t\tconst Attr& a1 = output[(cursor * 3 + 3) * components + j];\n\t\t\t\t\tconst Attr& v1 = output[(cursor * 3 + 4) * components + j];\n\t\t\t\t\tdata.push_back(interpolateHermite(v0, b0, v1, a1, t, range, type));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tassert(!\"Unknown interpolation type\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsize_t offset = (interpolation == cgltf_interpolation_type_cubic_spline) ? cursor * 3 + 1 : cursor;\n\n\t\t\tfor (size_t j = 0; j < components; ++j)\n\t\t\t{\n\t\t\t\tconst Attr& v = output[offset * components + j];\n\t\t\t\tdata.push_back(v);\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic bool isTrackEqual(const std::vector<Attr>& data, cgltf_animation_path_type type, int frames, const Attr* value, size_t components)\n{\n\tassert(data.size() == frames * components);\n\n\tfloat tolerance = getDeltaTolerance(type);\n\n\tfor (int i = 0; i < frames; ++i)\n\t{\n\t\tfor (size_t j = 0; j < components; ++j)\n\t\t{\n\t\t\tfloat delta = getDelta(value[j], data[i * components + j], type);\n\n\t\t\tif (delta > tolerance)\n\t\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstatic void getBaseTransform(Attr* result, size_t components, cgltf_animation_path_type type, cgltf_node* node)\n{\n\tswitch (type)\n\t{\n\tcase cgltf_animation_path_type_translation:\n\t\tmemcpy(result->f, node->translation, 3 * sizeof(float));\n\t\tbreak;\n\n\tcase cgltf_animation_path_type_rotation:\n\t\tmemcpy(result->f, node->rotation, 4 * sizeof(float));\n\t\tbreak;\n\n\tcase cgltf_animation_path_type_scale:\n\t\tmemcpy(result->f, node->scale, 3 * sizeof(float));\n\t\tbreak;\n\n\tcase cgltf_animation_path_type_weights:\n\t\tif (node->weights_count)\n\t\t{\n\t\t\tassert(node->weights_count == components);\n\t\t\tmemcpy(result->f, node->weights, components * sizeof(float));\n\t\t}\n\t\telse if (node->mesh && node->mesh->weights_count)\n\t\t{\n\t\t\tassert(node->mesh->weights_count == components);\n\t\t\tmemcpy(result->f, node->mesh->weights, components * sizeof(float));\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tassert(!\"Unknown animation path\");\n\t}\n}\n\nvoid processAnimation(Animation& animation, const Settings& settings)\n{\n\tfloat mint = FLT_MAX, maxt = 0;\n\n\tfor (size_t i = 0; i < animation.tracks.size(); ++i)\n\t{\n\t\tconst Track& track = animation.tracks[i];\n\t\tassert(!track.time.empty());\n\n\t\tmint = std::min(mint, track.time.front());\n\t\tmaxt = std::max(maxt, track.time.back());\n\t}\n\n\tmint = std::min(mint, maxt);\n\n\t\/\/ round the number of frames to nearest but favor the \"up\" direction\n\t\/\/ this means that at 10 Hz resampling, we will try to preserve the last frame <10ms\n\t\/\/ but if the last frame is <2ms we favor just removing this data\n\tint frames = 1 + int((maxt - mint) * settings.anim_freq + 0.8f);\n\n\tanimation.start = mint;\n\tanimation.frames = frames;\n\n\tstd::vector<Attr> base;\n\n\tfor (size_t i = 0; i < animation.tracks.size(); ++i)\n\t{\n\t\tTrack& track = animation.tracks[i];\n\n\t\tstd::vector<Attr> result;\n\t\tresampleKeyframes(result, track.time, track.data, track.path, track.interpolation, track.components, frames, mint, settings.anim_freq);\n\n\t\ttrack.time.clear();\n\t\ttrack.data.swap(result);\n\n\t\tif (isTrackEqual(track.data, track.path, frames, &track.data[0], track.components))\n\t\t{\n\t\t\t\/\/ track is constant (equal to first keyframe), we only need the first keyframe\n\t\t\ttrack.data.resize(track.components);\n\n\t\t\t\/\/ track.dummy is true iff track redundantly sets up the value to be equal to default node transform\n\t\t\tbase.resize(track.components);\n\t\t\tgetBaseTransform(&base[0], track.components, track.path, track.node);\n\n\t\t\ttrack.dummy = isTrackEqual(track.data, track.path, 1, &base[0], track.components);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (C) 2013 Aldebaran Robotics\n *\/\n\n#include <string>\n\n#include <boost\/program_options.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/foreach.hpp>\n\n#include <qi\/log.hpp>\n#include <qi\/detail\/log.hxx>\n\n#include <qi\/applicationsession.hpp>\n#include <qicore\/logmessage.hpp>\n#include <qicore\/logmanager.hpp>\n#include <qicore\/loglistener.hpp>\n\n#include \"qicli.hpp\"\n\n#define foreach BOOST_FOREACH\n\nqiLogCategory(\"qicli.qilog\");\n\nstatic void onMessage(const qi::LogMessage& msg)\n{\n std::stringstream ss;\n ss << qi::log::logLevelToString(static_cast<qi::LogLevel>(msg.level))\n << \" \" << msg.category\n << \" \" << msg.source\n << \" \" << msg.message;\n std::cout << ss.str() << std::endl;\n}\n\nstatic void setFilter(const std::string& rules, qi::LogListenerPtr listener)\n{\n std::string cat;\n qi::LogLevel level;\n for (auto &&p: qi::log::detail::parseFilterRules(rules))\n {\n std::tie(cat, level) = std::move(p);\n listener->addFilter(cat, level);\n }\n}\n\nint subCmd_logView(int argc, char **argv, qi::ApplicationSession& app)\n{\n po::options_description desc(\"Usage: qicli log-view\");\n\n desc.add_options()\n (\"help,h\", \"Print this help message and exit\")\n (\"verbose,v\", \"Set maximum logs verbosity shown to verbose.\")\n (\"debug,d\", \"Set maximum logs verbosity shown to debug.\")\n (\"level,l\", po::value<int>()->default_value(4), \"Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.\")\n (\"filters,f\", po::value<std::string>(), \"Set log filtering options. This option accepts the same arguments' format than --qi-log-filters.\")\n ;\n\n po::variables_map vm;\n if (!poDefault(po::command_line_parser(argc, argv).options(desc), vm, desc))\n return 1;\n\n qiLogVerbose() << \"Connecting to service directory\";\n app.startSession();\n qi::SessionPtr s = app.session();\n\n qiLogVerbose() << \"Resolving services\";\n\n app.loadModule(\"qicore\");\n qi::LogManagerPtr logger = app.session()->service(\"LogManager\");\n qi::LogListenerPtr listener = logger->createListener();\n listener->clearFilters();\n\n if (vm.count(\"level\"))\n {\n int level = vm[\"level\"].as<int>();\n\n if (level > 6)\n level = 6;\n else if (level <= 0)\n level = 0;\n\n listener->addFilter(\"*\", static_cast<qi::LogLevel>(level));\n }\n\n if (vm.count(\"verbose\"))\n listener->addFilter(\"*\", qi::LogLevel_Verbose);\n\n if (vm.count(\"debug\"))\n listener->addFilter(\"*\", qi::LogLevel_Debug);\n\n if (vm.count(\"filters\"))\n {\n std::string filters = vm[\"filters\"].as<std::string>();\n setFilter(filters, listener);\n }\n\n listener->onLogMessage.connect(&onMessage);\n app.run();\n\n return 0;\n}\n\nint subCmd_logSend(int argc, char **argv, qi::ApplicationSession& app)\n{\n po::options_description desc(\"Usage: qicli log-send <message>\");\n\n desc.add_options()\n (\"help,h\", \"Print this help message and exit\")\n (\"verbose,v\", \"Set sent message verbosity to verbose.\")\n (\"debug,d\", \"Set sent message verbosity to debug.\")\n (\"level,l\", po::value<int>()->default_value(4), \"Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.\")\n (\"category,c\", po::value<std::string>(), \"Message's category (default: \\\"qicli.qilog.logsend\\\").\")\n (\"message,m\", po::value<std::string>(), \"Message to send.\")\n ;\n\n po::positional_options_description positionalOptions;\n positionalOptions.add(\"message\", -1);\n\n po::variables_map vm;\n if (!poDefault(po::command_line_parser(argc, argv)\n .options(desc).positional(positionalOptions), vm, desc))\n return 1;\n\n qiLogVerbose() << \"Connecting to service directory\";\n app.startSession();\n qi::SessionPtr s = app.session();\n\n qiLogVerbose() << \"Resolving services\";\n\n qi::AnyObject logger = s->service(\"LogManager\");\n\n qi::os::timeval tv(qi::SystemClock::now());\n\n std::string source(__FILE__);\n source += ':';\n source += __FUNCTION__;\n source += ':';\n source += boost::lexical_cast<std::string>(__LINE__);\n\n int level = 4;\n if (vm.count(\"level\"))\n {\n level = vm[\"level\"].as<int>();\n\n if (level > 6)\n level = 6;\n else if (level <= 0)\n level = 0;\n }\n if (vm.count(\"verbose\"))\n level = 5;\n\n if (vm.count(\"debug\"))\n level = 6;\n\n std::string category = \"qicli.qilog.logsend\";\n if (vm.count(\"category\"))\n category = vm[\"category\"].as<std::string>();\n\n std::string location = qi::os::getMachineId() + \":\" + boost::lexical_cast<std::string>(qi::os::getpid());;\n std::string message = \"\";\n if (vm.count(\"message\"))\n message = vm[\"message\"].as<std::string>();\n\n \/\/ timestamp\n qi::AnyReferenceVector timeVectRef;\n timeVectRef.push_back(qi::AnyReference::from(tv.tv_sec));\n timeVectRef.push_back(qi::AnyReference::from(tv.tv_usec));\n qi::AnyValue timeVal = qi::AnyValue::makeTuple(timeVectRef);\n\n qi::AnyReferenceVector msgVectRef;\n msgVectRef.push_back(qi::AnyReference::from(source));\n msgVectRef.push_back(qi::AnyReference::from(level));\n msgVectRef.push_back(timeVal.asReference()); \/\/timestamp\n msgVectRef.push_back(qi::AnyReference::from(category));\n msgVectRef.push_back(qi::AnyReference::from(location));\n msgVectRef.push_back(qi::AnyReference::from(message));\n msgVectRef.push_back(qi::AnyReference::from(0));\n\n std::vector<qi::AnyValue> msgs;\n msgs.push_back(qi::AnyValue::makeTuple(msgVectRef));\n logger.call<void>(\"log\", qi::AnyValue::from(msgs));\n\n logger.reset();\n\n return 0;\n}\n<commit_msg>Rewrite qicli log-send using qicore type<commit_after>\/**\n * Copyright (C) 2013 Aldebaran Robotics\n *\/\n\n#include <string>\n\n#include <boost\/program_options.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/foreach.hpp>\n\n#include <qi\/log.hpp>\n#include <qi\/detail\/log.hxx>\n\n#include <qi\/applicationsession.hpp>\n#include <qi\/anymodule.hpp>\n#include <qicore\/logmessage.hpp>\n#include <qicore\/logmanager.hpp>\n#include <qicore\/loglistener.hpp>\n\n#include \"qicli.hpp\"\n\n#define foreach BOOST_FOREACH\n\nqiLogCategory(\"qicli.qilog\");\n\nstatic void onMessage(const qi::LogMessage& msg)\n{\n std::stringstream ss;\n ss << qi::log::logLevelToString(static_cast<qi::LogLevel>(msg.level))\n << \" \" << msg.category\n << \" \" << msg.source\n << \" \" << msg.message;\n std::cout << ss.str() << std::endl;\n}\n\nstatic void setFilter(const std::string& rules, qi::LogListenerPtr listener)\n{\n std::string cat;\n qi::LogLevel level;\n for (auto &&p: qi::log::detail::parseFilterRules(rules))\n {\n std::tie(cat, level) = std::move(p);\n listener->addFilter(cat, level);\n }\n}\n\nint subCmd_logView(int argc, char **argv, qi::ApplicationSession& app)\n{\n po::options_description desc(\"Usage: qicli log-view\");\n\n desc.add_options()\n (\"help,h\", \"Print this help message and exit\")\n (\"verbose,v\", \"Set maximum logs verbosity shown to verbose.\")\n (\"debug,d\", \"Set maximum logs verbosity shown to debug.\")\n (\"level,l\", po::value<int>()->default_value(4), \"Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.\")\n (\"filters,f\", po::value<std::string>(), \"Set log filtering options. This option accepts the same arguments' format than --qi-log-filters.\")\n ;\n\n po::variables_map vm;\n if (!poDefault(po::command_line_parser(argc, argv).options(desc), vm, desc))\n return 1;\n\n qiLogVerbose() << \"Connecting to service directory\";\n app.startSession();\n qi::SessionPtr s = app.session();\n\n qiLogVerbose() << \"Resolving services\";\n\n app.loadModule(\"qicore\");\n qi::LogManagerPtr logger = app.session()->service(\"LogManager\");\n qi::LogListenerPtr listener = logger->createListener();\n listener->clearFilters();\n\n if (vm.count(\"level\"))\n {\n int level = vm[\"level\"].as<int>();\n\n if (level > 6)\n level = 6;\n else if (level <= 0)\n level = 0;\n\n listener->addFilter(\"*\", static_cast<qi::LogLevel>(level));\n }\n\n if (vm.count(\"verbose\"))\n listener->addFilter(\"*\", qi::LogLevel_Verbose);\n\n if (vm.count(\"debug\"))\n listener->addFilter(\"*\", qi::LogLevel_Debug);\n\n if (vm.count(\"filters\"))\n {\n std::string filters = vm[\"filters\"].as<std::string>();\n setFilter(filters, listener);\n }\n\n listener->onLogMessage.connect(&onMessage);\n app.run();\n\n return 0;\n}\n\nint subCmd_logSend(int argc, char **argv, qi::ApplicationSession& app)\n{\n po::options_description desc(\"Usage: qicli log-send <message>\");\n\n desc.add_options()\n (\"help,h\", \"Print this help message and exit\")\n (\"verbose,v\", \"Set sent message verbosity to verbose.\")\n (\"debug,d\", \"Set sent message verbosity to debug.\")\n (\"level,l\", po::value<int>()->default_value(4), \"Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.\")\n (\"category,c\", po::value<std::string>(), \"Message's category (default: \\\"qicli.qilog.logsend\\\").\")\n (\"message,m\", po::value<std::string>(), \"Message to send.\")\n ;\n\n po::positional_options_description positionalOptions;\n positionalOptions.add(\"message\", -1);\n\n po::variables_map vm;\n if (!poDefault(po::command_line_parser(argc, argv)\n .options(desc).positional(positionalOptions), vm, desc))\n return 1;\n\n qiLogVerbose() << \"Connecting to service directory\";\n app.startSession();\n qi::SessionPtr s = app.session();\n\n qiLogVerbose() << \"Resolving services\";\n\n \/\/ import module\n qi::AnyModule mod = qi::import(\"qicore\");\n\n \/\/ get service Logger\n qi::LogManagerPtr logger = app.session()->service(\"LogManager\");\n\n qi::LogMessage msg;\n\n msg.source = __FILE__;\n msg.source += ':';\n msg.source += __FUNCTION__;\n msg.source += ':';\n msg.source += boost::lexical_cast<std::string>(__LINE__);\n\n msg.level = qi::LogLevel_Info;\n if (vm.count(\"level\"))\n {\n int level = vm[\"level\"].as<int>();\n\n if (level > 6)\n level = qi::LogLevel_Debug;\n else if (level <= 0)\n level = qi::LogLevel_Silent;\n\n msg.level = static_cast<qi::LogLevel>(level);\n }\n if (vm.count(\"verbose\"))\n msg.level = qi::LogLevel_Verbose;\n\n if (vm.count(\"debug\"))\n msg.level = qi::LogLevel_Debug;\n\n msg.category = \"qicli.qilog.logsend\";\n if (vm.count(\"category\"))\n msg.category = vm[\"category\"].as<std::string>();\n\n msg.location = qi::os::getMachineId() + \":\" + boost::lexical_cast<std::string>(qi::os::getpid());\n\n if (vm.count(\"message\"))\n msg.message = vm[\"message\"].as<std::string>();\n\n msg.date = qi::Clock::now();\n msg.systemDate = qi::SystemClock::now();\n\n std::vector<qi::LogMessage> msgs;\n msgs.push_back(msg);\n logger->log(msgs);\n\n logger.reset();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This source file is part of Hect.\n\/\/\n\/\/ Copyright (c) 2015 Colin Hill\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\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell 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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"DebugSystem.h\"\n\n#include \"Hect\/Interface\/Widgets\/CheckBox.h\"\n#include \"Hect\/Interface\/Widgets\/Grid.h\"\n#include \"Hect\/Interface\/Widgets\/Label.h\"\n#include \"Hect\/Logic\/Systems\/RenderSystem.h\"\n#include \"Hect\/Runtime\/Engine.h\"\n\nusing namespace hect;\n\nDebugSystem::DebugSystem(Engine& engine, Scene& scene) :\n System(engine, scene, SystemTickStage::Precedent),\n _renderer(engine.renderer()),\n _window(engine.window()),\n _interfaceSystem(scene.system<InterfaceSystem>())\n{\n}\n\nvoid DebugSystem::renderBox(DebugColor color, const Box& box, const Vector3& position, const Quaternion& rotation)\n{\n _boxes.emplace_back(box, position, rotation, color);\n}\n\nvoid DebugSystem::addRenderCalls(RenderSystem& renderSystem)\n{\n for (DebugBox& box : _boxes)\n {\n renderSystem.addRenderCall(box.transform, *boxMesh, _coloredMaterials[static_cast<size_t>(box.color)]);\n }\n}\n\nvoid DebugSystem::toggleShowInterface()\n{\n if (_systemPanel)\n {\n bool visible = _systemPanel->isVisible();\n _systemPanel->setVisible(!visible);\n }\n}\n\nvoid DebugSystem::initialize()\n{\n addColoredMaterial(Color(100, 0, 0)); \/\/ Primary\n addColoredMaterial(Color(0, 100, 0)); \/\/ Secondary\n addColoredMaterial(Color(0, 0, 100)); \/\/ Tertiary\n\n _renderer.uploadShader(*coloredLineShader);\n _renderer.uploadMesh(*boxMesh);\n\n if (_interfaceSystem)\n {\n createSystemPanel();\n }\n}\n\nvoid DebugSystem::tick(double timeStep)\n{\n (void)timeStep;\n _boxes.clear();\n}\n\nDebugSystem::DebugBox::DebugBox()\n{\n}\n\nDebugSystem::DebugBox::DebugBox(const Box& box, const Vector3& position, const Quaternion& rotation, DebugColor color) :\n box(box),\n color(color)\n{\n transform.globalPosition = position;\n transform.globalScale = box.scale();\n transform.globalRotation = rotation;\n}\n\nvoid DebugSystem::addColoredMaterial(const Color& color)\n{\n \/\/ Create a material for this color\n Material material;\n material.setShader(coloredLineShader);\n material.setUniformValue(\"color\", color);\n\n _coloredMaterials.push_back(material);\n}\n\nvoid DebugSystem::createSystemPanel()\n{\n const double checkBoxColumnWidth = 16;\n const double rowHeight = 18;\n const double panelMargin = 10;\n\n Grid::Handle grid = _interfaceSystem->addWidget<Grid>();\n grid->setHorizontalAlign(HorizontalAlign::Center);\n grid->setVerticalAlign(VerticalAlign::Center);\n\n Grid::ColumnId checkBoxColumnId = grid->addColumn(checkBoxColumnWidth);\n Grid::ColumnId systemNameColumnId = grid->addColumn();\n\n double maxSystemNameLength = 0;\n\n SystemRegistry::SystemTypeIdSequence typeIds = SystemRegistry::typeIds();\n for (SystemTypeId typeId : typeIds)\n {\n Grid::RowId rowId = grid->addRow(rowHeight);\n\n const std::string& systemName = SystemRegistry::typeNameOf(typeId);\n\n CheckBox::Handle checkBox = _interfaceSystem->addWidget<CheckBox>();\n checkBox->setHorizontalAlign(HorizontalAlign::Center);\n checkBox->setVerticalAlign(VerticalAlign::Center);\n checkBox->setPressAction([this, typeId, checkBox]\n {\n SystemBase& system = scene().systemOfTypeId(typeId);\n system.setDebugEnabled(checkBox->isChecked());\n });\n grid->setCell(checkBoxColumnId, rowId, checkBox);\n\n Label::Handle label = _interfaceSystem->addWidget<Label>();\n label->setText(systemName);\n label->setHorizontalAlign(HorizontalAlign::Left);\n label->setVerticalAlign(VerticalAlign::Bottom);\n grid->setCell(systemNameColumnId, rowId, label);\n\n maxSystemNameLength = std::max(maxSystemNameLength, label->dimensions().x);\n }\n\n grid->resizeColumn(systemNameColumnId, maxSystemNameLength);\n\n _systemPanel = _interfaceSystem->addWidget<Panel>();\n _systemPanel->setDimensions(grid->dimensions() + panelMargin);\n _systemPanel->addChild(grid);\n\n Vector2 windowDimensions(_window.width(), _window.height());\n Vector2 systemPanelPosition = windowDimensions * 0.5 - _systemPanel->dimensions() * 0.5;\n _systemPanel->setPosition(systemPanelPosition);\n\n _systemPanel->setVisible(false);\n}\n<commit_msg>Make systems ordered alphabetically in debug system UI<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This source file is part of Hect.\n\/\/\n\/\/ Copyright (c) 2015 Colin Hill\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\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell 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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"DebugSystem.h\"\n\n#include \"Hect\/Interface\/Widgets\/CheckBox.h\"\n#include \"Hect\/Interface\/Widgets\/Grid.h\"\n#include \"Hect\/Interface\/Widgets\/Label.h\"\n#include \"Hect\/Logic\/Systems\/RenderSystem.h\"\n#include \"Hect\/Runtime\/Engine.h\"\n\nusing namespace hect;\n\nDebugSystem::DebugSystem(Engine& engine, Scene& scene) :\n System(engine, scene, SystemTickStage::Precedent),\n _renderer(engine.renderer()),\n _window(engine.window()),\n _interfaceSystem(scene.system<InterfaceSystem>())\n{\n}\n\nvoid DebugSystem::renderBox(DebugColor color, const Box& box, const Vector3& position, const Quaternion& rotation)\n{\n _boxes.emplace_back(box, position, rotation, color);\n}\n\nvoid DebugSystem::addRenderCalls(RenderSystem& renderSystem)\n{\n for (DebugBox& box : _boxes)\n {\n renderSystem.addRenderCall(box.transform, *boxMesh, _coloredMaterials[static_cast<size_t>(box.color)]);\n }\n}\n\nvoid DebugSystem::toggleShowInterface()\n{\n if (_systemPanel)\n {\n bool visible = _systemPanel->isVisible();\n _systemPanel->setVisible(!visible);\n }\n}\n\nvoid DebugSystem::initialize()\n{\n addColoredMaterial(Color(100, 0, 0)); \/\/ Primary\n addColoredMaterial(Color(0, 100, 0)); \/\/ Secondary\n addColoredMaterial(Color(0, 0, 100)); \/\/ Tertiary\n\n _renderer.uploadShader(*coloredLineShader);\n _renderer.uploadMesh(*boxMesh);\n\n if (_interfaceSystem)\n {\n createSystemPanel();\n }\n}\n\nvoid DebugSystem::tick(double timeStep)\n{\n (void)timeStep;\n _boxes.clear();\n}\n\nDebugSystem::DebugBox::DebugBox()\n{\n}\n\nDebugSystem::DebugBox::DebugBox(const Box& box, const Vector3& position, const Quaternion& rotation, DebugColor color) :\n box(box),\n color(color)\n{\n transform.globalPosition = position;\n transform.globalScale = box.scale();\n transform.globalRotation = rotation;\n}\n\nvoid DebugSystem::addColoredMaterial(const Color& color)\n{\n Material material;\n material.setShader(coloredLineShader);\n material.setUniformValue(\"color\", color);\n\n _coloredMaterials.push_back(material);\n}\n\nvoid DebugSystem::createSystemPanel()\n{\n const double checkBoxColumnWidth = 16;\n const double rowHeight = 18;\n const double panelMargin = 10;\n\n Grid::Handle grid = _interfaceSystem->addWidget<Grid>();\n grid->setHorizontalAlign(HorizontalAlign::Center);\n grid->setVerticalAlign(VerticalAlign::Center);\n\n Grid::ColumnId checkBoxColumnId = grid->addColumn(checkBoxColumnWidth);\n Grid::ColumnId systemNameColumnId = grid->addColumn();\n\n double maxSystemNameLength = 0;\n\n SystemRegistry::SystemTypeIdSequence typeIds = SystemRegistry::typeIds();\n std::sort(typeIds.begin(), typeIds.end(), [] (SystemTypeId a, SystemTypeId b)\n {\n return SystemRegistry::typeNameOf(a) < SystemRegistry::typeNameOf(b);\n });\n\n for (SystemTypeId typeId : typeIds)\n {\n Grid::RowId rowId = grid->addRow(rowHeight);\n\n const std::string& systemName = SystemRegistry::typeNameOf(typeId);\n\n CheckBox::Handle checkBox = _interfaceSystem->addWidget<CheckBox>();\n checkBox->setHorizontalAlign(HorizontalAlign::Center);\n checkBox->setVerticalAlign(VerticalAlign::Center);\n checkBox->setPressAction([this, typeId, checkBox]\n {\n SystemBase& system = scene().systemOfTypeId(typeId);\n system.setDebugEnabled(checkBox->isChecked());\n });\n grid->setCell(checkBoxColumnId, rowId, checkBox);\n\n Label::Handle label = _interfaceSystem->addWidget<Label>();\n label->setText(systemName);\n label->setHorizontalAlign(HorizontalAlign::Left);\n label->setVerticalAlign(VerticalAlign::Bottom);\n grid->setCell(systemNameColumnId, rowId, label);\n\n maxSystemNameLength = std::max(maxSystemNameLength, label->dimensions().x);\n }\n\n grid->resizeColumn(systemNameColumnId, maxSystemNameLength);\n\n _systemPanel = _interfaceSystem->addWidget<Panel>();\n _systemPanel->setDimensions(grid->dimensions() + panelMargin);\n _systemPanel->addChild(grid);\n\n Vector2 windowDimensions(_window.width(), _window.height());\n Vector2 systemPanelPosition = windowDimensions * 0.5 - _systemPanel->dimensions() * 0.5;\n _systemPanel->setPosition(systemPanelPosition);\n\n _systemPanel->setVisible(false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\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#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbStreamingStatisticsVectorImageFilter.h\"\n#include \"otbEigenvalueLikelihoodMaximisation.h\"\n#include \"otbVcaImageFilter.h\"\n#include \"otbUnConstrainedLeastSquareImageFilter.h\"\n\n#include \"otbVectorImageToMatrixImageFilter.h\"\n\nint main(int argc, char * argv[])\n{\n if (argc != 3)\n {\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \"inputFileName outputFileName \" << std::endl;\n return EXIT_FAILURE;\n }\n\n const char * infname = argv[1];\n const char * outfname = argv[2];\n const unsigned int Dimension = 2;\n\n typedef double PixelType;\n typedef otb::VectorImage<PixelType, Dimension> ImageType;\n \n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::ImageFileWriter<FloatImageType> WriterType;\n \n typedef otb::StreamingStatisticsVectorImageFilter<ImageType> StreamingStatisticsVectorImageFilterType;\n typedef otb::EigenvalueLikelihoodMaximisation<double> ELMType;\n typedef otb::VCAImageFilter<ImageType> VCAFilterType;\n\n typedef otb::UnConstrainedLeastSquareImageFilter<ImageType,ImageType,double> UCLSUnmixingFilterType;\n\n typedef otb::VectorImageToMatrixImageFilter<ImageType> VectorImageToMatrixImageFilterType;\n\n typedef vnl_vector<double> VectorType;\n typedef vnl_matrix<double> MatrixType;\n\n\/\/\/ \/ Noise filtering\n \/\/ typedef otb::LocalActivityVectorImageFilter< ImageType, ImageType > NoiseFilterType;\n\n \/\/ \/\/ Image filtering\n \/\/ typedef otb::MNFImageFilter< ImageType, ImageType,\n \/\/ NoiseFilterType, otb::Transform::FORWARD > FilterType;\n\n \/\/read image\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(infname);\n reader->UpdateOutputInformation();\n\n std::cout << \"Computing stats\" << std::endl;\n\n StreamingStatisticsVectorImageFilterType::Pointer stats = StreamingStatisticsVectorImageFilterType::New();\n\n stats->SetInput(reader->GetOutput());\n otb::StandardWriterWatcher watcher(stats->GetStreamer(), stats->GetFilter(), \"Computing image stats\");\n stats->Update();\n\n VectorType mean (stats->GetMean().GetDataPointer(), stats->GetMean().GetSize());\n MatrixType covariance = stats->GetCovariance().GetVnlMatrix();\n MatrixType correlation = stats->GetCorrelation().GetVnlMatrix();\n\n \/*\n * Estimate Endmembers Numbers\n *\/\n std::cout << \"Estimate Endmembers Numbers by ELM\" << std::endl;\n\n ELMType::Pointer elm = ELMType::New();\n elm->SetCovariance(covariance);\n elm->SetCorrelation(correlation);\n elm->SetNumberOfPixels(reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels());\n elm->Compute();\n\n const unsigned int nbEndmembers = elm->GetNumberOfEndmembers();\n\n std::cout << \"ELM : \" << nbEndmembers << \" estimated endmembers\" << std::endl;\n\n std::cout << \"ELM likelihood values: \" << elm->GetLikelihood() << std::endl;\n \n\n\/*\n * Estimate Endmembers\n *\/\n std::cout << \"Estimate Endmembers by VCA\" << std::endl;\n\n VCAFilterType::Pointer vca = VCAFilterType::New();\n vca->SetNumberOfEndmembers(nbEndmembers);\n vca->SetInput(reader->GetOutput());\n\n ImageType::Pointer endmembersImage;\n endmembersImage = vca->GetOutput();\n\n \/*\n * Transform Endmembers image to matrix representation\n *\/\n std::cout << \"Endmembers extracted\" << std::endl;\n std::cout << \"Converting endmembers to matrix\" << std::endl;\n VectorImageToMatrixImageFilterType::Pointer endMember2Matrix = VectorImageToMatrixImageFilterType::New();\n endMember2Matrix->SetInput(endmembersImage);\n endMember2Matrix->Update();\n\n MatrixType endMembersMatrix = endMember2Matrix->GetMatrix();\n std::cout << \"Endmembers matrix : \" << endMembersMatrix << std::endl;\n\n \/*\n * Unmix\n *\/\n UCLSUnmixingFilterType::Pointer unmixer =\n UCLSUnmixingFilterType::New();\n\n unmixer->SetInput(reader->GetOutput());\n unmixer->SetMatrix(endMembersMatrix);\n unmixer->SetNumberOfThreads(1); \/\/ FIXME : currently buggy\n \n ImageType::Pointer abundanceMap;\n abundanceMap = unmixer->GetOutput();\n \n \/*\n * Write abundance map\n *\/\n std::cout << \"Write abundance map \" << outfname << std::endl;\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetInput(abundanceMap);\n writer->SetFileName(outfname);\n \n writer->Update();\n\n return EXIT_SUCCESS;\n} \/\/ end main\n<commit_msg>WPI:change example to display 3 abundance map bands<commit_after>\/*=========================================================================\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#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbStreamingStatisticsVectorImageFilter.h\"\n#include \"otbVcaImageFilter.h\"\n#include \"otbUnConstrainedLeastSquareImageFilter.h\"\n#include \"otbVectorRescaleIntensityImageFilter.h\"\n#include \"otbVectorImageToMatrixImageFilter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n#include \"otbVectorRescaleIntensityImageFilter.h\"\n#include \"otbMultiToMonoChannelExtractROI.h\"\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {ROI_QB_MUL_1.png}\n\/\/ OUTPUTS: {PCAOutput.tif}, {InversePCAOutput.tif}, {InversePCAOutput1.png}, {PCAOutput1.png}, {PCAOutput2.png}, {PCAOutput3.png}\n\/\/ 3\n\/\/ Software Guide : EndCommandLineArgs\nint main(int argc, char * argv[])\n{\n if (argc != 5)\n {\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \"inputFileName outputFileName EstimatenumberOfEndmembers outputPrettyFilename1 outputPrettyFilename2 outputPrettyFilename3 \" << std::endl;\n return EXIT_FAILURE;\n }\n\n const char * infname = argv[1];\n const char * outfname = argv[2];\n const unsigned int estimateNumberOfEndmembers = atoi(argv[3]);\n const unsigned int Dimension = 2;\n\n typedef double PixelType;\n typedef otb::VectorImage<PixelType, Dimension> ImageType;\n typedef otb::VectorImage<unsigned char, 2> OutputPrettyImageType;\n\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::ImageFileWriter<ImageType> WriterType;\n \n typedef otb::VectorRescaleIntensityImageFilter<ImageType,ImageType> RescalerType;\n typedef otb::VectorRescaleIntensityImageFilter<ImageType,OutputPrettyImageType> RescalerType2;\n \n typedef otb::StreamingStatisticsVectorImageFilter<ImageType> StreamingStatisticsVectorImageFilterType;\n typedef otb::VCAImageFilter<ImageType> VCAFilterType;\n\n typedef otb::UnConstrainedLeastSquareImageFilter<ImageType,ImageType,double> UCLSUnmixingFilterType;\n\n typedef otb::VectorImageToMatrixImageFilter<ImageType> VectorImageToMatrixImageFilterType;\n\n typedef vnl_vector<double> VectorType;\n typedef vnl_matrix<double> MatrixType;\n\n \/\/\/ \/ Noise filtering\n \/\/ typedef otb::LocalActivityVectorImageFilter< ImageType, ImageType > NoiseFilterType;\n\n \/\/ \/\/ Image filtering\n \/\/ typedef otb::MNFImageFilter< ImageType, ImageType,\n \/\/ NoiseFilterType, otb::Transform::FORWARD > FilterType;\n\n \/\/read image\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(infname);\n reader->UpdateOutputInformation();\n \n\n \/\/rescale input image between 0 and 1\n RescalerType::Pointer rescaler = RescalerType::New();\n rescaler->SetInput(reader->GetOutput());\n rescaler->SetOutputMinimum(0);\n rescaler->SetOutputMaximum(1.);\n \/*\n * Estimate Endmembers\n *\/\n std::cout << \"Estimate Endmembers by VCA\" << std::endl;\n\n VCAFilterType::Pointer vca = VCAFilterType::New();\n vca->SetNumberOfEndmembers(estimateNumberOfEndmembers);\n vca->SetInput(rescaler->GetOutput());\n\n ImageType::Pointer endmembersImage;\n endmembersImage = vca->GetOutput();\n\n \/*\n * Transform Endmembers image to matrix representation\n *\/\n std::cout << \"Endmembers extracted\" << std::endl;\n std::cout << \"Converting endmembers to matrix\" << std::endl;\n VectorImageToMatrixImageFilterType::Pointer endMember2Matrix = VectorImageToMatrixImageFilterType::New();\n endMember2Matrix->SetInput(endmembersImage);\n endMember2Matrix->Update();\n\n MatrixType endMembersMatrix = endMember2Matrix->GetMatrix();\n std::cout << \"Endmembers matrix : \" << endMembersMatrix << std::endl;\n\n \/*\n * Unmix\n *\/\n UCLSUnmixingFilterType::Pointer unmixer =\n UCLSUnmixingFilterType::New();\n\n unmixer->SetInput(rescaler->GetOutput());\n unmixer->SetMatrix(endMembersMatrix);\n unmixer->SetNumberOfThreads(1); \/\/ FIXME : currently buggy\n \n ImageType::Pointer abundanceMap;\n abundanceMap = unmixer->GetOutput();\n \n \/*\n * Write abundance map\n *\/\n std::cout << \"Write abundance map \" << outfname << std::endl;\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetInput(abundanceMap);\n writer->SetFileName(outfname);\n \n writer->Update();\n \n typedef otb::Image<PixelType, Dimension> MonoImageType;\n typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> ExtractROIFilterType;\n typedef otb::Image<unsigned char, 2> OutputImageType;\n typedef itk::RescaleIntensityImageFilter<MonoImageType,\n OutputImageType> PrettyRescalerType;\n typedef otb::ImageFileWriter<OutputImageType> WriterType2;\n\n for (unsigned int cpt = 0; cpt < 3; ++cpt)\n {\n ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();\n PrettyRescalerType::Pointer prettyRescaler = PrettyRescalerType::New();\n WriterType2::Pointer writer2 = WriterType2::New();\n\n extractROIFilter->SetInput(abundanceMap);\n extractROIFilter->SetChannel(cpt + 1);\n\n prettyRescaler->SetInput(extractROIFilter->GetOutput());\n prettyRescaler->SetOutputMinimum(0);\n prettyRescaler->SetOutputMaximum(255);\n\n writer2->SetInput(prettyRescaler->GetOutput());\n writer2->SetFileName(argv[cpt + 4]);\n writer2->Update();\n }\n\n return EXIT_SUCCESS;\n} \/\/ end main\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 0.9.9, packaged on May, 2008.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib 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 GLC-lib 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 GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n*****************************************************************************\/\n\n\/\/! \\file glc_3dstoworld.cpp implementation of the GLC_3dsToWorld class.\n\n#include \"glc_3dstoworld.h\"\n#include <QFileInfo>\n#include <QGLContext>\n\n#include \"glc_mesh2.h\"\n#include \"glc_world.h\"\n#include \"glc_fileformatexception.h\"\n#include \"glc_circle.h\"\n#include \"glc_material.h\"\n\/\/ Lib3ds Header\n#include \"lib3ds\/file.h\"\n#include \"lib3ds\/mesh.h\"\n#include \"lib3ds\/node.h\"\n#include \"lib3ds\/matrix.h\"\n#include \"lib3ds\/material.h\"\n\nGLC_3dsToWorld::GLC_3dsToWorld(const QGLContext *pContext)\n: m_pWorld(NULL)\n, m_FileName()\n, m_pQGLContext(pContext)\n, m_pCurrentMesh(NULL)\n, m_CurVertexIndex(0)\n, m_CurNormalIndex(0)\n, m_pLib3dsFile(NULL)\n, m_Materials()\n, m_MaterialsIndex()\n, m_NextMaterialIndex(0)\n, m_pCurrentMaterial(NULL)\n{\n}\n\nGLC_3dsToWorld::~GLC_3dsToWorld()\n{\n\tclear();\n}\n\n\/\/ Create an GLC_World from an input 3DS File\nGLC_World* GLC_3dsToWorld::CreateWorldFrom3ds(QFile &file)\n{\n\tclear();\n\tm_FileName= file.fileName();\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Test if the file exist and can be opened\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tif (!file.open(QIODevice::ReadOnly))\n\t{\n\t\tQString message(QString(\"GLC_3dsToWorld::CreateWorldFrom3ds File \") + m_FileName + QString(\" doesn't exist\"));\n\t\tGLC_FileFormatException fileFormatException(message, m_FileName);\n\t\tthrow(fileFormatException);\n\t}\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Init member\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tm_pWorld= new GLC_World;\n\t\n\t\/\/Load 3ds File\n\tm_pLib3dsFile=lib3ds_file_load(m_FileName.toStdString().c_str());\n\tif (!m_pLib3dsFile)\n\t{\n\t\tQString message= \"GLC_3dsToWorld::CreateWorldFrom3ds : Loading Failed\";\n\t\tGLC_FileFormatException fileFormatException(message, m_FileName);\n\t\tclear();\n\t\tthrow(fileFormatException);\n\t}\n\t\n\t\/* No nodes? Fabricate nodes to display all the meshes. *\/\n\tif(!m_pLib3dsFile->nodes)\n\t{\n\t\tqDebug() << \"No nodes\";\n\t\tLib3dsMesh *pMesh;\n\t\tLib3dsNode *pNode;\n\t\n\t\tfor(pMesh= m_pLib3dsFile->meshes; pMesh != NULL; pMesh = pMesh->next)\n\t\t{\n\t\t\tpNode= lib3ds_node_new_object();\n\t\t\tstrcpy(pNode->name, pMesh->name);\n\t\t\tpNode->parent_id= LIB3DS_NO_PARENT;\n\t\t\tlib3ds_file_insert_node(m_pLib3dsFile, pNode);\n\t\t}\n\t }\n\t \/\/ Create GLC_Instance with Node\n\t for (Lib3dsNode *pNode=m_pLib3dsFile->nodes; pNode!=0; pNode=pNode->next)\n\t {\n\t\t createMeshes(m_pWorld->rootProduct(), pNode);\n\t }\n\t\n\t\/\/ Free Lib3dsFile and all its ressources\n\tlib3ds_file_free(m_pLib3dsFile);\n\tm_pLib3dsFile= NULL;\n\tif (m_pWorld->collection()->isEmpty())\n\t{\n\t\tQString message= \"GLC_3dsToWorld::CreateWorldFrom3ds : No mesh found !\";\n\t\tGLC_FileFormatException fileFormatException(message, m_FileName);\n\t\tclear();\n\t\tthrow(fileFormatException);\n\t\t\n\t}\n\t\n\treturn m_pWorld;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Private services Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ clear stlToWorld allocate memmory and reset member\nvoid GLC_3dsToWorld::clear()\n{\n\tif (NULL != m_pCurrentMesh)\n\t{\n\t\tdelete m_pCurrentMesh;\n\t\tm_pCurrentMesh= NULL;\n\t}\n\tm_pWorld= NULL;\n\tm_FileName.clear();\n\tm_pCurrentMesh= NULL;\n\tm_CurVertexIndex= 0;\n\tm_CurNormalIndex= 0;\n\tif (NULL != m_pLib3dsFile)\n\t{\n\t\tlib3ds_file_free(m_pLib3dsFile);\n\t\tm_pLib3dsFile= NULL;\n\t}\n\t\n\t\/\/ Remove unused material\n\tQHash<QString, GLC_Material*>::iterator i;\n\tfor (i= m_Materials.begin(); i != m_Materials.end(); ++i)\n\t{\n\t\tif (i.value()->isUnused()) delete i.value();\n\t}\n\tm_Materials.clear();\n\t\/\/ Clear the material index hash table\n\tm_MaterialsIndex.clear();\n\tm_NextMaterialIndex= 0;\n\t\/\/ Set the current material to NULL\n\tm_pCurrentMaterial= NULL;\n\t\n}\n\n\/\/ Create meshes from the 3ds File\nvoid GLC_3dsToWorld::createMeshes(GLC_Product* pProduct, Lib3dsNode* pFatherNode)\n{\n\tGLC_Product* pChildProduct= NULL;\n\tLib3dsMesh *pMesh= NULL;\n\t\n\tif (pFatherNode->type == LIB3DS_OBJECT_NODE)\n\t{\n\t\t\/\/ Check if the node is a mesh or dummy\n\t\tif (strcmp(pFatherNode->name,\"$$$DUMMY\")==0)\n\t\t{\n\t\t\treturn;\n\t\t}\t\t\n\t\tpMesh = lib3ds_file_mesh_by_name(m_pLib3dsFile, pFatherNode->data.object.morph);\n\t if( pMesh == NULL )\n\t {\n\t \tpMesh = lib3ds_file_mesh_by_name(m_pLib3dsFile, pFatherNode->name);\n\t }\n\t \t\n\t GLC_Instance instance(createInstance(pMesh));\t\t \n\t pProduct->addChildPart(instance);\n\t}\n\t\n\t\/\/ If there is a child, create a child product\n\tif (NULL != pFatherNode->childs)\n\t{\n\t\tpChildProduct= pProduct->addNewChildProduct();\n\t\tif (NULL != pMesh)\n\t\t{\n\t\t\tLib3dsMatrix M;\n\t\t\tlib3ds_matrix_copy(M, pMesh->matrix);\n\t\t\tlib3ds_matrix_inv(M);\n\n\t\t\tGLC_Matrix4x4 mat(&M[0][0]);\n\t\t\t\n\t\t\t\/\/pChildProduct->move(mat);\n\t\t}\n\t}\n\t\/\/ Create Childs meshes if exists\n\tfor (Lib3dsNode* pNode= pFatherNode->childs; pNode!=0; pNode= pNode->next)\n\t{\t\n\t\tcreateMeshes(pChildProduct, pNode);\n\t}\n\t\n\n}\n\/\/! Create Instance from a Lib3dsNode\nGLC_Instance GLC_3dsToWorld::createInstance(Lib3dsMesh* p3dsMesh)\n{\n\tGLC_Mesh2 * pMesh= new GLC_Mesh2();\n\tpMesh->setName(p3dsMesh->name);\n\t\/\/ The mesh normals\n\tconst int normalsNumber= p3dsMesh->faces * 3;\n\tLib3dsVector *normalL= static_cast<Lib3dsVector*>(malloc(normalsNumber * sizeof(Lib3dsVector)));\n\tlib3ds_mesh_calculate_normals(p3dsMesh, normalL);\n\t\/\/ Add the normal to the mesh\n\tfor (int i= 0; i < normalsNumber; ++i)\n\t{\n\t\tpMesh->addNormal(i, GLC_Vector3d(normalL[i][0], normalL[i][1], normalL[i][2]));\n\t}\n\tdelete normalL;\n\t\n\t\/\/ Add Vertex to the mesh\n\tconst int vertexNumber= p3dsMesh->points;\n\tfor (int i= 0; i < vertexNumber; ++i)\n\t{\n\t\tpMesh->addVertex(i, GLC_Vector3d(p3dsMesh->pointL[i].pos[0], p3dsMesh->pointL[i].pos[1], p3dsMesh->pointL[i].pos[2]));\n\t}\n\t\n\tint normalIndex= 0;\n\tint textureIndex= 0;\n\t\n\tfor (unsigned int i= 0; i < p3dsMesh->faces; ++i)\n\t{\n\t\t\/\/Add the Normal\n\t\tQVector<int> normal;\n\t\tnormal.append(normalIndex++);\n\t\tnormal.append(normalIndex++);\n\t\tnormal.append(normalIndex++);\n\t\tQVector<int> vertex;\n\t\tLib3dsFace *p3dsFace=&p3dsMesh->faceL[i];\n\t\t\/\/ Load the material\n\t\t\/\/ The material current face index\n\t\tQVector<int> material;\n\t\t\n\t\tif (p3dsFace->material[0])\n\t\t{\n\t\t\tLib3dsMaterial* p3dsMat=lib3ds_file_material_by_name(m_pLib3dsFile, p3dsFace->material);\n\t\t\t\/\/ Check it this material as already been loaded\n\t\t\tconst QString materialName(p3dsFace->material);\n\t\t\tif (!m_Materials.contains(materialName))\n\t\t\t{ \/\/ Material not already loaded, load it\n\t\t\t\tloadMaterial(p3dsMat);\n\t\t\t\t\/\/ Add the loaded material to the mesh\n\t\t\t\tpMesh->addMaterial(m_MaterialsIndex[materialName], m_Materials[materialName]);\n\t\t\t}\n\t\t\t\/\/ Set the current material\n\t\t\tm_pCurrentMaterial= m_Materials[materialName];\n\t\t\t\n\t\t\tconst int index= m_MaterialsIndex[materialName];\n\t\t\tmaterial << index << index << index;\n\t\t}\n\t\telse \/\/ No material\n\t\t{\n\t\t\tif (NULL != m_pCurrentMaterial)\n\t\t\t{\n\t\t\t\tconst int index= m_MaterialsIndex[m_pCurrentMaterial->getName()];\n\t\t\t\tpMesh->addMaterial(index, m_pCurrentMaterial);\n\t\t\t\tmaterial << index << index << index;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmaterial << -1 << -1 << -1;\n\t\t\t}\n\t\t}\n\t\t\/\/ End of loading material\n\t\tvertex << p3dsFace->points[0] << p3dsFace->points[1] << p3dsFace->points[2];\n\t\t\/\/ check if the mesh have texture coordinate\n\t\tif (p3dsMesh->texels > 0)\n\t\t{\n\t\t\tQVector<int> texture;\n\t\t\tfor (int i= 0; i < 3; ++i)\n\t\t\t{\n\t\t\t\t\/\/ Load texture coordinate\n\t\t\t\tfloat x= p3dsMesh->texelL[p3dsFace->points[i]][0];\n\t\t\t\tfloat y= p3dsMesh->texelL[p3dsFace->points[i]][1];\n\t\t\t\tGLC_Vector2d texel(static_cast<double>(x), static_cast<double>(y));\n\t\t\t\ttexture.append(textureIndex);\n\t\t\t\tpMesh->addTextureCoordinate(textureIndex++, texel);\n\t\t\t}\n\t\t\tpMesh->addFace(material, vertex, normal, texture);\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpMesh->addFace(material, vertex, normal);\n\t\t}\n\t\t\n\t}\n\treturn GLC_Instance(pMesh);\n}\n\n\/\/ Load Material\nvoid GLC_3dsToWorld::loadMaterial(Lib3dsMaterial* p3dsMaterial)\n{\n\tGLC_Material* pMaterial= new GLC_Material;\n\t\/\/ Set the material name\n\tconst QString materialName(p3dsMaterial->name);\n\tpMaterial->setName(materialName);\n\t\/\/ Check if there is a texture\n\tif (p3dsMaterial->texture1_map.name[0])\n\t{\n\t\tconst QString textureName(p3dsMaterial->texture1_map.name);\n\t\t\/\/ Retrieve the .3ds file path\n\t\tQFileInfo fileInfo(m_FileName);\n\t\tQString textureFileName(fileInfo.absolutePath() + QDir::separator());\n\t\ttextureFileName.append(textureName);\n\t\tQFile textureFile(textureFileName);\n\t\t\n\t\tif (textureFile.open(QIODevice::ReadOnly))\n\t\t{\n\t\t\t\/\/ Create the texture and assign it to the material\n\t\t\tGLC_Texture *pTexture = new GLC_Texture(m_pQGLContext, textureFile);\n\t\t\tpMaterial->setTexture(pTexture);\n\t\t}\n\t\ttextureFile.close();\n\t}\n\t\/\/ Ambient Color\n\tQColor ambient;\n\tambient.setRgbF(p3dsMaterial->ambient[0], p3dsMaterial->ambient[1], p3dsMaterial->ambient[2]);\n\tambient.setAlphaF(p3dsMaterial->ambient[3]);\n\tpMaterial->setAmbientColor(ambient);\n\t\/\/ Diffuse Color\n\tQColor diffuse;\n\tdiffuse.setRgbF(p3dsMaterial->diffuse[0], p3dsMaterial->diffuse[1], p3dsMaterial->diffuse[2]);\n\tdiffuse.setAlphaF(p3dsMaterial->diffuse[3]);\n\tpMaterial->setDiffuseColor(diffuse);\n\t\/\/ Specular Color\n\tQColor specular;\n\tspecular.setRgbF(p3dsMaterial->specular[0], p3dsMaterial->specular[1], p3dsMaterial->specular[2]);\n\tspecular.setAlphaF(p3dsMaterial->specular[3]);\n\tpMaterial->setSpecularColor(specular);\n\t\/\/ Shininess\n\t\/\/pMaterial->setShininess(pow(2, 10.0 * p3dsMaterial->shininess));\n\t\/\/ Transparency\n\tpMaterial->setTransparency(1.0 - p3dsMaterial->transparency);\n\t\n\t\/\/ Add the material to the hash table\n\tm_Materials.insert(materialName, pMaterial);\n\t\/\/ Add the material index\n\tm_MaterialsIndex.insert(materialName, m_NextMaterialIndex++);\n}\n\n<commit_msg>Fix Node position matrix bug.<commit_after>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 0.9.9, packaged on May, 2008.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib 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 GLC-lib 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 GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n*****************************************************************************\/\n\n\/\/! \\file glc_3dstoworld.cpp implementation of the GLC_3dsToWorld class.\n\n#include \"glc_3dstoworld.h\"\n#include <QFileInfo>\n#include <QGLContext>\n\n#include \"glc_mesh2.h\"\n#include \"glc_world.h\"\n#include \"glc_fileformatexception.h\"\n#include \"glc_circle.h\"\n#include \"glc_material.h\"\n\/\/ Lib3ds Header\n#include \"lib3ds\/file.h\"\n#include \"lib3ds\/mesh.h\"\n#include \"lib3ds\/node.h\"\n#include \"lib3ds\/matrix.h\"\n#include \"lib3ds\/material.h\"\n\nGLC_3dsToWorld::GLC_3dsToWorld(const QGLContext *pContext)\n: m_pWorld(NULL)\n, m_FileName()\n, m_pQGLContext(pContext)\n, m_pCurrentMesh(NULL)\n, m_CurVertexIndex(0)\n, m_CurNormalIndex(0)\n, m_pLib3dsFile(NULL)\n, m_Materials()\n, m_MaterialsIndex()\n, m_NextMaterialIndex(0)\n, m_pCurrentMaterial(NULL)\n{\n}\n\nGLC_3dsToWorld::~GLC_3dsToWorld()\n{\n\tclear();\n}\n\n\/\/ Create an GLC_World from an input 3DS File\nGLC_World* GLC_3dsToWorld::CreateWorldFrom3ds(QFile &file)\n{\n\tclear();\n\tm_FileName= file.fileName();\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Test if the file exist and can be opened\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tif (!file.open(QIODevice::ReadOnly))\n\t{\n\t\tQString message(QString(\"GLC_3dsToWorld::CreateWorldFrom3ds File \") + m_FileName + QString(\" doesn't exist\"));\n\t\tGLC_FileFormatException fileFormatException(message, m_FileName);\n\t\tthrow(fileFormatException);\n\t}\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Init member\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tm_pWorld= new GLC_World;\n\t\n\t\/\/Load 3ds File\n\tm_pLib3dsFile=lib3ds_file_load(m_FileName.toStdString().c_str());\n\tif (!m_pLib3dsFile)\n\t{\n\t\tQString message= \"GLC_3dsToWorld::CreateWorldFrom3ds : Loading Failed\";\n\t\tGLC_FileFormatException fileFormatException(message, m_FileName);\n\t\tclear();\n\t\tthrow(fileFormatException);\n\t}\n\t\n\t\/\/ Create GLC_Instance with Node\n\tfor (Lib3dsNode *pNode=m_pLib3dsFile->nodes; pNode!=0; pNode=pNode->next)\n\t{\n\t\tcreateMeshes(m_pWorld->rootProduct(), pNode);\n\t}\n\n\t\/* No nodes? Fabricate nodes to display all the meshes. *\/\n\tif(m_pWorld->collection()->isEmpty())\n\t{\n\t\tqDebug() << \"No nodes founds\";\n\t\tLib3dsMesh *pMesh;\n\t\tLib3dsNode *pNode;\n\t\n\t\tfor(pMesh= m_pLib3dsFile->meshes; pMesh != NULL; pMesh = pMesh->next)\n\t\t{\n\t\t\tpNode= lib3ds_node_new_object();\n\t\t\tstrcpy(pNode->name, pMesh->name);\n\t\t\tpNode->parent_id= LIB3DS_NO_PARENT;\n\t\t\tlib3ds_file_insert_node(m_pLib3dsFile, pNode);\n\t\t}\n\t}\n\t\n\t\/\/ Free Lib3dsFile and all its ressources\n\tlib3ds_file_free(m_pLib3dsFile);\n\tm_pLib3dsFile= NULL;\n\tif (m_pWorld->collection()->isEmpty())\n\t{\n\t\tQString message= \"GLC_3dsToWorld::CreateWorldFrom3ds : No mesh found !\";\n\t\tGLC_FileFormatException fileFormatException(message, m_FileName);\n\t\tclear();\n\t\tthrow(fileFormatException);\t\t\n\t}\t\n\treturn m_pWorld;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Private services Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ clear stlToWorld allocate memmory and reset member\nvoid GLC_3dsToWorld::clear()\n{\n\tif (NULL != m_pCurrentMesh)\n\t{\n\t\tdelete m_pCurrentMesh;\n\t\tm_pCurrentMesh= NULL;\n\t}\n\tm_pWorld= NULL;\n\tm_FileName.clear();\n\tm_pCurrentMesh= NULL;\n\tm_CurVertexIndex= 0;\n\tm_CurNormalIndex= 0;\n\tif (NULL != m_pLib3dsFile)\n\t{\n\t\tlib3ds_file_free(m_pLib3dsFile);\n\t\tm_pLib3dsFile= NULL;\n\t}\n\t\n\t\/\/ Remove unused material\n\tQHash<QString, GLC_Material*>::iterator i;\n\tfor (i= m_Materials.begin(); i != m_Materials.end(); ++i)\n\t{\n\t\tif (i.value()->isUnused()) delete i.value();\n\t}\n\tm_Materials.clear();\n\t\/\/ Clear the material index hash table\n\tm_MaterialsIndex.clear();\n\tm_NextMaterialIndex= 0;\n\t\/\/ Set the current material to NULL\n\tm_pCurrentMaterial= NULL;\n\t\n}\n\n\/\/ Create meshes from the 3ds File\nvoid GLC_3dsToWorld::createMeshes(GLC_Product* pProduct, Lib3dsNode* pFatherNode)\n{\n\tGLC_Product* pChildProduct= NULL;\n\tLib3dsMesh *pMesh= NULL;\n\t\n\tif (pFatherNode->type == LIB3DS_OBJECT_NODE)\n\t{\n\t\t\/\/ Check if the node is a mesh or dummy\n\t\t\n\t\tif (strcmp(pFatherNode->name,\"$$$DUMMY\")==0)\n\t\t{\n\t\t\treturn;\n\t\t}\t\n\t\tpMesh = lib3ds_file_mesh_by_name(m_pLib3dsFile, pFatherNode->data.object.morph);\n\t if( pMesh == NULL )\n\t {\n\t \tpMesh = lib3ds_file_mesh_by_name(m_pLib3dsFile, pFatherNode->name);\n\t }\n\t if( pMesh != NULL )\n\t {\n\t \tGLC_Instance instance(createInstance(pMesh));\n\t\t\tLib3dsMatrix matrix;\n\t\t\tlib3ds_matrix_copy(matrix, pMesh->matrix);\n\t\t\tGLC_Matrix4x4 mat(&matrix[0][0]);\n\t\t\tGLC_Matrix4x4 matInv(&matrix[0][0]);\n\t\t\tmatInv.invert();\n\t\t\t\n\t\t\tLib3dsObjectData *pObjectData;\n\t\t\tpObjectData= &pFatherNode->data.object;\t\t\t\n\t\t\tGLC_Matrix4x4 trans(-pObjectData->pivot[0], -pObjectData->pivot[1], -pObjectData->pivot[2]);\n\t\t\t\n\t\t\tmat= mat * trans * matInv;\n\t\t\t\t\t\t\n\t\t\tpProduct->addChildPart(instance)->move(mat);\n\t }\n\t}\n\t\n\t\/\/ If there is a child, create a child product\n\tif (NULL != pFatherNode->childs)\n\t{\n\t\t\n\t\tpChildProduct= pProduct->addNewChildProduct();\n\t\t \n\t\t\/\/ Create Childs meshes if exists\n\t\tfor (Lib3dsNode* pNode= pFatherNode->childs; pNode!=0; pNode= pNode->next)\n\t\t{\t\n\t\t\tcreateMeshes(pChildProduct, pNode);\n\t\t}\n\t}\n\t\n\n}\n\/\/! Create Instance from a Lib3dsNode\nGLC_Instance GLC_3dsToWorld::createInstance(Lib3dsMesh* p3dsMesh)\n{\n\tGLC_Mesh2 * pMesh= new GLC_Mesh2();\n\tpMesh->setName(p3dsMesh->name);\n\t\/\/ The mesh normals\n\tconst int normalsNumber= p3dsMesh->faces * 3;\n\tLib3dsVector *normalL= static_cast<Lib3dsVector*>(malloc(normalsNumber * sizeof(Lib3dsVector)));\n\tlib3ds_mesh_calculate_normals(p3dsMesh, normalL);\n\t\/\/ Add the normal to the mesh\n\tfor (int i= 0; i < normalsNumber; ++i)\n\t{\n\t\tpMesh->addNormal(i, GLC_Vector3d(normalL[i][0], normalL[i][1], normalL[i][2]));\n\t}\n\tdelete normalL;\n\t\n\t\/\/ Add Vertex to the mesh\n\tconst int vertexNumber= p3dsMesh->points;\n\tfor (int i= 0; i < vertexNumber; ++i)\n\t{\n\t\tpMesh->addVertex(i, GLC_Vector3d(p3dsMesh->pointL[i].pos[0], p3dsMesh->pointL[i].pos[1], p3dsMesh->pointL[i].pos[2]));\n\t}\n\t\n\tint normalIndex= 0;\n\tint textureIndex= 0;\n\t\n\tfor (unsigned int i= 0; i < p3dsMesh->faces; ++i)\n\t{\n\t\t\/\/Add the Normal\n\t\tQVector<int> normal;\n\t\tnormal.append(normalIndex++);\n\t\tnormal.append(normalIndex++);\n\t\tnormal.append(normalIndex++);\n\t\tQVector<int> vertex;\n\t\tLib3dsFace *p3dsFace=&p3dsMesh->faceL[i];\n\t\t\/\/ Load the material\n\t\t\/\/ The material current face index\n\t\tQVector<int> material;\n\t\t\n\t\tif (p3dsFace->material[0])\n\t\t{\n\t\t\tLib3dsMaterial* p3dsMat=lib3ds_file_material_by_name(m_pLib3dsFile, p3dsFace->material);\n\t\t\t\/\/ Check it this material as already been loaded\n\t\t\tconst QString materialName(p3dsFace->material);\n\t\t\tif (!m_Materials.contains(materialName))\n\t\t\t{ \/\/ Material not already loaded, load it\n\t\t\t\tloadMaterial(p3dsMat);\n\t\t\t\t\/\/ Add the loaded material to the mesh\n\t\t\t\tpMesh->addMaterial(m_MaterialsIndex[materialName], m_Materials[materialName]);\n\t\t\t}\n\t\t\t\/\/ Set the current material\n\t\t\tm_pCurrentMaterial= m_Materials[materialName];\n\t\t\t\n\t\t\tconst int index= m_MaterialsIndex[materialName];\n\t\t\tmaterial << index << index << index;\n\t\t}\n\t\telse \/\/ No material\n\t\t{\n\t\t\tif (NULL != m_pCurrentMaterial)\n\t\t\t{\n\t\t\t\tconst int index= m_MaterialsIndex[m_pCurrentMaterial->getName()];\n\t\t\t\tpMesh->addMaterial(index, m_pCurrentMaterial);\n\t\t\t\tmaterial << index << index << index;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmaterial << -1 << -1 << -1;\n\t\t\t}\n\t\t}\n\t\t\/\/ End of loading material\n\t\tvertex << p3dsFace->points[0] << p3dsFace->points[1] << p3dsFace->points[2];\n\t\t\/\/ check if the mesh have texture coordinate\n\t\tif (p3dsMesh->texels > 0)\n\t\t{\n\t\t\tQVector<int> texture;\n\t\t\tfor (int i= 0; i < 3; ++i)\n\t\t\t{\n\t\t\t\t\/\/ Load texture coordinate\n\t\t\t\tfloat x= p3dsMesh->texelL[p3dsFace->points[i]][0];\n\t\t\t\tfloat y= p3dsMesh->texelL[p3dsFace->points[i]][1];\n\t\t\t\tGLC_Vector2d texel(static_cast<double>(x), static_cast<double>(y));\n\t\t\t\ttexture.append(textureIndex);\n\t\t\t\tpMesh->addTextureCoordinate(textureIndex++, texel);\n\t\t\t}\n\t\t\tpMesh->addFace(material, vertex, normal, texture);\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpMesh->addFace(material, vertex, normal);\n\t\t}\n\t\t\n\t}\n\treturn GLC_Instance(pMesh);\n}\n\n\/\/ Load Material\nvoid GLC_3dsToWorld::loadMaterial(Lib3dsMaterial* p3dsMaterial)\n{\n\tGLC_Material* pMaterial= new GLC_Material;\n\t\/\/ Set the material name\n\tconst QString materialName(p3dsMaterial->name);\n\tpMaterial->setName(materialName);\n\t\/\/ Check if there is a texture\n\tif (p3dsMaterial->texture1_map.name[0])\n\t{\n\t\tconst QString textureName(p3dsMaterial->texture1_map.name);\n\t\t\/\/ Retrieve the .3ds file path\n\t\tQFileInfo fileInfo(m_FileName);\n\t\tQString textureFileName(fileInfo.absolutePath() + QDir::separator());\n\t\ttextureFileName.append(textureName);\n\t\tQFile textureFile(textureFileName);\n\t\t\n\t\tif (textureFile.open(QIODevice::ReadOnly))\n\t\t{\n\t\t\t\/\/ Create the texture and assign it to the material\n\t\t\tGLC_Texture *pTexture = new GLC_Texture(m_pQGLContext, textureFile);\n\t\t\tpMaterial->setTexture(pTexture);\n\t\t}\n\t\ttextureFile.close();\n\t}\n\t\/\/ Ambient Color\n\tQColor ambient;\n\tambient.setRgbF(p3dsMaterial->ambient[0], p3dsMaterial->ambient[1], p3dsMaterial->ambient[2]);\n\tambient.setAlphaF(p3dsMaterial->ambient[3]);\n\tpMaterial->setAmbientColor(ambient);\n\t\/\/ Diffuse Color\n\tQColor diffuse;\n\tdiffuse.setRgbF(p3dsMaterial->diffuse[0], p3dsMaterial->diffuse[1], p3dsMaterial->diffuse[2]);\n\tdiffuse.setAlphaF(p3dsMaterial->diffuse[3]);\n\tpMaterial->setDiffuseColor(diffuse);\n\t\/\/ Specular Color\n\tQColor specular;\n\tspecular.setRgbF(p3dsMaterial->specular[0], p3dsMaterial->specular[1], p3dsMaterial->specular[2]);\n\tspecular.setAlphaF(p3dsMaterial->specular[3]);\n\tpMaterial->setSpecularColor(specular);\n\t\/\/ Shininess\n\t\/\/pMaterial->setShininess(pow(2, 10.0 * p3dsMaterial->shininess));\n\t\/\/ Transparency\n\tpMaterial->setTransparency(1.0 - p3dsMaterial->transparency);\n\t\n\t\/\/ Add the material to the hash table\n\tm_Materials.insert(materialName, pMaterial);\n\t\/\/ Add the material index\n\tm_MaterialsIndex.insert(materialName, m_NextMaterialIndex++);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 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 \"gm.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkLayerRasterizer.h\"\n#include \"SkBlurMaskFilter.h\"\n\nstatic void r0(SkLayerRasterizer* rast, SkPaint& p) {\n p.setMaskFilter(SkBlurMaskFilter::Create(SkIntToScalar(3),\n SkBlurMaskFilter::kNormal_BlurStyle))->unref();\n rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3));\n \n p.setMaskFilter(NULL);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1);\n rast->addLayer(p);\n \n p.setAlpha(0x11);\n p.setStyle(SkPaint::kFill_Style);\n p.setXfermodeMode(SkXfermode::kSrc_Mode);\n rast->addLayer(p);\n}\n\nstatic void r1(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n p.setAlpha(0x40);\n p.setXfermodeMode(SkXfermode::kSrc_Mode);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1*2);\n rast->addLayer(p);\n}\n\nstatic void r2(SkLayerRasterizer* rast, SkPaint& p) {\n p.setStyle(SkPaint::kStrokeAndFill_Style);\n p.setStrokeWidth(SK_Scalar1*4);\n rast->addLayer(p);\n \n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1*3\/2);\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p);\n}\n\nstatic void r3(SkLayerRasterizer* rast, SkPaint& p) {\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1*3);\n rast->addLayer(p);\n \n p.setAlpha(0x20);\n p.setStyle(SkPaint::kFill_Style);\n p.setXfermodeMode(SkXfermode::kSrc_Mode);\n rast->addLayer(p);\n}\n\nstatic void r4(SkLayerRasterizer* rast, SkPaint& p) {\n p.setAlpha(0x60);\n rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3));\n \n p.setAlpha(0xFF);\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p, SK_Scalar1*3\/2, SK_Scalar1*3\/2);\n \n p.setXfermode(NULL);\n rast->addLayer(p);\n}\n\n#include \"SkDiscretePathEffect.h\"\n\nstatic void r5(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n p.setPathEffect(new SkDiscretePathEffect(SK_Scalar1*4, SK_Scalar1*3))->unref();\n p.setXfermodeMode(SkXfermode::kSrcOut_Mode);\n rast->addLayer(p);\n}\n\nstatic void r6(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n p.setAntiAlias(false);\n SkLayerRasterizer* rast2 = new SkLayerRasterizer;\n r5(rast2, p);\n p.setRasterizer(rast2)->unref();\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p);\n}\n\n#include \"Sk2DPathEffect.h\"\n\nstatic SkPathEffect* MakeDotEffect(SkScalar radius, const SkMatrix& matrix) {\n SkPath path;\n path.addCircle(0, 0, radius);\n return new SkPath2DPathEffect(matrix, path);\n}\n\nstatic void r7(SkLayerRasterizer* rast, SkPaint& p) {\n SkMatrix lattice;\n lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0);\n lattice.postSkew(SK_Scalar1\/3, 0, 0, 0);\n p.setPathEffect(MakeDotEffect(SK_Scalar1*4, lattice))->unref();\n rast->addLayer(p);\n}\n\nstatic void r8(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n SkMatrix lattice;\n lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0);\n lattice.postSkew(SK_Scalar1\/3, 0, 0, 0);\n p.setPathEffect(MakeDotEffect(SK_Scalar1*2, lattice))->unref();\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p);\n \n p.setPathEffect(NULL);\n p.setXfermode(NULL);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1);\n rast->addLayer(p);\n}\n\nclass Line2DPathEffect : public Sk2DPathEffect {\npublic:\n Line2DPathEffect(SkScalar width, const SkMatrix& matrix)\n : Sk2DPathEffect(matrix), fWidth(width) {}\n \n\tvirtual bool filterPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec) SK_OVERRIDE {\n if (this->INHERITED::filterPath(dst, src, rec)) {\n rec->setStrokeStyle(fWidth);\n return true;\n }\n return false;\n }\n \n SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(Line2DPathEffect)\n \nprotected:\n\tvirtual void nextSpan(int u, int v, int ucount, SkPath* dst) {\n if (ucount > 1) {\n SkPoint\tsrc[2], dstP[2];\n \n src[0].set(SkIntToScalar(u) + SK_ScalarHalf,\n SkIntToScalar(v) + SK_ScalarHalf);\n src[1].set(SkIntToScalar(u+ucount) + SK_ScalarHalf,\n SkIntToScalar(v) + SK_ScalarHalf);\n this->getMatrix().mapPoints(dstP, src, 2);\n \n dst->moveTo(dstP[0]);\n dst->lineTo(dstP[1]);\n }\n }\n \n Line2DPathEffect(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {\n fWidth = buffer.readScalar();\n }\n virtual void flatten(SkFlattenableWriteBuffer& buffer) const SK_OVERRIDE {\n this->INHERITED::flatten(buffer);\n buffer.writeScalar(fWidth);\n }\n \nprivate:\n SkScalar fWidth;\n \n typedef Sk2DPathEffect INHERITED;\n};\n\nstatic void r9(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n SkMatrix lattice;\n lattice.setScale(SK_Scalar1, SK_Scalar1*6, 0, 0);\n lattice.postRotate(SkIntToScalar(30), 0, 0);\n p.setPathEffect(new Line2DPathEffect(SK_Scalar1*2, lattice))->unref();\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p);\n \n p.setPathEffect(NULL);\n p.setXfermode(NULL);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1);\n rast->addLayer(p);\n}\n\ntypedef void (*raster_proc)(SkLayerRasterizer*, SkPaint&);\n\nstatic const raster_proc gRastProcs[] = {\n r0, r1, r2, r3, r4, r5, r6, r7, r8, r9\n};\n\nstatic const struct {\n SkColor fMul, fAdd;\n} gLightingColors[] = {\n { 0x808080, 0x800000 }, \/\/ general case\n { 0x707070, 0x707070 }, \/\/ no-pin case\n { 0xFFFFFF, 0x800000 }, \/\/ just-add case\n { 0x808080, 0x000000 }, \/\/ just-mul case\n { 0xFFFFFF, 0x000000 } \/\/ identity case\n};\n\n#include \"SkXfermode.h\"\n\nstatic void apply_shader(SkPaint* paint, int index) {\n raster_proc proc = gRastProcs[index];\n if (proc)\n {\n SkPaint p;\n SkLayerRasterizer* rast = new SkLayerRasterizer;\n \n p.setAntiAlias(true);\n proc(rast, p);\n paint->setRasterizer(rast)->unref();\n }\n \n#if 0\n SkScalar dir[] = { SK_Scalar1, SK_Scalar1, SK_Scalar1 };\n paint->setMaskFilter(SkBlurMaskFilter::CreateEmboss(dir, SK_Scalar1\/4, SkIntToScalar(4), SkIntToScalar(3)))->unref();\n#endif\n paint->setColor(SK_ColorBLUE);\n}\n\nclass TextEffectsGM : public skiagm::GM {\npublic:\n\tTextEffectsGM() {}\n \nprotected:\n virtual SkString onShortName() SK_OVERRIDE {\n return SkString(\"texteffects\");\n }\n \n virtual SkISize onISize() SK_OVERRIDE {\n return SkISize::Make(640, 480);\n }\n \n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n canvas->save();\n \n SkPaint paint;\n \n paint.setAntiAlias(true);\n paint.setTextSize(SkIntToScalar(56));\n \n SkScalar x = SkIntToScalar(20);\n SkScalar y = paint.getTextSize();\n \n SkString str(\"Hamburgefons\");\n \n for (size_t i = 0; i < SK_ARRAY_COUNT(gRastProcs); i++) {\n apply_shader(&paint, i);\n \n \/\/ paint.setMaskFilter(NULL);\n \/\/ paint.setColor(SK_ColorBLACK);\n \n canvas->drawText(str.c_str(), str.size(), x, y, paint);\n \n y += paint.getFontSpacing();\n }\n \n canvas->restore();\n }\n \nprivate:\n typedef skiagm::GM INHERITED;\n};\n \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic skiagm::GM* MyFactory(void*) { return new TextEffectsGM; }\nstatic skiagm::GMRegistry reg(MyFactory);\n \n<commit_msg>adjust size to match the content<commit_after>\/*\n * Copyright 2011 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 \"gm.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkLayerRasterizer.h\"\n#include \"SkBlurMaskFilter.h\"\n\nstatic void r0(SkLayerRasterizer* rast, SkPaint& p) {\n p.setMaskFilter(SkBlurMaskFilter::Create(SkIntToScalar(3),\n SkBlurMaskFilter::kNormal_BlurStyle))->unref();\n rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3));\n \n p.setMaskFilter(NULL);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1);\n rast->addLayer(p);\n \n p.setAlpha(0x11);\n p.setStyle(SkPaint::kFill_Style);\n p.setXfermodeMode(SkXfermode::kSrc_Mode);\n rast->addLayer(p);\n}\n\nstatic void r1(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n p.setAlpha(0x40);\n p.setXfermodeMode(SkXfermode::kSrc_Mode);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1*2);\n rast->addLayer(p);\n}\n\nstatic void r2(SkLayerRasterizer* rast, SkPaint& p) {\n p.setStyle(SkPaint::kStrokeAndFill_Style);\n p.setStrokeWidth(SK_Scalar1*4);\n rast->addLayer(p);\n \n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1*3\/2);\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p);\n}\n\nstatic void r3(SkLayerRasterizer* rast, SkPaint& p) {\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1*3);\n rast->addLayer(p);\n \n p.setAlpha(0x20);\n p.setStyle(SkPaint::kFill_Style);\n p.setXfermodeMode(SkXfermode::kSrc_Mode);\n rast->addLayer(p);\n}\n\nstatic void r4(SkLayerRasterizer* rast, SkPaint& p) {\n p.setAlpha(0x60);\n rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3));\n \n p.setAlpha(0xFF);\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p, SK_Scalar1*3\/2, SK_Scalar1*3\/2);\n \n p.setXfermode(NULL);\n rast->addLayer(p);\n}\n\n#include \"SkDiscretePathEffect.h\"\n\nstatic void r5(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n p.setPathEffect(new SkDiscretePathEffect(SK_Scalar1*4, SK_Scalar1*3))->unref();\n p.setXfermodeMode(SkXfermode::kSrcOut_Mode);\n rast->addLayer(p);\n}\n\nstatic void r6(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n p.setAntiAlias(false);\n SkLayerRasterizer* rast2 = new SkLayerRasterizer;\n r5(rast2, p);\n p.setRasterizer(rast2)->unref();\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p);\n}\n\n#include \"Sk2DPathEffect.h\"\n\nstatic SkPathEffect* MakeDotEffect(SkScalar radius, const SkMatrix& matrix) {\n SkPath path;\n path.addCircle(0, 0, radius);\n return new SkPath2DPathEffect(matrix, path);\n}\n\nstatic void r7(SkLayerRasterizer* rast, SkPaint& p) {\n SkMatrix lattice;\n lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0);\n lattice.postSkew(SK_Scalar1\/3, 0, 0, 0);\n p.setPathEffect(MakeDotEffect(SK_Scalar1*4, lattice))->unref();\n rast->addLayer(p);\n}\n\nstatic void r8(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n SkMatrix lattice;\n lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0);\n lattice.postSkew(SK_Scalar1\/3, 0, 0, 0);\n p.setPathEffect(MakeDotEffect(SK_Scalar1*2, lattice))->unref();\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p);\n \n p.setPathEffect(NULL);\n p.setXfermode(NULL);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1);\n rast->addLayer(p);\n}\n\nclass Line2DPathEffect : public Sk2DPathEffect {\npublic:\n Line2DPathEffect(SkScalar width, const SkMatrix& matrix)\n : Sk2DPathEffect(matrix), fWidth(width) {}\n \n\tvirtual bool filterPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec) SK_OVERRIDE {\n if (this->INHERITED::filterPath(dst, src, rec)) {\n rec->setStrokeStyle(fWidth);\n return true;\n }\n return false;\n }\n \n SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(Line2DPathEffect)\n \nprotected:\n\tvirtual void nextSpan(int u, int v, int ucount, SkPath* dst) {\n if (ucount > 1) {\n SkPoint\tsrc[2], dstP[2];\n \n src[0].set(SkIntToScalar(u) + SK_ScalarHalf,\n SkIntToScalar(v) + SK_ScalarHalf);\n src[1].set(SkIntToScalar(u+ucount) + SK_ScalarHalf,\n SkIntToScalar(v) + SK_ScalarHalf);\n this->getMatrix().mapPoints(dstP, src, 2);\n \n dst->moveTo(dstP[0]);\n dst->lineTo(dstP[1]);\n }\n }\n \n Line2DPathEffect(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {\n fWidth = buffer.readScalar();\n }\n virtual void flatten(SkFlattenableWriteBuffer& buffer) const SK_OVERRIDE {\n this->INHERITED::flatten(buffer);\n buffer.writeScalar(fWidth);\n }\n \nprivate:\n SkScalar fWidth;\n \n typedef Sk2DPathEffect INHERITED;\n};\n\nstatic void r9(SkLayerRasterizer* rast, SkPaint& p) {\n rast->addLayer(p);\n \n SkMatrix lattice;\n lattice.setScale(SK_Scalar1, SK_Scalar1*6, 0, 0);\n lattice.postRotate(SkIntToScalar(30), 0, 0);\n p.setPathEffect(new Line2DPathEffect(SK_Scalar1*2, lattice))->unref();\n p.setXfermodeMode(SkXfermode::kClear_Mode);\n rast->addLayer(p);\n \n p.setPathEffect(NULL);\n p.setXfermode(NULL);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1);\n rast->addLayer(p);\n}\n\ntypedef void (*raster_proc)(SkLayerRasterizer*, SkPaint&);\n\nstatic const raster_proc gRastProcs[] = {\n r0, r1, r2, r3, r4, r5, r6, r7, r8, r9\n};\n\nstatic const struct {\n SkColor fMul, fAdd;\n} gLightingColors[] = {\n { 0x808080, 0x800000 }, \/\/ general case\n { 0x707070, 0x707070 }, \/\/ no-pin case\n { 0xFFFFFF, 0x800000 }, \/\/ just-add case\n { 0x808080, 0x000000 }, \/\/ just-mul case\n { 0xFFFFFF, 0x000000 } \/\/ identity case\n};\n\n#include \"SkXfermode.h\"\n\nstatic void apply_shader(SkPaint* paint, int index) {\n raster_proc proc = gRastProcs[index];\n if (proc)\n {\n SkPaint p;\n SkLayerRasterizer* rast = new SkLayerRasterizer;\n \n p.setAntiAlias(true);\n proc(rast, p);\n paint->setRasterizer(rast)->unref();\n }\n \n#if 0\n SkScalar dir[] = { SK_Scalar1, SK_Scalar1, SK_Scalar1 };\n paint->setMaskFilter(SkBlurMaskFilter::CreateEmboss(dir, SK_Scalar1\/4, SkIntToScalar(4), SkIntToScalar(3)))->unref();\n#endif\n paint->setColor(SK_ColorBLUE);\n}\n\nclass TextEffectsGM : public skiagm::GM {\npublic:\n\tTextEffectsGM() {}\n \nprotected:\n virtual SkString onShortName() SK_OVERRIDE {\n return SkString(\"texteffects\");\n }\n \n virtual SkISize onISize() SK_OVERRIDE {\n return SkISize::Make(460, 680);\n }\n \n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n canvas->save();\n \n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setTextSize(SkIntToScalar(56));\n \n SkScalar x = SkIntToScalar(20);\n SkScalar y = paint.getTextSize();\n \n SkString str(\"Hamburgefons\");\n \n for (size_t i = 0; i < SK_ARRAY_COUNT(gRastProcs); i++) {\n apply_shader(&paint, i);\n \n \/\/ paint.setMaskFilter(NULL);\n \/\/ paint.setColor(SK_ColorBLACK);\n \n canvas->drawText(str.c_str(), str.size(), x, y, paint);\n \n y += paint.getFontSpacing();\n }\n \n canvas->restore();\n }\n \nprivate:\n typedef skiagm::GM INHERITED;\n};\n \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic skiagm::GM* MyFactory(void*) { return new TextEffectsGM; }\nstatic skiagm::GMRegistry reg(MyFactory);\n \n<|endoftext|>"} {"text":"<commit_before>\/* GNE - Game Networking Engine, a portable multithreaded networking library.\n * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)\n * Project website: http:\/\/www.rit.edu\/~jpw9607\/\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include \"..\/include\/gnelib\/gneintern.h\"\n#include \"..\/include\/gnelib\/ConnectionEventGenerator.h\"\n#include \"..\/include\/gnelib\/ConnectionStats.h\"\n#include \"..\/include\/gnelib\/PacketParser.h\"\n#include \"..\/include\/gnelib\/GNE.h\"\n#include \"..\/include\/gnelib\/Address.h\"\n#include \"..\/include\/gnelib\/Error.h\"\n#include \"..\/include\/gnelib\/Errors.h\"\n#include \"..\/include\/gnelib\/PingPacket.h\"\n#include \"..\/include\/gnelib\/ObjectBrokerClient.h\"\n#include \"..\/include\/gnelib\/Timer.h\"\n#include \"..\/include\/gnelib\/Connection.h\"\n#include \"..\/include\/gnelib\/Console.h\"\n#include \"..\/include\/gnelib\/ServerConnectionListener.h\"\n\n#ifndef WIN32\n#include <signal.h>\n#endif\n\nnamespace GNE {\n namespace PacketParser {\n \/\/this is declared here only so the user cannot access it, and the \"real\"\n \/\/function can do checking on the ID given to it.\n void registerGNEPackets();\n }\n\nchar gameNameBuf[32] = {0};\nguint32 userVersion = 0;\nConnectionEventGenerator::sptr eGen;\n\nstatic bool initialized = false;\nstatic int timeToWait = 10000;\n\nbool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void)), int timeToClose ) {\n if (!initialized) {\n gnedbg(1, \"GNE initialized\");\n PacketParser::registerGNEPackets();\n ObjectBrokerClient::staticInit();\n timeToWait = timeToClose;\n\n if (networkType != NO_NET) {\n if (nlInit() == NL_FALSE)\n return true;\n if (nlSelectNetwork(networkType) == NL_FALSE)\n return true;\n nlEnable(NL_BLOCKING_IO);\n nlEnable(NL_TCP_NO_DELAY);\n \/\/GNE sends its data in little endian format.\n nlEnable(NL_LITTLE_ENDIAN_DATA);\n nlDisable(NL_SOCKET_STATS);\n eGen = ConnectionEventGenerator::create();\n eGen->start();\n initialized = true; \/\/We need only to set this to true if we are using HawkNL\n }\n\n#ifndef WIN32\n signal(SIGPIPE, SIG_IGN);\n#endif\n\n#ifdef _DEBUG\n \/\/Register killDebug separately, so we can still print out debugging\n \/\/messages until the last minute possible.\n atexit_ptr(killDebug);\n#endif\n\n atexit_ptr(shutdownGNE);\n\n return false;\n }\n return false;\n}\n\nvoid shutdownGNE() {\n if ( eGen ) {\n gnedbg( 1, \"Shutting down CEG.\" );\n eGen->shutDown();\n \/\/I'd like to use a join because that's cleaner, but I want to make sure\n \/\/the program does not block indefinitely when closing.\n }\n\n gnedbg( 1, \"GNE Shutdown begin: Closing all listeners.\" );\n ServerConnectionListener::closeAllListeners();\n gnedbg( 1, \"Shutting down all connections.\" );\n Connection::disconnectAll();\n gnedbg( 1, \"Stopping all timers.\" );\n Timer::stopAll();\n gnedbg( 1, \"Shutting down all user threads.\" );\n Thread::requestAllShutdown( Thread::USER );\n\n gnedbg1( 1, \"Waiting up to %d ms for all threads to shutdown.\", timeToWait );\n bool timeout = Thread::waitForAllThreads( timeToWait );\n if ( timeout ) {\n gnedbg( 1, \"Wait timeout: NOT ALL THREADS SHUT DOWN!\" );\n }\n\n if ( eGen && eGen->isRunning() ) {\n gnedbg( 1, \"CEG failed to shut down properly! Please file a bug report.\" );\n }\n eGen.reset();\n\n if (initialized) {\n gnedbg( 1, \"Shutting down HawkNL.\" );\n nlShutdown();\n initialized = false;\n }\n\n Console::shutdownConsole();\n\n gnedbg(1, \"GNE Shutdown\");\n}\n\nAddress getLocalAddress() {\n assert(initialized);\n NLaddress nlAddr;\n\n NLsocket temp = nlOpen(0, NL_RELIABLE);\n nlGetLocalAddr(temp, &nlAddr);\n nlClose(temp);\n\n Address ret(nlAddr);\n ret.setPort(0);\n return ret;\n}\n\nConnectionStats getGlobalStats() {\n assert(initialized);\n ConnectionStats ret;\n ret.packetsSent = nlGetInteger(NL_PACKETS_SENT);\n ret.bytesSent = nlGetInteger(NL_BYTES_SENT);\n ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT);\n ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT);\n ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED);\n ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED);\n ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED);\n ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED);\n ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS);\n return ret;\n}\n\nvoid enableStats() {\n assert(initialized);\n nlEnable(NL_SOCKET_STATS);\n}\n\nvoid disableStats() {\n assert(initialized);\n nlDisable(NL_SOCKET_STATS);\n}\n\nvoid clearStats() {\n assert(initialized);\n nlClear(NL_ALL_STATS);\n}\n\nint getOpenConnections() {\n assert(initialized);\n return nlGetInteger(NL_OPEN_SOCKETS);\n}\n\nGNEProtocolVersionNumber getGNEProtocolVersion() {\n assert(initialized);\n\n GNEProtocolVersionNumber ret;\n ret.version = 0;\n ret.subVersion = 0;\n ret.build = 6;\n\n return ret;\n}\n\nconst char* getGameName() {\n return gameNameBuf;\n}\n\nguint32 getUserVersion() {\n assert(initialized);\n return userVersion;\n}\n\nvoid setGameInformation(std::string gameName, guint32 version) {\n assert(initialized);\n assert(gameName.length() <= (std::string::size_type)GNE::MAX_GAME_NAME_LEN);\n \/\/We do this assert since this function should only be called once.\n assert(gameNameBuf[0] == 0);\n\n userVersion = version;\n strncpy(gameNameBuf, gameName.c_str(), MAX_GAME_NAME_LEN);\n}\n\nvoid checkVersions(const GNEProtocolVersionNumber& otherGNE,\n std::string otherName, guint32 otherUser) {\n GNEProtocolVersionNumber us = getGNEProtocolVersion();\n\n \/\/Check the GNE version numbers\n if (otherGNE.version != us.version ||\n otherGNE.subVersion != us.subVersion ||\n otherGNE.build != us.build) {\n if ((otherGNE.version > us.version) ||\n (otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) ||\n (otherGNE.subVersion == us.subVersion && otherGNE.build > us.build))\n throw Error(Error::GNETheirVersionHigh);\n else\n throw Error(Error::GNETheirVersionLow);\n }\n\n \/\/Check the game name\n if (otherName != gameNameBuf)\n throw WrongGame(otherName);\n\n \/\/Check the user version numbers\n if (userVersion != otherUser)\n throw UserVersionMismatch(otherUser);\n}\n\n}\n<commit_msg>Set NL_LITTLE_ENDIAN even if NO_NET.<commit_after>\/* GNE - Game Networking Engine, a portable multithreaded networking library.\n * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)\n * Project website: http:\/\/www.rit.edu\/~jpw9607\/\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include \"..\/include\/gnelib\/gneintern.h\"\n#include \"..\/include\/gnelib\/ConnectionEventGenerator.h\"\n#include \"..\/include\/gnelib\/ConnectionStats.h\"\n#include \"..\/include\/gnelib\/PacketParser.h\"\n#include \"..\/include\/gnelib\/GNE.h\"\n#include \"..\/include\/gnelib\/Address.h\"\n#include \"..\/include\/gnelib\/Error.h\"\n#include \"..\/include\/gnelib\/Errors.h\"\n#include \"..\/include\/gnelib\/PingPacket.h\"\n#include \"..\/include\/gnelib\/ObjectBrokerClient.h\"\n#include \"..\/include\/gnelib\/Timer.h\"\n#include \"..\/include\/gnelib\/Connection.h\"\n#include \"..\/include\/gnelib\/Console.h\"\n#include \"..\/include\/gnelib\/ServerConnectionListener.h\"\n\n#ifndef WIN32\n#include <signal.h>\n#endif\n\nnamespace GNE {\n namespace PacketParser {\n \/\/this is declared here only so the user cannot access it, and the \"real\"\n \/\/function can do checking on the ID given to it.\n void registerGNEPackets();\n }\n\nchar gameNameBuf[32] = {0};\nguint32 userVersion = 0;\nConnectionEventGenerator::sptr eGen;\n\nstatic bool initialized = false;\nstatic int timeToWait = 10000;\n\nbool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void)), int timeToClose ) {\n if (!initialized) {\n gnedbg(1, \"GNE initialized\");\n PacketParser::registerGNEPackets();\n ObjectBrokerClient::staticInit();\n timeToWait = timeToClose;\n\n \/\/This is a little hacky, but I checked the HawkNL source to make sure this\n \/\/worked before I did this.\n nlEnable(NL_LITTLE_ENDIAN_DATA);\n\n if (networkType != NO_NET) {\n if (nlInit() == NL_FALSE)\n return true;\n if (nlSelectNetwork(networkType) == NL_FALSE)\n return true;\n nlEnable(NL_BLOCKING_IO);\n nlEnable(NL_TCP_NO_DELAY);\n \/\/GNE sends its data in little endian format.\n nlDisable(NL_SOCKET_STATS);\n eGen = ConnectionEventGenerator::create();\n eGen->start();\n initialized = true; \/\/We need only to set this to true if we are using HawkNL\n }\n\n#ifndef WIN32\n signal(SIGPIPE, SIG_IGN);\n#endif\n\n#ifdef _DEBUG\n \/\/Register killDebug separately, so we can still print out debugging\n \/\/messages until the last minute possible.\n atexit_ptr(killDebug);\n#endif\n\n atexit_ptr(shutdownGNE);\n\n return false;\n }\n return false;\n}\n\nvoid shutdownGNE() {\n if ( eGen ) {\n gnedbg( 1, \"Shutting down CEG.\" );\n eGen->shutDown();\n \/\/I'd like to use a join because that's cleaner, but I want to make sure\n \/\/the program does not block indefinitely when closing.\n }\n\n gnedbg( 1, \"GNE Shutdown begin: Closing all listeners.\" );\n ServerConnectionListener::closeAllListeners();\n gnedbg( 1, \"Shutting down all connections.\" );\n Connection::disconnectAll();\n gnedbg( 1, \"Stopping all timers.\" );\n Timer::stopAll();\n gnedbg( 1, \"Shutting down all user threads.\" );\n Thread::requestAllShutdown( Thread::USER );\n\n gnedbg1( 1, \"Waiting up to %d ms for all threads to shutdown.\", timeToWait );\n bool timeout = Thread::waitForAllThreads( timeToWait );\n if ( timeout ) {\n gnedbg( 1, \"Wait timeout: NOT ALL THREADS SHUT DOWN!\" );\n }\n\n if ( eGen && eGen->isRunning() ) {\n gnedbg( 1, \"CEG failed to shut down properly! Please file a bug report.\" );\n }\n eGen.reset();\n\n if (initialized) {\n gnedbg( 1, \"Shutting down HawkNL.\" );\n nlShutdown();\n initialized = false;\n }\n\n Console::shutdownConsole();\n\n gnedbg(1, \"GNE Shutdown\");\n}\n\nAddress getLocalAddress() {\n assert(initialized);\n NLaddress nlAddr;\n\n NLsocket temp = nlOpen(0, NL_RELIABLE);\n nlGetLocalAddr(temp, &nlAddr);\n nlClose(temp);\n\n Address ret(nlAddr);\n ret.setPort(0);\n return ret;\n}\n\nConnectionStats getGlobalStats() {\n assert(initialized);\n ConnectionStats ret;\n ret.packetsSent = nlGetInteger(NL_PACKETS_SENT);\n ret.bytesSent = nlGetInteger(NL_BYTES_SENT);\n ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT);\n ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT);\n ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED);\n ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED);\n ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED);\n ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED);\n ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS);\n return ret;\n}\n\nvoid enableStats() {\n assert(initialized);\n nlEnable(NL_SOCKET_STATS);\n}\n\nvoid disableStats() {\n assert(initialized);\n nlDisable(NL_SOCKET_STATS);\n}\n\nvoid clearStats() {\n assert(initialized);\n nlClear(NL_ALL_STATS);\n}\n\nint getOpenConnections() {\n assert(initialized);\n return nlGetInteger(NL_OPEN_SOCKETS);\n}\n\nGNEProtocolVersionNumber getGNEProtocolVersion() {\n assert(initialized);\n\n GNEProtocolVersionNumber ret;\n ret.version = 0;\n ret.subVersion = 0;\n ret.build = 6;\n\n return ret;\n}\n\nconst char* getGameName() {\n return gameNameBuf;\n}\n\nguint32 getUserVersion() {\n assert(initialized);\n return userVersion;\n}\n\nvoid setGameInformation(std::string gameName, guint32 version) {\n assert(initialized);\n assert(gameName.length() <= (std::string::size_type)GNE::MAX_GAME_NAME_LEN);\n \/\/We do this assert since this function should only be called once.\n assert(gameNameBuf[0] == 0);\n\n userVersion = version;\n strncpy(gameNameBuf, gameName.c_str(), MAX_GAME_NAME_LEN);\n}\n\nvoid checkVersions(const GNEProtocolVersionNumber& otherGNE,\n std::string otherName, guint32 otherUser) {\n GNEProtocolVersionNumber us = getGNEProtocolVersion();\n\n \/\/Check the GNE version numbers\n if (otherGNE.version != us.version ||\n otherGNE.subVersion != us.subVersion ||\n otherGNE.build != us.build) {\n if ((otherGNE.version > us.version) ||\n (otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) ||\n (otherGNE.subVersion == us.subVersion && otherGNE.build > us.build))\n throw Error(Error::GNETheirVersionHigh);\n else\n throw Error(Error::GNETheirVersionLow);\n }\n\n \/\/Check the game name\n if (otherName != gameNameBuf)\n throw WrongGame(otherName);\n\n \/\/Check the user version numbers\n if (userVersion != otherUser)\n throw UserVersionMismatch(otherUser);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"UIController.h\"\r\n#include <QApplication>\r\n#include <QDebug>\r\n#include <cmath>\r\n#include <QKeyEvent>\r\n\r\n#include \"MemoryLeakCheck.h\"\r\n\r\nnamespace QtUI\r\n{\r\n\r\nUIController::UIController() : mouseDown_(false), arrange_(false), responseTimeLimit_(500)\r\n{}\r\n\r\nUIController::~UIController()\r\n{}\r\n\r\nvoid UIController::Update()\r\n{\r\n\r\n QList<boost::shared_ptr<UICanvas> >::iterator iter = canvases_.begin();\r\n for(; iter != canvases_.end(); ++iter)\r\n (*iter)->Render();\r\n \r\n \/\/Update Z-order if needed.\r\n\r\n Arrange(); \r\n}\r\n\r\nvoid UIController::Arrange()\r\n{\r\n if (arrange_)\r\n {\r\n \/\/\/todo Arrange canvases to z-order.\r\n }\r\n arrange_ = false;\r\n \r\n}\r\n\r\nvoid UIController::RemoveCanvas(const QString& id)\r\n{\r\n QList<boost::shared_ptr<UICanvas> >::iterator iter = canvases_.begin();\r\n int index = 0;\r\n for(; iter != canvases_.end(); ++iter, ++index)\r\n {\r\n QString canvas_id = (*iter)->GetID();\r\n if ( canvas_id == id)\r\n {\r\n canvases_.removeAt(index);\r\n break;\r\n }\r\n }\r\n}\r\n\r\n\r\nboost::weak_ptr<UICanvas> UIController::CreateCanvas(UICanvas::Mode mode)\r\n{\r\n boost::shared_ptr<UICanvas> canvas(new UICanvas(mode, parentWindowSize_));\r\n \r\n QObject::connect(this,SIGNAL(RenderWindowSizeChanged(const QSize&)),canvas.get(), SLOT(SetRenderWindowSize(const QSize&)));\r\n QObject::connect(canvas.get(), SIGNAL(RequestArrange()), this, SLOT(RequestArrange()));\r\n\r\n canvases_.append(canvas);\r\n return canvas;\r\n}\r\n\r\nvoid UIController::InjectMouseMove(int x, int y)\r\n{\r\n \r\n QPoint point(x,y);\r\n int index = GetCanvas(point);\r\n \r\n \/\/ Normal move. \r\n\r\n if (index != -1 && !mouseDown_)\r\n {\r\n \r\n \/\/ Location of mouse event in scene.\r\n QPoint p = canvases_[index]->MapToCanvas(x,y);\r\n QPointF pos = canvases_[index]->mapToScene(p);\r\n \r\n \/\/QPointF pos = canvases_[index]->mapToScene(point);\r\n \r\n QPoint currentMousePos((int)pos.x(), (int)pos.y());\r\n\r\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove);\r\n \r\n if (mouseDown_)\r\n {\r\n mouseEvent.setButtonDownScenePos(Qt::LeftButton, mousePress_);\r\n mouseEvent.setButtonDownScreenPos(Qt::LeftButton, mousePress_);\r\n }\r\n else\r\n {\r\n mouseEvent.setButtonDownScenePos(Qt::NoButton, currentMousePos);\r\n mouseEvent.setButtonDownScreenPos(Qt::NoButton, currentMousePos);\r\n }\r\n \r\n mouseEvent.setScenePos(currentMousePos);\r\n mouseEvent.setScreenPos(currentMousePos);\r\n mouseEvent.setLastScenePos(currentMousePos);\r\n mouseEvent.setLastScreenPos(currentMousePos);\r\n mouseEvent.setButtons(mouseDown_ ? Qt::LeftButton : Qt::NoButton);\r\n mouseEvent.setButton(mouseDown_ ? Qt::LeftButton : Qt::NoButton);\r\n mouseEvent.setModifiers(0);\r\n mouseEvent.setAccepted(false);\r\n \r\n QApplication::sendEvent(canvases_[index]->scene(), &mouseEvent); \r\n \r\n }\r\n else if ( mouseDown_ )\r\n {\r\n \/\/ Drag event. \r\n \r\n \/\/ Find active canvas, move it to this location (if canvas is not locked.)\r\n \r\n index = GetCanvas(lastPosition_);\r\n \r\n if ( index != -1)\r\n {\r\n if ( !canvases_[index]->IsCanvasPositionLocked() )\r\n {\r\n QPoint pos = canvases_[index]->GetPosition().toPoint();\r\n\r\n int xPos = point.x()-(lastPosition_.x()-pos.x());\r\n int yPos = point.y()-(lastPosition_.y()-pos.y());\r\n \r\n canvases_[index]->SetPosition(xPos, yPos);\r\n }\r\n }\r\n\r\n }\r\n \r\n lastPosition_ = point;\r\n\r\n}\r\n\r\nvoid UIController::InjectMousePress(int x, int y)\r\n{\r\n \r\n QPoint point(x,y);\r\n \r\n int index = GetCanvas(point);\r\n \r\n if ( timer_.isNull() )\r\n {\r\n \/\/ First press. \r\n timer_.start();\r\n }\r\n else if ( timer_.elapsed() <= responseTimeLimit_)\r\n {\r\n \/\/ Double click has happen.\r\n \r\n \/\/ Restart to zero.\r\n timer_.setHMS(0,0,0,-1);\r\n QPoint loc = lastPosition_ - point;\r\n \r\n if ( loc.manhattanLength() < 5)\r\n InjectDoubleClick(x,y);\r\n\r\n lastPosition_ = point;\r\n return;\r\n }\r\n else \r\n {\r\n \/\/ Restart to zero.\r\n \r\n timer_.setHMS(0,0,0,-1);\r\n }\r\n \r\n \r\n if (index != -1)\r\n {\r\n \r\n \/\/ Translate the mouse position from QGraphicsView coordinate frame onto\r\n \/\/ the QGraphicsScene coordinate frame.\r\n QPoint p = canvases_[index]->MapToCanvas(x,y);\r\n QPointF pos = canvases_[index]->mapToScene(p);\r\n QPoint currentMousePos((int)pos.x(), (int)pos.y());\r\n\r\n \/\/ For future use save press state. \r\n mouseDown_ = true;\r\n mousePress_ = point;\r\n\r\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);\r\n \r\n mouseEvent.setButtonDownScenePos(Qt::LeftButton, currentMousePos);\r\n mouseEvent.setButtonDownScreenPos(Qt::LeftButton, currentMousePos);\r\n mouseEvent.setScenePos(currentMousePos);\r\n mouseEvent.setScreenPos(currentMousePos);\r\n mouseEvent.setLastScenePos(currentMousePos);\r\n mouseEvent.setLastScreenPos(currentMousePos);\r\n mouseEvent.setButtons(Qt::LeftButton);\r\n mouseEvent.setButton(Qt::LeftButton);\r\n\r\n mouseEvent.setModifiers(0);\r\n mouseEvent.setAccepted(false);\r\n \r\n QApplication::sendEvent(canvases_[index]->scene(), &mouseEvent);\r\n\r\n \r\n }\r\n lastPosition_ = point;\r\n}\r\n\r\nvoid UIController::InjectMouseRelease(int x, int y)\r\n{\r\n \/\/\/\/todo what to do release after double click?\r\n \r\n QPoint point(x,y);\r\n int index = GetCanvas(point);\r\n\r\n if (index != -1)\r\n {\r\n \r\n \/\/ Translate the mouse position from QGraphicsView coordinate frame onto\r\n \/\/ the QGraphicsScene coordinate frame.\r\n QPoint p = canvases_[index]->MapToCanvas(x,y);\r\n QPointF pos = canvases_[index]->mapToScene(p);\r\n QPoint currentMousePos((int)pos.x(), (int)pos.y());\r\n\r\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseRelease);\r\n mouseEvent.setButtonDownScenePos(Qt::NoButton, currentMousePos);\r\n mouseEvent.setButtonDownScreenPos(Qt::NoButton, currentMousePos);\r\n mouseEvent.setScenePos(currentMousePos);\r\n mouseEvent.setScreenPos(currentMousePos);\r\n mouseEvent.setLastScenePos(currentMousePos);\r\n mouseEvent.setLastScreenPos(currentMousePos);\r\n mouseEvent.setButtons(Qt::NoButton);\r\n mouseEvent.setButton(Qt::LeftButton);\r\n mouseEvent.setModifiers(0);\r\n mouseEvent.setAccepted(false);\r\n \r\n \r\n\r\n QApplication::sendEvent(canvases_[index]->scene(), &mouseEvent);\r\n \r\n }\r\n\r\n mouseDown_ = false;\r\n lastPosition_ = point;\r\n}\r\n\r\nvoid UIController::InjectDoubleClick(int x, int y)\r\n{\r\n QPoint point(x,y);\r\n lastPosition_ = point;\r\n int index = GetCanvas(point);\r\n \r\n if (index != -1)\r\n {\r\n \r\n \/\/ Translate the mouse position from QGraphicsView coordinate frame onto\r\n \/\/ the QGraphicsScene coordinate frame.\r\n QPoint p = canvases_[index]->MapToCanvas(x,y);\r\n QPointF pos = canvases_[index]->mapToScene(p);\r\n QPoint currentMousePos((int)pos.x(), (int)pos.y());\r\n\r\n mouseDown_ = false;\r\n \r\n \/\/ In case of double click we set that left button generated click -> so it is set down. \r\n\r\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseDoubleClick);\r\n\r\n mouseEvent.setButtonDownScenePos(Qt::LeftButton, currentMousePos);\r\n mouseEvent.setButtonDownScreenPos(Qt::LeftButton, currentMousePos);\r\n mouseEvent.setScenePos(currentMousePos);\r\n mouseEvent.setScreenPos(currentMousePos);\r\n mouseEvent.setLastScenePos(currentMousePos);\r\n mouseEvent.setLastScreenPos(currentMousePos);\r\n mouseEvent.setButtons(Qt::LeftButton);\r\n mouseEvent.setButton(Qt::LeftButton);\r\n \r\n mouseEvent.setModifiers(0);\r\n mouseEvent.setAccepted(false);\r\n \r\n QApplication::sendEvent(canvases_[index]->scene(), &mouseEvent);\r\n \r\n }\r\n \r\n}\r\n\r\nvoid UIController::InjectKeyPressed(Qt::Key keyCode, const Qt::KeyboardModifier& modifier)\r\n{\r\n QKeySequence sequence(keyCode); \r\n QKeyEvent keyEvent(QEvent::KeyPress, keyCode, modifier, sequence.toString().toLower());\r\n keyEvent.setAccepted(false);\r\n \r\n \/\/ Take a location of last known mouse press and send it to that canvas. \r\n \r\n int index = GetCanvas(mousePress_);\r\n if ( index != -1 )\r\n {\r\n QApplication::sendEvent(canvases_[index]->scene(), &keyEvent);\r\n }\r\n\r\n}\r\n\r\nvoid UIController::SetParentWindowSize(const QSize& size)\r\n{\r\n parentWindowSize_ = size;\r\n emit RenderWindowSizeChanged(size);\r\n}\r\n\r\n\r\nint UIController::GetCanvas(const QPoint& point) \r\n{\r\n QList<boost::shared_ptr<UICanvas> >::iterator iter = canvases_.begin();\r\n int index = 0;\r\n for (; iter != canvases_.end(); ++iter, ++index)\r\n {\r\n UICanvas::Mode mode = (*iter)->GetMode();\r\n \r\n switch(mode)\r\n {\r\n \/\/ If mode is external we let the Qt own window manager to things. \r\n case UICanvas::External:\r\n break;\r\n case UICanvas::Internal:\r\n {\r\n if (Contains(*iter, point))\r\n return index;\r\n break;\r\n }\r\n \r\n default:\r\n break; \r\n\r\n }\r\n\r\n }\r\n\r\n \/\/ Did not find any canvases so let's return -1.\r\n\r\n return -1;\r\n}\r\n\r\nbool UIController::Contains(const boost::shared_ptr<UICanvas>& canvas, const QPoint& point) const\r\n{\r\n QPoint pos = canvas->GetPosition().toPoint();\r\n return pos.x() <= point.x() && \r\n pos.y() <= point.y() && \r\n (pos.x() + canvas->width()) > point.x() && \r\n (pos.y() + canvas->height()) > point.y();\r\n}\r\n\r\n}\r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n\r\n \r\n <commit_msg>Fix for double-click now it works as it should work. <commit_after>\r\n\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"UIController.h\"\r\n#include <QApplication>\r\n#include <QDebug>\r\n#include <cmath>\r\n#include <QKeyEvent>\r\n\r\n#include \"MemoryLeakCheck.h\"\r\n\r\nnamespace QtUI\r\n{\r\n\r\nUIController::UIController() : mouseDown_(false), arrange_(false), responseTimeLimit_(500)\r\n{}\r\n\r\nUIController::~UIController()\r\n{}\r\n\r\nvoid UIController::Update()\r\n{\r\n\r\n QList<boost::shared_ptr<UICanvas> >::iterator iter = canvases_.begin();\r\n for(; iter != canvases_.end(); ++iter)\r\n (*iter)->Render();\r\n \r\n \/\/Update Z-order if needed.\r\n\r\n Arrange(); \r\n}\r\n\r\nvoid UIController::Arrange()\r\n{\r\n if (arrange_)\r\n {\r\n \/\/\/todo Arrange canvases to z-order.\r\n }\r\n arrange_ = false;\r\n \r\n}\r\n\r\nvoid UIController::RemoveCanvas(const QString& id)\r\n{\r\n QList<boost::shared_ptr<UICanvas> >::iterator iter = canvases_.begin();\r\n int index = 0;\r\n for(; iter != canvases_.end(); ++iter, ++index)\r\n {\r\n QString canvas_id = (*iter)->GetID();\r\n if ( canvas_id == id)\r\n {\r\n canvases_.removeAt(index);\r\n break;\r\n }\r\n }\r\n}\r\n\r\n\r\nboost::weak_ptr<UICanvas> UIController::CreateCanvas(UICanvas::Mode mode)\r\n{\r\n boost::shared_ptr<UICanvas> canvas(new UICanvas(mode, parentWindowSize_));\r\n \r\n QObject::connect(this,SIGNAL(RenderWindowSizeChanged(const QSize&)),canvas.get(), SLOT(SetRenderWindowSize(const QSize&)));\r\n QObject::connect(canvas.get(), SIGNAL(RequestArrange()), this, SLOT(RequestArrange()));\r\n\r\n canvases_.append(canvas);\r\n return canvas;\r\n}\r\n\r\nvoid UIController::InjectMouseMove(int x, int y)\r\n{\r\n \r\n QPoint point(x,y);\r\n int index = GetCanvas(point);\r\n \r\n \/\/ Normal move. \r\n\r\n if (index != -1 && !mouseDown_)\r\n {\r\n \r\n \/\/ Location of mouse event in scene.\r\n QPoint p = canvases_[index]->MapToCanvas(x,y);\r\n QPointF pos = canvases_[index]->mapToScene(p);\r\n \r\n \/\/QPointF pos = canvases_[index]->mapToScene(point);\r\n \r\n QPoint currentMousePos((int)pos.x(), (int)pos.y());\r\n\r\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove);\r\n \r\n if (mouseDown_)\r\n {\r\n mouseEvent.setButtonDownScenePos(Qt::LeftButton, mousePress_);\r\n mouseEvent.setButtonDownScreenPos(Qt::LeftButton, mousePress_);\r\n }\r\n else\r\n {\r\n mouseEvent.setButtonDownScenePos(Qt::NoButton, currentMousePos);\r\n mouseEvent.setButtonDownScreenPos(Qt::NoButton, currentMousePos);\r\n }\r\n \r\n mouseEvent.setScenePos(currentMousePos);\r\n mouseEvent.setScreenPos(currentMousePos);\r\n mouseEvent.setLastScenePos(currentMousePos);\r\n mouseEvent.setLastScreenPos(currentMousePos);\r\n mouseEvent.setButtons(mouseDown_ ? Qt::LeftButton : Qt::NoButton);\r\n mouseEvent.setButton(mouseDown_ ? Qt::LeftButton : Qt::NoButton);\r\n mouseEvent.setModifiers(0);\r\n mouseEvent.setAccepted(false);\r\n \r\n QApplication::sendEvent(canvases_[index]->scene(), &mouseEvent); \r\n \r\n }\r\n else if ( mouseDown_ )\r\n {\r\n \/\/ Drag event. \r\n \r\n \/\/ Find active canvas, move it to this location (if canvas is not locked.)\r\n \r\n index = GetCanvas(lastPosition_);\r\n \r\n if ( index != -1)\r\n {\r\n if ( !canvases_[index]->IsCanvasPositionLocked() )\r\n {\r\n QPoint pos = canvases_[index]->GetPosition().toPoint();\r\n\r\n int xPos = point.x()-(lastPosition_.x()-pos.x());\r\n int yPos = point.y()-(lastPosition_.y()-pos.y());\r\n \r\n canvases_[index]->SetPosition(xPos, yPos);\r\n }\r\n }\r\n\r\n }\r\n \r\n lastPosition_ = point;\r\n\r\n}\r\n\r\nvoid UIController::InjectMousePress(int x, int y)\r\n{\r\n \r\n QPoint point(x,y);\r\n \r\n int index = GetCanvas(point);\r\n \r\n if ( timer_.isNull() )\r\n {\r\n \/\/ First press. \r\n timer_.start();\r\n }\r\n else if ( timer_.elapsed() <= responseTimeLimit_)\r\n {\r\n \/\/ Double click has happen.\r\n \r\n \/\/ Restart to zero.\r\n timer_ = QTime();\r\n \r\n QPoint loc = lastPosition_ - point;\r\n lastPosition_ = point;\r\n if ( loc.manhattanLength() < 2)\r\n {\r\n InjectDoubleClick(x,y);\r\n return;\r\n }\r\n \r\n \r\n }\r\n else \r\n {\r\n \/\/ Restart to zero.\r\n timer_ = QTime();\r\n \/\/ And start again. \r\n timer_.start();\r\n }\r\n \r\n \r\n if (index != -1)\r\n {\r\n \r\n \/\/ Translate the mouse position from QGraphicsView coordinate frame onto\r\n \/\/ the QGraphicsScene coordinate frame.\r\n QPoint p = canvases_[index]->MapToCanvas(x,y);\r\n QPointF pos = canvases_[index]->mapToScene(p);\r\n QPoint currentMousePos((int)pos.x(), (int)pos.y());\r\n\r\n \/\/ For future use save press state. \r\n mouseDown_ = true;\r\n mousePress_ = point;\r\n\r\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);\r\n \r\n mouseEvent.setButtonDownScenePos(Qt::LeftButton, currentMousePos);\r\n mouseEvent.setButtonDownScreenPos(Qt::LeftButton, currentMousePos);\r\n mouseEvent.setScenePos(currentMousePos);\r\n mouseEvent.setScreenPos(currentMousePos);\r\n mouseEvent.setLastScenePos(currentMousePos);\r\n mouseEvent.setLastScreenPos(currentMousePos);\r\n mouseEvent.setButtons(Qt::LeftButton);\r\n mouseEvent.setButton(Qt::LeftButton);\r\n\r\n mouseEvent.setModifiers(0);\r\n mouseEvent.setAccepted(false);\r\n \r\n QApplication::sendEvent(canvases_[index]->scene(), &mouseEvent);\r\n\r\n \r\n }\r\n lastPosition_ = point;\r\n}\r\n\r\nvoid UIController::InjectMouseRelease(int x, int y)\r\n{\r\n \/\/\/\/todo what to do release after double click?\r\n \r\n QPoint point(x,y);\r\n int index = GetCanvas(point);\r\n\r\n if (index != -1)\r\n {\r\n \r\n \/\/ Translate the mouse position from QGraphicsView coordinate frame onto\r\n \/\/ the QGraphicsScene coordinate frame.\r\n QPoint p = canvases_[index]->MapToCanvas(x,y);\r\n QPointF pos = canvases_[index]->mapToScene(p);\r\n QPoint currentMousePos((int)pos.x(), (int)pos.y());\r\n\r\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseRelease);\r\n mouseEvent.setButtonDownScenePos(Qt::NoButton, currentMousePos);\r\n mouseEvent.setButtonDownScreenPos(Qt::NoButton, currentMousePos);\r\n mouseEvent.setScenePos(currentMousePos);\r\n mouseEvent.setScreenPos(currentMousePos);\r\n mouseEvent.setLastScenePos(currentMousePos);\r\n mouseEvent.setLastScreenPos(currentMousePos);\r\n mouseEvent.setButtons(Qt::NoButton);\r\n mouseEvent.setButton(Qt::LeftButton);\r\n mouseEvent.setModifiers(0);\r\n mouseEvent.setAccepted(false);\r\n \r\n \r\n\r\n QApplication::sendEvent(canvases_[index]->scene(), &mouseEvent);\r\n \r\n }\r\n\r\n mouseDown_ = false;\r\n lastPosition_ = point;\r\n}\r\n\r\nvoid UIController::InjectDoubleClick(int x, int y)\r\n{\r\n QPoint point(x,y);\r\n lastPosition_ = point;\r\n int index = GetCanvas(point);\r\n \r\n if (index != -1)\r\n {\r\n \r\n \/\/ Translate the mouse position from QGraphicsView coordinate frame onto\r\n \/\/ the QGraphicsScene coordinate frame.\r\n QPoint p = canvases_[index]->MapToCanvas(x,y);\r\n QPointF pos = canvases_[index]->mapToScene(p);\r\n QPoint currentMousePos((int)pos.x(), (int)pos.y());\r\n\r\n mouseDown_ = false;\r\n \r\n \/\/ In case of double click we set that left button generated click -> so it is set down. \r\n\r\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseDoubleClick);\r\n\r\n mouseEvent.setButtonDownScenePos(Qt::LeftButton, currentMousePos);\r\n mouseEvent.setButtonDownScreenPos(Qt::LeftButton, currentMousePos);\r\n mouseEvent.setScenePos(currentMousePos);\r\n mouseEvent.setScreenPos(currentMousePos);\r\n mouseEvent.setLastScenePos(currentMousePos);\r\n mouseEvent.setLastScreenPos(currentMousePos);\r\n mouseEvent.setButtons(Qt::LeftButton);\r\n mouseEvent.setButton(Qt::LeftButton);\r\n \r\n mouseEvent.setModifiers(0);\r\n mouseEvent.setAccepted(false);\r\n \r\n QApplication::sendEvent(canvases_[index]->scene(), &mouseEvent);\r\n \r\n }\r\n \r\n}\r\n\r\nvoid UIController::InjectKeyPressed(Qt::Key keyCode, const Qt::KeyboardModifier& modifier)\r\n{\r\n QKeySequence sequence(keyCode); \r\n QKeyEvent keyEvent(QEvent::KeyPress, keyCode, modifier, sequence.toString().toLower());\r\n keyEvent.setAccepted(false);\r\n \r\n \/\/ Take a location of last known mouse press and send it to that canvas. \r\n \r\n int index = GetCanvas(mousePress_);\r\n if ( index != -1 )\r\n {\r\n QApplication::sendEvent(canvases_[index]->scene(), &keyEvent);\r\n }\r\n\r\n}\r\n\r\nvoid UIController::SetParentWindowSize(const QSize& size)\r\n{\r\n parentWindowSize_ = size;\r\n emit RenderWindowSizeChanged(size);\r\n}\r\n\r\n\r\nint UIController::GetCanvas(const QPoint& point) \r\n{\r\n QList<boost::shared_ptr<UICanvas> >::iterator iter = canvases_.begin();\r\n int index = 0;\r\n for (; iter != canvases_.end(); ++iter, ++index)\r\n {\r\n UICanvas::Mode mode = (*iter)->GetMode();\r\n \r\n switch(mode)\r\n {\r\n \/\/ If mode is external we let the Qt own window manager to things. \r\n case UICanvas::External:\r\n break;\r\n case UICanvas::Internal:\r\n {\r\n if (Contains(*iter, point))\r\n return index;\r\n break;\r\n }\r\n \r\n default:\r\n break; \r\n\r\n }\r\n\r\n }\r\n\r\n \/\/ Did not find any canvases so let's return -1.\r\n\r\n return -1;\r\n}\r\n\r\nbool UIController::Contains(const boost::shared_ptr<UICanvas>& canvas, const QPoint& point) const\r\n{\r\n QPoint pos = canvas->GetPosition().toPoint();\r\n return pos.x() <= point.x() && \r\n pos.y() <= point.y() && \r\n (pos.x() + canvas->width()) > point.x() && \r\n (pos.y() + canvas->height()) > point.y();\r\n}\r\n\r\n}\r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n\r\n \r\n <|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\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#include <iterator>\n#include <limits>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <thrift\/conformance\/data\/PatchGenerator.h>\n\n#include <boost\/mp11.hpp>\n#include <fmt\/core.h>\n\n#include <thrift\/conformance\/cpp2\/Object.h>\n#include <thrift\/conformance\/data\/ValueGenerator.h>\n#include <thrift\/lib\/cpp2\/op\/Clear.h>\n#include <thrift\/lib\/cpp2\/op\/Get.h>\n#include <thrift\/lib\/cpp2\/op\/Patch.h>\n#include <thrift\/lib\/cpp2\/type\/BaseType.h>\n#include <thrift\/lib\/cpp2\/type\/Name.h>\n#include <thrift\/lib\/cpp2\/type\/Tag.h>\n#include <thrift\/lib\/thrift\/gen-cpp2\/patch_types_custom_protocol.h>\n\nnamespace apache::thrift::conformance::data {\n\nnamespace mp11 = boost::mp11;\n\nnamespace {\n\ntemplate <typename TT, typename GeneratedValue>\nauto toValue(const GeneratedValue& value) {\n if constexpr (std::is_same_v<TT, type::binary_t>) {\n return *folly::IOBuf::copyBuffer(value.data());\n } else {\n return value;\n }\n}\n\ntemplate <typename TT, typename GeneratedValue>\nPatchOpTestCase makeAssignTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n auto initialValue = value.value;\n op::clear<TT>(initialValue);\n req.value() = registry.store(asValueStruct<TT>(initialValue), protocol);\n\n auto patch = op::patch_type<TT>();\n patch = toValue<TT>(value.value);\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n opTest.request() = req;\n opTest.result() = registry.store(asValueStruct<TT>(value.value), protocol);\n return opTest;\n}\n\ntemplate <typename TT, typename GeneratedValue>\nPatchOpTestCase makeClearTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n req.value() = registry.store(asValueStruct<TT>(value.value), protocol);\n\n auto patch = op::patch_type<TT>();\n patch.clear();\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n\n auto clearValue = value.value;\n op::clear<TT>(clearValue);\n opTest.request() = req;\n opTest.result() = registry.store(asValueStruct<TT>(clearValue), protocol);\n return opTest;\n}\n\ntemplate <typename TT, typename T>\nT makeAddExpectedResult(T value, int add = 1) {\n if constexpr (std::is_convertible_v<TT, type::bool_t>) {\n return !value;\n } else {\n if (std::numeric_limits<T>::max() == value && add > 0) {\n return value;\n } else if (std::numeric_limits<T>::min() == value && add < 0) {\n return value;\n }\n return value + add;\n }\n}\n\ntemplate <typename TT, typename GeneratedValue, typename T>\nPatchOpTestCase makeAddTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol,\n T toAdd) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n req.value() = registry.store(asValueStruct<TT>(value.value), protocol);\n\n auto addOp = [&](auto& patch) {\n if constexpr (std::is_same_v<TT, type::bool_t>) {\n patch.invert();\n } else {\n patch += toAdd;\n }\n };\n\n auto patch = op::patch_type<TT>();\n addOp(patch);\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n opTest.request() = req;\n opTest.result() = registry.store(\n asValueStruct<TT>(makeAddExpectedResult<TT>(value.value)), protocol);\n return opTest;\n}\n\ntemplate <typename TT, typename GeneratedValue>\nPatchOpTestCase makePrependTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n req.value() = registry.store(asValueStruct<TT>(value.value), protocol);\n\n auto patch = op::patch_type<TT>();\n patch.prepend(toValue<TT>(value.value));\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n opTest.request() = req;\n auto expected = value.value + value.value;\n opTest.result() =\n registry.store(asValueStruct<TT>(toValue<TT>(expected)), protocol);\n return opTest;\n}\n\ntemplate <typename TT, typename GeneratedValue>\nPatchOpTestCase makeAppendTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n req.value() = registry.store(asValueStruct<TT>(value.value), protocol);\n\n auto patch = op::patch_type<TT>();\n patch.append(toValue<TT>(value.value));\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n opTest.request() = req;\n auto expected = value.value + value.value;\n opTest.result() =\n registry.store(asValueStruct<TT>(toValue<TT>(expected)), protocol);\n return opTest;\n}\n\ntemplate <typename TT>\nTest createNumericPatchTest(\n const AnyRegistry& registry, const Protocol& protocol) {\n Test test;\n test.name() = protocol.name();\n\n for (const auto& value : ValueGenerator<TT>::getInterestingValues()) {\n auto& assignCase = test.testCases()->emplace_back();\n assignCase.name() =\n fmt::format(\"{}\/assign.{}\", type::getName<TT>(), value.name);\n auto& tascase = assignCase.test().emplace().objectPatch_ref().emplace();\n tascase = makeAssignTest<TT>(value, registry, protocol);\n\n \/\/ TODO(afuller): decide if bool and numeric should have clear()\n\n using ValueType = decltype(value.value);\n auto addAddTestCase = [&](ValueType toAdd) {\n auto& addCase = test.testCases()->emplace_back();\n addCase.name() =\n fmt::format(\"{}\/add.{}_{}\", type::getName<TT>(), value.name, toAdd);\n auto& tadcase = addCase.test().emplace().objectPatch_ref().emplace();\n tadcase = makeAddTest<TT>(value, registry, protocol, toAdd);\n };\n\n addAddTestCase(1);\n if constexpr (!std::is_same_v<TT, type::bool_t>) {\n addAddTestCase(-1);\n if (value.value > 0) {\n addAddTestCase(-value.value);\n }\n }\n }\n\n return test;\n}\n\ntemplate <typename TT>\nTest createStringLikePatchTest(\n const AnyRegistry& registry, const Protocol& protocol) {\n Test test;\n test.name() = protocol.name();\n\n for (const auto& value : ValueGenerator<TT>::getInterestingValues()) {\n auto& assignCase = test.testCases()->emplace_back();\n assignCase.name() =\n fmt::format(\"{}\/assign.{}\", type::getName<TT>(), value.name);\n auto& tascase = assignCase.test().emplace().objectPatch_ref().emplace();\n tascase = makeAssignTest<TT>(value, registry, protocol);\n\n auto& clearCase = test.testCases()->emplace_back();\n clearCase.name() = fmt::format(\"{}\/clear\", type::getName<TT>());\n auto& tclcase = clearCase.test().emplace().objectPatch_ref().emplace();\n tclcase = makeClearTest<TT>(value, registry, protocol);\n\n auto& prependCase = test.testCases()->emplace_back();\n prependCase.name() =\n fmt::format(\"{}\/prepend.{}\", type::getName<TT>(), value.name);\n auto& tprcase = prependCase.test().emplace().objectPatch_ref().emplace();\n tprcase = makePrependTest<TT>(value, registry, protocol);\n\n auto& appendCase = test.testCases()->emplace_back();\n appendCase.name() =\n fmt::format(\"{}\/append.{}\", type::getName<TT>(), value.name);\n auto& tapcase = appendCase.test().emplace().objectPatch_ref().emplace();\n tapcase = makeAppendTest<TT>(value, registry, protocol);\n }\n\n return test;\n}\n\nnamespace {\ntemplate <typename T>\nstruct container_from_class {\n static_assert(std::is_same_v<T, type::container_c>, \"Not a container class\");\n};\n\ntemplate <>\nstruct container_from_class<type::list_c> {\n template <typename ValueType>\n using type = type::list<ValueType>;\n};\n\ntemplate <>\nstruct container_from_class<type::set_c> {\n template <typename ValueType>\n using type = type::set<ValueType>;\n};\n\ntemplate <typename C, typename... Types>\nusing container_from_class_t =\n typename container_from_class<C>::template type<Types...>;\n\ntemplate <typename Tag>\nObject patchAddOperation(Object&& patch, op::PatchOp operation, auto value) {\n auto opId = static_cast<int16_t>(operation);\n patch.members().ensure()[opId] = asValueStruct<Tag>(value);\n return std::move(patch);\n}\n\ntemplate <typename Tag>\nValue makePatchObject(auto operation, auto value) {\n Value result;\n result.objectValue_ref() = patchAddOperation<Tag>(Object{}, operation, value);\n return result;\n}\n\ntemplate <typename ContainerTag>\nPatchOpTestCase makeValueContainerAssignTC(\n const AnyRegistry& registry, const Protocol& protocol, auto value) {\n PatchOpTestCase tascase;\n PatchOpRequest req;\n\n using Container = type::standard_type<ContainerTag>;\n\n Container initial;\n Container expected = {value.value};\n\n req.value() = registry.store(asValueStruct<ContainerTag>(initial), protocol);\n req.patch() = registry.store(\n makePatchObject<ContainerTag>(op::PatchOp::Assign, expected), protocol);\n tascase.request() = req;\n tascase.result() =\n registry.store(asValueStruct<ContainerTag>(expected), protocol);\n return tascase;\n}\n\ntemplate <typename ContainerTag>\nPatchOpTestCase makeValueContainerClearTC(\n const AnyRegistry& registry, const Protocol& protocol, auto value) {\n PatchOpTestCase tascase;\n PatchOpRequest req;\n\n using Container = type::standard_type<ContainerTag>;\n\n Container initial = {value.value};\n Container expected;\n\n req.value() = registry.store(asValueStruct<ContainerTag>(initial), protocol);\n req.patch() = registry.store(\n makePatchObject<type::bool_t>(op::PatchOp::Clear, true), protocol);\n tascase.request() = req;\n tascase.result() =\n registry.store(asValueStruct<ContainerTag>(expected), protocol);\n return tascase;\n}\n\n} \/\/ namespace\n\ntemplate <typename TT>\nTest createListSetPatchTest(\n const AnyRegistry& registry, const Protocol& protocol) {\n Test test;\n test.name() = protocol.name();\n\n using ValueContainers = boost::mp11::mp_list<type::list_c, type::set_c>;\n mp11::mp_for_each<ValueContainers>([&](auto cc) {\n using CC = decltype(cc);\n for (const auto& value : ValueGenerator<TT>::getInterestingValues()) {\n using ContainerTag = container_from_class_t<CC, TT>;\n auto& assignCase = test.testCases()->emplace_back();\n assignCase.name() = fmt::format(\n \"{}<{}>\/assign.{}\",\n type::getName<CC>(),\n type::getName<TT>(),\n value.name);\n assignCase.test().emplace().objectPatch_ref() =\n makeValueContainerAssignTC<ContainerTag>(registry, protocol, value);\n\n auto& clearCase = test.testCases()->emplace_back();\n clearCase.name() = fmt::format(\n \"{}<{}>\/clear.{}\",\n type::getName<CC>(),\n type::getName<TT>(),\n value.name);\n clearCase.test().emplace().objectPatch_ref() =\n makeValueContainerClearTC<ContainerTag>(registry, protocol, value);\n }\n });\n\n return test;\n}\n\nvoid addPatchToSuite(\n const AnyRegistry& registry, const Protocol& protocol, TestSuite& suite) {\n mp11::mp_for_each<detail::PrimaryTypeTags>([&](auto tt) {\n using TT = decltype(tt);\n if constexpr (\n !std::is_same_v<TT, type::string_t> &&\n !std::is_same_v<TT, type::binary_t>) {\n suite.tests()->emplace_back(\n createNumericPatchTest<TT>(registry, protocol));\n } else {\n suite.tests()->emplace_back(\n createStringLikePatchTest<TT>(registry, protocol));\n }\n\n if constexpr (!std::is_same_v<TT, type::bool_t>) {\n suite.tests()->emplace_back(\n createListSetPatchTest<TT>(registry, protocol));\n }\n });\n}\n} \/\/ namespace\n\nTestSuite createPatchSuite(\n const std::set<Protocol>& protocols, const AnyRegistry& registry) {\n TestSuite suite;\n suite.name() = \"PatchTest\";\n for (const auto& protocol : protocols) {\n addPatchToSuite(registry, protocol, suite);\n }\n return suite;\n}\n\n} \/\/ namespace apache::thrift::conformance::data\n<commit_msg>Add remove() conformance test cases for list and set patching.<commit_after>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\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#include <iterator>\n#include <limits>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <thrift\/conformance\/data\/PatchGenerator.h>\n\n#include <boost\/mp11.hpp>\n#include <fmt\/core.h>\n\n#include <thrift\/conformance\/cpp2\/Object.h>\n#include <thrift\/conformance\/data\/ValueGenerator.h>\n#include <thrift\/lib\/cpp2\/op\/Clear.h>\n#include <thrift\/lib\/cpp2\/op\/Get.h>\n#include <thrift\/lib\/cpp2\/op\/Patch.h>\n#include <thrift\/lib\/cpp2\/type\/BaseType.h>\n#include <thrift\/lib\/cpp2\/type\/Name.h>\n#include <thrift\/lib\/cpp2\/type\/Tag.h>\n#include <thrift\/lib\/thrift\/gen-cpp2\/patch_types_custom_protocol.h>\n\nnamespace apache::thrift::conformance::data {\n\nnamespace mp11 = boost::mp11;\n\nnamespace {\n\ntemplate <typename TT, typename GeneratedValue>\nauto toValue(const GeneratedValue& value) {\n if constexpr (std::is_same_v<TT, type::binary_t>) {\n return *folly::IOBuf::copyBuffer(value.data());\n } else {\n return value;\n }\n}\n\ntemplate <typename TT, typename GeneratedValue>\nPatchOpTestCase makeAssignTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n auto initialValue = value.value;\n op::clear<TT>(initialValue);\n req.value() = registry.store(asValueStruct<TT>(initialValue), protocol);\n\n auto patch = op::patch_type<TT>();\n patch = toValue<TT>(value.value);\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n opTest.request() = req;\n opTest.result() = registry.store(asValueStruct<TT>(value.value), protocol);\n return opTest;\n}\n\ntemplate <typename TT, typename GeneratedValue>\nPatchOpTestCase makeClearTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n req.value() = registry.store(asValueStruct<TT>(value.value), protocol);\n\n auto patch = op::patch_type<TT>();\n patch.clear();\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n\n auto clearValue = value.value;\n op::clear<TT>(clearValue);\n opTest.request() = req;\n opTest.result() = registry.store(asValueStruct<TT>(clearValue), protocol);\n return opTest;\n}\n\ntemplate <typename TT, typename T>\nT makeAddExpectedResult(T value, int add = 1) {\n if constexpr (std::is_convertible_v<TT, type::bool_t>) {\n return !value;\n } else {\n if (std::numeric_limits<T>::max() == value && add > 0) {\n return value;\n } else if (std::numeric_limits<T>::min() == value && add < 0) {\n return value;\n }\n return value + add;\n }\n}\n\ntemplate <typename TT, typename GeneratedValue, typename T>\nPatchOpTestCase makeAddTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol,\n T toAdd) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n req.value() = registry.store(asValueStruct<TT>(value.value), protocol);\n\n auto addOp = [&](auto& patch) {\n if constexpr (std::is_same_v<TT, type::bool_t>) {\n patch.invert();\n } else {\n patch += toAdd;\n }\n };\n\n auto patch = op::patch_type<TT>();\n addOp(patch);\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n opTest.request() = req;\n opTest.result() = registry.store(\n asValueStruct<TT>(makeAddExpectedResult<TT>(value.value)), protocol);\n return opTest;\n}\n\ntemplate <typename TT, typename GeneratedValue>\nPatchOpTestCase makePrependTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n req.value() = registry.store(asValueStruct<TT>(value.value), protocol);\n\n auto patch = op::patch_type<TT>();\n patch.prepend(toValue<TT>(value.value));\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n opTest.request() = req;\n auto expected = value.value + value.value;\n opTest.result() =\n registry.store(asValueStruct<TT>(toValue<TT>(expected)), protocol);\n return opTest;\n}\n\ntemplate <typename TT, typename GeneratedValue>\nPatchOpTestCase makeAppendTest(\n const GeneratedValue& value,\n const AnyRegistry& registry,\n const Protocol& protocol) {\n PatchOpTestCase opTest;\n PatchOpRequest req;\n req.value() = registry.store(asValueStruct<TT>(value.value), protocol);\n\n auto patch = op::patch_type<TT>();\n patch.append(toValue<TT>(value.value));\n req.patch() =\n registry.store(asValueStruct<type::struct_c>(patch.toThrift()), protocol);\n opTest.request() = req;\n auto expected = value.value + value.value;\n opTest.result() =\n registry.store(asValueStruct<TT>(toValue<TT>(expected)), protocol);\n return opTest;\n}\n\ntemplate <typename TT>\nTest createNumericPatchTest(\n const AnyRegistry& registry, const Protocol& protocol) {\n Test test;\n test.name() = protocol.name();\n\n for (const auto& value : ValueGenerator<TT>::getInterestingValues()) {\n auto& assignCase = test.testCases()->emplace_back();\n assignCase.name() =\n fmt::format(\"{}\/assign.{}\", type::getName<TT>(), value.name);\n auto& tascase = assignCase.test().emplace().objectPatch_ref().emplace();\n tascase = makeAssignTest<TT>(value, registry, protocol);\n\n \/\/ TODO(afuller): decide if bool and numeric should have clear()\n\n using ValueType = decltype(value.value);\n auto addAddTestCase = [&](ValueType toAdd) {\n auto& addCase = test.testCases()->emplace_back();\n addCase.name() =\n fmt::format(\"{}\/add.{}_{}\", type::getName<TT>(), value.name, toAdd);\n auto& tadcase = addCase.test().emplace().objectPatch_ref().emplace();\n tadcase = makeAddTest<TT>(value, registry, protocol, toAdd);\n };\n\n addAddTestCase(1);\n if constexpr (!std::is_same_v<TT, type::bool_t>) {\n addAddTestCase(-1);\n if (value.value > 0) {\n addAddTestCase(-value.value);\n }\n }\n }\n\n return test;\n}\n\ntemplate <typename TT>\nTest createStringLikePatchTest(\n const AnyRegistry& registry, const Protocol& protocol) {\n Test test;\n test.name() = protocol.name();\n\n for (const auto& value : ValueGenerator<TT>::getInterestingValues()) {\n auto& assignCase = test.testCases()->emplace_back();\n assignCase.name() =\n fmt::format(\"{}\/assign.{}\", type::getName<TT>(), value.name);\n auto& tascase = assignCase.test().emplace().objectPatch_ref().emplace();\n tascase = makeAssignTest<TT>(value, registry, protocol);\n\n auto& clearCase = test.testCases()->emplace_back();\n clearCase.name() = fmt::format(\"{}\/clear\", type::getName<TT>());\n auto& tclcase = clearCase.test().emplace().objectPatch_ref().emplace();\n tclcase = makeClearTest<TT>(value, registry, protocol);\n\n auto& prependCase = test.testCases()->emplace_back();\n prependCase.name() =\n fmt::format(\"{}\/prepend.{}\", type::getName<TT>(), value.name);\n auto& tprcase = prependCase.test().emplace().objectPatch_ref().emplace();\n tprcase = makePrependTest<TT>(value, registry, protocol);\n\n auto& appendCase = test.testCases()->emplace_back();\n appendCase.name() =\n fmt::format(\"{}\/append.{}\", type::getName<TT>(), value.name);\n auto& tapcase = appendCase.test().emplace().objectPatch_ref().emplace();\n tapcase = makeAppendTest<TT>(value, registry, protocol);\n }\n\n return test;\n}\n\nnamespace {\ntemplate <typename T>\nstruct container_from_class {\n static_assert(std::is_same_v<T, type::container_c>, \"Not a container class\");\n};\n\ntemplate <>\nstruct container_from_class<type::list_c> {\n template <typename ValueType>\n using type = type::list<ValueType>;\n};\n\ntemplate <>\nstruct container_from_class<type::set_c> {\n template <typename ValueType>\n using type = type::set<ValueType>;\n};\n\ntemplate <typename C, typename... Types>\nusing container_from_class_t =\n typename container_from_class<C>::template type<Types...>;\n\ntemplate <typename Tag>\nObject patchAddOperation(Object&& patch, op::PatchOp operation, auto value) {\n auto opId = static_cast<int16_t>(operation);\n patch.members().ensure()[opId] = asValueStruct<Tag>(value);\n return std::move(patch);\n}\n\ntemplate <typename Tag>\nValue makePatchObject(auto operation, auto value) {\n Value result;\n result.objectValue_ref() = patchAddOperation<Tag>(Object{}, operation, value);\n return result;\n}\n\ntemplate <typename ContainerTag>\nPatchOpTestCase makeValueContainerAssignTC(\n const AnyRegistry& registry, const Protocol& protocol, auto value) {\n PatchOpTestCase tascase;\n PatchOpRequest req;\n\n using Container = type::standard_type<ContainerTag>;\n\n Container initial;\n Container expected = {value.value};\n\n req.value() = registry.store(asValueStruct<ContainerTag>(initial), protocol);\n req.patch() = registry.store(\n makePatchObject<ContainerTag>(op::PatchOp::Assign, expected), protocol);\n tascase.request() = req;\n tascase.result() =\n registry.store(asValueStruct<ContainerTag>(expected), protocol);\n return tascase;\n}\n\ntemplate <typename ContainerTag>\nPatchOpTestCase makeValueContainerClearTC(\n const AnyRegistry& registry, const Protocol& protocol, auto value) {\n PatchOpTestCase tascase;\n PatchOpRequest req;\n\n using Container = type::standard_type<ContainerTag>;\n\n Container initial = {value.value};\n Container expected;\n\n req.value() = registry.store(asValueStruct<ContainerTag>(initial), protocol);\n req.patch() = registry.store(\n makePatchObject<type::bool_t>(op::PatchOp::Clear, true), protocol);\n tascase.request() = req;\n tascase.result() =\n registry.store(asValueStruct<ContainerTag>(expected), protocol);\n return tascase;\n}\n\ntemplate <typename ContainerTag, typename ValueTag>\nPatchOpTestCase makeValueContainerRemoveTC(\n const AnyRegistry& registry, const Protocol& protocol, auto value) {\n PatchOpTestCase tascase;\n PatchOpRequest req;\n\n using Container = type::native_type<ContainerTag>;\n\n Container initial = {value.value};\n Container expected;\n\n req.value() = registry.store(asValueStruct<ContainerTag>(initial), protocol);\n req.patch() = registry.store(\n makePatchObject<type::set<ValueTag>>(\n op::PatchOp::Remove,\n std::set<type::standard_type<ValueTag>>{value.value}),\n protocol);\n tascase.request() = req;\n tascase.result() =\n registry.store(asValueStruct<ContainerTag>(expected), protocol);\n return tascase;\n}\n\n} \/\/ namespace\n\ntemplate <typename TT>\nTest createListSetPatchTest(\n const AnyRegistry& registry, const Protocol& protocol) {\n Test test;\n test.name() = protocol.name();\n\n using ValueContainers = boost::mp11::mp_list<type::list_c, type::set_c>;\n mp11::mp_for_each<ValueContainers>([&](auto cc) {\n using CC = decltype(cc);\n for (const auto& value : ValueGenerator<TT>::getInterestingValues()) {\n using ContainerTag = container_from_class_t<CC, TT>;\n auto& assignCase = test.testCases()->emplace_back();\n assignCase.name() = fmt::format(\n \"{}<{}>\/assign.{}\",\n type::getName<CC>(),\n type::getName<TT>(),\n value.name);\n assignCase.test().emplace().objectPatch_ref() =\n makeValueContainerAssignTC<ContainerTag>(registry, protocol, value);\n\n auto& clearCase = test.testCases()->emplace_back();\n clearCase.name() = fmt::format(\n \"{}<{}>\/clear.{}\",\n type::getName<CC>(),\n type::getName<TT>(),\n value.name);\n clearCase.test().emplace().objectPatch_ref() =\n makeValueContainerClearTC<ContainerTag>(registry, protocol, value);\n\n auto& removeCase = test.testCases()->emplace_back();\n removeCase.name() = fmt::format(\n \"{}<{}>\/remove.{}\",\n type::getName<CC>(),\n type::getName<TT>(),\n value.name);\n removeCase.test().emplace().objectPatch_ref() =\n makeValueContainerRemoveTC<ContainerTag, TT>(\n registry, protocol, value);\n }\n });\n\n return test;\n}\n\nvoid addPatchToSuite(\n const AnyRegistry& registry, const Protocol& protocol, TestSuite& suite) {\n mp11::mp_for_each<detail::PrimaryTypeTags>([&](auto tt) {\n using TT = decltype(tt);\n if constexpr (\n !std::is_same_v<TT, type::string_t> &&\n !std::is_same_v<TT, type::binary_t>) {\n suite.tests()->emplace_back(\n createNumericPatchTest<TT>(registry, protocol));\n } else {\n suite.tests()->emplace_back(\n createStringLikePatchTest<TT>(registry, protocol));\n }\n\n if constexpr (!std::is_same_v<TT, type::bool_t>) {\n suite.tests()->emplace_back(\n createListSetPatchTest<TT>(registry, protocol));\n }\n });\n}\n} \/\/ namespace\n\nTestSuite createPatchSuite(\n const std::set<Protocol>& protocols, const AnyRegistry& registry) {\n TestSuite suite;\n suite.name() = \"PatchTest\";\n for (const auto& protocol : protocols) {\n addPatchToSuite(registry, protocol, suite);\n }\n return suite;\n}\n\n} \/\/ namespace apache::thrift::conformance::data\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\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#include <thrift\/lib\/cpp2\/async\/ClientSinkBridge.h>\n\n#include <folly\/Overload.h>\n\nnamespace apache {\nnamespace thrift {\nnamespace detail {\n\n\/\/ Explicitly instantiate the base of ClientSinkBridge\ntemplate class TwoWayBridge<\n ClientSinkConsumer,\n ClientMessage,\n ClientSinkBridge,\n ServerMessage,\n ClientSinkBridge>;\n\nClientSinkBridge::ClientSinkBridge(FirstResponseCallback* callback)\n : firstResponseCallback_(callback) {}\n\nClientSinkBridge::~ClientSinkBridge() {}\n\nSinkClientCallback* ClientSinkBridge::create(FirstResponseCallback* callback) {\n return new ClientSinkBridge(callback);\n}\n\nvoid ClientSinkBridge::close() {\n serverClose();\n serverCallback_ = nullptr;\n evb_.reset();\n Ptr(this);\n}\n\nbool ClientSinkBridge::wait(ClientSinkConsumer* consumer) {\n return clientWait(consumer);\n}\n\nvoid ClientSinkBridge::push(ServerMessage&& value) {\n clientPush(std::move(value));\n}\n\nClientSinkBridge::ClientQueue ClientSinkBridge::getMessages() {\n return clientGetMessages();\n}\n\n#if FOLLY_HAS_COROUTINES\n\nfolly::coro::Task<folly::Try<StreamPayload>> ClientSinkBridge::sink(\n folly::coro::AsyncGenerator<folly::Try<StreamPayload>&&> generator) {\n uint64_t credits = 0;\n folly::Try<StreamPayload> finalResponse;\n const auto& clientCancelToken =\n co_await folly::coro::co_current_cancellation_token;\n auto mergedToken = folly::CancellationToken::merge(\n serverCancelSource_.getToken(), clientCancelToken);\n\n auto waitEvent = [&]() -> folly::coro::Task<void> {\n CoroConsumer consumer;\n if (clientWait(&consumer)) {\n folly::CancellationCallback cb{\n clientCancelToken, [&]() {\n if (auto* cancelledCb = cancelClientWait()) {\n cancelledCb->canceled();\n }\n }};\n co_await consumer.wait();\n }\n auto queue = clientGetMessages();\n while (!queue.empty()) {\n auto& message = queue.front();\n folly::variant_match(\n message,\n [&](folly::Try<StreamPayload>& payload) {\n finalResponse = std::move(payload);\n },\n [&](uint64_t n) { credits += n; });\n queue.pop();\n if (finalResponse.hasValue() || finalResponse.hasException()) {\n co_return;\n }\n }\n co_return;\n };\n\n bool sinkComplete = false;\n\n while (true) {\n co_await waitEvent();\n if (finalResponse.hasValue() || finalResponse.hasException()) {\n break;\n }\n\n if (clientCancelToken.isCancellationRequested()) {\n if (!sinkComplete) {\n clientPush(folly::Try<apache::thrift::StreamPayload>(\n rocket::RocketException(rocket::ErrorCode::CANCELED)));\n }\n co_yield folly::coro::co_cancelled;\n }\n\n while (credits > 0 && !sinkComplete &&\n !serverCancelSource_.isCancellationRequested()) {\n auto item = co_await folly::coro::co_withCancellation(\n mergedToken, generator.next());\n if (serverCancelSource_.isCancellationRequested()) {\n break;\n }\n\n if (clientCancelToken.isCancellationRequested()) {\n clientPush(folly::Try<apache::thrift::StreamPayload>(\n rocket::RocketException(rocket::ErrorCode::CANCELED)));\n co_yield folly::coro::co_cancelled;\n }\n\n if (item.has_value()) {\n if ((*item).hasValue()) {\n clientPush(std::move(*item));\n } else {\n clientPush(std::move(*item));\n \/\/ AsyncGenerator who serialized and yield the exception also in\n \/\/ charge of propagating it back to user, just return empty Try\n \/\/ here.\n co_return folly::Try<StreamPayload>();\n }\n } else {\n clientPush({});\n sinkComplete = true;\n \/\/ release generator\n generator = {};\n }\n credits--;\n }\n }\n co_return std::move(finalResponse);\n}\n\n#endif\n\nvoid ClientSinkBridge::cancel(folly::Try<StreamPayload> payload) {\n CHECK(payload.hasException());\n clientPush(std::move(payload));\n}\n\n\/\/ SinkClientCallback method\nbool ClientSinkBridge::onFirstResponse(\n FirstResponsePayload&& firstPayload,\n folly::EventBase* evb,\n SinkServerCallback* serverCallback) {\n auto firstResponseCallback = firstResponseCallback_;\n serverCallback_ = serverCallback;\n evb_ = folly::getKeepAliveToken(evb);\n bool scheduledWait = serverWait(this);\n DCHECK(scheduledWait);\n firstResponseCallback->onFirstResponse(std::move(firstPayload), copy());\n return true;\n}\n\nvoid ClientSinkBridge::onFirstResponseError(folly::exception_wrapper ew) {\n firstResponseCallback_->onFirstResponseError(std::move(ew));\n close();\n}\n\nvoid ClientSinkBridge::onFinalResponse(StreamPayload&& payload) {\n serverPush(folly::Try<StreamPayload>(std::move(payload)));\n serverCancelSource_.requestCancellation();\n close();\n}\n\nvoid ClientSinkBridge::onFinalResponseError(folly::exception_wrapper ew) {\n using apache::thrift::detail::EncodedError;\n auto rex = ew.get_exception<rocket::RocketException>();\n auto payload = rex\n ? folly::Try<StreamPayload>(EncodedError(rex->moveErrorData()))\n : folly::Try<StreamPayload>(std::move(ew));\n serverPush(std::move(payload));\n serverCancelSource_.requestCancellation();\n close();\n}\n\nbool ClientSinkBridge::onSinkRequestN(uint64_t n) {\n serverPush(n);\n return true;\n}\n\nvoid ClientSinkBridge::resetServerCallback(SinkServerCallback& serverCallback) {\n serverCallback_ = &serverCallback;\n}\n\nvoid ClientSinkBridge::consume() {\n DCHECK(evb_);\n evb_->runInEventBaseThread(\n [self = copy()]() mutable { self->processServerMessages(); });\n}\n\nvoid ClientSinkBridge::processServerMessages() {\n if (!serverCallback_) {\n return;\n }\n\n do {\n for (auto messages = serverGetMessages(); !messages.empty();\n messages.pop()) {\n bool terminated = false;\n auto& payload = messages.front();\n if (payload.hasException()) {\n serverCallback_->onSinkError(std::move(payload).exception());\n terminated = true;\n } else if (payload.hasValue()) {\n terminated = !serverCallback_->onSinkNext(std::move(payload).value());\n } else {\n terminated = !serverCallback_->onSinkComplete();\n }\n\n if (terminated) {\n close();\n return;\n }\n }\n } while (!serverWait(this));\n}\n\nbool ClientSinkBridge::hasServerCancelled() {\n return serverCancelSource_.isCancellationRequested();\n}\n\n} \/\/ namespace detail\n} \/\/ namespace thrift\n} \/\/ namespace apache\n<commit_msg>Tighten scopes in ClientSinkBridge::sink<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\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#include <thrift\/lib\/cpp2\/async\/ClientSinkBridge.h>\n\n#include <folly\/Overload.h>\n\nnamespace apache {\nnamespace thrift {\nnamespace detail {\n\n\/\/ Explicitly instantiate the base of ClientSinkBridge\ntemplate class TwoWayBridge<\n ClientSinkConsumer,\n ClientMessage,\n ClientSinkBridge,\n ServerMessage,\n ClientSinkBridge>;\n\nClientSinkBridge::ClientSinkBridge(FirstResponseCallback* callback)\n : firstResponseCallback_(callback) {}\n\nClientSinkBridge::~ClientSinkBridge() {}\n\nSinkClientCallback* ClientSinkBridge::create(FirstResponseCallback* callback) {\n return new ClientSinkBridge(callback);\n}\n\nvoid ClientSinkBridge::close() {\n serverClose();\n serverCallback_ = nullptr;\n evb_.reset();\n Ptr(this);\n}\n\nbool ClientSinkBridge::wait(ClientSinkConsumer* consumer) {\n return clientWait(consumer);\n}\n\nvoid ClientSinkBridge::push(ServerMessage&& value) {\n clientPush(std::move(value));\n}\n\nClientSinkBridge::ClientQueue ClientSinkBridge::getMessages() {\n return clientGetMessages();\n}\n\n#if FOLLY_HAS_COROUTINES\n\nfolly::coro::Task<folly::Try<StreamPayload>> ClientSinkBridge::sink(\n folly::coro::AsyncGenerator<folly::Try<StreamPayload>&&> generator) {\n uint64_t credits = 0;\n const auto& clientCancelToken =\n co_await folly::coro::co_current_cancellation_token;\n auto mergedToken = folly::CancellationToken::merge(\n serverCancelSource_.getToken(), clientCancelToken);\n bool sinkComplete = false;\n\n while (true) {\n if (CoroConsumer consumer; clientWait(&consumer)) {\n folly::CancellationCallback cb{\n clientCancelToken, [&]() {\n if (auto* cancelledCb = cancelClientWait()) {\n cancelledCb->canceled();\n }\n }};\n co_await consumer.wait();\n }\n\n for (auto queue = clientGetMessages(); !queue.empty(); queue.pop()) {\n auto& message = queue.front();\n if (auto* n = std::get_if<uint64_t>(&message)) {\n credits += *n;\n } else {\n co_return std::get<folly::Try<StreamPayload>>(std::move(message));\n }\n }\n\n if (clientCancelToken.isCancellationRequested()) {\n if (!sinkComplete) {\n clientPush(folly::Try<apache::thrift::StreamPayload>(\n rocket::RocketException(rocket::ErrorCode::CANCELED)));\n }\n co_yield folly::coro::co_cancelled;\n }\n\n while (credits > 0 && !sinkComplete &&\n !serverCancelSource_.isCancellationRequested()) {\n auto item = co_await folly::coro::co_withCancellation(\n mergedToken, generator.next());\n if (serverCancelSource_.isCancellationRequested()) {\n break;\n }\n\n if (clientCancelToken.isCancellationRequested()) {\n clientPush(folly::Try<apache::thrift::StreamPayload>(\n rocket::RocketException(rocket::ErrorCode::CANCELED)));\n co_yield folly::coro::co_cancelled;\n }\n\n if (item.has_value()) {\n if ((*item).hasValue()) {\n clientPush(std::move(*item));\n } else {\n clientPush(std::move(*item));\n \/\/ AsyncGenerator who serialized and yield the exception also in\n \/\/ charge of propagating it back to user, just return empty Try\n \/\/ here.\n co_return folly::Try<StreamPayload>();\n }\n } else {\n clientPush({});\n sinkComplete = true;\n \/\/ release generator\n generator = {};\n }\n credits--;\n }\n }\n}\n\n#endif\n\nvoid ClientSinkBridge::cancel(folly::Try<StreamPayload> payload) {\n CHECK(payload.hasException());\n clientPush(std::move(payload));\n}\n\n\/\/ SinkClientCallback method\nbool ClientSinkBridge::onFirstResponse(\n FirstResponsePayload&& firstPayload,\n folly::EventBase* evb,\n SinkServerCallback* serverCallback) {\n auto firstResponseCallback = firstResponseCallback_;\n serverCallback_ = serverCallback;\n evb_ = folly::getKeepAliveToken(evb);\n bool scheduledWait = serverWait(this);\n DCHECK(scheduledWait);\n firstResponseCallback->onFirstResponse(std::move(firstPayload), copy());\n return true;\n}\n\nvoid ClientSinkBridge::onFirstResponseError(folly::exception_wrapper ew) {\n firstResponseCallback_->onFirstResponseError(std::move(ew));\n close();\n}\n\nvoid ClientSinkBridge::onFinalResponse(StreamPayload&& payload) {\n serverPush(folly::Try<StreamPayload>(std::move(payload)));\n serverCancelSource_.requestCancellation();\n close();\n}\n\nvoid ClientSinkBridge::onFinalResponseError(folly::exception_wrapper ew) {\n using apache::thrift::detail::EncodedError;\n auto rex = ew.get_exception<rocket::RocketException>();\n auto payload = rex\n ? folly::Try<StreamPayload>(EncodedError(rex->moveErrorData()))\n : folly::Try<StreamPayload>(std::move(ew));\n serverPush(std::move(payload));\n serverCancelSource_.requestCancellation();\n close();\n}\n\nbool ClientSinkBridge::onSinkRequestN(uint64_t n) {\n serverPush(n);\n return true;\n}\n\nvoid ClientSinkBridge::resetServerCallback(SinkServerCallback& serverCallback) {\n serverCallback_ = &serverCallback;\n}\n\nvoid ClientSinkBridge::consume() {\n DCHECK(evb_);\n evb_->runInEventBaseThread(\n [self = copy()]() mutable { self->processServerMessages(); });\n}\n\nvoid ClientSinkBridge::processServerMessages() {\n if (!serverCallback_) {\n return;\n }\n\n do {\n for (auto messages = serverGetMessages(); !messages.empty();\n messages.pop()) {\n bool terminated = false;\n auto& payload = messages.front();\n if (payload.hasException()) {\n serverCallback_->onSinkError(std::move(payload).exception());\n terminated = true;\n } else if (payload.hasValue()) {\n terminated = !serverCallback_->onSinkNext(std::move(payload).value());\n } else {\n terminated = !serverCallback_->onSinkComplete();\n }\n\n if (terminated) {\n close();\n return;\n }\n }\n } while (!serverWait(this));\n}\n\nbool ClientSinkBridge::hasServerCancelled() {\n return serverCancelSource_.isCancellationRequested();\n}\n\n} \/\/ namespace detail\n} \/\/ namespace thrift\n} \/\/ namespace apache\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ngtcp2\n *\n * Copyright (c) 2017 ngtcp2 contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include \"debug.h\"\n\n#include <cassert>\n#include <random>\n#include <iostream>\n\n#include \"util.h\"\n\nnamespace ngtcp2 {\n\nnamespace debug {\n\nnamespace {\nauto randgen = util::make_mt19937();\n} \/\/ namespace\n\nnamespace {\nauto *outfile = stderr;\n} \/\/ namespace\n\nint handshake_completed(ngtcp2_conn *conn, void *user_data) {\n fprintf(outfile, \"QUIC handshake has completed\\n\");\n return 0;\n}\n\nbool packet_lost(double prob) {\n auto p = std::uniform_real_distribution<>(0, 1)(randgen);\n return p < prob;\n}\n\nvoid print_crypto_data(ngtcp2_crypto_level crypto_level, const uint8_t *data,\n size_t datalen) {\n const char *crypto_level_str;\n switch (crypto_level) {\n case NGTCP2_CRYPTO_LEVEL_INITIAL:\n crypto_level_str = \"Initial\";\n break;\n case NGTCP2_CRYPTO_LEVEL_HANDSHAKE:\n crypto_level_str = \"Handshake\";\n break;\n case NGTCP2_CRYPTO_LEVEL_APP:\n crypto_level_str = \"Application\";\n break;\n default:\n assert(0);\n }\n fprintf(outfile, \"Ordered CRYPTO data in %s crypto level\\n\",\n crypto_level_str);\n util::hexdump(outfile, data, datalen);\n}\n\nvoid print_stream_data(int64_t stream_id, const uint8_t *data, size_t datalen) {\n fprintf(outfile, \"Ordered STREAM data stream_id=0x%\" PRIx64 \"\\n\", stream_id);\n util::hexdump(outfile, data, datalen);\n}\n\nvoid print_initial_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"initial_secret=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_client_in_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"client_in_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_server_in_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"server_in_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_handshake_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"handshake_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_client_hs_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"client_hs_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_server_hs_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"server_hs_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_client_0rtt_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"client_0rtt_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_client_1rtt_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"client_1rtt_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_server_1rtt_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"server_1rtt_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_client_pp_key(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ client_pp_key=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_server_pp_key(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ server_pp_key=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_client_pp_iv(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ client_pp_iv=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_server_pp_iv(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ server_pp_iv=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_client_pp_hp(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ client_pp_hp=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_server_pp_hp(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ server_pp_hp=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_secrets(const uint8_t *secret, size_t secretlen, const uint8_t *key,\n size_t keylen, const uint8_t *iv, size_t ivlen,\n const uint8_t *hp, size_t hplen) {\n std::cerr << \"+ secret=\" << util::format_hex(secret, secretlen) << \"\\n\"\n << \"+ key=\" << util::format_hex(key, keylen) << \"\\n\"\n << \"+ iv=\" << util::format_hex(iv, ivlen) << \"\\n\"\n << \"+ hp=\" << util::format_hex(hp, hplen) << std::endl;\n}\n\nvoid print_secrets(const uint8_t *secret, size_t secretlen, const uint8_t *key,\n size_t keylen, const uint8_t *iv, size_t ivlen) {\n std::cerr << \"+ secret=\" << util::format_hex(secret, secretlen) << \"\\n\"\n << \"+ key=\" << util::format_hex(key, keylen) << \"\\n\"\n << \"+ iv=\" << util::format_hex(iv, ivlen) << std::endl;\n}\n\nvoid print_hp_mask(const uint8_t *mask, size_t masklen, const uint8_t *sample,\n size_t samplelen) {\n fprintf(outfile, \"mask=%s sample=%s\\n\",\n util::format_hex(mask, masklen).c_str(),\n util::format_hex(sample, samplelen).c_str());\n}\n\nvoid log_printf(void *user_data, const char *fmt, ...) {\n va_list ap;\n\n va_start(ap, fmt);\n vfprintf(stderr, fmt, ap);\n va_end(ap);\n\n fprintf(stderr, \"\\n\");\n}\n\nvoid path_validation(const ngtcp2_path *path,\n ngtcp2_path_validation_result res) {\n auto local_addr = util::straddr(\n reinterpret_cast<sockaddr *>(path->local.addr), path->local.addrlen);\n auto remote_addr = util::straddr(\n reinterpret_cast<sockaddr *>(path->remote.addr), path->remote.addrlen);\n\n std::cerr << \"Path validation against path {local:\" << local_addr\n << \", remote:\" << remote_addr << \"} \"\n << (res == NGTCP2_PATH_VALIDATION_RESULT_SUCCESS ? \"succeeded\"\n : \"failed\")\n << std::endl;\n}\n\nvoid print_http_begin_request_headers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" request headers started\\n\",\n stream_id);\n}\n\nvoid print_http_begin_response_headers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" response headers started\\n\",\n stream_id);\n}\n\nnamespace {\nvoid print_header(const uint8_t *name, const uint8_t *value, uint8_t flags) {\n fprintf(outfile, \"[%s: %s]%s\\n\", name, value,\n (flags & NGHTTP3_NV_FLAG_NEVER_INDEX) ? \"(sensitive)\" : \"\");\n}\n} \/\/ namespace\n\nnamespace {\nvoid print_header(const nghttp3_rcbuf *name, const nghttp3_rcbuf *value,\n uint8_t flags) {\n print_header(nghttp3_rcbuf_get_buf(name).base,\n nghttp3_rcbuf_get_buf(value).base, flags);\n}\n} \/\/ namespace\n\nnamespace {\nvoid print_header(const nghttp3_nv &nv) {\n print_header(nv.name, nv.value, nv.flags);\n}\n} \/\/ namespace\n\nvoid print_http_header(int64_t stream_id, const nghttp3_rcbuf *name,\n const nghttp3_rcbuf *value, uint8_t flags) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" \", stream_id);\n print_header(name, value, flags);\n}\n\nvoid print_http_end_headers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" headers ended\\n\", stream_id);\n}\n\nvoid print_http_data(int64_t stream_id, const uint8_t *data, size_t datalen) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" body %zu bytes\\n\", stream_id,\n datalen);\n util::hexdump(outfile, data, datalen);\n}\n\nvoid print_http_begin_trailers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" trailers started\\n\", stream_id);\n}\n\nvoid print_http_end_trailers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" trailers ended\\n\", stream_id);\n}\n\nvoid print_http_begin_push_promise(int64_t stream_id, int64_t push_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" push 0x%\" PRIx64 \" started\\n\",\n stream_id, push_id);\n}\n\nvoid print_http_push_promise(int64_t stream_id, int64_t push_id,\n const nghttp3_rcbuf *name,\n const nghttp3_rcbuf *value, uint8_t flags) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" push 0x%\" PRIx64 \" \", stream_id,\n push_id);\n print_header(name, value, flags);\n}\n\nvoid print_http_end_push_promise(int64_t stream_id, int64_t push_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" push 0x%\" PRIx64 \" ended\\n\",\n stream_id, push_id);\n}\n\nvoid cancel_push(int64_t push_id, int64_t stream_id) {\n fprintf(outfile,\n \"http: push 0x%\" PRIx64 \" (stream 0x%\" PRIx64\n \") has been cancelled by remote endpoint\\n\",\n push_id, stream_id);\n}\n\nvoid push_stream(int64_t push_id, int64_t stream_id) {\n fprintf(outfile,\n \"http: push 0x%\" PRIx64 \" promise fulfilled stream 0x%\" PRIx64 \"\\n\",\n push_id, stream_id);\n}\n\nvoid print_http_request_headers(int64_t stream_id, const nghttp3_nv *nva,\n size_t nvlen) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" submit request headers\\n\",\n stream_id);\n for (size_t i = 0; i < nvlen; ++i) {\n auto &nv = nva[i];\n print_header(nv);\n }\n}\n\nvoid print_http_response_headers(int64_t stream_id, const nghttp3_nv *nva,\n size_t nvlen) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" submit response headers\\n\",\n stream_id);\n for (size_t i = 0; i < nvlen; ++i) {\n auto &nv = nva[i];\n print_header(nv);\n }\n}\n\nvoid print_http_push_promise(int64_t stream_id, int64_t push_id,\n const nghttp3_nv *nva, size_t nvlen) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" submit push 0x%\" PRIx64 \"\\n\",\n stream_id, push_id);\n for (size_t i = 0; i < nvlen; ++i) {\n auto &nv = nva[i];\n print_header(nv);\n }\n}\n\n} \/\/ namespace debug\n\n} \/\/ namespace ngtcp2\n<commit_msg>Fix header printing bug<commit_after>\/*\n * ngtcp2\n *\n * Copyright (c) 2017 ngtcp2 contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include \"debug.h\"\n\n#include <cassert>\n#include <random>\n#include <iostream>\n\n#include \"util.h\"\n\nnamespace ngtcp2 {\n\nnamespace debug {\n\nnamespace {\nauto randgen = util::make_mt19937();\n} \/\/ namespace\n\nnamespace {\nauto *outfile = stderr;\n} \/\/ namespace\n\nint handshake_completed(ngtcp2_conn *conn, void *user_data) {\n fprintf(outfile, \"QUIC handshake has completed\\n\");\n return 0;\n}\n\nbool packet_lost(double prob) {\n auto p = std::uniform_real_distribution<>(0, 1)(randgen);\n return p < prob;\n}\n\nvoid print_crypto_data(ngtcp2_crypto_level crypto_level, const uint8_t *data,\n size_t datalen) {\n const char *crypto_level_str;\n switch (crypto_level) {\n case NGTCP2_CRYPTO_LEVEL_INITIAL:\n crypto_level_str = \"Initial\";\n break;\n case NGTCP2_CRYPTO_LEVEL_HANDSHAKE:\n crypto_level_str = \"Handshake\";\n break;\n case NGTCP2_CRYPTO_LEVEL_APP:\n crypto_level_str = \"Application\";\n break;\n default:\n assert(0);\n }\n fprintf(outfile, \"Ordered CRYPTO data in %s crypto level\\n\",\n crypto_level_str);\n util::hexdump(outfile, data, datalen);\n}\n\nvoid print_stream_data(int64_t stream_id, const uint8_t *data, size_t datalen) {\n fprintf(outfile, \"Ordered STREAM data stream_id=0x%\" PRIx64 \"\\n\", stream_id);\n util::hexdump(outfile, data, datalen);\n}\n\nvoid print_initial_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"initial_secret=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_client_in_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"client_in_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_server_in_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"server_in_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_handshake_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"handshake_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_client_hs_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"client_hs_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_server_hs_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"server_hs_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_client_0rtt_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"client_0rtt_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_client_1rtt_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"client_1rtt_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_server_1rtt_secret(const uint8_t *data, size_t len) {\n fprintf(outfile, \"server_1rtt_secret=%s\\n\",\n util::format_hex(data, len).c_str());\n}\n\nvoid print_client_pp_key(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ client_pp_key=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_server_pp_key(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ server_pp_key=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_client_pp_iv(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ client_pp_iv=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_server_pp_iv(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ server_pp_iv=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_client_pp_hp(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ client_pp_hp=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_server_pp_hp(const uint8_t *data, size_t len) {\n fprintf(outfile, \"+ server_pp_hp=%s\\n\", util::format_hex(data, len).c_str());\n}\n\nvoid print_secrets(const uint8_t *secret, size_t secretlen, const uint8_t *key,\n size_t keylen, const uint8_t *iv, size_t ivlen,\n const uint8_t *hp, size_t hplen) {\n std::cerr << \"+ secret=\" << util::format_hex(secret, secretlen) << \"\\n\"\n << \"+ key=\" << util::format_hex(key, keylen) << \"\\n\"\n << \"+ iv=\" << util::format_hex(iv, ivlen) << \"\\n\"\n << \"+ hp=\" << util::format_hex(hp, hplen) << std::endl;\n}\n\nvoid print_secrets(const uint8_t *secret, size_t secretlen, const uint8_t *key,\n size_t keylen, const uint8_t *iv, size_t ivlen) {\n std::cerr << \"+ secret=\" << util::format_hex(secret, secretlen) << \"\\n\"\n << \"+ key=\" << util::format_hex(key, keylen) << \"\\n\"\n << \"+ iv=\" << util::format_hex(iv, ivlen) << std::endl;\n}\n\nvoid print_hp_mask(const uint8_t *mask, size_t masklen, const uint8_t *sample,\n size_t samplelen) {\n fprintf(outfile, \"mask=%s sample=%s\\n\",\n util::format_hex(mask, masklen).c_str(),\n util::format_hex(sample, samplelen).c_str());\n}\n\nvoid log_printf(void *user_data, const char *fmt, ...) {\n va_list ap;\n\n va_start(ap, fmt);\n vfprintf(stderr, fmt, ap);\n va_end(ap);\n\n fprintf(stderr, \"\\n\");\n}\n\nvoid path_validation(const ngtcp2_path *path,\n ngtcp2_path_validation_result res) {\n auto local_addr = util::straddr(\n reinterpret_cast<sockaddr *>(path->local.addr), path->local.addrlen);\n auto remote_addr = util::straddr(\n reinterpret_cast<sockaddr *>(path->remote.addr), path->remote.addrlen);\n\n std::cerr << \"Path validation against path {local:\" << local_addr\n << \", remote:\" << remote_addr << \"} \"\n << (res == NGTCP2_PATH_VALIDATION_RESULT_SUCCESS ? \"succeeded\"\n : \"failed\")\n << std::endl;\n}\n\nvoid print_http_begin_request_headers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" request headers started\\n\",\n stream_id);\n}\n\nvoid print_http_begin_response_headers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" response headers started\\n\",\n stream_id);\n}\n\nnamespace {\nvoid print_header(const uint8_t *name, size_t namelen, const uint8_t *value,\n size_t valuelen, uint8_t flags) {\n fprintf(outfile, \"[%.*s: %.*s]%s\\n\", static_cast<int>(namelen), name,\n static_cast<int>(valuelen), value,\n (flags & NGHTTP3_NV_FLAG_NEVER_INDEX) ? \"(sensitive)\" : \"\");\n}\n} \/\/ namespace\n\nnamespace {\nvoid print_header(const nghttp3_rcbuf *name, const nghttp3_rcbuf *value,\n uint8_t flags) {\n auto namebuf = nghttp3_rcbuf_get_buf(name);\n auto valuebuf = nghttp3_rcbuf_get_buf(value);\n print_header(namebuf.base, namebuf.len, valuebuf.base, valuebuf.len, flags);\n}\n} \/\/ namespace\n\nnamespace {\nvoid print_header(const nghttp3_nv &nv) {\n print_header(nv.name, nv.namelen, nv.value, nv.valuelen, nv.flags);\n}\n} \/\/ namespace\n\nvoid print_http_header(int64_t stream_id, const nghttp3_rcbuf *name,\n const nghttp3_rcbuf *value, uint8_t flags) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" \", stream_id);\n print_header(name, value, flags);\n}\n\nvoid print_http_end_headers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" headers ended\\n\", stream_id);\n}\n\nvoid print_http_data(int64_t stream_id, const uint8_t *data, size_t datalen) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" body %zu bytes\\n\", stream_id,\n datalen);\n util::hexdump(outfile, data, datalen);\n}\n\nvoid print_http_begin_trailers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" trailers started\\n\", stream_id);\n}\n\nvoid print_http_end_trailers(int64_t stream_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" trailers ended\\n\", stream_id);\n}\n\nvoid print_http_begin_push_promise(int64_t stream_id, int64_t push_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" push 0x%\" PRIx64 \" started\\n\",\n stream_id, push_id);\n}\n\nvoid print_http_push_promise(int64_t stream_id, int64_t push_id,\n const nghttp3_rcbuf *name,\n const nghttp3_rcbuf *value, uint8_t flags) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" push 0x%\" PRIx64 \" \", stream_id,\n push_id);\n print_header(name, value, flags);\n}\n\nvoid print_http_end_push_promise(int64_t stream_id, int64_t push_id) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" push 0x%\" PRIx64 \" ended\\n\",\n stream_id, push_id);\n}\n\nvoid cancel_push(int64_t push_id, int64_t stream_id) {\n fprintf(outfile,\n \"http: push 0x%\" PRIx64 \" (stream 0x%\" PRIx64\n \") has been cancelled by remote endpoint\\n\",\n push_id, stream_id);\n}\n\nvoid push_stream(int64_t push_id, int64_t stream_id) {\n fprintf(outfile,\n \"http: push 0x%\" PRIx64 \" promise fulfilled stream 0x%\" PRIx64 \"\\n\",\n push_id, stream_id);\n}\n\nvoid print_http_request_headers(int64_t stream_id, const nghttp3_nv *nva,\n size_t nvlen) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" submit request headers\\n\",\n stream_id);\n for (size_t i = 0; i < nvlen; ++i) {\n auto &nv = nva[i];\n print_header(nv);\n }\n}\n\nvoid print_http_response_headers(int64_t stream_id, const nghttp3_nv *nva,\n size_t nvlen) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" submit response headers\\n\",\n stream_id);\n for (size_t i = 0; i < nvlen; ++i) {\n auto &nv = nva[i];\n print_header(nv);\n }\n}\n\nvoid print_http_push_promise(int64_t stream_id, int64_t push_id,\n const nghttp3_nv *nva, size_t nvlen) {\n fprintf(outfile, \"http: stream 0x%\" PRIx64 \" submit push 0x%\" PRIx64 \"\\n\",\n stream_id, push_id);\n for (size_t i = 0; i < nvlen; ++i) {\n auto &nv = nva[i];\n print_header(nv);\n }\n}\n\n} \/\/ namespace debug\n\n} \/\/ namespace ngtcp2\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 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. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"JpegCompressor.h\"\n\n#include \"logging\/Logger.h\"\n\n#include <jpeglib.h>\n\n#include <cerrno>\n#include <cstring>\n#include <memory>\n#include <setjmp.h>\n\nnamespace medialibrary\n{\n\nconst char* JpegCompressor::extension() const\n{\n return \"jpg\";\n}\n\nconst char* JpegCompressor::fourCC() const\n{\n return \"RV24\";\n}\n\nuint32_t JpegCompressor::bpp() const\n{\n return 3;\n}\n\nstruct jpegError : public jpeg_error_mgr\n{\n jmp_buf buff;\n char message[JMSG_LENGTH_MAX];\n\n static void jpegErrorHandler( j_common_ptr common )\n {\n auto error = reinterpret_cast<jpegError*>( common->err );\n (*error->format_message)( common, error->message );\n longjmp( error->buff, 1 );\n }\n};\n\nbool JpegCompressor::compress( const uint8_t* buffer, const std::string& outputFile,\n uint32_t inputWidth, uint32_t,\n uint32_t outputWidth, uint32_t outputHeight,\n uint32_t hOffset, uint32_t vOffset )\n{\n const auto stride = inputWidth * bpp();\n\n \/\/FIXME: Abstract this away, though libjpeg requires a FILE*...\n auto fOut = std::unique_ptr<FILE, int(*)(FILE*)>( fopen( outputFile.c_str(), \"wb\" ), &fclose );\n if ( fOut == nullptr )\n {\n LOG_ERROR( \"Failed to open thumbnail file \", outputFile, '(', strerror( errno ), ')' );\n return false;\n }\n\n jpeg_compress_struct compInfo;\n JSAMPROW row_pointer[1];\n\n \/\/libjpeg's default error handling is to call exit(), which would\n \/\/be slightly problematic...\n jpegError err;\n compInfo.err = jpeg_std_error(&err);\n err.error_exit = jpegError::jpegErrorHandler;\n\n if ( setjmp( err.buff ) )\n {\n LOG_ERROR(\"JPEG failure: \", err.message);\n jpeg_destroy_compress(&compInfo);\n return false;\n }\n\n jpeg_create_compress(&compInfo);\n jpeg_stdio_dest(&compInfo, fOut.get());\n\n compInfo.image_width = outputWidth;\n compInfo.image_height = outputHeight;\n compInfo.input_components = bpp();\n compInfo.in_color_space = JCS_RGB;\n jpeg_set_defaults( &compInfo );\n jpeg_set_quality( &compInfo, 85, TRUE );\n\n jpeg_start_compress( &compInfo, TRUE );\n\n while ( compInfo.next_scanline < outputHeight )\n {\n row_pointer[0] = const_cast<uint8_t*>( &buffer[(compInfo.next_scanline + vOffset ) * stride + hOffset * bpp()] );\n jpeg_write_scanlines(&compInfo, row_pointer, 1);\n }\n jpeg_finish_compress(&compInfo);\n jpeg_destroy_compress(&compInfo);\n return true;\n}\n\n}\n<commit_msg>JpegCompressor: Reduce quality to 80<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 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. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"JpegCompressor.h\"\n\n#include \"logging\/Logger.h\"\n\n#include <jpeglib.h>\n\n#include <cerrno>\n#include <cstring>\n#include <memory>\n#include <setjmp.h>\n\nnamespace medialibrary\n{\n\nconst char* JpegCompressor::extension() const\n{\n return \"jpg\";\n}\n\nconst char* JpegCompressor::fourCC() const\n{\n return \"RV24\";\n}\n\nuint32_t JpegCompressor::bpp() const\n{\n return 3;\n}\n\nstruct jpegError : public jpeg_error_mgr\n{\n jmp_buf buff;\n char message[JMSG_LENGTH_MAX];\n\n static void jpegErrorHandler( j_common_ptr common )\n {\n auto error = reinterpret_cast<jpegError*>( common->err );\n (*error->format_message)( common, error->message );\n longjmp( error->buff, 1 );\n }\n};\n\nbool JpegCompressor::compress( const uint8_t* buffer, const std::string& outputFile,\n uint32_t inputWidth, uint32_t,\n uint32_t outputWidth, uint32_t outputHeight,\n uint32_t hOffset, uint32_t vOffset )\n{\n const auto stride = inputWidth * bpp();\n\n \/\/FIXME: Abstract this away, though libjpeg requires a FILE*...\n auto fOut = std::unique_ptr<FILE, int(*)(FILE*)>( fopen( outputFile.c_str(), \"wb\" ), &fclose );\n if ( fOut == nullptr )\n {\n LOG_ERROR( \"Failed to open thumbnail file \", outputFile, '(', strerror( errno ), ')' );\n return false;\n }\n\n jpeg_compress_struct compInfo;\n JSAMPROW row_pointer[1];\n\n \/\/libjpeg's default error handling is to call exit(), which would\n \/\/be slightly problematic...\n jpegError err;\n compInfo.err = jpeg_std_error(&err);\n err.error_exit = jpegError::jpegErrorHandler;\n\n if ( setjmp( err.buff ) )\n {\n LOG_ERROR(\"JPEG failure: \", err.message);\n jpeg_destroy_compress(&compInfo);\n return false;\n }\n\n jpeg_create_compress(&compInfo);\n jpeg_stdio_dest(&compInfo, fOut.get());\n\n compInfo.image_width = outputWidth;\n compInfo.image_height = outputHeight;\n compInfo.input_components = bpp();\n compInfo.in_color_space = JCS_RGB;\n jpeg_set_defaults( &compInfo );\n jpeg_set_quality( &compInfo, 80, TRUE );\n\n jpeg_start_compress( &compInfo, TRUE );\n\n while ( compInfo.next_scanline < outputHeight )\n {\n row_pointer[0] = const_cast<uint8_t*>( &buffer[(compInfo.next_scanline + vOffset ) * stride + hOffset * bpp()] );\n jpeg_write_scanlines(&compInfo, row_pointer, 1);\n }\n jpeg_finish_compress(&compInfo);\n jpeg_destroy_compress(&compInfo);\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ test_observer.cpp\n\/\/ hardware-control\n\/\/\n\/\/ Created by Julian Becker on 03.09.15.\n\/\/ Copyright (c) 2015 Julian Becker. All rights reserved.\n\/\/\n#include \"..\/catch.h\"\n#include <stdio.h>\n#include <memory>\n#include <list>\n#include <map>\n#include <functional>\n\ntemplate <typename T> struct\ninotifyable {\n virtual void handle(T&&) = 0;\n};\n\ntemplate <typename _Kty> struct\nwith_destructor {\n std::map<_Kty,std::function<void()>> functors;\npublic:\n template <typename Callable>\n void add_raii(_Kty key, Callable fun) {\n functors[std::move(key)] = std::move(fun);\n }\n\n void remove_raii(_Kty key) {\n functors.erase(std::move(key));\n }\n \n virtual ~with_destructor() {\n for(auto& f : functors)\n f.second();\n }\n};\n\ntemplate <typename T> struct\nilistener;\n\ntemplate <typename T> struct\niobservable;\n\n\ntemplate <typename T> struct\nilistener : inotifyable<T>, with_destructor<iobservable<T>*> {\n};\n\ntemplate <typename T> struct\niobservable {\n};\n\n\ntemplate <typename T>\nclass listener;\n\n\n\ntemplate <typename T>\nclass observable : public iobservable<T> {\n T value;\n std::set<ilistener<T>*> listeners;\n \npublic:\n observable(T value)\n : value(value)\n {\n }\n \n observable(const observable& other)\n : value(other.value), listeners(other.listeners)\n {\n for(auto& l : listeners)\n l->add_raii(this,[this,&l]{ unregisterListener(*l); });\n }\n\n observable(observable&& other)\n : value(std::move(other.value)), listeners(std::move(other.listeners))\n {\n for(auto& l : listeners) {\n l->remove_raii(&other);\n l->add_raii(this,[this,&l]{ unregisterListener(*l); });\n }\n }\n \n observable& operator = (const observable& other) {\n if(this != &other) {\n observable copy(other);\n *this = std::move(copy);\n }\n return *this;\n }\n \n observable& operator = (observable&& other) {\n listeners = std::move(other.listeners);\n value = std::move(value);\n for(auto& l : listeners) {\n l->remove_raii(&other);\n l->add_raii(this,[this,&l]{ unregisterListener(*l); });\n }\n return *this;\n }\n\n ~observable() {\n for(auto& l : listeners)\n l->remove_raii(this);\n }\n\n void registerListener(ilistener<T>& l) {\n listeners.insert(&l);\n l.add_raii(this,[this,&l]{ unregisterListener(l); });\n }\n\n void unregisterListener(ilistener<T>& l) {\n listeners.erase(&l);\n }\n \n observable& operator=(const T& val) {\n value = val;\n for(auto& lstnr : listeners)\n lstnr->handle(T(val));\n return *this;\n }\n \n operator const T& () const {\n return value;\n }\n\n};\n\n\n\n\n\ntemplate <typename T>\nclass listener final : public ilistener<T> {\n std::function<void(T&&)> behavior;\n \npublic:\n template <typename LAMBDA>\n listener(LAMBDA lam)\n : behavior(std::forward<LAMBDA>(lam))\n {\n }\n \n void handle(T&& arg) override {\n behavior(std::move(arg));\n }\n \n ~listener() {\n }\n};\n\n\n\nTEST_CASE( \"Create an observable\", \"[observable]\" ) {\n WHEN(\"constructing an observable<int>\") {\n THEN(\"no exception is thrown\") {\n REQUIRE_NOTHROW(observable<int>(0));\n }\n }\n \n WHEN(\"consturcting an observable<T> with T throwing in its constructor\") {\n struct t_throws_in_constructor {\n t_throws_in_constructor() { throw nullptr; }\n };\n THEN(\"the constructor of observable<T> will also throw\") {\n REQUIRE_THROWS_AS(t_throws_in_constructor(), std::nullptr_t);\n }\n }\n}\n\n\n\n\n\n\nTEST_CASE( \"Create a listener\", \"[listener]\" ) {\n WHEN(\"constructing an listener<int>\") {\n THEN(\"no exception is thrown\") {\n REQUIRE_NOTHROW(listener<int>([](int&&){}));\n }\n }\n}\n\nTEST_CASE(\"Register listener at observable\", \"[observable][listener]\") {\n GIVEN(\"a listener and an observable\") {\n observable<int> obs(0);\n listener<int> lst([](int&&){});\n WHEN(\"registering the listener at the observable\") {\n THEN(\"no exception is thrown\") {\n REQUIRE_NOTHROW(obs.registerListener(lst));\n }\n }\n }\n}\n\n\nTEST_CASE(\"Observable is copyable\", \"[observable][listener]\") {\n observable<int> obs(0);\n observable<int> obsCopy(obs);\n}\n\n\nTEST_CASE(\"Observable copy behaves exactly like the original\", \"[observable][listener]\") {\n GIVEN(\"an observable and a listener registered at the observable\") {\n observable<int> obs(0);\n bool triggered = false;\n listener<int> lst([&triggered](int&&){ triggered = true; });\n obs.registerListener(lst);\n \n THEN(\"creating a copy of the observabe and modifying the value of the copy will trigger all listeners that have been registered at the initial observable\") {\n observable<int> obsCopy(obs);\n obsCopy = 42;\n REQUIRE(triggered);\n }\n }\n}\n\n\nTEST_CASE(\"Observable copy does not result in segfault\", \"[observable][listener]\") {\n GIVEN(\"an observable and a listener registered at the observable\") {\n auto obs = std::make_shared<observable<int>>(0);\n bool triggered = false;\n auto lst = std::make_shared<listener<int>>([&triggered](int&&){ triggered = true; });\n obs->registerListener(*lst);\n \n THEN(\"creating a copy of the observabe and destroying the original and the listener will not result in a segfault (and will not trigger the listener)\") {\n observable<int> obsCopy(*obs);\n obs = nullptr;\n lst = nullptr;\n REQUIRE(!triggered);\n }\n\n AND_THEN(\"modifying the copied observable after the original has been destroyed still triggers the listener\") {\n observable<int> obsCopy(*obs);\n obs = nullptr;\n obsCopy = 42;\n REQUIRE(triggered);\n }\n }\n}\n\nTEST_CASE(\"Assign value to observable\",\"[observable]\") {\n GIVEN(\"We may assign an value to an observable\") {\n observable<int> obs(0);\n obs = 1;\n }\n\n WHEN(\"an observable is constructed\") {\n observable<int> obs(0x1337);\n THEN(\"the value it holds is the value given the constructor\") {\n REQUIRE(0x1337 == obs);\n }\n }\n \n WHEN(\"a value is assigned to an observable\") {\n observable<int> obs(0);\n obs = 42;\n THEN(\"the same value can be retrieved back from the observable\") {\n REQUIRE(42 == obs);\n }\n }\n}\n\nTEST_CASE(\"Assigning value triggers observer\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a listener<int>\") {\n observable<int> obs(0);\n bool triggered = false;\n listener<int> lstnr([&triggered](int&&){ triggered = true; });\n WHEN(\"listener registers at observable and a value is put into the observable\") {\n obs.registerListener(lstnr);\n obs = 42;\n THEN(\"the listener is triggered\") {\n REQUIRE(triggered);\n }\n }\n }\n}\n\n\nTEST_CASE(\"Assigning value triggers all listeners\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a several listener<int>\") {\n observable<int> obs(0);\n bool triggered1 = false, triggered2 = false, triggered3 = false;\n listener<int> lstnr1([&triggered1](int&&){ triggered1 = true; });\n listener<int> lstnr2([&triggered2](int&&){ triggered2 = true; });\n listener<int> lstnr3([&triggered3](int&&){ triggered3 = true; });\n WHEN(\"several listeners registers at observable and a value is put into the observable\") {\n obs.registerListener(lstnr1);\n obs.registerListener(lstnr2);\n obs.registerListener(lstnr3);\n obs = 42;\n THEN(\"all registered listeners are triggered\") {\n REQUIRE(triggered1);\n REQUIRE(triggered2);\n REQUIRE(triggered3);\n }\n }\n }\n}\n\n\nTEST_CASE(\"Unregister listener\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a listener<int>\") {\n observable<int> obs(0);\n bool triggered = false;\n listener<int> lstnr([&triggered](int&&){ triggered = true; });\n WHEN(\"listener registers and unregisteres at the observable and a value is put into the observable\") {\n obs.registerListener(lstnr);\n obs.unregisterListener(lstnr);\n obs = 42;\n THEN(\"the listener is not triggered\") {\n REQUIRE(!triggered);\n }\n }\n }\n}\n\n\nTEST_CASE(\"destroying listener before observable must be safe\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a listener<int>\") {\n auto obs = std::make_shared<observable<int>>(0);\n bool triggered = false;\n auto lstnr = std::make_shared<listener<int>>([&triggered](int&&){ triggered = true; });\n \n WHEN(\"the listener is destroyed and the observable triggered\") {\n obs->registerListener(*lstnr);\n lstnr=0;\n *obs = 37;\n THEN(\"the program does not crash and the registered listener is still not triggered\") {\n REQUIRE(!triggered);\n }\n }\n }\n}\n\n\nTEST_CASE(\"destroying observable before listener must be safe\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a listener<int>\") {\n auto obs = std::make_shared<observable<int>>(0);\n auto lstnr = std::make_shared<listener<int>>([](int&&){});\n \n WHEN(\"the observable is destroyed the registered listener can be safely destructed\") {\n obs->registerListener(*lstnr);\n obs = nullptr;\n \n int* x;\n \n THEN(\"the program does not crash and the registered listener is still not triggered\") {\n lstnr = nullptr;\n }\n }\n }\n}\n\nTEST_CASE(\"moving an observable into another observable keeps the listeners intact\") {\n GIVEN(\"an observable and a listener\") {\n observable<int> obs(0);\n bool triggered = false;\n auto lstnr = std::make_shared<listener<int>>([&triggered](int&&){ triggered = true; });\n WHEN(\"the listener is registered it the observable\") {\n obs.registerListener(*lstnr);\n AND_WHEN(\"the observable is move-constructed into a different observable\") {\n observable<int> obs2(std::move(obs));\n THEN(\"modifying the moved-to observable will trigger the listener\") {\n obs2 = 42;\n REQUIRE(triggered);\n }\n }\n AND_WHEN(\"the observable is moved into a different observable\") {\n observable<int> obs2(0);\n obs2 = std::move(obs);\n THEN(\"modifying the moved-to observable will trigger the listener\") {\n obs2 = 42;\n REQUIRE(triggered);\n }\n }\n }\n }\n}<commit_msg>reworked test case to use a mock for ilistener<int> instead of the concrete class listener<int>.<commit_after>\/\/\n\/\/ test_observer.cpp\n\/\/ hardware-control\n\/\/\n\/\/ Created by Julian Becker on 03.09.15.\n\/\/ Copyright (c) 2015 Julian Becker. All rights reserved.\n\/\/\n#include \"..\/catch.h\"\n#include <stdio.h>\n#include <memory>\n#include <list>\n#include <map>\n#include <functional>\n\ntemplate <typename T> struct\ninotifyable {\n virtual void handle(T&&) = 0;\n};\n\ntemplate <typename _Kty> struct\nwith_destructor {\n std::map<_Kty,std::function<void()>> functors;\npublic:\n template <typename Callable>\n void add_raii(_Kty key, Callable fun) {\n functors[std::move(key)] = std::move(fun);\n }\n\n void remove_raii(_Kty key) {\n functors.erase(std::move(key));\n }\n \n virtual ~with_destructor() {\n for(auto& f : functors)\n f.second();\n }\n};\n\ntemplate <typename T> struct\nilistener;\n\ntemplate <typename T> struct\niobservable {\n virtual void registerListener(ilistener<T>& l) = 0;\n\n virtual void unregisterListener(ilistener<T>& l) = 0;\n};\n\n\ntemplate <typename T> struct\nilistener : inotifyable<T>, with_destructor<iobservable<T>*> {\n};\n\n\n\ntemplate <typename T>\nclass observable : public iobservable<T> {\n T value;\n std::set<ilistener<T>*> listeners;\n \npublic:\n observable(T value)\n : value(value)\n {\n }\n \n observable(const observable& other)\n : value(other.value), listeners(other.listeners)\n {\n for(auto& l : listeners)\n l->add_raii(this,[this,&l]{ unregisterListener(*l); });\n }\n\n observable(observable&& other)\n : value(std::move(other.value)), listeners(std::move(other.listeners))\n {\n for(auto& l : listeners) {\n l->remove_raii(&other);\n l->add_raii(this,[this,&l]{ unregisterListener(*l); });\n }\n }\n \n observable& operator = (const observable& other) {\n if(this != &other) {\n observable copy(other);\n *this = std::move(copy);\n }\n return *this;\n }\n \n observable& operator = (observable&& other) {\n listeners = std::move(other.listeners);\n value = std::move(value);\n for(auto& l : listeners) {\n l->remove_raii(&other);\n l->add_raii(this,[this,&l]{ unregisterListener(*l); });\n }\n return *this;\n }\n\n ~observable() {\n for(auto& l : listeners)\n l->remove_raii(this);\n }\n\n void registerListener(ilistener<T>& l) override {\n listeners.insert(&l);\n l.add_raii(this,[this,&l]{ unregisterListener(l); });\n }\n\n void unregisterListener(ilistener<T>& l) override {\n listeners.erase(&l);\n }\n \n observable& operator=(const T& val) {\n value = val;\n for(auto& lstnr : listeners)\n lstnr->handle(T(val));\n return *this;\n }\n \n operator const T& () const {\n return value;\n }\n\n};\n\n\n\n\n\ntemplate <typename T>\nclass listener final : public ilistener<T> {\n std::function<void(T&&)> behavior;\n \npublic:\n template <typename LAMBDA>\n listener(LAMBDA lam)\n : behavior(std::forward<LAMBDA>(lam))\n {\n }\n \n void handle(T&& arg) override {\n behavior(std::move(arg));\n }\n \n ~listener() {\n }\n};\n\n\n\nTEST_CASE( \"Create an observable\", \"[observable]\" ) {\n WHEN(\"constructing an observable<int>\") {\n THEN(\"no exception is thrown\") {\n REQUIRE_NOTHROW(observable<int>(0));\n }\n }\n \n WHEN(\"consturcting an observable<T> with T throwing in its constructor\") {\n struct t_throws_in_constructor {\n t_throws_in_constructor() { throw nullptr; }\n };\n THEN(\"the constructor of observable<T> will also throw\") {\n REQUIRE_THROWS_AS(t_throws_in_constructor(), std::nullptr_t);\n }\n }\n}\n\n\n\n\n\n\nTEST_CASE( \"Create a listener\", \"[listener]\" ) {\n WHEN(\"constructing an listener<int>\") {\n THEN(\"no exception is thrown\") {\n REQUIRE_NOTHROW(listener<int>([](int&&){}));\n }\n }\n}\n\nTEST_CASE(\"Register listener at observable\", \"[observable][listener]\") {\n GIVEN(\"a listener and an observable\") {\n observable<int> obs(0);\n listener<int> lst([](int&&){});\n WHEN(\"registering the listener at the observable\") {\n THEN(\"no exception is thrown\") {\n REQUIRE_NOTHROW(obs.registerListener(lst));\n }\n }\n }\n}\n\n\nTEST_CASE(\"Observable is copyable\", \"[observable]\") {\n observable<int> obs(0);\n observable<int> obsCopy(obs);\n}\n\n\nTEST_CASE(\"Observable copy behaves exactly like the original\", \"[observable]\") {\n GIVEN(\"an observable and a listener registered at the observable\") {\n struct test_listener final : ilistener<int> {\n int value = 0;\n bool triggered = false;\n \n void handle(int&& i) {\n value = i;\n triggered = true;\n }\n } lst;\n \n observable<int> obs(0);\n obs.registerListener(lst);\n \n THEN(\"creating a copy of the observabe and modifying the value of the copy will trigger all listeners that have been registered at the initial observable\") {\n observable<int> obsCopy(obs);\n obsCopy = 42;\n REQUIRE(lst.triggered);\n }\n }\n}\n\n\nTEST_CASE(\"Observable copy does not result in segfault\", \"[observable][listener]\") {\n GIVEN(\"an observable and a listener registered at the observable\") {\n auto obs = std::make_shared<observable<int>>(0);\n bool triggered = false;\n auto lst = std::make_shared<listener<int>>([&triggered](int&&){ triggered = true; });\n obs->registerListener(*lst);\n \n THEN(\"creating a copy of the observabe and destroying the original and the listener will not result in a segfault (and will not trigger the listener)\") {\n observable<int> obsCopy(*obs);\n obs = nullptr;\n lst = nullptr;\n REQUIRE(!triggered);\n }\n\n AND_THEN(\"modifying the copied observable after the original has been destroyed still triggers the listener\") {\n observable<int> obsCopy(*obs);\n obs = nullptr;\n obsCopy = 42;\n REQUIRE(triggered);\n }\n }\n}\n\nTEST_CASE(\"Assign value to observable\",\"[observable]\") {\n GIVEN(\"We may assign an value to an observable\") {\n observable<int> obs(0);\n obs = 1;\n }\n\n WHEN(\"an observable is constructed\") {\n observable<int> obs(0x1337);\n THEN(\"the value it holds is the value given the constructor\") {\n REQUIRE(0x1337 == obs);\n }\n }\n \n WHEN(\"a value is assigned to an observable\") {\n observable<int> obs(0);\n obs = 42;\n THEN(\"the same value can be retrieved back from the observable\") {\n REQUIRE(42 == obs);\n }\n }\n}\n\nTEST_CASE(\"Assigning value triggers observer\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a listener<int>\") {\n observable<int> obs(0);\n bool triggered = false;\n listener<int> lstnr([&triggered](int&&){ triggered = true; });\n WHEN(\"listener registers at observable and a value is put into the observable\") {\n obs.registerListener(lstnr);\n obs = 42;\n THEN(\"the listener is triggered\") {\n REQUIRE(triggered);\n }\n }\n }\n}\n\n\nTEST_CASE(\"Assigning value triggers all listeners\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a several listener<int>\") {\n observable<int> obs(0);\n bool triggered1 = false, triggered2 = false, triggered3 = false;\n listener<int> lstnr1([&triggered1](int&&){ triggered1 = true; });\n listener<int> lstnr2([&triggered2](int&&){ triggered2 = true; });\n listener<int> lstnr3([&triggered3](int&&){ triggered3 = true; });\n WHEN(\"several listeners registers at observable and a value is put into the observable\") {\n obs.registerListener(lstnr1);\n obs.registerListener(lstnr2);\n obs.registerListener(lstnr3);\n obs = 42;\n THEN(\"all registered listeners are triggered\") {\n REQUIRE(triggered1);\n REQUIRE(triggered2);\n REQUIRE(triggered3);\n }\n }\n }\n}\n\n\nTEST_CASE(\"Unregister listener\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a listener<int>\") {\n observable<int> obs(0);\n bool triggered = false;\n listener<int> lstnr([&triggered](int&&){ triggered = true; });\n WHEN(\"listener registers and unregisteres at the observable and a value is put into the observable\") {\n obs.registerListener(lstnr);\n obs.unregisterListener(lstnr);\n obs = 42;\n THEN(\"the listener is not triggered\") {\n REQUIRE(!triggered);\n }\n }\n }\n}\n\n\nTEST_CASE(\"destroying listener before observable must be safe\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a listener<int>\") {\n auto obs = std::make_shared<observable<int>>(0);\n bool triggered = false;\n auto lstnr = std::make_shared<listener<int>>([&triggered](int&&){ triggered = true; });\n \n WHEN(\"the listener is destroyed and the observable triggered\") {\n obs->registerListener(*lstnr);\n lstnr=0;\n *obs = 37;\n THEN(\"the program does not crash and the registered listener is still not triggered\") {\n REQUIRE(!triggered);\n }\n }\n }\n}\n\n\nTEST_CASE(\"destroying observable before listener must be safe\", \"[observable][listener]\") {\n GIVEN(\"an observable<int> and a listener<int>\") {\n auto obs = std::make_shared<observable<int>>(0);\n auto lstnr = std::make_shared<listener<int>>([](int&&){});\n \n WHEN(\"the observable is destroyed the registered listener can be safely destructed\") {\n obs->registerListener(*lstnr);\n obs = nullptr;\n \n int* x;\n \n THEN(\"the program does not crash and the registered listener is still not triggered\") {\n lstnr = nullptr;\n }\n }\n }\n}\n\nTEST_CASE(\"moving an observable into another observable keeps the listeners intact\") {\n GIVEN(\"an observable and a listener\") {\n observable<int> obs(0);\n bool triggered = false;\n auto lstnr = std::make_shared<listener<int>>([&triggered](int&&){ triggered = true; });\n WHEN(\"the listener is registered it the observable\") {\n obs.registerListener(*lstnr);\n AND_WHEN(\"the observable is move-constructed into a different observable\") {\n observable<int> obs2(std::move(obs));\n THEN(\"modifying the moved-to observable will trigger the listener\") {\n obs2 = 42;\n REQUIRE(triggered);\n }\n }\n AND_WHEN(\"the observable is moved into a different observable\") {\n observable<int> obs2(0);\n obs2 = std::move(obs);\n THEN(\"modifying the moved-to observable will trigger the listener\") {\n obs2 = 42;\n REQUIRE(triggered);\n }\n }\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>#include\"mfem.hpp\"\n\n#include<memory>\n#include<iostream>\n#include<fstream>\n\nnamespace mfem {\n\n\nclass LinDiffQFunc\n{\npublic:\n LinDiffQFunc(mfem::Coefficient& dd, mfem::Coefficient& ll, double gg_,\n double pp0_, double pp1_):diff(dd),load(ll),gg(gg_),pp0(pp0_),pp1(pp1_)\n {\n\n }\n\n double QEnergy(ElementTransformation &T,\n const IntegrationPoint &ip,\n mfem::Vector& param, mfem::Vector& uu)\n {\n double dd=diff.Eval(T,ip);\n double ll=load.Eval(T,ip);\n\n double rho0=param[0];\n double rho1=param[1];\n double fd=dd*std::pow(rho0,pp0)*std::pow(rho1,pp1);\n\n double rez = 0.5*(uu[0]*uu[0]+uu[1]*uu[1]+uu[2]*uu[2])*fd\n + 0.5*gg*uu[3]*uu[3] -uu[3]*ll;\n\n return rez;\n }\n\n void QResidual(ElementTransformation &T,\n const IntegrationPoint &ip,\n mfem::Vector& param, mfem::Vector& uu, mfem::Vector& rr)\n {\n rr.SetSize(4);\n double dd=diff.Eval(T,ip);\n double ll=load.Eval(T,ip);\n\n double rho0=param[0];\n double rho1=param[1];\n\n double fd=dd*std::pow(rho0,pp0)*std::pow(rho1,pp1);\n\n rr[0]=uu[0]*fd;\n rr[1]=uu[1]*fd;\n rr[2]=uu[2]*fd;\n rr[3]=gg*uu[3]-ll;\n }\n\n void AQResidual(ElementTransformation &T,\n const IntegrationPoint &ip,\n mfem::Vector& param,\n mfem::Vector& uu, mfem::Vector& aa, mfem::Vector& rr)\n {\n rr.SetSize(2);\n double dd=diff.Eval(T,ip);\n double ll=load.Eval(T,ip);\n\n double rho0=param[0];\n double rho1=param[1];\n\n double fd0=dd*pp0*std::pow(rho0,pp0-1.0)*std::pow(rho1,pp1);\n double fd1=dd*std::pow(rho0,pp0)*pp1*std::pow(rho1,pp1-1.0);\n\n rr[0] = (aa[0]*uu[0]+aa[1]*uu[1]+aa[2]*uu[2])*fd0;\n rr[1] = (aa[0]*uu[0]+aa[1]*uu[1]+aa[2]*uu[2])*fd1;\n\n }\n\n void QGradResidual(ElementTransformation &T,\n const IntegrationPoint &ip,\n mfem::Vector& param, mfem::Vector& uu, mfem::DenseMatrix& hh)\n {\n hh.SetSize(4);\n double dd=diff.Eval(T,ip);\n \/\/double ll=load.Eval(T,ip);\n\n\n double rho0=param[0];\n double rho1=param[1];\n\n double fd=dd*std::pow(rho0,pp0)*std::pow(rho1,pp1);\n hh=0.0;\n\n hh(0,0)=fd;\n hh(1,1)=fd;\n hh(2,2)=fd;\n hh(3,3)=gg;\n }\n\n\nprivate:\n mfem::Coefficient& diff;\n mfem::Coefficient& load;\n double gg;\n double pp0;\n double pp1;\n};\n\n\nclass PrmBlockLSFEMDiffusion: public PrmBlockNonlinearFormIntegrator\n{\npublic:\n PrmBlockLSFEMDiffusion(LinDiffQFunc& qfun_)\n {\n qfunc=&qfun_;\n }\n\n \/\/\/ Compute the local energy\n virtual double GetElementEnergy(const Array<const FiniteElement *>&el,\n const Array<const FiniteElement *>&pel,\n ElementTransformation &Tr,\n const Array<const Vector *>&elfun,\n const Array<const Vector *>&pelfun)\n {\n int dof_u0 = el[0]->GetDof();\n int dof_r0 = pel[0]->GetDof();\n int dof_r1 = pel[1]->GetDof();\n\n int dim = el[0]->GetDim();\n int spaceDim = Tr.GetSpaceDim();\n if (dim != spaceDim)\n {\n mfem::mfem_error(\" PrmBlockLSFEMDiffusion::GetElementEnergy\"\n \" is not defined on manifold meshes\");\n }\n\n \/\/shape functions\n Vector shu0(dof_u0);\n Vector shr0(dof_r0);\n Vector shr1(dof_r1);\n DenseMatrix dsu0(dof_u0,dim);\n DenseMatrix B(dof_u0, 4);\n B=0.0;\n\n double w;\n\n Vector param(2); param=0.0;\n Vector uu(4); uu=0.0;\n\n double energy =0.0;\n\n const IntegrationRule *ir = nullptr;\n if(ir==nullptr){\n int order= 2 * el[0]->GetOrder() + Tr.OrderGrad(el[0])\n +pel[0]->GetOrder()+pel[1]->GetOrder();\n ir=&IntRules.Get(Tr.GetGeometryType(),order);\n }\n\n for (int i = 0; i < ir->GetNPoints(); i++)\n {\n const IntegrationPoint &ip = ir->IntPoint(i);\n Tr.SetIntPoint(&ip);\n w=Tr.Weight();\n w = ip.weight * w;\n\n el[0]->CalcPhysDShape(Tr,dsu0);\n el[0]->CalcPhysShape(Tr,shu0);\n pel[0]->CalcPhysShape(Tr,shr0);\n pel[1]->CalcPhysShape(Tr,shr1);\n\n param[0]=shr0*(*pelfun[0]);\n param[1]=shr1*(*pelfun[1]);\n\n \/\/set the matrix B\n for(int jj=0;jj<dim;jj++)\n {\n B.SetCol(jj,dsu0.GetColumn(jj));\n }\n B.SetCol(3,shu0);\n B.MultTranspose(*elfun[0],uu);\n energy=energy+w * qfunc->QEnergy(Tr,ip,param,uu);\n }\n return energy;\n }\n\n \/\/\/ Perform the local action of the BlockNonlinearFormIntegrator\n virtual void AssembleElementVector(const Array<const FiniteElement *> &el,\n const Array<const FiniteElement *>&pel,\n ElementTransformation &Tr,\n const Array<const Vector *> &elfun,\n const Array<const Vector *>&pelfun,\n const Array<Vector *> &elvec)\n {\n int dof_u0 = el[0]->GetDof();\n int dof_r0 = pel[0]->GetDof();\n int dof_r1 = pel[1]->GetDof();\n\n int dim = el[0]->GetDim();\n\n elvec[0]->SetSize(dof_u0);\n *elvec[0]=0.0;\n int spaceDim = Tr.GetSpaceDim();\n if (dim != spaceDim)\n {\n mfem::mfem_error(\" PrmBlockLSFEMDiffusion::AssembleElementVector\"\n \" is not defined on manifold meshes\");\n }\n\n \/\/shape functions\n Vector shu0(dof_u0);\n Vector shr0(dof_r0);\n Vector shr1(dof_r1);\n DenseMatrix dsu0(dof_u0,dim);\n DenseMatrix B(dof_u0, 4);\n B=0.0;\n\n double w;\n\n Vector param(2); param=0.0;\n Vector uu(4); uu=0.0;\n Vector rr;\n Vector lvec; lvec.SetSize(dof_u0);\n\n const IntegrationRule *ir = nullptr;\n if(ir==nullptr){\n int order= 2 * el[0]->GetOrder() + Tr.OrderGrad(el[0])\n +pel[0]->GetOrder()+pel[1]->GetOrder();\n ir=&IntRules.Get(Tr.GetGeometryType(),order);\n }\n\n for (int i = 0; i < ir->GetNPoints(); i++)\n {\n const IntegrationPoint &ip = ir->IntPoint(i);\n Tr.SetIntPoint(&ip);\n w=Tr.Weight();\n w = ip.weight * w;\n\n el[0]->CalcPhysDShape(Tr,dsu0);\n el[0]->CalcPhysShape(Tr,shu0);\n pel[0]->CalcPhysShape(Tr,shr0);\n pel[1]->CalcPhysShape(Tr,shr1);\n\n param[0]=shr0*(*pelfun[0]);\n param[1]=shr1*(*pelfun[1]);\n\n \/\/set the matrix B\n for(int jj=0;jj<dim;jj++)\n {\n B.SetCol(jj,dsu0.GetColumn(jj));\n }\n B.SetCol(3,shu0);\n B.MultTranspose(*elfun[0],uu);\n qfunc->QResidual(Tr,ip,param, uu, rr);\n\n B.Mult(rr,lvec);\n elvec[0]->Add(w,lvec);\n }\n\n }\n\n virtual void AssembleFaceVector(const Array<const FiniteElement *> &el1,\n const Array<const FiniteElement *> &el2,\n const Array<const FiniteElement *> &pel1,\n const Array<const FiniteElement *> &pel2,\n FaceElementTransformations &Tr,\n const Array<const Vector *> &elfun,\n const Array<const Vector *>&pelfun,\n const Array<Vector *> &elvect)\n {\n\n }\n\n \/\/\/ Assemble the local gradient matrix\n virtual void AssembleElementGrad(const Array<const FiniteElement*> &el,\n const Array<const FiniteElement *>&pel,\n ElementTransformation &Tr,\n const Array<const Vector *> &elfun,\n const Array<const Vector *>&pelfun,\n const Array2D<DenseMatrix *> &elmats)\n {\n int dof_u0 = el[0]->GetDof();\n int dof_r0 = pel[0]->GetDof();\n int dof_r1 = pel[1]->GetDof();\n\n int dim = el[0]->GetDim();\n\n \/\/elmats[0]->Size(dof_u0, dof_u0);\n \/\/*elmats[0]=0.0;\n\n DenseMatrix* K=elmats(0,0);\n K->SetSize(dof_u0,dof_u0);\n (*K)=0.0;\n\n int spaceDim = Tr.GetSpaceDim();\n if (dim != spaceDim)\n {\n mfem::mfem_error(\" PrmBlockLSFEMDiffusion::AssembleElementVector\"\n \" is not defined on manifold meshes\");\n }\n\n \/\/shape functions\n Vector shu0(dof_u0);\n Vector shr0(dof_r0);\n Vector shr1(dof_r1);\n DenseMatrix dsu0(dof_u0,dim);\n DenseMatrix B(dof_u0, 4);\n DenseMatrix A(dof_u0, 4);\n B=0.0;\n\n double w;\n\n Vector param(2); param=0.0;\n Vector uu(4); uu=0.0;\n DenseMatrix hh;\n Vector lvec; lvec.SetSize(dof_u0);\n\n const IntegrationRule *ir = nullptr;\n if(ir==nullptr){\n int order= 2 * el[0]->GetOrder() + Tr.OrderGrad(el[0])\n +pel[0]->GetOrder()+pel[1]->GetOrder();\n ir=&IntRules.Get(Tr.GetGeometryType(),order);\n }\n\n for (int i = 0; i < ir->GetNPoints(); i++)\n {\n const IntegrationPoint &ip = ir->IntPoint(i);\n Tr.SetIntPoint(&ip);\n w = Tr.Weight();\n w = ip.weight * w;\n\n el[0]->CalcPhysDShape(Tr,dsu0);\n el[0]->CalcPhysShape(Tr,shu0);\n pel[0]->CalcPhysShape(Tr,shr0);\n pel[1]->CalcPhysShape(Tr,shr1);\n\n param[0]=shr0*(*pelfun[0]);\n param[1]=shr1*(*pelfun[1]);\n\n \/\/set the matrix B\n for(int jj=0;jj<dim;jj++)\n {\n B.SetCol(jj,dsu0.GetColumn(jj));\n }\n B.SetCol(3,shu0);\n B.MultTranspose(*elfun[0],uu);\n qfunc->QGradResidual(Tr,ip,param,uu,hh);\n Mult(B,hh,A);\n AddMult_a_ABt(w,A,B,*K);\n }\n }\n\n virtual void AssembleFaceGrad(const Array<const FiniteElement *>&el1,\n const Array<const FiniteElement *>&el2,\n const Array<const FiniteElement *> &pel1,\n const Array<const FiniteElement *> &pel2,\n FaceElementTransformations &Tr,\n const Array<const Vector *> &elfun,\n const Array<const Vector *>&pelfun,\n const Array2D<DenseMatrix *> &elmats)\n {\n\n }\n\n virtual void AssemblePrmElementVector(const Array<const FiniteElement *> &el,\n const Array<const FiniteElement *> &pel,\n ElementTransformation &Tr,\n const Array<const Vector *> &elfun,\n const Array<const Vector *> &alfun,\n const Array<const Vector *> &pelfun,\n const Array<Vector *> &elvec)\n {\n int dof_u0 = el[0]->GetDof();\n int dof_r0 = pel[0]->GetDof();\n int dof_r1 = pel[1]->GetDof();\n\n int dim = el[0]->GetDim();\n\n Vector& e0 = *(elvec[0]);\n Vector& e1 = *(elvec[1]);\n\n e0.SetSize(dof_r0);\n e0=0.0;\n e1.SetSize(dof_r1);\n e1=0.0;\n\n int spaceDim = Tr.GetSpaceDim();\n if (dim != spaceDim)\n {\n mfem::mfem_error(\" PrmBlockLSFEMDiffusion::AssembleElementVector\"\n \" is not defined on manifold meshes\");\n }\n\n \/\/shape functions\n Vector shu0(dof_u0);\n Vector shr0(dof_r0);\n Vector shr1(dof_r1);\n DenseMatrix dsu0(dof_u0,dim);\n DenseMatrix B(dof_u0, 4);\n B=0.0;\n\n double w;\n\n Vector param(2); param=0.0;\n Vector uu(4); uu=0.0;\n Vector aa(4); aa=0.0;\n Vector rr;\n Vector lvec0; lvec0.SetSize(dof_r0);\n Vector lvec1; lvec1.SetSize(dof_r1);\n\n const IntegrationRule *ir = nullptr;\n if(ir==nullptr){\n int order= 2 * el[0]->GetOrder() + Tr.OrderGrad(el[0])\n +pel[0]->GetOrder()+pel[1]->GetOrder();\n ir=&IntRules.Get(Tr.GetGeometryType(),order);\n }\n\n for (int i = 0; i < ir->GetNPoints(); i++)\n {\n const IntegrationPoint &ip = ir->IntPoint(i);\n Tr.SetIntPoint(&ip);\n w=Tr.Weight();\n w = ip.weight * w;\n\n el[0]->CalcPhysDShape(Tr,dsu0);\n el[0]->CalcPhysShape(Tr,shu0);\n pel[0]->CalcPhysShape(Tr,shr0);\n pel[1]->CalcPhysShape(Tr,shr1);\n\n param[0]=shr0*(*pelfun[0]);\n param[1]=shr1*(*pelfun[1]);\n\n \/\/set the matrix B\n for(int jj=0;jj<dim;jj++)\n {\n B.SetCol(jj,dsu0.GetColumn(jj));\n }\n B.SetCol(3,shu0);\n B.MultTranspose(*elfun[0],uu);\n B.MultTranspose(*alfun[0],aa);\n\n qfunc->AQResidual(Tr, ip, param, uu, aa, rr);\n\n lvec0=shr0;\n lvec0*=rr[0];\n lvec1=shr1;\n lvec1*=rr[1];\n\n e0.Add(w,lvec0);\n e1.Add(w,lvec1);\n }\n\n }\n\n virtual void AssemblePrmFaceVector(const Array<const FiniteElement *> &el1,\n const Array<const FiniteElement *> &el2,\n const Array<const FiniteElement *> &pel1,\n const Array<const FiniteElement *> &pel2,\n FaceElementTransformations &Tr,\n const Array<const Vector *> &elfun,\n const Array<const Vector *> &alfun,\n const Array<const Vector *> &pelfun,\n const Array<Vector *> &elvect)\n {\n\n }\n\n\n\nprivate:\n LinDiffQFunc* qfunc;\n};\n\n}\n\nint main(int argc, char *argv[])\n{\n const char *mesh_file = \"..\/..\/data\/beam-tet.mesh\";\n int ser_ref_levels = 1;\n int order = 2;\n bool visualization = true;\n double newton_rel_tol = 1e-4;\n double newton_abs_tol = 1e-6;\n int newton_iter = 10;\n int print_level = 0;\n\n mfem::OptionsParser args(argc, argv);\n args.AddOption(&mesh_file, \"-m\", \"--mesh\", \"Mesh file to use.\");\n args.AddOption(&ser_ref_levels,\n \"-rs\",\n \"--refine-serial\",\n \"Number of times to refine the mesh uniformly in serial.\");\n args.AddOption(&order,\n \"-o\",\n \"--order\",\n \"Order (degree) of the finite elements.\");\n args.AddOption(&visualization,\n \"-vis\",\n \"--visualization\",\n \"-no-vis\",\n \"--no-visualization\",\n \"Enable or disable GLVis visualization.\");\n args.AddOption(&newton_rel_tol,\n \"-rel\",\n \"--relative-tolerance\",\n \"Relative tolerance for the Newton solve.\");\n args.AddOption(&newton_abs_tol,\n \"-abs\",\n \"--absolute-tolerance\",\n \"Absolute tolerance for the Newton solve.\");\n args.AddOption(&newton_iter,\n \"-it\",\n \"--newton-iterations\",\n \"Maximum iterations for the Newton solve.\");\n\n args.Parse();\n if (!args.Good())\n {\n args.PrintUsage(std::cout);\n return 1;\n }\n args.PrintOptions(std::cout);\n \/\/ 3. Read the (serial) mesh from the given mesh file on all processors. We\n \/\/ can handle triangular, quadrilateral, tetrahedral and hexahedral meshes\n \/\/ with the same code.\n mfem::Mesh *mesh = new mfem::Mesh(mesh_file, 1, 1);\n int dim = mesh->Dimension();\n\n \/\/ 4. Refine the mesh in serial to increase the resolution. In this example\n \/\/ we do 'ser_ref_levels' of uniform refinement, where 'ser_ref_levels' is\n \/\/ a command-line parameter.\n for (int lev = 0; lev < ser_ref_levels; lev++)\n {\n mesh->UniformRefinement();\n }\n\n \/\/\/ Define the q-function\n mfem::ConstantCoefficient* dc=new mfem::ConstantCoefficient(1.0);\n mfem::ConstantCoefficient* lc=new mfem::ConstantCoefficient(1.0);\n mfem::LinDiffQFunc* qfun=new mfem::LinDiffQFunc(*dc,*lc,1.0,1.0,1.0);\n\n mfem::H1_FECollection fec00(order, dim);\n mfem::L2_FECollection fec01(order, dim);\n mfem::FiniteElementSpace* bfes00=new mfem::FiniteElementSpace(mesh,&fec00,1,mfem::Ordering::byVDIM);\n mfem::FiniteElementSpace* pfes00=new mfem::FiniteElementSpace(mesh,&fec00,1,mfem::Ordering::byVDIM);\n mfem::FiniteElementSpace* pfes01=new mfem::FiniteElementSpace(mesh,&fec01,1,mfem::Ordering::byVDIM);\n\n \/\/\/ Define parametric nonlinear form\n mfem::Array<mfem::FiniteElementSpace*> bfes;\n mfem::Array<mfem::FiniteElementSpace*> pfes;\n\n bfes.Append(bfes00);\n pfes.Append(pfes00);\n pfes.Append(pfes01);\n\n mfem::PrmBlockNonlinearForm* nf=new mfem::PrmBlockNonlinearForm(bfes,pfes);\n nf->AddDomainIntegrator(new mfem::PrmBlockLSFEMDiffusion(*qfun));\n\n \/\/\/ Define the grid functions\n mfem::GridFunction* bgf00=new mfem::GridFunction(bfes00);\n mfem::GridFunction* pgf00=new mfem::GridFunction(pfes00);\n mfem::GridFunction* pgf01=new mfem::GridFunction(pfes01);\n mfem::GridFunction* ggf00=new mfem::GridFunction(pfes00);\n mfem::GridFunction* ggf01=new mfem::GridFunction(pfes01);\n\n *bgf00=0.0;\n *pgf00=1.0;\n *pgf01=1.0;\n\n mfem::BlockVector solbv; solbv.Update(nf->GetBlockTrueOffsets()); solbv=0.0;\n mfem::BlockVector resbv; resbv.Update(nf->GetBlockTrueOffsets()); resbv=0.0;\n mfem::BlockVector adjbv; adjbv.Update(nf->GetBlockTrueOffsets()); adjbv=0.0;\n mfem::BlockVector prmbv; prmbv.Update(nf->PrmGetBlockTrueOffsets()); prmbv=1.0;\n mfem::BlockVector grdbv; grdbv.Update(nf->PrmGetBlockTrueOffsets()); grdbv=0.0;\n\n bgf00->SetFromTrueDofs(solbv.GetBlock(0));\n pgf00->SetFromTrueDofs(prmbv.GetBlock(0));\n pgf01->SetFromTrueDofs(prmbv.GetBlock(1));\n\n nf->SetPrmFields(prmbv);\n double energy = nf->GetEnergy(solbv);\n\n nf->Mult(solbv,resbv);\n std::cout<<\"Norm res=\"<<resbv.Norml2()<<std::endl;\n\n \/\/mfem::Operator& K=nf->GetGradient(solbv);\n std::cout<<\"energy =\"<< energy<<std::endl;\n\n nf->SetStateFields(solbv);\n nf->SetAdjointFields(adjbv);\n nf->PrmMult(prmbv,grdbv);\n\n\n \/\/set the BC for the physics\n mfem::Array<mfem::Array<int> *> ess_bdr;\n mfem::Array<mfem::Vector*> ess_rhs;\n ess_bdr.Append(new mfem::Array<int>(mesh->bdr_attributes.Max()));\n ess_rhs.Append(nullptr);\n (*ess_bdr[0]) = 1;\n nf->SetEssentialBC(ess_bdr,ess_rhs);\n\n \/\/define the solvers\n mfem::UMFPackSolver* umfsolv=new mfem::UMFPackSolver();\n\n mfem::GMRESSolver *gmres;\n gmres = new mfem::GMRESSolver();\n gmres->SetAbsTol(newton_abs_tol\/10);\n gmres->SetRelTol(newton_rel_tol\/10);\n gmres->SetMaxIter(100);\n gmres->SetPrintLevel(print_level);\n \/\/gmres->SetPreconditioner(*prec);\n\n\n mfem::NewtonSolver *ns;\n ns = new mfem::NewtonSolver();\n ns->iterative_mode = true;\n ns->SetSolver(*gmres);\n ns->SetOperator(*nf);\n ns->SetPrintLevel(print_level);\n ns->SetRelTol(newton_rel_tol);\n ns->SetAbsTol(newton_abs_tol);\n ns->SetMaxIter(newton_iter);\n\n mfem::Vector b; \/\/RHS is zero\n solbv=0.0;\n ns->Mult(b, solbv);\n\n\n nf->SetStateFields(solbv);\n nf->SetAdjointFields(solbv);\n nf->PrmMult(prmbv,grdbv);\n\n\n\n\n mfem::ParaViewDataCollection *dacol = new mfem::ParaViewDataCollection(\"Example91\",\n mesh);\n\n ggf00->SetFromTrueDofs(grdbv.GetBlock(0));\n ggf01->SetFromTrueDofs(grdbv.GetBlock(1));\n pgf00->SetFromTrueDofs(solbv.GetBlock(0));\n\n dacol->SetLevelsOfDetail(order);\n dacol->RegisterField(\"sol\", pgf00);\n dacol->RegisterField(\"grad00\", ggf00);\n dacol->RegisterField(\"grad01\", ggf01);\n\n dacol->SetTime(1.0);\n dacol->SetCycle(1);\n dacol->Save();\n\n delete dacol;\n\n delete ns;\n delete umfsolv;\n delete gmres;\n delete ess_bdr[0];\n\n delete bgf00;\n delete pgf00;\n delete pgf01;\n delete ggf00;\n delete ggf01;\n\n\n delete nf;\n delete pfes01;\n delete pfes00;\n delete bfes00;\n\n delete qfun;\n delete lc;\n delete dc;\n\n delete mesh;\n\n}\n<commit_msg>clean start<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2016 Fixstars Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include <stdlib.h>\n#include <iostream>\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n\n#include <libsgm.h>\n\n#define ASSERT_MSG(expr, msg) \\\n\tif (!(expr)) { \\\n\t\tstd::cerr << msg << std::endl; \\\n\t\tstd::exit(EXIT_FAILURE); \\\n\t} \\\n\nint main(int argc, char* argv[])\n{\n\tcv::CommandLineParser parser(argc, argv,\n\t\t\"{@left_img | <none> | path to input left image }\"\n\t\t\"{@right_img | <none> | path to input right image }\"\n\t\t\"{disp_size | 64 | maximum possible disparity value }\"\n\t\t\"{P1 | 10 | penalty on the disparity change by plus or minus 1 between nieghbor pixels }\"\n\t\t\"{P2 | 120 | penalty on the disparity change by more than 1 between neighbor pixels }\"\n\t\t\"{uniqueness | 0.95 | margin in ratio by which the best cost function value should be at least second one }\"\n\t\t\"{num_paths | 8 | number of scanlines used in cost aggregation }\"\n\t\t\"{min_disp | 0 | minimum disparity value }\"\n\t\t\"{help h | | display this help and exit }\");\n\n\tif (parser.has(\"help\")) {\n\t\tparser.printMessage();\n\t\treturn 0;\n\t}\n\n\tcv::Mat left = cv::imread(parser.get<cv::String>(\"@left_img\"), -1);\n\tcv::Mat right = cv::imread(parser.get<cv::String>(\"@right_img\"), -1);\n\n\tif (!parser.check()) {\n\t\tparser.printErrors();\n\t\tparser.printMessage();\n\t\tstd::exit(EXIT_FAILURE);\n\t}\n\n\tconst int disp_size = parser.get<int>(\"disp_size\");\n\tconst int P1 = parser.get<int>(\"P1\");\n\tconst int P2 = parser.get<int>(\"P2\");\n\tconst float uniqueness = parser.get<float>(\"uniqueness\");\n\tconst int num_paths = parser.get<int>(\"num_paths\");\n\tconst int min_disp = parser.get<int>(\"min_disp\");\n\n\tASSERT_MSG(!left.empty() && !right.empty(), \"imread failed.\");\n\tASSERT_MSG(left.size() == right.size() && left.type() == right.type(), \"input images must be same size and type.\");\n\tASSERT_MSG(left.type() == CV_8U || left.type() == CV_16U, \"input image format must be CV_8U or CV_16U.\");\n\tASSERT_MSG(disp_size == 64 || disp_size == 128 || disp_size == 256, \"disparity size must be 64, 128 or 256.\");\n\tASSERT_MSG(num_paths == 4 || num_paths == 8, \"number of scanlines must be 4 or 8.\");\n\n\tconst sgm::PathType path_type = num_paths == 8 ? sgm::PathType::SCAN_8PATH : sgm::PathType::SCAN_4PATH;\n\tconst int input_depth = left.type() == CV_8U ? 8 : 16;\n\tconst int output_depth = 16;\n\n\tconst sgm::StereoSGM::Parameters param(P1, P2, uniqueness, false, path_type, min_disp);\n\tsgm::StereoSGM ssgm(left.cols, left.rows, disp_size, input_depth, output_depth, sgm::EXECUTE_INOUT_HOST2HOST, param);\n\n\tcv::Mat disparity(left.size(), CV_16S);\n\n\tssgm.execute(left.data, right.data, disparity.data);\n\n\t\/\/ create mask for invalid disp\n\tcv::Mat mask = disparity == ssgm.get_invalid_disparity();\n\n\t\/\/ show image\n\tcv::Mat disparity_8u, disparity_color;\n\tdisparity.convertTo(disparity_8u, CV_8U, 255. \/ disp_size);\n\tcv::applyColorMap(disparity_8u, disparity_color, cv::COLORMAP_JET);\n\tdisparity_8u.setTo(0, mask);\n\tdisparity_color.setTo(cv::Scalar(0, 0, 0), mask);\n\tif (left.type() != CV_8U)\n\t\tcv::normalize(left, left, 0, 255, cv::NORM_MINMAX, CV_8U);\n\n\tstd::vector<cv::Mat> images = { disparity_8u, disparity_color, left };\n\tstd::vector<std::string> titles = { \"disparity\", \"disparity color\", \"input\" };\n\n\tstd::cout << \"Hot keys:\" << std::endl;\n\tstd::cout << \"\\tESC - quit the program\" << std::endl;\n\tstd::cout << \"\\ts - switch display (disparity | colored disparity | input image)\" << std::endl;\n\n\tint mode = 0;\n\twhile (true) {\n\n\t\tcv::setWindowTitle(\"image\", titles[mode]);\n\t\tcv::imshow(\"image\", images[mode]);\n\n\t\tconst char c = cv::waitKey(0);\n\t\tif (c == 's')\n\t\t\tmode = (mode < 2 ? mode + 1 : 0);\n\t\tif (c == 27)\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Use LR_max_diff param at sample\/image<commit_after>\/*\nCopyright 2016 Fixstars Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include <stdlib.h>\n#include <iostream>\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n\n#include <libsgm.h>\n\n#define ASSERT_MSG(expr, msg) \\\n\tif (!(expr)) { \\\n\t\tstd::cerr << msg << std::endl; \\\n\t\tstd::exit(EXIT_FAILURE); \\\n\t} \\\n\nint main(int argc, char* argv[])\n{\n\tcv::CommandLineParser parser(argc, argv,\n\t\t\"{@left_img | <none> | path to input left image }\"\n\t\t\"{@right_img | <none> | path to input right image }\"\n\t\t\"{disp_size | 64 | maximum possible disparity value }\"\n\t\t\"{P1 | 10 | penalty on the disparity change by plus or minus 1 between nieghbor pixels }\"\n\t\t\"{P2 | 120 | penalty on the disparity change by more than 1 between neighbor pixels }\"\n\t\t\"{uniqueness | 0.95 | margin in ratio by which the best cost function value should be at least second one }\"\n\t\t\"{num_paths | 8 | number of scanlines used in cost aggregation }\"\n\t\t\"{min_disp | 0 | minimum disparity value }\"\n\t\t\"{LR_max_diff | 1 | maximum allowed difference between left and right disparity }\"\n\t\t\"{help h | | display this help and exit }\");\n\n\tif (parser.has(\"help\")) {\n\t\tparser.printMessage();\n\t\treturn 0;\n\t}\n\n\tcv::Mat left = cv::imread(parser.get<cv::String>(\"@left_img\"), -1);\n\tcv::Mat right = cv::imread(parser.get<cv::String>(\"@right_img\"), -1);\n\n\tif (!parser.check()) {\n\t\tparser.printErrors();\n\t\tparser.printMessage();\n\t\tstd::exit(EXIT_FAILURE);\n\t}\n\n\tconst int disp_size = parser.get<int>(\"disp_size\");\n\tconst int P1 = parser.get<int>(\"P1\");\n\tconst int P2 = parser.get<int>(\"P2\");\n\tconst float uniqueness = parser.get<float>(\"uniqueness\");\n\tconst int num_paths = parser.get<int>(\"num_paths\");\n\tconst int min_disp = parser.get<int>(\"min_disp\");\n\tconst int LR_max_diff = parser.get<int>(\"LR_max_diff\");\n\n\tASSERT_MSG(!left.empty() && !right.empty(), \"imread failed.\");\n\tASSERT_MSG(left.size() == right.size() && left.type() == right.type(), \"input images must be same size and type.\");\n\tASSERT_MSG(left.type() == CV_8U || left.type() == CV_16U, \"input image format must be CV_8U or CV_16U.\");\n\tASSERT_MSG(disp_size == 64 || disp_size == 128 || disp_size == 256, \"disparity size must be 64, 128 or 256.\");\n\tASSERT_MSG(num_paths == 4 || num_paths == 8, \"number of scanlines must be 4 or 8.\");\n\n\tconst sgm::PathType path_type = num_paths == 8 ? sgm::PathType::SCAN_8PATH : sgm::PathType::SCAN_4PATH;\n\tconst int input_depth = left.type() == CV_8U ? 8 : 16;\n\tconst int output_depth = 16;\n\n\tconst sgm::StereoSGM::Parameters param(P1, P2, uniqueness, false, path_type, min_disp, LR_max_diff);\n\tsgm::StereoSGM ssgm(left.cols, left.rows, disp_size, input_depth, output_depth, sgm::EXECUTE_INOUT_HOST2HOST, param);\n\n\tcv::Mat disparity(left.size(), CV_16S);\n\n\tssgm.execute(left.data, right.data, disparity.data);\n\n\t\/\/ create mask for invalid disp\n\tcv::Mat mask = disparity == ssgm.get_invalid_disparity();\n\n\t\/\/ show image\n\tcv::Mat disparity_8u, disparity_color;\n\tdisparity.convertTo(disparity_8u, CV_8U, 255. \/ disp_size);\n\tcv::applyColorMap(disparity_8u, disparity_color, cv::COLORMAP_JET);\n\tdisparity_8u.setTo(0, mask);\n\tdisparity_color.setTo(cv::Scalar(0, 0, 0), mask);\n\tif (left.type() != CV_8U)\n\t\tcv::normalize(left, left, 0, 255, cv::NORM_MINMAX, CV_8U);\n\n\tstd::vector<cv::Mat> images = { disparity_8u, disparity_color, left };\n\tstd::vector<std::string> titles = { \"disparity\", \"disparity color\", \"input\" };\n\n\tstd::cout << \"Hot keys:\" << std::endl;\n\tstd::cout << \"\\tESC - quit the program\" << std::endl;\n\tstd::cout << \"\\ts - switch display (disparity | colored disparity | input image)\" << std::endl;\n\n\tint mode = 0;\n\twhile (true) {\n\n\t\tcv::setWindowTitle(\"image\", titles[mode]);\n\t\tcv::imshow(\"image\", images[mode]);\n\n\t\tconst char c = cv::waitKey(0);\n\t\tif (c == 's')\n\t\t\tmode = (mode < 2 ? mode + 1 : 0);\n\t\tif (c == 27)\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <ctype.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <metaUtils.h>\n#include <metaObject.h>\n#include <metaLine.h>\n\n\/\/\n\/\/ MetaLine Constructors\n\/\/\nMetaLine::\nMetaLine()\n:MetaObject()\n{\n if(META_DEBUG) std::cout << \"MetaLine()\" << std::endl;\n Clear();\n}\n\n\/\/\nMetaLine::\nMetaLine(const char *_headerName)\n:MetaObject(_headerName)\n{\n if(META_DEBUG) std::cout << \"MetaLine()\" << std::endl;\n Clear();\n Read(_headerName);\n}\n\n\/\/\nMetaLine::\nMetaLine(const MetaLine *_line)\n:MetaObject()\n{\n if(META_DEBUG) std::cout << \"MetaLine()\" << std::endl;\n Clear();\n CopyInfo(_line);\n}\n\n\n\n\/\/\nMetaLine::\nMetaLine(unsigned int dim)\n:MetaObject(dim)\n{\n if(META_DEBUG) std::cout << \"MetaLine()\" << std::endl;\n Clear();\n}\n\n\/\/\nMetaLine::\n~MetaLine()\n{\n Clear();\n M_Destroy();\n}\n\n\/\/\nvoid MetaLine::\nPrintInfo() const\n{\n MetaObject::PrintInfo();\n std::cout << \"PointDim = \" << m_PointDim << std::endl;\n std::cout << \"NPoints = \" << m_NPoints << std::endl;\n char str[255];\n MET_TypeToString(m_ElementType, str);\n std::cout << \"ElementType = \" << str << std::endl;\n}\n\nvoid MetaLine::\nCopyInfo(const MetaLine * _line)\n{\n MetaObject::CopyInfo(_line);\n}\n\n \n\nvoid MetaLine::\nPointDim(const char* pointDim)\n{\n strcpy(m_PointDim,pointDim);\n}\n \nconst char* MetaLine::\nPointDim(void) const\n{\n return m_PointDim;\n}\n\nvoid MetaLine::\nNPoints(int npnt)\n{\n m_NPoints = npnt;\n}\n\nint MetaLine::\nNPoints(void) const\n{\n return m_NPoints;\n}\n\n\/** Clear line information *\/\nvoid MetaLine::\nClear(void)\n{\n if(META_DEBUG) std::cout << \"MetaLine: Clear\" << std::endl;\n MetaObject::Clear();\n m_NPoints = 0;\n \/\/ Delete the list of pointers to lines.\n PointListType::iterator it = m_PointList.begin();\n while(it != m_PointList.end())\n {\n LinePnt* pnt = *it;\n it++;\n delete pnt;\n } \n m_PointList.clear();\n\n strcpy(m_PointDim, \"x y z v1x v1y v1z\");\n m_ElementType = MET_FLOAT;\n}\n \n\/** Destroy line information *\/\nvoid MetaLine::\nM_Destroy(void)\n{\n MetaObject::M_Destroy();\n}\n\n\/** Set Read fields *\/\nvoid MetaLine::\nM_SetupReadFields(void)\n{\n if(META_DEBUG) std::cout << \"MetaLine: M_SetupReadFields\" << std::endl;\n\n MetaObject::M_SetupReadFields();\n\n MET_FieldRecordType * mF;\n\n \/\/int nDimsRecNum = MET_GetFieldRecordNumber(\"NDims\", &m_Fields);\n\n mF = new MET_FieldRecordType;\n MET_InitReadField(mF, \"PointDim\", MET_STRING, true);\n m_Fields.push_back(mF);\n\n mF = new MET_FieldRecordType;\n MET_InitReadField(mF, \"NPoints\", MET_INT, true);\n m_Fields.push_back(mF);\n\n mF = new MET_FieldRecordType;\n MET_InitReadField(mF, \"ElementType\", MET_STRING, true);\n mF->required = true;\n m_Fields.push_back(mF);\n\n mF = new MET_FieldRecordType;\n MET_InitReadField(mF, \"Points\", MET_NONE, true);\n mF->terminateRead = true;\n m_Fields.push_back(mF);\n\n}\n\nvoid MetaLine::\nM_SetupWriteFields(void)\n{\n strcpy(m_ObjectTypeName,\"Line\");\n MetaObject::M_SetupWriteFields();\n\n MET_FieldRecordType * mF;\n\n char s[255];\n mF = new MET_FieldRecordType;\n MET_TypeToString(m_ElementType, s);\n MET_InitWriteField(mF, \"ElementType\", MET_STRING, strlen(s), s);\n m_Fields.push_back(mF);\n\n if(strlen(m_PointDim)>0)\n {\n mF = new MET_FieldRecordType;\n MET_InitWriteField(mF, \"PointDim\", MET_STRING,\n strlen(m_PointDim),m_PointDim);\n m_Fields.push_back(mF);\n }\n\n m_NPoints = m_PointList.size();\n mF = new MET_FieldRecordType;\n MET_InitWriteField(mF, \"NPoints\", MET_INT,m_NPoints);\n m_Fields.push_back(mF);\n\n mF = new MET_FieldRecordType;\n MET_InitWriteField(mF, \"Points\", MET_NONE);\n m_Fields.push_back(mF);\n\n}\n\nMET_ValueEnumType MetaLine::\nElementType(void) const\n{\n return m_ElementType;\n}\n\nvoid MetaLine::\nElementType(MET_ValueEnumType _elementType)\n{\n m_ElementType = _elementType;\n}\n\n\nbool MetaLine::\nM_Read(void)\n{\n if(META_DEBUG) std::cout << \"MetaLine: M_Read: Loading Header\" << std::endl;\n\n if(!MetaObject::M_Read())\n {\n std::cout << \"MetaLine: M_Read: Error parsing file\" << std::endl;\n return false;\n }\n\n if(META_DEBUG) std::cout << \"MetaLine: M_Read: Parsing Header\" << std::endl;\n \n MET_FieldRecordType * mF;\n \n mF = MET_GetFieldRecord(\"NPoints\", &m_Fields);\n if(mF->defined)\n {\n m_NPoints= (int)mF->value[0];\n }\n\n mF = MET_GetFieldRecord(\"ElementType\", &m_Fields);\n if(mF->defined)\n {\n MET_StringToType((char *)(mF->value), &m_ElementType);\n }\n\n mF = MET_GetFieldRecord(\"PointDim\", &m_Fields);\n if(mF->defined)\n {\n strcpy(m_PointDim,(char *)(mF->value));\n }\n\n int pntDim;\n char** pntVal = NULL;\n MET_StringToWordArray(m_PointDim, &pntDim, &pntVal);\n \n int i;\n for(i=0;i<pntDim;i++)\n {\n delete [] pntVal[i];\n }\n delete [] pntVal;\n\n float v[16];\n\n if(m_BinaryData)\n {\n int elementSize;\n MET_SizeOfType(m_ElementType, &elementSize);\n int readSize = m_NPoints*(m_NDims*m_NDims+4)*elementSize;\n\n char* _data = new char[readSize];\n m_ReadStream->read((char *)_data, readSize);\n\n int gc = m_ReadStream->gcount();\n if(gc != readSize)\n {\n std::cout << \"MetaLine: m_Read: data not read completely\" \n << std::endl;\n std::cout << \" ideal = \" << readSize << \" : actual = \" << gc << std::endl;\n return false;\n }\n\n i=0;\n double td;\n int d;\n for(int j=0; j<m_NPoints; j++) \n {\n LinePnt* pnt = new LinePnt(m_NDims);\n \n for(d=0; d<m_NDims; d++)\n {\n MET_ValueToDouble(m_ElementType, _data, i++, &td);\n pnt->m_X[d] = (float)td;\n }\n\n for(int l=0;l<m_NDims-1;l++)\n {\n for(d=0; d<m_NDims; d++)\n {\n MET_ValueToDouble(m_ElementType, _data, i++, &td);\n pnt->m_V[l][d] = (float)td;\n } \n }\n \n for(d=0; d<4; d++)\n {\n MET_ValueToDouble(m_ElementType, _data, i++, &td);\n pnt->m_Color[d] = (float)td;\n }\n\n m_PointList.push_back(pnt);\n }\n delete [] _data;\n }\n else\n {\n for(int j=0; j<m_NPoints; j++) \n {\n LinePnt* pnt = new LinePnt(m_NDims);\n \n int k;\n int d;\n for(k=0; k<m_NDims; k++)\n {\n *m_ReadStream >> v[k];\n m_ReadStream->get();\n }\n\n \/\/float* x = new float[m_NDims];\n for(d=0; d<m_NDims; d++)\n {\n pnt->m_X[d] = v[d];\n }\n\n \/\/pnt.m_X = x;\n\n for(k=0; k<m_NDims-1; k++)\n {\n for(j=0; j<m_NDims; j++)\n {\n *m_ReadStream >> v[j];\n m_ReadStream->get();\n }\n\n \/\/float* n = new float[m_NDims];\n for(d=0; d<m_NDims; d++)\n {\n pnt->m_V[k][d] = v[d];\n }\n \/\/pnt.m_V[k] = n;\n }\n for(k=0; k<4; k++)\n {\n *m_ReadStream >> v[k];\n m_ReadStream->get();\n pnt->m_Color[k] = v[k];\n }\n\n m_PointList.push_back(pnt);\n }\n\n \n char c = ' ';\n while( (c!='\\n') && (!m_ReadStream->eof()))\n {\n c = m_ReadStream->get();\/\/ to avoid unrecognized characters\n }\n }\n\n return true;\n}\n\n\nbool MetaLine::\nM_Write(void)\n{\n\n if(!MetaObject::M_Write())\n {\n std::cout << \"MetaLine: M_Read: Error parsing file\" << std::endl;\n return false;\n }\n\n \/** Then copy all points *\/\n if(m_BinaryData)\n {\n PointListType::const_iterator it = m_PointList.begin();\n int elementSize;\n MET_SizeOfType(m_ElementType, &elementSize);\n\n char* data = new char[(m_NDims*m_NDims+4)*m_NPoints*elementSize];\n int i=0;\n int d;\n while(it != m_PointList.end())\n {\n for(d = 0; d < m_NDims; d++)\n {\n MET_DoubleToValue((double)(*it)->m_X[d],m_ElementType,data,i++); \n }\n\n for(int j=0;j<m_NDims-1;j++)\n {\n for(d=0; d<m_NDims; d++)\n {\n MET_DoubleToValue((double)(*it)->m_V[j][d],m_ElementType,data,i++);\n }\n }\n\n for(d=0; d<4; d++)\n {\n MET_DoubleToValue((double)(*it)->m_Color[d],m_ElementType,data,i++);\n }\n\n it++;\n }\n\n m_WriteStream->write((char *)data,(m_NDims*m_NDims+4)*m_NPoints*elementSize);\n m_WriteStream->write(\"\\n\",1);\n delete [] data;\n }\n else\n {\n PointListType::const_iterator it = m_PointList.begin();\n \n int d;\n while(it != m_PointList.end())\n {\n for(d = 0; d < m_NDims; d++)\n {\n *m_WriteStream << (*it)->m_X[d] << \" \";\n }\n\n for(d = 0; d < m_NDims-1; d++)\n {\n for(int i = 0; i < m_NDims; i++)\n {\n *m_WriteStream << (*it)->m_V[d][i] << \" \";\n }\n }\n\n for(d=0;d<4;d++)\n {\n *m_WriteStream << (*it)->m_Color[d] << \" \";\n }\n\n *m_WriteStream << std::endl;\n it++;\n }\n }\n\n return true;\n\n}\n<commit_msg>BUG: strange interaction with shadowed variable.<commit_after>#include <stdio.h>\n#include <ctype.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <metaUtils.h>\n#include <metaObject.h>\n#include <metaLine.h>\n\n\/\/\n\/\/ MetaLine Constructors\n\/\/\nMetaLine::\nMetaLine()\n:MetaObject()\n{\n if(META_DEBUG) std::cout << \"MetaLine()\" << std::endl;\n Clear();\n}\n\n\/\/\nMetaLine::\nMetaLine(const char *_headerName)\n:MetaObject(_headerName)\n{\n if(META_DEBUG) std::cout << \"MetaLine()\" << std::endl;\n Clear();\n Read(_headerName);\n}\n\n\/\/\nMetaLine::\nMetaLine(const MetaLine *_line)\n:MetaObject()\n{\n if(META_DEBUG) std::cout << \"MetaLine()\" << std::endl;\n Clear();\n CopyInfo(_line);\n}\n\n\n\n\/\/\nMetaLine::\nMetaLine(unsigned int dim)\n:MetaObject(dim)\n{\n if(META_DEBUG) std::cout << \"MetaLine()\" << std::endl;\n Clear();\n}\n\n\/\/\nMetaLine::\n~MetaLine()\n{\n Clear();\n M_Destroy();\n}\n\n\/\/\nvoid MetaLine::\nPrintInfo() const\n{\n MetaObject::PrintInfo();\n std::cout << \"PointDim = \" << m_PointDim << std::endl;\n std::cout << \"NPoints = \" << m_NPoints << std::endl;\n char str[255];\n MET_TypeToString(m_ElementType, str);\n std::cout << \"ElementType = \" << str << std::endl;\n}\n\nvoid MetaLine::\nCopyInfo(const MetaLine * _line)\n{\n MetaObject::CopyInfo(_line);\n}\n\n \n\nvoid MetaLine::\nPointDim(const char* pointDim)\n{\n strcpy(m_PointDim,pointDim);\n}\n \nconst char* MetaLine::\nPointDim(void) const\n{\n return m_PointDim;\n}\n\nvoid MetaLine::\nNPoints(int npnt)\n{\n m_NPoints = npnt;\n}\n\nint MetaLine::\nNPoints(void) const\n{\n return m_NPoints;\n}\n\n\/** Clear line information *\/\nvoid MetaLine::\nClear(void)\n{\n if(META_DEBUG) std::cout << \"MetaLine: Clear\" << std::endl;\n MetaObject::Clear();\n m_NPoints = 0;\n \/\/ Delete the list of pointers to lines.\n PointListType::iterator it = m_PointList.begin();\n while(it != m_PointList.end())\n {\n LinePnt* pnt = *it;\n it++;\n delete pnt;\n } \n m_PointList.clear();\n\n strcpy(m_PointDim, \"x y z v1x v1y v1z\");\n m_ElementType = MET_FLOAT;\n}\n \n\/** Destroy line information *\/\nvoid MetaLine::\nM_Destroy(void)\n{\n MetaObject::M_Destroy();\n}\n\n\/** Set Read fields *\/\nvoid MetaLine::\nM_SetupReadFields(void)\n{\n if(META_DEBUG) std::cout << \"MetaLine: M_SetupReadFields\" << std::endl;\n\n MetaObject::M_SetupReadFields();\n\n MET_FieldRecordType * mF;\n\n \/\/int nDimsRecNum = MET_GetFieldRecordNumber(\"NDims\", &m_Fields);\n\n mF = new MET_FieldRecordType;\n MET_InitReadField(mF, \"PointDim\", MET_STRING, true);\n m_Fields.push_back(mF);\n\n mF = new MET_FieldRecordType;\n MET_InitReadField(mF, \"NPoints\", MET_INT, true);\n m_Fields.push_back(mF);\n\n mF = new MET_FieldRecordType;\n MET_InitReadField(mF, \"ElementType\", MET_STRING, true);\n mF->required = true;\n m_Fields.push_back(mF);\n\n mF = new MET_FieldRecordType;\n MET_InitReadField(mF, \"Points\", MET_NONE, true);\n mF->terminateRead = true;\n m_Fields.push_back(mF);\n\n}\n\nvoid MetaLine::\nM_SetupWriteFields(void)\n{\n strcpy(m_ObjectTypeName,\"Line\");\n MetaObject::M_SetupWriteFields();\n\n MET_FieldRecordType * mF;\n\n char s[255];\n mF = new MET_FieldRecordType;\n MET_TypeToString(m_ElementType, s);\n MET_InitWriteField(mF, \"ElementType\", MET_STRING, strlen(s), s);\n m_Fields.push_back(mF);\n\n if(strlen(m_PointDim)>0)\n {\n mF = new MET_FieldRecordType;\n MET_InitWriteField(mF, \"PointDim\", MET_STRING,\n strlen(m_PointDim),m_PointDim);\n m_Fields.push_back(mF);\n }\n\n m_NPoints = m_PointList.size();\n mF = new MET_FieldRecordType;\n MET_InitWriteField(mF, \"NPoints\", MET_INT,m_NPoints);\n m_Fields.push_back(mF);\n\n mF = new MET_FieldRecordType;\n MET_InitWriteField(mF, \"Points\", MET_NONE);\n m_Fields.push_back(mF);\n\n}\n\nMET_ValueEnumType MetaLine::\nElementType(void) const\n{\n return m_ElementType;\n}\n\nvoid MetaLine::\nElementType(MET_ValueEnumType _elementType)\n{\n m_ElementType = _elementType;\n}\n\n\nbool MetaLine::\nM_Read(void)\n{\n if(META_DEBUG) std::cout << \"MetaLine: M_Read: Loading Header\" << std::endl;\n\n if(!MetaObject::M_Read())\n {\n std::cout << \"MetaLine: M_Read: Error parsing file\" << std::endl;\n return false;\n }\n\n if(META_DEBUG) std::cout << \"MetaLine: M_Read: Parsing Header\" << std::endl;\n \n MET_FieldRecordType * mF;\n \n mF = MET_GetFieldRecord(\"NPoints\", &m_Fields);\n if(mF->defined)\n {\n m_NPoints= (int)mF->value[0];\n }\n\n mF = MET_GetFieldRecord(\"ElementType\", &m_Fields);\n if(mF->defined)\n {\n MET_StringToType((char *)(mF->value), &m_ElementType);\n }\n\n mF = MET_GetFieldRecord(\"PointDim\", &m_Fields);\n if(mF->defined)\n {\n strcpy(m_PointDim,(char *)(mF->value));\n }\n\n int pntDim;\n char** pntVal = NULL;\n MET_StringToWordArray(m_PointDim, &pntDim, &pntVal);\n \n int ii;\n for(ii=0;ii<pntDim;ii++)\n {\n delete [] pntVal[ii];\n }\n delete [] pntVal;\n\n float v[16];\n\n if(m_BinaryData)\n {\n int elementSize;\n MET_SizeOfType(m_ElementType, &elementSize);\n int readSize = m_NPoints*(m_NDims*m_NDims+4)*elementSize;\n\n char* _data = new char[readSize];\n m_ReadStream->read((char *)_data, readSize);\n\n int gc = m_ReadStream->gcount();\n if(gc != readSize)\n {\n std::cout << \"MetaLine: m_Read: data not read completely\" \n << std::endl;\n std::cout << \" ideal = \" << readSize << \" : actual = \" << gc << std::endl;\n return false;\n }\n\n int i=0;\n double td;\n int d;\n for(int j=0; j<m_NPoints; j++) \n {\n LinePnt* pnt = new LinePnt(m_NDims);\n \n for(d=0; d<m_NDims; d++)\n {\n MET_ValueToDouble(m_ElementType, _data, i++, &td);\n pnt->m_X[d] = (float)td;\n }\n\n for(int l=0;l<m_NDims-1;l++)\n {\n for(d=0; d<m_NDims; d++)\n {\n MET_ValueToDouble(m_ElementType, _data, i++, &td);\n pnt->m_V[l][d] = (float)td;\n } \n }\n \n for(d=0; d<4; d++)\n {\n MET_ValueToDouble(m_ElementType, _data, i++, &td);\n pnt->m_Color[d] = (float)td;\n }\n\n m_PointList.push_back(pnt);\n }\n delete [] _data;\n }\n else\n {\n for(int j=0; j<m_NPoints; j++) \n {\n LinePnt* pnt = new LinePnt(m_NDims);\n \n int k;\n int d;\n for(k=0; k<m_NDims; k++)\n {\n *m_ReadStream >> v[k];\n m_ReadStream->get();\n }\n\n \/\/float* x = new float[m_NDims];\n for(d=0; d<m_NDims; d++)\n {\n pnt->m_X[d] = v[d];\n }\n\n \/\/pnt.m_X = x;\n\n for(k=0; k<m_NDims-1; k++)\n {\n for(int j=0; j<m_NDims; j++)\n {\n *m_ReadStream >> v[j];\n m_ReadStream->get();\n }\n\n \/\/float* n = new float[m_NDims];\n for(d=0; d<m_NDims; d++)\n {\n pnt->m_V[k][d] = v[d];\n }\n \/\/pnt.m_V[k] = n;\n }\n for(k=0; k<4; k++)\n {\n *m_ReadStream >> v[k];\n m_ReadStream->get();\n pnt->m_Color[k] = v[k];\n }\n\n m_PointList.push_back(pnt);\n }\n\n \n char c = ' ';\n while( (c!='\\n') && (!m_ReadStream->eof()))\n {\n c = m_ReadStream->get();\/\/ to avoid unrecognized characters\n }\n }\n\n return true;\n}\n\n\nbool MetaLine::\nM_Write(void)\n{\n\n if(!MetaObject::M_Write())\n {\n std::cout << \"MetaLine: M_Read: Error parsing file\" << std::endl;\n return false;\n }\n\n \/** Then copy all points *\/\n if(m_BinaryData)\n {\n PointListType::const_iterator it = m_PointList.begin();\n int elementSize;\n MET_SizeOfType(m_ElementType, &elementSize);\n\n char* data = new char[(m_NDims*m_NDims+4)*m_NPoints*elementSize];\n int i=0;\n int d;\n while(it != m_PointList.end())\n {\n for(d = 0; d < m_NDims; d++)\n {\n MET_DoubleToValue((double)(*it)->m_X[d],m_ElementType,data,i++); \n }\n\n for(int j=0;j<m_NDims-1;j++)\n {\n for(d=0; d<m_NDims; d++)\n {\n MET_DoubleToValue((double)(*it)->m_V[j][d],m_ElementType,data,i++);\n }\n }\n\n for(d=0; d<4; d++)\n {\n MET_DoubleToValue((double)(*it)->m_Color[d],m_ElementType,data,i++);\n }\n\n it++;\n }\n\n m_WriteStream->write((char *)data,(m_NDims*m_NDims+4)*m_NPoints*elementSize);\n m_WriteStream->write(\"\\n\",1);\n delete [] data;\n }\n else\n {\n PointListType::const_iterator it = m_PointList.begin();\n \n int d;\n while(it != m_PointList.end())\n {\n for(d = 0; d < m_NDims; d++)\n {\n *m_WriteStream << (*it)->m_X[d] << \" \";\n }\n\n for(d = 0; d < m_NDims-1; d++)\n {\n for(int i = 0; i < m_NDims; i++)\n {\n *m_WriteStream << (*it)->m_V[d][i] << \" \";\n }\n }\n\n for(d=0;d<4;d++)\n {\n *m_WriteStream << (*it)->m_Color[d] << \" \";\n }\n\n *m_WriteStream << std::endl;\n it++;\n }\n }\n\n return true;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2021 Intel Corporation. All Rights Reserved.\n\n\n#include \"converter-csv.hpp\"\n#include <iomanip>\n#include <algorithm>\n#include <iostream>\n\nusing namespace rs2::tools::converter;\n\nconverter_csv::motion_pose_frame_record::motion_pose_frame_record(rs2_stream stream_type, int stream_index,\n unsigned long long frame_number, \n double frame_ts, double backend_ts, double arrival_time,\n double p1, double p2, double p3,\n double p4, double p5, double p6, double p7) :\n _stream_type(stream_type),\n _stream_idx(stream_index),\n _frame_number(frame_number),\n _frame_ts(frame_ts),\n _backend_ts(backend_ts),\n _arrival_time(arrival_time),\n _params({ p1, p2, p3, p4, p5, p6, p7 }){}\n\nstd::string converter_csv::motion_pose_frame_record::to_string() const\n{\n std::stringstream ss;\n ss << rs2_stream_to_string(_stream_type) << \",\" << _frame_number << \",\"\n << std::fixed << std::setprecision(3) << _frame_ts << \",\" << _backend_ts << \",\" << _arrival_time;\n\n \/\/ IMU and Pose frame hold the sample data in addition to the frame's header attributes\n size_t specific_attributes = 0;\n if (val_in_range(_stream_type, { RS2_STREAM_GYRO,RS2_STREAM_ACCEL }))\n specific_attributes = 3;\n if (val_in_range(_stream_type, { RS2_STREAM_POSE }))\n specific_attributes = 7;\n\n for (auto i = 0; i < specific_attributes; i++)\n ss << \",\" << _params[i];\n ss << std::endl;\n return ss.str().c_str();\n}\n\nconverter_csv::converter_csv(const std::string& filePath, rs2_stream streamType)\n : _filePath(filePath)\n , _streamType(streamType)\n , _imu_pose_collection()\n , _sub_workers_joined(false)\n , _m()\n , _cv()\n{\n}\n\nvoid converter_csv::convert_depth(rs2::depth_frame& depthframe)\n{\n if (frames_map_get_and_set(depthframe.get_profile().stream_type(), depthframe.get_frame_number())) {\n return;\n }\n\n start_worker(\n [this, &depthframe] {\n\n std::stringstream filename;\n filename << _filePath\n << \"_\" << depthframe.get_profile().stream_name()\n << \"_\" << std::setprecision(14) << std::fixed << depthframe.get_timestamp()\n << \".csv\";\n\n std::stringstream metadata_file;\n metadata_file << _filePath\n << \"_\" << depthframe.get_profile().stream_name()\n << \"_metadata_\" << std::setprecision(14) << std::fixed << depthframe.get_timestamp()\n << \".txt\";\n\n std::string filenameS = filename.str();\n std::string metadataS = metadata_file.str();\n\n add_sub_worker(\n [filenameS, metadataS, depthframe] {\n std::ofstream fs(filenameS, std::ios::trunc);\n\n if (fs) {\n for (int y = 0; y < depthframe.get_height(); y++) {\n auto delim = \"\";\n\n for (int x = 0; x < depthframe.get_width(); x++) {\n fs << delim << depthframe.get_distance(x, y);\n delim = \",\";\n }\n fs << '\\n';\n }\n fs.flush();\n }\n metadata_to_txtfile(depthframe, metadataS);\n });\n wait_sub_workers();\n });\n}\n\nstd::string converter_csv::get_time_string() const\n{\n auto t = time(nullptr);\n char buffer[20] = {};\n const tm* time = localtime(&t);\n if (nullptr != time)\n strftime(buffer, sizeof(buffer), \"%Y%m%d%H%M%S\", time);\n\n return std::string(buffer);\n}\n\nvoid converter_csv::save_motion_pose_data_to_file()\n{\n if (!_imu_pose_collection.size())\n throw std::runtime_error(stringify() << \"No imu or pose data collected, aborting\");\n\n \/\/ Report amount of frames collected\n std::vector<uint64_t> frames_per_stream;\n for (const auto& kv : _imu_pose_collection)\n frames_per_stream.emplace_back(kv.second.size());\n\n std::sort(frames_per_stream.begin(), frames_per_stream.end());\n\n \/\/ Serialize and store data into csv-like format\n static auto time_Str = get_time_string();\n std::stringstream filename;\n filename << _filePath << \"_\" << time_Str <<\"_imu_pose.csv\";\n std::ofstream csv(filename.str());\n if (!csv.is_open())\n throw std::runtime_error(stringify() << \"Cannot open the requested output file \" << _filePath << \", please check permissions\");\n\n for (const auto& elem : _imu_pose_collection)\n {\n csv << \"\\n\\nStream Type,F#,HW Timestamp (ms),Backend Timestamp(ms),Host Timestamp(ms)\"\n << (val_in_range(elem.first.first, { RS2_STREAM_GYRO,RS2_STREAM_ACCEL }) ? \",3DOF_x,3DOF_y,3DOF_z\" : \"\")\n << (val_in_range(elem.first.first, { RS2_STREAM_POSE }) ? \",t_x,t_y,t_z,r_x,r_y,r_z,r_w\" : \"\")\n << std::endl; \n\n for (auto i = 0; i < elem.second.size(); i++)\n csv << elem.second[i].to_string();\n }\n\n}\n\nvoid converter_csv::convert_motion_pose(rs2::frame& f)\n{\n if (frames_map_get_and_set(f.get_profile().stream_type(), f.get_frame_number())) {\n return;\n }\n\n\n start_worker(\n [this, f] {\n\n add_sub_worker(\n [this, f] {\n auto stream_uid = std::make_pair(f.get_profile().stream_type(),\n f.get_profile().stream_index());\n\n double frame_timestamp = 0.;\n if (f.supports_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP))\n frame_timestamp = f.get_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP);\n\n double backend_timestamp = 0.;\n if (f.supports_frame_metadata(RS2_FRAME_METADATA_BACKEND_TIMESTAMP))\n backend_timestamp = f.get_frame_metadata(RS2_FRAME_METADATA_BACKEND_TIMESTAMP);\n\n double time_of_arrival = 0.;\n if (f.supports_frame_metadata(RS2_FRAME_METADATA_TIME_OF_ARRIVAL))\n time_of_arrival = f.get_frame_metadata(RS2_FRAME_METADATA_TIME_OF_ARRIVAL);\n \n motion_pose_frame_record record{ f.get_profile().stream_type(),\n f.get_profile().stream_index(),\n f.get_frame_number(),\n frame_timestamp,\n backend_timestamp,\n time_of_arrival};\n\n if (auto motion = f.as<rs2::motion_frame>())\n {\n auto axes = motion.get_motion_data();\n record._params = { axes.x, axes.y, axes.z };\n }\n\n if (auto pf = f.as<rs2::pose_frame>())\n {\n auto pose = pf.get_pose_data();\n record._params = { pose.translation.x, pose.translation.y, pose.translation.z,\n pose.rotation.x,pose.rotation.y,pose.rotation.z,pose.rotation.w };\n }\n\n _imu_pose_collection[stream_uid].emplace_back(record);\n });\n wait_sub_workers();\n _sub_workers_joined = true;\n _cv.notify_all();\n });\n std::unique_lock<std::mutex> lck(_m);\n while (!_sub_workers_joined)\n _cv.wait(lck);\n save_motion_pose_data_to_file();\n}\n\nvoid converter_csv::convert(rs2::frame& frame)\n{\n if (!(_streamType == rs2_stream::RS2_STREAM_ANY || frame.get_profile().stream_type() == _streamType))\n return;\n\n auto depthframe = frame.as<rs2::depth_frame>();\n if (depthframe)\n {\n convert_depth(depthframe);\n return;\n }\n\n auto motionframe = frame.as<rs2::motion_frame>();\n auto poseframe = frame.as<rs2::pose_frame>();\n if (motionframe || poseframe)\n {\n convert_motion_pose(frame);\n return;\n }\n}\n<commit_msg>cr correction<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2021 Intel Corporation. All Rights Reserved.\n\n\n#include \"converter-csv.hpp\"\n#include <iomanip>\n#include <algorithm>\n#include <iostream>\n\nusing namespace rs2::tools::converter;\n\nconverter_csv::motion_pose_frame_record::motion_pose_frame_record(rs2_stream stream_type, int stream_index,\n unsigned long long frame_number, \n double frame_ts, double backend_ts, double arrival_time,\n double p1, double p2, double p3,\n double p4, double p5, double p6, double p7) :\n _stream_type(stream_type),\n _stream_idx(stream_index),\n _frame_number(frame_number),\n _frame_ts(frame_ts),\n _backend_ts(backend_ts),\n _arrival_time(arrival_time),\n _params({ p1, p2, p3, p4, p5, p6, p7 }){}\n\nstd::string converter_csv::motion_pose_frame_record::to_string() const\n{\n std::stringstream ss;\n ss << rs2_stream_to_string(_stream_type) << \",\" << _frame_number << \",\"\n << std::fixed << std::setprecision(3) << _frame_ts << \",\" << _backend_ts << \",\" << _arrival_time;\n\n \/\/ IMU and Pose frame hold the sample data in addition to the frame's header attributes\n size_t specific_attributes = 0;\n if (val_in_range(_stream_type, { RS2_STREAM_GYRO,RS2_STREAM_ACCEL }))\n specific_attributes = 3;\n if (val_in_range(_stream_type, { RS2_STREAM_POSE }))\n specific_attributes = 7;\n\n for (auto i = 0; i < specific_attributes; i++)\n ss << \",\" << _params[i];\n ss << std::endl;\n return ss.str().c_str();\n}\n\nconverter_csv::converter_csv(const std::string& filePath, rs2_stream streamType)\n : _filePath(filePath)\n , _streamType(streamType)\n , _imu_pose_collection()\n , _sub_workers_joined(false)\n , _m()\n , _cv()\n{\n}\n\nvoid converter_csv::convert_depth(rs2::depth_frame& depthframe)\n{\n if (frames_map_get_and_set(depthframe.get_profile().stream_type(), depthframe.get_frame_number())) {\n return;\n }\n\n start_worker(\n [this, &depthframe] {\n\n std::stringstream filename;\n filename << _filePath\n << \"_\" << depthframe.get_profile().stream_name()\n << \"_\" << std::setprecision(14) << std::fixed << depthframe.get_timestamp()\n << \".csv\";\n\n std::stringstream metadata_file;\n metadata_file << _filePath\n << \"_\" << depthframe.get_profile().stream_name()\n << \"_metadata_\" << std::setprecision(14) << std::fixed << depthframe.get_timestamp()\n << \".txt\";\n\n std::string filenameS = filename.str();\n std::string metadataS = metadata_file.str();\n\n add_sub_worker(\n [filenameS, metadataS, depthframe] {\n std::ofstream fs(filenameS, std::ios::trunc);\n\n if (fs) {\n for (int y = 0; y < depthframe.get_height(); y++) {\n auto delim = \"\";\n\n for (int x = 0; x < depthframe.get_width(); x++) {\n fs << delim << depthframe.get_distance(x, y);\n delim = \",\";\n }\n fs << '\\n';\n }\n fs.flush();\n }\n metadata_to_txtfile(depthframe, metadataS);\n });\n wait_sub_workers();\n });\n}\n\nstd::string converter_csv::get_time_string() const\n{\n auto t = time(nullptr);\n char buffer[20] = {};\n const tm* time = localtime(&t);\n if (nullptr != time)\n strftime(buffer, sizeof(buffer), \"%Y%m%d%H%M%S\", time);\n\n return std::string(buffer);\n}\n\nvoid converter_csv::save_motion_pose_data_to_file()\n{\n if (!_imu_pose_collection.size())\n {\n std::cout << \"No imu or pose data collected\" << std::endl;\n return;\n }\n\n \/\/ Report amount of frames collected\n std::vector<uint64_t> frames_per_stream;\n for (const auto& kv : _imu_pose_collection)\n frames_per_stream.emplace_back(kv.second.size());\n\n std::sort(frames_per_stream.begin(), frames_per_stream.end());\n\n \/\/ Serialize and store data into csv-like format\n static auto time_Str = get_time_string();\n std::stringstream filename;\n filename << _filePath << \"_\" << time_Str <<\"_imu_pose.csv\";\n std::ofstream csv(filename.str());\n if (!csv.is_open())\n throw std::runtime_error(stringify() << \"Cannot open the requested output file \" << _filePath << \", please check permissions\");\n\n for (const auto& elem : _imu_pose_collection)\n {\n csv << \"\\n\\nStream Type,F#,HW Timestamp (ms),Backend Timestamp(ms),Host Timestamp(ms)\"\n << (val_in_range(elem.first.first, { RS2_STREAM_GYRO,RS2_STREAM_ACCEL }) ? \",3DOF_x,3DOF_y,3DOF_z\" : \"\")\n << (val_in_range(elem.first.first, { RS2_STREAM_POSE }) ? \",t_x,t_y,t_z,r_x,r_y,r_z,r_w\" : \"\")\n << std::endl; \n\n for (auto i = 0; i < elem.second.size(); i++)\n csv << elem.second[i].to_string();\n }\n\n}\n\nvoid converter_csv::convert_motion_pose(rs2::frame& f)\n{\n if (frames_map_get_and_set(f.get_profile().stream_type(), f.get_frame_number())) {\n return;\n }\n\n start_worker(\n [this, f] {\n\n add_sub_worker(\n [this, f] {\n auto stream_uid = std::make_pair(f.get_profile().stream_type(),\n f.get_profile().stream_index());\n\n double frame_timestamp = 0.;\n if (f.supports_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP))\n frame_timestamp = f.get_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP);\n\n double backend_timestamp = 0.;\n if (f.supports_frame_metadata(RS2_FRAME_METADATA_BACKEND_TIMESTAMP))\n backend_timestamp = f.get_frame_metadata(RS2_FRAME_METADATA_BACKEND_TIMESTAMP);\n\n double time_of_arrival = 0.;\n if (f.supports_frame_metadata(RS2_FRAME_METADATA_TIME_OF_ARRIVAL))\n time_of_arrival = f.get_frame_metadata(RS2_FRAME_METADATA_TIME_OF_ARRIVAL);\n \n motion_pose_frame_record record{ f.get_profile().stream_type(),\n f.get_profile().stream_index(),\n f.get_frame_number(),\n frame_timestamp,\n backend_timestamp,\n time_of_arrival};\n\n if (auto motion = f.as<rs2::motion_frame>())\n {\n auto axes = motion.get_motion_data();\n record._params = { axes.x, axes.y, axes.z };\n }\n\n if (auto pf = f.as<rs2::pose_frame>())\n {\n auto pose = pf.get_pose_data();\n record._params = { pose.translation.x, pose.translation.y, pose.translation.z,\n pose.rotation.x,pose.rotation.y,pose.rotation.z,pose.rotation.w };\n }\n\n _imu_pose_collection[stream_uid].emplace_back(record);\n });\n wait_sub_workers();\n _sub_workers_joined = true;\n _cv.notify_all();\n });\n std::unique_lock<std::mutex> lck(_m);\n while (!_sub_workers_joined)\n _cv.wait(lck);\n save_motion_pose_data_to_file();\n}\n\nvoid converter_csv::convert(rs2::frame& frame)\n{\n if (!(_streamType == rs2_stream::RS2_STREAM_ANY || frame.get_profile().stream_type() == _streamType))\n return;\n\n auto depthframe = frame.as<rs2::depth_frame>();\n if (depthframe)\n {\n convert_depth(depthframe);\n return;\n }\n\n auto motionframe = frame.as<rs2::motion_frame>();\n auto poseframe = frame.as<rs2::pose_frame>();\n if (motionframe || poseframe)\n {\n convert_motion_pose(frame);\n return;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2015, Intel Corporation, all rights reserved.\n\n\/*\n* This sample shows how to use custom schema in xml file.\n*\/\n\n#include <vmf\/vmf.hpp>\n#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n\nusing namespace vmf;\nusing namespace std;\nvoid dumpMetadataDesc(shared_ptr<MetadataDesc> spDesc)\n{\n\tif (spDesc == nullptr)\n\t\treturn;\n\n\tcout << \"Metadata: \" << spDesc->getMetadataName() << endl;\n\tvector<FieldDesc> fields = spDesc->getFields();\n\tfor (FieldDesc field : fields)\n\t{\n\t\tcout << \"\\t[\" << field.name << \"]: \" << Variant::typeToString(field.type) << std::endl;\n\t}\n}\nvoid demoLoadSchemaFromFile(const string& schemaFilePath, const string& schemaName)\n{\n\tMetadataStream stream;\n\n\ttry\n\t{\n\t\t\/\/ Open schema file\n\t\tstd::ifstream inputFile(schemaFilePath);\n\n\t\t\/\/ Read schema content into memory string\n\t\tstringstream ss;\n\t\tss << inputFile.rdbuf();\n\n\t\t\/\/ Parse schema content and load it into stream\n\t\tXMLReader reader;\n\t\tstream.deserialize(ss.str(), reader);\n\n\t\t\/\/ Get a pointer to the schema\n\t\tshared_ptr<MetadataSchema> spSchema = stream.getSchema(schemaName);\n\t\tif (spSchema == nullptr)\n\t\t\tthrow exception(\"Did not find schema in the xml file!\");\n\n\t\t\/\/ Get a pointer to the metadata description structure\n\t\tshared_ptr<MetadataDesc> spMetadataDesc = spSchema->findMetadataDesc(\"table2\");\n\t\tif (spMetadataDesc == nullptr)\n\t\t\tthrow exception(\"Did not find metadata <table2> in the schema.\");\n\n\t\t\/\/ Found everything!\n\t\tstd::cout << \"Found schema and metadata!\" << std::endl;\n\t\tstd::cout << \"Schema: \" << spSchema->getName() << std::endl;\n\t\tdumpMetadataDesc(spMetadataDesc);\n\n\t\tstream.close();\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cout << \"Operation fialed: \" << e.what() << std::endl;\n\t\tstream.close();\n\t}\n}\n\nint main(int argc, char* argv[])\n{\n vmf::initialize();\n\n\tstring schemaFilePath(\"demo_schema.xml\");\n\tstring schemaName(\"vmf:\/\/ns.intel.com\/vmf\/demo-schema-1.0\");\n\t\n\tstring appPath = argv[0];\n#ifdef WIN32\n\tchar delim = '\\\\';\n#else\n\tchar delim = '\/';\n#endif\n\tsize_t pos = appPath.find_last_of(delim);\n\n\tstring workingPath;\n\tif (pos != string::npos)\n\t{\n\t\tworkingPath = appPath.substr(0, pos + 1);\n\t}\n\n\t\/\/ Run demo\n\tdemoLoadSchemaFromFile(workingPath + schemaFilePath, schemaName);\n\n vmf::terminate();\n\n return 0;\n}\n<commit_msg>Added new header boilerplate<commit_after>\/* \n * Copyright 2015 Intel(r) Corporation\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\/*\n* This sample shows how to use custom schema in xml file.\n*\/\n\n#include <vmf\/vmf.hpp>\n#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n\nusing namespace vmf;\nusing namespace std;\nvoid dumpMetadataDesc(shared_ptr<MetadataDesc> spDesc)\n{\n\tif (spDesc == nullptr)\n\t\treturn;\n\n\tcout << \"Metadata: \" << spDesc->getMetadataName() << endl;\n\tvector<FieldDesc> fields = spDesc->getFields();\n\tfor (FieldDesc field : fields)\n\t{\n\t\tcout << \"\\t[\" << field.name << \"]: \" << Variant::typeToString(field.type) << std::endl;\n\t}\n}\nvoid demoLoadSchemaFromFile(const string& schemaFilePath, const string& schemaName)\n{\n\tMetadataStream stream;\n\n\ttry\n\t{\n\t\t\/\/ Open schema file\n\t\tstd::ifstream inputFile(schemaFilePath);\n\n\t\t\/\/ Read schema content into memory string\n\t\tstringstream ss;\n\t\tss << inputFile.rdbuf();\n\n\t\t\/\/ Parse schema content and load it into stream\n\t\tXMLReader reader;\n\t\tstream.deserialize(ss.str(), reader);\n\n\t\t\/\/ Get a pointer to the schema\n\t\tshared_ptr<MetadataSchema> spSchema = stream.getSchema(schemaName);\n\t\tif (spSchema == nullptr)\n\t\t\tthrow exception(\"Did not find schema in the xml file!\");\n\n\t\t\/\/ Get a pointer to the metadata description structure\n\t\tshared_ptr<MetadataDesc> spMetadataDesc = spSchema->findMetadataDesc(\"table2\");\n\t\tif (spMetadataDesc == nullptr)\n\t\t\tthrow exception(\"Did not find metadata <table2> in the schema.\");\n\n\t\t\/\/ Found everything!\n\t\tstd::cout << \"Found schema and metadata!\" << std::endl;\n\t\tstd::cout << \"Schema: \" << spSchema->getName() << std::endl;\n\t\tdumpMetadataDesc(spMetadataDesc);\n\n\t\tstream.close();\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cout << \"Operation fialed: \" << e.what() << std::endl;\n\t\tstream.close();\n\t}\n}\n\nint main(int argc, char* argv[])\n{\n vmf::initialize();\n\n\tstring schemaFilePath(\"demo_schema.xml\");\n\tstring schemaName(\"vmf:\/\/ns.intel.com\/vmf\/demo-schema-1.0\");\n\t\n\tstring appPath = argv[0];\n#ifdef WIN32\n\tchar delim = '\\\\';\n#else\n\tchar delim = '\/';\n#endif\n\tsize_t pos = appPath.find_last_of(delim);\n\n\tstring workingPath;\n\tif (pos != string::npos)\n\t{\n\t\tworkingPath = appPath.substr(0, pos + 1);\n\t}\n\n\t\/\/ Run demo\n\tdemoLoadSchemaFromFile(workingPath + schemaFilePath, schemaName);\n\n vmf::terminate();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"immediate_hud.h\"\n#include \"entity_system\/entity.h\"\n#include \"entity_system\/world.h\"\n\n#include \"game\/systems\/render_system.h\"\n#include \"game\/systems\/gui_system.h\"\n#include \"game\/components\/sprite_component.h\"\n#include \"game\/components\/camera_component.h\"\n#include \"game\/components\/sentience_component.h\"\n#include \"game\/components\/render_component.h\"\n#include \"game\/components\/physics_component.h\"\n#include \"game\/components\/name_component.h\"\n\n#include \"game\/messages\/health_event.h\"\n\n#include \"game\/detail\/inventory_utils.h\"\n#include \"game\/detail\/inventory_slot.h\"\n#include \"game\/detail\/inventory_slot_id.h\"\n#include \"game\/detail\/entity_description.h\"\n\n#include \"graphics\/renderer.h\"\n#include \"graphics\/vertex.h\"\n#include \"stream.h\"\n#include \"stlutil.h\"\n#include \"augs\/gui\/text_drawer.h\"\n\nvoid immediate_hud::draw_circular_bars(messages::camera_render_request_message r) {\n\tauto& render = r.camera->get_owner_world().get_system<render_system>();\n\tconst auto& visible_entities = render.get_all_visible_entities();\n\tauto& target = *r.state.output;\n\n\tauto camera = r.camera;\n\tauto watched_character = camera->get<components::camera>().entity_to_chase;\n\n\tint timestamp_ms = render.frame_timestamp_seconds() * 1000;\n\n\tcircular_bars_information.clear();\n\tpure_color_highlights.clear();\n\n\tfor (auto v : render.get_all_visible_entities()) {\n\t\tauto* sentience = v->find<components::sentience>();\n\n\t\tif (sentience) {\n\t\t\tauto hr = sentience->health_ratio();\n\t\t\tauto one_less_hr = 1 - hr;\n\n\t\t\tint pulse_duration = 1250 - 1000 * (1 - hr);\n\t\t\tfloat time_pulse_ratio = (timestamp_ms % pulse_duration) \/ float(pulse_duration);\n\n\t\t\thr *= 1.f - (0.2f * time_pulse_ratio);\n\n\t\t\tauto* render = v->find<components::render>();\n\t\t\t\n\t\t\tif (render) {\n\t\t\t\t\/\/render->partial_overlay_color = red;\n\t\t\t\t\/\/render->partial_overlay_height_ratio = 1 - hr;\n\t\t\t\tif (hr < 1.f) {\n\t\t\t\t\trender->draw_border = true;\n\t\t\t\t\trender->border_color = rgba(255, 0, 0, one_less_hr * one_less_hr * one_less_hr * one_less_hr * 255 * time_pulse_ratio);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\trender->draw_border = false;\n\t\t\t}\n\n\t\t\tauto health_col = sentience->calculate_health_color(time_pulse_ratio);\n\n\t\t\tauto& transform = v->get<components::transform>();\n\t\t\tshared::state_for_drawing_renderable state;\n\t\t\tstate.setup_camera_state(r.state);\n\t\t\tstate.renderable_transform = transform;\n\t\t\tstate.renderable_transform.rotation = 0;\n\n\t\t\tcomponents::sprite circle_hud;\n\t\t\tcircle_hud.set(assets::HUD_CIRCULAR_BAR_MEDIUM, health_col);\n\t\t\tcircle_hud.draw(state);\n\n\t\t\t\n\t\t\tauto watched_character_transform = watched_character->get<components::transform>();\n\t\t\tfloat starting_health_angle = 0.f;\n\t\t\tfloat ending_health_angle = 0.f;\n\n\t\t\tif (v == watched_character) {\n\t\t\t\tstarting_health_angle = watched_character_transform.rotation + 135;\n\t\t\t\tending_health_angle = starting_health_angle + sentience->health_ratio() * 90.f;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstarting_health_angle = (v->get<components::transform>().pos - watched_character_transform.pos).degrees() - 45;\n\t\t\t\tending_health_angle = starting_health_angle + sentience->health_ratio() * 90.f;\n\t\t\t}\n\n\t\t\tauto push_angles = [&target](float lower_outside, float upper_outside, float lower_inside, float upper_inside) {\n\t\t\t\taugs::special s;\n\n\t\t\t\ts.v1.set(normalize_degrees(lower_outside) \/ 180, normalize_degrees(upper_outside) \/ 180);\n\t\t\t\ts.v2.set(normalize_degrees(lower_inside) \/ 180, normalize_degrees(upper_inside) \/ 180);\n\n\t\t\t\ttarget.push_special_vertex_triangle(s, s, s);\n\t\t\t\ttarget.push_special_vertex_triangle(s, s, s);\n\t\t\t};\n\t\t\t\n\t\t\tpush_angles(starting_health_angle, starting_health_angle + 90, starting_health_angle, ending_health_angle);\n\n\t\t\tstruct circle_info {\n\t\t\t\tfloat angle;\n\t\t\t\tstd::wstring text;\n\t\t\t\trgba color;\n\t\t\t};\n\n\t\t\tstd::vector<circle_info> textual_infos;\n\n\t\t\tif (v == watched_character) {\n\t\t\t\tauto examine_item_slot = [&textual_infos, &push_angles, &circle_hud, &state](inventory_slot_id id, float lower_outside, float max_angular_length, bool ccw) {\n\t\t\t\t\tif (id.alive() && id.has_items()) {\n\t\t\t\t\t\tauto item = id->items_inside[0];\n\n\t\t\t\t\t\tauto maybe_magazine_slot = item[slot_function::GUN_DETACHABLE_MAGAZINE];\n\t\t\t\t\t\tauto chamber_slot = item[slot_function::GUN_CHAMBER];\n\n\t\t\t\t\t\tfloat ammo_ratio = 0.f;\n\t\t\t\t\t\tint charges = 0;\n\t\t\t\t\t\tfloat total_space_available = 0.f;\n\t\t\t\t\t\tfloat total_actual_free_space = 0.f;\n\n\t\t\t\t\t\tif (maybe_magazine_slot.alive() && maybe_magazine_slot.has_items()) {\n\t\t\t\t\t\t\tauto mag = maybe_magazine_slot->items_inside[0];\n\t\t\t\t\t\t\tauto ammo_depo = mag[slot_function::ITEM_DEPOSIT];\n\t\t\t\t\t\t\tcharges += count_charges_in_deposit(mag);\n\n\t\t\t\t\t\t\ttotal_space_available += ammo_depo->space_available;\n\t\t\t\t\t\t\ttotal_actual_free_space += ammo_depo->calculate_free_space_with_children();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (chamber_slot.alive()) {\n\t\t\t\t\t\t\tcharges += count_charges_inside(chamber_slot);\n\n\t\t\t\t\t\t\ttotal_space_available += chamber_slot->space_available;\n\t\t\t\t\t\t\ttotal_actual_free_space += chamber_slot->calculate_free_space_with_children();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (total_space_available > 0) {\n\t\t\t\t\t\t\tammo_ratio = 1 - (total_actual_free_space \/ total_space_available);\n\n\t\t\t\t\t\t\tauto redviolet = augs::violet;\n\t\t\t\t\t\t\tredviolet.r = 200;\n\t\t\t\t\t\t\tcircle_hud.color = augs::interp(augs::white, redviolet, (1 - ammo_ratio)* (1 - ammo_ratio));\n\t\t\t\t\t\t\tcircle_hud.color.a = 200;\n\t\t\t\t\t\t\tcircle_hud.draw(state);\n\n\t\t\t\t\t\t\tcircle_info new_info;\n\n\t\t\t\t\t\t\tauto upper_outside = lower_outside + max_angular_length;\n\n\t\t\t\t\t\t\tif (!ccw) {\n\t\t\t\t\t\t\t\tpush_angles(lower_outside, upper_outside, lower_outside, lower_outside + ammo_ratio * max_angular_length);\n\t\t\t\t\t\t\t\tnew_info.angle = upper_outside;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tpush_angles(lower_outside, upper_outside, upper_outside - ammo_ratio * max_angular_length, upper_outside);\n\t\t\t\t\t\t\t\tnew_info.angle = lower_outside;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tnew_info.text = augs::to_wstring(charges);\n\t\t\t\t\t\t\tnew_info.color = circle_hud.color;\n\n\t\t\t\t\t\t\ttextual_infos.push_back(new_info);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\texamine_item_slot(v[slot_function::SECONDARY_HAND], starting_health_angle + 90, 90, false);\n\t\t\t\texamine_item_slot(v[slot_function::PRIMARY_HAND], starting_health_angle - 90, 90, true);\n\t\t\t}\n\n\t\t\tint radius = (*assets::HUD_CIRCULAR_BAR_MEDIUM).get_size().x \/ 2;\n\n\t\t\ttextual_infos.push_back({ starting_health_angle + 90, augs::to_wstring(sentience->health), health_col });\n\t\t\ttextual_infos.push_back({ starting_health_angle, description_of_entity(v).name, health_col });\n\n\t\t\tfor (auto& in : textual_infos) {\n\t\t\t\tif (in.text.empty()) continue;\n\n\t\t\t\taugs::gui::text_drawer health_points;\n\t\t\t\thealth_points.set_text(augs::gui::text::format(in.text, augs::gui::text::style(assets::GUI_FONT, in.color)));\n\n\t\t\t\tauto circle_displacement_length = health_points.get_bbox().bigger_side() + radius;\n\t\t\t\tvec2i screen_space_circle_center = r.get_screen_space(transform.pos);\n\n\t\t\t\thealth_points.pos = screen_space_circle_center + vec2().set_from_degrees(in.angle).set_length(circle_displacement_length);\n\n\t\t\t\thealth_points.draw_stroke(circular_bars_information);\n\t\t\t\thealth_points.draw(circular_bars_information);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid immediate_hud::draw_circular_bars_information(messages::camera_render_request_message r) {\n\tr.state.output->triangles.insert(r.state.output->triangles.begin(), circular_bars_information.begin(), circular_bars_information.end());\n}\n\nvoid immediate_hud::acquire_game_events(augs::world& w) {\n\tauto& healths = w.get_message_queue<messages::health_event>();\n\n\tfor (auto& h : healths) {\n\t\tvertically_flying_number vn;\n\t\tvn.time_of_occurence = w.get_current_timestamp();\n\t\tvn.value = h.effective_amount;\n\t\tvn.maximum_duration_seconds = 0.7;\n\n\t\taugs::rgba col;\n\n\t\tif (h.target == messages::health_event::HEALTH) {\n\t\t\tif (h.effective_amount > 0) {\n\t\t\t\tcol = red;\n\t\t\t}\n\t\t\telse col = green;\n\t\t}\n\t\telse\n\t\t\tcontinue;\n\n\t\tvn.text.set_text(augs::gui::text::format(augs::to_wstring(std::abs(vn.value)), augs::gui::text::style(assets::GUI_FONT, col)));\n\t\tvn.transform.pos = h.point_of_impact;\n\n\t\trecent_vertically_flying_numbers.push_back(vn);\n\n\t\tpure_color_highlight ph;\n\t\tph.time_of_occurence = w.get_current_timestamp();\n\t\tph.target = h.subject;\n\t\tph.starting_alpha_ratio = std::min(1.f, h.ratio_to_maximum_value * 15);\n\t\tph.maximum_duration_seconds = 0.3;\n\t\tph.color = col;\n\n\t\terase_remove(recent_pure_color_highlights, [&ph](const pure_color_highlight& h) { return h.target == ph.target; });\n\t\trecent_pure_color_highlights.push_back(ph);\n\t}\n}\n\ndouble immediate_hud::get_current_time(messages::camera_render_request_message msg) const {\n\tauto& world = msg.camera->get_owner_world();\n\treturn world.get_current_timestamp() + world.parent_overworld.fixed_delta_milliseconds() \/ 1000 * world.parent_overworld.view_interpolation_ratio();\n}\n\nvoid immediate_hud::draw_vertically_flying_numbers(messages::camera_render_request_message msg) {\n\tauto& target = renderer::get_current();\n\t\n\tauto current_time = get_current_time(msg);\n\n\tfor (auto& r : recent_vertically_flying_numbers) { \n\t\tauto passed = current_time - r.time_of_occurence;\n\t\tauto ratio = passed \/ r.maximum_duration_seconds;\n\n\t\tr.text.pos = msg.get_screen_space((r.transform.pos - vec2(0, sqrt(passed) * 150.f)));\n\t\t\n\t\tr.text.draw_stroke(msg.state.output->triangles);\n\t\tr.text.draw(msg.state.output->triangles);\n\t}\n\n\tauto timeout_lambda = [current_time](const game_event_visualization& v) {\n\t\treturn (current_time - v.time_of_occurence) > v.maximum_duration_seconds;\n\t};\n\n\terase_remove(recent_vertically_flying_numbers, timeout_lambda);\n\terase_remove(recent_pure_color_highlights, timeout_lambda);\n}\n\nvoid immediate_hud::draw_pure_color_highlights(messages::camera_render_request_message msg) {\n\tauto current_time = get_current_time(msg);\n\n\tfor (auto& r : recent_pure_color_highlights) {\n\t\tauto& col = r.target->get<components::sprite>().color;\n\t\tauto prevcol = col;\n\t\tcol = r.color;\n\n\t\tauto passed = current_time - r.time_of_occurence;\n\t\tauto ratio = passed \/ r.maximum_duration_seconds;\n\n\t\tcol.a = 255 * (1-ratio) * r.starting_alpha_ratio;\n\t\trender_system::standard_draw_entity(r.target, msg.state);\n\t\tcol = prevcol;\n\t}\n\n\t\/\/msg.state.output->triangles.insert(msg.state.output->triangles.begin(), pure_color_highlights.begin(), pure_color_highlights.end());\n}<commit_msg>moving ammo\/health captions<commit_after>#include \"immediate_hud.h\"\n#include \"entity_system\/entity.h\"\n#include \"entity_system\/world.h\"\n\n#include \"game\/systems\/render_system.h\"\n#include \"game\/systems\/gui_system.h\"\n#include \"game\/components\/sprite_component.h\"\n#include \"game\/components\/camera_component.h\"\n#include \"game\/components\/sentience_component.h\"\n#include \"game\/components\/render_component.h\"\n#include \"game\/components\/physics_component.h\"\n#include \"game\/components\/name_component.h\"\n\n#include \"game\/messages\/health_event.h\"\n\n#include \"game\/detail\/inventory_utils.h\"\n#include \"game\/detail\/inventory_slot.h\"\n#include \"game\/detail\/inventory_slot_id.h\"\n#include \"game\/detail\/entity_description.h\"\n\n#include \"graphics\/renderer.h\"\n#include \"graphics\/vertex.h\"\n#include \"stream.h\"\n#include \"stlutil.h\"\n#include \"augs\/gui\/text_drawer.h\"\n\nvoid immediate_hud::draw_circular_bars(messages::camera_render_request_message r) {\n\tauto& render = r.camera->get_owner_world().get_system<render_system>();\n\tconst auto& visible_entities = render.get_all_visible_entities();\n\tauto& target = *r.state.output;\n\n\tauto camera = r.camera;\n\tauto watched_character = camera->get<components::camera>().entity_to_chase;\n\n\tint timestamp_ms = render.frame_timestamp_seconds() * 1000;\n\n\tcircular_bars_information.clear();\n\tpure_color_highlights.clear();\n\n\tfor (auto v : render.get_all_visible_entities()) {\n\t\tauto* sentience = v->find<components::sentience>();\n\n\t\tif (sentience) {\n\t\t\tauto hr = sentience->health_ratio();\n\t\t\tauto one_less_hr = 1 - hr;\n\n\t\t\tint pulse_duration = 1250 - 1000 * (1 - hr);\n\t\t\tfloat time_pulse_ratio = (timestamp_ms % pulse_duration) \/ float(pulse_duration);\n\n\t\t\thr *= 1.f - (0.2f * time_pulse_ratio);\n\n\t\t\tauto* render = v->find<components::render>();\n\t\t\t\n\t\t\tif (render) {\n\t\t\t\t\/\/render->partial_overlay_color = red;\n\t\t\t\t\/\/render->partial_overlay_height_ratio = 1 - hr;\n\t\t\t\tif (hr < 1.f) {\n\t\t\t\t\trender->draw_border = true;\n\t\t\t\t\trender->border_color = rgba(255, 0, 0, one_less_hr * one_less_hr * one_less_hr * one_less_hr * 255 * time_pulse_ratio);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\trender->draw_border = false;\n\t\t\t}\n\n\t\t\tauto health_col = sentience->calculate_health_color(time_pulse_ratio);\n\n\t\t\tauto& transform = v->get<components::transform>();\n\t\t\tshared::state_for_drawing_renderable state;\n\t\t\tstate.setup_camera_state(r.state);\n\t\t\tstate.renderable_transform = transform;\n\t\t\tstate.renderable_transform.rotation = 0;\n\n\t\t\tcomponents::sprite circle_hud;\n\t\t\tcircle_hud.set(assets::HUD_CIRCULAR_BAR_MEDIUM, health_col);\n\t\t\tcircle_hud.draw(state);\n\n\t\t\t\n\t\t\tauto watched_character_transform = watched_character->get<components::transform>();\n\t\t\tfloat starting_health_angle = 0.f;\n\t\t\tfloat ending_health_angle = 0.f;\n\n\t\t\tif (v == watched_character) {\n\t\t\t\tstarting_health_angle = watched_character_transform.rotation + 135;\n\t\t\t\tending_health_angle = starting_health_angle + sentience->health_ratio() * 90.f;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstarting_health_angle = (v->get<components::transform>().pos - watched_character_transform.pos).degrees() - 45;\n\t\t\t\tending_health_angle = starting_health_angle + sentience->health_ratio() * 90.f;\n\t\t\t}\n\n\t\t\tauto push_angles = [&target](float lower_outside, float upper_outside, float lower_inside, float upper_inside) {\n\t\t\t\taugs::special s;\n\n\t\t\t\ts.v1.set(normalize_degrees(lower_outside) \/ 180, normalize_degrees(upper_outside) \/ 180);\n\t\t\t\ts.v2.set(normalize_degrees(lower_inside) \/ 180, normalize_degrees(upper_inside) \/ 180);\n\n\t\t\t\ttarget.push_special_vertex_triangle(s, s, s);\n\t\t\t\ttarget.push_special_vertex_triangle(s, s, s);\n\t\t\t};\n\t\t\t\n\t\t\tpush_angles(starting_health_angle, starting_health_angle + 90, starting_health_angle, ending_health_angle);\n\n\t\t\tstruct circle_info {\n\t\t\t\tfloat angle;\n\t\t\t\tstd::wstring text;\n\t\t\t\trgba color;\n\t\t\t};\n\n\t\t\tstd::vector<circle_info> textual_infos;\n\n\t\t\tif (v == watched_character) {\n\t\t\t\tauto examine_item_slot = [&textual_infos, &push_angles, &circle_hud, &state](inventory_slot_id id, float lower_outside, float max_angular_length, bool ccw) {\n\t\t\t\t\tif (id.alive() && id.has_items()) {\n\t\t\t\t\t\tauto item = id->items_inside[0];\n\n\t\t\t\t\t\tauto maybe_magazine_slot = item[slot_function::GUN_DETACHABLE_MAGAZINE];\n\t\t\t\t\t\tauto chamber_slot = item[slot_function::GUN_CHAMBER];\n\n\t\t\t\t\t\tfloat ammo_ratio = 0.f;\n\t\t\t\t\t\tint charges = 0;\n\t\t\t\t\t\tfloat total_space_available = 0.f;\n\t\t\t\t\t\tfloat total_actual_free_space = 0.f;\n\n\t\t\t\t\t\tif (maybe_magazine_slot.alive() && maybe_magazine_slot.has_items()) {\n\t\t\t\t\t\t\tauto mag = maybe_magazine_slot->items_inside[0];\n\t\t\t\t\t\t\tauto ammo_depo = mag[slot_function::ITEM_DEPOSIT];\n\t\t\t\t\t\t\tcharges += count_charges_in_deposit(mag);\n\n\t\t\t\t\t\t\ttotal_space_available += ammo_depo->space_available;\n\t\t\t\t\t\t\ttotal_actual_free_space += ammo_depo->calculate_free_space_with_children();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (chamber_slot.alive()) {\n\t\t\t\t\t\t\tcharges += count_charges_inside(chamber_slot);\n\n\t\t\t\t\t\t\ttotal_space_available += chamber_slot->space_available;\n\t\t\t\t\t\t\ttotal_actual_free_space += chamber_slot->calculate_free_space_with_children();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (total_space_available > 0) {\n\t\t\t\t\t\t\tammo_ratio = 1 - (total_actual_free_space \/ total_space_available);\n\n\t\t\t\t\t\t\tauto redviolet = augs::violet;\n\t\t\t\t\t\t\tredviolet.r = 200;\n\t\t\t\t\t\t\tcircle_hud.color = augs::interp(augs::white, redviolet, (1 - ammo_ratio)* (1 - ammo_ratio));\n\t\t\t\t\t\t\tcircle_hud.color.a = 200;\n\t\t\t\t\t\t\tcircle_hud.draw(state);\n\n\t\t\t\t\t\t\tcircle_info new_info;\n\n\t\t\t\t\t\t\tauto upper_outside = lower_outside + max_angular_length;\n\n\t\t\t\t\t\t\tauto empty_amount = (1 - ammo_ratio) * max_angular_length;\n\n\t\t\t\t\t\t\tif (!ccw) {\n\t\t\t\t\t\t\t\tpush_angles(lower_outside, upper_outside, lower_outside, lower_outside + ammo_ratio * max_angular_length);\n\t\t\t\t\t\t\t\tnew_info.angle = upper_outside - empty_amount\/2;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tpush_angles(lower_outside, upper_outside, upper_outside - ammo_ratio * max_angular_length, upper_outside);\n\t\t\t\t\t\t\t\tnew_info.angle = lower_outside + empty_amount \/ 2;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tnew_info.text = augs::to_wstring(charges);\n\t\t\t\t\t\t\tnew_info.color = circle_hud.color;\n\n\t\t\t\t\t\t\ttextual_infos.push_back(new_info);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\texamine_item_slot(v[slot_function::SECONDARY_HAND], starting_health_angle + 90 + 22.5, 90, false);\n\t\t\t\texamine_item_slot(v[slot_function::PRIMARY_HAND], starting_health_angle - 90 - 22.5, 90, true);\n\t\t\t}\n\n\t\t\tint radius = (*assets::HUD_CIRCULAR_BAR_MEDIUM).get_size().x \/ 2;\n\n\t\t\tint empty_health_amount = (1 - sentience->health_ratio()) * 90;\n\n\t\t\ttextual_infos.push_back({ starting_health_angle + 90 - empty_health_amount\/2, augs::to_wstring(sentience->health), health_col });\n\t\t\ttextual_infos.push_back({ starting_health_angle, description_of_entity(v).name, health_col });\n\n\t\t\tfor (auto& in : textual_infos) {\n\t\t\t\tif (in.text.empty()) continue;\n\n\t\t\t\taugs::gui::text_drawer health_points;\n\t\t\t\thealth_points.set_text(augs::gui::text::format(in.text, augs::gui::text::style(assets::GUI_FONT, in.color)));\n\n\t\t\t\tauto circle_displacement_length = health_points.get_bbox().bigger_side() + radius;\n\t\t\t\tvec2i screen_space_circle_center = r.get_screen_space(transform.pos);\n\n\t\t\t\thealth_points.pos = screen_space_circle_center + vec2().set_from_degrees(in.angle).set_length(circle_displacement_length);\n\n\t\t\t\thealth_points.draw_stroke(circular_bars_information);\n\t\t\t\thealth_points.draw(circular_bars_information);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid immediate_hud::draw_circular_bars_information(messages::camera_render_request_message r) {\n\tr.state.output->triangles.insert(r.state.output->triangles.begin(), circular_bars_information.begin(), circular_bars_information.end());\n}\n\nvoid immediate_hud::acquire_game_events(augs::world& w) {\n\tauto& healths = w.get_message_queue<messages::health_event>();\n\n\tfor (auto& h : healths) {\n\t\tvertically_flying_number vn;\n\t\tvn.time_of_occurence = w.get_current_timestamp();\n\t\tvn.value = h.effective_amount;\n\t\tvn.maximum_duration_seconds = 0.7;\n\n\t\taugs::rgba col;\n\n\t\tif (h.target == messages::health_event::HEALTH) {\n\t\t\tif (h.effective_amount > 0) {\n\t\t\t\tcol = red;\n\t\t\t}\n\t\t\telse col = green;\n\t\t}\n\t\telse\n\t\t\tcontinue;\n\n\t\tvn.text.set_text(augs::gui::text::format(augs::to_wstring(std::abs(vn.value)), augs::gui::text::style(assets::GUI_FONT, col)));\n\t\tvn.transform.pos = h.point_of_impact;\n\n\t\trecent_vertically_flying_numbers.push_back(vn);\n\n\t\tpure_color_highlight ph;\n\t\tph.time_of_occurence = w.get_current_timestamp();\n\t\tph.target = h.subject;\n\t\tph.starting_alpha_ratio = std::min(1.f, h.ratio_to_maximum_value * 15);\n\t\tph.maximum_duration_seconds = 0.3;\n\t\tph.color = col;\n\n\t\terase_remove(recent_pure_color_highlights, [&ph](const pure_color_highlight& h) { return h.target == ph.target; });\n\t\trecent_pure_color_highlights.push_back(ph);\n\t}\n}\n\ndouble immediate_hud::get_current_time(messages::camera_render_request_message msg) const {\n\tauto& world = msg.camera->get_owner_world();\n\treturn world.get_current_timestamp() + world.parent_overworld.fixed_delta_milliseconds() \/ 1000 * world.parent_overworld.view_interpolation_ratio();\n}\n\nvoid immediate_hud::draw_vertically_flying_numbers(messages::camera_render_request_message msg) {\n\tauto& target = renderer::get_current();\n\t\n\tauto current_time = get_current_time(msg);\n\n\tfor (auto& r : recent_vertically_flying_numbers) { \n\t\tauto passed = current_time - r.time_of_occurence;\n\t\tauto ratio = passed \/ r.maximum_duration_seconds;\n\n\t\tr.text.pos = msg.get_screen_space((r.transform.pos - vec2(0, sqrt(passed) * 150.f)));\n\t\t\n\t\tr.text.draw_stroke(msg.state.output->triangles);\n\t\tr.text.draw(msg.state.output->triangles);\n\t}\n\n\tauto timeout_lambda = [current_time](const game_event_visualization& v) {\n\t\treturn (current_time - v.time_of_occurence) > v.maximum_duration_seconds;\n\t};\n\n\terase_remove(recent_vertically_flying_numbers, timeout_lambda);\n\terase_remove(recent_pure_color_highlights, timeout_lambda);\n}\n\nvoid immediate_hud::draw_pure_color_highlights(messages::camera_render_request_message msg) {\n\tauto current_time = get_current_time(msg);\n\n\tfor (auto& r : recent_pure_color_highlights) {\n\t\tauto& col = r.target->get<components::sprite>().color;\n\t\tauto prevcol = col;\n\t\tcol = r.color;\n\n\t\tauto passed = current_time - r.time_of_occurence;\n\t\tauto ratio = passed \/ r.maximum_duration_seconds;\n\n\t\tcol.a = 255 * (1-ratio) * r.starting_alpha_ratio;\n\t\trender_system::standard_draw_entity(r.target, msg.state);\n\t\tcol = prevcol;\n\t}\n\n\t\/\/msg.state.output->triangles.insert(msg.state.output->triangles.begin(), pure_color_highlights.begin(), pure_color_highlights.end());\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS loadenv01 (1.2.28); FILE MERGED 2004\/03\/22 09:07:51 as 1.2.28.2: RESYNC: (1.2-1.3); FILE MERGED 2004\/03\/15 06:04:06 as 1.2.28.1: #i24378# use new MediaDescriptor class and constants<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"analysis.h\"\n\n\/**\n * @brief POI::POI\n *\/\nPOI::POI(){}\n\n\/**\n * @brief POI::add_detections\n * Adds OOIs for a specific frame in a POI.\n * @param frame_num\n * @param detections\n *\/\nvoid POI::add_detections(int frame_num, std::vector<OOI> detections) {\n if (start_frame == -1)\n start_frame = frame_num;\n OOIs[frame_num] = detections;\n}\n\n\/**\n * @brief POI::set_end_frame\n * Sets the end frame of the POI.\n * @param frame_num\n *\/\nvoid POI::set_end_frame(int frame_num) {\n end_frame = frame_num;\n}\n\n\/**\n * @brief POI::read\n * Reads POI from json format.\n * @param json\n *\/\nvoid POI::read(const QJsonObject& json) {\n \/\/ TODO\n this->start_frame = json[\"start\"].toInt();\n this->end_frame = json[\"end\"].toInt();\n for(int i = start_frame; i != end_frame; i++){\n QJsonArray json_frame_OOIs = json[QString::number(i)];\n std::vector<OOI> oois;\n for(int j = 0; j = json_frame_OOIs.size(); j++){\n OOI ooi;\n ooi.read(json_frame_OOIs[j]);\n oois.push_back(ooi);\n }\n this->OOIs.insert(std::make_pair(i, oois));\n }\n}\n\n\/**\n * @brief POI::write\n * Writes POI to json format.\n * @param json\n *\/\nvoid POI::write(QJsonObject& json) {\n json[\"start\"] = start_frame;\n json[\"end\"] = end_frame;\n\n for(const auto& ooi_pair : OOIs){\n QJsonArray json_frame_OOIs;\n int frame = ooi_pair.first;\n std::vector<OOI> oois = ooi_pair.second;\n for (OOI o : oois) {\n QJsonObject json_ooi;\n o.write(json_ooi);\n json_frame_OOIs.append(json_ooi);\n }\n json[QString::number(frame)] = json_frame_OOIs;\n }\n}\n\n\/**\n * @brief OOI::OOI\n *\/\nOOI::OOI(){}\n\n\/**\n * @brief OOI::OOI\n * @param upper_left\n * @param down_right\n *\/\nOOI::OOI(std::pair<int, int> upper_left, std::pair<int, int> down_right){\n this->upper_left = upper_left;\n this->lower_right = down_right;\n}\n\n\/**\n * @brief OOI::OOI\n * @param upper_left\n * @param height\n * @param width\n *\/\nOOI::OOI(std::pair<int, int> upper_left, int height, int width){\n this->upper_left = upper_left;\n this ->lower_right = std::make_pair(upper_left.second + width, upper_left.second + height);\n}\n\n\/**\n * @brief OOI::OOI\n * Creates an OOI from a cv::Rect.\n * @param rect\n *\/\nOOI::OOI(cv::Rect rect) {\n upper_left = std::make_pair(rect.x, rect.y);\n lower_right = std::make_pair(rect.x + rect.width, rect.y + rect.height);\n}\n\n\/**\n * @brief OOI::read\n * Reads OOI from json format.\n * @param json\n *\/\nvoid OOI::read(const QJsonObject &json){\n this->upper_left.first = json[\"UL_X\"].toInt();\n this->upper_left.second = json[\"UL_Y\"].toInt();\n\n this->lower_right.first = json[\"LR_X\"].toInt();\n this->lower_right.second = json[\"LR_Y\"].toInt();\n}\n\n\/**\n * @brief OOI::write\n * Writes OOI to json format.\n * @param json\n *\/\nvoid OOI::write(QJsonObject &json){\n json[\"UL_X\"] = this->upper_left.first;\n json[\"UL_Y\"] = this->upper_left.second;\n\n json[\"LR_X\"] = this->lower_right.first;\n json[\"LR_Y\"] = this->lower_right.second;\n}\n\n\/**\n * @brief OOI::get_rect\n * Returns the rectangle specified by the OOI.\n * @return\n *\/\ncv::Rect OOI::get_rect() {\n return cv::Rect(upper_left.first, upper_left.second, lower_right.first - upper_left.first,\n lower_right.second - upper_left.second);\n}\n\n\/**\n * @brief Analysis::Analysis\n *\/\nAnalysis::Analysis() {\n}\n\n\/**\n * @brief Analysis::Analysis\n * Copy constructor. Needed for signals and slots.\n * @param obj\n *\/\nAnalysis::Analysis(const Analysis &obj) {\n POIs = obj.POIs;\n type = obj.type;\n}\n\n\/**\n * @brief Analysis::~Analysis\n *\/\nAnalysis::~Analysis() {\n}\n\n\/**\n * @brief Analysis::add_POI\n * Adds a POI to the analysis.\n * @param poi\n *\/\nvoid Analysis::add_POI(POI poi){\n this->POIs.push_back(poi);\n}\n\n\/**\n * @brief Analysis::read\n * Reads analysis from json format.\n * @param json\n *\/\nvoid Analysis::read(const QJsonObject &json){\n this->type = (ANALYSIS_TYPE)json[\"analysis\"].toInt();\n QJsonArray json_pois = json[\"POI:s\"].toArray();\n for (int i = 0; i < json_pois.size(); ++i) {\n QJsonObject json_poi = json_pois[i].toObject();\n POI poi;\n POI.read(json_poi);\n this->add_POI(poi);\n }\n}\n\n\/**\n * @brief Analysis::write\n * Writes analysis to json format.\n * @param json\n *\/\nvoid Analysis::write(QJsonObject &json){\n json[\"type\"] = this->type;\n QJsonArray json_POIs;\n for(auto it = this->POIs.begin(); it != this->POIs.end(); it++){\n QJsonObject json_POI;\n POI p = *it;\n p.write(json_POI);\n json_POIs.append(json_POI);\n }\n json[\"POI:s\"] = json_POIs;\n}\n\n\/**\n * @brief Analysis::get_detections_on_frame\n * Returns all detections on a specified frame in the analysed video.\n * @param frame_num\n * @return\n *\/\nstd::vector<cv::Rect> Analysis::get_detections_on_frame(int frame_num) {\n std::vector<cv::Rect> rects;\n for (POI p : POIs) {\n if (frame_num >= p.start_frame && frame_num <= p.end_frame) {\n std::vector<OOI> oois = p.OOIs[frame_num];\n for (OOI o : oois) {\n rects.push_back(o.get_rect());\n }\n break;\n }\n }\n return rects;\n}\n<commit_msg>woops, compiles now<commit_after>#include \"analysis.h\"\n\n\/**\n * @brief POI::POI\n *\/\nPOI::POI(){}\n\n\/**\n * @brief POI::add_detections\n * Adds OOIs for a specific frame in a POI.\n * @param frame_num\n * @param detections\n *\/\nvoid POI::add_detections(int frame_num, std::vector<OOI> detections) {\n if (start_frame == -1)\n start_frame = frame_num;\n OOIs[frame_num] = detections;\n}\n\n\/**\n * @brief POI::set_end_frame\n * Sets the end frame of the POI.\n * @param frame_num\n *\/\nvoid POI::set_end_frame(int frame_num) {\n end_frame = frame_num;\n}\n\n\/**\n * @brief POI::read\n * Reads POI from json format.\n * @param json\n *\/\nvoid POI::read(const QJsonObject& json) {\n \/\/ TODO\n this->start_frame = json[\"start\"].toInt();\n this->end_frame = json[\"end\"].toInt(); \n for(int i = start_frame; i != end_frame; i++){ \n QJsonArray json_frame_OOIs = json[QString::number(i)].toArray();\n std::vector<OOI> oois;\n for(int j = 0; j = json_frame_OOIs.size(); j++){ \n OOI ooi;\n ooi.read(json_frame_OOIs[j].toObject());\n oois.push_back(ooi);\n }\n this->OOIs.insert(std::make_pair(i, oois));\n }\n}\n\n\/**\n * @brief POI::write\n * Writes POI to json format.\n * @param json\n *\/\nvoid POI::write(QJsonObject& json) {\n json[\"start\"] = start_frame;\n json[\"end\"] = end_frame;\n\n for(const auto& ooi_pair : OOIs){\n QJsonArray json_frame_OOIs;\n int frame = ooi_pair.first;\n std::vector<OOI> oois = ooi_pair.second;\n for (OOI o : oois) {\n QJsonObject json_ooi;\n o.write(json_ooi);\n json_frame_OOIs.append(json_ooi);\n }\n json[QString::number(frame)] = json_frame_OOIs;\n }\n}\n\n\/**\n * @brief OOI::OOI\n *\/\nOOI::OOI(){}\n\n\/**\n * @brief OOI::OOI\n * @param upper_left\n * @param down_right\n *\/\nOOI::OOI(std::pair<int, int> upper_left, std::pair<int, int> down_right){\n this->upper_left = upper_left;\n this->lower_right = down_right;\n}\n\n\/**\n * @brief OOI::OOI\n * @param upper_left\n * @param height\n * @param width\n *\/\nOOI::OOI(std::pair<int, int> upper_left, int height, int width){\n this->upper_left = upper_left;\n this ->lower_right = std::make_pair(upper_left.second + width, upper_left.second + height);\n}\n\n\/**\n * @brief OOI::OOI\n * Creates an OOI from a cv::Rect.\n * @param rect\n *\/\nOOI::OOI(cv::Rect rect) {\n upper_left = std::make_pair(rect.x, rect.y);\n lower_right = std::make_pair(rect.x + rect.width, rect.y + rect.height);\n}\n\n\/**\n * @brief OOI::read\n * Reads OOI from json format.\n * @param json\n *\/\nvoid OOI::read(const QJsonObject &json){\n this->upper_left.first = json[\"UL_X\"].toInt();\n this->upper_left.second = json[\"UL_Y\"].toInt();\n\n this->lower_right.first = json[\"LR_X\"].toInt();\n this->lower_right.second = json[\"LR_Y\"].toInt();\n}\n\n\/**\n * @brief OOI::write\n * Writes OOI to json format.\n * @param json\n *\/\nvoid OOI::write(QJsonObject &json){\n json[\"UL_X\"] = this->upper_left.first;\n json[\"UL_Y\"] = this->upper_left.second;\n\n json[\"LR_X\"] = this->lower_right.first;\n json[\"LR_Y\"] = this->lower_right.second;\n}\n\n\/**\n * @brief OOI::get_rect\n * Returns the rectangle specified by the OOI.\n * @return\n *\/\ncv::Rect OOI::get_rect() {\n return cv::Rect(upper_left.first, upper_left.second, lower_right.first - upper_left.first,\n lower_right.second - upper_left.second);\n}\n\n\/**\n * @brief Analysis::Analysis\n *\/\nAnalysis::Analysis() {\n}\n\n\/**\n * @brief Analysis::Analysis\n * Copy constructor. Needed for signals and slots.\n * @param obj\n *\/\nAnalysis::Analysis(const Analysis &obj) {\n POIs = obj.POIs;\n type = obj.type;\n}\n\n\/**\n * @brief Analysis::~Analysis\n *\/\nAnalysis::~Analysis() {\n}\n\n\/**\n * @brief Analysis::add_POI\n * Adds a POI to the analysis.\n * @param poi\n *\/\nvoid Analysis::add_POI(POI poi){\n this->POIs.push_back(poi);\n}\n\n\/**\n * @brief Analysis::read\n * Reads analysis from json format.\n * @param json\n *\/\nvoid Analysis::read(const QJsonObject &json){\n this->type = (ANALYSIS_TYPE)json[\"analysis\"].toInt();\n QJsonArray json_pois = json[\"POI:s\"].toArray();\n for (int i = 0; i < json_pois.size(); ++i) {\n QJsonObject json_poi = json_pois[i].toObject();\n POI poi;\n poi.read(json_poi);\n this->add_POI(poi);\n }\n}\n\n\/**\n * @brief Analysis::write\n * Writes analysis to json format.\n * @param json\n *\/\nvoid Analysis::write(QJsonObject &json){\n json[\"type\"] = this->type;\n QJsonArray json_POIs;\n for(auto it = this->POIs.begin(); it != this->POIs.end(); it++){\n QJsonObject json_POI;\n POI p = *it;\n p.write(json_POI);\n json_POIs.append(json_POI);\n }\n json[\"POI:s\"] = json_POIs;\n}\n\n\/**\n * @brief Analysis::get_detections_on_frame\n * Returns all detections on a specified frame in the analysed video.\n * @param frame_num\n * @return\n *\/\nstd::vector<cv::Rect> Analysis::get_detections_on_frame(int frame_num) {\n std::vector<cv::Rect> rects;\n for (POI p : POIs) {\n if (frame_num >= p.start_frame && frame_num <= p.end_frame) {\n std::vector<OOI> oois = p.OOIs[frame_num];\n for (OOI o : oois) {\n rects.push_back(o.get_rect());\n }\n break;\n }\n }\n return rects;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <renderer.h>\n#include <rasterizer.h>\n#include <s1516.h>\n\n#include <stdio.h>\n\n#define FLYTHROUGH_CAMERA_IMPLEMENTATION\n#include <flythrough_camera.h>\n\n#include <Windows.h>\n#include <DirectXMath.h>\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n\n#include <imgui.h>\n#include <imgui_impl_win32_gl.h>\n\n#pragma comment(lib, \"OpenGL32.lib\")\n#pragma comment(lib, \"glu32.lib\")\n\nLRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\n{\n if (ImGui_ImplWin32GL_WndProcHandler(hWnd, message, wParam, lParam))\n return true;\n\n switch (message)\n {\n case WM_CLOSE:\n ExitProcess(0);\n return 0;\n case WM_SYSCOMMAND:\n if ((wParam & 0xfff0) == SC_KEYMENU) \/\/ Disable ALT application menu\n return 0;\n break;\n }\n return DefWindowProc(hWnd, message, wParam, lParam);\n}\n\nHDC g_hDC;\n\nvoid init_window(int32_t width, int32_t height)\n{\n WNDCLASSEX wc;\n ZeroMemory(&wc, sizeof(wc));\n wc.cbSize = sizeof(wc);\n wc.style = CS_OWNDC;\n wc.lpfnWndProc = MyWndProc;\n wc.hInstance = GetModuleHandle(NULL);\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;\n wc.lpszClassName = TEXT(\"WindowClass\");\n RegisterClassEx(&wc);\n\n RECT wr = { 0, 0, width, height };\n AdjustWindowRect(&wr, 0, FALSE);\n HWND hWnd = CreateWindowEx(\n 0, TEXT(\"WindowClass\"),\n TEXT(\"viewer\"),\n WS_OVERLAPPEDWINDOW,\n 0, 0, wr.right - wr.left, wr.bottom - wr.top,\n 0, 0, GetModuleHandle(NULL), 0);\n\n PIXELFORMATDESCRIPTOR pfd;\n ZeroMemory(&pfd, sizeof(pfd));\n pfd.nSize = sizeof(pfd);\n pfd.nVersion = 1;\n pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;\n pfd.iPixelType = PFD_TYPE_RGBA;\n pfd.cColorBits = 32;\n pfd.iLayerType = PFD_MAIN_PLANE;\n\n g_hDC = GetDC(hWnd);\n\n int chosenPixelFormat = ChoosePixelFormat(g_hDC, &pfd);\n SetPixelFormat(g_hDC, chosenPixelFormat, &pfd);\n\n HGLRC hGLRC = wglCreateContext(g_hDC);\n wglMakeCurrent(g_hDC, hGLRC);\n\n ShowWindow(hWnd, SW_SHOWNORMAL);\n\n ImGui_ImplWin32GL_Init(hWnd);\n}\n\nint main()\n{\n int fbwidth = 1024;\n int fbheight = 768;\n\n SetProcessDPIAware();\n init_window(fbwidth, fbheight);\n\n renderer_t* rd = new_renderer(fbwidth, fbheight);\n\n scene_t* sc = new_scene();\n uint32_t first_model_id, num_added_models;\n scene_add_models(sc, \"assets\/cube\/cube.obj\", \"assets\/cube\/\", &first_model_id, &num_added_models);\n for (uint32_t model_id = first_model_id; model_id < first_model_id + num_added_models; model_id++)\n {\n uint32_t instance_id;\n scene_add_instance(sc, model_id, &instance_id);\n }\n\n \/\/ compute projection matrix with DirectXMath because lazy\n {\n DirectX::XMMATRIX proj = DirectX::XMMatrixPerspectiveFovLH(DirectX::XMConvertToRadians(70.0f), (float)fbwidth \/ fbheight, 0.01f, 10.0f);\n DirectX::XMFLOAT4X4 proj4x4;\n DirectX::XMStoreFloat4x4(&proj4x4, proj);\n\n int32_t fx_proj[16];\n for (int32_t i = 0; i < 16; i++)\n {\n fx_proj[i] = s1516_flt(*((float*)proj4x4.m + i));\n }\n scene_set_projection(sc, fx_proj);\n }\n\n float eye[3] = { 0.0f, 0.0f, 3.0f };\n float look[3] = { 0.0f, 0.0f, -1.0f };\n const float up[3] = { 0.0f, 1.0f, 0.0f };\n\n LARGE_INTEGER then, now, freq;\n QueryPerformanceFrequency(&freq);\n QueryPerformanceCounter(&then);\n\n POINT oldcursor;\n GetCursorPos(&oldcursor);\n\n bool show_tiles = true;\n\n uint8_t* rgba8_pixels = (uint8_t*)malloc(fbwidth * fbheight * 4);\n assert(rgba8_pixels);\n\n \/\/ readback framebuffer contents\n framebuffer_t* fb = renderer_get_framebuffer(rd);\n\n while (!(GetAsyncKeyState(VK_ESCAPE) & 0x8000))\n {\n MSG msg;\n while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))\n {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n ImGui_ImplWin32GL_NewFrame();\n \n if (ImGui::Begin(\"Toolbox\"))\n {\n ImGui::Checkbox(\"Show tiles\", &show_tiles);\n ImGui::End();\n }\n\n QueryPerformanceCounter(&now);\n float delta_time_sec = (float)(now.QuadPart - then.QuadPart) \/ freq.QuadPart;\n\n POINT cursor;\n GetCursorPos(&cursor);\n\n \/\/ only move and rotate camera when right mouse button is pressed\n float activated = (GetAsyncKeyState(VK_RBUTTON) & 0x8000) ? 1.0f : 0.0f;\n\n float view[16];\n flythrough_camera_update(\n eye, look, up, view,\n delta_time_sec,\n 10.0f * ((GetAsyncKeyState(VK_LSHIFT) & 0x8000) ? 2.0f : 1.0f) * activated,\n 0.5f * activated,\n 80.0f,\n cursor.x - oldcursor.x, cursor.y - oldcursor.y,\n GetAsyncKeyState('W') & 0x8000, GetAsyncKeyState('A') & 0x8000, GetAsyncKeyState('S') & 0x8000, GetAsyncKeyState('D') & 0x8000,\n GetAsyncKeyState(VK_SPACE) & 0x8000, GetAsyncKeyState(VK_LCONTROL) & 0x8000,\n FLYTHROUGH_CAMERA_LEFT_HANDED_BIT);\n\n int32_t view_s1516[16];\n for (int32_t i = 0; i < 16; i++)\n {\n view_s1516[i] = s1516_flt(view[i]);\n }\n scene_set_view(sc, view_s1516);\n\n renderer_render_scene(rd, sc);\n\n \/\/ render rasterization to screen\n {\n framebuffer_t* fb = renderer_get_framebuffer(rd);\n framebuffer_pack_row_major(fb, 0, 0, fbwidth, fbheight, pixelformat_r8g8b8a8_unorm, rgba8_pixels);\n \/\/ flip the rows to appease the OpenGL gods\n for (int32_t row = 0; row < fbheight \/ 2; row++)\n {\n for (int32_t col = 0; col < fbwidth; col++)\n {\n uint32_t tmp = *(uint32_t*)&rgba8_pixels[(row * fbwidth + col) * 4];\n *(uint32_t*)&rgba8_pixels[(row * fbwidth + col) * 4] = *(uint32_t*)&rgba8_pixels[((fbheight - row - 1) * fbwidth + col) * 4];\n *(uint32_t*)&rgba8_pixels[((fbheight - row - 1) * fbwidth + col) * 4] = tmp;\n }\n }\n glDrawPixels(fbwidth, fbheight, GL_RGBA, GL_UNSIGNED_BYTE, rgba8_pixels);\n }\n\n \/\/ draw lines showing tiles\n if (show_tiles)\n {\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluOrtho2D(0.0, (GLdouble)fbwidth, (GLdouble)fbheight, 0.0);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n glBegin(GL_LINES);\n glColor4f(1.0f, 1.0f, 1.0f, 0.5f);\n for (int i = 0; i < fbwidth \/ 128; i++)\n {\n glVertex2f(i * 128.0f, 0.0f);\n glVertex2f(i * 128.0f, (float)fbheight);\n }\n for (int i = 0; i < fbheight \/ 128; i++)\n {\n glVertex2f(0.0f, i * 128.0f);\n glVertex2f((float)fbwidth, i * 128.0f);\n }\n glEnd();\n glBlendFunc(GL_ONE, GL_ZERO);\n glDisable(GL_BLEND);\n }\n\n ImGui::Render();\n\n SwapBuffers(g_hDC);\n\n then = now;\n oldcursor = cursor;\n }\n\n free(rgba8_pixels);\n\n delete_scene(sc);\n delete_renderer(rd);\n\n return 0;\n}<commit_msg>add raster time info<commit_after>#include <renderer.h>\n#include <rasterizer.h>\n#include <s1516.h>\n\n#include <stdio.h>\n\n#define FLYTHROUGH_CAMERA_IMPLEMENTATION\n#include <flythrough_camera.h>\n\n#include <Windows.h>\n#include <DirectXMath.h>\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n\n#include <imgui.h>\n#include <imgui_impl_win32_gl.h>\n\n#pragma comment(lib, \"OpenGL32.lib\")\n#pragma comment(lib, \"glu32.lib\")\n\nLRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\n{\n if (ImGui_ImplWin32GL_WndProcHandler(hWnd, message, wParam, lParam))\n return true;\n\n switch (message)\n {\n case WM_CLOSE:\n ExitProcess(0);\n return 0;\n case WM_SYSCOMMAND:\n if ((wParam & 0xfff0) == SC_KEYMENU) \/\/ Disable ALT application menu\n return 0;\n break;\n }\n return DefWindowProc(hWnd, message, wParam, lParam);\n}\n\nHDC g_hDC;\n\nvoid init_window(int32_t width, int32_t height)\n{\n WNDCLASSEX wc;\n ZeroMemory(&wc, sizeof(wc));\n wc.cbSize = sizeof(wc);\n wc.style = CS_OWNDC;\n wc.lpfnWndProc = MyWndProc;\n wc.hInstance = GetModuleHandle(NULL);\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;\n wc.lpszClassName = TEXT(\"WindowClass\");\n RegisterClassEx(&wc);\n\n RECT wr = { 0, 0, width, height };\n AdjustWindowRect(&wr, 0, FALSE);\n HWND hWnd = CreateWindowEx(\n 0, TEXT(\"WindowClass\"),\n TEXT(\"viewer\"),\n WS_OVERLAPPEDWINDOW,\n 0, 0, wr.right - wr.left, wr.bottom - wr.top,\n 0, 0, GetModuleHandle(NULL), 0);\n\n PIXELFORMATDESCRIPTOR pfd;\n ZeroMemory(&pfd, sizeof(pfd));\n pfd.nSize = sizeof(pfd);\n pfd.nVersion = 1;\n pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;\n pfd.iPixelType = PFD_TYPE_RGBA;\n pfd.cColorBits = 32;\n pfd.iLayerType = PFD_MAIN_PLANE;\n\n g_hDC = GetDC(hWnd);\n\n int chosenPixelFormat = ChoosePixelFormat(g_hDC, &pfd);\n SetPixelFormat(g_hDC, chosenPixelFormat, &pfd);\n\n HGLRC hGLRC = wglCreateContext(g_hDC);\n wglMakeCurrent(g_hDC, hGLRC);\n\n ShowWindow(hWnd, SW_SHOWNORMAL);\n\n ImGui_ImplWin32GL_Init(hWnd);\n}\n\nint main()\n{\n int fbwidth = 1024;\n int fbheight = 768;\n\n SetProcessDPIAware();\n init_window(fbwidth, fbheight);\n\n renderer_t* rd = new_renderer(fbwidth, fbheight);\n\n scene_t* sc = new_scene();\n uint32_t first_model_id, num_added_models;\n scene_add_models(sc, \"assets\/cube\/cube.obj\", \"assets\/cube\/\", &first_model_id, &num_added_models);\n for (uint32_t model_id = first_model_id; model_id < first_model_id + num_added_models; model_id++)\n {\n uint32_t instance_id;\n scene_add_instance(sc, model_id, &instance_id);\n }\n\n \/\/ compute projection matrix with DirectXMath because lazy\n {\n DirectX::XMMATRIX proj = DirectX::XMMatrixPerspectiveFovLH(DirectX::XMConvertToRadians(70.0f), (float)fbwidth \/ fbheight, 0.01f, 10.0f);\n DirectX::XMFLOAT4X4 proj4x4;\n DirectX::XMStoreFloat4x4(&proj4x4, proj);\n\n int32_t fx_proj[16];\n for (int32_t i = 0; i < 16; i++)\n {\n fx_proj[i] = s1516_flt(*((float*)proj4x4.m + i));\n }\n scene_set_projection(sc, fx_proj);\n }\n\n float eye[3] = { 0.0f, 0.0f, 3.0f };\n float look[3] = { 0.0f, 0.0f, -1.0f };\n const float up[3] = { 0.0f, 1.0f, 0.0f };\n\n LARGE_INTEGER then, now, freq;\n QueryPerformanceFrequency(&freq);\n QueryPerformanceCounter(&then);\n\n POINT oldcursor;\n GetCursorPos(&oldcursor);\n\n bool show_tiles = true;\n\n uint8_t* rgba8_pixels = (uint8_t*)malloc(fbwidth * fbheight * 4);\n assert(rgba8_pixels);\n\n \/\/ readback framebuffer contents\n framebuffer_t* fb = renderer_get_framebuffer(rd);\n\n while (!(GetAsyncKeyState(VK_ESCAPE) & 0x8000))\n {\n MSG msg;\n while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))\n {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n ImGui_ImplWin32GL_NewFrame();\n \n if (ImGui::Begin(\"Toolbox\"))\n {\n ImGui::Checkbox(\"Show tiles\", &show_tiles);\n ImGui::End();\n }\n\n QueryPerformanceCounter(&now);\n float delta_time_sec = (float)(now.QuadPart - then.QuadPart) \/ freq.QuadPart;\n\n POINT cursor;\n GetCursorPos(&cursor);\n\n \/\/ only move and rotate camera when right mouse button is pressed\n float activated = (GetAsyncKeyState(VK_RBUTTON) & 0x8000) ? 1.0f : 0.0f;\n\n float view[16];\n flythrough_camera_update(\n eye, look, up, view,\n delta_time_sec,\n 10.0f * ((GetAsyncKeyState(VK_LSHIFT) & 0x8000) ? 2.0f : 1.0f) * activated,\n 0.5f * activated,\n 80.0f,\n cursor.x - oldcursor.x, cursor.y - oldcursor.y,\n GetAsyncKeyState('W') & 0x8000, GetAsyncKeyState('A') & 0x8000, GetAsyncKeyState('S') & 0x8000, GetAsyncKeyState('D') & 0x8000,\n GetAsyncKeyState(VK_SPACE) & 0x8000, GetAsyncKeyState(VK_LCONTROL) & 0x8000,\n FLYTHROUGH_CAMERA_LEFT_HANDED_BIT);\n\n int32_t view_s1516[16];\n for (int32_t i = 0; i < 16; i++)\n {\n view_s1516[i] = s1516_flt(view[i]);\n }\n scene_set_view(sc, view_s1516);\n\n LARGE_INTEGER before_raster, after_raster;\n QueryPerformanceCounter(&before_raster);\n renderer_render_scene(rd, sc);\n QueryPerformanceCounter(&after_raster);\n\n \/\/ render rasterization to screen\n {\n framebuffer_t* fb = renderer_get_framebuffer(rd);\n framebuffer_pack_row_major(fb, 0, 0, fbwidth, fbheight, pixelformat_r8g8b8a8_unorm, rgba8_pixels);\n \/\/ flip the rows to appease the OpenGL gods\n for (int32_t row = 0; row < fbheight \/ 2; row++)\n {\n for (int32_t col = 0; col < fbwidth; col++)\n {\n uint32_t tmp = *(uint32_t*)&rgba8_pixels[(row * fbwidth + col) * 4];\n *(uint32_t*)&rgba8_pixels[(row * fbwidth + col) * 4] = *(uint32_t*)&rgba8_pixels[((fbheight - row - 1) * fbwidth + col) * 4];\n *(uint32_t*)&rgba8_pixels[((fbheight - row - 1) * fbwidth + col) * 4] = tmp;\n }\n }\n glDrawPixels(fbwidth, fbheight, GL_RGBA, GL_UNSIGNED_BYTE, rgba8_pixels);\n }\n\n \/\/ draw lines showing tiles\n if (show_tiles)\n {\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluOrtho2D(0.0, (GLdouble)fbwidth, (GLdouble)fbheight, 0.0);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n glBegin(GL_LINES);\n glColor4f(1.0f, 1.0f, 1.0f, 0.5f);\n for (int i = 0; i < fbwidth \/ 128; i++)\n {\n glVertex2f(i * 128.0f, 0.0f);\n glVertex2f(i * 128.0f, (float)fbheight);\n }\n for (int i = 0; i < fbheight \/ 128; i++)\n {\n glVertex2f(0.0f, i * 128.0f);\n glVertex2f((float)fbwidth, i * 128.0f);\n }\n glEnd();\n glBlendFunc(GL_ONE, GL_ZERO);\n glDisable(GL_BLEND);\n }\n\n if (ImGui::Begin(\"Info\"))\n {\n LONGLONG raster_time = after_raster.QuadPart - before_raster.QuadPart;\n LONGLONG raster_time_us = raster_time * 1000000 \/ freq.QuadPart;\n ImGui::Text(\"Raster time: %llu microseconds\", raster_time_us);\n ImGui::End();\n }\n\n ImGui::Render();\n\n SwapBuffers(g_hDC);\n\n then = now;\n oldcursor = cursor;\n }\n\n free(rgba8_pixels);\n\n delete_scene(sc);\n delete_renderer(rd);\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: brwview.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: oj $ $Date: 2002-02-11 12:46:43 $\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 _SBX_BRWVIEW_HXX\n#define _SBX_BRWVIEW_HXX\n\n#ifndef _SV_WINDOW_HXX \/\/autogen\n#include <vcl\/window.hxx>\n#endif\n\n#ifndef _TOOLBOX_HXX \/\/autogen\n#include <vcl\/toolbox.hxx>\n#endif\n\n#ifndef _TOOLS_RESID_HXX \/\/autogen wg. ResId\n#include <tools\/resid.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_\n#include <com\/sun\/star\/awt\/PosSize.hpp>\n#endif\n#ifndef DBAUI_DATAVIEW_HXX\n#include \"dataview.hxx\"\n#endif\n\nnamespace com { namespace sun { namespace star { namespace awt {\n class XControl;\n class XControlContainer;\n class XControlModel;\n}}}}\n\n\/\/ =========================================================================\nclass ResMgr;\nclass Splitter;\n\nnamespace dbaui\n{\n class DBTreeListModel;\n class DBTreeView;\n class SbaGridControl;\n\n class UnoDataBrowserView : public ODataView\n {\n protected:\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > m_xGrid; \/\/ our grid's UNO representation\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > m_xMe; \/\/ our own UNO representation\n DBTreeView* m_pTreeView;\n Splitter* m_pSplitter;\n SbaGridControl* m_pVclControl; \/\/ our grid's VCL representation\n Window* m_pStatus;\n\n DECL_LINK( SplitHdl, void* );\n \/\/ attribute access\n public:\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > getGridControl() const { return m_xGrid; }\n SbaGridControl* getVclControl() const { return m_pVclControl; }\n\n public:\n UnoDataBrowserView( Window* pParent,\n IController* _pController,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );\n virtual ~UnoDataBrowserView();\n\n \/\/\/ late construction\n virtual void Construct(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& xModel);\n\n \/** as columns may be hidden there is a difference between a columns model pos and its view pos\n so we you may use these translation function\n *\/\n sal_uInt16 Model2ViewPos(sal_uInt16 nPos) const;\n sal_uInt16 View2ModelPos(sal_uInt16 nPos) const;\n \/\/\/ for the same reason the view column count isn't the same as the model column count\n sal_uInt16 ViewColumnCount() const;\n\n void setSplitter(Splitter* _pSplitter);\n void setTreeView(DBTreeView* _pTreeView);\n\n void showStatus( const String& _rStatus );\n void hideStatus();\n\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > getContainer() { return m_xMe; }\n\n protected:\n virtual long PreNotify( NotifyEvent& rNEvt );\n virtual void GetFocus();\n virtual void resizeDocumentView(Rectangle& rRect);\n };\n\n class BrowserViewStatusDisplay\n {\n protected:\n UnoDataBrowserView* m_pView;\n\n public:\n BrowserViewStatusDisplay( UnoDataBrowserView* _pView, const String& _rStatus );\n ~BrowserViewStatusDisplay( );\n };\n}\n#endif \/\/ _SBX_BRWVIEW_HXX\n\n<commit_msg>INTEGRATION: CWS insight01 (1.8.112); FILE MERGED 2004\/03\/11 09:04:03 oj 1.8.112.2: #111075# changes for closing 2004\/02\/27 08:40:24 oj 1.8.112.1: #111075# check for vcl control<commit_after>\/*************************************************************************\n *\n * $RCSfile: brwview.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2004-08-02 15:56:11 $\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 _SBX_BRWVIEW_HXX\n#define _SBX_BRWVIEW_HXX\n\n#ifndef _SV_WINDOW_HXX \/\/autogen\n#include <vcl\/window.hxx>\n#endif\n\n#ifndef _TOOLBOX_HXX \/\/autogen\n#include <vcl\/toolbox.hxx>\n#endif\n\n#ifndef _TOOLS_RESID_HXX \/\/autogen wg. ResId\n#include <tools\/resid.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_\n#include <com\/sun\/star\/awt\/PosSize.hpp>\n#endif\n#ifndef DBAUI_DATAVIEW_HXX\n#include \"dataview.hxx\"\n#endif\n#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_\n#include <unotools\/eventlisteneradapter.hxx>\n#endif\n\n\nnamespace com { namespace sun { namespace star { namespace awt {\n class XControl;\n class XControlContainer;\n class XControlModel;\n}}}}\n\n\/\/ =========================================================================\nclass ResMgr;\nclass Splitter;\n\nnamespace dbaui\n{\n class DBTreeListModel;\n class DBTreeView;\n class SbaGridControl;\n\n class UnoDataBrowserView : public ODataView, public ::utl::OEventListenerAdapter\n {\n protected:\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > m_xGrid; \/\/ our grid's UNO representation\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > m_xMe; \/\/ our own UNO representation\n DBTreeView* m_pTreeView;\n Splitter* m_pSplitter;\n mutable SbaGridControl* m_pVclControl; \/\/ our grid's VCL representation\n Window* m_pStatus;\n\n DECL_LINK( SplitHdl, void* );\n \/\/ attribute access\n public:\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > getGridControl() const { return m_xGrid; }\n SbaGridControl* getVclControl() const;\n\n public:\n UnoDataBrowserView( Window* pParent,\n IController* _pController,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );\n virtual ~UnoDataBrowserView();\n\n \/\/\/ late construction\n virtual void Construct(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& xModel);\n\n \/** as columns may be hidden there is a difference between a columns model pos and its view pos\n so we you may use these translation function\n *\/\n sal_uInt16 Model2ViewPos(sal_uInt16 nPos) const;\n sal_uInt16 View2ModelPos(sal_uInt16 nPos) const;\n \/\/\/ for the same reason the view column count isn't the same as the model column count\n sal_uInt16 ViewColumnCount() const;\n\n void setSplitter(Splitter* _pSplitter);\n void setTreeView(DBTreeView* _pTreeView);\n\n void showStatus( const String& _rStatus );\n void hideStatus();\n\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > getContainer() { return m_xMe; }\n\n protected:\n virtual long PreNotify( NotifyEvent& rNEvt );\n virtual void GetFocus();\n virtual void resizeDocumentView(Rectangle& rRect);\n virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );\n };\n\n class BrowserViewStatusDisplay\n {\n protected:\n UnoDataBrowserView* m_pView;\n\n public:\n BrowserViewStatusDisplay( UnoDataBrowserView* _pView, const String& _rStatus );\n ~BrowserViewStatusDisplay( );\n };\n}\n#endif \/\/ _SBX_BRWVIEW_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dsmeta.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2008-01-30 08:53:14 $\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#include \"dsmeta.hxx\"\n\n\/** === begin UNO includes === **\/\n\/** === end UNO includes === **\/\n\n#include <map>\n\n\/\/........................................................................\nnamespace dbaui\n{\n\/\/........................................................................\n\n \/** === begin UNO using === **\/\n \/** === end UNO using === **\/\n\n struct InitAdvanced : public AdvancedSettingsSupport\n {\n \/\/ strange ctor, but makes instantiating this class more readable (see below)\n InitAdvanced( short _Generated, short _SQL, short _Append, short _As, short _Outer, short _Priv, short _Param,\n short _Version, short _Catalog, short _Schema, short _Index, short _DOS, short _Required, short _Bool,short _IgnoreCur )\n :AdvancedSettingsSupport()\n {\n bGeneratedValues = ( _Generated != 0 );\n bUseSQL92NamingConstraints = ( _SQL != 0 );\n bAppendTableAliasInSelect = ( _Append != 0 );\n bUseKeywordAsBeforeAlias = ( _As != 0 );\n bUseBracketedOuterJoinSyntax = ( _Outer != 0 );\n bIgnoreDriverPrivileges = ( _Priv != 0 );\n bParameterNameSubstitution = ( _Param != 0 );\n bDisplayVersionColumns = ( _Version != 0 );\n bUseCatalogInSelect = ( _Catalog != 0 );\n bUseSchemaInSelect = ( _Schema != 0 );\n bUseIndexDirectionKeyword = ( _Index != 0 );\n bUseDOSLineEnds = ( _DOS != 0 );\n bBooleanComparisonMode = ( _Bool != 0 );\n bFormsCheckRequiredFields = ( _Required != 0 );\n bIgnoreCurrency = ( _IgnoreCur != 0 );\n }\n\n enum Special { All, None };\n\n InitAdvanced( Special _eType )\n :AdvancedSettingsSupport()\n {\n bGeneratedValues = ( _eType == All );\n bUseSQL92NamingConstraints = ( _eType == All );\n bAppendTableAliasInSelect = ( _eType == All );\n bUseKeywordAsBeforeAlias = ( _eType == All );\n bUseBracketedOuterJoinSyntax = ( _eType == All );\n bIgnoreDriverPrivileges = ( _eType == All );\n bParameterNameSubstitution = ( _eType == All );\n bDisplayVersionColumns = ( _eType == All );\n bUseCatalogInSelect = ( _eType == All );\n bUseSchemaInSelect = ( _eType == All );\n bUseIndexDirectionKeyword = ( _eType == All );\n bUseDOSLineEnds = ( _eType == All );\n bBooleanComparisonMode = ( _eType == All );\n bFormsCheckRequiredFields = ( _eType == All );\n bIgnoreCurrency = false; \/\/ Oracle special\n }\n };\n\n struct FeatureSupport\n {\n \/\/ authentication mode of the data source\n AuthenticationMode eAuthentication;\n\n FeatureSupport()\n :eAuthentication( AuthUserPwd )\n {\n }\n\n FeatureSupport( AuthenticationMode _Auth )\n :eAuthentication( _Auth )\n {\n }\n };\n\n \/\/====================================================================\n \/\/= global tables\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n static const AdvancedSettingsSupport& getAdvancedSettingsSupport( DATASOURCE_TYPE _eType )\n {\n typedef ::std::map< DATASOURCE_TYPE, AdvancedSettingsSupport > AdvancedSupport;\n\n static AdvancedSupport s_aSupport;\n if ( s_aSupport.empty() )\n {\n s_aSupport[ DST_MSACCESS ] = InitAdvanced( 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_ODBC ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_JDBC ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_ORACLE_JDBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ADABAS ] = InitAdvanced( 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_CALC ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_DBASE ] = InitAdvanced( 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 );\n s_aSupport[ DST_FLAT ] = InitAdvanced( 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );\n s_aSupport[ DST_JDBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ODBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ADO ] = InitAdvanced( 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0 );\n s_aSupport[ DST_MOZILLA ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_THUNDERBIRD ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_LDAP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_OUTLOOK ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_OUTLOOKEXP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION_GROUPWISE ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION_LDAP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_KAB ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_MSACCESS_2007 ] = InitAdvanced( 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_EMBEDDED_HSQLDB ] = InitAdvanced( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 );\n s_aSupport[ DST_USERDEFINE1 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE2 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE3 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE4 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE5 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE6 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE7 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE8 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE9 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE10 ] = InitAdvanced( InitAdvanced::All );\n\n s_aSupport[ DST_ORACLE_JDBC ].bIgnoreCurrency = true;\n }\n return s_aSupport[ _eType ];\n }\n\n \/\/--------------------------------------------------------------------\n static AuthenticationMode getAuthenticationMode( DATASOURCE_TYPE _eType )\n {\n typedef ::std::map< DATASOURCE_TYPE, FeatureSupport > Supported;\n\n static Supported s_aSupport;\n if ( s_aSupport.empty() )\n {\n s_aSupport[ DST_MSACCESS ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_MYSQL_ODBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MYSQL_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ORACLE_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ADABAS ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_CALC ] = FeatureSupport( AuthPwd );\n s_aSupport[ DST_DBASE ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_FLAT ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ODBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ADO ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MOZILLA ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_THUNDERBIRD ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_LDAP ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_OUTLOOK ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_OUTLOOKEXP ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION_GROUPWISE ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION_LDAP ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_KAB ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_MSACCESS_2007 ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EMBEDDED_HSQLDB ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_USERDEFINE1 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE2 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE3 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE4 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE5 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE6 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE7 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE8 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE9 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE10 ] = FeatureSupport( AuthUserPwd );\n }\n return s_aSupport[ _eType ].eAuthentication;\n }\n\n \/\/====================================================================\n \/\/= DataSourceMetaData_Impl\n \/\/====================================================================\n class DataSourceMetaData_Impl\n {\n public:\n DataSourceMetaData_Impl( DATASOURCE_TYPE _eType );\n\n inline DATASOURCE_TYPE getType() const { return m_eType; }\n\n private:\n DATASOURCE_TYPE m_eType;\n };\n\n \/\/--------------------------------------------------------------------\n DataSourceMetaData_Impl::DataSourceMetaData_Impl( DATASOURCE_TYPE _eType )\n :m_eType( _eType )\n {\n }\n\n \/\/====================================================================\n \/\/= DataSourceMetaData\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n DataSourceMetaData::DataSourceMetaData( DATASOURCE_TYPE _eType )\n :m_pImpl( new DataSourceMetaData_Impl( _eType ) )\n {\n }\n\n \/\/--------------------------------------------------------------------\n DataSourceMetaData::~DataSourceMetaData()\n {\n }\n\n \/\/--------------------------------------------------------------------\n DATASOURCE_TYPE DataSourceMetaData::getType() const\n {\n return m_pImpl->getType();\n }\n\n \/\/--------------------------------------------------------------------\n const AdvancedSettingsSupport& DataSourceMetaData::getAdvancedSettingsSupport() const\n {\n return ::dbaui::getAdvancedSettingsSupport( m_pImpl->getType() );\n }\n\n \/\/--------------------------------------------------------------------\n AuthenticationMode DataSourceMetaData::getAuthentication() const\n {\n return getAuthenticationMode( m_pImpl->getType() );\n }\n\n \/\/--------------------------------------------------------------------\n AuthenticationMode DataSourceMetaData::getAuthentication( DATASOURCE_TYPE _eType )\n {\n return getAuthenticationMode( _eType );\n }\n\n\/\/........................................................................\n} \/\/ namespace dbaui\n\/\/........................................................................\n<commit_msg>INTEGRATION: CWS dba30a (1.5.12); FILE MERGED 2008\/02\/20 21:31:56 fs 1.5.12.2: remove unused code Issue number: #i86284# Submitted by: cmc@openoffice.org Reviewed by: fs@openoffice.org 2008\/02\/14 08:37:49 oj 1.5.12.1: #i86088# add url handling for sdbc:mysqlc:<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dsmeta.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 17:05:29 $\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#include \"dsmeta.hxx\"\n\n\/** === begin UNO includes === **\/\n\/** === end UNO includes === **\/\n\n#include <map>\n\n\/\/........................................................................\nnamespace dbaui\n{\n\/\/........................................................................\n\n \/** === begin UNO using === **\/\n \/** === end UNO using === **\/\n\n struct InitAdvanced : public AdvancedSettingsSupport\n {\n \/\/ strange ctor, but makes instantiating this class more readable (see below)\n InitAdvanced( short _Generated, short _SQL, short _Append, short _As, short _Outer, short _Priv, short _Param,\n short _Version, short _Catalog, short _Schema, short _Index, short _DOS, short _Required, short _Bool,short _IgnoreCur )\n :AdvancedSettingsSupport()\n {\n bGeneratedValues = ( _Generated != 0 );\n bUseSQL92NamingConstraints = ( _SQL != 0 );\n bAppendTableAliasInSelect = ( _Append != 0 );\n bUseKeywordAsBeforeAlias = ( _As != 0 );\n bUseBracketedOuterJoinSyntax = ( _Outer != 0 );\n bIgnoreDriverPrivileges = ( _Priv != 0 );\n bParameterNameSubstitution = ( _Param != 0 );\n bDisplayVersionColumns = ( _Version != 0 );\n bUseCatalogInSelect = ( _Catalog != 0 );\n bUseSchemaInSelect = ( _Schema != 0 );\n bUseIndexDirectionKeyword = ( _Index != 0 );\n bUseDOSLineEnds = ( _DOS != 0 );\n bBooleanComparisonMode = ( _Bool != 0 );\n bFormsCheckRequiredFields = ( _Required != 0 );\n bIgnoreCurrency = ( _IgnoreCur != 0 );\n }\n\n enum Special { All, None };\n\n InitAdvanced( Special _eType )\n :AdvancedSettingsSupport()\n {\n bGeneratedValues = ( _eType == All );\n bUseSQL92NamingConstraints = ( _eType == All );\n bAppendTableAliasInSelect = ( _eType == All );\n bUseKeywordAsBeforeAlias = ( _eType == All );\n bUseBracketedOuterJoinSyntax = ( _eType == All );\n bIgnoreDriverPrivileges = ( _eType == All );\n bParameterNameSubstitution = ( _eType == All );\n bDisplayVersionColumns = ( _eType == All );\n bUseCatalogInSelect = ( _eType == All );\n bUseSchemaInSelect = ( _eType == All );\n bUseIndexDirectionKeyword = ( _eType == All );\n bUseDOSLineEnds = ( _eType == All );\n bBooleanComparisonMode = ( _eType == All );\n bFormsCheckRequiredFields = ( _eType == All );\n bIgnoreCurrency = false; \/\/ Oracle special\n }\n };\n\n struct FeatureSupport\n {\n \/\/ authentication mode of the data source\n AuthenticationMode eAuthentication;\n\n FeatureSupport()\n :eAuthentication( AuthUserPwd )\n {\n }\n\n FeatureSupport( AuthenticationMode _Auth )\n :eAuthentication( _Auth )\n {\n }\n };\n\n \/\/====================================================================\n \/\/= global tables\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n static const AdvancedSettingsSupport& getAdvancedSettingsSupport( DATASOURCE_TYPE _eType )\n {\n typedef ::std::map< DATASOURCE_TYPE, AdvancedSettingsSupport > AdvancedSupport;\n\n static AdvancedSupport s_aSupport;\n if ( s_aSupport.empty() )\n {\n s_aSupport[ DST_MSACCESS ] = InitAdvanced( 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_ODBC ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_JDBC ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_NATIVE ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_ORACLE_JDBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ADABAS ] = InitAdvanced( 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_CALC ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_DBASE ] = InitAdvanced( 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 );\n s_aSupport[ DST_FLAT ] = InitAdvanced( 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );\n s_aSupport[ DST_JDBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ODBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ADO ] = InitAdvanced( 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0 );\n s_aSupport[ DST_MOZILLA ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_THUNDERBIRD ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_LDAP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_OUTLOOK ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_OUTLOOKEXP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION_GROUPWISE ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION_LDAP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_KAB ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_MSACCESS_2007 ] = InitAdvanced( 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_EMBEDDED_HSQLDB ] = InitAdvanced( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 );\n s_aSupport[ DST_USERDEFINE1 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE2 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE3 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE4 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE5 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE6 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE7 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE8 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE9 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE10 ] = InitAdvanced( InitAdvanced::All );\n\n s_aSupport[ DST_ORACLE_JDBC ].bIgnoreCurrency = true;\n }\n return s_aSupport[ _eType ];\n }\n\n \/\/--------------------------------------------------------------------\n static AuthenticationMode getAuthenticationMode( DATASOURCE_TYPE _eType )\n {\n typedef ::std::map< DATASOURCE_TYPE, FeatureSupport > Supported;\n\n static Supported s_aSupport;\n if ( s_aSupport.empty() )\n {\n s_aSupport[ DST_MSACCESS ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_MYSQL_NATIVE ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MYSQL_ODBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MYSQL_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ORACLE_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ADABAS ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_CALC ] = FeatureSupport( AuthPwd );\n s_aSupport[ DST_DBASE ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_FLAT ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ODBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ADO ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MOZILLA ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_THUNDERBIRD ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_LDAP ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_OUTLOOK ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_OUTLOOKEXP ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION_GROUPWISE ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION_LDAP ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_KAB ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_MSACCESS_2007 ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EMBEDDED_HSQLDB ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_USERDEFINE1 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE2 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE3 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE4 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE5 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE6 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE7 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE8 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE9 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE10 ] = FeatureSupport( AuthUserPwd );\n }\n return s_aSupport[ _eType ].eAuthentication;\n }\n\n \/\/====================================================================\n \/\/= DataSourceMetaData_Impl\n \/\/====================================================================\n class DataSourceMetaData_Impl\n {\n public:\n DataSourceMetaData_Impl( DATASOURCE_TYPE _eType );\n\n inline DATASOURCE_TYPE getType() const { return m_eType; }\n\n private:\n DATASOURCE_TYPE m_eType;\n };\n\n \/\/--------------------------------------------------------------------\n DataSourceMetaData_Impl::DataSourceMetaData_Impl( DATASOURCE_TYPE _eType )\n :m_eType( _eType )\n {\n }\n\n \/\/====================================================================\n \/\/= DataSourceMetaData\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n DataSourceMetaData::DataSourceMetaData( DATASOURCE_TYPE _eType )\n :m_pImpl( new DataSourceMetaData_Impl( _eType ) )\n {\n }\n\n \/\/--------------------------------------------------------------------\n DataSourceMetaData::~DataSourceMetaData()\n {\n }\n\n \/\/--------------------------------------------------------------------\n const AdvancedSettingsSupport& DataSourceMetaData::getAdvancedSettingsSupport() const\n {\n return ::dbaui::getAdvancedSettingsSupport( m_pImpl->getType() );\n }\n\n \/\/--------------------------------------------------------------------\n AuthenticationMode DataSourceMetaData::getAuthentication() const\n {\n return getAuthenticationMode( m_pImpl->getType() );\n }\n\n \/\/--------------------------------------------------------------------\n AuthenticationMode DataSourceMetaData::getAuthentication( DATASOURCE_TYPE _eType )\n {\n return getAuthenticationMode( _eType );\n }\n\n\/\/........................................................................\n} \/\/ namespace dbaui\n\/\/........................................................................\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\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: dptabdat.cxx,v $\n * $Revision: 1.14 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_sc.hxx\"\n\n\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include <rtl\/math.hxx>\n#include <tools\/debug.hxx>\n#include <tools\/date.hxx>\n#include <unotools\/transliterationwrapper.hxx>\n#include <unotools\/collatorwrapper.hxx>\n\n#include <com\/sun\/star\/sheet\/DataPilotFieldFilter.hpp>\n\n#include \"dptabdat.hxx\"\n#include \"global.hxx\"\n#include \"dpcachetable.hxx\"\n#include \"dptabres.hxx\"\n\nusing namespace ::com::sun::star;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::uno::Any;\nusing ::std::vector;\nusing ::std::set;\nusing ::std::hash_map;\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ScDPItemData::IsCaseInsEqual( const ScDPItemData& r ) const\n{\n \/\/! pass Transliteration?\n \/\/! inline?\n return bHasValue ? ( r.bHasValue && rtl::math::approxEqual( fValue, r.fValue ) ) :\n ( !r.bHasValue &&\n ScGlobal::pTransliteration->isEqual( aString, r.aString ) );\n}\n\nsize_t ScDPItemData::Hash() const\n{\n if ( bHasValue )\n return (size_t) rtl::math::approxFloor( fValue );\n else\n \/\/ If we do unicode safe case insensitive hash we can drop\n \/\/ ScDPItemData::operator== and use ::IsCasInsEqual\n return rtl_ustr_hashCode_WithLength( aString.GetBuffer(), aString.Len() );\n}\n\nBOOL ScDPItemData::operator==( const ScDPItemData& r ) const\n{\n if ( bHasValue )\n {\n if ( r.bHasValue )\n return rtl::math::approxEqual( fValue, r.fValue );\n else\n return FALSE;\n }\n else if ( r.bHasValue )\n return FALSE;\n else\n \/\/ need exact equality until we have a safe case insensitive string hash\n return aString == r.aString;\n}\n\nsal_Int32 ScDPItemData::Compare( const ScDPItemData& rA,\n const ScDPItemData& rB )\n{\n if ( rA.bHasValue )\n {\n if ( rB.bHasValue )\n {\n if ( rtl::math::approxEqual( rA.fValue, rB.fValue ) )\n return 0;\n else if ( rA.fValue < rB.fValue )\n return -1;\n else\n return 1;\n }\n else\n return -1; \/\/ values first\n }\n else if ( rB.bHasValue )\n return 1; \/\/ values first\n else\n return ScGlobal::pCollator->compareString( rA.aString, rB.aString );\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nScDPTableData::CalcInfo::CalcInfo() :\n bRepeatIfEmpty(false)\n{\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nScDPTableData::ScDPTableData()\n{\n nLastDateVal = nLastHier = nLastLevel = nLastRet = -1; \/\/ invalid\n\n \/\/! reset before new calculation (in case the base date is changed)\n}\n\nScDPTableData::~ScDPTableData()\n{\n}\n\nlong ScDPTableData::GetDatePart( long nDateVal, long nHierarchy, long nLevel )\n{\n if ( nDateVal == nLastDateVal && nHierarchy == nLastHier && nLevel == nLastLevel )\n return nLastRet;\n\n Date aDate( 30,12,1899 ); \/\/! get from source data (and cache here)\n aDate += nDateVal;\n\n long nRet = 0;\n switch (nHierarchy)\n {\n case SC_DAPI_HIERARCHY_QUARTER:\n switch (nLevel)\n {\n case 0: nRet = aDate.GetYear(); break;\n case 1: nRet = (aDate.GetMonth()-1) \/ 3 + 1; break;\n case 2: nRet = aDate.GetMonth(); break;\n case 3: nRet = aDate.GetDay(); break;\n default:\n DBG_ERROR(\"GetDatePart: wrong level\");\n }\n break;\n case SC_DAPI_HIERARCHY_WEEK:\n switch (nLevel)\n {\n \/\/! use settings for different definitions\n case 0: nRet = aDate.GetYear(); break; \/\/!...\n case 1: nRet = aDate.GetWeekOfYear(); break;\n case 2: nRet = (long)aDate.GetDayOfWeek(); break;\n default:\n DBG_ERROR(\"GetDatePart: wrong level\");\n }\n break;\n default:\n DBG_ERROR(\"GetDatePart: wrong hierarchy\");\n }\n\n nLastDateVal = nDateVal;\n nLastHier = nHierarchy;\n nLastLevel = nLevel;\n nLastRet = nRet;\n\n return nRet;\n}\n\nbool ScDPTableData::IsRepeatIfEmpty()\n{\n return false;\n}\n\nvoid ScDPTableData::CreateCacheTable()\n{\n fprintf(stdout, \"ScDPTableData::CreateCacheTable: un-implemented...\\n\");fflush(stdout);\n}\n\nvoid ScDPTableData::FilterCacheTable(const vector<ScDPDimension*>& rPageDims)\n{\n fprintf(stdout, \"ScDPTableData::FilterCacheTable: un-implemented...\\n\");fflush(stdout);\n}\n\nvoid ScDPTableData::GetDrillDownData(const vector<ScDPCacheTable::Criterion>&, Sequence< Sequence<Any> >&)\n{\n fprintf(stdout, \"ScDPTableData::GetDrillDownData: un-implemented...\\n\");fflush(stdout);\n}\n\nvoid ScDPTableData::CalcResults(CalcInfo& rInfo, bool bAutoShow)\n{\n fprintf(stdout, \"ScDPTableData::CalcResults: un-implemented...\\n\");fflush(stdout);\n}\n\nUINT32 ScDPTableData::GetNumberFormat(long)\n{\n return 0; \/\/ default format\n}\n\nBOOL ScDPTableData::IsBaseForGroup(long) const\n{\n return FALSE; \/\/ always false\n}\n\nlong ScDPTableData::GetGroupBase(long) const\n{\n return -1; \/\/ always none\n}\n\nBOOL ScDPTableData::IsNumOrDateGroup(long) const\n{\n return FALSE; \/\/ always false\n}\n\nBOOL ScDPTableData::IsInGroup( const ScDPItemData&, long,\n const ScDPItemData&, long ) const\n{\n DBG_ERROR(\"IsInGroup shouldn't be called for non-group data\");\n return FALSE;\n}\n\nBOOL ScDPTableData::HasCommonElement( const ScDPItemData&, long,\n const ScDPItemData&, long ) const\n{\n DBG_ERROR(\"HasCommonElement shouldn't be called for non-group data\");\n return FALSE;\n}\n\nvoid ScDPTableData::FillRowDataFromCacheTable(sal_Int32 nRow, const ScDPCacheTable& rCacheTable,\n const CalcInfo& rInfo, CalcRowData& rData)\n{\n \/\/ column dimensions\n GetItemData(rCacheTable, nRow, rInfo.aColLevelDims, rData.aColData);\n\n \/\/ row dimensions\n GetItemData(rCacheTable, nRow, rInfo.aRowLevelDims, rData.aRowData);\n\n \/\/ page dimensions\n GetItemData(rCacheTable, nRow, rInfo.aPageDims, rData.aPageData);\n\n sal_Int32 n = rInfo.aDataSrcCols.size();\n for (sal_Int32 i = 0; i < n; ++i)\n {\n long nDim = rInfo.aDataSrcCols[i];\n rData.aValues.push_back( ScDPValueData() );\n ScDPValueData& rVal = rData.aValues.back();\n const ScDPCacheTable::Cell* pCell = rCacheTable.getCell(nDim, nRow);\n if (pCell)\n {\n rVal.fValue = pCell->mbNumeric ? pCell->mfValue : 0.0;\n rVal.nType = pCell->mnType;\n }\n else\n rVal.Set(0.0, SC_VALTYPE_EMPTY);\n }\n}\n\nvoid ScDPTableData::ProcessRowData(CalcInfo& rInfo, CalcRowData& rData, bool bAutoShow)\n{\n if (!bAutoShow)\n {\n rInfo.pColRoot->LateInitFrom(rInfo.aColDims, rInfo.aColLevels, rData.aColData, 0, *rInfo.pInitState);\n rInfo.pRowRoot->LateInitFrom(rInfo.aRowDims, rInfo.aRowLevels, rData.aRowData, 0, *rInfo.pInitState);\n }\n\n if ( ( !rInfo.pColRoot->GetChildDimension() || rInfo.pColRoot->GetChildDimension()->IsValidEntry(rData.aColData) ) &&\n ( !rInfo.pRowRoot->GetChildDimension() || rInfo.pRowRoot->GetChildDimension()->IsValidEntry(rData.aRowData) ) )\n {\n \/\/! single process method with ColMembers, RowMembers and data !!!\n if (rInfo.pColRoot->GetChildDimension())\n {\n vector<ScDPItemData> aEmptyData;\n rInfo.pColRoot->GetChildDimension()->ProcessData(rData.aColData, NULL, aEmptyData, rData.aValues);\n }\n\n rInfo.pRowRoot->ProcessData(rData.aRowData, rInfo.pColRoot->GetChildDimension(),\n rData.aColData, rData.aValues);\n }\n}\n\nvoid ScDPTableData::CalcResultsFromCacheTable(const ScDPCacheTable& rCacheTable, CalcInfo& rInfo, bool bAutoShow)\n{\n sal_Int32 nRowSize = rCacheTable.getRowSize();\n for (sal_Int32 nRow = 0; nRow < nRowSize; ++nRow)\n {\n if (!rCacheTable.isRowActive(nRow))\n continue;\n\n CalcRowData aData;\n FillRowDataFromCacheTable(nRow, rCacheTable, rInfo, aData);\n ProcessRowData(rInfo, aData, bAutoShow);\n }\n}\n\nvoid ScDPTableData::GetItemData(const ScDPCacheTable& rCacheTable, sal_Int32 nRow,\n const vector<long>& rDims, vector<ScDPItemData>& rItemData)\n{\n sal_Int32 nDimSize = rDims.size();\n for (sal_Int32 i = 0; i < nDimSize; ++i)\n {\n long nDim = rDims[i];\n rItemData.push_back( ScDPItemData() );\n ScDPItemData& rData = rItemData.back();\n if (getIsDataLayoutDimension(nDim))\n {\n rData.SetString(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(\"x\")));\n continue;\n }\n\n const ScDPCacheTable::Cell* pCell = rCacheTable.getCell(nDim, nRow, IsRepeatIfEmpty());\n if (!pCell || pCell->mnType == SC_VALTYPE_EMPTY)\n continue;\n\n const String* pString = ScSharedString::getString(pCell->mnStrId);\n if (!pString)\n continue;\n\n rData.aString = *pString;\n rData.bHasValue = false;\n if (pCell->mbNumeric)\n {\n rData.bHasValue = true;\n rData.fValue = pCell->mfValue;\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\n\n\n\n<commit_msg>#i10000# warning fixed<commit_after>\/*************************************************************************\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: dptabdat.cxx,v $\n * $Revision: 1.15 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_sc.hxx\"\n\n\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include <rtl\/math.hxx>\n#include <tools\/debug.hxx>\n#include <tools\/date.hxx>\n#include <unotools\/transliterationwrapper.hxx>\n#include <unotools\/collatorwrapper.hxx>\n\n#include <com\/sun\/star\/sheet\/DataPilotFieldFilter.hpp>\n\n#include \"dptabdat.hxx\"\n#include \"global.hxx\"\n#include \"dpcachetable.hxx\"\n#include \"dptabres.hxx\"\n\nusing namespace ::com::sun::star;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::uno::Any;\nusing ::std::vector;\nusing ::std::set;\nusing ::std::hash_map;\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ScDPItemData::IsCaseInsEqual( const ScDPItemData& r ) const\n{\n \/\/! pass Transliteration?\n \/\/! inline?\n return bHasValue ? ( r.bHasValue && rtl::math::approxEqual( fValue, r.fValue ) ) :\n ( !r.bHasValue &&\n ScGlobal::pTransliteration->isEqual( aString, r.aString ) );\n}\n\nsize_t ScDPItemData::Hash() const\n{\n if ( bHasValue )\n return (size_t) rtl::math::approxFloor( fValue );\n else\n \/\/ If we do unicode safe case insensitive hash we can drop\n \/\/ ScDPItemData::operator== and use ::IsCasInsEqual\n return rtl_ustr_hashCode_WithLength( aString.GetBuffer(), aString.Len() );\n}\n\nBOOL ScDPItemData::operator==( const ScDPItemData& r ) const\n{\n if ( bHasValue )\n {\n if ( r.bHasValue )\n return rtl::math::approxEqual( fValue, r.fValue );\n else\n return FALSE;\n }\n else if ( r.bHasValue )\n return FALSE;\n else\n \/\/ need exact equality until we have a safe case insensitive string hash\n return aString == r.aString;\n}\n\nsal_Int32 ScDPItemData::Compare( const ScDPItemData& rA,\n const ScDPItemData& rB )\n{\n if ( rA.bHasValue )\n {\n if ( rB.bHasValue )\n {\n if ( rtl::math::approxEqual( rA.fValue, rB.fValue ) )\n return 0;\n else if ( rA.fValue < rB.fValue )\n return -1;\n else\n return 1;\n }\n else\n return -1; \/\/ values first\n }\n else if ( rB.bHasValue )\n return 1; \/\/ values first\n else\n return ScGlobal::pCollator->compareString( rA.aString, rB.aString );\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nScDPTableData::CalcInfo::CalcInfo() :\n bRepeatIfEmpty(false)\n{\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nScDPTableData::ScDPTableData()\n{\n nLastDateVal = nLastHier = nLastLevel = nLastRet = -1; \/\/ invalid\n\n \/\/! reset before new calculation (in case the base date is changed)\n}\n\nScDPTableData::~ScDPTableData()\n{\n}\n\nlong ScDPTableData::GetDatePart( long nDateVal, long nHierarchy, long nLevel )\n{\n if ( nDateVal == nLastDateVal && nHierarchy == nLastHier && nLevel == nLastLevel )\n return nLastRet;\n\n Date aDate( 30,12,1899 ); \/\/! get from source data (and cache here)\n aDate += nDateVal;\n\n long nRet = 0;\n switch (nHierarchy)\n {\n case SC_DAPI_HIERARCHY_QUARTER:\n switch (nLevel)\n {\n case 0: nRet = aDate.GetYear(); break;\n case 1: nRet = (aDate.GetMonth()-1) \/ 3 + 1; break;\n case 2: nRet = aDate.GetMonth(); break;\n case 3: nRet = aDate.GetDay(); break;\n default:\n DBG_ERROR(\"GetDatePart: wrong level\");\n }\n break;\n case SC_DAPI_HIERARCHY_WEEK:\n switch (nLevel)\n {\n \/\/! use settings for different definitions\n case 0: nRet = aDate.GetYear(); break; \/\/!...\n case 1: nRet = aDate.GetWeekOfYear(); break;\n case 2: nRet = (long)aDate.GetDayOfWeek(); break;\n default:\n DBG_ERROR(\"GetDatePart: wrong level\");\n }\n break;\n default:\n DBG_ERROR(\"GetDatePart: wrong hierarchy\");\n }\n\n nLastDateVal = nDateVal;\n nLastHier = nHierarchy;\n nLastLevel = nLevel;\n nLastRet = nRet;\n\n return nRet;\n}\n\nbool ScDPTableData::IsRepeatIfEmpty()\n{\n return false;\n}\n\nvoid ScDPTableData::CreateCacheTable()\n{\n fprintf(stdout, \"ScDPTableData::CreateCacheTable: un-implemented...\\n\");fflush(stdout);\n}\n\nvoid ScDPTableData::FilterCacheTable(const vector<ScDPDimension*>&)\n{\n fprintf(stdout, \"ScDPTableData::FilterCacheTable: un-implemented...\\n\");fflush(stdout);\n}\n\nvoid ScDPTableData::GetDrillDownData(const vector<ScDPCacheTable::Criterion>&, Sequence< Sequence<Any> >&)\n{\n fprintf(stdout, \"ScDPTableData::GetDrillDownData: un-implemented...\\n\");fflush(stdout);\n}\n\nvoid ScDPTableData::CalcResults(CalcInfo&, bool)\n{\n fprintf(stdout, \"ScDPTableData::CalcResults: un-implemented...\\n\");fflush(stdout);\n}\n\nUINT32 ScDPTableData::GetNumberFormat(long)\n{\n return 0; \/\/ default format\n}\n\nBOOL ScDPTableData::IsBaseForGroup(long) const\n{\n return FALSE; \/\/ always false\n}\n\nlong ScDPTableData::GetGroupBase(long) const\n{\n return -1; \/\/ always none\n}\n\nBOOL ScDPTableData::IsNumOrDateGroup(long) const\n{\n return FALSE; \/\/ always false\n}\n\nBOOL ScDPTableData::IsInGroup( const ScDPItemData&, long,\n const ScDPItemData&, long ) const\n{\n DBG_ERROR(\"IsInGroup shouldn't be called for non-group data\");\n return FALSE;\n}\n\nBOOL ScDPTableData::HasCommonElement( const ScDPItemData&, long,\n const ScDPItemData&, long ) const\n{\n DBG_ERROR(\"HasCommonElement shouldn't be called for non-group data\");\n return FALSE;\n}\n\nvoid ScDPTableData::FillRowDataFromCacheTable(sal_Int32 nRow, const ScDPCacheTable& rCacheTable,\n const CalcInfo& rInfo, CalcRowData& rData)\n{\n \/\/ column dimensions\n GetItemData(rCacheTable, nRow, rInfo.aColLevelDims, rData.aColData);\n\n \/\/ row dimensions\n GetItemData(rCacheTable, nRow, rInfo.aRowLevelDims, rData.aRowData);\n\n \/\/ page dimensions\n GetItemData(rCacheTable, nRow, rInfo.aPageDims, rData.aPageData);\n\n sal_Int32 n = rInfo.aDataSrcCols.size();\n for (sal_Int32 i = 0; i < n; ++i)\n {\n long nDim = rInfo.aDataSrcCols[i];\n rData.aValues.push_back( ScDPValueData() );\n ScDPValueData& rVal = rData.aValues.back();\n const ScDPCacheTable::Cell* pCell = rCacheTable.getCell(nDim, nRow);\n if (pCell)\n {\n rVal.fValue = pCell->mbNumeric ? pCell->mfValue : 0.0;\n rVal.nType = pCell->mnType;\n }\n else\n rVal.Set(0.0, SC_VALTYPE_EMPTY);\n }\n}\n\nvoid ScDPTableData::ProcessRowData(CalcInfo& rInfo, CalcRowData& rData, bool bAutoShow)\n{\n if (!bAutoShow)\n {\n rInfo.pColRoot->LateInitFrom(rInfo.aColDims, rInfo.aColLevels, rData.aColData, 0, *rInfo.pInitState);\n rInfo.pRowRoot->LateInitFrom(rInfo.aRowDims, rInfo.aRowLevels, rData.aRowData, 0, *rInfo.pInitState);\n }\n\n if ( ( !rInfo.pColRoot->GetChildDimension() || rInfo.pColRoot->GetChildDimension()->IsValidEntry(rData.aColData) ) &&\n ( !rInfo.pRowRoot->GetChildDimension() || rInfo.pRowRoot->GetChildDimension()->IsValidEntry(rData.aRowData) ) )\n {\n \/\/! single process method with ColMembers, RowMembers and data !!!\n if (rInfo.pColRoot->GetChildDimension())\n {\n vector<ScDPItemData> aEmptyData;\n rInfo.pColRoot->GetChildDimension()->ProcessData(rData.aColData, NULL, aEmptyData, rData.aValues);\n }\n\n rInfo.pRowRoot->ProcessData(rData.aRowData, rInfo.pColRoot->GetChildDimension(),\n rData.aColData, rData.aValues);\n }\n}\n\nvoid ScDPTableData::CalcResultsFromCacheTable(const ScDPCacheTable& rCacheTable, CalcInfo& rInfo, bool bAutoShow)\n{\n sal_Int32 nRowSize = rCacheTable.getRowSize();\n for (sal_Int32 nRow = 0; nRow < nRowSize; ++nRow)\n {\n if (!rCacheTable.isRowActive(nRow))\n continue;\n\n CalcRowData aData;\n FillRowDataFromCacheTable(nRow, rCacheTable, rInfo, aData);\n ProcessRowData(rInfo, aData, bAutoShow);\n }\n}\n\nvoid ScDPTableData::GetItemData(const ScDPCacheTable& rCacheTable, sal_Int32 nRow,\n const vector<long>& rDims, vector<ScDPItemData>& rItemData)\n{\n sal_Int32 nDimSize = rDims.size();\n for (sal_Int32 i = 0; i < nDimSize; ++i)\n {\n long nDim = rDims[i];\n rItemData.push_back( ScDPItemData() );\n ScDPItemData& rData = rItemData.back();\n if (getIsDataLayoutDimension(nDim))\n {\n rData.SetString(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(\"x\")));\n continue;\n }\n\n const ScDPCacheTable::Cell* pCell = rCacheTable.getCell(nDim, nRow, IsRepeatIfEmpty());\n if (!pCell || pCell->mnType == SC_VALTYPE_EMPTY)\n continue;\n\n const String* pString = ScSharedString::getString(pCell->mnStrId);\n if (!pString)\n continue;\n\n rData.aString = *pString;\n rData.bHasValue = false;\n if (pCell->mbNumeric)\n {\n rData.bHasValue = true;\n rData.fValue = pCell->mfValue;\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dsmeta.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 17:05:29 $\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#include \"dsmeta.hxx\"\n\n\/** === begin UNO includes === **\/\n\/** === end UNO includes === **\/\n\n#include <map>\n\n\/\/........................................................................\nnamespace dbaui\n{\n\/\/........................................................................\n\n \/** === begin UNO using === **\/\n \/** === end UNO using === **\/\n\n struct InitAdvanced : public AdvancedSettingsSupport\n {\n \/\/ strange ctor, but makes instantiating this class more readable (see below)\n InitAdvanced( short _Generated, short _SQL, short _Append, short _As, short _Outer, short _Priv, short _Param,\n short _Version, short _Catalog, short _Schema, short _Index, short _DOS, short _Required, short _Bool,short _IgnoreCur )\n :AdvancedSettingsSupport()\n {\n bGeneratedValues = ( _Generated != 0 );\n bUseSQL92NamingConstraints = ( _SQL != 0 );\n bAppendTableAliasInSelect = ( _Append != 0 );\n bUseKeywordAsBeforeAlias = ( _As != 0 );\n bUseBracketedOuterJoinSyntax = ( _Outer != 0 );\n bIgnoreDriverPrivileges = ( _Priv != 0 );\n bParameterNameSubstitution = ( _Param != 0 );\n bDisplayVersionColumns = ( _Version != 0 );\n bUseCatalogInSelect = ( _Catalog != 0 );\n bUseSchemaInSelect = ( _Schema != 0 );\n bUseIndexDirectionKeyword = ( _Index != 0 );\n bUseDOSLineEnds = ( _DOS != 0 );\n bBooleanComparisonMode = ( _Bool != 0 );\n bFormsCheckRequiredFields = ( _Required != 0 );\n bIgnoreCurrency = ( _IgnoreCur != 0 );\n }\n\n enum Special { All, None };\n\n InitAdvanced( Special _eType )\n :AdvancedSettingsSupport()\n {\n bGeneratedValues = ( _eType == All );\n bUseSQL92NamingConstraints = ( _eType == All );\n bAppendTableAliasInSelect = ( _eType == All );\n bUseKeywordAsBeforeAlias = ( _eType == All );\n bUseBracketedOuterJoinSyntax = ( _eType == All );\n bIgnoreDriverPrivileges = ( _eType == All );\n bParameterNameSubstitution = ( _eType == All );\n bDisplayVersionColumns = ( _eType == All );\n bUseCatalogInSelect = ( _eType == All );\n bUseSchemaInSelect = ( _eType == All );\n bUseIndexDirectionKeyword = ( _eType == All );\n bUseDOSLineEnds = ( _eType == All );\n bBooleanComparisonMode = ( _eType == All );\n bFormsCheckRequiredFields = ( _eType == All );\n bIgnoreCurrency = false; \/\/ Oracle special\n }\n };\n\n struct FeatureSupport\n {\n \/\/ authentication mode of the data source\n AuthenticationMode eAuthentication;\n\n FeatureSupport()\n :eAuthentication( AuthUserPwd )\n {\n }\n\n FeatureSupport( AuthenticationMode _Auth )\n :eAuthentication( _Auth )\n {\n }\n };\n\n \/\/====================================================================\n \/\/= global tables\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n static const AdvancedSettingsSupport& getAdvancedSettingsSupport( DATASOURCE_TYPE _eType )\n {\n typedef ::std::map< DATASOURCE_TYPE, AdvancedSettingsSupport > AdvancedSupport;\n\n static AdvancedSupport s_aSupport;\n if ( s_aSupport.empty() )\n {\n s_aSupport[ DST_MSACCESS ] = InitAdvanced( 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_ODBC ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_JDBC ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_NATIVE ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_ORACLE_JDBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ADABAS ] = InitAdvanced( 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_CALC ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_DBASE ] = InitAdvanced( 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 );\n s_aSupport[ DST_FLAT ] = InitAdvanced( 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );\n s_aSupport[ DST_JDBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ODBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ADO ] = InitAdvanced( 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0 );\n s_aSupport[ DST_MOZILLA ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_THUNDERBIRD ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_LDAP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_OUTLOOK ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_OUTLOOKEXP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION_GROUPWISE ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION_LDAP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_KAB ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_MSACCESS_2007 ] = InitAdvanced( 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_EMBEDDED_HSQLDB ] = InitAdvanced( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 );\n s_aSupport[ DST_USERDEFINE1 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE2 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE3 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE4 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE5 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE6 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE7 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE8 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE9 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE10 ] = InitAdvanced( InitAdvanced::All );\n\n s_aSupport[ DST_ORACLE_JDBC ].bIgnoreCurrency = true;\n }\n return s_aSupport[ _eType ];\n }\n\n \/\/--------------------------------------------------------------------\n static AuthenticationMode getAuthenticationMode( DATASOURCE_TYPE _eType )\n {\n typedef ::std::map< DATASOURCE_TYPE, FeatureSupport > Supported;\n\n static Supported s_aSupport;\n if ( s_aSupport.empty() )\n {\n s_aSupport[ DST_MSACCESS ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_MYSQL_NATIVE ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MYSQL_ODBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MYSQL_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ORACLE_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ADABAS ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_CALC ] = FeatureSupport( AuthPwd );\n s_aSupport[ DST_DBASE ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_FLAT ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ODBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ADO ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MOZILLA ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_THUNDERBIRD ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_LDAP ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_OUTLOOK ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_OUTLOOKEXP ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION_GROUPWISE ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION_LDAP ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_KAB ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_MSACCESS_2007 ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EMBEDDED_HSQLDB ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_USERDEFINE1 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE2 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE3 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE4 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE5 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE6 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE7 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE8 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE9 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE10 ] = FeatureSupport( AuthUserPwd );\n }\n return s_aSupport[ _eType ].eAuthentication;\n }\n\n \/\/====================================================================\n \/\/= DataSourceMetaData_Impl\n \/\/====================================================================\n class DataSourceMetaData_Impl\n {\n public:\n DataSourceMetaData_Impl( DATASOURCE_TYPE _eType );\n\n inline DATASOURCE_TYPE getType() const { return m_eType; }\n\n private:\n DATASOURCE_TYPE m_eType;\n };\n\n \/\/--------------------------------------------------------------------\n DataSourceMetaData_Impl::DataSourceMetaData_Impl( DATASOURCE_TYPE _eType )\n :m_eType( _eType )\n {\n }\n\n \/\/====================================================================\n \/\/= DataSourceMetaData\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n DataSourceMetaData::DataSourceMetaData( DATASOURCE_TYPE _eType )\n :m_pImpl( new DataSourceMetaData_Impl( _eType ) )\n {\n }\n\n \/\/--------------------------------------------------------------------\n DataSourceMetaData::~DataSourceMetaData()\n {\n }\n\n \/\/--------------------------------------------------------------------\n const AdvancedSettingsSupport& DataSourceMetaData::getAdvancedSettingsSupport() const\n {\n return ::dbaui::getAdvancedSettingsSupport( m_pImpl->getType() );\n }\n\n \/\/--------------------------------------------------------------------\n AuthenticationMode DataSourceMetaData::getAuthentication() const\n {\n return getAuthenticationMode( m_pImpl->getType() );\n }\n\n \/\/--------------------------------------------------------------------\n AuthenticationMode DataSourceMetaData::getAuthentication( DATASOURCE_TYPE _eType )\n {\n return getAuthenticationMode( _eType );\n }\n\n\/\/........................................................................\n} \/\/ namespace dbaui\n\/\/........................................................................\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.12); FILE MERGED 2008\/03\/31 13:27:54 rt 1.6.12.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: dsmeta.cxx,v $\n * $Revision: 1.7 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"dsmeta.hxx\"\n\n\/** === begin UNO includes === **\/\n\/** === end UNO includes === **\/\n\n#include <map>\n\n\/\/........................................................................\nnamespace dbaui\n{\n\/\/........................................................................\n\n \/** === begin UNO using === **\/\n \/** === end UNO using === **\/\n\n struct InitAdvanced : public AdvancedSettingsSupport\n {\n \/\/ strange ctor, but makes instantiating this class more readable (see below)\n InitAdvanced( short _Generated, short _SQL, short _Append, short _As, short _Outer, short _Priv, short _Param,\n short _Version, short _Catalog, short _Schema, short _Index, short _DOS, short _Required, short _Bool,short _IgnoreCur )\n :AdvancedSettingsSupport()\n {\n bGeneratedValues = ( _Generated != 0 );\n bUseSQL92NamingConstraints = ( _SQL != 0 );\n bAppendTableAliasInSelect = ( _Append != 0 );\n bUseKeywordAsBeforeAlias = ( _As != 0 );\n bUseBracketedOuterJoinSyntax = ( _Outer != 0 );\n bIgnoreDriverPrivileges = ( _Priv != 0 );\n bParameterNameSubstitution = ( _Param != 0 );\n bDisplayVersionColumns = ( _Version != 0 );\n bUseCatalogInSelect = ( _Catalog != 0 );\n bUseSchemaInSelect = ( _Schema != 0 );\n bUseIndexDirectionKeyword = ( _Index != 0 );\n bUseDOSLineEnds = ( _DOS != 0 );\n bBooleanComparisonMode = ( _Bool != 0 );\n bFormsCheckRequiredFields = ( _Required != 0 );\n bIgnoreCurrency = ( _IgnoreCur != 0 );\n }\n\n enum Special { All, None };\n\n InitAdvanced( Special _eType )\n :AdvancedSettingsSupport()\n {\n bGeneratedValues = ( _eType == All );\n bUseSQL92NamingConstraints = ( _eType == All );\n bAppendTableAliasInSelect = ( _eType == All );\n bUseKeywordAsBeforeAlias = ( _eType == All );\n bUseBracketedOuterJoinSyntax = ( _eType == All );\n bIgnoreDriverPrivileges = ( _eType == All );\n bParameterNameSubstitution = ( _eType == All );\n bDisplayVersionColumns = ( _eType == All );\n bUseCatalogInSelect = ( _eType == All );\n bUseSchemaInSelect = ( _eType == All );\n bUseIndexDirectionKeyword = ( _eType == All );\n bUseDOSLineEnds = ( _eType == All );\n bBooleanComparisonMode = ( _eType == All );\n bFormsCheckRequiredFields = ( _eType == All );\n bIgnoreCurrency = false; \/\/ Oracle special\n }\n };\n\n struct FeatureSupport\n {\n \/\/ authentication mode of the data source\n AuthenticationMode eAuthentication;\n\n FeatureSupport()\n :eAuthentication( AuthUserPwd )\n {\n }\n\n FeatureSupport( AuthenticationMode _Auth )\n :eAuthentication( _Auth )\n {\n }\n };\n\n \/\/====================================================================\n \/\/= global tables\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n static const AdvancedSettingsSupport& getAdvancedSettingsSupport( DATASOURCE_TYPE _eType )\n {\n typedef ::std::map< DATASOURCE_TYPE, AdvancedSettingsSupport > AdvancedSupport;\n\n static AdvancedSupport s_aSupport;\n if ( s_aSupport.empty() )\n {\n s_aSupport[ DST_MSACCESS ] = InitAdvanced( 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_ODBC ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_JDBC ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_MYSQL_NATIVE ] = InitAdvanced( 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_ORACLE_JDBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ADABAS ] = InitAdvanced( 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_CALC ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_DBASE ] = InitAdvanced( 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 );\n s_aSupport[ DST_FLAT ] = InitAdvanced( 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );\n s_aSupport[ DST_JDBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ODBC ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_ADO ] = InitAdvanced( 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0 );\n s_aSupport[ DST_MOZILLA ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_THUNDERBIRD ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_LDAP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_OUTLOOK ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_OUTLOOKEXP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION_GROUPWISE ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_EVOLUTION_LDAP ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_KAB ] = InitAdvanced( InitAdvanced::None );\n s_aSupport[ DST_MSACCESS_2007 ] = InitAdvanced( 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 );\n s_aSupport[ DST_EMBEDDED_HSQLDB ] = InitAdvanced( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 );\n s_aSupport[ DST_USERDEFINE1 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE2 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE3 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE4 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE5 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE6 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE7 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE8 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE9 ] = InitAdvanced( InitAdvanced::All );\n s_aSupport[ DST_USERDEFINE10 ] = InitAdvanced( InitAdvanced::All );\n\n s_aSupport[ DST_ORACLE_JDBC ].bIgnoreCurrency = true;\n }\n return s_aSupport[ _eType ];\n }\n\n \/\/--------------------------------------------------------------------\n static AuthenticationMode getAuthenticationMode( DATASOURCE_TYPE _eType )\n {\n typedef ::std::map< DATASOURCE_TYPE, FeatureSupport > Supported;\n\n static Supported s_aSupport;\n if ( s_aSupport.empty() )\n {\n s_aSupport[ DST_MSACCESS ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_MYSQL_NATIVE ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MYSQL_ODBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MYSQL_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ORACLE_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ADABAS ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_CALC ] = FeatureSupport( AuthPwd );\n s_aSupport[ DST_DBASE ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_FLAT ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_JDBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ODBC ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_ADO ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_MOZILLA ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_THUNDERBIRD ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_LDAP ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_OUTLOOK ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_OUTLOOKEXP ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION_GROUPWISE ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EVOLUTION_LDAP ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_KAB ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_MSACCESS_2007 ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_EMBEDDED_HSQLDB ] = FeatureSupport( AuthNone );\n s_aSupport[ DST_USERDEFINE1 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE2 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE3 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE4 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE5 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE6 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE7 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE8 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE9 ] = FeatureSupport( AuthUserPwd );\n s_aSupport[ DST_USERDEFINE10 ] = FeatureSupport( AuthUserPwd );\n }\n return s_aSupport[ _eType ].eAuthentication;\n }\n\n \/\/====================================================================\n \/\/= DataSourceMetaData_Impl\n \/\/====================================================================\n class DataSourceMetaData_Impl\n {\n public:\n DataSourceMetaData_Impl( DATASOURCE_TYPE _eType );\n\n inline DATASOURCE_TYPE getType() const { return m_eType; }\n\n private:\n DATASOURCE_TYPE m_eType;\n };\n\n \/\/--------------------------------------------------------------------\n DataSourceMetaData_Impl::DataSourceMetaData_Impl( DATASOURCE_TYPE _eType )\n :m_eType( _eType )\n {\n }\n\n \/\/====================================================================\n \/\/= DataSourceMetaData\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n DataSourceMetaData::DataSourceMetaData( DATASOURCE_TYPE _eType )\n :m_pImpl( new DataSourceMetaData_Impl( _eType ) )\n {\n }\n\n \/\/--------------------------------------------------------------------\n DataSourceMetaData::~DataSourceMetaData()\n {\n }\n\n \/\/--------------------------------------------------------------------\n const AdvancedSettingsSupport& DataSourceMetaData::getAdvancedSettingsSupport() const\n {\n return ::dbaui::getAdvancedSettingsSupport( m_pImpl->getType() );\n }\n\n \/\/--------------------------------------------------------------------\n AuthenticationMode DataSourceMetaData::getAuthentication() const\n {\n return getAuthenticationMode( m_pImpl->getType() );\n }\n\n \/\/--------------------------------------------------------------------\n AuthenticationMode DataSourceMetaData::getAuthentication( DATASOURCE_TYPE _eType )\n {\n return getAuthenticationMode( _eType );\n }\n\n\/\/........................................................................\n} \/\/ namespace dbaui\n\/\/........................................................................\n<|endoftext|>"} {"text":"<commit_before>\n#include \"ffmpegvideoread.h\"\n#include <thread>\n#include <iostream>\n#include <exception>\n\nnamespace sgraph{\n\n\/\/stream_ffmpegi::stream_ffmpegi(uint8_t * data[4], enum AVPixelFormat pix_fmt) : sgstream()\n\/\/{\n\t\/**av_image_fill_pointers \t(data,pix_fmt,height,\n\t\tthis->ptr,\n\t\tconst int \tlinesizes[4] \n\t) \t*\/\n\n\/\/}\n\n\n\nffmpegvideoread::ffmpegvideoread(double freq, int64_t blocking, std::string sourcepath, std::string sourceprovider): sgactor(freq, blocking)\n{\n\tthis->sourcepath=sourcepath;\n\tthis->sourceprovider=sourceprovider;\n}\n\nvoid ffmpegvideoread::enter(const std::vector<sgstreamspec*> &in,const std::vector<std::string> &out)\n{\n\tint errorno;\n\tffmpeg::av_register_all();\n\t\/\/needed?\n\tffmpeg::avcodec_register_all();\n\n\tif (in.size()!=0 || out.size()!=1)\n\t\tthrow(sgraph::sgraphStreamException(\"invalid amount of in- or outstreams\"));\n\n\tffmpeg::AVInputFormat *input_device_format=NULL;\n\tif (this->sourceprovider!=\"\")\n\t{\n\t\t\/\/needed?\n\t\tffmpeg::avdevice_register_all();\n\t\tinput_device_format = ffmpeg::av_input_video_device_next(input_device_format);\n\t\twhile (input_device_format!=NULL)\n\t\t{\n\t\t\tif(strcmp(this->sourceprovider.c_str(), input_device_format->name)==0)\n\t\t\t\tbreak;\n\t\t\tinput_device_format = ffmpeg::av_input_video_device_next(input_device_format);\n\t\t}\n\n\t\tif (input_device_format==NULL)\n\t\t{\n\t\t\tthrow(sgraphException(\"Error: finding video input format failed\"));\n\t\t}\n\t}\n\n\terrorno = ffmpeg::avformat_open_input (&this->form_context, this->sourcepath.c_str(), NULL, NULL);\n\tif (errorno<0)\n\t{\n\t\tthrow(sgraphException(\"Error: opening video file failed\"));\n\t}\n\tffmpeg::av_dump_format(this->form_context, 0, this->sourcepath.c_str(), 0);\n\n\tthis->video_stream_index = ffmpeg::av_find_best_stream(this->form_context, ffmpeg::AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);\n\tif(this->video_stream_index < 0)\n\t{\n\t\tthrow(sgraphException(\"Error: no videostream found\"));\n\t}\n\tthis->cod_context = this->form_context->streams[this->video_stream_index]->codec;\n\t\/\/av_opt_set_int(this->codec, \"refcounted_frames\", 1, 0);\n\tthis->codec = ffmpeg::avcodec_find_decoder(this->cod_context->codec_id);\n\tif (this->codec == NULL) {\n\t\tthrow(sgraphException(\"Error: unsupported codec\"));\n\t}\n\n\t\/\/ init the video decoder\n\terrorno = ffmpeg::avcodec_open2(this->cod_context, this->codec, NULL);\n\tif (errorno < 0) {\n\t\tthrow(sgraphException(\"Error: codec could not be opened\"));\n\t}\n\n\tthis->getManager()->updateStreamspec(out[0], new spec_ffmpegi(this->cod_context, 4));\n\n\tffmpeg::av_init_packet(&this->packet);\n\tthis->frame = ffmpeg::av_frame_alloc();\n\tthis->intern_thread=new std::thread(sgactor::thread_wrapper, this);\n}\nvoid ffmpegvideoread::run(const std::vector<std::shared_ptr<sgstream>> )\n{\n\t\/\/this->packet.data=0;\n\t\/\/this->packet.size=0;\n\tif (ffmpeg::av_read_frame(this->form_context, &this->packet)<0)\n\t\treturn;\n\t\/\/ dismiss wrong packets\n\tstd::cout << \"read1\\n\";\n\twhile(packet.stream_index!=this->video_stream_index)\n\t{\n\t\tif (ffmpeg::av_read_frame(this->form_context, &this->packet)<0)\n\t\t\treturn;\n\t}\n\tstd::cout << \"read2\\n\";\n\n\n\t\/\/this->input_device_format->read_packet(this->form_context, this->packet);\n\t\/\/av_read_frame(&this->contex, &packet)\n\tffmpeg::avcodec_decode_video2(this->cod_context, this->origframe, &this->got_frame, &this->packet);\n\tif (this->got_frame==0)\n\t\treturn;\n\tint size = ffmpeg::av_image_get_buffer_size(ffmpeg::AV_PIX_FMT_RGBA64, this->origframe->width, this->origframe->height, 0);\n\tstd::cout << size << std::endl;\n\tuint8_t *buffer=(uint8_t*)calloc(sizeof(uint8_t),size);\n\tffmpeg::sws_scale(sws_ctx, (uint8_t const * const *)this->frame->data,\n\t\t\t this->frame->linesize, 0, this->cod_context->height,\n\t\t\t pFrameRGB->data, pFrameRGB->linesize)\n\tffmpeg::av_image_copy_to_buffer(buffer,size, this->frame->data, this->frame->linesize, ffmpeg::AV_PIX_FMT_RGBA64, this->frame->width, this->frame->height, 0);\n\tthis->streamsout[0]->updateStream(new stream_data(buffer, size));\n\t\/\/this->packet.data=0;\n\t\/\/this->packet.size=0;\n\t\n}\nvoid ffmpegvideoread::leave()\n{\n\n\t\/\/if (this->input_device_format)\n\t\/\/\tav_freep (this->input_device_format);\n\t\/\/ Close the codec\n\t\/\/ Close the video file\n\tffmpeg::av_frame_free(&this->origframe);\n\tffmpeg::av_frame_free(&this->convertframe);\n\tffmpeg::av_free_packet(&this->packet);\n\n\tffmpeg::avcodec_close (this->cod_context);\n\tthis->cod_context = 0;\n\n\tffmpeg::avformat_close_input (&this->form_context);\n\tthis->form_context = 0;\n\n}\n\nffmpegvideoread::~ffmpegvideoread()\n{\n\n\n\t\/\/if (this->input_device_format)\n\t\/\/\tav_freep (this->input_device_format);\n\t\/\/ Close the codec\n\tif (this->cod_context)\n\t\tffmpeg::avcodec_close (this->cod_context);\n\t\/\/ Close the video file\n\tif (this->form_context)\n\t\tffmpeg::avformat_close_input (&this->form_context);\n\n}\n\n\n}\n<commit_msg>fix build<commit_after>\n#include \"ffmpegvideoread.h\"\n#include <thread>\n#include <iostream>\n#include <exception>\n\nnamespace sgraph{\n\n\/\/stream_ffmpegi::stream_ffmpegi(uint8_t * data[4], enum AVPixelFormat pix_fmt) : sgstream()\n\/\/{\n\t\/**av_image_fill_pointers \t(data,pix_fmt,height,\n\t\tthis->ptr,\n\t\tconst int \tlinesizes[4] \n\t) \t*\/\n\n\/\/}\n\n\n\nffmpegvideoread::ffmpegvideoread(double freq, int64_t blocking, std::string sourcepath, std::string sourceprovider): sgactor(freq, blocking)\n{\n\tthis->sourcepath=sourcepath;\n\tthis->sourceprovider=sourceprovider;\n}\n\nvoid ffmpegvideoread::enter(const std::vector<sgstreamspec*> &in,const std::vector<std::string> &out)\n{\n\tint errorno;\n\tffmpeg::av_register_all();\n\t\/\/needed?\n\tffmpeg::avcodec_register_all();\n\n\tif (in.size()!=0 || out.size()!=1)\n\t\tthrow(sgraph::sgraphStreamException(\"invalid amount of in- or outstreams\"));\n\n\tffmpeg::AVInputFormat *input_device_format=NULL;\n\tif (this->sourceprovider!=\"\")\n\t{\n\t\t\/\/needed?\n\t\tffmpeg::avdevice_register_all();\n\t\tinput_device_format = ffmpeg::av_input_video_device_next(input_device_format);\n\t\twhile (input_device_format!=NULL)\n\t\t{\n\t\t\tif(strcmp(this->sourceprovider.c_str(), input_device_format->name)==0)\n\t\t\t\tbreak;\n\t\t\tinput_device_format = ffmpeg::av_input_video_device_next(input_device_format);\n\t\t}\n\n\t\tif (input_device_format==NULL)\n\t\t{\n\t\t\tthrow(sgraphException(\"Error: finding video input format failed\"));\n\t\t}\n\t}\n\n\terrorno = ffmpeg::avformat_open_input (&this->form_context, this->sourcepath.c_str(), NULL, NULL);\n\tif (errorno<0)\n\t{\n\t\tthrow(sgraphException(\"Error: opening video file failed\"));\n\t}\n\tffmpeg::av_dump_format(this->form_context, 0, this->sourcepath.c_str(), 0);\n\n\tthis->video_stream_index = ffmpeg::av_find_best_stream(this->form_context, ffmpeg::AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);\n\tif(this->video_stream_index < 0)\n\t{\n\t\tthrow(sgraphException(\"Error: no videostream found\"));\n\t}\n\tthis->cod_context = this->form_context->streams[this->video_stream_index]->codec;\n\t\/\/av_opt_set_int(this->codec, \"refcounted_frames\", 1, 0);\n\tthis->codec = ffmpeg::avcodec_find_decoder(this->cod_context->codec_id);\n\tif (this->codec == NULL) {\n\t\tthrow(sgraphException(\"Error: unsupported codec\"));\n\t}\n\n\t\/\/ init the video decoder\n\terrorno = ffmpeg::avcodec_open2(this->cod_context, this->codec, NULL);\n\tif (errorno < 0) {\n\t\tthrow(sgraphException(\"Error: codec could not be opened\"));\n\t}\n\n\tthis->getManager()->updateStreamspec(out[0], new spec_ffmpegi(this->cod_context, 4));\n\n\tffmpeg::av_init_packet(&this->packet);\n\tthis->origframe = ffmpeg::av_frame_alloc();\n\tthis->convertframe = ffmpeg::av_frame_alloc();\n\tthis->intern_thread=new std::thread(sgactor::thread_wrapper, this);\n}\nvoid ffmpegvideoread::run(const std::vector<std::shared_ptr<sgstream>> )\n{\n\t\/\/this->packet.data=0;\n\t\/\/this->packet.size=0;\n\tif (ffmpeg::av_read_frame(this->form_context, &this->packet)<0)\n\t\treturn;\n\t\/\/ dismiss wrong packets\n\t\/\/std::cout << \"read1\\n\";\n\twhile(packet.stream_index!=this->video_stream_index)\n\t{\n\t\tif (ffmpeg::av_read_frame(this->form_context, &this->packet)<0)\n\t\t\treturn;\n\t}\n\t\/\/std::cout << \"read2\\n\";\n\n\n\t\/\/this->input_device_format->read_packet(this->form_context, this->packet);\n\t\/\/av_read_frame(&this->contex, &packet)\n\tffmpeg::avcodec_decode_video2(this->cod_context, this->origframe, &this->got_frame, &this->packet);\n\tif (this->got_frame==0)\n\t\treturn;\n\tint size = ffmpeg::av_image_get_buffer_size(ffmpeg::AV_PIX_FMT_RGBA64, this->origframe->width, this->origframe->height, 0);\n\t\/\/std::cout << size << std::endl;\n\t\/\/uint8_t *buffer=(uint8_t*)calloc(sizeof(uint8_t),size);\n\t\/\/ffmpeg::sws_scale(sws_ctx, (uint8_t const * const *)this->origframe->data,\n\t\/\/\t\t this->convertframe->linesize, 0, this->cod_context->height,\n\t\/\/\t\t pFrameRGB->data, pFrameRGB->linesize)\n\t\/\/ffmpeg::av_image_copy_to_buffer(buffer,size, this->convertframe->data, this->convertframe->linesize, ffmpeg::AV_PIX_FMT_RGBA64, this->convertframe->width, this->convertframe->height, 0);\n\t\/\/this->streamsout[0]->updateStream(new stream_data(buffer, size));\n\t\/\/this->packet.data=0;\n\t\/\/this->packet.size=0;\n\t\n}\nvoid ffmpegvideoread::leave()\n{\n\n\t\/\/if (this->input_device_format)\n\t\/\/\tav_freep (this->input_device_format);\n\t\/\/ Close the codec\n\t\/\/ Close the video file\n\tffmpeg::av_frame_free(&this->origframe);\n\tffmpeg::av_frame_free(&this->convertframe);\n\tffmpeg::av_free_packet(&this->packet);\n\n\tffmpeg::avcodec_close (this->cod_context);\n\tthis->cod_context = 0;\n\n\tffmpeg::avformat_close_input (&this->form_context);\n\tthis->form_context = 0;\n\n}\n\nffmpegvideoread::~ffmpegvideoread()\n{\n\n\n\t\/\/if (this->input_device_format)\n\t\/\/\tav_freep (this->input_device_format);\n\t\/\/ Close the codec\n\tif (this->cod_context)\n\t\tffmpeg::avcodec_close (this->cod_context);\n\t\/\/ Close the video file\n\tif (this->form_context)\n\t\tffmpeg::avformat_close_input (&this->form_context);\n\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>oculusDK2 Plugin<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * C S O U N D\n *\n * L I C E N S E\n *\n * This software 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 software 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 software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n#include \"VoiceleadingNode.hpp\"\n#include \"Conversions.hpp\"\n#include \"Voicelead.hpp\"\n#include \"System.hpp\"\n\n#include <cmath>\n#include <cfloat>\n#include <sstream>\n\nnamespace csound\n{\n extern void printChord(std::ostream &stream, std::string label, const std::vector<double> &chord);\n\n extern void printChord(std::string label, const std::vector<double> &chord);\n\n \/**\n * Utility class for storing voice-leading operations.\n *\/\n VoiceleadingOperation::VoiceleadingOperation() :\n beginTime(0.0),\n rescaledBeginTime(0.0),\n rescaledEndTime(0.0),\n P(DBL_MAX),\n T(DBL_MAX),\n C(DBL_MAX),\n K(DBL_MAX),\n Q(DBL_MAX),\n V(DBL_MAX),\n L(false),\n begin(0),\n end(0),\n avoidParallels(false)\n {\n }\n\n VoiceleadingOperation::~VoiceleadingOperation()\n {\n }\n\n VoiceleadingNode::VoiceleadingNode() :\n base(36.0),\n range(60.0),\n rescaleTimes(true),\n avoidParallels(true),\n divisionsPerOctave(12)\n {\n }\n\n VoiceleadingNode::~VoiceleadingNode()\n {\n }\n\n std::ostream &operator << (std::ostream &stream, const VoiceleadingOperation &operation)\n {\n stream << \" beginTime: \" << operation.beginTime << std::endl;\n stream << \" rescaledBeginTime: \" << operation.rescaledBeginTime << std::endl;\n stream << \" rescaledEndTime: \" << operation.rescaledEndTime << std::endl;\n stream << \" begin: \" << operation.begin << std::endl;\n stream << \" end: \" << operation.end << std::endl;\n if (!(operation.P == DBL_MAX)) {\n stream << \" P: \" << operation.P << std::endl;\n }\n if (!(operation.T == DBL_MAX)) {\n stream << \" T: \" << operation.T << std::endl;\n }\n if (!(operation.C == DBL_MAX)) {\n stream << \" C: \" << operation.C << std::endl;\n }\n if (!(operation.K == DBL_MAX)) {\n stream << \" K: \" << operation.K << std::endl;\n }\n if (!(operation.Q == DBL_MAX)) {\n stream << \" Q: \" << operation.Q << std::endl;\n }\n if (!(operation.V == DBL_MAX)) {\n stream << \" V: \" << operation.V << std::endl;\n }\n if (operation.L) {\n stream << \" L: \" << int(operation.L) << std::endl;\n }\n return stream;\n }\n\n void VoiceleadingNode::apply(Score &score, const VoiceleadingOperation &priorOperation, const VoiceleadingOperation &operation)\n {\n if ( (System::getMessageLevel() & System::INFORMATION_LEVEL) == System::INFORMATION_LEVEL) {\n std::stringstream stream;\n stream << \"BEGAN VoiceleadingNode::apply:...\" << std::endl;\n stream << \"Events in score: \" << score.size() << std::endl;\n stream << \"Score duration: \" << score.getDuration() << std::endl;\n stream << \"Events in operation: \" << (operation.end - operation.begin) << std::endl;\n stream << \"priorOperation: \" << std::endl << priorOperation;\n stream << \"currrentOperation: \" << std::endl << operation;\n stream << \"modality: \";\n printChord(stream, \"\", modality);\n stream << std::endl;\n System::inform(stream.str().c_str());\n }\n if (operation.begin == operation.end) {\n return;\n }\n if (!(operation.K == DBL_MAX)) {\n if ((operation.V == DBL_MAX) && (!operation.L)) {\n\tSystem::inform(\"Operation: K\\n\");\n\tscore.setK(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t base,\n\t\t range);\n } else if ((operation.V != DBL_MAX) && (!operation.L)) {\n\tSystem::inform(\"Operation: KV\\n\");\n\tscore.setKV(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t operation.V,\n\t\t base,\n\t\t range);\n } else if ((operation.V == DBL_MAX) && (operation.L)) {\n\tSystem::inform(\"Operation: KL\\n\");\n\tscore.setKL(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t base,\n\t\t range,\n\t\t operation.avoidParallels);\n }\n } else if (!(operation.Q == DBL_MAX)) {\n if ((operation.V == DBL_MAX) && (operation.L == DBL_MAX)) {\n\tSystem::inform(\"Operation: Q\\n\");\n\tscore.setQ(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t operation.Q,\n\t\t modality,\n\t\t base,\n\t\t range);\n } else if ((operation.V != DBL_MAX) && (operation.L == DBL_MAX)) {\t\n\tSystem::inform(\"Operation: QV\\n\");\n\tscore.setQV(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t operation.Q,\n\t\t modality,\n\t\t operation.V,\n\t\t base,\n\t\t range);\n } else if ((operation.V == DBL_MAX) && (operation.L != DBL_MAX)) {\n\tSystem::inform(\"Operation: QL\\n\");\n\tscore.setQL(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t operation.Q,\n\t\t modality,\n\t\t base,\n\t\t range,\n\t\t operation.avoidParallels);\n }\n } else if (!(operation.P == DBL_MAX) && !(operation.T == DBL_MAX)) {\n if (!(operation.V == DBL_MAX)) {\n\tSystem::inform(\"Operation: PTV\\n\");\n score.setPTV(operation.begin,\n operation.end,\n operation.P,\n operation.T,\n operation.V,\n base,\n range);\n } else if (operation.L) {\n\tSystem::inform(\"Operation: PTL\\n\");\n score.setPT(operation.begin,\n operation.end,\n operation.P,\n operation.T,\n base,\n range,\n divisionsPerOctave);\n score.voicelead(priorOperation.begin,\n priorOperation.end,\n operation.begin,\n operation.end,\n base,\n range,\n avoidParallels,\n divisionsPerOctave);\n } else {\n\tSystem::inform(\"Operation: PT\\n\");\n score.setPT(operation.begin,\n operation.end,\n operation.P,\n operation.T,\n base,\n range,\n divisionsPerOctave);\n }\n } else if (!(operation.C == DBL_MAX)) {\n if (!(operation.V == DBL_MAX)) {\n\tSystem::inform(\"Operation: CV\\n\");\n std::vector<double> pcs = Voicelead::mToPitchClassSet(Voicelead::cToM(operation.C, divisionsPerOctave), divisionsPerOctave);\n printChord(\"CV\", pcs);\n std::vector<double> pt = Voicelead::pitchClassSetToPandT(pcs, divisionsPerOctave);\n double prime = pt[0];\n double transposition = pt[1];\n System::inform(\"prime: %f transposition %f: divisionsPerOctave %d\\n\", prime, transposition, divisionsPerOctave);\n score.setPTV(operation.begin,\n operation.end,\n prime,\n transposition,\n operation.V,\n base,\n range);\n } else if (operation.L) {\n\tSystem::inform(\"Operation: CL\\n\");\n std::vector<double> pcs = Voicelead::mToPitchClassSet(Voicelead::cToM(operation.C, divisionsPerOctave), divisionsPerOctave);\n printChord(\"CL\", pcs);\n score.voicelead(priorOperation.begin,\n priorOperation.end,\n operation.begin,\n operation.end,\n pcs,\n base,\n range,\n avoidParallels,\n divisionsPerOctave);\n } else {\n\tSystem::inform(\"Operation: C\\n\");\n std::vector<double> pcs = Voicelead::mToPitchClassSet(Voicelead::cToM(operation.C, divisionsPerOctave), divisionsPerOctave);\n score.setPitchClassSet(operation.begin,\n operation.end,\n pcs,\n divisionsPerOctave);\n }\n } else {\n\tSystem::inform(\"Operation: V\\n\");\n if (!(operation.V == DBL_MAX)) {\n std::vector<double> ptv = score.getPTV(operation.begin,\n operation.end,\n base,\n range,\n divisionsPerOctave);\n score.setPTV(operation.begin,\n operation.end,\n ptv[0],\n ptv[1],\n operation.V,\n base,\n range,\n divisionsPerOctave);\n } else if (operation.L) {\n\tSystem::inform(\"Operation: L\\n\");\n score.voicelead(priorOperation.begin,\n priorOperation.end,\n operation.begin,\n operation.end,\n base,\n range,\n avoidParallels,\n divisionsPerOctave);\n }\n }\n System::message(\"ENDED VoiceleadingNode::apply.\\n\");\n }\n\n void VoiceleadingNode::PT(double time, double P, double T)\n {\n operations[time].beginTime = time;\n operations[time].P = P;\n operations[time].T = T;\n }\n\n void VoiceleadingNode::PTV(double time, double P, double T, double V)\n {\n operations[time].beginTime = time;\n operations[time].P = P;\n operations[time].T = T;\n operations[time].V = V;\n }\n\n void VoiceleadingNode::PTL(double time, double P, double T, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].P = P;\n operations[time].T = T;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::C(double time, double C_)\n {\n operations[time].beginTime = time;\n operations[time].C = C_;\n }\n\n void VoiceleadingNode::C(double time, std::string C_)\n {\n C(time, Voicelead::nameToC(C_, divisionsPerOctave));\n }\n\n void VoiceleadingNode::CV(double time, double C, double V)\n {\n operations[time].beginTime = time;\n operations[time].C = C;\n operations[time].V = V;\n }\n\n void VoiceleadingNode::CV(double time, std::string C, double V)\n {\n CV(time, Voicelead::nameToC(C, divisionsPerOctave), V);\n }\n\n void VoiceleadingNode::CL(double time, double C, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].C = C;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::CL(double time, std::string C, bool avoidParallels)\n {\n CL(time, Voicelead::nameToC(C, divisionsPerOctave), avoidParallels);\n }\n\n void VoiceleadingNode::K(double time)\n {\n operations[time].beginTime = time;\n operations[time].K = 1.0;\n }\n\n void VoiceleadingNode::KV(double time, double V)\n {\n operations[time].beginTime = time;\n operations[time].K = 1.0;\n operations[time].V = V;\n }\n\n void VoiceleadingNode::KL(double time, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].K = 1.0;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::Q(double time, double Q)\n {\n operations[time].beginTime = time;\n operations[time].Q = Q;\n }\n\n void VoiceleadingNode::QV(double time, double Q, double V)\n {\n operations[time].beginTime = time;\n operations[time].Q = Q;\n operations[time].V = V;\n }\n\n void VoiceleadingNode::QL(double time, double Q, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].Q = Q;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::V(double time, double V_)\n {\n operations[time].beginTime = time;\n operations[time].V = V_;\n }\n\n void VoiceleadingNode::L(double time, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &coordinates)\n {\n transform(score, rescaleTimes);\n }\n\n void VoiceleadingNode::transform(Score &score, bool rescaleTimes_)\n {\n if (operations.empty()) {\n return;\n }\n \/\/ Find the time rescale factor.\n score.sort();\n score.findScale();\n double scoreMinTime = score.scaleActualMinima.getTime();\n double scoreDuration = score.getDuration();\n double scoreMaxTime = scoreMinTime + scoreDuration;\n double operationMaxTime = 0.0;\n double timeScale = 1.0;\n std::vector<VoiceleadingOperation *> ops;\n for (std::map<double, VoiceleadingOperation>::iterator it = operations.begin(); it != operations.end(); ++it) {\n if (it->second.beginTime > operationMaxTime) {\n operationMaxTime = it->second.beginTime;\n }\n ops.push_back(&it->second);\n }\n \n if (rescaleTimes_) {\n if (operationMaxTime > 0.0) {\n timeScale = scoreMaxTime \/ operationMaxTime;\n }\n }\n System::inform(\"BEGAN VoiceleadingNode::produceOrTransform operationMaxTime: %f origin: %f duration: %f scoreMaxTime: %f timeScale: %f...\\n\",\n operationMaxTime,\n scoreMinTime,\n scoreDuration,\n scoreMaxTime,\n timeScale);\n VoiceleadingOperation *priorOperation = 0;\n VoiceleadingOperation *currentOperation = 0;\n VoiceleadingOperation *nextOperation = 0;\n int priorIndex = 0;\n int currentIndex = 0;\n int nextIndex = 0;\n int backIndex = ops.size() - 1;\n int endIndex = ops.size();\n for (currentIndex = 0; currentIndex < endIndex; ++currentIndex) {\n if (currentIndex == 0) {\n\tpriorIndex = currentIndex;\n } else {\n\tpriorIndex = currentIndex - 1;\n }\n if (currentIndex == backIndex) {\n\tnextIndex = currentIndex;\n } else {\n\tnextIndex = currentIndex + 1;\n }\n priorOperation = ops[priorIndex];\n currentOperation = ops[currentIndex];\n nextOperation = ops[nextIndex];\n currentOperation->rescaledBeginTime = currentOperation->beginTime * timeScale;\n currentOperation->begin = score.indexAtTime(currentOperation->rescaledBeginTime);\n currentOperation->rescaledEndTime = nextOperation->beginTime * timeScale;\n currentOperation->end = score.indexAfterTime(currentOperation->rescaledEndTime);\n apply(score, *priorOperation, *currentOperation);\n }\n System::inform(\"ENDED VoiceleadingNode::produceOrTransform.\\n\");\n }\n\n}\n<commit_msg>*** empty log message ***<commit_after>\/*\n * C S O U N D\n *\n * L I C E N S E\n *\n * This software 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 software 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 software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n#include \"VoiceleadingNode.hpp\"\n#include \"Conversions.hpp\"\n#include \"Voicelead.hpp\"\n#include \"System.hpp\"\n\n#include <cmath>\n#include <cfloat>\n#include <sstream>\n\nnamespace csound\n{\n extern void printChord(std::ostream &stream, std::string label, const std::vector<double> &chord);\n\n extern void printChord(std::string label, const std::vector<double> &chord);\n\n \/**\n * Utility class for storing voice-leading operations.\n *\/\n VoiceleadingOperation::VoiceleadingOperation() :\n beginTime(0.0),\n rescaledBeginTime(0.0),\n rescaledEndTime(0.0),\n P(DBL_MAX),\n T(DBL_MAX),\n C(DBL_MAX),\n K(DBL_MAX),\n Q(DBL_MAX),\n V(DBL_MAX),\n L(false),\n begin(0),\n end(0),\n avoidParallels(false)\n {\n }\n\n VoiceleadingOperation::~VoiceleadingOperation()\n {\n }\n\n VoiceleadingNode::VoiceleadingNode() :\n base(36.0),\n range(60.0),\n rescaleTimes(true),\n avoidParallels(true),\n divisionsPerOctave(12)\n {\n }\n\n VoiceleadingNode::~VoiceleadingNode()\n {\n }\n\n std::ostream &operator << (std::ostream &stream, const VoiceleadingOperation &operation)\n {\n stream << \" beginTime: \" << operation.beginTime << std::endl;\n stream << \" rescaledBeginTime: \" << operation.rescaledBeginTime << std::endl;\n stream << \" rescaledEndTime: \" << operation.rescaledEndTime << std::endl;\n stream << \" begin: \" << operation.begin << std::endl;\n stream << \" end: \" << operation.end << std::endl;\n if (!(operation.P == DBL_MAX)) {\n stream << \" P: \" << operation.P << std::endl;\n }\n if (!(operation.T == DBL_MAX)) {\n stream << \" T: \" << operation.T << std::endl;\n }\n if (!(operation.C == DBL_MAX)) {\n stream << \" C: \" << operation.C << std::endl;\n }\n if (!(operation.K == DBL_MAX)) {\n stream << \" K: \" << operation.K << std::endl;\n }\n if (!(operation.Q == DBL_MAX)) {\n stream << \" Q: \" << operation.Q << std::endl;\n }\n if (!(operation.V == DBL_MAX)) {\n stream << \" V: \" << operation.V << std::endl;\n }\n if (operation.L) {\n stream << \" L: \" << int(operation.L) << std::endl;\n }\n return stream;\n }\n\n void VoiceleadingNode::apply(Score &score, const VoiceleadingOperation &priorOperation, const VoiceleadingOperation &operation)\n {\n if ( (System::getMessageLevel() & System::INFORMATION_LEVEL) == System::INFORMATION_LEVEL) {\n std::stringstream stream;\n stream << \"BEGAN VoiceleadingNode::apply:...\" << std::endl;\n stream << \"Events in score: \" << score.size() << std::endl;\n stream << \"Score duration: \" << score.getDuration() << std::endl;\n stream << \"Events in operation: \" << (operation.end - operation.begin) << std::endl;\n stream << \"priorOperation: \" << std::endl << priorOperation;\n stream << \"currrentOperation: \" << std::endl << operation;\n stream << \"modality: \";\n printChord(stream, \"\", modality);\n stream << std::endl;\n System::inform(stream.str().c_str());\n }\n if (operation.begin == operation.end) {\n return;\n }\n if (!(operation.K == DBL_MAX)) {\n if ((operation.V == DBL_MAX) && (!operation.L)) {\n\tSystem::inform(\"Operation: K\\n\");\n\tscore.setK(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t base,\n\t\t range);\n } else if ((operation.V != DBL_MAX) && (!operation.L)) {\n\tSystem::inform(\"Operation: KV\\n\");\n\tscore.setKV(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t operation.V,\n\t\t base,\n\t\t range);\n } else if ((operation.V == DBL_MAX) && (operation.L)) {\n\tSystem::inform(\"Operation: KL\\n\");\n\tscore.setKL(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t base,\n\t\t range,\n\t\t operation.avoidParallels);\n }\n } else if (!(operation.Q == DBL_MAX)) {\n if ((operation.V == DBL_MAX) && (!operation.L)) {\n\tSystem::inform(\"Operation: Q\\n\");\n\tscore.setQ(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t operation.Q,\n\t\t modality,\n\t\t base,\n\t\t range);\n } else if ((operation.V != DBL_MAX) && (!operation.L)) {\t\n\tSystem::inform(\"Operation: QV\\n\");\n\tscore.setQV(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t operation.Q,\n\t\t modality,\n\t\t operation.V,\n\t\t base,\n\t\t range);\n } else if ((operation.V == DBL_MAX) && (operation.L)) {\n\tSystem::inform(\"Operation: QL\\n\");\n\tscore.setQL(priorOperation.begin,\n\t\t operation.begin,\n\t\t operation.end,\n\t\t operation.Q,\n\t\t modality,\n\t\t base,\n\t\t range,\n\t\t operation.avoidParallels);\n }\n } else if (!(operation.P == DBL_MAX) && !(operation.T == DBL_MAX)) {\n if (!(operation.V == DBL_MAX)) {\n\tSystem::inform(\"Operation: PTV\\n\");\n score.setPTV(operation.begin,\n operation.end,\n operation.P,\n operation.T,\n operation.V,\n base,\n range);\n } else if (operation.L) {\n\tSystem::inform(\"Operation: PTL\\n\");\n score.setPT(operation.begin,\n operation.end,\n operation.P,\n operation.T,\n base,\n range,\n divisionsPerOctave);\n score.voicelead(priorOperation.begin,\n priorOperation.end,\n operation.begin,\n operation.end,\n base,\n range,\n avoidParallels,\n divisionsPerOctave);\n } else {\n\tSystem::inform(\"Operation: PT\\n\");\n score.setPT(operation.begin,\n operation.end,\n operation.P,\n operation.T,\n base,\n range,\n divisionsPerOctave);\n }\n } else if (!(operation.C == DBL_MAX)) {\n if (!(operation.V == DBL_MAX)) {\n\tSystem::inform(\"Operation: CV\\n\");\n std::vector<double> pcs = Voicelead::mToPitchClassSet(Voicelead::cToM(operation.C, divisionsPerOctave), divisionsPerOctave);\n printChord(\"CV\", pcs);\n std::vector<double> pt = Voicelead::pitchClassSetToPandT(pcs, divisionsPerOctave);\n double prime = pt[0];\n double transposition = pt[1];\n System::inform(\"prime: %f transposition %f: divisionsPerOctave %d\\n\", prime, transposition, divisionsPerOctave);\n score.setPTV(operation.begin,\n operation.end,\n prime,\n transposition,\n operation.V,\n base,\n range);\n } else if (operation.L) {\n\tSystem::inform(\"Operation: CL\\n\");\n std::vector<double> pcs = Voicelead::mToPitchClassSet(Voicelead::cToM(operation.C, divisionsPerOctave), divisionsPerOctave);\n printChord(\"CL\", pcs);\n score.voicelead(priorOperation.begin,\n priorOperation.end,\n operation.begin,\n operation.end,\n pcs,\n base,\n range,\n avoidParallels,\n divisionsPerOctave);\n } else {\n\tSystem::inform(\"Operation: C\\n\");\n std::vector<double> pcs = Voicelead::mToPitchClassSet(Voicelead::cToM(operation.C, divisionsPerOctave), divisionsPerOctave);\n score.setPitchClassSet(operation.begin,\n operation.end,\n pcs,\n divisionsPerOctave);\n }\n } else {\n\tSystem::inform(\"Operation: V\\n\");\n if (!(operation.V == DBL_MAX)) {\n std::vector<double> ptv = score.getPTV(operation.begin,\n operation.end,\n base,\n range,\n divisionsPerOctave);\n score.setPTV(operation.begin,\n operation.end,\n ptv[0],\n ptv[1],\n operation.V,\n base,\n range,\n divisionsPerOctave);\n } else if (operation.L) {\n\tSystem::inform(\"Operation: L\\n\");\n score.voicelead(priorOperation.begin,\n priorOperation.end,\n operation.begin,\n operation.end,\n base,\n range,\n avoidParallels,\n divisionsPerOctave);\n }\n }\n System::message(\"ENDED VoiceleadingNode::apply.\\n\");\n }\n\n void VoiceleadingNode::PT(double time, double P, double T)\n {\n operations[time].beginTime = time;\n operations[time].P = P;\n operations[time].T = T;\n }\n\n void VoiceleadingNode::PTV(double time, double P, double T, double V)\n {\n operations[time].beginTime = time;\n operations[time].P = P;\n operations[time].T = T;\n operations[time].V = V;\n }\n\n void VoiceleadingNode::PTL(double time, double P, double T, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].P = P;\n operations[time].T = T;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::C(double time, double C_)\n {\n operations[time].beginTime = time;\n operations[time].C = C_;\n }\n\n void VoiceleadingNode::C(double time, std::string C_)\n {\n C(time, Voicelead::nameToC(C_, divisionsPerOctave));\n }\n\n void VoiceleadingNode::CV(double time, double C, double V)\n {\n operations[time].beginTime = time;\n operations[time].C = C;\n operations[time].V = V;\n }\n\n void VoiceleadingNode::CV(double time, std::string C, double V)\n {\n CV(time, Voicelead::nameToC(C, divisionsPerOctave), V);\n }\n\n void VoiceleadingNode::CL(double time, double C, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].C = C;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::CL(double time, std::string C, bool avoidParallels)\n {\n CL(time, Voicelead::nameToC(C, divisionsPerOctave), avoidParallels);\n }\n\n void VoiceleadingNode::K(double time)\n {\n operations[time].beginTime = time;\n operations[time].K = 1.0;\n }\n\n void VoiceleadingNode::KV(double time, double V)\n {\n operations[time].beginTime = time;\n operations[time].K = 1.0;\n operations[time].V = V;\n }\n\n void VoiceleadingNode::KL(double time, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].K = 1.0;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::Q(double time, double Q)\n {\n operations[time].beginTime = time;\n operations[time].Q = Q;\n }\n\n void VoiceleadingNode::QV(double time, double Q, double V)\n {\n operations[time].beginTime = time;\n operations[time].Q = Q;\n operations[time].V = V;\n }\n\n void VoiceleadingNode::QL(double time, double Q, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].Q = Q;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::V(double time, double V_)\n {\n operations[time].beginTime = time;\n operations[time].V = V_;\n }\n\n void VoiceleadingNode::L(double time, bool avoidParallels)\n {\n operations[time].beginTime = time;\n operations[time].L = true;\n operations[time].avoidParallels = avoidParallels;\n }\n\n void VoiceleadingNode::produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &coordinates)\n {\n transform(score, rescaleTimes);\n }\n\n void VoiceleadingNode::transform(Score &score, bool rescaleTimes_)\n {\n if (operations.empty()) {\n return;\n }\n \/\/ Find the time rescale factor.\n score.sort();\n score.findScale();\n double scoreMinTime = score.scaleActualMinima.getTime();\n double scoreDuration = score.getDuration();\n double scoreMaxTime = scoreMinTime + scoreDuration;\n double operationMaxTime = 0.0;\n double timeScale = 1.0;\n std::vector<VoiceleadingOperation *> ops;\n for (std::map<double, VoiceleadingOperation>::iterator it = operations.begin(); it != operations.end(); ++it) {\n if (it->second.beginTime > operationMaxTime) {\n operationMaxTime = it->second.beginTime;\n }\n ops.push_back(&it->second);\n }\n \n if (rescaleTimes_) {\n if (operationMaxTime > 0.0) {\n timeScale = scoreMaxTime \/ operationMaxTime;\n }\n }\n System::inform(\"BEGAN VoiceleadingNode::produceOrTransform operationMaxTime: %f origin: %f duration: %f scoreMaxTime: %f timeScale: %f...\\n\",\n operationMaxTime,\n scoreMinTime,\n scoreDuration,\n scoreMaxTime,\n timeScale);\n VoiceleadingOperation *priorOperation = 0;\n VoiceleadingOperation *currentOperation = 0;\n VoiceleadingOperation *nextOperation = 0;\n int priorIndex = 0;\n int currentIndex = 0;\n int nextIndex = 0;\n int backIndex = ops.size() - 1;\n int endIndex = ops.size();\n for (currentIndex = 0; currentIndex < endIndex; ++currentIndex) {\n if (currentIndex == 0) {\n\tpriorIndex = currentIndex;\n } else {\n\tpriorIndex = currentIndex - 1;\n }\n if (currentIndex == backIndex) {\n\tnextIndex = currentIndex;\n } else {\n\tnextIndex = currentIndex + 1;\n }\n priorOperation = ops[priorIndex];\n currentOperation = ops[currentIndex];\n nextOperation = ops[nextIndex];\n currentOperation->rescaledBeginTime = currentOperation->beginTime * timeScale;\n currentOperation->begin = score.indexAtTime(currentOperation->rescaledBeginTime);\n currentOperation->rescaledEndTime = nextOperation->beginTime * timeScale;\n currentOperation->end = score.indexAfterTime(currentOperation->rescaledEndTime);\n apply(score, *priorOperation, *currentOperation);\n }\n System::inform(\"ENDED VoiceleadingNode::produceOrTransform.\\n\");\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Utility functions used for parsing and evaluating equations\n\/\/ William Immendorf - 2016\n\/\/ Compile with --std=c++11\n\n#include <stdexcept>\n#include <unordered_map>\n\n#include \"utility.hpp\"\n\nstruct operator_detail \n{\n\tint precendence;\n\tbool right_associative;\n};\n\nconst std::unordered_map<char, operator_detail> operator_map \n{\n\t{'+', {2, false}},\n\t{'-', {2, false}},\n\t{'*', {3, false}},\n\t{'\/', {3, false}},\n\t{'^', {4, true}}\n};\n\nnamespace EquParser\n{\n\tbool precendence_less_than(char op1, char op2)\n\t{\n\t\tauto op_iterator1 = operator_map.find(op1);\n\t\tauto op_iterator2 = operator_map.find(op2);\n\n\t\tif (op_iterator1 != operator_map.end() && op_iterator2 != operator_map.end())\n\t\t{\n\t\t\tif (op_iterator1->second.right_associative)\n\t\t\t{\n\t\t\t\tif (op_iterator1->second.precendence < op_iterator2->second.precendence)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tif (op_iterator1->second.precendence <= op_iterator2->second.precendence)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tbool enough_on_stack(std::stack<int> stack, int size)\n {\n if (stack.size() < size)\n {\n return false;\n }\n\t return true;\n }\n \n std::stack<int> process_operator(std::stack<int> num_stack, std::function<int (int val1, int val2)> expression)\n {\n if (enough_on_stack(num_stack, 2))\n {\n int val1 = num_stack.top();\n num_stack.pop();\n int val2 = num_stack.top();\n num_stack.pop();\n num_stack.push(expression(val1, val2));\n }\n else\n throw std::runtime_error(\"Not enough arguments for an operator\");\n return num_stack;\n\t}\n}\n<commit_msg>Inline 'enough on stack' function<commit_after>\/\/ Utility functions used for parsing and evaluating equations\n\/\/ William Immendorf - 2016\n\/\/ Compile with --std=c++11\n\n#include <stdexcept>\n#include <unordered_map>\n\n#include \"utility.hpp\"\n\nstruct operator_detail \n{\n\tint precendence;\n\tbool right_associative;\n};\n\nconst std::unordered_map<char, operator_detail> operator_map \n{\n\t{'+', {2, false}},\n\t{'-', {2, false}},\n\t{'*', {3, false}},\n\t{'\/', {3, false}},\n\t{'^', {4, true}}\n};\n\nnamespace EquParser\n{\n\tbool precendence_less_than(char op1, char op2)\n\t{\n\t\tauto op_iterator1 = operator_map.find(op1);\n\t\tauto op_iterator2 = operator_map.find(op2);\n\n\t\tif (op_iterator1 != operator_map.end() && op_iterator2 != operator_map.end())\n\t\t{\n\t\t\tif (op_iterator1->second.right_associative)\n\t\t\t{\n\t\t\t\tif (op_iterator1->second.precendence < op_iterator2->second.precendence)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tif (op_iterator1->second.precendence <= op_iterator2->second.precendence)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tinline bool enough_on_stack(std::stack<int> stack, int size)\n {\n if (stack.size() < size)\n {\n return false;\n }\n\t return true;\n }\n \n std::stack<int> process_operator(std::stack<int> num_stack, std::function<int (int val1, int val2)> expression)\n {\n if (enough_on_stack(num_stack, 2))\n {\n int val1 = num_stack.top();\n num_stack.pop();\n int val2 = num_stack.top();\n num_stack.pop();\n num_stack.push(expression(val1, val2));\n }\n else\n throw std::runtime_error(\"Not enough arguments for an operator\");\n return num_stack;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2000 by Jorrit Tyberghein\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 <stdarg.h>\n\n#include \"sysdef.h\"\n#include \"qint.h\"\n#include \"csgeom\/math2d.h\"\n#include \"csgeom\/math3d.h\"\n#include \"cs3d\/line\/line_g3d.h\"\n#include \"cs3d\/line\/line_txt.h\"\n#include \"cs3d\/common\/memheap.h\"\n#include \"csutil\/inifile.h\"\n#include \"ipolygon.h\"\n#include \"isystem.h\"\n#include \"igraph2d.h\"\n#include \"ilghtmap.h\"\n\n\/\/\/---------------------------------------------------------------------------\n\nIMPLEMENT_FACTORY (csGraphics3DLine)\n\nEXPORT_CLASS_TABLE (line3d)\n EXPORT_CLASS (csGraphics3DLine, \"crystalspace.graphics3d.line\",\n \"Line 3D graphics driver for Crystal Space\")\nEXPORT_CLASS_TABLE_END\n\nIMPLEMENT_IBASE (csGraphics3DLine)\n IMPLEMENTS_INTERFACE (iPlugIn)\n IMPLEMENTS_INTERFACE (iGraphics3D)\n IMPLEMENTS_EMBEDDED_INTERFACE (iConfig)\nIMPLEMENT_IBASE_END\n\n#if defined (OS_LINUX)\nchar* get_software_2d_driver ()\n{\n if (getenv (\"GGI_DISPLAY\"))\n return SOFTWARE_2D_DRIVER_GGI;\n else if (getenv (\"DISPLAY\"))\n return \"crystalspace.graphics2d.linexlib\";\n else\n return SOFTWARE_2D_DRIVER_SVGA;\n}\n#elif defined (OS_UNIX) && !defined (OS_BE)\n\/\/ by the way, other unices has SVGALib support too... through GGI ;-)\nchar* get_software_2d_driver ()\n{\n if (getenv (\"GGI_DISPLAY\"))\n return SOFTWARE_2D_DRIVER_GGI;\n else\n return \"crystalspace.graphics2d.linexlib\";\n}\n#endif\n\ncsGraphics3DLine::csGraphics3DLine (iBase *iParent) : G2D (NULL)\n{\n CONSTRUCT_IBASE (iParent);\n CONSTRUCT_EMBEDDED_IBASE (scfiConfig);\n\n config = new csIniFile (\"line3d.cfg\");\n\n txtmgr = NULL;\n}\n\ncsGraphics3DLine::~csGraphics3DLine ()\n{\n Close ();\n CHK (delete txtmgr);\n if (G2D)\n G2D->DecRef ();\n CHK (delete config;)\n}\n\nbool csGraphics3DLine::Initialize (iSystem *iSys)\n{\n System = iSys;\n\n width = height = -1;\n\n if (!System->RegisterDriver (\"iGraphics3D\", this))\n return false;\n\n const char *driver = config->GetStr (\"Hardware\", \"Driver2D\", SOFTWARE_2D_DRIVER);\n G2D = LOAD_PLUGIN (System, driver, iGraphics2D);\n if (!G2D)\n return false;\n\n CHK (txtmgr = new csTextureManagerLine (System, G2D));\n txtmgr->SetConfig (config);\n txtmgr->Initialize ();\n\n return true;\n}\n\nbool csGraphics3DLine::Open (const char *Title)\n{\n DrawMode = 0;\n\n if (!G2D->Open (Title))\n {\n SysPrintf (MSG_FATAL_ERROR, \"Error opening Graphics2D context.\");\n \/\/ set \"not opened\" flag\n width = height = -1;\n\n return false;\n }\n\n int nWidth = G2D->GetWidth ();\n int nHeight = G2D->GetHeight ();\n bool bFullScreen = G2D->GetFullScreen ();\n\n SetDimensions (nWidth, nHeight);\n\n SysPrintf (MSG_INITIALIZATION, \"Using %s mode %dx%d.\\n\",\n bFullScreen ? \"full screen\" : \"windowed\", width, height);\n\n z_buf_mode = CS_ZBUF_NONE;\n\n return true;\n}\n\nvoid csGraphics3DLine::Close()\n{\n if ((width == height) && (width == -1))\n return;\n\n G2D->Close ();\n width = height = -1;\n}\n\nvoid csGraphics3DLine::SetDimensions (int nwidth, int nheight)\n{\n width = nwidth;\n height = nheight;\n width2 = width\/2;\n height2 = height\/2;\n}\n\nvoid csGraphics3DLine::SetPerspectiveCenter (int x, int y)\n{\n width2 = x;\n height2 = y;\n}\n\nbool csGraphics3DLine::BeginDraw (int DrawFlags)\n{\n \/\/ if 2D graphics is not locked, lock it\n if ((DrawFlags & (CSDRAW_2DGRAPHICS | CSDRAW_3DGRAPHICS))\n && (!(DrawMode & (CSDRAW_2DGRAPHICS | CSDRAW_3DGRAPHICS))))\n {\n if (!G2D->BeginDraw())\n return false;\n }\n\n if (DrawFlags & CSDRAW_CLEARSCREEN)\n G2D->Clear (0);\n\n if (DrawFlags & CSDRAW_3DGRAPHICS)\n {\n G2D->Clear (0);\n }\n else if (DrawMode & CSDRAW_3DGRAPHICS)\n {\n }\n\n DrawMode = DrawFlags;\n\n return true;\n}\n\nvoid csGraphics3DLine::FinishDraw ()\n{\n if (DrawMode & (CSDRAW_2DGRAPHICS | CSDRAW_3DGRAPHICS))\n G2D->FinishDraw ();\n DrawMode = 0;\n}\n\nvoid csGraphics3DLine::Print (csRect *area)\n{\n G2D->Print (area);\n}\n\nvoid csGraphics3DLine::SetZBufMode (G3DZBufMode mode)\n{\n z_buf_mode = mode;\n}\n\nvoid csGraphics3DLine::DrawPolygon (G3DPolygonDP& poly)\n{\n if (poly.num < 3)\n return;\n int i;\n int color = txtmgr->FindRGB (255, 255, 255);\n for (i = 0 ; i < poly.num ; i++)\n {\n G2D->DrawLine (poly.vertices[i].sx, height-poly.vertices[i].sy,\n \tpoly.vertices[(i+1)%poly.num].sx, height-poly.vertices[(i+1)%poly.num].sy,\n\tcolor);\n }\n}\n\nvoid csGraphics3DLine::DrawPolygonFX (G3DPolygonDPFX& poly)\n{\n if (poly.num < 3)\n return;\n int i;\n int color = txtmgr->FindRGB (255, 0, 0);\n for (i = 0 ; i < poly.num ; i++)\n {\n G2D->DrawLine (poly.vertices[i].sx, height-poly.vertices[i].sy,\n \tpoly.vertices[(i+1)%poly.num].sx, height-poly.vertices[(i+1)%poly.num].sy,\n\tcolor);\n }\n}\n\nbool csGraphics3DLine::SetRenderState (G3D_RENDERSTATEOPTION op,\n long value)\n{\n switch (op)\n {\n case G3DRENDERSTATE_NOTHING:\n return true;\n case G3DRENDERSTATE_ZBUFFERTESTENABLE:\n if (value)\n {\n if (z_buf_mode == CS_ZBUF_TEST)\n return true;\n if (z_buf_mode == CS_ZBUF_NONE)\n z_buf_mode = CS_ZBUF_TEST;\n else if (z_buf_mode == CS_ZBUF_FILL)\n z_buf_mode = CS_ZBUF_USE;\n }\n else\n {\n if (z_buf_mode == CS_ZBUF_FILL)\n return true;\n if (z_buf_mode == CS_ZBUF_USE)\n z_buf_mode = CS_ZBUF_FILL;\n else if (z_buf_mode == CS_ZBUF_TEST)\n z_buf_mode = CS_ZBUF_NONE;\n }\n break;\n case G3DRENDERSTATE_ZBUFFERFILLENABLE:\n if (value)\n {\n if (z_buf_mode == CS_ZBUF_FILL)\n return true;\n if (z_buf_mode == CS_ZBUF_NONE)\n z_buf_mode = CS_ZBUF_FILL;\n else if (z_buf_mode == CS_ZBUF_TEST)\n z_buf_mode = CS_ZBUF_USE;\n }\n else\n {\n if (z_buf_mode == CS_ZBUF_TEST)\n return true;\n if (z_buf_mode == CS_ZBUF_USE)\n z_buf_mode = CS_ZBUF_TEST;\n else if (z_buf_mode == CS_ZBUF_FILL)\n z_buf_mode = CS_ZBUF_NONE;\n }\n break;\n default:\n return false;\n }\n\n return true;\n}\n\nlong csGraphics3DLine::GetRenderState (G3D_RENDERSTATEOPTION op)\n{\n switch (op)\n {\n case G3DRENDERSTATE_NOTHING:\n return 0;\n case G3DRENDERSTATE_ZBUFFERTESTENABLE:\n return (bool)(z_buf_mode & CS_ZBUF_TEST);\n case G3DRENDERSTATE_ZBUFFERFILLENABLE:\n return (bool)(z_buf_mode & CS_ZBUF_FILL);\n default:\n return 0;\n }\n}\n\nvoid csGraphics3DLine::GetCaps (G3D_CAPS *caps)\n{\n if (!caps)\n return;\n\n caps->ColorModel = G3DCOLORMODEL_RGB;\n caps->CanClip = false;\n caps->SupportsArbitraryMipMapping = true;\n caps->BitDepth = 8;\n caps->ZBufBitDepth = 32;\n caps->minTexHeight = 2;\n caps->minTexWidth = 2;\n caps->maxTexHeight = 1024;\n caps->maxTexWidth = 1024;\n caps->PrimaryCaps.RasterCaps = G3DRASTERCAPS_SUBPIXEL;\n caps->PrimaryCaps.canBlend = true;\n caps->PrimaryCaps.ShadeCaps = G3DRASTERCAPS_LIGHTMAP;\n caps->PrimaryCaps.PerspectiveCorrects = true;\n caps->PrimaryCaps.FilterCaps = G3D_FILTERCAPS((int)G3DFILTERCAPS_NEAREST | (int)G3DFILTERCAPS_MIPNEAREST);\n caps->fog = G3D_FOGMETHOD((int)G3DFOGMETHOD_NONE);\n}\n\nvoid csGraphics3DLine::DrawLine (csVector3& v1, csVector3& v2, float fov, int color)\n{\n if (v1.z < SMALL_Z && v2.z < SMALL_Z)\n return;\n\n float x1 = v1.x, y1 = v1.y, z1 = v1.z;\n float x2 = v2.x, y2 = v2.y, z2 = v2.z;\n\n if (z1 < SMALL_Z)\n {\n \/\/ x = t*(x2-x1)+x1;\n \/\/ y = t*(y2-y1)+y1;\n \/\/ z = t*(z2-z1)+z1;\n float t = (SMALL_Z-z1) \/ (z2-z1);\n x1 = t*(x2-x1)+x1;\n y1 = t*(y2-y1)+y1;\n z1 = SMALL_Z;\n }\n else if (z2 < SMALL_Z)\n {\n \/\/ x = t*(x2-x1)+x1;\n \/\/ y = t*(y2-y1)+y1;\n \/\/ z = t*(z2-z1)+z1;\n float t = (SMALL_Z-z1) \/ (z2-z1);\n x2 = t*(x2-x1)+x1;\n y2 = t*(y2-y1)+y1;\n z2 = SMALL_Z;\n }\n\n float iz1 = fov\/z1;\n int px1 = QInt (x1 * iz1 + (width\/2));\n int py1 = height - 1 - QInt (y1 * iz1 + (height\/2));\n float iz2 = fov\/z2;\n int px2 = QInt (x2 * iz2 + (width\/2));\n int py2 = height - 1 - QInt (y2 * iz2 + (height\/2));\n\n G2D->DrawLine (px1, py1, px2, py2, color);\n}\n\nvoid csGraphics3DLine::SysPrintf (int mode, char* szMsg, ...)\n{\n char buf[1024];\n va_list arg;\n\n va_start (arg, szMsg);\n vsprintf (buf, szMsg, arg);\n va_end (arg);\n\n System->Print (mode, buf);\n}\n\n\/\/---------------------------------------------------------------------------\n\nIMPLEMENT_EMBEDDED_IBASE (csGraphics3DLine::csLineConfig)\n IMPLEMENTS_INTERFACE (iConfig)\nIMPLEMENT_EMBEDDED_IBASE_END\n\n#define NUM_OPTIONS 1\n\nstatic const csOptionDescription config_options [NUM_OPTIONS] =\n{\n { 0, \"dummy\", \"Dummy\", CSVAR_BOOL },\n};\n\nbool csGraphics3DLine::csLineConfig::SetOption (int id, csVariant* value)\n{\n if (value->type != config_options[id].type)\n return false;\n switch (id)\n {\n case 0: break;\n default: return false;\n }\n return true;\n}\n\nbool csGraphics3DLine::csLineConfig::GetOption (int id, csVariant* value)\n{\n value->type = config_options[id].type;\n switch (id)\n {\n case 0: value->v.b = false; break;\n default: return false;\n }\n return true;\n}\n\nbool csGraphics3DLine::csLineConfig::GetOptionDescription\n (int idx, csOptionDescription* option)\n{\n if (idx < 0 || idx >= NUM_OPTIONS)\n return false;\n *option = config_options[idx];\n return true;\n}\n\n<commit_msg>Draw lines based on texture color.<commit_after>\/*\n Copyright (C) 2000 by Jorrit Tyberghein\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 <stdarg.h>\n\n#include \"sysdef.h\"\n#include \"qint.h\"\n#include \"csgeom\/math2d.h\"\n#include \"csgeom\/math3d.h\"\n#include \"cs3d\/line\/line_g3d.h\"\n#include \"cs3d\/line\/line_txt.h\"\n#include \"cs3d\/common\/memheap.h\"\n#include \"csutil\/inifile.h\"\n#include \"ipolygon.h\"\n#include \"isystem.h\"\n#include \"igraph2d.h\"\n#include \"ilghtmap.h\"\n\n\/\/\/---------------------------------------------------------------------------\n\nIMPLEMENT_FACTORY (csGraphics3DLine)\n\nEXPORT_CLASS_TABLE (line3d)\n EXPORT_CLASS (csGraphics3DLine, \"crystalspace.graphics3d.line\",\n \"Line 3D graphics driver for Crystal Space\")\nEXPORT_CLASS_TABLE_END\n\nIMPLEMENT_IBASE (csGraphics3DLine)\n IMPLEMENTS_INTERFACE (iPlugIn)\n IMPLEMENTS_INTERFACE (iGraphics3D)\n IMPLEMENTS_EMBEDDED_INTERFACE (iConfig)\nIMPLEMENT_IBASE_END\n\n#if defined (OS_LINUX)\nchar* get_software_2d_driver ()\n{\n if (getenv (\"GGI_DISPLAY\"))\n return SOFTWARE_2D_DRIVER_GGI;\n else if (getenv (\"DISPLAY\"))\n return \"crystalspace.graphics2d.linexlib\";\n else\n return SOFTWARE_2D_DRIVER_SVGA;\n}\n#elif defined (OS_UNIX) && !defined (OS_BE)\n\/\/ by the way, other unices has SVGALib support too... through GGI ;-)\nchar* get_software_2d_driver ()\n{\n if (getenv (\"GGI_DISPLAY\"))\n return SOFTWARE_2D_DRIVER_GGI;\n else\n return \"crystalspace.graphics2d.linexlib\";\n}\n#endif\n\ncsGraphics3DLine::csGraphics3DLine (iBase *iParent) : G2D (NULL)\n{\n CONSTRUCT_IBASE (iParent);\n CONSTRUCT_EMBEDDED_IBASE (scfiConfig);\n\n config = new csIniFile (\"line3d.cfg\");\n\n txtmgr = NULL;\n}\n\ncsGraphics3DLine::~csGraphics3DLine ()\n{\n Close ();\n CHK (delete txtmgr);\n if (G2D)\n G2D->DecRef ();\n CHK (delete config;)\n}\n\nbool csGraphics3DLine::Initialize (iSystem *iSys)\n{\n System = iSys;\n\n width = height = -1;\n\n if (!System->RegisterDriver (\"iGraphics3D\", this))\n return false;\n\n const char *driver = config->GetStr (\"Hardware\", \"Driver2D\", SOFTWARE_2D_DRIVER);\n G2D = LOAD_PLUGIN (System, driver, iGraphics2D);\n if (!G2D)\n return false;\n\n CHK (txtmgr = new csTextureManagerLine (System, G2D));\n txtmgr->SetConfig (config);\n txtmgr->Initialize ();\n\n return true;\n}\n\nbool csGraphics3DLine::Open (const char *Title)\n{\n DrawMode = 0;\n\n if (!G2D->Open (Title))\n {\n SysPrintf (MSG_FATAL_ERROR, \"Error opening Graphics2D context.\");\n \/\/ set \"not opened\" flag\n width = height = -1;\n\n return false;\n }\n\n int nWidth = G2D->GetWidth ();\n int nHeight = G2D->GetHeight ();\n bool bFullScreen = G2D->GetFullScreen ();\n\n SetDimensions (nWidth, nHeight);\n\n SysPrintf (MSG_INITIALIZATION, \"Using %s mode %dx%d.\\n\",\n bFullScreen ? \"full screen\" : \"windowed\", width, height);\n\n z_buf_mode = CS_ZBUF_NONE;\n\n return true;\n}\n\nvoid csGraphics3DLine::Close()\n{\n if ((width == height) && (width == -1))\n return;\n\n G2D->Close ();\n width = height = -1;\n}\n\nvoid csGraphics3DLine::SetDimensions (int nwidth, int nheight)\n{\n width = nwidth;\n height = nheight;\n width2 = width\/2;\n height2 = height\/2;\n}\n\nvoid csGraphics3DLine::SetPerspectiveCenter (int x, int y)\n{\n width2 = x;\n height2 = y;\n}\n\nbool csGraphics3DLine::BeginDraw (int DrawFlags)\n{\n \/\/ if 2D graphics is not locked, lock it\n if ((DrawFlags & (CSDRAW_2DGRAPHICS | CSDRAW_3DGRAPHICS))\n && (!(DrawMode & (CSDRAW_2DGRAPHICS | CSDRAW_3DGRAPHICS))))\n {\n if (!G2D->BeginDraw())\n return false;\n }\n\n if (DrawFlags & CSDRAW_CLEARSCREEN)\n G2D->Clear (0);\n\n if (DrawFlags & CSDRAW_3DGRAPHICS)\n {\n G2D->Clear (0);\n }\n else if (DrawMode & CSDRAW_3DGRAPHICS)\n {\n }\n\n DrawMode = DrawFlags;\n\n return true;\n}\n\nvoid csGraphics3DLine::FinishDraw ()\n{\n if (DrawMode & (CSDRAW_2DGRAPHICS | CSDRAW_3DGRAPHICS))\n G2D->FinishDraw ();\n DrawMode = 0;\n}\n\nvoid csGraphics3DLine::Print (csRect *area)\n{\n G2D->Print (area);\n}\n\nvoid csGraphics3DLine::SetZBufMode (G3DZBufMode mode)\n{\n z_buf_mode = mode;\n}\n\nvoid csGraphics3DLine::DrawPolygon (G3DPolygonDP& poly)\n{\n if (poly.num < 3)\n return;\n int i;\n int color = txtmgr->FindRGB (128+QInt (poly.flat_color_r*128),\n \t128+QInt (poly.flat_color_g*128), 128+QInt (poly.flat_color_b*128));\n for (i = 0 ; i < poly.num ; i++)\n {\n G2D->DrawLine (poly.vertices[i].sx, height-poly.vertices[i].sy,\n \tpoly.vertices[(i+1)%poly.num].sx, height-poly.vertices[(i+1)%poly.num].sy,\n\tcolor);\n }\n}\n\nvoid csGraphics3DLine::DrawPolygonFX (G3DPolygonDPFX& poly)\n{\n if (poly.num < 3)\n return;\n int i;\n int color = txtmgr->FindRGB (QInt (poly.flat_color_r*255),\n \tQInt (poly.flat_color_g*255), QInt (poly.flat_color_b*255));\n for (i = 0 ; i < poly.num ; i++)\n {\n G2D->DrawLine (poly.vertices[i].sx, height-poly.vertices[i].sy,\n \tpoly.vertices[(i+1)%poly.num].sx, height-poly.vertices[(i+1)%poly.num].sy,\n\tcolor);\n }\n}\n\nbool csGraphics3DLine::SetRenderState (G3D_RENDERSTATEOPTION op,\n long value)\n{\n switch (op)\n {\n case G3DRENDERSTATE_NOTHING:\n return true;\n case G3DRENDERSTATE_ZBUFFERTESTENABLE:\n if (value)\n {\n if (z_buf_mode == CS_ZBUF_TEST)\n return true;\n if (z_buf_mode == CS_ZBUF_NONE)\n z_buf_mode = CS_ZBUF_TEST;\n else if (z_buf_mode == CS_ZBUF_FILL)\n z_buf_mode = CS_ZBUF_USE;\n }\n else\n {\n if (z_buf_mode == CS_ZBUF_FILL)\n return true;\n if (z_buf_mode == CS_ZBUF_USE)\n z_buf_mode = CS_ZBUF_FILL;\n else if (z_buf_mode == CS_ZBUF_TEST)\n z_buf_mode = CS_ZBUF_NONE;\n }\n break;\n case G3DRENDERSTATE_ZBUFFERFILLENABLE:\n if (value)\n {\n if (z_buf_mode == CS_ZBUF_FILL)\n return true;\n if (z_buf_mode == CS_ZBUF_NONE)\n z_buf_mode = CS_ZBUF_FILL;\n else if (z_buf_mode == CS_ZBUF_TEST)\n z_buf_mode = CS_ZBUF_USE;\n }\n else\n {\n if (z_buf_mode == CS_ZBUF_TEST)\n return true;\n if (z_buf_mode == CS_ZBUF_USE)\n z_buf_mode = CS_ZBUF_TEST;\n else if (z_buf_mode == CS_ZBUF_FILL)\n z_buf_mode = CS_ZBUF_NONE;\n }\n break;\n default:\n return false;\n }\n\n return true;\n}\n\nlong csGraphics3DLine::GetRenderState (G3D_RENDERSTATEOPTION op)\n{\n switch (op)\n {\n case G3DRENDERSTATE_NOTHING:\n return 0;\n case G3DRENDERSTATE_ZBUFFERTESTENABLE:\n return (bool)(z_buf_mode & CS_ZBUF_TEST);\n case G3DRENDERSTATE_ZBUFFERFILLENABLE:\n return (bool)(z_buf_mode & CS_ZBUF_FILL);\n default:\n return 0;\n }\n}\n\nvoid csGraphics3DLine::GetCaps (G3D_CAPS *caps)\n{\n if (!caps)\n return;\n\n caps->ColorModel = G3DCOLORMODEL_RGB;\n caps->CanClip = false;\n caps->SupportsArbitraryMipMapping = true;\n caps->BitDepth = 8;\n caps->ZBufBitDepth = 32;\n caps->minTexHeight = 2;\n caps->minTexWidth = 2;\n caps->maxTexHeight = 1024;\n caps->maxTexWidth = 1024;\n caps->PrimaryCaps.RasterCaps = G3DRASTERCAPS_SUBPIXEL;\n caps->PrimaryCaps.canBlend = true;\n caps->PrimaryCaps.ShadeCaps = G3DRASTERCAPS_LIGHTMAP;\n caps->PrimaryCaps.PerspectiveCorrects = true;\n caps->PrimaryCaps.FilterCaps = G3D_FILTERCAPS((int)G3DFILTERCAPS_NEAREST | (int)G3DFILTERCAPS_MIPNEAREST);\n caps->fog = G3D_FOGMETHOD((int)G3DFOGMETHOD_NONE);\n}\n\nvoid csGraphics3DLine::DrawLine (csVector3& v1, csVector3& v2, float fov, int color)\n{\n if (v1.z < SMALL_Z && v2.z < SMALL_Z)\n return;\n\n float x1 = v1.x, y1 = v1.y, z1 = v1.z;\n float x2 = v2.x, y2 = v2.y, z2 = v2.z;\n\n if (z1 < SMALL_Z)\n {\n \/\/ x = t*(x2-x1)+x1;\n \/\/ y = t*(y2-y1)+y1;\n \/\/ z = t*(z2-z1)+z1;\n float t = (SMALL_Z-z1) \/ (z2-z1);\n x1 = t*(x2-x1)+x1;\n y1 = t*(y2-y1)+y1;\n z1 = SMALL_Z;\n }\n else if (z2 < SMALL_Z)\n {\n \/\/ x = t*(x2-x1)+x1;\n \/\/ y = t*(y2-y1)+y1;\n \/\/ z = t*(z2-z1)+z1;\n float t = (SMALL_Z-z1) \/ (z2-z1);\n x2 = t*(x2-x1)+x1;\n y2 = t*(y2-y1)+y1;\n z2 = SMALL_Z;\n }\n\n float iz1 = fov\/z1;\n int px1 = QInt (x1 * iz1 + (width\/2));\n int py1 = height - 1 - QInt (y1 * iz1 + (height\/2));\n float iz2 = fov\/z2;\n int px2 = QInt (x2 * iz2 + (width\/2));\n int py2 = height - 1 - QInt (y2 * iz2 + (height\/2));\n\n G2D->DrawLine (px1, py1, px2, py2, color);\n}\n\nvoid csGraphics3DLine::SysPrintf (int mode, char* szMsg, ...)\n{\n char buf[1024];\n va_list arg;\n\n va_start (arg, szMsg);\n vsprintf (buf, szMsg, arg);\n va_end (arg);\n\n System->Print (mode, buf);\n}\n\n\/\/---------------------------------------------------------------------------\n\nIMPLEMENT_EMBEDDED_IBASE (csGraphics3DLine::csLineConfig)\n IMPLEMENTS_INTERFACE (iConfig)\nIMPLEMENT_EMBEDDED_IBASE_END\n\n#define NUM_OPTIONS 1\n\nstatic const csOptionDescription config_options [NUM_OPTIONS] =\n{\n { 0, \"dummy\", \"Dummy\", CSVAR_BOOL },\n};\n\nbool csGraphics3DLine::csLineConfig::SetOption (int id, csVariant* value)\n{\n if (value->type != config_options[id].type)\n return false;\n switch (id)\n {\n case 0: break;\n default: return false;\n }\n return true;\n}\n\nbool csGraphics3DLine::csLineConfig::GetOption (int id, csVariant* value)\n{\n value->type = config_options[id].type;\n switch (id)\n {\n case 0: value->v.b = false; break;\n default: return false;\n }\n return true;\n}\n\nbool csGraphics3DLine::csLineConfig::GetOptionDescription\n (int idx, csOptionDescription* option)\n{\n if (idx < 0 || idx >= NUM_OPTIONS)\n return false;\n *option = config_options[idx];\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 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 \"net\/base\/tcp_client_socket.h\"\n\n#include \"base\/memory_debug.h\"\n#include \"base\/string_util.h\"\n#include \"base\/trace_event.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/winsock_init.h\"\n\nnamespace net {\n\n\/\/-----------------------------------------------------------------------------\n\nstatic int MapWinsockError(DWORD err) {\n \/\/ There are numerous Winsock error codes, but these are the ones we thus far\n \/\/ find interesting.\n switch (err) {\n case WSAENETDOWN:\n return ERR_INTERNET_DISCONNECTED;\n case WSAETIMEDOUT:\n return ERR_TIMED_OUT;\n case WSAECONNRESET:\n case WSAENETRESET: \/\/ Related to keep-alive\n return ERR_CONNECTION_RESET;\n case WSAECONNABORTED:\n return ERR_CONNECTION_ABORTED;\n case WSAECONNREFUSED:\n return ERR_CONNECTION_REFUSED;\n case WSAEDISCON:\n \/\/ Returned by WSARecv or WSARecvFrom for message-oriented sockets (where\n \/\/ a return value of zero means a zero-byte message) to indicate graceful\n \/\/ connection shutdown. We should not ever see this error code for TCP\n \/\/ sockets, which are byte stream oriented.\n NOTREACHED();\n return ERR_CONNECTION_CLOSED;\n case WSAEHOSTUNREACH:\n case WSAENETUNREACH:\n return ERR_ADDRESS_UNREACHABLE;\n case WSAEADDRNOTAVAIL:\n return ERR_ADDRESS_INVALID;\n case WSA_IO_INCOMPLETE:\n return ERR_UNEXPECTED;\n case ERROR_SUCCESS:\n return OK;\n default:\n LOG(WARNING) << \"Unknown error \" << err << \" mapped to net::ERR_FAILED\";\n return ERR_FAILED;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\nTCPClientSocket::TCPClientSocket(const AddressList& addresses)\n : socket_(INVALID_SOCKET),\n addresses_(addresses),\n current_ai_(addresses_.head()),\n wait_state_(NOT_WAITING),\n callback_(NULL) {\n memset(&overlapped_, 0, sizeof(overlapped_));\n EnsureWinsockInit();\n}\n\nTCPClientSocket::~TCPClientSocket() {\n Disconnect();\n}\n\nint TCPClientSocket::Connect(CompletionCallback* callback) {\n \/\/ If already connected, then just return OK.\n if (socket_ != INVALID_SOCKET)\n return OK;\n\n TRACE_EVENT_BEGIN(\"socket.connect\", this, \"\");\n const struct addrinfo* ai = current_ai_;\n DCHECK(ai);\n\n int rv = CreateSocket(ai);\n if (rv != OK)\n return rv;\n\n \/\/ WSACreateEvent creates a manual-reset event object.\n overlapped_.hEvent = WSACreateEvent();\n \/\/ WSAEventSelect sets the socket to non-blocking mode as a side effect.\n \/\/ Our connect() and recv() calls require that the socket be non-blocking.\n WSAEventSelect(socket_, overlapped_.hEvent, FD_CONNECT);\n\n if (!connect(socket_, ai->ai_addr, static_cast<int>(ai->ai_addrlen))) {\n \/\/ Connected without waiting!\n CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_OBJECT_0);\n BOOL ok = WSAResetEvent(overlapped_.hEvent);\n CHECK(ok);\n TRACE_EVENT_END(\"socket.connect\", this, \"\");\n return OK;\n }\n\n DWORD err = WSAGetLastError();\n if (err != WSAEWOULDBLOCK) {\n LOG(ERROR) << \"connect failed: \" << err;\n return MapWinsockError(err);\n }\n\n watcher_.StartWatching(overlapped_.hEvent, this);\n wait_state_ = WAITING_CONNECT;\n callback_ = callback;\n return ERR_IO_PENDING;\n}\n\nint TCPClientSocket::ReconnectIgnoringLastError(CompletionCallback* callback) {\n \/\/ No ignorable errors!\n return ERR_UNEXPECTED;\n}\n\nvoid TCPClientSocket::Disconnect() {\n if (socket_ == INVALID_SOCKET)\n return;\n\n TRACE_EVENT_INSTANT(\"socket.disconnect\", this, \"\");\n\n \/\/ Make sure the message loop is not watching this object anymore.\n watcher_.StopWatching();\n\n \/\/ Cancel any pending IO and wait for it to be aborted.\n if (wait_state_ == WAITING_READ || wait_state_ == WAITING_WRITE) {\n CancelIo(reinterpret_cast<HANDLE>(socket_));\n WaitForSingleObject(overlapped_.hEvent, INFINITE);\n wait_state_ = NOT_WAITING;\n }\n\n \/\/ In most socket implementations, closing a socket results in a graceful\n \/\/ connection shutdown, but in Winsock we have to call shutdown explicitly.\n \/\/ See the MSDN page \"Graceful Shutdown, Linger Options, and Socket Closure\"\n \/\/ at http:\/\/msdn.microsoft.com\/en-us\/library\/ms738547.aspx\n shutdown(socket_, SD_SEND);\n\n closesocket(socket_);\n socket_ = INVALID_SOCKET;\n\n WSACloseEvent(overlapped_.hEvent);\n memset(&overlapped_, 0, sizeof(overlapped_));\n\n \/\/ Reset for next time.\n current_ai_ = addresses_.head();\n}\n\nbool TCPClientSocket::IsConnected() const {\n if (socket_ == INVALID_SOCKET || wait_state_ == WAITING_CONNECT)\n return false;\n\n \/\/ Check if connection is alive.\n char c;\n int rv = recv(socket_, &c, 1, MSG_PEEK);\n if (rv == 0)\n return false;\n if (rv == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)\n return false;\n\n return true;\n}\n\nint TCPClientSocket::Read(char* buf,\n int buf_len,\n CompletionCallback* callback) {\n DCHECK(socket_ != INVALID_SOCKET);\n DCHECK(wait_state_ == NOT_WAITING);\n DCHECK(!callback_);\n\n buffer_.len = buf_len;\n buffer_.buf = buf;\n\n TRACE_EVENT_BEGIN(\"socket.read\", this, \"\");\n \/\/ TODO(wtc): Remove the CHECKs after enough testing.\n CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);\n DWORD num, flags = 0;\n int rv = WSARecv(socket_, &buffer_, 1, &num, &flags, &overlapped_, NULL);\n if (rv == 0) {\n CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_OBJECT_0);\n BOOL ok = WSAResetEvent(overlapped_.hEvent);\n CHECK(ok);\n TRACE_EVENT_END(\"socket.read\", this, StringPrintf(\"%d bytes\", num));\n\n \/\/ Because of how WSARecv fills memory when used asynchronously, Purify\n \/\/ isn't able to detect that it's been initialized, so it scans for 0xcd\n \/\/ in the buffer and reports UMRs (uninitialized memory reads) for those\n \/\/ individual bytes. We override that in PURIFY builds to avoid the false\n \/\/ error reports.\n \/\/ See bug 5297.\n base::MemoryDebug::MarkAsInitialized(buffer_.buf, num);\n return static_cast<int>(num);\n }\n int err = WSAGetLastError();\n if (err == WSA_IO_PENDING) {\n watcher_.StartWatching(overlapped_.hEvent, this);\n wait_state_ = WAITING_READ;\n callback_ = callback;\n return ERR_IO_PENDING;\n }\n return MapWinsockError(err);\n}\n\nint TCPClientSocket::Write(const char* buf,\n int buf_len,\n CompletionCallback* callback) {\n DCHECK(socket_ != INVALID_SOCKET);\n DCHECK(wait_state_ == NOT_WAITING);\n DCHECK(!callback_);\n\n buffer_.len = buf_len;\n buffer_.buf = const_cast<char*>(buf);\n\n TRACE_EVENT_BEGIN(\"socket.write\", this, \"\");\n \/\/ TODO(wtc): Remove the CHECKs after enough testing.\n CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);\n DWORD num;\n int rv = WSASend(socket_, &buffer_, 1, &num, 0, &overlapped_, NULL);\n if (rv == 0) {\n \/\/ TODO(wtc): These temporary CHECKs are intended to determine the return\n \/\/ value and error code of the WaitForSingleObject call if it doesn't\n \/\/ return the expected WAIT_OBJECT_0. See http:\/\/crbug.com\/6500.\n DWORD wait_rv = WaitForSingleObject(overlapped_.hEvent, 0);\n if (wait_rv != WAIT_OBJECT_0) {\n if (wait_rv == WAIT_ABANDONED) {\n CHECK(false);\n } else if (wait_rv == WAIT_TIMEOUT) {\n CHECK(false);\n } else if (wait_rv == WAIT_FAILED) {\n DWORD wait_error = GetLastError();\n if (wait_error == ERROR_INVALID_HANDLE) {\n CHECK(false);\n } else {\n CHECK(false);\n }\n } else {\n CHECK(false);\n }\n }\n BOOL ok = WSAResetEvent(overlapped_.hEvent);\n CHECK(ok);\n TRACE_EVENT_END(\"socket.write\", this, StringPrintf(\"%d bytes\", num));\n return static_cast<int>(num);\n }\n int err = WSAGetLastError();\n if (err == WSA_IO_PENDING) {\n watcher_.StartWatching(overlapped_.hEvent, this);\n wait_state_ = WAITING_WRITE;\n callback_ = callback;\n return ERR_IO_PENDING;\n }\n return MapWinsockError(err);\n}\n\nint TCPClientSocket::CreateSocket(const struct addrinfo* ai) {\n socket_ = WSASocket(ai->ai_family, ai->ai_socktype, ai->ai_protocol, NULL, 0,\n WSA_FLAG_OVERLAPPED);\n if (socket_ == INVALID_SOCKET) {\n DWORD err = WSAGetLastError();\n LOG(ERROR) << \"WSASocket failed: \" << err;\n return MapWinsockError(err);\n }\n\n \/\/ Increase the socket buffer sizes from the default sizes.\n \/\/ In performance testing, there is substantial benefit by increasing\n \/\/ from 8KB to 32KB. I tested 64, 128, and 256KB as well, but did not\n \/\/ see additional performance benefit (will be network dependent).\n \/\/ See also:\n \/\/ http:\/\/support.microsoft.com\/kb\/823764\/EN-US\n \/\/ On XP, the default buffer sizes are 8KB.\n const int kSocketBufferSize = 32 * 1024;\n int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,\n reinterpret_cast<const char*>(&kSocketBufferSize),\n sizeof(kSocketBufferSize));\n DCHECK(!rv) << \"Could not set socket send buffer size\";\n rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF,\n reinterpret_cast<const char*>(&kSocketBufferSize),\n sizeof(kSocketBufferSize));\n DCHECK(!rv) << \"Could not set socket receive buffer size\";\n\n \/\/ Disable Nagle.\n \/\/ The Nagle implementation on windows is governed by RFC 896. The idea\n \/\/ behind Nagle is to reduce small packets on the network. When Nagle is\n \/\/ enabled, if a partial packet has been sent, the TCP stack will disallow\n \/\/ further *partial* packets until an ACK has been received from the other\n \/\/ side. Good applications should always strive to send as much data as\n \/\/ possible and avoid partial-packet sends. However, in most real world\n \/\/ applications, there are edge cases where this does not happen, and two\n \/\/ partil packets may be sent back to back. For a browser, it is NEVER\n \/\/ a benefit to delay for an RTT before the second packet is sent.\n \/\/\n \/\/ As a practical example in Chromium today, consider the case of a small\n \/\/ POST. I have verified this:\n \/\/ Client writes 649 bytes of header (partial packet #1)\n \/\/ Client writes 50 bytes of POST data (partial packet #2)\n \/\/ In the above example, with Nagle, a RTT delay is inserted between these\n \/\/ two sends due to nagle. RTTs can easily be 100ms or more. The best\n \/\/ fix is to make sure that for POSTing data, we write as much data as\n \/\/ possible and minimize partial packets. We will fix that. But disabling\n \/\/ Nagle also ensure we don't run into this delay in other edge cases.\n \/\/ See also:\n \/\/ http:\/\/technet.microsoft.com\/en-us\/library\/bb726981.aspx\n const BOOL kDisableNagle = TRUE;\n rv = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY,\n reinterpret_cast<const char*>(&kDisableNagle), sizeof(kDisableNagle));\n DCHECK(!rv) << \"Could not disable nagle\";\n\n return OK;\n}\n\nvoid TCPClientSocket::DoCallback(int rv) {\n DCHECK(rv != ERR_IO_PENDING);\n DCHECK(callback_);\n\n \/\/ since Run may result in Read being called, clear callback_ up front.\n CompletionCallback* c = callback_;\n callback_ = NULL;\n c->Run(rv);\n}\n\nvoid TCPClientSocket::DidCompleteConnect() {\n int result;\n\n TRACE_EVENT_END(\"socket.connect\", this, \"\");\n wait_state_ = NOT_WAITING;\n\n WSANETWORKEVENTS events;\n int rv = WSAEnumNetworkEvents(socket_, overlapped_.hEvent, &events);\n if (rv == SOCKET_ERROR) {\n NOTREACHED();\n result = MapWinsockError(WSAGetLastError());\n } else if (events.lNetworkEvents & FD_CONNECT) {\n wait_state_ = NOT_WAITING;\n DWORD error_code = static_cast<DWORD>(events.iErrorCode[FD_CONNECT_BIT]);\n if (current_ai_->ai_next && (\n error_code == WSAEADDRNOTAVAIL ||\n error_code == WSAEAFNOSUPPORT ||\n error_code == WSAECONNREFUSED ||\n error_code == WSAENETUNREACH ||\n error_code == WSAEHOSTUNREACH ||\n error_code == WSAETIMEDOUT)) {\n \/\/ Try using the next address.\n const struct addrinfo* next = current_ai_->ai_next;\n Disconnect();\n current_ai_ = next;\n result = Connect(callback_);\n } else {\n result = MapWinsockError(error_code);\n }\n } else {\n NOTREACHED();\n result = ERR_UNEXPECTED;\n }\n\n if (result != ERR_IO_PENDING)\n DoCallback(result);\n}\n\nvoid TCPClientSocket::DidCompleteIO() {\n DWORD num_bytes, flags;\n BOOL ok = WSAGetOverlappedResult(\n socket_, &overlapped_, &num_bytes, FALSE, &flags);\n WSAResetEvent(overlapped_.hEvent);\n if (wait_state_ == WAITING_READ) {\n TRACE_EVENT_END(\"socket.read\", this, StringPrintf(\"%d bytes\", num_bytes));\n } else {\n TRACE_EVENT_END(\"socket.write\", this, StringPrintf(\"%d bytes\", num_bytes));\n }\n wait_state_ = NOT_WAITING;\n DoCallback(ok ? num_bytes : MapWinsockError(WSAGetLastError()));\n}\n\nvoid TCPClientSocket::OnObjectSignaled(HANDLE object) {\n DCHECK(object == overlapped_.hEvent);\n\n switch (wait_state_) {\n case WAITING_CONNECT:\n DidCompleteConnect();\n break;\n case WAITING_READ:\n case WAITING_WRITE:\n DidCompleteIO();\n break;\n default:\n NOTREACHED();\n break;\n }\n}\n\n} \/\/ namespace net\n\n<commit_msg>Add a dummy function CrashBug6500 so that the return value and error code of the WaitForSingleObject call are captured as function arguments in the crash dumps.<commit_after>\/\/ Copyright (c) 2006-2008 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 \"net\/base\/tcp_client_socket.h\"\n\n#include \"base\/memory_debug.h\"\n#include \"base\/string_util.h\"\n#include \"base\/trace_event.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/winsock_init.h\"\n\nnamespace net {\n\n\/\/-----------------------------------------------------------------------------\n\nstatic int MapWinsockError(DWORD err) {\n \/\/ There are numerous Winsock error codes, but these are the ones we thus far\n \/\/ find interesting.\n switch (err) {\n case WSAENETDOWN:\n return ERR_INTERNET_DISCONNECTED;\n case WSAETIMEDOUT:\n return ERR_TIMED_OUT;\n case WSAECONNRESET:\n case WSAENETRESET: \/\/ Related to keep-alive\n return ERR_CONNECTION_RESET;\n case WSAECONNABORTED:\n return ERR_CONNECTION_ABORTED;\n case WSAECONNREFUSED:\n return ERR_CONNECTION_REFUSED;\n case WSAEDISCON:\n \/\/ Returned by WSARecv or WSARecvFrom for message-oriented sockets (where\n \/\/ a return value of zero means a zero-byte message) to indicate graceful\n \/\/ connection shutdown. We should not ever see this error code for TCP\n \/\/ sockets, which are byte stream oriented.\n NOTREACHED();\n return ERR_CONNECTION_CLOSED;\n case WSAEHOSTUNREACH:\n case WSAENETUNREACH:\n return ERR_ADDRESS_UNREACHABLE;\n case WSAEADDRNOTAVAIL:\n return ERR_ADDRESS_INVALID;\n case WSA_IO_INCOMPLETE:\n return ERR_UNEXPECTED;\n case ERROR_SUCCESS:\n return OK;\n default:\n LOG(WARNING) << \"Unknown error \" << err << \" mapped to net::ERR_FAILED\";\n return ERR_FAILED;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\nTCPClientSocket::TCPClientSocket(const AddressList& addresses)\n : socket_(INVALID_SOCKET),\n addresses_(addresses),\n current_ai_(addresses_.head()),\n wait_state_(NOT_WAITING),\n callback_(NULL) {\n memset(&overlapped_, 0, sizeof(overlapped_));\n EnsureWinsockInit();\n}\n\nTCPClientSocket::~TCPClientSocket() {\n Disconnect();\n}\n\nint TCPClientSocket::Connect(CompletionCallback* callback) {\n \/\/ If already connected, then just return OK.\n if (socket_ != INVALID_SOCKET)\n return OK;\n\n TRACE_EVENT_BEGIN(\"socket.connect\", this, \"\");\n const struct addrinfo* ai = current_ai_;\n DCHECK(ai);\n\n int rv = CreateSocket(ai);\n if (rv != OK)\n return rv;\n\n \/\/ WSACreateEvent creates a manual-reset event object.\n overlapped_.hEvent = WSACreateEvent();\n \/\/ WSAEventSelect sets the socket to non-blocking mode as a side effect.\n \/\/ Our connect() and recv() calls require that the socket be non-blocking.\n WSAEventSelect(socket_, overlapped_.hEvent, FD_CONNECT);\n\n if (!connect(socket_, ai->ai_addr, static_cast<int>(ai->ai_addrlen))) {\n \/\/ Connected without waiting!\n CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_OBJECT_0);\n BOOL ok = WSAResetEvent(overlapped_.hEvent);\n CHECK(ok);\n TRACE_EVENT_END(\"socket.connect\", this, \"\");\n return OK;\n }\n\n DWORD err = WSAGetLastError();\n if (err != WSAEWOULDBLOCK) {\n LOG(ERROR) << \"connect failed: \" << err;\n return MapWinsockError(err);\n }\n\n watcher_.StartWatching(overlapped_.hEvent, this);\n wait_state_ = WAITING_CONNECT;\n callback_ = callback;\n return ERR_IO_PENDING;\n}\n\nint TCPClientSocket::ReconnectIgnoringLastError(CompletionCallback* callback) {\n \/\/ No ignorable errors!\n return ERR_UNEXPECTED;\n}\n\nvoid TCPClientSocket::Disconnect() {\n if (socket_ == INVALID_SOCKET)\n return;\n\n TRACE_EVENT_INSTANT(\"socket.disconnect\", this, \"\");\n\n \/\/ Make sure the message loop is not watching this object anymore.\n watcher_.StopWatching();\n\n \/\/ Cancel any pending IO and wait for it to be aborted.\n if (wait_state_ == WAITING_READ || wait_state_ == WAITING_WRITE) {\n CancelIo(reinterpret_cast<HANDLE>(socket_));\n WaitForSingleObject(overlapped_.hEvent, INFINITE);\n wait_state_ = NOT_WAITING;\n }\n\n \/\/ In most socket implementations, closing a socket results in a graceful\n \/\/ connection shutdown, but in Winsock we have to call shutdown explicitly.\n \/\/ See the MSDN page \"Graceful Shutdown, Linger Options, and Socket Closure\"\n \/\/ at http:\/\/msdn.microsoft.com\/en-us\/library\/ms738547.aspx\n shutdown(socket_, SD_SEND);\n\n closesocket(socket_);\n socket_ = INVALID_SOCKET;\n\n WSACloseEvent(overlapped_.hEvent);\n memset(&overlapped_, 0, sizeof(overlapped_));\n\n \/\/ Reset for next time.\n current_ai_ = addresses_.head();\n}\n\nbool TCPClientSocket::IsConnected() const {\n if (socket_ == INVALID_SOCKET || wait_state_ == WAITING_CONNECT)\n return false;\n\n \/\/ Check if connection is alive.\n char c;\n int rv = recv(socket_, &c, 1, MSG_PEEK);\n if (rv == 0)\n return false;\n if (rv == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)\n return false;\n\n return true;\n}\n\nint TCPClientSocket::Read(char* buf,\n int buf_len,\n CompletionCallback* callback) {\n DCHECK(socket_ != INVALID_SOCKET);\n DCHECK(wait_state_ == NOT_WAITING);\n DCHECK(!callback_);\n\n buffer_.len = buf_len;\n buffer_.buf = buf;\n\n TRACE_EVENT_BEGIN(\"socket.read\", this, \"\");\n \/\/ TODO(wtc): Remove the CHECKs after enough testing.\n CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);\n DWORD num, flags = 0;\n int rv = WSARecv(socket_, &buffer_, 1, &num, &flags, &overlapped_, NULL);\n if (rv == 0) {\n CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_OBJECT_0);\n BOOL ok = WSAResetEvent(overlapped_.hEvent);\n CHECK(ok);\n TRACE_EVENT_END(\"socket.read\", this, StringPrintf(\"%d bytes\", num));\n\n \/\/ Because of how WSARecv fills memory when used asynchronously, Purify\n \/\/ isn't able to detect that it's been initialized, so it scans for 0xcd\n \/\/ in the buffer and reports UMRs (uninitialized memory reads) for those\n \/\/ individual bytes. We override that in PURIFY builds to avoid the false\n \/\/ error reports.\n \/\/ See bug 5297.\n base::MemoryDebug::MarkAsInitialized(buffer_.buf, num);\n return static_cast<int>(num);\n }\n int err = WSAGetLastError();\n if (err == WSA_IO_PENDING) {\n watcher_.StartWatching(overlapped_.hEvent, this);\n wait_state_ = WAITING_READ;\n callback_ = callback;\n return ERR_IO_PENDING;\n }\n return MapWinsockError(err);\n}\n\n\/\/ TODO(wtc): This temporary function is intended to determine the return\n\/\/ value and error code of the WaitForSingleObject call in\n\/\/ TCPClientSocket::Write if it doesn't return the expected WAIT_OBJECT_0.\n\/\/ See http:\/\/crbug.com\/6500.\nstatic void CrashBug6500(DWORD wait_rv, DWORD wait_error) {\n \/\/ wait_error is meaningful only if wait_rv is WAIT_FAILED.\n CHECK(false) << wait_rv << wait_error;\n}\n\nint TCPClientSocket::Write(const char* buf,\n int buf_len,\n CompletionCallback* callback) {\n DCHECK(socket_ != INVALID_SOCKET);\n DCHECK(wait_state_ == NOT_WAITING);\n DCHECK(!callback_);\n\n buffer_.len = buf_len;\n buffer_.buf = const_cast<char*>(buf);\n\n TRACE_EVENT_BEGIN(\"socket.write\", this, \"\");\n \/\/ TODO(wtc): Remove the CHECKs after enough testing.\n CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);\n DWORD num;\n int rv = WSASend(socket_, &buffer_, 1, &num, 0, &overlapped_, NULL);\n if (rv == 0) {\n DWORD wait_rv = WaitForSingleObject(overlapped_.hEvent, 0);\n if (wait_rv != WAIT_OBJECT_0) {\n DWORD wait_error = GetLastError();\n CrashBug6500(wait_rv, wait_error);\n }\n BOOL ok = WSAResetEvent(overlapped_.hEvent);\n CHECK(ok);\n TRACE_EVENT_END(\"socket.write\", this, StringPrintf(\"%d bytes\", num));\n return static_cast<int>(num);\n }\n int err = WSAGetLastError();\n if (err == WSA_IO_PENDING) {\n watcher_.StartWatching(overlapped_.hEvent, this);\n wait_state_ = WAITING_WRITE;\n callback_ = callback;\n return ERR_IO_PENDING;\n }\n return MapWinsockError(err);\n}\n\nint TCPClientSocket::CreateSocket(const struct addrinfo* ai) {\n socket_ = WSASocket(ai->ai_family, ai->ai_socktype, ai->ai_protocol, NULL, 0,\n WSA_FLAG_OVERLAPPED);\n if (socket_ == INVALID_SOCKET) {\n DWORD err = WSAGetLastError();\n LOG(ERROR) << \"WSASocket failed: \" << err;\n return MapWinsockError(err);\n }\n\n \/\/ Increase the socket buffer sizes from the default sizes.\n \/\/ In performance testing, there is substantial benefit by increasing\n \/\/ from 8KB to 32KB. I tested 64, 128, and 256KB as well, but did not\n \/\/ see additional performance benefit (will be network dependent).\n \/\/ See also:\n \/\/ http:\/\/support.microsoft.com\/kb\/823764\/EN-US\n \/\/ On XP, the default buffer sizes are 8KB.\n const int kSocketBufferSize = 32 * 1024;\n int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,\n reinterpret_cast<const char*>(&kSocketBufferSize),\n sizeof(kSocketBufferSize));\n DCHECK(!rv) << \"Could not set socket send buffer size\";\n rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF,\n reinterpret_cast<const char*>(&kSocketBufferSize),\n sizeof(kSocketBufferSize));\n DCHECK(!rv) << \"Could not set socket receive buffer size\";\n\n \/\/ Disable Nagle.\n \/\/ The Nagle implementation on windows is governed by RFC 896. The idea\n \/\/ behind Nagle is to reduce small packets on the network. When Nagle is\n \/\/ enabled, if a partial packet has been sent, the TCP stack will disallow\n \/\/ further *partial* packets until an ACK has been received from the other\n \/\/ side. Good applications should always strive to send as much data as\n \/\/ possible and avoid partial-packet sends. However, in most real world\n \/\/ applications, there are edge cases where this does not happen, and two\n \/\/ partil packets may be sent back to back. For a browser, it is NEVER\n \/\/ a benefit to delay for an RTT before the second packet is sent.\n \/\/\n \/\/ As a practical example in Chromium today, consider the case of a small\n \/\/ POST. I have verified this:\n \/\/ Client writes 649 bytes of header (partial packet #1)\n \/\/ Client writes 50 bytes of POST data (partial packet #2)\n \/\/ In the above example, with Nagle, a RTT delay is inserted between these\n \/\/ two sends due to nagle. RTTs can easily be 100ms or more. The best\n \/\/ fix is to make sure that for POSTing data, we write as much data as\n \/\/ possible and minimize partial packets. We will fix that. But disabling\n \/\/ Nagle also ensure we don't run into this delay in other edge cases.\n \/\/ See also:\n \/\/ http:\/\/technet.microsoft.com\/en-us\/library\/bb726981.aspx\n const BOOL kDisableNagle = TRUE;\n rv = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY,\n reinterpret_cast<const char*>(&kDisableNagle), sizeof(kDisableNagle));\n DCHECK(!rv) << \"Could not disable nagle\";\n\n return OK;\n}\n\nvoid TCPClientSocket::DoCallback(int rv) {\n DCHECK(rv != ERR_IO_PENDING);\n DCHECK(callback_);\n\n \/\/ since Run may result in Read being called, clear callback_ up front.\n CompletionCallback* c = callback_;\n callback_ = NULL;\n c->Run(rv);\n}\n\nvoid TCPClientSocket::DidCompleteConnect() {\n int result;\n\n TRACE_EVENT_END(\"socket.connect\", this, \"\");\n wait_state_ = NOT_WAITING;\n\n WSANETWORKEVENTS events;\n int rv = WSAEnumNetworkEvents(socket_, overlapped_.hEvent, &events);\n if (rv == SOCKET_ERROR) {\n NOTREACHED();\n result = MapWinsockError(WSAGetLastError());\n } else if (events.lNetworkEvents & FD_CONNECT) {\n wait_state_ = NOT_WAITING;\n DWORD error_code = static_cast<DWORD>(events.iErrorCode[FD_CONNECT_BIT]);\n if (current_ai_->ai_next && (\n error_code == WSAEADDRNOTAVAIL ||\n error_code == WSAEAFNOSUPPORT ||\n error_code == WSAECONNREFUSED ||\n error_code == WSAENETUNREACH ||\n error_code == WSAEHOSTUNREACH ||\n error_code == WSAETIMEDOUT)) {\n \/\/ Try using the next address.\n const struct addrinfo* next = current_ai_->ai_next;\n Disconnect();\n current_ai_ = next;\n result = Connect(callback_);\n } else {\n result = MapWinsockError(error_code);\n }\n } else {\n NOTREACHED();\n result = ERR_UNEXPECTED;\n }\n\n if (result != ERR_IO_PENDING)\n DoCallback(result);\n}\n\nvoid TCPClientSocket::DidCompleteIO() {\n DWORD num_bytes, flags;\n BOOL ok = WSAGetOverlappedResult(\n socket_, &overlapped_, &num_bytes, FALSE, &flags);\n WSAResetEvent(overlapped_.hEvent);\n if (wait_state_ == WAITING_READ) {\n TRACE_EVENT_END(\"socket.read\", this, StringPrintf(\"%d bytes\", num_bytes));\n } else {\n TRACE_EVENT_END(\"socket.write\", this, StringPrintf(\"%d bytes\", num_bytes));\n }\n wait_state_ = NOT_WAITING;\n DoCallback(ok ? num_bytes : MapWinsockError(WSAGetLastError()));\n}\n\nvoid TCPClientSocket::OnObjectSignaled(HANDLE object) {\n DCHECK(object == overlapped_.hEvent);\n\n switch (wait_state_) {\n case WAITING_CONNECT:\n DidCompleteConnect();\n break;\n case WAITING_READ:\n case WAITING_WRITE:\n DidCompleteIO();\n break;\n default:\n NOTREACHED();\n break;\n }\n}\n\n} \/\/ namespace net\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS layoutmanager (1.1.2); FILE ADDED 2004\/01\/19 13:12:05 cd 1.1.2.1: #111899# Moved xml load\/store classes to own sub folder<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2003 MySQL AB\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; 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. 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, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#define DBTUP_C\n#include \"Dbtup.hpp\"\n#include <RefConvert.hpp>\n#include <ndb_limits.h>\n#include <pc.hpp>\n\n#define ljam() { jamLine(9000 + __LINE__); }\n#define ljamEntry() { jamEntryLine(9000 + __LINE__); }\n\nvoid Dbtup::freeAllAttrBuffers(Operationrec* const regOperPtr)\n{\n if (regOperPtr->storedProcedureId == RNIL) {\n ljam();\n freeAttrinbufrec(regOperPtr->firstAttrinbufrec);\n } else {\n ljam();\n StoredProcPtr storedPtr;\n c_storedProcPool.getPtr(storedPtr, (Uint32)regOperPtr->storedProcedureId);\n ndbrequire(storedPtr.p->storedCode == ZSCAN_PROCEDURE);\n storedPtr.p->storedCounter--;\n regOperPtr->storedProcedureId = ZNIL;\n }\/\/if\n regOperPtr->firstAttrinbufrec = RNIL;\n regOperPtr->lastAttrinbufrec = RNIL;\n}\/\/Dbtup::freeAllAttrBuffers()\n\nvoid Dbtup::freeAttrinbufrec(Uint32 anAttrBuf) \n{\n Uint32 Ttemp;\n AttrbufrecPtr localAttrBufPtr;\n Uint32 RnoFree = cnoFreeAttrbufrec;\n localAttrBufPtr.i = anAttrBuf;\n while (localAttrBufPtr.i != RNIL) {\n ljam();\n ptrCheckGuard(localAttrBufPtr, cnoOfAttrbufrec, attrbufrec);\n Ttemp = localAttrBufPtr.p->attrbuf[ZBUF_NEXT];\n localAttrBufPtr.p->attrbuf[ZBUF_NEXT] = cfirstfreeAttrbufrec;\n cfirstfreeAttrbufrec = localAttrBufPtr.i;\n localAttrBufPtr.i = Ttemp;\n RnoFree++;\n }\/\/if\n cnoFreeAttrbufrec = RnoFree;\n}\/\/Dbtup::freeAttrinbufrec()\n\n\/**\n * Abort abort this operation and all after (nextActiveOp's)\n *\/\nvoid Dbtup::execTUP_ABORTREQ(Signal* signal) \n{\n ljamEntry();\n do_tup_abortreq(signal, 0);\n}\n\nvoid Dbtup::do_tup_abortreq(Signal* signal, Uint32 flags)\n{\n OperationrecPtr regOperPtr;\n FragrecordPtr regFragPtr;\n TablerecPtr regTabPtr;\n\n regOperPtr.i = signal->theData[0];\n c_operation_pool.getPtr(regOperPtr);\n TransState trans_state= get_trans_state(regOperPtr.p);\n ndbrequire((trans_state == TRANS_STARTED) ||\n (trans_state == TRANS_TOO_MUCH_AI) ||\n (trans_state == TRANS_ERROR_WAIT_TUPKEYREQ) ||\n (trans_state == TRANS_IDLE));\n if (regOperPtr.p->op_struct.op_type == ZREAD) {\n ljam();\n freeAllAttrBuffers(regOperPtr.p);\n initOpConnection(regOperPtr.p);\n return;\n }\/\/if\n\n regFragPtr.i = regOperPtr.p->fragmentPtr;\n ptrCheckGuard(regFragPtr, cnoOfFragrec, fragrecord);\n\n regTabPtr.i = regFragPtr.p->fragTableId;\n ptrCheckGuard(regTabPtr, cnoOfTablerec, tablerec);\n\n if (get_tuple_state(regOperPtr.p) == TUPLE_PREPARED)\n {\n ljam();\n if (!regTabPtr.p->tuxCustomTriggers.isEmpty() &&\n (flags & ZSKIP_TUX_TRIGGERS) == 0)\n executeTuxAbortTriggers(signal,\n\t\t\t regOperPtr.p,\n\t\t\t regFragPtr.p,\n\t\t\t regTabPtr.p);\n \n OperationrecPtr loopOpPtr;\n loopOpPtr.i = regOperPtr.p->nextActiveOp;\n while (loopOpPtr.i != RNIL) {\n ljam();\n c_operation_pool.getPtr(loopOpPtr);\n if (get_tuple_state(loopOpPtr.p) != TUPLE_ALREADY_ABORTED &&\n\t !regTabPtr.p->tuxCustomTriggers.isEmpty() &&\n (flags & ZSKIP_TUX_TRIGGERS) == 0) {\n ljam();\n executeTuxAbortTriggers(signal,\n loopOpPtr.p,\n regFragPtr.p,\n regTabPtr.p);\n }\n set_tuple_state(loopOpPtr.p, TUPLE_ALREADY_ABORTED); \n loopOpPtr.i = loopOpPtr.p->nextActiveOp;\n }\n }\n\n PagePtr page;\n Tuple_header *tuple_ptr= (Tuple_header*)\n get_ptr(&page, ®OperPtr.p->m_tuple_location, regTabPtr.p);\n\n Uint32 bits= tuple_ptr->m_header_bits; \n if(regOperPtr.p->op_struct.op_type != ZDELETE)\n {\n Tuple_header *copy= (Tuple_header*)\n c_undo_buffer.get_ptr(®OperPtr.p->m_copy_tuple_location);\n \n if(regOperPtr.p->op_struct.m_disk_preallocated)\n {\n jam();\n Local_key key;\n memcpy(&key, copy->get_disk_ref_ptr(regTabPtr.p), sizeof(key));\n disk_page_abort_prealloc(signal, regFragPtr.p, &key, key.m_page_idx);\n }\n \n\n Uint32 copy_bits= copy->m_header_bits;\n if(! (bits & Tuple_header::ALLOC))\n {\n if(copy_bits & Tuple_header::MM_GROWN)\n {\n\tndbout_c(\"abort grow\");\n\tPtr<Page> vpage;\n\tUint32 idx= regOperPtr.p->m_tuple_location.m_page_idx;\n\tUint32 mm_vars= regTabPtr.p->m_attributes[MM].m_no_of_varsize;\n\tUint32 *var_part;\n\n\tndbassert(tuple_ptr->m_header_bits & Tuple_header::CHAINED_ROW);\n\t\n\tUint32 ref= * tuple_ptr->get_var_part_ptr(regTabPtr.p);\n\tLocal_key tmp; \n\ttmp.assref(ref); \n\t\n\tidx= tmp.m_page_idx;\n\tvar_part= get_ptr(&vpage, *(Var_part_ref*)&ref);\n\tVar_page* pageP = (Var_page*)vpage.p;\n\tUint32 len= pageP->get_entry_len(idx) & ~Var_page::CHAIN;\n\tUint32 sz = ((((mm_vars + 1) << 1) + (((Uint16*)var_part)[mm_vars]) + 3)>> 2);\n\tndbassert(sz <= len);\n\tpageP->shrink_entry(idx, sz);\n\tupdate_free_page_list(regFragPtr.p, vpage);\n } \n else if(bits & Tuple_header::MM_SHRINK)\n {\n\tndbout_c(\"abort shrink\");\n }\n }\n else if (regOperPtr.p->is_first_operation() && \n\t regOperPtr.p->is_last_operation())\n {\n \/**\n * Aborting last operation that performed ALLOC\n *\/\n tuple_ptr->m_header_bits &= ~(Uint32)Tuple_header::ALLOC;\n tuple_ptr->m_header_bits |= Tuple_header::FREED;\n }\n }\n else if (regOperPtr.p->is_first_operation() && \n\t regOperPtr.p->is_last_operation())\n {\n if (bits & Tuple_header::ALLOC)\n {\n tuple_ptr->m_header_bits &= ~(Uint32)Tuple_header::ALLOC;\n tuple_ptr->m_header_bits |= Tuple_header::FREED;\n }\n }\n \n if(regOperPtr.p->is_first_operation() && regOperPtr.p->is_last_operation())\n {\n if (regOperPtr.p->m_undo_buffer_space)\n c_lgman->free_log_space(regFragPtr.p->m_logfile_group_id, \n\t\t\t regOperPtr.p->m_undo_buffer_space);\n }\n\n removeActiveOpList(regOperPtr.p, tuple_ptr);\n initOpConnection(regOperPtr.p);\n}\n\n\/* **************************************************************** *\/\n\/* ********************** TRANSACTION ERROR MODULE **************** *\/\n\/* **************************************************************** *\/\nint Dbtup::TUPKEY_abort(Signal* signal, int error_type)\n{\n switch(error_type) {\n case 1:\n\/\/tmupdate_alloc_error:\n terrorCode= ZMEM_NOMEM_ERROR;\n ljam();\n break;\n\n case 15:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 16:\n ljam();\n terrorCode = ZTRY_TO_UPDATE_ERROR;\n break;\n\n case 17:\n ljam();\n terrorCode = ZNO_ILLEGAL_NULL_ATTR;\n break;\n\n case 19:\n ljam();\n terrorCode = ZTRY_TO_UPDATE_ERROR;\n break;\n\n case 20:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 22:\n ljam();\n terrorCode = ZTOTAL_LEN_ERROR;\n break;\n\n case 23:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 24:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 26:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 27:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 28:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 29:\n ljam();\n break;\n\n case 30:\n ljam();\n terrorCode = ZCALL_ERROR;\n break;\n\n case 31:\n ljam();\n terrorCode = ZSTACK_OVERFLOW_ERROR;\n break;\n\n case 32:\n ljam();\n terrorCode = ZSTACK_UNDERFLOW_ERROR;\n break;\n\n case 33:\n ljam();\n terrorCode = ZNO_INSTRUCTION_ERROR;\n break;\n\n case 34:\n ljam();\n terrorCode = ZOUTSIDE_OF_PROGRAM_ERROR;\n break;\n\n case 35:\n ljam();\n terrorCode = ZTOO_MANY_INSTRUCTIONS_ERROR;\n break;\n\n case 38:\n ljam();\n terrorCode = ZTEMPORARY_RESOURCE_FAILURE;\n break;\n\n case 39:\n if (get_trans_state(operPtr.p) == TRANS_TOO_MUCH_AI) {\n ljam();\n terrorCode = ZTOO_MUCH_ATTRINFO_ERROR;\n } else if (get_trans_state(operPtr.p) == TRANS_ERROR_WAIT_TUPKEYREQ) {\n ljam();\n terrorCode = ZSEIZE_ATTRINBUFREC_ERROR;\n } else {\n ndbrequire(false);\n }\/\/if\n break;\n default:\n ndbrequire(false);\n break;\n }\/\/switch\n tupkeyErrorLab(signal);\n return -1;\n}\n\nvoid Dbtup::early_tupkey_error(Signal* signal)\n{\n Operationrec * const regOperPtr = operPtr.p;\n ndbrequire(!regOperPtr->op_struct.in_active_list);\n set_trans_state(regOperPtr, TRANS_IDLE);\n set_tuple_state(regOperPtr, TUPLE_PREPARED);\n initOpConnection(regOperPtr);\n send_TUPKEYREF(signal, regOperPtr);\n}\n\nvoid Dbtup::tupkeyErrorLab(Signal* signal) \n{\n Operationrec * const regOperPtr = operPtr.p;\n set_trans_state(regOperPtr, TRANS_IDLE);\n set_tuple_state(regOperPtr, TUPLE_PREPARED);\n\n FragrecordPtr fragPtr;\n fragPtr.i= regOperPtr->fragmentPtr;\n ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord);\n\n TablerecPtr tabPtr;\n tabPtr.i= fragPtr.p->fragTableId;\n ptrCheckGuard(tabPtr, cnoOfTablerec, tablerec);\n\n if (regOperPtr->m_undo_buffer_space)\n {\n c_lgman->free_log_space(fragPtr.p->m_logfile_group_id, \n\t\t\t regOperPtr->m_undo_buffer_space);\n }\n\n Uint32 *ptr = 0;\n if (!regOperPtr->m_tuple_location.isNull())\n {\n PagePtr tmp;\n ptr= get_ptr(&tmp, ®OperPtr->m_tuple_location, tabPtr.p);\n }\n\n\n removeActiveOpList(regOperPtr, (Tuple_header*)ptr);\n initOpConnection(regOperPtr);\n send_TUPKEYREF(signal, regOperPtr);\n}\n\nvoid Dbtup::send_TUPKEYREF(Signal* signal,\n Operationrec* const regOperPtr)\n{\n TupKeyRef * const tupKeyRef = (TupKeyRef *)signal->getDataPtrSend(); \n tupKeyRef->userRef = regOperPtr->userpointer;\n tupKeyRef->errorCode = terrorCode;\n sendSignal(DBLQH_REF, GSN_TUPKEYREF, signal, \n TupKeyRef::SignalLength, JBB);\n}\n\n<commit_msg>ndb - bug#23430 make sure not to release log buffer twice (or several times) in case of abort of multi update<commit_after>\/* Copyright (C) 2003 MySQL AB\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; 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. 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, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#define DBTUP_C\n#include \"Dbtup.hpp\"\n#include <RefConvert.hpp>\n#include <ndb_limits.h>\n#include <pc.hpp>\n\n#define ljam() { jamLine(9000 + __LINE__); }\n#define ljamEntry() { jamEntryLine(9000 + __LINE__); }\n\nvoid Dbtup::freeAllAttrBuffers(Operationrec* const regOperPtr)\n{\n if (regOperPtr->storedProcedureId == RNIL) {\n ljam();\n freeAttrinbufrec(regOperPtr->firstAttrinbufrec);\n } else {\n ljam();\n StoredProcPtr storedPtr;\n c_storedProcPool.getPtr(storedPtr, (Uint32)regOperPtr->storedProcedureId);\n ndbrequire(storedPtr.p->storedCode == ZSCAN_PROCEDURE);\n storedPtr.p->storedCounter--;\n regOperPtr->storedProcedureId = ZNIL;\n }\/\/if\n regOperPtr->firstAttrinbufrec = RNIL;\n regOperPtr->lastAttrinbufrec = RNIL;\n}\/\/Dbtup::freeAllAttrBuffers()\n\nvoid Dbtup::freeAttrinbufrec(Uint32 anAttrBuf) \n{\n Uint32 Ttemp;\n AttrbufrecPtr localAttrBufPtr;\n Uint32 RnoFree = cnoFreeAttrbufrec;\n localAttrBufPtr.i = anAttrBuf;\n while (localAttrBufPtr.i != RNIL) {\n ljam();\n ptrCheckGuard(localAttrBufPtr, cnoOfAttrbufrec, attrbufrec);\n Ttemp = localAttrBufPtr.p->attrbuf[ZBUF_NEXT];\n localAttrBufPtr.p->attrbuf[ZBUF_NEXT] = cfirstfreeAttrbufrec;\n cfirstfreeAttrbufrec = localAttrBufPtr.i;\n localAttrBufPtr.i = Ttemp;\n RnoFree++;\n }\/\/if\n cnoFreeAttrbufrec = RnoFree;\n}\/\/Dbtup::freeAttrinbufrec()\n\n\/**\n * Abort abort this operation and all after (nextActiveOp's)\n *\/\nvoid Dbtup::execTUP_ABORTREQ(Signal* signal) \n{\n ljamEntry();\n do_tup_abortreq(signal, 0);\n}\n\nvoid Dbtup::do_tup_abortreq(Signal* signal, Uint32 flags)\n{\n OperationrecPtr regOperPtr;\n FragrecordPtr regFragPtr;\n TablerecPtr regTabPtr;\n\n regOperPtr.i = signal->theData[0];\n c_operation_pool.getPtr(regOperPtr);\n TransState trans_state= get_trans_state(regOperPtr.p);\n ndbrequire((trans_state == TRANS_STARTED) ||\n (trans_state == TRANS_TOO_MUCH_AI) ||\n (trans_state == TRANS_ERROR_WAIT_TUPKEYREQ) ||\n (trans_state == TRANS_IDLE));\n if (regOperPtr.p->op_struct.op_type == ZREAD) {\n ljam();\n freeAllAttrBuffers(regOperPtr.p);\n initOpConnection(regOperPtr.p);\n return;\n }\/\/if\n\n regFragPtr.i = regOperPtr.p->fragmentPtr;\n ptrCheckGuard(regFragPtr, cnoOfFragrec, fragrecord);\n\n regTabPtr.i = regFragPtr.p->fragTableId;\n ptrCheckGuard(regTabPtr, cnoOfTablerec, tablerec);\n\n if (get_tuple_state(regOperPtr.p) == TUPLE_PREPARED)\n {\n ljam();\n if (!regTabPtr.p->tuxCustomTriggers.isEmpty() &&\n (flags & ZSKIP_TUX_TRIGGERS) == 0)\n executeTuxAbortTriggers(signal,\n\t\t\t regOperPtr.p,\n\t\t\t regFragPtr.p,\n\t\t\t regTabPtr.p);\n \n OperationrecPtr loopOpPtr;\n loopOpPtr.i = regOperPtr.p->nextActiveOp;\n while (loopOpPtr.i != RNIL) {\n ljam();\n c_operation_pool.getPtr(loopOpPtr);\n if (get_tuple_state(loopOpPtr.p) != TUPLE_ALREADY_ABORTED &&\n\t !regTabPtr.p->tuxCustomTriggers.isEmpty() &&\n (flags & ZSKIP_TUX_TRIGGERS) == 0) {\n ljam();\n executeTuxAbortTriggers(signal,\n loopOpPtr.p,\n regFragPtr.p,\n regTabPtr.p);\n }\n set_tuple_state(loopOpPtr.p, TUPLE_ALREADY_ABORTED); \n loopOpPtr.i = loopOpPtr.p->nextActiveOp;\n }\n }\n\n PagePtr page;\n Tuple_header *tuple_ptr= (Tuple_header*)\n get_ptr(&page, ®OperPtr.p->m_tuple_location, regTabPtr.p);\n\n Uint32 bits= tuple_ptr->m_header_bits; \n if(regOperPtr.p->op_struct.op_type != ZDELETE)\n {\n Tuple_header *copy= (Tuple_header*)\n c_undo_buffer.get_ptr(®OperPtr.p->m_copy_tuple_location);\n \n if(regOperPtr.p->op_struct.m_disk_preallocated)\n {\n jam();\n Local_key key;\n memcpy(&key, copy->get_disk_ref_ptr(regTabPtr.p), sizeof(key));\n disk_page_abort_prealloc(signal, regFragPtr.p, &key, key.m_page_idx);\n }\n \n\n Uint32 copy_bits= copy->m_header_bits;\n if(! (bits & Tuple_header::ALLOC))\n {\n if(copy_bits & Tuple_header::MM_GROWN)\n {\n\tndbout_c(\"abort grow\");\n\tPtr<Page> vpage;\n\tUint32 idx= regOperPtr.p->m_tuple_location.m_page_idx;\n\tUint32 mm_vars= regTabPtr.p->m_attributes[MM].m_no_of_varsize;\n\tUint32 *var_part;\n\n\tndbassert(tuple_ptr->m_header_bits & Tuple_header::CHAINED_ROW);\n\t\n\tUint32 ref= * tuple_ptr->get_var_part_ptr(regTabPtr.p);\n\tLocal_key tmp; \n\ttmp.assref(ref); \n\t\n\tidx= tmp.m_page_idx;\n\tvar_part= get_ptr(&vpage, *(Var_part_ref*)&ref);\n\tVar_page* pageP = (Var_page*)vpage.p;\n\tUint32 len= pageP->get_entry_len(idx) & ~Var_page::CHAIN;\n\tUint32 sz = ((((mm_vars + 1) << 1) + (((Uint16*)var_part)[mm_vars]) + 3)>> 2);\n\tndbassert(sz <= len);\n\tpageP->shrink_entry(idx, sz);\n\tupdate_free_page_list(regFragPtr.p, vpage);\n } \n else if(bits & Tuple_header::MM_SHRINK)\n {\n\tndbout_c(\"abort shrink\");\n }\n }\n else if (regOperPtr.p->is_first_operation() && \n\t regOperPtr.p->is_last_operation())\n {\n \/**\n * Aborting last operation that performed ALLOC\n *\/\n tuple_ptr->m_header_bits &= ~(Uint32)Tuple_header::ALLOC;\n tuple_ptr->m_header_bits |= Tuple_header::FREED;\n }\n }\n else if (regOperPtr.p->is_first_operation() && \n\t regOperPtr.p->is_last_operation())\n {\n if (bits & Tuple_header::ALLOC)\n {\n tuple_ptr->m_header_bits &= ~(Uint32)Tuple_header::ALLOC;\n tuple_ptr->m_header_bits |= Tuple_header::FREED;\n }\n }\n \n if(regOperPtr.p->is_first_operation() && regOperPtr.p->is_last_operation())\n {\n if (regOperPtr.p->m_undo_buffer_space)\n c_lgman->free_log_space(regFragPtr.p->m_logfile_group_id, \n\t\t\t regOperPtr.p->m_undo_buffer_space);\n }\n\n removeActiveOpList(regOperPtr.p, tuple_ptr);\n initOpConnection(regOperPtr.p);\n}\n\n\/* **************************************************************** *\/\n\/* ********************** TRANSACTION ERROR MODULE **************** *\/\n\/* **************************************************************** *\/\nint Dbtup::TUPKEY_abort(Signal* signal, int error_type)\n{\n switch(error_type) {\n case 1:\n\/\/tmupdate_alloc_error:\n terrorCode= ZMEM_NOMEM_ERROR;\n ljam();\n break;\n\n case 15:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 16:\n ljam();\n terrorCode = ZTRY_TO_UPDATE_ERROR;\n break;\n\n case 17:\n ljam();\n terrorCode = ZNO_ILLEGAL_NULL_ATTR;\n break;\n\n case 19:\n ljam();\n terrorCode = ZTRY_TO_UPDATE_ERROR;\n break;\n\n case 20:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 22:\n ljam();\n terrorCode = ZTOTAL_LEN_ERROR;\n break;\n\n case 23:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 24:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 26:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 27:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 28:\n ljam();\n terrorCode = ZREGISTER_INIT_ERROR;\n break;\n\n case 29:\n ljam();\n break;\n\n case 30:\n ljam();\n terrorCode = ZCALL_ERROR;\n break;\n\n case 31:\n ljam();\n terrorCode = ZSTACK_OVERFLOW_ERROR;\n break;\n\n case 32:\n ljam();\n terrorCode = ZSTACK_UNDERFLOW_ERROR;\n break;\n\n case 33:\n ljam();\n terrorCode = ZNO_INSTRUCTION_ERROR;\n break;\n\n case 34:\n ljam();\n terrorCode = ZOUTSIDE_OF_PROGRAM_ERROR;\n break;\n\n case 35:\n ljam();\n terrorCode = ZTOO_MANY_INSTRUCTIONS_ERROR;\n break;\n\n case 38:\n ljam();\n terrorCode = ZTEMPORARY_RESOURCE_FAILURE;\n break;\n\n case 39:\n if (get_trans_state(operPtr.p) == TRANS_TOO_MUCH_AI) {\n ljam();\n terrorCode = ZTOO_MUCH_ATTRINFO_ERROR;\n } else if (get_trans_state(operPtr.p) == TRANS_ERROR_WAIT_TUPKEYREQ) {\n ljam();\n terrorCode = ZSEIZE_ATTRINBUFREC_ERROR;\n } else {\n ndbrequire(false);\n }\/\/if\n break;\n default:\n ndbrequire(false);\n break;\n }\/\/switch\n tupkeyErrorLab(signal);\n return -1;\n}\n\nvoid Dbtup::early_tupkey_error(Signal* signal)\n{\n Operationrec * const regOperPtr = operPtr.p;\n ndbrequire(!regOperPtr->op_struct.in_active_list);\n set_trans_state(regOperPtr, TRANS_IDLE);\n set_tuple_state(regOperPtr, TUPLE_PREPARED);\n initOpConnection(regOperPtr);\n send_TUPKEYREF(signal, regOperPtr);\n}\n\nvoid Dbtup::tupkeyErrorLab(Signal* signal) \n{\n Operationrec * const regOperPtr = operPtr.p;\n set_trans_state(regOperPtr, TRANS_IDLE);\n set_tuple_state(regOperPtr, TUPLE_PREPARED);\n\n FragrecordPtr fragPtr;\n fragPtr.i= regOperPtr->fragmentPtr;\n ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord);\n\n TablerecPtr tabPtr;\n tabPtr.i= fragPtr.p->fragTableId;\n ptrCheckGuard(tabPtr, cnoOfTablerec, tablerec);\n\n if (regOperPtr->m_undo_buffer_space &&\n (regOperPtr->is_first_operation() && regOperPtr->is_last_operation()))\n {\n c_lgman->free_log_space(fragPtr.p->m_logfile_group_id, \n\t\t\t regOperPtr->m_undo_buffer_space);\n }\n\n Uint32 *ptr = 0;\n if (!regOperPtr->m_tuple_location.isNull())\n {\n PagePtr tmp;\n ptr= get_ptr(&tmp, ®OperPtr->m_tuple_location, tabPtr.p);\n }\n\n\n removeActiveOpList(regOperPtr, (Tuple_header*)ptr);\n initOpConnection(regOperPtr);\n send_TUPKEYREF(signal, regOperPtr);\n}\n\nvoid Dbtup::send_TUPKEYREF(Signal* signal,\n Operationrec* const regOperPtr)\n{\n TupKeyRef * const tupKeyRef = (TupKeyRef *)signal->getDataPtrSend(); \n tupKeyRef->userRef = regOperPtr->userpointer;\n tupKeyRef->errorCode = terrorCode;\n sendSignal(DBLQH_REF, GSN_TUPKEYREF, signal, \n TupKeyRef::SignalLength, JBB);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * NetworkSolver.hpp\n *\n * Created on: 03.06.2016\n * Author: hartung\n *\/\n\n#ifndef NETWORK_INCLUDE_NETWORKSOLVER_HPP_\n#define NETWORK_INCLUDE_NETWORKSOLVER_HPP_\n\n#include \"solver\/AbstractSolver.hpp\"\n#include \"SimulationServer.hpp\"\n\nnamespace Solver\n{\n\n \/*! \\brief\n *\n * This is a specialization of template class AbstractSolver with FMUClass=FMI::EmptyFMU.\n *\/\n template<class DataManagerClass>\n class NetworkSolver : public ISolver\n {\n public:\n NetworkSolver() = delete;\n\n ~NetworkSolver() = default;\n\n NetworkSolver(const Initialization::SolverPlan & in, const FMI::EmptyFmu & fmu,\n shared_ptr<DataManagerClass> & dataManager)\n : _id(in.id),\n _dataManager(dataManager),\n _currentTime(in.startTime),\n _endTime(in.endTime),\n _simServer(in.networkPlan.server),\n _spec(NetOff::ClientMessageSpecifyer::UNPAUSE),\n _solvPlan(in),\n _fmu(fmu),\n _lastRequestHandled(true),\n _outputsSent(false)\n {\n if (!_simServer->isActive())\n throw runtime_error(\"SimulationServer isn't active. Abort.\");\n }\n\n size_type solve(const size_type & numSteps) override\n {\n std::cout << \"Networksolver::Solve\\n\";\n unsigned count = 0, testVar = 1;\n while (count++ < numSteps && testVar == 1)\n {\n if (_lastRequestHandled)\n _spec = _simServer->getClientRequest();\n switch (_spec)\n {\n case NetOff::ClientMessageSpecifyer::INPUTS:\n testVar = confirmInputs();\n break;\n case NetOff::ClientMessageSpecifyer::PAUSE:\n testVar = pauseSim();\n break;\n case NetOff::ClientMessageSpecifyer::UNPAUSE:\n testVar = unpauseSim();\n break;\n case NetOff::ClientMessageSpecifyer::RESET:\n testVar = abortSim();\n break;\n case NetOff::ClientMessageSpecifyer::CLIENT_ABORT:\n testVar = abortSim();\n break;\n }\n }\n return (testVar == 1) ? count : testVar;\n }\n\n void initialize() override\n {\n \/\/ set up values\n size_type numReals = 0, numInts = 0, numBools = 0, numStrings = 0;\n\n for (const auto & fmuCon : _solvPlan.networkPlan.fmuNet)\n {\n numReals += fmuCon.inputMap.template size<real_type>() + fmuCon.outputMap.template size<real_type>();\n numInts += fmuCon.inputMap.template size<int_type>() + fmuCon.outputMap.template size<int_type>();\n numBools += fmuCon.inputMap.template size<bool_type>() + fmuCon.outputMap.template size<bool_type>();\n numStrings += fmuCon.inputMap.template size<string_type>() + fmuCon.outputMap.template size<string_type>();\n }\n _fmu.setNumValues(numReals, numInts, numBools, numStrings);\n\n _dataManager->addFmu(&_fmu);\n\n for (auto& con : _fmu.getConnections())\n {\n if (con->isOutgoing(_fmu.getFmuName()))\n _outConns.push_back(con);\n }\n _simServer->confirmStart();\n }\n\n ErrorInfo getErrorInfo() const\n {\n return ErrorInfo();\n }\n\n size_type getSolverOrder() const\n {\n return 1u;\n }\n\n void setEndTime(const real_type & simTime) override\n {\n _endTime = simTime;\n }\n\n void setTolerance(const real_type & tolerance) override\n {\n\n }\n\n Synchronization::IDataManager* getDataManager() override\n {\n return _dataManager.get();\n }\n\n real_type getCurrentTime() const\n {\n return _currentTime;\n }\n\n real_type getEndTime() const\n {\n return _endTime;\n }\n\n real_type getCurrentStepSize() const\n {\n return 0.01;\n }\n\n void setStepSize(const real_type & in) override\n {\n\n }\n\n real_type getStepSize() const\n {\n return 0.01;\n }\n\n bool_type isFinished() const\n {\n return _simServer->isActive();\n }\n\n size_type getId() const\n {\n return _id;\n }\n\n const FMI::AbstractFmu* getFmu() const\n {\n return &_fmu;\n }\n\n FMI::AbstractFmu* getFmu() override\n {\n return &_fmu;\n }\n\n real_type getTolerance() const\n {\n return 1.0e-5;\n }\n\n real_type getMaxError() const\n {\n return 0.0;\n }\n\n void setMaxError(const real_type & maxError) override\n {\n\n }\n\n size_type getEventCounter() const\n {\n return 0;\n }\n\n private:\n size_type _id;\n shared_ptr<DataManagerClass> _dataManager;\n real_type _currentTime;\n real_type _endTime;\n\n shared_ptr<NetOff::SimulationServer> _simServer;\n vector<Synchronization::ConnectionSPtr> _outConns; \/\/ refs simNum to connection\n NetOff::ClientMessageSpecifyer _spec;\n\n const Initialization::SolverPlan _solvPlan;\n FMI::EmptyFmu _fmu;\n\n bool _lastRequestHandled;\n bool _outputsSent;\n\n size_type confirmInputs()\n {\n int fmuId = _simServer->getLastSimId();\n real_type remoteTime = _simServer->getLastReceivedTime(fmuId);\n if (!_outputsSent)\n {\n if (_dataManager->sendSingleOutput(remoteTime, 1, &_fmu, _outConns[fmuId]->getLocalId()))\n _outputsSent = true;\n else\n {\n _lastRequestHandled = false;\n _outputsSent = false;\n return 1;\n }\n }\n if (std::abs(_currentTime - remoteTime) > 1.0e-10)\n {\n \/\/ get values\n if (_dataManager->getDependencyInfo(&_fmu).depStatus != Solver::DependencyStatus::BLOCKED)\n {\n _dataManager->setFmuInputValuesAtT(remoteTime, &_fmu);\n _currentTime = remoteTime;\n }\n else\n {\n _lastRequestHandled = false;\n return 1;\n }\n }\n NetOff::ValueContainer & vals = _simServer->getOutputValueContainer(fmuId);\n const FMI::ValueCollection & fmuVals = _fmu.getEmptyFmuValues();\n FMI::ValueCollection tmp = _solvPlan.networkPlan.fmuNet[fmuId].outputMap.pack(fmuVals); \/\/ TODO alloc\n vals.setRealValues(tmp.getValues<real_type>().data());\n vals.setIntValues(tmp.getValues<int_type>().data());\n vals.setBoolValues(tmp.getValues<bool_type>().data());\n\n \/\/ _lastRequestHandled = _simServer->sendOutputValues(fmuId, _currentTime, vals);\n _lastRequestHandled = _simServer->sendOutputValues(fmuId, _currentTime);\n return 1;\n }\n\n size_type pauseSim()\n {\n return 1;\n }\n\n size_type unpauseSim()\n {\n return 1;\n }\n\n size_type abortSim()\n {\n _simServer->deinitialize();\n return std::numeric_limits<size_type>::max();\n }\n\n };\n}\n#endif\n<commit_msg>Add curly braces for one liners<commit_after>\/*\n * NetworkSolver.hpp\n *\n * Created on: 03.06.2016\n * Author: hartung\n *\/\n\n#ifndef NETWORK_INCLUDE_NETWORKSOLVER_HPP_\n#define NETWORK_INCLUDE_NETWORKSOLVER_HPP_\n\n#include \"solver\/AbstractSolver.hpp\"\n#include \"SimulationServer.hpp\"\n\nnamespace Solver\n{\n\n \/*! \\brief\n *\n * This is a specialization of template class AbstractSolver with FMUClass=FMI::EmptyFMU.\n *\/\n template<class DataManagerClass>\n class NetworkSolver : public ISolver\n {\n public:\n NetworkSolver() = delete;\n\n ~NetworkSolver() = default;\n\n NetworkSolver(const Initialization::SolverPlan & in, const FMI::EmptyFmu & fmu,\n shared_ptr<DataManagerClass> & dataManager)\n : _id(in.id),\n _dataManager(dataManager),\n _currentTime(in.startTime),\n _endTime(in.endTime),\n _simServer(in.networkPlan.server),\n _spec(NetOff::ClientMessageSpecifyer::UNPAUSE),\n _solvPlan(in),\n _fmu(fmu),\n _lastRequestHandled(true),\n _outputsSent(false)\n {\n if (!_simServer->isActive())\n {\n throw runtime_error(\"SimulationServer isn't active. Abort.\");\n }\n }\n\n size_type solve(const size_type & numSteps) override\n {\n std::cout << \"Networksolver::Solve\\n\";\n unsigned count = 0, testVar = 1;\n while (count++ < numSteps && testVar == 1)\n {\n if (_lastRequestHandled)\n {\n _spec = _simServer->getClientRequest();\n }\n switch (_spec)\n {\n case NetOff::ClientMessageSpecifyer::INPUTS:\n testVar = confirmInputs();\n break;\n case NetOff::ClientMessageSpecifyer::PAUSE:\n testVar = pauseSim();\n break;\n case NetOff::ClientMessageSpecifyer::UNPAUSE:\n testVar = unpauseSim();\n break;\n case NetOff::ClientMessageSpecifyer::RESET:\n testVar = abortSim();\n break;\n case NetOff::ClientMessageSpecifyer::CLIENT_ABORT:\n testVar = abortSim();\n break;\n }\n }\n return (testVar == 1) ? count : testVar;\n }\n\n void initialize() override\n {\n \/\/ set up values\n size_type numReals = 0, numInts = 0, numBools = 0, numStrings = 0;\n\n for (const auto & fmuCon : _solvPlan.networkPlan.fmuNet)\n {\n numReals += fmuCon.inputMap.template size<real_type>() + fmuCon.outputMap.template size<real_type>();\n numInts += fmuCon.inputMap.template size<int_type>() + fmuCon.outputMap.template size<int_type>();\n numBools += fmuCon.inputMap.template size<bool_type>() + fmuCon.outputMap.template size<bool_type>();\n numStrings += fmuCon.inputMap.template size<string_type>() + fmuCon.outputMap.template size<string_type>();\n }\n _fmu.setNumValues(numReals, numInts, numBools, numStrings);\n\n _dataManager->addFmu(&_fmu);\n\n for (auto& con : _fmu.getConnections())\n {\n if (con->isOutgoing(_fmu.getFmuName()))\n {\n _outConns.push_back(con);\n }\n }\n _simServer->confirmStart();\n }\n\n ErrorInfo getErrorInfo() const\n {\n return ErrorInfo();\n }\n\n size_type getSolverOrder() const\n {\n return 1u;\n }\n\n void setEndTime(const real_type & simTime) override\n {\n _endTime = simTime;\n }\n\n void setTolerance(const real_type & tolerance) override\n {\n\n }\n\n Synchronization::IDataManager* getDataManager() override\n {\n return _dataManager.get();\n }\n\n real_type getCurrentTime() const\n {\n return _currentTime;\n }\n\n real_type getEndTime() const\n {\n return _endTime;\n }\n\n real_type getCurrentStepSize() const\n {\n return 0.01;\n }\n\n void setStepSize(const real_type & in) override\n {\n\n }\n\n real_type getStepSize() const\n {\n return 0.01;\n }\n\n bool_type isFinished() const\n {\n return _simServer->isActive();\n }\n\n size_type getId() const\n {\n return _id;\n }\n\n const FMI::AbstractFmu* getFmu() const\n {\n return &_fmu;\n }\n\n FMI::AbstractFmu* getFmu() override\n {\n return &_fmu;\n }\n\n real_type getTolerance() const\n {\n return 1.0e-5;\n }\n\n real_type getMaxError() const\n {\n return 0.0;\n }\n\n void setMaxError(const real_type & maxError) override\n {\n\n }\n\n size_type getEventCounter() const\n {\n return 0;\n }\n\n private:\n size_type _id;\n shared_ptr<DataManagerClass> _dataManager;\n real_type _currentTime;\n real_type _endTime;\n\n shared_ptr<NetOff::SimulationServer> _simServer;\n vector<Synchronization::ConnectionSPtr> _outConns; \/\/ refs simNum to connection\n NetOff::ClientMessageSpecifyer _spec;\n\n const Initialization::SolverPlan _solvPlan;\n FMI::EmptyFmu _fmu;\n\n bool _lastRequestHandled;\n bool _outputsSent;\n\n size_type confirmInputs()\n {\n int fmuId = _simServer->getLastSimId();\n real_type remoteTime = _simServer->getLastReceivedTime(fmuId);\n if (!_outputsSent)\n {\n if (_dataManager->sendSingleOutput(remoteTime, 1, &_fmu, _outConns[fmuId]->getLocalId()))\n {\n _outputsSent = true;\n }\n else\n {\n _lastRequestHandled = false;\n _outputsSent = false;\n return 1;\n }\n }\n if (std::abs(_currentTime - remoteTime) > 1.0e-10)\n {\n \/\/ get values\n if (_dataManager->getDependencyInfo(&_fmu).depStatus != Solver::DependencyStatus::BLOCKED)\n {\n _dataManager->setFmuInputValuesAtT(remoteTime, &_fmu);\n _currentTime = remoteTime;\n }\n else\n {\n _lastRequestHandled = false;\n return 1;\n }\n }\n NetOff::ValueContainer & vals = _simServer->getOutputValueContainer(fmuId);\n const FMI::ValueCollection & fmuVals = _fmu.getEmptyFmuValues();\n FMI::ValueCollection tmp = _solvPlan.networkPlan.fmuNet[fmuId].outputMap.pack(fmuVals); \/\/ TODO alloc\n vals.setRealValues(tmp.getValues<real_type>().data());\n vals.setIntValues(tmp.getValues<int_type>().data());\n vals.setBoolValues(tmp.getValues<bool_type>().data());\n\n \/\/ _lastRequestHandled = _simServer->sendOutputValues(fmuId, _currentTime, vals);\n _lastRequestHandled = _simServer->sendOutputValues(fmuId, _currentTime);\n return 1;\n }\n\n size_type pauseSim()\n {\n return 1;\n }\n\n size_type unpauseSim()\n {\n return 1;\n }\n\n size_type abortSim()\n {\n _simServer->deinitialize();\n return std::numeric_limits<size_type>::max();\n }\n\n };\n\n} \/\/ namespace Solver\n\n#endif \/\/ NETWORK_INCLUDE_NETWORKSOLVER_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015, 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#include \"AstNode.h\"\n#include \"GraphQLParser.h\"\n#include \"c\/GraphQLAstToJSON.h\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::fopen;\nusing std::fclose;\nusing std::free;\n\n\nint main(int argc, char **argv) {\n const char *error;\n FILE * in;\n if (argc > 1) {\n in = fopen(argv[1], \"r\");\n } else {\n in = stdin;\n }\n auto AST = facebook::graphql::parseFile(in, &error);\n if (argc > 1) {\n fclose(in);\n }\n if (!AST) {\n cerr << \"Parser failed with error: \" << error << endl;\n free((void *)error);\n return 1;\n }\n\n puts(graphql_ast_to_json((const struct GraphQLAstNode *)AST.get()));\n\n return 0;\n}\n<commit_msg>dump_json_ast: don't leak return value of graphql_ast_to_json<commit_after>\/**\n * Copyright (c) 2015, 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#include \"AstNode.h\"\n#include \"GraphQLParser.h\"\n#include \"c\/GraphQLAstToJSON.h\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::fopen;\nusing std::fclose;\nusing std::free;\n\n\nint main(int argc, char **argv) {\n const char *error;\n FILE * in;\n if (argc > 1) {\n in = fopen(argv[1], \"r\");\n } else {\n in = stdin;\n }\n auto AST = facebook::graphql::parseFile(in, &error);\n if (argc > 1) {\n fclose(in);\n }\n if (!AST) {\n cerr << \"Parser failed with error: \" << error << endl;\n free((void *)error);\n return 1;\n }\n\n const char *json = graphql_ast_to_json((const struct GraphQLAstNode *)AST.get());\n puts(json);\n free((void *)json);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: rangeseq.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 10:38:38 $\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#ifdef PCH\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include <svtools\/zforlist.hxx>\n#include <rtl\/math.hxx>\n#include <tools\/debug.hxx>\n\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n\n#include \"rangeseq.hxx\"\n#include \"document.hxx\"\n#include \"scmatrix.hxx\"\n#include \"cell.hxx\"\n\nusing namespace com::sun::star;\n\n\/\/------------------------------------------------------------------------\n\nlong lcl_DoubleToLong( double fVal )\n{\n double fInt = (fVal >= 0.0) ? ::rtl::math::approxFloor( fVal ) :\n ::rtl::math::approxCeil( fVal );\n if ( fInt >= LONG_MIN && fInt <= LONG_MAX )\n return (long)fInt;\n else\n return 0; \/\/ out of range\n}\n\nBOOL ScRangeToSequence::FillLongArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n SCTAB nTab = rRange.aStart.Tab();\n SCCOL nStartCol = rRange.aStart.Col();\n SCROW nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n uno::Sequence< uno::Sequence<INT32> > aRowSeq( nRowCount );\n uno::Sequence<INT32>* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<INT32> aColSeq( nColCount );\n INT32* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n pColAry[nCol] = lcl_DoubleToLong( pDoc->GetValue(\n ScAddress( (SCCOL)(nStartCol+nCol), (SCROW)(nStartRow+nRow), nTab ) ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillLongArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n SCSIZE nColCount;\n SCSIZE nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence<INT32> > aRowSeq( static_cast<sal_Int32>(nRowCount) );\n uno::Sequence<INT32>* pRowAry = aRowSeq.getArray();\n for (SCSIZE nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<INT32> aColSeq( static_cast<sal_Int32>(nColCount) );\n INT32* pColAry = aColSeq.getArray();\n for (SCSIZE nCol = 0; nCol < nColCount; nCol++)\n if ( pMatrix->IsString( nCol, nRow ) )\n pColAry[nCol] = 0;\n else\n pColAry[nCol] = lcl_DoubleToLong( pMatrix->GetDouble( nCol, nRow ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillDoubleArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n SCTAB nTab = rRange.aStart.Tab();\n SCCOL nStartCol = rRange.aStart.Col();\n SCROW nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n uno::Sequence< uno::Sequence<double> > aRowSeq( nRowCount );\n uno::Sequence<double>* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<double> aColSeq( nColCount );\n double* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n pColAry[nCol] = pDoc->GetValue(\n ScAddress( (SCCOL)(nStartCol+nCol), (SCROW)(nStartRow+nRow), nTab ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillDoubleArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n SCSIZE nColCount;\n SCSIZE nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence<double> > aRowSeq( static_cast<sal_Int32>(nRowCount) );\n uno::Sequence<double>* pRowAry = aRowSeq.getArray();\n for (SCSIZE nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<double> aColSeq( static_cast<sal_Int32>(nColCount) );\n double* pColAry = aColSeq.getArray();\n for (SCSIZE nCol = 0; nCol < nColCount; nCol++)\n if ( pMatrix->IsString( nCol, nRow ) )\n pColAry[nCol] = 0.0;\n else\n pColAry[nCol] = pMatrix->GetDouble( nCol, nRow );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillStringArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n SCTAB nTab = rRange.aStart.Tab();\n SCCOL nStartCol = rRange.aStart.Col();\n SCROW nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n String aDocStr;\n\n uno::Sequence< uno::Sequence<rtl::OUString> > aRowSeq( nRowCount );\n uno::Sequence<rtl::OUString>* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<rtl::OUString> aColSeq( nColCount );\n rtl::OUString* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n {\n pDoc->GetString( (SCCOL)(nStartCol+nCol), (SCROW)(nStartRow+nRow), nTab, aDocStr );\n pColAry[nCol] = rtl::OUString( aDocStr );\n }\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillStringArray( uno::Any& rAny, const ScMatrix* pMatrix,\n SvNumberFormatter* pFormatter )\n{\n if (!pMatrix)\n return FALSE;\n\n SCSIZE nColCount;\n SCSIZE nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence<rtl::OUString> > aRowSeq( static_cast<sal_Int32>(nRowCount) );\n uno::Sequence<rtl::OUString>* pRowAry = aRowSeq.getArray();\n for (SCSIZE nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<rtl::OUString> aColSeq( static_cast<sal_Int32>(nColCount) );\n rtl::OUString* pColAry = aColSeq.getArray();\n for (SCSIZE nCol = 0; nCol < nColCount; nCol++)\n {\n String aStr;\n if ( pMatrix->IsString( nCol, nRow ) )\n {\n if ( !pMatrix->IsEmpty( nCol, nRow ) )\n aStr = pMatrix->GetString( nCol, nRow );\n }\n else if ( pFormatter )\n {\n double fVal = pMatrix->GetDouble( nCol, nRow );\n Color* pColor;\n pFormatter->GetOutputString( fVal, 0, aStr, &pColor );\n }\n pColAry[nCol] = rtl::OUString( aStr );\n }\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\ndouble lcl_GetValueFromCell( ScBaseCell& rCell )\n{\n \/\/! ScBaseCell member function?\n\n CellType eType = rCell.GetCellType();\n if ( eType == CELLTYPE_VALUE )\n return ((ScValueCell&)rCell).GetValue();\n else if ( eType == CELLTYPE_FORMULA )\n return ((ScFormulaCell&)rCell).GetValue(); \/\/ called only if result is value\n\n DBG_ERROR( \"GetValueFromCell: wrong type\" );\n return 0;\n}\n\nBOOL ScRangeToSequence::FillMixedArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange,\n BOOL bAllowNV )\n{\n SCTAB nTab = rRange.aStart.Tab();\n SCCOL nStartCol = rRange.aStart.Col();\n SCROW nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n String aDocStr;\n BOOL bHasErrors = FALSE;\n\n uno::Sequence< uno::Sequence<uno::Any> > aRowSeq( nRowCount );\n uno::Sequence<uno::Any>* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<uno::Any> aColSeq( nColCount );\n uno::Any* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n {\n uno::Any& rElement = pColAry[nCol];\n\n ScAddress aPos( (SCCOL)(nStartCol+nCol), (SCROW)(nStartRow+nRow), nTab );\n ScBaseCell* pCell = pDoc->GetCell( aPos );\n if ( pCell )\n {\n if ( pCell->GetCellType() == CELLTYPE_FORMULA &&\n ((ScFormulaCell*)pCell)->GetErrCode() != 0 )\n {\n \/\/ if NV is allowed, leave empty for errors\n bHasErrors = TRUE;\n }\n else if ( pCell->HasValueData() )\n rElement <<= (double) lcl_GetValueFromCell( *pCell );\n else\n rElement <<= rtl::OUString( pCell->GetStringData() );\n }\n else\n rElement <<= rtl::OUString(); \/\/ empty: empty string\n }\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return bAllowNV || !bHasErrors;\n}\n\n\nBOOL ScRangeToSequence::FillMixedArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n SCSIZE nColCount;\n SCSIZE nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence<uno::Any> > aRowSeq( static_cast<sal_Int32>(nRowCount) );\n uno::Sequence<uno::Any>* pRowAry = aRowSeq.getArray();\n for (SCSIZE nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<uno::Any> aColSeq( static_cast<sal_Int32>(nColCount) );\n uno::Any* pColAry = aColSeq.getArray();\n for (SCSIZE nCol = 0; nCol < nColCount; nCol++)\n {\n if ( pMatrix->IsString( nCol, nRow ) )\n {\n String aStr;\n if ( !pMatrix->IsEmpty( nCol, nRow ) )\n aStr = pMatrix->GetString( nCol, nRow );\n pColAry[nCol] <<= rtl::OUString( aStr );\n }\n else\n pColAry[nCol] <<= (double) pMatrix->GetDouble( nCol, nRow );\n }\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScByteSequenceToString::GetString( String& rString, const uno::Any& rAny,\n sal_uInt16 nEncoding )\n{\n uno::Sequence<sal_Int8> aSeq;\n if ( rAny >>= aSeq )\n {\n rString = String( (const sal_Char*)aSeq.getConstArray(),\n (xub_StrLen)aSeq.getLength(), nEncoding );\n rString.EraseTrailingChars( (sal_Unicode) 0 );\n return TRUE;\n }\n return FALSE;\n}\n\n\/\/------------------------------------------------------------------------\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.452); FILE MERGED 2005\/09\/05 15:02:07 rt 1.5.452.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rangeseq.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 18:48:43 $\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#ifdef PCH\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include <svtools\/zforlist.hxx>\n#include <rtl\/math.hxx>\n#include <tools\/debug.hxx>\n\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n\n#include \"rangeseq.hxx\"\n#include \"document.hxx\"\n#include \"scmatrix.hxx\"\n#include \"cell.hxx\"\n\nusing namespace com::sun::star;\n\n\/\/------------------------------------------------------------------------\n\nlong lcl_DoubleToLong( double fVal )\n{\n double fInt = (fVal >= 0.0) ? ::rtl::math::approxFloor( fVal ) :\n ::rtl::math::approxCeil( fVal );\n if ( fInt >= LONG_MIN && fInt <= LONG_MAX )\n return (long)fInt;\n else\n return 0; \/\/ out of range\n}\n\nBOOL ScRangeToSequence::FillLongArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n SCTAB nTab = rRange.aStart.Tab();\n SCCOL nStartCol = rRange.aStart.Col();\n SCROW nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n uno::Sequence< uno::Sequence<INT32> > aRowSeq( nRowCount );\n uno::Sequence<INT32>* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<INT32> aColSeq( nColCount );\n INT32* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n pColAry[nCol] = lcl_DoubleToLong( pDoc->GetValue(\n ScAddress( (SCCOL)(nStartCol+nCol), (SCROW)(nStartRow+nRow), nTab ) ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillLongArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n SCSIZE nColCount;\n SCSIZE nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence<INT32> > aRowSeq( static_cast<sal_Int32>(nRowCount) );\n uno::Sequence<INT32>* pRowAry = aRowSeq.getArray();\n for (SCSIZE nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<INT32> aColSeq( static_cast<sal_Int32>(nColCount) );\n INT32* pColAry = aColSeq.getArray();\n for (SCSIZE nCol = 0; nCol < nColCount; nCol++)\n if ( pMatrix->IsString( nCol, nRow ) )\n pColAry[nCol] = 0;\n else\n pColAry[nCol] = lcl_DoubleToLong( pMatrix->GetDouble( nCol, nRow ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillDoubleArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n SCTAB nTab = rRange.aStart.Tab();\n SCCOL nStartCol = rRange.aStart.Col();\n SCROW nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n uno::Sequence< uno::Sequence<double> > aRowSeq( nRowCount );\n uno::Sequence<double>* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<double> aColSeq( nColCount );\n double* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n pColAry[nCol] = pDoc->GetValue(\n ScAddress( (SCCOL)(nStartCol+nCol), (SCROW)(nStartRow+nRow), nTab ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillDoubleArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n SCSIZE nColCount;\n SCSIZE nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence<double> > aRowSeq( static_cast<sal_Int32>(nRowCount) );\n uno::Sequence<double>* pRowAry = aRowSeq.getArray();\n for (SCSIZE nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<double> aColSeq( static_cast<sal_Int32>(nColCount) );\n double* pColAry = aColSeq.getArray();\n for (SCSIZE nCol = 0; nCol < nColCount; nCol++)\n if ( pMatrix->IsString( nCol, nRow ) )\n pColAry[nCol] = 0.0;\n else\n pColAry[nCol] = pMatrix->GetDouble( nCol, nRow );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillStringArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n SCTAB nTab = rRange.aStart.Tab();\n SCCOL nStartCol = rRange.aStart.Col();\n SCROW nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n String aDocStr;\n\n uno::Sequence< uno::Sequence<rtl::OUString> > aRowSeq( nRowCount );\n uno::Sequence<rtl::OUString>* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<rtl::OUString> aColSeq( nColCount );\n rtl::OUString* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n {\n pDoc->GetString( (SCCOL)(nStartCol+nCol), (SCROW)(nStartRow+nRow), nTab, aDocStr );\n pColAry[nCol] = rtl::OUString( aDocStr );\n }\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillStringArray( uno::Any& rAny, const ScMatrix* pMatrix,\n SvNumberFormatter* pFormatter )\n{\n if (!pMatrix)\n return FALSE;\n\n SCSIZE nColCount;\n SCSIZE nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence<rtl::OUString> > aRowSeq( static_cast<sal_Int32>(nRowCount) );\n uno::Sequence<rtl::OUString>* pRowAry = aRowSeq.getArray();\n for (SCSIZE nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<rtl::OUString> aColSeq( static_cast<sal_Int32>(nColCount) );\n rtl::OUString* pColAry = aColSeq.getArray();\n for (SCSIZE nCol = 0; nCol < nColCount; nCol++)\n {\n String aStr;\n if ( pMatrix->IsString( nCol, nRow ) )\n {\n if ( !pMatrix->IsEmpty( nCol, nRow ) )\n aStr = pMatrix->GetString( nCol, nRow );\n }\n else if ( pFormatter )\n {\n double fVal = pMatrix->GetDouble( nCol, nRow );\n Color* pColor;\n pFormatter->GetOutputString( fVal, 0, aStr, &pColor );\n }\n pColAry[nCol] = rtl::OUString( aStr );\n }\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\ndouble lcl_GetValueFromCell( ScBaseCell& rCell )\n{\n \/\/! ScBaseCell member function?\n\n CellType eType = rCell.GetCellType();\n if ( eType == CELLTYPE_VALUE )\n return ((ScValueCell&)rCell).GetValue();\n else if ( eType == CELLTYPE_FORMULA )\n return ((ScFormulaCell&)rCell).GetValue(); \/\/ called only if result is value\n\n DBG_ERROR( \"GetValueFromCell: wrong type\" );\n return 0;\n}\n\nBOOL ScRangeToSequence::FillMixedArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange,\n BOOL bAllowNV )\n{\n SCTAB nTab = rRange.aStart.Tab();\n SCCOL nStartCol = rRange.aStart.Col();\n SCROW nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n String aDocStr;\n BOOL bHasErrors = FALSE;\n\n uno::Sequence< uno::Sequence<uno::Any> > aRowSeq( nRowCount );\n uno::Sequence<uno::Any>* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<uno::Any> aColSeq( nColCount );\n uno::Any* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n {\n uno::Any& rElement = pColAry[nCol];\n\n ScAddress aPos( (SCCOL)(nStartCol+nCol), (SCROW)(nStartRow+nRow), nTab );\n ScBaseCell* pCell = pDoc->GetCell( aPos );\n if ( pCell )\n {\n if ( pCell->GetCellType() == CELLTYPE_FORMULA &&\n ((ScFormulaCell*)pCell)->GetErrCode() != 0 )\n {\n \/\/ if NV is allowed, leave empty for errors\n bHasErrors = TRUE;\n }\n else if ( pCell->HasValueData() )\n rElement <<= (double) lcl_GetValueFromCell( *pCell );\n else\n rElement <<= rtl::OUString( pCell->GetStringData() );\n }\n else\n rElement <<= rtl::OUString(); \/\/ empty: empty string\n }\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return bAllowNV || !bHasErrors;\n}\n\n\nBOOL ScRangeToSequence::FillMixedArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n SCSIZE nColCount;\n SCSIZE nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence<uno::Any> > aRowSeq( static_cast<sal_Int32>(nRowCount) );\n uno::Sequence<uno::Any>* pRowAry = aRowSeq.getArray();\n for (SCSIZE nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence<uno::Any> aColSeq( static_cast<sal_Int32>(nColCount) );\n uno::Any* pColAry = aColSeq.getArray();\n for (SCSIZE nCol = 0; nCol < nColCount; nCol++)\n {\n if ( pMatrix->IsString( nCol, nRow ) )\n {\n String aStr;\n if ( !pMatrix->IsEmpty( nCol, nRow ) )\n aStr = pMatrix->GetString( nCol, nRow );\n pColAry[nCol] <<= rtl::OUString( aStr );\n }\n else\n pColAry[nCol] <<= (double) pMatrix->GetDouble( nCol, nRow );\n }\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScByteSequenceToString::GetString( String& rString, const uno::Any& rAny,\n sal_uInt16 nEncoding )\n{\n uno::Sequence<sal_Int8> aSeq;\n if ( rAny >>= aSeq )\n {\n rString = String( (const sal_Char*)aSeq.getConstArray(),\n (xub_StrLen)aSeq.getLength(), nEncoding );\n rString.EraseTrailingChars( (sal_Unicode) 0 );\n return TRUE;\n }\n return FALSE;\n}\n\n\/\/------------------------------------------------------------------------\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_SC_SOURCE_FILTER_INC_HTMLEXP_HXX\n#define INCLUDED_SC_SOURCE_FILTER_INC_HTMLEXP_HXX\n\n#include \"global.hxx\"\n#include <rtl\/textenc.h>\n#include <tools\/gen.hxx>\n#include <tools\/color.hxx>\n#include <boost\/ptr_container\/ptr_vector.hpp>\n#include <boost\/scoped_ptr.hpp>\n\n#include \"expbase.hxx\"\n\n\nclass ScDocument;\nclass SfxItemSet;\nclass SdrPage;\nclass Graphic;\nclass SdrObject;\nclass OutputDevice;\nclass ScDrawLayer;\nclass EditTextObject;\n\nnamespace editeng { class SvxBorderLine; }\n\nstruct ScHTMLStyle\n{ \/\/ Defaults aus StyleSheet\n Color aBackgroundColor;\n OUString aFontFamilyName;\n sal_uInt32 nFontHeight; \/\/ Item-Value\n sal_uInt16 nFontSizeNumber; \/\/ HTML value 1-7\n sal_uInt8 nDefaultScriptType; \/\/ Font values are valid for the default script type\n bool bInitialized;\n\n ScHTMLStyle() : nFontHeight(0), nFontSizeNumber(2), nDefaultScriptType(0),\n bInitialized(false) {}\n\n const ScHTMLStyle& operator=( const ScHTMLStyle& r )\n {\n aBackgroundColor = r.aBackgroundColor;\n aFontFamilyName = r.aFontFamilyName;\n nFontHeight = r.nFontHeight;\n nFontSizeNumber = r.nFontSizeNumber;\n nDefaultScriptType = r.nDefaultScriptType;\n bInitialized = r.bInitialized;\n return *this;\n }\n};\n\nstruct ScHTMLGraphEntry\n{\n ScRange aRange; \/\/ ueberlagerter Zellbereich\n Size aSize; \/\/ Groesse in Pixeln\n Size aSpace; \/\/ Spacing in Pixeln\n SdrObject* pObject;\n bool bInCell; \/\/ ob in Zelle ausgegeben wird\n bool bWritten;\n\n ScHTMLGraphEntry( SdrObject* pObj, const ScRange& rRange,\n const Size& rSize, bool bIn, const Size& rSpace ) :\n aRange( rRange ), aSize( rSize ), aSpace( rSpace ),\n pObject( pObj ), bInCell( bIn ), bWritten( false ) {}\n};\n\n\n#define SC_HTML_FONTSIZES 7\nconst short nIndentMax = 23;\n\nclass ScHTMLExport : public ScExportBase\n{\n \/\/ default HtmlFontSz[1-7]\n static const sal_uInt16 nDefaultFontSize[SC_HTML_FONTSIZES];\n \/\/ HtmlFontSz[1-7] in s*3.ini [user]\n static sal_uInt16 nFontSize[SC_HTML_FONTSIZES];\n static const char* pFontSizeCss[SC_HTML_FONTSIZES];\n static const sal_uInt16 nCellSpacing;\n static const sal_Char sIndentSource[];\n\n boost::ptr_vector< ScHTMLGraphEntry > aGraphList;\n ScHTMLStyle aHTMLStyle;\n OUString aBaseURL;\n OUString aStreamPath;\n OUString aFilterOptions;\n OUString aCId; \/\/ Content-Id fuer Mail-Export\n OutputDevice* pAppWin; \/\/ fuer Pixelei\n boost::scoped_ptr< std::map<OUString, OUString> > pFileNameMap; \/\/ fuer CopyLocalFileToINet\n OUString aNonConvertibleChars; \/\/ collect nonconvertible characters\n rtl_TextEncoding eDestEnc;\n SCTAB nUsedTables;\n short nIndent;\n sal_Char sIndent[nIndentMax+1];\n bool bAll; \/\/ ganzes Dokument\n bool bTabHasGraphics;\n bool bTabAlignedLeft;\n bool bCalcAsShown;\n bool bCopyLocalFileToINet;\n bool bTableDataWidth;\n bool bTableDataHeight;\n\n const SfxItemSet& PageDefaults( SCTAB nTab );\n\n void WriteBody();\n void WriteHeader();\n void WriteOverview();\n void WriteTables();\n void WriteCell( SCCOL nCol, SCROW nRow, SCTAB nTab );\n void WriteGraphEntry( ScHTMLGraphEntry* );\n void WriteImage( OUString& rLinkName,\n const Graphic&, const OString& rImgOptions,\n sal_uLong nXOutFlags = 0 );\n \/\/ nXOutFlags fuer XOutBitmap::WriteGraphic\n\n \/\/ write to stream if and only if URL fields in edit cell\n bool WriteFieldText( const EditTextObject* pData );\n\n \/\/ kopiere ggfs. eine lokale Datei ins Internet\n bool CopyLocalFileToINet( OUString& rFileNm,\n const OUString& rTargetNm, bool bFileToFile = false );\n bool HasCId() { return !aCId.isEmpty(); }\n void MakeCIdURL( OUString& rURL );\n\n void PrepareGraphics( ScDrawLayer*, SCTAB nTab,\n SCCOL nStartCol, SCROW nStartRow,\n SCCOL nEndCol, SCROW nEndRow );\n void FillGraphList( const SdrPage*, SCTAB nTab,\n SCCOL nStartCol, SCROW nStartRow,\n SCCOL nEndCol, SCROW nEndRow );\n\n OString BorderToStyle(const char* pBorderName,\n const ::editeng::SvxBorderLine* pLine, bool& bInsertSemicolon);\n\n sal_uInt16 GetFontSizeNumber( sal_uInt16 nHeight );\n const char* GetFontSizeCss( sal_uInt16 nHeight );\n sal_uInt16 ToPixel( sal_uInt16 nTwips );\n Size MMToPixel( const Size& r100thMMSize );\n void IncIndent( short nVal );\n const sal_Char* GetIndentStr() { return sIndent; }\n\npublic:\n ScHTMLExport( SvStream&, const OUString&, ScDocument*, const ScRange&,\n bool bAll, const OUString& aStreamPath, const OUString& rFilterOptions );\n virtual ~ScHTMLExport();\n sal_uLong Write();\n const OUString& GetNonConvertibleChars() const\n { return aNonConvertibleChars; }\n};\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>sc html export: cleanup htmlexp.hxx<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_SC_SOURCE_FILTER_INC_HTMLEXP_HXX\n#define INCLUDED_SC_SOURCE_FILTER_INC_HTMLEXP_HXX\n\n#include \"global.hxx\"\n#include <rtl\/textenc.h>\n#include <tools\/gen.hxx>\n#include <tools\/color.hxx>\n#include <boost\/ptr_container\/ptr_vector.hpp>\n#include <boost\/scoped_ptr.hpp>\n\n#include \"expbase.hxx\"\n\nclass ScDocument;\nclass SfxItemSet;\nclass SdrPage;\nclass Graphic;\nclass SdrObject;\nclass OutputDevice;\nclass ScDrawLayer;\nclass EditTextObject;\n\nnamespace editeng { class SvxBorderLine; }\n\nstruct ScHTMLStyle\n{ \/\/ Defaults aus StyleSheet\n Color aBackgroundColor;\n OUString aFontFamilyName;\n sal_uInt32 nFontHeight; \/\/ Item-Value\n sal_uInt16 nFontSizeNumber; \/\/ HTML value 1-7\n sal_uInt8 nDefaultScriptType; \/\/ Font values are valid for the default script type\n bool bInitialized;\n\n ScHTMLStyle() :\n nFontHeight(0),\n nFontSizeNumber(2),\n nDefaultScriptType(),\n bInitialized(false)\n {}\n\n const ScHTMLStyle& operator=( const ScHTMLStyle& rScHTMLStyle )\n {\n aBackgroundColor = rScHTMLStyle.aBackgroundColor;\n aFontFamilyName = rScHTMLStyle.aFontFamilyName;\n nFontHeight = rScHTMLStyle.nFontHeight;\n nFontSizeNumber = rScHTMLStyle.nFontSizeNumber;\n nDefaultScriptType = rScHTMLStyle.nDefaultScriptType;\n bInitialized = rScHTMLStyle.bInitialized;\n return *this;\n }\n};\n\nstruct ScHTMLGraphEntry\n{\n ScRange aRange; \/\/ ueberlagerter Zellbereich\n Size aSize; \/\/ Groesse in Pixeln\n Size aSpace; \/\/ Spacing in Pixeln\n SdrObject* pObject;\n bool bInCell; \/\/ ob in Zelle ausgegeben wird\n bool bWritten;\n\n ScHTMLGraphEntry( SdrObject* pObj, const ScRange& rRange,\n const Size& rSize, bool bIn, const Size& rSpace ) :\n aRange( rRange ),\n aSize( rSize ),\n aSpace( rSpace ),\n pObject( pObj ),\n bInCell( bIn ),\n bWritten( false )\n {}\n};\n\n\n#define SC_HTML_FONTSIZES 7\nconst short nIndentMax = 23;\n\nclass ScHTMLExport : public ScExportBase\n{\n \/\/ default HtmlFontSz[1-7]\n static const sal_uInt16 nDefaultFontSize[SC_HTML_FONTSIZES];\n \/\/ HtmlFontSz[1-7] in s*3.ini [user]\n static sal_uInt16 nFontSize[SC_HTML_FONTSIZES];\n static const char* pFontSizeCss[SC_HTML_FONTSIZES];\n static const sal_uInt16 nCellSpacing;\n static const sal_Char sIndentSource[];\n\n typedef boost::scoped_ptr<std::map<OUString, OUString>> FileNameMapPtr;\n typedef boost::ptr_vector< ScHTMLGraphEntry > GraphEntryList;\n\n GraphEntryList aGraphList;\n ScHTMLStyle aHTMLStyle;\n OUString aBaseURL;\n OUString aStreamPath;\n OUString aFilterOptions;\n OUString aCId; \/\/ Content-Id fuer Mail-Export\n OutputDevice* pAppWin; \/\/ fuer Pixelei\n FileNameMapPtr pFileNameMap; \/\/ fuer CopyLocalFileToINet\n OUString aNonConvertibleChars; \/\/ collect nonconvertible characters\n rtl_TextEncoding eDestEnc;\n SCTAB nUsedTables;\n short nIndent;\n sal_Char sIndent[nIndentMax+1];\n bool bAll; \/\/ ganzes Dokument\n bool bTabHasGraphics;\n bool bTabAlignedLeft;\n bool bCalcAsShown;\n bool bCopyLocalFileToINet;\n bool bTableDataWidth;\n bool bTableDataHeight;\n\n const SfxItemSet& PageDefaults( SCTAB nTab );\n\n void WriteBody();\n void WriteHeader();\n void WriteOverview();\n void WriteTables();\n void WriteCell( SCCOL nCol, SCROW nRow, SCTAB nTab );\n void WriteGraphEntry( ScHTMLGraphEntry* );\n void WriteImage( OUString& rLinkName,\n const Graphic&, const OString& rImgOptions,\n sal_uLong nXOutFlags = 0 );\n \/\/ nXOutFlags fuer XOutBitmap::WriteGraphic\n\n \/\/ write to stream if and only if URL fields in edit cell\n bool WriteFieldText( const EditTextObject* pData );\n\n \/\/ kopiere ggfs. eine lokale Datei ins Internet\n bool CopyLocalFileToINet( OUString& rFileNm, const OUString& rTargetNm, bool bFileToFile = false );\n bool HasCId()\n {\n return !aCId.isEmpty();\n }\n void MakeCIdURL( OUString& rURL );\n\n void PrepareGraphics( ScDrawLayer*, SCTAB nTab,\n SCCOL nStartCol, SCROW nStartRow,\n SCCOL nEndCol, SCROW nEndRow );\n\n void FillGraphList( const SdrPage*, SCTAB nTab,\n SCCOL nStartCol, SCROW nStartRow,\n SCCOL nEndCol, SCROW nEndRow );\n\n OString BorderToStyle(const char* pBorderName,\n const editeng::SvxBorderLine* pLine,\n bool& bInsertSemicolon);\n\n sal_uInt16 GetFontSizeNumber( sal_uInt16 nHeight );\n const char* GetFontSizeCss( sal_uInt16 nHeight );\n sal_uInt16 ToPixel( sal_uInt16 nTwips );\n Size MMToPixel( const Size& r100thMMSize );\n void IncIndent( short nVal );\n\n const sal_Char* GetIndentStr()\n {\n return sIndent;\n }\n\npublic:\n ScHTMLExport( SvStream&, const OUString&, ScDocument*, const ScRange&,\n bool bAll, const OUString& aStreamPath, const OUString& rFilterOptions );\n virtual ~ScHTMLExport();\n sal_uLong Write();\n const OUString& GetNonConvertibleChars() const\n {\n return aNonConvertibleChars;\n }\n};\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xlconst.hxx,v $\n *\n * $Revision: 1.27 $\n *\n * last change: $Author: rt $ $Date: 2006-05-05 09:42:07 $\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_XLCONST_HXX\n#define SC_XLCONST_HXX\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n\/\/ Common =====================================================================\n\n\/\/ BIFF versions --------------------------------------------------------------\n\n\/** An enumeration for all Excel file format types (BIFF types). *\/\nenum XclBiff\n{\n EXC_BIFF2 = 0, \/\/\/ MS Excel 2.1\n EXC_BIFF3, \/\/\/ MS Excel 3.0\n EXC_BIFF4, \/\/\/ MS Excel 4.0\n EXC_BIFF5, \/\/\/ MS Excel 5.0, MS Excel 7.0 (95)\n EXC_BIFF8, \/\/\/ MS Excel 8.0 (97), 9.0 (2000), 10.0 (XP), 11.0 (2003)\n EXC_BIFF_UNKNOWN \/\/\/ Unknown BIFF version.\n};\n\n\/\/ Excel sheet dimensions -----------------------------------------------------\n\nconst SCCOL EXC_MAXCOL2 = 255;\nconst SCROW EXC_MAXROW2 = 16383;\nconst SCTAB EXC_MAXTAB2 = 0;\n\nconst SCCOL EXC_MAXCOL3 = EXC_MAXCOL2;\nconst SCROW EXC_MAXROW3 = EXC_MAXROW2;\nconst SCTAB EXC_MAXTAB3 = EXC_MAXTAB2;\n\nconst SCCOL EXC_MAXCOL4 = EXC_MAXCOL3;\nconst SCROW EXC_MAXROW4 = EXC_MAXROW3;\nconst SCTAB EXC_MAXTAB4 = 32767;\n\nconst SCCOL EXC_MAXCOL5 = EXC_MAXCOL4;\nconst SCROW EXC_MAXROW5 = EXC_MAXROW4;\nconst SCTAB EXC_MAXTAB5 = EXC_MAXTAB4;\n\nconst SCCOL EXC_MAXCOL8 = EXC_MAXCOL5;\nconst SCROW EXC_MAXROW8 = 65535;\nconst SCTAB EXC_MAXTAB8 = EXC_MAXTAB5;\n\nconst sal_uInt16 EXC_NOTAB = SAL_MAX_UINT16; \/\/\/ An invalid Excel sheet index, for common use.\nconst SCTAB SCTAB_INVALID = SCTAB_MAX; \/\/\/ An invalid Calc sheet index, for common use.\nconst SCTAB SCTAB_GLOBAL = SCTAB_MAX; \/\/\/ A Calc sheet index for the workbook globals.\n\n\/\/ Storage\/stream names -------------------------------------------------------\n\n#define EXC_STORAGE_OLE_LINKED CREATE_STRING( \"LNK\" )\n#define EXC_STORAGE_OLE_EMBEDDED CREATE_STRING( \"MBD\" )\n#define EXC_STORAGE_VBA_PROJECT CREATE_STRING( \"_VBA_PROJECT_CUR\" )\n#define EXC_STORAGE_VBA CREATE_STRING( \"VBA\" )\n\n#define EXC_STREAM_BOOK CREATE_STRING( \"Book\" )\n#define EXC_STREAM_WORKBOOK CREATE_STRING( \"Workbook\" )\n#define EXC_STREAM_CTLS CREATE_STRING( \"Ctls\" )\n\n\/\/ Encoded URLs ---------------------------------------------------------------\n\nconst sal_Unicode EXC_URLSTART_ENCODED = '\\x01'; \/\/\/ Encoded URL.\nconst sal_Unicode EXC_URLSTART_SELF = '\\x02'; \/\/\/ Reference to own workbook.\nconst sal_Unicode EXC_URLSTART_SELFENCODED = '\\x03'; \/\/\/ Encoded self reference.\nconst sal_Unicode EXC_URLSTART_OWNDOC = '\\x04'; \/\/\/ Reference to own workbook (BIFF5\/BIFF7).\n\nconst sal_Unicode EXC_URL_DOSDRIVE = '\\x01'; \/\/\/ DOS drive letter or UNC server name.\nconst sal_Unicode EXC_URL_DRIVEROOT = '\\x02'; \/\/\/ Root directory of current drive.\nconst sal_Unicode EXC_URL_SUBDIR = '\\x03'; \/\/\/ Directory name delimiter.\nconst sal_Unicode EXC_URL_PARENTDIR = '\\x04'; \/\/\/ Parent directory.\nconst sal_Unicode EXC_URL_RAW = '\\x05'; \/\/\/ Unencoded URL.\nconst sal_Unicode EXC_URL_SHEETNAME = '\\x09'; \/\/\/ Sheet name starts here (BIFF4).\n\nconst sal_Unicode EXC_DDE_DELIM = '\\x03'; \/\/\/ DDE application-topic delimiter\n\n\/\/ Error codes ----------------------------------------------------------------\n\nconst sal_uInt8 EXC_ERR_NULL = 0x00;\nconst sal_uInt8 EXC_ERR_DIV0 = 0x07;\nconst sal_uInt8 EXC_ERR_VALUE = 0x0F;\nconst sal_uInt8 EXC_ERR_REF = 0x17;\nconst sal_uInt8 EXC_ERR_NAME = 0x1D;\nconst sal_uInt8 EXC_ERR_NUM = 0x24;\nconst sal_uInt8 EXC_ERR_NA = 0x2A;\n\n\/\/ Cached values list (EXTERNNAME, ptgArray, ...) -----------------------------\n\nconst sal_uInt8 EXC_CACHEDVAL_EMPTY = 0x00;\nconst sal_uInt8 EXC_CACHEDVAL_DOUBLE = 0x01;\nconst sal_uInt8 EXC_CACHEDVAL_STRING = 0x02;\nconst sal_uInt8 EXC_CACHEDVAL_BOOL = 0x04;\nconst sal_uInt8 EXC_CACHEDVAL_ERROR = 0x10;\n\n\/\/ RK values ------------------------------------------------------------------\n\nconst sal_Int32 EXC_RK_100FLAG = 0x00000001;\nconst sal_Int32 EXC_RK_INTFLAG = 0x00000002;\nconst sal_Int32 EXC_RK_VALUEMASK = 0xFFFFFFFC;\n\nconst sal_Int32 EXC_RK_DBL = 0x00000000;\nconst sal_Int32 EXC_RK_DBL100 = EXC_RK_100FLAG;\nconst sal_Int32 EXC_RK_INT = EXC_RK_INTFLAG;\nconst sal_Int32 EXC_RK_INT100 = EXC_RK_100FLAG | EXC_RK_INTFLAG;\n\n\/\/ Measures -------------------------------------------------------------------\n\nconst sal_Int32 EXC_POINTS_PER_INCH = 72;\nconst sal_Int32 EXC_TWIPS_PER_INCH = EXC_POINTS_PER_INCH * 20;\n\nconst sal_uInt8 EXC_ROT_BOTTOM_TOP = 90; \/\/\/ Vertical rotation bottom->top.\nconst sal_uInt8 EXC_ROT_TOP_BOTTOM = 180; \/\/\/ Vertical rotation top->bottom.\nconst sal_uInt8 EXC_ROT_STACKED = 0xFF; \/\/\/ Characters vertically stacked.\n\n\/\/ Records (ordered by lowest record ID) ======================================\n\n\/\/ (0x0009, 0x0209, 0x0409, 0x0809) BOF ---------------------------------------\n\nconst sal_uInt16 EXC_ID2_BOF = 0x0009;\nconst sal_uInt16 EXC_ID3_BOF = 0x0209;\nconst sal_uInt16 EXC_ID4_BOF = 0x0409;\nconst sal_uInt16 EXC_ID5_BOF = 0x0809;\n\nconst sal_uInt16 EXC_BOF_BIFF2 = 0x0200;\nconst sal_uInt16 EXC_BOF_BIFF3 = 0x0300;\nconst sal_uInt16 EXC_BOF_BIFF4 = 0x0400;\nconst sal_uInt16 EXC_BOF_BIFF5 = 0x0500;\nconst sal_uInt16 EXC_BOF_BIFF8 = 0x0600;\n\nconst sal_uInt16 EXC_BOF_GLOBALS = 0x0005; \/\/\/ BIFF5-BIFF8 workbook globals.\nconst sal_uInt16 EXC_BOF_VBMODULE = 0x0006; \/\/\/ BIFF5-BIFF8 Visual BASIC module.\nconst sal_uInt16 EXC_BOF_SHEET = 0x0010; \/\/\/ Regular worksheet.\nconst sal_uInt16 EXC_BOF_CHART = 0x0020; \/\/\/ Chart sheet.\nconst sal_uInt16 EXC_BOF_MACROSHEET = 0x0040; \/\/\/ Macro sheet.\nconst sal_uInt16 EXC_BOF_WORKSPACE = 0x0100; \/\/\/ Workspace.\nconst sal_uInt16 EXC_BOF_UNKNOWN = 0xFFFF; \/\/\/ Internal use only.\n\n\/\/ (0x000A) EOF ---------------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_EOF = 0x000A;\n\n\/\/ (0x0012) PROTECT -----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_PROTECT = 0x0012;\n\n\/\/ (0x0013) PASSWORD ----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_PASSWORD = 0x0013;\n\n\/\/ (0x0019) WINDOWPROTECT -----------------------------------------------------\n\nconst sal_uInt16 EXC_ID_WINDOWPROTECT = 0x0019;\n\n\/\/ (0x0042) CODEPAGE ----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_CODEPAGE = 0x0042;\n\n\/\/ (0x0081) WSBOOL ------------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_WSBOOL = 0x0081;\n\nconst sal_uInt16 EXC_WSBOOL_ROWBELOW = 0x0040;\nconst sal_uInt16 EXC_WSBOOL_COLBELOW = 0x0080;\nconst sal_uInt16 EXC_WSBOOL_FITTOPAGE = 0x0100;\n\nconst sal_uInt16 EXC_WSBOOL_DEFAULTFLAGS = 0x04C1;\n\n\/\/ (0x008C) COUNTRY -----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_COUNTRY = 0x008C;\n\n\/\/ (0x009B) FILTERMODE --------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_FILTERMODE = 0x009B;\n\n\/\/ (0x009D) AUTOFILTERINFO ----------------------------------------------------\n\nconst sal_uInt16 EXC_ID_AUTOFILTERINFO = 0x009D;\n\n\/\/ (0x009E) AUTOFILTER --------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_AUTOFILTER = 0x009E;\n\n\/\/ (0x0160) USESELFS ----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_USESELFS = 0x0160;\n\n\/\/ (0x01AA,0x01AB) USERSVIEWBEGIN, USERSVIEWEND -------------------------------\n\nconst sal_uInt16 EXC_ID_USERSVIEWBEGIN = 0x01AA;\nconst sal_uInt16 EXC_ID_USERSVIEWEND = 0x01AB;\n\n\/\/ ============================================================================\n\n#endif\n\n<commit_msg>INTEGRATION: CWS chart2mst3 (1.26.10); FILE MERGED 2007\/02\/13 14:02:36 dr 1.26.10.3: #i71697# wrong assertion 2006\/08\/31 10:00:33 dr 1.26.10.2: chart2 export: text formatting, series formatting 2006\/03\/28 15:11:41 dr 1.26.10.1: dumper merged from CWS dr47<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xlconst.hxx,v $\n *\n * $Revision: 1.28 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 19:58:54 $\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_XLCONST_HXX\n#define SC_XLCONST_HXX\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n\/\/ Common =====================================================================\n\n\/\/ BIFF versions --------------------------------------------------------------\n\n\/** An enumeration for all Excel file format types (BIFF types). *\/\nenum XclBiff\n{\n EXC_BIFF2 = 0, \/\/\/ MS Excel 2.1\n EXC_BIFF3, \/\/\/ MS Excel 3.0\n EXC_BIFF4, \/\/\/ MS Excel 4.0\n EXC_BIFF5, \/\/\/ MS Excel 5.0, MS Excel 7.0 (95)\n EXC_BIFF8, \/\/\/ MS Excel 8.0 (97), 9.0 (2000), 10.0 (XP), 11.0 (2003)\n EXC_BIFF_UNKNOWN \/\/\/ Unknown BIFF version.\n};\n\n\/\/ Excel sheet dimensions -----------------------------------------------------\n\nconst SCCOL EXC_MAXCOL2 = 255;\nconst SCROW EXC_MAXROW2 = 16383;\nconst SCTAB EXC_MAXTAB2 = 0;\n\nconst SCCOL EXC_MAXCOL3 = EXC_MAXCOL2;\nconst SCROW EXC_MAXROW3 = EXC_MAXROW2;\nconst SCTAB EXC_MAXTAB3 = EXC_MAXTAB2;\n\nconst SCCOL EXC_MAXCOL4 = EXC_MAXCOL3;\nconst SCROW EXC_MAXROW4 = EXC_MAXROW3;\nconst SCTAB EXC_MAXTAB4 = 32767;\n\nconst SCCOL EXC_MAXCOL5 = EXC_MAXCOL4;\nconst SCROW EXC_MAXROW5 = EXC_MAXROW4;\nconst SCTAB EXC_MAXTAB5 = EXC_MAXTAB4;\n\nconst SCCOL EXC_MAXCOL8 = EXC_MAXCOL5;\nconst SCROW EXC_MAXROW8 = 65535;\nconst SCTAB EXC_MAXTAB8 = EXC_MAXTAB5;\n\nconst sal_uInt16 EXC_NOTAB = SAL_MAX_UINT16; \/\/\/ An invalid Excel sheet index, for common use.\nconst SCTAB SCTAB_INVALID = SCTAB_MAX; \/\/\/ An invalid Calc sheet index, for common use.\nconst SCTAB SCTAB_GLOBAL = SCTAB_MAX; \/\/\/ A Calc sheet index for the workbook globals.\n\n\/\/ Storage\/stream names -------------------------------------------------------\n\n#define EXC_STORAGE_OLE_LINKED CREATE_STRING( \"LNK\" )\n#define EXC_STORAGE_OLE_EMBEDDED CREATE_STRING( \"MBD\" )\n#define EXC_STORAGE_VBA_PROJECT CREATE_STRING( \"_VBA_PROJECT_CUR\" )\n#define EXC_STORAGE_VBA CREATE_STRING( \"VBA\" )\n\n#define EXC_STREAM_BOOK CREATE_STRING( \"Book\" )\n#define EXC_STREAM_WORKBOOK CREATE_STRING( \"Workbook\" )\n#define EXC_STREAM_CTLS CREATE_STRING( \"Ctls\" )\n\n\/\/ Encoded URLs ---------------------------------------------------------------\n\nconst sal_Unicode EXC_URLSTART_ENCODED = '\\x01'; \/\/\/ Encoded URL.\nconst sal_Unicode EXC_URLSTART_SELF = '\\x02'; \/\/\/ Reference to own workbook.\nconst sal_Unicode EXC_URLSTART_SELFENCODED = '\\x03'; \/\/\/ Encoded self reference.\nconst sal_Unicode EXC_URLSTART_OWNDOC = '\\x04'; \/\/\/ Reference to own workbook (BIFF5\/BIFF7).\n\nconst sal_Unicode EXC_URL_DOSDRIVE = '\\x01'; \/\/\/ DOS drive letter or UNC server name.\nconst sal_Unicode EXC_URL_DRIVEROOT = '\\x02'; \/\/\/ Root directory of current drive.\nconst sal_Unicode EXC_URL_SUBDIR = '\\x03'; \/\/\/ Directory name delimiter.\nconst sal_Unicode EXC_URL_PARENTDIR = '\\x04'; \/\/\/ Parent directory.\nconst sal_Unicode EXC_URL_RAW = '\\x05'; \/\/\/ Unencoded URL.\nconst sal_Unicode EXC_URL_SHEETNAME = '\\x09'; \/\/\/ Sheet name starts here (BIFF4).\n\nconst sal_Unicode EXC_DDE_DELIM = '\\x03'; \/\/\/ DDE application-topic delimiter\n\n\/\/ Error codes ----------------------------------------------------------------\n\nconst sal_uInt8 EXC_ERR_NULL = 0x00;\nconst sal_uInt8 EXC_ERR_DIV0 = 0x07;\nconst sal_uInt8 EXC_ERR_VALUE = 0x0F;\nconst sal_uInt8 EXC_ERR_REF = 0x17;\nconst sal_uInt8 EXC_ERR_NAME = 0x1D;\nconst sal_uInt8 EXC_ERR_NUM = 0x24;\nconst sal_uInt8 EXC_ERR_NA = 0x2A;\n\n\/\/ Cached values list (EXTERNNAME, ptgArray, ...) -----------------------------\n\nconst sal_uInt8 EXC_CACHEDVAL_EMPTY = 0x00;\nconst sal_uInt8 EXC_CACHEDVAL_DOUBLE = 0x01;\nconst sal_uInt8 EXC_CACHEDVAL_STRING = 0x02;\nconst sal_uInt8 EXC_CACHEDVAL_BOOL = 0x04;\nconst sal_uInt8 EXC_CACHEDVAL_ERROR = 0x10;\n\n\/\/ RK values ------------------------------------------------------------------\n\nconst sal_Int32 EXC_RK_100FLAG = 0x00000001;\nconst sal_Int32 EXC_RK_INTFLAG = 0x00000002;\nconst sal_Int32 EXC_RK_VALUEMASK = 0xFFFFFFFC;\n\nconst sal_Int32 EXC_RK_DBL = 0x00000000;\nconst sal_Int32 EXC_RK_DBL100 = EXC_RK_100FLAG;\nconst sal_Int32 EXC_RK_INT = EXC_RK_INTFLAG;\nconst sal_Int32 EXC_RK_INT100 = EXC_RK_100FLAG | EXC_RK_INTFLAG;\n\n\/\/ Measures -------------------------------------------------------------------\n\nconst sal_Int32 EXC_POINTS_PER_INCH = 72;\nconst sal_Int32 EXC_TWIPS_PER_INCH = EXC_POINTS_PER_INCH * 20;\n\nconst sal_uInt8 EXC_ORIENT_NONE = 0; \/\/\/ Text orientation: not rotated.\nconst sal_uInt8 EXC_ORIENT_STACKED = 1; \/\/\/ Text orientation: vertically stacked.\nconst sal_uInt8 EXC_ORIENT_90CCW = 2; \/\/\/ Text orientation: 90 deg counterclockwise.\nconst sal_uInt8 EXC_ORIENT_90CW = 3; \/\/\/ Text orientation: 90 deg clockwise.\n\nconst sal_uInt8 EXC_ROT_NONE = 0; \/\/\/ Text rotation: not rotated.\nconst sal_uInt8 EXC_ROT_90CCW = 90; \/\/\/ Text rotation: 90 deg counterclockwise.\nconst sal_uInt8 EXC_ROT_90CW = 180; \/\/\/ Text rotation: 90 deg clockwise.\nconst sal_uInt8 EXC_ROT_STACKED = 255; \/\/\/ Text rotation: vertically stacked.\n\n\/\/ Records (ordered by lowest record ID) ======================================\n\n\/\/ (0x0009, 0x0209, 0x0409, 0x0809) BOF ---------------------------------------\n\nconst sal_uInt16 EXC_ID2_BOF = 0x0009;\nconst sal_uInt16 EXC_ID3_BOF = 0x0209;\nconst sal_uInt16 EXC_ID4_BOF = 0x0409;\nconst sal_uInt16 EXC_ID5_BOF = 0x0809;\n\nconst sal_uInt16 EXC_BOF_BIFF2 = 0x0200;\nconst sal_uInt16 EXC_BOF_BIFF3 = 0x0300;\nconst sal_uInt16 EXC_BOF_BIFF4 = 0x0400;\nconst sal_uInt16 EXC_BOF_BIFF5 = 0x0500;\nconst sal_uInt16 EXC_BOF_BIFF8 = 0x0600;\n\nconst sal_uInt16 EXC_BOF_GLOBALS = 0x0005; \/\/\/ BIFF5-BIFF8 workbook globals.\nconst sal_uInt16 EXC_BOF_VBMODULE = 0x0006; \/\/\/ BIFF5-BIFF8 Visual BASIC module.\nconst sal_uInt16 EXC_BOF_SHEET = 0x0010; \/\/\/ Regular worksheet.\nconst sal_uInt16 EXC_BOF_CHART = 0x0020; \/\/\/ Chart sheet.\nconst sal_uInt16 EXC_BOF_MACROSHEET = 0x0040; \/\/\/ Macro sheet.\nconst sal_uInt16 EXC_BOF_WORKSPACE = 0x0100; \/\/\/ Workspace.\nconst sal_uInt16 EXC_BOF_UNKNOWN = 0xFFFF; \/\/\/ Internal use only.\n\n\/\/ (0x000A) EOF ---------------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_EOF = 0x000A;\n\n\/\/ (0x0012) PROTECT -----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_PROTECT = 0x0012;\n\n\/\/ (0x0013) PASSWORD ----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_PASSWORD = 0x0013;\n\n\/\/ (0x0019) WINDOWPROTECT -----------------------------------------------------\n\nconst sal_uInt16 EXC_ID_WINDOWPROTECT = 0x0019;\n\n\/\/ (0x0042) CODEPAGE ----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_CODEPAGE = 0x0042;\n\n\/\/ (0x0081) WSBOOL ------------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_WSBOOL = 0x0081;\n\nconst sal_uInt16 EXC_WSBOOL_ROWBELOW = 0x0040;\nconst sal_uInt16 EXC_WSBOOL_COLBELOW = 0x0080;\nconst sal_uInt16 EXC_WSBOOL_FITTOPAGE = 0x0100;\n\nconst sal_uInt16 EXC_WSBOOL_DEFAULTFLAGS = 0x04C1;\n\n\/\/ (0x008C) COUNTRY -----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_COUNTRY = 0x008C;\n\n\/\/ (0x009B) FILTERMODE --------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_FILTERMODE = 0x009B;\n\n\/\/ (0x009D) AUTOFILTERINFO ----------------------------------------------------\n\nconst sal_uInt16 EXC_ID_AUTOFILTERINFO = 0x009D;\n\n\/\/ (0x009E) AUTOFILTER --------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_AUTOFILTER = 0x009E;\n\n\/\/ (0x0160) USESELFS ----------------------------------------------------------\n\nconst sal_uInt16 EXC_ID_USESELFS = 0x0160;\n\n\/\/ (0x01AA,0x01AB) USERSVIEWBEGIN, USERSVIEWEND -------------------------------\n\nconst sal_uInt16 EXC_ID_USERSVIEWBEGIN = 0x01AA;\nconst sal_uInt16 EXC_ID_USERSVIEWEND = 0x01AB;\n\n\/\/ ============================================================================\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* Siconos-Kernel, Copyright INRIA 2005-2010.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a 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 * Siconos 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 Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n *\/\n\/*! \\file DynamicalSystemsSet.hpp\nSet of SP::DynamicalSystem\n*\/\n#ifndef DSSET_H\n#define DSSET_H\n\n#include \"DynamicalSystem.hpp\"\n#include \"SiconosSet.hpp\"\n\n#include <boost\/shared_ptr.hpp>\n\n\/** DEPRECATED : A set of pointers to dynamical systems, sorted in a growing order\n according to their numbers *\/\nclass DynamicalSystemsSet : public std::vector<SP::DynamicalSystem>\n{\npublic:\n typedef std::vector<SP::DynamicalSystem>::iterator iterator;\n typedef std::vector<SP::DynamicalSystem>::const_iterator const_iterator;\n DynamicalSystemsSet() {};\n\n bool isEmpty() const\n {\n return size() == 0. ;\n };\n\n SP::DynamicalSystem getPtr(int num) const\n {\n assert(0);\n };\n\n bool isIn(SP::DynamicalSystem& ds)\n {\n bool find = false;\n for (iterator it = begin(); it != end(); ++it)\n {\n if ((*it)->number() == ds->number())\n {\n find = true;\n break;\n }\n }\n return find;\n };\n\n bool isIn(int num)\n {\n bool find = false;\n for (iterator it = begin(); it != end(); ++it)\n {\n if ((*it)->number() == num)\n {\n find = true;\n break;\n }\n }\n return find;\n };\n\n iterator find(int num)\n {\n iterator it;\n for (it = begin(); it != end(); ++it)\n {\n if ((*it)->number() == num)\n {\n break;\n }\n }\n return it;\n };\n\n void insert(SP::DynamicalSystem s)\n {\n this->push_back(s);\n };\n\n void insert(iterator begin,\n iterator end)\n {\n for (iterator it = begin; it != end; ++it)\n {\n insert(*it);\n }\n }\n\n void insert(const_iterator begin,\n const_iterator end)\n {\n for (const_iterator it = begin; it != end; ++it)\n {\n insert(*it);\n }\n }\n\n};\n\n\/** Iterator through a set of DS *\/\ntypedef DynamicalSystemsSet::iterator DSIterator;\n\n\/** const Iterator through a set of DS *\/\ntypedef DynamicalSystemsSet::const_iterator ConstDSIterator;\n\n\/** return type value for insert function - bool = false if insertion\n failed. *\/\ntypedef std::pair<DSIterator, bool> CheckInsertDS;\n\nTYPEDEF_SPTR(DynamicalSystemsSet);\n\n#endif\n<commit_msg>getPtr to avoid warnings<commit_after>\/* Siconos-Kernel, Copyright INRIA 2005-2010.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a 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 * Siconos 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 Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n *\/\n\/*! \\file DynamicalSystemsSet.hpp\nSet of SP::DynamicalSystem\n*\/\n#ifndef DSSET_H\n#define DSSET_H\n\n#include \"DynamicalSystem.hpp\"\n#include \"SiconosSet.hpp\"\n\n#include <boost\/shared_ptr.hpp>\n\n\/** DEPRECATED : A set of pointers to dynamical systems, sorted in a growing order\n according to their numbers *\/\nclass DynamicalSystemsSet : public std::vector<SP::DynamicalSystem>\n{\npublic:\n typedef std::vector<SP::DynamicalSystem>::iterator iterator;\n typedef std::vector<SP::DynamicalSystem>::const_iterator const_iterator;\n DynamicalSystemsSet() {};\n\n bool isEmpty() const\n {\n return size() == 0. ;\n };\n\n SP::DynamicalSystem getPtr(int num)\n {\n SP::DynamicalSystem ds;\n for (iterator it = begin(); it != end(); ++it)\n {\n if ((*it)->number() == ds->number())\n {\n ds = *it;\n break;\n }\n }\n if (!ds) RuntimeException::selfThrow(\"getPtr: dynamicalSystem no found\");\n return ds;\n };\n\n bool isIn(SP::DynamicalSystem& ds)\n {\n bool find = false;\n for (iterator it = begin(); it != end(); ++it)\n {\n if ((*it)->number() == ds->number())\n {\n find = true;\n break;\n }\n }\n return find;\n };\n\n bool isIn(int num)\n {\n bool find = false;\n for (iterator it = begin(); it != end(); ++it)\n {\n if ((*it)->number() == num)\n {\n find = true;\n break;\n }\n }\n return find;\n };\n\n iterator find(int num)\n {\n iterator it;\n for (it = begin(); it != end(); ++it)\n {\n if ((*it)->number() == num)\n {\n break;\n }\n }\n return it;\n };\n\n void insert(SP::DynamicalSystem s)\n {\n this->push_back(s);\n };\n\n void insert(iterator begin,\n iterator end)\n {\n for (iterator it = begin; it != end; ++it)\n {\n insert(*it);\n }\n }\n\n void insert(const_iterator begin,\n const_iterator end)\n {\n for (const_iterator it = begin; it != end; ++it)\n {\n insert(*it);\n }\n }\n\n};\n\n\/** Iterator through a set of DS *\/\ntypedef DynamicalSystemsSet::iterator DSIterator;\n\n\/** const Iterator through a set of DS *\/\ntypedef DynamicalSystemsSet::const_iterator ConstDSIterator;\n\n\/** return type value for insert function - bool = false if insertion\n failed. *\/\ntypedef std::pair<DSIterator, bool> CheckInsertDS;\n\nTYPEDEF_SPTR(DynamicalSystemsSet);\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nThis is the global optimization using the tradeoff tables\n\nWe decide on parameters for each document based on some constraints on meta data size\n\n*\/\n\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define NUM_DOCS 240179\n\ntypedef struct\n{\n int total;\n int numDistinctFrags;\n int numPostings;\n float wsize;\n} linfo;\n\nint comparep(const void* a1, const void* a2)\n{\n linfo* l1 = (linfo*)a1;\n linfo* l2 = (linfo*)a2;\n\n int ret = l1->numPostings - l2->numPostings;\n int ret2 = l1->total - l2->total;\n\n if (ret2 == 0)\n return ret;\n else\n return ret2;\n}\n\nint main(int argc, char** argv)\n{\n linfo* lbuf = new linfo[NUM_DOCS];\n int ptr = 0;\n unsigned* lens = new unsigned[NUM_DOCS];\n memset(lens, 0, NUM_DOCS * sizeof(unsigned));\n char fn[256];\n memset(fn, 0, 256);\n FILE* f2 = fopen(\"finfos\", \"wb\");\n FILE* f3 = fopen(\"\/data\/jhe\/wiki_access\/numv\", \"rb\");\n int size;\n fread(&size, sizeof(unsigned), 1, f3);\n unsigned* lens2 = new unsigned[size];\n fread(lens2, sizeof(unsigned), size, f3);\n fclose(f3);\n\n FILE* f4 = fopen(\"\/data\/jhe\/wiki_access\/word_size\", \"rb\");\n unsigned wlens;\n fread(&wlens, sizeof(unsigned), 1, f4);\n unsigned* dlens = new unsigned[wlens];\n fread(dlens, sizeof(unsigned), wlens, f4);\n fclose(f4);\n int wsize = 0;\n FILE* fexcept = fopen(\"except\", \"w\");\n\n for (int i = 0; i < atoi(argv[1]); i++)\n {\n memset(fn, 0, 256);\n sprintf(fn, \"test\/%d.2\", i);\n FILE* f1 = fopen(fn, \"r\");\n ptr = 0;\n printf(\"processing:%d...\", i);\n if (lens2[i] > 1)\n {\n bool change = false; \n while (fscanf(f1, \"%f\\t%d\\t%d\\t%d\\n\", &lbuf[ptr].wsize, &lbuf[ptr].numDistinctFrags, &lbuf[ptr].total, &lbuf[ptr].numPostings)>0)\n {\n if (ptr > 0 && lbuf[ptr].numPostings != lbuf[ptr-1].numPostings)\n {\n change = true;\n }\n ptr++;\n }\n fclose(f1);\n memset(fn, 0, 256);\n sprintf(fn, \"test\/convert-%d\", i);\n f1 = fopen(fn, \"w\");\n qsort(lbuf, ptr, sizeof(linfo), comparep);\n int ptr1 = 0;\n int ptr2 = 1;\n while (ptr2 < ptr)\n {\n while (ptr2 < ptr && lbuf[ptr2].numPostings >= lbuf[ptr1].numPostings)\n ptr2++;\n\n if (ptr2 >= ptr)\n break;\n\n ptr1++;\n lbuf[ptr1] = lbuf[ptr2];\n ptr2++;\n }\n ptr1++;\n \n for (int j = 0; j < ptr1; j++)\n {\n fprintf(f1, \"%.1f\\t%d\\t%d\\t%d\\n\", lbuf[j].wsize, lbuf[j].total, lbuf[j].numDistinctFrags, lbuf[j].numPostings);\n }\n \n fclose(f1);\n fwrite(lbuf, sizeof(linfo), ptr1, f2);\n lens[i] = ptr1;\n if (change == false)\n {\n fprintf(fexcept, \"%d\\t%d\\n\", i, ptr);\n }\n }\n else\n {\n fclose(f1);\n lens[i] = 1;\n lbuf[0].wsize = dlens[wsize];\n lbuf[0].total = 1;\n lbuf[0].numDistinctFrags = 1;\n lbuf[0].numPostings = dlens[wsize];\n fwrite(lbuf, sizeof(linfo), 1, f2);\n }\n wsize += lens2[i];\n printf(\"done!\\n\");\n }\n\n fclose(fexcept);\n size = atoi(argv[1]);\n FILE* fsize = fopen(\"linfos\", \"wb\");\n fwrite(&size, sizeof(unsigned), 1, fsize);\n fwrite(lens, sizeof(unsigned), size , fsize);\n fclose(fsize);\n fclose(f2);\n return 0;\n}<commit_msg>check if file exists in convert script<commit_after>\/*\n\nThis is the global optimization using the tradeoff tables\n\nWe decide on parameters for each document based on some constraints on meta data size\n\n*\/\n\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define NUM_DOCS 240179\n\ntypedef struct\n{\n int total;\n int numDistinctFrags;\n int numPostings;\n float wsize;\n} linfo;\n\nint comparep(const void* a1, const void* a2)\n{\n linfo* l1 = (linfo*)a1;\n linfo* l2 = (linfo*)a2;\n\n int ret = l1->numPostings - l2->numPostings;\n int ret2 = l1->total - l2->total;\n\n if (ret2 == 0)\n return ret;\n else\n return ret2;\n}\n\nint main(int argc, char** argv)\n{\n linfo* lbuf = new linfo[NUM_DOCS];\n int ptr = 0;\n unsigned* lens = new unsigned[NUM_DOCS];\n memset(lens, 0, NUM_DOCS * sizeof(unsigned));\n char fn[256];\n memset(fn, 0, 256);\n FILE* f2 = fopen(\"finfos\", \"wb\");\n FILE* f3 = fopen(\"\/data\/jhe\/wiki_access\/numv\", \"rb\");\n int size;\n fread(&size, sizeof(unsigned), 1, f3);\n unsigned* lens2 = new unsigned[size];\n fread(lens2, sizeof(unsigned), size, f3);\n fclose(f3);\n\n FILE* f4 = fopen(\"\/data\/jhe\/wiki_access\/word_size\", \"rb\");\n unsigned wlens;\n fread(&wlens, sizeof(unsigned), 1, f4);\n unsigned* dlens = new unsigned[wlens];\n fread(dlens, sizeof(unsigned), wlens, f4);\n fclose(f4);\n int wsize = 0;\n FILE* fexcept = fopen(\"except\", \"w\");\n\n for (int i = 0; i < atoi(argv[1]); i++)\n {\n memset(fn, 0, 256);\n sprintf(fn, \"test\/meta-vs-index-tradeoff-%d\", i);\n FILE* f1 = fopen(fn, \"r\");\n if (!f1) {\n printf(\"skipping:%d...\\n\", i); \n continue;\n }\n ptr = 0;\n printf(\"processing:%d...\", i);\n if (lens2[i] > 1)\n {\n bool change = false; \n while (fscanf(f1, \"%f\\t%d\\t%d\\t%d\\n\", &lbuf[ptr].wsize, &lbuf[ptr].numDistinctFrags, &lbuf[ptr].total, &lbuf[ptr].numPostings)>0)\n {\n if (ptr > 0 && lbuf[ptr].numPostings != lbuf[ptr-1].numPostings)\n {\n change = true;\n }\n ptr++;\n }\n fclose(f1);\n memset(fn, 0, 256);\n sprintf(fn, \"test\/convert-%d\", i);\n f1 = fopen(fn, \"w\");\n qsort(lbuf, ptr, sizeof(linfo), comparep);\n int ptr1 = 0;\n int ptr2 = 1;\n while (ptr2 < ptr)\n {\n while (ptr2 < ptr && lbuf[ptr2].numPostings >= lbuf[ptr1].numPostings)\n ptr2++;\n\n if (ptr2 >= ptr)\n break;\n\n ptr1++;\n lbuf[ptr1] = lbuf[ptr2];\n ptr2++;\n }\n ptr1++;\n \n for (int j = 0; j < ptr1; j++)\n {\n fprintf(f1, \"%.1f\\t%d\\t%d\\t%d\\n\", lbuf[j].wsize, lbuf[j].total, lbuf[j].numDistinctFrags, lbuf[j].numPostings);\n }\n \n fclose(f1);\n fwrite(lbuf, sizeof(linfo), ptr1, f2);\n lens[i] = ptr1;\n if (change == false)\n {\n fprintf(fexcept, \"%d\\t%d\\n\", i, ptr);\n }\n }\n else\n {\n fclose(f1);\n lens[i] = 1;\n lbuf[0].wsize = dlens[wsize];\n lbuf[0].total = 1;\n lbuf[0].numDistinctFrags = 1;\n lbuf[0].numPostings = dlens[wsize];\n fwrite(lbuf, sizeof(linfo), 1, f2);\n }\n wsize += lens2[i];\n printf(\"done!\\n\");\n }\n\n fclose(fexcept);\n size = atoi(argv[1]);\n FILE* fsize = fopen(\"linfos\", \"wb\");\n fwrite(&size, sizeof(unsigned), 1, fsize);\n fwrite(lens, sizeof(unsigned), size , fsize);\n fclose(fsize);\n fclose(f2);\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <type_traits>\n#include <typeinfo>\n#include <functional>\n#include <cstring>\n\ntemplate <size_t ...args>\nstruct static_max;\n\ntemplate <size_t value>\nstruct static_max<value>\n{\n static const size_t result = value;\n};\n\ntemplate <size_t value, size_t ...values>\nstruct static_max<value, values...>\n{\n static const size_t result =\n value > static_max<values...>::result ?\n value :\n static_max<values...>::result;\n};\n\ntemplate <size_t count, typename ...args>\nstruct variant_lookup;\n\ntemplate <size_t count, typename Lookup>\nstruct variant_lookup<count, Lookup>\n{\n static const int result = -1;\n};\n\ntemplate <size_t count, typename Lookup, typename Candidate, typename ...rest>\nstruct variant_lookup<count, Lookup, Candidate, rest...>\n{\n static const int result = std::is_same<Lookup, Candidate>::value ?\n count :\n variant_lookup<count + 1, Lookup, rest...>::result;\n};\n\ntemplate <typename... ContainedTypes>\nstruct Variant\n{\n Variant()\n : type(-1)\n {\n\n }\n\n Variant(const Variant ©)\n : type(copy.type)\n {\n void *origin = ©.data;\n void *destination = &data;\n memcpy(destination, origin, data_size);\n }\n\n Variant(Variant &&) = delete;\n\n template <typename Type>\n explicit Variant(const Type &value)\n : type(variant_lookup<0, Type, ContainedTypes...>::value)\n {\n init(value);\n static_cast<Type>(data) = value;\n }\n\n ~Variant()\n {\n destroy();\n }\n\n template <typename Type>\n void init(const Type &value)\n {\n Type *ptr = reinterpret_cast<Type *>(&data);\n new (ptr) Type(value);\n }\n\n void destroy()\n {\n static std::function<void (void *)> destructors[] =\n { build_destructor<ContainedTypes>()... };\n\n if (type < 0) return;\n\n destructors[type](&data);\n type = -1;\n }\n\n Variant<ContainedTypes...> & operator=(const Variant ©)\n {\n destroy();\n type = copy.type;\n void *origin = ©.data;\n void *destination = &data;\n memcpy(destination, origin, data_size);\n\n return *this;\n }\n\n Variant<ContainedTypes...> & operator=(Variant &&) = delete;\n\n template <typename Type>\n Variant<ContainedTypes...> & operator=(const Type &value)\n {\n destroy();\n type = variant_lookup<0, Type, ContainedTypes...>::result;\n\n init(value);\n\n return *this;\n }\n\n template <typename Evaluator>\n void apply(Evaluator &value)\n {\n static std::function<void (Evaluator &, void *)> dispatchers[] =\n { build_dispatch<Evaluator, ContainedTypes>()... };\n\n dispatchers[type](value, &data);\n }\n\n template <typename Evaluator, typename Target>\n std::function<void (Evaluator &, void *)> build_dispatch()\n {\n return [](Evaluator &functor, void *data)\n {\n auto *v = reinterpret_cast<Target *>(data);\n\n functor.operator()(*v);\n };\n }\n\n template <typename Target>\n std::function<void (void *)> build_destructor()\n {\n return [](void *data)\n {\n auto *v = reinterpret_cast<Target *>(data);\n\n v->~Target();\n };\n }\n\n static const size_t data_size = static_max<sizeof(ContainedTypes)...>::result;\n static const size_t data_align = static_max<alignof(ContainedTypes)...>::result;\n using Storage = typename std::aligned_storage<data_size, data_align>::type;\n\n int type;\n Storage data;\n};\n<commit_msg>Fixed an mistake where we did a redundant operator= operation after doing a copy constructor action.<commit_after>#pragma once\n\n#include <type_traits>\n#include <typeinfo>\n#include <functional>\n#include <cstring>\n\ntemplate <size_t ...args>\nstruct static_max;\n\ntemplate <size_t value>\nstruct static_max<value>\n{\n static const size_t result = value;\n};\n\ntemplate <size_t value, size_t ...values>\nstruct static_max<value, values...>\n{\n static const size_t result =\n value > static_max<values...>::result ?\n value :\n static_max<values...>::result;\n};\n\ntemplate <size_t count, typename ...args>\nstruct variant_lookup;\n\ntemplate <size_t count, typename Lookup>\nstruct variant_lookup<count, Lookup>\n{\n static const int result = -1;\n};\n\ntemplate <size_t count, typename Lookup, typename Candidate, typename ...rest>\nstruct variant_lookup<count, Lookup, Candidate, rest...>\n{\n static const int result = std::is_same<Lookup, Candidate>::value ?\n count :\n variant_lookup<count + 1, Lookup, rest...>::result;\n};\n\ntemplate <typename... ContainedTypes>\nstruct Variant\n{\n Variant()\n : type(-1)\n {\n\n }\n\n Variant(const Variant ©)\n : type(copy.type)\n {\n void *origin = ©.data;\n void *destination = &data;\n memcpy(destination, origin, data_size);\n }\n\n Variant(Variant &&) = delete;\n\n template <typename Type>\n explicit Variant(const Type &value)\n : type(variant_lookup<0, Type, ContainedTypes...>::value)\n {\n init(value);\n }\n\n ~Variant()\n {\n destroy();\n }\n\n template <typename Type>\n void init(const Type &value)\n {\n Type *ptr = reinterpret_cast<Type *>(&data);\n new (ptr) Type(value);\n }\n\n void destroy()\n {\n static std::function<void (void *)> destructors[] =\n { build_destructor<ContainedTypes>()... };\n\n if (type < 0) return;\n\n destructors[type](&data);\n type = -1;\n }\n\n Variant<ContainedTypes...> & operator=(const Variant ©)\n {\n destroy();\n type = copy.type;\n void *origin = ©.data;\n void *destination = &data;\n memcpy(destination, origin, data_size);\n\n return *this;\n }\n\n Variant<ContainedTypes...> & operator=(Variant &&) = delete;\n\n template <typename Type>\n Variant<ContainedTypes...> & operator=(const Type &value)\n {\n destroy();\n type = variant_lookup<0, Type, ContainedTypes...>::result;\n\n init(value);\n\n return *this;\n }\n\n template <typename Evaluator>\n void apply(Evaluator &value)\n {\n static std::function<void (Evaluator &, void *)> dispatchers[] =\n { build_dispatch<Evaluator, ContainedTypes>()... };\n\n dispatchers[type](value, &data);\n }\n\n template <typename Evaluator, typename Target>\n std::function<void (Evaluator &, void *)> build_dispatch()\n {\n return [](Evaluator &functor, void *data)\n {\n auto *v = reinterpret_cast<Target *>(data);\n\n functor.operator()(*v);\n };\n }\n\n template <typename Target>\n std::function<void (void *)> build_destructor()\n {\n return [](void *data)\n {\n auto *v = reinterpret_cast<Target *>(data);\n\n v->~Target();\n };\n }\n\n static const size_t data_size = static_max<sizeof(ContainedTypes)...>::result;\n static const size_t data_align = static_max<alignof(ContainedTypes)...>::result;\n using Storage = typename std::aligned_storage<data_size, data_align>::type;\n\n int type;\n Storage data;\n};\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"ext\/dep_gecode\/version_problem_oc_ih.h\"\n\n\/\/ build: g++ test.cpp -o test ext\/gecode\/dep_selector_to_gecode_interface.o ext\/gecode\/dep_selector_to_gecode.o -lgecodesupport -lgecodekernel -lgecodeint -lgecodesearch \n\nusing namespace std;\n\n\n\nint problem_nosol() {\n VersionProblemOCIH* problem = VersionProblemCreate(10);\n \/\/ package A has versions 0, 1v\n int pkg_a = AddPackage(problem, 0, 1, 1);\n \/\/ package B has versions 0, 1\n int pkg_b = AddPackage(problem, 0, 1, 1);\n \/\/ package C has versions 0, 1\n int pkg_c = AddPackage(problem, 0, 1, 0);\n\n \/\/ A0 depends on B1\n AddVersionConstraint(problem, pkg_a, 0, pkg_b, 1, 1);\n\n \/\/ A1 depends on B0, C0\n AddVersionConstraint(problem, pkg_a, 0, pkg_b, 0, 0);\n AddVersionConstraint(problem, pkg_a, 0, pkg_c, 0, 0);\n\n \/\/ B1 depends on C10, which doesn't even exist...\n AddVersionConstraint(problem, pkg_b, 1, pkg_c, 10, 10);\n\n \/\/ metapackage is a \"ghost\" package whose dependencies are the\n \/\/ solution constraints; thereby forcing packages to be\n \/\/ appropriately constrained\n int metapkg = AddPackage(problem, 0, 0, 0);\n\n cout << \"before adding solution constraints\" << endl;\n VersionProblemPrintPackageVar(problem, pkg_a);\n cout << endl;\n VersionProblemPrintPackageVar(problem, pkg_b);\n cout << endl;\n VersionProblemPrintPackageVar(problem, pkg_c);\n cout << endl;\n VersionProblemPrintPackageVar(problem, metapkg);\n cout << endl;\n\n \/\/ solution constraints: [A,(B=0)], which is satisfiable as A=1, B=0\n \/\/AddVersionConstraint(problem, metapkg, 0, pkg_a, 0, 1);\n \/\/AddVersionConstraint(problem, metapkg, 0, pkg_b, 0, 0);\n \/\/ solution constraints: [(A=0),(B=0)], which is not satisfiable\n AddVersionConstraint(problem, metapkg, 0, pkg_a, 0, 0);\n AddVersionConstraint(problem, metapkg, 0, pkg_b, 0, 0);\n\n cout << \"after adding solution constraints\" << endl;\n VersionProblemPrintPackageVar(problem, pkg_a);\n cout << endl;\n VersionProblemPrintPackageVar(problem, pkg_b);\n cout << endl;\n VersionProblemPrintPackageVar(problem, pkg_c);\n cout << endl;\n VersionProblemPrintPackageVar(problem, metapkg);\n cout << endl;\n\n VersionProblemOCIH *solution = Solve(problem);\n if (solution != NULL) {\n \/\/ solve and interrogate problem\n cout << \"after running solve\" << endl;\n VersionProblemPrintPackageVar(solution, pkg_a);\n cout << endl;\n VersionProblemPrintPackageVar(solution, pkg_b);\n cout << endl;\n VersionProblemPrintPackageVar(solution, pkg_c);\n cout << endl;\n VersionProblemPrintPackageVar(solution, metapkg);\n cout << endl;\n VersionProblemDestroy(solution);\n } else {\n cout << \"No solution\" << endl;\n }\n VersionProblemDestroy(problem);\n\n}\n\n\nint problem_sol() {\n VersionProblemOCIH* problem = VersionProblemCreate(10);\n \/\/ package A has versions 0, 1v\n int pkg_a = AddPackage(problem, 0, 1, 1);\n \/\/ package B has versions 0, 1\n int pkg_b = AddPackage(problem, 0, 1, 1);\n \/\/ package C has versions 0\n int pkg_c = AddPackage(problem, 0, 0, 0);\n\n \/\/ A0 depends on B1\n AddVersionConstraint(problem, pkg_a, 0, pkg_b, 1, 1);\n\n \/\/ A1 depends on B0, C0\n AddVersionConstraint(problem, pkg_a, 0, pkg_b, 0, 0);\n AddVersionConstraint(problem, pkg_a, 0, pkg_c, 0, 0);\n\n \/\/ metapackage is a \"ghost\" package whose dependencies are the\n \/\/ solution constraints; thereby forcing packages to be\n \/\/ appropriately constrained\n int metapkg = AddPackage(problem, 0, 0, 0);\n\n cout << \"before adding solution constraints\" << endl;\n VersionProblemPrintPackageVar(problem, pkg_a);\n cout << endl;\n VersionProblemPrintPackageVar(problem, pkg_b);\n cout << endl;\n VersionProblemPrintPackageVar(problem, pkg_c);\n cout << endl;\n VersionProblemPrintPackageVar(problem, metapkg);\n cout << endl;\n\n \/\/ solution constraints: [A,(B=0)], which is satisfiable as A=1, B=0\n AddVersionConstraint(problem, metapkg, 0, pkg_a, 0, 1);\n AddVersionConstraint(problem, metapkg, 0, pkg_b, 0, 0);\n \/\/ solution constraints: [(A=0),(B=0)], which is not satisfiable\n \/\/AddVersionConstraint(problem, metapkg, 0, pkg_a, 0, 0);\n \/\/AddVersionConstraint(problem, metapkg, 0, pkg_b, 0, 0);\n\n cout << \"after adding solution constraints\" << endl;\n VersionProblemPrintPackageVar(problem, pkg_a);\n cout << endl;\n VersionProblemPrintPackageVar(problem, pkg_b);\n cout << endl;\n VersionProblemPrintPackageVar(problem, pkg_c);\n cout << endl;\n VersionProblemPrintPackageVar(problem, metapkg);\n cout << endl;\n\n VersionProblemOCIH *solution = Solve(problem);\n if (solution != NULL) {\n \/\/ solve and interrogate problem\n cout << \"after running solve\" << endl;\n VersionProblemPrintPackageVar(solution, pkg_a);\n cout << endl;\n VersionProblemPrintPackageVar(solution, pkg_b);\n cout << endl;\n VersionProblemPrintPackageVar(solution, pkg_c);\n cout << endl;\n VersionProblemPrintPackageVar(solution, metapkg);\n cout << endl;\n VersionProblemDestroy(solution);\n } else {\n cout << \"No solution\" << endl;\n }\n VersionProblemDestroy(problem);\n}\n\nint main() {\n problem_nosol();\n}\n<commit_msg>Remove garbage file.<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/framework\/channel.h\"\n\n#include <chrono>\n#include <thread>\n\n#include \"gtest\/gtest.h\"\n\nusing paddle::framework::Channel;\nusing paddle::framework::MakeChannel;\nusing paddle::framework::CloseChannel;\n\nTEST(Channel, MakeAndClose) {\n using paddle::framework::details::Buffered;\n using paddle::framework::details::UnBuffered;\n {\n \/\/ MakeChannel should return a buffered channel is buffer_size > 0.\n auto ch = MakeChannel<int>(10);\n EXPECT_NE(dynamic_cast<Buffered<int> *>(ch), nullptr);\n EXPECT_EQ(dynamic_cast<UnBuffered<int> *>(ch), nullptr);\n CloseChannel(ch);\n delete ch;\n }\n {\n \/\/ MakeChannel should return an un-buffered channel is buffer_size = 0.\n auto ch = MakeChannel<int>(0);\n EXPECT_EQ(dynamic_cast<Buffered<int> *>(ch), nullptr);\n EXPECT_NE(dynamic_cast<UnBuffered<int> *>(ch), nullptr);\n CloseChannel(ch);\n delete ch;\n }\n}\n\nTEST(Channel, SufficientBufferSizeDoesntBlock) {\n const size_t buffer_size = 10;\n auto ch = MakeChannel<size_t>(buffer_size);\n for (size_t i = 0; i < buffer_size; ++i) {\n ch->Send(&i); \/\/ should not block\n }\n\n size_t out;\n for (size_t i = 0; i < buffer_size; ++i) {\n ch->Receive(&out); \/\/ should not block\n EXPECT_EQ(out, i);\n }\n CloseChannel(ch);\n delete ch;\n}\n\nTEST(Channel, ConcurrentSendNonConcurrentReceiveWithSufficientBufferSize) {\n const size_t buffer_size = 10;\n auto ch = MakeChannel<size_t>(buffer_size);\n size_t sum = 0;\n std::thread t([&]() {\n \/\/ Try to write more than buffer size.\n for (size_t i = 0; i < 2 * buffer_size; ++i) {\n ch->Send(&i); \/\/ should block after 10 iterations\n sum += i;\n }\n });\n std::this_thread::sleep_for(std::chrono::milliseconds(100)); \/\/ wait 0.5 sec\n EXPECT_EQ(sum, 45U);\n\n CloseChannel(ch);\n t.join();\n delete ch;\n}\n\nTEST(Channel, SimpleUnbufferedChannelTest) {\n auto ch = MakeChannel<int>(0);\n unsigned sum_send = 0;\n std::thread t([&]() {\n for (int i = 0; i < 5; i++) {\n ch->Send(&i);\n sum_send += i;\n }\n });\n for (int i = 0; i < 5; i++) {\n int recv;\n ch->Receive(&recv);\n EXPECT_EQ(recv, i);\n }\n\n CloseChannel(ch);\n t.join();\n EXPECT_EQ(sum_send, 10U);\n delete ch;\n}\n\n\/\/ This tests that closing an unbuffered channel also unblocks\n\/\/ unblocks any receivers waiting for senders\nTEST(Channel, UnbufferedChannelCloseUnblocksReceiversTest) {\n auto ch = MakeChannel<int>(0);\n size_t num_threads = 5;\n std::thread t[num_threads];\n bool thread_ended[num_threads];\n\n \/\/ Launches threads that try to read and are blocked becausew of no writers\n for (size_t i = 0; i < num_threads; i++) {\n thread_ended[i] = false;\n t[i] = std::thread(\n [&](bool *p) {\n int data;\n ch->Receive(&data);\n *p = true;\n },\n &thread_ended[i]);\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n\n \/\/ Verify that all the threads are blocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], false);\n }\n\n \/\/ Explicitly close the thread\n \/\/ This should unblock all receivers\n CloseChannel(ch);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n\n \/\/ Verify that all threads got unblocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], true);\n }\n\n for (size_t i = 0; i < num_threads; i++) t[i].join();\n delete ch;\n}\n\n\/\/ This tests that closing an unbuffered channel also unblocks\n\/\/ unblocks any senders waiting for senders\nTEST(Channel, UnbufferedChannelCloseUnblocksSendersTest) {\n auto ch = MakeChannel<int>(0);\n size_t num_threads = 5;\n std::thread t[num_threads];\n bool thread_ended[num_threads];\n\n \/\/ Launches threads that try to read and are blocked becausew of no writers\n for (size_t i = 0; i < num_threads; i++) {\n thread_ended[i] = false;\n t[i] = std::thread(\n [&](bool *p) {\n int data = 10;\n ch->Send(&data);\n *p = true;\n },\n &thread_ended[i]);\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n\n \/\/ Verify that all the threads are blocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], false);\n }\n\n \/\/ Explicitly close the thread\n \/\/ This should unblock all receivers\n CloseChannel(ch);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n\n \/\/ Verify that all threads got unblocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], true);\n }\n\n for (size_t i = 0; i < num_threads; i++) t[i].join();\n delete ch;\n}\n\nTEST(Channel, UnbufferedLessReceiveMoreSendTest) {\n auto ch = MakeChannel<int>(0);\n unsigned sum_send = 0;\n \/\/ Send should block after three iterations\n \/\/ since we only have three receivers.\n std::thread t([&]() {\n \/\/ Try to send more number of times\n \/\/ than receivers\n for (int i = 0; i < 4; i++) {\n ch->Send(&i);\n sum_send += i;\n }\n });\n for (int i = 0; i < 3; i++) {\n int recv;\n ch->Receive(&recv);\n EXPECT_EQ(recv, i);\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(100)); \/\/ wait 0.5 sec\n EXPECT_EQ(sum_send, 3U);\n\n CloseChannel(ch);\n t.join();\n delete ch;\n}\n\nTEST(Channel, UnbufferedMoreReceiveLessSendTest) {\n auto ch = MakeChannel<int>(0);\n unsigned sum_send = 0;\n unsigned sum_receive = 0;\n \/\/ The receiver should block after 5\n \/\/ iterations, since there are only 5 senders.\n std::thread t([&]() {\n for (int i = 0; i < 8; i++) {\n int recv;\n ch->Receive(&recv); \/\/ should block after the fifth iteration.\n EXPECT_EQ(recv, i);\n sum_receive += i;\n }\n });\n for (int i = 0; i < 5; i++) {\n ch->Send(&i);\n sum_send += i;\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n EXPECT_EQ(sum_send, 10U);\n EXPECT_EQ(sum_receive, 10U);\n \/\/ send three more elements\n for (int i = 5; i < 8; i++) {\n ch->Send(&i);\n sum_send += i;\n }\n\n CloseChannel(ch);\n t.join();\n EXPECT_EQ(sum_send, 28U);\n EXPECT_EQ(sum_receive, 28U);\n delete ch;\n}\n<commit_msg>Close buffered channel should unblock the blocked senders and receivers (#8109)<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/framework\/channel.h\"\n\n#include <chrono>\n#include <thread>\n\n#include \"gtest\/gtest.h\"\n\nusing paddle::framework::Channel;\nusing paddle::framework::MakeChannel;\nusing paddle::framework::CloseChannel;\n\nTEST(Channel, MakeAndClose) {\n using paddle::framework::details::Buffered;\n using paddle::framework::details::UnBuffered;\n {\n \/\/ MakeChannel should return a buffered channel is buffer_size > 0.\n auto ch = MakeChannel<int>(10);\n EXPECT_NE(dynamic_cast<Buffered<int> *>(ch), nullptr);\n EXPECT_EQ(dynamic_cast<UnBuffered<int> *>(ch), nullptr);\n CloseChannel(ch);\n delete ch;\n }\n {\n \/\/ MakeChannel should return an un-buffered channel is buffer_size = 0.\n auto ch = MakeChannel<int>(0);\n EXPECT_EQ(dynamic_cast<Buffered<int> *>(ch), nullptr);\n EXPECT_NE(dynamic_cast<UnBuffered<int> *>(ch), nullptr);\n CloseChannel(ch);\n delete ch;\n }\n}\n\nTEST(Channel, SufficientBufferSizeDoesntBlock) {\n const size_t buffer_size = 10;\n auto ch = MakeChannel<size_t>(buffer_size);\n for (size_t i = 0; i < buffer_size; ++i) {\n EXPECT_EQ(ch->Send(&i), true); \/\/ should not block\n }\n\n size_t out;\n for (size_t i = 0; i < buffer_size; ++i) {\n EXPECT_EQ(ch->Receive(&out), true); \/\/ should not block\n EXPECT_EQ(out, i);\n }\n CloseChannel(ch);\n delete ch;\n}\n\nTEST(Channel, ConcurrentSendNonConcurrentReceiveWithSufficientBufferSize) {\n const size_t buffer_size = 10;\n auto ch = MakeChannel<size_t>(buffer_size);\n size_t sum = 0;\n std::thread t([&]() {\n \/\/ Try to write more than buffer size.\n for (size_t i = 0; i < 2 * buffer_size; ++i) {\n if (i < buffer_size)\n EXPECT_EQ(ch->Send(&i), true); \/\/ should block after 10 iterations\n else\n EXPECT_EQ(ch->Send(&i), false);\n sum += i;\n }\n });\n std::this_thread::sleep_for(std::chrono::milliseconds(100)); \/\/ wait 0.5 sec\n EXPECT_EQ(sum, 45U);\n\n CloseChannel(ch);\n t.join();\n delete ch;\n}\n\nTEST(Channel, SimpleUnbufferedChannelTest) {\n auto ch = MakeChannel<int>(0);\n unsigned sum_send = 0;\n std::thread t([&]() {\n for (int i = 0; i < 5; i++) {\n EXPECT_EQ(ch->Send(&i), true);\n sum_send += i;\n }\n });\n for (int i = 0; i < 5; i++) {\n int recv;\n EXPECT_EQ(ch->Receive(&recv), true);\n EXPECT_EQ(recv, i);\n }\n\n CloseChannel(ch);\n t.join();\n EXPECT_EQ(sum_send, 10U);\n delete ch;\n}\n\n\/\/ This tests that closing a buffered channel also unblocks\n\/\/ any receivers waiting on the channel\nTEST(Channel, BufferedChannelCloseUnblocksReceiversTest) {\n auto ch = MakeChannel<int>(1);\n size_t num_threads = 5;\n std::thread t[num_threads];\n bool thread_ended[num_threads];\n\n \/\/ Launches threads that try to read and are blocked because of no writers\n for (size_t i = 0; i < num_threads; i++) {\n thread_ended[i] = false;\n t[i] = std::thread(\n [&](bool *p) {\n int data;\n \/\/ All reads should return false\n EXPECT_EQ(ch->Receive(&data), false);\n *p = true;\n },\n &thread_ended[i]);\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(100)); \/\/ wait\n\n \/\/ Verify that all threads are blocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], false);\n }\n\n \/\/ Explicitly close the channel\n \/\/ This should unblock all receivers\n CloseChannel(ch);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(200)); \/\/ wait\n\n \/\/ Verify that all threads got unblocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], true);\n }\n\n for (size_t i = 0; i < num_threads; i++) t[i].join();\n delete ch;\n}\n\n\/\/ This tests that closing a buffered channel also unblocks\n\/\/ any senders waiting for channel to have write space\nTEST(Channel, BufferedChannelCloseUnblocksSendersTest) {\n auto ch = MakeChannel<int>(1);\n size_t num_threads = 5;\n std::thread t[num_threads];\n bool thread_ended[num_threads];\n bool send_success[num_threads];\n\n \/\/ Launches threads that try to write and are blocked because of no readers\n for (size_t i = 0; i < num_threads; i++) {\n thread_ended[i] = false;\n send_success[i] = false;\n t[i] = std::thread(\n [&](bool *ended, bool *success) {\n int data = 10;\n *success = ch->Send(&data);\n *ended = true;\n },\n &thread_ended[i], &send_success[i]);\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(100)); \/\/ wait\n\n \/\/ Verify that atleast 4 threads are blocked\n int ct = 0;\n for (size_t i = 0; i < num_threads; i++) {\n if (thread_ended[i] == false) ct++;\n }\n \/\/ Atleast 4 threads must be blocked\n EXPECT_GE(ct, 4);\n\n \/\/ Explicitly close the thread\n \/\/ This should unblock all senders\n CloseChannel(ch);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(200)); \/\/ wait\n\n \/\/ Verify that all threads got unblocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], true);\n }\n\n \/\/ Verify that only 1 send was successful\n ct = 0;\n for (size_t i = 0; i < num_threads; i++) {\n if (send_success[i]) ct++;\n }\n \/\/ Only 1 send must be successful\n EXPECT_EQ(ct, 1);\n\n for (size_t i = 0; i < num_threads; i++) t[i].join();\n delete ch;\n}\n\n\/\/ This tests that closing an unbuffered channel also unblocks\n\/\/ unblocks any receivers waiting for senders\nTEST(Channel, UnbufferedChannelCloseUnblocksReceiversTest) {\n auto ch = MakeChannel<int>(0);\n size_t num_threads = 5;\n std::thread t[num_threads];\n bool thread_ended[num_threads];\n\n \/\/ Launches threads that try to read and are blocked becausew of no writers\n for (size_t i = 0; i < num_threads; i++) {\n thread_ended[i] = false;\n t[i] = std::thread(\n [&](bool *p) {\n int data;\n EXPECT_EQ(ch->Receive(&data), false);\n *p = true;\n },\n &thread_ended[i]);\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n\n \/\/ Verify that all the threads are blocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], false);\n }\n\n \/\/ Explicitly close the thread\n \/\/ This should unblock all receivers\n CloseChannel(ch);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n\n \/\/ Verify that all threads got unblocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], true);\n }\n\n for (size_t i = 0; i < num_threads; i++) t[i].join();\n delete ch;\n}\n\n\/\/ This tests that closing an unbuffered channel also unblocks\n\/\/ unblocks any senders waiting for senders\nTEST(Channel, UnbufferedChannelCloseUnblocksSendersTest) {\n auto ch = MakeChannel<int>(0);\n size_t num_threads = 5;\n std::thread t[num_threads];\n bool thread_ended[num_threads];\n\n \/\/ Launches threads that try to read and are blocked becausew of no writers\n for (size_t i = 0; i < num_threads; i++) {\n thread_ended[i] = false;\n t[i] = std::thread(\n [&](bool *p) {\n int data = 10;\n EXPECT_EQ(ch->Send(&data), false);\n *p = true;\n },\n &thread_ended[i]);\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n\n \/\/ Verify that all the threads are blocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], false);\n }\n\n \/\/ Explicitly close the thread\n \/\/ This should unblock all receivers\n CloseChannel(ch);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n\n \/\/ Verify that all threads got unblocked\n for (size_t i = 0; i < num_threads; i++) {\n EXPECT_EQ(thread_ended[i], true);\n }\n\n for (size_t i = 0; i < num_threads; i++) t[i].join();\n delete ch;\n}\n\nTEST(Channel, UnbufferedLessReceiveMoreSendTest) {\n auto ch = MakeChannel<int>(0);\n unsigned sum_send = 0;\n \/\/ Send should block after three iterations\n \/\/ since we only have three receivers.\n std::thread t([&]() {\n \/\/ Try to send more number of times\n \/\/ than receivers\n for (int i = 0; i < 4; i++) {\n ch->Send(&i);\n sum_send += i;\n }\n });\n for (int i = 0; i < 3; i++) {\n int recv;\n ch->Receive(&recv);\n EXPECT_EQ(recv, i);\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(100)); \/\/ wait 0.5 sec\n EXPECT_EQ(sum_send, 3U);\n\n CloseChannel(ch);\n t.join();\n delete ch;\n}\n\nTEST(Channel, UnbufferedMoreReceiveLessSendTest) {\n auto ch = MakeChannel<int>(0);\n unsigned sum_send = 0;\n unsigned sum_receive = 0;\n \/\/ The receiver should block after 5\n \/\/ iterations, since there are only 5 senders.\n std::thread t([&]() {\n for (int i = 0; i < 8; i++) {\n int recv;\n ch->Receive(&recv); \/\/ should block after the fifth iteration.\n EXPECT_EQ(recv, i);\n sum_receive += i;\n }\n });\n for (int i = 0; i < 5; i++) {\n ch->Send(&i);\n sum_send += i;\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); \/\/ wait 0.5 sec\n EXPECT_EQ(sum_send, 10U);\n EXPECT_EQ(sum_receive, 10U);\n \/\/ send three more elements\n for (int i = 5; i < 8; i++) {\n ch->Send(&i);\n sum_send += i;\n }\n\n CloseChannel(ch);\n t.join();\n EXPECT_EQ(sum_send, 28U);\n EXPECT_EQ(sum_receive, 28U);\n delete ch;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"chrome\/browser\/extensions\/external_pref_extension_provider.h\"\n\n#include \"app\/app_paths.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/version.h\"\n#include \"chrome\/common\/json_value_serializer.h\"\n\n\/\/ Constants for keeping track of extension preferences.\nconst wchar_t kLocation[] = L\"location\";\nconst wchar_t kState[] = L\"state\";\nconst wchar_t kExternalCrx[] = L\"external_crx\";\nconst wchar_t kExternalVersion[] = L\"external_version\";\n\nExternalPrefExtensionProvider::ExternalPrefExtensionProvider() {\n FilePath json_file;\n PathService::Get(app::DIR_EXTERNAL_EXTENSIONS, &json_file);\n json_file = json_file.Append(FILE_PATH_LITERAL(\"external_extensions.json\"));\n\n JSONFileValueSerializer serializer(json_file);\n SetPreferences(&serializer);\n}\n\nExternalPrefExtensionProvider::~ExternalPrefExtensionProvider() {\n}\n\nvoid ExternalPrefExtensionProvider::SetPreferencesForTesting(\n std::string json_data_for_testing) {\n JSONStringValueSerializer serializer(json_data_for_testing);\n SetPreferences(&serializer);\n}\n\nvoid ExternalPrefExtensionProvider::VisitRegisteredExtension(\n Visitor* visitor, const std::set<std::string>& ids_to_ignore) const {\n for (DictionaryValue::key_iterator i = prefs_->begin_keys();\n i != prefs_->end_keys(); ++i) {\n const std::wstring& extension_id = *i;\n if (ids_to_ignore.find(WideToASCII(extension_id)) != ids_to_ignore.end())\n continue;\n\n DictionaryValue* extension = NULL;\n if (!prefs_->GetDictionary(extension_id, &extension)) {\n continue;\n }\n\n FilePath::StringType external_crx;\n std::string external_version;\n if (!extension->GetString(kExternalCrx, &external_crx) ||\n !extension->GetString(kExternalVersion, &external_version)) {\n LOG(WARNING) << \"Malformed extension dictionary for extension: \"\n << extension_id.c_str();\n continue;\n }\n\n if (external_crx.find(FilePath::kParentDirectory) != StringPiece::npos) {\n LOG(WARNING) << \"Path traversal not allowed in path: \"\n << external_crx.c_str();\n continue;\n }\n\n \/\/ See if it's an absolute path...\n FilePath path(external_crx);\n if (!path.IsAbsolute()) {\n \/\/ Try path as relative path from external extension dir.\n FilePath base_path;\n PathService::Get(app::DIR_EXTERNAL_EXTENSIONS, &base_path);\n path = base_path.Append(external_crx);\n }\n\n scoped_ptr<Version> version;\n version.reset(Version::GetVersionFromString(external_version));\n visitor->OnExternalExtensionFound(\n WideToASCII(extension_id), version.get(), path);\n }\n}\n\nVersion* ExternalPrefExtensionProvider::RegisteredVersion(\n std::string id, Extension::Location* location) const {\n DictionaryValue* extension = NULL;\n if (!prefs_->GetDictionary(ASCIIToWide(id), &extension))\n return NULL;\n\n std::string external_version;\n if (!extension->GetString(kExternalVersion, &external_version))\n return NULL;\n\n if (location)\n *location = Extension::EXTERNAL_PREF;\n return Version::GetVersionFromString(external_version);\n}\n\nvoid ExternalPrefExtensionProvider::SetPreferences(\n ValueSerializer* serializer) {\n std::string error_msg;\n Value* extensions = serializer->Deserialize(&error_msg);\n scoped_ptr<DictionaryValue> dictionary(new DictionaryValue());\n if (!error_msg.empty()) {\n NOTREACHED() << L\"Unable to deserialize json data: \"\n << error_msg.c_str();\n } else {\n \/\/ This can be null if the json file specified does not exist.\n if (extensions) {\n if (!extensions->IsType(Value::TYPE_DICTIONARY)) {\n NOTREACHED() << L\"Invalid json data\";\n } else {\n dictionary.reset(static_cast<DictionaryValue*>(extensions));\n }\n }\n }\n prefs_.reset(dictionary.release());\n}\n<commit_msg>Fix build. <commit_after>\/\/ 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 \"chrome\/browser\/extensions\/external_pref_extension_provider.h\"\n\n#include \"app\/app_paths.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/version.h\"\n#include \"chrome\/common\/json_value_serializer.h\"\n\n\/\/ Constants for keeping track of extension preferences.\nconst wchar_t kLocation[] = L\"location\";\nconst wchar_t kState[] = L\"state\";\nconst wchar_t kExternalCrx[] = L\"external_crx\";\nconst wchar_t kExternalVersion[] = L\"external_version\";\n\nExternalPrefExtensionProvider::ExternalPrefExtensionProvider() {\n FilePath json_file;\n PathService::Get(app::DIR_EXTERNAL_EXTENSIONS, &json_file);\n json_file = json_file.Append(FILE_PATH_LITERAL(\"external_extensions.json\"));\n\n JSONFileValueSerializer serializer(json_file);\n SetPreferences(&serializer);\n}\n\nExternalPrefExtensionProvider::~ExternalPrefExtensionProvider() {\n}\n\nvoid ExternalPrefExtensionProvider::SetPreferencesForTesting(\n std::string json_data_for_testing) {\n JSONStringValueSerializer serializer(json_data_for_testing);\n SetPreferences(&serializer);\n}\n\nvoid ExternalPrefExtensionProvider::VisitRegisteredExtension(\n Visitor* visitor, const std::set<std::string>& ids_to_ignore) const {\n for (DictionaryValue::key_iterator i = prefs_->begin_keys();\n i != prefs_->end_keys(); ++i) {\n const std::wstring& extension_id = *i;\n if (ids_to_ignore.find(WideToASCII(extension_id)) != ids_to_ignore.end())\n continue;\n\n DictionaryValue* extension = NULL;\n if (!prefs_->GetDictionary(extension_id, &extension)) {\n continue;\n }\n\n FilePath::StringType external_crx;\n std::string external_version;\n if (!extension->GetString(kExternalCrx, &external_crx) ||\n !extension->GetString(kExternalVersion, &external_version)) {\n LOG(WARNING) << \"Malformed extension dictionary for extension: \"\n << extension_id.c_str();\n continue;\n }\n\n if (external_crx.find(FilePath::kParentDirectory) != StringPiece::npos) {\n LOG(WARNING) << \"Path traversal not allowed in path: \"\n << external_crx.c_str();\n continue;\n }\n\n \/\/ See if it's an absolute path...\n FilePath path(external_crx);\n if (!path.IsAbsolute()) {\n \/\/ Try path as relative path from external extension dir.\n FilePath base_path;\n PathService::Get(app::DIR_EXTERNAL_EXTENSIONS, &base_path);\n path = base_path.Append(external_crx);\n }\n\n scoped_ptr<Version> version;\n version.reset(Version::GetVersionFromString(external_version));\n visitor->OnExternalExtensionFound(\n WideToASCII(extension_id), version.get(), path);\n }\n}\n\nVersion* ExternalPrefExtensionProvider::RegisteredVersion(\n std::string id, Extension::Location* location) const {\n DictionaryValue* extension = NULL;\n if (!prefs_->GetDictionary(ASCIIToWide(id), &extension))\n return NULL;\n\n std::string external_version;\n if (!extension->GetString(kExternalVersion, &external_version))\n return NULL;\n\n if (location)\n *location = Extension::EXTERNAL_PREF;\n return Version::GetVersionFromString(external_version);\n}\n\nvoid ExternalPrefExtensionProvider::SetPreferences(\n ValueSerializer* serializer) {\n std::string error_msg;\n Value* extensions = serializer->Deserialize(&error_msg);\n scoped_ptr<DictionaryValue> dictionary(new DictionaryValue());\n if (!error_msg.empty()) {\n LOG(WARNING) << L\"Unable to deserialize json data: \"\n << error_msg.c_str();\n } else {\n \/\/ This can be null if the json file specified does not exist.\n if (extensions) {\n if (!extensions->IsType(Value::TYPE_DICTIONARY)) {\n NOTREACHED() << L\"Invalid json data\";\n } else {\n dictionary.reset(static_cast<DictionaryValue*>(extensions));\n }\n }\n }\n prefs_.reset(dictionary.release());\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <climits>\n#include <fyut.h>\n#include <new> \/\/ nothrow\n#include<libgen.h>\n\/*\nDescription _fullpath converts the relative path name name 'pathname'\n to a fully qualified pathname, stored in 'buffer'. The\n relative path can contain \".\\\" and \"..\".\n\n The maximum size of the supplied buffer is 'maxlen'.\n If the fully qualified path is longer than 'maxlen',\n NULL is returned. The buffer should be at least _MAX_PATH\n bytes long (this constant is defined in stdlib.h).\n\n If 'buffer' is NULL, a buffer to store the fully qualified\n path is allocated and is returned. The calling program\n must free this buffer with GlobalFree(() when it is no longer needed.\n\n If the pathname does not specify a disk drive, the current\ni drive is used.\n\n Allocate a temporary buffer to hold the fully qualified path.\nif ((tempbuf = (char*)UT_MALLOC(_MAX_PATH*2+1)) == NULL)\n return (NULL);\n\n\nreturn (char*)(realloc(tempbuf,len));\n*\/\n\nchar * _ffullpath(char *buffer, const char *pathname, size_t maxlen) {\n\tif(maxlen < _MAX_PATH) {\n\t\treturn NULL;\n\t}\n\tchar * wpath;\n\twpath = new (std::nothrow) char[_MAX_PATH];\n\tif (wpath == NULL) { \/\/ could not allocate memory\n\t\treturn NULL;\n\t}\n\t\n\tchar * wpath2;\n\twpath2 = new (std::nothrow) char[_MAX_PATH];\n\tif (wpath2 == NULL) {\n\t\tdelete [] wpath;\n\t\treturn NULL;\n\t}\n\n\tstrncpy(wpath, pathname, _MAX_PATH);\t\n\tstrncpy(wpath2, pathname, _MAX_PATH);\n\n\t\/* Make relativer paths of .\/foo-paths *\/\n\tif(pathname[0] == '.' && pathname[1] == UT_SLASH) {\n\t\tstrncpy(wpath, pathname+2, _MAX_PATH);\n\t\tstrncpy(wpath, pathname+2, _MAX_PATH);\n\t}\n\n\tchar * prevPos = NULL;\n\t\n\tchar same[4] = { UT_SLASH, '.', UT_SLASH, '\\0' }; \/\/ e.g. \"\/.\/\"\n \/* replace \/.\/ with nothing *\/\n while ((prevPos = strstr(wpath, same)) != NULL) {\n prevPos[1] = '\\0';\n UT_StrCopy(wpath2, wpath, _MAX_PATH);\n strncat(wpath2, (prevPos+strlen(same)), _MAX_PATH);\n UT_StrCopy(wpath, wpath2, _MAX_PATH);\n }\n\tchar prev[5] = { UT_SLASH, '.', '.', UT_SLASH, '\\0' }; \/\/ e.g \"\/..\/\"\n\n\tint i = -1;\n\t\/* Remove \/..\/ and parent folder *\/\n\twhile ((prevPos = strstr(wpath, prev)) != NULL) {\n\t\t\/* Walk forward in the string until first slash or start of string *\/\n\t\twhile((prevPos + i) >= wpath && prevPos[i] != UT_SLASH) {\n\t\t\tprevPos[i--] = '\\0';\n\t\t}\n\t\tUT_StrCopy(wpath2, wpath, _MAX_PATH);\n\t\tstrncat(wpath2, (prevPos+strlen(prev)), _MAX_PATH);\n\t\tUT_StrCopy(wpath, wpath2, _MAX_PATH);\n\t\ti = -1;\n\t}\n\t\n\t\/* prepend cwd on relative paths *\/\n\tif(wpath[0] != UT_SLASH) {\n\t\tif(getcwd(wpath2, _MAX_PATH) == NULL) {\n\t\t\tdelete [] wpath;\n\t\t delete [] wpath2;\n\t\t\treturn NULL;\n\t\t}\n\t\t\/* getcwd gives ut the path w\/o ending slash *\/\n\t\tstrncat(wpath2, UT_STR_SLASH, _MAX_PATH-(strlen(wpath2)+1));\n\t\tstrncat(wpath2, wpath, _MAX_PATH)-(strlen(wpath2)+1);\n\t\tUT_StrCopy(wpath, wpath2, _MAX_PATH);\n\t}\n\n\tint endLen = strlen(wpath);\n\tint startAt = 0;\n\tif(wpath[0] == '\/') { \n\t\tendLen--;\n\t\tstartAt = 1;\n\t}\n\tdelete [] wpath2;\n\tif (endLen < maxlen && buffer != NULL) { \/* we have a buffer, and we have room in buffer *\/\n \tUT_StrCopy(buffer, (wpath+startAt), maxlen);\n\t\tdelete [] wpath;\n\t\treturn buffer;\n\t} else if (buffer == NULL) { \/* we have no buffer *\/\n\t\tchar * tempbuf;\n\t\tif ((tempbuf = (char*)UT_MALLOC(endLen+1)) != NULL) {\n\t\t\tUT_StrCopy(tempbuf, (wpath+startAt), (endLen+1));\n\t\t\tdelete [] wpath;\n\t\t\treturn tempbuf;\n\t\t} else { \/* failed to alloc memory*\/\n\t\t\tdelete [] wpath;\n return NULL;\n\t\t}\n\t} else { \/* not room in buffer and we were supposed to use the buffer *\/\n\t\tdelete [] wpath;\n\t\treturn NULL;\n\t}\n}\n\nint main(int argc, char** args) {\n\tif(argc < 2) {\n\t\texit(1);\n\t}\n\/\/ char absPath[_MAX_PATH], absPath2[_MAX_PATH];\n\/\/\tabsPath[0] = '\\0';\n\/\/\tabsPath2[0] = '\\0';\n\tchar * absPath; char * absPath2;\n\tabsPath2 = _ffullpath(NULL, args[1], _MAX_PATH); \n\tabsPath = _fullpath (NULL, args[1], _MAX_PATH);\n\tif (absPath == NULL || absPath2 == NULL) {\n\t\tif (absPath == NULL)\n\t\t\tprintf(\"\\x1b[%dmPRIO returned NULL\\x1b[0m\\n\\n\", 31);\n\t\tif (absPath2 == NULL)\n\t\t\tprintf(\"\\x1b[%dmFREE returned NULL\\x1b[0m\\n\\n\", 31);\n\t\t\n\t\treturn 0;\n\t}\n\tif (!(strcmp(absPath, absPath2) == 0)) {\n\t\tprintf(\"\\x1b[%dmPRIO: '%s'\\n\", 31, absPath);\n\t\tprintf(\"FREE: '%s'\\x1b[0m\\n\\n\", absPath2); \t\t\n\t} else {\n\t\tprintf(\"\\x1b[%dmBOTH: '%s'\\x1b[0m\\n\\n\", 32, absPath);\n\t}\n\tUT_FREE(absPath); UT_FREE(absPath2);\n}\n\n<commit_msg>Cleanup headers, better docs<commit_after>#include <cstdlib> \/\/ malloc etc\n#include <cstring> \/\/ strcat etc \n#include <new> \/\/ nothrow\n#include <fyut.h>\n\n\/*\nCH _ffullpath \nCD ==============================================================\nCD Makes a complete path from a non-complete path. Handles \"..\",\nCD \".\" and will prepend the path with current working directory\nCD if it is relative (does not start with slash)\nCD\nCD The function returns buffer, pointer to memory area containing \nCD full path if buffer was NULL, or NULL if a error occured\nCD (e.g. full path was longer than maxlen and a buffer \nCD was supplied.) The pointer should be free'd by calling code.\nCD\nCD Parameters:\nCD Type Name I\/O Explanation\nCD -------------------------------------------------------------\nCD char *buffer i\/o Buffer to put full path into or NULL.\nCD const char *pathname i Pathname to expand\nCD size_t maxlen i Size of buffer.\nCD char * r buffer, pointer to char[] or NULL\nCD ==============================================================\n*\/\nchar * _ffullpath(char *buffer, const char *pathname, size_t maxlen) {\n\tif(maxlen < _MAX_PATH) {\n\t\treturn NULL;\n\t}\n\tchar * wpath;\n\twpath = new (std::nothrow) char[_MAX_PATH];\n\tif (wpath == NULL) { \/\/ could not allocate memory\n\t\treturn NULL;\n\t}\n\t\n\tchar * wpath2;\n\twpath2 = new (std::nothrow) char[_MAX_PATH];\n\tif (wpath2 == NULL) {\n\t\tdelete [] wpath;\n\t\treturn NULL;\n\t}\n\n\tstrncpy(wpath, pathname, _MAX_PATH);\t\n\tstrncpy(wpath2, pathname, _MAX_PATH);\n\n\t\/* Make relativer paths of .\/foo-paths *\/\n\tif(pathname[0] == '.' && pathname[1] == UT_SLASH) {\n\t\tstrncpy(wpath, pathname+2, _MAX_PATH);\n\t\tstrncpy(wpath, pathname+2, _MAX_PATH);\n\t}\n\n\tchar * prevPos = NULL;\n\t\n\tchar same[4] = { UT_SLASH, '.', UT_SLASH, '\\0' }; \/\/ e.g. \"\/.\/\"\n \/* replace \/.\/ with nothing *\/\n while ((prevPos = strstr(wpath, same)) != NULL) {\n prevPos[1] = '\\0';\n UT_StrCopy(wpath2, wpath, _MAX_PATH);\n strncat(wpath2, (prevPos+strlen(same)), _MAX_PATH);\n UT_StrCopy(wpath, wpath2, _MAX_PATH);\n }\n\tchar prev[5] = { UT_SLASH, '.', '.', UT_SLASH, '\\0' }; \/\/ e.g \"\/..\/\"\n\n\tint i = -1;\n\t\/* Remove \/..\/ and parent folder *\/\n\twhile ((prevPos = strstr(wpath, prev)) != NULL) {\n\t\t\/* Walk forward in the string until first slash or start of string *\/\n\t\twhile((prevPos + i) >= wpath && prevPos[i] != UT_SLASH) {\n\t\t\tprevPos[i--] = '\\0';\n\t\t}\n\t\tUT_StrCopy(wpath2, wpath, _MAX_PATH);\n\t\tstrncat(wpath2, (prevPos+strlen(prev)), _MAX_PATH);\n\t\tUT_StrCopy(wpath, wpath2, _MAX_PATH);\n\t\ti = -1;\n\t}\n\t\n\t\/* prepend cwd on relative paths *\/\n\tif(wpath[0] != UT_SLASH) {\n\t\tif(getcwd(wpath2, _MAX_PATH) == NULL) {\n\t\t\tdelete [] wpath;\n\t\t delete [] wpath2;\n\t\t\treturn NULL;\n\t\t}\n\t\t\/* getcwd gives ut the path w\/o ending slash *\/\n\t\tstrncat(wpath2, UT_STR_SLASH, _MAX_PATH-(strlen(wpath2)+1));\n\t\tstrncat(wpath2, wpath, _MAX_PATH)-(strlen(wpath2)+1);\n\t\tUT_StrCopy(wpath, wpath2, _MAX_PATH);\n\t}\n\n\tint endLen = strlen(wpath);\n\tint startAt = 0;\n\tif(wpath[0] == '\/') { \n\t\tendLen--;\n\t\tstartAt = 1;\n\t}\n\tdelete [] wpath2;\n\tif (endLen < maxlen && buffer != NULL) { \/* we have a buffer, and we have room in buffer *\/\n \tUT_StrCopy(buffer, (wpath+startAt), maxlen);\n\t\tdelete [] wpath;\n\t\treturn buffer;\n\t} else if (buffer == NULL) { \/* we have no buffer *\/\n\t\tchar * tempbuf;\n\t\tif ((tempbuf = (char*)UT_MALLOC(endLen+1)) != NULL) {\n\t\t\tUT_StrCopy(tempbuf, (wpath+startAt), (endLen+1));\n\t\t\tdelete [] wpath;\n\t\t\treturn tempbuf;\n\t\t} else { \/* failed to alloc memory*\/\n\t\t\tdelete [] wpath;\n return NULL;\n\t\t}\n\t} else { \/* not room in buffer and we were supposed to use the buffer *\/\n\t\tdelete [] wpath;\n\t\treturn NULL;\n\t}\n}\n\nint main(int argc, char** args) {\n\tif(argc < 2) {\n\t\texit(1);\n\t}\n\/\/ char absPath[_MAX_PATH], absPath2[_MAX_PATH];\n\/\/\tabsPath[0] = '\\0';\n\/\/\tabsPath2[0] = '\\0';\n\tchar * absPath; char * absPath2;\n\tabsPath2 = _ffullpath(NULL, args[1], _MAX_PATH); \n\tabsPath = _fullpath (NULL, args[1], _MAX_PATH);\n\tif (absPath == NULL || absPath2 == NULL) {\n\t\tif (absPath == NULL)\n\t\t\tprintf(\"\\x1b[%dmPRIO returned NULL\\x1b[0m\\n\\n\", 31);\n\t\tif (absPath2 == NULL)\n\t\t\tprintf(\"\\x1b[%dmFREE returned NULL\\x1b[0m\\n\\n\", 31);\n\t\t\n\t\treturn 0;\n\t}\n\tif (!(strcmp(absPath, absPath2) == 0)) {\n\t\tprintf(\"\\x1b[%dmPRIO: '%s'\\n\", 31, absPath);\n\t\tprintf(\"FREE: '%s'\\x1b[0m\\n\\n\", absPath2); \t\t\n\t} else {\n\t\tprintf(\"\\x1b[%dmBOTH: '%s'\\x1b[0m\\n\\n\", 32, absPath);\n\t}\n\tUT_FREE(absPath); UT_FREE(absPath2);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) Microsoft. All rights reserved.\n\n\/\/ ConsoleApplication.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"pch.h\"\n\n#include <windows.h>\n#include <chrono>\n#include <thread>\n\nusing namespace std;\n\n\/\/ Use to convert bytes to KB\n#define DIV 1024\n\n\/\/ Specify the width of the field in which to print the numbers. \n#define MESSAGE_WIDTH 30\n#define NUMERIC_WIDTH 10\n\nvoid printMessage(LPCSTR msg, bool addColon)\n{\n cout.width(MESSAGE_WIDTH);\n cout << msg;\n if (addColon)\n {\n cout << \" : \";\n }\n}\n\nvoid printMessageLine(LPCSTR msg)\n{\n printMessage(msg, false);\n cout << endl;\n}\n\nvoid printMessageLine(LPCSTR msg, DWORD value)\n{\n printMessage(msg, true);\n cout.width(NUMERIC_WIDTH);\n cout << right << value << endl;\n}\n\nvoid printMessageLine(LPCSTR msg, DWORDLONG value)\n{\n printMessage(msg, true);\n cout.width(NUMERIC_WIDTH);\n cout << right << value << endl;\n}\n\nvoid checkInput(HANDLE exitEvent)\n{\n for (;;)\n {\n char character;\n cin.get(character);\n if (character == 'q')\n {\n SetEvent(exitEvent);\n break;\n }\n }\n}\n\nint main(int argc, char **argv)\n{\n printMessageLine(\"Starting to monitor memory consumption! Press enter to start monitoring\");\n printMessageLine(\"You can press q and enter at anytime to exit\");\n cin.get();\n HANDLE exitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);\n if (NULL == exitEvent)\n {\n printMessageLine(\"Failed to create exitEvent.\");\n return -1;\n }\n std::thread inputThread(checkInput, exitEvent);\n for (;;)\n {\n MEMORYSTATUSEX statex;\n statex.dwLength = sizeof(statex);\n\n BOOL success = ::GlobalMemoryStatusEx(&statex);\n if (!success)\n {\n DWORD error = GetLastError();\n printMessageLine(\"*************************************************\");\n printMessageLine(\"Error getting memory information\", error);\n printMessageLine(\"*************************************************\");\n }\n else\n {\n DWORD load = statex.dwMemoryLoad;\n DWORDLONG physKb = statex.ullTotalPhys \/ DIV;\n DWORDLONG freePhysKb = statex.ullAvailPhys \/ DIV;\n DWORDLONG pageKb = statex.ullTotalPageFile \/ DIV;\n DWORDLONG freePageKb = statex.ullAvailPageFile \/ DIV;\n DWORDLONG virtualKb = statex.ullTotalVirtual \/ DIV;\n DWORDLONG freeVirtualKb = statex.ullAvailVirtual \/ DIV;\n DWORDLONG freeExtKb = statex.ullAvailExtendedVirtual \/ DIV;\n\n printMessageLine(\"*************************************************\");\n\n printMessageLine(\"Percent of memory in use\", load);\n printMessageLine(\"KB of physical memory\", physKb);\n printMessageLine(\"KB of free physical memory\", freePhysKb);\n printMessageLine(\"KB of paging file\", pageKb);\n printMessageLine(\"KB of free paging file\", freePageKb);\n printMessageLine(\"KB of virtual memory\", virtualKb);\n printMessageLine(\"KB of free virtual memory\", freeVirtualKb);\n printMessageLine(\"KB of free extended memory\", freeExtKb);\n\n printMessageLine(\"*************************************************\");\n\n }\n\n if (WAIT_OBJECT_0 == ::WaitForSingleObject(exitEvent, 100))\n {\n break;\n }\n }\n\n inputThread.join();\n ::CloseHandle(exitEvent);\n printMessageLine(\"No longer monitoring memory consumption!\");\n}\n<commit_msg>Adding global scope to SetEvent<commit_after>\/\/ Copyright (c) Microsoft. All rights reserved.\n\n\/\/ ConsoleApplication.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"pch.h\"\n\n#include <windows.h>\n#include <chrono>\n#include <thread>\n\nusing namespace std;\n\n\/\/ Use to convert bytes to KB\n#define DIV 1024\n\n\/\/ Specify the width of the field in which to print the numbers. \n#define MESSAGE_WIDTH 30\n#define NUMERIC_WIDTH 10\n\nvoid printMessage(LPCSTR msg, bool addColon)\n{\n cout.width(MESSAGE_WIDTH);\n cout << msg;\n if (addColon)\n {\n cout << \" : \";\n }\n}\n\nvoid printMessageLine(LPCSTR msg)\n{\n printMessage(msg, false);\n cout << endl;\n}\n\nvoid printMessageLine(LPCSTR msg, DWORD value)\n{\n printMessage(msg, true);\n cout.width(NUMERIC_WIDTH);\n cout << right << value << endl;\n}\n\nvoid printMessageLine(LPCSTR msg, DWORDLONG value)\n{\n printMessage(msg, true);\n cout.width(NUMERIC_WIDTH);\n cout << right << value << endl;\n}\n\nvoid checkInput(HANDLE exitEvent)\n{\n for (;;)\n {\n char character;\n cin.get(character);\n if (character == 'q')\n {\n ::SetEvent(exitEvent);\n break;\n }\n }\n}\n\nint main(int argc, char **argv)\n{\n printMessageLine(\"Starting to monitor memory consumption! Press enter to start monitoring\");\n printMessageLine(\"You can press q and enter at anytime to exit\");\n cin.get();\n HANDLE exitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);\n if (NULL == exitEvent)\n {\n printMessageLine(\"Failed to create exitEvent.\");\n return -1;\n }\n std::thread inputThread(checkInput, exitEvent);\n for (;;)\n {\n MEMORYSTATUSEX statex;\n statex.dwLength = sizeof(statex);\n\n BOOL success = ::GlobalMemoryStatusEx(&statex);\n if (!success)\n {\n DWORD error = GetLastError();\n printMessageLine(\"*************************************************\");\n printMessageLine(\"Error getting memory information\", error);\n printMessageLine(\"*************************************************\");\n }\n else\n {\n DWORD load = statex.dwMemoryLoad;\n DWORDLONG physKb = statex.ullTotalPhys \/ DIV;\n DWORDLONG freePhysKb = statex.ullAvailPhys \/ DIV;\n DWORDLONG pageKb = statex.ullTotalPageFile \/ DIV;\n DWORDLONG freePageKb = statex.ullAvailPageFile \/ DIV;\n DWORDLONG virtualKb = statex.ullTotalVirtual \/ DIV;\n DWORDLONG freeVirtualKb = statex.ullAvailVirtual \/ DIV;\n DWORDLONG freeExtKb = statex.ullAvailExtendedVirtual \/ DIV;\n\n printMessageLine(\"*************************************************\");\n\n printMessageLine(\"Percent of memory in use\", load);\n printMessageLine(\"KB of physical memory\", physKb);\n printMessageLine(\"KB of free physical memory\", freePhysKb);\n printMessageLine(\"KB of paging file\", pageKb);\n printMessageLine(\"KB of free paging file\", freePageKb);\n printMessageLine(\"KB of virtual memory\", virtualKb);\n printMessageLine(\"KB of free virtual memory\", freeVirtualKb);\n printMessageLine(\"KB of free extended memory\", freeExtKb);\n\n printMessageLine(\"*************************************************\");\n\n }\n\n if (WAIT_OBJECT_0 == ::WaitForSingleObject(exitEvent, 100))\n {\n break;\n }\n }\n\n inputThread.join();\n ::CloseHandle(exitEvent);\n printMessageLine(\"No longer monitoring memory consumption!\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/branchLocations.cpp \n\/\/create two vectors from the given SMILES string that contain the indicies of the opening and closing parentheses\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nstd::vector<int> locations(std::string sample, char branch);\n\nint main()\n{\n\tstd::string SMILES; \/\/SMILES goes here\n\n\tchar startBranch = '(';\n\tchar endBranch = ')';\n\n\n\tstd::vector<int> startResults = locations(SMILES, startBranch);\n\tstd::vector<int> endResults = locations(SMILES, endBranch);\n\n\tsystem(\"pause\");\n\treturn 0;\n}\n\nstd::vector<int> locations(std::string testString, char testChar)\n{\n\tstd::vector<int> characterLocations;\n\tfor (int i = 0; i < testString.size(); i++)\n\t{\n\t\tif (testString[i] == testChar)\n\t\t{\n\t\t\tcharacterLocations.push_back(i); \/\/ gives the indicies of the instances of the chosen characters\n\t\t}\n\t}\n\treturn characterLocations;\n\n}<commit_msg>started working on files again<commit_after>\/\/branchLocations.cpp \n\/\/create two vectors from the given SMILES string that contain the indicies of the opening and closing parentheses\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nstd::vector<int> locations(std::string sample, char branch);\n\nint main() {\n\tstd::cout << \"Please input SMILES\\n\";\n\tstd::string SMILES;\n\tstd::cin >> SMILES; \/\/SMILES goes here\n\n\tchar startBranch = '(';\n\tchar endBranch = ')';\n\n\n\tstd::vector<int> startResults = locations(SMILES, startBranch);\n\tstd::vector<int> endResults = locations(SMILES, endBranch);\n\t\n\n\n\tsystem(\"pause\");\n\treturn 0;\n}\n\nstd::vector<int> locations(std::string testString, char testChar) {\n\tstd::vector<int> characterLocations;\n\tfor (int i = 0; i < testString.size(); i++)\n\t{\n\t\tif (testString[i] == testChar)\n\t\t{\n\t\t\tcharacterLocations.push_back(i); \/\/ gives the indicies of the instances of the chosen characters\n\t\t}\n\t}\n\treturn characterLocations;\n\n}<|endoftext|>"} {"text":"<commit_before>#include \"GUI.hpp\"\n\n#if __APPLE__\n#import <IOKit\/pwr_mgt\/IOPMLib.h>\n#elif _WIN32\n#include <Windows.h>\n#pragma comment(lib, \"user32.lib\")\n#endif\n\nnamespace Slic3r { namespace GUI {\n\n#if __APPLE__\nIOPMAssertionID assertionID;\n#endif\n\nvoid\ndisable_screensaver()\n{\n #if __APPLE__\n CFStringRef reasonForActivity = CFSTR(\"Slic3r\");\n IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, \n kIOPMAssertionLevelOn, reasonForActivity, &assertionID); \n \/\/ ignore result: success == kIOReturnSuccess\n #elif _WIN32\n SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_CONTINUOUS);\n #endif\n}\n\nvoid\nenable_screensaver()\n{\n #if __APPLE__\n IOReturn success = IOPMAssertionRelease(assertionID);\n #elif _WIN32\n SetThreadExecutionState(ES_CONTINUOUS);\n #endif\n}\n\nbool \ndebugged()\n{\n #ifdef _WIN32\n return IsDebuggerPresent();\n\t#else\n\treturn false;\n #endif \/* _WIN32 *\/\n}\n\nvoid\nbreak_to_debugger()\n{\n #ifdef _WIN32\n if (IsDebuggerPresent())\n DebugBreak();\n #endif \/* _WIN32 *\/\n}\n\n} }\n<commit_msg>Try to enforce the use of a high performance NVIDIA \/ ATI GPU on dual graphic card laptops.<commit_after>#include \"GUI.hpp\"\n\n#if __APPLE__\n#import <IOKit\/pwr_mgt\/IOPMLib.h>\n#elif _WIN32\n#include <Windows.h>\n#pragma comment(lib, \"user32.lib\")\nextern \"C\" {\n__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;\n__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;\n}\n#endif\n\nnamespace Slic3r { namespace GUI {\n\n#if __APPLE__\nIOPMAssertionID assertionID;\n#endif\n\nvoid\ndisable_screensaver()\n{\n #if __APPLE__\n CFStringRef reasonForActivity = CFSTR(\"Slic3r\");\n IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, \n kIOPMAssertionLevelOn, reasonForActivity, &assertionID); \n \/\/ ignore result: success == kIOReturnSuccess\n #elif _WIN32\n SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_CONTINUOUS);\n #endif\n}\n\nvoid\nenable_screensaver()\n{\n #if __APPLE__\n IOReturn success = IOPMAssertionRelease(assertionID);\n #elif _WIN32\n SetThreadExecutionState(ES_CONTINUOUS);\n #endif\n}\n\nbool \ndebugged()\n{\n #ifdef _WIN32\n return IsDebuggerPresent();\n\t#else\n\treturn false;\n #endif \/* _WIN32 *\/\n}\n\nvoid\nbreak_to_debugger()\n{\n #ifdef _WIN32\n if (IsDebuggerPresent())\n DebugBreak();\n #endif \/* _WIN32 *\/\n}\n\n} }\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE libraries and the Kate part.\n *\n * Copyright (C) 2008-2011 Erlend Hamberg <ehamberg@gmail.com>\n * Copyright (C) 2011 Svyatoslav Kuzmich <svatoslav1@gmail.com>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kateviinsertmode.h\"\n#include \"kateviinputmodemanager.h\"\n#include \"kateview.h\"\n#include \"kateviewinternal.h\"\n#include \"kateconfig.h\"\n#include \"katecompletionwidget.h\"\n#include \"kateglobal.h\"\n#include \"katevikeyparser.h\"\n\nusing KTextEditor::Cursor;\n\nKateViInsertMode::KateViInsertMode( KateViInputModeManager *viInputModeManager,\n KateView * view, KateViewInternal * viewInternal ) : KateViModeBase()\n{\n m_view = view;\n m_viewInternal = viewInternal;\n m_viInputModeManager = viInputModeManager;\n\n m_blockInsert = None;\n m_eolPos = 0;\n m_count = 1;\n m_countedRepeatsBeginOnNewLine = false;\n}\n\nKateViInsertMode::~KateViInsertMode()\n{\n}\n\n\nbool KateViInsertMode::commandInsertFromAbove()\n{\n Cursor c( m_view->cursorPosition() );\n\n if ( c.line() <= 0 ) {\n return false;\n }\n\n QString line = doc()->line( c.line()-1 );\n int tabWidth = doc()->config()->tabWidth();\n QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );\n\n if ( ch == QChar::Null ) {\n return false;\n }\n\n return doc()->insertText( c, ch );\n}\n\nbool KateViInsertMode::commandInsertFromBelow()\n{\n Cursor c( m_view->cursorPosition() );\n\n if ( c.line() >= doc()->lines()-1 ) {\n return false;\n }\n\n QString line = doc()->line( c.line()+1 );\n int tabWidth = doc()->config()->tabWidth();\n QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );\n\n if ( ch == QChar::Null ) {\n return false;\n }\n\n return doc()->insertText( c, ch );\n}\n\nbool KateViInsertMode::commandDeleteWord()\n{\n Cursor c1( m_view->cursorPosition() );\n Cursor c2;\n\n c2 = findPrevWordStart( c1.line(), c1.column() );\n\n if ( c2.line() != c1.line() ) {\n if ( c1.column() == 0 ) {\n c2.setColumn( doc()->line( c2.line() ).length() );\n } else {\n c2.setColumn( 0 );\n c2.setLine( c2.line()+1 );\n }\n }\n\n KateViRange r( c2.line(), c2.column(), c1.line(), c1.column(), ViMotion::ExclusiveMotion );\n\n return deleteRange( r, CharWise, false );\n}\n\nbool KateViInsertMode::commandDeleteCharBackward()\n{\n kDebug( 13070 ) << \"Char backward!\\n\";\n Cursor c( m_view->cursorPosition() );\n\n KateViRange r( c.line(), c.column()-getCount(), c.line(), c.column(), ViMotion::ExclusiveMotion );\n\n if (c.column() == 0) {\n if (c.line() == 0) {\n return true;\n } else {\n r.startColumn = doc()->line(c.line()-1).length();\n r.startLine--;\n }\n }\n\n return deleteRange( r, CharWise );\n}\n\nbool KateViInsertMode::commandNewLine()\n{\n doc()->newLine( m_view );\n return true;\n}\n\nbool KateViInsertMode::commandIndent()\n{\n Cursor c( m_view->cursorPosition() );\n doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), 1 );\n return true;\n}\n\nbool KateViInsertMode::commandUnindent()\n{\n Cursor c( m_view->cursorPosition() );\n doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), -1 );\n return true;\n}\n\nbool KateViInsertMode::commandToFirstCharacterInFile()\n{\n Cursor c;\n\n c.setLine( 0 );\n c.setColumn( 0 );\n\n updateCursor( c );\n\n return true;\n}\n\nbool KateViInsertMode::commandToLastCharacterInFile()\n{\n Cursor c;\n\n int lines = doc()->lines()-1;\n c.setLine( lines );\n c.setColumn( doc()->line( lines ).length() );\n\n updateCursor( c );\n\n return true;\n}\n\nbool KateViInsertMode::commandMoveOneWordLeft()\n{\n Cursor c( m_view->cursorPosition() );\n c = findPrevWordStart( c.line(), c.column() );\n\n updateCursor( c );\n return true;\n}\n\nbool KateViInsertMode::commandMoveOneWordRight()\n{\n Cursor c( m_view->cursorPosition() );\n c = findNextWordStart( c.line(), c.column() );\n\n updateCursor( c );\n return true;\n}\n\nbool KateViInsertMode::commandCompleteNext()\n{\n \/\/ Completion may yield different results when performed\n \/\/ other places in the document. Therefore, repeat the\n \/\/ inserted text instead of the typed keystrokes.\n m_viInputModeManager->setTextualRepeat();\n if(m_view->completionWidget()->isCompletionActive()) {\n m_view->completionWidget()->cursorDown();\n } else {\n m_view->userInvokedCompletion();\n }\n return true;\n}\n\nbool KateViInsertMode::commandCompletePrevious()\n{\n m_viInputModeManager->setTextualRepeat();\n if(m_view->completionWidget()->isCompletionActive()) {\n m_view->completionWidget()->cursorUp();\n } else {\n m_view->userInvokedCompletion();\n m_view->completionWidget()->bottom();\n }\n return true;\n}\n\nbool KateViInsertMode::commandInsertContentOfRegister(){\n Cursor c( m_view->cursorPosition() );\n Cursor cAfter = c;\n QChar reg = getChosenRegister( m_register );\n\n OperationMode m = getRegisterFlag( reg );\n QString textToInsert = getRegisterContent( reg );\n\n if ( textToInsert.isNull() ) {\n error(i18n(\"Nothing in register %1\", reg ));\n return false;\n }\n\n if ( m == LineWise ) {\n textToInsert.chop( 1 ); \/\/ remove the last \\n\n c.setColumn( doc()->lineLength( c.line() ) ); \/\/ paste after the current line and ...\n textToInsert.prepend( QChar( '\\n' ) ); \/\/ ... prepend a \\n, so the text starts on a new line\n\n cAfter.setLine( cAfter.line()+1 );\n cAfter.setColumn( 0 );\n }\n\n doc()->insertText( c, textToInsert, m == Block );\n\n updateCursor( cAfter );\n\n return true;\n}\n\n\/\/ Start Normal mode just for one command and return to Insert mode\nbool KateViInsertMode::commandSwitchToNormalModeForJustOneCommand(){\n m_viInputModeManager->setTemporaryNormalMode(true);\n m_viInputModeManager->changeViMode(NormalMode);\n const Cursor cursorPos = m_view->cursorPosition();\n \/\/ If we're at end of the line, move the cursor back one step, as in Vim.\n if (doc()->line(cursorPos.line()).length() == cursorPos.column())\n {\n m_view->setCursorPosition(Cursor(cursorPos.line(), cursorPos.column() - 1));\n }\n m_view->setCaretStyle( KateRenderer::Block, true );\n m_view->updateViModeBarMode();\n m_viewInternal->repaint();\n return true;\n}\n\n\/**\n * checks if the key is a valid command\n * @return true if a command was completed and executed, false otherwise\n *\/\nbool KateViInsertMode::handleKeypress( const QKeyEvent *e )\n{\n \/\/ backspace should work even if the shift key is down\n if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) {\n m_view->backspace();\n return true;\n }\n\n if(m_keys.isEmpty()){\n if ( e->modifiers() == Qt::NoModifier ) {\n switch ( e->key() ) {\n case Qt::Key_Escape:\n leaveInsertMode();\n return true;\n break;\n case Qt::Key_Left:\n m_view->cursorLeft();\n return true;\n case Qt::Key_Right:\n m_view->cursorRight();\n return true;\n case Qt::Key_Up:\n m_view->up();\n return true;\n case Qt::Key_Down:\n m_view->down();\n return true;\n case Qt::Key_Delete:\n m_view->keyDelete();\n return true;\n case Qt::Key_Home:\n m_view->home();\n return true;\n case Qt::Key_End:\n m_view->end();\n return true;\n case Qt::Key_PageUp:\n m_view->pageUp();\n return true;\n case Qt::Key_PageDown:\n m_view->pageDown();\n return true;\n default:\n return false;\n break;\n }\n } else if ( e->modifiers() == Qt::ControlModifier ) {\n switch( e->key() ) {\n case Qt::Key_BracketLeft:\n case Qt::Key_3:\n leaveInsertMode();\n return true;\n break;\n case Qt::Key_Space:\n commandCompleteNext();\n return true;\n break;\n case Qt::Key_C:\n leaveInsertMode( true );\n return true;\n break;\n case Qt::Key_D:\n commandUnindent();\n return true;\n break;\n case Qt::Key_E:\n commandInsertFromBelow();\n return true;\n break;\n case Qt::Key_N:\n commandCompleteNext();\n return true;\n break;\n case Qt::Key_P:\n commandCompletePrevious();\n return true;\n break;\n case Qt::Key_T:\n commandIndent();\n return true;\n break;\n case Qt::Key_W:\n commandDeleteWord();\n return true;\n break;\n case Qt::Key_J:\n commandNewLine();\n return true;\n break;\n case Qt::Key_H:\n commandDeleteCharBackward();\n return true;\n break;\n case Qt::Key_Y:\n commandInsertFromAbove();\n return true;\n break;\n case Qt::Key_O:\n commandSwitchToNormalModeForJustOneCommand();\n return true;\n break;\n case Qt::Key_Home:\n commandToFirstCharacterInFile();\n return true;\n break;\n case Qt::Key_R:\n m_keys = \"cR\";\n \/\/ Waiting for register\n return true;\n break;\n case Qt::Key_End:\n commandToLastCharacterInFile();\n return true;\n break;\n case Qt::Key_Left:\n commandMoveOneWordLeft();\n return true;\n break;\n case Qt::Key_Right:\n commandMoveOneWordRight();\n return true;\n break;\n default:\n return false;\n }\n }\n\n return false;\n} else {\n\n \/\/ Was waiting for register for Ctrl-R\n if (m_keys == \"cR\"){\n QChar key = KateViKeyParser::self()->KeyEventToQChar(\n e->key(),\n e->text(),\n e->modifiers(),\n e->nativeScanCode() );\n key = key.toLower();\n\n \/\/ is it register ?\n if ( ( key >= '0' && key <= '9' ) || ( key >= 'a' && key <= 'z' ) ||\n key == '_' || key == '+' || key == '*' ) {\n m_register = key;\n } else {\n m_keys = \"\";\n return false;\n }\n commandInsertContentOfRegister();\n m_keys = \"\";\n return true;\n }\n }\n return false;\n}\n\n\/\/ leave insert mode when esc, etc, is pressed. if leaving block\n\/\/ prepend\/append, the inserted text will be added to all block lines. if\n\/\/ ctrl-c is used to exit insert mode this is not done.\nvoid KateViInsertMode::leaveInsertMode( bool force )\n{\n if ( !force && m_blockInsert != None ) { \/\/ block append\/prepend\n\n \/\/ make sure cursor haven't been moved\n if ( m_blockRange.startLine == m_view->cursorPosition().line() ) {\n int start, len;\n QString added;\n Cursor c;\n\n switch ( m_blockInsert ) {\n case Append:\n case Prepend:\n if ( m_blockInsert == Append ) {\n start = m_blockRange.endColumn+1;\n } else {\n start = m_blockRange.startColumn;\n }\n\n len = m_view->cursorPosition().column()-start;\n added = getLine().mid( start, len );\n\n c = Cursor( m_blockRange.startLine, start );\n for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {\n c.setLine( i );\n doc()->insertText( c, added );\n }\n break;\n case AppendEOL:\n start = m_eolPos;\n len = m_view->cursorPosition().column()-start;\n added = getLine().mid( start, len );\n\n c = Cursor( m_blockRange.startLine, start );\n for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {\n c.setLine( i );\n c.setColumn( doc()->lineLength( i ) );\n doc()->insertText( c, added );\n }\n break;\n default:\n error(\"not supported\");\n }\n }\n\n m_blockInsert = None;\n }\n else if (!force)\n {\n const QString added = doc()->text(Range(m_viInputModeManager->getMarkPosition('^'), m_view->cursorPosition()));\n\n if (m_count > 1)\n {\n for (unsigned int i = 0; i < m_count - 1; i++)\n {\n if (m_countedRepeatsBeginOnNewLine)\n {\n doc()->newLine(m_view);\n }\n doc()->insertText( m_view->cursorPosition(), added );\n }\n }\n m_countedRepeatsBeginOnNewLine = false;\n }\n startNormalMode();\n}\n\nvoid KateViInsertMode::setBlockPrependMode( KateViRange blockRange )\n{\n \/\/ ignore if not more than one line is selected\n if ( blockRange.startLine != blockRange.endLine ) {\n m_blockInsert = Prepend;\n m_blockRange = blockRange;\n }\n}\n\nvoid KateViInsertMode::setBlockAppendMode( KateViRange blockRange, BlockInsert b )\n{\n Q_ASSERT( b == Append || b == AppendEOL );\n\n \/\/ ignore if not more than one line is selected\n if ( blockRange.startLine != blockRange.endLine ) {\n m_blockRange = blockRange;\n m_blockInsert = b;\n if ( b == AppendEOL ) {\n m_eolPos = doc()->lineLength( m_blockRange.startLine );\n }\n } else {\n kDebug( 13070 ) << \"cursor moved. ignoring block append\/prepend\";\n }\n}\n<commit_msg>Refactor this if ... else slightly.<commit_after>\/* This file is part of the KDE libraries and the Kate part.\n *\n * Copyright (C) 2008-2011 Erlend Hamberg <ehamberg@gmail.com>\n * Copyright (C) 2011 Svyatoslav Kuzmich <svatoslav1@gmail.com>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kateviinsertmode.h\"\n#include \"kateviinputmodemanager.h\"\n#include \"kateview.h\"\n#include \"kateviewinternal.h\"\n#include \"kateconfig.h\"\n#include \"katecompletionwidget.h\"\n#include \"kateglobal.h\"\n#include \"katevikeyparser.h\"\n\nusing KTextEditor::Cursor;\n\nKateViInsertMode::KateViInsertMode( KateViInputModeManager *viInputModeManager,\n KateView * view, KateViewInternal * viewInternal ) : KateViModeBase()\n{\n m_view = view;\n m_viewInternal = viewInternal;\n m_viInputModeManager = viInputModeManager;\n\n m_blockInsert = None;\n m_eolPos = 0;\n m_count = 1;\n m_countedRepeatsBeginOnNewLine = false;\n}\n\nKateViInsertMode::~KateViInsertMode()\n{\n}\n\n\nbool KateViInsertMode::commandInsertFromAbove()\n{\n Cursor c( m_view->cursorPosition() );\n\n if ( c.line() <= 0 ) {\n return false;\n }\n\n QString line = doc()->line( c.line()-1 );\n int tabWidth = doc()->config()->tabWidth();\n QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );\n\n if ( ch == QChar::Null ) {\n return false;\n }\n\n return doc()->insertText( c, ch );\n}\n\nbool KateViInsertMode::commandInsertFromBelow()\n{\n Cursor c( m_view->cursorPosition() );\n\n if ( c.line() >= doc()->lines()-1 ) {\n return false;\n }\n\n QString line = doc()->line( c.line()+1 );\n int tabWidth = doc()->config()->tabWidth();\n QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );\n\n if ( ch == QChar::Null ) {\n return false;\n }\n\n return doc()->insertText( c, ch );\n}\n\nbool KateViInsertMode::commandDeleteWord()\n{\n Cursor c1( m_view->cursorPosition() );\n Cursor c2;\n\n c2 = findPrevWordStart( c1.line(), c1.column() );\n\n if ( c2.line() != c1.line() ) {\n if ( c1.column() == 0 ) {\n c2.setColumn( doc()->line( c2.line() ).length() );\n } else {\n c2.setColumn( 0 );\n c2.setLine( c2.line()+1 );\n }\n }\n\n KateViRange r( c2.line(), c2.column(), c1.line(), c1.column(), ViMotion::ExclusiveMotion );\n\n return deleteRange( r, CharWise, false );\n}\n\nbool KateViInsertMode::commandDeleteCharBackward()\n{\n kDebug( 13070 ) << \"Char backward!\\n\";\n Cursor c( m_view->cursorPosition() );\n\n KateViRange r( c.line(), c.column()-getCount(), c.line(), c.column(), ViMotion::ExclusiveMotion );\n\n if (c.column() == 0) {\n if (c.line() == 0) {\n return true;\n } else {\n r.startColumn = doc()->line(c.line()-1).length();\n r.startLine--;\n }\n }\n\n return deleteRange( r, CharWise );\n}\n\nbool KateViInsertMode::commandNewLine()\n{\n doc()->newLine( m_view );\n return true;\n}\n\nbool KateViInsertMode::commandIndent()\n{\n Cursor c( m_view->cursorPosition() );\n doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), 1 );\n return true;\n}\n\nbool KateViInsertMode::commandUnindent()\n{\n Cursor c( m_view->cursorPosition() );\n doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), -1 );\n return true;\n}\n\nbool KateViInsertMode::commandToFirstCharacterInFile()\n{\n Cursor c;\n\n c.setLine( 0 );\n c.setColumn( 0 );\n\n updateCursor( c );\n\n return true;\n}\n\nbool KateViInsertMode::commandToLastCharacterInFile()\n{\n Cursor c;\n\n int lines = doc()->lines()-1;\n c.setLine( lines );\n c.setColumn( doc()->line( lines ).length() );\n\n updateCursor( c );\n\n return true;\n}\n\nbool KateViInsertMode::commandMoveOneWordLeft()\n{\n Cursor c( m_view->cursorPosition() );\n c = findPrevWordStart( c.line(), c.column() );\n\n updateCursor( c );\n return true;\n}\n\nbool KateViInsertMode::commandMoveOneWordRight()\n{\n Cursor c( m_view->cursorPosition() );\n c = findNextWordStart( c.line(), c.column() );\n\n updateCursor( c );\n return true;\n}\n\nbool KateViInsertMode::commandCompleteNext()\n{\n \/\/ Completion may yield different results when performed\n \/\/ other places in the document. Therefore, repeat the\n \/\/ inserted text instead of the typed keystrokes.\n m_viInputModeManager->setTextualRepeat();\n if(m_view->completionWidget()->isCompletionActive()) {\n m_view->completionWidget()->cursorDown();\n } else {\n m_view->userInvokedCompletion();\n }\n return true;\n}\n\nbool KateViInsertMode::commandCompletePrevious()\n{\n m_viInputModeManager->setTextualRepeat();\n if(m_view->completionWidget()->isCompletionActive()) {\n m_view->completionWidget()->cursorUp();\n } else {\n m_view->userInvokedCompletion();\n m_view->completionWidget()->bottom();\n }\n return true;\n}\n\nbool KateViInsertMode::commandInsertContentOfRegister(){\n Cursor c( m_view->cursorPosition() );\n Cursor cAfter = c;\n QChar reg = getChosenRegister( m_register );\n\n OperationMode m = getRegisterFlag( reg );\n QString textToInsert = getRegisterContent( reg );\n\n if ( textToInsert.isNull() ) {\n error(i18n(\"Nothing in register %1\", reg ));\n return false;\n }\n\n if ( m == LineWise ) {\n textToInsert.chop( 1 ); \/\/ remove the last \\n\n c.setColumn( doc()->lineLength( c.line() ) ); \/\/ paste after the current line and ...\n textToInsert.prepend( QChar( '\\n' ) ); \/\/ ... prepend a \\n, so the text starts on a new line\n\n cAfter.setLine( cAfter.line()+1 );\n cAfter.setColumn( 0 );\n }\n\n doc()->insertText( c, textToInsert, m == Block );\n\n updateCursor( cAfter );\n\n return true;\n}\n\n\/\/ Start Normal mode just for one command and return to Insert mode\nbool KateViInsertMode::commandSwitchToNormalModeForJustOneCommand(){\n m_viInputModeManager->setTemporaryNormalMode(true);\n m_viInputModeManager->changeViMode(NormalMode);\n const Cursor cursorPos = m_view->cursorPosition();\n \/\/ If we're at end of the line, move the cursor back one step, as in Vim.\n if (doc()->line(cursorPos.line()).length() == cursorPos.column())\n {\n m_view->setCursorPosition(Cursor(cursorPos.line(), cursorPos.column() - 1));\n }\n m_view->setCaretStyle( KateRenderer::Block, true );\n m_view->updateViModeBarMode();\n m_viewInternal->repaint();\n return true;\n}\n\n\/**\n * checks if the key is a valid command\n * @return true if a command was completed and executed, false otherwise\n *\/\nbool KateViInsertMode::handleKeypress( const QKeyEvent *e )\n{\n \/\/ backspace should work even if the shift key is down\n if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) {\n m_view->backspace();\n return true;\n }\n\n if(m_keys.isEmpty()){\n if ( e->modifiers() == Qt::NoModifier ) {\n switch ( e->key() ) {\n case Qt::Key_Escape:\n leaveInsertMode();\n return true;\n break;\n case Qt::Key_Left:\n m_view->cursorLeft();\n return true;\n case Qt::Key_Right:\n m_view->cursorRight();\n return true;\n case Qt::Key_Up:\n m_view->up();\n return true;\n case Qt::Key_Down:\n m_view->down();\n return true;\n case Qt::Key_Delete:\n m_view->keyDelete();\n return true;\n case Qt::Key_Home:\n m_view->home();\n return true;\n case Qt::Key_End:\n m_view->end();\n return true;\n case Qt::Key_PageUp:\n m_view->pageUp();\n return true;\n case Qt::Key_PageDown:\n m_view->pageDown();\n return true;\n default:\n return false;\n break;\n }\n } else if ( e->modifiers() == Qt::ControlModifier ) {\n switch( e->key() ) {\n case Qt::Key_BracketLeft:\n case Qt::Key_3:\n leaveInsertMode();\n return true;\n break;\n case Qt::Key_Space:\n commandCompleteNext();\n return true;\n break;\n case Qt::Key_C:\n leaveInsertMode( true );\n return true;\n break;\n case Qt::Key_D:\n commandUnindent();\n return true;\n break;\n case Qt::Key_E:\n commandInsertFromBelow();\n return true;\n break;\n case Qt::Key_N:\n commandCompleteNext();\n return true;\n break;\n case Qt::Key_P:\n commandCompletePrevious();\n return true;\n break;\n case Qt::Key_T:\n commandIndent();\n return true;\n break;\n case Qt::Key_W:\n commandDeleteWord();\n return true;\n break;\n case Qt::Key_J:\n commandNewLine();\n return true;\n break;\n case Qt::Key_H:\n commandDeleteCharBackward();\n return true;\n break;\n case Qt::Key_Y:\n commandInsertFromAbove();\n return true;\n break;\n case Qt::Key_O:\n commandSwitchToNormalModeForJustOneCommand();\n return true;\n break;\n case Qt::Key_Home:\n commandToFirstCharacterInFile();\n return true;\n break;\n case Qt::Key_R:\n m_keys = \"cR\";\n \/\/ Waiting for register\n return true;\n break;\n case Qt::Key_End:\n commandToLastCharacterInFile();\n return true;\n break;\n case Qt::Key_Left:\n commandMoveOneWordLeft();\n return true;\n break;\n case Qt::Key_Right:\n commandMoveOneWordRight();\n return true;\n break;\n default:\n return false;\n }\n }\n\n return false;\n} else {\n\n \/\/ Was waiting for register for Ctrl-R\n if (m_keys == \"cR\"){\n QChar key = KateViKeyParser::self()->KeyEventToQChar(\n e->key(),\n e->text(),\n e->modifiers(),\n e->nativeScanCode() );\n key = key.toLower();\n\n \/\/ is it register ?\n if ( ( key >= '0' && key <= '9' ) || ( key >= 'a' && key <= 'z' ) ||\n key == '_' || key == '+' || key == '*' ) {\n m_register = key;\n } else {\n m_keys = \"\";\n return false;\n }\n commandInsertContentOfRegister();\n m_keys = \"\";\n return true;\n }\n }\n return false;\n}\n\n\/\/ leave insert mode when esc, etc, is pressed. if leaving block\n\/\/ prepend\/append, the inserted text will be added to all block lines. if\n\/\/ ctrl-c is used to exit insert mode this is not done.\nvoid KateViInsertMode::leaveInsertMode( bool force )\n{\n if ( !force )\n {\n if ( m_blockInsert != None ) { \/\/ block append\/prepend\n\n \/\/ make sure cursor haven't been moved\n if ( m_blockRange.startLine == m_view->cursorPosition().line() ) {\n int start, len;\n QString added;\n Cursor c;\n\n switch ( m_blockInsert ) {\n case Append:\n case Prepend:\n if ( m_blockInsert == Append ) {\n start = m_blockRange.endColumn+1;\n } else {\n start = m_blockRange.startColumn;\n }\n\n len = m_view->cursorPosition().column()-start;\n added = getLine().mid( start, len );\n\n c = Cursor( m_blockRange.startLine, start );\n for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {\n c.setLine( i );\n doc()->insertText( c, added );\n }\n break;\n case AppendEOL:\n start = m_eolPos;\n len = m_view->cursorPosition().column()-start;\n added = getLine().mid( start, len );\n\n c = Cursor( m_blockRange.startLine, start );\n for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {\n c.setLine( i );\n c.setColumn( doc()->lineLength( i ) );\n doc()->insertText( c, added );\n }\n break;\n default:\n error(\"not supported\");\n }\n }\n\n m_blockInsert = None;\n }\n else\n {\n const QString added = doc()->text(Range(m_viInputModeManager->getMarkPosition('^'), m_view->cursorPosition()));\n\n if (m_count > 1)\n {\n for (unsigned int i = 0; i < m_count - 1; i++)\n {\n if (m_countedRepeatsBeginOnNewLine)\n {\n doc()->newLine(m_view);\n }\n doc()->insertText( m_view->cursorPosition(), added );\n }\n }\n m_countedRepeatsBeginOnNewLine = false;\n }\n }\n startNormalMode();\n}\n\nvoid KateViInsertMode::setBlockPrependMode( KateViRange blockRange )\n{\n \/\/ ignore if not more than one line is selected\n if ( blockRange.startLine != blockRange.endLine ) {\n m_blockInsert = Prepend;\n m_blockRange = blockRange;\n }\n}\n\nvoid KateViInsertMode::setBlockAppendMode( KateViRange blockRange, BlockInsert b )\n{\n Q_ASSERT( b == Append || b == AppendEOL );\n\n \/\/ ignore if not more than one line is selected\n if ( blockRange.startLine != blockRange.endLine ) {\n m_blockRange = blockRange;\n m_blockInsert = b;\n if ( b == AppendEOL ) {\n m_eolPos = doc()->lineLength( m_blockRange.startLine );\n }\n } else {\n kDebug( 13070 ) << \"cursor moved. ignoring block append\/prepend\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: attributeproperties.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2006-11-21 16:43:05 $\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 _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX\n#define _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX\n\n#ifndef _SFXLSTNER_HXX\n#include <svtools\/lstner.hxx>\n#endif\n\n#ifndef _SDR_PROPERTIES_DEFAULTPROPERTIES_HXX\n#include <svx\/sdr\/properties\/defaultproperties.hxx>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace properties\n {\n class SVX_DLLPUBLIC AttributeProperties : public DefaultProperties, public SfxListener\n {\n \/\/ add style sheet, do all the necessary handling\n void ImpAddStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);\n\n \/\/ remove StyleSheet, do all the necessary handling\n void ImpRemoveStyleSheet();\n\n protected:\n \/\/ the SytleSheet of this object\n SfxStyleSheet* mpStyleSheet;\n\n \/\/ create a new itemset\n virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& pPool);\n\n \/\/ Do the ItemChange, may do special handling\n virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0);\n\n \/\/ react on ItemSet changes\n virtual void ItemSetChanged(const SfxItemSet& rSet);\n\n public:\n \/\/ basic constructor\n AttributeProperties(SdrObject& rObj);\n\n \/\/ constructor for copying, but using new object\n AttributeProperties(const AttributeProperties& rProps, SdrObject& rObj);\n\n \/\/ Clone() operator, normally just calls the local copy constructor\n virtual BaseProperties& Clone(SdrObject& rObj) const;\n\n \/\/ destructor\n virtual ~AttributeProperties();\n\n \/\/ set a new StyleSheet and broadcast\n virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);\n\n \/\/ get the installed StyleSheet\n virtual SfxStyleSheet* GetStyleSheet() const;\n\n \/\/ Move properties to a new ItemPool.\n virtual void MoveToItemPool(SfxItemPool* pSrcPool, SfxItemPool* pDestPool, SdrModel* pNewModel = 0L);\n\n \/\/ Set new model.\n virtual void SetModel(SdrModel* pOldModel, SdrModel* pNewModel);\n\n \/\/ force all attributes which come from styles to hard attributes\n \/\/ to be able to live without the style.\n virtual void ForceStyleToHardAttributes();\n\n \/\/ This is the Notify(...) from 2nd base class SfxListener\n virtual void Notify(SfxBroadcaster& rBC, const SfxHint& rHint);\n };\n } \/\/ end of namespace properties\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/_SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX\n\n\/\/ eof\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.622); FILE MERGED 2008\/04\/01 15:50:06 thb 1.7.622.3: #i85898# Stripping all external header guards 2008\/04\/01 12:47:54 thb 1.7.622.2: #i85898# Stripping all external header guards 2008\/03\/31 14:19:05 rt 1.7.622.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: attributeproperties.hxx,v $\n * $Revision: 1.8 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX\n#define _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX\n\n#include <svtools\/lstner.hxx>\n#include <svx\/sdr\/properties\/defaultproperties.hxx>\n#include \"svx\/svxdllapi.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace properties\n {\n class SVX_DLLPUBLIC AttributeProperties : public DefaultProperties, public SfxListener\n {\n \/\/ add style sheet, do all the necessary handling\n void ImpAddStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);\n\n \/\/ remove StyleSheet, do all the necessary handling\n void ImpRemoveStyleSheet();\n\n protected:\n \/\/ the SytleSheet of this object\n SfxStyleSheet* mpStyleSheet;\n\n \/\/ create a new itemset\n virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& pPool);\n\n \/\/ Do the ItemChange, may do special handling\n virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0);\n\n \/\/ react on ItemSet changes\n virtual void ItemSetChanged(const SfxItemSet& rSet);\n\n public:\n \/\/ basic constructor\n AttributeProperties(SdrObject& rObj);\n\n \/\/ constructor for copying, but using new object\n AttributeProperties(const AttributeProperties& rProps, SdrObject& rObj);\n\n \/\/ Clone() operator, normally just calls the local copy constructor\n virtual BaseProperties& Clone(SdrObject& rObj) const;\n\n \/\/ destructor\n virtual ~AttributeProperties();\n\n \/\/ set a new StyleSheet and broadcast\n virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);\n\n \/\/ get the installed StyleSheet\n virtual SfxStyleSheet* GetStyleSheet() const;\n\n \/\/ Move properties to a new ItemPool.\n virtual void MoveToItemPool(SfxItemPool* pSrcPool, SfxItemPool* pDestPool, SdrModel* pNewModel = 0L);\n\n \/\/ Set new model.\n virtual void SetModel(SdrModel* pOldModel, SdrModel* pNewModel);\n\n \/\/ force all attributes which come from styles to hard attributes\n \/\/ to be able to live without the style.\n virtual void ForceStyleToHardAttributes();\n\n \/\/ This is the Notify(...) from 2nd base class SfxListener\n virtual void Notify(SfxBroadcaster& rBC, const SfxHint& rHint);\n };\n } \/\/ end of namespace properties\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/_SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX\n\n\/\/ eof\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\r\n** **\r\n** SWoOz is a software platform written in C++ used for behavioral **\r\n** experiments based on interactions between people and robots **\r\n** or 3D avatars. **\r\n** **\r\n** This program is free software: you can redistribute it and\/or modify **\r\n** it under the terms of the GNU Lesser General Public License as published **\r\n** by the Free Software Foundation, either version 3 of the License, or **\r\n** (at your option) any later version. **\r\n** **\r\n** This program is distributed in the hope that it will be useful, **\r\n** but WITHOUT ANY WARRANTY; without even the implied warranty of **\r\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **\r\n** GNU Lesser General Public License for more details. **\r\n** **\r\n** You should have received a copy of the GNU Lesser General Public License **\r\n** along with Foobar. If not, see <http:\/\/www.gnu.org\/licenses\/>. **\r\n** **\r\n** *****************************************************************************\r\n** Authors: Guillaume Gibert, Florian Lance **\r\n** Website\/Contact: http:\/\/swooz.free.fr\/ **\r\n** Repository: https:\/\/github.com\/GuillaumeGibert\/swooz **\r\n********************************************************************************\/\r\n\r\n\/**\r\n * \\file OpenNITracking.cpp\r\n * \\brief Defines OpenNITracking class\r\n * \\author Emmanuel Body\r\n * \\date 07\/01\/13\r\n *\/\r\n\r\n#include \"rgbd\/SWOpenNITracking.h\"\r\n#include \"SWTrackingDevice.h\"\r\n\r\n\/\/ SWOOZ Toolkit\r\n#include \"geometryUtility.h\"\r\n#include \"SWExceptions.h\"\r\n\r\n\r\nSWOpenNITracking::SWOpenNITracking()\r\n :m_IsOpenNiInitialized(false)\r\n{\r\n std::string l_DeviceName = \"rgbd\";\r\n std::string l_LibraryName = \"openni\";\r\n\r\n m_sHeadTrackingPortName\t\t= \"\/tracking\/\" + l_DeviceName + \"\/\"+ l_LibraryName + \"\/head\";\r\n m_sTorsoTrackingPortName = \"\/tracking\/\" + l_DeviceName + \"\/\"+ l_LibraryName + \"\/torso\";\r\n m_sLeftArmTrackingPortName\t= \"\/tracking\/\" + l_DeviceName + \"\/\"+ l_LibraryName + \"\/left_arm\";\r\n m_sRightArmTrackingPortName\t= \"\/tracking\/\" + l_DeviceName + \"\/\"+ l_LibraryName + \"\/right_arm\";\r\n\r\n m_oHeadTrackingPort.open(m_sHeadTrackingPortName.c_str());\r\n m_oTorsoTrackingPort.open(m_sTorsoTrackingPortName.c_str());\r\n m_oLeftArmTrackingPort.open(m_sLeftArmTrackingPortName.c_str());\r\n m_oRightArmTrackingPort.open(m_sRightArmTrackingPortName.c_str());\r\n m_oAllJointsTrackingPort.open(\"\/tracking\/joints:o\");\r\n\r\n initOpenNi();\r\n}\r\n\r\n\r\nSWOpenNITracking::~SWOpenNITracking()\r\n{\r\n m_oHeadTrackingPort.close();\r\n m_oTorsoTrackingPort.close();\r\n m_oLeftArmTrackingPort.close();\r\n m_oRightArmTrackingPort.close();\r\n m_oAllJointsTrackingPort.close();\r\n}\r\n\r\nvoid SWOpenNITracking::initOpenNi()\r\n{\r\n m_oKinectSkeleton.reset(swDevice::SWKinectSkeleton::getInstance());\r\n\r\n if (m_oKinectSkeleton->init() == 0)\r\n\t{\r\n m_oKinectSkeleton->selectProfile(swDevice::SWKinectSkeleton::UpperBody);\r\n m_IsOpenNiInitialized = true;\r\n\r\n std::cout << \"OpenNI skeleton initialized. \" << std::endl;\r\n\t}\r\n\telse\r\n\t{\r\n std::cerr << \"-ERROR : OpenNI initialisation failure. \" << std::endl;\r\n\t}\r\n}\r\n\r\nbool SWOpenNITracking::isOpenNIInitialized() const\r\n{\r\n\treturn m_IsOpenNiInitialized;\r\n}\r\n\r\ndouble SWOpenNITracking::getPeriod()\r\n{\r\n\t\/\/ module periodicity (seconds), called implicitly by myModule\r\n return 0.001\/30.;\r\n}\r\n\r\nbool SWOpenNITracking::interruptModule() {\r\n m_oHeadTrackingPort\t\t.interrupt();\r\n m_oTorsoTrackingPort .interrupt();\r\n m_oLeftArmTrackingPort\t.interrupt();\r\n m_oRightArmTrackingPort\t.interrupt();\r\n m_oAllJointsTrackingPort\t.interrupt();\r\n\treturn true;\r\n}\r\n\r\nbool SWOpenNITracking::configure(yarp::os::ResourceFinder & rf)\r\n{\r\n\t\/\/ nothing\r\n\treturn true;\r\n}\r\n\r\n\r\nbool SWOpenNITracking::updateModule()\r\n{\r\n\tif (!m_IsOpenNiInitialized)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::vector<swDevice::SWKinectSkeleton::Coordinates> l_values;\r\n if (m_oKinectSkeleton->grab(l_values) == 0)\r\n\t{\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointTorso\t\t= l_values[0];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointNeck\t\t= l_values[1];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointHead\t\t= l_values[2];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointLShoulder\t\t= l_values[3];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointRShoulder\t\t= l_values[4];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointLElbow\t\t= l_values[5];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointRElbow\t\t= l_values[6];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointLHand\t\t= l_values[7];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointRHand\t\t= l_values[8];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointLHip\t\t\t= l_values[9];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointRHip\t\t\t= l_values[10];\r\n\r\n\r\n yarp::os::Bottle & l_HeadBottle\t\t= m_oHeadTrackingPort.prepare();\r\n\t\tl_HeadBottle.clear();\r\n\t\t\tl_HeadBottle.addInt(swTracking::OPENNI_LIB);\r\n\t\t\tl_HeadBottle.addDouble(l_pointNeck.X);\t\t\tl_HeadBottle.addDouble(l_pointNeck.Y);\t\t\tl_HeadBottle.addDouble(l_pointNeck.Z);\r\n\t\t\tl_HeadBottle.addDouble(l_pointHead.X);\t\t\tl_HeadBottle.addDouble(l_pointHead.Y);\t\t\tl_HeadBottle.addDouble(l_pointHead.Z);\r\n\t\t\tl_HeadBottle.addDouble(l_pointLShoulder.X);\t\tl_HeadBottle.addDouble(l_pointLShoulder.Y);\t\tl_HeadBottle.addDouble(l_pointLShoulder.Z);\r\n\t\t\tl_HeadBottle.addDouble(l_pointRShoulder.X);\t\tl_HeadBottle.addDouble(l_pointRShoulder.Y);\t\tl_HeadBottle.addDouble(l_pointRShoulder.Z);\r\n m_oHeadTrackingPort.write();\r\n\r\n yarp::os::Bottle & l_TorsoBottle \t= m_oTorsoTrackingPort.prepare();\r\n\t\tl_TorsoBottle.clear();\r\n\t\t\tl_TorsoBottle.addInt(swTracking::OPENNI_LIB);\r\n\t\t\tl_TorsoBottle.addDouble(l_pointTorso.X);\t\tl_TorsoBottle.addDouble(l_pointTorso.Y);\t\tl_TorsoBottle.addDouble(l_pointTorso.Z);\r\n\t\t\tl_TorsoBottle.addDouble(l_pointNeck.X);\t\t\tl_TorsoBottle.addDouble(l_pointNeck.Y);\t\t\tl_TorsoBottle.addDouble(l_pointNeck.Z);\r\n\t\t\tl_TorsoBottle.addDouble(l_pointLShoulder.X);\tl_TorsoBottle.addDouble(l_pointLShoulder.Y);\tl_TorsoBottle.addDouble(l_pointLShoulder.Z);\r\n\t\t\tl_TorsoBottle.addDouble(l_pointRShoulder.X);\tl_TorsoBottle.addDouble(l_pointRShoulder.Y);\tl_TorsoBottle.addDouble(l_pointRShoulder.Z);\r\n m_oTorsoTrackingPort.write();\r\n\r\n yarp::os::Bottle & l_LeftArmBottle \t= m_oLeftArmTrackingPort.prepare();\r\n\t\tl_LeftArmBottle.clear();\r\n\t\t\tl_LeftArmBottle.addInt(swTracking::OPENNI_LIB);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointTorso.X);\t\tl_LeftArmBottle.addDouble(l_pointTorso.Y);\t\tl_LeftArmBottle.addDouble(l_pointTorso.Z);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointNeck.X);\t\tl_LeftArmBottle.addDouble(l_pointNeck.Y);\t\tl_LeftArmBottle.addDouble(l_pointNeck.Z);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointLShoulder.X);\tl_LeftArmBottle.addDouble(l_pointLShoulder.Y);\tl_LeftArmBottle.addDouble(l_pointLShoulder.Z);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointLElbow.X);\t\tl_LeftArmBottle.addDouble(l_pointLElbow.Y);\t\tl_LeftArmBottle.addDouble(l_pointLElbow.Z);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointLHand.X);\t\tl_LeftArmBottle.addDouble(l_pointLHand.Y);\t\tl_LeftArmBottle.addDouble(l_pointLHand.Z);\r\n m_oLeftArmTrackingPort.write();\r\n\r\n yarp::os::Bottle & l_RightArmBottle = m_oRightArmTrackingPort.prepare();\r\n\t\tl_RightArmBottle.clear();\r\n\t\t\tl_RightArmBottle.addInt(swTracking::OPENNI_LIB);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointTorso.X);\t\tl_RightArmBottle.addDouble(l_pointTorso.Y);\t\tl_RightArmBottle.addDouble(l_pointTorso.Z);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointNeck.X);\t\tl_RightArmBottle.addDouble(l_pointNeck.Y);\t\tl_RightArmBottle.addDouble(l_pointNeck.Z);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointRShoulder.X);\tl_RightArmBottle.addDouble(l_pointRShoulder.Y);\tl_RightArmBottle.addDouble(l_pointRShoulder.Z);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointRElbow.X);\tl_RightArmBottle.addDouble(l_pointRElbow.Y);\tl_RightArmBottle.addDouble(l_pointRElbow.Z);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointRHand.X);\t\tl_RightArmBottle.addDouble(l_pointRHand.Y);\t\tl_RightArmBottle.addDouble(l_pointRHand.Z);\r\n m_oRightArmTrackingPort.write(); \r\n\r\n\r\n yarp::os::Bottle &l_allJointsBottle = m_oAllJointsTrackingPort.prepare();\r\n l_allJointsBottle.clear();\r\n l_HeadBottle.addDouble(l_pointNeck.X);\t\t\tl_HeadBottle.addDouble(l_pointNeck.Y);\t\t\tl_HeadBottle.addDouble(l_pointNeck.Z);\r\n l_HeadBottle.addDouble(l_pointHead.X);\t\t\tl_HeadBottle.addDouble(l_pointHead.Y);\t\t\tl_HeadBottle.addDouble(l_pointHead.Z);\r\n l_HeadBottle.addDouble(l_pointLShoulder.X);\t\tl_HeadBottle.addDouble(l_pointLShoulder.Y);\t\tl_HeadBottle.addDouble(l_pointLShoulder.Z);\r\n l_HeadBottle.addDouble(l_pointRShoulder.X);\t\tl_HeadBottle.addDouble(l_pointRShoulder.Y);\t\tl_HeadBottle.addDouble(l_pointRShoulder.Z);\r\n l_TorsoBottle.addDouble(l_pointTorso.X);\t\tl_TorsoBottle.addDouble(l_pointTorso.Y);\t\tl_TorsoBottle.addDouble(l_pointTorso.Z);\r\n l_LeftArmBottle.addDouble(l_pointLElbow.X);\t\tl_LeftArmBottle.addDouble(l_pointLElbow.Y);\t\tl_LeftArmBottle.addDouble(l_pointLElbow.Z);\r\n l_RightArmBottle.addDouble(l_pointRElbow.X);\tl_RightArmBottle.addDouble(l_pointRElbow.Y);\tl_RightArmBottle.addDouble(l_pointRElbow.Z);\r\n l_LeftArmBottle.addDouble(l_pointLHand.X);\t\tl_LeftArmBottle.addDouble(l_pointLHand.Y);\t\tl_LeftArmBottle.addDouble(l_pointLHand.Z);\r\n l_RightArmBottle.addDouble(l_pointRHand.X);\t\tl_RightArmBottle.addDouble(l_pointRHand.Y);\t\tl_RightArmBottle.addDouble(l_pointRHand.Z);\r\n m_oAllJointsTrackingPort.write();\r\n\t}\r\n\r\n\treturn true; \/\/ RF Module OK\r\n}\r\n\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\r\n yarp::os::Network netwotk;\r\n if (!netwotk.checkNetwork())\r\n {\r\n std::cerr << \"\/!\\\\ Problem connecting to YARP server.\" << std::endl;\r\n return -1;\r\n } \r\n\r\n std::cout << \"Starting the OpenNI Skeleton capture module..\" << std::endl;\r\n SWOpenNITracking l_OpenNITracking;\r\n\r\n \/\/ prepare and configure the resource finder\r\n\/\/ yarp::os::ResourceFinder rf;\r\n\/\/ rf.setVerbose(true);\r\n\/\/ rf.setDefaultConfigFile(\"openniTracking.ini\");\r\n\/\/ rf.setDefaultContext(\"swtracking\/conf\");\r\n\/\/ rf.configure(\"YARP_DIR\", argc, argv);\r\n\r\n\/\/ if(l_OpenNITracking.configure(rf))\r\n\/\/ {\r\n l_OpenNITracking.runModule();\r\n\/\/ }\r\n\r\n std::cout << \"Ending OpenNI Skeleton capture module...\" << std::endl;\r\n}\r\n<commit_msg>* Modify the frame rate of the openNI module to 30 fps<commit_after>\/*******************************************************************************\r\n** **\r\n** SWoOz is a software platform written in C++ used for behavioral **\r\n** experiments based on interactions between people and robots **\r\n** or 3D avatars. **\r\n** **\r\n** This program is free software: you can redistribute it and\/or modify **\r\n** it under the terms of the GNU Lesser General Public License as published **\r\n** by the Free Software Foundation, either version 3 of the License, or **\r\n** (at your option) any later version. **\r\n** **\r\n** This program is distributed in the hope that it will be useful, **\r\n** but WITHOUT ANY WARRANTY; without even the implied warranty of **\r\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **\r\n** GNU Lesser General Public License for more details. **\r\n** **\r\n** You should have received a copy of the GNU Lesser General Public License **\r\n** along with Foobar. If not, see <http:\/\/www.gnu.org\/licenses\/>. **\r\n** **\r\n** *****************************************************************************\r\n** Authors: Guillaume Gibert, Florian Lance **\r\n** Website\/Contact: http:\/\/swooz.free.fr\/ **\r\n** Repository: https:\/\/github.com\/GuillaumeGibert\/swooz **\r\n********************************************************************************\/\r\n\r\n\/**\r\n * \\file OpenNITracking.cpp\r\n * \\brief Defines OpenNITracking class\r\n * \\author Emmanuel Body\r\n * \\date 07\/01\/13\r\n *\/\r\n\r\n#include \"rgbd\/SWOpenNITracking.h\"\r\n#include \"SWTrackingDevice.h\"\r\n\r\n\/\/ SWOOZ Toolkit\r\n#include \"geometryUtility.h\"\r\n#include \"SWExceptions.h\"\r\n\r\n\r\nSWOpenNITracking::SWOpenNITracking()\r\n :m_IsOpenNiInitialized(false)\r\n{\r\n std::string l_DeviceName = \"rgbd\";\r\n std::string l_LibraryName = \"openni\";\r\n\r\n m_sHeadTrackingPortName\t\t= \"\/tracking\/\" + l_DeviceName + \"\/\"+ l_LibraryName + \"\/head\";\r\n m_sTorsoTrackingPortName = \"\/tracking\/\" + l_DeviceName + \"\/\"+ l_LibraryName + \"\/torso\";\r\n m_sLeftArmTrackingPortName\t= \"\/tracking\/\" + l_DeviceName + \"\/\"+ l_LibraryName + \"\/left_arm\";\r\n m_sRightArmTrackingPortName\t= \"\/tracking\/\" + l_DeviceName + \"\/\"+ l_LibraryName + \"\/right_arm\";\r\n\r\n m_oHeadTrackingPort.open(m_sHeadTrackingPortName.c_str());\r\n m_oTorsoTrackingPort.open(m_sTorsoTrackingPortName.c_str());\r\n m_oLeftArmTrackingPort.open(m_sLeftArmTrackingPortName.c_str());\r\n m_oRightArmTrackingPort.open(m_sRightArmTrackingPortName.c_str());\r\n m_oAllJointsTrackingPort.open(\"\/tracking\/joints:o\");\r\n\r\n initOpenNi();\r\n}\r\n\r\n\r\nSWOpenNITracking::~SWOpenNITracking()\r\n{\r\n m_oHeadTrackingPort.close();\r\n m_oTorsoTrackingPort.close();\r\n m_oLeftArmTrackingPort.close();\r\n m_oRightArmTrackingPort.close();\r\n m_oAllJointsTrackingPort.close();\r\n}\r\n\r\nvoid SWOpenNITracking::initOpenNi()\r\n{\r\n m_oKinectSkeleton.reset(swDevice::SWKinectSkeleton::getInstance());\r\n\r\n if (m_oKinectSkeleton->init() == 0)\r\n\t{\r\n m_oKinectSkeleton->selectProfile(swDevice::SWKinectSkeleton::UpperBody);\r\n m_IsOpenNiInitialized = true;\r\n\r\n std::cout << \"OpenNI skeleton initialized. \" << std::endl;\r\n\t}\r\n\telse\r\n\t{\r\n std::cerr << \"-ERROR : OpenNI initialisation failure. \" << std::endl;\r\n\t}\r\n}\r\n\r\nbool SWOpenNITracking::isOpenNIInitialized() const\r\n{\r\n\treturn m_IsOpenNiInitialized;\r\n}\r\n\r\ndouble SWOpenNITracking::getPeriod()\r\n{\r\n\t\/\/ module periodicity (seconds), called implicitly by myModule\r\n return 1\/30.;\r\n}\r\n\r\nbool SWOpenNITracking::interruptModule() {\r\n m_oHeadTrackingPort\t\t.interrupt();\r\n m_oTorsoTrackingPort .interrupt();\r\n m_oLeftArmTrackingPort\t.interrupt();\r\n m_oRightArmTrackingPort\t.interrupt();\r\n m_oAllJointsTrackingPort\t.interrupt();\r\n\treturn true;\r\n}\r\n\r\nbool SWOpenNITracking::configure(yarp::os::ResourceFinder & rf)\r\n{\r\n\t\/\/ nothing\r\n\treturn true;\r\n}\r\n\r\n\r\nbool SWOpenNITracking::updateModule()\r\n{\r\n\tif (!m_IsOpenNiInitialized)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::vector<swDevice::SWKinectSkeleton::Coordinates> l_values;\r\n if (m_oKinectSkeleton->grab(l_values) == 0)\r\n\t{\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointTorso\t\t= l_values[0];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointNeck\t\t= l_values[1];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointHead\t\t= l_values[2];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointLShoulder\t\t= l_values[3];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointRShoulder\t\t= l_values[4];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointLElbow\t\t= l_values[5];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointRElbow\t\t= l_values[6];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointLHand\t\t= l_values[7];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointRHand\t\t= l_values[8];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointLHip\t\t\t= l_values[9];\r\n\t\tswDevice::SWKinectSkeleton::Coordinates l_pointRHip\t\t\t= l_values[10];\r\n\r\n\r\n yarp::os::Bottle & l_HeadBottle\t\t= m_oHeadTrackingPort.prepare();\r\n\t\tl_HeadBottle.clear();\r\n\t\t\tl_HeadBottle.addInt(swTracking::OPENNI_LIB);\r\n\t\t\tl_HeadBottle.addDouble(l_pointNeck.X);\t\t\tl_HeadBottle.addDouble(l_pointNeck.Y);\t\t\tl_HeadBottle.addDouble(l_pointNeck.Z);\r\n\t\t\tl_HeadBottle.addDouble(l_pointHead.X);\t\t\tl_HeadBottle.addDouble(l_pointHead.Y);\t\t\tl_HeadBottle.addDouble(l_pointHead.Z);\r\n\t\t\tl_HeadBottle.addDouble(l_pointLShoulder.X);\t\tl_HeadBottle.addDouble(l_pointLShoulder.Y);\t\tl_HeadBottle.addDouble(l_pointLShoulder.Z);\r\n\t\t\tl_HeadBottle.addDouble(l_pointRShoulder.X);\t\tl_HeadBottle.addDouble(l_pointRShoulder.Y);\t\tl_HeadBottle.addDouble(l_pointRShoulder.Z);\r\n m_oHeadTrackingPort.write();\r\n\r\n yarp::os::Bottle & l_TorsoBottle \t= m_oTorsoTrackingPort.prepare();\r\n\t\tl_TorsoBottle.clear();\r\n\t\t\tl_TorsoBottle.addInt(swTracking::OPENNI_LIB);\r\n\t\t\tl_TorsoBottle.addDouble(l_pointTorso.X);\t\tl_TorsoBottle.addDouble(l_pointTorso.Y);\t\tl_TorsoBottle.addDouble(l_pointTorso.Z);\r\n\t\t\tl_TorsoBottle.addDouble(l_pointNeck.X);\t\t\tl_TorsoBottle.addDouble(l_pointNeck.Y);\t\t\tl_TorsoBottle.addDouble(l_pointNeck.Z);\r\n\t\t\tl_TorsoBottle.addDouble(l_pointLShoulder.X);\tl_TorsoBottle.addDouble(l_pointLShoulder.Y);\tl_TorsoBottle.addDouble(l_pointLShoulder.Z);\r\n\t\t\tl_TorsoBottle.addDouble(l_pointRShoulder.X);\tl_TorsoBottle.addDouble(l_pointRShoulder.Y);\tl_TorsoBottle.addDouble(l_pointRShoulder.Z);\r\n m_oTorsoTrackingPort.write();\r\n\r\n yarp::os::Bottle & l_LeftArmBottle \t= m_oLeftArmTrackingPort.prepare();\r\n\t\tl_LeftArmBottle.clear();\r\n\t\t\tl_LeftArmBottle.addInt(swTracking::OPENNI_LIB);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointTorso.X);\t\tl_LeftArmBottle.addDouble(l_pointTorso.Y);\t\tl_LeftArmBottle.addDouble(l_pointTorso.Z);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointNeck.X);\t\tl_LeftArmBottle.addDouble(l_pointNeck.Y);\t\tl_LeftArmBottle.addDouble(l_pointNeck.Z);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointLShoulder.X);\tl_LeftArmBottle.addDouble(l_pointLShoulder.Y);\tl_LeftArmBottle.addDouble(l_pointLShoulder.Z);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointLElbow.X);\t\tl_LeftArmBottle.addDouble(l_pointLElbow.Y);\t\tl_LeftArmBottle.addDouble(l_pointLElbow.Z);\r\n\t\t\tl_LeftArmBottle.addDouble(l_pointLHand.X);\t\tl_LeftArmBottle.addDouble(l_pointLHand.Y);\t\tl_LeftArmBottle.addDouble(l_pointLHand.Z);\r\n m_oLeftArmTrackingPort.write();\r\n\r\n yarp::os::Bottle & l_RightArmBottle = m_oRightArmTrackingPort.prepare();\r\n\t\tl_RightArmBottle.clear();\r\n\t\t\tl_RightArmBottle.addInt(swTracking::OPENNI_LIB);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointTorso.X);\t\tl_RightArmBottle.addDouble(l_pointTorso.Y);\t\tl_RightArmBottle.addDouble(l_pointTorso.Z);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointNeck.X);\t\tl_RightArmBottle.addDouble(l_pointNeck.Y);\t\tl_RightArmBottle.addDouble(l_pointNeck.Z);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointRShoulder.X);\tl_RightArmBottle.addDouble(l_pointRShoulder.Y);\tl_RightArmBottle.addDouble(l_pointRShoulder.Z);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointRElbow.X);\tl_RightArmBottle.addDouble(l_pointRElbow.Y);\tl_RightArmBottle.addDouble(l_pointRElbow.Z);\r\n\t\t\tl_RightArmBottle.addDouble(l_pointRHand.X);\t\tl_RightArmBottle.addDouble(l_pointRHand.Y);\t\tl_RightArmBottle.addDouble(l_pointRHand.Z);\r\n m_oRightArmTrackingPort.write(); \r\n\r\n\r\n yarp::os::Bottle &l_allJointsBottle = m_oAllJointsTrackingPort.prepare();\r\n l_allJointsBottle.clear();\r\n l_HeadBottle.addDouble(l_pointNeck.X);\t\t\tl_HeadBottle.addDouble(l_pointNeck.Y);\t\t\tl_HeadBottle.addDouble(l_pointNeck.Z);\r\n l_HeadBottle.addDouble(l_pointHead.X);\t\t\tl_HeadBottle.addDouble(l_pointHead.Y);\t\t\tl_HeadBottle.addDouble(l_pointHead.Z);\r\n l_HeadBottle.addDouble(l_pointLShoulder.X);\t\tl_HeadBottle.addDouble(l_pointLShoulder.Y);\t\tl_HeadBottle.addDouble(l_pointLShoulder.Z);\r\n l_HeadBottle.addDouble(l_pointRShoulder.X);\t\tl_HeadBottle.addDouble(l_pointRShoulder.Y);\t\tl_HeadBottle.addDouble(l_pointRShoulder.Z);\r\n l_TorsoBottle.addDouble(l_pointTorso.X);\t\tl_TorsoBottle.addDouble(l_pointTorso.Y);\t\tl_TorsoBottle.addDouble(l_pointTorso.Z);\r\n l_LeftArmBottle.addDouble(l_pointLElbow.X);\t\tl_LeftArmBottle.addDouble(l_pointLElbow.Y);\t\tl_LeftArmBottle.addDouble(l_pointLElbow.Z);\r\n l_RightArmBottle.addDouble(l_pointRElbow.X);\tl_RightArmBottle.addDouble(l_pointRElbow.Y);\tl_RightArmBottle.addDouble(l_pointRElbow.Z);\r\n l_LeftArmBottle.addDouble(l_pointLHand.X);\t\tl_LeftArmBottle.addDouble(l_pointLHand.Y);\t\tl_LeftArmBottle.addDouble(l_pointLHand.Z);\r\n l_RightArmBottle.addDouble(l_pointRHand.X);\t\tl_RightArmBottle.addDouble(l_pointRHand.Y);\t\tl_RightArmBottle.addDouble(l_pointRHand.Z);\r\n m_oAllJointsTrackingPort.write();\r\n\t}\r\n\r\n\treturn true; \/\/ RF Module OK\r\n}\r\n\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\r\n yarp::os::Network netwotk;\r\n if (!netwotk.checkNetwork())\r\n {\r\n std::cerr << \"\/!\\\\ Problem connecting to YARP server.\" << std::endl;\r\n return -1;\r\n } \r\n\r\n std::cout << \"Starting the OpenNI Skeleton capture module..\" << std::endl;\r\n SWOpenNITracking l_OpenNITracking;\r\n\r\n \/\/ prepare and configure the resource finder\r\n\/\/ yarp::os::ResourceFinder rf;\r\n\/\/ rf.setVerbose(true);\r\n\/\/ rf.setDefaultConfigFile(\"openniTracking.ini\");\r\n\/\/ rf.setDefaultContext(\"swtracking\/conf\");\r\n\/\/ rf.configure(\"YARP_DIR\", argc, argv);\r\n\r\n\/\/ if(l_OpenNITracking.configure(rf))\r\n\/\/ {\r\n l_OpenNITracking.runModule();\r\n\/\/ }\r\n\r\n std::cout << \"Ending OpenNI Skeleton capture module...\" << std::endl;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright © 2017-2018 Ruben Van Boxem\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\n#include \"gui\/events\/xcb.h++\"\n\n#include \"gui\/native_window\/xcb.h++\"\n#include \"gui\/native_window\/xlib.h++\"\n#include \"gui\/window.h++\"\n\n#include <core\/debug.h++>\n\nnamespace\n{\n using namespace skui::gui::input;\n\n std::uint8_t mask_send_event_bit(std::uint8_t response_type)\n {\n return response_type & 0b0111'1111;\n }\n\n std::optional<button> get_button(xcb_button_t xcb_button)\n {\n switch(xcb_button)\n {\n case 1:\n return button::primary;\n case 2:\n return button::middle;\n case 3:\n return button::secondary;\n default:\n return {};\n }\n }\n\n std::optional<scroll> get_scroll(xcb_button_t xcb_button)\n {\n switch(xcb_button)\n {\n case 4:\n return scroll::up;\n case 5:\n return scroll::down;\n case 6:\n return scroll::left; \/\/?\n case 7:\n return scroll::right; \/\/?\n default:\n return {};\n }\n }\n}\n\nnamespace skui\n{\n namespace gui\n {\n namespace events\n {\n xcb::xcb(gui::window& window)\n : base{window}\n {\n auto native_xcb_window = dynamic_cast<native_window::xcb*>(&window.get_native_window());\n if(!native_xcb_window)\n core::debug_print(\"events::xcb requires a native_window::xcb or native_window::xlib.\\n\");\n\n connection = native_xcb_window->get_connection();\n xcb_window = native_xcb_window->get_window();\n\n \/\/ The magic incantation to receive and be able to check for the \"window was closed\" event\n xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, true, 12, \"WM_PROTOCOLS\");\n core::unique_free_ptr<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(connection, cookie, nullptr));\n\n xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, false, 16, \"WM_DELETE_WINDOW\");\n wm_delete_window.reset(xcb_intern_atom_reply(connection, cookie2, nullptr));\n\n xcb_change_property(connection,\n XCB_PROP_MODE_REPLACE,\n xcb_window,\n reply->atom, 4, 32, 1, &wm_delete_window->atom);\n \/\/ end magic\n\n xcb_flush(connection);\n }\n\n xcb::~xcb() = default;\n\n void xcb::exec()\n {\n bool running = true;\n\n while(running)\n {\n core::unique_free_ptr<const xcb_generic_event_t> event_ptr(xcb_wait_for_event(connection));\n if(!event_ptr)\n {\n core::debug_print(\"Call to xcb_wait_for_event failed. Most likely an I\/O error.\\n\");\n running = false;\n break;\n }\n\n switch(mask_send_event_bit(event_ptr->response_type))\n {\n case XCB_EXPOSE:\n {\n const auto& expose = reinterpret_cast<const xcb_expose_event_t&>(*event_ptr);\n if(expose.count>0)\n continue;\n\n window.repaint();\n\n break;\n }\n case XCB_UNMAP_NOTIFY:\n {\n \/\/const auto& unmap = reinterpret_cast<const xcb_unmap_notify_event_t&>(*event_ptr);\n break;\n }\n case XCB_MAP_NOTIFY:\n {\n \/\/const auto& map = reinterpret_cast<const xcb_map_notify_event_t&>(*event_ptr);\n window.state = window_state::windowed;\n\n \/\/ Force a repaint on map. This ensures a unminized window is properly displayed.\n window.repaint(true);\n\n break;\n }\n case XCB_BUTTON_PRESS:\n {\n const auto& button_press = reinterpret_cast<const xcb_button_press_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{button_press.event_x,\n button_press.event_y};\n\n if(const auto button = get_button(button_press.detail); button)\n {\n pressed_buttons.set(*button);\n\n window.pointer.pressed(*button, position);\n }\n else if(const auto scroll = get_scroll(button_press.detail); scroll)\n {\n window.pointer.scroll(*scroll, position);\n }\n\n break;\n }\n case XCB_BUTTON_RELEASE:\n {\n const auto& button_release = reinterpret_cast<const xcb_button_release_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{button_release.event_x,\n button_release.event_y};\n\n if(const auto button = get_button(button_release.detail); button)\n {\n const bool click = pressed_buttons.test(*button);\n pressed_buttons.unset(*button);\n\n window.pointer.released(*button, position);\n if(click)\n window.pointer.clicked(*button, position);\n }\n\n break;\n }\n case XCB_MOTION_NOTIFY:\n {\n const auto& motion = reinterpret_cast<const xcb_motion_notify_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{motion.event_x,\n motion.event_y};\n window.pointer.moved(position);\n\n break;\n }\n case XCB_ENTER_NOTIFY:\n {\n const auto& enter = reinterpret_cast<const xcb_enter_notify_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{enter.event_x,\n enter.event_y};\n window.pointer.entered(position);\n\n break;\n }\n case XCB_LEAVE_NOTIFY:\n {\n const auto& leave = reinterpret_cast<const xcb_leave_notify_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{leave.event_x,\n leave.event_y};\n window.pointer.left(position);\n\n break;\n }\n case XCB_KEY_PRESS:\n {\n \/\/const auto& key_press = reinterpret_cast<xcb_key_press_event_t&>(*event_ptr);\n \/\/implementation::print_modifiers(key_press->state);\n break;\n }\n case XCB_KEY_RELEASE:\n {\n \/\/const auto& key_release = reinterpret_cast<xcb_key_release_event_t*>(*event_ptr);\n \/\/implementation::print_modifiers(key_release->state);\n break;\n }\n case XCB_CONFIGURE_NOTIFY:\n {\n \/\/const auto& configure_notify = reinterpret_cast<const xcb_configure_notify_event_t&>(*event_ptr);\n\n window.repaint(true);\n\n break;\n }\n case XCB_CLIENT_MESSAGE:\n {\n const auto& client_message = reinterpret_cast<const xcb_client_message_event_t&>(*event_ptr);\n\n if(client_message.data.data32[0] == wm_delete_window->atom)\n {\n core::debug_print(\"WM_DELETE_WINDOW received.\\n\");\n window.close();\n }\n break;\n }\n case XCB_DESTROY_NOTIFY:\n {\n running = false;\n break;\n }\n case XCB_REPARENT_NOTIFY:\n {\n \/\/const auto& reparent = reinterpret_cast<const xcb_reparent_notify_event_t&>(*event_ptr);\n\n break;\n }\n default:\n if(const auto* xlib_window = dynamic_cast<native_window::xlib*>(&window.get_native_window());\n xlib_window)\n {\n xlib_window->handle_dri2_events(const_cast<xcb_generic_event_t&>(*event_ptr));\n break;\n }\n core::debug_print(\"Unknown event: \", (int)mask_send_event_bit(event_ptr->response_type), \".\\n\");\n break;\n }\n }\n }\n }\n }\n}\n<commit_msg>It is better to force repaint on expose instead of configure events. Some extra painting could be seen after resizing fast for some time before this change.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright © 2017-2018 Ruben Van Boxem\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\n#include \"gui\/events\/xcb.h++\"\n\n#include \"gui\/native_window\/xcb.h++\"\n#include \"gui\/native_window\/xlib.h++\"\n#include \"gui\/window.h++\"\n\n#include <core\/debug.h++>\n\nnamespace\n{\n using namespace skui::gui::input;\n\n std::uint8_t mask_send_event_bit(std::uint8_t response_type)\n {\n return response_type & 0b0111'1111;\n }\n\n std::optional<button> get_button(xcb_button_t xcb_button)\n {\n switch(xcb_button)\n {\n case 1:\n return button::primary;\n case 2:\n return button::middle;\n case 3:\n return button::secondary;\n default:\n return {};\n }\n }\n\n std::optional<scroll> get_scroll(xcb_button_t xcb_button)\n {\n switch(xcb_button)\n {\n case 4:\n return scroll::up;\n case 5:\n return scroll::down;\n case 6:\n return scroll::left; \/\/?\n case 7:\n return scroll::right; \/\/?\n default:\n return {};\n }\n }\n}\n\nnamespace skui\n{\n namespace gui\n {\n namespace events\n {\n xcb::xcb(gui::window& window)\n : base{window}\n {\n auto native_xcb_window = dynamic_cast<native_window::xcb*>(&window.get_native_window());\n if(!native_xcb_window)\n core::debug_print(\"events::xcb requires a native_window::xcb or native_window::xlib.\\n\");\n\n connection = native_xcb_window->get_connection();\n xcb_window = native_xcb_window->get_window();\n\n \/\/ The magic incantation to receive and be able to check for the \"window was closed\" event\n xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, true, 12, \"WM_PROTOCOLS\");\n core::unique_free_ptr<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(connection, cookie, nullptr));\n\n xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, false, 16, \"WM_DELETE_WINDOW\");\n wm_delete_window.reset(xcb_intern_atom_reply(connection, cookie2, nullptr));\n\n xcb_change_property(connection,\n XCB_PROP_MODE_REPLACE,\n xcb_window,\n reply->atom, 4, 32, 1, &wm_delete_window->atom);\n \/\/ end magic\n\n xcb_flush(connection);\n }\n\n xcb::~xcb() = default;\n\n void xcb::exec()\n {\n bool running = true;\n\n while(running)\n {\n core::unique_free_ptr<const xcb_generic_event_t> event_ptr(xcb_wait_for_event(connection));\n if(!event_ptr)\n {\n core::debug_print(\"Call to xcb_wait_for_event failed. Most likely an I\/O error.\\n\");\n running = false;\n break;\n }\n\n switch(mask_send_event_bit(event_ptr->response_type))\n {\n case XCB_EXPOSE:\n {\n const auto& expose = reinterpret_cast<const xcb_expose_event_t&>(*event_ptr);\n if(expose.count>0)\n continue;\n\n window.repaint(true);\n\n break;\n }\n case XCB_UNMAP_NOTIFY:\n {\n \/\/const auto& unmap = reinterpret_cast<const xcb_unmap_notify_event_t&>(*event_ptr);\n break;\n }\n case XCB_MAP_NOTIFY:\n {\n \/\/const auto& map = reinterpret_cast<const xcb_map_notify_event_t&>(*event_ptr);\n window.state = window_state::windowed;\n\n \/\/ Force a repaint on map. This ensures a unminized window is properly displayed.\n window.repaint(true);\n\n break;\n }\n case XCB_BUTTON_PRESS:\n {\n const auto& button_press = reinterpret_cast<const xcb_button_press_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{button_press.event_x,\n button_press.event_y};\n\n if(const auto button = get_button(button_press.detail); button)\n {\n pressed_buttons.set(*button);\n\n window.pointer.pressed(*button, position);\n }\n else if(const auto scroll = get_scroll(button_press.detail); scroll)\n {\n window.pointer.scroll(*scroll, position);\n }\n\n break;\n }\n case XCB_BUTTON_RELEASE:\n {\n const auto& button_release = reinterpret_cast<const xcb_button_release_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{button_release.event_x,\n button_release.event_y};\n\n if(const auto button = get_button(button_release.detail); button)\n {\n const bool click = pressed_buttons.test(*button);\n pressed_buttons.unset(*button);\n\n window.pointer.released(*button, position);\n if(click)\n window.pointer.clicked(*button, position);\n }\n\n break;\n }\n case XCB_MOTION_NOTIFY:\n {\n const auto& motion = reinterpret_cast<const xcb_motion_notify_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{motion.event_x,\n motion.event_y};\n window.pointer.moved(position);\n\n break;\n }\n case XCB_ENTER_NOTIFY:\n {\n const auto& enter = reinterpret_cast<const xcb_enter_notify_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{enter.event_x,\n enter.event_y};\n window.pointer.entered(position);\n\n break;\n }\n case XCB_LEAVE_NOTIFY:\n {\n const auto& leave = reinterpret_cast<const xcb_leave_notify_event_t&>(*event_ptr);\n\n const graphics::pixel_position position{leave.event_x,\n leave.event_y};\n window.pointer.left(position);\n\n break;\n }\n case XCB_KEY_PRESS:\n {\n \/\/const auto& key_press = reinterpret_cast<xcb_key_press_event_t&>(*event_ptr);\n \/\/implementation::print_modifiers(key_press->state);\n break;\n }\n case XCB_KEY_RELEASE:\n {\n \/\/const auto& key_release = reinterpret_cast<xcb_key_release_event_t*>(*event_ptr);\n \/\/implementation::print_modifiers(key_release->state);\n break;\n }\n case XCB_CONFIGURE_NOTIFY:\n {\n \/\/const auto& configure_notify = reinterpret_cast<const xcb_configure_notify_event_t&>(*event_ptr);\n\n window.repaint();\n\n break;\n }\n case XCB_CLIENT_MESSAGE:\n {\n const auto& client_message = reinterpret_cast<const xcb_client_message_event_t&>(*event_ptr);\n\n if(client_message.data.data32[0] == wm_delete_window->atom)\n {\n core::debug_print(\"WM_DELETE_WINDOW received.\\n\");\n window.close();\n }\n break;\n }\n case XCB_DESTROY_NOTIFY:\n {\n running = false;\n break;\n }\n case XCB_REPARENT_NOTIFY:\n {\n \/\/const auto& reparent = reinterpret_cast<const xcb_reparent_notify_event_t&>(*event_ptr);\n\n break;\n }\n default:\n if(const auto* xlib_window = dynamic_cast<native_window::xlib*>(&window.get_native_window());\n xlib_window)\n {\n xlib_window->handle_dri2_events(const_cast<xcb_generic_event_t&>(*event_ptr));\n break;\n }\n core::debug_print(\"Unknown event: \", (int)mask_send_event_bit(event_ptr->response_type), \".\\n\");\n break;\n }\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\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#ifndef __itkGradientRecursiveGaussianImageFilter_hxx\n#define __itkGradientRecursiveGaussianImageFilter_hxx\n\n#include \"itkGradientRecursiveGaussianImageFilter.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkImageRegionConstIterator.h\"\n\nnamespace itk\n{\n\/**\n * Constructor\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GradientRecursiveGaussianImageFilter()\n{\n m_NormalizeAcrossScale = false;\n this->m_UseImageDirection = true;\n\n unsigned int imageDimensionMinus1 = ImageDimension - 1;\n if ( ImageDimension > 1 )\n {\n m_SmoothingFilters.resize(imageDimensionMinus1);\n }\n\n for ( unsigned int i = 0; i < imageDimensionMinus1; i++ )\n {\n m_SmoothingFilters[i] = GaussianFilterType::New();\n m_SmoothingFilters[i]->SetOrder(GaussianFilterType::ZeroOrder);\n m_SmoothingFilters[i]->SetNormalizeAcrossScale(m_NormalizeAcrossScale);\n m_SmoothingFilters[i]->InPlaceOn();\n m_SmoothingFilters[i]->ReleaseDataFlagOn();\n }\n\n m_DerivativeFilter = DerivativeFilterType::New();\n m_DerivativeFilter->SetOrder(DerivativeFilterType::FirstOrder);\n m_DerivativeFilter->SetNormalizeAcrossScale(m_NormalizeAcrossScale);\n m_DerivativeFilter->ReleaseDataFlagOn();\n m_DerivativeFilter->InPlaceOff();\n m_DerivativeFilter->SetInput( this->GetInput() );\n\n if ( ImageDimension > 1 )\n {\n m_SmoothingFilters[0]->SetInput( m_DerivativeFilter->GetOutput() );\n }\n\n for ( unsigned int i = 1; i < imageDimensionMinus1; i++ )\n {\n m_SmoothingFilters[i]->SetInput(\n m_SmoothingFilters[i - 1]->GetOutput() );\n }\n\n m_ImageAdaptor = OutputImageAdaptorType::New();\n\n this->SetSigma(1.0);\n}\n\n\/**\n * Set value of Sigma\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::SetSigma(ScalarRealType sigma)\n{\n int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;\n\n for ( int i = 0; i < imageDimensionMinus1; i++ )\n {\n m_SmoothingFilters[i]->SetSigma(sigma);\n }\n m_DerivativeFilter->SetSigma(sigma);\n\n this->Modified();\n}\n\n\/**\n * Get value of Sigma\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\ntypename GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::RealType\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GetSigma() const\n{\n return m_DerivativeFilter->GetSigma();\n}\n\n\/**\n * Set Normalize Across Scale Space\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::SetNormalizeAcrossScale(bool normalize)\n{\n m_NormalizeAcrossScale = normalize;\n\n int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;\n for ( int i = 0; i < imageDimensionMinus1; i++ )\n {\n m_SmoothingFilters[i]->SetNormalizeAcrossScale(normalize);\n }\n m_DerivativeFilter->SetNormalizeAcrossScale(normalize);\n\n this->Modified();\n}\n\n\/\/\n\/\/\n\/\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GenerateInputRequestedRegion()\n{\n \/\/ call the superclass' implementation of this method. this should\n \/\/ copy the output requested region to the input requested region\n Superclass::GenerateInputRequestedRegion();\n\n \/\/ This filter needs all of the input\n typename GradientRecursiveGaussianImageFilter< TInputImage,\n TOutputImage >::InputImagePointer image =\n const_cast< InputImageType * >( this->GetInput() );\n if ( image )\n {\n image->SetRequestedRegion( this->GetInput()->GetLargestPossibleRegion() );\n }\n}\n\n\/\/\n\/\/\n\/\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::EnlargeOutputRequestedRegion(DataObject *output)\n{\n TOutputImage *out = dynamic_cast< TOutputImage * >( output );\n\n if ( out )\n {\n out->SetRequestedRegion( out->GetLargestPossibleRegion() );\n }\n}\n\n\/**\n * Compute filter for Gaussian kernel\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GenerateData(void)\n{\n \/\/ Create a process accumulator for tracking the progress of this\n \/\/ minipipeline\n ProgressAccumulator::Pointer progress = ProgressAccumulator::New();\n progress->SetMiniPipelineFilter(this);\n\n \/\/ Compute the contribution of each filter to the total progress.\n const double weight = 1.0 \/ ( ImageDimension * ImageDimension );\n\n unsigned int imageDimensionMinus1 = ImageDimension - 1;\n for ( unsigned int i = 0; i < imageDimensionMinus1; i++ )\n {\n progress->RegisterInternalFilter(m_SmoothingFilters[i], weight);\n }\n\n progress->RegisterInternalFilter(m_DerivativeFilter, weight);\n\n const typename TInputImage::ConstPointer inputImage( this->GetInput() );\n typename TOutputImage::Pointer outputImage( this->GetOutput() );\n\n unsigned int nComponents = inputImage->GetNumberOfComponentsPerPixel();\n \/* An Image of VariableLengthVectors will return 0 *\/\n if (nComponents == 0 )\n {\n const typename InputImageType::IndexType idx = inputImage->GetLargestPossibleRegion().GetIndex();\n nComponents = NumericTraits<typename InputImageType::PixelType>::GetLength( inputImage->GetPixel(idx) );\n }\n\n m_ImageAdaptor->SetImage( outputImage );\n\n m_ImageAdaptor->SetLargestPossibleRegion(\n inputImage->GetLargestPossibleRegion() );\n\n m_ImageAdaptor->SetBufferedRegion(\n inputImage->GetBufferedRegion() );\n\n m_ImageAdaptor->SetRequestedRegion(\n inputImage->GetRequestedRegion() );\n\n m_ImageAdaptor->Allocate();\n\n m_DerivativeFilter->SetInput(inputImage);\n\n \/\/ For variable length output pixel types\n ImageRegionIteratorWithIndex<OutputImageType> initGradIt(\n outputImage, this->m_ImageAdaptor->GetRequestedRegion() );\n\n\n for ( unsigned int nc = 0; nc < nComponents; nc++ )\n {\n for ( unsigned int dim = 0; dim < ImageDimension; dim++ )\n {\n unsigned int i = 0;\n unsigned int j = 0;\n while ( i < imageDimensionMinus1 )\n {\n if ( i == dim )\n {\n j++;\n }\n m_SmoothingFilters[i]->SetDirection(j);\n i++;\n j++;\n }\n m_DerivativeFilter->SetDirection(dim);\n\n GaussianFilterPointer lastFilter;\n\n if ( ImageDimension > 1 )\n {\n const unsigned int imageDimensionMinus2 = static_cast< unsigned int >( ImageDimension - 2 );\n lastFilter = m_SmoothingFilters[imageDimensionMinus2];\n lastFilter->UpdateLargestPossibleRegion();\n }\n else\n {\n m_DerivativeFilter->UpdateLargestPossibleRegion();\n }\n\n \/\/ Copy the results to the corresponding component\n \/\/ on the output image of vectors\n m_ImageAdaptor->SelectNthElement(nc*ImageDimension + dim);\n\n typename RealImageType::Pointer derivativeImage;\n if ( ImageDimension > 1 )\n {\n derivativeImage = lastFilter->GetOutput();\n }\n else\n {\n derivativeImage = m_DerivativeFilter->GetOutput();\n }\n\n ImageRegionIteratorWithIndex< RealImageType > it(\n derivativeImage,\n derivativeImage->GetRequestedRegion() );\n\n ImageRegionIteratorWithIndex< OutputImageAdaptorType > ot(\n m_ImageAdaptor,\n m_ImageAdaptor->GetRequestedRegion() );\n\n const ScalarRealType spacing = inputImage->GetSpacing()[dim];\n\n it.GoToBegin();\n ot.GoToBegin();\n while ( !it.IsAtEnd() )\n {\n OutputComponentType outValue = static_cast<OutputComponentType>( DefaultConvertPixelTraits<InternalRealType>::GetNthComponent( nc, it.Get() \/ spacing ) );\n ot.Set( outValue );\n ++it;\n ++ot;\n }\n }\n }\n\n \/\/ manually release memory in last filter in the mini-pipeline\n if ( ImageDimension > 1 )\n {\n int temp_dim = static_cast< int >( ImageDimension ) - 2;\n m_SmoothingFilters[temp_dim]->GetOutput()->ReleaseData();\n }\n else\n {\n m_DerivativeFilter->GetOutput()->ReleaseData();\n }\n\n \/\/ If the flag for using the input image direction is ON,\n \/\/ then we apply the direction correction to all the pixels\n \/\/ of the output gradient image.\n if ( this->m_UseImageDirection )\n {\n\n OutputImageType *gradientImage = outputImage;\n ImageRegionIterator< OutputImageType > itr( gradientImage,\n gradientImage->GetRequestedRegion() );\n\n while ( !itr.IsAtEnd() )\n {\n\n TransformOutputPixel( itr );\n ++itr;\n }\n\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GenerateOutputInformation()\n{\n \/\/ this methods is overloaded so that if the output image is a\n \/\/ VectorImage then the correct number of components are set.\n\n\n Superclass::GenerateOutputInformation();\n\n OutputImageType* output = this->GetOutput();\n const typename TInputImage::ConstPointer inputImage( this->GetInput() );\n\n unsigned int nComponents = inputImage->GetNumberOfComponentsPerPixel() * ImageDimension;\n\n\n output->SetNumberOfComponentsPerPixel( nComponents );\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n os << indent << \"NormalizeAcrossScale: \" << m_NormalizeAcrossScale << std::endl;\n os << indent << \"UseImageDirection : \"\n << ( this->m_UseImageDirection ? \"On\" : \"Off\" ) << std::endl;\n}\n} \/\/ end namespace itk\n\n#endif\n<commit_msg>COMP: Improve const correctness of GradientRecursiveGaussianImageFilter.<commit_after>\/*=========================================================================\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#ifndef __itkGradientRecursiveGaussianImageFilter_hxx\n#define __itkGradientRecursiveGaussianImageFilter_hxx\n\n#include \"itkGradientRecursiveGaussianImageFilter.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkImageRegionConstIterator.h\"\n\nnamespace itk\n{\n\/**\n * Constructor\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GradientRecursiveGaussianImageFilter()\n{\n m_NormalizeAcrossScale = false;\n this->m_UseImageDirection = true;\n\n const int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;\n if ( ImageDimension > 1 )\n {\n m_SmoothingFilters.resize(imageDimensionMinus1);\n\n for ( int i = 0; i < imageDimensionMinus1; ++i )\n {\n m_SmoothingFilters[i] = GaussianFilterType::New();\n m_SmoothingFilters[i]->SetOrder(GaussianFilterType::ZeroOrder);\n m_SmoothingFilters[i]->SetNormalizeAcrossScale(m_NormalizeAcrossScale);\n m_SmoothingFilters[i]->InPlaceOn();\n m_SmoothingFilters[i]->ReleaseDataFlagOn();\n }\n }\n\n m_DerivativeFilter = DerivativeFilterType::New();\n m_DerivativeFilter->SetOrder(DerivativeFilterType::FirstOrder);\n m_DerivativeFilter->SetNormalizeAcrossScale(m_NormalizeAcrossScale);\n m_DerivativeFilter->ReleaseDataFlagOn();\n m_DerivativeFilter->InPlaceOff();\n m_DerivativeFilter->SetInput( this->GetInput() );\n\n if ( ImageDimension > 1 )\n {\n m_SmoothingFilters[0]->SetInput( m_DerivativeFilter->GetOutput() );\n\n for ( int i = 1; i < imageDimensionMinus1; ++i )\n {\n m_SmoothingFilters[i]->SetInput(\n m_SmoothingFilters[i - 1]->GetOutput() );\n }\n }\n\n m_ImageAdaptor = OutputImageAdaptorType::New();\n\n this->SetSigma(1.0);\n}\n\n\/**\n * Set value of Sigma\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::SetSigma(ScalarRealType sigma)\n{\n if (ImageDimension > 1)\n {\n const int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;\n for ( int i = 0; i < imageDimensionMinus1; ++i )\n {\n m_SmoothingFilters[i]->SetSigma(sigma);\n }\n }\n m_DerivativeFilter->SetSigma(sigma);\n this->Modified();\n}\n\n\/**\n * Get value of Sigma\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\ntypename GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::RealType\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GetSigma() const\n{\n return m_DerivativeFilter->GetSigma();\n}\n\n\/**\n * Set Normalize Across Scale Space\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::SetNormalizeAcrossScale(bool normalize)\n{\n m_NormalizeAcrossScale = normalize;\n\n const int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;\n for ( int i = 0; i < imageDimensionMinus1; i++ )\n {\n m_SmoothingFilters[i]->SetNormalizeAcrossScale(normalize);\n }\n m_DerivativeFilter->SetNormalizeAcrossScale(normalize);\n\n this->Modified();\n}\n\n\/\/\n\/\/\n\/\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GenerateInputRequestedRegion()\n{\n \/\/ call the superclass' implementation of this method. this should\n \/\/ copy the output requested region to the input requested region\n Superclass::GenerateInputRequestedRegion();\n\n \/\/ This filter needs all of the input\n typename GradientRecursiveGaussianImageFilter< TInputImage,\n TOutputImage >::InputImagePointer image =\n const_cast< InputImageType * >( this->GetInput() );\n if ( image )\n {\n image->SetRequestedRegion( this->GetInput()->GetLargestPossibleRegion() );\n }\n}\n\n\/\/\n\/\/\n\/\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::EnlargeOutputRequestedRegion(DataObject *output)\n{\n TOutputImage *out = dynamic_cast< TOutputImage * >( output );\n\n if ( out )\n {\n out->SetRequestedRegion( out->GetLargestPossibleRegion() );\n }\n}\n\n\/**\n * Compute filter for Gaussian kernel\n *\/\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GenerateData(void)\n{\n \/\/ Create a process accumulator for tracking the progress of this\n \/\/ minipipeline\n ProgressAccumulator::Pointer progress = ProgressAccumulator::New();\n progress->SetMiniPipelineFilter(this);\n\n \/\/ Compute the contribution of each filter to the total progress.\n const double weight = 1.0 \/ ( ImageDimension * ImageDimension );\n\n const int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;\n if( ImageDimension > 1 )\n {\n for( int i = 0; i < imageDimensionMinus1; ++i )\n {\n progress->RegisterInternalFilter(m_SmoothingFilters[i], weight);\n }\n }\n\n progress->RegisterInternalFilter(m_DerivativeFilter, weight);\n\n const typename TInputImage::ConstPointer inputImage( this->GetInput() );\n typename TOutputImage::Pointer outputImage( this->GetOutput() );\n\n unsigned int nComponents = inputImage->GetNumberOfComponentsPerPixel();\n \/* An Image of VariableLengthVectors will return 0 *\/\n if (nComponents == 0 )\n {\n const typename InputImageType::IndexType idx = inputImage->GetLargestPossibleRegion().GetIndex();\n nComponents = NumericTraits<typename InputImageType::PixelType>::GetLength( inputImage->GetPixel(idx) );\n }\n\n m_ImageAdaptor->SetImage( outputImage );\n\n m_ImageAdaptor->SetLargestPossibleRegion(\n inputImage->GetLargestPossibleRegion() );\n\n m_ImageAdaptor->SetBufferedRegion(\n inputImage->GetBufferedRegion() );\n\n m_ImageAdaptor->SetRequestedRegion(\n inputImage->GetRequestedRegion() );\n\n m_ImageAdaptor->Allocate();\n\n m_DerivativeFilter->SetInput(inputImage);\n\n \/\/ For variable length output pixel types\n ImageRegionIteratorWithIndex<OutputImageType> initGradIt(\n outputImage, this->m_ImageAdaptor->GetRequestedRegion() );\n\n\n for ( unsigned int nc = 0; nc < nComponents; ++nc )\n {\n for ( int dim = 0; dim < ImageDimension; ++dim )\n {\n int i = 0;\n int j = 0;\n while( i < imageDimensionMinus1 )\n {\n if( i == dim )\n {\n ++j;\n }\n m_SmoothingFilters[i]->SetDirection(j);\n ++i;\n ++j;\n }\n m_DerivativeFilter->SetDirection(dim);\n\n GaussianFilterPointer lastFilter;\n\n if ( ImageDimension > 1 )\n {\n const unsigned int imageDimensionMinus2 = static_cast< unsigned int >( ImageDimension - 2 );\n lastFilter = m_SmoothingFilters[imageDimensionMinus2];\n lastFilter->UpdateLargestPossibleRegion();\n }\n else\n {\n m_DerivativeFilter->UpdateLargestPossibleRegion();\n }\n\n \/\/ Copy the results to the corresponding component\n \/\/ on the output image of vectors\n m_ImageAdaptor->SelectNthElement(nc*ImageDimension + dim);\n\n typename RealImageType::Pointer derivativeImage;\n if ( ImageDimension > 1 )\n {\n derivativeImage = lastFilter->GetOutput();\n }\n else\n {\n derivativeImage = m_DerivativeFilter->GetOutput();\n }\n\n ImageRegionIteratorWithIndex< RealImageType > it(\n derivativeImage,\n derivativeImage->GetRequestedRegion() );\n\n ImageRegionIteratorWithIndex< OutputImageAdaptorType > ot(\n m_ImageAdaptor,\n m_ImageAdaptor->GetRequestedRegion() );\n\n const ScalarRealType spacing = inputImage->GetSpacing()[dim];\n\n it.GoToBegin();\n ot.GoToBegin();\n while ( !it.IsAtEnd() )\n {\n OutputComponentType outValue = static_cast<OutputComponentType>( DefaultConvertPixelTraits<InternalRealType>::GetNthComponent( nc, it.Get() \/ spacing ) );\n ot.Set( outValue );\n ++it;\n ++ot;\n }\n }\n }\n\n \/\/ manually release memory in last filter in the mini-pipeline\n if ( ImageDimension > 1 )\n {\n int temp_dim = static_cast< int >( ImageDimension ) - 2;\n m_SmoothingFilters[temp_dim]->GetOutput()->ReleaseData();\n }\n else\n {\n m_DerivativeFilter->GetOutput()->ReleaseData();\n }\n\n \/\/ If the flag for using the input image direction is ON,\n \/\/ then we apply the direction correction to all the pixels\n \/\/ of the output gradient image.\n if ( this->m_UseImageDirection )\n {\n\n OutputImageType *gradientImage = outputImage;\n ImageRegionIterator< OutputImageType > itr( gradientImage,\n gradientImage->GetRequestedRegion() );\n\n while ( !itr.IsAtEnd() )\n {\n\n TransformOutputPixel( itr );\n ++itr;\n }\n\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::GenerateOutputInformation()\n{\n \/\/ this methods is overloaded so that if the output image is a\n \/\/ VectorImage then the correct number of components are set.\n\n\n Superclass::GenerateOutputInformation();\n\n OutputImageType* output = this->GetOutput();\n const typename TInputImage::ConstPointer inputImage( this->GetInput() );\n\n const unsigned int nComponents = inputImage->GetNumberOfComponentsPerPixel() * ImageDimension;\n\n\n output->SetNumberOfComponentsPerPixel( nComponents );\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nGradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n os << indent << \"NormalizeAcrossScale: \" << m_NormalizeAcrossScale << std::endl;\n os << indent << \"UseImageDirection : \"\n << ( this->m_UseImageDirection ? \"On\" : \"Off\" ) << std::endl;\n}\n\n} \/\/ end namespace itk\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\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#include \"otbWrapperMapProjectionParametersHandler.h\"\n\n\/\/ Needed for methods relative to projections\n#include \"otbMapProjections.h\"\n#include \"otbImageToGenericRSOutputParameters.h\"\n#include \"otbWrapperInputImageListParameter.h\"\n\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nvoid MapProjectionParametersHandler::AddMapProjectionParameters( Application::Pointer app, const std::string & key)\n{\n app->AddParameter(ParameterType_Choice, key, \"Output Cartographic Map Projection\");\n app->SetParameterDescription(key,\"Parameters of the output map projection to be used.\");\n\n \/\/ utm\n std::ostringstream oss;\n oss << key<<\".utm\";\n app->AddChoice(oss.str(), \"Universal Trans-Mercator (UTM)\");\n app->SetParameterDescription(oss.str(),\"A system of transverse mercator projections dividing the surface of Earth between 80S and 84N latitude.\");\n\n oss << \".zone\";\n app->AddParameter(ParameterType_Int, oss.str(), \"Zone number\");\n app->SetParameterDescription(oss.str(),\"The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere)\");\n app->SetMinimumParameterIntValue(oss.str(), 1);\n app->SetDefaultParameterInt(oss.str(), 31);\n\n oss.str(\"\");\n oss <<key<<\".utm\" <<\".northhem\";\n app->AddParameter(ParameterType_Empty, oss.str(), \"Northern Hemisphere\");\n app->SetParameterDescription(oss.str(),\"The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.\");\n\n\n \/\/ lambert2\n oss.str(\"\");\n oss << key<<\".lambert2\";\n app->AddChoice(oss.str(), \"Lambert II Etendu\");\n app->SetParameterDescription(oss.str(),\"This is a Lambert Conformal Conic projection mainly used in France.\");\n\n \/\/ lambert93\n oss.str(\"\");\n oss << key<<\".lambert93\";\n app->AddChoice(oss.str(), \"Lambert93\");\n app->SetParameterDescription(oss.str(), \"This is a Lambert 93 projection mainly used in France.\");\n\n \/\/ Transmercator\n \/*oss.str(\"\");\n oss << key<<\".transmercator\";\n app->AddChoice(oss.str(), \"Transmercator\");\n app->SetParameterDescription(oss.str(),\n \"This is a Transverse Mercator, a cylindrical projection widely used. The required values are set by default.\");\n\n std::ostringstream subParamKey;\n subParamKey<<oss.str()<<\".falseeasting\";\n app->AddParameter(ParameterType_Float, subParamKey.str(), \"False easting\");\n app->SetParameterDescription( subParamKey.str(), \" Transmercator false easting value.\");\n app->SetDefaultParameterFloat(subParamKey.str(), 0.);\n\n subParamKey.str(\"\");\n subParamKey<<oss.str()<<\".falsenorthing\";\n app->AddParameter(ParameterType_Float, subParamKey.str(), \"False northing\");\n app->SetParameterDescription(subParamKey.str(), \" Transmercator false northing value.\");\n app->SetDefaultParameterFloat(subParamKey.str(), 0.);\n\n subParamKey.str(\"\");\n subParamKey<<oss.str()<<\".scale\";\n app->AddParameter(ParameterType_Float, subParamKey.str(), \"Scale factor\");\n app->SetParameterDescription(subParamKey.str(), \" Transmercator scale factor value.\");\n app->SetDefaultParameterFloat(subParamKey.str(), 1.);\n *\/\n \/\/ wgs84\n oss.str(\"\");\n oss << key<<\".wgs\";\n app->AddChoice(oss.str(), \"WGS 84\");\n app->SetParameterDescription(oss.str(),\"This is a Geographical projection\");\n\n \/\/ epsg code\n oss.str(\"\");\n oss<<key<<\".epsg\";\n app->AddChoice(oss.str(),\"EPSG Code\");\n app->SetParameterDescription(oss.str(),\n \"This code is a generic way of identifying map projections, and allows specifying a large amount of them. See www.spatialreference.org to find which EPSG code is associated to your projection;\");\n\n oss <<\".code\";\n app->AddParameter(ParameterType_Int, oss.str(), \"EPSG Code\");\n app->SetParameterDescription(oss.str(),\"See www.spatialreference.org to find which EPSG code is associated to your projection\");\n app->SetDefaultParameterInt(oss.str(), 4326);\n\n app->SetParameterString(key, \"utm\");\n}\n\n\/**\n * Helper method : Compute the ProjectionRef knowing the map\n * projection picked up by the user\n *\n *\/\nconst std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(const Application::Pointer app,\n const std::string & key)\n{\n std::ostringstream zoneKey;\n zoneKey << key<<\".utm.zone\";\n\n std::ostringstream hemKey;\n hemKey << key<<\".utm.northhem\";\n\n std::ostringstream epsgKey;\n epsgKey << key <<\".epsg.code\";\n\n \/\/ Get the user choice\n switch ( app->GetParameterInt(key) )\n {\n case Map_Utm:\n {\n otb::UtmInverseProjection::Pointer utmProjection =\n otb::UtmInverseProjection::New();\n\n \/\/ Set the zone\n utmProjection->SetZone(app->GetParameterInt(zoneKey.str()));\n\n \/\/ Set the hem\n char hem = 'N';\n if (!app->IsParameterEnabled(hemKey.str()))\n hem = 'S';\n utmProjection->SetHemisphere(hem);\n\n \/\/ Get the projection ref\n return utmProjection->GetWkt();\n }\n break;\n case Map_Lambert2:\n {\n otb::Lambert2EtenduForwardProjection::Pointer lambert2Projection =\n otb::Lambert2EtenduForwardProjection::New();\n return lambert2Projection->GetWkt();\n }\n break;\n case Map_Lambert93:\n {\n otb::Lambert93InverseProjection::Pointer lambert93Projection =\n otb::Lambert93InverseProjection::New();\n return lambert93Projection->GetWkt();\n }\n break;\n \/*case Map_Transmercator:\n {\n typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;\n TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();\n\n \/\/ Get the Transmercator parameters\n std::ostringstream falseeasting;\n std::ostringstream falsenorthing;\n std::ostringstream scale;\n\n falseeasting <<key <<\".transmercator.falseeasting\";\n falsenorthing <<key <<\".transmercator.falsenorthing\";\n scale <<key <<\".transmercator.scale\";\n\n transMercatorProjection->SetParameters(app->GetParameterFloat( falseeasting.str() ),\n app->GetParameterFloat( falsenorthing.str() ),\n app->GetParameterFloat( scale.str()) );\n return transMercatorProjection->GetWkt();\n }\n break; *\/\n case Map_WGS84:\n {\n return otb::GeoInformationConversion::ToWKT(4326);\n }\n break;\n case Map_Epsg:\n {\n return otb::GeoInformationConversion::ToWKT(app->GetParameterInt(epsgKey.str()));\n }\n break;\n }\n\n return \"\";\n}\n\n\/**\n * Helper method : Compute the UTM parameters relative to an image Origin\n * Note: The key of the image must be set to be able to get the image.\n * The key must be totally if the InputImageParameter belongs\n * to a ParameterGroup, ie set io.in\n *\/\nvoid MapProjectionParametersHandler::InitializeUTMParameters(Application::Pointer app,\n const std::string & imageKey,\n const std::string & mapKey )\n{\n \/\/ Get the UTM params keys\n std::ostringstream zoneKey;\n zoneKey << mapKey << \".utm.zone\";\n\n std::ostringstream hemKey;\n hemKey << mapKey << \".utm.northhem\";\n\n \/\/ Compute the zone and the hemisphere if not UserValue defined\n if (!app->HasUserValue(zoneKey.str()) && app->HasValue(imageKey))\n {\n \/\/ Compute the Origin lat\/long coordinate\n typedef otb::ImageToGenericRSOutputParameters<FloatVectorImageType> OutputParametersEstimatorType;\n OutputParametersEstimatorType::Pointer genericRSEstimator = OutputParametersEstimatorType::New();\n\n Parameter* param = app->GetParameterByKey(imageKey);\n if (dynamic_cast<InputImageParameter*> (param))\n {\n genericRSEstimator->SetInput(app->GetParameterImage(imageKey));\n }\n else\n if (dynamic_cast<InputImageListParameter*> (param))\n {\n genericRSEstimator->SetInput(app->GetParameterImageList(imageKey)->GetNthElement(0));\n }\n\n genericRSEstimator->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326));\n genericRSEstimator->Compute();\n\n int zone = otb::Utils::GetZoneFromGeoPoint(genericRSEstimator->GetOutputOrigin()[0],\n genericRSEstimator->GetOutputOrigin()[1]);\n \/\/ Update the UTM Gui fields\n app->SetParameterInt(zoneKey.str(), zone);\n if (genericRSEstimator->GetOutputOrigin()[1] > 0.)\n {\n app->EnableParameter(hemKey.str());\n }\n else\n {\n app->DisableParameter(hemKey.str());\n }\n\n app->AutomaticValueOn(zoneKey.str());\n app->AutomaticValueOn(hemKey.str());\n }\n}\n\n\n}\/\/ End namespace Wrapper\n}\/\/ End namespace otb\n<commit_msg>DOC: Enhance generic documentation for map projection parameters group<commit_after>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\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#include \"otbWrapperMapProjectionParametersHandler.h\"\n\n\/\/ Needed for methods relative to projections\n#include \"otbMapProjections.h\"\n#include \"otbImageToGenericRSOutputParameters.h\"\n#include \"otbWrapperInputImageListParameter.h\"\n\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nvoid MapProjectionParametersHandler::AddMapProjectionParameters( Application::Pointer app, const std::string & key)\n{\n app->AddParameter(ParameterType_Choice, key, \"Map Projection\");\n app->SetParameterDescription(key,\"Defines the map projection to be used.\");\n\n \/\/ utm\n std::ostringstream oss;\n oss << key<<\".utm\";\n app->AddChoice(oss.str(), \"Universal Trans-Mercator (UTM)\");\n app->SetParameterDescription(oss.str(),\"A system of transverse mercator projections dividing the surface of Earth between 80S and 84N latitude.\");\n\n oss << \".zone\";\n app->AddParameter(ParameterType_Int, oss.str(), \"Zone number\");\n app->SetParameterDescription(oss.str(),\"The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere)\");\n app->SetMinimumParameterIntValue(oss.str(), 1);\n app->SetDefaultParameterInt(oss.str(), 31);\n\n oss.str(\"\");\n oss <<key<<\".utm\" <<\".northhem\";\n app->AddParameter(ParameterType_Empty, oss.str(), \"Northern Hemisphere\");\n app->SetParameterDescription(oss.str(),\"The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.\");\n\n\n \/\/ lambert2\n oss.str(\"\");\n oss << key<<\".lambert2\";\n app->AddChoice(oss.str(), \"Lambert II Etendu\");\n app->SetParameterDescription(oss.str(),\"This is a Lambert Conformal Conic projection mainly used in France.\");\n\n \/\/ lambert93\n oss.str(\"\");\n oss << key<<\".lambert93\";\n app->AddChoice(oss.str(), \"Lambert93\");\n app->SetParameterDescription(oss.str(), \"This is a Lambert 93 projection mainly used in France.\");\n\n \/\/ Transmercator\n \/*oss.str(\"\");\n oss << key<<\".transmercator\";\n app->AddChoice(oss.str(), \"Transmercator\");\n app->SetParameterDescription(oss.str(),\n \"This is a Transverse Mercator, a cylindrical projection widely used. The required values are set by default.\");\n\n std::ostringstream subParamKey;\n subParamKey<<oss.str()<<\".falseeasting\";\n app->AddParameter(ParameterType_Float, subParamKey.str(), \"False easting\");\n app->SetParameterDescription( subParamKey.str(), \" Transmercator false easting value.\");\n app->SetDefaultParameterFloat(subParamKey.str(), 0.);\n\n subParamKey.str(\"\");\n subParamKey<<oss.str()<<\".falsenorthing\";\n app->AddParameter(ParameterType_Float, subParamKey.str(), \"False northing\");\n app->SetParameterDescription(subParamKey.str(), \" Transmercator false northing value.\");\n app->SetDefaultParameterFloat(subParamKey.str(), 0.);\n\n subParamKey.str(\"\");\n subParamKey<<oss.str()<<\".scale\";\n app->AddParameter(ParameterType_Float, subParamKey.str(), \"Scale factor\");\n app->SetParameterDescription(subParamKey.str(), \" Transmercator scale factor value.\");\n app->SetDefaultParameterFloat(subParamKey.str(), 1.);\n *\/\n \/\/ wgs84\n oss.str(\"\");\n oss << key<<\".wgs\";\n app->AddChoice(oss.str(), \"WGS 84\");\n app->SetParameterDescription(oss.str(),\"This is a Geographical projection\");\n\n \/\/ epsg code\n oss.str(\"\");\n oss<<key<<\".epsg\";\n app->AddChoice(oss.str(),\"EPSG Code\");\n app->SetParameterDescription(oss.str(),\n \"This code is a generic way of identifying map projections, and allows specifying a large amount of them. See www.spatialreference.org to find which EPSG code is associated to your projection;\");\n\n oss <<\".code\";\n app->AddParameter(ParameterType_Int, oss.str(), \"EPSG Code\");\n app->SetParameterDescription(oss.str(),\"See www.spatialreference.org to find which EPSG code is associated to your projection\");\n app->SetDefaultParameterInt(oss.str(), 4326);\n\n app->SetParameterString(key, \"utm\");\n}\n\n\/**\n * Helper method : Compute the ProjectionRef knowing the map\n * projection picked up by the user\n *\n *\/\nconst std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(const Application::Pointer app,\n const std::string & key)\n{\n std::ostringstream zoneKey;\n zoneKey << key<<\".utm.zone\";\n\n std::ostringstream hemKey;\n hemKey << key<<\".utm.northhem\";\n\n std::ostringstream epsgKey;\n epsgKey << key <<\".epsg.code\";\n\n \/\/ Get the user choice\n switch ( app->GetParameterInt(key) )\n {\n case Map_Utm:\n {\n otb::UtmInverseProjection::Pointer utmProjection =\n otb::UtmInverseProjection::New();\n\n \/\/ Set the zone\n utmProjection->SetZone(app->GetParameterInt(zoneKey.str()));\n\n \/\/ Set the hem\n char hem = 'N';\n if (!app->IsParameterEnabled(hemKey.str()))\n hem = 'S';\n utmProjection->SetHemisphere(hem);\n\n \/\/ Get the projection ref\n return utmProjection->GetWkt();\n }\n break;\n case Map_Lambert2:\n {\n otb::Lambert2EtenduForwardProjection::Pointer lambert2Projection =\n otb::Lambert2EtenduForwardProjection::New();\n return lambert2Projection->GetWkt();\n }\n break;\n case Map_Lambert93:\n {\n otb::Lambert93InverseProjection::Pointer lambert93Projection =\n otb::Lambert93InverseProjection::New();\n return lambert93Projection->GetWkt();\n }\n break;\n \/*case Map_Transmercator:\n {\n typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;\n TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();\n\n \/\/ Get the Transmercator parameters\n std::ostringstream falseeasting;\n std::ostringstream falsenorthing;\n std::ostringstream scale;\n\n falseeasting <<key <<\".transmercator.falseeasting\";\n falsenorthing <<key <<\".transmercator.falsenorthing\";\n scale <<key <<\".transmercator.scale\";\n\n transMercatorProjection->SetParameters(app->GetParameterFloat( falseeasting.str() ),\n app->GetParameterFloat( falsenorthing.str() ),\n app->GetParameterFloat( scale.str()) );\n return transMercatorProjection->GetWkt();\n }\n break; *\/\n case Map_WGS84:\n {\n return otb::GeoInformationConversion::ToWKT(4326);\n }\n break;\n case Map_Epsg:\n {\n return otb::GeoInformationConversion::ToWKT(app->GetParameterInt(epsgKey.str()));\n }\n break;\n }\n\n return \"\";\n}\n\n\/**\n * Helper method : Compute the UTM parameters relative to an image Origin\n * Note: The key of the image must be set to be able to get the image.\n * The key must be totally if the InputImageParameter belongs\n * to a ParameterGroup, ie set io.in\n *\/\nvoid MapProjectionParametersHandler::InitializeUTMParameters(Application::Pointer app,\n const std::string & imageKey,\n const std::string & mapKey )\n{\n \/\/ Get the UTM params keys\n std::ostringstream zoneKey;\n zoneKey << mapKey << \".utm.zone\";\n\n std::ostringstream hemKey;\n hemKey << mapKey << \".utm.northhem\";\n\n \/\/ Compute the zone and the hemisphere if not UserValue defined\n if (!app->HasUserValue(zoneKey.str()) && app->HasValue(imageKey))\n {\n \/\/ Compute the Origin lat\/long coordinate\n typedef otb::ImageToGenericRSOutputParameters<FloatVectorImageType> OutputParametersEstimatorType;\n OutputParametersEstimatorType::Pointer genericRSEstimator = OutputParametersEstimatorType::New();\n\n Parameter* param = app->GetParameterByKey(imageKey);\n if (dynamic_cast<InputImageParameter*> (param))\n {\n genericRSEstimator->SetInput(app->GetParameterImage(imageKey));\n }\n else\n if (dynamic_cast<InputImageListParameter*> (param))\n {\n genericRSEstimator->SetInput(app->GetParameterImageList(imageKey)->GetNthElement(0));\n }\n\n genericRSEstimator->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326));\n genericRSEstimator->Compute();\n\n int zone = otb::Utils::GetZoneFromGeoPoint(genericRSEstimator->GetOutputOrigin()[0],\n genericRSEstimator->GetOutputOrigin()[1]);\n \/\/ Update the UTM Gui fields\n app->SetParameterInt(zoneKey.str(), zone);\n if (genericRSEstimator->GetOutputOrigin()[1] > 0.)\n {\n app->EnableParameter(hemKey.str());\n }\n else\n {\n app->DisableParameter(hemKey.str());\n }\n\n app->AutomaticValueOn(zoneKey.str());\n app->AutomaticValueOn(hemKey.str());\n }\n}\n\n\n}\/\/ End namespace Wrapper\n}\/\/ End namespace otb\n<|endoftext|>"} {"text":"<commit_before>#include \"zlib.h\"\n#include \"catch.hpp\"\n#include \"helpers.h\"\n#include \"png.h\"\n#include \"gif_lib.h\"\n#include \"test_weighting_helpers.h\"\n#include \"trim_whitespace.h\"\n#include \"string.h\"\n#include \"lcms2.h\"\n\n\/\/ TODO: https:\/\/github.com\/pornel\/pngquant\/\n\nuint8_t gif_bytes_32[]\n = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04,\n 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02 };\nuint8_t gif_bytes_43[] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xFF, 0xFF,\n 0xFF, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00,\n 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3B };\nstatic int read_func(GifFileType * gif, GifByteType * buffer, int bytes_please)\n{\n int gif_byte_count = sizeof(gif_bytes_43);\n int * cursor = (int *)gif->UserData;\n if (*cursor + bytes_please > gif_byte_count) {\n fprintf(stderr, \"More bytes requested (%i) by giflib than available (%i)\", bytes_please,\n gif_byte_count - *cursor);\n bytes_please = gif_byte_count - *cursor;\n }\n memcpy(buffer, &gif_bytes_43[*cursor], bytes_please);\n *cursor += bytes_please;\n return bytes_please;\n}\n\nTEST_CASE(\"Test overlapped slurp\", \"\")\n{\n int cursor_a = 0, cursor_b = 0, error = 0;\n GifFileType * a = DGifOpen(&cursor_a, read_func, &error);\n REQUIRE(error == D_GIF_SUCCEEDED);\n\n REQUIRE(DGifSlurp(a) == GIF_OK);\n REQUIRE(a->Error == D_GIF_SUCCEEDED);\n\n GifFileType * b = DGifOpen(&cursor_b, read_func, &error);\n REQUIRE(error == D_GIF_SUCCEEDED);\n REQUIRE(DGifSlurp(b) == GIF_OK);\n\n int err = 0;\n DGifCloseFile(a, &err);\n DGifCloseFile(b, &err);\n}\n\nTEST_CASE(\"Load png\", \"[fastscaling]\")\n{\n\n bool success = false;\n\n uint8_t image_bytes_literal[]\n = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00,\n 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00,\n 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01,\n 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 };\n png_size_t image_bytes_count = sizeof(image_bytes_literal);\n png_const_voidp image_bytes = &image_bytes_literal;\n\n png_image image;\n\n \/* Only the image structure version number needs to be set. *\/\n memset(&image, 0, sizeof image);\n image.version = PNG_IMAGE_VERSION;\n image.opaque = NULL;\n\n if (png_image_begin_read_from_memory(&image, image_bytes, image_bytes_count)) {\n png_bytep buffer;\n\n \/* Change this to try different formats! If you set a colormap format\n * then you must also supply a colormap below.\n *\/\n image.format = PNG_FORMAT_BGRA;\n\n buffer = (png_bytep)malloc(PNG_IMAGE_SIZE(image));\n\n if (buffer != NULL) {\n if (png_image_finish_read(&image, NULL \/*background*\/, buffer, 0 \/*row_stride*\/,\n NULL \/*colormap for PNG_FORMAT_FLAG_COLORMAP *\/)) {\n\n success = true;\n\n \/\/ if (png_image_write_to_file(&image, argv[2],\n \/\/ 0\/*convert_to_8bit*\/, buffer, 0\/*row_stride*\/,\n \/\/ NULL\/*colormap*\/))\n \/\/ result = 0;\n \/\/\n \/\/ else\n \/\/ fprintf(stderr, \"pngtopng: write %s: %s\\n\",\n \/\/ image.message);\n \/\/\n \/\/ free(buffer);\n }\n\n else {\n fprintf(stderr, \"png_image_finish_read: %s\\n\", image.message);\n\n \/* This is the only place where a 'free' is required; libpng does\n * the cleanup on error and success, but in this case we couldn't\n * complete the read because of running out of memory.\n *\/\n png_image_free(&image);\n }\n free(buffer);\n }\n\n else\n fprintf(stderr, \"pngtopng: out of memory: %lu bytes\\n\", (unsigned long)PNG_IMAGE_SIZE(image));\n }\n\n else\n \/* Failed to read the first argument: *\/\n fprintf(stderr, \"png_image_begin_read_from_memory: %s\\n\", image.message);\n\n REQUIRE(success);\n}\n\nTEST_CASE(\"Load png from URL\", \"[fastscaling]\")\n{\n\n bool success = false;\n\n size_t bytes_count = 0;\n flow_c * c = flow_context_create();\n\n uint8_t * bytes = get_bytes_cached(c, &bytes_count, \"http:\/\/s3.amazonaws.com\/resizer-images\/sun_256.png\", __FILE__);\n REQUIRE_FALSE(bytes == NULL);\n png_size_t image_bytes_count = bytes_count;\n png_const_voidp image_bytes = bytes;\n\n png_image image;\n\n \/* Only the image structure version number needs to be set. *\/\n memset(&image, 0, sizeof image);\n image.version = PNG_IMAGE_VERSION;\n image.opaque = NULL;\n\n if (png_image_begin_read_from_memory(&image, image_bytes, image_bytes_count)) {\n png_bytep buffer;\n\n \/* Change this to try different formats! If you set a colormap format\n * then you must also supply a colormap below.\n *\/\n image.format = PNG_FORMAT_BGRA;\n\n buffer = FLOW_calloc_array(c, PNG_IMAGE_SIZE(image), png_byte);\n\n if (buffer != NULL) {\n if (png_image_finish_read(&image, NULL \/*background*\/, buffer, 0 \/*row_stride*\/,\n NULL \/*colormap for PNG_FORMAT_FLAG_COLORMAP *\/)) {\n\n int nonzero = (int)nonzero_count((uint8_t *)buffer, PNG_IMAGE_SIZE(image));\n if (nonzero > 0) {\n printf(\"nonzero buffer: %d of %d\", nonzero, PNG_IMAGE_SIZE(image));\n }\n\n struct flow_bitmap_bgra * source\n = flow_bitmap_bgra_create_header(c, (unsigned int)(image.width), (unsigned int)(image.height));\n REQUIRE_FALSE(source == NULL);\n source->fmt = flow_pixel_format::flow_bgra32;\n source->stride = PNG_IMAGE_ROW_STRIDE(image);\n printf(\"png stride (%d), calculated (%d)\\n\", source->stride,\n source->w * flow_pixel_format_bytes_per_pixel(source->fmt));\n source->alpha_meaningful = true;\n source->pixels = buffer;\n\n int target_width = 300;\n int target_height = 200;\n\n struct flow_bitmap_bgra * canvas\n = flow_bitmap_bgra_create(c, target_width, target_height, true, flow_bgra32);\n\n REQUIRE_FALSE(canvas == NULL);\n struct flow_RenderDetails * details\n = flow_RenderDetails_create_with(c, flow_interpolation_filter::flow_interpolation_filter_Robidoux);\n details->interpolate_last_percent = 2.1f;\n details->minimum_sample_window_to_interposharpen = 1.5;\n details->havling_acceptable_pixel_loss = 0.26f;\n\n REQUIRE_FALSE(details == NULL);\n \/\/ details->sharpen_percent_goal = 50;\n \/\/ details->post_flip_x = flipx;\n \/\/ details->post_flip_y = flipy;\n \/\/ details->post_transpose = transpose;\n \/\/ details->enable_profiling = profile;\n\n \/\/ Should we even have Renderer_* functions, or just 1 call that does it all?\n \/\/ If we add memory use estimation, we should keep flow_Renderer\n\n if (!flow_RenderDetails_render(c, details, source, canvas)) {\n\n char error[255];\n flow_context_error_message(c, error, 255);\n printf(\"%s\", error);\n exit(77);\n }\n printf(\"Rendered!\");\n flow_RenderDetails_destroy(c, details);\n\n flow_bitmap_bgra_destroy(c, source);\n\n \/\/ TODO, write out PNG here\n\n struct flow_io * buf = flow_io_create_for_output_buffer(c, c);\n \/\/ memset(canvas->pixels, 0, canvas->stride * canvas->h);\n if (!flow_bitmap_bgra_write_png(c, canvas, buf)) {\n \/\/ FLOW_error_return(context);\n FAIL(\"Failed to write png\");\n } else {\n if (!flow_io_write_output_buffer_to_file(c, buf, \"outpng.png\")) {\n FAIL(\"Failed to copy to disk\");\n }\n success = true;\n }\n\n flow_bitmap_bgra_destroy(c, canvas);\n\n } else {\n fprintf(stderr, \"png_image_finish_read: %s\\n\", image.message);\n\n \/* This is the only place where a 'free' is required; libpng does\n * the cleanup on error and success, but in this case we couldn't\n * complete the read because of running out of memory.\n *\/\n png_image_free(&image);\n }\n }\n\n else\n fprintf(stderr, \"pngtopng: out of memory: %lu bytes\\n\", (unsigned long)PNG_IMAGE_SIZE(image));\n }\n\n else\n \/* Failed to read the first argument: *\/\n fprintf(stderr, \"png_image_begin_read_from_memory: %s\\n\", image.message);\n\n flow_context_destroy(c);\n REQUIRE(success);\n}\n\n\/\/ This test is windows only\n\/\/ TEST_CASE(\"Test png writing; repro uninitialized value\", \"[libpng]\"){\n\/\/ png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL,\n\/\/ NULL); \/\/ makepng_error, makepng_warning);\n\/\/\n\/\/ uint32_t w = 300;\n\/\/ uint32_t h = 200;\n\/\/ uint32_t stride = 1200;\n\/\/\n\/\/ uint8_t * pixels = (uint8_t *)calloc(1, stride * h);\n\/\/ uint8_t ** rows = (uint8_t **)calloc(1, sizeof(uint8_t *) * h);\n\/\/\n\/\/ unsigned int y;\n\/\/ for (y = 0; y < h; ++y) {\n\/\/ rows[y] = ((uint8_t *)pixels + (stride * y));\n\/\/ }\n\/\/\n\/\/ png_set_compression_level(png_ptr, Z_BEST_SPEED);\n\/\/ png_set_text_compression_level(png_ptr, Z_DEFAULT_COMPRESSION);\n\/\/\n\/\/ png_init_io(png_ptr, fopen(\"\/dev\/null\",\"wb\"));\n\/\/\n\/\/ png_infop info_ptr = NULL;\n\/\/ info_ptr = png_create_info_struct(png_ptr);\n\/\/ if (info_ptr == NULL)\n\/\/ png_error(png_ptr, \"OOM allocating info structure\"); \/\/ TODO: comprehend png error handling\n\/\/ {\n\/\/ png_set_rows(png_ptr, info_ptr, rows);\n\/\/\n\/\/ int color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n\/\/ int transform = PNG_TRANSFORM_BGR;\n\/\/\n\/\/ png_set_IHDR(png_ptr, info_ptr, (png_uint_32)w, (png_uint_32)h, 8, color_type,\n\/\/ PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n\/\/\n\/\/ png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);\n\/\/\n\/\/ png_write_png(png_ptr, info_ptr, transform, NULL);\n\/\/\n\/\/ rows = NULL;\n\/\/ png_destroy_write_struct(&png_ptr, &info_ptr);\n\/\/ }\n\/\/ free(pixels);\n\/\/ free(rows);\n\/\/}\n\nTEST_CASE(\"Test png writing\", \"[libpng]\")\n{\n printf(\"\\n Testing libpng version %s\\n\", PNG_LIBPNG_VER_STRING);\n printf(\" with zlib version %s\\n\", ZLIB_VERSION);\n png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL,\n NULL); \/\/ makepng_error, makepng_warning);\n\n uint32_t w = 300;\n uint32_t h = 200;\n uint32_t stride = 1200;\n\n uint8_t * pixels = (uint8_t *)calloc(1, stride * h);\n uint8_t ** rows = (uint8_t **)calloc(1, sizeof(uint8_t *) * h);\n\n unsigned int y;\n for (y = 0; y < h; ++y) {\n rows[y] = ((uint8_t *)pixels + (stride * y));\n }\n\n png_set_compression_level(png_ptr, Z_BEST_SPEED);\n png_set_text_compression_level(png_ptr, Z_DEFAULT_COMPRESSION);\n\n png_init_io(png_ptr, fopen(\"\/dev\/null\", \"wb\"));\n png_infop info_ptr = NULL;\n info_ptr = png_create_info_struct(png_ptr);\n png_set_rows(png_ptr, info_ptr, rows);\n int color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n int transform = PNG_TRANSFORM_BGR;\n png_set_IHDR(png_ptr, info_ptr, (png_uint_32)w, (png_uint_32)h, 8, color_type,\n PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);\n\/\/Uninitialized read happens here:\n png_write_png(png_ptr, info_ptr, transform, NULL);\n\n png_destroy_write_struct(&png_ptr, &info_ptr);\n free(pixels);\n free(rows);\n}\n<commit_msg>Don't try to use dev\/null on windows. It's not there.<commit_after>#include \"zlib.h\"\n#include \"catch.hpp\"\n#include \"helpers.h\"\n#include \"png.h\"\n#include \"gif_lib.h\"\n#include \"test_weighting_helpers.h\"\n#include \"trim_whitespace.h\"\n#include \"string.h\"\n#include \"lcms2.h\"\n\n\/\/ TODO: https:\/\/github.com\/pornel\/pngquant\/\n\nuint8_t gif_bytes_32[]\n = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04,\n 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02 };\nuint8_t gif_bytes_43[] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xFF, 0xFF,\n 0xFF, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00,\n 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3B };\nstatic int read_func(GifFileType * gif, GifByteType * buffer, int bytes_please)\n{\n int gif_byte_count = sizeof(gif_bytes_43);\n int * cursor = (int *)gif->UserData;\n if (*cursor + bytes_please > gif_byte_count) {\n fprintf(stderr, \"More bytes requested (%i) by giflib than available (%i)\", bytes_please,\n gif_byte_count - *cursor);\n bytes_please = gif_byte_count - *cursor;\n }\n memcpy(buffer, &gif_bytes_43[*cursor], bytes_please);\n *cursor += bytes_please;\n return bytes_please;\n}\n\nTEST_CASE(\"Test overlapped slurp\", \"\")\n{\n int cursor_a = 0, cursor_b = 0, error = 0;\n GifFileType * a = DGifOpen(&cursor_a, read_func, &error);\n REQUIRE(error == D_GIF_SUCCEEDED);\n\n REQUIRE(DGifSlurp(a) == GIF_OK);\n REQUIRE(a->Error == D_GIF_SUCCEEDED);\n\n GifFileType * b = DGifOpen(&cursor_b, read_func, &error);\n REQUIRE(error == D_GIF_SUCCEEDED);\n REQUIRE(DGifSlurp(b) == GIF_OK);\n\n int err = 0;\n DGifCloseFile(a, &err);\n DGifCloseFile(b, &err);\n}\n\nTEST_CASE(\"Load png\", \"[fastscaling]\")\n{\n\n bool success = false;\n\n uint8_t image_bytes_literal[]\n = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00,\n 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00,\n 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01,\n 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 };\n png_size_t image_bytes_count = sizeof(image_bytes_literal);\n png_const_voidp image_bytes = &image_bytes_literal;\n\n png_image image;\n\n \/* Only the image structure version number needs to be set. *\/\n memset(&image, 0, sizeof image);\n image.version = PNG_IMAGE_VERSION;\n image.opaque = NULL;\n\n if (png_image_begin_read_from_memory(&image, image_bytes, image_bytes_count)) {\n png_bytep buffer;\n\n \/* Change this to try different formats! If you set a colormap format\n * then you must also supply a colormap below.\n *\/\n image.format = PNG_FORMAT_BGRA;\n\n buffer = (png_bytep)malloc(PNG_IMAGE_SIZE(image));\n\n if (buffer != NULL) {\n if (png_image_finish_read(&image, NULL \/*background*\/, buffer, 0 \/*row_stride*\/,\n NULL \/*colormap for PNG_FORMAT_FLAG_COLORMAP *\/)) {\n\n success = true;\n\n \/\/ if (png_image_write_to_file(&image, argv[2],\n \/\/ 0\/*convert_to_8bit*\/, buffer, 0\/*row_stride*\/,\n \/\/ NULL\/*colormap*\/))\n \/\/ result = 0;\n \/\/\n \/\/ else\n \/\/ fprintf(stderr, \"pngtopng: write %s: %s\\n\",\n \/\/ image.message);\n \/\/\n \/\/ free(buffer);\n }\n\n else {\n fprintf(stderr, \"png_image_finish_read: %s\\n\", image.message);\n\n \/* This is the only place where a 'free' is required; libpng does\n * the cleanup on error and success, but in this case we couldn't\n * complete the read because of running out of memory.\n *\/\n png_image_free(&image);\n }\n free(buffer);\n }\n\n else\n fprintf(stderr, \"pngtopng: out of memory: %lu bytes\\n\", (unsigned long)PNG_IMAGE_SIZE(image));\n }\n\n else\n \/* Failed to read the first argument: *\/\n fprintf(stderr, \"png_image_begin_read_from_memory: %s\\n\", image.message);\n\n REQUIRE(success);\n}\n\nTEST_CASE(\"Load png from URL\", \"[fastscaling]\")\n{\n\n bool success = false;\n\n size_t bytes_count = 0;\n flow_c * c = flow_context_create();\n\n uint8_t * bytes = get_bytes_cached(c, &bytes_count, \"http:\/\/s3.amazonaws.com\/resizer-images\/sun_256.png\", __FILE__);\n REQUIRE_FALSE(bytes == NULL);\n png_size_t image_bytes_count = bytes_count;\n png_const_voidp image_bytes = bytes;\n\n png_image image;\n\n \/* Only the image structure version number needs to be set. *\/\n memset(&image, 0, sizeof image);\n image.version = PNG_IMAGE_VERSION;\n image.opaque = NULL;\n\n if (png_image_begin_read_from_memory(&image, image_bytes, image_bytes_count)) {\n png_bytep buffer;\n\n \/* Change this to try different formats! If you set a colormap format\n * then you must also supply a colormap below.\n *\/\n image.format = PNG_FORMAT_BGRA;\n\n buffer = FLOW_calloc_array(c, PNG_IMAGE_SIZE(image), png_byte);\n\n if (buffer != NULL) {\n if (png_image_finish_read(&image, NULL \/*background*\/, buffer, 0 \/*row_stride*\/,\n NULL \/*colormap for PNG_FORMAT_FLAG_COLORMAP *\/)) {\n\n int nonzero = (int)nonzero_count((uint8_t *)buffer, PNG_IMAGE_SIZE(image));\n if (nonzero > 0) {\n printf(\"nonzero buffer: %d of %d\", nonzero, PNG_IMAGE_SIZE(image));\n }\n\n struct flow_bitmap_bgra * source\n = flow_bitmap_bgra_create_header(c, (unsigned int)(image.width), (unsigned int)(image.height));\n REQUIRE_FALSE(source == NULL);\n source->fmt = flow_pixel_format::flow_bgra32;\n source->stride = PNG_IMAGE_ROW_STRIDE(image);\n printf(\"png stride (%d), calculated (%d)\\n\", source->stride,\n source->w * flow_pixel_format_bytes_per_pixel(source->fmt));\n source->alpha_meaningful = true;\n source->pixels = buffer;\n\n int target_width = 300;\n int target_height = 200;\n\n struct flow_bitmap_bgra * canvas\n = flow_bitmap_bgra_create(c, target_width, target_height, true, flow_bgra32);\n\n REQUIRE_FALSE(canvas == NULL);\n struct flow_RenderDetails * details\n = flow_RenderDetails_create_with(c, flow_interpolation_filter::flow_interpolation_filter_Robidoux);\n details->interpolate_last_percent = 2.1f;\n details->minimum_sample_window_to_interposharpen = 1.5;\n details->havling_acceptable_pixel_loss = 0.26f;\n\n REQUIRE_FALSE(details == NULL);\n \/\/ details->sharpen_percent_goal = 50;\n \/\/ details->post_flip_x = flipx;\n \/\/ details->post_flip_y = flipy;\n \/\/ details->post_transpose = transpose;\n \/\/ details->enable_profiling = profile;\n\n \/\/ Should we even have Renderer_* functions, or just 1 call that does it all?\n \/\/ If we add memory use estimation, we should keep flow_Renderer\n\n if (!flow_RenderDetails_render(c, details, source, canvas)) {\n\n char error[255];\n flow_context_error_message(c, error, 255);\n printf(\"%s\", error);\n exit(77);\n }\n printf(\"Rendered!\");\n flow_RenderDetails_destroy(c, details);\n\n flow_bitmap_bgra_destroy(c, source);\n\n \/\/ TODO, write out PNG here\n\n struct flow_io * buf = flow_io_create_for_output_buffer(c, c);\n \/\/ memset(canvas->pixels, 0, canvas->stride * canvas->h);\n if (!flow_bitmap_bgra_write_png(c, canvas, buf)) {\n \/\/ FLOW_error_return(context);\n FAIL(\"Failed to write png\");\n } else {\n if (!flow_io_write_output_buffer_to_file(c, buf, \"outpng.png\")) {\n FAIL(\"Failed to copy to disk\");\n }\n success = true;\n }\n\n flow_bitmap_bgra_destroy(c, canvas);\n\n } else {\n fprintf(stderr, \"png_image_finish_read: %s\\n\", image.message);\n\n \/* This is the only place where a 'free' is required; libpng does\n * the cleanup on error and success, but in this case we couldn't\n * complete the read because of running out of memory.\n *\/\n png_image_free(&image);\n }\n }\n\n else\n fprintf(stderr, \"pngtopng: out of memory: %lu bytes\\n\", (unsigned long)PNG_IMAGE_SIZE(image));\n }\n\n else\n \/* Failed to read the first argument: *\/\n fprintf(stderr, \"png_image_begin_read_from_memory: %s\\n\", image.message);\n\n flow_context_destroy(c);\n REQUIRE(success);\n}\n\n#ifdef _MSC_VER\n\/\/ \/dev\/null doesn't work on windows. Don't try this test.\n#else\n\nTEST_CASE(\"Test png writing\", \"[libpng]\")\n{\n printf(\"\\n Testing libpng version %s\\n\", PNG_LIBPNG_VER_STRING);\n printf(\" with zlib version %s\\n\", ZLIB_VERSION);\n png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL,\n NULL); \/\/ makepng_error, makepng_warning);\n\n uint32_t w = 300;\n uint32_t h = 200;\n uint32_t stride = 1200;\n\n uint8_t * pixels = (uint8_t *)calloc(1, stride * h);\n uint8_t ** rows = (uint8_t **)calloc(1, sizeof(uint8_t *) * h);\n\n unsigned int y;\n for (y = 0; y < h; ++y) {\n rows[y] = ((uint8_t *)pixels + (stride * y));\n }\n\n png_set_compression_level(png_ptr, Z_BEST_SPEED);\n png_set_text_compression_level(png_ptr, Z_DEFAULT_COMPRESSION);\n\n png_init_io(png_ptr, fopen(\"\/dev\/null\", \"wb\"));\n png_infop info_ptr = NULL;\n info_ptr = png_create_info_struct(png_ptr);\n png_set_rows(png_ptr, info_ptr, rows);\n int color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n int transform = PNG_TRANSFORM_BGR;\n png_set_IHDR(png_ptr, info_ptr, (png_uint_32)w, (png_uint_32)h, 8, color_type,\n PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);\n\/\/Uninitialized read happens here:\n png_write_png(png_ptr, info_ptr, transform, NULL);\n\n png_destroy_write_struct(&png_ptr, &info_ptr);\n free(pixels);\n free(rows);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_fusible.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/ir_emission_utils.h\"\n\nnamespace xla {\nnamespace gpu {\n\nnamespace {\nvoid AppendParams(const HloInstruction& instr,\n std::vector<HloInstruction*>* params) {\n if (instr.opcode() == HloOpcode::kFusion) {\n params->insert(std::end(*params), std::begin(instr.fused_parameters()),\n std::end(instr.fused_parameters()));\n } else {\n for (HloInstruction* operand : instr.operands()) {\n params->push_back(operand);\n }\n }\n}\n} \/\/ namespace\n\nbool LayoutsAreReduceInputFusionFriendly(const HloInstruction& producer,\n const HloInstruction& reduce) {\n std::vector<HloInstruction*> params;\n AppendParams(producer, ¶ms);\n AppendParams(reduce, ¶ms);\n int64 max_rank = -1;\n const Layout* max_rank_layout;\n for (HloInstruction* param : params) {\n if (param->shape().IsArray() && param->shape().rank() > max_rank) {\n max_rank = param->shape().rank();\n max_rank_layout = ¶m->shape().layout();\n }\n }\n return absl::c_all_of(params, [&](HloInstruction* param) {\n return (!param->shape().IsArray()) || (param->shape().rank() < max_rank) ||\n (LayoutUtil::Equal(param->shape().layout(), *max_rank_layout));\n });\n}\n\nbool IsReduceInputFusion(const HloInstruction& instr) {\n if (instr.IsMultiOutputFusion()) {\n for (const HloInstruction* operand :\n instr.fused_expression_root()->operands()) {\n if (IsReductionToVector(*operand)) {\n CHECK(instr.fusion_kind() == HloInstruction::FusionKind::kInput)\n << \" Multi-output fusion rooted at reduction-to-vector ops must be \"\n \"of kind kInput: \"\n << instr.ToString();\n return true;\n }\n }\n } else if (instr.opcode() == HloOpcode::kFusion &&\n IsReductionToVector(*instr.fused_expression_root())) {\n CHECK(instr.fusion_kind() == HloInstruction::FusionKind::kInput)\n << \" Fusion rooted at reduction-to-vector op must be of kind kInput: \"\n << instr.ToString();\n return true;\n }\n return false;\n}\n\nbool IsInputFusibleReduction(const HloInstruction& instr) {\n return IsReduceInputFusion(instr) || IsReductionToVector(instr);\n}\n\nbool ShapesCompatibleForMultiOutputFusion(const HloInstruction& instr1,\n const HloInstruction& instr2) {\n \/\/ Returns the instructions that determines the emitter used for lowering,\n \/\/ sometimes referred to as \"the real hero\".\n auto get_real_hero =\n [&](const HloInstruction* instr) -> const HloInstruction* {\n if (instr->opcode() == HloOpcode::kFusion) {\n auto fused_expression_root = instr->fused_expression_root();\n if (instr->IsMultiOutputFusion()) {\n \/\/ If possible, we want to pick a reduction-to-vector operand of the\n \/\/ fusion root, because it has the most constraints.\n for (const auto* inst : fused_expression_root->operands()) {\n if (IsReductionToVector(*inst)) {\n return inst;\n }\n }\n return fused_expression_root->operands()[0];\n }\n return fused_expression_root;\n }\n return instr;\n };\n\n \/\/ Multi-output fusion kernels share a common parallel loop. The loop\n \/\/ dimenstions are determined by instruction shapes.\n auto get_loop_shape = [&](const HloInstruction* element_instr) {\n \/\/ Special-case reduction-to-vector ops: The loop dimensions are determined\n \/\/ by the shape of the first operand.\n if (IsReductionToVector(*element_instr)) {\n return element_instr->operand(0)->shape();\n }\n return element_instr->shape();\n };\n\n \/\/ All shapes of the root tuple of multi-output fusions should agree, i.e. all\n \/\/ root ops should have equal output shapes. An exception are\n \/\/ reduction-to-vector ops. Here the input shapes of the reduction (first\n \/\/ operand shape) and the reduction dimensions need to match.\n auto* instr_1 = get_real_hero(&instr1);\n auto* instr_2 = get_real_hero(&instr2);\n \/\/ TODO(tjoerg): Relax the shape constraint. The datatype does not matter.\n if (IsReductionToVector(*instr_1) && IsReductionToVector(*instr_2) &&\n (!ShapeUtil::Equal(instr_1->shape(), instr_2->shape()) ||\n instr_1->dimensions() != instr_2->dimensions())) {\n return false;\n }\n \/\/ The elementwise output shapes must be the same (including layout).\n \/\/ TODO(tjoerg): Further relax the constraint. The datatype does not matter.\n return ShapeUtil::EqualIgnoringFpPrecision(get_loop_shape(instr_1),\n get_loop_shape(instr_2));\n}\n\nbool IsFusible(const HloInstruction& instr) {\n \/\/ Don't fuse get-tuple-element on GPU: We can, but it's slower than not\n \/\/ fusing. We never generate kernels for unfused GTEs. Instead, if an\n \/\/ unfused GTE is an input to a kernel (including a fusion kernel), we\n \/\/ compute the address of the GTE at the top of the kernel. Often we know the\n \/\/ address of the GTE result statically, so we can do this without chasing any\n \/\/ pointers.\n return (instr.IsElementwise() && instr.operand_count() > 0) ||\n instr.opcode() == HloOpcode::kBitcast ||\n instr.opcode() == HloOpcode::kBroadcast ||\n instr.opcode() == HloOpcode::kConcatenate ||\n instr.opcode() == HloOpcode::kDynamicSlice ||\n instr.opcode() == HloOpcode::kDynamicUpdateSlice ||\n instr.opcode() == HloOpcode::kFusion ||\n instr.opcode() == HloOpcode::kGather ||\n instr.opcode() == HloOpcode::kIota || instr.opcode() == HloOpcode::kPad ||\n instr.opcode() == HloOpcode::kReduce ||\n instr.opcode() == HloOpcode::kReduceWindow ||\n instr.opcode() == HloOpcode::kReshape ||\n instr.opcode() == HloOpcode::kReverse ||\n instr.opcode() == HloOpcode::kScatter ||\n instr.opcode() == HloOpcode::kSlice ||\n instr.opcode() == HloOpcode::kTranspose;\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<commit_msg>Fix formatting issues in IsFusible<commit_after>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_fusible.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/ir_emission_utils.h\"\n\nnamespace xla {\nnamespace gpu {\n\nnamespace {\nvoid AppendParams(const HloInstruction& instr,\n std::vector<HloInstruction*>* params) {\n if (instr.opcode() == HloOpcode::kFusion) {\n params->insert(std::end(*params), std::begin(instr.fused_parameters()),\n std::end(instr.fused_parameters()));\n } else {\n for (HloInstruction* operand : instr.operands()) {\n params->push_back(operand);\n }\n }\n}\n} \/\/ namespace\n\nbool LayoutsAreReduceInputFusionFriendly(const HloInstruction& producer,\n const HloInstruction& reduce) {\n std::vector<HloInstruction*> params;\n AppendParams(producer, ¶ms);\n AppendParams(reduce, ¶ms);\n int64 max_rank = -1;\n const Layout* max_rank_layout;\n for (HloInstruction* param : params) {\n if (param->shape().IsArray() && param->shape().rank() > max_rank) {\n max_rank = param->shape().rank();\n max_rank_layout = ¶m->shape().layout();\n }\n }\n return absl::c_all_of(params, [&](HloInstruction* param) {\n return (!param->shape().IsArray()) || (param->shape().rank() < max_rank) ||\n (LayoutUtil::Equal(param->shape().layout(), *max_rank_layout));\n });\n}\n\nbool IsReduceInputFusion(const HloInstruction& instr) {\n if (instr.IsMultiOutputFusion()) {\n for (const HloInstruction* operand :\n instr.fused_expression_root()->operands()) {\n if (IsReductionToVector(*operand)) {\n CHECK(instr.fusion_kind() == HloInstruction::FusionKind::kInput)\n << \" Multi-output fusion rooted at reduction-to-vector ops must be \"\n \"of kind kInput: \"\n << instr.ToString();\n return true;\n }\n }\n } else if (instr.opcode() == HloOpcode::kFusion &&\n IsReductionToVector(*instr.fused_expression_root())) {\n CHECK(instr.fusion_kind() == HloInstruction::FusionKind::kInput)\n << \" Fusion rooted at reduction-to-vector op must be of kind kInput: \"\n << instr.ToString();\n return true;\n }\n return false;\n}\n\nbool IsInputFusibleReduction(const HloInstruction& instr) {\n return IsReduceInputFusion(instr) || IsReductionToVector(instr);\n}\n\nbool ShapesCompatibleForMultiOutputFusion(const HloInstruction& instr1,\n const HloInstruction& instr2) {\n \/\/ Returns the instructions that determines the emitter used for lowering,\n \/\/ sometimes referred to as \"the real hero\".\n auto get_real_hero =\n [&](const HloInstruction* instr) -> const HloInstruction* {\n if (instr->opcode() == HloOpcode::kFusion) {\n auto fused_expression_root = instr->fused_expression_root();\n if (instr->IsMultiOutputFusion()) {\n \/\/ If possible, we want to pick a reduction-to-vector operand of the\n \/\/ fusion root, because it has the most constraints.\n for (const auto* inst : fused_expression_root->operands()) {\n if (IsReductionToVector(*inst)) {\n return inst;\n }\n }\n return fused_expression_root->operands()[0];\n }\n return fused_expression_root;\n }\n return instr;\n };\n\n \/\/ Multi-output fusion kernels share a common parallel loop. The loop\n \/\/ dimenstions are determined by instruction shapes.\n auto get_loop_shape = [&](const HloInstruction* element_instr) {\n \/\/ Special-case reduction-to-vector ops: The loop dimensions are determined\n \/\/ by the shape of the first operand.\n if (IsReductionToVector(*element_instr)) {\n return element_instr->operand(0)->shape();\n }\n return element_instr->shape();\n };\n\n \/\/ All shapes of the root tuple of multi-output fusions should agree, i.e. all\n \/\/ root ops should have equal output shapes. An exception are\n \/\/ reduction-to-vector ops. Here the input shapes of the reduction (first\n \/\/ operand shape) and the reduction dimensions need to match.\n auto* instr_1 = get_real_hero(&instr1);\n auto* instr_2 = get_real_hero(&instr2);\n \/\/ TODO(tjoerg): Relax the shape constraint. The datatype does not matter.\n if (IsReductionToVector(*instr_1) && IsReductionToVector(*instr_2) &&\n (!ShapeUtil::Equal(instr_1->shape(), instr_2->shape()) ||\n instr_1->dimensions() != instr_2->dimensions())) {\n return false;\n }\n \/\/ The elementwise output shapes must be the same (including layout).\n \/\/ TODO(tjoerg): Further relax the constraint. The datatype does not matter.\n return ShapeUtil::EqualIgnoringFpPrecision(get_loop_shape(instr_1),\n get_loop_shape(instr_2));\n}\n\nbool IsFusible(const HloInstruction& instr) {\n \/\/ Don't fuse get-tuple-element on GPU: We can, but it's slower than not\n \/\/ fusing. We never generate kernels for unfused GTEs. Instead, if an\n \/\/ unfused GTE is an input to a kernel (including a fusion kernel), we\n \/\/ compute the address of the GTE at the top of the kernel. Often we know the\n \/\/ address of the GTE result statically, so we can do this without chasing any\n \/\/ pointers.\n return (instr.IsElementwise() && instr.operand_count() > 0) ||\n instr.opcode() == HloOpcode::kBitcast ||\n instr.opcode() == HloOpcode::kBroadcast ||\n instr.opcode() == HloOpcode::kConcatenate ||\n instr.opcode() == HloOpcode::kDynamicSlice ||\n instr.opcode() == HloOpcode::kDynamicUpdateSlice ||\n instr.opcode() == HloOpcode::kFusion ||\n instr.opcode() == HloOpcode::kGather ||\n instr.opcode() == HloOpcode::kIota ||\n instr.opcode() == HloOpcode::kPad ||\n instr.opcode() == HloOpcode::kReduce ||\n instr.opcode() == HloOpcode::kReduceWindow ||\n instr.opcode() == HloOpcode::kReshape ||\n instr.opcode() == HloOpcode::kReverse ||\n instr.opcode() == HloOpcode::kScatter ||\n instr.opcode() == HloOpcode::kSlice ||\n instr.opcode() == HloOpcode::kTranspose;\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"<commit_before>\/\/ Author: Enrico Guiraud, CERN 10\/2021\n\n\/*************************************************************************\n * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_RDF_RVARIATION\n#define ROOT_RDF_RVARIATION\n\n#include \"Utils.hxx\" \/\/ IsRVec\n#include \"ColumnReaderUtils.hxx\"\n#include \"RColumnReaderBase.hxx\"\n#include \"RLoopManager.hxx\"\n#include \"RVariationBase.hxx\"\n\n#include <ROOT\/RStringView.hxx>\n#include <ROOT\/TypeTraits.hxx>\n#include <Rtypes.h> \/\/ R__CLING_PTRCHECK, Long64_t\n\n#include <array>\n#include <deque>\n#include <map>\n#include <string>\n#include <type_traits> \/\/ std::is_same, std::conditional_t\n#include <utility> \/\/ std::index_sequence\n#include <vector>\n\nclass TTreeReader;\n\nnamespace ROOT {\n\nnamespace RDF {\nclass RDataSource;\n}\n\nnamespace Internal {\nnamespace RDF {\n\nusing namespace ROOT::TypeTraits;\n\ntemplate <typename T>\nbool ResultsSizeEq(const RVec<RVec<T>> &results, std::size_t expected, std::size_t nColumns)\n{\n if (nColumns == 1)\n return results.size() == expected;\n\n return std::all_of(results.begin(), results.end(), [&expected](const RVec<T> &v) { return v.size() == expected; });\n}\n\ntemplate <typename T>\nbool ResultsSizeEq(const RVec<T> &results, std::size_t expected, std::size_t nColumns)\n{\n assert(nColumns == 1);\n (void)nColumns;\n\n return results.size() == expected;\n}\n\ntemplate <typename T>\nstd::size_t GetNVariations(const RVec<RVec<T>> &results)\n{\n assert(!results.empty());\n return results[0].size();\n}\n\ntemplate <typename T>\nstd::size_t GetNVariations(const RVec<T> &results)\n{\n return results.size();\n}\n\ntemplate <typename F>\nclass R__CLING_PTRCHECK(off) RVariation final : public RVariationBase {\n using ColumnTypes_t = typename CallableTraits<F>::arg_types;\n using TypeInd_t = std::make_index_sequence<ColumnTypes_t::list_size>;\n using ret_type = typename CallableTraits<F>::ret_type;\n \/\/ Avoid instantiating vector<bool> as `operator[]` returns temporaries in that case. Use std::deque instead.\n using ValuesPerSlot_t =\n std::conditional_t<std::is_same<ret_type, bool>::value, std::deque<ret_type>, std::vector<ret_type>>;\n\n F fExpression;\n ValuesPerSlot_t fLastResults;\n\n \/\/\/ Column readers per slot and per input column\n std::vector<std::array<std::unique_ptr<RColumnReaderBase>, ColumnTypes_t::list_size>> fValues;\n\n template <typename... ColTypes, std::size_t... S>\n void UpdateHelper(unsigned int slot, Long64_t entry, TypeList<ColTypes...>, std::index_sequence<S...>)\n {\n \/\/ fExpression must return an RVec<T>\n const auto &results = fExpression(fValues[slot][S]->template Get<ColTypes>(entry)...);\n if (!ResultsSizeEq(results, fVariationNames.size(), fColNames.size())) {\n std::string variationName = fVariationNames[0].substr(0, fVariationNames[0].find_first_of(':'));\n throw std::runtime_error(\"The evaluation of the expression for variation \\\"\" + variationName +\n \"\\\" resulted in \" + std::to_string(GetNVariations(results)) + \" values, but \" +\n std::to_string(fVariationNames.size()) + \" were expected.\");\n }\n \/\/ Assign into fLastResults without changing the addresses of its elements (we gave those addresses away in\n \/\/ GetValuePtr)\n fLastResults[slot * CacheLineStep<ret_type>()].assign(results.begin(), results.end());\n\n \/\/ silence \"unused parameter\" warnings in gcc\n (void)slot;\n (void)entry;\n }\n\n \/\/ This overload is for the case of a single column and ret_type != RVec<RVec<...>> -- the colIdx is ignored.\n template <typename U = typename ret_type::value_type>\n std::enable_if_t<!IsRVec<U>::value, void *>\n GetValuePtr(unsigned int slot, std::size_t \/*colIdx*\/, std::size_t varIdx)\n {\n auto &value = fLastResults[slot * CacheLineStep<ret_type>()][varIdx];\n return static_cast<void *>(&value);\n }\n\n \/\/ This overload is for the case of ret_type == RVec<RVec<...>>\n template <typename U = typename ret_type::value_type>\n std::enable_if_t<IsRVec<U>::value, void *> GetValuePtr(unsigned int slot, std::size_t colIdx, std::size_t varIdx)\n {\n if (fColNames.size() == 1) {\n auto &value = fLastResults[slot * CacheLineStep<ret_type>()][varIdx];\n return static_cast<void *>(&value);\n }\n\n auto &value = fLastResults[slot * CacheLineStep<ret_type>()][colIdx][varIdx];\n return static_cast<void *>(&value);\n }\n\npublic:\n RVariation(const std::vector<std::string> &colNames, std::string_view variationName, F expression,\n const std::vector<std::string> &variationTags, std::string_view type, const RColumnRegister &defines,\n RLoopManager &lm, const ColumnNames_t &inputColNames)\n : RVariationBase(colNames, variationName, variationTags, type, defines, lm, inputColNames),\n fExpression(std::move(expression)), fLastResults(lm.GetNSlots() * RDFInternal::CacheLineStep<ret_type>()),\n fValues(lm.GetNSlots())\n {\n for (auto i = 0u; i < lm.GetNSlots(); ++i)\n fLastResults[i * RDFInternal::CacheLineStep<ret_type>()].resize(fVariationNames.size());\n }\n\n RVariation(const RVariation &) = delete;\n RVariation &operator=(const RVariation &) = delete;\n\n void InitSlot(TTreeReader *r, unsigned int slot) final\n {\n for (auto &define : fColumnRegister.GetColumns())\n define.second->InitSlot(r, slot);\n RColumnReadersInfo info{fInputColumns, fColumnRegister, fIsDefine.data(), fLoopManager->GetDSValuePtrs(),\n fLoopManager->GetDataSource()};\n fValues[slot] = MakeColumnReaders(slot, r, ColumnTypes_t{}, info);\n fLastCheckedEntry[slot * CacheLineStep<Long64_t>()] = -1;\n }\n\n \/\/\/ Return the (type-erased) address of the value for the given processing slot.\n void *GetValuePtr(unsigned int slot, const std::string &column, const std::string &variation) final\n {\n const auto colIt = std::find(fColNames.begin(), fColNames.end(), column);\n assert(colIt != fColNames.end());\n const auto colIdx = std::distance(fColNames.begin(), colIt);\n\n const auto varIt = std::find(fVariationNames.begin(), fVariationNames.end(), variation);\n assert(varIt != fVariationNames.end());\n const auto varIdx = std::distance(fVariationNames.begin(), varIt);\n\n return GetValuePtr(slot, colIdx, varIdx);\n }\n\n \/\/\/ Update the value at the address returned by GetValuePtr with the content corresponding to the given entry\n void Update(unsigned int slot, Long64_t entry) final\n {\n if (entry != fLastCheckedEntry[slot * CacheLineStep<Long64_t>()]) {\n \/\/ evaluate this filter, cache the result\n UpdateHelper(slot, entry, ColumnTypes_t{}, TypeInd_t{});\n fLastCheckedEntry[slot * CacheLineStep<Long64_t>()] = entry;\n }\n }\n\n const std::type_info &GetTypeId() const { return typeid(ret_type); }\n\n \/\/\/ Clean-up operations to be performed at the end of a task.\n void FinalizeSlot(unsigned int slot) final\n {\n for (auto &v : fValues[slot])\n v.reset();\n }\n};\n\n} \/\/ namespace RDF\n} \/\/ namespace Internal\n} \/\/ namespace ROOT\n\n#endif \/\/ ROOT_RDF_RVARIATION\n<commit_msg>[DF] Remove useless protection against vector<bool><commit_after>\/\/ Author: Enrico Guiraud, CERN 10\/2021\n\n\/*************************************************************************\n * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_RDF_RVARIATION\n#define ROOT_RDF_RVARIATION\n\n#include \"Utils.hxx\" \/\/ IsRVec\n#include \"ColumnReaderUtils.hxx\"\n#include \"RColumnReaderBase.hxx\"\n#include \"RLoopManager.hxx\"\n#include \"RVariationBase.hxx\"\n\n#include <ROOT\/RStringView.hxx>\n#include <ROOT\/TypeTraits.hxx>\n#include <Rtypes.h> \/\/ R__CLING_PTRCHECK, Long64_t\n\n#include <array>\n#include <deque>\n#include <map>\n#include <string>\n#include <type_traits> \/\/ std::is_same, std::conditional_t\n#include <utility> \/\/ std::index_sequence\n#include <vector>\n\nclass TTreeReader;\n\nnamespace ROOT {\n\nnamespace RDF {\nclass RDataSource;\n}\n\nnamespace Internal {\nnamespace RDF {\n\nusing namespace ROOT::TypeTraits;\n\ntemplate <typename T>\nbool ResultsSizeEq(const RVec<RVec<T>> &results, std::size_t expected, std::size_t nColumns)\n{\n if (nColumns == 1)\n return results.size() == expected;\n\n return std::all_of(results.begin(), results.end(), [&expected](const RVec<T> &v) { return v.size() == expected; });\n}\n\ntemplate <typename T>\nbool ResultsSizeEq(const RVec<T> &results, std::size_t expected, std::size_t nColumns)\n{\n assert(nColumns == 1);\n (void)nColumns;\n\n return results.size() == expected;\n}\n\ntemplate <typename T>\nstd::size_t GetNVariations(const RVec<RVec<T>> &results)\n{\n assert(!results.empty());\n return results[0].size();\n}\n\ntemplate <typename T>\nstd::size_t GetNVariations(const RVec<T> &results)\n{\n return results.size();\n}\n\ntemplate <typename F>\nclass R__CLING_PTRCHECK(off) RVariation final : public RVariationBase {\n using ColumnTypes_t = typename CallableTraits<F>::arg_types;\n using TypeInd_t = std::make_index_sequence<ColumnTypes_t::list_size>;\n using ret_type = typename CallableTraits<F>::ret_type;\n\n F fExpression;\n std::vector<ret_type> fLastResults;\n\n \/\/\/ Column readers per slot and per input column\n std::vector<std::array<std::unique_ptr<RColumnReaderBase>, ColumnTypes_t::list_size>> fValues;\n\n template <typename... ColTypes, std::size_t... S>\n void UpdateHelper(unsigned int slot, Long64_t entry, TypeList<ColTypes...>, std::index_sequence<S...>)\n {\n \/\/ fExpression must return an RVec<T>\n const auto &results = fExpression(fValues[slot][S]->template Get<ColTypes>(entry)...);\n if (!ResultsSizeEq(results, fVariationNames.size(), fColNames.size())) {\n std::string variationName = fVariationNames[0].substr(0, fVariationNames[0].find_first_of(':'));\n throw std::runtime_error(\"The evaluation of the expression for variation \\\"\" + variationName +\n \"\\\" resulted in \" + std::to_string(GetNVariations(results)) + \" values, but \" +\n std::to_string(fVariationNames.size()) + \" were expected.\");\n }\n \/\/ Assign into fLastResults without changing the addresses of its elements (we gave those addresses away in\n \/\/ GetValuePtr)\n fLastResults[slot * CacheLineStep<ret_type>()].assign(results.begin(), results.end());\n\n \/\/ silence \"unused parameter\" warnings in gcc\n (void)slot;\n (void)entry;\n }\n\n \/\/ This overload is for the case of a single column and ret_type != RVec<RVec<...>> -- the colIdx is ignored.\n template <typename U = typename ret_type::value_type>\n std::enable_if_t<!IsRVec<U>::value, void *>\n GetValuePtr(unsigned int slot, std::size_t \/*colIdx*\/, std::size_t varIdx)\n {\n auto &value = fLastResults[slot * CacheLineStep<ret_type>()][varIdx];\n return static_cast<void *>(&value);\n }\n\n \/\/ This overload is for the case of ret_type == RVec<RVec<...>>\n template <typename U = typename ret_type::value_type>\n std::enable_if_t<IsRVec<U>::value, void *> GetValuePtr(unsigned int slot, std::size_t colIdx, std::size_t varIdx)\n {\n if (fColNames.size() == 1) {\n auto &value = fLastResults[slot * CacheLineStep<ret_type>()][varIdx];\n return static_cast<void *>(&value);\n }\n\n auto &value = fLastResults[slot * CacheLineStep<ret_type>()][colIdx][varIdx];\n return static_cast<void *>(&value);\n }\n\npublic:\n RVariation(const std::vector<std::string> &colNames, std::string_view variationName, F expression,\n const std::vector<std::string> &variationTags, std::string_view type, const RColumnRegister &defines,\n RLoopManager &lm, const ColumnNames_t &inputColNames)\n : RVariationBase(colNames, variationName, variationTags, type, defines, lm, inputColNames),\n fExpression(std::move(expression)), fLastResults(lm.GetNSlots() * RDFInternal::CacheLineStep<ret_type>()),\n fValues(lm.GetNSlots())\n {\n for (auto i = 0u; i < lm.GetNSlots(); ++i)\n fLastResults[i * RDFInternal::CacheLineStep<ret_type>()].resize(fVariationNames.size());\n }\n\n RVariation(const RVariation &) = delete;\n RVariation &operator=(const RVariation &) = delete;\n\n void InitSlot(TTreeReader *r, unsigned int slot) final\n {\n for (auto &define : fColumnRegister.GetColumns())\n define.second->InitSlot(r, slot);\n RColumnReadersInfo info{fInputColumns, fColumnRegister, fIsDefine.data(), fLoopManager->GetDSValuePtrs(),\n fLoopManager->GetDataSource()};\n fValues[slot] = MakeColumnReaders(slot, r, ColumnTypes_t{}, info);\n fLastCheckedEntry[slot * CacheLineStep<Long64_t>()] = -1;\n }\n\n \/\/\/ Return the (type-erased) address of the value for the given processing slot.\n void *GetValuePtr(unsigned int slot, const std::string &column, const std::string &variation) final\n {\n const auto colIt = std::find(fColNames.begin(), fColNames.end(), column);\n assert(colIt != fColNames.end());\n const auto colIdx = std::distance(fColNames.begin(), colIt);\n\n const auto varIt = std::find(fVariationNames.begin(), fVariationNames.end(), variation);\n assert(varIt != fVariationNames.end());\n const auto varIdx = std::distance(fVariationNames.begin(), varIt);\n\n return GetValuePtr(slot, colIdx, varIdx);\n }\n\n \/\/\/ Update the value at the address returned by GetValuePtr with the content corresponding to the given entry\n void Update(unsigned int slot, Long64_t entry) final\n {\n if (entry != fLastCheckedEntry[slot * CacheLineStep<Long64_t>()]) {\n \/\/ evaluate this filter, cache the result\n UpdateHelper(slot, entry, ColumnTypes_t{}, TypeInd_t{});\n fLastCheckedEntry[slot * CacheLineStep<Long64_t>()] = entry;\n }\n }\n\n const std::type_info &GetTypeId() const { return typeid(ret_type); }\n\n \/\/\/ Clean-up operations to be performed at the end of a task.\n void FinalizeSlot(unsigned int slot) final\n {\n for (auto &v : fValues[slot])\n v.reset();\n }\n};\n\n} \/\/ namespace RDF\n} \/\/ namespace Internal\n} \/\/ namespace ROOT\n\n#endif \/\/ ROOT_RDF_RVARIATION\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/mlir_gpu\/passes.h\"\n\n#include \"absl\/memory\/memory.h\"\n#include \"llvm\/ADT\/SetVector.h\"\n#include \"mlir\/Dialect\/GPU\/GPUDialect.h\" \/\/ from @llvm-project\n#include \"mlir\/Dialect\/GPU\/ParallelLoopMapper.h\" \/\/ from @llvm-project\n#include \"mlir\/Dialect\/SCF\/SCF.h\" \/\/ from @llvm-project\n#include \"mlir\/Dialect\/SCF\/Transforms.h\" \/\/ from @llvm-project\n#include \"mlir\/Dialect\/StandardOps\/IR\/Ops.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/BlockAndValueMapping.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Builders.h\" \/\/ from @llvm-project\n#include \"mlir\/Interfaces\/SideEffectInterfaces.h\" \/\/ from @llvm-project\n#include \"mlir\/Transforms\/LoopUtils.h\" \/\/ from @llvm-project\n#include \"mlir\/Transforms\/RegionUtils.h\" \/\/ from @llvm-project\n#include \"tensorflow\/compiler\/mlir\/hlo\/include\/mlir-hlo\/Dialect\/mhlo\/IR\/lhlo_ops.h\"\n\nnamespace xla {\nnamespace mlir_gpu {\nnamespace {\n\n#define GEN_PASS_CLASSES\n#include \"tensorflow\/compiler\/xla\/service\/mlir_gpu\/passes.h.inc\"\n\nstruct FusionOpRemoverPass : FusionOpRemoverPassBase<FusionOpRemoverPass> {\n void runOnFunction() override {\n getFunction().walk([&](mlir::lmhlo::FusionOp op) {\n mlir::OpBuilder builder(op);\n \/\/ FusionOp has a single region with a single block, so we can just walk\n \/\/ over it and clone operations to the outside.\n mlir::BlockAndValueMapping mapping;\n for (auto& nested_op : op.region().front().without_terminator()) {\n auto clone = builder.clone(nested_op, mapping);\n for (auto pair :\n llvm::zip(nested_op.getResults(), clone->getResults())) {\n mapping.map(std::get<0>(pair), std::get<1>(pair));\n }\n }\n op.erase();\n });\n }\n};\n\ntemplate <typename EffectTy>\nbool HasEffectsOnValue(mlir::Value value, mlir::Operation* op) {\n auto mem_effects_interface =\n mlir::dyn_cast_or_null<mlir::MemoryEffectOpInterface>(op);\n if (!mem_effects_interface) {\n return false;\n }\n llvm::SmallVector<mlir::MemoryEffects::EffectInstance, 2> effects;\n mem_effects_interface.getEffects(effects);\n return llvm::any_of(effects,\n [op](const mlir::MemoryEffects::EffectInstance& effect) {\n return mlir::isa<EffectTy>(effect.getEffect());\n });\n}\n\nstruct StoreForwardingPass : StoreForwardingPassBase<StoreForwardingPass> {\n mlir::StoreOp findStore(mlir::Operation* op,\n std::function<bool(mlir::StoreOp)> matches) {\n \/\/ Search from op upwards in the current block.\n mlir::Block* block = op->getBlock();\n auto startFromIt =\n std::find_if(block->rbegin(), block->rend(),\n [op](mlir::Operation& other) { return &other == op; });\n for (auto storeOpIt = startFromIt; storeOpIt != block->rend();\n ++storeOpIt) {\n auto storeOp = llvm::dyn_cast<mlir::StoreOp>(&*(storeOpIt));\n if (!storeOp || !matches(storeOp)) {\n continue;\n }\n\n return storeOp;\n }\n \/\/ No store operation found. Continue search outside of the parallel\n \/\/ loop if block is in a parallel loop.\n if (auto parallelOp =\n llvm::dyn_cast<mlir::scf::ParallelOp>(block->getParentOp())) {\n return findStore(parallelOp.getOperation(), matches);\n }\n return {};\n }\n\n \/\/ Recursively search defining ops for AllocOp. Return either AllocOp if it is\n \/\/ found or nullptr.\n mlir::Operation* SearchAllocOp(mlir::Value memref) {\n mlir::Operation* defOp = memref.getDefiningOp();\n while (auto subviewOp = mlir::dyn_cast_or_null<mlir::SubViewOp>(defOp)) {\n defOp = subviewOp.source().getDefiningOp();\n }\n return HasEffectsOnValue<mlir::MemoryEffects::Allocate>(memref, defOp)\n ? defOp\n : nullptr;\n }\n\n \/\/ Retrieves AllocOp from the cache or actually looks for it.\n mlir::Operation* GetAllocOp(\n mlir::Value memref,\n llvm::DenseMap<mlir::Value, mlir::Operation*>* memrefToAllocOp) {\n auto allocOpIt = memrefToAllocOp->find(memref);\n if (allocOpIt != memrefToAllocOp->end()) {\n return allocOpIt->second;\n }\n mlir::Operation* allocOp = SearchAllocOp(memref);\n memrefToAllocOp->insert({memref, allocOp});\n return allocOp;\n }\n\n void runOnFunction() override {\n llvm::DenseMap<mlir::Value, mlir::Operation*> memrefToAllocOp;\n\n getFunction().walk([&](mlir::LoadOp loadOp) {\n auto storeOp = findStore(loadOp, [&](mlir::StoreOp storeOp) {\n mlir::Operation* storeOpAlloc =\n GetAllocOp(storeOp.memref(), &memrefToAllocOp);\n mlir::Operation* loadOpAlloc =\n GetAllocOp(loadOp.memref(), &memrefToAllocOp);\n return storeOpAlloc && loadOpAlloc && (storeOpAlloc == loadOpAlloc);\n });\n if (!storeOp) {\n return;\n }\n auto storeIndices = storeOp.getIndices();\n auto loadIndices = loadOp.getIndices();\n if (!std::equal(storeIndices.begin(), storeIndices.end(),\n loadIndices.begin(), loadIndices.end())) {\n return;\n }\n loadOp.replaceAllUsesWith(storeOp.getValueToStore());\n loadOp.erase();\n });\n }\n};\n\nstruct DeadTempBufferRemovalPass\n : DeadTempBufferRemovalPassBase<DeadTempBufferRemovalPass> {\n bool operationConsideredDead(mlir::Operation* op) {\n for (auto result : op->getResults()) {\n if (!llvm::all_of(result.getUsers(), [&](mlir::Operation* op) {\n \/\/ Store and Dealloc is OK.\n if (llvm::isa<mlir::StoreOp, mlir::DeallocOp>(op)) {\n return true;\n }\n \/\/ Load without uses is also ok.\n if (auto loadOp = llvm::dyn_cast<mlir::LoadOp>(op)) {\n return loadOp.use_empty();\n }\n \/\/ Subview is ok if it is dead itself.\n if (llvm::isa<mlir::SubViewOp>(op)) {\n return operationConsideredDead(op);\n }\n return false;\n })) {\n return false;\n }\n }\n return true;\n }\n\n void recursiveErase(mlir::Operation* op,\n llvm::SmallVectorImpl<mlir::Operation*>* erase_list) {\n for (auto result : op->getResults()) {\n for (auto user : llvm::make_early_inc_range(result.getUsers())) {\n recursiveErase(user, erase_list);\n }\n }\n erase_list->push_back(op);\n }\n\n void runOnFunction() override {\n llvm::SmallVector<mlir::Operation*, 8> dead_ops;\n getFunction().walk([&](mlir::Operation* op) {\n if (op->getNumResults() != 1 ||\n !HasEffectsOnValue<mlir::MemoryEffects::Allocate>(op->getResult(0),\n op)) {\n return;\n }\n if (!operationConsideredDead(op)) {\n return;\n }\n\n \/\/ TODO(herhut): There should be a generic helper for this.\n recursiveErase(op, &dead_ops);\n });\n for (auto op : dead_ops) {\n op->erase();\n }\n }\n};\n\nstruct RewriteKernelSignaturePass\n : RewriteKernelSignaturePassBase<RewriteKernelSignaturePass> {\n void runOnFunction() override {\n mlir::FuncOp func = getFunction();\n mlir::ModuleOp module = func.getParentOfType<mlir::ModuleOp>();\n getFunction().walk([&](mlir::gpu::LaunchFuncOp launchOp) {\n mlir::gpu::GPUFuncOp kernel =\n module.lookupSymbol<mlir::gpu::GPUFuncOp>(launchOp.kernel());\n\n if (kernel.getNumFuncArguments() !=\n func.getNumArguments() + func.getNumResults()) {\n kernel.emitError()\n << \"number of kernel arguments does not match number\"\n << \"of arguments and results of surrounding function\";\n signalPassFailure();\n return;\n }\n if (!llvm::hasSingleElement(func)) {\n func.emitError() << \"surrounding function has more than one block\";\n signalPassFailure();\n return;\n }\n\n \/\/ Compute a map from function arguments to kernel function operands.\n mlir::BlockAndValueMapping func_to_kernel;\n for (mlir::BlockArgument arg : func.getArguments()) {\n for (int i = 0, e = launchOp.getNumKernelOperands(); i < e; ++i) {\n if (launchOp.getKernelOperand(i) == arg) {\n func_to_kernel.map(arg, kernel.getArgument(i));\n break;\n }\n }\n }\n \/\/ Also add function results that are computed by the launch.\n mlir::Operation* returnOp = func.getBody().back().getTerminator();\n for (mlir::Value result : returnOp->getOperands()) {\n for (int i = 0, e = launchOp.getNumKernelOperands(); i < e; ++i) {\n if (launchOp.getKernelOperand(i) == result) {\n func_to_kernel.map(result, kernel.getArgument(i));\n break;\n }\n }\n }\n\n \/\/ Create a new kernel function with modified signature. It will have the\n \/\/ parameters and result types of the original funcion as its parameter\n \/\/ type and otherwise will be void.\n auto gpu_module = kernel.getParentOfType<mlir::gpu::GPUModuleOp>();\n mlir::OpBuilder kernel_builder(gpu_module.body());\n auto operand_types = llvm::to_vector<4>(llvm::concat<const mlir::Type>(\n func.getType().getInputs(), func.getType().getResults()));\n auto new_kernel = kernel_builder.create<mlir::gpu::GPUFuncOp>(\n kernel.getLoc(), kernel.getName(),\n kernel_builder.getFunctionType(operand_types, {}));\n new_kernel->setAttr(mlir::gpu::GPUDialect::getKernelFuncAttrName(),\n kernel_builder.getUnitAttr());\n\n \/\/ Create a map from old kernel argument to new one.\n mlir::BlockAndValueMapping old_kernel_to_new;\n for (int i = 0, e = func.getNumArguments(); i < e; ++i) {\n mlir::Value func_arg = func.getArgument(i);\n mlir::Value new_kernel_arg = new_kernel.getArgument(i);\n mlir::Value old_kernel_arg = func_to_kernel.lookupOrNull(func_arg);\n if (!old_kernel_arg) {\n kernel.emitOpError()\n << \"argument \" << i\n << \" to containing function is not an argument to the kernel\";\n signalPassFailure();\n return;\n }\n old_kernel_to_new.map(old_kernel_arg, new_kernel_arg);\n }\n for (int i = 0, e = returnOp->getNumOperands(); i < e; ++i) {\n mlir::Value ret_op = returnOp->getOperand(i);\n mlir::Value new_kernel_arg =\n new_kernel.getArgument(func.getNumArguments() + i);\n mlir::Value old_kernel_arg = func_to_kernel.lookupOrNull(ret_op);\n if (!old_kernel_arg) {\n kernel.emitOpError()\n << \"result \" << i\n << \" of containing function is not an argument to the kernel\";\n signalPassFailure();\n return;\n }\n old_kernel_to_new.map(old_kernel_arg, new_kernel_arg);\n }\n \/\/ Steal the body by appending the blocks and inserting a branch.\n kernel.body().cloneInto(&new_kernel.getBody(), old_kernel_to_new);\n kernel_builder.setInsertionPointToEnd(&new_kernel.body().front());\n kernel_builder.create<mlir::BranchOp>(\n new_kernel.getLoc(), &*std::next(new_kernel.body().begin()));\n \/\/ Now create a new launchOp calling the new kernel. We need to forward\n \/\/ the arguments of the surrounding function and operands to the return.\n mlir::SmallVector<mlir::Value, 4> new_operands;\n new_operands.reserve(new_kernel.getNumFuncArguments());\n new_operands.append(func.args_begin(), func.args_end());\n new_operands.append(returnOp->operand_begin(), returnOp->operand_end());\n mlir::OpBuilder launch_builder(launchOp);\n launch_builder.create<mlir::gpu::LaunchFuncOp>(\n launchOp.getLoc(), new_kernel, launchOp.getGridSizeOperandValues(),\n launchOp.getBlockSizeOperandValues(), new_operands);\n \/\/ Launch does not have results, so we can just erase it. And the kernel\n \/\/ also needs to go.\n launchOp.erase();\n kernel.erase();\n });\n }\n};\n\nstruct MapParallelLoopsPass : MapParallelLoopsPassBase<MapParallelLoopsPass> {\n void runOnFunction() override {\n mlir::greedilyMapParallelSCFToGPU(getFunction().getBody());\n }\n};\n\nstruct FuseInnerParallelLoopsPass\n : FuseInnerParallelLoopsPassBase<FuseInnerParallelLoopsPass> {\n void runOnFunction() override {\n getFunction().walk([](mlir::scf::ParallelOp op) {\n mlir::scf::naivelyFuseParallelOps(op.region());\n });\n }\n};\n\nstruct ParallelLoopCollapsingToFirstDimPass\n : ParallelLoopCollapsingToFirstDimPassBase<\n ParallelLoopCollapsingToFirstDimPass> {\n void runOnFunction() override {\n getFunction().walk([&](mlir::scf::ParallelOp op) {\n unsigned num_loops = op.getNumLoops();\n std::vector<unsigned> combinedLoops;\n combinedLoops.reserve(num_loops);\n for (unsigned i = 0; i < num_loops; ++i) {\n combinedLoops.push_back(i);\n }\n mlir::collapseParallelLoops(op, {combinedLoops});\n });\n }\n};\n\n} \/\/ namespace\n\nstd::unique_ptr<mlir::FunctionPass> createFusionOpRemoverPass() {\n return absl::make_unique<FusionOpRemoverPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createStoreForwardingPass() {\n return absl::make_unique<StoreForwardingPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createDeadTempBufferRemovalPass() {\n return absl::make_unique<DeadTempBufferRemovalPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createRewriteKernelSignaturePass() {\n return absl::make_unique<RewriteKernelSignaturePass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createFuseInnerParallelLoopsPass() {\n return absl::make_unique<FuseInnerParallelLoopsPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createMapParallelLoopsPass() {\n return absl::make_unique<MapParallelLoopsPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass>\ncreateParallelLoopCollapsingToFirstDimPass() {\n return absl::make_unique<ParallelLoopCollapsingToFirstDimPass>();\n}\n\n} \/\/ namespace mlir_gpu\n} \/\/ namespace xla\n<commit_msg>Use mlir::OpState::operator->() to get to methods of mlir::Operation.<commit_after>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/mlir_gpu\/passes.h\"\n\n#include \"absl\/memory\/memory.h\"\n#include \"llvm\/ADT\/SetVector.h\"\n#include \"mlir\/Dialect\/GPU\/GPUDialect.h\" \/\/ from @llvm-project\n#include \"mlir\/Dialect\/GPU\/ParallelLoopMapper.h\" \/\/ from @llvm-project\n#include \"mlir\/Dialect\/SCF\/SCF.h\" \/\/ from @llvm-project\n#include \"mlir\/Dialect\/SCF\/Transforms.h\" \/\/ from @llvm-project\n#include \"mlir\/Dialect\/StandardOps\/IR\/Ops.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/BlockAndValueMapping.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Builders.h\" \/\/ from @llvm-project\n#include \"mlir\/Interfaces\/SideEffectInterfaces.h\" \/\/ from @llvm-project\n#include \"mlir\/Transforms\/LoopUtils.h\" \/\/ from @llvm-project\n#include \"mlir\/Transforms\/RegionUtils.h\" \/\/ from @llvm-project\n#include \"tensorflow\/compiler\/mlir\/hlo\/include\/mlir-hlo\/Dialect\/mhlo\/IR\/lhlo_ops.h\"\n\nnamespace xla {\nnamespace mlir_gpu {\nnamespace {\n\n#define GEN_PASS_CLASSES\n#include \"tensorflow\/compiler\/xla\/service\/mlir_gpu\/passes.h.inc\"\n\nstruct FusionOpRemoverPass : FusionOpRemoverPassBase<FusionOpRemoverPass> {\n void runOnFunction() override {\n getFunction().walk([&](mlir::lmhlo::FusionOp op) {\n mlir::OpBuilder builder(op);\n \/\/ FusionOp has a single region with a single block, so we can just walk\n \/\/ over it and clone operations to the outside.\n mlir::BlockAndValueMapping mapping;\n for (auto& nested_op : op.region().front().without_terminator()) {\n auto clone = builder.clone(nested_op, mapping);\n for (auto pair :\n llvm::zip(nested_op.getResults(), clone->getResults())) {\n mapping.map(std::get<0>(pair), std::get<1>(pair));\n }\n }\n op.erase();\n });\n }\n};\n\ntemplate <typename EffectTy>\nbool HasEffectsOnValue(mlir::Value value, mlir::Operation* op) {\n auto mem_effects_interface =\n mlir::dyn_cast_or_null<mlir::MemoryEffectOpInterface>(op);\n if (!mem_effects_interface) {\n return false;\n }\n llvm::SmallVector<mlir::MemoryEffects::EffectInstance, 2> effects;\n mem_effects_interface.getEffects(effects);\n return llvm::any_of(effects,\n [op](const mlir::MemoryEffects::EffectInstance& effect) {\n return mlir::isa<EffectTy>(effect.getEffect());\n });\n}\n\nstruct StoreForwardingPass : StoreForwardingPassBase<StoreForwardingPass> {\n mlir::StoreOp findStore(mlir::Operation* op,\n std::function<bool(mlir::StoreOp)> matches) {\n \/\/ Search from op upwards in the current block.\n mlir::Block* block = op->getBlock();\n auto startFromIt =\n std::find_if(block->rbegin(), block->rend(),\n [op](mlir::Operation& other) { return &other == op; });\n for (auto storeOpIt = startFromIt; storeOpIt != block->rend();\n ++storeOpIt) {\n auto storeOp = llvm::dyn_cast<mlir::StoreOp>(&*(storeOpIt));\n if (!storeOp || !matches(storeOp)) {\n continue;\n }\n\n return storeOp;\n }\n \/\/ No store operation found. Continue search outside of the parallel\n \/\/ loop if block is in a parallel loop.\n if (auto parallelOp =\n llvm::dyn_cast<mlir::scf::ParallelOp>(block->getParentOp())) {\n return findStore(parallelOp.getOperation(), matches);\n }\n return {};\n }\n\n \/\/ Recursively search defining ops for AllocOp. Return either AllocOp if it is\n \/\/ found or nullptr.\n mlir::Operation* SearchAllocOp(mlir::Value memref) {\n mlir::Operation* defOp = memref.getDefiningOp();\n while (auto subviewOp = mlir::dyn_cast_or_null<mlir::SubViewOp>(defOp)) {\n defOp = subviewOp.source().getDefiningOp();\n }\n return HasEffectsOnValue<mlir::MemoryEffects::Allocate>(memref, defOp)\n ? defOp\n : nullptr;\n }\n\n \/\/ Retrieves AllocOp from the cache or actually looks for it.\n mlir::Operation* GetAllocOp(\n mlir::Value memref,\n llvm::DenseMap<mlir::Value, mlir::Operation*>* memrefToAllocOp) {\n auto allocOpIt = memrefToAllocOp->find(memref);\n if (allocOpIt != memrefToAllocOp->end()) {\n return allocOpIt->second;\n }\n mlir::Operation* allocOp = SearchAllocOp(memref);\n memrefToAllocOp->insert({memref, allocOp});\n return allocOp;\n }\n\n void runOnFunction() override {\n llvm::DenseMap<mlir::Value, mlir::Operation*> memrefToAllocOp;\n\n getFunction().walk([&](mlir::LoadOp loadOp) {\n auto storeOp = findStore(loadOp, [&](mlir::StoreOp storeOp) {\n mlir::Operation* storeOpAlloc =\n GetAllocOp(storeOp.memref(), &memrefToAllocOp);\n mlir::Operation* loadOpAlloc =\n GetAllocOp(loadOp.memref(), &memrefToAllocOp);\n return storeOpAlloc && loadOpAlloc && (storeOpAlloc == loadOpAlloc);\n });\n if (!storeOp) {\n return;\n }\n auto storeIndices = storeOp.getIndices();\n auto loadIndices = loadOp.getIndices();\n if (!std::equal(storeIndices.begin(), storeIndices.end(),\n loadIndices.begin(), loadIndices.end())) {\n return;\n }\n loadOp.replaceAllUsesWith(storeOp.getValueToStore());\n loadOp.erase();\n });\n }\n};\n\nstruct DeadTempBufferRemovalPass\n : DeadTempBufferRemovalPassBase<DeadTempBufferRemovalPass> {\n bool operationConsideredDead(mlir::Operation* op) {\n for (auto result : op->getResults()) {\n if (!llvm::all_of(result.getUsers(), [&](mlir::Operation* op) {\n \/\/ Store and Dealloc is OK.\n if (llvm::isa<mlir::StoreOp, mlir::DeallocOp>(op)) {\n return true;\n }\n \/\/ Load without uses is also ok.\n if (auto loadOp = llvm::dyn_cast<mlir::LoadOp>(op)) {\n return loadOp.use_empty();\n }\n \/\/ Subview is ok if it is dead itself.\n if (llvm::isa<mlir::SubViewOp>(op)) {\n return operationConsideredDead(op);\n }\n return false;\n })) {\n return false;\n }\n }\n return true;\n }\n\n void recursiveErase(mlir::Operation* op,\n llvm::SmallVectorImpl<mlir::Operation*>* erase_list) {\n for (auto result : op->getResults()) {\n for (auto user : llvm::make_early_inc_range(result.getUsers())) {\n recursiveErase(user, erase_list);\n }\n }\n erase_list->push_back(op);\n }\n\n void runOnFunction() override {\n llvm::SmallVector<mlir::Operation*, 8> dead_ops;\n getFunction().walk([&](mlir::Operation* op) {\n if (op->getNumResults() != 1 ||\n !HasEffectsOnValue<mlir::MemoryEffects::Allocate>(op->getResult(0),\n op)) {\n return;\n }\n if (!operationConsideredDead(op)) {\n return;\n }\n\n \/\/ TODO(herhut): There should be a generic helper for this.\n recursiveErase(op, &dead_ops);\n });\n for (auto op : dead_ops) {\n op->erase();\n }\n }\n};\n\nstruct RewriteKernelSignaturePass\n : RewriteKernelSignaturePassBase<RewriteKernelSignaturePass> {\n void runOnFunction() override {\n mlir::FuncOp func = getFunction();\n mlir::ModuleOp module = func->getParentOfType<mlir::ModuleOp>();\n getFunction().walk([&](mlir::gpu::LaunchFuncOp launchOp) {\n mlir::gpu::GPUFuncOp kernel =\n module.lookupSymbol<mlir::gpu::GPUFuncOp>(launchOp.kernel());\n\n if (kernel.getNumFuncArguments() !=\n func.getNumArguments() + func.getNumResults()) {\n kernel.emitError()\n << \"number of kernel arguments does not match number\"\n << \"of arguments and results of surrounding function\";\n signalPassFailure();\n return;\n }\n if (!llvm::hasSingleElement(func)) {\n func.emitError() << \"surrounding function has more than one block\";\n signalPassFailure();\n return;\n }\n\n \/\/ Compute a map from function arguments to kernel function operands.\n mlir::BlockAndValueMapping func_to_kernel;\n for (mlir::BlockArgument arg : func.getArguments()) {\n for (int i = 0, e = launchOp.getNumKernelOperands(); i < e; ++i) {\n if (launchOp.getKernelOperand(i) == arg) {\n func_to_kernel.map(arg, kernel.getArgument(i));\n break;\n }\n }\n }\n \/\/ Also add function results that are computed by the launch.\n mlir::Operation* returnOp = func.getBody().back().getTerminator();\n for (mlir::Value result : returnOp->getOperands()) {\n for (int i = 0, e = launchOp.getNumKernelOperands(); i < e; ++i) {\n if (launchOp.getKernelOperand(i) == result) {\n func_to_kernel.map(result, kernel.getArgument(i));\n break;\n }\n }\n }\n\n \/\/ Create a new kernel function with modified signature. It will have the\n \/\/ parameters and result types of the original funcion as its parameter\n \/\/ type and otherwise will be void.\n auto gpu_module = kernel->getParentOfType<mlir::gpu::GPUModuleOp>();\n mlir::OpBuilder kernel_builder(gpu_module.body());\n auto operand_types = llvm::to_vector<4>(llvm::concat<const mlir::Type>(\n func.getType().getInputs(), func.getType().getResults()));\n auto new_kernel = kernel_builder.create<mlir::gpu::GPUFuncOp>(\n kernel.getLoc(), kernel.getName(),\n kernel_builder.getFunctionType(operand_types, {}));\n new_kernel->setAttr(mlir::gpu::GPUDialect::getKernelFuncAttrName(),\n kernel_builder.getUnitAttr());\n\n \/\/ Create a map from old kernel argument to new one.\n mlir::BlockAndValueMapping old_kernel_to_new;\n for (int i = 0, e = func.getNumArguments(); i < e; ++i) {\n mlir::Value func_arg = func.getArgument(i);\n mlir::Value new_kernel_arg = new_kernel.getArgument(i);\n mlir::Value old_kernel_arg = func_to_kernel.lookupOrNull(func_arg);\n if (!old_kernel_arg) {\n kernel.emitOpError()\n << \"argument \" << i\n << \" to containing function is not an argument to the kernel\";\n signalPassFailure();\n return;\n }\n old_kernel_to_new.map(old_kernel_arg, new_kernel_arg);\n }\n for (int i = 0, e = returnOp->getNumOperands(); i < e; ++i) {\n mlir::Value ret_op = returnOp->getOperand(i);\n mlir::Value new_kernel_arg =\n new_kernel.getArgument(func.getNumArguments() + i);\n mlir::Value old_kernel_arg = func_to_kernel.lookupOrNull(ret_op);\n if (!old_kernel_arg) {\n kernel.emitOpError()\n << \"result \" << i\n << \" of containing function is not an argument to the kernel\";\n signalPassFailure();\n return;\n }\n old_kernel_to_new.map(old_kernel_arg, new_kernel_arg);\n }\n \/\/ Steal the body by appending the blocks and inserting a branch.\n kernel.body().cloneInto(&new_kernel.getBody(), old_kernel_to_new);\n kernel_builder.setInsertionPointToEnd(&new_kernel.body().front());\n kernel_builder.create<mlir::BranchOp>(\n new_kernel.getLoc(), &*std::next(new_kernel.body().begin()));\n \/\/ Now create a new launchOp calling the new kernel. We need to forward\n \/\/ the arguments of the surrounding function and operands to the return.\n mlir::SmallVector<mlir::Value, 4> new_operands;\n new_operands.reserve(new_kernel.getNumFuncArguments());\n new_operands.append(func.args_begin(), func.args_end());\n new_operands.append(returnOp->operand_begin(), returnOp->operand_end());\n mlir::OpBuilder launch_builder(launchOp);\n launch_builder.create<mlir::gpu::LaunchFuncOp>(\n launchOp.getLoc(), new_kernel, launchOp.getGridSizeOperandValues(),\n launchOp.getBlockSizeOperandValues(), new_operands);\n \/\/ Launch does not have results, so we can just erase it. And the kernel\n \/\/ also needs to go.\n launchOp.erase();\n kernel.erase();\n });\n }\n};\n\nstruct MapParallelLoopsPass : MapParallelLoopsPassBase<MapParallelLoopsPass> {\n void runOnFunction() override {\n mlir::greedilyMapParallelSCFToGPU(getFunction().getBody());\n }\n};\n\nstruct FuseInnerParallelLoopsPass\n : FuseInnerParallelLoopsPassBase<FuseInnerParallelLoopsPass> {\n void runOnFunction() override {\n getFunction().walk([](mlir::scf::ParallelOp op) {\n mlir::scf::naivelyFuseParallelOps(op.region());\n });\n }\n};\n\nstruct ParallelLoopCollapsingToFirstDimPass\n : ParallelLoopCollapsingToFirstDimPassBase<\n ParallelLoopCollapsingToFirstDimPass> {\n void runOnFunction() override {\n getFunction().walk([&](mlir::scf::ParallelOp op) {\n unsigned num_loops = op.getNumLoops();\n std::vector<unsigned> combinedLoops;\n combinedLoops.reserve(num_loops);\n for (unsigned i = 0; i < num_loops; ++i) {\n combinedLoops.push_back(i);\n }\n mlir::collapseParallelLoops(op, {combinedLoops});\n });\n }\n};\n\n} \/\/ namespace\n\nstd::unique_ptr<mlir::FunctionPass> createFusionOpRemoverPass() {\n return absl::make_unique<FusionOpRemoverPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createStoreForwardingPass() {\n return absl::make_unique<StoreForwardingPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createDeadTempBufferRemovalPass() {\n return absl::make_unique<DeadTempBufferRemovalPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createRewriteKernelSignaturePass() {\n return absl::make_unique<RewriteKernelSignaturePass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createFuseInnerParallelLoopsPass() {\n return absl::make_unique<FuseInnerParallelLoopsPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass> createMapParallelLoopsPass() {\n return absl::make_unique<MapParallelLoopsPass>();\n}\n\nstd::unique_ptr<mlir::FunctionPass>\ncreateParallelLoopCollapsingToFirstDimPass() {\n return absl::make_unique<ParallelLoopCollapsingToFirstDimPass>();\n}\n\n} \/\/ namespace mlir_gpu\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <cmath>\n\n#include \"tensorflow\/core\/framework\/allocator.h\"\n#include \"tensorflow\/core\/framework\/fake_input.h\"\n#include \"tensorflow\/core\/framework\/node_def_builder.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor_testutil.h\"\n#include \"tensorflow\/core\/framework\/types.h\"\n#include \"tensorflow\/core\/framework\/types.pb.h\"\n#include \"tensorflow\/core\/kernels\/ops_testutil.h\"\n#include \"tensorflow\/core\/kernels\/ops_util.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n#include \"tensorflow\/core\/platform\/test_benchmark.h\"\n\nnamespace tensorflow {\n\nclass MklRequantizatedOpsTest : public OpsTestBase {};\n\nclass MklRequantizatedOpsTestHelper : public OpsTestBase {\n public:\n void Setup(Tensor &input_tensor_qint32, float &range_weights_ch1,\n float &range_weights_ch2);\n void TestBody(){};\n};\n\nvoid MklRequantizatedOpsTestHelper::Setup(Tensor &input_tensor_qint32,\n float &range_weights_ch1,\n float &range_weights_ch2) {\n \/\/ Step 1: Input range assumptions\n \/\/ -------------------------------\n \/\/ Assume input Tensor T (NHWC) in FP32 has range [0, 5.0] size nt*ht*wt*ct\n \/\/ Assume input Filter W (NHWC) with 2 output channels of size nw*ht*wt*2\n \/\/ logically, Filter W has 2 channels W1 and W2 each of size nw*ht*wt*1\n \/\/ Assume input Filter W1(NHWC) in FP32 has range [-2.0, 2.0]size nw*ht*wt*1\n \/\/ Assume input Filter W2(NHWC) in FP32 has range [-3.0, 3.0]size nw*ht*wt*1\n\n \/\/ Step 2: Quantization details (per channel)\n \/\/ ------------------------------------------\n \/\/ T and W are quantized using a Quantize Op.\n \/\/ The input Tensor T (NHWC) is quantized to unsigned int8.\n \/\/ Hence T's max value is mapped to ((2^8-1) = 255).\n \/\/ The input Filter W (NHWC) is quantized to signed int8.\n \/\/ Hence W's max value is mapped to ((2^7)-1 = 127)).\n\n \/\/ Range of Quantized T in uint8[0 , 255] maps to orig T in FP32[0 , 5.0]\n \/\/ Range of Quantized W1 in int8[-127, 127] maps to orig W1 in FP32[-2.0, 2.0]\n \/\/ Range of Quantized W2 in int8[-127, 127] maps to orig W2 in FP32[-3.0, 3.0]\n\n \/\/ Hence the resolution of Quantized T will be 5.0\/255\n \/\/ Hence the resolution of Quantized W1 will be 2.0\/127\n \/\/ Hence the resolution of Quantized W2 will be 3.0\/127\n\n \/\/ Step 3: Assumption of quantizedconv on quantized input&weights(per channel)\n \/\/ ---------------------------------------------------------------------------\n \/\/ The input T and weights W1 (or W2) will be convolved.\n \/\/ The output Tensor T is in int32 whose range is [-2^31, 2^31).\n \/\/ For simplicity, we truncate the range to (-2^31, 2^31) to make it\n \/\/ symmetric.\n \/\/ The range of the convolved T*W1 is ((2^31)-1) * 5.0\/255 * 2.0\/127 =\n \/\/ 663110.59\n \/\/ So the range of convolved T*W1 in int32(-2^31, 2^31) that maps to\n \/\/ orig T range in FP32[0, 5.0] * [-2.0, 2.0] is [-663110.59, 663110.59]\n\n \/\/ The range of the convolved T*W2 is (2^31-1) * 5.0\/255 * 3.0\/127 = 994665.88\n \/\/ So the range of convolved T*W1 in int32(-2^31, 2^31) that maps to\n \/\/ orig T range in FP32 [0, 5.0] * [-3.0, 3.0] is [-994665.88, 994665.88]\n\n \/\/ Step 4: Assumption output above is fed to Requantization_range_perchannel\n \/\/ --------------------------------------------------------------------------\n \/\/ Here we recalculate the new range for convolved T*W so that we\n \/\/ make good use in int8 quantization from int32 to int8.\n\n \/\/ We assume the above operations are performed and use these values above\n \/\/ as ranges for Requantization_range_perchannel_op.\n range_weights_ch1 = 663110.59; \/\/ For W1 channel\n range_weights_ch2 = 994665.88; \/\/ For W2 Channel\n\n \/\/ We Fill the input Tensor T qint32 with arbitrary int32 values\n test::FillValues<qint32>(\n &input_tensor_qint32,\n {-1000, -2000, 2000, 4000, -3000, -6000, 4000, 8000,\n 5000, 10000, -6000, -12000, 7000, 14000, 8000, 16000,\n 9000, -18000, -10000, -20000, 11000, 22000, -12000, -24000,\n 13000, 26000, 14000, 28000, -15000, -30000, 16000, 32000});\n\n \/\/ Step 5: Define and run requantization_range_perchannel\n \/\/ -------------------------------------------------------\n \/\/ See test RequantizationRangePerChannelTest_Basic and\/or\n \/\/ test RequantizationRangePerChannelTest_ClipMax\n}\n\n\/\/ Tests the RequantizationRangePerChannel Op wherein the range\n\/\/ of the weights is calculated per channel.\nTEST_F(MklRequantizatedOpsTest, RequantizationRangePerChannelTest_Basic) {\n \/\/ Let us set up the tensor and inputs before we run this op.\n float clip_value_max = static_cast<float>((1L << 31) - 1);\n float range_weights_ch1 = 0.0;\n float range_weights_ch2 = 0.0;\n\n \/\/ Create the input tensor\n const int input_height = 4;\n const int input_width = 4;\n const int input_channels = 2;\n\n \/\/ Define the shape of T.\n Tensor input_tensor_qint32(DT_QINT32,\n {1, input_height, input_width, input_channels});\n\n \/\/ Explanation and setup prior to this Op. Fill T and populate range values.\n MklRequantizatedOpsTestHelper helper;\n helper.Setup(input_tensor_qint32, range_weights_ch1, range_weights_ch2);\n\n \/\/ Step 5: Define and run requantization_range_perchannel\n \/\/ -------------------------------------------------------\n \/\/ Define, create and initialize the OP in question.\n TF_ASSERT_OK(NodeDefBuilder(\"requantization_range_per_channel\",\n \"RequantizationRangePerChannel\")\n .Input(FakeInput(DT_QINT32))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"T\", DataTypeToEnum<qint32>::v())\n .Attr(\"clip_value_max\", clip_value_max)\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n \/\/ Add the Input Nodes to the Op.\n AddInputFromArray<qint32>(input_tensor_qint32.shape(),\n input_tensor_qint32.flat<qint32>());\n\n \/\/ Calculate the Min and max from the ranges\n float ch1_min = -range_weights_ch1;\n float ch1_max = range_weights_ch1;\n float ch2_min = -range_weights_ch2;\n float ch2_max = range_weights_ch2;\n\n \/\/ Add the Perchannel range Nodes to the Op.\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_min, ch2_min});\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_max, ch2_max});\n\n \/\/ Run the Kernel\n TF_ASSERT_OK(RunOpKernel());\n\n \/\/ Step 6: Verify Output and Store values to test Requantize_perchannel\n \/\/ --------------------------------------------------------------------\n\n \/\/ Verify the Expected Outputs\n const float output_min = GetOutput(0)->flat<float>()(0);\n const float output_max = GetOutput(1)->flat<float>()(0);\n EXPECT_NEAR(-14.8217, output_min, 0.002);\n EXPECT_NEAR(14.8217, output_max, 0.002);\n\n \/\/ output range is made use in RequantizePerChannelTest_Basic\n}\n\nTEST_F(MklRequantizatedOpsTest, RequantizationRangePerChannelTest_ClipMax) {\n \/\/ Let us setup the tensor and inputs before we run this op.\n float clip_value_max = 6; \/\/ Can be used as 6 for Relu 6 activations.\n float range_weights_ch1 = 0.0;\n float range_weights_ch2 = 0.0;\n\n \/\/ Create the input tensor\n const int input_height = 4;\n const int input_width = 4;\n const int input_channels = 2;\n\n \/\/ define and input tensor T shape.\n Tensor input_tensor_qint32(DT_QINT32,\n {1, input_height, input_width, input_channels});\n\n \/\/ Explanation and setup prior to this Op. Fill T and populate range values.\n MklRequantizatedOpsTestHelper helper;\n helper.Setup(input_tensor_qint32, range_weights_ch1, range_weights_ch2);\n\n \/\/ Step 5: Define and run requantization_range_perchannel\n \/\/ -------------------------------------------------------\n \/\/ Define, create and initalize the OP in question.\n TF_ASSERT_OK(NodeDefBuilder(\"requantization_range_per_channel\",\n \"RequantizationRangePerChannel\")\n .Input(FakeInput(DT_QINT32))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"T\", DataTypeToEnum<qint32>::v())\n .Attr(\"clip_value_max\", clip_value_max)\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n \/\/ Add the Input Nodes to the Op.\n AddInputFromArray<qint32>(input_tensor_qint32.shape(),\n input_tensor_qint32.flat<qint32>());\n\n \/\/ Calculate the Min and max from the ranges\n float ch1_min = -range_weights_ch1;\n float ch1_max = range_weights_ch1;\n float ch2_min = -range_weights_ch2;\n float ch2_max = range_weights_ch2;\n\n \/\/ Add the Perchannel range Nodes to the Op.\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_min, ch2_min});\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_max, ch2_max});\n\n \/\/ Run the Kernel\n TF_ASSERT_OK(RunOpKernel());\n\n \/\/ Step 6: Verify Output and Store values to test Requantize_perchannel\n \/\/ --------------------------------------------------------------------\n\n \/\/ Verify the Expected Outputs\n const float output_min = GetOutput(0)->flat<float>()(0);\n const float output_max = GetOutput(1)->flat<float>()(0);\n EXPECT_NEAR(-6.0, output_min, 0.002); \/\/ Values are Max as with clip_value\n EXPECT_NEAR(6.0, output_max, 0.002); \/\/ Values are Max as with clip_value\n}\n\nTEST_F(MklRequantizatedOpsTest, RequantizePerChannelTest_Basic) {\n \/\/ Let us setup the tensor and inputs before we run this op.\n float range_weights_ch1 = 0.0;\n float range_weights_ch2 = 0.0;\n\n \/\/ Create the input tensor\n const int input_height = 4;\n const int input_width = 4;\n const int input_channels = 2;\n\n \/\/ define an input tensor T shape.\n Tensor input_tensor_qint32(DT_QINT32,\n {1, input_height, input_width, input_channels});\n\n \/\/ Explanation and setup prior to this Op. Fill T and populate range values.\n MklRequantizatedOpsTestHelper helper;\n helper.Setup(input_tensor_qint32, range_weights_ch1, range_weights_ch2);\n\n \/\/ Step 7: Define and run requantize_perchannel\n \/\/ --------------------------------------------\n \/\/ The output of Requantization_range_op_per_channel which calculated the\n \/\/ new ranges of int8 is fed to the requantize per channel op.\n \/\/ Here the Values of Convolved T*W is converted from int32 to int8.\n\n TF_ASSERT_OK(NodeDefBuilder(\"requantize_per_channel\", \"RequantizePerChannel\")\n .Input(FakeInput(DT_QINT32))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"T\", DataTypeToEnum<qint32>::v())\n .Attr(\"out_type\", DataTypeToEnum<qint8>::v())\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n \/\/ Add the Input Nodes to the Op.\n AddInputFromArray<qint32>(input_tensor_qint32.shape(),\n input_tensor_qint32.flat<qint32>());\n\n \/\/ Calculate the Min and max from the ranges\n float ch1_min = -range_weights_ch1;\n float ch1_max = range_weights_ch1;\n float ch2_min = -range_weights_ch2;\n float ch2_max = range_weights_ch2;\n\n \/\/ Add the Perchannel range Nodes to the Op.\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_min, ch2_min});\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_max, ch2_max});\n\n \/\/ Calculate the Min and max from Step 6 above\n \/\/ in RequantizationRangePerChannelTest_Basic\n float range_op_output_min = -14.8217;\n float range_op_output_max = 14.8217;\n\n \/\/ Add the Requested_min and requested_max stored from Step 6.\n AddInputFromArray<float>(TensorShape({1}), {range_op_output_min});\n AddInputFromArray<float>(TensorShape({1}), {range_op_output_max});\n\n \/\/ Run the kernel\n TF_ASSERT_OK(RunOpKernel());\n\n \/\/ Verify the output with the expected output\n Tensor output = *GetOutput(0);\n const float output_min = GetOutput(1)->flat<float>()(0);\n const float output_max = GetOutput(2)->flat<float>()(0);\n EXPECT_NEAR(range_op_output_min, output_min, 0.002);\n EXPECT_NEAR(range_op_output_max, output_max, 0.002);\n}\n\n} \/\/ namespace tensorflow\n<commit_msg>change comments for test 2<commit_after>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <cmath>\n\n#include \"tensorflow\/core\/framework\/allocator.h\"\n#include \"tensorflow\/core\/framework\/fake_input.h\"\n#include \"tensorflow\/core\/framework\/node_def_builder.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor_testutil.h\"\n#include \"tensorflow\/core\/framework\/types.h\"\n#include \"tensorflow\/core\/framework\/types.pb.h\"\n#include \"tensorflow\/core\/kernels\/ops_testutil.h\"\n#include \"tensorflow\/core\/kernels\/ops_util.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n#include \"tensorflow\/core\/platform\/test_benchmark.h\"\n\nnamespace tensorflow {\n\nclass MklRequantizatedOpsTest : public OpsTestBase {};\n\nclass MklRequantizatedOpsTestHelper : public OpsTestBase {\n public:\n void Setup(Tensor &input_tensor_qint32, float &range_weights_ch1,\n float &range_weights_ch2);\n void TestBody(){};\n};\n\nvoid MklRequantizatedOpsTestHelper::Setup(Tensor &input_tensor_qint32,\n float &range_weights_ch1,\n float &range_weights_ch2) {\n \/\/ Step 1: Input range assumptions\n \/\/ -------------------------------\n \/\/ Assume input tensor T (NHWC) in FP32 has range [0, 5.0] size nt*ht*wt*ct\n \/\/ Assume input filter W (NHWC) with 2 output channels of size nw*ht*wt*2\n \/\/ logically, filter W has 2 channels W1 and W2 each of size nw*ht*wt*1\n \/\/ Assume input filter W1(NHWC) in FP32 has range [-2.0, 2.0]size nw*ht*wt*1\n \/\/ Assume input filter W2(NHWC) in FP32 has range [-3.0, 3.0]size nw*ht*wt*1\n\n \/\/ Step 2: Quantization details (per channel)\n \/\/ ------------------------------------------\n \/\/ T and W are quantized using a quantize Op.\n \/\/ The input tensor T (NHWC) is quantized to unsigned int8.\n \/\/ Hence T's max value is mapped to ((2^8-1) = 255).\n \/\/ The input filter W (NHWC) is quantized to signed int8.\n \/\/ Hence W's max value is mapped to ((2^7)-1 = 127)).\n\n \/\/ Range of quantized T in uint8[0 , 255] maps to orig T in FP32[0 , 5.0]\n \/\/ Range of quantized W1 in int8[-127, 127] maps to orig W1 in FP32[-2.0, 2.0]\n \/\/ Range of quantized W2 in int8[-127, 127] maps to orig W2 in FP32[-3.0, 3.0]\n\n \/\/ Hence the resolution of quantized T will be 5.0\/255\n \/\/ Hence the resolution of quantized W1 will be 2.0\/127\n \/\/ Hence the resolution of quantized W2 will be 3.0\/127\n\n \/\/ Step 3: Assumption of quantizedconv on quantized input&weights(per channel)\n \/\/ ---------------------------------------------------------------------------\n \/\/ The input T and weights W1 (or W2) will be convolved.\n \/\/ The output tensor T is in int32 whose range is [-2^31, 2^31).\n \/\/ For simplicity, we truncate the range to (-2^31, 2^31) to make it\n \/\/ symmetric.\n \/\/ The range of the convolved T*W1 is ((2^31)-1) * 5.0\/255 * 2.0\/127 =\n \/\/ 663110.59\n \/\/ So the range of convolved T*W1 in int32(-2^31, 2^31) that maps to\n \/\/ orig T range in FP32[0, 5.0] * [-2.0, 2.0] is [-663110.59, 663110.59]\n\n \/\/ The range of the convolved T*W2 is (2^31-1) * 5.0\/255 * 3.0\/127 = 994665.88\n \/\/ So the range of convolved T*W1 in int32(-2^31, 2^31) that maps to\n \/\/ orig T range in FP32 [0, 5.0] * [-3.0, 3.0] is [-994665.88, 994665.88]\n\n \/\/ Step 4: Assumption output above is fed to requantization_range_perchannel\n \/\/ --------------------------------------------------------------------------\n \/\/ Here we recalculate the new range for convolved T*W so that we\n \/\/ make good use in int8 quantization from int32 to int8.\n\n \/\/ We assume the above operations are performed and use these values above\n \/\/ as ranges for requantization_range_perchannel_op.\n range_weights_ch1 = 663110.59; \/\/ For W1 channel\n range_weights_ch2 = 994665.88; \/\/ For W2 Channel\n\n \/\/ We Fill the input tensor T qint32 with arbitrary int32 values\n test::FillValues<qint32>(\n &input_tensor_qint32,\n {-1000, -2000, 2000, 4000, -3000, -6000, 4000, 8000,\n 5000, 10000, -6000, -12000, 7000, 14000, 8000, 16000,\n 9000, -18000, -10000, -20000, 11000, 22000, -12000, -24000,\n 13000, 26000, 14000, 28000, -15000, -30000, 16000, 32000});\n\n \/\/ Step 5: Define and run requantization_range_perchannel\n \/\/ -------------------------------------------------------\n \/\/ See test RequantizationRangePerChannelTest_Basic and\/or\n \/\/ test RequantizationRangePerChannelTest_ClipMax\n}\n\n\/\/ Tests the RequantizationRangePerChannel Op wherein the range\n\/\/ of the weights is calculated per channel.\nTEST_F(MklRequantizatedOpsTest, RequantizationRangePerChannelTest_Basic) {\n \/\/ Let us set up the tensor and inputs before we run this op.\n float clip_value_max = static_cast<float>((1L << 31) - 1);\n float range_weights_ch1 = 0.0;\n float range_weights_ch2 = 0.0;\n\n \/\/ Create the input tensor\n const int input_height = 4;\n const int input_width = 4;\n const int input_channels = 2;\n\n \/\/ Define the shape of T.\n Tensor input_tensor_qint32(DT_QINT32,\n {1, input_height, input_width, input_channels});\n\n \/\/ Explanation and setup prior to this Op. Fill T and populate range values.\n MklRequantizatedOpsTestHelper helper;\n helper.Setup(input_tensor_qint32, range_weights_ch1, range_weights_ch2);\n\n \/\/ Step 5: Define and run requantization_range_perchannel\n \/\/ -------------------------------------------------------\n \/\/ Define, create and initialize the OP in question.\n TF_ASSERT_OK(NodeDefBuilder(\"requantization_range_per_channel\",\n \"RequantizationRangePerChannel\")\n .Input(FakeInput(DT_QINT32))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"T\", DataTypeToEnum<qint32>::v())\n .Attr(\"clip_value_max\", clip_value_max)\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n \/\/ Add the Input Nodes to the Op.\n AddInputFromArray<qint32>(input_tensor_qint32.shape(),\n input_tensor_qint32.flat<qint32>());\n\n \/\/ Calculate the Min and max from the ranges\n float ch1_min = -range_weights_ch1;\n float ch1_max = range_weights_ch1;\n float ch2_min = -range_weights_ch2;\n float ch2_max = range_weights_ch2;\n\n \/\/ Add the perchannel range Nodes to the Op.\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_min, ch2_min});\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_max, ch2_max});\n\n \/\/ Run the kernel\n TF_ASSERT_OK(RunOpKernel());\n\n \/\/ Step 6: Verify output and store values to test requantize_perchannel\n \/\/ --------------------------------------------------------------------\n\n \/\/ Verify the Expected Outputs\n const float output_min = GetOutput(0)->flat<float>()(0);\n const float output_max = GetOutput(1)->flat<float>()(0);\n EXPECT_NEAR(-14.8217, output_min, 0.002);\n EXPECT_NEAR(14.8217, output_max, 0.002);\n\n \/\/ output range is made use in requantizePerChannelTest_Basic\n}\n\nTEST_F(MklRequantizatedOpsTest, RequantizationRangePerChannelTest_ClipMax) {\n \/\/ Let us setup the tensor and inputs before we run this op.\n float clip_value_max = 6; \/\/ Can be used as 6 for Relu 6 activations.\n float range_weights_ch1 = 0.0;\n float range_weights_ch2 = 0.0;\n\n \/\/ Create the input tensor\n const int input_height = 4;\n const int input_width = 4;\n const int input_channels = 2;\n\n \/\/ define and input tensor T shape.\n Tensor input_tensor_qint32(DT_QINT32,\n {1, input_height, input_width, input_channels});\n\n \/\/ Explanation and setup prior to this Op. Fill T and populate range values.\n MklRequantizatedOpsTestHelper helper;\n helper.Setup(input_tensor_qint32, range_weights_ch1, range_weights_ch2);\n\n \/\/ Step 5: Define and run requantization_range_perchannel\n \/\/ -------------------------------------------------------\n \/\/ Define, create and initalize the OP in question.\n TF_ASSERT_OK(NodeDefBuilder(\"requantization_range_per_channel\",\n \"RequantizationRangePerChannel\")\n .Input(FakeInput(DT_QINT32))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"T\", DataTypeToEnum<qint32>::v())\n .Attr(\"clip_value_max\", clip_value_max)\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n \/\/ Add the Input Nodes to the Op.\n AddInputFromArray<qint32>(input_tensor_qint32.shape(),\n input_tensor_qint32.flat<qint32>());\n\n \/\/ Calculate the min and max from the ranges\n float ch1_min = -range_weights_ch1;\n float ch1_max = range_weights_ch1;\n float ch2_min = -range_weights_ch2;\n float ch2_max = range_weights_ch2;\n\n \/\/ Add the perchannel range nodes to the Op.\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_min, ch2_min});\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_max, ch2_max});\n\n \/\/ Run the kernel\n TF_ASSERT_OK(RunOpKernel());\n\n \/\/ Step 6: Verify output and store values to test requantize_perchannel\n \/\/ --------------------------------------------------------------------\n\n \/\/ Verify the expected outputs\n const float output_min = GetOutput(0)->flat<float>()(0);\n const float output_max = GetOutput(1)->flat<float>()(0);\n EXPECT_NEAR(-6.0, output_min, 0.002); \/\/ Values are Max as with clip_value\n EXPECT_NEAR(6.0, output_max, 0.002); \/\/ Values are Max as with clip_value\n}\n\nTEST_F(MklRequantizatedOpsTest, RequantizePerChannelTest_Basic) {\n \/\/ Let us setup the tensor and inputs before we run this op.\n float range_weights_ch1 = 0.0;\n float range_weights_ch2 = 0.0;\n\n \/\/ Create the input tensor\n const int input_height = 4;\n const int input_width = 4;\n const int input_channels = 2;\n\n \/\/ define an input tensor T shape.\n Tensor input_tensor_qint32(DT_QINT32,\n {1, input_height, input_width, input_channels});\n\n \/\/ Explanation and setup prior to this Op. Fill T and populate range values.\n MklRequantizatedOpsTestHelper helper;\n helper.Setup(input_tensor_qint32, range_weights_ch1, range_weights_ch2);\n\n \/\/ Step 7: Define and run requantize_perchannel\n \/\/ --------------------------------------------\n \/\/ The output of requantization_range_op_per_channel which calculated the\n \/\/ new ranges of int8 is fed to the requantize per channel op.\n \/\/ Here the Values of Convolved T*W is converted from int32 to int8.\n\n TF_ASSERT_OK(NodeDefBuilder(\"requantize_per_channel\", \"RequantizePerChannel\")\n .Input(FakeInput(DT_QINT32))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"T\", DataTypeToEnum<qint32>::v())\n .Attr(\"out_type\", DataTypeToEnum<qint8>::v())\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n \/\/ Add the input Nodes to the Op.\n AddInputFromArray<qint32>(input_tensor_qint32.shape(),\n input_tensor_qint32.flat<qint32>());\n\n \/\/ Calculate the min and max from the ranges\n float ch1_min = -range_weights_ch1;\n float ch1_max = range_weights_ch1;\n float ch2_min = -range_weights_ch2;\n float ch2_max = range_weights_ch2;\n\n \/\/ Add the perchannel range nodes to the Op.\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_min, ch2_min});\n AddInputFromArray<float>(TensorShape({input_channels}), {ch1_max, ch2_max});\n\n \/\/ Calculate the min and max from Step 6 above\n \/\/ in RequantizationRangePerChannelTest_Basic\n float range_op_output_min = -14.8217;\n float range_op_output_max = 14.8217;\n\n \/\/ Add the requested_min and requested_max stored from Step 6.\n AddInputFromArray<float>(TensorShape({1}), {range_op_output_min});\n AddInputFromArray<float>(TensorShape({1}), {range_op_output_max});\n\n \/\/ Run the kernel\n TF_ASSERT_OK(RunOpKernel());\n\n \/\/ Verify the output with the expected output\n Tensor output = *GetOutput(0);\n const float output_min = GetOutput(1)->flat<float>()(0);\n const float output_max = GetOutput(2)->flat<float>()(0);\n EXPECT_NEAR(range_op_output_min, output_min, 0.002);\n EXPECT_NEAR(range_op_output_max, output_max, 0.002);\n}\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>#if defined(__GNUG__) && __GNUG__ < 3\n#define _XOPEN_SOURCE\n#endif\n\n#include \"datetime.h\"\n#include \"error.h\"\n\n#include <ctime>\n#include <cctype>\n\nnamespace ledger {\n\nstd::time_t now\t = std::time(NULL);\nint now_year = std::localtime(&now)->tm_year;\n\nstatic std::time_t base = -1;\nstatic int\t base_year = -1;\n\nstatic const int month_days[12] = {\n 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\n};\n\nstatic const char * formats[] = {\n \"%Y\/%m\/%d\",\n \"%m\/%d\",\n \"%Y.%m.%d\",\n \"%m.%d\",\n \"%Y-%m-%d\",\n \"%m-%d\",\n \"%a\",\n \"%A\",\n \"%b\",\n \"%B\",\n \"%Y\",\n NULL\n};\n\nstd::time_t interval_t::first(const std::time_t moment) const\n{\n std::time_t quant = begin;\n\n if (moment && std::difftime(moment, quant) > 0) {\n \/\/ Find an efficient starting point for the upcoming while loop.\n \/\/ We want a date early enough that the range will be correct, but\n \/\/ late enough that we don't spend hundreds of thousands of loops\n \/\/ skipping through time.\n\n struct std::tm * desc = std::gmtime(&moment);\n if (years)\n desc->tm_mon = 0;\n desc->tm_mday = 1;\n desc->tm_hour = 0;\n desc->tm_min = 0;\n desc->tm_sec = 0;\n quant = std::mktime(desc);\n\n std::time_t temp;\n while (std::difftime(moment, temp = increment(quant)) >= 0) {\n if (quant == temp)\n\tbreak;\n quant = temp;\n }\n }\n\n return quant;\n}\n\nstd::time_t interval_t::increment(const std::time_t moment) const\n{\n std::time_t then = moment;\n\n if (years || months) {\n struct std::tm * desc = std::gmtime(&then);\n\n if (years)\n desc->tm_year += years;\n\n if (months) {\n desc->tm_mon += months;\n\n if (desc->tm_mon > 11) {\n\tdesc->tm_year++;\n\tdesc->tm_mon -= 12;\n }\n else if (desc->tm_mon < 0) {\n\tdesc->tm_year--;\n\tdesc->tm_mon += 12;\n }\n }\n\n desc->tm_hour = 0;\n desc->tm_min = 0;\n desc->tm_sec = 0;\n\n then = std::mktime(desc);\n }\n\n return then + seconds;\n}\n\nstatic void parse_inclusion_specifier(const std::string& word,\n\t\t\t\t std::time_t *\t begin,\n\t\t\t\t std::time_t *\t end)\n{\n struct std::tm when;\n\n if (! parse_date_mask(word.c_str(), &when))\n throw interval_expr_error(std::string(\"Could not parse date mask: \") +\n\t\t\t word);\n\n when.tm_hour = 0;\n when.tm_min = 0;\n when.tm_sec = 0;\n\n bool saw_year = true;\n bool saw_mon = true;\n\n if (when.tm_year == -1) {\n when.tm_year = now_year;\n saw_year = false;\n }\n if (when.tm_mon == -1) {\n when.tm_mon = 0;\n saw_mon = false;\n } else {\n saw_year = false;\t\t\/\/ don't increment by year if month used\n }\n if (when.tm_mday == -1)\n when.tm_mday = 1;\n\n if (begin) {\n *begin = std::mktime(&when);\n if (end)\n *end = interval_t(0, saw_mon ? 1 : 0, saw_year ? 1 : 0).increment(*begin);\n }\n else if (end) {\n *end = std::mktime(&when);\n }\n}\n\nstatic inline\nvoid read_lower_word(std::istream& in, std::string& word) {\n in >> word;\n for (int i = 0, l = word.length(); i < l; i++)\n word[i] = std::tolower(word[i]);\n}\n\nstatic void parse_date_words(std::istream& in, std::string& word,\n\t\t\t std::time_t * begin, std::time_t * end)\n{\n std::string type;\n bool\t mon_spec = false;\n char\t buf[32];\n\n if (word == \"this\" || word == \"last\" || word == \"next\") {\n type = word;\n if (! in.eof())\n read_lower_word(in, word);\n else\n word = \"month\";\n } else {\n type = \"this\";\n }\n\n if (word == \"month\") {\n std::strftime(buf, 31, \"%B\", std::localtime(&now));\n word = buf;\n mon_spec = true;\n }\n else if (word == \"year\") {\n std::strftime(buf, 31, \"%Y\", std::localtime(&now));\n word = buf;\n }\n\n parse_inclusion_specifier(word, begin, end);\n\n if (type == \"last\") {\n if (mon_spec) {\n if (begin)\n\t*begin = interval_t(0, -1, 0).increment(*begin);\n if (end)\n\t*end = interval_t(0, -1, 0).increment(*end);\n } else {\n if (begin)\n\t*begin = interval_t(0, 0, -1).increment(*begin);\n if (end)\n\t*end = interval_t(0, 0, -1).increment(*end);\n }\n }\n else if (type == \"next\") {\n if (mon_spec) {\n if (begin)\n\t*begin = interval_t(0, 1, 0).increment(*begin);\n if (end)\n\t*end = interval_t(0, 1, 0).increment(*end);\n } else {\n if (begin)\n\t*begin = interval_t(0, 0, 1).increment(*begin);\n if (end)\n\t*end = interval_t(0, 0, 1).increment(*end);\n }\n }\n}\n\nvoid interval_t::parse(std::istream& in)\n{\n std::string word;\n\n while (! in.eof()) {\n read_lower_word(in, word);\n if (word == \"every\") {\n read_lower_word(in, word);\n if (std::isdigit(word[0])) {\n\tint quantity = std::atol(word.c_str());\n\tread_lower_word(in, word);\n\tif (word == \"days\")\n\t seconds = 86400 * quantity;\n\telse if (word == \"weeks\")\n\t seconds = 7 * 86400 * quantity;\n\telse if (word == \"months\")\n\t months = quantity;\n\telse if (word == \"quarters\")\n\t months = 3 * quantity;\n\telse if (word == \"years\")\n\t years = quantity;\n }\n else if (word == \"day\")\n\tseconds = 86400;\n else if (word == \"week\")\n\tseconds = 7 * 86400;\n else if (word == \"monthly\")\n\tmonths = 1;\n else if (word == \"quarter\")\n\tmonths = 3;\n else if (word == \"year\")\n\tyears = 1;\n }\n else if (word == \"daily\")\n seconds = 86400;\n else if (word == \"weekly\")\n seconds = 7 * 86400;\n else if (word == \"biweekly\")\n seconds = 14 * 86400;\n else if (word == \"monthly\")\n months = 1;\n else if (word == \"bimonthly\")\n months = 2;\n else if (word == \"quarterly\")\n months = 3;\n else if (word == \"yearly\")\n years = 1;\n else if (word == \"this\" || word == \"last\" || word == \"next\") {\n parse_date_words(in, word, &begin, &end);\n }\n else if (word == \"in\") {\n read_lower_word(in, word);\n parse_date_words(in, word, &begin, &end);\n }\n else if (word == \"from\" || word == \"since\") {\n read_lower_word(in, word);\n parse_date_words(in, word, &begin, NULL);\n }\n else if (word == \"to\" || word == \"until\") {\n read_lower_word(in, word);\n parse_date_words(in, word, NULL, &end);\n }\n else {\n parse_inclusion_specifier(word, &begin, &end);\n }\n }\n}\n\nbool parse_date_mask(const char * date_str, struct std::tm * result)\n{\n for (const char ** f = formats; *f; f++) {\n memset(result, INT_MAX, sizeof(struct std::tm));\n if (strptime(date_str, *f, result))\n return true;\n }\n return false;\n}\n\nbool parse_date(const char * date_str, std::time_t * result, const int year)\n{\n struct std::tm when;\n\n if (! parse_date_mask(date_str, &when))\n return false;\n\n when.tm_hour = 0;\n when.tm_min = 0;\n when.tm_sec = 0;\n\n if (when.tm_year == -1)\n when.tm_year = ((year == -1) ? now_year : (year - 1900));\n\n if (when.tm_mon == -1)\n when.tm_mon = 0;\n\n if (when.tm_mday == -1)\n when.tm_mday = 1;\n\n *result = std::mktime(&when);\n\n return true;\n}\n\nbool quick_parse_date(const char * date_str, std::time_t * result)\n{\n int year = -1, month = -1, day, num = 0;\n\n for (const char * p = date_str; *p; p++) {\n if (*p == '\/' || *p == '-' || *p == '.') {\n if (year == -1)\n\tyear = num;\n else\n\tmonth = num;\n num = 0;\n }\n else if (*p < '0' || *p > '9') {\n return false;\n }\n else {\n num *= 10;\n num += *p - '0';\n }\n }\n\n day = num;\n\n if (month == -1) {\n month = year;\n year = now_year + 1900;\n }\n\n if (base == -1 || year != base_year) {\n struct std::tm when;\n std::memset(&when, 0, sizeof(when));\n\n base_year = year == -1 ? now_year + 1900 : year;\n when.tm_year = year == -1 ? now_year : year - 1900;\n when.tm_mday = 1;\n\n base = std::mktime(&when);\n year = base_year;\n }\n\n *result = base;\n\n --month;\n while (--month >= 0) {\n *result += month_days[month] * 24 * 60 * 60;\n if (month == 1 && year % 4 == 0 && year != 2000) \/\/ february in leap years\n *result += 24 * 60 * 60;\n }\n\n if (--day)\n *result += day * 24 * 60 * 60;\n\n return true;\n}\n\n} \/\/ namespace ledger\n\n#ifdef USE_BOOST_PYTHON\n\n#include <boost\/python.hpp>\n\nusing namespace boost::python;\nusing namespace ledger;\n\nunsigned int interval_len(interval_t& interval)\n{\n int periods = 1;\n std::time_t when = interval.first();\n while (interval.end && when < interval.end) {\n when = interval.increment(when);\n if (when < interval.end)\n periods++;\n }\n return periods;\n}\n\nstd::time_t interval_getitem(interval_t& interval, int i)\n{\n static std::time_t last_index = 0;\n static std::time_t last_moment = 0;\n\n if (i == 0) {\n last_index = 0;\n last_moment = interval.first();\n }\n else {\n last_moment = interval.increment(last_moment);\n if (interval.end && last_moment >= interval.end) {\n PyErr_SetString(PyExc_IndexError, \"Index out of range\");\n throw_error_already_set();\n }\n }\n return last_moment;\n}\n\nvoid export_datetime()\n{\n class_< interval_t >\n (\"Interval\", init<optional<int, int, int, std::time_t, std::time_t> >())\n .def(init<std::string>())\n .def(! self)\n\n .def_readwrite(\"years\", &interval_t::years)\n .def_readwrite(\"months\", &interval_t::months)\n .def_readwrite(\"seconds\", &interval_t::seconds)\n .def_readwrite(\"begin\", &interval_t::begin)\n .def_readwrite(\"end\", &interval_t::end)\n\n .def(\"__len__\", interval_len)\n .def(\"__getitem__\", interval_getitem)\n\n .def(\"increment\", &interval_t::increment)\n ;\n}\n\n#endif \/\/ USE_BOOST_PYTHON\n<commit_msg>(export_datetime): Exposed \"parse_date\" function.<commit_after>#if defined(__GNUG__) && __GNUG__ < 3\n#define _XOPEN_SOURCE\n#endif\n\n#include \"datetime.h\"\n#include \"error.h\"\n\n#include <ctime>\n#include <cctype>\n\nnamespace ledger {\n\nstd::time_t now\t = std::time(NULL);\nint now_year = std::localtime(&now)->tm_year;\n\nstatic std::time_t base = -1;\nstatic int\t base_year = -1;\n\nstatic const int month_days[12] = {\n 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\n};\n\nstatic const char * formats[] = {\n \"%Y\/%m\/%d\",\n \"%m\/%d\",\n \"%Y.%m.%d\",\n \"%m.%d\",\n \"%Y-%m-%d\",\n \"%m-%d\",\n \"%a\",\n \"%A\",\n \"%b\",\n \"%B\",\n \"%Y\",\n NULL\n};\n\nstd::time_t interval_t::first(const std::time_t moment) const\n{\n std::time_t quant = begin;\n\n if (moment && std::difftime(moment, quant) > 0) {\n \/\/ Find an efficient starting point for the upcoming while loop.\n \/\/ We want a date early enough that the range will be correct, but\n \/\/ late enough that we don't spend hundreds of thousands of loops\n \/\/ skipping through time.\n\n struct std::tm * desc = std::gmtime(&moment);\n if (years)\n desc->tm_mon = 0;\n desc->tm_mday = 1;\n desc->tm_hour = 0;\n desc->tm_min = 0;\n desc->tm_sec = 0;\n quant = std::mktime(desc);\n\n std::time_t temp;\n while (std::difftime(moment, temp = increment(quant)) >= 0) {\n if (quant == temp)\n\tbreak;\n quant = temp;\n }\n }\n\n return quant;\n}\n\nstd::time_t interval_t::increment(const std::time_t moment) const\n{\n std::time_t then = moment;\n\n if (years || months) {\n struct std::tm * desc = std::gmtime(&then);\n\n if (years)\n desc->tm_year += years;\n\n if (months) {\n desc->tm_mon += months;\n\n if (desc->tm_mon > 11) {\n\tdesc->tm_year++;\n\tdesc->tm_mon -= 12;\n }\n else if (desc->tm_mon < 0) {\n\tdesc->tm_year--;\n\tdesc->tm_mon += 12;\n }\n }\n\n desc->tm_hour = 0;\n desc->tm_min = 0;\n desc->tm_sec = 0;\n\n then = std::mktime(desc);\n }\n\n return then + seconds;\n}\n\nstatic void parse_inclusion_specifier(const std::string& word,\n\t\t\t\t std::time_t *\t begin,\n\t\t\t\t std::time_t *\t end)\n{\n struct std::tm when;\n\n if (! parse_date_mask(word.c_str(), &when))\n throw interval_expr_error(std::string(\"Could not parse date mask: \") +\n\t\t\t word);\n\n when.tm_hour = 0;\n when.tm_min = 0;\n when.tm_sec = 0;\n\n bool saw_year = true;\n bool saw_mon = true;\n\n if (when.tm_year == -1) {\n when.tm_year = now_year;\n saw_year = false;\n }\n if (when.tm_mon == -1) {\n when.tm_mon = 0;\n saw_mon = false;\n } else {\n saw_year = false;\t\t\/\/ don't increment by year if month used\n }\n if (when.tm_mday == -1)\n when.tm_mday = 1;\n\n if (begin) {\n *begin = std::mktime(&when);\n if (end)\n *end = interval_t(0, saw_mon ? 1 : 0, saw_year ? 1 : 0).increment(*begin);\n }\n else if (end) {\n *end = std::mktime(&when);\n }\n}\n\nstatic inline\nvoid read_lower_word(std::istream& in, std::string& word) {\n in >> word;\n for (int i = 0, l = word.length(); i < l; i++)\n word[i] = std::tolower(word[i]);\n}\n\nstatic void parse_date_words(std::istream& in, std::string& word,\n\t\t\t std::time_t * begin, std::time_t * end)\n{\n std::string type;\n bool\t mon_spec = false;\n char\t buf[32];\n\n if (word == \"this\" || word == \"last\" || word == \"next\") {\n type = word;\n if (! in.eof())\n read_lower_word(in, word);\n else\n word = \"month\";\n } else {\n type = \"this\";\n }\n\n if (word == \"month\") {\n std::strftime(buf, 31, \"%B\", std::localtime(&now));\n word = buf;\n mon_spec = true;\n }\n else if (word == \"year\") {\n std::strftime(buf, 31, \"%Y\", std::localtime(&now));\n word = buf;\n }\n\n parse_inclusion_specifier(word, begin, end);\n\n if (type == \"last\") {\n if (mon_spec) {\n if (begin)\n\t*begin = interval_t(0, -1, 0).increment(*begin);\n if (end)\n\t*end = interval_t(0, -1, 0).increment(*end);\n } else {\n if (begin)\n\t*begin = interval_t(0, 0, -1).increment(*begin);\n if (end)\n\t*end = interval_t(0, 0, -1).increment(*end);\n }\n }\n else if (type == \"next\") {\n if (mon_spec) {\n if (begin)\n\t*begin = interval_t(0, 1, 0).increment(*begin);\n if (end)\n\t*end = interval_t(0, 1, 0).increment(*end);\n } else {\n if (begin)\n\t*begin = interval_t(0, 0, 1).increment(*begin);\n if (end)\n\t*end = interval_t(0, 0, 1).increment(*end);\n }\n }\n}\n\nvoid interval_t::parse(std::istream& in)\n{\n std::string word;\n\n while (! in.eof()) {\n read_lower_word(in, word);\n if (word == \"every\") {\n read_lower_word(in, word);\n if (std::isdigit(word[0])) {\n\tint quantity = std::atol(word.c_str());\n\tread_lower_word(in, word);\n\tif (word == \"days\")\n\t seconds = 86400 * quantity;\n\telse if (word == \"weeks\")\n\t seconds = 7 * 86400 * quantity;\n\telse if (word == \"months\")\n\t months = quantity;\n\telse if (word == \"quarters\")\n\t months = 3 * quantity;\n\telse if (word == \"years\")\n\t years = quantity;\n }\n else if (word == \"day\")\n\tseconds = 86400;\n else if (word == \"week\")\n\tseconds = 7 * 86400;\n else if (word == \"monthly\")\n\tmonths = 1;\n else if (word == \"quarter\")\n\tmonths = 3;\n else if (word == \"year\")\n\tyears = 1;\n }\n else if (word == \"daily\")\n seconds = 86400;\n else if (word == \"weekly\")\n seconds = 7 * 86400;\n else if (word == \"biweekly\")\n seconds = 14 * 86400;\n else if (word == \"monthly\")\n months = 1;\n else if (word == \"bimonthly\")\n months = 2;\n else if (word == \"quarterly\")\n months = 3;\n else if (word == \"yearly\")\n years = 1;\n else if (word == \"this\" || word == \"last\" || word == \"next\") {\n parse_date_words(in, word, &begin, &end);\n }\n else if (word == \"in\") {\n read_lower_word(in, word);\n parse_date_words(in, word, &begin, &end);\n }\n else if (word == \"from\" || word == \"since\") {\n read_lower_word(in, word);\n parse_date_words(in, word, &begin, NULL);\n }\n else if (word == \"to\" || word == \"until\") {\n read_lower_word(in, word);\n parse_date_words(in, word, NULL, &end);\n }\n else {\n parse_inclusion_specifier(word, &begin, &end);\n }\n }\n}\n\nbool parse_date_mask(const char * date_str, struct std::tm * result)\n{\n for (const char ** f = formats; *f; f++) {\n memset(result, INT_MAX, sizeof(struct std::tm));\n if (strptime(date_str, *f, result))\n return true;\n }\n return false;\n}\n\nbool parse_date(const char * date_str, std::time_t * result, const int year)\n{\n struct std::tm when;\n\n if (! parse_date_mask(date_str, &when))\n return false;\n\n when.tm_hour = 0;\n when.tm_min = 0;\n when.tm_sec = 0;\n\n if (when.tm_year == -1)\n when.tm_year = ((year == -1) ? now_year : (year - 1900));\n\n if (when.tm_mon == -1)\n when.tm_mon = 0;\n\n if (when.tm_mday == -1)\n when.tm_mday = 1;\n\n *result = std::mktime(&when);\n\n return true;\n}\n\nbool quick_parse_date(const char * date_str, std::time_t * result)\n{\n int year = -1, month = -1, day, num = 0;\n\n for (const char * p = date_str; *p; p++) {\n if (*p == '\/' || *p == '-' || *p == '.') {\n if (year == -1)\n\tyear = num;\n else\n\tmonth = num;\n num = 0;\n }\n else if (*p < '0' || *p > '9') {\n return false;\n }\n else {\n num *= 10;\n num += *p - '0';\n }\n }\n\n day = num;\n\n if (month == -1) {\n month = year;\n year = now_year + 1900;\n }\n\n if (base == -1 || year != base_year) {\n struct std::tm when;\n std::memset(&when, 0, sizeof(when));\n\n base_year = year == -1 ? now_year + 1900 : year;\n when.tm_year = year == -1 ? now_year : year - 1900;\n when.tm_mday = 1;\n\n base = std::mktime(&when);\n year = base_year;\n }\n\n *result = base;\n\n --month;\n while (--month >= 0) {\n *result += month_days[month] * 24 * 60 * 60;\n if (month == 1 && year % 4 == 0 && year != 2000) \/\/ february in leap years\n *result += 24 * 60 * 60;\n }\n\n if (--day)\n *result += day * 24 * 60 * 60;\n\n return true;\n}\n\n} \/\/ namespace ledger\n\n#ifdef USE_BOOST_PYTHON\n\n#include <boost\/python.hpp>\n\nusing namespace boost::python;\nusing namespace ledger;\n\nunsigned int interval_len(interval_t& interval)\n{\n int periods = 1;\n std::time_t when = interval.first();\n while (interval.end && when < interval.end) {\n when = interval.increment(when);\n if (when < interval.end)\n periods++;\n }\n return periods;\n}\n\nstd::time_t interval_getitem(interval_t& interval, int i)\n{\n static std::time_t last_index = 0;\n static std::time_t last_moment = 0;\n\n if (i == 0) {\n last_index = 0;\n last_moment = interval.first();\n }\n else {\n last_moment = interval.increment(last_moment);\n if (interval.end && last_moment >= interval.end) {\n PyErr_SetString(PyExc_IndexError, \"Index out of range\");\n throw_error_already_set();\n }\n }\n return last_moment;\n}\n\nstd::time_t py_parse_date(const char * date_str)\n{\n std::time_t temp;\n if (parse_date(date_str, &temp))\n return temp;\n return 0;\n}\n\nstd::time_t py_parse_date_yr(const char * date_str, const int year)\n{\n std::time_t temp;\n if (parse_date(date_str, &temp, year))\n return temp;\n return 0;\n}\n\nvoid export_datetime()\n{\n class_< interval_t >\n (\"Interval\", init<optional<int, int, int, std::time_t, std::time_t> >())\n .def(init<std::string>())\n .def(! self)\n\n .def_readwrite(\"years\", &interval_t::years)\n .def_readwrite(\"months\", &interval_t::months)\n .def_readwrite(\"seconds\", &interval_t::seconds)\n .def_readwrite(\"begin\", &interval_t::begin)\n .def_readwrite(\"end\", &interval_t::end)\n\n .def(\"__len__\", interval_len)\n .def(\"__getitem__\", interval_getitem)\n\n .def(\"increment\", &interval_t::increment)\n ;\n\n def(\"parse_date\", py_parse_date);\n def(\"parse_date\", py_parse_date_yr);\n}\n\n#endif \/\/ USE_BOOST_PYTHON\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * TessuMod: Mod for integrating TeamSpeak into World of Tanks\r\n * Copyright (C) 2015 Janne Hakonen\r\n *\r\n * This library is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\r\n * USA\r\n *\/\r\n\r\n#include \"settingsstorage.h\"\r\n#include \"..\/entities\/settings.h\"\r\n#include \"..\/interfaces\/drivers.h\"\r\n\r\nnamespace Storage\r\n{\r\n\r\nSettingsStorage::SettingsStorage( Interfaces::SettingsDriver *driver, QObject *parent )\r\n\t: QObject( parent ), driver( driver )\r\n{\r\n}\r\n\r\nEntity::Settings SettingsStorage::get() const\r\n{\r\n\tEntity::Settings settings;\r\n\tsettings.audioBackend = (Entity::AudioBackend) driver->get( \"General\", \"AudioBackend\", (int)Entity::OpenALBackend ).toInt();\r\n\tsettings.positioningEnabled = driver->get( \"General\", \"PositionalAudioEnabled\", true ).toBool();\r\n\tsettings.testRotateMode = (Entity::RotateMode) driver->get( \"General\", \"TestRotateMode\", Entity::RotateYAxis ).toInt();\r\n\tsettings.hrtfEnabled = driver->get( \"General\", \"HrtfEnabled\", false ).toBool();\r\n\tsettings.hrtfDataSet = driver->get( \"General\", \"HrtfDataSet\", \"MIT_KEMAR\" ).toString();\r\n\tsettings.audioLoggingEnabled = driver->get( \"General\", \"AudioLoggingEnabled\", false ).toBool();\r\n\treturn settings;\r\n}\r\n\r\nvoid SettingsStorage::set( const Entity::Settings &settings )\r\n{\r\n\tdriver->set( \"General\", \"AudioBackend\", (int)settings.audioBackend );\r\n\tdriver->set( \"General\", \"PositionalAudioEnabled\", settings.positioningEnabled );\r\n\tdriver->set( \"General\", \"TestRotateMode\", (int)settings.testRotateMode );\r\n\tdriver->set( \"General\", \"HrtfEnabled\", settings.hrtfEnabled );\r\n\tdriver->set( \"General\", \"HrtfDataSet\", settings.hrtfDataSet );\r\n\tdriver->set( \"General\", \"AudioLoggingEnabled\", settings.audioLoggingEnabled );\r\n}\r\n\r\n}\r\n<commit_msg>Issue #3: Fixed default HRTF not set correctly.<commit_after>\/*\r\n * TessuMod: Mod for integrating TeamSpeak into World of Tanks\r\n * Copyright (C) 2015 Janne Hakonen\r\n *\r\n * This library is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\r\n * USA\r\n *\/\r\n\r\n#include \"settingsstorage.h\"\r\n#include \"..\/entities\/settings.h\"\r\n#include \"..\/interfaces\/drivers.h\"\r\n\r\nnamespace Storage\r\n{\r\n\r\nSettingsStorage::SettingsStorage( Interfaces::SettingsDriver *driver, QObject *parent )\r\n\t: QObject( parent ), driver( driver )\r\n{\r\n}\r\n\r\nEntity::Settings SettingsStorage::get() const\r\n{\r\n\tEntity::Settings settings;\r\n\tsettings.audioBackend = (Entity::AudioBackend) driver->get( \"General\", \"AudioBackend\", (int)Entity::OpenALBackend ).toInt();\r\n\tsettings.positioningEnabled = driver->get( \"General\", \"PositionalAudioEnabled\", true ).toBool();\r\n\tsettings.testRotateMode = (Entity::RotateMode) driver->get( \"General\", \"TestRotateMode\", Entity::RotateYAxis ).toInt();\r\n\tsettings.hrtfEnabled = driver->get( \"General\", \"HrtfEnabled\", false ).toBool();\r\n\tsettings.hrtfDataSet = driver->get( \"General\", \"HrtfDataSet\", \":\/etc\/hrtfs\/mit_kemar-44100.mhr\" ).toString();\r\n\tsettings.audioLoggingEnabled = driver->get( \"General\", \"AudioLoggingEnabled\", false ).toBool();\r\n\treturn settings;\r\n}\r\n\r\nvoid SettingsStorage::set( const Entity::Settings &settings )\r\n{\r\n\tdriver->set( \"General\", \"AudioBackend\", (int)settings.audioBackend );\r\n\tdriver->set( \"General\", \"PositionalAudioEnabled\", settings.positioningEnabled );\r\n\tdriver->set( \"General\", \"TestRotateMode\", (int)settings.testRotateMode );\r\n\tdriver->set( \"General\", \"HrtfEnabled\", settings.hrtfEnabled );\r\n\tdriver->set( \"General\", \"HrtfDataSet\", settings.hrtfDataSet );\r\n\tdriver->set( \"General\", \"AudioLoggingEnabled\", settings.audioLoggingEnabled );\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_ASSEMBLER_TMP_STORAGE_HH\n#define DUNE_GDT_ASSEMBLER_TMP_STORAGE_HH\n\n#include <vector>\n\n#include <dune\/stuff\/common\/disable_warnings.hh>\n# include <dune\/common\/dynmatrix.hh>\n#include <dune\/stuff\/common\/reenable_warnings.hh>\n#include <dune\/common\/dynvector.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace TmpStorageProvider {\n\n\ntemplate< class FieldType = double >\nclass Matrices\n{\n static size_t safely_get(const std::vector< size_t >& vec, const size_t ii)\n {\n assert(ii < vec.size());\n return vec[ii];\n } \/\/ ... safely_get(...)\n\npublic:\n typedef DynamicMatrix< FieldType > LocalMatrixType;\n\n Matrices(const std::vector< size_t >& num_tmp_objects,\n const size_t max_rows,\n const size_t max_cols)\n : matrices_({ std::vector< LocalMatrixType >(safely_get(num_tmp_objects, 0),\n LocalMatrixType(max_rows, max_cols, FieldType(0)))\n , std::vector< LocalMatrixType >(safely_get(num_tmp_objects, 1),\n LocalMatrixType(max_rows, max_cols, FieldType(0))) })\n , indices_(4, Dune::DynamicVector< size_t >(std::max(max_rows, max_cols)))\n {}\n\n virtual ~Matrices() {}\n\n std::vector< std::vector< LocalMatrixType > >& matrices()\n {\n return matrices_;\n }\n\n std::vector< Dune::DynamicVector< size_t > >& indices()\n {\n return indices_;\n }\n\nprotected:\n std::vector< std::vector< LocalMatrixType > > matrices_;\n std::vector< DynamicVector< size_t > > indices_;\n}; \/\/ class Matrices\n\n\ntemplate< class FieldType = double >\nclass Vectors\n{\n static size_t safely_get(const std::vector< size_t >& vec, const size_t ii)\n {\n assert(ii < vec.size());\n return vec[ii];\n } \/\/ ... safely_get(...)\n\npublic:\n typedef DynamicVector< FieldType > LocalVectorType;\n\n Vectors(const std::vector< size_t >& num_tmp_objects,\n const size_t max_size)\n : vectors_({ std::vector< LocalVectorType >(safely_get(num_tmp_objects, 0),\n LocalVectorType(max_size, FieldType(0)))\n , std::vector< LocalVectorType >(safely_get(num_tmp_objects, 1),\n LocalVectorType(max_size, FieldType(0))) })\n , indices_(max_size)\n {}\n\n virtual ~Vectors() {}\n\n std::vector< std::vector< LocalVectorType > >& vectors()\n {\n return vectors_;\n }\n\n Dune::DynamicVector< size_t >& indices()\n {\n return indices_;\n }\n\nprotected:\n std::vector< std::vector< LocalVectorType > > vectors_;\n Dune::DynamicVector< size_t > indices_;\n}; \/\/ class Vectors\n\n\n} \/\/ namespace TmpStorageProvider\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_ASSEMBLER_TMP_STORAGE_HH\n<commit_msg>[assembler] thread safe tmp storage<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_ASSEMBLER_TMP_STORAGE_HH\n#define DUNE_GDT_ASSEMBLER_TMP_STORAGE_HH\n\n#include <vector>\n\n#include <dune\/stuff\/common\/disable_warnings.hh>\n# include <dune\/common\/dynmatrix.hh>\n#include <dune\/stuff\/common\/reenable_warnings.hh>\n#include <dune\/common\/dynvector.hh>\n#include <dune\/stuff\/common\/parallel\/threadmanager.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace TmpStorageProvider {\n\n\ntemplate< class FieldType = double >\nclass Matrices\n{\npublic:\n typedef DynamicMatrix< FieldType > LocalMatrixType;\nprotected:\n typedef std::vector< std::vector< LocalMatrixType > > LocalMatrixContainerType;\n\npublic:\n\n Matrices(const std::vector< size_t >& num_tmp_objects,\n const size_t max_rows,\n const size_t max_cols)\n : matrices_(LocalMatrixContainerType({std::vector< LocalMatrixType >(num_tmp_objects.at(0),\n LocalMatrixType(max_rows, max_cols, FieldType(0)))\n , std::vector< LocalMatrixType >(num_tmp_objects.at(1),\n LocalMatrixType(max_rows, max_cols, FieldType(0))) } ))\n , indices_(4, Dune::DynamicVector< size_t >(std::max(max_rows, max_cols)))\n {}\n\n virtual ~Matrices() {}\n\n std::vector< std::vector< LocalMatrixType > >& matrices()\n {\n return *matrices_;\n }\n\n std::vector< Dune::DynamicVector< size_t > >& indices()\n {\n return *indices_;\n }\n\nprotected:\n DS::PerThreadValue< LocalMatrixContainerType > matrices_;\n DS::PerThreadValue< std::vector< DynamicVector< size_t > > > indices_;\n}; \/\/ class Matrices\n\n\ntemplate< class FieldType = double >\nclass Vectors\n{\npublic:\n typedef DynamicVector< FieldType > LocalVectorType;\nprotected:\n typedef std::vector< std::vector< LocalVectorType > > LocalVectorContainerType;\n\n Vectors(const std::vector< size_t >& num_tmp_objects,\n const size_t max_size)\n : vectors_(LocalVectorContainerType({ std::vector< LocalVectorType >(num_tmp_objects.at(0),\n LocalVectorType(max_size, FieldType(0)))\n , std::vector< LocalVectorType >(num_tmp_objects.at(1),\n LocalVectorType(max_size, FieldType(0))) } ))\n , indices_(max_size)\n {}\n\n virtual ~Vectors() {}\n\n std::vector< std::vector< LocalVectorType > >& vectors()\n {\n return *vectors_;\n }\n\n Dune::DynamicVector< size_t >& indices()\n {\n return *indices_;\n }\n\nprotected:\n DS::PerThreadValue< std::vector< std::vector< LocalVectorType > > > vectors_;\n DS::PerThreadValue< Dune::DynamicVector< size_t > > indices_;\n}; \/\/ class Vectors\n\n\n} \/\/ namespace TmpStorageProvider\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_ASSEMBLER_TMP_STORAGE_HH\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH\n#define DUNE_STUFF_FUNCTION_EXPRESSION_HH\n\n#include <sstream>\n#include <vector>\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/common\/exceptions.hh>\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/common\/color.hh>\n\n#include \"expression\/base.hh\"\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >\nclass FunctionExpression\n : public FunctionExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >\n , public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 >\n{\n typedef FunctionExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType;\n typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > InterfaceType;\npublic:\n typedef FunctionExpression< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;\n\n typedef typename InterfaceType::DomainFieldType DomainFieldType;\n static const int dimDomain = InterfaceType::dimDomain;\n typedef typename InterfaceType::DomainType DomainType;\n typedef typename InterfaceType::RangeFieldType RangeFieldType;\n static const int dimRange = InterfaceType::dimRange;\n typedef typename InterfaceType::RangeType RangeType;\n\n static const std::string id()\n {\n return InterfaceType::id() + \".expression\";\n }\n\n FunctionExpression(const std::string _variable,\n const std::string _expression,\n const int _order = -1,\n const std::string _name = id())\n : BaseType(_variable, _expression)\n , order_(_order)\n , name_(_name)\n {}\n\n FunctionExpression(const std::string _variable,\n const std::vector< std::string > _expressions,\n const int _order = -1,\n const std::string _name = id())\n : BaseType(_variable, _expressions)\n , order_(_order)\n , name_(_name)\n {}\n\n static Dune::ParameterTree createSampleDescription(const std::string subName = \"\")\n {\n Dune::ParameterTree description;\n description[\"variable\"] = \"x\";\n description[\"expression\"] = \"[x[0]; sin(x[0])]\";\n description[\"order\"] = \"1\";\n description[\"name\"] = \"function.expression\";\n if (subName.empty())\n return description;\n else {\n Dune::Stuff::Common::ExtendedParameterTree extendedDescription;\n extendedDescription.add(description, subName);\n return extendedDescription;\n }\n } \/\/ ... createSampleDescription(...)\n\n static ThisType* create(const DSC::ExtendedParameterTree description)\n {\n \/\/ get necessary\n const std::string _variable = description.get< std::string >(\"variable\", \"x\");\n std::vector< std::string > _expressions;\n \/\/ lets see, if there is a key or vector\n if (description.hasVector(\"expression\")) {\n const std::vector< std::string > expr = description.getVector< std::string >(\"expression\", 1);\n for (size_t ii = 0; ii < expr.size(); ++ii)\n _expressions.push_back(expr[ii]);\n } else if (description.hasKey(\"expression\")) {\n const std::string expr = description.get< std::string >(\"expression\");\n _expressions.push_back(expr);\n } else\n DUNE_THROW(Dune::IOError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" neither key nor vector 'expression' found in the following description:\\n\"\n << description.reportString(\" \"));\n \/\/ get optional\n const int _order = description.get< int >(\"order\", -1);\n const std::string _name = description.get< std::string >(\"name\", \"function.expression\");\n \/\/ create and return\n return new ThisType(_variable, _expressions, _order, _name);\n } \/\/ ... create(...)\n\n virtual int order() const\n {\n return order_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n virtual void evaluate(const DomainType& _x, RangeType& _ret) const\n {\n BaseType::evaluate(_x, _ret);\n }\n\nprivate:\n int order_;\n std::string name_;\n}; \/\/ class FunctionExpression\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_EXPRESSION_HH\n<commit_msg>[function.expression] added localFunction<commit_after>#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH\n#define DUNE_STUFF_FUNCTION_EXPRESSION_HH\n\n#include <sstream>\n#include <vector>\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/common\/exceptions.hh>\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/common\/color.hh>\n\n#include \"expression\/base.hh\"\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >\nclass FunctionExpression\n : public FunctionExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >\n , public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 >\n{\n typedef FunctionExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType;\n typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > InterfaceType;\npublic:\n typedef FunctionExpression< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;\n\n typedef typename InterfaceType::DomainFieldType DomainFieldType;\n static const int dimDomain = InterfaceType::dimDomain;\n typedef typename InterfaceType::DomainType DomainType;\n typedef typename InterfaceType::RangeFieldType RangeFieldType;\n static const int dimRange = InterfaceType::dimRange;\n typedef typename InterfaceType::RangeType RangeType;\n\n static const std::string id()\n {\n return InterfaceType::id() + \".expression\";\n }\n\n FunctionExpression(const std::string _variable,\n const std::string _expression,\n const int _order = -1,\n const std::string _name = id())\n : BaseType(_variable, _expression)\n , order_(_order)\n , name_(_name)\n {}\n\n FunctionExpression(const std::string _variable,\n const std::vector< std::string > _expressions,\n const int _order = -1,\n const std::string _name = id())\n : BaseType(_variable, _expressions)\n , order_(_order)\n , name_(_name)\n {}\n\n static Dune::ParameterTree createSampleDescription(const std::string subName = \"\")\n {\n Dune::ParameterTree description;\n description[\"variable\"] = \"x\";\n description[\"expression\"] = \"[x[0]; sin(x[0])]\";\n description[\"order\"] = \"1\";\n description[\"name\"] = \"function.expression\";\n if (subName.empty())\n return description;\n else {\n Dune::Stuff::Common::ExtendedParameterTree extendedDescription;\n extendedDescription.add(description, subName);\n return extendedDescription;\n }\n } \/\/ ... createSampleDescription(...)\n\n static ThisType* create(const DSC::ExtendedParameterTree description)\n {\n \/\/ get necessary\n const std::string _variable = description.get< std::string >(\"variable\", \"x\");\n std::vector< std::string > _expressions;\n \/\/ lets see, if there is a key or vector\n if (description.hasVector(\"expression\")) {\n const std::vector< std::string > expr = description.getVector< std::string >(\"expression\", 1);\n for (size_t ii = 0; ii < expr.size(); ++ii)\n _expressions.push_back(expr[ii]);\n } else if (description.hasKey(\"expression\")) {\n const std::string expr = description.get< std::string >(\"expression\");\n _expressions.push_back(expr);\n } else\n DUNE_THROW(Dune::IOError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" neither key nor vector 'expression' found in the following description:\\n\"\n << description.reportString(\" \"));\n \/\/ get optional\n const int _order = description.get< int >(\"order\", -1);\n const std::string _name = description.get< std::string >(\"name\", \"function.expression\");\n \/\/ create and return\n return new ThisType(_variable, _expressions, _order, _name);\n } \/\/ ... create(...)\n\n virtual int order() const\n {\n return order_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n virtual void evaluate(const DomainType& _x, RangeType& _ret) const\n {\n BaseType::evaluate(_x, _ret);\n }\n\n using InterfaceType::localFunction;\n\nprivate:\n int order_;\n std::string name_;\n}; \/\/ class FunctionExpression\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_EXPRESSION_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include \"test_common.hh\"\n\n#include <unordered_map>\n#include <dune\/common\/mpihelper.hh>\n#include <dune\/common\/parametertreeparser.hh>\n\n#include <dune\/stuff\/grid\/provider\/cube.hh>\n\n#include <dune\/stuff\/functions\/expression.hh>\n#include <dune\/stuff\/common\/profiler.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/functions\/femadapter.hh>\n#include <dune\/stuff\/functions\/norm.hh>\n#include <dune\/stuff\/functions\/global.hh>\n#include <dune\/stuff\/functions\/pdelabadapter.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n#include <dune\/stuff\/aliases.hh>\n\n#if HAVE_DUNE_FEM\n# include <dune\/fem\/gridpart\/adaptiveleafgridpart.hh>\n# include <dune\/fem\/function\/adaptivefunction\/adaptivefunction.hh>\n# include <dune\/fem\/space\/common\/functionspace.hh>\n# include <dune\/fem\/space\/lagrange.hh>\n# include <dune\/fem\/io\/file\/vtkio.hh>\n# include <dune\/fem\/operator\/lagrangeinterpolation.hh>\n#endif \/\/ HAVE_DUNE_FEM\n\n\/\/#define HAVE_DUNE_PDELAB 1\n#if HAVE_DUNE_PDELAB\n# include <dune\/pdelab\/common\/function.hh>\n# include <dune\/pdelab\/gridfunctionspace\/gridfunctionspace.hh>\n# include <dune\/pdelab\/backend\/istl\/descriptors.hh>\n# include <dune\/pdelab\/backend\/istl\/bcrsmatrixbackend.hh>\n# include <dune\/pdelab\/finiteelementmap\/qkfem.hh>\n# include <dune\/pdelab\/backend\/istlvectorbackend.hh>\n# include <dune\/pdelab\/backend\/backendselector.hh>\n# include <dune\/pdelab\/constraints\/conforming.hh>\n# include <dune\/pdelab\/gridfunctionspace\/interpolate.hh>\n#endif\nusing namespace Dune;\n\nstatic const int dim = 2;\ntypedef testing::Types< Dune::YaspGrid< dim >\n#if HAVE_ALUGRID\n , Dune::ALUCubeGrid< dim, dim >\n , Dune::ALUConformGrid< dim, dim >\n , Dune::ALUSimplexGrid< dim, dim >\n#endif\n#if HAVE_ALBERTA\n , Dune::AlbertaGrid< dim, dim >\n#endif\n#if HAVE_UG\n , Dune::UGGrid< dim >\n#endif\n , Dune::SGrid< dim, dim > > GridTypes;\n\ntypedef YaspGrid<dim> SourceGrid;\ntypedef std::unordered_map<std::string, double> ResultMap;\n\ntemplate <class Grid>\nstruct GTraits {\n typedef double FieldType;\n static constexpr int polynomial_order = 1;\n typedef DSG::Providers::Cube<Grid> GridProvider;\n typedef typename Grid::template Codim<0>::Entity Entity;\n typedef Stuff::GlobalConstantFunction<Entity, typename Grid::ctype,\n Grid::dimension, typename Grid::ctype, 1> ConstantFunction;\n typedef Stuff::Functions::Expression< Entity, typename Grid::ctype,\n Grid::dimension, typename Grid::ctype, 1 > ScalarFunction;\n#if HAVE_DUNE_FEM\n typedef Dune::Fem::AdaptiveLeafGridPart<Grid> GridPart;\n typedef Dune::Fem::FunctionSpace<FieldType, FieldType, dim,1> ContFunctionSpace;\n typedef Dune::Fem::LagrangeDiscreteFunctionSpace<ContFunctionSpace, Dune::Fem::AdaptiveLeafGridPart<Grid>, polynomial_order> DiscreteSpace;\n typedef Fem::AdaptiveDiscreteFunction<DiscreteSpace> DiscreteFunction;\n#endif\n#if HAVE_DUNE_PDELAB\n typedef PDELab::QkLocalFiniteElementMap<typename Grid::LeafGridView, typename Grid::ctype,FieldType,polynomial_order>\n FEMap;\n typedef Dune::PDELab::ISTLVectorBackend<> VectorBackend;\n typedef Dune::PDELab::istl::BCRSMatrixBackend<> MatrixBackend;\n typedef PDELab::GridFunctionSpace<typename Grid::LeafGridView,FEMap,PDELab::ConformingDirichletConstraints,\n VectorBackend> GridFunctionSpace;\n typedef typename PDELab::BackendVectorSelector<GridFunctionSpace,FieldType>::Type PdelabVector;\n\n#endif\n};\n\ntemplate <class Grid>\nstd::shared_ptr<Grid> make_grid(const int macro_elements) {\n auto source_cube = typename GTraits<Grid>::GridProvider(0,1,macro_elements).grid();\n source_cube->globalRefine(2);\n return source_cube;\n}\n\nvoid output(const ResultMap& values) {\n for(auto pair : values) {\n DSC_LOG_INFO << (boost::format(\"%s\\t%e\\n\") % pair.first % pair.second).str();\n }\n}\n\ntemplate <class Grid>\nvoid fem(const int macro_elements, ResultMap& values)\n{\n typedef GTraits<Grid> Traits;\n\n auto grid = make_grid<Grid>(macro_elements);\n typename Traits::GridPart part(*grid);\n typename Traits::DiscreteSpace space(part);\n\n\n typename Traits::ScalarFunction linear_gradient(\"x\", \"x[0]\");\n typename Traits::DiscreteFunction linear_gradient_df(\"\", space);\n typename Traits::ConstantFunction constant_0(0);\n typename Traits::ConstantFunction constant_neg1(-1);\n typename Traits::DiscreteFunction constant_0_df(\"\", space);\n typename Traits::DiscreteFunction constant_neg1_df(\"\", space);\n\n Fem::LagrangeInterpolation<typename Traits::ScalarFunction,typename Traits::DiscreteFunction>\n ::apply(linear_gradient, linear_gradient_df);\n Fem::LagrangeInterpolation<typename Traits::ConstantFunction,typename Traits::DiscreteFunction>\n ::apply(constant_0, constant_0_df);\n Fem::LagrangeInterpolation<typename Traits::ConstantFunction,typename Traits::DiscreteFunction>\n ::apply(constant_neg1, constant_neg1_df);\n\n values[\"constant_0_l2\"] = DS::l2norm(constant_0_df);\n values[\"constant_0_h1\"] = DS::h1norm(constant_0_df);\n values[\"constant_neg1_l2\"] = DS::l2norm(constant_neg1_df);\n values[\"constant_neg1_h1\"] = DS::h1norm(constant_neg1_df);\n}\n\ntemplate <class Grid>\nvoid pdelab(const int macro_elements, ResultMap& values)\n{\n typedef GTraits<Grid> Traits;\n\n auto grid = make_grid<Grid>(macro_elements);\n const auto& grid_view = grid->leafGridView();\n typename Traits::FEMap fe_map(grid_view);\n typename Traits::ScalarFunction linear_gradient_ltr(\"x\", \"x[0]\", 1, \"id\", {{\"1\", \"0\"}});\n typename Traits::ScalarFunction linear_gradient_btt(\"x\", \"x[1]\", 1, \"id\", {{\"0\", \"1\"}});\n typename Traits::GridFunctionSpace space(grid_view, fe_map);\n typename Traits::ConstantFunction constant_0(0);\n typename Traits::ConstantFunction constant_neg1(-1);\n typename Traits::PdelabVector constant_0_pde(space, 0.0);\n typename Traits::PdelabVector constant_neg1_pde(space, -1.0);\n typename Traits::PdelabVector linear_gradient_ltr_pde(space, 0.0);\n typename Traits::PdelabVector linear_gradient_btt_pde(space, 0.0);\n Dune::PDELab::interpolate(DS::pdelabAdapted(linear_gradient_ltr, grid_view), space, linear_gradient_ltr_pde);\n Dune::PDELab::interpolate(DS::pdelabAdapted(linear_gradient_btt, grid_view), space, linear_gradient_btt_pde);\n\n values[\"constant_0_l2_diff\"] = DS::l2distance(constant_0, constant_0_pde);\n values[\"constant_0_h1_diff\"] = DS::h1distance(constant_0, constant_0_pde);\n values[\"constant_neg1_l2_diff\"] = DS::l2distance(constant_neg1, constant_neg1_pde);\n values[\"constant_neg1_h1_diff\"] = DS::h1distance(constant_neg1, constant_neg1_pde);\n values[\"scalar_grad_ltr_l2_diff\"] = DS::l2distance(linear_gradient_ltr, linear_gradient_ltr_pde);\n values[\"scalar_grad_ltr_h1_diff\"] = DS::h1distance(linear_gradient_ltr, linear_gradient_ltr_pde);\n values[\"scalar_grad_ltr_to_0_l2_diff\"] = DS::l2distance(constant_0, linear_gradient_ltr_pde);\n values[\"scalar_grad_ltr_to_0_h1_diff\"] = DS::h1distance(constant_0, linear_gradient_ltr_pde);\n values[\"scalar_grad_btt_l2_diff\"] = DS::l2distance(linear_gradient_btt, linear_gradient_btt_pde);\n values[\"scalar_grad_btt_h1_diff\"] = DS::h1distance(linear_gradient_btt, linear_gradient_btt_pde);\n values[\"scalar_grad_btt_to_0_l2_diff\"] = DS::l2distance(constant_0, linear_gradient_btt_pde);\n values[\"scalar_grad_btt_to_0_h1_diff\"] = DS::h1distance(constant_0, linear_gradient_btt_pde);\n}\n\nTEST(Norm, All){\n const int runs = DSC_CONFIG_GET(\"runs\", 1);\n DSC_PROFILER.reset(runs);\n for (auto i : DSC::valueRange(runs)) {\n const auto el = std::pow(8, i+1);\n ResultMap values;\n#if HAVE_DUNE_FEM\n fem<SourceGrid>(el, values);\n DSC_LOG_INFO << \"dune-fem results:\\n\";\n output(values);\n#endif \/\/ HAVE_DUNE_FEM\n#if HAVE_DUNE_PDELAB\n pdelab<SourceGrid>(el, values);\n DSC_LOG_INFO << \"dune-pdelab results:\\n\";\n output(values);\n#endif \/\/ HAVE_DUNE_PDELAB\n DSC_PROFILER.nextRun();\n }\n DSC_PROFILER.outputTimingsAll();\n DSC_LOG_INFO << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n test_init(argc, argv);\n return RUN_ALL_TESTS();\n}\n\n<commit_msg>[test.functions_norm] fixed some names and includes<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include \"test_common.hh\"\n\n#include <unordered_map>\n#include <dune\/common\/mpihelper.hh>\n#include <dune\/common\/parametertreeparser.hh>\n\n#include <dune\/stuff\/grid\/provider\/cube.hh>\n\n#include <dune\/stuff\/functions\/constant.hh>\n#include <dune\/stuff\/functions\/expression.hh>\n#include <dune\/stuff\/common\/profiler.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/playground\/functions\/femadapter.hh>\n#include <dune\/stuff\/playground\/functions\/norm.hh>\n#include <dune\/stuff\/playground\/functions\/pdelabadapter.hh>\n#include <dune\/stuff\/aliases.hh>\n\n#if HAVE_DUNE_FEM\n# include <dune\/fem\/gridpart\/adaptiveleafgridpart.hh>\n# include <dune\/fem\/function\/adaptivefunction\/adaptivefunction.hh>\n# include <dune\/fem\/space\/common\/functionspace.hh>\n# include <dune\/fem\/space\/lagrange.hh>\n# include <dune\/fem\/io\/file\/vtkio.hh>\n# include <dune\/fem\/operator\/lagrangeinterpolation.hh>\n#endif \/\/ HAVE_DUNE_FEM\n\n#if HAVE_DUNE_PDELAB\n# include <dune\/pdelab\/common\/function.hh>\n# include <dune\/pdelab\/gridfunctionspace\/gridfunctionspace.hh>\n# include <dune\/pdelab\/backend\/istl\/descriptors.hh>\n# include <dune\/pdelab\/backend\/istl\/bcrsmatrixbackend.hh>\n# include <dune\/pdelab\/finiteelementmap\/qkfem.hh>\n# include <dune\/pdelab\/backend\/istlvectorbackend.hh>\n# include <dune\/pdelab\/backend\/backendselector.hh>\n# include <dune\/pdelab\/constraints\/conforming.hh>\n# include <dune\/pdelab\/gridfunctionspace\/interpolate.hh>\n#endif\nusing namespace Dune;\n\nstatic const int dim = 2;\ntypedef testing::Types< Dune::YaspGrid< dim >\n#if HAVE_ALUGRID\n , Dune::ALUCubeGrid< dim, dim >\n , Dune::ALUConformGrid< dim, dim >\n , Dune::ALUSimplexGrid< dim, dim >\n#endif\n#if HAVE_ALBERTA\n , Dune::AlbertaGrid< dim, dim >\n#endif\n#if HAVE_UG\n , Dune::UGGrid< dim >\n#endif\n , Dune::SGrid< dim, dim > > GridTypes;\n\ntypedef YaspGrid<dim> SourceGrid;\ntypedef std::unordered_map<std::string, double> ResultMap;\n\ntemplate <class Grid>\nstruct GTraits {\n typedef double FieldType;\n static constexpr int polynomial_order = 1;\n typedef DSG::Providers::Cube<Grid> GridProvider;\n typedef typename Grid::template Codim<0>::Entity Entity;\n typedef Stuff::Functions::Constant<Entity, typename Grid::ctype,\n Grid::dimension, typename Grid::ctype, 1> ConstantFunction;\n typedef Stuff::Functions::Expression< Entity, typename Grid::ctype,\n Grid::dimension, typename Grid::ctype, 1 > ScalarFunction;\n#if HAVE_DUNE_FEM\n typedef Dune::Fem::AdaptiveLeafGridPart<Grid> GridPart;\n typedef Dune::Fem::FunctionSpace<FieldType, FieldType, dim,1> ContFunctionSpace;\n typedef Dune::Fem::LagrangeDiscreteFunctionSpace<ContFunctionSpace, Dune::Fem::AdaptiveLeafGridPart<Grid>, polynomial_order> DiscreteSpace;\n typedef Fem::AdaptiveDiscreteFunction<DiscreteSpace> DiscreteFunction;\n#endif\n#if HAVE_DUNE_PDELAB\n typedef PDELab::QkLocalFiniteElementMap<typename Grid::LeafGridView, typename Grid::ctype,FieldType,polynomial_order>\n FEMap;\n typedef Dune::PDELab::ISTLVectorBackend<> VectorBackend;\n typedef Dune::PDELab::istl::BCRSMatrixBackend<> MatrixBackend;\n typedef PDELab::GridFunctionSpace<typename Grid::LeafGridView,FEMap,PDELab::ConformingDirichletConstraints,\n VectorBackend> GridFunctionSpace;\n typedef typename PDELab::BackendVectorSelector<GridFunctionSpace,FieldType>::Type PdelabVector;\n\n#endif\n};\n\ntemplate <class Grid>\nstd::shared_ptr<Grid> make_grid(const int macro_elements) {\n auto source_cube = typename GTraits<Grid>::GridProvider(0,1,macro_elements).grid();\n source_cube->globalRefine(2);\n return source_cube;\n}\n\nvoid output(const ResultMap& values) {\n for(auto pair : values) {\n DSC_LOG_INFO << (boost::format(\"%s\\t%e\\n\") % pair.first % pair.second).str();\n }\n}\n\ntemplate <class Grid>\nvoid fem(const int macro_elements, ResultMap& values)\n{\n typedef GTraits<Grid> Traits;\n\n auto grid = make_grid<Grid>(macro_elements);\n typename Traits::GridPart part(*grid);\n typename Traits::DiscreteSpace space(part);\n\n\n typename Traits::ScalarFunction linear_gradient(\"x\", \"x[0]\");\n typename Traits::DiscreteFunction linear_gradient_df(\"\", space);\n typename Traits::ConstantFunction constant_0(0);\n typename Traits::ConstantFunction constant_neg1(-1);\n typename Traits::DiscreteFunction constant_0_df(\"\", space);\n typename Traits::DiscreteFunction constant_neg1_df(\"\", space);\n\n Fem::LagrangeInterpolation<typename Traits::ScalarFunction,typename Traits::DiscreteFunction>\n ::apply(linear_gradient, linear_gradient_df);\n Fem::LagrangeInterpolation<typename Traits::ConstantFunction,typename Traits::DiscreteFunction>\n ::apply(constant_0, constant_0_df);\n Fem::LagrangeInterpolation<typename Traits::ConstantFunction,typename Traits::DiscreteFunction>\n ::apply(constant_neg1, constant_neg1_df);\n\n values[\"constant_0_l2\"] = DS::l2norm(constant_0_df);\n values[\"constant_0_h1\"] = DS::h1norm(constant_0_df);\n values[\"constant_neg1_l2\"] = DS::l2norm(constant_neg1_df);\n values[\"constant_neg1_h1\"] = DS::h1norm(constant_neg1_df);\n}\n\ntemplate <class Grid>\nvoid pdelab(const int macro_elements, ResultMap& values)\n{\n typedef GTraits<Grid> Traits;\n\n auto grid = make_grid<Grid>(macro_elements);\n const auto& grid_view = grid->leafGridView();\n typename Traits::FEMap fe_map(grid_view);\n typename Traits::ScalarFunction linear_gradient_ltr(\"x\", \"x[0]\", 1, \"id\", {{\"1\", \"0\"}});\n typename Traits::ScalarFunction linear_gradient_btt(\"x\", \"x[1]\", 1, \"id\", {{\"0\", \"1\"}});\n typename Traits::GridFunctionSpace space(grid_view, fe_map);\n typename Traits::ConstantFunction constant_0(0);\n typename Traits::ConstantFunction constant_neg1(-1);\n typename Traits::PdelabVector constant_0_pde(space, 0.0);\n typename Traits::PdelabVector constant_neg1_pde(space, -1.0);\n typename Traits::PdelabVector linear_gradient_ltr_pde(space, 0.0);\n typename Traits::PdelabVector linear_gradient_btt_pde(space, 0.0);\n Dune::PDELab::interpolate(DS::pdelabAdapted(linear_gradient_ltr, grid_view), space, linear_gradient_ltr_pde);\n Dune::PDELab::interpolate(DS::pdelabAdapted(linear_gradient_btt, grid_view), space, linear_gradient_btt_pde);\n\n values[\"constant_0_l2_diff\"] = DS::l2distance(constant_0, constant_0_pde);\n values[\"constant_0_h1_diff\"] = DS::h1distance(constant_0, constant_0_pde);\n values[\"constant_neg1_l2_diff\"] = DS::l2distance(constant_neg1, constant_neg1_pde);\n values[\"constant_neg1_h1_diff\"] = DS::h1distance(constant_neg1, constant_neg1_pde);\n values[\"scalar_grad_ltr_l2_diff\"] = DS::l2distance(linear_gradient_ltr, linear_gradient_ltr_pde);\n values[\"scalar_grad_ltr_h1_diff\"] = DS::h1distance(linear_gradient_ltr, linear_gradient_ltr_pde);\n values[\"scalar_grad_ltr_to_0_l2_diff\"] = DS::l2distance(constant_0, linear_gradient_ltr_pde);\n values[\"scalar_grad_ltr_to_0_h1_diff\"] = DS::h1distance(constant_0, linear_gradient_ltr_pde);\n values[\"scalar_grad_btt_l2_diff\"] = DS::l2distance(linear_gradient_btt, linear_gradient_btt_pde);\n values[\"scalar_grad_btt_h1_diff\"] = DS::h1distance(linear_gradient_btt, linear_gradient_btt_pde);\n values[\"scalar_grad_btt_to_0_l2_diff\"] = DS::l2distance(constant_0, linear_gradient_btt_pde);\n values[\"scalar_grad_btt_to_0_h1_diff\"] = DS::h1distance(constant_0, linear_gradient_btt_pde);\n}\n\nTEST(Norm, All){\n const int runs = DSC_CONFIG_GET(\"runs\", 1);\n DSC_PROFILER.reset(runs);\n for (auto i : DSC::valueRange(runs)) {\n const auto el = std::pow(8, i+1);\n ResultMap values;\n#if HAVE_DUNE_FEM\n fem<SourceGrid>(el, values);\n DSC_LOG_INFO << \"dune-fem results:\\n\";\n output(values);\n#endif \/\/ HAVE_DUNE_FEM\n#if HAVE_DUNE_PDELAB\n pdelab<SourceGrid>(el, values);\n DSC_LOG_INFO << \"dune-pdelab results:\\n\";\n output(values);\n#endif \/\/ HAVE_DUNE_PDELAB\n DSC_PROFILER.nextRun();\n }\n DSC_PROFILER.outputTimingsAll();\n DSC_LOG_INFO << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n test_init(argc, argv);\n return RUN_ALL_TESTS();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 Google Inc.\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#include <cstdio>\n#include <cstdlib>\n#include <exception>\n#include <memory>\n#include <string>\n#include <sstream>\n#include <string.h>\n#include \"png.h\"\n#include \"guetzli\/jpeg_data.h\"\n#include \"guetzli\/jpeg_data_reader.h\"\n#include \"guetzli\/processor.h\"\n#include \"guetzli\/quality.h\"\n#include \"guetzli\/stats.h\"\n\nnamespace {\n\nconstexpr int kDefaultJPEGQuality = 95;\n\n\/\/ An upper estimate of memory usage of Guetzli. The bound is\n\/\/ max(kLowerMemusaeMB * 1<<20, pixel_count * kBytesPerPixel)\nconstexpr int kBytesPerPixel = 300;\nconstexpr int kLowestMemusageMB = 100; \/\/ in MB\n\nconstexpr int kDefaultMemlimitMB = 6000; \/\/ in MB\n\ninline uint8_t BlendOnBlack(const uint8_t val, const uint8_t alpha) {\n return (static_cast<int>(val) * static_cast<int>(alpha) + 128) \/ 255;\n}\n\nbool ReadPNG(const std::string& data, int* xsize, int* ysize,\n std::vector<uint8_t>* rgb) {\n png_structp png_ptr =\n png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);\n if (!png_ptr) {\n return false;\n }\n\n png_infop info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_read_struct(&png_ptr, nullptr, nullptr);\n return false;\n }\n\n if (setjmp(png_jmpbuf(png_ptr)) != 0) {\n \/\/ Ok we are here because of the setjmp.\n png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);\n return false;\n }\n\n std::istringstream memstream(data, std::ios::in | std::ios::binary);\n png_set_read_fn(png_ptr, static_cast<void*>(&memstream), [](png_structp png_ptr, png_bytep outBytes, png_size_t byteCountToRead) {\n std::istringstream& memstream = *static_cast<std::istringstream*>(png_get_io_ptr(png_ptr));\n \n memstream.read(reinterpret_cast<char*>(outBytes), byteCountToRead);\n\n if (memstream.eof()) png_error(png_ptr, \"unexpected end of data\");\n if (memstream.fail()) png_error(png_ptr, \"read from memory error\");\n });\n\n \/\/ The png_transforms flags are as follows:\n \/\/ packing == convert 1,2,4 bit images,\n \/\/ strip == 16 -> 8 bits \/ channel,\n \/\/ shift == use sBIT dynamics, and\n \/\/ expand == palettes -> rgb, grayscale -> 8 bit images, tRNS -> alpha.\n const unsigned int png_transforms =\n PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_STRIP_16;\n\n png_read_png(png_ptr, info_ptr, png_transforms, nullptr);\n\n png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);\n\n *xsize = png_get_image_width(png_ptr, info_ptr);\n *ysize = png_get_image_height(png_ptr, info_ptr);\n rgb->resize(3 * (*xsize) * (*ysize));\n\n const int components = png_get_channels(png_ptr, info_ptr);\n switch (components) {\n case 1: {\n \/\/ GRAYSCALE\n for (int y = 0; y < *ysize; ++y) {\n const uint8_t* row_in = row_pointers[y];\n uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];\n for (int x = 0; x < *xsize; ++x) {\n const uint8_t gray = row_in[x];\n row_out[3 * x + 0] = gray;\n row_out[3 * x + 1] = gray;\n row_out[3 * x + 2] = gray;\n }\n }\n break;\n }\n case 2: {\n \/\/ GRAYSCALE + ALPHA\n for (int y = 0; y < *ysize; ++y) {\n const uint8_t* row_in = row_pointers[y];\n uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];\n for (int x = 0; x < *xsize; ++x) {\n const uint8_t gray = BlendOnBlack(row_in[2 * x], row_in[2 * x + 1]);\n row_out[3 * x + 0] = gray;\n row_out[3 * x + 1] = gray;\n row_out[3 * x + 2] = gray;\n }\n }\n break;\n }\n case 3: {\n \/\/ RGB\n for (int y = 0; y < *ysize; ++y) {\n const uint8_t* row_in = row_pointers[y];\n uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];\n memcpy(row_out, row_in, 3 * (*xsize));\n }\n break;\n }\n case 4: {\n \/\/ RGBA\n for (int y = 0; y < *ysize; ++y) {\n const uint8_t* row_in = row_pointers[y];\n uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];\n for (int x = 0; x < *xsize; ++x) {\n const uint8_t alpha = row_in[4 * x + 3];\n row_out[3 * x + 0] = BlendOnBlack(row_in[4 * x + 0], alpha);\n row_out[3 * x + 1] = BlendOnBlack(row_in[4 * x + 1], alpha);\n row_out[3 * x + 2] = BlendOnBlack(row_in[4 * x + 2], alpha);\n }\n }\n break;\n }\n default:\n png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);\n return false;\n }\n png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);\n return true;\n}\n\nstd::string ReadFileOrDie(const char* filename) {\n bool read_from_stdin = strncmp(filename, \"-\", 2) == 0;\n\n FILE* f = read_from_stdin ? stdin : fopen(filename, \"rb\");\n if (!f) {\n perror(\"Can't open input file\");\n exit(1);\n }\n\n std::string result;\n off_t buffer_size = 8192;\n\n if (fseek(f, 0, SEEK_END) == 0) {\n buffer_size = ftell(f);\n if (fseek(f, 0, SEEK_SET) != 0) {\n perror(\"fseek\");\n exit(1);\n }\n } else if (ferror(f)) {\n perror(\"fseek\");\n exit(1);\n }\n\n std::unique_ptr<char[]> buf(new char[buffer_size]);\n while (!feof(f)) {\n size_t read_bytes = fread(buf.get(), sizeof(char), buffer_size, f);\n if (ferror(f)) {\n perror(\"fread\");\n exit(1);\n }\n result.append(buf.get(), read_bytes);\n }\n\n fclose(f);\n return result;\n}\n\nvoid WriteFileOrDie(const char* filename, const std::string& contents) {\n bool write_to_stdout = strncmp(filename, \"-\", 2) == 0;\n\n FILE* f = write_to_stdout ? stdout : fopen(filename, \"wb\");\n if (!f) {\n perror(\"Can't open output file for writing\");\n exit(1);\n }\n if (fwrite(contents.data(), 1, contents.size(), f) != contents.size()) {\n perror(\"fwrite\");\n exit(1);\n }\n if (fclose(f) < 0) {\n perror(\"fclose\");\n exit(1);\n }\n}\n\nvoid TerminateHandler() {\n fprintf(stderr, \"Unhandled exception. Most likely insufficient memory available.\\n\"\n \"Make sure that there is 300MB\/MPix of memory available.\\n\");\n exit(1);\n}\n\nvoid Usage() {\n fprintf(stderr,\n \"Guetzli JPEG compressor. Usage: \\n\"\n \"guetzli [flags] input_filename output_filename\\n\"\n \"\\n\"\n \"Flags:\\n\"\n \" --verbose - Print a verbose trace of all attempts to standard output.\\n\"\n \" --quality Q - Visual quality to aim for, expressed as a JPEG quality value.\\n\"\n \" Default value is %d.\\n\"\n \" --memlimit M - Memory limit in MB. Guetzli will fail if unable to stay under\\n\"\n \" the limit. Default limit is %d MB.\\n\"\n \" --nomemlimit - Do not limit memory usage.\\n\", kDefaultJPEGQuality, kDefaultMemlimitMB);\n exit(1);\n}\n\n} \/\/ namespace\n\nint main(int argc, char** argv) {\n std::set_terminate(TerminateHandler);\n\n int verbose = 0;\n int quality = kDefaultJPEGQuality;\n int memlimit_mb = kDefaultMemlimitMB;\n\n int opt_idx = 1;\n for(;opt_idx < argc;opt_idx++) {\n if (strnlen(argv[opt_idx], 2) < 2 || argv[opt_idx][0] != '-' || argv[opt_idx][1] != '-')\n break;\n if (!strcmp(argv[opt_idx], \"--verbose\")) {\n verbose = 1;\n } else if (!strcmp(argv[opt_idx], \"--quality\")) {\n opt_idx++;\n if (opt_idx >= argc)\n Usage();\n quality = atoi(argv[opt_idx]);\n } else if (!strcmp(argv[opt_idx], \"--memlimit\")) {\n opt_idx++;\n if (opt_idx >= argc)\n Usage();\n memlimit_mb = atoi(argv[opt_idx]);\n } else if (!strcmp(argv[opt_idx], \"--nomemlimit\")) {\n memlimit_mb = -1;\n } else if (!strcmp(argv[opt_idx], \"--\")) {\n opt_idx++;\n break;\n } else {\n fprintf(stderr, \"Unknown commandline flag: %s\\n\", argv[opt_idx]);\n Usage();\n }\n }\n\n if (argc - opt_idx != 2) {\n Usage();\n }\n\n std::string in_data = ReadFileOrDie(argv[opt_idx]);\n std::string out_data;\n\n guetzli::Params params;\n params.butteraugli_target =\n guetzli::ButteraugliScoreForQuality(quality);\n\n guetzli::ProcessStats stats;\n\n if (verbose) {\n stats.debug_output_file = stderr;\n }\n\n static const unsigned char kPNGMagicBytes[] = {\n 0x89, 'P', 'N', 'G', '\\r', '\\n', 0x1a, '\\n',\n };\n if (in_data.size() >= 8 &&\n memcmp(in_data.data(), kPNGMagicBytes, sizeof(kPNGMagicBytes)) == 0) {\n int xsize, ysize;\n std::vector<uint8_t> rgb;\n if (!ReadPNG(in_data, &xsize, &ysize, &rgb)) {\n fprintf(stderr, \"Error reading PNG data from input file\\n\");\n return 1;\n }\n double pixels = static_cast<double>(xsize) * ysize;\n if (memlimit_mb != -1\n && (pixels * kBytesPerPixel \/ (1 << 20) > memlimit_mb\n || memlimit_mb < kLowestMemusageMB)) {\n fprintf(stderr, \"Memory limit would be exceeded. Failing.\\n\");\n return 1;\n }\n if (!guetzli::Process(params, &stats, rgb, xsize, ysize, &out_data)) {\n fprintf(stderr, \"Guetzli processing failed\\n\");\n return 1;\n }\n } else {\n guetzli::JPEGData jpg_header;\n if (!guetzli::ReadJpeg(in_data, guetzli::JPEG_READ_HEADER, &jpg_header)) {\n fprintf(stderr, \"Error reading JPG data from input file\\n\");\n return 1;\n }\n double pixels = static_cast<double>(jpg_header.width) * jpg_header.height;\n if (memlimit_mb != -1\n && (pixels * kBytesPerPixel \/ (1 << 20) > memlimit_mb\n || memlimit_mb < kLowestMemusageMB)) {\n fprintf(stderr, \"Memory limit would be exceeded. Failing.\\n\");\n return 1;\n }\n if (!guetzli::Process(params, &stats, in_data, &out_data)) {\n fprintf(stderr, \"Guetzli processing failed\\n\");\n return 1;\n }\n }\n\n WriteFileOrDie(argv[opt_idx + 1], out_data);\n return 0;\n}\n<commit_msg>Update the memory usage estimate to 200 bytes \/ pixel.<commit_after>\/*\n * Copyright 2016 Google Inc.\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#include <cstdio>\n#include <cstdlib>\n#include <exception>\n#include <memory>\n#include <string>\n#include <sstream>\n#include <string.h>\n#include \"png.h\"\n#include \"guetzli\/jpeg_data.h\"\n#include \"guetzli\/jpeg_data_reader.h\"\n#include \"guetzli\/processor.h\"\n#include \"guetzli\/quality.h\"\n#include \"guetzli\/stats.h\"\n\nnamespace {\n\nconstexpr int kDefaultJPEGQuality = 95;\n\n\/\/ An upper estimate of memory usage of Guetzli. The bound is\n\/\/ max(kLowerMemusaeMB * 1<<20, pixel_count * kBytesPerPixel)\nconstexpr int kBytesPerPixel = 200;\nconstexpr int kLowestMemusageMB = 100; \/\/ in MB\n\nconstexpr int kDefaultMemlimitMB = 6000; \/\/ in MB\n\ninline uint8_t BlendOnBlack(const uint8_t val, const uint8_t alpha) {\n return (static_cast<int>(val) * static_cast<int>(alpha) + 128) \/ 255;\n}\n\nbool ReadPNG(const std::string& data, int* xsize, int* ysize,\n std::vector<uint8_t>* rgb) {\n png_structp png_ptr =\n png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);\n if (!png_ptr) {\n return false;\n }\n\n png_infop info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_read_struct(&png_ptr, nullptr, nullptr);\n return false;\n }\n\n if (setjmp(png_jmpbuf(png_ptr)) != 0) {\n \/\/ Ok we are here because of the setjmp.\n png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);\n return false;\n }\n\n std::istringstream memstream(data, std::ios::in | std::ios::binary);\n png_set_read_fn(png_ptr, static_cast<void*>(&memstream), [](png_structp png_ptr, png_bytep outBytes, png_size_t byteCountToRead) {\n std::istringstream& memstream = *static_cast<std::istringstream*>(png_get_io_ptr(png_ptr));\n \n memstream.read(reinterpret_cast<char*>(outBytes), byteCountToRead);\n\n if (memstream.eof()) png_error(png_ptr, \"unexpected end of data\");\n if (memstream.fail()) png_error(png_ptr, \"read from memory error\");\n });\n\n \/\/ The png_transforms flags are as follows:\n \/\/ packing == convert 1,2,4 bit images,\n \/\/ strip == 16 -> 8 bits \/ channel,\n \/\/ shift == use sBIT dynamics, and\n \/\/ expand == palettes -> rgb, grayscale -> 8 bit images, tRNS -> alpha.\n const unsigned int png_transforms =\n PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_STRIP_16;\n\n png_read_png(png_ptr, info_ptr, png_transforms, nullptr);\n\n png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);\n\n *xsize = png_get_image_width(png_ptr, info_ptr);\n *ysize = png_get_image_height(png_ptr, info_ptr);\n rgb->resize(3 * (*xsize) * (*ysize));\n\n const int components = png_get_channels(png_ptr, info_ptr);\n switch (components) {\n case 1: {\n \/\/ GRAYSCALE\n for (int y = 0; y < *ysize; ++y) {\n const uint8_t* row_in = row_pointers[y];\n uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];\n for (int x = 0; x < *xsize; ++x) {\n const uint8_t gray = row_in[x];\n row_out[3 * x + 0] = gray;\n row_out[3 * x + 1] = gray;\n row_out[3 * x + 2] = gray;\n }\n }\n break;\n }\n case 2: {\n \/\/ GRAYSCALE + ALPHA\n for (int y = 0; y < *ysize; ++y) {\n const uint8_t* row_in = row_pointers[y];\n uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];\n for (int x = 0; x < *xsize; ++x) {\n const uint8_t gray = BlendOnBlack(row_in[2 * x], row_in[2 * x + 1]);\n row_out[3 * x + 0] = gray;\n row_out[3 * x + 1] = gray;\n row_out[3 * x + 2] = gray;\n }\n }\n break;\n }\n case 3: {\n \/\/ RGB\n for (int y = 0; y < *ysize; ++y) {\n const uint8_t* row_in = row_pointers[y];\n uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];\n memcpy(row_out, row_in, 3 * (*xsize));\n }\n break;\n }\n case 4: {\n \/\/ RGBA\n for (int y = 0; y < *ysize; ++y) {\n const uint8_t* row_in = row_pointers[y];\n uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];\n for (int x = 0; x < *xsize; ++x) {\n const uint8_t alpha = row_in[4 * x + 3];\n row_out[3 * x + 0] = BlendOnBlack(row_in[4 * x + 0], alpha);\n row_out[3 * x + 1] = BlendOnBlack(row_in[4 * x + 1], alpha);\n row_out[3 * x + 2] = BlendOnBlack(row_in[4 * x + 2], alpha);\n }\n }\n break;\n }\n default:\n png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);\n return false;\n }\n png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);\n return true;\n}\n\nstd::string ReadFileOrDie(const char* filename) {\n bool read_from_stdin = strncmp(filename, \"-\", 2) == 0;\n\n FILE* f = read_from_stdin ? stdin : fopen(filename, \"rb\");\n if (!f) {\n perror(\"Can't open input file\");\n exit(1);\n }\n\n std::string result;\n off_t buffer_size = 8192;\n\n if (fseek(f, 0, SEEK_END) == 0) {\n buffer_size = ftell(f);\n if (fseek(f, 0, SEEK_SET) != 0) {\n perror(\"fseek\");\n exit(1);\n }\n } else if (ferror(f)) {\n perror(\"fseek\");\n exit(1);\n }\n\n std::unique_ptr<char[]> buf(new char[buffer_size]);\n while (!feof(f)) {\n size_t read_bytes = fread(buf.get(), sizeof(char), buffer_size, f);\n if (ferror(f)) {\n perror(\"fread\");\n exit(1);\n }\n result.append(buf.get(), read_bytes);\n }\n\n fclose(f);\n return result;\n}\n\nvoid WriteFileOrDie(const char* filename, const std::string& contents) {\n bool write_to_stdout = strncmp(filename, \"-\", 2) == 0;\n\n FILE* f = write_to_stdout ? stdout : fopen(filename, \"wb\");\n if (!f) {\n perror(\"Can't open output file for writing\");\n exit(1);\n }\n if (fwrite(contents.data(), 1, contents.size(), f) != contents.size()) {\n perror(\"fwrite\");\n exit(1);\n }\n if (fclose(f) < 0) {\n perror(\"fclose\");\n exit(1);\n }\n}\n\nvoid TerminateHandler() {\n fprintf(stderr, \"Unhandled exception. Most likely insufficient memory available.\\n\"\n \"Make sure that there is 300MB\/MPix of memory available.\\n\");\n exit(1);\n}\n\nvoid Usage() {\n fprintf(stderr,\n \"Guetzli JPEG compressor. Usage: \\n\"\n \"guetzli [flags] input_filename output_filename\\n\"\n \"\\n\"\n \"Flags:\\n\"\n \" --verbose - Print a verbose trace of all attempts to standard output.\\n\"\n \" --quality Q - Visual quality to aim for, expressed as a JPEG quality value.\\n\"\n \" Default value is %d.\\n\"\n \" --memlimit M - Memory limit in MB. Guetzli will fail if unable to stay under\\n\"\n \" the limit. Default limit is %d MB.\\n\"\n \" --nomemlimit - Do not limit memory usage.\\n\", kDefaultJPEGQuality, kDefaultMemlimitMB);\n exit(1);\n}\n\n} \/\/ namespace\n\nint main(int argc, char** argv) {\n std::set_terminate(TerminateHandler);\n\n int verbose = 0;\n int quality = kDefaultJPEGQuality;\n int memlimit_mb = kDefaultMemlimitMB;\n\n int opt_idx = 1;\n for(;opt_idx < argc;opt_idx++) {\n if (strnlen(argv[opt_idx], 2) < 2 || argv[opt_idx][0] != '-' || argv[opt_idx][1] != '-')\n break;\n if (!strcmp(argv[opt_idx], \"--verbose\")) {\n verbose = 1;\n } else if (!strcmp(argv[opt_idx], \"--quality\")) {\n opt_idx++;\n if (opt_idx >= argc)\n Usage();\n quality = atoi(argv[opt_idx]);\n } else if (!strcmp(argv[opt_idx], \"--memlimit\")) {\n opt_idx++;\n if (opt_idx >= argc)\n Usage();\n memlimit_mb = atoi(argv[opt_idx]);\n } else if (!strcmp(argv[opt_idx], \"--nomemlimit\")) {\n memlimit_mb = -1;\n } else if (!strcmp(argv[opt_idx], \"--\")) {\n opt_idx++;\n break;\n } else {\n fprintf(stderr, \"Unknown commandline flag: %s\\n\", argv[opt_idx]);\n Usage();\n }\n }\n\n if (argc - opt_idx != 2) {\n Usage();\n }\n\n std::string in_data = ReadFileOrDie(argv[opt_idx]);\n std::string out_data;\n\n guetzli::Params params;\n params.butteraugli_target =\n guetzli::ButteraugliScoreForQuality(quality);\n\n guetzli::ProcessStats stats;\n\n if (verbose) {\n stats.debug_output_file = stderr;\n }\n\n static const unsigned char kPNGMagicBytes[] = {\n 0x89, 'P', 'N', 'G', '\\r', '\\n', 0x1a, '\\n',\n };\n if (in_data.size() >= 8 &&\n memcmp(in_data.data(), kPNGMagicBytes, sizeof(kPNGMagicBytes)) == 0) {\n int xsize, ysize;\n std::vector<uint8_t> rgb;\n if (!ReadPNG(in_data, &xsize, &ysize, &rgb)) {\n fprintf(stderr, \"Error reading PNG data from input file\\n\");\n return 1;\n }\n double pixels = static_cast<double>(xsize) * ysize;\n if (memlimit_mb != -1\n && (pixels * kBytesPerPixel \/ (1 << 20) > memlimit_mb\n || memlimit_mb < kLowestMemusageMB)) {\n fprintf(stderr, \"Memory limit would be exceeded. Failing.\\n\");\n return 1;\n }\n if (!guetzli::Process(params, &stats, rgb, xsize, ysize, &out_data)) {\n fprintf(stderr, \"Guetzli processing failed\\n\");\n return 1;\n }\n } else {\n guetzli::JPEGData jpg_header;\n if (!guetzli::ReadJpeg(in_data, guetzli::JPEG_READ_HEADER, &jpg_header)) {\n fprintf(stderr, \"Error reading JPG data from input file\\n\");\n return 1;\n }\n double pixels = static_cast<double>(jpg_header.width) * jpg_header.height;\n if (memlimit_mb != -1\n && (pixels * kBytesPerPixel \/ (1 << 20) > memlimit_mb\n || memlimit_mb < kLowestMemusageMB)) {\n fprintf(stderr, \"Memory limit would be exceeded. Failing.\\n\");\n return 1;\n }\n if (!guetzli::Process(params, &stats, in_data, &out_data)) {\n fprintf(stderr, \"Guetzli processing failed\\n\");\n return 1;\n }\n }\n\n WriteFileOrDie(argv[opt_idx + 1], out_data);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011-2012 Gregory Banks\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 \"np\/spiegel\/common.hxx\"\n#include \"state.hxx\"\n#include \"compile_unit.hxx\"\n#include \"walker.hxx\"\n#include \"enumerations.hxx\"\n\nnamespace np { namespace spiegel { namespace dwarf {\nusing namespace std;\nusing namespace np::util;\n\nbool\ncompile_unit_t::read_header(reader_t &r)\n{\n reader_ = r;\t \/\/ sample offset of start of header\n\n np::spiegel::offset_t length;\n uint16_t version;\n bool is64 = false;\n if (!r.read_u32(length))\n\treturn false;\n if (length == 0xffffffff)\n {\n\t\/* An all-1 length marks the 64-bit format\n\t * introduced in the DWARF3 standard *\/\n#if _NP_ADDRSIZE == 4\n\tfatal(\"The 64-bit DWARF format is not supported on 32-bit architectures\");\n#elif _NP_ADDRSIZE == 8\n\tis64 = true;\n\tif (!r.read_u64(length))\n\t return false;\n#else\n#error \"Unknown address size\"\n#endif\n }\n if (length > r.get_remains())\n\tfatal(\"Bad DWARF compilation unit length %llu\", (unsigned long long)length);\n\n if (!r.read_u16(version))\n\treturn false;\n if (version < MIN_DWARF_VERSION || version > MAX_DWARF_VERSION)\n\tfatal(\"Bad DWARF version %u, expecting %u-%u\",\n\t version, MIN_DWARF_VERSION, MAX_DWARF_VERSION);\n if (length < (unsigned)(header_length-(is64 ? 14 : 6)\/*read so far*\/))\n\tfatal(\"Bad DWARF compilation unit length %llu\", (unsigned long long)length);\n\n uint8_t addrsize;\n if (!r.read_u32(abbrevs_offset_) ||\n\t!r.read_u8(addrsize))\n\treturn false;\n if (addrsize != _NP_ADDRSIZE) fatal(\"Bad DWARF addrsize %u, expecting %u\",\n\t addrsize, _NP_ADDRSIZE);\n\n#if _NP_DEBUG\n printf(\"DWARF compilation unit header\\n\");\n printf(\" length %u\\n\", (unsigned)length);\n printf(\" version %u\\n\", (unsigned)version);\n printf(\" is64 %s\\n\", is64 ? \"true\" : \"false\");\n printf(\" abbrevs_offset %u\\n\", (unsigned)abbrevs_offset_);\n printf(\" addrsize %u\\n\", (unsigned)addrsize);\n#endif\n\n version_ = version;\n is64_ = is64;\n\n length += is64 ? 12 : 4;\t\/\/ account for the `length' field of the header\n\n \/\/ setup reader_ to point to the whole compile\n \/\/ unit but not any bytes of the next one\n reader_.set_is64(is64);\n reader_ = reader_.initial_subset(length);\n\n \/\/ skip the outer reader over the body\n r.skip(length - header_length);\n\n return true;\n}\n\nvoid\ncompile_unit_t::read_abbrevs(reader_t &r)\n{\n r.seek(abbrevs_offset_);\n\n uint32_t code;\n \/* code 0 indicates end of compile unit *\/\n while (r.read_uleb128(code) && code)\n {\n\tabbrev_t *a = new abbrev_t(code);\n\tif (!a->read(r))\n\t{\n\t delete a;\n\t break;\n\t}\n\tif (a->code >= abbrevs_.size())\n\t abbrevs_.resize(a->code+1, 0);\n\tabbrevs_[a->code] = a;\n }\n}\n\n\nvoid\ncompile_unit_t::dump_abbrevs() const\n{\n printf(\"Abbrevs {\\n\");\n\n vector<abbrev_t*>::const_iterator itr;\n for (itr = abbrevs_.begin() ; itr != abbrevs_.end() ; ++itr)\n {\n\tabbrev_t *a = *itr;\n\tif (!a) continue;\n\tprintf(\"Code %u\\n\", a->code);\n\tprintf(\" tag 0x%x (%s)\\n\", a->tag, tagnames.to_name(a->tag));\n\tprintf(\" children %u (%s)\\n\",\n\t\t(unsigned)a->children,\n\t\tchildvals.to_name(a->children));\n\tprintf(\" attribute specifications {\\n\");\n\n\tvector<abbrev_t::attr_spec_t>::iterator i;\n\tfor (i = a->attr_specs.begin() ; i != a->attr_specs.end() ; ++i)\n\t{\n\t printf(\" name 0x%x (%s)\",\n\t\t i->name, attrnames.to_name(i->name));\n\t printf(\" form 0x%x (%s)\\n\",\n\t\t i->form, formvals.to_name(i->form));\n\t}\n\tprintf(\" }\\n\");\n }\n printf(\"}\\n\");\n}\n\nconst char *\ncompile_unit_t::get_executable() const\n{\n const state_t::linkobj_t *lo = state_t::instance()->linkobjs_[loindex_];\n return lo->filename_;\n}\n\nconst section_t *\ncompile_unit_t::get_section(uint32_t i) const\n{\n const state_t::linkobj_t *lo = state_t::instance()->linkobjs_[loindex_];\n return &lo->sections_[i];\n}\n\n\/\/ close namespaces\n}; }; };\n<commit_msg>Fix some error messages<commit_after>\/*\n * Copyright 2011-2012 Gregory Banks\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 \"np\/spiegel\/common.hxx\"\n#include \"state.hxx\"\n#include \"compile_unit.hxx\"\n#include \"walker.hxx\"\n#include \"enumerations.hxx\"\n\nnamespace np { namespace spiegel { namespace dwarf {\nusing namespace std;\nusing namespace np::util;\n\nbool\ncompile_unit_t::read_header(reader_t &r)\n{\n reader_ = r;\t \/\/ sample offset of start of header\n\n np::spiegel::offset_t length;\n uint16_t version;\n bool is64 = false;\n if (!r.read_u32(length))\n\treturn false;\n if (length == 0xffffffff)\n {\n\t\/* An all-1 length marks the 64-bit format\n\t * introduced in the DWARF3 standard *\/\n#if _NP_ADDRSIZE == 4\n\tfatal(\"The 64-bit DWARF format is not supported on 32-bit architectures\");\n#elif _NP_ADDRSIZE == 8\n\tis64 = true;\n\tif (!r.read_u64(length))\n\t return false;\n#else\n#error \"Unknown address size\"\n#endif\n }\n if (length > r.get_remains())\n\tfatal(\"Bad DWARF compile unit length %llu\", (unsigned long long)length);\n\n if (!r.read_u16(version))\n\treturn false;\n if (version < MIN_DWARF_VERSION || version > MAX_DWARF_VERSION)\n\tfatal(\"Bad DWARF version %u, expecting %u-%u\",\n\t version, MIN_DWARF_VERSION, MAX_DWARF_VERSION);\n if (length < (unsigned)(header_length-(is64 ? 14 : 6)\/*read so far*\/))\n\tfatal(\"Bad DWARF compile unit length %llu\", (unsigned long long)length);\n\n uint8_t addrsize;\n if (!r.read_u32(abbrevs_offset_) ||\n\t!r.read_u8(addrsize))\n\treturn false;\n if (addrsize != _NP_ADDRSIZE) fatal(\"Bad DWARF addrsize %u, expecting %u\",\n\t addrsize, _NP_ADDRSIZE);\n\n#if _NP_DEBUG\n printf(\"DWARF compilation unit header\\n\");\n printf(\" length %u\\n\", (unsigned)length);\n printf(\" version %u\\n\", (unsigned)version);\n printf(\" is64 %s\\n\", is64 ? \"true\" : \"false\");\n printf(\" abbrevs_offset %u\\n\", (unsigned)abbrevs_offset_);\n printf(\" addrsize %u\\n\", (unsigned)addrsize);\n#endif\n\n version_ = version;\n is64_ = is64;\n\n length += is64 ? 12 : 4;\t\/\/ account for the `length' field of the header\n\n \/\/ setup reader_ to point to the whole compile\n \/\/ unit but not any bytes of the next one\n reader_.set_is64(is64);\n reader_ = reader_.initial_subset(length);\n\n \/\/ skip the outer reader over the body\n r.skip(length - header_length);\n\n return true;\n}\n\nvoid\ncompile_unit_t::read_abbrevs(reader_t &r)\n{\n r.seek(abbrevs_offset_);\n\n uint32_t code;\n \/* code 0 indicates end of compile unit *\/\n while (r.read_uleb128(code) && code)\n {\n\tabbrev_t *a = new abbrev_t(code);\n\tif (!a->read(r))\n\t{\n\t delete a;\n\t break;\n\t}\n\tif (a->code >= abbrevs_.size())\n\t abbrevs_.resize(a->code+1, 0);\n\tabbrevs_[a->code] = a;\n }\n}\n\n\nvoid\ncompile_unit_t::dump_abbrevs() const\n{\n printf(\"Abbrevs {\\n\");\n\n vector<abbrev_t*>::const_iterator itr;\n for (itr = abbrevs_.begin() ; itr != abbrevs_.end() ; ++itr)\n {\n\tabbrev_t *a = *itr;\n\tif (!a) continue;\n\tprintf(\"Code %u\\n\", a->code);\n\tprintf(\" tag 0x%x (%s)\\n\", a->tag, tagnames.to_name(a->tag));\n\tprintf(\" children %u (%s)\\n\",\n\t\t(unsigned)a->children,\n\t\tchildvals.to_name(a->children));\n\tprintf(\" attribute specifications {\\n\");\n\n\tvector<abbrev_t::attr_spec_t>::iterator i;\n\tfor (i = a->attr_specs.begin() ; i != a->attr_specs.end() ; ++i)\n\t{\n\t printf(\" name 0x%x (%s)\",\n\t\t i->name, attrnames.to_name(i->name));\n\t printf(\" form 0x%x (%s)\\n\",\n\t\t i->form, formvals.to_name(i->form));\n\t}\n\tprintf(\" }\\n\");\n }\n printf(\"}\\n\");\n}\n\nconst char *\ncompile_unit_t::get_executable() const\n{\n const state_t::linkobj_t *lo = state_t::instance()->linkobjs_[loindex_];\n return lo->filename_;\n}\n\nconst section_t *\ncompile_unit_t::get_section(uint32_t i) const\n{\n const state_t::linkobj_t *lo = state_t::instance()->linkobjs_[loindex_];\n return &lo->sections_[i];\n}\n\n\/\/ close namespaces\n}; }; };\n<|endoftext|>"} {"text":"<commit_before><commit_msg>tdf#93052 Fix abundance of calc annotation styles<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"j1App.h\"\n#include \"j1Render.h\"\n#include \"p2Log.h\"\n#include \"j1Camera.h\"\n#include \"j1Player.h\"\n#include \"j1Window.h\"\n#include \"Color.h\"\n#include \"GuiLabel.h\"\n\nj1Camera::j1Camera()\n{\n\tname.create(\"camera\");\n}\n\nj1Camera::~j1Camera()\n{\n\n}\n\n\/\/ Called before render is available\nbool j1Camera::Awake(pugi::xml_node&)\n{\n\t\/\/Create the ellipses\n\tLitleEllipse.ellipsecentre = { 0,0 };\n\tLitleEllipse.semimajoraxis = 320;\n\tLitleEllipse.semiminoraxis = 180;\n\n\tBigEllipse.ellipsecentre = { 0,0 };\n\tBigEllipse.semimajoraxis = 640;\n\tBigEllipse.semiminoraxis = 360;\n\n\tf_border_between_ellipses = BigEllipse.InsideEllipseValue({ 0,LitleEllipse.semiminoraxis});\n\n\tDebugPerformanceData_Rect = { 0,0,260,135 };\n\n\treturn true;\n}\n\n\/\/ Called before the first frame\nbool j1Camera::Start()\n{\n\t\/\/Get some useful variables\n\tf_Max_scale = App->win->scale;\n\tf_Min_scale = f_Max_scale - 0.3f;\n\tif (f_Min_scale < 0.8f)\n\t\tf_Min_scale = 0.8f;\n\tint w, h = 0;\n\tSDL_GetRendererOutputSize(App->render->renderer, &w, &h);\n\ti_Half_w = (int)(w * 0.5f);\n\ti_Half_h = (int)(h * 0.5f);\n\n\t\/\/Fill up debug performance data vector\n\tfor (int i = 0, pos = App->win->GetWindowH() - DebugPerformanceData_Rect.h + 6; i < 8; i++, pos += 15) \/\/8, number of debug strings\n\t\tDebugPerformanceData.push_back(App->gui->CreateLabel({ 10,pos }, &std::string(\"\"), false, AddGuiTo::none));\n\tDebugPerformanceData[6]->EditLabelStr(&std::string(\"Press F9 to toggle this window visibility.\"));\n\tDebugPerformanceData[6]->SetLabelColor(&Yellow);\n\tDebugPerformanceData[7]->EditLabelStr(&std::string(\"Press F10 to report a bug.\"));\n\tDebugPerformanceData[7]->SetLabelColor(&Yellow);\n\n\treturn true;\n}\n\n\/\/ Called each loop iteration\nbool j1Camera::PreUpdate()\n{\n\t\/\/Calculate camera centre\n\t\/**\/\n\tif (App->input->GetKey(SDL_SCANCODE_L) == KEY_REPEAT) App->win->scale += 0.005;\n\tif (App->input->GetKey(SDL_SCANCODE_K) == KEY_REPEAT) App->win->scale -= 0.005;\n\t\/**\/\n\tfloat Scale = App->win->GetScale();\n\tiPoint Centre = { 0,0 };\n\tCentre.x = (int)((((float)(App->player->Link->pos.x + App->player->Zelda->pos.x)) * 0.5f));\n\tCentre.y = (int)((((float)(App->player->Link->pos.y + App->player->Zelda->pos.y)) * 0.5f) );\n\t\/\/Camera position\n\tApp->render->camera.x = -Centre.x * Scale + i_Half_w;\n\tApp->render->camera.y = -Centre.y * Scale + i_Half_h;\n\t\/\/Ellipss centre\n\tiPoint CentrePos = { 0,0 };\n\tCentrePos = App->render->WorldToScreen(Centre.x, Centre.y);\n\tLitleEllipse.ellipsecentre = BigEllipse.ellipsecentre = { (int)(CentrePos.x), (int)(CentrePos.y) };\n\n\t\/\/Debug Performance Data\n\tDebugPerformanceData_Rect.x = -App->render->camera.x;\n\tDebugPerformanceData_Rect.y = -App->render->camera.y + App->win->GetWindowH() - DebugPerformanceData_Rect.h;\n\treturn true;\n}\n\n\/\/ Called each loop iteration\nbool j1Camera::Update(float dt)\n{\n\tiPoint LinkPos = { 0,0 };\n\tLinkPos = App->render->WorldToScreen(App->player->Link->pos.x, App->player->Link->pos.y);\n\t\/**\/\n\t\/\/Is inside the little ellipse\n\tif (LitleEllipse.InsideEllipse(LinkPos))\n\t\tApp->win->scale = f_Max_scale;\n\t\/\/Is out the little ellipse\n\telse\n\t{\n\t\t\/\/Is between the big ellipse and the little one\n\t\tif (BigEllipse.InsideEllipse(LinkPos))\n\t\t{\n\t\t\t\/\/Scale between f_Max_scale and f_Min_scale\n\t\t\tfloat f_percentual_value = (((float)(BigEllipse.InsideEllipseValue(LinkPos) - f_border_between_ellipses)) \/ ((float)(1.0f - f_border_between_ellipses))) * 100.0f;\n\t\t\tfloat f_invert_percentual_value = 100.0f - f_percentual_value;\n\t\t\tif (f_invert_percentual_value < 0.0f)\n\t\t\t\tf_invert_percentual_value = 0.0f;\n\t\t\telse if (f_invert_percentual_value > 100.0f)\n\t\t\t\tf_invert_percentual_value = 100.0f;\n\t\t\tApp->win->scale = (((f_Max_scale - f_Min_scale) * f_invert_percentual_value) \/ (100.0f)) + f_Min_scale;\n\t\t}\n\t\t\/\/Is out the big ellipse\n\t\telse\n\t\t\tApp->win->scale = f_Min_scale;\n\t}\n\t\/**\/\n\n\t\/\/Some ellipses debug draw for testing\n\t\/*\n\t\/\/Little ellipse\n\t\/\/Centre\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x, LitleEllipse.ellipsecentre.y, 5, 0, 0, 255);\n\t\/\/Axis\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x + LitleEllipse.semimajoraxis, LitleEllipse.ellipsecentre.y, 5, 0, 0, 255);\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x - LitleEllipse.semimajoraxis, LitleEllipse.ellipsecentre.y, 5, 0, 0, 255);\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x, LitleEllipse.ellipsecentre.y + LitleEllipse.semiminoraxis, 5, 0, 0, 255);\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x, LitleEllipse.ellipsecentre.y - LitleEllipse.semiminoraxis, 5, 0, 0, 255);\n\n\t\/\/Big ellipse\n\t\/\/Centre\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x, BigEllipse.ellipsecentre.y, 10, 255, 0, 0);\n\t\/\/Axis\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x + BigEllipse.semimajoraxis, BigEllipse.ellipsecentre.y, 10, 255, 0, 0);\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x - BigEllipse.semimajoraxis, BigEllipse.ellipsecentre.y, 10, 255, 0, 0);\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x, BigEllipse.ellipsecentre.y + BigEllipse.semiminoraxis, 10, 255, 0, 0);\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x, BigEllipse.ellipsecentre.y - BigEllipse.semiminoraxis, 10, 255, 0, 0);\n\t*\/\n\n\t\/\/Debug window with perdformance data\n\tif (App->input->GetKey(SDL_SCANCODE_F9) == KEY_DOWN)\n\t\tf_DebugPerformanceData = !f_DebugPerformanceData;\n\n\tif (App->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN)\n\t\tShellExecute(NULL, \"open\", \"https:\/\/github.com\/Guille1406\/The-Legend-of-Zelda-Hyrule-Conquest\/issues\", NULL, NULL, SW_SHOWMAXIMIZED);\n\n\tif (f_DebugPerformanceData)\n\t{\n\t\tApp->render->DrawQuad(DebugPerformanceData_Rect, Blue(0), Blue(1), Blue(2), 150, true, true, false);\n\n\t\tfor (int i = 0; i < DebugPerformanceData.size(); i++)\n\t\t{\n\t\t\tswitch (i)\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t\tstatic char AvFPS[25];\n\t\t\t\tsprintf_s(AvFPS, 25, \"Av.FPS: %.2f\", App->avg_fps);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(AvFPS));\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tstatic char LastFrameMs[25];\n\t\t\t\tsprintf_s(LastFrameMs, 25, \"Last Frame Ms: %u\", App->last_frame_ms);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(LastFrameMs));\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tstatic char Lastsecframes[25];\n\t\t\t\tsprintf_s(Lastsecframes, 25, \"Last sec frames: %i\", App->frames_on_last_update);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(Lastsecframes));\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstatic char Lastdt[25];\n\t\t\t\tsprintf_s(Lastdt, 25, \"Last dt: %.3f\", App->dt);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(Lastdt));\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tstatic char Timesincestartup[100];\n\t\t\t\tsprintf_s(Timesincestartup, 100, \"Time since startup: %.3f\", App->seconds_since_startup);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(Timesincestartup));\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tstatic char FrameCount[100];\n\t\t\t\tsprintf_s(FrameCount, 100, \"Frame Count: %lu\", App->frame_count);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(FrameCount));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDebugPerformanceData[i]->Draw();\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\/\/ Called each loop iteration\nbool j1Camera::PostUpdate()\n{\n\treturn true;\n}\n\n\/\/ Called before quitting\nbool j1Camera::CleanUp()\n{\n\tLOG(\"Freeing camera\");\n\treturn true;\n}\n\nvoid j1Camera::OnGui(Gui* ui, GuiEvent event)\n{\n\n}\n\nvoid j1Camera::OnConsoleCommand(const Command* command, const std::vector<std::string>& commandarguments)\n{\n\n}\n\nvoid j1Camera::OnConsoleCVar(const CVar* cvar)\n{\n\n}<commit_msg>Camera Updated<commit_after>#include \"j1App.h\"\n#include \"j1Render.h\"\n#include \"p2Log.h\"\n#include \"j1Camera.h\"\n#include \"j1Player.h\"\n#include \"j1Window.h\"\n#include \"Color.h\"\n#include \"GuiLabel.h\"\n\nj1Camera::j1Camera()\n{\n\tname.create(\"camera\");\n}\n\nj1Camera::~j1Camera()\n{\n\n}\n\n\/\/ Called before render is available\nbool j1Camera::Awake(pugi::xml_node&)\n{\n\t\/\/Create the ellipses\n\tLitleEllipse.ellipsecentre = { 0,0 };\n\tLitleEllipse.semimajoraxis = 320;\n\tLitleEllipse.semiminoraxis = 180;\n\n\tBigEllipse.ellipsecentre = { 0,0 };\n\tBigEllipse.semimajoraxis = 640;\n\tBigEllipse.semiminoraxis = 360;\n\n\tf_border_between_ellipses = BigEllipse.InsideEllipseValue({ 0,LitleEllipse.semiminoraxis});\n\n\tDebugPerformanceData_Rect = { 0,0,260,135 };\n\n\treturn true;\n}\n\n\/\/ Called before the first frame\nbool j1Camera::Start()\n{\n\t\/\/Get some useful variables\n\tf_Max_scale = App->win->scale;\n\tf_Min_scale = f_Max_scale - 0.3f;\n\tif (f_Min_scale < 0.8f)\n\t\tf_Min_scale = 0.8f;\n\tint w, h = 0;\n\tSDL_GetRendererOutputSize(App->render->renderer, &w, &h);\n\ti_Half_w = (int)(w * 0.5f);\n\ti_Half_h = (int)(h * 0.5f);\n\n\t\/\/Fill up debug performance data vector\n\tfor (int i = 0, pos = App->win->GetWindowH() - DebugPerformanceData_Rect.h + 6; i < 8; i++, pos += 15) \/\/8, number of debug strings\n\t\tDebugPerformanceData.push_back(App->gui->CreateLabel({ 10,pos }, &std::string(\"\"), false, AddGuiTo::none));\n\tDebugPerformanceData[6]->EditLabelStr(&std::string(\"Press F9 to toggle this window visibility.\"));\n\tDebugPerformanceData[6]->SetLabelColor(&Yellow);\n\tDebugPerformanceData[7]->EditLabelStr(&std::string(\"Press F10 to report a bug.\"));\n\tDebugPerformanceData[7]->SetLabelColor(&Yellow);\n\n\treturn true;\n}\n\n\/\/ Called each loop iteration\nbool j1Camera::PreUpdate()\n{\n\t\/\/Calculate camera centre\n\t\/**\/\n\tif (App->input->GetKey(SDL_SCANCODE_L) == KEY_REPEAT) App->win->scale += 0.005;\n\tif (App->input->GetKey(SDL_SCANCODE_K) == KEY_REPEAT) App->win->scale -= 0.005;\n\t\/**\/\n\tfloat Scale = App->win->GetScale();\n\tiPoint Centre = { 0,0 };\n\tCentre.x = (int)((((float)(App->player->Link->pos.x + App->player->Zelda->pos.x)) * 0.5f));\n\tCentre.y = (int)((((float)(App->player->Link->pos.y + App->player->Zelda->pos.y)) * 0.5f) );\n\t\/\/Camera position\n\t\n\n\tApp->render->camera.x = -Centre.x * Scale + i_Half_w;\n\tApp->render->camera.y = -Centre.y * Scale + i_Half_h;\n\n\tif (App->render->camera.x >= 0) App->render->camera.x = 0;\n\tif (-App->render->camera.x >= App->map->data.width * App->map->data.tile_width - App->render->camera.w \/ App->win->GetScale()) {\n\t\tApp->render->camera.x = -1 * (App->map->data.width * App->map->data.tile_width - App->render->camera.w \/ App->win->GetScale());\n\t}\n\n\tif (App->render->camera.y >= 0) App->render->camera.y = 0;\n\tif (-App->render->camera.y >= App->map->data.height * App->map->data.tile_height - App->render->camera.h \/ App->win->GetScale()) {\n\t\tApp->render->camera.y = -1 * (App->map->data.height * App->map->data.tile_height - App->render->camera.h \/ App->win->GetScale());\n\t}\n\t\/\/Ellipss centre\n\tiPoint CentrePos = { 0,0 };\n\tCentrePos = App->render->WorldToScreen(Centre.x, Centre.y);\n\tLitleEllipse.ellipsecentre = BigEllipse.ellipsecentre = { (int)(CentrePos.x), (int)(CentrePos.y) };\n\n\t\/\/Debug Performance Data\n\tDebugPerformanceData_Rect.x = -App->render->camera.x;\n\tDebugPerformanceData_Rect.y = -App->render->camera.y + App->win->GetWindowH() - DebugPerformanceData_Rect.h;\n\treturn true;\n}\n\n\/\/ Called each loop iteration\nbool j1Camera::Update(float dt)\n{\n\tiPoint LinkPos = { 0,0 };\n\tLinkPos = App->render->WorldToScreen(App->player->Link->pos.x, App->player->Link->pos.y);\n\t\/**\/\n\t\/\/Is inside the little ellipse\n\tif (LitleEllipse.InsideEllipse(LinkPos))\n\t\tApp->win->scale = f_Max_scale;\n\t\/\/Is out the little ellipse\n\telse\n\t{\n\t\t\/\/Is between the big ellipse and the little one\n\t\tif (BigEllipse.InsideEllipse(LinkPos))\n\t\t{\n\t\t\t\/\/Scale between f_Max_scale and f_Min_scale\n\t\t\tfloat f_percentual_value = (((float)(BigEllipse.InsideEllipseValue(LinkPos) - f_border_between_ellipses)) \/ ((float)(1.0f - f_border_between_ellipses))) * 100.0f;\n\t\t\tfloat f_invert_percentual_value = 100.0f - f_percentual_value;\n\t\t\tif (f_invert_percentual_value < 0.0f)\n\t\t\t\tf_invert_percentual_value = 0.0f;\n\t\t\telse if (f_invert_percentual_value > 100.0f)\n\t\t\t\tf_invert_percentual_value = 100.0f;\n\t\t\tApp->win->scale = (((f_Max_scale - f_Min_scale) * f_invert_percentual_value) \/ (100.0f)) + f_Min_scale;\n\t\t}\n\t\t\/\/Is out the big ellipse\n\t\telse\n\t\t\tApp->win->scale = f_Min_scale;\n\t}\n\t\/**\/\n\n\t\/\/Some ellipses debug draw for testing\n\t\/*\n\t\/\/Little ellipse\n\t\/\/Centre\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x, LitleEllipse.ellipsecentre.y, 5, 0, 0, 255);\n\t\/\/Axis\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x + LitleEllipse.semimajoraxis, LitleEllipse.ellipsecentre.y, 5, 0, 0, 255);\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x - LitleEllipse.semimajoraxis, LitleEllipse.ellipsecentre.y, 5, 0, 0, 255);\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x, LitleEllipse.ellipsecentre.y + LitleEllipse.semiminoraxis, 5, 0, 0, 255);\n\tApp->render->DrawCircle(LitleEllipse.ellipsecentre.x, LitleEllipse.ellipsecentre.y - LitleEllipse.semiminoraxis, 5, 0, 0, 255);\n\n\t\/\/Big ellipse\n\t\/\/Centre\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x, BigEllipse.ellipsecentre.y, 10, 255, 0, 0);\n\t\/\/Axis\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x + BigEllipse.semimajoraxis, BigEllipse.ellipsecentre.y, 10, 255, 0, 0);\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x - BigEllipse.semimajoraxis, BigEllipse.ellipsecentre.y, 10, 255, 0, 0);\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x, BigEllipse.ellipsecentre.y + BigEllipse.semiminoraxis, 10, 255, 0, 0);\n\tApp->render->DrawCircle(BigEllipse.ellipsecentre.x, BigEllipse.ellipsecentre.y - BigEllipse.semiminoraxis, 10, 255, 0, 0);\n\t*\/\n\n\t\/\/Debug window with perdformance data\n\tif (App->input->GetKey(SDL_SCANCODE_F9) == KEY_DOWN)\n\t\tf_DebugPerformanceData = !f_DebugPerformanceData;\n\n\tif (App->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN)\n\t\tShellExecute(NULL, \"open\", \"https:\/\/github.com\/Guille1406\/The-Legend-of-Zelda-Hyrule-Conquest\/issues\", NULL, NULL, SW_SHOWMAXIMIZED);\n\n\tif (f_DebugPerformanceData)\n\t{\n\t\tApp->render->DrawQuad(DebugPerformanceData_Rect, Blue(0), Blue(1), Blue(2), 150, true, true, false);\n\n\t\tfor (int i = 0; i < DebugPerformanceData.size(); i++)\n\t\t{\n\t\t\tswitch (i)\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t\tstatic char AvFPS[25];\n\t\t\t\tsprintf_s(AvFPS, 25, \"Av.FPS: %.2f\", App->avg_fps);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(AvFPS));\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tstatic char LastFrameMs[25];\n\t\t\t\tsprintf_s(LastFrameMs, 25, \"Last Frame Ms: %u\", App->last_frame_ms);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(LastFrameMs));\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tstatic char Lastsecframes[25];\n\t\t\t\tsprintf_s(Lastsecframes, 25, \"Last sec frames: %i\", App->frames_on_last_update);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(Lastsecframes));\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstatic char Lastdt[25];\n\t\t\t\tsprintf_s(Lastdt, 25, \"Last dt: %.3f\", App->dt);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(Lastdt));\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tstatic char Timesincestartup[100];\n\t\t\t\tsprintf_s(Timesincestartup, 100, \"Time since startup: %.3f\", App->seconds_since_startup);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(Timesincestartup));\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tstatic char FrameCount[100];\n\t\t\t\tsprintf_s(FrameCount, 100, \"Frame Count: %lu\", App->frame_count);\n\t\t\t\tDebugPerformanceData[i]->EditLabelStr(&std::string(FrameCount));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDebugPerformanceData[i]->Draw();\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\/\/ Called each loop iteration\nbool j1Camera::PostUpdate()\n{\n\treturn true;\n}\n\n\/\/ Called before quitting\nbool j1Camera::CleanUp()\n{\n\tLOG(\"Freeing camera\");\n\treturn true;\n}\n\nvoid j1Camera::OnGui(Gui* ui, GuiEvent event)\n{\n\n}\n\nvoid j1Camera::OnConsoleCommand(const Command* command, const std::vector<std::string>& commandarguments)\n{\n\n}\n\nvoid j1Camera::OnConsoleCVar(const CVar* cvar)\n{\n\n}<|endoftext|>"} {"text":"<commit_before>#include \"CRUD_Link.h\"\n\n#include \"CRUD_Events.h\"\n\n\/\/ CRUD link receives messages from ServerEndpoint,\n\/\/ these are basically CRUDP_Packets preprocessed by CRUDP_Protocol\n\n\/\/ ServerEndpoint gets new input -> Bytes -> CRUDP_Protocol -> pushq(PacketEvent)\n\/\/ ACE_Reactor knows to wake CRUDLink up, whenever there are new events\n\n\/\/\/\n\/\/\/ \\brief CRUDLink::event_for_packet - convert incoming packet into higher level events and push them to our target()\n\/\/\/ \\param pak_ev - received packet\n\/\/\/\nvoid CRUDLink::event_for_packet(PacketEvent * pak_ev)\n{\n CrudP_Packet *pak=pak_ev->m_pkt;\n \/\/ switch this to while, maybe many events are coming from single packet ?\n CRUDLink_Event *res = factory().EventFromStream(*pak->GetStream());\n if(!res)\n {\n ACE_ERROR((LM_ERROR, ACE_TEXT (\"%p EventFromStream returned NULL\\n\")));\n return;\n }\n res->serializefrom(*pak->GetStream());\n res->src(this);\n res->seq_number = pak->GetSequenceNumber();\n target()->putq(res);\n if(pak->GetStream()->GetReadableBits()>1)\n ACE_DEBUG((LM_WARNING,ACE_TEXT(\"(%P|%t) leftover bits in packet: %s\\n\"),res->info()));\n}\n\/\/\/\n\/\/\/ \\brief CRUDLink::packets_for_event - convert event to 1-n packets and push them to our net_layer()\n\/\/\/ \\param ev - an event that we've received from our downstream.\n\/\/\/\nvoid CRUDLink::packets_for_event(SEGSEvent *ev)\n{\n lCrudP_Packet packets;\n CRUDLink_Event *c_ev =static_cast<CRUDLink_Event *>(ev);\n CrudP_Packet *res = new CrudP_Packet;\n ACE_ASSERT(res);\n ACE_DEBUG((LM_WARNING,ACE_TEXT(\"(%P|%t) packets_for_event %s\\n\"),ev->info()));\n\n c_ev->serializeto(*res->GetStream()); \/\/ serialize packet into res packet\n \/\/ create one or more properly formated CrudP_Packets in the protocol object\n m_protocol.SendPacket(res);\n size_t cnt=m_protocol.GetUnsentPackets(packets);\n \/\/ wrap all packets as PacketEvents and put them on link queue\n while(cnt--)\n {\n net_layer()->putq(new PacketEvent(this,*packets.begin(),peer_addr()));\n packets.pop_front();\n }\n connection_sent_packet(); \/\/ data was sent, update\n}\nint CRUDLink::open (void *p)\n{\n if (EventProcessor::open (p) == -1)\n return -1;\n m_notifier.reactor(reactor()); \/\/ notify reactor with write event,\n msg_queue()->notification_strategy (&m_notifier); \/\/ whenever there is a new event on msg_queue()\n connection_update(); \/\/ record first activity time.\n connection_sent_packet();\n return 0;\n}\nint CRUDLink::handle_output( ACE_HANDLE )\n{\n SEGSEvent *ev;\n ACE_Time_Value nowait (ACE_OS::gettimeofday ());\n while (-1 != getq(ev, &nowait))\n {\n switch(ev->type())\n {\n case SEGS_EventTypes::evFinish:\n ev->release();\n return -1;\n case SEGS_EventTypes::evConnect:\n m_peer_addr=static_cast<ConnectEvent *>(ev)->src_addr;\n connection_update();\n break;\n case SEGS_EventTypes::evDisconnect:\n putq(new SEGSEvent(SEGS_EventTypes::evFinish)); \/\/ close the link\n break;\n case CRUD_EventTypes::evPacket: \/\/ CRUDP_Protocol has posted a pre-parsed packet to us\n event_for_packet(static_cast<PacketEvent *>(ev));\n connection_update(); \/\/ we've received some bytes -> connection update\n break;\n default:\n packets_for_event(static_cast<CRUDLink_Event *>(ev));\n break;\n }\n ev->release();\n \/\/TODO: check how getq works when nowait is before now() ??\n \/\/nowait = ACE_OS::gettimeofday();\n \/\/TODO: consider breaking out of this loop after processing N messages ?\n }\n \/\/ Now if our message queue is empty, we will wait unitl m_notifier awakens us.\n if (msg_queue()->is_empty ()) \/\/ we don't want to be woken up\n reactor()->cancel_wakeup(this, ACE_Event_Handler::WRITE_MASK);\n else \/\/ unless there is something to send still\n reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);\n return 0;\n}\n\/\/\/\n\/\/\/ \\brief CRUDLink::received_block - convert incoming bytes to PacketEvent's\n\/\/\/ \\param bytes - raw data to convert into packets.\n\/\/\/\nvoid CRUDLink::received_block( BitStream &bytes )\n{\n size_t recv_count=0; \/\/ count of proper packets\n \/\/ Fill the protocol with 'raw' bit stream\n m_protocol.ReceivedBlock(bytes);\n \/\/ now try to get actual packets\n CrudP_Packet *pkt = m_protocol.RecvPacket(false);\n while(pkt)\n {\n putq(new PacketEvent(net_layer(),pkt,peer_addr()));\n ++recv_count;\n pkt=m_protocol.RecvPacket(false);\n }\n if(recv_count>0)\n connection_update(); \/\/update the last time we've seen packets on this link\n}\n\n<commit_msg>fix a missed field rename<commit_after>#include \"CRUD_Link.h\"\n\n#include \"CRUD_Events.h\"\n\n\/\/ CRUD link receives messages from ServerEndpoint,\n\/\/ these are basically CRUDP_Packets preprocessed by CRUDP_Protocol\n\n\/\/ ServerEndpoint gets new input -> Bytes -> CRUDP_Protocol -> pushq(PacketEvent)\n\/\/ ACE_Reactor knows to wake CRUDLink up, whenever there are new events\n\n\/\/\/\n\/\/\/ \\brief CRUDLink::event_for_packet - convert incoming packet into higher level events and push them to our target()\n\/\/\/ \\param pak_ev - received packet\n\/\/\/\nvoid CRUDLink::event_for_packet(PacketEvent * pak_ev)\n{\n CrudP_Packet *pak=pak_ev->m_pkt;\n \/\/ switch this to while, maybe many events are coming from single packet ?\n CRUDLink_Event *res = factory().EventFromStream(*pak->GetStream());\n if(!res)\n {\n ACE_ERROR((LM_ERROR, ACE_TEXT (\"%p EventFromStream returned NULL\\n\")));\n return;\n }\n res->serializefrom(*pak->GetStream());\n res->src(this);\n res->m_seq_number = pak->GetSequenceNumber();\n target()->putq(res);\n if(pak->GetStream()->GetReadableBits()>1)\n ACE_DEBUG((LM_WARNING,ACE_TEXT(\"(%P|%t) leftover bits in packet: %s\\n\"),res->info()));\n}\n\/\/\/\n\/\/\/ \\brief CRUDLink::packets_for_event - convert event to 1-n packets and push them to our net_layer()\n\/\/\/ \\param ev - an event that we've received from our downstream.\n\/\/\/\nvoid CRUDLink::packets_for_event(SEGSEvent *ev)\n{\n lCrudP_Packet packets;\n CRUDLink_Event *c_ev =static_cast<CRUDLink_Event *>(ev);\n CrudP_Packet *res = new CrudP_Packet;\n ACE_ASSERT(res);\n ACE_DEBUG((LM_WARNING,ACE_TEXT(\"(%P|%t) packets_for_event %s\\n\"),ev->info()));\n\n c_ev->serializeto(*res->GetStream()); \/\/ serialize packet into res packet\n \/\/ create one or more properly formated CrudP_Packets in the protocol object\n m_protocol.SendPacket(res);\n size_t cnt=m_protocol.GetUnsentPackets(packets);\n \/\/ wrap all packets as PacketEvents and put them on link queue\n while(cnt--)\n {\n net_layer()->putq(new PacketEvent(this,*packets.begin(),peer_addr()));\n packets.pop_front();\n }\n connection_sent_packet(); \/\/ data was sent, update\n}\nint CRUDLink::open (void *p)\n{\n if (EventProcessor::open (p) == -1)\n return -1;\n m_notifier.reactor(reactor()); \/\/ notify reactor with write event,\n msg_queue()->notification_strategy (&m_notifier); \/\/ whenever there is a new event on msg_queue()\n connection_update(); \/\/ record first activity time.\n connection_sent_packet();\n return 0;\n}\nint CRUDLink::handle_output( ACE_HANDLE )\n{\n SEGSEvent *ev;\n ACE_Time_Value nowait (ACE_OS::gettimeofday ());\n while (-1 != getq(ev, &nowait))\n {\n switch(ev->type())\n {\n case SEGS_EventTypes::evFinish:\n ev->release();\n return -1;\n case SEGS_EventTypes::evConnect:\n m_peer_addr=static_cast<ConnectEvent *>(ev)->src_addr;\n connection_update();\n break;\n case SEGS_EventTypes::evDisconnect:\n putq(new SEGSEvent(SEGS_EventTypes::evFinish)); \/\/ close the link\n break;\n case CRUD_EventTypes::evPacket: \/\/ CRUDP_Protocol has posted a pre-parsed packet to us\n event_for_packet(static_cast<PacketEvent *>(ev));\n connection_update(); \/\/ we've received some bytes -> connection update\n break;\n default:\n packets_for_event(static_cast<CRUDLink_Event *>(ev));\n break;\n }\n ev->release();\n \/\/TODO: check how getq works when nowait is before now() ??\n \/\/nowait = ACE_OS::gettimeofday();\n \/\/TODO: consider breaking out of this loop after processing N messages ?\n }\n \/\/ Now if our message queue is empty, we will wait unitl m_notifier awakens us.\n if (msg_queue()->is_empty ()) \/\/ we don't want to be woken up\n reactor()->cancel_wakeup(this, ACE_Event_Handler::WRITE_MASK);\n else \/\/ unless there is something to send still\n reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);\n return 0;\n}\n\/\/\/\n\/\/\/ \\brief CRUDLink::received_block - convert incoming bytes to PacketEvent's\n\/\/\/ \\param bytes - raw data to convert into packets.\n\/\/\/\nvoid CRUDLink::received_block( BitStream &bytes )\n{\n size_t recv_count=0; \/\/ count of proper packets\n \/\/ Fill the protocol with 'raw' bit stream\n m_protocol.ReceivedBlock(bytes);\n \/\/ now try to get actual packets\n CrudP_Packet *pkt = m_protocol.RecvPacket(false);\n while(pkt)\n {\n putq(new PacketEvent(net_layer(),pkt,peer_addr()));\n ++recv_count;\n pkt=m_protocol.RecvPacket(false);\n }\n if(recv_count>0)\n connection_update(); \/\/update the last time we've seen packets on this link\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2012, Willow Garage, Inc.\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 Willow Garage 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\/* Author: Ioan Sucan *\/\n\n#include <moveit\/move_group_interface\/move_group.h>\n#include <moveit\/py_bindings_tools\/roscpp_initializer.h>\n#include <moveit\/py_bindings_tools\/py_conversions.h>\n#include <eigen_conversions\/eigen_msg.h>\n\n#include <boost\/function.hpp>\n#include <boost\/python.hpp>\n#include <boost\/python\/return_value_policy.hpp>\n#include <boost\/python\/stl_iterator.hpp>\n#include <boost\/python\/suite\/indexing\/vector_indexing_suite.hpp>\n#include <boost\/python\/suite\/indexing\/map_indexing_suite.hpp>\n\n#include <boost\/shared_ptr.hpp>\n#include <Python.h>\n#include <ros\/ros.h>\n#include <boost\/thread.hpp>\n\nnamespace bp = boost::python;\n\nnamespace move_group_interface\n{\n\nclass MoveGroupWrapper : protected moveit_py_bindings_tools::ROScppInitializer,\n public MoveGroup\n{\npublic:\n\n \/\/ ROSInitializer is constructed first, and ensures ros::init() was called, if needed\n MoveGroupWrapper(const std::string &group_name) : moveit_py_bindings_tools::ROScppInitializer(),\n MoveGroup(group_name, boost::shared_ptr<tf::Transformer>(), ros::Duration(5, 0))\n {\n }\n \n void setJointValueTargetPerJointPythonList(const std::string &joint, bp::list &values)\n {\n setJointValueTarget(joint, moveit_py_bindings_tools::doubleFromList(values));\n }\n \n void setJointValueTargetPythonList(bp::list &values)\n {\n setJointValueTarget(moveit_py_bindings_tools::doubleFromList(values));\n }\n\n void setJointValueTargetPythonDict(bp::dict &values)\n {\n bp::list k = values.keys(); \n int l = bp::len(k);\n std::map<std::string, double> v;\n for (int i = 0; i < l ; ++i)\n v[bp::extract<std::string>(k[i])] = bp::extract<double>(values[k[i]]);\n setJointValueTarget(v);\n }\n \n void rememberJointValuesFromPythonList(const std::string &string, bp::list &values)\n {\n rememberJointValues(string, moveit_py_bindings_tools::doubleFromList(values));\n }\n\n bp::list getJointsList(void)\n {\n return moveit_py_bindings_tools::listFromString(getJoints());\n }\n\n bp::list getCurrentJointValuesList(void)\n {\n return moveit_py_bindings_tools::listFromDouble(getCurrentJointValues());\n }\n \n bp::list getRandomJointValuesList(void)\n {\n return moveit_py_bindings_tools::listFromDouble(getRandomJointValues());\n }\n \n bp::dict getRememberedJointValuesPython(void) const\n {\n const std::map<std::string, std::vector<double> > &rv = getRememberedJointValues();\n bp::dict d;\n for (std::map<std::string, std::vector<double> >::const_iterator it = rv.begin() ; it != rv.end() ; ++it)\n d[it->first] = moveit_py_bindings_tools::listFromDouble(it->second);\n return d;\n }\n \n bp::list getCurrentPosePython(const std::string &end_effector_link)\n {\n geometry_msgs::PoseStamped pose = getCurrentPose(end_effector_link);\n std::vector<double> v(6);\n v[0] = pose.pose.position.x;\n v[1] = pose.pose.position.y;\n v[2] = pose.pose.position.z;\n Eigen::Quaterniond q;\n tf::quaternionMsgToEigen(pose.pose.orientation, q);\n Eigen::Vector3d r = Eigen::Matrix3d(q).eulerAngles(0, 1, 2); \/\/ XYZ\n v[3] = r(0);\n v[4] = r(1);\n v[5] = r(2);\n return moveit_py_bindings_tools::listFromDouble(v);\n }\n\n bp::list getKnownConstraintsList(void) const\n {\n return moveit_py_bindings_tools::listFromString(getKnownConstraints());\n }\n \n void setPoseTargetPython(bp::list &pose, const std::string &end_effector_link)\n {\n std::vector<double> v = moveit_py_bindings_tools::doubleFromList(pose);\n if (v.size() == 6)\n {\n setPositionTarget(v[0], v[1], v[2], end_effector_link);\n setOrientationTarget(v[3], v[4], v[5], end_effector_link);\n }\n else\n if (v.size() == 7)\n {\n setPositionTarget(v[0], v[1], v[2], end_effector_link);\n setOrientationTarget(v[3], v[4], v[5], v[6], end_effector_link);\n }\n else\n ROS_ERROR(\"Pose description expected to consist of either 6 or 7 values\");\n }\n\n const char* getEndEffectorLinkCStr(void) const\n {\n return getEndEffectorLink().c_str();\n } \n \n const char* getPoseReferenceFrameCStr(void) const\n {\n return getPoseReferenceFrame().c_str();\n }\n \n const char* getNameCStr(void) const\n {\n return getName().c_str();\n }\n\n bp::dict getPlanPythonDict(void)\n {\n MoveGroup::Plan plan;\n MoveGroup::plan(plan);\n bp::list joint_names = moveit_py_bindings_tools::listFromString(plan.trajectory_.joint_trajectory.joint_names);\n bp::dict plan_dict, joint_trajectory, multi_dof_joint_trajectory;\n joint_trajectory[\"joint_names\"] = joint_names;\n multi_dof_joint_trajectory[\"joint_names\"] = joint_names;\n bp::list joint_traj_points, multi_dof_traj_points, poses;\n bp::dict joint_traj_point, multi_dof_traj_point, pose, position, orientation;\n\n for (std::vector<trajectory_msgs::JointTrajectoryPoint>::const_iterator it = plan.trajectory_.joint_trajectory.points.begin() ; it != plan.trajectory_.joint_trajectory.points.end() ; ++it)\n {\n joint_traj_point[\"positions\"] = moveit_py_bindings_tools::listFromDouble(it->positions);\n joint_traj_point[\"velocities\"] = moveit_py_bindings_tools::listFromDouble(it->velocities);\n joint_traj_point[\"accelerations\"] = moveit_py_bindings_tools::listFromDouble(it->accelerations);\n joint_traj_points.append(joint_traj_point);\n }\n\n joint_trajectory[\"points\"] = joint_traj_points;\n \n bp::list frame_ids = moveit_py_bindings_tools::listFromString(plan.trajectory_.multi_dof_joint_trajectory.frame_ids);\n bp::list child_frame_ids = moveit_py_bindings_tools::listFromString(plan.trajectory_.multi_dof_joint_trajectory.child_frame_ids);\n multi_dof_joint_trajectory[\"frame_ids\"] = frame_ids;\n multi_dof_joint_trajectory[\"child_frame_ids\"] = child_frame_ids;\n\n for (std::vector<moveit_msgs::MultiDOFJointTrajectoryPoint>::const_iterator it = plan.trajectory_.multi_dof_joint_trajectory.points.begin() ; it != plan.trajectory_.multi_dof_joint_trajectory.points.end() ; ++it)\n {\n for (std::vector<geometry_msgs::Pose>::const_iterator itr = it->poses.begin() ; itr != it->poses.end() ; ++itr)\n {\n position[\"x\"] = itr->position.x;\n position[\"y\"] = itr->position.y;\n position[\"z\"] = itr->position.z;\n pose[\"position\"] = position;\n\n orientation[\"x\"] = itr->orientation.x;\n orientation[\"y\"] = itr->orientation.y;\n orientation[\"z\"] = itr->orientation.z;\n orientation[\"w\"] = itr->orientation.w;\n pose[\"orientation\"] = orientation;\n poses.append(pose);\n }\n multi_dof_traj_point[\"poses\"] = poses;\n multi_dof_traj_points.append(multi_dof_traj_point);\n }\n \n multi_dof_joint_trajectory[\"points\"] = multi_dof_traj_points;\n\n plan_dict[\"joint_trajectory\"] = joint_trajectory;\n plan_dict[\"multi_dof_joint_trajectory\"] = multi_dof_joint_trajectory;\n return plan_dict;\n }\n\n}; \n \nvoid wrap_move_group_interface()\n{\n bp::class_<MoveGroupWrapper> MoveGroupClass(\"MoveGroup\", bp::init<std::string>());\n\n MoveGroupClass.def(\"async_move\", &MoveGroupWrapper::asyncMove);\n MoveGroupClass.def(\"move\", &MoveGroupWrapper::move);\n MoveGroupClass.def(\"execute\", &MoveGroupWrapper::execute);\n MoveGroupClass.def(\"stop\", &MoveGroupWrapper::stop);\n\n MoveGroupClass.def(\"get_name\", &MoveGroupWrapper::getNameCStr);\n MoveGroupClass.def(\"get_joints\", &MoveGroupWrapper::getJointsList);\n MoveGroupClass.def(\"allow_looking\", &MoveGroupWrapper::allowLooking);\n MoveGroupClass.def(\"allow_replanning\", &MoveGroupWrapper::allowReplanning);\n \n MoveGroupClass.def(\"set_pose_reference_frame\", &MoveGroupWrapper::setPoseReferenceFrame);\n \n MoveGroupClass.def(\"set_pose_reference_frame\", &MoveGroupWrapper::setPoseReferenceFrame);\n MoveGroupClass.def(\"set_end_effector_link\", &MoveGroupWrapper::setEndEffectorLink);\n MoveGroupClass.def(\"get_end_effector_link\", &MoveGroupWrapper::getEndEffectorLinkCStr);\n MoveGroupClass.def(\"get_pose_reference_frame\", &MoveGroupWrapper::getPoseReferenceFrameCStr);\n \n void (MoveGroupWrapper::*setPoseTarget_1)(const geometry_msgs::PoseStamped &, const std::string&) = &MoveGroupWrapper::setPoseTarget;\n MoveGroupClass.def(\"set_pose_target\", setPoseTarget_1);\n\n void (MoveGroupWrapper::*setPoseTarget_2)(const geometry_msgs::Pose &, const std::string&) = &MoveGroupWrapper::setPoseTarget;\n MoveGroupClass.def(\"set_pose_target\", setPoseTarget_2);\n\n MoveGroupClass.def(\"set_pose_target\", &MoveGroupWrapper::setPoseTargetPython);\n\n MoveGroupClass.def(\"set_position_target\", &MoveGroupWrapper::setPositionTarget);\n \n void (MoveGroupWrapper::*setOrientationTarget_1)(double, double, double, const std::string&) = &MoveGroupWrapper::setOrientationTarget;\n MoveGroupClass.def(\"set_orientation_target\", setOrientationTarget_1);\n\n void (MoveGroupWrapper::*setOrientationTarget_2)(double, double, double, double, const std::string&) = &MoveGroupWrapper::setOrientationTarget;\n MoveGroupClass.def(\"set_orientation_target\", setOrientationTarget_2);\n \n MoveGroupClass.def(\"get_current_pose\", &MoveGroupWrapper::getCurrentPosePython);\n\n MoveGroupClass.def(\"clear_pose_target\", &MoveGroupWrapper::clearPoseTarget);\n MoveGroupClass.def(\"clear_pose_targets\", &MoveGroupWrapper::clearPoseTargets);\n\n MoveGroupClass.def(\"set_joint_value_target\", &MoveGroupWrapper::setJointValueTargetPythonList);\n MoveGroupClass.def(\"set_joint_value_target\", &MoveGroupWrapper::setJointValueTargetPythonDict);\n MoveGroupClass.def(\"set_joint_value_target\", &MoveGroupWrapper::setJointValueTargetPerJointPythonList);\n void (MoveGroupWrapper::*setJointValueTarget_4)(const std::string&, double) = &MoveGroupWrapper::setJointValueTarget;\n MoveGroupClass.def(\"set_joint_value_target\", setJointValueTarget_4);\n\n void (MoveGroupWrapper::*setJointValueTarget_5)(const sensor_msgs::JointState &) = &MoveGroupWrapper::setJointValueTarget;\n MoveGroupClass.def(\"set_joint_value_target\", setJointValueTarget_5);\n\n MoveGroupClass.def(\"set_named_target\", &MoveGroupWrapper::setNamedTarget); \n MoveGroupClass.def(\"set_random_target\", &MoveGroupWrapper::setRandomTarget); \n\n void (MoveGroupWrapper::*rememberJointValues_2)(const std::string&) = &MoveGroupWrapper::rememberJointValues;\n MoveGroupClass.def(\"remember_joint_values\", rememberJointValues_2);\n \n MoveGroupClass.def(\"remember_joint_values\", &MoveGroupWrapper::rememberJointValuesFromPythonList);\n\n MoveGroupClass.def(\"get_current_joint_values\", &MoveGroupWrapper::getCurrentJointValuesList);\n MoveGroupClass.def(\"get_random_joint_values\", &MoveGroupWrapper::getRandomJointValuesList);\n MoveGroupClass.def(\"get_remembered_joint_values\", &MoveGroupWrapper::getRememberedJointValuesPython);\n\n MoveGroupClass.def(\"forget_joint_values\", &MoveGroupWrapper::forgetJointValues); \n\n MoveGroupClass.def(\"get_goal_tolerance\", &MoveGroupWrapper::getGoalTolerance); \n MoveGroupClass.def(\"set_goal_tolerance\", &MoveGroupWrapper::setGoalTolerance); \n\n MoveGroupClass.def(\"set_path_constraints\", &MoveGroupWrapper::setPathConstraints); \n MoveGroupClass.def(\"clear_path_constraints\", &MoveGroupWrapper::clearPathConstraints); \n MoveGroupClass.def(\"get_known_constraints\", &MoveGroupWrapper::getKnownConstraintsList);\n MoveGroupClass.def(\"set_constraints_database\", &MoveGroupWrapper::setConstraintsDatabase); \n MoveGroupClass.def(\"set_workspace\", &MoveGroupWrapper::setWorkspace);\n MoveGroupClass.def(\"set_planning_time\", &MoveGroupWrapper::setPlanningTime);\n MoveGroupClass.def(\"get_plan\", &MoveGroupWrapper::getPlanPythonDict);\n}\n\n}\n\nBOOST_PYTHON_MODULE(_moveit_move_group_interface)\n{\n using namespace move_group_interface;\n wrap_move_group_interface();\n}\n<commit_msg>fix #39 to some extent<commit_after>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2012, Willow Garage, Inc.\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 Willow Garage 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\/* Author: Ioan Sucan *\/\n\n#include <moveit\/move_group_interface\/move_group.h>\n#include <moveit\/py_bindings_tools\/roscpp_initializer.h>\n#include <moveit\/py_bindings_tools\/py_conversions.h>\n#include <eigen_conversions\/eigen_msg.h>\n\n#include <boost\/function.hpp>\n#include <boost\/python.hpp>\n#include <boost\/python\/return_value_policy.hpp>\n#include <boost\/python\/stl_iterator.hpp>\n#include <boost\/python\/suite\/indexing\/vector_indexing_suite.hpp>\n#include <boost\/python\/suite\/indexing\/map_indexing_suite.hpp>\n\n#include <boost\/shared_ptr.hpp>\n#include <Python.h>\n#include <ros\/ros.h>\n#include <boost\/thread.hpp>\n\nnamespace bp = boost::python;\n\nnamespace move_group_interface\n{\n\nclass MoveGroupWrapper : protected moveit_py_bindings_tools::ROScppInitializer,\n public MoveGroup\n{\npublic:\n\n \/\/ ROSInitializer is constructed first, and ensures ros::init() was called, if needed\n MoveGroupWrapper(const std::string &group_name) : moveit_py_bindings_tools::ROScppInitializer(),\n MoveGroup(group_name, boost::shared_ptr<tf::Transformer>(), ros::Duration(5, 0))\n {\n }\n \n void setJointValueTargetPerJointPythonList(const std::string &joint, bp::list &values)\n {\n setJointValueTarget(joint, moveit_py_bindings_tools::doubleFromList(values));\n }\n \n void setJointValueTargetPythonList(bp::list &values)\n {\n setJointValueTarget(moveit_py_bindings_tools::doubleFromList(values));\n }\n\n void setJointValueTargetPythonDict(bp::dict &values)\n {\n bp::list k = values.keys(); \n int l = bp::len(k);\n std::map<std::string, double> v;\n for (int i = 0; i < l ; ++i)\n v[bp::extract<std::string>(k[i])] = bp::extract<double>(values[k[i]]);\n setJointValueTarget(v);\n }\n \n void rememberJointValuesFromPythonList(const std::string &string, bp::list &values)\n {\n rememberJointValues(string, moveit_py_bindings_tools::doubleFromList(values));\n }\n\n bp::list getJointsList(void)\n {\n return moveit_py_bindings_tools::listFromString(getJoints());\n }\n\n bp::list getCurrentJointValuesList(void)\n {\n return moveit_py_bindings_tools::listFromDouble(getCurrentJointValues());\n }\n \n bp::list getRandomJointValuesList(void)\n {\n return moveit_py_bindings_tools::listFromDouble(getRandomJointValues());\n }\n \n bp::dict getRememberedJointValuesPython(void) const\n {\n const std::map<std::string, std::vector<double> > &rv = getRememberedJointValues();\n bp::dict d;\n for (std::map<std::string, std::vector<double> >::const_iterator it = rv.begin() ; it != rv.end() ; ++it)\n d[it->first] = moveit_py_bindings_tools::listFromDouble(it->second);\n return d;\n }\n \n bp::list getCurrentPosePython(const std::string &end_effector_link = \"\")\n {\n geometry_msgs::PoseStamped pose = getCurrentPose(end_effector_link);\n std::vector<double> v(6);\n v[0] = pose.pose.position.x;\n v[1] = pose.pose.position.y;\n v[2] = pose.pose.position.z;\n Eigen::Quaterniond q;\n tf::quaternionMsgToEigen(pose.pose.orientation, q);\n Eigen::Vector3d r = Eigen::Matrix3d(q).eulerAngles(0, 1, 2); \/\/ XYZ\n v[3] = r(0);\n v[4] = r(1);\n v[5] = r(2);\n return moveit_py_bindings_tools::listFromDouble(v);\n }\n\n bp::list getKnownConstraintsList(void) const\n {\n return moveit_py_bindings_tools::listFromString(getKnownConstraints());\n }\n\n void convertToArrayOfPoses(bp::list &poses, std::vector<geometry_msgs::Pose> &msg)\n { \n int l = bp::len(poses);\n for (int i = 0; i < l ; ++i)\n {\n bp::list pose = bp::extract<bp::list>(poses[i]);\n std::vector<double> v = moveit_py_bindings_tools::doubleFromList(pose);\n if (v.size() == 6 || v.size() == 7)\n {\n Eigen::Affine3d p = v.size() == 6 ? \n Eigen::Affine3d(Eigen::AngleAxisd(v[3], Eigen::Vector3d::UnitX())\n * Eigen::AngleAxisd(v[4], Eigen::Vector3d::UnitY())\n * Eigen::AngleAxisd(v[5], Eigen::Vector3d::UnitZ())) :\n Eigen::Affine3d(Eigen::Quaterniond(v[6], v[3], v[4], v[5]));\n p.translation() = Eigen::Vector3d(v[0], v[1], v[2]);\n geometry_msgs::Pose pm;\n tf::poseEigenToMsg(p, pm);\n msg.push_back(pm);\n }\n else\n ROS_WARN(\"Incorrect number of values for a pose: %u\", (unsigned int)v.size());\n }\n }\n \n void setPoseTargetsPython(bp::list &poses, const std::string &end_effector_link = \"\")\n {\n std::vector<geometry_msgs::Pose> msg;\n convertToArrayOfPoses(poses, msg);\n setPoseTargets(msg, end_effector_link);\n }\n\n void followConstraintsPython(bp::list &poses, const std::string &end_effector_link = \"\")\n {\n std::vector<geometry_msgs::Pose> msg;\n convertToArrayOfPoses(poses, msg);\n followConstraints(msg, 1e-3, 1e-2, end_effector_link);\n }\n \n void setPoseTargetPython(bp::list &pose, const std::string &end_effector_link = \"\")\n {\n std::vector<double> v = moveit_py_bindings_tools::doubleFromList(pose);\n if (v.size() == 6)\n {\n setPositionTarget(v[0], v[1], v[2], end_effector_link);\n setOrientationTarget(v[3], v[4], v[5], end_effector_link);\n }\n else\n if (v.size() == 7)\n {\n setPositionTarget(v[0], v[1], v[2], end_effector_link);\n setOrientationTarget(v[3], v[4], v[5], v[6], end_effector_link);\n }\n else\n ROS_ERROR(\"Pose description expected to consist of either 6 or 7 values\");\n }\n\n const char* getEndEffectorLinkCStr(void) const\n {\n return getEndEffectorLink().c_str();\n } \n \n const char* getPoseReferenceFrameCStr(void) const\n {\n return getPoseReferenceFrame().c_str();\n }\n \n const char* getNameCStr(void) const\n {\n return getName().c_str();\n }\n\n bp::dict getPlanPythonDict(void)\n {\n MoveGroup::Plan plan;\n MoveGroup::plan(plan);\n bp::list joint_names = moveit_py_bindings_tools::listFromString(plan.trajectory_.joint_trajectory.joint_names);\n bp::dict plan_dict, joint_trajectory, multi_dof_joint_trajectory;\n joint_trajectory[\"joint_names\"] = joint_names;\n multi_dof_joint_trajectory[\"joint_names\"] = joint_names;\n bp::list joint_traj_points, multi_dof_traj_points, poses;\n bp::dict joint_traj_point, multi_dof_traj_point, pose, position, orientation;\n\n for (std::vector<trajectory_msgs::JointTrajectoryPoint>::const_iterator it = plan.trajectory_.joint_trajectory.points.begin() ;\n it != plan.trajectory_.joint_trajectory.points.end() ; ++it)\n {\n joint_traj_point[\"positions\"] = moveit_py_bindings_tools::listFromDouble(it->positions);\n joint_traj_point[\"velocities\"] = moveit_py_bindings_tools::listFromDouble(it->velocities);\n joint_traj_point[\"accelerations\"] = moveit_py_bindings_tools::listFromDouble(it->accelerations);\n joint_traj_points.append(joint_traj_point);\n }\n\n joint_trajectory[\"points\"] = joint_traj_points;\n \n bp::list frame_ids = moveit_py_bindings_tools::listFromString(plan.trajectory_.multi_dof_joint_trajectory.frame_ids);\n bp::list child_frame_ids = moveit_py_bindings_tools::listFromString(plan.trajectory_.multi_dof_joint_trajectory.child_frame_ids);\n multi_dof_joint_trajectory[\"frame_ids\"] = frame_ids;\n multi_dof_joint_trajectory[\"child_frame_ids\"] = child_frame_ids;\n\n for (std::vector<moveit_msgs::MultiDOFJointTrajectoryPoint>::const_iterator it = plan.trajectory_.multi_dof_joint_trajectory.points.begin() ;\n it != plan.trajectory_.multi_dof_joint_trajectory.points.end() ; ++it)\n {\n for (std::vector<geometry_msgs::Pose>::const_iterator itr = it->poses.begin() ; itr != it->poses.end() ; ++itr)\n {\n position[\"x\"] = itr->position.x;\n position[\"y\"] = itr->position.y;\n position[\"z\"] = itr->position.z;\n pose[\"position\"] = position;\n\n orientation[\"x\"] = itr->orientation.x;\n orientation[\"y\"] = itr->orientation.y;\n orientation[\"z\"] = itr->orientation.z;\n orientation[\"w\"] = itr->orientation.w;\n pose[\"orientation\"] = orientation;\n poses.append(pose);\n }\n multi_dof_traj_point[\"poses\"] = poses;\n multi_dof_traj_points.append(multi_dof_traj_point);\n }\n \n multi_dof_joint_trajectory[\"points\"] = multi_dof_traj_points;\n\n plan_dict[\"joint_trajectory\"] = joint_trajectory;\n plan_dict[\"multi_dof_joint_trajectory\"] = multi_dof_joint_trajectory;\n return plan_dict;\n }\n\n}; \n \nvoid wrap_move_group_interface()\n{\n bp::class_<MoveGroupWrapper> MoveGroupClass(\"MoveGroup\", bp::init<std::string>());\n\n MoveGroupClass.def(\"async_move\", &MoveGroupWrapper::asyncMove);\n MoveGroupClass.def(\"move\", &MoveGroupWrapper::move);\n MoveGroupClass.def(\"execute\", &MoveGroupWrapper::execute);\n MoveGroupClass.def(\"stop\", &MoveGroupWrapper::stop);\n\n MoveGroupClass.def(\"get_name\", &MoveGroupWrapper::getNameCStr);\n MoveGroupClass.def(\"get_joints\", &MoveGroupWrapper::getJointsList);\n MoveGroupClass.def(\"allow_looking\", &MoveGroupWrapper::allowLooking);\n MoveGroupClass.def(\"allow_replanning\", &MoveGroupWrapper::allowReplanning);\n \n MoveGroupClass.def(\"set_pose_reference_frame\", &MoveGroupWrapper::setPoseReferenceFrame);\n \n MoveGroupClass.def(\"set_pose_reference_frame\", &MoveGroupWrapper::setPoseReferenceFrame);\n MoveGroupClass.def(\"set_end_effector_link\", &MoveGroupWrapper::setEndEffectorLink);\n MoveGroupClass.def(\"get_end_effector_link\", &MoveGroupWrapper::getEndEffectorLinkCStr);\n MoveGroupClass.def(\"get_pose_reference_frame\", &MoveGroupWrapper::getPoseReferenceFrameCStr);\n \n void (MoveGroupWrapper::*setPoseTarget_1)(const geometry_msgs::PoseStamped &, const std::string&) = &MoveGroupWrapper::setPoseTarget;\n MoveGroupClass.def(\"set_pose_target\", setPoseTarget_1);\n\n void (MoveGroupWrapper::*setPoseTarget_2)(const geometry_msgs::Pose &, const std::string&) = &MoveGroupWrapper::setPoseTarget;\n MoveGroupClass.def(\"set_pose_target\", setPoseTarget_2);\n\n MoveGroupClass.def(\"set_pose_target\", &MoveGroupWrapper::setPoseTargetPython);\n\n MoveGroupClass.def(\"set_pose_targets\", &MoveGroupWrapper::setPoseTargetsPython);\n\n MoveGroupClass.def(\"set_position_target\", &MoveGroupWrapper::setPositionTarget);\n \n void (MoveGroupWrapper::*setOrientationTarget_1)(double, double, double, const std::string&) = &MoveGroupWrapper::setOrientationTarget;\n MoveGroupClass.def(\"set_orientation_target\", setOrientationTarget_1);\n\n void (MoveGroupWrapper::*setOrientationTarget_2)(double, double, double, double, const std::string&) = &MoveGroupWrapper::setOrientationTarget;\n MoveGroupClass.def(\"set_orientation_target\", setOrientationTarget_2);\n \n MoveGroupClass.def(\"get_current_pose\", &MoveGroupWrapper::getCurrentPosePython);\n\n MoveGroupClass.def(\"clear_pose_target\", &MoveGroupWrapper::clearPoseTarget);\n MoveGroupClass.def(\"clear_pose_targets\", &MoveGroupWrapper::clearPoseTargets);\n\n MoveGroupClass.def(\"set_joint_value_target\", &MoveGroupWrapper::setJointValueTargetPythonList);\n MoveGroupClass.def(\"set_joint_value_target\", &MoveGroupWrapper::setJointValueTargetPythonDict);\n MoveGroupClass.def(\"set_joint_value_target\", &MoveGroupWrapper::setJointValueTargetPerJointPythonList);\n void (MoveGroupWrapper::*setJointValueTarget_4)(const std::string&, double) = &MoveGroupWrapper::setJointValueTarget;\n MoveGroupClass.def(\"set_joint_value_target\", setJointValueTarget_4);\n\n void (MoveGroupWrapper::*setJointValueTarget_5)(const sensor_msgs::JointState &) = &MoveGroupWrapper::setJointValueTarget;\n MoveGroupClass.def(\"set_joint_value_target\", setJointValueTarget_5);\n\n MoveGroupClass.def(\"set_named_target\", &MoveGroupWrapper::setNamedTarget); \n MoveGroupClass.def(\"set_random_target\", &MoveGroupWrapper::setRandomTarget); \n\n MoveGroupClass.def(\"follow_constraints\", &MoveGroupWrapper::followConstraintsPython);\n \n void (MoveGroupWrapper::*rememberJointValues_2)(const std::string&) = &MoveGroupWrapper::rememberJointValues;\n MoveGroupClass.def(\"remember_joint_values\", rememberJointValues_2);\n \n MoveGroupClass.def(\"remember_joint_values\", &MoveGroupWrapper::rememberJointValuesFromPythonList);\n\n MoveGroupClass.def(\"get_current_joint_values\", &MoveGroupWrapper::getCurrentJointValuesList);\n MoveGroupClass.def(\"get_random_joint_values\", &MoveGroupWrapper::getRandomJointValuesList);\n MoveGroupClass.def(\"get_remembered_joint_values\", &MoveGroupWrapper::getRememberedJointValuesPython);\n\n MoveGroupClass.def(\"forget_joint_values\", &MoveGroupWrapper::forgetJointValues); \n\n MoveGroupClass.def(\"get_goal_tolerance\", &MoveGroupWrapper::getGoalTolerance); \n MoveGroupClass.def(\"set_goal_tolerance\", &MoveGroupWrapper::setGoalTolerance); \n\n MoveGroupClass.def(\"set_path_constraints\", &MoveGroupWrapper::setPathConstraints); \n MoveGroupClass.def(\"clear_path_constraints\", &MoveGroupWrapper::clearPathConstraints); \n MoveGroupClass.def(\"get_known_constraints\", &MoveGroupWrapper::getKnownConstraintsList);\n MoveGroupClass.def(\"set_constraints_database\", &MoveGroupWrapper::setConstraintsDatabase); \n MoveGroupClass.def(\"set_workspace\", &MoveGroupWrapper::setWorkspace);\n MoveGroupClass.def(\"set_planning_time\", &MoveGroupWrapper::setPlanningTime);\n MoveGroupClass.def(\"get_plan\", &MoveGroupWrapper::getPlanPythonDict);\n}\n\n}\n\nBOOST_PYTHON_MODULE(_moveit_move_group_interface)\n{\n using namespace move_group_interface;\n wrap_move_group_interface();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef FIXEDPOINTHELPERS_HPP\n#define FIXEDPOINTHELPERS_HPP\n#include <cmath>\n#include <limits.h>\n\nnamespace FixedPointHelpers {\n constexpr double dipow_accum(double base, int exponent, double accum) {\n return exponent == 0 ? accum :\n exponent < 0 ? dipow_accum(base, exponent + 1, accum \/ base):\n dipow_accum(base, exponent - 1, accum * base);\n }\n\n constexpr double dipow(double base, int exponent) {\n return dipow_accum(base, exponent, 1.);\n }\n\n constexpr int ilogb(double v) {\n return v < 0 ? ilogb(-v) :\n std::isnan(v) ? 0 :\n std::isinf(v) ? INT_MAX :\n v == 0 ? INT_MIN :\n v < 1 ? ilogb(v*2)-1 :\n v >= 2 ? ilogb(v\/2) + 1 :\n 0;\n }\n}\n#endif \/\/ FIXEDPOINTHELPERS_HPP\n<commit_msg>Make dipow_accum legible<commit_after>#ifndef FIXEDPOINTHELPERS_HPP\n#define FIXEDPOINTHELPERS_HPP\n#include <cmath>\n#include <limits.h>\n\nnamespace FixedPointHelpers {\n constexpr double dipow_accum(double base, int exponent, double accum) {\n if (exponent == 0) {\n return accum;\n }\n if (exponent < 0) {\n return dipow_accum(base, exponent + 1, accum \/ base);\n }\n\n return dipow_accum(base, exponent - 1, accum * base);\n }\n\n constexpr double dipow(double base, int exponent) {\n return dipow_accum(base, exponent, 1.);\n }\n\n constexpr int ilogb(double v) {\n return v < 0 ? ilogb(-v) :\n std::isnan(v) ? 0 :\n std::isinf(v) ? INT_MAX :\n v == 0 ? INT_MIN :\n v < 1 ? ilogb(v*2)-1 :\n v >= 2 ? ilogb(v\/2) + 1 :\n 0;\n }\n}\n#endif \/\/ FIXEDPOINTHELPERS_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"realloc.hpp\"\n#include <windows.h>\n\nvoid *realloc(void *block, size_t size)\n{\n if (block)\n return HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,block,size);\n else\n return HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,size);\n}\n<commit_msg>update realloc<commit_after>#include \"realloc.hpp\"\n#include <windows.h>\n\nvoid *realloc(void *block, size_t size)\n{\n if (!size)\n {\n if (block)\n HeapFree(GetProcessHeap(),0,block);\n return NULL;\n }\n\n if (block)\n return HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,block,size);\n else\n return HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,size);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Renderer module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Renderer\/RenderStates.hpp>\n#include <Nazara\/Core\/Algorithm.hpp>\n#include <Nazara\/Math\/Algorithm.hpp>\n#include <functional>\n#include <Nazara\/Renderer\/Debug.hpp>\n\nnamespace Nz\n{\n\tbool operator==(const RenderStates& lhs, const RenderStates& rhs)\n\t{\n\t\t#define NazaraRenderStateMember(field) if (lhs.field != rhs.field) return false\n\t\t#define NazaraRenderStateBoolMember NazaraRenderStateMember\n\t\t#define NazaraRenderStateFloatMember(field, maxDiff) if (!NumberEquals(lhs.field, rhs.field, maxDiff)) return false\n\n\t\tNazaraRenderStateBoolMember(blending);\n\t\tNazaraRenderStateBoolMember(colorWrite);\n\t\tNazaraRenderStateBoolMember(depthBuffer);\n\t\tNazaraRenderStateBoolMember(faceCulling);\n\t\tNazaraRenderStateBoolMember(scissorTest);\n\t\tNazaraRenderStateBoolMember(stencilTest);\n\n\t\tif (lhs.depthBuffer)\n\t\t\tNazaraRenderStateBoolMember(depthWrite);\n\n\t\tNazaraRenderStateMember(faceFilling);\n\n\t\tif (lhs.blending) \/\/< Remember, at this time we know lhs.blending == rhs.blending\n\t\t{\n\t\t\tNazaraRenderStateMember(dstBlend);\n\t\t\tNazaraRenderStateMember(srcBlend);\n\t\t}\n\n\t\tif (lhs.depthBuffer)\n\t\t\tNazaraRenderStateMember(depthFunc);\n\n\t\tif (lhs.faceCulling)\n\t\t\tNazaraRenderStateMember(cullingSide);\n\n\t\tif (lhs.stencilTest)\n\t\t{\n\t\t\tNazaraRenderStateMember(stencilCompare.back);\n\t\t\tNazaraRenderStateMember(stencilCompare.front);\n\t\t\tNazaraRenderStateMember(stencilCompareMask.back);\n\t\t\tNazaraRenderStateMember(stencilCompareMask.front);\n\t\t\tNazaraRenderStateMember(stencilDepthFail.back);\n\t\t\tNazaraRenderStateMember(stencilDepthFail.front);\n\t\t\tNazaraRenderStateMember(stencilFail.back);\n\t\t\tNazaraRenderStateMember(stencilFail.front);\n\t\t\tNazaraRenderStateMember(stencilPass.back);\n\t\t\tNazaraRenderStateMember(stencilPass.front);\n\t\t\tNazaraRenderStateMember(stencilReference.back);\n\t\t\tNazaraRenderStateMember(stencilReference.front);\n\t\t\tNazaraRenderStateMember(stencilWriteMask.back);\n\t\t\tNazaraRenderStateMember(stencilWriteMask.front);\n\t\t}\n\n\t\tNazaraRenderStateFloatMember(lineWidth, 0.001f);\n\t\tNazaraRenderStateFloatMember(pointSize, 0.001f);\n\n\t\t#undef NazaraRenderStateMember\n\t\t#undef NazaraRenderStateBoolMember\n\t\t#undef NazaraRenderStateFloatMember\n\n\t\treturn true;\n\t}\n}\n\nnamespace std\n{\n\ttemplate<>\n\tstruct hash<Nz::RenderStates>\n\t{\n\t\tsize_t operator()(const Nz::RenderStates& pipelineInfo) const\n\t\t{\n\t\t\tstd::size_t seed = 0;\n\n\t\t\tNz::UInt8 parameterHash = 0;\n\t\t\tNz::UInt8 parameterIndex = 0;\n\n\t\t\t#define NazaraRenderStateMember(member) Nz::HashCombine(seed, pipelineInfo.member)\n\t\t\t#define NazaraRenderStateBoolMember(member) parameterHash |= ((pipelineInfo.member) ? 1U : 0U) << (parameterIndex++)\n\t\t\t#define NazaraRenderStateBoolMemberDep(dependency, member) parameterHash |= ((pipelineInfo.dependency && pipelineInfo.member) ? 1U : 0U) << (parameterIndex++)\n\t\t\t#define NazaraRenderStateFloatMember(member, maxDiff) Nz::HashCombine(seed, std::floor(pipelineInfo.member \/ maxDiff) * maxDiff)\n\n\t\t\tNazaraRenderStateBoolMember(blending);\n\t\t\tNazaraRenderStateBoolMember(colorWrite);\n\t\t\tNazaraRenderStateBoolMember(depthBuffer);\n\t\t\tNazaraRenderStateBoolMember(faceCulling);\n\t\t\tNazaraRenderStateBoolMember(scissorTest);\n\t\t\tNazaraRenderStateBoolMember(stencilTest);\n\n\t\t\tNazaraRenderStateBoolMemberDep(depthBuffer, depthWrite);\n\n\t\t\tNazaraRenderStateMember(faceFilling);\n\n\t\t\tif (pipelineInfo.blending) \/\/< Remember, at this time we know lhs.blending == rhs.blending\n\t\t\t{\n\t\t\t\tNazaraRenderStateMember(dstBlend);\n\t\t\t\tNazaraRenderStateMember(srcBlend);\n\t\t\t}\n\n\t\t\tif (pipelineInfo.depthBuffer)\n\t\t\t\tNazaraRenderStateMember(depthFunc);\n\n\t\t\tif (pipelineInfo.faceCulling)\n\t\t\t\tNazaraRenderStateMember(cullingSide);\n\n\t\t\tif (pipelineInfo.stencilTest)\n\t\t\t{\n\t\t\t\tNazaraRenderStateMember(stencilCompare.back);\n\t\t\t\tNazaraRenderStateMember(stencilCompare.front);\n\t\t\t\tNazaraRenderStateMember(stencilCompareMask.back);\n\t\t\t\tNazaraRenderStateMember(stencilCompareMask.front);\n\t\t\t\tNazaraRenderStateMember(stencilDepthFail.back);\n\t\t\t\tNazaraRenderStateMember(stencilDepthFail.front);\n\t\t\t\tNazaraRenderStateMember(stencilFail.back);\n\t\t\t\tNazaraRenderStateMember(stencilFail.front);\n\t\t\t\tNazaraRenderStateMember(stencilPass.back);\n\t\t\t\tNazaraRenderStateMember(stencilPass.front);\n\t\t\t\tNazaraRenderStateMember(stencilReference.back);\n\t\t\t\tNazaraRenderStateMember(stencilReference.front);\n\t\t\t\tNazaraRenderStateMember(stencilWriteMask.back);\n\t\t\t\tNazaraRenderStateMember(stencilWriteMask.front);\n\t\t\t}\n\n\t\t\tNazaraRenderStateFloatMember(lineWidth, 0.001f);\n\t\t\tNazaraRenderStateFloatMember(pointSize, 0.001f);\n\n\t\t\t#undef NazaraRenderStateMember\n\t\t\t#undef NazaraRenderStateBoolMember\n\t\t\t#undef NazaraRenderStateBoolMemberDep\n\t\t\t#undef NazaraRenderStateFloatMember\n\n\t\t\tNz::HashCombine(seed, parameterHash);\n\n\t\t\treturn seed;\n\t\t}\n\t};\n}\n\n#include <Nazara\/Renderer\/DebugOff.hpp>\n<commit_msg>Ditto<commit_after>\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Renderer module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Renderer\/RenderStates.hpp>\n#include <Nazara\/Core\/Algorithm.hpp>\n#include <Nazara\/Math\/Algorithm.hpp>\n#include <functional>\n#include <Nazara\/Renderer\/Debug.hpp>\n\nnamespace Nz\n{\n\tbool operator==(const RenderStates& lhs, const RenderStates& rhs)\n\t{\n\t\t#define NazaraRenderStateMember(field) if (lhs.field != rhs.field) return false\n\t\t#define NazaraRenderStateBoolMember NazaraRenderStateMember\n\t\t#define NazaraRenderStateFloatMember(field, maxDiff) if (!NumberEquals(lhs.field, rhs.field, maxDiff)) return false\n\n\t\tNazaraRenderStateBoolMember(blending);\n\t\tNazaraRenderStateBoolMember(colorWrite);\n\t\tNazaraRenderStateBoolMember(depthBuffer);\n\t\tNazaraRenderStateBoolMember(faceCulling);\n\t\tNazaraRenderStateBoolMember(scissorTest);\n\t\tNazaraRenderStateBoolMember(stencilTest);\n\n\t\tif (lhs.depthBuffer)\n\t\t\tNazaraRenderStateBoolMember(depthWrite);\n\n\t\tNazaraRenderStateMember(faceFilling);\n\n\t\tif (lhs.blending) \/\/< Remember, at this time we know lhs.blending == rhs.blending\n\t\t{\n\t\t\tNazaraRenderStateMember(dstBlend);\n\t\t\tNazaraRenderStateMember(srcBlend);\n\t\t}\n\n\t\tif (lhs.depthBuffer)\n\t\t\tNazaraRenderStateMember(depthFunc);\n\n\t\tif (lhs.faceCulling)\n\t\t\tNazaraRenderStateMember(cullingSide);\n\n\t\tif (lhs.stencilTest)\n\t\t{\n\t\t\tNazaraRenderStateMember(stencilCompare.back);\n\t\t\tNazaraRenderStateMember(stencilCompare.front);\n\t\t\tNazaraRenderStateMember(stencilCompareMask.back);\n\t\t\tNazaraRenderStateMember(stencilCompareMask.front);\n\t\t\tNazaraRenderStateMember(stencilDepthFail.back);\n\t\t\tNazaraRenderStateMember(stencilDepthFail.front);\n\t\t\tNazaraRenderStateMember(stencilFail.back);\n\t\t\tNazaraRenderStateMember(stencilFail.front);\n\t\t\tNazaraRenderStateMember(stencilPass.back);\n\t\t\tNazaraRenderStateMember(stencilPass.front);\n\t\t\tNazaraRenderStateMember(stencilReference.back);\n\t\t\tNazaraRenderStateMember(stencilReference.front);\n\t\t\tNazaraRenderStateMember(stencilWriteMask.back);\n\t\t\tNazaraRenderStateMember(stencilWriteMask.front);\n\t\t}\n\n\t\tNazaraRenderStateFloatMember(lineWidth, 0.001f);\n\t\tNazaraRenderStateFloatMember(pointSize, 0.001f);\n\n\t\t#undef NazaraRenderStateMember\n\t\t#undef NazaraRenderStateBoolMember\n\t\t#undef NazaraRenderStateFloatMember\n\n\t\treturn true;\n\t}\n}\n\nnamespace std\n{\n\ttemplate<>\n\tstruct hash<Nz::RenderStates>\n\t{\n\t\tsize_t operator()(const Nz::RenderStates& pipelineInfo) const\n\t\t{\n\t\t\tstd::size_t seed = 0;\n\n\t\t\tNz::UInt8 parameterHash = 0;\n\t\t\tNz::UInt8 parameterIndex = 0;\n\n\t\t\t#define NazaraRenderStateBool(member) parameterHash |= ((pipelineInfo.member) ? 1U : 0U) << (parameterIndex++)\n\t\t\t#define NazaraRenderStateBoolDep(dependency, member) parameterHash |= ((pipelineInfo.dependency && pipelineInfo.member) ? 1U : 0U) << (parameterIndex++)\n\t\t\t#define NazaraRenderStateEnum(member) Nz::HashCombine(seed, static_cast<Nz::UInt8>(pipelineInfo.member))\n\t\t\t#define NazaraRenderStateFloat(member, maxDiff) Nz::HashCombine(seed, std::floor(pipelineInfo.member \/ maxDiff) * maxDiff)\n\n\t\t\tNazaraRenderStateBool(blending);\n\t\t\tNazaraRenderStateBool(colorWrite);\n\t\t\tNazaraRenderStateBool(depthBuffer);\n\t\t\tNazaraRenderStateBool(faceCulling);\n\t\t\tNazaraRenderStateBool(scissorTest);\n\t\t\tNazaraRenderStateBool(stencilTest);\n\n\t\t\tNazaraRenderStateBoolDep(depthBuffer, depthWrite);\n\n\t\t\tNazaraRenderStateEnum(faceFilling);\n\n\t\t\tif (pipelineInfo.blending) \/\/< Remember, at this time we know lhs.blending == rhs.blending\n\t\t\t{\n\t\t\t\tNazaraRenderStateEnum(dstBlend);\n\t\t\t\tNazaraRenderStateEnum(srcBlend);\n\t\t\t}\n\n\t\t\tif (pipelineInfo.depthBuffer)\n\t\t\t\tNazaraRenderStateEnum(depthFunc);\n\n\t\t\tif (pipelineInfo.faceCulling)\n\t\t\t\tNazaraRenderStateEnum(cullingSide);\n\n\t\t\tif (pipelineInfo.stencilTest)\n\t\t\t{\n\t\t\t\tNazaraRenderStateEnum(stencilCompare.back);\n\t\t\t\tNazaraRenderStateEnum(stencilCompare.front);\n\t\t\t\tNazaraRenderStateEnum(stencilCompareMask.back);\n\t\t\t\tNazaraRenderStateEnum(stencilCompareMask.front);\n\t\t\t\tNazaraRenderStateEnum(stencilDepthFail.back);\n\t\t\t\tNazaraRenderStateEnum(stencilDepthFail.front);\n\t\t\t\tNazaraRenderStateEnum(stencilFail.back);\n\t\t\t\tNazaraRenderStateEnum(stencilFail.front);\n\t\t\t\tNazaraRenderStateEnum(stencilPass.back);\n\t\t\t\tNazaraRenderStateEnum(stencilPass.front);\n\t\t\t\tNazaraRenderStateEnum(stencilReference.back);\n\t\t\t\tNazaraRenderStateEnum(stencilReference.front);\n\t\t\t\tNazaraRenderStateEnum(stencilWriteMask.back);\n\t\t\t\tNazaraRenderStateEnum(stencilWriteMask.front);\n\t\t\t}\n\n\t\t\tNazaraRenderStateFloat(lineWidth, 0.001f);\n\t\t\tNazaraRenderStateFloat(pointSize, 0.001f);\n\n\t\t\t#undef NazaraRenderStateBool\n\t\t\t#undef NazaraRenderStateBoolDep\n\t\t\t#undef NazaraRenderStateEnum\n\t\t\t#undef NazaraRenderStateFloat\n\n\t\t\tNz::HashCombine(seed, parameterHash);\n\n\t\t\treturn seed;\n\t\t}\n\t};\n}\n\n#include <Nazara\/Renderer\/DebugOff.hpp>\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__\n#define ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__\n\n#include <algorithm>\n#include <limits>\n#include <iterator>\n#include <numeric>\n#include <random>\n#include <stdexcept>\n#include <vector>\n\n#include <aleph\/geometry\/RipsExpander.hh>\n\n#include <aleph\/geometry\/distances\/Traits.hh>\n\n#include <aleph\/math\/SymmetricMatrix.hh>\n\n#include <aleph\/topology\/Simplex.hh>\n#include <aleph\/topology\/SimplicialComplex.hh>\n\n#include <aleph\/topology\/filtrations\/Data.hh>\n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\n\/**\n Builds a witness complex from a given container. This requires a set\n of *landmarks*. Other configuration options influence how a new edge\n will be created from the data.\n\n If you call this function with its barest minimum parameters by only\n specifying a container and a set of landmarks, the resulting complex\n will automatically adjust to your data and follows the definition of\n the paper:\n\n > Topological estimation using witness complexes\\n\n > Vin de Silva and Gunnar Carlsson\\n\n > Eurographics Symposium on Point-Based Graphics, 2004\n\n The other parameters, in particular \\p R, permit tuning the results,\n thereby given the complex more \"slack\" when creating edges. However,\n this also increases the size of the complex.\n\n @param container Container for which to calculate the witness complex\n\n @param begin Input iterator to begin of landmark range; landmarks\n must be specified as *indices*. Each index has to be\n valid for \\p container.\n\n @param end Input iterator to end of landmark range\n\n @param dimension Maximum dimension for expanding the witness complex\n after obtaining its edges. The expansion process is\n going to use the maximum possible dimension if this\n parameter is not specified by the client.\n\n @param nu \\f$\\nu\\f$-parameter as defined in the paper. The\n parameter controls which distance threshold is used\n for creating an edge.\\n\n\n More precisely, an edge is created if the following\n holds:\\n\n \\n\n \\f[\n \\max(\\mathrm{dist}_{a,i}\\mathrm{dist}_{b,i}) \\leq R + m_i\n \\f]\n \\n\n Here, \\f$m_i\\f$ refers to the \\f$\\nu\\f$th\n smallest element of the distance matrix.\n\n @param R Maximum radius parameter for determining whether to\n create an edge or not. The default value makes sure\n that *only* the distances between the landmarks and\n the points will be used for edge creation.\n\n @param distance Distance functor, e.g. the Euclidean distance, that\n is used for calculating distances between landmarks\n and data points. This parameter is provided to make\n it possible for the compiler to detect the template\n parameter \\p distance automatically.\n\n @returns Witness complex of the given container. Notice that\n the complex is stored as a simplicial complex whose\n data type and index type are derived from the input\n data. The data of a simplex contains the *smallest*\n threshold for which they appear in the complex. The\n complex will be sorted according to this value.\n*\/\n\ntemplate <\n class Distance,\n class Container,\n class InputIterator\n> auto buildWitnessComplex(\n const Container& container,\n InputIterator begin,\n InputIterator end,\n unsigned dimension = 0,\n unsigned nu = 2,\n typename Distance::ResultType R = typename Distance::ResultType(),\n Distance \/* distance *\/ = Distance() ) -> topology::SimplicialComplex< topology::Simplex<typename Distance::ResultType, typename std::iterator_traits<InputIterator>::value_type> >\n{\n using IndexType = typename std::iterator_traits<InputIterator>::value_type;\n using VertexType = IndexType;\n using DataType = typename Distance::ResultType;\n using Traits = aleph::geometry::distances::Traits<Distance>;\n using Simplex = topology::Simplex<DataType, VertexType>;\n using SimplicialComplex = topology::SimplicialComplex<Simplex>;\n\n \/\/ These are only the *indices* of the landmarks, with respect to the\n \/\/ underlying point cloud.\n std::vector<IndexType> landmarkIndices( begin, end );\n\n auto n = landmarkIndices.size();\n auto N = container.size();\n auto d = container.dimension();\n\n \/\/ Much of the behaviour below will be undefined if we permit such\n \/\/ situations to occur.\n if( n == 0 || N == 0 )\n return {};\n\n \/\/ Distance matrix between a set of $n$ landmarks (cols) and $N$ data\n \/\/ points (rows). Note that I transposed the matrix because accessing\n \/\/ the columns is faster that way (and will be required later on).\n std::vector< std::vector<DataType> > D;\n D.reserve( N );\n\n Distance dist;\n Traits traits;\n\n for( std::size_t j = 0; j < N; j++ )\n {\n std::vector<DataType> distances;\n distances.reserve( n );\n\n auto&& point = container[j];\n\n for( std::size_t i = 0; i < n; i++ )\n {\n auto&& landmark = container[ landmarkIndices.at(i) ];\n\n distances.emplace_back( traits.from( dist( landmark.begin(), point.begin(), d ) ) );\n }\n\n D.push_back( distances );\n }\n\n \/\/ Get smallest entries of the distance matrix. This is required for\n \/\/ deciding whether a specific edge is valid or not, with respect to\n \/\/ the given parameters.\n\n std::vector<DataType> smallest( N );\n\n if( nu != 0 )\n {\n for( std::size_t col = 0; col < N; col++ )\n {\n std::vector<DataType> column = D[col];\n\n std::nth_element( column.begin(), column.begin() + nu - 1, column.end() );\n smallest[col] = column.at( nu - 1 );\n }\n }\n\n \/\/ -------------------------------------------------------------------\n \/\/\n \/\/ Records the appearance times of each potential edge in the witness\n \/\/ complex and creates the valid edges.\n\n std::vector<Simplex> simplices;\n\n aleph::math::SymmetricMatrix<DataType> M( n );\n\n for( std::size_t i = 0; i < n; i++ )\n {\n simplices.push_back( Simplex( static_cast<VertexType>(i) ) );\n\n for( std::size_t j = i+1; j < n; j++ )\n {\n auto min = std::numeric_limits<DataType>::max();\n\n for( std::size_t k = 0; k < N; k++ )\n {\n if( std::max( D[k][i], D[k][j] ) <= R + smallest.at(k) )\n min = std::min( min, std::max( D[k][i], D[k][j] ) );\n }\n\n if( min != std::numeric_limits<DataType>::max() )\n {\n auto u = static_cast<VertexType>(i);\n auto v = static_cast<VertexType>(j);\n\n simplices.push_back( Simplex( {u,v}, min ) );\n }\n }\n }\n\n aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander;\n\n SimplicialComplex K = SimplicialComplex( simplices.begin(), simplices.end() );\n SimplicialComplex L = ripsExpander( K, dimension == 0 ? static_cast<unsigned>( d + 1 ) : dimension );\n L = ripsExpander.assignMaximumWeight( L );\n\n L.sort( aleph::topology::filtrations::Data<Simplex>() );\n return L;\n}\n\ntemplate <class T, class OutputIterator> void generateRandomLandmarks( T n, T k, OutputIterator result )\n{\n std::random_device rd;\n std::mt19937 rng( rd() );\n\n std::vector<T> indices( n );\n\n using DifferenceType = typename std::vector<T>::difference_type;\n\n std::iota( indices.begin(), indices.end(), T() );\n std::shuffle( indices.begin(), indices.end(), rng );\n std::copy( indices.begin(), indices.begin() + static_cast<DifferenceType>(k), result );\n}\n\ntemplate <\n class Distance,\n class Container,\n class OutputIterator\n> void generateMaxMinLandmarks( const Container& container, std::size_t n, OutputIterator result, Distance distance = Distance() )\n{\n if( n > container.size() )\n throw std::out_of_range( \"Number of landmarks is out of range\" );\n\n using SizeType = decltype( container.size() );\n\n std::random_device rd;\n std::mt19937 rng( rd() );\n\n std::uniform_int_distribution<SizeType> distribution( SizeType(0), container.size() - 1 );\n\n std::vector<SizeType> indices;\n indices.reserve( n );\n\n indices.emplace_back( distribution( rng ) );\n\n using DataType = typename Distance::ResultType;\n auto N = container.size();\n auto d = container.dimension();\n\n while( indices.size() < n )\n {\n auto index = SizeType(0);\n auto max = std::numeric_limits<DataType>::lowest();\n\n for( SizeType i = 0; i < N; i++ )\n {\n auto min = std::numeric_limits<DataType>::max();\n\n for( auto&& landmarkIndex : indices )\n {\n auto dist = distance( container[i].begin(), container[landmarkIndex].begin(), d );\n min = std::min( min, dist );\n }\n\n if( min > max )\n {\n max = min;\n index = i;\n }\n }\n\n indices.push_back( index );\n }\n\n std::copy( indices.begin(), indices.end(), result );\n}\n\n\n} \/\/ namespace geometry\n\n} \/\/ namespace aleph\n\n#endif\n<commit_msg>Documented witness complex landmark creation strategies<commit_after>#ifndef ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__\n#define ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__\n\n#include <algorithm>\n#include <limits>\n#include <iterator>\n#include <numeric>\n#include <random>\n#include <stdexcept>\n#include <vector>\n\n#include <aleph\/geometry\/RipsExpander.hh>\n\n#include <aleph\/geometry\/distances\/Traits.hh>\n\n#include <aleph\/math\/SymmetricMatrix.hh>\n\n#include <aleph\/topology\/Simplex.hh>\n#include <aleph\/topology\/SimplicialComplex.hh>\n\n#include <aleph\/topology\/filtrations\/Data.hh>\n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\n\/**\n Builds a witness complex from a given container. This requires a set\n of *landmarks*. Other configuration options influence how a new edge\n will be created from the data.\n\n If you call this function with its barest minimum parameters by only\n specifying a container and a set of landmarks, the resulting complex\n will automatically adjust to your data and follows the definition of\n the paper:\n\n > Topological estimation using witness complexes\\n\n > Vin de Silva and Gunnar Carlsson\\n\n > Eurographics Symposium on Point-Based Graphics, 2004\n\n The other parameters, in particular \\p R, permit tuning the results,\n thereby given the complex more \"slack\" when creating edges. However,\n this also increases the size of the complex.\n\n @param container Container for which to calculate the witness complex\n\n @param begin Input iterator to begin of landmark range; landmarks\n must be specified as *indices*. Each index has to be\n valid for \\p container.\n\n @param end Input iterator to end of landmark range\n\n @param dimension Maximum dimension for expanding the witness complex\n after obtaining its edges. The expansion process is\n going to use the maximum possible dimension if this\n parameter is not specified by the client.\n\n @param nu \\f$\\nu\\f$-parameter as defined in the paper. The\n parameter controls which distance threshold is used\n for creating an edge.\\n\n\n More precisely, an edge is created if the following\n holds:\\n\n \\n\n \\f[\n \\max(\\mathrm{dist}_{a,i}\\mathrm{dist}_{b,i}) \\leq R + m_i\n \\f]\n \\n\n Here, \\f$m_i\\f$ refers to the \\f$\\nu\\f$th\n smallest element of the distance matrix.\n\n @param R Maximum radius parameter for determining whether to\n create an edge or not. The default value makes sure\n that *only* the distances between the landmarks and\n the points will be used for edge creation.\n\n @param distance Distance functor, e.g. the Euclidean distance, that\n is used for calculating distances between landmarks\n and data points. This parameter is provided to make\n it possible for the compiler to detect the template\n parameter \\p distance automatically.\n\n @returns Witness complex of the given container. Notice that\n the complex is stored as a simplicial complex whose\n data type and index type are derived from the input\n data. The data of a simplex contains the *smallest*\n threshold for which they appear in the complex. The\n complex will be sorted according to this value.\n*\/\n\ntemplate <\n class Distance,\n class Container,\n class InputIterator\n> auto buildWitnessComplex(\n const Container& container,\n InputIterator begin,\n InputIterator end,\n unsigned dimension = 0,\n unsigned nu = 2,\n typename Distance::ResultType R = typename Distance::ResultType(),\n Distance \/* distance *\/ = Distance() ) -> topology::SimplicialComplex< topology::Simplex<typename Distance::ResultType, typename std::iterator_traits<InputIterator>::value_type> >\n{\n using IndexType = typename std::iterator_traits<InputIterator>::value_type;\n using VertexType = IndexType;\n using DataType = typename Distance::ResultType;\n using Traits = aleph::geometry::distances::Traits<Distance>;\n using Simplex = topology::Simplex<DataType, VertexType>;\n using SimplicialComplex = topology::SimplicialComplex<Simplex>;\n\n \/\/ These are only the *indices* of the landmarks, with respect to the\n \/\/ underlying point cloud.\n std::vector<IndexType> landmarkIndices( begin, end );\n\n auto n = landmarkIndices.size();\n auto N = container.size();\n auto d = container.dimension();\n\n \/\/ Much of the behaviour below will be undefined if we permit such\n \/\/ situations to occur.\n if( n == 0 || N == 0 )\n return {};\n\n \/\/ Distance matrix between a set of $n$ landmarks (cols) and $N$ data\n \/\/ points (rows). Note that I transposed the matrix because accessing\n \/\/ the columns is faster that way (and will be required later on).\n std::vector< std::vector<DataType> > D;\n D.reserve( N );\n\n Distance dist;\n Traits traits;\n\n for( std::size_t j = 0; j < N; j++ )\n {\n std::vector<DataType> distances;\n distances.reserve( n );\n\n auto&& point = container[j];\n\n for( std::size_t i = 0; i < n; i++ )\n {\n auto&& landmark = container[ landmarkIndices.at(i) ];\n\n distances.emplace_back( traits.from( dist( landmark.begin(), point.begin(), d ) ) );\n }\n\n D.push_back( distances );\n }\n\n \/\/ Get smallest entries of the distance matrix. This is required for\n \/\/ deciding whether a specific edge is valid or not, with respect to\n \/\/ the given parameters.\n\n std::vector<DataType> smallest( N );\n\n if( nu != 0 )\n {\n for( std::size_t col = 0; col < N; col++ )\n {\n std::vector<DataType> column = D[col];\n\n std::nth_element( column.begin(), column.begin() + nu - 1, column.end() );\n smallest[col] = column.at( nu - 1 );\n }\n }\n\n \/\/ -------------------------------------------------------------------\n \/\/\n \/\/ Records the appearance times of each potential edge in the witness\n \/\/ complex and creates the valid edges.\n\n std::vector<Simplex> simplices;\n\n aleph::math::SymmetricMatrix<DataType> M( n );\n\n for( std::size_t i = 0; i < n; i++ )\n {\n simplices.push_back( Simplex( static_cast<VertexType>(i) ) );\n\n for( std::size_t j = i+1; j < n; j++ )\n {\n auto min = std::numeric_limits<DataType>::max();\n\n for( std::size_t k = 0; k < N; k++ )\n {\n if( std::max( D[k][i], D[k][j] ) <= R + smallest.at(k) )\n min = std::min( min, std::max( D[k][i], D[k][j] ) );\n }\n\n if( min != std::numeric_limits<DataType>::max() )\n {\n auto u = static_cast<VertexType>(i);\n auto v = static_cast<VertexType>(j);\n\n simplices.push_back( Simplex( {u,v}, min ) );\n }\n }\n }\n\n aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander;\n\n SimplicialComplex K = SimplicialComplex( simplices.begin(), simplices.end() );\n SimplicialComplex L = ripsExpander( K, dimension == 0 ? static_cast<unsigned>( d + 1 ) : dimension );\n L = ripsExpander.assignMaximumWeight( L );\n\n L.sort( aleph::topology::filtrations::Data<Simplex>() );\n return L;\n}\n\n\/**\n Generates a random set of landmarks for use with the witness complex.\n Essentially, this function merely generates a set of *random indices*\n based on a random shuffle operation. The results of this are saved in\n an output iterator.\n\n @param n Number of points\n @param k Number of landmarks\n @param result Output iterator for storing the results\n*\/\n\ntemplate <class T, class OutputIterator> void generateRandomLandmarks( T n, T k, OutputIterator result )\n{\n std::random_device rd;\n std::mt19937 rng( rd() );\n\n std::vector<T> indices( n );\n\n using DifferenceType = typename std::vector<T>::difference_type;\n\n std::iota( indices.begin(), indices.end(), T() );\n std::shuffle( indices.begin(), indices.end(), rng );\n std::copy( indices.begin(), indices.begin() + static_cast<DifferenceType>(k), result );\n}\n\n\/**\n Generates a set of landmarks for the witness complex, using the\n max-min strategy. Given a distance measure, a new landmark will\n be chosen so as to *maximize* the *minimum distance* to the set\n of selected landmarks. An output iterator is used to report the\n indices of the selected landmarks.\n\n @param container Container that stores the input data\n @param n Number of landmarks to select\n @param result Output iterator for storing the results\n @param distance Distance measure. This parameter may be specified\n to permit template type deduction.\n*\/\n\ntemplate <\n class Distance,\n class Container,\n class OutputIterator\n> void generateMaxMinLandmarks( const Container& container, std::size_t n, OutputIterator result, Distance distance = Distance() )\n{\n if( n > container.size() )\n throw std::out_of_range( \"Number of landmarks is out of range\" );\n\n using SizeType = decltype( container.size() );\n\n std::random_device rd;\n std::mt19937 rng( rd() );\n\n std::uniform_int_distribution<SizeType> distribution( SizeType(0), container.size() - 1 );\n\n std::vector<SizeType> indices;\n indices.reserve( n );\n\n indices.emplace_back( distribution( rng ) );\n\n using DataType = typename Distance::ResultType;\n auto N = container.size();\n auto d = container.dimension();\n\n while( indices.size() < n )\n {\n auto index = SizeType(0);\n auto max = std::numeric_limits<DataType>::lowest();\n\n for( SizeType i = 0; i < N; i++ )\n {\n auto min = std::numeric_limits<DataType>::max();\n\n for( auto&& landmarkIndex : indices )\n {\n auto dist = distance( container[i].begin(), container[landmarkIndex].begin(), d );\n min = std::min( min, dist );\n }\n\n if( min > max )\n {\n max = min;\n index = i;\n }\n }\n\n indices.push_back( index );\n }\n\n std::copy( indices.begin(), indices.end(), result );\n}\n\n} \/\/ namespace geometry\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This File is part of Davix, The IO library for HTTP based protocols\n * Copyright (C) 2013 Adrien Devresse <adrien.devresse@cern.ch>, CERN\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*\/\n\n\n#ifndef DAVIX_HOOKS_IMPL_HPP\n#define DAVIX_HOOKS_IMPL_HPP\n\n#include <hooks\/davix_hooks_fwd.hpp>\n\n\/\/ intern file, Never use directly\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n\nnamespace Davix{\n\nstruct ContextInternal;\n\n#ifndef DAVIX_STD_CXX03\n\nclass HookList{\npublic:\n\n RequestPreRunHook _pre_run_req;\n\n RequestPreSendHook _pre_send_req;\n\n RequestPreReceHook _pre_rece_req;\n\nprivate:\n HookList();\n friend class ContextInternal;\n};\n\n\n\/\/ define\ntemplate<typename HookType>\ninline void hookDefine(HookList & c, const HookType & hook){\n throw DavixException(std::string(\"davix::hook\"), StatusCode::InvalidHook, \"Invalid Hook type\");\n}\n\ntemplate<>\ninline void hookDefine(HookList &c, const RequestPreRunHook & hook){\n c._pre_run_req = hook;\n}\n\ntemplate<>\ninline void hookDefine(HookList &c, const RequestPreSendHook & hook){\n c._pre_send_req = hook;\n}\n\ntemplate<>\ninline void hookDefine(HookList &c, const RequestPreReceHook & hook){\n c._pre_rece_req = hook;\n}\n\n\n\/\/ get\ntemplate<typename HookType>\ninline const HookType & hookGet(HookList & c){\n throw DavixException(std::string(\"davix::hook\"), StatusCode::InvalidHook, \"Invalid Hook type\");\n}\n\ntemplate<>\ninline const RequestPreRunHook & hookGet(HookList & c){\n return c._pre_run_req;\n}\n\ntemplate<>\ninline const RequestPreSendHook & hookGet(HookList & c){\n return c._pre_send_req;\n}\n\ntemplate<>\ninline const RequestPreReceHook & hookGet(HookList & c){\n return c._pre_rece_req;\n}\n\n\n#endif\n\n}\n\n#endif\n\n#endif \/\/ DAVIX_HOOKS_IMPL_HPP\n<commit_msg>- correct minor compilation warning on OSX<commit_after>\/*\n * This File is part of Davix, The IO library for HTTP based protocols\n * Copyright (C) 2013 Adrien Devresse <adrien.devresse@cern.ch>, CERN\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*\/\n\n\n#ifndef DAVIX_HOOKS_IMPL_HPP\n#define DAVIX_HOOKS_IMPL_HPP\n\n#include <hooks\/davix_hooks_fwd.hpp>\n\n\/\/ intern file, Never use directly\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n\nnamespace Davix{\n\nstruct ContextInternal;\n\n#ifndef DAVIX_STD_CXX03\n\nclass HookList{\npublic:\n\n RequestPreRunHook _pre_run_req;\n\n RequestPreSendHook _pre_send_req;\n\n RequestPreReceHook _pre_rece_req;\n\nprivate:\n HookList();\n friend struct ContextInternal;\n};\n\n\n\/\/ define\ntemplate<typename HookType>\ninline void hookDefine(HookList & c, const HookType & hook){\n throw DavixException(std::string(\"davix::hook\"), StatusCode::InvalidHook, \"Invalid Hook type\");\n}\n\ntemplate<>\ninline void hookDefine(HookList &c, const RequestPreRunHook & hook){\n c._pre_run_req = hook;\n}\n\ntemplate<>\ninline void hookDefine(HookList &c, const RequestPreSendHook & hook){\n c._pre_send_req = hook;\n}\n\ntemplate<>\ninline void hookDefine(HookList &c, const RequestPreReceHook & hook){\n c._pre_rece_req = hook;\n}\n\n\n\/\/ get\ntemplate<typename HookType>\ninline const HookType & hookGet(HookList & c){\n throw DavixException(std::string(\"davix::hook\"), StatusCode::InvalidHook, \"Invalid Hook type\");\n}\n\ntemplate<>\ninline const RequestPreRunHook & hookGet(HookList & c){\n return c._pre_run_req;\n}\n\ntemplate<>\ninline const RequestPreSendHook & hookGet(HookList & c){\n return c._pre_send_req;\n}\n\ntemplate<>\ninline const RequestPreReceHook & hookGet(HookList & c){\n return c._pre_rece_req;\n}\n\n\n#endif\n\n}\n\n#endif\n\n#endif \/\/ DAVIX_HOOKS_IMPL_HPP\n<|endoftext|>"} {"text":"<commit_before><commit_msg>prevent invalid OOXML files with trendlines, related #i88825#<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreGLFrameBufferObject.h\"\n#include \"OgreGLPixelFormat.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreRoot.h\"\n#include \"OgreGLHardwarePixelBuffer.h\"\n#include \"OgreGLFBORenderTexture.h\"\n\nnamespace Ogre {\n\n\/\/-----------------------------------------------------------------------------\n GLFrameBufferObject::GLFrameBufferObject(GLFBOManager *manager, uint fsaa):\n mManager(manager), mNumSamples(fsaa)\n {\n \/\/\/ Generate framebuffer object\n glGenFramebuffersEXT(1, &mFB);\n\t\t\/\/ check multisampling\n\t\tif (GLEW_EXT_framebuffer_blit && GLEW_EXT_framebuffer_multisample)\n\t\t{\n\t\t\t\/\/ check samples supported\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);\n\t\t\tGLint maxSamples;\n\t\t\tglGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples);\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);\n\t\t\tmNumSamples = std::min(mNumSamples, (GLsizei)maxSamples);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmNumSamples = 0;\n\t\t}\n\t\t\/\/ will we need a second FBO to do multisampling?\n\t\tif (mNumSamples)\n\t\t{\n\t\t\tglGenFramebuffersEXT(1, &mMultisampleFB);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmMultisampleFB = 0;\n\t\t}\n \/\/\/ Initialise state\n mDepth.buffer=0;\n mStencil.buffer=0;\n for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)\n {\n mColour[x].buffer=0;\n }\n }\n GLFrameBufferObject::~GLFrameBufferObject()\n {\n mManager->releaseRenderBuffer(mDepth);\n mManager->releaseRenderBuffer(mStencil);\n\t\tmManager->releaseRenderBuffer(mMultisampleColourBuffer);\n \/\/\/ Delete framebuffer object\n glDeleteFramebuffersEXT(1, &mFB); \n\t\tif (mMultisampleFB)\n\t\t\tglDeleteFramebuffersEXT(1, &mMultisampleFB);\n\n }\n void GLFrameBufferObject::bindSurface(size_t attachment, const GLSurfaceDesc &target)\n {\n assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);\n mColour[attachment] = target;\n\t\t\/\/ Re-initialise\n\t\tif(mColour[0].buffer)\n\t\t\tinitialise();\n }\n void GLFrameBufferObject::unbindSurface(size_t attachment)\n {\n assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);\n mColour[attachment].buffer = 0;\n\t\t\/\/ Re-initialise if buffer 0 still bound\n\t\tif(mColour[0].buffer)\n\t\t{\n\t\t\tinitialise();\n\t\t}\n }\n void GLFrameBufferObject::initialise()\n {\n\t\t\/\/ Release depth and stencil, if they were bound\n mManager->releaseRenderBuffer(mDepth);\n mManager->releaseRenderBuffer(mStencil);\n\t\tmManager->releaseRenderBuffer(mMultisampleColourBuffer);\n \/\/\/ First buffer must be bound\n if(!mColour[0].buffer)\n {\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, \n \"Attachment 0 must have surface attached\",\n\t\t \t\"GLFrameBufferObject::initialise\");\n }\n\n\t\t\/\/ If we're doing multisampling, then we need another FBO which contains a\n\t\t\/\/ renderbuffer which is set up to multisample, and we'll blit it to the final \n\t\t\/\/ FBO afterwards to perform the multisample resolve. In that case, the \n\t\t\/\/ mMultisampleFB is bound during rendering and is the one with a depth\/stencil\n\n \/\/\/ Store basic stats\n size_t width = mColour[0].buffer->getWidth();\n size_t height = mColour[0].buffer->getHeight();\n GLuint format = mColour[0].buffer->getGLFormat();\n PixelFormat ogreFormat = mColour[0].buffer->getFormat();\n\n\t\t\/\/ Bind simple buffer to add colour attachments\n\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);\n\n \/\/\/ Bind all attachment points to frame buffer\n for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)\n {\n if(mColour[x].buffer)\n {\n if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)\n {\n StringStream ss;\n ss << \"Attachment \" << x << \" has incompatible size \";\n ss << mColour[x].buffer->getWidth() << \"x\" << mColour[x].buffer->getHeight();\n ss << \". It must be of the same as the size of surface 0, \";\n ss << width << \"x\" << height;\n ss << \".\";\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), \"GLFrameBufferObject::initialise\");\n }\n if(mColour[x].buffer->getGLFormat() != format)\n {\n StringStream ss;\n ss << \"Attachment \" << x << \" has incompatible format.\";\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), \"GLFrameBufferObject::initialise\");\n }\n\t mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT+x, mColour[x].zoffset);\n }\n else\n {\n \/\/ Detach\n glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+x,\n GL_RENDERBUFFER_EXT, 0);\n }\n }\n\n\t\t\/\/ Now deal with depth \/ stencil\n\t\tif (mMultisampleFB)\n\t\t{\n\t\t\t\/\/ Bind multisample buffer\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);\n\n\t\t\t\/\/ Create AA render buffer (colour)\n\t\t\t\/\/ note, this can be shared too because we blit it to the final FBO\n\t\t\t\/\/ right after the render is finished\n\t\t\tmMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);\n\n\t\t\t\/\/ Attach it, because we won't be attaching below and non-multisample has\n\t\t\t\/\/ actually been attached to other FBO\n\t\t\tmMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT, \n\t\t\t\tmMultisampleColourBuffer.zoffset);\n\n\t\t\t\/\/ depth & stencil will be dealt with below\n\n\t\t}\n\n \/\/\/ Find suitable depth and stencil format that is compatible with colour format\n GLenum depthFormat, stencilFormat;\n mManager->getBestDepthStencil(ogreFormat, &depthFormat, &stencilFormat);\n \n \/\/\/ Request surfaces\n mDepth = mManager->requestRenderBuffer(depthFormat, width, height, mNumSamples);\n\t\tif (depthFormat == GL_DEPTH24_STENCIL8_EXT)\n\t\t{\n\t\t\t\/\/ bind same buffer to depth and stencil attachments\n mManager->requestRenderBuffer(mDepth);\n\t\t\tmStencil = mDepth;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ separate stencil\n\t\t\tmStencil = mManager->requestRenderBuffer(stencilFormat, width, height, mNumSamples);\n\t\t}\n \n \/\/\/ Attach\/detach surfaces\n if(mDepth.buffer)\n {\n mDepth.buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT_EXT, mDepth.zoffset);\n }\n else\n {\n glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,\n GL_RENDERBUFFER_EXT, 0);\n }\n if(mStencil.buffer)\n {\n mStencil.buffer->bindToFramebuffer(GL_STENCIL_ATTACHMENT_EXT, mStencil.zoffset);\n }\n else\n {\n glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,\n GL_RENDERBUFFER_EXT, 0);\n }\n\n\t\t\/\/\/ Do glDrawBuffer calls\n\t\tGLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];\n\t\tGLsizei n=0;\n\t\tfor(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)\n\t\t{\n\t\t\t\/\/ Fill attached colour buffers\n\t\t\tif(mColour[x].buffer)\n\t\t\t{\n\t\t\t\tbufs[x] = GL_COLOR_ATTACHMENT0_EXT + x;\n\t\t\t\t\/\/ Keep highest used buffer + 1\n\t\t\t\tn = x+1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbufs[x] = GL_NONE;\n\t\t\t}\n\t\t}\n\t\tif(glDrawBuffers)\n\t\t{\n\t\t\t\/\/\/ Drawbuffer extension supported, use it\n\t\t\tglDrawBuffers(n, bufs);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/\/ In this case, the capabilities will not show more than 1 simultaneaous render target.\n\t\t\tglDrawBuffer(bufs[0]);\n\t\t}\n\t\tif (mMultisampleFB)\n\t\t{\n\t\t\t\/\/ we need a read buffer because we'll be blitting to mFB\n\t\t\tglReadBuffer(bufs[0]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/\/ No read buffer, by default, if we want to read anyway we must not forget to set this.\n\t\t\tglReadBuffer(GL_NONE);\n\t\t}\n \n \/\/\/ Check status\n GLuint status;\n status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);\n \n \/\/\/ Bind main buffer\n glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);\n \n switch(status)\n {\n case GL_FRAMEBUFFER_COMPLETE_EXT:\n \/\/ All is good\n break;\n case GL_FRAMEBUFFER_UNSUPPORTED_EXT:\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, \n \"All framebuffer formats with this texture internal format unsupported\",\n\t\t \t\"GLFrameBufferObject::initialise\");\n default:\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, \n \"Framebuffer incomplete or other FBO status error\",\n\t\t \t\"GLFrameBufferObject::initialise\");\n }\n \n }\n void GLFrameBufferObject::bind()\n {\n \/\/\/ Bind it to FBO\n\t\tif (mMultisampleFB)\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);\n\t\telse\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);\n }\n\n\tvoid GLFrameBufferObject::swapBuffers()\n\t{\n\t\tif (mMultisampleFB)\n\t\t{\n\t\t\t\/\/ blit from multisample buffer to final buffer, triggers resolve\n\t\t\tsize_t width = mColour[0].buffer->getWidth();\n\t\t\tsize_t height = mColour[0].buffer->getHeight();\n\t\t\tglBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, mMultisampleFB);\n\t\t\tglBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, mFB);\n\t\t\tglBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);\n\n\t\t}\n\t}\n\n size_t GLFrameBufferObject::getWidth()\n {\n assert(mColour[0].buffer);\n return mColour[0].buffer->getWidth();\n }\n size_t GLFrameBufferObject::getHeight()\n {\n assert(mColour[0].buffer);\n return mColour[0].buffer->getHeight();\n }\n PixelFormat GLFrameBufferObject::getFormat()\n {\n assert(mColour[0].buffer);\n return mColour[0].buffer->getFormat();\n }\n\/\/-----------------------------------------------------------------------------\n}\n<commit_msg>GL: Only bind up to the max supported number of render targets since not all implementations support 8. This prevents a few OpenGL errors.<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreGLFrameBufferObject.h\"\n#include \"OgreGLPixelFormat.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreRoot.h\"\n#include \"OgreGLHardwarePixelBuffer.h\"\n#include \"OgreGLFBORenderTexture.h\"\n\nnamespace Ogre {\n\n\/\/-----------------------------------------------------------------------------\n GLFrameBufferObject::GLFrameBufferObject(GLFBOManager *manager, uint fsaa):\n mManager(manager), mNumSamples(fsaa)\n {\n \/\/\/ Generate framebuffer object\n glGenFramebuffersEXT(1, &mFB);\n\t\t\/\/ check multisampling\n\t\tif (GLEW_EXT_framebuffer_blit && GLEW_EXT_framebuffer_multisample)\n\t\t{\n\t\t\t\/\/ check samples supported\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);\n\t\t\tGLint maxSamples;\n\t\t\tglGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples);\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);\n\t\t\tmNumSamples = std::min(mNumSamples, (GLsizei)maxSamples);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmNumSamples = 0;\n\t\t}\n\t\t\/\/ will we need a second FBO to do multisampling?\n\t\tif (mNumSamples)\n\t\t{\n\t\t\tglGenFramebuffersEXT(1, &mMultisampleFB);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmMultisampleFB = 0;\n\t\t}\n \/\/\/ Initialise state\n mDepth.buffer=0;\n mStencil.buffer=0;\n for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)\n {\n mColour[x].buffer=0;\n }\n }\n GLFrameBufferObject::~GLFrameBufferObject()\n {\n mManager->releaseRenderBuffer(mDepth);\n mManager->releaseRenderBuffer(mStencil);\n\t\tmManager->releaseRenderBuffer(mMultisampleColourBuffer);\n \/\/\/ Delete framebuffer object\n glDeleteFramebuffersEXT(1, &mFB); \n\t\tif (mMultisampleFB)\n\t\t\tglDeleteFramebuffersEXT(1, &mMultisampleFB);\n\n }\n void GLFrameBufferObject::bindSurface(size_t attachment, const GLSurfaceDesc &target)\n {\n assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);\n mColour[attachment] = target;\n\t\t\/\/ Re-initialise\n\t\tif(mColour[0].buffer)\n\t\t\tinitialise();\n }\n void GLFrameBufferObject::unbindSurface(size_t attachment)\n {\n assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);\n mColour[attachment].buffer = 0;\n\t\t\/\/ Re-initialise if buffer 0 still bound\n\t\tif(mColour[0].buffer)\n\t\t{\n\t\t\tinitialise();\n\t\t}\n }\n void GLFrameBufferObject::initialise()\n {\n\t\t\/\/ Release depth and stencil, if they were bound\n mManager->releaseRenderBuffer(mDepth);\n mManager->releaseRenderBuffer(mStencil);\n\t\tmManager->releaseRenderBuffer(mMultisampleColourBuffer);\n \/\/\/ First buffer must be bound\n if(!mColour[0].buffer)\n {\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, \n \"Attachment 0 must have surface attached\",\n\t\t \t\"GLFrameBufferObject::initialise\");\n }\n\n\t\t\/\/ If we're doing multisampling, then we need another FBO which contains a\n\t\t\/\/ renderbuffer which is set up to multisample, and we'll blit it to the final \n\t\t\/\/ FBO afterwards to perform the multisample resolve. In that case, the \n\t\t\/\/ mMultisampleFB is bound during rendering and is the one with a depth\/stencil\n\n \/\/\/ Store basic stats\n size_t width = mColour[0].buffer->getWidth();\n size_t height = mColour[0].buffer->getHeight();\n GLuint format = mColour[0].buffer->getGLFormat();\n PixelFormat ogreFormat = mColour[0].buffer->getFormat();\n ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets();\n\n\t\t\/\/ Bind simple buffer to add colour attachments\n\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);\n\n \/\/\/ Bind all attachment points to frame buffer\n for(size_t x=0; x<maxSupportedMRTs; ++x)\n {\n if(mColour[x].buffer)\n {\n if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)\n {\n StringStream ss;\n ss << \"Attachment \" << x << \" has incompatible size \";\n ss << mColour[x].buffer->getWidth() << \"x\" << mColour[x].buffer->getHeight();\n ss << \". It must be of the same as the size of surface 0, \";\n ss << width << \"x\" << height;\n ss << \".\";\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), \"GLFrameBufferObject::initialise\");\n }\n if(mColour[x].buffer->getGLFormat() != format)\n {\n StringStream ss;\n ss << \"Attachment \" << x << \" has incompatible format.\";\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), \"GLFrameBufferObject::initialise\");\n }\n\t mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT+x, mColour[x].zoffset);\n }\n else\n {\n \/\/ Detach\n glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+x,\n GL_RENDERBUFFER_EXT, 0);\n }\n }\n\n\t\t\/\/ Now deal with depth \/ stencil\n\t\tif (mMultisampleFB)\n\t\t{\n\t\t\t\/\/ Bind multisample buffer\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);\n\n\t\t\t\/\/ Create AA render buffer (colour)\n\t\t\t\/\/ note, this can be shared too because we blit it to the final FBO\n\t\t\t\/\/ right after the render is finished\n\t\t\tmMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);\n\n\t\t\t\/\/ Attach it, because we won't be attaching below and non-multisample has\n\t\t\t\/\/ actually been attached to other FBO\n\t\t\tmMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT, \n\t\t\t\tmMultisampleColourBuffer.zoffset);\n\n\t\t\t\/\/ depth & stencil will be dealt with below\n\n\t\t}\n\n \/\/\/ Find suitable depth and stencil format that is compatible with colour format\n GLenum depthFormat, stencilFormat;\n mManager->getBestDepthStencil(ogreFormat, &depthFormat, &stencilFormat);\n \n \/\/\/ Request surfaces\n mDepth = mManager->requestRenderBuffer(depthFormat, width, height, mNumSamples);\n\t\tif (depthFormat == GL_DEPTH24_STENCIL8_EXT)\n\t\t{\n\t\t\t\/\/ bind same buffer to depth and stencil attachments\n mManager->requestRenderBuffer(mDepth);\n\t\t\tmStencil = mDepth;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ separate stencil\n\t\t\tmStencil = mManager->requestRenderBuffer(stencilFormat, width, height, mNumSamples);\n\t\t}\n \n \/\/\/ Attach\/detach surfaces\n if(mDepth.buffer)\n {\n mDepth.buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT_EXT, mDepth.zoffset);\n }\n else\n {\n glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,\n GL_RENDERBUFFER_EXT, 0);\n }\n if(mStencil.buffer)\n {\n mStencil.buffer->bindToFramebuffer(GL_STENCIL_ATTACHMENT_EXT, mStencil.zoffset);\n }\n else\n {\n glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,\n GL_RENDERBUFFER_EXT, 0);\n }\n\n\t\t\/\/\/ Do glDrawBuffer calls\n\t\tGLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];\n\t\tGLsizei n=0;\n\t\tfor(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)\n\t\t{\n\t\t\t\/\/ Fill attached colour buffers\n\t\t\tif(mColour[x].buffer)\n\t\t\t{\n\t\t\t\tbufs[x] = GL_COLOR_ATTACHMENT0_EXT + x;\n\t\t\t\t\/\/ Keep highest used buffer + 1\n\t\t\t\tn = x+1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbufs[x] = GL_NONE;\n\t\t\t}\n\t\t}\n\t\tif(glDrawBuffers)\n\t\t{\n\t\t\t\/\/\/ Drawbuffer extension supported, use it\n\t\t\tglDrawBuffers(n, bufs);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/\/ In this case, the capabilities will not show more than 1 simultaneaous render target.\n\t\t\tglDrawBuffer(bufs[0]);\n\t\t}\n\t\tif (mMultisampleFB)\n\t\t{\n\t\t\t\/\/ we need a read buffer because we'll be blitting to mFB\n\t\t\tglReadBuffer(bufs[0]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/\/ No read buffer, by default, if we want to read anyway we must not forget to set this.\n\t\t\tglReadBuffer(GL_NONE);\n\t\t}\n \n \/\/\/ Check status\n GLuint status;\n status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);\n \n \/\/\/ Bind main buffer\n glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);\n \n switch(status)\n {\n case GL_FRAMEBUFFER_COMPLETE_EXT:\n \/\/ All is good\n break;\n case GL_FRAMEBUFFER_UNSUPPORTED_EXT:\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, \n \"All framebuffer formats with this texture internal format unsupported\",\n\t\t \t\"GLFrameBufferObject::initialise\");\n default:\n OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, \n \"Framebuffer incomplete or other FBO status error\",\n\t\t \t\"GLFrameBufferObject::initialise\");\n }\n \n }\n void GLFrameBufferObject::bind()\n {\n \/\/\/ Bind it to FBO\n\t\tif (mMultisampleFB)\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);\n\t\telse\n\t\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);\n }\n\n\tvoid GLFrameBufferObject::swapBuffers()\n\t{\n\t\tif (mMultisampleFB)\n\t\t{\n\t\t\t\/\/ blit from multisample buffer to final buffer, triggers resolve\n\t\t\tsize_t width = mColour[0].buffer->getWidth();\n\t\t\tsize_t height = mColour[0].buffer->getHeight();\n\t\t\tglBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, mMultisampleFB);\n\t\t\tglBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, mFB);\n\t\t\tglBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);\n\n\t\t}\n\t}\n\n size_t GLFrameBufferObject::getWidth()\n {\n assert(mColour[0].buffer);\n return mColour[0].buffer->getWidth();\n }\n size_t GLFrameBufferObject::getHeight()\n {\n assert(mColour[0].buffer);\n return mColour[0].buffer->getHeight();\n }\n PixelFormat GLFrameBufferObject::getFormat()\n {\n assert(mColour[0].buffer);\n return mColour[0].buffer->getFormat();\n }\n\/\/-----------------------------------------------------------------------------\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Backend.cpp - Interface to LLVM backend technologies -------------===\/\/\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#include \"ASTConsumers.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTConsumer.h\"\n#include \"clang\/AST\/TranslationUnit.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/CodeGen\/ModuleBuilder.h\"\n#include \"clang\/Driver\/CompileOptions.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ModuleProvider.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/CodeGen\/RegAllocRegistry.h\"\n#include \"llvm\/CodeGen\/SchedulerRegistry.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/System\/Program.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n\nusing namespace clang;\nusing namespace llvm;\n\nnamespace {\n class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {\n BackendAction Action;\n CompileOptions CompileOpts;\n const std::string &InputFile;\n std::string OutputFile;\n bool GenerateDebugInfo;\n\n llvm::OwningPtr<CodeGenerator> Gen;\n \n llvm::Module *TheModule;\n llvm::TargetData *TheTargetData;\n llvm::raw_ostream *AsmOutStream;\n\n mutable llvm::ModuleProvider *ModuleProvider;\n mutable FunctionPassManager *CodeGenPasses;\n mutable PassManager *PerModulePasses;\n mutable FunctionPassManager *PerFunctionPasses;\n\n FunctionPassManager *getCodeGenPasses() const;\n PassManager *getPerModulePasses() const;\n FunctionPassManager *getPerFunctionPasses() const;\n\n void CreatePasses();\n\n \/\/\/ AddEmitPasses - Add passes necessary to emit assembly or LLVM\n \/\/\/ IR.\n \/\/\/\n \/\/\/ \\return True on success. On failure \\arg Error will be set to\n \/\/\/ a user readable error message.\n bool AddEmitPasses(std::string &Error);\n\n void EmitAssembly();\n \n public: \n BackendConsumer(BackendAction action, Diagnostic &Diags, \n const LangOptions &Features, const CompileOptions &compopts,\n const std::string& infile, const std::string& outfile,\n bool debug) :\n Action(action), \n CompileOpts(compopts),\n InputFile(infile), \n OutputFile(outfile), \n GenerateDebugInfo(debug),\n Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),\n TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),\n CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}\n\n ~BackendConsumer() {\n delete AsmOutStream;\n delete TheTargetData;\n delete ModuleProvider;\n delete CodeGenPasses;\n delete PerModulePasses;\n delete PerFunctionPasses;\n }\n\n virtual void InitializeTU(TranslationUnit& TU) {\n Gen->InitializeTU(TU);\n\n TheModule = Gen->GetModule();\n ModuleProvider = new ExistingModuleProvider(TheModule);\n TheTargetData = \n new llvm::TargetData(TU.getContext().Target.getTargetDescription());\n }\n \n virtual void HandleTopLevelDecl(Decl *D) {\n Gen->HandleTopLevelDecl(D);\n }\n \n virtual void HandleTranslationUnit(TranslationUnit& TU) {\n Gen->HandleTranslationUnit(TU);\n\n EmitAssembly(); \n \/\/ Force a flush here in case we never get released.\n if (AsmOutStream)\n AsmOutStream->flush();\n }\n \n virtual void HandleTagDeclDefinition(TagDecl *D) {\n Gen->HandleTagDeclDefinition(D);\n }\n }; \n}\n\nFunctionPassManager *BackendConsumer::getCodeGenPasses() const {\n if (!CodeGenPasses) {\n CodeGenPasses = new FunctionPassManager(ModuleProvider);\n CodeGenPasses->add(new TargetData(*TheTargetData));\n }\n\n return CodeGenPasses;\n}\n\nPassManager *BackendConsumer::getPerModulePasses() const {\n if (!PerModulePasses) {\n PerModulePasses = new PassManager();\n PerModulePasses->add(new TargetData(*TheTargetData));\n }\n\n return PerModulePasses;\n}\n\nFunctionPassManager *BackendConsumer::getPerFunctionPasses() const {\n if (!PerFunctionPasses) {\n PerFunctionPasses = new FunctionPassManager(ModuleProvider);\n PerFunctionPasses->add(new TargetData(*TheTargetData));\n }\n\n return PerFunctionPasses;\n}\n\nbool BackendConsumer::AddEmitPasses(std::string &Error) {\n if (OutputFile == \"-\" || (InputFile == \"-\" && OutputFile.empty())) {\n AsmOutStream = new raw_stdout_ostream();\n sys::Program::ChangeStdoutToBinary();\n } else {\n if (OutputFile.empty()) {\n llvm::sys::Path Path(InputFile);\n Path.eraseSuffix();\n if (Action == Backend_EmitBC) {\n Path.appendSuffix(\"bc\");\n } else if (Action == Backend_EmitLL) {\n Path.appendSuffix(\"ll\");\n } else {\n Path.appendSuffix(\"s\");\n }\n OutputFile = Path.toString();\n }\n\n AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error);\n if (!Error.empty())\n return false;\n }\n\n if (Action == Backend_EmitBC) {\n getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));\n } else if (Action == Backend_EmitLL) {\n getPerModulePasses()->add(createPrintModulePass(AsmOutStream));\n } else {\n bool Fast = CompileOpts.OptimizationLevel == 0;\n\n \/\/ Create the TargetMachine for generating code.\n const TargetMachineRegistry::entry *TME = \n TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);\n if (!TME) {\n Error = std::string(\"Unable to get target machine: \") + Error;\n return false;\n }\n \n \/\/ FIXME: Support features?\n std::string FeatureStr;\n TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);\n \n \/\/ Set register scheduler & allocation policy.\n RegisterScheduler::setDefault(createDefaultScheduler);\n RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator : \n createLinearScanRegisterAllocator); \n\n \/\/ From llvm-gcc:\n \/\/ If there are passes we have to run on the entire module, we do codegen\n \/\/ as a separate \"pass\" after that happens.\n \/\/ FIXME: This is disabled right now until bugs can be worked out. Reenable\n \/\/ this for fast -O0 compiles!\n FunctionPassManager *PM = getCodeGenPasses();\n \n \/\/ Normal mode, emit a .s file by running the code generator.\n \/\/ Note, this also adds codegenerator level optimization passes.\n switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,\n TargetMachine::AssemblyFile, Fast)) {\n default:\n case FileModel::Error:\n Error = \"Unable to interface with target machine!\\n\";\n return false;\n case FileModel::AsmFile:\n break;\n }\n \n if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {\n Error = \"Unable to interface with target machine!\\n\";\n return false;\n }\n }\n\n return true;\n}\n\nvoid BackendConsumer::CreatePasses() {\n \/\/ In -O0 if checking is disabled, we don't even have per-function passes.\n if (CompileOpts.VerifyModule)\n getPerFunctionPasses()->add(createVerifierPass());\n\n if (CompileOpts.OptimizationLevel > 0) {\n FunctionPassManager *PM = getPerFunctionPasses();\n PM->add(createCFGSimplificationPass());\n if (CompileOpts.OptimizationLevel == 1)\n PM->add(createPromoteMemoryToRegisterPass());\n else\n PM->add(createScalarReplAggregatesPass());\n PM->add(createInstructionCombiningPass());\n }\n\n \/\/ For now we always create per module passes.\n PassManager *PM = getPerModulePasses();\n if (CompileOpts.OptimizationLevel > 0) {\n if (CompileOpts.UnitAtATime)\n PM->add(createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n PM->add(createCFGSimplificationPass()); \/\/ Clean up disgusting code\n PM->add(createPromoteMemoryToRegisterPass()); \/\/ Kill useless allocas\n if (CompileOpts.UnitAtATime) {\n PM->add(createGlobalOptimizerPass()); \/\/ Optimize out global vars\n PM->add(createGlobalDCEPass()); \/\/ Remove unused fns and globs\n PM->add(createIPConstantPropagationPass()); \/\/ IP Constant Propagation\n PM->add(createDeadArgEliminationPass()); \/\/ Dead argument elimination\n }\n PM->add(createInstructionCombiningPass()); \/\/ Clean up after IPCP & DAE\n PM->add(createCFGSimplificationPass()); \/\/ Clean up after IPCP & DAE\n if (CompileOpts.UnitAtATime) {\n PM->add(createPruneEHPass()); \/\/ Remove dead EH info\n PM->add(createFunctionAttrsPass()); \/\/ Set readonly\/readnone attrs\n }\n if (CompileOpts.InlineFunctions)\n PM->add(createFunctionInliningPass()); \/\/ Inline small functions\n else \n PM->add(createAlwaysInlinerPass()); \/\/ Respect always_inline\n if (CompileOpts.OptimizationLevel > 2)\n PM->add(createArgumentPromotionPass()); \/\/ Scalarize uninlined fn args\n if (CompileOpts.SimplifyLibCalls)\n PM->add(createSimplifyLibCallsPass()); \/\/ Library Call Optimizations\n PM->add(createInstructionCombiningPass()); \/\/ Cleanup for scalarrepl.\n PM->add(createJumpThreadingPass()); \/\/ Thread jumps.\n PM->add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n PM->add(createScalarReplAggregatesPass()); \/\/ Break up aggregate allocas\n PM->add(createInstructionCombiningPass()); \/\/ Combine silly seq's\n PM->add(createCondPropagationPass()); \/\/ Propagate conditionals\n PM->add(createTailCallEliminationPass()); \/\/ Eliminate tail calls\n PM->add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n PM->add(createReassociatePass()); \/\/ Reassociate expressions\n PM->add(createLoopRotatePass()); \/\/ Rotate Loop\n PM->add(createLICMPass()); \/\/ Hoist loop invariants\n PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));\n\/\/ PM->add(createLoopIndexSplitPass()); \/\/ Split loop index\n PM->add(createInstructionCombiningPass()); \n PM->add(createIndVarSimplifyPass()); \/\/ Canonicalize indvars\n PM->add(createLoopDeletionPass()); \/\/ Delete dead loops\n if (CompileOpts.UnrollLoops)\n PM->add(createLoopUnrollPass()); \/\/ Unroll small loops\n PM->add(createInstructionCombiningPass()); \/\/ Clean up after the unroller\n PM->add(createGVNPass()); \/\/ Remove redundancies\n PM->add(createMemCpyOptPass()); \/\/ Remove memcpy \/ form memset\n PM->add(createSCCPPass()); \/\/ Constant prop with SCCP\n \n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n PM->add(createInstructionCombiningPass());\n PM->add(createCondPropagationPass()); \/\/ Propagate conditionals\n PM->add(createDeadStoreEliminationPass()); \/\/ Delete dead stores\n PM->add(createAggressiveDCEPass()); \/\/ Delete dead instructions\n PM->add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n\n if (CompileOpts.UnitAtATime) {\n PM->add(createStripDeadPrototypesPass()); \/\/ Get rid of dead prototypes\n PM->add(createDeadTypeEliminationPass()); \/\/ Eliminate dead types\n }\n\n if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)\n PM->add(createConstantMergePass()); \/\/ Merge dup global constants \n } else {\n PM->add(createAlwaysInlinerPass()); \n }\n}\n\n\/\/\/ EmitAssembly - Handle interaction with LLVM backend to generate\n\/\/\/ actual machine code. \nvoid BackendConsumer::EmitAssembly() {\n \/\/ Silently ignore if we weren't initialized for some reason.\n if (!TheModule || !TheTargetData)\n return;\n\n \/\/ Make sure IR generation is happy with the module. This is\n \/\/ released by the module provider.\n Module *M = Gen->ReleaseModule();\n if (!M) {\n \/\/ The module has been released by IR gen on failures, do not\n \/\/ double free.\n ModuleProvider->releaseModule();\n TheModule = 0;\n return;\n }\n\n assert(TheModule == M && \"Unexpected module change during IR generation\");\n\n CreatePasses();\n\n std::string Error;\n if (!AddEmitPasses(Error)) {\n \/\/ FIXME: Don't fail this way.\n llvm::cerr << \"ERROR: \" << Error << \"\\n\";\n ::exit(1);\n }\n\n \/\/ Run passes. For now we do all passes at once, but eventually we\n \/\/ would like to have the option of streaming code generation.\n\n if (PerFunctionPasses) {\n PerFunctionPasses->doInitialization();\n for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)\n if (!I->isDeclaration())\n PerFunctionPasses->run(*I);\n PerFunctionPasses->doFinalization();\n }\n \n if (PerModulePasses)\n PerModulePasses->run(*M);\n \n if (CodeGenPasses) {\n CodeGenPasses->doInitialization();\n for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)\n if (!I->isDeclaration())\n CodeGenPasses->run(*I);\n CodeGenPasses->doFinalization();\n }\n}\n\nASTConsumer *clang::CreateBackendConsumer(BackendAction Action,\n Diagnostic &Diags,\n const LangOptions &Features,\n const CompileOptions &CompileOpts,\n const std::string& InFile,\n const std::string& OutFile,\n bool GenerateDebugInfo) {\n return new BackendConsumer(Action, Diags, Features, CompileOpts,\n InFile, OutFile, GenerateDebugInfo); \n}\n<commit_msg>for now, disable all debug info generation at -O1 and above. This mirrors similar logic in llvm-gcc and will hopefully be fixed soon.<commit_after>\/\/===--- Backend.cpp - Interface to LLVM backend technologies -------------===\/\/\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#include \"ASTConsumers.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTConsumer.h\"\n#include \"clang\/AST\/TranslationUnit.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/CodeGen\/ModuleBuilder.h\"\n#include \"clang\/Driver\/CompileOptions.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ModuleProvider.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/CodeGen\/RegAllocRegistry.h\"\n#include \"llvm\/CodeGen\/SchedulerRegistry.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/System\/Program.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n\nusing namespace clang;\nusing namespace llvm;\n\nnamespace {\n class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {\n BackendAction Action;\n CompileOptions CompileOpts;\n const std::string &InputFile;\n std::string OutputFile;\n bool GenerateDebugInfo;\n\n llvm::OwningPtr<CodeGenerator> Gen;\n \n llvm::Module *TheModule;\n llvm::TargetData *TheTargetData;\n llvm::raw_ostream *AsmOutStream;\n\n mutable llvm::ModuleProvider *ModuleProvider;\n mutable FunctionPassManager *CodeGenPasses;\n mutable PassManager *PerModulePasses;\n mutable FunctionPassManager *PerFunctionPasses;\n\n FunctionPassManager *getCodeGenPasses() const;\n PassManager *getPerModulePasses() const;\n FunctionPassManager *getPerFunctionPasses() const;\n\n void CreatePasses();\n\n \/\/\/ AddEmitPasses - Add passes necessary to emit assembly or LLVM\n \/\/\/ IR.\n \/\/\/\n \/\/\/ \\return True on success. On failure \\arg Error will be set to\n \/\/\/ a user readable error message.\n bool AddEmitPasses(std::string &Error);\n\n void EmitAssembly();\n \n public: \n BackendConsumer(BackendAction action, Diagnostic &Diags, \n const LangOptions &Features, const CompileOptions &compopts,\n const std::string& infile, const std::string& outfile,\n bool debug) :\n Action(action), \n CompileOpts(compopts),\n InputFile(infile), \n OutputFile(outfile), \n GenerateDebugInfo(debug),\n Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),\n TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),\n CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}\n\n ~BackendConsumer() {\n delete AsmOutStream;\n delete TheTargetData;\n delete ModuleProvider;\n delete CodeGenPasses;\n delete PerModulePasses;\n delete PerFunctionPasses;\n }\n\n virtual void InitializeTU(TranslationUnit& TU) {\n Gen->InitializeTU(TU);\n\n TheModule = Gen->GetModule();\n ModuleProvider = new ExistingModuleProvider(TheModule);\n TheTargetData = \n new llvm::TargetData(TU.getContext().Target.getTargetDescription());\n }\n \n virtual void HandleTopLevelDecl(Decl *D) {\n Gen->HandleTopLevelDecl(D);\n }\n \n virtual void HandleTranslationUnit(TranslationUnit& TU) {\n Gen->HandleTranslationUnit(TU);\n\n EmitAssembly(); \n \/\/ Force a flush here in case we never get released.\n if (AsmOutStream)\n AsmOutStream->flush();\n }\n \n virtual void HandleTagDeclDefinition(TagDecl *D) {\n Gen->HandleTagDeclDefinition(D);\n }\n }; \n}\n\nFunctionPassManager *BackendConsumer::getCodeGenPasses() const {\n if (!CodeGenPasses) {\n CodeGenPasses = new FunctionPassManager(ModuleProvider);\n CodeGenPasses->add(new TargetData(*TheTargetData));\n }\n\n return CodeGenPasses;\n}\n\nPassManager *BackendConsumer::getPerModulePasses() const {\n if (!PerModulePasses) {\n PerModulePasses = new PassManager();\n PerModulePasses->add(new TargetData(*TheTargetData));\n }\n\n return PerModulePasses;\n}\n\nFunctionPassManager *BackendConsumer::getPerFunctionPasses() const {\n if (!PerFunctionPasses) {\n PerFunctionPasses = new FunctionPassManager(ModuleProvider);\n PerFunctionPasses->add(new TargetData(*TheTargetData));\n }\n\n return PerFunctionPasses;\n}\n\nbool BackendConsumer::AddEmitPasses(std::string &Error) {\n if (OutputFile == \"-\" || (InputFile == \"-\" && OutputFile.empty())) {\n AsmOutStream = new raw_stdout_ostream();\n sys::Program::ChangeStdoutToBinary();\n } else {\n if (OutputFile.empty()) {\n llvm::sys::Path Path(InputFile);\n Path.eraseSuffix();\n if (Action == Backend_EmitBC) {\n Path.appendSuffix(\"bc\");\n } else if (Action == Backend_EmitLL) {\n Path.appendSuffix(\"ll\");\n } else {\n Path.appendSuffix(\"s\");\n }\n OutputFile = Path.toString();\n }\n\n AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error);\n if (!Error.empty())\n return false;\n }\n\n if (Action == Backend_EmitBC) {\n getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));\n } else if (Action == Backend_EmitLL) {\n getPerModulePasses()->add(createPrintModulePass(AsmOutStream));\n } else {\n bool Fast = CompileOpts.OptimizationLevel == 0;\n\n \/\/ Create the TargetMachine for generating code.\n const TargetMachineRegistry::entry *TME = \n TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);\n if (!TME) {\n Error = std::string(\"Unable to get target machine: \") + Error;\n return false;\n }\n \n \/\/ FIXME: Support features?\n std::string FeatureStr;\n TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);\n \n \/\/ Set register scheduler & allocation policy.\n RegisterScheduler::setDefault(createDefaultScheduler);\n RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator : \n createLinearScanRegisterAllocator); \n\n \/\/ From llvm-gcc:\n \/\/ If there are passes we have to run on the entire module, we do codegen\n \/\/ as a separate \"pass\" after that happens.\n \/\/ FIXME: This is disabled right now until bugs can be worked out. Reenable\n \/\/ this for fast -O0 compiles!\n FunctionPassManager *PM = getCodeGenPasses();\n \n \/\/ Normal mode, emit a .s file by running the code generator.\n \/\/ Note, this also adds codegenerator level optimization passes.\n switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,\n TargetMachine::AssemblyFile, Fast)) {\n default:\n case FileModel::Error:\n Error = \"Unable to interface with target machine!\\n\";\n return false;\n case FileModel::AsmFile:\n break;\n }\n \n if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {\n Error = \"Unable to interface with target machine!\\n\";\n return false;\n }\n }\n\n return true;\n}\n\nvoid BackendConsumer::CreatePasses() {\n \/\/ In -O0 if checking is disabled, we don't even have per-function passes.\n if (CompileOpts.VerifyModule)\n getPerFunctionPasses()->add(createVerifierPass());\n\n if (CompileOpts.OptimizationLevel > 0) {\n FunctionPassManager *PM = getPerFunctionPasses();\n PM->add(createCFGSimplificationPass());\n if (CompileOpts.OptimizationLevel == 1)\n PM->add(createPromoteMemoryToRegisterPass());\n else\n PM->add(createScalarReplAggregatesPass());\n PM->add(createInstructionCombiningPass());\n }\n\n \/\/ For now we always create per module passes.\n PassManager *PM = getPerModulePasses();\n if (CompileOpts.OptimizationLevel > 0) {\n if (CompileOpts.UnitAtATime)\n PM->add(createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n PM->add(createCFGSimplificationPass()); \/\/ Clean up disgusting code\n PM->add(createPromoteMemoryToRegisterPass()); \/\/ Kill useless allocas\n if (CompileOpts.UnitAtATime) {\n PM->add(createGlobalOptimizerPass()); \/\/ Optimize out global vars\n PM->add(createGlobalDCEPass()); \/\/ Remove unused fns and globs\n PM->add(createIPConstantPropagationPass()); \/\/ IP Constant Propagation\n PM->add(createDeadArgEliminationPass()); \/\/ Dead argument elimination\n }\n PM->add(createInstructionCombiningPass()); \/\/ Clean up after IPCP & DAE\n PM->add(createCFGSimplificationPass()); \/\/ Clean up after IPCP & DAE\n if (CompileOpts.UnitAtATime) {\n PM->add(createPruneEHPass()); \/\/ Remove dead EH info\n PM->add(createFunctionAttrsPass()); \/\/ Set readonly\/readnone attrs\n }\n if (CompileOpts.InlineFunctions)\n PM->add(createFunctionInliningPass()); \/\/ Inline small functions\n else \n PM->add(createAlwaysInlinerPass()); \/\/ Respect always_inline\n if (CompileOpts.OptimizationLevel > 2)\n PM->add(createArgumentPromotionPass()); \/\/ Scalarize uninlined fn args\n if (CompileOpts.SimplifyLibCalls)\n PM->add(createSimplifyLibCallsPass()); \/\/ Library Call Optimizations\n PM->add(createInstructionCombiningPass()); \/\/ Cleanup for scalarrepl.\n PM->add(createJumpThreadingPass()); \/\/ Thread jumps.\n PM->add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n PM->add(createScalarReplAggregatesPass()); \/\/ Break up aggregate allocas\n PM->add(createInstructionCombiningPass()); \/\/ Combine silly seq's\n PM->add(createCondPropagationPass()); \/\/ Propagate conditionals\n PM->add(createTailCallEliminationPass()); \/\/ Eliminate tail calls\n PM->add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n PM->add(createReassociatePass()); \/\/ Reassociate expressions\n PM->add(createLoopRotatePass()); \/\/ Rotate Loop\n PM->add(createLICMPass()); \/\/ Hoist loop invariants\n PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));\n\/\/ PM->add(createLoopIndexSplitPass()); \/\/ Split loop index\n PM->add(createInstructionCombiningPass()); \n PM->add(createIndVarSimplifyPass()); \/\/ Canonicalize indvars\n PM->add(createLoopDeletionPass()); \/\/ Delete dead loops\n if (CompileOpts.UnrollLoops)\n PM->add(createLoopUnrollPass()); \/\/ Unroll small loops\n PM->add(createInstructionCombiningPass()); \/\/ Clean up after the unroller\n PM->add(createGVNPass()); \/\/ Remove redundancies\n PM->add(createMemCpyOptPass()); \/\/ Remove memcpy \/ form memset\n PM->add(createSCCPPass()); \/\/ Constant prop with SCCP\n \n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n PM->add(createInstructionCombiningPass());\n PM->add(createCondPropagationPass()); \/\/ Propagate conditionals\n PM->add(createDeadStoreEliminationPass()); \/\/ Delete dead stores\n PM->add(createAggressiveDCEPass()); \/\/ Delete dead instructions\n PM->add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n\n if (CompileOpts.UnitAtATime) {\n PM->add(createStripDeadPrototypesPass()); \/\/ Get rid of dead prototypes\n PM->add(createDeadTypeEliminationPass()); \/\/ Eliminate dead types\n }\n\n if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)\n PM->add(createConstantMergePass()); \/\/ Merge dup global constants \n } else {\n PM->add(createAlwaysInlinerPass()); \n }\n}\n\n\/\/\/ EmitAssembly - Handle interaction with LLVM backend to generate\n\/\/\/ actual machine code. \nvoid BackendConsumer::EmitAssembly() {\n \/\/ Silently ignore if we weren't initialized for some reason.\n if (!TheModule || !TheTargetData)\n return;\n\n \/\/ Make sure IR generation is happy with the module. This is\n \/\/ released by the module provider.\n Module *M = Gen->ReleaseModule();\n if (!M) {\n \/\/ The module has been released by IR gen on failures, do not\n \/\/ double free.\n ModuleProvider->releaseModule();\n TheModule = 0;\n return;\n }\n\n assert(TheModule == M && \"Unexpected module change during IR generation\");\n\n CreatePasses();\n\n std::string Error;\n if (!AddEmitPasses(Error)) {\n \/\/ FIXME: Don't fail this way.\n llvm::cerr << \"ERROR: \" << Error << \"\\n\";\n ::exit(1);\n }\n\n \/\/ Run passes. For now we do all passes at once, but eventually we\n \/\/ would like to have the option of streaming code generation.\n\n if (PerFunctionPasses) {\n PerFunctionPasses->doInitialization();\n for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)\n if (!I->isDeclaration())\n PerFunctionPasses->run(*I);\n PerFunctionPasses->doFinalization();\n }\n \n if (PerModulePasses)\n PerModulePasses->run(*M);\n \n if (CodeGenPasses) {\n CodeGenPasses->doInitialization();\n for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)\n if (!I->isDeclaration())\n CodeGenPasses->run(*I);\n CodeGenPasses->doFinalization();\n }\n}\n\nASTConsumer *clang::CreateBackendConsumer(BackendAction Action,\n Diagnostic &Diags,\n const LangOptions &Features,\n const CompileOptions &CompileOpts,\n const std::string& InFile,\n const std::string& OutFile,\n bool GenerateDebugInfo) {\n \/\/ FIXME: If optimizing, disable all debug info generation. The LLVM\n \/\/ optimizer and backend is not ready to handle it when optimizations\n \/\/ are enabled.\n if (CompileOpts.OptimizationLevel > 0)\n GenerateDebugInfo = false;\n \n \n return new BackendConsumer(Action, Diags, Features, CompileOpts,\n InFile, OutFile, GenerateDebugInfo); \n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ MathLib.cpp\r\n\/\/ This file is part of the EScript programming language.\r\n\/\/ See copyright notice in EScript.h\r\n\/\/ ------------------------------------------------------\r\n#include \"MathLib.h\"\r\n#include <cmath>\r\n\r\n#include \"ext\/Rand.h\"\r\n#include \"..\/EScript\/EScript.h\"\r\n\r\nnamespace EScript{\r\nnamespace MathLib{\r\n\r\n\r\n\/\/ ---------------------------------------------------------\r\n\r\n\/\/! EWrapper for Rand-Class\r\nclass E_RandNumGenerator : public ReferenceObject<Rand> {\r\n\tES_PROVIDES_TYPE_NAME(RandNumGenerator);\r\npublic:\r\n\t\/\/! (static)\r\n\tstatic Type * getTypeObject() {\r\n\t\tstatic Type * typeObject=new Type(Object::getTypeObject());\r\n\t\treturn typeObject;\r\n\t}\r\n\tstatic void init(EScript::Namespace & globals);\r\n\r\n\t\/\/! (ctor)\r\n\tE_RandNumGenerator(uint32_t seed=0):\r\n\t\t\tReferenceObject<Rand>(seed,getTypeObject()){}\r\n\r\n\t\/\/! (dtor)\r\n\tvirtual ~E_RandNumGenerator(){}\r\n};\r\n\r\n\r\n\/\/ ---------------------------------------------------------\r\n\r\n\/\/! (static) MathLib init\r\nvoid init(EScript::Namespace * globals) {\r\n\tNamespace * lib=new Namespace();\r\n\tdeclareConstant(globals,\"Math\",lib);\r\n\r\n\tdeclareConstant(lib,\"PI\",Number::create(M_PI));\r\n\tdeclareConstant(lib,\"PI_2\",Number::create(M_PI_2));\r\n\/\/\r\n\/\/\t\/*!\t[ESF] number Math.rand(max,[seed])\r\n\/\/\t\tbased on \/\/ http:\/\/www.cs.wm.edu\/~va\/software\/park\/\t*\/\r\n\/\/\tES_FUNCTION_DECLARE(lib,\"rand\",1,2,{\r\n\/\/\t\tstatic long seed=1;\r\n\/\/\t\tif (parameter.count()>1)\r\n\/\/\t\t\tseed=static_cast<unsigned int>(parameter[1].toInt());\r\n\/\/\t\tconst long Q = 2147483647 \/ 48271;\r\n\/\/\t\tconst long R = 2147483647 % 48271;\r\n\/\/\t\tlong t = 48271 * (seed % Q) - R * (seed \/ Q);\r\n\/\/\t\tif (t > 0)\r\n\/\/\t\t\tseed = t;\r\n\/\/\t\telse\r\n\/\/\t\t\tseed = t + 2147483647;\r\n\/\/\t\treturn Number::create( seed%(static_cast<unsigned int>(parameter[0].toInt()+1)));\r\n\/\/\t})\r\n\r\n\t\/\/! Number Math.atan2(a,b)\r\n\tESF_DECLARE(lib, \"atan2\", 2, 2,\r\n\t\t\t\tNumber::create(std::atan2(parameter[0].toDouble(), parameter[1].toDouble())))\r\n\r\n\r\n\t\/\/ init E_RandNumGenerator\r\n\tE_RandNumGenerator::init(*lib);\r\n\r\n\t\/\/ init global E_RandNumGenerator-Object\r\n\tdeclareConstant(globals,\"Rand\",new E_RandNumGenerator);\r\n\r\n\t\/\/ ------\r\n}\r\n\r\n\/\/ ---------------------------------------------------------------\r\n\r\n\/\/! (static) init members for E_RandNumGenerator\r\nvoid E_RandNumGenerator::init(EScript::Namespace & lib) {\r\n\r\n\t\/\/ E_Rand ---|> [Object]\r\n\tType * typeObject=getTypeObject();\r\n\tdeclareConstant(&lib,getClassName(),typeObject);\r\n\r\n\r\n\t\/\/! [ESF] new RandNumGenerator( [seed] )\r\n\tESF_DECLARE(typeObject,\"_constructor\",0,1,(\r\n\t\t\tnew E_RandNumGenerator(parameter[0].toInt(0))))\r\n\r\n\t\/\/! [ESF] [0,1] RandNumGenerator.bernoulli(p)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"bernoulli\",1,1,(\r\n\t\t\tNumber::create( self->ref().bernoulli(parameter[0].toDouble()))))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.binomial(n,p)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"binomial\",2,2,\r\n\t\t\t\tNumber::create( self->ref().binomial(parameter[0].toInt(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.chisquare(n)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"chisquare\",1,1,\r\n\t\t\t\tNumber::create(self->ref().chisquare(parameter[0].toInt())))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.equilikely(a,b)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"equilikely\",2,2,\r\n\t\t\t\tNumber::create(self->ref().equilikely(parameter[0].toInt(),parameter[1].toInt())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.erlang(n,b)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"erlang\",2,2,\r\n\t\t\t\tNumber::create( self->ref().erlang(parameter[0].toInt(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.exponential(m)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"exponential\",1,1,\r\n\t\t\t\tNumber::create(self->ref().exponential(parameter[0].toDouble())))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.geometric(p)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"geometric\",1,1,\r\n\t\t\t\tNumber::create( self->ref().geometric(parameter[0].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.lognormal(a,b)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"lognormal\",2,2,\r\n\t\t\t\tNumber::create( self->ref().lognormal(parameter[0].toDouble(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.normal(m,s)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"normal\",2,2,\r\n\t\t\t\tNumber::create( self->ref().normal(parameter[0].toDouble(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.pascal(n,p)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"pascal\",2,2,\r\n\t\t\t\tNumber::create(self->ref().pascal(parameter[0].toInt(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.poisson(m)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"poisson\",1,1,\r\n\t\t\t\tNumber::create(self->ref().poisson(parameter[0].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.random() [0.0 ... 1.0]\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"random\",0,0,\r\n\t\t\t\tNumber::create(self->ref().random()))\r\n\r\n\t\/\/! [ESF]float RandNumGenerator.student(n)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"student\",1,1,\r\n\t\t\t\tNumber::create(self->ref().student(parameter[0].toInt())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.uniform(a,b)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"uniform\",2,2,\r\n\t\t\t\tNumber::create( self->ref().uniform(parameter[0].toDouble(),parameter[1].toDouble())))\r\n\r\n}\r\n\/\/ ---------------------------------------------------------------\r\n\r\n}\r\n}\r\n<commit_msg>Remove extra ;<commit_after>\/\/ MathLib.cpp\r\n\/\/ This file is part of the EScript programming language.\r\n\/\/ See copyright notice in EScript.h\r\n\/\/ ------------------------------------------------------\r\n#include \"MathLib.h\"\r\n#include <cmath>\r\n\r\n#include \"ext\/Rand.h\"\r\n#include \"..\/EScript\/EScript.h\"\r\n\r\nnamespace EScript{\r\nnamespace MathLib{\r\n\r\n\r\n\/\/ ---------------------------------------------------------\r\n\r\n\/\/! EWrapper for Rand-Class\r\nclass E_RandNumGenerator : public ReferenceObject<Rand> {\r\n\tES_PROVIDES_TYPE_NAME(RandNumGenerator)\r\npublic:\r\n\t\/\/! (static)\r\n\tstatic Type * getTypeObject() {\r\n\t\tstatic Type * typeObject=new Type(Object::getTypeObject());\r\n\t\treturn typeObject;\r\n\t}\r\n\tstatic void init(EScript::Namespace & globals);\r\n\r\n\t\/\/! (ctor)\r\n\tE_RandNumGenerator(uint32_t seed=0):\r\n\t\t\tReferenceObject<Rand>(seed,getTypeObject()){}\r\n\r\n\t\/\/! (dtor)\r\n\tvirtual ~E_RandNumGenerator(){}\r\n};\r\n\r\n\r\n\/\/ ---------------------------------------------------------\r\n\r\n\/\/! (static) MathLib init\r\nvoid init(EScript::Namespace * globals) {\r\n\tNamespace * lib=new Namespace();\r\n\tdeclareConstant(globals,\"Math\",lib);\r\n\r\n\tdeclareConstant(lib,\"PI\",Number::create(M_PI));\r\n\tdeclareConstant(lib,\"PI_2\",Number::create(M_PI_2));\r\n\/\/\r\n\/\/\t\/*!\t[ESF] number Math.rand(max,[seed])\r\n\/\/\t\tbased on \/\/ http:\/\/www.cs.wm.edu\/~va\/software\/park\/\t*\/\r\n\/\/\tES_FUNCTION_DECLARE(lib,\"rand\",1,2,{\r\n\/\/\t\tstatic long seed=1;\r\n\/\/\t\tif (parameter.count()>1)\r\n\/\/\t\t\tseed=static_cast<unsigned int>(parameter[1].toInt());\r\n\/\/\t\tconst long Q = 2147483647 \/ 48271;\r\n\/\/\t\tconst long R = 2147483647 % 48271;\r\n\/\/\t\tlong t = 48271 * (seed % Q) - R * (seed \/ Q);\r\n\/\/\t\tif (t > 0)\r\n\/\/\t\t\tseed = t;\r\n\/\/\t\telse\r\n\/\/\t\t\tseed = t + 2147483647;\r\n\/\/\t\treturn Number::create( seed%(static_cast<unsigned int>(parameter[0].toInt()+1)));\r\n\/\/\t})\r\n\r\n\t\/\/! Number Math.atan2(a,b)\r\n\tESF_DECLARE(lib, \"atan2\", 2, 2,\r\n\t\t\t\tNumber::create(std::atan2(parameter[0].toDouble(), parameter[1].toDouble())))\r\n\r\n\r\n\t\/\/ init E_RandNumGenerator\r\n\tE_RandNumGenerator::init(*lib);\r\n\r\n\t\/\/ init global E_RandNumGenerator-Object\r\n\tdeclareConstant(globals,\"Rand\",new E_RandNumGenerator);\r\n\r\n\t\/\/ ------\r\n}\r\n\r\n\/\/ ---------------------------------------------------------------\r\n\r\n\/\/! (static) init members for E_RandNumGenerator\r\nvoid E_RandNumGenerator::init(EScript::Namespace & lib) {\r\n\r\n\t\/\/ E_Rand ---|> [Object]\r\n\tType * typeObject=getTypeObject();\r\n\tdeclareConstant(&lib,getClassName(),typeObject);\r\n\r\n\r\n\t\/\/! [ESF] new RandNumGenerator( [seed] )\r\n\tESF_DECLARE(typeObject,\"_constructor\",0,1,(\r\n\t\t\tnew E_RandNumGenerator(parameter[0].toInt(0))))\r\n\r\n\t\/\/! [ESF] [0,1] RandNumGenerator.bernoulli(p)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"bernoulli\",1,1,(\r\n\t\t\tNumber::create( self->ref().bernoulli(parameter[0].toDouble()))))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.binomial(n,p)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"binomial\",2,2,\r\n\t\t\t\tNumber::create( self->ref().binomial(parameter[0].toInt(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.chisquare(n)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"chisquare\",1,1,\r\n\t\t\t\tNumber::create(self->ref().chisquare(parameter[0].toInt())))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.equilikely(a,b)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"equilikely\",2,2,\r\n\t\t\t\tNumber::create(self->ref().equilikely(parameter[0].toInt(),parameter[1].toInt())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.erlang(n,b)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"erlang\",2,2,\r\n\t\t\t\tNumber::create( self->ref().erlang(parameter[0].toInt(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.exponential(m)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"exponential\",1,1,\r\n\t\t\t\tNumber::create(self->ref().exponential(parameter[0].toDouble())))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.geometric(p)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"geometric\",1,1,\r\n\t\t\t\tNumber::create( self->ref().geometric(parameter[0].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.lognormal(a,b)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"lognormal\",2,2,\r\n\t\t\t\tNumber::create( self->ref().lognormal(parameter[0].toDouble(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.normal(m,s)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"normal\",2,2,\r\n\t\t\t\tNumber::create( self->ref().normal(parameter[0].toDouble(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.pascal(n,p)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"pascal\",2,2,\r\n\t\t\t\tNumber::create(self->ref().pascal(parameter[0].toInt(),parameter[1].toDouble())))\r\n\r\n\t\/\/! [ESF] int RandNumGenerator.poisson(m)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"poisson\",1,1,\r\n\t\t\t\tNumber::create(self->ref().poisson(parameter[0].toDouble())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.random() [0.0 ... 1.0]\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"random\",0,0,\r\n\t\t\t\tNumber::create(self->ref().random()))\r\n\r\n\t\/\/! [ESF]float RandNumGenerator.student(n)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"student\",1,1,\r\n\t\t\t\tNumber::create(self->ref().student(parameter[0].toInt())))\r\n\r\n\t\/\/! [ESF] float RandNumGenerator.uniform(a,b)\r\n\tESMF_DECLARE(typeObject,E_RandNumGenerator,\"uniform\",2,2,\r\n\t\t\t\tNumber::create( self->ref().uniform(parameter[0].toDouble(),parameter[1].toDouble())))\r\n\r\n}\r\n\/\/ ---------------------------------------------------------------\r\n\r\n}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ FONcTransmitter.cc\n\n\/\/ This file is part of BES Netcdf File Out Module\n\n\/\/ Copyright (c) 2004,2005 University Corporation for Atmospheric Research\n\/\/ Author: Patrick West <pwest@ucar.edu> and Jose Garcia <jgarcia@ucar.edu>\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\/\/ You can contact University Corporation for Atmospheric Research at\n\/\/ 3080 Center Green Drive, Boulder, CO 80301\n\n\/\/ (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005\n\/\/ Please read the full copyright statement in the file COPYRIGHT_UCAR.\n\/\/\n\/\/ Authors:\n\/\/ pwest Patrick West <pwest@ucar.edu>\n\/\/ jgarcia Jose Garcia <jgarcia@ucar.edu>\n\n#include \"config.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\n#include <sys\/types.h> \/\/ For umask\n#include <sys\/stat.h>\n\n#include <iostream>\n#include <fstream>\n#include <exception>\n\n#include <DataDDS.h>\n#include <BaseType.h>\n#include <escaping.h>\n#include <ConstraintEvaluator.h>\n\n#include <BESInternalError.h>\n#include <BESDapError.h>\n#include <TheBESKeys.h>\n#include <BESContextManager.h>\n#include <BESDataDDSResponse.h>\n#include <BESDapNames.h>\n#include <BESDataNames.h>\n#include <BESDebug.h>\n#include <DapFunctionUtils.h>\n\n#include \"FONcBaseType.h\"\n#include \"FONcRequestHandler.h\"\n#include \"FONcTransmitter.h\"\n#include \"FONcTransform.h\"\n\nusing namespace ::libdap;\nusing namespace std;\n\n\/\/ size of the buffer used to read from the temporary file built on disk and\n\/\/ send data to the client over the network connection (socket\/stream)\n#define OUTPUT_FILE_BLOCK_SIZE 4096\n\n\/** @brief Construct the FONcTransmitter, adding it with name netcdf to be\n * able to transmit a data response\n *\n * The transmitter is created to add the ability to return OPeNDAP data\n * objects (DataDDS) as a netcdf file.\n *\n * The OPeNDAP data object is written to a netcdf file locally in a\n * temporary directory specified by the BES configuration parameter\n * FONc.Tempdir. If this variable is not found or is not set then it\n * defaults to the macro definition FONC_TEMP_DIR.\n *\/\nFONcTransmitter::FONcTransmitter() :\n BESBasicTransmitter()\n{\n add_method(DATA_SERVICE, FONcTransmitter::send_data);\n}\n\n#if 0\n\/**\n * Hack to ensure the file descriptor for the temporary file is closed.\n *\/\nstruct wrap_file_descriptor {\n int fd;\n wrap_file_descriptor(int i) : fd(i) { }\n ~wrap_file_descriptor() { cerr << \"*** Closing fd\" << endl; close(fd); }\n};\n#endif\n\n\/** @brief The static method registered to transmit OPeNDAP data objects as\n * a netcdf file.\n *\n * This function takes the OPeNDAP DataDDS object, reads in the data (can be\n * used with any data handler), transforms the data into a netcdf file, and\n * streams back that netcdf file back to the requester using the stream\n * specified in the BESDataHandlerInterface.\n *\n * @param obj The BESResponseObject containing the OPeNDAP DataDDS object\n * @param dhi BESDataHandlerInterface containing information about the\n * request and response\n * @throws BESInternalError if the response is not an OPeNDAP DataDDS or if\n * there are any problems reading the data, writing to a netcdf file, or\n * streaming the netcdf file\n *\/\nvoid FONcTransmitter::send_data(BESResponseObject *obj, BESDataHandlerInterface &dhi)\n{\n BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj);\n if (!bdds) throw BESInternalError(\"cast error\", __FILE__, __LINE__);\n\n libdap::DataDDS *dds = bdds->get_dds();\n if (!dds) throw BESInternalError(\"No DataDDS has been created for transmit\", __FILE__, __LINE__);\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Parsing the constraint\" << endl);\n\n ConstraintEvaluator &eval = bdds->get_ce();\n\n string ncVersion = dhi.data[RETURN_CMD];\n\n ostream &strm = dhi.get_output_stream();\n if (!strm) throw BESInternalError(\"Output stream is not set, can not return as\", __FILE__, __LINE__);\n\n \/\/ ticket 1248 jhrg 2\/23\/09\n string ce = www2id(dhi.data[POST_CONSTRAINT], \"%\", \"%20%26\");\n try {\n eval.parse_constraint(ce, *dds);\n }\n catch (Error &e) {\n throw BESDapError(\"Failed to parse the constraint expression: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (...) {\n throw BESInternalError(\"Failed to parse the constraint expression: Unknown exception caught\", __FILE__,\n __LINE__);\n }\n\n \/\/ The dataset_name is no longer used in the constraint evaluator, so no\n \/\/ need to get here. Plus, just getting the first container's dataset\n \/\/ name would not have worked with multiple containers.\n \/\/ pwest Jan 4, 2009\n \/\/ string dataset_name = \"\";\n\n \/\/ now we need to read the data\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Reading data into DataDDS\" << endl);\n\n \/\/ ADB: remember when we're using a temp DDS\n \/\/ bool using_temp_dds = false; See comment below about set_dds(). jhrg 8\/8\/14\n\n try {\n \/\/ Handle *functional* constraint expressions specially\n if (eval.function_clauses()) {\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Processing functional constraint clause(s).\" << endl);\n DataDDS *tmp_dds = eval.eval_function_clauses(*dds);\n delete dds;\n dds = tmp_dds;\n bdds->set_dds(dds);\n\n \/\/ This next step utilizes a well known function, promote_function_output_structures()\n \/\/ to look for one or more top level Structures whose name indicates (by way of ending\n \/\/ with \"_uwrap\") that their contents should be promoted (aka moved) to the top level.\n \/\/ This is in support of a hack around the current API where server side functions\n \/\/ may only return a single DAP object and not a collection of objects. The name suffix\n \/\/ \"_unwrap\" is used as a signal from the function to the the various response\n \/\/ builders and transmitters that the representation needs to be altered before\n \/\/ transmission, and that in fact is what happens in our friend\n \/\/ promote_function_output_structures()\n promote_function_output_structures(dds);\n\n }\n else {\n \/\/ Iterate through the variables in the DataDDS and read\n \/\/ in the data if the variable has the send flag set.\n\n for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) {\n if ((*i)->send_p()) {\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Interning data for variable: '\" << (*i)->name() << \"'\" << endl);\n (*i)->intern_data(eval, *dds);\n }\n }\n }\n }\n catch (Error &e) {\n throw BESDapError(\"Failed to read data: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (BESError &e) {\n throw;\n }\n catch (std::exception &e) {\n throw BESInternalError(\"Failed to read data: STL Error: \" + string(e.what()), __FILE__, __LINE__);\n }\n catch (...) {\n throw BESInternalError(\"Failed to read data. Unknown Error\", __FILE__, __LINE__);\n }\n\n \/\/string temp_file_name = FONcTransmitter::temp_dir + '\/' + \"ncXXXXXX\";\n string temp_file_name = FONcRequestHandler::temp_dir + '\/' + \"ncXXXXXX\";\n vector<char> temp_full(temp_file_name.length() + 1);\n string::size_type len = temp_file_name.copy(&temp_full[0], temp_file_name.length());\n temp_full[len] = '\\0';\n \/\/ cover the case where older versions of mkstemp() create the file using\n \/\/ a mode of 666.\n mode_t original_mode = umask(077);\n int fd = mkstemp(&temp_full[0]);\n umask(original_mode);\n#if 0\n \/\/ Trick: We can unlink the file right here - it will persist until the file descriptor\n \/\/ is closed. This means we don't have to litter the code with call to unlink(). jhrg 11\/25\/15\n (void) unlink(&temp_full[0]);\n \/\/ Hack: Use this simple class to 'wrap' the file descriptor so that we can be sure it\n \/\/ is closed no matter how this code is exited. jhrg 11\/25\/15\n wrap_file_descriptor wrapped_fd(fd);\n#endif\n if (fd == -1) throw BESInternalError(\"Failed to open the temporary file: \" + temp_file_name, __FILE__, __LINE__);\n\n \/\/ transform the OPeNDAP DataDDS to the netcdf file\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - Transforming into temporary file: \" << &temp_full[0] << endl);\n\n try {\n FONcTransform ft(dds, dhi, &temp_full[0], ncVersion);\n ft.transform();\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - Transmitting temp file \" << &temp_full[0] << endl);\n FONcTransmitter::return_temp_stream(&temp_full[0], strm, ncVersion);\n }\n catch (Error &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESDapError(\"Failed to Transform data to NetCDF: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (BESError &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw;\n }\n catch (std::exception &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESInternalError(\"Failed to Transform data to NetCDF: STL Error: \" + string(e.what()), __FILE__, __LINE__);\n }\n catch (...) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESInternalError(\"Failed to Transform data to NetCDF. Unknown Error\", __FILE__, __LINE__);\n }\n\n (void) unlink(&temp_full[0]);\n close(fd);\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - done transmitting to netcdf\" << endl);\n}\n\n\/** @brief stream the temporary netcdf file back to the requester\n *\n * Streams the temporary netcdf file specified by filename to the specified\n * C++ ostream\n *\n * @param filename The name of the file to stream back to the requester\n * @param strm C++ ostream to write the contents of the file to\n * @throws BESInternalError if problem opening the file\n *\/\nvoid FONcTransmitter::return_temp_stream(const string &filename, ostream &strm, const string &ncVersion)\n{\n ifstream os;\n os.open(filename.c_str(), ios::binary | ios::in);\n if (!os)\n throw BESInternalError(\"Fileout netcdf: Cannot connect to netcdf file.\", __FILE__, __LINE__);;\n\n char block[OUTPUT_FILE_BLOCK_SIZE];\n\n os.read(block, sizeof block);\n int nbytes = os.gcount();\n if (nbytes > 0) {\n bool found = false;\n string context = \"transmit_protocol\";\n string protocol = BESContextManager::TheManager()->get_context(context, found);\n if (protocol == \"HTTP\") {\n strm << \"HTTP\/1.0 200 OK\\n\";\n strm << \"Content-type: application\/octet-stream\\n\";\n strm << \"Content-Description: \" << \"BES dataset\" << \"\\n\";\n if (ncVersion == RETURNAS_NETCDF4) {\n strm << \"Content-Disposition: filename=\" << filename << \".nc4;\\n\\n\";\n }\n else {\n strm << \"Content-Disposition: filename=\" << filename << \".nc;\\n\\n\";\n }\n strm << flush;\n }\n strm.write(block, nbytes);\n }\n else {\n \/\/ close the stream before we leave.\n os.close();\n throw BESInternalError(\"Fileout netcdf: Failed to stream the response back to the client, got zero count on stream buffer.\", __FILE__, __LINE__);\n }\n\n while (os) {\n os.read(block, sizeof block);\n strm.write(block, os.gcount());\n }\n\n os.close();\n}\n\n<commit_msg>Added first draft of history attribute machinery.<commit_after>\/\/ FONcTransmitter.cc\n\n\/\/ This file is part of BES Netcdf File Out Module\n\n\/\/ Copyright (c) 2004,2005 University Corporation for Atmospheric Research\n\/\/ Author: Patrick West <pwest@ucar.edu> and Jose Garcia <jgarcia@ucar.edu>\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\/\/ You can contact University Corporation for Atmospheric Research at\n\/\/ 3080 Center Green Drive, Boulder, CO 80301\n\n\/\/ (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005\n\/\/ Please read the full copyright statement in the file COPYRIGHT_UCAR.\n\/\/\n\/\/ Authors:\n\/\/ pwest Patrick West <pwest@ucar.edu>\n\/\/ jgarcia Jose Garcia <jgarcia@ucar.edu>\n\n#include \"config.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\n#include <sys\/types.h> \/\/ For umask\n#include <sys\/stat.h>\n\n#include <iostream>\n#include <fstream>\n#include <exception>\n#include <sstream> \/\/ std::stringstream\n\n#include <DataDDS.h>\n#include <BaseType.h>\n#include <escaping.h>\n#include <ConstraintEvaluator.h>\n\n#include <BESInternalError.h>\n#include <BESDapError.h>\n#include <TheBESKeys.h>\n#include <BESContextManager.h>\n#include <BESDataDDSResponse.h>\n#include <BESDapNames.h>\n#include <BESDataNames.h>\n#include <BESDebug.h>\n#include <DapFunctionUtils.h>\n\n#include \"FONcBaseType.h\"\n#include \"FONcRequestHandler.h\"\n#include \"FONcTransmitter.h\"\n#include \"FONcTransform.h\"\n\nusing namespace ::libdap;\nusing namespace std;\n\n\/\/ size of the buffer used to read from the temporary file built on disk and\n\/\/ send data to the client over the network connection (socket\/stream)\n#define OUTPUT_FILE_BLOCK_SIZE 4096\n\n\/** @brief Construct the FONcTransmitter, adding it with name netcdf to be\n * able to transmit a data response\n *\n * The transmitter is created to add the ability to return OPeNDAP data\n * objects (DataDDS) as a netcdf file.\n *\n * The OPeNDAP data object is written to a netcdf file locally in a\n * temporary directory specified by the BES configuration parameter\n * FONc.Tempdir. If this variable is not found or is not set then it\n * defaults to the macro definition FONC_TEMP_DIR.\n *\/\nFONcTransmitter::FONcTransmitter() :\n BESBasicTransmitter()\n{\n add_method(DATA_SERVICE, FONcTransmitter::send_data);\n}\n\n#if 0\n\/**\n * Hack to ensure the file descriptor for the temporary file is closed.\n *\/\nstruct wrap_file_descriptor {\n int fd;\n wrap_file_descriptor(int i) : fd(i) { }\n ~wrap_file_descriptor() { cerr << \"*** Closing fd\" << endl; close(fd); }\n};\n#endif\n\n\n\/**\n * Process the \"history\" attribute.\n * We add:\n * - Sub-setting information if any\n * - SSFunction invocations\n * - ResourceID? URL?\n *\/\nvoid updateHistoryAttribute(DDS *dds){\n\n string hyrax_version = \"Hyrax-1.13.1\";\n string request_url = \"http:\/\/gosuckanegg.com\";\n\n std::stringstream new_history_entry;\n\n time_t raw_now;\n struct tm * timeinfo;\n time(&raw_now); \/* get current time; same as: timer = time(NULL) *\/\n timeinfo = localtime (&raw_now);\n\n char time_str[100];\n \/\/ 2000-6-1 6:00:00\n strftime(time_str,100,\"%Y-%m-%d %H:%M:%S\",timeinfo);\n\n new_history_entry << time_str << \" \"<< hyrax_version << \" \" << request_url;\n vector<string> hist_entry_vec;\n hist_entry_vec.push_back(new_history_entry.str());\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::updateHistoryAttribute() - new_history_entry: '\" << new_history_entry.str() << \"'\" << endl);\n\n\n \/\/ Add the new entry to the \"history\" attribute\n \/\/ Get the top level Attribute table.\n AttrTable &globals = dds->get_attr_table();\n\n\n \/\/ Since many files support \"CF\" conventions the history tag may already exist in the source data\n \/\/ and we should add an entry to it if possible.\n bool done = false; \/\/ Used to indicate that we located a toplevel ATtrTable whose name ends in \"_GLOBAL\" and that has an existing \"history\" attribute.\n unsigned int num_attrs = globals.get_size();\n if (num_attrs) {\n \/\/ Here we look for a top level AttrTable whose name ends with \"_GLOBAL\" which is where, by convention,\n \/\/ data ingest handlers place global level attributes found in the source dataset.\n AttrTable::Attr_iter i = globals.attr_begin();\n AttrTable::Attr_iter e = globals.attr_end();\n for (; i != e && !done; i++) {\n AttrType attrType = globals.get_attr_type(i);\n string attr_name = globals.get_name(i);\n \/\/ Test the entry...\n if (attrType==Attr_container && BESUtil::endsWith(attr_name, \"_GLOBAL\")) {\n \/\/ Look promising, but does it have an existing \"history\" Attribute?\n AttrTable *source_file_globals = globals.get_attr_table(i);\n AttrTable::Attr_iter history_attrItr = source_file_globals->simple_find(\"history\");\n if(history_attrItr != source_file_globals->attr_end()){\n \/\/ Yup! Add our entry...\n BESDEBUG(\"fonc\", \"FONcTransmitter::updateHistoryAttribute() - Adding history entry to \" << attr_name << endl);\n source_file_globals->append_attr(\"history\", \"string\", &hist_entry_vec);\n done = true;\n }\n }\n }\n }\n\n if(!done){\n \/\/ We never found an existing location to place the \"history\" entry, so we'll just stuff it into the top level AttrTable.\n BESDEBUG(\"fonc\", \"FONcTransmitter::updateHistoryAttribute() - Adding history entry to top level AttrTable\" << endl);\n globals.append_attr(\"history\", \"string\", &hist_entry_vec);\n\n }\n\n#if 0\n\n \/\/ SIMPLE FIRST DRAFT\n\n\n \/\/ ###########\n \/\/ The following should be rewritten to add the history to any global\n \/\/ attribute table who's name ends in _GLOBAL and that already has a history attr.\n \/\/ because people use CF in hdf4, hdf5, nc, etc.\n \/\/ . . . . . .\n \/\/ Since we know that the contents NC_GLOBAL AttrTable will be promoted to global level attributes in the resulting nectdf file\n \/\/ we check for an existing history attribute there and add the new entry if we find the history attr there.\n AttrTable *nc_global_attrT = globals.simple_find_container(\"NC_GLOBAL\");\n \/\/ Is there an NC_GLOBAL attribute table.\n if(nc_global_attrT){\n \/\/ If we found an NC_GLOBAL attribute table, append our \"history\" attribute to it.\n BESDEBUG(\"fonc\", \"FONcTransmitter::updateHistoryAttribute() - Adding history entry to NC_GLOBAL\" << endl);\n nc_global_attrT->append_attr(\"history\", \"string\", &hist_entry_vec);\n }\n else {\n\n \/\/ If we don't have an NC_GLOBAL attribute table just append it to the global table.\n \/\/ Other wise we just add it to the top level where it belongs.\n BESDEBUG(\"fonc\", \"FONcTransmitter::updateHistoryAttribute() - Adding history entry to top level AttrTable\" << endl);\n globals.append_attr(\"history\", \"string\", &hist_entry_vec);\n\n }\n \/\/ ###########\n#endif\n}\n\n\n\n\n\/** @brief The static method registered to transmit OPeNDAP data objects as\n * a netcdf file.\n *\n * This function takes the OPeNDAP DataDDS object, reads in the data (can be\n * used with any data handler), transforms the data into a netcdf file, and\n * streams back that netcdf file back to the requester using the stream\n * specified in the BESDataHandlerInterface.\n *\n * @param obj The BESResponseObject containing the OPeNDAP DataDDS object\n * @param dhi BESDataHandlerInterface containing information about the\n * request and response\n * @throws BESInternalError if the response is not an OPeNDAP DataDDS or if\n * there are any problems reading the data, writing to a netcdf file, or\n * streaming the netcdf file\n *\/\nvoid FONcTransmitter::send_data(BESResponseObject *obj, BESDataHandlerInterface &dhi)\n{\n BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj);\n if (!bdds) throw BESInternalError(\"cast error\", __FILE__, __LINE__);\n\n libdap::DataDDS *dds = bdds->get_dds();\n if (!dds) throw BESInternalError(\"No DataDDS has been created for transmit\", __FILE__, __LINE__);\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Parsing the constraint\" << endl);\n\n ConstraintEvaluator &eval = bdds->get_ce();\n\n string ncVersion = dhi.data[RETURN_CMD];\n\n ostream &strm = dhi.get_output_stream();\n if (!strm) throw BESInternalError(\"Output stream is not set, can not return as\", __FILE__, __LINE__);\n\n \/\/ ticket 1248 jhrg 2\/23\/09\n string ce = www2id(dhi.data[POST_CONSTRAINT], \"%\", \"%20%26\");\n try {\n eval.parse_constraint(ce, *dds);\n }\n catch (Error &e) {\n throw BESDapError(\"Failed to parse the constraint expression: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (...) {\n throw BESInternalError(\"Failed to parse the constraint expression: Unknown exception caught\", __FILE__,\n __LINE__);\n }\n\n \/\/ The dataset_name is no longer used in the constraint evaluator, so no\n \/\/ need to get here. Plus, just getting the first container's dataset\n \/\/ name would not have worked with multiple containers.\n \/\/ pwest Jan 4, 2009\n \/\/ string dataset_name = \"\";\n\n \/\/ now we need to read the data\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Reading data into DataDDS\" << endl);\n\n \/\/ ADB: remember when we're using a temp DDS\n \/\/ bool using_temp_dds = false; See comment below about set_dds(). jhrg 8\/8\/14\n\n try {\n \/\/ Handle *functional* constraint expressions specially\n if (eval.function_clauses()) {\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Processing functional constraint clause(s).\" << endl);\n DataDDS *tmp_dds = eval.eval_function_clauses(*dds);\n delete dds;\n dds = tmp_dds;\n bdds->set_dds(dds);\n\n \/\/ This next step utilizes a well known function, promote_function_output_structures()\n \/\/ to look for one or more top level Structures whose name indicates (by way of ending\n \/\/ with \"_uwrap\") that their contents should be promoted (aka moved) to the top level.\n \/\/ This is in support of a hack around the current API where server side functions\n \/\/ may only return a single DAP object and not a collection of objects. The name suffix\n \/\/ \"_unwrap\" is used as a signal from the function to the the various response\n \/\/ builders and transmitters that the representation needs to be altered before\n \/\/ transmission, and that in fact is what happens in our friend\n \/\/ promote_function_output_structures()\n promote_function_output_structures(dds);\n\n }\n else {\n \/\/ Iterate through the variables in the DataDDS and read\n \/\/ in the data if the variable has the send flag set.\n\n for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) {\n if ((*i)->send_p()) {\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Interning data for variable: '\" << (*i)->name() << \"'\" << endl);\n (*i)->intern_data(eval, *dds);\n }\n }\n }\n }\n catch (Error &e) {\n throw BESDapError(\"Failed to read data: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (BESError &e) {\n throw;\n }\n catch (std::exception &e) {\n throw BESInternalError(\"Failed to read data: STL Error: \" + string(e.what()), __FILE__, __LINE__);\n }\n catch (...) {\n throw BESInternalError(\"Failed to read data. Unknown Error\", __FILE__, __LINE__);\n }\n\n\n updateHistoryAttribute(dds);\n\n\n\n\n \/\/string temp_file_name = FONcTransmitter::temp_dir + '\/' + \"ncXXXXXX\";\n string temp_file_name = FONcRequestHandler::temp_dir + '\/' + \"ncXXXXXX\";\n vector<char> temp_full(temp_file_name.length() + 1);\n string::size_type len = temp_file_name.copy(&temp_full[0], temp_file_name.length());\n temp_full[len] = '\\0';\n \/\/ cover the case where older versions of mkstemp() create the file using\n \/\/ a mode of 666.\n mode_t original_mode = umask(077);\n int fd = mkstemp(&temp_full[0]);\n umask(original_mode);\n#if 0\n \/\/ Trick: We can unlink the file right here - it will persist until the file descriptor\n \/\/ is closed. This means we don't have to litter the code with call to unlink(). jhrg 11\/25\/15\n (void) unlink(&temp_full[0]);\n \/\/ Hack: Use this simple class to 'wrap' the file descriptor so that we can be sure it\n \/\/ is closed no matter how this code is exited. jhrg 11\/25\/15\n wrap_file_descriptor wrapped_fd(fd);\n#endif\n if (fd == -1) throw BESInternalError(\"Failed to open the temporary file: \" + temp_file_name, __FILE__, __LINE__);\n\n \/\/ transform the OPeNDAP DataDDS to the netcdf file\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - Transforming into temporary file: \" << &temp_full[0] << endl);\n\n try {\n FONcTransform ft(dds, dhi, &temp_full[0], ncVersion);\n ft.transform();\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - Transmitting temp file \" << &temp_full[0] << endl);\n FONcTransmitter::return_temp_stream(&temp_full[0], strm, ncVersion);\n }\n catch (Error &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESDapError(\"Failed to Transform data to NetCDF: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (BESError &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw;\n }\n catch (std::exception &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESInternalError(\"Failed to Transform data to NetCDF: STL Error: \" + string(e.what()), __FILE__, __LINE__);\n }\n catch (...) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESInternalError(\"Failed to Transform data to NetCDF. Unknown Error\", __FILE__, __LINE__);\n }\n\n (void) unlink(&temp_full[0]);\n close(fd);\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - done transmitting to netcdf\" << endl);\n}\n\n\/** @brief stream the temporary netcdf file back to the requester\n *\n * Streams the temporary netcdf file specified by filename to the specified\n * C++ ostream\n *\n * @param filename The name of the file to stream back to the requester\n * @param strm C++ ostream to write the contents of the file to\n * @throws BESInternalError if problem opening the file\n *\/\nvoid FONcTransmitter::return_temp_stream(const string &filename, ostream &strm, const string &ncVersion)\n{\n ifstream os;\n os.open(filename.c_str(), ios::binary | ios::in);\n if (!os)\n throw BESInternalError(\"Fileout netcdf: Cannot connect to netcdf file.\", __FILE__, __LINE__);;\n\n char block[OUTPUT_FILE_BLOCK_SIZE];\n\n os.read(block, sizeof block);\n int nbytes = os.gcount();\n if (nbytes > 0) {\n bool found = false;\n string context = \"transmit_protocol\";\n string protocol = BESContextManager::TheManager()->get_context(context, found);\n if (protocol == \"HTTP\") {\n strm << \"HTTP\/1.0 200 OK\\n\";\n strm << \"Content-type: application\/octet-stream\\n\";\n strm << \"Content-Description: \" << \"BES dataset\" << \"\\n\";\n if (ncVersion == RETURNAS_NETCDF4) {\n strm << \"Content-Disposition: filename=\" << filename << \".nc4;\\n\\n\";\n }\n else {\n strm << \"Content-Disposition: filename=\" << filename << \".nc;\\n\\n\";\n }\n strm << flush;\n }\n strm.write(block, nbytes);\n }\n else {\n \/\/ close the stream before we leave.\n os.close();\n throw BESInternalError(\"Fileout netcdf: Failed to stream the response back to the client, got zero count on stream buffer.\", __FILE__, __LINE__);\n }\n\n while (os) {\n os.read(block, sizeof block);\n strm.write(block, os.gcount());\n }\n\n os.close();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nRozbuduj poprzeni program o operacje modyfikujące elementy tablicy.\nPo każdej operacji wypisz tablicę na ekran:\n- odwracanie kolejności elementów tablicy\n- przesunięcie tablicy w prawo\n(element na pozycji 0 jest przesuwany na pozycję 1,\nelement na pozycji 1 jest przesuwany na pozycję numer 2, itd.\nOstatni element jest wstawiany na pozycję 0)\n- sortowanie tablicy (uporządkowanie elementów rosnąco)\n*\/\n\n#include <iostream>\n#include <cstdlib>\n#include <ctime>\n#include <utility>\n\n#define SIZE 10\n\nusing std::cout;\nusing std::endl;\n\nint main() {\n\n\tint tab[SIZE];\n\tsrand(time(NULL));\n\n cout << \"Tablica: \";\n\tfor (int i = 0; i < SIZE; i++) {\n\t\ttab[i] = rand() % 100;\n\t\tcout << tab[i] << \" \";\n\t}\n cout << endl;\n\n for (int i = 0; i < SIZE \/ 2; i++) {\n \/\/int t = tab[SIZE - i - 1];\n \/\/tab[SIZE - i - 1] = tab[i];\n \/\/tab[i] = t;\n std::swap(tab[SIZE - i - 1], tab[i]);\n }\n\n cout << \"Tablica odwrócona: \";\n for (int i = 0; i < SIZE; i++) {\n cout << tab[i] << \" \";\n }\n cout << endl;\n\n int t{0};\n for (int i = 0; i < SIZE; i++) {\n if (i + 1 == SIZE) {\n tab[0] = tab[SIZE - 1];\n tab[SIZE - 1] = t;\n } else {\n int r = tab[i];\n tab[i] = t;\n t = r;\n }\n }\n\n cout << \"Tablica przesunięta w prawo: \";\n for (int i = 0; i < SIZE; i++) {\n cout << tab[i] << \" \";\n }\n cout << endl;\n\n}\n<commit_msg>sortowanie bąbelkowe<commit_after>\/*\nRozbuduj poprzeni program o operacje modyfikujące elementy tablicy.\nPo każdej operacji wypisz tablicę na ekran:\n- odwracanie kolejności elementów tablicy\n- przesunięcie tablicy w prawo\n(element na pozycji 0 jest przesuwany na pozycję 1,\nelement na pozycji 1 jest przesuwany na pozycję numer 2, itd.\nOstatni element jest wstawiany na pozycję 0)\n- sortowanie tablicy (uporządkowanie elementów rosnąco)\n*\/\n\n#include <iostream>\n#include <cstdlib>\n#include <ctime>\n#include <utility>\n\n#define SIZE 10\n\nusing std::cout;\nusing std::endl;\n\nint main() {\n\n\tint tab[SIZE];\n\tsrand(time(NULL));\n\n cout << \"Tablica: \";\n\tfor (int i = 0; i < SIZE; i++) {\n\t\ttab[i] = rand() % 100;\n\t\tcout << tab[i] << \" \";\n\t}\n cout << endl;\n\n for (int i = 0; i < SIZE \/ 2; i++) {\n \/\/int t = tab[SIZE - i - 1];\n \/\/tab[SIZE - i - 1] = tab[i];\n \/\/tab[i] = t;\n std::swap(tab[SIZE - i - 1], tab[i]);\n }\n\n cout << \"Tablica odwrócona: \";\n for (int i = 0; i < SIZE; i++) {\n cout << tab[i] << \" \";\n }\n cout << endl;\n\n int t{0};\n for (int i = 0; i < SIZE; i++) {\n if (i + 1 == SIZE) {\n tab[0] = tab[SIZE - 1];\n tab[SIZE - 1] = t;\n } else {\n int r = tab[i];\n tab[i] = t;\n t = r;\n }\n }\n\n cout << \"Tablica przesunięta w prawo: \";\n for (int i = 0; i < SIZE; i++) {\n cout << tab[i] << \" \";\n }\n cout << endl;\n \n \/* \n procedure bubbleSort( A : lista elementów do posortowania )\n\tn = liczba_elementów(A)\n\tdo\n\t\tfor (i = 0; i < n-1; i++) do:\n\t\t\tif A[i] > A[i+1] then\n\t\t\t\tswap(A[i], A[i+1])\n\t\t\tend if\n\t\tend for\n\t\tn = n-1\n\twhile n > 1\n\tend procedure\n\t*\/\n int n = SIZE;\n do {\n\t\tfor (int i = 0; i < n-1; i++) {\n\t\t\tif (tab[i] > tab[i+1]) {\n\t\t\t\t\/\/std::swap(tab[i], tab[i+1]);\n\t\t\t\tint c = tab[i];\n\t\t\t\ttab[i] = tab[i+1];\n\t\t\t\ttab[i+1] = c;\n\t\t\t}\n\t\t}\n\t\tn--;\n\t} while (n > 1);\n\n\tcout << \"Tablica posortowana: \";\n\tfor (int i = 0; i < SIZE; i++) {\n cout << tab[i] << \" \";\n }\n cout << endl;\n \t\n\n}\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2014-2015 DataStax\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 STAND_ALONE\n# define BOOST_TEST_MODULE cassandra\n#endif\n\n#include <algorithm>\n\n#if !defined(WIN32) && !defined(_WIN32)\n#include <signal.h>\n#endif\n\n#include \"cassandra.h\"\n#include \"testing.hpp\"\n#include \"test_utils.hpp\"\n#include \"cql_ccm_bridge.hpp\"\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/test\/debug.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/cstdint.hpp>\n#include <boost\/format.hpp>\n#include <boost\/asio\/io_service.hpp>\n#include <boost\/thread\/future.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/chrono.hpp>\n#include <boost\/cstdint.hpp>\n\n#include <map>\n#include <set>\n#include <string>\n\nBOOST_AUTO_TEST_SUITE(custom_payload)\n\nBOOST_AUTO_TEST_CASE(simple)\n{\n test_utils::CassClusterPtr cluster(cass_cluster_new());\n\n const cql::cql_ccm_bridge_configuration_t& conf = cql::get_ccm_bridge_configuration();\n boost::shared_ptr<cql::cql_ccm_bridge_t> ccm = cql::cql_ccm_bridge_t::create(conf, \"test\");\n\n ccm->add_node(1);\n ccm->start(1, \"-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler\");\n\n CassVersion version = ccm->version();\n BOOST_REQUIRE((version.major >= 2 && version.minor >= 2) || version.major >= 3);\n\n test_utils::initialize_contact_points(cluster.get(), conf.ip_prefix(), 1, 0);\n\n test_utils::CassSessionPtr session(test_utils::create_session(cluster.get()));\n\n test_utils::CassStatementPtr statement(cass_statement_new(\"SELECT * FROM system.local\", 0));\n\n test_utils::CassCustomPayloadPtr custom_payload(cass_custom_payload_new());\n\n typedef std::map<std::string, std::string> PayloadItemMap;\n\n PayloadItemMap items;\n items[\"key1\"] = \"value1\";\n items[\"key2\"] = \"value2\";\n items[\"key3\"] = \"value3\";\n\n for (PayloadItemMap::const_iterator i = items.begin(); i != items.end(); ++i) {\n cass_custom_payload_set(custom_payload.get(),\n i->first.c_str(),\n reinterpret_cast<const cass_byte_t*>(i->second.data()), i->second.size());\n }\n\n cass_statement_set_custom_payload(statement.get(), custom_payload.get());\n\n test_utils::CassFuturePtr future(cass_session_execute(session.get(), statement.get()));\n\n size_t item_count = cass_future_custom_payload_item_count(future.get());\n\n BOOST_REQUIRE(item_count == items.size());\n\n for (size_t i = 0; i < item_count; ++i) {\n const char* name;\n size_t name_length;\n const cass_byte_t* value;\n size_t value_size;\n BOOST_REQUIRE(cass_future_custom_payload_item(future.get(), i,\n &name, &name_length,\n &value, &value_size) == CASS_OK);\n\n PayloadItemMap::const_iterator it = items.find(std::string(name, name_length));\n BOOST_REQUIRE(it != items.end());\n BOOST_CHECK_EQUAL(it->second, std::string(reinterpret_cast<const char*>(value), value_size));\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Removing unused includes and limiting test to run with C* 2.2+<commit_after>\/*\n Copyright (c) 2014-2015 DataStax\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 STAND_ALONE\n# define BOOST_TEST_MODULE cassandra\n#endif\n\n#include \"cassandra.h\"\n#include \"test_utils.hpp\"\n#include \"cql_ccm_bridge.hpp\"\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/test\/debug.hpp>\n\n#include <map>\n#include <set>\n#include <string>\n\nBOOST_AUTO_TEST_SUITE(custom_payload)\n\nBOOST_AUTO_TEST_CASE(simple)\n{\n const cql::cql_ccm_bridge_configuration_t& conf = cql::get_ccm_bridge_configuration();\n CassVersion version(conf.cassandara_version());\n if ((version.major >= 2 && version.minor >= 2) || version.major >= 3) {\n boost::debug::detect_memory_leaks(false);\n boost::shared_ptr<cql::cql_ccm_bridge_t> ccm = cql::cql_ccm_bridge_t::create(conf, \"test\");\n\n ccm->populate(1);\n ccm->start(1, \"-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler\");\n\n test_utils::CassClusterPtr cluster(cass_cluster_new());\n test_utils::initialize_contact_points(cluster.get(), conf.ip_prefix(), 1, 0);\n\n test_utils::CassSessionPtr session(test_utils::create_session(cluster.get()));\n\n test_utils::CassStatementPtr statement(cass_statement_new(\"SELECT * FROM system.local\", 0));\n\n test_utils::CassCustomPayloadPtr custom_payload(cass_custom_payload_new());\n\n typedef std::map<std::string, std::string> PayloadItemMap;\n\n PayloadItemMap items;\n items[\"key1\"] = \"value1\";\n items[\"key2\"] = \"value2\";\n items[\"key3\"] = \"value3\";\n\n for (PayloadItemMap::const_iterator i = items.begin(); i != items.end(); ++i) {\n cass_custom_payload_set(custom_payload.get(),\n i->first.c_str(),\n reinterpret_cast<const cass_byte_t*>(i->second.data()), i->second.size());\n }\n\n cass_statement_set_custom_payload(statement.get(), custom_payload.get());\n\n test_utils::CassFuturePtr future(cass_session_execute(session.get(), statement.get()));\n\n size_t item_count = cass_future_custom_payload_item_count(future.get());\n\n BOOST_REQUIRE(item_count == items.size());\n\n for (size_t i = 0; i < item_count; ++i) {\n const char* name;\n size_t name_length;\n const cass_byte_t* value;\n size_t value_size;\n BOOST_REQUIRE(cass_future_custom_payload_item(future.get(), i,\n &name, &name_length,\n &value, &value_size) == CASS_OK);\n\n PayloadItemMap::const_iterator it = items.find(std::string(name, name_length));\n BOOST_REQUIRE(it != items.end());\n BOOST_CHECK_EQUAL(it->second, std::string(reinterpret_cast<const char*>(value), value_size));\n }\n } else {\n boost::unit_test::unit_test_log_t::instance().set_threshold_level(boost::unit_test::log_messages);\n BOOST_TEST_MESSAGE(\"Unsupported Test for Cassandra v\" << version.to_string() << \": Skipping custom_payload\/simple\");\n BOOST_REQUIRE(true);\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_CHECK_HPP\n#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_CHECK_HPP\n\n#include \"traits.hpp\"\n#include \"function_traits.hpp\"\n#include \"construct_function.hpp\"\n#include \"override_traits.hpp\"\n\nnamespace kgr {\nnamespace detail {\n\n\/*\n * Trait that check if the service definition can be constructed given the return type of it's construct function.\n *\/\ntemplate<typename T, typename... Args>\nstruct is_service_constructible_helper {\nprivate:\n\ttemplate<typename U, typename... As, std::size_t F, std::size_t... S>\n\tstatic is_service_instantiable<T,\n\t\ttuple_element_t<F, function_result_t<construct_function_t<U, As...>>>,\n\t\ttuple_element_t<S, function_result_t<construct_function_t<U, As...>>>...> test(seq<F, S...>);\n\n\t\/\/ This overload is needed for msvc.\n\t\/\/ Or else it will try to call the one just above with a 0 as S for strange reason.\n\ttemplate<typename U, typename... As, int_t<construct_function_t<U, As...>> = 0>\n\tstatic is_service_instantiable<T> test(seq<>);\n\t\n\ttemplate<typename U, typename... As, enable_if_t<is_supplied_service<U>::value || !has_any_construct<U, As...>::value, int> = 0>\n\tstatic std::true_type test_helper(int);\n\t\n\ttemplate<typename...>\n\tstatic std::false_type test(...);\n\t\n\ttemplate<typename...>\n\tstatic std::false_type test_helper(...);\n\t\n\t\/\/ The enable if is required here or else the function call will be ambiguous on visual studio.\n\ttemplate<typename U, typename... As, enable_if_t<!is_supplied_service<U>::value && has_any_construct<U, As...>::value, int> = 0>\n\tstatic auto test_helper(int) -> decltype(test<U, As...>(tuple_seq<function_result_t<construct_function_t<U, As...>>>{}));\n\t\npublic:\n\tusing type = decltype(test_helper<T, Args...>(0));\n};\n\n\/*\n * Alias for is_service_constructible_helper\n *\/\ntemplate<typename T, typename... Args>\nusing is_service_constructible = typename is_service_constructible_helper<T, Args...>::type;\n\n\n\n\/*\n * Meta trait that applies a trait recursively for each dependencies and thier dependencies.\n *\/\ntemplate<template<typename...> class Trait, typename T, typename... Args>\nstruct dependency_trait {\n\ttemplate<typename... Service>\n\tstruct service_check_dependencies : conjunction<\n\t\tTrait<detected_t<injected_service_t, Service>>...,\n\t\tdependency_trait<Trait, detected_t<injected_service_t, Service>, Args...>...\n\t> {};\n\n\tstatic constexpr bool value =\n\t\tis_supplied_service<T>::value ||\n\t\texpand_n<\n\t\t\tsafe_minus(detected_or<std::integral_constant<int, 0>, meta_list_size, detected_or<meta_list<>, function_arguments_t, detected_t<construct_function_t, T, Args...>>>::value, sizeof...(Args)),\n\t\t\tdetected_or<meta_list<>, function_arguments_t, detected_t<construct_function_t, T, Args...>>,\n\t\t\tservice_check_dependencies\n\t\t>::value;\n};\n\n\/*\n * Validity check for default services\n *\/\ntemplate<typename T>\nusing is_default_service_valid = std::integral_constant<bool,\n\t(is_abstract_service<T>::value || !has_default<T>::value) &&\n\tis_default_overrides_abstract<T>::value &&\n\tis_default_convertible<T>::value\n>;\n\ntemplate<typename T>\nusing is_abstract_not_final = std::integral_constant<bool,\n\t!is_abstract_service<T>::value || !is_final_service<T>::value\n>;\n\n\/*\n * Validity check for a service, without it's dependencies\n *\/\ntemplate<typename T, typename... Args>\nusing shallow_service_check = std::integral_constant<bool,\n\tis_service<T>::value &&\n\tis_service_constructible<T, Args...>::value &&\n\tis_construct_function_callable<T, Args...>::value &&\n\tis_default_service_valid<T>::value &&\n\tis_override_convertible<T>::value &&\n\tis_override_polymorphic<T>::value &&\n\tis_override_services<T>::value &&\n\tis_override_not_final<T>::value &&\n\tis_abstract_not_final<T>::value\n>;\n\n\/*\n * Validity check for dependencies of a service\n *\/\ntemplate<typename T, typename... Args>\nusing dependency_check = dependency_trait<shallow_service_check, T, Args...>;\n\ntemplate<typename T, typename... Args>\nstruct service_check : bool_constant<\n\tshallow_service_check<T, Args...>::value && dependency_check<T, Args...>::value\n> {};\n\n} \/\/ namespace detail\n} \/\/ namespace kgr\n\n#endif \/\/ KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_CHECK_HPP\n<commit_msg>Made dependency_trait work with both the latest visual studio and visual studio 2015<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_CHECK_HPP\n#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_CHECK_HPP\n\n#include \"traits.hpp\"\n#include \"function_traits.hpp\"\n#include \"construct_function.hpp\"\n#include \"override_traits.hpp\"\n\nnamespace kgr {\nnamespace detail {\n\n#ifndef KGR_KANGARU_MSVC_DEPENDENCY_TRAIT_STRUCT\n#if _MSC_VER == 1900\n#ifndef __clang__\n\/\/ MSVC has a defect that makes the use of the template keyword an error in some corner cases.\n#define KGR_KANGARU_MSVC_DEPENDENCY_TRAIT_STRUCT\n#endif \/\/ !__clang__\n#endif \/\/ _MSC_VER\n#endif \/\/ KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD\n\n\/*\n * Trait that check if the service definition can be constructed given the return type of it's construct function.\n *\/\ntemplate<typename T, typename... Args>\nstruct is_service_constructible_helper {\nprivate:\n\ttemplate<typename U, typename... As, std::size_t F, std::size_t... S>\n\tstatic is_service_instantiable<T,\n\t\ttuple_element_t<F, function_result_t<construct_function_t<U, As...>>>,\n\t\ttuple_element_t<S, function_result_t<construct_function_t<U, As...>>>...> test(seq<F, S...>);\n\n\t\/\/ This overload is needed for msvc.\n\t\/\/ Or else it will try to call the one just above with a 0 as S for strange reason.\n\ttemplate<typename U, typename... As, int_t<construct_function_t<U, As...>> = 0>\n\tstatic is_service_instantiable<T> test(seq<>);\n\t\n\ttemplate<typename U, typename... As, enable_if_t<is_supplied_service<U>::value || !has_any_construct<U, As...>::value, int> = 0>\n\tstatic std::true_type test_helper(int);\n\t\n\ttemplate<typename...>\n\tstatic std::false_type test(...);\n\t\n\ttemplate<typename...>\n\tstatic std::false_type test_helper(...);\n\t\n\t\/\/ The enable if is required here or else the function call will be ambiguous on visual studio.\n\ttemplate<typename U, typename... As, enable_if_t<!is_supplied_service<U>::value && has_any_construct<U, As...>::value, int> = 0>\n\tstatic auto test_helper(int) -> decltype(test<U, As...>(tuple_seq<function_result_t<construct_function_t<U, As...>>>{}));\n\t\npublic:\n\tusing type = decltype(test_helper<T, Args...>(0));\n};\n\n\/*\n * Alias for is_service_constructible_helper\n *\/\ntemplate<typename T, typename... Args>\nusing is_service_constructible = typename is_service_constructible_helper<T, Args...>::type;\n\n\n\n\/*\n * Meta trait that applies a trait recursively for each dependencies and thier dependencies.\n *\/\ntemplate<template<typename...> class Trait, typename T, typename... Args>\nstruct dependency_trait {\n\ttemplate<typename... Service>\n\tstruct service_check_dependencies {\n\t\tstatic constexpr bool value = conjunction<\n\t\t\tTrait<detected_t<injected_service_t, Service>>...,\n\t\t\tdependency_trait<Trait, detected_t<injected_service_t, Service>, Args...>...\n\t\t>::value;\n\t};\n\n\tstatic constexpr bool value =\n\t\tis_supplied_service<T>::value ||\n\t\texpand_n<\n\t\t\tsafe_minus(detected_or<std::integral_constant<int, 0>, meta_list_size, detected_or<meta_list<>, function_arguments_t, detected_t<construct_function_t, T, Args...>>>::value, sizeof...(Args)),\n\t\t\tdetected_or<meta_list<>, function_arguments_t, detected_t<construct_function_t, T, Args...>>,\n\t\t\tservice_check_dependencies\n\t\t>::value;\n};\n\n\/*\n * Validity check for default services\n *\/\ntemplate<typename T>\nusing is_default_service_valid = std::integral_constant<bool,\n\t(is_abstract_service<T>::value || !has_default<T>::value) &&\n\tis_default_overrides_abstract<T>::value &&\n\tis_default_convertible<T>::value\n>;\n\ntemplate<typename T>\nusing is_abstract_not_final = std::integral_constant<bool,\n\t!is_abstract_service<T>::value || !is_final_service<T>::value\n>;\n\n\/*\n * Validity check for a service, without it's dependencies\n *\/\ntemplate<typename T, typename... Args>\nusing shallow_service_check = std::integral_constant<bool,\n\tis_service<T>::value &&\n\tis_service_constructible<T, Args...>::value &&\n\tis_construct_function_callable<T, Args...>::value &&\n\tis_default_service_valid<T>::value &&\n\tis_override_convertible<T>::value &&\n\tis_override_polymorphic<T>::value &&\n\tis_override_services<T>::value &&\n\tis_override_not_final<T>::value &&\n\tis_abstract_not_final<T>::value\n>;\n\n\/*\n * Validity check for dependencies of a service\n *\/\ntemplate<typename T, typename... Args>\nusing dependency_check = dependency_trait<shallow_service_check, T, Args...>;\n\ntemplate<typename T, typename... Args>\nstruct service_check : bool_constant<\n\tshallow_service_check<T, Args...>::value && dependency_check<T, Args...>::value\n> {};\n\n} \/\/ namespace detail\n} \/\/ namespace kgr\n\n#endif \/\/ KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_CHECK_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016-2020 Francesco Biscani (bluescarni@gmail.com)\n\/\/\n\/\/ This file is part of the mp++ library.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef MPPP_DETAIL_INTEGER_LITERALS_HPP\n#define MPPP_DETAIL_INTEGER_LITERALS_HPP\n\n#include <cassert>\n#include <cstddef>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <utility>\n\n#include <mp++\/config.hpp>\n#include <mp++\/detail\/gmp.hpp>\n#include <mp++\/detail\/utils.hpp>\n\nnamespace mppp\n{\n\nnamespace detail\n{\n\n\/\/ Helper to check if an integral literal is valid.\n\/\/ It will return the base of the literal. Supported\n\/\/ bases are 2, 8, 10 and 16.\n\/\/ NOTE: we need this function in the C++11\/C++14 implementation\n\/\/ as well, so use MPPP_CONSTEXPR_14, MPPP_FALLTHROUGH, etc.\ntemplate <std::size_t Size>\ninline\n#if !defined(_MSC_VER) || defined(__clang__)\n MPPP_CONSTEXPR_14\n#endif\n int\n integer_literal_check_str(const char (&arr)[Size])\n{\n \/\/ We expect the size of the array to be\n \/\/ always at least 2, the null terminator\n \/\/ plus at least one char from the literal.\n static_assert(Size >= 2u, \"Invalid array size.\");\n#if MPPP_CPLUSPLUS >= 201703L\n assert(arr[Size - 1u] == '\\0');\n#endif\n\n \/\/ The actual string length of the literal.\n constexpr auto str_length = Size - 1u;\n\n \/\/ Helpers to check a digit in various bases.\n auto base10_digit_check = [&arr](char c) {\n if (c < '0' || c > '9') {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n };\n\n auto base8_digit_check = [&arr](char c) {\n if (c < '0' || c > '7') {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n };\n\n auto base2_digit_check = [&arr](char c) {\n if (c != '0' && c != '1') {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n };\n\n auto base16_digit_check = [&arr](char c) {\n if (c < '0' || c > '9') {\n switch (c) {\n case 'a':\n MPPP_FALLTHROUGH;\n case 'b':\n MPPP_FALLTHROUGH;\n case 'c':\n MPPP_FALLTHROUGH;\n case 'd':\n MPPP_FALLTHROUGH;\n case 'e':\n MPPP_FALLTHROUGH;\n case 'f':\n MPPP_FALLTHROUGH;\n case 'A':\n MPPP_FALLTHROUGH;\n case 'B':\n MPPP_FALLTHROUGH;\n case 'C':\n MPPP_FALLTHROUGH;\n case 'D':\n MPPP_FALLTHROUGH;\n case 'E':\n MPPP_FALLTHROUGH;\n case 'F':\n return;\n default:\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n }\n };\n\n if (str_length == 1u) {\n \/\/ If the string length is 1, the only\n \/\/ character must be in the ['0', '9'] range.\n base10_digit_check(arr[0]);\n\n \/\/ NOTE: the literal \"0\" is actually an\n \/\/ octal, but it does not matter if we\n \/\/ construct it using base 10.\n return 10;\n }\n\n \/\/ The string length is at least 2. Infer the base\n \/\/ of the literal.\n const int base = [&arr, base8_digit_check, base10_digit_check]() -> int {\n \/\/ Fetch the first 2 digits.\n const auto d0 = arr[0], d1 = arr[1];\n\n if (d0 == '0') {\n \/\/ Binary, octal or hex.\n if (d1 == 'b' || d1 == 'B') {\n return 2;\n } else if (d1 == 'x' || d1 == 'X') {\n return 16;\n } else {\n base8_digit_check(d1);\n return 8;\n }\n } else {\n \/\/ Decimal.\n base10_digit_check(d0);\n base10_digit_check(d1);\n return 10;\n }\n }();\n\n#if MPPP_CPLUSPLUS >= 201703L\n assert(base == 2 || base == 8 || base == 10 || base == 16);\n#endif\n\n \/\/ Run the checks on the rest of the literal,\n \/\/ after we already checked the first 2 digits.\n \/\/ For bases 2 and 16, we need to have other digits,\n \/\/ otherwise the literal is malformed.\n \/\/ NOLINTNEXTLINE(hicpp-multiway-paths-covered)\n switch (base) {\n case 2:\n if (str_length == 2u) {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n for (std::size_t i = 2; i < str_length; ++i) {\n base2_digit_check(arr[i]);\n }\n break;\n case 8:\n for (std::size_t i = 2; i < str_length; ++i) {\n base8_digit_check(arr[i]);\n }\n break;\n case 10:\n for (std::size_t i = 2; i < str_length; ++i) {\n base10_digit_check(arr[i]);\n }\n break;\n case 16:\n if (str_length == 2u) {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n for (std::size_t i = 2; i < str_length; ++i) {\n base16_digit_check(arr[i]);\n }\n }\n\n return base;\n}\n\n#if MPPP_CPLUSPLUS >= 201703L && (!defined(_MSC_VER) || defined(__clang__))\n\n\/\/ Small helper to convert the char representation\n\/\/ of a digit into the corresponding numerical\n\/\/ value for a given Base. Base must be one\n\/\/ of 2, 8, 10 or 16, and Int must be some integral\n\/\/ type.\ntemplate <int Base, typename Int>\nconstexpr Int digit_to_value(char c)\n{\n static_assert(std::is_integral_v<Int>);\n static_assert(Base == 2 || Base == 8 || Base == 10 || Base == 16);\n\n if constexpr (Base == 16) {\n if (c >= '0' && c <= '9') {\n return static_cast<Int>(c - '0');\n } else {\n switch (c) {\n case 'a':\n [[fallthrough]];\n case 'A':\n return static_cast<Int>(10);\n case 'b':\n [[fallthrough]];\n case 'B':\n return static_cast<Int>(11);\n case 'c':\n [[fallthrough]];\n case 'C':\n return static_cast<Int>(12);\n case 'd':\n [[fallthrough]];\n case 'D':\n return static_cast<Int>(13);\n case 'e':\n [[fallthrough]];\n case 'E':\n return static_cast<Int>(14);\n default:\n assert(c == 'f' || c == 'F');\n return static_cast<Int>(15);\n }\n }\n } else {\n if constexpr (Base == 2) {\n assert(c == '0' || c == '1');\n } else if constexpr (Base == 8) {\n assert(c >= '0' && c <= '7');\n } else {\n assert(c >= '0' && c <= '9');\n }\n return static_cast<Int>(c - '0');\n }\n}\n\n#endif\n\ntemplate <std::size_t SSize, char... Chars>\ninline integer<SSize> integer_literal_impl()\n{\n \/\/ Turn the sequence of input chars\n \/\/ into a null-terminated char array.\n \/\/ NOTE: earlier clang versions won't properly\n \/\/ capture arr in the lambdas below if it is\n \/\/ not marked as static.\n#if defined(__clang__) && __clang_major__ <= 5\n static\n#endif\n constexpr char arr[]\n = {Chars..., '\\0'};\n\n#if MPPP_CPLUSPLUS >= 201703L && (!defined(_MSC_VER) || defined(__clang__)) && !defined(__INTEL_COMPILER)\n \/\/ Run the checks on the char sequence, and determine the base.\n constexpr auto base = integer_literal_check_str(arr);\n static_assert(base == 2 || base == 8 || base == 10 || base == 16);\n\n \/\/ The actual number of digits in the literal\n \/\/ (discounting prefixes).\n constexpr auto ndigits = (base == 2 || base == 16) ? (sizeof...(Chars) - 2u)\n : (base == 8 ? (sizeof...(Chars) - 1u) : sizeof...(Chars));\n\n \/\/ Determine how many digits in the given base we can always fit\n \/\/ into a single mp_limb_t.\n constexpr auto nd_limb = static_cast<unsigned>([]() {\n [[maybe_unused]] constexpr auto nbits = std::numeric_limits<::mp_limb_t>::digits;\n\n if constexpr (base == 2) {\n \/\/ Base 2, just return the number of bits.\n return nbits;\n } else if constexpr (base == 8) {\n \/\/ Base 8, need 3 bits per digit.\n return nbits \/ 3;\n } else if constexpr (base == 16) {\n \/\/ Base 16, need 4 bits per digit.\n return nbits \/ 4;\n } else {\n \/\/ Base 10, use digits10.\n return std::numeric_limits<::mp_limb_t>::digits10;\n }\n }());\n\n \/\/ Determine how many instances of mp_limb_t we need\n \/\/ to represent the literal.\n constexpr auto nlimbs = ndigits \/ nd_limb + static_cast<unsigned>(ndigits % nd_limb != 0u);\n static_assert(nlimbs > 0u);\n\n \/\/ Helper function to parse a single limb from a subset\n \/\/ of digits at indices [begin, end) in the literal.\n auto parse_limb = [](std::size_t begin, std::size_t end) {\n ::mp_limb_t retval = 0, shifter = 1;\n\n for (auto i = end; i > begin; --i) {\n const auto cur_digit = digit_to_value<base, ::mp_limb_t>(arr[i - 1u]);\n retval += cur_digit * shifter;\n\n if (i > begin + 1u) {\n \/\/ If this is not the last iteration, update the shifter.\n shifter *= static_cast<::mp_limb_t>(base);\n }\n }\n\n return retval;\n };\n\n if constexpr (nlimbs == 1u) {\n \/\/ Fast path if the literal fits into\n \/\/ a single mp_limb_t.\n constexpr auto l = parse_limb(sizeof...(Chars) - ndigits, sizeof...(Chars));\n\n return integer<SSize>{l};\n } else {\n \/\/ The literal needs more than 1 limb:\n \/\/ build an array of limbs from the literal\n \/\/ and use it to construct the integer\n \/\/ arithmetically.\n\n \/\/ Small wrapper to return an array\n \/\/ from a lambda.\n struct arr_wrap {\n ::mp_limb_t arr[nlimbs];\n };\n\n constexpr auto limb_arr = [parse_limb]() {\n arr_wrap retval{};\n\n \/\/ Manually compute the first limb, which might\n \/\/ contain fewer digits than the others (in which\n \/\/ case rem is non-null).\n constexpr auto rem = ndigits % nd_limb;\n const auto idx_end1 = sizeof...(Chars) - ndigits + (rem == 0u ? nd_limb : rem);\n retval.arr[0] = parse_limb(sizeof...(Chars) - ndigits, idx_end1);\n\n for (std::size_t i = 1; i < nlimbs; ++i) {\n retval.arr[i] = parse_limb(idx_end1 + (i - 1u) * nd_limb, idx_end1 + i * nd_limb);\n }\n\n return retval;\n }();\n\n \/\/ Turn the limb array into an integer.\n \/\/ Start with the least significant limb.\n integer<SSize> retval{limb_arr.arr[nlimbs - 1u]}, tmp;\n\n \/\/ A couple of variables used only in base 10.\n [[maybe_unused]] const auto factor10 = []() {\n if constexpr (base == 10) {\n return mppp::pow_ui(integer<SSize>{10}, nd_limb);\n } else {\n return 0;\n }\n }();\n [[maybe_unused]] auto cur_factor10(factor10);\n\n if constexpr (base != 10) {\n \/\/ NOTE: for bases other than 10, we will use bit shifting below.\n \/\/ Make sure that we can represent the max shift amount\n \/\/ via std::size_t.\n static_assert(nlimbs <= std::numeric_limits<std::size_t>::max()\n \/ static_cast<unsigned>(std::numeric_limits<::mp_limb_t>::digits));\n }\n\n for (std::size_t i = nlimbs - 1u; i > 0u; --i) {\n tmp = limb_arr.arr[i - 1u];\n\n if constexpr (base == 2) {\n tmp <<= (nd_limb * (nlimbs - i));\n } else if constexpr (base == 8) {\n tmp <<= (nd_limb * 3u * (nlimbs - i));\n } else if constexpr (base == 16) {\n tmp <<= (nd_limb * 4u * (nlimbs - i));\n } else {\n tmp *= cur_factor10;\n cur_factor10 *= factor10;\n }\n\n retval += tmp;\n }\n\n return retval;\n }\n#else\n \/\/ Run the checks on the char sequence, and determine the base.\n const auto base = integer_literal_check_str(arr);\n assert(base == 2 || base == 8 || base == 10 || base == 16);\n\n switch (base) {\n case 2:\n return integer<SSize>{arr + 2, arr + sizeof(arr) - 1, 2};\n case 8:\n return integer<SSize>{arr + 1, arr + sizeof(arr) - 1, 8};\n case 16:\n return integer<SSize>{arr + 2, arr + sizeof(arr) - 1, 16};\n default:\n return integer<SSize>{arr};\n }\n#endif\n}\n\n} \/\/ namespace detail\n\ninline namespace literals\n{\n\n#define MPPP_DECLARE_INTEGRAL_UDL(n) \\\n template <char... Chars> \\\n inline integer<n> operator\"\" _z##n() \\\n { \\\n return detail::integer_literal_impl<n, Chars...>(); \\\n }\n\nMPPP_DECLARE_INTEGRAL_UDL(1)\nMPPP_DECLARE_INTEGRAL_UDL(2)\nMPPP_DECLARE_INTEGRAL_UDL(3)\n\n#undef MPPP_DECLARE_INTEGRAL_UDL\n\n} \/\/ namespace literals\n\n} \/\/ namespace mppp\n\n#endif\n<commit_msg>workaround for AppleClang<commit_after>\/\/ Copyright 2016-2020 Francesco Biscani (bluescarni@gmail.com)\n\/\/\n\/\/ This file is part of the mp++ library.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef MPPP_DETAIL_INTEGER_LITERALS_HPP\n#define MPPP_DETAIL_INTEGER_LITERALS_HPP\n\n#include <cassert>\n#include <cstddef>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <utility>\n\n#include <mp++\/config.hpp>\n#include <mp++\/detail\/gmp.hpp>\n#include <mp++\/detail\/utils.hpp>\n\nnamespace mppp\n{\n\nnamespace detail\n{\n\n\/\/ Helper to check if an integral literal is valid.\n\/\/ It will return the base of the literal. Supported\n\/\/ bases are 2, 8, 10 and 16.\n\/\/ NOTE: we need this function in the C++11\/C++14 implementation\n\/\/ as well, so use MPPP_CONSTEXPR_14, MPPP_FALLTHROUGH, etc.\ntemplate <std::size_t Size>\ninline\n#if !defined(_MSC_VER) || defined(__clang__)\n MPPP_CONSTEXPR_14\n#endif\n int\n integer_literal_check_str(const char (&arr)[Size])\n{\n \/\/ We expect the size of the array to be\n \/\/ always at least 2, the null terminator\n \/\/ plus at least one char from the literal.\n static_assert(Size >= 2u, \"Invalid array size.\");\n#if MPPP_CPLUSPLUS >= 201703L\n assert(arr[Size - 1u] == '\\0');\n#endif\n\n \/\/ The actual string length of the literal.\n constexpr auto str_length = Size - 1u;\n\n \/\/ Helpers to check a digit in various bases.\n auto base10_digit_check = [&arr](char c) {\n if (c < '0' || c > '9') {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n };\n\n auto base8_digit_check = [&arr](char c) {\n if (c < '0' || c > '7') {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n };\n\n auto base2_digit_check = [&arr](char c) {\n if (c != '0' && c != '1') {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n };\n\n auto base16_digit_check = [&arr](char c) {\n if (c < '0' || c > '9') {\n switch (c) {\n case 'a':\n MPPP_FALLTHROUGH;\n case 'b':\n MPPP_FALLTHROUGH;\n case 'c':\n MPPP_FALLTHROUGH;\n case 'd':\n MPPP_FALLTHROUGH;\n case 'e':\n MPPP_FALLTHROUGH;\n case 'f':\n MPPP_FALLTHROUGH;\n case 'A':\n MPPP_FALLTHROUGH;\n case 'B':\n MPPP_FALLTHROUGH;\n case 'C':\n MPPP_FALLTHROUGH;\n case 'D':\n MPPP_FALLTHROUGH;\n case 'E':\n MPPP_FALLTHROUGH;\n case 'F':\n return;\n default:\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n }\n };\n\n if (str_length == 1u) {\n \/\/ If the string length is 1, the only\n \/\/ character must be in the ['0', '9'] range.\n base10_digit_check(arr[0]);\n\n \/\/ NOTE: the literal \"0\" is actually an\n \/\/ octal, but it does not matter if we\n \/\/ construct it using base 10.\n return 10;\n }\n\n \/\/ The string length is at least 2. Infer the base\n \/\/ of the literal.\n const int base = [&arr, base8_digit_check, base10_digit_check]() -> int {\n \/\/ Fetch the first 2 digits.\n const auto d0 = arr[0], d1 = arr[1];\n\n if (d0 == '0') {\n \/\/ Binary, octal or hex.\n if (d1 == 'b' || d1 == 'B') {\n return 2;\n } else if (d1 == 'x' || d1 == 'X') {\n return 16;\n } else {\n base8_digit_check(d1);\n return 8;\n }\n } else {\n \/\/ Decimal.\n base10_digit_check(d0);\n base10_digit_check(d1);\n return 10;\n }\n }();\n\n#if MPPP_CPLUSPLUS >= 201703L\n assert(base == 2 || base == 8 || base == 10 || base == 16);\n#endif\n\n \/\/ Run the checks on the rest of the literal,\n \/\/ after we already checked the first 2 digits.\n \/\/ For bases 2 and 16, we need to have other digits,\n \/\/ otherwise the literal is malformed.\n \/\/ NOLINTNEXTLINE(hicpp-multiway-paths-covered)\n switch (base) {\n case 2:\n if (str_length == 2u) {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n for (std::size_t i = 2; i < str_length; ++i) {\n base2_digit_check(arr[i]);\n }\n break;\n case 8:\n for (std::size_t i = 2; i < str_length; ++i) {\n base8_digit_check(arr[i]);\n }\n break;\n case 10:\n for (std::size_t i = 2; i < str_length; ++i) {\n base10_digit_check(arr[i]);\n }\n break;\n case 16:\n if (str_length == 2u) {\n throw std::invalid_argument(\"Invalid integral literal: \" + std::string(arr));\n }\n for (std::size_t i = 2; i < str_length; ++i) {\n base16_digit_check(arr[i]);\n }\n }\n\n return base;\n}\n\n#if MPPP_CPLUSPLUS >= 201703L && (!defined(_MSC_VER) || defined(__clang__))\n\n\/\/ Small helper to convert the char representation\n\/\/ of a digit into the corresponding numerical\n\/\/ value for a given Base. Base must be one\n\/\/ of 2, 8, 10 or 16, and Int must be some integral\n\/\/ type.\ntemplate <int Base, typename Int>\nconstexpr Int digit_to_value(char c)\n{\n static_assert(std::is_integral_v<Int>);\n static_assert(Base == 2 || Base == 8 || Base == 10 || Base == 16);\n\n if constexpr (Base == 16) {\n if (c >= '0' && c <= '9') {\n return static_cast<Int>(c - '0');\n } else {\n switch (c) {\n case 'a':\n [[fallthrough]];\n case 'A':\n return static_cast<Int>(10);\n case 'b':\n [[fallthrough]];\n case 'B':\n return static_cast<Int>(11);\n case 'c':\n [[fallthrough]];\n case 'C':\n return static_cast<Int>(12);\n case 'd':\n [[fallthrough]];\n case 'D':\n return static_cast<Int>(13);\n case 'e':\n [[fallthrough]];\n case 'E':\n return static_cast<Int>(14);\n default:\n assert(c == 'f' || c == 'F');\n return static_cast<Int>(15);\n }\n }\n } else {\n if constexpr (Base == 2) {\n assert(c == '0' || c == '1');\n } else if constexpr (Base == 8) {\n assert(c >= '0' && c <= '7');\n } else {\n assert(c >= '0' && c <= '9');\n }\n return static_cast<Int>(c - '0');\n }\n}\n\n#endif\n\ntemplate <std::size_t SSize, char... Chars>\ninline integer<SSize> integer_literal_impl()\n{\n \/\/ Turn the sequence of input chars\n \/\/ into a null-terminated char array.\n \/\/ NOTE: earlier clang versions won't properly\n \/\/ capture arr in the lambdas below if it is\n \/\/ not marked as static.\n#if defined(__clang__) && (defined(__apple_build_version__) || __clang_major__ <= 5)\n static\n#endif\n constexpr char arr[]\n = {Chars..., '\\0'};\n\n#if MPPP_CPLUSPLUS >= 201703L && (!defined(_MSC_VER) || defined(__clang__)) && !defined(__INTEL_COMPILER)\n \/\/ Run the checks on the char sequence, and determine the base.\n constexpr auto base = integer_literal_check_str(arr);\n static_assert(base == 2 || base == 8 || base == 10 || base == 16);\n\n \/\/ The actual number of digits in the literal\n \/\/ (discounting prefixes).\n constexpr auto ndigits = (base == 2 || base == 16) ? (sizeof...(Chars) - 2u)\n : (base == 8 ? (sizeof...(Chars) - 1u) : sizeof...(Chars));\n\n \/\/ Determine how many digits in the given base we can always fit\n \/\/ into a single mp_limb_t.\n constexpr auto nd_limb = static_cast<unsigned>([]() {\n [[maybe_unused]] constexpr auto nbits = std::numeric_limits<::mp_limb_t>::digits;\n\n if constexpr (base == 2) {\n \/\/ Base 2, just return the number of bits.\n return nbits;\n } else if constexpr (base == 8) {\n \/\/ Base 8, need 3 bits per digit.\n return nbits \/ 3;\n } else if constexpr (base == 16) {\n \/\/ Base 16, need 4 bits per digit.\n return nbits \/ 4;\n } else {\n \/\/ Base 10, use digits10.\n return std::numeric_limits<::mp_limb_t>::digits10;\n }\n }());\n\n \/\/ Determine how many instances of mp_limb_t we need\n \/\/ to represent the literal.\n constexpr auto nlimbs = ndigits \/ nd_limb + static_cast<unsigned>(ndigits % nd_limb != 0u);\n static_assert(nlimbs > 0u);\n\n \/\/ Helper function to parse a single limb from a subset\n \/\/ of digits at indices [begin, end) in the literal.\n auto parse_limb = [](std::size_t begin, std::size_t end) {\n ::mp_limb_t retval = 0, shifter = 1;\n\n for (auto i = end; i > begin; --i) {\n const auto cur_digit = digit_to_value<base, ::mp_limb_t>(arr[i - 1u]);\n retval += cur_digit * shifter;\n\n if (i > begin + 1u) {\n \/\/ If this is not the last iteration, update the shifter.\n shifter *= static_cast<::mp_limb_t>(base);\n }\n }\n\n return retval;\n };\n\n if constexpr (nlimbs == 1u) {\n \/\/ Fast path if the literal fits into\n \/\/ a single mp_limb_t.\n constexpr auto l = parse_limb(sizeof...(Chars) - ndigits, sizeof...(Chars));\n\n return integer<SSize>{l};\n } else {\n \/\/ The literal needs more than 1 limb:\n \/\/ build an array of limbs from the literal\n \/\/ and use it to construct the integer\n \/\/ arithmetically.\n\n \/\/ Small wrapper to return an array\n \/\/ from a lambda.\n struct arr_wrap {\n ::mp_limb_t arr[nlimbs];\n };\n\n constexpr auto limb_arr = [parse_limb]() {\n arr_wrap retval{};\n\n \/\/ Manually compute the first limb, which might\n \/\/ contain fewer digits than the others (in which\n \/\/ case rem is non-null).\n constexpr auto rem = ndigits % nd_limb;\n const auto idx_end1 = sizeof...(Chars) - ndigits + (rem == 0u ? nd_limb : rem);\n retval.arr[0] = parse_limb(sizeof...(Chars) - ndigits, idx_end1);\n\n for (std::size_t i = 1; i < nlimbs; ++i) {\n retval.arr[i] = parse_limb(idx_end1 + (i - 1u) * nd_limb, idx_end1 + i * nd_limb);\n }\n\n return retval;\n }();\n\n \/\/ Turn the limb array into an integer.\n \/\/ Start with the least significant limb.\n integer<SSize> retval{limb_arr.arr[nlimbs - 1u]}, tmp;\n\n \/\/ A couple of variables used only in base 10.\n [[maybe_unused]] const auto factor10 = []() {\n if constexpr (base == 10) {\n return mppp::pow_ui(integer<SSize>{10}, nd_limb);\n } else {\n return 0;\n }\n }();\n [[maybe_unused]] auto cur_factor10(factor10);\n\n if constexpr (base != 10) {\n \/\/ NOTE: for bases other than 10, we will use bit shifting below.\n \/\/ Make sure that we can represent the max shift amount\n \/\/ via std::size_t.\n static_assert(nlimbs <= std::numeric_limits<std::size_t>::max()\n \/ static_cast<unsigned>(std::numeric_limits<::mp_limb_t>::digits));\n }\n\n for (std::size_t i = nlimbs - 1u; i > 0u; --i) {\n tmp = limb_arr.arr[i - 1u];\n\n if constexpr (base == 2) {\n tmp <<= (nd_limb * (nlimbs - i));\n } else if constexpr (base == 8) {\n tmp <<= (nd_limb * 3u * (nlimbs - i));\n } else if constexpr (base == 16) {\n tmp <<= (nd_limb * 4u * (nlimbs - i));\n } else {\n tmp *= cur_factor10;\n cur_factor10 *= factor10;\n }\n\n retval += tmp;\n }\n\n return retval;\n }\n#else\n \/\/ Run the checks on the char sequence, and determine the base.\n const auto base = integer_literal_check_str(arr);\n assert(base == 2 || base == 8 || base == 10 || base == 16);\n\n switch (base) {\n case 2:\n return integer<SSize>{arr + 2, arr + sizeof(arr) - 1, 2};\n case 8:\n return integer<SSize>{arr + 1, arr + sizeof(arr) - 1, 8};\n case 16:\n return integer<SSize>{arr + 2, arr + sizeof(arr) - 1, 16};\n default:\n return integer<SSize>{arr};\n }\n#endif\n}\n\n} \/\/ namespace detail\n\ninline namespace literals\n{\n\n#define MPPP_DECLARE_INTEGRAL_UDL(n) \\\n template <char... Chars> \\\n inline integer<n> operator\"\" _z##n() \\\n { \\\n return detail::integer_literal_impl<n, Chars...>(); \\\n }\n\nMPPP_DECLARE_INTEGRAL_UDL(1)\nMPPP_DECLARE_INTEGRAL_UDL(2)\nMPPP_DECLARE_INTEGRAL_UDL(3)\n\n#undef MPPP_DECLARE_INTEGRAL_UDL\n\n} \/\/ namespace literals\n\n} \/\/ namespace mppp\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"dram_directory_cache.h\"\n#include \"log.h\"\n#include \"utils.h\"\n\nnamespace PrL1PrL2DramDirectoryMSI\n{\n\nDramDirectoryCache::DramDirectoryCache(\n std::string directory_type_str,\n UInt32 total_entries,\n UInt32 associativity,\n UInt32 cache_block_size,\n UInt32 max_hw_sharers,\n UInt32 max_num_sharers,\n UInt32 dram_directory_cache_access_time,\n ShmemPerfModel* shmem_perf_model):\n m_total_entries(total_entries),\n m_associativity(associativity),\n m_cache_block_size(cache_block_size),\n m_dram_directory_cache_access_time(dram_directory_cache_access_time),\n m_shmem_perf_model(shmem_perf_model)\n{\n m_num_sets = m_total_entries \/ m_associativity;\n \n \/\/ Instantiate the directory\n m_directory = new Directory(directory_type_str, total_entries, max_hw_sharers, max_num_sharers);\n\n \/\/ Logs\n m_log_num_sets = floorLog2(m_num_sets);\n m_log_cache_block_size = floorLog2(m_cache_block_size);\n}\n\nDramDirectoryCache::~DramDirectoryCache()\n{\n delete m_directory;\n}\n\nDirectoryEntry*\nDramDirectoryCache::getDirectoryEntry(IntPtr address)\n{\n if (m_shmem_perf_model)\n getShmemPerfModel()->incrCycleCount(m_dram_directory_cache_access_time);\n\n IntPtr tag;\n UInt32 set_index;\n \n \/\/ Assume that it always hit in the Dram Directory Cache for now\n splitAddress(address, tag, set_index);\n \n \/\/ Find the relevant directory entry\n for (UInt32 i = 0; i < m_associativity; i++)\n {\n DirectoryEntry* directory_entry = m_directory->getDirectoryEntry(set_index * m_associativity + i);\n if (m_shmem_perf_model)\n getShmemPerfModel()->incrCycleCount(directory_entry->getLatency());\n\n if (directory_entry->getAddress() == address)\n {\n \/\/ Simple check for now. Make sophisticated later\n return directory_entry;\n }\n }\n\n \/\/ Find a free directory entry if one does not currently exist\n for (UInt32 i = 0; i < m_associativity; i++)\n {\n DirectoryEntry* directory_entry = m_directory->getDirectoryEntry(set_index * m_associativity + i);\n if (directory_entry->getAddress() == INVALID_ADDRESS)\n {\n \/\/ Simple check for now. Make sophisticated later\n directory_entry->setAddress(address);\n return directory_entry;\n }\n }\n\n \/\/ Check in the m_replaced_directory_entry_list\n std::vector<DirectoryEntry*>::iterator it;\n for (it = m_replaced_directory_entry_list.begin(); it != m_replaced_directory_entry_list.end(); it++)\n {\n if ((*it)->getAddress() == address)\n {\n return (*it);\n } \n }\n\n return (DirectoryEntry*) NULL;\n}\n\nvoid\nDramDirectoryCache::getReplacementCandidates(IntPtr address, std::vector<DirectoryEntry*>& replacement_candidate_list)\n{\n assert(getDirectoryEntry(address) == NULL);\n \n IntPtr tag;\n UInt32 set_index;\n splitAddress(address, tag, set_index);\n\n for (UInt32 i = 0; i < m_associativity; i++)\n {\n replacement_candidate_list.push_back(m_directory->getDirectoryEntry(set_index * m_associativity + i));\n }\n}\n\nDirectoryEntry*\nDramDirectoryCache::replaceDirectoryEntry(IntPtr replaced_address, IntPtr address)\n{\n IntPtr tag;\n UInt32 set_index;\n splitAddress(replaced_address, tag, set_index);\n\n for (UInt32 i = 0; i < m_associativity; i++)\n {\n DirectoryEntry* replaced_directory_entry = m_directory->getDirectoryEntry(set_index * m_associativity + i);\n if (replaced_directory_entry->getAddress() == replaced_address)\n {\n m_replaced_directory_entry_list.push_back(replaced_directory_entry);\n\n DirectoryEntry* directory_entry = m_directory->createDirectoryEntry();\n directory_entry->setAddress(address);\n m_directory->setDirectoryEntry(set_index * m_associativity + i, directory_entry);\n\n return directory_entry;\n }\n }\n\n \/\/ Should not reach here\n assert(false);\n}\n\nvoid\nDramDirectoryCache::invalidateDirectoryEntry(IntPtr address)\n{\n std::vector<DirectoryEntry*>::iterator it;\n for (it = m_replaced_directory_entry_list.begin(); it != m_replaced_directory_entry_list.end(); it++)\n {\n if ((*it)->getAddress() == address)\n {\n delete (*it);\n m_replaced_directory_entry_list.erase(it);\n\n return;\n } \n }\n\n \/\/ Should not reach here\n assert(false);\n}\n\nvoid\nDramDirectoryCache::splitAddress(IntPtr address, IntPtr& tag, UInt32& set_index)\n{\n IntPtr cache_block_address = address >> getLogCacheBlockSize();\n tag = cache_block_address >> getLogNumSets();\n set_index = ((UInt32) cache_block_address) & (getNumSets() - 1);\n\n}\n\n}\n<commit_msg>[shared mem] Small change to a performance model<commit_after>#include \"dram_directory_cache.h\"\n#include \"log.h\"\n#include \"utils.h\"\n\nnamespace PrL1PrL2DramDirectoryMSI\n{\n\nDramDirectoryCache::DramDirectoryCache(\n std::string directory_type_str,\n UInt32 total_entries,\n UInt32 associativity,\n UInt32 cache_block_size,\n UInt32 max_hw_sharers,\n UInt32 max_num_sharers,\n UInt32 dram_directory_cache_access_time,\n ShmemPerfModel* shmem_perf_model):\n m_total_entries(total_entries),\n m_associativity(associativity),\n m_cache_block_size(cache_block_size),\n m_dram_directory_cache_access_time(dram_directory_cache_access_time),\n m_shmem_perf_model(shmem_perf_model)\n{\n m_num_sets = m_total_entries \/ m_associativity;\n \n \/\/ Instantiate the directory\n m_directory = new Directory(directory_type_str, total_entries, max_hw_sharers, max_num_sharers);\n\n \/\/ Logs\n m_log_num_sets = floorLog2(m_num_sets);\n m_log_cache_block_size = floorLog2(m_cache_block_size);\n}\n\nDramDirectoryCache::~DramDirectoryCache()\n{\n delete m_directory;\n}\n\nDirectoryEntry*\nDramDirectoryCache::getDirectoryEntry(IntPtr address)\n{\n if (m_shmem_perf_model)\n getShmemPerfModel()->incrCycleCount(m_dram_directory_cache_access_time);\n\n IntPtr tag;\n UInt32 set_index;\n \n \/\/ Assume that it always hit in the Dram Directory Cache for now\n splitAddress(address, tag, set_index);\n \n \/\/ Find the relevant directory entry\n for (UInt32 i = 0; i < m_associativity; i++)\n {\n DirectoryEntry* directory_entry = m_directory->getDirectoryEntry(set_index * m_associativity + i);\n\n if (directory_entry->getAddress() == address)\n {\n if (m_shmem_perf_model)\n getShmemPerfModel()->incrCycleCount(directory_entry->getLatency());\n \/\/ Simple check for now. Make sophisticated later\n return directory_entry;\n }\n }\n\n \/\/ Find a free directory entry if one does not currently exist\n for (UInt32 i = 0; i < m_associativity; i++)\n {\n DirectoryEntry* directory_entry = m_directory->getDirectoryEntry(set_index * m_associativity + i);\n if (directory_entry->getAddress() == INVALID_ADDRESS)\n {\n \/\/ Simple check for now. Make sophisticated later\n directory_entry->setAddress(address);\n return directory_entry;\n }\n }\n\n \/\/ Check in the m_replaced_directory_entry_list\n std::vector<DirectoryEntry*>::iterator it;\n for (it = m_replaced_directory_entry_list.begin(); it != m_replaced_directory_entry_list.end(); it++)\n {\n if ((*it)->getAddress() == address)\n {\n return (*it);\n } \n }\n\n return (DirectoryEntry*) NULL;\n}\n\nvoid\nDramDirectoryCache::getReplacementCandidates(IntPtr address, std::vector<DirectoryEntry*>& replacement_candidate_list)\n{\n assert(getDirectoryEntry(address) == NULL);\n \n IntPtr tag;\n UInt32 set_index;\n splitAddress(address, tag, set_index);\n\n for (UInt32 i = 0; i < m_associativity; i++)\n {\n replacement_candidate_list.push_back(m_directory->getDirectoryEntry(set_index * m_associativity + i));\n }\n}\n\nDirectoryEntry*\nDramDirectoryCache::replaceDirectoryEntry(IntPtr replaced_address, IntPtr address)\n{\n if (m_shmem_perf_model)\n getShmemPerfModel()->incrCycleCount(m_dram_directory_cache_access_time);\n\n IntPtr tag;\n UInt32 set_index;\n splitAddress(replaced_address, tag, set_index);\n\n for (UInt32 i = 0; i < m_associativity; i++)\n {\n DirectoryEntry* replaced_directory_entry = m_directory->getDirectoryEntry(set_index * m_associativity + i);\n if (replaced_directory_entry->getAddress() == replaced_address)\n {\n m_replaced_directory_entry_list.push_back(replaced_directory_entry);\n\n DirectoryEntry* directory_entry = m_directory->createDirectoryEntry();\n directory_entry->setAddress(address);\n m_directory->setDirectoryEntry(set_index * m_associativity + i, directory_entry);\n\n return directory_entry;\n }\n }\n\n \/\/ Should not reach here\n assert(false);\n}\n\nvoid\nDramDirectoryCache::invalidateDirectoryEntry(IntPtr address)\n{\n std::vector<DirectoryEntry*>::iterator it;\n for (it = m_replaced_directory_entry_list.begin(); it != m_replaced_directory_entry_list.end(); it++)\n {\n if ((*it)->getAddress() == address)\n {\n delete (*it);\n m_replaced_directory_entry_list.erase(it);\n\n return;\n } \n }\n\n \/\/ Should not reach here\n assert(false);\n}\n\nvoid\nDramDirectoryCache::splitAddress(IntPtr address, IntPtr& tag, UInt32& set_index)\n{\n IntPtr cache_block_address = address >> getLogCacheBlockSize();\n tag = cache_block_address >> getLogNumSets();\n set_index = ((UInt32) cache_block_address) & (getNumSets() - 1);\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkBasicArchitectureTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include <iostream>\n#include \"itkImage.h\"\n#include \"itkScalar.h\"\n#include \"itkVector.h\"\n#include \"itkRandomImageSource.h\"\n#include \"itkShrinkImage.h\"\n#include \"itkWriteVTKImage.h\"\n#include \"itkReadVTKImage.h\"\n#include \"itkCommand.h\"\n#include \"itkOutputWindow.h\"\n\n\n\/\/ this class is used to send output to stdout and not the itk window\nclass TextOutput : public itk::OutputWindow\n{\npublic:\n virtual void DisplayText(const char* s)\n {\n std::cout << s << std::endl;\n }\n};\n\n\/\/ The following three classes are used to support callbacks\n\/\/ on the shrink filter in the pipeline that follows later\nclass ShowProgressObject\n{\npublic:\n ShowProgressObject(itk::ProcessObject* o)\n {m_Process = o;}\n void ShowProgress()\n {std::cout << \"Progress \" << m_Process->GetProgress() << std::endl;}\n itk::ProcessObject::Pointer m_Process;\n};\n \nclass StartEndEvent\n{\npublic:\n void Start() \n {std::cout << \"start event\" << std::endl;}\n void End()\n {std::cout << \"end event \" << std::endl;}\n};\n\n\nclass AllEvents\n{\npublic:\n void WatchEvents(itk::LightObject *caller, unsigned long event)\n {\n const char* eventName = 0;\n switch(event)\n {\n case itk::Command::DeleteEvent:\n eventName = \"DeleteEvent\";\n break;\n case itk::Command::StartEvent:\n eventName = \"StartEvent\";\n break;\n case itk::Command::EndEvent:\n eventName = \"EndEvent\";\n break;\n case itk::Command::ProgressEvent:\n {\n itk::ProcessObject* obj = dynamic_cast<itk::ProcessObject*>(caller);\n std::cout << \"AnyEvent Progress \" << obj->GetProgress() << std::endl;\n eventName = \"ProgressEvent\";\n break;\n }\n case itk::Command::PickEvent:\n eventName = \"PickEvent\";\n break;\n case itk::Command::StartPickEvent:\n eventName = \"StartPickEvent\";\n break;\n case itk::Command::AbortCheckEvent:\n eventName = \"AbortCheckEvent\";\n break;\n case itk::Command::ExitEvent:\n eventName = \"ExitEvent\";\n break;\n default:\n eventName = \"UserEvent\";\n }\n std::cout << \"Event name: \" << eventName << \" Id: \" << event << std::endl;\n }\n};\n\n\nint main()\n{\n \/\/ Comment the following if you want to use the itk text output window\n itk::OutputWindow::SetInstance(new TextOutput);\n \/\/ Uncomment the following if you want to see each message independently\n \/\/ itk::OutputWindow::GetInstance()->PromptUserOn();\n\n \/\/ Test the creation of an image with native type\n \/\/\n itk::Image<float,2>::Pointer if2 = itk::Image<float,2>::New();\n\n std::cout << std::endl\n << \"Image dimension is \" << itk::Image<float,5>::ImageDimension\n << std::endl;\n std::cout << \"Image dimension is \" << itk::Image<short,1>::ImageDimension\n << std::endl;\n\n \/\/ Begin by creating a simple pipeline. Use the Scalar class as a pixel.\n \/\/\n \/\/ Create a typedef to make the code more digestable\n typedef itk::Image<itk::Scalar<float>,2> FloatImage2DType;\n\n \/\/ Create a source object (in this case a reader)\n itk::ReadVTKImage<FloatImage2DType>::Pointer reader;\n reader = itk::ReadVTKImage<FloatImage2DType>::New();\n reader->SetFileName(\"junkInput.vtk\");\n\n \/\/ Create another source object (in this case a random image generator).\n \/\/ The source object is templated on the output type.\n \/\/\n itk::RandomImageSource<FloatImage2DType>::Pointer random;\n random = itk::RandomImageSource<FloatImage2DType>::New();\n random->SetMin(0.0);\n random->SetMax(1.0);\n\n \/\/ Create a filter...shrink the image by an integral amount. We also \n \/\/ add some callbacks to the start, progress, and end filter execution\n \/\/ methods. The filter is templated on the input and output data types.\n \/\/\n itk::ShrinkImage<FloatImage2DType,FloatImage2DType>::Pointer shrink;\n shrink = itk::ShrinkImage<FloatImage2DType,FloatImage2DType>::New();\n shrink->SetInput(random->GetOutput());\n shrink->SetShrinkFactor(2);\n shrink->DebugOn();\n \n \/\/ Create a command to call ShowProgress when progress event is triggered\n ShowProgressObject progressWatch(shrink);\n itk::SimpleMemberCommand<ShowProgressObject>::Pointer command;\n command = itk::SimpleMemberCommand<ShowProgressObject>::New();\n command->SetCallbackFunction(&progressWatch,\n ShowProgressObject::ShowProgress);\n shrink->AddObserver(itk::Command::ProgressEvent, command);\n \n \/\/ Create a command to call StartEndEvent when start event is triggered\n StartEndEvent startEndWatch;\n itk::SimpleMemberCommand<StartEndEvent>::Pointer start;\n start = itk::SimpleMemberCommand<StartEndEvent>::New();\n start->SetCallbackFunction(&startEndWatch, StartEndEvent::Start);\n shrink->AddObserver(itk::Command::StartEvent, start);\n \n \/\/ Create a command to call StartEndEvent when end event is triggered\n itk::SimpleMemberCommand<StartEndEvent>::Pointer end;\n end = itk::SimpleMemberCommand<StartEndEvent>::New();\n end->SetCallbackFunction(&startEndWatch, StartEndEvent::End);\n shrink->AddObserver(itk::Command::EndEvent, end);\n \n \/\/ Create a command that to call AnyEvent when event is fired\n AllEvents allWatch;\n itk::MemberCommand<AllEvents>::Pointer allEvents;\n allEvents = itk::MemberCommand<AllEvents>::New();\n allEvents->SetCallbackFunction(&allWatch,\n AllEvents::WatchEvents);\n shrink->AddObserver(itk::Command::AnyEvent, allEvents);\n \n \/\/ Create a mapper (in this case a writer). A mapper\n \/\/ is templated on the input type.\n \/\/\n itk::WriteVTKImage<FloatImage2DType>::Pointer writer;\n writer = itk::WriteVTKImage<FloatImage2DType>::New();\n writer->SetInput(shrink->GetOutput());\n writer->SetFileName(\"junkImage.vtk\");\n writer->SetFileTypeToASCII();\n writer->DebugOn();\n writer->Write();\n\n return EXIT_SUCCESS;\n}\n\n\n\n<commit_msg>ENH:Added test for RawImageWriter<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkBasicArchitectureTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include <iostream>\n#include \"itkImage.h\"\n#include \"itkScalar.h\"\n#include \"itkVector.h\"\n#include \"itkRandomImageSource.h\"\n#include \"itkShrinkImage.h\"\n#include \"itkWriteVTKImage.h\"\n#include \"itkWriteRawImage.h\"\n#include \"itkReadVTKImage.h\"\n#include \"itkCommand.h\"\n#include \"itkOutputWindow.h\"\n\n\n\/\/ this class is used to send output to stdout and not the itk window\nclass TextOutput : public itk::OutputWindow\n{\npublic:\n virtual void DisplayText(const char* s)\n {\n std::cout << s << std::endl;\n }\n};\n\n\/\/ The following three classes are used to support callbacks\n\/\/ on the shrink filter in the pipeline that follows later\nclass ShowProgressObject\n{\npublic:\n ShowProgressObject(itk::ProcessObject* o)\n {m_Process = o;}\n void ShowProgress()\n {std::cout << \"Progress \" << m_Process->GetProgress() << std::endl;}\n itk::ProcessObject::Pointer m_Process;\n};\n \nclass StartEndEvent\n{\npublic:\n void Start() \n {std::cout << \"start event\" << std::endl;}\n void End()\n {std::cout << \"end event \" << std::endl;}\n};\n\n\nclass AllEvents\n{\npublic:\n void WatchEvents(itk::LightObject *caller, unsigned long event)\n {\n const char* eventName = 0;\n switch(event)\n {\n case itk::Command::DeleteEvent:\n eventName = \"DeleteEvent\";\n break;\n case itk::Command::StartEvent:\n eventName = \"StartEvent\";\n break;\n case itk::Command::EndEvent:\n eventName = \"EndEvent\";\n break;\n case itk::Command::ProgressEvent:\n {\n itk::ProcessObject* obj = dynamic_cast<itk::ProcessObject*>(caller);\n std::cout << \"AnyEvent Progress \" << obj->GetProgress() << std::endl;\n eventName = \"ProgressEvent\";\n break;\n }\n case itk::Command::PickEvent:\n eventName = \"PickEvent\";\n break;\n case itk::Command::StartPickEvent:\n eventName = \"StartPickEvent\";\n break;\n case itk::Command::AbortCheckEvent:\n eventName = \"AbortCheckEvent\";\n break;\n case itk::Command::ExitEvent:\n eventName = \"ExitEvent\";\n break;\n default:\n eventName = \"UserEvent\";\n }\n std::cout << \"Event name: \" << eventName << \" Id: \" << event << std::endl;\n }\n};\n\n\nint main()\n{\n \/\/ Comment the following if you want to use the itk text output window\n itk::OutputWindow::SetInstance(new TextOutput);\n \/\/ Uncomment the following if you want to see each message independently\n \/\/ itk::OutputWindow::GetInstance()->PromptUserOn();\n\n \/\/ Test the creation of an image with native type\n \/\/\n itk::Image<float,2>::Pointer if2 = itk::Image<float,2>::New();\n\n std::cout << std::endl\n << \"Image dimension is \" << itk::Image<float,5>::ImageDimension\n << std::endl;\n std::cout << \"Image dimension is \" << itk::Image<short,1>::ImageDimension\n << std::endl;\n\n \/\/ Begin by creating a simple pipeline. Use the Scalar class as a pixel.\n \/\/\n \/\/ Create a typedef to make the code more digestable\n typedef itk::Image<itk::Scalar<float>,2> FloatImage2DType;\n\n \/\/ Create a source object (in this case a reader)\n itk::ReadVTKImage<FloatImage2DType>::Pointer reader;\n reader = itk::ReadVTKImage<FloatImage2DType>::New();\n reader->SetFileName(\"junkInput.vtk\");\n\n \/\/ Create another source object (in this case a random image generator).\n \/\/ The source object is templated on the output type.\n \/\/\n itk::RandomImageSource<FloatImage2DType>::Pointer random;\n random = itk::RandomImageSource<FloatImage2DType>::New();\n random->SetMin(0.0);\n random->SetMax(1.0);\n\n \/\/ Create a filter...shrink the image by an integral amount. We also \n \/\/ add some callbacks to the start, progress, and end filter execution\n \/\/ methods. The filter is templated on the input and output data types.\n \/\/\n itk::ShrinkImage<FloatImage2DType,FloatImage2DType>::Pointer shrink;\n shrink = itk::ShrinkImage<FloatImage2DType,FloatImage2DType>::New();\n shrink->SetInput(random->GetOutput());\n shrink->SetShrinkFactor(2);\n shrink->DebugOn();\n \n \/\/ Create a command to call ShowProgress when progress event is triggered\n ShowProgressObject progressWatch(shrink);\n itk::SimpleMemberCommand<ShowProgressObject>::Pointer command;\n command = itk::SimpleMemberCommand<ShowProgressObject>::New();\n command->SetCallbackFunction(&progressWatch,\n ShowProgressObject::ShowProgress);\n shrink->AddObserver(itk::Command::ProgressEvent, command);\n \n \/\/ Create a command to call StartEndEvent when start event is triggered\n StartEndEvent startEndWatch;\n itk::SimpleMemberCommand<StartEndEvent>::Pointer start;\n start = itk::SimpleMemberCommand<StartEndEvent>::New();\n start->SetCallbackFunction(&startEndWatch, StartEndEvent::Start);\n shrink->AddObserver(itk::Command::StartEvent, start);\n \n \/\/ Create a command to call StartEndEvent when end event is triggered\n itk::SimpleMemberCommand<StartEndEvent>::Pointer end;\n end = itk::SimpleMemberCommand<StartEndEvent>::New();\n end->SetCallbackFunction(&startEndWatch, StartEndEvent::End);\n shrink->AddObserver(itk::Command::EndEvent, end);\n \n \/\/ Create a command that to call AnyEvent when event is fired\n AllEvents allWatch;\n itk::MemberCommand<AllEvents>::Pointer allEvents;\n allEvents = itk::MemberCommand<AllEvents>::New();\n allEvents->SetCallbackFunction(&allWatch,\n AllEvents::WatchEvents);\n shrink->AddObserver(itk::Command::AnyEvent, allEvents);\n \n \/\/ Create a mapper (in this case a writer). A mapper\n \/\/ is templated on the input type.\n \/\/\n itk::WriteVTKImage<FloatImage2DType>::Pointer writer;\n writer = itk::WriteVTKImage<FloatImage2DType>::New();\n writer->SetInput(shrink->GetOutput());\n writer->SetFileName(\"BasicArchitectureImage.vtk\");\n writer->SetFileTypeToASCII();\n writer->DebugOn();\n writer->Write();\n\n itk::WriteRawImage<FloatImage2DType>::Pointer rawWriter;\n rawWriter = itk::WriteRawImage<FloatImage2DType>::New();\n rawWriter->SetInput(shrink->GetOutput());\n rawWriter->SetFileName(\"BasicArchitectureImage.dat\");\n rawWriter->SetFileTypeToBinary();\n rawWriter->SetByteOrderToBigEndian();\n rawWriter->DebugOn();\n rawWriter->Write();\n\n return EXIT_SUCCESS;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"dco.hpp\"\n#include \"ampi_tape.hpp\"\n\n#define INT64 long int\n\ntypedef dco::ga1s<double> AD_MODE;\ntypedef AD_MODE::type type;\n\n#ifndef DCO_AMPI\nvoid ampi_interpret_tape(long int idx) {}\n#endif\n\/\/long int ampi_counter=0;\n\nvoid ampi_get_val(void *buf, int *i, double *x) {\n *x=static_cast<type*>(buf)[*i]._value();\n}\nvoid ampi_set_val(void* buf, int *i, double *v) {\n type &dummy= static_cast<type*>(buf)[*i];\n *const_cast<double*>(&(dummy._value())) = *v;\n}\n\nvoid ampi_get_idx(void *buf, int *i, INT64 *idx) {\n type &var = static_cast<type*>(buf)[*i];\n if(!var._data()._is_registered()) {\n *idx=0;\n }\n else {\n *idx = dco::tape_index(var);\n }\n}\n\nvoid ampi_get_adj(INT64 *idx, double *x) {\n if(*idx!=0) *x = AD_MODE::global_tape->_adjoint(*idx);\n}\nvoid ampi_set_adj(INT64 *idx, double *x) {\n if(*idx!=0) AD_MODE::global_tape->_adjoint(*idx) += *x;\n}\n\n\n\/*extern \"C\" *\/void ampi_reset_entry(long int handle);\n\nstruct AMPI_data : AD_MODE::callback_object_t::callback_object_base {\n void* handle;\n \n AMPI_data(){}\n AMPI_data(const AMPI_data *other) {\n handle=other->handle;\n }\n virtual ~AMPI_data() {\n ampi_reset_entry(handle);\n }\n};\n\nvoid ampi_tape_wrapper(AMPI_data *data) {\n ampi_interpret_tape(data->handle);\n}\n\n\nvoid ampi_create_tape_entry(void* handle) {\n if(AD_MODE::global_tape == NULL || !AD_MODE::global_tape->is_active()) {\n\/\/\tstd::cout << \"tape is passive, not AMPI Callback will be created!\" << std::endl;\n\treturn;\n }\n \/\/todo: insert an external function handler!!!\n \/\/AD_MODE::global_tape->register_external_function(&i_tape_wrapper, new AMPI_data(handle));\n AMPI_data *tmp=new AMPI_data();\n tmp->handle=handle;\n AD_MODE::global_tape->insert_callback(\n &i_tape_wrapper,\n AD_MODE::global_tape->create_callback_object<AMPI_data>(tmp)\n );\n\n\n \/\/ ampi_counter++;\n \/\/ std::cout << \"ampi_counter: \" << ampi_counter << endl;\n \n \/\/this will call ampi_interpret_tape\n\/\/std::cout << \"i: \" << *i << endl;\n }\n\nvoid ampi_create_dummies(void *buf, int *size) {\n type *values=static_cast<type*>(buf);\n\n for(int i=0; i<*size; ++i) {\n type &dummy=values[i];\n dummy=0;\n AD_MODE::global_tape->register_variable(dummy);\n }\n}\n\nvoid ampi_create_dummies_displ(void *buf, int* displ, int *size) {\n if (NULL != AD_MODE::global_tape && AD_MODE::global_tape->is_active()){\n\n AD_MODE::type *values=static_cast<AD_MODE::type*>(buf);\n\n for(int i=0;i<*size;++i) {\n AD_MODE::type& dummy=values[*displ + i];\n dummy=0;\n AD_MODE::global_tape->register_variable(dummy);\n }\n }\n}\n\nint ampi_is_tape_active () {\n if (NULL != AD_MODE::global_tape) {\n#ifdef DCO_ALLOW_TAPE_SWITCH_OFF\n return AD_MODE::global_tape->is_active();\n#else\n return 1;\n#endif\n } else {\n return 0;\n }\n}\n\n \n<commit_msg>_data() does not exist in dco anymore. tape_index returns zero for unregistered variables anyway, thus if clause can be omitted<commit_after>#include \"dco.hpp\"\n#include \"ampi_tape.hpp\"\n\n#define INT64 long int\n\ntypedef dco::ga1s<double> AD_MODE;\ntypedef AD_MODE::type type;\n\n#ifndef DCO_AMPI\nvoid ampi_interpret_tape(long int idx) {}\n#endif\n\/\/long int ampi_counter=0;\n\nvoid ampi_get_val(void *buf, int *i, double *x) {\n *x=static_cast<type*>(buf)[*i]._value();\n}\nvoid ampi_set_val(void* buf, int *i, double *v) {\n type &dummy= static_cast<type*>(buf)[*i];\n *const_cast<double*>(&(dummy._value())) = *v;\n}\n\nvoid ampi_get_idx(void *buf, int *i, INT64 *idx) {\n type &var = static_cast<type*>(buf)[*i];\n *idx = dco::tape_index(var);\n}\n\nvoid ampi_get_adj(INT64 *idx, double *x) {\n if(*idx!=0) *x = AD_MODE::global_tape->_adjoint(*idx);\n}\nvoid ampi_set_adj(INT64 *idx, double *x) {\n if(*idx!=0) AD_MODE::global_tape->_adjoint(*idx) += *x;\n}\n\n\n\/*extern \"C\" *\/void ampi_reset_entry(long int handle);\n\nstruct AMPI_data : AD_MODE::callback_object_t::callback_object_base {\n void* handle;\n\n AMPI_data(){}\n AMPI_data(const AMPI_data *other) {\n handle=other->handle;\n }\n virtual ~AMPI_data() {\n ampi_reset_entry(handle);\n }\n};\n\nvoid ampi_tape_wrapper(AMPI_data *data) {\n ampi_interpret_tape(data->handle);\n}\n\n\nvoid ampi_create_tape_entry(void* handle) {\n if(AD_MODE::global_tape == NULL || !AD_MODE::global_tape->is_active()) {\n\/\/\tstd::cout << \"tape is passive, not AMPI Callback will be created!\" << std::endl;\n\treturn;\n }\n \/\/todo: insert an external function handler!!!\n \/\/AD_MODE::global_tape->register_external_function(&i_tape_wrapper, new AMPI_data(handle));\n AMPI_data *tmp=new AMPI_data();\n tmp->handle=handle;\n AD_MODE::global_tape->insert_callback(\n &i_tape_wrapper,\n AD_MODE::global_tape->create_callback_object<AMPI_data>(tmp)\n );\n\n\n \/\/ ampi_counter++;\n \/\/ std::cout << \"ampi_counter: \" << ampi_counter << endl;\n \n \/\/this will call ampi_interpret_tape\n\/\/std::cout << \"i: \" << *i << endl;\n }\n\nvoid ampi_create_dummies(void *buf, int *size) {\n type *values=static_cast<type*>(buf);\n\n for(int i=0; i<*size; ++i) {\n type &dummy=values[i];\n dummy=0;\n AD_MODE::global_tape->register_variable(dummy);\n }\n}\n\nvoid ampi_create_dummies_displ(void *buf, int* displ, int *size) {\n if (NULL != AD_MODE::global_tape && AD_MODE::global_tape->is_active()){\n\n AD_MODE::type *values=static_cast<AD_MODE::type*>(buf);\n\n for(int i=0;i<*size;++i) {\n AD_MODE::type& dummy=values[*displ + i];\n dummy=0;\n AD_MODE::global_tape->register_variable(dummy);\n }\n }\n}\n\nint ampi_is_tape_active () {\n if (NULL != AD_MODE::global_tape) {\n#ifdef DCO_ALLOW_TAPE_SWITCH_OFF\n return AD_MODE::global_tape->is_active();\n#else\n return 1;\n#endif\n } else {\n return 0;\n }\n}\n\n \n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: epgm.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2004-09-09 11:28:07 $\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#include <vcl\/svapp.hxx>\n#include <vcl\/graph.hxx>\n#include <vcl\/bmpacc.hxx>\n#include <vcl\/msgbox.hxx>\n#include <svtools\/solar.hrc>\n#include <svtools\/fltcall.hxx>\n#include <svtools\/FilterConfigItem.hxx>\n#include \"strings.hrc\"\n#include \"dlgepgm.hrc\"\n#include \"dlgepgm.hxx\"\n\n\/\/============================ PGMWriter ==================================\n\nclass PGMWriter {\n\nprivate:\n\n PFilterCallback mpCallback;\n void * mpCallerData;\n\n SvStream* mpOStm; \/\/ Die auszugebende PGM-Datei\n USHORT mpOStmOldModus;\n\n BOOL mbStatus;\n UINT32 mnMode;\n BitmapReadAccess* mpAcc;\n ULONG mnWidth, mnHeight; \/\/ Bildausmass in Pixeln\n\n BOOL ImplCallback( USHORT nPercent );\n BOOL ImplWriteHeader();\n void ImplWriteBody();\n void ImplWriteNumber( sal_Int32 );\n\npublic:\n PGMWriter();\n ~PGMWriter();\n\n BOOL WritePGM( const Graphic& rGraphic, SvStream& rPGM,\n PFilterCallback pCallback, void* pCallerdata,\n FilterConfigItem* pConfigItem );\n};\n\n\/\/=================== Methoden von PGMWriter ==============================\n\nPGMWriter::PGMWriter() :\n mbStatus ( TRUE ),\n mpAcc ( NULL )\n{\n}\n\n\/\/ ------------------------------------------------------------------------\n\nPGMWriter::~PGMWriter()\n{\n}\n\n\/\/ ------------------------------------------------------------------------\n\nBOOL PGMWriter::ImplCallback( USHORT nPercent )\n{\n if ( mpCallback != NULL )\n {\n if ( ( (*mpCallback)( mpCallerData, nPercent ) ) == TRUE )\n {\n mpOStm->SetError( SVSTREAM_FILEFORMAT_ERROR );\n return TRUE;\n }\n }\n return FALSE;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nBOOL PGMWriter::WritePGM( const Graphic& rGraphic, SvStream& rPGM,\n PFilterCallback pCallback, void* pCallerdata,\n FilterConfigItem* pConfigItem )\n{\n\n mpOStm = &rPGM;\n mpCallback = pCallback;\n mpCallerData = pCallerdata;\n\n if ( pConfigItem )\n mnMode = pConfigItem->ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( \"FileFormat\" ) ), 0 );\n\n BitmapEx aBmpEx( rGraphic.GetBitmapEx() );\n Bitmap aBmp = aBmpEx.GetBitmap();\n aBmp.Convert( BMP_CONVERSION_8BIT_GREYS );\n\n mpOStmOldModus = mpOStm->GetNumberFormatInt();\n mpOStm->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );\n\n mpAcc = aBmp.AcquireReadAccess();\n if( mpAcc )\n {\n if ( ImplWriteHeader() )\n {\n ImplWriteBody();\n }\n aBmp.ReleaseAccess( mpAcc );\n }\n else\n mbStatus = FALSE;\n\n mpOStm->SetNumberFormatInt( mpOStmOldModus );\n\n return mbStatus;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nBOOL PGMWriter::ImplWriteHeader()\n{\n mnWidth = mpAcc->Width();\n mnHeight = mpAcc->Height();\n if ( mnWidth && mnHeight )\n {\n if ( mnMode == 0 )\n *mpOStm << \"P5\\x0a\";\n else\n *mpOStm << \"P2\\x0a\";\n\n ImplWriteNumber( mnWidth );\n *mpOStm << (BYTE)32;\n ImplWriteNumber( mnHeight );\n *mpOStm << (BYTE)32;\n ImplWriteNumber( 255 ); \/\/ max. gray value\n *mpOStm << (BYTE)10;\n }\n else\n mbStatus = FALSE;\n\n return mbStatus;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid PGMWriter::ImplWriteBody()\n{\n if ( mnMode == 0 )\n {\n for ( ULONG y = 0; y < mnHeight; y++ )\n {\n for ( ULONG x = 0; x < mnWidth; x++ )\n {\n *mpOStm << (BYTE)( mpAcc->GetPixel( y, x ) );\n }\n }\n }\n else\n {\n for ( ULONG y = 0; y < mnHeight; y++ )\n {\n int nCount = 70;\n for ( ULONG x = 0; x < mnWidth; x++ )\n {\n BYTE nDat, nNumb;\n if ( nCount < 0 )\n {\n nCount = 69;\n *mpOStm << (BYTE)10;\n }\n nDat = (BYTE)mpAcc->GetPixel( y, x );\n if ( ( nNumb = nDat \/ 100 ) )\n {\n *mpOStm << (BYTE)( nNumb + '0' );\n nDat -= ( nNumb * 100 );\n nNumb = nDat \/ 10;\n *mpOStm << (BYTE)( nNumb + '0' );\n nDat -= ( nNumb * 10 );\n *mpOStm << (BYTE)( nDat + '0' );\n nCount -= 4;\n }\n else if ( ( nNumb = nDat \/ 10 ) )\n {\n *mpOStm << (BYTE)( nNumb + '0' );\n nDat -= ( nNumb * 10 );\n *mpOStm << (BYTE)( nDat + '0' );\n nCount -= 3;\n }\n else\n {\n *mpOStm << (BYTE)( nDat + '0' );\n nCount -= 2;\n }\n *mpOStm << (BYTE)' ';\n }\n *mpOStm << (BYTE)10;\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\/\/ eine Dezimalzahl im ASCII format wird in den Stream geschrieben\n\nvoid PGMWriter::ImplWriteNumber( sal_Int32 nNumber )\n{\n const ByteString aNum( ByteString::CreateFromInt32( nNumber ) );\n\n for( sal_Int16 n = 0UL, nLen = aNum.Len(); n < nLen; n++ )\n *mpOStm << aNum.GetChar( n );\n\n}\n\n\/\/ ------------------------------------------------------------------------\n\n\/\/ ---------------------\n\/\/ - exported function -\n\/\/ ---------------------\n\nextern \"C\" BOOL __LOADONCALLAPI GraphicExport( SvStream& rStream, Graphic& rGraphic,\n PFilterCallback pCallback, void* pCallerData,\n FilterConfigItem* pConfigItem, BOOL )\n{\n PGMWriter aPGMWriter;\n\n return aPGMWriter.WritePGM( rGraphic, rStream, pCallback, pCallerData, pConfigItem );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nextern \"C\" BOOL __LOADONCALLAPI DoExportDialog( FltCallDialogParameter& rPara )\n{\n BOOL bRet = FALSE;\n\n if ( rPara.pWindow )\n {\n ByteString aResMgrName( \"epg\" );\n ResMgr* pResMgr;\n\n aResMgrName.Append( ByteString::CreateFromInt32( SOLARUPD ) );\n pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(), Application::GetSettings().GetUILocale() );\n\n if( pResMgr )\n {\n rPara.pResMgr = pResMgr;\n bRet = ( DlgExportEPGM( rPara ).Execute() == RET_OK );\n delete pResMgr;\n }\n else\n bRet = TRUE;\n }\n\n return bRet;\n}\n\n\/\/ ------------------------------------------------------------------------\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n\/\/ ---------------\n\/\/ - Win16 trash -\n\/\/ ---------------\n\n#ifdef WIN\n\nstatic HINSTANCE hDLLInst = 0;\n\nextern \"C\" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )\n{\n if ( nHeap )\n UnlockData( 0 );\n\n hDLLInst = hDLL;\n\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nextern \"C\" int CALLBACK WEP( int )\n{\n return 1;\n}\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.84); FILE MERGED 2005\/09\/05 15:12:21 rt 1.5.84.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: epgm.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 02:38: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\n#include <vcl\/svapp.hxx>\n#include <vcl\/graph.hxx>\n#include <vcl\/bmpacc.hxx>\n#include <vcl\/msgbox.hxx>\n#include <svtools\/solar.hrc>\n#include <svtools\/fltcall.hxx>\n#include <svtools\/FilterConfigItem.hxx>\n#include \"strings.hrc\"\n#include \"dlgepgm.hrc\"\n#include \"dlgepgm.hxx\"\n\n\/\/============================ PGMWriter ==================================\n\nclass PGMWriter {\n\nprivate:\n\n PFilterCallback mpCallback;\n void * mpCallerData;\n\n SvStream* mpOStm; \/\/ Die auszugebende PGM-Datei\n USHORT mpOStmOldModus;\n\n BOOL mbStatus;\n UINT32 mnMode;\n BitmapReadAccess* mpAcc;\n ULONG mnWidth, mnHeight; \/\/ Bildausmass in Pixeln\n\n BOOL ImplCallback( USHORT nPercent );\n BOOL ImplWriteHeader();\n void ImplWriteBody();\n void ImplWriteNumber( sal_Int32 );\n\npublic:\n PGMWriter();\n ~PGMWriter();\n\n BOOL WritePGM( const Graphic& rGraphic, SvStream& rPGM,\n PFilterCallback pCallback, void* pCallerdata,\n FilterConfigItem* pConfigItem );\n};\n\n\/\/=================== Methoden von PGMWriter ==============================\n\nPGMWriter::PGMWriter() :\n mbStatus ( TRUE ),\n mpAcc ( NULL )\n{\n}\n\n\/\/ ------------------------------------------------------------------------\n\nPGMWriter::~PGMWriter()\n{\n}\n\n\/\/ ------------------------------------------------------------------------\n\nBOOL PGMWriter::ImplCallback( USHORT nPercent )\n{\n if ( mpCallback != NULL )\n {\n if ( ( (*mpCallback)( mpCallerData, nPercent ) ) == TRUE )\n {\n mpOStm->SetError( SVSTREAM_FILEFORMAT_ERROR );\n return TRUE;\n }\n }\n return FALSE;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nBOOL PGMWriter::WritePGM( const Graphic& rGraphic, SvStream& rPGM,\n PFilterCallback pCallback, void* pCallerdata,\n FilterConfigItem* pConfigItem )\n{\n\n mpOStm = &rPGM;\n mpCallback = pCallback;\n mpCallerData = pCallerdata;\n\n if ( pConfigItem )\n mnMode = pConfigItem->ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( \"FileFormat\" ) ), 0 );\n\n BitmapEx aBmpEx( rGraphic.GetBitmapEx() );\n Bitmap aBmp = aBmpEx.GetBitmap();\n aBmp.Convert( BMP_CONVERSION_8BIT_GREYS );\n\n mpOStmOldModus = mpOStm->GetNumberFormatInt();\n mpOStm->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );\n\n mpAcc = aBmp.AcquireReadAccess();\n if( mpAcc )\n {\n if ( ImplWriteHeader() )\n {\n ImplWriteBody();\n }\n aBmp.ReleaseAccess( mpAcc );\n }\n else\n mbStatus = FALSE;\n\n mpOStm->SetNumberFormatInt( mpOStmOldModus );\n\n return mbStatus;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nBOOL PGMWriter::ImplWriteHeader()\n{\n mnWidth = mpAcc->Width();\n mnHeight = mpAcc->Height();\n if ( mnWidth && mnHeight )\n {\n if ( mnMode == 0 )\n *mpOStm << \"P5\\x0a\";\n else\n *mpOStm << \"P2\\x0a\";\n\n ImplWriteNumber( mnWidth );\n *mpOStm << (BYTE)32;\n ImplWriteNumber( mnHeight );\n *mpOStm << (BYTE)32;\n ImplWriteNumber( 255 ); \/\/ max. gray value\n *mpOStm << (BYTE)10;\n }\n else\n mbStatus = FALSE;\n\n return mbStatus;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid PGMWriter::ImplWriteBody()\n{\n if ( mnMode == 0 )\n {\n for ( ULONG y = 0; y < mnHeight; y++ )\n {\n for ( ULONG x = 0; x < mnWidth; x++ )\n {\n *mpOStm << (BYTE)( mpAcc->GetPixel( y, x ) );\n }\n }\n }\n else\n {\n for ( ULONG y = 0; y < mnHeight; y++ )\n {\n int nCount = 70;\n for ( ULONG x = 0; x < mnWidth; x++ )\n {\n BYTE nDat, nNumb;\n if ( nCount < 0 )\n {\n nCount = 69;\n *mpOStm << (BYTE)10;\n }\n nDat = (BYTE)mpAcc->GetPixel( y, x );\n if ( ( nNumb = nDat \/ 100 ) )\n {\n *mpOStm << (BYTE)( nNumb + '0' );\n nDat -= ( nNumb * 100 );\n nNumb = nDat \/ 10;\n *mpOStm << (BYTE)( nNumb + '0' );\n nDat -= ( nNumb * 10 );\n *mpOStm << (BYTE)( nDat + '0' );\n nCount -= 4;\n }\n else if ( ( nNumb = nDat \/ 10 ) )\n {\n *mpOStm << (BYTE)( nNumb + '0' );\n nDat -= ( nNumb * 10 );\n *mpOStm << (BYTE)( nDat + '0' );\n nCount -= 3;\n }\n else\n {\n *mpOStm << (BYTE)( nDat + '0' );\n nCount -= 2;\n }\n *mpOStm << (BYTE)' ';\n }\n *mpOStm << (BYTE)10;\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\/\/ eine Dezimalzahl im ASCII format wird in den Stream geschrieben\n\nvoid PGMWriter::ImplWriteNumber( sal_Int32 nNumber )\n{\n const ByteString aNum( ByteString::CreateFromInt32( nNumber ) );\n\n for( sal_Int16 n = 0UL, nLen = aNum.Len(); n < nLen; n++ )\n *mpOStm << aNum.GetChar( n );\n\n}\n\n\/\/ ------------------------------------------------------------------------\n\n\/\/ ---------------------\n\/\/ - exported function -\n\/\/ ---------------------\n\nextern \"C\" BOOL __LOADONCALLAPI GraphicExport( SvStream& rStream, Graphic& rGraphic,\n PFilterCallback pCallback, void* pCallerData,\n FilterConfigItem* pConfigItem, BOOL )\n{\n PGMWriter aPGMWriter;\n\n return aPGMWriter.WritePGM( rGraphic, rStream, pCallback, pCallerData, pConfigItem );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nextern \"C\" BOOL __LOADONCALLAPI DoExportDialog( FltCallDialogParameter& rPara )\n{\n BOOL bRet = FALSE;\n\n if ( rPara.pWindow )\n {\n ByteString aResMgrName( \"epg\" );\n ResMgr* pResMgr;\n\n aResMgrName.Append( ByteString::CreateFromInt32( SOLARUPD ) );\n pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(), Application::GetSettings().GetUILocale() );\n\n if( pResMgr )\n {\n rPara.pResMgr = pResMgr;\n bRet = ( DlgExportEPGM( rPara ).Execute() == RET_OK );\n delete pResMgr;\n }\n else\n bRet = TRUE;\n }\n\n return bRet;\n}\n\n\/\/ ------------------------------------------------------------------------\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n\/\/ ---------------\n\/\/ - Win16 trash -\n\/\/ ---------------\n\n#ifdef WIN\n\nstatic HINSTANCE hDLLInst = 0;\n\nextern \"C\" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )\n{\n if ( nHeap )\n UnlockData( 0 );\n\n hDLLInst = hDLL;\n\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nextern \"C\" int CALLBACK WEP( int )\n{\n return 1;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: main.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 02:52:49 $\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 CGM_MAIN_HXX\n#define CGM_MAIN_HXX\n\n#include <cgm.hxx>\n\n\/\/ ---------------------------------------------------------------\n\n#define CGM_LEVEL1 0x0001 \/\/ VERSION 1 METAFILE\n#define CGM_LEVEL2 0x0002\n#define CGM_LEVEL3 0x0003\n#define CGM_GDSF_ONLY 0x00F0\n#define CGM_UNKNOWN_LEVEL 0x00F1\n#define CGM_UNKNOWN_COMMAND 0x00F2\n#define CGM_DESCRIPTION 0x00F3\n\n#define CGM_EXTENDED_PRIMITIVES_SET 0x0100 \/\/ INDICATES PRIMITIVES WHICH ARE AVAILABLE IN\n \/\/ LEVEL 1 BUT ARE NOT DEFINED IN ISO 7942(GKS)\n#define CGM_DRAWING_PLUS_CONTROL_SET 0x0200 \/\/ INDICATES THAT THIS IS AN ADDITIONAL LEVEL 1\n \/\/ ELEMENT\n#define ComOut( Level, Description ) if ( mpCommentOut ) ImplComment( Level, Description );\n\n#define BMCOL( _col ) BitmapColor( (sal_Int8)(_col >> 16 ), (sal_Int8)( _col >> 8 ), (sal_Int8)_col )\n#define ALIGN2( _nElementSize ) { _nElementSize = ( _nElementSize + 1 ) & ~1; }\n#define ALIGN4( _nElementSize ) { _nElementSize = ( _nElementSize + 3 ) & ~3; }\n#define ALIGN8( _nElementSize ) { _nElementSize = ( _nElementSize + 7 ) & ~7; }\n\n#include <vcl\/salbtype.hxx>\n#include <tools\/stream.hxx>\n#include <tools\/list.hxx>\n#include \"bundles.hxx\"\n#include \"bitmap.hxx\"\n#include \"elements.hxx\"\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.2.28); FILE MERGED 2005\/10\/28 09:53:13 sj 1.2.28.1: #i55991# warning free code<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: main.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 21:45:46 $\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 CGM_MAIN_HXX\n#define CGM_MAIN_HXX\n\n#include \"cgm.hxx\"\n\n\/\/ ---------------------------------------------------------------\n\n#define CGM_LEVEL1 0x0001 \/\/ VERSION 1 METAFILE\n#define CGM_LEVEL2 0x0002\n#define CGM_LEVEL3 0x0003\n#define CGM_GDSF_ONLY 0x00F0\n#define CGM_UNKNOWN_LEVEL 0x00F1\n#define CGM_UNKNOWN_COMMAND 0x00F2\n#define CGM_DESCRIPTION 0x00F3\n\n#define CGM_EXTENDED_PRIMITIVES_SET 0x0100 \/\/ INDICATES PRIMITIVES WHICH ARE AVAILABLE IN\n \/\/ LEVEL 1 BUT ARE NOT DEFINED IN ISO 7942(GKS)\n#define CGM_DRAWING_PLUS_CONTROL_SET 0x0200 \/\/ INDICATES THAT THIS IS AN ADDITIONAL LEVEL 1\n \/\/ ELEMENT\n#define ComOut( Level, Description ) if ( mpCommentOut ) ImplComment( Level, Description );\n\n#define BMCOL( _col ) BitmapColor( (sal_Int8)(_col >> 16 ), (sal_Int8)( _col >> 8 ), (sal_Int8)_col )\n#define ALIGN2( _nElementSize ) { _nElementSize = ( _nElementSize + 1 ) & ~1; }\n#define ALIGN4( _nElementSize ) { _nElementSize = ( _nElementSize + 3 ) & ~3; }\n#define ALIGN8( _nElementSize ) { _nElementSize = ( _nElementSize + 7 ) & ~7; }\n\n#include <vcl\/salbtype.hxx>\n#include <tools\/stream.hxx>\n#include <tools\/list.hxx>\n#include \"bundles.hxx\"\n#include \"bitmap.hxx\"\n#include \"elements.hxx\"\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>simplify FileSystemHelper implementation<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot & Vincent Caron\n \n licence: see nui3\/LICENCE.TXT\n *\/\n\n\n#pragma once\n#include \"nuiGestureRecognizer.h\"\n\n\n\n\/\/*******************************************************************************************************************\n\/\/*******************************************************************************************************************\n\/\/\n\/\/ class nuiGestureRecognizer\n\/\/\n\n\nnuiGestureRecognizer::nuiGestureRecognizer()\n: nuiSimpleContainer()\n{\n mState = eGestureRecognizerStatePossible;\n}\n\n\nnuiGestureRecognizer::~nuiGestureRecognizer()\n{\n\n}\n\n\nnuiGestureRecognizerState nuiGestureRecognizer::GetState() const\n{\n return mState;\n}\n\nvoid nuiGestureRecognizer::SetState(nuiGestureRecognizerState state)\n{\n mState = state;\n \n \/\/ send synchronous signal\n SignalStateChanged(mState);\n}\n\n \n\n\/\/ virtual \nbool nuiGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n return false;\n}\n\n\n\/\/ virtual \nbool nuiGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n return false;\n}\n\n\n\/\/ virtual \nbool nuiGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)\n{\n return false;\n}\n \n\nconst char* nuiGetString(nuiGestureDirection dir)\n{\n#define F(X) case X: return #X; break;\n switch (dir)\n {\n F(nuiGestureDirectionNull);\n F(nuiGestureDirectionRight);\n F(nuiGestureDirectionLeft);\n F(nuiGestureDirectionUp);\n F(nuiGestureDirectionDown);\n F(nuiGestureDirectionUpRight);\n F(nuiGestureDirectionDownRight);\n F(nuiGestureDirectionDownLeft);\n F(nuiGestureDirectionUpLeft);\n }\n#undef F\n return \"unknown direction\";\n}\n\n\n\n\n\n\n\n\n#define SWIPE_INITIATED_THRESHOLD 9\n#define SWIPE_INITIATED_TIMEOUT 0.10f\n#define SWIPE_ACTIVATED_THRESHOLD 70\n#define SWIPE_ACTIVATED_TIMEOUT 0.15f\n\n\n\/\/************************************************************************************************************\n\/\/************************************************************************************************************\n\/\/\n\/\/ class nuiSwipeGestureRecognizer\n\/\/\n\n\nnuiSwipeGestureRecognizer::nuiSwipeGestureRecognizer(nuiGestureDirection direction)\n: nuiGestureRecognizer()\n{\n mClicked = false;\n mStartX = 0;\n mStartY = 0;\n \n mDirection = direction;\n mRecognizedDirection = nuiGestureDirectionNull;\n}\n\n\n\nnuiSwipeGestureRecognizer::~nuiSwipeGestureRecognizer()\n{\n\n}\n \nvoid nuiSwipeGestureRecognizer::SetDirections(nuiGestureDirection direction)\n{\n mDirection = direction;\n}\n\n\n\/\/ virtual \nbool nuiSwipeGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n bool res = nuiGestureRecognizer::MouseClicked(X, Y, Button);\n \n mRecognizedDirection = nuiGestureDirectionNull;\n \n mClicked = true;\n mTime = nglTime();\n mInitiatedTime = 0;\n mStartX = X;\n mStartY = Y;\n\n Grab();\n return false;\n}\n\n\n\/\/ virtual \nbool nuiSwipeGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n bool res = nuiGestureRecognizer::MouseUnclicked(X, Y, Button);\n \n mClicked = false;\n SetState(eGestureRecognizerStatePossible);\n\n mTime = nglTime();\n mInitiatedTime = 0;\n mStartX = 0;\n mStartY = 0;\n Ungrab();\n \n return false;\n}\n\n\n\/\/ virtual \nbool nuiSwipeGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)\n{\n bool res = nuiGestureRecognizer::MouseMoved(X, Y);\n\n if (!mClicked)\n return false;\n \n if (GetState() == eGestureRecognizerStateEnded)\n return false;\n \n\tdouble diffx = mStartX - X;\n\tdouble diffy = mStartY - Y;\n double currentTime = nglTime();\n \n \/\/ has the swipe gesture been initiated?\n if (GetState() != eGestureRecognizerStateBegan)\n {\n bool initiatedOnX = (abs(diffx) >= SWIPE_INITIATED_THRESHOLD);\n bool initiatedOnY = (abs(diffy) >= SWIPE_INITIATED_THRESHOLD);\n \n \/\/ yes, it's been initiated.\n if (initiatedOnX || initiatedOnY)\n {\n mRecognizedDirection = GetGestureDirection(initiatedOnX, initiatedOnY, mStartX, X, mStartY, Y);\n\n \/\/ is this recognizer in charge of the detected gesture?\n if ((mRecognizedDirection & mDirection) \n && ((currentTime - mTime) < SWIPE_INITIATED_TIMEOUT))\n {\n \/\/ yes. consider that the gesture recognition has began\n mInitiatedTime = currentTime;\n SetState(eGestureRecognizerStateBegan);\n }\n \/\/ no, it's not. set data for the next call\n else\n {\n mStartX = X;\n mStartY = Y;\n mTime = currentTime;\n }\n }\n }\n \n \/\/ not yet. it's a simple \"move\" gesture.\n if (GetState() != eGestureRecognizerStateBegan)\n return false;\n \n \/\/ swipe has been initiated, is the gesture fully completed?\n bool activatedOnX = (abs(diffx) >= SWIPE_ACTIVATED_THRESHOLD);\n bool activatedOnY = (abs(diffy) >= SWIPE_ACTIVATED_THRESHOLD);\n \n if(activatedOnX || activatedOnY)\n\t{\n \/\/ the swipe gesture has been avorted. let's reset the data and start again\n if ((currentTime - mInitiatedTime) > SWIPE_ACTIVATED_TIMEOUT)\n {\n mTime = nglTime();\n mInitiatedTime = 0;\n mStartX = X;\n mStartY = Y;\n SetState(eGestureRecognizerStateFailed);\n mRecognizedDirection = nuiGestureDirectionNull;\n \n return false;\n }\n \n \/\/ ok! the swipe gesture has been completed!\n\t\tSetState(eGestureRecognizerStateEnded);\n \n \/\/ let's assume it's no use to compute mDirection here, since it's been done when the swipe gesture has been initiated.\n \/\/ we'll see in the future if it's wrong to make that assumption.\n \/\/ mDirection = GetGesturePosition(activatedOnX, activatedOnY, mStartX, X, mStartY, Y);\n \n \/\/ send synchronous event\n SignalSwipe(mRecognizedDirection);\n\t}\n \n return false;\n}\n\n\nnuiGestureDirection nuiSwipeGestureRecognizer::GetRecognizedDirection() const\n{\n return mRecognizedDirection;\n}\n\n\nnuiGestureDirection nuiSwipeGestureRecognizer::GetGestureDirection(bool evalOnX, bool evalOnY, nuiSize x1, nuiSize x2, nuiSize y1, nuiSize y2) const\n{\n \/\/ diagonal gesture?\n if (evalOnX && evalOnY)\n {\n if (x1 < x2) \n {\n if (y1 < y2)\n return nuiGestureDirectionDownRight;\n else\n return nuiGestureDirectionUpRight;\n }\n else \n {\n if (y1 < y2)\n return nuiGestureDirectionDownLeft;\n else\n return nuiGestureDirectionUpLeft;\n }\n }\n \/\/ horizontal gesture?\n else if (evalOnX)\n {\n if (x1 < x2) \n return nuiGestureDirectionRight;\n else\n return nuiGestureDirectionLeft;\n }\n \/\/ vertical gesture?\n else if (evalOnY)\n {\n if (y1 < y2) \n return nuiGestureDirectionDown;\n else\n return nuiGestureDirectionUp;\n }\n \n return nuiGestureDirectionNull;\n}\n\n\n\n#define PAD_INITIATED_THRESHOLD 9\n#define PAD_INITIATED_TIMEOUT 0.10f\n#define PAD_ACTIVATED_THRESHOLD 70\n#define PAD_ACTIVATED_TIMEOUT 0.15f\n#define PAD_FRICTION 0.9f\n#define PAD_ATTENUATOR_THRESHOLD 4.0f\n#define PAD_THRESHOLD 1.0f\n\n\n\/\/************************************************************************************************************\n\/\/************************************************************************************************************\n\/\/\n\/\/ class nuiPadGestureRecognizer\n\/\/\n\n\nnuiPadGestureRecognizer::nuiPadGestureRecognizer(nuiGestureDirection direction)\n: nuiGestureRecognizer(), mSink(this)\n{\n mClicked = false;\n mLastX = 0;\n mLastY = 0;\n mFriction = 0.1;\n \n SetDirections(direction);\n mRecognizedDirection = nuiGestureDirectionNull;\n \n nuiTimer* pTimer = nuiAnimation::AcquireTimer();\n mSink.Connect(pTimer->Tick, &nuiPadGestureRecognizer::UpdateForces);\n}\n\n\n\nnuiPadGestureRecognizer::~nuiPadGestureRecognizer()\n{\n \n}\n\nvoid nuiPadGestureRecognizer::SetDirections(nuiGestureDirection direction)\n{\n mDirection = direction;\n\n#define F(X) (std::pair<float, float>(X - 22.5, X + 22.5))\n \n mDirections[nuiGestureDirectionRight] = F(0);\n mDirections[nuiGestureDirectionUpRight] = F(45);\n mDirections[nuiGestureDirectionUp] = F(90);\n mDirections[nuiGestureDirectionUpLeft] = F(135);\n mDirections[nuiGestureDirectionLeft] = F(180);\n mDirections[nuiGestureDirectionDownLeft] = F(225);\n mDirections[nuiGestureDirectionDown] = F(270);\n mDirections[nuiGestureDirectionDownRight] = F(315);\n \n#undef X\n}\n\nnuiGestureDirection nuiPadGestureRecognizer::GetDirectionFromAngle(float angle) const\n{\n std::map<nuiGestureDirection, std::pair<float, float> >::const_iterator it = mDirections.begin();\n\n if (angle > 360 - 22.5)\n angle = angle - 360;\n \n while (it != mDirections.end())\n {\n if (it->second.first < angle && it->second.second >= angle)\n return it->first;\n \n ++it;\n }\n \n return nuiGestureDirectionNull;\n}\n\n\n\/\/ virtual \nbool nuiPadGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n bool res = nuiGestureRecognizer::MouseClicked(X, Y, Button);\n \n mRecognizedDirection = nuiGestureDirectionNull;\n \n mClicked = true;\n mLastX = X;\n mLastY = Y;\n \n Grab();\n return false;\n}\n\n\n\/\/ virtual \nbool nuiPadGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n bool res = nuiGestureRecognizer::MouseUnclicked(X, Y, Button);\n \n mClicked = false;\n SetState(eGestureRecognizerStatePossible);\n \n mLastX = 0;\n mLastY = 0;\n\n Ungrab();\n return false;\n}\n\nvoid nuiPadGestureRecognizer::UpdateForces(const nuiEvent& rEvent)\n{\n mForce *= mFriction;\n \/\/printf(\"UPD norm: %f - angle: %f\\n\", GetStrength(), GetDegrees());\n \n UpdateDirection();\n}\n\nvoid nuiPadGestureRecognizer::UpdateDirection()\n{\n nuiGestureDirection olddir = mRecognizedDirection;\n if (GetStrength() >= PAD_THRESHOLD)\n {\n \/\/ See where we're going\n mRecognizedDirection = GetDirectionFromAngle(GetDegrees());\n }\n else\n {\n mRecognizedDirection = nuiGestureDirectionNull;\n }\n \n if (olddir != mRecognizedDirection)\n {\n \/\/printf(\"New Pad Direction: %s\\n\", nuiGetString(mRecognizedDirection));\n SignalDirectionChanged(mRecognizedDirection);\n \n }\n}\n\nconst nuiVector& nuiPadGestureRecognizer::GetForce() const\n{\n return mForce;\n}\n\nfloat nuiPadGestureRecognizer::GetStrength() const\n{\n return mForce.Length();\n}\n\nfloat nuiPadGestureRecognizer::GetDegrees() const\n{\n return 360.0 * GetRadians() \/ (2 * M_PI);\n}\n\nfloat nuiPadGestureRecognizer::GetRadians() const\n{\n nuiVector n = mForce;\n n.Normalize();\n \/\/ Get angle:\n double angle = acos(-n[0]);\n if (n[1] < 0)\n angle = 2 * M_PI - angle;\n \n return angle;\n}\n\nfloat nuiPadGestureRecognizer::GetFriction() const\n{\n return mFriction;\n}\n\nvoid nuiPadGestureRecognizer::SetFriction(float set)\n{\n mFriction = set;\n}\n\n\n\/\/ virtual \nbool nuiPadGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)\n{\n bool res = nuiGestureRecognizer::MouseMoved(X, Y);\n \n if (!mClicked)\n return false;\n \n\tdouble diffx = mLastX - X;\n\tdouble diffy = mLastY - Y;\n double currentTime = nglTime();\n nuiVector v(diffx, diffy, 0);\n\n double l = v.Length();\n if (l > PAD_ATTENUATOR_THRESHOLD)\n mForce *= 1.0 \/ l;\n \n mForce += v;\n\n double length = mForce.Length();\n\n nuiVector n = mForce;\n \/\/printf(\"NEW norm: %f - angle: %f\\n\", GetStrength(), GetDegrees());\n \n mLastX = X;\n mLastY = Y;\n \n\n UpdateDirection();\n \n return false;\n}\n\n\nnuiGestureDirection nuiPadGestureRecognizer::GetRecognizedDirection() const\n{\n return mRecognizedDirection;\n}\n\n<commit_msg>removed logs<commit_after>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot & Vincent Caron\n \n licence: see nui3\/LICENCE.TXT\n *\/\n\n\n#pragma once\n#include \"nuiGestureRecognizer.h\"\n\n\n\n\/\/*******************************************************************************************************************\n\/\/*******************************************************************************************************************\n\/\/\n\/\/ class nuiGestureRecognizer\n\/\/\n\n\nnuiGestureRecognizer::nuiGestureRecognizer()\n: nuiSimpleContainer()\n{\n mState = eGestureRecognizerStatePossible;\n}\n\n\nnuiGestureRecognizer::~nuiGestureRecognizer()\n{\n\n}\n\n\nnuiGestureRecognizerState nuiGestureRecognizer::GetState() const\n{\n return mState;\n}\n\nvoid nuiGestureRecognizer::SetState(nuiGestureRecognizerState state)\n{\n mState = state;\n \n \/\/ send synchronous signal\n SignalStateChanged(mState);\n}\n\n \n\n\/\/ virtual \nbool nuiGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n return false;\n}\n\n\n\/\/ virtual \nbool nuiGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n return false;\n}\n\n\n\/\/ virtual \nbool nuiGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)\n{\n return false;\n}\n \n\nconst char* nuiGetString(nuiGestureDirection dir)\n{\n#define F(X) case X: return #X; break;\n switch (dir)\n {\n F(nuiGestureDirectionNull);\n F(nuiGestureDirectionRight);\n F(nuiGestureDirectionLeft);\n F(nuiGestureDirectionUp);\n F(nuiGestureDirectionDown);\n F(nuiGestureDirectionUpRight);\n F(nuiGestureDirectionDownRight);\n F(nuiGestureDirectionDownLeft);\n F(nuiGestureDirectionUpLeft);\n }\n#undef F\n return \"unknown direction\";\n}\n\n\n\n\n\n\n\n\n#define SWIPE_INITIATED_THRESHOLD 9\n#define SWIPE_INITIATED_TIMEOUT 0.10f\n#define SWIPE_ACTIVATED_THRESHOLD 70\n#define SWIPE_ACTIVATED_TIMEOUT 0.15f\n\n\n\/\/************************************************************************************************************\n\/\/************************************************************************************************************\n\/\/\n\/\/ class nuiSwipeGestureRecognizer\n\/\/\n\n\nnuiSwipeGestureRecognizer::nuiSwipeGestureRecognizer(nuiGestureDirection direction)\n: nuiGestureRecognizer()\n{\n mClicked = false;\n mStartX = 0;\n mStartY = 0;\n \n mDirection = direction;\n mRecognizedDirection = nuiGestureDirectionNull;\n}\n\n\n\nnuiSwipeGestureRecognizer::~nuiSwipeGestureRecognizer()\n{\n\n}\n \nvoid nuiSwipeGestureRecognizer::SetDirections(nuiGestureDirection direction)\n{\n mDirection = direction;\n}\n\n\n\/\/ virtual \nbool nuiSwipeGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n bool res = nuiGestureRecognizer::MouseClicked(X, Y, Button);\n \n mRecognizedDirection = nuiGestureDirectionNull;\n \n mClicked = true;\n mTime = nglTime();\n mInitiatedTime = 0;\n mStartX = X;\n mStartY = Y;\n\n Grab();\n return false;\n}\n\n\n\/\/ virtual \nbool nuiSwipeGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n bool res = nuiGestureRecognizer::MouseUnclicked(X, Y, Button);\n \n mClicked = false;\n SetState(eGestureRecognizerStatePossible);\n\n mTime = nglTime();\n mInitiatedTime = 0;\n mStartX = 0;\n mStartY = 0;\n Ungrab();\n \n return false;\n}\n\n\n\/\/ virtual \nbool nuiSwipeGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)\n{\n bool res = nuiGestureRecognizer::MouseMoved(X, Y);\n\n if (!mClicked)\n return false;\n \n if (GetState() == eGestureRecognizerStateEnded)\n return false;\n \n\tdouble diffx = mStartX - X;\n\tdouble diffy = mStartY - Y;\n double currentTime = nglTime();\n \n \/\/ has the swipe gesture been initiated?\n if (GetState() != eGestureRecognizerStateBegan)\n {\n bool initiatedOnX = (abs(diffx) >= SWIPE_INITIATED_THRESHOLD);\n bool initiatedOnY = (abs(diffy) >= SWIPE_INITIATED_THRESHOLD);\n \n \/\/ yes, it's been initiated.\n if (initiatedOnX || initiatedOnY)\n {\n mRecognizedDirection = GetGestureDirection(initiatedOnX, initiatedOnY, mStartX, X, mStartY, Y);\n\n \/\/ is this recognizer in charge of the detected gesture?\n if ((mRecognizedDirection & mDirection) \n && ((currentTime - mTime) < SWIPE_INITIATED_TIMEOUT))\n {\n \/\/ yes. consider that the gesture recognition has began\n mInitiatedTime = currentTime;\n SetState(eGestureRecognizerStateBegan);\n }\n \/\/ no, it's not. set data for the next call\n else\n {\n mStartX = X;\n mStartY = Y;\n mTime = currentTime;\n }\n }\n }\n \n \/\/ not yet. it's a simple \"move\" gesture.\n if (GetState() != eGestureRecognizerStateBegan)\n return false;\n \n \/\/ swipe has been initiated, is the gesture fully completed?\n bool activatedOnX = (abs(diffx) >= SWIPE_ACTIVATED_THRESHOLD);\n bool activatedOnY = (abs(diffy) >= SWIPE_ACTIVATED_THRESHOLD);\n \n if(activatedOnX || activatedOnY)\n\t{\n \/\/ the swipe gesture has been avorted. let's reset the data and start again\n if ((currentTime - mInitiatedTime) > SWIPE_ACTIVATED_TIMEOUT)\n {\n mTime = nglTime();\n mInitiatedTime = 0;\n mStartX = X;\n mStartY = Y;\n SetState(eGestureRecognizerStateFailed);\n mRecognizedDirection = nuiGestureDirectionNull;\n \n return false;\n }\n \n \/\/ ok! the swipe gesture has been completed!\n\t\tSetState(eGestureRecognizerStateEnded);\n \n \/\/ let's assume it's no use to compute mDirection here, since it's been done when the swipe gesture has been initiated.\n \/\/ we'll see in the future if it's wrong to make that assumption.\n \/\/ mDirection = GetGesturePosition(activatedOnX, activatedOnY, mStartX, X, mStartY, Y);\n \n \/\/ send synchronous event\n SignalSwipe(mRecognizedDirection);\n\t}\n \n return false;\n}\n\n\nnuiGestureDirection nuiSwipeGestureRecognizer::GetRecognizedDirection() const\n{\n return mRecognizedDirection;\n}\n\n\nnuiGestureDirection nuiSwipeGestureRecognizer::GetGestureDirection(bool evalOnX, bool evalOnY, nuiSize x1, nuiSize x2, nuiSize y1, nuiSize y2) const\n{\n \/\/ diagonal gesture?\n if (evalOnX && evalOnY)\n {\n if (x1 < x2) \n {\n if (y1 < y2)\n return nuiGestureDirectionDownRight;\n else\n return nuiGestureDirectionUpRight;\n }\n else \n {\n if (y1 < y2)\n return nuiGestureDirectionDownLeft;\n else\n return nuiGestureDirectionUpLeft;\n }\n }\n \/\/ horizontal gesture?\n else if (evalOnX)\n {\n if (x1 < x2) \n return nuiGestureDirectionRight;\n else\n return nuiGestureDirectionLeft;\n }\n \/\/ vertical gesture?\n else if (evalOnY)\n {\n if (y1 < y2) \n return nuiGestureDirectionDown;\n else\n return nuiGestureDirectionUp;\n }\n \n return nuiGestureDirectionNull;\n}\n\n\n\n#define PAD_INITIATED_THRESHOLD 9\n#define PAD_INITIATED_TIMEOUT 0.10f\n#define PAD_ACTIVATED_THRESHOLD 70\n#define PAD_ACTIVATED_TIMEOUT 0.15f\n#define PAD_FRICTION 0.9f\n#define PAD_ATTENUATOR_THRESHOLD 4.0f\n#define PAD_THRESHOLD 4.0f\n\n\n\/\/************************************************************************************************************\n\/\/************************************************************************************************************\n\/\/\n\/\/ class nuiPadGestureRecognizer\n\/\/\n\n\nnuiPadGestureRecognizer::nuiPadGestureRecognizer(nuiGestureDirection direction)\n: nuiGestureRecognizer(), mSink(this)\n{\n mClicked = false;\n mLastX = 0;\n mLastY = 0;\n mFriction = 0.1;\n \n SetDirections(direction);\n mRecognizedDirection = nuiGestureDirectionNull;\n \n nuiTimer* pTimer = nuiAnimation::AcquireTimer();\n mSink.Connect(pTimer->Tick, &nuiPadGestureRecognizer::UpdateForces);\n}\n\n\n\nnuiPadGestureRecognizer::~nuiPadGestureRecognizer()\n{\n \n}\n\nvoid nuiPadGestureRecognizer::SetDirections(nuiGestureDirection direction)\n{\n mDirection = direction;\n\n#define F(X) (std::pair<float, float>(X - 22.5, X + 22.5))\n \n mDirections[nuiGestureDirectionRight] = F(0);\n mDirections[nuiGestureDirectionUpRight] = F(45);\n mDirections[nuiGestureDirectionUp] = F(90);\n mDirections[nuiGestureDirectionUpLeft] = F(135);\n mDirections[nuiGestureDirectionLeft] = F(180);\n mDirections[nuiGestureDirectionDownLeft] = F(225);\n mDirections[nuiGestureDirectionDown] = F(270);\n mDirections[nuiGestureDirectionDownRight] = F(315);\n \n#undef X\n}\n\nnuiGestureDirection nuiPadGestureRecognizer::GetDirectionFromAngle(float angle) const\n{\n std::map<nuiGestureDirection, std::pair<float, float> >::const_iterator it = mDirections.begin();\n\n if (angle > 360 - 22.5)\n angle = angle - 360;\n \n while (it != mDirections.end())\n {\n if (it->second.first < angle && it->second.second >= angle)\n return it->first;\n \n ++it;\n }\n \n return nuiGestureDirectionNull;\n}\n\n\n\/\/ virtual \nbool nuiPadGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n bool res = nuiGestureRecognizer::MouseClicked(X, Y, Button);\n \n mRecognizedDirection = nuiGestureDirectionNull;\n \n mClicked = true;\n mLastX = X;\n mLastY = Y;\n \n Grab();\n return false;\n}\n\n\n\/\/ virtual \nbool nuiPadGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)\n{\n bool res = nuiGestureRecognizer::MouseUnclicked(X, Y, Button);\n \n mClicked = false;\n SetState(eGestureRecognizerStatePossible);\n \n mLastX = 0;\n mLastY = 0;\n\n Ungrab();\n return false;\n}\n\nvoid nuiPadGestureRecognizer::UpdateForces(const nuiEvent& rEvent)\n{\n mForce *= mFriction;\n \/\/printf(\"UPD norm: %f - angle: %f\\n\", GetStrength(), GetDegrees());\n \n UpdateDirection();\n}\n\nvoid nuiPadGestureRecognizer::UpdateDirection()\n{\n nuiGestureDirection olddir = mRecognizedDirection;\n if (GetStrength() >= PAD_THRESHOLD)\n {\n \/\/ See where we're going\n mRecognizedDirection = GetDirectionFromAngle(GetDegrees());\n }\n else\n {\n mRecognizedDirection = nuiGestureDirectionNull;\n }\n \n if (olddir != mRecognizedDirection)\n {\n \/\/printf(\"New Pad Direction: %s\\n\", nuiGetString(mRecognizedDirection));\n SignalDirectionChanged(mRecognizedDirection);\n \n }\n}\n\nconst nuiVector& nuiPadGestureRecognizer::GetForce() const\n{\n return mForce;\n}\n\nfloat nuiPadGestureRecognizer::GetStrength() const\n{\n return mForce.Length();\n}\n\nfloat nuiPadGestureRecognizer::GetDegrees() const\n{\n return 360.0 * GetRadians() \/ (2 * M_PI);\n}\n\nfloat nuiPadGestureRecognizer::GetRadians() const\n{\n nuiVector n = mForce;\n n.Normalize();\n \/\/ Get angle:\n double angle = acos(-n[0]);\n if (n[1] < 0)\n angle = 2 * M_PI - angle;\n \n return angle;\n}\n\nfloat nuiPadGestureRecognizer::GetFriction() const\n{\n return mFriction;\n}\n\nvoid nuiPadGestureRecognizer::SetFriction(float set)\n{\n mFriction = set;\n}\n\n\n\/\/ virtual \nbool nuiPadGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)\n{\n bool res = nuiGestureRecognizer::MouseMoved(X, Y);\n \n if (!mClicked)\n return false;\n \n\tdouble diffx = mLastX - X;\n\tdouble diffy = mLastY - Y;\n double currentTime = nglTime();\n nuiVector v(diffx, diffy, 0);\n\n double l = v.Length();\n if (l > PAD_ATTENUATOR_THRESHOLD)\n mForce *= 1.0 \/ l;\n \n mForce += v;\n\n double length = mForce.Length();\n\n nuiVector n = mForce;\n \/\/printf(\"NEW norm: %f - angle: %f\\n\", GetStrength(), GetDegrees());\n \n mLastX = X;\n mLastY = Y;\n \n\n UpdateDirection();\n \n return false;\n}\n\n\nnuiGestureDirection nuiPadGestureRecognizer::GetRecognizedDirection() const\n{\n return mRecognizedDirection;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include \"storage\/DevicegraphImpl.h\"\n#include \"storage\/Environment.h\"\n#include \"storage\/Storage.h\"\n#include \"storage\/Action.h\"\n#include \"storage\/Devices\/DeviceImpl.h\"\n#include \"storage\/Devices\/BlkDevice.h\"\n#include \"storage\/Devices\/Partitionable.h\"\n#include \"storage\/Devices\/PartitionTable.h\"\n#include \"storage\/Devices\/LvmVgImpl.h\"\n#include \"storage\/Devices\/LvmPvImpl.h\"\n#include \"storage\/Devices\/BcacheCsetImpl.h\"\n#include \"storage\/Filesystems\/BlkFilesystem.h\"\n#include \"storage\/Filesystems\/Btrfs.h\"\n#include \"storage\/Filesystems\/BtrfsSubvolume.h\"\n#include \"storage\/Filesystems\/MountPoint.h\"\n#include \"testsuite\/helpers\/TsCmp.h\"\n\n\nusing namespace std;\n\n\nnamespace storage\n{\n\n std::ostream&\n operator<<(std::ostream& out, const TsCmp& ts_cmp)\n {\n\tout << endl;\n\n\tfor (const string& error : ts_cmp.errors)\n\t out << error << endl;\n\n\treturn out;\n }\n\n\n TsCmpDevicegraph::TsCmpDevicegraph(const Devicegraph& lhs, Devicegraph& rhs)\n {\n\tadjust_sids(lhs, rhs);\n\n\tif (lhs != rhs)\n\t{\n\t ostringstream tmp1;\n\t lhs.get_impl().log_diff(tmp1, rhs.get_impl());\n\t string tmp2 = tmp1.str();\n\t boost::split(errors, tmp2, boost::is_any_of(\"\\n\"), boost::token_compress_on);\n\t}\n }\n\n\n \/**\n * This function adjusts the sids which is needed when devices are the\n * detected in a differnet order than expected. Block devices use the name\n * for identification, most others a uuid or a path. Some types are not\n * handled at all, e.g. Nfs.\n *\n * The function makes assumptions that break in the general case and does\n * no error checking. It can even ruin the devicegraph.\n *\n * Only enable it when you know what you are doing!\n *\/\n void\n TsCmpDevicegraph::adjust_sids(const Devicegraph& lhs, Devicegraph& rhs) const\n {\n#if 0\n\n\tfor (Device* device_rhs : Device::get_all(&rhs))\n\t{\n\t \/\/ BlkDevices\n\n\t if (is_blk_device(device_rhs))\n\t {\n\t\tBlkDevice* blk_device_rhs = to_blk_device(device_rhs);\n\t\tconst BlkDevice* blk_device_lhs = BlkDevice::find_by_name(&lhs, blk_device_rhs->get_name());\n\n\t\tadjust_sid(blk_device_lhs, blk_device_rhs);\n\n\t\t\/\/ PartitionTables\n\n\t\tif (is_partitionable(blk_device_lhs) && is_partitionable(blk_device_rhs))\n\t\t{\n\t\t const Partitionable* partitionable_lhs = to_partitionable(blk_device_lhs);\n\t\t Partitionable* partitionable_rhs = to_partitionable(blk_device_rhs);\n\n\t\t if (partitionable_lhs->has_partition_table() && partitionable_rhs->has_partition_table())\n\t\t\tadjust_sid(partitionable_lhs->get_partition_table(), partitionable_rhs->get_partition_table());\n\t\t}\n\t }\n\n\t \/\/ LvmVgs\n\n\t if (is_lvm_vg(device_rhs))\n\t {\n\t\tLvmVg* lvm_vg_rhs = to_lvm_vg(device_rhs);\n\t\tconst LvmVg* lvm_vg_lhs = LvmVg::Impl::find_by_uuid(&lhs, lvm_vg_rhs->get_impl().get_uuid());\n\n\t\tadjust_sid(lvm_vg_lhs, lvm_vg_rhs);\n\t }\n\n\t \/\/ LvmPvs\n\n\t if (is_lvm_pv(device_rhs))\n\t {\n\t\tLvmPv* lvm_pv_rhs = to_lvm_pv(device_rhs);\n\t\tconst LvmPv* lvm_pv_lhs = LvmPv::Impl::find_by_uuid(&lhs, lvm_pv_rhs->get_impl().get_uuid());\n\n\t\tadjust_sid(lvm_pv_lhs, lvm_pv_rhs);\n\t }\n\n\t \/\/ BcacheCset\n\n\t if (is_bcache_cset(device_rhs))\n\t {\n\t\tBcacheCset* bcache_cset_rhs = to_bcache_cset(device_rhs);\n\t\tconst BcacheCset* bcache_cset_lhs = BcacheCset::Impl::find_by_uuid(&lhs, bcache_cset_rhs->get_uuid());\n\n\t\tadjust_sid(bcache_cset_lhs, bcache_cset_rhs);\n\t }\n\n\t \/\/ BlkFilesystems\n\n\t if (is_blk_filesystem(device_rhs))\n\t {\n\t\tBlkFilesystem* blk_filesystem_rhs = to_blk_filesystem(device_rhs);\n\t\tconst BlkFilesystem* blk_filesystem_lhs = BlkFilesystem::find_by_uuid(&lhs, blk_filesystem_rhs->get_uuid()).front();\n\n\t\tadjust_sid(blk_filesystem_lhs, blk_filesystem_rhs);\n\n\t\t\/\/ BtrfsSubvolumes\n\n\t\tif (is_btrfs(blk_filesystem_lhs) && is_btrfs(blk_filesystem_rhs))\n\t\t{\n\t\t const Btrfs* btrfs_lhs = to_btrfs(blk_filesystem_lhs);\n\t\t Btrfs* btrfs_rhs = to_btrfs(blk_filesystem_rhs);\n\n\t\t for (BtrfsSubvolume* btrfs_subvolume_rhs : btrfs_rhs->get_btrfs_subvolumes())\n\t\t {\n\t\t\tconst BtrfsSubvolume* btrfs_subvolume_lhs = btrfs_lhs->find_btrfs_subvolume_by_path(btrfs_subvolume_rhs->get_path());\n\t\t\tadjust_sid(btrfs_subvolume_lhs, btrfs_subvolume_rhs);\n\t\t }\n\t\t}\n\t }\n\n\t \/\/ MountPoints\n\n\t if (is_mount_point(device_rhs))\n {\n MountPoint* mount_point_rhs = to_mount_point(device_rhs);\n const MountPoint* mount_point_lhs = MountPoint::find_by_path(&lhs, mount_point_rhs->get_path()).front();\n\n\t\tadjust_sid(mount_point_lhs, mount_point_rhs);\n }\n\t}\n\n#endif\n }\n\n\n void\n TsCmpDevicegraph::adjust_sid(const Device* lhs, Device* rhs) const\n {\n\tif (lhs->get_sid() != rhs->get_sid())\n\t{\n\t cout << \"adjust sid \" << rhs->get_impl().get_classname() << \" (\"\n\t\t << rhs->get_displayname() << \") \" << rhs->get_sid() << \" -> \"\n\t\t << lhs->get_sid() << endl;\n\n\t rhs->get_impl().set_sid(lhs->get_sid());\n\t}\n }\n\n\n TsCmpActiongraph::Expected::Expected(const string& filename)\n {\n\tstd::ifstream fin(filename);\n\tif (!fin)\n\t ST_THROW(Exception(\"failed to load \" + filename));\n\n\tstring line;\n\twhile (getline(fin, line))\n\t{\n\t if (!line.empty() && !boost::starts_with(line, \"#\"))\n\t\tlines.push_back(line);\n\t}\n }\n\n\n TsCmpActiongraph::TsCmpActiongraph(const string& name)\n {\n\tEnvironment environment(true, ProbeMode::READ_DEVICEGRAPH, TargetMode::DIRECT);\n\tenvironment.set_devicegraph_filename(name + \"-probed.xml\");\n\n\tStorage storage(environment);\n\tstorage.probe();\n\tstorage.get_staging()->load(name + \"-staging.xml\");\n\n\tActiongraph actiongraph(storage, storage.get_system(), storage.get_staging());\n\n\tif (access(\"\/usr\/bin\/dot\", X_OK) == 0)\n\t{\n\t storage.get_probed()->write_graphviz(name + \"-probed.gv\", GraphvizFlags::SID);\n\t system((\"dot -Tsvg < \" + name + \"-probed.gv > \" + name + \"-probed.svg\").c_str());\n\n\t storage.get_staging()->write_graphviz(name + \"-staging.gv\", GraphvizFlags::SID);\n\t system((\"dot -Tsvg < \" + name + \"-staging.gv > \" + name + \"-staging.svg\").c_str());\n\n\t actiongraph.write_graphviz(name + \"-action.gv\", GraphvizFlags::SID);\n\t system((\"dot -Tsvg < \" + name + \"-action.gv > \" + name + \"-action.svg\").c_str());\n\t}\n\n\tTsCmpActiongraph::Expected expected(name + \"-expected.txt\");\n\n\tconst CommitData commit_data(actiongraph.get_impl(), Tense::SIMPLE_PRESENT);\n\n\tcmp(commit_data, expected);\n }\n\n\n TsCmpActiongraph::TsCmpActiongraph(const Actiongraph& actiongraph, const Expected& expected)\n {\n\tconst CommitData commit_data(actiongraph.get_impl(), Tense::SIMPLE_PRESENT);\n\n\tcmp(commit_data, expected);\n }\n\n\n void\n TsCmpActiongraph::cmp(const CommitData& commit_data, const Expected& expected)\n {\n\tfor (const string& line : expected.lines)\n\t entries.push_back(Entry(line));\n\n\tcheck();\n\n\tcmp_texts(commit_data);\n\n\tif (!ok())\n\t return;\n\n\tcmp_dependencies(commit_data);\n }\n\n\n TsCmpActiongraph::Entry::Entry(const string& line)\n {\n\tstring::size_type pos1 = line.find('-');\n\tif (pos1 == string::npos)\n\t ST_THROW(Exception(\"parse error, did not find '-'\"));\n\n\tstring::size_type pos2 = line.rfind(\"->\");\n\tif (pos2 == string::npos)\n\t ST_THROW(Exception(\"parse error, did not find '->'\"));\n\n\tid = boost::trim_copy(line.substr(0, pos1), locale::classic());\n\ttext = boost::trim_copy(line.substr(pos1 + 1, pos2 - pos1 - 1), locale::classic());\n\n\tstring tmp = boost::trim_copy(line.substr(pos2 + 2), locale::classic());\n\tif (!tmp.empty())\n\t boost::split(dep_ids, tmp, boost::is_any_of(\" \"), boost::token_compress_on);\n }\n\n\n void\n TsCmpActiongraph::check() const\n {\n\tset<string> ids;\n\tset<string> texts;\n\n\tfor (const Entry& entry : entries)\n\t{\n\t if (!ids.insert(entry.id).second)\n\t\tST_THROW(Exception(\"duplicate id\"));\n\n\t if (!texts.insert(entry.text).second)\n\t\tST_THROW(Exception(\"duplicate text\"));\n\t}\n\n\tfor (const Entry& entry : entries)\n\t{\n\t for (const string dep_id : entry.dep_ids)\n\t {\n\t\tif (ids.find(dep_id) == ids.end())\n\t\t ST_THROW(Exception(\"unknown dependency-id\"));\n\t }\n\t}\n }\n\n\n string\n TsCmpActiongraph::text(const CommitData& commit_data, Actiongraph::Impl::vertex_descriptor vertex) const\n {\n\tconst Action::Base* action = commit_data.actiongraph[vertex];\n\n\tstring text = action->text(commit_data).native;\n\n\tif (action->nop)\n\t text += \" [nop]\";\n\n\treturn text;\n }\n\n\n void\n TsCmpActiongraph::cmp_texts(const CommitData& commit_data)\n {\n\tset<string> tmp1;\n\tfor (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())\n\t tmp1.insert(text(commit_data, vertex));\n\n\tset<string> tmp2;\n\tfor (const Entry& entry : entries)\n\t tmp2.insert(entry.text);\n\n\tif (tmp1 != tmp2)\n\t{\n\t errors.push_back(\"action texts differ\");\n\n\t vector<string> diff1;\n\t set_difference(tmp2.begin(), tmp2.end(), tmp1.begin(), tmp1.end(), back_inserter(diff1));\n\t for (const string& error : diff1)\n\t\terrors.push_back(\"- \" + error);\n\n\t vector<string> diff2;\n\t set_difference(tmp1.begin(), tmp1.end(), tmp2.begin(), tmp2.end(), back_inserter(diff2));\n\t for (const string& error : diff2)\n\t\terrors.push_back(\"+ \" + error);\n\t}\n }\n\n\n void\n TsCmpActiongraph::cmp_dependencies(const CommitData& commit_data)\n {\n\tmap<string, string> text_to_id;\n\tfor (const Entry& entry : entries)\n\t text_to_id[entry.text] = entry.id;\n\n\tmap<string, Actiongraph::Impl::vertex_descriptor> text_to_vertex;\n\tfor (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())\n\t text_to_vertex[text(commit_data, vertex)] = vertex;\n\n\tfor (const Entry& entry : entries)\n\t{\n\t Actiongraph::Impl::vertex_descriptor vertex = text_to_vertex[entry.text];\n\n\t set<string> tmp;\n\t for (Actiongraph::Impl::vertex_descriptor child : commit_data.actiongraph.children(vertex))\n\t\ttmp.insert(text_to_id[text(commit_data, child)]);\n\n\t if (tmp != entry.dep_ids)\n\t {\n\t\terrors.push_back(\"wrong dependencies for '\" + entry.text + \"'\");\n\t\terrors.push_back(\"- \" + boost::join(tmp, \" \"));\n\t\terrors.push_back(\"+ \" + boost::join(entry.dep_ids, \" \"));\n\t }\n\t}\n }\n\n}\n<commit_msg>- generate dot files with more information<commit_after>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include \"storage\/DevicegraphImpl.h\"\n#include \"storage\/Environment.h\"\n#include \"storage\/Storage.h\"\n#include \"storage\/Action.h\"\n#include \"storage\/Devices\/DeviceImpl.h\"\n#include \"storage\/Devices\/BlkDevice.h\"\n#include \"storage\/Devices\/Partitionable.h\"\n#include \"storage\/Devices\/PartitionTable.h\"\n#include \"storage\/Devices\/LvmVgImpl.h\"\n#include \"storage\/Devices\/LvmPvImpl.h\"\n#include \"storage\/Devices\/BcacheCsetImpl.h\"\n#include \"storage\/Filesystems\/BlkFilesystem.h\"\n#include \"storage\/Filesystems\/Btrfs.h\"\n#include \"storage\/Filesystems\/BtrfsSubvolume.h\"\n#include \"storage\/Filesystems\/MountPoint.h\"\n#include \"testsuite\/helpers\/TsCmp.h\"\n\n\nusing namespace std;\n\n\nnamespace storage\n{\n\n std::ostream&\n operator<<(std::ostream& out, const TsCmp& ts_cmp)\n {\n\tout << endl;\n\n\tfor (const string& error : ts_cmp.errors)\n\t out << error << endl;\n\n\treturn out;\n }\n\n\n TsCmpDevicegraph::TsCmpDevicegraph(const Devicegraph& lhs, Devicegraph& rhs)\n {\n\tadjust_sids(lhs, rhs);\n\n\tif (lhs != rhs)\n\t{\n\t ostringstream tmp1;\n\t lhs.get_impl().log_diff(tmp1, rhs.get_impl());\n\t string tmp2 = tmp1.str();\n\t boost::split(errors, tmp2, boost::is_any_of(\"\\n\"), boost::token_compress_on);\n\t}\n }\n\n\n \/**\n * This function adjusts the sids which is needed when devices are the\n * detected in a differnet order than expected. Block devices use the name\n * for identification, most others a uuid or a path. Some types are not\n * handled at all, e.g. Nfs.\n *\n * The function makes assumptions that break in the general case and does\n * no error checking. It can even ruin the devicegraph.\n *\n * Only enable it when you know what you are doing!\n *\/\n void\n TsCmpDevicegraph::adjust_sids(const Devicegraph& lhs, Devicegraph& rhs) const\n {\n#if 0\n\n\tfor (Device* device_rhs : Device::get_all(&rhs))\n\t{\n\t \/\/ BlkDevices\n\n\t if (is_blk_device(device_rhs))\n\t {\n\t\tBlkDevice* blk_device_rhs = to_blk_device(device_rhs);\n\t\tconst BlkDevice* blk_device_lhs = BlkDevice::find_by_name(&lhs, blk_device_rhs->get_name());\n\n\t\tadjust_sid(blk_device_lhs, blk_device_rhs);\n\n\t\t\/\/ PartitionTables\n\n\t\tif (is_partitionable(blk_device_lhs) && is_partitionable(blk_device_rhs))\n\t\t{\n\t\t const Partitionable* partitionable_lhs = to_partitionable(blk_device_lhs);\n\t\t Partitionable* partitionable_rhs = to_partitionable(blk_device_rhs);\n\n\t\t if (partitionable_lhs->has_partition_table() && partitionable_rhs->has_partition_table())\n\t\t\tadjust_sid(partitionable_lhs->get_partition_table(), partitionable_rhs->get_partition_table());\n\t\t}\n\t }\n\n\t \/\/ LvmVgs\n\n\t if (is_lvm_vg(device_rhs))\n\t {\n\t\tLvmVg* lvm_vg_rhs = to_lvm_vg(device_rhs);\n\t\tconst LvmVg* lvm_vg_lhs = LvmVg::Impl::find_by_uuid(&lhs, lvm_vg_rhs->get_impl().get_uuid());\n\n\t\tadjust_sid(lvm_vg_lhs, lvm_vg_rhs);\n\t }\n\n\t \/\/ LvmPvs\n\n\t if (is_lvm_pv(device_rhs))\n\t {\n\t\tLvmPv* lvm_pv_rhs = to_lvm_pv(device_rhs);\n\t\tconst LvmPv* lvm_pv_lhs = LvmPv::Impl::find_by_uuid(&lhs, lvm_pv_rhs->get_impl().get_uuid());\n\n\t\tadjust_sid(lvm_pv_lhs, lvm_pv_rhs);\n\t }\n\n\t \/\/ BcacheCset\n\n\t if (is_bcache_cset(device_rhs))\n\t {\n\t\tBcacheCset* bcache_cset_rhs = to_bcache_cset(device_rhs);\n\t\tconst BcacheCset* bcache_cset_lhs = BcacheCset::Impl::find_by_uuid(&lhs, bcache_cset_rhs->get_uuid());\n\n\t\tadjust_sid(bcache_cset_lhs, bcache_cset_rhs);\n\t }\n\n\t \/\/ BlkFilesystems\n\n\t if (is_blk_filesystem(device_rhs))\n\t {\n\t\tBlkFilesystem* blk_filesystem_rhs = to_blk_filesystem(device_rhs);\n\t\tconst BlkFilesystem* blk_filesystem_lhs = BlkFilesystem::find_by_uuid(&lhs, blk_filesystem_rhs->get_uuid()).front();\n\n\t\tadjust_sid(blk_filesystem_lhs, blk_filesystem_rhs);\n\n\t\t\/\/ BtrfsSubvolumes\n\n\t\tif (is_btrfs(blk_filesystem_lhs) && is_btrfs(blk_filesystem_rhs))\n\t\t{\n\t\t const Btrfs* btrfs_lhs = to_btrfs(blk_filesystem_lhs);\n\t\t Btrfs* btrfs_rhs = to_btrfs(blk_filesystem_rhs);\n\n\t\t for (BtrfsSubvolume* btrfs_subvolume_rhs : btrfs_rhs->get_btrfs_subvolumes())\n\t\t {\n\t\t\tconst BtrfsSubvolume* btrfs_subvolume_lhs = btrfs_lhs->find_btrfs_subvolume_by_path(btrfs_subvolume_rhs->get_path());\n\t\t\tadjust_sid(btrfs_subvolume_lhs, btrfs_subvolume_rhs);\n\t\t }\n\t\t}\n\t }\n\n\t \/\/ MountPoints\n\n\t if (is_mount_point(device_rhs))\n {\n MountPoint* mount_point_rhs = to_mount_point(device_rhs);\n const MountPoint* mount_point_lhs = MountPoint::find_by_path(&lhs, mount_point_rhs->get_path()).front();\n\n\t\tadjust_sid(mount_point_lhs, mount_point_rhs);\n }\n\t}\n\n#endif\n }\n\n\n void\n TsCmpDevicegraph::adjust_sid(const Device* lhs, Device* rhs) const\n {\n\tif (lhs->get_sid() != rhs->get_sid())\n\t{\n\t cout << \"adjust sid \" << rhs->get_impl().get_classname() << \" (\"\n\t\t << rhs->get_displayname() << \") \" << rhs->get_sid() << \" -> \"\n\t\t << lhs->get_sid() << endl;\n\n\t rhs->get_impl().set_sid(lhs->get_sid());\n\t}\n }\n\n\n TsCmpActiongraph::Expected::Expected(const string& filename)\n {\n\tstd::ifstream fin(filename);\n\tif (!fin)\n\t ST_THROW(Exception(\"failed to load \" + filename));\n\n\tstring line;\n\twhile (getline(fin, line))\n\t{\n\t if (!line.empty() && !boost::starts_with(line, \"#\"))\n\t\tlines.push_back(line);\n\t}\n }\n\n\n TsCmpActiongraph::TsCmpActiongraph(const string& name)\n {\n\tEnvironment environment(true, ProbeMode::READ_DEVICEGRAPH, TargetMode::DIRECT);\n\tenvironment.set_devicegraph_filename(name + \"-probed.xml\");\n\n\tStorage storage(environment);\n\tstorage.probe();\n\tstorage.get_staging()->load(name + \"-staging.xml\");\n\n\tActiongraph actiongraph(storage, storage.get_system(), storage.get_staging());\n\n\tif (access(\"\/usr\/bin\/dot\", X_OK) == 0)\n\t{\n\t storage.get_probed()->write_graphviz(name + \"-probed.gv\", GraphvizFlags::CLASSNAME |\n\t\t\t\t\t\t GraphvizFlags::NAME | GraphvizFlags::SID |\n\t\t\t\t\t\t GraphvizFlags::SIZE);\n\t system((\"dot -Tsvg < \" + name + \"-probed.gv > \" + name + \"-probed.svg\").c_str());\n\n\t storage.get_staging()->write_graphviz(name + \"-staging.gv\", GraphvizFlags::CLASSNAME |\n\t\t\t\t\t\t GraphvizFlags::NAME | GraphvizFlags::SID |\n\t\t\t\t\t\t GraphvizFlags::SIZE);\n\t system((\"dot -Tsvg < \" + name + \"-staging.gv > \" + name + \"-staging.svg\").c_str());\n\n\t actiongraph.write_graphviz(name + \"-action.gv\", GraphvizFlags::SID | GraphvizFlags::NAME);\n\t system((\"dot -Tsvg < \" + name + \"-action.gv > \" + name + \"-action.svg\").c_str());\n\t}\n\n\tTsCmpActiongraph::Expected expected(name + \"-expected.txt\");\n\n\tconst CommitData commit_data(actiongraph.get_impl(), Tense::SIMPLE_PRESENT);\n\n\tcmp(commit_data, expected);\n }\n\n\n TsCmpActiongraph::TsCmpActiongraph(const Actiongraph& actiongraph, const Expected& expected)\n {\n\tconst CommitData commit_data(actiongraph.get_impl(), Tense::SIMPLE_PRESENT);\n\n\tcmp(commit_data, expected);\n }\n\n\n void\n TsCmpActiongraph::cmp(const CommitData& commit_data, const Expected& expected)\n {\n\tfor (const string& line : expected.lines)\n\t entries.push_back(Entry(line));\n\n\tcheck();\n\n\tcmp_texts(commit_data);\n\n\tif (!ok())\n\t return;\n\n\tcmp_dependencies(commit_data);\n }\n\n\n TsCmpActiongraph::Entry::Entry(const string& line)\n {\n\tstring::size_type pos1 = line.find('-');\n\tif (pos1 == string::npos)\n\t ST_THROW(Exception(\"parse error, did not find '-'\"));\n\n\tstring::size_type pos2 = line.rfind(\"->\");\n\tif (pos2 == string::npos)\n\t ST_THROW(Exception(\"parse error, did not find '->'\"));\n\n\tid = boost::trim_copy(line.substr(0, pos1), locale::classic());\n\ttext = boost::trim_copy(line.substr(pos1 + 1, pos2 - pos1 - 1), locale::classic());\n\n\tstring tmp = boost::trim_copy(line.substr(pos2 + 2), locale::classic());\n\tif (!tmp.empty())\n\t boost::split(dep_ids, tmp, boost::is_any_of(\" \"), boost::token_compress_on);\n }\n\n\n void\n TsCmpActiongraph::check() const\n {\n\tset<string> ids;\n\tset<string> texts;\n\n\tfor (const Entry& entry : entries)\n\t{\n\t if (!ids.insert(entry.id).second)\n\t\tST_THROW(Exception(\"duplicate id\"));\n\n\t if (!texts.insert(entry.text).second)\n\t\tST_THROW(Exception(\"duplicate text\"));\n\t}\n\n\tfor (const Entry& entry : entries)\n\t{\n\t for (const string dep_id : entry.dep_ids)\n\t {\n\t\tif (ids.find(dep_id) == ids.end())\n\t\t ST_THROW(Exception(\"unknown dependency-id\"));\n\t }\n\t}\n }\n\n\n string\n TsCmpActiongraph::text(const CommitData& commit_data, Actiongraph::Impl::vertex_descriptor vertex) const\n {\n\tconst Action::Base* action = commit_data.actiongraph[vertex];\n\n\tstring text = action->text(commit_data).native;\n\n\tif (action->nop)\n\t text += \" [nop]\";\n\n\treturn text;\n }\n\n\n void\n TsCmpActiongraph::cmp_texts(const CommitData& commit_data)\n {\n\tset<string> tmp1;\n\tfor (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())\n\t tmp1.insert(text(commit_data, vertex));\n\n\tset<string> tmp2;\n\tfor (const Entry& entry : entries)\n\t tmp2.insert(entry.text);\n\n\tif (tmp1 != tmp2)\n\t{\n\t errors.push_back(\"action texts differ\");\n\n\t vector<string> diff1;\n\t set_difference(tmp2.begin(), tmp2.end(), tmp1.begin(), tmp1.end(), back_inserter(diff1));\n\t for (const string& error : diff1)\n\t\terrors.push_back(\"- \" + error);\n\n\t vector<string> diff2;\n\t set_difference(tmp1.begin(), tmp1.end(), tmp2.begin(), tmp2.end(), back_inserter(diff2));\n\t for (const string& error : diff2)\n\t\terrors.push_back(\"+ \" + error);\n\t}\n }\n\n\n void\n TsCmpActiongraph::cmp_dependencies(const CommitData& commit_data)\n {\n\tmap<string, string> text_to_id;\n\tfor (const Entry& entry : entries)\n\t text_to_id[entry.text] = entry.id;\n\n\tmap<string, Actiongraph::Impl::vertex_descriptor> text_to_vertex;\n\tfor (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())\n\t text_to_vertex[text(commit_data, vertex)] = vertex;\n\n\tfor (const Entry& entry : entries)\n\t{\n\t Actiongraph::Impl::vertex_descriptor vertex = text_to_vertex[entry.text];\n\n\t set<string> tmp;\n\t for (Actiongraph::Impl::vertex_descriptor child : commit_data.actiongraph.children(vertex))\n\t\ttmp.insert(text_to_id[text(commit_data, child)]);\n\n\t if (tmp != entry.dep_ids)\n\t {\n\t\terrors.push_back(\"wrong dependencies for '\" + entry.text + \"'\");\n\t\terrors.push_back(\"- \" + boost::join(tmp, \" \"));\n\t\terrors.push_back(\"+ \" + boost::join(entry.dep_ids, \" \"));\n\t }\n\t}\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (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***********************************************************************************************************************\/\n\n\/***********************************************************************************************************************\n * PositionLayout.cpp\n *\n * Created on: Feb 2, 2011\n * Author: Dimitar Asenov\n **********************************************************************************************************************\/\n\n#include \"layouts\/PositionLayout.h\"\n#include \"shapes\/Shape.h\"\n#include \"..\/renderer\/ModelRenderer.h\"\n\n#include \"ModelBase\/src\/model\/Model.h\"\n\nnamespace Visualization {\n\nITEM_COMMON_DEFINITIONS( PositionLayout, \"layout\" )\n\nPositionLayout::PositionLayout(Item* parent, const StyleType* style) :\n\tLayout(parent, style)\n{\n}\n\nPositionLayout::~PositionLayout()\n{\n\tfor (int i = 0; i<items.size(); i++) SAFE_DELETE_ITEM( items[i]);\n}\n\nint PositionLayout::length() const\n{\n\treturn items.size();\n}\n\nbool PositionLayout::containsNode(Model::Node* node_)\n{\n\tfor(int i=0; i<items.size(); ++i)\n\t\tif (items[i]->node() == node_) return true;\n\n\treturn false;\n}\n\nvoid PositionLayout::insert(Item* item)\n{\n\t\/\/ Check whether this item has a node and a position associated with it\n\tif ( !item->hasNode() ) throw VisualizationException(\"Adding an Item that has no node to a PositionLayout\");\n\n\tModel::ExtendableNode* extNode = dynamic_cast<Model::ExtendableNode*> (item->node());\n\tif (!extNode)\n\t\tthrow VisualizationException(\"Adding an Item that does not implement ExtendableNode to a PositionLayout\");\n\n\tPosition* pos = extNode->extension<Position>();\n\n\tif (!pos)\n\t\tthrow VisualizationException(\"Adding a Item whose node does not have a Position extension to a PositionLayout\");\n\n\titem->setParentItem(this);\n\titems.append(item);\n\tpositions.append(pos);\n\tsetUpdateNeeded(StandardUpdate);\n}\n\nvoid PositionLayout::remove(int index, bool deleteItem)\n{\n\tif (deleteItem) SAFE_DELETE_ITEM( items[index]);\n\telse if(items[index]) items[index]->setParentItem(nullptr);\n\n\tSAFE_DELETE( positions[index] );\n\titems.remove(index);\n\tpositions.remove(index);\n\tsetUpdateNeeded(StandardUpdate);\n}\n\nvoid PositionLayout::removeAll(Item* item, bool deleteItem)\n{\n\tfor (int i = items.size() - 1; i>=0; --i)\n\t{\n\t\tif (items.at(i) == item)\n\t\t{\n\t\t\titems.remove(i);\n\t\t\tSAFE_DELETE( positions[i] );\n\t\t\tpositions.remove(i);\n\t\t}\n\t}\n\n\tif (deleteItem) SAFE_DELETE_ITEM(item);\n\telse if (item) item->setParentItem(nullptr);\n\n\tsetUpdateNeeded(StandardUpdate);\n}\n\nvoid PositionLayout::clear(bool deleteItems)\n{\n\tfor (int i = 0; i<items.size(); ++i)\n\t{\n\t\tif (deleteItems) SAFE_DELETE_ITEM(items[i]);\n\t\telse if (items[i]) items[i]->setParentItem(nullptr);\n\t}\n\n\tfor (int i = 0; i<positions.size(); ++i) SAFE_DELETE(positions[i]);\n\titems.clear();\n\tpositions.clear();\n}\n\nvoid PositionLayout::swap(int i, int j)\n{\n\tItem* t = items[i];\n\titems[i] = items[j];\n\titems[j] = t;\n\n\tPosition* p = positions[i];\n\tpositions[i] = positions[j];\n\tpositions[j] = p;\n}\n\nvoid PositionLayout::synchronizeWithNodes(const QList<Model::Node*>& nodes, ModelRenderer* renderer)\n{\n\tallNodesLackPositionInfo = items.isEmpty();\n\n\t\/\/ Inserts elements that are not yet visualized and adjusts the order to match that in 'nodes'.\n\tfor (int i = 0; i < nodes.size(); ++i)\n\t{\n\t\t\/\/ Check if node has position info\n\t\tModel::ExtendableNode* extNode = dynamic_cast<Model::ExtendableNode*> (nodes[i]);\n\t\tif (extNode)\n\t\t{\n\t\t\tPosition* pos = extNode->extension<Position>();\n\t\t\tif (pos)\n\t\t\t{\n\t\t\t\tif (pos->xNode() || pos->yNode())\n\t\t\t\t\tallNodesLackPositionInfo = false;\n\t\t\t}\n\t\t}\n\n\t\tif (i >= items.size() ) insert( renderer->render(this, nodes[i]));\t\/\/ This node is new\n\t\telse if ( items[i]->node() == nodes[i] ) continue;\t\/\/ This node is already there\n\t\telse\n\t\t{\n\t\t\t\/\/ This node might appear somewhere ahead, we should look for it\n\t\t\tbool found = false;\n\t\t\tfor (int k = i + 1; k<items.size(); ++k)\n\t\t\t{\n\t\t\t\tif ( items[k]->node() == nodes[i] )\n\t\t\t\t{\n\t\t\t\t\t\/\/ We found this node, swap the visualizations\n\t\t\t\t\tswap(i, k);\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ The node was not found, insert a visualization here\n\t\t\tif (!found )\n\t\t\t{\n\t\t\t\tinsert( renderer->render(this, nodes[i]) );\n\t\t\t\tswap(i, items.size()-1);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Remove excess items\n\twhile (items.size() > nodes.size()) remove(items.size()-1);\n}\n\ninline int PositionLayout::toGrid(const int& pos) const\n{\n\tint mod = (pos >=0) ? ( pos % style()->gridSize() ) : ( (-pos) % style()->gridSize() );\n\tint add = (pos >=0) ? ( style()->gridSize() - mod) : mod;\n\treturn pos + ( (mod !=0) ? add : 0 );\n}\n\nbool PositionLayout::isEmpty() const\n{\n\tfor(int i = 0; i<items.size(); ++i)\n\t\tif (!items[i]->isEmpty()) return false;\n\n\treturn true;\n}\n\nvoid PositionLayout::updateGeometry(int, int)\n{\n\t\/\/ Arrange items if they were all missing positions.\n\tif (allNodesLackPositionInfo && !items.isEmpty())\n\t{\n\t\t\/\/ Get averages\n\t\tdouble averageWidth = 0;\n\t\tdouble averageHeight = 0;\n\t\tfor(auto i : items)\n\t\t{\n\t\t\taverageWidth += i->width();\n\t\t\taverageHeight += i->height();\n\t\t}\n\t\taverageWidth \/= items.size();\n\t\taverageHeight \/= items.size();\n\n\t\t\/\/ Get 'optimal' number of rows to achieve a square\n\t\tdouble prevRatio = 0;\n\t\tint rows = 1;\n\t\tfor (rows = 1; rows<items.size(); ++rows)\n\t\t{\n\t\t\tint cols = (items.size()\/rows) + ((items.size()%rows)?1:0);\n\t\t\tdouble ratio = (averageWidth*cols) \/ (averageHeight*rows);\n\n\t\t\tif (ratio > 1) ratio = 1\/ratio;\n\n\t\t\tif (ratio > prevRatio)\n\t\t\t{\n\t\t\t\tprevRatio = ratio;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (rows > 1) --rows;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint heightLimit = rows*averageHeight;\n\n\t\t\/\/Compute the columns and set the positions\n\t\tint lastBottom = 0;\n\t\tint lastRight = 0;\n\t\tint colWidth = 0;\n\n\t\tfor(int i = 0; i<items.size(); ++i)\n\t\t{\n\t\t\tint x = lastRight;\n\t\t\tint y = lastBottom;\n\n\t\t\tif (lastBottom == 0 || (lastBottom + items[i]->height() <= heightLimit))\n\t\t\t{\n\t\t\t\tlastBottom += 10 + items[i]->height();\n\t\t\t\tlastBottom = toGrid(lastBottom);\n\n\t\t\t\tif (items[i]->width() > colWidth) colWidth = items[i]->width();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ty = 0;\n\t\t\t\tlastBottom = 10 + items[i]->height();\n\n\t\t\t\tlastRight += 10 + colWidth;\n\t\t\t\tlastRight = toGrid(lastRight);\n\t\t\t\tx = lastRight;\n\t\t\t\tcolWidth = items[i]->width();\n\t\t\t}\n\n\t\t\titems[i]->node()->beginModification(\"Automatically set position\");\n\t\t\tpositions[i]->setX(x);\n\t\t\tpositions[i]->setY(y);\n\t\t\titems[i]->node()->endModification();\n\t\t}\n\n\t\tallNodesLackPositionInfo = false;\n\t}\n\n\tQPoint topLeft;\n\tQPoint bottomRight;\n\n\tfor(int i = 0; i<items.size(); ++i)\n\t{\n\t\tint x = positions[i]->xNode() ? toGrid(positions[i]->x()) : 0;\n\t\tint y = positions[i]->yNode() ? toGrid(positions[i]->y()) : 0;\n\n\t\tif (i==0 || topLeft.x() > x )\n\t\t\ttopLeft.setX( x );\n\t\tif (i==0 || topLeft.y() > y )\n\t\t\ttopLeft.setY( y );\n\t\tif (i==0 || bottomRight.x() < x + items[i]->width() )\n\t\t\tbottomRight.setX( x + items[i]->width() );\n\t\tif (i==0 || bottomRight.y() < y + items[i]->height() )\n\t\t\tbottomRight.setY( y + items[i]->height() );\n\t}\n\n\tint sizeWidth = bottomRight.x() - topLeft.x() + style()->leftInnerMargin() + style()->rightInnerMargin();\n\tint sizeHeight = bottomRight.y() - topLeft.y() + style()->topInnerMargin() + style()->bottomInnerMargin();\n\tsetInnerSize(sizeWidth, sizeHeight);\n\n\tfor (int i =0; i<items.size(); ++i)\n\t{\n\t\tint x = positions[i]->xNode() ? toGrid(positions[i]->x()) : 0;\n\t\tint y = positions[i]->yNode() ? toGrid(positions[i]->y()) : 0;\n\t\titems[i]->setPos( xOffset() + style()->leftInnerMargin() + x - topLeft.x(),\n\t\t\t\t\t\t\t\tyOffset() + style()->topInnerMargin() + y - topLeft.y());\n\t}\n}\n\nint PositionLayout::focusedElementIndex() const\n{\n\tfor (int i = 0; i<items.size(); ++i)\n\t\tif ( items[i]->itemOrChildHasFocus()) return i;\n\n\treturn -1;\n}\n\n}\n<commit_msg>Speedup automatic positioning of nodes within a PositionLayout<commit_after>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (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***********************************************************************************************************************\/\n\n\/***********************************************************************************************************************\n * PositionLayout.cpp\n *\n * Created on: Feb 2, 2011\n * Author: Dimitar Asenov\n **********************************************************************************************************************\/\n\n#include \"layouts\/PositionLayout.h\"\n#include \"shapes\/Shape.h\"\n#include \"..\/renderer\/ModelRenderer.h\"\n\n#include \"ModelBase\/src\/model\/Model.h\"\n\nnamespace Visualization {\n\nITEM_COMMON_DEFINITIONS( PositionLayout, \"layout\" )\n\nPositionLayout::PositionLayout(Item* parent, const StyleType* style) :\n\tLayout(parent, style)\n{\n}\n\nPositionLayout::~PositionLayout()\n{\n\tfor (int i = 0; i<items.size(); i++) SAFE_DELETE_ITEM( items[i]);\n}\n\nint PositionLayout::length() const\n{\n\treturn items.size();\n}\n\nbool PositionLayout::containsNode(Model::Node* node_)\n{\n\tfor(int i=0; i<items.size(); ++i)\n\t\tif (items[i]->node() == node_) return true;\n\n\treturn false;\n}\n\nvoid PositionLayout::insert(Item* item)\n{\n\t\/\/ Check whether this item has a node and a position associated with it\n\tif ( !item->hasNode() ) throw VisualizationException(\"Adding an Item that has no node to a PositionLayout\");\n\n\tModel::ExtendableNode* extNode = dynamic_cast<Model::ExtendableNode*> (item->node());\n\tif (!extNode)\n\t\tthrow VisualizationException(\"Adding an Item that does not implement ExtendableNode to a PositionLayout\");\n\n\tPosition* pos = extNode->extension<Position>();\n\n\tif (!pos)\n\t\tthrow VisualizationException(\"Adding a Item whose node does not have a Position extension to a PositionLayout\");\n\n\titem->setParentItem(this);\n\titems.append(item);\n\tpositions.append(pos);\n\tsetUpdateNeeded(StandardUpdate);\n}\n\nvoid PositionLayout::remove(int index, bool deleteItem)\n{\n\tif (deleteItem) SAFE_DELETE_ITEM( items[index]);\n\telse if(items[index]) items[index]->setParentItem(nullptr);\n\n\tSAFE_DELETE( positions[index] );\n\titems.remove(index);\n\tpositions.remove(index);\n\tsetUpdateNeeded(StandardUpdate);\n}\n\nvoid PositionLayout::removeAll(Item* item, bool deleteItem)\n{\n\tfor (int i = items.size() - 1; i>=0; --i)\n\t{\n\t\tif (items.at(i) == item)\n\t\t{\n\t\t\titems.remove(i);\n\t\t\tSAFE_DELETE( positions[i] );\n\t\t\tpositions.remove(i);\n\t\t}\n\t}\n\n\tif (deleteItem) SAFE_DELETE_ITEM(item);\n\telse if (item) item->setParentItem(nullptr);\n\n\tsetUpdateNeeded(StandardUpdate);\n}\n\nvoid PositionLayout::clear(bool deleteItems)\n{\n\tfor (int i = 0; i<items.size(); ++i)\n\t{\n\t\tif (deleteItems) SAFE_DELETE_ITEM(items[i]);\n\t\telse if (items[i]) items[i]->setParentItem(nullptr);\n\t}\n\n\tfor (int i = 0; i<positions.size(); ++i) SAFE_DELETE(positions[i]);\n\titems.clear();\n\tpositions.clear();\n}\n\nvoid PositionLayout::swap(int i, int j)\n{\n\tItem* t = items[i];\n\titems[i] = items[j];\n\titems[j] = t;\n\n\tPosition* p = positions[i];\n\tpositions[i] = positions[j];\n\tpositions[j] = p;\n}\n\nvoid PositionLayout::synchronizeWithNodes(const QList<Model::Node*>& nodes, ModelRenderer* renderer)\n{\n\tallNodesLackPositionInfo = items.isEmpty();\n\n\t\/\/ Inserts elements that are not yet visualized and adjusts the order to match that in 'nodes'.\n\tfor (int i = 0; i < nodes.size(); ++i)\n\t{\n\t\t\/\/ Check if node has position info\n\t\tModel::ExtendableNode* extNode = dynamic_cast<Model::ExtendableNode*> (nodes[i]);\n\t\tif (extNode)\n\t\t{\n\t\t\tPosition* pos = extNode->extension<Position>();\n\t\t\tif (pos)\n\t\t\t{\n\t\t\t\tif (pos->xNode() || pos->yNode())\n\t\t\t\t\tallNodesLackPositionInfo = false;\n\t\t\t}\n\t\t}\n\n\t\tif (i >= items.size() ) insert( renderer->render(this, nodes[i]));\t\/\/ This node is new\n\t\telse if ( items[i]->node() == nodes[i] ) continue;\t\/\/ This node is already there\n\t\telse\n\t\t{\n\t\t\t\/\/ This node might appear somewhere ahead, we should look for it\n\t\t\tbool found = false;\n\t\t\tfor (int k = i + 1; k<items.size(); ++k)\n\t\t\t{\n\t\t\t\tif ( items[k]->node() == nodes[i] )\n\t\t\t\t{\n\t\t\t\t\t\/\/ We found this node, swap the visualizations\n\t\t\t\t\tswap(i, k);\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ The node was not found, insert a visualization here\n\t\t\tif (!found )\n\t\t\t{\n\t\t\t\tinsert( renderer->render(this, nodes[i]) );\n\t\t\t\tswap(i, items.size()-1);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Remove excess items\n\twhile (items.size() > nodes.size()) remove(items.size()-1);\n}\n\ninline int PositionLayout::toGrid(const int& pos) const\n{\n\tint mod = (pos >=0) ? ( pos % style()->gridSize() ) : ( (-pos) % style()->gridSize() );\n\tint add = (pos >=0) ? ( style()->gridSize() - mod) : mod;\n\treturn pos + ( (mod !=0) ? add : 0 );\n}\n\nbool PositionLayout::isEmpty() const\n{\n\tfor(int i = 0; i<items.size(); ++i)\n\t\tif (!items[i]->isEmpty()) return false;\n\n\treturn true;\n}\n\nvoid PositionLayout::updateGeometry(int, int)\n{\n\t\/\/ Arrange items if they were all missing positions.\n\tif (allNodesLackPositionInfo && !items.isEmpty())\n\t{\n\t\t\/\/ Get averages\n\t\tdouble averageWidth = 0;\n\t\tdouble averageHeight = 0;\n\t\tfor(auto i : items)\n\t\t{\n\t\t\taverageWidth += i->width();\n\t\t\taverageHeight += i->height();\n\t\t}\n\t\taverageWidth \/= items.size();\n\t\taverageHeight \/= items.size();\n\n\t\t\/\/ Get 'optimal' number of rows to achieve a square\n\t\tdouble prevRatio = 0;\n\t\tint rows = 1;\n\t\tfor (rows = 1; rows<items.size(); ++rows)\n\t\t{\n\t\t\tint cols = (items.size()\/rows) + ((items.size()%rows)?1:0);\n\t\t\tdouble ratio = (averageWidth*cols) \/ (averageHeight*rows);\n\n\t\t\tif (ratio > 1) ratio = 1\/ratio;\n\n\t\t\tif (ratio > prevRatio)\n\t\t\t{\n\t\t\t\tprevRatio = ratio;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (rows > 1) --rows;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint heightLimit = rows*averageHeight;\n\n\t\t\/\/Compute the columns and set the positions\n\t\tint lastBottom = 0;\n\t\tint lastRight = 0;\n\t\tint colWidth = 0;\n\n\t\tauto model = items[0]->node()->model();\n\t\tmodel->beginModification(items[0]->node(), \"Automatically set position\");\n\t\t\/\/ It is important to batch the modifications, since model::endModification() send a notification signal.\n\n\t\tfor(int i = 0; i<items.size(); ++i)\n\t\t{\n\t\t\tint x = lastRight;\n\t\t\tint y = lastBottom;\n\n\t\t\tif (lastBottom == 0 || (lastBottom + items[i]->height() <= heightLimit))\n\t\t\t{\n\t\t\t\tlastBottom += 10 + items[i]->height();\n\t\t\t\tlastBottom = toGrid(lastBottom);\n\n\t\t\t\tif (items[i]->width() > colWidth) colWidth = items[i]->width();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ty = 0;\n\t\t\t\tlastBottom = 10 + items[i]->height();\n\n\t\t\t\tlastRight += 10 + colWidth;\n\t\t\t\tlastRight = toGrid(lastRight);\n\t\t\t\tx = lastRight;\n\t\t\t\tcolWidth = items[i]->width();\n\t\t\t}\n\n\t\t\tmodel->changeModificationTarget(items[i]->node());\n\t\t\tpositions[i]->setX(x);\n\t\t\tpositions[i]->setY(y);\n\t\t}\n\n\t\tmodel->endModification();\n\t\tallNodesLackPositionInfo = false;\n\t}\n\n\tQPoint topLeft;\n\tQPoint bottomRight;\n\n\tfor(int i = 0; i<items.size(); ++i)\n\t{\n\t\tint x = positions[i]->xNode() ? toGrid(positions[i]->x()) : 0;\n\t\tint y = positions[i]->yNode() ? toGrid(positions[i]->y()) : 0;\n\n\t\tif (i==0 || topLeft.x() > x )\n\t\t\ttopLeft.setX( x );\n\t\tif (i==0 || topLeft.y() > y )\n\t\t\ttopLeft.setY( y );\n\t\tif (i==0 || bottomRight.x() < x + items[i]->width() )\n\t\t\tbottomRight.setX( x + items[i]->width() );\n\t\tif (i==0 || bottomRight.y() < y + items[i]->height() )\n\t\t\tbottomRight.setY( y + items[i]->height() );\n\t}\n\n\tint sizeWidth = bottomRight.x() - topLeft.x() + style()->leftInnerMargin() + style()->rightInnerMargin();\n\tint sizeHeight = bottomRight.y() - topLeft.y() + style()->topInnerMargin() + style()->bottomInnerMargin();\n\tsetInnerSize(sizeWidth, sizeHeight);\n\n\tfor (int i =0; i<items.size(); ++i)\n\t{\n\t\tint x = positions[i]->xNode() ? toGrid(positions[i]->x()) : 0;\n\t\tint y = positions[i]->yNode() ? toGrid(positions[i]->y()) : 0;\n\t\titems[i]->setPos( xOffset() + style()->leftInnerMargin() + x - topLeft.x(),\n\t\t\t\t\t\t\t\tyOffset() + style()->topInnerMargin() + y - topLeft.y());\n\t}\n}\n\nint PositionLayout::focusedElementIndex() const\n{\n\tfor (int i = 0; i<items.size(); ++i)\n\t\tif ( items[i]->itemOrChildHasFocus()) return i;\n\n\treturn -1;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include <algorithm>\n#include \"simple_strategy.hh\"\n#include \"utils\/class_registrator.hh\"\n#include <boost\/algorithm\/string.hpp>\n#include \"utils\/sequenced_set.hh\"\n\nnamespace locator {\n\nsimple_strategy::simple_strategy(const sstring& keyspace_name, token_metadata& token_metadata, snitch_ptr& snitch, const std::map<sstring, sstring>& config_options) :\n abstract_replication_strategy(keyspace_name, token_metadata, snitch, config_options, replication_strategy_type::simple) {\n for (auto& config_pair : config_options) {\n auto& key = config_pair.first;\n auto& val = config_pair.second;\n\n if (boost::iequals(key, \"replication_factor\")) {\n _replication_factor = std::stol(val);\n\n break;\n }\n }\n}\n\nstd::vector<inet_address> simple_strategy::calculate_natural_endpoints(const token& t) {\n const std::vector<token>& tokens = _token_metadata.sorted_tokens();\n\n if (tokens.empty()) {\n return std::vector<inet_address>();\n }\n\n size_t replicas = get_replication_factor();\n utils::sequenced_set<inet_address> endpoints;\n endpoints.reserve(replicas);\n\n for (auto& token : _token_metadata.ring_range(t)) {\n auto ep = _token_metadata.get_endpoint(token);\n assert(ep);\n\n endpoints.push_back(*ep);\n if (endpoints.size() == replicas) break;\n }\n\n return std::move(endpoints.get_vector());\n}\n\nsize_t simple_strategy::get_replication_factor() const {\n return _replication_factor;\n}\n\nusing registry = class_registrator<abstract_replication_strategy, simple_strategy, const sstring&, token_metadata&, snitch_ptr&, const std::map<sstring, sstring>&>;\nstatic registry registrator(\"org.apache.cassandra.locator.SimpleStrategy\");\nstatic registry registrator_short_name(\"SimpleStrategy\");\n\n}\n<commit_msg>simple_strategy: coding convention fixes<commit_after>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include <algorithm>\n#include \"simple_strategy.hh\"\n#include \"utils\/class_registrator.hh\"\n#include <boost\/algorithm\/string.hpp>\n#include \"utils\/sequenced_set.hh\"\n\nnamespace locator {\n\nsimple_strategy::simple_strategy(const sstring& keyspace_name, token_metadata& token_metadata, snitch_ptr& snitch, const std::map<sstring, sstring>& config_options) :\n abstract_replication_strategy(keyspace_name, token_metadata, snitch, config_options, replication_strategy_type::simple) {\n for (auto& config_pair : config_options) {\n auto& key = config_pair.first;\n auto& val = config_pair.second;\n\n if (boost::iequals(key, \"replication_factor\")) {\n _replication_factor = std::stol(val);\n\n break;\n }\n }\n}\n\nstd::vector<inet_address> simple_strategy::calculate_natural_endpoints(const token& t) {\n const std::vector<token>& tokens = _token_metadata.sorted_tokens();\n\n if (tokens.empty()) {\n return std::vector<inet_address>();\n }\n\n size_t replicas = get_replication_factor();\n utils::sequenced_set<inet_address> endpoints;\n endpoints.reserve(replicas);\n\n for (auto& token : _token_metadata.ring_range(t)) {\n auto ep = _token_metadata.get_endpoint(token);\n assert(ep);\n\n endpoints.push_back(*ep);\n if (endpoints.size() == replicas) {\n break;\n }\n }\n\n return std::move(endpoints.get_vector());\n}\n\nsize_t simple_strategy::get_replication_factor() const {\n return _replication_factor;\n}\n\nusing registry = class_registrator<abstract_replication_strategy, simple_strategy, const sstring&, token_metadata&, snitch_ptr&, const std::map<sstring, sstring>&>;\nstatic registry registrator(\"org.apache.cassandra.locator.SimpleStrategy\");\nstatic registry registrator_short_name(\"SimpleStrategy\");\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <mutex>\n#include <thread>\n\n#include <SFML\/Config.hpp>\n#include <SFML\/Graphics.hpp>\n#include <yaml-cpp\/yaml.h>\n\n#ifdef NDEBUG\n#define LOGOG_LEVEL LOGOG_LEVEL_INFO\n#else\n#define LOGOG_LEVEL LOGOG_LEVEL_ALL\n#endif\n#include <logog\/logog.hpp>\n\n#include <Sprite.hpp>\n\nclass Engine {\npublic:\n const uint32_t JAGE_VERSION_MAJOR = 0;\n const uint32_t JAGE_VERSION_MINOR = 5;\n const uint32_t JAGE_VERSION_REVISION = 2;\n\n Engine(const int argc, const char** argv);\n ~Engine();\n\n bool ready();\n\n \/\/ main event loop\n bool run();\n\nprivate:\n \/* methods *\/\n\n \/\/event dispatcher\n void processEvents();\n \/\/ update the simulation\n void update(const sf::Time& elapsed);\n \/\/ render everything, runs in separate thread\n void renderLoop();\n\n \/\/ event handlers\n void handleResize(const sf::Event::SizeEvent& newSize);\n void handleKeyPress(const sf::Event& event);\n void handleKeyRelease(const sf::Event& event);\n\n \/\/ log some build & system info\n void dumpSystemInfo();\n\n \/\/ get the configuration from an INI file\n void readConfig();\n\n \/\/ [re]create the rendering window, possibly fullscreen\n void createWindow(const bool shouldFullscreen = false);\n \/\/ change the viewport to maintain 16:9 aspect ratio\n void adjustAspect(const sf::Vector2u& newSize);\n\n \/\/ control the window mutex and active window\n void inline lockWindow();\n void inline releaseWindow();\n\n \/* member data *\/\n\n int argc;\n const char** argv;\n\n logog::LogFile* logFile;\n logog::Cout* logConsole;\n logog::Formatter* formatter;\n\n std::unique_ptr<std::thread> renderThread;\n\n bool isReady = false;\n bool running = false;\n\n std::string game;\n std::string data_dir;\n\n \/\/ render internally to 720p widescreen\n unsigned int renderWidth = 1280;\n unsigned int renderHeight = 720;\n\n struct {\n std::string name;\n \/\/ this size fits in most screens in windowed mode\n unsigned int width = 1200;\n unsigned int height = 675;\n \/\/ don't start fullscreen\n bool fullscreen = false;\n \/\/ but do use desktop size when going fullscreen\n bool useDesktopSize = true;\n \/\/ obvi, use vsync\n bool vsync = true;\n \/\/ controller\/keyboard settings\n float deadZone = 15.0;\n float keySpeed = 75.0;\n } config;\n\n \/\/ where everything is drawn\n sf::RenderWindow window;\n \/\/ controls the 2D camera, used for rendering internally at a set size\n sf::View view;\n \/\/ where we render the game before copying it to the window\n sf::RenderTexture screen;\n\n \/\/ mutexes for the window and sprite list\n std::recursive_mutex windowMutex;\n std::recursive_mutex spritesMutex;\n\n \/\/ all normal sprites to draw\n std::vector<std::shared_ptr<Sprite>> sprites;\n\n \/\/ the player's ship sprite\n std::shared_ptr<Sprite> player;\n \/\/ computer opponent's ship sprite\n std::shared_ptr<Sprite> enemy;\n};\n<commit_msg>std::recursive_mutex was not the right choice.<commit_after>#pragma once\n\n#include <mutex>\n#include <thread>\n\n#include <SFML\/Config.hpp>\n#include <SFML\/Graphics.hpp>\n#include <yaml-cpp\/yaml.h>\n\n#ifdef NDEBUG\n#define LOGOG_LEVEL LOGOG_LEVEL_INFO\n#else\n#define LOGOG_LEVEL LOGOG_LEVEL_ALL\n#endif\n#include <logog\/logog.hpp>\n\n#include <Sprite.hpp>\n\nclass Engine {\npublic:\n const uint32_t JAGE_VERSION_MAJOR = 0;\n const uint32_t JAGE_VERSION_MINOR = 5;\n const uint32_t JAGE_VERSION_REVISION = 2;\n\n Engine(const int argc, const char** argv);\n ~Engine();\n\n bool ready();\n\n \/\/ main event loop\n bool run();\n\nprivate:\n \/* methods *\/\n\n \/\/event dispatcher\n void processEvents();\n \/\/ update the simulation\n void update(const sf::Time& elapsed);\n \/\/ render everything, runs in separate thread\n void renderLoop();\n\n \/\/ event handlers\n void handleResize(const sf::Event::SizeEvent& newSize);\n void handleKeyPress(const sf::Event& event);\n void handleKeyRelease(const sf::Event& event);\n\n \/\/ log some build & system info\n void dumpSystemInfo();\n\n \/\/ get the configuration from an INI file\n void readConfig();\n\n \/\/ [re]create the rendering window, possibly fullscreen\n void createWindow(const bool shouldFullscreen = false);\n \/\/ change the viewport to maintain 16:9 aspect ratio\n void adjustAspect(const sf::Vector2u& newSize);\n\n \/\/ control the window mutex and active window\n void inline lockWindow();\n void inline releaseWindow();\n\n \/* member data *\/\n\n int argc;\n const char** argv;\n\n logog::LogFile* logFile;\n logog::Cout* logConsole;\n logog::Formatter* formatter;\n\n std::unique_ptr<std::thread> renderThread;\n\n bool isReady = false;\n bool running = false;\n\n std::string game;\n std::string data_dir;\n\n \/\/ render internally to 720p widescreen\n unsigned int renderWidth = 1280;\n unsigned int renderHeight = 720;\n\n struct {\n std::string name;\n \/\/ this size fits in most screens in windowed mode\n unsigned int width = 1200;\n unsigned int height = 675;\n \/\/ don't start fullscreen\n bool fullscreen = false;\n \/\/ but do use desktop size when going fullscreen\n bool useDesktopSize = true;\n \/\/ obvi, use vsync\n bool vsync = true;\n \/\/ controller\/keyboard settings\n float deadZone = 15.0;\n float keySpeed = 75.0;\n } config;\n\n \/\/ where everything is drawn\n sf::RenderWindow window;\n \/\/ controls the 2D camera, used for rendering internally at a set size\n sf::View view;\n \/\/ where we render the game before copying it to the window\n sf::RenderTexture screen;\n\n \/\/ mutexes for the window and sprite list\n std::mutex windowMutex;\n std::mutex spritesMutex;\n\n \/\/ all normal sprites to draw\n std::vector<std::shared_ptr<Sprite>> sprites;\n\n \/\/ the player's ship sprite\n std::shared_ptr<Sprite> player;\n \/\/ computer opponent's ship sprite\n std::shared_ptr<Sprite> enemy;\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\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#ifndef TARGET_MACROS_H\n#define TARGET_MACROS_H\n\nnamespace eddic {\n\n#ifdef __GNUG__\n #ifdef __LP64__\n static bool Target64 = true;\n #else\n static bool Target64 = false;\n #endif\n static bool TargetDetermined = true;\n#else\n static bool Target64 = false;\n static bool TargetDetermined = false;\n#endif\n\n} \/\/end of eddic\n\n#endif\n<commit_msg>Put global variables to const<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\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#ifndef TARGET_MACROS_H\n#define TARGET_MACROS_H\n\nnamespace eddic {\n\n#ifdef __GNUG__\n #ifdef __LP64__\n static const bool Target64 = true;\n #else\n static const bool Target64 = false;\n #endif\n static const bool TargetDetermined = true;\n#else\n static const bool Target64 = false;\n static const bool TargetDetermined = false;\n#endif\n\n} \/\/end of eddic\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\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#ifndef KERNEL_OS_HPP\n#define KERNEL_OS_HPP\n\n#include <common>\n#include <arch.hpp>\n#include <kernel\/memmap.hpp>\n#include <kernel\/rtc.hpp>\n#include <hertz>\n#include <string>\n#include <vector>\n#include <boot\/multiboot.h>\n\n\/**\n * The entrypoint for OS services\n *\n * @note For device access, see Dev\n *\/\nclass OS {\npublic:\n using print_func = delegate<void(const char*, size_t)>;\n using Plugin = delegate<void()>;\n using Span_mods = gsl::span<multiboot_module_t>;\n\n \/**\n * Returns the OS version string\n **\/\n static const std::string& version() noexcept\n { return version_str_; }\n\n \/**\n * Returns the CPU architecture for which the OS was built\n **\/\n static const std::string& arch() noexcept\n { return arch_str_; }\n\n\n \/**\n * Returns the commandline arguments provided,\n * if any, to the VM passed on by multiboot or\n * other mechanisms. The first argument is always\n * the binary name.\n **\/\n static const char* cmdline_args() noexcept;\n\n \/** Clock cycles since boot. *\/\n static uint64_t cycles_since_boot() {\n return __arch_cpu_cycles();\n }\n \/** micro seconds since boot *\/\n static int64_t micros_since_boot() noexcept;\n\n \/** Timestamp for when OS was booted *\/\n static RTC::timestamp_t boot_timestamp();\n\n \/** Uptime in whole seconds. *\/\n static RTC::timestamp_t uptime();\n\n \/** Time spent sleeping (halt) in cycles *\/\n static uint64_t cycles_asleep() noexcept;\n\n \/** Time spent sleeping (halt) in micros *\/\n static uint64_t micros_asleep() noexcept;\n\n\n static MHz cpu_freq() noexcept\n { return cpu_mhz_; }\n\n \/**\n * Reboot operating system\n *\n **\/\n static void reboot();\n\n \/**\n * Shutdown operating system\n *\n **\/\n static void shutdown();\n\n \/**\n * Halt until next interrupt.\n *\n * @Warning If there is no regular timer interrupt (i.e. from PIT \/ APIC)\n * we'll stay asleep.\n *\/\n static void halt();\n\n \/**\n * Returns true when the OS will still be running, and not shutting down.\n *\/\n static bool is_running() noexcept {\n return power_;\n }\n\n \/**\n * Returns true when the OS has passed the boot sequence, and\n * is at least processing plugins and about to call Service::start\n *\/\n static bool is_booted() noexcept {\n return boot_sequence_passed_;\n }\n\n static bool block_drivers_ready() noexcept {\n return m_block_drivers_ready;\n }\n\n \/**\n * Returns true when the OS is currently panicking\n *\/\n static bool is_panicking() noexcept;\n\n \/**\n * Sometimes the OS just has a bad day and crashes\n * The on_panic handler will be called directly after a panic,\n * or any condition which will deliberately cause the OS to become\n * unresponsive. After the handler is called, the OS goes to sleep.\n * This handler can thus be used to, for example, automatically\n * have the OS restart on any crash.\n **\/\n typedef void (*on_panic_func) (const char*);\n static void on_panic(on_panic_func);\n\n \/**\n * Write data to standard out callbacks\n *\/\n static void print(const char* ptr, const size_t len);\n\n \/**\n * Add handler for standard output.\n *\/\n static void add_stdout(print_func func);\n\n \/**\n * The default output method preferred by each platform\n * Directly writes the string to its output mechanism\n **\/\n static void default_stdout(const char*, size_t);\n\n \/** Memory page helpers *\/\n static constexpr uint32_t page_size() noexcept {\n return 4096;\n }\n static constexpr uint32_t addr_to_page(uintptr_t addr) noexcept {\n return addr >> PAGE_SHIFT;\n }\n static constexpr uintptr_t page_to_addr(uint32_t page) noexcept {\n return page << PAGE_SHIFT;\n }\n\n \/** Total used dynamic memory, in bytes *\/\n static uintptr_t heap_usage() noexcept;\n\n \/** Attempt to trim the heap end, reducing the size *\/\n static void heap_trim() noexcept;\n\n \/** First address of the heap **\/\n static uintptr_t heap_begin() noexcept;\n\n \/** Last used address of the heap **\/\n static uintptr_t heap_end() noexcept;\n\n \/** Resize the heap if possible. Return (potentially) new size. **\/\n static uintptr_t resize_heap(size_t size);\n\n \/** The maximum last address of the dynamic memory area (heap) *\/\n static uintptr_t heap_max() noexcept;\n\n \/** The end of usable memory **\/\n static uintptr_t memory_end() noexcept {\n return memory_end_;\n }\n\n \/**\n * Returns true when the current OS comes from a live update,\n * as opposed to booting from either a rollback or a normal boot\n *\/\n static bool is_live_updated() noexcept;\n\n \/** Returns the automatic location set aside for storing system and program state **\/\n static void* liveupdate_storage_area() noexcept;\n\n \/**\n * A map of memory ranges. The key is the starting address in numeric form.\n * @note : the idea is to avoid raw pointers whenever possible\n **\/\n static Memory_map& memory_map() {\n static Memory_map memmap {};\n return memmap;\n }\n\n \/** Get \"kernel modules\", provided by multiboot *\/\n static Span_mods modules();\n\n \/**\n * Register a custom initialization function. The provided delegate is\n * guaranteed to be called after global constructors and device initialization\n * and before Service::start, provided that this funciton was called by a\n * global constructor.\n * @param delg : A delegate to be called\n * @param name : A human readable identifier\n **\/\n static void register_plugin(Plugin delg, const char* name);\n\n\n \/**\n * Block for a while, e.g. until the next round in the event loop\n **\/\n static void block();\n\n\n \/** The main event loop. Check interrupts, timers etc., and do callbacks. *\/\n static void event_loop();\n\n \/** Initialize platform, devices etc. *\/\n static void start(uint32_t boot_magic, uint32_t boot_addr);\n\n static void start(char *cmdline, uintptr_t mem_size);\n\n \/** Initialize common subsystems, call Service::start *\/\n static void post_start();\n\nprivate:\n \/** Process multiboot info. Called by 'start' if multibooted **\/\n static void multiboot(uint32_t boot_addr);\n\n static multiboot_info_t* bootinfo();\n\n \/** Boot with no multiboot params *\/\n static void legacy_boot();\n\n \/** Resume stuff from a soft reset **\/\n static bool is_softreset_magic(uint32_t value);\n static void resume_softreset(intptr_t boot_addr);\n\n static constexpr int PAGE_SHIFT = 12;\n static bool power_;\n static bool boot_sequence_passed_;\n static bool m_is_live_updated;\n static bool m_block_drivers_ready;\n static MHz cpu_mhz_;\n\n static RTC::timestamp_t booted_at_;\n static uintptr_t liveupdate_loc_;\n static std::string version_str_;\n static std::string arch_str_;\n static uintptr_t memory_end_;\n static uintptr_t heap_max_;\n static const uintptr_t elf_binary_size_;\n static const char* cmdline;\n\n \/\/ Prohibit copy and move operations\n OS(OS&) = delete;\n OS(OS&&) = delete;\n OS& operator=(OS&) = delete;\n OS& operator=(OS&&) = delete;\n ~OS() = delete;\n \/\/ Prohibit construction\n OS() = delete;\n\n friend void __platform_init();\n}; \/\/< OS\n\ninline OS::Span_mods OS::modules()\n{\n auto* bootinfo_ = bootinfo();\n if (bootinfo_ and bootinfo_->flags & MULTIBOOT_INFO_MODS and bootinfo_->mods_count) {\n\n Expects(bootinfo_->mods_count < std::numeric_limits<int>::max());\n\n return Span_mods{\n reinterpret_cast<multiboot_module_t*>(bootinfo_->mods_addr),\n static_cast<int>(bootinfo_->mods_count) };\n }\n return nullptr;\n}\n\n#endif \/\/< KERNEL_OS_HPP\n<commit_msg>os: Implement OS::is_live_updated<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\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#ifndef KERNEL_OS_HPP\n#define KERNEL_OS_HPP\n\n#include <common>\n#include <arch.hpp>\n#include <kernel\/memmap.hpp>\n#include <kernel\/rtc.hpp>\n#include <hertz>\n#include <string>\n#include <vector>\n#include <boot\/multiboot.h>\n\n\/**\n * The entrypoint for OS services\n *\n * @note For device access, see Dev\n *\/\nclass OS {\npublic:\n using print_func = delegate<void(const char*, size_t)>;\n using Plugin = delegate<void()>;\n using Span_mods = gsl::span<multiboot_module_t>;\n\n \/**\n * Returns the OS version string\n **\/\n static const std::string& version() noexcept\n { return version_str_; }\n\n \/**\n * Returns the CPU architecture for which the OS was built\n **\/\n static const std::string& arch() noexcept\n { return arch_str_; }\n\n\n \/**\n * Returns the commandline arguments provided,\n * if any, to the VM passed on by multiboot or\n * other mechanisms. The first argument is always\n * the binary name.\n **\/\n static const char* cmdline_args() noexcept;\n\n \/** Clock cycles since boot. *\/\n static uint64_t cycles_since_boot() {\n return __arch_cpu_cycles();\n }\n \/** micro seconds since boot *\/\n static int64_t micros_since_boot() noexcept;\n\n \/** Timestamp for when OS was booted *\/\n static RTC::timestamp_t boot_timestamp();\n\n \/** Uptime in whole seconds. *\/\n static RTC::timestamp_t uptime();\n\n \/** Time spent sleeping (halt) in cycles *\/\n static uint64_t cycles_asleep() noexcept;\n\n \/** Time spent sleeping (halt) in micros *\/\n static uint64_t micros_asleep() noexcept;\n\n\n static MHz cpu_freq() noexcept\n { return cpu_mhz_; }\n\n \/**\n * Reboot operating system\n *\n **\/\n static void reboot();\n\n \/**\n * Shutdown operating system\n *\n **\/\n static void shutdown();\n\n \/**\n * Halt until next interrupt.\n *\n * @Warning If there is no regular timer interrupt (i.e. from PIT \/ APIC)\n * we'll stay asleep.\n *\/\n static void halt();\n\n \/**\n * Returns true when the OS will still be running, and not shutting down.\n *\/\n static bool is_running() noexcept {\n return power_;\n }\n\n \/**\n * Returns true when the OS has passed the boot sequence, and\n * is at least processing plugins and about to call Service::start\n *\/\n static bool is_booted() noexcept {\n return boot_sequence_passed_;\n }\n\n static bool block_drivers_ready() noexcept {\n return m_block_drivers_ready;\n }\n\n \/**\n * Returns true when the OS is currently panicking\n *\/\n static bool is_panicking() noexcept;\n\n \/**\n * Sometimes the OS just has a bad day and crashes\n * The on_panic handler will be called directly after a panic,\n * or any condition which will deliberately cause the OS to become\n * unresponsive. After the handler is called, the OS goes to sleep.\n * This handler can thus be used to, for example, automatically\n * have the OS restart on any crash.\n **\/\n typedef void (*on_panic_func) (const char*);\n static void on_panic(on_panic_func);\n\n \/**\n * Write data to standard out callbacks\n *\/\n static void print(const char* ptr, const size_t len);\n\n \/**\n * Add handler for standard output.\n *\/\n static void add_stdout(print_func func);\n\n \/**\n * The default output method preferred by each platform\n * Directly writes the string to its output mechanism\n **\/\n static void default_stdout(const char*, size_t);\n\n \/** Memory page helpers *\/\n static constexpr uint32_t page_size() noexcept {\n return 4096;\n }\n static constexpr uint32_t addr_to_page(uintptr_t addr) noexcept {\n return addr >> PAGE_SHIFT;\n }\n static constexpr uintptr_t page_to_addr(uint32_t page) noexcept {\n return page << PAGE_SHIFT;\n }\n\n \/** Total used dynamic memory, in bytes *\/\n static uintptr_t heap_usage() noexcept;\n\n \/** Attempt to trim the heap end, reducing the size *\/\n static void heap_trim() noexcept;\n\n \/** First address of the heap **\/\n static uintptr_t heap_begin() noexcept;\n\n \/** Last used address of the heap **\/\n static uintptr_t heap_end() noexcept;\n\n \/** Resize the heap if possible. Return (potentially) new size. **\/\n static uintptr_t resize_heap(size_t size);\n\n \/** The maximum last address of the dynamic memory area (heap) *\/\n static uintptr_t heap_max() noexcept;\n\n \/** The end of usable memory **\/\n static uintptr_t memory_end() noexcept {\n return memory_end_;\n }\n\n \/**\n * Returns true when the current OS comes from a live update,\n * as opposed to booting from either a rollback or a normal boot\n *\/\n static bool is_live_updated() noexcept;\n\n \/** Returns the automatic location set aside for storing system and program state **\/\n static void* liveupdate_storage_area() noexcept;\n\n \/**\n * A map of memory ranges. The key is the starting address in numeric form.\n * @note : the idea is to avoid raw pointers whenever possible\n **\/\n static Memory_map& memory_map() {\n static Memory_map memmap {};\n return memmap;\n }\n\n \/** Get \"kernel modules\", provided by multiboot *\/\n static Span_mods modules();\n\n \/**\n * Register a custom initialization function. The provided delegate is\n * guaranteed to be called after global constructors and device initialization\n * and before Service::start, provided that this funciton was called by a\n * global constructor.\n * @param delg : A delegate to be called\n * @param name : A human readable identifier\n **\/\n static void register_plugin(Plugin delg, const char* name);\n\n\n \/**\n * Block for a while, e.g. until the next round in the event loop\n **\/\n static void block();\n\n\n \/** The main event loop. Check interrupts, timers etc., and do callbacks. *\/\n static void event_loop();\n\n \/** Initialize platform, devices etc. *\/\n static void start(uint32_t boot_magic, uint32_t boot_addr);\n\n static void start(char *cmdline, uintptr_t mem_size);\n\n \/** Initialize common subsystems, call Service::start *\/\n static void post_start();\n\nprivate:\n \/** Process multiboot info. Called by 'start' if multibooted **\/\n static void multiboot(uint32_t boot_addr);\n\n static multiboot_info_t* bootinfo();\n\n \/** Boot with no multiboot params *\/\n static void legacy_boot();\n\n \/** Resume stuff from a soft reset **\/\n static bool is_softreset_magic(uint32_t value);\n static void resume_softreset(intptr_t boot_addr);\n\n static constexpr int PAGE_SHIFT = 12;\n static bool power_;\n static bool boot_sequence_passed_;\n static bool m_is_live_updated;\n static bool m_block_drivers_ready;\n static MHz cpu_mhz_;\n\n static RTC::timestamp_t booted_at_;\n static uintptr_t liveupdate_loc_;\n static std::string version_str_;\n static std::string arch_str_;\n static uintptr_t memory_end_;\n static uintptr_t heap_max_;\n static const uintptr_t elf_binary_size_;\n static const char* cmdline;\n\n \/\/ Prohibit copy and move operations\n OS(OS&) = delete;\n OS(OS&&) = delete;\n OS& operator=(OS&) = delete;\n OS& operator=(OS&&) = delete;\n ~OS() = delete;\n \/\/ Prohibit construction\n OS() = delete;\n\n friend void __platform_init();\n}; \/\/< OS\n\ninline bool OS::is_live_updated() noexcept {\n return OS::m_is_live_updated;\n}\n\ninline OS::Span_mods OS::modules()\n{\n auto* bootinfo_ = bootinfo();\n if (bootinfo_ and bootinfo_->flags & MULTIBOOT_INFO_MODS and bootinfo_->mods_count) {\n\n Expects(bootinfo_->mods_count < std::numeric_limits<int>::max());\n\n return Span_mods{\n reinterpret_cast<multiboot_module_t*>(bootinfo_->mods_addr),\n static_cast<int>(bootinfo_->mods_count) };\n }\n return nullptr;\n}\n\n#endif \/\/< KERNEL_OS_HPP\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <iostream>\n\nusing namespace std;\n\n\n\/* DIS DA COMPILA\n mainly an assortment of tools for the levels (or levels) to use\n has all the capabilities, but none of the drive\n levels take over and make use of it *\/\n\nclass Level{\npublic:\n vector<char> spec;\n vector<int (*)()> routes;\n Level* parent;\n\n Level(vector<char> s, vector<int (*)()> r, Level* p){\n if(s.size()==r.size()){\n spec = s;\n routes = r;\n parent = p;\n }\n else\n throw \"Special character and routine lists not of equal length!\";\n }\n\n int isSpec(char c){\n \/\/checks if c is a special char\n \/\/returns its index in spec[] if so, -1 otherwise\n\n int mid, low = 0, high = spec.size()-1;\n\n int ans;\n \n while (high > low){\n mid = (high+low)\/2;\n\n if (c <= spec[low])\n\treturn c == spec[low] ? low : -1;\n \n else if (c >= spec[high])\n\treturn c == spec[high] ? high : -1;\n\n else {\n\tchar diff = c - spec[mid];\n\tif (diff < 0) high = mid-1;\n\telse if (diff > 0) low = mid+1;\n\telse return mid;\n }\n }\n return -1;\n }\n\n int checkSpec(char c){\n int x = isSpec(c);\n if (x != -1)\n (*routes[x])();\n return x;\n }\n};\n\n\n#define MAXWL 100 \/\/max word length: 100\n\nLevel* clevel;\nchar wuff[MAXWL]; \/\/word buffer\nint wptr = 0; \/\/pointer to current position in word\n \nint add(char c){\n \/\/returns 1 for a sucessful add, 0 if the buffer is full or some other fail\n if (wptr < MAXWL){\n wuff[wptr++] = c;\n return 1;\n } else return 0;\n}\n\nvoid bead(char c){\n if (! clevel->checkSpec(c))\n add(c);\n}\n\nvector<char> cV(const char* c){\n vector<char> cv;\n\n while (*c != '\\0'){\n cv.push_back(*(c++)); \/\/would this work w\/o parens?\n }\n return cv;\n}\n\n#include \"levels.hpp\"\n\nint main(int argc, char *argv[]){\n try\n {\n clevel = new Root;\n } catch (const char* s) {\n cout << s << \"\\n\";\n }\n return 0;\n}\n\n\n\n \/\/this is it, a fresh start\n\n \/\/ int bead(char c)\n\n \/\/ sigh, ok major decision here. need to not rush, but come to a final conclusion\n \/\/ so this wont be a constant nagging question\n \/\/ do i want each level to simply have a giant function? so easy to do...\n \/\/ \t might not be as fast, but gets rid of ridiculous libraries of functions\n \/\/ \t is more free in the sense that the levels have no requirements besides have that one function that takes a char\n\n \/\/ \t or is it better to have the structure of words and special characters?\n \/\/ \t its a great way to have a very simple unobtrusive level of comprehension\n \/\/ \t all code will have variable names which will have no inherent meaning to the compiler\n \/\/ \t this stuff, if nothing else, is the words, and all else special characters [this is the way to do it, winner]\n\n \/\/ so, nothing should have to be done in terms of a 'normal function' (for handling non-special characters)\n \/\/ it should be standard, regardless of level, because it is simply making a word, and finding spec chars should be standardized,\n \/\/ so it is easy to ooptimize (without changing a bunch of code)\n\n \/\/ so yeah, as we know, a level needs a list of special chars and a list of equal length containing functions defining behavior when a special character is called or hit or whatever. [ok, sidenote: there should be a variable in the compiler that is the current character being dealt with. this way spec char funks can refernce this char and be the same funk while storing character specific info. (whew)]\n\n \/\/ the end result of this level of parsing is going to be very simple it is words and directions to other levels\n \/\/ pop + soda -> drank (simply a chain of words)\n \/\/ ( po + p ) + soda -> drank (enter sublevel (words) exit sublevel) words\n\n \/\/ it can be expressed as a list of objects that are either a word or a direction to another level\n \/\/ the next (separate) level of operation is the compiler starting at root level as current level, switcching whenever it comes upon those pobjects, and feeding th ewords from the other objects into whatever the current level is\n\n \/\/ it seems like that level will require functors or for each level to be a subclass of level (making them subclasses would be better)\n<commit_msg>all the goodies<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2015 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#ifndef CPM_IO_HPP\n#define CPM_IO_HPP\n\n#include <unistd.h>\n#include <algorithm>\n#include <iomanip>\n\n#include <sys\/stat.h>\n\nnamespace cpm {\n\ninline std::size_t max_path_length(){\n auto path_max = pathconf(\".\", _PC_PATH_MAX);\n if (path_max == -1){\n path_max = 1024;\n } else if (path_max > 10240){\n path_max = 10240;\n }\n return path_max;\n}\n\ninline std::string get_cwd(){\n auto path_max = max_path_length();\n\n char* buf = static_cast<char*>(malloc(sizeof(char) * path_max));\n if(!buf){\n return \"\";\n }\n\n char* ptr = getcwd(buf, path_max);\n if (!ptr) {\n return \"\";\n }\n\n std::string cwd = buf;\n\n free(buf);\n\n return cwd;\n}\n\ninline std::string make_absolute(const std::string& folder){\n auto path_max = max_path_length();\n\n char* buf = static_cast<char*>(malloc(sizeof(char) * path_max));\n if(!buf){\n return folder;\n }\n\n char* res = realpath(folder.c_str(), buf);\n\n if(!res){\n return folder;\n }\n\n std::string abs = buf;\n\n free(buf);\n\n return abs;\n}\n\ninline std::string get_free_file(const std::string& base_folder){\n std::size_t result_name = 0;\n std::string result_folder;\n\n struct stat buffer;\n do {\n ++result_name;\n result_folder = base_folder + std::to_string(result_name) + \".cpm\";\n } while(stat(result_folder.c_str(), &buffer) == 0);\n\n return std::to_string(result_name);\n}\n\ninline bool folder_exists(const std::string& folder){\n struct stat buffer;\n if (stat(folder.c_str(), &buffer) == 0 && S_ISDIR(buffer.st_mode)){\n return true;\n } else {\n return false;\n }\n}\n\ninline std::string url_encode(const std::string& value) {\n std::ostringstream escaped;\n escaped.fill('0');\n escaped << std::hex;\n\n for (auto i = value.begin(), n = value.end(); i != n; ++i) {\n auto c = *i;\n\n \/\/ Keep alphanumeric and other accepted characters intact\n if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {\n escaped << c;\n continue;\n }\n\n \/\/ Any other characters are percent-encoded\n escaped << '%' << std::setw(2) << int((unsigned char) c);\n }\n\n return escaped.str();\n}\n\ninline std::string filify(std::string name){\n std::string n{std::move(name)};\n\n \/\/Replace all spaces\n std::replace(n.begin(), n.end(), ' ', '_');\n\n \/\/Append extension\n n += \".html\";\n\n return n;\n}\n\ninline std::string filify(std::string compiler, std::string configuration){\n std::string n1{std::move(compiler)};\n std::string n2{std::move(configuration)};\n\n auto n = n1 + \"-\" + n2;\n\n return filify(n);\n}\n\ninline std::string filify(std::string compiler, std::string configuration, std::string bench){\n std::string n1{std::move(compiler)};\n std::string n2{std::move(configuration)};\n std::string n3{std::move(bench)};\n\n auto n = n1 + \"-\" + n2 + \"-\" + n3;\n\n return filify(n);\n}\n\n} \/\/end of namespace cpm\n\n#endif \/\/CPM_IO_HPP\n<commit_msg>Fix slashes<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2015 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#ifndef CPM_IO_HPP\n#define CPM_IO_HPP\n\n#include <unistd.h>\n#include <algorithm>\n#include <iomanip>\n\n#include <sys\/stat.h>\n\nnamespace cpm {\n\ninline std::size_t max_path_length(){\n auto path_max = pathconf(\".\", _PC_PATH_MAX);\n if (path_max == -1){\n path_max = 1024;\n } else if (path_max > 10240){\n path_max = 10240;\n }\n return path_max;\n}\n\ninline std::string get_cwd(){\n auto path_max = max_path_length();\n\n char* buf = static_cast<char*>(malloc(sizeof(char) * path_max));\n if(!buf){\n return \"\";\n }\n\n char* ptr = getcwd(buf, path_max);\n if (!ptr) {\n return \"\";\n }\n\n std::string cwd = buf;\n\n free(buf);\n\n return cwd;\n}\n\ninline std::string make_absolute(const std::string& folder){\n auto path_max = max_path_length();\n\n char* buf = static_cast<char*>(malloc(sizeof(char) * path_max));\n if(!buf){\n return folder;\n }\n\n char* res = realpath(folder.c_str(), buf);\n\n if(!res){\n return folder;\n }\n\n std::string abs = buf;\n\n free(buf);\n\n return abs;\n}\n\ninline std::string get_free_file(const std::string& base_folder){\n std::size_t result_name = 0;\n std::string result_folder;\n\n struct stat buffer;\n do {\n ++result_name;\n result_folder = base_folder + std::to_string(result_name) + \".cpm\";\n } while(stat(result_folder.c_str(), &buffer) == 0);\n\n return std::to_string(result_name);\n}\n\ninline bool folder_exists(const std::string& folder){\n struct stat buffer;\n if (stat(folder.c_str(), &buffer) == 0 && S_ISDIR(buffer.st_mode)){\n return true;\n } else {\n return false;\n }\n}\n\ninline std::string url_encode(const std::string& value) {\n std::ostringstream escaped;\n escaped.fill('0');\n escaped << std::hex;\n\n for (auto i = value.begin(), n = value.end(); i != n; ++i) {\n auto c = *i;\n\n \/\/ Keep alphanumeric and other accepted characters intact\n if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {\n escaped << c;\n continue;\n }\n\n \/\/ Any other characters are percent-encoded\n escaped << '%' << std::setw(2) << int((unsigned char) c);\n }\n\n return escaped.str();\n}\n\ninline std::string filify(std::string name){\n std::string n{std::move(name)};\n\n \/\/Replace all spaces\n std::replace(n.begin(), n.end(), ' ', '_');\n\n \/\/Replace all forward slashes\n std::replace(n.begin(), n.end(), '\/', '|');\n\n \/\/Append extension\n n += \".html\";\n\n return n;\n}\n\ninline std::string filify(std::string compiler, std::string configuration){\n std::string n1{std::move(compiler)};\n std::string n2{std::move(configuration)};\n\n auto n = n1 + \"-\" + n2;\n\n return filify(n);\n}\n\ninline std::string filify(std::string compiler, std::string configuration, std::string bench){\n std::string n1{std::move(compiler)};\n std::string n2{std::move(configuration)};\n std::string n3{std::move(bench)};\n\n auto n = n1 + \"-\" + n2 + \"-\" + n3;\n\n return filify(n);\n}\n\n} \/\/end of namespace cpm\n\n#endif \/\/CPM_IO_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef ERRORS_H_INCLUDED\n#define ERRORS_H_INCLUDED\n\n#include <iostream>\n#include <SDL.h>\n\n\/* Log a SDL error *\/\nstatic inline void logSDLError(const std::string &msg,\n std::ostream &os = std::cerr)\n{\n os << \"[SDL ] \" << msg << \" error: \" << SDL_GetError() << std::endl;\n}\n\n\/* Log a normal message *\/\nstatic inline void log(const std::string &msg, std::ostream &os = std::cout)\n{\n os << \"[ ] \" << msg << std::endl;\n}\n\n#endif \/* ERRORS_H_INCLUDED *\/\n<commit_msg>Error: adding raw error log<commit_after>#ifndef ERRORS_H_INCLUDED\n#define ERRORS_H_INCLUDED\n\n#include <iostream>\n#include <SDL.h>\n\n\/* Log a SDL error *\/\nstatic inline void logSDLError(const std::string &msg,\n std::ostream &os = std::cerr)\n{\n os << \"[SDL ] \" << msg << \" error: \" << SDL_GetError() << std::endl;\n}\n\n\/* Log a normal message *\/\nstatic inline void log(const std::string &msg, std::ostream &os = std::cout)\n{\n os << \"[ ] \" << msg << std::endl;\n}\n\n\/* Log a raw error *\/\nstatic inline void logError(const std::string &msg,\n std::ostream &os = std::cerr)\n{\n os << \"[XXXX] \" << msg << std::endl;\n}\n\n#endif \/* ERRORS_H_INCLUDED *\/\n<|endoftext|>"} {"text":"<commit_before>\/* json11\n *\n * json11 is a tiny JSON library for C++11, providing JSON parsing and\n * serialization.\n *\n * The core object provided by the library is json11::Json. A Json object\n * represents any JSON value: null, bool, number (int or double), string\n * (std::string), array (std::vector), or object (std::map).\n *\n * Json objects act like values: they can be assigned, copied, moved, compared\n * for equality or order, etc. There are also helper methods Json::dump, to\n * serialize a Json to a string, and Json::parse (static) to parse a std::string\n * as a Json object.\n *\n * Internally, the various types of Json object are represented by the JsonValue\n * class hierarchy.\n *\n * A note on numbers - JSON specifies the syntax of number formatting but not\n * its semantics, so some JSON implementations distinguish between integers and\n * floating-point numbers, while some don't. In json11, we choose the latter.\n * Because some JSON implementations (namely Javascript itself) treat all\n * numbers as the same type, distinguishing the two leads to JSON that will be\n * *silently* changed by a round-trip through those implementations. Dangerous!\n * To avoid that risk, json11 stores all numbers as double internally, but also\n * provides integer helpers.\n *\n * Fortunately, double-precision IEEE754 ('double') can precisely store any\n * integer in the range +\/-2^53, which includes every 'int' on most systems.\n * (Timestamps often use int64 or long long to avoid the Y2038K problem; a\n * double storing microseconds since some epoch will be exact for +\/- 275\n * years.)\n *\/\n\n\/* Copyright (c) 2013 Dropbox, Inc.\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\n#pragma once\n\n#include <initializer_list>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#ifdef _MSC_VER\n#if _MSC_VER <= 1800 \/\/ VS 2013\n#ifndef noexcept\n#define noexcept throw()\n#endif\n\n#ifndef snprintf\n#define snprintf _snprintf_s\n#endif\n#endif\n#endif\n\nnamespace json11 {\n\nenum JsonParse { STANDARD, COMMENTS };\n\nclass JsonValue;\n\nclass Json final {\n public:\n \/\/ Types\n enum Type { NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT };\n\n \/\/ Array and object typedefs\n typedef std::vector<Json> array;\n typedef std::map<std::string, Json> object_;\n\n \/\/ Constructors for the various types of JSON value.\n Json() noexcept; \/\/ NUL\n Json(std::nullptr_t) noexcept; \/\/ NUL\n Json(double value); \/\/ NUMBER\n Json(int value); \/\/ NUMBER\n Json(bool value); \/\/ BOOL\n Json(const std::string &value); \/\/ STRING\n Json(std::string &&value); \/\/ STRING\n Json(const char *value); \/\/ STRING\n Json(const array &values); \/\/ ARRAY\n Json(array &&values); \/\/ ARRAY\n Json(const object_ &values); \/\/ OBJECT\n Json(object_ &&values); \/\/ OBJECT\n\n \/\/ Implicit constructor: anything with a to_json() function.\n template <class T, class = decltype(&T::to_json)>\n Json(const T &t) : Json(t.to_json()) {}\n\n \/\/ Implicit constructor: map-like objects (std::map, std::unordered_map, etc)\n template <\n class M,\n typename std::enable_if<\n std::is_constructible<std::string, typename M::key_type>::value &&\n std::is_constructible<Json, typename M::mapped_type>::value,\n int>::type = 0>\n Json(const M &m) : Json(object_(m.begin(), m.end())) {}\n\n \/\/ Implicit constructor: vector-like objects (std::list, std::vector,\n \/\/ std::set, etc)\n template <class V,\n typename std::enable_if<\n std::is_constructible<Json, typename V::value_type>::value,\n int>::type = 0>\n Json(const V &v) : Json(array(v.begin(), v.end())) {}\n\n \/\/ This prevents Json(some_pointer) from accidentally producing a bool. Use\n \/\/ Json(bool(some_pointer)) if that behavior is desired.\n Json(void *) = delete;\n\n \/\/ Accessors\n Type type() const;\n\n bool is_null() const { return type() == NUL; }\n bool is_number() const { return type() == NUMBER; }\n bool is_bool() const { return type() == BOOL; }\n bool is_string() const { return type() == STRING; }\n bool is_array() const { return type() == ARRAY; }\n bool is_object() const { return type() == OBJECT; }\n\n \/\/ Return the enclosed value if this is a number, 0 otherwise. Note that\n \/\/ json11 does not distinguish between integer and non-integer numbers -\n \/\/ number_value() and int_value() can both be applied to a NUMBER-typed\n \/\/ object.\n double number_value() const;\n int int_value() const;\n\n \/\/ Return the enclosed value if this is a boolean, false otherwise.\n bool bool_value() const;\n \/\/ Return the enclosed string if this is a string, \"\" otherwise.\n const std::string &string_value() const;\n \/\/ Return the enclosed std::vector if this is an array, or an empty vector\n \/\/ otherwise.\n const array &array_items() const;\n \/\/ Return the enclosed std::map if this is an object, or an empty map\n \/\/ otherwise.\n const object_ &object_items() const;\n\n \/\/ Return a reference to arr[i] if this is an array, Json() otherwise.\n const Json &operator[](size_t i) const;\n \/\/ Return a reference to obj[key] if this is an object, Json() otherwise.\n const Json &operator[](const std::string &key) const;\n\n \/\/ Serialize.\n void dump(std::string &out) const;\n std::string dump() const {\n std::string out;\n dump(out);\n return out;\n }\n\n \/\/ Parse. If parse fails, return Json() and assign an error message to err.\n static Json parse(const std::string &in, std::string &err,\n JsonParse strategy = JsonParse::STANDARD);\n static Json parse(const char *in, std::string &err,\n JsonParse strategy = JsonParse::STANDARD) {\n if (in) {\n return parse(std::string(in), err, strategy);\n } else {\n err = \"null input\";\n return nullptr;\n }\n }\n \/\/ Parse multiple objects, concatenated or separated by whitespace\n static std::vector<Json> parse_multi(\n const std::string &in, std::string::size_type &parser_stop_pos,\n std::string &err, JsonParse strategy = JsonParse::STANDARD);\n\n static inline std::vector<Json> parse_multi(\n const std::string &in, std::string &err,\n JsonParse strategy = JsonParse::STANDARD) {\n std::string::size_type parser_stop_pos;\n return parse_multi(in, parser_stop_pos, err, strategy);\n }\n\n bool operator==(const Json &rhs) const;\n bool operator<(const Json &rhs) const;\n bool operator!=(const Json &rhs) const { return !(*this == rhs); }\n bool operator<=(const Json &rhs) const { return !(rhs < *this); }\n bool operator>(const Json &rhs) const { return (rhs < *this); }\n bool operator>=(const Json &rhs) const { return !(*this < rhs); }\n\n \/* has_shape(types, err)\n *\n * Return true if this is a JSON object and, for each item in types, has a\n * field of the given type. If not, return false and set err to a descriptive\n * message.\n *\/\n typedef std::initializer_list<std::pair<std::string, Type>> shape;\n bool has_shape(const shape &types, std::string &err) const;\n\n private:\n std::shared_ptr<JsonValue> m_ptr;\n};\n\n\/\/ Internal class hierarchy - JsonValue objects are not exposed to users of this\n\/\/ API.\nclass JsonValue {\n protected:\n friend class Json;\n friend class JsonInt;\n friend class JsonDouble;\n virtual Json::Type type() const = 0;\n virtual bool equals(const JsonValue *other) const = 0;\n virtual bool less(const JsonValue *other) const = 0;\n virtual void dump(std::string &out) const = 0;\n virtual double number_value() const;\n virtual int int_value() const;\n virtual bool bool_value() const;\n virtual const std::string &string_value() const;\n virtual const Json::array &array_items() const;\n virtual const Json &operator[](size_t i) const;\n virtual const Json::object_ &object_items() const;\n virtual const Json &operator[](const std::string &key) const;\n virtual ~JsonValue() {}\n};\n\n} \/\/ namespace json11\n<commit_msg>Change Json map\/vector conversions to invoke begin() directly<commit_after>\/* json11\n *\n * json11 is a tiny JSON library for C++11, providing JSON parsing and\n * serialization.\n *\n * The core object provided by the library is json11::Json. A Json object\n * represents any JSON value: null, bool, number (int or double), string\n * (std::string), array (std::vector), or object (std::map).\n *\n * Json objects act like values: they can be assigned, copied, moved, compared\n * for equality or order, etc. There are also helper methods Json::dump, to\n * serialize a Json to a string, and Json::parse (static) to parse a std::string\n * as a Json object.\n *\n * Internally, the various types of Json object are represented by the JsonValue\n * class hierarchy.\n *\n * A note on numbers - JSON specifies the syntax of number formatting but not\n * its semantics, so some JSON implementations distinguish between integers and\n * floating-point numbers, while some don't. In json11, we choose the latter.\n * Because some JSON implementations (namely Javascript itself) treat all\n * numbers as the same type, distinguishing the two leads to JSON that will be\n * *silently* changed by a round-trip through those implementations. Dangerous!\n * To avoid that risk, json11 stores all numbers as double internally, but also\n * provides integer helpers.\n *\n * Fortunately, double-precision IEEE754 ('double') can precisely store any\n * integer in the range +\/-2^53, which includes every 'int' on most systems.\n * (Timestamps often use int64 or long long to avoid the Y2038K problem; a\n * double storing microseconds since some epoch will be exact for +\/- 275\n * years.)\n *\/\n\n\/* Copyright (c) 2013 Dropbox, Inc.\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\n#pragma once\n\n#include <initializer_list>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#ifdef _MSC_VER\n#if _MSC_VER <= 1800 \/\/ VS 2013\n#ifndef noexcept\n#define noexcept throw()\n#endif\n\n#ifndef snprintf\n#define snprintf _snprintf_s\n#endif\n#endif\n#endif\n\nnamespace json11 {\n\nenum JsonParse { STANDARD, COMMENTS };\n\nclass JsonValue;\n\nclass Json final {\n public:\n \/\/ Types\n enum Type { NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT };\n\n \/\/ Array and object typedefs\n typedef std::vector<Json> array;\n typedef std::map<std::string, Json> object_;\n\n \/\/ Constructors for the various types of JSON value.\n Json() noexcept; \/\/ NUL\n Json(std::nullptr_t) noexcept; \/\/ NUL\n Json(double value); \/\/ NUMBER\n Json(int value); \/\/ NUMBER\n Json(bool value); \/\/ BOOL\n Json(const std::string &value); \/\/ STRING\n Json(std::string &&value); \/\/ STRING\n Json(const char *value); \/\/ STRING\n Json(const array &values); \/\/ ARRAY\n Json(array &&values); \/\/ ARRAY\n Json(const object_ &values); \/\/ OBJECT\n Json(object_ &&values); \/\/ OBJECT\n\n \/\/ Implicit constructor: anything with a to_json() function.\n template <class T, class = decltype(&T::to_json)>\n Json(const T &t) : Json(t.to_json()) {}\n\n \/\/ Implicit constructor: map-like objects (std::map, std::unordered_map, etc)\n template <\n class M,\n typename std::enable_if<\n std::is_constructible<\n std::string, decltype(std::declval<M>().begin()->first)>::value &&\n std::is_constructible<\n Json, decltype(std::declval<M>().begin()->second)>::value,\n int>::type = 0>\n Json(const M &m) : Json(object_(m.begin(), m.end())) {}\n\n \/\/ Implicit constructor: vector-like objects (std::list, std::vector,\n \/\/ std::set, etc)\n template <class V, typename std::enable_if<\n std::is_constructible<\n Json, decltype(*std::declval<V>().begin())>::value,\n int>::type = 0>\n Json(const V &v) : Json(array(v.begin(), v.end())) {}\n\n \/\/ This prevents Json(some_pointer) from accidentally producing a bool. Use\n \/\/ Json(bool(some_pointer)) if that behavior is desired.\n Json(void *) = delete;\n\n \/\/ Accessors\n Type type() const;\n\n bool is_null() const { return type() == NUL; }\n bool is_number() const { return type() == NUMBER; }\n bool is_bool() const { return type() == BOOL; }\n bool is_string() const { return type() == STRING; }\n bool is_array() const { return type() == ARRAY; }\n bool is_object() const { return type() == OBJECT; }\n\n \/\/ Return the enclosed value if this is a number, 0 otherwise. Note that\n \/\/ json11 does not distinguish between integer and non-integer numbers -\n \/\/ number_value() and int_value() can both be applied to a NUMBER-typed\n \/\/ object.\n double number_value() const;\n int int_value() const;\n\n \/\/ Return the enclosed value if this is a boolean, false otherwise.\n bool bool_value() const;\n \/\/ Return the enclosed string if this is a string, \"\" otherwise.\n const std::string &string_value() const;\n \/\/ Return the enclosed std::vector if this is an array, or an empty vector\n \/\/ otherwise.\n const array &array_items() const;\n \/\/ Return the enclosed std::map if this is an object, or an empty map\n \/\/ otherwise.\n const object_ &object_items() const;\n\n \/\/ Return a reference to arr[i] if this is an array, Json() otherwise.\n const Json &operator[](size_t i) const;\n \/\/ Return a reference to obj[key] if this is an object, Json() otherwise.\n const Json &operator[](const std::string &key) const;\n\n \/\/ Serialize.\n void dump(std::string &out) const;\n std::string dump() const {\n std::string out;\n dump(out);\n return out;\n }\n\n \/\/ Parse. If parse fails, return Json() and assign an error message to err.\n static Json parse(const std::string &in, std::string &err,\n JsonParse strategy = JsonParse::STANDARD);\n static Json parse(const char *in, std::string &err,\n JsonParse strategy = JsonParse::STANDARD) {\n if (in) {\n return parse(std::string(in), err, strategy);\n } else {\n err = \"null input\";\n return nullptr;\n }\n }\n \/\/ Parse multiple objects, concatenated or separated by whitespace\n static std::vector<Json> parse_multi(\n const std::string &in, std::string::size_type &parser_stop_pos,\n std::string &err, JsonParse strategy = JsonParse::STANDARD);\n\n static inline std::vector<Json> parse_multi(\n const std::string &in, std::string &err,\n JsonParse strategy = JsonParse::STANDARD) {\n std::string::size_type parser_stop_pos;\n return parse_multi(in, parser_stop_pos, err, strategy);\n }\n\n bool operator==(const Json &rhs) const;\n bool operator<(const Json &rhs) const;\n bool operator!=(const Json &rhs) const { return !(*this == rhs); }\n bool operator<=(const Json &rhs) const { return !(rhs < *this); }\n bool operator>(const Json &rhs) const { return (rhs < *this); }\n bool operator>=(const Json &rhs) const { return !(*this < rhs); }\n\n \/* has_shape(types, err)\n *\n * Return true if this is a JSON object and, for each item in types, has a\n * field of the given type. If not, return false and set err to a descriptive\n * message.\n *\/\n typedef std::initializer_list<std::pair<std::string, Type>> shape;\n bool has_shape(const shape &types, std::string &err) const;\n\n private:\n std::shared_ptr<JsonValue> m_ptr;\n};\n\n\/\/ Internal class hierarchy - JsonValue objects are not exposed to users of this\n\/\/ API.\nclass JsonValue {\n protected:\n friend class Json;\n friend class JsonInt;\n friend class JsonDouble;\n virtual Json::Type type() const = 0;\n virtual bool equals(const JsonValue *other) const = 0;\n virtual bool less(const JsonValue *other) const = 0;\n virtual void dump(std::string &out) const = 0;\n virtual double number_value() const;\n virtual int int_value() const;\n virtual bool bool_value() const;\n virtual const std::string &string_value() const;\n virtual const Json::array &array_items() const;\n virtual const Json &operator[](size_t i) const;\n virtual const Json::object_ &object_items() const;\n virtual const Json &operator[](const std::string &key) const;\n virtual ~JsonValue() {}\n};\n\n} \/\/ namespace json11\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip>\n#include <fstream>\n\nusing namespace std;\n\nclass Matrix\n{\nprivate:\n\tint **matr;\n\tint st, cl;\n\npublic:\n\tMatrix();\n\tMatrix(int, int);\n\tMatrix(const Matrix &matrc);\n\t~Matrix();\n\tint rows()const;\n\tint columns()const;\n\tMatrix operator+ (const Matrix &mat_2) const;\n\tMatrix operator* (const Matrix &mat_2) const;\n\tMatrix& operator =(Matrix &);\n\tbool operator==(const Matrix&)const;\n\tfriend istream& operator >> (istream& ist, Matrix& cmatr);\n\tfriend ostream& operator << (ostream&, const Matrix&);\n};\n<commit_msg>Update matrix.hpp<commit_after>#include <iostream> \n#include <string> \n#include <fstream> \n#include <cstdint> \n\nusing namespace std;\n\ntemplate <typename T>\nstruct Node\n{\n\tNode *left;\n\tNode *right;\n\tT data;\n};\n\ntemplate <typename T>\nclass BinaryTree;\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream&, const BinaryTree<T>&);\n\ntemplate <typename T>\nclass BinaryTree\n{\nprivate:\n\tNode<T>*root;\n\tint count = 0;\npublic:\n\tBinaryTree();\n\t~BinaryTree();\n\tNode<T>* root_();\n\tunsigned int getCount()const;\n\tNode<T> *findNode(const T&, Node<T>*)const;\n\tvoid insertNode(const T&x);\n\tvoid deleteNode(Node<T>* temp);\n\tbool removeElement(Node<T>* parent, Node<T>* current, const T& val);\n\tbool deleteValue(const T& value);\n\tvoid write(const std::string& filename)const;\n\tfriend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);\n};\n\ntemplate <typename T>\nBinaryTree<T>::BinaryTree()\n{\n\troot = nullptr;\n}\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::root_()\n{\n\treturn root;\n}\n\ntemplate <typename T>\nBinaryTree<T>::~BinaryTree()\n{\n\tdeleteNode(root);\n}\n\ntemplate <typename T>\nunsigned int BinaryTree<T>::getCount()const\n{\n\treturn count;\n}\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::findNode(const T& data, Node<T>* temp) const\n{\n\tif (temp == 0 || data == temp->data)\n\t\treturn temp;\n\tif (data > temp->data)\n\t\treturn findNode(data, temp->right);\n\telse\n\t\treturn findNode(data, temp->left);\n}\n\ntemplate<typename T>\nvoid BinaryTree<T>::insertNode(const T&x)\n{\n\tif (findNode(x, root_())) return;\n\tNode<T>* Tree = new Node<T>;\n\tMyTree->data = x;\n\tMyTree->left = Tree->right = 0;\n\tNode<T>* buff = root;\n\tNode<T>* temp = root;\n\twhile (temp)\n\t{\n\t\tbuff = temp;\n\t\tif (x < temp->data)\n\t\t\ttemp = temp->left;\n\t\telse\n\t\t\ttemp = temp->right;\n\t}\n\tif (!buff)\n\t\troot = Tree;\n\telse\n\t{\n\t\tif (x < buff->data)\n\t\t\tbuff->left = Tree;\n\t\telse\n\t\t\tbuff->right = Tree;\n\t}\n\t++count;\n}\n\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::write(const std::string& filename)const\n{\n\tofstream file_1(filename);\n\tfile_1 << count << \"\\t\";\n\toutput(file_1, root);\n\tfile_1.close();\n}\n\ntemplate<typename T>\nvoid BinaryTree<T>::deleteNode(Node<T>* temp)\n{\n\tif (!temp)\n\t\treturn;\n\tif (temp->left)\n\t{\n\t\tdeleteNode(temp->left);\n\t\ttemp->left = nullptr;\n\t}\n\n\tif (temp->right)\n\t{\n\t\tdeleteNode(temp->right);\n\t\ttemp->right = nullptr;\n\t}\n\tdelete temp;\n}\n\ntemplate <typename T>\nstd::ostream& output(std::ostream& out, const Node<T>* node, unsigned int level)\n{\n\tif (!node)\n\t\treturn out;\n\toutput(out, node->right, level + 1);\n\tfor (unsigned int i = 0; i < level; i++)\n\t\tout << \"\\t\";\n\tout << node->data << std::endl;\n\toutput(out, node->left, level + 1);\n\treturn out;\n}\n\ntemplate<typename T>\nbool BinaryTree<T>::removeElement(Node<T>* parent, Node<T>* current, const T& val)\n{\n\tif (!current) return false;\n\tif (current->data == val)\n\t{\n\t\tif (current->left == NULL || current->right == NULL) {\n\t\t\tNode<T>* temp = current->left;\n\t\t\tif (current->right) temp = current->right;\n\t\t\tif (parent) {\n\t\t\t\tif (parent->left == current) {\n\t\t\t\t\tparent->left = temp;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tparent->right = temp;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis->root = temp;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tNode<T>* validSubs = current->right;\n\t\t\twhile (validSubs->left) {\n\t\t\t\tvalidSubs = validSubs->left;\n\t\t\t}\n\t\t\tT temp = current->data;\n\t\t\tcurrent->data = validSubs->data;\n\t\t\tvalidSubs->data = temp;\n\t\t\treturn removeElement(current, current->right, temp);\n\t\t}\n\t\tdelete current;\n\t\tcount--;\n\t\treturn true;\n\t}\n\tif (current->data > val)\n\t\treturn removeElement(current, current->left, val);\n\telse\n\t\treturn removeElement(current, current->right, val);\n}\n\ntemplate<typename T>\nbool BinaryTree<T>::deleteValue(const T& value)\n{\n\treturn this->removeElement(NULL, root, value);\n}\n\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& out, const BinaryTree<T>& temp)\n{\n\toutput(out, temp.root, 0);\n\treturn out;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n** Copyright 1994 by Miron Livny, and Mike Litzkow\n** \n** Permission to use, copy, modify, and distribute this software and its\n** documentation for any purpose and without fee is hereby granted,\n** provided that the above copyright notice appear in all copies and that\n** both that copyright notice and this permission notice appear in\n** supporting documentation, and that the names of the University of\n** Wisconsin and the copyright holders not be used in advertising or\n** publicity pertaining to distribution of the software without specific,\n** written prior permission. The University of Wisconsin and the \n** copyright holders make no representations about the suitability of this\n** software for any purpose. It is provided \"as is\" without express\n** or implied warranty.\n** \n** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL\n** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES\n** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF\n** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT\n** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE\n** OR PERFORMANCE OF THIS SOFTWARE.\n** \n** Author: Mike Greger\n**\n*\/ \n\n#include \"image.h\"\n#include <unistd.h>\n#include <stdio.h>\n#include <sys\/mman.h>\n#include \"condor_debug.h\"\n#include \"condor_syscalls.h\"\n\n\n\/\/ Class to hold proc file system stuff\nclass Proc {\npublic:\n\tProc();\n\tvoid read_proc();\n\tlong data_start_addr();\n\tlong data_end_addr();\n\tlong stack_start_addr();\n\tlong stack_end_addr();\nprivate:\n\tlong\tproc_pid;\n\tchar\tproc_comm[PATH_MAX];\n\tchar\tproc_state;\n\tlong\tproc_ppid;\n\tlong\tproc_pgrp;\n\tlong\tproc_session;\n\tlong\tproc_tty;\n\tlong\tproc_tpgid;\n\tunsigned long\tproc_flags;\n\tunsigned long\tproc_min_flt;\n\tunsigned long\tproc_cmin_flt;\n\tunsigned long\tproc_maj_flt;\n\tunsigned long\tproc_cmaj_flt;\n\tlong\tproc_utime;\n\tlong\tproc_stime;\n\tlong\tproc_cutime;\n\tlong\tproc_cstime;\n\tlong\tproc_priority;\n\tlong\tproc_nice;\n\tunsigned long\tproc_timeout;\n\tunsigned long\tproc_it_real_value;\n\tlong\tproc_start_time;\n\tunsigned long\tproc_vsize;\n\tunsigned long\tproc_rss;\n\tunsigned long\tproc_rlim;\n\tunsigned long\tproc_start_code;\n\tunsigned long\tproc_end_code;\n\tunsigned long\tproc_stack_start_addr;\n\tunsigned long\tproc_kstk_esp;\n\tunsigned long\tproc_kstk_eip;\n\tlong\tproc_signal;\n\tlong\tproc_blocked;\n\tlong\tproc_sigignore;\n\tlong\tproc_sigcatch;\n\tunsigned long\tproc_wchan;\n\tlong\tproc_stack_end_addr;\n};\n\nProc::Proc()\n{\n}\n\nvoid Proc::read_proc()\n{\n\tint\t\tscm;\n\tpid_t\t\tpid;\n\tFILE\t\t*proc;\n\tchar\t\tfn[PATH_MAX];\n\tunsigned long\ttmp_u;\n\n\n scm = SetSyscalls( SYS_LOCAL | SYS_UNMAPPED );\n pid = getpid();\n\n\tsprintf(fn ,\"\/proc\/%d\/stat\", pid);\n proc=fopen(fn, \"r\");\n\tif(!proc) {\n\t\tprintf(\"Can't open %s for reading\\n\", fn);\n\t}\n\n\tfscanf(proc, \"%d %s %c %d %d %d %d %d\",\n\t\t&proc_pid, proc_comm, &proc_state, &proc_ppid, &proc_pgrp,\n\t\t&proc_session, &proc_tty, &proc_tpgid);\n\tfscanf(proc, \"%u %u %u %u %u\",\n\t\t&proc_flags, &proc_min_flt, &proc_cmin_flt,\n\t\t&proc_maj_flt, &proc_cmaj_flt);\n\tfscanf(proc, \"%d %d %d %d %d %d\",\n\t\t&proc_utime, &proc_stime, &proc_cutime, &proc_cstime, \n\t\t&proc_priority, &proc_nice);\n\tfscanf(proc, \"%u %u %d\",\n\t\t&proc_timeout, &proc_it_real_value, &proc_start_time);\n\tfscanf(proc, \"%u %u %u %u %u %u %u %u %u\",\n\t\t&proc_vsize, &proc_rss, &proc_rlim, &proc_start_code,\n\t\t&proc_end_code, &tmp_u, &proc_stack_start_addr, &proc_kstk_esp,\n\t\t&proc_kstk_eip); \/* FIXME - Greger This works, but why? *\/\n\t\/*`\n\tfscanf(proc, \"%d %d %d %d %u\",\n\t\t&proc_signal, &proc_blocked, &proc_sigignore, &proc_sigcatch,\n\t\t&proc_wchan);*\/\n\n fclose(proc);\n\tSetSyscalls(scm);\n\tproc_stack_end_addr = 0xbfffffff;\n}\n\n\nlong Proc::data_start_addr()\n{\n\tread_proc();\n\treturn((long)((proc_end_code+7) & ~7)+4096); \/\/ Odd, isn't it!\n}\n\nlong Proc::data_end_addr()\n{\n\treturn(long)sbrk(0);\n}\n\nlong Proc::stack_start_addr()\n{\n\tread_proc();\n\treturn((long)proc_stack_start_addr & ~4095);\n}\n\nlong Proc::stack_end_addr()\n{\n\tread_proc();\n\treturn((long)proc_stack_end_addr);\n}\n\n\/*\n Return starting address of the data segment\n*\/\nlong\ndata_start_addr()\n{\n\tProc\tp;\n\t\/*printf(\"Data Start: 0x%x\\n\", p.data_start_addr());*\/\n\treturn(p.data_start_addr());\n}\n\n\/*\n Return ending address of the data segment\n*\/\nlong\ndata_end_addr()\n{\n\tProc\tp;\n\t\/*printf(\"Data End : 0x%x\\n\", p.data_end_addr());*\/\n\treturn(p.data_end_addr());\n}\n\n\/*\n Return TRUE if the stack grows toward lower addresses, and FALSE\n otherwise.\n*\/\nBOOL StackGrowsDown()\n{\n\treturn TRUE;\n}\n\n\/*\n Return the index into the jmp_buf where the stack pointer is stored.\n Expect that the jmp_buf will be viewed as an array of integers for\n this.\n*\/\nint JmpBufSP_Index()\n{\n\treturn 4;\n}\n\n\/*\n Return starting address of stack segment.\n*\/\nlong\nstack_start_addr()\n{\n\tProc\tp;\n\treturn(p.stack_start_addr());\n}\n\n\/*\n Return ending address of stack segment.\n*\/\nlong\nstack_end_addr()\n{\n\tProc\tp;\n\treturn(p.stack_end_addr());\n}\n\n\/*\n Patch any registers whose vaules should be different at restart\n time than they were at checkpoint time.\n*\/\nvoid\npatch_registers( void *generic_ptr )\n{\n\t\/\/Any Needed?? Don't think so.\n}\n\n\n\n\/\/ Support for shared library linking\n\/\/ Written by Michael J. Greger (greger@cae.wisc.edu) August, 1996\n\/\/ Based on Solaris port by Mike Litzkow\n\n\nstruct map_t {\n\tlong\tmem_start;\n\tlong\tmem_end;\n\tlong\toffset;\n\tint\t\tprot;\n\tint\t\tflags;\n\tint\t\tinode;\n\tchar\tr, w, x, p;\n};\n\nstatic map_t\tmy_map[MAX_SEGS];\nstatic int\t\tmap_count=0;\nstatic int\t\ttext_loc=-1, stack_loc=-1, heap_loc=-1;\n\nint find_map_for_addr(long addr)\n{\n\tint\t\ti;\n\n\tfprintf(stderr, \"Finding map for addr:0x%x (map_cnt=%d)\\n\", addr, map_count);\n\tfor(i=0;i<map_count;i++) {\n\t\tfprintf(stderr, \"0x%x 0x%x\\n\", my_map[i].mem_start, my_map[i].mem_end);\n\t\tif(addr >= my_map[i].mem_start && addr <= my_map[i].mem_end) {\n\t\t\tfprintf(stderr, \" Found:%d\\n\", i);\n\t\t\treturn i;\n\t\t}\n\t}\n\tfprintf(stderr, \" NOT Found\\n\");\n\treturn -1;\n}\n\n\nint num_segments()\n{\n\tFILE\t*pfs;\n\tchar\tproc[128];\n\tchar\trperm, wperm, xperm, priv;\n\tint\t\tscm;\n\tint\t\tnum_seg=0;\n\tint\t\tmajor, minor, inode;\n\tlong\tmem_start, mem_end;\n\tlong\toffset;\n\tchar\te, f;\n\n\n\tscm=SetSyscalls(SYS_LOCAL | SYS_UNMAPPED);\n\n\tsprintf(proc, \"\/proc\/%d\/maps\", syscall(SYS_getpid));\n\tpfs=fopen(proc, \"r\");\n\tif(!pfs) {\n\t\tSetSyscalls(scm);\n\t\treturn -1;\n\t}\n\n\t\/\/ Count the numer of mmapped files in use by the executable\n\twhile(!feof(pfs)) {\n\t\tfscanf(pfs, \"%x-%x %c%c%c%c %x %d:%d %d\\n\",\n\t\t\t&mem_start, &mem_end, &rperm, &wperm,\n\t\t\t&xperm, &priv, &offset, &major, &minor, &inode);\n\t\tfprintf(stderr, \"0x%x 0x%x %c%c%c%c 0x%x %d:%d %d\\n\", \n\t\t\tmem_start, mem_end, rperm, wperm, xperm, priv,\n\t\t\toffset, major, minor, inode);\n\t\tmy_map[num_seg].mem_start=mem_start;\n\t\tmy_map[num_seg].mem_end=mem_end-1;\n\t\t\/* FIXME - Greger *\/\n\t\tif(my_map[num_seg].mem_end-my_map[num_seg].mem_start==0x34000-1)\n\t\t\tmy_map[num_seg].mem_end=my_map[num_seg].mem_start+0x320ff;\n\t\tmy_map[num_seg].offset=offset;\n\t\tmy_map[num_seg].prot=(rperm=='r'?PROT_READ:0) |\n\t\t\t\t\t\t\t (wperm=='w'?PROT_WRITE:0) |\n\t\t\t\t\t\t\t (xperm=='x'?PROT_EXEC:0);\n\t\tmy_map[num_seg].flags=(priv=='p'?:0);\n\t\tmy_map[num_seg].inode=inode;\n\t\tmy_map[num_seg].r=rperm;\n\t\tmy_map[num_seg].w=wperm;\n\t\tmy_map[num_seg].x=xperm;\n\t\tmy_map[num_seg].p=priv;\n\t\tnum_seg++;\n\t}\n\tfclose(pfs);\n\n\tmap_count=num_seg;\n\ttext_loc=find_map_for_addr((long)num_segments);\n\tif(StackGrowsDown())\n\t\tstack_loc=find_map_for_addr((long)stack_end_addr());\n\telse\n\t\tstack_loc=find_map_for_addr((long)stack_start_addr());\n\theap_loc=find_map_for_addr((long)data_start_addr());\n\n\tfprintf(stderr, \"%d segments\\n\", num_seg);\n\tSetSyscalls(scm);\n\treturn num_seg;\n}\n\nint segment_bounds(int seg_num, RAW_ADDR &start, RAW_ADDR &end, int &prot)\n{\n\tstart=(long)my_map[seg_num].mem_start;\n\tend=(long)my_map[seg_num].mem_end;\n\tprot=my_map[seg_num].prot;\n\tif(seg_num==text_loc)\n\t\treturn 1;\n\telse if(seg_num==stack_loc)\n\t\treturn 2;\n\telse if(seg_num==heap_loc || \n\t\t(my_map[seg_num].mem_start >= data_start_addr() &&\n\t\t my_map[seg_num].mem_start <= data_end_addr()))\n\t \treturn 3;\n\t\/\/else if(!my_map[seg_num].inode)\n\t\t\/\/return 1;\n\n\treturn 0;\n}\n\nstruct ma_flags {\n\tint \tflag_val;\n\tchar\t*flag_name;\n};\n\nvoid display_prmap()\n{\n\tint\t\ti;\n\n\tfor(i=0;i<map_count;i++) {\n\t\tdprintf(D_ALWAYS, \"addr= 0x%p, size= 0x%lx, offset= 0x%x\\n\",\n\t\t\tmy_map[i].mem_start, my_map[i].mem_end-my_map[i].mem_start,\n\t\t\tmy_map[i].offset);\n\t\tdprintf(D_ALWAYS, \"Flags: %c%c%c%c inode %d\\n\", \n\t\t\tmy_map[i].r, my_map[i].w, my_map[i].x, my_map[i].p,\n\t\t\tmy_map[i].inode);\n\t}\n}\n\n\/*\n * This is a hack! The values found in \/proc\/pid\/maps do not always seem\n * to be correct. This function works its way down from the end addr\n * until it finds an addr that we can read from... - Greger\n *\/\nunsigned long find_correct_vm_addr(unsigned long start, unsigned long end,\n\tint prot)\n{\n\n\tif((mprotect((char *)start, end-start, PROT_READ))==0) {\n\t\t\/*\n\t\t * We were allowed to do read access to the chunk. Change\n\t\t * protection back to what it was before the call.\n\t\t *\/\n\t\tif((mprotect((char *)start, end-start, prot))==0) {\n\t\t\treturn end;\n\t\t} else {\n\t\t\tdprintf(D_ALWAYS, \"Fatal error, Can't restore memory protection\\n\");\n\t\t}\n\t} else {\n\t\t\/*\n\t\t * We were not allowed read permission to the whole block. Find\n\t\t * a smaller block that we do have access to...\n\t\t *\/\n\t\tfor(;end>start;end-=4) { \/* Most lib stuff is alligned on 4 bytes or less??... *\/\n\t\t\tif((mprotect((char *)start, end-start, PROT_READ))==0) {\n\t\t\t\t\/*\n\t\t \t\t* We were allowed to do read access to the chunk. Change\n\t\t \t\t* protection back to what it was before the call.\n\t\t \t\t*\/\n\t\t\t\tif((mprotect((char *)start, end-start, prot))==0) {\n\t\t\t\t\treturn end;\n\t\t\t\t} else {\n\t\t\t\t\tdprintf(D_ALWAYS, \"Fatal error, Can't restore memory protection\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdprintf(D_ALWAYS, \"Fatal error, Can't read any of this block\\n\");\n\t}\n}\n\n\n\n<commit_msg> In find_correct_vm_addr(), since we're calling mprotect(), we need to be in local syscall mode.<commit_after>\/* \n** Copyright 1994 by Miron Livny, and Mike Litzkow\n** \n** Permission to use, copy, modify, and distribute this software and its\n** documentation for any purpose and without fee is hereby granted,\n** provided that the above copyright notice appear in all copies and that\n** both that copyright notice and this permission notice appear in\n** supporting documentation, and that the names of the University of\n** Wisconsin and the copyright holders not be used in advertising or\n** publicity pertaining to distribution of the software without specific,\n** written prior permission. The University of Wisconsin and the \n** copyright holders make no representations about the suitability of this\n** software for any purpose. It is provided \"as is\" without express\n** or implied warranty.\n** \n** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL\n** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES\n** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF\n** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT\n** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE\n** OR PERFORMANCE OF THIS SOFTWARE.\n** \n** Author: Mike Greger\n**\n*\/ \n\n#include \"image.h\"\n#include <unistd.h>\n#include <stdio.h>\n#include <sys\/mman.h>\n#include \"condor_debug.h\"\n#include \"condor_syscalls.h\"\n\n\n\/\/ Class to hold proc file system stuff\nclass Proc {\npublic:\n\tProc();\n\tvoid read_proc();\n\tlong data_start_addr();\n\tlong data_end_addr();\n\tlong stack_start_addr();\n\tlong stack_end_addr();\nprivate:\n\tlong\tproc_pid;\n\tchar\tproc_comm[PATH_MAX];\n\tchar\tproc_state;\n\tlong\tproc_ppid;\n\tlong\tproc_pgrp;\n\tlong\tproc_session;\n\tlong\tproc_tty;\n\tlong\tproc_tpgid;\n\tunsigned long\tproc_flags;\n\tunsigned long\tproc_min_flt;\n\tunsigned long\tproc_cmin_flt;\n\tunsigned long\tproc_maj_flt;\n\tunsigned long\tproc_cmaj_flt;\n\tlong\tproc_utime;\n\tlong\tproc_stime;\n\tlong\tproc_cutime;\n\tlong\tproc_cstime;\n\tlong\tproc_priority;\n\tlong\tproc_nice;\n\tunsigned long\tproc_timeout;\n\tunsigned long\tproc_it_real_value;\n\tlong\tproc_start_time;\n\tunsigned long\tproc_vsize;\n\tunsigned long\tproc_rss;\n\tunsigned long\tproc_rlim;\n\tunsigned long\tproc_start_code;\n\tunsigned long\tproc_end_code;\n\tunsigned long\tproc_stack_start_addr;\n\tunsigned long\tproc_kstk_esp;\n\tunsigned long\tproc_kstk_eip;\n\tlong\tproc_signal;\n\tlong\tproc_blocked;\n\tlong\tproc_sigignore;\n\tlong\tproc_sigcatch;\n\tunsigned long\tproc_wchan;\n\tlong\tproc_stack_end_addr;\n};\n\nProc::Proc()\n{\n}\n\nvoid Proc::read_proc()\n{\n\tint\t\tscm;\n\tpid_t\t\tpid;\n\tFILE\t\t*proc;\n\tchar\t\tfn[PATH_MAX];\n\tunsigned long\ttmp_u;\n\n\n scm = SetSyscalls( SYS_LOCAL | SYS_UNMAPPED );\n pid = getpid();\n\n\tsprintf(fn ,\"\/proc\/%d\/stat\", pid);\n proc=fopen(fn, \"r\");\n\tif(!proc) {\n\t\tprintf(\"Can't open %s for reading\\n\", fn);\n\t}\n\n\tfscanf(proc, \"%d %s %c %d %d %d %d %d\",\n\t\t&proc_pid, proc_comm, &proc_state, &proc_ppid, &proc_pgrp,\n\t\t&proc_session, &proc_tty, &proc_tpgid);\n\tfscanf(proc, \"%u %u %u %u %u\",\n\t\t&proc_flags, &proc_min_flt, &proc_cmin_flt,\n\t\t&proc_maj_flt, &proc_cmaj_flt);\n\tfscanf(proc, \"%d %d %d %d %d %d\",\n\t\t&proc_utime, &proc_stime, &proc_cutime, &proc_cstime, \n\t\t&proc_priority, &proc_nice);\n\tfscanf(proc, \"%u %u %d\",\n\t\t&proc_timeout, &proc_it_real_value, &proc_start_time);\n\tfscanf(proc, \"%u %u %u %u %u %u %u %u %u\",\n\t\t&proc_vsize, &proc_rss, &proc_rlim, &proc_start_code,\n\t\t&proc_end_code, &tmp_u, &proc_stack_start_addr, &proc_kstk_esp,\n\t\t&proc_kstk_eip); \/* FIXME - Greger This works, but why? *\/\n\t\/*`\n\tfscanf(proc, \"%d %d %d %d %u\",\n\t\t&proc_signal, &proc_blocked, &proc_sigignore, &proc_sigcatch,\n\t\t&proc_wchan);*\/\n\n fclose(proc);\n\tSetSyscalls(scm);\n\tproc_stack_end_addr = 0xbfffffff;\n}\n\n\nlong Proc::data_start_addr()\n{\n\tread_proc();\n\treturn((long)((proc_end_code+7) & ~7)+4096); \/\/ Odd, isn't it!\n}\n\nlong Proc::data_end_addr()\n{\n\treturn(long)sbrk(0);\n}\n\nlong Proc::stack_start_addr()\n{\n\tread_proc();\n\treturn((long)proc_stack_start_addr & ~4095);\n}\n\nlong Proc::stack_end_addr()\n{\n\tread_proc();\n\treturn((long)proc_stack_end_addr);\n}\n\n\/*\n Return starting address of the data segment\n*\/\nlong\ndata_start_addr()\n{\n\tProc\tp;\n\t\/*printf(\"Data Start: 0x%x\\n\", p.data_start_addr());*\/\n\treturn(p.data_start_addr());\n}\n\n\/*\n Return ending address of the data segment\n*\/\nlong\ndata_end_addr()\n{\n\tProc\tp;\n\t\/*printf(\"Data End : 0x%x\\n\", p.data_end_addr());*\/\n\treturn(p.data_end_addr());\n}\n\n\/*\n Return TRUE if the stack grows toward lower addresses, and FALSE\n otherwise.\n*\/\nBOOL StackGrowsDown()\n{\n\treturn TRUE;\n}\n\n\/*\n Return the index into the jmp_buf where the stack pointer is stored.\n Expect that the jmp_buf will be viewed as an array of integers for\n this.\n*\/\nint JmpBufSP_Index()\n{\n\treturn 4;\n}\n\n\/*\n Return starting address of stack segment.\n*\/\nlong\nstack_start_addr()\n{\n\tProc\tp;\n\treturn(p.stack_start_addr());\n}\n\n\/*\n Return ending address of stack segment.\n*\/\nlong\nstack_end_addr()\n{\n\tProc\tp;\n\treturn(p.stack_end_addr());\n}\n\n\/*\n Patch any registers whose vaules should be different at restart\n time than they were at checkpoint time.\n*\/\nvoid\npatch_registers( void *generic_ptr )\n{\n\t\/\/Any Needed?? Don't think so.\n}\n\n\n\n\/\/ Support for shared library linking\n\/\/ Written by Michael J. Greger (greger@cae.wisc.edu) August, 1996\n\/\/ Based on Solaris port by Mike Litzkow\n\n\nstruct map_t {\n\tlong\tmem_start;\n\tlong\tmem_end;\n\tlong\toffset;\n\tint\t\tprot;\n\tint\t\tflags;\n\tint\t\tinode;\n\tchar\tr, w, x, p;\n};\n\nstatic map_t\tmy_map[MAX_SEGS];\nstatic int\t\tmap_count=0;\nstatic int\t\ttext_loc=-1, stack_loc=-1, heap_loc=-1;\n\nint find_map_for_addr(long addr)\n{\n\tint\t\ti;\n\n\tfprintf(stderr, \"Finding map for addr:0x%x (map_cnt=%d)\\n\", addr, map_count);\n\tfor(i=0;i<map_count;i++) {\n\t\tfprintf(stderr, \"0x%x 0x%x\\n\", my_map[i].mem_start, my_map[i].mem_end);\n\t\tif(addr >= my_map[i].mem_start && addr <= my_map[i].mem_end) {\n\t\t\tfprintf(stderr, \" Found:%d\\n\", i);\n\t\t\treturn i;\n\t\t}\n\t}\n\tfprintf(stderr, \" NOT Found\\n\");\n\treturn -1;\n}\n\n\nint num_segments()\n{\n\tFILE\t*pfs;\n\tchar\tproc[128];\n\tchar\trperm, wperm, xperm, priv;\n\tint\t\tscm;\n\tint\t\tnum_seg=0;\n\tint\t\tmajor, minor, inode;\n\tlong\tmem_start, mem_end;\n\tlong\toffset;\n\tchar\te, f;\n\n\n\tscm=SetSyscalls(SYS_LOCAL | SYS_UNMAPPED);\n\n\tsprintf(proc, \"\/proc\/%d\/maps\", syscall(SYS_getpid));\n\tpfs=fopen(proc, \"r\");\n\tif(!pfs) {\n\t\tSetSyscalls(scm);\n\t\treturn -1;\n\t}\n\n\t\/\/ Count the numer of mmapped files in use by the executable\n\twhile(!feof(pfs)) {\n\t\tfscanf(pfs, \"%x-%x %c%c%c%c %x %d:%d %d\\n\",\n\t\t\t&mem_start, &mem_end, &rperm, &wperm,\n\t\t\t&xperm, &priv, &offset, &major, &minor, &inode);\n\t\tfprintf(stderr, \"0x%x 0x%x %c%c%c%c 0x%x %d:%d %d\\n\", \n\t\t\tmem_start, mem_end, rperm, wperm, xperm, priv,\n\t\t\toffset, major, minor, inode);\n\t\tmy_map[num_seg].mem_start=mem_start;\n\t\tmy_map[num_seg].mem_end=mem_end-1;\n\t\t\/* FIXME - Greger *\/\n\t\tif(my_map[num_seg].mem_end-my_map[num_seg].mem_start==0x34000-1)\n\t\t\tmy_map[num_seg].mem_end=my_map[num_seg].mem_start+0x320ff;\n\t\tmy_map[num_seg].offset=offset;\n\t\tmy_map[num_seg].prot=(rperm=='r'?PROT_READ:0) |\n\t\t\t\t\t\t\t (wperm=='w'?PROT_WRITE:0) |\n\t\t\t\t\t\t\t (xperm=='x'?PROT_EXEC:0);\n\t\tmy_map[num_seg].flags=(priv=='p'?:0);\n\t\tmy_map[num_seg].inode=inode;\n\t\tmy_map[num_seg].r=rperm;\n\t\tmy_map[num_seg].w=wperm;\n\t\tmy_map[num_seg].x=xperm;\n\t\tmy_map[num_seg].p=priv;\n\t\tnum_seg++;\n\t}\n\tfclose(pfs);\n\n\tmap_count=num_seg;\n\ttext_loc=find_map_for_addr((long)num_segments);\n\tif(StackGrowsDown())\n\t\tstack_loc=find_map_for_addr((long)stack_end_addr());\n\telse\n\t\tstack_loc=find_map_for_addr((long)stack_start_addr());\n\theap_loc=find_map_for_addr((long)data_start_addr());\n\n\tfprintf(stderr, \"%d segments\\n\", num_seg);\n\tSetSyscalls(scm);\n\treturn num_seg;\n}\n\nint segment_bounds(int seg_num, RAW_ADDR &start, RAW_ADDR &end, int &prot)\n{\n\tstart=(long)my_map[seg_num].mem_start;\n\tend=(long)my_map[seg_num].mem_end;\n\tprot=my_map[seg_num].prot;\n\tif(seg_num==text_loc)\n\t\treturn 1;\n\telse if(seg_num==stack_loc)\n\t\treturn 2;\n\telse if(seg_num==heap_loc || \n\t\t(my_map[seg_num].mem_start >= data_start_addr() &&\n\t\t my_map[seg_num].mem_start <= data_end_addr()))\n\t \treturn 3;\n\t\/\/else if(!my_map[seg_num].inode)\n\t\t\/\/return 1;\n\n\treturn 0;\n}\n\nstruct ma_flags {\n\tint \tflag_val;\n\tchar\t*flag_name;\n};\n\nvoid display_prmap()\n{\n\tint\t\ti;\n\n\tfor(i=0;i<map_count;i++) {\n\t\tdprintf(D_ALWAYS, \"addr= 0x%p, size= 0x%lx, offset= 0x%x\\n\",\n\t\t\tmy_map[i].mem_start, my_map[i].mem_end-my_map[i].mem_start,\n\t\t\tmy_map[i].offset);\n\t\tdprintf(D_ALWAYS, \"Flags: %c%c%c%c inode %d\\n\", \n\t\t\tmy_map[i].r, my_map[i].w, my_map[i].x, my_map[i].p,\n\t\t\tmy_map[i].inode);\n\t}\n}\n\n\/*\n * This is a hack! The values found in \/proc\/pid\/maps do not always seem\n * to be correct. This function works its way down from the end addr\n * until it finds an addr that we can read from... - Greger\n *\/\nunsigned long find_correct_vm_addr(unsigned long start, unsigned long end,\n\tint prot)\n{\n\tint scm=SetSyscalls(SYS_LOCAL | SYS_UNMAPPED);\n\n\tif((mprotect((char *)start, end-start, PROT_READ))==0) {\n\t\t\/*\n\t\t * We were allowed to do read access to the chunk. Change\n\t\t * protection back to what it was before the call.\n\t\t *\/\n\t\tif((mprotect((char *)start, end-start, prot))==0) {\n\t\t\tSetSyscalls(scm);\n\t\t\treturn end;\n\t\t} else {\n\t\t\tdprintf(D_ALWAYS, \"Fatal error, Can't restore memory protection\\n\");\n\t\t}\n\t} else {\n\t\t\/*\n\t\t * We were not allowed read permission to the whole block. Find\n\t\t * a smaller block that we do have access to...\n\t\t *\/\n\t\tfor(;end>start;end-=4) { \/* Most lib stuff is alligned on 4 bytes or less??... *\/\n\t\t\tif((mprotect((char *)start, end-start, PROT_READ))==0) {\n\t\t\t\t\/*\n\t\t \t\t* We were allowed to do read access to the chunk. Change\n\t\t \t\t* protection back to what it was before the call.\n\t\t \t\t*\/\n\t\t\t\tif((mprotect((char *)start, end-start, prot))==0) {\n\t\t\t\t\tSetSyscalls(scm);\t\n\t\t\t\t\treturn end;\n\t\t\t\t} else {\n\t\t\t\t\tdprintf(D_ALWAYS, \"Fatal error, Can't restore memory protection\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdprintf(D_ALWAYS, \"Fatal error, Can't read any of this block\\n\");\n\t}\n\tSetSyscalls(scm);\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"startd.h\"\nstatic char *_FileName_ = __FILE__;\n\n\nResource::Resource( Sock* coll_sock, Sock* alt_sock )\n{\n\tchar tmp[100];\n\n\tr_classad = new ClassAd;\n\tr_private_classad = new ClassAd;\n\tr_state = new ResState( this );\n\tr_starter = new Starter;\n\tr_cur = new Match;\n\tr_pre = NULL;\n\tr_reqexp = new Reqexp( r_classad );\n\tr_attr = new ResAttributes( this );\n\n\tif( gethostname( tmp, 99 ) < 0 ) {\n\t\tEXCEPT( \"gethostname\" );\n\t}\n\tr_name = strdup( tmp );\n\n\tthis->coll_sock = coll_sock;\n\tthis->alt_sock = alt_sock;\n\tup_tid = -1;\n\tpoll_tid = -1;\n}\n\n\nResource::~Resource()\n{\n\tdaemonCore->Cancel_Timer( up_tid );\n\tthis->cancel_poll_timer();\n\n\tdelete r_state;\n\tdelete r_classad;\n\tdelete r_private_classad;\n\tdelete r_starter;\n\tdelete r_cur;\t\t\n\tdelete r_pre;\t\t\n\tdelete r_reqexp; \n\tdelete r_attr;\t\t\n\tfree( r_name );\n}\n\n\nint\nResource::init_classad()\n{\n\tchar \ttmp[80];\n\tint \tphys_memory = -1;\n#if !defined(WIN32)\n\tchar*\thost_cell;\n#endif\n\tchar*\tptr;\n\tint\t\tneeds_free = 0;\n\n\t\t\/\/ Insert state and activity attributes into public ad\n\tr_state->init_classad( r_classad );\n\n\t\t\/\/ Name of this resource (needs to be in public and private ads)\n\tsprintf( tmp, \"%s=\\\"%s\\\"\", ATTR_NAME, r_name );\n\tr_classad->Insert( tmp );\n\tr_private_classad->Insert( tmp );\n\n\t\t\/\/ STARTD_IP_ADDR (needs to be in public and private ads)\n\tsprintf( tmp, \"%s=\\\"%s\\\"\", ATTR_STARTD_IP_ADDR, \n\t\t\t daemonCore->InfoCommandSinfulString() );\n\tr_classad->Insert( tmp );\n\tr_private_classad->Insert( tmp );\n\n#if !defined(WIN32) \/* NEED TO PORT TO WIN32 *\/\n\t\t\/\/ AFS cell\n\thost_cell = get_host_cell();\n\tif( host_cell ) {\n\t\tsprintf( tmp, \"%s=\\\"%s\\\"\", ATTR_AFS_CELL, host_cell );\n\t\tr_classad->Insert( tmp );\n\t\tdprintf( D_ALWAYS, \"AFS_Cell = \\\"%s\\\"\\n\", host_cell );\n\t\tdelete [] host_cell;\n\t} else {\n\t\tdprintf( D_ALWAYS, \"AFS_Cell not set\\n\" );\n\t}\n#endif\n\n\t\t\/\/ If the UID domain is not set, use our hostname as the\n\t\t\/\/ default. \n\tif( (ptr = param(\"UID_DOMAIN\")) == NULL ) {\n\t\tptr = get_full_hostname();\n\t} else {\n\t\t\t\/\/ If the UID domain is defined as \"*\", accept uids from\n\t\t\t\/\/ anyone. \n\t\tif( ptr[0] == '*' ) {\n\t\t\tfree( ptr );\n\t\t\tptr = \"\";\n\t\t} else {\n\t\t\tneeds_free = 1;\n\t\t}\n\t}\n\tdprintf( D_ALWAYS, \"%s = \\\"%s\\\"\\n\", ATTR_UID_DOMAIN, ptr );\n\tsprintf( tmp, \"%s=\\\"%s\\\"\", ATTR_UID_DOMAIN, ptr );\n\tr_classad->Insert( tmp );\n\tif( needs_free ) {\n\t\tfree( ptr );\n\t\tneeds_free = 0;\n\t}\n\n\t\t\/\/ If the file system domain is not set, use our hostname as\n\t\t\/\/ the default. \n\tif( (ptr = param(\"FILESYSTEM_DOMAIN\")) == NULL ) {\n\t\tptr = get_full_hostname();\n\t} else {\n\t\t\t\/\/ If the file system domain is defined as \"*\", assume we\n\t\t\t\/\/ share files with everyone.\n\t\tif( ptr[0] == '*' ) {\n\t\t\tfree( ptr );\n\t\t\tptr = \"\";\n\t\t} else {\n\t\t\tneeds_free = 1;\n\t\t}\n\t}\n\tdprintf( D_ALWAYS, \"%s = \\\"%s\\\"\\n\", ATTR_FILE_SYSTEM_DOMAIN, ptr );\n\tsprintf( tmp, \"%s=\\\"%s\\\"\", ATTR_FILE_SYSTEM_DOMAIN, ptr );\n\tr_classad->Insert( tmp );\n\tif( needs_free ) {\n\t\tfree( ptr );\n\t\tneeds_free = 0;\n\t}\n\n\t\t\/\/ Number of CPUs. \n\tsprintf( tmp, \"%s=%d\", ATTR_CPUS, calc_ncpus() );\n\tr_classad->Insert( tmp );\n\n\t\t\/\/ Physical memory\n\tphys_memory = calc_phys_memory();\n\tif( phys_memory > 0 ) {\n\t\tsprintf( tmp, \"%s=%d\", ATTR_MEMORY, phys_memory );\n\t\tr_classad->Insert( tmp );\n\t}\n\n\t\t\/\/ Nest\n\tif( (ptr = param(\"NEST\")) != NULL ) {\n\t\tsprintf( tmp, \"%s=\\\"%s\\\"\", ATTR_NEST, ptr );\n\t\tr_classad->Insert( tmp );\n\t\tfree( ptr );\n\t}\n\n\t\t\/\/ Current rank\n\tsprintf( tmp, \"%s=0\", ATTR_CURRENT_RANK );\n\tr_classad->Insert( tmp );\n\n\treturn TRUE;\n}\n\n\nint\nResource::update_classad()\n{\n\tClassAd* cp = r_classad;\n\tchar line[80];\n\n\t\t\/\/ Recompute update-only statistics\n\tr_attr->update();\n\t\n\t\t\/\/ Refresh the classad with statistics that are only needed on updates\n\tsprintf( line, \"%s=%lu\", ATTR_VIRTUAL_MEMORY, r_attr->virtmem() );\n \tcp->Insert( line ); \n\n\tsprintf( line, \"%s=%lu\", ATTR_DISK, r_attr->disk() );\n\tcp->Insert( line ); \n \n\t\/\/ KFLOPS and MIPS are only conditionally computed; thus, only\n\t\/\/ advertise them if we computed them.\n\tif ( r_attr->kflops() > 0 ) {\n\t\tsprintf( line, \"%s=%d\", ATTR_KFLOPS, r_attr->kflops() );\n\t\tcp->Insert( line );\n\t}\n\tif ( r_attr->mips() > 0 ) {\n\t\tsprintf( line, \"%s=%d\", ATTR_MIPS, r_attr->mips() );\n\t\tcp->Insert( line );\n\t}\n\n\t\t\/\/ Add capability to private classad. If r_pre exists, we\n\t\t\/\/ need to advertise it's capability. Otherwise, we should\n\t\t\/\/ get the capability from r_cur.\n\tif( r_pre ) {\n\t\tsprintf( line, \"%s=\\\"%s\\\"\", ATTR_CAPABILITY, r_pre->capab() );\n\t} else {\n\t\tsprintf( line, \"%s=\\\"%s\\\"\", ATTR_CAPABILITY, r_cur->capab() );\n\t}\t\t\n\tr_private_classad->Insert( line );\n\n\t\t\/\/ Update current rank expression in classad\n\tsprintf( line, \"%s=%f\", ATTR_CURRENT_RANK, r_cur->rank() );\n\tcp->Insert( line );\n\n\treturn TRUE;\n}\n\n\nint\nResource::timeout_classad()\n{\n\tClassAd* cp = r_classad;\n\tchar line[80];\n \n\t\t\/\/ Recompute statistics needed at every timeout\n\tr_attr->timeout();\n\n\tsprintf( line, \"%s=%f\", ATTR_LOAD_AVG, r_attr->load() );\n\tcp->Insert(line);\n\n\tsprintf( line, \"%s=%f\", ATTR_CONDOR_LOAD_AVG, r_attr->condor_load() );\n\tcp->Insert(line);\n\n\tsprintf(line, \"%s=%d\", ATTR_KEYBOARD_IDLE, r_attr->idle() );\n\tcp->Insert(line); \n \n\t\/\/ ConsoleIdle cannot be determined on all platforms; thus, only\n\t\/\/ advertise if it is not -1.\n\tif( r_attr->console_idle() != -1 ) {\n\t\tsprintf( line, \"%s=%d\", ATTR_CONSOLE_IDLE, \n\t\t\t\t r_attr->console_idle() );\n\t\tcp->Insert(line); \n\t}\n\n\treturn TRUE;\n}\n\n\nint\nResource::update()\n{\n\tint rval1 = TRUE, rval2 = TRUE;\n\n\t\t\/\/ Recompute stats needed only for updates and refresh classad. \n\tthis->update_classad();\n\n\t\t\/\/ Send class ad to collector\n\trval1 = send_classad_to_sock( coll_sock, TRUE );\n\tif( rval1 ) {\n\t\tdprintf( D_ALWAYS, \"Sent update to the collector (%s)\\n\", \n\t\t\t\t collector_host );\n\t}\n\n\t\t\/\/ If we have an alternate collector, send CA there.\n\tif( alt_sock ) {\n\t\tif( (rval2 = send_classad_to_sock( alt_sock, FALSE )) ) {\n\t\t\tdprintf( D_FULLDEBUG, \n\t\t\t\t\t \"Sent update to the condor_view host (%s)\\n\",\n\t\t\t\t\t condor_view_host );\n\t\t}\n\t}\n\n\t\t\/\/ Set a flag to indicate that we've done an update.\n\tdid_update = TRUE;\n\n\t\t\/\/ Reset our timer so we update again after update_interval.\n\tdaemonCore->Reset_Timer( up_tid, update_interval, 0 );\n\n\treturn( rval1 && rval2 );\n}\n\n\nint\nResource::eval_and_update()\n{\n\tdid_update = FALSE;\n\n\t\t\/\/ Evaluate the state of this resource.\n\teval_state();\n\n\t\t\/\/ If we didn't update b\/c of the eval_state, we need to\n\t\t\/\/ actually do the update now.\n\tif( ! did_update ) {\n\t\tupdate();\n\t}\n\treturn TRUE;\n}\n\n\nint\nResource::start_update_timer()\n{\n\tup_tid = \n\t\tdaemonCore->Register_Timer( update_interval, 0,\n\t\t\t\t\t\t\t\t\t(TimerHandler)timeout_and_update,\n\t\t\t\t\t\t\t\t\t\"timeout_and_update\" );\n\tif( up_tid < 0 ) {\n\t\tEXCEPT( \"Can't register DaemonCore timer\" );\n\t}\n\n\tif( ! daemonCore->Register_DataPtr( (void*) this ) ) {\n\t\tEXCEPT( \"Can't register update timer data pointer\" );\n\t}\n\treturn TRUE;\n}\n\n\nint\nResource::start_poll_timer()\n{\n\tif( poll_tid >= 0 ) {\n\t\t\t\/\/ Timer already started.\n\t\treturn TRUE;\n\t}\n\n\tpoll_tid = \n\t\tdaemonCore->Register_Timer( polling_interval,\n\t\t\t\t\t\t\t\t\tpolling_interval, \n\t\t\t\t\t\t\t\t\t(TimerHandler)poll_resource,\n\t\t\t\t\t\t\t\t\t\"poll_resource\" );\n\tif( poll_tid < 0 ) {\n\t\tEXCEPT( \"Can't register DaemonCore timer\" );\n\t}\n\n\tif( ! daemonCore->Register_DataPtr( (void*) this ) ) {\n\t\tEXCEPT( \"Can't register update timer data pointer\" );\n\t}\n\treturn TRUE;\n}\n\n\nvoid\nResource::cancel_poll_timer()\n{\n\tif( poll_tid != -1 ) {\n\t\tdaemonCore->Cancel_Timer( poll_tid );\n\t\tpoll_tid = -1;\n\t\tdprintf( D_FULLDEBUG, \"Canceled polling timer.\\n\" );\n\t}\n}\n\n\nint\nResource::change_state( State newstate )\n{\n\treturn r_state->change( newstate );\n}\n\n\nint\nResource::change_state( Activity newact )\n{\n\treturn r_state->change( newact );\n}\n\n\nbool\nResource::in_use()\n{\n\tState s = state();\n\tif( s == owner_state || s == unclaimed_state ) {\n\t\treturn false;\n\t} else {\n\t\treturn true;\n\t}\n}\n\n\nvoid\nResource::starter_exited()\n{\n\tdprintf( D_ALWAYS, \"Starter pid %d has exited.\\n\",\n\t\t\t r_starter->pid() );\n\tr_starter->exited();\n\tchange_state( idle_act );\n}\n\n\nint\nResource::send_classad_to_sock( Sock* sock, int send_private ) \n{\n\tsock->encode();\n\n\tr_classad->SetMyTypeName( STARTD_ADTYPE );\n\tr_classad->SetTargetTypeName( JOB_ADTYPE );\n\n\tif( send_private ) {\n\t\tr_private_classad->SetMyTypeName( STARTD_ADTYPE );\n\t\tr_private_classad->SetTargetTypeName( JOB_ADTYPE );\n\t}\n\n\tif( ! sock->put( UPDATE_STARTD_AD ) ) {\n\t\tdprintf( D_ALWAYS, \"Can't send command\\n\");\n\t\tsock->end_of_message();\n\t\treturn FALSE;\n\t}\n\n\tif( ! r_classad->put( *sock ) ) {\n\t\tdprintf( D_ALWAYS, \"Can't send public classad\\n\");\n\t\tsock->end_of_message();\n\t\treturn FALSE;\n\t}\n\n\tif( send_private ) {\n\t\tif( ! r_private_classad->put( *sock ) ) {\n\t\t\tdprintf( D_ALWAYS, \"Can't send private classad\\n\");\n\t\t\tsock->end_of_message();\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\tif( ! sock->end_of_message() ) {\n\t\tdprintf( D_ALWAYS, \"Can't send end_of_message\\n\");\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}\n\n\n<commit_msg>+ init_classad(), update_classad() and timeout_classad() all return void. + Use the new ResState::update() and ResAttributes::update() interface. Pass a pointer to the classad you want filled in, and let them do all the work. + Use my_hostname() instead of calling gethostname() directly. + Automatically insert Machine, Arch and OpSys into the startd ad.<commit_after>#include \"startd.h\"\nstatic char *_FileName_ = __FILE__;\n\n\nResource::Resource( Sock* coll_sock, Sock* alt_sock )\n{\n\tr_classad = new ClassAd;\n\tr_private_classad = new ClassAd;\n\tr_state = new ResState( this );\n\tr_starter = new Starter;\n\tr_cur = new Match;\n\tr_pre = NULL;\n\tr_reqexp = new Reqexp( r_classad );\n\tr_attr = new ResAttributes( this );\n\tr_name = strdup( my_hostname() );\n\n\tthis->coll_sock = coll_sock;\n\tthis->alt_sock = alt_sock;\n\tup_tid = -1;\n\tpoll_tid = -1;\n}\n\n\nResource::~Resource()\n{\n\tdaemonCore->Cancel_Timer( up_tid );\n\tthis->cancel_poll_timer();\n\n\tdelete r_state;\n\tdelete r_classad;\n\tdelete r_private_classad;\n\tdelete r_starter;\n\tdelete r_cur;\t\t\n\tdelete r_pre;\t\t\n\tdelete r_reqexp; \n\tdelete r_attr;\t\t\n\tfree( r_name );\n}\n\n\nvoid\nResource::init_classad()\n{\n\tchar \ttmp[80];\n\tint \tphys_memory = -1;\n\tchar*\tptr;\n\tint\t\tneeds_free = 0;\n\n\t\t\/\/ Insert state and activity attributes into public ad\n\tr_state->update( r_classad );\n\n\t\t\/\/ Name of this resource (needs to be in public and private ads)\n\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_NAME, r_name );\n\tr_classad->Insert( tmp );\n\tr_private_classad->Insert( tmp );\n\n\t\t\/\/ Stick the hostname of this machine into classad.\n\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_MACHINE, my_hostname() );\n\tr_classad->Insert( tmp );\n\n\t\t\/\/ STARTD_IP_ADDR (needs to be in public and private ads)\n\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_STARTD_IP_ADDR, \n\t\t\t daemonCore->InfoCommandSinfulString() );\n\tr_classad->Insert( tmp );\n\tr_private_classad->Insert( tmp );\n\n\t\t\/\/ Arch and OpSys. Note: these will always return something,\n\t\t\/\/ since config() will insert values for these from uname() if\n\t\t\/\/ we don't have them in the config file. \n\tptr = param( \"ARCH\" );\n\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_ARCH, ptr );\n\tr_classad->Insert( tmp );\n\tfree( ptr );\n\n\tptr = param( \"OPSYS\" );\n\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_OPSYS, ptr );\n\tr_classad->Insert( tmp );\n\tfree( ptr );\n\n#if !defined(WIN32) \/* NEED TO PORT TO WIN32 *\/\n\t\t\/\/ AFS cell\n\tif( r_attr->afs_cell() ) {\n\t\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_AFS_CELL, r_attr->afs_cell() );\n\t\tr_classad->Insert( tmp );\n\t\tdprintf( D_ALWAYS, \"%s\\n\", tmp );\n\t} else {\n\t\tdprintf( D_ALWAYS, \"AFS_Cell not set\\n\" );\n\t}\n#endif\n\n\t\t\/\/ If the UID domain is not set, use our hostname as the\n\t\t\/\/ default. \n\tif( (ptr = param(\"UID_DOMAIN\")) == NULL ) {\n\t\tptr = my_full_hostname();\n\t} else {\n\t\t\t\/\/ If the UID domain is defined as \"*\", accept uids from\n\t\t\t\/\/ anyone. \n\t\tif( ptr[0] == '*' ) {\n\t\t\tfree( ptr );\n\t\t\tptr = \"\";\n\t\t} else {\n\t\t\tneeds_free = 1;\n\t\t}\n\t}\n\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_UID_DOMAIN, ptr );\n\tdprintf( D_ALWAYS, \"%s\\n\", tmp );\n\tr_classad->Insert( tmp );\n\tif( needs_free ) {\n\t\tfree( ptr );\n\t\tneeds_free = 0;\n\t}\n\n\t\t\/\/ If the file system domain is not set, use our hostname as\n\t\t\/\/ the default. \n\tif( (ptr = param(\"FILESYSTEM_DOMAIN\")) == NULL ) {\n\t\tptr = my_full_hostname();\n\t} else {\n\t\t\t\/\/ If the file system domain is defined as \"*\", assume we\n\t\t\t\/\/ share files with everyone.\n\t\tif( ptr[0] == '*' ) {\n\t\t\tfree( ptr );\n\t\t\tptr = \"\";\n\t\t} else {\n\t\t\tneeds_free = 1;\n\t\t}\n\t}\n\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_FILE_SYSTEM_DOMAIN, ptr );\n\tdprintf( D_ALWAYS, \"%s\\n\", tmp );\n\tr_classad->Insert( tmp );\n\tif( needs_free ) {\n\t\tfree( ptr );\n\t\tneeds_free = 0;\n\t}\n\n\t\t\/\/ Number of CPUs. \n\tsprintf( tmp, \"%s = %d\", ATTR_CPUS, calc_ncpus() );\n\tr_classad->Insert( tmp );\n\n\t\t\/\/ Physical memory\n\tphys_memory = calc_phys_memory();\n\tif( phys_memory > 0 ) {\n\t\tsprintf( tmp, \"%s = %d\", ATTR_MEMORY, phys_memory );\n\t\tr_classad->Insert( tmp );\n\t}\n\n\t\t\/\/ Nest\n\tif( (ptr = param(\"NEST\")) != NULL ) {\n\t\tsprintf( tmp, \"%s = \\\"%s\\\"\", ATTR_NEST, ptr );\n\t\tr_classad->Insert( tmp );\n\t\tfree( ptr );\n\t}\n\n\t\t\/\/ Current rank\n\tsprintf( tmp, \"%s = 0\", ATTR_CURRENT_RANK );\n\tr_classad->Insert( tmp );\n}\n\n\nvoid\nResource::update_classad()\n{\n\tchar line[100];\n\n\t\t\/\/ Recompute update-only statistics and fill in classad\n\tr_attr->update( r_classad );\n\t\n\t\t\/\/ Add capability to private classad. If r_pre exists, we\n\t\t\/\/ need to advertise it's capability. Otherwise, we should\n\t\t\/\/ get the capability from r_cur.\n\tif( r_pre ) {\n\t\tsprintf( line, \"%s = \\\"%s\\\"\", ATTR_CAPABILITY, r_pre->capab() );\n\t} else {\n\t\tsprintf( line, \"%s = \\\"%s\\\"\", ATTR_CAPABILITY, r_cur->capab() );\n\t}\t\t\n\tr_private_classad->Insert( line );\n\n\t\t\/\/ Update current rank expression in classad\n\tsprintf( line, \"%s = %f\", ATTR_CURRENT_RANK, r_cur->rank() );\n\tr_classad->Insert( line );\n}\n\n\nvoid\nResource::timeout_classad()\n{\n\t\t\/\/ Recompute statistics needed at every timeout and fill in classad\n\tr_attr->timeout( r_classad );\n}\n\n\nint\nResource::update()\n{\n\tint rval1 = TRUE, rval2 = TRUE;\n\n\t\t\/\/ Recompute stats needed only for updates and refresh classad. \n\tthis->update_classad();\n\n\t\t\/\/ Send class ad to collector\n\tif( (rval1 = send_classad_to_sock( coll_sock, TRUE )) ) {\n\t\tdprintf( D_ALWAYS, \"Sent update to the collector (%s)\\n\", \n\t\t\t\t collector_host );\n\t} \n\n\t\t\/\/ If we have an alternate collector, send CA there.\n\tif( alt_sock ) {\n\t\tif( (rval2 = send_classad_to_sock( alt_sock, FALSE )) ) {\n\t\t\tdprintf( D_FULLDEBUG, \n\t\t\t\t\t \"Sent update to the condor_view host (%s)\\n\",\n\t\t\t\t\t condor_view_host );\n\t\t}\n\t}\n\n\t\t\/\/ Set a flag to indicate that we've done an update.\n\tdid_update = TRUE;\n\n\t\t\/\/ Reset our timer so we update again after update_interval.\n\tdaemonCore->Reset_Timer( up_tid, update_interval, 0 );\n\n\treturn( rval1 && rval2 );\n}\n\n\nint\nResource::eval_and_update()\n{\n\tdid_update = FALSE;\n\n\t\t\/\/ Evaluate the state of this resource.\n\teval_state();\n\n\t\t\/\/ If we didn't update b\/c of the eval_state, we need to\n\t\t\/\/ actually do the update now.\n\tif( ! did_update ) {\n\t\tupdate();\n\t}\n\treturn TRUE;\n}\n\n\nint\nResource::start_update_timer()\n{\n\tup_tid = \n\t\tdaemonCore->Register_Timer( update_interval, 0,\n\t\t\t\t\t\t\t\t\t(TimerHandler)timeout_and_update,\n\t\t\t\t\t\t\t\t\t\"timeout_and_update\" );\n\tif( up_tid < 0 ) {\n\t\tEXCEPT( \"Can't register DaemonCore timer\" );\n\t}\n\n\tif( ! daemonCore->Register_DataPtr( (void*) this ) ) {\n\t\tEXCEPT( \"Can't register update timer data pointer\" );\n\t}\n\treturn TRUE;\n}\n\n\nint\nResource::start_poll_timer()\n{\n\tif( poll_tid >= 0 ) {\n\t\t\t\/\/ Timer already started.\n\t\treturn TRUE;\n\t}\n\n\tpoll_tid = \n\t\tdaemonCore->Register_Timer( polling_interval,\n\t\t\t\t\t\t\t\t\tpolling_interval, \n\t\t\t\t\t\t\t\t\t(TimerHandler)poll_resource,\n\t\t\t\t\t\t\t\t\t\"poll_resource\" );\n\tif( poll_tid < 0 ) {\n\t\tEXCEPT( \"Can't register DaemonCore timer\" );\n\t}\n\n\tif( ! daemonCore->Register_DataPtr( (void*) this ) ) {\n\t\tEXCEPT( \"Can't register update timer data pointer\" );\n\t}\n\treturn TRUE;\n}\n\n\nvoid\nResource::cancel_poll_timer()\n{\n\tif( poll_tid != -1 ) {\n\t\tdaemonCore->Cancel_Timer( poll_tid );\n\t\tpoll_tid = -1;\n\t\tdprintf( D_FULLDEBUG, \"Canceled polling timer.\\n\" );\n\t}\n}\n\n\nint\nResource::change_state( State newstate )\n{\n\treturn r_state->change( newstate );\n}\n\n\nint\nResource::change_state( Activity newact )\n{\n\treturn r_state->change( newact );\n}\n\n\nbool\nResource::in_use()\n{\n\tState s = state();\n\tif( s == owner_state || s == unclaimed_state ) {\n\t\treturn false;\n\t} else {\n\t\treturn true;\n\t}\n}\n\n\nvoid\nResource::starter_exited()\n{\n\tdprintf( D_ALWAYS, \"Starter pid %d has exited.\\n\",\n\t\t\t r_starter->pid() );\n\tr_starter->exited();\n\tchange_state( idle_act );\n}\n\n\nint\nResource::send_classad_to_sock( Sock* sock, int send_private ) \n{\n\tsock->encode();\n\n\tr_classad->SetMyTypeName( STARTD_ADTYPE );\n\tr_classad->SetTargetTypeName( JOB_ADTYPE );\n\n\tif( send_private ) {\n\t\tr_private_classad->SetMyTypeName( STARTD_ADTYPE );\n\t\tr_private_classad->SetTargetTypeName( JOB_ADTYPE );\n\t}\n\n\tif( ! sock->put( UPDATE_STARTD_AD ) ) {\n\t\tdprintf( D_ALWAYS, \"Can't send command\\n\");\n\t\tsock->end_of_message();\n\t\treturn FALSE;\n\t}\n\n\tif( ! r_classad->put( *sock ) ) {\n\t\tdprintf( D_ALWAYS, \"Can't send public classad\\n\");\n\t\tsock->end_of_message();\n\t\treturn FALSE;\n\t}\n\n\tif( send_private ) {\n\t\tif( ! r_private_classad->put( *sock ) ) {\n\t\t\tdprintf( D_ALWAYS, \"Can't send private classad\\n\");\n\t\t\tsock->end_of_message();\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\tif( ! sock->end_of_message() ) {\n\t\tdprintf( D_ALWAYS, \"Can't send end_of_message\\n\");\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2009 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is 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\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\/**\n \\file uvfUVFMetadata.cpp\n \\author Tom Fogal\n SCI Institute\n University of Utah\n \\brief UVF-specific implementation of metadata.\n*\/\n\n#include <algorithm>\n#include \"uvfMetadata.h\"\n\nnamespace tuvok {\n\nUVFMetadata::UVFMetadata() :\n m_pVolumeDataBlock(NULL),\n m_pMaxMinData(NULL)\n{\n}\n\nUVFMetadata::UVFMetadata(RasterDataBlock* pVolumeDataBlock,\n MaxMinDataBlock* pMaxMinData, bool bIsSameEndianness):\n m_pVolumeDataBlock(pVolumeDataBlock),\n m_pMaxMinData(pMaxMinData),\n m_bIsSameEndianness(bIsSameEndianness)\n{\n std::vector<double> vfScale;\n size_t iSize = m_pVolumeDataBlock->ulDomainSize.size();\n\n \/\/ we require the data to be at least 3D\n assert(iSize >= 3);\n\n \/\/ we also assume that x,y,z are in the first 3 components and\n \/\/ we have no anisotropy (i.e. ulLODLevelCount.size=1)\n m_iLODLevel = static_cast<size_t>(m_pVolumeDataBlock->ulLODLevelCount[0]);\n for (size_t i = 0;i<3;i++) {\n m_aOverlap[i] = m_pVolumeDataBlock->ulBrickOverlap[i];\n m_aMaxBrickSize[i] = m_pVolumeDataBlock->ulBrickSize[i];\n m_aScale[i] = m_pVolumeDataBlock->dDomainTransformation[i+(iSize+1)*i];\n }\n\n m_vvaBrickSize.resize(m_iLODLevel);\n if (m_pMaxMinData) m_vvaMaxMin.resize(m_iLODLevel);\n\n for (size_t j = 0;j<m_iLODLevel;j++) {\n std::vector<UINT64> vLOD; vLOD.push_back(j);\n std::vector<UINT64> vDomSize = m_pVolumeDataBlock->GetLODDomainSize(vLOD);\n m_aDomainSize.push_back(UINT64VECTOR3(vDomSize[0], vDomSize[1],\n vDomSize[2]));\n\n std::vector<UINT64> vBrickCount = m_pVolumeDataBlock->GetBrickCount(vLOD);\n m_vaBrickCount.push_back(UINT64VECTOR3(vBrickCount[0], vBrickCount[1],\n vBrickCount[2]));\n\n m_vvaBrickSize[j].resize(m_vaBrickCount[j].x);\n if (m_pMaxMinData) {\n m_vvaMaxMin[j].resize(m_vaBrickCount[j].x);\n }\n for (UINT64 x=0; x < m_vaBrickCount[j].x; x++) {\n m_vvaBrickSize[j][x].resize(m_vaBrickCount[j].y);\n if (m_pMaxMinData) {\n m_vvaMaxMin[j][x].resize(m_vaBrickCount[j].y);\n }\n\n for (UINT64 y=0; y < m_vaBrickCount[j].y; y++) {\n if (m_pMaxMinData) {\n m_vvaMaxMin[j][x][y].resize(m_vaBrickCount[j].z);\n }\n\n for (UINT64 z=0; z < m_vaBrickCount[j].z; z++) {\n std::vector<UINT64> vBrick;\n vBrick.push_back(x);\n vBrick.push_back(y);\n vBrick.push_back(z);\n std::vector<UINT64> vBrickSize =\n m_pVolumeDataBlock->GetBrickSize(vLOD, vBrick);\n\n m_vvaBrickSize[j][x][y].push_back(UINT64VECTOR3(vBrickSize[0],\n vBrickSize[1],\n vBrickSize[2]));\n }\n }\n }\n }\n\n size_t iSerializedIndex = 0;\n if (m_pMaxMinData) {\n for (size_t lod=0; lod < m_iLODLevel; lod++) {\n for (UINT64 z=0; z < m_vaBrickCount[lod].z; z++) {\n for (UINT64 y=0; y < m_vaBrickCount[lod].y; y++) {\n for (UINT64 x=0; x < m_vaBrickCount[lod].x; x++) {\n \/\/ for four-component data we use the fourth component\n \/\/ (presumably the alpha channel); for all other data we use\n \/\/ the first component\n \/\/\/ \\todo we may have to change this if we add support for other\n \/\/\/ kinds of multicomponent data.\n m_vvaMaxMin[lod][x][y][z] =\n m_pMaxMinData->GetValue(iSerializedIndex++,\n (m_pVolumeDataBlock->ulElementDimensionSize[0] == 4) ? 3 : 0\n );\n }\n }\n }\n }\n }\n\n \/\/ Use a minimum of 3 elements, which ...\n size_t n_elems = std::max(static_cast<size_t>(3),\n m_pVolumeDataBlock->ulDomainSemantics.size());\n std::vector<double> rescale(n_elems);\n for (size_t i=0; i < n_elems; i++) {\n rescale[i] = 1.0;\n }\n \/\/ ... allows us to assume we can deref the first 3 elements here.\n this->SetRescaleFactors(DOUBLEVECTOR3(rescale[0],rescale[1],rescale[2]));\n}\n\n\n\/\/ Return the number of bricks in the given LoD, along each axis.\nUINT64VECTOR3 UVFMetadata::GetBrickCount(const UINT64 lod) const\n{\n return m_vaBrickCount[lod];\n}\n\n\/\/ Size of the brick in logical space.\nUINT64VECTOR3 UVFMetadata::GetBrickSize(const NDBrickKey &k) const\n{\n const UINT64 lod = k.first[0];\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n return m_vvaBrickSize[lod][vBrick[0]][vBrick[1]][vBrick[2]];\n}\n\n\n\/\/ Gives the size of a brick in real space.\nUINT64VECTOR3 UVFMetadata::GetEffectiveBrickSize(const NDBrickKey &k) const\n{\n const UINT64 iLOD = k.first[0];\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n UINT64VECTOR3 vBrickSize(\n m_vvaBrickSize[iLOD][vBrick[0]][vBrick[1]][vBrick[2]].x,\n m_vvaBrickSize[iLOD][vBrick[0]][vBrick[1]][vBrick[2]].y,\n m_vvaBrickSize[iLOD][vBrick[0]][vBrick[1]][vBrick[2]].z\n );\n\n if (m_vaBrickCount[iLOD].x > 1) {\n if (vBrick[0] > 0) vBrickSize.x -= m_aOverlap.x\/2.0f;\n if (vBrick[0] < m_vaBrickCount[iLOD].x-1) vBrickSize.x -= m_aOverlap.x\/2.0f;\n }\n if (m_vaBrickCount[iLOD].y > 1) {\n if (vBrick[1] < m_vaBrickCount[iLOD].y-1) vBrickSize.y -= m_aOverlap.y\/2.0f;\n if (vBrick[1] > 0) vBrickSize.y -= m_aOverlap.y\/2.0f;\n }\n if (m_vaBrickCount[iLOD].z > 1) {\n if (vBrick[2] < m_vaBrickCount[iLOD].z-1) vBrickSize.z -= m_aOverlap.z\/2.0f;\n if (vBrick[2] > 0) vBrickSize.z -= m_aOverlap.z\/2.0f;\n }\n\n return vBrickSize;\n}\n\nUINT64VECTOR3 UVFMetadata::GetDomainSize(const UINT64 lod) const\n{\n return m_aDomainSize[lod];\n}\n\nUINT64VECTOR3 UVFMetadata::GetMaxBrickSize() const\n{\n return m_aMaxBrickSize;\n}\n\nUINT64VECTOR3 UVFMetadata::GetBrickOverlapSize() const\n{\n return m_aOverlap;\n}\n\nUINT64 UVFMetadata::GetLODLevelCount() const\n{\n return m_iLODLevel;\n}\n\nDOUBLEVECTOR3 UVFMetadata::GetScale() const\n{\n double rescale[3];\n this->GetRescaleFactors(rescale);\n return m_aScale * DOUBLEVECTOR3(rescale[0], rescale[1], rescale[2]);\n}\n\n\/\/\/ \\todo change this if we want to support data where elements are of\n\/\/ different size\nUINT64 UVFMetadata::GetBitWidth() const\n{\n return m_pVolumeDataBlock->ulElementBitSize[0][0];\n}\n\nUINT64 UVFMetadata::GetComponentCount() const\n{\n return m_pVolumeDataBlock->ulElementDimensionSize[0];\n}\n\n\/\/\/ \\todo change this if we want to support data where elements are of\n\/\/\/ different type\nbool UVFMetadata::GetIsSigned() const\n{\n return m_pVolumeDataBlock->bSignedElement[0][0];\n}\n\n\/\/\/ \\todo change this if we want to support data where elements are of\n\/\/\/ different type\nbool UVFMetadata::GetIsFloat() const\n{\n return GetBitWidth() != m_pVolumeDataBlock->ulElementBitSize[0][0];\n}\n\nbool UVFMetadata::IsSameEndianness() const\n{\n return m_bIsSameEndianness;\n}\n\n\nconst std::vector<UINT64>&\nUVFMetadata::GetBrickCountND(const std::vector<UINT64>& vLOD) const\n{\n return m_pVolumeDataBlock->GetBrickCount(vLOD);\n}\n\nconst std::vector<UINT64>&\nUVFMetadata::GetBrickSizeND(const std::vector<UINT64>& vLOD,\n const std::vector<UINT64>& vBrick) const\n{\n return m_pVolumeDataBlock->GetBrickSize(vLOD, vBrick);\n}\n\nconst std::vector<UINT64>& UVFMetadata::GetDomainSizeND() const\n{\n return m_pVolumeDataBlock->ulDomainSize;\n}\n\nconst std::vector<UINT64>& UVFMetadata::GetMaxBrickSizeND() const\n{\n return m_pVolumeDataBlock->ulBrickSize;\n}\n\nconst std::vector<UINT64>& UVFMetadata::GetBrickOverlapSizeND() const\n{\n return m_pVolumeDataBlock->ulBrickOverlap;\n}\n\nconst std::vector<UINT64>& UVFMetadata::GetLODLevelCountND() const\n{\n return m_pVolumeDataBlock->ulLODLevelCount;\n}\n\nconst std::vector<double> UVFMetadata::GetScaleND() const\n{\n std::vector<double> vfScale;\n\n const DOUBLEVECTOR3 rescale = this->GetRescaleFactors();\n const size_t iSize = m_pVolumeDataBlock->ulDomainSize.size();\n\n for (size_t i=0; i < iSize; i++) {\n vfScale.push_back(m_pVolumeDataBlock->dDomainTransformation[i+(iSize+1)*i]\n * rescale[i]);\n }\n\n return vfScale;\n}\n\n\nbool UVFMetadata::ContainsData(const NDBrickKey &k, double isoval) const\n{\n \/\/ if we have no max min data we have to assume that every block is visible\n if(NULL == m_pMaxMinData) {\n return true;\n }\n\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n const InternalMaxMinElement& maxMinElement = m_vvaMaxMin[k.first[0]]\n [vBrick[0]]\n [vBrick[1]]\n [vBrick[2]];\n return (isoval <= maxMinElement.maxScalar);\n}\n\nbool UVFMetadata::ContainsData(const NDBrickKey &k,\n double fMin,double fMax) const\n{\n \/\/ if we have no max min data we have to assume that every block is visible\n if(NULL == m_pMaxMinData) {\n return true;\n }\n\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n const InternalMaxMinElement& maxMinElement = m_vvaMaxMin[k.first[0]]\n [vBrick[0]]\n [vBrick[1]]\n [vBrick[2]];\n return (fMax >= maxMinElement.minScalar && fMin <= maxMinElement.maxScalar);\n}\nbool UVFMetadata::ContainsData(const NDBrickKey &k, double fMin,double fMax,\n double fMinGradient,double fMaxGradient) const\n{\n \/\/ if we have no max min data we have to assume that every block is visible\n if(NULL == m_pMaxMinData) {\n return true;\n }\n\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n const InternalMaxMinElement& maxMinElement = m_vvaMaxMin[k.first[0]]\n [vBrick[0]]\n [vBrick[1]]\n [vBrick[2]];\n return (fMax >= maxMinElement.minScalar &&\n fMin <= maxMinElement.maxScalar)\n &&\n (fMaxGradient >= maxMinElement.minGradient &&\n fMinGradient <= maxMinElement.maxGradient);\n}\n\n}; \/\/ namespace tuvok\n<commit_msg>Minor cleanup to brick size calculation with overlaps.<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2009 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is 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\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\/**\n \\file uvfUVFMetadata.cpp\n \\author Tom Fogal\n SCI Institute\n University of Utah\n \\brief UVF-specific implementation of metadata.\n*\/\n\n#include <algorithm>\n#include \"uvfMetadata.h\"\n\nnamespace tuvok {\n\nUVFMetadata::UVFMetadata() :\n m_pVolumeDataBlock(NULL),\n m_pMaxMinData(NULL)\n{\n}\n\nUVFMetadata::UVFMetadata(RasterDataBlock* pVolumeDataBlock,\n MaxMinDataBlock* pMaxMinData, bool bIsSameEndianness):\n m_pVolumeDataBlock(pVolumeDataBlock),\n m_pMaxMinData(pMaxMinData),\n m_bIsSameEndianness(bIsSameEndianness)\n{\n std::vector<double> vfScale;\n size_t iSize = m_pVolumeDataBlock->ulDomainSize.size();\n\n \/\/ we require the data to be at least 3D\n assert(iSize >= 3);\n\n \/\/ we also assume that x,y,z are in the first 3 components and\n \/\/ we have no anisotropy (i.e. ulLODLevelCount.size=1)\n m_iLODLevel = static_cast<size_t>(m_pVolumeDataBlock->ulLODLevelCount[0]);\n for (size_t i = 0;i<3;i++) {\n m_aOverlap[i] = m_pVolumeDataBlock->ulBrickOverlap[i];\n m_aMaxBrickSize[i] = m_pVolumeDataBlock->ulBrickSize[i];\n m_aScale[i] = m_pVolumeDataBlock->dDomainTransformation[i+(iSize+1)*i];\n }\n\n m_vvaBrickSize.resize(m_iLODLevel);\n if (m_pMaxMinData) m_vvaMaxMin.resize(m_iLODLevel);\n\n for (size_t j = 0;j<m_iLODLevel;j++) {\n std::vector<UINT64> vLOD; vLOD.push_back(j);\n std::vector<UINT64> vDomSize = m_pVolumeDataBlock->GetLODDomainSize(vLOD);\n m_aDomainSize.push_back(UINT64VECTOR3(vDomSize[0], vDomSize[1],\n vDomSize[2]));\n\n std::vector<UINT64> vBrickCount = m_pVolumeDataBlock->GetBrickCount(vLOD);\n m_vaBrickCount.push_back(UINT64VECTOR3(vBrickCount[0], vBrickCount[1],\n vBrickCount[2]));\n\n m_vvaBrickSize[j].resize(m_vaBrickCount[j].x);\n if (m_pMaxMinData) {\n m_vvaMaxMin[j].resize(m_vaBrickCount[j].x);\n }\n for (UINT64 x=0; x < m_vaBrickCount[j].x; x++) {\n m_vvaBrickSize[j][x].resize(m_vaBrickCount[j].y);\n if (m_pMaxMinData) {\n m_vvaMaxMin[j][x].resize(m_vaBrickCount[j].y);\n }\n\n for (UINT64 y=0; y < m_vaBrickCount[j].y; y++) {\n if (m_pMaxMinData) {\n m_vvaMaxMin[j][x][y].resize(m_vaBrickCount[j].z);\n }\n\n for (UINT64 z=0; z < m_vaBrickCount[j].z; z++) {\n std::vector<UINT64> vBrick;\n vBrick.push_back(x);\n vBrick.push_back(y);\n vBrick.push_back(z);\n std::vector<UINT64> vBrickSize =\n m_pVolumeDataBlock->GetBrickSize(vLOD, vBrick);\n\n m_vvaBrickSize[j][x][y].push_back(UINT64VECTOR3(vBrickSize[0],\n vBrickSize[1],\n vBrickSize[2]));\n }\n }\n }\n }\n\n size_t iSerializedIndex = 0;\n if (m_pMaxMinData) {\n for (size_t lod=0; lod < m_iLODLevel; lod++) {\n for (UINT64 z=0; z < m_vaBrickCount[lod].z; z++) {\n for (UINT64 y=0; y < m_vaBrickCount[lod].y; y++) {\n for (UINT64 x=0; x < m_vaBrickCount[lod].x; x++) {\n \/\/ for four-component data we use the fourth component\n \/\/ (presumably the alpha channel); for all other data we use\n \/\/ the first component\n \/\/\/ \\todo we may have to change this if we add support for other\n \/\/\/ kinds of multicomponent data.\n m_vvaMaxMin[lod][x][y][z] =\n m_pMaxMinData->GetValue(iSerializedIndex++,\n (m_pVolumeDataBlock->ulElementDimensionSize[0] == 4) ? 3 : 0\n );\n }\n }\n }\n }\n }\n\n \/\/ Use a minimum of 3 elements, which ...\n size_t n_elems = std::max(static_cast<size_t>(3),\n m_pVolumeDataBlock->ulDomainSemantics.size());\n std::vector<double> rescale(n_elems);\n for (size_t i=0; i < n_elems; i++) {\n rescale[i] = 1.0;\n }\n \/\/ ... allows us to assume we can deref the first 3 elements here.\n this->SetRescaleFactors(DOUBLEVECTOR3(rescale[0],rescale[1],rescale[2]));\n}\n\n\n\/\/ Return the number of bricks in the given LoD, along each axis.\nUINT64VECTOR3 UVFMetadata::GetBrickCount(const UINT64 lod) const\n{\n return m_vaBrickCount[lod];\n}\n\n\/\/ Size of the brick in logical space.\nUINT64VECTOR3 UVFMetadata::GetBrickSize(const NDBrickKey &k) const\n{\n const UINT64 lod = k.first[0];\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n return m_vvaBrickSize[lod][vBrick[0]][vBrick[1]][vBrick[2]];\n}\n\n\/\/ One dimensional brick shrinking for internal bricks that have some overlap\n\/\/ with neighboring bricks. Assumes overlap is constant per dataset: this\n\/\/ brick's overlap with the brick to its right is the same as the overlap with\n\/\/ the right brick's overlap with the brick to the left.\n\/\/\/ @param v original brick size for this dimension\n\/\/\/ @param nbrick which brick this is\n\/\/\/ @param count number of bricks for this dimension\n\/\/\/ @param overlap amount of per-brick overlap.\nstatic void fix_overlap(UINT64& v, UINT64 nbrick, UINT64 count,\n UINT64 overlap) {\n if(nbrick > 0) {\n v -= static_cast<size_t>(overlap\/2.0f);\n }\n if(nbrick < count) {\n v -= static_cast<size_t>(overlap\/2.0f);\n }\n}\n\n\n\/\/ Gives the size of a brick in real space.\nUINT64VECTOR3 UVFMetadata::GetEffectiveBrickSize(const NDBrickKey &k) const\n{\n const UINT64 iLOD = k.first[0];\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n UINT64VECTOR3 vBrickSize(\n m_vvaBrickSize[iLOD][vBrick[0]][vBrick[1]][vBrick[2]].x,\n m_vvaBrickSize[iLOD][vBrick[0]][vBrick[1]][vBrick[2]].y,\n m_vvaBrickSize[iLOD][vBrick[0]][vBrick[1]][vBrick[2]].z\n );\n\n \/\/ If this is an internal brick, the size is a bit smaller based on the\n \/\/ amount of overlap per-brick.\n if (m_vaBrickCount[iLOD].x > 1) {\n fix_overlap(vBrickSize.x, vBrick[0], m_vaBrickCount[iLOD].x-1,\n m_aOverlap.x);\n }\n if (m_vaBrickCount[iLOD].y > 1) {\n fix_overlap(vBrickSize.y, vBrick[1], m_vaBrickCount[iLOD].y-1,\n m_aOverlap.y);\n }\n if (m_vaBrickCount[iLOD].z > 1) {\n fix_overlap(vBrickSize.z, vBrick[2], m_vaBrickCount[iLOD].z-1,\n m_aOverlap.z);\n }\n\n return vBrickSize;\n}\n\nUINT64VECTOR3 UVFMetadata::GetDomainSize(const UINT64 lod) const\n{\n return m_aDomainSize[lod];\n}\n\nUINT64VECTOR3 UVFMetadata::GetMaxBrickSize() const\n{\n return m_aMaxBrickSize;\n}\n\nUINT64VECTOR3 UVFMetadata::GetBrickOverlapSize() const\n{\n return m_aOverlap;\n}\n\nUINT64 UVFMetadata::GetLODLevelCount() const\n{\n return m_iLODLevel;\n}\n\nDOUBLEVECTOR3 UVFMetadata::GetScale() const\n{\n double rescale[3];\n this->GetRescaleFactors(rescale);\n return m_aScale * DOUBLEVECTOR3(rescale[0], rescale[1], rescale[2]);\n}\n\n\/\/\/ \\todo change this if we want to support data where elements are of\n\/\/ different size\nUINT64 UVFMetadata::GetBitWidth() const\n{\n return m_pVolumeDataBlock->ulElementBitSize[0][0];\n}\n\nUINT64 UVFMetadata::GetComponentCount() const\n{\n return m_pVolumeDataBlock->ulElementDimensionSize[0];\n}\n\n\/\/\/ \\todo change this if we want to support data where elements are of\n\/\/\/ different type\nbool UVFMetadata::GetIsSigned() const\n{\n return m_pVolumeDataBlock->bSignedElement[0][0];\n}\n\n\/\/\/ \\todo change this if we want to support data where elements are of\n\/\/\/ different type\nbool UVFMetadata::GetIsFloat() const\n{\n return GetBitWidth() != m_pVolumeDataBlock->ulElementBitSize[0][0];\n}\n\nbool UVFMetadata::IsSameEndianness() const\n{\n return m_bIsSameEndianness;\n}\n\n\nconst std::vector<UINT64>&\nUVFMetadata::GetBrickCountND(const std::vector<UINT64>& vLOD) const\n{\n return m_pVolumeDataBlock->GetBrickCount(vLOD);\n}\n\nconst std::vector<UINT64>&\nUVFMetadata::GetBrickSizeND(const std::vector<UINT64>& vLOD,\n const std::vector<UINT64>& vBrick) const\n{\n return m_pVolumeDataBlock->GetBrickSize(vLOD, vBrick);\n}\n\nconst std::vector<UINT64>& UVFMetadata::GetDomainSizeND() const\n{\n return m_pVolumeDataBlock->ulDomainSize;\n}\n\nconst std::vector<UINT64>& UVFMetadata::GetMaxBrickSizeND() const\n{\n return m_pVolumeDataBlock->ulBrickSize;\n}\n\nconst std::vector<UINT64>& UVFMetadata::GetBrickOverlapSizeND() const\n{\n return m_pVolumeDataBlock->ulBrickOverlap;\n}\n\nconst std::vector<UINT64>& UVFMetadata::GetLODLevelCountND() const\n{\n return m_pVolumeDataBlock->ulLODLevelCount;\n}\n\nconst std::vector<double> UVFMetadata::GetScaleND() const\n{\n std::vector<double> vfScale;\n\n const DOUBLEVECTOR3 rescale = this->GetRescaleFactors();\n const size_t iSize = m_pVolumeDataBlock->ulDomainSize.size();\n\n for (size_t i=0; i < iSize; i++) {\n vfScale.push_back(m_pVolumeDataBlock->dDomainTransformation[i+(iSize+1)*i]\n * rescale[i]);\n }\n\n return vfScale;\n}\n\n\nbool UVFMetadata::ContainsData(const NDBrickKey &k, double isoval) const\n{\n \/\/ if we have no max min data we have to assume that every block is visible\n if(NULL == m_pMaxMinData) {\n return true;\n }\n\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n const InternalMaxMinElement& maxMinElement = m_vvaMaxMin[k.first[0]]\n [vBrick[0]]\n [vBrick[1]]\n [vBrick[2]];\n return (isoval <= maxMinElement.maxScalar);\n}\n\nbool UVFMetadata::ContainsData(const NDBrickKey &k,\n double fMin,double fMax) const\n{\n \/\/ if we have no max min data we have to assume that every block is visible\n if(NULL == m_pMaxMinData) {\n return true;\n }\n\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n const InternalMaxMinElement& maxMinElement = m_vvaMaxMin[k.first[0]]\n [vBrick[0]]\n [vBrick[1]]\n [vBrick[2]];\n return (fMax >= maxMinElement.minScalar && fMin <= maxMinElement.maxScalar);\n}\nbool UVFMetadata::ContainsData(const NDBrickKey &k, double fMin,double fMax,\n double fMinGradient,double fMaxGradient) const\n{\n \/\/ if we have no max min data we have to assume that every block is visible\n if(NULL == m_pMaxMinData) {\n return true;\n }\n\n const size_t vBrick[3] = {\n static_cast<size_t>(k.second[0].x),\n static_cast<size_t>(k.second[0].y),\n static_cast<size_t>(k.second[0].z)\n };\n const InternalMaxMinElement& maxMinElement = m_vvaMaxMin[k.first[0]]\n [vBrick[0]]\n [vBrick[1]]\n [vBrick[2]];\n return (fMax >= maxMinElement.minScalar &&\n fMin <= maxMinElement.maxScalar)\n &&\n (fMaxGradient >= maxMinElement.minGradient &&\n fMinGradient <= maxMinElement.maxGradient);\n}\n\n}; \/\/ namespace tuvok\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************** \nKCalendar support for OpenSync kdepim-sync plugin\nCopyright (C) 2004 Conectiva S. A.\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License version 2 as\npublished by the Free Software Foundation;\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY\nCLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES \nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN \nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF \nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, \nCOPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS \nSOFTWARE IS DISCLAIMED.\n*************************************************************************\/\n\/**\n * @autor Eduardo Pereira Habkost <ehabkost@conectiva.com.br>\n *\/\n\n#include <libkcal\/calendarresources.h>\n#include <libkcal\/icalformat.h>\n#include <libkcal\/calendarlocal.h>\n#include <kdeversion.h>\n\n#include \"osyncbase.h\"\n#include \"kcal.h\"\n\nKCalDataSource::KCalDataSource(OSyncMember *member, OSyncHashTable *hashtable)\n : hashtable(hashtable), member(member)\n{\n}\n\nbool KCalDataSource::connect(OSyncContext *ctx)\n{\n calendar = new KCal::CalendarResources();\n if (!calendar) {\n osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, \"Can't open KDE calendar\");\n return false;\n }\n#if KDE_IS_VERSION(3,3,0)\n \/* On KDE 3.2, there was no readConfig() and load(): the data\n * was loaded automatically on the CalendarResources() constructor\n *\/\n calendar->readConfig();\n calendar->load();\n#endif\n osync_debug(\"kcal\", 3, \"Calendar: %d events\", calendar->events().size());\n \/*FIXME: We don't lock the data *\/\n \/\/saveTicket = calendar->requestSaveTicket();\n if (!saveTicket) {\n osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, \"Couldn't request write to the KDE calendar\");\n return false;\n }\n return true;\n}\n\nbool KCalDataSource::disconnect(OSyncContext *)\n{\n \/\/ We are not locking the data\n \/\/calendar->save(saveTicket);\n delete calendar;\n calendar = NULL;\n return true;\n}\n\nstatic QString calc_hash(const KCal::Incidence *e)\n{\n QDateTime d = e->lastModified();\n if (!d.isValid())\n d = QDateTime::currentDateTime();\n \/*FIXME: not i18ned string *\/\n return d.toString();\n}\n\n\/** Report a list of calendar incidences (events or to-dos), with the\n * right objtype and objformat.\n *\n * This function exists because the logic for converting the events or to-dos\n * is the same, only the objtype and format is different.\n *\/\nbool KCalDataSource::report_incidence(OSyncContext *ctx, KCal::Incidence *e, const char *objtype, const char *objformat)\n{\n\tosync_debug(\"kcal\", 3, \"One calendar incidence (%s)\", objtype);\n\tQString hash = calc_hash(e);\n\n\tQString uid = e->uid();\n\n\t\/* Build a local calendar for the incidence data *\/\n\tKCal::CalendarLocal cal(calendar->timeZoneId());\n\tosync_debug(\"kcal\", 3, \"timezoneid: %s\\n\", (const char*)cal.timeZoneId().local8Bit());\n\tcal.addIncidence(e->clone());\n\n\t\/* Convert the data to vcalendar *\/\n\tKCal::ICalFormat format;\n\t\/* Ugly workaround to a ICalFormat bug, format.toString()\n\t * doesn't work, but if save() or load() is called before\n\t * toString(), the segmentation fault will not happen (as\n\t * the mCalendar private field will be set)\n\t *\n\tformat.save(&cal, \"\");*\/\n\tQCString datastr = format.toString(&cal).local8Bit();\n\tconst char *data = datastr;\n\n\tosync_debug(\"kcal\", 3, \"UID: %s\\n\", (const char*)uid.local8Bit());\n\tOSyncChange *chg = osync_change_new();\n\tosync_change_set_uid(chg, uid.local8Bit());\n\tosync_change_set_member(chg, member);\n\n\t\/\/ object type and format\n\tosync_change_set_objtype_string(chg, objtype);\n\tosync_change_set_objformat_string(chg, objformat);\n\tosync_change_set_data(chg, strdup(data), strlen(data), 1);\n\n\t\/\/ Use the hash table to check if the object\n\t\/\/ needs to be reported\n\tosync_change_set_hash(chg, hash.data());\n\tif (osync_hashtable_detect_change(hashtable, chg)) {\n\t\tosync_context_report_change(ctx, chg);\n\t\tosync_hashtable_update_hash(hashtable, chg);\n\t}\n\n return true;\n}\n\nbool KCalDataSource::get_changeinfo_events(OSyncContext *ctx)\n{\n KCal::Event::List events = calendar->events();\n osync_debug(\"kcal\", 3, \"Number of events: %d\", events.size());\n\n for (KCal::Event::List::ConstIterator i = events.begin(); i != events.end(); i++) {\n if (!report_incidence(ctx, *i, \"event\", \"vevent\"))\n return false;\n }\n\n osync_hashtable_report_deleted(hashtable, ctx, \"event\");\n\n return true;\n}\n\nbool KCalDataSource::get_changeinfo_todos(OSyncContext *ctx)\n{\n KCal::Todo::List todos = calendar->todos();\n\n osync_debug(\"kcal\", 3, \"Number of to-dos: %d\", todos.size());\n \n for (KCal::Todo::List::ConstIterator i = todos.begin(); i != todos.end(); i++) {\n osync_debug(\"kcal\", 3, \"%p: doesFloat: %d\", *i, (*i)->doesFloat());\n if (!report_incidence(ctx, *i, \"todo\", \"vtodo\"))\n return false;\n }\n\n osync_hashtable_report_deleted(hashtable, ctx, \"todo\");\n\n return true;\n\n}\n\nvoid KCalDataSource::get_data(OSyncContext *ctx, OSyncChange *)\n{\n osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, \"Not implemented yet\");\n}\n\n\/** Add or change a incidence on the calendar. This function\n * is used for events and to-dos\n *\/\nbool KCalDataSource::__access(OSyncContext *ctx, OSyncChange *chg)\n{\n OSyncChangeType type = osync_change_get_changetype(chg);\n osync_debug(\"kcal\", 3, \"%s\", __FUNCTION__);\n switch (type) {\n case CHANGE_DELETED:\n {\n KCal::Event *e = calendar->event(osync_change_get_uid(chg));\n if (!e) {\n osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, \"Event not found while deleting\");\n return false;\n }\n calendar->deleteEvent(e);\n }\n break;\n case CHANGE_ADDED:\n case CHANGE_MODIFIED:\n {\n KCal::ICalFormat format;\n\n \/* First, parse to a temporary calendar, because\n * we should set the uid on the events\n *\/\n KCal::CalendarLocal cal;\n QString data = QString::fromLocal8Bit(osync_change_get_data(chg), osync_change_get_datasize(chg));\n \/* Ugly workaround to a ICalFormat bug, format.toString()\n * doesn't work, but if save() or load() is called before\n * toString(), the segmentation fault will not happen (as\n * the mCalendar private field will be set)\n *\n format.save(&cal, \"\"); *\/\n if (!format.fromString(&cal, data)) {\n osync_context_report_error(ctx, OSYNC_ERROR_CONVERT, \"Couldn't import calendar data\");\n return false;\n }\n\n \/*FIXME: The event\/to-do will be overwritten. But I can't differentiate\n * between a field being removed and a missing field because\n * the other device don't support them, because OpenSync currently\n * doesn't have support for it. Yes, it is risky, but unfortunately\n * CalendarResources don't have support for changing an event\n * from vcard data, and not adding it.\n *\/\n KCal::Incidence *oldevt = calendar->incidence(osync_change_get_uid(chg));\n if (oldevt)\n calendar->deleteIncidence(oldevt);\n\n \/* Add the events from the temporary calendar, setting the UID\n *\n * We iterate over the list, but it should have only one event.\n *\/\n KCal::Incidence::List evts = cal.incidences();\n for (KCal::Incidence::List::ConstIterator i = evts.begin(); i != evts.end(); i++) {\n KCal::Incidence *e = (*i)->clone();\n e->setUid(osync_change_get_uid(chg));\n\n osync_debug(\"kcal\", 3, \"Writing incidence: uid: %s, summary: %s\",\n (const char*)e->uid().local8Bit(), (const char*)e->summary().local8Bit());\n calendar->addIncidence(e);\n }\n\n\n }\n break;\n default:\n osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, \"Invalid or unsupported change type\");\n return false;\n }\n\n \/* Save the changes *\/\n calendar->save();\n\n return true;\n}\n\nbool KCalDataSource::event_access(OSyncContext *ctx, OSyncChange *chg)\n{\n \/\/ We use the same function for events and to-do\n if (!__access(ctx, chg))\n return false;\n\n osync_context_report_success(ctx);\n return true;\n}\n\nbool KCalDataSource::event_commit_change(OSyncContext *ctx, OSyncChange *chg)\n{\n \/\/ We use the same function for events and to-do\n if ( !__access(ctx, chg) )\n return false;\n osync_hashtable_update_hash(hashtable, chg);\n osync_context_report_success(ctx);\n return true;\n}\n\nbool KCalDataSource::todo_access(OSyncContext *ctx, OSyncChange *chg)\n{\n \/\/ We use the same function for calendar and to-do\n if (!__access(ctx, chg))\n return false;\n\n osync_context_report_success(ctx);\n return true;\n}\n\nbool KCalDataSource::todo_commit_change(OSyncContext *ctx, OSyncChange *chg)\n{\n \/\/ We use the same function for calendar and to-do\n if ( !__access(ctx, chg) )\n return false;\n osync_hashtable_update_hash(hashtable, chg);\n osync_context_report_success(ctx);\n return true;\n}\n<commit_msg>Removing VCalFormat bug workarounds<commit_after>\/*********************************************************************** \nKCalendar support for OpenSync kdepim-sync plugin\nCopyright (C) 2004 Conectiva S. A.\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License version 2 as\npublished by the Free Software Foundation;\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY\nCLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES \nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN \nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF \nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, \nCOPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS \nSOFTWARE IS DISCLAIMED.\n*************************************************************************\/\n\/**\n * @autor Eduardo Pereira Habkost <ehabkost@conectiva.com.br>\n *\/\n\n#include <libkcal\/calendarresources.h>\n#include <libkcal\/icalformat.h>\n#include <libkcal\/calendarlocal.h>\n#include <kdeversion.h>\n\n#include \"osyncbase.h\"\n#include \"kcal.h\"\n\nKCalDataSource::KCalDataSource(OSyncMember *member, OSyncHashTable *hashtable)\n : hashtable(hashtable), member(member)\n{\n}\n\nbool KCalDataSource::connect(OSyncContext *ctx)\n{\n calendar = new KCal::CalendarResources();\n if (!calendar) {\n osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, \"Can't open KDE calendar\");\n return false;\n }\n#if KDE_IS_VERSION(3,3,0)\n \/* On KDE 3.2, there was no readConfig() and load(): the data\n * was loaded automatically on the CalendarResources() constructor\n *\/\n calendar->readConfig();\n calendar->load();\n#endif\n osync_debug(\"kcal\", 3, \"Calendar: %d events\", calendar->events().size());\n \/*FIXME: We don't lock the data *\/\n \/\/saveTicket = calendar->requestSaveTicket();\n if (!saveTicket) {\n osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, \"Couldn't request write to the KDE calendar\");\n return false;\n }\n return true;\n}\n\nbool KCalDataSource::disconnect(OSyncContext *)\n{\n \/\/ We are not locking the data\n \/\/calendar->save(saveTicket);\n delete calendar;\n calendar = NULL;\n return true;\n}\n\nstatic QString calc_hash(const KCal::Incidence *e)\n{\n QDateTime d = e->lastModified();\n if (!d.isValid())\n d = QDateTime::currentDateTime();\n \/*FIXME: not i18ned string *\/\n return d.toString();\n}\n\n\/** Report a list of calendar incidences (events or to-dos), with the\n * right objtype and objformat.\n *\n * This function exists because the logic for converting the events or to-dos\n * is the same, only the objtype and format is different.\n *\/\nbool KCalDataSource::report_incidence(OSyncContext *ctx, KCal::Incidence *e, const char *objtype, const char *objformat)\n{\n\tosync_debug(\"kcal\", 3, \"One calendar incidence (%s)\", objtype);\n\tQString hash = calc_hash(e);\n\n\tQString uid = e->uid();\n\n\t\/* Build a local calendar for the incidence data *\/\n\tKCal::CalendarLocal cal(calendar->timeZoneId());\n\tosync_debug(\"kcal\", 3, \"timezoneid: %s\\n\", (const char*)cal.timeZoneId().local8Bit());\n\tcal.addIncidence(e->clone());\n\n\t\/* Convert the data to vcalendar *\/\n\tKCal::ICalFormat format;\n\tQCString datastr = format.toString(&cal).local8Bit();\n\tconst char *data = datastr;\n\n\tosync_debug(\"kcal\", 3, \"UID: %s\\n\", (const char*)uid.local8Bit());\n\tOSyncChange *chg = osync_change_new();\n\tosync_change_set_uid(chg, uid.local8Bit());\n\tosync_change_set_member(chg, member);\n\n\t\/\/ object type and format\n\tosync_change_set_objtype_string(chg, objtype);\n\tosync_change_set_objformat_string(chg, objformat);\n\tosync_change_set_data(chg, strdup(data), strlen(data), 1);\n\n\t\/\/ Use the hash table to check if the object\n\t\/\/ needs to be reported\n\tosync_change_set_hash(chg, hash.data());\n\tif (osync_hashtable_detect_change(hashtable, chg)) {\n\t\tosync_context_report_change(ctx, chg);\n\t\tosync_hashtable_update_hash(hashtable, chg);\n\t}\n\n return true;\n}\n\nbool KCalDataSource::get_changeinfo_events(OSyncContext *ctx)\n{\n KCal::Event::List events = calendar->events();\n osync_debug(\"kcal\", 3, \"Number of events: %d\", events.size());\n\n for (KCal::Event::List::ConstIterator i = events.begin(); i != events.end(); i++) {\n if (!report_incidence(ctx, *i, \"event\", \"vevent\"))\n return false;\n }\n\n osync_hashtable_report_deleted(hashtable, ctx, \"event\");\n\n return true;\n}\n\nbool KCalDataSource::get_changeinfo_todos(OSyncContext *ctx)\n{\n KCal::Todo::List todos = calendar->todos();\n\n osync_debug(\"kcal\", 3, \"Number of to-dos: %d\", todos.size());\n \n for (KCal::Todo::List::ConstIterator i = todos.begin(); i != todos.end(); i++) {\n osync_debug(\"kcal\", 3, \"%p: doesFloat: %d\", *i, (*i)->doesFloat());\n if (!report_incidence(ctx, *i, \"todo\", \"vtodo\"))\n return false;\n }\n\n osync_hashtable_report_deleted(hashtable, ctx, \"todo\");\n\n return true;\n\n}\n\nvoid KCalDataSource::get_data(OSyncContext *ctx, OSyncChange *)\n{\n osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, \"Not implemented yet\");\n}\n\n\/** Add or change a incidence on the calendar. This function\n * is used for events and to-dos\n *\/\nbool KCalDataSource::__access(OSyncContext *ctx, OSyncChange *chg)\n{\n OSyncChangeType type = osync_change_get_changetype(chg);\n osync_debug(\"kcal\", 3, \"%s\", __FUNCTION__);\n switch (type) {\n case CHANGE_DELETED:\n {\n KCal::Event *e = calendar->event(osync_change_get_uid(chg));\n if (!e) {\n osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, \"Event not found while deleting\");\n return false;\n }\n calendar->deleteEvent(e);\n }\n break;\n case CHANGE_ADDED:\n case CHANGE_MODIFIED:\n {\n KCal::ICalFormat format;\n\n \/* First, parse to a temporary calendar, because\n * we should set the uid on the events\n *\/\n KCal::CalendarLocal cal;\n QString data = QString::fromLocal8Bit(osync_change_get_data(chg), osync_change_get_datasize(chg));\n if (!format.fromString(&cal, data)) {\n osync_context_report_error(ctx, OSYNC_ERROR_CONVERT, \"Couldn't import calendar data\");\n return false;\n }\n\n \/*FIXME: The event\/to-do will be overwritten. But I can't differentiate\n * between a field being removed and a missing field because\n * the other device don't support them, because OpenSync currently\n * doesn't have support for it. Yes, it is risky, but unfortunately\n * CalendarResources don't have support for changing an event\n * from vcard data, and not adding it.\n *\/\n KCal::Incidence *oldevt = calendar->incidence(osync_change_get_uid(chg));\n if (oldevt)\n calendar->deleteIncidence(oldevt);\n\n \/* Add the events from the temporary calendar, setting the UID\n *\n * We iterate over the list, but it should have only one event.\n *\/\n KCal::Incidence::List evts = cal.incidences();\n for (KCal::Incidence::List::ConstIterator i = evts.begin(); i != evts.end(); i++) {\n KCal::Incidence *e = (*i)->clone();\n e->setUid(osync_change_get_uid(chg));\n\n osync_debug(\"kcal\", 3, \"Writing incidence: uid: %s, summary: %s\",\n (const char*)e->uid().local8Bit(), (const char*)e->summary().local8Bit());\n calendar->addIncidence(e);\n }\n\n\n }\n break;\n default:\n osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, \"Invalid or unsupported change type\");\n return false;\n }\n\n \/* Save the changes *\/\n calendar->save();\n\n return true;\n}\n\nbool KCalDataSource::event_access(OSyncContext *ctx, OSyncChange *chg)\n{\n \/\/ We use the same function for events and to-do\n if (!__access(ctx, chg))\n return false;\n\n osync_context_report_success(ctx);\n return true;\n}\n\nbool KCalDataSource::event_commit_change(OSyncContext *ctx, OSyncChange *chg)\n{\n \/\/ We use the same function for events and to-do\n if ( !__access(ctx, chg) )\n return false;\n osync_hashtable_update_hash(hashtable, chg);\n osync_context_report_success(ctx);\n return true;\n}\n\nbool KCalDataSource::todo_access(OSyncContext *ctx, OSyncChange *chg)\n{\n \/\/ We use the same function for calendar and to-do\n if (!__access(ctx, chg))\n return false;\n\n osync_context_report_success(ctx);\n return true;\n}\n\nbool KCalDataSource::todo_commit_change(OSyncContext *ctx, OSyncChange *chg)\n{\n \/\/ We use the same function for calendar and to-do\n if ( !__access(ctx, chg) )\n return false;\n osync_hashtable_update_hash(hashtable, chg);\n osync_context_report_success(ctx);\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * arcemu MMORPG Server\n * Copyright (C) 2005-2008 arcemu Team <http:\/\/www.arcemuemu.com\/>\n *\n * Circular Buffer Class\n * Based on the Bip Buffer concept, from http:\/\/www.codeproject.com\/KB\/IP\/bipbuffer.aspx\n * Implementation Copyright (c) 2008 Burlex\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * 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. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"..\/Common.h\"\n#include \"CircularBuffer.h\"\n\n\/** Constructor\n *\/\nCircularBuffer::CircularBuffer()\n{\n\tm_buffer = m_bufferEnd = m_regionAPointer = m_regionBPointer = NULL;\n\tm_regionASize = m_regionBSize = 0;\n}\n\n\/** Destructor\n *\/\nCircularBuffer::~CircularBuffer()\n{\n\tfree(m_buffer);\n}\n\n\/** Read bytes from the buffer\n * @param destination pointer to destination where bytes will be written\n * @param bytes number of bytes to read\n * @return true if there was enough data, false otherwise\n *\/\nbool CircularBuffer::Read(void * destination, size_t bytes)\n{\n\t\/\/ copy as much out of region a\n\tsize_t cnt = bytes;\n\tsize_t aRead = 0, bRead = 0;\n\tif( (m_regionASize + m_regionBSize) < bytes )\n\t\treturn false;\n\n\t\/\/ If we have both region A and region B, always \"finish\" off region A first, as\n\t\/\/ this will contain the \"oldest\" data\n\tif( m_regionASize > 0 )\n\t{\n\t\taRead = (cnt > m_regionASize) ? m_regionASize : cnt;\n\t\tmemcpy(destination, m_regionAPointer, aRead);\n\t\tm_regionASize -= aRead;\n\t\tm_regionAPointer += aRead;\n\t\tcnt -= aRead;\n\t}\n\n\t\/\/ Data left over? read the data from buffer B\n\tif( cnt > 0 && m_regionBSize > 0 )\n\t{\n\t\tbRead = (cnt > m_regionBSize) ? m_regionBSize : cnt;\n\t\tmemcpy((char*)destination + aRead, m_regionBPointer, bRead);\n\t\tm_regionBSize -= bRead;\n\t\tm_regionBPointer += bRead;\n\t\tcnt -= bRead;\n\t}\n\n\t\/\/ is buffer A empty? move buffer B to buffer A, to increase future performance\n\tif( m_regionASize == 0 )\n\t{\n\t\tif( m_regionBSize > 0 )\n\t\t{\n\t\t\t\/\/ push it all to the start of the buffer.\n\t\t\tif( m_regionBPointer != m_buffer )\n\t\t\t\tmemmove(m_buffer, m_regionBPointer, m_regionBSize);\n\n\t\t\tm_regionAPointer = m_buffer;\n\t\t\tm_regionASize = m_regionBSize;\n\t\t\tm_regionBPointer = NULL;\n\t\t\tm_regionBSize = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ no data in region b\n\t\t\tm_regionBPointer = NULL;\n\t\t\tm_regionBSize = 0;\n\t\t\tm_regionAPointer = m_buffer;\n\t\t\tm_regionASize = 0;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nvoid CircularBuffer::AllocateB()\n{\n\t\/\/printf(\"[allocating B]\\n\");\n\tm_regionBPointer = m_buffer;\n}\n\n\/** Write bytes to the buffer\n * @param data pointer to the data to be written\n * @param bytes number of bytes to be written\n * @return true if was successful, otherwise false\n *\/\nbool CircularBuffer::Write(const void * data, size_t bytes)\n{\n\t\/\/ If buffer B exists, write to it.\n\tif( m_regionBPointer != NULL )\n\t{\n\t\tif( GetBFreeSpace() < bytes )\n\t\t\treturn false;\n\n\t\tmemcpy(&m_regionBPointer[m_regionBSize], data, bytes);\n\t\tm_regionBSize += bytes;\n\t\treturn true;\n\t}\n\n\t\/\/ Otherwise, write to buffer A, or initialize buffer B depending on which has more space.\n\tif( GetAFreeSpace() < GetSpaceBeforeA() )\n\t{\n\t\tAllocateB();\n\t\tif( GetBFreeSpace() < bytes )\n\t\t\treturn false;\n\n\t\tmemcpy(&m_regionBPointer[m_regionBSize], data, bytes);\n\t\tm_regionBSize += bytes;\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tif( GetAFreeSpace() < bytes )\n\t\t\treturn false;\n\n\t\tmemcpy(&m_regionAPointer[m_regionASize], data, bytes);\n\t\tm_regionASize += bytes;\n\t\treturn true;\n\t}\n}\n\n\/** Returns the number of available bytes left.\n *\/\nsize_t CircularBuffer::GetSpace()\n{\n\tif( m_regionBPointer != NULL )\n\t\treturn GetBFreeSpace();\n\telse\n\t{\n\t\t\/\/ would allocating buffer B get us more data?\n\t\tif( GetAFreeSpace() < GetSpaceBeforeA() )\n\t\t{\n\t\t\tAllocateB();\n\t\t\treturn GetBFreeSpace();\n\t\t}\n\n\t\t\/\/ or not?\n\t\treturn GetAFreeSpace();\n\t}\n}\n\n\/** Returns the number of bytes currently stored in the buffer.\n *\/\nsize_t CircularBuffer::GetSize()\n{\n\treturn m_regionASize + m_regionBSize;\n}\n\n\/** Returns the number of contiguous bytes (that can be pushed out in one operation)\n *\/\nsize_t CircularBuffer::GetContiguiousBytes()\n{\n\tif( m_regionASize )\t\t\t\/\/ A before B\n\t\treturn m_regionASize;\n\telse\n\t\treturn m_regionBSize;\n}\n\n\/** Removes len bytes from the front of the buffer\n * @param len the number of bytes to \"cut\"\n *\/\nvoid CircularBuffer::Remove(size_t len)\n{\n\t\/\/ remove from A first before we remove from b\n\tsize_t cnt = len;\n\tsize_t aRem, bRem;\n\n\t\/\/ If we have both region A and region B, always \"finish\" off region A first, as\n\t\/\/ this will contain the \"oldest\" data\n\tif( m_regionASize > 0 )\n\t{\n\t\taRem = (cnt > m_regionASize) ? m_regionASize : cnt;\n\t\tm_regionASize -= aRem;\n\t\tm_regionAPointer += aRem;\n\t\tcnt -= aRem;\n\t}\n\n\t\/\/ Data left over? cut the data from buffer B\n\tif( cnt > 0 && m_regionBSize > 0 )\n\t{\n\t\tbRem = (cnt > m_regionBSize) ? m_regionBSize : cnt;\n\t\tm_regionBSize -= bRem;\n\t\tm_regionBPointer += bRem;\n\t\tcnt -= bRem;\n\t}\n\n\t\/\/ is buffer A empty? move buffer B to buffer A, to increase future performance\n\tif( m_regionASize == 0 )\n\t{\n\t\tif( m_regionBSize > 0 )\n\t\t{\n\t\t\t\/\/ push it all to the start of the buffer.\n\t\t\tif( m_regionBPointer != m_buffer )\n\t\t\t\tmemmove(m_buffer, m_regionBPointer, m_regionBSize);\n\t\n\t\t\tm_regionAPointer = m_buffer;\n\t\t\tm_regionASize = m_regionBSize;\n\t\t\tm_regionBPointer = NULL;\n\t\t\tm_regionBSize = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ no data in region b\n\t\t\tm_regionBPointer = NULL;\n\t\t\tm_regionBSize = 0;\n\t\t\tm_regionAPointer = m_buffer;\n\t\t\tm_regionASize = 0;\n\t\t}\n\t}\n}\n\n\/** Returns a pointer at the \"end\" of the buffer, where new data can be written\n *\/\nvoid * CircularBuffer::GetBuffer()\n{\n\tif( m_regionBPointer != NULL )\n\t\treturn m_regionBPointer + m_regionBSize;\n\telse\n\t\treturn m_regionAPointer + m_regionASize;\n}\n\n\/** Allocate the buffer with room for size bytes\n * @param size the number of bytes to allocate\n *\/\nvoid CircularBuffer::Allocate(size_t size)\n{\n\tm_buffer = (uint8*)malloc(size);\n\tm_bufferEnd = m_buffer + size;\n\tm_regionAPointer = m_buffer;\t\t\/\/ reset A to the start\n}\n\n\/** Increments the \"writen\" pointer forward len bytes\n * @param len number of bytes to step\n *\/\nvoid CircularBuffer::IncrementWritten(size_t len)\t\t\t\/\/ known as \"commit\"\n{\n\tif( m_regionBPointer != NULL )\n\t\tm_regionBSize += len;\n\telse\n\t\tm_regionASize += len;\n}\n\n\/** Returns a pointer at the \"beginning\" of the buffer, where data can be pulled from\n *\/\nvoid * CircularBuffer::GetBufferStart()\n{\n\tif( m_regionASize > 0 )\n\t\treturn m_regionAPointer;\n\telse\n\t\treturn m_regionBPointer;\n\t\t\n}\n<commit_msg>NULL checks<commit_after>\/*\n * arcemu MMORPG Server\n * Copyright (C) 2005-2008 arcemu Team <http:\/\/www.arcemuemu.com\/>\n *\n * Circular Buffer Class\n * Based on the Bip Buffer concept, from http:\/\/www.codeproject.com\/KB\/IP\/bipbuffer.aspx\n * Implementation Copyright (c) 2008 Burlex\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * 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. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"..\/Common.h\"\n#include \"CircularBuffer.h\"\n\n\/** Constructor\n *\/\nCircularBuffer::CircularBuffer()\n{\n\tm_buffer = m_bufferEnd = m_regionAPointer = m_regionBPointer = NULL;\n\tm_regionASize = m_regionBSize = 0;\n}\n\n\/** Destructor\n *\/\nCircularBuffer::~CircularBuffer()\n{\n\tfree(m_buffer);\n}\n\n\/** Read bytes from the buffer\n * @param destination pointer to destination where bytes will be written\n * @param bytes number of bytes to read\n * @return true if there was enough data, false otherwise\n *\/\nbool CircularBuffer::Read(void * destination, size_t bytes)\n{\n\tif (m_buffer == NULL)\n\t\treturn false;\n\n\t\/\/ copy as much out of region a\n\tsize_t cnt = bytes;\n\tsize_t aRead = 0, bRead = 0;\n\tif( (m_regionASize + m_regionBSize) < bytes )\n\t\treturn false;\n\n\t\/\/ If we have both region A and region B, always \"finish\" off region A first, as\n\t\/\/ this will contain the \"oldest\" data\n\tif( m_regionASize > 0 )\n\t{\n\t\taRead = (cnt > m_regionASize) ? m_regionASize : cnt;\n\t\tmemcpy(destination, m_regionAPointer, aRead);\n\t\tm_regionASize -= aRead;\n\t\tm_regionAPointer += aRead;\n\t\tcnt -= aRead;\n\t}\n\n\t\/\/ Data left over? read the data from buffer B\n\tif( cnt > 0 && m_regionBSize > 0 )\n\t{\n\t\tbRead = (cnt > m_regionBSize) ? m_regionBSize : cnt;\n\t\tmemcpy((char*)destination + aRead, m_regionBPointer, bRead);\n\t\tm_regionBSize -= bRead;\n\t\tm_regionBPointer += bRead;\n\t\tcnt -= bRead;\n\t}\n\n\t\/\/ is buffer A empty? move buffer B to buffer A, to increase future performance\n\tif( m_regionASize == 0 )\n\t{\n\t\tif( m_regionBSize > 0 )\n\t\t{\n\t\t\t\/\/ push it all to the start of the buffer.\n\t\t\tif( m_regionBPointer != m_buffer )\n\t\t\t\tmemmove(m_buffer, m_regionBPointer, m_regionBSize);\n\n\t\t\tm_regionAPointer = m_buffer;\n\t\t\tm_regionASize = m_regionBSize;\n\t\t\tm_regionBPointer = NULL;\n\t\t\tm_regionBSize = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ no data in region b\n\t\t\tm_regionBPointer = NULL;\n\t\t\tm_regionBSize = 0;\n\t\t\tm_regionAPointer = m_buffer;\n\t\t\tm_regionASize = 0;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nvoid CircularBuffer::AllocateB()\n{\n\t\/\/printf(\"[allocating B]\\n\");\n\tm_regionBPointer = m_buffer;\n}\n\n\/** Write bytes to the buffer\n * @param data pointer to the data to be written\n * @param bytes number of bytes to be written\n * @return true if was successful, otherwise false\n *\/\nbool CircularBuffer::Write(const void * data, size_t bytes)\n{\n\tif (m_buffer == NULL)\n\t\treturn false;\n\n\t\/\/ If buffer B exists, write to it.\n\tif( m_regionBPointer != NULL )\n\t{\n\t\tif( GetBFreeSpace() < bytes )\n\t\t\treturn false;\n\n\t\tmemcpy(&m_regionBPointer[m_regionBSize], data, bytes);\n\t\tm_regionBSize += bytes;\n\t\treturn true;\n\t}\n\n\t\/\/ Otherwise, write to buffer A, or initialize buffer B depending on which has more space.\n\tif( GetAFreeSpace() < GetSpaceBeforeA() )\n\t{\n\t\tAllocateB();\n\t\tif( GetBFreeSpace() < bytes )\n\t\t\treturn false;\n\n\t\tmemcpy(&m_regionBPointer[m_regionBSize], data, bytes);\n\t\tm_regionBSize += bytes;\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tif( GetAFreeSpace() < bytes )\n\t\t\treturn false;\n\n\t\tmemcpy(&m_regionAPointer[m_regionASize], data, bytes);\n\t\tm_regionASize += bytes;\n\t\treturn true;\n\t}\n}\n\n\/** Returns the number of available bytes left.\n *\/\nsize_t CircularBuffer::GetSpace()\n{\n\tif( m_regionBPointer != NULL )\n\t\treturn GetBFreeSpace();\n\telse\n\t{\n\t\t\/\/ would allocating buffer B get us more data?\n\t\tif( GetAFreeSpace() < GetSpaceBeforeA() )\n\t\t{\n\t\t\tAllocateB();\n\t\t\treturn GetBFreeSpace();\n\t\t}\n\n\t\t\/\/ or not?\n\t\treturn GetAFreeSpace();\n\t}\n}\n\n\/** Returns the number of bytes currently stored in the buffer.\n *\/\nsize_t CircularBuffer::GetSize()\n{\n\treturn m_regionASize + m_regionBSize;\n}\n\n\/** Returns the number of contiguous bytes (that can be pushed out in one operation)\n *\/\nsize_t CircularBuffer::GetContiguiousBytes()\n{\n\tif( m_regionASize )\t\t\t\/\/ A before B\n\t\treturn m_regionASize;\n\telse\n\t\treturn m_regionBSize;\n}\n\n\/** Removes len bytes from the front of the buffer\n * @param len the number of bytes to \"cut\"\n *\/\nvoid CircularBuffer::Remove(size_t len)\n{\n\t\/\/ remove from A first before we remove from b\n\tsize_t cnt = len;\n\tsize_t aRem, bRem;\n\n\t\/\/ If we have both region A and region B, always \"finish\" off region A first, as\n\t\/\/ this will contain the \"oldest\" data\n\tif( m_regionASize > 0 )\n\t{\n\t\taRem = (cnt > m_regionASize) ? m_regionASize : cnt;\n\t\tm_regionASize -= aRem;\n\t\tm_regionAPointer += aRem;\n\t\tcnt -= aRem;\n\t}\n\n\t\/\/ Data left over? cut the data from buffer B\n\tif( cnt > 0 && m_regionBSize > 0 )\n\t{\n\t\tbRem = (cnt > m_regionBSize) ? m_regionBSize : cnt;\n\t\tm_regionBSize -= bRem;\n\t\tm_regionBPointer += bRem;\n\t\tcnt -= bRem;\n\t}\n\n\t\/\/ is buffer A empty? move buffer B to buffer A, to increase future performance\n\tif( m_regionASize == 0 )\n\t{\n\t\tif( m_regionBSize > 0 )\n\t\t{\n\t\t\t\/\/ push it all to the start of the buffer.\n\t\t\tif( m_regionBPointer != m_buffer )\n\t\t\t\tmemmove(m_buffer, m_regionBPointer, m_regionBSize);\n\t\n\t\t\tm_regionAPointer = m_buffer;\n\t\t\tm_regionASize = m_regionBSize;\n\t\t\tm_regionBPointer = NULL;\n\t\t\tm_regionBSize = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ no data in region b\n\t\t\tm_regionBPointer = NULL;\n\t\t\tm_regionBSize = 0;\n\t\t\tm_regionAPointer = m_buffer;\n\t\t\tm_regionASize = 0;\n\t\t}\n\t}\n}\n\n\/** Returns a pointer at the \"end\" of the buffer, where new data can be written\n *\/\nvoid * CircularBuffer::GetBuffer()\n{\n\tif( m_regionBPointer != NULL )\n\t\treturn m_regionBPointer + m_regionBSize;\n\telse\n\t\treturn m_regionAPointer + m_regionASize;\n}\n\n\/** Allocate the buffer with room for size bytes\n * @param size the number of bytes to allocate\n *\/\nvoid CircularBuffer::Allocate(size_t size)\n{\n\tm_buffer = (uint8*)malloc(size);\n\tm_bufferEnd = m_buffer + size;\n\tm_regionAPointer = m_buffer;\t\t\/\/ reset A to the start\n}\n\n\/** Increments the \"writen\" pointer forward len bytes\n * @param len number of bytes to step\n *\/\nvoid CircularBuffer::IncrementWritten(size_t len)\t\t\t\/\/ known as \"commit\"\n{\n\tif( m_regionBPointer != NULL )\n\t\tm_regionBSize += len;\n\telse\n\t\tm_regionASize += len;\n}\n\n\/** Returns a pointer at the \"beginning\" of the buffer, where data can be pulled from\n *\/\nvoid * CircularBuffer::GetBufferStart()\n{\n\tif( m_regionASize > 0 )\n\t\treturn m_regionAPointer;\n\telse\n\t\treturn m_regionBPointer;\n\t\t\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 1998 by Jorrit Tyberghein \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 <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"cssysdef.h\"\n#include \"util.h\"\n#include \"isound\/loader.h\"\n#include \"soundraw.h\"\n#include \"sndload.h\"\n\n\/\/ Microsoft Wav file loader\n\/\/ support 8 and 16 bits PCM (RIFF)\n\nclass csSoundLoader_WAV : public iSoundLoader\n{\npublic:\n DECLARE_IBASE;\n\n csSoundLoader_WAV(iBase *p) {\n CONSTRUCT_IBASE(p);\n }\n virtual bool Initialize(iSystem *) {\n return true;\n }\n virtual iSoundData *LoadSound(void *Buffer, unsigned long Size) const;\n};\n\nIMPLEMENT_IBASE(csSoundLoader_WAV)\n IMPLEMENTS_INTERFACE(iSoundLoader)\n IMPLEMENTS_INTERFACE(iPlugIn)\nIMPLEMENT_IBASE_END;\n\nIMPLEMENT_FACTORY(csSoundLoader_WAV);\n\n\nstruct _WAVchk\n{\n char chunk[4];\n unsigned long len;\n} wavchk;\n\nstruct _WAVhdr\n{\n char format[4];\n unsigned long f_len;\n char fmt[8];\n unsigned long fmt_len;\n unsigned short fmt_tag;\n unsigned short channel;\n unsigned long samples_per_sec;\n unsigned long avg_bytes_per_sec;\n unsigned short blk_align;\n unsigned short bits_per_sample;\n} wavhdr;\n\n#define setStream(x) {if(x>size) {goto exit_read;} else {index=x;}}\n#define canAddStream(x) {if((index+x)>size) goto exit_read;}\n#define addStream(x) {if((index+x)>size) {goto exit_read;} else {index+=x;}}\n#define Stream buf[index]\n\niSoundData *csSoundLoader_WAV::LoadSound(void *databuf, ULong size) const {\n UByte *buf = (UByte*) databuf;\n int index=0;\n\n csSoundDataRaw *sb= NULL;\n char *data=NULL;\n UByte *ptr;\n UByte *ptr_end;\n\n memset(&wavhdr, 0, sizeof(wavhdr));\n if(size<sizeof(wavhdr)) goto exit_read;\n \n if(memcpy(&wavhdr, &Stream, sizeof(wavhdr))==NULL)\n goto exit_read;\n canAddStream(sizeof(wavhdr));\n addStream(sizeof(wavhdr));\n\n if(memcmp(wavhdr.format, \"RIFF\", 4))\n goto exit_read;\n\n if(memcmp(wavhdr.fmt, \"WAVEfmt \", 8))\n goto exit_read;\n \n#ifdef CS_BIG_ENDIAN\n wavhdr.f_len = ByteSwap32bit( wavhdr.f_len );\n wavhdr.fmt_len = ByteSwap32bit( wavhdr.fmt_len );\n wavhdr.fmt_tag = ByteSwap16bit( wavhdr.fmt_tag );\n wavhdr.channel = ByteSwap16bit( wavhdr.channel );\n wavhdr.samples_per_sec = ByteSwap32bit( wavhdr.samples_per_sec );\n wavhdr.avg_bytes_per_sec = ByteSwap32bit( wavhdr.avg_bytes_per_sec );\n wavhdr.blk_align = ByteSwap16bit( wavhdr.blk_align );\n wavhdr.bits_per_sample = ByteSwap16bit( wavhdr.bits_per_sample );\n#endif \/\/ CS_BIG_ENDIAN\n\n if(!((wavhdr.channel == 1) || (wavhdr.channel == 2)))\n goto exit_read;\n \n\n ptr=&Stream;\n ptr_end=ptr+size;\n while(ptr<ptr_end)\n {\n memcpy(&wavchk, ptr, sizeof(wavchk));\n#ifdef CS_BIG_ENDIAN\n wavchk.len = ByteSwap32bit( wavchk.len );\n#endif \/\/ CS_BIG_ENDIAN\n\n ptr+=sizeof(wavchk);\n if(memcmp(wavchk.chunk, \"data\", 4)==0)\n break;\n ptr+=wavchk.len;\n }\n \n data=new char[wavchk.len];\n if(data==NULL)\n goto exit_read;\n \n if(memcpy(data, ptr, wavchk.len)==NULL)\n goto exit_read; \n\n#ifdef CS_BIG_ENDIAN\n if ( wavhdr.bits_per_sample==16 ) {\n ByteSwap16bitBuffer( (unsigned short *)data, wavchk.len \/ 2 );\n }\n#endif \/\/ CS_BIG_ENDIAN\n\n\n csSoundFormat Format;\n Format.Freq=wavhdr.samples_per_sec;\n Format.Bits=wavhdr.bits_per_sample;\n Format.Channels=wavhdr.channel;\n sb=new csSoundDataRaw(NULL, data,\n (wavhdr.bits_per_sample==16)?(wavchk.len\/2)-1:wavchk.len-1, Format);\n\n goto exit_ok;\nexit_read:\n if(data) delete [] data;\n\nexit_ok:\n return sb;\n}\n<commit_msg>Corrected the include to util.h and fixed a very freaky compile error it generated in VC6. :-)<commit_after>\/*\n Copyright (C) 1998 by Jorrit Tyberghein \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 <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"cssysdef.h\"\n#include \"csutil\/util.h\"\n#include \"isound\/loader.h\"\n#include \"soundraw.h\"\n#include \"sndload.h\"\n\n\/\/ Microsoft Wav file loader\n\/\/ support 8 and 16 bits PCM (RIFF)\n\nclass csSoundLoader_WAV : public iSoundLoader\n{\npublic:\n DECLARE_IBASE;\n\n csSoundLoader_WAV(iBase *p) {\n CONSTRUCT_IBASE(p);\n }\n virtual bool Initialize(iSystem *) {\n return true;\n }\n virtual iSoundData *LoadSound(void *Buffer, unsigned long Size) const;\n};\n\nIMPLEMENT_IBASE(csSoundLoader_WAV)\n IMPLEMENTS_INTERFACE(iSoundLoader)\n IMPLEMENTS_INTERFACE(iPlugIn)\nIMPLEMENT_IBASE_END;\n\nIMPLEMENT_FACTORY(csSoundLoader_WAV);\n\n\nstruct _WAVchk\n{\n char chunk[4];\n unsigned long len;\n} wavchk;\n\nstruct _WAVhdr\n{\n char format[4];\n unsigned long f_len;\n char fmt[8];\n unsigned long fmt_len;\n unsigned short fmt_tag;\n unsigned short channel;\n unsigned long samples_per_sec;\n unsigned long avg_bytes_per_sec;\n unsigned short blk_align;\n unsigned short bits_per_sample;\n} wavhdr;\n\n#define setStream(x) {if(x>size) {goto exit_read;} else {index=x;}}\n#define canAddStream(x) {if((index+x)>size) goto exit_read;}\n#define addStream(x) {if((index+x)>size) {goto exit_read;} else {index+=x;}}\n#define Stream buf[index]\n\niSoundData *csSoundLoader_WAV::LoadSound(void *databuf, ULong size) const {\n UByte *buf = (UByte*) databuf;\n int index=0;\n\n csSoundDataRaw *sb= NULL;\n char *data=NULL;\n UByte *ptr;\n UByte *ptr_end;\n\n memset(&wavhdr, 0, sizeof(wavhdr));\n if(size<sizeof(wavhdr)) goto exit_read;\n \n if(memcpy(&wavhdr, &Stream, sizeof(wavhdr))==NULL)\n goto exit_read;\n canAddStream(sizeof(wavhdr));\n addStream(sizeof(wavhdr));\n\n if(memcmp(wavhdr.format, \"RIFF\", 4))\n goto exit_read;\n\n if(memcmp(wavhdr.fmt, \"WAVEfmt \", 8))\n goto exit_read;\n \n#ifdef CS_BIG_ENDIAN\n wavhdr.f_len = ByteSwap32bit( wavhdr.f_len );\n wavhdr.fmt_len = ByteSwap32bit( wavhdr.fmt_len );\n wavhdr.fmt_tag = ByteSwap16bit( wavhdr.fmt_tag );\n wavhdr.channel = ByteSwap16bit( wavhdr.channel );\n wavhdr.samples_per_sec = ByteSwap32bit( wavhdr.samples_per_sec );\n wavhdr.avg_bytes_per_sec = ByteSwap32bit( wavhdr.avg_bytes_per_sec );\n wavhdr.blk_align = ByteSwap16bit( wavhdr.blk_align );\n wavhdr.bits_per_sample = ByteSwap16bit( wavhdr.bits_per_sample );\n#endif \/\/ CS_BIG_ENDIAN\n\n if(!((wavhdr.channel == 1) || (wavhdr.channel == 2)))\n goto exit_read;\n \n\n ptr=&Stream;\n ptr_end=ptr+size;\n while(ptr<ptr_end)\n {\n memcpy(&wavchk, ptr, sizeof(wavchk));\n#ifdef CS_BIG_ENDIAN\n wavchk.len = ByteSwap32bit( wavchk.len );\n#endif \/\/ CS_BIG_ENDIAN\n\n ptr+=sizeof(wavchk);\n if(memcmp(wavchk.chunk, \"data\", 4)==0)\n break;\n ptr+=wavchk.len;\n }\n \n data=new char[wavchk.len];\n if(data==NULL)\n goto exit_read;\n \n if(memcpy(data, ptr, wavchk.len)==NULL)\n goto exit_read; \n\n#ifdef CS_BIG_ENDIAN\n if ( wavhdr.bits_per_sample==16 ) {\n ByteSwap16bitBuffer( (unsigned short *)data, wavchk.len \/ 2 );\n }\n#endif \/\/ CS_BIG_ENDIAN\n\n\n csSoundFormat Format;\n Format.Freq=wavhdr.samples_per_sec;\n Format.Bits=wavhdr.bits_per_sample;\n Format.Channels=wavhdr.channel;\n sb=new csSoundDataRaw(NULL, data,\n (wavhdr.bits_per_sample==16)?(wavchk.len\/2)-1:wavchk.len-1, Format);\n\n goto exit_ok;\nexit_read:\n if(data) delete [] data;\n\nexit_ok:\n return sb;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\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#include \"HistogramWidget.h\"\n\n#include \"ActiveObjects.h\"\n#include \"DataSource.h\"\n#include \"ModuleContour.h\"\n#include \"ModuleManager.h\"\n#include \"QVTKGLWidget.h\"\n#include \"Utilities.h\"\n\n#include \"vtkChartHistogramColorOpacityEditor.h\"\n\n#include <vtkContextScene.h>\n#include <vtkContextView.h>\n#include <vtkControlPointsItem.h>\n#include <vtkEventQtSlotConnect.h>\n#include <vtkPiecewiseFunction.h>\n#include <vtkRenderWindow.h>\n#include <vtkVector.h>\n\n#include <pqApplicationCore.h>\n#include <pqCoreUtilities.h>\n#include <pqPresetDialog.h>\n#include <pqRescaleRange.h>\n#include <pqResetScalarRangeReaction.h>\n#include <pqServerManagerModel.h>\n#include <pqView.h>\n\n#include <vtkPVDiscretizableColorTransferFunction.h>\n#include <vtkSMPropertyHelper.h>\n#include <vtkSMTransferFunctionManager.h>\n#include <vtkSMTransferFunctionProxy.h>\n#include <vtkSMViewProxy.h>\n\n#include <QCheckBox>\n#include <QColorDialog>\n#include <QHBoxLayout>\n#include <QToolButton>\n#include <QVBoxLayout>\n\n#include <QDebug>\n\nnamespace tomviz {\n\nHistogramWidget::HistogramWidget(QWidget* parent)\n : QWidget(parent), m_qvtk(new QVTKGLWidget(this))\n{\n \/\/ Set up our little chart.\n m_histogramView->SetRenderWindow(m_qvtk->GetRenderWindow());\n m_histogramView->SetInteractor(m_qvtk->GetInteractor());\n m_histogramView->GetScene()->AddItem(m_histogramColorOpacityEditor.Get());\n\n \/\/ Connect events from the histogram color\/opacity editor.\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkCommand::CursorChangedEvent,\n this,\n SLOT(histogramClicked(vtkObject*)));\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkCommand::EndEvent,\n this,\n SLOT(onScalarOpacityFunctionChanged()));\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkControlPointsItem::CurrentPointEditEvent,\n this,\n SLOT(onCurrentPointEditEvent()));\n\n auto hLayout = new QHBoxLayout(this);\n hLayout->addWidget(m_qvtk);\n auto vLayout = new QVBoxLayout;\n hLayout->addLayout(vLayout);\n hLayout->setContentsMargins(0, 0, 5, 0);\n\n vLayout->setContentsMargins(0, 0, 0, 0);\n vLayout->addStretch(1);\n\n auto button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqResetRange.png\"));\n button->setToolTip(\"Reset data range\");\n connect(button, SIGNAL(clicked()), this, SLOT(onResetRangeClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqResetRangeCustom.png\"));\n button->setToolTip(\"Specify data range\");\n connect(button, SIGNAL(clicked()), this, SLOT(onCustomRangeClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqInvert.png\"));\n button->setToolTip(\"Invert color map\");\n connect(button, SIGNAL(clicked()), this, SLOT(onInvertClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqFavorites.png\"));\n button->setToolTip(\"Choose preset color map\");\n connect(button, SIGNAL(clicked()), this, SLOT(onPresetClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n m_colorLegendToolButton = button;\n button->setIcon(QIcon(\":\/pqWidgets\/Icons\/pqScalarBar24.png\"));\n button->setToolTip(\"Show color legend in the 3D window.\");\n button->setCheckable(true);\n connect(button, SIGNAL(toggled(bool)), this, SIGNAL(colorLegendToggled(bool)));\n button->setChecked(false);\n vLayout->addWidget(button);\n\n vLayout->addStretch(1);\n\n connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),\n this, SLOT(updateUI()));\n connect(this, SIGNAL(colorMapUpdated()), this, SLOT(updateUI()));\n\n setLayout(hLayout);\n}\n\nHistogramWidget::~HistogramWidget() = default;\n\nvoid HistogramWidget::setLUT(vtkPVDiscretizableColorTransferFunction* lut)\n{\n if (m_LUT != lut) {\n if (m_scalarOpacityFunction) {\n m_eventLink->Disconnect(m_scalarOpacityFunction,\n vtkCommand::ModifiedEvent,\n this,\n SLOT(onScalarOpacityFunctionChanged()));\n }\n m_LUT = lut;\n m_scalarOpacityFunction = m_LUT->GetScalarOpacityFunction();\n m_eventLink->Connect(m_scalarOpacityFunction,\n vtkCommand::ModifiedEvent,\n this,\n SLOT(onScalarOpacityFunctionChanged()));\n emit colorMapUpdated();\n }\n}\n\nvoid HistogramWidget::setLUTProxy(vtkSMProxy* proxy)\n{\n if (m_LUTProxy != proxy) {\n m_LUTProxy = proxy;\n vtkPVDiscretizableColorTransferFunction* lut =\n vtkPVDiscretizableColorTransferFunction::SafeDownCast(\n proxy->GetClientSideObject());\n setLUT(lut);\n\n auto view = ActiveObjects::instance().activeView();\n\n \/\/ Update widget to reflect scalar bar visibility.\n if (m_LUTProxy) {\n auto sbProxy = getScalarBarRepresentation(view);\n if (sbProxy) {\n bool visible = vtkSMPropertyHelper(sbProxy, \"Visibility\").GetAsInt() == 1;\n m_colorLegendToolButton->setChecked(visible);\n }\n }\n }\n}\n\nvoid HistogramWidget::setInputData(vtkTable* table,\n const char* x_,\n const char* y_)\n{\n m_histogramColorOpacityEditor->SetHistogramInputData(table, x_, y_);\n m_histogramColorOpacityEditor->SetOpacityFunction(m_scalarOpacityFunction);\n if (m_LUT && table) {\n m_histogramColorOpacityEditor->SetScalarVisibility(true);\n m_histogramColorOpacityEditor->SetColorTransferFunction(m_LUT);\n m_histogramColorOpacityEditor->SelectColorArray(\"image_extents\");\n }\n m_histogramView->Render();\n}\n\nvtkSMProxy* HistogramWidget::getScalarBarRepresentation(vtkSMProxy* view)\n{\n if (!view) {\n return nullptr;\n }\n\n vtkSMTransferFunctionProxy* tferProxy =\n vtkSMTransferFunctionProxy::SafeDownCast(m_LUTProxy);\n Q_ASSERT(tferProxy);\n\n auto sbProxy = tferProxy->FindScalarBarRepresentation(view);\n if (!sbProxy) {\n \/\/ No scalar bar representation exists yet, create it and initialize it\n \/\/ with some default settings.\n vtkNew<vtkSMTransferFunctionManager> tferManager;\n sbProxy = tferManager->GetScalarBarRepresentation(m_LUTProxy, view);\n vtkSMPropertyHelper(sbProxy, \"Visibility\").Set(0);\n vtkSMPropertyHelper(sbProxy, \"Enabled\").Set(0);\n vtkSMPropertyHelper(sbProxy, \"Title\").Set(\"\");\n vtkSMPropertyHelper(sbProxy, \"ComponentTitle\").Set(\"\");\n sbProxy->UpdateVTKObjects();\n }\n\n return sbProxy;\n}\n\nvoid HistogramWidget::onScalarOpacityFunctionChanged()\n{\n auto core = pqApplicationCore::instance();\n auto smModel = core->getServerManagerModel();\n QList<pqView*> views = smModel->findItems<pqView*>();\n foreach (pqView* view, views) {\n view->render();\n }\n\n \/\/ Update the histogram\n m_histogramView->GetRenderWindow()->Render();\n\n \/\/ Update the scalar opacity function proxy as it does not update it's\n \/\/ internal state when the VTK object changes.\n if (!m_LUTProxy) {\n return;\n }\n\n vtkSMProxy* opacityMapProxy =\n vtkSMPropertyHelper(m_LUTProxy, \"ScalarOpacityFunction\", true).GetAsProxy();\n if (!opacityMapProxy) {\n return;\n }\n\n vtkSMPropertyHelper pointsHelper(opacityMapProxy, \"Points\");\n vtkObjectBase* opacityMapObject = opacityMapProxy->GetClientSideObject();\n auto pwf = vtkPiecewiseFunction::SafeDownCast(opacityMapObject);\n if (pwf) {\n pointsHelper.SetNumberOfElements(4 * pwf->GetSize());\n for (int i = 0; i < pwf->GetSize(); ++i) {\n double value[4];\n pwf->GetNodeValue(i, value);\n pointsHelper.Set(4 * i + 0, value[0]);\n pointsHelper.Set(4 * i + 1, value[1]);\n pointsHelper.Set(4 * i + 2, value[2]);\n pointsHelper.Set(4 * i + 3, value[3]);\n }\n }\n\n emit opacityChanged();\n}\n\nvoid HistogramWidget::onCurrentPointEditEvent()\n{\n double rgb[3];\n if (m_histogramColorOpacityEditor->GetCurrentControlPointColor(rgb)) {\n QColor color =\n QColorDialog::getColor(QColor::fromRgbF(rgb[0], rgb[1], rgb[2]),\n this,\n \"Select Color for Control Point\",\n QColorDialog::DontUseNativeDialog);\n if (color.isValid()) {\n rgb[0] = color.redF();\n rgb[1] = color.greenF();\n rgb[2] = color.blueF();\n m_histogramColorOpacityEditor->SetCurrentControlPointColor(rgb);\n onScalarOpacityFunctionChanged();\n }\n }\n}\n\nvoid HistogramWidget::histogramClicked(vtkObject*)\n{\n auto activeDataSource = ActiveObjects::instance().activeDataSource();\n Q_ASSERT(activeDataSource);\n\n auto view = ActiveObjects::instance().activeView();\n if (!view) {\n return;\n }\n\n \/\/ Use active ModuleContour is possible. Otherwise, find the first existing\n \/\/ ModuleContour instance or just create a new one, if none exists.\n typedef ModuleContour ModuleContourType;\n\n auto contour =\n qobject_cast<ModuleContourType*>(ActiveObjects::instance().activeModule());\n if (!contour) {\n QList<ModuleContourType*> contours =\n ModuleManager::instance().findModules<ModuleContourType*>(\n activeDataSource, view);\n if (contours.size() == 0) {\n contour = qobject_cast<ModuleContourType*>(\n ModuleManager::instance().createAndAddModule(\n \"Contour\", activeDataSource, view));\n } else {\n contour = contours[0];\n }\n ActiveObjects::instance().setActiveModule(contour);\n }\n Q_ASSERT(contour);\n contour->setIsoValue(m_histogramColorOpacityEditor->GetContourValue());\n tomviz::convert<pqView*>(view)->render();\n}\n\nvoid HistogramWidget::onResetRangeClicked()\n{\n pqResetScalarRangeReaction::resetScalarRangeToData(nullptr);\n}\n\nvoid HistogramWidget::onCustomRangeClicked()\n{\n vtkVector2d range;\n vtkDiscretizableColorTransferFunction* discFunc =\n vtkDiscretizableColorTransferFunction::SafeDownCast(\n m_LUTProxy->GetClientSideObject());\n if (!discFunc) {\n return;\n }\n discFunc->GetRange(range.GetData());\n pqRescaleRange dialog(pqCoreUtilities::mainWidget());\n dialog.setRange(range[0], range[1]);\n if (dialog.exec() == QDialog::Accepted) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(\n m_LUTProxy, dialog.minimum(), dialog.maximum());\n }\n renderViews();\n emit colorMapUpdated();\n}\n\nvoid HistogramWidget::onInvertClicked()\n{\n vtkSMTransferFunctionProxy::InvertTransferFunction(m_LUTProxy);\n renderViews();\n emit colorMapUpdated();\n}\n\nvoid HistogramWidget::onPresetClicked()\n{\n pqPresetDialog dialog(pqCoreUtilities::mainWidget(),\n pqPresetDialog::SHOW_NON_INDEXED_COLORS_ONLY);\n dialog.setCustomizableLoadColors(true);\n dialog.setCustomizableLoadOpacities(true);\n dialog.setCustomizableUsePresetRange(true);\n dialog.setCustomizableLoadAnnotations(false);\n connect(&dialog,\n SIGNAL(applyPreset(const Json::Value&)),\n SLOT(applyCurrentPreset()));\n dialog.exec();\n}\n\nvoid HistogramWidget::applyCurrentPreset()\n{\n auto dialog = qobject_cast<pqPresetDialog*>(sender());\n Q_ASSERT(dialog);\n\n vtkSMProxy* lut = m_LUTProxy;\n if (!lut) {\n return;\n }\n\n if (dialog->loadColors() || dialog->loadOpacities()) {\n vtkSMProxy* sof =\n vtkSMPropertyHelper(lut, \"ScalarOpacityFunction\", true).GetAsProxy();\n if (dialog->loadColors()) {\n vtkSMTransferFunctionProxy::ApplyPreset(\n lut, dialog->currentPreset(), !dialog->usePresetRange());\n }\n if (dialog->loadOpacities()) {\n if (sof) {\n vtkSMTransferFunctionProxy::ApplyPreset(\n sof, dialog->currentPreset(), !dialog->usePresetRange());\n } else {\n qWarning(\"Cannot load opacities since 'ScalarOpacityFunction' is not \"\n \"present.\");\n }\n }\n\n \/\/ We need to take extra care to avoid the color and opacity function ranges\n \/\/ from straying away from each other. This can happen if only one of them\n \/\/ is getting a preset and we're using the preset range.\n if (dialog->usePresetRange() &&\n (dialog->loadColors() ^ dialog->loadOpacities()) && sof) {\n double range[2];\n if (dialog->loadColors() &&\n vtkSMTransferFunctionProxy::GetRange(lut, range)) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(sof, range);\n } else if (dialog->loadOpacities() &&\n vtkSMTransferFunctionProxy::GetRange(sof, range)) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(lut, range);\n }\n }\n renderViews();\n emit colorMapUpdated();\n }\n}\n\nvoid HistogramWidget::updateUI()\n{\n auto view = ActiveObjects::instance().activeView();\n\n \/\/ Update widget to reflect scalar bar visibility.\n if (m_LUTProxy) {\n auto sbProxy = getScalarBarRepresentation(view);\n if (view && sbProxy) {\n m_colorLegendToolButton->blockSignals(true);\n m_colorLegendToolButton->\n setChecked(vtkSMPropertyHelper(sbProxy, \"Visibility\").GetAsInt() == 1);\n m_colorLegendToolButton->blockSignals(false);\n }\n }\n}\n\nvoid HistogramWidget::renderViews()\n{\n pqView* view =\n tomviz::convert<pqView*>(ActiveObjects::instance().activeView());\n if (view) {\n view->render();\n }\n}\n\nvoid HistogramWidget::showEvent(QShowEvent* event)\n{\n QWidget::showEvent(event);\n this->renderViews();\n}\n}\n<commit_msg>Modify the RangeLabelFormat for the scalar bar<commit_after>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\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#include \"HistogramWidget.h\"\n\n#include \"ActiveObjects.h\"\n#include \"DataSource.h\"\n#include \"ModuleContour.h\"\n#include \"ModuleManager.h\"\n#include \"QVTKGLWidget.h\"\n#include \"Utilities.h\"\n\n#include \"vtkChartHistogramColorOpacityEditor.h\"\n\n#include <vtkContextScene.h>\n#include <vtkContextView.h>\n#include <vtkControlPointsItem.h>\n#include <vtkEventQtSlotConnect.h>\n#include <vtkPiecewiseFunction.h>\n#include <vtkRenderWindow.h>\n#include <vtkVector.h>\n\n#include <pqApplicationCore.h>\n#include <pqCoreUtilities.h>\n#include <pqPresetDialog.h>\n#include <pqRescaleRange.h>\n#include <pqResetScalarRangeReaction.h>\n#include <pqServerManagerModel.h>\n#include <pqView.h>\n\n#include <vtkPVDiscretizableColorTransferFunction.h>\n#include <vtkSMPropertyHelper.h>\n#include <vtkSMTransferFunctionManager.h>\n#include <vtkSMTransferFunctionProxy.h>\n#include <vtkSMViewProxy.h>\n\n#include <QCheckBox>\n#include <QColorDialog>\n#include <QHBoxLayout>\n#include <QToolButton>\n#include <QVBoxLayout>\n\n#include <QDebug>\n\nnamespace tomviz {\n\nHistogramWidget::HistogramWidget(QWidget* parent)\n : QWidget(parent), m_qvtk(new QVTKGLWidget(this))\n{\n \/\/ Set up our little chart.\n m_histogramView->SetRenderWindow(m_qvtk->GetRenderWindow());\n m_histogramView->SetInteractor(m_qvtk->GetInteractor());\n m_histogramView->GetScene()->AddItem(m_histogramColorOpacityEditor.Get());\n\n \/\/ Connect events from the histogram color\/opacity editor.\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkCommand::CursorChangedEvent,\n this,\n SLOT(histogramClicked(vtkObject*)));\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkCommand::EndEvent,\n this,\n SLOT(onScalarOpacityFunctionChanged()));\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkControlPointsItem::CurrentPointEditEvent,\n this,\n SLOT(onCurrentPointEditEvent()));\n\n auto hLayout = new QHBoxLayout(this);\n hLayout->addWidget(m_qvtk);\n auto vLayout = new QVBoxLayout;\n hLayout->addLayout(vLayout);\n hLayout->setContentsMargins(0, 0, 5, 0);\n\n vLayout->setContentsMargins(0, 0, 0, 0);\n vLayout->addStretch(1);\n\n auto button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqResetRange.png\"));\n button->setToolTip(\"Reset data range\");\n connect(button, SIGNAL(clicked()), this, SLOT(onResetRangeClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqResetRangeCustom.png\"));\n button->setToolTip(\"Specify data range\");\n connect(button, SIGNAL(clicked()), this, SLOT(onCustomRangeClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqInvert.png\"));\n button->setToolTip(\"Invert color map\");\n connect(button, SIGNAL(clicked()), this, SLOT(onInvertClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqFavorites.png\"));\n button->setToolTip(\"Choose preset color map\");\n connect(button, SIGNAL(clicked()), this, SLOT(onPresetClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n m_colorLegendToolButton = button;\n button->setIcon(QIcon(\":\/pqWidgets\/Icons\/pqScalarBar24.png\"));\n button->setToolTip(\"Show color legend in the 3D window.\");\n button->setCheckable(true);\n connect(button, SIGNAL(toggled(bool)), this, SIGNAL(colorLegendToggled(bool)));\n button->setChecked(false);\n vLayout->addWidget(button);\n\n vLayout->addStretch(1);\n\n connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),\n this, SLOT(updateUI()));\n connect(this, SIGNAL(colorMapUpdated()), this, SLOT(updateUI()));\n\n setLayout(hLayout);\n}\n\nHistogramWidget::~HistogramWidget() = default;\n\nvoid HistogramWidget::setLUT(vtkPVDiscretizableColorTransferFunction* lut)\n{\n if (m_LUT != lut) {\n if (m_scalarOpacityFunction) {\n m_eventLink->Disconnect(m_scalarOpacityFunction,\n vtkCommand::ModifiedEvent,\n this,\n SLOT(onScalarOpacityFunctionChanged()));\n }\n m_LUT = lut;\n m_scalarOpacityFunction = m_LUT->GetScalarOpacityFunction();\n m_eventLink->Connect(m_scalarOpacityFunction,\n vtkCommand::ModifiedEvent,\n this,\n SLOT(onScalarOpacityFunctionChanged()));\n emit colorMapUpdated();\n }\n}\n\nvoid HistogramWidget::setLUTProxy(vtkSMProxy* proxy)\n{\n if (m_LUTProxy != proxy) {\n m_LUTProxy = proxy;\n vtkPVDiscretizableColorTransferFunction* lut =\n vtkPVDiscretizableColorTransferFunction::SafeDownCast(\n proxy->GetClientSideObject());\n setLUT(lut);\n\n auto view = ActiveObjects::instance().activeView();\n\n \/\/ Update widget to reflect scalar bar visibility.\n if (m_LUTProxy) {\n auto sbProxy = getScalarBarRepresentation(view);\n if (sbProxy) {\n bool visible = vtkSMPropertyHelper(sbProxy, \"Visibility\").GetAsInt() == 1;\n m_colorLegendToolButton->setChecked(visible);\n }\n }\n }\n}\n\nvoid HistogramWidget::setInputData(vtkTable* table,\n const char* x_,\n const char* y_)\n{\n m_histogramColorOpacityEditor->SetHistogramInputData(table, x_, y_);\n m_histogramColorOpacityEditor->SetOpacityFunction(m_scalarOpacityFunction);\n if (m_LUT && table) {\n m_histogramColorOpacityEditor->SetScalarVisibility(true);\n m_histogramColorOpacityEditor->SetColorTransferFunction(m_LUT);\n m_histogramColorOpacityEditor->SelectColorArray(\"image_extents\");\n }\n m_histogramView->Render();\n}\n\nvtkSMProxy* HistogramWidget::getScalarBarRepresentation(vtkSMProxy* view)\n{\n if (!view) {\n return nullptr;\n }\n\n vtkSMTransferFunctionProxy* tferProxy =\n vtkSMTransferFunctionProxy::SafeDownCast(m_LUTProxy);\n Q_ASSERT(tferProxy);\n\n auto sbProxy = tferProxy->FindScalarBarRepresentation(view);\n if (!sbProxy) {\n \/\/ No scalar bar representation exists yet, create it and initialize it\n \/\/ with some default settings.\n vtkNew<vtkSMTransferFunctionManager> tferManager;\n sbProxy = tferManager->GetScalarBarRepresentation(m_LUTProxy, view);\n vtkSMPropertyHelper(sbProxy, \"Visibility\").Set(0);\n vtkSMPropertyHelper(sbProxy, \"Enabled\").Set(0);\n vtkSMPropertyHelper(sbProxy, \"Title\").Set(\"\");\n vtkSMPropertyHelper(sbProxy, \"ComponentTitle\").Set(\"\");\n vtkSMPropertyHelper(sbProxy, \"RangeLabelFormat\").Set(\"%g\");\n sbProxy->UpdateVTKObjects();\n }\n\n return sbProxy;\n}\n\nvoid HistogramWidget::onScalarOpacityFunctionChanged()\n{\n auto core = pqApplicationCore::instance();\n auto smModel = core->getServerManagerModel();\n QList<pqView*> views = smModel->findItems<pqView*>();\n foreach (pqView* view, views) {\n view->render();\n }\n\n \/\/ Update the histogram\n m_histogramView->GetRenderWindow()->Render();\n\n \/\/ Update the scalar opacity function proxy as it does not update it's\n \/\/ internal state when the VTK object changes.\n if (!m_LUTProxy) {\n return;\n }\n\n vtkSMProxy* opacityMapProxy =\n vtkSMPropertyHelper(m_LUTProxy, \"ScalarOpacityFunction\", true).GetAsProxy();\n if (!opacityMapProxy) {\n return;\n }\n\n vtkSMPropertyHelper pointsHelper(opacityMapProxy, \"Points\");\n vtkObjectBase* opacityMapObject = opacityMapProxy->GetClientSideObject();\n auto pwf = vtkPiecewiseFunction::SafeDownCast(opacityMapObject);\n if (pwf) {\n pointsHelper.SetNumberOfElements(4 * pwf->GetSize());\n for (int i = 0; i < pwf->GetSize(); ++i) {\n double value[4];\n pwf->GetNodeValue(i, value);\n pointsHelper.Set(4 * i + 0, value[0]);\n pointsHelper.Set(4 * i + 1, value[1]);\n pointsHelper.Set(4 * i + 2, value[2]);\n pointsHelper.Set(4 * i + 3, value[3]);\n }\n }\n\n emit opacityChanged();\n}\n\nvoid HistogramWidget::onCurrentPointEditEvent()\n{\n double rgb[3];\n if (m_histogramColorOpacityEditor->GetCurrentControlPointColor(rgb)) {\n QColor color =\n QColorDialog::getColor(QColor::fromRgbF(rgb[0], rgb[1], rgb[2]),\n this,\n \"Select Color for Control Point\",\n QColorDialog::DontUseNativeDialog);\n if (color.isValid()) {\n rgb[0] = color.redF();\n rgb[1] = color.greenF();\n rgb[2] = color.blueF();\n m_histogramColorOpacityEditor->SetCurrentControlPointColor(rgb);\n onScalarOpacityFunctionChanged();\n }\n }\n}\n\nvoid HistogramWidget::histogramClicked(vtkObject*)\n{\n auto activeDataSource = ActiveObjects::instance().activeDataSource();\n Q_ASSERT(activeDataSource);\n\n auto view = ActiveObjects::instance().activeView();\n if (!view) {\n return;\n }\n\n \/\/ Use active ModuleContour is possible. Otherwise, find the first existing\n \/\/ ModuleContour instance or just create a new one, if none exists.\n typedef ModuleContour ModuleContourType;\n\n auto contour =\n qobject_cast<ModuleContourType*>(ActiveObjects::instance().activeModule());\n if (!contour) {\n QList<ModuleContourType*> contours =\n ModuleManager::instance().findModules<ModuleContourType*>(\n activeDataSource, view);\n if (contours.size() == 0) {\n contour = qobject_cast<ModuleContourType*>(\n ModuleManager::instance().createAndAddModule(\n \"Contour\", activeDataSource, view));\n } else {\n contour = contours[0];\n }\n ActiveObjects::instance().setActiveModule(contour);\n }\n Q_ASSERT(contour);\n contour->setIsoValue(m_histogramColorOpacityEditor->GetContourValue());\n tomviz::convert<pqView*>(view)->render();\n}\n\nvoid HistogramWidget::onResetRangeClicked()\n{\n pqResetScalarRangeReaction::resetScalarRangeToData(nullptr);\n}\n\nvoid HistogramWidget::onCustomRangeClicked()\n{\n vtkVector2d range;\n vtkDiscretizableColorTransferFunction* discFunc =\n vtkDiscretizableColorTransferFunction::SafeDownCast(\n m_LUTProxy->GetClientSideObject());\n if (!discFunc) {\n return;\n }\n discFunc->GetRange(range.GetData());\n pqRescaleRange dialog(pqCoreUtilities::mainWidget());\n dialog.setRange(range[0], range[1]);\n if (dialog.exec() == QDialog::Accepted) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(\n m_LUTProxy, dialog.minimum(), dialog.maximum());\n }\n renderViews();\n emit colorMapUpdated();\n}\n\nvoid HistogramWidget::onInvertClicked()\n{\n vtkSMTransferFunctionProxy::InvertTransferFunction(m_LUTProxy);\n renderViews();\n emit colorMapUpdated();\n}\n\nvoid HistogramWidget::onPresetClicked()\n{\n pqPresetDialog dialog(pqCoreUtilities::mainWidget(),\n pqPresetDialog::SHOW_NON_INDEXED_COLORS_ONLY);\n dialog.setCustomizableLoadColors(true);\n dialog.setCustomizableLoadOpacities(true);\n dialog.setCustomizableUsePresetRange(true);\n dialog.setCustomizableLoadAnnotations(false);\n connect(&dialog,\n SIGNAL(applyPreset(const Json::Value&)),\n SLOT(applyCurrentPreset()));\n dialog.exec();\n}\n\nvoid HistogramWidget::applyCurrentPreset()\n{\n auto dialog = qobject_cast<pqPresetDialog*>(sender());\n Q_ASSERT(dialog);\n\n vtkSMProxy* lut = m_LUTProxy;\n if (!lut) {\n return;\n }\n\n if (dialog->loadColors() || dialog->loadOpacities()) {\n vtkSMProxy* sof =\n vtkSMPropertyHelper(lut, \"ScalarOpacityFunction\", true).GetAsProxy();\n if (dialog->loadColors()) {\n vtkSMTransferFunctionProxy::ApplyPreset(\n lut, dialog->currentPreset(), !dialog->usePresetRange());\n }\n if (dialog->loadOpacities()) {\n if (sof) {\n vtkSMTransferFunctionProxy::ApplyPreset(\n sof, dialog->currentPreset(), !dialog->usePresetRange());\n } else {\n qWarning(\"Cannot load opacities since 'ScalarOpacityFunction' is not \"\n \"present.\");\n }\n }\n\n \/\/ We need to take extra care to avoid the color and opacity function ranges\n \/\/ from straying away from each other. This can happen if only one of them\n \/\/ is getting a preset and we're using the preset range.\n if (dialog->usePresetRange() &&\n (dialog->loadColors() ^ dialog->loadOpacities()) && sof) {\n double range[2];\n if (dialog->loadColors() &&\n vtkSMTransferFunctionProxy::GetRange(lut, range)) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(sof, range);\n } else if (dialog->loadOpacities() &&\n vtkSMTransferFunctionProxy::GetRange(sof, range)) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(lut, range);\n }\n }\n renderViews();\n emit colorMapUpdated();\n }\n}\n\nvoid HistogramWidget::updateUI()\n{\n auto view = ActiveObjects::instance().activeView();\n\n \/\/ Update widget to reflect scalar bar visibility.\n if (m_LUTProxy) {\n auto sbProxy = getScalarBarRepresentation(view);\n if (view && sbProxy) {\n m_colorLegendToolButton->blockSignals(true);\n m_colorLegendToolButton->\n setChecked(vtkSMPropertyHelper(sbProxy, \"Visibility\").GetAsInt() == 1);\n m_colorLegendToolButton->blockSignals(false);\n }\n }\n}\n\nvoid HistogramWidget::renderViews()\n{\n pqView* view =\n tomviz::convert<pqView*>(ActiveObjects::instance().activeView());\n if (view) {\n view->render();\n }\n}\n\nvoid HistogramWidget::showEvent(QShowEvent* event)\n{\n QWidget::showEvent(event);\n this->renderViews();\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2012 Frederik Gladhorn <gladhorn@kde.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 as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), which shall\n act as a proxy defined in Section 6 of version 3 of the license.\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, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#define QT_GUI_LIB\n#include <qtest.h>\n\n#include <qpushbutton.h>\n#include <qdebug.h>\n\n#include \"accessible\/registry.h\"\n#include \"accessible\/accessibleobject.h\"\n\n#include \"atspi\/dbusconnection.h\"\n\nusing namespace KAccessibleClient;\n\nclass AccessibilityClientTest :public QObject\n{\n Q_OBJECT\n\nprivate Q_SLOTS:\n\/\/ void initTestCase();\n void tst_navigation();\n\nprivate:\n DBusConnection m_conn;\n};\n\nvoid AccessibilityClientTest::tst_navigation()\n{\n QPushButton button;\n button.setText(QLatin1String(\"Hello a11y\"));\n button.show();\n\n QTest::qWaitForWindowShown(&button);\n\n Registry r;\n\n QString appname = QLatin1String(\"Lib KAccessibleClient test\");\n qApp->setApplicationName(appname);\n AccessibleObject app = r.applications().last();\n QVERIFY(app.isValid());\n QCOMPARE(app.name(), appname);\n\n QCOMPARE(app.childCount(), 1);\n AccessibleObject child1 = app.child(0);\n QVERIFY(child1.isValid());\n QCOMPARE(child1.name(), button.text());\n AccessibleObject child2 = app.children().first();\n QCOMPARE(child1, child2);\n AccessibleObject parent = child1.parent();\n QCOMPARE(parent, app);\n\n AccessibleObject invalidChild = child1.child(0);\n QVERIFY(!invalidChild.isValid());\n QVERIFY(invalidChild.name().isEmpty());\n\n AccessibleObject invalidParent = app.parent();\n QVERIFY(!invalidParent.isValid());\n QVERIFY(invalidParent.name().isEmpty());\n}\n\nQTEST_MAIN(AccessibilityClientTest)\n\n#include \"tst_accessibilityclient.moc\"\n<commit_msg>Remove unused var.<commit_after>\/*\n Copyright 2012 Frederik Gladhorn <gladhorn@kde.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 as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), which shall\n act as a proxy defined in Section 6 of version 3 of the license.\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, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#define QT_GUI_LIB\n#include <qtest.h>\n\n#include <qpushbutton.h>\n#include <qdebug.h>\n\n#include \"accessible\/registry.h\"\n#include \"accessible\/accessibleobject.h\"\n\n#include \"atspi\/dbusconnection.h\"\n\nusing namespace KAccessibleClient;\n\nclass AccessibilityClientTest :public QObject\n{\n Q_OBJECT\n\nprivate Q_SLOTS:\n void tst_navigation();\n};\n\nvoid AccessibilityClientTest::tst_navigation()\n{\n QPushButton button;\n button.setText(QLatin1String(\"Hello a11y\"));\n button.show();\n\n QTest::qWaitForWindowShown(&button);\n\n Registry r;\n\n QString appname = QLatin1String(\"Lib KAccessibleClient test\");\n qApp->setApplicationName(appname);\n AccessibleObject app = r.applications().last();\n QVERIFY(app.isValid());\n QCOMPARE(app.name(), appname);\n\n QCOMPARE(app.childCount(), 1);\n AccessibleObject child1 = app.child(0);\n QVERIFY(child1.isValid());\n QCOMPARE(child1.name(), button.text());\n AccessibleObject child2 = app.children().first();\n QCOMPARE(child1, child2);\n AccessibleObject parent = child1.parent();\n QCOMPARE(parent, app);\n\n AccessibleObject invalidChild = child1.child(0);\n QVERIFY(!invalidChild.isValid());\n QVERIFY(invalidChild.name().isEmpty());\n\n AccessibleObject invalidParent = app.parent();\n QVERIFY(!invalidParent.isValid());\n QVERIFY(invalidParent.name().isEmpty());\n}\n\nQTEST_MAIN(AccessibilityClientTest)\n\n#include \"tst_accessibilityclient.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"bochs.h\"\n#include \"cpu\/cpu.h\"\n\n#if BX_DEBUGGER\n#if !((BX_HAVE_HASH_MAP || BX_HAVE_HASH_MAP_H) && (BX_HAVE_SET || BX_HAVE_SET_H))\n\nstatic char *BX_HAVE_HASH_MAP_ERR = \"context not implemented because BX_HAVE_HASH_MAP=0\\n\";\n\nchar* bx_dbg_symbolic_address(Bit32u context, Bit32u eip, Bit32u base)\n{\n static bx_bool first = true;\n if (first) {\n dbg_printf(BX_HAVE_HASH_MAP_ERR);\n first = false;\n }\n return \"unk. ctxt\";\n}\n\nchar* bx_dbg_symbolic_address_16bit(Bit32u eip, Bit32u cs)\n{\n \/\/ just prints an error anyway\n return bx_dbg_symbolic_address (0,0,0);\n}\n\nvoid bx_dbg_symbol_command(char* filename, bx_bool global, Bit32u offset)\n{\n dbg_printf(BX_HAVE_HASH_MAP_ERR);\n}\n\nvoid bx_dbg_info_symbols_command(char *Symbol)\n{\n dbg_printf(BX_HAVE_HASH_MAP_ERR);\n}\n\nint bx_dbg_lbreakpoint_symbol_command(char *Symbol)\n{\n dbg_printf(BX_HAVE_HASH_MAP_ERR);\n return -1;\n}\n\nBit32u bx_dbg_get_symbol_value(char *Symbol)\n{\n return 0;\n}\n\nchar* bx_dbg_disasm_symbolic_address(Bit32u eip, Bit32u base)\n{\n return 0;\n}\n\n#else \/* if BX_HAVE_HASH_MAP == 1 *\/\n\n\/* Haven't figured out how to port this code to OSF1 cxx compiler.\n Until a more portable solution is found, at least make it easy\n to disable the template code: just set BX_HAVE_HASH_MAP=0\n in config.h *\/\n#if BX_HAVE_HASH_MAP\n#include <hash_map>\n#elif BX_HAVE_HASH_MAP_H\n#include <hash_map.h>\n#endif\n\n#if BX_HAVE_SET\n#include <set>\n#elif BX_HAVE_SET_H\n#include <set.h>\n#endif\n\nusing namespace std;\n\nstruct symbol_entry_t\n{\n symbol_entry_t (Bit32u _start = 0, char* _name = 0)\n {\n start = _start;\n name = _name;\n }\n\n char* name;\n Bit32u start;\n};\n\nstruct lt_symbol_entry_t\n{\n bool operator()(const symbol_entry_t* s1, const symbol_entry_t* s2) const\n {\n return s1->start < s2->start;\n }\n};\n\nstruct lt_rsymbol_entry_t\n{\n bool operator()(const symbol_entry_t* s1, const symbol_entry_t* s2) const\n {\n return strcoll(s1->name, s2->name) < 0;\n }\n};\n\nstruct context_t\n{\n context_t (Bit32u);\n ~context_t();\n static context_t* get_context(Bit32u);\n symbol_entry_t* get_symbol_entry(Bit32u);\n symbol_entry_t* get_symbol_entry(const char *Symbol) const;\n void add_symbol(symbol_entry_t*);\n const set<symbol_entry_t*,lt_symbol_entry_t>* get_all_symbols() const {return syms;}\n const set<symbol_entry_t*,lt_rsymbol_entry_t>* get_all_rsymbols() const {return rsyms;}\nprivate:\n static hash_map<int,context_t*>* map;\n \/\/ Forvard references (find name by address)\n set<symbol_entry_t*,lt_symbol_entry_t>* syms;\n \/\/ Reverse references (find address by name)\n set<symbol_entry_t*,lt_rsymbol_entry_t>* rsyms;\n Bit32u id;\n};\n\nhash_map<int,context_t*>* context_t::map = new hash_map<int,context_t*>;\n\ncontext_t::context_t (Bit32u _id)\n{\n id = _id;\n syms = new set<symbol_entry_t*, lt_symbol_entry_t>;\n rsyms = new set<symbol_entry_t*, lt_rsymbol_entry_t>;\n (*map)[id] = this;\n}\n\ncontext_t::~context_t()\n{\n set<symbol_entry_t*>::iterator iter;\n if(syms) {\n for(iter=syms->begin();iter!=syms->end();++iter)\n if(*iter)\n delete *iter;\n }\n\n if(rsyms) {\n for(iter=rsyms->begin();iter!=rsyms->end();++iter)\n if(*iter)\n delete *iter;\n }\n}\n\ncontext_t* context_t::get_context(Bit32u i)\n{\n return (*map)[i];\n}\n\nsymbol_entry_t* context_t::get_symbol_entry(Bit32u ip)\n{\n symbol_entry_t probe;\n probe.start = ip;\n \/\/ find the first symbol whose address is greater than ip.\n if (syms->empty ()) return 0;\n set<symbol_entry_t*>::iterator iter = syms->upper_bound(&probe);\n\n if (iter == syms->end()) { \/\/ No symbol found\n return 0;\n }\n\n return *(--iter);\n}\n\nsymbol_entry_t* context_t::get_symbol_entry(const char *Symbol) const\n{\n symbol_entry_t probe;\n probe.name=(char *)Symbol;\n\n if (rsyms->empty ())\n return 0;\n\n set<symbol_entry_t*>::const_iterator iter;\n iter=rsyms->find(&probe);\n if(iter==rsyms->end()) \/\/ No symbol found\n return 0;\n return *iter;\n}\n\nvoid context_t::add_symbol(symbol_entry_t* sym)\n{\n syms->insert(sym);\n rsyms->insert(sym);\n}\n\nBit32u bx_dbg_get_symbol_value(char *Symbol)\n{\n context_t* cntx = context_t::get_context(0);\n if(!cntx) \/\/ Context not found\n return 0;\n\n if (Symbol[0]=='\\\"') Symbol++;\n int len = strlen(Symbol);\n if (Symbol[len - 1] == '\\\"') Symbol[len - 1] = '\\0';\n\n symbol_entry_t* sym=cntx->get_symbol_entry(Symbol);\n if(!sym) \/\/ Symbol not found\n return 0;\n\n return sym->start;\n}\n\nchar* bx_dbg_symbolic_address(Bit32u context, Bit32u eip, Bit32u base)\n{\n static char buf[80];\n#if 0\n \/\/ bbd: I don't see why we shouldn't allow symbol lookups on\n \/\/ segments with a nonzero base. I need to trace user\n \/\/ processes in Linux, which have a base of 0xc0000000.\n if (base != 0) {\n snprintf (buf, 80, \"non-zero base\");\n return buf;\n }\n#endif\n \/\/ Look up this context\n context_t* cntx = context_t::get_context(context);\n if (!cntx) {\n \/\/ Try global context\n cntx = context_t::get_context(0);\n if (!cntx) {\n snprintf (buf, 80, \"unk. ctxt\");\n return buf;\n }\n }\n \/\/ full linear address not only eip (for nonzero based segments)\n symbol_entry_t* entr = cntx->get_symbol_entry(base+eip);\n if (!entr) {\n snprintf (buf, 80, \"no symbol\");\n return buf;\n }\n snprintf (buf, 80, \"%s+%x\", entr->name, (base+eip) - entr->start);\n return buf;\n}\n\nchar* bx_dbg_disasm_symbolic_address(Bit32u eip, Bit32u base)\n{\n static char buf[80];\n\n \/\/ Try global context\n context_t* cntx = context_t::get_context(0);\n if (!cntx) {\n return 0;\n }\n\n \/\/ full linear address not only eip (for nonzero based segments)\n symbol_entry_t* entr = cntx->get_symbol_entry(base+eip);\n if (!entr) {\n return 0;\n }\n snprintf (buf, 80, \"%s+%x\", entr->name, (base+eip) - entr->start);\n return buf;\n}\n\nchar* bx_dbg_symbolic_address_16bit(Bit32u eip, Bit32u cs)\n{\n \/\/ in 16-bit code, the segment selector and offset are combined into a\n \/\/ 20-bit linear address = (segment selector<<4) + offset.\n eip &= 0xffff;\n cs &= 0xffff;\n return bx_dbg_symbolic_address (0, eip+(cs<<4), 0);\n}\n\nvoid bx_dbg_symbol_command(char* filename, bx_bool global, Bit32u offset)\n{\n if (filename[0] == '\"')\n filename++;\n int len = strlen(filename);\n if (filename[len - 1] == '\"')\n filename[len - 1] = '\\0';\n\n \/\/ Install symbols in correct context (page table)\n \/\/ The file format should be\n \/\/ address symbol (example '00002afe _StartLoseNT')\n\n context_t* cntx = (global) ? context_t::get_context(0)\n : context_t::get_context((BX_CPU(dbg_cpu)->cr3) >> 12);\n\n if (!cntx) {\n cntx = (global) ? new context_t(0)\n : new context_t((BX_CPU(dbg_cpu)->cr3) >> 12);\n }\n\n FILE* fp = fopen(filename, \"rt\"); \/\/ 't' is need for win32, unixes simply ignore it\n if (!fp) {\n dbg_printf (\"Could not open symbol file '%s'\\n\", filename);\n return;\n }\n char buf[200];\n while (fgets(buf, 200, fp)) {\n \/\/ Parse\n char* sym_name = buf;\n\n for (int i = 0; i < 200 && buf[i]; i++) {\n if (buf[i] == ' ') {\n buf[i] = '\\0';\n sym_name = buf + i + 1;\n break;\n }\n }\n if (sym_name == buf) {\n dbg_printf (\"Syntax error '%s'\\n\", buf);\n break;\n }\n Bit32u addr = strtoul(buf, 0, 16);\n if (sym_name[strlen(sym_name)-1] == '\\n')\n sym_name[strlen(sym_name)-1] = '\\0';\n symbol_entry_t* sym = new symbol_entry_t(addr + offset, strdup(sym_name));\n cntx->add_symbol(sym);\n }\n}\n\n\/\/ chack if s1 is prefix of s2\nstatic bool bx_dbg_strprefix(const char *s1, const char *s2)\n{\n if(!s1 || !s2)\n return false;\n\n size_t len=strlen(s1);\n\n if(len>strlen(s2))\n return false;\n return strncmp(s1, s2, len)==0;\n}\n\nvoid bx_dbg_info_symbols_command(char *Symbol)\n{\n context_t* cntx = context_t::get_context(0);\n\n if(!cntx) {\n dbg_printf (\"Global context not available\\n\");\n return;\n }\n\n if(Symbol) {\n const set<symbol_entry_t*,lt_rsymbol_entry_t>* rsyms;\n\n rsyms=cntx->get_all_rsymbols();\n if (rsyms->empty ()) {\n dbg_printf (\"Symbols not loaded\\n\");\n return;\n }\n \/\/ remove leading and trailing quotas\n if (Symbol[0]=='\\\"') Symbol++;\n int len = strlen(Symbol);\n if (Symbol[len - 1] == '\\\"') Symbol[len - 1] = '\\0';\n\n symbol_entry_t probe;\n probe.name=Symbol;\n set<symbol_entry_t*>::const_iterator iter;\n iter=rsyms->lower_bound(&probe);\n\n if(iter==rsyms->end() || !bx_dbg_strprefix(Symbol, (*iter)->name))\n dbg_printf (\"No symbols found\\n\");\n else\n for(;iter!=rsyms->end() && bx_dbg_strprefix(Symbol, (*iter)->name);++iter) {\n dbg_printf (\"%08x: %s\\n\", (*iter)->start, (*iter)->name);\n }\n }\n else {\n const set<symbol_entry_t*,lt_symbol_entry_t>* syms;\n\n syms=cntx->get_all_symbols();\n if (syms->empty ()) {\n dbg_printf (\"Symbols not loaded\\n\");\n return;\n }\n\n set<symbol_entry_t*>::const_iterator iter;\n for(iter = syms->begin();iter!=syms->end();++iter) {\n dbg_printf (\"%08x: %s\\n\", (*iter)->start, (*iter)->name);\n }\n }\n}\n\nint bx_dbg_lbreakpoint_symbol_command(char *Symbol)\n{\n context_t* cntx = context_t::get_context(0);\n if(!cntx) {\n dbg_printf (\"Global context not available\\n\");\n return -1;\n }\n if (Symbol[0]=='\\\"') Symbol++;\n int len = strlen(Symbol);\n if (Symbol[len - 1] == '\\\"') Symbol[len - 1] = '\\0';\n\n const symbol_entry_t* sym=cntx->get_symbol_entry(Symbol);\n if(sym)\n return bx_dbg_lbreakpoint_command(bkRegular, sym->start);\n dbg_printf (\"Symbol not found\\n\");\n return -1;\n}\n#endif\n#endif\n<commit_msg>Another #SF patch merge another patch to fix compilation with vc8 (or, more precisely with Dimkunware STL). It corrects the usage of std::set iterators.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"bochs.h\"\n#include \"cpu\/cpu.h\"\n\n#if BX_DEBUGGER\n#if !((BX_HAVE_HASH_MAP || BX_HAVE_HASH_MAP_H) && (BX_HAVE_SET || BX_HAVE_SET_H))\n\nstatic char *BX_HAVE_HASH_MAP_ERR = \"context not implemented because BX_HAVE_HASH_MAP=0\\n\";\n\nchar* bx_dbg_symbolic_address(Bit32u context, Bit32u eip, Bit32u base)\n{\n static bx_bool first = true;\n if (first) {\n dbg_printf(BX_HAVE_HASH_MAP_ERR);\n first = false;\n }\n return \"unk. ctxt\";\n}\n\nchar* bx_dbg_symbolic_address_16bit(Bit32u eip, Bit32u cs)\n{\n \/\/ just prints an error anyway\n return bx_dbg_symbolic_address (0,0,0);\n}\n\nvoid bx_dbg_symbol_command(char* filename, bx_bool global, Bit32u offset)\n{\n dbg_printf(BX_HAVE_HASH_MAP_ERR);\n}\n\nvoid bx_dbg_info_symbols_command(char *Symbol)\n{\n dbg_printf(BX_HAVE_HASH_MAP_ERR);\n}\n\nint bx_dbg_lbreakpoint_symbol_command(char *Symbol)\n{\n dbg_printf(BX_HAVE_HASH_MAP_ERR);\n return -1;\n}\n\nBit32u bx_dbg_get_symbol_value(char *Symbol)\n{\n return 0;\n}\n\nchar* bx_dbg_disasm_symbolic_address(Bit32u eip, Bit32u base)\n{\n return 0;\n}\n\n#else \/* if BX_HAVE_HASH_MAP == 1 *\/\n\n\/* Haven't figured out how to port this code to OSF1 cxx compiler.\n Until a more portable solution is found, at least make it easy\n to disable the template code: just set BX_HAVE_HASH_MAP=0\n in config.h *\/\n#if BX_HAVE_HASH_MAP\n#include <hash_map>\n#elif BX_HAVE_HASH_MAP_H\n#include <hash_map.h>\n#endif\n\n#if BX_HAVE_SET\n#include <set>\n#elif BX_HAVE_SET_H\n#include <set.h>\n#endif\n\nusing namespace std;\n\nstruct symbol_entry_t\n{\n symbol_entry_t (Bit32u _start = 0, char* _name = 0)\n {\n start = _start;\n name = _name;\n }\n\n char* name;\n Bit32u start;\n};\n\nstruct lt_symbol_entry_t\n{\n bool operator()(const symbol_entry_t* s1, const symbol_entry_t* s2) const\n {\n return s1->start < s2->start;\n }\n};\n\nstruct lt_rsymbol_entry_t\n{\n bool operator()(const symbol_entry_t* s1, const symbol_entry_t* s2) const\n {\n return strcoll(s1->name, s2->name) < 0;\n }\n};\n\nstruct context_t\n{\n typedef set<symbol_entry_t*,lt_symbol_entry_t> sym_set_t;\n typedef set<symbol_entry_t*,lt_rsymbol_entry_t> rsym_set_t;\n\n context_t (Bit32u);\n ~context_t();\n\n static context_t* get_context(Bit32u);\n symbol_entry_t* get_symbol_entry(Bit32u);\n symbol_entry_t* get_symbol_entry(const char *Symbol) const;\n void add_symbol(symbol_entry_t*);\n const sym_set_t* get_all_symbols() const {return syms;}\n const rsym_set_t* get_all_rsymbols() const {return rsyms;}\n\nprivate:\n static hash_map<int,context_t*>* map;\n \/\/ Forvard references (find name by address)\n sym_set_t* syms;\n \/\/ Reverse references (find address by name)\n rsym_set_t* rsyms;\n Bit32u id;\n};\n\nhash_map<int,context_t*>* context_t::map = new hash_map<int,context_t*>;\n\ncontext_t::context_t (Bit32u _id)\n{\n id = _id;\n syms = new sym_set_t;\n rsyms = new rsym_set_t;\n (*map)[id] = this;\n}\n\ncontext_t::~context_t()\n{\n if(syms) {\n sym_set_t::iterator iter;\n for(iter=syms->begin();iter!=syms->end();++iter)\n if(*iter)\n delete *iter;\n }\n\n if(rsyms) {\n rsym_set_t::iterator iter;\n for(iter=rsyms->begin();iter!=rsyms->end();++iter)\n if(*iter)\n delete *iter;\n }\n}\n\ncontext_t* context_t::get_context(Bit32u i)\n{\n return (*map)[i];\n}\n\nsymbol_entry_t* context_t::get_symbol_entry(Bit32u ip)\n{\n symbol_entry_t probe;\n probe.start = ip;\n \/\/ find the first symbol whose address is greater than ip.\n if (syms->empty ()) return 0;\n sym_set_t::iterator iter = syms->upper_bound(&probe);\n\n if (iter == syms->end()) { \/\/ No symbol found\n return 0;\n }\n\n return *(--iter);\n}\n\nsymbol_entry_t* context_t::get_symbol_entry(const char *Symbol) const\n{\n symbol_entry_t probe;\n probe.name=(char *)Symbol;\n\n if (rsyms->empty())\n return 0;\n\n rsym_set_t::const_iterator iter;\n iter=rsyms->find(&probe);\n if(iter==rsyms->end()) \/\/ No symbol found\n return 0;\n return *iter;\n}\n\nvoid context_t::add_symbol(symbol_entry_t* sym)\n{\n syms->insert(sym);\n rsyms->insert(sym);\n}\n\nBit32u bx_dbg_get_symbol_value(char *Symbol)\n{\n context_t* cntx = context_t::get_context(0);\n if(!cntx) \/\/ Context not found\n return 0;\n\n if (Symbol[0]=='\\\"') Symbol++;\n int len = strlen(Symbol);\n if (Symbol[len - 1] == '\\\"') Symbol[len - 1] = '\\0';\n\n symbol_entry_t* sym=cntx->get_symbol_entry(Symbol);\n if(!sym) \/\/ Symbol not found\n return 0;\n\n return sym->start;\n}\n\nchar* bx_dbg_symbolic_address(Bit32u context, Bit32u eip, Bit32u base)\n{\n static char buf[80];\n#if 0\n \/\/ bbd: I don't see why we shouldn't allow symbol lookups on\n \/\/ segments with a nonzero base. I need to trace user\n \/\/ processes in Linux, which have a base of 0xc0000000.\n if (base != 0) {\n snprintf (buf, 80, \"non-zero base\");\n return buf;\n }\n#endif\n \/\/ Look up this context\n context_t* cntx = context_t::get_context(context);\n if (!cntx) {\n \/\/ Try global context\n cntx = context_t::get_context(0);\n if (!cntx) {\n snprintf (buf, 80, \"unk. ctxt\");\n return buf;\n }\n }\n \/\/ full linear address not only eip (for nonzero based segments)\n symbol_entry_t* entr = cntx->get_symbol_entry(base+eip);\n if (!entr) {\n snprintf (buf, 80, \"no symbol\");\n return buf;\n }\n snprintf (buf, 80, \"%s+%x\", entr->name, (base+eip) - entr->start);\n return buf;\n}\n\nchar* bx_dbg_disasm_symbolic_address(Bit32u eip, Bit32u base)\n{\n static char buf[80];\n\n \/\/ Try global context\n context_t* cntx = context_t::get_context(0);\n if (!cntx) {\n return 0;\n }\n\n \/\/ full linear address not only eip (for nonzero based segments)\n symbol_entry_t* entr = cntx->get_symbol_entry(base+eip);\n if (!entr) {\n return 0;\n }\n snprintf (buf, 80, \"%s+%x\", entr->name, (base+eip) - entr->start);\n return buf;\n}\n\nchar* bx_dbg_symbolic_address_16bit(Bit32u eip, Bit32u cs)\n{\n \/\/ in 16-bit code, the segment selector and offset are combined into a\n \/\/ 20-bit linear address = (segment selector<<4) + offset.\n eip &= 0xffff;\n cs &= 0xffff;\n return bx_dbg_symbolic_address (0, eip+(cs<<4), 0);\n}\n\nvoid bx_dbg_symbol_command(char* filename, bx_bool global, Bit32u offset)\n{\n if (filename[0] == '\"')\n filename++;\n int len = strlen(filename);\n if (filename[len - 1] == '\"')\n filename[len - 1] = '\\0';\n\n \/\/ Install symbols in correct context (page table)\n \/\/ The file format should be\n \/\/ address symbol (example '00002afe _StartLoseNT')\n\n context_t* cntx = (global) ? context_t::get_context(0)\n : context_t::get_context((BX_CPU(dbg_cpu)->cr3) >> 12);\n\n if (!cntx) {\n cntx = (global) ? new context_t(0)\n : new context_t((BX_CPU(dbg_cpu)->cr3) >> 12);\n }\n\n FILE* fp = fopen(filename, \"rt\"); \/\/ 't' is need for win32, unixes simply ignore it\n if (!fp) {\n dbg_printf (\"Could not open symbol file '%s'\\n\", filename);\n return;\n }\n char buf[200];\n while (fgets(buf, 200, fp)) {\n \/\/ Parse\n char* sym_name = buf;\n\n for (int i = 0; i < 200 && buf[i]; i++) {\n if (buf[i] == ' ') {\n buf[i] = '\\0';\n sym_name = buf + i + 1;\n break;\n }\n }\n if (sym_name == buf) {\n dbg_printf (\"Syntax error '%s'\\n\", buf);\n break;\n }\n Bit32u addr = strtoul(buf, 0, 16);\n if (sym_name[strlen(sym_name)-1] == '\\n')\n sym_name[strlen(sym_name)-1] = '\\0';\n symbol_entry_t* sym = new symbol_entry_t(addr + offset, strdup(sym_name));\n cntx->add_symbol(sym);\n }\n}\n\n\/\/ chack if s1 is prefix of s2\nstatic bool bx_dbg_strprefix(const char *s1, const char *s2)\n{\n if(!s1 || !s2)\n return false;\n\n size_t len=strlen(s1);\n\n if(len>strlen(s2))\n return false;\n return strncmp(s1, s2, len)==0;\n}\n\nvoid bx_dbg_info_symbols_command(char *Symbol)\n{\n context_t* cntx = context_t::get_context(0);\n\n if(!cntx) {\n dbg_printf (\"Global context not available\\n\");\n return;\n }\n\n if(Symbol) {\n const context_t::rsym_set_t* rsyms;\n\n rsyms=cntx->get_all_rsymbols();\n if (rsyms->empty ()) {\n dbg_printf (\"Symbols not loaded\\n\");\n return;\n }\n \/\/ remove leading and trailing quotas\n if (Symbol[0]=='\\\"') Symbol++;\n int len = strlen(Symbol);\n if (Symbol[len - 1] == '\\\"') Symbol[len - 1] = '\\0';\n\n symbol_entry_t probe;\n probe.name=Symbol;\n context_t::rsym_set_t::const_iterator iter;\n iter=rsyms->lower_bound(&probe);\n\n if(iter==rsyms->end() || !bx_dbg_strprefix(Symbol, (*iter)->name))\n dbg_printf (\"No symbols found\\n\");\n else {\n for(;iter!=rsyms->end() && bx_dbg_strprefix(Symbol, (*iter)->name);++iter) {\n dbg_printf (\"%08x: %s\\n\", (*iter)->start, (*iter)->name);\n }\n }\n }\n else {\n const context_t::sym_set_t* syms;\n\n syms=cntx->get_all_symbols();\n if (syms->empty ()) {\n dbg_printf (\"Symbols not loaded\\n\");\n return;\n }\n\n context_t::sym_set_t::const_iterator iter;\n for(iter = syms->begin();iter!=syms->end();++iter) {\n dbg_printf (\"%08x: %s\\n\", (*iter)->start, (*iter)->name);\n }\n }\n}\n\nint bx_dbg_lbreakpoint_symbol_command(char *Symbol)\n{\n context_t* cntx = context_t::get_context(0);\n if(!cntx) {\n dbg_printf (\"Global context not available\\n\");\n return -1;\n }\n if (Symbol[0]=='\\\"') Symbol++;\n int len = strlen(Symbol);\n if (Symbol[len - 1] == '\\\"') Symbol[len - 1] = '\\0';\n\n const symbol_entry_t* sym=cntx->get_symbol_entry(Symbol);\n if(sym)\n return bx_dbg_lbreakpoint_command(bkRegular, sym->start);\n dbg_printf (\"Symbol not found\\n\");\n return -1;\n}\n\n#endif\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"Doing.h\"\n#include <Windows.h>\n#include <string>\n#include \"Win32Util.h\"\n#include <oleacc.h>\n#include <iostream>\n#include <atlbase.h>\n#include <UIAutomationClient.h>\n#include \"StringUtil.h\"\n#include \"Activity.h\"\n#include <ctime>\n#include <thread>\n#include <chrono>\n#include \"ActivityKey.h\"\n#include \"SimpleLogger.h\"\nDoing::Doing(ConcurrentQueue<Activity>& ptr_map) : _job_queue(ptr_map)\n{\n ::CoInitialize(NULL);\n _machine_name = Win32Util<std::wstring>::GetMachineName();\n\n}\nvoid Doing::StartReportActivities() const\n{\n}\nvoid Doing::Sample()\n{\n ::CoInitialize(NULL);\n ActivityKey cur_activity_key;\n bool prev_is_active = true;\n while (true)\n {\n ActivityKey next_activity_key;\n std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n if (_last_time != 0)\n {\n HWND hwnd = GetForegroundWindow();\n DWORD pid = 0;\n if (hwnd)\n {\n if (GetWindowThreadProcessId(hwnd, &pid))\n {\n if (!(pid == GetCurrentProcessId()))\n {\n next_activity_key.proc_name = Win32Util<std::wstring>::GetProcName(pid);;\n \/\/1. get key of the activity\n std::wstring url;\n next_activity_key.window_text = Win32Util<std::wstring>::GetWindowTitleByHandle(hwnd);\n if (next_activity_key.proc_name.compare(L\"chrome.exe\") == 0)\n {\n next_activity_key.url = ReportUrlByHandle(hwnd);\n }\n\n \/\/creates key internally\n \/\/as of this step, the internal data members should all be set\n next_activity_key.GenerateKey();\n\n if (cur_activity_key.IsEmpty()) \/\/ first time\n {\n cur_activity_key = next_activity_key; \/\/copy constructor\n }\n else\n {\n _acitive_duration += ms.count() - _last_time;\/\/if this is still the same activity, increase the duration\n bool cur_is_active = prev_is_active; \n try\n {\n cur_is_active = (GetTickCount() - GetLastInputTime()) < 120000;\n \/\/debug purpose\n if (cur_is_active != prev_is_active)\n {\n wprintf(L\"activity %s activeness changed from %d to %d\\n\",next_activity_key.GetKey().c_str(), prev_is_active,cur_is_active);\n \/\/SimpleLogger::GetInstance().WriteLogMessage(LOGGER_LEVEL::INFO_LVL,);\n }\n }\n catch (const std::exception& e)\n {\n std::string s = e.what();\n \/\/ya lazy ass. handle i18n multibyte to wide char when it breaks :P\n SimpleLogger::GetInstance().WriteLogMessage(LOGGER_LEVEL::ERROR_LVL, std::wstring(s.begin(), s.end()));\n }\n\n \/\/When Activity itself has changed\n if (next_activity_key != cur_activity_key) \n {\n Activity activity(_acitive_duration,\n ms.count(),\n _machine_name,\n cur_activity_key,\n cur_is_active);\n _job_queue.Push(activity); \n cur_activity_key = next_activity_key;\n\n \/\/previous recording of this activity is done\n \/\/now reset all bookkeeping local variables\n _acitive_duration = 0;\n prev_is_active = true;\n }\n else if (cur_is_active != prev_is_active)\n {\n Activity activity(_acitive_duration,\n ms.count(),\n _machine_name,\n cur_activity_key,\n \/\/cur_is_active actually describes current activity's activeness\n \/\/prev_is_active describes the *already queued*, last acitivity\n cur_is_active);\n _job_queue.Push(activity);\n prev_is_active = cur_is_active;\n cur_activity_key = next_activity_key;\n \/\/previous recording of this activity is done\n \/\/now reset all bookkeeping local variables\n _acitive_duration = 0;\n }\n \n }\n }\n }\n else\n {\n wprintf(L\"GetWindowThreadProcessId failed errcode = %d\", GetLastError());\n }\n }\n }\n\n\n \/\/always bumps this, we are increasing this in a 500 ms \n {\n _last_time = ms.count();\n }\n \n Sleep(500);\n }\n}\nvoid Doing::Monitor()\n{\n std::thread t_sampling(&Doing::Sample,this);\n t_sampling.detach();\n}\nDoing::~Doing()\n{\n ::CoUninitialize();\n}\nstd::wstring Doing::ReportUrlByHandle(const HWND hwnd)\n{\n CComPtr<IUIAutomation> pAutomation = NULL;\n HRESULT hr = pAutomation.CoCreateInstance(CLSID_CUIAutomation, NULL, CLSCTX_INPROC_SERVER);\n CComPtr<IUIAutomationElement> pElement = NULL;\n std::wstring val_std_str;\n if (SUCCEEDED(hr))\n {\n hr = pAutomation->ElementFromHandle(hwnd, &pElement);\n if (pElement)\n {\n CComPtr<IUIAutomationCondition> pCondition = NULL;\n IUIAutomationElement* pFound = NULL; \/\/ don't use smart pointer because we want non RAII control over this pointer\n BSTR urlControlName = SysAllocString(L\"Address and search bar\");\n if (urlControlName)\n {\n VARIANT varProp;\n varProp.vt = VT_BSTR;\n varProp.bstrVal = urlControlName;\n pAutomation->CreatePropertyCondition(UIA_NamePropertyId, varProp, &pCondition);\n if (pCondition)\n {\n pElement->FindFirst(TreeScope_Descendants, pCondition, &pFound);\n if (pFound)\n {\n BSTR val = NULL;\n BSTR name = NULL;\n CComPtr<IUIAutomationValuePattern> ptr_val_pattern = NULL;\n pFound->get_CurrentName(&name);\n pFound->GetCurrentPatternAs(UIA_ValuePatternId, __uuidof(IUIAutomationValuePattern), (void**)&ptr_val_pattern);\n ptr_val_pattern->get_CurrentValue(&val);\n val_std_str = StringUtilBase::BSTR2StdString(val);\n \/\/std::wstring name_std_str = StringUtilBase<std::wstring>::BSTR2StdString(name);\n pFound->Release();\n }\n }\n\n SysFreeString(urlControlName);\n }\n }\n }\n return val_std_str;\n}\n\/*\ndesc:\n Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 day\n since last user input\n\nret:\n last user input time in milis\n\nexception:\n throw std::exception when GetLastInputInfo fails. \n MSDN does not mention what ERROR CODE to expect when failing though.\n \n*\/\nunsigned long long Doing::GetLastInputTime()\n{\n#ifdef _WIN32\n LASTINPUTINFO lii;\n \/\/The size of the structure, in bytes. This member must be set to sizeof(LASTINPUTINFO).\n \/\/It's a common way for versioning in Windows API.\n lii.cbSize = sizeof(LASTINPUTINFO);\n if (!GetLastInputInfo(&lii))\n {\n throw std::exception(\"GetLastInputInfo failed!\");\n }\n return lii.dwTime;\n#else \n return 0;\n#endif\n}\n\/\/end of the file<commit_msg>time_stamp now is the start time instead of the endtime<commit_after>#include \"Doing.h\"\n#include <Windows.h>\n#include <string>\n#include \"Win32Util.h\"\n#include <oleacc.h>\n#include <iostream>\n#include <atlbase.h>\n#include <UIAutomationClient.h>\n#include \"StringUtil.h\"\n#include \"Activity.h\"\n#include <ctime>\n#include <thread>\n#include <chrono>\n#include \"ActivityKey.h\"\n#include \"SimpleLogger.h\"\nDoing::Doing(ConcurrentQueue<Activity>& ptr_map) : _job_queue(ptr_map)\n{\n ::CoInitialize(NULL);\n _machine_name = Win32Util<std::wstring>::GetMachineName();\n\n}\nvoid Doing::StartReportActivities() const\n{\n}\nvoid Doing::Sample()\n{\n ::CoInitialize(NULL);\n ActivityKey cur_activity_key;\n bool prev_is_active = true;\n while (true)\n {\n ActivityKey next_activity_key;\n std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n unsigned long long start_time = 0; \/\/ 0 can be used to verify if start_time has been inited or not\n if (_last_time != 0)\n {\n HWND hwnd = GetForegroundWindow();\n DWORD pid = 0;\n if (hwnd)\n {\n if (GetWindowThreadProcessId(hwnd, &pid))\n {\n if (!(pid == GetCurrentProcessId()))\n {\n next_activity_key.proc_name = Win32Util<std::wstring>::GetProcName(pid);;\n \/\/1. get key of the activity\n std::wstring url;\n next_activity_key.window_text = Win32Util<std::wstring>::GetWindowTitleByHandle(hwnd);\n if (next_activity_key.proc_name.compare(L\"chrome.exe\") == 0)\n {\n next_activity_key.url = ReportUrlByHandle(hwnd);\n }\n\n \/\/creates key internally\n \/\/as of this step, the internal data members should all be set\n next_activity_key.GenerateKey();\n\n if (cur_activity_key.IsEmpty()) \/\/ first time\n {\n cur_activity_key = next_activity_key; \/\/copy constructor\n start_time = ms.count();\/\/init start time\n }\n else\n {\n _acitive_duration += ms.count() - _last_time;\/\/if this is still the same activity, increase the duration\n bool cur_is_active = prev_is_active; \n try\n {\n cur_is_active = (GetTickCount() - GetLastInputTime()) < 120000;\n \/\/debug purpose\n if (cur_is_active != prev_is_active)\n {\n wprintf(L\"activity %s activeness changed from %d to %d\\n\",next_activity_key.GetKey().c_str(), prev_is_active,cur_is_active);\n \/\/SimpleLogger::GetInstance().WriteLogMessage(LOGGER_LEVEL::INFO_LVL,);\n }\n }\n catch (const std::exception& e)\n {\n std::string s = e.what();\n \/\/ya lazy ass. handle i18n multibyte to wide char when it breaks :P\n SimpleLogger::GetInstance().WriteLogMessage(LOGGER_LEVEL::ERROR_LVL, std::wstring(s.begin(), s.end()));\n }\n\n \/\/When Activity itself has changed\n if (next_activity_key != cur_activity_key) \n {\n Activity activity(_acitive_duration,\n start_time,\n _machine_name,\n cur_activity_key,\n cur_is_active);\n _job_queue.Push(activity); \n cur_activity_key = next_activity_key;\n\n \/\/previous recording of this activity is done\n \/\/now reset all bookkeeping local variables\n _acitive_duration = 0;\n prev_is_active = true;\n start_time = ms.count(); \/\/reset start time\n }\n else if (cur_is_active != prev_is_active)\n {\n Activity activity(_acitive_duration,\n start_time,\n _machine_name,\n cur_activity_key,\n \/\/cur_is_active actually describes current activity's activeness\n \/\/prev_is_active describes the *already queued*, last acitivity\n cur_is_active);\n _job_queue.Push(activity);\n prev_is_active = cur_is_active;\n cur_activity_key = next_activity_key;\n \/\/previous recording of this activity is done\n \/\/now reset all bookkeeping local variables\n _acitive_duration = 0;\n start_time = ms.count(); \/\/reset start time\n }\n \n }\n }\n }\n else\n {\n wprintf(L\"GetWindowThreadProcessId failed errcode = %d\", GetLastError());\n }\n }\n }\n\n\n \/\/always bumps this, we are increasing this in a 500 ms \n {\n _last_time = ms.count();\n }\n \n Sleep(500);\n }\n}\nvoid Doing::Monitor()\n{\n std::thread t_sampling(&Doing::Sample,this);\n t_sampling.detach();\n}\nDoing::~Doing()\n{\n ::CoUninitialize();\n}\nstd::wstring Doing::ReportUrlByHandle(const HWND hwnd)\n{\n CComPtr<IUIAutomation> pAutomation = NULL;\n HRESULT hr = pAutomation.CoCreateInstance(CLSID_CUIAutomation, NULL, CLSCTX_INPROC_SERVER);\n CComPtr<IUIAutomationElement> pElement = NULL;\n std::wstring val_std_str;\n if (SUCCEEDED(hr))\n {\n hr = pAutomation->ElementFromHandle(hwnd, &pElement);\n if (pElement)\n {\n CComPtr<IUIAutomationCondition> pCondition = NULL;\n IUIAutomationElement* pFound = NULL; \/\/ don't use smart pointer because we want non RAII control over this pointer\n BSTR urlControlName = SysAllocString(L\"Address and search bar\");\n if (urlControlName)\n {\n VARIANT varProp;\n varProp.vt = VT_BSTR;\n varProp.bstrVal = urlControlName;\n pAutomation->CreatePropertyCondition(UIA_NamePropertyId, varProp, &pCondition);\n if (pCondition)\n {\n pElement->FindFirst(TreeScope_Descendants, pCondition, &pFound);\n if (pFound)\n {\n BSTR val = NULL;\n BSTR name = NULL;\n CComPtr<IUIAutomationValuePattern> ptr_val_pattern = NULL;\n pFound->get_CurrentName(&name);\n pFound->GetCurrentPatternAs(UIA_ValuePatternId, __uuidof(IUIAutomationValuePattern), (void**)&ptr_val_pattern);\n ptr_val_pattern->get_CurrentValue(&val);\n val_std_str = StringUtilBase::BSTR2StdString(val);\n \/\/std::wstring name_std_str = StringUtilBase<std::wstring>::BSTR2StdString(name);\n pFound->Release();\n }\n }\n\n SysFreeString(urlControlName);\n }\n }\n }\n return val_std_str;\n}\n\/*\ndesc:\n Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 day\n since last user input\n\nret:\n last user input time in milis\n\nexception:\n throw std::exception when GetLastInputInfo fails. \n MSDN does not mention what ERROR CODE to expect when failing though.\n \n*\/\nunsigned long long Doing::GetLastInputTime()\n{\n#ifdef _WIN32\n LASTINPUTINFO lii;\n \/\/The size of the structure, in bytes. This member must be set to sizeof(LASTINPUTINFO).\n \/\/It's a common way for versioning in Windows API.\n lii.cbSize = sizeof(LASTINPUTINFO);\n if (!GetLastInputInfo(&lii))\n {\n throw std::exception(\"GetLastInputInfo failed!\");\n }\n return lii.dwTime;\n#else \n return 0;\n#endif\n}\n\/\/end of the file<|endoftext|>"} {"text":"<commit_before>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Contributions: Jon Trulson <jtrulson@ics.com>\n * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>\n * Copyright (c) 2014 - 2015 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"uart.h\"\n#include \"types.hpp\"\n#include <stdexcept>\n#include <cstring>\n\nnamespace mraa\n{\n\n\/**\n * @brief API to UART (enabling only)\n *\n * This file defines the UART interface for libmraa\n *\n * @snippet Uart-example.cpp Interesting\n *\/\nclass Uart\n{\n public:\n \/**\n * Uart Constructor, takes a pin number which will map directly to the\n * linux uart number, this 'enables' the uart, nothing more\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(int uart)\n {\n m_uart = mraa_uart_init(uart);\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart Constructor, takes a string to the path of the serial\n * interface that is needed.\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(std::string path)\n {\n m_uart = mraa_uart_init_raw(path.c_str());\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart destructor\n *\/\n ~Uart()\n {\n mraa_uart_stop(m_uart);\n }\n\n \/**\n * Get string with tty device path within Linux\n * For example. Could point to \"\/dev\/ttyS0\"\n *\n * @return char pointer of device path\n *\/\n std::string\n getDevicePath()\n {\n std::string ret_val(mraa_uart_get_dev_path(m_uart));\n return ret_val;\n }\n\n \/**\n * Read bytes from the device into char* buffer\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return numbers of bytes read\n *\/\n int\n read(char* data, int length)\n {\n return mraa_uart_read(m_uart, data, (size_t) length);\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n write(const char* data, int length)\n {\n return mraa_uart_write(m_uart, data, (size_t) length);\n }\n\n \/**\n * Read bytes from the device into a String object\n *\n * @param length to read\n * @return string of data\n *\/\n std::string\n readStr(int length)\n {\n char* data = (char*) malloc(sizeof(char) * length);\n int v = mraa_uart_read(m_uart, data, (size_t) length);\n std::string ret(data, v);\n free(data);\n return ret;\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param string to write\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n writeStr(std::string data)\n {\n \/\/ this is data.length() not +1 because we want to avoid the '\\0' char\n return mraa_uart_write(m_uart, data.c_str(), (data.length()));\n }\n\n \/**\n * Check to see if data is available on the device for reading\n *\n * @param millis number of milliseconds to wait, or 0 to return immediately\n * @return true if there is data available to read, false otherwise\n *\/\n bool\n dataAvailable(unsigned int millis = 0)\n {\n if (mraa_uart_data_available(m_uart, millis))\n return true;\n else\n return false;\n }\n\n \/**\n * Flush the outbound data.\n * Blocks until complete.\n *\n * @return Result of operation\n *\/\n Result\n flush()\n {\n return (Result) mraa_uart_flush(m_uart);\n }\n\n \/**\n * Set the baudrate.\n * Takes an int and will attempt to decide what baudrate is\n * to be used on the UART hardware.\n *\n * @param baud unsigned int of baudrate i.e. 9600\n * @return Result of operation\n *\/\n Result\n setBaudRate(unsigned int baud)\n {\n return (Result) mraa_uart_set_baudrate(m_uart, baud);\n }\n\n \/**\n * Set the transfer mode\n * For example setting the mode to 8N1 would be\n * \"dev.setMode(8,UART_PARITY_NONE , 1)\"\n *\n * @param bytesize data bits\n * @param parity Parity bit setting\n * @param stopbits stop bits\n * @return Result of operation\n *\/\n Result\n setMode(int bytesize, UartParity parity, int stopbits)\n {\n return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);\n }\n\n \/**\n * Set the flowcontrol\n *\n * @param xonxoff XON\/XOFF Software flow control.\n * @param rtscts RTS\/CTS out of band hardware flow control\n * @return Result of operation\n *\/\n Result\n setFlowcontrol(bool xonxoff, bool rtscts)\n {\n return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);\n }\n\n \/**\n * Set the timeout for read and write operations\n * <= 0 will disable that timeout\n *\n * @param read read timeout\n * @param write write timeout\n * @param interchar inbetween char timeout\n * @return Result of operation\n *\/\n Result\n setTimeout(int read, int write, int interchar)\n {\n return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);\n }\n\n private:\n mraa_uart_context m_uart;\n};\n}\n<commit_msg>uart: Added stdlib.h to uart.hpp so malloc() and free() are declared<commit_after>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Contributions: Jon Trulson <jtrulson@ics.com>\n * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>\n * Copyright (c) 2014 - 2015 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"uart.h\"\n#include \"types.hpp\"\n#include <stdlib.h>\n#include <stdexcept>\n#include <cstring>\n\nnamespace mraa\n{\n\n\/**\n * @brief API to UART (enabling only)\n *\n * This file defines the UART interface for libmraa\n *\n * @snippet Uart-example.cpp Interesting\n *\/\nclass Uart\n{\n public:\n \/**\n * Uart Constructor, takes a pin number which will map directly to the\n * linux uart number, this 'enables' the uart, nothing more\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(int uart)\n {\n m_uart = mraa_uart_init(uart);\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart Constructor, takes a string to the path of the serial\n * interface that is needed.\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(std::string path)\n {\n m_uart = mraa_uart_init_raw(path.c_str());\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart destructor\n *\/\n ~Uart()\n {\n mraa_uart_stop(m_uart);\n }\n\n \/**\n * Get string with tty device path within Linux\n * For example. Could point to \"\/dev\/ttyS0\"\n *\n * @return char pointer of device path\n *\/\n std::string\n getDevicePath()\n {\n std::string ret_val(mraa_uart_get_dev_path(m_uart));\n return ret_val;\n }\n\n \/**\n * Read bytes from the device into char* buffer\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return numbers of bytes read\n *\/\n int\n read(char* data, int length)\n {\n return mraa_uart_read(m_uart, data, (size_t) length);\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n write(const char* data, int length)\n {\n return mraa_uart_write(m_uart, data, (size_t) length);\n }\n\n \/**\n * Read bytes from the device into a String object\n *\n * @param length to read\n * @return string of data\n *\/\n std::string\n readStr(int length)\n {\n char* data = (char*) malloc(sizeof(char) * length);\n int v = mraa_uart_read(m_uart, data, (size_t) length);\n std::string ret(data, v);\n free(data);\n return ret;\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param string to write\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n writeStr(std::string data)\n {\n \/\/ this is data.length() not +1 because we want to avoid the '\\0' char\n return mraa_uart_write(m_uart, data.c_str(), (data.length()));\n }\n\n \/**\n * Check to see if data is available on the device for reading\n *\n * @param millis number of milliseconds to wait, or 0 to return immediately\n * @return true if there is data available to read, false otherwise\n *\/\n bool\n dataAvailable(unsigned int millis = 0)\n {\n if (mraa_uart_data_available(m_uart, millis))\n return true;\n else\n return false;\n }\n\n \/**\n * Flush the outbound data.\n * Blocks until complete.\n *\n * @return Result of operation\n *\/\n Result\n flush()\n {\n return (Result) mraa_uart_flush(m_uart);\n }\n\n \/**\n * Set the baudrate.\n * Takes an int and will attempt to decide what baudrate is\n * to be used on the UART hardware.\n *\n * @param baud unsigned int of baudrate i.e. 9600\n * @return Result of operation\n *\/\n Result\n setBaudRate(unsigned int baud)\n {\n return (Result) mraa_uart_set_baudrate(m_uart, baud);\n }\n\n \/**\n * Set the transfer mode\n * For example setting the mode to 8N1 would be\n * \"dev.setMode(8,UART_PARITY_NONE , 1)\"\n *\n * @param bytesize data bits\n * @param parity Parity bit setting\n * @param stopbits stop bits\n * @return Result of operation\n *\/\n Result\n setMode(int bytesize, UartParity parity, int stopbits)\n {\n return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);\n }\n\n \/**\n * Set the flowcontrol\n *\n * @param xonxoff XON\/XOFF Software flow control.\n * @param rtscts RTS\/CTS out of band hardware flow control\n * @return Result of operation\n *\/\n Result\n setFlowcontrol(bool xonxoff, bool rtscts)\n {\n return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);\n }\n\n \/**\n * Set the timeout for read and write operations\n * <= 0 will disable that timeout\n *\n * @param read read timeout\n * @param write write timeout\n * @param interchar inbetween char timeout\n * @return Result of operation\n *\/\n Result\n setTimeout(int read, int write, int interchar)\n {\n return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);\n }\n\n private:\n mraa_uart_context m_uart;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>#include <json\/json.h>\n#include <boost\/filesystem.hpp>\n#include <boost\/program_options.hpp>\n#include <algorithm>\n#include <regex>\n\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\n\/\/ append autoids to the given vector\n\/\/ - recursively parses a json \"tree\" and stores all values of string type objects\n\/\/ - strings with leading '%' are stored without '%' as well\nvoid parseJSON(Json::Value& root, std::set<std::string>& autoids)\n{\n for ( auto it = root.begin(), e = root.end(); it != e; ++it)\n {\n if ( (*it).isString() )\n {\n std::string id((*it).asString());\n autoids.insert(id);\n \/\/ insert it without %% as well\n id.erase(std::remove(id.begin(), id.end(),'%'), id.end());\n autoids.insert(id);\n }\n parseJSON(*it, autoids);\n }\n}\n\n\/\/ append autoids to the given vector\n\/\/ - collects string literals from AutoId calls\n\/\/ - collects string literals from macros that use AutoId\n\/\/ possible issues:\n\/\/ - multiplie AutoId expressions in 1 line are not parsed\nvoid parseCpp(std::string& content, std::set<std::string>& autoids)\n{\n static std::array<std::string,7> macros = {\n \"DEFINE_BUFF_BASE\",\n \"DEFINE_COMPONENT_BASE\",\n \"DEFINE_ROOM_PROPERTY\",\n \"DEFINE_MAP_ELEMENT_BASE\",\n \"DEFINE_SUB_SYSTEM_BASE\",\n \"DEFINE_SYSTEM_BASE\",\n \"DEFINE_MESSAGE_BASE\" };\n \/\/ the matching group (1) contains the actual string\n static std::regex autoid_regex(\"AutoId\\\\(\\\\s*\\\"(\\\\S+)\\\"\\\\s*\\\\)\", std::regex_constants::ECMAScript | std::regex_constants::icase);\n auto aid_begin = std::sregex_iterator(content.begin(), content.end(), autoid_regex);\n auto aid_end = std::sregex_iterator();\n for ( auto it = aid_begin; it != aid_end; ++it )\n {\n std::smatch match = *it;\n \/\/std::cout << \"full: \" << match.str() << \", group: \" << match.str(1) << std::endl;\n autoids.insert(match.str(1));\n }\n \/\/ todo macros:\n \/\/ define_buff_base\n \/\/ define_component_base\n \/\/ define_room_property_base\n \/\/ define_map_element_base\n \/\/ define_sub_system_base\n \/\/ define_system_base\n \/\/ define_message_base\n for ( auto m : macros )\n {\n \/\/std::cout << \"matching for macro \" << m << \"...\" << std::endl;\n std::regex macro_regex( m+\"\\\\(\\\\s*(\\\\S+)\\\\s*\\\\)\", std::regex_constants::ECMAScript | std::regex_constants::icase);\n auto m_begin = std::sregex_iterator(content.begin(), content.end(), macro_regex);\n auto m_end = std::sregex_iterator();\n for ( auto it = m_begin; it != m_end; ++it )\n {\n std::smatch match = *it;\n \/\/std::cout << \"full: \" << match.str() << \", group: \" << match.str(1) << std::endl;\n autoids.insert(match.str(1));\n }\n }\n}\n\nint main( int argc, char** argv)\n{\n std::string path(\"\"), output(\"\");\n std::vector<std::string> ext;\n bool enableCpp(false), enableJSON(false);\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help\",\"prints help\")\n (\"path\",po::value<std::string>(&path),\"path to files\")\n (\"ext\", po::value< std::vector<std::string> >(&ext)->multitoken(),\"extension of files, use comma separated list for multiple extensions\")\n (\"enable-cpp\", \"enable CPP parsing\")\n (\"enable-json\", \"enable JSON parsing\")\n (\"output-file\", po::value<std::string>(&output),\"name of the output file\");\n po::variables_map vm;\n po::store(po::parse_command_line(argc,argv,desc),vm);\n po::notify(vm);\n if (vm.count(\"help\"))\n {\n std::cout << \"This program collects autoids from files in a directory recursively.\" << std::endl\n << \"Files can be interpreted as either source files or content files, so enable-cpp and enable-json are exclusive.\" << std::endl\n << desc << std::endl;\n return 1;\n }\n if (vm.count(\"path\") == 0)\n {\n std::cout <<\"no path given\" << std::endl;\n return 1;\n }\n if (vm.count(\"output-file\") == 0)\n {\n std::cout << \"no output file given\" << std::endl;\n return 1;\n }\n enableCpp = vm.count(\"enable-cpp\") > 0;\n enableJSON = vm.count(\"enable-json\") > 0;\n if ( enableCpp && enableJSON )\n {\n std::cout << \"enable-cpp and enable-json are exclusive, but you enabled both\" << std::endl;\n return 1;\n }\n if ( !enableCpp && !enableJSON )\n {\n std::cout << \"you must enable either cpp or json parsing\" << std::endl;\n return 1;\n }\n if (vm.count(\"ext\") == 0)\n {\n std::cout << \"no extension given\" << std::endl;\n if (enableCpp)\n {\n std::cout << \"defaulting to .cpp,.h\" << std::endl;\n ext.push_back(\".cpp\");\n ext.push_back(\".h\");\n }\n else\n {\n std::cout << \"defaulting to .json\" << std::endl;\n ext.push_back(\".json\");\n }\n }\n \/\/std::cout << \"supported extensions:\" << std::endl;\n \/\/ auto prepend '.' : cpp -> .cpp\n for ( std::string& s : ext )\n {\n if ( s[0] != '.' )\n {\n s = '.'+s;\n }\n \/\/std::cout << s << std::endl;\n }\n \/*\n std::string e = ext.front();\n e = std::accumulate(std::next(ext.begin()), ext.end(),e, [](std::string& s, std::string& ss){ return s+\",\"+ss;});\n std::cout << \"called with\" << std::endl\n << \"path:\" << path << std::endl\n << \"ext:\" << e << std::endl\n << \"enable-cpp\" << enableCpp << std::endl\n << \"enable-json\" << enableJSON << std::endl\n << \"output \" << output << std::endl;*\/\n if (!fs::exists(path) || !fs::is_directory(path))\n {\n std::cout << path << \"does not exist or not a directory\" << std::endl;\n return 1;\n }\n std::set<std::string> autoids;\n for ( fs::recursive_directory_iterator it(path), eit; it != eit; ++it )\n {\n if ( fs::is_regular_file(*it) )\n {\n \/\/std::cout << \"checking file \" << it->path().filename() << \" extesion :\" << it->path().extension() << std::endl;\n if ( std::find(ext.begin(), ext.end(), it->path().extension()) == ext.end() )\n {\n \/\/std::cout << \"not supported extension \" << it->path().extension() << std::endl;\n continue;\n }\n if (enableJSON)\n {\n fs::ifstream in(it->path());\n Json::Value root;\n in >> root;\n parseJSON(root, autoids);\n }\n else\n {\n \/\/std::cout << \"checking \" << it->path() << std::endl;\n fs::ifstream in(it->path());\n std::string content((std::istreambuf_iterator<char>(in)), (std::istreambuf_iterator<char>()));\n \/\/std::cout << \"content \" << content << std::endl;\n parseCpp(content, autoids);\n }\n }\n }\n fs::ofstream out(output);\n for (auto autoid:autoids)\n {\n out << autoid << std::endl;\n }\n return 0;\n}\n<commit_msg>remove comment<commit_after>#include <json\/json.h>\n#include <boost\/filesystem.hpp>\n#include <boost\/program_options.hpp>\n#include <algorithm>\n#include <regex>\n\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\n\/\/ append autoids to the given vector\n\/\/ - recursively parses a json \"tree\" and stores all values of string type objects\n\/\/ - strings with leading '%' are stored without '%' as well\nvoid parseJSON(Json::Value& root, std::set<std::string>& autoids)\n{\n for ( auto it = root.begin(), e = root.end(); it != e; ++it)\n {\n if ( (*it).isString() )\n {\n std::string id((*it).asString());\n autoids.insert(id);\n \/\/ insert it without %% as well\n id.erase(std::remove(id.begin(), id.end(),'%'), id.end());\n autoids.insert(id);\n }\n parseJSON(*it, autoids);\n }\n}\n\n\/\/ append autoids to the given vector\n\/\/ - collects string literals from AutoId calls\n\/\/ - collects string literals from macros that use AutoId\n\/\/ possible issues:\n\/\/ - multiplie AutoId expressions in 1 line are not parsed\nvoid parseCpp(std::string& content, std::set<std::string>& autoids)\n{\n static std::array<std::string,7> macros = {\n \"DEFINE_BUFF_BASE\",\n \"DEFINE_COMPONENT_BASE\",\n \"DEFINE_ROOM_PROPERTY\",\n \"DEFINE_MAP_ELEMENT_BASE\",\n \"DEFINE_SUB_SYSTEM_BASE\",\n \"DEFINE_SYSTEM_BASE\",\n \"DEFINE_MESSAGE_BASE\" };\n \/\/ the matching group (1) contains the actual string\n static std::regex autoid_regex(\"AutoId\\\\(\\\\s*\\\"(\\\\S+)\\\"\\\\s*\\\\)\", std::regex_constants::ECMAScript | std::regex_constants::icase);\n auto aid_begin = std::sregex_iterator(content.begin(), content.end(), autoid_regex);\n auto aid_end = std::sregex_iterator();\n for ( auto it = aid_begin; it != aid_end; ++it )\n {\n std::smatch match = *it;\n \/\/std::cout << \"full: \" << match.str() << \", group: \" << match.str(1) << std::endl;\n autoids.insert(match.str(1));\n }\n for ( auto m : macros )\n {\n \/\/std::cout << \"matching for macro \" << m << \"...\" << std::endl;\n std::regex macro_regex( m+\"\\\\(\\\\s*(\\\\S+)\\\\s*\\\\)\", std::regex_constants::ECMAScript | std::regex_constants::icase);\n auto m_begin = std::sregex_iterator(content.begin(), content.end(), macro_regex);\n auto m_end = std::sregex_iterator();\n for ( auto it = m_begin; it != m_end; ++it )\n {\n std::smatch match = *it;\n \/\/std::cout << \"full: \" << match.str() << \", group: \" << match.str(1) << std::endl;\n autoids.insert(match.str(1));\n }\n }\n}\n\nint main( int argc, char** argv)\n{\n std::string path(\"\"), output(\"\");\n std::vector<std::string> ext;\n bool enableCpp(false), enableJSON(false);\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help\",\"prints help\")\n (\"path\",po::value<std::string>(&path),\"path to files\")\n (\"ext\", po::value< std::vector<std::string> >(&ext)->multitoken(),\"extension of files, use comma separated list for multiple extensions\")\n (\"enable-cpp\", \"enable CPP parsing\")\n (\"enable-json\", \"enable JSON parsing\")\n (\"output-file\", po::value<std::string>(&output),\"name of the output file\");\n po::variables_map vm;\n po::store(po::parse_command_line(argc,argv,desc),vm);\n po::notify(vm);\n if (vm.count(\"help\"))\n {\n std::cout << \"This program collects autoids from files in a directory recursively.\" << std::endl\n << \"Files can be interpreted as either source files or content files, so enable-cpp and enable-json are exclusive.\" << std::endl\n << desc << std::endl;\n return 1;\n }\n if (vm.count(\"path\") == 0)\n {\n std::cout <<\"no path given\" << std::endl;\n return 1;\n }\n if (vm.count(\"output-file\") == 0)\n {\n std::cout << \"no output file given\" << std::endl;\n return 1;\n }\n enableCpp = vm.count(\"enable-cpp\") > 0;\n enableJSON = vm.count(\"enable-json\") > 0;\n if ( enableCpp && enableJSON )\n {\n std::cout << \"enable-cpp and enable-json are exclusive, but you enabled both\" << std::endl;\n return 1;\n }\n if ( !enableCpp && !enableJSON )\n {\n std::cout << \"you must enable either cpp or json parsing\" << std::endl;\n return 1;\n }\n if (vm.count(\"ext\") == 0)\n {\n std::cout << \"no extension given\" << std::endl;\n if (enableCpp)\n {\n std::cout << \"defaulting to .cpp,.h\" << std::endl;\n ext.push_back(\".cpp\");\n ext.push_back(\".h\");\n }\n else\n {\n std::cout << \"defaulting to .json\" << std::endl;\n ext.push_back(\".json\");\n }\n }\n \/\/std::cout << \"supported extensions:\" << std::endl;\n \/\/ auto prepend '.' : cpp -> .cpp\n for ( std::string& s : ext )\n {\n if ( s[0] != '.' )\n {\n s = '.'+s;\n }\n \/\/std::cout << s << std::endl;\n }\n \/*\n std::string e = ext.front();\n e = std::accumulate(std::next(ext.begin()), ext.end(),e, [](std::string& s, std::string& ss){ return s+\",\"+ss;});\n std::cout << \"called with\" << std::endl\n << \"path:\" << path << std::endl\n << \"ext:\" << e << std::endl\n << \"enable-cpp\" << enableCpp << std::endl\n << \"enable-json\" << enableJSON << std::endl\n << \"output \" << output << std::endl;*\/\n if (!fs::exists(path) || !fs::is_directory(path))\n {\n std::cout << path << \"does not exist or not a directory\" << std::endl;\n return 1;\n }\n std::set<std::string> autoids;\n for ( fs::recursive_directory_iterator it(path), eit; it != eit; ++it )\n {\n if ( fs::is_regular_file(*it) )\n {\n \/\/std::cout << \"checking file \" << it->path().filename() << \" extesion :\" << it->path().extension() << std::endl;\n if ( std::find(ext.begin(), ext.end(), it->path().extension()) == ext.end() )\n {\n \/\/std::cout << \"not supported extension \" << it->path().extension() << std::endl;\n continue;\n }\n if (enableJSON)\n {\n fs::ifstream in(it->path());\n Json::Value root;\n in >> root;\n parseJSON(root, autoids);\n }\n else\n {\n \/\/std::cout << \"checking \" << it->path() << std::endl;\n fs::ifstream in(it->path());\n std::string content((std::istreambuf_iterator<char>(in)), (std::istreambuf_iterator<char>()));\n \/\/std::cout << \"content \" << content << std::endl;\n parseCpp(content, autoids);\n }\n }\n }\n fs::ofstream out(output);\n for (auto autoid:autoids)\n {\n out << autoid << std::endl;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule\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 <iostream>\n#include <sys\/time.h>\n\n#include \"src\/ext\/cpputil\/include\/command_line\/command_line.h\"\n#include \"src\/ext\/cpputil\/include\/io\/column.h\"\n#include \"src\/ext\/cpputil\/include\/io\/filterstream.h\"\n#include \"src\/ext\/cpputil\/include\/signal\/debug_handler.h\"\n\n#include \"src\/cfg\/cfg_transforms.h\"\n#include \"src\/tunit\/tunit.h\"\n#include \"src\/search\/progress_callback.h\"\n#include \"src\/search\/statistics_callback.h\"\n#include \"src\/search\/timeout.h\"\n#include \"tools\/args\/search.h\"\n#include \"tools\/args\/target.h\"\n#include \"tools\/gadgets\/cost_function.h\"\n#include \"tools\/gadgets\/sandbox.h\"\n#include \"tools\/gadgets\/search.h\"\n#include \"tools\/gadgets\/search_state.h\"\n#include \"tools\/gadgets\/seed.h\"\n#include \"tools\/gadgets\/target.h\"\n#include \"tools\/gadgets\/testcases.h\"\n#include \"tools\/gadgets\/transforms.h\"\n#include \"tools\/gadgets\/verifier.h\"\n#include \"tools\/io\/timeout.h\"\n#include \"tools\/ui\/console.h\"\n\nusing namespace cpputil;\nusing namespace std;\nusing namespace stoke;\n\nauto& io = Heading::create(\"Output Options:\");\nauto& out = ValueArg<string>::create(\"out\")\n .alternate(\"o\")\n .usage(\"<path\/to\/file.s>\")\n .description(\"File to write successful results to\")\n .default_val(\"result.s\");\n\nauto& stats = Heading::create(\"Statistics Options:\");\nauto& stat_int =\n ValueArg<size_t>::create(\"statistics_interval\")\n .usage(\"<int>\")\n .description(\"Number of iterations between statistics updates\")\n .default_val(1000000);\n\nauto& automation_heading = Heading::create(\"Automation Options:\");\nauto& timeout_action_arg =\n ValueArg<Timeout, TimeoutReader, TimeoutWriter>::create(\"timeout_action\")\n .usage(\"(quit|restart|testcase)\")\n .description(\"Action to take when search times out\")\n .default_val(Timeout::RESTART);\nauto& timeout_cycles_arg =\n ValueArg<size_t>::create(\"timeout_cycles\")\n .usage(\"<int>\")\n .description(\"Number of timeout cycles to attempt before giving up\")\n .default_val(16);\n\nvoid sep(ostream& os) {\n for (size_t i = 0; i < 80; ++i) {\n os << \"*\";\n }\n os << endl << endl;\n}\n\nvoid pcb(const ProgressCallbackData& data, void* arg) {\n ostream& os = *((ostream*)arg);\n\n CfgTransforms tforms;\n\n os << \"Progress Update: \" << endl;\n os << endl;\n\n ofilterstream<Column> ofs(os);\n ofs.filter().padding(5);\n\n auto best_yet = data.state.best_yet;\n tforms.remove_unreachable(best_yet);\n tforms.remove_nop(best_yet);\n\n ofs << \"Lowest Cost Discovered (\" << data.state.best_yet_cost << \")\" << endl;\n ofs << endl;\n ofs << best_yet.get_code();\n ofs.filter().next();\n\n auto best_correct = data.state.best_correct;\n tforms.remove_unreachable(best_correct);\n tforms.remove_nop(best_correct);\n\n ofs << \"Lowest Known Correct Cost (\" << data.state.best_correct_cost << \")\" << endl;\n ofs << endl;\n ofs << best_correct.get_code();\n ofs.filter().done();\n\n os << endl << endl;\n sep(os);\n}\n\nstruct ScbArg {\n ostream* os;\n uint32_t** cost_stats;\n};\n\nvoid scb(const StatisticsCallbackData& data, void* arg) {\n ScbArg sa = *((ScbArg*)arg);\n ostream& os = *(sa.os);\n uint32_t** cost_stats = sa.cost_stats;\n\n os << \"Statistics Update: \" << endl;\n os << endl;\n os << \"Iterations: \" << data.iterations << endl;\n os << \"Elapsed Time: \" << data.elapsed.count() << \"s\" << endl;\n os << \"Iterations\/s: \" << (data.iterations \/ data.elapsed.count()) << endl;\n os << endl;\n\n ofilterstream<Column> ofs(os);\n ofs.filter().padding(5);\n\n Statistics total;\n for (size_t i = 0; i < 6; ++i) {\n total += data.move_statistics[i];\n }\n\n ofs << \"Move Type\" << endl;\n ofs << endl;\n ofs << \"Instruction\" << endl;\n ofs << \"Opcode\" << endl;\n ofs << \"Operand\" << endl;\n ofs << \"Resize\" << endl;\n ofs << \"Local Swap\" << endl;\n ofs << \"Global Swap\" << endl;\n ofs << \"Extension\" << endl;\n ofs << endl;\n ofs << \"Total\";\n ofs.filter().next();\n\n ofs << \"Proposed\" << endl;\n ofs << endl;\n for (size_t i = 0; i < (size_t) Move::NUM_MOVES; ++i) {\n ofs << 100 * (double)data.move_statistics[i].num_proposed \/ data.iterations << \"%\" << endl;\n }\n ofs << endl;\n ofs << 100 * (double)total.num_proposed \/ data.iterations << \"%\";\n ofs.filter().next();\n\n ofs << \"Succeeded\" << endl;\n ofs << endl;\n for (size_t i = 0; i < (size_t) Move::NUM_MOVES; ++i) {\n ofs << 100 * (double)data.move_statistics[i].num_succeeded \/ data.iterations << \"%\" << endl;\n }\n ofs << endl;\n ofs << 100 * (double)total.num_succeeded \/ data.iterations << \"%\";\n ofs.filter().next();\n\n ofs << \"Accepted\" << endl;\n ofs << endl;\n for (size_t i = 0; i < (size_t) Move::NUM_MOVES; ++i) {\n ofs << 100 * (double)data.move_statistics[i].num_accepted \/ data.iterations << \"%\" << endl;\n }\n ofs << endl;\n ofs << 100 * (double)total.num_accepted \/ data.iterations << \"%\";\n ofs.filter().done();\n\n os << endl << endl;\n sep(os);\n\n}\n\nint main(int argc, char** argv) {\n CommandLineConfig::strict_with_convenience(argc, argv);\n DebugHandler::install_sigsegv();\n DebugHandler::install_sigill();\n\n SeedGadget seed;\n TargetGadget target;\n\n TrainingSetGadget training_set(seed);\n SandboxGadget training_sb(training_set);\n\n TransformsGadget transforms(seed);\n SearchGadget search(&transforms, seed);\n\n TestSetGadget test_set(seed);\n SandboxGadget test_sb(test_set);\n CostFunctionGadget holdout_fxn(target, &test_sb);\n VerifierGadget verifier(holdout_fxn);\n\n if (!target.is_sound()) {\n Console::error(1) << \"Target reads undefined variables, or leaves live_out undefined.\" << endl;\n }\n\n ScbArg scb_arg {&Console::msg(), nullptr};\n search.set_progress_callback(pcb, &Console::msg())\n .set_statistics_callback(scb, &scb_arg)\n .set_statistics_interval(stat_int);\n\n SearchStateGadget state;\n for (size_t i = 0; ; ++i) {\n CostFunctionGadget fxn(target, &training_sb);\n\n Console::msg() << \"Running search:\" << endl << endl;\n state = SearchStateGadget();\n search.run(target, fxn, init_arg, state, aux_fxns_arg.value());\n\n if (state.interrupted) {\n Console::msg() << \"Search interrupted!\" << endl;\n exit(1);\n }\n\n const auto verified = verifier.verify(target, state.best_correct);\n\n if (!state.success) {\n Console::msg() << \"Unable to discover a new correct rewrite before timing out... \" << endl << endl;\n } else if (!verified) {\n Console::msg() << \"Unable to verify new rewrite...\" << endl << endl;\n } else {\n if (strategy_arg.value() == Strategy::NONE) {\n Console::msg() << \"Search terminated successfully (but no verification was performed)!\" << endl;\n } else {\n Console::msg() << \"Search terminated successfully with a verified rewrite!\" << endl;\n }\n break;\n }\n\n sep(Console::msg());\n\n if ((timeout_action_arg == Timeout::RESTART) && (i < timeout_cycles_arg.value())) {\n Console::msg() << \"Restarting search:\" << endl << endl;\n } else if ((timeout_action_arg == Timeout::TESTCASE) && (i < timeout_cycles_arg.value())\n && verifier.counter_example_available()) {\n Console::msg() << \"Restarting search using new testcase:\" << endl << endl;\n Console::msg() << verifier.get_counter_example() << endl << endl;\n training_sb.insert_input(verifier.get_counter_example());\n } else {\n Console::error(1) << \"Search terminated unsuccessfully; unable to discover a new rewrite!\" << endl;\n }\n }\n\n CfgTransforms tforms;\n tforms.remove_unreachable(state.best_correct);\n tforms.remove_nop(state.best_correct);\n\n TUnit rewrite;\n rewrite.name = target_arg.value().name;\n rewrite.code = state.best_correct.get_code();\n\n ofstream ofs(out.value());\n ofs << rewrite;\n\n return 0;\n}\n<commit_msg>added verifier errors to stoke search<commit_after>\/\/ Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule\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 <iostream>\n#include <sys\/time.h>\n\n#include \"src\/ext\/cpputil\/include\/command_line\/command_line.h\"\n#include \"src\/ext\/cpputil\/include\/io\/column.h\"\n#include \"src\/ext\/cpputil\/include\/io\/filterstream.h\"\n#include \"src\/ext\/cpputil\/include\/signal\/debug_handler.h\"\n\n#include \"src\/cfg\/cfg_transforms.h\"\n#include \"src\/tunit\/tunit.h\"\n#include \"src\/search\/progress_callback.h\"\n#include \"src\/search\/statistics_callback.h\"\n#include \"src\/search\/timeout.h\"\n#include \"tools\/args\/search.h\"\n#include \"tools\/args\/target.h\"\n#include \"tools\/gadgets\/cost_function.h\"\n#include \"tools\/gadgets\/sandbox.h\"\n#include \"tools\/gadgets\/search.h\"\n#include \"tools\/gadgets\/search_state.h\"\n#include \"tools\/gadgets\/seed.h\"\n#include \"tools\/gadgets\/target.h\"\n#include \"tools\/gadgets\/testcases.h\"\n#include \"tools\/gadgets\/transforms.h\"\n#include \"tools\/gadgets\/verifier.h\"\n#include \"tools\/io\/timeout.h\"\n#include \"tools\/ui\/console.h\"\n\nusing namespace cpputil;\nusing namespace std;\nusing namespace stoke;\n\nauto& io = Heading::create(\"Output Options:\");\nauto& out = ValueArg<string>::create(\"out\")\n .alternate(\"o\")\n .usage(\"<path\/to\/file.s>\")\n .description(\"File to write successful results to\")\n .default_val(\"result.s\");\n\nauto& stats = Heading::create(\"Statistics Options:\");\nauto& stat_int =\n ValueArg<size_t>::create(\"statistics_interval\")\n .usage(\"<int>\")\n .description(\"Number of iterations between statistics updates\")\n .default_val(1000000);\n\nauto& automation_heading = Heading::create(\"Automation Options:\");\nauto& timeout_action_arg =\n ValueArg<Timeout, TimeoutReader, TimeoutWriter>::create(\"timeout_action\")\n .usage(\"(quit|restart|testcase)\")\n .description(\"Action to take when search times out\")\n .default_val(Timeout::RESTART);\nauto& timeout_cycles_arg =\n ValueArg<size_t>::create(\"timeout_cycles\")\n .usage(\"<int>\")\n .description(\"Number of timeout cycles to attempt before giving up\")\n .default_val(16);\n\nvoid sep(ostream& os) {\n for (size_t i = 0; i < 80; ++i) {\n os << \"*\";\n }\n os << endl << endl;\n}\n\nvoid pcb(const ProgressCallbackData& data, void* arg) {\n ostream& os = *((ostream*)arg);\n\n CfgTransforms tforms;\n\n os << \"Progress Update: \" << endl;\n os << endl;\n\n ofilterstream<Column> ofs(os);\n ofs.filter().padding(5);\n\n auto best_yet = data.state.best_yet;\n tforms.remove_unreachable(best_yet);\n tforms.remove_nop(best_yet);\n\n ofs << \"Lowest Cost Discovered (\" << data.state.best_yet_cost << \")\" << endl;\n ofs << endl;\n ofs << best_yet.get_code();\n ofs.filter().next();\n\n auto best_correct = data.state.best_correct;\n tforms.remove_unreachable(best_correct);\n tforms.remove_nop(best_correct);\n\n ofs << \"Lowest Known Correct Cost (\" << data.state.best_correct_cost << \")\" << endl;\n ofs << endl;\n ofs << best_correct.get_code();\n ofs.filter().done();\n\n os << endl << endl;\n sep(os);\n}\n\nstruct ScbArg {\n ostream* os;\n uint32_t** cost_stats;\n};\n\nvoid scb(const StatisticsCallbackData& data, void* arg) {\n ScbArg sa = *((ScbArg*)arg);\n ostream& os = *(sa.os);\n uint32_t** cost_stats = sa.cost_stats;\n\n os << \"Statistics Update: \" << endl;\n os << endl;\n os << \"Iterations: \" << data.iterations << endl;\n os << \"Elapsed Time: \" << data.elapsed.count() << \"s\" << endl;\n os << \"Iterations\/s: \" << (data.iterations \/ data.elapsed.count()) << endl;\n os << endl;\n\n ofilterstream<Column> ofs(os);\n ofs.filter().padding(5);\n\n Statistics total;\n for (size_t i = 0; i < 6; ++i) {\n total += data.move_statistics[i];\n }\n\n ofs << \"Move Type\" << endl;\n ofs << endl;\n ofs << \"Instruction\" << endl;\n ofs << \"Opcode\" << endl;\n ofs << \"Operand\" << endl;\n ofs << \"Resize\" << endl;\n ofs << \"Local Swap\" << endl;\n ofs << \"Global Swap\" << endl;\n ofs << \"Extension\" << endl;\n ofs << endl;\n ofs << \"Total\";\n ofs.filter().next();\n\n ofs << \"Proposed\" << endl;\n ofs << endl;\n for (size_t i = 0; i < (size_t) Move::NUM_MOVES; ++i) {\n ofs << 100 * (double)data.move_statistics[i].num_proposed \/ data.iterations << \"%\" << endl;\n }\n ofs << endl;\n ofs << 100 * (double)total.num_proposed \/ data.iterations << \"%\";\n ofs.filter().next();\n\n ofs << \"Succeeded\" << endl;\n ofs << endl;\n for (size_t i = 0; i < (size_t) Move::NUM_MOVES; ++i) {\n ofs << 100 * (double)data.move_statistics[i].num_succeeded \/ data.iterations << \"%\" << endl;\n }\n ofs << endl;\n ofs << 100 * (double)total.num_succeeded \/ data.iterations << \"%\";\n ofs.filter().next();\n\n ofs << \"Accepted\" << endl;\n ofs << endl;\n for (size_t i = 0; i < (size_t) Move::NUM_MOVES; ++i) {\n ofs << 100 * (double)data.move_statistics[i].num_accepted \/ data.iterations << \"%\" << endl;\n }\n ofs << endl;\n ofs << 100 * (double)total.num_accepted \/ data.iterations << \"%\";\n ofs.filter().done();\n\n os << endl << endl;\n sep(os);\n\n}\n\nint main(int argc, char** argv) {\n CommandLineConfig::strict_with_convenience(argc, argv);\n DebugHandler::install_sigsegv();\n DebugHandler::install_sigill();\n\n SeedGadget seed;\n TargetGadget target;\n\n TrainingSetGadget training_set(seed);\n SandboxGadget training_sb(training_set);\n\n TransformsGadget transforms(seed);\n SearchGadget search(&transforms, seed);\n\n TestSetGadget test_set(seed);\n SandboxGadget test_sb(test_set);\n CostFunctionGadget holdout_fxn(target, &test_sb);\n VerifierGadget verifier(holdout_fxn);\n\n if (!target.is_sound()) {\n Console::error(1) << \"Target reads undefined variables, or leaves live_out undefined.\" << endl;\n }\n\n ScbArg scb_arg {&Console::msg(), nullptr};\n search.set_progress_callback(pcb, &Console::msg())\n .set_statistics_callback(scb, &scb_arg)\n .set_statistics_interval(stat_int);\n\n SearchStateGadget state;\n for (size_t i = 0; ; ++i) {\n CostFunctionGadget fxn(target, &training_sb);\n\n Console::msg() << \"Running search:\" << endl << endl;\n state = SearchStateGadget();\n search.run(target, fxn, init_arg, state, aux_fxns_arg.value());\n\n if (state.interrupted) {\n Console::msg() << \"Search interrupted!\" << endl;\n exit(1);\n }\n\n const auto verified = verifier.verify(target, state.best_correct);\n\n if(verifier.has_error()) {\n Console::msg() << \"The verifier encountered an error:\" << endl;\n Console::msg() << verifier.error() << endl;\n }\n\n if (!state.success) {\n Console::msg() << \"Unable to discover a new correct rewrite before timing out... \" << endl << endl;\n } else if (!verified) {\n Console::msg() << \"Unable to verify new rewrite...\" << endl << endl;\n } else {\n if (strategy_arg.value() == Strategy::NONE) {\n Console::msg() << \"Search terminated successfully (but no verification was performed)!\" << endl;\n } else {\n Console::msg() << \"Search terminated successfully with a verified rewrite!\" << endl;\n }\n break;\n }\n\n sep(Console::msg());\n\n if ((timeout_action_arg == Timeout::RESTART) && (i < timeout_cycles_arg.value())) {\n Console::msg() << \"Restarting search:\" << endl << endl;\n } else if ((timeout_action_arg == Timeout::TESTCASE) && (i < timeout_cycles_arg.value())\n && verifier.counter_example_available()) {\n Console::msg() << \"Restarting search using new testcase:\" << endl << endl;\n Console::msg() << verifier.get_counter_example() << endl << endl;\n training_sb.insert_input(verifier.get_counter_example());\n } else {\n Console::error(1) << \"Search terminated unsuccessfully; unable to discover a new rewrite!\" << endl;\n }\n }\n\n CfgTransforms tforms;\n tforms.remove_unreachable(state.best_correct);\n tforms.remove_nop(state.best_correct);\n\n TUnit rewrite;\n rewrite.name = target_arg.value().name;\n rewrite.code = state.best_correct.get_code();\n\n ofstream ofs(out.value());\n ofs << rewrite;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file fractile.cpp\n *\n * @date June, 2016\n * @author Tack\n **\/\n\n#include \"fractile.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <string>\n\n#include <boost\/thread.hpp>\n\n#include \"logger_factory.h\"\n#include \"plugin_factory.h\"\n\n#include \"json_parser.h\"\n#include \"fetcher.h\"\n#include \"ensemble.h\"\n\nnamespace himan\n{\n\nnamespace plugin\n{\n\nfractile::fractile()\n{\n itsClearTextFormula = \"%\";\n itsCudaEnabledCalculation = false;\n itsLogger = logger_factory::Instance()->GetLog(\"fractile\");\n}\n\nfractile::~fractile()\n{\n}\n\nvoid fractile::Process(const std::shared_ptr<const plugin_configuration> conf)\n{\n Init(conf);\n\n if(!itsConfiguration->GetValue(\"param\").empty())\n {\n itsParamName = itsConfiguration->GetValue(\"param\");\n }\n else\n {\n throw std::runtime_error(\"Fractile_plugin: param not specified.\");\n exit(1);\n }\n\n auto r = GET_PLUGIN(radon);\n\n params calculatedParams;\n std::vector<std::string> fractiles = {\"F0-\",\"F10-\",\"F25-\",\"F50-\",\"F75-\",\"F90-\",\"F100-\"};\n\n for (const std::string& fractile : fractiles)\n {\n\tcalculatedParams.push_back(param(fractile + itsParamName));\n }\n\n SetParams(calculatedParams);\n\n Start();\n}\n\nvoid fractile::Calculate(std::shared_ptr<info> myTargetInfo, uint16_t threadIndex)\n{\n\n const int numForecasts = 51;\n std::vector<int> fractile = {0,10,25,50,75,90,100};\n\n const std::string deviceType = \"CPU\";\n\n auto threadedLogger = logger_factory::Instance()->GetLog(\"fractileThread # \" + boost::lexical_cast<std::string>(threadIndex));\n\n forecast_time forecastTime = myTargetInfo->Time();\n level forecastLevel = myTargetInfo->Level();\n\n threadedLogger->Info(\"Calculating time \" + static_cast<std::string>(forecastTime.ValidDateTime()) +\n \" level \" + static_cast<std::string>(forecastLevel));\n \n ensemble ens(param(itsParamName), numForecasts);\n\n try\n {\n ens.Fetch(itsConfiguration, forecastTime, forecastLevel);\n }\n catch (const HPExceptionType& e)\n {\n\tif (e == kFileDataNotFound)\n\t{\n \tthrow std::runtime_error(ClassName() + \" failed to find ensemble data\");\n\t}\n }\n\n myTargetInfo->ResetLocation();\n ens.ResetLocation();\n\n while (myTargetInfo->NextLocation() && ens.NextLocation())\n {\n\tauto sortedValues = ens.SortedValues();\n\n size_t targetInfoIndex = 0;\n for (auto i : fractile)\n {\n myTargetInfo->ParamIndex(targetInfoIndex);\n myTargetInfo->Value(sortedValues[i*(numForecasts-1)\/100]);\n ++targetInfoIndex;\n }\n }\n\n\tthreadedLogger->Info(\"[\" + deviceType + \"] Missing values: \" + boost::lexical_cast<std::string>\n\t\t\t(myTargetInfo->Data().MissingCount()) + \"\/\" + boost::lexical_cast<std::string> (myTargetInfo->Data().Size()));\n}\n\n} \/\/ plugin\n\n} \/\/ namespace\n<commit_msg>Remove get plugin call<commit_after>\/**\n * @file fractile.cpp\n *\n * @date June, 2016\n * @author Tack\n **\/\n\n#include \"fractile.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <string>\n\n#include <boost\/thread.hpp>\n\n#include \"logger_factory.h\"\n#include \"plugin_factory.h\"\n\n#include \"json_parser.h\"\n#include \"fetcher.h\"\n#include \"ensemble.h\"\n\nnamespace himan\n{\n\nnamespace plugin\n{\n\nfractile::fractile()\n{\n itsClearTextFormula = \"%\";\n itsCudaEnabledCalculation = false;\n itsLogger = logger_factory::Instance()->GetLog(\"fractile\");\n}\n\nfractile::~fractile()\n{\n}\n\nvoid fractile::Process(const std::shared_ptr<const plugin_configuration> conf)\n{\n Init(conf);\n\n if(!itsConfiguration->GetValue(\"param\").empty())\n {\n itsParamName = itsConfiguration->GetValue(\"param\");\n }\n else\n {\n throw std::runtime_error(\"Fractile_plugin: param not specified.\");\n exit(1);\n }\n\n params calculatedParams;\n std::vector<std::string> fractiles = {\"F0-\",\"F10-\",\"F25-\",\"F50-\",\"F75-\",\"F90-\",\"F100-\"};\n\n for (const std::string& fractile : fractiles)\n {\n\tcalculatedParams.push_back(param(fractile + itsParamName));\n }\n\n SetParams(calculatedParams);\n\n Start();\n}\n\nvoid fractile::Calculate(std::shared_ptr<info> myTargetInfo, uint16_t threadIndex)\n{\n\n const int numForecasts = 51;\n std::vector<int> fractile = {0,10,25,50,75,90,100};\n\n const std::string deviceType = \"CPU\";\n\n auto threadedLogger = logger_factory::Instance()->GetLog(\"fractileThread # \" + boost::lexical_cast<std::string>(threadIndex));\n\n forecast_time forecastTime = myTargetInfo->Time();\n level forecastLevel = myTargetInfo->Level();\n\n threadedLogger->Info(\"Calculating time \" + static_cast<std::string>(forecastTime.ValidDateTime()) +\n \" level \" + static_cast<std::string>(forecastLevel));\n \n ensemble ens(param(itsParamName), numForecasts);\n\n try\n {\n ens.Fetch(itsConfiguration, forecastTime, forecastLevel);\n }\n catch (const HPExceptionType& e)\n {\n\tif (e == kFileDataNotFound)\n\t{\n \tthrow std::runtime_error(ClassName() + \" failed to find ensemble data\");\n\t}\n }\n\n myTargetInfo->ResetLocation();\n ens.ResetLocation();\n\n while (myTargetInfo->NextLocation() && ens.NextLocation())\n {\n\tauto sortedValues = ens.SortedValues();\n\n size_t targetInfoIndex = 0;\n for (auto i : fractile)\n {\n myTargetInfo->ParamIndex(targetInfoIndex);\n myTargetInfo->Value(sortedValues[i*(numForecasts-1)\/100]);\n ++targetInfoIndex;\n }\n }\n\n\tthreadedLogger->Info(\"[\" + deviceType + \"] Missing values: \" + boost::lexical_cast<std::string>\n\t\t\t(myTargetInfo->Data().MissingCount()) + \"\/\" + boost::lexical_cast<std::string> (myTargetInfo->Data().Size()));\n}\n\n} \/\/ plugin\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <getopt.h>\n#include <algorithm>\n#include <memory>\n\n#include <zcm\/zcm-cpp.hpp>\n\n#include \"zcm\/json\/json.h\"\n\n#include \"zcm\/util\/TypeDb.hpp\"\n\n#include \"IndexerPluginDb.hpp\"\n\nusing namespace std;\n\nstruct Args\n{\n string logfile = \"\";\n string output = \"\";\n string plugin_path = \"\";\n string type_path = \"\";\n bool readable = false;\n bool debug = false;\n\n bool parse(int argc, char *argv[])\n {\n \/\/ set some defaults\n const char *optstring = \"l:o:p:t:rdh\";\n struct option long_opts[] = {\n { \"log\", required_argument, 0, 'l' },\n { \"output\", required_argument, 0, 'o' },\n { \"plugin-path\", required_argument, 0, 'p' },\n { \"type-path\", required_argument, 0, 't' },\n { \"readable\", no_argument, 0, 'r' },\n { \"debug\", no_argument, 0, 'd' },\n { \"help\", no_argument, 0, 'h' },\n { 0, 0, 0, 0 }\n };\n\n int c;\n while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0) {\n switch (c) {\n case 'l': logfile = string(optarg); break;\n case 'o': output = string(optarg); break;\n case 'p': plugin_path = string(optarg); break;\n case 't': type_path = string(optarg); break;\n case 'r': readable = true; break;\n case 'd': debug = true; break;\n case 'h': default: return false;\n };\n }\n\n if (logfile == \"\") {\n cerr << \"Please specify logfile input\" << endl;\n return false;\n }\n\n if (output == \"\") {\n cerr << \"Please specify index file output\" << endl;\n return false;\n }\n\n const char* type_path_env = getenv(\"ZCM_LOG_INDEXER_ZCMTYPES_PATH\");\n if (type_path == \"\" && type_path_env) type_path = type_path_env;\n if (type_path == \"\") {\n cerr << \"Please specify a zcmtypes.so path either through -t TYPE_PATH \"\n \"or through the env var ZCM_LOG_INDEXER_ZCMTYPES_PATH\" << endl;\n return false;\n }\n\n const char* plugin_path_env = getenv(\"ZCM_LOG_INDEXER_PLUGINS_PATH\");\n if (plugin_path == \"\" && plugin_path_env) plugin_path = plugin_path_env;\n if (plugin_path == \"\") cerr << \"Running with default timestamp indexer plugin\" << endl;\n\n return true;\n }\n\n void usage()\n {\n cerr << \"usage: zcm-log-indexer [options]\" << endl\n << \"\" << endl\n << \" Load in a log file and write an index json file that\" << endl\n << \" allows for faster log indexing.\" << endl\n << \"\" << endl\n << \"Example:\" << endl\n << \" zcm-log-indexer -l zcm.log -o index.dbz -t path\/to\/zcmtypes.so\" << endl\n << \"\" << endl\n << \"Options:\" << endl\n << \"\" << endl\n << \" -h, --help Shows this help text and exits\" << endl\n << \" -l, --log=logfile Input log to index for fast querying\" << endl\n << \" -o, --output=indexfile Output index file to be used with log\" << endl\n << \" -p, --plugin-path=path Path to shared library containing indexer plugins\" << endl\n << \" Can also be specified via the environment variable\" << endl\n << \" ZCM_LOG_INDEXER_ZCMTYPES_PATH\" << endl\n << \" -t, --type-path=path Path to shared library containing the zcmtypes\" << endl\n << \" Can also be specified via the environment variable\" << endl\n << \" ZCM_LOG_INDEXER_PLUGINS_PATH\" << endl\n << \" -r, --readable Don't minify the output index file. \" << endl\n << \" Leave it human readable\" << endl\n << \" -d, --debug Run a dry run to ensure proper indexer setup\" << endl\n << endl << endl;\n }\n};\n\nint main(int argc, char* argv[])\n{\n Args args;\n if (!args.parse(argc, argv)) {\n args.usage();\n return 1;\n }\n\n zcm::LogFile log(args.logfile, \"r\");\n if (!log.good()) {\n cerr << \"Unable to open logfile: \" << args.logfile << endl;\n return 1;\n }\n fseeko(log.getFilePtr(), 0, SEEK_END);\n \/\/ XXX Look into handling large logfiles\n off_t logSize = ftello(log.getFilePtr());\n\n ofstream output;\n output.open(args.output);\n if (!output.is_open()) {\n cerr << \"Unable to open output file: \" << args.output << endl;\n log.close();\n return 1;\n }\n\n vector<zcm::IndexerPlugin*> plugins;\n\n bool defaultShouldBeIncluded = true;\n zcm::IndexerPlugin* defaultPlugin = new zcm::IndexerPlugin();\n\n IndexerPluginDb pluginDb(args.plugin_path, args.debug);\n \/\/ Load plugins from path if specified\n if (args.plugin_path != \"\") {\n bool dependsOnDefault = false;\n vector<const zcm::IndexerPlugin*> dbPlugins = pluginDb.getPlugins();\n \/\/ casting away constness. Don't mess up.\n for (auto dbp : dbPlugins) {\n plugins.push_back((zcm::IndexerPlugin*) dbp);\n defaultShouldBeIncluded = false;\n auto deps = dbp->dependsOn();\n for (auto dep : deps) {\n if (dep == defaultPlugin->name()) {\n dependsOnDefault = true;\n break;\n }\n }\n }\n\n if (dependsOnDefault)\n defaultShouldBeIncluded = true;\n }\n\n if (defaultShouldBeIncluded) plugins.push_back(defaultPlugin);\n\n for (size_t i = 0; i < plugins.size(); ++i) {\n for (size_t j = i + 1; j < plugins.size(); ++j) {\n if (args.debug)\n cout << plugins.data()[i] << \"->name() == \"\n << plugins.data()[j] << \"->name()\" << endl;\n\n if (plugins[i]->name() == plugins[j]->name()) {\n cerr << \"Plugins must have unique names. Collision: \"\n << plugins[i]->name() << endl;\n return 1;\n }\n }\n }\n\n TypeDb types(args.type_path, args.debug);\n\n if (args.debug) return 0;\n\n struct PluginRuntimeInfo {\n zcm::IndexerPlugin* plugin;\n bool runThroughLog;\n };\n\n auto buildPluginGroups = [] (vector<zcm::IndexerPlugin*> plugins) {\n vector<vector<PluginRuntimeInfo>> groups;\n vector<zcm::IndexerPlugin*> lastLoop = plugins;\n while (!plugins.empty()) {\n groups.resize(groups.size() + 1);\n for (auto p = plugins.begin(); p != plugins.end();) {\n auto deps = (*p)->dependsOn();\n\n bool skipUntilLater = false;\n for (auto* dep : plugins) {\n if (find(deps.begin(), deps.end(), dep->name()) != deps.end()) {\n skipUntilLater = true;\n break;\n }\n }\n for (auto dep : groups.back()) {\n if (find(deps.begin(), deps.end(), dep.plugin->name()) != deps.end()) {\n skipUntilLater = true;\n break;\n }\n }\n if (!skipUntilLater) {\n groups.back().push_back({*p, false});\n p = plugins.erase(p);\n } else {\n ++p;\n }\n }\n\n \/\/ Check for dependency resolution failure\n if (plugins == lastLoop) {\n cerr << \"Unable to resolve all plugin dependencies. \"\n \"Plugins left to resolve:\" << endl << endl;\n for (auto* p : plugins) {\n cerr << p->name() << endl\n << \" Depends on:\" << endl;\n for (auto d : p->dependsOn())\n cerr << \" \" << d << endl;\n cerr << endl;\n }\n exit(1);\n }\n lastLoop = plugins;\n }\n return groups;\n };\n\n \/\/ We do not own all the memory in here. We only own the default prorgam\n vector<vector<PluginRuntimeInfo>> pluginGroups;\n pluginGroups = buildPluginGroups(plugins);\n if (pluginGroups.size() > 1) {\n cout << \"Identified \" << pluginGroups.size() << \" indexer plugin groups\" << endl\n << \"Running through log \" << pluginGroups.size()\n << \" times to satisfy dependencies\" << endl;\n }\n\n zcm::Json::Value index;\n\n size_t numEvents = 0;\n const zcm::LogEvent* evt;\n for (size_t i = 0; i < pluginGroups.size(); ++i) {\n if (pluginGroups.size() != 1) cout << \"Plugin group \" << (i + 1) << endl;\n off_t offset = 0;\n fseeko(log.getFilePtr(), 0, SEEK_SET);\n\n for (auto& p : pluginGroups[i])\n p.runThroughLog = p.plugin->setUp(index, index[p.plugin->name()], log);\n\n while (1) {\n offset = ftello(log.getFilePtr());\n\n static int lastPrintPercent = 0;\n int percent = (100.0 * offset \/ logSize) * 100;\n if (percent != lastPrintPercent) {\n cout << \"\\r\" << \"Percent Complete: \" << (percent \/ 100) << flush;\n lastPrintPercent = percent;\n }\n\n evt = log.readNextEvent();\n if (evt == nullptr) break;\n\n int64_t msg_hash;\n __int64_t_decode_array(evt->data, 0, 8, &msg_hash, 1);\n const TypeMetadata* md = types.getByHash(msg_hash);\n if (!md) continue;\n\n for (auto& p : pluginGroups[i]) {\n assert(p.plugin);\n\n if (!p.runThroughLog) continue;\n\n p.plugin->indexEvent(index, index[p.plugin->name()],\n evt->channel, md->name,\n offset, evt->timestamp,\n (uint64_t) msg_hash,\n evt->data, evt->datalen);\n\n numEvents++;\n }\n }\n\n cout << endl;\n\n for (auto& p : pluginGroups[i])\n p.plugin->tearDown(index, index[p.plugin->name()], log);\n }\n\n delete defaultPlugin;\n defaultPlugin = nullptr;\n\n zcm::Json::StreamWriterBuilder builder;\n builder[\"indentation\"] = args.readable ? \" \" : \"\";\n std::unique_ptr<zcm::Json::StreamWriter> writer(builder.newStreamWriter());\n writer->write(index, &output);\n output << endl;\n output.close();\n\n cout << \"Indexed \" << numEvents << \" events\" << endl;\n return 0;\n}\n<commit_msg>Now can force running of default<commit_after>#include <iostream>\n#include <fstream>\n#include <getopt.h>\n#include <algorithm>\n#include <memory>\n\n#include <zcm\/zcm-cpp.hpp>\n\n#include \"zcm\/json\/json.h\"\n\n#include \"zcm\/util\/TypeDb.hpp\"\n\n#include \"IndexerPluginDb.hpp\"\n\nusing namespace std;\n\nstruct Args\n{\n string logfile = \"\";\n string output = \"\";\n string plugin_path = \"\";\n string type_path = \"\";\n bool readable = false;\n bool debug = false;\n bool useDefault = false;\n\n bool parse(int argc, char *argv[])\n {\n \/\/ set some defaults\n const char *optstring = \"l:o:p:t:rdh\";\n struct option long_opts[] = {\n { \"log\", required_argument, 0, 'l' },\n { \"output\", required_argument, 0, 'o' },\n { \"plugin-path\", required_argument, 0, 'p' },\n { \"type-path\", required_argument, 0, 't' },\n { \"readable\", no_argument, 0, 'r' },\n { \"use-default\", no_argument, 0, 'd' },\n { \"debug\", no_argument, 0, 0 },\n { \"help\", no_argument, 0, 'h' },\n { 0, 0, 0, 0 }\n };\n\n int c;\n while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0) {\n switch (c) {\n case 'l': logfile = string(optarg); break;\n case 'o': output = string(optarg); break;\n case 'p': plugin_path = string(optarg); break;\n case 't': type_path = string(optarg); break;\n case 'r': readable = true; break;\n case 'd': useDefault = true; break;\n case 'h':\n default:\n if (string(argv[optind]) == \"debug\") {\n debug = true;\n } else return false;\n };\n }\n\n if (logfile == \"\") {\n cerr << \"Please specify logfile input\" << endl;\n return false;\n }\n\n if (output == \"\") {\n cerr << \"Please specify index file output\" << endl;\n return false;\n }\n\n const char* type_path_env = getenv(\"ZCM_LOG_INDEXER_ZCMTYPES_PATH\");\n if (type_path == \"\" && type_path_env) type_path = type_path_env;\n if (type_path == \"\") {\n cerr << \"Please specify a zcmtypes.so path either through -t TYPE_PATH \"\n \"or through the env var ZCM_LOG_INDEXER_ZCMTYPES_PATH\" << endl;\n return false;\n }\n\n const char* plugin_path_env = getenv(\"ZCM_LOG_INDEXER_PLUGINS_PATH\");\n if (plugin_path == \"\" && plugin_path_env) plugin_path = plugin_path_env;\n if (plugin_path == \"\") cerr << \"Running with default timestamp indexer plugin\" << endl;\n\n return true;\n }\n\n void usage()\n {\n cerr << \"usage: zcm-log-indexer [options]\" << endl\n << \"\" << endl\n << \" Load in a log file and write an index json file that\" << endl\n << \" allows for faster log indexing.\" << endl\n << \"\" << endl\n << \"Example:\" << endl\n << \" zcm-log-indexer -l zcm.log -o index.dbz -t path\/to\/zcmtypes.so\" << endl\n << \"\" << endl\n << \"Options:\" << endl\n << \"\" << endl\n << \" -h, --help Shows this help text and exits\" << endl\n << \" -l, --log=logfile Input log to index for fast querying\" << endl\n << \" -o, --output=indexfile Output index file to be used with log\" << endl\n << \" -p, --plugin-path=path Path to shared library containing indexer plugins\" << endl\n << \" Can also be specified via the environment variable\" << endl\n << \" ZCM_LOG_INDEXER_ZCMTYPES_PATH\" << endl\n << \" -t, --type-path=path Path to shared library containing the zcmtypes\" << endl\n << \" Can also be specified via the environment variable\" << endl\n << \" ZCM_LOG_INDEXER_PLUGINS_PATH\" << endl\n << \" -r, --readable Don't minify the output index file. \" << endl\n << \" Leave it human readable\" << endl\n << \" -d, --debug Run a dry run to ensure proper indexer setup\" << endl\n << endl << endl;\n }\n};\n\nint main(int argc, char* argv[])\n{\n Args args;\n if (!args.parse(argc, argv)) {\n args.usage();\n return 1;\n }\n\n zcm::LogFile log(args.logfile, \"r\");\n if (!log.good()) {\n cerr << \"Unable to open logfile: \" << args.logfile << endl;\n return 1;\n }\n fseeko(log.getFilePtr(), 0, SEEK_END);\n \/\/ XXX Look into handling large logfiles\n off_t logSize = ftello(log.getFilePtr());\n\n ofstream output;\n output.open(args.output);\n if (!output.is_open()) {\n cerr << \"Unable to open output file: \" << args.output << endl;\n log.close();\n return 1;\n }\n\n vector<zcm::IndexerPlugin*> plugins;\n\n bool defaultShouldBeIncluded = true;\n zcm::IndexerPlugin* defaultPlugin = new zcm::IndexerPlugin();\n\n IndexerPluginDb pluginDb(args.plugin_path, args.debug);\n \/\/ Load plugins from path if specified\n if (args.plugin_path != \"\") {\n bool dependsOnDefault = false;\n vector<const zcm::IndexerPlugin*> dbPlugins = pluginDb.getPlugins();\n \/\/ casting away constness. Don't mess up.\n for (auto dbp : dbPlugins) {\n plugins.push_back((zcm::IndexerPlugin*) dbp);\n defaultShouldBeIncluded = false;\n auto deps = dbp->dependsOn();\n for (auto dep : deps) {\n if (dep == defaultPlugin->name()) {\n dependsOnDefault = true;\n break;\n }\n }\n }\n\n if (dependsOnDefault || args.useDefault)\n defaultShouldBeIncluded = true;\n }\n\n if (defaultShouldBeIncluded) plugins.push_back(defaultPlugin);\n\n for (size_t i = 0; i < plugins.size(); ++i) {\n for (size_t j = i + 1; j < plugins.size(); ++j) {\n if (args.debug)\n cout << plugins.data()[i] << \"->name() == \"\n << plugins.data()[j] << \"->name()\" << endl;\n\n if (plugins[i]->name() == plugins[j]->name()) {\n cerr << \"Plugins must have unique names. Collision: \"\n << plugins[i]->name() << endl;\n return 1;\n }\n }\n }\n\n TypeDb types(args.type_path, args.debug);\n\n if (args.debug) return 0;\n\n struct PluginRuntimeInfo {\n zcm::IndexerPlugin* plugin;\n bool runThroughLog;\n };\n\n auto buildPluginGroups = [] (vector<zcm::IndexerPlugin*> plugins) {\n vector<vector<PluginRuntimeInfo>> groups;\n vector<zcm::IndexerPlugin*> lastLoop = plugins;\n while (!plugins.empty()) {\n groups.resize(groups.size() + 1);\n for (auto p = plugins.begin(); p != plugins.end();) {\n auto deps = (*p)->dependsOn();\n\n bool skipUntilLater = false;\n for (auto* dep : plugins) {\n if (find(deps.begin(), deps.end(), dep->name()) != deps.end()) {\n skipUntilLater = true;\n break;\n }\n }\n for (auto dep : groups.back()) {\n if (find(deps.begin(), deps.end(), dep.plugin->name()) != deps.end()) {\n skipUntilLater = true;\n break;\n }\n }\n if (!skipUntilLater) {\n groups.back().push_back({*p, false});\n p = plugins.erase(p);\n } else {\n ++p;\n }\n }\n\n \/\/ Check for dependency resolution failure\n if (plugins == lastLoop) {\n cerr << \"Unable to resolve all plugin dependencies. \"\n \"Plugins left to resolve:\" << endl << endl;\n for (auto* p : plugins) {\n cerr << p->name() << endl\n << \" Depends on:\" << endl;\n for (auto d : p->dependsOn())\n cerr << \" \" << d << endl;\n cerr << endl;\n }\n exit(1);\n }\n lastLoop = plugins;\n }\n return groups;\n };\n\n \/\/ We do not own all the memory in here. We only own the default prorgam\n vector<vector<PluginRuntimeInfo>> pluginGroups;\n pluginGroups = buildPluginGroups(plugins);\n if (pluginGroups.size() > 1) {\n cout << \"Identified \" << pluginGroups.size() << \" indexer plugin groups\" << endl\n << \"Running through log \" << pluginGroups.size()\n << \" times to satisfy dependencies\" << endl;\n }\n\n zcm::Json::Value index;\n\n size_t numEvents = 0;\n const zcm::LogEvent* evt;\n for (size_t i = 0; i < pluginGroups.size(); ++i) {\n if (pluginGroups.size() != 1) cout << \"Plugin group \" << (i + 1) << endl;\n off_t offset = 0;\n fseeko(log.getFilePtr(), 0, SEEK_SET);\n\n for (auto& p : pluginGroups[i])\n p.runThroughLog = p.plugin->setUp(index, index[p.plugin->name()], log);\n\n while (1) {\n offset = ftello(log.getFilePtr());\n\n static int lastPrintPercent = 0;\n int percent = (100.0 * offset \/ logSize) * 100;\n if (percent != lastPrintPercent) {\n cout << \"\\r\" << \"Percent Complete: \" << (percent \/ 100) << flush;\n lastPrintPercent = percent;\n }\n\n evt = log.readNextEvent();\n if (evt == nullptr) break;\n\n int64_t msg_hash;\n __int64_t_decode_array(evt->data, 0, 8, &msg_hash, 1);\n const TypeMetadata* md = types.getByHash(msg_hash);\n if (!md) continue;\n\n for (auto& p : pluginGroups[i]) {\n assert(p.plugin);\n\n if (!p.runThroughLog) continue;\n\n p.plugin->indexEvent(index, index[p.plugin->name()],\n evt->channel, md->name,\n offset, evt->timestamp,\n (uint64_t) msg_hash,\n evt->data, evt->datalen);\n\n numEvents++;\n }\n }\n\n cout << endl;\n\n for (auto& p : pluginGroups[i])\n p.plugin->tearDown(index, index[p.plugin->name()], log);\n }\n\n delete defaultPlugin;\n defaultPlugin = nullptr;\n\n zcm::Json::StreamWriterBuilder builder;\n builder[\"indentation\"] = args.readable ? \" \" : \"\";\n std::unique_ptr<zcm::Json::StreamWriter> writer(builder.newStreamWriter());\n writer->write(index, &output);\n output << endl;\n output.close();\n\n cout << \"Indexed \" << numEvents << \" events\" << endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdio>\n#include \"driver.hpp\"\n#include \"conv_driver.hpp\"\n#include \"pool_driver.hpp\"\n#include \"lrn_driver.hpp\"\n#include \"activ_driver.hpp\"\n#include \"softmax_driver.hpp\"\n#include \"gemm_driver.hpp\"\n\nint main(int argc, char *argv[]) {\n\n\tstd::string base_arg = ParseBaseArg(argc, argv);\n\n\tDriver *drv;\n\tif(base_arg == \"conv\") {\n\t\tdrv = new ConvDriver<float>();\n\t}\n\telse if(base_arg == \"pool\") {\n\t\tdrv = new PoolDriver<float>();\n\t}\n\telse if(base_arg == \"lrn\") {\n\t\tdrv = new LRNDriver<float>();\n\t}\n\telse if (base_arg == \"activ\") {\n\t\tdrv = new ActivationDriver<float>();\n\t}\n\telse if (base_arg == \"softmax\") {\n\t\tdrv = new SoftmaxDriver<float>();\n\t}\n#ifdef MLOPEN_USE_TINYGEMMM\n\telse if (base_arg == \"gemm\") {\n\t\tdrv = new GemmDriver<float>();\n\t}\n#endif\n\telse {\n\t\tprintf(\"Incorrect BaseArg\\n\");\n\t\texit(0);\n\t}\n\n\tdrv->AddCmdLineArgs();\n\tdrv->ParseCmdLineArgs(argc, argv);\n\tdrv->GetandSetData();\n\n\tdrv->AllocateBuffersAndCopy();\n\n\tdrv->RunForwardGPU();\n\n\tif(drv->GetInputFlags().GetValueInt(\"verify\") == 1) {\n\t\tif(base_arg == \"gemm\")\n\t\t\tprintf(\"GEMM verification done in the GEMM library\\n\");\n\t\telse\n\t\t\tdrv->VerifyForward();\n\t}\n\t\n\tif(drv->GetInputFlags().GetValueInt(\"forw\") == 0) {\n\t\tif(!(base_arg == \"gemm\")) {\n\t\t\tdrv->RunBackwardGPU();\n\t\t\tif(drv->GetInputFlags().GetValueInt(\"verify\") == 1) {\n\t\t\t\tdrv->VerifyBackward();\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n<commit_msg>Typo fix<commit_after>#include <iostream>\n#include <cstdio>\n#include \"driver.hpp\"\n#include \"conv_driver.hpp\"\n#include \"pool_driver.hpp\"\n#include \"lrn_driver.hpp\"\n#include \"activ_driver.hpp\"\n#include \"softmax_driver.hpp\"\n#include \"gemm_driver.hpp\"\n\nint main(int argc, char *argv[]) {\n\n\tstd::string base_arg = ParseBaseArg(argc, argv);\n\n\tDriver *drv;\n\tif(base_arg == \"conv\") {\n\t\tdrv = new ConvDriver<float>();\n\t}\n\telse if(base_arg == \"pool\") {\n\t\tdrv = new PoolDriver<float>();\n\t}\n\telse if(base_arg == \"lrn\") {\n\t\tdrv = new LRNDriver<float>();\n\t}\n\telse if (base_arg == \"activ\") {\n\t\tdrv = new ActivationDriver<float>();\n\t}\n\telse if (base_arg == \"softmax\") {\n\t\tdrv = new SoftmaxDriver<float>();\n\t}\n#ifdef MLOPEN_USE_TINYGEMM\n\telse if (base_arg == \"gemm\") {\n\t\tdrv = new GemmDriver<float>();\n\t}\n#endif\n\telse {\n\t\tprintf(\"Incorrect BaseArg\\n\");\n\t\texit(0);\n\t}\n\n\tdrv->AddCmdLineArgs();\n\tdrv->ParseCmdLineArgs(argc, argv);\n\tdrv->GetandSetData();\n\n\tdrv->AllocateBuffersAndCopy();\n\n\tdrv->RunForwardGPU();\n\n\tif(drv->GetInputFlags().GetValueInt(\"verify\") == 1) {\n\t\tif(base_arg == \"gemm\")\n\t\t\tprintf(\"GEMM verification done in the GEMM library\\n\");\n\t\telse\n\t\t\tdrv->VerifyForward();\n\t}\n\t\n\tif(drv->GetInputFlags().GetValueInt(\"forw\") == 0) {\n\t\tif(!(base_arg == \"gemm\")) {\n\t\t\tdrv->RunBackwardGPU();\n\t\t\tif(drv->GetInputFlags().GetValueInt(\"verify\") == 1) {\n\t\t\t\tdrv->VerifyBackward();\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2013 CompleteDB LLC.\r\n *\r\n * This program is free software: you can redistribute it and\/or modify\r\n * it under the terms of the GNU Affero General Public License as\r\n * published by the Free Software Foundation, either version 3 of the\r\n * License, or (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with PubSubSQL. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n *\/\r\n\r\n#include <iostream>\r\n#include <thread>\r\n#include \"process.h\"\r\n#include \"eventlog.h\"\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\t\/*\r\n\tpipe testPipe;\r\n\tif (!testPipe.ok()) {\r\n\t\tstd::cerr << \"pipe failed\" << std::endl;\r\n\t}\r\n\t\/\/\r\n\tstd::thread t([&]() {\r\n\t\tstd::cout<< testPipe.readLine();\r\n\t});\r\n\ttestPipe.writeLine(\"pipe test\");\r\n\tt.join();\r\n\t\/\/ test filepath\r\n\tstd::cout << eventlog::getPath() << std::endl;\r\n\t*\/\r\n\teventlog::install(\"pubsubsqlsvc.exe\", \"pubsubsql\");\r\n\t\/*\r\n\teventlog log(\"pubsubsql\");\r\n\tlog.logdebug(\"debug\");\r\n\tlog.loginfo(\"info\");\r\n\tlog.logwarn(\"warn\");\r\n\tlog.logerror(\"error\");\r\n\t*\/\r\n\t\/\/ test process redirection\r\n\tprocess pubsubsql;\r\n\tif (pubsubsql.start(\"C:\\\\Users\\\\Oleg\\\\Go\\\\src\\\\pubsubsql\\\\pubsubsql.exe\")) {\r\n\t\tint i = 0;\r\n\t\tstd::cin >> i;\r\n\t\tpubsubsql.stop();\r\n\t\tpubsubsql.wait(3000);\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n<commit_msg>wnidows service backup current progress<commit_after>\/* Copyright (C) 2013 CompleteDB LLC.\r\n *\r\n * This program is free software: you can redistribute it and\/or modify\r\n * it under the terms of the GNU Affero General Public License as\r\n * published by the Free Software Foundation, either version 3 of the\r\n * License, or (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with PubSubSQL. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n *\/\r\n\r\n#include <iostream>\r\n#include <thread>\r\n#include \"process.h\"\r\n#include \"eventlog.h\"\r\n\r\nint install(const std::string& options);\r\nint uninstall();\r\nint runAsService();\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\t\/\/ validate command line input\r\n\tstd::string usage = \"valid commands [install, uninstall]\";\r\n\tif (argc < 2) {\r\n\t\tstd::cerr << \"no command found: \" << usage << std::endl;\r\n\t\treturn EXIT_FAILURE;\r\n\t}\r\n\t\/\/ assemble options\r\n\tstd::string options;\r\n\tfor (int i = 2; i < argc; i++) {\r\n\t\tchar* arg = argv[i];\r\n\t\toptions.append(\" \");\r\n\t\toptions.append(arg);\r\n\t}\r\n\tstd::cout << options << std::endl;\r\n\t\/\/ execute\r\n\tstd::string command(argv[1]);\r\n\tif (command == \"install\") return install();\r\n\telse if (command == \"uninstall\") return uninstall();\r\n\telse if (command == \"svc\") return runAsService();\r\n\t\/\/ invalid command\r\n\tstd::cerr << \"invalid command: \" << usage << std::endl;\r\n\treturn EXIT_FAILURE;\r\n\r\n\r\n\t\/*\r\n\tpipe testPipe;\r\n\tif (!testPipe.ok()) {\r\n\t\tstd::cerr << \"pipe failed\" << std::endl;\r\n\t}\r\n\t\/\/\r\n\tstd::thread t([&]() {\r\n\t\tstd::cout<< testPipe.readLine();\r\n\t});\r\n\ttestPipe.writeLine(\"pipe test\");\r\n\tt.join();\r\n\t\/\/ test filepath\r\n\tstd::cout << eventlog::getPath() << std::endl;\r\n\t*\/\r\n\t\/\/eventlog::install(\"pubsubsqlsvc.exe\", \"pubsubsql\");\r\n\t\/*\r\n\teventlog log(\"pubsubsql\");\r\n\tlog.logdebug(\"debug\");\r\n\tlog.loginfo(\"info\");\r\n\tlog.logwarn(\"warn\");\r\n\tlog.logerror(\"error\");\r\n\t*\/\r\n\t\/\/ test process redirection\r\n\r\n\t\/*\r\n\tprocess pubsubsql;\r\n\tif (pubsubsql.start(\"C:\\\\Users\\\\Oleg\\\\Go\\\\src\\\\pubsubsql\\\\pubsubsql.exe\")) {\r\n\t\tint i = 0;\r\n\t\tstd::cin >> i;\r\n\t\tpubsubsql.stop();\r\n\t\tpubsubsql.wait(3000);\r\n\t}\r\n\t*\/\r\n\treturn 0;\r\n}\r\n\r\nint install(const std::string& options) {\r\n\tint ret = EXIT_SUCCESS;\r\n\tSC_HANDLE manager = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CREATE_SERVICE);\r\n\tif (NULL == manager) {\r\n\t\tstd::cerr << \"failed to connect to service control manager\" << std::endl;\r\n\t\treturn EXIT_FAILURE;\r\n\t}\r\n\r\n\tstd::string servicePath;\r\n\tSC_HANDLE service = CreateService(manager, \"PubSubSQL Service\", \"PubSubSQL Service\", SERVICE_START | SERVICE_STOP | DELETE,\r\n\t\tSERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, servicePath.c_str(),\r\n\t\tNULL, NULL, NULL, NULL, NULL);\r\n\t\r\n\treturn EXIT_SUCCESS;\r\n}\r\n\r\nint uninstall() {\r\n\treturn EXIT_SUCCESS;\r\n}\r\n\r\nint runAsService() {\r\n\treturn EXIT_SUCCESS;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 BVLC and contributors.\n\n#include <stdio.h> \/\/ for snprintf\n#include <cuda_runtime.h>\n#include <google\/protobuf\/text_format.h>\n#include <leveldb\/db.h>\n#include <leveldb\/write_batch.h>\n#include <boost\/algorithm\/string.hpp>\n#include <string>\n#include <vector>\n\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/net.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/proto\/caffe.pb.h\"\n#include \"caffe\/util\/io.hpp\"\n\nusing namespace caffe; \/\/ NOLINT(build\/namespaces)\n\ntemplate<typename Dtype>\nint feature_extraction_pipeline(int argc, char** argv);\n\nint main(int argc, char** argv) {\n return feature_extraction_pipeline<float>(argc, argv);\n\/\/ return feature_extraction_pipeline<double>(argc, argv);\n}\n\ntemplate<typename Dtype>\nint feature_extraction_pipeline(int argc, char** argv) {\n const int num_required_args = 6;\n if (argc < num_required_args) {\n LOG(ERROR)<<\n \"This program takes in a trained network and an input data layer, and then\"\n \" extract features of the input data produced by the net.\\n\"\n \"Usage: extract_features pretrained_net_param\"\n \" feature_extraction_proto_file extract_feature_blob_name1[,name2,...]\"\n \" save_feature_leveldb_name1[,name2,...] num_mini_batches [CPU\/GPU]\"\n \" [DEVICE_ID=0]\\n\"\n \"Note: you can extract multiple features in one pass by specifying\"\n \" multiple feature blob names and leveldb names seperated by ','.\"\n \" The names cannot contain white space characters and the number of blobs\"\n \" and leveldbs must be equal.\";\n return 1;\n }\n int arg_pos = num_required_args;\n\n arg_pos = num_required_args;\n if (argc > arg_pos && strcmp(argv[arg_pos], \"GPU\") == 0) {\n LOG(ERROR)<< \"Using GPU\";\n uint device_id = 0;\n if (argc > arg_pos + 1) {\n device_id = atoi(argv[arg_pos + 1]);\n CHECK_GE(device_id, 0);\n }\n LOG(ERROR) << \"Using Device_id=\" << device_id;\n Caffe::SetDevice(device_id);\n Caffe::set_mode(Caffe::GPU);\n } else {\n LOG(ERROR) << \"Using CPU\";\n Caffe::set_mode(Caffe::CPU);\n }\n Caffe::set_phase(Caffe::TEST);\n\n arg_pos = 0; \/\/ the name of the executable\n string pretrained_binary_proto(argv[++arg_pos]);\n\n \/\/ Expected prototxt contains at least one data layer such as\n \/\/ the layer data_layer_name and one feature blob such as the\n \/\/ fc7 top blob to extract features.\n \/*\n layers {\n name: \"data_layer_name\"\n type: DATA\n data_param {\n source: \"\/path\/to\/your\/images\/to\/extract\/feature\/images_leveldb\"\n mean_file: \"\/path\/to\/your\/image_mean.binaryproto\"\n batch_size: 128\n crop_size: 227\n mirror: false\n }\n top: \"data_blob_name\"\n top: \"label_blob_name\"\n }\n layers {\n name: \"drop7\"\n type: DROPOUT\n dropout_param {\n dropout_ratio: 0.5\n }\n bottom: \"fc7\"\n top: \"fc7\"\n }\n *\/\n string feature_extraction_proto(argv[++arg_pos]);\n shared_ptr<Net<Dtype> > feature_extraction_net(\n new Net<Dtype>(feature_extraction_proto));\n feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);\n\n string extract_feature_blob_names(argv[++arg_pos]);\n vector<string> blob_names;\n boost::split(blob_names, extract_feature_blob_names, boost::is_any_of(\",\"));\n\n string save_feature_leveldb_names(argv[++arg_pos]);\n vector<string> leveldb_names;\n boost::split(leveldb_names, save_feature_leveldb_names,\n boost::is_any_of(\",\"));\n CHECK_EQ(blob_names.size(), leveldb_names.size()) <<\n \" the number of blob names and leveldb names must be equal\";\n size_t num_features = blob_names.size();\n\n for (size_t i = 0; i < num_features; i++) {\n CHECK(feature_extraction_net->has_blob(blob_names[i]))\n << \"Unknown feature blob name \" << blob_names[i]\n << \" in the network \" << feature_extraction_proto;\n }\n\n leveldb::Options options;\n options.error_if_exists = true;\n options.create_if_missing = true;\n options.write_buffer_size = 268435456;\n vector<shared_ptr<leveldb::DB> > feature_dbs;\n for (size_t i = 0; i < num_features; ++i) {\n LOG(INFO)<< \"Opening leveldb \" << leveldb_names[i];\n leveldb::DB* db;\n leveldb::Status status = leveldb::DB::Open(options,\n leveldb_names[i].c_str(),\n &db);\n CHECK(status.ok()) << \"Failed to open leveldb \" << leveldb_names[i];\n feature_dbs.push_back(shared_ptr<leveldb::DB>(db));\n }\n\n int num_mini_batches = atoi(argv[++arg_pos]);\n\n LOG(ERROR)<< \"Extacting Features\";\n\n Datum datum;\n vector<shared_ptr<leveldb::WriteBatch> > feature_batches(\n num_features,\n shared_ptr<leveldb::WriteBatch>(new leveldb::WriteBatch()));\n const int kMaxKeyStrLength = 100;\n char key_str[kMaxKeyStrLength];\n int num_bytes_of_binary_code = sizeof(Dtype);\n vector<Blob<float>*> input_vec;\n vector<int> image_indices(num_features, 0);\n for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {\n feature_extraction_net->Forward(input_vec);\n for (int i = 0; i < num_features; ++i) {\n const shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net\n ->blob_by_name(blob_names[i]);\n int batch_size = feature_blob->num();\n int dim_features = feature_blob->count() \/ batch_size;\n Dtype* feature_blob_data;\n for (int n = 0; n < batch_size; ++n) {\n datum.set_height(dim_features);\n datum.set_width(1);\n datum.set_channels(1);\n datum.clear_data();\n datum.clear_float_data();\n feature_blob_data = feature_blob->mutable_cpu_data() +\n feature_blob->offset(n);\n for (int d = 0; d < dim_features; ++d) {\n datum.add_float_data(feature_blob_data[d]);\n }\n string value;\n datum.SerializeToString(&value);\n snprintf(key_str, kMaxKeyStrLength, \"%d\", image_indices[i]);\n feature_batches[i]->Put(string(key_str), value);\n ++image_indices[i];\n if (image_indices[i] % 1000 == 0) {\n feature_dbs[i]->Write(leveldb::WriteOptions(),\n feature_batches[i].get());\n LOG(ERROR)<< \"Extracted features of \" << image_indices[i] <<\n \" query images for feature blob \" << blob_names[i];\n feature_batches[i].reset(new leveldb::WriteBatch());\n }\n } \/\/ for (int n = 0; n < batch_size; ++n)\n } \/\/ for (int i = 0; i < num_features; ++i)\n } \/\/ for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)\n \/\/ write the last batch\n for (int i = 0; i < num_features; ++i) {\n if (image_indices[i] % 1000 != 0) {\n feature_dbs[i]->Write(leveldb::WriteOptions(), feature_batches[i].get());\n }\n LOG(ERROR)<< \"Extracted features of \" << image_indices[i] <<\n \" query images for feature blob \" << blob_names[i];\n }\n\n LOG(ERROR)<< \"Successfully extracted the features!\";\n return 0;\n}\n\n<commit_msg>Init google logging<commit_after>\/\/ Copyright 2014 BVLC and contributors.\n\n#include <stdio.h> \/\/ for snprintf\n#include <cuda_runtime.h>\n#include <google\/protobuf\/text_format.h>\n#include <leveldb\/db.h>\n#include <leveldb\/write_batch.h>\n#include <boost\/algorithm\/string.hpp>\n#include <string>\n#include <vector>\n\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/net.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/proto\/caffe.pb.h\"\n#include \"caffe\/util\/io.hpp\"\n\nusing namespace caffe; \/\/ NOLINT(build\/namespaces)\n\ntemplate<typename Dtype>\nint feature_extraction_pipeline(int argc, char** argv);\n\nint main(int argc, char** argv) {\n return feature_extraction_pipeline<float>(argc, argv);\n\/\/ return feature_extraction_pipeline<double>(argc, argv);\n}\n\ntemplate<typename Dtype>\nint feature_extraction_pipeline(int argc, char** argv) {\n ::google::InitGoogleLogging(argv[0]);\n const int num_required_args = 6;\n if (argc < num_required_args) {\n LOG(ERROR)<<\n \"This program takes in a trained network and an input data layer, and then\"\n \" extract features of the input data produced by the net.\\n\"\n \"Usage: extract_features pretrained_net_param\"\n \" feature_extraction_proto_file extract_feature_blob_name1[,name2,...]\"\n \" save_feature_leveldb_name1[,name2,...] num_mini_batches [CPU\/GPU]\"\n \" [DEVICE_ID=0]\\n\"\n \"Note: you can extract multiple features in one pass by specifying\"\n \" multiple feature blob names and leveldb names seperated by ','.\"\n \" The names cannot contain white space characters and the number of blobs\"\n \" and leveldbs must be equal.\";\n return 1;\n }\n int arg_pos = num_required_args;\n\n arg_pos = num_required_args;\n if (argc > arg_pos && strcmp(argv[arg_pos], \"GPU\") == 0) {\n LOG(ERROR)<< \"Using GPU\";\n uint device_id = 0;\n if (argc > arg_pos + 1) {\n device_id = atoi(argv[arg_pos + 1]);\n CHECK_GE(device_id, 0);\n }\n LOG(ERROR) << \"Using Device_id=\" << device_id;\n Caffe::SetDevice(device_id);\n Caffe::set_mode(Caffe::GPU);\n } else {\n LOG(ERROR) << \"Using CPU\";\n Caffe::set_mode(Caffe::CPU);\n }\n Caffe::set_phase(Caffe::TEST);\n\n arg_pos = 0; \/\/ the name of the executable\n string pretrained_binary_proto(argv[++arg_pos]);\n\n \/\/ Expected prototxt contains at least one data layer such as\n \/\/ the layer data_layer_name and one feature blob such as the\n \/\/ fc7 top blob to extract features.\n \/*\n layers {\n name: \"data_layer_name\"\n type: DATA\n data_param {\n source: \"\/path\/to\/your\/images\/to\/extract\/feature\/images_leveldb\"\n mean_file: \"\/path\/to\/your\/image_mean.binaryproto\"\n batch_size: 128\n crop_size: 227\n mirror: false\n }\n top: \"data_blob_name\"\n top: \"label_blob_name\"\n }\n layers {\n name: \"drop7\"\n type: DROPOUT\n dropout_param {\n dropout_ratio: 0.5\n }\n bottom: \"fc7\"\n top: \"fc7\"\n }\n *\/\n string feature_extraction_proto(argv[++arg_pos]);\n shared_ptr<Net<Dtype> > feature_extraction_net(\n new Net<Dtype>(feature_extraction_proto));\n feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);\n\n string extract_feature_blob_names(argv[++arg_pos]);\n vector<string> blob_names;\n boost::split(blob_names, extract_feature_blob_names, boost::is_any_of(\",\"));\n\n string save_feature_leveldb_names(argv[++arg_pos]);\n vector<string> leveldb_names;\n boost::split(leveldb_names, save_feature_leveldb_names,\n boost::is_any_of(\",\"));\n CHECK_EQ(blob_names.size(), leveldb_names.size()) <<\n \" the number of blob names and leveldb names must be equal\";\n size_t num_features = blob_names.size();\n\n for (size_t i = 0; i < num_features; i++) {\n CHECK(feature_extraction_net->has_blob(blob_names[i]))\n << \"Unknown feature blob name \" << blob_names[i]\n << \" in the network \" << feature_extraction_proto;\n }\n\n leveldb::Options options;\n options.error_if_exists = true;\n options.create_if_missing = true;\n options.write_buffer_size = 268435456;\n vector<shared_ptr<leveldb::DB> > feature_dbs;\n for (size_t i = 0; i < num_features; ++i) {\n LOG(INFO)<< \"Opening leveldb \" << leveldb_names[i];\n leveldb::DB* db;\n leveldb::Status status = leveldb::DB::Open(options,\n leveldb_names[i].c_str(),\n &db);\n CHECK(status.ok()) << \"Failed to open leveldb \" << leveldb_names[i];\n feature_dbs.push_back(shared_ptr<leveldb::DB>(db));\n }\n\n int num_mini_batches = atoi(argv[++arg_pos]);\n\n LOG(ERROR)<< \"Extacting Features\";\n\n Datum datum;\n vector<shared_ptr<leveldb::WriteBatch> > feature_batches(\n num_features,\n shared_ptr<leveldb::WriteBatch>(new leveldb::WriteBatch()));\n const int kMaxKeyStrLength = 100;\n char key_str[kMaxKeyStrLength];\n int num_bytes_of_binary_code = sizeof(Dtype);\n vector<Blob<float>*> input_vec;\n vector<int> image_indices(num_features, 0);\n for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {\n feature_extraction_net->Forward(input_vec);\n for (int i = 0; i < num_features; ++i) {\n const shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net\n ->blob_by_name(blob_names[i]);\n int batch_size = feature_blob->num();\n int dim_features = feature_blob->count() \/ batch_size;\n Dtype* feature_blob_data;\n for (int n = 0; n < batch_size; ++n) {\n datum.set_height(dim_features);\n datum.set_width(1);\n datum.set_channels(1);\n datum.clear_data();\n datum.clear_float_data();\n feature_blob_data = feature_blob->mutable_cpu_data() +\n feature_blob->offset(n);\n for (int d = 0; d < dim_features; ++d) {\n datum.add_float_data(feature_blob_data[d]);\n }\n string value;\n datum.SerializeToString(&value);\n snprintf(key_str, kMaxKeyStrLength, \"%d\", image_indices[i]);\n feature_batches[i]->Put(string(key_str), value);\n ++image_indices[i];\n if (image_indices[i] % 1000 == 0) {\n feature_dbs[i]->Write(leveldb::WriteOptions(),\n feature_batches[i].get());\n LOG(ERROR)<< \"Extracted features of \" << image_indices[i] <<\n \" query images for feature blob \" << blob_names[i];\n feature_batches[i].reset(new leveldb::WriteBatch());\n }\n } \/\/ for (int n = 0; n < batch_size; ++n)\n } \/\/ for (int i = 0; i < num_features; ++i)\n } \/\/ for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)\n \/\/ write the last batch\n for (int i = 0; i < num_features; ++i) {\n if (image_indices[i] % 1000 != 0) {\n feature_dbs[i]->Write(leveldb::WriteOptions(), feature_batches[i].get());\n }\n LOG(ERROR)<< \"Extracted features of \" << image_indices[i] <<\n \" query images for feature blob \" << blob_names[i];\n }\n\n LOG(ERROR)<< \"Successfully extracted the features!\";\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"AlembicLicensing.h\"\n#include \"AlembicWriteJob.h\"\n#include \"AlembicObject.h\"\n#include \"AlembicXform.h\"\n#include \"AlembicCamera.h\"\n#include \"AlembicPolyMsh.h\"\n#include \"AlembicCurves.h\"\n#include \"AlembicPoints.h\"\n#include \"AlembicModel.h\"\n#include \"AlembicSubD.h\"\n#include \"AlembicNurbs.h\"\n#include \"Utility.h\"\n\n#include <xsi_application.h>\n#include <xsi_time.h>\n#include <xsi_project.h>\n#include <xsi_scene.h>\n#include <xsi_property.h>\n#include <xsi_parameter.h>\n#include <xsi_x3dobject.h>\n#include <xsi_primitive.h>\n#include <xsi_kinematics.h>\n#include <xsi_kinematicstate.h>\n#include <xsi_uitoolkit.h>\n#include <xsi_geometry.h>\n#include <xsi_iceattribute.h>\n#include <xsi_model.h>\n#include <xsi_utils.h>\n\n#include \"sceneGraph.h\"\n\nusing namespace XSI;\nusing namespace MATH;\n\nnamespace AbcA = ::Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS;\nusing namespace AbcA;\n\nAlembicWriteJob::AlembicWriteJob\n(\n const CString & in_FileName,\n const exoNode::SelectionMap& in_Selection,\n const CDoubleArray & in_Frames\n)\n{\n \/\/ ensure to clear the isRefAnimated cache\n clearIsRefAnimatedCache();\n\n mFileName = CUtils::ResolveTokenString(in_FileName,XSI::CTime(),false);\n mSelection = in_Selection;\n\n for(LONG i=0;i<in_Frames.GetCount();i++)\n mFrames.push_back(in_Frames[i]);\n}\n\nAlembicWriteJob::~AlembicWriteJob()\n{\n}\n\nvoid AlembicWriteJob::SetOption(const CString & in_Name, const CValue & in_Value)\n{\n std::map<XSI::CString,XSI::CValue>::iterator it = mOptions.find(in_Name);\n if(it == mOptions.end())\n mOptions.insert(std::pair<XSI::CString,XSI::CValue>(in_Name,in_Value));\n else\n it->second = in_Value;\n}\n\nbool AlembicWriteJob::HasOption(const CString & in_Name)\n{\n std::map<XSI::CString,XSI::CValue>::iterator it = mOptions.find(in_Name);\n return it != mOptions.end();\n}\n\nCValue AlembicWriteJob::GetOption(const CString & in_Name)\n{\n std::map<XSI::CString,XSI::CValue>::iterator it = mOptions.find(in_Name);\n if(it != mOptions.end())\n return it->second;\n return CValue(false);\n}\n\n\/\/AlembicObjectPtr AlembicWriteJob::GetObject(const XSI::CRef & in_Ref)\n\/\/{\n\/\/ \tstd::string key = std::string( in_Ref.GetAsText().GetAsciiString() );\n\/\/\n\/\/\tstd::map<std::string,AlembicObjectPtr>::const_iterator it = mObjectsNames.find( key );\n\/\/\n\/\/\tif (it != mObjectsNames.end()) {\n\/\/\t\treturn it->second;\n\/\/\t}\n\/\/\treturn AlembicObjectPtr();\n\/\/}\n\nbool AlembicWriteJob::AddObject(AlembicObjectPtr in_Obj)\n{\n if(!in_Obj)\n return false;\n if(!in_Obj->GetRef().IsValid())\n return false;\n mObjects.push_back(in_Obj);\n return true;\n}\n\n\nCStatus AlembicWriteJob::PreProcess()\n{\n \/\/ check filenames\n if(mFileName.IsEmpty())\n {\n Application().LogMessage(L\"[ExocortexAlembic] No filename specified.\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n \/\/ check objects\n if(mSelection.size() == 0)\n {\n Application().LogMessage(L\"[ExocortexAlembic] No objects specified.\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n \/\/ check frames\n if(mFrames.size() == 0)\n {\n Application().LogMessage(L\"[ExocortexAlembic] No frames specified.\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n \/\/ check if the file is currently in use\n if(getRefArchive(mFileName) > 0)\n {\n Application().LogMessage(L\"[ExocortexAlembic] Error writing to file '\"+mFileName+L\"'. File currently in use.\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n \/\/ init archive (use a locally scoped archive)\n CString sceneFileName = L\"Exported from: \"+Application().GetActiveProject().GetActiveScene().GetParameterValue(L\"FileName\").GetAsText();\n try\n {\n mArchive = CreateArchiveWithInfo(\n Alembic::AbcCoreHDF5::WriteArchive(),\n mFileName.GetAsciiString(),\n \"Softimage Alembic Plugin\",\n sceneFileName.GetAsciiString(),\n Alembic::Abc::ErrorHandler::kThrowPolicy);\n }\n catch(Alembic::Util::Exception& e)\n {\n CString exc(e.what());\n Application().LogMessage(L\"[ExocortexAlembic] Error writing to file '\"+mFileName+L\"' (\"+exc+L\"). Do you still have it opened?\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n mTop = mArchive.getTop();\n\n \/\/ get the frame rate\n mFrameRate = 25.0;\n CValue returnVal;\n CValueArray args(1);\n args[0] = L\"PlayControl.Rate\";\n Application().ExecuteCommand(L\"GetValue\",args,returnVal);\n mFrameRate = returnVal;\n if(mFrameRate == 0.0)\n mFrameRate = 25.0;\n\n std::vector<Alembic::AbcCoreAbstract::chrono_t> frames;\n for(LONG i=0;i<mFrames.size();i++)\n frames.push_back(mFrames[i] \/ mFrameRate);\n\n \/\/ create the sampling\n double timePerSample = 1.0 \/ mFrameRate;\n if(frames.size() > 1)\n {\n if( ! HasAlembicWriterLicense() )\n {\n if(frames.size() > 75)\n {\n frames.resize(75);\n EC_LOG_WARNING(\"[ExocortexAlembic] Writer license not found: Maximum exportable samplecount is 75!\");\n }\n }\n\n double timePerCycle = frames[frames.size()-1] - frames[0];\n AbcA::TimeSamplingType samplingType((uint32_t)frames.size(),timePerCycle);\n AbcA::TimeSampling sampling(samplingType,frames);\n mTs = mArchive.addTimeSampling(sampling);\n }\n else\n {\n AbcA::TimeSampling sampling(1.0,frames[0]);\n mTs = mArchive.addTimeSampling(sampling);\n }\n\n const bool bSelectParents = true;\n const bool bSelectChildren = true;\n const bool bTransformCache = (bool)GetOption(L\"transformCache\");\n const bool bFlattenHierarchy = (bool)GetOption(L\"flattenHierarchy\");\n\n \/\/TODO: eventually this should be a replaced with an equivalent virtual method, and the exporter will be shared\n exoNodePtr exoSceneRoot = buildCommonSceneGraph(Application().GetActiveSceneRoot());\n \n selectNodes(exoSceneRoot, mSelection, bSelectParents, bSelectChildren, bTransformCache ? false : bFlattenHierarchy, bTransformCache);\n\n ::printSceneGraph(exoSceneRoot);\n\n return CStatus::OK;\n\n struct stackElement\n {\n exoNodePtr eNode;\n Alembic::Abc::OObject oParent;\n\n stackElement(exoNodePtr enode, Alembic::Abc::OObject parent):eNode(enode), oParent(parent)\n {}\n };\n std::list<stackElement> sceneStack;\n \n sceneStack.push_back(stackElement(exoSceneRoot, GetTop()));\n\n while( !sceneStack.empty() )\n {\n\n stackElement sElement = sceneStack.back();\n exoNodePtr eNode = sElement.eNode;\n sceneStack.pop_back();\n \n Alembic::Abc::OObject oParent = sElement.oParent;\n Alembic::Abc::OObject oNewParent;\n\n AlembicObjectPtr pNewObject;\n\n if(eNode->selected)\n {\n if(eNode->type == exoNode::SCENE_ROOT){\n \/\/we do not want to export the Scene_Root (the alembic archive has one already)\n }\n else if(eNode->type == exoNode::ITRANSFORM || eNode->type == exoNode::ETRANSFORM){\n pNewObject.reset(new AlembicModel(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::CAMERA){\n pNewObject.reset(new AlembicCamera(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::POLYMESH){\n pNewObject.reset(new AlembicPolyMesh(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::SUBD){\n pNewObject.reset(new AlembicSubD(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::SURFACE){\n pNewObject.reset(new AlembicNurbs(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::CURVES){\n pNewObject.reset(new AlembicCurves(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::PARTICLES){\n pNewObject.reset(new AlembicPoints(eNode, this, oParent));\n }\n else{\n ESS_LOG_WARNING(\"Unknown type: not exporting \"<<eNode->name);\/\/Export as transform, and give warning?\n }\n }\n\n if(pNewObject){\n\n \/\/setup the next parent\n oNewParent = oParent.getChild(eNode->name);\n \n \/\/add the alembic object to the export list\n AddObject(pNewObject);\n }\n else{\n \/\/if we skip node A, we parent node A's children to the parent of A\n oNewParent = oParent;\n }\n\n if(oNewParent.valid()){\n for( std::list<exoNodePtr>::iterator it = eNode->children.begin(); it != eNode->children.end(); it++){\n sceneStack.push_back(stackElement(*it, oNewParent));\n }\n }\n else{\n ESS_LOG_ERROR(\"Do not have refernce to parent.\");\n return CStatus::Fail;\n }\n }\n\n\n#if 0\n\n for(LONG i=0; i<mSelection.size(); i++)\n {\n mSelection[i].nNodeDepth = getNodeDepthFromRef(mSelection[i].cRef);\n }\n std::sort(mSelection.begin(), mSelection.end());\n\n Alembic::Abc::OBox3dProperty boxProp = Alembic::AbcGeom::CreateOArchiveBounds(mArchive,mTs);\n\n CString activeSceneRoot_GetFullName = Application().GetActiveSceneRoot().GetFullName();\n \/\/ create object for each\n for(LONG i=0;i<mSelection.size();i++)\n {\n\t X3DObject xObj(mSelection[i].cRef);\n\t CRef xObj_GetActivePrimitive_GetRef = xObj.GetActivePrimitive().GetRef();\n \/\/if(GetObject(xObj_GetActivePrimitive_GetRef) != NULL) continue;\n\n \/\/ push all models up the hierarchy\n\t \n\t \/\/ MHahn: we are going to disable this code for now, since it should probably be an additional \n\t \/\/ export option, and we would prefer not to make things more complicated. We we will require\n\t \/\/ the user select the exact set of nodes that should be exported.\n\n \/\/Model model(xObj.GetRef());\n \/\/if(!model.IsValid())\n \/\/ model = xObj.GetModel();\n CRefArray modelRefs;\n \/\/if((bool)GetOption(L\"transformCache\"))\n if((bool)GetOption(L\"flattenHierarchy\") == false)\n {\n X3DObject parent = xObj.GetParent3DObject();\n while(parent.IsValid() && !parent.GetFullName().IsEqualNoCase( activeSceneRoot_GetFullName ))\n {\n modelRefs.Add(parent.GetActivePrimitive().GetRef());\n parent = parent.GetParent3DObject();\n }\n }\n \/\/else\n \/\/{\n \/\/ while(model.IsValid() && !model.GetFullName().IsEqualNoCase( activeSceneRoot_GetFullName ))\n \/\/ {\n \/\/ modelRefs.Add(model.GetActivePrimitive().GetRef());\n \/\/ model = model.GetModel();\n \/\/ }\n \/\/}\n for(LONG j=modelRefs.GetCount()-1;j>=0;j--)\n {\n \/\/if(GetObject(modelRefs[j]) == NULL)\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicModel(modelRefs[j],this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n }\n\n \n if((bool)GetOption(L\"transformCache\"))\n {\n \/\/always export all transforms whether the hierarchy is flattened or not\n\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicModel(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n\n continue;\/\/ only do models (tranforms) if we perform pure transformcache\n }\n\n \/\/ take care of all other types\n\t CString xObj_GetType = xObj.GetType();\n if(xObj_GetType.IsEqualNoCase(L\"null\") && ((bool)GetOption(L\"flattenHierarchy\") == false))\n\t {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicModel(xObj_GetActivePrimitive_GetRef, this));\n \/\/AddObjectIfDoesNotExist(ptr);\n\t }\n else if(xObj_GetType.IsEqualNoCase(L\"camera\"))\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicCamera(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else if(xObj_GetType.IsEqualNoCase(L\"polymsh\"))\n {\n Property geomProp;\n xObj.GetPropertyFromName(L\"geomapprox\",geomProp);\n LONG subDivLevel = geomProp.GetParameterValue(L\"gapproxmordrsl\");\n if(subDivLevel > 0)\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicSubD(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicPolyMesh(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n }\n else if(xObj_GetType.IsEqualNoCase(L\"surfmsh\"))\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicNurbs(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else if(xObj_GetType.IsEqualNoCase(L\"crvlist\"))\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicCurves(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else if(xObj_GetType.IsEqualNoCase(L\"hair\"))\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicCurves(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else if(xObj_GetType.IsEqualNoCase(L\"pointcloud\"))\n {\n AlembicObjectPtr ptr;\n ICEAttribute strandPosition = xObj.GetActivePrimitive().GetGeometry().GetICEAttributeFromName(L\"StrandPosition\");\n if(strandPosition.IsDefined() && strandPosition.IsValid())\n ptr.reset(new AlembicCurves(xObj_GetActivePrimitive_GetRef,this));\n else\n ptr.reset(new AlembicPoints(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n }\n\n#endif\n\n return CStatus::OK;\n}\n\nCStatus AlembicWriteJob::Process(double frame)\n{\n CStatus result = CStatus::False;\n\n for(size_t i=0;i<mFrames.size();i++)\n {\n \/\/ compare the frames\n if(abs(mFrames[i] - frame) > 0.001)\n continue;\n\n \/\/ run the export for all objects\n for(size_t j=0;j<mObjects.size();j++)\n {\n CStatus status = mObjects[j]->Save(mFrames[i]);\n if(status != CStatus::OK)\n return status;\n result = CStatus::OK;\n }\n }\n\n return result;\n}<commit_msg>issue #164<commit_after>#include \"AlembicLicensing.h\"\n#include \"AlembicWriteJob.h\"\n#include \"AlembicObject.h\"\n#include \"AlembicXform.h\"\n#include \"AlembicCamera.h\"\n#include \"AlembicPolyMsh.h\"\n#include \"AlembicCurves.h\"\n#include \"AlembicPoints.h\"\n#include \"AlembicModel.h\"\n#include \"AlembicSubD.h\"\n#include \"AlembicNurbs.h\"\n#include \"Utility.h\"\n\n#include <xsi_application.h>\n#include <xsi_time.h>\n#include <xsi_project.h>\n#include <xsi_scene.h>\n#include <xsi_property.h>\n#include <xsi_parameter.h>\n#include <xsi_x3dobject.h>\n#include <xsi_primitive.h>\n#include <xsi_kinematics.h>\n#include <xsi_kinematicstate.h>\n#include <xsi_uitoolkit.h>\n#include <xsi_geometry.h>\n#include <xsi_iceattribute.h>\n#include <xsi_model.h>\n#include <xsi_utils.h>\n\n#include \"sceneGraph.h\"\n\nusing namespace XSI;\nusing namespace MATH;\n\nnamespace AbcA = ::Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS;\nusing namespace AbcA;\n\nAlembicWriteJob::AlembicWriteJob\n(\n const CString & in_FileName,\n const exoNode::SelectionMap& in_Selection,\n const CDoubleArray & in_Frames\n)\n{\n \/\/ ensure to clear the isRefAnimated cache\n clearIsRefAnimatedCache();\n\n mFileName = CUtils::ResolveTokenString(in_FileName,XSI::CTime(),false);\n mSelection = in_Selection;\n\n for(LONG i=0;i<in_Frames.GetCount();i++)\n mFrames.push_back(in_Frames[i]);\n}\n\nAlembicWriteJob::~AlembicWriteJob()\n{\n}\n\nvoid AlembicWriteJob::SetOption(const CString & in_Name, const CValue & in_Value)\n{\n std::map<XSI::CString,XSI::CValue>::iterator it = mOptions.find(in_Name);\n if(it == mOptions.end())\n mOptions.insert(std::pair<XSI::CString,XSI::CValue>(in_Name,in_Value));\n else\n it->second = in_Value;\n}\n\nbool AlembicWriteJob::HasOption(const CString & in_Name)\n{\n std::map<XSI::CString,XSI::CValue>::iterator it = mOptions.find(in_Name);\n return it != mOptions.end();\n}\n\nCValue AlembicWriteJob::GetOption(const CString & in_Name)\n{\n std::map<XSI::CString,XSI::CValue>::iterator it = mOptions.find(in_Name);\n if(it != mOptions.end())\n return it->second;\n return CValue(false);\n}\n\n\/\/AlembicObjectPtr AlembicWriteJob::GetObject(const XSI::CRef & in_Ref)\n\/\/{\n\/\/ \tstd::string key = std::string( in_Ref.GetAsText().GetAsciiString() );\n\/\/\n\/\/\tstd::map<std::string,AlembicObjectPtr>::const_iterator it = mObjectsNames.find( key );\n\/\/\n\/\/\tif (it != mObjectsNames.end()) {\n\/\/\t\treturn it->second;\n\/\/\t}\n\/\/\treturn AlembicObjectPtr();\n\/\/}\n\nbool AlembicWriteJob::AddObject(AlembicObjectPtr in_Obj)\n{\n if(!in_Obj)\n return false;\n if(!in_Obj->GetRef().IsValid())\n return false;\n mObjects.push_back(in_Obj);\n return true;\n}\n\n\nCStatus AlembicWriteJob::PreProcess()\n{\n \/\/ check filenames\n if(mFileName.IsEmpty())\n {\n Application().LogMessage(L\"[ExocortexAlembic] No filename specified.\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n \/\/ check objects\n if(mSelection.size() == 0)\n {\n Application().LogMessage(L\"[ExocortexAlembic] No objects specified.\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n \/\/ check frames\n if(mFrames.size() == 0)\n {\n Application().LogMessage(L\"[ExocortexAlembic] No frames specified.\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n \/\/ check if the file is currently in use\n if(getRefArchive(mFileName) > 0)\n {\n Application().LogMessage(L\"[ExocortexAlembic] Error writing to file '\"+mFileName+L\"'. File currently in use.\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n \/\/ init archive (use a locally scoped archive)\n CString sceneFileName = L\"Exported from: \"+Application().GetActiveProject().GetActiveScene().GetParameterValue(L\"FileName\").GetAsText();\n try\n {\n mArchive = CreateArchiveWithInfo(\n Alembic::AbcCoreHDF5::WriteArchive(),\n mFileName.GetAsciiString(),\n \"Softimage Alembic Plugin\",\n sceneFileName.GetAsciiString(),\n Alembic::Abc::ErrorHandler::kThrowPolicy);\n }\n catch(Alembic::Util::Exception& e)\n {\n CString exc(e.what());\n Application().LogMessage(L\"[ExocortexAlembic] Error writing to file '\"+mFileName+L\"' (\"+exc+L\"). Do you still have it opened?\",siErrorMsg);\n return CStatus::InvalidArgument;\n }\n\n mTop = mArchive.getTop();\n\n \/\/ get the frame rate\n mFrameRate = 25.0;\n CValue returnVal;\n CValueArray args(1);\n args[0] = L\"PlayControl.Rate\";\n Application().ExecuteCommand(L\"GetValue\",args,returnVal);\n mFrameRate = returnVal;\n if(mFrameRate == 0.0)\n mFrameRate = 25.0;\n\n std::vector<Alembic::AbcCoreAbstract::chrono_t> frames;\n for(LONG i=0;i<mFrames.size();i++)\n frames.push_back(mFrames[i] \/ mFrameRate);\n\n \/\/ create the sampling\n double timePerSample = 1.0 \/ mFrameRate;\n if(frames.size() > 1)\n {\n if( ! HasAlembicWriterLicense() )\n {\n if(frames.size() > 75)\n {\n frames.resize(75);\n EC_LOG_WARNING(\"[ExocortexAlembic] Writer license not found: Maximum exportable samplecount is 75!\");\n }\n }\n\n double timePerCycle = frames[frames.size()-1] - frames[0];\n AbcA::TimeSamplingType samplingType((uint32_t)frames.size(),timePerCycle);\n AbcA::TimeSampling sampling(samplingType,frames);\n mTs = mArchive.addTimeSampling(sampling);\n }\n else\n {\n AbcA::TimeSampling sampling(1.0,frames[0]);\n mTs = mArchive.addTimeSampling(sampling);\n }\n\n const bool bSelectParents = true;\n const bool bSelectChildren = true;\n const bool bTransformCache = (bool)GetOption(L\"transformCache\");\n const bool bFlattenHierarchy = (bool)GetOption(L\"flattenHierarchy\");\n\n \/\/TODO: eventually this should be a replaced with an equivalent virtual method, and the exporter will be shared\n exoNodePtr exoSceneRoot = buildCommonSceneGraph(Application().GetActiveSceneRoot());\n \n selectNodes(exoSceneRoot, mSelection, bSelectParents, bSelectChildren);\n filterNodeSelection(exoSceneRoot, bTransformCache ? false : bFlattenHierarchy, bTransformCache);\n\n ::printSceneGraph(exoSceneRoot);\n\n \/\/return CStatus::OK;\n\n struct stackElement\n {\n exoNodePtr eNode;\n Alembic::Abc::OObject oParent;\n\n stackElement(exoNodePtr enode, Alembic::Abc::OObject parent):eNode(enode), oParent(parent)\n {}\n };\n std::list<stackElement> sceneStack;\n \n sceneStack.push_back(stackElement(exoSceneRoot, GetTop()));\n\n while( !sceneStack.empty() )\n {\n\n stackElement sElement = sceneStack.back();\n exoNodePtr eNode = sElement.eNode;\n sceneStack.pop_back();\n \n Alembic::Abc::OObject oParent = sElement.oParent;\n Alembic::Abc::OObject oNewParent;\n\n AlembicObjectPtr pNewObject;\n\n if(eNode->selected)\n {\n if(eNode->type == exoNode::SCENE_ROOT){\n \/\/we do not want to export the Scene_Root (the alembic archive has one already)\n }\n else if(eNode->type == exoNode::ITRANSFORM || eNode->type == exoNode::ETRANSFORM){\n pNewObject.reset(new AlembicModel(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::CAMERA){\n pNewObject.reset(new AlembicCamera(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::POLYMESH){\n pNewObject.reset(new AlembicPolyMesh(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::SUBD){\n pNewObject.reset(new AlembicSubD(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::SURFACE){\n pNewObject.reset(new AlembicNurbs(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::CURVES){\n pNewObject.reset(new AlembicCurves(eNode, this, oParent));\n }\n else if(eNode->type == exoNode::PARTICLES){\n pNewObject.reset(new AlembicPoints(eNode, this, oParent));\n }\n else{\n ESS_LOG_WARNING(\"Unknown type: not exporting \"<<eNode->name);\/\/Export as transform, and give warning?\n }\n }\n\n if(pNewObject){\n \/\/setup the next parent\n oNewParent = oParent.getChild(eNode->name);\n \/\/add the alembic object to the export list\n AddObject(pNewObject);\n }\n else{\n \/\/if we skip node A, we parent node A's children to the parent of A\n oNewParent = oParent;\n }\n\n if(oNewParent.valid()){\n for( std::list<exoNodePtr>::iterator it = eNode->children.begin(); it != eNode->children.end(); it++){\n sceneStack.push_back(stackElement(*it, oNewParent));\n }\n }\n else{\n ESS_LOG_ERROR(\"Do not have refernce to parent.\");\n return CStatus::Fail;\n }\n }\n\n\n#if 0\n\n for(LONG i=0; i<mSelection.size(); i++)\n {\n mSelection[i].nNodeDepth = getNodeDepthFromRef(mSelection[i].cRef);\n }\n std::sort(mSelection.begin(), mSelection.end());\n\n Alembic::Abc::OBox3dProperty boxProp = Alembic::AbcGeom::CreateOArchiveBounds(mArchive,mTs);\n\n CString activeSceneRoot_GetFullName = Application().GetActiveSceneRoot().GetFullName();\n \/\/ create object for each\n for(LONG i=0;i<mSelection.size();i++)\n {\n\t X3DObject xObj(mSelection[i].cRef);\n\t CRef xObj_GetActivePrimitive_GetRef = xObj.GetActivePrimitive().GetRef();\n \/\/if(GetObject(xObj_GetActivePrimitive_GetRef) != NULL) continue;\n\n \/\/ push all models up the hierarchy\n\t \n\t \/\/ MHahn: we are going to disable this code for now, since it should probably be an additional \n\t \/\/ export option, and we would prefer not to make things more complicated. We we will require\n\t \/\/ the user select the exact set of nodes that should be exported.\n\n \/\/Model model(xObj.GetRef());\n \/\/if(!model.IsValid())\n \/\/ model = xObj.GetModel();\n CRefArray modelRefs;\n \/\/if((bool)GetOption(L\"transformCache\"))\n if((bool)GetOption(L\"flattenHierarchy\") == false)\n {\n X3DObject parent = xObj.GetParent3DObject();\n while(parent.IsValid() && !parent.GetFullName().IsEqualNoCase( activeSceneRoot_GetFullName ))\n {\n modelRefs.Add(parent.GetActivePrimitive().GetRef());\n parent = parent.GetParent3DObject();\n }\n }\n \/\/else\n \/\/{\n \/\/ while(model.IsValid() && !model.GetFullName().IsEqualNoCase( activeSceneRoot_GetFullName ))\n \/\/ {\n \/\/ modelRefs.Add(model.GetActivePrimitive().GetRef());\n \/\/ model = model.GetModel();\n \/\/ }\n \/\/}\n for(LONG j=modelRefs.GetCount()-1;j>=0;j--)\n {\n \/\/if(GetObject(modelRefs[j]) == NULL)\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicModel(modelRefs[j],this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n }\n\n \n if((bool)GetOption(L\"transformCache\"))\n {\n \/\/always export all transforms whether the hierarchy is flattened or not\n\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicModel(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n\n continue;\/\/ only do models (tranforms) if we perform pure transformcache\n }\n\n \/\/ take care of all other types\n\t CString xObj_GetType = xObj.GetType();\n if(xObj_GetType.IsEqualNoCase(L\"null\") && ((bool)GetOption(L\"flattenHierarchy\") == false))\n\t {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicModel(xObj_GetActivePrimitive_GetRef, this));\n \/\/AddObjectIfDoesNotExist(ptr);\n\t }\n else if(xObj_GetType.IsEqualNoCase(L\"camera\"))\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicCamera(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else if(xObj_GetType.IsEqualNoCase(L\"polymsh\"))\n {\n Property geomProp;\n xObj.GetPropertyFromName(L\"geomapprox\",geomProp);\n LONG subDivLevel = geomProp.GetParameterValue(L\"gapproxmordrsl\");\n if(subDivLevel > 0)\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicSubD(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicPolyMesh(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n }\n else if(xObj_GetType.IsEqualNoCase(L\"surfmsh\"))\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicNurbs(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else if(xObj_GetType.IsEqualNoCase(L\"crvlist\"))\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicCurves(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else if(xObj_GetType.IsEqualNoCase(L\"hair\"))\n {\n AlembicObjectPtr ptr;\n ptr.reset(new AlembicCurves(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n else if(xObj_GetType.IsEqualNoCase(L\"pointcloud\"))\n {\n AlembicObjectPtr ptr;\n ICEAttribute strandPosition = xObj.GetActivePrimitive().GetGeometry().GetICEAttributeFromName(L\"StrandPosition\");\n if(strandPosition.IsDefined() && strandPosition.IsValid())\n ptr.reset(new AlembicCurves(xObj_GetActivePrimitive_GetRef,this));\n else\n ptr.reset(new AlembicPoints(xObj_GetActivePrimitive_GetRef,this));\n \/\/AddObjectIfDoesNotExist(ptr);\n }\n }\n\n#endif\n\n return CStatus::OK;\n}\n\nCStatus AlembicWriteJob::Process(double frame)\n{\n CStatus result = CStatus::False;\n\n for(size_t i=0;i<mFrames.size();i++)\n {\n \/\/ compare the frames\n if(abs(mFrames[i] - frame) > 0.001)\n continue;\n\n \/\/ run the export for all objects\n for(size_t j=0;j<mObjects.size();j++)\n {\n CStatus status = mObjects[j]->Save(mFrames[i]);\n if(status != CStatus::OK)\n return status;\n result = CStatus::OK;\n }\n }\n\n return result;\n}<|endoftext|>"} {"text":"<commit_before>\/\/===- AsmLexer.cpp - Lexer for Assembly Files ----------------------------===\/\/\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\/\/ This class implements the lexer for assembly files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmLexer.h\"\n#include \"llvm\/Support\/SMLoc.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Config\/config.h\" \/\/ for strtoull.\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\nusing namespace llvm;\n\nAsmLexer::AsmLexer(const MCAsmInfo &_MAI) : MAI(_MAI) {\n CurBuf = NULL;\n CurPtr = NULL;\n TokStart = 0;\n}\n\nAsmLexer::~AsmLexer() {\n}\n\nvoid AsmLexer::setBuffer(const MemoryBuffer *buf, const char *ptr) {\n CurBuf = buf;\n \n if (ptr)\n CurPtr = ptr;\n else\n CurPtr = CurBuf->getBufferStart();\n \n TokStart = 0;\n}\n\nSMLoc AsmLexer::getLoc() const {\n return SMLoc::getFromPointer(TokStart);\n}\n\n\/\/\/ ReturnError - Set the error to the specified string at the specified\n\/\/\/ location. This is defined to always return AsmToken::Error.\nAsmToken AsmLexer::ReturnError(const char *Loc, const std::string &Msg) {\n SetError(SMLoc::getFromPointer(Loc), Msg);\n \n return AsmToken(AsmToken::Error, StringRef(Loc, 0));\n}\n\nint AsmLexer::getNextChar() {\n char CurChar = *CurPtr++;\n switch (CurChar) {\n default:\n return (unsigned char)CurChar;\n case 0:\n \/\/ A nul character in the stream is either the end of the current buffer or\n \/\/ a random nul in the file. Disambiguate that here.\n if (CurPtr-1 != CurBuf->getBufferEnd())\n return 0; \/\/ Just whitespace.\n \n \/\/ Otherwise, return end of file.\n --CurPtr; \/\/ Another call to lex will return EOF again. \n return EOF;\n }\n}\n\n\/\/\/ LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*\nAsmToken AsmLexer::LexIdentifier() {\n while (isalnum(*CurPtr) || *CurPtr == '_' || *CurPtr == '$' ||\n *CurPtr == '.' || *CurPtr == '@')\n ++CurPtr;\n return AsmToken(AsmToken::Identifier, StringRef(TokStart, CurPtr - TokStart));\n}\n\n\/\/\/ LexSlash: Slash: \/\n\/\/\/ C-Style Comment: \/* ... *\/\nAsmToken AsmLexer::LexSlash() {\n switch (*CurPtr) {\n case '*': break; \/\/ C style comment.\n case '\/': return ++CurPtr, LexLineComment();\n default: return AsmToken(AsmToken::Slash, StringRef(CurPtr, 1));\n }\n\n \/\/ C Style comment.\n ++CurPtr; \/\/ skip the star.\n while (1) {\n int CurChar = getNextChar();\n switch (CurChar) {\n case EOF:\n return ReturnError(TokStart, \"unterminated comment\");\n case '*':\n \/\/ End of the comment?\n if (CurPtr[0] != '\/') break;\n \n ++CurPtr; \/\/ End the *\/.\n return LexToken();\n }\n }\n}\n\n\/\/\/ LexLineComment: Comment: #[^\\n]*\n\/\/\/ : \/\/[^\\n]*\nAsmToken AsmLexer::LexLineComment() {\n \/\/ FIXME: This is broken if we happen to a comment at the end of a file, which\n \/\/ was .included, and which doesn't end with a newline.\n int CurChar = getNextChar();\n while (CurChar != '\\n' && CurChar != '\\n' && CurChar != EOF)\n CurChar = getNextChar();\n \n if (CurChar == EOF)\n return AsmToken(AsmToken::Eof, StringRef(CurPtr, 0));\n return AsmToken(AsmToken::EndOfStatement, StringRef(CurPtr, 0));\n}\n\n\n\/\/\/ LexDigit: First character is [0-9].\n\/\/\/ Local Label: [0-9][:]\n\/\/\/ Forward\/Backward Label: [0-9][fb]\n\/\/\/ Binary integer: 0b[01]+\n\/\/\/ Octal integer: 0[0-7]+\n\/\/\/ Hex integer: 0x[0-9a-fA-F]+\n\/\/\/ Decimal integer: [1-9][0-9]*\n\/\/\/ TODO: FP literal.\nAsmToken AsmLexer::LexDigit() {\n if (*CurPtr == ':')\n return ReturnError(TokStart, \"FIXME: local label not implemented\");\n if (*CurPtr == 'f' || *CurPtr == 'b')\n return ReturnError(TokStart, \"FIXME: directional label not implemented\");\n \n \/\/ Decimal integer: [1-9][0-9]*\n if (CurPtr[-1] != '0') {\n while (isdigit(*CurPtr))\n ++CurPtr;\n return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart), \n strtoll(TokStart, 0, 10));\n }\n \n if (*CurPtr == 'b') {\n ++CurPtr;\n const char *NumStart = CurPtr;\n while (CurPtr[0] == '0' || CurPtr[0] == '1')\n ++CurPtr;\n \n \/\/ Requires at least one binary digit.\n if (CurPtr == NumStart)\n return ReturnError(CurPtr-2, \"Invalid binary number\");\n return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),\n strtoll(NumStart, 0, 2));\n }\n \n if (*CurPtr == 'x') {\n ++CurPtr;\n const char *NumStart = CurPtr;\n while (isxdigit(CurPtr[0]))\n ++CurPtr;\n \n \/\/ Requires at least one hex digit.\n if (CurPtr == NumStart)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n \n errno = 0;\n if (errno == EINVAL)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n if (errno == ERANGE) {\n errno = 0;\n if (errno == EINVAL)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n if (errno == ERANGE)\n return ReturnError(CurPtr-2, \"Hexadecimal number out of range\");\n }\n return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),\n (int64_t) strtoull(NumStart, 0, 16));\n }\n \n \/\/ Must be an octal number, it starts with 0.\n while (*CurPtr >= '0' && *CurPtr <= '7')\n ++CurPtr;\n return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),\n strtoll(TokStart, 0, 8));\n}\n\n\/\/\/ LexQuote: String: \"...\"\nAsmToken AsmLexer::LexQuote() {\n int CurChar = getNextChar();\n \/\/ TODO: does gas allow multiline string constants?\n while (CurChar != '\"') {\n if (CurChar == '\\\\') {\n \/\/ Allow \\\", etc.\n CurChar = getNextChar();\n }\n \n if (CurChar == EOF)\n return ReturnError(TokStart, \"unterminated string constant\");\n\n CurChar = getNextChar();\n }\n \n return AsmToken(AsmToken::String, StringRef(TokStart, CurPtr - TokStart));\n}\n\nStringRef AsmLexer::LexUntilEndOfStatement() {\n TokStart = CurPtr;\n\n while (!isAtStartOfComment(*CurPtr) && \/\/ Start of line comment.\n\t *CurPtr != ';' && \/\/ End of statement marker.\n *CurPtr != '\\n' &&\n *CurPtr != '\\r' &&\n (*CurPtr != 0 || CurPtr != CurBuf->getBufferEnd())) {\n ++CurPtr;\n }\n return StringRef(TokStart, CurPtr-TokStart);\n}\n\nbool AsmLexer::isAtStartOfComment(char Char) {\n \/\/ FIXME: This won't work for multi-character comment indicators like \"\/\/\".\n return Char == *MAI.getCommentString();\n}\n\nAsmToken AsmLexer::LexToken() {\n TokStart = CurPtr;\n \/\/ This always consumes at least one character.\n int CurChar = getNextChar();\n \n if (isAtStartOfComment(CurChar))\n return LexLineComment();\n\n switch (CurChar) {\n default:\n \/\/ Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*\n if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')\n return LexIdentifier();\n \n \/\/ Unknown character, emit an error.\n return ReturnError(TokStart, \"invalid character in input\");\n case EOF: return AsmToken(AsmToken::Eof, StringRef(TokStart, 0));\n case 0:\n case ' ':\n case '\\t':\n \/\/ Ignore whitespace.\n return LexToken();\n case '\\n': \/\/ FALL THROUGH.\n case '\\r': \/\/ FALL THROUGH.\n case ';': return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 1));\n case ':': return AsmToken(AsmToken::Colon, StringRef(TokStart, 1));\n case '+': return AsmToken(AsmToken::Plus, StringRef(TokStart, 1));\n case '-': return AsmToken(AsmToken::Minus, StringRef(TokStart, 1));\n case '~': return AsmToken(AsmToken::Tilde, StringRef(TokStart, 1));\n case '(': return AsmToken(AsmToken::LParen, StringRef(TokStart, 1));\n case ')': return AsmToken(AsmToken::RParen, StringRef(TokStart, 1));\n case '[': return AsmToken(AsmToken::LBrac, StringRef(TokStart, 1));\n case ']': return AsmToken(AsmToken::RBrac, StringRef(TokStart, 1));\n case '{': return AsmToken(AsmToken::LCurly, StringRef(TokStart, 1));\n case '}': return AsmToken(AsmToken::RCurly, StringRef(TokStart, 1));\n case '*': return AsmToken(AsmToken::Star, StringRef(TokStart, 1));\n case ',': return AsmToken(AsmToken::Comma, StringRef(TokStart, 1));\n case '$': return AsmToken(AsmToken::Dollar, StringRef(TokStart, 1));\n case '=': \n if (*CurPtr == '=')\n return ++CurPtr, AsmToken(AsmToken::EqualEqual, StringRef(TokStart, 2));\n return AsmToken(AsmToken::Equal, StringRef(TokStart, 1));\n case '|': \n if (*CurPtr == '|')\n return ++CurPtr, AsmToken(AsmToken::PipePipe, StringRef(TokStart, 2));\n return AsmToken(AsmToken::Pipe, StringRef(TokStart, 1));\n case '^': return AsmToken(AsmToken::Caret, StringRef(TokStart, 1));\n case '&': \n if (*CurPtr == '&')\n return ++CurPtr, AsmToken(AsmToken::AmpAmp, StringRef(TokStart, 2));\n return AsmToken(AsmToken::Amp, StringRef(TokStart, 1));\n case '!': \n if (*CurPtr == '=')\n return ++CurPtr, AsmToken(AsmToken::ExclaimEqual, StringRef(TokStart, 2));\n return AsmToken(AsmToken::Exclaim, StringRef(TokStart, 1));\n case '%': return AsmToken(AsmToken::Percent, StringRef(TokStart, 1));\n case '\/': return LexSlash();\n case '#': return AsmToken(AsmToken::Hash, StringRef(TokStart, 1));\n case '\"': return LexQuote();\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n return LexDigit();\n case '<':\n switch (*CurPtr) {\n case '<': return ++CurPtr, AsmToken(AsmToken::LessLess, \n StringRef(TokStart, 2));\n case '=': return ++CurPtr, AsmToken(AsmToken::LessEqual, \n StringRef(TokStart, 2));\n case '>': return ++CurPtr, AsmToken(AsmToken::LessGreater, \n StringRef(TokStart, 2));\n default: return AsmToken(AsmToken::Less, StringRef(TokStart, 1));\n }\n case '>':\n switch (*CurPtr) {\n case '>': return ++CurPtr, AsmToken(AsmToken::GreaterGreater, \n StringRef(TokStart, 2));\n case '=': return ++CurPtr, AsmToken(AsmToken::GreaterEqual, \n StringRef(TokStart, 2));\n default: return AsmToken(AsmToken::Greater, StringRef(TokStart, 1));\n }\n \n \/\/ TODO: Quoted identifiers (objc methods etc)\n \/\/ local labels: [0-9][:]\n \/\/ Forward\/backward labels: [0-9][fb]\n \/\/ Integers, fp constants, character constants.\n }\n}\n<commit_msg>remove some confused code that used strtoull<commit_after>\/\/===- AsmLexer.cpp - Lexer for Assembly Files ----------------------------===\/\/\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\/\/ This class implements the lexer for assembly files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmLexer.h\"\n#include \"llvm\/Support\/SMLoc.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\nusing namespace llvm;\n\nAsmLexer::AsmLexer(const MCAsmInfo &_MAI) : MAI(_MAI) {\n CurBuf = NULL;\n CurPtr = NULL;\n TokStart = 0;\n}\n\nAsmLexer::~AsmLexer() {\n}\n\nvoid AsmLexer::setBuffer(const MemoryBuffer *buf, const char *ptr) {\n CurBuf = buf;\n \n if (ptr)\n CurPtr = ptr;\n else\n CurPtr = CurBuf->getBufferStart();\n \n TokStart = 0;\n}\n\nSMLoc AsmLexer::getLoc() const {\n return SMLoc::getFromPointer(TokStart);\n}\n\n\/\/\/ ReturnError - Set the error to the specified string at the specified\n\/\/\/ location. This is defined to always return AsmToken::Error.\nAsmToken AsmLexer::ReturnError(const char *Loc, const std::string &Msg) {\n SetError(SMLoc::getFromPointer(Loc), Msg);\n \n return AsmToken(AsmToken::Error, StringRef(Loc, 0));\n}\n\nint AsmLexer::getNextChar() {\n char CurChar = *CurPtr++;\n switch (CurChar) {\n default:\n return (unsigned char)CurChar;\n case 0:\n \/\/ A nul character in the stream is either the end of the current buffer or\n \/\/ a random nul in the file. Disambiguate that here.\n if (CurPtr-1 != CurBuf->getBufferEnd())\n return 0; \/\/ Just whitespace.\n \n \/\/ Otherwise, return end of file.\n --CurPtr; \/\/ Another call to lex will return EOF again. \n return EOF;\n }\n}\n\n\/\/\/ LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*\nAsmToken AsmLexer::LexIdentifier() {\n while (isalnum(*CurPtr) || *CurPtr == '_' || *CurPtr == '$' ||\n *CurPtr == '.' || *CurPtr == '@')\n ++CurPtr;\n return AsmToken(AsmToken::Identifier, StringRef(TokStart, CurPtr - TokStart));\n}\n\n\/\/\/ LexSlash: Slash: \/\n\/\/\/ C-Style Comment: \/* ... *\/\nAsmToken AsmLexer::LexSlash() {\n switch (*CurPtr) {\n case '*': break; \/\/ C style comment.\n case '\/': return ++CurPtr, LexLineComment();\n default: return AsmToken(AsmToken::Slash, StringRef(CurPtr, 1));\n }\n\n \/\/ C Style comment.\n ++CurPtr; \/\/ skip the star.\n while (1) {\n int CurChar = getNextChar();\n switch (CurChar) {\n case EOF:\n return ReturnError(TokStart, \"unterminated comment\");\n case '*':\n \/\/ End of the comment?\n if (CurPtr[0] != '\/') break;\n \n ++CurPtr; \/\/ End the *\/.\n return LexToken();\n }\n }\n}\n\n\/\/\/ LexLineComment: Comment: #[^\\n]*\n\/\/\/ : \/\/[^\\n]*\nAsmToken AsmLexer::LexLineComment() {\n \/\/ FIXME: This is broken if we happen to a comment at the end of a file, which\n \/\/ was .included, and which doesn't end with a newline.\n int CurChar = getNextChar();\n while (CurChar != '\\n' && CurChar != '\\n' && CurChar != EOF)\n CurChar = getNextChar();\n \n if (CurChar == EOF)\n return AsmToken(AsmToken::Eof, StringRef(CurPtr, 0));\n return AsmToken(AsmToken::EndOfStatement, StringRef(CurPtr, 0));\n}\n\n\n\/\/\/ LexDigit: First character is [0-9].\n\/\/\/ Local Label: [0-9][:]\n\/\/\/ Forward\/Backward Label: [0-9][fb]\n\/\/\/ Binary integer: 0b[01]+\n\/\/\/ Octal integer: 0[0-7]+\n\/\/\/ Hex integer: 0x[0-9a-fA-F]+\n\/\/\/ Decimal integer: [1-9][0-9]*\n\/\/\/ TODO: FP literal.\nAsmToken AsmLexer::LexDigit() {\n if (*CurPtr == ':')\n return ReturnError(TokStart, \"FIXME: local label not implemented\");\n if (*CurPtr == 'f' || *CurPtr == 'b')\n return ReturnError(TokStart, \"FIXME: directional label not implemented\");\n \n \/\/ Decimal integer: [1-9][0-9]*\n if (CurPtr[-1] != '0') {\n while (isdigit(*CurPtr))\n ++CurPtr;\n return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart), \n strtoll(TokStart, 0, 10));\n }\n \n if (*CurPtr == 'b') {\n ++CurPtr;\n const char *NumStart = CurPtr;\n while (CurPtr[0] == '0' || CurPtr[0] == '1')\n ++CurPtr;\n \n \/\/ Requires at least one binary digit.\n if (CurPtr == NumStart)\n return ReturnError(CurPtr-2, \"Invalid binary number\");\n return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),\n strtoll(NumStart, 0, 2));\n }\n \n if (*CurPtr == 'x') {\n ++CurPtr;\n const char *NumStart = CurPtr;\n while (isxdigit(CurPtr[0]))\n ++CurPtr;\n \n \/\/ Requires at least one hex digit.\n if (CurPtr == NumStart)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n\n unsigned long long Result;\n if (StringRef(TokStart, CurPtr - TokStart).getAsInteger(0, Result))\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n \n return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),\n (int64_t)Result);\n }\n \n \/\/ Must be an octal number, it starts with 0.\n while (*CurPtr >= '0' && *CurPtr <= '7')\n ++CurPtr;\n return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),\n strtoll(TokStart, 0, 8));\n}\n\n\/\/\/ LexQuote: String: \"...\"\nAsmToken AsmLexer::LexQuote() {\n int CurChar = getNextChar();\n \/\/ TODO: does gas allow multiline string constants?\n while (CurChar != '\"') {\n if (CurChar == '\\\\') {\n \/\/ Allow \\\", etc.\n CurChar = getNextChar();\n }\n \n if (CurChar == EOF)\n return ReturnError(TokStart, \"unterminated string constant\");\n\n CurChar = getNextChar();\n }\n \n return AsmToken(AsmToken::String, StringRef(TokStart, CurPtr - TokStart));\n}\n\nStringRef AsmLexer::LexUntilEndOfStatement() {\n TokStart = CurPtr;\n\n while (!isAtStartOfComment(*CurPtr) && \/\/ Start of line comment.\n\t *CurPtr != ';' && \/\/ End of statement marker.\n *CurPtr != '\\n' &&\n *CurPtr != '\\r' &&\n (*CurPtr != 0 || CurPtr != CurBuf->getBufferEnd())) {\n ++CurPtr;\n }\n return StringRef(TokStart, CurPtr-TokStart);\n}\n\nbool AsmLexer::isAtStartOfComment(char Char) {\n \/\/ FIXME: This won't work for multi-character comment indicators like \"\/\/\".\n return Char == *MAI.getCommentString();\n}\n\nAsmToken AsmLexer::LexToken() {\n TokStart = CurPtr;\n \/\/ This always consumes at least one character.\n int CurChar = getNextChar();\n \n if (isAtStartOfComment(CurChar))\n return LexLineComment();\n\n switch (CurChar) {\n default:\n \/\/ Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*\n if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')\n return LexIdentifier();\n \n \/\/ Unknown character, emit an error.\n return ReturnError(TokStart, \"invalid character in input\");\n case EOF: return AsmToken(AsmToken::Eof, StringRef(TokStart, 0));\n case 0:\n case ' ':\n case '\\t':\n \/\/ Ignore whitespace.\n return LexToken();\n case '\\n': \/\/ FALL THROUGH.\n case '\\r': \/\/ FALL THROUGH.\n case ';': return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 1));\n case ':': return AsmToken(AsmToken::Colon, StringRef(TokStart, 1));\n case '+': return AsmToken(AsmToken::Plus, StringRef(TokStart, 1));\n case '-': return AsmToken(AsmToken::Minus, StringRef(TokStart, 1));\n case '~': return AsmToken(AsmToken::Tilde, StringRef(TokStart, 1));\n case '(': return AsmToken(AsmToken::LParen, StringRef(TokStart, 1));\n case ')': return AsmToken(AsmToken::RParen, StringRef(TokStart, 1));\n case '[': return AsmToken(AsmToken::LBrac, StringRef(TokStart, 1));\n case ']': return AsmToken(AsmToken::RBrac, StringRef(TokStart, 1));\n case '{': return AsmToken(AsmToken::LCurly, StringRef(TokStart, 1));\n case '}': return AsmToken(AsmToken::RCurly, StringRef(TokStart, 1));\n case '*': return AsmToken(AsmToken::Star, StringRef(TokStart, 1));\n case ',': return AsmToken(AsmToken::Comma, StringRef(TokStart, 1));\n case '$': return AsmToken(AsmToken::Dollar, StringRef(TokStart, 1));\n case '=': \n if (*CurPtr == '=')\n return ++CurPtr, AsmToken(AsmToken::EqualEqual, StringRef(TokStart, 2));\n return AsmToken(AsmToken::Equal, StringRef(TokStart, 1));\n case '|': \n if (*CurPtr == '|')\n return ++CurPtr, AsmToken(AsmToken::PipePipe, StringRef(TokStart, 2));\n return AsmToken(AsmToken::Pipe, StringRef(TokStart, 1));\n case '^': return AsmToken(AsmToken::Caret, StringRef(TokStart, 1));\n case '&': \n if (*CurPtr == '&')\n return ++CurPtr, AsmToken(AsmToken::AmpAmp, StringRef(TokStart, 2));\n return AsmToken(AsmToken::Amp, StringRef(TokStart, 1));\n case '!': \n if (*CurPtr == '=')\n return ++CurPtr, AsmToken(AsmToken::ExclaimEqual, StringRef(TokStart, 2));\n return AsmToken(AsmToken::Exclaim, StringRef(TokStart, 1));\n case '%': return AsmToken(AsmToken::Percent, StringRef(TokStart, 1));\n case '\/': return LexSlash();\n case '#': return AsmToken(AsmToken::Hash, StringRef(TokStart, 1));\n case '\"': return LexQuote();\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n return LexDigit();\n case '<':\n switch (*CurPtr) {\n case '<': return ++CurPtr, AsmToken(AsmToken::LessLess, \n StringRef(TokStart, 2));\n case '=': return ++CurPtr, AsmToken(AsmToken::LessEqual, \n StringRef(TokStart, 2));\n case '>': return ++CurPtr, AsmToken(AsmToken::LessGreater, \n StringRef(TokStart, 2));\n default: return AsmToken(AsmToken::Less, StringRef(TokStart, 1));\n }\n case '>':\n switch (*CurPtr) {\n case '>': return ++CurPtr, AsmToken(AsmToken::GreaterGreater, \n StringRef(TokStart, 2));\n case '=': return ++CurPtr, AsmToken(AsmToken::GreaterEqual, \n StringRef(TokStart, 2));\n default: return AsmToken(AsmToken::Greater, StringRef(TokStart, 1));\n }\n \n \/\/ TODO: Quoted identifiers (objc methods etc)\n \/\/ local labels: [0-9][:]\n \/\/ Forward\/backward labels: [0-9][fb]\n \/\/ Integers, fp constants, character constants.\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n **\n ** Copyright (C) Qxt Foundation. Some rights reserved.\n **\n ** This file is part of the QxtCore module of the Qxt library.\n **\n ** This library is free software; you can redistribute it and\/or modify it\n ** under the terms of the Common Public License, version 1.0, as published\n ** by IBM, and\/or under the terms of the GNU Lesser General Public License,\n ** version 2.1, as published by the Free Software Foundation.\n **\n ** This file is provided \"AS IS\", without WARRANTIES OR CONDITIONS OF ANY\n ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY\n ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR\n ** FITNESS FOR A PARTICULAR PURPOSE.\n **\n ** You should have received a copy of the CPL and the LGPL along with this\n ** file. See the LICENSE file and the cpl1.0.txt\/lgpl-2.1.txt files\n ** included with the source distribution for more information.\n ** If you did not receive a copy of the licenses, contact the Qxt Foundation.\n **\n ** <http:\/\/libqxt.org> <foundation@libqxt.org>\n **\n ****************************************************************************\/\n#include \"qxtmodelserializer.h\"\n#include <QAbstractItemModel>\n#include <QDataStream>\n\n\/*!\n \\class QxtModelSerializer QxtModelSerializer\n \\inmodule QxtCore\n \\brief Provides serialization of QAbstractItemModel\n *\/\n\nstruct QxtModelItem\n{\n QMap<int, QVariant> itemData;\n int rowCount;\n int columnCount;\n};\n\ninline QDataStream& operator<<(QDataStream& out, const QxtModelItem& item)\n{\n out << item.itemData;\n out << item.rowCount;\n out << item.columnCount;\n return out;\n}\n\ninline QDataStream& operator>>(QDataStream& in, QxtModelItem& item)\n{\n in >> item.itemData;\n in >> item.rowCount;\n in >> item.columnCount;\n return in;\n}\n\nclass QxtModelSerializerPrivate : public QxtPrivate<QxtModelSerializer>\n{\npublic:\n QxtModelSerializerPrivate() : model(0) { }\n\n void save(QDataStream& stream, const QModelIndex& index) const;\n bool restore(QDataStream& stream, const QModelIndex& index);\n void print(const QByteArray& data) const;\n\n QAbstractItemModel* model;\n};\n\nvoid QxtModelSerializerPrivate::save(QDataStream& stream, const QModelIndex& index) const\n{\n QxtModelItem item;\n item.itemData = model->itemData(index);\n item.rowCount = model->rowCount(index);\n item.columnCount = model->columnCount(index);\n stream << item;\n for (int r = 0; r < item.rowCount; ++r)\n for (int c = 0; c < item.columnCount; ++c)\n save(stream, model->index(r, c, index));\n}\n\nbool QxtModelSerializerPrivate::restore(QDataStream& stream, const QModelIndex& index)\n{\n QxtModelItem item;\n stream >> item;\n\n if (index.isValid())\n model->setItemData(index, item.itemData);\n if (item.rowCount > 0)\n model->insertRows(0, item.rowCount, index);\n if (item.columnCount > 0)\n model->insertColumns(0, item.columnCount, index);\n\n for (int r = 0; r < item.rowCount; ++r)\n {\n for (int c = 0; c < item.columnCount; ++c)\n restore(stream, model->index(r, c, index));\n }\n return stream.status() == QDataStream::Ok;\n}\n\nvoid QxtModelSerializerPrivate::print(const QByteArray& data) const\n{\n QDataStream stream(data);\n while (!stream.atEnd())\n {\n QxtModelItem item;\n stream >> item;\n }\n}\n\nQxtModelSerializer::QxtModelSerializer(QAbstractItemModel* model)\n{\n qxt_d().model = model;\n}\n\nQxtModelSerializer::~QxtModelSerializer()\n{\n}\n\nQAbstractItemModel* QxtModelSerializer::model() const\n{\n return qxt_d().model;\n}\n\nvoid QxtModelSerializer::setModel(QAbstractItemModel* model)\n{\n qxt_d().model = model;\n}\n\nQByteArray QxtModelSerializer::saveModel(const QModelIndex& index) const\n{\n if (!qxt_d().model)\n {\n qWarning(\"QxtModelSerializer::saveModel(): model == null\");\n return QByteArray();\n }\n\n QByteArray data;\n QDataStream stream(&data, QIODevice::WriteOnly);\n qxt_d().save(stream, index);\n qxt_d().print(data);\n return data;\n}\n\nbool QxtModelSerializer::restoreModel(const QByteArray& data, const QModelIndex& index)\n{\n if (!qxt_d().model)\n {\n qWarning(\"QxtModelSerializer::restoreModel(): model == null\");\n return false;\n }\n\n QDataStream stream(data);\n qxt_d().print(data);\n return qxt_d().restore(stream, index);\n}\n<commit_msg>Disabled QxtModelSerializer docs temporarily.<commit_after>\/****************************************************************************\n **\n ** Copyright (C) Qxt Foundation. Some rights reserved.\n **\n ** This file is part of the QxtCore module of the Qxt library.\n **\n ** This library is free software; you can redistribute it and\/or modify it\n ** under the terms of the Common Public License, version 1.0, as published\n ** by IBM, and\/or under the terms of the GNU Lesser General Public License,\n ** version 2.1, as published by the Free Software Foundation.\n **\n ** This file is provided \"AS IS\", without WARRANTIES OR CONDITIONS OF ANY\n ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY\n ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR\n ** FITNESS FOR A PARTICULAR PURPOSE.\n **\n ** You should have received a copy of the CPL and the LGPL along with this\n ** file. See the LICENSE file and the cpl1.0.txt\/lgpl-2.1.txt files\n ** included with the source distribution for more information.\n ** If you did not receive a copy of the licenses, contact the Qxt Foundation.\n **\n ** <http:\/\/libqxt.org> <foundation@libqxt.org>\n **\n ****************************************************************************\/\n#include \"qxtmodelserializer.h\"\n#include <QAbstractItemModel>\n#include <QDataStream>\n\n\/*\n \\class QxtModelSerializer\n \\inmodule QxtCore\n \\brief Provides serialization of QAbstractItemModel\n *\/\n\nstruct QxtModelItem\n{\n QMap<int, QVariant> itemData;\n int rowCount;\n int columnCount;\n};\n\ninline QDataStream& operator<<(QDataStream& out, const QxtModelItem& item)\n{\n out << item.itemData;\n out << item.rowCount;\n out << item.columnCount;\n return out;\n}\n\ninline QDataStream& operator>>(QDataStream& in, QxtModelItem& item)\n{\n in >> item.itemData;\n in >> item.rowCount;\n in >> item.columnCount;\n return in;\n}\n\nclass QxtModelSerializerPrivate : public QxtPrivate<QxtModelSerializer>\n{\npublic:\n QxtModelSerializerPrivate() : model(0) { }\n\n void save(QDataStream& stream, const QModelIndex& index) const;\n bool restore(QDataStream& stream, const QModelIndex& index);\n void print(const QByteArray& data) const;\n\n QAbstractItemModel* model;\n};\n\nvoid QxtModelSerializerPrivate::save(QDataStream& stream, const QModelIndex& index) const\n{\n QxtModelItem item;\n item.itemData = model->itemData(index);\n item.rowCount = model->rowCount(index);\n item.columnCount = model->columnCount(index);\n stream << item;\n for (int r = 0; r < item.rowCount; ++r)\n for (int c = 0; c < item.columnCount; ++c)\n save(stream, model->index(r, c, index));\n}\n\nbool QxtModelSerializerPrivate::restore(QDataStream& stream, const QModelIndex& index)\n{\n QxtModelItem item;\n stream >> item;\n\n if (index.isValid())\n model->setItemData(index, item.itemData);\n if (item.rowCount > 0)\n model->insertRows(0, item.rowCount, index);\n if (item.columnCount > 0)\n model->insertColumns(0, item.columnCount, index);\n\n for (int r = 0; r < item.rowCount; ++r)\n {\n for (int c = 0; c < item.columnCount; ++c)\n restore(stream, model->index(r, c, index));\n }\n return stream.status() == QDataStream::Ok;\n}\n\nvoid QxtModelSerializerPrivate::print(const QByteArray& data) const\n{\n QDataStream stream(data);\n while (!stream.atEnd())\n {\n QxtModelItem item;\n stream >> item;\n }\n}\n\nQxtModelSerializer::QxtModelSerializer(QAbstractItemModel* model)\n{\n qxt_d().model = model;\n}\n\nQxtModelSerializer::~QxtModelSerializer()\n{\n}\n\nQAbstractItemModel* QxtModelSerializer::model() const\n{\n return qxt_d().model;\n}\n\nvoid QxtModelSerializer::setModel(QAbstractItemModel* model)\n{\n qxt_d().model = model;\n}\n\nQByteArray QxtModelSerializer::saveModel(const QModelIndex& index) const\n{\n if (!qxt_d().model)\n {\n qWarning(\"QxtModelSerializer::saveModel(): model == null\");\n return QByteArray();\n }\n\n QByteArray data;\n QDataStream stream(&data, QIODevice::WriteOnly);\n qxt_d().save(stream, index);\n qxt_d().print(data);\n return data;\n}\n\nbool QxtModelSerializer::restoreModel(const QByteArray& data, const QModelIndex& index)\n{\n if (!qxt_d().model)\n {\n qWarning(\"QxtModelSerializer::restoreModel(): model == null\");\n return false;\n }\n\n QDataStream stream(data);\n qxt_d().print(data);\n return qxt_d().restore(stream, index);\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\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 <QGraphicsSceneContextMenuEvent>\n#include <QSettings>\n#include \"mbuttongroup.h\"\n#include \"mbutton.h\"\n#include \"mbutton_p.h\"\n#include \"mtheme.h\"\n\n#include \"mwidgetcreator.h\"\nM_REGISTER_WIDGET(MButton)\n\nconst MTheme::ViewType MButton::toggleType = \"toggle\";\nconst MTheme::ViewType MButton::checkboxType = \"checkbox\";\nconst MTheme::ViewType MButton::iconType = \"icon\";\nconst MTheme::ViewType MButton::switchType = \"switch\";\nconst MTheme::ViewType MButton::groupType = \"group\";\n\nMButtonPrivate::MButtonPrivate()\n : MWidgetControllerPrivate(),\n buttonGroup(0)\n{\n}\n\nMButtonPrivate::~MButtonPrivate()\n{\n}\n\nvoid MButtonPrivate::init()\n{\n}\n\nvoid MButtonPrivate::init(const QString &newIconID, const QString &newText)\n{\n Q_Q(MButton);\n init();\n\n q->setText(newText);\n q->setIconID(newIconID);\n}\n\nMButton::MButton(MButtonPrivate *dd, MButtonModel *model, QGraphicsItem *parent)\n : MWidgetController(dd, model, parent)\n{\n Q_D(MButton);\n\n d->init();\n}\n\nMButton::MButton(QGraphicsItem *parent, MButtonModel *model)\n : MWidgetController(new MButtonPrivate, model == NULL ? new MButtonModel : model, parent)\n{\n Q_D(MButton);\n\n d->init();\n}\n\nMButton::MButton(const QString &text, QGraphicsItem *parent, MButtonModel *model)\n : MWidgetController(new MButtonPrivate, model == NULL ? new MButtonModel : model, parent)\n{\n Q_D(MButton);\n\n d->init(QString(), text);\n}\n\nMButton::MButton(const QString &iconID, const QString &text, QGraphicsItem *parent, MButtonModel *model)\n : MWidgetController(new MButtonPrivate, model == NULL ? new MButtonModel : model, parent)\n{\n Q_D(MButton);\n\n d->init(iconID, text);\n}\n\nMButton::~MButton()\n{\n Q_D(MButton);\n\n if (d->buttonGroup) {\n d->buttonGroup->removeButton(this);\n }\n}\n\nvoid MButton::setIconID(const QString &iconID)\n{\n model()->setIconID(iconID);\n}\n\n\nQString MButton::iconID() const\n{\n return model()->iconID();\n}\n\nvoid MButton::setToggledIconID(const QString &toggledIconID)\n{\n model()->setToggledIconID(toggledIconID);\n}\n\nQString MButton::toggledIconID() const\n{\n return model()->toggledIconID();\n}\n\nvoid MButton::setIcon(const QIcon &icon)\n{\n model()->setIcon(icon);\n}\n\nQIcon MButton::icon() const\n{\n return model()->icon();\n}\n\nvoid MButton::setText(const QString &text)\n{\n model()->setText(text);\n}\n\nQString MButton::text() const\n{\n return model()->text();\n}\n\nbool MButton::isTextVisible() const\n{\n return model()->textVisible();\n}\n\nvoid MButton::setTextVisible(bool textVisible)\n{\n model()->setTextVisible(textVisible);\n}\n\nbool MButton::isIconVisible() const\n{\n return model()->iconVisible();\n}\n\nvoid MButton::setIconVisible(bool iconVisible)\n{\n model()->setIconVisible(iconVisible);\n}\n\nbool MButton::isCheckable() const\n{\n return model()->checkable();\n}\n\nvoid MButton::setCheckable(bool buttonCheckable)\n{\n if (!buttonCheckable && model()->checked())\n model()->setChecked(false);\n model()->setCheckable(buttonCheckable);\n}\n\nbool MButton::isChecked() const\n{\n return model()->checked();\n}\n\n\/\/TODO Remove this when delayed model initialization bug is properly fixed.\nstatic bool toggleEmitted = false;\n\nvoid MButton::setChecked(bool buttonChecked)\n{\n \/\/ FIXME: these checks could be done in model side, the group needs moved to model first\n if (isCheckable() && buttonChecked != isChecked()) {\n\n \/* The active button in an exclusive group cannot be deselected *\/\n if (group() && group()->exclusive() && group()->checkedButton() == this) {\n return;\n }\n\n \/\/TODO This is here just because of the delayed model initialization, this\n \/\/ call should be removed when the delayed model initialization bug\/feature\n \/\/ is properly fixed.\n \/\/\n \/\/ The bug causes invalid functionaliy for buttons inside a buttongroup,\n \/\/ if state of a button(s) is changed before messageloop is run first\n \/\/ time. The updateData() slot does does not get called and toggled\n \/\/ signal is not emitted. Exclusive buttongroup uses the toggled signal\n \/\/ to uncheck buttons.\n bool shouldEmit = (model()->checked() != buttonChecked);\n toggleEmitted = false;\n\n model()->setChecked(buttonChecked);\n\n \/\/TODO Remove this when delayed model initialization bug is properly fixed.\n if (shouldEmit && !toggleEmitted)\n emit toggled(model()->checked());\n }\n}\n\nbool MButton::isDown() const\n{\n return model()->down();\n}\n\nvoid MButton::setDown(bool status)\n{\n model()->setDown(status);\n}\n\nvoid MButton::click()\n{\n model()->setDown(true);\n model()->setDown(false);\n modelClick();\n}\n\nvoid MButton::toggle()\n{\n setChecked(!isChecked());\n}\n\nMButtonGroup *MButton::group() const\n{\n Q_D(const MButton);\n return d->buttonGroup;\n}\n\nvoid MButton::setGroup(MButtonGroup *group)\n{\n Q_D(MButton);\n\n d->buttonGroup = group;\n}\n\nvoid MButton::setupModel()\n{\n MWidgetController::setupModel();\n\n connect(model(), SIGNAL(clicked()), SLOT(modelClick()));\n}\n\nvoid MButton::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)\n{\n MWidgetController::contextMenuEvent(event);\n event->accept();\n}\n\nvoid MButton::updateData(const QList<const char *>& modifications)\n{\n MWidgetController::updateData(modifications);\n\n const char *member;\n foreach(member, modifications) {\n if (member == MButtonModel::Checked) {\n emit toggled(model()->checked());\n\n \/\/TODO Remove this when delayed model initialization bug is properly fixed.\n toggleEmitted = true;\n } else if (member == MButtonModel::Down) {\n if (model()->down())\n emit pressed();\n else\n emit released();\n }\n }\n}\n\nvoid MButton::modelClick()\n{\n toggle();\n emit clicked(isChecked());\n}\n\n<commit_msg>Changes: The button will ignore the context menu event and propagate it further.<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\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 <QGraphicsSceneContextMenuEvent>\n#include <QSettings>\n#include \"mbuttongroup.h\"\n#include \"mbutton.h\"\n#include \"mbutton_p.h\"\n#include \"mtheme.h\"\n\n#include \"mwidgetcreator.h\"\nM_REGISTER_WIDGET(MButton)\n\nconst MTheme::ViewType MButton::toggleType = \"toggle\";\nconst MTheme::ViewType MButton::checkboxType = \"checkbox\";\nconst MTheme::ViewType MButton::iconType = \"icon\";\nconst MTheme::ViewType MButton::switchType = \"switch\";\nconst MTheme::ViewType MButton::groupType = \"group\";\n\nMButtonPrivate::MButtonPrivate()\n : MWidgetControllerPrivate(),\n buttonGroup(0)\n{\n}\n\nMButtonPrivate::~MButtonPrivate()\n{\n}\n\nvoid MButtonPrivate::init()\n{\n}\n\nvoid MButtonPrivate::init(const QString &newIconID, const QString &newText)\n{\n Q_Q(MButton);\n init();\n\n q->setText(newText);\n q->setIconID(newIconID);\n}\n\nMButton::MButton(MButtonPrivate *dd, MButtonModel *model, QGraphicsItem *parent)\n : MWidgetController(dd, model, parent)\n{\n Q_D(MButton);\n\n d->init();\n}\n\nMButton::MButton(QGraphicsItem *parent, MButtonModel *model)\n : MWidgetController(new MButtonPrivate, model == NULL ? new MButtonModel : model, parent)\n{\n Q_D(MButton);\n\n d->init();\n}\n\nMButton::MButton(const QString &text, QGraphicsItem *parent, MButtonModel *model)\n : MWidgetController(new MButtonPrivate, model == NULL ? new MButtonModel : model, parent)\n{\n Q_D(MButton);\n\n d->init(QString(), text);\n}\n\nMButton::MButton(const QString &iconID, const QString &text, QGraphicsItem *parent, MButtonModel *model)\n : MWidgetController(new MButtonPrivate, model == NULL ? new MButtonModel : model, parent)\n{\n Q_D(MButton);\n\n d->init(iconID, text);\n}\n\nMButton::~MButton()\n{\n Q_D(MButton);\n\n if (d->buttonGroup) {\n d->buttonGroup->removeButton(this);\n }\n}\n\nvoid MButton::setIconID(const QString &iconID)\n{\n model()->setIconID(iconID);\n}\n\n\nQString MButton::iconID() const\n{\n return model()->iconID();\n}\n\nvoid MButton::setToggledIconID(const QString &toggledIconID)\n{\n model()->setToggledIconID(toggledIconID);\n}\n\nQString MButton::toggledIconID() const\n{\n return model()->toggledIconID();\n}\n\nvoid MButton::setIcon(const QIcon &icon)\n{\n model()->setIcon(icon);\n}\n\nQIcon MButton::icon() const\n{\n return model()->icon();\n}\n\nvoid MButton::setText(const QString &text)\n{\n model()->setText(text);\n}\n\nQString MButton::text() const\n{\n return model()->text();\n}\n\nbool MButton::isTextVisible() const\n{\n return model()->textVisible();\n}\n\nvoid MButton::setTextVisible(bool textVisible)\n{\n model()->setTextVisible(textVisible);\n}\n\nbool MButton::isIconVisible() const\n{\n return model()->iconVisible();\n}\n\nvoid MButton::setIconVisible(bool iconVisible)\n{\n model()->setIconVisible(iconVisible);\n}\n\nbool MButton::isCheckable() const\n{\n return model()->checkable();\n}\n\nvoid MButton::setCheckable(bool buttonCheckable)\n{\n if (!buttonCheckable && model()->checked())\n model()->setChecked(false);\n model()->setCheckable(buttonCheckable);\n}\n\nbool MButton::isChecked() const\n{\n return model()->checked();\n}\n\n\/\/TODO Remove this when delayed model initialization bug is properly fixed.\nstatic bool toggleEmitted = false;\n\nvoid MButton::setChecked(bool buttonChecked)\n{\n \/\/ FIXME: these checks could be done in model side, the group needs moved to model first\n if (isCheckable() && buttonChecked != isChecked()) {\n\n \/* The active button in an exclusive group cannot be deselected *\/\n if (group() && group()->exclusive() && group()->checkedButton() == this) {\n return;\n }\n\n \/\/TODO This is here just because of the delayed model initialization, this\n \/\/ call should be removed when the delayed model initialization bug\/feature\n \/\/ is properly fixed.\n \/\/\n \/\/ The bug causes invalid functionaliy for buttons inside a buttongroup,\n \/\/ if state of a button(s) is changed before messageloop is run first\n \/\/ time. The updateData() slot does does not get called and toggled\n \/\/ signal is not emitted. Exclusive buttongroup uses the toggled signal\n \/\/ to uncheck buttons.\n bool shouldEmit = (model()->checked() != buttonChecked);\n toggleEmitted = false;\n\n model()->setChecked(buttonChecked);\n\n \/\/TODO Remove this when delayed model initialization bug is properly fixed.\n if (shouldEmit && !toggleEmitted)\n emit toggled(model()->checked());\n }\n}\n\nbool MButton::isDown() const\n{\n return model()->down();\n}\n\nvoid MButton::setDown(bool status)\n{\n model()->setDown(status);\n}\n\nvoid MButton::click()\n{\n model()->setDown(true);\n model()->setDown(false);\n modelClick();\n}\n\nvoid MButton::toggle()\n{\n setChecked(!isChecked());\n}\n\nMButtonGroup *MButton::group() const\n{\n Q_D(const MButton);\n return d->buttonGroup;\n}\n\nvoid MButton::setGroup(MButtonGroup *group)\n{\n Q_D(MButton);\n\n d->buttonGroup = group;\n}\n\nvoid MButton::setupModel()\n{\n MWidgetController::setupModel();\n\n connect(model(), SIGNAL(clicked()), SLOT(modelClick()));\n}\n\nvoid MButton::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)\n{\n MWidgetController::contextMenuEvent(event);\n}\n\nvoid MButton::updateData(const QList<const char *>& modifications)\n{\n MWidgetController::updateData(modifications);\n\n const char *member;\n foreach(member, modifications) {\n if (member == MButtonModel::Checked) {\n emit toggled(model()->checked());\n\n \/\/TODO Remove this when delayed model initialization bug is properly fixed.\n toggleEmitted = true;\n } else if (member == MButtonModel::Down) {\n if (model()->down())\n emit pressed();\n else\n emit released();\n }\n }\n}\n\nvoid MButton::modelClick()\n{\n toggle();\n emit clicked(isChecked());\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"ppapi\/tests\/test_mouse_lock.h\"\n\n#include \"ppapi\/cpp\/input_event.h\"\n#include \"ppapi\/cpp\/view.h\"\n#include \"ppapi\/tests\/testing_instance.h\"\n\nREGISTER_TEST_CASE(MouseLock);\n\nTestMouseLock::TestMouseLock(TestingInstance* instance)\n : TestCase(instance),\n MouseLock(instance),\n nested_event_(instance->pp_instance()) {\n}\n\nTestMouseLock::~TestMouseLock() {\n}\n\nbool TestMouseLock::Init() {\n return CheckTestingInterface();\n}\n\nvoid TestMouseLock::RunTests(const std::string& filter) {\n RUN_TEST(SucceedWhenAllowed, filter);\n RUN_TEST(FailWhenBlocked, filter);\n}\n\nvoid TestMouseLock::DidChangeView(const pp::View& view) {\n position_ = view.GetRect();\n}\n\nvoid TestMouseLock::MouseLockLost() {\n nested_event_.Signal();\n}\n\nstd::string TestMouseLock::TestSucceedWhenAllowed() {\n \/\/ Content settings are configured to allow mouse lock for any site.\n \/\/ Please see chrome\/test\/ppapi\/ppapi_interactive_browsertest.cc.\n TestCompletionCallback callback(instance_->pp_instance(), callback_type());\n SimulateUserGesture();\n callback.WaitForResult(LockMouse(callback));\n ASSERT_EQ(PP_OK, callback.result());\n\n UnlockMouse();\n \/\/ Wait for the MouseLockLost() call.\n nested_event_.Wait();\n\n PASS();\n}\n\nstd::string TestMouseLock::TestFailWhenBlocked() {\n \/\/ Content settings are configured to block mouse lock for any site.\n \/\/ Please see chrome\/test\/ppapi\/ppapi_interactive_browsertest.cc.\n TestCompletionCallback callback(instance_->pp_instance(), callback_type());\n SimulateUserGesture();\n callback.WaitForResult(LockMouse(callback));\n ASSERT_NE(PP_OK, callback.result());\n\n PASS();\n}\n\nvoid TestMouseLock::SimulateUserGesture() {\n pp::Point mouse_movement;\n pp::MouseInputEvent input_event(\n instance_,\n PP_INPUTEVENT_TYPE_MOUSEDOWN,\n 0, \/\/ time_stamp\n 0, \/\/ modifiers\n PP_INPUTEVENT_MOUSEBUTTON_LEFT,\n position_.CenterPoint(),\n 1, \/\/ click_count\n mouse_movement);\n\n testing_interface_->SimulateInputEvent(instance_->pp_instance(),\n input_event.pp_resource());\n}\n<commit_msg>Disable SucceedWhenAllowed due to timeouts.<commit_after>\/\/ 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 \"ppapi\/tests\/test_mouse_lock.h\"\n\n#include \"ppapi\/cpp\/input_event.h\"\n#include \"ppapi\/cpp\/view.h\"\n#include \"ppapi\/tests\/testing_instance.h\"\n\nREGISTER_TEST_CASE(MouseLock);\n\nTestMouseLock::TestMouseLock(TestingInstance* instance)\n : TestCase(instance),\n MouseLock(instance),\n nested_event_(instance->pp_instance()) {\n}\n\nTestMouseLock::~TestMouseLock() {\n}\n\nbool TestMouseLock::Init() {\n return CheckTestingInterface();\n}\n\nvoid TestMouseLock::RunTests(const std::string& filter) {\n \/\/ Disabled due to timeouts: http:\/\/crbug.com\/136548\n \/\/ RUN_TEST(SucceedWhenAllowed, filter);\n RUN_TEST(FailWhenBlocked, filter);\n}\n\nvoid TestMouseLock::DidChangeView(const pp::View& view) {\n position_ = view.GetRect();\n}\n\nvoid TestMouseLock::MouseLockLost() {\n nested_event_.Signal();\n}\n\nstd::string TestMouseLock::TestSucceedWhenAllowed() {\n \/\/ Content settings are configured to allow mouse lock for any site.\n \/\/ Please see chrome\/test\/ppapi\/ppapi_interactive_browsertest.cc.\n TestCompletionCallback callback(instance_->pp_instance(), callback_type());\n SimulateUserGesture();\n callback.WaitForResult(LockMouse(callback));\n ASSERT_EQ(PP_OK, callback.result());\n\n UnlockMouse();\n \/\/ Wait for the MouseLockLost() call.\n nested_event_.Wait();\n\n PASS();\n}\n\nstd::string TestMouseLock::TestFailWhenBlocked() {\n \/\/ Content settings are configured to block mouse lock for any site.\n \/\/ Please see chrome\/test\/ppapi\/ppapi_interactive_browsertest.cc.\n TestCompletionCallback callback(instance_->pp_instance(), callback_type());\n SimulateUserGesture();\n callback.WaitForResult(LockMouse(callback));\n ASSERT_NE(PP_OK, callback.result());\n\n PASS();\n}\n\nvoid TestMouseLock::SimulateUserGesture() {\n pp::Point mouse_movement;\n pp::MouseInputEvent input_event(\n instance_,\n PP_INPUTEVENT_TYPE_MOUSEDOWN,\n 0, \/\/ time_stamp\n 0, \/\/ modifiers\n PP_INPUTEVENT_MOUSEBUTTON_LEFT,\n position_.CenterPoint(),\n 1, \/\/ click_count\n mouse_movement);\n\n testing_interface_->SimulateInputEvent(instance_->pp_instance(),\n input_event.pp_resource());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <cassert>\n\n#include <algorithm>\n#include <iostream>\n#include <limits>\n#include <ostream>\n\n#include <GL\/glew.h>\n\n#include <osg\/io_utils>\n#include <osg\/Material>\n#include <osg\/MatrixTransform>\n#include <osg\/StateSet>\n#include <osg\/TriangleFunctor>\n\n#include <cover\/coVRConfig.h>\n#include <cover\/coVRPluginSupport.h>\n#include <cover\/VRViewer.h>\n\n#include <visionaray\/detail\/aligned_vector.h>\n#include <visionaray\/math\/math.h>\n#include <visionaray\/bvh.h>\n#include <visionaray\/kernels.h>\n#include <visionaray\/point_light.h>\n#include <visionaray\/render_target.h>\n#include <visionaray\/scheduler.h>\n\n#include \"visionaray_plugin.h\"\n\nnamespace visionaray { namespace cover {\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Type definitions\n\/\/\n\nusing triangle_type = basic_triangle<3, float>;\nusing triangle_list = aligned_vector<triangle_type>;\nusing normal_list = aligned_vector<vec3>;\nusing material_list = aligned_vector<phong<float>>;\n\nusing host_ray_type = basic_ray<simd::float4>;\nusing host_bvh_type = bvh<triangle_type>;\nusing host_sched_type = tiled_sched<host_ray_type>;\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Functor that stores triangles from osg::Drawable\n\/\/\n\nclass store_triangle\n{\npublic:\n\n store_triangle() : triangles_(nullptr) {}\n\n void init(triangle_list& tris, normal_list& norms, unsigned geom_id)\n {\n triangles_ = &tris;\n normals_ = &norms;\n geom_id_ = geom_id;\n }\n\n void operator()(osg::Vec3 const& v1, osg::Vec3 const& v2, osg::Vec3 const& v3, bool) const\n {\n assert( triangles_ && normals_ );\n\n triangle_type tri;\n tri.prim_id = static_cast<unsigned>(triangles_->size());\n tri.geom_id = geom_id_;\n tri.v1 = vec3(v1.x(), v1.y(), v1.z());\n tri.e1 = vec3(v2.x(), v2.y(), v2.z()) - tri.v1;\n tri.e2 = vec3(v3.x(), v3.y(), v3.z()) - tri.v1;\n triangles_->push_back(tri);\n\n normals_->push_back( normalize(cross(tri.e1, tri.e2)) );\n\n assert( triangles_->size() == normals_->size() );\n }\n\nprivate:\n\n \/\/ Store pointers because osg::TriangleFunctor is shitty..\n triangle_list* triangles_;\n normal_list* normals_;\n unsigned geom_id_;\n\n};\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Visitor to acquire scene data\n\/\/\n\nclass get_scene_visitor : public osg::NodeVisitor\n{\npublic:\n\n using base_type = osg::NodeVisitor;\n using base_type::apply;\n\n get_scene_visitor(triangle_list& tris, normal_list& norms, material_list& mats, TraversalMode tm)\n : base_type(tm)\n , triangles_(tris)\n , normals_(norms)\n , materials_(mats)\n {\n }\n\n void apply(osg::Geode& geode)\n {\n for (size_t i = 0; i < geode.getNumDrawables(); ++i)\n {\n auto drawable = geode.getDrawable(i);\n if (drawable)\n {\n auto set = drawable->getOrCreateStateSet();\n auto attr = set->getAttribute(osg::StateAttribute::MATERIAL);\n auto mat = dynamic_cast<osg::Material*>(attr);\n\n if (mat)\n {\n auto cd = mat->getDiffuse(osg::Material::Face::FRONT);\n auto cs = mat->getSpecular(osg::Material::Face::FRONT);\n\n phong<float> vsnray_mat;\n vsnray_mat.set_cd( vec3(cd.x(), cd.y(), cd.z()) );\n vsnray_mat.set_kd( 1.0f );\n vsnray_mat.set_ks( cs.x() ); \/\/ TODO: e.g. luminance?\n vsnray_mat.set_specular_exp( mat->getShininess(osg::Material::Face::FRONT) );\n materials_.push_back(vsnray_mat);\n }\n\n assert( static_cast<material_list::size_type>(static_cast<unsigned>(materials.size()) == materials.size()) );\n\n osg::TriangleFunctor<store_triangle> tf;\n tf.init( triangles_, normals_, materials_.size() == 0 ? 0 : static_cast<unsigned>(materials_.size() - 1) );\n drawable->accept(tf);\n }\n }\n\n base_type::traverse(geode);\n }\n\nprivate:\n\n triangle_list& triangles_;\n normal_list& normals_;\n material_list& materials_;\n\n};\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Private implementation\n\/\/\n\nstruct Visionaray::impl\n{\n impl()\n {\n }\n\n triangle_list triangles;\n normal_list normals;\n material_list materials;\n host_bvh_type host_bvh;\n host_sched_type host_sched;\n cpu_buffer_rt host_rt;\n\n recti viewport;\n\n osg::ref_ptr<osg::Geode> geode;\n};\n\n\nVisionaray::Visionaray()\n : impl_(new impl)\n{\n setSupportsDisplayList(false);\n}\n\nVisionaray::Visionaray(Visionaray const& rhs, osg::CopyOp const& op)\n : Drawable(rhs, op)\n , impl_(new impl)\n{\n setSupportsDisplayList(false);\n}\n\nVisionaray::~Visionaray()\n{\n opencover::cover->getObjectsRoot()->removeChild(impl_->geode);\n}\n\nbool Visionaray::init()\n{\n using namespace osg;\n\n opencover::VRViewer::instance()->culling(false);\n\n std::cout << \"Init Visionaray Plugin!!\" << std::endl;\n\n ref_ptr<osg::StateSet> state = new osg::StateSet();\n state->setGlobalDefaults();\n\n impl_->geode = new osg::Geode;\n impl_->geode->setName(\"Visionaray\");\n impl_->geode->setStateSet(state);\n impl_->geode->addDrawable(this);\n\n opencover::cover->getScene()->addChild(impl_->geode);\n\n return true;\n}\n\nvoid Visionaray::preFrame()\n{\n}\n\nvoid Visionaray::expandBoundingSphere(osg::BoundingSphere &bs)\n{\n aabb bounds( vec3(std::numeric_limits<float>::max()), -vec3(std::numeric_limits<float>::max()) );\n for (auto const& tri : impl_->triangles)\n {\n auto v1 = tri.v1;\n auto v2 = tri.v1 + tri.e1;\n auto v3 = tri.v1 + tri.e2;\n\n bounds = combine(bounds, aabb(v1, v1));\n bounds = combine(bounds, aabb(v2, v2));\n bounds = combine(bounds, aabb(v3, v3));\n }\n\n auto c = bounds.center();\n osg::BoundingSphere::vec_type center(c.x, c.y, c.z);\n osg::BoundingSphere::value_type radius = length( c - bounds.min );\n bs.set(center, radius);\n}\n\nvoid Visionaray::drawImplementation(osg::RenderInfo&) const\n{\n \/\/ TODO?\n\n static bool glewed = false;\n\n if (!glewed)\n {\n glewed = glewInit() == GLEW_OK;\n }\n\n\n \/\/ Scene data\n\n if (impl_->triangles.size() == 0)\n {\n \/\/ TODO: no dynamic scenes for now :(\n get_scene_visitor visitor(impl_->triangles, impl_->normals, impl_->materials,\n osg::NodeVisitor::TRAVERSE_ALL_CHILDREN);\n visitor.apply(*opencover::cover->getObjectsRoot());\n\n if (impl_->triangles.size() == 0)\n {\n return;\n }\n\n if (impl_->materials.size() == 0)\n {\n phong<float> m;\n m.set_cd( vec3(0.8f, 0.8f, 0.8f) );\n m.set_kd( 1.0f );\n m.set_ks( 1.0f );\n m.set_specular_exp( 32.0f );\n impl_->materials.push_back(m);\n }\n\n impl_->host_bvh = build<host_bvh_type>(impl_->triangles.data(), impl_->triangles.size());\n\n opencover::cover->getObjectsRoot()->setNodeMask\n (\n opencover::cover->getObjectsRoot()->getNodeMask()\n & ~opencover::VRViewer::instance()->getCullMask()\n );\n }\n\n\n \/\/ Sched params\n\n auto osg_cam = opencover::coVRConfig::instance()->channels[0].camera;\n\n auto t = opencover::cover->getXformMat();\n auto s = opencover::cover->getObjectsScale()->getMatrix();\n \/\/ TODO: understand COVER API..\n\/\/ auto v = opencover::cover->getViewerMat();\n auto v = opencover::coVRConfig::instance()->channels[0].rightView;\n auto osg_view_matrix = s * t * v;\n auto osg_proj_matrix = opencover::coVRConfig::instance()->channels[0].rightProj;\n auto osg_viewport = osg_cam->getViewport();\n\n float view[16];\n float proj[16];\n\n std::copy(osg_view_matrix.ptr(), osg_view_matrix.ptr() + 16, view);\n std::copy(osg_proj_matrix.ptr(), osg_proj_matrix.ptr() + 16, proj);\n\n mat4 view_matrix(view);\n mat4 proj_matrix(proj);\n recti viewport(osg_viewport->x(), osg_viewport->y(), osg_viewport->width(), osg_viewport->height());\n\n auto sparams = make_sched_params<pixel_sampler::uniform_type>( view_matrix, proj_matrix, viewport, impl_->host_rt );\n\n if (impl_->viewport != viewport)\n {\n impl_->host_rt.resize(viewport[2], viewport[3]);\n impl_->viewport = viewport;\n }\n\n \/\/ Kernel params\n\n aligned_vector<host_bvh_type::bvh_ref> host_primitives;\n host_primitives.push_back(impl_->host_bvh.ref());\n\n vec4 lpos;\n glGetLightfv(GL_LIGHT0, GL_POSITION, lpos.data());\n\n aligned_vector<point_light<float>> lights;\n vec3 light0_pos = (inverse(view_matrix) * lpos).xyz();\n lights.push_back({ light0_pos });\n\n\n auto kparams = make_params\n (\n host_primitives.data(),\n host_primitives.data() + host_primitives.size(),\n impl_->normals.data(),\n impl_->materials.data(),\n lights.data(),\n lights.data() + lights.size()\n );\n\n \/\/ Render\n\n auto kern = simple::kernel<decltype(kparams)>();\n kern.params = kparams;\n impl_->host_sched.frame(kern, sparams);\n\n \/\/ TODO: generate depth buffer and use RGB render target\n glDepthMask(GL_FALSE);\n glPixelTransferf(GL_ALPHA_SCALE, 0.0f);\n\n impl_->host_rt.display_color_buffer();\n}\n\n}} \/\/ namespace visionaray::cover\n\nCOVERPLUGIN(visionaray::cover::Visionaray)\n<commit_msg>Fix debug build<commit_after>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <cassert>\n\n#include <algorithm>\n#include <iostream>\n#include <limits>\n#include <ostream>\n\n#include <GL\/glew.h>\n\n#include <osg\/io_utils>\n#include <osg\/Material>\n#include <osg\/MatrixTransform>\n#include <osg\/StateSet>\n#include <osg\/TriangleFunctor>\n\n#include <cover\/coVRConfig.h>\n#include <cover\/coVRPluginSupport.h>\n#include <cover\/VRViewer.h>\n\n#include <visionaray\/detail\/aligned_vector.h>\n#include <visionaray\/math\/math.h>\n#include <visionaray\/bvh.h>\n#include <visionaray\/kernels.h>\n#include <visionaray\/point_light.h>\n#include <visionaray\/render_target.h>\n#include <visionaray\/scheduler.h>\n\n#include \"visionaray_plugin.h\"\n\nnamespace visionaray { namespace cover {\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Type definitions\n\/\/\n\nusing triangle_type = basic_triangle<3, float>;\nusing triangle_list = aligned_vector<triangle_type>;\nusing normal_list = aligned_vector<vec3>;\nusing material_list = aligned_vector<phong<float>>;\n\nusing host_ray_type = basic_ray<simd::float4>;\nusing host_bvh_type = bvh<triangle_type>;\nusing host_sched_type = tiled_sched<host_ray_type>;\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Functor that stores triangles from osg::Drawable\n\/\/\n\nclass store_triangle\n{\npublic:\n\n store_triangle() : triangles_(nullptr) {}\n\n void init(triangle_list& tris, normal_list& norms, unsigned geom_id)\n {\n triangles_ = &tris;\n normals_ = &norms;\n geom_id_ = geom_id;\n }\n\n void operator()(osg::Vec3 const& v1, osg::Vec3 const& v2, osg::Vec3 const& v3, bool) const\n {\n assert( triangles_ && normals_ );\n\n triangle_type tri;\n tri.prim_id = static_cast<unsigned>(triangles_->size());\n tri.geom_id = geom_id_;\n tri.v1 = vec3(v1.x(), v1.y(), v1.z());\n tri.e1 = vec3(v2.x(), v2.y(), v2.z()) - tri.v1;\n tri.e2 = vec3(v3.x(), v3.y(), v3.z()) - tri.v1;\n triangles_->push_back(tri);\n\n normals_->push_back( normalize(cross(tri.e1, tri.e2)) );\n\n assert( triangles_->size() == normals_->size() );\n }\n\nprivate:\n\n \/\/ Store pointers because osg::TriangleFunctor is shitty..\n triangle_list* triangles_;\n normal_list* normals_;\n unsigned geom_id_;\n\n};\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Visitor to acquire scene data\n\/\/\n\nclass get_scene_visitor : public osg::NodeVisitor\n{\npublic:\n\n using base_type = osg::NodeVisitor;\n using base_type::apply;\n\n get_scene_visitor(triangle_list& tris, normal_list& norms, material_list& mats, TraversalMode tm)\n : base_type(tm)\n , triangles_(tris)\n , normals_(norms)\n , materials_(mats)\n {\n }\n\n void apply(osg::Geode& geode)\n {\n for (size_t i = 0; i < geode.getNumDrawables(); ++i)\n {\n auto drawable = geode.getDrawable(i);\n if (drawable)\n {\n auto set = drawable->getOrCreateStateSet();\n auto attr = set->getAttribute(osg::StateAttribute::MATERIAL);\n auto mat = dynamic_cast<osg::Material*>(attr);\n\n if (mat)\n {\n auto cd = mat->getDiffuse(osg::Material::Face::FRONT);\n auto cs = mat->getSpecular(osg::Material::Face::FRONT);\n\n phong<float> vsnray_mat;\n vsnray_mat.set_cd( vec3(cd.x(), cd.y(), cd.z()) );\n vsnray_mat.set_kd( 1.0f );\n vsnray_mat.set_ks( cs.x() ); \/\/ TODO: e.g. luminance?\n vsnray_mat.set_specular_exp( mat->getShininess(osg::Material::Face::FRONT) );\n materials_.push_back(vsnray_mat);\n }\n\n assert( static_cast<material_list::size_type>(static_cast<unsigned>(materials_.size()) == materials_.size()) );\n\n osg::TriangleFunctor<store_triangle> tf;\n tf.init( triangles_, normals_, materials_.size() == 0 ? 0 : static_cast<unsigned>(materials_.size() - 1) );\n drawable->accept(tf);\n }\n }\n\n base_type::traverse(geode);\n }\n\nprivate:\n\n triangle_list& triangles_;\n normal_list& normals_;\n material_list& materials_;\n\n};\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Private implementation\n\/\/\n\nstruct Visionaray::impl\n{\n impl()\n {\n }\n\n triangle_list triangles;\n normal_list normals;\n material_list materials;\n host_bvh_type host_bvh;\n host_sched_type host_sched;\n cpu_buffer_rt host_rt;\n\n recti viewport;\n\n osg::ref_ptr<osg::Geode> geode;\n};\n\n\nVisionaray::Visionaray()\n : impl_(new impl)\n{\n setSupportsDisplayList(false);\n}\n\nVisionaray::Visionaray(Visionaray const& rhs, osg::CopyOp const& op)\n : Drawable(rhs, op)\n , impl_(new impl)\n{\n setSupportsDisplayList(false);\n}\n\nVisionaray::~Visionaray()\n{\n opencover::cover->getObjectsRoot()->removeChild(impl_->geode);\n}\n\nbool Visionaray::init()\n{\n using namespace osg;\n\n opencover::VRViewer::instance()->culling(false);\n\n std::cout << \"Init Visionaray Plugin!!\" << std::endl;\n\n ref_ptr<osg::StateSet> state = new osg::StateSet();\n state->setGlobalDefaults();\n\n impl_->geode = new osg::Geode;\n impl_->geode->setName(\"Visionaray\");\n impl_->geode->setStateSet(state);\n impl_->geode->addDrawable(this);\n\n opencover::cover->getScene()->addChild(impl_->geode);\n\n return true;\n}\n\nvoid Visionaray::preFrame()\n{\n}\n\nvoid Visionaray::expandBoundingSphere(osg::BoundingSphere &bs)\n{\n aabb bounds( vec3(std::numeric_limits<float>::max()), -vec3(std::numeric_limits<float>::max()) );\n for (auto const& tri : impl_->triangles)\n {\n auto v1 = tri.v1;\n auto v2 = tri.v1 + tri.e1;\n auto v3 = tri.v1 + tri.e2;\n\n bounds = combine(bounds, aabb(v1, v1));\n bounds = combine(bounds, aabb(v2, v2));\n bounds = combine(bounds, aabb(v3, v3));\n }\n\n auto c = bounds.center();\n osg::BoundingSphere::vec_type center(c.x, c.y, c.z);\n osg::BoundingSphere::value_type radius = length( c - bounds.min );\n bs.set(center, radius);\n}\n\nvoid Visionaray::drawImplementation(osg::RenderInfo&) const\n{\n \/\/ TODO?\n\n static bool glewed = false;\n\n if (!glewed)\n {\n glewed = glewInit() == GLEW_OK;\n }\n\n\n \/\/ Scene data\n\n if (impl_->triangles.size() == 0)\n {\n \/\/ TODO: no dynamic scenes for now :(\n get_scene_visitor visitor(impl_->triangles, impl_->normals, impl_->materials,\n osg::NodeVisitor::TRAVERSE_ALL_CHILDREN);\n visitor.apply(*opencover::cover->getObjectsRoot());\n\n if (impl_->triangles.size() == 0)\n {\n return;\n }\n\n if (impl_->materials.size() == 0)\n {\n phong<float> m;\n m.set_cd( vec3(0.8f, 0.8f, 0.8f) );\n m.set_kd( 1.0f );\n m.set_ks( 1.0f );\n m.set_specular_exp( 32.0f );\n impl_->materials.push_back(m);\n }\n\n impl_->host_bvh = build<host_bvh_type>(impl_->triangles.data(), impl_->triangles.size());\n\n opencover::cover->getObjectsRoot()->setNodeMask\n (\n opencover::cover->getObjectsRoot()->getNodeMask()\n & ~opencover::VRViewer::instance()->getCullMask()\n );\n }\n\n\n \/\/ Sched params\n\n auto osg_cam = opencover::coVRConfig::instance()->channels[0].camera;\n\n auto t = opencover::cover->getXformMat();\n auto s = opencover::cover->getObjectsScale()->getMatrix();\n \/\/ TODO: understand COVER API..\n\/\/ auto v = opencover::cover->getViewerMat();\n auto v = opencover::coVRConfig::instance()->channels[0].rightView;\n auto osg_view_matrix = s * t * v;\n auto osg_proj_matrix = opencover::coVRConfig::instance()->channels[0].rightProj;\n auto osg_viewport = osg_cam->getViewport();\n\n float view[16];\n float proj[16];\n\n std::copy(osg_view_matrix.ptr(), osg_view_matrix.ptr() + 16, view);\n std::copy(osg_proj_matrix.ptr(), osg_proj_matrix.ptr() + 16, proj);\n\n mat4 view_matrix(view);\n mat4 proj_matrix(proj);\n recti viewport(osg_viewport->x(), osg_viewport->y(), osg_viewport->width(), osg_viewport->height());\n\n auto sparams = make_sched_params<pixel_sampler::uniform_type>( view_matrix, proj_matrix, viewport, impl_->host_rt );\n\n if (impl_->viewport != viewport)\n {\n impl_->host_rt.resize(viewport[2], viewport[3]);\n impl_->viewport = viewport;\n }\n\n \/\/ Kernel params\n\n aligned_vector<host_bvh_type::bvh_ref> host_primitives;\n host_primitives.push_back(impl_->host_bvh.ref());\n\n vec4 lpos;\n glGetLightfv(GL_LIGHT0, GL_POSITION, lpos.data());\n\n aligned_vector<point_light<float>> lights;\n vec3 light0_pos = (inverse(view_matrix) * lpos).xyz();\n lights.push_back({ light0_pos });\n\n\n auto kparams = make_params\n (\n host_primitives.data(),\n host_primitives.data() + host_primitives.size(),\n impl_->normals.data(),\n impl_->materials.data(),\n lights.data(),\n lights.data() + lights.size()\n );\n\n \/\/ Render\n\n auto kern = simple::kernel<decltype(kparams)>();\n kern.params = kparams;\n impl_->host_sched.frame(kern, sparams);\n\n \/\/ TODO: generate depth buffer and use RGB render target\n glDepthMask(GL_FALSE);\n glPixelTransferf(GL_ALPHA_SCALE, 0.0f);\n\n impl_->host_rt.display_color_buffer();\n}\n\n}} \/\/ namespace visionaray::cover\n\nCOVERPLUGIN(visionaray::cover::Visionaray)\n<|endoftext|>"} {"text":"<commit_before>#ifdef TREE_HPP\n\n#include <cstddef>\n#include <iostream>\n\ntemplate < class T >\nTree< T >::Tree() {\n this->root = nullptr;\n}\n\ntemplate < class T >\nvoid Tree< T >::push( const T value ) {\n if( this->root == nullptr ) {\n this->root = new Node< T >( value, nullptr, nullptr );\n } else {\n push( &( this->root ), value );\n }\n}\n\ntemplate < class T >\nvoid Tree< T >::push( Node< T >** node, T value ) {\n if( node == nullptr ) {\n *node = new Node< T >( value, nullptr, nullptr );\n return;\n\n } else if( value < ( *node )->getValue() ) {\n push( &( ( *node )->left ), value );\n } else if( value > ( *node )->getValue() ) {\n push( &( ( *node )->right ), value );\n } else {\n throw std::runtime_error( \"Duplicate value\" );\n }\n}\n\n#endif<commit_msg>Correção do método push<commit_after>#ifdef TREE_HPP\n\n#include <cstddef>\n#include <iostream>\n\ntemplate < class T >\nTree< T >::Tree() {\n this->root = nullptr;\n}\n\ntemplate < class T >\nvoid Tree< T >::push( const T value ) {\n push( &( this->root ), value );\n}\n\ntemplate < class T >\nvoid Tree< T >::push( Node< T >** node, T value ) {\n if( *node == nullptr ) {\n *node = new Node< T >( value, nullptr, nullptr );\n return;\n\n } else if( value < ( *node )->getValue() ) {\n push( &( ( *node )->left ), value );\n } else if( value > ( *node )->getValue() ) {\n push( &( ( *node )->right ), value );\n } else {\n throw std::runtime_error( \"Duplicate value\" );\n }\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2004-2015 Cray Inc.\n * Other additional copyright holders may be indicated within.\n *\n * The entirety of this work is licensed under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n *\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#include \"processTokens.h\"\n\n#include \"chapel.tab.h\"\n#include \"countTokens.h\"\n#include \"misc.h\"\n#include \"stringutil.h\"\n#include \"yy.h\"\n\n#include <cstring>\n#include <cctype>\n\nstatic int stringBuffLen = 0;\nstatic int stringLen = 0;\nstatic char* stringBuffer = NULL;\n\n\nstatic void newString(void) {\n stringLen = 0;\n if (stringBuffLen) {\n stringBuffer[stringLen] = '\\0';\n }\n}\n\n\/\/ Returns the hexadecimal character for 0-16.\nstatic char toHex(char c)\n{\n if (0 <= c && c <= 9) return '0' + c;\n else return 'A' + (c - 10);\n}\n\nstatic void addCharMaybeEscape(char c, bool canEscape) {\n int escape = canEscape && !(isascii(c) && isprint(c));\n int charlen = escape ? 4 : 1; \/\/ convert nonasci to \\xNN\n\n if (stringLen+charlen+1 > stringBuffLen) {\n stringBuffLen = 2*(stringBuffLen + charlen);\n stringBuffer = (char*)realloc(stringBuffer, stringBuffLen*sizeof(char));\n }\n\n if (escape) {\n stringBuffer[stringLen++] = '\\\\';\n stringBuffer[stringLen++] = 'x';\n stringBuffer[stringLen++] = toHex(((unsigned char)c) >> 4);\n stringBuffer[stringLen++] = toHex(c & 0xf);\n } else {\n stringBuffer[stringLen++] = c;\n }\n stringBuffer[stringLen] = '\\0';\n}\n\nstatic inline void addCharString(char c) {\n addCharMaybeEscape(c, true);\n}\n\nstatic inline void addChar(char c) {\n addCharMaybeEscape(c, false);\n}\n\nstatic void addString(const char* str) {\n int i;\n for( i = 0; str[i]; i++ ) addChar(str[i]);\n}\n\nvoid processNewline(void) {\n chplLineno++;\n yylloc.first_column = yylloc.last_column = 0;\n yylloc.first_line = yylloc.last_line = chplLineno;\n countNewline();\n}\n\n\nchar* eatStringLiteral(const char* startChar) {\n register int c;\n const char startCh = *startChar;\n \n newString();\n while ((c = getNextYYChar()) != startCh && c != 0) {\n if (c == '\\n')\n {\n yytext[0] = '\\0'; yyerror(\n \"end-of-line in a string literal without a preceeding backslash\");\n } else {\n if (startCh == '\\'' && c == '\\\"') {\n addCharString('\\\\');\n }\n addCharString(c);\n }\n if (c == '\\\\') {\n c = getNextYYChar();\n if (c == '\\n')\n {\n processNewline(); addCharString('n');\n } else if (c != 0) {\n addCharString(c);\n }\n else\n break;\n }\n } \/* eat up string *\/\n if (c == 0) {\n yyerror(\"EOF in string\");\n }\n return stringBuffer;\n}\n\n\nvoid processSingleLineComment(void) {\n register int c;\n\n newString();\n countCommentLine();\n while (1) {\n while ( (c = getNextYYChar()) != '\\n' && c != 0) {\n addChar(c);\n } \/* eat up text of comment *\/\n countSingleLineComment(stringBuffer);\n if (c != 0) {\n processNewline();\n }\n break;\n }\n}\n\n\nvoid processMultiLineComment() {\n int c;\n int lastc;\n int lastlastc;\n int depth;\n\n c = 0;\n lastc = 0;\n depth = 1;\n\n newString();\n countCommentLine();\n\n int labelIndex = 0;\n int len = strlen(fDocsCommentLabel);\n if (len >= 2) {\n labelIndex = 2;\n }\n\n std::string wholeComment = \"\";\n \n while (depth > 0) {\n lastlastc = lastc;\n lastc = c;\n c = getNextYYChar();\n if( c == '\\n' ) {\n countMultiLineComment(stringBuffer);\n processNewline();\n if (fDocs && labelIndex == len) {\n wholeComment += stringBuffer;\n wholeComment += '\\n';\n }\n newString();\n countCommentLine();\n } else {\n if ((labelIndex < len) && (labelIndex != -1)) {\n if (c == fDocsCommentLabel[labelIndex]) {\n labelIndex++;\n } else {\n labelIndex = -1;\n }\n }\n addChar(c);\n }\n if( lastc == '*' && c == '\/' && lastlastc != '\/' ) { \/\/ close comment\n depth--;\n } else if( lastc == '\/' && c == '*' ) { \/\/ start nested\n depth++;\n } else if( c == 0 ) {\n yyerror( \"EOF in comment\" );\n }\n }\n\n \/\/ back up two to not print *\/ again.\n if( stringLen >= 2 ) stringLen -= 2;\n \/\/ back up further if the user has specified a special form of commenting\n if (len > 2 && labelIndex == len) stringLen -= (len - 2);\n stringBuffer[stringLen] = '\\0';\n \n \/\/ Saves the comment grabbed to the comment field of the location struct,\n \/\/ for use when the --docs flag is implemented\n if (fDocs && labelIndex == len) {\n wholeComment += stringBuffer;\n if (len > 2) {\n len -= 2;\n wholeComment = wholeComment.substr(len);\n \/\/ Trim the start of the string if the user has specified a special form\n \/\/ of commenting\n }\n\n \/\/ Also, only need to fix indentation failure when the comment matters\n size_t location = wholeComment.find(\"\\\\x09\");\n while (location != std::string::npos) {\n wholeComment = wholeComment.substr(0, location) + wholeComment.substr(location + 4);\n wholeComment.insert(location, \"\\t\");\n location = wholeComment.find(\"\\\\x09\");\n }\n yylloc.comment = (char *)astr(wholeComment.c_str());\n }\n\n countMultiLineComment(stringBuffer);\n newString();\n}\n\nchar* eatExternCode() {\n \/\/ Note - when the lexer calls this function, it has already\n \/\/ consumed the first {\n int depth = 1;\n int c = 0, lastc = 0;\n const int in_code = 0;\n const int in_single_quote = 1;\n const int in_single_quote_backslash = 2;\n const int in_double_quote = 3;\n const int in_double_quote_backslash = 4;\n const int in_single_line_comment = 5;\n const int in_single_line_comment_backslash = 6;\n const int in_multi_line_comment = 7;\n int state = 0;\n\n newString();\n\n \/\/ First, store the line information.\n addString(\"#line \");\n addString(istr(chplLineno));\n addString(\" \\\"\");\n addString(yyfilename);\n addString(\"\\\" \");\n addString(\"\\n\");\n\n \/\/ Now, append the C code until we get to a }.\n while (depth > 0) {\n lastc = c;\n c = getNextYYChar();\n \n if (c == 0) {\n switch (state) {\n case in_code:\n \/\/ there was no match to the {\n yyerror(\"Missing } in extern block\");\n break;\n case in_single_quote:\n case in_single_quote_backslash:\n yyerror(\"Runaway \\'string\\' in extern block\");\n break;\n case in_double_quote:\n case in_double_quote_backslash:\n yyerror(\"Runaway \\\"string\\\" in extern block\");\n break;\n case in_single_line_comment: \n yyerror(\"Missing newline after extern block \/\/ comment\");\n break;\n case in_multi_line_comment: \n yyerror(\"Runaway \/* comment *\/ in extern block\");\n break;\n }\n break;\n }\n\n addChar(c);\n\n if( c == '\\n' ) processNewline();\n\n \/\/ Now update state (are we in a comment? a string?)\n switch (state) {\n case in_code:\n if( c == '\\'' ) state = in_single_quote;\n else if( c == '\"' ) state = in_double_quote;\n else if( lastc == '\/' && c == '\/' ) state = in_single_line_comment;\n else if( lastc == '\/' && c == '*' ) state = in_multi_line_comment;\n else if( c == '{' ) depth++;\n else if( c == '}' ) depth--;\n break;\n case in_single_quote:\n if( c == '\\\\' ) state = in_single_quote_backslash;\n else if( c == '\\'' ) state = in_code;\n break;\n case in_single_quote_backslash:\n state = in_single_quote;\n break;\n case in_double_quote:\n if( c == '\\\\' ) state = in_double_quote_backslash;\n else if( c == '\"' ) state = in_code;\n break;\n case in_double_quote_backslash:\n state = in_double_quote;\n break;\n case in_single_line_comment: \n if( c == '\\n' ) state = in_code;\n break;\n case in_single_line_comment_backslash: \n if( c == ' ' || c == '\\t' || c == '\\n' )\n state = in_single_line_comment_backslash;\n else state = in_single_line_comment;\n break;\n case in_multi_line_comment: \n if( lastc == '*' && c == '\/' ) state = in_code;\n break;\n }\n }\n\n \/\/save the C String\n \/\/eliminate the final '{'\n if (stringLen >=1) stringLen -= 1;\n stringBuffer[stringLen] = '\\0';\n\n return stringBuffer;\n}\n\nvoid processWhitespace(const char* tabOrSpace) {\n \/\/ might eventually want to keep track of column numbers and do\n \/\/ something here\n}\n\n\nvoid processInvalidToken() {\n yyerror(\"Invalid token\");\n}\n<commit_msg>processTokens.cpp: yy.h must preceed chapel.tab.h for Bison 2.3<commit_after>\/*\n * Copyright 2004-2015 Cray Inc.\n * Other additional copyright holders may be indicated within.\n *\n * The entirety of this work is licensed under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n *\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#include \"processTokens.h\"\n\n#include \"countTokens.h\"\n#include \"misc.h\"\n#include \"stringutil.h\"\n\n#include \"yy.h\"\n#include \"chapel.tab.h\"\n\n#include <cstring>\n#include <cctype>\n\nstatic int stringBuffLen = 0;\nstatic int stringLen = 0;\nstatic char* stringBuffer = NULL;\n\n\nstatic void newString(void) {\n stringLen = 0;\n if (stringBuffLen) {\n stringBuffer[stringLen] = '\\0';\n }\n}\n\n\/\/ Returns the hexadecimal character for 0-16.\nstatic char toHex(char c)\n{\n if (0 <= c && c <= 9) return '0' + c;\n else return 'A' + (c - 10);\n}\n\nstatic void addCharMaybeEscape(char c, bool canEscape) {\n int escape = canEscape && !(isascii(c) && isprint(c));\n int charlen = escape ? 4 : 1; \/\/ convert nonasci to \\xNN\n\n if (stringLen+charlen+1 > stringBuffLen) {\n stringBuffLen = 2*(stringBuffLen + charlen);\n stringBuffer = (char*)realloc(stringBuffer, stringBuffLen*sizeof(char));\n }\n\n if (escape) {\n stringBuffer[stringLen++] = '\\\\';\n stringBuffer[stringLen++] = 'x';\n stringBuffer[stringLen++] = toHex(((unsigned char)c) >> 4);\n stringBuffer[stringLen++] = toHex(c & 0xf);\n } else {\n stringBuffer[stringLen++] = c;\n }\n stringBuffer[stringLen] = '\\0';\n}\n\nstatic inline void addCharString(char c) {\n addCharMaybeEscape(c, true);\n}\n\nstatic inline void addChar(char c) {\n addCharMaybeEscape(c, false);\n}\n\nstatic void addString(const char* str) {\n int i;\n for( i = 0; str[i]; i++ ) addChar(str[i]);\n}\n\nvoid processNewline(void) {\n chplLineno++;\n yylloc.first_column = yylloc.last_column = 0;\n yylloc.first_line = yylloc.last_line = chplLineno;\n countNewline();\n}\n\n\nchar* eatStringLiteral(const char* startChar) {\n register int c;\n const char startCh = *startChar;\n \n newString();\n while ((c = getNextYYChar()) != startCh && c != 0) {\n if (c == '\\n')\n {\n yytext[0] = '\\0'; yyerror(\n \"end-of-line in a string literal without a preceeding backslash\");\n } else {\n if (startCh == '\\'' && c == '\\\"') {\n addCharString('\\\\');\n }\n addCharString(c);\n }\n if (c == '\\\\') {\n c = getNextYYChar();\n if (c == '\\n')\n {\n processNewline(); addCharString('n');\n } else if (c != 0) {\n addCharString(c);\n }\n else\n break;\n }\n } \/* eat up string *\/\n if (c == 0) {\n yyerror(\"EOF in string\");\n }\n return stringBuffer;\n}\n\n\nvoid processSingleLineComment(void) {\n register int c;\n\n newString();\n countCommentLine();\n while (1) {\n while ( (c = getNextYYChar()) != '\\n' && c != 0) {\n addChar(c);\n } \/* eat up text of comment *\/\n countSingleLineComment(stringBuffer);\n if (c != 0) {\n processNewline();\n }\n break;\n }\n}\n\n\nvoid processMultiLineComment() {\n int c;\n int lastc;\n int lastlastc;\n int depth;\n\n c = 0;\n lastc = 0;\n depth = 1;\n\n newString();\n countCommentLine();\n\n int labelIndex = 0;\n int len = strlen(fDocsCommentLabel);\n if (len >= 2) {\n labelIndex = 2;\n }\n\n std::string wholeComment = \"\";\n \n while (depth > 0) {\n lastlastc = lastc;\n lastc = c;\n c = getNextYYChar();\n if( c == '\\n' ) {\n countMultiLineComment(stringBuffer);\n processNewline();\n if (fDocs && labelIndex == len) {\n wholeComment += stringBuffer;\n wholeComment += '\\n';\n }\n newString();\n countCommentLine();\n } else {\n if ((labelIndex < len) && (labelIndex != -1)) {\n if (c == fDocsCommentLabel[labelIndex]) {\n labelIndex++;\n } else {\n labelIndex = -1;\n }\n }\n addChar(c);\n }\n if( lastc == '*' && c == '\/' && lastlastc != '\/' ) { \/\/ close comment\n depth--;\n } else if( lastc == '\/' && c == '*' ) { \/\/ start nested\n depth++;\n } else if( c == 0 ) {\n yyerror( \"EOF in comment\" );\n }\n }\n\n \/\/ back up two to not print *\/ again.\n if( stringLen >= 2 ) stringLen -= 2;\n \/\/ back up further if the user has specified a special form of commenting\n if (len > 2 && labelIndex == len) stringLen -= (len - 2);\n stringBuffer[stringLen] = '\\0';\n \n \/\/ Saves the comment grabbed to the comment field of the location struct,\n \/\/ for use when the --docs flag is implemented\n if (fDocs && labelIndex == len) {\n wholeComment += stringBuffer;\n if (len > 2) {\n len -= 2;\n wholeComment = wholeComment.substr(len);\n \/\/ Trim the start of the string if the user has specified a special form\n \/\/ of commenting\n }\n\n \/\/ Also, only need to fix indentation failure when the comment matters\n size_t location = wholeComment.find(\"\\\\x09\");\n while (location != std::string::npos) {\n wholeComment = wholeComment.substr(0, location) + wholeComment.substr(location + 4);\n wholeComment.insert(location, \"\\t\");\n location = wholeComment.find(\"\\\\x09\");\n }\n yylloc.comment = (char *)astr(wholeComment.c_str());\n }\n\n countMultiLineComment(stringBuffer);\n newString();\n}\n\nchar* eatExternCode() {\n \/\/ Note - when the lexer calls this function, it has already\n \/\/ consumed the first {\n int depth = 1;\n int c = 0, lastc = 0;\n const int in_code = 0;\n const int in_single_quote = 1;\n const int in_single_quote_backslash = 2;\n const int in_double_quote = 3;\n const int in_double_quote_backslash = 4;\n const int in_single_line_comment = 5;\n const int in_single_line_comment_backslash = 6;\n const int in_multi_line_comment = 7;\n int state = 0;\n\n newString();\n\n \/\/ First, store the line information.\n addString(\"#line \");\n addString(istr(chplLineno));\n addString(\" \\\"\");\n addString(yyfilename);\n addString(\"\\\" \");\n addString(\"\\n\");\n\n \/\/ Now, append the C code until we get to a }.\n while (depth > 0) {\n lastc = c;\n c = getNextYYChar();\n \n if (c == 0) {\n switch (state) {\n case in_code:\n \/\/ there was no match to the {\n yyerror(\"Missing } in extern block\");\n break;\n case in_single_quote:\n case in_single_quote_backslash:\n yyerror(\"Runaway \\'string\\' in extern block\");\n break;\n case in_double_quote:\n case in_double_quote_backslash:\n yyerror(\"Runaway \\\"string\\\" in extern block\");\n break;\n case in_single_line_comment: \n yyerror(\"Missing newline after extern block \/\/ comment\");\n break;\n case in_multi_line_comment: \n yyerror(\"Runaway \/* comment *\/ in extern block\");\n break;\n }\n break;\n }\n\n addChar(c);\n\n if( c == '\\n' ) processNewline();\n\n \/\/ Now update state (are we in a comment? a string?)\n switch (state) {\n case in_code:\n if( c == '\\'' ) state = in_single_quote;\n else if( c == '\"' ) state = in_double_quote;\n else if( lastc == '\/' && c == '\/' ) state = in_single_line_comment;\n else if( lastc == '\/' && c == '*' ) state = in_multi_line_comment;\n else if( c == '{' ) depth++;\n else if( c == '}' ) depth--;\n break;\n case in_single_quote:\n if( c == '\\\\' ) state = in_single_quote_backslash;\n else if( c == '\\'' ) state = in_code;\n break;\n case in_single_quote_backslash:\n state = in_single_quote;\n break;\n case in_double_quote:\n if( c == '\\\\' ) state = in_double_quote_backslash;\n else if( c == '\"' ) state = in_code;\n break;\n case in_double_quote_backslash:\n state = in_double_quote;\n break;\n case in_single_line_comment: \n if( c == '\\n' ) state = in_code;\n break;\n case in_single_line_comment_backslash: \n if( c == ' ' || c == '\\t' || c == '\\n' )\n state = in_single_line_comment_backslash;\n else state = in_single_line_comment;\n break;\n case in_multi_line_comment: \n if( lastc == '*' && c == '\/' ) state = in_code;\n break;\n }\n }\n\n \/\/save the C String\n \/\/eliminate the final '{'\n if (stringLen >=1) stringLen -= 1;\n stringBuffer[stringLen] = '\\0';\n\n return stringBuffer;\n}\n\nvoid processWhitespace(const char* tabOrSpace) {\n \/\/ might eventually want to keep track of column numbers and do\n \/\/ something here\n}\n\n\nvoid processInvalidToken() {\n yyerror(\"Invalid token\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\nfontResource.cpp\r\nThis file is part of:\r\nGAME PENCIL ENGINE\r\nhttps:\/\/create.pawbyte.com\r\nCopyright (c) 2014-2020 Nathan Hurde, Chase Lee.\r\n\r\nCopyright (c) 2014-2020 PawByte LLC.\r\nCopyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page )\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the “Software”), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\r\n-Game Pencil Engine <https:\/\/create.pawbyte.com>\r\n\r\n\r\n*\/\r\n\r\n#include \"font_resource.h\"\r\n#include \"gpe_editor_settings.h\"\r\n\r\n\/\/\r\n\r\nstd::string SUPPORTED_FONT_EXT[FONT_FILE_TYPES];\r\n\r\nfontResource::fontResource(GPE_GeneralResourceContainer * pFolder)\r\n{\r\n projectParentFolder = pFolder;\r\n fontInEditor = NULL;\r\n resourceFileName = \" \";\r\n for( int i = 0; i < FONT_FILE_TYPES; i++)\r\n {\r\n storedFontFileNames[i] = \"\";\r\n }\r\n resourceName = \" \";\r\n fontId = -1;\r\n fontType = -1;\r\n fontWidth = 32;\r\n fontHeight = 32;\r\n fontSize = 12;\r\n fontSizeField = new GPE_TextInputNumber(\"Range: 8 to 512\",true,2,256);\r\n fontPreviewTextField = new GPE_TextInputBasic(\"ABCD012456789\",\"Previewed Text\");\r\n fontPreviewTextField->set_label(\"Preview Text\");\r\n fontSizeField->set_string(\"12\");\r\n fontSizeField->set_label(\"Font Size\");\r\n if( saveResourceButton!=NULL)\r\n {\r\n fontSizeField->set_coords(-1,saveResourceButton->get_ypos()+saveResourceButton->get_height()+GENERAL_GPE_GUI_PADDING+48);\r\n }\r\n fontTypeButtonController = new GPE_RadioButtonControllerBasic(\"Font Type\", true,1);\r\n fontTypeButtonController->add_opton(\"Normal Font\");\r\n fontTypeButtonController->add_opton(\"MonoSpace Font\");\r\n loadResourceButton->set_name(\"Load Custom Font\");\r\n saveResourceButton->set_width( loadResourceButton->get_width() );\r\n fontFamilyName = \"\";\r\n\r\n openExternalEditorButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+\"resources\/gfx\/iconpacks\/fontawesome\/rocket.png\",\"Use External Editor\" );\r\n}\r\n\r\nfontResource::~fontResource()\r\n{\r\n if( fontTypeButtonController!=NULL)\r\n {\r\n delete fontTypeButtonController;\r\n fontTypeButtonController = NULL;\r\n }\r\n if( fontPreviewTextField!=NULL)\r\n {\r\n delete fontPreviewTextField;\r\n fontPreviewTextField = NULL;\r\n }\r\n if( fontSizeField!=NULL)\r\n {\r\n delete fontSizeField;\r\n fontSizeField = NULL;\r\n }\r\n if( fontInEditor!=NULL)\r\n {\r\n gfs->close_font(fontInEditor);\r\n fontInEditor= NULL;\r\n }\r\n if( openExternalEditorButton!=NULL)\r\n {\r\n delete openExternalEditorButton;\r\n openExternalEditorButton= NULL;\r\n }\r\n}\r\n\r\nbool fontResource::build_intohtml5_file(std::ofstream * fileTarget, int leftTabAmount)\r\n{\r\n if( fileTarget!=NULL && fileTarget->is_open() )\r\n {\r\n std::string nestedTabsStr = generate_tabs( leftTabAmount );\r\n\r\n *fileTarget << nestedTabsStr << \"var \" << resourceName << \" = GPE.rsm.add_font(\";\r\n *fileTarget << int_to_string (exportBuildGlobalId ) +\",'\";\r\n if( (int)fontFamilyName.size() > 4)\r\n {\r\n *fileTarget << fontFamilyName+\"',\";\r\n }\r\n else\r\n {\r\n *fileTarget << \"Arial',\";\r\n }\r\n for( int i = 0; i < FONT_FILE_TYPES; i++)\r\n {\r\n \/\/*fileTarget << \"'resources\/animations\/\"+get_short_filename (animInEditor->fileName,true )+\"',\";\r\n if( (int)storedFontFileNames[i].size() > 4)\r\n {\r\n *fileTarget << \"'resources\/fonts\/\"+get_short_filename( storedFontFileNames[i],true) << \"',\";\r\n }\r\n else\r\n {\r\n *fileTarget << \"'',\";\r\n }\r\n }\r\n if( fontInEditor==NULL )\r\n {\r\n fontSize = fontSizeField->get_held_number();\r\n }\r\n if( fontSize <=8)\r\n {\r\n fontSize = 8;\r\n }\r\n if( fontSize >=256)\r\n {\r\n fontSize = 256;\r\n }\r\n *fileTarget << int_to_string (fontSize ) +\",\";\r\n\r\n *fileTarget << int_to_string (fontWidth ) +\",\";\r\n *fileTarget << int_to_string (fontHeight ) +\",\";\r\n if( fontTypeButtonController!=NULL)\r\n {\r\n *fileTarget << int_to_string (fontTypeButtonController->get_selected_id() );\r\n }\r\n else\r\n {\r\n *fileTarget << \"0\";\r\n }\r\n\r\n *fileTarget << \");\\n\";\r\n return true;\r\n }\r\n return false;\r\n\r\n}\r\n\r\nbool fontResource::build_css3_file(std::ofstream * fileTarget, int leftTabAmount)\r\n{\r\n if( fileTarget!=NULL && fileTarget->is_open() )\r\n {\r\n std::string nestedTabsStr = generate_tabs( leftTabAmount );\r\n\r\n bool foundHeldFont = false;\r\n for( int i = 0; i < FONT_FILE_TYPES; i++)\r\n {\r\n if( (int)storedFontFileNames[i].size() > 0)\r\n {\r\n foundHeldFont = true;\r\n break;\r\n }\r\n }\r\n if( foundHeldFont)\r\n {\r\n *fileTarget << nestedTabsStr << \"@font-face{\\n\";\r\n *fileTarget << nestedTabsStr << \"font-family: '\"+fontFamilyName+\"';\\n\";\r\n if( (int)storedFontFileNames[FONT_EOT].size() > 0)\r\n {\r\n *fileTarget << nestedTabsStr << \"src: url('..\/resources\/fonts\/\" << get_short_filename(storedFontFileNames[FONT_EOT],true) << \"'),\\n\";\r\n *fileTarget << nestedTabsStr << \"src: url('..\/resources\/fonts\/\" << get_short_filename(storedFontFileNames[FONT_EOT],true ) << \"?#iefix') format('embedded-opentype'),\\n,\";\r\n }\r\n *fileTarget << nestedTabsStr << \"src: local('☺')\";\r\n if( (int)storedFontFileNames[FONT_WOFF].size() > 0)\r\n {\r\n *fileTarget << nestedTabsStr << \",\\n\" << \"url('..\/resources\/fonts\/\" << get_short_filename(storedFontFileNames[FONT_WOFF],true) << \"') format('woff')\";\r\n }\r\n if( (int)storedFontFileNames[FONT_TTF].size() > 0)\r\n {\r\n *fileTarget << nestedTabsStr << \",\\n\" << \"url('..\/resources\/fonts\/\" << get_short_filename(storedFontFileNames[FONT_TTF],true) << \"') format('truetype')\";\r\n }\r\n if( (int)storedFontFileNames[FONT_SVG].size() > 0)\r\n {\r\n *fileTarget << nestedTabsStr << \"\\n\" << \"url('..\/resources\/fonts\/\" << get_short_filename(storedFontFileNames[FONT_SVG],true) << \"#\" << fontFamilyName << \"') format('svg')\";\r\n }\r\n *fileTarget << nestedTabsStr << \";\\n\" << \"font-weight: normal;\\n\";\r\n *fileTarget << nestedTabsStr << \"font-style: normal;\\n\";\r\n *fileTarget << nestedTabsStr << \"}\\n\";\r\n }\r\n }\r\n return false;\r\n}\r\n\r\nbool fontResource::build_intocpp_file(std::ofstream * fileTarget, int leftTabAmount )\r\n{\r\n return true;\r\n}\r\n\r\nvoid fontResource::compile_cpp()\r\n{\r\n\r\n}\r\n\r\nbool fontResource::include_local_files( std::string pBuildDir , int buildType )\r\n{\r\n appendToFile(get_user_settings_folder()+\"resources_check.txt\",get_name() +\"...\");\r\n\r\n bool fontNotCopied = false;\r\n std::string copyFileDestination;\r\n for( int jFontType = 0; jFontType < FONT_FILE_TYPES; jFontType++)\r\n {\r\n if( (int)storedFontFileNames[jFontType].size() > 3 )\r\n {\r\n copyFileDestination = pBuildDir+\"\/resources\/fonts\/\"+get_short_filename(storedFontFileNames[jFontType],true);\r\n if( copy_file( storedFontFileNames[jFontType],copyFileDestination)==false )\r\n {\r\n appendToFile(get_user_settings_folder()+\"resources_check.txt\",\"Unable to copy [\"+storedFontFileNames[jFontType]+\"] to [\"+copyFileDestination+\"]...\");\r\n return fontNotCopied;\r\n }\r\n }\r\n }\r\n\r\n return !fontNotCopied;\r\n}\r\n\r\nvoid fontResource::load_font(std::string newFileName, int newFontSize )\r\n{\r\n if( (int)newFileName.size() > 0)\r\n {\r\n if( newFontSize < 0 && fontSizeField->get_held_number() > 0 )\r\n {\r\n newFontSize = fontSizeField->get_held_number();\r\n }\r\n else if( newFontSize < 0 )\r\n {\r\n newFontSize = 8;\r\n }\r\n else if(newFontSize > 512)\r\n {\r\n newFontSize = 512;\r\n }\r\n fontSizeField->set_string( int_to_string(newFontSize) );\r\n fontSize = newFontSize;\r\n\r\n \/\/Saves the font where possible...\r\n if( get_file_ext(newFileName)==\"eot\" || get_file_ext(newFileName)==\"EOT\" )\r\n {\r\n std::string copyDestinationStr = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+ get_short_filename(newFileName,true);\r\n storedFontFileNames[FONT_EOT] = copyDestinationStr;\r\n copy_file(newFileName.c_str(),copyDestinationStr );\r\n }\r\n else if( get_file_ext(newFileName)==\"svg\" || get_file_ext(newFileName)==\"SVG\" )\r\n {\r\n std::string copyDestinationStr = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+ get_short_filename(newFileName,true);\r\n storedFontFileNames[FONT_SVG] = copyDestinationStr;\r\n copy_file(newFileName.c_str(),copyDestinationStr );\r\n }\r\n else if( get_file_ext(newFileName)==\"otf\" || get_file_ext(newFileName)==\"OTF\" )\r\n {\r\n if( fontInEditor!=NULL)\r\n {\r\n gfs->close_font(fontInEditor);\r\n fontInEditor = NULL;\r\n }\r\n fontInEditorFileName = get_short_filename(newFileName,true);\r\n std::string copyDestinationStr = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+ fontInEditorFileName;\r\n copy_file(newFileName.c_str(),copyDestinationStr );\r\n\r\n fontInEditor = gfs->open_font(copyDestinationStr.c_str(),newFontSize,false,\"Custom Font\");\r\n fontFamilyName =fontInEditor->get_family_name();\r\n if( fontInEditor==NULL)\r\n {\r\n display_user_alert(\"Font Resource Editor\",\"Oh dear! Houston has a problem reading this .ttf font\"+newFileName+\"\/\"+int_to_string(newFontSize)+\"...\");\r\n }\r\n else\r\n {\r\n fontInEditorFileName = get_short_filename(newFileName,true);\r\n fontInEditor->get_metrics( \"AgyW\", &fontWidth, &fontHeight);\r\n fontWidth\/=4;\r\n std::string copyDestinationStr = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+ get_short_filename(newFileName,true);\r\n storedFontFileNames[FONT_OTF] = copyDestinationStr;\r\n fontInEditor->get_metrics( \"AgyW\", &fontWidth, &fontHeight);\r\n fontWidth\/=4;\r\n\r\n }\r\n }\r\n else if( get_file_ext(newFileName)==\"ttf\" || get_file_ext(newFileName)==\"TTF\" )\r\n {\r\n if( fontInEditor!=NULL)\r\n {\r\n gfs->close_font(fontInEditor);\r\n fontInEditor = NULL;\r\n }\r\n fontInEditorFileName = get_short_filename(newFileName,true);\r\n std::string copyDestinationStr = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+ fontInEditorFileName;\r\n copy_file(newFileName.c_str(),copyDestinationStr );\r\n\r\n fontInEditor = gfs->open_font(copyDestinationStr.c_str(),newFontSize,false,\"Custom Font\");\r\n fontFamilyName =fontInEditor->get_family_name();\r\n if( fontInEditor==NULL)\r\n {\r\n display_user_alert(\"Font Resource Editor\",\"Oh dear! Houston has a problem reading this .ttf font\"+newFileName+\"\/\"+int_to_string(newFontSize)+\"...\");\r\n }\r\n else\r\n {\r\n fontInEditorFileName = get_short_filename(newFileName,true);\r\n fontInEditor->get_metrics( \"AgyW\", &fontWidth, &fontHeight);\r\n fontWidth\/=4;\r\n std::string copyDestinationStr = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+ get_short_filename(newFileName,true);\r\n storedFontFileNames[FONT_TTF] = copyDestinationStr;\r\n fontInEditor->get_metrics( \"AgyW\", &fontWidth, &fontHeight);\r\n fontWidth\/=4;\r\n\r\n }\r\n }\r\n else if( get_file_ext(newFileName)==\"woff\" || get_file_ext(newFileName)==\"WOFF\" )\r\n {\r\n std::string copyDestinationStr = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+ get_short_filename(newFileName,true);\r\n storedFontFileNames[FONT_WOFF] = copyDestinationStr;\r\n copy_file(newFileName.c_str(),copyDestinationStr );\r\n }\r\n else if( get_file_ext(newFileName)==\"woff2\" || get_file_ext(newFileName)==\"WOFF2\" )\r\n {\r\n std::string copyDestinationStr = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+ get_short_filename(newFileName,true);\r\n storedFontFileNames[FONT_WOFF2] = copyDestinationStr;\r\n copy_file(newFileName.c_str(),copyDestinationStr );\r\n }\r\n else\r\n {\r\n display_user_alert(\"Font Resource Editor\",\"Invalid Font File Type given. Please use .ttf files\");\r\n }\r\n }\r\n}\r\n\r\nvoid fontResource::preprocess_self(std::string alternatePath)\r\n{\r\n if( resourcePostProcessed ==false || file_exists(alternatePath) )\r\n {\r\n if( GPE_LOADER != NULL )\r\n {\r\n GPE_LOADER->update_submessages( \"Processing Font\", resourceName );\r\n }\r\n\r\n std::string otherColContainerName = \"\";\r\n\r\n std::string newFileIn =\"\";\r\n std::string soughtDir = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\";\r\n if( file_exists(alternatePath) )\r\n {\r\n newFileIn = alternatePath;\r\n soughtDir = get_path_from_file(newFileIn);\r\n }\r\n else\r\n {\r\n newFileIn = soughtDir + resourceName+\".gpf\";\r\n }\r\n std::ifstream gameResourceFileIn( newFileIn.c_str() );\r\n\r\n GPE_Report(\"Loading font - \"+newFileIn);\r\n \/\/If the level file could be loaded\r\n if( !gameResourceFileIn.fail() )\r\n {\r\n \/\/makes sure the file is open\r\n if (gameResourceFileIn.is_open())\r\n {\r\n int equalPos = 0;\r\n std::string firstChar=\"\";\r\n std::string section=\"\";\r\n std::string keyString=\"\";\r\n std::string valString=\"\";\r\n std::string subValString=\"\";\r\n std::string currLine=\"\";\r\n std::string currLineToBeProcessed;\r\n float foundFileVersion = 0;\r\n std::string fFontFile = \"\";\r\n int tFontSize = 12;\r\n while ( gameResourceFileIn.good() )\r\n {\r\n getline (gameResourceFileIn,currLine); \/\/gets the next line of the file\r\n currLineToBeProcessed = trim_left_inplace(currLine);\r\n currLineToBeProcessed = trim_right_inplace(currLineToBeProcessed);\r\n\r\n if( foundFileVersion <=0)\r\n {\r\n \/\/Empty Line skipping is only allowed at the top of the file\r\n if(!currLineToBeProcessed.empty() )\r\n {\r\n \/\/Comment skipping is only allowed at the top of the file\r\n if( currLineToBeProcessed[0]!= '#' && currLineToBeProcessed[0]!='\/' )\r\n {\r\n \/\/searches for an equal character and parses through the variable\r\n equalPos=currLineToBeProcessed.find_first_of(\"=\");\r\n if(equalPos!=(int)std::string::npos)\r\n {\r\n \/\/if the equalPos is present, then parse on through and carryon\r\n keyString = currLineToBeProcessed.substr(0,equalPos);\r\n valString = currLineToBeProcessed.substr(equalPos+1,currLineToBeProcessed.length());\r\n if( keyString==\"Version\")\r\n {\r\n foundFileVersion = string_to_float(valString);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else if( foundFileVersion <= 2)\r\n {\r\n \/\/Begin processing the file.\r\n if(!currLineToBeProcessed.empty() )\r\n {\r\n equalPos=currLineToBeProcessed.find_first_of(\"=\");\r\n if(equalPos!=(int)std::string::npos)\r\n {\r\n \/\/if the equalPos is present, then parse on through and carryon\r\n keyString = currLineToBeProcessed.substr(0,equalPos);\r\n valString = currLineToBeProcessed.substr(equalPos+1,currLineToBeProcessed.length());\r\n\r\n if( keyString==\"ResourceName\")\r\n {\r\n renameBox->set_string(valString);\r\n }\r\n else if( keyString==\"FontSize\")\r\n {\r\n fontSizeField->set_string(valString);\r\n tFontSize = fontSizeField->get_held_number();\r\n }\r\n else if( keyString==\"FontType\")\r\n {\r\n fontTypeButtonController->set_selection(string_to_int(valString,0));\r\n }\r\n if( keyString==\"PreviewText\")\r\n {\r\n fontPreviewTextField->set_string(valString);\r\n }\r\n else\r\n {\r\n for( int i = 0; i < FONT_FILE_TYPES; i++)\r\n {\r\n if( keyString==SUPPORTED_FONT_EXT[i]+\"_File\")\r\n {\r\n load_font( soughtDir+valString,tFontSize );\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n GPE_Report(\"Invalid FoundFileVersion =\"+float_to_string(foundFileVersion)+\".\");\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid fontResource::prerender_self( )\r\n{\r\n standardEditableGameResource::prerender_self( );\r\n if( fontTypeButtonController!=NULL)\r\n {\r\n fontTypeButtonController->prerender_self( );\r\n }\r\n}\r\n\r\nvoid fontResource::process_self(GPE_Rect * viewedSpace,GPE_Rect * cam )\r\n{\r\n viewedSpace = GPE_find_camera(viewedSpace);\r\n cam = GPE_find_camera(cam);\r\n if(cam!=NULL && viewedSpace!=NULL && PANEL_GENERAL_EDITOR!=NULL && fontSizeField!=NULL)\r\n {\r\n PANEL_GENERAL_EDITOR->clear_panel();\r\n PANEL_GENERAL_EDITOR->add_gui_element(renameBox,true);\r\n PANEL_GENERAL_EDITOR->add_gui_element(loadResourceButton,false);\r\n PANEL_GENERAL_EDITOR->add_gui_element(exportResourceButton,false);\r\n PANEL_GENERAL_EDITOR->add_gui_element(openExternalEditorButton,true);\r\n\r\n PANEL_GENERAL_EDITOR->add_gui_element(fontSizeField,true);\r\n PANEL_GENERAL_EDITOR->add_gui_element(fontPreviewTextField,true);\r\n PANEL_GENERAL_EDITOR->add_gui_element(fontTypeButtonController,true);\r\n PANEL_GENERAL_EDITOR->add_gui_element(confirmResourceButton,true);\r\n PANEL_GENERAL_EDITOR->add_gui_element(cancelResourceButton,true);\r\n int prevFontSize = fontSizeField->get_held_number();\r\n\r\n\r\n PANEL_GENERAL_EDITOR->process_self(NULL, NULL);\r\n if( openExternalEditorButton!=NULL && openExternalEditorButton->is_clicked() )\r\n {\r\n bool hasFileToOpen = false;\r\n int ii = 0;\r\n for( ii = 0; ii < FONT_FILE_TYPES; ii++)\r\n {\r\n if( (int)storedFontFileNames[ii].size() > 0)\r\n {\r\n hasFileToOpen = true;\r\n break;\r\n }\r\n }\r\n if( hasFileToOpen )\r\n {\r\n GPE_open_context_menu(-1,-1,400);\r\n for( ii = 0; ii < FONT_FILE_TYPES; ii++)\r\n {\r\n if( (int)storedFontFileNames[ii].size() > 0)\r\n {\r\n MAIN_CONTEXT_MENU->add_menu_option(\"Edit \"+storedFontFileNames[ii],ii,NULL,-1,NULL,true,true);\r\n }\r\n }\r\n MAIN_CONTEXT_MENU->set_width( MAIN_CONTEXT_MENU->subOptionWidthSpace );\r\n int menuSelection = GPE_Get_Context_Result();\r\n if( menuSelection >=0 && menuSelection < FONT_FILE_TYPES)\r\n {\r\n std::string fileToEdit = storedFontFileNames[menuSelection];\r\n\r\n if( MAIN_EDITOR_SETTINGS!=NULL && MAIN_EDITOR_SETTINGS->pencilExternalEditorsFile[GPE_EXTERNAL_EDITOR_FONT]!=NULL)\r\n {\r\n GPE_OpenProgram(MAIN_EDITOR_SETTINGS->pencilExternalEditorsFile[GPE_EXTERNAL_EDITOR_FONT]->get_string(),fileToEdit, true );\r\n }\r\n else\r\n {\r\n GPE_OpenURL(fileToEdit);\r\n }\r\n \/*\r\n fileToEdit = \"\\\"C:\/Program Files (x86)\/Audacity\/audacity.exe\\\" \\\"\"+fileToEdit+\"\\\"\";\r\n GPE_OpenURL(fileToEdit);*\/\r\n appendToFile(get_user_settings_folder()+\"gpe_error_log2.txt\",\"Attempting to edit [\"+fileToEdit+\"]...\");\r\n }\r\n }\r\n }\r\n\r\n if( fontSizeField->is_valid() )\r\n {\r\n if( fontSizeField->get_held_number()!=prevFontSize && fontSizeField->get_held_number() >= 8 )\r\n {\r\n load_font( storedFontFileNames[FONT_TTF], fontSizeField->get_held_number() );\r\n }\r\n }\r\n if( loadResourceButton->is_clicked() )\r\n {\r\n std::string newFontFile = GPE_GetOpenFileName(\"Load In Custom Font...\",\"\",MAIN_GUI_SETTINGS->fileOpenFontDir );\r\n if( (int)newFontFile.size() > 3)\r\n {\r\n load_font( newFontFile, fontSizeField->get_held_number() );\r\n }\r\n }\r\n else if( confirmResourceButton->is_clicked() )\r\n {\r\n save_resource();\r\n }\r\n else if( cancelResourceButton->is_clicked() )\r\n {\r\n if( GPE_Display_Basic_Prompt(\"Are you sure you will like to reverse changes?\",\"This will load in data from save-file!\", true )== DISPLAY_QUERY_YES )\r\n {\r\n resourcePostProcessed = false;\r\n preprocess_self();\r\n }\r\n }\r\n }\r\n}\r\n\r\nbool fontResource::render_held_font( int xPos, int yPos, std::string textureText, GPE_Color * textColor,int hAlign,int vAlign, float renderAngle, float renderScale, int renderAlpha )\r\n{\r\n if( fontInEditor!=NULL )\r\n {\r\n return fontInEditor->render_text_special( xPos, yPos, textureText, textColor, hAlign, vAlign, renderAngle, renderScale, renderAlpha );\r\n }\r\n return false;\r\n}\r\n\r\nvoid fontResource::render_self(GPE_Rect * viewedSpace,GPE_Rect *cam )\r\n{\r\n viewedSpace = GPE_find_camera(viewedSpace);\r\n cam = GPE_find_camera(cam);\r\n if( cam!=NULL && viewedSpace!=NULL )\r\n {\r\n if(fontTypeButtonController!=NULL)\r\n {\r\n gcanvas->render_vertical_line_color( 0,0,viewedSpace->h,GPE_MAIN_THEME->Program_Header_Color );\r\n }\r\n if( fontInEditor!=NULL)\r\n {\r\n gfs->render_text( GENERAL_GPE_GUI_PADDING,GENERAL_GPE_GUI_PADDING,\"Font Preview: \"+get_short_filename(storedFontFileNames[FONT_TTF],true)+\" | \"+fontFamilyName,GPE_MAIN_THEME->Main_Box_Font_Color,FONT_LABEL,FA_LEFT,FA_TOP);\r\n gfs->render_text( GENERAL_GPE_GUI_PADDING,GENERAL_GPE_GUI_PADDING+32,fontPreviewTextField->get_string(),GPE_MAIN_THEME->Main_Box_Font_Color,fontInEditor,FA_LEFT,FA_TOP);\r\n }\r\n else\r\n {\r\n gfs->render_text( GENERAL_GPE_GUI_PADDING,GENERAL_GPE_GUI_PADDING,\"Please Select A Font\",GPE_MAIN_THEME->Main_Box_Font_Color,FONT_LABEL,FA_LEFT,FA_TOP);\r\n }\r\n for( int i = FONT_FILE_TYPES-1; i >=0; i--)\r\n {\r\n if( storedFontFileNames[i].size()> 3)\r\n {\r\n gfs->render_text( viewedSpace->w-GENERAL_GPE_GUI_PADDING*2,viewedSpace->h-GENERAL_GPE_GUI_PADDING-GPE_AVERAGE_LINE_HEIGHT*i,SUPPORTED_FONT_EXT[i]+\" is used\",GPE_MAIN_THEME->Main_Suggestion_Font_Color,GPE_DEFAULT_FONT,FA_RIGHT,FA_BOTTOM);\r\n }\r\n else\r\n {\r\n gfs->render_text( viewedSpace->w-GENERAL_GPE_GUI_PADDING*2,viewedSpace->h-GENERAL_GPE_GUI_PADDING-GPE_AVERAGE_LINE_HEIGHT*i,SUPPORTED_FONT_EXT[i]+\" not used\",GPE_MAIN_THEME->Main_Error_Font_Color,GPE_DEFAULT_FONT,FA_RIGHT,FA_BOTTOM);\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid fontResource::save_resource(std::string alternatePath, int backupId)\r\n{\r\n if( GPE_LOADER != NULL )\r\n {\r\n GPE_LOADER->update_submessages( \"Saving Font\", resourceName );\r\n }\r\n\r\n bool usingAltSaveSource = false;\r\n std::string newFileOut =\"\";\r\n std::string soughtDir = get_path_from_file(alternatePath);\r\n if( path_exists(soughtDir) )\r\n {\r\n newFileOut = alternatePath;\r\n usingAltSaveSource= true;\r\n }\r\n else\r\n {\r\n soughtDir = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\";\r\n newFileOut = soughtDir + resourceName+\".gpf\";\r\n }\r\n std::ofstream newSaveDataFile( newFileOut.c_str() );\r\n \/\/If the font file could be saved\r\n if( !newSaveDataFile.fail() && newSaveDataFile.is_open() )\r\n {\r\n write_header_on_file(&newSaveDataFile);\r\n if( fontSizeField!=NULL)\r\n {\r\n newSaveDataFile << \"FontSize=\" << std::max(8,(int)fontSizeField->get_held_number() )<< \"\\n\";\r\n }\r\n else\r\n {\r\n newSaveDataFile << \"FontSize=12\\n\";\r\n }\r\n\r\n std::string resFileLocation = \"\";\r\n std::string resFileCopySrc;\r\n std::string resFileCopyDest;\r\n for( int i = 0; i < FONT_FILE_TYPES; i++)\r\n {\r\n if( (int)storedFontFileNames[i].size() > 3)\r\n {\r\n resFileLocation = storedFontFileNames[i];\r\n newSaveDataFile << SUPPORTED_FONT_EXT[i]+\"_File=\" << resFileLocation <<\"\\n\";\r\n if( (int)resFileLocation.size() > 0 && usingAltSaveSource )\r\n {\r\n resFileCopySrc = file_to_dir(parentProjectName)+\"\/gpe_project\/resources\/fonts\/\"+resFileLocation;\r\n resFileCopyDest = soughtDir+resFileLocation;\r\n if( file_exists(resFileCopyDest) )\r\n {\r\n \/*\r\n if( GPE_Display_Basic_Prompt(\"[WARNING]Font File Already exists?\",\"Are you sure you will like to overwrite your [\"+resFileLocation+\"] font file? This action is irreversible!\")==DISPLAY_QUERY_YES)\r\n {\r\n copy_file(resFileCopySrc,resFileCopyDest);\r\n }\r\n *\/\r\n }\r\n else\r\n {\r\n copy_file(resFileCopySrc,resFileCopyDest);\r\n }\r\n }\r\n }\r\n }\r\n\r\n if( fontTypeButtonController!=NULL)\r\n {\r\n newSaveDataFile << \"FontType=\" <<fontTypeButtonController->get_selected_id() << \"\\n\";\r\n }\r\n else\r\n {\r\n newSaveDataFile << \"FontType=0\\n\";\r\n }\r\n if(fontPreviewTextField!=NULL)\r\n {\r\n newSaveDataFile << \"PreviewText=\" <<fontPreviewTextField->get_string() << \"\\n\";\r\n }\r\n newSaveDataFile.close();\r\n if( !usingAltSaveSource)\r\n {\r\n isModified = false;\r\n }\r\n if( GPE_LOADER != NULL )\r\n {\r\n GPE_LOADER->update_submessages( \"Font Successfully Saved!\", resourceName );\r\n }\r\n return;\r\n }\r\n\r\n GPE_Main_Logs->log_general_error(\"Unable to save file [\"+newFileOut+\"]\");\r\n if( GPE_LOADER != NULL )\r\n {\r\n GPE_LOADER->update_submessages( \"Font Unable to Save!\", resourceName );\r\n }\r\n}\r\n\r\nbool fontResource::write_data_into_projectfile(std::ofstream * fileTarget, int nestedFoldersIn)\r\n{\r\n if( fileTarget!=NULL)\r\n {\r\n if( fileTarget->is_open() )\r\n {\r\n std::string nestedTabsStr = generate_tabs( nestedFoldersIn );\r\n *fileTarget << nestedTabsStr << \"Font=\" << resourceName << \",\" << get_global_rid() << \",\";\r\n\r\n *fileTarget << \"\\n\";\r\n \/\/save_resource();\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n\r\n<commit_msg>Delete font_resource.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\/\/\n\/*\n Copyright (c) 2012, Stuart R. Slattery\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:\n\n *: Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\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\n *: Neither the name of the University of Wisconsin - Madison nor the\n names of its contributors may be used to endorse or promote products\n derived 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 FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n HOLDER 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\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\file MCLS_EpetraAdapater.hpp\n * \\author Stuart R. Slattery\n * \\brief Epetra Helpers.\n *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#ifndef MCLS_EPETRAHELPERS_HPP\n#define MCLS_EPETRAHELPERS_HPP\n\n#include <MCLS_DBC.hpp>\n\n#include <Teuchos_RCP.hpp>\n#include <Teuchos_Array.hpp>\n#include <Teuchos_ArrayView.hpp>\n#include <Teuchos_as.hpp>\n\n#include <Epetra_Map.h>\n#include <Epetra_RowMatrix.h>\n#include <Epetra_CrsMatrix.h>\n#include <Epetra_Export.h>\n#include <Epetra_RowMatrixTransposer.h>\n\n#include <EpetraExt_MatrixMatrix.h>\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\class UndefinedEpetraHelpers\n * \\brief Class for undefined EpetraHelper functions.\n *\n * Will throw a compile-time error if these traits are not specialized.\n *\/\ntemplate<class Matrix>\nstruct UndefinedEpetraHelpers\n{\n static inline void notDefined()\n {\n\treturn Matrix::this_type_is_missing_a_specialization();\n }\n};\n\nnamespace MCLS\n{\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\class EpetraMatrixHelpers\n * \\brief Helper functions for Epetra implementations.\n *\/\ntemplate<class Matrix>\nclass EpetraMatrixHelpers\n{\n public:\n\n \/\/@{\n \/\/! Typedefs.\n typedef Matrix matrix_type;\n \/\/@}\n\n \/*!\n * \\brief Get the on-process global matrix column indices that, as global\n * row indices, are off-process.\n *\/\n static Teuchos::Array<int> getOffProcColsAsRows( const Matrix& matrix )\n { \n\tUndefinedEpetraHelpers<Matrix>::notDefined(); \n\treturn Teuchos::Array<int>(0); \n }\n\n \/*!\n * \\brief Get a copy of the transpose of a matrix.\n *\/\n static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )\n { \n\tUndefinedEpetraHelpers<Matrix>::notDefined(); \n\treturn Teuchos::null;\n }\n\n \/*\n * \\brief Create a reference-counted pointer to a new matrix with a\n * specified number of off-process nearest-neighbor global rows.\n *\/\n static Teuchos::RCP<matrix_type> copyNearestNeighbors( \n \tconst matrix_type& matrix, const int& num_neighbors )\n { \n\tUndefinedEpetraHelpers<Matrix>::notDefined(); \n\treturn Teuchos::null;\n }\n\n \/*!\n * \\brief Matrix-Matrix multiply C = A*B\n *\/\n static void multiply( const Teuchos::RCP<const matrix_type>& A, \n\t\t\t const Teuchos::RCP<const matrix_type>& B, \n\t\t\t const Teuchos::RCP<matrix_type>& C )\n { UndefinedEpetraHelpers<Matrix>::notDefined(); }\n};\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\class EpetraMatrixHelpers\n * \\brief EpetraMatrixHelpers specialization for Epetra_RowMatrix.\n *\/\ntemplate<>\nclass EpetraMatrixHelpers<Epetra_RowMatrix>\n{\n public:\n\n \/\/@{\n \/\/! Typedefs.\n typedef Epetra_RowMatrix matrix_type;\n \/\/@}\n\n \/*!\n * \\brief Get the on-process global matrix column indices that, as global\n * row indices, are off-process.\n *\/\n static Teuchos::Array<int> getOffProcColsAsRows( const matrix_type& matrix )\n { \n\tMCLS_REQUIRE( matrix.Filled() );\n\n\tconst Epetra_Map& row_map = matrix.RowMatrixRowMap();\n\tconst Epetra_Map& col_map = matrix.RowMatrixColMap();\n\n\tTeuchos::ArrayView<const int> global_cols( col_map.MyGlobalElements(),\n\t\t\t\t\t\t col_map.NumMyElements() );\n\n\tTeuchos::Array<int> off_proc_cols(0);\n\tTeuchos::ArrayView<const int>::const_iterator global_col_it;\n\tfor ( global_col_it = global_cols.begin();\n\t global_col_it != global_cols.end();\n\t ++global_col_it )\n\t{\n\t if ( !row_map.MyGID( *global_col_it ) )\n\t {\n\t\toff_proc_cols.push_back( *global_col_it );\n\t }\n\t}\n\n\treturn off_proc_cols;\n }\n\n \/*!\n * \\brief Get a copy of the transpose of a matrix.\n *\/\n static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )\n { \n\tEpetra_RowMatrixTransposer transposer( const_cast<matrix_type*>(&matrix) );\n\n\tEpetra_CrsMatrix* transpose_matrix;\n\ttransposer.CreateTranspose( true, transpose_matrix );\n\n\tMCLS_ENSURE( transpose_matrix->Filled() );\n\treturn Teuchos::RCP<matrix_type>( transpose_matrix );\n }\n\n \/*\n * \\brief Create a reference-counted pointer to a new matrix with a\n * specified number of off-process nearest-neighbor global rows.\n *\/\n static Teuchos::RCP<matrix_type> copyNearestNeighbors( \n \tconst matrix_type& matrix, const int& num_neighbors )\n { \n\tMCLS_REQUIRE( num_neighbors >= 0 ); \n\n\t\/\/ Setup for neighbor construction.\n\tTeuchos::RCP<const Epetra_Map> empty_map = Teuchos::rcp(\n\t new Epetra_Map( 0, 0, matrix.Comm() ) );\n\tTeuchos::RCP<Epetra_CrsMatrix> neighbor_matrix = \n\t Teuchos::rcp( new Epetra_CrsMatrix( Copy, *empty_map, 0 ) );\n\tneighbor_matrix->FillComplete();\n\n\tTeuchos::ArrayView<const int> global_rows;\n\tTeuchos::ArrayView<const int>::const_iterator global_rows_it;\n\tTeuchos::Array<int>::iterator ghost_global_bound;\n\n\t\/\/ Get the initial off proc columns.\n\tTeuchos::Array<int> ghost_global_rows = getOffProcColsAsRows( matrix );\n\n\t\/\/ Build the neighbors by traversing the graph.\n\tfor ( int i = 0; i < num_neighbors; ++i )\n\t{\n\t \/\/ Get rid of the global rows that belong to the original\n\t \/\/ matrix. We don't need to store these, just the neighbors.\n\t global_rows = Teuchos::ArrayView<const int>( \n\t\tmatrix.RowMatrixRowMap().MyGlobalElements(),\n\t\tmatrix.RowMatrixRowMap().NumMyElements() );\n\t for ( global_rows_it = global_rows.begin();\n\t\t global_rows_it != global_rows.end();\n\t\t ++global_rows_it )\n\t {\n\t\tghost_global_bound = std::remove( ghost_global_rows.begin(), \n\t\t\t\t\t\t ghost_global_rows.end(), \n\t\t\t\t\t\t *global_rows_it );\n\t\tghost_global_rows.resize( std::distance(ghost_global_rows.begin(),\n\t\t\t\t\t\t\tghost_global_bound) );\n\t }\n\n\t \/\/ Get the current set of global rows in the neighbor matrix. \n\t global_rows = Teuchos::ArrayView<const int>( \n\t\tneighbor_matrix->RowMatrixRowMap().MyGlobalElements(),\n\t\tneighbor_matrix->RowMatrixRowMap().NumMyElements() );\n\n\t \/\/ Append the on proc neighbor columns to the off proc columns.\n\t for ( global_rows_it = global_rows.begin();\n\t\t global_rows_it != global_rows.end();\n\t\t ++global_rows_it )\n\t {\n\t\tghost_global_rows.push_back( *global_rows_it );\n\t }\n\t\n\t \/\/ Make a new map of the combined global rows and off proc columns.\n\t Teuchos::RCP<const Epetra_Map> ghost_map = Teuchos::rcp( \n\t\tnew Epetra_Map( -1, \n\t\t\t\tTeuchos::as<int>(ghost_global_rows.size()),\n\t\t\t\tghost_global_rows.getRawPtr(),\n\t\t\t\t0,\n\t\t\t\tneighbor_matrix->Comm() ) );\n\n\t \/\/ Export the neighbor matrix with the new neighbor.\n\t Epetra_Export ghost_exporter( matrix.RowMatrixRowMap(), *ghost_map );\n\n\t neighbor_matrix = Teuchos::rcp( \n\t\tnew Epetra_CrsMatrix( Copy, *ghost_map, 0 ) );\n\n\t neighbor_matrix->Export( matrix, ghost_exporter, Insert );\n\t neighbor_matrix->FillComplete();\n\n\t \/\/ Get the next rows in the graph.\n\t ghost_global_rows = getOffProcColsAsRows( *neighbor_matrix );\n\t}\n\n\tMCLS_ENSURE( !neighbor_matrix.is_null() );\n\tMCLS_ENSURE( neighbor_matrix->Filled() );\n\treturn neighbor_matrix;\n }\n\n \/*!\n * \\brief Matrix-Matrix multiply C = A*B\n *\/\n static void multiply( const Teuchos::RCP<const matrix_type>& A, \n\t\t\t const Teuchos::RCP<const matrix_type>& B, \n\t\t\t const Teuchos::RCP<matrix_type>& C )\n {\n\tTeuchos::RCP<const Epetra_CrsMatrix> A_crs =\n\t Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( A );\n\n\tTeuchos::RCP<const Epetra_CrsMatrix> B_crs =\n\t Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( B );\n\n\tTeuchos::RCP<Epetra_CrsMatrix> C_crs =\n\t Teuchos::rcp_dynamic_cast<Epetra_CrsMatrix>( C );\n\n\tif ( Teuchos::is_null(A_crs) )\n\t{\n\t A_crs = createCrsMatrix( A );\n\t}\n\n\tif ( Teuchos::is_null(B_crs) )\n\t{\n\t B_crs = createCrsMatrix( B );\n\t}\n\n\tif ( Teuchos::is_null(C_crs) )\n\t{\n\t C_crs = Teuchos::rcp( \n\t\tnew Epetra_CrsMatrix(Copy, A->RowMatrixRowMap(), 0) );\n\t}\n\n\tEpetraExt::MatrixMatrix::Multiply( \n\t *A_crs, false, *B_crs, false, *C_crs );\n }\n\n \/*!\n * \\brief Create a copy of a RowMatrix in a CrsMatrix.\n *\/\n static Teuchos::RCP<Epetra_CrsMatrix>\n createCrsMatrix( const Teuchos::RCP<const matrix_type>& A )\n {\n\tTeuchos::RCP<Epetra_CrsMatrix> A_crs = Teuchos::rcp( \n\t new Epetra_CrsMatrix(Copy, A->RowMatrixRowMap(), \n\t\t\t\t A->RowMatrixColMap(),A->MaxNumEntries()) );\n\n\tint max_row_entries = A->MaxNumEntries();\n\tint num_local_rows = A->NumMyRows();\n\tint num_entries = 0;\n\n\tTeuchos::Array<double> values( max_row_entries );\n\tTeuchos::Array<int> indices( max_row_entries );\n\n\tfor ( int n = 0; n < num_local_rows; ++n )\n\t{\n\t A->ExtractMyRowCopy( n, max_row_entries, num_entries,\n\t\t\t\t values.getRawPtr(), indices.getRawPtr() );\n\n\t A_crs->ReplaceMyValues( n, num_entries, \n\t\t\t\t values.getRawPtr(), indices.getRawPtr() );\n\t}\n\n\tA_crs->FillComplete();\n\n\treturn A_crs;\n }\n};\n\n\/\/---------------------------------------------------------------------------\/\/\n\n} \/\/ end namespace MCLS\n\n#endif \/\/ end MCLS_EPETRAHELPERS_HPP\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end MCLS_EpetraHelpers.hpp\n\/\/---------------------------------------------------------------------------\/\/\n<commit_msg>fixing erroneous crs matrix creation in matrix-matrix multiply<commit_after>\/\/---------------------------------------------------------------------------\/\/\n\/*\n Copyright (c) 2012, Stuart R. Slattery\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:\n\n *: Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\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\n *: Neither the name of the University of Wisconsin - Madison nor the\n names of its contributors may be used to endorse or promote products\n derived 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 FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n HOLDER 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\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\file MCLS_EpetraAdapater.hpp\n * \\author Stuart R. Slattery\n * \\brief Epetra Helpers.\n *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#ifndef MCLS_EPETRAHELPERS_HPP\n#define MCLS_EPETRAHELPERS_HPP\n\n#include <MCLS_DBC.hpp>\n\n#include <Teuchos_RCP.hpp>\n#include <Teuchos_Array.hpp>\n#include <Teuchos_ArrayView.hpp>\n#include <Teuchos_as.hpp>\n\n#include <Epetra_Map.h>\n#include <Epetra_RowMatrix.h>\n#include <Epetra_CrsMatrix.h>\n#include <Epetra_Export.h>\n#include <Epetra_RowMatrixTransposer.h>\n\n#include <EpetraExt_MatrixMatrix.h>\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\class UndefinedEpetraHelpers\n * \\brief Class for undefined EpetraHelper functions.\n *\n * Will throw a compile-time error if these traits are not specialized.\n *\/\ntemplate<class Matrix>\nstruct UndefinedEpetraHelpers\n{\n static inline void notDefined()\n {\n\treturn Matrix::this_type_is_missing_a_specialization();\n }\n};\n\nnamespace MCLS\n{\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\class EpetraMatrixHelpers\n * \\brief Helper functions for Epetra implementations.\n *\/\ntemplate<class Matrix>\nclass EpetraMatrixHelpers\n{\n public:\n\n \/\/@{\n \/\/! Typedefs.\n typedef Matrix matrix_type;\n \/\/@}\n\n \/*!\n * \\brief Get the on-process global matrix column indices that, as global\n * row indices, are off-process.\n *\/\n static Teuchos::Array<int> getOffProcColsAsRows( const Matrix& matrix )\n { \n\tUndefinedEpetraHelpers<Matrix>::notDefined(); \n\treturn Teuchos::Array<int>(0); \n }\n\n \/*!\n * \\brief Get a copy of the transpose of a matrix.\n *\/\n static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )\n { \n\tUndefinedEpetraHelpers<Matrix>::notDefined(); \n\treturn Teuchos::null;\n }\n\n \/*\n * \\brief Create a reference-counted pointer to a new matrix with a\n * specified number of off-process nearest-neighbor global rows.\n *\/\n static Teuchos::RCP<matrix_type> copyNearestNeighbors( \n \tconst matrix_type& matrix, const int& num_neighbors )\n { \n\tUndefinedEpetraHelpers<Matrix>::notDefined(); \n\treturn Teuchos::null;\n }\n\n \/*!\n * \\brief Matrix-Matrix multiply C = A*B\n *\/\n static void multiply( const Teuchos::RCP<const matrix_type>& A, \n\t\t\t const Teuchos::RCP<const matrix_type>& B, \n\t\t\t const Teuchos::RCP<matrix_type>& C )\n { UndefinedEpetraHelpers<Matrix>::notDefined(); }\n};\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\class EpetraMatrixHelpers\n * \\brief EpetraMatrixHelpers specialization for Epetra_RowMatrix.\n *\/\ntemplate<>\nclass EpetraMatrixHelpers<Epetra_RowMatrix>\n{\n public:\n\n \/\/@{\n \/\/! Typedefs.\n typedef Epetra_RowMatrix matrix_type;\n \/\/@}\n\n \/*!\n * \\brief Get the on-process global matrix column indices that, as global\n * row indices, are off-process.\n *\/\n static Teuchos::Array<int> getOffProcColsAsRows( const matrix_type& matrix )\n { \n\tMCLS_REQUIRE( matrix.Filled() );\n\n\tconst Epetra_Map& row_map = matrix.RowMatrixRowMap();\n\tconst Epetra_Map& col_map = matrix.RowMatrixColMap();\n\n\tTeuchos::ArrayView<const int> global_cols( col_map.MyGlobalElements(),\n\t\t\t\t\t\t col_map.NumMyElements() );\n\n\tTeuchos::Array<int> off_proc_cols(0);\n\tTeuchos::ArrayView<const int>::const_iterator global_col_it;\n\tfor ( global_col_it = global_cols.begin();\n\t global_col_it != global_cols.end();\n\t ++global_col_it )\n\t{\n\t if ( !row_map.MyGID( *global_col_it ) )\n\t {\n\t\toff_proc_cols.push_back( *global_col_it );\n\t }\n\t}\n\n\treturn off_proc_cols;\n }\n\n \/*!\n * \\brief Get a copy of the transpose of a matrix.\n *\/\n static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )\n { \n\tEpetra_RowMatrixTransposer transposer( const_cast<matrix_type*>(&matrix) );\n\n\tEpetra_CrsMatrix* transpose_matrix;\n\ttransposer.CreateTranspose( true, transpose_matrix );\n\n\tMCLS_ENSURE( transpose_matrix->Filled() );\n\treturn Teuchos::RCP<matrix_type>( transpose_matrix );\n }\n\n \/*\n * \\brief Create a reference-counted pointer to a new matrix with a\n * specified number of off-process nearest-neighbor global rows.\n *\/\n static Teuchos::RCP<matrix_type> copyNearestNeighbors( \n \tconst matrix_type& matrix, const int& num_neighbors )\n { \n\tMCLS_REQUIRE( num_neighbors >= 0 ); \n\n\t\/\/ Setup for neighbor construction.\n\tTeuchos::RCP<const Epetra_Map> empty_map = Teuchos::rcp(\n\t new Epetra_Map( 0, 0, matrix.Comm() ) );\n\tTeuchos::RCP<Epetra_CrsMatrix> neighbor_matrix = \n\t Teuchos::rcp( new Epetra_CrsMatrix( Copy, *empty_map, 0 ) );\n\tneighbor_matrix->FillComplete();\n\n\tTeuchos::ArrayView<const int> global_rows;\n\tTeuchos::ArrayView<const int>::const_iterator global_rows_it;\n\tTeuchos::Array<int>::iterator ghost_global_bound;\n\n\t\/\/ Get the initial off proc columns.\n\tTeuchos::Array<int> ghost_global_rows = getOffProcColsAsRows( matrix );\n\n\t\/\/ Build the neighbors by traversing the graph.\n\tfor ( int i = 0; i < num_neighbors; ++i )\n\t{\n\t \/\/ Get rid of the global rows that belong to the original\n\t \/\/ matrix. We don't need to store these, just the neighbors.\n\t global_rows = Teuchos::ArrayView<const int>( \n\t\tmatrix.RowMatrixRowMap().MyGlobalElements(),\n\t\tmatrix.RowMatrixRowMap().NumMyElements() );\n\t for ( global_rows_it = global_rows.begin();\n\t\t global_rows_it != global_rows.end();\n\t\t ++global_rows_it )\n\t {\n\t\tghost_global_bound = std::remove( ghost_global_rows.begin(), \n\t\t\t\t\t\t ghost_global_rows.end(), \n\t\t\t\t\t\t *global_rows_it );\n\t\tghost_global_rows.resize( std::distance(ghost_global_rows.begin(),\n\t\t\t\t\t\t\tghost_global_bound) );\n\t }\n\n\t \/\/ Get the current set of global rows in the neighbor matrix. \n\t global_rows = Teuchos::ArrayView<const int>( \n\t\tneighbor_matrix->RowMatrixRowMap().MyGlobalElements(),\n\t\tneighbor_matrix->RowMatrixRowMap().NumMyElements() );\n\n\t \/\/ Append the on proc neighbor columns to the off proc columns.\n\t for ( global_rows_it = global_rows.begin();\n\t\t global_rows_it != global_rows.end();\n\t\t ++global_rows_it )\n\t {\n\t\tghost_global_rows.push_back( *global_rows_it );\n\t }\n\t\n\t \/\/ Make a new map of the combined global rows and off proc columns.\n\t Teuchos::RCP<const Epetra_Map> ghost_map = Teuchos::rcp( \n\t\tnew Epetra_Map( -1, \n\t\t\t\tTeuchos::as<int>(ghost_global_rows.size()),\n\t\t\t\tghost_global_rows.getRawPtr(),\n\t\t\t\t0,\n\t\t\t\tneighbor_matrix->Comm() ) );\n\n\t \/\/ Export the neighbor matrix with the new neighbor.\n\t Epetra_Export ghost_exporter( matrix.RowMatrixRowMap(), *ghost_map );\n\n\t neighbor_matrix = Teuchos::rcp( \n\t\tnew Epetra_CrsMatrix( Copy, *ghost_map, 0 ) );\n\n\t neighbor_matrix->Export( matrix, ghost_exporter, Insert );\n\t neighbor_matrix->FillComplete();\n\n\t \/\/ Get the next rows in the graph.\n\t ghost_global_rows = getOffProcColsAsRows( *neighbor_matrix );\n\t}\n\n\tMCLS_ENSURE( !neighbor_matrix.is_null() );\n\tMCLS_ENSURE( neighbor_matrix->Filled() );\n\treturn neighbor_matrix;\n }\n\n \/*!\n * \\brief Matrix-Matrix multiply C = A*B\n *\/\n static void multiply( const Teuchos::RCP<const matrix_type>& A, \n\t\t\t const Teuchos::RCP<const matrix_type>& B, \n\t\t\t const Teuchos::RCP<matrix_type>& C )\n {\n\tTeuchos::RCP<const Epetra_CrsMatrix> A_crs =\n\t Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( A );\n\n\tTeuchos::RCP<const Epetra_CrsMatrix> B_crs =\n\t Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( B );\n\n\tTeuchos::RCP<Epetra_CrsMatrix> C_crs =\n\t Teuchos::rcp_dynamic_cast<Epetra_CrsMatrix>( C );\n\n\tif ( Teuchos::is_null(A_crs) )\n\t{\n\t A_crs = createCrsMatrix( A );\n\t}\n\n\tif ( Teuchos::is_null(B_crs) )\n\t{\n\t B_crs = createCrsMatrix( B );\n\t}\n\n\tif ( Teuchos::is_null(C_crs) )\n\t{\n\t C_crs = Teuchos::rcp( \n\t\tnew Epetra_CrsMatrix(Copy, A->RowMatrixRowMap(), 0) );\n\t}\n\n\tEpetraExt::MatrixMatrix::Multiply( \n\t *A_crs, false, *B_crs, false, *C_crs );\n }\n\n \/*!\n * \\brief Create a copy of a RowMatrix in a CrsMatrix.\n *\/\n static Teuchos::RCP<Epetra_CrsMatrix>\n createCrsMatrix( const Teuchos::RCP<const matrix_type>& A )\n {\n\tTeuchos::RCP<Epetra_CrsMatrix> A_crs = Teuchos::rcp( \n\t new Epetra_CrsMatrix(Copy, A->RowMatrixRowMap(), \n\t\t\t\t A->RowMatrixColMap(),A->MaxNumEntries()) );\n\n\tint max_row_entries = A->MaxNumEntries();\n\tint num_local_rows = A->NumMyRows();\n\tint num_entries = 0;\n\n\tTeuchos::Array<double> values( max_row_entries );\n\tTeuchos::Array<int> indices( max_row_entries );\n\n\tfor ( int n = 0; n < num_local_rows; ++n )\n\t{\n\t A->ExtractMyRowCopy( n, max_row_entries, num_entries,\n\t\t\t\t values.getRawPtr(), indices.getRawPtr() );\n\n\t A_crs->InsertMyValues( n, num_entries, \n\t\t\t\t values.getRawPtr(), indices.getRawPtr() );\n\t}\n\n\tA_crs->FillComplete();\n\n\treturn A_crs;\n }\n};\n\n\/\/---------------------------------------------------------------------------\/\/\n\n} \/\/ end namespace MCLS\n\n#endif \/\/ end MCLS_EPETRAHELPERS_HPP\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end MCLS_EpetraHelpers.hpp\n\/\/---------------------------------------------------------------------------\/\/\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************\n*\n*\tCyberX3D for C++\n*\n*\tCopyright (C) Satoshi Konno 1996-2007\n*\n*\tFile:\tBoxNode.cpp\n*\n******************************************************************\/\n\n#include <cybergarage\/x3d\/BoxNode.h>\n#include <cybergarage\/x3d\/Graphic3D.h>\n\nusing namespace CyberX3D;\n\nBoxNode::BoxNode() \n{\n\tsetHeaderFlag(false);\n\tsetType(BOX_NODE);\n\n\t\/\/ size exposed field\n\tsizeField = new SFVec3f(2.0f, 2.0f, 2.0f);\n\tsizeField->setName(sizeFieldString);\n\taddExposedField(sizeField);\n}\n\nBoxNode::~BoxNode() \n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tsize\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSFVec3f *BoxNode::getSizeField() const \n{\n\tif (isInstanceNode() == false)\n\t\treturn sizeField;\n\treturn (SFVec3f *)getExposedField(sizeFieldString);\n}\n\nvoid BoxNode::setSize(float value[]) \n{\n\tgetSizeField()->setValue(value);\n}\n\nvoid BoxNode::setSize(float x, float y, float z) \n{\n\tgetSizeField()->setValue(x, y, z);\n}\n\nvoid BoxNode::getSize(float value[]) const\n{\n\tgetSizeField()->getValue(value);\n}\n\nfloat BoxNode::getX() const\n{\n\treturn getSizeField()->getX();\n}\n\nfloat BoxNode::getY()const \n{\n\treturn getSizeField()->getY();\n}\n\nfloat BoxNode::getZ()const \n{\n\treturn getSizeField()->getZ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tList\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBoxNode *BoxNode::next()const \n{\n\treturn (BoxNode *)Node::next(getType());\n}\n\nBoxNode *BoxNode::nextTraversal()const \n{\n\treturn (BoxNode *)Node::nextTraversalByType(getType());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tfunctions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\nbool BoxNode::isChildNodeType(Node *node) const\n{\n\treturn false;\n}\n\nvoid BoxNode::initialize() \n{\n\trecomputeBoundingBox();\n#ifdef CX3D_SUPPORT_OPENGL\n\trecomputeDisplayList();\n#endif\n}\n\nvoid BoxNode::uninitialize() \n{\n}\n\nvoid BoxNode::update() \n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tInfomation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid BoxNode::outputContext(std::ostream &printStream, const char *indentString) const\n{\n\tSFVec3f *size = getSizeField();\n\tprintStream << indentString << \"\\t\" << \"size \" << size << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tBoxNode::recomputeBoundingBox\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid BoxNode::recomputeBoundingBox() \n{\n\tsetBoundingBoxCenter(0.0f, 0.0f, 0.0f);\n\tsetBoundingBoxSize(getX()\/2.0f, getY()\/2.0f, getZ()\/2.0f);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tBoxNode::getVertexArray\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nsize_t BoxNode::getNumVertexArrays()\n{\n\treturn 1;\n}\n\nvoid BoxNode::getVertexArray(VertexArray& array, size_t id) \n{\n\tif (id != 0) return;\n\n\tVertexFormat format;\n\tformat.addAttribute<float>(\"position\", 3);\n\tformat.addAttribute<float>(\"normal\", 3);\n\tformat.addAttribute<float>(\"texcoord\", 2);\n\tarray = VertexArray(6 * 4, 0, false, format);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tBoxNode::getVertexData\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid BoxNode::getVertexData(size_t id, void *vertex_data)\n{\n\tif (id >= getNumVertexArrays()) {\n\t\treturn;\n\t}\n\n\tVertexArray array;\n\tgetVertexArray(array, id);\n \tconst VertexFormat& format = array.getFormat();\n\n\tstatic float n[6][3] = {\n\t\t\t{0.0, 0.0, 1.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0},\n\t\t\t{0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {-1.0, 0.0, 0.0}};\n\n\tstatic int faces[6][4] = {\n\t\t\t{ 3, 2, 1, 0 }, { 7, 6, 2, 3 }, { 4, 5, 6, 7 },\n\t\t\t{ 0, 1, 5, 4 }, { 1, 2, 6, 5 }, { 3, 0, 4, 7 }};\n\n\tstatic float t[4][2] = {\n\t\t\t{ 0.0f, 1.0f }, { 1.0f, 1.0f },\n\t\t\t{ 1.0f, 0.0f }, { 0.0f, 0.0f } };\n\n\tfloat v[8][3];\n\n\tv[0][0] = v[3][0] = v[4][0] = v[7][0] = -getX()\/2.0f;\n\tv[1][0] = v[2][0] = v[5][0] = v[6][0] = getX()\/2.0f;\n\tv[2][1] = v[3][1] = v[6][1] = v[7][1] = -getY()\/2.0f;\n\tv[0][1] = v[1][1] = v[4][1] = v[5][1] = getY()\/2.0f;\n\tv[4][2] = v[5][2] = v[6][2] = v[7][2] = -getZ()\/2.0f;\n\tv[0][2] = v[1][2] = v[2][2] = v[3][2] = getZ()\/2.0f;\n\n\t\n\tchar* buffer = (char*)vertex_data;\n\n\tfor (int i = 0; i < 6; i++) {\n\tfor (int j = 0; j < 4; j++) {\n\n for (int k = 0; k < format.getNumAttributes(); ++k) {\n\t\t\tconst Attribute* attrib = format.getAttribute(k);\n\t\t\tmemcpy(buffer + getIndexForVert(i*j, array, *attrib),\n\t\t\t v[faces[i][j]], attrib->getByteSize());\n\t\t}\n\n\t}\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tDrawBox\n\/\/\n\/\/\t 4+--------+5\n\/\/\t \/| \/|\n\/\/\t \/ | \/ |\n\/\/\t0+--------+1 |\n\/\/\t | | | |\n\/\/\t | 7+-----|--+6\n\/\/\t | \/ | \/\n\/\/\t |\/ |\/\n\/\/\t3+--------+2\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef CX3D_SUPPORT_OPENGL\n\nstatic void DrawBox(float x0, float x1, float y0, float y1,\tfloat z0, float z1)\n{\n static float n[6][3] = {\n\t\t\t{0.0, 0.0, 1.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0},\n\t\t\t{0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {-1.0, 0.0, 0.0}};\n\n static int faces[6][4] = {\n\t\t\t{ 3, 2, 1, 0 }, { 7, 6, 2, 3 }, { 4, 5, 6, 7 },\n\t\t\t{ 0, 1, 5, 4 }, { 1, 2, 6, 5 }, { 3, 0, 4, 7 }};\n\n static float t[4][2] = {\n\t\t\t{ 0.0f, 1.0f }, { 1.0f, 1.0f },\n\t\t\t{ 1.0f, 0.0f }, { 0.0f, 0.0f } };\n\n float\tv[8][3];\n\n\tv[0][0] = v[3][0] = v[4][0] = v[7][0] = x0;\n\tv[1][0] = v[2][0] = v[5][0] = v[6][0] = x1;\n\tv[2][1] = v[3][1] = v[6][1] = v[7][1] = y0;\n\tv[0][1] = v[1][1] = v[4][1] = v[5][1] = y1;\n\tv[4][2] = v[5][2] = v[6][2] = v[7][2] = z0;\n\tv[0][2] = v[1][2] = v[2][2] = v[3][2] = z1;\n\n\tglFrontFace(GL_CCW);\n\n for (int i = 0; i < 6; i++) {\n\t\tglBegin(GL_POLYGON);\n\t\tglNormal3fv(n[i]);\n\t\tglTexCoord2fv(t[0]);\n\t\tglVertex3fv(v[faces[i][0]]);\n\t\tglTexCoord2fv(t[1]);\n\t\tglVertex3fv(v[faces[i][1]]);\n\t\tglTexCoord2fv(t[2]);\n\t\tglVertex3fv(v[faces[i][2]]);\n\t\tglTexCoord2fv(t[3]);\n\t\tglVertex3fv(v[faces[i][3]]);\n\t\tglEnd();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tBoxNode::recomputeDisplayList\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid BoxNode::recomputeDisplayList() {\t\n\tunsigned int nCurrentDisplayList = getDisplayList();\n\tif (0 < nCurrentDisplayList)\n\t\tglDeleteLists(nCurrentDisplayList, 1);\n\n\tunsigned int nNewDisplayList = glGenLists(1);\n\tglNewList(nNewDisplayList, GL_COMPILE);\n\t\tDrawBox(-getX()\/2.0f, getX()\/2.0f, -getY()\/2.0f, getY()\/2.0f, -getZ()\/2.0f, getZ()\/2.0f);\n\tglEndList();\n\n\tsetDisplayList(nNewDisplayList);\n};\n\n#endif\n<commit_msg>Update cube generation<commit_after>\/******************************************************************\n*\n*\tCyberX3D for C++\n*\n*\tCopyright (C) Satoshi Konno 1996-2007\n*\n*\tFile:\tBoxNode.cpp\n*\n******************************************************************\/\n\n#include <cybergarage\/x3d\/BoxNode.h>\n#include <cybergarage\/x3d\/Graphic3D.h>\n\nusing namespace CyberX3D;\n\nBoxNode::BoxNode() \n{\n\tsetHeaderFlag(false);\n\tsetType(BOX_NODE);\n\n\t\/\/ size exposed field\n\tsizeField = new SFVec3f(2.0f, 2.0f, 2.0f);\n\tsizeField->setName(sizeFieldString);\n\taddExposedField(sizeField);\n}\n\nBoxNode::~BoxNode() \n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tsize\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSFVec3f *BoxNode::getSizeField() const \n{\n\tif (isInstanceNode() == false)\n\t\treturn sizeField;\n\treturn (SFVec3f *)getExposedField(sizeFieldString);\n}\n\nvoid BoxNode::setSize(float value[]) \n{\n\tgetSizeField()->setValue(value);\n}\n\nvoid BoxNode::setSize(float x, float y, float z) \n{\n\tgetSizeField()->setValue(x, y, z);\n}\n\nvoid BoxNode::getSize(float value[]) const\n{\n\tgetSizeField()->getValue(value);\n}\n\nfloat BoxNode::getX() const\n{\n\treturn getSizeField()->getX();\n}\n\nfloat BoxNode::getY()const \n{\n\treturn getSizeField()->getY();\n}\n\nfloat BoxNode::getZ()const \n{\n\treturn getSizeField()->getZ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tList\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBoxNode *BoxNode::next()const \n{\n\treturn (BoxNode *)Node::next(getType());\n}\n\nBoxNode *BoxNode::nextTraversal()const \n{\n\treturn (BoxNode *)Node::nextTraversalByType(getType());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tfunctions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\nbool BoxNode::isChildNodeType(Node *node) const\n{\n\treturn false;\n}\n\nvoid BoxNode::initialize() \n{\n\trecomputeBoundingBox();\n#ifdef CX3D_SUPPORT_OPENGL\n\trecomputeDisplayList();\n#endif\n}\n\nvoid BoxNode::uninitialize() \n{\n}\n\nvoid BoxNode::update() \n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tInfomation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid BoxNode::outputContext(std::ostream &printStream, const char *indentString) const\n{\n\tSFVec3f *size = getSizeField();\n\tprintStream << indentString << \"\\t\" << \"size \" << size << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tBoxNode::recomputeBoundingBox\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid BoxNode::recomputeBoundingBox() \n{\n\tsetBoundingBoxCenter(0.0f, 0.0f, 0.0f);\n\tsetBoundingBoxSize(getX()\/2.0f, getY()\/2.0f, getZ()\/2.0f);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tBoxNode::getVertexArray\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nsize_t BoxNode::getNumVertexArrays()\n{\n\treturn 1;\n}\n\nvoid BoxNode::getVertexArray(VertexArray& array, size_t id) \n{\n\tif (id != 0) return;\n\n\tVertexFormat format;\n\tformat.addAttribute<float>(\"position\", 3);\n\tformat.addAttribute<float>(\"normal\", 3);\n\tformat.addAttribute<float>(\"texcoord\", 2);\n\tarray = VertexArray(36, 0, false, format);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tBoxNode::getVertexData\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid BoxNode::getVertexData(size_t id, void *vertex_data)\n{\n\tif (id >= getNumVertexArrays()) {\n\t\treturn;\n\t}\n\n\tVertexArray array;\n\tgetVertexArray(array, id);\n \tconst VertexFormat& format = array.getFormat();\n\n\tstatic float n[6][3] = {\n\t\t\t{0.0, 0.0, 1.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0},\n\t\t\t{0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {-1.0, 0.0, 0.0}};\n\n\tstatic int faces[6][6] = {\n\t\t\t{ 3, 2, 1, 1, 0, 3 }, { 7, 6, 2, 2, 3, 7 },\n\t\t\t{ 4, 5, 6, 6, 7, 4 }, { 0, 1, 5, 5, 4, 0 },\n\t\t\t{ 1, 2, 6, 6, 5,1 }, { 3, 0, 4, 4, 7, 3 }};\n\n\tstatic float t[6][2] = {\n\t\t\t{ 0.0f, 1.0f }, { 1.0f, 1.0f },\n\t\t\t{ 1.0f, 0.0f }, { 1.0f, 0.0f },\n\t\t\t{ 0.0f, 0.0f }, { 0.0f, 1.0f } };\n\n\tfloat v[8][3];\n\n\tv[0][0] = v[3][0] = v[4][0] = v[7][0] = -getX()\/2.0f;\n\tv[1][0] = v[2][0] = v[5][0] = v[6][0] = getX()\/2.0f;\n\tv[2][1] = v[3][1] = v[6][1] = v[7][1] = -getY()\/2.0f;\n\tv[0][1] = v[1][1] = v[4][1] = v[5][1] = getY()\/2.0f;\n\tv[4][2] = v[5][2] = v[6][2] = v[7][2] = -getZ()\/2.0f;\n\tv[0][2] = v[1][2] = v[2][2] = v[3][2] = getZ()\/2.0f;\n\n\t\n\tchar* buffer = (char*)vertex_data;\n\n\tconst Attribute& position = *format.getAttribute(0);\n\tconst Attribute& normal = *format.getAttribute(1);\n\tconst Attribute& tex_coord = *format.getAttribute(2);\n\n\tfor (int i = 0; i < 6; i++) {\n\t\tfor (int j = 0; j < 6; j++) {\n\t\t\tconst int vertex = i*6 + j;\n\t\t\tmemcpy(buffer + getIndexForVert(vertex, array, position),\n\t\t\t v[faces[i][j]], position.getByteSize());\n\t\t\tmemcpy(buffer + getIndexForVert(vertex, array, normal),\n\t\t\t n[i], normal.getByteSize());\n\t\t\tmemcpy(buffer + getIndexForVert(vertex, array, tex_coord),\n\t\t\t t[j], tex_coord.getByteSize());\n\t\t}\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tDrawBox\n\/\/\n\/\/\t 4+--------+5\n\/\/\t \/| \/|\n\/\/\t \/ | \/ |\n\/\/\t0+--------+1 |\n\/\/\t | | | |\n\/\/\t | 7+-----|--+6\n\/\/\t | \/ | \/\n\/\/\t |\/ |\/\n\/\/\t3+--------+2\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef CX3D_SUPPORT_OPENGL\n\nstatic void DrawBox(float x0, float x1, float y0, float y1,\tfloat z0, float z1)\n{\n static float n[6][3] = {\n\t\t\t{0.0, 0.0, 1.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0},\n\t\t\t{0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {-1.0, 0.0, 0.0}};\n\n static int faces[6][4] = {\n\t\t\t{ 3, 2, 1, 0 }, { 7, 6, 2, 3 }, { 4, 5, 6, 7 },\n\t\t\t{ 0, 1, 5, 4 }, { 1, 2, 6, 5 }, { 3, 0, 4, 7 }};\n\n static float t[4][2] = {\n\t\t\t{ 0.0f, 1.0f }, { 1.0f, 1.0f },\n\t\t\t{ 1.0f, 0.0f }, { 0.0f, 0.0f } };\n\n float\tv[8][3];\n\n\tv[0][0] = v[3][0] = v[4][0] = v[7][0] = x0;\n\tv[1][0] = v[2][0] = v[5][0] = v[6][0] = x1;\n\tv[2][1] = v[3][1] = v[6][1] = v[7][1] = y0;\n\tv[0][1] = v[1][1] = v[4][1] = v[5][1] = y1;\n\tv[4][2] = v[5][2] = v[6][2] = v[7][2] = z0;\n\tv[0][2] = v[1][2] = v[2][2] = v[3][2] = z1;\n\n\tglFrontFace(GL_CCW);\n\n for (int i = 0; i < 6; i++) {\n\t\tglBegin(GL_POLYGON);\n\t\tglNormal3fv(n[i]);\n\t\tglTexCoord2fv(t[0]);\n\t\tglVertex3fv(v[faces[i][0]]);\n\t\tglTexCoord2fv(t[1]);\n\t\tglVertex3fv(v[faces[i][1]]);\n\t\tglTexCoord2fv(t[2]);\n\t\tglVertex3fv(v[faces[i][2]]);\n\t\tglTexCoord2fv(t[3]);\n\t\tglVertex3fv(v[faces[i][3]]);\n\t\tglEnd();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\tBoxNode::recomputeDisplayList\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid BoxNode::recomputeDisplayList() {\t\n\tunsigned int nCurrentDisplayList = getDisplayList();\n\tif (0 < nCurrentDisplayList)\n\t\tglDeleteLists(nCurrentDisplayList, 1);\n\n\tunsigned int nNewDisplayList = glGenLists(1);\n\tglNewList(nNewDisplayList, GL_COMPILE);\n\t\tDrawBox(-getX()\/2.0f, getX()\/2.0f, -getY()\/2.0f, getY()\/2.0f, -getZ()\/2.0f, getZ()\/2.0f);\n\tglEndList();\n\n\tsetDisplayList(nNewDisplayList);\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \"BloomFilterWrap.h\"\n\nnamespace BloomFilterWrap {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Boolean;\nusing v8::Value;\n\nPersistent<Function> BloomFilterWrap::constructor;\n\nBloomFilterWrap::BloomFilterWrap(unsigned int bitsPerElement,\n unsigned int estimatedNumElements, HashFn hashFns[], int numHashFns)\n : BloomFilter(bitsPerElement, estimatedNumElements, hashFns, numHashFns) {\n}\n\nBloomFilterWrap::~BloomFilterWrap() {\n}\n\nvoid BloomFilterWrap::Init(Local<Object> exports) {\n Isolate* isolate = exports->GetIsolate();\n\n \/\/ Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"BloomFilter\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, \"add\", BloomFilterWrap::Add);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"exists\", BloomFilterWrap::Exists);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"BloomFilter\"),\n tpl->GetFunction());\n}\n\nvoid BloomFilterWrap::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n \/\/ Invoked as constructor: `new BloomFilter(...)`\n BloomFilterWrap* obj = new BloomFilterWrap();\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n \/\/ Invoked as plain function `BloomFilter(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Object> result =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nvoid BloomFilterWrap::Add(const FunctionCallbackInfo<Value>& args) {\n String::Utf8Value str(args[0]->ToString());\n const char * buffer = *str;\n\n BloomFilterWrap* obj = ObjectWrap::Unwrap<BloomFilterWrap>(args.Holder());\n obj->add(buffer);\n}\n\nvoid BloomFilterWrap::Exists(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n String::Utf8Value str(args[0]->ToString());\n const char * buffer = *str;\n\n BloomFilterWrap* obj = ObjectWrap::Unwrap<BloomFilterWrap>(args.Holder());\n bool exists = obj->exists(buffer);\n\n args.GetReturnValue().Set(Boolean::New(isolate, exists));\n}\n\n\n} \/\/ namespace BloomFilterWrap\n<commit_msg>Update deprecated calls for v8\/node<commit_after>\/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \"BloomFilterWrap.h\"\n\nnamespace BloomFilterWrap {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Boolean;\nusing v8::Value;\n\nPersistent<Function> BloomFilterWrap::constructor;\n\nBloomFilterWrap::BloomFilterWrap(unsigned int bitsPerElement,\n unsigned int estimatedNumElements, HashFn hashFns[], int numHashFns)\n : BloomFilter(bitsPerElement, estimatedNumElements, hashFns, numHashFns) {\n}\n\nBloomFilterWrap::~BloomFilterWrap() {\n}\n\nvoid BloomFilterWrap::Init(Local<Object> exports) {\n Isolate* isolate = exports->GetIsolate();\n\n \/\/ Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"BloomFilter\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, \"add\", BloomFilterWrap::Add);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"exists\", BloomFilterWrap::Exists);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"BloomFilter\"),\n tpl->GetFunction());\n}\n\nvoid BloomFilterWrap::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n \/\/ Invoked as constructor: `new BloomFilter(...)`\n BloomFilterWrap* obj = new BloomFilterWrap();\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n \/\/ Invoked as plain function `BloomFilter(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Object> result =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nvoid BloomFilterWrap::Add(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n String::Utf8Value str(isolate, args[0]->ToString());\n const char * buffer = *str;\n\n BloomFilterWrap* obj = ObjectWrap::Unwrap<BloomFilterWrap>(args.Holder());\n obj->add(buffer);\n}\n\nvoid BloomFilterWrap::Exists(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n String::Utf8Value str(isolate, args[0]->ToString());\n const char * buffer = *str;\n\n BloomFilterWrap* obj = ObjectWrap::Unwrap<BloomFilterWrap>(args.Holder());\n bool exists = obj->exists(buffer);\n\n args.GetReturnValue().Set(Boolean::New(isolate, exists));\n}\n\n\n} \/\/ namespace BloomFilterWrap\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file popcnt.hpp\n\/\/\/ @brief Functions to count the number of 1 bits inside\n\/\/\/ an array or a 64-bit word.\n\/\/\/\n\/\/\/ Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POPCNT_HPP\n#define POPCNT_HPP\n\n#include <stdint.h>\n\n#if !defined(DISABLE_POPCNT)\n\n#ifndef __has_builtin\n #define __has_builtin(x) 0\n#endif\n\n#if defined(__GNUC__) || __has_builtin(__builtin_popcountll)\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return __builtin_popcountll(x);\n}\n\n#elif defined(_MSC_VER) && \\\n defined(_WIN64)\n\n#include <nmmintrin.h>\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return _mm_popcnt_u64(x);\n}\n\n#elif defined(_MSC_VER) && \\\n defined(_WIN32)\n\n#include <nmmintrin.h>\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return _mm_popcnt_u32((uint32_t) x) +\n _mm_popcnt_u32((uint32_t)(x >> 32));\n}\n\n#else\n\n\/\/ fallback mode\n#define DISABLE_POPCNT\n\n#endif\n#endif\n\n#if !defined(DISABLE_POPCNT)\n\ninline uint64_t popcnt(const uint64_t* data, uint64_t size)\n{\n uint64_t cnt = 0;\n uint64_t i = 0;\n uint64_t limit = size - size % 4;\n\n for (; i < limit; i += 4)\n {\n cnt += popcnt64(data[i+0]);\n cnt += popcnt64(data[i+1]);\n cnt += popcnt64(data[i+2]);\n cnt += popcnt64(data[i+3]);\n }\n\n for (; i < size; i++)\n cnt += popcnt64(data[i]);\n\n return cnt;\n}\n\n#endif\n\n#if defined(DISABLE_POPCNT)\n\n\/\/\/ This uses fewer arithmetic operations than any other known\n\/\/\/ implementation on machines with fast multiplication.\n\/\/\/ It uses 12 arithmetic operations, one of which is a multiply.\n\/\/\/ https:\/\/en.wikipedia.org\/wiki\/Hamming_weight#Efficient_implementation\n\/\/\/\ninline uint64_t popcnt64(uint64_t x)\n{\n uint64_t m1 = 0x5555555555555555ll;\n uint64_t m2 = 0x3333333333333333ll;\n uint64_t m4 = 0x0F0F0F0F0F0F0F0Fll;\n uint64_t h01 = 0x0101010101010101ll;\n\n x -= (x >> 1) & m1;\n x = (x & m2) + ((x >> 2) & m2);\n x = (x + (x >> 4)) & m4;\n\n return (x * h01) >> 56;\n}\n\n\/\/\/ Carry-save adder (CSA).\n\/\/\/ @see Chapter 5 in \"Hacker's Delight\" 2nd edition.\n\/\/\/\ninline void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c)\n{\n uint64_t u = a ^ b;\n h = (a & b) | (u & c);\n l = u ^ c;\n}\n\n\/\/\/ Harley-Seal popcount (3rd iteration).\n\/\/\/ The Harley-Seal popcount algorithm is one of the fastest algorithms\n\/\/\/ for counting 1 bits in an array using only integer operations.\n\/\/\/ This implementation uses only 6.38 instructions per 64-bit word.\n\/\/\/ @see Chapter 5 in \"Hacker's Delight\" 2nd edition.\n\/\/\/\ninline uint64_t popcnt(const uint64_t* data, uint64_t size)\n{\n uint64_t cnt = 0;\n uint64_t ones = 0, twos = 0, fours = 0, eights = 0;\n uint64_t twosA, twosB, foursA, foursB;\n uint64_t limit = size - size % 8;\n uint64_t i = 0;\n\n for(; i < limit; i += 8)\n {\n CSA(twosA, ones, ones, data[i+0], data[i+1]);\n CSA(twosB, ones, ones, data[i+2], data[i+3]);\n CSA(foursA, twos, twos, twosA, twosB);\n CSA(twosA, ones, ones, data[i+4], data[i+5]);\n CSA(twosB, ones, ones, data[i+6], data[i+7]);\n CSA(foursB, twos, twos, twosA, twosB);\n CSA(eights, fours, fours, foursA, foursB);\n\n cnt += popcnt64(eights);\n }\n\n cnt *= 8;\n cnt += 4 * popcnt64(fours);\n cnt += 2 * popcnt64(twos);\n cnt += 1 * popcnt64(ones);\n\n for(; i < size; i++)\n cnt += popcnt64(data[i]);\n\n return cnt;\n}\n\n#endif\n\n#endif \/\/ POPCNT_HPP\n<commit_msg>Refactor<commit_after>\/\/\/\n\/\/\/ @file popcnt.hpp\n\/\/\/ @brief Functions to count the number of 1 bits inside\n\/\/\/ an array or a 64-bit word.\n\/\/\/\n\/\/\/ Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POPCNT_HPP\n#define POPCNT_HPP\n\n#include <stdint.h>\n\n#if !defined(DISABLE_POPCNT)\n\n#ifndef __has_builtin\n #define __has_builtin(x) 0\n#endif\n\n#if defined(__GNUC__) || __has_builtin(__builtin_popcountll)\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return __builtin_popcountll(x);\n}\n\n#elif defined(_MSC_VER) && \\\n defined(_WIN64)\n\n#include <nmmintrin.h>\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return _mm_popcnt_u64(x);\n}\n\n#elif defined(_MSC_VER) && \\\n defined(_WIN32)\n\n#include <nmmintrin.h>\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return _mm_popcnt_u32((uint32_t) x) +\n _mm_popcnt_u32((uint32_t)(x >> 32));\n}\n\n#else\n\n\/\/ fallback mode\n#define DISABLE_POPCNT\n\n#endif\n#endif\n\nnamespace {\n\n#if !defined(DISABLE_POPCNT)\n\ninline uint64_t popcnt(const uint64_t* data, uint64_t size)\n{\n uint64_t cnt = 0;\n uint64_t i = 0;\n uint64_t limit = size - size % 4;\n\n for (; i < limit; i += 4)\n {\n cnt += popcnt64(data[i+0]);\n cnt += popcnt64(data[i+1]);\n cnt += popcnt64(data[i+2]);\n cnt += popcnt64(data[i+3]);\n }\n\n for (; i < size; i++)\n cnt += popcnt64(data[i]);\n\n return cnt;\n}\n\n#endif\n\n#if defined(DISABLE_POPCNT)\n\n\/\/\/ This uses fewer arithmetic operations than any other known\n\/\/\/ implementation on machines with fast multiplication.\n\/\/\/ It uses 12 arithmetic operations, one of which is a multiply.\n\/\/\/ https:\/\/en.wikipedia.org\/wiki\/Hamming_weight#Efficient_implementation\n\/\/\/\ninline uint64_t popcnt64(uint64_t x)\n{\n uint64_t m1 = 0x5555555555555555ull;\n uint64_t m2 = 0x3333333333333333ull;\n uint64_t m4 = 0x0F0F0F0F0F0F0F0Full;\n uint64_t h01 = 0x0101010101010101ull;\n\n x -= (x >> 1) & m1;\n x = (x & m2) + ((x >> 2) & m2);\n x = (x + (x >> 4)) & m4;\n\n return (x * h01) >> 56;\n}\n\n\/\/\/ Carry-save adder (CSA).\n\/\/\/ @see Chapter 5 in \"Hacker's Delight\" 2nd edition.\n\/\/\/\ninline void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c)\n{\n uint64_t u = a ^ b;\n h = (a & b) | (u & c);\n l = u ^ c;\n}\n\n\/\/\/ Harley-Seal popcount (3rd iteration).\n\/\/\/ The Harley-Seal popcount algorithm is one of the fastest algorithms\n\/\/\/ for counting 1 bits in an array using only integer operations.\n\/\/\/ This implementation uses only 6.38 instructions per 64-bit word.\n\/\/\/ @see Chapter 5 in \"Hacker's Delight\" 2nd edition.\n\/\/\/\ninline uint64_t popcnt(const uint64_t* data, uint64_t size)\n{\n uint64_t cnt = 0;\n uint64_t ones = 0, twos = 0, fours = 0, eights = 0;\n uint64_t twosA, twosB, foursA, foursB;\n uint64_t limit = size - size % 8;\n uint64_t i = 0;\n\n for(; i < limit; i += 8)\n {\n CSA(twosA, ones, ones, data[i+0], data[i+1]);\n CSA(twosB, ones, ones, data[i+2], data[i+3]);\n CSA(foursA, twos, twos, twosA, twosB);\n CSA(twosA, ones, ones, data[i+4], data[i+5]);\n CSA(twosB, ones, ones, data[i+6], data[i+7]);\n CSA(foursB, twos, twos, twosA, twosB);\n CSA(eights, fours, fours, foursA, foursB);\n\n cnt += popcnt64(eights);\n }\n\n cnt *= 8;\n cnt += 4 * popcnt64(fours);\n cnt += 2 * popcnt64(twos);\n cnt += 1 * popcnt64(ones);\n\n for(; i < size; i++)\n cnt += popcnt64(data[i]);\n\n return cnt;\n}\n\n#endif\n\n} \/\/ namespace\n\n#endif \/\/ POPCNT_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file popcnt.hpp\n\/\/\/ @brief Functions to count the number of 1 bits inside\n\/\/\/ an array or a 64-bit word.\n\/\/\/\n\/\/\/ Copyright (C) 2020 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POPCNT_HPP\n#define POPCNT_HPP\n\n#include <stdint.h>\n\n#if defined(__has_include)\n #define HAS_INCLUDE(header) __has_include(header)\n#else\n \/\/ If the __has_include() macro does not exist\n \/\/ we assume that the header file exists.\n #define HAS_INCLUDE(header) 1\n#endif\n\n#if defined(ENABLE_POPCNT)\n\n#if !defined(__has_builtin)\n #define __has_builtin(x) 0\n#endif\n\n\/\/ GCC & Clang\n#if defined(__GNUC__) || \\\n __has_builtin(__builtin_popcountll)\n\nnamespace {\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return __builtin_popcountll(x);\n}\n\n} \/\/ namespace\n\n#elif defined(_MSC_VER) && \\\n defined(_WIN64) && \\\n HAS_INCLUDE(<nmmintrin.h>)\n\n#include <nmmintrin.h>\n\nnamespace {\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return _mm_popcnt_u64(x);\n}\n\n} \/\/ namespace\n\n#elif defined(_MSC_VER) && \\\n defined(_WIN32) && \\\n HAS_INCLUDE(<nmmintrin.h>)\n\n#include <nmmintrin.h>\n\nnamespace {\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return _mm_popcnt_u32((uint32_t) x) +\n _mm_popcnt_u32((uint32_t)(x >> 32));\n}\n\n} \/\/ namespace\n\n#else\n\n\/\/ Since hardware popcount support is very important for\n\/\/ performance in primecount we want the compilation to fail in\n\/\/ case the compiler does not select any of the implementations\n\/\/ above (which use compiler intrinsics to enable hardware\n\/\/ popcount support). This way we can be relatively sure that\n\/\/ when primecount has been compiled successfully, primecount\n\/\/ will have hardware popcount support.\n#error \"No fast popcount function implemented for this compiler!\"\n\n#endif\n#endif\n\n#if !defined(ENABLE_POPCNT)\n\nnamespace {\n\n\/\/\/ This uses fewer arithmetic operations than any other known\n\/\/\/ implementation on machines with fast multiplication.\n\/\/\/ It uses 12 arithmetic operations, one of which is a multiply.\n\/\/\/ https:\/\/en.wikipedia.org\/wiki\/Hamming_weight#Efficient_implementation\n\/\/\/\ninline uint64_t popcnt64(uint64_t x)\n{\n uint64_t m1 = 0x5555555555555555ull;\n uint64_t m2 = 0x3333333333333333ull;\n uint64_t m4 = 0x0F0F0F0F0F0F0F0Full;\n uint64_t h01 = 0x0101010101010101ull;\n\n x -= (x >> 1) & m1;\n x = (x & m2) + ((x >> 2) & m2);\n x = (x + (x >> 4)) & m4;\n\n return (x * h01) >> 56;\n}\n\n\/\/\/ Carry-save adder (CSA).\n\/\/\/ @see Chapter 5 in \"Hacker's Delight\" 2nd edition.\n\/\/\/\ninline void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c)\n{\n uint64_t u = a ^ b;\n h = (a & b) | (u & c);\n l = u ^ c;\n}\n\n\/\/\/ Harley-Seal popcount (3rd iteration).\n\/\/\/ The Harley-Seal popcount algorithm is one of the fastest algorithms\n\/\/\/ for counting 1 bits in an array using only integer operations.\n\/\/\/ This implementation uses only 6.38 instructions per 64-bit word.\n\/\/\/ @see Chapter 5 in \"Hacker's Delight\" 2nd edition.\n\/\/\/\ninline uint64_t popcnt(const uint64_t* data, uint64_t size)\n{\n uint64_t cnt = 0;\n uint64_t ones = 0, twos = 0, fours = 0, eights = 0;\n uint64_t twosA, twosB, foursA, foursB;\n uint64_t limit = size - size % 8;\n uint64_t i = 0;\n\n for(; i < limit; i += 8)\n {\n CSA(twosA, ones, ones, data[i+0], data[i+1]);\n CSA(twosB, ones, ones, data[i+2], data[i+3]);\n CSA(foursA, twos, twos, twosA, twosB);\n CSA(twosA, ones, ones, data[i+4], data[i+5]);\n CSA(twosB, ones, ones, data[i+6], data[i+7]);\n CSA(foursB, twos, twos, twosA, twosB);\n CSA(eights, fours, fours, foursA, foursB);\n\n cnt += popcnt64(eights);\n }\n\n cnt *= 8;\n cnt += 4 * popcnt64(fours);\n cnt += 2 * popcnt64(twos);\n cnt += 1 * popcnt64(ones);\n\n for(; i < size; i++)\n cnt += popcnt64(data[i]);\n\n return cnt;\n}\n\n} \/\/ namespace\n\n#elif (defined(__ARM_NEON) || \\\n defined(__aarch64__)) && \\\n HAS_INCLUDE(<arm_neon.h>)\n\n#include <algorithm>\n#include <arm_neon.h>\n\nnamespace {\n\ninline uint64x2_t vpadalq(uint64x2_t sum, uint8x16_t t)\n{\n return vpadalq_u32(sum, vpaddlq_u16(vpaddlq_u8(t)));\n}\n\n\/\/\/ Count the number of 1 bits in the data array.\n\/\/\/ ARM NEON has a vector popcount instruction but no scalar\n\/\/\/ popcount instruction that's why the ARM popcount function\n\/\/\/ is more complicated than the x86 popcount function.\n\/\/\/ This function has been copied from:\n\/\/\/ https:\/\/github.com\/kimwalisch\/libpopcnt\n\/\/\/\ninline uint64_t popcnt(const uint64_t* data, uint64_t size)\n{\n uint64_t i = 0;\n uint64_t cnt = 0;\n\n if (size >= 8)\n {\n const uint8_t* data8 = (const uint8_t*) data;\n uint64_t bytes = size * sizeof(uint64_t);\n uint64_t chunk_size = 64;\n uint64_t iters = bytes \/ chunk_size;\n\n uint64x2_t sum = vcombine_u64(vcreate_u64(0), vcreate_u64(0));\n uint8x16_t zero = vcombine_u8(vcreate_u8(0), vcreate_u8(0));\n\n do\n {\n uint8x16_t t0 = zero;\n uint8x16_t t1 = zero;\n uint8x16_t t2 = zero;\n uint8x16_t t3 = zero;\n\n \/\/ After every 31 iterations we need to add the\n \/\/ temporary sums (t0, t1, t2, t3) to the total sum.\n \/\/ We must ensure that the temporary sums <= 255\n \/\/ and 31 * 8 bits = 248 which is OK.\n uint64_t limit = std::min(i + 31, iters);\n\n \/\/ Each iteration processes 64 bytes\n for (; i < limit; i++)\n {\n uint8x16x4_t input = vld4q_u8(data8);\n data8 += chunk_size;\n\n t0 = vaddq_u8(t0, vcntq_u8(input.val[0]));\n t1 = vaddq_u8(t1, vcntq_u8(input.val[1]));\n t2 = vaddq_u8(t2, vcntq_u8(input.val[2]));\n t3 = vaddq_u8(t3, vcntq_u8(input.val[3]));\n }\n\n sum = vpadalq(sum, t0);\n sum = vpadalq(sum, t1);\n sum = vpadalq(sum, t2);\n sum = vpadalq(sum, t3);\n }\n while (i < iters);\n\n uint64_t tmp[2];\n vst1q_u64(tmp, sum);\n cnt += tmp[0];\n cnt += tmp[1];\n\n uint64_t bytes_processed = iters * chunk_size;\n i = bytes_processed \/ sizeof(uint64_t);\n }\n\n \/\/ Process the remaining bytes\n for (; i < size; i++)\n cnt += popcnt64(data[i]);\n\n return cnt;\n}\n\n} \/\/ namespace\n\n#else\n\nnamespace {\n\n\/\/\/ Used for all CPUs except ARM\ninline uint64_t popcnt(const uint64_t* data, uint64_t size)\n{\n uint64_t cnt = 0;\n\n for (uint64_t i = 0; i < size; i++)\n cnt += popcnt64(data[i]);\n\n return cnt;\n}\n\n} \/\/ namespace\n\n#endif\n\n#endif \/\/ POPCNT_HPP\n<commit_msg>Simplify popcnt<commit_after>\/\/\/\n\/\/\/ @file popcnt.hpp\n\/\/\/ @brief Functions to count the number of 1 bits inside\n\/\/\/ an array or a 64-bit word.\n\/\/\/\n\/\/\/ Copyright (C) 2020 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POPCNT_HPP\n#define POPCNT_HPP\n\n#include <stdint.h>\n\n#if defined(__has_include)\n #define HAS_INCLUDE(header) __has_include(header)\n#else\n \/\/ If the __has_include() macro does not exist\n \/\/ we assume that the header file exists.\n #define HAS_INCLUDE(header) 1\n#endif\n\n#if defined(ENABLE_POPCNT)\n\n#if !defined(__has_builtin)\n #define __has_builtin(x) 0\n#endif\n\n\/\/ GCC & Clang\n#if defined(__GNUC__) || \\\n __has_builtin(__builtin_popcountll)\n\nnamespace {\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return __builtin_popcountll(x);\n}\n\n} \/\/ namespace\n\n#elif defined(_MSC_VER) && \\\n defined(_WIN64) && \\\n HAS_INCLUDE(<nmmintrin.h>)\n\n#include <nmmintrin.h>\n\nnamespace {\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return _mm_popcnt_u64(x);\n}\n\n} \/\/ namespace\n\n#elif defined(_MSC_VER) && \\\n defined(_WIN32) && \\\n HAS_INCLUDE(<nmmintrin.h>)\n\n#include <nmmintrin.h>\n\nnamespace {\n\ninline uint64_t popcnt64(uint64_t x)\n{\n return _mm_popcnt_u32((uint32_t) x) +\n _mm_popcnt_u32((uint32_t)(x >> 32));\n}\n\n} \/\/ namespace\n\n#else\n\n\/\/ Since hardware popcount support is very important for\n\/\/ performance in primecount we want the compilation to fail in\n\/\/ case the compiler does not select any of the implementations\n\/\/ above (which use compiler intrinsics to enable hardware\n\/\/ popcount support). This way we can be relatively sure that\n\/\/ when primecount has been compiled successfully, primecount\n\/\/ will have hardware popcount support.\n#error \"No fast popcount function implemented for this compiler!\"\n\n#endif\n#endif\n\nnamespace {\n\n#if !defined(ENABLE_POPCNT)\n\n\/\/\/ This uses fewer arithmetic operations than any other known\n\/\/\/ implementation on machines with fast multiplication.\n\/\/\/ It uses 12 arithmetic operations, one of which is a multiply.\n\/\/\/ https:\/\/en.wikipedia.org\/wiki\/Hamming_weight#Efficient_implementation\n\/\/\/\ninline uint64_t popcnt64(uint64_t x)\n{\n uint64_t m1 = 0x5555555555555555ull;\n uint64_t m2 = 0x3333333333333333ull;\n uint64_t m4 = 0x0F0F0F0F0F0F0F0Full;\n uint64_t h01 = 0x0101010101010101ull;\n\n x -= (x >> 1) & m1;\n x = (x & m2) + ((x >> 2) & m2);\n x = (x + (x >> 4)) & m4;\n\n return (x * h01) >> 56;\n}\n\n#endif\n\ninline uint64_t popcnt(const uint64_t* data, uint64_t size)\n{\n uint64_t cnt = 0;\n\n for (uint64_t i = 0; i < size; i++)\n cnt += popcnt64(data[i]);\n\n return cnt;\n}\n\n} \/\/ namespace\n\n#endif \/\/ POPCNT_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2014 The Trustees of Princeton University\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#include \"driver.h\"\n\n\/\/ start up the driver\nint driver_init( void** driver_state ) {\n \n return 0;\n}\n\n\n\/\/ shut down the driver \nint driver_shutdown( void* driver_state ) {\n \n return 0;\n}\n\n\/\/ connect\nint connect_dataset_block( struct AG_connection_context* ag_ctx, void* driver_state, void** driver_connection_state ) {\n \n char* request_path = AG_driver_get_request_path( ag_ctx );\n char* url = AG_driver_get_query_string( ag_ctx );\n \n struct curl_connection_context* curl_ctx = CALLOC_LIST( struct curl_connection_context, 1 );\n \n curl_ctx->request_path = request_path;\n curl_ctx->url = url;\n \n *driver_connection_state = curl_ctx;\n \n return 0;\n}\n\n\/\/ free a connection context \nint close_dataset_block( void* driver_connection_state ) {\n \n struct curl_connection_context* curl_ctx = (struct curl_connection_context*)driver_connection_state;\n \n if( curl_ctx != NULL ) {\n if( curl_ctx->request_path != NULL ) {\n free( curl_ctx->request_path );\n curl_ctx->request_path = NULL;\n }\n\n if( curl_ctx->url != NULL ) {\n free( curl_ctx->url );\n curl_ctx->url = NULL;\n }\n\n free( curl_ctx );\n }\n return 0;\n}\n\n\n\/\/ dummy header function; seems to be needed to stat files \nstatic size_t curl_null_header( void* ptr, size_t size, size_t nmemb, void* data ) {\n return size * nmemb;\n}\n\n\/\/ write function to fill our buffer, and abort if we get too much \nstatic size_t curl_write_block( void* ptr, size_t size, size_t nmemb, void* data ) {\n \n struct curl_write_context* write_ctx = (struct curl_write_context*)data;\n \n size_t total_available = size * nmemb;\n \n \/\/ have space?\n if( write_ctx->num_written + total_available <= write_ctx->buf_len ) {\n \n memcpy( write_ctx->buf + write_ctx->num_written, ptr, total_available );\n write_ctx->num_written += total_available;\n \n return total_available;\n }\n else {\n \/\/ not enough space\n errorf(\"Not enough space (have %zu bytes, but need at least %zu)\\n\", write_ctx->buf_len, write_ctx->num_written + total_available );\n return 0;\n }\n}\n\n\n\/\/ find out how big a file is, and when it was modified \n\/\/ return 0 on success\n\/\/ return negative errno on failure, or if errno was not set, return positive curl status code on failure\nstatic int curl_stat_file( CURL* curl, char const* url, struct AG_driver_publish_info* pub_info ) {\n \n \/\/ set up the curl handle\n curl_easy_setopt( curl, CURLOPT_URL, url );\n curl_easy_setopt( curl, CURLOPT_NOBODY, 1L );\n curl_easy_setopt( curl, CURLOPT_FILETIME, 1L );\n curl_easy_setopt( curl, CURLOPT_HEADERFUNCTION, curl_null_header );\n curl_easy_setopt( curl, CURLOPT_HEADER, 0L );\n \n int rc = curl_easy_perform( curl );\n \n if( rc != 0 ) {\n \/\/ error of some sort \n long oserr = 0;\n \n curl_easy_getinfo( curl, CURLINFO_OS_ERRNO, &oserr );\n \n if( oserr != 0 ) {\n errorf(\"curl_easy_perform(%s) rc = %d, errno = %ld\\n\", url, rc, -oserr );\n return (int)(-oserr);\n }\n else {\n errorf(\"curl_easy_perform(%s) rc = %d\\n\", url, rc );\n return rc;\n }\n }\n \n \/\/ success! get info \n long filetime = -1;\n double filesize = -1.0;\n \n int filetime_rc = curl_easy_getinfo( curl, CURLINFO_FILETIME, &filetime );\n int filesize_rc = curl_easy_getinfo( curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &filesize );\n \n if( (filetime_rc != 0 || filetime < 0) || (filesize_rc != 0 || filesize <= 0.0 ) ) {\n \n \/\/ failed to get data\n rc = -ENODATA;\n \n if( filetime_rc != 0 ) {\n errorf(\"curl_easy_getinfo( CURLINFO_FILETIME ) rc = %d\\n\", filetime_rc );\n rc = filetime_rc;\n }\n if( filesize_rc != 0 ) {\n errorf(\"curl_easy_getinfo( CURLINFO_CONTENT_LENGTH_DOWNLOAD ) rc = %d\\n\", filesize_rc );\n rc = filesize_rc;\n }\n \n return rc;\n }\n \n \/\/ fill in our pubinfo \n pub_info->size = (off_t)filesize;\n \n \/\/ set the time to now \n pub_info->mtime_sec = (int64_t)filetime;\n pub_info->mtime_nsec = 0;\n \n return 0;\n}\n\n\n\/\/ get a block of data, and get its pubinfo while we're at it\n\/\/ return the number of bytes received on success\n\/\/ return negative errno on failure, or if errno was not set, return positive curl status code on failure\nstatic int curl_download_block( CURL* curl, char const* url, uint64_t block_id, char* buf, uint64_t block_size, struct AG_driver_publish_info* pub_info ) {\n \n struct curl_write_context write_ctx;\n memset( &write_ctx, 0, sizeof(struct curl_write_context) );\n \n write_ctx.num_written = 0;\n write_ctx.buf = buf;\n write_ctx.buf_len = block_size;\n \n \/\/ set up the curl handle\n curl_easy_setopt( curl, CURLOPT_URL, url );\n curl_easy_setopt( curl, CURLOPT_FILETIME, 1L );\n curl_easy_setopt( curl, CURLOPT_HEADERFUNCTION, curl_null_header );\n curl_easy_setopt( curl, CURLOPT_HEADER, 0L );\n curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, curl_write_block );\n curl_easy_setopt( curl, CURLOPT_WRITEDATA, &write_ctx );\n \n \/\/ add range requirement\n \/\/ format: X-Y, where X and Y are 64-bit byte indices. Y is inclusive\n size_t range_maxlen = 20 + 1 + 20 + 1; \/\/ NOTE: 19 < log10( UINT64_MAX ) < 20\n char range_buf[20 + 1 + 20 + 1]; \n snprintf( range_buf, range_maxlen, \"%\" PRIu64 \"-%\" PRIu64, block_id * block_size, (block_id + 1) * block_size - 1 );\n \n curl_easy_setopt( curl, CURLOPT_RANGE, range_buf );\n \n int rc = curl_easy_perform( curl );\n \n if( rc != 0 ) {\n \/\/ error of some sort \n long oserr = 0;\n \n curl_easy_getinfo( curl, CURLINFO_OS_ERRNO, &oserr );\n \n if( oserr != 0 ) {\n errorf(\"curl_easy_perform(%s) rc = %d, errno = %ld\\n\", url, rc, -oserr );\n return (int)(-oserr);\n }\n else {\n if( rc == CURLE_BAD_DOWNLOAD_RESUME ) {\n \/\/ EOF \n errorf(\"WARN: Block %\" PRIu64 \" is off the end of the file\\n\", block_id );\n \n write_ctx.num_written = 0;\n }\n else {\n errorf(\"curl_easy_perform(%s) rc = %d\\n\", url, rc );\n return -rc;\n }\n }\n }\n \n \/\/ success! opportunistically try to get metadata info \n long filetime = -1;\n double filesize = -1.0;\n \n int filetime_rc = curl_easy_getinfo( curl, CURLINFO_FILETIME, &filetime );\n int filesize_rc = curl_easy_getinfo( curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &filesize );\n \n \/\/ opportunistically got metadata?\n if( filetime_rc == 0 && filetime > 0 && filesize_rc == 0 && filesize >= 1.0 ) {\n \n \/\/ fill in our pubinfo \n pub_info->size = (off_t)filesize;\n pub_info->mtime_sec = (int64_t)filetime;\n pub_info->mtime_nsec = 0;\n }\n \n return write_ctx.num_written;\n}\n\n\n\/\/ get the publish information for a dataset \nint curl_get_pubinfo( char const* request_path, char const* url, struct AG_driver_publish_info* pubinfo ) {\n \n \/\/ maybe we've cached it?\n char* info_path = md_fullpath( request_path, \"curl-info\", NULL );\n \n char* pubinfo_buf = NULL;\n size_t pubinfo_buflen = 0;\n \n int rc = AG_driver_cache_get_chunk( info_path, &pubinfo_buf, &pubinfo_buflen );\n \n if( rc == 0 ) {\n \n if( pubinfo_buflen == sizeof(struct AG_driver_publish_info) ) {\n \/\/ success!\n memcpy( pubinfo, pubinfo_buf, sizeof(struct AG_driver_publish_info) );\n free( pubinfo_buf );\n \n AG_driver_cache_promote_chunk( info_path );\n free( info_path );\n return 0;\n }\n else {\n errorf(\"WARN: got invalid data for %s\\n\", info_path );\n AG_driver_cache_evict_chunk( info_path );\n \n rc = 0;\n free( pubinfo_buf );\n pubinfo_buf = NULL;\n }\n }\n \n \/\/ miss\n CURL* curl = curl_easy_init();\n\n \/\/ not cached\n rc = curl_stat_file( curl, url, pubinfo );\n if( rc != 0 ) {\n errorf(\"ERR: curl_stat_file(%s, %s) rc = %d\\n\", info_path, url, rc );\n }\n else {\n \/\/ success! cache it \n \n char* cache_chunk = CALLOC_LIST( char, sizeof(struct AG_driver_publish_info) );\n memcpy( cache_chunk, &pubinfo, sizeof(struct AG_driver_publish_info) );\n \n AG_driver_cache_put_chunk_async( info_path, cache_chunk, sizeof(struct AG_driver_publish_info) );\n \n dbprintf(\"Got pubinfo for %s: { size = %jd, mtime_sec = %\" PRId64 \", mtime_nsec = %\" PRId32 \" }\\n\", request_path, pubinfo->size, pubinfo->mtime_sec, pubinfo->mtime_nsec );\n }\n \n curl_easy_cleanup( curl );\n \n free( info_path );\n \n return rc;\n}\n\n\n\/\/ get data for a block.\n\/\/ get it from the cache, if possible.\n\/\/ otherwise, download it and serve it back \nssize_t get_dataset_block( struct AG_connection_context* ag_ctx, uint64_t block_id, char* block_buf, size_t buf_len, void* driver_connection_state ) {\n \n struct curl_connection_context* curl_ctx = (struct curl_connection_context*)driver_connection_state;\n \n \/\/ opportunistically get pubinfo\n struct AG_driver_publish_info pubinfo;\n memset( &pubinfo, 0, sizeof(struct AG_driver_publish_info) );\n \n pubinfo.size = -1;\n pubinfo.mtime_sec = -1;\n \n CURL* curl = curl_easy_init();\n \n \/\/ no data cached; go get it \n int num_read = curl_download_block( curl, curl_ctx->url, block_id, block_buf, buf_len, &pubinfo );\n \n if( num_read < 0 ) {\n \n errorf(\"curl_download_block(%s, %\" PRIu64 \") rc = %d\\n\", curl_ctx->url, block_id, num_read );\n }\n else {\n \n \/\/ got data!\n \/\/ did we get any pubinfo?\n if( pubinfo.mtime_sec > 0 && pubinfo.size > 0 ) {\n \n dbprintf(\"Update cached publish info for %s\\n\", curl_ctx->request_path );\n \n \/\/ update the cache\n char* info_path = md_fullpath( curl_ctx->request_path, \"curl-info\", NULL );\n \n char* cache_chunk = CALLOC_LIST( char, sizeof(struct AG_driver_publish_info) );\n memcpy( cache_chunk, &pubinfo, sizeof(struct AG_driver_publish_info) );\n \n AG_driver_cache_put_chunk_async( info_path, cache_chunk, sizeof(struct AG_driver_publish_info) );\n \n free( info_path );\n }\n }\n \n curl_easy_cleanup( curl );\n \n return num_read;\n}\n\n\n\/\/ prepare to publish--fill in pub_info\nint stat_dataset( char const* path, struct AG_map_info* map_info, struct AG_driver_publish_info* pub_info, void* driver_state ) {\n \n char* url = AG_driver_map_info_get_query_string( map_info );\n \n \n dbprintf(\"stat %s (url: %s)\\n\", path, url );\n \n if( url == NULL ) {\n \n \/\/ it's a directory.\n \/\/ timestamp is simply now \n pub_info->size = 4096;\n \n struct timespec ts;\n clock_gettime( CLOCK_REALTIME, &ts );\n \n pub_info->mtime_sec = ts.tv_sec;\n pub_info->mtime_nsec = ts.tv_nsec;\n \n return 0;\n }\n \n int rc = 0;\n \n \/\/ it's a file.\n \/\/ get information from upstream?\n char* get_from_upstream = AG_driver_get_config_var( AG_CURL_DRIVER_CONFIG_CHECK_UPSTREAM );\n if( get_from_upstream != NULL ) {\n \n free( get_from_upstream );\n \n \/\/ get the info from upstream\n int rc = curl_get_pubinfo( path, url, pub_info );\n \n if( rc != 0 ) {\n errorf(\"curl_get_pubinfo(%s, %s) rc = %d\\n\", path, url, rc );\n }\n \n }\n else {\n \/\/ get locally \n pub_info->size = -1;\n \n struct timespec ts;\n clock_gettime( CLOCK_REALTIME, &ts );\n \n pub_info->mtime_sec = ts.tv_sec;\n pub_info->mtime_nsec = ts.tv_nsec;\n }\n \n free( url );\n return rc;\n}\n\n\n\/\/ handle dataset reversion \nint reversion_dataset( char const* path, struct AG_map_info* mi, void* driver_state ) {\n \n \/\/ evict the associated cached publish info \n char* info_path = md_fullpath( path, \"curl-info\", NULL );\n \n AG_driver_cache_evict_chunk( info_path );\n \n free( info_path );\n return 0;\n}\n\n\/\/ query type: curl\nchar* get_query_type(void) {\n return strdup(\"curl\");\n}\n<commit_msg>Don't bother re-obtaining publish information in the CURL driver when we fetch a block. The AG shouldn't evict the cached data until it is time to reversion.<commit_after>\/*\n Copyright 2014 The Trustees of Princeton University\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#include \"driver.h\"\n\n\/\/ start up the driver\nint driver_init( void** driver_state ) {\n \n return 0;\n}\n\n\n\/\/ shut down the driver \nint driver_shutdown( void* driver_state ) {\n \n return 0;\n}\n\n\/\/ connect\nint connect_dataset_block( struct AG_connection_context* ag_ctx, void* driver_state, void** driver_connection_state ) {\n \n char* request_path = AG_driver_get_request_path( ag_ctx );\n char* url = AG_driver_get_query_string( ag_ctx );\n \n struct curl_connection_context* curl_ctx = CALLOC_LIST( struct curl_connection_context, 1 );\n \n curl_ctx->request_path = request_path;\n curl_ctx->url = url;\n \n *driver_connection_state = curl_ctx;\n \n return 0;\n}\n\n\/\/ free a connection context \nint close_dataset_block( void* driver_connection_state ) {\n \n struct curl_connection_context* curl_ctx = (struct curl_connection_context*)driver_connection_state;\n \n if( curl_ctx != NULL ) {\n if( curl_ctx->request_path != NULL ) {\n free( curl_ctx->request_path );\n curl_ctx->request_path = NULL;\n }\n\n if( curl_ctx->url != NULL ) {\n free( curl_ctx->url );\n curl_ctx->url = NULL;\n }\n\n free( curl_ctx );\n }\n return 0;\n}\n\n\n\/\/ dummy header function; seems to be needed to stat files \nstatic size_t curl_null_header( void* ptr, size_t size, size_t nmemb, void* data ) {\n return size * nmemb;\n}\n\n\/\/ write function to fill our buffer, and abort if we get too much \nstatic size_t curl_write_block( void* ptr, size_t size, size_t nmemb, void* data ) {\n \n struct curl_write_context* write_ctx = (struct curl_write_context*)data;\n \n size_t total_available = size * nmemb;\n \n \/\/ have space?\n if( write_ctx->num_written + total_available <= write_ctx->buf_len ) {\n \n memcpy( write_ctx->buf + write_ctx->num_written, ptr, total_available );\n write_ctx->num_written += total_available;\n \n return total_available;\n }\n else {\n \/\/ not enough space\n errorf(\"Not enough space (have %zu bytes, but need at least %zu)\\n\", write_ctx->buf_len, write_ctx->num_written + total_available );\n return 0;\n }\n}\n\n\n\/\/ find out how big a file is, and when it was modified \n\/\/ return 0 on success\n\/\/ return negative errno on failure, or if errno was not set, return positive curl status code on failure\nstatic int curl_stat_file( CURL* curl, char const* url, struct AG_driver_publish_info* pub_info ) {\n \n dbprintf(\"stat %s\\n\", url );\n \n \/\/ set up the curl handle\n curl_easy_setopt( curl, CURLOPT_URL, url );\n curl_easy_setopt( curl, CURLOPT_NOBODY, 1L );\n curl_easy_setopt( curl, CURLOPT_FILETIME, 1L );\n curl_easy_setopt( curl, CURLOPT_HEADERFUNCTION, curl_null_header );\n curl_easy_setopt( curl, CURLOPT_HEADER, 0L );\n \n int rc = curl_easy_perform( curl );\n \n if( rc != 0 ) {\n \/\/ error of some sort \n long oserr = 0;\n \n curl_easy_getinfo( curl, CURLINFO_OS_ERRNO, &oserr );\n \n if( oserr != 0 ) {\n errorf(\"curl_easy_perform(%s) rc = %d, errno = %ld\\n\", url, rc, -oserr );\n return (int)(-oserr);\n }\n else {\n errorf(\"curl_easy_perform(%s) rc = %d\\n\", url, rc );\n return rc;\n }\n }\n \n \/\/ success! get info \n long filetime = -1;\n double filesize = -1.0;\n \n int filetime_rc = curl_easy_getinfo( curl, CURLINFO_FILETIME, &filetime );\n int filesize_rc = curl_easy_getinfo( curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &filesize );\n \n if( (filetime_rc != 0 || filetime < 0) || (filesize_rc != 0 || filesize <= 0.0 ) ) {\n \n \/\/ failed to get data\n rc = -ENODATA;\n \n if( filetime_rc != 0 ) {\n errorf(\"curl_easy_getinfo( CURLINFO_FILETIME ) rc = %d\\n\", filetime_rc );\n rc = filetime_rc;\n }\n if( filesize_rc != 0 ) {\n errorf(\"curl_easy_getinfo( CURLINFO_CONTENT_LENGTH_DOWNLOAD ) rc = %d\\n\", filesize_rc );\n rc = filesize_rc;\n }\n \n return rc;\n }\n \n \/\/ fill in our pubinfo \n pub_info->size = (off_t)filesize;\n \n \/\/ set the time to now \n pub_info->mtime_sec = (int64_t)filetime;\n pub_info->mtime_nsec = 0;\n \n return 0;\n}\n\n\n\/\/ get a block of data, and get its pubinfo while we're at it\n\/\/ return the number of bytes received on success\n\/\/ return negative errno on failure, or if errno was not set, return positive curl status code on failure\nstatic int curl_download_block( CURL* curl, char const* url, uint64_t block_id, char* buf, uint64_t block_size, struct AG_driver_publish_info* pub_info ) {\n \n dbprintf(\"Get block %s\\n\", url );\n \n struct curl_write_context write_ctx;\n memset( &write_ctx, 0, sizeof(struct curl_write_context) );\n \n write_ctx.num_written = 0;\n write_ctx.buf = buf;\n write_ctx.buf_len = block_size;\n \n \/\/ set up the curl handle\n curl_easy_setopt( curl, CURLOPT_URL, url );\n curl_easy_setopt( curl, CURLOPT_FILETIME, 1L );\n curl_easy_setopt( curl, CURLOPT_HEADERFUNCTION, curl_null_header );\n curl_easy_setopt( curl, CURLOPT_HEADER, 0L );\n curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, curl_write_block );\n curl_easy_setopt( curl, CURLOPT_WRITEDATA, &write_ctx );\n \n \/\/ add range requirement\n \/\/ format: X-Y, where X and Y are 64-bit byte indices. Y is inclusive\n size_t range_maxlen = 20 + 1 + 20 + 1; \/\/ NOTE: 19 < log10( UINT64_MAX ) < 20\n char range_buf[20 + 1 + 20 + 1]; \n snprintf( range_buf, range_maxlen, \"%\" PRIu64 \"-%\" PRIu64, block_id * block_size, (block_id + 1) * block_size - 1 );\n \n curl_easy_setopt( curl, CURLOPT_RANGE, range_buf );\n \n int rc = curl_easy_perform( curl );\n \n if( rc != 0 ) {\n \/\/ error of some sort \n long oserr = 0;\n \n curl_easy_getinfo( curl, CURLINFO_OS_ERRNO, &oserr );\n \n if( oserr != 0 ) {\n errorf(\"curl_easy_perform(%s) rc = %d, errno = %ld\\n\", url, rc, -oserr );\n return (int)(-oserr);\n }\n else {\n if( rc == CURLE_BAD_DOWNLOAD_RESUME ) {\n \/\/ EOF \n errorf(\"WARN: Block %\" PRIu64 \" is off the end of the file\\n\", block_id );\n \n write_ctx.num_written = 0;\n }\n else {\n errorf(\"curl_easy_perform(%s) rc = %d\\n\", url, rc );\n return -rc;\n }\n }\n }\n \n \/\/ success! opportunistically try to get metadata info \n long filetime = -1;\n double filesize = -1.0;\n \n int filetime_rc = curl_easy_getinfo( curl, CURLINFO_FILETIME, &filetime );\n int filesize_rc = curl_easy_getinfo( curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &filesize );\n \n \/\/ opportunistically got metadata?\n if( filetime_rc == 0 && filetime > 0 && filesize_rc == 0 && filesize >= 1.0 ) {\n \n \/\/ fill in our pubinfo \n pub_info->size = (off_t)filesize;\n pub_info->mtime_sec = (int64_t)filetime;\n pub_info->mtime_nsec = 0;\n }\n \n return write_ctx.num_written;\n}\n\n\n\/\/ get the publish information for a dataset \nint curl_get_pubinfo( char const* request_path, char const* url, struct AG_driver_publish_info* pubinfo ) {\n \n \/\/ maybe we've cached it?\n char* info_path = md_fullpath( request_path, \"curl-info\", NULL );\n \n char* pubinfo_buf = NULL;\n size_t pubinfo_buflen = 0;\n \n int rc = AG_driver_cache_get_chunk( info_path, &pubinfo_buf, &pubinfo_buflen );\n \n if( rc == 0 ) {\n \n if( pubinfo_buflen == sizeof(struct AG_driver_publish_info) ) {\n \/\/ success!\n memcpy( pubinfo, pubinfo_buf, sizeof(struct AG_driver_publish_info) );\n free( pubinfo_buf );\n \n AG_driver_cache_promote_chunk( info_path );\n free( info_path );\n return 0;\n }\n else {\n errorf(\"WARN: got invalid data for %s\\n\", info_path );\n AG_driver_cache_evict_chunk( info_path );\n \n rc = 0;\n free( pubinfo_buf );\n pubinfo_buf = NULL;\n }\n }\n \n \/\/ miss\n CURL* curl = curl_easy_init();\n\n \/\/ not cached\n rc = curl_stat_file( curl, url, pubinfo );\n if( rc != 0 ) {\n errorf(\"ERR: curl_stat_file(%s, %s) rc = %d\\n\", info_path, url, rc );\n }\n else {\n \/\/ success! cache it \n \n char* cache_chunk = CALLOC_LIST( char, sizeof(struct AG_driver_publish_info) );\n memcpy( cache_chunk, &pubinfo, sizeof(struct AG_driver_publish_info) );\n \n AG_driver_cache_put_chunk_async( info_path, cache_chunk, sizeof(struct AG_driver_publish_info) );\n \n dbprintf(\"Got pubinfo for %s: { size = %jd, mtime_sec = %\" PRId64 \", mtime_nsec = %\" PRId32 \" }\\n\", request_path, pubinfo->size, pubinfo->mtime_sec, pubinfo->mtime_nsec );\n }\n \n curl_easy_cleanup( curl );\n \n free( info_path );\n \n return rc;\n}\n\n\n\/\/ get data for a block.\n\/\/ get it from the cache, if possible.\n\/\/ otherwise, download it and serve it back \nssize_t get_dataset_block( struct AG_connection_context* ag_ctx, uint64_t block_id, char* block_buf, size_t buf_len, void* driver_connection_state ) {\n \n struct curl_connection_context* curl_ctx = (struct curl_connection_context*)driver_connection_state;\n \n \/\/ opportunistically get pubinfo\n struct AG_driver_publish_info pubinfo;\n memset( &pubinfo, 0, sizeof(struct AG_driver_publish_info) );\n \n pubinfo.size = -1;\n pubinfo.mtime_sec = -1;\n \n CURL* curl = curl_easy_init();\n \n \/\/ no data cached; go get it \n int num_read = curl_download_block( curl, curl_ctx->url, block_id, block_buf, buf_len, &pubinfo );\n \n if( num_read < 0 ) {\n \n errorf(\"curl_download_block(%s, %\" PRIu64 \") rc = %d\\n\", curl_ctx->url, block_id, num_read );\n }\n \n curl_easy_cleanup( curl );\n \n return num_read;\n}\n\n\n\/\/ prepare to publish--fill in pub_info\nint stat_dataset( char const* path, struct AG_map_info* map_info, struct AG_driver_publish_info* pub_info, void* driver_state ) {\n \n char* url = AG_driver_map_info_get_query_string( map_info );\n \n \n dbprintf(\"stat %s (url: %s)\\n\", path, url );\n \n if( url == NULL ) {\n \n \/\/ it's a directory.\n \/\/ timestamp is simply now \n pub_info->size = 4096;\n \n struct timespec ts;\n clock_gettime( CLOCK_REALTIME, &ts );\n \n pub_info->mtime_sec = ts.tv_sec;\n pub_info->mtime_nsec = ts.tv_nsec;\n \n return 0;\n }\n \n int rc = 0;\n \n \/\/ it's a file.\n \/\/ get information from upstream?\n char* get_from_upstream = AG_driver_get_config_var( AG_CURL_DRIVER_CONFIG_CHECK_UPSTREAM );\n if( get_from_upstream != NULL ) {\n \n free( get_from_upstream );\n \n \/\/ get the info from upstream\n int rc = curl_get_pubinfo( path, url, pub_info );\n \n if( rc != 0 ) {\n errorf(\"curl_get_pubinfo(%s, %s) rc = %d\\n\", path, url, rc );\n }\n \n }\n else {\n \/\/ get locally \n pub_info->size = -1;\n \n struct timespec ts;\n clock_gettime( CLOCK_REALTIME, &ts );\n \n pub_info->mtime_sec = ts.tv_sec;\n pub_info->mtime_nsec = ts.tv_nsec;\n }\n \n free( url );\n return rc;\n}\n\n\n\/\/ handle dataset reversion \nint reversion_dataset( char const* path, struct AG_map_info* mi, void* driver_state ) {\n \n \/\/ evict the associated cached publish info \n char* info_path = md_fullpath( path, \"curl-info\", NULL );\n \n AG_driver_cache_evict_chunk( info_path );\n \n free( info_path );\n return 0;\n}\n\n\/\/ query type: curl\nchar* get_query_type(void) {\n return strdup(\"curl\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017 offa\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions.\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"danek\/internal\/ToString.h\"\n#include \"danek\/internal\/ConfigItem.h\"\n#include \"danek\/internal\/ConfigScope.h\"\n#include \"danek\/internal\/UidIdentifierProcessor.h\"\n#include <algorithm>\n#include <iterator>\n#include <sstream>\n\nnamespace danek\n{\n\n namespace\n {\n std::string indent(std::size_t level)\n {\n constexpr std::size_t indentCount = 4;\n return std::string(level * indentCount, ' ');\n }\n\n\n void replaceInplace(std::string& input, const std::string& str, const std::string& replacement)\n {\n if( str.empty() == false )\n {\n std::size_t pos = 0;\n\n while( ( pos = input.find(str, pos) ) != std::string::npos )\n {\n input.replace(pos, str.size(), replacement);\n pos += replacement.size();\n }\n }\n }\n\n\n std::string escape(const std::string& str)\n {\n auto output = str;\n\n replaceInplace(output, \"%\", \"%%\");\n replaceInplace(output, \"\\t\", \"%t\");\n replaceInplace(output, \"\\n\", \"%n\");\n replaceInplace(output, \"\\\"\", \"%\\\"\");\n\n return \"\\\"\" + output + \"\\\"\";\n }\n\n\n std::string expandUid(const std::string& name, bool expand)\n {\n if( expand == false )\n {\n UidIdentifierProcessor uidIdProc;\n StringBuffer nameBuf;\n return uidIdProc.unexpand(name.c_str(), nameBuf);\n }\n return name;\n }\n\n void appendConfType(std::stringstream& stream, const ConfigScope& scope, ConfType type, bool expandUid, std::size_t indentLevel)\n {\n auto names = scope.listLocallyScopedNames(type, false, { });\n std::sort(names.begin(), names.end());\n\n for( std::size_t i=0; i<names.size(); ++i )\n {\n const auto item = scope.findItem(names[i]);\n stream << toString(*item, item->name(), expandUid, indentLevel);\n }\n }\n\n }\n\n\n std::string toString(const ConfigItem& item, const std::string& name, bool expandUidNames, std::size_t indentLevel)\n {\n const std::string nameStr = expandUid(name, expandUidNames);\n std::stringstream os;\n\n os << indent(indentLevel);\n\n switch(item.type())\n {\n case ConfType::String:\n os << nameStr << \" = \" << escape(item.stringVal()) << \";\\n\";\n break;\n case ConfType::List:\n {\n os << nameStr << \" = [\";\n const auto values = item.listVal();\n\n if( values.empty() == false )\n {\n using OItr = std::ostream_iterator<std::string>;\n std::transform(values.cbegin(), std::prev(values.cend()), OItr{os, \", \"}, escape);\n std::transform(std::prev(values.cend()), values.cend(), OItr{os}, escape);\n }\n\n os << \"];\\n\";\n }\n break;\n case ConfType::Scope:\n {\n os << nameStr << \" {\\n\";\n StringBuffer buffer;\n os << toString(*(item.scopeVal()), expandUidNames, indentLevel + 1);\n os << indent(indentLevel) << buffer.str() << \"}\\n\";\n }\n break;\n default:\n break;\n }\n\n return os.str();\n }\n\n\n std::string toString(const ConfigScope& scope, bool expandUidNames, std::size_t indentLevel)\n {\n std::stringstream ss;\n appendConfType(ss, scope, ConfType::Variables, expandUidNames, indentLevel);\n appendConfType(ss, scope, ConfType::Scope, expandUidNames, indentLevel);\n\n return ss.str();\n }\n\n}\n<commit_msg>Useless code removed.<commit_after>\/\/ Copyright (c) 2017 offa\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions.\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"danek\/internal\/ToString.h\"\n#include \"danek\/internal\/ConfigItem.h\"\n#include \"danek\/internal\/ConfigScope.h\"\n#include \"danek\/internal\/UidIdentifierProcessor.h\"\n#include <algorithm>\n#include <iterator>\n#include <sstream>\n\nnamespace danek\n{\n\n namespace\n {\n std::string indent(std::size_t level)\n {\n constexpr std::size_t indentCount = 4;\n return std::string(level * indentCount, ' ');\n }\n\n\n void replaceInplace(std::string& input, const std::string& str, const std::string& replacement)\n {\n if( str.empty() == false )\n {\n std::size_t pos = 0;\n\n while( ( pos = input.find(str, pos) ) != std::string::npos )\n {\n input.replace(pos, str.size(), replacement);\n pos += replacement.size();\n }\n }\n }\n\n\n std::string escape(const std::string& str)\n {\n auto output = str;\n\n replaceInplace(output, \"%\", \"%%\");\n replaceInplace(output, \"\\t\", \"%t\");\n replaceInplace(output, \"\\n\", \"%n\");\n replaceInplace(output, \"\\\"\", \"%\\\"\");\n\n return \"\\\"\" + output + \"\\\"\";\n }\n\n\n std::string expandUid(const std::string& name, bool expand)\n {\n if( expand == false )\n {\n UidIdentifierProcessor uidIdProc;\n StringBuffer nameBuf;\n return uidIdProc.unexpand(name.c_str(), nameBuf);\n }\n return name;\n }\n\n void appendConfType(std::stringstream& stream, const ConfigScope& scope, ConfType type, bool expandUid, std::size_t indentLevel)\n {\n auto names = scope.listLocallyScopedNames(type, false, { });\n std::sort(names.begin(), names.end());\n\n for( std::size_t i=0; i<names.size(); ++i )\n {\n const auto item = scope.findItem(names[i]);\n stream << toString(*item, item->name(), expandUid, indentLevel);\n }\n }\n\n }\n\n\n std::string toString(const ConfigItem& item, const std::string& name, bool expandUidNames, std::size_t indentLevel)\n {\n const std::string nameStr = expandUid(name, expandUidNames);\n std::stringstream os;\n\n os << indent(indentLevel);\n\n switch(item.type())\n {\n case ConfType::String:\n os << nameStr << \" = \" << escape(item.stringVal()) << \";\\n\";\n break;\n case ConfType::List:\n {\n os << nameStr << \" = [\";\n const auto values = item.listVal();\n\n if( values.empty() == false )\n {\n using OItr = std::ostream_iterator<std::string>;\n std::transform(values.cbegin(), std::prev(values.cend()), OItr{os, \", \"}, escape);\n std::transform(std::prev(values.cend()), values.cend(), OItr{os}, escape);\n }\n\n os << \"];\\n\";\n }\n break;\n case ConfType::Scope:\n {\n os << nameStr << \" {\\n\";\n os << toString(*(item.scopeVal()), expandUidNames, indentLevel + 1);\n os << indent(indentLevel) << \"}\\n\";\n }\n break;\n default:\n break;\n }\n\n return os.str();\n }\n\n\n std::string toString(const ConfigScope& scope, bool expandUidNames, std::size_t indentLevel)\n {\n std::stringstream ss;\n appendConfType(ss, scope, ConfType::Variables, expandUidNames, indentLevel);\n appendConfType(ss, scope, ConfType::Scope, expandUidNames, indentLevel);\n\n return ss.str();\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"MainWindow.h\"\n\n#include <y\/io\/File.h>\n\n#include <yave\/framegraph\/renderers.h>\n\nusing namespace editor;\n\n\nint test_graph() {\n\tInstance instance(DebugParams::debug());\n\tDevice device(instance);\n\tScene scene;\n\n\t{\n\t\tFrameGraph graph(&device);\n\n\t\tauto& gbuffer = render_gbuffer(graph, SceneView(scene), math::Vec2ui(512));\n\n\t\t{\n\t\t\tCmdBufferRecorder rec(device.create_disposable_cmd_buffer());\n\t\t\tstd::move(graph).render(rec, gbuffer.color);\n\t\t\tRecordedCmdBuffer cmd(std::move(rec));\n\t\t\tdevice.queue(vk::QueueFlagBits::eGraphics).submit<SyncSubmit>(std::move(cmd));\n\t\t}\n\t}\n\n\treturn 4;\n}\n\nvoid test_mat_data() {\n\tstruct Tester : NonCopyable {\n\t\tusize& i;\n\n\t\tTester(usize& p) : i(p) {\n\t\t}\n\n\t\t~Tester() {\n\t\t\t++i;\n\t\t}\n\t};\n\n\tusize i = 0;\n\t{\n\t\tMaterialData data;\n\n\t\t{\n\t\t\tauto test = std::make_shared<Tester>(i);\n\t\t}\n\t\tif(i != 1) {\n\t\t\ty_fatal(\"Tester not deleted.\");\n\t\t}\n\n\t\t{\n\t\t\tauto test = std::make_shared<Tester>(i);\n\t\t\tdata.keep_alive(test);\n\t\t}\n\t\tif(i != 1) {\n\t\t\ty_fatal(\"Tester deleted.\");\n\t\t}\n\t}\n\tif(i != 2) {\n\t\ty_fatal(\"Tester not deleted.\");\n\t}\n\tlog_msg(\"Test = OK\");\n}\n\nint main(int argc, char** argv) {\n\tperf::set_output(std::move(io::File::create(\"perfdump.json\").unwrap()));\n\n\t\/*log_msg(\"Testing frame graph\");\n\n\treturn test_graph();*\/\n\n\n\n\n\tbool debug = true;\n\tfor(std::string_view arg : core::ArrayView<const char*>(argv, argc)) {\n\t\tif(arg == \"--nodebug\") {\n\t\t\tlog_msg(\"Vulkan debugging disabled\", Log::Warning);\n\t\t\tdebug = false;\n\t\t}\n\t}\n\n\tInstance instance(debug ? DebugParams::debug() : DebugParams::none());\n\tDevice device(instance);\n\n\tEditorContext ctx(&device);\n\n\tMainWindow window(&ctx);\n\twindow.exec();\n\n\treturn 0;\n}\n<commit_msg>Fixed compilation failure<commit_after>\n#include \"MainWindow.h\"\n\n#include <y\/io\/File.h>\n\n#include <yave\/framegraph\/renderers.h>\n\nusing namespace editor;\n\n\nint test_graph() {\n\tInstance instance(DebugParams::debug());\n\tDevice device(instance);\n\tScene scene;\n\n\t{\n\t\tFrameGraph graph(&device);\n\n\t\tauto& gbuffer = render_gbuffer(graph, SceneView(scene), math::Vec2ui(512));\n\n\t\t{\n\t\t\tCmdBufferRecorder rec(device.create_disposable_cmd_buffer());\n\t\t\tstd::move(graph).render(rec, gbuffer.color);\n\t\t\tRecordedCmdBuffer cmd(std::move(rec));\n\t\t\tdevice.queue(vk::QueueFlagBits::eGraphics).submit<SyncSubmit>(std::move(cmd));\n\t\t}\n\t}\n\n\treturn 4;\n}\n\nint main(int argc, char** argv) {\n\tperf::set_output(std::move(io::File::create(\"perfdump.json\").unwrap()));\n\n\t\/*log_msg(\"Testing frame graph\");\n\n\treturn test_graph();*\/\n\n\n\n\n\tbool debug = true;\n\tfor(std::string_view arg : core::ArrayView<const char*>(argv, argc)) {\n\t\tif(arg == \"--nodebug\") {\n\t\t\tlog_msg(\"Vulkan debugging disabled\", Log::Warning);\n\t\t\tdebug = false;\n\t\t}\n\t}\n\n\tInstance instance(debug ? DebugParams::debug() : DebugParams::none());\n\tDevice device(instance);\n\n\tEditorContext ctx(&device);\n\n\tMainWindow window(&ctx);\n\twindow.exec();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"box.hpp\"\n#include <cmath>\n#include <iostream>\n#include <string>\n#include \"color.hpp\"\n#include \"ray.hpp\"\n#include \"material.hpp\"\n#include <glm\/glm.hpp>\n\nBox::Box() : Shape{}, min_{0.0f, 0.0f, 0.0f}, max_{0.0f, 0.0f, 0.0f} {}\nBox::Box(glm::vec3 const& min, glm::vec3 const& max):Shape{}, min_{min}, max_{max} {}\n\/\/ Box::Box(glm::vec3 const& min, glm::vec3 const& max, std::string name, Color const& color):Shape{name, color}, min_{min}, max_{max} {}\n\/\/Box::~Box(){std::cout << \"Box Destructor\" << std::endl;}\n\n\/*Box::Box(glm::vec3 const& min, glm::vec3 const& max, std::string name, Material const& mat):Shape{name, mat}, min_{min}, max_{max} {}\nBox::Box(glm::vec3 const& min, glm::vec3 const& max, std::string name, std::string name_mat, Color const& ka, Color const& kd, Color const& ks,\nfloat m):Shape{name, name_mat, ka, kd, ks, m}, min_{min}, max_{max} {}*\/\n\nBox::Box(std::string name, glm::vec3 const& min, glm::vec3 const& max, std::string material):Shape{name, material}, \nmin_{min}, max_{max} {}\n\n\nglm::vec3 const& Box::get_min()const{\n\treturn min_;\n}\nglm::vec3 const& Box::get_max()const{\n\treturn max_;\n}\n\n\n\/*float Box::area() const{\n\tfloat depth = fabs(max_.x - min_.x);\n\tfloat width = fabs(max_.y - min_.y);\n\tfloat high = fabs(max_.z - min_.z);\n\treturn (2 * high * width + 2 * width * depth + 2 * high * depth) ;\n}\nfloat Box::volume() const{\n\tfloat depth = fabs(max_.x - min_.x);\n\tfloat width = fabs(max_.y - min_.y);\n\tfloat high = fabs(max_.z - min_.z);\n\treturn (high * width * depth);\n}*\/\n\nstd::ostream& Box::print(std::ostream& os) const{\n\tShape::print(os);\n\t\/\/os << \"Name: \" << get_name() << \", Color: \" << get_color().r << \" \" << get_color().g << \" \" << get_color().b << \"\\n\";\n\tos << \"Min: \" << min_.x << \" \" << min_.y << \" \" << min_.z << \", Max: \"<< max_.x << \" \" << max_.y << \" \" << max_.z;\n\treturn os;\n}\n\nbool Box::intersect(Ray const& ray, float& distance) const{\n double a = (get_min().x - ray.origin.x) * ray.inv_direction.x;\n double b = (get_max().x - ray.origin.x) * ray.inv_direction.x;\n double tmin = std::min(a, b);\n double tmax = std::max(a, b);\n\n a = (get_min().y - ray.origin.y) * ray.inv_direction.y;\n b = (get_max().y - ray.origin.y) * ray.inv_direction.y;\n tmin = std::max(tmin, std::min(a, b));\n tmax = std::min(tmax, std::max(a, b));\n\n a = (get_min().z - ray.origin.z) * ray.inv_direction.z;\n b = (get_max().z - ray.origin.z) * ray.inv_direction.z;\n tmin = std::max(tmin, std::min(a, b));\n tmax = std::min(tmax, std::max(a, b));\n\n if (tmax > std::max(0.0, tmin)) {\n distance = sqrt(tmin * tmin * (ray.direction.x * ray.direction.x + ray.direction.y * ray.direction.y + ray.direction.z * ray.direction.z));\n return true;\n }\n return false;\n}\n\nbool Box::intersect(Ray const& ray, float& distance, glm::vec3& intersection, glm::vec3& normal) const{\n double a = (min_.x - ray.origin.x) * ray.inv_direction.x;\n double b = (max_.x - ray.origin.x) * ray.inv_direction.x;\n double tmin = std::min(a, b);\n double tmax = std::max(a, b);\n\n a = (min_.y - ray.origin.y) * ray.inv_direction.y;\n b = (max_.y - ray.origin.y) * ray.inv_direction.y;\n tmin = std::max(tmin, std::min(a, b));\n tmax = std::min(tmax, std::max(a, b));\n\n a = (min_.z - ray.origin.z) * ray.inv_direction.z;\n b = (max_.z - ray.origin.z) * ray.inv_direction.z;\n tmin = std::max(tmin, std::min(a, b));\n tmax = std::min(tmax, std::max(a, b));\n\n\t\/\/neu\n float t = tmin;\n if (t < 0){\n \tt = tmax;\n \tif (t < 0) return false;\n }\n \n \/\/Intersectionpoint\n intersection = ray.origin + ray.direction * t;\n \n\n \/\/normale\n \/\/Ein Wert des Intersectionpoint muss mit min oder max übereinstimmen\n\n if (min_.x == intersection.x)\n {\n \/\/vorne\n normal = normale_box(min_, intersection, glm::vec3(min_.x, max_.y, max_.z) );\n }\n else if (max_.x == intersection.x)\n {\n \/\/hinten\n normal = normale_box(max_, intersection, glm::vec3(max_.x, min_.y, min_.z) );\n }\n else if (min_.y == intersection.y)\n {\n \/\/links\n normal = normale_box(min_, intersection, glm::vec3(max_.x, min_.y, max_.z) );\n }\n else if (max_.y == intersection.y)\n {\n \/\/rechts\n normal = normale_box(max_, intersection, glm::vec3(min_.x, max_.y, min_.z) );\n }\n else if (min_.z == intersection.z)\n {\n \/\/unten\n normal = normale_box(min_, intersection, glm::vec3(max_.x, max_.y, min_.z) );\n }\n else if (max_.z == intersection.z)\n {\n \/\/oben\n normal = normale_box(max_, intersection, glm::vec3(min_.x, min_.y, max_.z) );\n }\n\n\n\n \/\/ende neu\n if (tmax > std::max(0.0, tmin)) {\n distance = sqrt(tmin * tmin * (ray.direction.x * ray.direction.x + ray.direction.y * ray.direction.y + ray.direction.z * ray.direction.z));\n return true;\n }\n return false;\n}\n\nglm::vec3 Box::normale_box(glm::vec3 const& p1, glm::vec3 const& p2, glm::vec3 const& p3)const{\n glm::vec3 normale(0.0,0.0,0.0);\n \/\/ überprüfen ob Ebene möglich\n float rx = (p3.x-p1.x)\/(p2.x-p1.x);\n float ry = (p3.y-p1.y)\/(p2.y-p1.y);\n float rz = (p3.z-p3.z)\/(p2.z-p1.z);\n\n if(rx == ry && ry == rz){\n \/\/Normale der Gerade berechnen (richtungsvektor*normalenvektor = 0)\n normale.x = (p2.y-p1.y) * -1;\n normale.y = (p2.x-p1.x);\n }\n else{\n \/\/Kreuzprodukt der beiden Richtungsvektoren\n normale.x = (((p2.y-p1.y) * (p3.z-p1.z)) - ((p2.z-p1.z) * (p3.y-p1.y)));\n normale.y = (((p2.z-p1.z) * (p3.x-p1.x)) - ((p2.x-p1.x) * (p3.z-p1.z)));\n normale.z = (((p2.x-p1.x) * (p3.y-p1.y)) - ((p2.y-p1.y) * (p3.x-p1.x)));\n }\n normale = glm::normalize(normale);\n return normale;\n\n}\n<commit_msg>Probe mit anderer Intersect<commit_after>#include \"box.hpp\"\n#include <cmath>\n#include <iostream>\n#include <string>\n#include \"color.hpp\"\n#include \"ray.hpp\"\n#include \"material.hpp\"\n#include <glm\/glm.hpp>\n\nBox::Box() : Shape{}, min_{0.0f, 0.0f, 0.0f}, max_{0.0f, 0.0f, 0.0f} {}\nBox::Box(glm::vec3 const& min, glm::vec3 const& max):Shape{}, min_{min}, max_{max} {}\n\/\/ Box::Box(glm::vec3 const& min, glm::vec3 const& max, std::string name, Color const& color):Shape{name, color}, min_{min}, max_{max} {}\n\/\/Box::~Box(){std::cout << \"Box Destructor\" << std::endl;}\n\n\/*Box::Box(glm::vec3 const& min, glm::vec3 const& max, std::string name, Material const& mat):Shape{name, mat}, min_{min}, max_{max} {}\nBox::Box(glm::vec3 const& min, glm::vec3 const& max, std::string name, std::string name_mat, Color const& ka, Color const& kd, Color const& ks,\nfloat m):Shape{name, name_mat, ka, kd, ks, m}, min_{min}, max_{max} {}*\/\n\nBox::Box(std::string name, glm::vec3 const& min, glm::vec3 const& max, std::string material):Shape{name, material}, \nmin_{min}, max_{max} {}\n\n\nglm::vec3 const& Box::get_min()const{\n\treturn min_;\n}\nglm::vec3 const& Box::get_max()const{\n\treturn max_;\n}\n\n\n\/*float Box::area() const{\n\tfloat depth = fabs(max_.x - min_.x);\n\tfloat width = fabs(max_.y - min_.y);\n\tfloat high = fabs(max_.z - min_.z);\n\treturn (2 * high * width + 2 * width * depth + 2 * high * depth) ;\n}\nfloat Box::volume() const{\n\tfloat depth = fabs(max_.x - min_.x);\n\tfloat width = fabs(max_.y - min_.y);\n\tfloat high = fabs(max_.z - min_.z);\n\treturn (high * width * depth);\n}*\/\n\nstd::ostream& Box::print(std::ostream& os) const{\n\tShape::print(os);\n\t\/\/os << \"Name: \" << get_name() << \", Color: \" << get_color().r << \" \" << get_color().g << \" \" << get_color().b << \"\\n\";\n\tos << \"Min: \" << min_.x << \" \" << min_.y << \" \" << min_.z << \", Max: \"<< max_.x << \" \" << max_.y << \" \" << max_.z;\n\treturn os;\n}\n\nbool Box::intersect(Ray const& ray, float& distance) const{\n double a = (get_min().x - ray.origin.x) * ray.inv_direction.x;\n double b = (get_max().x - ray.origin.x) * ray.inv_direction.x;\n double tmin = std::min(a, b);\n double tmax = std::max(a, b);\n\n a = (get_min().y - ray.origin.y) * ray.inv_direction.y;\n b = (get_max().y - ray.origin.y) * ray.inv_direction.y;\n tmin = std::max(tmin, std::min(a, b));\n tmax = std::min(tmax, std::max(a, b));\n\n a = (get_min().z - ray.origin.z) * ray.inv_direction.z;\n b = (get_max().z - ray.origin.z) * ray.inv_direction.z;\n tmin = std::max(tmin, std::min(a, b));\n tmax = std::min(tmax, std::max(a, b));\n\n if (tmax > std::max(0.0, tmin)) {\n distance = sqrt(tmin * tmin * (ray.direction.x * ray.direction.x + ray.direction.y * ray.direction.y + ray.direction.z * ray.direction.z));\n return true;\n }\n return false;\n}\n\nbool Box::intersect(Ray const& ray, float& distance, glm::vec3& intersection, glm::vec3& normal) const{\n double a = (min_.x - ray.origin.x) * ray.inv_direction.x;\n double b = (max_.x - ray.origin.x) * ray.inv_direction.x;\n double tmin = std::min(a, b);\n double tmax = std::max(a, b);\n\n a = (min_.y - ray.origin.y) * ray.inv_direction.y;\n b = (max_.y - ray.origin.y) * ray.inv_direction.y;\n tmin = std::max(tmin, std::min(a, b));\n tmax = std::min(tmax, std::max(a, b));\n\n a = (min_.z - ray.origin.z) * ray.inv_direction.z;\n b = (max_.z - ray.origin.z) * ray.inv_direction.z;\n tmin = std::max(tmin, std::min(a, b));\n tmax = std::min(tmax, std::max(a, b));\n\n\t\/\/neu\n float t = tmin;\n if (t < 0){\n \tt = tmax;\n \tif (t < 0) return false;\n }\n \n \/\/Intersectionpoint\n intersection = ray.origin + ray.direction * t;\n \n\n \/\/normale\n \n \/\/Ein Wert des Intersectionpoint muss mit min oder max übereinstimmen\n\n if (min_.x == intersection.x)\n {\n \/\/vorne\n normal = normale_box(min_, intersection, glm::vec3(min_.x, max_.y, max_.z) );\n }\n else if (max_.x == intersection.x)\n {\n \/\/hinten\n normal = normale_box(max_, intersection, glm::vec3(max_.x, min_.y, min_.z) );\n }\n else if (min_.y == intersection.y)\n {\n \/\/links\n normal = normale_box(min_, intersection, glm::vec3(max_.x, min_.y, max_.z) );\n }\n else if (max_.y == intersection.y)\n {\n \/\/rechts\n normal = normale_box(max_, intersection, glm::vec3(min_.x, max_.y, min_.z) );\n }\n else if (min_.z == intersection.z)\n {\n \/\/unten\n normal = normale_box(min_, intersection, glm::vec3(max_.x, max_.y, min_.z) );\n }\n else if (max_.z == intersection.z)\n {\n \/\/oben\n normal = normale_box(max_, intersection, glm::vec3(min_.x, min_.y, max_.z) );\n }\n \n \/\/normal = normale_box(intersection);\n\n \/\/ende neu\n if (tmax > std::max(0.0, tmin)) {\n distance = sqrt(tmin * tmin * (ray.direction.x * ray.direction.x + ray.direction.y * ray.direction.y + ray.direction.z * ray.direction.z));\n return true;\n }\n return false;\n}\n\nglm::vec3 Box::normale_box(glm::vec3 const& p1, glm::vec3 const& p2, glm::vec3 const& p3)const{\n glm::vec3 normale(0.0,0.0,0.0);\n\n \n \/\/ überprüfen ob Ebene möglich\n float rx = (p3.x-p1.x)\/(p2.x-p1.x);\n float ry = (p3.y-p1.y)\/(p2.y-p1.y);\n float rz = (p3.z-p3.z)\/(p2.z-p1.z);\n\n if(rx == ry && ry == rz){\n \/\/Normale der Gerade berechnen (richtungsvektor*normalenvektor = 0)\n normale.x = (p2.y-p1.y) * -1;\n normale.y = (p2.x-p1.x);\n }\n else{\n \/\/Kreuzprodukt der beiden Richtungsvektoren\n normale.x = (((p2.y-p1.y) * (p3.z-p1.z)) - ((p2.z-p1.z) * (p3.y-p1.y)));\n normale.y = (((p2.z-p1.z) * (p3.x-p1.x)) - ((p2.x-p1.x) * (p3.z-p1.z)));\n normale.z = (((p2.x-p1.x) * (p3.y-p1.y)) - ((p2.y-p1.y) * (p3.x-p1.x)));\n }\n \/*\n if (max_.x < origin.x)\n {\n normale.x = 1; \n }\n else{\n normale.x = -1;\n }\n\n if (max_.y < origin.y)\n {\n normale.y = 1; \n }\n else{\n normale.y = -1;\n }\n\n if (max_.z < origin.z)\n {\n normale.z = 1; \n }\n else{\n normale.z = -1;\n }*\/\n\n normale = glm::normalize(normale);\n return normale;\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef RAY_HPP\n#define RAY_HPP\n\n#include <glm\/vec3.hpp>\n#include <glm\/vec4.hpp>\n#include <glm\/glm.hpp>\nstruct Ray\n{\n\tRay():\n\torigin{0.0f,0.0f,0.0f},\n\tdirection{0.0f,0.0f,0.0f}\n\t{}\n\n\tRay(glm::vec3 const& ori, glm::vec3 const& dir):\n\torigin{ori},\n\tdirection{dir}\n\t{}\n\n\t\/*Ray(glm::vec4 const& transori, glm::vec4 const& transdir):\n\ttransorigin{transori},\n\ttransdirection{transdir}\n\t{}\n\n\tRay(glm::vec4 const& scalori, glm::vec4 const& scaldir):\n\tscaorigin{scalori},\n\tscadirection{scaldir}\n\t{}*\/\n\n\tglm::vec3 origin;\n\tglm::vec3 direction;\n\t\/*glm::vec4 transorigin;\n\tglm::vec4 transdirection;\n\tglm::vec4 scaorigin;\n\tglm::vec4 scadirection;*\/\n\n\tRay transformRay(glm::mat4 const& mat)\n{\n\n\n \/*glm::vec4 origin4{origin, 1.0f};\n glm::vec4 direction4{direction, 0.0f};\n glm::vec4 origin_trans = mat * origin4;\n glm::vec4 direction_trans = mat * direction4;\n\n glm::vec3 origin3(origin_trans);\n glm::vec3 direction3(direction_trans);\n\n Ray ray{origin3, direction3};\n\n return ray;*\/\n\n\n\tglm::vec4 origino{origin,1.0f};\n\tglm::vec4 directiono{direction,0.0f};\n\n \/\/world_transformation_inv = glm::inverse(world_transformation);\n \/\/world_transformation_inv_tp = glm::transpose(world_transformation_inv);\n\n \/\/glm::vec4 newOrigin {origin * world_transformation_inv};\n \/\/glm::vec4 newDirection{direction * world_transformation_inv};\n\n\tglm::vec4 origin_homogen = mat * origino;\n\tglm::vec4 direction_homogen = mat * directiono;\n\n\tglm::vec3 origini(origin_homogen);\n\tglm::vec3 directini(direction_homogen); \n\n\tRay ray{origini, directini};\n\n\t\/\/return Ray{glm::vec3{newOrigin.x, newOrigin.y, newOrigin.z }, glm::vec3{newDirection.x, newDirection.y, newDirection.z}};\n\treturn ray; \n}\n};\n\n#endif<commit_msg>Removed Comments at ray.hpp OK<commit_after>#ifndef RAY_HPP\n#define RAY_HPP\n\n#include <glm\/vec3.hpp>\n#include <glm\/vec4.hpp>\n#include <glm\/glm.hpp>\n\nstruct Ray\n{\n\tRay():\n\torigin{0.0f,0.0f,0.0f},\n\tdirection{0.0f,0.0f,0.0f}\n\t{}\n\n\tRay(glm::vec3 const& ori, glm::vec3 const& dir):\n\torigin{ori},\n\tdirection{dir}\n\t{}\n\n\tglm::vec3 origin;\n\tglm::vec3 direction;\n\n\tRay transformRay(glm::mat4 const& mat)\n\t{\n\t\tglm::vec4 origino{origin,1.0f};\n\t\tglm::vec4 directiono{direction,0.0f};\n\n\t\tglm::vec4 origin_homogen = mat * origino;\n\t\tglm::vec4 direction_homogen = mat * directiono;\n\n\t\tglm::vec3 origini(origin_homogen);\n\t\tglm::vec3 directini(direction_homogen); \n\n\t\treturn Ray {origini, directini};\n\t}\n};\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/ \n\/\/ Copyright (C) 2006-2011 SIPez LLC. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/\n\/\/ Copyright (C) 2004-2006 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"rtcp\/RtcpConfig.h\"\n\n#undef WANT_RTCP_LOG_MESSAGES\n#undef DROP_SOME_PACKETS\n\n\/\/ SYSTEM INCLUDES\n#include <assert.h>\n\n#ifdef _VXWORKS \/* [ *\/\n#include <iosLib.h>\n#include <netinet\/in.h>\n#endif \/* _VXWORKS ] *\/\n\n#ifdef WIN32 \/* [ *\/\n#include <winsock2.h>\n# ifndef WINCE\n# include <io.h>\n# endif\n#endif \/* WIN32 ] *\/\n\n#ifdef __pingtel_on_posix__ \/* [ *\/\n#include \"os\/OsIntTypes.h\"\n#include <sys\/types.h>\n#include <netinet\/in.h>\n#endif \/* __pingtel_on_posix__ ] *\/\n\n\/\/ APPLICATION INCLUDES\n#include \"os\/OsDefs.h\"\n#include \"mp\/MpMisc.h\"\n#include \"mp\/MpBuf.h\"\n#include \"mp\/MprToNet.h\"\n#include \"mp\/NetInTask.h\"\n#include \"mp\/MprFromNet.h\"\n#include \"mp\/dmaTask.h\"\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\n#ifdef ENABLE_PACKET_HACKING \/* [ *\/\nint MprToNet::sDebug1 = 0;\nint MprToNet::sDebug2 = 0;\nint MprToNet::sDebug3 = 0;\nint MprToNet::sDebug4 = 0;\nint MprToNet::sDebug5 = 0;\n#endif \/* ENABLE_PACKET_HACKING ] *\/\n\nstatic int doPadRtp = 1;\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nMprToNet::MprToNet()\n: mpFromNetPal(NULL)\n, mRtcpPackets(0)\n, mRtcpFrameCount(0)\n, mRtcpFrameLimit(500)\n#ifdef DEBUG \/* [ *\/\n, mRtpSampleCounter(0)\n#endif \/* DEBUG ] *\/\n, mTimestampDelta(0)\n, mSeqNum(0)\n, mSSRC(0)\n, mpRtpSocket(NULL)\n, mpRtcpSocket(NULL)\n, mNumRtpWriteErrors(0)\n, mNumRtcpWriteErrors(0)\n#ifdef INCLUDE_RTCP \/* [ *\/\n, mpiRTPAccumulator(NULL)\n#endif \/* INCLUDE_RTCP ] *\/\n\n{\n}\n\n\/\/ Destructor\nMprToNet::~MprToNet()\n{\n#ifdef INCLUDE_RTCP \/* [ *\/\n\n\/\/ Release the reference held to the RTP Accumulator interface used to\n\/\/ RTP outbound stream statistics\n if(mpiRTPAccumulator)\n {\n mpiRTPAccumulator->Release();\n mpiRTPAccumulator = NULL;\n }\n#endif \/* INCLUDE_RTCP ] *\/\n if (0 != mNumRtpWriteErrors) {\n osPrintf(\"MprToNet: %d network write errors on RTP socket!\\n\",\n mNumRtpWriteErrors);\n }\n if (0 != mNumRtcpWriteErrors) {\n osPrintf(\"MprToNet: %d network write errors on RTCP socket!\\n\",\n mNumRtcpWriteErrors);\n }\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\n\/\/ Set the outbound RTP and RTCP sockets.\nOsStatus MprToNet::setSockets(OsSocket& rRtpSocket, OsSocket& rRtcpSocket)\n{\n mpRtpSocket = &rRtpSocket;\n mpRtcpSocket = &rRtcpSocket;\n\n return OS_SUCCESS;\n}\n\n\/\/ Clear the outbound RTP and RTCP sockets.\nOsStatus MprToNet::resetSockets(void)\n{\n mpRtpSocket = NULL;\n mpRtcpSocket = NULL;\n\n return OS_SUCCESS;\n}\n\nvoid MprToNet::setSSRC(int iSSRC)\n{\n mSSRC = iSSRC;\n mSeqNum = rand_timer32() | 0xfc00;\n mTimestampDelta = rand_timer32();\n}\n\n#ifdef INCLUDE_RTCP \/* [ *\/\nvoid MprToNet::setRTPAccumulator(ISetSenderStatistics *piRTPAccumulator)\n{\n mpiRTPAccumulator = piRTPAccumulator;\n if(mpiRTPAccumulator)\n {\n mpiRTPAccumulator->SetRTPTimestamp(mTimestampDelta);\n }\n}\n\n#endif \/* INCLUDE_RTCP ] *\/\n\n#ifdef DROP_SOME_PACKETS \/\/ [\nstatic int dropLimit = 1<<30;\nstatic int dropCount = 0;\n\nextern \"C\" {\nextern int dropEvery(int limit);\n}\n\nint dropEvery(int limit)\n{\n int save = dropLimit;\n if (limit < 0) limit = 1<<30;\n if (limit > 0) {\n dropLimit = limit;\n dropCount = 0;\n }\n return save;\n}\n#endif \/\/ DROP_SOME_PACKETS ]\n\nint MprToNet::writeRtp(int payloadType, UtlBoolean markerState,\n const unsigned char* payloadData, int payloadOctets,\n unsigned int timestamp, void* csrcList)\n{\n MpRtpBufPtr pRtpPacket;\n char paddingLength;\n\n \/\/ Nothing to do when no socket specified.\n if (mpRtpSocket == NULL)\n return 0;\n\n \/\/ Allocate new RTP packet.\n pRtpPacket = MpMisc.RtpPool->getBuffer();\n\n \/\/ Get rid of packet sequence number.\n mSeqNum++;\n\n \/\/ Fill packet RTP header.\n pRtpPacket->setRtpVersion(2);\n pRtpPacket->setRtpPayloadType(payloadType);\n pRtpPacket->setPayloadSize(payloadOctets);\n if (markerState)\n pRtpPacket->enableRtpMarker();\n else\n pRtpPacket->disableRtpMarker();\n pRtpPacket->disableRtpExtension();\n pRtpPacket->setRtpSequenceNumber(mSeqNum);\n pRtpPacket->setRtpTimestamp(mTimestampDelta + timestamp);\n pRtpPacket->setRtpSSRC(mSSRC);\n pRtpPacket->setRtpCSRCCount(0);\n\n#ifdef ENABLE_PACKET_HACKING \/* [ *\/\n adjustRtpPacket(pRtpPacket->getRtpHeader());\n#endif \/* ENABLE_PACKET_HACKING ] *\/\n\n \/\/ Calculate number of padding bytes\n paddingLength = doPadRtp ? ((4 - (payloadOctets & 3))&3) : 0;\n\n if (paddingLength>0)\n pRtpPacket->enableRtpPadding();\n else\n pRtpPacket->disableRtpPadding();\n\n if (csrcList != NULL)\n {\n int csrcSize = pRtpPacket->getRtpCSRCCount() * sizeof(RtpSRC);\n \/\/ TODO:: implement CSRC list.\n assert(csrcSize == 0);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Next part of code should separated from previous \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n char *pBuf;\n int numBytesSent;\n MpUdpBufPtr pUdpPacket;\n\n \/\/ Allocate UDP packet\n pUdpPacket = MpMisc.UdpPool->getBuffer();\n pBuf = pUdpPacket->getDataWritePtr();\n\n \/\/ Set size of data to send\n assert(pUdpPacket->getMaximumPacketSize() >= sizeof(RtpHeader)+payloadOctets+paddingLength);\n pUdpPacket->setPacketSize(sizeof(RtpHeader)+payloadOctets+paddingLength);\n\n \/\/ Copy RTP header to UDP packet\n memcpy(pBuf, &pRtpPacket->getRtpHeader(), sizeof(RtpHeader));\n pBuf += sizeof(RtpHeader);\n\n \/\/ TODO:: Copy CSRC list here.\n\n \/\/ Copy payload to UDP packet\n memcpy(pBuf, payloadData, payloadOctets);\n pBuf += payloadOctets;\n\n \/\/ Fill padding\n switch (paddingLength) {\n case 3:\n pBuf[1] = 0; \/\/ fall through\n case 2:\n pBuf[0] = 0; \/\/ fall through\n case 1:\n pBuf[paddingLength-1] = paddingLength; \/\/ fall through\n case 0:\n break;\n }\n\n#ifdef INCLUDE_RTCP \/* [ *\/\n \/\/ Update the Accumulated statistics kept for an inbound RTP packet.\n \/\/ These statistics comprise a Sender Report that is sent out periodically\n \/\/ to the originating site\n if(mpiRTPAccumulator)\n {\n mpiRTPAccumulator->IncrementCounts(payloadOctets);\n }\n#endif \/* INCLUDE_RTCP ] *\/\n\n#ifdef DROP_SOME_PACKETS \/* [ *\/\n if (dropCount++ == dropLimit) {\n dropCount = 0;\n numBytesSent = pUdpPacket->getPacketSize();\n } else {\n numBytesSent = mpRtpSocket->write(pUdpPacket->getDataPtr(), pUdpPacket->getPacketSize());\n }\n#else \/* DROP_SOME_PACKETS ] [*\/\n numBytesSent = mpRtpSocket->write(pUdpPacket->getDataPtr(), pUdpPacket->getPacketSize());\n#endif \/* DROP_SOME_PACKETS ] *\/\n\n#ifdef TEST_PRINT\n UtlString remoteIp(\"null socket\");\n int remotePort;\n if(mpRtpSocket)\n {\n mpRtpSocket->getRemoteHostIp(&remoteIp, &remotePort);\n }\n OsSysLog::add(FAC_MP, PRI_DEBUG, \"MprToNet::writeRtp payload: %d send to address: %s port: %d numBytesSent: %d errno: %d\",\n payloadType, remoteIp.data(), remotePort, numBytesSent, errno);\n#endif\n\n if (numBytesSent != pUdpPacket->getPacketSize()) {\n switch (errno) {\n \/* insert other benign errno values here *\/\n case 0:\n case 55: \/\/ Network disconnected, continue and hope it comes back\n break;\n default:\n \/\/ close(fd); MAYBE: mpRtpSocket->close() ?\n \/\/ mpRtpSocket = NULL;\n break;\n }\n\n }\n return (pUdpPacket->getPacketSize() == numBytesSent) ? pUdpPacket->getPacketSize() : numBytesSent;\n}\n\n#ifdef ENABLE_PACKET_HACKING \/* [ *\/\nextern \"C\" {\nextern int sTRA(int a, int b, int c);\nextern int setToRtpAdjustment(int a, int b, int c);\n};\n\nint setToRtpAdjustment(int ssrc, int seq, int ts)\n{\n MprToNet::sDebug1 = ssrc;\n MprToNet::sDebug2 = seq;\n MprToNet::sDebug3 = ts;\n return 0;\n}\n\nint sTRA(int a, int b, int c) {return setToRtpAdjustment(a,b,c);}\n#endif \/* ENABLE_PACKET_HACKING ] *\/\n\n\/* ============================ ACCESSORS ================================= *\/\n\nOsStatus MprToNet::setRtpPal(MprFromNet* pal)\n{\n mpFromNetPal = pal;\n return OS_SUCCESS;\n}\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n#ifdef ENABLE_PACKET_HACKING \/* [ *\/\nvoid MprToNet::adjustRtpPacket(struct RtpHeader* rp)\n{\n struct RtpHeader rh;\n\n memcpy((char *) &rh, (char *) rp, sizeof(struct RtpHeader));\n \/\/ rh.vpxcc = rh.vpxcc;\n \/\/ rh.mpt = rh.mpt;\n rh.ssrc = ntohl(rh.ssrc) - sDebug1;\n rh.seq = ntohs(rh.seq) - sDebug2;\n rh.timestamp = ntohl(rh.timestamp) - sDebug3;\n rh.ssrc = htonl(rh.ssrc);\n rh.seq = htons(rh.seq);\n rh.timestamp = htonl(rh.timestamp);\n memcpy((char *) rp, (char *) &rh, sizeof(struct RtpHeader));\n}\n#endif \/* ENABLE_PACKET_HACKING ] *\/\n\n\/* ============================ FUNCTIONS ================================= *\/\n<commit_msg>Check if RTP output soceket is NULL immediately before write as it can be set to NULL outside media task. This sometimes caused a crash in when many lines are active.<commit_after>\/\/ \n\/\/ Copyright (C) 2006-2012 SIPez LLC. All rights reserved.\n\/\/\n\/\/ Copyright (C) 2004-2006 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"rtcp\/RtcpConfig.h\"\n\n#undef WANT_RTCP_LOG_MESSAGES\n#undef DROP_SOME_PACKETS\n\n\/\/ SYSTEM INCLUDES\n#include <assert.h>\n\n#ifdef _VXWORKS \/* [ *\/\n#include <iosLib.h>\n#include <netinet\/in.h>\n#endif \/* _VXWORKS ] *\/\n\n#ifdef WIN32 \/* [ *\/\n#include <winsock2.h>\n# ifndef WINCE\n# include <io.h>\n# endif\n#endif \/* WIN32 ] *\/\n\n#ifdef __pingtel_on_posix__ \/* [ *\/\n#include \"os\/OsIntTypes.h\"\n#include <sys\/types.h>\n#include <netinet\/in.h>\n#endif \/* __pingtel_on_posix__ ] *\/\n\n\/\/ APPLICATION INCLUDES\n#include \"os\/OsDefs.h\"\n#include \"mp\/MpMisc.h\"\n#include \"mp\/MpBuf.h\"\n#include \"mp\/MprToNet.h\"\n#include \"mp\/NetInTask.h\"\n#include \"mp\/MprFromNet.h\"\n#include \"mp\/dmaTask.h\"\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\n#ifdef ENABLE_PACKET_HACKING \/* [ *\/\nint MprToNet::sDebug1 = 0;\nint MprToNet::sDebug2 = 0;\nint MprToNet::sDebug3 = 0;\nint MprToNet::sDebug4 = 0;\nint MprToNet::sDebug5 = 0;\n#endif \/* ENABLE_PACKET_HACKING ] *\/\n\nstatic int doPadRtp = 1;\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nMprToNet::MprToNet()\n: mpFromNetPal(NULL)\n, mRtcpPackets(0)\n, mRtcpFrameCount(0)\n, mRtcpFrameLimit(500)\n#ifdef DEBUG \/* [ *\/\n, mRtpSampleCounter(0)\n#endif \/* DEBUG ] *\/\n, mTimestampDelta(0)\n, mSeqNum(0)\n, mSSRC(0)\n, mpRtpSocket(NULL)\n, mpRtcpSocket(NULL)\n, mNumRtpWriteErrors(0)\n, mNumRtcpWriteErrors(0)\n#ifdef INCLUDE_RTCP \/* [ *\/\n, mpiRTPAccumulator(NULL)\n#endif \/* INCLUDE_RTCP ] *\/\n\n{\n}\n\n\/\/ Destructor\nMprToNet::~MprToNet()\n{\n#ifdef INCLUDE_RTCP \/* [ *\/\n\n\/\/ Release the reference held to the RTP Accumulator interface used to\n\/\/ RTP outbound stream statistics\n if(mpiRTPAccumulator)\n {\n mpiRTPAccumulator->Release();\n mpiRTPAccumulator = NULL;\n }\n#endif \/* INCLUDE_RTCP ] *\/\n if (0 != mNumRtpWriteErrors) {\n osPrintf(\"MprToNet: %d network write errors on RTP socket!\\n\",\n mNumRtpWriteErrors);\n }\n if (0 != mNumRtcpWriteErrors) {\n osPrintf(\"MprToNet: %d network write errors on RTCP socket!\\n\",\n mNumRtcpWriteErrors);\n }\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\n\/\/ Set the outbound RTP and RTCP sockets.\nOsStatus MprToNet::setSockets(OsSocket& rRtpSocket, OsSocket& rRtcpSocket)\n{\n mpRtpSocket = &rRtpSocket;\n mpRtcpSocket = &rRtcpSocket;\n\n return OS_SUCCESS;\n}\n\n\/\/ Clear the outbound RTP and RTCP sockets.\nOsStatus MprToNet::resetSockets(void)\n{\n mpRtpSocket = NULL;\n mpRtcpSocket = NULL;\n\n return OS_SUCCESS;\n}\n\nvoid MprToNet::setSSRC(int iSSRC)\n{\n mSSRC = iSSRC;\n mSeqNum = rand_timer32() | 0xfc00;\n mTimestampDelta = rand_timer32();\n}\n\n#ifdef INCLUDE_RTCP \/* [ *\/\nvoid MprToNet::setRTPAccumulator(ISetSenderStatistics *piRTPAccumulator)\n{\n mpiRTPAccumulator = piRTPAccumulator;\n if(mpiRTPAccumulator)\n {\n mpiRTPAccumulator->SetRTPTimestamp(mTimestampDelta);\n }\n}\n\n#endif \/* INCLUDE_RTCP ] *\/\n\n#ifdef DROP_SOME_PACKETS \/\/ [\nstatic int dropLimit = 1<<30;\nstatic int dropCount = 0;\n\nextern \"C\" {\nextern int dropEvery(int limit);\n}\n\nint dropEvery(int limit)\n{\n int save = dropLimit;\n if (limit < 0) limit = 1<<30;\n if (limit > 0) {\n dropLimit = limit;\n dropCount = 0;\n }\n return save;\n}\n#endif \/\/ DROP_SOME_PACKETS ]\n\nint MprToNet::writeRtp(int payloadType, UtlBoolean markerState,\n const unsigned char* payloadData, int payloadOctets,\n unsigned int timestamp, void* csrcList)\n{\n MpRtpBufPtr pRtpPacket;\n char paddingLength;\n\n \/\/ Nothing to do when no socket specified.\n if (mpRtpSocket == NULL)\n return 0;\n\n \/\/ Allocate new RTP packet.\n pRtpPacket = MpMisc.RtpPool->getBuffer();\n\n \/\/ Get rid of packet sequence number.\n mSeqNum++;\n\n \/\/ Fill packet RTP header.\n pRtpPacket->setRtpVersion(2);\n pRtpPacket->setRtpPayloadType(payloadType);\n pRtpPacket->setPayloadSize(payloadOctets);\n if (markerState)\n pRtpPacket->enableRtpMarker();\n else\n pRtpPacket->disableRtpMarker();\n pRtpPacket->disableRtpExtension();\n pRtpPacket->setRtpSequenceNumber(mSeqNum);\n pRtpPacket->setRtpTimestamp(mTimestampDelta + timestamp);\n pRtpPacket->setRtpSSRC(mSSRC);\n pRtpPacket->setRtpCSRCCount(0);\n\n#ifdef ENABLE_PACKET_HACKING \/* [ *\/\n adjustRtpPacket(pRtpPacket->getRtpHeader());\n#endif \/* ENABLE_PACKET_HACKING ] *\/\n\n \/\/ Calculate number of padding bytes\n paddingLength = doPadRtp ? ((4 - (payloadOctets & 3))&3) : 0;\n\n if (paddingLength>0)\n pRtpPacket->enableRtpPadding();\n else\n pRtpPacket->disableRtpPadding();\n\n if (csrcList != NULL)\n {\n int csrcSize = pRtpPacket->getRtpCSRCCount() * sizeof(RtpSRC);\n \/\/ TODO:: implement CSRC list.\n assert(csrcSize == 0);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Next part of code should separated from previous \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n char *pBuf;\n unsigned int numBytesSent;\n MpUdpBufPtr pUdpPacket;\n\n \/\/ Allocate UDP packet\n pUdpPacket = MpMisc.UdpPool->getBuffer();\n pBuf = pUdpPacket->getDataWritePtr();\n\n \/\/ Set size of data to send\n assert(pUdpPacket->getMaximumPacketSize() >= sizeof(RtpHeader)+payloadOctets+paddingLength);\n pUdpPacket->setPacketSize(sizeof(RtpHeader)+payloadOctets+paddingLength);\n\n \/\/ Copy RTP header to UDP packet\n memcpy(pBuf, &pRtpPacket->getRtpHeader(), sizeof(RtpHeader));\n pBuf += sizeof(RtpHeader);\n\n \/\/ TODO:: Copy CSRC list here.\n\n \/\/ Copy payload to UDP packet\n memcpy(pBuf, payloadData, payloadOctets);\n pBuf += payloadOctets;\n\n \/\/ Fill padding\n switch (paddingLength) {\n case 3:\n pBuf[1] = 0; \/\/ fall through\n case 2:\n pBuf[0] = 0; \/\/ fall through\n case 1:\n pBuf[paddingLength-1] = paddingLength; \/\/ fall through\n case 0:\n break;\n }\n\n#ifdef INCLUDE_RTCP \/* [ *\/\n \/\/ Update the Accumulated statistics kept for an inbound RTP packet.\n \/\/ These statistics comprise a Sender Report that is sent out periodically\n \/\/ to the originating site\n if(mpiRTPAccumulator)\n {\n mpiRTPAccumulator->IncrementCounts(payloadOctets);\n }\n#endif \/* INCLUDE_RTCP ] *\/\n\n const char* writeBytes = pUdpPacket->getDataPtr();\n int packetSize = pUdpPacket->getPacketSize();\n\n#ifdef DROP_SOME_PACKETS \/* [ *\/\n if (dropCount++ == dropLimit) {\n dropCount = 0;\n numBytesSent = pUdpPacket->getPacketSize();\n } \n \/\/ Socket can get set asynchronously to NULL when RTP send is stopped. So check immediately before accessing socket.\n else if(mpRtpSocket)\n {\n numBytesSent = mpRtpSocket->write(writeBytes, packetSize);\n }\n else\n {\n numBytesSent = 0;\n }\n#else \/* DROP_SOME_PACKETS ] [*\/\n\n \/\/ Socket can get set asynchronously to NULL when RTP send is stopped. So check immediately before accessing socket.\n if(mpRtpSocket)\n {\n numBytesSent = mpRtpSocket->write(writeBytes, packetSize);\n }\n else\n {\n numBytesSent = 0;\n }\n#endif \/* DROP_SOME_PACKETS ] *\/\n\n#ifdef TEST_PRINT\n UtlString remoteIp(\"null socket\");\n int remotePort;\n if(mpRtpSocket)\n {\n mpRtpSocket->getRemoteHostIp(&remoteIp, &remotePort);\n }\n OsSysLog::add(FAC_MP, PRI_DEBUG, \"MprToNet::writeRtp payload: %d send to address: %s port: %d numBytesSent: %d errno: %d\",\n payloadType, remoteIp.data(), remotePort, numBytesSent, errno);\n#endif\n\n if (numBytesSent != pUdpPacket->getPacketSize()) {\n switch (errno) {\n \/* insert other benign errno values here *\/\n case 0:\n case 55: \/\/ Network disconnected, continue and hope it comes back\n break;\n default:\n \/\/ close(fd); MAYBE: mpRtpSocket->close() ?\n \/\/ mpRtpSocket = NULL;\n break;\n }\n\n }\n return (pUdpPacket->getPacketSize() == numBytesSent) ? pUdpPacket->getPacketSize() : numBytesSent;\n}\n\n#ifdef ENABLE_PACKET_HACKING \/* [ *\/\nextern \"C\" {\nextern int sTRA(int a, int b, int c);\nextern int setToRtpAdjustment(int a, int b, int c);\n};\n\nint setToRtpAdjustment(int ssrc, int seq, int ts)\n{\n MprToNet::sDebug1 = ssrc;\n MprToNet::sDebug2 = seq;\n MprToNet::sDebug3 = ts;\n return 0;\n}\n\nint sTRA(int a, int b, int c) {return setToRtpAdjustment(a,b,c);}\n#endif \/* ENABLE_PACKET_HACKING ] *\/\n\n\/* ============================ ACCESSORS ================================= *\/\n\nOsStatus MprToNet::setRtpPal(MprFromNet* pal)\n{\n mpFromNetPal = pal;\n return OS_SUCCESS;\n}\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n#ifdef ENABLE_PACKET_HACKING \/* [ *\/\nvoid MprToNet::adjustRtpPacket(struct RtpHeader* rp)\n{\n struct RtpHeader rh;\n\n memcpy((char *) &rh, (char *) rp, sizeof(struct RtpHeader));\n \/\/ rh.vpxcc = rh.vpxcc;\n \/\/ rh.mpt = rh.mpt;\n rh.ssrc = ntohl(rh.ssrc) - sDebug1;\n rh.seq = ntohs(rh.seq) - sDebug2;\n rh.timestamp = ntohl(rh.timestamp) - sDebug3;\n rh.ssrc = htonl(rh.ssrc);\n rh.seq = htons(rh.seq);\n rh.timestamp = htonl(rh.timestamp);\n memcpy((char *) rp, (char *) &rh, sizeof(struct RtpHeader));\n}\n#endif \/* ENABLE_PACKET_HACKING ] *\/\n\n\/* ============================ FUNCTIONS ================================= *\/\n<|endoftext|>"} {"text":"<commit_before>#include \".\/..\/include\/Camera.hpp\"\n#include <iostream>\n\n#include <glm\/gtc\/type_precision.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\nusing namespace std;\n\nCamera::Camera()\n : m_view{ glm::lookAt( glm::vec3{0, 0, -5}, glm::vec3{}, glm::vec3{0,1,0}) },\n m_fov{ 1.04f }, m_ratio{ 1.0f }, m_znear{ 1.0f }, m_zfar{ 500.0f },\n m_mouseBehavior{ ARCBALL_BEHAVIOR }\n{}\n\nCamera::~Camera()\n{\n\n}\n\nvoid Camera::animate(float time)\n{\n}\n\nconst glm::mat4& Camera::viewMatrix() const\n{\n return m_view;\n}\n\nvoid Camera::setViewMatrix(const glm::mat4& view)\n{\n m_view = view;\n}\n\nglm::vec3 Camera::getPosition() const\n{\n return -glm::vec3( m_view[3] ) * glm::mat3( m_view );\n}\n\nglm::vec3 Camera::getRight() const\n{\n return glm::vec3( m_view[0][0], m_view[1][0], m_view[2][0] );\n}\n\nglm::vec3 Camera::getUp() const\n{\n return glm::vec3( m_view[0][1], m_view[1][1], m_view[2][1] );\n}\n\nglm::vec3 Camera::getForward() const\n{\n return glm::vec3( -m_view[0][2], -m_view[1][2], -m_view[2][2] );\n}\n\nvoid Camera::setPosition( const glm::vec3& pos )\n{\n for( int i = 0; i < 3; ++ i )\n {\n m_view[3][i] = float(0);\n for( int j = 0; j < 3; ++ j )\n {\n m_view[3][i] -= m_view[j][i] * pos[j];\n }\n }\n}\n\nvoid Camera::setRight( const glm::vec3& right )\n{\n glm::vec3 minus_pos = glm::vec3( m_view[3] ) * glm::mat3( m_view );\n m_view[0][0] = right.x;\n m_view[1][0] = right.y;\n m_view[2][0] = right.z;\n m_view[3][0] = dot( right, minus_pos );\n}\n\nvoid Camera::setUp( const glm::vec3& up )\n{\n glm::vec3 minus_pos = glm::vec3( m_view[3] ) * glm::mat3( m_view );\n m_view[0][1] = up.x;\n m_view[1][1] = up.y;\n m_view[2][1] = up.z;\n m_view[3][1] = dot( up, minus_pos );\n}\n\nvoid Camera::setForward( const glm::vec3& forward )\n{\n glm::vec3 pos = -glm::vec3( m_view[3] ) * glm::mat3( m_view );\n m_view[0][0] = -forward.x;\n m_view[1][0] = -forward.y;\n m_view[2][0] = -forward.z;\n m_view[3][0] = dot( forward, pos );\n}\n\nconst glm::mat4& Camera::projectionMatrix() const\n{\n return m_projection;\n}\n\nvoid Camera::setProjectionMatrix(const glm::mat4& projection)\n{\n m_projection = projection;\n}\n\nfloat Camera::fov() const\n{\n return m_fov;\n}\n\nfloat Camera::ratio() const\n{\n return m_ratio;\n}\n\nfloat Camera::znear() const\n{\n return m_znear;\n}\n\nfloat Camera::zfar() const\n{\n return m_zfar;\n}\n\nvoid Camera::setFov( const float& v )\n{\n m_fov = v;\n m_projection = glm::perspective( m_fov, m_ratio, m_znear, m_zfar );\n}\n\nvoid Camera::setRatio( const float& v )\n{\n m_ratio = v;\n m_projection = glm::perspective( m_fov, m_ratio, m_znear, m_zfar );\n}\n\nvoid Camera::setZfar( const float& v )\n{\n m_zfar = v;\n m_projection = glm::perspective( m_fov, m_ratio, m_znear, m_zfar );\n}\n\nvoid Camera::setZnear( const float& v )\n{\n m_znear = v;\n m_projection = glm::perspective( m_fov, m_ratio, m_znear, m_zfar );\n}\n\nCamera::CAMERA_MOUSE_BEHAVIOR Camera::getMouseBehavior() const\n{\n return m_mouseBehavior;\n}\n\nvoid Camera::setMouseBehavior( const CAMERA_MOUSE_BEHAVIOR& v )\n{\n m_mouseBehavior = v;\n if( m_mouseBehavior == ARCBALL_BEHAVIOR )\n {\n glm::vec3 pos = getPosition();\n glm::vec3 up = getUp();\n m_view = glm::lookAt(\n getPosition(),\n glm::vec3{},\n getUp());\n }\n}\n\nvoid Camera::update( float dx, float dy )\n{\n switch( m_mouseBehavior )\n {\n case ARCBALL_BEHAVIOR:\n {\n glm::mat4 rotation = glm::rotate( glm::mat4( glm::mat3(m_view) ), dx, getUp());\n rotation = glm::rotate( rotation, dy, getRight());\n\n m_view[0] = rotation[0];\n m_view[1] = rotation[1];\n m_view[2] = rotation[2];\n\n setPosition(-glm::vec3(m_view[3]) * glm::mat3(rotation));\n }\n break;\n\n case SPACESHIP_BEHAVIOR:\n {\n const float cx = float( std::cos( dx ) );\n const float sx = float( std::sin( dx ) );\n const float cy = float( std::cos( dy ) );\n const float sy = float( std::sin( dy ) );\n\n glm::mat3 rotation = glm::mat3( m_view );\n glm::vec3 minus_pos = glm::vec3( m_view[3] ) * rotation;\n \/\/ build a rotation matrix to apply to the current rotation:\n \/\/\n rotation = glm::mat3(\n glm::vec3( cx, sx*sy,-sx*cy),\n glm::vec3( 0, cy, sy),\n glm::vec3( sx,-cx*sy, cx*cy) ) *rotation;\n for( int col = 0; col < 3; ++ col )\n for( int lin = 0; lin < 3; ++ lin )\n {\n m_view[col][lin] = rotation[col][lin];\n }\n m_view[3][0] = dot( minus_pos, getRight() );\n m_view[3][1] = dot( minus_pos, getUp() );\n m_view[3][2] = dot( minus_pos, -getForward() );\n }\n break;\n\n default:\n assert(false);\n }\n}\n<commit_msg>[Map] Camera modified<commit_after>#include \".\/..\/include\/Camera.hpp\"\n#include <iostream>\n\n#include <glm\/gtc\/type_precision.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\nusing namespace std;\n\nCamera::Camera()\n : m_view{ glm::lookAt( glm::vec3{0, 0, -5}, glm::vec3{}, glm::vec3{0,1,0}) },\n m_fov{ 1.04f }, m_ratio{ 1.0f }, m_znear{ 1.0f }, m_zfar{ 1500.0f },\n m_mouseBehavior{ ARCBALL_BEHAVIOR }\n{}\n\nCamera::~Camera()\n{\n\n}\n\nvoid Camera::animate(float time)\n{\n}\n\nconst glm::mat4& Camera::viewMatrix() const\n{\n return m_view;\n}\n\nvoid Camera::setViewMatrix(const glm::mat4& view)\n{\n m_view = view;\n}\n\nglm::vec3 Camera::getPosition() const\n{\n return -glm::vec3( m_view[3] ) * glm::mat3( m_view );\n}\n\nglm::vec3 Camera::getRight() const\n{\n return glm::vec3( m_view[0][0], m_view[1][0], m_view[2][0] );\n}\n\nglm::vec3 Camera::getUp() const\n{\n return glm::vec3( m_view[0][1], m_view[1][1], m_view[2][1] );\n}\n\nglm::vec3 Camera::getForward() const\n{\n return glm::vec3( -m_view[0][2], -m_view[1][2], -m_view[2][2] );\n}\n\nvoid Camera::setPosition( const glm::vec3& pos )\n{\n for( int i = 0; i < 3; ++ i )\n {\n m_view[3][i] = float(0);\n for( int j = 0; j < 3; ++ j )\n {\n m_view[3][i] -= m_view[j][i] * pos[j];\n }\n }\n}\n\nvoid Camera::setRight( const glm::vec3& right )\n{\n glm::vec3 minus_pos = glm::vec3( m_view[3] ) * glm::mat3( m_view );\n m_view[0][0] = right.x;\n m_view[1][0] = right.y;\n m_view[2][0] = right.z;\n m_view[3][0] = dot( right, minus_pos );\n}\n\nvoid Camera::setUp( const glm::vec3& up )\n{\n glm::vec3 minus_pos = glm::vec3( m_view[3] ) * glm::mat3( m_view );\n m_view[0][1] = up.x;\n m_view[1][1] = up.y;\n m_view[2][1] = up.z;\n m_view[3][1] = dot( up, minus_pos );\n}\n\nvoid Camera::setForward( const glm::vec3& forward )\n{\n glm::vec3 pos = -glm::vec3( m_view[3] ) * glm::mat3( m_view );\n m_view[0][0] = -forward.x;\n m_view[1][0] = -forward.y;\n m_view[2][0] = -forward.z;\n m_view[3][0] = dot( forward, pos );\n}\n\nconst glm::mat4& Camera::projectionMatrix() const\n{\n return m_projection;\n}\n\nvoid Camera::setProjectionMatrix(const glm::mat4& projection)\n{\n m_projection = projection;\n}\n\nfloat Camera::fov() const\n{\n return m_fov;\n}\n\nfloat Camera::ratio() const\n{\n return m_ratio;\n}\n\nfloat Camera::znear() const\n{\n return m_znear;\n}\n\nfloat Camera::zfar() const\n{\n return m_zfar;\n}\n\nvoid Camera::setFov( const float& v )\n{\n m_fov = v;\n m_projection = glm::perspective( m_fov, m_ratio, m_znear, m_zfar );\n}\n\nvoid Camera::setRatio( const float& v )\n{\n m_ratio = v;\n m_projection = glm::perspective( m_fov, m_ratio, m_znear, m_zfar );\n}\n\nvoid Camera::setZfar( const float& v )\n{\n m_zfar = v;\n m_projection = glm::perspective( m_fov, m_ratio, m_znear, m_zfar );\n}\n\nvoid Camera::setZnear( const float& v )\n{\n m_znear = v;\n m_projection = glm::perspective( m_fov, m_ratio, m_znear, m_zfar );\n}\n\nCamera::CAMERA_MOUSE_BEHAVIOR Camera::getMouseBehavior() const\n{\n return m_mouseBehavior;\n}\n\nvoid Camera::setMouseBehavior( const CAMERA_MOUSE_BEHAVIOR& v )\n{\n m_mouseBehavior = v;\n if( m_mouseBehavior == ARCBALL_BEHAVIOR )\n {\n glm::vec3 pos = getPosition();\n glm::vec3 up = getUp();\n m_view = glm::lookAt(\n getPosition(),\n glm::vec3{},\n getUp());\n }\n}\n\nvoid Camera::update( float dx, float dy )\n{\n switch( m_mouseBehavior )\n {\n case ARCBALL_BEHAVIOR:\n {\n glm::mat4 rotation = glm::rotate( glm::mat4( glm::mat3(m_view) ), dx, getUp());\n rotation = glm::rotate( rotation, dy, getRight());\n\n m_view[0] = rotation[0];\n m_view[1] = rotation[1];\n m_view[2] = rotation[2];\n\n setPosition(-glm::vec3(m_view[3]) * glm::mat3(rotation));\n }\n break;\n\n case SPACESHIP_BEHAVIOR:\n {\n const float cx = float( std::cos( dx ) );\n const float sx = float( std::sin( dx ) );\n const float cy = float( std::cos( dy ) );\n const float sy = float( std::sin( dy ) );\n\n glm::mat3 rotation = glm::mat3( m_view );\n glm::vec3 minus_pos = glm::vec3( m_view[3] ) * rotation;\n \/\/ build a rotation matrix to apply to the current rotation:\n \/\/\n rotation = glm::mat3(\n glm::vec3( cx, sx*sy,-sx*cy),\n glm::vec3( 0, cy, sy),\n glm::vec3( sx,-cx*sy, cx*cy) ) *rotation;\n for( int col = 0; col < 3; ++ col )\n for( int lin = 0; lin < 3; ++ lin )\n {\n m_view[col][lin] = rotation[col][lin];\n }\n m_view[3][0] = dot( minus_pos, getRight() );\n m_view[3][1] = dot( minus_pos, getUp() );\n m_view[3][2] = dot( minus_pos, -getForward() );\n }\n break;\n\n default:\n assert(false);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdsneezy.h\"\n#include \"database.h\"\n\nvoid updateStockHistory()\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"insert into stockhistory select max(sh.n)+1, si.ticker, si.price from stockinfo si, stockhistory sh group by si.ticker, si.price\");\n\n db.query(\"insert into stockhistory select max(sh.n), 'INDX', sum(si.price*si.shares)\/sum(si.shares) from stockinfo si, stockhistory sh where sh.ticker=si.ticker\");\n}\n\n\nvoid stockSplit(sstring ticker, float pricechange)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"update stockinfo set shares=shares*2, price=(price\/2)+%f where ticker='%s'\", pricechange, ticker.c_str());\n \n db.query(\"update stockhistory set price=price\/2 where ticker='%s'\",\n \t ticker.c_str());\n\n \/\/ db.query(\"insert into stockhistory select max(n), ticker, max(price) from stockhistory where ticker='%s' group by ticker\", ticker.c_str());\n \/\/ db.query(\"insert into stockhistory select max(n), ticker, min(price) from stockhistory where ticker='%s' group by ticker\", ticker.c_str());\n}\n\nvoid stockReverseSplit(sstring ticker, float pricechange)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"update stockinfo set shares=shares\/10, price=(price*2)+%f where ticker='%s'\", pricechange, ticker.c_str());\n\n db.query(\"update stockhistory set price=price*10 where ticker='%s'\",\n\t ticker.c_str());\n \n \/\/ db.query(\"insert into stockhistory select max(n), ticker, max(price) from stockhistory where ticker='%s' group by ticker\", ticker.c_str());\n \/\/ db.query(\"insert into stockhistory select max(n), ticker, min(price) from stockhistory where ticker='%s' group by ticker\", ticker.c_str());\n}\n\nvoid updateStocks()\n{\n TDatabase db(DB_SNEEZY), stocks(DB_SNEEZY);\n\n stocks.query(\"select ticker, shares, price, (((random() * volatility * 2) - volatility) \/ 1000) as pricechange from stockinfo\");\n\n while(stocks.fetchRow()){\n float pricechange=convertTo<float>(stocks[\"pricechange\"]);\n float price=convertTo<float>(stocks[\"price\"]);\n sstring ticker=stocks[\"ticker\"];\n int shares=convertTo<int>(stocks[\"shares\"]);\n\n if(shares<=0)\n continue;\n\n if((price+pricechange) < ::number(1,5)){\n stockReverseSplit(ticker, pricechange);\n } else if(price+pricechange > ::number(100, 125)){\n stockSplit(ticker, pricechange);\n } else {\n db.query(\"update stockinfo set price=price+%f where ticker='%s'\",\n\t pricechange, ticker.c_str());\n }\n \n }\n\n\n}\n\nint stockBoard(TBeing *ch, cmdTypeT cmd, const char *arg, TObj *o1, TObj *o2)\n{\n int found=0;\n TThing *o;\n TObj *to;\n TDatabase db(DB_SNEEZY);\n float price, pricediff;\n int shares;\n\n if(cmd != CMD_LOOK)\n return FALSE;\n\n for (o = ch->roomp->getStuff(); o; o = o->nextThing) {\n to = dynamic_cast<TObj *>(o);\n if (to && to->spec == SPEC_STOCK_BOARD &&\n\tisname(arg, to->name)){\n found=1;\n break;\n }\n }\n\n if(!found)\n return FALSE;\n\n ch->sendTo(\"You examine the board:\\n\\r\");\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n db.query(\"select sum(sh.price*si.shares)\/sum(si.shares) as dayprice, sum(si.price*si.shares)\/sum(si.shares) as price from stockinfo si, stockhistory sh, (select ticker, max(n) as n from stockhistory group by ticker) sn where sh.n=sn.n and si.ticker=sh.ticker\");\n \n if(db.fetchRow()){\n price=convertTo<float>(db[\"price\"]);\n pricediff=price-convertTo<float>(db[\"dayprice\"]);\n \n ch->sendTo(COLOR_BASIC, fmt(\"Market: <Y>%.2f %s%+.2f<1>\\n\\r\") %\n\t price % (pricediff>0?\"<G>\":\"<R>\") %\n\t (convertTo<float>(db[\"dayprice\"]) - price));\n }\n\t\t\t\n\n\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n ch->sendTo(\"Ticker Bid Ask Change Market Cap \\n\\r\");\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n \n db.query(\"select distinct si.ticker, si.price, sh.price as dayprice, si.shares from stockinfo si, stockhistory sh, (select ticker, max(n) as n from stockhistory group by ticker) sn where sh.n=sn.n and si.ticker=sh.ticker and sn.ticker=si.ticker\");\n\n\n while(db.fetchRow()){\n price=convertTo<float>(db[\"price\"]);\n shares=convertTo<int>(db[\"shares\"]);\n pricediff=price-convertTo<float>(db[\"dayprice\"]);\n\n ch->sendTo(COLOR_BASIC, fmt(\"%-6s <Y>%.2f %.2f<1> %s%+.2f<1> %s\\n\\r\") %\n\t db[\"ticker\"] % (price*0.97) % (price * 1.03) % \n\t (pricediff>0?\"<G>\":\"<R>\") % pricediff %\n\t talenDisplay((int)(price*(float)shares)));\n }\n\n\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n ch->sendTo(\"Price charts can be seen at: http:\/\/sneezy.saw.net\/peel\/stocks\/\\n\\r\");\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n\n return TRUE;\n}\n\n\n\n<commit_msg>typo fix<commit_after>#include \"stdsneezy.h\"\n#include \"database.h\"\n\nvoid updateStockHistory()\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"insert into stockhistory select max(sh.n)+1, si.ticker, si.price from stockinfo si, stockhistory sh group by si.ticker, si.price\");\n\n db.query(\"insert into stockhistory select max(sh.n), 'INDX', sum(si.price*si.shares)\/sum(si.shares) from stockinfo si, stockhistory sh where sh.ticker=si.ticker\");\n}\n\n\nvoid stockSplit(sstring ticker, float pricechange)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"update stockinfo set shares=shares*2, price=(price\/2)+%f where ticker='%s'\", pricechange, ticker.c_str());\n \n db.query(\"update stockhistory set price=price\/2 where ticker='%s'\",\n \t ticker.c_str());\n\n \/\/ db.query(\"insert into stockhistory select max(n), ticker, max(price) from stockhistory where ticker='%s' group by ticker\", ticker.c_str());\n \/\/ db.query(\"insert into stockhistory select max(n), ticker, min(price) from stockhistory where ticker='%s' group by ticker\", ticker.c_str());\n}\n\nvoid stockReverseSplit(sstring ticker, float pricechange)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"update stockinfo set shares=shares\/10, price=(price*2)+%f where ticker='%s'\", pricechange, ticker.c_str());\n\n db.query(\"update stockhistory set price=price*10 where ticker='%s'\",\n\t ticker.c_str());\n \n \/\/ db.query(\"insert into stockhistory select max(n), ticker, max(price) from stockhistory where ticker='%s' group by ticker\", ticker.c_str());\n \/\/ db.query(\"insert into stockhistory select max(n), ticker, min(price) from stockhistory where ticker='%s' group by ticker\", ticker.c_str());\n}\n\nvoid updateStocks()\n{\n TDatabase db(DB_SNEEZY), stocks(DB_SNEEZY);\n\n stocks.query(\"select ticker, shares, price, (((random() * volatility * 2) - volatility) \/ 1000) as pricechange from stockinfo\");\n\n while(stocks.fetchRow()){\n float pricechange=convertTo<float>(stocks[\"pricechange\"]);\n float price=convertTo<float>(stocks[\"price\"]);\n sstring ticker=stocks[\"ticker\"];\n int shares=convertTo<int>(stocks[\"shares\"]);\n\n if(shares<=0)\n continue;\n\n if((price+pricechange) < ::number(1,5)){\n stockReverseSplit(ticker, pricechange);\n } else if(price+pricechange > ::number(100, 125)){\n stockSplit(ticker, pricechange);\n } else {\n db.query(\"update stockinfo set price=price+%f where ticker='%s'\",\n\t pricechange, ticker.c_str());\n }\n \n }\n\n\n}\n\nint stockBoard(TBeing *ch, cmdTypeT cmd, const char *arg, TObj *o1, TObj *o2)\n{\n int found=0;\n TThing *o;\n TObj *to;\n TDatabase db(DB_SNEEZY);\n float price, pricediff;\n int shares;\n\n if(cmd != CMD_LOOK)\n return FALSE;\n\n for (o = ch->roomp->getStuff(); o; o = o->nextThing) {\n to = dynamic_cast<TObj *>(o);\n if (to && to->spec == SPEC_STOCK_BOARD &&\n\tisname(arg, to->name)){\n found=1;\n break;\n }\n }\n\n if(!found)\n return FALSE;\n\n ch->sendTo(\"You examine the board:\\n\\r\");\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n db.query(\"select sum(sh.price*si.shares)\/sum(si.shares) as dayprice, sum(si.price*si.shares)\/sum(si.shares) as price from stockinfo si, stockhistory sh, (select ticker, max(n) as n from stockhistory group by ticker) sn where sh.n=sn.n and si.ticker=sh.ticker\");\n \n if(db.fetchRow()){\n price=convertTo<float>(db[\"price\"]);\n pricediff=price-convertTo<float>(db[\"dayprice\"]);\n \n ch->sendTo(COLOR_BASIC, fmt(\"Market: <Y>%.2f %s%+.2f<1>\\n\\r\") %\n\t price % (pricediff>0?\"<G>\":\"<R>\") %\n\t (price - convertTo<float>(db[\"dayprice\"])));\n }\n\t\t\t\n\n\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n ch->sendTo(\"Ticker Bid Ask Change Market Cap \\n\\r\");\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n \n db.query(\"select distinct si.ticker, si.price, sh.price as dayprice, si.shares from stockinfo si, stockhistory sh, (select ticker, max(n) as n from stockhistory group by ticker) sn where sh.n=sn.n and si.ticker=sh.ticker and sn.ticker=si.ticker\");\n\n\n while(db.fetchRow()){\n price=convertTo<float>(db[\"price\"]);\n shares=convertTo<int>(db[\"shares\"]);\n pricediff=price-convertTo<float>(db[\"dayprice\"]);\n\n ch->sendTo(COLOR_BASIC, fmt(\"%-6s <Y>%.2f %.2f<1> %s%+.2f<1> %s\\n\\r\") %\n\t db[\"ticker\"] % (price*0.97) % (price * 1.03) % \n\t (pricediff>0?\"<G>\":\"<R>\") % pricediff %\n\t talenDisplay((int)(price*(float)shares)));\n }\n\n\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n ch->sendTo(\"Price charts can be seen at: http:\/\/sneezy.saw.net\/peel\/stocks\/\\n\\r\");\n ch->sendTo(\"------------------------------------------------------------\\n\\r\");\n\n return TRUE;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n\n#include \"mcc\/gas\/gas.h\"\n\n#include \"mcc\/tac\/float_literal.h\"\n#include \"mcc\/tac\/helper\/ast_converters.h\"\n#include \"mcc\/tac\/int_literal.h\"\n#include \"parser.h\"\n#include \"test_utils.h\"\n\n#include <iostream>\n#include <regex>\n\nusing namespace mcc::gas;\n\nnamespace mcc {\nnamespace gas {\nTEST(Gas, FunctionStackSpace) {\n auto tree = parser::parse(\n R\"(\n void bar(int arg1);\n\n void foo(int arg1) {\n if(arg1 < 0) return;\n bar(arg1 - 1);\n }\n\n void bar(int arg1) {\n if(arg1 < 0) return;\n foo(arg1 - 1);\n bar(arg1 - 1);\n }\n\n int main() {\n foo(10);\n return 0;\n }\n )\");\n\n Tac tac = Tac(tree);\n Gas gas = Gas(tac);\n\n function_stack_space_map_type expected;\n\n auto l1 = std::make_shared<Label>(\"foo\");\n auto l2 = std::make_shared<Label>(\"bar\");\n auto l3 = std::make_shared<Label>(\"main\");\n\n expected[l1] = 4;\n expected[l2] = 8;\n expected[l3] = 0;\n\n for (auto const e : expected) {\n auto result = gas.getRegisterManager()->lookupFunctionStackSpace(e.first);\n\n EXPECT_EQ(e.second, result);\n }\n}\n\nTEST(Gas, VariableStackOffset) {\n auto tree = parser::parse(\n R\"(\n void bar(int arg1);\n\n void foo(int arg1, int arg2) {\n if(arg1 < 0) return;\n bar(arg1 - 1);\n }\n\n void bar(int arg1) {\n if(arg1 < 0) return;\n foo(arg1 - 1, arg1);\n bar(arg1 - 1);\n }\n\n int main() {\n foo(10, 10);\n return 0;\n }\n )\");\n\n Tac tac = Tac(tree);\n Gas gas = Gas(tac);\n\n auto regMan = gas.getRegisterManager();\n\n Label::ptr_t currentFunction;\n int varCounter = 0;\n signed expectedOffsets[] = {8, 12, -4, -4, -8, 8, -4, -4, -8, -8, -12, -4};\n for (auto codeLine : tac.codeLines) {\n if (helper::isType<Label>(codeLine)) {\n auto label = std::static_pointer_cast<Label>(codeLine);\n if (label->isFunctionEntry()) {\n currentFunction = label;\n }\n }\n\n if (codeLine->containsTargetVar()) {\n auto targetVar = codeLine->getTargetVariable();\n auto targetVarOffset =\n regMan->lookupVariableStackOffset(currentFunction, targetVar);\n\n EXPECT_EQ(expectedOffsets[varCounter++], targetVarOffset);\n }\n }\n}\n\n\/* Gas Conversion *\/\nTEST(Gas, GasConversion) {\n auto tree = parser::parse(\n R\"(\n void print_int(int out);\n int read_int();\n\n int fibonacci(int n) {\n if ( n == 0 )\n return 0;\n else if ( n == 1 )\n return 1;\n else\n return (fibonacci(n-1) + fibonacci(n-2));\n } \n\n int main(void) {\n int i = read_int();\n int fib = fibonacci(i); \n print_int(fib);\n\n return 0;\n }\n )\");\n\n auto tac = Tac(tree);\n Gas gas = Gas(tac);\n\n \/\/ get labels from tac\n auto labels = std::vector<std::string>();\n for (auto triple : tac.codeLines) {\n switch (triple->getOperator().getName()) {\n case OperatorName::LABEL: {\n auto label = std::static_pointer_cast<Label>(triple);\n if (!label->isFunctionEntry()) {\n labels.push_back(label->getValue());\n }\n } break;\n case OperatorName::JUMP: {\n auto label = std::static_pointer_cast<Label>(triple->getArg1());\n if (!label->isFunctionEntry()) {\n labels.push_back(label->getValue());\n }\n } break;\n case OperatorName::JUMPFALSE: {\n auto label = std::static_pointer_cast<Label>(triple->getArg2());\n if (!label->isFunctionEntry()) {\n labels.push_back(label->getValue());\n }\n } break;\n default:\n \/\/ ignore\n break;\n }\n }\n\n auto curLabel = labels.begin();\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nfibonacci:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 20\n\tpush ebx\n\tpush edi\n\tpush esi\n\tmov ecx, DWORD PTR [ebp + 8]\n\tcmp ecx, 0\n\tjne )\" + *curLabel++ +\n R\"(\n\tmov eax, 0\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 20\n\tmov esp, ebp\n\tpop ebp\n\tret\n\tjmp )\" + *curLabel++ +\n R\"(\n\n)\" + *curLabel++ +\n R\"(:\n\tcmp ecx, 1\n\tjne )\" + *curLabel++ +\n R\"(\n\tmov eax, 1\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 20\n\tmov esp, ebp\n\tpop ebp\n\tret\n\tjmp )\" + *curLabel++ +\n R\"(\n\n)\" + *curLabel++ +\n R\"(:\n\tmov eax, ecx\n\tsub eax, 1\n\tmov ebx, eax\n\tpush ecx\n\tpush edx\n\tpush ebx\n\tcall fibonacci\n\tadd esp, 4\n\tpop edx\n\tpop ecx\n\tmov edx, eax\n\tmov eax, ecx\n\tsub eax, 2\n\tmov ebx, eax\n\tpush ecx\n\tpush edx\n\tpush ebx\n\tcall fibonacci\n\tadd esp, 4\n\tpop edx\n\tpop ecx\n\tmov ebx, eax\n\tmov eax, edx\n\tadd eax, ebx\n\tmov ecx, eax\n\tmov eax, ecx\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 20\n\tmov esp, ebp\n\tpop ebp\n\tret\n\n)\" + *curLabel++ +\n R\"(:\n\n)\" + *curLabel++ +\n R\"(:\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 20\n\tmov esp, ebp\n\tpop ebp\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 8\n\tpush ebx\n\tpush edi\n\tpush esi\n\tpush ecx\n\tpush edx\n\tcall read_int\n\tpop edx\n\tpop ecx\n\tmov ebx, eax\n\tpush ecx\n\tpush edx\n\tpush ebx\n\tcall fibonacci\n\tadd esp, 4\n\tpop edx\n\tpop ecx\n\tmov ebx, eax\n\tpush ecx\n\tpush edx\n\tpush ebx\n\tcall print_int\n\tadd esp, 4\n\tpop edx\n\tpop ecx\n\tmov eax, 0\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 8\n\tmov esp, ebp\n\tpop ebp\n\tret\n\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasAddIntegerConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n IntLiteral::ptr_t operandOne = std::make_shared<IntLiteral>(10);\n IntLiteral::ptr_t operandTwo = std::make_shared<IntLiteral>(15);\n Operator op = Operator(OperatorName::ADD);\n\n Triple::ptr_t addTriple =\n std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(addTriple);\n\n Gas gas = Gas(tac);\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tmov eax, 10\n\tadd eax, 15\n\tmov ebx, eax\n\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasSubIntegerConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n IntLiteral::ptr_t operandOne = std::make_shared<IntLiteral>(10);\n IntLiteral::ptr_t operandTwo = std::make_shared<IntLiteral>(15);\n Operator op = Operator(OperatorName::SUB);\n\n Triple::ptr_t subTriple =\n std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(subTriple);\n\n Gas gas = Gas(tac);\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tmov eax, 10\n\tsub eax, 15\n\tmov ebx, eax\n\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasMulIntegerConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n IntLiteral::ptr_t operandOne = std::make_shared<IntLiteral>(10);\n IntLiteral::ptr_t operandTwo = std::make_shared<IntLiteral>(15);\n Operator op = Operator(OperatorName::MUL);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tmov eax, 10\n\timul eax, 15\n\tmov ebx, eax\n\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasAddFloatConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n FloatLiteral::ptr_t operandOne = std::make_shared<FloatLiteral>(10.0);\n FloatLiteral::ptr_t operandTwo = std::make_shared<FloatLiteral>(15.0);\n Operator op = Operator(OperatorName::ADD);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tfld DWORD PTR .FC0\n\tfld DWORD PTR .FC1\n\tfaddp st(1), st\n\tfstp DWORD PTR [ebp - 4]\n\tmov ebx, DWORD PTR [ebp - 4]\n\n.FC0: .float 10.000000\n.FC1: .float 15.000000\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasSubFloatConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n FloatLiteral::ptr_t operandOne = std::make_shared<FloatLiteral>(10.0);\n FloatLiteral::ptr_t operandTwo = std::make_shared<FloatLiteral>(15.0);\n Operator op = Operator(OperatorName::SUB);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tfld DWORD PTR .FC0\n\tfld DWORD PTR .FC1\n\tfsubp st(1), st\n\tfstp DWORD PTR [ebp - 4]\n\tmov ebx, DWORD PTR [ebp - 4]\n\n.FC0: .float 10.000000\n.FC1: .float 15.000000\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasMulFloatConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n FloatLiteral::ptr_t operandOne = std::make_shared<FloatLiteral>(10.0);\n FloatLiteral::ptr_t operandTwo = std::make_shared<FloatLiteral>(15.0);\n Operator op = Operator(OperatorName::MUL);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tfld DWORD PTR .FC0\n\tfld DWORD PTR .FC1\n\tfmulp st(1), st\n\tfstp DWORD PTR [ebp - 4]\n\tmov ebx, DWORD PTR [ebp - 4]\n\n.FC0: .float 10.000000\n.FC1: .float 15.000000\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasDivFloatConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n FloatLiteral::ptr_t operandOne = std::make_shared<FloatLiteral>(10.0);\n FloatLiteral::ptr_t operandTwo = std::make_shared<FloatLiteral>(15.0);\n Operator op = Operator(OperatorName::DIV);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tfld DWORD PTR .FC0\n\tfld DWORD PTR .FC1\n\tfdivp st(1), st\n\tfstp DWORD PTR [ebp - 4]\n\tmov ebx, DWORD PTR [ebp - 4]\n\n.FC0: .float 10.000000\n.FC1: .float 15.000000\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n}\n}\n<commit_msg>temporarily fixed tests<commit_after>#include <gtest\/gtest.h>\n\n#include \"mcc\/gas\/gas.h\"\n\n#include \"mcc\/tac\/float_literal.h\"\n#include \"mcc\/tac\/helper\/ast_converters.h\"\n#include \"mcc\/tac\/int_literal.h\"\n#include \"parser.h\"\n#include \"test_utils.h\"\n\n#include <iostream>\n#include <regex>\n\nusing namespace mcc::gas;\n\nnamespace mcc {\nnamespace gas {\nTEST(Gas, FunctionStackSpace) {\n auto tree = parser::parse(\n R\"(\n void bar(int arg1);\n\n void foo(int arg1) {\n if(arg1 < 0) return;\n bar(arg1 - 1);\n }\n\n void bar(int arg1) {\n if(arg1 < 0) return;\n foo(arg1 - 1);\n bar(arg1 - 1);\n }\n\n int main() {\n foo(10);\n return 0;\n }\n )\");\n\n Tac tac = Tac(tree);\n Gas gas = Gas(tac);\n\n function_stack_space_map_type expected;\n\n auto l1 = std::make_shared<Label>(\"foo\");\n auto l2 = std::make_shared<Label>(\"bar\");\n auto l3 = std::make_shared<Label>(\"main\");\n\n expected[l1] = 4;\n expected[l2] = 8;\n expected[l3] = 0;\n\n for (auto const e : expected) {\n auto result = gas.getRegisterManager()->lookupFunctionStackSpace(e.first);\n\n EXPECT_EQ(e.second, result);\n }\n}\n\nTEST(Gas, VariableStackOffset) {\n auto tree = parser::parse(\n R\"(\n void bar(int arg1);\n\n void foo(int arg1, int arg2) {\n if(arg1 < 0) return;\n bar(arg1 - 1);\n }\n\n void bar(int arg1) {\n if(arg1 < 0) return;\n foo(arg1 - 1, arg1);\n bar(arg1 - 1);\n }\n\n int main() {\n foo(10, 10);\n return 0;\n }\n )\");\n\n Tac tac = Tac(tree);\n Gas gas = Gas(tac);\n\n auto regMan = gas.getRegisterManager();\n\n Label::ptr_t currentFunction;\n int varCounter = 0;\n signed expectedOffsets[] = {8, 12, -4, -4, -8, 8, -4, -4, -8, -8, -12, -4};\n for (auto codeLine : tac.codeLines) {\n if (helper::isType<Label>(codeLine)) {\n auto label = std::static_pointer_cast<Label>(codeLine);\n if (label->isFunctionEntry()) {\n currentFunction = label;\n }\n }\n\n if (codeLine->containsTargetVar()) {\n auto targetVar = codeLine->getTargetVariable();\n auto targetVarOffset =\n regMan->lookupVariableStackOffset(currentFunction, targetVar);\n\n EXPECT_EQ(expectedOffsets[varCounter++], targetVarOffset);\n }\n }\n}\n\n\/* Gas Conversion *\/\nTEST(Gas, GasConversion) {\n auto tree = parser::parse(\n R\"(\n void print_int(int out);\n int read_int();\n\n int fibonacci(int n) {\n if ( n == 0 )\n return 0;\n else if ( n == 1 )\n return 1;\n else\n return (fibonacci(n-1) + fibonacci(n-2));\n } \n\n int main(void) {\n int i = read_int();\n int fib = fibonacci(i); \n print_int(fib);\n\n return 0;\n }\n )\");\n\n auto tac = Tac(tree);\n Gas gas = Gas(tac);\n\n \/\/ get labels from tac\n auto labels = std::vector<std::string>();\n for (auto triple : tac.codeLines) {\n switch (triple->getOperator().getName()) {\n case OperatorName::LABEL: {\n auto label = std::static_pointer_cast<Label>(triple);\n if (!label->isFunctionEntry()) {\n labels.push_back(label->getValue());\n }\n } break;\n case OperatorName::JUMP: {\n auto label = std::static_pointer_cast<Label>(triple->getArg1());\n if (!label->isFunctionEntry()) {\n labels.push_back(label->getValue());\n }\n } break;\n case OperatorName::JUMPFALSE: {\n auto label = std::static_pointer_cast<Label>(triple->getArg2());\n if (!label->isFunctionEntry()) {\n labels.push_back(label->getValue());\n }\n } break;\n default:\n \/\/ ignore\n break;\n }\n }\n\n auto curLabel = labels.begin();\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nfibonacci:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 20\n\tpush ebx\n\tpush edi\n\tpush esi\n\tmov edx, DWORD PTR [ebp + 8]\n\tcmp edx, 0\n\tjne )\" + *curLabel++ +\n R\"(\n\tmov eax, 0\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 20\n\tmov esp, ebp\n\tpop ebp\n\tret\n\tjmp )\" + *curLabel++ +\n R\"(\n\n)\" + *curLabel++ +\n R\"(:\n\tcmp edx, 1\n\tjne )\" + *curLabel++ +\n R\"(\n\tmov eax, 1\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 20\n\tmov esp, ebp\n\tpop ebp\n\tret\n\tjmp )\" + *curLabel++ +\n R\"(\n\n)\" + *curLabel++ +\n R\"(:\n\tmov eax, edx\n\tsub eax, 1\n\tmov ecx, eax\n\tpush ecx\n\tpush edx\n\tpush ecx\n\tcall fibonacci\n\tadd esp, 4\n\tpop edx\n\tpop ecx\n\tmov esi, eax\n\tmov ebx, edx\n\tsub ebx, 2\n\tmov ecx, ebx\n\tpush ecx\n\tpush edx\n\tpush ecx\n\tcall fibonacci\n\tadd esp, 4\n\tpop edx\n\tpop ecx\n\tmov ecx, eax\n\tmov eax, esi\n\tadd eax, ecx\n\tmov edx, eax\n\tmov eax, edx\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 20\n\tmov esp, ebp\n\tpop ebp\n\tret\n\n)\" + *curLabel++ +\n R\"(:\n\n)\" + *curLabel++ +\n R\"(:\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 20\n\tmov esp, ebp\n\tpop ebp\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 8\n\tpush ebx\n\tpush edi\n\tpush esi\n\tpush ecx\n\tpush edx\n\tcall read_int\n\tpop edx\n\tpop ecx\n\tmov ecx, eax\n\tpush ecx\n\tpush edx\n\tpush ecx\n\tcall fibonacci\n\tadd esp, 4\n\tpop edx\n\tpop ecx\n\tmov ecx, eax\n\tpush ecx\n\tpush edx\n\tpush ecx\n\tcall print_int\n\tadd esp, 4\n\tpop edx\n\tpop ecx\n\tmov eax, 0\n\tpop esi\n\tpop edi\n\tpop ebx\n\tadd esp, 8\n\tmov esp, ebp\n\tpop ebp\n\tret\n\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasAddIntegerConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n IntLiteral::ptr_t operandOne = std::make_shared<IntLiteral>(10);\n IntLiteral::ptr_t operandTwo = std::make_shared<IntLiteral>(15);\n Operator op = Operator(OperatorName::ADD);\n\n Triple::ptr_t addTriple =\n std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(addTriple);\n\n Gas gas = Gas(tac);\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tmov eax, 10\n\tadd eax, 15\n\tmov ecx, eax\n\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasSubIntegerConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n IntLiteral::ptr_t operandOne = std::make_shared<IntLiteral>(10);\n IntLiteral::ptr_t operandTwo = std::make_shared<IntLiteral>(15);\n Operator op = Operator(OperatorName::SUB);\n\n Triple::ptr_t subTriple =\n std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(subTriple);\n\n Gas gas = Gas(tac);\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tmov eax, 10\n\tsub eax, 15\n\tmov ecx, eax\n\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasMulIntegerConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n IntLiteral::ptr_t operandOne = std::make_shared<IntLiteral>(10);\n IntLiteral::ptr_t operandTwo = std::make_shared<IntLiteral>(15);\n Operator op = Operator(OperatorName::MUL);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tmov ebx, 10\n\timul ebx, 15\n\tmov ecx, ebx\n\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasAddFloatConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n FloatLiteral::ptr_t operandOne = std::make_shared<FloatLiteral>(10.0);\n FloatLiteral::ptr_t operandTwo = std::make_shared<FloatLiteral>(15.0);\n Operator op = Operator(OperatorName::ADD);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tfld DWORD PTR .FC0\n\tfld DWORD PTR .FC1\n\tfaddp st(1), st\n\tfstp DWORD PTR [ebp - 4]\n\tmov ecx, DWORD PTR [ebp - 4]\n\n.FC0: .float 10.000000\n.FC1: .float 15.000000\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasSubFloatConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n FloatLiteral::ptr_t operandOne = std::make_shared<FloatLiteral>(10.0);\n FloatLiteral::ptr_t operandTwo = std::make_shared<FloatLiteral>(15.0);\n Operator op = Operator(OperatorName::SUB);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tfld DWORD PTR .FC0\n\tfld DWORD PTR .FC1\n\tfsubp st(1), st\n\tfstp DWORD PTR [ebp - 4]\n\tmov ecx, DWORD PTR [ebp - 4]\n\n.FC0: .float 10.000000\n.FC1: .float 15.000000\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasMulFloatConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n FloatLiteral::ptr_t operandOne = std::make_shared<FloatLiteral>(10.0);\n FloatLiteral::ptr_t operandTwo = std::make_shared<FloatLiteral>(15.0);\n Operator op = Operator(OperatorName::MUL);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tfld DWORD PTR .FC0\n\tfld DWORD PTR .FC1\n\tfmulp st(1), st\n\tfstp DWORD PTR [ebp - 4]\n\tmov ecx, DWORD PTR [ebp - 4]\n\n.FC0: .float 10.000000\n.FC1: .float 15.000000\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n\nTEST(Gas, GasDivFloatConversion) {\n auto tree = parser::parse(\n R\"(\n void main() {\n \n }\n )\");\n\n Tac tac = Tac(tree);\n FloatLiteral::ptr_t operandOne = std::make_shared<FloatLiteral>(10.0);\n FloatLiteral::ptr_t operandTwo = std::make_shared<FloatLiteral>(15.0);\n Operator op = Operator(OperatorName::DIV);\n\n Triple::ptr_t triple = std::make_shared<Triple>(op, operandOne, operandTwo);\n tac.addLine(triple);\n\n Gas gas = Gas(tac);\n\n auto expected = R\"(.intel_syntax noprefix\n.global main\n\nmain:\n\tpush ebp\n\tmov ebp, esp\n\tsub esp, 4\n\tpush ebx\n\tpush edi\n\tpush esi\n\tfld DWORD PTR .FC0\n\tfld DWORD PTR .FC1\n\tfdivp st(1), st\n\tfstp DWORD PTR [ebp - 4]\n\tmov ecx, DWORD PTR [ebp - 4]\n\n.FC0: .float 10.000000\n.FC1: .float 15.000000\n\n.att_syntax noprefix\n)\";\n\n EXPECT_EQ(expected, gas.toString());\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n\n\/\/ optimize stack size\nclass Stack\n{\n public:\n Stack() { head = 0; }\n\n void Push(char val) { body[head++] = val; }\n char Pop() { return body[--head]; }\n char Peek() { return body[head-1]; }\n bool isEmpty() { return head == 0; }\n private:\n char body[100];\n int head;\n};\n\nenum class InputType\n{\n Console,\n File,\n Constructor\n};\n\nclass CalculationNotDoneException: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"The Input() method should be executed before Output()\";\n }\n} calc_not_done;\n\nclass Calculator\n{\n public:\n std::string InputFileName;\n std::string OutputFileName;\n\n Calculator() :\n InputFileName(\"Input.txt\"),\n OutputFileName(\"Output.txt\"),\n result(0),\n calculationDone(false)\n {\n \/\/ empty constructor, totally legit\n }\n\n Calculator(const InputType& inputFrom)\n {\n Calculator();\n\n Input(inputFrom);\n }\n\n Calculator(const InputType& inputFrom, const std::string& expression)\n {\n Calculator();\n\n Input(inputFrom, expression);\n }\n\n Calculator(const InputType& inputFrom, const std::string& inputFileName, const std::string& outputFileName)\n {\n Calculator();\n\n InputFileName = inputFileName;\n OutputFileName = outputFileName;\n\n Input(inputFrom);\n }\n\n void Input(const InputType& inputFrom, const std::string& expression = \"\")\n {\n if (InputType::Console == inputFrom)\n {\n std::getline(std::cin, input);\n }\n else if (InputType::File == inputFrom)\n {\n std::ifstream inputFile(InputFileName);\n\n if (inputFile.is_open())\n {\n std::getline(inputFile, input);\n\n inputFile.close();\n }\n else\n {\n std::cout << \"Can't open a file named \" << InputFileName << std::endl;\n\n return;\n }\n }\n else if (InputType::Constructor == inputFrom)\n {\n input = expression;\n }\n\n processInput();\n }\n\n double Output()\n {\n if (!calculationDone) throw calc_not_done;\n\n if (InputType::Console == inputType)\n {\n std::cout << result << std::endl;\n }\n else if (InputType::File == inputType)\n {\n std::ofstream outputFile(OutputFileName);\n\n if (outputFile.is_open())\n {\n outputFile << result << std::endl;\n\n outputFile.close();\n }\n else\n {\n std::cout << \"Can't read a file named \" << OutputFileName << std::endl;\n\n return result;\n }\n }\n else if (InputType::Constructor == inputType)\n {\n \/\/ nothing specific, just return the result\n }\n\n calculationDone = false;\n\n return result;\n }\n\n private:\n double result;\n bool calculationDone;\n InputType inputType;\n std::string input;\n\n void processInput()\n {\n Stack st;\n std::string out;\n\n for (int i = 0; i < input.length(); ++i)\n {\n char c = input[i];\n\n if (c == ')')\n {\n while (st.Peek() != '(')\n {\n out += st.Pop();\n }\n\n st.Pop();\n }\n\n if (c >= '0' && c <= '9')\n {\n out += c;\n }\n\n if (c == '(')\n {\n st.Push(c);\n }\n\n if(c == '+' || c == '-' || c == '\/' || c == '*')\n {\n if (st.isEmpty())\n {\n st.Push(c);\n }\n else\n {\n if (priority(st.Peek()) < priority(c))\n {\n st.Push(c);\n }\n else\n {\n while (!st.isEmpty() && (priority(st.Peek()) >= priority(c)))\n {\n out += st.Pop();\n }\n\n st.Push(c);\n }\n }\n }\n }\n\n while (!st.isEmpty())\n {\n out += st.Pop();\n }\n\n std::cout << \"Polish notation: \" << out << std::endl;\n }\n\n int priority(char sign)\n {\n switch(sign)\n {\n case '*':\n case '\/':\n return 3;\n\n case '-':\n case '+':\n return 2;\n\n case '(':\n return 1;\n }\n }\n\n double calculate()\n {\n \/\/ calculate\n\n calculationDone = true;\n }\n};\n\n\/\/ add an option to use command line arguments\n\/\/ int argc, char* argv[]\nint main()\n{\n \/\/ Use case #1 - expression comes from console\n auto calc1 = new Calculator(InputType::Console); \/\/ Input() method called automatically\n calc1->Output();\n\n \/\/ Use case #2 - expression comes from file\n auto calc2 = new Calculator(InputType::File, \"test.in\", \"test.out\"); \/\/ custom filenames\n calc2->Output();\n\n \/\/ Use case #3 - expression in a constructor\n auto calc3 = new Calculator(InputType::Constructor, \"2 * 5 - 7 \/ 3 + (2 - 1 \/ 2)\"); \/\/ brackets supported\n calc3->Output();\n}\n<commit_msg>Finished implementation of calculation using polish notation<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <stack>\n\nenum class InputType\n{\n Console,\n File,\n Constructor\n};\n\nclass CalculationNotDoneException: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"The Input() method should be executed before Output()\";\n }\n} calc_not_done;\n\nclass Calculator\n{\n public:\n std::string InputFileName;\n std::string OutputFileName;\n\n Calculator() :\n InputFileName(\"Input.txt\"),\n OutputFileName(\"Output.txt\"),\n result(0),\n calculationDone(false)\n {\n \/\/ empty constructor, totally legit\n }\n\n Calculator(const InputType& inputFrom)\n {\n Calculator();\n\n Input(inputFrom);\n }\n\n Calculator(const InputType& inputFrom, const std::string& expression)\n {\n Calculator();\n\n Input(inputFrom, expression);\n }\n\n Calculator(const InputType& inputFrom, const std::string& inputFileName, const std::string& outputFileName)\n {\n Calculator();\n\n InputFileName = inputFileName;\n OutputFileName = outputFileName;\n\n Input(inputFrom);\n }\n\n void Input(const InputType& inputFrom, const std::string& expression = \"\")\n {\n inputType = inputFrom;\n\n if (InputType::Console == inputType)\n {\n std::getline(std::cin, input);\n }\n else if (InputType::File == inputType)\n {\n std::ifstream inputFile(InputFileName);\n\n if (inputFile.is_open())\n {\n std::getline(inputFile, input);\n\n inputFile.close();\n }\n else\n {\n std::cout << \"Can't read from file named \" << InputFileName << std::endl;\n\n return;\n }\n }\n else if (InputType::Constructor == inputType)\n {\n input = expression;\n }\n\n processInput();\n }\n\n long Output()\n {\n if (!calculationDone) throw calc_not_done;\n\n if (InputType::Console == inputType)\n {\n std::cout << result << std::endl;\n }\n else if (InputType::File == inputType)\n {\n std::ofstream outputFile(OutputFileName);\n\n if (outputFile.is_open())\n {\n outputFile << result << std::endl;\n\n outputFile.close();\n }\n else\n {\n std::cout << \"Can't create a file named \" << OutputFileName << std::endl;\n\n return result;\n }\n }\n else if (InputType::Constructor == inputType)\n {\n \/\/ nothing specific, just return the result\n }\n\n calculationDone = false;\n\n return result;\n }\n\n private:\n long result;\n bool calculationDone;\n InputType inputType;\n std::string input;\n\n \/\/ add ^ operator\n void processInput()\n {\n std::stack<char> st;\n std::string out;\n\n for (int i = 0; i < input.length(); ++i)\n {\n char c = input[i];\n\n if (c == ')')\n {\n while (st.top() != '(')\n {\n out += st.top();\n st.pop();\n }\n st.pop();\n }\n\n if (c >= '0' && c <= '9')\n {\n out += c;\n }\n\n if (c == '(')\n {\n st.push(c);\n }\n\n if(c == '+' || c == '-' || c == '\/' || c == '*')\n {\n if (st.empty())\n {\n st.push(c);\n }\n else\n {\n if (operationPriority(st.top()) < operationPriority(c))\n {\n st.push(c);\n }\n else\n {\n while (!st.empty() && (operationPriority(st.top()) >= operationPriority(c)))\n {\n out += st.top();\n st.pop();\n }\n\n st.push(c);\n }\n }\n }\n }\n\n while (!st.empty())\n {\n out += st.top();\n st.pop();\n }\n\n input = out;\n\n calculateOutput();\n }\n\n \/\/ add ^ operator\n int operationPriority(char sign)\n {\n switch(sign)\n {\n case '*':\n case '\/':\n return 3;\n\n case '-':\n case '+':\n return 2;\n\n case '(':\n return 1;\n }\n }\n\n \/\/ add ^ operator\n long calculateOutput()\n {\n std::stack<std::string> st;\n\n for (int i = 0; i < input.length(); ++i)\n {\n char c = input[i];\n\n if(c == '+' || c == '-' || c == '*' || c == '\/')\n {\n long a = std::stol(st.top());\n st.pop();\n long b = std::stol(st.top());\n st.pop();\n\n switch(c)\n {\n case '+':\n st.push(std::to_string(a + b));\n break;\n\n case '-':\n st.push(std::to_string(a - b));\n break;\n\n case '*':\n st.push(std::to_string(a * b));\n break;\n\n case '\/':\n st.push(std::to_string(a \/ b));\n break;\n }\n }\n else\n {\n st.push(std::to_string(c));\n }\n }\n\n result = std::stol(st.top());\n\n calculationDone = true;\n }\n};\n\n\/\/ add an option to use command line arguments\n\/\/ int argc, char* argv[]\nint main()\n{\n \/\/ Use case #1 - expression comes from console\n auto calc1 = new Calculator(InputType::Console); \/\/ Input() method called automatically\n calc1->Output();\n\n \/\/ Use case #2 - expression comes from file\n auto calc2 = new Calculator(InputType::File, \"test.in\", \"test.out\"); \/\/ custom filenames\n calc2->Output();\n\n \/\/ Use case #3 - expression in a constructor\n auto calc3 = new Calculator(InputType::Constructor, \"2 * 5 - 7 \/ 3 + (2 - 1 \/ 2)\"); \/\/ brackets supported\n calc3->Output();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"xchainer\/memory.h\"\n\n#include <cassert>\n\n#ifdef XCHAINER_ENABLE_CUDA\n#include <cuda.h>\n#include <cuda_runtime.h>\n#endif \/\/ XCHAINER_ENABLE_CUDA\n\n#include \"xchainer\/backend.h\"\n#ifdef XCHAINER_ENABLE_CUDA\n#include \"xchainer\/cuda\/cuda_runtime.h\"\n#endif \/\/ XCHAINER_ENABLE_CUDA\n#include \"xchainer\/device_id.h\"\n#include \"xchainer\/error.h\"\n\n#include <iostream>\n\nnamespace xchainer {\nnamespace internal {\n\nbool IsPointerCudaMemory(const void* ptr) {\n#ifdef XCHAINER_ENABLE_CUDA\n cudaPointerAttributes attr = {};\n cudaError_t status = cudaPointerGetAttributes(&attr, ptr);\n switch (status) {\n case cudaSuccess:\n if (attr.isManaged) {\n return true;\n } else {\n throw XchainerError(\"Non-managed GPU memory is not supported\");\n }\n case cudaErrorInvalidValue:\n return false;\n default:\n cuda::CheckError(status);\n break;\n }\n assert(false); \/\/ should never be reached\n#else\n (void)ptr; \/\/ unused\n return false;\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\nstd::shared_ptr<void> Allocate(const DeviceId& device_id, size_t bytesize) {\n \/\/ TODO(sonots): Use device_id.backend->Allocate()\n if (device_id.backend()->GetName() == \"native\") {\n return std::make_unique<uint8_t[]>(bytesize);\n#ifdef XCHAINER_ENABLE_CUDA\n } else if (device_id.backend()->GetName() == \"cuda\") {\n void* raw_ptr = nullptr;\n \/\/ Be careful to be exception-safe, i.e., do not throw before creating shared_ptr\n cudaError_t status = cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal);\n if (status == cudaSuccess) {\n return std::shared_ptr<void>{raw_ptr, cudaFree};\n } else {\n cuda::Throw(status);\n }\n assert(false); \/\/ should never be reached\n#endif \/\/ XCHAINER_ENABLE_CUDA\n } else {\n throw DeviceError(\"invalid device_id\");\n }\n}\n\nvoid MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {\n#ifdef XCHAINER_ENABLE_CUDA\n bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);\n bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);\n if (is_dst_cuda_memory) {\n if (is_src_cuda_memory) {\n \/\/ Copy from device_id to device_id is faster even in unified memory\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));\n } else {\n \/\/ For pre-6.x GPU architecture, we encountered SEGV with std::memcpy\n \/\/ ref. https:\/\/github.com\/pfnet\/xchainer\/pull\/74\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));\n }\n } else {\n if (is_src_cuda_memory) {\n \/\/ For pre-6.x GPU architecture, we encountered SEGV with std::memcpy\n \/\/ ref. https:\/\/github.com\/pfnet\/xchainer\/pull\/74\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));\n } else {\n std::memcpy(dst_ptr, src_ptr, bytesize);\n }\n }\n#else\n std::memcpy(dst_ptr, src_ptr, bytesize);\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\nstd::shared_ptr<void> MemoryFromBuffer(const DeviceId& device_id, const std::shared_ptr<void>& src_ptr, size_t bytesize) {\n\/\/ TODO(sonots): Use device_id.backend->FromBuffer()\n#ifdef XCHAINER_ENABLE_CUDA\n if (device_id.backend()->GetName() == \"native\") {\n if (IsPointerCudaMemory(src_ptr.get())) {\n std::shared_ptr<void> dst_ptr = Allocate(device_id, bytesize);\n cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));\n return dst_ptr;\n } else {\n return src_ptr;\n }\n } else if (device_id.backend()->GetName() == \"cuda\") {\n if (IsPointerCudaMemory(src_ptr.get())) {\n return src_ptr;\n } else {\n std::shared_ptr<void> dst_ptr = Allocate(device_id, bytesize);\n cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));\n return dst_ptr;\n }\n } else {\n throw DeviceError(\"invalid device_id\");\n }\n#else\n (void)bytesize; \/\/ unused\n if (device_id.backend()->GetName() == \"native\") {\n return src_ptr;\n } else {\n throw DeviceError(\"invalid device_id\");\n }\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\n} \/\/ namespace internal\n} \/\/ namespace xchainer\n<commit_msg>trivial: fix comments<commit_after>#include \"xchainer\/memory.h\"\n\n#include <cassert>\n\n#ifdef XCHAINER_ENABLE_CUDA\n#include <cuda.h>\n#include <cuda_runtime.h>\n#endif \/\/ XCHAINER_ENABLE_CUDA\n\n#include \"xchainer\/backend.h\"\n#ifdef XCHAINER_ENABLE_CUDA\n#include \"xchainer\/cuda\/cuda_runtime.h\"\n#endif \/\/ XCHAINER_ENABLE_CUDA\n#include \"xchainer\/device_id.h\"\n#include \"xchainer\/error.h\"\n\n#include <iostream>\n\nnamespace xchainer {\nnamespace internal {\n\nbool IsPointerCudaMemory(const void* ptr) {\n#ifdef XCHAINER_ENABLE_CUDA\n cudaPointerAttributes attr = {};\n cudaError_t status = cudaPointerGetAttributes(&attr, ptr);\n switch (status) {\n case cudaSuccess:\n if (attr.isManaged) {\n return true;\n } else {\n throw XchainerError(\"Non-managed GPU memory is not supported\");\n }\n case cudaErrorInvalidValue:\n return false;\n default:\n cuda::CheckError(status);\n break;\n }\n assert(false); \/\/ should never be reached\n#else\n (void)ptr; \/\/ unused\n return false;\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\nstd::shared_ptr<void> Allocate(const DeviceId& device_id, size_t bytesize) {\n \/\/ TODO(sonots): Use device_id.backend->Allocate()\n if (device_id.backend()->GetName() == \"native\") {\n return std::make_unique<uint8_t[]>(bytesize);\n#ifdef XCHAINER_ENABLE_CUDA\n } else if (device_id.backend()->GetName() == \"cuda\") {\n void* raw_ptr = nullptr;\n \/\/ Be careful to be exception-safe, i.e., do not throw before creating shared_ptr\n cudaError_t status = cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal);\n if (status == cudaSuccess) {\n return std::shared_ptr<void>{raw_ptr, cudaFree};\n } else {\n cuda::Throw(status);\n }\n assert(false); \/\/ should never be reached\n#endif \/\/ XCHAINER_ENABLE_CUDA\n } else {\n throw DeviceError(\"invalid device_id\");\n }\n}\n\nvoid MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {\n#ifdef XCHAINER_ENABLE_CUDA\n bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);\n bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);\n if (is_dst_cuda_memory) {\n if (is_src_cuda_memory) {\n \/\/ Copy from device to device is faster even in unified memory\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));\n } else {\n \/\/ For pre-6.x GPU architecture, we encountered SEGV with std::memcpy\n \/\/ ref. https:\/\/github.com\/pfnet\/xchainer\/pull\/74\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));\n }\n } else {\n if (is_src_cuda_memory) {\n \/\/ For pre-6.x GPU architecture, we encountered SEGV with std::memcpy\n \/\/ ref. https:\/\/github.com\/pfnet\/xchainer\/pull\/74\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));\n } else {\n std::memcpy(dst_ptr, src_ptr, bytesize);\n }\n }\n#else\n std::memcpy(dst_ptr, src_ptr, bytesize);\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\nstd::shared_ptr<void> MemoryFromBuffer(const DeviceId& device_id, const std::shared_ptr<void>& src_ptr, size_t bytesize) {\n\/\/ TODO(sonots): Use device_id.backend->FromBuffer()\n#ifdef XCHAINER_ENABLE_CUDA\n if (device_id.backend()->GetName() == \"native\") {\n if (IsPointerCudaMemory(src_ptr.get())) {\n std::shared_ptr<void> dst_ptr = Allocate(device_id, bytesize);\n cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));\n return dst_ptr;\n } else {\n return src_ptr;\n }\n } else if (device_id.backend()->GetName() == \"cuda\") {\n if (IsPointerCudaMemory(src_ptr.get())) {\n return src_ptr;\n } else {\n std::shared_ptr<void> dst_ptr = Allocate(device_id, bytesize);\n cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));\n return dst_ptr;\n }\n } else {\n throw DeviceError(\"invalid device_id\");\n }\n#else\n (void)bytesize; \/\/ unused\n if (device_id.backend()->GetName() == \"native\") {\n return src_ptr;\n } else {\n throw DeviceError(\"invalid device_id\");\n }\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\n} \/\/ namespace internal\n} \/\/ namespace xchainer\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <set>\n\n#include \"cauchycoding.h\"\n#include \"alloc.h\"\n\n#include \"jerasure.h\"\n#include \"cauchy.h\"\n\nvoid CauchyCoding::checkParams() {\n if (k <= 0 || m <= 0 || w <= 0)\n throw std::invalid_argument(\"Invalid Coding Parameters\");\n}\n\nvector<ErlNifBinary> CauchyCoding::doEncode(unsigned char* data, size_t dataSize) {\n vector<ErlNifBinary> allBlockEntry;\n\n int *matrix = cauchy_good_general_coding_matrix(k, m, w);\n int *bitmatrix = jerasure_matrix_to_bitmatrix(k, m, w, matrix);\n int **smart = jerasure_smart_bitmatrix_to_schedule(k, m, w, bitmatrix);\n\n size_t blockSize = roundTo((roundTo(dataSize, k*w) \/ (k*w)), sizeof(long)) * w;\n\n char** dataBlocks = (char**)alloc(sizeof(char*) * k);\n char** codeBlocks = (char**)alloc(sizeof(char*) * m);\n\n size_t offset = 0;\n for(int i = 0; i < k; ++i) {\n ErlNifBinary tmpBlock;\n enif_alloc_binary(blockSize, &tmpBlock);\n dataBlocks[i] = (char*)tmpBlock.data;\n\n allBlockEntry.push_back(tmpBlock);\n\n if (i == k - 1) {\n memset(dataBlocks[i], 0, blockSize);\n memcpy(dataBlocks[i], data + offset, dataSize - offset);\n } else {\n memcpy(dataBlocks[i], data + offset, blockSize);\n }\n offset += blockSize;\n }\n\n for(int i = 0; i < m; ++i) {\n ErlNifBinary tmpBlock;\n enif_alloc_binary(blockSize, &tmpBlock);\n codeBlocks[i] = (char*)tmpBlock.data;\n \n allBlockEntry.push_back(tmpBlock);\n }\n\n jerasure_schedule_encode(k, m, w, smart, dataBlocks, codeBlocks, blockSize, blockSize \/ w);\n\n jerasure_free_schedule(smart);\n free(matrix);\n free(bitmatrix);\n dealloc(dataBlocks);\n dealloc(codeBlocks);\n return allBlockEntry;\n}\n\nErlNifBinary CauchyCoding::doDecode(vector<ErlNifBinary> blockList, vector<int> blockIdList, size_t dataSize) {\n\n ErlNifBinary file;\n\n char** dataBlocks = (char**)alloc(sizeof(char*) * k);\n char** codeBlocks = (char**)alloc(sizeof(char*) * m);\n int erasures[k + m];\n size_t blockSize = blockList[0].size;\n set<int> availSet(blockIdList.begin(), blockIdList.end());\n\n int j = 0;\n for(int i = 0; i < k + m; ++i) {\n i < k ? dataBlocks[i] = (char*)alloc(blockSize) : codeBlocks[i - k] = (char*)alloc(blockSize);\n if (availSet.count(i) == 0) {\n erasures[j++] = i;\n }\n }\n erasures[j] = -1;\n\n for(size_t i = 0; i < blockList.size(); ++i) {\n int blockId = blockIdList[i];\n if (blockId < k) {\n memcpy(dataBlocks[blockId], blockList[i].data, blockSize);\n } else {\n memcpy(codeBlocks[blockId - k], blockList[i].data, blockSize);\n }\n }\n\n int *matrix = cauchy_good_general_coding_matrix(k, m, w);\n int *bitmatrix = jerasure_matrix_to_bitmatrix(k, m, w, matrix);\n jerasure_schedule_decode_lazy(k, m, w, bitmatrix, erasures, dataBlocks, codeBlocks, blockSize, blockSize \/ w, 1);\n\n enif_alloc_binary(dataSize, &file);\n size_t offset = 0;\n int i = 0;\n while(offset < dataSize) {\n size_t copySize = min(dataSize - offset, blockSize);\n memcpy(file.data + offset, dataBlocks[i], copySize);\n i++;\n offset += copySize;\n }\n\n for(int i = 0; i < k + m; ++i) {\n i < k ? dealloc(dataBlocks[i]) : dealloc(codeBlocks[i - k]);\n }\n\n free(matrix);\n free(bitmatrix);\n dealloc(dataBlocks);\n dealloc(codeBlocks);\n return file;\n}\n<commit_msg>[CauchyRS] Added Parameters check for w<commit_after>#include <string.h>\n#include <set>\n\n#include \"cauchycoding.h\"\n#include \"alloc.h\"\n\n#include \"jerasure.h\"\n#include \"cauchy.h\"\n\nvoid CauchyCoding::checkParams() {\n if (k <= 0 || m <= 0 || w <= 0)\n throw std::invalid_argument(\"Invalid Coding Parameters\");\n if ((k + m) > (1 << w))\n throw std::invalid_argument(\"Invalid Coding Parameters (larger w)\");\n}\n\nvector<ErlNifBinary> CauchyCoding::doEncode(unsigned char* data, size_t dataSize) {\n vector<ErlNifBinary> allBlockEntry;\n\n int *matrix = cauchy_good_general_coding_matrix(k, m, w);\n int *bitmatrix = jerasure_matrix_to_bitmatrix(k, m, w, matrix);\n int **smart = jerasure_smart_bitmatrix_to_schedule(k, m, w, bitmatrix);\n\n size_t blockSize = roundTo((roundTo(dataSize, k*w) \/ (k*w)), sizeof(long)) * w;\n\n char** dataBlocks = (char**)alloc(sizeof(char*) * k);\n char** codeBlocks = (char**)alloc(sizeof(char*) * m);\n\n size_t offset = 0;\n for(int i = 0; i < k; ++i) {\n ErlNifBinary tmpBlock;\n enif_alloc_binary(blockSize, &tmpBlock);\n dataBlocks[i] = (char*)tmpBlock.data;\n\n allBlockEntry.push_back(tmpBlock);\n\n if (i == k - 1) {\n memset(dataBlocks[i], 0, blockSize);\n memcpy(dataBlocks[i], data + offset, dataSize - offset);\n } else {\n memcpy(dataBlocks[i], data + offset, blockSize);\n }\n offset += blockSize;\n }\n\n for(int i = 0; i < m; ++i) {\n ErlNifBinary tmpBlock;\n enif_alloc_binary(blockSize, &tmpBlock);\n codeBlocks[i] = (char*)tmpBlock.data;\n \n allBlockEntry.push_back(tmpBlock);\n }\n\n jerasure_schedule_encode(k, m, w, smart, dataBlocks, codeBlocks, blockSize, blockSize \/ w);\n\n jerasure_free_schedule(smart);\n free(matrix);\n free(bitmatrix);\n dealloc(dataBlocks);\n dealloc(codeBlocks);\n return allBlockEntry;\n}\n\nErlNifBinary CauchyCoding::doDecode(vector<ErlNifBinary> blockList, vector<int> blockIdList, size_t dataSize) {\n\n ErlNifBinary file;\n\n char** dataBlocks = (char**)alloc(sizeof(char*) * k);\n char** codeBlocks = (char**)alloc(sizeof(char*) * m);\n int erasures[k + m];\n size_t blockSize = blockList[0].size;\n set<int> availSet(blockIdList.begin(), blockIdList.end());\n\n int j = 0;\n for(int i = 0; i < k + m; ++i) {\n i < k ? dataBlocks[i] = (char*)alloc(blockSize) : codeBlocks[i - k] = (char*)alloc(blockSize);\n if (availSet.count(i) == 0) {\n erasures[j++] = i;\n }\n }\n erasures[j] = -1;\n\n for(size_t i = 0; i < blockList.size(); ++i) {\n int blockId = blockIdList[i];\n if (blockId < k) {\n memcpy(dataBlocks[blockId], blockList[i].data, blockSize);\n } else {\n memcpy(codeBlocks[blockId - k], blockList[i].data, blockSize);\n }\n }\n\n int *matrix = cauchy_good_general_coding_matrix(k, m, w);\n int *bitmatrix = jerasure_matrix_to_bitmatrix(k, m, w, matrix);\n jerasure_schedule_decode_lazy(k, m, w, bitmatrix, erasures, dataBlocks, codeBlocks, blockSize, blockSize \/ w, 1);\n\n enif_alloc_binary(dataSize, &file);\n size_t offset = 0;\n int i = 0;\n while(offset < dataSize) {\n size_t copySize = min(dataSize - offset, blockSize);\n memcpy(file.data + offset, dataBlocks[i], copySize);\n i++;\n offset += copySize;\n }\n\n for(int i = 0; i < k + m; ++i) {\n i < k ? dealloc(dataBlocks[i]) : dealloc(codeBlocks[i - k]);\n }\n\n free(matrix);\n free(bitmatrix);\n dealloc(dataBlocks);\n dealloc(codeBlocks);\n return file;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ @brief computes scales for CORDIC rotations in case of hyperbolic coordinates\r\n\r\nnamespace core { namespace cordic {\r\n template<size_t n, typename fp>\r\n double lut<n, fp>::hyperbolic_scale_with_repeated_iterations(size_t n)\r\n {\r\n double scale(1.0);\r\n\r\n size_t num(0);\r\n size_t repeated(4u);\r\n BOOST_FOREACH(size_t i, boost::irange<size_t>(1, n, 1))\r\n {\r\n scale *= std::sqrt(1 - std::powl(2.0, -2.0 * i));\r\n if (i == repeated && i != n - 1) {\r\n scale *= std::sqrt(1 - std::powl(2.0, -2.0 * i++));\r\n\r\n repeated = 3u * repeated + 1u;\r\n }\r\n }\r\n\r\n return scale;\r\n }\r\n}}\r\n<commit_msg>hyperbolic_scale.inl: remove implicit cast + unrefenced variable<commit_after>\/\/\/ @brief computes scales for CORDIC rotations in case of hyperbolic coordinates\r\n\r\nnamespace core { namespace cordic {\r\n template<size_t n, typename fp>\r\n double lut<n, fp>::hyperbolic_scale_with_repeated_iterations(size_t n)\r\n {\r\n double scale(1.0);\r\n\r\n size_t repeated(4u);\r\n BOOST_FOREACH(size_t i, boost::irange<size_t>(1, n, 1))\r\n {\r\n scale *= std::sqrt(1 - std::pow(2.0, -2.0 * i));\r\n if (i == repeated && i != n - 1) {\r\n scale *= std::sqrt(1 - std::pow(2.0, -2.0 * i++));\r\n\r\n repeated = 3u * repeated + 1u;\r\n }\r\n }\r\n\r\n return scale;\r\n }\r\n}}\r\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n* Copyright (c) 2013 David D. Marshall <ddmarsha@calpoly.edu>\n*\n* All rights reserved. This program and the accompanying materials\n* are made available under the terms of the Eclipse Public License v1.0\n* which accompanies this distribution, and is available at\n* http:\/\/www.eclipse.org\/legal\/epl-v10.html\n*\n* Contributors:\n* David D. Marshall - initial code and implementation\n********************************************************************************\/\n\n#ifndef eli_mutil_opt_least_squares_hpp\n#define eli_mutil_opt_least_squares_hpp\n\n#include \"eli\/code_eli.hpp\"\n\nnamespace eli\n{\n namespace mutil\n {\n namespace opt\n {\n template<typename data1__, typename data2__, typename data3__>\n void least_squares_uncon(Eigen::MatrixBase<data1__> &x, const Eigen::MatrixBase<data2__> &A, const Eigen::MatrixBase<data3__> &r)\n {\n unsigned int flags(0);\n if (Eigen::MatrixBase<data2__>::ColsAtCompileTime==Eigen::Dynamic)\n flags=Eigen::ComputeThinU | Eigen::ComputeThinV;\n else\n flags=Eigen::ComputeFullU | Eigen::ComputeFullV;\n\n Eigen::JacobiSVD<typename Eigen::MatrixBase<data2__>::PlainObject > svd(A, flags);\n x=svd.solve(r);\n }\n\n template<typename data1__, typename data2__, typename data3__, typename data4__, typename data5__>\n void least_squares_eqcon(Eigen::MatrixBase<data1__> &x, const Eigen::MatrixBase<data2__> &A, const Eigen::MatrixBase<data3__> &b, const Eigen::MatrixBase<data4__> &B, const Eigen::MatrixBase<data5__> &d)\n {\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data4__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> B_matrixD;\n B_matrixD Q, R, temp_B, temp_R;\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data2__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> A_matrixD;\n A_matrixD A1, A2, temp_A;\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data5__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> d_matrixD;\n d_matrixD y;\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data3__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> b_matrixD;\n b_matrixD z, rhs;\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data1__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> x_matrixD;\n x_matrixD x_temp(A.cols(), b.cols());\n typename A_matrixD::Index p(B.rows()), n(A.cols());\n #ifdef DEBUG\n typename A_matrixD::Index m(b.rows());\n #endif\n\n \/\/ build Q and R\n Eigen::HouseholderQR<B_matrixD> qr(B.transpose());\n Q=qr.householderQ();\n temp_B=qr.matrixQR();\n temp_R=Eigen::TriangularView<B_matrixD, Eigen::Upper>(temp_B);\n R=temp_R.topRows(p);\n assert((R.rows()==p) && (R.cols()==p));\n assert((Q.rows()==n) && (Q.cols()==n));\n\n \/\/ build A1 and A2\n temp_A=A*Q;\n A1=temp_A.leftCols(p);\n A2=temp_A.rightCols(n-p);\n#ifdef DEBUG\n assert((A1.rows()==m) && (A1.cols()==p));\n assert((A2.rows()==m) && (A2.cols()==n-p));\n#endif\n assert(A1.cols()==p);\n assert(A2.cols()==n-p);\n\n \/\/ solve for y\n y=R.transpose().lu().solve(d);\n\n \/\/ setup the unconstrained optimization\n rhs=b-A1*y;\n least_squares_uncon(z, A2, rhs);\n\n \/\/ build the solution\n x_temp.topRows(p)=y;\n x_temp.bottomRows(n-p)=z;\n x=Q*x_temp;\n }\n }\n }\n}\n\n#endif\n<commit_msg>Added documentation to function.<commit_after>\/*********************************************************************************\n* Copyright (c) 2013 David D. Marshall <ddmarsha@calpoly.edu>\n*\n* All rights reserved. This program and the accompanying materials\n* are made available under the terms of the Eclipse Public License v1.0\n* which accompanies this distribution, and is available at\n* http:\/\/www.eclipse.org\/legal\/epl-v10.html\n*\n* Contributors:\n* David D. Marshall - initial code and implementation\n********************************************************************************\/\n\n#ifndef eli_mutil_opt_least_squares_hpp\n#define eli_mutil_opt_least_squares_hpp\n\n#include \"eli\/code_eli.hpp\"\n\nnamespace eli\n{\n namespace mutil\n {\n namespace opt\n {\n template<typename data1__, typename data2__, typename data3__>\n void least_squares_uncon(Eigen::MatrixBase<data1__> &x, const Eigen::MatrixBase<data2__> &A, const Eigen::MatrixBase<data3__> &r)\n {\n unsigned int flags(0);\n if (Eigen::MatrixBase<data2__>::ColsAtCompileTime==Eigen::Dynamic)\n flags=Eigen::ComputeThinU | Eigen::ComputeThinV;\n else\n flags=Eigen::ComputeFullU | Eigen::ComputeFullV;\n\n Eigen::JacobiSVD<typename Eigen::MatrixBase<data2__>::PlainObject > svd(A, flags);\n x=svd.solve(r);\n }\n\n \/**\n This solves a linear least squares problem of the form \\f$ \\min_{B\\vec{x}=\\vec{d}}\\left|\\left| A\\vec{x}-\\vec{b} \\right|\\right|^2 \\f$ \n *\/\n template<typename data1__, typename data2__, typename data3__, typename data4__, typename data5__>\n void least_squares_eqcon(Eigen::MatrixBase<data1__> &x, const Eigen::MatrixBase<data2__> &A, const Eigen::MatrixBase<data3__> &b, const Eigen::MatrixBase<data4__> &B, const Eigen::MatrixBase<data5__> &d)\n {\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data4__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> B_matrixD;\n B_matrixD Q, R, temp_B, temp_R;\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data2__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> A_matrixD;\n A_matrixD A1, A2, temp_A;\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data5__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> d_matrixD;\n d_matrixD y;\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data3__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> b_matrixD;\n b_matrixD z, rhs;\n typedef Eigen::Matrix<typename Eigen::MatrixBase<data1__>::Scalar, Eigen::Dynamic, Eigen::Dynamic> x_matrixD;\n x_matrixD x_temp(A.cols(), b.cols());\n typename A_matrixD::Index p(B.rows()), n(A.cols());\n #ifdef DEBUG\n typename A_matrixD::Index m(b.rows());\n #endif\n\n \/\/ build Q and R\n Eigen::HouseholderQR<B_matrixD> qr(B.transpose());\n Q=qr.householderQ();\n temp_B=qr.matrixQR();\n temp_R=Eigen::TriangularView<B_matrixD, Eigen::Upper>(temp_B);\n R=temp_R.topRows(p);\n assert((R.rows()==p) && (R.cols()==p));\n assert((Q.rows()==n) && (Q.cols()==n));\n\n \/\/ build A1 and A2\n temp_A=A*Q;\n A1=temp_A.leftCols(p);\n A2=temp_A.rightCols(n-p);\n#ifdef DEBUG\n assert((A1.rows()==m) && (A1.cols()==p));\n assert((A2.rows()==m) && (A2.cols()==n-p));\n#endif\n assert(A1.cols()==p);\n assert(A2.cols()==n-p);\n\n \/\/ solve for y\n y=R.transpose().lu().solve(d);\n\n \/\/ setup the unconstrained optimization\n rhs=b-A1*y;\n least_squares_uncon(z, A2, rhs);\n\n \/\/ build the solution\n x_temp.topRows(p)=y;\n x_temp.bottomRows(n-p)=z;\n x=Q*x_temp;\n }\n }\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 Eran Pe'er.\n *\n * This program is made available under the terms of the MIT License.\n *\n * Created on Mar 10, 2014\n *\/\n\n#ifndef MethodMockingContext_h__\n#define MethodMockingContext_h__\n\n#include <functional>\n#include <type_traits>\n#include <tuple>\n#include <memory>\n#include <vector>\n#include <unordered_set>\n#include <set>\n#include <iosfwd>\n\n#include \"fakeit\/RecordedMethodBody.hpp\"\n#include \"fakeit\/StubbingProgress.hpp\"\n#include \"fakeit\/Sequence.hpp\"\n#include \"fakeit\/ActualInvocation.hpp\"\n#include \"fakeit\/EventHandler.hpp\"\n#include \"fakeit\/ActionSequence.hpp\"\n#include \"fakeit\/DomainObjects.hpp\"\n#include \"fakeit\/SpyingContext.hpp\"\n#include \"fakeit\/StubbingContext.hpp\"\n#include \"fakeit\/MatchersCollector.hpp\"\n#include \"mockutils\/type_utils.hpp\"\n\nnamespace fakeit {\n\/**\n * Build recorded sequence and the matching criteria.\n * For example, for the following line:\n * When(Method(mock,foo)).Return(1).Return(2_Times(2)).Throw(e1);\n * The matching criteria is: Any invocation of mock.foo\n * The recorded sequence is: {Return(1), Return(2), Return(2), Throw(e1)}\n *\/\ntemplate<typename R, typename ... arglist>\nclass MethodMockingContext: \/\/\npublic Sequence, \/\/ For use in Verify(sequence1,...)... phrases.\n\t\tpublic ActualInvocationsSource, \/\/ For use in Using(source1,souece2,...) and VerifyNoOtherInvocations(source1,souece2...) phrases.\n\t\tpublic virtual StubbingContext<R, arglist...>, \/\/ For use in Fake, Spy & When phrases\n\t\tpublic virtual SpyingContext<R, arglist...>, \/\/ For use in Fake, Spy & When phrases\n\t\tprivate Invocation::Matcher {\n\npublic:\n\n\tstruct Context: public Destructable {\n\n\t\tvirtual ~Context() = default;\n\n\t\t\/**\n\t\t * Return the original method. not the mock.\n\t\t *\/\n\t\tvirtual std::function<R(arglist&...)> getOriginalMethod() = 0;\n\n\t\tvirtual std::string getMethodName() = 0;\n\n\t\tvirtual void addMethodInvocationHandler(typename ActualInvocation<arglist...>::Matcher* matcher,\n\t\t\t\tMethodInvocationHandler<R, arglist...>* invocationHandler) = 0;\n\n\t\tvirtual void scanActualInvocations(const std::function<void(ActualInvocation<arglist...>&)>& scanner) = 0;\n\n\t\tvirtual void setMethodDetails(std::string mockName, std::string methodName) = 0;\n\n\t\tvirtual bool isOfMethod(Method& method) = 0;\n\n\t\tvirtual ActualInvocationsSource& getInvolvedMock() = 0;\n\t};\n\nprivate:\n\tclass Implementation {\n\n\t\tContext* _stubbingContext;\n\t\tActionSequence<R, arglist...>* _recordedActionSequence;\n\t\ttypename ActualInvocation<arglist...>::Matcher* _invocationMatcher;bool _commited;\n\n\t\tContext& getStubbingContext() const {\n\t\t\treturn *_stubbingContext;\n\t\t}\n\n\tpublic:\n\n\t\tImplementation(Context* stubbingContext)\n\t\t\t\t: _stubbingContext(stubbingContext), _recordedActionSequence(new ActionSequence<R, arglist...>()), _invocationMatcher {\n\t\t\t\t\t\tnew DefaultInvocationMatcher<arglist...>() }, _commited(false) {\n\t\t}\n\n\t\t~Implementation() {\n\t\t\tdelete _stubbingContext;\n\t\t\tif (!_commited) {\n\t\t\t\t\/\/ no commit. delete the created objects.\n\t\t\t\tdelete _recordedActionSequence;\n\t\t\t\tdelete _invocationMatcher;\n\t\t\t}\n\t\t}\n\n\t\tActionSequence<R, arglist...>& getRecordedActionSequence() {\n\t\t\treturn *_recordedActionSequence;\n\t\t}\n\n\t\tstd::string format() const {\n\t\t\tstd::string s = getStubbingContext().getMethodName();\n\t\t\ts += _invocationMatcher->format();\n\t\t\treturn s;\n\t\t}\n\n\t\tvoid getActualInvocations(std::unordered_set<Invocation*>& into) const {\n\t\t\tauto scanner = [&](ActualInvocation<arglist...>& a) {\n\t\t\t\tif (_invocationMatcher->matches(a)) {\n\t\t\t\t\tinto.insert(&a);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetStubbingContext().scanActualInvocations(scanner);\n\t\t}\n\n\t\t\/**\n\t\t * Used only by Verify phrase.\n\t\t *\/\n\t\tbool matches(Invocation& invocation) {\n\t\t\tMethod& actualMethod = invocation.getMethod();\n\t\t\tif (!getStubbingContext().isOfMethod(actualMethod)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tActualInvocation<arglist...>& actualInvocation = dynamic_cast<ActualInvocation<arglist...>&>(invocation);\n\t\t\treturn _invocationMatcher->matches(actualInvocation);\n\t\t}\n\n\t\tvoid commit() {\n\t\t\tgetStubbingContext().addMethodInvocationHandler(_invocationMatcher, _recordedActionSequence);\n\t\t\t_commited = true;\n\t\t}\n\n\t\tvoid appendAction(Action<R, arglist...>* action) {\n\t\t\tgetRecordedActionSequence().AppendDo(action);\n\t\t}\n\n\t\tvoid setMethodBodyByAssignment(std::function<R(arglist&...)> method) {\n\t\t\tappendAction(new RepeatForever<R, arglist...>(method));\n\t\t\tcommit();\n\t\t}\n\n\t\tvoid setMethodDetails(std::string mockName, std::string methodName) {\n\t\t\tgetStubbingContext().setMethodDetails(mockName, methodName);\n\t\t}\n\n\t\tvoid getInvolvedMocks(std::set<const ActualInvocationsSource*>& into) const {\n\t\t\tinto.insert(&getStubbingContext().getInvolvedMock());\n\t\t}\n\n\t\ttypename std::function<R(arglist&...)> getOriginalMethod() {\n\t\t\treturn getStubbingContext().getOriginalMethod();\n\t\t}\n\n\t\tvoid setInvocationMatcher(typename ActualInvocation<arglist...>::Matcher* matcher) {\n\t\t\tdelete _invocationMatcher;\n\t\t\t_invocationMatcher = matcher;\n\t\t}\n\t};\n\nprotected:\n\n\tMethodMockingContext(Context* stubbingContext)\n\t\t\t: _impl { new Implementation(stubbingContext) } {\n\t}\n\n\t\/\/Move ctor for use by derived classes.\n\tMethodMockingContext(MethodMockingContext& other)\n\t\t\t: _impl(other._impl) {\n\t}\n\n\tvirtual ~MethodMockingContext() = default;\n\n\tstd::string format() const {\n\t\treturn _impl->format();\n\t}\n\n\tunsigned int size() const override {\n\t\treturn 1;\n\t}\n\n\t\/**\n\t * Used only by Verify phrase.\n\t *\/\n\tvoid getInvolvedMocks(std::set<const ActualInvocationsSource*>& into) const override {\n\t\t_impl->getInvolvedMocks(into);\n\t}\n\n\tvoid getExpectedSequence(std::vector<Invocation::Matcher*>& into) const override {\n\t\tconst Invocation::Matcher* b = this;\n\t\tInvocation::Matcher* c = const_cast<Invocation::Matcher*>(b);\n\t\tinto.push_back(c);\n\t}\n\n\t\/**\n\t * Used only by Verify phrase.\n\t *\/\n\tvoid getActualInvocations(std::unordered_set<Invocation*>& into) const override {\n\t\t_impl->getActualInvocations(into);\n\t}\n\n\t\/**\n\t * Used only by Verify phrase.\n\t *\/\n\tvirtual bool matches(Invocation& invocation) override {\n\t\treturn _impl->matches(invocation);\n\t}\n\n\tvirtual void commit() override {\n\t\t_impl->commit();\n\t}\n\n\tvoid setMethodDetails(std::string mockName, std::string methodName) {\n\t\t_impl->setMethodDetails(mockName, methodName);\n\t}\n\n\/\/\tvoid setMatchingCriteria(const arglist&... args) {\n\/\/\t\t_impl->setMatchingCriteria(args...);\n\/\/\t}\n\n\tvoid setMatchingCriteria(std::function<bool(arglist&...)> predicate) {\n\t\ttypename ActualInvocation<arglist...>::Matcher* matcher { new UserDefinedInvocationMatcher<arglist...>(predicate) };\n\t\t_impl->setInvocationMatcher(matcher);\n\t}\n\n\tvoid setMatchingCriteria(const std::vector<Destructable*>& matchers) {\n\t\ttypename ActualInvocation<arglist...>::Matcher* matcher { new ArgumentsMatcherInvocationMatcher<arglist...>(matchers) };\n\t\t_impl->setInvocationMatcher(matcher);\n\t}\n\n\t\/**\n\t * Used by Fake, Spy & When functors\n\t *\/\n\tvoid appendAction(Action<R, arglist...>* action) override {\n\t\t_impl->appendAction(action);\n\t}\n\n\tvoid setMethodBodyByAssignment(std::function<R(arglist&...)> method) {\n\t\t_impl->setMethodBodyByAssignment(method);\n\t}\n\n\ttemplate<class ...matcherCreators, class = typename std::enable_if<sizeof...(matcherCreators)==sizeof...(arglist)>::type>\n\tvoid setMatchingCriteria(const matcherCreators& ... matcherCreator) {\n\t\tstd::vector<Destructable*> matchers;\n\n\t\tMatchersCollector<0, arglist...> c(matchers);\n\t\tc.CollectMatchers(matcherCreator...);\n\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(matchers);\n\t}\nprivate:\n\n\ttypename std::function<R(arglist&...)> getOriginalMethod() override {\n\t\treturn _impl->getOriginalMethod();\n\t}\n\n\tstd::shared_ptr<Implementation> _impl;\n};\n\ntemplate<typename R, typename ... arglist>\nclass MockingContext: \/\/\npublic virtual MethodMockingContext<R, arglist...> \/\/\n{\n\tMockingContext & operator=(const MockingContext&) = delete;\n\npublic:\n\n\tMockingContext(typename MethodMockingContext<R, arglist...>::Context* stubbingContext)\n\t\t\t: MethodMockingContext<R, arglist...>(stubbingContext) {\n\t}\n\n\tMockingContext(MockingContext<R, arglist...>&other)\n\t\t\t: MethodMockingContext<R, arglist...>(other) {\n\t}\n\tMockingContext(MockingContext<R, arglist...> &&other)\n\t\t\t: MethodMockingContext<R, arglist...>(other) {\n\t}\n\n\tvirtual ~MockingContext() THROWS {\n\t}\n\n\tMockingContext<R, arglist...>& setMethodDetails(std::string mockName, std::string methodName) {\n\t\tMethodMockingContext<R, arglist...>::setMethodDetails(mockName, methodName);\n\t\treturn *this;\n\t}\n\n\tMockingContext<R, arglist...>& Using(const arglist&... args) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(args...);\n\t\treturn *this;\n\t}\n\n\ttemplate<class ...matcherCreator>\n\tMockingContext<R, arglist...>& Using(const matcherCreator& ... matcherCreators) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(matcherCreators...);\n\t\treturn *this;\n\t}\n\n\tMockingContext<R, arglist...>& Matching(std::function<bool(arglist&...)> matcher) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(matcher);\n\t\treturn *this;\n\t}\n\n\tMockingContext<R, arglist...>& operator()(const arglist&... args) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(args...);\n\t\treturn *this;\n\t}\n\n\tMockingContext<R, arglist...>& operator()(std::function<bool(arglist&...)> matcher) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(matcher);\n\t\treturn *this;\n\t}\n\n\tvoid operator=(std::function<R(arglist&...)> method) {\n\t\tMethodMockingContext<R, arglist...>::setMethodBodyByAssignment(method);\n\t}\n\n\ttemplate<typename U = R>\n\ttypename std::enable_if<!std::is_reference<U>::value, void>::type operator=(const R& r) {\n\t\tauto method = [r](arglist&...) -> R {return r;};\n\t\tMethodMockingContext<R, arglist...>::setMethodBodyByAssignment(method);\n\t}\n\n\ttemplate<typename U = R>\n\ttypename std::enable_if<std::is_reference<U>::value, void>::type operator=(const R& r) {\n\t\tauto method = [&r](arglist&...) -> R {return r;};\n\t\tMethodMockingContext<R, arglist...>::setMethodBodyByAssignment(method);\n\t}\n};\n\ntemplate<typename ... arglist>\nclass MockingContext<void, arglist...> : \/\/\npublic virtual MethodMockingContext<void, arglist...> {\n\n\tMockingContext & operator=(const MockingContext&) = delete;\n\npublic:\n\tMockingContext(typename MethodMockingContext<void, arglist...>::Context* stubbingContext)\n\t\t\t: MethodMockingContext<void, arglist...>(stubbingContext) {\n\t}\n\n\tvirtual ~MockingContext() THROWS {\n\t}\n\n\tMockingContext(MockingContext<void, arglist...>& other)\n\t\t\t: MethodMockingContext<void, arglist...>(other) {\n\t}\n\tMockingContext(MockingContext<void, arglist...> && other)\n\t\t\t: MethodMockingContext<void, arglist...>(other) {\n\t}\n\n\tvoid operator=(std::function<void(arglist&...)> method) {\n\t\tMethodMockingContext<void, arglist...>::setMethodBodyByAssignment(method);\n\t}\n\n\tMockingContext<void, arglist...>& setMethodDetails(std::string mockName, std::string methodName) {\n\t\tMethodMockingContext<void, arglist...>::setMethodDetails(mockName, methodName);\n\t\treturn *this;\n\t}\n\n\tMockingContext<void, arglist...>& Using(const arglist&... args) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(args...);\n\t\treturn *this;\n\t}\n\n\ttemplate<class ...matcherCreator>\n\tMockingContext<void, arglist...>& Using(const matcherCreator& ... matcherCreators) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(matcherCreators...);\n\t\treturn *this;\n\t}\n\n\tMockingContext<void, arglist...>& Matching(std::function<bool(arglist&...)> matcher) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(matcher);\n\t\treturn *this;\n\t}\n\n\tMockingContext<void, arglist...>& operator()(const arglist&... args) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(args...);\n\t\treturn *this;\n\t}\n\n\tMockingContext<void, arglist...>& operator()(std::function<bool(arglist&...)> matcher) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(matcher);\n\t\treturn *this;\n\t}\n};\n\n}\n#endif\n<commit_msg>cleanup<commit_after>\/*\n * Copyright (c) 2014 Eran Pe'er.\n *\n * This program is made available under the terms of the MIT License.\n *\n * Created on Mar 10, 2014\n *\/\n\n#ifndef MethodMockingContext_h__\n#define MethodMockingContext_h__\n\n#include <functional>\n#include <type_traits>\n#include <tuple>\n#include <memory>\n#include <vector>\n#include <unordered_set>\n#include <set>\n#include <iosfwd>\n\n#include \"fakeit\/RecordedMethodBody.hpp\"\n#include \"fakeit\/StubbingProgress.hpp\"\n#include \"fakeit\/Sequence.hpp\"\n#include \"fakeit\/ActualInvocation.hpp\"\n#include \"fakeit\/EventHandler.hpp\"\n#include \"fakeit\/ActionSequence.hpp\"\n#include \"fakeit\/DomainObjects.hpp\"\n#include \"fakeit\/SpyingContext.hpp\"\n#include \"fakeit\/StubbingContext.hpp\"\n#include \"fakeit\/MatchersCollector.hpp\"\n#include \"mockutils\/type_utils.hpp\"\n\nnamespace fakeit {\n\/**\n * Build recorded sequence and the matching criteria.\n * For example, for the following line:\n * When(Method(mock,foo)).Return(1).Return(2_Times(2)).Throw(e1);\n * The matching criteria is: Any invocation of mock.foo\n * The recorded sequence is: {Return(1), Return(2), Return(2), Throw(e1)}\n *\/\ntemplate<typename R, typename ... arglist>\nclass MethodMockingContext: \/\/\npublic Sequence, \/\/ For use in Verify(sequence1,...)... phrases.\n\t\tpublic ActualInvocationsSource, \/\/ For use in Using(source1,souece2,...) and VerifyNoOtherInvocations(source1,souece2...) phrases.\n\t\tpublic virtual StubbingContext<R, arglist...>, \/\/ For use in Fake, Spy & When phrases\n\t\tpublic virtual SpyingContext<R, arglist...>, \/\/ For use in Fake, Spy & When phrases\n\t\tprivate Invocation::Matcher {\n\npublic:\n\n\tstruct Context: public Destructable {\n\n\t\tvirtual ~Context() = default;\n\n\t\t\/**\n\t\t * Return the original method. not the mock.\n\t\t *\/\n\t\tvirtual std::function<R(arglist&...)> getOriginalMethod() = 0;\n\n\t\tvirtual std::string getMethodName() = 0;\n\n\t\tvirtual void addMethodInvocationHandler(typename ActualInvocation<arglist...>::Matcher* matcher,\n\t\t\t\tMethodInvocationHandler<R, arglist...>* invocationHandler) = 0;\n\n\t\tvirtual void scanActualInvocations(const std::function<void(ActualInvocation<arglist...>&)>& scanner) = 0;\n\n\t\tvirtual void setMethodDetails(std::string mockName, std::string methodName) = 0;\n\n\t\tvirtual bool isOfMethod(Method& method) = 0;\n\n\t\tvirtual ActualInvocationsSource& getInvolvedMock() = 0;\n\t};\n\nprivate:\n\tclass Implementation {\n\n\t\tContext* _stubbingContext;\n\t\tActionSequence<R, arglist...>* _recordedActionSequence;\n\t\ttypename ActualInvocation<arglist...>::Matcher* _invocationMatcher;bool _commited;\n\n\t\tContext& getStubbingContext() const {\n\t\t\treturn *_stubbingContext;\n\t\t}\n\n\tpublic:\n\n\t\tImplementation(Context* stubbingContext)\n\t\t\t\t: _stubbingContext(stubbingContext), _recordedActionSequence(new ActionSequence<R, arglist...>()), _invocationMatcher {\n\t\t\t\t\t\tnew DefaultInvocationMatcher<arglist...>() }, _commited(false) {\n\t\t}\n\n\t\t~Implementation() {\n\t\t\tdelete _stubbingContext;\n\t\t\tif (!_commited) {\n\t\t\t\t\/\/ no commit. delete the created objects.\n\t\t\t\tdelete _recordedActionSequence;\n\t\t\t\tdelete _invocationMatcher;\n\t\t\t}\n\t\t}\n\n\t\tActionSequence<R, arglist...>& getRecordedActionSequence() {\n\t\t\treturn *_recordedActionSequence;\n\t\t}\n\n\t\tstd::string format() const {\n\t\t\tstd::string s = getStubbingContext().getMethodName();\n\t\t\ts += _invocationMatcher->format();\n\t\t\treturn s;\n\t\t}\n\n\t\tvoid getActualInvocations(std::unordered_set<Invocation*>& into) const {\n\t\t\tauto scanner = [&](ActualInvocation<arglist...>& a) {\n\t\t\t\tif (_invocationMatcher->matches(a)) {\n\t\t\t\t\tinto.insert(&a);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetStubbingContext().scanActualInvocations(scanner);\n\t\t}\n\n\t\t\/**\n\t\t * Used only by Verify phrase.\n\t\t *\/\n\t\tbool matches(Invocation& invocation) {\n\t\t\tMethod& actualMethod = invocation.getMethod();\n\t\t\tif (!getStubbingContext().isOfMethod(actualMethod)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tActualInvocation<arglist...>& actualInvocation = dynamic_cast<ActualInvocation<arglist...>&>(invocation);\n\t\t\treturn _invocationMatcher->matches(actualInvocation);\n\t\t}\n\n\t\tvoid commit() {\n\t\t\tgetStubbingContext().addMethodInvocationHandler(_invocationMatcher, _recordedActionSequence);\n\t\t\t_commited = true;\n\t\t}\n\n\t\tvoid appendAction(Action<R, arglist...>* action) {\n\t\t\tgetRecordedActionSequence().AppendDo(action);\n\t\t}\n\n\t\tvoid setMethodBodyByAssignment(std::function<R(arglist&...)> method) {\n\t\t\tappendAction(new RepeatForever<R, arglist...>(method));\n\t\t\tcommit();\n\t\t}\n\n\t\tvoid setMethodDetails(std::string mockName, std::string methodName) {\n\t\t\tgetStubbingContext().setMethodDetails(mockName, methodName);\n\t\t}\n\n\t\tvoid getInvolvedMocks(std::set<const ActualInvocationsSource*>& into) const {\n\t\t\tinto.insert(&getStubbingContext().getInvolvedMock());\n\t\t}\n\n\t\ttypename std::function<R(arglist&...)> getOriginalMethod() {\n\t\t\treturn getStubbingContext().getOriginalMethod();\n\t\t}\n\n\t\tvoid setInvocationMatcher(typename ActualInvocation<arglist...>::Matcher* matcher) {\n\t\t\tdelete _invocationMatcher;\n\t\t\t_invocationMatcher = matcher;\n\t\t}\n\t};\n\nprotected:\n\n\tMethodMockingContext(Context* stubbingContext)\n\t\t\t: _impl { new Implementation(stubbingContext) } {\n\t}\n\n\t\/\/Move ctor for use by derived classes.\n\tMethodMockingContext(MethodMockingContext& other)\n\t\t\t: _impl(other._impl) {\n\t}\n\n\tvirtual ~MethodMockingContext() {}\n\n\tstd::string format() const {\n\t\treturn _impl->format();\n\t}\n\n\tunsigned int size() const override {\n\t\treturn 1;\n\t}\n\n\t\/**\n\t * Used only by Verify phrase.\n\t *\/\n\tvoid getInvolvedMocks(std::set<const ActualInvocationsSource*>& into) const override {\n\t\t_impl->getInvolvedMocks(into);\n\t}\n\n\tvoid getExpectedSequence(std::vector<Invocation::Matcher*>& into) const override {\n\t\tconst Invocation::Matcher* b = this;\n\t\tInvocation::Matcher* c = const_cast<Invocation::Matcher*>(b);\n\t\tinto.push_back(c);\n\t}\n\n\t\/**\n\t * Used only by Verify phrase.\n\t *\/\n\tvoid getActualInvocations(std::unordered_set<Invocation*>& into) const override {\n\t\t_impl->getActualInvocations(into);\n\t}\n\n\t\/**\n\t * Used only by Verify phrase.\n\t *\/\n\tvirtual bool matches(Invocation& invocation) override {\n\t\treturn _impl->matches(invocation);\n\t}\n\n\tvirtual void commit() override {\n\t\t_impl->commit();\n\t}\n\n\tvoid setMethodDetails(std::string mockName, std::string methodName) {\n\t\t_impl->setMethodDetails(mockName, methodName);\n\t}\n\n\/\/\tvoid setMatchingCriteria(const arglist&... args) {\n\/\/\t\t_impl->setMatchingCriteria(args...);\n\/\/\t}\n\n\tvoid setMatchingCriteria(std::function<bool(arglist&...)> predicate) {\n\t\ttypename ActualInvocation<arglist...>::Matcher* matcher { new UserDefinedInvocationMatcher<arglist...>(predicate) };\n\t\t_impl->setInvocationMatcher(matcher);\n\t}\n\n\tvoid setMatchingCriteria(const std::vector<Destructable*>& matchers) {\n\t\ttypename ActualInvocation<arglist...>::Matcher* matcher { new ArgumentsMatcherInvocationMatcher<arglist...>(matchers) };\n\t\t_impl->setInvocationMatcher(matcher);\n\t}\n\n\t\/**\n\t * Used by Fake, Spy & When functors\n\t *\/\n\tvoid appendAction(Action<R, arglist...>* action) override {\n\t\t_impl->appendAction(action);\n\t}\n\n\tvoid setMethodBodyByAssignment(std::function<R(arglist&...)> method) {\n\t\t_impl->setMethodBodyByAssignment(method);\n\t}\n\n\ttemplate<class ...matcherCreators, class = typename std::enable_if<sizeof...(matcherCreators)==sizeof...(arglist)>::type>\n\tvoid setMatchingCriteria(const matcherCreators& ... matcherCreator) {\n\t\tstd::vector<Destructable*> matchers;\n\n\t\tMatchersCollector<0, arglist...> c(matchers);\n\t\tc.CollectMatchers(matcherCreator...);\n\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(matchers);\n\t}\nprivate:\n\n\ttypename std::function<R(arglist&...)> getOriginalMethod() override {\n\t\treturn _impl->getOriginalMethod();\n\t}\n\n\tstd::shared_ptr<Implementation> _impl;\n};\n\ntemplate<typename R, typename ... arglist>\nclass MockingContext: \/\/\npublic virtual MethodMockingContext<R, arglist...> \/\/\n{\n\tMockingContext & operator=(const MockingContext&) = delete;\n\npublic:\n\n\tMockingContext(typename MethodMockingContext<R, arglist...>::Context* stubbingContext)\n\t\t\t: MethodMockingContext<R, arglist...>(stubbingContext) {\n\t}\n\n\tMockingContext(MockingContext<R, arglist...>&other)\n\t\t\t: MethodMockingContext<R, arglist...>(other) {\n\t}\n\tMockingContext(MockingContext<R, arglist...> &&other)\n\t\t\t: MethodMockingContext<R, arglist...>(other) {\n\t}\n\n\tvirtual ~MockingContext() THROWS {\n\t}\n\n\tMockingContext<R, arglist...>& setMethodDetails(std::string mockName, std::string methodName) {\n\t\tMethodMockingContext<R, arglist...>::setMethodDetails(mockName, methodName);\n\t\treturn *this;\n\t}\n\n\tMockingContext<R, arglist...>& Using(const arglist&... args) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(args...);\n\t\treturn *this;\n\t}\n\n\ttemplate<class ...matcherCreator>\n\tMockingContext<R, arglist...>& Using(const matcherCreator& ... matcherCreators) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(matcherCreators...);\n\t\treturn *this;\n\t}\n\n\tMockingContext<R, arglist...>& Matching(std::function<bool(arglist&...)> matcher) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(matcher);\n\t\treturn *this;\n\t}\n\n\tMockingContext<R, arglist...>& operator()(const arglist&... args) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(args...);\n\t\treturn *this;\n\t}\n\n\tMockingContext<R, arglist...>& operator()(std::function<bool(arglist&...)> matcher) {\n\t\tMethodMockingContext<R, arglist...>::setMatchingCriteria(matcher);\n\t\treturn *this;\n\t}\n\n\tvoid operator=(std::function<R(arglist&...)> method) {\n\t\tMethodMockingContext<R, arglist...>::setMethodBodyByAssignment(method);\n\t}\n\n\ttemplate<typename U = R>\n\ttypename std::enable_if<!std::is_reference<U>::value, void>::type operator=(const R& r) {\n\t\tauto method = [r](arglist&...) -> R {return r;};\n\t\tMethodMockingContext<R, arglist...>::setMethodBodyByAssignment(method);\n\t}\n\n\ttemplate<typename U = R>\n\ttypename std::enable_if<std::is_reference<U>::value, void>::type operator=(const R& r) {\n\t\tauto method = [&r](arglist&...) -> R {return r;};\n\t\tMethodMockingContext<R, arglist...>::setMethodBodyByAssignment(method);\n\t}\n};\n\ntemplate<typename ... arglist>\nclass MockingContext<void, arglist...> : \/\/\npublic virtual MethodMockingContext<void, arglist...> {\n\n\tMockingContext & operator=(const MockingContext&) = delete;\n\npublic:\n\tMockingContext(typename MethodMockingContext<void, arglist...>::Context* stubbingContext)\n\t\t\t: MethodMockingContext<void, arglist...>(stubbingContext) {\n\t}\n\n\tvirtual ~MockingContext() THROWS {\n\t}\n\n\tMockingContext(MockingContext<void, arglist...>& other)\n\t\t\t: MethodMockingContext<void, arglist...>(other) {\n\t}\n\tMockingContext(MockingContext<void, arglist...> && other)\n\t\t\t: MethodMockingContext<void, arglist...>(other) {\n\t}\n\n\tvoid operator=(std::function<void(arglist&...)> method) {\n\t\tMethodMockingContext<void, arglist...>::setMethodBodyByAssignment(method);\n\t}\n\n\tMockingContext<void, arglist...>& setMethodDetails(std::string mockName, std::string methodName) {\n\t\tMethodMockingContext<void, arglist...>::setMethodDetails(mockName, methodName);\n\t\treturn *this;\n\t}\n\n\tMockingContext<void, arglist...>& Using(const arglist&... args) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(args...);\n\t\treturn *this;\n\t}\n\n\ttemplate<class ...matcherCreator>\n\tMockingContext<void, arglist...>& Using(const matcherCreator& ... matcherCreators) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(matcherCreators...);\n\t\treturn *this;\n\t}\n\n\tMockingContext<void, arglist...>& Matching(std::function<bool(arglist&...)> matcher) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(matcher);\n\t\treturn *this;\n\t}\n\n\tMockingContext<void, arglist...>& operator()(const arglist&... args) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(args...);\n\t\treturn *this;\n\t}\n\n\tMockingContext<void, arglist...>& operator()(std::function<bool(arglist&...)> matcher) {\n\t\tMethodMockingContext<void, arglist...>::setMatchingCriteria(matcher);\n\t\treturn *this;\n\t}\n};\n\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tNMEA デコード・クラス @n\r\n\t\t\tCopyright 2016 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <cstdint>\r\n#include <cstring>\r\n#include \"common\/time.h\"\r\n\r\nnamespace utils {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief NMEA デコード・クラス\r\n\t\t@param[in]\tSCI_IO\tシリアルI/O\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <class SCI_IO>\r\n\tclass nmea_dec {\r\n\r\n\tpublic:\r\n\r\n\t\tstatic const uint32_t sinfo_num_ = 12;\t\t\/\/\/< 衛星情報の最大数\r\n\r\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 衛星パラメーター\r\n\t\t*\/\r\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\tstruct sat_info {\r\n\t\t\tchar\tno_[4]; \t\/\/\/< 衛星番号\r\n\t\t\tchar\telv_[4];\t\/\/\/< 衛星仰角(Elevation)、0~90度\r\n\t\t\tchar\tazi_[4];\t\/\/\/< 衛星方位角(Azimuth)、0~359度\r\n\t\t\tchar\tcn_[4];\t\t\/\/\/< キャリア/ノイズ比、0~99dB\r\n\r\n\t\t\tsat_info() {\r\n\t\t\t\tno_[0] = 0;\r\n\t\t\t\telv_[0] = 0;\r\n\t\t\t\tazi_[0] = 0;\r\n\t\t\t\tcn_[0] = 0;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\tprivate:\r\n\t\tSCI_IO&\t\tsci_;\r\n\r\n\t\tuint16_t\tpos_;\r\n\t\tchar\t\tline_[128];\r\n\r\n\t\tchar\t\ttime_[12]; \/\/ 時間\r\n\t\tchar\t\tlat_[12]; \/\/ 緯度(latitude)\r\n\t\tchar\t\tns_[2]; \/\/ 北緯、南緯\r\n\t\tchar\t\tlon_[12]; \/\/ 経度(longitude)\r\n\t\tchar\t\tew_[2]; \/\/ 東経、西経\r\n\t\tchar\t\tq_[2]; \/\/ 品質\r\n\t\tchar\t\tsatellite_[4]; \/\/ 衛星数\r\n\t\tchar\t\thq_[4];\t\t\/\/ 水平精度低下率\r\n\t\tchar\t\talt_[6];\t\/\/ 海抜高度(Altitude above sea level)\r\n\t\tchar\t\talt_unit_[2];\t\/\/ 海抜高度単位\r\n\r\n\t\tchar\t\tdate_[8]; \/\/ 日付\r\n\r\n\t\tuint16_t\tsidx_;\r\n\t\tsat_info\tsinfo_[sinfo_num_];\t\/\/ 衛星情報\r\n\r\n\t\tuint32_t\tid_;\r\n\t\tuint32_t\tiid_;\r\n\r\n\t\tstatic uint16_t word_(const char* src)\r\n\t\t{\r\n\t\t\tconst char* top = src;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = *src++) != 0) {\r\n\t\t\t\tif(ch == ',' || ch == '*') return src - top;\r\n\t\t\t}\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tstatic void copy_word_(char* dst, const char* src, uint16_t len)\r\n\t\t{\r\n\t\t\tstd::strncpy(dst, src, len);\r\n\t\t\tdst[len] = 0;\r\n\t\t}\r\n\r\n\t\tstatic int32_t get_dec_(const char* t, uint16_t n = 0)\r\n\t\t{\r\n\t\t\tint32_t val = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = *t++) != 0) {\r\n\t\t\t\tif('0' <= ch && ch <= '9') {\r\n\t\t\t\t\tval *= 10;\r\n\t\t\t\t\tval += ch - '0';\r\n\t\t\t\t} else {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tif(n > 0) {\r\n\t\t\t\t\t--n;\r\n\t\t\t\t\tif(n == 0) break;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn val;\r\n\t\t}\r\n\r\n\t\tbool decode_()\r\n\t\t{\r\n\t\t\tif(line_[0] != '$') return false;\r\n\r\n\t\t\tif(std::strncmp(&line_[1], \"GPGGA,\", 6) == 0) {\r\n\t\t\t\tconst char* p = &line_[7];\r\n\t\t\t\tuint16_t n = 0;\r\n\t\t\t\tuint16_t l;\r\n\t\t\t\twhile((l = word_(p)) != 0) {\r\n\t\t\t\t\tif(n == 0) copy_word_(time_, p, l - 1);\r\n\t\t\t\t\telse if(n == 1) copy_word_(lat_, p, l - 1);\r\n\t\t\t\t\telse if(n == 2) copy_word_(ns_, p, l - 1);\r\n\t\t\t\t\telse if(n == 3) copy_word_(lon_, p, l - 1);\r\n\t\t\t\t\telse if(n == 4) copy_word_(ew_, p, l - 1);\r\n\t\t\t\t\telse if(n == 5) copy_word_(q_, p, l - 1);\r\n\t\t\t\t\telse if(n == 6) copy_word_(satellite_, p, l - 1);\r\n\t\t\t\t\telse if(n == 7) copy_word_(hq_, p, l - 1);\r\n\t\t\t\t\telse if(n == 8) copy_word_(alt_, p, l - 1);\r\n\t\t\t\t\telse if(n == 9) copy_word_(alt_unit_, p, l - 1);\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tp += l;\r\n\t\t\t\t\t++n;\r\n\t\t\t\t}\r\n\t\t\t} else if(std::strncmp(&line_[1], \"GPRMC,\", 6) == 0) {\r\n\t\t\t\tconst char* p = &line_[7];\r\n\t\t\t\tuint16_t n = 0;\r\n\t\t\t\tuint16_t l;\r\n\t\t\t\twhile((l = word_(p)) != 0) {\r\n\t\t\t\t\tif(n == 8) copy_word_(date_, p, l - 1);\r\n\t\t\t\t\tp += l;\r\n\t\t\t\t\t++n;\r\n\t\t\t\t}\r\n\t\t\t} else if(std::strncmp(&line_[1], \"GPGSV,\", 6) == 0) {\r\n\t\t\t\tconst char* p = &line_[7];\r\n\t\t\t\tuint16_t n = 0;\r\n\t\t\t\tuint16_t l;\r\n\t\t\t\twhile((l = word_(p)) != 0) {\r\n\t\t\t\t\tif(n == 0) ;\r\n\t\t\t\t\telse if(n == 1) ;\r\n\/\/ std::strncpy(date_, p, l - 1);\r\n\t\t\t\t\tp += l;\r\n\t\t\t\t\t++n;\r\n\t\t\t\t}\r\n\t\t\t\t++iid_;\r\n\t\t\t} else if(std::strncmp(&line_[1], \"GPVTG,\", 6) == 0) {\r\n\t\t\t\t++id_;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\tpublic:\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief コンストラクター\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tnmea_dec(SCI_IO& sci) : sci_(sci), pos_(0), sidx_(0), id_(0), iid_(0) {\r\n\t\t\tline_[0] = 0;\r\n\t\t\ttime_[0] = 0;\r\n\t\t\tlat_[0] = 0;\r\n\t\t\tns_[0] = 0;\r\n\t\t\tlon_[0] = 0;\r\n\t\t\tew_[0] = 0;\r\n\t\t\tq_[0] = 0;\r\n\t\t\tsatellite_[0] = 0;\r\n\t\t\thq_[0] = 0;\r\n\t\t\talt_[0] = 0;\r\n\t\t\talt_unit_[0] = 0;\r\n\r\n\t\t\tdate_[0] = 0;\r\n\t\t}\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 処理IDを取得\r\n\t\t\t@return 処理ID\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t get_id() const { return id_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 情報処理IDを取得\r\n\t\t\t@return 情報処理ID\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t get_iid() const { return iid_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 時間を取得\r\n\t\t\t@return 時間\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_time() const { return time_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 日付を取得\r\n\t\t\t@return 日付\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_date() const { return date_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 時間「time_t」を取得(グリニッチ時間)\r\n\t\t\t@return 時間「time_t」\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\ttime_t get_tm() const {\r\n\t\t\ttm ts;\r\n\t\t\tts.tm_sec = get_dec_(&time_[4], 2);\r\n\t\t\tts.tm_min = get_dec_(&time_[2], 2);\r\n\t\t\tts.tm_hour = get_dec_(&time_[0], 2);\r\n\t\t\tts.tm_mday = get_dec_(&date_[0], 2);\r\n\t\t\tts.tm_mon = get_dec_(&date_[2], 2);\r\n\t\t\tts.tm_year = get_dec_(&date_[4], 2);\r\n\t\t\tts.tm_year += 100; \/\/ 起点1900年\r\n\t\t\treturn mktime_gmt(&ts);\r\n\t\t}\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 緯度を取得\r\n\t\t\t@return 緯度\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_lat() const { return lat_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 経度を取得\r\n\t\t\t@return 経度\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_lon() const { return lon_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 品質を取得\r\n\t\t\t@return 品質\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_quality() const { return q_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 衛星数を取得\r\n\t\t\t@return 衛星数\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_satellite() const { return satellite_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 水平品質を取得\r\n\t\t\t@return 水平品質\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_holizontal_quality() const { return hq_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 海抜高度を取得\r\n\t\t\t@return 海抜高度\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_altitude() const { return alt_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 海抜高度単位を取得\r\n\t\t\t@return 海抜高度単位\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_altitude_unit() const { return alt_unit_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 衛星情報の取得\r\n\t\t\t@param[in]\tidx\t衛星インデックス\r\n\t\t\t@return 衛星情報\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst sat_info& get_satellite_info(uint16_t idx) const\r\n\t\t{\r\n\t\t\tif(idx < sinfo_num_) {\r\n\t\t\t\treturn sinfo_[idx];\r\n\t\t\t} else {\r\n\t\t\t\tstatic sat_info si;\r\n\t\t\t\treturn si;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief スタート\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid start()\r\n\t\t{\r\n\t\t}\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief サービス @n\r\n\t\t\t\t\t情報量に応じて呼ぶ(通常毎フレーム呼ぶ)\r\n\t\t\t@return 更新されたら「true」\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tbool service()\r\n\t\t{\r\n\t\t\tchar ch;\r\n\t\t\tbool ret = false;\r\n\t\t\twhile(sci_.recv_length() > 0) {\r\n\t\t\t\tch = sci_.getch();\r\n\t\t\t\tif(ch == 0x0d) {\r\n\t\t\t\t\tline_[pos_] = 0;\r\n\t\t\t\t\tret = decode_();\r\n\t\t\t\t\tpos_ = 0;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(ch >= ' ' && ch <= 0x7f) {\r\n\t\t\t\t\t\tif(pos_ < sizeof(line_)) {\r\n\t\t\t\t\t\t\tline_[pos_] = ch;\r\n\t\t\t\t\t\t\t++pos_;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n<commit_msg>fix time_t convert<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tNMEA デコード・クラス @n\r\n\t\t\tCopyright 2016 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <cstdint>\r\n#include <cstring>\r\n#include \"common\/time.h\"\r\n\r\nnamespace utils {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief NMEA デコード・クラス\r\n\t\t@param[in]\tSCI_IO\tシリアルI/O\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <class SCI_IO>\r\n\tclass nmea_dec {\r\n\r\n\tpublic:\r\n\r\n\t\tstatic const uint32_t sinfo_num_ = 12;\t\t\/\/\/< 衛星情報の最大数\r\n\r\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 衛星パラメーター\r\n\t\t*\/\r\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\tstruct sat_info {\r\n\t\t\tchar\tno_[4]; \t\/\/\/< 衛星番号\r\n\t\t\tchar\telv_[4];\t\/\/\/< 衛星仰角(Elevation)、0~90度\r\n\t\t\tchar\tazi_[4];\t\/\/\/< 衛星方位角(Azimuth)、0~359度\r\n\t\t\tchar\tcn_[4];\t\t\/\/\/< キャリア/ノイズ比、0~99dB\r\n\r\n\t\t\tsat_info() {\r\n\t\t\t\tno_[0] = 0;\r\n\t\t\t\telv_[0] = 0;\r\n\t\t\t\tazi_[0] = 0;\r\n\t\t\t\tcn_[0] = 0;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\tprivate:\r\n\t\tSCI_IO&\t\tsci_;\r\n\r\n\t\tuint16_t\tpos_;\r\n\t\tchar\t\tline_[128];\r\n\r\n\t\tchar\t\ttime_[12]; \/\/ 時間\r\n\t\tchar\t\tlat_[12]; \/\/ 緯度(latitude)\r\n\t\tchar\t\tns_[2]; \/\/ 北緯、南緯\r\n\t\tchar\t\tlon_[12]; \/\/ 経度(longitude)\r\n\t\tchar\t\tew_[2]; \/\/ 東経、西経\r\n\t\tchar\t\tq_[2]; \/\/ 品質\r\n\t\tchar\t\tsatellite_[4]; \/\/ 衛星数\r\n\t\tchar\t\thq_[4];\t\t\/\/ 水平精度低下率\r\n\t\tchar\t\talt_[6];\t\/\/ 海抜高度(Altitude above sea level)\r\n\t\tchar\t\talt_unit_[2];\t\/\/ 海抜高度単位\r\n\r\n\t\tchar\t\tdate_[8]; \/\/ 日付\r\n\r\n\t\tuint16_t\tsidx_;\r\n\t\tsat_info\tsinfo_[sinfo_num_];\t\/\/ 衛星情報\r\n\r\n\t\tuint32_t\tid_;\r\n\t\tuint32_t\tiid_;\r\n\r\n\t\tstatic uint16_t word_(const char* src)\r\n\t\t{\r\n\t\t\tconst char* top = src;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = *src++) != 0) {\r\n\t\t\t\tif(ch == ',' || ch == '*') return src - top;\r\n\t\t\t}\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tstatic void copy_word_(char* dst, const char* src, uint16_t len)\r\n\t\t{\r\n\t\t\tstd::strncpy(dst, src, len);\r\n\t\t\tdst[len] = 0;\r\n\t\t}\r\n\r\n\t\tstatic int32_t get_dec_(const char* t, uint16_t n = 0)\r\n\t\t{\r\n\t\t\tint32_t val = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = *t++) != 0) {\r\n\t\t\t\tif('0' <= ch && ch <= '9') {\r\n\t\t\t\t\tval *= 10;\r\n\t\t\t\t\tval += ch - '0';\r\n\t\t\t\t} else {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tif(n > 0) {\r\n\t\t\t\t\t--n;\r\n\t\t\t\t\tif(n == 0) break;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn val;\r\n\t\t}\r\n\r\n\t\tbool decode_()\r\n\t\t{\r\n\t\t\tif(line_[0] != '$') return false;\r\n\r\n\t\t\tif(std::strncmp(&line_[1], \"GPGGA,\", 6) == 0) {\r\n\t\t\t\tconst char* p = &line_[7];\r\n\t\t\t\tuint16_t n = 0;\r\n\t\t\t\tuint16_t l;\r\n\t\t\t\twhile((l = word_(p)) != 0) {\r\n\t\t\t\t\tif(n == 0) copy_word_(time_, p, l - 1);\r\n\t\t\t\t\telse if(n == 1) copy_word_(lat_, p, l - 1);\r\n\t\t\t\t\telse if(n == 2) copy_word_(ns_, p, l - 1);\r\n\t\t\t\t\telse if(n == 3) copy_word_(lon_, p, l - 1);\r\n\t\t\t\t\telse if(n == 4) copy_word_(ew_, p, l - 1);\r\n\t\t\t\t\telse if(n == 5) copy_word_(q_, p, l - 1);\r\n\t\t\t\t\telse if(n == 6) copy_word_(satellite_, p, l - 1);\r\n\t\t\t\t\telse if(n == 7) copy_word_(hq_, p, l - 1);\r\n\t\t\t\t\telse if(n == 8) copy_word_(alt_, p, l - 1);\r\n\t\t\t\t\telse if(n == 9) copy_word_(alt_unit_, p, l - 1);\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tp += l;\r\n\t\t\t\t\t++n;\r\n\t\t\t\t}\r\n\t\t\t} else if(std::strncmp(&line_[1], \"GPRMC,\", 6) == 0) {\r\n\t\t\t\tconst char* p = &line_[7];\r\n\t\t\t\tuint16_t n = 0;\r\n\t\t\t\tuint16_t l;\r\n\t\t\t\twhile((l = word_(p)) != 0) {\r\n\t\t\t\t\tif(n == 8) copy_word_(date_, p, l - 1);\r\n\t\t\t\t\tp += l;\r\n\t\t\t\t\t++n;\r\n\t\t\t\t}\r\n\t\t\t} else if(std::strncmp(&line_[1], \"GPGSV,\", 6) == 0) {\r\n\t\t\t\tconst char* p = &line_[7];\r\n\t\t\t\tuint16_t n = 0;\r\n\t\t\t\tuint16_t l;\r\n\t\t\t\twhile((l = word_(p)) != 0) {\r\n\t\t\t\t\tif(n == 0) ;\r\n\t\t\t\t\telse if(n == 1) ;\r\n\/\/ std::strncpy(date_, p, l - 1);\r\n\t\t\t\t\tp += l;\r\n\t\t\t\t\t++n;\r\n\t\t\t\t}\r\n\t\t\t\t++iid_;\r\n\t\t\t} else if(std::strncmp(&line_[1], \"GPVTG,\", 6) == 0) {\r\n\t\t\t\t++id_;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\tpublic:\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief コンストラクター\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tnmea_dec(SCI_IO& sci) : sci_(sci), pos_(0), sidx_(0), id_(0), iid_(0) {\r\n\t\t\tline_[0] = 0;\r\n\t\t\ttime_[0] = 0;\r\n\t\t\tlat_[0] = 0;\r\n\t\t\tns_[0] = 0;\r\n\t\t\tlon_[0] = 0;\r\n\t\t\tew_[0] = 0;\r\n\t\t\tq_[0] = 0;\r\n\t\t\tsatellite_[0] = 0;\r\n\t\t\thq_[0] = 0;\r\n\t\t\talt_[0] = 0;\r\n\t\t\talt_unit_[0] = 0;\r\n\r\n\t\t\tdate_[0] = 0;\r\n\t\t}\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 処理IDを取得\r\n\t\t\t@return 処理ID\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t get_id() const { return id_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 情報処理IDを取得\r\n\t\t\t@return 情報処理ID\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t get_iid() const { return iid_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 時間を取得\r\n\t\t\t@return 時間\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_time() const { return time_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 日付を取得\r\n\t\t\t@return 日付\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_date() const { return date_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 時間「time_t」を取得(グリニッチ時間)\r\n\t\t\t@return 時間「time_t」\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\ttime_t get_gmtime() const {\r\n\t\t\ttm ts;\r\n\t\t\tts.tm_sec = get_dec_(&time_[4], 2);\r\n\t\t\tts.tm_min = get_dec_(&time_[2], 2);\r\n\t\t\tts.tm_hour = get_dec_(&time_[0], 2);\r\n\t\t\tts.tm_mday = get_dec_(&date_[0], 2);\r\n\t\t\tts.tm_mon = get_dec_(&date_[2], 2) - 1;\r\n\t\t\tts.tm_year = get_dec_(&date_[4], 2);\r\n\t\t\tts.tm_year += 100; \/\/ 起点1900年\r\n\t\t\treturn mktime_gmt(&ts);\r\n\t\t}\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 緯度を取得\r\n\t\t\t@return 緯度\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_lat() const { return lat_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 経度を取得\r\n\t\t\t@return 経度\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_lon() const { return lon_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 品質を取得\r\n\t\t\t@return 品質\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_quality() const { return q_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 衛星数を取得\r\n\t\t\t@return 衛星数\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_satellite() const { return satellite_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 水平品質を取得\r\n\t\t\t@return 水平品質\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_holizontal_quality() const { return hq_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 海抜高度を取得\r\n\t\t\t@return 海抜高度\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_altitude() const { return alt_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 海抜高度単位を取得\r\n\t\t\t@return 海抜高度単位\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* get_altitude_unit() const { return alt_unit_; }\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief 衛星情報の取得\r\n\t\t\t@param[in]\tidx\t衛星インデックス\r\n\t\t\t@return 衛星情報\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tconst sat_info& get_satellite_info(uint16_t idx) const\r\n\t\t{\r\n\t\t\tif(idx < sinfo_num_) {\r\n\t\t\t\treturn sinfo_[idx];\r\n\t\t\t} else {\r\n\t\t\t\tstatic sat_info si;\r\n\t\t\t\treturn si;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief スタート\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid start()\r\n\t\t{\r\n\t\t}\r\n\r\n\r\n \/\/-----------------------------------------------------------------\/\/\r\n \/*!\r\n @brief サービス @n\r\n\t\t\t\t\t情報量に応じて呼ぶ(通常毎フレーム呼ぶ)\r\n\t\t\t@return 更新されたら「true」\r\n *\/\r\n \/\/-----------------------------------------------------------------\/\/\r\n\t\tbool service()\r\n\t\t{\r\n\t\t\tchar ch;\r\n\t\t\tbool ret = false;\r\n\t\t\twhile(sci_.recv_length() > 0) {\r\n\t\t\t\tch = sci_.getch();\r\n\t\t\t\tif(ch == 0x0d) {\r\n\t\t\t\t\tline_[pos_] = 0;\r\n\t\t\t\t\tret = decode_();\r\n\t\t\t\t\tpos_ = 0;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(ch >= ' ' && ch <= 0x7f) {\r\n\t\t\t\t\t\tif(pos_ < sizeof(line_)) {\r\n\t\t\t\t\t\t\tline_[pos_] = ch;\r\n\t\t\t\t\t\t\t++pos_;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ basic_iostream.hpp\n\/\/ fibio\n\/\/\n\/\/ Created by Chen Xu on 14-3-8.\n\/\/ Copyright (c) 2014 0d0a.com. All rights reserved.\n\/\/\n\n#ifndef fibio_basic_iostream_hpp\n#define fibio_basic_iostream_hpp\n\n#include <streambuf>\n#include <iostream>\n#include <chrono>\n#include <fibio\/fibers\/fiber.hpp>\n\nnamespace fibio { namespace stream {\n constexpr size_t bf_size=4096;\n constexpr std::streamsize pb_size=4;\n \n template<typename StreamDescriptor>\n class streambuf : public std::streambuf {\n public:\n streambuf()\n : sd_(fibio::fibers::this_fiber::detail::get_io_service())\n {\n memset(buffer_in_, 0, bf_size);\n memset(buffer_out_, 0, bf_size);\n setg(buffer_in_ + pb_size,\n buffer_in_ + pb_size,\n buffer_in_ + pb_size);\n setp(buffer_out_,\n buffer_out_ + bf_size - 1 );\n }\n \n streambuf(asio::io_service &iosvc)\n : sd_(iosvc)\n {\n memset(buffer_in_, 0, bf_size);\n memset(buffer_out_, 0, bf_size);\n setg(buffer_in_ + pb_size,\n buffer_in_ + pb_size,\n buffer_in_ + pb_size);\n setp(buffer_out_,\n buffer_out_ + bf_size - 1 );\n }\n \n \/**\n * Constructor\n *\n * @param sd underlying stream device, such as socket or pipe\n *\/\n streambuf(StreamDescriptor &&sd)\n : sd_(std::move(sd))\n {\n memset(buffer_in_, 0, bf_size);\n memset(buffer_out_, 0, bf_size);\n setg(buffer_in_ + pb_size,\n buffer_in_ + pb_size,\n buffer_in_ + pb_size);\n setp(buffer_out_,\n buffer_out_ + bf_size - 1 );\n }\n \n \/\/ Movable\n streambuf(streambuf &&src)\n : sd_(std::move(src.sd_))\n {\n memcpy(buffer_in_, src.buffer_in_, bf_size);\n memcpy(buffer_out_, src.buffer_out_, bf_size);\n }\n \n \/\/ Non-copyable\n streambuf(const streambuf&) = delete;\n streambuf& operator=(const streambuf&) = delete;\n \n ~streambuf()\n { close(); }\n \n template <typename... T>\n std::error_code open(T... x) {\n return fibio::io::open(sd_, x...);\n }\n\n template <typename... T>\n std::error_code connect(T... x) {\n sd_.close();\n typename StreamDescriptor::protocol_type::resolver::query q(x...);\n typename StreamDescriptor::protocol_type::endpoint ep=fibio::io::resolve(q);\n typedef typename StreamDescriptor::protocol_type::endpoint endpoint_t;\n return fibio::io::connect(sd_, ep, endpoint_t(), connect_timeout_);\n }\n \n inline bool is_open() const\n { return sd_.is_open(); }\n \n inline void close() {\n if(sd_.is_open()) {\n std::error_code ec;\n sd_.close(ec);\n }\n }\n \n typename StreamDescriptor::native_handle_type release()\n { return sd_.release(); }\n \n inline StreamDescriptor &stream_descriptor()\n { return sd_; }\n \n template<typename Rep, typename Period>\n void set_connect_timeout(const std::chrono::duration<Rep, Period>& timeout_duration)\n { connect_timeout_=std::chrono::duration_cast<std::chrono::microseconds>(timeout_duration).count(); }\n \n template<typename Rep, typename Period>\n void set_read_timeout(const std::chrono::duration<Rep, Period>& timeout_duration)\n { read_timeout_=std::chrono::duration_cast<std::chrono::microseconds>(timeout_duration).count(); }\n \n template<typename Rep, typename Period>\n void set_write_timeout(const std::chrono::duration<Rep, Period>& timeout_duration)\n { write_timeout_=std::chrono::duration_cast<std::chrono::microseconds>(timeout_duration).count(); }\n \n protected:\n virtual int_type overflow(int_type c) override {\n if (unbuffered_) {\n if (traits_type::eq_int_type(c, traits_type::eof())) {\n \/\/ Nothing to do.\n return traits_type::not_eof(c);\n }\n std::error_code ec;\n async_write_char_with_timeout(c, ec);\n if(ec)\n return traits_type::eof();\n return c;\n } else {\n if ( c != traits_type::eof() ) {\n *pptr() = c;\n pbump(1);\n if (nudge_())\n return c;\n } else {\n c = 0;\n }\n \n return traits_type::eof();\n }\n }\n \n virtual int_type underflow() override {\n if ( gptr() < egptr() )\n return traits_type::to_int_type( *gptr() );\n \n if ( 0 > fetch_() )\n return traits_type::eof();\n else\n return traits_type::to_int_type( *gptr() );\n }\n \n virtual int sync() override\n { return nudge_()==0 ? 0 : -1; }\n \n virtual std::streamsize showmanyc() override {\n if ( gptr() == egptr() ) {\n \/\/ Getting area is empty\n return fetch_();\n }\n return egptr()-gptr();\n }\n \n virtual std::streambuf* setbuf(char_type* s, std::streamsize n) override {\n if (pptr() == pbase() && s == 0 && n == 0) {\n \/\/ Turn off output buffering\n unbuffered_ = true;\n setp(0, 0);\n return this;\n }\n return 0;\n }\n \n private:\n void async_write_char_with_timeout(char c, std::error_code &ec) {\n fibio::io::write_some(sd_, &c, 1, write_timeout_, ec);\n }\n \n size_t async_read_some_with_timeout(std::error_code &ec) {\n return fibio::io::read_some(sd_,\n buffer_in_ + pb_size,\n bf_size - pb_size,\n read_timeout_,\n ec);\n }\n \n void async_write_with_timeout(std::error_code &ec) {\n char *ptr=pbase();\n size_t size=pptr()-pbase();\n while(size>0) {\n size_t bytes_transferred=fibio::io::write_some(sd_,\n ptr,\n size,\n write_timeout_,\n ec);\n ptr+=bytes_transferred;\n size-=bytes_transferred;\n }\n }\n \n int_type fetch_() {\n std::streamsize num = std::min(static_cast<std::streamsize>(gptr() - eback()),\n pb_size);\n \n std::memmove(buffer_in_ + (pb_size - num),\n gptr() - num,\n num);\n \n std::error_code ec;\n std::size_t n = async_read_some_with_timeout(ec);\n if (ec) {\n setg(0, 0, 0);\n return -1;\n }\n setg(buffer_in_ + pb_size - num,\n buffer_in_ + pb_size,\n buffer_in_ + pb_size + n);\n return n;\n }\n \n int_type nudge_() {\n \/\/ Don't flush empty buffer\n if(pptr()<=pbase()) return 0;\n std::error_code ec;\n async_write_with_timeout(ec);\n setp(buffer_out_,\n buffer_out_ + bf_size - 1);\n return ec ? traits_type::eof() : 0;\n }\n \n StreamDescriptor sd_;\n char buffer_in_[bf_size];\n char buffer_out_[bf_size];\n int connect_timeout_=0;\n int read_timeout_=0;\n int write_timeout_=0;\n bool unbuffered_=false;\n };\n \n template<typename StreamDescriptor>\n struct iostream_base {\n typedef streambuf<StreamDescriptor> streambuf_t;\n \n iostream_base()=default;\n \n iostream_base(StreamDescriptor &&s)\n : sbuf_(std::move(s))\n {}\n \n iostream_base(iostream_base<StreamDescriptor> &&other)\n : sbuf_(std::move(other.sbuf_))\n {}\n \n streambuf_t sbuf_;\n };\n \n template<typename StreamDescriptor>\n class basic_iostream : private iostream_base<StreamDescriptor>, public std::iostream {\n public:\n typedef streambuf<StreamDescriptor> streambuf_t;\n typedef iostream_base<StreamDescriptor> streambase_t;\n \n basic_iostream()\n : streambase_t()\n , std::iostream(&(this->sbuf_))\n {}\n \n \/**\n * Constructor\n *\n * @param s underlying stream device, such as socket or pipe\n *\/\n basic_iostream(StreamDescriptor &&s)\n : streambase_t(std::move(s))\n , std::iostream(&(this->sbuf_))\n {}\n \n \/\/ Non-movable\n basic_iostream(basic_iostream &&src)=delete;\n \n \/\/ Non-copyable\n basic_iostream(const basic_iostream&) = delete;\n basic_iostream& operator=(const basic_iostream&) = delete;\n \n template <typename... T>\n std::error_code open(T... x) {\n return this->sbuf_.open(x...);\n }\n \n template <typename... T>\n std::error_code connect(T... x) {\n return this->sbuf_.connect(x...);\n }\n \n \/**\n * Close underlying stream device, flushing if necessary\n *\/\n inline void close() {\n if(streambuf().is_open()) {\n flush();\n }\n streambuf().close();\n }\n \n inline bool is_open() const\n { return this->sbuf_.is_open(); }\n \n inline streambuf_t &streambuf()\n { return this->sbuf_; }\n \n inline const streambuf_t &streambuf() const\n { return this->sbuf_; }\n \n inline StreamDescriptor &stream_descriptor()\n { return streambuf().stream_descriptor(); }\n \n template<typename Rep, typename Period>\n void set_connect_timeout(const std::chrono::duration<Rep, Period>& timeout_duration)\n { this->sbuf_.set_connect_timeout(timeout_duration); }\n \n template<typename Rep, typename Period>\n void set_read_timeout(const std::chrono::duration<Rep, Period>& timeout_duration)\n { this->sbuf_.set_read_timeout(timeout_duration); }\n \n template<typename Rep, typename Period>\n void set_write_timeout(const std::chrono::duration<Rep, Period>& timeout_duration)\n { this->sbuf_.set_write_timeout(timeout_duration); }\n \n };\n}} \/\/ End of namespace fibio::stream\n\n#endif\n<commit_msg>remove unused file<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef __ABSTRACT_DOMAINS_HH__\n#define __ABSTRACT_DOMAINS_HH__\n\n#include \"crab_llvm\/crab_cfg.hh\"\n\n#include \"crab\/domains\/linear_constraints.hpp\" \n#include \"crab\/domains\/intervals.hpp\" \n#include \"crab\/domains\/dis_intervals.hpp\" \n#include \"crab\/domains\/sparse_dbm.hpp\"\n#include \"crab\/domains\/split_dbm.hpp\"\n#include \"crab\/domains\/boxes.hpp\"\n#include \"crab\/domains\/apron_domains.hpp\"\n\/\/#include \"crab\/domains\/array_sparse_graph.hpp\"\n#include \"crab\/domains\/array_smashing.hpp\"\n#include \"crab\/domains\/term_equiv.hpp\"\n\/\/#include \"crab\/domains\/nullity.hpp\"\n#include \"crab\/domains\/flat_boolean_domain.hpp\"\n#include \"crab\/domains\/combined_domains.hpp\"\n\n\/*\n Definition of the abstract domains (no instantiation done here)\n*\/\n\nnamespace crab_llvm {\n\n using namespace crab::domains;\n using namespace ikos;\n\n \/\/\/ --- Types for linear constraints and expressions\n typedef ikos::linear_expression<z_number, varname_t> z_lin_exp_t;\n typedef ikos::linear_constraint<z_number, varname_t> z_lin_cst_t;\n typedef ikos::linear_constraint_system<z_number, varname_t> z_lin_cst_sys_t;\n\n \/* BEGIN MACROS only for internal use *\/\n \/\/ The base numerical domain \n #define BASE(DOM) base_ ## DOM\n \/\/ Array functor domain where the base domain is a reduced product\n \/\/ of a boolean domain with the numerical domain DOM.\n #define ARRAY_BOOL_NUM(DOM) \\\n typedef array_smashing<flat_boolean_numerical_domain<BASE(DOM)> > DOM\n \/\/ Array functor domain where the base domain is DOM\n #define ARRAY_NUM(DOM) \\\n typedef array_smashing<BASE(DOM)> DOM;\n \/* END MACROS only for internal use *\/\n \n \/\/\/\/\/\/\n \/\/ Base domains\n \/\/\/\/\/\/\n \n \/\/\/ -- Intervals\n #if 1\n typedef interval_domain<z_number, varname_t> BASE(interval_domain_t);\n #else\n \/\/ -- enable apron version for more precise backward operations\n typedef apron_domain<z_number, varname_t, apron_domain_id_t::APRON_INT>\n BASE(interval_domain_t);\n #endif \n \/\/\/ -- Zones using sparse DBMs (SAS'16)\n typedef SpDBM_impl::DefaultParams<z_number> SparseDBMGraph;\n typedef SparseDBM<z_number, varname_t, SparseDBMGraph> BASE(dbm_domain_t);\n \/\/\/ -- Zones using sparse DBMs in split normal form (SAS'16)\n typedef SDBM_impl::DefaultParams<z_number> SplitDBMGraph;\n typedef SplitDBM<z_number, varname_t, SplitDBMGraph> BASE(split_dbm_domain_t);\n \/\/\/ -- Boxes\n typedef boxes_domain<z_number, varname_t> BASE(boxes_domain_t);\n \/\/\/ -- DisIntervals\n typedef dis_interval_domain <z_number, varname_t> BASE(dis_interval_domain_t);\n \/\/\/ -- Elina\/Apron domains\n typedef apron_domain<z_number, varname_t, apron_domain_id_t::APRON_OPT_OCT>\n BASE(opt_oct_apron_domain_t);\n typedef apron_domain<z_number, varname_t, apron_domain_id_t::APRON_PK>\n BASE(pk_apron_domain_t);\n \/\/\/ -- Reduced product of intervals with congruences\n typedef numerical_congruence_domain<BASE(interval_domain_t)> BASE(ric_domain_t);\n \/\/\/ -- Term functor domain with Intervals (VMCAI'16)\n typedef crab::cfg::var_factory_impl::str_var_alloc_col::varname_t str_varname_t;\n typedef interval_domain<z_number, str_varname_t> str_interval_dom_t;\n typedef term::TDomInfo<z_number, varname_t, str_interval_dom_t> idom_info;\n typedef term_domain<idom_info> BASE(term_int_domain_t);\n \/\/\/ -- Term functor domain with DisIntervals (VMCAI'16)\n typedef dis_interval_domain<z_number, str_varname_t> str_dis_interval_dom_t;\n typedef term::TDomInfo<z_number, varname_t, str_dis_interval_dom_t> dis_idom_info;\n typedef term_domain<dis_idom_info> BASE(term_dis_int_domain_t);\n \/\/\/ -- Reduced product of Term(DisIntervals) with split zones\n typedef reduced_numerical_domain_product2<BASE(term_dis_int_domain_t),\n\t\t\t\t\t BASE(split_dbm_domain_t)> BASE(num_domain_t);\n\n ARRAY_BOOL_NUM(interval_domain_t);\n ARRAY_BOOL_NUM(dbm_domain_t);\n ARRAY_BOOL_NUM(split_dbm_domain_t);\n ARRAY_BOOL_NUM(dis_interval_domain_t);\n ARRAY_BOOL_NUM(opt_oct_apron_domain_t);\n ARRAY_BOOL_NUM(pk_apron_domain_t);\n ARRAY_BOOL_NUM(ric_domain_t);\n ARRAY_BOOL_NUM(term_int_domain_t); \n ARRAY_BOOL_NUM(term_dis_int_domain_t); \n ARRAY_BOOL_NUM(num_domain_t);\n \/\/ Boxes can reason natively about booleans so that's why we don't\n \/\/ combine it with a boolean domain.\n ARRAY_NUM(boxes_domain_t);\n \n} \/\/ end namespace crab-llvm\n\n#endif\n<commit_msg>Domain used only for debugging<commit_after>#ifndef __ABSTRACT_DOMAINS_HH__\n#define __ABSTRACT_DOMAINS_HH__\n\n#include \"crab_llvm\/crab_cfg.hh\"\n\n#include \"crab\/domains\/linear_constraints.hpp\" \n#include \"crab\/domains\/intervals.hpp\" \n#include \"crab\/domains\/dis_intervals.hpp\" \n#include \"crab\/domains\/sparse_dbm.hpp\"\n#include \"crab\/domains\/split_dbm.hpp\"\n#include \"crab\/domains\/boxes.hpp\"\n#include \"crab\/domains\/apron_domains.hpp\"\n\/\/#include \"crab\/domains\/array_sparse_graph.hpp\"\n#include \"crab\/domains\/array_smashing.hpp\"\n#include \"crab\/domains\/term_equiv.hpp\"\n\/\/#include \"crab\/domains\/nullity.hpp\"\n#include \"crab\/domains\/flat_boolean_domain.hpp\"\n#include \"crab\/domains\/combined_domains.hpp\"\n\/\/#include \"crab\/domains\/diff_domain.hpp\" \/* only debugging *\/\n\n\/*\n Definition of the abstract domains (no instantiation done here)\n*\/\n\nnamespace crab_llvm {\n\n using namespace crab::domains;\n using namespace ikos;\n\n \/\/\/ --- Types for linear constraints and expressions\n typedef ikos::linear_expression<z_number, varname_t> z_lin_exp_t;\n typedef ikos::linear_constraint<z_number, varname_t> z_lin_cst_t;\n typedef ikos::linear_constraint_system<z_number, varname_t> z_lin_cst_sys_t;\n\n \/* BEGIN MACROS only for internal use *\/\n \/\/ The base numerical domain \n #define BASE(DOM) base_ ## DOM\n \/\/ Array functor domain where the base domain is a reduced product\n \/\/ of a boolean domain with the numerical domain DOM.\n #define ARRAY_BOOL_NUM(DOM) \\\n typedef array_smashing<flat_boolean_numerical_domain<BASE(DOM)> > DOM\n \/\/ Array functor domain where the base domain is DOM\n #define ARRAY_NUM(DOM) \\\n typedef array_smashing<BASE(DOM)> DOM;\n \/* END MACROS only for internal use *\/\n \n \/\/\/\/\/\/\n \/\/ Base domains\n \/\/\/\/\/\/\n \n \/\/\/ -- Intervals\n #if 1\n typedef interval_domain<z_number, varname_t> BASE(interval_domain_t);\n #else\n \/\/ -- enable apron version for more precise backward operations\n typedef apron_domain<z_number, varname_t, apron_domain_id_t::APRON_INT>\n BASE(interval_domain_t);\n #endif \n \/\/\/ -- Zones using sparse DBMs (SAS'16)\n typedef SpDBM_impl::DefaultParams<z_number> SparseDBMGraph;\n typedef SparseDBM<z_number, varname_t, SparseDBMGraph> BASE(dbm_domain_t);\n \/\/\/ -- Zones using sparse DBMs in split normal form (SAS'16)\n typedef SDBM_impl::DefaultParams<z_number> SplitDBMGraph;\n typedef SplitDBM<z_number, varname_t, SplitDBMGraph> BASE(split_dbm_domain_t);\n \/\/\/ -- Boxes\n typedef boxes_domain<z_number, varname_t> BASE(boxes_domain_t);\n \/\/ typedef diff_domain<flat_boolean_numerical_domain<BASE(interval_domain_t)>,\n \/\/ \t\t boxes_domain<z_number, varname_t> > BASE(boxes_domain_t);\n \/\/\/ -- DisIntervals\n typedef dis_interval_domain <z_number, varname_t> BASE(dis_interval_domain_t);\n \/\/\/ -- Elina\/Apron domains\n typedef apron_domain<z_number, varname_t, apron_domain_id_t::APRON_OPT_OCT>\n BASE(opt_oct_apron_domain_t);\n typedef apron_domain<z_number, varname_t, apron_domain_id_t::APRON_PK>\n BASE(pk_apron_domain_t);\n \/\/\/ -- Reduced product of intervals with congruences\n typedef numerical_congruence_domain<BASE(interval_domain_t)> BASE(ric_domain_t);\n \/\/\/ -- Term functor domain with Intervals (VMCAI'16)\n typedef crab::cfg::var_factory_impl::str_var_alloc_col::varname_t str_varname_t;\n typedef interval_domain<z_number, str_varname_t> str_interval_dom_t;\n typedef term::TDomInfo<z_number, varname_t, str_interval_dom_t> idom_info;\n typedef term_domain<idom_info> BASE(term_int_domain_t);\n \/\/\/ -- Term functor domain with DisIntervals (VMCAI'16)\n typedef dis_interval_domain<z_number, str_varname_t> str_dis_interval_dom_t;\n typedef term::TDomInfo<z_number, varname_t, str_dis_interval_dom_t> dis_idom_info;\n typedef term_domain<dis_idom_info> BASE(term_dis_int_domain_t);\n \/\/\/ -- Reduced product of Term(DisIntervals) with split zones\n typedef reduced_numerical_domain_product2<BASE(term_dis_int_domain_t),\n\t\t\t\t\t BASE(split_dbm_domain_t)> BASE(num_domain_t);\n\n ARRAY_BOOL_NUM(interval_domain_t);\n ARRAY_BOOL_NUM(dbm_domain_t);\n ARRAY_BOOL_NUM(split_dbm_domain_t);\n ARRAY_BOOL_NUM(dis_interval_domain_t);\n ARRAY_BOOL_NUM(opt_oct_apron_domain_t);\n ARRAY_BOOL_NUM(pk_apron_domain_t);\n ARRAY_BOOL_NUM(ric_domain_t);\n ARRAY_BOOL_NUM(term_int_domain_t); \n ARRAY_BOOL_NUM(term_dis_int_domain_t); \n ARRAY_BOOL_NUM(num_domain_t);\n \/\/ Boxes can reason natively about booleans so that's why we don't\n \/\/ combine it with a boolean domain.\n ARRAY_NUM(boxes_domain_t);\n \n} \/\/ end namespace crab-llvm\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include \"astutil.h\"\n#include \"bb.h\"\n#include \"bitVec.h\"\n#include \"expr.h\"\n#include \"stmt.h\"\n#include \"view.h\"\n\nBasicBlock::BasicBlock()\n : id(nextid++) {}\n\n#define BB_START() \\\n basicBlock = new BasicBlock()\n\n\/\/ The assert tests that the expression we are adding to this basic block\n\/\/ has not already been deleted.\n#define BB_ADD(expr) \\\n do { \\\n INT_ASSERT(expr); \\\n basicBlock->exprs.add(expr); \\\n } while (0)\n\n#define BB_STOP() \\\n fn->basicBlocks->add(Steal())\n\n#define BB_RESTART() \\\n do { \\\n BB_STOP(); \\\n BB_START(); \\\n } while (0)\n\n#define BBB(stmt) \\\n buildBasicBlocks(fn, stmt)\n\n#define BB_THREAD(src, dst) \\\n do { \\\n dst->ins.add(src); \\\n src->outs.add(dst); \\\n } while (0)\n\n\n\/\/# Statics\nBasicBlock* BasicBlock::basicBlock;\nMap<LabelSymbol*,Vec<BasicBlock*>*> BasicBlock::gotoMaps;\nMap<LabelSymbol*,BasicBlock*> BasicBlock::labelMaps;\nint BasicBlock::nextid;\n\n\n\/\/ Returns true if the class invariants have been preserved.\nbool BasicBlock::isOK()\n{\n \/\/ Right now we just test that all entries are valid.\n forv_Vec(Expr, expr, exprs)\n if (expr == 0) return false;\n return true;\n}\n\n\/\/ Reset the shared statics.\nvoid BasicBlock::reset(FnSymbol* fn)\n{\n if (fn->basicBlocks)\n {\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n delete bb;\n delete fn->basicBlocks;\n }\n fn->basicBlocks = new Vec<BasicBlock*>();\n gotoMaps.clear();\n labelMaps.clear();\n nextid = 0;\n}\n\nBasicBlock* BasicBlock::Steal()\n{\n BasicBlock* temp = basicBlock;\n basicBlock = 0;\n return temp;\n}\n\n\/\/ This is the top-level (public) builder function.\nvoid buildBasicBlocks(FnSymbol* fn)\n{\n BasicBlock::reset(fn);\n BasicBlock::basicBlock = new BasicBlock();\n BasicBlock::buildBasicBlocks(fn, fn->body);\n fn->basicBlocks->add(BasicBlock::Steal());\n}\n\nvoid BasicBlock::buildBasicBlocks(FnSymbol* fn, Expr* stmt)\n{\n if (!stmt) return;\n\n if (BlockStmt* s = toBlockStmt(stmt))\n {\n \/\/ If a loop statement.\n if (s->blockInfo)\n {\n BasicBlock* top = basicBlock;\n BB_RESTART();\n \/\/ Assumes that blockInfo is never null.\n BB_ADD(s->blockInfo);\n BasicBlock* loopTop = basicBlock;\n for_alist(stmt, s->body) {\n BBB(stmt);\n }\n BasicBlock* loopBottom = basicBlock;\n BB_RESTART();\n BasicBlock* bottom = basicBlock;\n BB_THREAD(top, loopTop);\n BB_THREAD(loopBottom, bottom);\n BB_THREAD(loopBottom, loopTop);\n BB_THREAD(top, bottom);\n }\n else\n {\n for_alist(stmt, s->body)\n BBB(stmt);\n }\n }\n else if (CondStmt* s = toCondStmt(stmt))\n {\n INT_ASSERT(s->condExpr);\n BB_ADD(s->condExpr);\n BasicBlock* top = basicBlock;\n BB_RESTART();\n BB_THREAD(top, basicBlock);\n BBB(s->thenStmt);\n BasicBlock* thenBottom = basicBlock;\n BB_RESTART();\n if (s->elseStmt)\n {\n BB_THREAD(top, basicBlock);\n BBB(s->elseStmt);\n BasicBlock* elseBottom = basicBlock;\n BB_RESTART();\n BB_THREAD(elseBottom, basicBlock);\n }\n else\n {\n BB_THREAD(top, basicBlock);\n }\n BB_THREAD(thenBottom, basicBlock);\n } else if (GotoStmt* s = toGotoStmt(stmt)) {\n LabelSymbol* label = toLabelSymbol(toSymExpr(s->label)->var);\n if (BasicBlock* bb = labelMaps.get(label)) {\n BB_THREAD(basicBlock, bb);\n } else {\n Vec<BasicBlock*>* vbb = gotoMaps.get(label);\n if (!vbb)\n vbb = new Vec<BasicBlock*>();\n vbb->add(basicBlock);\n gotoMaps.put(label, vbb);\n }\n BB_ADD(s); \/\/ Put the goto at the end of its block.\n BB_RESTART();\n } else {\n DefExpr* def = toDefExpr(stmt);\n if (def && toLabelSymbol(def->sym)) {\n \/\/ If a label appears in the middle of a block,\n \/\/ we start a new block.\n if (basicBlock->exprs.count() > 0)\n {\n BasicBlock* top = basicBlock;\n BB_RESTART();\n BB_THREAD(top, basicBlock);\n }\n BB_ADD(def); \/\/ Put the label def at the start of its block.\n\n \/\/ OK, this statement is a label def, so get the label.\n LabelSymbol* label = toLabelSymbol(def->sym);\n\n \/\/ See if we have any unresolved references to this label,\n \/\/ and resolve them.\n if (Vec<BasicBlock*>* vbb = gotoMaps.get(label)) {\n forv_Vec(BasicBlock, bb, *vbb) {\n BB_THREAD(bb, basicBlock);\n }\n }\n labelMaps.put(label, basicBlock);\n } else {\n BB_ADD(stmt);\n }\n }\n}\n\n\/\/ Returns true if the basic block structure is OK, false otherwise.\nbool verifyBasicBlocks(FnSymbol* fn)\n{\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n {\n if (! bb->isOK())\n return false;\n }\n return true;\n}\n\nvoid buildLocalsVectorMap(FnSymbol* fn,\n Vec<Symbol*>& locals,\n Map<Symbol*,int>& localMap) {\n int i = 0;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n forv_Vec(Expr, expr, bb->exprs) {\n if (DefExpr* def = toDefExpr(expr)) {\n if (toVarSymbol(def->sym)) {\n locals.add(def->sym);\n localMap.put(def->sym, i++);\n }\n }\n }\n }\n}\n\n\n\/\/#define DEBUG_FLOW\nvoid backwardFlowAnalysis(FnSymbol* fn,\n Vec<BitVec*>& GEN,\n Vec<BitVec*>& KILL,\n Vec<BitVec*>& IN,\n Vec<BitVec*>& OUT) {\n bool iterate = true;\n while (iterate) {\n iterate = false;\n int i = 0;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n for (int j = 0; j < IN.v[i]->ndata; j++) {\n unsigned new_in = (OUT.v[i]->data[j] & ~KILL.v[i]->data[j]) | GEN.v[i]->data[j];\n if (new_in != IN.v[i]->data[j]) {\n IN.v[i]->data[j] = new_in;\n iterate = true;\n }\n unsigned new_out = 0;\n forv_Vec(BasicBlock, bbout, bb->outs) {\n new_out = new_out | IN.v[bbout->id]->data[j];\n }\n if (new_out != OUT.v[i]->data[j]) {\n OUT.v[i]->data[j] = new_out;\n iterate = true;\n }\n }\n i++;\n }\n#ifdef DEBUG_FLOW\n printf(\"IN\\n\"); printBitVectorSets(IN);\n printf(\"OUT\\n\"); printBitVectorSets(OUT);\n#endif\n }\n}\n\n\nvoid forwardFlowAnalysis(FnSymbol* fn,\n Vec<BitVec*>& GEN,\n Vec<BitVec*>& KILL,\n Vec<BitVec*>& IN,\n Vec<BitVec*>& OUT,\n bool intersect) {\n int nbbq = fn->basicBlocks->n; \/\/ size of bb queue\n Vec<int> bbq;\n BitVec bbs(nbbq);\n int iq = -1, nq = nbbq-1; \/\/ index to first and last bb in bbq\n for (int i = 0; i < fn->basicBlocks->n; i++) {\n bbq.add(i);\n bbs.set(i);\n }\n while (iq != nq) {\n iq = (iq + 1) % nbbq;\n int i = bbq.v[iq];\n bbs.unset(i);\n#ifdef DEBUG_FLOW\n if (iq == 0) {\n printf(\"IN\\n\"); printBitVectorSets(IN);\n printf(\"OUT\\n\"); printBitVectorSets(OUT);\n }\n#endif\n BasicBlock* bb = fn->basicBlocks->v[i];\n bool change = false;\n for (int j = 0; j < IN.v[i]->ndata; j++) {\n if (bb->ins.n > 0) {\n unsigned new_in = (intersect) ? (unsigned)(-1) : 0;\n forv_Vec(BasicBlock, bbin, bb->ins) {\n if (intersect)\n new_in &= OUT.v[bbin->id]->data[j];\n else\n new_in |= OUT.v[bbin->id]->data[j];\n }\n if (new_in != IN.v[i]->data[j]) {\n IN.v[i]->data[j] = new_in;\n change = true;\n }\n }\n unsigned new_out = (IN.v[i]->data[j] & ~KILL.v[i]->data[j]) | GEN.v[i]->data[j];\n if (new_out != OUT.v[i]->data[j]) {\n OUT.v[i]->data[j] = new_out;\n change = true;\n }\n }\n if (change) {\n forv_Vec(BasicBlock, bbout, bb->outs) {\n if (!bbs.get(bbout->id)) {\n nq = (nq + 1) % nbbq;\n bbs.set(bbout->id);\n bbq.v[nq] = bbout->id;\n }\n }\n }\n }\n}\n\n\nvoid printBasicBlocks(FnSymbol* fn) {\n forv_Vec(BasicBlock, b, *fn->basicBlocks) {\n printf(\"%2d: \", b->id);\n forv_Vec(BasicBlock, bb, b->ins) {\n printf(\"%d \", bb->id);\n }\n printf(\" > \");\n forv_Vec(BasicBlock, bb, b->outs) {\n printf(\"%d \", bb->id);\n }\n printf(\"\\n\");\n forv_Vec(Expr, expr, b->exprs) {\n if (expr)\n list_view_noline(expr);\n else\n printf(\"0 (null)\\n\");\n }\n printf(\"\\n\");\n }\n}\n\nvoid printLocalsVector(Vec<Symbol*> locals, Map<Symbol*,int>& localMap) {\n printf(\"Local Variables\\n\");\n forv_Vec(Symbol, local, locals) {\n printf(\"%2d: %s[%d]\\n\", localMap.get(local), local->name, local->id);\n }\n printf(\"\\n\");\n}\n\nvoid printDefsVector(Vec<SymExpr*> defs, Map<SymExpr*,int>& defMap) {\n printf(\"Variable Definitions\\n\");\n forv_Vec(SymExpr, def, defs) {\n printf(\"%2d: %s[%d] in %d\\n\", defMap.get(def), def->var->name,\n def->var->id, def->getStmtExpr()->id);\n }\n printf(\"\\n\");\n}\n\nvoid printLocalsVectorSets(Vec<BitVec*>& sets, Vec<Symbol*> locals) {\n int i = 0;\n forv_Vec(BitVec, set, sets) {\n printf(\"%2d: \", i);\n for (int j = 0; j < set->size; j++) {\n if (set->get(j))\n printf(\"%s[%d] \", locals.v[j]->name, locals.v[j]->id);\n }\n printf(\"\\n\");\n i++;\n }\n printf(\"\\n\");\n}\n\nvoid printBitVectorSets(Vec<BitVec*>& sets) {\n int i = 0;\n forv_Vec(BitVec, set, sets) {\n printf(\"%2d: \", i);\n for (int j = 0; j < set->size; j++) {\n printf(\"%d\", (set->get(j)) ? 1 : 0);\n if ((j+1) % 10 == 0) printf(\" \");\n }\n printf(\"\\n\");\n i++;\n }\n printf(\"\\n\");\n}\n<commit_msg>Add consistency checking to basic block analysis.<commit_after>#include <cstdlib>\n#include \"astutil.h\"\n#include \"bb.h\"\n#include \"bitVec.h\"\n#include \"expr.h\"\n#include \"stmt.h\"\n#include \"view.h\"\n\nBasicBlock::BasicBlock()\n : id(nextid++) {}\n\n#define BB_START() \\\n basicBlock = new BasicBlock()\n\n\/\/ The assert tests that the expression we are adding to this basic block\n\/\/ has not already been deleted.\n#define BB_ADD(expr) \\\n do { \\\n INT_ASSERT(expr); \\\n basicBlock->exprs.add(expr); \\\n } while (0)\n\n#define BB_STOP() \\\n fn->basicBlocks->add(Steal())\n\n#define BB_RESTART() \\\n do { \\\n BB_STOP(); \\\n BB_START(); \\\n } while (0)\n\n#define BBB(stmt) \\\n buildBasicBlocks(fn, stmt)\n\n#define BB_THREAD(src, dst) \\\n do { \\\n dst->ins.add(src); \\\n src->outs.add(dst); \\\n } while (0)\n\n\n\/\/# Statics\nBasicBlock* BasicBlock::basicBlock;\nMap<LabelSymbol*,Vec<BasicBlock*>*> BasicBlock::gotoMaps;\nMap<LabelSymbol*,BasicBlock*> BasicBlock::labelMaps;\nint BasicBlock::nextid;\n\n\n\/\/ Returns true if the class invariants have been preserved.\nbool BasicBlock::isOK()\n{\n \/\/ Expressions must be live (non-NULL);\n forv_Vec(Expr, expr, exprs)\n if (expr == 0) return false;\n\n \/\/ Every in edge must have a corresponding out edge in the source block.\n forv_Vec(BasicBlock, source, ins) {\n bool found = false;\n forv_Vec(BasicBlock, bb, source->outs)\n if (bb == this) { found = true; break; }\n if (!found) return false;\n }\n\n \/\/ Every out edge must have a corresponding in edge in the target block.\n forv_Vec(BasicBlock, target, outs) {\n bool found = false;\n forv_Vec(BasicBlock, bb, target->ins)\n if (bb == this) { found = true; break; }\n if (!found) return false;\n }\n\n return true;\n}\n\n\/\/ Reset the shared statics.\nvoid BasicBlock::reset(FnSymbol* fn)\n{\n if (fn->basicBlocks)\n {\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n delete bb;\n delete fn->basicBlocks;\n }\n fn->basicBlocks = new Vec<BasicBlock*>();\n gotoMaps.clear();\n labelMaps.clear();\n nextid = 0;\n}\n\nBasicBlock* BasicBlock::Steal()\n{\n BasicBlock* temp = basicBlock;\n basicBlock = 0;\n return temp;\n}\n\n\/\/ This is the top-level (public) builder function.\nvoid buildBasicBlocks(FnSymbol* fn)\n{\n BasicBlock::reset(fn);\n BasicBlock::basicBlock = new BasicBlock(); \/\/ BB_START();\n BasicBlock::buildBasicBlocks(fn, fn->body); \/\/ BBB(fn->body);\n fn->basicBlocks->add(BasicBlock::Steal()); \/\/ BB_STOP();\n\n INT_ASSERT(verifyBasicBlocks(fn));\n}\n\nvoid BasicBlock::buildBasicBlocks(FnSymbol* fn, Expr* stmt)\n{\n if (!stmt) return;\n\n if (BlockStmt* s = toBlockStmt(stmt))\n {\n \/\/ If a loop statement.\n if (s->blockInfo)\n {\n BasicBlock* top = basicBlock;\n BB_RESTART();\n \/\/ Assumes that blockInfo is never null.\n BB_ADD(s->blockInfo);\n BasicBlock* loopTop = basicBlock;\n for_alist(stmt, s->body) {\n BBB(stmt);\n }\n BasicBlock* loopBottom = basicBlock;\n BB_RESTART();\n BasicBlock* bottom = basicBlock;\n BB_THREAD(top, loopTop);\n BB_THREAD(loopBottom, bottom);\n BB_THREAD(loopBottom, loopTop);\n BB_THREAD(top, bottom);\n }\n else\n {\n for_alist(stmt, s->body)\n BBB(stmt);\n }\n }\n else if (CondStmt* s = toCondStmt(stmt))\n {\n INT_ASSERT(s->condExpr);\n BB_ADD(s->condExpr);\n BasicBlock* top = basicBlock;\n BB_RESTART();\n BB_THREAD(top, basicBlock);\n BBB(s->thenStmt);\n BasicBlock* thenBottom = basicBlock;\n BB_RESTART();\n if (s->elseStmt)\n {\n BB_THREAD(top, basicBlock);\n BBB(s->elseStmt);\n BasicBlock* elseBottom = basicBlock;\n BB_RESTART();\n BB_THREAD(elseBottom, basicBlock);\n }\n else\n {\n BB_THREAD(top, basicBlock);\n }\n BB_THREAD(thenBottom, basicBlock);\n } else if (GotoStmt* s = toGotoStmt(stmt)) {\n LabelSymbol* label = toLabelSymbol(toSymExpr(s->label)->var);\n if (BasicBlock* bb = labelMaps.get(label)) {\n BB_THREAD(basicBlock, bb);\n } else {\n Vec<BasicBlock*>* vbb = gotoMaps.get(label);\n if (!vbb)\n vbb = new Vec<BasicBlock*>();\n vbb->add(basicBlock);\n gotoMaps.put(label, vbb);\n }\n BB_ADD(s); \/\/ Put the goto at the end of its block.\n BB_RESTART();\n } else {\n DefExpr* def = toDefExpr(stmt);\n if (def && toLabelSymbol(def->sym)) {\n \/\/ If a label appears in the middle of a block,\n \/\/ we start a new block.\n if (basicBlock->exprs.count() > 0)\n {\n BasicBlock* top = basicBlock;\n BB_RESTART();\n BB_THREAD(top, basicBlock);\n }\n BB_ADD(def); \/\/ Put the label def at the start of its block.\n\n \/\/ OK, this statement is a label def, so get the label.\n LabelSymbol* label = toLabelSymbol(def->sym);\n\n \/\/ See if we have any unresolved references to this label,\n \/\/ and resolve them.\n if (Vec<BasicBlock*>* vbb = gotoMaps.get(label)) {\n forv_Vec(BasicBlock, bb, *vbb) {\n BB_THREAD(bb, basicBlock);\n }\n }\n labelMaps.put(label, basicBlock);\n } else {\n BB_ADD(stmt);\n }\n }\n}\n\n\/\/ Returns true if the basic block structure is OK, false otherwise.\nbool verifyBasicBlocks(FnSymbol* fn)\n{\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n {\n if (! bb->isOK())\n return false;\n }\n return true;\n}\n\nvoid buildLocalsVectorMap(FnSymbol* fn,\n Vec<Symbol*>& locals,\n Map<Symbol*,int>& localMap) {\n int i = 0;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n forv_Vec(Expr, expr, bb->exprs) {\n if (DefExpr* def = toDefExpr(expr)) {\n if (toVarSymbol(def->sym)) {\n locals.add(def->sym);\n localMap.put(def->sym, i++);\n }\n }\n }\n }\n}\n\n\n\/\/#define DEBUG_FLOW\nvoid backwardFlowAnalysis(FnSymbol* fn,\n Vec<BitVec*>& GEN,\n Vec<BitVec*>& KILL,\n Vec<BitVec*>& IN,\n Vec<BitVec*>& OUT) {\n bool iterate = true;\n while (iterate) {\n iterate = false;\n int i = 0;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n for (int j = 0; j < IN.v[i]->ndata; j++) {\n unsigned new_in = (OUT.v[i]->data[j] & ~KILL.v[i]->data[j]) | GEN.v[i]->data[j];\n if (new_in != IN.v[i]->data[j]) {\n IN.v[i]->data[j] = new_in;\n iterate = true;\n }\n unsigned new_out = 0;\n forv_Vec(BasicBlock, bbout, bb->outs) {\n new_out = new_out | IN.v[bbout->id]->data[j];\n }\n if (new_out != OUT.v[i]->data[j]) {\n OUT.v[i]->data[j] = new_out;\n iterate = true;\n }\n }\n i++;\n }\n#ifdef DEBUG_FLOW\n printf(\"IN\\n\"); printBitVectorSets(IN);\n printf(\"OUT\\n\"); printBitVectorSets(OUT);\n#endif\n }\n}\n\n\nvoid forwardFlowAnalysis(FnSymbol* fn,\n Vec<BitVec*>& GEN,\n Vec<BitVec*>& KILL,\n Vec<BitVec*>& IN,\n Vec<BitVec*>& OUT,\n bool intersect) {\n int nbbq = fn->basicBlocks->n; \/\/ size of bb queue\n Vec<int> bbq;\n BitVec bbs(nbbq);\n int iq = -1, nq = nbbq-1; \/\/ index to first and last bb in bbq\n for (int i = 0; i < fn->basicBlocks->n; i++) {\n bbq.add(i);\n bbs.set(i);\n }\n while (iq != nq) {\n iq = (iq + 1) % nbbq;\n int i = bbq.v[iq];\n bbs.unset(i);\n#ifdef DEBUG_FLOW\n if (iq == 0) {\n printf(\"IN\\n\"); printBitVectorSets(IN);\n printf(\"OUT\\n\"); printBitVectorSets(OUT);\n }\n#endif\n BasicBlock* bb = fn->basicBlocks->v[i];\n bool change = false;\n for (int j = 0; j < IN.v[i]->ndata; j++) {\n if (bb->ins.n > 0) {\n unsigned new_in = (intersect) ? (unsigned)(-1) : 0;\n forv_Vec(BasicBlock, bbin, bb->ins) {\n if (intersect)\n new_in &= OUT.v[bbin->id]->data[j];\n else\n new_in |= OUT.v[bbin->id]->data[j];\n }\n if (new_in != IN.v[i]->data[j]) {\n IN.v[i]->data[j] = new_in;\n change = true;\n }\n }\n unsigned new_out = (IN.v[i]->data[j] & ~KILL.v[i]->data[j]) | GEN.v[i]->data[j];\n if (new_out != OUT.v[i]->data[j]) {\n OUT.v[i]->data[j] = new_out;\n change = true;\n }\n }\n if (change) {\n forv_Vec(BasicBlock, bbout, bb->outs) {\n if (!bbs.get(bbout->id)) {\n nq = (nq + 1) % nbbq;\n bbs.set(bbout->id);\n bbq.v[nq] = bbout->id;\n }\n }\n }\n }\n}\n\n\nvoid printBasicBlocks(FnSymbol* fn) {\n forv_Vec(BasicBlock, b, *fn->basicBlocks) {\n printf(\"%2d: \", b->id);\n forv_Vec(BasicBlock, bb, b->ins) {\n printf(\"%d \", bb->id);\n }\n printf(\" > \");\n forv_Vec(BasicBlock, bb, b->outs) {\n printf(\"%d \", bb->id);\n }\n printf(\"\\n\");\n forv_Vec(Expr, expr, b->exprs) {\n if (expr)\n list_view_noline(expr);\n else\n printf(\"0 (null)\\n\");\n }\n printf(\"\\n\");\n }\n}\n\nvoid printLocalsVector(Vec<Symbol*> locals, Map<Symbol*,int>& localMap) {\n printf(\"Local Variables\\n\");\n forv_Vec(Symbol, local, locals) {\n printf(\"%2d: %s[%d]\\n\", localMap.get(local), local->name, local->id);\n }\n printf(\"\\n\");\n}\n\nvoid printDefsVector(Vec<SymExpr*> defs, Map<SymExpr*,int>& defMap) {\n printf(\"Variable Definitions\\n\");\n forv_Vec(SymExpr, def, defs) {\n printf(\"%2d: %s[%d] in %d\\n\", defMap.get(def), def->var->name,\n def->var->id, def->getStmtExpr()->id);\n }\n printf(\"\\n\");\n}\n\nvoid printLocalsVectorSets(Vec<BitVec*>& sets, Vec<Symbol*> locals) {\n int i = 0;\n forv_Vec(BitVec, set, sets) {\n printf(\"%2d: \", i);\n for (int j = 0; j < set->size; j++) {\n if (set->get(j))\n printf(\"%s[%d] \", locals.v[j]->name, locals.v[j]->id);\n }\n printf(\"\\n\");\n i++;\n }\n printf(\"\\n\");\n}\n\nvoid printBitVectorSets(Vec<BitVec*>& sets) {\n int i = 0;\n forv_Vec(BitVec, set, sets) {\n printf(\"%2d: \", i);\n for (int j = 0; j < set->size; j++) {\n printf(\"%d\", (set->get(j)) ? 1 : 0);\n if ((j+1) % 10 == 0) printf(\" \");\n }\n printf(\"\\n\");\n i++;\n }\n printf(\"\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Particle.hpp\n *\n * Created on: 28.04.2010\n * Author: gmueller\n *\/\n\n#ifndef SMOOTH_PARTICLE_HPP_\n#define SMOOTH_PARTICLE_HPP_\n\n#include <ostream>\n#include \"gadget\/Vector3.hpp\"\n\nclass SmoothParticle {\npublic:\n\tVector3f position;\n\tVector3f bfield;\n\tfloat smoothingLength;\n\n\tstatic float kernel(float r) {\n\t\tif (r < 1.0) {\n\t\t\treturn 1.0 - 1.5 * r * r + 0.75 * r * r * r;\n\t\t} else if (r < 2.0) {\n\t\t\tfloat x = (2.0 - r);\n\t\t\treturn 0.25 * x * x * x;\n\t\t} else {\n\t\t\treturn 0.0;\n\t\t}\n\t}\n\n\tstatic float kernel(float value, float center, float position, float hsml) {\n\t\treturn value * kernel(std::fabs((center - position) \/ hsml));\n\t}\n\n\tstatic float kernel(float value, const Vector3f ¢er, const Vector3f &position, float hsml) {\n\t\treturn value * kernel(std::fabs((center - position).length() \/ hsml));\n\t}\n\n\tfloat kernel(const Vector3f ¢er) {\n\t\treturn value * kernel(std::fabs((center - position).length() \/ smoothingLength));\n\t}\n\n};\n\n\ninline std::ostream &operator <<(std::ostream &out, const SmoothParticle &v) {\n\tout << \"(\" << v.position.x << \",\" << v.position.x << \",\" << v.position.x\n\t\t\t<< \"), \" << \"(\" << v.bfield.x << \",\" << v.bfield.x << \",\"\n\t\t\t<< v.bfield.x << \"), \" << v.smoothingLength;\n\treturn out;\n}\n\n#endif \/* PARTICLE_HPP_ *\/\n<commit_msg>fixed smooting kernel to match Dolag et al<commit_after>\/*\n * Particle.hpp\n *\n * Created on: 28.04.2010\n * Author: gmueller\n *\/\n\n#ifndef SMOOTH_PARTICLE_HPP_\n#define SMOOTH_PARTICLE_HPP_\n\n#include <ostream>\n#include \"gadget\/Vector3.hpp\"\n\nclass SmoothParticle {\npublic:\n\tVector3f position;\n\tVector3f bfield;\n\tfloat smoothingLength;\n\n\tstatic float kernel(float r) {\n\t\tif (r < 0.5) {\n\t\t\treturn 1.0 + 6 * r * r * (r - 1);\n\t\t} else if (r < 1.0) {\n\t\t\tfloat x = (1 - r);\n\t\t\treturn 2 * x * x * x;\n\t\t} else {\n\t\t\treturn 0.0;\n\t\t}\n\t}\n\n\tstatic float kernel(float value, float center, float position, float hsml) {\n\t\treturn value * kernel(std::fabs((center - position) \/ hsml));\n\t}\n\n\tstatic float kernel(float value, const Vector3f ¢er, const Vector3f &position, float hsml) {\n\t\treturn value * kernel(std::fabs((center - position).length() \/ hsml));\n\t}\n\n\tfloat kernel(const Vector3f ¢er) {\n\t\treturn value * kernel(std::fabs((center - position).length() \/ smoothingLength));\n\t}\n\n};\n\n\ninline std::ostream &operator <<(std::ostream &out, const SmoothParticle &v) {\n\tout << \"(\" << v.position.x << \",\" << v.position.x << \",\" << v.position.x\n\t\t\t<< \"), \" << \"(\" << v.bfield.x << \",\" << v.bfield.x << \",\"\n\t\t\t<< v.bfield.x << \"), \" << v.smoothingLength;\n\treturn out;\n}\n\n#endif \/* PARTICLE_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef IF3_WORLD_PRECOMPILED_HPP\n#define IF3_WORLD_PRECOMPILED_HPP\n\n#if defined(__APPLE__)\n# define IF3_CONFIG_MACOSX\n#elif defined(__linux__)\n# define IF3_CONFIG_LINUX\n#elif defined(WIN32) || defined( _MSC_VER )\n# define IF3_CONFIG_WIN32\n#endif\n\n \/\/ platform options\n#if defined(IF3_CONFIG_WIN32)\n# define IF3_CONFIG_NEW\n# undef IF3_CONFIG_NEWNOTHROW\n# undef IF3_CONFIG_THROW\n#elif defined(IF3_CONFIG_MACOSX)\n# define IF3_CONFIG_NEW\n# undef IF3_CONFIG_NEWNOTHROW\n# undef IF3_CONFIG_THROW\n# define IF3_CONFIG_POSIX\n# define IF3_CONFIG_PTHREADS\n# define IF3_CONFIG_FORK\n#elif defined(IF3_CONFIG_LINUX)\n# define IF3_CONFIG_NEW\n# undef IF3_CONFIG_NEWNOTHROW\n# undef IF3_CONFIG_THROW\n# define IF3_CONFIG_POSIX\n# define IF3_CONFIG_PTHREADS\n# define IF3_CONFIG_FORK\n#else\n# error please define one of IF3_CONFIG_WIN32 IF3_CONFIG_MACOSX IF3_CONFIG_LINUX\n#endif\n\n#ifndef IF3_CONFIG_DEBUG\n# define IF3_CONFIG_DEBUG (1)\n#endif\n\n \/\/ for win32 we need windows.h and friends\n#if defined(IF3_CONFIG_WIN32)\n\n# include <winsock2.h>\n# include <windows.h>\n# include <io.h>\n# include <process.h>\n#endif\n\n#if defined(IF3_CONFIG_PTHREADS)\n# ifndef __STL_PTHREADS\n# define __STL_PTHREADS\n# endif\n# define _PTHREADS 1\n# include <pthread.h>\n#endif\n\n#if defined(IF3_CONFIG_POSIX)\n# include <signal.h>\n# include <sys\/time.h>\n# include <sys\/types.h>\n# include <sys\/stat.h>\n# include <sys\/wait.h>\n# include <sys\/mman.h>\n# include <sys\/stat.h>\n# include <netdb.h>\n# include <unistd.h>\n# include <netinet\/in.h>\n# include <sys\/poll.h>\n# include <unistd.h>\n# include <sys\/socket.h>\n# include <arpa\/inet.h>\n# include <net\/if.h>\n# include <sys\/resource.h>\n# include <sys\/stat.h>\n# include <fcntl.h>\n# include <sys\/types.h>\n# include <syslog.h>\n# include <pwd.h>\n#endif\n\n \/\/ include the normal standard c library stuff\n#include <stdlib.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <string.h>\n#include <time.h>\n#include <errno.h>\n#include <stdarg.h>\n\n\n#ifdef __cplusplus\n# if defined(IF3_CONFIG_NEW)\n# include <new>\n# endif\n\n# include <string>\n# include <iostream>\n# include <sstream>\n# include <list>\n# include <valarray>\n# include <vector>\n# include <algorithm>\n# include <exception>\n# include <stdexcept>\n# include <cstring>\n# include <cstdlib>\n# include <queue>\n# include <deque>\n# include <functional>\n# include <tr1\/functional>\n# include <map>\n\n# if defined(IF3_CONFIG_NEWNOTHROW)\n# define newnothrow new (std::nothrow)\n# else\n# define newnothrow new\n# endif\n\n# if defined(IF3_CONFIG_THROW)\n# define if3_throw( a, b ) throw( a(b) )\n# elif defined(IF3_CONFIG_POSIX)\n# define if3_throw( a, b ) do { fprintf(stderr,\"%s(\\\"%s\\\")\",#a,b); abort(); } while(0)\n# elif defined(IF3_CONFIG_WIN32)\n# define if3_throw( a, b ) do { fprintf(stderr,\"%s(\\\"%s\\\")\",#a,b); abort(); } while(0)\n# endif\n#endif\n\nnamespace if3\n{\n using tr1::function;\n\n template< typename T1, typename T2 > inline T1 lexical_cast ( const T2 &v )\n {\n T1 newval;\n std::stringstream os;\n\n if ( ! ( os << v ) || ! ( os >> newval ) )\n {\n if3_throw( std::invalid_argument, \"lexical_cast\" );\n }\n\n return newval;\n }\n\n\n}\n\n#endif\n\n<commit_msg>fixed functional tr1 reference<commit_after>#ifndef IF3_WORLD_PRECOMPILED_HPP\n#define IF3_WORLD_PRECOMPILED_HPP\n\n#if defined(__APPLE__)\n# define IF3_CONFIG_MACOSX\n#elif defined(__linux__)\n# define IF3_CONFIG_LINUX\n#elif defined(WIN32) || defined( _MSC_VER )\n# define IF3_CONFIG_WIN32\n#endif\n\n \/\/ platform options\n#if defined(IF3_CONFIG_WIN32)\n# define IF3_CONFIG_NEW\n# undef IF3_CONFIG_NEWNOTHROW\n# undef IF3_CONFIG_THROW\n#elif defined(IF3_CONFIG_MACOSX)\n# define IF3_CONFIG_NEW\n# undef IF3_CONFIG_NEWNOTHROW\n# undef IF3_CONFIG_THROW\n# define IF3_CONFIG_POSIX\n# define IF3_CONFIG_PTHREADS\n# define IF3_CONFIG_FORK\n#elif defined(IF3_CONFIG_LINUX)\n# define IF3_CONFIG_NEW\n# undef IF3_CONFIG_NEWNOTHROW\n# undef IF3_CONFIG_THROW\n# define IF3_CONFIG_POSIX\n# define IF3_CONFIG_PTHREADS\n# define IF3_CONFIG_FORK\n#else\n# error please define one of IF3_CONFIG_WIN32 IF3_CONFIG_MACOSX IF3_CONFIG_LINUX\n#endif\n\n#ifndef IF3_CONFIG_DEBUG\n# define IF3_CONFIG_DEBUG (1)\n#endif\n\n \/\/ for win32 we need windows.h and friends\n#if defined(IF3_CONFIG_WIN32)\n\n# include <winsock2.h>\n# include <windows.h>\n# include <io.h>\n# include <process.h>\n#endif\n\n#if defined(IF3_CONFIG_PTHREADS)\n# ifndef __STL_PTHREADS\n# define __STL_PTHREADS\n# endif\n# define _PTHREADS 1\n# include <pthread.h>\n#endif\n\n#if defined(IF3_CONFIG_POSIX)\n# include <signal.h>\n# include <sys\/time.h>\n# include <sys\/types.h>\n# include <sys\/stat.h>\n# include <sys\/wait.h>\n# include <sys\/mman.h>\n# include <sys\/stat.h>\n# include <netdb.h>\n# include <unistd.h>\n# include <netinet\/in.h>\n# include <sys\/poll.h>\n# include <unistd.h>\n# include <sys\/socket.h>\n# include <arpa\/inet.h>\n# include <net\/if.h>\n# include <sys\/resource.h>\n# include <sys\/stat.h>\n# include <fcntl.h>\n# include <sys\/types.h>\n# include <syslog.h>\n# include <pwd.h>\n#endif\n\n \/\/ include the normal standard c library stuff\n#include <stdlib.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <string.h>\n#include <time.h>\n#include <errno.h>\n#include <stdarg.h>\n\n\n#ifdef __cplusplus\n# if defined(IF3_CONFIG_NEW)\n# include <new>\n# endif\n\n# include <string>\n# include <iostream>\n# include <sstream>\n# include <list>\n# include <valarray>\n# include <vector>\n# include <algorithm>\n# include <exception>\n# include <stdexcept>\n# include <cstring>\n# include <cstdlib>\n# include <queue>\n# include <deque>\n# include <functional>\n# include <tr1\/functional>\n# include <map>\n\n# if defined(IF3_CONFIG_NEWNOTHROW)\n# define newnothrow new (std::nothrow)\n# else\n# define newnothrow new\n# endif\n\n# if defined(IF3_CONFIG_THROW)\n# define if3_throw( a, b ) throw( a(b) )\n# elif defined(IF3_CONFIG_POSIX)\n# define if3_throw( a, b ) do { fprintf(stderr,\"%s(\\\"%s\\\")\",#a,b); abort(); } while(0)\n# elif defined(IF3_CONFIG_WIN32)\n# define if3_throw( a, b ) do { fprintf(stderr,\"%s(\\\"%s\\\")\",#a,b); abort(); } while(0)\n# endif\n#endif\n\nnamespace if3\n{\n using std::tr1::function;\n\n template< typename T1, typename T2 > inline T1 lexical_cast ( const T2 &v )\n {\n T1 newval;\n std::stringstream os;\n\n if ( ! ( os << v ) || ! ( os >> newval ) )\n {\n if3_throw( std::invalid_argument, \"lexical_cast\" );\n }\n\n return newval;\n }\n\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2008, 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#ifndef TORRENT_ERROR_CODE_HPP_INCLUDED\n#define TORRENT_ERROR_CODE_HPP_INCLUDED\n\n#include <boost\/version.hpp>\n#include <boost\/shared_ptr.hpp>\n\n#if BOOST_VERSION < 103500\n#include <asio\/error_code.hpp>\n#else\n#include <boost\/system\/error_code.hpp>\n#endif\n\n#include \"libtorrent\/config.hpp\"\n\nnamespace libtorrent\n{\n\n\tnamespace errors\n\t{\n\t\tenum error_code_enum\n\t\t{\n\t\t\tno_error = 0,\n\t\t\tfile_collision,\n\t\t\tfailed_hash_check,\n\t\t\ttorrent_is_no_dict,\n\t\t\ttorrent_missing_info,\n\t\t\ttorrent_info_no_dict,\n\t\t\ttorrent_missing_piece_length,\n\t\t\ttorrent_missing_name,\n\t\t\ttorrent_invalid_name,\n\t\t\ttorrent_invalid_length,\n\t\t\ttorrent_file_parse_failed,\n\t\t\ttorrent_missing_pieces,\n\t\t\ttorrent_invalid_hashes,\n\t\t\ttoo_many_pieces_in_torrent,\n\t\t\tinvalid_swarm_metadata,\n\t\t\tinvalid_bencoding,\n\t\t\tno_files_in_torrent,\n\t\t\tinvalid_escaped_string,\n\t\t\tsession_is_closing,\n\t\t\tduplicate_torrent,\n\t\t\tinvalid_torrent_handle,\n\t\t\tinvalid_entry_type,\n\t\t\tmissing_info_hash_in_uri,\n\t\t\tfile_too_short,\n\t\t\tunsupported_url_protocol,\n\t\t\turl_parse_error,\n\t\t\tpeer_sent_empty_piece,\n\t\t\tparse_failed,\n\t\t\tinvalid_file_tag,\n\t\t\tmissing_info_hash,\n\t\t\tmismatching_info_hash,\n\t\t\tinvalid_hostname,\n\t\t\tinvalid_port,\n\t\t\tport_blocked,\n\t\t\texpected_close_bracket_in_address,\n\t\t\tdestructing_torrent,\n\t\t\ttimed_out,\n\t\t\tupload_upload_connection,\n\t\t\tuninteresting_upload_peer,\n\t\t\tinvalid_info_hash,\n\t\t\ttorrent_paused,\n\t\t\tinvalid_have,\n\t\t\tinvalid_bitfield_size,\n\t\t\ttoo_many_requests_when_choked,\n\t\t\tinvalid_piece,\n\t\t\tno_memory,\n\t\t\ttorrent_aborted,\n\t\t\tself_connection,\n\t\t\tinvalid_piece_size,\n\t\t\ttimed_out_no_interest,\n\t\t\ttimed_out_inactivity,\n\t\t\ttimed_out_no_handshake,\n\t\t\ttimed_out_no_request,\n\t\t\tinvalid_choke,\n\t\t\tinvalid_unchoke,\n\t\t\tinvalid_interested,\n\t\t\tinvalid_not_interested,\n\t\t\tinvalid_request,\n\t\t\tinvalid_hash_list,\n\t\t\tinvalid_hash_piece,\n\t\t\tinvalid_cancel,\n\t\t\tinvalid_dht_port,\n\t\t\tinvalid_suggest,\n\t\t\tinvalid_have_all,\n\t\t\tinvalid_have_none,\n\t\t\tinvalid_reject,\n\t\t\tinvalid_allow_fast,\n\t\t\tinvalid_extended,\n\t\t\tinvalid_message,\n\t\t\tsync_hash_not_found,\n\t\t\tinvalid_encryption_constant,\n\t\t\tno_plaintext_mode,\n\t\t\tno_rc4_mode,\n\t\t\tunsupported_encryption_mode,\n\t\t\tunsupported_encryption_mode_selected,\n\t\t\tinvalid_pad_size,\n\t\t\tinvalid_encrypt_handshake,\n\t\t\tno_incoming_encrypted,\n\t\t\tno_incoming_regular,\n\t\t\tduplicate_peer_id,\n\t\t\ttorrent_removed,\n\t\t\tpacket_too_large,\n\t\t\thttp_parse_error,\n\t\t\thttp_error,\n\t\t\tmissing_location,\n\t\t\tinvalid_redirection,\n\t\t\tredirecting,\n\t\t\tinvalid_range,\n\t\t\tno_content_length,\n\t\t\tbanned_by_ip_filter,\n\t\t\ttoo_many_connections,\n\t\t\tpeer_banned,\n\t\t\tstopping_torrent,\n\t\t\ttoo_many_corrupt_pieces,\n\t\t\ttorrent_not_ready,\n\t\t\tpeer_not_constructed,\n\t\t\tsession_closing,\n\t\t\toptimistic_disconnect,\n\t\t\ttorrent_finished,\n\t\t\tno_router,\n\t\t\tmetadata_too_large,\n\t\t\tinvalid_metadata_request,\n\t\t\tinvalid_metadata_size,\n\t\t\tinvalid_metadata_offset,\n\t\t\tinvalid_metadata_message,\n\t\t\tpex_message_too_large,\n\t\t\tinvalid_pex_message,\n\t\t\tinvalid_lt_tracker_message,\n\n\/\/ natpmp errors\n\t\t\tunsupported_protocol_version,\n\t\t\tnatpmp_not_authorized,\n\t\t\tnetwork_failure,\n\t\t\tno_resources,\n\t\t\tunsupported_opcode,\n\n\/\/ fastresume errors\n\t\t\tmissing_file_sizes,\n\t\t\tno_files_in_resume_data,\n\t\t\tmissing_pieces,\n\t\t\tmismatching_number_of_files,\n\t\t\tmismatching_file_size,\n\t\t\tmismatching_file_timestamp,\n\t\t\tnot_a_dictionary,\n\t\t\tinvalid_blocks_per_piece,\n\t\t\tmissing_slots,\n\t\t\ttoo_many_slots,\n\t\t\tinvalid_slot_list,\n\t\t\tinvalid_piece_index,\n\t\t\tpieces_need_reorder,\n\t\t\treserved1,\n\t\t\treserved2,\n\t\t\treserved3,\n\t\t\treserved4,\n\t\t\treserved5,\n\t\t\treserved6,\n\t\t\treserved7,\n\t\t\treserved8,\n\t\t};\n\t}\n\n#if BOOST_VERSION < 103500\n\ttypedef asio::error_code error_code;\n\tinline asio::error::error_category get_posix_category() { return asio::error::system_category; }\n\tinline asio::error::error_category get_system_category() { return asio::error::system_category; }\n\n\textern TORRENT_EXPORT asio::error::error_category libtorrent_category;\n#else\n\n\tclass TORRENT_EXPORT boost::system::error_category;\n\n\tstruct TORRENT_EXPORT libtorrent_error_category : boost::system::error_category\n\t{\n\t\tvirtual const char* name() const;\n\t\tvirtual std::string message(int ev) const;\n\t\tvirtual boost::system::error_condition default_error_condition(int ev) const\n\t\t{ return boost::system::error_condition(ev, *this); }\n\t};\n\n\textern TORRENT_EXPORT libtorrent_error_category libtorrent_category;\n\n\tusing boost::system::error_code;\n\tinline boost::system::error_category const& get_system_category()\n\t{ return boost::system::get_system_category(); }\n\tinline boost::system::error_category const& get_posix_category()\n#if BOOST_VERSION < 103600\n\t{ return boost::system::get_posix_category(); }\n#else\n\t{ return boost::system::get_generic_category(); }\n#endif\n#endif\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tstruct TORRENT_EXPORT libtorrent_exception: std::exception\n\t{\n\t\tlibtorrent_exception(error_code const& s): m_error(s) {}\n\t\tvirtual const char* what() const throw()\n\t\t{\n\t\t\tif (!m_msg) m_msg.reset(new std::string(m_error.message()));\n\t\t\treturn m_msg->c_str();\n\t\t}\n\t\tvirtual ~libtorrent_exception() throw() {}\n\t\terror_code error() const { return m_error; }\n\tprivate:\n\t\terror_code m_error;\n\t\tmutable boost::shared_ptr<std::string> m_msg;\n\t};\n#endif\n}\n\n#endif\n\n<commit_msg>remove useless declaration<commit_after>\/*\n\nCopyright (c) 2008, 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#ifndef TORRENT_ERROR_CODE_HPP_INCLUDED\n#define TORRENT_ERROR_CODE_HPP_INCLUDED\n\n#include <boost\/version.hpp>\n#include <boost\/shared_ptr.hpp>\n\n#if BOOST_VERSION < 103500\n#include <asio\/error_code.hpp>\n#else\n#include <boost\/system\/error_code.hpp>\n#endif\n\n#include \"libtorrent\/config.hpp\"\n\nnamespace libtorrent\n{\n\n\tnamespace errors\n\t{\n\t\tenum error_code_enum\n\t\t{\n\t\t\tno_error = 0,\n\t\t\tfile_collision,\n\t\t\tfailed_hash_check,\n\t\t\ttorrent_is_no_dict,\n\t\t\ttorrent_missing_info,\n\t\t\ttorrent_info_no_dict,\n\t\t\ttorrent_missing_piece_length,\n\t\t\ttorrent_missing_name,\n\t\t\ttorrent_invalid_name,\n\t\t\ttorrent_invalid_length,\n\t\t\ttorrent_file_parse_failed,\n\t\t\ttorrent_missing_pieces,\n\t\t\ttorrent_invalid_hashes,\n\t\t\ttoo_many_pieces_in_torrent,\n\t\t\tinvalid_swarm_metadata,\n\t\t\tinvalid_bencoding,\n\t\t\tno_files_in_torrent,\n\t\t\tinvalid_escaped_string,\n\t\t\tsession_is_closing,\n\t\t\tduplicate_torrent,\n\t\t\tinvalid_torrent_handle,\n\t\t\tinvalid_entry_type,\n\t\t\tmissing_info_hash_in_uri,\n\t\t\tfile_too_short,\n\t\t\tunsupported_url_protocol,\n\t\t\turl_parse_error,\n\t\t\tpeer_sent_empty_piece,\n\t\t\tparse_failed,\n\t\t\tinvalid_file_tag,\n\t\t\tmissing_info_hash,\n\t\t\tmismatching_info_hash,\n\t\t\tinvalid_hostname,\n\t\t\tinvalid_port,\n\t\t\tport_blocked,\n\t\t\texpected_close_bracket_in_address,\n\t\t\tdestructing_torrent,\n\t\t\ttimed_out,\n\t\t\tupload_upload_connection,\n\t\t\tuninteresting_upload_peer,\n\t\t\tinvalid_info_hash,\n\t\t\ttorrent_paused,\n\t\t\tinvalid_have,\n\t\t\tinvalid_bitfield_size,\n\t\t\ttoo_many_requests_when_choked,\n\t\t\tinvalid_piece,\n\t\t\tno_memory,\n\t\t\ttorrent_aborted,\n\t\t\tself_connection,\n\t\t\tinvalid_piece_size,\n\t\t\ttimed_out_no_interest,\n\t\t\ttimed_out_inactivity,\n\t\t\ttimed_out_no_handshake,\n\t\t\ttimed_out_no_request,\n\t\t\tinvalid_choke,\n\t\t\tinvalid_unchoke,\n\t\t\tinvalid_interested,\n\t\t\tinvalid_not_interested,\n\t\t\tinvalid_request,\n\t\t\tinvalid_hash_list,\n\t\t\tinvalid_hash_piece,\n\t\t\tinvalid_cancel,\n\t\t\tinvalid_dht_port,\n\t\t\tinvalid_suggest,\n\t\t\tinvalid_have_all,\n\t\t\tinvalid_have_none,\n\t\t\tinvalid_reject,\n\t\t\tinvalid_allow_fast,\n\t\t\tinvalid_extended,\n\t\t\tinvalid_message,\n\t\t\tsync_hash_not_found,\n\t\t\tinvalid_encryption_constant,\n\t\t\tno_plaintext_mode,\n\t\t\tno_rc4_mode,\n\t\t\tunsupported_encryption_mode,\n\t\t\tunsupported_encryption_mode_selected,\n\t\t\tinvalid_pad_size,\n\t\t\tinvalid_encrypt_handshake,\n\t\t\tno_incoming_encrypted,\n\t\t\tno_incoming_regular,\n\t\t\tduplicate_peer_id,\n\t\t\ttorrent_removed,\n\t\t\tpacket_too_large,\n\t\t\thttp_parse_error,\n\t\t\thttp_error,\n\t\t\tmissing_location,\n\t\t\tinvalid_redirection,\n\t\t\tredirecting,\n\t\t\tinvalid_range,\n\t\t\tno_content_length,\n\t\t\tbanned_by_ip_filter,\n\t\t\ttoo_many_connections,\n\t\t\tpeer_banned,\n\t\t\tstopping_torrent,\n\t\t\ttoo_many_corrupt_pieces,\n\t\t\ttorrent_not_ready,\n\t\t\tpeer_not_constructed,\n\t\t\tsession_closing,\n\t\t\toptimistic_disconnect,\n\t\t\ttorrent_finished,\n\t\t\tno_router,\n\t\t\tmetadata_too_large,\n\t\t\tinvalid_metadata_request,\n\t\t\tinvalid_metadata_size,\n\t\t\tinvalid_metadata_offset,\n\t\t\tinvalid_metadata_message,\n\t\t\tpex_message_too_large,\n\t\t\tinvalid_pex_message,\n\t\t\tinvalid_lt_tracker_message,\n\n\/\/ natpmp errors\n\t\t\tunsupported_protocol_version,\n\t\t\tnatpmp_not_authorized,\n\t\t\tnetwork_failure,\n\t\t\tno_resources,\n\t\t\tunsupported_opcode,\n\n\/\/ fastresume errors\n\t\t\tmissing_file_sizes,\n\t\t\tno_files_in_resume_data,\n\t\t\tmissing_pieces,\n\t\t\tmismatching_number_of_files,\n\t\t\tmismatching_file_size,\n\t\t\tmismatching_file_timestamp,\n\t\t\tnot_a_dictionary,\n\t\t\tinvalid_blocks_per_piece,\n\t\t\tmissing_slots,\n\t\t\ttoo_many_slots,\n\t\t\tinvalid_slot_list,\n\t\t\tinvalid_piece_index,\n\t\t\tpieces_need_reorder,\n\t\t\treserved1,\n\t\t\treserved2,\n\t\t\treserved3,\n\t\t\treserved4,\n\t\t\treserved5,\n\t\t\treserved6,\n\t\t\treserved7,\n\t\t\treserved8,\n\t\t};\n\t}\n\n#if BOOST_VERSION < 103500\n\ttypedef asio::error_code error_code;\n\tinline asio::error::error_category get_posix_category() { return asio::error::system_category; }\n\tinline asio::error::error_category get_system_category() { return asio::error::system_category; }\n\n\textern TORRENT_EXPORT asio::error::error_category libtorrent_category;\n#else\n\n\tstruct TORRENT_EXPORT libtorrent_error_category : boost::system::error_category\n\t{\n\t\tvirtual const char* name() const;\n\t\tvirtual std::string message(int ev) const;\n\t\tvirtual boost::system::error_condition default_error_condition(int ev) const\n\t\t{ return boost::system::error_condition(ev, *this); }\n\t};\n\n\textern TORRENT_EXPORT libtorrent_error_category libtorrent_category;\n\n\tusing boost::system::error_code;\n\tinline boost::system::error_category const& get_system_category()\n\t{ return boost::system::get_system_category(); }\n\tinline boost::system::error_category const& get_posix_category()\n#if BOOST_VERSION < 103600\n\t{ return boost::system::get_posix_category(); }\n#else\n\t{ return boost::system::get_generic_category(); }\n#endif\n#endif\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tstruct TORRENT_EXPORT libtorrent_exception: std::exception\n\t{\n\t\tlibtorrent_exception(error_code const& s): m_error(s) {}\n\t\tvirtual const char* what() const throw()\n\t\t{\n\t\t\tif (!m_msg) m_msg.reset(new std::string(m_error.message()));\n\t\t\treturn m_msg->c_str();\n\t\t}\n\t\tvirtual ~libtorrent_exception() throw() {}\n\t\terror_code error() const { return m_error; }\n\tprivate:\n\t\terror_code m_error;\n\t\tmutable boost::shared_ptr<std::string> m_msg;\n\t};\n#endif\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2006, 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#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED\n#define TORRENT_EXTENSIONS_HPP_INCLUDED\n\n#ifndef TORRENT_DISABLE_EXTENSIONS\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/weak_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux { struct session_impl; }\n\n\tstruct peer_plugin;\n\tclass bt_peer_connection;\n\tstruct peer_request;\n\tclass peer_connection;\n\tclass entry;\n\tstruct lazy_entry;\n\tstruct disk_buffer_holder;\n\tstruct bitfield;\n\tclass alert;\n\tstruct torrent_plugin;\n\n\tstruct TORRENT_EXPORT plugin\n\t{\n\t\tvirtual ~plugin() {}\n\n\t\tvirtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)\n\t\t{ return boost::shared_ptr<torrent_plugin>(); }\n\n\t\t\/\/ called when plugin is added to a session\n\t\tvirtual void added(boost::weak_ptr<aux::session_impl> s) {}\n\n\t\t\/\/ called when an alert is posted\n\t\t\/\/ alerts that are filtered are not\n\t\t\/\/ posted\n\t\tvirtual void on_alert(alert const* a) {}\n\n\t\t\/\/ called once per second\n\t\tvirtual void on_tick() {}\n\n\t\t\/\/ called when saving settings state\n\t\tvirtual void save_state(entry& ent) const {}\n\n\t\t\/\/ called when loading settings state\n\t\tvirtual void load_state(lazy_entry const& ent) {}\n\t};\n\n\tstruct TORRENT_EXPORT torrent_plugin\n\t{\n\t\tvirtual ~torrent_plugin() {}\n\t\t\/\/ throwing an exception closes the connection\n\t\t\/\/ returning a 0 pointer is valid and will not add\n\t\t\/\/ the peer_plugin to the peer_connection\n\t\tvirtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)\n\t\t{ return boost::shared_ptr<peer_plugin>(); }\n\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ if true is returned, it means the handler handled the event,\n\t\t\/\/ and no other plugins will have their handlers called, and the\n\t\t\/\/ default behavior will be skipped\n\t\tvirtual bool on_pause() { return false; }\n\t\tvirtual bool on_resume() { return false; }\n\n\t\t\/\/ this is called when the initial checking of\n\t\t\/\/ files is completed.\n\t\tvirtual void on_files_checked() {}\n\n\t\t\/\/ called when the torrent changes state\n\t\t\/\/ the state is one of torrent_status::state_t\n\t\t\/\/ enum members\n\t\tvirtual void on_state(int s) {}\n\t};\n\n\tstruct TORRENT_EXPORT peer_plugin\n\t{\n\t\tvirtual ~peer_plugin() {}\n\n\t\tvirtual char const* type() const { return \"\"; }\n\n\t\t\/\/ can add entries to the extension handshake\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual void add_handshake(entry&) {}\n\t\t\n\t\t\/\/ throwing an exception from any of the handlers (except add_handshake)\n\t\t\/\/ closes the connection\n\t\t\n\t\t\/\/ this is called when the initial BT handshake is received. Returning false\n\t\t\/\/ means that the other end doesn't support this extension and will remove\n\t\t\/\/ it from the list of plugins.\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_handshake(char const* reserved_bits) { return true; }\n\t\t\n\t\t\/\/ called when the extension handshake from the other end is received\n\t\t\/\/ if this returns false, it means that this extension isn't\n\t\t\/\/ supported by this peer. It will result in this peer_plugin\n\t\t\/\/ being removed from the peer_connection and destructed. \n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extension_handshake(lazy_entry const& h) { return true; }\n\n\t\t\/\/ returning true from any of the message handlers\n\t\t\/\/ indicates that the plugin has handeled the message.\n\t\t\/\/ it will break the plugin chain traversing and not let\n\t\t\/\/ anyone else handle the message, including the default\n\t\t\/\/ handler.\n\n\t\tvirtual bool on_choke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_unchoke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_not_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_bitfield(bitfield const& bitfield)\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_all()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_none()\n\t\t{ return false; }\n\n\t\tvirtual bool on_allowed_fast(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_request(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)\n\t\t{ return false; }\n\n\t\tvirtual bool on_cancel(peer_request const& req)\n\t\t{ return false; }\n\t\n\t\tvirtual bool on_reject(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_suggest(int index)\n\t\t{ return false; }\n\n\t\t\/\/ called when an extended message is received. If returning true,\n\t\t\/\/ the message is not processed by any other plugin and if false\n\t\t\/\/ is returned the next plugin in the chain will receive it to\n\t\t\/\/ be able to handle it\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extended(int length\n\t\t\t, int msg, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_unknown_message(int length, int msg\n\t\t\t, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ called when a piece that this peer participated in either\n\t\t\/\/ fails or passes the hash_check\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ called each time a request message is to be sent. If true\n\t\t\/\/ is returned, the original request message won't be sent and\n\t\t\/\/ no other plugin will have this function called.\n\t\tvirtual bool write_request(peer_request const& r) { return false; }\n\t};\n\n}\n\n#endif\n\n#endif \/\/ TORRENT_EXTENSIONS_HPP_INCLUDED\n\n<commit_msg>fix build<commit_after>\/*\n\nCopyright (c) 2006, 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#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED\n#define TORRENT_EXTENSIONS_HPP_INCLUDED\n\n#ifndef TORRENT_DISABLE_EXTENSIONS\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/weak_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux { struct session_impl; }\n\n\tstruct peer_plugin;\n\tclass bt_peer_connection;\n\tstruct peer_request;\n\tclass peer_connection;\n\tclass entry;\n\tstruct lazy_entry;\n\tstruct disk_buffer_holder;\n\tstruct bitfield;\n\tclass alert;\n\tstruct torrent_plugin;\n\tclass torrent;\n\n\tstruct TORRENT_EXPORT plugin\n\t{\n\t\tvirtual ~plugin() {}\n\n\t\tvirtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)\n\t\t{ return boost::shared_ptr<torrent_plugin>(); }\n\n\t\t\/\/ called when plugin is added to a session\n\t\tvirtual void added(boost::weak_ptr<aux::session_impl> s) {}\n\n\t\t\/\/ called when an alert is posted\n\t\t\/\/ alerts that are filtered are not\n\t\t\/\/ posted\n\t\tvirtual void on_alert(alert const* a) {}\n\n\t\t\/\/ called once per second\n\t\tvirtual void on_tick() {}\n\n\t\t\/\/ called when saving settings state\n\t\tvirtual void save_state(entry& ent) const {}\n\n\t\t\/\/ called when loading settings state\n\t\tvirtual void load_state(lazy_entry const& ent) {}\n\t};\n\n\tstruct TORRENT_EXPORT torrent_plugin\n\t{\n\t\tvirtual ~torrent_plugin() {}\n\t\t\/\/ throwing an exception closes the connection\n\t\t\/\/ returning a 0 pointer is valid and will not add\n\t\t\/\/ the peer_plugin to the peer_connection\n\t\tvirtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)\n\t\t{ return boost::shared_ptr<peer_plugin>(); }\n\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ if true is returned, it means the handler handled the event,\n\t\t\/\/ and no other plugins will have their handlers called, and the\n\t\t\/\/ default behavior will be skipped\n\t\tvirtual bool on_pause() { return false; }\n\t\tvirtual bool on_resume() { return false; }\n\n\t\t\/\/ this is called when the initial checking of\n\t\t\/\/ files is completed.\n\t\tvirtual void on_files_checked() {}\n\n\t\t\/\/ called when the torrent changes state\n\t\t\/\/ the state is one of torrent_status::state_t\n\t\t\/\/ enum members\n\t\tvirtual void on_state(int s) {}\n\t};\n\n\tstruct TORRENT_EXPORT peer_plugin\n\t{\n\t\tvirtual ~peer_plugin() {}\n\n\t\tvirtual char const* type() const { return \"\"; }\n\n\t\t\/\/ can add entries to the extension handshake\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual void add_handshake(entry&) {}\n\t\t\n\t\t\/\/ throwing an exception from any of the handlers (except add_handshake)\n\t\t\/\/ closes the connection\n\t\t\n\t\t\/\/ this is called when the initial BT handshake is received. Returning false\n\t\t\/\/ means that the other end doesn't support this extension and will remove\n\t\t\/\/ it from the list of plugins.\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_handshake(char const* reserved_bits) { return true; }\n\t\t\n\t\t\/\/ called when the extension handshake from the other end is received\n\t\t\/\/ if this returns false, it means that this extension isn't\n\t\t\/\/ supported by this peer. It will result in this peer_plugin\n\t\t\/\/ being removed from the peer_connection and destructed. \n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extension_handshake(lazy_entry const& h) { return true; }\n\n\t\t\/\/ returning true from any of the message handlers\n\t\t\/\/ indicates that the plugin has handeled the message.\n\t\t\/\/ it will break the plugin chain traversing and not let\n\t\t\/\/ anyone else handle the message, including the default\n\t\t\/\/ handler.\n\n\t\tvirtual bool on_choke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_unchoke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_not_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_bitfield(bitfield const& bitfield)\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_all()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_none()\n\t\t{ return false; }\n\n\t\tvirtual bool on_allowed_fast(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_request(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)\n\t\t{ return false; }\n\n\t\tvirtual bool on_cancel(peer_request const& req)\n\t\t{ return false; }\n\t\n\t\tvirtual bool on_reject(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_suggest(int index)\n\t\t{ return false; }\n\n\t\t\/\/ called when an extended message is received. If returning true,\n\t\t\/\/ the message is not processed by any other plugin and if false\n\t\t\/\/ is returned the next plugin in the chain will receive it to\n\t\t\/\/ be able to handle it\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extended(int length\n\t\t\t, int msg, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_unknown_message(int length, int msg\n\t\t\t, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ called when a piece that this peer participated in either\n\t\t\/\/ fails or passes the hash_check\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ called each time a request message is to be sent. If true\n\t\t\/\/ is returned, the original request message won't be sent and\n\t\t\/\/ no other plugin will have this function called.\n\t\tvirtual bool write_request(peer_request const& r) { return false; }\n\t};\n\n}\n\n#endif\n\n#endif \/\/ TORRENT_EXTENSIONS_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2008-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#ifndef TORRENT_SSL_STREAM_HPP_INCLUDED\n#define TORRENT_SSL_STREAM_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include <boost\/bind.hpp>\n#if BOOST_VERSION < 103500\n#include <asio\/ssl.hpp>\n#else\n#include <boost\/asio\/ssl.hpp>\n#endif\n\/\/ openssl seems to believe it owns\n\/\/ this name in every single scope\n#undef set_key\n\nnamespace libtorrent {\n\ntemplate <class Stream>\nclass ssl_stream\n{\npublic:\n\n\texplicit ssl_stream(io_service& io_service, asio::ssl::context& ctx)\n\t\t: m_sock(io_service, ctx)\n\t{\n\t}\n\n\ttypedef typename asio::ssl::stream<Stream> sock_type;\n\ttypedef typename sock_type::next_layer_type next_layer_type;\n\ttypedef typename Stream::lowest_layer_type lowest_layer_type;\n\ttypedef typename Stream::endpoint_type endpoint_type;\n\ttypedef typename Stream::protocol_type protocol_type;\n\n\tvoid set_host_name(std::string name)\n\t{\n#if OPENSSL_VERSION_NUMBER >= 0x90812f\n\t\tSSL_set_tlsext_host_name(m_sock.native_handle(), name.c_str());\n#endif\n\t}\n\n\ttemplate <class T>\n\tvoid set_verify_callback(T const& fun, error_code& ec)\n\t{ m_sock.set_verify_callback(fun, ec); }\n\n#if BOOST_VERSION >= 104700\n\tSSL* native_handle() { return m_sock.native_handle(); }\n#endif\n\n\ttypedef boost::function<void(error_code const&)> handler_type;\n\n\ttemplate <class Handler>\n\tvoid async_connect(endpoint_type const& endpoint, Handler const& handler)\n\t{\n\t\t\/\/ the connect is split up in the following steps:\n\t\t\/\/ 1. connect to peer\n\t\t\/\/ 2. perform SSL client handshake\n\n\t\t\/\/ to avoid unnecessary copying of the handler,\n\t\t\/\/ store it in a shared_ptr\n\t\tboost::shared_ptr<handler_type> h(new handler_type(handler));\n\n\t\tm_sock.next_layer().async_connect(endpoint\n\t\t\t, boost::bind(&ssl_stream::connected, this, _1, h));\n\t}\n\n\ttemplate <class Handler>\n\tvoid async_accept_handshake(Handler const& handler)\n\t{\n\t\t\/\/ this is used for accepting SSL connections\n\t\tboost::shared_ptr<handler_type> h(new handler_type(handler));\n\t\tm_sock.async_handshake(asio::ssl::stream_base::server\n\t\t\t, boost::bind(&ssl_stream::handshake, this, _1, h));\n\t}\n\n\tvoid accept_handshake(error_code& ec)\n\t{\n\t\t\/\/ this is used for accepting SSL connections\n\t\tm_sock.handshake(asio::ssl::stream_base::server, ec);\n\t}\n\n\ttemplate <class Handler>\n\tvoid async_shutdown(Handler const& handler)\n\t{\n\t\tm_sock.async_shutdown(handler);\n\t}\n\n\tvoid shutdown(error_code& ec)\n\t{\n\t\tm_sock.shutdown(ec);\n\t}\n\n\ttemplate <class Mutable_Buffers, class Handler>\n\tvoid async_read_some(Mutable_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tm_sock.async_read_some(buffers, handler);\n\t}\n\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers, error_code& ec)\n\t{\n\t\treturn m_sock.read_some(buffers, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class SettableSocketOption>\n\tvoid set_option(SettableSocketOption const& opt)\n\t{\n\t\tm_sock.next_layer().set_option(opt);\n\t}\n#endif\n\n\ttemplate <class SettableSocketOption>\n\terror_code set_option(SettableSocketOption const& opt, error_code& ec)\n\t{\n\t\treturn m_sock.next_layer().set_option(opt, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class GettableSocketOption>\n\tvoid get_option(GettableSocketOption& opt)\n\t{\n\t\tm_sock.get_option(opt);\n\t}\n#endif\n\n\ttemplate <class GettableSocketOption>\n\terror_code get_option(GettableSocketOption& opt, error_code& ec)\n\t{\n\t\treturn m_sock.get_option(opt, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers)\n\t{\n\t\treturn m_sock.read_some(buffers);\n\t}\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc)\n\t{\n\t\tm_sock.next_layer().io_control(ioc);\n\t}\n#endif\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc, error_code& ec)\n\t{\n\t\tm_sock.next_layer().io_control(ioc, ec);\n\t}\n\n\ttemplate <class Const_Buffers, class Handler>\n\tvoid async_write_some(Const_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tm_sock.async_write_some(buffers, handler);\n\t}\n\n\ttemplate <class Const_Buffers>\n\tstd::size_t write_some(Const_Buffers const& buffers, error_code& ec)\n\t{\n\t\treturn m_sock.write_some(buffers, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tstd::size_t available() const\n\t{ return const_cast<sock_type&>(m_sock).next_layer().available(); }\n#endif\n\n\tstd::size_t available(error_code& ec) const\n\t{ return const_cast<sock_type&>(m_sock).next_layer().available(ec); }\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tvoid bind(endpoint_type const& endpoint)\n\t{\n\t\tm_sock.next_layer().bind(endpoint);\n\t}\n#endif\n\n\tvoid bind(endpoint_type const& endpoint, error_code& ec)\n\t{\n\t\tm_sock.next_layer().bind(endpoint, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tvoid open(protocol_type const& p)\n\t{\n\t\tm_sock.next_layer().open(p);\n\t}\n#endif\n\n\tvoid open(protocol_type const& p, error_code& ec)\n\t{\n\t\tm_sock.next_layer().open(p, ec);\n\t}\n\n\tbool is_open() const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().is_open();\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tvoid close()\n\t{\n\t\tm_sock.next_layer().close();\n\t}\n#endif\n\n\tvoid close(error_code& ec)\n\t{\n\t\tm_sock.next_layer().close(ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tendpoint_type remote_endpoint() const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().remote_endpoint();\n\t}\n#endif\n\n\tendpoint_type remote_endpoint(error_code& ec) const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().remote_endpoint(ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tendpoint_type local_endpoint() const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().local_endpoint();\n\t}\n#endif\n\n\tendpoint_type local_endpoint(error_code& ec) const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().local_endpoint(ec);\n\t}\n\n\tio_service& get_io_service()\n\t{\n\t\treturn m_sock.get_io_service();\n\t}\n\n\tlowest_layer_type& lowest_layer()\n\t{\n\t\treturn m_sock.lowest_layer();\n\t}\n\t\n\tnext_layer_type& next_layer()\n\t{\n\t\treturn m_sock.next_layer();\n\t}\n\nprivate:\n\n\tvoid connected(error_code const& e, boost::shared_ptr<handler_type> h)\n\t{\n\t\tif (e)\n\t\t{\n\t\t\t(*h)(e);\n\t\t\treturn;\n\t\t}\n\n\t\tm_sock.async_handshake(asio::ssl::stream_base::client\n\t\t\t, boost::bind(&ssl_stream::handshake, this, _1, h));\n\t}\n\n\tvoid handshake(error_code const& e, boost::shared_ptr<handler_type> h)\n\t{\n\t\t(*h)(e);\n\t}\n\n\tasio::ssl::stream<Stream> m_sock;\n};\n\n}\n\n#endif\n\n<commit_msg>fix ssl_stream typo<commit_after>\/*\n\nCopyright (c) 2008-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#ifndef TORRENT_SSL_STREAM_HPP_INCLUDED\n#define TORRENT_SSL_STREAM_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include <boost\/bind.hpp>\n#if BOOST_VERSION < 103500\n#include <asio\/ssl.hpp>\n#else\n#include <boost\/asio\/ssl.hpp>\n#endif\n\/\/ openssl seems to believe it owns\n\/\/ this name in every single scope\n#undef set_key\n\nnamespace libtorrent {\n\ntemplate <class Stream>\nclass ssl_stream\n{\npublic:\n\n\texplicit ssl_stream(io_service& io_service, asio::ssl::context& ctx)\n\t\t: m_sock(io_service, ctx)\n\t{\n\t}\n\n\ttypedef typename asio::ssl::stream<Stream> sock_type;\n\ttypedef typename sock_type::next_layer_type next_layer_type;\n\ttypedef typename Stream::lowest_layer_type lowest_layer_type;\n\ttypedef typename Stream::endpoint_type endpoint_type;\n\ttypedef typename Stream::protocol_type protocol_type;\n\n\tvoid set_host_name(std::string name)\n\t{\n#if OPENSSL_VERSION_NUMBER >= 0x90812f\n\t\tSSL_set_tlsext_host_name(m_sock.native_handle(), name.c_str());\n#endif\n\t}\n\n\ttemplate <class T>\n\tvoid set_verify_callback(T const& fun, error_code& ec)\n\t{ m_sock.set_verify_callback(fun, ec); }\n\n#if BOOST_VERSION >= 104700\n\tSSL* native_handle() { return m_sock.native_handle(); }\n#endif\n\n\ttypedef boost::function<void(error_code const&)> handler_type;\n\n\ttemplate <class Handler>\n\tvoid async_connect(endpoint_type const& endpoint, Handler const& handler)\n\t{\n\t\t\/\/ the connect is split up in the following steps:\n\t\t\/\/ 1. connect to peer\n\t\t\/\/ 2. perform SSL client handshake\n\n\t\t\/\/ to avoid unnecessary copying of the handler,\n\t\t\/\/ store it in a shared_ptr\n\t\tboost::shared_ptr<handler_type> h(new handler_type(handler));\n\n\t\tm_sock.next_layer().async_connect(endpoint\n\t\t\t, boost::bind(&ssl_stream::connected, this, _1, h));\n\t}\n\n\ttemplate <class Handler>\n\tvoid async_accept_handshake(Handler const& handler)\n\t{\n\t\t\/\/ this is used for accepting SSL connections\n\t\tboost::shared_ptr<handler_type> h(new handler_type(handler));\n\t\tm_sock.async_handshake(asio::ssl::stream_base::server\n\t\t\t, boost::bind(&ssl_stream::handshake, this, _1, h));\n\t}\n\n\tvoid accept_handshake(error_code& ec)\n\t{\n\t\t\/\/ this is used for accepting SSL connections\n\t\tm_sock.handshake(asio::ssl::stream_base::server, ec);\n\t}\n\n\ttemplate <class Handler>\n\tvoid async_shutdown(Handler const& handler)\n\t{\n\t\tm_sock.async_shutdown(handler);\n\t}\n\n\tvoid shutdown(error_code& ec)\n\t{\n\t\tm_sock.shutdown(ec);\n\t}\n\n\ttemplate <class Mutable_Buffers, class Handler>\n\tvoid async_read_some(Mutable_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tm_sock.async_read_some(buffers, handler);\n\t}\n\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers, error_code& ec)\n\t{\n\t\treturn m_sock.read_some(buffers, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class SettableSocketOption>\n\tvoid set_option(SettableSocketOption const& opt)\n\t{\n\t\tm_sock.next_layer().set_option(opt);\n\t}\n#endif\n\n\ttemplate <class SettableSocketOption>\n\terror_code set_option(SettableSocketOption const& opt, error_code& ec)\n\t{\n\t\treturn m_sock.next_layer().set_option(opt, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class GettableSocketOption>\n\tvoid get_option(GettableSocketOption& opt)\n\t{\n\t\tm_sock.next_layer().get_option(opt);\n\t}\n#endif\n\n\ttemplate <class GettableSocketOption>\n\terror_code get_option(GettableSocketOption& opt, error_code& ec)\n\t{\n\t\treturn m_sock.next_layer().get_option(opt, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers)\n\t{\n\t\treturn m_sock.read_some(buffers);\n\t}\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc)\n\t{\n\t\tm_sock.next_layer().io_control(ioc);\n\t}\n#endif\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc, error_code& ec)\n\t{\n\t\tm_sock.next_layer().io_control(ioc, ec);\n\t}\n\n\ttemplate <class Const_Buffers, class Handler>\n\tvoid async_write_some(Const_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tm_sock.async_write_some(buffers, handler);\n\t}\n\n\ttemplate <class Const_Buffers>\n\tstd::size_t write_some(Const_Buffers const& buffers, error_code& ec)\n\t{\n\t\treturn m_sock.write_some(buffers, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tstd::size_t available() const\n\t{ return const_cast<sock_type&>(m_sock).next_layer().available(); }\n#endif\n\n\tstd::size_t available(error_code& ec) const\n\t{ return const_cast<sock_type&>(m_sock).next_layer().available(ec); }\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tvoid bind(endpoint_type const& endpoint)\n\t{\n\t\tm_sock.next_layer().bind(endpoint);\n\t}\n#endif\n\n\tvoid bind(endpoint_type const& endpoint, error_code& ec)\n\t{\n\t\tm_sock.next_layer().bind(endpoint, ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tvoid open(protocol_type const& p)\n\t{\n\t\tm_sock.next_layer().open(p);\n\t}\n#endif\n\n\tvoid open(protocol_type const& p, error_code& ec)\n\t{\n\t\tm_sock.next_layer().open(p, ec);\n\t}\n\n\tbool is_open() const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().is_open();\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tvoid close()\n\t{\n\t\tm_sock.next_layer().close();\n\t}\n#endif\n\n\tvoid close(error_code& ec)\n\t{\n\t\tm_sock.next_layer().close(ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tendpoint_type remote_endpoint() const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().remote_endpoint();\n\t}\n#endif\n\n\tendpoint_type remote_endpoint(error_code& ec) const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().remote_endpoint(ec);\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tendpoint_type local_endpoint() const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().local_endpoint();\n\t}\n#endif\n\n\tendpoint_type local_endpoint(error_code& ec) const\n\t{\n\t\treturn const_cast<sock_type&>(m_sock).next_layer().local_endpoint(ec);\n\t}\n\n\tio_service& get_io_service()\n\t{\n\t\treturn m_sock.get_io_service();\n\t}\n\n\tlowest_layer_type& lowest_layer()\n\t{\n\t\treturn m_sock.lowest_layer();\n\t}\n\t\n\tnext_layer_type& next_layer()\n\t{\n\t\treturn m_sock.next_layer();\n\t}\n\nprivate:\n\n\tvoid connected(error_code const& e, boost::shared_ptr<handler_type> h)\n\t{\n\t\tif (e)\n\t\t{\n\t\t\t(*h)(e);\n\t\t\treturn;\n\t\t}\n\n\t\tm_sock.async_handshake(asio::ssl::stream_base::client\n\t\t\t, boost::bind(&ssl_stream::handshake, this, _1, h));\n\t}\n\n\tvoid handshake(error_code const& e, boost::shared_ptr<handler_type> h)\n\t{\n\t\t(*h)(e);\n\t}\n\n\tasio::ssl::stream<Stream> m_sock;\n};\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2009, 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#ifndef TORRENT_UTP_STREAM_HPP_INCLUDED\n#define TORRENT_UTP_STREAM_HPP_INCLUDED\n\n#include \"libtorrent\/connection_queue.hpp\"\n#include \"libtorrent\/proxy_base.hpp\"\n#include \"libtorrent\/udp_socket.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/packet_buffer.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\n#include <boost\/bind.hpp>\n#include <boost\/function\/function1.hpp>\n#include <boost\/function\/function2.hpp>\n\n#define CCONTROL_TARGET 100\n\nnamespace libtorrent\n{\n\tstruct utp_socket_manager;\n\n\t\/\/ some MTU and protocol header sizes constants\n\tenum\n\t{\n\t\tTORRENT_IPV4_HEADER = 20,\n\t\tTORRENT_IPV6_HEADER = 40,\n\t\tTORRENT_UDP_HEADER = 8,\n\t\tTORRENT_SOCKS5_HEADER = 6, \/\/ plus the size of the destination address\n\n\t\tTORRENT_ETHERNET_MTU = 1500,\n\t\tTORRENT_TEREDO_MTU = 1280,\n\t\tTORRENT_INET_MIN_MTU = 576,\n\t\tTORRENT_INET_MAX_MTU = 0xffff\n\t};\n\n\t\/\/ the point of the bif_endian_int is two-fold\n\t\/\/ one purpuse is to not have any alignment requirements\n\t\/\/ so that any byffer received from the network can be cast\n\t\/\/ to it and read as an integer of various sizes without\n\t\/\/ triggering a bus error. The other purpose is to convert\n\t\/\/ from network byte order to host byte order when read and\n\t\/\/ written, to offer a convenient interface to both interpreting\n\t\/\/ and writing network packets\n\ttemplate <class T> struct big_endian_int\n\t{\n\t\tbig_endian_int& operator=(T v)\n\t\t{\n\t\t\tchar* p = m_storage;\n\t\t\tdetail::write_impl(v, p);\n\t\t\treturn *this;\n\t\t}\n\t\toperator T() const\n\t\t{\n\t\t\tconst char* p = m_storage;\n\t\t\treturn detail::read_impl(p, detail::type<T>());\n\t\t}\n\tprivate:\n\t\tchar m_storage[sizeof(T)];\n\t};\n\n\ttypedef big_endian_int<boost::uint64_t> be_uint64;\n\ttypedef big_endian_int<boost::uint32_t> be_uint32;\n\ttypedef big_endian_int<boost::uint16_t> be_uint16;\n\ttypedef big_endian_int<boost::int64_t> be_int64;\n\ttypedef big_endian_int<boost::int32_t> be_int32;\n\ttypedef big_endian_int<boost::int16_t> be_int16;\n\n\/*\n\tuTP header from BEP 29\n\n\t0 4 8 16 24 32\n\t+-------+-------+---------------+---------------+---------------+\n\t| type | ver | extension | connection_id |\n\t+-------+-------+---------------+---------------+---------------+\n\t| timestamp_microseconds |\n\t+---------------+---------------+---------------+---------------+\n\t| timestamp_difference_microseconds |\n\t+---------------+---------------+---------------+---------------+\n\t| wnd_size |\n\t+---------------+---------------+---------------+---------------+\n\t| seq_nr | ack_nr |\n\t+---------------+---------------+---------------+---------------+\n\n*\/\n\n\tenum type { ST_DATA = 0, ST_FIN, ST_STATE, ST_RESET, ST_SYN, NUM_TYPES };\n\n\tstruct utp_header\n\t{\n\t\tunsigned char type_ver;\n\t\tunsigned char extension;\n\t\tbe_uint16 connection_id;\n\t\tbe_uint32 timestamp_microseconds;\n\t\tbe_uint32 timestamp_difference_microseconds;\n\t\tbe_uint32 wnd_size;\n\t\tbe_uint16 seq_nr;\n\t\tbe_uint16 ack_nr;\n\n\t\tint get_type() const { return type_ver >> 4; }\n\t\tint get_version() const { return type_ver & 0xf; }\n\t};\n\nstruct utp_socket_impl;\n\nutp_socket_impl* construct_utp_impl(boost::uint16_t recv_id\n\t, boost::uint16_t send_id, void* userdata\n\t, utp_socket_manager* sm);\nvoid detach_utp_impl(utp_socket_impl* s);\nvoid delete_utp_impl(utp_socket_impl* s);\nbool should_delete(utp_socket_impl* s);\nvoid tick_utp_impl(utp_socket_impl* s, ptime const& now);\nvoid utp_init_mtu(utp_socket_impl* s, int link_mtu, int utp_mtu);\nbool utp_incoming_packet(utp_socket_impl* s, char const* p\n\t, int size, udp::endpoint const& ep, ptime receive_time);\nbool utp_match(utp_socket_impl* s, udp::endpoint const& ep, boost::uint16_t id);\nudp::endpoint utp_remote_endpoint(utp_socket_impl* s);\nboost::uint16_t utp_receive_id(utp_socket_impl* s);\nint utp_socket_state(utp_socket_impl const* s);\n\n#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING\nint socket_impl_size();\n#endif\n\n\/\/ this is the user-level stream interface to utp sockets.\n\/\/ the reason why it's split up in a utp_stream class and\n\/\/ an implementation class is because the socket state has\n\/\/ to be able to out-live the user level socket. For instance\n\/\/ when sending data on a stream and then closing it, the\n\/\/ state holding the send buffer has to be kept around until\n\/\/ it has been flushed, which may be longer than the client\n\/\/ will keep the utp_stream object around for.\n\/\/ for more details, see utp_socket_impl, which is analogous\n\/\/ to the kernel state for a socket. It's defined in utp_stream.cpp\nclass TORRENT_EXPORT utp_stream\n{\npublic:\n\n\ttypedef stream_socket::endpoint_type endpoint_type;\n\ttypedef stream_socket::protocol_type protocol_type;\n\n\texplicit utp_stream(asio::io_service& io_service);\n\t~utp_stream();\n\n\t\/\/ used for incoming connections\n\tvoid set_impl(utp_socket_impl* s);\n\tutp_socket_impl* get_impl();\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc) {}\n#endif\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc, error_code& ec) {}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tvoid bind(endpoint_type const& endpoint) {}\n#endif\n\n\tvoid bind(endpoint_type const& endpoint, error_code& ec);\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class SettableSocketOption>\n\tvoid set_option(SettableSocketOption const& opt) {}\n#endif\n\n\ttemplate <class SettableSocketOption>\n\terror_code set_option(SettableSocketOption const& opt, error_code& ec) { return ec; }\n\n\tvoid close();\n\tvoid close(error_code const& ec) { close(); }\n\tbool is_open() const { return m_open; }\n\n\tint read_buffer_size() const;\n\tstatic void on_read(void* self, size_t bytes_transferred, error_code const& ec, bool kill);\n\tstatic void on_write(void* self, size_t bytes_transferred, error_code const& ec, bool kill);\n\tstatic void on_connect(void* self, error_code const& ec, bool kill);\n\n\ttypedef void(*handler_t)(void*, size_t, error_code const&, bool);\n\ttypedef void(*connect_handler_t)(void*, error_code const&, bool);\n\n\tvoid add_read_buffer(void* buf, size_t len);\n\tvoid set_read_handler(handler_t h);\n\tvoid add_write_buffer(void const* buf, size_t len);\n\tvoid set_write_handler(handler_t h);\n\tsize_t read_some(bool clear_buffers);\n\t\n\tvoid do_connect(tcp::endpoint const& ep, connect_handler_t h);\n\n\tendpoint_type local_endpoint() const\n\t{\n\t\terror_code ec;\n\t\treturn local_endpoint(ec);\n\t}\n\n\tendpoint_type local_endpoint(error_code& ec) const;\n\n\tendpoint_type remote_endpoint() const\n\t{\n\t\terror_code ec;\n\t\treturn remote_endpoint(ec);\n\t}\n\n\tendpoint_type remote_endpoint(error_code& ec) const;\n\n\tstd::size_t available() const;\n\tstd::size_t available(error_code& ec) const { return available(); }\n\n\tasio::io_service& io_service()\n\t{ return m_io_service; }\n\n\ttemplate <class Handler>\n\tvoid async_connect(endpoint_type const& endpoint, Handler const& handler)\n\t{\n\t\tif (!endpoint.address().is_v4())\n\t\t{\n\t\t\terror_code ec = asio::error::operation_not_supported;\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tif (m_impl == 0)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tm_connect_handler = handler;\n\t\tdo_connect(endpoint, &utp_stream::on_connect);\n\t}\n\t\n\ttemplate <class Mutable_Buffers, class Handler>\n\tvoid async_read_some(Mutable_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tif (m_impl == 0)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tTORRENT_ASSERT(!m_read_handler);\n\t\tif (m_read_handler)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));\n\t\t\treturn;\n\t\t}\n\t\tfor (typename Mutable_Buffers::const_iterator i = buffers.begin()\n\t\t\t, end(buffers.end()); i != end; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(buffer_size(*i) > 0);\n\t\t\tusing asio::buffer_cast;\n\t\t\tusing asio::buffer_size;\n\t\t\tadd_read_buffer(buffer_cast<void*>(*i), buffer_size(*i));\n\t\t}\n\t\tm_read_handler = handler;\n\t\tset_read_handler(&utp_stream::on_read);\n\t}\n\n\tvoid do_async_connect(endpoint_type const& ep\n\t\t, boost::function<void(error_code const&)> const& handler);\n\n\ttemplate <class Protocol>\n\tvoid open(Protocol const& p, error_code& ec)\n\t{ m_open = true; }\n\n\ttemplate <class Protocol>\n\tvoid open(Protocol const& p)\n\t{ m_open = true; }\n\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers, error_code& ec)\n\t{\n\t\tTORRENT_ASSERT(!m_read_handler);\n\t\tif (m_impl == 0)\n\t\t{\n\t\t\tec = asio::error::not_connected;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (read_buffer_size() == 0)\n\t\t{\n\t\t\tec = asio::error::would_block;\n\t\t\treturn 0;\n\t\t}\n#ifdef TORRENT_DEBUG\n\t\tsize_t buf_size = 0;\n#endif\n\n\t\tfor (typename Mutable_Buffers::const_iterator i = buffers.begin()\n\t\t\t, end(buffers.end()); i != end; ++i)\n\t\t{\n\t\t\tusing asio::buffer_cast;\n\t\t\tusing asio::buffer_size;\n\t\t\tadd_read_buffer(buffer_cast<void*>(*i), buffer_size(*i));\n#ifdef TORRENT_DEBUG\n\t\t\tbuf_size += buffer_size(*i);\n#endif\n\t\t}\n\t\tstd::size_t ret = read_some(true);\n\t\tTORRENT_ASSERT(int(ret) <= buf_size);\n\t\tTORRENT_ASSERT(ret > 0);\n\t\treturn ret;\n\t}\n\n\ttemplate <class Const_Buffers>\n\tstd::size_t write_some(Const_Buffers const& buffers, error_code& ec)\n\t{\n\t\t\/\/ TODO: implement\n\t\treturn 0;\n\t}\n\n\ttemplate <class Const_Buffers, class Handler>\n\tvoid async_write_some(Const_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tif (m_impl == 0)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tTORRENT_ASSERT(!m_write_handler);\n\t\tif (m_write_handler)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tfor (typename Const_Buffers::const_iterator i = buffers.begin()\n\t\t\t, end(buffers.end()); i != end; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(buffer_size(*i) > 0);\n\t\t\tusing asio::buffer_cast;\n\t\t\tusing asio::buffer_size;\n\t\t\tadd_write_buffer((void*)buffer_cast<void const*>(*i), buffer_size(*i));\n\t\t}\n\t\tm_write_handler = handler;\n\t\tset_write_handler(&utp_stream::on_write);\n\t}\n\n\/\/private:\n\n\tvoid cancel_handlers(error_code const&);\n\n\tboost::function1<void, error_code const&> m_connect_handler;\n\tboost::function2<void, error_code const&, std::size_t> m_read_handler;\n\tboost::function2<void, error_code const&, std::size_t> m_write_handler;\n\n\tasio::io_service& m_io_service;\n\tutp_socket_impl* m_impl;\n\tbool m_open;\n};\n\n}\n\n#endif\n<commit_msg>fix warning in utp_stream<commit_after>\/*\n\nCopyright (c) 2009, 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#ifndef TORRENT_UTP_STREAM_HPP_INCLUDED\n#define TORRENT_UTP_STREAM_HPP_INCLUDED\n\n#include \"libtorrent\/connection_queue.hpp\"\n#include \"libtorrent\/proxy_base.hpp\"\n#include \"libtorrent\/udp_socket.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/packet_buffer.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\n#include <boost\/bind.hpp>\n#include <boost\/function\/function1.hpp>\n#include <boost\/function\/function2.hpp>\n\n#define CCONTROL_TARGET 100\n\nnamespace libtorrent\n{\n\tstruct utp_socket_manager;\n\n\t\/\/ some MTU and protocol header sizes constants\n\tenum\n\t{\n\t\tTORRENT_IPV4_HEADER = 20,\n\t\tTORRENT_IPV6_HEADER = 40,\n\t\tTORRENT_UDP_HEADER = 8,\n\t\tTORRENT_SOCKS5_HEADER = 6, \/\/ plus the size of the destination address\n\n\t\tTORRENT_ETHERNET_MTU = 1500,\n\t\tTORRENT_TEREDO_MTU = 1280,\n\t\tTORRENT_INET_MIN_MTU = 576,\n\t\tTORRENT_INET_MAX_MTU = 0xffff\n\t};\n\n\t\/\/ the point of the bif_endian_int is two-fold\n\t\/\/ one purpuse is to not have any alignment requirements\n\t\/\/ so that any byffer received from the network can be cast\n\t\/\/ to it and read as an integer of various sizes without\n\t\/\/ triggering a bus error. The other purpose is to convert\n\t\/\/ from network byte order to host byte order when read and\n\t\/\/ written, to offer a convenient interface to both interpreting\n\t\/\/ and writing network packets\n\ttemplate <class T> struct big_endian_int\n\t{\n\t\tbig_endian_int& operator=(T v)\n\t\t{\n\t\t\tchar* p = m_storage;\n\t\t\tdetail::write_impl(v, p);\n\t\t\treturn *this;\n\t\t}\n\t\toperator T() const\n\t\t{\n\t\t\tconst char* p = m_storage;\n\t\t\treturn detail::read_impl(p, detail::type<T>());\n\t\t}\n\tprivate:\n\t\tchar m_storage[sizeof(T)];\n\t};\n\n\ttypedef big_endian_int<boost::uint64_t> be_uint64;\n\ttypedef big_endian_int<boost::uint32_t> be_uint32;\n\ttypedef big_endian_int<boost::uint16_t> be_uint16;\n\ttypedef big_endian_int<boost::int64_t> be_int64;\n\ttypedef big_endian_int<boost::int32_t> be_int32;\n\ttypedef big_endian_int<boost::int16_t> be_int16;\n\n\/*\n\tuTP header from BEP 29\n\n\t0 4 8 16 24 32\n\t+-------+-------+---------------+---------------+---------------+\n\t| type | ver | extension | connection_id |\n\t+-------+-------+---------------+---------------+---------------+\n\t| timestamp_microseconds |\n\t+---------------+---------------+---------------+---------------+\n\t| timestamp_difference_microseconds |\n\t+---------------+---------------+---------------+---------------+\n\t| wnd_size |\n\t+---------------+---------------+---------------+---------------+\n\t| seq_nr | ack_nr |\n\t+---------------+---------------+---------------+---------------+\n\n*\/\n\n\tenum type { ST_DATA = 0, ST_FIN, ST_STATE, ST_RESET, ST_SYN, NUM_TYPES };\n\n\tstruct utp_header\n\t{\n\t\tunsigned char type_ver;\n\t\tunsigned char extension;\n\t\tbe_uint16 connection_id;\n\t\tbe_uint32 timestamp_microseconds;\n\t\tbe_uint32 timestamp_difference_microseconds;\n\t\tbe_uint32 wnd_size;\n\t\tbe_uint16 seq_nr;\n\t\tbe_uint16 ack_nr;\n\n\t\tint get_type() const { return type_ver >> 4; }\n\t\tint get_version() const { return type_ver & 0xf; }\n\t};\n\nstruct utp_socket_impl;\n\nutp_socket_impl* construct_utp_impl(boost::uint16_t recv_id\n\t, boost::uint16_t send_id, void* userdata\n\t, utp_socket_manager* sm);\nvoid detach_utp_impl(utp_socket_impl* s);\nvoid delete_utp_impl(utp_socket_impl* s);\nbool should_delete(utp_socket_impl* s);\nvoid tick_utp_impl(utp_socket_impl* s, ptime const& now);\nvoid utp_init_mtu(utp_socket_impl* s, int link_mtu, int utp_mtu);\nbool utp_incoming_packet(utp_socket_impl* s, char const* p\n\t, int size, udp::endpoint const& ep, ptime receive_time);\nbool utp_match(utp_socket_impl* s, udp::endpoint const& ep, boost::uint16_t id);\nudp::endpoint utp_remote_endpoint(utp_socket_impl* s);\nboost::uint16_t utp_receive_id(utp_socket_impl* s);\nint utp_socket_state(utp_socket_impl const* s);\n\n#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING\nint socket_impl_size();\n#endif\n\n\/\/ this is the user-level stream interface to utp sockets.\n\/\/ the reason why it's split up in a utp_stream class and\n\/\/ an implementation class is because the socket state has\n\/\/ to be able to out-live the user level socket. For instance\n\/\/ when sending data on a stream and then closing it, the\n\/\/ state holding the send buffer has to be kept around until\n\/\/ it has been flushed, which may be longer than the client\n\/\/ will keep the utp_stream object around for.\n\/\/ for more details, see utp_socket_impl, which is analogous\n\/\/ to the kernel state for a socket. It's defined in utp_stream.cpp\nclass TORRENT_EXPORT utp_stream\n{\npublic:\n\n\ttypedef stream_socket::endpoint_type endpoint_type;\n\ttypedef stream_socket::protocol_type protocol_type;\n\n\texplicit utp_stream(asio::io_service& io_service);\n\t~utp_stream();\n\n\t\/\/ used for incoming connections\n\tvoid set_impl(utp_socket_impl* s);\n\tutp_socket_impl* get_impl();\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc) {}\n#endif\n\n\ttemplate <class IO_Control_Command>\n\tvoid io_control(IO_Control_Command& ioc, error_code& ec) {}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\tvoid bind(endpoint_type const& endpoint) {}\n#endif\n\n\tvoid bind(endpoint_type const& endpoint, error_code& ec);\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttemplate <class SettableSocketOption>\n\tvoid set_option(SettableSocketOption const& opt) {}\n#endif\n\n\ttemplate <class SettableSocketOption>\n\terror_code set_option(SettableSocketOption const& opt, error_code& ec) { return ec; }\n\n\tvoid close();\n\tvoid close(error_code const& ec) { close(); }\n\tbool is_open() const { return m_open; }\n\n\tint read_buffer_size() const;\n\tstatic void on_read(void* self, size_t bytes_transferred, error_code const& ec, bool kill);\n\tstatic void on_write(void* self, size_t bytes_transferred, error_code const& ec, bool kill);\n\tstatic void on_connect(void* self, error_code const& ec, bool kill);\n\n\ttypedef void(*handler_t)(void*, size_t, error_code const&, bool);\n\ttypedef void(*connect_handler_t)(void*, error_code const&, bool);\n\n\tvoid add_read_buffer(void* buf, size_t len);\n\tvoid set_read_handler(handler_t h);\n\tvoid add_write_buffer(void const* buf, size_t len);\n\tvoid set_write_handler(handler_t h);\n\tsize_t read_some(bool clear_buffers);\n\t\n\tvoid do_connect(tcp::endpoint const& ep, connect_handler_t h);\n\n\tendpoint_type local_endpoint() const\n\t{\n\t\terror_code ec;\n\t\treturn local_endpoint(ec);\n\t}\n\n\tendpoint_type local_endpoint(error_code& ec) const;\n\n\tendpoint_type remote_endpoint() const\n\t{\n\t\terror_code ec;\n\t\treturn remote_endpoint(ec);\n\t}\n\n\tendpoint_type remote_endpoint(error_code& ec) const;\n\n\tstd::size_t available() const;\n\tstd::size_t available(error_code& ec) const { return available(); }\n\n\tasio::io_service& io_service()\n\t{ return m_io_service; }\n\n\ttemplate <class Handler>\n\tvoid async_connect(endpoint_type const& endpoint, Handler const& handler)\n\t{\n\t\tif (!endpoint.address().is_v4())\n\t\t{\n\t\t\terror_code ec = asio::error::operation_not_supported;\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tif (m_impl == 0)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tm_connect_handler = handler;\n\t\tdo_connect(endpoint, &utp_stream::on_connect);\n\t}\n\t\n\ttemplate <class Mutable_Buffers, class Handler>\n\tvoid async_read_some(Mutable_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tif (m_impl == 0)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tTORRENT_ASSERT(!m_read_handler);\n\t\tif (m_read_handler)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));\n\t\t\treturn;\n\t\t}\n\t\tfor (typename Mutable_Buffers::const_iterator i = buffers.begin()\n\t\t\t, end(buffers.end()); i != end; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(buffer_size(*i) > 0);\n\t\t\tusing asio::buffer_cast;\n\t\t\tusing asio::buffer_size;\n\t\t\tadd_read_buffer(buffer_cast<void*>(*i), buffer_size(*i));\n\t\t}\n\t\tm_read_handler = handler;\n\t\tset_read_handler(&utp_stream::on_read);\n\t}\n\n\tvoid do_async_connect(endpoint_type const& ep\n\t\t, boost::function<void(error_code const&)> const& handler);\n\n\ttemplate <class Protocol>\n\tvoid open(Protocol const& p, error_code& ec)\n\t{ m_open = true; }\n\n\ttemplate <class Protocol>\n\tvoid open(Protocol const& p)\n\t{ m_open = true; }\n\n\ttemplate <class Mutable_Buffers>\n\tstd::size_t read_some(Mutable_Buffers const& buffers, error_code& ec)\n\t{\n\t\tTORRENT_ASSERT(!m_read_handler);\n\t\tif (m_impl == 0)\n\t\t{\n\t\t\tec = asio::error::not_connected;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (read_buffer_size() == 0)\n\t\t{\n\t\t\tec = asio::error::would_block;\n\t\t\treturn 0;\n\t\t}\n#ifdef TORRENT_DEBUG\n\t\tsize_t buf_size = 0;\n#endif\n\n\t\tfor (typename Mutable_Buffers::const_iterator i = buffers.begin()\n\t\t\t, end(buffers.end()); i != end; ++i)\n\t\t{\n\t\t\tusing asio::buffer_cast;\n\t\t\tusing asio::buffer_size;\n\t\t\tadd_read_buffer(buffer_cast<void*>(*i), buffer_size(*i));\n#ifdef TORRENT_DEBUG\n\t\t\tbuf_size += buffer_size(*i);\n#endif\n\t\t}\n\t\tstd::size_t ret = read_some(true);\n\t\tTORRENT_ASSERT(ret <= buf_size);\n\t\tTORRENT_ASSERT(ret > 0);\n\t\treturn ret;\n\t}\n\n\ttemplate <class Const_Buffers>\n\tstd::size_t write_some(Const_Buffers const& buffers, error_code& ec)\n\t{\n\t\t\/\/ TODO: implement\n\t\treturn 0;\n\t}\n\n\ttemplate <class Const_Buffers, class Handler>\n\tvoid async_write_some(Const_Buffers const& buffers, Handler const& handler)\n\t{\n\t\tif (m_impl == 0)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tTORRENT_ASSERT(!m_write_handler);\n\t\tif (m_write_handler)\n\t\t{\n\t\t\tm_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tfor (typename Const_Buffers::const_iterator i = buffers.begin()\n\t\t\t, end(buffers.end()); i != end; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(buffer_size(*i) > 0);\n\t\t\tusing asio::buffer_cast;\n\t\t\tusing asio::buffer_size;\n\t\t\tadd_write_buffer((void*)buffer_cast<void const*>(*i), buffer_size(*i));\n\t\t}\n\t\tm_write_handler = handler;\n\t\tset_write_handler(&utp_stream::on_write);\n\t}\n\n\/\/private:\n\n\tvoid cancel_handlers(error_code const&);\n\n\tboost::function1<void, error_code const&> m_connect_handler;\n\tboost::function2<void, error_code const&, std::size_t> m_read_handler;\n\tboost::function2<void, error_code const&, std::size_t> m_write_handler;\n\n\tasio::io_service& m_io_service;\n\tutp_socket_impl* m_impl;\n\tbool m_open;\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_MARKER_HELPERS_HPP\n#define MAPNIK_MARKER_HELPERS_HPP\n\n#include <mapnik\/feature.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/geometry_type.hpp>\n#include <mapnik\/geometry_centroid.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/svg\/svg_path_attributes.hpp>\n#include <mapnik\/marker.hpp> \/\/ for svg_storage_type\n#include <mapnik\/markers_placement.hpp>\n#include <mapnik\/attribute.hpp>\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/vertex_processor.hpp>\n#include <mapnik\/renderer_common\/apply_vertex_converter.hpp>\n#include <mapnik\/renderer_common\/render_markers_symbolizer.hpp>\n\n\/\/ agg\n#include \"agg_trans_affine.h\"\n\n\/\/ stl\n#include <memory>\n\nnamespace mapnik {\n\nstruct clip_poly_tag;\n\nusing svg_attribute_type = agg::pod_bvector<svg::path_attributes>;\n\ntemplate <typename Detector>\nstruct vector_markers_dispatch : util::noncopyable\n{\n vector_markers_dispatch(svg_path_ptr const& src,\n svg_path_adapter & path,\n svg_attribute_type const& attrs,\n agg::trans_affine const& marker_trans,\n symbolizer_base const& sym,\n Detector & detector,\n double scale_factor,\n feature_impl const& feature,\n attributes const& vars,\n bool snap_to_pixels,\n markers_renderer_context & renderer_context)\n : params_(src->bounding_box(), recenter(src) * marker_trans,\n sym, feature, vars, scale_factor, snap_to_pixels)\n , renderer_context_(renderer_context)\n , src_(src)\n , path_(path)\n , attrs_(attrs)\n , detector_(detector)\n {}\n\n template <typename T>\n void add_path(T & path)\n {\n markers_placement_finder<T, Detector> placement_finder(\n params_.placement_method, path, detector_, params_.placement_params);\n double x, y, angle = .0;\n while (placement_finder.get_point(x, y, angle, params_.ignore_placement))\n {\n agg::trans_affine matrix = params_.placement_params.tr;\n matrix.rotate(angle);\n matrix.translate(x, y);\n renderer_context_.render_marker(src_, path_, attrs_, params_, matrix);\n }\n }\n\nprotected:\n static agg::trans_affine recenter(svg_path_ptr const& src)\n {\n coord2d center = src->bounding_box().center();\n return agg::trans_affine_translation(-center.x, -center.y);\n }\n\n markers_dispatch_params params_;\n markers_renderer_context & renderer_context_;\n svg_path_ptr const& src_;\n svg_path_adapter & path_;\n svg_attribute_type const& attrs_;\n Detector & detector_;\n};\n\ntemplate <typename Detector>\nstruct raster_markers_dispatch : util::noncopyable\n{\n raster_markers_dispatch(image_rgba8 const& src,\n agg::trans_affine const& marker_trans,\n symbolizer_base const& sym,\n Detector & detector,\n double scale_factor,\n feature_impl const& feature,\n attributes const& vars,\n markers_renderer_context & renderer_context)\n : params_(box2d<double>(0, 0, src.width(), src.height()),\n marker_trans, sym, feature, vars, scale_factor)\n , renderer_context_(renderer_context)\n , src_(src)\n , detector_(detector)\n {}\n\n template <typename T>\n void add_path(T & path)\n {\n markers_placement_finder<T, Detector> placement_finder(\n params_.placement_method, path, detector_, params_.placement_params);\n double x, y, angle = .0;\n while (placement_finder.get_point(x, y, angle, params_.ignore_placement))\n {\n agg::trans_affine matrix = params_.placement_params.tr;\n matrix.rotate(angle);\n matrix.translate(x, y);\n renderer_context_.render_marker(src_, params_, matrix);\n }\n }\n\nprotected:\n markers_dispatch_params params_;\n markers_renderer_context & renderer_context_;\n image_rgba8 const& src_;\n Detector & detector_;\n};\n\nvoid build_ellipse(symbolizer_base const& sym, mapnik::feature_impl & feature, attributes const& vars,\n svg_storage_type & marker_ellipse, svg::svg_path_adapter & svg_path);\n\nbool push_explicit_style(svg_attribute_type const& src,\n svg_attribute_type & dst,\n symbolizer_base const& sym,\n feature_impl & feature,\n attributes const& vars);\n\nvoid setup_transform_scaling(agg::trans_affine & tr,\n double svg_width,\n double svg_height,\n mapnik::feature_impl & feature,\n attributes const& vars,\n symbolizer_base const& sym);\n\n\/\/ Apply markers to a feature with multiple geometries\ntemplate <typename Converter, typename Processor>\nvoid apply_markers_single(Converter & converter, Processor & proc, geometry::geometry<double> const& geom, geometry::geometry_types type)\n{\n if (type == geometry::geometry_types::Point)\n {\n geometry::point_vertex_adapter<double> va(geom.get<geometry::point<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::LineString)\n {\n geometry::line_string_vertex_adapter<double> va(geom.get<geometry::line_string<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::Polygon)\n {\n geometry::polygon_vertex_adapter<double> va(geom.get<geometry::polygon<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::MultiPoint)\n {\n for (auto const& pt : geom.get<geometry::multi_point<double>>())\n {\n geometry::point_vertex_adapter<double> va(pt);\n converter.apply(va, proc);\n }\n }\n else if (type == geometry::geometry_types::MultiLineString)\n {\n for (auto const& line : geom.get<geometry::multi_line_string<double>>())\n {\n geometry::line_string_vertex_adapter<double> va(line);\n converter.apply(va, proc);\n }\n }\n else if (type == geometry::geometry_types::MultiPolygon)\n {\n for (auto const& poly : geom.get<geometry::multi_polygon<double>>())\n {\n geometry::polygon_vertex_adapter<double> va(poly);\n converter.apply(va, proc);\n }\n }\n}\n\ntemplate <typename Converter, typename Processor>\nvoid apply_markers_multi(feature_impl const& feature, attributes const& vars, Converter & converter, Processor & proc, symbolizer_base const& sym)\n{\n using apply_vertex_converter_type = detail::apply_vertex_converter<Converter,Processor>;\n apply_vertex_converter_type apply(converter, proc);\n auto const& geom = feature.get_geometry();\n geometry::geometry_types type = geometry::geometry_type(geom);\n\n if (type == geometry::geometry_types::Point\n ||\n type == geometry::geometry_types::LineString\n ||\n type == geometry::geometry_types::Polygon)\n {\n apply_markers_single(converter, proc, geom, type);\n }\n else\n {\n\n marker_multi_policy_enum multi_policy = get<marker_multi_policy_enum, keys::markers_multipolicy>(sym, feature, vars);\n marker_placement_enum placement = get<marker_placement_enum, keys::markers_placement_type>(sym, feature, vars);\n\n if (placement == MARKER_POINT_PLACEMENT &&\n multi_policy == MARKER_WHOLE_MULTI)\n {\n geometry::point<double> pt;\n \/\/ test if centroid is contained by bounding box\n if (geometry::centroid(geom, pt) && converter.disp_.args_.bbox.contains(pt.x, pt.y))\n {\n \/\/ unset any clipping since we're now dealing with a point\n converter.template unset<clip_poly_tag>();\n geometry::point_vertex_adapter<double> va(pt);\n converter.apply(va, proc);\n }\n }\n else if ((placement == MARKER_POINT_PLACEMENT || placement == MARKER_INTERIOR_PLACEMENT) &&\n multi_policy == MARKER_LARGEST_MULTI)\n {\n \/\/ Only apply to path with largest envelope area\n \/\/ TODO: consider using true area for polygon types\n if (type == geometry::geometry_types::MultiPolygon)\n {\n geometry::multi_polygon<double> const& multi_poly = mapnik::util::get<geometry::multi_polygon<double> >(geom);\n double maxarea = 0;\n geometry::polygon<double> const* largest = 0;\n for (geometry::polygon<double> const& poly : multi_poly)\n {\n box2d<double> bbox = geometry::envelope(poly);\n double area = bbox.width() * bbox.height();\n if (area > maxarea)\n {\n maxarea = area;\n largest = &poly;\n }\n }\n if (largest)\n {\n geometry::polygon_vertex_adapter<double> va(*largest);\n converter.apply(va, proc);\n }\n }\n else\n {\n MAPNIK_LOG_WARN(marker_symbolizer) << \"TODO: if you get here -> open an issue\";\n }\n }\n else\n {\n if (multi_policy != MARKER_EACH_MULTI && placement != MARKER_POINT_PLACEMENT)\n {\n MAPNIK_LOG_WARN(marker_symbolizer) << \"marker_multi_policy != 'each' has no effect with marker_placement != 'point'\";\n }\n if (type == geometry::geometry_types::GeometryCollection)\n {\n for (auto const& g : geom.get<geometry::geometry_collection<double>>())\n {\n apply_markers_single(converter, proc, g, geometry::geometry_type(g));\n }\n }\n else\n {\n apply_markers_single(converter, proc, geom, type);\n }\n }\n }\n}\n\n}\n\n#endif \/\/MAPNIK_MARKER_HELPERS_HPP\n<commit_msg>remove unused vars\/cleanup<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_MARKER_HELPERS_HPP\n#define MAPNIK_MARKER_HELPERS_HPP\n\n#include <mapnik\/feature.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/geometry_type.hpp>\n#include <mapnik\/geometry_centroid.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/svg\/svg_path_attributes.hpp>\n#include <mapnik\/marker.hpp> \/\/ for svg_storage_type\n#include <mapnik\/markers_placement.hpp>\n#include <mapnik\/attribute.hpp>\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/vertex_processor.hpp>\n#include <mapnik\/renderer_common\/apply_vertex_converter.hpp>\n#include <mapnik\/renderer_common\/render_markers_symbolizer.hpp>\n\n\/\/ agg\n#include \"agg_trans_affine.h\"\n\n\/\/ stl\n#include <memory>\n\nnamespace mapnik {\n\nstruct clip_poly_tag;\n\nusing svg_attribute_type = agg::pod_bvector<svg::path_attributes>;\n\ntemplate <typename Detector>\nstruct vector_markers_dispatch : util::noncopyable\n{\n vector_markers_dispatch(svg_path_ptr const& src,\n svg_path_adapter & path,\n svg_attribute_type const& attrs,\n agg::trans_affine const& marker_trans,\n symbolizer_base const& sym,\n Detector & detector,\n double scale_factor,\n feature_impl const& feature,\n attributes const& vars,\n bool snap_to_pixels,\n markers_renderer_context & renderer_context)\n : params_(src->bounding_box(), recenter(src) * marker_trans,\n sym, feature, vars, scale_factor, snap_to_pixels)\n , renderer_context_(renderer_context)\n , src_(src)\n , path_(path)\n , attrs_(attrs)\n , detector_(detector)\n {}\n\n template <typename T>\n void add_path(T & path)\n {\n markers_placement_finder<T, Detector> placement_finder(\n params_.placement_method, path, detector_, params_.placement_params);\n double x, y, angle = .0;\n while (placement_finder.get_point(x, y, angle, params_.ignore_placement))\n {\n agg::trans_affine matrix = params_.placement_params.tr;\n matrix.rotate(angle);\n matrix.translate(x, y);\n renderer_context_.render_marker(src_, path_, attrs_, params_, matrix);\n }\n }\n\nprotected:\n static agg::trans_affine recenter(svg_path_ptr const& src)\n {\n coord2d center = src->bounding_box().center();\n return agg::trans_affine_translation(-center.x, -center.y);\n }\n\n markers_dispatch_params params_;\n markers_renderer_context & renderer_context_;\n svg_path_ptr const& src_;\n svg_path_adapter & path_;\n svg_attribute_type const& attrs_;\n Detector & detector_;\n};\n\ntemplate <typename Detector>\nstruct raster_markers_dispatch : util::noncopyable\n{\n raster_markers_dispatch(image_rgba8 const& src,\n agg::trans_affine const& marker_trans,\n symbolizer_base const& sym,\n Detector & detector,\n double scale_factor,\n feature_impl const& feature,\n attributes const& vars,\n markers_renderer_context & renderer_context)\n : params_(box2d<double>(0, 0, src.width(), src.height()),\n marker_trans, sym, feature, vars, scale_factor)\n , renderer_context_(renderer_context)\n , src_(src)\n , detector_(detector)\n {}\n\n template <typename T>\n void add_path(T & path)\n {\n markers_placement_finder<T, Detector> placement_finder(\n params_.placement_method, path, detector_, params_.placement_params);\n double x, y, angle = .0;\n while (placement_finder.get_point(x, y, angle, params_.ignore_placement))\n {\n agg::trans_affine matrix = params_.placement_params.tr;\n matrix.rotate(angle);\n matrix.translate(x, y);\n renderer_context_.render_marker(src_, params_, matrix);\n }\n }\n\nprotected:\n markers_dispatch_params params_;\n markers_renderer_context & renderer_context_;\n image_rgba8 const& src_;\n Detector & detector_;\n};\n\nvoid build_ellipse(symbolizer_base const& sym, mapnik::feature_impl & feature, attributes const& vars,\n svg_storage_type & marker_ellipse, svg::svg_path_adapter & svg_path);\n\nbool push_explicit_style(svg_attribute_type const& src,\n svg_attribute_type & dst,\n symbolizer_base const& sym,\n feature_impl & feature,\n attributes const& vars);\n\nvoid setup_transform_scaling(agg::trans_affine & tr,\n double svg_width,\n double svg_height,\n mapnik::feature_impl & feature,\n attributes const& vars,\n symbolizer_base const& sym);\n\n\/\/ Apply markers to a feature with multiple geometries\ntemplate <typename Converter, typename Processor>\nvoid apply_markers_single(Converter & converter, Processor & proc, geometry::geometry<double> const& geom, geometry::geometry_types type)\n{\n if (type == geometry::geometry_types::Point)\n {\n geometry::point_vertex_adapter<double> va(geom.get<geometry::point<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::LineString)\n {\n geometry::line_string_vertex_adapter<double> va(geom.get<geometry::line_string<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::Polygon)\n {\n geometry::polygon_vertex_adapter<double> va(geom.get<geometry::polygon<double>>());\n converter.apply(va, proc);\n }\n else if (type == geometry::geometry_types::MultiPoint)\n {\n for (auto const& pt : geom.get<geometry::multi_point<double>>())\n {\n geometry::point_vertex_adapter<double> va(pt);\n converter.apply(va, proc);\n }\n }\n else if (type == geometry::geometry_types::MultiLineString)\n {\n for (auto const& line : geom.get<geometry::multi_line_string<double>>())\n {\n geometry::line_string_vertex_adapter<double> va(line);\n converter.apply(va, proc);\n }\n }\n else if (type == geometry::geometry_types::MultiPolygon)\n {\n for (auto const& poly : geom.get<geometry::multi_polygon<double>>())\n {\n geometry::polygon_vertex_adapter<double> va(poly);\n converter.apply(va, proc);\n }\n }\n}\n\ntemplate <typename Converter, typename Processor>\nvoid apply_markers_multi(feature_impl const& feature, attributes const& vars, Converter & converter, Processor & proc, symbolizer_base const& sym)\n{\n auto const& geom = feature.get_geometry();\n geometry::geometry_types type = geometry::geometry_type(geom);\n\n if (type == geometry::geometry_types::Point\n ||\n type == geometry::geometry_types::LineString\n ||\n type == geometry::geometry_types::Polygon)\n {\n apply_markers_single(converter, proc, geom, type);\n }\n else\n {\n\n marker_multi_policy_enum multi_policy = get<marker_multi_policy_enum, keys::markers_multipolicy>(sym, feature, vars);\n marker_placement_enum placement = get<marker_placement_enum, keys::markers_placement_type>(sym, feature, vars);\n\n if (placement == MARKER_POINT_PLACEMENT &&\n multi_policy == MARKER_WHOLE_MULTI)\n {\n geometry::point<double> pt;\n \/\/ test if centroid is contained by bounding box\n if (geometry::centroid(geom, pt) && converter.disp_.args_.bbox.contains(pt.x, pt.y))\n {\n \/\/ unset any clipping since we're now dealing with a point\n converter.template unset<clip_poly_tag>();\n geometry::point_vertex_adapter<double> va(pt);\n converter.apply(va, proc);\n }\n }\n else if ((placement == MARKER_POINT_PLACEMENT || placement == MARKER_INTERIOR_PLACEMENT) &&\n multi_policy == MARKER_LARGEST_MULTI)\n {\n \/\/ Only apply to path with largest envelope area\n \/\/ TODO: consider using true area for polygon types\n if (type == geometry::geometry_types::MultiPolygon)\n {\n geometry::multi_polygon<double> const& multi_poly = mapnik::util::get<geometry::multi_polygon<double> >(geom);\n double maxarea = 0;\n geometry::polygon<double> const* largest = 0;\n for (geometry::polygon<double> const& poly : multi_poly)\n {\n box2d<double> bbox = geometry::envelope(poly);\n double area = bbox.width() * bbox.height();\n if (area > maxarea)\n {\n maxarea = area;\n largest = &poly;\n }\n }\n if (largest)\n {\n geometry::polygon_vertex_adapter<double> va(*largest);\n converter.apply(va, proc);\n }\n }\n else\n {\n MAPNIK_LOG_WARN(marker_symbolizer) << \"TODO: if you get here -> open an issue\";\n }\n }\n else\n {\n if (multi_policy != MARKER_EACH_MULTI && placement != MARKER_POINT_PLACEMENT)\n {\n MAPNIK_LOG_WARN(marker_symbolizer) << \"marker_multi_policy != 'each' has no effect with marker_placement != 'point'\";\n }\n if (type == geometry::geometry_types::GeometryCollection)\n {\n for (auto const& g : geom.get<geometry::geometry_collection<double>>())\n {\n apply_markers_single(converter, proc, g, geometry::geometry_type(g));\n }\n }\n else\n {\n apply_markers_single(converter, proc, geom, type);\n }\n }\n }\n}\n\n}\n\n#endif \/\/MAPNIK_MARKER_HELPERS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2021 ScyllaDB\n *\/\n\n#pragma once\n\n#include <boost\/intrusive\/list.hpp>\n#include <boost\/intrusive\/slist.hpp>\n#include <boost\/container\/small_vector.hpp>\n#include <seastar\/core\/internal\/io_intent.hh>\n#include <seastar\/core\/io_priority_class.hh>\n\nnamespace bi = boost::intrusive;\n\nnamespace seastar {\n\n\/\/\/ \\example file_demo.cc\n\/\/\/ A handle confirming the caller's intent to do the IO\n\/\/\/\n\/\/\/ When a pointer to an intent is passed to the \\ref io_queue\n\/\/\/ \"io_queue\"::queue_request() method, the issued request is pinned\n\/\/\/ to the intent and is only processed as long as the intent object\n\/\/\/ is alive and the **cancel()** method is not called.\n\/\/\/\n\/\/\/ If no intent is provided, then the request is processed till its\n\/\/\/ completion be it success or error\nclass io_intent {\n struct intents_for_queue {\n dev_t dev;\n io_priority_class_id qid;\n internal::cancellable_queue cq;\n\n intents_for_queue(dev_t dev_, io_priority_class_id qid_) noexcept\n : dev(dev_), qid(qid_), cq() {}\n\n intents_for_queue(intents_for_queue&&) noexcept = default;\n intents_for_queue& operator=(intents_for_queue&&) noexcept = default;\n };\n\n struct references {\n internal::intent_reference::container_type list;\n\n references(references&& o) noexcept : list(std::move(o.list)) {}\n references() noexcept : list() {}\n ~references() { clear(); }\n\n void clear() {\n list.clear_and_dispose([] (internal::intent_reference* r) { r->on_cancel(); });\n }\n\n void bind(internal::intent_reference& iref) noexcept {\n list.push_back(iref);\n }\n };\n\n boost::container::small_vector<intents_for_queue, 1> _intents;\n references _refs;\n friend internal::intent_reference::intent_reference(io_intent*) noexcept;\n\npublic:\n io_intent() = default;\n ~io_intent() = default;\n\n io_intent(const io_intent&) = delete;\n io_intent& operator=(const io_intent&) = delete;\n io_intent& operator=(io_intent&&) = delete;\n io_intent(io_intent&& o) noexcept : _intents(std::move(o._intents)), _refs(std::move(o._refs)) {\n for (auto&& r : _refs.list) {\n r._intent = this;\n }\n }\n\n \/\/\/ Explicitly cancels all the requests attached to this intent\n \/\/\/ so far. The respective futures are resolved into the \\ref\n \/\/\/ cancelled_error \"cancelled_error\"\n void cancel() noexcept {\n _refs.clear();\n _intents.clear();\n }\n\n \/\/\/ @private\n internal::cancellable_queue& find_or_create_cancellable_queue(dev_t dev, io_priority_class_id qid) {\n for (auto&& i : _intents) {\n if (i.dev == dev && i.qid == qid) {\n return i.cq;\n }\n }\n\n _intents.emplace_back(dev, qid);\n return _intents.back().cq;\n }\n};\n\n} \/\/ namespace seastar\n<commit_msg>intent: drop unused headers<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2021 ScyllaDB\n *\/\n\n#pragma once\n\n#include <boost\/container\/small_vector.hpp>\n#include <seastar\/core\/internal\/io_intent.hh>\n#include <seastar\/core\/io_priority_class.hh>\n\nnamespace seastar {\n\n\/\/\/ \\example file_demo.cc\n\/\/\/ A handle confirming the caller's intent to do the IO\n\/\/\/\n\/\/\/ When a pointer to an intent is passed to the \\ref io_queue\n\/\/\/ \"io_queue\"::queue_request() method, the issued request is pinned\n\/\/\/ to the intent and is only processed as long as the intent object\n\/\/\/ is alive and the **cancel()** method is not called.\n\/\/\/\n\/\/\/ If no intent is provided, then the request is processed till its\n\/\/\/ completion be it success or error\nclass io_intent {\n struct intents_for_queue {\n dev_t dev;\n io_priority_class_id qid;\n internal::cancellable_queue cq;\n\n intents_for_queue(dev_t dev_, io_priority_class_id qid_) noexcept\n : dev(dev_), qid(qid_), cq() {}\n\n intents_for_queue(intents_for_queue&&) noexcept = default;\n intents_for_queue& operator=(intents_for_queue&&) noexcept = default;\n };\n\n struct references {\n internal::intent_reference::container_type list;\n\n references(references&& o) noexcept : list(std::move(o.list)) {}\n references() noexcept : list() {}\n ~references() { clear(); }\n\n void clear() {\n list.clear_and_dispose([] (internal::intent_reference* r) { r->on_cancel(); });\n }\n\n void bind(internal::intent_reference& iref) noexcept {\n list.push_back(iref);\n }\n };\n\n boost::container::small_vector<intents_for_queue, 1> _intents;\n references _refs;\n friend internal::intent_reference::intent_reference(io_intent*) noexcept;\n\npublic:\n io_intent() = default;\n ~io_intent() = default;\n\n io_intent(const io_intent&) = delete;\n io_intent& operator=(const io_intent&) = delete;\n io_intent& operator=(io_intent&&) = delete;\n io_intent(io_intent&& o) noexcept : _intents(std::move(o._intents)), _refs(std::move(o._refs)) {\n for (auto&& r : _refs.list) {\n r._intent = this;\n }\n }\n\n \/\/\/ Explicitly cancels all the requests attached to this intent\n \/\/\/ so far. The respective futures are resolved into the \\ref\n \/\/\/ cancelled_error \"cancelled_error\"\n void cancel() noexcept {\n _refs.clear();\n _intents.clear();\n }\n\n \/\/\/ @private\n internal::cancellable_queue& find_or_create_cancellable_queue(dev_t dev, io_priority_class_id qid) {\n for (auto&& i : _intents) {\n if (i.dev == dev && i.qid == qid) {\n return i.cq;\n }\n }\n\n _intents.emplace_back(dev, qid);\n return _intents.back().cq;\n }\n};\n\n} \/\/ namespace seastar\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Baldur Karlsson\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\n#include \"CustomPaintWidget.h\"\n#include <math.h>\n#include <QEvent>\n#include <QPainter>\n#include \"Code\/Interface\/QRDInterface.h\"\n\nCustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent)\n{\n m_Ctx = NULL;\n m_Output = NULL;\n setAttribute(Qt::WA_OpaquePaintEvent);\n setMouseTracking(true);\n m_Tag = QFormatStr(\"custompaint%1\").arg((uintptr_t) this);\n}\n\nCustomPaintWidget::CustomPaintWidget(ICaptureContext *c, QWidget *parent) : QWidget(parent)\n{\n m_Ctx = c;\n m_Output = NULL;\n setAttribute(Qt::WA_OpaquePaintEvent);\n if(c)\n setAttribute(Qt::WA_PaintOnScreen);\n setMouseTracking(true);\n m_Tag = QFormatStr(\"custompaint%1\").arg((uintptr_t) this);\n}\n\nCustomPaintWidget::~CustomPaintWidget()\n{\n}\n\nvoid CustomPaintWidget::mousePressEvent(QMouseEvent *e)\n{\n emit clicked(e);\n}\n\nvoid CustomPaintWidget::mouseDoubleClickEvent(QMouseEvent *event)\n{\n emit(doubleClicked(event));\n}\n\nvoid CustomPaintWidget::mouseMoveEvent(QMouseEvent *e)\n{\n emit mouseMove(e);\n}\n\nvoid CustomPaintWidget::wheelEvent(QWheelEvent *e)\n{\n emit mouseWheel(e);\n}\n\nvoid CustomPaintWidget::resizeEvent(QResizeEvent *e)\n{\n emit resize(e);\n}\n\nvoid CustomPaintWidget::keyPressEvent(QKeyEvent *e)\n{\n emit keyPress(e);\n}\n\nvoid CustomPaintWidget::keyReleaseEvent(QKeyEvent *e)\n{\n emit keyRelease(e);\n}\n\nvoid CustomPaintWidget::paintEvent(QPaintEvent *e)\n{\n if(m_Ctx)\n {\n if(m_Output != NULL)\n {\n QPointer<CustomPaintWidget> me(this);\n m_Ctx->Replay().AsyncInvoke(m_Tag, [me](IReplayController *r) {\n if(me && me->m_Output)\n me->m_Output->Display();\n });\n }\n }\n else if(m_Dark == m_Light)\n {\n QPainter p(this);\n p.fillRect(rect(), m_Dark);\n }\n else\n {\n int numX = (int)ceil((float)rect().width() \/ 64.0f);\n int numY = (int)ceil((float)rect().height() \/ 64.0f);\n\n QPainter p(this);\n for(int x = 0; x < numX; x++)\n {\n for(int y = 0; y < numY; y++)\n {\n QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light;\n\n p.fillRect(QRect(x * 64, y * 64, 64, 64), col);\n }\n }\n }\n}\n\n#if defined(RENDERDOC_PLATFORM_APPLE)\nbool CustomPaintWidget::event(QEvent *e)\n{\n if(m_Ctx && e->type() == QEvent::UpdateRequest)\n paintEvent(NULL);\n return QWidget::event(e);\n}\n#endif\n<commit_msg>Fix #1898: Add missing QPointer include<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Baldur Karlsson\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\n#include \"CustomPaintWidget.h\"\n#include <math.h>\n#include <QEvent>\n#include <QPainter>\n#include <QPointer>\n#include \"Code\/Interface\/QRDInterface.h\"\n\nCustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent)\n{\n m_Ctx = NULL;\n m_Output = NULL;\n setAttribute(Qt::WA_OpaquePaintEvent);\n setMouseTracking(true);\n m_Tag = QFormatStr(\"custompaint%1\").arg((uintptr_t) this);\n}\n\nCustomPaintWidget::CustomPaintWidget(ICaptureContext *c, QWidget *parent) : QWidget(parent)\n{\n m_Ctx = c;\n m_Output = NULL;\n setAttribute(Qt::WA_OpaquePaintEvent);\n if(c)\n setAttribute(Qt::WA_PaintOnScreen);\n setMouseTracking(true);\n m_Tag = QFormatStr(\"custompaint%1\").arg((uintptr_t) this);\n}\n\nCustomPaintWidget::~CustomPaintWidget()\n{\n}\n\nvoid CustomPaintWidget::mousePressEvent(QMouseEvent *e)\n{\n emit clicked(e);\n}\n\nvoid CustomPaintWidget::mouseDoubleClickEvent(QMouseEvent *event)\n{\n emit(doubleClicked(event));\n}\n\nvoid CustomPaintWidget::mouseMoveEvent(QMouseEvent *e)\n{\n emit mouseMove(e);\n}\n\nvoid CustomPaintWidget::wheelEvent(QWheelEvent *e)\n{\n emit mouseWheel(e);\n}\n\nvoid CustomPaintWidget::resizeEvent(QResizeEvent *e)\n{\n emit resize(e);\n}\n\nvoid CustomPaintWidget::keyPressEvent(QKeyEvent *e)\n{\n emit keyPress(e);\n}\n\nvoid CustomPaintWidget::keyReleaseEvent(QKeyEvent *e)\n{\n emit keyRelease(e);\n}\n\nvoid CustomPaintWidget::paintEvent(QPaintEvent *e)\n{\n if(m_Ctx)\n {\n if(m_Output != NULL)\n {\n QPointer<CustomPaintWidget> me(this);\n m_Ctx->Replay().AsyncInvoke(m_Tag, [me](IReplayController *r) {\n if(me && me->m_Output)\n me->m_Output->Display();\n });\n }\n }\n else if(m_Dark == m_Light)\n {\n QPainter p(this);\n p.fillRect(rect(), m_Dark);\n }\n else\n {\n int numX = (int)ceil((float)rect().width() \/ 64.0f);\n int numY = (int)ceil((float)rect().height() \/ 64.0f);\n\n QPainter p(this);\n for(int x = 0; x < numX; x++)\n {\n for(int y = 0; y < numY; y++)\n {\n QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light;\n\n p.fillRect(QRect(x * 64, y * 64, 64, 64), col);\n }\n }\n }\n}\n\n#if defined(RENDERDOC_PLATFORM_APPLE)\nbool CustomPaintWidget::event(QEvent *e)\n{\n if(m_Ctx && e->type() == QEvent::UpdateRequest)\n paintEvent(NULL);\n return QWidget::event(e);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * RecursiveFilter.cpp\n *\n * Copyright 2011 Michael Bell\n * All rights reserved.\n *\n *\/\n\n#include \"RecursiveFilter.h\"\n#include <iostream>\n#include <cmath>\n\nRecursiveFilter::RecursiveFilter(const int& fOrder, const int& fLengthScale)\n{\n\t\n\t\/\/ Create a filter based on the specified order and lengthscale\n\torder = fOrder;\n\tlengthScale = fLengthScale;\n\tgetFilterCoefficients();\n\t\n}\n\nRecursiveFilter::~RecursiveFilter()\n{\n}\n\nvoid RecursiveFilter::getFilterCoefficients()\n{\n\treal sigma = (lengthScale*lengthScale)\/2;\n\treal b[5][5];\n\treal a[201][201];\n\treal p[201];\n\treal K[9];\n\treal D[9];\n\t\n\t\/\/ b coefficients\n\tb[1][1] = 1;\n\tb[1][2] = 1\/12;\n\tb[1][3] = 1\/90;\n\tb[1][4] = 1\/560;\n\tb[2][2] = 1;\n\tb[2][3] = 1\/6;\n\tb[2][4] = 7\/240;\n\tb[3][3] = 1;\n\tb[3][4] = 1\/4;\n\tb[4][4] = 1;\n\t\n \/\/ Compute polynomial coefficients\n\tK[2] = b[1][1]*sigma;\n\tK[4] = b[1][2]*sigma + b[2][2]*(pow(sigma,2))\/factorial(2);\n\tK[6] = b[1][3]*sigma + b[2][3]*(pow(sigma,2))\/factorial(2)\n\t\t+ b[3][3]*(pow(sigma,3))\/factorial(3);\n\tK[8] = b[1][4]*sigma + b[2][4]*(pow(sigma,2))\/factorial(2)\n\t\t+ b[3][4]*(pow(sigma,3))\/factorial(3) + b[4][4]*(pow(sigma,4))\/factorial(4);\n\t\n\tfor (int i=0;i<=order*2;i++) {\n\t\tD[i] = 0;\n\t}\n\t\n\tfor (int n=2;n<=order*2;n+=2) {\n\t\tfor (int i=0;i<=n;i++) {\n\t\t\tint index = n\/2 - i;\n\t\t\treal coeff = (pow((-1),(n\/2)))*(pow((-1),i))*factorial(n)\/(factorial(n-i)*factorial(i));\n\t\t\tD[index+order] += K[n]*coeff;\n\t\t}\n\t}\n\tD[order] += 1;\n\t\n\tfor (int i=0;i<=200;i++) {\n\t\tfor (int j=0;j<=200;j++) {\n\t\t\tif (abs(j-i) <= order) {\n\t\t\t\ta[i][j] = D[j-i+order];\n\t\t\t} else {\n\t\t\t\ta[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/ Cholesky decomp\n\tfor (int i=0;i<=200;i++) {\n\t\tfor (int j=0;j<=200;j++) {\n\t\t\treal sum=a[i][j];\n\t\t\tfor (int k=i-1;k>=0;k--) {\n\t\t\t\tsum -= a[i][k]*a[j][k];\n\t\t\t}\n\t\t\tif (i == j) {\n\t\t\t\tif (sum <= 0.0) { \n\t\t\t\t\tstd::cout << \"cholesky failed at i,j sum\\n\";\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tp[i] = sqrt(sum);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ta[j][i]=sum\/p[i];\n\t\t\t}\n\t\t}\n\t}\n\tbeta = 1\/p[200];\n\talpha[1]=-beta*a[200][199];\n\tif (order > 1) {\n\t\talpha[2]=-beta*a[200][198];\n\t} else {\n\t\talpha[2]=0;\n\t}\n\tif (order > 2) {\n\t\talpha[3]=-beta*a[200][197];\n\t} else {\n\t\talpha[3]=0;\n\t}\n\tif (order > 3) {\n\t\talpha[4]=-beta*a[200][196];\n\t} else {\n\t\talpha[4]=0;\n\t}\n\t\n\tstd::cout << \"4th Order Recursive Filter coefficients computed for lengthscale \" \n\t\t<< lengthScale << \" Delta R\" << std::endl;\n\tstd::cout << \"\\tBeta: \" << beta << std::endl;\n\tstd::cout << \"\\tAlpha[1]: \" << alpha[1] << std::endl;\n\tstd::cout << \"\\tAlpha[2]: \" << alpha[2] << std::endl;\n\tstd::cout << \"\\tAlpha[3]: \" << alpha[3] << std::endl;\n\tstd::cout << \"\\tAlpha[4]: \" << alpha[4] << std::endl;\n\t\t\n\t\n\t\/\/ Boundary conditions\n\treal L[5][5];\n\treal U[5][5];\n\treal LT[5][5];\n\treal UT[5][5];\n\treal LI[5][5];\n\treal col[5];\n\treal colinv[5];\n\t\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\tL[i][j]=0.;\n\t\t\tU[i][j]=0.;\n\t\t}\n\t}\n\t\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=0;j<=order;j++) {\n\t\t\tint index = i+j;\n\t\t\tif (index <= order) {\n\t\t\t\tL[i+j][i] = -alpha[j];\n\t\t\t\tU[i][i+j] = alpha[order-j];\n\t\t\t}\n\t\t}\n\t\tL[i][i] = 1.;\n\t}\n\t\n\t\/\/ Invert L\n\tfor (int j=1;j<=order;j++) {\n\t\tfor (int i=1;i<=order;i++) { col[i] = 0.0; }\n\t\tcol[j] = 1;\n\t\tcolinv[0] = col[0];\n\t\tfor (int i=1;i<=order;i++) {\n\t\t\tcolinv[i] = col[i];\n\t\t\tfor (int k=i-1;k>=1;k--) {\n\t\t\t\tcolinv[i] -= L[i][k]*colinv[k];\n\t\t\t}\n\t\t}\n\t\tfor (int i=1;i<=order;i++) {\n\t\t\tLI[i][j] = colinv[i];\n\t\t}\n\t}\n\t\n\t\/\/ Transpose L & T\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\tLT[i][j] = L[j][i];\n\t\t\tUT[i][j] = U[j][i];\n\t\t}\n\t}\n\t\n\t\/\/ Get Sn matrix\n\treal tmp[5][5];\n\treal tmp2[5][5];\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\ttmp[i][j] = 0.;\n\t\t\tfor (int k=1;k<=order;k++) {\n\t\t\t\ttmp[i][j] += UT[i][k]*LI[k][j];\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\ttmp2[i][j] = 0.;\n\t\t\tfor (int k=1;k<=order;k++) {\n\t\t\t\ttmp2[i][j] += tmp[i][k]*U[k][j];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\tSn[i-1][j-1] = (LT[i][j] - tmp2[i][j])\/beta;\n\t\t}\n\t}\n\t\n}\n\nbool RecursiveFilter::filterArray(real* array, const int& arrLength)\n{\n\tint maxi = arrLength-1;\n\treal* p = array;\n\treal* q = new real[arrLength];\n\treal* s = new real[arrLength];\n\n\tfor (int i=0; i<= maxi; i++) {\n\t\tq[i] = 0;\n\t\ts[i] = 0;\n\t}\n\t\n\tq[0]=beta*p[0];\n\tq[1]=beta*p[1] + alpha[1]*q[0];\n\tq[2]=beta*p[2] + alpha[1]*q[1] + alpha[2]*q[0];\n\tq[3]=beta*p[3] + alpha[1]*q[2] + alpha[2]*q[1] + alpha[3]*q[0];\t\n\tfor (int i=order; i<= maxi; i++) {\n\t\tq[i] = beta*p[i] + alpha[1]*q[i-1]\n\t\t+ alpha[2]*q[i-2] + alpha[3]*q[i-3] + alpha[4]*q[i-4];\n\t}\n\t\n \/\/ Invert Sn\n\treal* A = new real[4];\n\treal* B = new real[4];\n\tfor (int i=maxi-order+1; i<= maxi; i++) {\n\t\tB[i-(maxi-order+1)] = q[i];\n\t}\n\tsolveBC(A, B);\n\tfor (int i=maxi; i>= (maxi-order+1); i--) {\n\t\ts[i] = A[i-(maxi-order+1)];\n\t}\n\tfor (int i=maxi-order;i>=0;i--) {\n\t\ts[i] = beta*q[i] + alpha[1]*s[i+1]\n\t\t+ alpha[2]*s[i+2] + alpha[3]*s[i+3] + alpha[4]*s[i+4];\n\t\t\/\/ std::cout << s[i] << std::endl;\n\t}\n\tdelete[] A;\n\tdelete[] B;\n\t\n\t\n\tfor (int i=0; i<= maxi; i++) {\n\t\t\/\/ To get a 'true' Gaussian, need to scale by this factor\n\t\t\/\/ To preserve total quantity (needed for Variational analysis)\n\t\t\/\/ Do not scale resulting vector\n\t\t\/\/real Pi = 3.141592653589793238462643;\n\t\t\/\/array[i] = s[i]*sqrt(2*Pi)*lengthScale;\n\t\tarray[i] = s[i];\n\t}\n\tdelete[] q;\n\tdelete[] s;\n\t\n\treturn true;\n\t\n}\n\nreal RecursiveFilter::factorial(const real& max) \n{\n\treal n = 1;\n\tfor (real i=2;i<=max;i++) {\n\t\tn *= i;\n\t}\n\treturn n;\n\t\n}\n\nvoid RecursiveFilter::solveBC(real* A, real*B) \n{\n\t\n\tint n = order-1;\n\tfor(int j=0;j<=n-1;j++) {\n\t\tfor (int i=j+1;i<=n;i++) {\n\t\t\tSn[i][j]=Sn[i][j]\/Sn[j][j];\n\t\t}\n\t\tfor\t(int i=j+1;i<=n;i++) {\n\t\t\tfor (int k=j+1;k<=n;k++) {\n\t\t\t\tSn[i][k]=Sn[i][k]-Sn[i][j]*Sn[j][k];\n\t\t\t}\n\t\t\tB[i]=B[i]-Sn[i][j]*B[j];\n\t\t}\n\t}\n\tA[n]=B[n]\/Sn[n][n];\n\tfor(int j=n-1;j>=0;j--) {\n\t\tA[j]=B[j];\n\t\tfor(int k=n;k>=j+1;k--) {\n\t\t\tA[j]=A[j]-A[k]*Sn[j][k];\n\t\t}\n\t\tA[j]=A[j]\/Sn[j][j];\n\t}\n}\n<commit_msg>Fix abs command to use std::abs<commit_after>\/*\n * RecursiveFilter.cpp\n *\n * Copyright 2011 Michael Bell\n * All rights reserved.\n *\n *\/\n\n#include \"RecursiveFilter.h\"\n#include <iostream>\n#include <cmath>\n\nRecursiveFilter::RecursiveFilter(const int& fOrder, const int& fLengthScale)\n{\n\t\n\t\/\/ Create a filter based on the specified order and lengthscale\n\torder = fOrder;\n\tlengthScale = fLengthScale;\n\tgetFilterCoefficients();\n\t\n}\n\nRecursiveFilter::~RecursiveFilter()\n{\n}\n\nvoid RecursiveFilter::getFilterCoefficients()\n{\n\treal sigma = (lengthScale*lengthScale)\/2;\n\treal b[5][5];\n\treal a[201][201];\n\treal p[201];\n\treal K[9];\n\treal D[9];\n\t\n\t\/\/ b coefficients\n\tb[1][1] = 1;\n\tb[1][2] = 1\/12;\n\tb[1][3] = 1\/90;\n\tb[1][4] = 1\/560;\n\tb[2][2] = 1;\n\tb[2][3] = 1\/6;\n\tb[2][4] = 7\/240;\n\tb[3][3] = 1;\n\tb[3][4] = 1\/4;\n\tb[4][4] = 1;\n\t\n \/\/ Compute polynomial coefficients\n\tK[2] = b[1][1]*sigma;\n\tK[4] = b[1][2]*sigma + b[2][2]*(pow(sigma,2))\/factorial(2);\n\tK[6] = b[1][3]*sigma + b[2][3]*(pow(sigma,2))\/factorial(2)\n\t\t+ b[3][3]*(pow(sigma,3))\/factorial(3);\n\tK[8] = b[1][4]*sigma + b[2][4]*(pow(sigma,2))\/factorial(2)\n\t\t+ b[3][4]*(pow(sigma,3))\/factorial(3) + b[4][4]*(pow(sigma,4))\/factorial(4);\n\t\n\tfor (int i=0;i<=order*2;i++) {\n\t\tD[i] = 0;\n\t}\n\t\n\tfor (int n=2;n<=order*2;n+=2) {\n\t\tfor (int i=0;i<=n;i++) {\n\t\t\tint index = n\/2 - i;\n\t\t\treal coeff = (pow((-1),(n\/2)))*(pow((-1),i))*factorial(n)\/(factorial(n-i)*factorial(i));\n\t\t\tD[index+order] += K[n]*coeff;\n\t\t}\n\t}\n\tD[order] += 1;\n\t\n\tfor (int i=0;i<=200;i++) {\n\t\tfor (int j=0;j<=200;j++) {\n\t\t\tif (std::abs((double)(j-i)) <= order) {\n\t\t\t\ta[i][j] = D[j-i+order];\n\t\t\t} else {\n\t\t\t\ta[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/ Cholesky decomp\n\tfor (int i=0;i<=200;i++) {\n\t\tfor (int j=0;j<=200;j++) {\n\t\t\treal sum=a[i][j];\n\t\t\tfor (int k=i-1;k>=0;k--) {\n\t\t\t\tsum -= a[i][k]*a[j][k];\n\t\t\t}\n\t\t\tif (i == j) {\n\t\t\t\tif (sum <= 0.0) { \n\t\t\t\t\tstd::cout << \"cholesky failed at i,j sum\\n\";\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tp[i] = sqrt(sum);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ta[j][i]=sum\/p[i];\n\t\t\t}\n\t\t}\n\t}\n\tbeta = 1\/p[200];\n\talpha[1]=-beta*a[200][199];\n\tif (order > 1) {\n\t\talpha[2]=-beta*a[200][198];\n\t} else {\n\t\talpha[2]=0;\n\t}\n\tif (order > 2) {\n\t\talpha[3]=-beta*a[200][197];\n\t} else {\n\t\talpha[3]=0;\n\t}\n\tif (order > 3) {\n\t\talpha[4]=-beta*a[200][196];\n\t} else {\n\t\talpha[4]=0;\n\t}\n\t\n\tstd::cout << \"4th Order Recursive Filter coefficients computed for lengthscale \" \n\t\t<< lengthScale << \" Delta R\" << std::endl;\n\tstd::cout << \"\\tBeta: \" << beta << std::endl;\n\tstd::cout << \"\\tAlpha[1]: \" << alpha[1] << std::endl;\n\tstd::cout << \"\\tAlpha[2]: \" << alpha[2] << std::endl;\n\tstd::cout << \"\\tAlpha[3]: \" << alpha[3] << std::endl;\n\tstd::cout << \"\\tAlpha[4]: \" << alpha[4] << std::endl;\n\t\t\n\t\n\t\/\/ Boundary conditions\n\treal L[5][5];\n\treal U[5][5];\n\treal LT[5][5];\n\treal UT[5][5];\n\treal LI[5][5];\n\treal col[5];\n\treal colinv[5];\n\t\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\tL[i][j]=0.;\n\t\t\tU[i][j]=0.;\n\t\t}\n\t}\n\t\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=0;j<=order;j++) {\n\t\t\tint index = i+j;\n\t\t\tif (index <= order) {\n\t\t\t\tL[i+j][i] = -alpha[j];\n\t\t\t\tU[i][i+j] = alpha[order-j];\n\t\t\t}\n\t\t}\n\t\tL[i][i] = 1.;\n\t}\n\t\n\t\/\/ Invert L\n\tfor (int j=1;j<=order;j++) {\n\t\tfor (int i=1;i<=order;i++) { col[i] = 0.0; }\n\t\tcol[j] = 1;\n\t\tcolinv[0] = col[0];\n\t\tfor (int i=1;i<=order;i++) {\n\t\t\tcolinv[i] = col[i];\n\t\t\tfor (int k=i-1;k>=1;k--) {\n\t\t\t\tcolinv[i] -= L[i][k]*colinv[k];\n\t\t\t}\n\t\t}\n\t\tfor (int i=1;i<=order;i++) {\n\t\t\tLI[i][j] = colinv[i];\n\t\t}\n\t}\n\t\n\t\/\/ Transpose L & T\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\tLT[i][j] = L[j][i];\n\t\t\tUT[i][j] = U[j][i];\n\t\t}\n\t}\n\t\n\t\/\/ Get Sn matrix\n\treal tmp[5][5];\n\treal tmp2[5][5];\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\ttmp[i][j] = 0.;\n\t\t\tfor (int k=1;k<=order;k++) {\n\t\t\t\ttmp[i][j] += UT[i][k]*LI[k][j];\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\ttmp2[i][j] = 0.;\n\t\t\tfor (int k=1;k<=order;k++) {\n\t\t\t\ttmp2[i][j] += tmp[i][k]*U[k][j];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (int i=1;i<=order;i++) {\n\t\tfor (int j=1;j<=order;j++) {\n\t\t\tSn[i-1][j-1] = (LT[i][j] - tmp2[i][j])\/beta;\n\t\t}\n\t}\n\t\n}\n\nbool RecursiveFilter::filterArray(real* array, const int& arrLength)\n{\n\tint maxi = arrLength-1;\n\treal* p = array;\n\treal* q = new real[arrLength];\n\treal* s = new real[arrLength];\n\n\tfor (int i=0; i<= maxi; i++) {\n\t\tq[i] = 0;\n\t\ts[i] = 0;\n\t}\n\t\n\tq[0]=beta*p[0];\n\tq[1]=beta*p[1] + alpha[1]*q[0];\n\tq[2]=beta*p[2] + alpha[1]*q[1] + alpha[2]*q[0];\n\tq[3]=beta*p[3] + alpha[1]*q[2] + alpha[2]*q[1] + alpha[3]*q[0];\t\n\tfor (int i=order; i<= maxi; i++) {\n\t\tq[i] = beta*p[i] + alpha[1]*q[i-1]\n\t\t+ alpha[2]*q[i-2] + alpha[3]*q[i-3] + alpha[4]*q[i-4];\n\t}\n\t\n \/\/ Invert Sn\n\treal* A = new real[4];\n\treal* B = new real[4];\n\tfor (int i=maxi-order+1; i<= maxi; i++) {\n\t\tB[i-(maxi-order+1)] = q[i];\n\t}\n\tsolveBC(A, B);\n\tfor (int i=maxi; i>= (maxi-order+1); i--) {\n\t\ts[i] = A[i-(maxi-order+1)];\n\t}\n\tfor (int i=maxi-order;i>=0;i--) {\n\t\ts[i] = beta*q[i] + alpha[1]*s[i+1]\n\t\t+ alpha[2]*s[i+2] + alpha[3]*s[i+3] + alpha[4]*s[i+4];\n\t\t\/\/ std::cout << s[i] << std::endl;\n\t}\n\tdelete[] A;\n\tdelete[] B;\n\t\n\t\n\tfor (int i=0; i<= maxi; i++) {\n\t\t\/\/ To get a 'true' Gaussian, need to scale by this factor\n\t\t\/\/ To preserve total quantity (needed for Variational analysis)\n\t\t\/\/ Do not scale resulting vector\n\t\t\/\/real Pi = 3.141592653589793238462643;\n\t\t\/\/array[i] = s[i]*sqrt(2*Pi)*lengthScale;\n\t\tarray[i] = s[i];\n\t}\n\tdelete[] q;\n\tdelete[] s;\n\t\n\treturn true;\n\t\n}\n\nreal RecursiveFilter::factorial(const real& max) \n{\n\treal n = 1;\n\tfor (real i=2;i<=max;i++) {\n\t\tn *= i;\n\t}\n\treturn n;\n\t\n}\n\nvoid RecursiveFilter::solveBC(real* A, real*B) \n{\n\t\n\tint n = order-1;\n\tfor(int j=0;j<=n-1;j++) {\n\t\tfor (int i=j+1;i<=n;i++) {\n\t\t\tSn[i][j]=Sn[i][j]\/Sn[j][j];\n\t\t}\n\t\tfor\t(int i=j+1;i<=n;i++) {\n\t\t\tfor (int k=j+1;k<=n;k++) {\n\t\t\t\tSn[i][k]=Sn[i][k]-Sn[i][j]*Sn[j][k];\n\t\t\t}\n\t\t\tB[i]=B[i]-Sn[i][j]*B[j];\n\t\t}\n\t}\n\tA[n]=B[n]\/Sn[n][n];\n\tfor(int j=n-1;j>=0;j--) {\n\t\tA[j]=B[j];\n\t\tfor(int k=n;k>=j+1;k--) {\n\t\t\tA[j]=A[j]-A[k]*Sn[j][k];\n\t\t}\n\t\tA[j]=A[j]\/Sn[j][j];\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"kwm.h\"\n\n\nextern uint32_t MaxDisplayCount;\nextern uint32_t ActiveDisplaysCount;\nextern CGDirectDisplayID ActiveDisplays[];\n\nextern screen_info *Screen;\nextern int CurrentSpace;\n\nextern std::map<unsigned int, screen_info> DisplayMap;\nextern std::vector<window_info> WindowLst;\nextern std::vector<window_info> FloatingAppLst;\nextern window_info *FocusedWindow;\n\nextern int DefaultPaddingLeft, DefaultPaddingRight;\nextern int DefaultPaddingTop, DefaultPaddingBottom;\nextern int DefaultGapVertical, DefaultGapHorizontal;\n\nvoid DisplayReconfigurationCallBack(CGDirectDisplayID Display, CGDisplayChangeSummaryFlags Flags, void *UserInfo)\n{\n if (Flags & kCGDisplayAddFlag)\n {\n \/\/ display has been added\n DEBUG(\"New display detected!\")\n }\n else if (Flags & kCGDisplayRemoveFlag)\n {\n \/\/ display has been removed\n DEBUG(\"Display has been removed!\")\n }\n}\n\nvoid GetActiveDisplays()\n{\n CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);\n for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)\n {\n CGRect DisplayRect = CGDisplayBounds(ActiveDisplays[DisplayIndex]);\n unsigned int DisplayID = ActiveDisplays[DisplayIndex];\n\n screen_info Screen;\n Screen.ID = DisplayIndex;\n Screen.ForceContainerUpdate = false;\n Screen.ActiveSpace = -1;\n Screen.OldWindowListCount = -1;\n\n Screen.X = DisplayRect.origin.x;\n Screen.Y = DisplayRect.origin.y;\n Screen.Width = DisplayRect.size.width;\n Screen.Height = DisplayRect.size.height;\n\n Screen.PaddingTop = DefaultPaddingTop;\n Screen.PaddingLeft = DefaultPaddingLeft;\n Screen.PaddingRight = DefaultPaddingRight;\n Screen.PaddingBottom = DefaultPaddingBottom;\n\n Screen.VerticalGap = DefaultGapVertical;\n Screen.HorizontalGap = DefaultGapHorizontal;\n\n DisplayMap[DisplayID] = Screen;\n }\n\n Screen = GetDisplayOfMousePointer();\n CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallBack, NULL);\n}\n\nscreen_info *GetDisplayFromScreenID(int ID)\n{\n std::map<unsigned int, screen_info>::iterator It;\n for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)\n {\n screen_info *Screen = &It->second;\n if(Screen->ID == ID)\n return Screen;\n }\n\n return NULL;\n}\n\nscreen_info *GetDisplayOfMousePointer()\n{\n CGEventRef Event = CGEventCreate(NULL);\n CGPoint Cursor = CGEventGetLocation(Event);\n CFRelease(Event);\n\n std::map<unsigned int, screen_info>::iterator It;\n for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)\n {\n screen_info *Screen = &It->second;\n if(Cursor.x >= Screen->X && Cursor.x <= Screen->X + Screen->Width &&\n Cursor.y >= Screen->Y && Cursor.y <= Screen->Y + Screen->Height)\n return Screen;\n }\n\n return NULL;\n}\n\nscreen_info *GetDisplayOfWindow(window_info *Window)\n{\n if(Window)\n {\n std::map<unsigned int, screen_info>::iterator It;\n for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)\n {\n screen_info *Screen = &It->second;\n if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)\n return Screen;\n }\n }\n\n return NULL;\n}\n\nstd::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)\n{\n screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);\n std::vector<window_info*> ScreenWindowLst;\n for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)\n {\n window_info *Window = &WindowLst[WindowIndex];\n if(!IsApplicationFloating(&WindowLst[WindowIndex]))\n {\n if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)\n ScreenWindowLst.push_back(Window);\n }\n }\n\n return ScreenWindowLst;\n}\n\nstd::vector<int> GetAllWindowIDsOnDisplay(int ScreenIndex)\n{\n screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);\n std::vector<int> ScreenWindowIDLst;\n for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)\n {\n window_info *Window = &WindowLst[WindowIndex];\n if(!IsApplicationFloating(&WindowLst[WindowIndex]))\n {\n if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)\n ScreenWindowIDLst.push_back(Window->WID);\n }\n }\n\n return ScreenWindowIDLst;\n}\n\nvoid SetDefaultPaddingOfDisplay(const std::string &Side, int Offset)\n{\n if(Side == \"left\")\n DefaultPaddingLeft = Offset;\n else if(Side == \"right\")\n DefaultPaddingRight = Offset;\n else if(Side == \"top\")\n DefaultPaddingTop = Offset;\n else if(Side == \"bottom\")\n DefaultPaddingBottom = Offset;\n}\n\nvoid SetDefaultGapOfDisplay(const std::string &Side, int Offset)\n{\n if(Side == \"vertical\")\n DefaultGapVertical = Offset;\n else if(Side == \"horizontal\")\n DefaultGapHorizontal = Offset;\n}\n\nvoid ChangePaddingOfDisplay(const std::string &Side, int Offset)\n{\n screen_info *Screen = GetDisplayOfMousePointer();\n if(Side == \"left\")\n Screen->Space[CurrentSpace].PaddingLeft += Offset;\n else if(Side == \"right\")\n Screen->Space[CurrentSpace].PaddingRight += Offset;\n else if(Side == \"top\")\n Screen->Space[CurrentSpace].PaddingTop += Offset;\n else if(Side == \"bottom\")\n Screen->Space[CurrentSpace].PaddingBottom += Offset;\n\n SetRootNodeContainer(Screen, Screen->Space[CurrentSpace].RootNode);\n CreateNodeContainers(Screen, Screen->Space[CurrentSpace].RootNode, true);\n ApplyNodeContainer(Screen->Space[CurrentSpace].RootNode);\n}\n\nvoid ChangeGapOfDisplay(const std::string &Side, int Offset)\n{\n screen_info *Screen = GetDisplayOfMousePointer();\n if(Side == \"vertical\")\n Screen->Space[CurrentSpace].VerticalGap += Offset;\n else if(Side == \"horizontal\")\n Screen->Space[CurrentSpace].HorizontalGap += Offset;\n\n CreateNodeContainers(Screen, Screen->Space[CurrentSpace].RootNode, true);\n ApplyNodeContainer(Screen->Space[CurrentSpace].RootNode);\n}\n\nvoid CycleFocusedWindowDisplay(int Shift)\n{\n screen_info *Screen = GetDisplayOfWindow(FocusedWindow);\n int NewScreenIndex = -1;\n\n if(Shift == 1)\n NewScreenIndex = (Screen->ID + 1 >= ActiveDisplaysCount) ? 0 : Screen->ID + 1;\n else if(Shift == -1)\n NewScreenIndex = (Screen->ID - 1 < 0) ? ActiveDisplaysCount - 1 : Screen->ID - 1;\n\n if(NewScreenIndex != Screen->ID)\n {\n screen_info *NewScreen = GetDisplayFromScreenID(NewScreenIndex);\n AddWindowToTreeOfUnfocusedMonitor(NewScreen);\n }\n}\n<commit_msg>kwm must no longer be restarted when a monitor is connected \/ disconnected<commit_after>#include \"kwm.h\"\n\n\nextern uint32_t MaxDisplayCount;\nextern uint32_t ActiveDisplaysCount;\nextern CGDirectDisplayID ActiveDisplays[];\n\nextern screen_info *Screen;\nextern int CurrentSpace;\n\nextern std::map<unsigned int, screen_info> DisplayMap;\nextern std::vector<window_info> WindowLst;\nextern std::vector<window_info> FloatingAppLst;\nextern window_info *FocusedWindow;\n\nextern int DefaultPaddingLeft, DefaultPaddingRight;\nextern int DefaultPaddingTop, DefaultPaddingBottom;\nextern int DefaultGapVertical, DefaultGapHorizontal;\n\nvoid DisplayReconfigurationCallBack(CGDirectDisplayID Display, CGDisplayChangeSummaryFlags Flags, void *UserInfo)\n{\n if (Flags & kCGDisplayAddFlag)\n {\n \/\/ display has been added\n DisplayMap[Display] = CreateDefaultScreenInfo(Display, ActiveDisplaysCount++);\n DEBUG(\"New display detected!\")\n }\n else if (Flags & kCGDisplayRemoveFlag)\n {\n \/\/ display has been removed\n DisplayMap.erase(Display);\n DEBUG(\"Display has been removed!\")\n }\n}\n\nscreen_info CreateDefaultScreenInfo(int DisplayIndex, int ScreenIndex)\n{\n CGRect DisplayRect = CGDisplayBounds(DisplayIndex);\n screen_info Screen;\n\n Screen.ID = ScreenIndex;\n Screen.ForceContainerUpdate = false;\n Screen.ActiveSpace = -1;\n Screen.OldWindowListCount = -1;\n\n Screen.X = DisplayRect.origin.x;\n Screen.Y = DisplayRect.origin.y;\n Screen.Width = DisplayRect.size.width;\n Screen.Height = DisplayRect.size.height;\n\n Screen.PaddingTop = DefaultPaddingTop;\n Screen.PaddingLeft = DefaultPaddingLeft;\n Screen.PaddingRight = DefaultPaddingRight;\n Screen.PaddingBottom = DefaultPaddingBottom;\n\n Screen.VerticalGap = DefaultGapVertical;\n Screen.HorizontalGap = DefaultGapHorizontal;\n\n return Screen;\n}\n\nvoid GetActiveDisplays()\n{\n CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);\n for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)\n {\n unsigned int DisplayID = ActiveDisplays[DisplayIndex];\n DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);;\n }\n\n Screen = GetDisplayOfMousePointer();\n CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallBack, NULL);\n}\n\nscreen_info *GetDisplayFromScreenID(int ID)\n{\n std::map<unsigned int, screen_info>::iterator It;\n for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)\n {\n screen_info *Screen = &It->second;\n if(Screen->ID == ID)\n return Screen;\n }\n\n return NULL;\n}\n\nscreen_info *GetDisplayOfMousePointer()\n{\n CGEventRef Event = CGEventCreate(NULL);\n CGPoint Cursor = CGEventGetLocation(Event);\n CFRelease(Event);\n\n std::map<unsigned int, screen_info>::iterator It;\n for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)\n {\n screen_info *Screen = &It->second;\n if(Cursor.x >= Screen->X && Cursor.x <= Screen->X + Screen->Width &&\n Cursor.y >= Screen->Y && Cursor.y <= Screen->Y + Screen->Height)\n return Screen;\n }\n\n return NULL;\n}\n\nscreen_info *GetDisplayOfWindow(window_info *Window)\n{\n if(Window)\n {\n std::map<unsigned int, screen_info>::iterator It;\n for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)\n {\n screen_info *Screen = &It->second;\n if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)\n return Screen;\n }\n }\n\n return NULL;\n}\n\nstd::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)\n{\n screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);\n std::vector<window_info*> ScreenWindowLst;\n for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)\n {\n window_info *Window = &WindowLst[WindowIndex];\n if(!IsApplicationFloating(&WindowLst[WindowIndex]))\n {\n if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)\n ScreenWindowLst.push_back(Window);\n }\n }\n\n return ScreenWindowLst;\n}\n\nstd::vector<int> GetAllWindowIDsOnDisplay(int ScreenIndex)\n{\n screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);\n std::vector<int> ScreenWindowIDLst;\n for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)\n {\n window_info *Window = &WindowLst[WindowIndex];\n if(!IsApplicationFloating(&WindowLst[WindowIndex]))\n {\n if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)\n ScreenWindowIDLst.push_back(Window->WID);\n }\n }\n\n return ScreenWindowIDLst;\n}\n\nvoid SetDefaultPaddingOfDisplay(const std::string &Side, int Offset)\n{\n if(Side == \"left\")\n DefaultPaddingLeft = Offset;\n else if(Side == \"right\")\n DefaultPaddingRight = Offset;\n else if(Side == \"top\")\n DefaultPaddingTop = Offset;\n else if(Side == \"bottom\")\n DefaultPaddingBottom = Offset;\n}\n\nvoid SetDefaultGapOfDisplay(const std::string &Side, int Offset)\n{\n if(Side == \"vertical\")\n DefaultGapVertical = Offset;\n else if(Side == \"horizontal\")\n DefaultGapHorizontal = Offset;\n}\n\nvoid ChangePaddingOfDisplay(const std::string &Side, int Offset)\n{\n screen_info *Screen = GetDisplayOfMousePointer();\n if(Side == \"left\")\n Screen->Space[CurrentSpace].PaddingLeft += Offset;\n else if(Side == \"right\")\n Screen->Space[CurrentSpace].PaddingRight += Offset;\n else if(Side == \"top\")\n Screen->Space[CurrentSpace].PaddingTop += Offset;\n else if(Side == \"bottom\")\n Screen->Space[CurrentSpace].PaddingBottom += Offset;\n\n SetRootNodeContainer(Screen, Screen->Space[CurrentSpace].RootNode);\n CreateNodeContainers(Screen, Screen->Space[CurrentSpace].RootNode, true);\n ApplyNodeContainer(Screen->Space[CurrentSpace].RootNode);\n}\n\nvoid ChangeGapOfDisplay(const std::string &Side, int Offset)\n{\n screen_info *Screen = GetDisplayOfMousePointer();\n if(Side == \"vertical\")\n Screen->Space[CurrentSpace].VerticalGap += Offset;\n else if(Side == \"horizontal\")\n Screen->Space[CurrentSpace].HorizontalGap += Offset;\n\n CreateNodeContainers(Screen, Screen->Space[CurrentSpace].RootNode, true);\n ApplyNodeContainer(Screen->Space[CurrentSpace].RootNode);\n}\n\nvoid CycleFocusedWindowDisplay(int Shift)\n{\n screen_info *Screen = GetDisplayOfWindow(FocusedWindow);\n int NewScreenIndex = -1;\n\n if(Shift == 1)\n NewScreenIndex = (Screen->ID + 1 >= ActiveDisplaysCount) ? 0 : Screen->ID + 1;\n else if(Shift == -1)\n NewScreenIndex = (Screen->ID - 1 < 0) ? ActiveDisplaysCount - 1 : Screen->ID - 1;\n\n if(NewScreenIndex != Screen->ID)\n {\n screen_info *NewScreen = GetDisplayFromScreenID(NewScreenIndex);\n AddWindowToTreeOfUnfocusedMonitor(NewScreen);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"jakmuse_common.h\"\n\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <cctype>\n#include <cmath>\n#include <cassert>\n\n#include <iostream>\n#include <string>\n\nstatic signed translate_note(char name)\n{\n switch(name) {\n case 'C': return 0;\n case 'D': return 2;\n case 'E': return 4;\n case 'F': return 5;\n case 'G': return 7;\n case 'A': return 9;\n case 'B': return 11;\n default: abort();\n }\n}\n\nstatic unsigned short get_frequency(char name, signed scale, char accidental)\n{\n signed Ascale = 4;\n signed A = 9;\n signed note = translate_note(name);\n\n signed step = (scale - Ascale) * 12 + note - A;\n\n switch(accidental) {\n case '#':\n ++step;\n break;\n case 'b':\n --step;\n break;\n default:\n break;\n }\n\n return (unsigned short)(440.0f * std::pow(2.0f, (float)step \/ 12.0f));\n}\n\nstatic bool isnote(char c)\n{\n static char notes[] = \"CDEFGAB\";\n return strchr(notes, c) != NULL;\n}\n\nvoid parse()\n{\n while(!std::cin.eof()) {\n \/\/ get channel\n unsigned channel(255);\n std::cin >> channel;\n if(!std::cin.good()) break;\n assert(channel < 5);\n \/\/ get fill factor\n unsigned fill(128);\n std::cin >> fill;\n \/\/ get scale factor\n unsigned scale(1);\n std::cin >> scale;\n assert(scale);\n \/\/ start reading notes\n std::string s;\n do {\n std::cin >> s;\n if(s.empty() || s.compare(\";\") == 0) break;\n\n size_t i = 0;\n size_t const ns = s.size();\n\n int length = 0;\n do {\n if(i >= ns || !isdigit(s[i])) break;\n length *= 10;\n length += s[i++] - '0';\n } while(1);\n assert(length);\n assert(i < ns);\n\n char note = s[i++];\n unsigned short frequency(0);\n\n if(isnote(note)) {\n assert(i < ns);\n char accidental = '\\0';\n if(s[i] == '#' || s[i] == 'b') {\n accidental = s[i++];\n }\n assert(i < ns);\n\n signed offset = 0;\n do {\n if(i >= ns || !isdigit(s[i])) break;\n offset *= 10;\n offset += s[i++] - '0';\n } while(1);\n assert(i >= ns);\n\n frequency = get_frequency(note, offset, accidental);\n }\n\n for(size_t i = 0; i < length * scale; ++i) {\n pwm el = { frequency, fill };\n g_channels[channel].push_back(el);\n } \n\n g_maxChannelLen = std::max(g_maxChannelLen, g_channels[channel].size());\n } while(1);\n }\n}\n<commit_msg>parser tells you things<commit_after>#include \"jakmuse_common.h\"\n\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <cctype>\n#include <cmath>\n#include <cassert>\n\n#include <iostream>\n#include <string>\n#include <sstream>\n\nstatic int toknum = 0;\nstatic std::string token(\"\");\n\n#define ENSURE(a) do{ \\\n if(!(a)) cancel(#a); \\\n}while(0)\n\n#define TOKEN(a) do{ \\\n std::string STR; \\\n std::cin >> STR; \\\n std::stringstream S1; \\\n S1 << STR; \\\n S1 >> a; \\\n std::stringstream S; \\\n ++toknum; \\\n token.assign(STR); \\\n}while(0)\n\nstatic void cancel(const char* assertion)\n{\n fprintf(stderr, \"Syntax error near token %d \\\"%s\\\"\\n\", toknum, token.c_str());\n fprintf(stderr, \"Failed assertion '%s'\\n\", assertion);\n return abort();\n}\n\nstatic bool isnote(char c)\n{\n static char notes[] = \"CDEFGAB\";\n return strchr(notes, c) != NULL;\n}\n\nstatic signed translate_note(char name)\n{\n switch(name) {\n case 'C': return 0;\n case 'D': return 2;\n case 'E': return 4;\n case 'F': return 5;\n case 'G': return 7;\n case 'A': return 9;\n case 'B': return 11;\n default: ENSURE(isnote(name));\n }\n}\n\nstatic unsigned short get_frequency(char name, signed scale, char accidental)\n{\n signed Ascale = 4;\n signed A = 9;\n signed note = translate_note(name);\n\n signed step = (scale - Ascale) * 12 + note - A;\n\n switch(accidental) {\n case '#':\n ++step;\n break;\n case 'b':\n --step;\n break;\n default:\n break;\n }\n\n return (unsigned short)(440.0f * std::pow(2.0f, (float)step \/ 12.0f));\n}\n\nvoid parse()\n{\n while(!std::cin.eof()) {\n \/\/ get channel\n unsigned channel(255);\n TOKEN(channel);\n if(!std::cin.good()) break;\n ENSURE(channel < 5);\n \/\/ get fill factor\n unsigned fill(128);\n TOKEN(fill);\n \/\/ get scale factor\n unsigned scale(1);\n TOKEN(scale);\n ENSURE(scale > 0);\n \/\/ start reading notes\n std::string s;\n do {\n TOKEN(s);\n if(s.empty() || s.compare(\";\") == 0) break;\n\n size_t i = 0;\n size_t const ns = s.size();\n\n int length = 0;\n do {\n if(i >= ns || !isdigit(s[i])) break;\n length *= 10;\n length += s[i++] - '0';\n } while(1);\n ENSURE(length > 0);\n ENSURE(i < ns);\n\n char note = s[i++];\n unsigned short frequency(0);\n\n if(isnote(note)) {\n ENSURE(i < ns);\n char accidental = '\\0';\n if(s[i] == '#' || s[i] == 'b') {\n accidental = s[i++];\n }\n ENSURE(i < ns);\n\n signed offset = 0;\n do {\n if(i >= ns || !isdigit(s[i])) break;\n offset *= 10;\n offset += s[i++] - '0';\n } while(1);\n ENSURE(i >= ns);\n\n frequency = get_frequency(note, offset, accidental);\n }\n\n for(size_t i = 0; i < length * scale; ++i) {\n pwm el = { frequency, fill };\n g_channels[channel].push_back(el);\n } \n\n g_maxChannelLen = std::max(g_maxChannelLen, g_channels[channel].size());\n } while(1);\n ENSURE(std::cin.good());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cmath>\n#include <unistd.h>\n#include <gtest\/gtest.h>\n#include \"dronelink.h\"\n\nusing namespace dronelink;\n\nint test_offboard_velocity()\n{\n DroneLink dl;\n\n DroneLink::ConnectionResult ret = dl.add_udp_connection();\n if (ret != DroneLink::ConnectionResult::SUCCESS) {\n std::cout << \"failed to add connection.\" << std::endl;\n return -1;\n }\n\n \/\/ Wait for device to connect via heartbeat.\n usleep(1500000);\n\n std::vector<uint64_t> uuids = dl.device_uuids();\n\n for (auto it = uuids.begin(); it != uuids.end(); ++it) {\n std::cout << \"found device with UUID: \" << *it << std::endl;\n }\n\n if (uuids.size() > 1) {\n std::cout << \"found more than one device, not sure which one to use.\" << std::endl;\n return -1;\n } else if (uuids.size() == 0) {\n std::cout << \"no device found.\" << std::endl;\n return -1;\n }\n\n uint64_t uuid = uuids.at(0);\n\n Action::Result action_ret = dl.device(uuid).action().arm();\n if (action_ret != Action::Result::SUCCESS) {\n std::cout << \"failed to arm\" << std::endl;\n }\n\n usleep(500000);\n\n action_ret = dl.device(uuid).action().takeoff();\n if (action_ret != Action::Result::SUCCESS) {\n std::cout << \"failed to takeoff\" << std::endl;\n }\n\n usleep(5000000);\n\n \/\/ Send it once before starting offboard, otherwise it will be rejected.\n dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, 0.0f, 0.0f});\n\n Offboard::Result offboard_result = dl.device(uuid).offboard().start();\n\n if (offboard_result != Offboard::Result::SUCCESS) {\n std::cout << \"failed to start offboard\" << std::endl;\n return 1;\n }\n\n for (unsigned i = 0; i < 1000; ++i) {\n float vx = 5.0f * sinf(i * 0.01f);\n std::cout << \"vx: \" << vx << std::endl;\n dl.device(uuid).offboard().set_velocity({vx, 0.0f, 0.0f, 90.0f});\n usleep(10000);\n }\n\n offboard_result = dl.device(uuid).offboard().stop();\n\n if (offboard_result != Offboard::Result::SUCCESS) {\n std::cout << \"failed to stop offboard\" << std::endl;\n return 1;\n }\n\n action_ret = dl.device(uuid).action().land();\n if (action_ret != Action::Result::SUCCESS) {\n std::cout << \"failed to land\" << std::endl;\n }\n\n return 0;\n}\n\nTEST(Offboard, Velocity)\n{\n ASSERT_EQ(test_offboard_velocity(), 0);\n}\n\n<commit_msg>offboard_velocity: improve test<commit_after>#include <iostream>\n#include <cmath>\n#include <unistd.h>\n#include <gtest\/gtest.h>\n#include \"dronelink.h\"\n\nusing namespace dronelink;\n\nint test_offboard_velocity()\n{\n DroneLink dl;\n\n DroneLink::ConnectionResult ret = dl.add_udp_connection();\n if (ret != DroneLink::ConnectionResult::SUCCESS) {\n std::cout << \"failed to add connection.\" << std::endl;\n return -1;\n }\n\n \/\/ Wait for device to connect via heartbeat.\n usleep(1500000);\n\n std::vector<uint64_t> uuids = dl.device_uuids();\n\n for (auto it = uuids.begin(); it != uuids.end(); ++it) {\n std::cout << \"found device with UUID: \" << *it << std::endl;\n }\n\n if (uuids.size() > 1) {\n std::cout << \"found more than one device, not sure which one to use.\" << std::endl;\n return -1;\n } else if (uuids.size() == 0) {\n std::cout << \"no device found.\" << std::endl;\n return -1;\n }\n\n uint64_t uuid = uuids.at(0);\n\n Action::Result action_ret = dl.device(uuid).action().arm();\n if (action_ret != Action::Result::SUCCESS) {\n std::cout << \"failed to arm\" << std::endl;\n }\n\n usleep(500000);\n\n action_ret = dl.device(uuid).action().takeoff();\n if (action_ret != Action::Result::SUCCESS) {\n std::cout << \"failed to takeoff\" << std::endl;\n }\n\n usleep(5000000);\n\n \/\/ Send it once before starting offboard, otherwise it will be rejected.\n dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, 0.0f, 0.0f});\n\n Offboard::Result offboard_result = dl.device(uuid).offboard().start();\n\n if (offboard_result != Offboard::Result::SUCCESS) {\n std::cout << \"failed to start offboard\" << std::endl;\n return 1;\n }\n\n for (unsigned i = 0; i < 750; ++i) {\n float vx = 5.0f * sinf(i * 0.01f);\n \/\/std::cout << \"vx: \" << vx << std::endl;\n dl.device(uuid).offboard().set_velocity({vx, 0.0f, 0.0f, 90.0f});\n usleep(10000);\n }\n\n for (unsigned i = 0; i < 100; ++i) {\n dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, 0.0f, 270.0f});\n usleep(10000);\n }\n\n for (unsigned i = 0; i < 100; ++i) {\n dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, -2.0f, 180.0f});\n usleep(10000);\n }\n\n dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, 0.0f, 90.0f});\n for (unsigned i = 0; i < 100; ++i) {\n usleep(10000);\n }\n\n for (unsigned i = 0; i < 100; ++i) {\n dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, -1.0f, 0.0f});\n usleep(10000);\n }\n\n offboard_result = dl.device(uuid).offboard().stop();\n\n if (offboard_result != Offboard::Result::SUCCESS) {\n std::cout << \"failed to stop offboard\" << std::endl;\n return 1;\n }\n\n action_ret = dl.device(uuid).action().land();\n if (action_ret != Action::Result::SUCCESS) {\n std::cout << \"failed to land\" << std::endl;\n }\n\n return 0;\n}\n\nTEST(Offboard, Velocity)\n{\n ASSERT_EQ(test_offboard_velocity(), 0);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 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 \"content\/child\/runtime_features.h\"\n\n#include \"base\/command_line.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"third_party\/WebKit\/public\/web\/WebRuntimeFeatures.h\"\n\n#if defined(OS_ANDROID)\n#include <cpu-features.h>\n#include \"media\/base\/android\/media_codec_bridge.h\"\n#endif\n\nusing blink::WebRuntimeFeatures;\n\nnamespace content {\n\nstatic void SetRuntimeFeatureDefaultsForPlatform() {\n#if defined(OS_ANDROID)\n#if !defined(GOOGLE_TV)\n \/\/ MSE\/EME implementation needs Android MediaCodec API.\n if (!media::MediaCodecBridge::IsAvailable()) {\n WebRuntimeFeatures::enableWebKitMediaSource(false);\n WebRuntimeFeatures::enableMediaSource(false);\n WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);\n }\n#endif \/\/ !defined(GOOGLE_TV)\n \/\/ WebAudio is enabled by default only on ARM and only when the\n \/\/ MediaCodec API is available.\n WebRuntimeFeatures::enableWebAudio(\n media::MediaCodecBridge::IsAvailable() &&\n (android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM));\n \/\/ Android does not support the Gamepad API.\n WebRuntimeFeatures::enableGamepad(false);\n \/\/ Android does not have support for PagePopup\n WebRuntimeFeatures::enablePagePopup(false);\n \/\/ Android does not yet support the Web Notification API. crbug.com\/115320\n WebRuntimeFeatures::enableNotifications(false);\n \/\/ Android does not yet support SharedWorker. crbug.com\/154571\n WebRuntimeFeatures::enableSharedWorker(false);\n \/\/ Android does not yet support NavigatorContentUtils.\n WebRuntimeFeatures::enableNavigatorContentUtils(false);\n WebRuntimeFeatures::enableTouchIconLoading(true);\n#else\n WebRuntimeFeatures::enableNavigatorContentUtils(true);\n#endif \/\/ defined(OS_ANDROID)\n}\n\nvoid SetRuntimeFeaturesDefaultsAndUpdateFromArgs(\n const CommandLine& command_line) {\n WebRuntimeFeatures::enableStableFeatures(true);\n\n if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures))\n WebRuntimeFeatures::enableExperimentalFeatures(true);\n\n SetRuntimeFeatureDefaultsForPlatform();\n\n if (command_line.HasSwitch(switches::kDisableDatabases))\n WebRuntimeFeatures::enableDatabase(false);\n\n if (command_line.HasSwitch(switches::kDisableApplicationCache))\n WebRuntimeFeatures::enableApplicationCache(false);\n\n if (command_line.HasSwitch(switches::kDisableDesktopNotifications))\n WebRuntimeFeatures::enableNotifications(false);\n\n if (command_line.HasSwitch(switches::kDisableNavigatorContentUtils))\n WebRuntimeFeatures::enableNavigatorContentUtils(false);\n\n if (command_line.HasSwitch(switches::kDisableLocalStorage))\n WebRuntimeFeatures::enableLocalStorage(false);\n\n if (command_line.HasSwitch(switches::kDisableSessionStorage))\n WebRuntimeFeatures::enableSessionStorage(false);\n\n if (command_line.HasSwitch(switches::kDisableGeolocation))\n WebRuntimeFeatures::enableGeolocation(false);\n\n if (command_line.HasSwitch(switches::kDisableWebKitMediaSource))\n WebRuntimeFeatures::enableWebKitMediaSource(false);\n\n if (command_line.HasSwitch(switches::kDisableUnprefixedMediaSource))\n WebRuntimeFeatures::enableMediaSource(false);\n\n if (command_line.HasSwitch(switches::kDisableSharedWorkers))\n WebRuntimeFeatures::enableSharedWorker(false);\n\n#if defined(OS_ANDROID)\n if (command_line.HasSwitch(switches::kDisableWebRTC)) {\n WebRuntimeFeatures::enableMediaStream(false);\n WebRuntimeFeatures::enablePeerConnection(false);\n }\n\n if (!command_line.HasSwitch(switches::kEnableSpeechRecognition))\n WebRuntimeFeatures::enableScriptedSpeech(false);\n#endif\n\n if (command_line.HasSwitch(switches::kEnableServiceWorker))\n WebRuntimeFeatures::enableServiceWorker(true);\n\n#if defined(OS_ANDROID)\n \/\/ WebAudio requires the MediaCodec API.\n#if defined(ARCH_CPU_X86)\n \/\/ WebAudio is disabled by default on x86.\n WebRuntimeFeatures::enableWebAudio(\n command_line.HasSwitch(switches::kEnableWebAudio) &&\n media::MediaCodecBridge::IsAvailable());\n#elif defined(ARCH_CPU_ARMEL)\n \/\/ WebAudio is enabled by default on ARM.\n WebRuntimeFeatures::enableWebAudio(\n !command_line.HasSwitch(switches::kDisableWebAudio) &&\n media::MediaCodecBridge::IsAvailable());\n#else\n WebRuntimeFeatures::enableWebAudio(false);\n#endif\n#else\n if (command_line.HasSwitch(switches::kDisableWebAudio))\n WebRuntimeFeatures::enableWebAudio(false);\n#endif\n\n if (command_line.HasSwitch(switches::kDisableFullScreen))\n WebRuntimeFeatures::enableFullscreen(false);\n\n if (command_line.HasSwitch(switches::kEnableEncryptedMedia))\n WebRuntimeFeatures::enableEncryptedMedia(true);\n\n if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia))\n WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);\n\n \/\/ FIXME: Remove the enable switch once Web Animations CSS is enabled by\n \/\/ default in Blink.\n if (command_line.HasSwitch(switches::kEnableWebAnimationsCSS))\n WebRuntimeFeatures::enableWebAnimationsCSS(true);\n else if (command_line.HasSwitch(switches::kDisableWebAnimationsCSS))\n WebRuntimeFeatures::enableWebAnimationsCSS(false);\n\n if (command_line.HasSwitch(switches::kEnableWebAnimationsSVG))\n WebRuntimeFeatures::enableWebAnimationsSVG(true);\n\n if (command_line.HasSwitch(switches::kEnableWebMIDI))\n WebRuntimeFeatures::enableWebMIDI(true);\n\n if (command_line.HasSwitch(switches::kDisableDeviceMotion))\n WebRuntimeFeatures::enableDeviceMotion(false);\n\n if (command_line.HasSwitch(switches::kDisableDeviceOrientation))\n WebRuntimeFeatures::enableDeviceOrientation(false);\n\n if (command_line.HasSwitch(switches::kDisableSpeechInput))\n WebRuntimeFeatures::enableSpeechInput(false);\n\n if (command_line.HasSwitch(switches::kDisableFileSystem))\n WebRuntimeFeatures::enableFileSystem(false);\n\n#if defined(OS_WIN)\n if (command_line.HasSwitch(switches::kEnableDirectWrite))\n WebRuntimeFeatures::enableDirectWrite(true);\n#endif\n\n if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))\n WebRuntimeFeatures::enableExperimentalCanvasFeatures(true);\n\n if (command_line.HasSwitch(switches::kEnableSpeechSynthesis))\n WebRuntimeFeatures::enableSpeechSynthesis(true);\n\n if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))\n WebRuntimeFeatures::enableWebGLDraftExtensions(true);\n\n if (command_line.HasSwitch(switches::kEnableHTMLImports))\n WebRuntimeFeatures::enableHTMLImports(true);\n\n if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo))\n WebRuntimeFeatures::enableOverlayFullscreenVideo(true);\n\n if (command_line.HasSwitch(switches::kEnableOverlayScrollbars))\n WebRuntimeFeatures::enableOverlayScrollbars(true);\n\n if (command_line.HasSwitch(switches::kEnableInputModeAttribute))\n WebRuntimeFeatures::enableInputModeAttribute(true);\n\n if (command_line.HasSwitch(switches::kEnableFastTextAutosizing))\n WebRuntimeFeatures::enableFastTextAutosizing(true);\n\n if (command_line.HasSwitch(switches::kEnableRepaintAfterLayout))\n WebRuntimeFeatures::enableRepaintAfterLayout(true);\n}\n\n} \/\/ namespace content\n<commit_msg>Enable OrientationEvent only for android.<commit_after>\/\/ Copyright 2013 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 \"content\/child\/runtime_features.h\"\n\n#include \"base\/command_line.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"third_party\/WebKit\/public\/web\/WebRuntimeFeatures.h\"\n\n#if defined(OS_ANDROID)\n#include <cpu-features.h>\n#include \"media\/base\/android\/media_codec_bridge.h\"\n#endif\n\nusing blink::WebRuntimeFeatures;\n\nnamespace content {\n\nstatic void SetRuntimeFeatureDefaultsForPlatform() {\n#if defined(OS_ANDROID)\n#if !defined(GOOGLE_TV)\n \/\/ MSE\/EME implementation needs Android MediaCodec API.\n if (!media::MediaCodecBridge::IsAvailable()) {\n WebRuntimeFeatures::enableWebKitMediaSource(false);\n WebRuntimeFeatures::enableMediaSource(false);\n WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);\n }\n#endif \/\/ !defined(GOOGLE_TV)\n \/\/ WebAudio is enabled by default only on ARM and only when the\n \/\/ MediaCodec API is available.\n WebRuntimeFeatures::enableWebAudio(\n media::MediaCodecBridge::IsAvailable() &&\n (android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM));\n \/\/ Android does not support the Gamepad API.\n WebRuntimeFeatures::enableGamepad(false);\n \/\/ Android does not have support for PagePopup\n WebRuntimeFeatures::enablePagePopup(false);\n \/\/ Android does not yet support the Web Notification API. crbug.com\/115320\n WebRuntimeFeatures::enableNotifications(false);\n \/\/ Android does not yet support SharedWorker. crbug.com\/154571\n WebRuntimeFeatures::enableSharedWorker(false);\n \/\/ Android does not yet support NavigatorContentUtils.\n WebRuntimeFeatures::enableNavigatorContentUtils(false);\n WebRuntimeFeatures::enableTouchIconLoading(true);\n WebRuntimeFeatures::enableOrientationEvent(true);\n#else\n WebRuntimeFeatures::enableNavigatorContentUtils(true);\n#endif \/\/ defined(OS_ANDROID)\n}\n\nvoid SetRuntimeFeaturesDefaultsAndUpdateFromArgs(\n const CommandLine& command_line) {\n WebRuntimeFeatures::enableStableFeatures(true);\n\n if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures))\n WebRuntimeFeatures::enableExperimentalFeatures(true);\n\n SetRuntimeFeatureDefaultsForPlatform();\n\n if (command_line.HasSwitch(switches::kDisableDatabases))\n WebRuntimeFeatures::enableDatabase(false);\n\n if (command_line.HasSwitch(switches::kDisableApplicationCache))\n WebRuntimeFeatures::enableApplicationCache(false);\n\n if (command_line.HasSwitch(switches::kDisableDesktopNotifications))\n WebRuntimeFeatures::enableNotifications(false);\n\n if (command_line.HasSwitch(switches::kDisableNavigatorContentUtils))\n WebRuntimeFeatures::enableNavigatorContentUtils(false);\n\n if (command_line.HasSwitch(switches::kDisableLocalStorage))\n WebRuntimeFeatures::enableLocalStorage(false);\n\n if (command_line.HasSwitch(switches::kDisableSessionStorage))\n WebRuntimeFeatures::enableSessionStorage(false);\n\n if (command_line.HasSwitch(switches::kDisableGeolocation))\n WebRuntimeFeatures::enableGeolocation(false);\n\n if (command_line.HasSwitch(switches::kDisableWebKitMediaSource))\n WebRuntimeFeatures::enableWebKitMediaSource(false);\n\n if (command_line.HasSwitch(switches::kDisableUnprefixedMediaSource))\n WebRuntimeFeatures::enableMediaSource(false);\n\n if (command_line.HasSwitch(switches::kDisableSharedWorkers))\n WebRuntimeFeatures::enableSharedWorker(false);\n\n#if defined(OS_ANDROID)\n if (command_line.HasSwitch(switches::kDisableWebRTC)) {\n WebRuntimeFeatures::enableMediaStream(false);\n WebRuntimeFeatures::enablePeerConnection(false);\n }\n\n if (!command_line.HasSwitch(switches::kEnableSpeechRecognition))\n WebRuntimeFeatures::enableScriptedSpeech(false);\n#endif\n\n if (command_line.HasSwitch(switches::kEnableServiceWorker))\n WebRuntimeFeatures::enableServiceWorker(true);\n\n#if defined(OS_ANDROID)\n \/\/ WebAudio requires the MediaCodec API.\n#if defined(ARCH_CPU_X86)\n \/\/ WebAudio is disabled by default on x86.\n WebRuntimeFeatures::enableWebAudio(\n command_line.HasSwitch(switches::kEnableWebAudio) &&\n media::MediaCodecBridge::IsAvailable());\n#elif defined(ARCH_CPU_ARMEL)\n \/\/ WebAudio is enabled by default on ARM.\n WebRuntimeFeatures::enableWebAudio(\n !command_line.HasSwitch(switches::kDisableWebAudio) &&\n media::MediaCodecBridge::IsAvailable());\n#else\n WebRuntimeFeatures::enableWebAudio(false);\n#endif\n#else\n if (command_line.HasSwitch(switches::kDisableWebAudio))\n WebRuntimeFeatures::enableWebAudio(false);\n#endif\n\n if (command_line.HasSwitch(switches::kDisableFullScreen))\n WebRuntimeFeatures::enableFullscreen(false);\n\n if (command_line.HasSwitch(switches::kEnableEncryptedMedia))\n WebRuntimeFeatures::enableEncryptedMedia(true);\n\n if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia))\n WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);\n\n \/\/ FIXME: Remove the enable switch once Web Animations CSS is enabled by\n \/\/ default in Blink.\n if (command_line.HasSwitch(switches::kEnableWebAnimationsCSS))\n WebRuntimeFeatures::enableWebAnimationsCSS(true);\n else if (command_line.HasSwitch(switches::kDisableWebAnimationsCSS))\n WebRuntimeFeatures::enableWebAnimationsCSS(false);\n\n if (command_line.HasSwitch(switches::kEnableWebAnimationsSVG))\n WebRuntimeFeatures::enableWebAnimationsSVG(true);\n\n if (command_line.HasSwitch(switches::kEnableWebMIDI))\n WebRuntimeFeatures::enableWebMIDI(true);\n\n if (command_line.HasSwitch(switches::kDisableDeviceMotion))\n WebRuntimeFeatures::enableDeviceMotion(false);\n\n if (command_line.HasSwitch(switches::kDisableDeviceOrientation))\n WebRuntimeFeatures::enableDeviceOrientation(false);\n\n if (command_line.HasSwitch(switches::kDisableSpeechInput))\n WebRuntimeFeatures::enableSpeechInput(false);\n\n if (command_line.HasSwitch(switches::kDisableFileSystem))\n WebRuntimeFeatures::enableFileSystem(false);\n\n#if defined(OS_WIN)\n if (command_line.HasSwitch(switches::kEnableDirectWrite))\n WebRuntimeFeatures::enableDirectWrite(true);\n#endif\n\n if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))\n WebRuntimeFeatures::enableExperimentalCanvasFeatures(true);\n\n if (command_line.HasSwitch(switches::kEnableSpeechSynthesis))\n WebRuntimeFeatures::enableSpeechSynthesis(true);\n\n if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))\n WebRuntimeFeatures::enableWebGLDraftExtensions(true);\n\n if (command_line.HasSwitch(switches::kEnableHTMLImports))\n WebRuntimeFeatures::enableHTMLImports(true);\n\n if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo))\n WebRuntimeFeatures::enableOverlayFullscreenVideo(true);\n\n if (command_line.HasSwitch(switches::kEnableOverlayScrollbars))\n WebRuntimeFeatures::enableOverlayScrollbars(true);\n\n if (command_line.HasSwitch(switches::kEnableInputModeAttribute))\n WebRuntimeFeatures::enableInputModeAttribute(true);\n\n if (command_line.HasSwitch(switches::kEnableFastTextAutosizing))\n WebRuntimeFeatures::enableFastTextAutosizing(true);\n\n if (command_line.HasSwitch(switches::kEnableRepaintAfterLayout))\n WebRuntimeFeatures::enableRepaintAfterLayout(true);\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include <dune\/stuff\/test\/main.hxx>\n\n#include \"prolongations\/l2-global.hh\"\n#include \"spaces\/cg\/fem.hh\"\n\nusing namespace Dune::GDT::Test;\n\n#if HAVE_DUNE_FEM\n\n\ntypedef testing::Types<SPACES_CG_FEM_LEVEL(1)\n#if HAVE_ALUGRID\n ,\n SPACES_CG_FEM_ALUGRID_LEVEL(1)\n#endif\n > SpaceTypes;\n\nTYPED_TEST_CASE(L2GlobalProlongationLocalizableOperatorTest, SpaceTypes);\nTYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, constructible_by_ctor)\n{\n this->constructible_by_ctor();\n}\nTYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, constructible_by_factory)\n{\n this->constructible_by_factory();\n}\nTYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, produces_correct_results)\n{\n this->produces_correct_results();\n}\n\n\n#else \/\/ HAVE_DUNE_FEM\n\n\nTEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, constructible_by_ctor)\n{\n}\nTEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, constructible_by_factory)\n{\n}\nTEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, produces_correct_results)\n{\n}\n\n\n#endif \/\/ HAVE_DUNE_FEM\n<commit_msg>[test.prolongations.l2_global] update expected results<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include <dune\/stuff\/test\/main.hxx>\n\n#include \"prolongations\/l2-global.hh\"\n#include \"spaces\/cg\/fem.hh\"\n\nusing namespace Dune::GDT::Test;\n\n#if HAVE_DUNE_FEM\n\n\ntypedef testing::Types<SPACES_CG_FEM_LEVEL(1)\n#if HAVE_ALUGRID\n ,\n SPACES_CG_FEM_ALUGRID_LEVEL(1)\n#endif\n > SpaceTypes;\n\nTYPED_TEST_CASE(L2GlobalProlongationLocalizableOperatorTest, SpaceTypes);\nTYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, constructible_by_ctor)\n{\n this->constructible_by_ctor();\n}\nTYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, constructible_by_factory)\n{\n this->constructible_by_factory();\n}\nTYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, produces_correct_results)\n{\n this->produces_correct_results(2.49e-14);\n}\n\n\n#else \/\/ HAVE_DUNE_FEM\n\n\nTEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, constructible_by_ctor)\n{\n}\nTEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, constructible_by_factory)\n{\n}\nTEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, produces_correct_results)\n{\n}\n\n\n#endif \/\/ HAVE_DUNE_FEM\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n#include \"libmesh_common.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\n\n\/\/ C++ includes\n\n\/\/ Local Includes\n#include \"nonlinear_implicit_system.h\"\n#include \"petsc_nonlinear_solver.h\"\n#include \"petsc_linear_solver.h\"\n#include \"petsc_vector.h\"\n#include \"petsc_matrix.h\"\n#include \"system.h\"\n#include \"dof_map.h\"\n#include \"preconditioner.h\"\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc. PETSc will call these\n\/\/ methods as needed.\n\/\/ \n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n \/\/ Older versions of PETSc do not have the different int typedefs.\n \/\/ On 64-bit machines, PetscInt may actually be a long long int.\n \/\/ This change occurred in Petsc-2.2.1.\n#if PETSC_VERSION_LESS_THAN(2,2,1)\n typedef int PetscErrorCode;\n typedef int PetscInt;\n#endif\n \n \/\/-------------------------------------------------------------------\n \/\/ this function is called by PETSc at the end of each nonlinear step \n PetscErrorCode\n __libmesh_petsc_snes_monitor (SNES, PetscInt its, PetscReal fnorm, void *)\n {\n \/\/int ierr=0;\n\n \/\/if (its > 0)\n libMesh::out << \" NL step \"\n\t\t << std::setw(2) << its\n\t\t << std::scientific\n\t\t << \", |residual|_2 = \" << fnorm\n\t\t << std::endl;\n\n \/\/return ierr;\n return 0;\n }\n\n\n\n \/\/---------------------------------------------------------------\n \/\/ this function is called by PETSc to evaluate the residual at X\n PetscErrorCode\n __libmesh_petsc_snes_residual (SNES, Vec x, Vec r, void *ctx)\n {\n int ierr=0;\n\n libmesh_assert (x != NULL);\n libmesh_assert (r != NULL);\n libmesh_assert (ctx != NULL);\n \n PetscNonlinearSolver<Number>* solver =\n static_cast<PetscNonlinearSolver<Number>*> (ctx);\n \n NonlinearImplicitSystem &sys = solver->system();\n\n PetscVector<Number>& X_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.solution.get());\n PetscVector<Number>& R_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.rhs);\n PetscVector<Number> X_global(x), R(r);\n\n \/\/ Use the systems update() to get a good local version of the parallel solution\n X_global.swap(X_sys);\n R.swap(R_sys);\n\n sys.get_dof_map().enforce_constraints_exactly(sys);\n \n sys.update();\n\n \/\/Swap back\n X_global.swap(X_sys);\n R.swap(R_sys);\n\n R.zero();\n\n if (solver->residual != NULL) solver->residual (*sys.current_local_solution.get(), R);\n else if (solver->matvec != NULL) solver->matvec (*sys.current_local_solution.get(), &R, NULL);\n else libmesh_error();\n \n R.close();\n X_global.close();\n \n return ierr;\n }\n\n\n \n \/\/---------------------------------------------------------------\n \/\/ this function is called by PETSc to evaluate the Jacobian at X\n PetscErrorCode\n __libmesh_petsc_snes_jacobian (SNES, Vec x, Mat *jac, Mat *pc, MatStructure *msflag, void *ctx)\n {\n int ierr=0;\n \n libmesh_assert (ctx != NULL);\n \n PetscNonlinearSolver<Number>* solver =\n static_cast<PetscNonlinearSolver<Number>*> (ctx);\n\n NonlinearImplicitSystem &sys = solver->system();\n \n PetscMatrix<Number> PC(*pc);\n PetscMatrix<Number> Jac(*jac);\n PetscVector<Number>& X_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.solution.get());\n PetscMatrix<Number>& Jac_sys = *libmesh_cast_ptr<PetscMatrix<Number>*>(sys.matrix);\n PetscVector<Number> X_global(x);\n\n \/\/ Set the dof maps\n PC.attach_dof_map(sys.get_dof_map());\n Jac.attach_dof_map(sys.get_dof_map());\n\n \/\/ Use the systems update() to get a good local version of the parallel solution\n X_global.swap(X_sys);\n Jac.swap(Jac_sys);\n\n sys.get_dof_map().enforce_constraints_exactly(sys);\n sys.update();\n\n X_global.swap(X_sys);\n Jac.swap(Jac_sys);\n\n PC.zero();\n\n if (solver->jacobian != NULL) solver->jacobian (*sys.current_local_solution.get(), PC);\n else if (solver->matvec != NULL) solver->matvec (*sys.current_local_solution.get(), NULL, &PC);\n else libmesh_error();\n \n PC.close();\n Jac.close();\n X_global.close();\n \n *msflag = SAME_NONZERO_PATTERN;\n \n return ierr;\n }\n \n} \/\/ end extern \"C\"\n\/\/---------------------------------------------------------------------\n\n\n\n\/\/---------------------------------------------------------------------\n\/\/ PetscNonlinearSolver<> methods\ntemplate <typename T>\nvoid PetscNonlinearSolver<T>::clear ()\n{\n if (this->initialized())\n {\n this->_is_initialized = false;\n\n int ierr=0;\n\n ierr = SNESDestroy(_snes);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n }\n}\n\n\n\ntemplate <typename T>\nvoid PetscNonlinearSolver<T>::init ()\n{ \n \/\/ Initialize the data structures if not done so already.\n if (!this->initialized())\n {\n this->_is_initialized = true;\n \n int ierr=0;\n\n#if PETSC_VERSION_LESS_THAN(2,1,2)\n \/\/ At least until Petsc 2.1.1, the SNESCreate had a different calling syntax.\n \/\/ The second argument was of type SNESProblemType, and could have a value of\n \/\/ either SNES_NONLINEAR_EQUATIONS or SNES_UNCONSTRAINED_MINIMIZATION.\n ierr = SNESCreate(libMesh::COMM_WORLD, SNES_NONLINEAR_EQUATIONS, &_snes);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n#else\n\n ierr = SNESCreate(libMesh::COMM_WORLD,&_snes);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n#endif\t \n\n#if PETSC_VERSION_LESS_THAN(2,3,3)\n ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,\n\t\t\t this, PETSC_NULL);\n#else\n \/\/ API name change in PETSc 2.3.3\n ierr = SNESMonitorSet (_snes, __libmesh_petsc_snes_monitor,\n\t\t\t this, PETSC_NULL);\n#endif\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t \n ierr = SNESSetFromOptions(_snes);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n if(this->_preconditioner)\n {\n KSP ksp;\t \n ierr = SNESGetKSP (_snes, &ksp);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n PC pc;\n ierr = KSPGetPC(ksp,&pc);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n \n PCSetType(pc, PCSHELL);\n PCShellSetContext(pc,(void*)this->_preconditioner);\n\n \/\/Re-Use the shell functions from petsc_linear_solver\n PCShellSetSetUp(pc,__libmesh_petsc_preconditioner_setup);\n PCShellSetApply(pc,__libmesh_petsc_preconditioner_apply);\n }\n }\n}\n\n\n\ntemplate <typename T>\nstd::pair<unsigned int, Real> \nPetscNonlinearSolver<T>::solve (SparseMatrix<T>& jac_in, \/\/ System Jacobian Matrix\n\t\t\t\tNumericVector<T>& x_in, \/\/ Solution vector\n\t\t\t\tNumericVector<T>& r_in, \/\/ Residual vector\n\t\t\t\tconst double, \/\/ Stopping tolerance\n\t\t\t\tconst unsigned int) \n{\n this->init ();\n \n \/\/ Make sure the data passed in are really of Petsc types\n PetscMatrix<T>* jac = libmesh_cast_ptr<PetscMatrix<T>*>(&jac_in);\n PetscVector<T>* x = libmesh_cast_ptr<PetscVector<T>*>(&x_in);\n PetscVector<T>* r = libmesh_cast_ptr<PetscVector<T>*>(&r_in);\n\n int ierr=0;\n int n_iterations =0;\n \/\/ Should actually be a PetscReal, but I don't know which version of PETSc first introduced PetscReal\n Real final_residual_norm=0.; \n\n ierr = SNESSetFunction (_snes, r->vec(), __libmesh_petsc_snes_residual, this);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESSetJacobian (_snes, jac->mat(), jac->mat(), __libmesh_petsc_snes_jacobian, this);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Have the Krylov subspace method use our good initial guess rather than 0\n KSP ksp;\t \n ierr = SNESGetKSP (_snes, &ksp);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Set the tolerances for the iterative solver. Use the user-supplied\n \/\/ tolerance for the relative residual & leave the others at default values\n ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,\n PETSC_DEFAULT, this->max_linear_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Set the tolerances for the non-linear solver.\n ierr = SNESSetTolerances(_snes, this->absolute_residual_tolerance, this->relative_residual_tolerance,\n this->absolute_step_tolerance, this->max_nonlinear_iterations, this->max_function_evaluations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/Pull in command-line options \n KSPSetFromOptions(ksp);\n SNESSetFromOptions(_snes);\n\n \/\/Set the preconditioning matrix\n if(this->_preconditioner)\n this->_preconditioner->set_matrix(jac_in);\n\n\/\/ ierr = KSPSetInitialGuessNonzero (ksp, PETSC_TRUE);\n\/\/ CHKERRABORT(libMesh::COMM_WORLD,ierr);\n \t \n\/\/ Older versions (at least up to 2.1.5) of SNESSolve took 3 arguments,\n\/\/ the last one being a pointer to an int to hold the number of iterations required.\n# if PETSC_VERSION_LESS_THAN(2,2,0)\n\n ierr = SNESSolve (_snes, x->vec(), &n_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n\/\/ 2.2.x style\t\n#elif PETSC_VERSION_LESS_THAN(2,3,0)\n\t\n ierr = SNESSolve (_snes, x->vec());\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n\/\/ 2.3.x & newer style\t\n#else\n\t\n ierr = SNESSolve (_snes, PETSC_NULL, x->vec());\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t \t\n#endif\n\n SNESConvergedReason reason;\n SNESGetConvergedReason(_snes,&reason);\n SNESGetIterationNumber(_snes,&n_iterations);\n SNESGetFunctionNorm(_snes,&final_residual_norm);\n\n \/\/Based on Petsc 2.3.3 documentation all diverged reasons are negative\n this->converged = reason >= 0;\n\n this->clear();\n\t\t \n \/\/ return the # of its. and the final residual norm.\n return std::make_pair(n_iterations, final_residual_norm);\n}\n\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ Explicit instantiations\ntemplate class PetscNonlinearSolver<Number>;\n \n\n\n#endif \/\/ #ifdef LIBMESH_HAVE_PETSC\n<commit_msg>Move calls to SNESGetIterationNumber and SNESGetFunctionNorm to within PETSc 2.3.x and greater codepaths.<commit_after>\/\/ $Id$\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n#include \"libmesh_common.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\n\n\/\/ C++ includes\n\n\/\/ Local Includes\n#include \"nonlinear_implicit_system.h\"\n#include \"petsc_nonlinear_solver.h\"\n#include \"petsc_linear_solver.h\"\n#include \"petsc_vector.h\"\n#include \"petsc_matrix.h\"\n#include \"system.h\"\n#include \"dof_map.h\"\n#include \"preconditioner.h\"\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc. PETSc will call these\n\/\/ methods as needed.\n\/\/ \n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n \/\/ Older versions of PETSc do not have the different int typedefs.\n \/\/ On 64-bit machines, PetscInt may actually be a long long int.\n \/\/ This change occurred in Petsc-2.2.1.\n#if PETSC_VERSION_LESS_THAN(2,2,1)\n typedef int PetscErrorCode;\n typedef int PetscInt;\n#endif\n \n \/\/-------------------------------------------------------------------\n \/\/ this function is called by PETSc at the end of each nonlinear step \n PetscErrorCode\n __libmesh_petsc_snes_monitor (SNES, PetscInt its, PetscReal fnorm, void *)\n {\n \/\/int ierr=0;\n\n \/\/if (its > 0)\n libMesh::out << \" NL step \"\n\t\t << std::setw(2) << its\n\t\t << std::scientific\n\t\t << \", |residual|_2 = \" << fnorm\n\t\t << std::endl;\n\n \/\/return ierr;\n return 0;\n }\n\n\n\n \/\/---------------------------------------------------------------\n \/\/ this function is called by PETSc to evaluate the residual at X\n PetscErrorCode\n __libmesh_petsc_snes_residual (SNES, Vec x, Vec r, void *ctx)\n {\n int ierr=0;\n\n libmesh_assert (x != NULL);\n libmesh_assert (r != NULL);\n libmesh_assert (ctx != NULL);\n \n PetscNonlinearSolver<Number>* solver =\n static_cast<PetscNonlinearSolver<Number>*> (ctx);\n \n NonlinearImplicitSystem &sys = solver->system();\n\n PetscVector<Number>& X_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.solution.get());\n PetscVector<Number>& R_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.rhs);\n PetscVector<Number> X_global(x), R(r);\n\n \/\/ Use the systems update() to get a good local version of the parallel solution\n X_global.swap(X_sys);\n R.swap(R_sys);\n\n sys.get_dof_map().enforce_constraints_exactly(sys);\n \n sys.update();\n\n \/\/Swap back\n X_global.swap(X_sys);\n R.swap(R_sys);\n\n R.zero();\n\n if (solver->residual != NULL) solver->residual (*sys.current_local_solution.get(), R);\n else if (solver->matvec != NULL) solver->matvec (*sys.current_local_solution.get(), &R, NULL);\n else libmesh_error();\n \n R.close();\n X_global.close();\n \n return ierr;\n }\n\n\n \n \/\/---------------------------------------------------------------\n \/\/ this function is called by PETSc to evaluate the Jacobian at X\n PetscErrorCode\n __libmesh_petsc_snes_jacobian (SNES, Vec x, Mat *jac, Mat *pc, MatStructure *msflag, void *ctx)\n {\n int ierr=0;\n \n libmesh_assert (ctx != NULL);\n \n PetscNonlinearSolver<Number>* solver =\n static_cast<PetscNonlinearSolver<Number>*> (ctx);\n\n NonlinearImplicitSystem &sys = solver->system();\n \n PetscMatrix<Number> PC(*pc);\n PetscMatrix<Number> Jac(*jac);\n PetscVector<Number>& X_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.solution.get());\n PetscMatrix<Number>& Jac_sys = *libmesh_cast_ptr<PetscMatrix<Number>*>(sys.matrix);\n PetscVector<Number> X_global(x);\n\n \/\/ Set the dof maps\n PC.attach_dof_map(sys.get_dof_map());\n Jac.attach_dof_map(sys.get_dof_map());\n\n \/\/ Use the systems update() to get a good local version of the parallel solution\n X_global.swap(X_sys);\n Jac.swap(Jac_sys);\n\n sys.get_dof_map().enforce_constraints_exactly(sys);\n sys.update();\n\n X_global.swap(X_sys);\n Jac.swap(Jac_sys);\n\n PC.zero();\n\n if (solver->jacobian != NULL) solver->jacobian (*sys.current_local_solution.get(), PC);\n else if (solver->matvec != NULL) solver->matvec (*sys.current_local_solution.get(), NULL, &PC);\n else libmesh_error();\n \n PC.close();\n Jac.close();\n X_global.close();\n \n *msflag = SAME_NONZERO_PATTERN;\n \n return ierr;\n }\n \n} \/\/ end extern \"C\"\n\/\/---------------------------------------------------------------------\n\n\n\n\/\/---------------------------------------------------------------------\n\/\/ PetscNonlinearSolver<> methods\ntemplate <typename T>\nvoid PetscNonlinearSolver<T>::clear ()\n{\n if (this->initialized())\n {\n this->_is_initialized = false;\n\n int ierr=0;\n\n ierr = SNESDestroy(_snes);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n }\n}\n\n\n\ntemplate <typename T>\nvoid PetscNonlinearSolver<T>::init ()\n{ \n \/\/ Initialize the data structures if not done so already.\n if (!this->initialized())\n {\n this->_is_initialized = true;\n \n int ierr=0;\n\n#if PETSC_VERSION_LESS_THAN(2,1,2)\n \/\/ At least until Petsc 2.1.1, the SNESCreate had a different calling syntax.\n \/\/ The second argument was of type SNESProblemType, and could have a value of\n \/\/ either SNES_NONLINEAR_EQUATIONS or SNES_UNCONSTRAINED_MINIMIZATION.\n ierr = SNESCreate(libMesh::COMM_WORLD, SNES_NONLINEAR_EQUATIONS, &_snes);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n#else\n\n ierr = SNESCreate(libMesh::COMM_WORLD,&_snes);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n#endif\t \n\n#if PETSC_VERSION_LESS_THAN(2,3,3)\n ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,\n\t\t\t this, PETSC_NULL);\n#else\n \/\/ API name change in PETSc 2.3.3\n ierr = SNESMonitorSet (_snes, __libmesh_petsc_snes_monitor,\n\t\t\t this, PETSC_NULL);\n#endif\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t \n ierr = SNESSetFromOptions(_snes);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n if(this->_preconditioner)\n {\n KSP ksp;\t \n ierr = SNESGetKSP (_snes, &ksp);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n PC pc;\n ierr = KSPGetPC(ksp,&pc);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n \n PCSetType(pc, PCSHELL);\n PCShellSetContext(pc,(void*)this->_preconditioner);\n\n \/\/Re-Use the shell functions from petsc_linear_solver\n PCShellSetSetUp(pc,__libmesh_petsc_preconditioner_setup);\n PCShellSetApply(pc,__libmesh_petsc_preconditioner_apply);\n }\n }\n}\n\n\n\ntemplate <typename T>\nstd::pair<unsigned int, Real> \nPetscNonlinearSolver<T>::solve (SparseMatrix<T>& jac_in, \/\/ System Jacobian Matrix\n\t\t\t\tNumericVector<T>& x_in, \/\/ Solution vector\n\t\t\t\tNumericVector<T>& r_in, \/\/ Residual vector\n\t\t\t\tconst double, \/\/ Stopping tolerance\n\t\t\t\tconst unsigned int) \n{\n this->init ();\n \n \/\/ Make sure the data passed in are really of Petsc types\n PetscMatrix<T>* jac = libmesh_cast_ptr<PetscMatrix<T>*>(&jac_in);\n PetscVector<T>* x = libmesh_cast_ptr<PetscVector<T>*>(&x_in);\n PetscVector<T>* r = libmesh_cast_ptr<PetscVector<T>*>(&r_in);\n\n int ierr=0;\n int n_iterations =0;\n \/\/ Should actually be a PetscReal, but I don't know which version of PETSc first introduced PetscReal\n Real final_residual_norm=0.; \n\n ierr = SNESSetFunction (_snes, r->vec(), __libmesh_petsc_snes_residual, this);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESSetJacobian (_snes, jac->mat(), jac->mat(), __libmesh_petsc_snes_jacobian, this);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Have the Krylov subspace method use our good initial guess rather than 0\n KSP ksp;\t \n ierr = SNESGetKSP (_snes, &ksp);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Set the tolerances for the iterative solver. Use the user-supplied\n \/\/ tolerance for the relative residual & leave the others at default values\n ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,\n PETSC_DEFAULT, this->max_linear_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Set the tolerances for the non-linear solver.\n ierr = SNESSetTolerances(_snes, this->absolute_residual_tolerance, this->relative_residual_tolerance,\n this->absolute_step_tolerance, this->max_nonlinear_iterations, this->max_function_evaluations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/Pull in command-line options \n KSPSetFromOptions(ksp);\n SNESSetFromOptions(_snes);\n\n \/\/Set the preconditioning matrix\n if(this->_preconditioner)\n this->_preconditioner->set_matrix(jac_in);\n\n\/\/ ierr = KSPSetInitialGuessNonzero (ksp, PETSC_TRUE);\n\/\/ CHKERRABORT(libMesh::COMM_WORLD,ierr);\n \t \n\/\/ Older versions (at least up to 2.1.5) of SNESSolve took 3 arguments,\n\/\/ the last one being a pointer to an int to hold the number of iterations required.\n# if PETSC_VERSION_LESS_THAN(2,2,0)\n\n ierr = SNESSolve (_snes, x->vec(), &n_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n\/\/ 2.2.x style\t\n#elif PETSC_VERSION_LESS_THAN(2,3,0)\n\t\n ierr = SNESSolve (_snes, x->vec());\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n\/\/ 2.3.x & newer style\t\n#else\n\t\n ierr = SNESSolve (_snes, PETSC_NULL, x->vec());\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESGetIterationNumber(_snes,&n_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t \n ierr = SNESGetFunctionNorm(_snes,&final_residual_norm);\n\t CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t \n#endif\n\n SNESConvergedReason reason;\n SNESGetConvergedReason(_snes,&reason);\n\n \/\/Based on Petsc 2.3.3 documentation all diverged reasons are negative\n this->converged = reason >= 0;\n\n this->clear();\n\t\t \n \/\/ return the # of its. and the final residual norm.\n return std::make_pair(n_iterations, final_residual_norm);\n}\n\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ Explicit instantiations\ntemplate class PetscNonlinearSolver<Number>;\n \n\n\n#endif \/\/ #ifdef LIBMESH_HAVE_PETSC\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cassert>\n#include <algorithm>\n#include <numeric>\n#include <vector>\n#include <agency\/experimental\/vector.hpp>\n\nvoid test_reallocating_range_assign()\n{\n using namespace agency::experimental;\n\n {\n \/\/ test range assign into empty vector\n\n vector<int> v;\n\n size_t num_elements_to_assign = 5;\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n\n {\n \/\/ test range assign into small vector\n\n vector<int> v(3);\n\n size_t num_elements_to_assign = 5;\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n}\n\nvoid test_nonreallocating_range_assign()\n{\n using namespace agency::experimental;\n\n {\n \/\/ test range assign into empty vector with capacity\n\n vector<int> v;\n \n size_t num_elements_to_assign = 5;\n v.reserve(5);\n\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n\n {\n \/\/ test range assign into small vector with capacity\n\n vector<int> v(3);\n \n size_t num_elements_to_assign = 5;\n v.reserve(5);\n\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n\n {\n \/\/ test range assign into large vector\n size_t num_elements_to_assign = 5;\n \n vector<int> v(2 * num_elements_to_assign);\n\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n}\n\nint main()\n{\n test_reallocating_range_assign();\n\n std::cout << \"OK\" << std::endl;\n\n return 0;\n}\n\n<commit_msg>Call test function<commit_after>#include <iostream>\n#include <cassert>\n#include <algorithm>\n#include <numeric>\n#include <vector>\n#include <agency\/experimental\/vector.hpp>\n\nvoid test_reallocating_range_assign()\n{\n using namespace agency::experimental;\n\n {\n \/\/ test range assign into empty vector\n\n vector<int> v;\n\n size_t num_elements_to_assign = 5;\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n\n {\n \/\/ test range assign into small vector\n\n vector<int> v(3);\n\n size_t num_elements_to_assign = 5;\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n}\n\nvoid test_nonreallocating_range_assign()\n{\n using namespace agency::experimental;\n\n {\n \/\/ test range assign into empty vector with capacity\n\n vector<int> v;\n \n size_t num_elements_to_assign = 5;\n v.reserve(5);\n\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n\n {\n \/\/ test range assign into small vector with capacity\n\n vector<int> v(3);\n \n size_t num_elements_to_assign = 5;\n v.reserve(5);\n\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n\n {\n \/\/ test range assign into large vector\n size_t num_elements_to_assign = 5;\n \n vector<int> v(2 * num_elements_to_assign);\n\n std::vector<int> assign_me(num_elements_to_assign);\n std::iota(assign_me.begin(), assign_me.end(), 0);\n\n v.assign(assign_me.begin(), assign_me.end());\n\n assert(v.size() == num_elements_to_assign);\n assert(std::equal(v.begin(), v.end(), assign_me.begin()));\n }\n}\n\nint main()\n{\n test_reallocating_range_assign();\n test_nonreallocating_range_assign();\n\n std::cout << \"OK\" << std::endl;\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>void PlotPressure()\n{\n FILE* file;\n file=fopen(\"gasPressure.dat\",\"r\");\n Float_t z1[20];\n Float_t g1[20], g2[20], g3[20], g4[20], g5[20];\n Float_t z2[21];\n Float_t h1[21], h2[21], h3[21], h4[21], h5[21];\n\n char c[45];\n Float_t z;\n \n for (Int_t i = 0; i < 20; i++)\n {\n\tfscanf(file, \"%f %f %f %f %f %f\", &z, \n\t &g1[i], &g2[i], &g3[i], &g4[i], &g5[i]);\n\/\/\tprintf(\"%d %f %f %f %f %f %f \\n\", i, z1[i], \n\/\/\t\t g1[i][0], g1[i][1], g1[i][2], g1[i][3], g1[i][4]);\n\tif (i > 0) {\n\t z1[i] = z1[i-1] + z;\n\t} else {\n\t z1[i] = 20.;\n\t}\n }\n\n \n for (Int_t i = 0; i < 21; i++)\n {\n\tfscanf(file, \"%f %f %f %f %f %f\", &z, \n\t &h1[i], &h2[i], &h3[i], &h4[i], &h5[i]);\n\tif (i > 0) {\n\t z2[i] = z2[i-1] + z;\n\t} else {\n\t z2[i] = 20.;\n\t}\n }\n\n\/\/\n\/\/ \n TCanvas *c1 = new TCanvas(\"c1\",\"Gas Pressure Beam 1\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* gr1 = new TGraph(20, z1, g1);\n gr1->SetMaximum(1e17);\n gr1->SetMinimum(1e11); \n gr1->SetLineColor(1);\n gr1->SetTitle(\"Ring 1: Beginning of Run\");\n \n TGraph* gr2 = new TGraph(20, z1, g3);\n gr2->SetLineColor(2);\n\n TGraph* gr3 = new TGraph(20, z1, g5);\n gr3->SetLineColor(4);\n\n gr1->Draw(\"AL\");\n gr2->Draw(\"L\");\n\/\/ gr3->Draw(\"L\");\n text();\n\n\/\/\n\/\/ \n TCanvas *c2 = new TCanvas(\"c2\",\"Gas Pressure Beam 1\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* gr4 = new TGraph(20, z1, g2);\n gr4->SetMaximum(1e17);\n gr4->SetMinimum(1e11); \n gr4->SetLineColor(1);\n gr4->SetTitle(\"Ring 1\");\n \n TGraph* gr5 = new TGraph(20, z1, g4);\n gr5->SetLineColor(2);\n\n TGraph* gr6 = new TGraph(20, z1, g5);\n gr6->SetLineColor(4);\n\n gr4->Draw(\"AL\");\n gr5->Draw(\"L\");\n gr6->Draw(\"L\");\n text();\n\n\/\/\n\/\/ \n TCanvas *c3 = new TCanvas(\"c3\",\"Gas Pressure Beam 2\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* hr1 = new TGraph(21, z2, h1);\n hr1->SetMaximum(1e17);\n hr1->SetMinimum(1e11); \n hr1->SetLineColor(1);\n hr1->SetTitle(\"Ring 2: Beginning of Run\");\n \n TGraph* hr2 = new TGraph(21, z2, h3);\n hr2->SetLineColor(2);\n\n TGraph* hr3 = new TGraph(21, z2, h5);\n hr3->SetLineColor(4);\n\n hr1->Draw(\"AL\");\n hr2->Draw(\"L\");\n\/\/ hr3->Draw(\"L\");\n text();\n\n\/\/\n\/\/ \n TCanvas *c4 = new TCanvas(\"c4\",\"Gas Pressure Beam 2\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* hr4 = new TGraph(21, z2, h2);\n hr4->SetMaximum(1e17);\n hr4->SetMinimum(1e11); \n hr4->SetLineColor(1);\n hr4->SetTitle(\"Ring 2\");\n \n TGraph* hr5 = new TGraph(21, z2, h4);\n hr5->SetLineColor(2);\n\n TGraph* hr6 = new TGraph(21, z2, h5);\n hr6->SetLineColor(4);\n\n hr4->Draw(\"AL\");\n hr5->Draw(\"L\");\n hr6->Draw(\"L\");\n text();\n \n}\n\nvoid text()\n{\n \n TPave *pave = new TPave(194.619,11.0495,293.103,12.6485,4,\"br\");\n pave->SetFillColor(18);\n pave->Draw();\n TLine *line = new TLine(199.702,11.8109,232.106,11.8109);\n line->SetLineColor(2);\n line->Draw();\n line = new TLine(198.431,12.2868,232.106,12.2868);\n line->Draw();\n line = new TLine(199.066,11.3731,232.742,11.3731);\n line->SetLineColor(4);\n line->Draw();\n line = new TLine(215.586,13.3338,215.586,13.3147);\n line->Draw();\n tex = new TLatex(239.096,11.6777,\"2nd year\");\n tex->SetTextSize(0.05);\n tex->SetLineWidth(2);\n tex->Draw();\n tex = new TLatex(236.554,12.1536,\"1st year\");\n tex->SetTextSize(0.0507614);\n tex->SetLineWidth(2);\n tex->Draw();\n tex = new TLatex(239.096,11.2589,\"3rd year\");\n tex->SetTextSize(0.05);\n tex->SetLineWidth(2);\n tex->Draw();\n c1->Modified();\n c1->cd();\n}\n<commit_msg>Example for interaction rate calculation added.<commit_after>void PlotPressure()\n{\n FILE* file;\n file=fopen(\"gasPressure.dat\",\"r\");\n Float_t z1[20];\n Float_t g1[20], g2[20], g3[20], g4[20], g5[20];\n Float_t z2[21];\n Float_t h1[21], h2[21], h3[21], h4[21], h5[21];\n\n char c[45];\n Float_t z;\n \n for (Int_t i = 0; i < 20; i++)\n {\n\tfscanf(file, \"%f %f %f %f %f %f\", &z, \n\t &g1[i], &g2[i], &g3[i], &g4[i], &g5[i]);\n\/\/\tprintf(\"%d %f %f %f %f %f %f \\n\", i, z1[i], \n\/\/\t\t g1[i][0], g1[i][1], g1[i][2], g1[i][3], g1[i][4]);\n\tif (i > 0) {\n\t z1[i] = z1[i-1] + z;\n\t} else {\n\t z1[i] = 20.;\n\t}\n }\n\n \n for (Int_t i = 0; i < 21; i++)\n {\n\tfscanf(file, \"%f %f %f %f %f %f\", &z, \n\t &h1[i], &h2[i], &h3[i], &h4[i], &h5[i]);\n\tif (i > 0) {\n\t z2[i] = z2[i-1] + z;\n\t} else {\n\t z2[i] = 20.;\n\t}\n }\n\n\/\/\n\/\/ \n TCanvas *c1 = new TCanvas(\"c1\",\"Gas Pressure Beam 1\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* gr1 = new TGraph(20, z1, g1);\n gr1->SetMaximum(1e17);\n gr1->SetMinimum(1e11); \n gr1->SetLineColor(1);\n gr1->SetTitle(\"Ring 1: Beginning of Run\");\n \n TGraph* gr2 = new TGraph(20, z1, g3);\n gr2->SetLineColor(2);\n\n TGraph* gr3 = new TGraph(20, z1, g5);\n gr3->SetLineColor(4);\n\n gr1->Draw(\"AL\");\n gr2->Draw(\"L\");\n\/\/ gr3->Draw(\"L\");\n text();\n\n\/\/\n\/\/ \n TCanvas *c2 = new TCanvas(\"c2\",\"Gas Pressure Beam 1\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* gr4 = new TGraph(20, z1, g2);\n gr4->SetMaximum(1e17);\n gr4->SetMinimum(1e11); \n gr4->SetLineColor(1);\n gr4->SetTitle(\"Ring 1\");\n \n TGraph* gr5 = new TGraph(20, z1, g4);\n gr5->SetLineColor(2);\n\n TGraph* gr6 = new TGraph(20, z1, g5);\n gr6->SetLineColor(4);\n\n gr4->Draw(\"AL\");\n gr5->Draw(\"L\");\n gr6->Draw(\"L\");\n text();\n\n\/\/\n\/\/ \n TCanvas *c3 = new TCanvas(\"c3\",\"Gas Pressure Beam 2\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* hr1 = new TGraph(21, z2, h1);\n hr1->SetMaximum(1e17);\n hr1->SetMinimum(1e11); \n hr1->SetLineColor(1);\n hr1->SetTitle(\"Ring 2: Beginning of Run\");\n \n TGraph* hr2 = new TGraph(21, z2, h3);\n hr2->SetLineColor(2);\n\n TGraph* hr3 = new TGraph(21, z2, h5);\n hr3->SetLineColor(4);\n\n hr1->Draw(\"AL\");\n hr2->Draw(\"L\");\n\/\/ hr3->Draw(\"L\");\n text();\n\n\/\/\n\/\/ \n TCanvas *c4 = new TCanvas(\"c4\",\"Gas Pressure Beam 2\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* hr4 = new TGraph(21, z2, h2);\n hr4->SetMaximum(1e17);\n hr4->SetMinimum(1e11); \n hr4->SetLineColor(1);\n hr4->SetTitle(\"Ring 2\");\n \n TGraph* hr5 = new TGraph(21, z2, h4);\n hr5->SetLineColor(2);\n\n TGraph* hr6 = new TGraph(21, z2, h5);\n hr6->SetLineColor(4);\n\n hr4->Draw(\"AL\");\n hr5->Draw(\"L\");\n hr6->Draw(\"L\");\n text();\n\/\/\n\/\/ One example of interaction rate calculation\n\/\/\n\/\/ 3rd year, full intensity\n\/\/\n Float_t r[20];\n const Float_t crossSection = 0.094e-28; \/\/ m^2\n const Float_t pFlux = 1.e11\/25.e-9; \/\/ 1\/s\n \n for (Int_t i= 0; i < 20; i++) \n {\n\tr[i] = g5[i] * crossSection * pFlux; \/\/ 1\/m\/s \n }\n\n TCanvas *c5 = new TCanvas(\"c5\",\"Interaction Rate Beam 1, 3rd year\", 200, 10, 700, 500);\n gPad->SetLogy();\n \n TGraph* rr1 = new TGraph(20, z1, r);\n rr1->SetMaximum(1e6);\n rr1->SetMinimum(1e1); \n rr1->SetLineColor(4);\n rr1->SetTitle(\"Ring 1\");\n rr1->Draw(\"AL\");\n}\n\nvoid text()\n{\n \n TPave *pave = new TPave(194.619,11.0495,293.103,12.6485,4,\"br\");\n pave->SetFillColor(18);\n pave->Draw();\n TLine *line = new TLine(199.702,11.8109,232.106,11.8109);\n line->SetLineColor(2);\n line->Draw();\n line = new TLine(198.431,12.2868,232.106,12.2868);\n line->Draw();\n line = new TLine(199.066,11.3731,232.742,11.3731);\n line->SetLineColor(4);\n line->Draw();\n line = new TLine(215.586,13.3338,215.586,13.3147);\n line->Draw();\n tex = new TLatex(239.096,11.6777,\"2nd year\");\n tex->SetTextSize(0.05);\n tex->SetLineWidth(2);\n tex->Draw();\n tex = new TLatex(236.554,12.1536,\"1st year\");\n tex->SetTextSize(0.0507614);\n tex->SetLineWidth(2);\n tex->Draw();\n tex = new TLatex(239.096,11.2589,\"3rd year\");\n tex->SetTextSize(0.05);\n tex->SetLineWidth(2);\n tex->Draw();\n c1->Modified();\n c1->cd();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2014 CyberTech Labs Ltd.\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 \"wiFiModeWidget.h\"\n\n#include <QtGui\/QKeyEvent>\n\n#include <trikKernel\/paths.h>\n#include <QsLog.h>\n\n#include \"wiFiClientWidget.h\"\n#include \"wiFiAPWidget.h\"\n#include \"wiFiInitWidget.h\"\n\nusing namespace trikGui;\n\nWiFiModeWidget::WiFiModeWidget(trikWiFi::TrikWiFi &wiFi, QWidget *parent)\n\t: TrikGuiDialog(parent)\n\t, mWiFi(wiFi)\n\t, mRcReader(trikKernel::Paths::trikRcName())\n\t, mTitle(tr(\"Choose mode:\"))\n{\n\tmModes.addItem(tr(\"Wi-Fi client\"));\n\tmModes.addItem(tr(\"Wi-Fi access point\"));\n\n\tmLayout.addWidget(&mTitle);\n\tmLayout.addWidget(&mModes);\n\tsetLayout(&mLayout);\n\n\tmModes.selectionModel()->select(\n\t\t\tmModes.model()->index(0, 0)\n\t\t\t, QItemSelectionModel::ClearAndSelect\n\t\t\t);\n}\n\nQString WiFiModeWidget::menuEntry()\n{\n\treturn tr(\"Network Config\");\n}\n\nvoid WiFiModeWidget::renewFocus()\n{\n\tmModes.setFocus();\n}\n\nvoid WiFiModeWidget::keyPressEvent(QKeyEvent *event)\n{\n\tswitch (event->key()) {\n\t\tcase Qt::Key_Return: {\n\t\t\tif (mModes.currentItem()->text() == tr(\"Wi-Fi client\")) {\n\t\t\t\tsetMode(client);\n\t\t\t} else {\n\t\t\t\tsetMode(accessPoint);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\tTrikGuiDialog::keyPressEvent(event);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid WiFiModeWidget::setMode(Mode mode)\n{\n\tmRcReader.read();\n\n\tconst QString currentModeText = mRcReader.value(\"trik_wifi_mode\");\n\n\tMode currentMode = unknown;\n\tif (currentModeText == \"client\") {\n\t\tcurrentMode = client;\n\t} else if (currentModeText == \"ap\") {\n\t\tcurrentMode = accessPoint;\n\t}\n\n\tif (currentMode != mode) {\n\t\tWiFiInitWidget wiFiInitWidget;\n\t\temit newWidget(wiFiInitWidget);\n\t\tif (wiFiInitWidget.init(mode) == WiFiInitWidget::fail) {\n\t\t\tQLOG_ERROR() << \"Faile on init WiFi widget in mode\" << currentModeText;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tint returnValue = 0;\n\n\tswitch (mode) {\n\t\tcase client: {\n\t\t\tif (currentMode != mode) {\n\t\t\t\tmWiFi.reinit();\n\t\t\t}\n\t\t\tWiFiClientWidget wiFiClientWidget(mWiFi);\n\t\t\temit newWidget(wiFiClientWidget);\n\t\t\treturnValue = wiFiClientWidget.exec();\n\t\t\tbreak;\n\t\t}\n\t\tcase accessPoint: {\n\t\t\tmWiFi.dispose();\n\t\t\tWiFiAPWidget wiFiAPWidget;\n\t\t\temit newWidget(wiFiAPWidget);\n\t\t\treturnValue = wiFiAPWidget.exec();\n\t\t\tbreak;\n\t\t}\n\t\tcase unknown: {\n\t\t\tQLOG_ERROR() << \"Error: unknown WiFi mode in WiFiModeWidget::setMode()\";\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (returnValue == 1) {\n\t\tgoHome();\n\t}\n}\n<commit_msg>Typo fix<commit_after>\/* Copyright 2014 CyberTech Labs Ltd.\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 \"wiFiModeWidget.h\"\n\n#include <QtGui\/QKeyEvent>\n\n#include <trikKernel\/paths.h>\n#include <QsLog.h>\n\n#include \"wiFiClientWidget.h\"\n#include \"wiFiAPWidget.h\"\n#include \"wiFiInitWidget.h\"\n\nusing namespace trikGui;\n\nWiFiModeWidget::WiFiModeWidget(trikWiFi::TrikWiFi &wiFi, QWidget *parent)\n\t: TrikGuiDialog(parent)\n\t, mWiFi(wiFi)\n\t, mRcReader(trikKernel::Paths::trikRcName())\n\t, mTitle(tr(\"Choose mode:\"))\n{\n\tmModes.addItem(tr(\"Wi-Fi client\"));\n\tmModes.addItem(tr(\"Wi-Fi access point\"));\n\n\tmLayout.addWidget(&mTitle);\n\tmLayout.addWidget(&mModes);\n\tsetLayout(&mLayout);\n\n\tmModes.selectionModel()->select(\n\t\t\tmModes.model()->index(0, 0)\n\t\t\t, QItemSelectionModel::ClearAndSelect\n\t\t\t);\n}\n\nQString WiFiModeWidget::menuEntry()\n{\n\treturn tr(\"Network Config\");\n}\n\nvoid WiFiModeWidget::renewFocus()\n{\n\tmModes.setFocus();\n}\n\nvoid WiFiModeWidget::keyPressEvent(QKeyEvent *event)\n{\n\tswitch (event->key()) {\n\t\tcase Qt::Key_Return: {\n\t\t\tif (mModes.currentItem()->text() == tr(\"Wi-Fi client\")) {\n\t\t\t\tsetMode(client);\n\t\t\t} else {\n\t\t\t\tsetMode(accessPoint);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\tTrikGuiDialog::keyPressEvent(event);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid WiFiModeWidget::setMode(Mode mode)\n{\n\tmRcReader.read();\n\n\tconst QString currentModeText = mRcReader.value(\"trik_wifi_mode\");\n\n\tMode currentMode = unknown;\n\tif (currentModeText == \"client\") {\n\t\tcurrentMode = client;\n\t} else if (currentModeText == \"ap\") {\n\t\tcurrentMode = accessPoint;\n\t}\n\n\tif (currentMode != mode) {\n\t\tWiFiInitWidget wiFiInitWidget;\n\t\temit newWidget(wiFiInitWidget);\n\t\tif (wiFiInitWidget.init(mode) == WiFiInitWidget::fail) {\n\t\t\tQLOG_ERROR() << \"Failed to init WiFi widget in mode\" << currentModeText;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tint returnValue = 0;\n\n\tswitch (mode) {\n\t\tcase client: {\n\t\t\tif (currentMode != mode) {\n\t\t\t\tmWiFi.reinit();\n\t\t\t}\n\t\t\tWiFiClientWidget wiFiClientWidget(mWiFi);\n\t\t\temit newWidget(wiFiClientWidget);\n\t\t\treturnValue = wiFiClientWidget.exec();\n\t\t\tbreak;\n\t\t}\n\t\tcase accessPoint: {\n\t\t\tmWiFi.dispose();\n\t\t\tWiFiAPWidget wiFiAPWidget;\n\t\t\temit newWidget(wiFiAPWidget);\n\t\t\treturnValue = wiFiAPWidget.exec();\n\t\t\tbreak;\n\t\t}\n\t\tcase unknown: {\n\t\t\tQLOG_ERROR() << \"Error: unknown WiFi mode in WiFiModeWidget::setMode()\";\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (returnValue == 1) {\n\t\tgoHome();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef HAVE_CXX11\n#include <functional>\n#define HAVE_CPP_FUNC_PTR\nnamespace funcptr = std;\n#else\n#ifdef HAVE_BOOST\n#include <boost\/function.hpp>\nnamespace funcptr = boost;\n#define HAVE_CPP_FUNC_PTR\n#endif\n#endif\n\n#include <fstream>\n#include <cctype>\n\n#ifndef WIN32\n#include <cstdio>\n#include <unistd.h>\n#endif\n\n#include <algorithm>\n\n#ifndef YAHTTP_MAX_REQUEST_SIZE\n#define YAHTTP_MAX_REQUEST_SIZE 2097152\n#endif\n\n#ifndef YAHTTP_MAX_RESPONSE_SIZE\n#define YAHTTP_MAX_RESPONSE_SIZE 2097152\n#endif\n\n#define YAHTTP_TYPE_REQUEST 1\n#define YAHTTP_TYPE_RESPONSE 2\n\nnamespace YaHTTP {\n typedef std::map<std::string,Cookie,ASCIICINullSafeComparator> strcookie_map_t; \/\/<! String to Cookie map\n\n typedef enum {\n urlencoded,\n multipart\n } postformat_t; \/\/<! Enumeration of possible post encodings, url encoding or multipart\n\n \/*! Base class for request and response *\/\n class HTTPBase {\n public:\n \/*! Default renderer for request\/response, simply copies body to response *\/\n class SendBodyRender {\n public:\n SendBodyRender() {};\n\n size_t operator()(const HTTPBase *doc, std::ostream& os, bool chunked) const {\n if (chunked) {\n std::string::size_type i,cl;\n for(i=0;i<doc->body.length();i+=1024) {\n cl = std::min(static_cast<std::string::size_type>(1024), doc->body.length()-i); \/\/ for less than 1k blocks\n os << std::hex << cl << std::dec << \"\\r\\n\";\n os << doc->body.substr(i, cl) << \"\\r\\n\";\n }\n os << 0 << \"\\r\\n\\r\\n\"; \/\/ last chunk\n } else {\n os << doc->body;\n }\n return doc->body.length();\n }; \/\/<! writes body to ostream and returns length \n };\n \/* Simple sendfile renderer which streams file to ostream *\/\n class SendFileRender {\n public:\n SendFileRender(const std::string& path_) {\n this->path = path_;\n };\n \n size_t operator()(const HTTPBase *doc __attribute__((unused)), std::ostream& os, bool chunked) const {\n char buf[4096];\n size_t n,k;\n#ifdef HAVE_CXX11\n std::ifstream ifs(path, std::ifstream::binary);\n#else\n std::ifstream ifs(path.c_str(), std::ifstream::binary);\n#endif\n n = 0;\n\n while(ifs.good()) {\n ifs.read(buf, sizeof buf);\n n += (k = ifs.gcount());\n if (k > 0) {\n if (chunked) os << std::hex << k << std::dec << \"\\r\\n\";\n os.write(buf, k);\n if (chunked) os << \"\\r\\n\"; \n }\n }\n if (chunked) os << 0 << \"\\r\\n\\r\\n\";\n return n;\n }; \/\/<! writes file to ostream and returns length\n\n std::string path; \/\/<! File to send\n };\n\n HTTPBase() {\n initialize();\n };\n\n virtual void initialize() {\n kind = 0;\n status = 0;\n#ifdef HAVE_CPP_FUNC_PTR\n renderer = SendBodyRender();\n#endif\n max_request_size = YAHTTP_MAX_REQUEST_SIZE;\n max_response_size = YAHTTP_MAX_RESPONSE_SIZE;\n url = \"\";\n method = \"\";\n statusText = \"\";\n jar.clear();\n headers.clear();\n parameters.clear();\n getvars.clear();\n postvars.clear();\n body = \"\";\n routeName = \"\";\n version = 11; \/\/ default to version 1.1\n is_multipart = false;\n }\nprotected:\n HTTPBase(const HTTPBase& rhs) {\n this->url = rhs.url; this->kind = rhs.kind;\n this->status = rhs.status; this->statusText = rhs.statusText;\n this->method = rhs.method; this->headers = rhs.headers;\n this->jar = rhs.jar; this->postvars = rhs.postvars;\n this->parameters = rhs.parameters; this->getvars = rhs.getvars;\n this->body = rhs.body; this->max_request_size = rhs.max_request_size;\n this->max_response_size = rhs.max_response_size; this->version = rhs.version;\n#ifdef HAVE_CPP_FUNC_PTR\n this->renderer = rhs.renderer;\n#endif\n this->is_multipart = rhs.is_multipart;\n };\n virtual HTTPBase& operator=(const HTTPBase& rhs) {\n this->url = rhs.url; this->kind = rhs.kind;\n this->status = rhs.status; this->statusText = rhs.statusText;\n this->method = rhs.method; this->headers = rhs.headers;\n this->jar = rhs.jar; this->postvars = rhs.postvars;\n this->parameters = rhs.parameters; this->getvars = rhs.getvars;\n this->body = rhs.body; this->max_request_size = rhs.max_request_size;\n this->max_response_size = rhs.max_response_size; this->version = rhs.version;\n#ifdef HAVE_CPP_FUNC_PTR\n this->renderer = rhs.renderer;\n#endif\n this->is_multipart = rhs.is_multipart;\n return *this;\n };\npublic:\n URL url; \/\/<! URL of this request\/response\n int kind; \/\/<! Type of object (1 = request, 2 = response)\n int status; \/\/<! status code \n int version; \/\/<! http version 9 = 0.9, 10 = 1.0, 11 = 1.1\n std::string statusText; \/\/<! textual representation of status code\n std::string method; \/\/<! http verb\n strstr_map_t headers; \/\/<! map of header(s)\n CookieJar jar; \/\/<! cookies \n strstr_map_t postvars; \/\/<! map of POST variables (from POST body)\n strstr_map_t getvars; \/\/<! map of GET variables (from URL)\n\/\/ these two are for Router\n strstr_map_t parameters; \/\/<! map of route parameters (only if you use YaHTTP::Router)\n std::string routeName; \/\/<! name of the current route (only if you use YaHTTP::Router)\n\n std::string body; \/\/<! the actual content\n\n ssize_t max_request_size; \/\/<! maximum size of request\n ssize_t max_response_size; \/\/<! maximum size of response\n bool is_multipart; \/\/<! if the request is multipart, prevents Content-Length header\n#ifdef HAVE_CPP_FUNC_PTR\n funcptr::function<size_t(const HTTPBase*,std::ostream&,bool)> renderer; \/\/<! rendering function\n#endif\n void write(std::ostream& os) const; \/\/<! writes request to the given output stream\n\n strstr_map_t& GET() { return getvars; }; \/\/<! acccessor for getvars\n strstr_map_t& POST() { return postvars; }; \/\/<! accessor for postvars\n strcookie_map_t& COOKIES() { return jar.cookies; }; \/\/<! accessor for cookies\n\n std::string versionStr(int version_) const {\n switch(version_) {\n case 9: return \"0.9\";\n case 10: return \"1.0\";\n case 11: return \"1.1\";\n default: throw YaHTTP::Error(\"Unsupported version\");\n }\n };\n\n std::string str() const {\n std::ostringstream oss;\n write(oss);\n return oss.str();\n }; \/\/<! return string representation of this object\n };\n\n \/*! Response class, represents a HTTP Response document *\/\n class Response: public HTTPBase { \n public:\n Response() { initialize(); };\n Response(const HTTPBase& rhs): HTTPBase(rhs) {\n this->kind = YAHTTP_TYPE_RESPONSE;\n };\n Response& operator=(const HTTPBase& rhs) {\n HTTPBase::operator=(rhs);\n this->kind = YAHTTP_TYPE_RESPONSE;\n return *this;\n };\n void initialize() {\n HTTPBase::initialize();\n this->kind = YAHTTP_TYPE_RESPONSE;\n }\n void initialize(const HTTPBase& rhs) {\n HTTPBase::initialize();\n this->kind = YAHTTP_TYPE_RESPONSE;\n \/\/ copy SOME attributes\n this->url = rhs.url;\n this->method = rhs.method;\n this->jar = rhs.jar;\n this->version = rhs.version;\n }\n friend std::ostream& operator<<(std::ostream& os, const Response &resp);\n friend std::istream& operator>>(std::istream& is, Response &resp);\n };\n\n \/* Request class, represents a HTTP Request document *\/\n class Request: public HTTPBase {\n public:\n Request() { initialize(); };\n Request(const HTTPBase& rhs): HTTPBase(rhs) {\n this->kind = YAHTTP_TYPE_REQUEST;\n };\n Request& operator=(const HTTPBase& rhs) {\n HTTPBase::operator=(rhs);\n this->kind = YAHTTP_TYPE_REQUEST;\n return *this;\n };\n void initialize() {\n HTTPBase::initialize();\n this->kind = YAHTTP_TYPE_REQUEST;\n }\n void initialize(const HTTPBase& rhs) {\n HTTPBase::initialize();\n this->kind = YAHTTP_TYPE_REQUEST;\n \/\/ copy SOME attributes\n this->url = rhs.url;\n this->method = rhs.method;\n this->jar = rhs.jar;\n this->version = rhs.version;\n }\n void setup(const std::string& method_, const std::string& url_) {\n this->url.parse(url_);\n this->headers[\"host\"] = this->url.host;\n this->method = method_;\n std::transform(this->method.begin(), this->method.end(), this->method.begin(), ::toupper);\n this->headers[\"user-agent\"] = \"YaHTTP v1.0\";\n }; \/\/<! Set some initial things for a request\n\n void preparePost(postformat_t format = urlencoded) {\n std::ostringstream postbuf;\n if (format == urlencoded) {\n for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {\n postbuf << Utility::encodeURL(i->first, false) << \"=\" << Utility::encodeURL(i->second, false) << \"&\";\n }\n \/\/ remove last bit\n if (postbuf.str().length()>0) \n body = postbuf.str().substr(0, postbuf.str().length()-1);\n else\n body = \"\";\n headers[\"content-type\"] = \"application\/x-www-form-urlencoded; charset=utf-8\";\n } else if (format == multipart) {\n headers[\"content-type\"] = \"multipart\/form-data; boundary=YaHTTP-12ca543\";\n this->is_multipart = true;\n for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {\n postbuf << \"--YaHTTP-12ca543\\r\\nContent-Disposition: form-data; name=\\\"\" << Utility::encodeURL(i->first, false) << \"\\\"; charset=UTF-8\\r\\nContent-Length: \" << i->second.size() << \"\\r\\n\\r\\n\"\n << Utility::encodeURL(i->second, false) << \"\\r\\n\";\n }\n postbuf << \"--\";\n body = postbuf.str();\n }\n\n postbuf.str(\"\");\n postbuf << body.length();\n \/\/ set method and change headers\n method = \"POST\";\n if (!this->is_multipart)\n headers[\"content-length\"] = postbuf.str();\n }; \/\/<! convert all postvars into string and stuff it into body\n\n friend std::ostream& operator<<(std::ostream& os, const Request &resp);\n friend std::istream& operator>>(std::istream& is, Request &resp);\n };\n\n \/*! Asynchronous HTTP document loader *\/\n template <class T>\n class AsyncLoader {\n public:\n T* target; \/\/<! target to populate\n int state; \/\/<! reader state\n size_t pos; \/\/<! reader position\n \n std::string buffer; \/\/<! read buffer \n bool chunked; \/\/<! whether we are parsing chunked data\n int chunk_size; \/\/<! expected size of next chunk\n std::ostringstream bodybuf; \/\/<! buffer for body\n size_t maxbody; \/\/<! maximum size of body\n size_t minbody; \/\/<! minimum size of body\n bool hasBody; \/\/<! are we expecting body\n\n void keyValuePair(const std::string &keyvalue, std::string &key, std::string &value); \/\/<! key value pair parser helper\n\n void initialize(T* target_) {\n chunked = false; chunk_size = 0;\n bodybuf.str(\"\"); minbody = 0; maxbody = 0;\n pos = 0; state = 0; this->target = target_;\n hasBody = false;\n buffer = \"\";\n this->target->initialize();\n }; \/\/<! Initialize the parser for target and clear state\n bool feed(const std::string& somedata); \/\/<! Feed data to the parser\n bool ready() {\n return (chunked == true && state == 3) || \/\/ if it's chunked we get end of data indication\n (chunked == false && state > 1 && \n (!hasBody || \n (bodybuf.str().size() <= maxbody && \n bodybuf.str().size() >= minbody)\n )\n ); \n }; \/\/<! whether we have received enough data\n void finalize() {\n bodybuf.flush();\n if (ready()) {\n strstr_map_t::iterator cpos = target->headers.find(\"content-type\");\n if (cpos != target->headers.end() && Utility::iequals(cpos->second, \"application\/x-www-form-urlencoded\", 32)) {\n target->postvars = Utility::parseUrlParameters(bodybuf.str());\n }\n target->body = bodybuf.str();\n }\n bodybuf.str(\"\");\n this->target = NULL;\n }; \/\/<! finalize and release target\n };\n\n \/*! Asynchronous HTTP response loader *\/\n class AsyncResponseLoader: public AsyncLoader<Response> {\n };\n\n \/*! Asynchronous HTTP request loader *\/\n class AsyncRequestLoader: public AsyncLoader<Request> {\n };\n\n};\n<commit_msg>reqresp.hpp: Use override keyword<commit_after>#ifdef HAVE_CXX11\n#include <functional>\n#define HAVE_CPP_FUNC_PTR\nnamespace funcptr = std;\n#else\n#ifdef HAVE_BOOST\n#include <boost\/function.hpp>\nnamespace funcptr = boost;\n#define HAVE_CPP_FUNC_PTR\n#endif\n#endif\n\n#include <fstream>\n#include <cctype>\n\n#ifndef WIN32\n#include <cstdio>\n#include <unistd.h>\n#endif\n\n#include <algorithm>\n\n#ifndef YAHTTP_MAX_REQUEST_SIZE\n#define YAHTTP_MAX_REQUEST_SIZE 2097152\n#endif\n\n#ifndef YAHTTP_MAX_RESPONSE_SIZE\n#define YAHTTP_MAX_RESPONSE_SIZE 2097152\n#endif\n\n#define YAHTTP_TYPE_REQUEST 1\n#define YAHTTP_TYPE_RESPONSE 2\n\nnamespace YaHTTP {\n typedef std::map<std::string,Cookie,ASCIICINullSafeComparator> strcookie_map_t; \/\/<! String to Cookie map\n\n typedef enum {\n urlencoded,\n multipart\n } postformat_t; \/\/<! Enumeration of possible post encodings, url encoding or multipart\n\n \/*! Base class for request and response *\/\n class HTTPBase {\n public:\n \/*! Default renderer for request\/response, simply copies body to response *\/\n class SendBodyRender {\n public:\n SendBodyRender() {};\n\n size_t operator()(const HTTPBase *doc, std::ostream& os, bool chunked) const {\n if (chunked) {\n std::string::size_type i,cl;\n for(i=0;i<doc->body.length();i+=1024) {\n cl = std::min(static_cast<std::string::size_type>(1024), doc->body.length()-i); \/\/ for less than 1k blocks\n os << std::hex << cl << std::dec << \"\\r\\n\";\n os << doc->body.substr(i, cl) << \"\\r\\n\";\n }\n os << 0 << \"\\r\\n\\r\\n\"; \/\/ last chunk\n } else {\n os << doc->body;\n }\n return doc->body.length();\n }; \/\/<! writes body to ostream and returns length \n };\n \/* Simple sendfile renderer which streams file to ostream *\/\n class SendFileRender {\n public:\n SendFileRender(const std::string& path_) {\n this->path = path_;\n };\n \n size_t operator()(const HTTPBase *doc __attribute__((unused)), std::ostream& os, bool chunked) const {\n char buf[4096];\n size_t n,k;\n#ifdef HAVE_CXX11\n std::ifstream ifs(path, std::ifstream::binary);\n#else\n std::ifstream ifs(path.c_str(), std::ifstream::binary);\n#endif\n n = 0;\n\n while(ifs.good()) {\n ifs.read(buf, sizeof buf);\n n += (k = ifs.gcount());\n if (k > 0) {\n if (chunked) os << std::hex << k << std::dec << \"\\r\\n\";\n os.write(buf, k);\n if (chunked) os << \"\\r\\n\"; \n }\n }\n if (chunked) os << 0 << \"\\r\\n\\r\\n\";\n return n;\n }; \/\/<! writes file to ostream and returns length\n\n std::string path; \/\/<! File to send\n };\n\n HTTPBase() {\n initialize();\n };\n\n virtual void initialize() {\n kind = 0;\n status = 0;\n#ifdef HAVE_CPP_FUNC_PTR\n renderer = SendBodyRender();\n#endif\n max_request_size = YAHTTP_MAX_REQUEST_SIZE;\n max_response_size = YAHTTP_MAX_RESPONSE_SIZE;\n url = \"\";\n method = \"\";\n statusText = \"\";\n jar.clear();\n headers.clear();\n parameters.clear();\n getvars.clear();\n postvars.clear();\n body = \"\";\n routeName = \"\";\n version = 11; \/\/ default to version 1.1\n is_multipart = false;\n }\nprotected:\n HTTPBase(const HTTPBase& rhs) {\n this->url = rhs.url; this->kind = rhs.kind;\n this->status = rhs.status; this->statusText = rhs.statusText;\n this->method = rhs.method; this->headers = rhs.headers;\n this->jar = rhs.jar; this->postvars = rhs.postvars;\n this->parameters = rhs.parameters; this->getvars = rhs.getvars;\n this->body = rhs.body; this->max_request_size = rhs.max_request_size;\n this->max_response_size = rhs.max_response_size; this->version = rhs.version;\n#ifdef HAVE_CPP_FUNC_PTR\n this->renderer = rhs.renderer;\n#endif\n this->is_multipart = rhs.is_multipart;\n };\n virtual HTTPBase& operator=(const HTTPBase& rhs) {\n this->url = rhs.url; this->kind = rhs.kind;\n this->status = rhs.status; this->statusText = rhs.statusText;\n this->method = rhs.method; this->headers = rhs.headers;\n this->jar = rhs.jar; this->postvars = rhs.postvars;\n this->parameters = rhs.parameters; this->getvars = rhs.getvars;\n this->body = rhs.body; this->max_request_size = rhs.max_request_size;\n this->max_response_size = rhs.max_response_size; this->version = rhs.version;\n#ifdef HAVE_CPP_FUNC_PTR\n this->renderer = rhs.renderer;\n#endif\n this->is_multipart = rhs.is_multipart;\n return *this;\n };\npublic:\n URL url; \/\/<! URL of this request\/response\n int kind; \/\/<! Type of object (1 = request, 2 = response)\n int status; \/\/<! status code \n int version; \/\/<! http version 9 = 0.9, 10 = 1.0, 11 = 1.1\n std::string statusText; \/\/<! textual representation of status code\n std::string method; \/\/<! http verb\n strstr_map_t headers; \/\/<! map of header(s)\n CookieJar jar; \/\/<! cookies \n strstr_map_t postvars; \/\/<! map of POST variables (from POST body)\n strstr_map_t getvars; \/\/<! map of GET variables (from URL)\n\/\/ these two are for Router\n strstr_map_t parameters; \/\/<! map of route parameters (only if you use YaHTTP::Router)\n std::string routeName; \/\/<! name of the current route (only if you use YaHTTP::Router)\n\n std::string body; \/\/<! the actual content\n\n ssize_t max_request_size; \/\/<! maximum size of request\n ssize_t max_response_size; \/\/<! maximum size of response\n bool is_multipart; \/\/<! if the request is multipart, prevents Content-Length header\n#ifdef HAVE_CPP_FUNC_PTR\n funcptr::function<size_t(const HTTPBase*,std::ostream&,bool)> renderer; \/\/<! rendering function\n#endif\n void write(std::ostream& os) const; \/\/<! writes request to the given output stream\n\n strstr_map_t& GET() { return getvars; }; \/\/<! acccessor for getvars\n strstr_map_t& POST() { return postvars; }; \/\/<! accessor for postvars\n strcookie_map_t& COOKIES() { return jar.cookies; }; \/\/<! accessor for cookies\n\n std::string versionStr(int version_) const {\n switch(version_) {\n case 9: return \"0.9\";\n case 10: return \"1.0\";\n case 11: return \"1.1\";\n default: throw YaHTTP::Error(\"Unsupported version\");\n }\n };\n\n std::string str() const {\n std::ostringstream oss;\n write(oss);\n return oss.str();\n }; \/\/<! return string representation of this object\n };\n\n \/*! Response class, represents a HTTP Response document *\/\n class Response: public HTTPBase { \n public:\n Response() { initialize(); };\n Response(const HTTPBase& rhs): HTTPBase(rhs) {\n this->kind = YAHTTP_TYPE_RESPONSE;\n };\n Response& operator=(const HTTPBase& rhs) override {\n HTTPBase::operator=(rhs);\n this->kind = YAHTTP_TYPE_RESPONSE;\n return *this;\n };\n void initialize() override {\n HTTPBase::initialize();\n this->kind = YAHTTP_TYPE_RESPONSE;\n }\n void initialize(const HTTPBase& rhs) {\n HTTPBase::initialize();\n this->kind = YAHTTP_TYPE_RESPONSE;\n \/\/ copy SOME attributes\n this->url = rhs.url;\n this->method = rhs.method;\n this->jar = rhs.jar;\n this->version = rhs.version;\n }\n friend std::ostream& operator<<(std::ostream& os, const Response &resp);\n friend std::istream& operator>>(std::istream& is, Response &resp);\n };\n\n \/* Request class, represents a HTTP Request document *\/\n class Request: public HTTPBase {\n public:\n Request() { initialize(); };\n Request(const HTTPBase& rhs): HTTPBase(rhs) {\n this->kind = YAHTTP_TYPE_REQUEST;\n };\n Request& operator=(const HTTPBase& rhs) override {\n HTTPBase::operator=(rhs);\n this->kind = YAHTTP_TYPE_REQUEST;\n return *this;\n };\n void initialize() override {\n HTTPBase::initialize();\n this->kind = YAHTTP_TYPE_REQUEST;\n }\n void initialize(const HTTPBase& rhs) {\n HTTPBase::initialize();\n this->kind = YAHTTP_TYPE_REQUEST;\n \/\/ copy SOME attributes\n this->url = rhs.url;\n this->method = rhs.method;\n this->jar = rhs.jar;\n this->version = rhs.version;\n }\n void setup(const std::string& method_, const std::string& url_) {\n this->url.parse(url_);\n this->headers[\"host\"] = this->url.host;\n this->method = method_;\n std::transform(this->method.begin(), this->method.end(), this->method.begin(), ::toupper);\n this->headers[\"user-agent\"] = \"YaHTTP v1.0\";\n }; \/\/<! Set some initial things for a request\n\n void preparePost(postformat_t format = urlencoded) {\n std::ostringstream postbuf;\n if (format == urlencoded) {\n for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {\n postbuf << Utility::encodeURL(i->first, false) << \"=\" << Utility::encodeURL(i->second, false) << \"&\";\n }\n \/\/ remove last bit\n if (postbuf.str().length()>0) \n body = postbuf.str().substr(0, postbuf.str().length()-1);\n else\n body = \"\";\n headers[\"content-type\"] = \"application\/x-www-form-urlencoded; charset=utf-8\";\n } else if (format == multipart) {\n headers[\"content-type\"] = \"multipart\/form-data; boundary=YaHTTP-12ca543\";\n this->is_multipart = true;\n for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {\n postbuf << \"--YaHTTP-12ca543\\r\\nContent-Disposition: form-data; name=\\\"\" << Utility::encodeURL(i->first, false) << \"\\\"; charset=UTF-8\\r\\nContent-Length: \" << i->second.size() << \"\\r\\n\\r\\n\"\n << Utility::encodeURL(i->second, false) << \"\\r\\n\";\n }\n postbuf << \"--\";\n body = postbuf.str();\n }\n\n postbuf.str(\"\");\n postbuf << body.length();\n \/\/ set method and change headers\n method = \"POST\";\n if (!this->is_multipart)\n headers[\"content-length\"] = postbuf.str();\n }; \/\/<! convert all postvars into string and stuff it into body\n\n friend std::ostream& operator<<(std::ostream& os, const Request &resp);\n friend std::istream& operator>>(std::istream& is, Request &resp);\n };\n\n \/*! Asynchronous HTTP document loader *\/\n template <class T>\n class AsyncLoader {\n public:\n T* target; \/\/<! target to populate\n int state; \/\/<! reader state\n size_t pos; \/\/<! reader position\n \n std::string buffer; \/\/<! read buffer \n bool chunked; \/\/<! whether we are parsing chunked data\n int chunk_size; \/\/<! expected size of next chunk\n std::ostringstream bodybuf; \/\/<! buffer for body\n size_t maxbody; \/\/<! maximum size of body\n size_t minbody; \/\/<! minimum size of body\n bool hasBody; \/\/<! are we expecting body\n\n void keyValuePair(const std::string &keyvalue, std::string &key, std::string &value); \/\/<! key value pair parser helper\n\n void initialize(T* target_) {\n chunked = false; chunk_size = 0;\n bodybuf.str(\"\"); minbody = 0; maxbody = 0;\n pos = 0; state = 0; this->target = target_;\n hasBody = false;\n buffer = \"\";\n this->target->initialize();\n }; \/\/<! Initialize the parser for target and clear state\n bool feed(const std::string& somedata); \/\/<! Feed data to the parser\n bool ready() {\n return (chunked == true && state == 3) || \/\/ if it's chunked we get end of data indication\n (chunked == false && state > 1 && \n (!hasBody || \n (bodybuf.str().size() <= maxbody && \n bodybuf.str().size() >= minbody)\n )\n ); \n }; \/\/<! whether we have received enough data\n void finalize() {\n bodybuf.flush();\n if (ready()) {\n strstr_map_t::iterator cpos = target->headers.find(\"content-type\");\n if (cpos != target->headers.end() && Utility::iequals(cpos->second, \"application\/x-www-form-urlencoded\", 32)) {\n target->postvars = Utility::parseUrlParameters(bodybuf.str());\n }\n target->body = bodybuf.str();\n }\n bodybuf.str(\"\");\n this->target = NULL;\n }; \/\/<! finalize and release target\n };\n\n \/*! Asynchronous HTTP response loader *\/\n class AsyncResponseLoader: public AsyncLoader<Response> {\n };\n\n \/*! Asynchronous HTTP request loader *\/\n class AsyncRequestLoader: public AsyncLoader<Request> {\n };\n\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/\r\n\/\/\/ SoundTouch - main class for tempo\/pitch\/rate adjusting routines. \r\n\/\/\/\r\n\/\/\/ Notes:\r\n\/\/\/ - Initialize the SoundTouch object instance by setting up the sound stream \r\n\/\/\/ parameters with functions 'setSampleRate' and 'setChannels', then set \r\n\/\/\/ desired tempo\/pitch\/rate settings with the corresponding functions.\r\n\/\/\/\r\n\/\/\/ - The SoundTouch class behaves like a first-in-first-out pipeline: The \r\n\/\/\/ samples that are to be processed are fed into one of the pipe by calling\r\n\/\/\/ function 'putSamples', while the ready processed samples can be read \r\n\/\/\/ from the other end of the pipeline with function 'receiveSamples'.\r\n\/\/\/ \r\n\/\/\/ - The SoundTouch processing classes require certain sized 'batches' of \r\n\/\/\/ samples in order to process the sound. For this reason the classes buffer \r\n\/\/\/ incoming samples until there are enough of samples available for \r\n\/\/\/ processing, then they carry out the processing step and consequently\r\n\/\/\/ make the processed samples available for outputting.\r\n\/\/\/ \r\n\/\/\/ - For the above reason, the processing routines introduce a certain \r\n\/\/\/ 'latency' between the input and output, so that the samples input to\r\n\/\/\/ SoundTouch may not be immediately available in the output, and neither \r\n\/\/\/ the amount of outputtable samples may not immediately be in direct \r\n\/\/\/ relationship with the amount of previously input samples.\r\n\/\/\/\r\n\/\/\/ - The tempo\/pitch\/rate control parameters can be altered during processing.\r\n\/\/\/ Please notice though that they aren't currently protected by semaphores,\r\n\/\/\/ so in multi-thread application external semaphore protection may be\r\n\/\/\/ required.\r\n\/\/\/\r\n\/\/\/ - This class utilizes classes 'TDStretch' for tempo change (without modifying\r\n\/\/\/ pitch) and 'RateTransposer' for changing the playback rate (that is, both \r\n\/\/\/ tempo and pitch in the same ratio) of the sound. The third available control \r\n\/\/\/ 'pitch' (change pitch but maintain tempo) is produced by a combination of\r\n\/\/\/ combining the two other controls.\r\n\/\/\/\r\n\/\/\/ Author : Copyright (c) Olli Parviainen\r\n\/\/\/ Author e-mail : oparviai 'at' iki.fi\r\n\/\/\/ SoundTouch WWW: http:\/\/www.surina.net\/soundtouch\r\n\/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ Last changed : $Date$\r\n\/\/ File revision : $Revision: 4 $\r\n\/\/\r\n\/\/ $Id$\r\n\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ License :\r\n\/\/\r\n\/\/ SoundTouch audio processing library\r\n\/\/ Copyright (c) Olli Parviainen\r\n\/\/\r\n\/\/ This library is free software; you can redistribute it and\/or\r\n\/\/ modify it under the terms of the GNU Lesser General Public\r\n\/\/ License as published by the Free Software Foundation; either\r\n\/\/ version 2.1 of the License, or (at your option) any later version.\r\n\/\/\r\n\/\/ This library is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n\/\/ Lesser General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU Lesser General Public\r\n\/\/ License along with this library; if not, write to the Free Software\r\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n#include <assert.h>\r\n#include <stdlib.h>\r\n#include <memory.h>\r\n#include <math.h>\r\n#include <stdexcept>\r\n#include <stdio.h>\r\n\r\n#include \"SoundTouch.h\"\r\n#include \"TDStretch.h\"\r\n#include \"RateTransposer.h\"\r\n#include \"cpu_detect.h\"\r\n\r\nusing namespace soundtouch;\r\n \r\n\/\/\/ test if two floating point numbers are equal\r\n#define TEST_FLOAT_EQUAL(a, b) (fabs(a - b) < 1e-10)\r\n\r\n\r\n\/\/\/ Print library version string for autoconf\r\nextern \"C\" void soundtouch_ac_test()\r\n{\r\n printf(\"SoundTouch Version: %s\\n\",SOUNDTOUCH_VERSION);\r\n} \r\n\r\n\r\nSoundTouch::SoundTouch()\r\n{\r\n \/\/ Initialize rate transposer and tempo changer instances\r\n\r\n pRateTransposer = RateTransposer::newInstance();\r\n pTDStretch = TDStretch::newInstance();\r\n\r\n setOutPipe(pTDStretch);\r\n\r\n rate = tempo = 0;\r\n\r\n virtualPitch = \r\n virtualRate = \r\n virtualTempo = 1.0;\r\n\r\n calcEffectiveRateAndTempo();\r\n\r\n channels = 0;\r\n bSrateSet = FALSE;\r\n}\r\n\r\n\r\n\r\nSoundTouch::~SoundTouch()\r\n{\r\n delete pRateTransposer;\r\n delete pTDStretch;\r\n}\r\n\r\n\r\n\r\n\/\/\/ Get SoundTouch library version string\r\nconst char *SoundTouch::getVersionString()\r\n{\r\n static const char *_version = SOUNDTOUCH_VERSION;\r\n\r\n return _version;\r\n}\r\n\r\n\r\n\/\/\/ Get SoundTouch library version Id\r\nuint SoundTouch::getVersionId()\r\n{\r\n return SOUNDTOUCH_VERSION_ID;\r\n}\r\n\r\n\r\n\/\/ Sets the number of channels, 1 = mono, 2 = stereo\r\nvoid SoundTouch::setChannels(uint numChannels)\r\n{\r\n if (numChannels != 1 && numChannels != 2) \r\n {\r\n throw std::runtime_error(\"Illegal number of channels\");\r\n }\r\n channels = numChannels;\r\n pRateTransposer->setChannels((int)numChannels);\r\n pTDStretch->setChannels((int)numChannels);\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new rate control value. Normal rate = 1.0, smaller values\r\n\/\/ represent slower rate, larger faster rates.\r\nvoid SoundTouch::setRate(float newRate)\r\n{\r\n virtualRate = newRate;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new rate control value as a difference in percents compared\r\n\/\/ to the original rate (-50 .. +100 %)\r\nvoid SoundTouch::setRateChange(float newRate)\r\n{\r\n virtualRate = 1.0f + 0.01f * newRate;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new tempo control value. Normal tempo = 1.0, smaller values\r\n\/\/ represent slower tempo, larger faster tempo.\r\nvoid SoundTouch::setTempo(float newTempo)\r\n{\r\n virtualTempo = newTempo;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new tempo control value as a difference in percents compared\r\n\/\/ to the original tempo (-50 .. +100 %)\r\nvoid SoundTouch::setTempoChange(float newTempo)\r\n{\r\n virtualTempo = 1.0f + 0.01f * newTempo;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new pitch control value. Original pitch = 1.0, smaller values\r\n\/\/ represent lower pitches, larger values higher pitch.\r\nvoid SoundTouch::setPitch(float newPitch)\r\n{\r\n virtualPitch = newPitch;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets pitch change in octaves compared to the original pitch\r\n\/\/ (-1.00 .. +1.00)\r\nvoid SoundTouch::setPitchOctaves(float newPitch)\r\n{\r\n virtualPitch = (float)exp(0.69314718056f * newPitch);\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets pitch change in semi-tones compared to the original pitch\r\n\/\/ (-12 .. +12)\r\nvoid SoundTouch::setPitchSemiTones(int newPitch)\r\n{\r\n setPitchOctaves((float)newPitch \/ 12.0f);\r\n}\r\n\r\n\r\n\r\nvoid SoundTouch::setPitchSemiTones(float newPitch)\r\n{\r\n setPitchOctaves(newPitch \/ 12.0f);\r\n}\r\n\r\n\r\n\/\/ Calculates 'effective' rate and tempo values from the\r\n\/\/ nominal control values.\r\nvoid SoundTouch::calcEffectiveRateAndTempo()\r\n{\r\n float oldTempo = tempo;\r\n float oldRate = rate;\r\n\r\n tempo = virtualTempo \/ virtualPitch;\r\n rate = virtualPitch * virtualRate;\r\n\r\n if (!TEST_FLOAT_EQUAL(rate,oldRate)) pRateTransposer->setRate(rate);\r\n if (!TEST_FLOAT_EQUAL(tempo, oldTempo)) pTDStretch->setTempo(tempo);\r\n\r\n#ifndef PREVENT_CLICK_AT_RATE_CROSSOVER\r\n if (rate <= 1.0f) \r\n {\r\n if (output != pTDStretch) \r\n {\r\n FIFOSamplePipe *tempoOut;\r\n\r\n assert(output == pRateTransposer);\r\n \/\/ move samples in the current output buffer to the output of pTDStretch\r\n tempoOut = pTDStretch->getOutput();\r\n tempoOut->moveSamples(*output);\r\n \/\/ move samples in pitch transposer's store buffer to tempo changer's input\r\n pTDStretch->moveSamples(*pRateTransposer->getStore());\r\n\r\n output = pTDStretch;\r\n }\r\n }\r\n else\r\n#endif\r\n {\r\n if (output != pRateTransposer) \r\n {\r\n FIFOSamplePipe *transOut;\r\n\r\n assert(output == pTDStretch);\r\n \/\/ move samples in the current output buffer to the output of pRateTransposer\r\n transOut = pRateTransposer->getOutput();\r\n transOut->moveSamples(*output);\r\n \/\/ move samples in tempo changer's input to pitch transposer's input\r\n pRateTransposer->moveSamples(*pTDStretch->getInput());\r\n\r\n output = pRateTransposer;\r\n }\r\n } \r\n}\r\n\r\n\r\n\/\/ Sets sample rate.\r\nvoid SoundTouch::setSampleRate(uint srate)\r\n{\r\n bSrateSet = TRUE;\r\n \/\/ set sample rate, leave other tempo changer parameters as they are.\r\n pTDStretch->setParameters((int)srate);\r\n}\r\n\r\n\r\n\/\/ Adds 'numSamples' pcs of samples from the 'samples' memory position into\r\n\/\/ the input of the object.\r\nvoid SoundTouch::putSamples(const SAMPLETYPE *samples, uint nSamples)\r\n{\r\n if (bSrateSet == FALSE) \r\n {\r\n throw std::runtime_error(\"SoundTouch : Sample rate not defined\");\r\n } \r\n else if (channels == 0) \r\n {\r\n throw std::runtime_error(\"SoundTouch : Number of channels not defined\");\r\n }\r\n\r\n \/\/ Transpose the rate of the new samples if necessary\r\n \/* Bypass the nominal setting - can introduce a click in sound when tempo\/pitch control crosses the nominal value...\r\n if (rate == 1.0f) \r\n {\r\n \/\/ The rate value is same as the original, simply evaluate the tempo changer. \r\n assert(output == pTDStretch);\r\n if (pRateTransposer->isEmpty() == 0) \r\n {\r\n \/\/ yet flush the last samples in the pitch transposer buffer\r\n \/\/ (may happen if 'rate' changes from a non-zero value to zero)\r\n pTDStretch->moveSamples(*pRateTransposer);\r\n }\r\n pTDStretch->putSamples(samples, nSamples);\r\n } \r\n *\/\r\n#ifndef _PREVENT_CLICK_AT_RATE_CROSSOVER\r\n else if (rate <= 1.0f) \r\n {\r\n \/\/ transpose the rate down, output the transposed sound to tempo changer buffer\r\n assert(output == pTDStretch);\r\n pRateTransposer->putSamples(samples, nSamples);\r\n pTDStretch->moveSamples(*pRateTransposer);\r\n } \r\n else \r\n#endif\r\n {\r\n \/\/ evaluate the tempo changer, then transpose the rate up, \r\n assert(output == pRateTransposer);\r\n pTDStretch->putSamples(samples, nSamples);\r\n pRateTransposer->moveSamples(*pTDStretch);\r\n }\r\n}\r\n\r\n\r\n\/\/ Flushes the last samples from the processing pipeline to the output.\r\n\/\/ Clears also the internal processing buffers.\r\n\/\/\r\n\/\/ Note: This function is meant for extracting the last samples of a sound\r\n\/\/ stream. This function may introduce additional blank samples in the end\r\n\/\/ of the sound stream, and thus it's not recommended to call this function\r\n\/\/ in the middle of a sound stream.\r\nvoid SoundTouch::flush()\r\n{\r\n int i;\r\n uint nOut;\r\n SAMPLETYPE buff[128];\r\n\r\n nOut = numSamples();\r\n\r\n memset(buff, 0, 128 * sizeof(SAMPLETYPE));\r\n \/\/ \"Push\" the last active samples out from the processing pipeline by\r\n \/\/ feeding blank samples into the processing pipeline until new, \r\n \/\/ processed samples appear in the output (not however, more than \r\n \/\/ 8ksamples in any case)\r\n for (i = 0; i < 128; i ++) \r\n {\r\n putSamples(buff, 64);\r\n if (numSamples() != nOut) break; \/\/ new samples have appeared in the output!\r\n }\r\n\r\n \/\/ Clear working buffers\r\n pRateTransposer->clear();\r\n pTDStretch->clearInput();\r\n \/\/ yet leave the 'tempoChanger' output intouched as that's where the\r\n \/\/ flushed samples are!\r\n}\r\n\r\n\r\n\/\/ Changes a setting controlling the processing system behaviour. See the\r\n\/\/ 'SETTING_...' defines for available setting ID's.\r\nBOOL SoundTouch::setSetting(int settingId, int value)\r\n{\r\n int sampleRate, sequenceMs, seekWindowMs, overlapMs;\r\n\r\n \/\/ read current tdstretch routine parameters\r\n pTDStretch->getParameters(&sampleRate, &sequenceMs, &seekWindowMs, &overlapMs);\r\n\r\n switch (settingId) \r\n {\r\n case SETTING_USE_AA_FILTER :\r\n \/\/ enables \/ disabless anti-alias filter\r\n pRateTransposer->enableAAFilter((value != 0) ? TRUE : FALSE);\r\n return TRUE;\r\n\r\n case SETTING_AA_FILTER_LENGTH :\r\n \/\/ sets anti-alias filter length\r\n pRateTransposer->getAAFilter()->setLength(value);\r\n return TRUE;\r\n\r\n case SETTING_USE_QUICKSEEK :\r\n \/\/ enables \/ disables tempo routine quick seeking algorithm\r\n pTDStretch->enableQuickSeek((value != 0) ? TRUE : FALSE);\r\n return TRUE;\r\n\r\n case SETTING_SEQUENCE_MS:\r\n \/\/ change time-stretch sequence duration parameter\r\n pTDStretch->setParameters(sampleRate, value, seekWindowMs, overlapMs);\r\n return TRUE;\r\n\r\n case SETTING_SEEKWINDOW_MS:\r\n \/\/ change time-stretch seek window length parameter\r\n pTDStretch->setParameters(sampleRate, sequenceMs, value, overlapMs);\r\n return TRUE;\r\n\r\n case SETTING_OVERLAP_MS:\r\n \/\/ change time-stretch overlap length parameter\r\n pTDStretch->setParameters(sampleRate, sequenceMs, seekWindowMs, value);\r\n return TRUE;\r\n\r\n default :\r\n return FALSE;\r\n }\r\n}\r\n\r\n\r\n\/\/ Reads a setting controlling the processing system behaviour. See the\r\n\/\/ 'SETTING_...' defines for available setting ID's.\r\n\/\/\r\n\/\/ Returns the setting value.\r\nint SoundTouch::getSetting(int settingId) const\r\n{\r\n int temp;\r\n\r\n switch (settingId) \r\n {\r\n case SETTING_USE_AA_FILTER :\r\n return (uint)pRateTransposer->isAAFilterEnabled();\r\n\r\n case SETTING_AA_FILTER_LENGTH :\r\n return pRateTransposer->getAAFilter()->getLength();\r\n\r\n case SETTING_USE_QUICKSEEK :\r\n return (uint) pTDStretch->isQuickSeekEnabled();\r\n\r\n case SETTING_SEQUENCE_MS:\r\n pTDStretch->getParameters(NULL, &temp, NULL, NULL);\r\n return temp;\r\n\r\n case SETTING_SEEKWINDOW_MS:\r\n pTDStretch->getParameters(NULL, NULL, &temp, NULL);\r\n return temp;\r\n\r\n case SETTING_OVERLAP_MS:\r\n pTDStretch->getParameters(NULL, NULL, NULL, &temp);\r\n return temp;\r\n\r\n default :\r\n return 0;\r\n }\r\n}\r\n\r\n\r\n\/\/ Clears all the samples in the object's output and internal processing\r\n\/\/ buffers.\r\nvoid SoundTouch::clear()\r\n{\r\n pRateTransposer->clear();\r\n pTDStretch->clear();\r\n}\r\n\r\n\r\n\r\n\/\/\/ Returns number of samples currently unprocessed.\r\nuint SoundTouch::numUnprocessedSamples() const\r\n{\r\n FIFOSamplePipe * psp;\r\n if (pTDStretch)\r\n {\r\n psp = pTDStretch->getInput();\r\n if (psp)\r\n {\r\n return psp->numSamples();\r\n }\r\n }\r\n return 0;\r\n}\r\n<commit_msg>Fixed a typo bug<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/\r\n\/\/\/ SoundTouch - main class for tempo\/pitch\/rate adjusting routines. \r\n\/\/\/\r\n\/\/\/ Notes:\r\n\/\/\/ - Initialize the SoundTouch object instance by setting up the sound stream \r\n\/\/\/ parameters with functions 'setSampleRate' and 'setChannels', then set \r\n\/\/\/ desired tempo\/pitch\/rate settings with the corresponding functions.\r\n\/\/\/\r\n\/\/\/ - The SoundTouch class behaves like a first-in-first-out pipeline: The \r\n\/\/\/ samples that are to be processed are fed into one of the pipe by calling\r\n\/\/\/ function 'putSamples', while the ready processed samples can be read \r\n\/\/\/ from the other end of the pipeline with function 'receiveSamples'.\r\n\/\/\/ \r\n\/\/\/ - The SoundTouch processing classes require certain sized 'batches' of \r\n\/\/\/ samples in order to process the sound. For this reason the classes buffer \r\n\/\/\/ incoming samples until there are enough of samples available for \r\n\/\/\/ processing, then they carry out the processing step and consequently\r\n\/\/\/ make the processed samples available for outputting.\r\n\/\/\/ \r\n\/\/\/ - For the above reason, the processing routines introduce a certain \r\n\/\/\/ 'latency' between the input and output, so that the samples input to\r\n\/\/\/ SoundTouch may not be immediately available in the output, and neither \r\n\/\/\/ the amount of outputtable samples may not immediately be in direct \r\n\/\/\/ relationship with the amount of previously input samples.\r\n\/\/\/\r\n\/\/\/ - The tempo\/pitch\/rate control parameters can be altered during processing.\r\n\/\/\/ Please notice though that they aren't currently protected by semaphores,\r\n\/\/\/ so in multi-thread application external semaphore protection may be\r\n\/\/\/ required.\r\n\/\/\/\r\n\/\/\/ - This class utilizes classes 'TDStretch' for tempo change (without modifying\r\n\/\/\/ pitch) and 'RateTransposer' for changing the playback rate (that is, both \r\n\/\/\/ tempo and pitch in the same ratio) of the sound. The third available control \r\n\/\/\/ 'pitch' (change pitch but maintain tempo) is produced by a combination of\r\n\/\/\/ combining the two other controls.\r\n\/\/\/\r\n\/\/\/ Author : Copyright (c) Olli Parviainen\r\n\/\/\/ Author e-mail : oparviai 'at' iki.fi\r\n\/\/\/ SoundTouch WWW: http:\/\/www.surina.net\/soundtouch\r\n\/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ Last changed : $Date$\r\n\/\/ File revision : $Revision: 4 $\r\n\/\/\r\n\/\/ $Id$\r\n\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ License :\r\n\/\/\r\n\/\/ SoundTouch audio processing library\r\n\/\/ Copyright (c) Olli Parviainen\r\n\/\/\r\n\/\/ This library is free software; you can redistribute it and\/or\r\n\/\/ modify it under the terms of the GNU Lesser General Public\r\n\/\/ License as published by the Free Software Foundation; either\r\n\/\/ version 2.1 of the License, or (at your option) any later version.\r\n\/\/\r\n\/\/ This library is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n\/\/ Lesser General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU Lesser General Public\r\n\/\/ License along with this library; if not, write to the Free Software\r\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n#include <assert.h>\r\n#include <stdlib.h>\r\n#include <memory.h>\r\n#include <math.h>\r\n#include <stdexcept>\r\n#include <stdio.h>\r\n\r\n#include \"SoundTouch.h\"\r\n#include \"TDStretch.h\"\r\n#include \"RateTransposer.h\"\r\n#include \"cpu_detect.h\"\r\n\r\nusing namespace soundtouch;\r\n \r\n\/\/\/ test if two floating point numbers are equal\r\n#define TEST_FLOAT_EQUAL(a, b) (fabs(a - b) < 1e-10)\r\n\r\n\r\n\/\/\/ Print library version string for autoconf\r\nextern \"C\" void soundtouch_ac_test()\r\n{\r\n printf(\"SoundTouch Version: %s\\n\",SOUNDTOUCH_VERSION);\r\n} \r\n\r\n\r\nSoundTouch::SoundTouch()\r\n{\r\n \/\/ Initialize rate transposer and tempo changer instances\r\n\r\n pRateTransposer = RateTransposer::newInstance();\r\n pTDStretch = TDStretch::newInstance();\r\n\r\n setOutPipe(pTDStretch);\r\n\r\n rate = tempo = 0;\r\n\r\n virtualPitch = \r\n virtualRate = \r\n virtualTempo = 1.0;\r\n\r\n calcEffectiveRateAndTempo();\r\n\r\n channels = 0;\r\n bSrateSet = FALSE;\r\n}\r\n\r\n\r\n\r\nSoundTouch::~SoundTouch()\r\n{\r\n delete pRateTransposer;\r\n delete pTDStretch;\r\n}\r\n\r\n\r\n\r\n\/\/\/ Get SoundTouch library version string\r\nconst char *SoundTouch::getVersionString()\r\n{\r\n static const char *_version = SOUNDTOUCH_VERSION;\r\n\r\n return _version;\r\n}\r\n\r\n\r\n\/\/\/ Get SoundTouch library version Id\r\nuint SoundTouch::getVersionId()\r\n{\r\n return SOUNDTOUCH_VERSION_ID;\r\n}\r\n\r\n\r\n\/\/ Sets the number of channels, 1 = mono, 2 = stereo\r\nvoid SoundTouch::setChannels(uint numChannels)\r\n{\r\n if (numChannels != 1 && numChannels != 2) \r\n {\r\n throw std::runtime_error(\"Illegal number of channels\");\r\n }\r\n channels = numChannels;\r\n pRateTransposer->setChannels((int)numChannels);\r\n pTDStretch->setChannels((int)numChannels);\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new rate control value. Normal rate = 1.0, smaller values\r\n\/\/ represent slower rate, larger faster rates.\r\nvoid SoundTouch::setRate(float newRate)\r\n{\r\n virtualRate = newRate;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new rate control value as a difference in percents compared\r\n\/\/ to the original rate (-50 .. +100 %)\r\nvoid SoundTouch::setRateChange(float newRate)\r\n{\r\n virtualRate = 1.0f + 0.01f * newRate;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new tempo control value. Normal tempo = 1.0, smaller values\r\n\/\/ represent slower tempo, larger faster tempo.\r\nvoid SoundTouch::setTempo(float newTempo)\r\n{\r\n virtualTempo = newTempo;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new tempo control value as a difference in percents compared\r\n\/\/ to the original tempo (-50 .. +100 %)\r\nvoid SoundTouch::setTempoChange(float newTempo)\r\n{\r\n virtualTempo = 1.0f + 0.01f * newTempo;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets new pitch control value. Original pitch = 1.0, smaller values\r\n\/\/ represent lower pitches, larger values higher pitch.\r\nvoid SoundTouch::setPitch(float newPitch)\r\n{\r\n virtualPitch = newPitch;\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets pitch change in octaves compared to the original pitch\r\n\/\/ (-1.00 .. +1.00)\r\nvoid SoundTouch::setPitchOctaves(float newPitch)\r\n{\r\n virtualPitch = (float)exp(0.69314718056f * newPitch);\r\n calcEffectiveRateAndTempo();\r\n}\r\n\r\n\r\n\r\n\/\/ Sets pitch change in semi-tones compared to the original pitch\r\n\/\/ (-12 .. +12)\r\nvoid SoundTouch::setPitchSemiTones(int newPitch)\r\n{\r\n setPitchOctaves((float)newPitch \/ 12.0f);\r\n}\r\n\r\n\r\n\r\nvoid SoundTouch::setPitchSemiTones(float newPitch)\r\n{\r\n setPitchOctaves(newPitch \/ 12.0f);\r\n}\r\n\r\n\r\n\/\/ Calculates 'effective' rate and tempo values from the\r\n\/\/ nominal control values.\r\nvoid SoundTouch::calcEffectiveRateAndTempo()\r\n{\r\n float oldTempo = tempo;\r\n float oldRate = rate;\r\n\r\n tempo = virtualTempo \/ virtualPitch;\r\n rate = virtualPitch * virtualRate;\r\n\r\n if (!TEST_FLOAT_EQUAL(rate,oldRate)) pRateTransposer->setRate(rate);\r\n if (!TEST_FLOAT_EQUAL(tempo, oldTempo)) pTDStretch->setTempo(tempo);\r\n\r\n#ifndef PREVENT_CLICK_AT_RATE_CROSSOVER\r\n if (rate <= 1.0f) \r\n {\r\n if (output != pTDStretch) \r\n {\r\n FIFOSamplePipe *tempoOut;\r\n\r\n assert(output == pRateTransposer);\r\n \/\/ move samples in the current output buffer to the output of pTDStretch\r\n tempoOut = pTDStretch->getOutput();\r\n tempoOut->moveSamples(*output);\r\n \/\/ move samples in pitch transposer's store buffer to tempo changer's input\r\n pTDStretch->moveSamples(*pRateTransposer->getStore());\r\n\r\n output = pTDStretch;\r\n }\r\n }\r\n else\r\n#endif\r\n {\r\n if (output != pRateTransposer) \r\n {\r\n FIFOSamplePipe *transOut;\r\n\r\n assert(output == pTDStretch);\r\n \/\/ move samples in the current output buffer to the output of pRateTransposer\r\n transOut = pRateTransposer->getOutput();\r\n transOut->moveSamples(*output);\r\n \/\/ move samples in tempo changer's input to pitch transposer's input\r\n pRateTransposer->moveSamples(*pTDStretch->getInput());\r\n\r\n output = pRateTransposer;\r\n }\r\n } \r\n}\r\n\r\n\r\n\/\/ Sets sample rate.\r\nvoid SoundTouch::setSampleRate(uint srate)\r\n{\r\n bSrateSet = TRUE;\r\n \/\/ set sample rate, leave other tempo changer parameters as they are.\r\n pTDStretch->setParameters((int)srate);\r\n}\r\n\r\n\r\n\/\/ Adds 'numSamples' pcs of samples from the 'samples' memory position into\r\n\/\/ the input of the object.\r\nvoid SoundTouch::putSamples(const SAMPLETYPE *samples, uint nSamples)\r\n{\r\n if (bSrateSet == FALSE) \r\n {\r\n throw std::runtime_error(\"SoundTouch : Sample rate not defined\");\r\n } \r\n else if (channels == 0) \r\n {\r\n throw std::runtime_error(\"SoundTouch : Number of channels not defined\");\r\n }\r\n\r\n \/\/ Transpose the rate of the new samples if necessary\r\n \/* Bypass the nominal setting - can introduce a click in sound when tempo\/pitch control crosses the nominal value...\r\n if (rate == 1.0f) \r\n {\r\n \/\/ The rate value is same as the original, simply evaluate the tempo changer. \r\n assert(output == pTDStretch);\r\n if (pRateTransposer->isEmpty() == 0) \r\n {\r\n \/\/ yet flush the last samples in the pitch transposer buffer\r\n \/\/ (may happen if 'rate' changes from a non-zero value to zero)\r\n pTDStretch->moveSamples(*pRateTransposer);\r\n }\r\n pTDStretch->putSamples(samples, nSamples);\r\n } \r\n *\/\r\n#ifndef PREVENT_CLICK_AT_RATE_CROSSOVER\r\n else if (rate <= 1.0f) \r\n {\r\n \/\/ transpose the rate down, output the transposed sound to tempo changer buffer\r\n assert(output == pTDStretch);\r\n pRateTransposer->putSamples(samples, nSamples);\r\n pTDStretch->moveSamples(*pRateTransposer);\r\n } \r\n else \r\n#endif\r\n {\r\n \/\/ evaluate the tempo changer, then transpose the rate up, \r\n assert(output == pRateTransposer);\r\n pTDStretch->putSamples(samples, nSamples);\r\n pRateTransposer->moveSamples(*pTDStretch);\r\n }\r\n}\r\n\r\n\r\n\/\/ Flushes the last samples from the processing pipeline to the output.\r\n\/\/ Clears also the internal processing buffers.\r\n\/\/\r\n\/\/ Note: This function is meant for extracting the last samples of a sound\r\n\/\/ stream. This function may introduce additional blank samples in the end\r\n\/\/ of the sound stream, and thus it's not recommended to call this function\r\n\/\/ in the middle of a sound stream.\r\nvoid SoundTouch::flush()\r\n{\r\n int i;\r\n uint nOut;\r\n SAMPLETYPE buff[128];\r\n\r\n nOut = numSamples();\r\n\r\n memset(buff, 0, 128 * sizeof(SAMPLETYPE));\r\n \/\/ \"Push\" the last active samples out from the processing pipeline by\r\n \/\/ feeding blank samples into the processing pipeline until new, \r\n \/\/ processed samples appear in the output (not however, more than \r\n \/\/ 8ksamples in any case)\r\n for (i = 0; i < 128; i ++) \r\n {\r\n putSamples(buff, 64);\r\n if (numSamples() != nOut) break; \/\/ new samples have appeared in the output!\r\n }\r\n\r\n \/\/ Clear working buffers\r\n pRateTransposer->clear();\r\n pTDStretch->clearInput();\r\n \/\/ yet leave the 'tempoChanger' output intouched as that's where the\r\n \/\/ flushed samples are!\r\n}\r\n\r\n\r\n\/\/ Changes a setting controlling the processing system behaviour. See the\r\n\/\/ 'SETTING_...' defines for available setting ID's.\r\nBOOL SoundTouch::setSetting(int settingId, int value)\r\n{\r\n int sampleRate, sequenceMs, seekWindowMs, overlapMs;\r\n\r\n \/\/ read current tdstretch routine parameters\r\n pTDStretch->getParameters(&sampleRate, &sequenceMs, &seekWindowMs, &overlapMs);\r\n\r\n switch (settingId) \r\n {\r\n case SETTING_USE_AA_FILTER :\r\n \/\/ enables \/ disabless anti-alias filter\r\n pRateTransposer->enableAAFilter((value != 0) ? TRUE : FALSE);\r\n return TRUE;\r\n\r\n case SETTING_AA_FILTER_LENGTH :\r\n \/\/ sets anti-alias filter length\r\n pRateTransposer->getAAFilter()->setLength(value);\r\n return TRUE;\r\n\r\n case SETTING_USE_QUICKSEEK :\r\n \/\/ enables \/ disables tempo routine quick seeking algorithm\r\n pTDStretch->enableQuickSeek((value != 0) ? TRUE : FALSE);\r\n return TRUE;\r\n\r\n case SETTING_SEQUENCE_MS:\r\n \/\/ change time-stretch sequence duration parameter\r\n pTDStretch->setParameters(sampleRate, value, seekWindowMs, overlapMs);\r\n return TRUE;\r\n\r\n case SETTING_SEEKWINDOW_MS:\r\n \/\/ change time-stretch seek window length parameter\r\n pTDStretch->setParameters(sampleRate, sequenceMs, value, overlapMs);\r\n return TRUE;\r\n\r\n case SETTING_OVERLAP_MS:\r\n \/\/ change time-stretch overlap length parameter\r\n pTDStretch->setParameters(sampleRate, sequenceMs, seekWindowMs, value);\r\n return TRUE;\r\n\r\n default :\r\n return FALSE;\r\n }\r\n}\r\n\r\n\r\n\/\/ Reads a setting controlling the processing system behaviour. See the\r\n\/\/ 'SETTING_...' defines for available setting ID's.\r\n\/\/\r\n\/\/ Returns the setting value.\r\nint SoundTouch::getSetting(int settingId) const\r\n{\r\n int temp;\r\n\r\n switch (settingId) \r\n {\r\n case SETTING_USE_AA_FILTER :\r\n return (uint)pRateTransposer->isAAFilterEnabled();\r\n\r\n case SETTING_AA_FILTER_LENGTH :\r\n return pRateTransposer->getAAFilter()->getLength();\r\n\r\n case SETTING_USE_QUICKSEEK :\r\n return (uint) pTDStretch->isQuickSeekEnabled();\r\n\r\n case SETTING_SEQUENCE_MS:\r\n pTDStretch->getParameters(NULL, &temp, NULL, NULL);\r\n return temp;\r\n\r\n case SETTING_SEEKWINDOW_MS:\r\n pTDStretch->getParameters(NULL, NULL, &temp, NULL);\r\n return temp;\r\n\r\n case SETTING_OVERLAP_MS:\r\n pTDStretch->getParameters(NULL, NULL, NULL, &temp);\r\n return temp;\r\n\r\n default :\r\n return 0;\r\n }\r\n}\r\n\r\n\r\n\/\/ Clears all the samples in the object's output and internal processing\r\n\/\/ buffers.\r\nvoid SoundTouch::clear()\r\n{\r\n pRateTransposer->clear();\r\n pTDStretch->clear();\r\n}\r\n\r\n\r\n\r\n\/\/\/ Returns number of samples currently unprocessed.\r\nuint SoundTouch::numUnprocessedSamples() const\r\n{\r\n FIFOSamplePipe * psp;\r\n if (pTDStretch)\r\n {\r\n psp = pTDStretch->getInput();\r\n if (psp)\r\n {\r\n return psp->numSamples();\r\n }\r\n }\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ ---------------------------------------------------------------------\n\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2004 - 2013 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n\n\/\/ TrilinosWrappers::SparseMatrix::print got column indices wrong\n\n#include \"..\/tests.h\"\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/base\/index_set.h>\n#include <deal.II\/lac\/trilinos_sparse_matrix.h>\n#include <deal.II\/lac\/trilinos_sparsity_pattern.h>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n\nvoid test ()\n{\n const unsigned int n_procs = Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);\n const unsigned int my_id = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n\n const unsigned int n_rows = 2;\n const unsigned int n_cols = 2;\n\n IndexSet row_partitioning (n_rows);\n IndexSet col_partitioning (n_cols);\n\n if (n_procs == 1)\n {\n row_partitioning.add_range(0, n_rows);\n col_partitioning.add_range(0, n_cols);\n }\n else if (n_procs == 2)\n {\n if (my_id == 0)\n {\n row_partitioning.add_range(0, 1);\n col_partitioning.add_range(0, 1);\n }\n else if (my_id == 1)\n {\n row_partitioning.add_range(1, n_rows);\n col_partitioning.add_range(1, n_cols);\n }\n }\n else\n Assert (false, ExcNotImplemented());\n\n \/* A is\n\n 0 1\n 0 1\n *\/\n const unsigned int n_entries = 2;\n const unsigned int line [n_entries] = {0, 1};\n const unsigned int local_index [n_entries] = {1, 1};\n const double local_value [n_entries] = {1.0, 1.0};\n\n TrilinosWrappers::SparsityPattern sp (row_partitioning, col_partitioning, MPI_COMM_WORLD);\n for (unsigned int i = 0; i < n_entries; ++i)\n if (row_partitioning.is_element(line[i]))\n sp.add(line[i], local_index[i]);\n sp.compress();\n\n TrilinosWrappers::SparseMatrix A;\n A.clear ();\n A.reinit (sp);\n for (unsigned int i = 0; i<n_entries; ++i)\n if (row_partitioning.is_element(line[i]))\n A.add(line[i], local_index[i], local_value[i]);\n A.compress(VectorOperation::add);\n\n if (my_id == 0)\n {\n Assert(A.el(0, 0) == 0, ExcMessage(\"Wrong element in A!\"));\n Assert(A.el(0, 1) == 1, ExcMessage(\"Wrong element in A!\"));\n }\n if ((n_procs == 1) || (my_id == 1))\n {\n Assert(A.el(1, 0) == 0, ExcMessage(\"Wrong element in A!\"));\n Assert(A.el(1, 1) == 1, ExcMessage(\"Wrong element in A!\"));\n }\n\n TrilinosWrappers::SparseMatrix AtA;\n A.Tmmult (AtA, A);\n\n \/* AtA should be\n\n 0 0\n 0 2\n *\/\n\n \/\/ checking AtA row partitioning\n if (n_procs == 2)\n {\n if (my_id == 0)\n {\n Assert(AtA.local_range().first == 0,\n ExcMessage(\"AtA Local Range is not as expected.\"));\n Assert(AtA.local_range().second == 1,\n ExcMessage(\"AtA Local Range is not as expected.\"));\n }\n if (my_id == 1)\n {\n Assert(AtA.local_range().first == 1,\n ExcMessage(\"AtA Local Range is not as expected.\"));\n Assert(AtA.local_range().second == 2,\n ExcMessage(\"AtA Local Range is not as expected.\"));\n }\n }\n\n \/\/ checking AtA elements. note that\n \/\/ the el() function either returns\n \/\/ the correct value, or zero in\n \/\/ case the element is stored on\n \/\/ other processors. consequently,\n \/\/ in the following we only test\n \/\/ that the values that *must* be\n \/\/ zero in AtA are indeed zero, but\n \/\/ not that the others have the\n \/\/ correct value\n Assert(AtA.el(0, 0) == 0, ExcMessage(\"Wrong element in AtA!\"));\n Assert(AtA.el(0, 1) == 0, ExcMessage(\"Wrong element in AtA!\"));\n Assert(AtA.el(1, 0) == 0, ExcMessage(\"Wrong element in AtA!\"));\n\n \/\/ now also check the one nonzero\n \/\/ element\n if ((n_procs == 1) || (my_id == 1))\n Assert(AtA.el(1, 1) == 2, ExcMessage(\"Wrong element in AtA!\"));\n\n deallog << \"OK\" << endl;\n}\n\n\n\nint main (int argc, char **argv)\n{\n Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv);\n\n unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);\n deallog.push(Utilities::int_to_string(myid));\n\n if (myid == 0)\n {\n std::ofstream logfile(\"output\");\n deallog.attach(logfile);\n deallog << std::setprecision(4);\n deallog.depth_console(0);\n deallog.threshold_double(1.e-10);\n\n test();\n }\n else\n test();\n\n}\n<commit_msg>Catch an exception that apparently happens in 64-bit mode.<commit_after>\/\/ ---------------------------------------------------------------------\n\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2004 - 2013 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n\n\/\/ TrilinosWrappers::SparseMatrix::print got column indices wrong\n\n#include \"..\/tests.h\"\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/base\/index_set.h>\n#include <deal.II\/lac\/trilinos_sparse_matrix.h>\n#include <deal.II\/lac\/trilinos_sparsity_pattern.h>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n\nvoid test ()\n{\n const unsigned int n_procs = Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);\n const unsigned int my_id = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n\n const unsigned int n_rows = 2;\n const unsigned int n_cols = 2;\n\n IndexSet row_partitioning (n_rows);\n IndexSet col_partitioning (n_cols);\n\n if (n_procs == 1)\n {\n row_partitioning.add_range(0, n_rows);\n col_partitioning.add_range(0, n_cols);\n }\n else if (n_procs == 2)\n {\n if (my_id == 0)\n {\n row_partitioning.add_range(0, 1);\n col_partitioning.add_range(0, 1);\n }\n else if (my_id == 1)\n {\n row_partitioning.add_range(1, n_rows);\n col_partitioning.add_range(1, n_cols);\n }\n }\n else\n Assert (false, ExcNotImplemented());\n\n \/* A is\n\n 0 1\n 0 1\n *\/\n const unsigned int n_entries = 2;\n const unsigned int line [n_entries] = {0, 1};\n const unsigned int local_index [n_entries] = {1, 1};\n const double local_value [n_entries] = {1.0, 1.0};\n\n TrilinosWrappers::SparsityPattern sp (row_partitioning, col_partitioning, MPI_COMM_WORLD);\n for (unsigned int i = 0; i < n_entries; ++i)\n if (row_partitioning.is_element(line[i]))\n sp.add(line[i], local_index[i]);\n sp.compress();\n\n TrilinosWrappers::SparseMatrix A;\n A.clear ();\n A.reinit (sp);\n for (unsigned int i = 0; i<n_entries; ++i)\n if (row_partitioning.is_element(line[i]))\n A.add(line[i], local_index[i], local_value[i]);\n A.compress(VectorOperation::add);\n\n if (my_id == 0)\n {\n Assert(A.el(0, 0) == 0, ExcMessage(\"Wrong element in A!\"));\n Assert(A.el(0, 1) == 1, ExcMessage(\"Wrong element in A!\"));\n }\n if ((n_procs == 1) || (my_id == 1))\n {\n Assert(A.el(1, 0) == 0, ExcMessage(\"Wrong element in A!\"));\n Assert(A.el(1, 1) == 1, ExcMessage(\"Wrong element in A!\"));\n }\n\n TrilinosWrappers::SparseMatrix AtA;\n A.Tmmult (AtA, A);\n\n \/* AtA should be\n\n 0 0\n 0 2\n *\/\n\n \/\/ checking AtA row partitioning\n if (n_procs == 2)\n {\n if (my_id == 0)\n {\n Assert(AtA.local_range().first == 0,\n ExcMessage(\"AtA Local Range is not as expected.\"));\n Assert(AtA.local_range().second == 1,\n ExcMessage(\"AtA Local Range is not as expected.\"));\n }\n if (my_id == 1)\n {\n Assert(AtA.local_range().first == 1,\n ExcMessage(\"AtA Local Range is not as expected.\"));\n Assert(AtA.local_range().second == 2,\n ExcMessage(\"AtA Local Range is not as expected.\"));\n }\n }\n\n \/\/ checking AtA elements. note that\n \/\/ the el() function either returns\n \/\/ the correct value, or zero in\n \/\/ case the element is stored on\n \/\/ other processors. consequently,\n \/\/ in the following we only test\n \/\/ that the values that *must* be\n \/\/ zero in AtA are indeed zero, but\n \/\/ not that the others have the\n \/\/ correct value\n Assert(AtA.el(0, 0) == 0, ExcMessage(\"Wrong element in AtA!\"));\n Assert(AtA.el(0, 1) == 0, ExcMessage(\"Wrong element in AtA!\"));\n Assert(AtA.el(1, 0) == 0, ExcMessage(\"Wrong element in AtA!\"));\n\n \/\/ now also check the one nonzero\n \/\/ element\n if ((n_procs == 1) || (my_id == 1))\n Assert(AtA.el(1, 1) == 2, ExcMessage(\"Wrong element in AtA!\"));\n\n deallog << \"OK\" << endl;\n}\n\n\n\nint main (int argc, char **argv)\n{\n Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv);\n\n unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);\n deallog.push(Utilities::int_to_string(myid));\n\n try\n {\n if (myid == 0)\n\t{\n\t std::ofstream logfile(\"output\");\n\t deallog.attach(logfile);\n\t deallog << std::setprecision(4);\n\t deallog.depth_console(0);\n\t deallog.threshold_double(1.e-10);\n\n\t test();\n\t}\n else\n\ttest();\n }\n catch (const char *p)\n {\n std::cerr << \"Uncaught exception: \" << p << std::endl;\n std::exit (1);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Typer.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 19\/06\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Typer_hpp\n#define Typer_hpp\n\n#include <memory>\n#include \"KeyboardMachine.hpp\"\n#include \"..\/ClockReceiver\/ClockReceiver.hpp\"\n\nnamespace Utility {\n\n\/*!\n\tAn interface that provides a mapping from logical characters to the sequence of keys\n\tnecessary to type that character on a given machine.\n*\/\nclass CharacterMapper {\n\tpublic:\n\t\t\/\/\/ @returns The EndSequence-terminated sequence of keys that would cause @c character to be typed.\n\t\tvirtual uint16_t *sequence_for_character(char character) = 0;\n\n\t\t\/\/\/ Terminates a key sequence.\n\t\tstatic const uint16_t EndSequence = 0xffff;\n\n\t\t\/*!\n\t\t\tIf returned as the first entry in a key sequence, indicates that the requested character\n\t\t\tcannot be mapped.\n\t\t*\/\n\t\tstatic const uint16_t NotMapped = 0xfffe;\n\n\tprotected:\n\t\ttypedef uint16_t KeySequence[16];\n\n\t\t\/*!\n\t\t\tProvided in the base class as a convenience: given the lookup table of key sequences @c sequences,\n\t\t\twith @c length entries, returns the sequence for character @c character if it exists; otherwise\n\t\t\treturns @c nullptr.\n\t\t*\/\n\t\tuint16_t *table_lookup_sequence_for_character(KeySequence *sequences, size_t length, char character);\n};\n\n\/*!\n\tProvides a stateful mechanism for typing a sequence of characters. Each character is mapped to a key sequence\n\tby a character mapper. That key sequence is then replayed to a delegate.\n\n\tBeing given a delay and frequency at construction, the run_for interface can be used to produce time-based\n\ttyping. Alternatively, an owner may decline to use run_for and simply call type_next_character each time a\n\tfresh key transition is ready to be consumed.\n*\/\nclass Typer {\n\tpublic:\n\t\tclass Delegate: public KeyboardMachine::Machine {\n\t\t\tpublic:\n\t\t\t\tvirtual void typer_reset(Typer *typer) = 0;\n\t\t};\n\n\t\tTyper(const char *string, HalfCycles delay, HalfCycles frequency, std::unique_ptr<CharacterMapper> character_mapper, Delegate *delegate);\n\t\t~Typer();\n\n\t\tvoid run_for(const HalfCycles duration);\n\t\tbool type_next_character();\n\n\t\tbool is_completed();\n\n\t\tconst char BeginString = 0x02;\t\/\/ i.e. ASCII start of text\n\t\tconst char EndString = 0x03;\t\/\/ i.e. ASCII end of text\n\n\tprivate:\n\t\tchar *string_;\n\t\tsize_t string_pointer_;\n\n\t\tHalfCycles frequency_;\n\t\tHalfCycles counter_;\n\t\tint phase_;\n\n\t\tDelegate *delegate_;\n\t\tstd::unique_ptr<CharacterMapper> character_mapper_;\n\n\t\tbool try_type_next_character();\n};\n\n\/*!\n\tProvides a default base class for type recipients: classes that want to attach a single typer at a time and\n\twhich may or may not want to nominate an initial delay and typing frequency.\n*\/\nclass TypeRecipient: public Typer::Delegate {\n\tpublic:\n\t\t\/\/\/ Attaches a typer to this class that will type @c string using @c character_mapper as a source.\n\t\tvoid set_typer_for_string(const char *string, std::unique_ptr<CharacterMapper> character_mapper) {\n\t\t\ttyper_.reset(new Typer(string, get_typer_delay(), get_typer_frequency(), std::move(character_mapper), this));\n\t\t}\n\n\t\t\/*!\n\t\t\tProvided as a hook for subclasses to implement so that external callers can install a typer\n\t\t\twithout needing inside knowledge as to where the character mapper comes from.\n\t\t*\/\n\t\tvirtual void set_typer_for_string(const char *string) = 0;\n\n\t\t\/*!\n\t\t\tProvided in order to conform to that part of the Typer::Delegate interface that goes above and\n\t\t\tbeyond KeyboardMachine::Machine; responds to the end of typing by clearing all keys.\n\t\t*\/\n\t\tvoid typer_reset(Typer *typer) {\n\t\t\tclear_all_keys();\n\t\t}\n\n\tprotected:\n\t\tvirtual HalfCycles get_typer_delay() { return HalfCycles(0); }\n\t\tvirtual HalfCycles get_typer_frequency() { return HalfCycles(0); }\n\t\tstd::unique_ptr<Typer> typer_;\n};\n\n}\n\n#endif \/* Typer_hpp *\/\n<commit_msg>Okay, even if releasing it is unsafe, I can at least move the typer so that it is no longer called.<commit_after>\/\/\n\/\/ Typer.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 19\/06\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Typer_hpp\n#define Typer_hpp\n\n#include <memory>\n#include \"KeyboardMachine.hpp\"\n#include \"..\/ClockReceiver\/ClockReceiver.hpp\"\n\nnamespace Utility {\n\n\/*!\n\tAn interface that provides a mapping from logical characters to the sequence of keys\n\tnecessary to type that character on a given machine.\n*\/\nclass CharacterMapper {\n\tpublic:\n\t\t\/\/\/ @returns The EndSequence-terminated sequence of keys that would cause @c character to be typed.\n\t\tvirtual uint16_t *sequence_for_character(char character) = 0;\n\n\t\t\/\/\/ Terminates a key sequence.\n\t\tstatic const uint16_t EndSequence = 0xffff;\n\n\t\t\/*!\n\t\t\tIf returned as the first entry in a key sequence, indicates that the requested character\n\t\t\tcannot be mapped.\n\t\t*\/\n\t\tstatic const uint16_t NotMapped = 0xfffe;\n\n\tprotected:\n\t\ttypedef uint16_t KeySequence[16];\n\n\t\t\/*!\n\t\t\tProvided in the base class as a convenience: given the lookup table of key sequences @c sequences,\n\t\t\twith @c length entries, returns the sequence for character @c character if it exists; otherwise\n\t\t\treturns @c nullptr.\n\t\t*\/\n\t\tuint16_t *table_lookup_sequence_for_character(KeySequence *sequences, size_t length, char character);\n};\n\n\/*!\n\tProvides a stateful mechanism for typing a sequence of characters. Each character is mapped to a key sequence\n\tby a character mapper. That key sequence is then replayed to a delegate.\n\n\tBeing given a delay and frequency at construction, the run_for interface can be used to produce time-based\n\ttyping. Alternatively, an owner may decline to use run_for and simply call type_next_character each time a\n\tfresh key transition is ready to be consumed.\n*\/\nclass Typer {\n\tpublic:\n\t\tclass Delegate: public KeyboardMachine::Machine {\n\t\t\tpublic:\n\t\t\t\tvirtual void typer_reset(Typer *typer) = 0;\n\t\t};\n\n\t\tTyper(const char *string, HalfCycles delay, HalfCycles frequency, std::unique_ptr<CharacterMapper> character_mapper, Delegate *delegate);\n\t\t~Typer();\n\n\t\tvoid run_for(const HalfCycles duration);\n\t\tbool type_next_character();\n\n\t\tbool is_completed();\n\n\t\tconst char BeginString = 0x02;\t\/\/ i.e. ASCII start of text\n\t\tconst char EndString = 0x03;\t\/\/ i.e. ASCII end of text\n\n\tprivate:\n\t\tchar *string_;\n\t\tsize_t string_pointer_;\n\n\t\tHalfCycles frequency_;\n\t\tHalfCycles counter_;\n\t\tint phase_;\n\n\t\tDelegate *delegate_;\n\t\tstd::unique_ptr<CharacterMapper> character_mapper_;\n\n\t\tbool try_type_next_character();\n};\n\n\/*!\n\tProvides a default base class for type recipients: classes that want to attach a single typer at a time and\n\twhich may or may not want to nominate an initial delay and typing frequency.\n*\/\nclass TypeRecipient: public Typer::Delegate {\n\tpublic:\n\t\t\/\/\/ Attaches a typer to this class that will type @c string using @c character_mapper as a source.\n\t\tvoid set_typer_for_string(const char *string, std::unique_ptr<CharacterMapper> character_mapper) {\n\t\t\ttyper_.reset(new Typer(string, get_typer_delay(), get_typer_frequency(), std::move(character_mapper), this));\n\t\t}\n\n\t\t\/*!\n\t\t\tProvided as a hook for subclasses to implement so that external callers can install a typer\n\t\t\twithout needing inside knowledge as to where the character mapper comes from.\n\t\t*\/\n\t\tvirtual void set_typer_for_string(const char *string) = 0;\n\n\t\t\/*!\n\t\t\tProvided in order to conform to that part of the Typer::Delegate interface that goes above and\n\t\t\tbeyond KeyboardMachine::Machine; responds to the end of typing by clearing all keys.\n\t\t*\/\n\t\tvoid typer_reset(Typer *typer) {\n\t\t\tclear_all_keys();\n\n\t\t\t\/\/ It's unsafe to deallocate typer right now, since it is the caller, but also it has a small\n\t\t\t\/\/ memory footprint and it's desireable not to imply that the subclass need call it any more.\n\t\t\t\/\/ So shuffle it off into a siding.\n\t\t\tprevious_typer_ = std::move(typer_);\n\t\t\ttyper_ = nullptr;\n\t\t}\n\n\tprotected:\n\t\tvirtual HalfCycles get_typer_delay() { return HalfCycles(0); }\n\t\tvirtual HalfCycles get_typer_frequency() { return HalfCycles(0); }\n\t\tstd::unique_ptr<Typer> typer_;\n\n\tprivate:\n\t\tstd::unique_ptr<Typer> previous_typer_;\n};\n\n}\n\n#endif \/* Typer_hpp *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"SkyBitmapGenerator.h\"\n\n#include <vector>\n#include <algorithm>\n\nnamespace carto {\n\n SkyBitmapGenerator::SkyBitmapGenerator(int width, int height) :\n _width(width),\n _height(height)\n {\n }\n\n SkyBitmapGenerator::~SkyBitmapGenerator() {\n }\n\n std::shared_ptr<Bitmap> SkyBitmapGenerator::generateBitmap(const Color& backgroundColor, const Color& skyColor) const {\n std::vector<unsigned char> data(_width * _height * 4);\n\n unsigned char baseValue = std::max(128, 255 - std::max(backgroundColor.getR(), std::max(backgroundColor.getG(), backgroundColor.getB())));\n Color baseColor(\n std::max(skyColor.getR(), baseValue) - baseValue,\n std::max(skyColor.getG(), baseValue) - baseValue,\n std::max(skyColor.getB(), baseValue) - baseValue,\n skyColor.getA()\n );\n\n for (int y = 0; y < _height; y++) {\n float a = std::min(1.0f, y * 1.25f \/ _height) * baseColor.getA() \/ 255.0f;\n float s = static_cast<float>(y * y) \/ ((_height + 1) * (_height + 1));\n Color color(\n static_cast<unsigned char>(((1 - s) * baseColor.getR() + s * backgroundColor.getR()) * a),\n static_cast<unsigned char>(((1 - s) * baseColor.getG() + s * backgroundColor.getG()) * a),\n static_cast<unsigned char>(((1 - s) * baseColor.getB() + s * backgroundColor.getB()) * a),\n static_cast<unsigned char>(255 * a)\n );\n\n for (int x = 0; x < _width; x++) {\n data[(y * _width + x) * 4 + 0] = color.getR();\n data[(y * _width + x) * 4 + 1] = color.getG();\n data[(y * _width + x) * 4 + 2] = color.getB();\n data[(y * _width + x) * 4 + 3] = color.getA();\n }\n }\n\n return std::make_shared<Bitmap>(data.data(), _width, _height, ColorFormat::COLOR_FORMAT_RGBA, 4 * _width);\n }\n\n}\n<commit_msg>Tweaks<commit_after>#include \"SkyBitmapGenerator.h\"\n\n#include <vector>\n#include <algorithm>\n\nnamespace carto {\n\n SkyBitmapGenerator::SkyBitmapGenerator(int width, int height) :\n _width(width),\n _height(height)\n {\n }\n\n SkyBitmapGenerator::~SkyBitmapGenerator() {\n }\n\n std::shared_ptr<Bitmap> SkyBitmapGenerator::generateBitmap(const Color& backgroundColor, const Color& skyColor) const {\n std::vector<unsigned char> data(_width * _height * 4);\n\n unsigned char baseValue = std::min(128, 255 - std::max(backgroundColor.getR(), std::max(backgroundColor.getG(), backgroundColor.getB())));\n Color baseColor(\n std::max(skyColor.getR(), baseValue) - baseValue,\n std::max(skyColor.getG(), baseValue) - baseValue,\n std::max(skyColor.getB(), baseValue) - baseValue,\n skyColor.getA()\n );\n\n for (int y = 0; y < _height; y++) {\n\t\t\tfloat v = y \/ (_height - 1.0f);\n float a = v * baseColor.getA() \/ 255.0f;\n float t = v * v;\n Color color(\n static_cast<unsigned char>(((1 - t) * baseColor.getR() + t * backgroundColor.getR()) * a),\n static_cast<unsigned char>(((1 - t) * baseColor.getG() + t * backgroundColor.getG()) * a),\n static_cast<unsigned char>(((1 - t) * baseColor.getB() + t * backgroundColor.getB()) * a),\n static_cast<unsigned char>(255 * a)\n );\n\n for (int x = 0; x < _width; x++) {\n data[(y * _width + x) * 4 + 0] = color.getR();\n data[(y * _width + x) * 4 + 1] = color.getG();\n data[(y * _width + x) * 4 + 2] = color.getB();\n data[(y * _width + x) * 4 + 3] = color.getA();\n }\n }\n\n return std::make_shared<Bitmap>(data.data(), _width, _height, ColorFormat::COLOR_FORMAT_RGBA, 4 * _width);\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Add code to replicate editing workflow from GUI to testContext in order to measure timing.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"EditorCommunicator.h\"\n\n\nResources::Status Communicator::Initialize(\n\tHWND hwnd,\n\tHINSTANCE hinstance,\n\tint w, int h,\n\tbool isPreview,\n\tstd::vector<Resources::Model*>* modelPtr\n)\n{\n\tthis->m_GraphicsHandler = new GraphicsHandler();\n\tthis->m_hwnd = hwnd;\n\tthis->m_hInstance = hinstance;\n\tthis->m_Width = w;\n\tthis->m_Height = h;\n\tthis->m_IsPreview = isPreview;\n\n\tthis->m_GraphicsHandler->Initialize(\n\t\t&this->m_hwnd,\n\t\tDirectX::XMINT2(m_Width, m_Height)\n\t);\n\tthis->m_GraphicsHandler->InitializeGrid();\n\n\tthis->m_Camera = new Camera();\n\tthis->m_Camera->Initialize(this->m_Width \/ this->m_Height);\n\tCamera* oldCam = this->m_GraphicsHandler->SetCamera(this->m_Camera);\n\tdelete oldCam;\n\toldCam = nullptr;\n\tthis->m_Camera->UpdateProjection();\n\tthis->m_Camera->Update();\n\n\tif (!isPreview)\n\t{\n\t\tthis->m_EditorInputHandler = new EditorInputHandler(\n\t\t\tthis->m_hInstance,\n\t\t\tthis->m_hwnd,\n\t\t\tthis->m_Camera,\n\t\t\tthis->m_Width,\n\t\t\tthis->m_Height,\n\t\t\tthis->m_GraphicsHandler,\n\t\t\t&this->m_currentLevel,\n\t\t\tmodelPtr\n\t\t);\n\t}\n\n\n\treturn Resources::ST_OK;\n}\n\nCommunicator::Communicator()\n{\n\n}\n\nCommunicator::~Communicator()\n{\n\n}\n\nResources::Status Communicator::Release()\n{\n\tthis->m_GraphicsHandler->Shutdown();\n\tdelete this->m_GraphicsHandler;\n\n\tif (!this->m_IsPreview)\n\t{\n\t\tdelete this->m_EditorInputHandler;\n\t}\n\treturn Resources::ST_OK;\n}\n\nResources::Status Communicator::FindModel(int modelID, std::vector<Container>* modelPtr)\n{\n\t\/\/std::unordered_map<unsigned int, std::vector<Container>>::iterator got = m_ModelMap.find(modelID);\n\t\/\/\n\t\/\/if (got == m_ModelMap.end()) { \/\/ if does not exists in memory\n\t\/\/\treturn Resources::Status::ST_RES_MISSING;\n\t\/\/}\n\t\/\/else {\n\t\/\/\tmodelPtr = &got->second;\n\t\treturn Resources::Status::ST_OK;\n\t\/\/}\n}\n\nResources::Status Communicator::GetComponent(unsigned int modelID, unsigned int instanceID, Container& container)\n{\n\treturn m_currentLevel.GetModelEntity(modelID, instanceID, container);\n}\n\nResources::Status Communicator::AddModel(unsigned int modelID, unsigned int instanceID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation)\n{\n\treturn m_currentLevel.AddModelEntity(modelID, instanceID, position, rotation);\n}\n\nResources::Status Communicator::UpdateModel(unsigned int modelID, unsigned int instanceID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation)\n{\n\treturn m_currentLevel.UpdateModel(modelID, instanceID, position, rotation);\n}\n\nResources::Status Communicator::RemoveModel(unsigned int modelID, unsigned int instanceID)\n{\n\treturn m_currentLevel.RemoveModel(modelID, instanceID);\n}\n<commit_msg>UPDATE: Initializing the editor renderer with the right flag<commit_after>#include \"EditorCommunicator.h\"\n\n\nResources::Status Communicator::Initialize(\n\tHWND hwnd,\n\tHINSTANCE hinstance,\n\tint w, int h,\n\tbool isPreview,\n\tstd::vector<Resources::Model*>* modelPtr\n)\n{\n\tthis->m_GraphicsHandler = new GraphicsHandler();\n\tthis->m_hwnd = hwnd;\n\tthis->m_hInstance = hinstance;\n\tthis->m_Width = w;\n\tthis->m_Height = h;\n\tthis->m_IsPreview = isPreview;\n\n\tthis->m_GraphicsHandler->Initialize(\n\t\t&this->m_hwnd,\n\t\tDirectX::XMINT2(m_Width, m_Height), true\n\t);\n\tthis->m_GraphicsHandler->InitializeGrid();\n\n\tthis->m_Camera = new Camera();\n\tthis->m_Camera->Initialize(this->m_Width \/ this->m_Height);\n\tCamera* oldCam = this->m_GraphicsHandler->SetCamera(this->m_Camera);\n\tdelete oldCam;\n\toldCam = nullptr;\n\tthis->m_Camera->UpdateProjection();\n\tthis->m_Camera->Update();\n\n\tif (!isPreview)\n\t{\n\t\tthis->m_EditorInputHandler = new EditorInputHandler(\n\t\t\tthis->m_hInstance,\n\t\t\tthis->m_hwnd,\n\t\t\tthis->m_Camera,\n\t\t\tthis->m_Width,\n\t\t\tthis->m_Height,\n\t\t\tthis->m_GraphicsHandler,\n\t\t\t&this->m_currentLevel,\n\t\t\tmodelPtr\n\t\t);\n\t}\n\n\n\treturn Resources::ST_OK;\n}\n\nCommunicator::Communicator()\n{\n\n}\n\nCommunicator::~Communicator()\n{\n\n}\n\nResources::Status Communicator::Release()\n{\n\tthis->m_GraphicsHandler->Shutdown();\n\tdelete this->m_GraphicsHandler;\n\n\tif (!this->m_IsPreview)\n\t{\n\t\tdelete this->m_EditorInputHandler;\n\t}\n\treturn Resources::ST_OK;\n}\n\nResources::Status Communicator::FindModel(int modelID, std::vector<Container>* modelPtr)\n{\n\t\/\/std::unordered_map<unsigned int, std::vector<Container>>::iterator got = m_ModelMap.find(modelID);\n\t\/\/\n\t\/\/if (got == m_ModelMap.end()) { \/\/ if does not exists in memory\n\t\/\/\treturn Resources::Status::ST_RES_MISSING;\n\t\/\/}\n\t\/\/else {\n\t\/\/\tmodelPtr = &got->second;\n\t\treturn Resources::Status::ST_OK;\n\t\/\/}\n}\n\nResources::Status Communicator::GetComponent(unsigned int modelID, unsigned int instanceID, Container& container)\n{\n\treturn m_currentLevel.GetModelEntity(modelID, instanceID, container);\n}\n\nResources::Status Communicator::AddModel(unsigned int modelID, unsigned int instanceID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation)\n{\n\treturn m_currentLevel.AddModelEntity(modelID, instanceID, position, rotation);\n}\n\nResources::Status Communicator::UpdateModel(unsigned int modelID, unsigned int instanceID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation)\n{\n\treturn m_currentLevel.UpdateModel(modelID, instanceID, position, rotation);\n}\n\nResources::Status Communicator::RemoveModel(unsigned int modelID, unsigned int instanceID)\n{\n\treturn m_currentLevel.RemoveModel(modelID, instanceID);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"best_stoptime.h\"\n\nnamespace navitia { namespace routing {\n\nstd::pair<const type::StopTime*, uint32_t>\nbest_stop_time(const type::JourneyPatternPoint* jpp,\n const DateTime dt,\n const type::VehicleProperties& vehicle_properties,\n const bool clockwise, bool disruption_active, const type::Data &data, bool reconstructing_path) {\n if(clockwise)\n return earliest_stop_time(jpp, dt, data, disruption_active, reconstructing_path, {}, vehicle_properties);\n else\n return tardiest_stop_time(jpp, dt, data, disruption_active, reconstructing_path, vehicle_properties);\n}\n\n\/** Which is the first valid stop_time in this range ?\n * Returns invalid_idx is none is\n *\/\nconst type::StopTime* next_valid_pick_up(type::idx_t idx, const type::idx_t end, const DateTime dt,\n const type::Data &data, bool reconstructing_path,\n const type::VehicleProperties &required_vehicle_properties,\n bool disruption_active){\n const auto date = DateTimeUtils::date(dt);\n const auto hour = DateTimeUtils::hour(dt);\n for(; idx < end; ++idx) {\n const type::StopTime* st = data.dataRaptor->st_idx_forward[idx];\n if (st->valid_end(reconstructing_path) && st->valid_hour(hour, true) &&\n ((disruption_active && st->arrival_adapted_validity_pattern->check(date)) || ((!disruption_active) && st->arrival_validity_pattern->check(date)))\n && st->vehicle_journey->accessible(required_vehicle_properties) ){\n return st;\n }\n }\n return nullptr;\n}\n\n\n\/**\n * the valid_pick_up funciton can be called 2 differents ways:\n * - with a date time => we look for the new valid stop time valid the the day of the date time and after the hour of the date time.\n * Note: if nothing found, we also look for a stop time the day after\n * - with a calendar and a hour => we look for the next valid stop time valid for the calendar and after the hour of the date time.\n *\/\nstd::pair<const type::StopTime*, DateTime>\nvalid_pick_up(const std::vector<uint32_t>::const_iterator begin, type::idx_t idx, const type::idx_t end, const DateTime dt,\n const type::Data &data, bool reconstructing_path,\n const type::VehicleProperties &vehicle_properties,\n bool disruption_active) {\n const type::StopTime* first_st = next_valid_pick_up(idx, end,\n dt, data, reconstructing_path, vehicle_properties, disruption_active);\n \/\/ If no trip was found, we look for one the day after\n if(first_st != nullptr) {\n return {first_st, dt};\n }\n idx = begin - data.dataRaptor->departure_times.begin();\n auto working_dt = DateTimeUtils::set(DateTimeUtils::date(dt)+1, 0);\n first_st = next_valid_pick_up(idx, end, working_dt,\n data, reconstructing_path, vehicle_properties,disruption_active);\n\n return {first_st, working_dt};\n}\n\nconst type::StopTime* valid_pick_up(type::idx_t idx, const type::idx_t end, const uint32_t hour,\n const std::string calendar_id,\n const type::Data& data, bool reconstructing_path,\n const type::VehicleProperties& required_vehicle_properties) {\n for(; idx < end; ++idx) {\n const type::StopTime* st = data.dataRaptor->st_idx_forward[idx];\n if (! st->valid_end(reconstructing_path)) {\n continue; \/\/we must be able to stop is this stop point\n }\n if (! st->valid_hour(hour, true)) {\n continue; \/\/the stop must be after the given hour\n }\n if (st->vehicle_journey->associated_calendars.find(calendar_id) == st->vehicle_journey->associated_calendars.end()) {\n continue; \/\/the calendar must be valid for this stop time\n }\n if (! st->vehicle_journey->accessible(required_vehicle_properties)) {\n continue; \/\/the stop time must be accessible\n }\n return st;\n }\n return nullptr;\n}\n\nconst type::StopTime* valid_drop_off(type::idx_t idx, const type::idx_t end, const DateTime dt,\n const type::Data &data, bool reconstructing_path,\n const type::VehicleProperties &required_vehicle_properties,\n bool disruption_active){\n const auto date = DateTimeUtils::date(dt);\n const auto hour = DateTimeUtils::hour(dt);\n for(; idx < end; ++idx) {\n const type::StopTime* st = data.dataRaptor->st_idx_backward[idx];\n if (st->valid_end(!reconstructing_path) && st->valid_hour(hour, false) &&\n ((disruption_active && st->arrival_adapted_validity_pattern->check(date)) || ((!disruption_active) && st->arrival_validity_pattern->check(date)))\n && st->vehicle_journey->accessible(required_vehicle_properties) ){\n return st;\n }\n }\n return nullptr;\n}\n\n\nstd::pair<const type::StopTime*, uint32_t>\nearliest_stop_time(const type::JourneyPatternPoint* jpp,\n const DateTime dt, const type::Data &data,\n bool disruption_active,\n bool reconstructing_path,\n boost::optional<const std::string> calendar_id,\n const type::VehicleProperties& vehicle_properties) {\n \/\/On cherche le plus petit stop time de la journey_pattern >= dt.hour()\n auto begin = data.dataRaptor->departure_times.begin() +\n data.dataRaptor->first_stop_time[jpp->journey_pattern->idx] +\n jpp->order * data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n auto end = begin + data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n auto it = std::lower_bound(begin, end, DateTimeUtils::hour(dt),\n bound_predicate_earliest);\n\n type::idx_t idx = it - data.dataRaptor->departure_times.begin();\n type::idx_t end_idx = (begin - data.dataRaptor->departure_times.begin()) +\n data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n\n \/\/On renvoie le premier trip valide\n std::pair<const type::StopTime*, DateTime> first_st = {nullptr, 0};\n if (! calendar_id) {\n first_st = valid_pick_up(begin, idx, end_idx, dt, data, reconstructing_path, vehicle_properties, disruption_active);\n } else {\n first_st.first = valid_pick_up(idx, end_idx, DateTimeUtils::hour(dt), *calendar_id, data, reconstructing_path, vehicle_properties);\n first_st.second = dt;\n }\n\n if(first_st.first != nullptr) {\n if(!first_st.first->is_frequency()) {\n DateTimeUtils::update(first_st.second, first_st.first->departure_time);\n } else {\n first_st.second = dt;\n const DateTime tmp_dt = f_departure_time(DateTimeUtils::hour(first_st.second), first_st.first);\n DateTimeUtils::update(first_st.second, DateTimeUtils::hour(tmp_dt));\n }\n return first_st;\n }\n return {nullptr, 0};\n}\n\n\nstd::pair<const type::StopTime*, uint32_t>\ntardiest_stop_time(const type::JourneyPatternPoint* jpp,\n const DateTime dt, const type::Data &data, bool disruption_active,\n bool reconstructing_path,\n const type::VehicleProperties& vehicle_properties) {\n \/\/On cherche le plus grand stop time de la journey_pattern <= dt.hour()\n const auto begin = data.dataRaptor->arrival_times.begin() +\n data.dataRaptor->first_stop_time[jpp->journey_pattern->idx] +\n jpp->order * data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n const auto end = begin + data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n auto it = std::lower_bound(begin, end, DateTimeUtils::hour(dt), bound_predicate_tardiest);\n\n type::idx_t idx = it - data.dataRaptor->arrival_times.begin();\n type::idx_t end_idx = (begin - data.dataRaptor->arrival_times.begin()) +\n data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n\n const type::StopTime* first_st = valid_drop_off(idx, end_idx,\n dt, data,\n reconstructing_path, vehicle_properties, disruption_active);\n\n auto working_dt = dt;\n \/\/ If no trip was found, we look for one the day before\n if(first_st == nullptr && DateTimeUtils::date(dt) > 0){\n idx = begin - data.dataRaptor->arrival_times.begin();\n working_dt = DateTimeUtils::set(DateTimeUtils::date(working_dt) - 1,\n DateTimeUtils::SECONDS_PER_DAY - 1);\n first_st = valid_drop_off(idx, end_idx, working_dt, data, reconstructing_path,\n vehicle_properties, disruption_active);\n }\n\n if(first_st != nullptr){\n if(!first_st->is_frequency()) {\n DateTimeUtils::update(working_dt, DateTimeUtils::hour(first_st->arrival_time), false);\n } else {\n working_dt = dt;\n const DateTime tmp_dt = f_arrival_time(DateTimeUtils::hour(working_dt), first_st);\n DateTimeUtils::update(working_dt, DateTimeUtils::hour(tmp_dt), false);\n }\n return std::make_pair(first_st, working_dt);\n }\n\n \/\/Cette journey_pattern ne comporte aucun trip compatible\n return std::make_pair(nullptr, 0);\n}\n}}\n\n<commit_msg>Use the departure validity pattern for pickup<commit_after>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"best_stoptime.h\"\n\nnamespace navitia { namespace routing {\n\nstd::pair<const type::StopTime*, uint32_t>\nbest_stop_time(const type::JourneyPatternPoint* jpp,\n const DateTime dt,\n const type::VehicleProperties& vehicle_properties,\n const bool clockwise, bool disruption_active, const type::Data &data, bool reconstructing_path) {\n if(clockwise)\n return earliest_stop_time(jpp, dt, data, disruption_active, reconstructing_path, {}, vehicle_properties);\n else\n return tardiest_stop_time(jpp, dt, data, disruption_active, reconstructing_path, vehicle_properties);\n}\n\n\/** Which is the first valid stop_time in this range ?\n * Returns invalid_idx is none is\n *\/\nconst type::StopTime* next_valid_pick_up(type::idx_t idx, const type::idx_t end, const DateTime dt,\n const type::Data &data, bool reconstructing_path,\n const type::VehicleProperties &required_vehicle_properties,\n bool disruption_active){\n const auto date = DateTimeUtils::date(dt);\n const auto hour = DateTimeUtils::hour(dt);\n for(; idx < end; ++idx) {\n const type::StopTime* st = data.dataRaptor->st_idx_forward[idx];\n if (st->valid_end(reconstructing_path) && st->valid_hour(hour, true) &&\n ((disruption_active && st->departure_adapted_validity_pattern->check(date)) || ((!disruption_active) && st->departure_validity_pattern->check(date)))\n && st->vehicle_journey->accessible(required_vehicle_properties) ){\n return st;\n }\n }\n return nullptr;\n}\n\n\n\/**\n * the valid_pick_up funciton can be called 2 differents ways:\n * - with a date time => we look for the new valid stop time valid the the day of the date time and after the hour of the date time.\n * Note: if nothing found, we also look for a stop time the day after\n * - with a calendar and a hour => we look for the next valid stop time valid for the calendar and after the hour of the date time.\n *\/\nstd::pair<const type::StopTime*, DateTime>\nvalid_pick_up(const std::vector<uint32_t>::const_iterator begin, type::idx_t idx, const type::idx_t end, const DateTime dt,\n const type::Data &data, bool reconstructing_path,\n const type::VehicleProperties &vehicle_properties,\n bool disruption_active) {\n const type::StopTime* first_st = next_valid_pick_up(idx, end,\n dt, data, reconstructing_path, vehicle_properties, disruption_active);\n \/\/ If no trip was found, we look for one the day after\n if(first_st != nullptr) {\n return {first_st, dt};\n }\n idx = begin - data.dataRaptor->departure_times.begin();\n auto working_dt = DateTimeUtils::set(DateTimeUtils::date(dt)+1, 0);\n first_st = next_valid_pick_up(idx, end, working_dt,\n data, reconstructing_path, vehicle_properties,disruption_active);\n\n return {first_st, working_dt};\n}\n\nconst type::StopTime* valid_pick_up(type::idx_t idx, const type::idx_t end, const uint32_t hour,\n const std::string calendar_id,\n const type::Data& data, bool reconstructing_path,\n const type::VehicleProperties& required_vehicle_properties) {\n for(; idx < end; ++idx) {\n const type::StopTime* st = data.dataRaptor->st_idx_forward[idx];\n if (! st->valid_end(reconstructing_path)) {\n continue; \/\/we must be able to stop is this stop point\n }\n if (! st->valid_hour(hour, true)) {\n continue; \/\/the stop must be after the given hour\n }\n if (st->vehicle_journey->associated_calendars.find(calendar_id) == st->vehicle_journey->associated_calendars.end()) {\n continue; \/\/the calendar must be valid for this stop time\n }\n if (! st->vehicle_journey->accessible(required_vehicle_properties)) {\n continue; \/\/the stop time must be accessible\n }\n return st;\n }\n return nullptr;\n}\n\nconst type::StopTime* valid_drop_off(type::idx_t idx, const type::idx_t end, const DateTime dt,\n const type::Data &data, bool reconstructing_path,\n const type::VehicleProperties &required_vehicle_properties,\n bool disruption_active){\n const auto date = DateTimeUtils::date(dt);\n const auto hour = DateTimeUtils::hour(dt);\n for(; idx < end; ++idx) {\n const type::StopTime* st = data.dataRaptor->st_idx_backward[idx];\n if (st->valid_end(!reconstructing_path) && st->valid_hour(hour, false) &&\n ((disruption_active && st->arrival_adapted_validity_pattern->check(date)) || ((!disruption_active) && st->arrival_validity_pattern->check(date)))\n && st->vehicle_journey->accessible(required_vehicle_properties) ){\n return st;\n }\n }\n return nullptr;\n}\n\n\nstd::pair<const type::StopTime*, uint32_t>\nearliest_stop_time(const type::JourneyPatternPoint* jpp,\n const DateTime dt, const type::Data &data,\n bool disruption_active,\n bool reconstructing_path,\n boost::optional<const std::string> calendar_id,\n const type::VehicleProperties& vehicle_properties) {\n \/\/On cherche le plus petit stop time de la journey_pattern >= dt.hour()\n auto begin = data.dataRaptor->departure_times.begin() +\n data.dataRaptor->first_stop_time[jpp->journey_pattern->idx] +\n jpp->order * data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n auto end = begin + data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n auto it = std::lower_bound(begin, end, DateTimeUtils::hour(dt),\n bound_predicate_earliest);\n\n type::idx_t idx = it - data.dataRaptor->departure_times.begin();\n type::idx_t end_idx = (begin - data.dataRaptor->departure_times.begin()) +\n data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n\n \/\/On renvoie le premier trip valide\n std::pair<const type::StopTime*, DateTime> first_st = {nullptr, 0};\n if (! calendar_id) {\n first_st = valid_pick_up(begin, idx, end_idx, dt, data, reconstructing_path, vehicle_properties, disruption_active);\n } else {\n first_st.first = valid_pick_up(idx, end_idx, DateTimeUtils::hour(dt), *calendar_id, data, reconstructing_path, vehicle_properties);\n first_st.second = dt;\n }\n\n if(first_st.first != nullptr) {\n if(!first_st.first->is_frequency()) {\n DateTimeUtils::update(first_st.second, first_st.first->departure_time);\n } else {\n first_st.second = dt;\n const DateTime tmp_dt = f_departure_time(DateTimeUtils::hour(first_st.second), first_st.first);\n DateTimeUtils::update(first_st.second, DateTimeUtils::hour(tmp_dt));\n }\n return first_st;\n }\n return {nullptr, 0};\n}\n\n\nstd::pair<const type::StopTime*, uint32_t>\ntardiest_stop_time(const type::JourneyPatternPoint* jpp,\n const DateTime dt, const type::Data &data, bool disruption_active,\n bool reconstructing_path,\n const type::VehicleProperties& vehicle_properties) {\n \/\/On cherche le plus grand stop time de la journey_pattern <= dt.hour()\n const auto begin = data.dataRaptor->arrival_times.begin() +\n data.dataRaptor->first_stop_time[jpp->journey_pattern->idx] +\n jpp->order * data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n const auto end = begin + data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n auto it = std::lower_bound(begin, end, DateTimeUtils::hour(dt), bound_predicate_tardiest);\n\n type::idx_t idx = it - data.dataRaptor->arrival_times.begin();\n type::idx_t end_idx = (begin - data.dataRaptor->arrival_times.begin()) +\n data.dataRaptor->nb_trips[jpp->journey_pattern->idx];\n\n const type::StopTime* first_st = valid_drop_off(idx, end_idx,\n dt, data,\n reconstructing_path, vehicle_properties, disruption_active);\n\n auto working_dt = dt;\n \/\/ If no trip was found, we look for one the day before\n if(first_st == nullptr && DateTimeUtils::date(dt) > 0){\n idx = begin - data.dataRaptor->arrival_times.begin();\n working_dt = DateTimeUtils::set(DateTimeUtils::date(working_dt) - 1,\n DateTimeUtils::SECONDS_PER_DAY - 1);\n first_st = valid_drop_off(idx, end_idx, working_dt, data, reconstructing_path,\n vehicle_properties, disruption_active);\n }\n\n if(first_st != nullptr){\n if(!first_st->is_frequency()) {\n DateTimeUtils::update(working_dt, DateTimeUtils::hour(first_st->arrival_time), false);\n } else {\n working_dt = dt;\n const DateTime tmp_dt = f_arrival_time(DateTimeUtils::hour(working_dt), first_st);\n DateTimeUtils::update(working_dt, DateTimeUtils::hour(tmp_dt), false);\n }\n return std::make_pair(first_st, working_dt);\n }\n\n \/\/Cette journey_pattern ne comporte aucun trip compatible\n return std::make_pair(nullptr, 0);\n}\n}}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/============================================================================\/\/\n\/\/ File: test:qcan_frame.cpp \/\/\n\/\/ Description: QCAN classes - Test QCan frame \/\/\n\/\/ \/\/\n\/\/ Copyright (C) MicroControl GmbH & Co. KG \/\/\n\/\/ 53844 Troisdorf - Germany \/\/\n\/\/ www.microcontrol.net \/\/\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\/\/ 1. Redistributions of source code must retain the above copyright \/\/\n\/\/ notice, this list of conditions, the following disclaimer and \/\/\n\/\/ the referenced file 'LICENSE'. \/\/\n\/\/ 2. 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\/\/ 3. Neither the name of MicroControl nor the names of its contributors \/\/\n\/\/ may be used to endorse or promote products derived from this software \/\/\n\/\/ without specific prior written permission. \/\/\n\/\/ \/\/\n\/\/ Provided that this notice is retained in full, this software may be \/\/\n\/\/ distributed under the terms of the GNU Lesser General Public License \/\/\n\/\/ (\"LGPL\") version 3 as distributed in the 'LICENSE' file. \/\/\n\/\/ \/\/\n\/\/============================================================================\/\/\n\n\n#include \"test_qcan_frame.hpp\"\n\n\nTestQCanFrame::TestQCanFrame()\n{\n\n}\n\n\nTestQCanFrame::~TestQCanFrame()\n{\n\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ initTestCase() \/\/\n\/\/ prepare test cases \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::initTestCase()\n{\n pclCanStdP = new QCanFrame(QCanFrame::eTYPE_CAN_STD);\n pclCanExtP = new QCanFrame(QCanFrame::eTYPE_CAN_EXT);\n pclFdStdP = new QCanFrame(QCanFrame::eTYPE_FD_STD);\n pclFdExtP = new QCanFrame(QCanFrame::eTYPE_FD_EXT);\n\n pclFrameP = new QCanFrame();\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameType() \/\/\n\/\/ check frame types \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameType()\n{\n QVERIFY(pclCanStdP->frameType() == QCanFrame::eTYPE_CAN_STD);\n QVERIFY(pclCanExtP->frameType() == QCanFrame::eTYPE_CAN_EXT);\n QVERIFY(pclFdStdP->frameType() == QCanFrame::eTYPE_FD_STD);\n QVERIFY(pclFdExtP->frameType() == QCanFrame::eTYPE_FD_EXT);\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameId() \/\/\n\/\/ check frame identifier \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameId()\n{\n uint32_t ulIdValueT;\n\n for(ulIdValueT = 0; ulIdValueT <= 0x0000FFFF; ulIdValueT++)\n {\n pclCanStdP->setStdId((uint16_t)ulIdValueT);\n pclCanExtP->setExtId(ulIdValueT);\n\n *pclFrameP = *pclCanStdP;\n if(ulIdValueT <= 0x07FF)\n {\n QVERIFY(pclCanStdP->identifier() == ulIdValueT);\n QVERIFY(pclFrameP->identifier() == ulIdValueT);\n }\n else\n {\n QVERIFY(pclCanStdP->identifier() == (ulIdValueT & 0x07FF));\n QVERIFY(pclFrameP->identifier() == (ulIdValueT & 0x07FF));\n }\n QVERIFY(pclCanExtP->identifier() == ulIdValueT);\n\n QVERIFY(pclCanStdP->isExtended() == 0);\n QVERIFY(pclFrameP->isExtended() == 0);\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameDlc() \/\/\n\/\/ check frame DLC \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameDlc()\n{\n uint8_t ubSizeT;\n \n \/\/----------------------------------------------------------------\n \/\/ Test 1: set the DLC value for classic CAN and CAN FD and\n \/\/ check the result for the dataSize() return\n \/\/\n for(ubSizeT = 0; ubSizeT < 16; ubSizeT++)\n {\n pclCanStdP->setDlc(ubSizeT);\n pclFdStdP->setDlc(ubSizeT);\n \n \/\/--------------------------------------------------------\n \/\/ check data size\n \/\/\n if(ubSizeT < 9)\n {\n QVERIFY(pclCanStdP->dataSize() == ubSizeT);\n QVERIFY(pclFdStdP->dataSize() == ubSizeT);\n }\n else\n {\n \/\/------------------------------------------------\n \/\/ copy FD frame contents and convert type to\n \/\/ classic CAN\n \/\/\n *pclFrameP = *pclFdStdP;\n pclFrameP->setFrameType(QCanFrame::eTYPE_CAN_STD);\n \n \/\/------------------------------------------------\n \/\/ make sure maximum dataSize of classic CAN is 8\n \/\/\n QVERIFY(pclFrameP->dataSize() == 8);\n QVERIFY(pclCanStdP->dataSize() == 8);\n \n \/\/------------------------------------------------\n \/\/ check data size of CAN FD \n \/\/\n switch(ubSizeT)\n {\n case 9:\n QVERIFY(pclFdStdP->dataSize() == 12);\n break;\n \n case 10:\n QVERIFY(pclFdStdP->dataSize() == 16);\n break;\n \n case 11:\n QVERIFY(pclFdStdP->dataSize() == 20);\n break;\n \n case 12:\n QVERIFY(pclFdStdP->dataSize() == 24);\n break;\n \n case 13:\n QVERIFY(pclFdStdP->dataSize() == 32);\n break;\n\n case 14:\n QVERIFY(pclFdStdP->dataSize() == 48);\n break;\n\n case 15:\n QVERIFY(pclFdStdP->dataSize() == 64);\n break;\n \n default:\n \n break;\n }\n }\n \n \/\/--------------------------------------------------------\n \/\/ check DLC\n \/\/\n if(ubSizeT < 9)\n {\n QVERIFY(pclCanStdP->dlc() == ubSizeT);\n QVERIFY(pclFdStdP->dlc() == ubSizeT);\n }\n else\n {\n QVERIFY(pclCanStdP->dlc() == 8);\n QVERIFY(pclFdStdP->dlc() == ubSizeT);\n }\n }\n\n \/\/----------------------------------------------------------------\n \/\/ Test 2: set DLC value out of range\n \/\/\n pclCanStdP->setDlc(22);\n pclFdStdP->setDlc(22);\n QVERIFY(pclCanStdP->dlc() <= 8);\n QVERIFY(pclFdStdP->dlc() <= 15);\n \n \n\n}\n\nvoid TestQCanFrame::checkFrameDataSize()\n{\n uint8_t ubSizeT;\n \n \/\/----------------------------------------------------------------\n \/\/ Test 3: set the data size value for classic CAN and CAN FD and\n \/\/ check the result for the dlc() return\n \/\/\n for(ubSizeT = 0; ubSizeT < 70; ubSizeT++)\n {\n pclCanStdP->setDataSize(ubSizeT);\n pclFdStdP->setDataSize(ubSizeT);\n \n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameData() \/\/\n\/\/ check frame data \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameData()\n{\n pclCanStdP->setDlc(4);\n pclCanStdP->setData(0, 0x12);\n pclCanStdP->setData(1, 0x34);\n pclCanStdP->setData(2, 0x56);\n pclCanStdP->setData(3, 0x78);\n \n QVERIFY(pclCanStdP->dataUInt16(0, 1) == 0x1234);\n QVERIFY(pclCanStdP->dataUInt16(1, 1) == 0x3456);\n QVERIFY(pclCanStdP->dataUInt16(2, 1) == 0x5678);\n QVERIFY(pclCanStdP->dataUInt16(3, 1) == 0x0000);\n\n QVERIFY(pclCanStdP->dataUInt32(0, 1) == 0x12345678);\n\n pclCanStdP->setDataUInt16(0, 0xAABB);\n QVERIFY(pclCanStdP->data(0) == 0xBB);\n QVERIFY(pclCanStdP->data(1) == 0xAA);\n QVERIFY(pclCanStdP->dataUInt16(0, 0) == 0xAABB);\n\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameRemote() \/\/\n\/\/ check remote frame \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameRemote()\n{\n \n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameData() \/\/\n\/\/ check frame data \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkByteArray()\n{\n QByteArray clByteArrayT;\n\n for(uint8_t ubCntT = 0; ubCntT < 9; ubCntT++)\n {\n pclCanStdP->setStdId(0x301 + ubCntT);\n pclCanStdP->setDlc(ubCntT);\n pclCanStdP->setData(0, ubCntT);\n pclCanStdP->setData(1, 0x10 + ubCntT);\n pclCanStdP->setData(2, 0x20 + ubCntT);\n pclCanStdP->setData(3, 0x30 + ubCntT);\n pclCanStdP->setData(4, 0x40 + ubCntT);\n pclCanStdP->setData(5, 0x50 + ubCntT);\n pclCanStdP->setData(6, 0x60 + ubCntT);\n pclCanStdP->setData(7, 0x70 + ubCntT);\n\n pclCanStdP->setMarker(0x223344);\n pclCanStdP->setUser(0xAB1023);\n\n clByteArrayT = pclCanStdP->toByteArray();\n\n QVERIFY(pclFrameP->fromByteArray(clByteArrayT) == true);\n\n QVERIFY(pclFrameP->identifier() == (0x301 + ubCntT));\n QVERIFY(pclFrameP->dlc() == (ubCntT));\n if(ubCntT == 4)\n {\n QVERIFY(pclFrameP->data(0) == (ubCntT));\n QVERIFY(pclFrameP->data(1) == (0x10 + ubCntT));\n QVERIFY(pclFrameP->data(2) == (0x20 + ubCntT));\n QVERIFY(pclFrameP->data(3) == (0x30 + ubCntT));\n QVERIFY(pclFrameP->data(4) == 0);\n }\n\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ cleanupTestCase() \/\/\n\/\/ cleanup test cases \/\/\n\/\/----------------------------------------------------------------------------\/\/\n\nvoid TestQCanFrame::cleanupTestCase()\n{\n delete(pclCanStdP);\n delete(pclCanExtP);\n delete(pclFdStdP);\n delete(pclFdExtP);\n\n delete(pclFrameP);\n}\n\n\n<commit_msg>Replace setStdId() and setExtId() functions<commit_after>\/\/============================================================================\/\/\n\/\/ File: test:qcan_frame.cpp \/\/\n\/\/ Description: QCAN classes - Test QCan frame \/\/\n\/\/ \/\/\n\/\/ Copyright (C) MicroControl GmbH & Co. KG \/\/\n\/\/ 53844 Troisdorf - Germany \/\/\n\/\/ www.microcontrol.net \/\/\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\/\/ 1. Redistributions of source code must retain the above copyright \/\/\n\/\/ notice, this list of conditions, the following disclaimer and \/\/\n\/\/ the referenced file 'LICENSE'. \/\/\n\/\/ 2. 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\/\/ 3. Neither the name of MicroControl nor the names of its contributors \/\/\n\/\/ may be used to endorse or promote products derived from this software \/\/\n\/\/ without specific prior written permission. \/\/\n\/\/ \/\/\n\/\/ Provided that this notice is retained in full, this software may be \/\/\n\/\/ distributed under the terms of the GNU Lesser General Public License \/\/\n\/\/ (\"LGPL\") version 3 as distributed in the 'LICENSE' file. \/\/\n\/\/ \/\/\n\/\/============================================================================\/\/\n\n\n#include \"test_qcan_frame.hpp\"\n\n\nTestQCanFrame::TestQCanFrame()\n{\n\n}\n\n\nTestQCanFrame::~TestQCanFrame()\n{\n\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ initTestCase() \/\/\n\/\/ prepare test cases \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::initTestCase()\n{\n pclCanStdP = new QCanFrame(QCanFrame::eTYPE_CAN_STD);\n pclCanExtP = new QCanFrame(QCanFrame::eTYPE_CAN_EXT);\n pclFdStdP = new QCanFrame(QCanFrame::eTYPE_FD_STD);\n pclFdExtP = new QCanFrame(QCanFrame::eTYPE_FD_EXT);\n\n pclFrameP = new QCanFrame();\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameType() \/\/\n\/\/ check frame types \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameType()\n{\n QVERIFY(pclCanStdP->frameType() == QCanFrame::eTYPE_CAN_STD);\n QVERIFY(pclCanExtP->frameType() == QCanFrame::eTYPE_CAN_EXT);\n QVERIFY(pclFdStdP->frameType() == QCanFrame::eTYPE_FD_STD);\n QVERIFY(pclFdExtP->frameType() == QCanFrame::eTYPE_FD_EXT);\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameId() \/\/\n\/\/ check frame identifier \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameId()\n{\n uint32_t ulIdValueT;\n\n for(ulIdValueT = 0; ulIdValueT <= 0x0000FFFF; ulIdValueT++)\n {\n pclCanStdP->setIdentifier(ulIdValueT);\n pclCanExtP->setIdentifier(ulIdValueT);\n\n *pclFrameP = *pclCanStdP;\n if(ulIdValueT <= 0x07FF)\n {\n QVERIFY(pclCanStdP->identifier() == ulIdValueT);\n QVERIFY(pclFrameP->identifier() == ulIdValueT);\n }\n else\n {\n QVERIFY(pclCanStdP->identifier() == (ulIdValueT & 0x07FF));\n QVERIFY(pclFrameP->identifier() == (ulIdValueT & 0x07FF));\n }\n QVERIFY(pclCanExtP->identifier() == ulIdValueT);\n\n QVERIFY(pclCanStdP->isExtended() == 0);\n QVERIFY(pclFrameP->isExtended() == 0);\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameDlc() \/\/\n\/\/ check frame DLC \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameDlc()\n{\n uint8_t ubSizeT;\n \n \/\/----------------------------------------------------------------\n \/\/ Test 1: set the DLC value for classic CAN and CAN FD and\n \/\/ check the result for the dataSize() return\n \/\/\n for(ubSizeT = 0; ubSizeT < 16; ubSizeT++)\n {\n pclCanStdP->setDlc(ubSizeT);\n pclFdStdP->setDlc(ubSizeT);\n \n \/\/--------------------------------------------------------\n \/\/ check data size\n \/\/\n if(ubSizeT < 9)\n {\n QVERIFY(pclCanStdP->dataSize() == ubSizeT);\n QVERIFY(pclFdStdP->dataSize() == ubSizeT);\n }\n else\n {\n \/\/------------------------------------------------\n \/\/ copy FD frame contents and convert type to\n \/\/ classic CAN\n \/\/\n *pclFrameP = *pclFdStdP;\n pclFrameP->setFrameType(QCanFrame::eTYPE_CAN_STD);\n \n \/\/------------------------------------------------\n \/\/ make sure maximum dataSize of classic CAN is 8\n \/\/\n QVERIFY(pclFrameP->dataSize() == 8);\n QVERIFY(pclCanStdP->dataSize() == 8);\n \n \/\/------------------------------------------------\n \/\/ check data size of CAN FD \n \/\/\n switch(ubSizeT)\n {\n case 9:\n QVERIFY(pclFdStdP->dataSize() == 12);\n break;\n \n case 10:\n QVERIFY(pclFdStdP->dataSize() == 16);\n break;\n \n case 11:\n QVERIFY(pclFdStdP->dataSize() == 20);\n break;\n \n case 12:\n QVERIFY(pclFdStdP->dataSize() == 24);\n break;\n \n case 13:\n QVERIFY(pclFdStdP->dataSize() == 32);\n break;\n\n case 14:\n QVERIFY(pclFdStdP->dataSize() == 48);\n break;\n\n case 15:\n QVERIFY(pclFdStdP->dataSize() == 64);\n break;\n \n default:\n \n break;\n }\n }\n \n \/\/--------------------------------------------------------\n \/\/ check DLC\n \/\/\n if(ubSizeT < 9)\n {\n QVERIFY(pclCanStdP->dlc() == ubSizeT);\n QVERIFY(pclFdStdP->dlc() == ubSizeT);\n }\n else\n {\n QVERIFY(pclCanStdP->dlc() == 8);\n QVERIFY(pclFdStdP->dlc() == ubSizeT);\n }\n }\n\n \/\/----------------------------------------------------------------\n \/\/ Test 2: set DLC value out of range\n \/\/\n pclCanStdP->setDlc(22);\n pclFdStdP->setDlc(22);\n QVERIFY(pclCanStdP->dlc() <= 8);\n QVERIFY(pclFdStdP->dlc() <= 15);\n \n \n\n}\n\nvoid TestQCanFrame::checkFrameDataSize()\n{\n uint8_t ubSizeT;\n \n \/\/----------------------------------------------------------------\n \/\/ Test 3: set the data size value for classic CAN and CAN FD and\n \/\/ check the result for the dlc() return\n \/\/\n for(ubSizeT = 0; ubSizeT < 70; ubSizeT++)\n {\n pclCanStdP->setDataSize(ubSizeT);\n pclFdStdP->setDataSize(ubSizeT);\n \n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameData() \/\/\n\/\/ check frame data \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameData()\n{\n pclCanStdP->setDlc(4);\n pclCanStdP->CpFrame::setData(0, 0x12);\n pclCanStdP->CpFrame::setData(1, 0x34);\n pclCanStdP->CpFrame::setData(2, 0x56);\n pclCanStdP->CpFrame::setData(3, 0x78);\n \n QVERIFY(pclCanStdP->dataUInt16(0, 1) == 0x1234);\n QVERIFY(pclCanStdP->dataUInt16(1, 1) == 0x3456);\n QVERIFY(pclCanStdP->dataUInt16(2, 1) == 0x5678);\n QVERIFY(pclCanStdP->dataUInt16(3, 1) == 0x0000);\n\n QVERIFY(pclCanStdP->dataUInt32(0, 1) == 0x12345678);\n\n pclCanStdP->setDataUInt16(0, 0xAABB);\n QVERIFY(pclCanStdP->CpFrame::data(0) == 0xBB);\n QVERIFY(pclCanStdP->CpFrame::data(1) == 0xAA);\n QVERIFY(pclCanStdP->dataUInt16(0, 0) == 0xAABB);\n\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameRemote() \/\/\n\/\/ check remote frame \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkFrameRemote()\n{\n \n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ checkFrameData() \/\/\n\/\/ check frame data \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid TestQCanFrame::checkByteArray()\n{\n QByteArray clByteArrayT;\n\n for(uint8_t ubCntT = 0; ubCntT < 9; ubCntT++)\n {\n pclCanStdP->setIdentifier(0x301 + ubCntT);\n pclCanStdP->setDlc(ubCntT);\n pclCanStdP->CpFrame::setData(0, ubCntT);\n pclCanStdP->CpFrame::setData(1, 0x10 + ubCntT);\n pclCanStdP->CpFrame::setData(2, 0x20 + ubCntT);\n pclCanStdP->CpFrame::setData(3, 0x30 + ubCntT);\n pclCanStdP->CpFrame::setData(4, 0x40 + ubCntT);\n pclCanStdP->CpFrame::setData(5, 0x50 + ubCntT);\n pclCanStdP->CpFrame::setData(6, 0x60 + ubCntT);\n pclCanStdP->CpFrame::setData(7, 0x70 + ubCntT);\n\n pclCanStdP->setMarker(0x223344);\n pclCanStdP->setUser(0xAB1023);\n\n clByteArrayT = pclCanStdP->toByteArray();\n\n QVERIFY(pclFrameP->fromByteArray(clByteArrayT) == true);\n\n QVERIFY(pclFrameP->identifier() == (0x301 + ubCntT));\n QVERIFY(pclFrameP->dlc() == (ubCntT));\n if(ubCntT == 4)\n {\n QVERIFY(pclFrameP->CpFrame::data(0) == (ubCntT));\n QVERIFY(pclFrameP->CpFrame::data(1) == (0x10 + ubCntT));\n QVERIFY(pclFrameP->CpFrame::data(2) == (0x20 + ubCntT));\n QVERIFY(pclFrameP->CpFrame::data(3) == (0x30 + ubCntT));\n QVERIFY(pclFrameP->CpFrame::data(4) == 0);\n }\n\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ cleanupTestCase() \/\/\n\/\/ cleanup test cases \/\/\n\/\/----------------------------------------------------------------------------\/\/\n\nvoid TestQCanFrame::cleanupTestCase()\n{\n delete(pclCanStdP);\n delete(pclCanExtP);\n delete(pclFdStdP);\n delete(pclFdExtP);\n\n delete(pclFrameP);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2001-2015, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"headsign_handler.h\"\n#include \"utils\/functions.h\"\n\nnamespace navitia { namespace type {\n\nvoid HeadsignHandler::change_name_and_register_as_headsign(VehicleJourney& vj,\n const std::string& new_name) {\n std::string prev_name = vj.name;\n vj.name = new_name;\n headsign_mvj[vj.name].insert(vj.meta_vj);\n update_headsign_mvj_after_remove(vj, prev_name);\n}\n\nvoid HeadsignHandler::update_headsign_mvj_after_remove(const VehicleJourney& vj,\n const std::string& removed_headsign) {\n \/\/ unregister meta-vj from headsign only if necessary\n auto has_mvj = [&] (const VehicleJourney* it_vj) {return it_vj->meta_vj == vj.meta_vj;};\n if (navitia::contains_if(get_vj_from_headsign(removed_headsign), has_mvj)) {\n return;\n }\n {\n auto it_headsign_mvj = headsign_mvj.find(removed_headsign);\n if (it_headsign_mvj == headsign_mvj.end()) {\n return;\n }\n it_headsign_mvj->second.erase(vj.meta_vj);\n if (it_headsign_mvj->second.empty()) {\n headsign_mvj.erase(it_headsign_mvj);\n }\n }\n}\n\nconst std::string& HeadsignHandler::get_headsign(const StopTime& stop_time) const{\n \/\/ if no headsign map for vj: return name\n if (!navitia::contains(headsign_changes, stop_time.vehicle_journey)) {\n return stop_time.vehicle_journey->name;\n }\n\n \/\/ otherwise use headsign change map\n const auto& map_stop_time_headsign_change =\n headsign_changes.at(stop_time.vehicle_journey);\n uint16_t order_stop_time = stop_time.order();\n\n \/\/ if no headsign change stored: return name\n if (map_stop_time_headsign_change.empty()) {\n return stop_time.vehicle_journey->name;\n }\n\n \/\/ get next change\n auto it_headsign = map_stop_time_headsign_change.upper_bound(order_stop_time);\n \/\/ if next change is the first: return name\n if(it_headsign == map_stop_time_headsign_change.begin()) {\n return stop_time.vehicle_journey->name;\n }\n\n \/\/ get previous change and return headsign\n if (it_headsign == map_stop_time_headsign_change.end()) {\n return map_stop_time_headsign_change.rbegin()->second;\n }\n return (--it_headsign)->second;\n}\n\nstd::set<std::string> HeadsignHandler::get_all_headsigns(const VehicleJourney* vj) {\n std::set<std::string> res;\n const auto& it_changes = headsign_changes.find(vj);\n if (!vj || it_changes == std::end(headsign_changes)) {\n return res;\n }\n for (const auto& change: it_changes->second) {\n \/\/ignore last headsign (vj.name) as it does not concern a stop_time\n if (change.first < vj->stop_time_list.size()) {\n res.insert(change.second);\n }\n }\n return res;\n}\n\nbool HeadsignHandler::has_headsign_or_name(const VehicleJourney& vj,\n const std::string& headsign) const {\n if (vj.name == headsign) {\n return true;\n }\n\n const auto it_vj_changes = headsign_changes.find(&vj);\n if (it_vj_changes == headsign_changes.end()) {\n return false;\n }\n\n auto has_headsign = [&] (const std::pair<uint16_t, std::string>& it_change)\n {return it_change.second == headsign;};\n if (navitia::contains_if(it_vj_changes->second, has_headsign)) {\n return true;\n }\n return false;\n}\n\nstd::vector<const VehicleJourney*>\nHeadsignHandler::get_vj_from_headsign(const std::string& headsign) const {\n std::vector<const VehicleJourney*> res;\n const auto& it_vj_set = headsign_mvj.find(headsign);\n if (it_vj_set == headsign_mvj.end()) {\n return res;\n }\n\n for (const MetaVehicleJourney* mvj: it_vj_set->second) {\n for (const auto& vect_vj: {mvj->base_vj, mvj->adapted_vj, mvj->real_time_vj}) {\n for (const VehicleJourney* vj: vect_vj) {\n if (has_headsign_or_name(*vj, headsign)) {\n res.push_back(vj);\n }\n }\n }\n }\n return res;\n}\n\nvoid HeadsignHandler::affect_headsign_to_stop_time(const StopTime& stop_time,\n const std::string& headsign) {\n const VehicleJourney* vj = stop_time.vehicle_journey;\n assert(navitia::contains_if(get_vj_from_headsign(vj->name),\n [&] (const VehicleJourney* it_vj) {return it_vj->meta_vj == vj->meta_vj;}));\n std::string prev_headsign_for_stop_time = get_headsign(stop_time);\n if (headsign == prev_headsign_for_stop_time) {\n return;\n }\n\n uint16_t order = stop_time.order();\n auto& vj_headsign_changes = headsign_changes[vj];\n \/\/ erase change if exists\n if (navitia::contains(vj_headsign_changes, order)) {\n vj_headsign_changes.erase(order);\n }\n \/\/ only if headsign erase is not enough: store change\n if (get_headsign(stop_time) != headsign) {\n vj_headsign_changes[order] = headsign;\n }\n \/\/ if next stop_time's value is prev_headsign_for_stop_time: store the change back to this\n \/\/ previous headsign. Done even if last, as we could add stop_time in the future\n if (!navitia::contains(vj_headsign_changes, order + 1)) {\n vj_headsign_changes[order + 1] = prev_headsign_for_stop_time;\n }\n \/\/ if next stop_time changed to headsign: erase mext change to merge\n else if(vj_headsign_changes[order + 1] == headsign) {\n vj_headsign_changes.erase(order + 1);\n }\n \/\/ if map for this vj is empty (all headsigns == vj.name): clean map\n if (vj_headsign_changes.empty()) {\n headsign_changes.erase(vj);\n }\n\n \/\/ register meta-vj from headsign\n headsign_mvj[headsign].insert(vj->meta_vj);\n update_headsign_mvj_after_remove(*vj, prev_headsign_for_stop_time);\n}\n\n}} \/\/namespace navitia::type\n<commit_msg>ed2nav: optimisation in headsign handler<commit_after>\/* Copyright © 2001-2015, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"headsign_handler.h\"\n#include \"utils\/functions.h\"\n\nnamespace navitia { namespace type {\n\nvoid HeadsignHandler::change_name_and_register_as_headsign(VehicleJourney& vj,\n const std::string& new_name) {\n std::string prev_name = vj.name;\n vj.name = new_name;\n headsign_mvj[vj.name].insert(vj.meta_vj);\n update_headsign_mvj_after_remove(vj, prev_name);\n}\n\nvoid HeadsignHandler::update_headsign_mvj_after_remove(const VehicleJourney& vj,\n const std::string& removed_headsign) {\n \/\/ unregister meta-vj from headsign only if necessary\n auto has_mvj = [&] (const VehicleJourney* it_vj) {return it_vj->meta_vj == vj.meta_vj;};\n if (navitia::contains_if(get_vj_from_headsign(removed_headsign), has_mvj)) {\n return;\n }\n {\n auto it_headsign_mvj = headsign_mvj.find(removed_headsign);\n if (it_headsign_mvj == headsign_mvj.end()) {\n return;\n }\n it_headsign_mvj->second.erase(vj.meta_vj);\n if (it_headsign_mvj->second.empty()) {\n headsign_mvj.erase(it_headsign_mvj);\n }\n }\n}\n\nconst std::string& HeadsignHandler::get_headsign(const StopTime& stop_time) const{\n \/\/ if no headsign map for vj: return name\n if (!navitia::contains(headsign_changes, stop_time.vehicle_journey)) {\n return stop_time.vehicle_journey->name;\n }\n\n \/\/ otherwise use headsign change map\n const auto& map_stop_time_headsign_change =\n headsign_changes.at(stop_time.vehicle_journey);\n uint16_t order_stop_time = stop_time.order();\n\n \/\/ if no headsign change stored: return name\n if (map_stop_time_headsign_change.empty()) {\n return stop_time.vehicle_journey->name;\n }\n\n \/\/ get next change\n auto it_headsign = map_stop_time_headsign_change.upper_bound(order_stop_time);\n \/\/ if next change is the first: return name\n if(it_headsign == map_stop_time_headsign_change.begin()) {\n return stop_time.vehicle_journey->name;\n }\n\n \/\/ get previous change and return headsign\n if (it_headsign == map_stop_time_headsign_change.end()) {\n return map_stop_time_headsign_change.rbegin()->second;\n }\n return (--it_headsign)->second;\n}\n\nstd::set<std::string> HeadsignHandler::get_all_headsigns(const VehicleJourney* vj) {\n std::set<std::string> res;\n const auto& it_changes = headsign_changes.find(vj);\n if (!vj || it_changes == std::end(headsign_changes)) {\n return res;\n }\n for (const auto& change: it_changes->second) {\n \/\/ignore last headsign (vj.name) as it does not concern a stop_time\n if (change.first < vj->stop_time_list.size()) {\n res.insert(change.second);\n }\n }\n return res;\n}\n\nbool HeadsignHandler::has_headsign_or_name(const VehicleJourney& vj,\n const std::string& headsign) const {\n if (vj.name == headsign) {\n return true;\n }\n\n const auto it_vj_changes = headsign_changes.find(&vj);\n if (it_vj_changes == headsign_changes.end()) {\n return false;\n }\n\n auto has_headsign = [&] (const std::pair<uint16_t, std::string>& it_change)\n {return it_change.second == headsign;};\n if (navitia::contains_if(it_vj_changes->second, has_headsign)) {\n return true;\n }\n return false;\n}\n\nstd::vector<const VehicleJourney*>\nHeadsignHandler::get_vj_from_headsign(const std::string& headsign) const {\n std::vector<const VehicleJourney*> res;\n const auto& it_vj_set = headsign_mvj.find(headsign);\n if (it_vj_set == headsign_mvj.end()) {\n return res;\n }\n\n for (const MetaVehicleJourney* mvj: it_vj_set->second) {\n for (const std::vector<navitia::type::VehicleJourney*>& vect_vj:\n {std::ref(mvj->base_vj), std::ref(mvj->adapted_vj), std::ref(mvj->real_time_vj)}) {\n for (const VehicleJourney* vj: vect_vj) {\n if (has_headsign_or_name(*vj, headsign)) {\n res.push_back(vj);\n }\n }\n }\n }\n return res;\n}\n\nvoid HeadsignHandler::affect_headsign_to_stop_time(const StopTime& stop_time,\n const std::string& headsign) {\n const VehicleJourney* vj = stop_time.vehicle_journey;\n assert(navitia::contains_if(get_vj_from_headsign(vj->name),\n [&] (const VehicleJourney* it_vj) {return it_vj->meta_vj == vj->meta_vj;}));\n std::string prev_headsign_for_stop_time = get_headsign(stop_time);\n if (headsign == prev_headsign_for_stop_time) {\n return;\n }\n\n uint16_t order = stop_time.order();\n auto& vj_headsign_changes = headsign_changes[vj];\n \/\/ erase change if exists\n if (navitia::contains(vj_headsign_changes, order)) {\n vj_headsign_changes.erase(order);\n }\n \/\/ only if headsign erase is not enough: store change\n if (get_headsign(stop_time) != headsign) {\n vj_headsign_changes[order] = headsign;\n }\n \/\/ if next stop_time's value is prev_headsign_for_stop_time: store the change back to this\n \/\/ previous headsign. Done even if last, as we could add stop_time in the future\n if (!navitia::contains(vj_headsign_changes, order + 1)) {\n vj_headsign_changes[order + 1] = prev_headsign_for_stop_time;\n }\n \/\/ if next stop_time changed to headsign: erase mext change to merge\n else if(vj_headsign_changes[order + 1] == headsign) {\n vj_headsign_changes.erase(order + 1);\n }\n \/\/ if map for this vj is empty (all headsigns == vj.name): clean map\n if (vj_headsign_changes.empty()) {\n headsign_changes.erase(vj);\n }\n\n \/\/ register meta-vj from headsign\n headsign_mvj[headsign].insert(vj->meta_vj);\n update_headsign_mvj_after_remove(*vj, prev_headsign_for_stop_time);\n}\n\n}} \/\/namespace navitia::type\n<|endoftext|>"} {"text":"<commit_before>#ifndef MANIFOLDS_FUNCTIONS_RECIRPOCAL_HH\n#define MANIFOLDS_FUNCTIONS_RECIRPOCAL_HH\n\n#include \"function.hh\"\n#include \"full_function_defs.hh\"\n\nnamespace manifolds {\ntemplate <class Numerator,\n\t class Denominator>\nstruct DivisionImpl : MultiFunction\n{\n static const bool stateless =\n and_<is_stateless<Numerator>,\n\t is_stateless<Denominator>>::value;\n\n DivisionImpl(){}\n DivisionImpl(Numerator n, Denominator d):\n n(n),d(d){}\n\n template <class ... Args>\n auto operator()(Args ... args) const\n {\n return n(args...) \/ d(args...);\n }\n\nprivate:\n Numerator n;\n Denominator d;\n};\n\nDEF_FF_TEMPLATE(Division)\n\n}\n\n#endif\n<commit_msg>Getters<commit_after>#ifndef MANIFOLDS_FUNCTIONS_RECIRPOCAL_HH\n#define MANIFOLDS_FUNCTIONS_RECIRPOCAL_HH\n\n#include \"function.hh\"\n#include \"full_function_defs.hh\"\n\nnamespace manifolds {\ntemplate <class Numerator,\n\t class Denominator>\nstruct DivisionImpl : MultiFunction\n{\n static const bool stateless =\n and_<is_stateless<Numerator>,\n\t is_stateless<Denominator>>::value;\n\n DivisionImpl(){}\n DivisionImpl(Numerator n, Denominator d):\n n(n),d(d){}\n\n template <class ... Args>\n auto operator()(Args ... args) const\n {\n return n(args...) \/ d(args...);\n }\n\n auto GetNumerator() const\n {\n return n;\n }\n\n auto GetDenominator() const\n {\n return d;\n }\n\n auto GetFunctions() const\n {\n return std::make_tuple(n,d);\n }\n\nprivate:\n Numerator n;\n Denominator d;\n};\n\nDEF_FF_TEMPLATE(Division)\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Vassil Vassilev 7\/10\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TClingCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Scope.h\"\n\nusing namespace clang;\nusing namespace cling;\n\nclass TObject;\n\n\/\/ Functions used to forward calls from code compiled with no-rtti to code \n\/\/ compiled with rtti.\nextern \"C\" {\n void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&);\n void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&); \n TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx);\n Decl* TCintWithCling__GetObjectDecl(TObject *obj);\n int TCintWithCling__AutoLoadCallback(const char* className);\n}\n\nTClingCallbacks::TClingCallbacks(cling::Interpreter* interp) \n : InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0),\n fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) {\n const Decl* D = 0;\n m_Interpreter->declare(\"namespace __ROOT_SpecialObjects{}\", &D);\n fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D));\n}\n\n\/\/pin the vtable here\nTClingCallbacks::~TClingCallbacks() {}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\nbool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {\n\n if (tryAutoloadInternal(R, S))\n return true; \/\/ happiness.\n\n \/\/ If the autoload wasn't successful try ROOT specials.\n return tryFindROOTSpecialInternal(R, S);\n}\n\nbool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) {\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclarationName Name = R.getLookupName();\n\n \/\/ Try to autoload first if autoloading is enabled\n if (IsAutoloadingEnabled()) {\n \/\/ Avoid tail chasing.\n if (fIsAutoloadingRecursively)\n return false;\n fIsAutoloadingRecursively = true;\n\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n Parser& P = const_cast<Parser&>(m_Interpreter->getParser());\n Parser::ParserCurTokRestoreRAII savedCurToken(P);\n\n bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics();\n SemaR.getDiagnostics().setSuppressAllDiagnostics();\n \n \/\/ We can't PushDeclContext, because we go up and the routine that pops \n \/\/ the DeclContext assumes that we drill down always.\n \/\/ We have to be on the global context. At that point we are in a \n \/\/ wrapper function so the parent context must be the global.\n Sema::ContextAndScopeRAII pushedSAndDC(SemaR, C.getTranslationUnitDecl(), \n SemaR.TUScope);\n\n bool lookupSuccess = false;\n if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) {\n pushedSAndDC.pop();\n cleanupRAII.pop();\n lookupSuccess = SemaR.LookupName(R, S);\n }\n\n SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags);\n\n fIsAutoloadingRecursively = false;\n \n if (lookupSuccess)\n return true;\n }\n\n}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {\n\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclContext *CurDC = SemaR.CurContext;\n DeclarationName Name = R.getLookupName();\n\n \/\/ Make sure that the failed lookup comes from the prompt.\n if(!CurDC || !CurDC->isFunctionOrMethod())\n return false;\n if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC))\n if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString()))\n return false;\n\n TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(), \n fLastLookupCtx);\n if (obj) {\n NamedDecl *ND = utils::Lookup::Named(&SemaR, Name, fROOTSpecialNamespace);\n if (ND) {\n TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(ND);\n \/\/ Since code was generated already we cannot rely on the initializer \n \/\/ of the decl in the AST, however we will update that init so that it\n \/\/ will be easier while debugging.\n VarDecl *VD = cast<VarDecl>(ND);\n CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());\n Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);\n CStyleCast->setSubExpr(newInit);\n\n \/\/ The actual update happens here, directly in memory.\n *address = obj;\n R.addDecl(ND);\n \/\/TODO: Check for same types.\n }\n else {\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n\n const Decl *TD = TCintWithCling__GetObjectDecl(obj);\n \/\/ We will declare the variable as pointer.\n QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));\n \n VarDecl *VD = VarDecl::Create(C, fROOTSpecialNamespace, \n SourceLocation(), SourceLocation(),\n Name.getAsIdentifierInfo(), QT,\n \/*TypeSourceInfo*\/0, SC_None, SC_None\n );\n \/\/ Build an initializer\n Expr* Init \n = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);\n \/\/ Register the decl in our hidden special namespace\n VD->setInit(Init);\n fROOTSpecialNamespace->addDecl(VD);\n\n cling::CompilationOptions CO;\n CO.DeclarationExtraction = 0;\n CO.ValuePrinting = CompilationOptions::VPDisabled;\n CO.ResultEvaluation = 0;\n CO.DynamicScoping = 0;\n CO.Debug = 0;\n CO.CodeGeneration = 1;\n\n cling::Transaction T(CO, \/*llvm::Module=*\/0);\n T.appendUnique(VD);\n T.setCompleted();\n\n Interpreter::CompilationResult Result = m_Interpreter->codegen(&T);\n assert(Result == Interpreter::kSuccess \n && \"Compilation should never fail!\");\n R.addDecl(VD);\n }\n return true;\n }\n\n return false;\n}\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionCommitted(const Transaction &T) {\n if (!T.size())\n return;\n if (fFirstRun) {\n \/\/ Before setting up the callbacks register what cling have seen during init.\n const cling::Transaction* T = m_Interpreter->getFirstTransaction();\n while (T) {\n if (T->getState() == cling::Transaction::kCommitted)\n TCintWithCling__UpdateListsOnCommitted(*T);\n T = T->getNext();\n }\n\n fFirstRun = false;\n }\n\n TCintWithCling__UpdateListsOnCommitted(T);\n}\n\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionUnloaded(const Transaction &T) {\n if (!T.size())\n return;\n\n TCintWithCling__UpdateListsOnUnloaded(T);\n}\n<commit_msg>Extract common code.<commit_after>\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Vassil Vassilev 7\/10\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TClingCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Scope.h\"\n\nusing namespace clang;\nusing namespace cling;\n\nclass TObject;\n\n\/\/ Functions used to forward calls from code compiled with no-rtti to code \n\/\/ compiled with rtti.\nextern \"C\" {\n void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&);\n void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&); \n TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx);\n Decl* TCintWithCling__GetObjectDecl(TObject *obj);\n int TCintWithCling__AutoLoadCallback(const char* className);\n}\n\nTClingCallbacks::TClingCallbacks(cling::Interpreter* interp) \n : InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0),\n fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) {\n const Decl* D = 0;\n m_Interpreter->declare(\"namespace __ROOT_SpecialObjects{}\", &D);\n fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D));\n}\n\n\/\/pin the vtable here\nTClingCallbacks::~TClingCallbacks() {}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\nbool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {\n\n if (tryAutoloadInternal(R, S))\n return true; \/\/ happiness.\n\n \/\/ If the autoload wasn't successful try ROOT specials.\n return tryFindROOTSpecialInternal(R, S);\n}\n\nbool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) {\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclarationName Name = R.getLookupName();\n\n \/\/ Try to autoload first if autoloading is enabled\n if (IsAutoloadingEnabled()) {\n \/\/ Avoid tail chasing.\n if (fIsAutoloadingRecursively)\n return false;\n fIsAutoloadingRecursively = true;\n\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n Parser& P = const_cast<Parser&>(m_Interpreter->getParser());\n Parser::ParserCurTokRestoreRAII savedCurToken(P);\n\n bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics();\n SemaR.getDiagnostics().setSuppressAllDiagnostics();\n \n \/\/ We can't PushDeclContext, because we go up and the routine that pops \n \/\/ the DeclContext assumes that we drill down always.\n \/\/ We have to be on the global context. At that point we are in a \n \/\/ wrapper function so the parent context must be the global.\n Sema::ContextAndScopeRAII pushedSAndDC(SemaR, C.getTranslationUnitDecl(), \n SemaR.TUScope);\n\n bool lookupSuccess = false;\n if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) {\n pushedSAndDC.pop();\n cleanupRAII.pop();\n lookupSuccess = SemaR.LookupName(R, S);\n }\n\n SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags);\n\n fIsAutoloadingRecursively = false;\n \n if (lookupSuccess)\n return true;\n }\n\n}\n\n\/\/ If cling cannot find a name it should ask ROOT before it issues an error.\n\/\/ If ROOT knows the name then it has to create a new variable with that name\n\/\/ and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).\n\/\/ For example if the interpreter is looking for h in h-Draw(), this routine\n\/\/ will create\n\/\/ namespace __ROOT_SpecialObjects {\n\/\/ THist* h = (THist*) the_address;\n\/\/ }\n\/\/\n\/\/ Later if h is called again it again won't be found by the standart lookup\n\/\/ because it is in our hidden namespace (nobody should do using namespace \n\/\/ __ROOT_SpecialObjects). It caches the variable declarations and their\n\/\/ last address. If the newly found decl with the same name (h) has different\n\/\/ address than the cached one it goes directly at the address and updates it.\n\/\/\n\/\/ returns true when declaration is found and no error should be emitted.\n\/\/\nbool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {\n\n Sema &SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n Preprocessor &PP = SemaR.getPreprocessor();\n DeclContext *CurDC = SemaR.CurContext;\n DeclarationName Name = R.getLookupName();\n\n \/\/ Make sure that the failed lookup comes from the prompt.\n if(!CurDC || !CurDC->isFunctionOrMethod())\n return false;\n if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC))\n if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString()))\n return false;\n\n TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(), \n fLastLookupCtx);\n if (obj) {\n VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, \n Name, \n fROOTSpecialNamespace));\n if (VD) {\n \/\/TODO: Check for same types.\n\n TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD);\n \/\/ Since code was generated already we cannot rely on the initializer \n \/\/ of the decl in the AST, however we will update that init so that it\n \/\/ will be easier while debugging.\n CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());\n Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);\n CStyleCast->setSubExpr(newInit);\n\n \/\/ The actual update happens here, directly in memory.\n *address = obj;\n }\n else {\n \/\/ Save state of the PP\n Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);\n\n const Decl *TD = TCintWithCling__GetObjectDecl(obj);\n \/\/ We will declare the variable as pointer.\n QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));\n \n VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(), \n SourceLocation(), Name.getAsIdentifierInfo(), QT,\n \/*TypeSourceInfo*\/0, SC_None, SC_None\n );\n \/\/ Build an initializer\n Expr* Init \n = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);\n \/\/ Register the decl in our hidden special namespace\n VD->setInit(Init);\n fROOTSpecialNamespace->addDecl(VD);\n\n cling::CompilationOptions CO;\n CO.DeclarationExtraction = 0;\n CO.ValuePrinting = CompilationOptions::VPDisabled;\n CO.ResultEvaluation = 0;\n CO.DynamicScoping = 0;\n CO.Debug = 0;\n CO.CodeGeneration = 1;\n\n cling::Transaction T(CO, \/*llvm::Module=*\/0);\n T.appendUnique(VD);\n T.setCompleted();\n\n Interpreter::CompilationResult Result = m_Interpreter->codegen(&T);\n assert(Result == Interpreter::kSuccess \n && \"Compilation should never fail!\");\n }\n assert(VD && \"Cannot be null!\");\n R.addDecl(VD);\n return true;\n }\n\n return false;\n}\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionCommitted(const Transaction &T) {\n if (!T.size())\n return;\n if (fFirstRun) {\n \/\/ Before setting up the callbacks register what cling have seen during init.\n const cling::Transaction* T = m_Interpreter->getFirstTransaction();\n while (T) {\n if (T->getState() == cling::Transaction::kCommitted)\n TCintWithCling__UpdateListsOnCommitted(*T);\n T = T->getNext();\n }\n\n fFirstRun = false;\n }\n\n TCintWithCling__UpdateListsOnCommitted(T);\n}\n\n\/\/ The callback is used to update the list of globals in ROOT.\n\/\/\nvoid TClingCallbacks::TransactionUnloaded(const Transaction &T) {\n if (!T.size())\n return;\n\n TCintWithCling__UpdateListsOnUnloaded(T);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013, Hernan Saez\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 met:\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 the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Rendering\/RenderPass.hpp\"\n#include \"Rendering\/Renderer.hpp\"\n#include \"Rendering\/RenderQueue.hpp\"\n\n#include \"SceneGraph\/Geometry.hpp\"\n\n#include \"Components\/RenderStateComponent.hpp\"\n\n#include \"Primitives\/QuadPrimitive.hpp\"\n\n#include \"Foundation\/Log.hpp\"\n#include \"Foundation\/Profiler.hpp\"\n\nusing namespace crimild;\n\nRenderPass::RenderPass( void )\n : _screen( crimild::alloc< QuadPrimitive >( 2.0f, 2.0f, VertexFormat::VF_P3_UV2, Vector2f( 0.0f, 1.0f ), Vector2f( 1.0f, -1.0f ) ) ),\n _imageEffects( crimild::alloc< SharedObjectList< ImageEffect >>() )\n{\n\n}\n\nRenderPass::~RenderPass( void )\n{\n\n}\n\nvoid RenderPass::render( RendererPtr const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera )\n{\n renderOpaqueObjects( renderer, renderQueue, camera );\n renderTranslucentObjects( renderer, renderQueue, camera );\n renderScreenObjects( renderer, renderQueue, camera );\n}\n\nvoid RenderPass::render( SharedPointer< Renderer > const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera, RenderQueue::MaterialMap const &objects )\n{\n const Matrix4f &projection = camera->getProjectionMatrix();\n const Matrix4f &view = camera->getViewMatrix();\n \n renderQueue->each( objects, [&]( MaterialPtr const &material, RenderQueue::PrimitiveMap const &primitives ) {\n auto program = material->getProgram() ? material->getProgram() : renderer->getShaderProgram( \"phong\" );\n if ( program == nullptr ) {\n Log::Error << \"No valid program for batch\" << Log::End;\n return;\n }\n \n \/\/ bind program\n renderer->bindProgram( program );\n \n \/\/ bind lights\n renderQueue->each( [&]( LightPtr const &light, int ) {\n renderer->bindLight( program, light );\n });\n \n \/\/ bind material properties\n renderer->bindMaterial( program, material );\n \n for ( auto primitiveIt : primitives ) {\n auto primitive = primitiveIt.first;\n \n \/\/ bind vertex and index buffers\n renderer->bindVertexBuffer( program, primitive->getVertexBuffer() );\n renderer->bindIndexBuffer( program, primitive->getIndexBuffer() );\n \n for ( auto geometryIt : primitiveIt.second ) {\n Matrix4f model = geometryIt.second.computeModelMatrix();\n Matrix4f normal = model;\n normal[ 12 ] = 0.0f;\n normal[ 13 ] = 0.0f;\n normal[ 14 ] = 0.0f;\n \n renderer->applyTransformations( program, projection, view, model, normal );\n renderer->drawPrimitive( program, primitive );\n }\n \n \/\/ unbind primitive buffers\n renderer->unbindVertexBuffer( program, primitive->getVertexBuffer() );\n renderer->unbindIndexBuffer( program, primitive->getIndexBuffer() );\n }\n \n \/\/ unbind material properties\n renderer->unbindMaterial( program, material );\n \n \/\/ unbind lights\n renderQueue->each( [&]( LightPtr const &light, int ) {\n renderer->unbindLight( program, light );\n });\n \n \/\/ unbind program\n renderer->unbindProgram( program );\n });\n}\n\nvoid RenderPass::render( RendererPtr const &renderer, TexturePtr const &texture, ShaderProgramPtr const &defaultProgram )\n{\n auto program = defaultProgram;\n if ( program == nullptr ) {\n program = renderer->getFallbackProgram( nullptr, nullptr, nullptr );\n if ( program == nullptr ) {\n return;\n }\n }\n \n \/\/ bind shader program first\n renderer->bindProgram( program );\n \n \/\/ bind framebuffer texture\n renderer->bindTexture( program->getStandardLocation( ShaderProgram::StandardLocation::MATERIAL_COLOR_MAP_UNIFORM ), texture );\n \n \/\/ bind vertex and index buffers\n renderer->bindVertexBuffer( program, _screen->getVertexBuffer() );\n renderer->bindIndexBuffer( program, _screen->getIndexBuffer() );\n\n Matrix4f mMatrix;\n mMatrix.makeIdentity();\n renderer->bindUniform( program->getStandardLocation( ShaderProgram::StandardLocation::MODEL_MATRIX_UNIFORM ), mMatrix );\n \n \/\/ draw primitive\n renderer->drawPrimitive( program, _screen );\n \n \/\/ unbind primitive buffers\n renderer->unbindVertexBuffer( program, _screen->getVertexBuffer() );\n renderer->unbindIndexBuffer( program, _screen->getIndexBuffer() );\n \n \/\/ unbind framebuffer texture\n renderer->unbindTexture( program->getStandardLocation( ShaderProgram::StandardLocation::MATERIAL_COLOR_MAP_UNIFORM ), texture );\n \n \/\/ lastly, unbind the shader program\n renderer->unbindProgram( program );\n}\n\nvoid RenderPass::renderOpaqueObjects( RendererPtr const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera )\n{\n CRIMILD_PROFILE( \"Render Opaque Objects\" )\n\n render( renderer, renderQueue, camera, renderQueue->getOpaqueObjects() );\n}\n\nvoid RenderPass::renderTranslucentObjects( RendererPtr const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera )\n{\n CRIMILD_PROFILE( \"Render Translucent Objects\" )\n \n render( renderer, renderQueue, camera, renderQueue->getTranslucentObjects() );\n}\n\nvoid RenderPass::renderScreenObjects( RendererPtr const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera )\n{\n CRIMILD_PROFILE( \"Render Screen Objects\" )\n \n const Matrix4f &projection = camera->getOrthographicMatrix();\n Matrix4f view;\n view.makeIdentity();\n \n renderQueue->each( renderQueue->getScreenObjects(), [&]( MaterialPtr const &material, RenderQueue::PrimitiveMap const &primitives ) {\n auto program = material->getProgram() ? material->getProgram() : renderer->getShaderProgram( \"phong\" );\n if ( program == nullptr ) {\n Log::Error << \"No valid program for batch\" << Log::End;\n return;\n }\n \n \/\/ bind program\n renderer->bindProgram( program );\n \n \/\/ bind lights\n renderQueue->each( [&]( LightPtr const &light, int ) {\n renderer->bindLight( program, light );\n });\n \n \/\/ bind material properties\n renderer->bindMaterial( program, material );\n \n for ( auto it : primitives ) {\n auto primitive = it.first;\n \n \/\/ bind vertex and index buffers\n renderer->bindVertexBuffer( program, primitive->getVertexBuffer() );\n renderer->bindIndexBuffer( program, primitive->getIndexBuffer() );\n \n for ( auto geometryIt : it.second ) {\n auto model = geometryIt.second.computeModelMatrix();\n auto normal = model;\n normal[ 12 ] = 0.0f;\n normal[ 13 ] = 0.0f;\n normal[ 14 ] = 0.0f;\n\n renderer->applyTransformations( program, projection, view, model, normal );\n renderer->drawPrimitive( program, primitive );\n }\n \n \/\/ unbind primitive buffers\n renderer->unbindVertexBuffer( program, primitive->getVertexBuffer() );\n renderer->unbindIndexBuffer( program, primitive->getIndexBuffer() );\n }\n \n \/\/ unbind material properties\n renderer->unbindMaterial( program, material );\n \n \/\/ unbind lights\n renderQueue->each( [&]( LightPtr const &light, int ) {\n renderer->unbindLight( program, light );\n });\n \n \/\/ unbind program\n renderer->unbindProgram( program );\n });\n \n}\n\n<commit_msg>RenderPass now uses right projection and view matrices for rendering<commit_after>\/*\n * Copyright (c) 2013, Hernan Saez\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 met:\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 the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Rendering\/RenderPass.hpp\"\n#include \"Rendering\/Renderer.hpp\"\n#include \"Rendering\/RenderQueue.hpp\"\n\n#include \"SceneGraph\/Geometry.hpp\"\n\n#include \"Components\/RenderStateComponent.hpp\"\n\n#include \"Primitives\/QuadPrimitive.hpp\"\n\n#include \"Foundation\/Log.hpp\"\n#include \"Foundation\/Profiler.hpp\"\n\nusing namespace crimild;\n\nRenderPass::RenderPass( void )\n : _screen( crimild::alloc< QuadPrimitive >( 2.0f, 2.0f, VertexFormat::VF_P3_UV2, Vector2f( 0.0f, 1.0f ), Vector2f( 1.0f, -1.0f ) ) ),\n _imageEffects( crimild::alloc< SharedObjectList< ImageEffect >>() )\n{\n\n}\n\nRenderPass::~RenderPass( void )\n{\n\n}\n\nvoid RenderPass::render( RendererPtr const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera )\n{\n renderOpaqueObjects( renderer, renderQueue, camera );\n renderTranslucentObjects( renderer, renderQueue, camera );\n renderScreenObjects( renderer, renderQueue, camera );\n}\n\nvoid RenderPass::render( SharedPointer< Renderer > const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera, RenderQueue::MaterialMap const &objects )\n{\n const Matrix4f &projection = renderQueue->getProjectionMatrix();\n const Matrix4f &view = renderQueue->getViewMatrix();\n \n renderQueue->each( objects, [&]( MaterialPtr const &material, RenderQueue::PrimitiveMap const &primitives ) {\n auto program = material->getProgram() ? material->getProgram() : renderer->getShaderProgram( \"phong\" );\n if ( program == nullptr ) {\n Log::Error << \"No valid program for batch\" << Log::End;\n return;\n }\n \n \/\/ bind program\n renderer->bindProgram( program );\n \n \/\/ bind lights\n renderQueue->each( [&]( LightPtr const &light, int ) {\n renderer->bindLight( program, light );\n });\n \n \/\/ bind material properties\n renderer->bindMaterial( program, material );\n \n for ( auto primitiveIt : primitives ) {\n auto primitive = primitiveIt.first;\n \n \/\/ bind vertex and index buffers\n renderer->bindVertexBuffer( program, primitive->getVertexBuffer() );\n renderer->bindIndexBuffer( program, primitive->getIndexBuffer() );\n \n for ( auto geometryIt : primitiveIt.second ) {\n Matrix4f model = geometryIt.second.computeModelMatrix();\n Matrix4f normal = model;\n normal[ 12 ] = 0.0f;\n normal[ 13 ] = 0.0f;\n normal[ 14 ] = 0.0f;\n \n renderer->applyTransformations( program, projection, view, model, normal );\n renderer->drawPrimitive( program, primitive );\n }\n \n \/\/ unbind primitive buffers\n renderer->unbindVertexBuffer( program, primitive->getVertexBuffer() );\n renderer->unbindIndexBuffer( program, primitive->getIndexBuffer() );\n }\n \n \/\/ unbind material properties\n renderer->unbindMaterial( program, material );\n \n \/\/ unbind lights\n renderQueue->each( [&]( LightPtr const &light, int ) {\n renderer->unbindLight( program, light );\n });\n \n \/\/ unbind program\n renderer->unbindProgram( program );\n });\n}\n\nvoid RenderPass::render( RendererPtr const &renderer, TexturePtr const &texture, ShaderProgramPtr const &defaultProgram )\n{\n auto program = defaultProgram;\n if ( program == nullptr ) {\n program = renderer->getFallbackProgram( nullptr, nullptr, nullptr );\n if ( program == nullptr ) {\n return;\n }\n }\n \n \/\/ bind shader program first\n renderer->bindProgram( program );\n \n \/\/ bind framebuffer texture\n renderer->bindTexture( program->getStandardLocation( ShaderProgram::StandardLocation::MATERIAL_COLOR_MAP_UNIFORM ), texture );\n \n \/\/ bind vertex and index buffers\n renderer->bindVertexBuffer( program, _screen->getVertexBuffer() );\n renderer->bindIndexBuffer( program, _screen->getIndexBuffer() );\n\n Matrix4f mMatrix;\n mMatrix.makeIdentity();\n renderer->bindUniform( program->getStandardLocation( ShaderProgram::StandardLocation::MODEL_MATRIX_UNIFORM ), mMatrix );\n \n \/\/ draw primitive\n renderer->drawPrimitive( program, _screen );\n \n \/\/ unbind primitive buffers\n renderer->unbindVertexBuffer( program, _screen->getVertexBuffer() );\n renderer->unbindIndexBuffer( program, _screen->getIndexBuffer() );\n \n \/\/ unbind framebuffer texture\n renderer->unbindTexture( program->getStandardLocation( ShaderProgram::StandardLocation::MATERIAL_COLOR_MAP_UNIFORM ), texture );\n \n \/\/ lastly, unbind the shader program\n renderer->unbindProgram( program );\n}\n\nvoid RenderPass::renderOpaqueObjects( RendererPtr const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera )\n{\n CRIMILD_PROFILE( \"Render Opaque Objects\" )\n\n render( renderer, renderQueue, camera, renderQueue->getOpaqueObjects() );\n}\n\nvoid RenderPass::renderTranslucentObjects( RendererPtr const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera )\n{\n CRIMILD_PROFILE( \"Render Translucent Objects\" )\n \n render( renderer, renderQueue, camera, renderQueue->getTranslucentObjects() );\n}\n\nvoid RenderPass::renderScreenObjects( RendererPtr const &renderer, RenderQueuePtr const &renderQueue, CameraPtr const &camera )\n{\n CRIMILD_PROFILE( \"Render Screen Objects\" )\n \n const Matrix4f &projection = camera->getOrthographicMatrix();\n Matrix4f view;\n view.makeIdentity();\n \n renderQueue->each( renderQueue->getScreenObjects(), [&]( MaterialPtr const &material, RenderQueue::PrimitiveMap const &primitives ) {\n auto program = material->getProgram() ? material->getProgram() : renderer->getShaderProgram( \"phong\" );\n if ( program == nullptr ) {\n Log::Error << \"No valid program for batch\" << Log::End;\n return;\n }\n \n \/\/ bind program\n renderer->bindProgram( program );\n \n \/\/ bind lights\n renderQueue->each( [&]( LightPtr const &light, int ) {\n renderer->bindLight( program, light );\n });\n \n \/\/ bind material properties\n renderer->bindMaterial( program, material );\n \n for ( auto it : primitives ) {\n auto primitive = it.first;\n \n \/\/ bind vertex and index buffers\n renderer->bindVertexBuffer( program, primitive->getVertexBuffer() );\n renderer->bindIndexBuffer( program, primitive->getIndexBuffer() );\n \n for ( auto geometryIt : it.second ) {\n auto model = geometryIt.second.computeModelMatrix();\n auto normal = model;\n normal[ 12 ] = 0.0f;\n normal[ 13 ] = 0.0f;\n normal[ 14 ] = 0.0f;\n\n renderer->applyTransformations( program, projection, view, model, normal );\n renderer->drawPrimitive( program, primitive );\n }\n \n \/\/ unbind primitive buffers\n renderer->unbindVertexBuffer( program, primitive->getVertexBuffer() );\n renderer->unbindIndexBuffer( program, primitive->getIndexBuffer() );\n }\n \n \/\/ unbind material properties\n renderer->unbindMaterial( program, material );\n \n \/\/ unbind lights\n renderQueue->each( [&]( LightPtr const &light, int ) {\n renderer->unbindLight( program, light );\n });\n \n \/\/ unbind program\n renderer->unbindProgram( program );\n });\n \n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix caret bounds to use min of available height and font height.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-hdd project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-hdd\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH\n#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH\n\n#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING\n\n#include <boost\/numeric\/conversion\/cast.hpp>\n\n#include <dune\/fem\/misc\/mpimanager.hh>\n\n#include <dune\/stuff\/common\/logging.hh>\n#include <dune\/stuff\/functions\/expression.hh>\n\n#include <dune\/pymor\/parameters\/base.hh>\n\n#include <dune\/gdt\/discretefunction\/default.hh>\n#include <dune\/gdt\/operators\/projections.hh>\n#include <dune\/gdt\/operators\/prolongations.hh>\n#include <dune\/gdt\/playground\/products\/elliptic-swipdg.hh>\n\n#include <dune\/hdd\/linearelliptic\/testcases\/OS2014.hh>\n#include <dune\/hdd\/linearelliptic\/testcases\/spe10.hh>\n#include <dune\/hdd\/linearelliptic\/discretizations\/block-swipdg.hh>\n#include <dune\/hdd\/linearelliptic\/estimators\/block-swipdg.hh>\n\nnamespace internal {\n\n\nclass Initializer\n{\npublic:\n Initializer(const ssize_t info_log_levels,\n const ssize_t debug_log_levels,\n const bool enable_warnings,\n const bool enable_colors,\n const std::string info_color,\n const std::string debug_color,\n const std::string warn_color)\n {\n try {\n int argc = 0;\n char** argv = new char* [0];\n Dune::Fem::MPIManager::initialize(argc, argv);\n } catch (...) {}\n DSC::TimedLogger().create(info_log_levels,\n debug_log_levels,\n enable_warnings,\n enable_colors,\n info_color,\n debug_color,\n warn_color);\n DSC::TimedLogger().get(\"OS2014.initializer\").info() << \"creating grid and problem... \" << std::endl;\n }\n}; \/\/ class Initializer\n\n\ntemplate< class TestCaseType >\nclass Example\n : Initializer\n{\npublic:\n typedef typename TestCaseType::GridType GridType;\n typedef double RangeFieldType;\n typedef Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG< GridType, RangeFieldType, 1 > DiscretizationType;\n typedef typename DiscretizationType::VectorType VectorType;\n\nprivate:\n typedef Dune::HDD::LinearElliptic::Estimators::BlockSWIPDG< typename DiscretizationType::AnsatzSpaceType,\n VectorType,\n typename DiscretizationType::ProblemType,\n GridType > Estimator;\n\npublic:\n Example(const std::string partitioning = \"[1 1 1]\",\n const DUNE_STUFF_SSIZE_T num_refinements = 0,\n const std::vector< std::string > products = {},\n const ssize_t info_log_levels = 0,\n const ssize_t debug_log_levels = -1,\n const bool enable_warnings = true,\n const bool enable_colors = true,\n const std::string info_color = DSC::TimedLogging::default_info_color(),\n const std::string debug_color = DSC::TimedLogging::default_debug_color(),\n const std::string warn_color = DSC::TimedLogging::default_warning_color())\n : Initializer(info_log_levels,\n debug_log_levels,\n enable_warnings,\n enable_colors,\n info_color,\n debug_color,\n warn_color)\n , test_case_({{\"mu\", Dune::Pymor::Parameter(\"mu\", 1)}, \/\/ <- it does not matter which parameters we give to the\n {\"mu_hat\", Dune::Pymor::Parameter(\"mu\", 1)}, \/\/ test case here, since we use test_case_.problem()\n {\"mu_bar\", Dune::Pymor::Parameter(\"mu\", 1)}, \/\/ (which is the parametric problem) anyway\n {\"mu_minimizing\", Dune::Pymor::Parameter(\"mu\", 1)}},\n partitioning,\n boost::numeric_cast< size_t >(num_refinements))\n , reference_test_case_({{\"mu\", Dune::Pymor::Parameter(\"mu\", 1)},\n {\"mu_hat\", Dune::Pymor::Parameter(\"mu\", 1)},\n {\"mu_bar\", Dune::Pymor::Parameter(\"mu\", 1)},\n {\"mu_minimizing\", Dune::Pymor::Parameter(\"mu\", 1)}},\n partitioning,\n boost::numeric_cast< size_t >(num_refinements + 1))\n , discretization_(*test_case_.reference_provider(),\n test_case_.boundary_info(),\n test_case_.problem(),\n products)\n , reference_discretization_(*reference_test_case_.reference_provider(),\n reference_test_case_.boundary_info(),\n reference_test_case_.problem(),\n products)\n {\n auto logger = DSC::TimedLogger().get(\"OS2014.example\");\n logger.info() << \"initializing discretization... \" << std::flush;\n discretization_.init();\n reference_discretization_.init();\n logger.info() << \"done (grid has \" << discretization_.grid_view().indexSet().size(0)\n << \" elements, discretization has \" << discretization_.ansatz_space()->mapper().size() << \" DoFs)\"\n << std::endl;\n } \/\/ ... OS2014Spe10Model1Example(...)\n\n const TestCaseType& test_case() const\n {\n return test_case_;\n }\n\n DiscretizationType& discretization()\n {\n return discretization_;\n }\n\n DiscretizationType* discretization_and_return_ptr() const\n {\n return new DiscretizationType(discretization_);\n }\n\n VectorType project(const std::string expression) const\n {\n using namespace Dune;\n typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;\n DiscreteFunctionType discrete_function(*discretization_.ansatz_space());\n\n typedef Stuff::Functions::Expression< typename DiscreteFunctionType::EntityType,\n typename DiscreteFunctionType::DomainFieldType,\n DiscreteFunctionType::dimDomain,\n typename DiscreteFunctionType::RangeFieldType,\n DiscreteFunctionType::dimRange > ExpressionFunctionType;\n ExpressionFunctionType func(\"x\", expression);\n\n GDT::Operators::Projection< typename DiscretizationType::GridViewType > projection(discretization_.grid_view());\n projection.apply(func, discrete_function);\n\n return discrete_function.vector();\n } \/\/ ... project(...)\n\n RangeFieldType compute_error(const VectorType& solution,\n const std::string product_type = \"\",\n const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter(),\n const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())\n {\n const std::string type = (product_type.empty() && reference_discretization_.available_products().size() == 1)\n ? reference_discretization_.available_products()[0]\n : product_type;\n \/\/ wrap solution into a discrete function\n using namespace Dune;\n typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;\n ConstDiscreteFunctionType coarse_solution(*discretization_.ansatz_space(), solution);\n \/\/ prolong to reference grid view\n typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;\n DiscreteFunctionType fine_solution(*reference_discretization_.ansatz_space());\n GDT::Operators::Prolongation< typename DiscretizationType::GridViewType >\n prolongation_operator(reference_discretization_.grid_view());\n prolongation_operator.apply(coarse_solution, fine_solution);\n \/\/ compute reference solution\n DiscreteFunctionType reference_solution(*reference_discretization_.ansatz_space());\n reference_discretization_.solve(reference_solution.vector(), mu);\n \/\/ compute error\n const auto product = reference_discretization_.get_product(type).freeze_parameter(mu_product);\n const auto difference = reference_solution.vector() - fine_solution.vector();\n return std::sqrt(product.apply2(difference, difference));\n } \/\/ ... compute_error(...)\n\n RangeFieldType compute_jump_norm(const VectorType& solution_vector,\n const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())\n {\n using namespace Dune;\n typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;\n ConstDiscreteFunctionType solution(*discretization_.ansatz_space(), solution_vector);\n const auto diffusion_factor = discretization_.problem().diffusion_factor()->with_mu(mu_product);\n const auto diffusion_tensor = discretization_.problem().diffusion_tensor()->with_mu(mu_product);\n typedef GDT::Products::EllipticSWIPDGPenaltyLocalizable\n < typename DiscretizationType::GridViewType,\n typename DiscretizationType::ProblemType::DiffusionFactorType::NonparametricType,\n ConstDiscreteFunctionType,\n ConstDiscreteFunctionType,\n RangeFieldType,\n typename DiscretizationType::ProblemType::DiffusionTensorType::NonparametricType > ProductType;\n ProductType penalty_product(discretization_.grid_view(),\n solution,\n solution,\n *diffusion_factor,\n *diffusion_tensor,\n 2);\n return std::sqrt(penalty_product.apply2());\n } \/\/ ... compute_jump_norm(...)\n\n std::vector< std::string > available_estimators() const\n {\n return Estimator::available();\n }\n\n RangeFieldType estimate(const VectorType& vector,\n const std::string type,\n const Dune::Pymor::Parameter mu_hat = Dune::Pymor::Parameter(),\n const Dune::Pymor::Parameter mu_bar = Dune::Pymor::Parameter(),\n const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter())\n {\n return Estimator::estimate(*discretization_.ansatz_space(),\n vector,\n discretization_.problem(),\n type,\n {{\"mu_hat\", mu_hat},\n {\"mu_bar\", mu_bar},\n {\"mu\", mu},\n {\"mu_minimizing\", Dune::Pymor::Parameter(\"mu\", 0.1)}});\n } \/\/ ... estimate(...)\n\npublic:\n TestCaseType test_case_;\n TestCaseType reference_test_case_;\n DiscretizationType discretization_;\n DiscretizationType reference_discretization_;\n}; \/\/ class Example\n\n\n} \/\/ namespace internal\n\n\ntemplate< class GridImp >\nclass Spe10Model1Example\n : public internal::Example< Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridImp > >\n{\n static_assert(GridImp::dimension == 2, \"Only available in 2d!\");\n typedef internal::Example< Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridImp > > BaseType;\n\npublic:\n template< class... Args >\n Spe10Model1Example(Args&& ...args)\n : BaseType(std::forward< Args >(args)...)\n {}\n}; \/\/ class Spe10Model1Example\n\n\ntemplate< class GridImp >\nclass OS2014Example\n : public internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridImp > >\n{\n static_assert(GridImp::dimension == 2, \"Only available in 2d!\");\n typedef internal::Example\n < Dune::HDD::LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridImp > > BaseType;\n\npublic:\n template< class... Args >\n OS2014Example(Args&& ...args)\n : BaseType(std::forward< Args >(args)...)\n {}\n}; \/\/ class OS2014Example\n\n\n#endif \/\/ DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH\n<commit_msg>[examples.linearelliptic.OS2014] circumvent freeze_parameter() of product<commit_after>\/\/ This file is part of the dune-hdd project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-hdd\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH\n#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH\n\n#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING\n\n#include <boost\/numeric\/conversion\/cast.hpp>\n\n#include <dune\/fem\/misc\/mpimanager.hh>\n\n#include <dune\/stuff\/common\/logging.hh>\n#include <dune\/stuff\/functions\/expression.hh>\n\n#include <dune\/pymor\/parameters\/base.hh>\n\n#include <dune\/gdt\/discretefunction\/default.hh>\n#include <dune\/gdt\/operators\/projections.hh>\n#include <dune\/gdt\/operators\/prolongations.hh>\n#include <dune\/gdt\/playground\/products\/elliptic-swipdg.hh>\n\n#include <dune\/hdd\/linearelliptic\/testcases\/OS2014.hh>\n#include <dune\/hdd\/linearelliptic\/testcases\/spe10.hh>\n#include <dune\/hdd\/linearelliptic\/discretizations\/block-swipdg.hh>\n#include <dune\/hdd\/linearelliptic\/estimators\/block-swipdg.hh>\n\nnamespace internal {\n\n\nclass Initializer\n{\npublic:\n Initializer(const ssize_t info_log_levels,\n const ssize_t debug_log_levels,\n const bool enable_warnings,\n const bool enable_colors,\n const std::string info_color,\n const std::string debug_color,\n const std::string warn_color)\n {\n try {\n int argc = 0;\n char** argv = new char* [0];\n Dune::Fem::MPIManager::initialize(argc, argv);\n } catch (...) {}\n DSC::TimedLogger().create(info_log_levels,\n debug_log_levels,\n enable_warnings,\n enable_colors,\n info_color,\n debug_color,\n warn_color);\n DSC::TimedLogger().get(\"OS2014.initializer\").info() << \"creating grid and problem... \" << std::endl;\n }\n}; \/\/ class Initializer\n\n\ntemplate< class TestCaseType >\nclass Example\n : Initializer\n{\npublic:\n typedef typename TestCaseType::GridType GridType;\n typedef double RangeFieldType;\n typedef Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG< GridType, RangeFieldType, 1 > DiscretizationType;\n typedef typename DiscretizationType::VectorType VectorType;\n\nprivate:\n typedef Dune::HDD::LinearElliptic::Estimators::BlockSWIPDG< typename DiscretizationType::AnsatzSpaceType,\n VectorType,\n typename DiscretizationType::ProblemType,\n GridType > Estimator;\n\npublic:\n Example(const std::string partitioning = \"[1 1 1]\",\n const DUNE_STUFF_SSIZE_T num_refinements = 0,\n const std::vector< std::string > products = {},\n const ssize_t info_log_levels = 0,\n const ssize_t debug_log_levels = -1,\n const bool enable_warnings = true,\n const bool enable_colors = true,\n const std::string info_color = DSC::TimedLogging::default_info_color(),\n const std::string debug_color = DSC::TimedLogging::default_debug_color(),\n const std::string warn_color = DSC::TimedLogging::default_warning_color())\n : Initializer(info_log_levels,\n debug_log_levels,\n enable_warnings,\n enable_colors,\n info_color,\n debug_color,\n warn_color)\n , test_case_({{\"mu\", Dune::Pymor::Parameter(\"mu\", 1)}, \/\/ <- it does not matter which parameters we give to the\n {\"mu_hat\", Dune::Pymor::Parameter(\"mu\", 1)}, \/\/ test case here, since we use test_case_.problem()\n {\"mu_bar\", Dune::Pymor::Parameter(\"mu\", 1)}, \/\/ (which is the parametric problem) anyway\n {\"mu_minimizing\", Dune::Pymor::Parameter(\"mu\", 1)}},\n partitioning,\n boost::numeric_cast< size_t >(num_refinements))\n , reference_test_case_({{\"mu\", Dune::Pymor::Parameter(\"mu\", 1)},\n {\"mu_hat\", Dune::Pymor::Parameter(\"mu\", 1)},\n {\"mu_bar\", Dune::Pymor::Parameter(\"mu\", 1)},\n {\"mu_minimizing\", Dune::Pymor::Parameter(\"mu\", 1)}},\n partitioning,\n boost::numeric_cast< size_t >(num_refinements + 1))\n , discretization_(*test_case_.reference_provider(),\n test_case_.boundary_info(),\n test_case_.problem(),\n products)\n , reference_discretization_(*reference_test_case_.reference_provider(),\n reference_test_case_.boundary_info(),\n reference_test_case_.problem(),\n products)\n {\n auto logger = DSC::TimedLogger().get(\"OS2014.example\");\n logger.info() << \"initializing discretization... \" << std::flush;\n discretization_.init();\n reference_discretization_.init();\n logger.info() << \"done (grid has \" << discretization_.grid_view().indexSet().size(0)\n << \" elements, discretization has \" << discretization_.ansatz_space()->mapper().size() << \" DoFs)\"\n << std::endl;\n } \/\/ ... OS2014Spe10Model1Example(...)\n\n const TestCaseType& test_case() const\n {\n return test_case_;\n }\n\n DiscretizationType& discretization()\n {\n return discretization_;\n }\n\n DiscretizationType* discretization_and_return_ptr() const\n {\n return new DiscretizationType(discretization_);\n }\n\n VectorType project(const std::string expression) const\n {\n using namespace Dune;\n typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;\n DiscreteFunctionType discrete_function(*discretization_.ansatz_space());\n\n typedef Stuff::Functions::Expression< typename DiscreteFunctionType::EntityType,\n typename DiscreteFunctionType::DomainFieldType,\n DiscreteFunctionType::dimDomain,\n typename DiscreteFunctionType::RangeFieldType,\n DiscreteFunctionType::dimRange > ExpressionFunctionType;\n ExpressionFunctionType func(\"x\", expression);\n\n GDT::Operators::Projection< typename DiscretizationType::GridViewType > projection(discretization_.grid_view());\n projection.apply(func, discrete_function);\n\n return discrete_function.vector();\n } \/\/ ... project(...)\n\n RangeFieldType compute_error(const VectorType& solution,\n const std::string product_type = \"\",\n const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter(),\n const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())\n {\n const std::string type = (product_type.empty() && reference_discretization_.available_products().size() == 1)\n ? reference_discretization_.available_products()[0]\n : product_type;\n \/\/ wrap solution into a discrete function\n using namespace Dune;\n typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;\n ConstDiscreteFunctionType coarse_solution(*discretization_.ansatz_space(), solution);\n \/\/ prolong to reference grid view\n typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;\n DiscreteFunctionType fine_solution(*reference_discretization_.ansatz_space());\n GDT::Operators::Prolongation< typename DiscretizationType::GridViewType >\n prolongation_operator(reference_discretization_.grid_view());\n prolongation_operator.apply(coarse_solution, fine_solution);\n \/\/ compute reference solution\n DiscreteFunctionType reference_solution(*reference_discretization_.ansatz_space());\n reference_discretization_.solve(reference_solution.vector(), mu);\n \/\/ compute error\n const auto difference = reference_solution.vector() - fine_solution.vector();\n const auto product = reference_discretization_.get_product(type);\n return std::sqrt(product.apply2(difference, difference, mu_product));\n } \/\/ ... compute_error(...)\n\n RangeFieldType compute_jump_norm(const VectorType& solution_vector,\n const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())\n {\n using namespace Dune;\n typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;\n ConstDiscreteFunctionType solution(*discretization_.ansatz_space(), solution_vector);\n const auto diffusion_factor = discretization_.problem().diffusion_factor()->with_mu(mu_product);\n const auto diffusion_tensor = discretization_.problem().diffusion_tensor()->with_mu(mu_product);\n typedef GDT::Products::EllipticSWIPDGPenaltyLocalizable\n < typename DiscretizationType::GridViewType,\n typename DiscretizationType::ProblemType::DiffusionFactorType::NonparametricType,\n ConstDiscreteFunctionType,\n ConstDiscreteFunctionType,\n RangeFieldType,\n typename DiscretizationType::ProblemType::DiffusionTensorType::NonparametricType > ProductType;\n ProductType penalty_product(discretization_.grid_view(),\n solution,\n solution,\n *diffusion_factor,\n *diffusion_tensor,\n 2);\n return std::sqrt(penalty_product.apply2());\n } \/\/ ... compute_jump_norm(...)\n\n std::vector< std::string > available_estimators() const\n {\n return Estimator::available();\n }\n\n RangeFieldType estimate(const VectorType& vector,\n const std::string type,\n const Dune::Pymor::Parameter mu_hat = Dune::Pymor::Parameter(),\n const Dune::Pymor::Parameter mu_bar = Dune::Pymor::Parameter(),\n const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter())\n {\n return Estimator::estimate(*discretization_.ansatz_space(),\n vector,\n discretization_.problem(),\n type,\n {{\"mu_hat\", mu_hat},\n {\"mu_bar\", mu_bar},\n {\"mu\", mu},\n {\"mu_minimizing\", Dune::Pymor::Parameter(\"mu\", 0.1)}});\n } \/\/ ... estimate(...)\n\npublic:\n TestCaseType test_case_;\n TestCaseType reference_test_case_;\n DiscretizationType discretization_;\n DiscretizationType reference_discretization_;\n}; \/\/ class Example\n\n\n} \/\/ namespace internal\n\n\ntemplate< class GridImp >\nclass Spe10Model1Example\n : public internal::Example< Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridImp > >\n{\n static_assert(GridImp::dimension == 2, \"Only available in 2d!\");\n typedef internal::Example< Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridImp > > BaseType;\n\npublic:\n template< class... Args >\n Spe10Model1Example(Args&& ...args)\n : BaseType(std::forward< Args >(args)...)\n {}\n}; \/\/ class Spe10Model1Example\n\n\ntemplate< class GridImp >\nclass OS2014Example\n : public internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridImp > >\n{\n static_assert(GridImp::dimension == 2, \"Only available in 2d!\");\n typedef internal::Example\n < Dune::HDD::LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridImp > > BaseType;\n\npublic:\n template< class... Args >\n OS2014Example(Args&& ...args)\n : BaseType(std::forward< Args >(args)...)\n {}\n}; \/\/ class OS2014Example\n\n\n#endif \/\/ DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH\n<|endoftext|>"} {"text":"<commit_before>#ifndef EXAMPLES_MPI_DOMAIN_PARTITION_HPP\n#define EXAMPLES_MPI_DOMAIN_PARTITION_HPP\n\n#include <vector>\n#include <utility>\n\n#include <boost\/foreach.hpp>\n#include <boost\/geometry.hpp>\n#include <boost\/geometry\/geometries\/adapted\/boost_array.hpp>\n#include <boost\/geometry\/geometries\/box.hpp>\n#include <boost\/geometry\/index\/rtree.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)\n\ntemplate <int NDIM>\nclass domain_partition {\n public:\n typedef boost::array<ptrdiff_t, NDIM> point;\n typedef boost::geometry::model::box<point> box;\n typedef std::pair<box, int> process;\n\n domain_partition(point lo, point hi, int num_processes) {\n split(box(lo, hi), num_processes);\n\n for(int i = 0; i < num_processes; ++i)\n rtree.insert( std::make_pair(subdomains[i], i) );\n }\n\n std::pair<int, ptrdiff_t> index(point p) const {\n namespace bgi = boost::geometry::index;\n\n BOOST_FOREACH(const process &v, rtree | bgi::adaptors::queried(bgi::intersects(p)) )\n {\n return std::make_pair(v.second, local_index(v.first, p));\n }\n\n \/\/ Unreachable:\n return std::make_pair(0, 0l);\n }\n\n size_t size(size_t process) const {\n if (process >= subdomains.size()) return 0;\n\n point lo = subdomains[process].min_corner();\n point hi = subdomains[process].max_corner();\n\n size_t v = 1;\n\n for(int i = 0; i < NDIM; ++i)\n v *= hi[i] - lo[i] + 1;\n\n return v;\n }\n\n box domain(size_t process) const {\n if (process < subdomains.size())\n return subdomains[process];\n else {\n boost::array<ptrdiff_t, 3> lo = { { 0, 0, 0} };\n boost::array<ptrdiff_t, 3> hi = { {-1, -1, -1} };\n return box(lo, hi);\n }\n }\n private:\n std::vector<box> subdomains;\n\n boost::geometry::index::rtree<\n process,\n boost::geometry::index::quadratic<16>\n > rtree;\n\n static ptrdiff_t local_index(box domain, point p) {\n point lo = domain.min_corner();\n point hi = domain.max_corner();\n\n ptrdiff_t stride = 1, idx = 0;\n for(int i = 0; i < NDIM; ++i) {\n idx += (p[i] - lo[i]) * stride;\n stride *= hi[i] - lo[i] + 1;\n }\n\n return idx;\n }\n\n void split(box domain, int np) {\n if (np == 1) {\n subdomains.push_back(domain);\n return;\n }\n\n point lo = domain.min_corner();\n point hi = domain.max_corner();\n\n \/\/ Get longest dimension of the domain\n int wd = 0;\n for(int i = 1; i < NDIM; ++i)\n if (hi[i] - lo[i] > hi[wd] - lo[wd]) wd = i;\n\n ptrdiff_t mid = lo[wd] + (hi[wd] - lo[wd]) * (np \/ 2) \/ np;\n\n box sd1 = domain;\n box sd2 = domain;\n\n sd1.max_corner()[wd] = mid;\n sd2.min_corner()[wd] = mid + 1;\n\n split(sd1, np \/ 2);\n split(sd2, np - np \/ 2);\n }\n};\n\n#endif\n<commit_msg>Fix domain_partition for dimensions other than 3<commit_after>#ifndef EXAMPLES_MPI_DOMAIN_PARTITION_HPP\n#define EXAMPLES_MPI_DOMAIN_PARTITION_HPP\n\n#include <vector>\n#include <utility>\n\n#include <boost\/foreach.hpp>\n#include <boost\/geometry.hpp>\n#include <boost\/geometry\/geometries\/adapted\/boost_array.hpp>\n#include <boost\/geometry\/geometries\/box.hpp>\n#include <boost\/geometry\/index\/rtree.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)\n\ntemplate <int NDIM>\nclass domain_partition {\n public:\n typedef boost::array<ptrdiff_t, NDIM> point;\n typedef boost::geometry::model::box<point> box;\n typedef std::pair<box, int> process;\n\n domain_partition(point lo, point hi, int num_processes) {\n split(box(lo, hi), num_processes);\n\n for(int i = 0; i < num_processes; ++i)\n rtree.insert( std::make_pair(subdomains[i], i) );\n }\n\n std::pair<int, ptrdiff_t> index(point p) const {\n namespace bgi = boost::geometry::index;\n\n BOOST_FOREACH(const process &v, rtree | bgi::adaptors::queried(bgi::intersects(p)) )\n {\n return std::make_pair(v.second, local_index(v.first, p));\n }\n\n \/\/ Unreachable:\n return std::make_pair(0, 0l);\n }\n\n size_t size(size_t process) const {\n if (process >= subdomains.size()) return 0;\n\n point lo = subdomains[process].min_corner();\n point hi = subdomains[process].max_corner();\n\n size_t v = 1;\n\n for(int i = 0; i < NDIM; ++i)\n v *= hi[i] - lo[i] + 1;\n\n return v;\n }\n\n box domain(size_t process) const {\n if (process < subdomains.size())\n return subdomains[process];\n else {\n point lo;\n point hi;\n for(int i = 0; i < NDIM; ++i) {\n lo[i] = 0;\n hi[i] = -1;\n }\n return box(lo, hi);\n }\n }\n private:\n std::vector<box> subdomains;\n\n boost::geometry::index::rtree<\n process,\n boost::geometry::index::quadratic<16>\n > rtree;\n\n static ptrdiff_t local_index(box domain, point p) {\n point lo = domain.min_corner();\n point hi = domain.max_corner();\n\n ptrdiff_t stride = 1, idx = 0;\n for(int i = 0; i < NDIM; ++i) {\n idx += (p[i] - lo[i]) * stride;\n stride *= hi[i] - lo[i] + 1;\n }\n\n return idx;\n }\n\n void split(box domain, int np) {\n if (np == 1) {\n subdomains.push_back(domain);\n return;\n }\n\n point lo = domain.min_corner();\n point hi = domain.max_corner();\n\n \/\/ Get longest dimension of the domain\n int wd = 0;\n for(int i = 1; i < NDIM; ++i)\n if (hi[i] - lo[i] > hi[wd] - lo[wd]) wd = i;\n\n ptrdiff_t mid = lo[wd] + (hi[wd] - lo[wd]) * (np \/ 2) \/ np;\n\n box sd1 = domain;\n box sd2 = domain;\n\n sd1.max_corner()[wd] = mid;\n sd2.min_corner()[wd] = mid + 1;\n\n split(sd1, np \/ 2);\n split(sd2, np - np \/ 2);\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* OpenSceneGraph example, osghangglide.\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 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\n\/\/ #include <math.h>\n\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osg\/Texture2D>\n#include <osg\/TexEnv>\n#include <osg\/StateSet>\n\n#include <osgDB\/ReadFile>\n\n#include \"terrain_coords.h\"\n#include \"terrain_texcoords.h\"\n\nusing namespace osg;\n\nvoid getDatabaseCenterRadius( float dbcenter[3], float *dbradius )\n{\n int i;\n double n=0.0;\n double center[3] = { 0.0f, 0.0f, 0.0f };\n float cnt;\n\n cnt = 39 * 38;\n for( i = 0; i < cnt; i++ )\n {\n center[0] += (double)vertex[i][0];\n center[1] += (double)vertex[i][1];\n center[2] += (double)vertex[i][2];\n\n n = n + 1.0;\n }\n\n center[0] \/= n;\n center[1] \/= n;\n center[2] \/= n;\n\n float r = 0.0;\n\n \/\/ for( i = 0; i < sizeof( vertex ) \/ (sizeof( float[3] )); i++ )\n for( i = 0; i < cnt; i++ )\n {\n double d = sqrt(\n (((double)vertex[i][0] - center[0]) * ((double)vertex[i][0] - center[0])) +\n (((double)vertex[i][1] - center[1]) * ((double)vertex[i][1] - center[1])) +\n (((double)vertex[i][2] - center[2]) * ((double)vertex[i][2] - center[2])) );\n\n if( d > (double)r ) r = (float)d;\n\n }\n\n *dbradius = r;\n dbcenter[0] = (float)center[0];\n dbcenter[1] = (float)center[1];\n dbcenter[2] = (float)center[2];\n\n int index = 19 * 39 + 19;\n dbcenter[0] = vertex[index][0] - 0.15;\n dbcenter[1] = vertex[index][1];\n dbcenter[2] = vertex[index][2] + 0.35;\n\n}\n\n\nNode *makeTerrain( void )\n{\n int m, n;\n int i, j;\n float dbcenter[3];\n float dbradius;\n\n getDatabaseCenterRadius( dbcenter, &dbradius );\n\n m = (sizeof( vertex ) \/(sizeof( float[3])))\/39;\n n = 39;\n\n Vec3Array& v = *(new Vec3Array(m*n));\n Vec2Array& t = *(new Vec2Array(m*n));\n Vec4Array& col = *(new Vec4Array(1));\n\n col[0][0] = col[0][1] = col[0][2] = col[0][3] = 1.0f;\n\n for( i = 0; i < m * n; i++ )\n {\n v[i][0] = vertex[i][0] - dbcenter[0];\n v[i][1] = vertex[i][1] - dbcenter[1];\n v[i][2] = vertex[i][2];\n\n t[i][0] = texcoord[i][0] + 0.025;\n t[i][1] = texcoord[i][1];\n }\n\n Geometry *geom = new Geometry;\n\n geom->setVertexArray( &v );\n geom->setTexCoordArray( 0, &t );\n\n geom->setColorArray( &col, Array::BIND_OVERALL );\n\n for( i = 0; i < m-2; i++ )\n {\n DrawElementsUShort* elements = new DrawElementsUShort(PrimitiveSet::TRIANGLE_STRIP);\n elements->reserve(39*2);\n for( j = 0; j < n; j++ )\n {\n elements->push_back((i+0)*n+j);\n elements->push_back((i+1)*n+j);\n }\n geom->addPrimitiveSet(elements);\n }\n\n\n Texture2D *tex = new Texture2D;\n\n tex->setImage(osgDB::readImageFile(\"Images\/lz.rgb\"));\n\n StateSet *dstate = new StateSet;\n dstate->setMode( GL_LIGHTING, StateAttribute::OFF );\n dstate->setTextureAttributeAndModes(0, tex, StateAttribute::ON );\n dstate->setTextureAttribute(0, new TexEnv );\n\n geom->setStateSet( dstate );\n\n Geode *geode = new Geode;\n geode->addDrawable( geom );\n\n return geode;\n}\n<commit_msg>Fixed warning<commit_after>\/* OpenSceneGraph example, osghangglide.\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 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\n\/\/ #include <math.h>\n\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osg\/Texture2D>\n#include <osg\/TexEnv>\n#include <osg\/StateSet>\n\n#include <osgDB\/ReadFile>\n\n#include \"terrain_coords.h\"\n#include \"terrain_texcoords.h\"\n\nusing namespace osg;\n\nvoid getDatabaseCenterRadius( float dbcenter[3], float *dbradius )\n{\n int i;\n double n=0.0;\n double center[3] = { 0.0f, 0.0f, 0.0f };\n float cnt;\n\n cnt = 39 * 38;\n for( i = 0; i < cnt; i++ )\n {\n center[0] += (double)vertex[i][0];\n center[1] += (double)vertex[i][1];\n center[2] += (double)vertex[i][2];\n\n n = n + 1.0;\n }\n\n center[0] \/= n;\n center[1] \/= n;\n center[2] \/= n;\n\n float r = 0.0;\n\n \/\/ for( i = 0; i < sizeof( vertex ) \/ (sizeof( float[3] )); i++ )\n for( i = 0; i < cnt; i++ )\n {\n double d = sqrt(\n (((double)vertex[i][0] - center[0]) * ((double)vertex[i][0] - center[0])) +\n (((double)vertex[i][1] - center[1]) * ((double)vertex[i][1] - center[1])) +\n (((double)vertex[i][2] - center[2]) * ((double)vertex[i][2] - center[2])) );\n\n if( d > (double)r ) r = (float)d;\n\n }\n\n *dbradius = r;\n dbcenter[0] = (float)center[0];\n dbcenter[1] = (float)center[1];\n dbcenter[2] = (float)center[2];\n\n int index = 19 * 39 + 19;\n dbcenter[0] = vertex[index][0] - 0.15;\n dbcenter[1] = vertex[index][1];\n dbcenter[2] = vertex[index][2] + 0.35;\n\n}\n\n\nNode *makeTerrain( void )\n{\n int m, n;\n int i, j;\n float dbcenter[3];\n float dbradius;\n\n getDatabaseCenterRadius( dbcenter, &dbradius );\n\n m = (sizeof( vertex ) \/(sizeof( float[3])))\/39;\n n = 39;\n\n Vec3Array& v = *(new Vec3Array(m*n));\n Vec2Array& t = *(new Vec2Array(m*n));\n Vec4Array& col = *(new Vec4Array(1));\n\n col[0][0] = col[0][1] = col[0][2] = col[0][3] = 1.0f;\n\n for( i = 0; i < m * n; i++ )\n {\n float* vc = vertex[i];\n v[i][0] = vc[0] - dbcenter[0];\n v[i][1] = vc[1] - dbcenter[1];\n v[i][2] = vc[2];\n\n float* tc = texcoord[i];\n t[i][0] = tc[0];\n t[i][1] = tc[1];\n }\n\n Geometry *geom = new Geometry;\n\n geom->setVertexArray( &v );\n geom->setTexCoordArray( 0, &t );\n\n geom->setColorArray( &col, Array::BIND_OVERALL );\n\n for( i = 0; i < m-2; i++ )\n {\n DrawElementsUShort* elements = new DrawElementsUShort(PrimitiveSet::TRIANGLE_STRIP);\n elements->reserve(39*2);\n for( j = 0; j < n; j++ )\n {\n elements->push_back((i+0)*n+j);\n elements->push_back((i+1)*n+j);\n }\n geom->addPrimitiveSet(elements);\n }\n\n\n Texture2D *tex = new Texture2D;\n\n tex->setImage(osgDB::readImageFile(\"Images\/lz.rgb\"));\n\n StateSet *dstate = new StateSet;\n dstate->setMode( GL_LIGHTING, StateAttribute::OFF );\n dstate->setTextureAttributeAndModes(0, tex, StateAttribute::ON );\n dstate->setTextureAttribute(0, new TexEnv );\n\n geom->setStateSet( dstate );\n\n Geode *geode = new Geode;\n geode->addDrawable( geom );\n\n return geode;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.6.342); FILE MERGED 2005\/09\/05 17:23:06 rt 1.6.342.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <cmath>\n#include <boost\/shared_ptr.hpp>\n#include <lcm\/lcm-cpp.hpp>\n#include \"lcmtypes\/drc_lcmtypes.hpp\"\n#include <ConciseArgs>\n#include <string>\n#include <deque>\nusing namespace std;\n\n\nclass App{\n public:\n App(boost::shared_ptr<lcm::LCM> &lcm_, bool is_left);\n \n ~App(){\n }\n \n \n private:\n boost::shared_ptr<lcm::LCM> lcm_;\n bool is_left;\n \n std::vector < float > command_pos_;\n std::vector<float> sensed_pos_;\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void commandHandler(const lcm::ReceiveBuffer* rbuf, \n const std::string& channel, const drc::joint_command_t* msg); \n void stateHandler(const lcm::ReceiveBuffer* rbuf, \n const std::string& channel, const drc::hand_state_t* msg); \n}; \n\nApp::App(boost::shared_ptr<lcm::LCM> &lcm_, bool is_left):\n lcm_(lcm_), is_left(is_left){\n \n \n lcm_->subscribe(is_left ? \"L_HAND_JOINT_COMMANDS\":\"R_HAND_JOINT_COMMANDS\", \n &App::commandHandler, this); \n\n lcm_->subscribe(is_left ? \"SANDIA_LEFT_STATE\":\"SANDIA_RIGHT_STATE\", \n &App::stateHandler, this); \n \n}\n\nvoid App::commandHandler(const lcm::ReceiveBuffer* rbuf, \n const std::string& channel, const drc::joint_command_t* msg){\n \n std::cout << \"got command\\n\";\n std::vector<float> v_float( msg->position.begin(), msg->position.end()); \n command_pos_ = v_float; \n\n \n}\n\n\nvoid App::stateHandler(const lcm::ReceiveBuffer* rbuf, \n const std::string& channel, const drc::hand_state_t* msg){\n \n sensed_pos_ = msg->joint_position;\n std::cout << \"got state\\n\";\n \n \n if (command_pos_.size() != sensed_pos_.size()){\n \/\/std::cout << \"sensed and commanded don't match\\n\";\n return; \n }\n \n std::vector <float> diffs;\n for (size_t i=0; i < command_pos_.size() ; i++){\n diffs.push_back( fabs( command_pos_[i] - sensed_pos_[i] ) );\n }\n std::vector <float> finger_diffs(4,0.0);\n finger_diffs[0] = diffs[0] + diffs[1] + diffs[2];\n finger_diffs[1] = diffs[3] + diffs[4] + diffs[5];\n finger_diffs[2] = diffs[6] + diffs[7] + diffs[8];\n finger_diffs[3] = diffs[9] + diffs[10] + diffs[11];\n \n \n std::cout << diffs[9] << \" \" << diffs[10] << \" \" << diffs[11] << \"\\n\";\n \n if (finger_diffs[3] > 0.2){\n std::cout << finger_diffs[3] << \" BIG==================\\n\"; \n }else{\n std::cout << finger_diffs[3] << \"SMALL\\n\"; \n }\n \n \n}\n\n\n \nint main(int argc, char *argv[]){\n bool lhand=false, rhand=false;\n ConciseArgs opt(argc, (char**)argv);\n opt.add(rhand, \"r\", \"right\",\"Process right hand message\");\n opt.add(lhand, \"l\", \"left\",\"Process left hand message\");\n \n opt.parse();\n if(rhand && lhand){\n printf(\"Only one hand at a time.\\n\");\n return 1;\n }\n if(!rhand && !lhand){\n printf(\"Please specify a hand. Type -h for usage.\\n\");\n return 1;\n }\n \n boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM() );\n if(!lcm->good())\n return 1; \n \n App app(lcm, lhand);\n while(0 == lcm->handle());\n return 0;\n}\n<commit_msg>map raw diff values to 0 to 1 with hand-tuned logistic function. not yet published to LCM<commit_after>#include <stdio.h>\n#include <cmath>\n#include <boost\/shared_ptr.hpp>\n#include <lcm\/lcm-cpp.hpp>\n#include \"lcmtypes\/drc_lcmtypes.hpp\"\n#include <ConciseArgs>\n#include <string>\n#include <deque>\nusing namespace std;\n\n\nclass App{\n public:\n App(boost::shared_ptr<lcm::LCM> &lcm_, bool is_left);\n \n ~App(){\n }\n \n \n private:\n boost::shared_ptr<lcm::LCM> lcm_;\n bool is_left;\n \n std::vector < float > command_pos_;\n std::vector<float> sensed_pos_;\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void commandHandler(const lcm::ReceiveBuffer* rbuf, \n const std::string& channel, const drc::joint_command_t* msg); \n void stateHandler(const lcm::ReceiveBuffer* rbuf, \n const std::string& channel, const drc::hand_state_t* msg); \n}; \n\nApp::App(boost::shared_ptr<lcm::LCM> &lcm_, bool is_left):\n lcm_(lcm_), is_left(is_left){\n \n \n lcm_->subscribe(is_left ? \"L_HAND_JOINT_COMMANDS\":\"R_HAND_JOINT_COMMANDS\", \n &App::commandHandler, this); \n\n lcm_->subscribe(is_left ? \"SANDIA_LEFT_STATE\":\"SANDIA_RIGHT_STATE\", \n &App::stateHandler, this); \n \n}\n\nvoid App::commandHandler(const lcm::ReceiveBuffer* rbuf, \n const std::string& channel, const drc::joint_command_t* msg){\n \n std::cout << \"got command\\n\";\n std::vector<float> v_float( msg->position.begin(), msg->position.end()); \n command_pos_ = v_float; \n\n \n}\n\/\/ logistic function F(x)=1\/(1+e^{-b_1 (x-b_0)})\nfloat logit(float x, float b0=0, float b1=1){\n return 1.0\/(1.0+exp(-(b1*(x-b0))));\n}\n\nvoid App::stateHandler(const lcm::ReceiveBuffer* rbuf, \n const std::string& channel, const drc::hand_state_t* msg){\n \n sensed_pos_ = msg->joint_position;\n std::cout << \"got state\\n\";\n \n \n if (command_pos_.size() != sensed_pos_.size()){\n \/\/std::cout << \"sensed and commanded don't match\\n\";\n return; \n }\n \n std::vector <float> diffs;\n for (size_t i=0; i < command_pos_.size() ; i++){\n diffs.push_back( fabs( command_pos_[i] - sensed_pos_[i] ) );\n }\n std::vector <float> finger_diffs(4,0.0);\n finger_diffs[0] = diffs[0] + diffs[1] + diffs[2];\n finger_diffs[1] = diffs[3] + diffs[4] + diffs[5];\n finger_diffs[2] = diffs[6] + diffs[7] + diffs[8];\n finger_diffs[3] = diffs[9] + diffs[10] + diffs[11];\n \n \n std::cout << diffs[9] << \" \" << diffs[10] << \" \" << diffs[11] << \"\\n\";\n \n if (finger_diffs[3] > 0.2){\n std::cout << finger_diffs[3] << \" BIG==================\\n\"; \n }else{\n std::cout << finger_diffs[3] << \"SMALL\\n\"; \n }\n \n std::cout << \"logit(finger_diffs[0])=\" << logit(finger_diffs[0],0.1,60) << endl;\n std::cout << \"logit(finger_diffs[1])=\" << logit(finger_diffs[1],0.1,60) << endl;\n std::cout << \"logit(finger_diffs[2])=\" << logit(finger_diffs[2],0.1,60) << endl;\n std::cout << \"logit(finger_diffs[3])=\" << logit(finger_diffs[3],0.1,60) << endl;\n \n}\n\n\n \nint main(int argc, char *argv[]){\n bool lhand=false, rhand=false;\n ConciseArgs opt(argc, (char**)argv);\n opt.add(rhand, \"r\", \"right\",\"Process right hand message\");\n opt.add(lhand, \"l\", \"left\",\"Process left hand message\");\n \n opt.parse();\n if(rhand && lhand){\n printf(\"Only one hand at a time.\\n\");\n return 1;\n }\n if(!rhand && !lhand){\n printf(\"Please specify a hand. Type -h for usage.\\n\");\n return 1;\n }\n \n boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM() );\n if(!lcm->good())\n return 1; \n \n App app(lcm, lhand);\n while(0 == lcm->handle());\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"tray.h\"\r\n\r\n#include <QMessageBox>\r\n#include <QSharedMemory>\r\n#include <QtGui>\r\n#include <QRegExp>\r\n#include <QDesktopServices>\r\n#include <QUrl>\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n\r\n \/\/ disable Maximize functionality\r\n setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowMaximizeButtonHint);\r\n \/\/setFixedWidth(600);\r\n \/\/setFixedHeight(270);\r\n\r\n \/\/ overrides the window title defined in mainwindow.ui\r\n setWindowTitle(APP_NAME_AND_VERSION);\r\n\r\n createActions();\r\n\r\n createTrayIcon();\r\n\r\n \/\/ fetch version numbers from the daemons and set label text\r\n ui->label_Nginx_Version->setText( getNginxVersion() );\r\n ui->label_PHP_Version->setText( getPHPVersion() );\r\n ui->label_MariaDb_Version->setText( getMariaVersion() );\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::createTrayIcon()\r\n{\r\n \/\/ The tray icon is an instance of the QSystemTrayIcon class.\r\n \/\/ To check whether a system tray is present on the user's desktop,\r\n \/\/ we call the static QSystemTrayIcon::isSystemTrayAvailable() function.\r\n if (false == QSystemTrayIcon::isSystemTrayAvailable())\r\n {\r\n QMessageBox::critical(0, APP_NAME, tr(\"You don't have a system tray.\"));\r\n \/\/return 1;\r\n }\r\n else\r\n {\r\n \/\/ instantiate and attach the tray icon to the system tray\r\n trayIcon = new Tray(qApp);\r\n trayIcon->show();\r\n\r\n \/\/ handle clicks on the icon\r\n connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\r\n this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));\r\n }\r\n}\r\n\r\nvoid MainWindow::createActions()\r\n {\r\n minimizeAction = new QAction(tr(\"Mi&nimize\"), this);\r\n connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));\r\n\r\n restoreAction = new QAction(tr(\"&Restore\"), this);\r\n connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));\r\n\r\n quitAction = new QAction(tr(\"&Quit\"), this);\r\n \/\/ qApp is global pointer to QApplication\r\n connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\r\n\r\n \/\/ PushButtons:: Website, ReportBug, Donate\r\n connect(ui->pushButton_Website, SIGNAL(clicked()), this, SLOT(goToWebsite()));\r\n connect(ui->pushButton_GoogleGroup, SIGNAL(clicked()), this, SLOT(goToGoogleGroup()));\r\n connect(ui->pushButton_ReportBug, SIGNAL(clicked()), this, SLOT(goToReportIssue()));\r\n connect(ui->pushButton_Donate, SIGNAL(clicked()), this, SLOT(goToDonate()));\r\n\r\n \/\/ PushButtons: Configuration, Help, About, Close\r\n connect(ui->pushButton_Configuration, SIGNAL(clicked()), this, SLOT(openConfigurationDialog()));\r\n connect(ui->pushButton_Help, SIGNAL(clicked()), this, SLOT(openHelpDialog()));\r\n connect(ui->pushButton_About, SIGNAL(clicked()), this, SLOT(openAboutDialog()));\r\n connect(ui->pushButton_Close, SIGNAL(clicked()), qApp, SLOT(quit()));\r\n\r\n \/\/ Actions - Start\r\n \/\/connect(ui->pushButton_StartNginx, SIGNAL(clicked()), trayIcon, SLOT(runNginx()));\r\n \/\/connect(ui->pushButton_StartPHP, SIGNAL(clicked()), trayIcon, SLOT(runPhp()));\r\n \/\/connect(ui->pushButton_StartMariaDb, SIGNAL(clicked()), trayIcon, SLOT(runMySQL()));\r\n\r\n \/\/ Actions - Stop\r\n \/\/ connect(ui->pushButton_StopNginx, SIGNAL(clicked()), trayIcon, SLOT(stopNginx()));\r\n \/\/ connect(ui->pushButton_StopPHP, SIGNAL(clicked()), trayIcon, SLOT(stopPhp()));\r\n \/\/connect(ui->pushButton_StopMariaDb, SIGNAL(clicked()), trayIcon, SLOT(stopMySQL()));\r\n }\r\n\r\nvoid MainWindow::changeEvent(QEvent *event)\r\n{\r\n switch (event->type())\r\n {\r\n \/\/case QEvent::LanguageChange:\r\n \/\/ this->ui->retranslateUi(this);\r\n \/\/ break;\r\n case QEvent::WindowStateChange:\r\n {\r\n \/\/ minimize to tray (do not minimize to taskbar)\r\n if (this->windowState() & Qt::WindowMinimized)\r\n {\r\n \/\/ @todo provide configuration options to let the user decide on this\r\n \/\/if (Preferences::instance().minimizeToTray())\r\n \/\/{\r\n QTimer::singleShot(0, this, SLOT(hide()));\r\n \/\/}\r\n }\r\n\r\n break;\r\n }\r\n default:\r\n break;\r\n }\r\n\r\n QMainWindow::changeEvent(event);\r\n}\r\n\r\nvoid MainWindow::closeEvent(QCloseEvent *event)\r\n{\r\n if (trayIcon->isVisible()) {\r\n QMessageBox::information(this, APP_NAME,\r\n tr(\"The program will keep running in the system tray.<br>\"\r\n \"To terminate the program, choose <b>Quit<\/b> in the context menu of the system tray.\"));\r\n hide();\r\n\r\n \/\/ do not propagate the event to the base class\r\n event->ignore();\r\n }\r\n}\r\n\r\nvoid MainWindow::setVisible(bool visible)\r\n {\r\n minimizeAction->setEnabled(visible);\r\n restoreAction->setEnabled(isMaximized() || !visible);\r\n QMainWindow::setVisible(visible);\r\n }\r\n\r\nvoid MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)\r\n{\r\n switch (reason) {\r\n case QSystemTrayIcon::Trigger:\r\n case QSystemTrayIcon::DoubleClick:\r\n \/\/case QSystemTrayIcon::MiddleClick:\r\n\r\n \/\/ clicking the tray icon, when the main window is hidden, shows the main window\r\n if(!isVisible()) {\r\n setVisible(true);\r\n setWindowState( windowState() & ( ~Qt::WindowMinimized | Qt::WindowActive ) );\r\n }\r\n else {\r\n \/\/ clicking the tray icon, when the main window is shown, hides it\r\n setVisible(false);\r\n }\r\n\r\n break;\r\n default:;\r\n }\r\n}\r\n\r\nQString MainWindow::getNginxVersion()\r\n{\r\n QProcess* processNginx;\r\n\r\n processNginx = new QProcess(this);\r\n \/\/processNginx->setWorkingDirectory(cfgNginxDir);\r\n \/\/processNginx->start(\".\/nginx\", QStringList() << \"-v\");\r\n processNginx->waitForFinished(-1);\r\n\r\n \/\/QString p_stdout = processNginx->readAllStandardOutput();\r\n QString p_stderr = processNginx->readAllStandardError();\r\n\r\n \/\/ test\r\n QString p_stdout = \"nginx version: nginx\/1.1.11\";\r\n\r\n qDebug() << p_stdout;\r\n qDebug() << p_stderr;\r\n\r\n return parseVersionNumber(p_stdout);\r\n}\r\n\r\nQString MainWindow::getMariaVersion()\r\n{\r\n QProcess* processMaria;\r\n\r\n processMaria = new QProcess(this);\r\n \/\/processMaria->setWorkingDirectory(cfgMariaDir);\r\n processMaria->start(\".\/mysqld\", QStringList() << \"-V\"); \/\/ upper-case V\r\n processMaria->waitForFinished(-1);\r\n\r\n \/\/QString p_stdout = processMaria->readAllStandardOutput();\r\n QString p_stderr = processMaria->readAllStandardError();\r\n\r\n \/\/ test\r\n QString p_stdout = \"mysql Ver 15.1 Distrib 5.5.23-MariaDB, for Win32 (x86)\";\r\n\r\n qDebug() << p_stdout;\r\n qDebug() << p_stderr;\r\n\r\n return parseVersionNumber(p_stdout.mid(15));\r\n}\r\n\r\nQString MainWindow::getPHPVersion()\r\n{\r\n QProcess* processPhp;\r\n\r\n processPhp = new QProcess(this);\r\n \/\/processPhp->setWorkingDirectory(cfgPHPDir);\r\n \/\/processPhp->start(cfgPHPDir+cfgPHPExec, QStringList() << \"-v\");\r\n processPhp->waitForFinished(-1);\r\n\r\n \/\/QString p_stdout = processPhp->readAllStandardOutput();\r\n QString p_stderr = processPhp->readAllStandardError();\r\n\r\n \/\/ test\r\n QString p_stdout = \"PHP 5.4.0 (cli) (built: Feb 29 2012 19:06:50)\";\r\n\r\n qDebug() << p_stdout;\r\n qDebug() << p_stderr;\r\n\r\n return parseVersionNumber(p_stdout);\r\n}\r\n\r\nQString MainWindow::parseVersionNumber(QString stringWithVersion)\r\n{\r\n qDebug() << stringWithVersion;\r\n\r\n \/\/ The RegExp for matching version numbers is (\\d+\\.)?(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)\r\n \/\/ The following one is escaped:\r\n QRegExp regex(\"(\\\\d+\\\\.)?(\\\\d+\\\\.)?(\\\\d+\\\\.)?(\\\\*|\\\\d+)\");\r\n\r\n \/\/ match\r\n regex.indexIn(stringWithVersion);\r\n\r\n qDebug() << regex.cap(0);\r\n QString cap = regex.cap(0);\r\n return cap;\r\n\r\n\/\/ Leave this for debugging reasons\r\n\/\/ int pos = 0;\r\n\/\/ while((pos = regex.indexIn(stringWithVersion, pos)) != -1)\r\n\/\/ {\r\n\/\/ qDebug() << \"Match at pos \" << pos\r\n\/\/ << \" with length \" << regex.matchedLength()\r\n\/\/ << \", captured = \" << regex.capturedTexts().at(0).toLatin1().data()\r\n\/\/ << \".\\n\";\r\n\/\/ pos += regex.matchedLength();\r\n\/\/ }\r\n}\r\n\r\nvoid MainWindow::goToWebsite()\r\n{\r\n QDesktopServices::openUrl(QUrl(\"http:\/\/wpn-xm.org\/\"));\r\n}\r\n\r\nvoid MainWindow::goToGoogleGroup()\r\n{\r\n QDesktopServices::openUrl(QUrl(\"http:\/\/groups.google.com\/group\/wpn-xm\/\"));\r\n}\r\n\r\nvoid MainWindow::goToReportIssue()\r\n{\r\n QDesktopServices::openUrl(QUrl(\"https:\/\/github.com\/jakoch\/WPN-XM\/issues\/\"));\r\n}\r\n\r\nvoid MainWindow::goToDonate()\r\n{\r\n QDesktopServices::openUrl(QUrl(\"http:\/\/wpn-xm.org\/#donate\"));\r\n}\r\n\r\nvoid MainWindow::openHelpDialog()\r\n{\r\n\r\n}\r\n\r\nvoid MainWindow::openConfigurationDialog()\r\n{\r\n\r\n}\r\n\r\nvoid MainWindow::openAboutDialog()\r\n{\r\n\r\n}\r\n\r\n\r\n<commit_msg>connected signal to slot added method setLabelStatusActive set default value disabled on status labels<commit_after>#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"tray.h\"\r\n\r\n#include <QMessageBox>\r\n#include <QSharedMemory>\r\n#include <QtGui>\r\n#include <QRegExp>\r\n#include <QDesktopServices>\r\n#include <QUrl>\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n\r\n \/\/ disable Maximize functionality\r\n setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowMaximizeButtonHint);\r\n \/\/setFixedWidth(600);\r\n \/\/setFixedHeight(270);\r\n\r\n \/\/ overrides the window title defined in mainwindow.ui\r\n setWindowTitle(APP_NAME_AND_VERSION);\r\n\r\n createActions();\r\n\r\n createTrayIcon();\r\n\r\n \/\/ fetch version numbers from the daemons and set label text accordingly\r\n ui->label_Nginx_Version->setText( getNginxVersion() );\r\n ui->label_PHP_Version->setText( getPHPVersion() );\r\n ui->label_MariaDb_Version->setText( getMariaVersion() );\r\n\r\n \/\/ the initial state of daemon status icons is disabled\r\n ui->label_Nginx_Status->setEnabled(false);\r\n ui->label_PHP_Status->setEnabled(false);\r\n ui->label_MariaDB_Status->setEnabled(false);\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::setLabelStatusActive(QString label, bool enabled)\r\n{\r\n if(label == \"nginx\")\r\n {\r\n ui->label_Nginx_Status->setEnabled(enabled);\r\n }\r\n\r\n if(label == \"php\")\r\n {\r\n ui->label_PHP_Status->setEnabled(enabled);\r\n }\r\n\r\n if(label == \"nginx\")\r\n {\r\n ui->label_MariaDB_Status->setEnabled(enabled);\r\n }\r\n}\r\n\r\nvoid MainWindow::createTrayIcon()\r\n{\r\n \/\/ The tray icon is an instance of the QSystemTrayIcon class.\r\n \/\/ To check whether a system tray is present on the user's desktop,\r\n \/\/ we call the static QSystemTrayIcon::isSystemTrayAvailable() function.\r\n if (false == QSystemTrayIcon::isSystemTrayAvailable())\r\n {\r\n QMessageBox::critical(0, APP_NAME, tr(\"You don't have a system tray.\"));\r\n \/\/return 1;\r\n }\r\n else\r\n {\r\n \/\/ instantiate and attach the tray icon to the system tray\r\n trayIcon = new Tray(qApp);\r\n trayIcon->show();\r\n\r\n \/\/ handle clicks on the icon\r\n connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\r\n this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));\r\n\r\n \/\/ if process state of a daemon changes, then change the label status in UI::MainWindow too\r\n connect(trayIcon, SIGNAL(signalSetLabelStatusActive(QString, bool)),\r\n this, SLOT(setLabelStatusActive(QString, bool)));\r\n }\r\n}\r\n\r\nvoid MainWindow::createActions()\r\n {\r\n minimizeAction = new QAction(tr(\"Mi&nimize\"), this);\r\n connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));\r\n\r\n restoreAction = new QAction(tr(\"&Restore\"), this);\r\n connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));\r\n\r\n quitAction = new QAction(tr(\"&Quit\"), this);\r\n \/\/ qApp is global pointer to QApplication\r\n connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\r\n\r\n \/\/ PushButtons:: Website, ReportBug, Donate\r\n connect(ui->pushButton_Website, SIGNAL(clicked()), this, SLOT(goToWebsite()));\r\n connect(ui->pushButton_GoogleGroup, SIGNAL(clicked()), this, SLOT(goToGoogleGroup()));\r\n connect(ui->pushButton_ReportBug, SIGNAL(clicked()), this, SLOT(goToReportIssue()));\r\n connect(ui->pushButton_Donate, SIGNAL(clicked()), this, SLOT(goToDonate()));\r\n\r\n \/\/ PushButtons: Configuration, Help, About, Close\r\n connect(ui->pushButton_Configuration, SIGNAL(clicked()), this, SLOT(openConfigurationDialog()));\r\n connect(ui->pushButton_Help, SIGNAL(clicked()), this, SLOT(openHelpDialog()));\r\n connect(ui->pushButton_About, SIGNAL(clicked()), this, SLOT(openAboutDialog()));\r\n connect(ui->pushButton_Close, SIGNAL(clicked()), qApp, SLOT(quit()));\r\n\r\n \/\/ Actions - Start\r\n \/\/connect(ui->pushButton_StartNginx, SIGNAL(clicked()), trayIcon, SLOT(runNginx()));\r\n \/\/connect(ui->pushButton_StartPHP, SIGNAL(clicked()), trayIcon, SLOT(runPhp()));\r\n \/\/connect(ui->pushButton_StartMariaDb, SIGNAL(clicked()), trayIcon, SLOT(runMySQL()));\r\n\r\n \/\/ Actions - Stop\r\n \/\/ connect(ui->pushButton_StopNginx, SIGNAL(clicked()), trayIcon, SLOT(stopNginx()));\r\n \/\/ connect(ui->pushButton_StopPHP, SIGNAL(clicked()), trayIcon, SLOT(stopPhp()));\r\n \/\/connect(ui->pushButton_StopMariaDb, SIGNAL(clicked()), trayIcon, SLOT(stopMySQL()));\r\n }\r\n\r\nvoid MainWindow::changeEvent(QEvent *event)\r\n{\r\n switch (event->type())\r\n {\r\n \/\/case QEvent::LanguageChange:\r\n \/\/ this->ui->retranslateUi(this);\r\n \/\/ break;\r\n case QEvent::WindowStateChange:\r\n {\r\n \/\/ minimize to tray (do not minimize to taskbar)\r\n if (this->windowState() & Qt::WindowMinimized)\r\n {\r\n \/\/ @todo provide configuration options to let the user decide on this\r\n \/\/if (Preferences::instance().minimizeToTray())\r\n \/\/{\r\n QTimer::singleShot(0, this, SLOT(hide()));\r\n \/\/}\r\n }\r\n\r\n break;\r\n }\r\n default:\r\n break;\r\n }\r\n\r\n QMainWindow::changeEvent(event);\r\n}\r\n\r\nvoid MainWindow::closeEvent(QCloseEvent *event)\r\n{\r\n if (trayIcon->isVisible()) {\r\n QMessageBox::information(this, APP_NAME,\r\n tr(\"The program will keep running in the system tray.<br>\"\r\n \"To terminate the program, choose <b>Quit<\/b> in the context menu of the system tray.\"));\r\n hide();\r\n\r\n \/\/ do not propagate the event to the base class\r\n event->ignore();\r\n }\r\n}\r\n\r\nvoid MainWindow::setVisible(bool visible)\r\n {\r\n minimizeAction->setEnabled(visible);\r\n restoreAction->setEnabled(isMaximized() || !visible);\r\n QMainWindow::setVisible(visible);\r\n }\r\n\r\nvoid MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)\r\n{\r\n switch (reason) {\r\n case QSystemTrayIcon::Trigger:\r\n case QSystemTrayIcon::DoubleClick:\r\n \/\/case QSystemTrayIcon::MiddleClick:\r\n\r\n \/\/ clicking the tray icon, when the main window is hidden, shows the main window\r\n if(!isVisible()) {\r\n setVisible(true);\r\n setWindowState( windowState() & ( ~Qt::WindowMinimized | Qt::WindowActive ) );\r\n }\r\n else {\r\n \/\/ clicking the tray icon, when the main window is shown, hides it\r\n setVisible(false);\r\n }\r\n\r\n break;\r\n default:;\r\n }\r\n}\r\n\r\nQString MainWindow::getNginxVersion()\r\n{\r\n QProcess* processNginx;\r\n\r\n processNginx = new QProcess(this);\r\n \/\/processNginx->setWorkingDirectory(cfgNginxDir);\r\n \/\/processNginx->start(\".\/nginx\", QStringList() << \"-v\");\r\n processNginx->waitForFinished(-1);\r\n\r\n \/\/QString p_stdout = processNginx->readAllStandardOutput();\r\n QString p_stderr = processNginx->readAllStandardError();\r\n\r\n \/\/ test\r\n QString p_stdout = \"nginx version: nginx\/1.1.11\";\r\n\r\n qDebug() << p_stdout;\r\n qDebug() << p_stderr;\r\n\r\n return parseVersionNumber(p_stdout);\r\n}\r\n\r\nQString MainWindow::getMariaVersion()\r\n{\r\n QProcess* processMaria;\r\n\r\n processMaria = new QProcess(this);\r\n \/\/processMaria->setWorkingDirectory(cfgMariaDir);\r\n processMaria->start(\".\/mysqld\", QStringList() << \"-V\"); \/\/ upper-case V\r\n processMaria->waitForFinished(-1);\r\n\r\n \/\/QString p_stdout = processMaria->readAllStandardOutput();\r\n QString p_stderr = processMaria->readAllStandardError();\r\n\r\n \/\/ test\r\n QString p_stdout = \"mysql Ver 15.1 Distrib 5.5.23-MariaDB, for Win32 (x86)\";\r\n\r\n qDebug() << p_stdout;\r\n qDebug() << p_stderr;\r\n\r\n return parseVersionNumber(p_stdout.mid(15));\r\n}\r\n\r\nQString MainWindow::getPHPVersion()\r\n{\r\n QProcess* processPhp;\r\n\r\n processPhp = new QProcess(this);\r\n \/\/processPhp->setWorkingDirectory(cfgPHPDir);\r\n \/\/processPhp->start(cfgPHPDir+cfgPHPExec, QStringList() << \"-v\");\r\n processPhp->waitForFinished(-1);\r\n\r\n \/\/QString p_stdout = processPhp->readAllStandardOutput();\r\n QString p_stderr = processPhp->readAllStandardError();\r\n\r\n \/\/ test\r\n QString p_stdout = \"PHP 5.4.0 (cli) (built: Feb 29 2012 19:06:50)\";\r\n\r\n qDebug() << p_stdout;\r\n qDebug() << p_stderr;\r\n\r\n return parseVersionNumber(p_stdout);\r\n}\r\n\r\nQString MainWindow::parseVersionNumber(QString stringWithVersion)\r\n{\r\n qDebug() << stringWithVersion;\r\n\r\n \/\/ The RegExp for matching version numbers is (\\d+\\.)?(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)\r\n \/\/ The following one is escaped:\r\n QRegExp regex(\"(\\\\d+\\\\.)?(\\\\d+\\\\.)?(\\\\d+\\\\.)?(\\\\*|\\\\d+)\");\r\n\r\n \/\/ match\r\n regex.indexIn(stringWithVersion);\r\n\r\n qDebug() << regex.cap(0);\r\n QString cap = regex.cap(0);\r\n return cap;\r\n\r\n\/\/ Leave this for debugging reasons\r\n\/\/ int pos = 0;\r\n\/\/ while((pos = regex.indexIn(stringWithVersion, pos)) != -1)\r\n\/\/ {\r\n\/\/ qDebug() << \"Match at pos \" << pos\r\n\/\/ << \" with length \" << regex.matchedLength()\r\n\/\/ << \", captured = \" << regex.capturedTexts().at(0).toLatin1().data()\r\n\/\/ << \".\\n\";\r\n\/\/ pos += regex.matchedLength();\r\n\/\/ }\r\n}\r\n\r\nvoid MainWindow::goToWebsite()\r\n{\r\n QDesktopServices::openUrl(QUrl(\"http:\/\/wpn-xm.org\/\"));\r\n}\r\n\r\nvoid MainWindow::goToGoogleGroup()\r\n{\r\n QDesktopServices::openUrl(QUrl(\"http:\/\/groups.google.com\/group\/wpn-xm\/\"));\r\n}\r\n\r\nvoid MainWindow::goToReportIssue()\r\n{\r\n QDesktopServices::openUrl(QUrl(\"https:\/\/github.com\/jakoch\/WPN-XM\/issues\/\"));\r\n}\r\n\r\nvoid MainWindow::goToDonate()\r\n{\r\n QDesktopServices::openUrl(QUrl(\"http:\/\/wpn-xm.org\/#donate\"));\r\n}\r\n\r\nvoid MainWindow::openHelpDialog()\r\n{\r\n\r\n}\r\n\r\nvoid MainWindow::openConfigurationDialog()\r\n{\r\n\r\n}\r\n\r\nvoid MainWindow::openAboutDialog()\r\n{\r\n QMessageBox::about(this, tr(\"About WPN-XM\"),\r\n tr(\"<b>\" APP_NAME_AND_VERSION \"<\/b><br><br>\"\r\n \"<b>License<\/b>: GNU\/GPL v3+.<br><br>\"\r\n \"<b>Author(s)<\/b>: Yann Le Moigne (c) 2010, Jens-Andr Koch (c) 2011 - onwards.<br><br>\"\r\n \"<b>Website<\/b>: <a href=\\\"http:\/\/wpn-xm.org\/\\\">http:\/\/wpn-xm.org\/<\/a><br>\"\r\n \"<b>Github<\/b>: <a href=\\\"https:\/\/github.com\/jakoch\/WPN-XM\/\\\">https:\/\/github.com\/jakoch\/WPN-XM\/<\/a>\"));\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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\n\/\/ When defined, different heap allocators can be used via an environment\n\/\/ variable set before running the program. This may reduce the amount\n\/\/ of inlining that we get with malloc\/free\/etc. Disabling makes it\n\/\/ so that only tcmalloc can be used.\n#define ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n\n\/\/ TODO(mbelshe): Ensure that all calls to tcmalloc have the proper call depth\n\/\/ from the \"user code\" so that debugging tools (HeapChecker) can work.\n\n\/\/ __THROW is defined in glibc systems. It means, counter-intuitively,\n\/\/ \"This function will never throw an exception.\" It's an optional\n\/\/ optimization tool, but we may need to use it to match glibc prototypes.\n#ifndef __THROW \/\/ I guess we're not on a glibc system\n# define __THROW \/\/ __THROW is just an optimization, so ok to make it \"\"\n#endif\n\n\/\/ new_mode behaves similarly to MSVC's _set_new_mode.\n\/\/ If flag is 0 (default), calls to malloc will behave normally.\n\/\/ If flag is 1, calls to malloc will behave like calls to new,\n\/\/ and the std_new_handler will be invoked on failure.\n\/\/ Can be set by calling _set_new_mode().\nstatic int new_mode = 0;\n\ntypedef enum {\n TCMALLOC, \/\/ TCMalloc is the default allocator.\n JEMALLOC, \/\/ JEMalloc\n WINDEFAULT, \/\/ Windows Heap\n WINLFH, \/\/ Windows LFH Heap\n} Allocator;\n\n\/\/ This is the default allocator.\nstatic Allocator allocator = TCMALLOC;\n\n\/\/ We include tcmalloc and the win_allocator to get as much inlining as\n\/\/ possible.\n#include \"tcmalloc.cc\"\n#include \"win_allocator.cc\"\n\n\/\/ Forward declarations from jemalloc.\nextern \"C\" {\nvoid* je_malloc(size_t s);\nvoid* je_realloc(void* p, size_t s);\nvoid je_free(void* s);\nsize_t je_msize(void* p);\nbool je_malloc_init_hard();\n}\n\nextern \"C\" {\n\n\/\/ Call the new handler, if one has been set.\n\/\/ Returns true on successfully calling the handler, false otherwise.\ninline bool call_new_handler(bool nothrow) {\n \/\/ Get the current new handler. NB: this function is not\n \/\/ thread-safe. We make a feeble stab at making it so here, but\n \/\/ this lock only protects against tcmalloc interfering with\n \/\/ itself, not with other libraries calling set_new_handler.\n std::new_handler nh;\n {\n SpinLockHolder h(&set_new_handler_lock);\n nh = std::set_new_handler(0);\n (void) std::set_new_handler(nh);\n }\n#if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)\n if (!nh)\n return false;\n \/\/ Since exceptions are disabled, we don't really know if new_handler\n \/\/ failed. Assume it will abort if it fails.\n (*nh)();\n return false; \/\/ break out of the retry loop.\n#else\n \/\/ If no new_handler is established, the allocation failed.\n if (!nh) {\n if (nothrow)\n return 0;\n throw std::bad_alloc();\n }\n \/\/ Otherwise, try the new_handler. If it returns, retry the\n \/\/ allocation. If it throws std::bad_alloc, fail the allocation.\n \/\/ if it throws something else, don't interfere.\n try {\n (*nh)();\n } catch (const std::bad_alloc&) {\n if (!nothrow)\n throw;\n return p;\n }\n#endif \/\/ (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)\n}\n\nvoid* malloc(size_t size) __THROW {\n void* ptr;\n for (;;) {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n ptr = je_malloc(size);\n break;\n case WINDEFAULT:\n case WINLFH:\n ptr = win_heap_malloc(size);\n break;\n case TCMALLOC:\n default:\n ptr = do_malloc(size);\n break;\n }\n#else\n \/\/ TCMalloc case.\n ptr = do_malloc(size);\n#endif\n if (ptr)\n return ptr;\n\n if (!new_mode || !call_new_handler(true))\n break;\n }\n return ptr;\n}\n\nvoid free(void* p) __THROW {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n je_free(p);\n return;\n case WINDEFAULT:\n case WINLFH:\n win_heap_free(p);\n return;\n }\n#endif\n \/\/ TCMalloc case.\n do_free(p);\n}\n\nvoid* realloc(void* ptr, size_t size) __THROW {\n void* new_ptr;\n for (;;) {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n new_ptr = je_realloc(ptr, size);\n break;\n case WINDEFAULT:\n case WINLFH:\n new_ptr = win_heap_realloc(ptr, size);\n break;\n case TCMALLOC:\n default:\n new_ptr = do_realloc(ptr, size);\n break;\n }\n#else\n \/\/ TCMalloc case.\n new_ptr = do_realloc(ptr, size);\n#endif\n\n \/\/ Subtle warning: NULL return does not alwas indicate out-of-memory. If\n \/\/ the requested new size is zero, realloc should free the ptr and return\n \/\/ NULL.\n if (new_ptr || !size)\n return new_ptr;\n if (!new_mode || !call_new_handler(true))\n break;\n }\n return new_ptr;\n}\n\n\/\/ TODO(mbelshe): Implement this for other allocators.\nvoid malloc_stats(void) __THROW {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n \/\/ No stats.\n return;\n case WINDEFAULT:\n case WINLFH:\n \/\/ No stats.\n return;\n }\n#endif\n tc_malloc_stats();\n}\n\n#ifdef WIN32\n\nextern \"C\" size_t _msize(void* p) {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n return je_msize(p);\n case WINDEFAULT:\n case WINLFH:\n return win_heap_msize(p);\n }\n#endif\n return MallocExtension::instance()->GetAllocatedSize(p);\n}\n\n\/\/ This is included to resolve references from libcmt.\nextern \"C\" intptr_t _get_heap_handle() {\n return 0;\n}\n\n\/\/ The CRT heap initialization stub.\nextern \"C\" int _heap_init() {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n const char* override = GetenvBeforeMain(\"CHROME_ALLOCATOR\");\n if (override) {\n if (!stricmp(override, \"jemalloc\"))\n allocator = JEMALLOC;\n else if (!stricmp(override, \"winheap\"))\n allocator = WINDEFAULT;\n else if (!stricmp(override, \"winlfh\"))\n allocator = WINLFH;\n else if (!stricmp(override, \"tcmalloc\"))\n allocator = TCMALLOC;\n }\n\n switch (allocator) {\n case JEMALLOC:\n return je_malloc_init_hard() ? 0 : 1;\n case WINDEFAULT:\n return win_heap_init(false) ? 1 : 0;\n case WINLFH:\n return win_heap_init(true) ? 1 : 0;\n case TCMALLOC:\n default:\n \/\/ fall through\n break;\n }\n#endif\n \/\/ Initializing tcmalloc.\n \/\/ We intentionally leak this object. It lasts for the process\n \/\/ lifetime. Trying to teardown at _heap_term() is so late that\n \/\/ you can't do anything useful anyway.\n new TCMallocGuard();\n return 1;\n}\n\n\/\/ The CRT heap cleanup stub.\nextern \"C\" void _heap_term() {}\n\n\/\/ We set this to 1 because part of the CRT uses a check of _crtheap != 0\n\/\/ to test whether the CRT has been initialized. Once we've ripped out\n\/\/ the allocators from libcmt, we need to provide this definition so that\n\/\/ the rest of the CRT is still usable.\nextern \"C\" void* _crtheap = reinterpret_cast<void*>(1);\n\n#endif \/\/ WIN32\n\n#include \"generic_allocators.cc\"\n\n} \/\/ extern C\n<commit_msg>Set JEMalloc as the default allocator (instead of TCMalloc)<commit_after>\/\/ 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\n\/\/ When defined, different heap allocators can be used via an environment\n\/\/ variable set before running the program. This may reduce the amount\n\/\/ of inlining that we get with malloc\/free\/etc. Disabling makes it\n\/\/ so that only tcmalloc can be used.\n#define ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n\n\/\/ TODO(mbelshe): Ensure that all calls to tcmalloc have the proper call depth\n\/\/ from the \"user code\" so that debugging tools (HeapChecker) can work.\n\n\/\/ __THROW is defined in glibc systems. It means, counter-intuitively,\n\/\/ \"This function will never throw an exception.\" It's an optional\n\/\/ optimization tool, but we may need to use it to match glibc prototypes.\n#ifndef __THROW \/\/ I guess we're not on a glibc system\n# define __THROW \/\/ __THROW is just an optimization, so ok to make it \"\"\n#endif\n\n\/\/ new_mode behaves similarly to MSVC's _set_new_mode.\n\/\/ If flag is 0 (default), calls to malloc will behave normally.\n\/\/ If flag is 1, calls to malloc will behave like calls to new,\n\/\/ and the std_new_handler will be invoked on failure.\n\/\/ Can be set by calling _set_new_mode().\nstatic int new_mode = 0;\n\ntypedef enum {\n TCMALLOC, \/\/ TCMalloc is the default allocator.\n JEMALLOC, \/\/ JEMalloc\n WINDEFAULT, \/\/ Windows Heap\n WINLFH, \/\/ Windows LFH Heap\n} Allocator;\n\n\/\/ This is the default allocator.\nstatic Allocator allocator = JEMALLOC;\n\n\/\/ We include tcmalloc and the win_allocator to get as much inlining as\n\/\/ possible.\n#include \"tcmalloc.cc\"\n#include \"win_allocator.cc\"\n\n\/\/ Forward declarations from jemalloc.\nextern \"C\" {\nvoid* je_malloc(size_t s);\nvoid* je_realloc(void* p, size_t s);\nvoid je_free(void* s);\nsize_t je_msize(void* p);\nbool je_malloc_init_hard();\n}\n\nextern \"C\" {\n\n\/\/ Call the new handler, if one has been set.\n\/\/ Returns true on successfully calling the handler, false otherwise.\ninline bool call_new_handler(bool nothrow) {\n \/\/ Get the current new handler. NB: this function is not\n \/\/ thread-safe. We make a feeble stab at making it so here, but\n \/\/ this lock only protects against tcmalloc interfering with\n \/\/ itself, not with other libraries calling set_new_handler.\n std::new_handler nh;\n {\n SpinLockHolder h(&set_new_handler_lock);\n nh = std::set_new_handler(0);\n (void) std::set_new_handler(nh);\n }\n#if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)\n if (!nh)\n return false;\n \/\/ Since exceptions are disabled, we don't really know if new_handler\n \/\/ failed. Assume it will abort if it fails.\n (*nh)();\n return false; \/\/ break out of the retry loop.\n#else\n \/\/ If no new_handler is established, the allocation failed.\n if (!nh) {\n if (nothrow)\n return 0;\n throw std::bad_alloc();\n }\n \/\/ Otherwise, try the new_handler. If it returns, retry the\n \/\/ allocation. If it throws std::bad_alloc, fail the allocation.\n \/\/ if it throws something else, don't interfere.\n try {\n (*nh)();\n } catch (const std::bad_alloc&) {\n if (!nothrow)\n throw;\n return p;\n }\n#endif \/\/ (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)\n}\n\nvoid* malloc(size_t size) __THROW {\n void* ptr;\n for (;;) {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n ptr = je_malloc(size);\n break;\n case WINDEFAULT:\n case WINLFH:\n ptr = win_heap_malloc(size);\n break;\n case TCMALLOC:\n default:\n ptr = do_malloc(size);\n break;\n }\n#else\n \/\/ TCMalloc case.\n ptr = do_malloc(size);\n#endif\n if (ptr)\n return ptr;\n\n if (!new_mode || !call_new_handler(true))\n break;\n }\n return ptr;\n}\n\nvoid free(void* p) __THROW {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n je_free(p);\n return;\n case WINDEFAULT:\n case WINLFH:\n win_heap_free(p);\n return;\n }\n#endif\n \/\/ TCMalloc case.\n do_free(p);\n}\n\nvoid* realloc(void* ptr, size_t size) __THROW {\n void* new_ptr;\n for (;;) {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n new_ptr = je_realloc(ptr, size);\n break;\n case WINDEFAULT:\n case WINLFH:\n new_ptr = win_heap_realloc(ptr, size);\n break;\n case TCMALLOC:\n default:\n new_ptr = do_realloc(ptr, size);\n break;\n }\n#else\n \/\/ TCMalloc case.\n new_ptr = do_realloc(ptr, size);\n#endif\n\n \/\/ Subtle warning: NULL return does not alwas indicate out-of-memory. If\n \/\/ the requested new size is zero, realloc should free the ptr and return\n \/\/ NULL.\n if (new_ptr || !size)\n return new_ptr;\n if (!new_mode || !call_new_handler(true))\n break;\n }\n return new_ptr;\n}\n\n\/\/ TODO(mbelshe): Implement this for other allocators.\nvoid malloc_stats(void) __THROW {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n \/\/ No stats.\n return;\n case WINDEFAULT:\n case WINLFH:\n \/\/ No stats.\n return;\n }\n#endif\n tc_malloc_stats();\n}\n\n#ifdef WIN32\n\nextern \"C\" size_t _msize(void* p) {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n switch (allocator) {\n case JEMALLOC:\n return je_msize(p);\n case WINDEFAULT:\n case WINLFH:\n return win_heap_msize(p);\n }\n#endif\n return MallocExtension::instance()->GetAllocatedSize(p);\n}\n\n\/\/ This is included to resolve references from libcmt.\nextern \"C\" intptr_t _get_heap_handle() {\n return 0;\n}\n\n\/\/ The CRT heap initialization stub.\nextern \"C\" int _heap_init() {\n#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING\n const char* override = GetenvBeforeMain(\"CHROME_ALLOCATOR\");\n if (override) {\n if (!stricmp(override, \"jemalloc\"))\n allocator = JEMALLOC;\n else if (!stricmp(override, \"winheap\"))\n allocator = WINDEFAULT;\n else if (!stricmp(override, \"winlfh\"))\n allocator = WINLFH;\n else if (!stricmp(override, \"tcmalloc\"))\n allocator = TCMALLOC;\n }\n\n switch (allocator) {\n case JEMALLOC:\n return je_malloc_init_hard() ? 0 : 1;\n case WINDEFAULT:\n return win_heap_init(false) ? 1 : 0;\n case WINLFH:\n return win_heap_init(true) ? 1 : 0;\n case TCMALLOC:\n default:\n \/\/ fall through\n break;\n }\n#endif\n \/\/ Initializing tcmalloc.\n \/\/ We intentionally leak this object. It lasts for the process\n \/\/ lifetime. Trying to teardown at _heap_term() is so late that\n \/\/ you can't do anything useful anyway.\n new TCMallocGuard();\n return 1;\n}\n\n\/\/ The CRT heap cleanup stub.\nextern \"C\" void _heap_term() {}\n\n\/\/ We set this to 1 because part of the CRT uses a check of _crtheap != 0\n\/\/ to test whether the CRT has been initialized. Once we've ripped out\n\/\/ the allocators from libcmt, we need to provide this definition so that\n\/\/ the rest of the CRT is still usable.\nextern \"C\" void* _crtheap = reinterpret_cast<void*>(1);\n\n#endif \/\/ WIN32\n\n#include \"generic_allocators.cc\"\n\n} \/\/ extern C\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) *\n * *\n * This file is part of LuxRays. *\n * *\n * LuxRays 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 3 of the License, or *\n * (at your option) any later version. *\n * *\n * LuxRays 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 <http:\/\/www.gnu.org\/licenses\/>. *\n * *\n * LuxRays website: http:\/\/www.luxrender.net *\n ***************************************************************************\/\n\n#if !defined(LUXRAYS_DISABLE_OPENCL)\n\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <string.h>\n#include <string>\n#include <sstream>\n#include <stdexcept>\n\n#include <boost\/thread\/mutex.hpp>\n\n#include \"smalllux.h\"\n\n#include \"pathocl\/pathocl.h\"\n#include \"pathocl\/kernels\/kernels.h\"\n#include \"renderconfig.h\"\n#include \"luxrays\/core\/geometry\/transform.h\"\n#include \"luxrays\/accelerators\/mqbvhaccel.h\"\n#include \"luxrays\/accelerators\/bvhaccel.h\"\n#include \"luxrays\/opencl\/intersectiondevice.h\"\n\n\/\/------------------------------------------------------------------------------\n\/\/ PathOCLRenderEngine\n\/\/------------------------------------------------------------------------------\n\nPathOCLRenderEngine::PathOCLRenderEngine(RenderConfig *rcfg, Film *flm, boost::mutex *flmMutex) :\n\t\tOCLRenderEngine(rcfg, flm, flmMutex) {\n\tconst Properties &cfg = renderConfig->cfg;\n\tcompiledScene = NULL;\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Allocate devices\n\t\/\/--------------------------------------------------------------------------\n\n\tstd::vector<IntersectionDevice *> devs = ctx->AddIntersectionDevices(selectedDeviceDescs);\n\n\t\/\/ Check if I have to disable image storage and set max. QBVH stack size\n\tconst bool forcedDisableImageStorage = (renderConfig->scene->GetAccelType() == 2);\n\tconst size_t qbvhStackSize = cfg.GetInt(\"accelerator.qbvh.stacksize.max\", 24);\n\tSLG_LOG(\"OpenCL Devices used:\");\n\tfor (size_t i = 0; i < devs.size(); ++i) {\n\t\tSLG_LOG(\"[\" << devs[i]->GetName() << \"]\");\n\t\tdevs[i]->SetMaxStackSize(qbvhStackSize);\n\t\tintersectionDevices.push_back(devs[i]);\n\n\t\tOpenCLIntersectionDevice *oclIntersectionDevice = (OpenCLIntersectionDevice *)(devs[i]);\n\t\toclIntersectionDevice->DisableImageStorage(forcedDisableImageStorage);\n\t\t\/\/ Disable the support for hybrid rendering\n\t\toclIntersectionDevice->SetDataParallelSupport(false);\n\t}\n\n\t\/\/ Set the LuxRays SataSet\n\tctx->SetDataSet(renderConfig->scene->dataSet);\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Rendering parameters\n\t\/\/--------------------------------------------------------------------------\n\n\ttaskCount = RoundUpPow2(cfg.GetInt(\"opencl.task.count\", 65536));\n\tSLG_LOG(\"[PathOCLRenderThread] OpenCL task count: \" << taskCount);\n\n\tif (cfg.IsDefined(\"opencl.memory.maxpagesize\"))\n\t\tmaxMemPageSize = cfg.GetSize(\"opencl.memory.maxpagesize\", 512 * 1024 * 1024);\n\telse {\n\t\t\/\/ Look for the max. page size allowed\n\t\tmaxMemPageSize = ((OpenCLIntersectionDevice *)(intersectionDevices[0]))->GetDeviceDesc()->GetMaxMemoryAllocSize();\n\t\tfor (u_int i = 1; i < intersectionDevices.size(); ++i)\n\t\t\tmaxMemPageSize = Min(maxMemPageSize, ((OpenCLIntersectionDevice *)(intersectionDevices[i]))->GetDeviceDesc()->GetMaxMemoryAllocSize());\n\t}\n\tSLG_LOG(\"[PathOCLRenderThread] OpenCL max. page memory size: \" << maxMemPageSize \/ 1024 << \"Kbytes\");\n\t\n\tmaxPathDepth = cfg.GetInt(\"path.maxdepth\", 5);\n\tmaxDiffusePathVertexCount = cfg.GetInt(\"path.maxdiffusebounce\", 5);\n\trrDepth = cfg.GetInt(\"path.russianroulette.depth\", 3);\n\trrImportanceCap = cfg.GetFloat(\"path.russianroulette.cap\", 0.125f);\n\tepsilon = cfg.GetFloat(\"scene.epsilon\", .0001f);\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Sampler\n\t\/\/--------------------------------------------------------------------------\n\n\tconst string samplerTypeName = cfg.GetString(\"path.sampler.type\", \"INLINED_RANDOM\");\n\tif (samplerTypeName.compare(\"INLINED_RANDOM\") == 0)\n\t\tsampler = new PathOCL::InlinedRandomSampler();\n\telse if (samplerTypeName.compare(\"RANDOM\") == 0)\n\t\tsampler = new PathOCL::RandomSampler();\n\telse if (samplerTypeName.compare(\"STRATIFIED\") == 0) {\n\t\tconst unsigned int xSamples = cfg.GetInt(\"path.sampler.xsamples\", 3);\n\t\tconst unsigned int ySamples = cfg.GetInt(\"path.sampler.ysamples\", 3);\n\n\t\tsampler = new PathOCL::StratifiedSampler(xSamples, ySamples);\n\t} else if (samplerTypeName.compare(\"METROPOLIS\") == 0) {\n\t\tconst float rate = cfg.GetFloat(\"path.sampler.largesteprate\", .4f);\n\t\tconst float reject = cfg.GetFloat(\"path.sampler.maxconsecutivereject\", 512);\n\t\tconst float mutationrate = cfg.GetFloat(\"path.sampler.imagemutationrate\", .1f);\n\n\t\tsampler = new PathOCL::MetropolisSampler(rate, reject, mutationrate);\n\t} else\n\t\tthrow std::runtime_error(\"Unknown path.sampler.type\");\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Filter\n\t\/\/--------------------------------------------------------------------------\n\n\tconst string filterType = cfg.GetString(\"path.filter.type\", \"NONE\");\n\tconst float filterWidthX = cfg.GetFloat(\"path.filter.width.x\", 1.5f);\n\tconst float filterWidthY = cfg.GetFloat(\"path.filter.width.y\", 1.5f);\n\tif ((filterWidthX <= 0.f) || (filterWidthX > 1.5f))\n\t\tthrow std::runtime_error(\"path.filter.width.x must be between 0.0 and 1.5\");\n\tif ((filterWidthY <= 0.f) || (filterWidthY > 1.5f))\n\t\tthrow std::runtime_error(\"path.filter.width.y must be between 0.0 and 1.5\");\n\n\tif (filterType.compare(\"NONE\") == 0)\n\t\tfilter = new PathOCL::NoneFilter();\n\telse if (filterType.compare(\"BOX\") == 0)\n\t\tfilter = new PathOCL::BoxFilter(filterWidthX, filterWidthY);\n\telse if (filterType.compare(\"GAUSSIAN\") == 0) {\n\t\tconst float alpha = cfg.GetFloat(\"path.filter.alpha\", 2.f);\n\t\tfilter = new PathOCL::GaussianFilter(filterWidthX, filterWidthY, alpha);\n\t} else if (filterType.compare(\"MITCHELL\") == 0) {\n\t\tconst float B = cfg.GetFloat(\"path.filter.B\", 1.f \/ 3.f);\n\t\tconst float C = cfg.GetFloat(\"path.filter.C\", 1.f \/ 3.f);\n\t\tfilter = new PathOCL::MitchellFilter(filterWidthX, filterWidthY, B, C);\n\t} else\n\t\tthrow std::runtime_error(\"Unknown path.filter.type\");\n\n\tusePixelAtomics = (cfg.GetInt(\"path.pixelatomics.enable\", 0) != 0);\t\n\n\tconst unsigned int seedBase = (unsigned int)(WallClockTime() \/ 1000.0);\n\n\tfilm->EnableOverlappedScreenBufferUpdate(true);\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Create and start render threads\n\t\/\/--------------------------------------------------------------------------\n\n\tconst size_t renderThreadCount = intersectionDevices.size();\n\tSLG_LOG(\"Starting \"<< renderThreadCount << \" PathOCL render threads\");\n\tfor (size_t i = 0; i < renderThreadCount; ++i) {\n\t\tPathOCLRenderThread *t = new PathOCLRenderThread(i,\n\t\t\tseedBase + i * taskCount, i \/ (float)renderThreadCount,\n\t\t\t(OpenCLIntersectionDevice *)(intersectionDevices[i]),\n\t\t\tthis);\n\t\trenderThreads.push_back(t);\n\t}\n}\n\nPathOCLRenderEngine::~PathOCLRenderEngine() {\n\tif (editMode)\n\t\tEndEdit(EditActionList());\n\tif (started)\n\t\tStop();\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\tdelete renderThreads[i];\n\n\tdelete sampler;\n\tdelete filter;\n}\n\nvoid PathOCLRenderEngine::StartLockLess() {\n\tcompiledScene = new CompiledScene(renderConfig->scene, film, maxMemPageSize);\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Start();\n}\n\nvoid PathOCLRenderEngine::StopLockLess() {\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Interrupt();\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Stop();\n\n\tdelete compiledScene;\n\tcompiledScene = NULL;\n}\n\nvoid PathOCLRenderEngine::BeginEditLockLess() {\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Interrupt();\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->BeginEdit();\n}\n\nvoid PathOCLRenderEngine::EndEditLockLess(const EditActionList &editActions) {\n\tcompiledScene->Recompile(editActions);\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->EndEdit(editActions);\n}\n\nvoid PathOCLRenderEngine::UpdateFilmLockLess() {\n\tboost::unique_lock<boost::mutex> lock(*filmMutex);\n\n\tconst unsigned int imgWidth = film->GetWidth();\n\tconst unsigned int imgHeight = film->GetHeight();\n\n\tfilm->Reset();\n\n\tconst bool isAlphaChannelEnabled = film->IsAlphaChannelEnabled();\n\n\tswitch (film->GetFilterType()) {\n\t\tcase FILTER_GAUSSIAN: {\n\t\t\tfor (unsigned int y = 0; y < imgHeight; ++y) {\n\t\t\t\tunsigned int pGPU = 1 + (y + 1) * (imgWidth + 2);\n\n\t\t\t\tfor (unsigned int x = 0; x < imgWidth; ++x) {\n\t\t\t\t\tSpectrum c;\n\t\t\t\t\tfloat alpha = 0.0f;\n\t\t\t\t\tfloat count = 0.f;\n\t\t\t\t\tfor (size_t i = 0; i < renderThreads.size(); ++i) {\n\t\t\t\t\t\tif (renderThreads[i]->frameBuffer) {\n\t\t\t\t\t\t\tc += renderThreads[i]->frameBuffer[pGPU].c;\n\t\t\t\t\t\t\tcount += renderThreads[i]->frameBuffer[pGPU].count;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (renderThreads[i]->alphaFrameBuffer)\n\t\t\t\t\t\t\talpha += renderThreads[i]->alphaFrameBuffer[pGPU].alpha;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((count > 0) && !c.IsNaN()) {\n\t\t\t\t\t\tc \/= count;\n\t\t\t\t\t\tfilm->AddSampleCount(1.f);\n\t\t\t\t\t\t\/\/ -.5f is to align correctly the pixel after the splat\n\t\t\t\t\t\tfilm->SplatFiltered(PER_PIXEL_NORMALIZED, x - .5f, y - .5f, c);\n\n\t\t\t\t\t\tif (isAlphaChannelEnabled && !isnan(alpha))\n\t\t\t\t\t\t\tfilm->SplatFilteredAlpha(x - .5f, y - .5f, alpha \/ count);\n\t\t\t\t\t}\n\n\t\t\t\t\t++pGPU;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase FILTER_NONE: {\n\t\t\tfor (unsigned int y = 0; y < imgHeight; ++y) {\n\t\t\t\tunsigned int pGPU = 1 + (y + 1) * (imgWidth + 2);\n\n\t\t\t\tfor (unsigned int x = 0; x < imgWidth; ++x) {\n\t\t\t\t\tSpectrum c;\n\t\t\t\t\tfloat alpha = 0.0f;\n\t\t\t\t\tfloat count = 0.f;\n\t\t\t\t\tfor (size_t i = 0; i < renderThreads.size(); ++i) {\n\t\t\t\t\t\tif (renderThreads[i]->frameBuffer) {\n\t\t\t\t\t\t\tc += renderThreads[i]->frameBuffer[pGPU].c;\n\t\t\t\t\t\t\tcount += renderThreads[i]->frameBuffer[pGPU].count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (renderThreads[i]->alphaFrameBuffer)\n\t\t\t\t\t\t\talpha += renderThreads[i]->alphaFrameBuffer[pGPU].alpha;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((count > 0) && !c.IsNaN()) {\n\t\t\t\t\t\tfilm->AddSampleCount(1.f);\n\t\t\t\t\t\tfilm->AddRadiance(PER_PIXEL_NORMALIZED, x, y, c \/ count, count);\n\n\t\t\t\t\t\tif (isAlphaChannelEnabled && !isnan(alpha))\n\t\t\t\t\t\t\tfilm->AddAlpha(x, y, alpha \/ count, 1.f);\n\t\t\t\t\t}\n\n\t\t\t\t\t++pGPU;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tassert (false);\n\t\t\tbreak;\n\t}\n}\n\nvoid PathOCLRenderEngine::UpdateCounters() {\n\t\/\/ Update the sample count statistic\n\tunsigned long long totalCount = 0;\n\tfor (size_t i = 0; i < renderThreads.size(); ++i) {\n\t\tPathOCL::GPUTaskStats *stats = renderThreads[i]->gpuTaskStats;\n\n\t\tfor (size_t i = 0; i < taskCount; ++i)\n\t\t\ttotalCount += stats[i].sampleCount;\n\t}\n\n\tsamplesCount = totalCount;\n\n\t\/\/ Update the ray count statistic\n\ttotalCount = 0.0;\n\tfor (size_t i = 0; i < intersectionDevices.size(); ++i)\n\t\ttotalCount += intersectionDevices[i]->GetTotalRaysCount();\n\traysCount = totalCount;\n}\n\n#endif\n<commit_msg>PathOCL: sampler.* parameters are now accepted too<commit_after>\/***************************************************************************\n * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) *\n * *\n * This file is part of LuxRays. *\n * *\n * LuxRays 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 3 of the License, or *\n * (at your option) any later version. *\n * *\n * LuxRays 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 <http:\/\/www.gnu.org\/licenses\/>. *\n * *\n * LuxRays website: http:\/\/www.luxrender.net *\n ***************************************************************************\/\n\n#if !defined(LUXRAYS_DISABLE_OPENCL)\n\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <string.h>\n#include <string>\n#include <sstream>\n#include <stdexcept>\n\n#include <boost\/thread\/mutex.hpp>\n\n#include \"smalllux.h\"\n\n#include \"pathocl\/pathocl.h\"\n#include \"pathocl\/kernels\/kernels.h\"\n#include \"renderconfig.h\"\n#include \"luxrays\/core\/geometry\/transform.h\"\n#include \"luxrays\/accelerators\/mqbvhaccel.h\"\n#include \"luxrays\/accelerators\/bvhaccel.h\"\n#include \"luxrays\/opencl\/intersectiondevice.h\"\n\n\/\/------------------------------------------------------------------------------\n\/\/ PathOCLRenderEngine\n\/\/------------------------------------------------------------------------------\n\nPathOCLRenderEngine::PathOCLRenderEngine(RenderConfig *rcfg, Film *flm, boost::mutex *flmMutex) :\n\t\tOCLRenderEngine(rcfg, flm, flmMutex) {\n\tconst Properties &cfg = renderConfig->cfg;\n\tcompiledScene = NULL;\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Allocate devices\n\t\/\/--------------------------------------------------------------------------\n\n\tstd::vector<IntersectionDevice *> devs = ctx->AddIntersectionDevices(selectedDeviceDescs);\n\n\t\/\/ Check if I have to disable image storage and set max. QBVH stack size\n\tconst bool forcedDisableImageStorage = (renderConfig->scene->GetAccelType() == 2);\n\tconst size_t qbvhStackSize = cfg.GetInt(\"accelerator.qbvh.stacksize.max\", 24);\n\tSLG_LOG(\"OpenCL Devices used:\");\n\tfor (size_t i = 0; i < devs.size(); ++i) {\n\t\tSLG_LOG(\"[\" << devs[i]->GetName() << \"]\");\n\t\tdevs[i]->SetMaxStackSize(qbvhStackSize);\n\t\tintersectionDevices.push_back(devs[i]);\n\n\t\tOpenCLIntersectionDevice *oclIntersectionDevice = (OpenCLIntersectionDevice *)(devs[i]);\n\t\toclIntersectionDevice->DisableImageStorage(forcedDisableImageStorage);\n\t\t\/\/ Disable the support for hybrid rendering\n\t\toclIntersectionDevice->SetDataParallelSupport(false);\n\t}\n\n\t\/\/ Set the LuxRays SataSet\n\tctx->SetDataSet(renderConfig->scene->dataSet);\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Rendering parameters\n\t\/\/--------------------------------------------------------------------------\n\n\ttaskCount = RoundUpPow2(cfg.GetInt(\"opencl.task.count\", 65536));\n\tSLG_LOG(\"[PathOCLRenderThread] OpenCL task count: \" << taskCount);\n\n\tif (cfg.IsDefined(\"opencl.memory.maxpagesize\"))\n\t\tmaxMemPageSize = cfg.GetSize(\"opencl.memory.maxpagesize\", 512 * 1024 * 1024);\n\telse {\n\t\t\/\/ Look for the max. page size allowed\n\t\tmaxMemPageSize = ((OpenCLIntersectionDevice *)(intersectionDevices[0]))->GetDeviceDesc()->GetMaxMemoryAllocSize();\n\t\tfor (u_int i = 1; i < intersectionDevices.size(); ++i)\n\t\t\tmaxMemPageSize = Min(maxMemPageSize, ((OpenCLIntersectionDevice *)(intersectionDevices[i]))->GetDeviceDesc()->GetMaxMemoryAllocSize());\n\t}\n\tSLG_LOG(\"[PathOCLRenderThread] OpenCL max. page memory size: \" << maxMemPageSize \/ 1024 << \"Kbytes\");\n\t\n\tmaxPathDepth = cfg.GetInt(\"path.maxdepth\", 5);\n\tmaxDiffusePathVertexCount = cfg.GetInt(\"path.maxdiffusebounce\", 5);\n\trrDepth = cfg.GetInt(\"path.russianroulette.depth\", 3);\n\trrImportanceCap = cfg.GetFloat(\"path.russianroulette.cap\", 0.125f);\n\tepsilon = cfg.GetFloat(\"scene.epsilon\", .0001f);\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Sampler\n\t\/\/--------------------------------------------------------------------------\n\n\tconst string samplerTypeName = cfg.GetString(\"sampler.type\",\n\t\t\tcfg.GetString(\"path.sampler.type\", \"INLINED_RANDOM\"));\n\tif (samplerTypeName.compare(\"INLINED_RANDOM\") == 0)\n\t\tsampler = new PathOCL::InlinedRandomSampler();\n\telse if (samplerTypeName.compare(\"RANDOM\") == 0)\n\t\tsampler = new PathOCL::RandomSampler();\n\telse if (samplerTypeName.compare(\"STRATIFIED\") == 0) {\n\t\tconst unsigned int xSamples = cfg.GetInt(\"path.sampler.xsamples\", 3);\n\t\tconst unsigned int ySamples = cfg.GetInt(\"path.sampler.ysamples\", 3);\n\n\t\tsampler = new PathOCL::StratifiedSampler(xSamples, ySamples);\n\t} else if (samplerTypeName.compare(\"METROPOLIS\") == 0) {\n\t\tconst float rate = cfg.GetFloat(\"sampler.largesteprate\",\n\t\t\t\tcfg.GetFloat(\"path.sampler.largesteprate\", .4f));\n\t\tconst float reject = cfg.GetFloat(\"sampler.maxconsecutivereject\",\n\t\t\t\tcfg.GetFloat(\"path.sampler.maxconsecutivereject\", 512));\n\t\tconst float mutationrate = cfg.GetFloat(\"sampler.imagemutationrate\",\n\t\t\t\tcfg.GetFloat(\"path.sampler.imagemutationrate\", .1f));\n\n\t\tsampler = new PathOCL::MetropolisSampler(rate, reject, mutationrate);\n\t} else\n\t\tthrow std::runtime_error(\"Unknown path.sampler.type\");\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Filter\n\t\/\/--------------------------------------------------------------------------\n\n\tconst string filterType = cfg.GetString(\"path.filter.type\", \"NONE\");\n\tconst float filterWidthX = cfg.GetFloat(\"path.filter.width.x\", 1.5f);\n\tconst float filterWidthY = cfg.GetFloat(\"path.filter.width.y\", 1.5f);\n\tif ((filterWidthX <= 0.f) || (filterWidthX > 1.5f))\n\t\tthrow std::runtime_error(\"path.filter.width.x must be between 0.0 and 1.5\");\n\tif ((filterWidthY <= 0.f) || (filterWidthY > 1.5f))\n\t\tthrow std::runtime_error(\"path.filter.width.y must be between 0.0 and 1.5\");\n\n\tif (filterType.compare(\"NONE\") == 0)\n\t\tfilter = new PathOCL::NoneFilter();\n\telse if (filterType.compare(\"BOX\") == 0)\n\t\tfilter = new PathOCL::BoxFilter(filterWidthX, filterWidthY);\n\telse if (filterType.compare(\"GAUSSIAN\") == 0) {\n\t\tconst float alpha = cfg.GetFloat(\"path.filter.alpha\", 2.f);\n\t\tfilter = new PathOCL::GaussianFilter(filterWidthX, filterWidthY, alpha);\n\t} else if (filterType.compare(\"MITCHELL\") == 0) {\n\t\tconst float B = cfg.GetFloat(\"path.filter.B\", 1.f \/ 3.f);\n\t\tconst float C = cfg.GetFloat(\"path.filter.C\", 1.f \/ 3.f);\n\t\tfilter = new PathOCL::MitchellFilter(filterWidthX, filterWidthY, B, C);\n\t} else\n\t\tthrow std::runtime_error(\"Unknown path.filter.type\");\n\n\tusePixelAtomics = (cfg.GetInt(\"path.pixelatomics.enable\", 0) != 0);\t\n\n\tconst unsigned int seedBase = (unsigned int)(WallClockTime() \/ 1000.0);\n\n\tfilm->EnableOverlappedScreenBufferUpdate(true);\n\n\t\/\/--------------------------------------------------------------------------\n\t\/\/ Create and start render threads\n\t\/\/--------------------------------------------------------------------------\n\n\tconst size_t renderThreadCount = intersectionDevices.size();\n\tSLG_LOG(\"Starting \"<< renderThreadCount << \" PathOCL render threads\");\n\tfor (size_t i = 0; i < renderThreadCount; ++i) {\n\t\tPathOCLRenderThread *t = new PathOCLRenderThread(i,\n\t\t\tseedBase + i * taskCount, i \/ (float)renderThreadCount,\n\t\t\t(OpenCLIntersectionDevice *)(intersectionDevices[i]),\n\t\t\tthis);\n\t\trenderThreads.push_back(t);\n\t}\n}\n\nPathOCLRenderEngine::~PathOCLRenderEngine() {\n\tif (editMode)\n\t\tEndEdit(EditActionList());\n\tif (started)\n\t\tStop();\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\tdelete renderThreads[i];\n\n\tdelete sampler;\n\tdelete filter;\n}\n\nvoid PathOCLRenderEngine::StartLockLess() {\n\tcompiledScene = new CompiledScene(renderConfig->scene, film, maxMemPageSize);\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Start();\n}\n\nvoid PathOCLRenderEngine::StopLockLess() {\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Interrupt();\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Stop();\n\n\tdelete compiledScene;\n\tcompiledScene = NULL;\n}\n\nvoid PathOCLRenderEngine::BeginEditLockLess() {\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Interrupt();\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->BeginEdit();\n}\n\nvoid PathOCLRenderEngine::EndEditLockLess(const EditActionList &editActions) {\n\tcompiledScene->Recompile(editActions);\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->EndEdit(editActions);\n}\n\nvoid PathOCLRenderEngine::UpdateFilmLockLess() {\n\tboost::unique_lock<boost::mutex> lock(*filmMutex);\n\n\tconst unsigned int imgWidth = film->GetWidth();\n\tconst unsigned int imgHeight = film->GetHeight();\n\n\tfilm->Reset();\n\n\tconst bool isAlphaChannelEnabled = film->IsAlphaChannelEnabled();\n\n\tswitch (film->GetFilterType()) {\n\t\tcase FILTER_GAUSSIAN: {\n\t\t\tfor (unsigned int y = 0; y < imgHeight; ++y) {\n\t\t\t\tunsigned int pGPU = 1 + (y + 1) * (imgWidth + 2);\n\n\t\t\t\tfor (unsigned int x = 0; x < imgWidth; ++x) {\n\t\t\t\t\tSpectrum c;\n\t\t\t\t\tfloat alpha = 0.0f;\n\t\t\t\t\tfloat count = 0.f;\n\t\t\t\t\tfor (size_t i = 0; i < renderThreads.size(); ++i) {\n\t\t\t\t\t\tif (renderThreads[i]->frameBuffer) {\n\t\t\t\t\t\t\tc += renderThreads[i]->frameBuffer[pGPU].c;\n\t\t\t\t\t\t\tcount += renderThreads[i]->frameBuffer[pGPU].count;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (renderThreads[i]->alphaFrameBuffer)\n\t\t\t\t\t\t\talpha += renderThreads[i]->alphaFrameBuffer[pGPU].alpha;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((count > 0) && !c.IsNaN()) {\n\t\t\t\t\t\tc \/= count;\n\t\t\t\t\t\tfilm->AddSampleCount(1.f);\n\t\t\t\t\t\t\/\/ -.5f is to align correctly the pixel after the splat\n\t\t\t\t\t\tfilm->SplatFiltered(PER_PIXEL_NORMALIZED, x - .5f, y - .5f, c);\n\n\t\t\t\t\t\tif (isAlphaChannelEnabled && !isnan(alpha))\n\t\t\t\t\t\t\tfilm->SplatFilteredAlpha(x - .5f, y - .5f, alpha \/ count);\n\t\t\t\t\t}\n\n\t\t\t\t\t++pGPU;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase FILTER_NONE: {\n\t\t\tfor (unsigned int y = 0; y < imgHeight; ++y) {\n\t\t\t\tunsigned int pGPU = 1 + (y + 1) * (imgWidth + 2);\n\n\t\t\t\tfor (unsigned int x = 0; x < imgWidth; ++x) {\n\t\t\t\t\tSpectrum c;\n\t\t\t\t\tfloat alpha = 0.0f;\n\t\t\t\t\tfloat count = 0.f;\n\t\t\t\t\tfor (size_t i = 0; i < renderThreads.size(); ++i) {\n\t\t\t\t\t\tif (renderThreads[i]->frameBuffer) {\n\t\t\t\t\t\t\tc += renderThreads[i]->frameBuffer[pGPU].c;\n\t\t\t\t\t\t\tcount += renderThreads[i]->frameBuffer[pGPU].count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (renderThreads[i]->alphaFrameBuffer)\n\t\t\t\t\t\t\talpha += renderThreads[i]->alphaFrameBuffer[pGPU].alpha;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((count > 0) && !c.IsNaN()) {\n\t\t\t\t\t\tfilm->AddSampleCount(1.f);\n\t\t\t\t\t\tfilm->AddRadiance(PER_PIXEL_NORMALIZED, x, y, c \/ count, count);\n\n\t\t\t\t\t\tif (isAlphaChannelEnabled && !isnan(alpha))\n\t\t\t\t\t\t\tfilm->AddAlpha(x, y, alpha \/ count, 1.f);\n\t\t\t\t\t}\n\n\t\t\t\t\t++pGPU;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tassert (false);\n\t\t\tbreak;\n\t}\n}\n\nvoid PathOCLRenderEngine::UpdateCounters() {\n\t\/\/ Update the sample count statistic\n\tunsigned long long totalCount = 0;\n\tfor (size_t i = 0; i < renderThreads.size(); ++i) {\n\t\tPathOCL::GPUTaskStats *stats = renderThreads[i]->gpuTaskStats;\n\n\t\tfor (size_t i = 0; i < taskCount; ++i)\n\t\t\ttotalCount += stats[i].sampleCount;\n\t}\n\n\tsamplesCount = totalCount;\n\n\t\/\/ Update the ray count statistic\n\ttotalCount = 0.0;\n\tfor (size_t i = 0; i < intersectionDevices.size(); ++i)\n\t\ttotalCount += intersectionDevices[i]->GetTotalRaysCount();\n\traysCount = totalCount;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n#define DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n\n#include <vector>\n\n#include <dune\/common\/dynmatrix.hh>\n#include <dune\/common\/dynvector.hh>\n\n#include <dune\/stuff\/common\/matrix.hh>\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n\n#include <dune\/gdt\/localoperator\/interface.hh>\n#include <dune\/gdt\/localfunctional\/interface.hh>\n#include <dune\/gdt\/space\/interface.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace LocalAssembler {\n\n\n\/\/ forward, to be used in the traits\ntemplate <class LocalOperatorImp>\nclass Codim0Matrix;\n\n\ntemplate <class LocalOperatorImp>\nclass Codim0MatrixTraits\n{\npublic:\n typedef Codim0Matrix<LocalOperatorImp> derived_type;\n typedef LocalOperator::Codim0Interface<typename LocalOperatorImp::Traits> LocalOperatorType;\n}; \/\/ class LocalAssemblerCodim0MatrixTraits\n\n\ntemplate <class LocalOperatorImp>\nclass Codim0Matrix\n{\npublic:\n typedef Codim0MatrixTraits<LocalOperatorImp> Traits;\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n\n Codim0Matrix(const LocalOperatorType& op)\n : localOperator_(op)\n {\n }\n\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\nprivate:\n static const size_t numTmpObjectsRequired_ = 1;\n\npublic:\n std::vector<size_t> numTmpObjectsRequired() const\n {\n return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};\n }\n\n \/**\n * \\tparam T Traits of the SpaceInterface implementation, representing the type of testSpace\n * \\tparam A Traits of the SpaceInterface implementation, representing the type of ansatzSpace\n * \\tparam EntityType A model of Dune::Entity< 0 >\n * \\tparam M Traits of the Dune::Stuff::LA::Container::MatrixInterface implementation, representing the\n * type of systemMatrix\n * \\tparam R RangeFieldType, i.e. double\n *\/\n template <class T, class A, class EntityType, class M, class R>\n void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace, const EntityType& entity,\n Dune::Stuff::LA::MatrixInterface<M>& systemMatrix,\n std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,\n std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const\n {\n \/\/ check\n assert(tmpLocalMatricesContainer.size() >= 1);\n assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);\n assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());\n assert(tmpIndicesContainer.size() >= 2);\n \/\/ get and clear matrix\n Dune::DynamicMatrix<R>& localMatrix = tmpLocalMatricesContainer[0][0];\n Dune::Stuff::Common::clear(localMatrix);\n auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];\n \/\/ apply local operator (result is in localMatrix)\n localOperator_.apply(\n testSpace.base_function_set(entity), ansatzSpace.base_function_set(entity), localMatrix, tmpOperatorMatrices);\n \/\/ write local matrix to global\n Dune::DynamicVector<size_t>& globalRows = tmpIndicesContainer[0];\n Dune::DynamicVector<size_t>& globalCols = tmpIndicesContainer[1];\n const size_t rows = testSpace.mapper().numDofs(entity);\n const size_t cols = ansatzSpace.mapper().numDofs(entity);\n assert(globalRows.size() >= rows);\n assert(globalCols.size() >= cols);\n testSpace.mapper().globalIndices(entity, globalRows);\n ansatzSpace.mapper().globalIndices(entity, globalCols);\n for (size_t ii = 0; ii < rows; ++ii) {\n const auto& localRow = localMatrix[ii];\n const size_t globalII = globalRows[ii];\n for (size_t jj = 0; jj < cols; ++jj) {\n const size_t globalJJ = globalCols[jj];\n systemMatrix.add_to_entry(globalII, globalJJ, localRow[jj]);\n }\n } \/\/ write local matrix to global\n } \/\/ ... assembleLocal(...)\n\nprivate:\n const LocalOperatorType& localOperator_;\n}; \/\/ class LocalAssemblerCodim0Matrix\n\n\n\/\/ forward, to be used in the traits\ntemplate <class LocalOperatorImp>\nclass Codim0Vector;\n\n\ntemplate <class LocalFunctionalImp>\nclass Codim0VectorTraits\n{\npublic:\n typedef Codim0Vector<LocalFunctionalImp> derived_type;\n typedef LocalFunctional::Codim0Interface<typename LocalFunctionalImp::Traits> LocalFunctionalType;\n}; \/\/ class LocalAssemblerCodim0MatrixTraits\n\n\ntemplate <class LocalFunctionalImp>\nclass Codim0Vector\n{\npublic:\n typedef Codim0VectorTraits<LocalFunctionalImp> Traits;\n typedef typename Traits::LocalFunctionalType LocalFunctionalType;\n\n Codim0Vector(const LocalFunctionalType& func)\n : localFunctional_(func)\n {\n }\n\n const LocalFunctionalType& localFunctional() const\n {\n return localFunctional_;\n }\n\nprivate:\n static const size_t numTmpObjectsRequired_ = 1;\n\npublic:\n std::vector<size_t> numTmpObjectsRequired() const\n {\n return {numTmpObjectsRequired_, localFunctional_.numTmpObjectsRequired()};\n }\n\n \/**\n * \\tparam T Traits of the SpaceInterface implementation, representing the type of testSpace\n * \\tparam EntityType A model of Dune::Entity< 0 >\n * \\tparam V Traits of the Dune::Stuff::LA::Container::VectorInterface implementation, representing the\n * type of systemVector\n * \\tparam R RangeFieldType, i.e. double\n *\/\n template <class T, class EntityType, class V, class R>\n void assembleLocal(const SpaceInterface<T>& testSpace, const EntityType& entity,\n Dune::Stuff::LA::VectorInterface<V>& systemVector,\n std::vector<std::vector<Dune::DynamicVector<R>>>& tmpLocalVectorContainer,\n Dune::DynamicVector<size_t>& tmpIndices) const\n {\n \/\/ check\n assert(tmpLocalVectorContainer.size() >= 1);\n assert(tmpLocalVectorContainer[0].size() >= numTmpObjectsRequired_);\n assert(tmpLocalVectorContainer[1].size() >= localFunctional_.numTmpObjectsRequired());\n \/\/ get and clear vector\n auto& localVector = tmpLocalVectorContainer[0][0];\n Dune::Stuff::Common::clear(localVector);\n auto& tmpFunctionalVectors = tmpLocalVectorContainer[1];\n \/\/ apply local functional (result is in localVector)\n localFunctional_.apply(testSpace.base_function_set(entity), localVector, tmpFunctionalVectors);\n \/\/ write local vector to global\n const size_t size = testSpace.mapper().numDofs(entity);\n assert(tmpIndices.size() >= size);\n testSpace.mapper().globalIndices(entity, tmpIndices);\n for (size_t ii = 0; ii < size; ++ii) {\n systemVector.add_to_entry(tmpIndices[ii], localVector[ii]);\n } \/\/ write local matrix to global\n } \/\/ ... assembleLocal(...)\n\nprivate:\n const LocalFunctionalType& localFunctional_;\n}; \/\/ class Codim0Vector\n\n\n} \/\/ namespace LocalAssembler\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n<commit_msg>[assembler.local.codim0] minor fix<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n#define DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n\n#include <vector>\n\n#include <dune\/common\/dynmatrix.hh>\n#include <dune\/common\/dynvector.hh>\n\n#include <dune\/stuff\/common\/matrix.hh>\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n\n#include <dune\/gdt\/localoperator\/interface.hh>\n#include <dune\/gdt\/localfunctional\/interface.hh>\n#include <dune\/gdt\/space\/interface.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace LocalAssembler {\n\n\n\/\/ forward, to be used in the traits\ntemplate <class LocalOperatorImp>\nclass Codim0Matrix;\n\n\ntemplate <class LocalOperatorImp>\nclass Codim0MatrixTraits\n{\npublic:\n typedef Codim0Matrix<LocalOperatorImp> derived_type;\n typedef LocalOperator::Codim0Interface<typename LocalOperatorImp::Traits> LocalOperatorType;\n}; \/\/ class LocalAssemblerCodim0MatrixTraits\n\n\ntemplate <class LocalOperatorImp>\nclass Codim0Matrix\n{\npublic:\n typedef Codim0MatrixTraits<LocalOperatorImp> Traits;\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n\n Codim0Matrix(const LocalOperatorType& op)\n : localOperator_(op)\n {\n }\n\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\nprivate:\n static const size_t numTmpObjectsRequired_ = 1;\n\npublic:\n std::vector<size_t> numTmpObjectsRequired() const\n {\n return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};\n }\n\n \/**\n * \\tparam T Traits of the SpaceInterface implementation, representing the type of testSpace\n * \\tparam A Traits of the SpaceInterface implementation, representing the type of ansatzSpace\n * \\tparam EntityType A model of Dune::Entity< 0 >\n * \\tparam M Traits of the Dune::Stuff::LA::Container::MatrixInterface implementation, representing the\n * type of systemMatrix\n * \\tparam R RangeFieldType, i.e. double\n *\/\n template <class T, class A, class EntityType, class M, class R>\n void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace, const EntityType& entity,\n Dune::Stuff::LA::MatrixInterface<M>& systemMatrix,\n std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,\n std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const\n {\n \/\/ check\n assert(tmpLocalMatricesContainer.size() >= 1);\n assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);\n assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());\n assert(tmpIndicesContainer.size() >= 2);\n \/\/ get and clear matrix\n Dune::DynamicMatrix<R>& localMatrix = tmpLocalMatricesContainer[0][0];\n Dune::Stuff::Common::clear(localMatrix);\n auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];\n \/\/ apply local operator (result is in localMatrix)\n localOperator_.apply(\n testSpace.base_function_set(entity), ansatzSpace.base_function_set(entity), localMatrix, tmpOperatorMatrices);\n \/\/ write local matrix to global\n Dune::DynamicVector<size_t>& globalRows = tmpIndicesContainer[0];\n Dune::DynamicVector<size_t>& globalCols = tmpIndicesContainer[1];\n const size_t rows = testSpace.mapper().numDofs(entity);\n const size_t cols = ansatzSpace.mapper().numDofs(entity);\n assert(globalRows.size() >= rows);\n assert(globalCols.size() >= cols);\n testSpace.mapper().globalIndices(entity, globalRows);\n ansatzSpace.mapper().globalIndices(entity, globalCols);\n for (size_t ii = 0; ii < rows; ++ii) {\n const auto& localRow = localMatrix[ii];\n const size_t globalII = globalRows[ii];\n for (size_t jj = 0; jj < cols; ++jj) {\n const size_t globalJJ = globalCols[jj];\n systemMatrix.add_to_entry(globalII, globalJJ, localRow[jj]);\n }\n } \/\/ write local matrix to global\n } \/\/ ... assembleLocal(...)\n\nprivate:\n const LocalOperatorType& localOperator_;\n}; \/\/ class LocalAssemblerCodim0Matrix\n\n\n\/\/ forward, to be used in the traits\ntemplate <class LocalOperatorImp>\nclass Codim0Vector;\n\n\ntemplate <class LocalFunctionalImp>\nclass Codim0VectorTraits\n{\npublic:\n typedef Codim0Vector<LocalFunctionalImp> derived_type;\n typedef LocalFunctional::Codim0Interface<typename LocalFunctionalImp::Traits> LocalFunctionalType;\n}; \/\/ class LocalAssemblerCodim0MatrixTraits\n\n\ntemplate <class LocalFunctionalImp>\nclass Codim0Vector\n{\npublic:\n typedef Codim0VectorTraits<LocalFunctionalImp> Traits;\n typedef typename Traits::LocalFunctionalType LocalFunctionalType;\n\n Codim0Vector(const LocalFunctionalType& func)\n : localFunctional_(func)\n {\n }\n\n const LocalFunctionalType& localFunctional() const\n {\n return localFunctional_;\n }\n\nprivate:\n static const size_t numTmpObjectsRequired_ = 1;\n\npublic:\n std::vector<size_t> numTmpObjectsRequired() const\n {\n return {numTmpObjectsRequired_, localFunctional_.numTmpObjectsRequired()};\n }\n\n \/**\n * \\tparam T Traits of the SpaceInterface implementation, representing the type of testSpace\n * \\tparam EntityType A model of Dune::Entity< 0 >\n * \\tparam V Traits of the Dune::Stuff::LA::Container::VectorInterface implementation, representing the\n * type of systemVector\n * \\tparam R RangeFieldType, i.e. double\n *\/\n template <class T, class EntityType, class V, class R>\n void assembleLocal(const SpaceInterface<T>& testSpace, const EntityType& entity,\n Dune::Stuff::LA::VectorInterface<V>& systemVector,\n std::vector<std::vector<Dune::DynamicVector<R>>>& tmpLocalVectorContainer,\n Dune::DynamicVector<size_t>& tmpIndices) const\n {\n \/\/ check\n assert(tmpLocalVectorContainer.size() >= 2);\n assert(tmpLocalVectorContainer[0].size() >= numTmpObjectsRequired_);\n assert(tmpLocalVectorContainer[1].size() >= localFunctional_.numTmpObjectsRequired());\n \/\/ get and clear vector\n auto& localVector = tmpLocalVectorContainer[0][0];\n Dune::Stuff::Common::clear(localVector);\n auto& tmpFunctionalVectors = tmpLocalVectorContainer[1];\n \/\/ apply local functional (result is in localVector)\n localFunctional_.apply(testSpace.base_function_set(entity), localVector, tmpFunctionalVectors);\n \/\/ write local vector to global\n const size_t size = testSpace.mapper().numDofs(entity);\n assert(tmpIndices.size() >= size);\n testSpace.mapper().globalIndices(entity, tmpIndices);\n for (size_t ii = 0; ii < size; ++ii) {\n systemVector.add_to_entry(tmpIndices[ii], localVector[ii]);\n } \/\/ write local matrix to global\n } \/\/ ... assembleLocal(...)\n\nprivate:\n const LocalFunctionalType& localFunctional_;\n}; \/\/ class Codim0Vector\n\n\n} \/\/ namespace LocalAssembler\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-pymor project:\n\/\/ https:\/\/github.com\/pyMor\/dune-pymor\n\/\/ Copyright Holders: Felix Albrecht, Stephan Rave\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_PYMOR_OPERATORS_INTERFACES_HH\n#define DUNE_PYMOR_OPERATORS_INTERFACES_HH\n\n#include <dune\/pymor\/common\/exceptions.hh>\n#include <dune\/pymor\/parameters\/base.hh>\n#include <dune\/pymor\/la\/container\/interfaces.hh>\n#include <dune\/pymor\/la\/container.hh>\n\nnamespace Dune {\nnamespace Pymor {\n\n\nclass OperatorInterface\n : public Parametric\n{\npublic:\n template< class... Args >\n OperatorInterface(Args&& ...args)\n : Parametric(std::forward< Args >(args)...)\n {}\n\n virtual ~OperatorInterface() {}\n\n virtual bool linear() const = 0;\n\n virtual unsigned int dim_source() const = 0;\n\n virtual unsigned int dim_range() const = 0;\n\n virtual std::string type_source() const = 0;\n\n virtual std::string type_range() const = 0;\n\n virtual void apply(const LA::VectorInterface* \/*source*\/,\n LA::VectorInterface* \/*range*\/,\n const Parameter \/*mu*\/ = Parameter()) const throw (Exception::types_are_not_compatible,\n Exception::you_have_to_implement_this,\n Exception::sizes_do_not_match,\n Exception::wrong_parameter_type,\n Exception::requirements_not_met) = 0;\n\n virtual LA::VectorInterface* apply(const LA::VectorInterface* source, const Parameter mu = Parameter()) const\n throw (Exception::types_are_not_compatible,\n Exception::you_have_to_implement_this,\n Exception::sizes_do_not_match,\n Exception::wrong_parameter_type)\n {\n DUNE_PYMOR_THROW(Exception::types_are_not_compatible,\n \"source (\" << source->type() << \") is not a compatible type_source (\" << type_source() << \")!\");\n LA::VectorInterface* ret = LA::createVector(type_range(), dim_range());\n apply(source, ret, mu);\n return ret;\n }\n\n virtual double apply2(const LA::VectorInterface* range,\n const LA::VectorInterface* source,\n const Parameter mu = Parameter()) const throw (Exception::types_are_not_compatible,\n Exception::sizes_do_not_match,\n Exception::wrong_parameter_type)\n {\n std::stringstream msg;\n size_t throw_up = 0;\n if (source->type() != type_source()) {\n msg << \"source (\" << source->type() << \") is not a compatible type_source (\" << type_source() << \")\";\n ++throw_up;\n }\n if (range->type() != type_range()) {\n if (throw_up)\n msg << \" and \";\n msg << \"range (\" << range->type() << \") is not a compatible type_range (\" << type_range() << \")\";\n }\n if (throw_up) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, msg.str() << \"!\");\n if (source->dim() != dim_source())\n DUNE_PYMOR_THROW(Exception::sizes_do_not_match,\n \"dim of source (\" << source->dim() << \") does not match dim_source of this (\" << dim_source()\n << \")!\");\n if (range->dim() != dim_range())\n DUNE_PYMOR_THROW(Exception::sizes_do_not_match,\n \"dim of range (\" << range->dim() << \") does not match dim_range of this (\" << dim_range()\n << \")!\");\n LA::VectorInterface* tmp = apply(source, mu);\n return range->dot(tmp);\n }\n\n virtual OperatorInterface* freeze_parameter(const Parameter \/*mu*\/ = Parameter()) const\n throw (Exception::this_is_not_parametric, Exception::you_have_to_implement_this)\n {\n DUNE_PYMOR_THROW(Exception::you_have_to_implement_this, \"you really do!\");\n }\n}; \/\/ class OperatorInterface\n\n\n} \/\/ namespace Pymor\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_PYMOR_OPERATORS_INTERFACES_HH\n<commit_msg>[operators.interface] removed 'range = apply(source)'<commit_after>\/\/ This file is part of the dune-pymor project:\n\/\/ https:\/\/github.com\/pyMor\/dune-pymor\n\/\/ Copyright Holders: Felix Albrecht, Stephan Rave\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_PYMOR_OPERATORS_INTERFACES_HH\n#define DUNE_PYMOR_OPERATORS_INTERFACES_HH\n\n#include <dune\/pymor\/common\/exceptions.hh>\n#include <dune\/pymor\/parameters\/base.hh>\n#include <dune\/pymor\/la\/container\/interfaces.hh>\n#include <dune\/pymor\/la\/container.hh>\n\nnamespace Dune {\nnamespace Pymor {\n\n\nclass OperatorInterface\n : public Parametric\n{\npublic:\n template< class... Args >\n OperatorInterface(Args&& ...args)\n : Parametric(std::forward< Args >(args)...)\n {}\n\n virtual ~OperatorInterface() {}\n\n virtual bool linear() const = 0;\n\n virtual unsigned int dim_source() const = 0;\n\n virtual unsigned int dim_range() const = 0;\n\n virtual std::string type_source() const = 0;\n\n virtual std::string type_range() const = 0;\n\n virtual void apply(const LA::VectorInterface* \/*source*\/,\n LA::VectorInterface* \/*range*\/,\n const Parameter \/*mu*\/ = Parameter()) const throw (Exception::types_are_not_compatible,\n Exception::you_have_to_implement_this,\n Exception::sizes_do_not_match,\n Exception::wrong_parameter_type,\n Exception::requirements_not_met) = 0;\n\n virtual double apply2(const LA::VectorInterface* range,\n const LA::VectorInterface* source,\n const Parameter mu = Parameter()) const throw (Exception::types_are_not_compatible,\n Exception::sizes_do_not_match,\n Exception::wrong_parameter_type)\n {\n std::stringstream msg;\n size_t throw_up = 0;\n if (source->type() != type_source()) {\n msg << \"source (\" << source->type() << \") is not a compatible type_source (\" << type_source() << \")\";\n ++throw_up;\n }\n if (range->type() != type_range()) {\n if (throw_up)\n msg << \" and \";\n msg << \"range (\" << range->type() << \") is not a compatible type_range (\" << type_range() << \")\";\n }\n if (throw_up) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, msg.str() << \"!\");\n if (source->dim() != dim_source())\n DUNE_PYMOR_THROW(Exception::sizes_do_not_match,\n \"dim of source (\" << source->dim() << \") does not match dim_source of this (\" << dim_source()\n << \")!\");\n if (range->dim() != dim_range())\n DUNE_PYMOR_THROW(Exception::sizes_do_not_match,\n \"dim of range (\" << range->dim() << \") does not match dim_range of this (\" << dim_range()\n << \")!\");\n LA::VectorInterface* tmp = LA::createVector(type_range(), dim_range());\n apply(source, tmp, mu);\n return range->dot(tmp);\n }\n\n virtual OperatorInterface* freeze_parameter(const Parameter \/*mu*\/ = Parameter()) const\n throw (Exception::this_is_not_parametric, Exception::you_have_to_implement_this)\n {\n DUNE_PYMOR_THROW(Exception::you_have_to_implement_this, \"you really do!\");\n }\n}; \/\/ class OperatorInterface\n\n\n} \/\/ namespace Pymor\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_PYMOR_OPERATORS_INTERFACES_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_FEM_FUNCTIONS_CUSTOMPROJECTION_HH\n#define DUNE_STUFF_FEM_FUNCTIONS_CUSTOMPROJECTION_HH\n\n#if HAVE_DUNE_FEM\n\n#include <dune\/fem\/quadrature\/cachingquadrature.hh>\n#include <dune\/fem\/function\/common\/discretefunction.hh>\n#include <dune\/fem\/function\/common\/gridfunctionadapter.hh>\n#include <dune\/fem\/operator\/common\/operator.hh>\n\n#include <dune\/stuff\/common\/math.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n\n#include \"localmassmatrix.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Fem {\n\n \/** A custom projection of an analytical function that uses a non-standard evalute signature:\\n\n * <pre>template < class IntersectionIteratorType >\\n\n * void evaluate( const DomainType& arg, RangeType& ret, const IntersectionIteratorType& faceIter ) const<\/pre>\\n\n * \\note example being our boundary functions\n * \\note output currently somewhat meaningless\n * \\see analyticaldata.hh\n **\/\nclass CustomProjection\n{\npublic:\n template< class OriginFunctionType, class DestinationFunctionType >\n static void project(const OriginFunctionType& f, DestinationFunctionType& discFunc) {\n typedef Dune::Fem::CachingQuadrature< typename DestinationFunctionType::DiscreteFunctionSpaceType::GridPartType, 1 >\n FaceQuadratureType;\n const auto& space_ = discFunc.space();\n const auto& gridPart_ = space_.gridPart();\n typename DestinationFunctionType::DiscreteFunctionSpaceType::RangeType phi(0.0);\n\n for (const auto& e : space_)\n {\n auto lf = discFunc.localFunction(e);\n auto baseFunctionset = space_.baseFunctionSet(e);\n size_t intersection_count = 0;\n const auto intItEnd = gridPart_.iend(e);\n for (auto intIt = gridPart_.ibegin(e);\n intIt != intItEnd;\n ++intIt)\n {\n intersection_count++;\n FaceQuadratureType faceQuadrature(gridPart_,\n *intIt,\n ( 4 * space_.order() ) + 1,\n FaceQuadratureType::INSIDE);\n typename DestinationFunctionType::RangeType ret;\n for (size_t qP = 0; qP < faceQuadrature.nop(); ++qP)\n {\n const double intel\n = faceQuadrature.weight(qP) * e.geometry().integrationElement( faceQuadrature.point(qP) ); \/\/ general case\n\n if ( intIt->boundary() )\n {\n f.evaluate(faceQuadrature.point(qP), ret, *intIt);\n\n for (size_t i = 0; i < baseFunctionset.size(); ++i)\n {\n baseFunctionset.evaluate(i, faceQuadrature[qP], phi);\n lf[i] += intel * (ret * phi);\n }\n }\n }\n }\n }\n } \/\/ project\n};\n\n\/\/! basically the fem L2Projection with a function evaluate that converts between compatible types instead of failing\nclass BetterL2Projection\n{\nprotected:\n template< class FunctionType >\n struct DefaultEvaluationFunctor;\n\npublic:\n template< class FunctionImp, class DiscreteFunctionImp >\n static void project(const FunctionImp& func,\n DiscreteFunctionImp& discFunc,\n int polOrd = -1)\n {\n static_assert(!(Conversion< FunctionImp, Dune::Fem::IsDiscreteFunction >::exists),\n \"TimeAwareL2Projection_not_implemented_for_discrete_source_functions\");\n DefaultEvaluationFunctor< FunctionImp > functor(func);\n projectCommon(functor, discFunc, polOrd);\n }\n\n template< class TimeProviderType, class FunctionImp, class DiscreteFunctionImp >\n static void project(const TimeProviderType& timeProvider,\n const FunctionImp& func,\n DiscreteFunctionImp& discFunc,\n int polOrd = -1)\n {\n static_assert(!(Conversion< FunctionImp, Dune::Fem::IsDiscreteFunction >::exists),\n \"TimeAwareL2Projection_not_implemented_for_discrete_source_functions\");\n TimeEvaluationFunctor< FunctionImp, TimeProviderType > functor(func, timeProvider);\n projectCommon(functor, discFunc, polOrd);\n }\n\nprotected:\n template< class FunctionType >\n struct DefaultEvaluationFunctor\n {\n const FunctionType& function_;\n DefaultEvaluationFunctor(const FunctionType& function)\n : function_(function)\n {}\n\n void evaluate(const typename FunctionType::DomainType& arg, typename FunctionType::RangeType& ret) const {\n function_.evaluate(arg, ret);\n }\n };\n template< class FunctionType, class TimeProviderType >\n struct TimeEvaluationFunctor\n {\n const FunctionType& function_;\n const TimeProviderType& timeProvider_;\n TimeEvaluationFunctor(const FunctionType& function,\n const TimeProviderType& timeProvider)\n : function_(function)\n , timeProvider_(timeProvider)\n {}\n void evaluate(const typename FunctionType::DomainType& arg, typename FunctionType::RangeType& ret) const {\n function_.evaluate(timeProvider_.subTime(), arg, ret);\n }\n };\n template< class FunctionType >\n struct TimeEvaluationFunctor< FunctionType, double >\n {\n const FunctionType& function_;\n const double time_;\n TimeEvaluationFunctor(const FunctionType& function,\n const double time)\n : function_(function)\n , time_(time)\n {}\n void evaluate(const typename FunctionType::DomainType& arg, typename FunctionType::RangeType& ret) const {\n function_.evaluate(time_, arg, ret);\n }\n };\n\n template< class DiscreteFunctionImp, class EvaluationFunctorType >\n static void projectCommon(const EvaluationFunctorType& evalutionFunctor,\n DiscreteFunctionImp& discFunc,\n int polOrd = -1) {\n typedef typename DiscreteFunctionImp::DiscreteFunctionSpaceType DiscreteFunctionSpaceType;\n typedef typename DiscreteFunctionSpaceType::Traits::GridPartType GridPartType;\n typedef Dune::Fem::CachingQuadrature< GridPartType, 0 > QuadratureType;\n\n typename DiscreteFunctionSpaceType::RangeType ret(0.0);\n typename DiscreteFunctionSpaceType::RangeType phi(0.0);\n const auto& space = discFunc.space();\n const auto quadOrd = std::max(2 * space.order() + 2, polOrd);\n const Dune::Fem::LocalMassMatrix< DiscreteFunctionSpaceType, QuadratureType > massMatrix(space, quadOrd);\n const bool affineMapping = massMatrix.affine();\n discFunc.clear();\n\n for (const auto& en : space)\n {\n const auto& geo = en.geometry();\n const QuadratureType quad(en, quadOrd);\n auto lf = discFunc.localFunction(en);\n const auto& baseset = lf.baseFunctionSet();\n const auto quadNop = quad.nop();\n const auto numDofs = lf.numDofs();\n for (decltype(quadNop) qP = 0; qP < quadNop; ++qP)\n {\n const double intel = (affineMapping) ?\n quad.weight(qP) : \/\/ affine case\n quad.weight(qP) * geo.integrationElement( quad.point(qP) ); \/\/ general case\n\n const auto x = geo.global( quad.point(qP) );\n evalutionFunctor.evaluate(x, ret);\n for (decltype(numDofs) i = 0; i < numDofs; ++i)\n {\n baseset.evaluate(i, quad[qP], phi);\n lf[i] += intel * (ret * phi);\n }\n }\n \/\/ in case of non-linear mapping apply inverse\n if (!affineMapping)\n {\n massMatrix.applyInverse(en, lf);\n }\n }\n } \/\/ projectCommon\n};\n\nnamespace Experimental {\n\ntemplate< int dim, class RangeType, class JacobianRangeType >\nstruct GradientJacobianToLaplacian\n : public RangeType\n{\n GradientJacobianToLaplacian(const JacobianRangeType& \/*jacobian*\/) {\n \/\/ Dune::CompileTimeChecker< ( dim == 1 || dim > 3 ) > NotImplemented;\n static_assert( (dim == 1 || dim > 3), \"GradientJacobianToLaplacian not implemented for this dimension!\" );\n }\n};\n\ntemplate< class RangeType, class JacobianRangeType >\nstruct GradientJacobianToLaplacian< 2, RangeType, JacobianRangeType >\n : public RangeType\n{\n GradientJacobianToLaplacian(const JacobianRangeType& jacobian) {\n (*this)[0] = jacobian[0][0];\n (*this)[1] = jacobian[3][1];\n }\n};\n\ntemplate< class RangeType, class JacobianRangeType >\nstruct GradientJacobianToLaplacian< 3, RangeType, JacobianRangeType >\n : public RangeType\n{\n GradientJacobianToLaplacian(const JacobianRangeType& jacobian) {\n (*this)[0] = jacobian[0][0];\n (*this)[1] = jacobian[4][1];\n (*this)[2] = jacobian[8][2];\n }\n};\n\ntemplate< class TimeProviderType,\n class DiscreteVelocityFunctionType,\n class SigmaFunctionType >\nclass GradientAdapterFunction\n : public SigmaFunctionType\n{\nprotected:\n typedef GradientAdapterFunction< TimeProviderType,\n DiscreteVelocityFunctionType,\n SigmaFunctionType >\n ThisType;\n typedef SigmaFunctionType\n BaseType;\n const TimeProviderType& timeProvider_;\n\npublic:\n GradientAdapterFunction(const TimeProviderType& timeProvider,\n const DiscreteVelocityFunctionType& velocity,\n SigmaFunctionType& dummy,\n int polOrd = -1)\n : BaseType( \"grad\", dummy.space() )\n , timeProvider_(timeProvider) {\n typedef SigmaFunctionType\n DiscreteFunctionType;\n typedef typename SigmaFunctionType::DiscreteFunctionSpaceType\n DiscreteFunctionSpaceType;\n typedef typename DiscreteFunctionType::LocalFunctionType\n LocalFuncType;\n typedef typename DiscreteFunctionSpaceType::Traits::GridPartType\n GridPartType;\n typedef typename DiscreteFunctionSpaceType::Traits::IteratorType\n Iterator;\n typedef typename DiscreteFunctionSpaceType::BaseFunctionSetType\n BaseFunctionSetType;\n\/\/ typedef typename GridPartType::IntersectionIteratorType\n\/\/ IntersectionIteratorType;\n typedef typename DiscreteVelocityFunctionType::LocalFunctionType\n LocalFType;\n\n const DiscreteFunctionSpaceType space( velocity.space().gridPart() );\n const GridPartType& gridPart = space.gridPart();\n \/\/ type of quadrature\n typedef Dune::Fem::CachingQuadrature< GridPartType, 0 > VolumeQuadratureType;\n\/\/ typedef Dune::Fem::CachingQuadrature< GridPartType, 1 > FaceQuadratureType;\n \/\/ type of local mass matrix\n typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType, VolumeQuadratureType > LocalMassMatrixType;\n\n const auto quadOrd = std::max(2 * space.order() + 2, polOrd);\n\n \/\/ create local mass matrix object\n LocalMassMatrixType massMatrix(space, quadOrd);\n\n \/\/ check whether geometry mappings are affine or not\n const bool affineMapping = massMatrix.affine();\n\n \/\/ clear destination\n BaseType::clear();\n\n const Iterator endit = space.end();\n for (Iterator it = space.begin(); it != endit; ++it)\n {\n \/\/ get entity\n const typename GridPartType::GridType::template Codim< 0 >::Entity& entity = *it;\n \/\/ get geometry\n typedef typename GridPartType::GridType::template Codim< 0 >::Geometry\n Geometry;\n const Geometry& geo = entity.geometry();\n\n \/\/ get quadrature\n VolumeQuadratureType quad(entity, quadOrd);\n\n \/\/ get local function of destination\n LocalFuncType self_local = BaseType::localFunction(entity);\n \/\/ get local function of argument\n const LocalFType velocity_local = velocity.localFunction(entity);\n\n \/\/ get base function set\n const BaseFunctionSetType& baseset = self_local.baseFunctionSet();\n\n const auto quadNop = quad.nop();\n const auto numDofs = self_local.numDofs();\n\n \/\/ volume part\n for (decltype(quadNop) qP = 0; qP < quadNop; ++qP)\n {\n const typename DiscreteFunctionSpaceType::DomainType xLocal = quad.point(qP);\n\n const double intel = (affineMapping) ?\n quad.weight(qP) : \/\/ affine case\n quad.weight(qP) * geo.integrationElement(xLocal); \/\/ general case\n\n typename DiscreteFunctionSpaceType::DomainType\n xWorld = geo.global(xLocal);\n\n \/\/ evaluate function\n typename DiscreteVelocityFunctionType::DiscreteFunctionSpaceType::RangeType\n velocity_eval;\n velocity_local.evaluate(quad[qP], velocity_eval);\n\n typename DiscreteVelocityFunctionType::DiscreteFunctionSpaceType::JacobianRangeType\n velocity_jacobian_eval;\n velocity_local.jacobian(quad[qP], velocity_jacobian_eval);\n\n \/\/ do projection\n for (int i = 0; i < numDofs; ++i)\n {\n typename DiscreteFunctionType::DiscreteFunctionSpaceType::RangeType phi(0.0);\n baseset.evaluate(i, quad[qP], phi);\n self_local[i] += intel * ( Dune::Stuff::Common::colonProduct(velocity_jacobian_eval, phi) );\n }\n }\n\n \/\/ in case of non-linear mapping apply inverse\n if (!affineMapping)\n {\n massMatrix.applyInverse(entity, self_local);\n }\n }\n }\n};\n\n} \/\/ namespace Experimental\n\n} \/\/ namespace Fem\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ HAVE_DUNE_FEM\n\n#endif \/\/ DUNE_STUFF_FEM_FUNCTIONS_CUSTOMPROJECTION_HH\n<commit_msg>[fem.customprojection] refs #10<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_FEM_FUNCTIONS_CUSTOMPROJECTION_HH\n#define DUNE_STUFF_FEM_FUNCTIONS_CUSTOMPROJECTION_HH\n\n#if HAVE_DUNE_FEM\n\n#include <dune\/fem\/quadrature\/cachingquadrature.hh>\n#include <dune\/fem\/function\/common\/discretefunction.hh>\n#include <dune\/fem\/function\/common\/gridfunctionadapter.hh>\n#include <dune\/fem\/operator\/common\/operator.hh>\n\n#include <dune\/stuff\/common\/math.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n\n#include \"localmassmatrix.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Fem {\n\n \/** A custom projection of an analytical function that uses a non-standard evalute signature:\\n\n * <pre>template < class IntersectionIteratorType >\\n\n * void evaluate( const DomainType& arg, RangeType& ret, const IntersectionIteratorType& faceIter ) const<\/pre>\\n\n * \\note example being our boundary functions\n * \\note output currently somewhat meaningless\n * \\see analyticaldata.hh\n **\/\nclass CustomProjection\n{\npublic:\n template< class OriginFunctionType, class DestinationFunctionType >\n static void project(const OriginFunctionType& f, DestinationFunctionType& discFunc) {\n typedef Dune::Fem::CachingQuadrature< typename DestinationFunctionType::DiscreteFunctionSpaceType::GridPartType, 1 >\n FaceQuadratureType;\n const auto& space_ = discFunc.space();\n const auto& gridPart_ = space_.gridPart();\n typename DestinationFunctionType::DiscreteFunctionSpaceType::RangeType phi(0.0);\n\n for (const auto& e : space_)\n {\n auto lf = discFunc.localFunction(e);\n auto baseFunctionset = space_.baseFunctionSet(e);\n size_t intersection_count = 0;\n const auto intItEnd = gridPart_.iend(e);\n for (auto intIt = gridPart_.ibegin(e);\n intIt != intItEnd;\n ++intIt)\n {\n intersection_count++;\n FaceQuadratureType faceQuadrature(gridPart_,\n *intIt,\n ( 4 * space_.order() ) + 1,\n FaceQuadratureType::INSIDE);\n typename DestinationFunctionType::RangeType ret;\n for (size_t qP = 0; qP < faceQuadrature.nop(); ++qP)\n {\n const double intel\n = faceQuadrature.weight(qP) * e.geometry().integrationElement( faceQuadrature.point(qP) ); \/\/ general case\n\n if ( intIt->boundary() )\n {\n f.evaluate(faceQuadrature.point(qP), ret, *intIt);\n\n for (size_t i = 0; i < baseFunctionset.size(); ++i)\n {\n baseFunctionset.evaluate(i, faceQuadrature[qP], phi);\n lf[i] += intel * (ret * phi);\n }\n }\n }\n }\n }\n } \/\/ project\n};\n\n\/\/! basically the fem L2Projection with a function evaluate that converts between compatible types instead of failing\nclass BetterL2Projection\n{\nprotected:\n template< class FunctionType >\n struct DefaultEvaluationFunctor;\n\npublic:\n template< class FunctionImp, class DiscreteFunctionImp >\n static void project(const FunctionImp& func,\n DiscreteFunctionImp& discFunc,\n int polOrd = -1)\n {\n static_assert(!(Conversion< FunctionImp, Dune::Fem::IsDiscreteFunction >::exists),\n \"TimeAwareL2Projection_not_implemented_for_discrete_source_functions\");\n DefaultEvaluationFunctor< FunctionImp > functor(func);\n projectCommon(functor, discFunc, polOrd);\n }\n\n template< class TimeProviderType, class FunctionImp, class DiscreteFunctionImp >\n static void project(const TimeProviderType& timeProvider,\n const FunctionImp& func,\n DiscreteFunctionImp& discFunc,\n int polOrd = -1)\n {\n static_assert(!(Conversion< FunctionImp, Dune::Fem::IsDiscreteFunction >::exists),\n \"TimeAwareL2Projection_not_implemented_for_discrete_source_functions\");\n TimeEvaluationFunctor< FunctionImp, TimeProviderType > functor(func, timeProvider);\n projectCommon(functor, discFunc, polOrd);\n }\n\nprotected:\n template< class FunctionType >\n struct DefaultEvaluationFunctor\n {\n const FunctionType& function_;\n DefaultEvaluationFunctor(const FunctionType& function)\n : function_(function)\n {}\n\n void evaluate(const typename FunctionType::DomainType& arg, typename FunctionType::RangeType& ret) const {\n function_.evaluate(arg, ret);\n }\n };\n template< class FunctionType, class TimeProviderType >\n struct TimeEvaluationFunctor\n {\n const FunctionType& function_;\n const TimeProviderType& timeProvider_;\n TimeEvaluationFunctor(const FunctionType& function,\n const TimeProviderType& timeProvider)\n : function_(function)\n , timeProvider_(timeProvider)\n {}\n void evaluate(const typename FunctionType::DomainType& arg, typename FunctionType::RangeType& ret) const {\n function_.evaluate(timeProvider_.subTime(), arg, ret);\n }\n };\n template< class FunctionType >\n struct TimeEvaluationFunctor< FunctionType, double >\n {\n const FunctionType& function_;\n const double time_;\n TimeEvaluationFunctor(const FunctionType& function,\n const double time)\n : function_(function)\n , time_(time)\n {}\n void evaluate(const typename FunctionType::DomainType& arg, typename FunctionType::RangeType& ret) const {\n function_.evaluate(time_, arg, ret);\n }\n };\n\n template< class DiscreteFunctionImp, class EvaluationFunctorType >\n static void projectCommon(const EvaluationFunctorType& evalutionFunctor,\n DiscreteFunctionImp& discFunc,\n int polOrd = -1) {\n typedef typename DiscreteFunctionImp::DiscreteFunctionSpaceType DiscreteFunctionSpaceType;\n typedef typename DiscreteFunctionSpaceType::Traits::GridPartType GridPartType;\n typedef Dune::Fem::CachingQuadrature< GridPartType, 0 > QuadratureType;\n\n typename DiscreteFunctionSpaceType::RangeType ret(0.0);\n typename DiscreteFunctionSpaceType::RangeType phi(0.0);\n const auto& space = discFunc.space();\n const auto quadOrd = std::max(2 * space.order() + 2, polOrd);\n const Dune::Fem::LocalMassMatrix< DiscreteFunctionSpaceType, QuadratureType > massMatrix(space, quadOrd);\n const bool affineMapping = massMatrix.affine();\n discFunc.clear();\n\n for (const auto& en : space)\n {\n const auto& geo = en.geometry();\n const QuadratureType quad(en, quadOrd);\n auto lf = discFunc.localFunction(en);\n const auto& baseset = lf.baseFunctionSet();\n const auto quadNop = quad.nop();\n const auto numDofs = lf.numDofs();\n for (decltype(quadNop) qP = 0; qP < quadNop; ++qP)\n {\n const double intel = (affineMapping) ?\n quad.weight(qP) : \/\/ affine case\n quad.weight(qP) * geo.integrationElement( quad.point(qP) ); \/\/ general case\n\n const auto x = geo.global( quad.point(qP) );\n evalutionFunctor.evaluate(x, ret);\n for (decltype(numDofs) i = 0; i < numDofs; ++i)\n {\n baseset.evaluate(i, quad[qP], phi);\n lf[i] += intel * (ret * phi);\n }\n }\n \/\/ in case of non-linear mapping apply inverse\n if (!affineMapping)\n {\n massMatrix.applyInverse(en, lf);\n }\n }\n } \/\/ projectCommon\n};\n\nnamespace Experimental {\n\ntemplate< int dim, class RangeType, class JacobianRangeType >\nstruct GradientJacobianToLaplacian\n : public RangeType\n{\n GradientJacobianToLaplacian(const JacobianRangeType& \/*jacobian*\/) {\n \/\/ Dune::CompileTimeChecker< ( dim == 1 || dim > 3 ) > NotImplemented;\n static_assert( (dim == 1 || dim > 3), \"GradientJacobianToLaplacian not implemented for this dimension!\" );\n }\n};\n\ntemplate< class RangeType, class JacobianRangeType >\nstruct GradientJacobianToLaplacian< 2, RangeType, JacobianRangeType >\n : public RangeType\n{\n GradientJacobianToLaplacian(const JacobianRangeType& jacobian) {\n (*this)[0] = jacobian[0][0];\n (*this)[1] = jacobian[3][1];\n }\n};\n\ntemplate< class RangeType, class JacobianRangeType >\nstruct GradientJacobianToLaplacian< 3, RangeType, JacobianRangeType >\n : public RangeType\n{\n GradientJacobianToLaplacian(const JacobianRangeType& jacobian) {\n (*this)[0] = jacobian[0][0];\n (*this)[1] = jacobian[4][1];\n (*this)[2] = jacobian[8][2];\n }\n};\n\ntemplate< class TimeProviderType,\n class DiscreteVelocityFunctionType,\n class SigmaFunctionType >\nclass GradientAdapterFunction\n : public SigmaFunctionType\n{\nprotected:\n typedef GradientAdapterFunction< TimeProviderType,\n DiscreteVelocityFunctionType,\n SigmaFunctionType >\n ThisType;\n typedef SigmaFunctionType\n BaseType;\n const TimeProviderType& timeProvider_;\n\npublic:\n GradientAdapterFunction(const TimeProviderType& timeProvider,\n const DiscreteVelocityFunctionType& velocity,\n SigmaFunctionType& dummy,\n int polOrd = -1)\n : BaseType( \"grad\", dummy.space() )\n , timeProvider_(timeProvider) {\n typedef SigmaFunctionType\n DiscreteFunctionType;\n typedef typename SigmaFunctionType::DiscreteFunctionSpaceType\n DiscreteFunctionSpaceType;\n typedef typename DiscreteFunctionType::LocalFunctionType\n LocalFuncType;\n typedef typename DiscreteFunctionSpaceType::Traits::GridPartType\n GridPartType;\n typedef typename DiscreteFunctionSpaceType::Traits::IteratorType\n Iterator;\n typedef typename DiscreteFunctionSpaceType::BaseFunctionSetType\n BaseFunctionSetType;\n\/\/ typedef typename GridPartType::IntersectionIteratorType\n\/\/ IntersectionIteratorType;\n typedef typename DiscreteVelocityFunctionType::LocalFunctionType\n LocalFType;\n\n const DiscreteFunctionSpaceType space( velocity.space().gridPart() );\n const GridPartType& gridPart = space.gridPart();\n \/\/ type of quadrature\n typedef Dune::Fem::CachingQuadrature< GridPartType, 0 > VolumeQuadratureType;\n\/\/ typedef Dune::Fem::CachingQuadrature< GridPartType, 1 > FaceQuadratureType;\n \/\/ type of local mass matrix\n typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType, VolumeQuadratureType > LocalMassMatrixType;\n\n const auto quadOrd = std::max(2 * space.order() + 2, polOrd);\n\n \/\/ create local mass matrix object\n LocalMassMatrixType massMatrix(space, quadOrd);\n\n \/\/ check whether geometry mappings are affine or not\n const bool affineMapping = massMatrix.affine();\n\n \/\/ clear destination\n BaseType::clear();\n\n const Iterator endit = space.end();\n for (Iterator it = space.begin(); it != endit; ++it)\n {\n \/\/ get entity\n const typename GridPartType::GridType::template Codim< 0 >::Entity& entity = *it;\n \/\/ get geometry\n typedef typename GridPartType::GridType::template Codim< 0 >::Geometry\n Geometry;\n const Geometry& geo = entity.geometry();\n\n \/\/ get quadrature\n VolumeQuadratureType quad(entity, quadOrd);\n\n \/\/ get local function of destination\n LocalFuncType self_local = BaseType::localFunction(entity);\n \/\/ get local function of argument\n const LocalFType velocity_local = velocity.localFunction(entity);\n\n \/\/ get base function set\n const BaseFunctionSetType& baseset = self_local.baseFunctionSet();\n\n const auto quadNop = quad.nop();\n const auto numDofs = self_local.numDofs();\n\n \/\/ volume part\n for (decltype(quadNop) qP = 0; qP < quadNop; ++qP)\n {\n const typename DiscreteFunctionSpaceType::DomainType xLocal = quad.point(qP);\n\n const double intel = (affineMapping) ?\n quad.weight(qP) : \/\/ affine case\n quad.weight(qP) * geo.integrationElement(xLocal); \/\/ general case\n\n typename DiscreteFunctionSpaceType::DomainType\n xWorld = geo.global(xLocal);\n\n \/\/ evaluate function\n typename DiscreteVelocityFunctionType::DiscreteFunctionSpaceType::RangeType\n velocity_eval;\n velocity_local.evaluate(quad[qP], velocity_eval);\n\n typename DiscreteVelocityFunctionType::DiscreteFunctionSpaceType::JacobianRangeType\n velocity_jacobian_eval;\n velocity_local.jacobian(quad[qP], velocity_jacobian_eval);\n\n \/\/ do projection\n for (decltype(numDofs) i = 0; i < numDofs; ++i)\n {\n typename DiscreteFunctionType::DiscreteFunctionSpaceType::RangeType phi(0.0);\n baseset.evaluate(i, quad[qP], phi);\n self_local[i] += intel * ( Dune::Stuff::Common::colonProduct(velocity_jacobian_eval, phi) );\n }\n }\n\n \/\/ in case of non-linear mapping apply inverse\n if (!affineMapping)\n {\n massMatrix.applyInverse(entity, self_local);\n }\n }\n }\n};\n\n} \/\/ namespace Experimental\n\n} \/\/ namespace Fem\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ HAVE_DUNE_FEM\n\n#endif \/\/ DUNE_STUFF_FEM_FUNCTIONS_CUSTOMPROJECTION_HH\n<|endoftext|>"} {"text":"<commit_before>#include \"platform.h\"\n#include <iostream>\nusing namespace std;\n\nPlatform::Platform() {\n\t\/\/TODO: 初始化各个玩家\n\tinitLevels();\n\tinitCards();\n\n}\n\nvoid Platform::initLevels() {\n\t\/\/ http:\/\/zh.wikipedia.org\/wiki\/%E8%B0%81%E6%98%AF%E7%89%9B%E5%A4%B4%E7%8E%8B\n\tfor (int i = 1; i <= MAX_CARD; ++i) {\n\t\tif ( (i - 5) % 5 == 0) {\n\t\t\tlevel.insert(pair <int, int>(i, 2)); \n\t\t\tcontinue;\n\t\t}\n\t\tif (i % 10 == 0) {\n\t\t\tlevel.insert(pair <int, int>(i, 3)); \n\t\t\tcontinue;\n\t\t}\n\t\tif (i % 11 == 0) {\n\t\t\tlevel.insert(pair <int, int>(i, 5));\n\t\t\tcontinue;\n\t\t}\n\t\tif (i == 55) {\n\t\t\tlevel.insert(pair <int, int>(i, 7));\n\t\t\tcontinue;\n\t\t}\n\t\tlevel.insert(pair <int, int>(i, 1));\n\t}\n\t\/\/ for (auto iter = level.begin(); iter != level.end(); ++iter) {\n\t\/\/ \tcout << iter->first << ' ' << iter->second<<endl;\n\t\/\/ }\n}\n\nvoid Platform::initCards() {\n\tfor (int i = 1; i <= MAX_CARD; ++i) \n\t\tcards.push_back(i);\n\trandom_shuffle(cards.begin(), cards.end());\n\n\tauto iter = cards.begin();\n\n\tint avaliableCount = MAX_CARD - 4;\n\textraCards.resize(avaliableCount % player_count);\n\tcopy(iter, iter + avaliableCount % player_count, extraCards.begin());\n\tprintVector(extraCards);\n\titer += avaliableCount % player_count;\n\n\t\/\/TODO 伪造数据\n\tfor (int i = 0; i != player_count; ++i) {\n\t\tvector<int> tempCards(avaliableCount \/ player_count);\n\t\tcopy(iter, iter + avaliableCount \/ player_count, tempCards.begin());\n\t\tuserCards.insert(pair <string, vector<int>> (\"name\" + i, tempCards));\n\t\titer = iter + avaliableCount \/ player_count;\n\t}\n\n\twhile (iter != cards.end()) {\n\t\theapCards.push_back(*iter);\n\t\t++iter;\n\t}\n\tprintVector(heapCards);\n}\n\nvoid Platform::printVector(vector<int> vec) {\n\tfor (auto ai = vec.begin(); ai != vec.end(); ++ai) \n\t\tcout << *ai << ' ';\n\tcout << endl;\n}<commit_msg>忘了提交了什么<commit_after>#include \"platform.h\"\n#include <iostream>\nusing namespace std;\n\nPlatform::Platform() {\n\t\/\/TODO: 初始化各个玩家\n\tinitLevels();\n\tinitCards();\n\n}\n\nvoid Platform::initLevels() {\n\t\/\/ http:\/\/zh.wikipedia.org\/wiki\/%E8%B0%81%E6%98%AF%E7%89%9B%E5%A4%B4%E7%8E%8B\n\tfor (int i = 1; i <= MAX_CARD; ++i) {\n\t\tif ( (i - 5) % 5 == 0) {\n\t\t\tlevel.insert(pair <int, int>(i, 2)); \n\t\t\tcontinue;\n\t\t}\n\t\tif (i % 10 == 0) {\n\t\t\tlevel.insert(pair <int, int>(i, 3)); \n\t\t\tcontinue;\n\t\t}\n\t\tif (i % 11 == 0) {\n\t\t\tlevel.insert(pair <int, int>(i, 5));\n\t\t\tcontinue;\n\t\t}\n\t\tif (i == 55) {\n\t\t\tlevel.insert(pair <int, int>(i, 7));\n\t\t\tcontinue;\n\t\t}\n\t\tlevel.insert(pair <int, int>(i, 1));\n\t}\n\t\/\/ for (auto iter = level.begin(); iter != level.end(); ++iter) {\n\t\/\/ \tcout << iter->first << ' ' << iter->second<<endl;\n\t\/\/ }\n}\n\nvoid Platform::initCards() {\n\tfor (int i = 1; i <= MAX_CARD; ++i) \n\t\tcards.push_back(i);\n\trandom_shuffle(cards.begin(), cards.end());\n\n\tauto iter = cards.begin();\n\n\tint avaliableCount = MAX_CARD - 4;\n\textraCards.resize(avaliableCount % player_count);\n\tcopy(iter, iter + avaliableCount % player_count, extraCards.begin());\n\titer += avaliableCount % player_count;\n\n\t\/\/TODO 伪造数据\n\tfor (int i = 0; i != player_count; ++i) {\n\t\tvector<int> tempCards(avaliableCount \/ player_count);\n\t\tcopy(iter, iter + avaliableCount \/ player_count, tempCards.begin());\n\t\tuserCards.insert(pair <string, vector<int>> (\"name\" + i, tempCards));\n\t\titer = iter + avaliableCount \/ player_count;\n\t}\n\n\twhile (iter != cards.end()) {\n\t\theapCards.push_back(*iter);\n\t\t++iter;\n\t}\n}\n\nvoid Platform::printVector(vector<int> vec) {\n\tfor (auto ai = vec.begin(); ai != vec.end(); ++ai) \n\t\tcout << *ai << ' ';\n\tcout << endl;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode: c++; coding: utf-8 -*-\n#pragma once\n#ifndef GRN_HPP_\n#define GRN_HPP_\n\n#include <boost\/graph\/adjacency_list.hpp>\n\n#include <boost\/graph\/graphviz.hpp>\n#include <boost\/graph\/graphml.hpp>\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\nnamespace wtl {\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n\/\/typedef boost::property<boost::vertex_priority_t, double> VertexProperty;\ntypedef boost::property<boost::vertex_potential_t, double> VertexProperty;\ntypedef boost::property<boost::edge_weight_t, double> EdgeProperty;\ntypedef boost::property<boost::graph_name_t, double> GraphProperty;\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS,\n VertexProperty, EdgeProperty, GraphProperty> Graph;\ntypedef boost::graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef boost::graph_traits<Graph>::edge_descriptor Edge;\n\nGraph make_graph(const std::vector<std::vector<double> >& adj_matrix) {\n const size_t order = adj_matrix.size();\n std::vector<std::pair<size_t, size_t> > adj_list;\n std::vector<double> weights;\n for (size_t i=0; i<order; ++i) {\n const auto& row = adj_matrix[i];\n for (size_t j=0; j<order; ++j) {\n if (row[j] != 0.0) {\n adj_list.push_back({j, i});\n weights.push_back(row[j]);\n }\n }\n }\n Graph graph(adj_list.begin(), adj_list.end(), weights.begin(), order);\n return graph;\n}\n\ntemplate <class Graph>\nclass weight_label_writer {\n public:\n weight_label_writer(const Graph& g) : graph_(g) {}\n\n template <class VertexOrEdge>\n void operator()(std::ostream& ost, const VertexOrEdge& edge) const {\n write(ost, boost::get(boost::edge_weight, graph_, edge));\n }\n\n private:\n template <class Edge, class Weight>\n void write(std::ostream& ost, const Weight& weight) const {\n ost << \"[weight=\" << weight << \"]\";\n }\n\n const Graph& graph_;\n};\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n} \/\/ namespace wtl\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ GRN_HPP_\n<commit_msg>complete grn.hpp for now<commit_after>\/\/ -*- mode: c++; coding: utf-8 -*-\n#pragma once\n#ifndef GRN_HPP_\n#define GRN_HPP_\n\n#include <string>\n#include <sstream>\n\n#include <boost\/graph\/adjacency_list.hpp>\n\n#include <boost\/graph\/graphviz.hpp>\n#include <boost\/graph\/graphml.hpp>\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\nenum vertex_input_t {vertex_input};\nenum graph_frequency_t {graph_frequency};\n\nnamespace boost {\n BOOST_INSTALL_PROPERTY(vertex, input);\n BOOST_INSTALL_PROPERTY(graph, frequency);\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\nnamespace wtl {\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\ntypedef boost::property<vertex_input_t, double> VertexProperty;\ntypedef boost::property<boost::edge_weight_t, double> EdgeProperty;\n\ntypedef std::map<std::string, std::string> AttrMap;\n\ntypedef boost::property<boost::graph_graph_attribute_t, AttrMap,\n boost::property<boost::graph_vertex_attribute_t, AttrMap,\n boost::property<boost::graph_edge_attribute_t, AttrMap> > > GraphProperty;\n\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS,\n boost::no_property, EdgeProperty, GraphProperty> Graph;\n\/\/ VertexProperty, EdgeProperty, GraphProperty> Graph;\n\nGraph make_graph(const std::vector<std::vector<double> >& adj_matrix) {\n const size_t order = adj_matrix.size();\n std::vector<std::pair<size_t, size_t> > adj_list;\n std::vector<double> weights;\n for (size_t i=0; i<order; ++i) {\n const auto& row = adj_matrix[i];\n for (size_t j=0; j<order; ++j) {\n if (row[j] != 0.0) {\n adj_list.push_back({j, i});\n weights.push_back(row[j]);\n }\n }\n }\n Graph graph(adj_list.begin(), adj_list.end(), weights.begin(), order);\n return graph;\n}\n\ntemplate <class Values>\nclass property_writer {\n public:\n property_writer(const Values& v, const std::string& key)\n : values_(v), key_(key) {}\n\n template <class VertexOrEdge>\n void operator()(std::ostream& ost, const VertexOrEdge& voe) const {\n ost << \"[\" << key_ << \"=\" << boost::get(values_, voe) << \"]\";\n }\n private:\n const Values values_;\n const std::string key_;\n};\ntemplate <class Values> inline\nproperty_writer<Values>\nmake_property_writer(const Values& values, const std::string& key=\"label\") {\n return property_writer<Values>(values, key);\n}\n\ninline std::string str_graphviz(Graph& graph) {\n std::ostringstream oss;\n boost::write_graphviz(oss, graph,\n boost::default_writer(),\n\/\/ make_property_writer(boost::get(VertexProperty::tag_type(), graph), \"input\"),\n make_property_writer(boost::get(boost::edge_weight, graph), \"weight\"),\n boost::make_graph_attributes_writer(graph)\n );\n return oss.str();\n}\n\ntemplate <class GraphType> inline\nstd::string str_graphml(GraphType& graph) {\n std::ostringstream oss;\n boost::dynamic_properties dp;\n dp.property(\"node_id\", boost::get(boost::vertex_index, graph));\n dp.property(\"input\", boost::get(GraphType::vertex_property_type::tag_type(), graph));\n dp.property(\"weight\", boost::get(GraphType::edge_property_type::tag_type(), graph));\n boost::write_graphml(oss, graph, dp);\n return oss.str();\n}\n\ntemplate <class GraphType, class V> inline\nvoid put_vertices_property(GraphType* g, const V& values) {\n for (size_t i=0; i<values.size(); ++i) {\n boost::put(GraphType::vertex_property_type::tag_type(),\n *g, boost::vertex(i, *g), values[i]);\n }\n}\n\ntemplate <class GraphType, class Value> inline\nvoid insert_graphattr(GraphType* graph, const std::string& key, const Value& value) {\n auto attrmap = boost::get_property(*graph, boost::graph_graph_attribute);\n attrmap[key] = std::to_string(value);\n boost::set_property(*graph, boost::graph_graph_attribute, attrmap);\n}\n\nstd::string dot_grn(const std::vector<std::vector<double> >& adj_matrix,\n\/\/ const std::vector<double>& receptors,\n const size_t frequency) {\n Graph graph = make_graph(adj_matrix);\n\/\/ put_vertices_property(&graph, receptors);\n insert_graphattr(&graph, \"freqency\", frequency);\n return str_graphviz(graph);\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n} \/\/ namespace wtl\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ GRN_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"event.h\"\n#include <stdlib.h>\n#include <sys\/epoll.h>\n#include <stdio.h>\n\nevent::event(int fd)\n: fd_(fd)\n{\n struct epoll_event ev;\n events_ = new struct epoll_event[1];\n int listen_sock, conn_sock, nfds, epollfd;\n\n \/* Set up listening socket, 'listen_sock' (socket(),\n bind(), listen()) *\/\n\n data_ = epoll_create(10);\n if (epollfd == -1) \n {\n perror(\"epoll_create\");\n exit(EXIT_FAILURE);\n }\n\n ev.events = EPOLLIN;\n ev.data.fd = fd;\n if (epoll_ctl(data_, EPOLL_CTL_ADD, fd, &ev) == -1) {\n perror(\"epoll_ctl: listen_sock\");\n exit(EXIT_FAILURE);\n }\n\n}\n\nevent::~event()\n{\n delete [](struct epoll_event*)events_;\n}\n\nbool event::wait(uint32_t timeout_usec)\n{\n auto nfds = epoll_wait(data_, static_cast<struct epoll_event*>(events_), 10, -1);\n if (nfds == -1) {\n perror(\"epoll_pwait\");\n exit(EXIT_FAILURE);\n }\n}\n<commit_msg>update event::wait<commit_after>#include \"event.h\"\n#include <stdlib.h>\n#include <sys\/epoll.h>\n#include <stdio.h>\n\nevent::event(int fd)\n: fd_(fd)\n{\n struct epoll_event ev;\n events_ = new struct epoll_event[1];\n int listen_sock, conn_sock, nfds, epollfd;\n\n \/* Set up listening socket, 'listen_sock' (socket(),\n bind(), listen()) *\/\n\n data_ = epoll_create(10);\n if (epollfd == -1) \n {\n perror(\"epoll_create\");\n exit(EXIT_FAILURE);\n }\n\n ev.events = EPOLLIN;\n ev.data.fd = fd;\n if (epoll_ctl(data_, EPOLL_CTL_ADD, fd, &ev) == -1) {\n perror(\"epoll_ctl: listen_sock\");\n exit(EXIT_FAILURE);\n }\n\n}\n\nevent::~event()\n{\n delete [](struct epoll_event*)events_;\n}\n\nbool event::wait(uint32_t timeout_usec)\n{\n auto nfds = epoll_wait(data_, static_cast<struct epoll_event*>(events_), 10, -1);\n if (nfds == -1) {\n perror(\"epoll_pwait\");\n exit(EXIT_FAILURE);\n }\n return nfds > 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\nframenotifier_app.cpp\n\n Created on: 13 Oct 2015\n Author: up45\n*\/\n#include <signal.h>\n#include <string>\n#include <cstring>\n#include <iostream>\n#include <fstream>\nusing namespace std;\n\n\n#include <log4cxx\/logger.h>\n#include <log4cxx\/basicconfigurator.h>\n#include <log4cxx\/propertyconfigurator.h>\n#include <log4cxx\/helpers\/exception.h>\nusing namespace log4cxx;\nusing namespace log4cxx::helpers;\n\n#include <boost\/foreach.hpp>\n#include <boost\/program_options.hpp>\n#include \"boost\/date_time\/posix_time\/posix_time.hpp\"\nnamespace po = boost::program_options;\n\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/writer.h\"\n#include \"rapidjson\/prettywriter.h\"\n#include \"rapidjson\/stringbuffer.h\"\nusing namespace rapidjson;\n\n#include \"zmq\/zmq.hpp\"\n\n#include \"framenotifier_data.h\"\n\nvoid parse_arguments(int argc, char** argv, po::variables_map& vm, LoggerPtr& logger)\n{\n try\n {\n std::string config_file;\n\n \/\/ Declare a group of options that will allowed only on the command line\n po::options_description generic(\"Generic options\");\n generic.add_options()\n (\"help,h\",\n \"Print this help message\")\n (\"config,c\", po::value<string>(&config_file),\n \"Specify program configuration file\")\n ;\n\n \/\/ Declare a group of options that will be allowed both on the command line\n \/\/ and in the configuration file\n po::options_description config(\"Configuration options\");\n config.add_options()\n (\"logconfig,l\", po::value<string>(),\n \"Set the log4cxx logging configuration file\")\n (\"ready,r\", po::value<std::string>()->default_value(\"tcp:\/\/127.0.0.1:5001\"),\n \"Ready ZMQ endpoint from frameReceiver\")\n (\"release\", po::value<std::string>()->default_value(\"tcp:\/\/127.0.0.1:5002\"),\n \"Release frame ZMQ endpoint from frameReceiver\")\n (\"frames,f\", po::value<unsigned int>()->default_value(1),\n \"Set the number of frames to be notified about before terminating\")\n (\"sharedbuf\", po::value<std::string>()->default_value(\"FrameReceiverBuffer\"),\n \"Set the name of the shared memory frame buffer\")\n ;\n\n \/\/ Group the variables for parsing at the command line and\/or from the configuration file\n po::options_description cmdline_options;\n cmdline_options.add(generic).add(config);\n po::options_description config_file_options;\n config_file_options.add(config);\n\n \/\/ Parse the command line options\n po::store(po::parse_command_line(argc, argv, cmdline_options), vm);\n po::notify(vm);\n\n \/\/ If the command-line help option was given, print help and exit\n if (vm.count(\"help\"))\n {\n std::cout << \"usage: frameReceiver [options]\" << std::endl << std::endl;\n std::cout << cmdline_options << std::endl;\n exit(1);\n }\n\n \/\/ If the command line config option was given, parse the specified configuration\n \/\/ file for additional options. Note that boost::program_options gives precedence\n \/\/ to the first instance occurring. In this case, that implies that command-line\n \/\/ options have precedence over equivalent configuration file entries.\n if (vm.count(\"config\"))\n {\n std::ifstream config_ifs(config_file.c_str());\n if (config_ifs)\n {\n LOG4CXX_DEBUG(logger, \"Parsing configuration file \" << config_file);\n po::store(po::parse_config_file(config_ifs, config_file_options, true), vm);\n po::notify(vm);\n }\n else\n {\n LOG4CXX_ERROR(logger, \"Unable to open configuration file \" << config_file << \" for parsing\");\n exit(1);\n }\n }\n\n if (vm.count(\"logconfig\"))\n {\n PropertyConfigurator::configure(vm[\"logconfig\"].as<string>());\n LOG4CXX_DEBUG(logger, \"log4cxx config file is set to \" << vm[\"logconfig\"].as<string>());\n }\n\n if (vm.count(\"ready\"))\n {\n LOG4CXX_DEBUG(logger, \"Setting frame ready notification ZMQ address to \" << vm[\"ready\"].as<string>());\n }\n\n if (vm.count(\"release\"))\n {\n LOG4CXX_DEBUG(logger, \"Setting frame release notification ZMQ address to \" << vm[\"release\"].as<string>());\n }\n\n if (vm.count(\"frames\"))\n {\n LOG4CXX_DEBUG(logger, \"Setting number of frames to receive to \" << vm[\"frames\"].as<unsigned int>());\n }\n\n }\n catch (po::unknown_option &e)\n {\n LOG4CXX_WARN(logger, \"CLI parsing error: \" << e.what() << \". Will carry on...\");\n }\n catch (Exception &e)\n {\n LOG4CXX_FATAL(logger, \"Got Log4CXX exception: \" << e.what());\n throw;\n }\n catch (exception &e)\n {\n LOG4CXX_ERROR(logger, \"Got exception:\" << e.what());\n throw;\n }\n catch (...)\n {\n LOG4CXX_FATAL(logger, \"Exception of unknown type!\");\n throw;\n }\n}\n\nint main(int argc, char** argv)\n{\n int rc = 0;\n\n \/\/ Create a default basic logger configuration, which can be overridden by command-line option later\n BasicConfigurator::configure();\n\n LoggerPtr logger(Logger::getLogger(\"FrameNotifier\"));\n po::variables_map vm;\n parse_arguments(argc, argv, vm, logger);\n\n SharedMemParser smp(vm[\"sharedbuf\"].as<string>());\n\n \/\/ Assuming this is a P2M, our image dimensions are:\n dimensions_t p2m_dims(2); p2m_dims[0] = 1484; p2m_dims[1] = 1404;\n\n zmq::context_t zmq_context; \/\/ Global ZMQ context\n\n \/\/ The \"release\" ZMQ PUB socket, used to release frames back to the frameReceiver\n zmq::socket_t zsocket_release(zmq_context, ZMQ_PUB);\n zsocket_release.connect(vm[\"release\"].as<string>().c_str());\n\n \/\/ The \"ready\" ZMQ SUB socket, used to get notifications that new frames are ready to be processed\n zmq::socket_t zsocket_ready(zmq_context, ZMQ_SUB);\n zsocket_ready.connect(vm[\"ready\"].as<string>().c_str());\n zsocket_ready.setsockopt(ZMQ_SUBSCRIBE, \"\", strlen(\"\"));\n zmq::pollitem_t poll_item;\n poll_item.socket = zsocket_ready;\n poll_item.events = ZMQ_POLLIN;\n poll_item.fd = 0;\n poll_item.revents = 0;\n\n \/\/ The polling loop. Polls on all elements in poll_item\n \/\/ Stop the loop by setting keep_running=false\n \/\/ Loop automatically ends if notification_count > user option \"frames\"\n unsigned long notification_count = 0;\n bool keep_running = true;\n LOG4CXX_DEBUG(logger, \"Entering ZMQ polling loop (\" << vm[\"ready\"].as<string>().c_str() << \")\");\n while (keep_running)\n {\n \/\/ Always reset the last raw events before polling\n poll_item.revents = 0;\n\n \/\/ Do the poll with a 10ms timeout (i.e. 10Hz poll)\n zmq::poll(&poll_item, 1, 10);\n\n \/\/ Check for poll error and exit the loop is one is found\n if (poll_item.revents & ZMQ_POLLERR)\n {\n LOG4CXX_ERROR(logger, \"Got ZMQ error in polling. Quitting polling loop.\");\n keep_running = false;\n }\n \/\/ Do work if a message is received\n else if (poll_item.revents & ZMQ_POLLIN)\n {\n LOG4CXX_DEBUG(logger, \"Reading data from ZMQ socket\");\n notification_count++;\n zmq::message_t msg;\n zsocket_ready.recv(&msg); \/\/ Read the message from the ready socket\n\n string msg_str(reinterpret_cast<char*>(msg.data()), msg.size()-1);\n LOG4CXX_DEBUG(logger, \"Parsing JSON msg string: \" << msg_str);\n Document msg_doc;\n msg_doc.Parse(msg_str.c_str()); \/\/ Parse the JSON string into a Document DOM object\n\n \/\/ Setup a string buffer and a writer so we can stringify the Document DOM object again\n StringBuffer buffer;\n PrettyWriter<StringBuffer> writer(buffer);\n msg_doc.Accept(writer);\n LOG4CXX_DEBUG(logger, \"Parsed json: \" << buffer.GetString());\n\n \/\/ Copy the data out into a Frame object\n LOG4CXX_DEBUG(logger, \"Creating Frame object\");\n Frame frame(smp.get_buffer_size(), p2m_dims);\n LOG4CXX_DEBUG(logger, \"Copying buffer ID: \" << msg_doc[\"params\"][\"buffer_id\"].GetInt64());\n smp.get_frame(frame, msg_doc[\"params\"][\"buffer_id\"].GetInt64());\n LOG4CXX_DEBUG(logger, \"Frame completeness: \" << frame.get_header()->packets_received << \" packets received\");\n\n \/\/ Clear the json string buffer and reset the writer so we can re-use them\n \/\/ after modifying the Document DOM object\n buffer.Clear();\n writer.Reset(buffer);\n\n \/\/ We want to return the exact same JSON message back to the frameReceiver\n \/\/ so we just modify the relevant bits: msg_val: from frame_ready to frame_release\n \/\/ and update the timestamp\n msg_doc[\"msg_val\"].SetString(\"frame_release\");\n\n \/\/ Create and update the timestamp in the JSON message\n boost::posix_time::ptime msg_timestamp = boost::posix_time::microsec_clock::local_time();\n string msg_timestamp_str = boost::posix_time::to_iso_extended_string(msg_timestamp);\n msg_doc[\"timestamp\"].SetString(StringRef(msg_timestamp_str.c_str()));\n\n \/\/ Encode the JSON Document DOM object using the writer\n msg_doc.Accept(writer);\n LOG4CXX_DEBUG(logger, \"Changing msg_val: \" << msg_doc[\"msg_val\"].GetString());\n string release_msg(buffer.GetString()); \/\/ Get a copy of the JSON string\n LOG4CXX_DEBUG(logger, \"New json: \" << release_msg);\n\n LOG4CXX_DEBUG(logger, \"Sending release response\");\n \/\/ Send the new JSON object (string) back to the frameReceiver on the \"release\" ZMQ socket\n size_t nbytes = zsocket_release.send(release_msg.c_str(), release_msg.size() + 1);\n LOG4CXX_DEBUG(logger, \"Sent \" << nbytes << \" bytes\");\n } else\n {\n \/\/ No new data\n }\n\n \/\/ Quit the loop if we have received the desired number of frames\n if (notification_count >= vm[\"frames\"].as<unsigned int>()) keep_running=false;\n }\n return rc;\n}\n\n\n<commit_msg>filewriter: Using the FileWriter class in the main application<commit_after>\/**\nframenotifier_app.cpp\n\n Created on: 13 Oct 2015\n Author: up45\n*\/\n#include <signal.h>\n#include <string>\n#include <cstring>\n#include <iostream>\n#include <fstream>\nusing namespace std;\n\n\n#include <log4cxx\/logger.h>\n#include <log4cxx\/basicconfigurator.h>\n#include <log4cxx\/propertyconfigurator.h>\n#include <log4cxx\/helpers\/exception.h>\nusing namespace log4cxx;\nusing namespace log4cxx::helpers;\n\n#include <boost\/foreach.hpp>\n#include <boost\/program_options.hpp>\n#include \"boost\/date_time\/posix_time\/posix_time.hpp\"\nnamespace po = boost::program_options;\n\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/writer.h\"\n#include \"rapidjson\/prettywriter.h\"\n#include \"rapidjson\/stringbuffer.h\"\nusing namespace rapidjson;\n\n#include \"zmq\/zmq.hpp\"\n\n#include \"framenotifier_data.h\"\n#include \"FileWriter.h\"\n\nvoid parse_arguments(int argc, char** argv, po::variables_map& vm, LoggerPtr& logger)\n{\n try\n {\n std::string config_file;\n\n \/\/ Declare a group of options that will allowed only on the command line\n po::options_description generic(\"Generic options\");\n generic.add_options()\n (\"help,h\",\n \"Print this help message\")\n (\"config,c\", po::value<string>(&config_file),\n \"Specify program configuration file\")\n ;\n\n \/\/ Declare a group of options that will be allowed both on the command line\n \/\/ and in the configuration file\n po::options_description config(\"Configuration options\");\n config.add_options()\n (\"logconfig,l\", po::value<string>(),\n \"Set the log4cxx logging configuration file\")\n (\"ready,r\", po::value<std::string>()->default_value(\"tcp:\/\/127.0.0.1:5001\"),\n \"Ready ZMQ endpoint from frameReceiver\")\n (\"release\", po::value<std::string>()->default_value(\"tcp:\/\/127.0.0.1:5002\"),\n \"Release frame ZMQ endpoint from frameReceiver\")\n (\"frames,f\", po::value<unsigned int>()->default_value(1),\n \"Set the number of frames to be notified about before terminating\")\n (\"sharedbuf\", po::value<std::string>()->default_value(\"FrameReceiverBuffer\"),\n \"Set the name of the shared memory frame buffer\")\n ;\n\n \/\/ Group the variables for parsing at the command line and\/or from the configuration file\n po::options_description cmdline_options;\n cmdline_options.add(generic).add(config);\n po::options_description config_file_options;\n config_file_options.add(config);\n\n \/\/ Parse the command line options\n po::store(po::parse_command_line(argc, argv, cmdline_options), vm);\n po::notify(vm);\n\n \/\/ If the command-line help option was given, print help and exit\n if (vm.count(\"help\"))\n {\n std::cout << \"usage: frameReceiver [options]\" << std::endl << std::endl;\n std::cout << cmdline_options << std::endl;\n exit(1);\n }\n\n \/\/ If the command line config option was given, parse the specified configuration\n \/\/ file for additional options. Note that boost::program_options gives precedence\n \/\/ to the first instance occurring. In this case, that implies that command-line\n \/\/ options have precedence over equivalent configuration file entries.\n if (vm.count(\"config\"))\n {\n std::ifstream config_ifs(config_file.c_str());\n if (config_ifs)\n {\n LOG4CXX_DEBUG(logger, \"Parsing configuration file \" << config_file);\n po::store(po::parse_config_file(config_ifs, config_file_options, true), vm);\n po::notify(vm);\n }\n else\n {\n LOG4CXX_ERROR(logger, \"Unable to open configuration file \" << config_file << \" for parsing\");\n exit(1);\n }\n }\n\n if (vm.count(\"logconfig\"))\n {\n PropertyConfigurator::configure(vm[\"logconfig\"].as<string>());\n LOG4CXX_DEBUG(logger, \"log4cxx config file is set to \" << vm[\"logconfig\"].as<string>());\n }\n\n if (vm.count(\"ready\"))\n {\n LOG4CXX_DEBUG(logger, \"Setting frame ready notification ZMQ address to \" << vm[\"ready\"].as<string>());\n }\n\n if (vm.count(\"release\"))\n {\n LOG4CXX_DEBUG(logger, \"Setting frame release notification ZMQ address to \" << vm[\"release\"].as<string>());\n }\n\n if (vm.count(\"frames\"))\n {\n LOG4CXX_DEBUG(logger, \"Setting number of frames to receive to \" << vm[\"frames\"].as<unsigned int>());\n }\n\n }\n catch (po::unknown_option &e)\n {\n LOG4CXX_WARN(logger, \"CLI parsing error: \" << e.what() << \". Will carry on...\");\n }\n catch (Exception &e)\n {\n LOG4CXX_FATAL(logger, \"Got Log4CXX exception: \" << e.what());\n throw;\n }\n catch (exception &e)\n {\n LOG4CXX_ERROR(logger, \"Got exception:\" << e.what());\n throw;\n }\n catch (...)\n {\n LOG4CXX_FATAL(logger, \"Exception of unknown type!\");\n throw;\n }\n}\n\nint main(int argc, char** argv)\n{\n int rc = 0;\n\n \/\/ Create a default basic logger configuration, which can be overridden by command-line option later\n BasicConfigurator::configure();\n\n LoggerPtr logger(Logger::getLogger(\"FrameNotifier\"));\n po::variables_map vm;\n parse_arguments(argc, argv, vm, logger);\n\n SharedMemParser smp(vm[\"sharedbuf\"].as<string>());\n\n \/\/ Assuming this is a P2M, our image dimensions are:\n size_t bytes_per_pixel = 2;\n dimensions_t p2m_dims(2); p2m_dims[0] = 1484; p2m_dims[1] = 1404;\n\n zmq::context_t zmq_context; \/\/ Global ZMQ context\n\n \/\/ The \"release\" ZMQ PUB socket, used to release frames back to the frameReceiver\n zmq::socket_t zsocket_release(zmq_context, ZMQ_PUB);\n zsocket_release.connect(vm[\"release\"].as<string>().c_str());\n\n \/\/ The \"ready\" ZMQ SUB socket, used to get notifications that new frames are ready to be processed\n zmq::socket_t zsocket_ready(zmq_context, ZMQ_SUB);\n zsocket_ready.connect(vm[\"ready\"].as<string>().c_str());\n zsocket_ready.setsockopt(ZMQ_SUBSCRIBE, \"\", strlen(\"\"));\n zmq::pollitem_t poll_item;\n poll_item.socket = zsocket_ready;\n poll_item.events = ZMQ_POLLIN;\n poll_item.fd = 0;\n poll_item.revents = 0;\n\n \/\/ The file writer object\n FileWriter hdfwr;\n hdfwr.createFile(\"data.h5\");\n FileWriter::DatasetDefinition dset_def;\n dset_def.name = \"data\";\n dset_def.frame_dimensions = p2m_dims;\n dset_def.pixel = FileWriter::pixel_raw_16bit;\n dset_def.num_frames = vm[\"frames\"].as<unsigned int>();\n hdfwr.createDataset(dset_def);\n\n \/\/ The polling loop. Polls on all elements in poll_item\n \/\/ Stop the loop by setting keep_running=false\n \/\/ Loop automatically ends if notification_count > user option \"frames\"\n unsigned long notification_count = 0;\n bool keep_running = true;\n LOG4CXX_DEBUG(logger, \"Entering ZMQ polling loop (\" << vm[\"ready\"].as<string>().c_str() << \")\");\n while (keep_running)\n {\n \/\/ Always reset the last raw events before polling\n poll_item.revents = 0;\n\n \/\/ Do the poll with a 10ms timeout (i.e. 10Hz poll)\n zmq::poll(&poll_item, 1, 10);\n\n \/\/ Check for poll error and exit the loop is one is found\n if (poll_item.revents & ZMQ_POLLERR)\n {\n LOG4CXX_ERROR(logger, \"Got ZMQ error in polling. Quitting polling loop.\");\n keep_running = false;\n }\n \/\/ Do work if a message is received\n else if (poll_item.revents & ZMQ_POLLIN)\n {\n LOG4CXX_DEBUG(logger, \"Reading data from ZMQ socket\");\n notification_count++;\n zmq::message_t msg;\n zsocket_ready.recv(&msg); \/\/ Read the message from the ready socket\n\n string msg_str(reinterpret_cast<char*>(msg.data()), msg.size()-1);\n LOG4CXX_DEBUG(logger, \"Parsing JSON msg string: \" << msg_str);\n Document msg_doc;\n msg_doc.Parse(msg_str.c_str()); \/\/ Parse the JSON string into a Document DOM object\n\n \/\/ Setup a string buffer and a writer so we can stringify the Document DOM object again\n StringBuffer buffer;\n PrettyWriter<StringBuffer> writer(buffer);\n msg_doc.Accept(writer);\n LOG4CXX_DEBUG(logger, \"Parsed json: \" << buffer.GetString());\n\n \/\/ Copy the data out into a Frame object\n LOG4CXX_DEBUG(logger, \"Creating Frame object\");\n Frame frame(bytes_per_pixel, p2m_dims);\n LOG4CXX_DEBUG(logger, \"Copying buffer ID: \" << msg_doc[\"params\"][\"buffer_id\"].GetInt64());\n smp.get_frame(frame, msg_doc[\"params\"][\"buffer_id\"].GetInt64());\n LOG4CXX_DEBUG(logger, \"Frame completeness: \" << frame.get_header()->packets_received << \" packets received\");\n\n \/\/ Clear the json string buffer and reset the writer so we can re-use them\n \/\/ after modifying the Document DOM object\n buffer.Clear();\n writer.Reset(buffer);\n\n \/\/ We want to return the exact same JSON message back to the frameReceiver\n \/\/ so we just modify the relevant bits: msg_val: from frame_ready to frame_release\n \/\/ and update the timestamp\n msg_doc[\"msg_val\"].SetString(\"frame_release\");\n\n \/\/ Create and update the timestamp in the JSON message\n boost::posix_time::ptime msg_timestamp = boost::posix_time::microsec_clock::local_time();\n string msg_timestamp_str = boost::posix_time::to_iso_extended_string(msg_timestamp);\n msg_doc[\"timestamp\"].SetString(StringRef(msg_timestamp_str.c_str()));\n\n \/\/ Encode the JSON Document DOM object using the writer\n msg_doc.Accept(writer);\n LOG4CXX_DEBUG(logger, \"Changing msg_val: \" << msg_doc[\"msg_val\"].GetString());\n string release_msg(buffer.GetString()); \/\/ Get a copy of the JSON string\n LOG4CXX_DEBUG(logger, \"New json: \" << release_msg);\n\n LOG4CXX_DEBUG(logger, \"Sending release response\");\n \/\/ Send the new JSON object (string) back to the frameReceiver on the \"release\" ZMQ socket\n size_t nbytes = zsocket_release.send(release_msg.c_str(), release_msg.size() + 1);\n LOG4CXX_DEBUG(logger, \"Sent \" << nbytes << \" bytes\");\n\n \/\/ Write the frame to disk\n hdfwr.writeFrame(frame);\n\n } else\n {\n \/\/ No new data\n }\n\n \/\/ Quit the loop if we have received the desired number of frames\n if (notification_count >= vm[\"frames\"].as<unsigned int>()) keep_running=false;\n }\n hdfwr.closeFile();\n return rc;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _OBJECT_HXX\n#define _OBJECT_HXX\n\n#define _SVSTDARR_ULONGS\n#include <types.hxx>\n#include <slot.hxx>\n#include <vector>\n#include <tools\/list.hxx>\n\nstruct SvSlotElement\n{\n SvMetaSlotRef xSlot;\n ByteString aPrefix;\n SvSlotElement( SvMetaSlot * pS, const ByteString & rPrefix )\n : xSlot( pS )\n , aPrefix( rPrefix )\n {}\n};\ntypedef std::vector< SvSlotElement* > SvSlotElementList;\n\nclass SvMetaClass;\ntypedef ::std::vector< SvMetaClass* > SvMetaClassList;\n\nSV_DECL_REF(SvMetaClass)\nclass SvClassElement : public SvPersistBase\n{\n SvBOOL aAutomation;\n ByteString aPrefix;\n SvMetaClassRef xClass;\npublic:\n SV_DECL_PERSIST1( SvClassElement, SvPersistBase, 1 )\n SvClassElement();\n\n void SetPrefix( const ByteString & rPrefix )\n { aPrefix = rPrefix; }\n const ByteString & GetPrefix() const\n { return aPrefix; }\n\n void SetAutomation( sal_Bool rAutomation )\n { aAutomation = rAutomation; }\n sal_Bool GetAutomation() const\n { return aAutomation; }\n\n void SetClass( SvMetaClass * pClass )\n { xClass = pClass; }\n SvMetaClass * GetClass() const\n { return xClass; }\n};\n\nSV_DECL_IMPL_REF(SvClassElement)\nSV_DECL_IMPL_PERSIST_LIST(SvClassElement,SvClassElement *)\n\nclass SvMetaModule;\nSV_DECL_PERSIST_LIST(SvMetaClass,SvMetaClass *)\nclass SvMetaClass : public SvMetaType\n{\n SvMetaAttributeMemberList aAttrList;\n SvClassElementMemberList aClassList;\n SvMetaClassRef aSuperClass;\n SvBOOL aAutomation;\n SvMetaClassRef xAutomationInterface;\n\n sal_Bool TestAttribute( SvIdlDataBase & rBase, SvTokenStream & rInStm,\n SvMetaAttribute & rAttr ) const;\n#ifdef IDL_COMPILER\n void WriteSlotStubs( const ByteString & rShellName,\n SvSlotElementList & rSlotList,\n ByteStringList & rList,\n SvStream & rOutStm );\n sal_uInt16 WriteSlotParamArray( SvIdlDataBase & rBase,\n SvSlotElementList & rSlotList,\n SvStream & rOutStm );\n sal_uInt16 WriteSlots( const ByteString & rShellName, sal_uInt16 nCount,\n SvSlotElementList & rSlotList,\n SvIdlDataBase & rBase,\n SvStream & rOutStm );\n\n void InsertSlots( SvSlotElementList& rList, std::vector<sal_uLong>& rSuperList,\n SvMetaClassList & rClassList,\n const ByteString & rPrefix, SvIdlDataBase& rBase );\n\nprotected:\n virtual void ReadAttributesSvIdl( SvIdlDataBase & rBase,\n SvTokenStream & rInStm );\n virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase,\n SvStream & rOutStm, sal_uInt16 nTab );\n virtual void ReadContextSvIdl( SvIdlDataBase &,\n SvTokenStream & rInStm );\n virtual void WriteContextSvIdl( SvIdlDataBase & rBase,\n SvStream & rOutStm, sal_uInt16 nTab );\n void WriteOdlMembers( ByteStringList & rSuperList,\n sal_Bool bVariable, sal_Bool bWriteTab,\n SvIdlDataBase & rBase,\n SvStream & rOutStm, sal_uInt16 nTab );\n#endif\npublic:\n SV_DECL_META_FACTORY1( SvMetaClass, SvMetaType, 6 )\n SvMetaClass();\n\n sal_Bool GetAutomation() const\n { return aAutomation; }\n SvMetaClass * GetSuperClass() const\n { return aSuperClass; }\n\n void FillClasses( SvMetaClassList & rList );\n\n const SvClassElementMemberList&\n GetClassList() const\n { return aClassList; }\n\n#ifdef IDL_COMPILER\n virtual sal_Bool ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );\n virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );\n virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm,\n sal_uInt16 nTab,\n WriteType, WriteAttribute = 0 );\n virtual void WriteSfx( SvIdlDataBase & rBase, SvStream & rOutStm );\n virtual void WriteHelpIds( SvIdlDataBase & rBase, SvStream & rOutStm,\n Table* pTable );\n virtual void WriteSrc( SvIdlDataBase & rBase, SvStream & rOutStm,\n Table * pTable );\n virtual void WriteCxx( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );\n virtual void WriteHxx( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );\n#endif\n};\nSV_IMPL_REF(SvMetaClass)\nSV_IMPL_PERSIST_LIST(SvMetaClass,SvMetaClass *)\n\n\n#endif \/\/ _OBJECT_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Remove unneed include of <tools\/list.hxx><commit_after>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _OBJECT_HXX\n#define _OBJECT_HXX\n\n#define _SVSTDARR_ULONGS\n#include <types.hxx>\n#include <slot.hxx>\n#include <vector>\n\nstruct SvSlotElement\n{\n SvMetaSlotRef xSlot;\n ByteString aPrefix;\n SvSlotElement( SvMetaSlot * pS, const ByteString & rPrefix )\n : xSlot( pS )\n , aPrefix( rPrefix )\n {}\n};\ntypedef std::vector< SvSlotElement* > SvSlotElementList;\n\nclass SvMetaClass;\ntypedef ::std::vector< SvMetaClass* > SvMetaClassList;\n\nSV_DECL_REF(SvMetaClass)\nclass SvClassElement : public SvPersistBase\n{\n SvBOOL aAutomation;\n ByteString aPrefix;\n SvMetaClassRef xClass;\npublic:\n SV_DECL_PERSIST1( SvClassElement, SvPersistBase, 1 )\n SvClassElement();\n\n void SetPrefix( const ByteString & rPrefix )\n { aPrefix = rPrefix; }\n const ByteString & GetPrefix() const\n { return aPrefix; }\n\n void SetAutomation( sal_Bool rAutomation )\n { aAutomation = rAutomation; }\n sal_Bool GetAutomation() const\n { return aAutomation; }\n\n void SetClass( SvMetaClass * pClass )\n { xClass = pClass; }\n SvMetaClass * GetClass() const\n { return xClass; }\n};\n\nSV_DECL_IMPL_REF(SvClassElement)\nSV_DECL_IMPL_PERSIST_LIST(SvClassElement,SvClassElement *)\n\nclass SvMetaModule;\nSV_DECL_PERSIST_LIST(SvMetaClass,SvMetaClass *)\nclass SvMetaClass : public SvMetaType\n{\n SvMetaAttributeMemberList aAttrList;\n SvClassElementMemberList aClassList;\n SvMetaClassRef aSuperClass;\n SvBOOL aAutomation;\n SvMetaClassRef xAutomationInterface;\n\n sal_Bool TestAttribute( SvIdlDataBase & rBase, SvTokenStream & rInStm,\n SvMetaAttribute & rAttr ) const;\n#ifdef IDL_COMPILER\n void WriteSlotStubs( const ByteString & rShellName,\n SvSlotElementList & rSlotList,\n ByteStringList & rList,\n SvStream & rOutStm );\n sal_uInt16 WriteSlotParamArray( SvIdlDataBase & rBase,\n SvSlotElementList & rSlotList,\n SvStream & rOutStm );\n sal_uInt16 WriteSlots( const ByteString & rShellName, sal_uInt16 nCount,\n SvSlotElementList & rSlotList,\n SvIdlDataBase & rBase,\n SvStream & rOutStm );\n\n void InsertSlots( SvSlotElementList& rList, std::vector<sal_uLong>& rSuperList,\n SvMetaClassList & rClassList,\n const ByteString & rPrefix, SvIdlDataBase& rBase );\n\nprotected:\n virtual void ReadAttributesSvIdl( SvIdlDataBase & rBase,\n SvTokenStream & rInStm );\n virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase,\n SvStream & rOutStm, sal_uInt16 nTab );\n virtual void ReadContextSvIdl( SvIdlDataBase &,\n SvTokenStream & rInStm );\n virtual void WriteContextSvIdl( SvIdlDataBase & rBase,\n SvStream & rOutStm, sal_uInt16 nTab );\n void WriteOdlMembers( ByteStringList & rSuperList,\n sal_Bool bVariable, sal_Bool bWriteTab,\n SvIdlDataBase & rBase,\n SvStream & rOutStm, sal_uInt16 nTab );\n#endif\npublic:\n SV_DECL_META_FACTORY1( SvMetaClass, SvMetaType, 6 )\n SvMetaClass();\n\n sal_Bool GetAutomation() const\n { return aAutomation; }\n SvMetaClass * GetSuperClass() const\n { return aSuperClass; }\n\n void FillClasses( SvMetaClassList & rList );\n\n const SvClassElementMemberList&\n GetClassList() const\n { return aClassList; }\n\n#ifdef IDL_COMPILER\n virtual sal_Bool ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );\n virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );\n virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm,\n sal_uInt16 nTab,\n WriteType, WriteAttribute = 0 );\n virtual void WriteSfx( SvIdlDataBase & rBase, SvStream & rOutStm );\n virtual void WriteHelpIds( SvIdlDataBase & rBase, SvStream & rOutStm,\n Table* pTable );\n virtual void WriteSrc( SvIdlDataBase & rBase, SvStream & rOutStm,\n Table * pTable );\n virtual void WriteCxx( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );\n virtual void WriteHxx( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );\n#endif\n};\nSV_IMPL_REF(SvMetaClass)\nSV_IMPL_PERSIST_LIST(SvMetaClass,SvMetaClass *)\n\n\n#endif \/\/ _OBJECT_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n# ifndef CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP\n# define CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the\n Eclipse Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n# include <cppad\/local\/optimize\/hash_code.hpp>\n\/*!\n\\file match_op.hpp\nCheck if current operator matches a previous operator.\n*\/\n\/\/ BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\nnamespace CppAD { namespace local { namespace optimize {\n\/*!\nSearch for a previous operator that matches the current one.\n\n\\param var2op\nmapping from variable index to operator index.\n\n\\param op_info\nmapping from operator index to operator information\n\n\\param current\nis the index of the current operator.\n\n\\li\nThis must be a unary or binary\noperator; hence, NumArg( op_info[current].op ) is one or two.\nThere is one exception, NumRes( ErfOp ) == 3, but arg[0]\nis the only true arguments (the others are always the same).\n\n\\li\nThis must not be a VecAD load or store operation; i.e.,\nLtpvOp, LtvpOp, LtvvOp, StppOp, StpvOp, StvpOp, StvvOp.\nIt also must not be an independent variable operator InvOp.\n\n\\param hash_table_op\nis a vector with size CPPAD_HASH_TABLE_SIZE\nthat maps a hash code to the corresponding\nvariable index in the operation sequence.\nAll the values in this table are less than current.\n\n\\param code [out]\nThe input value of code does not matter.\nThe output value of code is the hash code corresponding to\nthe current operation in the new operation sequence.\n\n\\return\nWe refer to the return value as pevious.\nIf pevious == 0, no match was found.\nIf previous != 0,\nit is a pevious operator that can be used in place of current.\nIn addition op_info[previous].previous == 0.\n*\/\n\ninline size_t match_op(\n\tconst vector<size_t>& var2op ,\n\tconst vector<struct_op_info>& op_info ,\n\tsize_t current ,\n\tconst vector<size_t>& hash_table_op ,\n\tunsigned short& code )\n{\t\/\/ current operator\n\tOpCode op = op_info[current].op;\n\tconst addr_t* arg = op_info[current].arg;\n\t\/\/\n\t\/\/ which arguments are variable\n\tsize_t num_arg = NumArg(op);\n\t\/\/\n\tbool variable[2];\n\tvariable[0] = false;\n\tvariable[1] = false;\n\tswitch(op)\n\t{\t\/\/\n\t\tcase ErfOp:\n\t\tnum_arg = 1; \/\/ other arugments are always the same\n\t\t\/\/\n\t\tcase AbsOp:\n\t\tcase AcosOp:\n\t\tcase AcoshOp:\n\t\tcase AsinOp:\n\t\tcase AsinhOp:\n\t\tcase AtanOp:\n\t\tcase AtanhOp:\n\t\tcase CosOp:\n\t\tcase CoshOp:\n\t\tcase ExpOp:\n\t\tcase Expm1Op:\n\t\tcase LogOp:\n\t\tcase Log1pOp:\n\t\tcase SignOp:\n\t\tcase SinOp:\n\t\tcase SinhOp:\n\t\tcase SqrtOp:\n\t\tcase TanOp:\n\t\tcase TanhOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 1 );\n\t\tvariable[0] = true;\n\t\tbreak;\n\n\n\t\tcase AddpvOp:\n\t\tcase DisOp:\n\t\tcase DivpvOp:\n\t\tcase EqpvOp:\n\t\tcase LepvOp:\n\t\tcase LtpvOp:\n\t\tcase MulpvOp:\n\t\tcase NepvOp:\n\t\tcase PowpvOp:\n\t\tcase SubpvOp:\n\t\tcase ZmulpvOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[1] = true;\n\t\tbreak;\n\n\t\tcase DivvpOp:\n\t\tcase LevpOp:\n\t\tcase LtvpOp:\n\t\tcase PowvpOp:\n\t\tcase SubvpOp:\n\t\tcase ZmulvpOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[0] = true;\n\t\tbreak;\n\n\t\tcase AddvvOp:\n\t\tcase DivvvOp:\n\t\tcase EqvvOp:\n\t\tcase LevvOp:\n\t\tcase LtvvOp:\n\t\tcase MulvvOp:\n\t\tcase NevvOp:\n\t\tcase PowvvOp:\n\t\tcase SubvvOp:\n\t\tcase ZmulvvOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[0] = true;\n\t\tvariable[1] = true;\n\t\tbreak;\n\n\t\tdefault:\n\t\tCPPAD_ASSERT_UNKNOWN(false);\n\t}\n\t\/\/\n\t\/\/ If i-th argument to current operator has a previous operator,\n\t\/\/ this is the i-th argument for previous operator.\n\t\/\/ Otherwise, it is the i-th argument for the current operator\n\t\/\/ (if a previous variable exists)\n\taddr_t arg_match[2];\n\tfor(size_t j = 0; j < num_arg; ++j)\n\t{\targ_match[j] = arg[j];\n\t\tif( variable[j] )\n\t\t{\tsize_t previous = op_info[ var2op[arg[j]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\/\/\n\t\t\t\targ_match[j] = op_info[previous].i_var;\n\t\t\t}\n\t\t}\n\t}\n\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\/\/\n\t\/\/ candidate previous for current operator\n\tsize_t candidate = hash_table_op[code];\n\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\/\/\n\t\/\/ check for a match\n\tbool match = candidate != 0;\n\tmatch &= op == op_info[candidate].op;\n\tif( match )\n\t{\tfor(size_t j = 0; j < num_arg; j++)\n\t\t{\tif( variable[j] )\n\t\t\t{\tsize_t previous =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\t\/\/\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t}\n\t\t}\n\t\tif( match )\n\t\t\treturn candidate;\n\t}\n\n\t\/\/ special case where operator is commutative\n\tif( (op == AddvvOp) | (op == MulvvOp ) )\n\t{\tCPPAD_ASSERT_UNKNOWN( NumArg(op) == 2 );\n\t\tstd::swap( arg_match[0], arg_match[1] );\n\t\t\/\/\n\t\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\tcandidate = hash_table_op[code];\n\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\/\/\n\t\tmatch = candidate != 0;\n\t\tmatch &= op == op_info[candidate].op;\n\t\tif( match )\n\t\t{\tfor(size_t j = 0; j < num_arg; j++)\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( variable[j] )\n\t\t\t\tsize_t previous =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\t\/\/\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t}\n\t}\n\t\/\/ special op code used for no match\n\treturn 0;\n}\n\n} } } \/\/ END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\n\n# endif\n<commit_msg>optimize branch: match_op.hpp: improve speed by making Unary special case.<commit_after>\/\/ $Id$\n# ifndef CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP\n# define CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the\n Eclipse Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n# include <cppad\/local\/optimize\/hash_code.hpp>\n\/*!\n\\file match_op.hpp\nCheck if current operator matches a previous operator.\n*\/\n\/\/ BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\nnamespace CppAD { namespace local { namespace optimize {\n\/*!\nSearch for a previous operator that matches the current one.\n\n\\param var2op\nmapping from variable index to operator index.\n\n\\param op_info\nmapping from operator index to operator information\n\n\\param current\nis the index of the current operator.\n\n\\li\nThis must be a unary or binary\noperator; hence, NumArg( op_info[current].op ) is one or two.\nThere is one exception, NumRes( ErfOp ) == 3, but arg[0]\nis the only true arguments (the others are always the same).\n\n\\li\nThis must not be a VecAD load or store operation; i.e.,\nLtpvOp, LtvpOp, LtvvOp, StppOp, StpvOp, StvpOp, StvvOp.\nIt also must not be an independent variable operator InvOp.\n\n\\param hash_table_op\nis a vector with size CPPAD_HASH_TABLE_SIZE\nthat maps a hash code to the corresponding\nvariable index in the operation sequence.\nAll the values in this table are less than current.\n\n\\param code [out]\nThe input value of code does not matter.\nThe output value of code is the hash code corresponding to\nthe current operation in the new operation sequence.\n\n\\return\nWe refer to the return value as pevious.\nIf pevious == 0, no match was found.\nIf previous != 0,\nit is a pevious operator that can be used in place of current.\nIn addition op_info[previous].previous == 0.\n*\/\n\ninline size_t match_op(\n\tconst vector<size_t>& var2op ,\n\tconst vector<struct_op_info>& op_info ,\n\tsize_t current ,\n\tconst vector<size_t>& hash_table_op ,\n\tunsigned short& code )\n{\t\/\/ current operator\n\tOpCode op = op_info[current].op;\n\tconst addr_t* arg = op_info[current].arg;\n\t\/\/\n\t\/\/ which arguments are variable\n\tsize_t num_arg = NumArg(op);\n\t\/\/\n\tbool variable[2];\n\tvariable[0] = false;\n\tvariable[1] = false;\n\t\/\/\n\t\/\/ If i-th argument to current operator has a previous operator,\n\t\/\/ this is the i-th argument for previous operator.\n\t\/\/ Otherwise, it is the i-th argument for the current operator\n\t\/\/ (if a previous variable exists)\n\taddr_t arg_match[2];\n\tswitch(op)\n\t{\t\/\/\n\t\tcase ErfOp:\n\t\tcase AbsOp:\n\t\tcase AcosOp:\n\t\tcase AcoshOp:\n\t\tcase AsinOp:\n\t\tcase AsinhOp:\n\t\tcase AtanOp:\n\t\tcase AtanhOp:\n\t\tcase CosOp:\n\t\tcase CoshOp:\n\t\tcase ExpOp:\n\t\tcase Expm1Op:\n\t\tcase LogOp:\n\t\tcase Log1pOp:\n\t\tcase SignOp:\n\t\tcase SinOp:\n\t\tcase SinhOp:\n\t\tcase SqrtOp:\n\t\tcase TanOp:\n\t\tcase TanhOp:\n\t\t{\targ_match[0] = arg[0];\n\t\t\tsize_t previous = op_info[ var2op[arg[0]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\targ_match[0] = op_info[previous].i_var;\n\t\t\t}\n\t\t\tnum_arg = 1;\n\t\t\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\t\t\/\/\n\t\t\t\/\/ candidate previous for current operator\n\t\t\tsize_t candidate = hash_table_op[code];\n\t\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\t\/\/\n\t\t\tif( (candidate == 0) | (op != op_info[candidate].op) )\n\t\t\t\treturn 0;\n\t\t\t\/\/\n\t\t\t\/\/ check for a match\n\t\t\tbool match;\n\t\t\tprevious = op_info[ var2op[op_info[candidate].arg[0]] ].previous;\n\t\t\tif( previous == 0 )\n\t\t\t\tmatch = arg_match[0] == op_info[candidate].arg[0];\n\t\t\telse\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\tmatch = arg_match[0] == addr_t( op_info[previous].i_var );\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t\treturn 0;\n\t\t}\n\t\tbreak;\n\n\n\t\tcase AddpvOp:\n\t\tcase DisOp:\n\t\tcase DivpvOp:\n\t\tcase EqpvOp:\n\t\tcase LepvOp:\n\t\tcase LtpvOp:\n\t\tcase MulpvOp:\n\t\tcase NepvOp:\n\t\tcase PowpvOp:\n\t\tcase SubpvOp:\n\t\tcase ZmulpvOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[1] = true;\n\t\tbreak;\n\n\t\tcase DivvpOp:\n\t\tcase LevpOp:\n\t\tcase LtvpOp:\n\t\tcase PowvpOp:\n\t\tcase SubvpOp:\n\t\tcase ZmulvpOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[0] = true;\n\t\tbreak;\n\n\t\tcase AddvvOp:\n\t\tcase DivvvOp:\n\t\tcase EqvvOp:\n\t\tcase LevvOp:\n\t\tcase LtvvOp:\n\t\tcase MulvvOp:\n\t\tcase NevvOp:\n\t\tcase PowvvOp:\n\t\tcase SubvvOp:\n\t\tcase ZmulvvOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[0] = true;\n\t\tvariable[1] = true;\n\t\tbreak;\n\n\t\tdefault:\n\t\tCPPAD_ASSERT_UNKNOWN(false);\n\t}\n\tfor(size_t j = 0; j < num_arg; ++j)\n\t{\targ_match[j] = arg[j];\n\t\tif( variable[j] )\n\t\t{\tsize_t previous = op_info[ var2op[arg[j]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\/\/\n\t\t\t\targ_match[j] = op_info[previous].i_var;\n\t\t\t}\n\t\t}\n\t}\n\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\/\/\n\t\/\/ candidate previous for current operator\n\tsize_t candidate = hash_table_op[code];\n\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\/\/\n\t\/\/ check for a match\n\tbool match = candidate != 0;\n\tmatch &= op == op_info[candidate].op;\n\tif( match )\n\t{\tfor(size_t j = 0; j < num_arg; j++)\n\t\t{\tif( variable[j] )\n\t\t\t{\tsize_t previous =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\t\/\/\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t}\n\t\t}\n\t\tif( match )\n\t\t\treturn candidate;\n\t}\n\n\t\/\/ special case where operator is commutative\n\tif( (op == AddvvOp) | (op == MulvvOp ) )\n\t{\tCPPAD_ASSERT_UNKNOWN( NumArg(op) == 2 );\n\t\tstd::swap( arg_match[0], arg_match[1] );\n\t\t\/\/\n\t\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\tcandidate = hash_table_op[code];\n\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\/\/\n\t\tmatch = candidate != 0;\n\t\tmatch &= op == op_info[candidate].op;\n\t\tif( match )\n\t\t{\tfor(size_t j = 0; j < num_arg; j++)\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( variable[j] )\n\t\t\t\tsize_t previous =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\t\/\/\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t}\n\t}\n\t\/\/ special op code used for no match\n\treturn 0;\n}\n\n} } } \/\/ END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\n\n# endif\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"libpng17\/png.h\"\n\n#include \"png_load.h\"\n#include \"base\/logging.h\"\n\n\/\/ *image_data_ptr should be deleted with free()\n\/\/ return value of 1 == success.\nint pngLoad(const char *file, int *pwidth, int *pheight, unsigned char **image_data_ptr, bool flip) {\n\tif (flip)\n\t\tELOG(\"pngLoad: flip flag not supported, image will be loaded upside down\");\n\tpng_image png;\n\tmemset(&png, 0, sizeof(png));\n\tpng.version = PNG_IMAGE_VERSION;\n\n\tpng_image_begin_read_from_file(&png, file);\n\n\tif (PNG_IMAGE_FAILED(png))\n\t{\n\t\tELOG(\"pngLoad: %s\", png.message);\n\t\treturn 0;\n\t}\n\t*pwidth = png.width;\n\t*pheight = png.height;\n\tpng.format = PNG_FORMAT_RGBA;\n\n\tint stride = PNG_IMAGE_ROW_STRIDE(png);\n\t*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));\n\tpng_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);\n\n\treturn 1;\n}\n\nint pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr,\n\tbool flip) {\n\tif (flip)\n\t\tELOG(\"pngLoad: flip flag not supported, image will be loaded upside down\");\n\tpng_image png;\n\tmemset(&png, 0, sizeof(png));\n\tpng.version = PNG_IMAGE_VERSION;\n\n\tpng_image_begin_read_from_memory(&png, input_ptr, input_len);\n\n\tif (PNG_IMAGE_FAILED(png))\n\t{\n\t\tELOG(\"pngLoad: %s\", png.message);\n\t\treturn 0;\n\t}\n\t*pwidth = png.width;\n\t*pheight = png.height;\n\tpng.format = PNG_FORMAT_RGBA;\n\n\tint stride = PNG_IMAGE_ROW_STRIDE(png);\n\t*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));\n\tpng_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);\n\n\treturn 1;\n}\n<commit_msg>Qt: Use inbuilt png handler to resolve conflicts.<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef USING_QT_UI\n#include <QImage>\n#else\n#include \"libpng17\/png.h\"\n#endif\n\n#include \"png_load.h\"\n#include \"base\/logging.h\"\n\n\/\/ *image_data_ptr should be deleted with free()\n\/\/ return value of 1 == success.\nint pngLoad(const char *file, int *pwidth, int *pheight, unsigned char **image_data_ptr, bool flip) {\n#ifdef USING_QT_UI\n\tQImage image(file, \"PNG\");\n\tif (image.isNull()) {\n\t\tELOG(\"pngLoad: Error loading image %s\", file);\n\t\treturn 0;\n\t}\n\tif (flip)\n\t\timage = image.mirrored();\n\timage.convertToFormat(QImage::Format_RGB32);\n\t*pwidth = image.width();\n\t*pheight = image.height();\n\t*image_data_ptr = (unsigned char *)malloc(image.byteCount());\n\tmemcpy(image.bits(), *image_data_ptr, image.byteCount());\n#else\n\tif (flip)\n\t\tELOG(\"pngLoad: flip flag not supported, image will be loaded upside down\");\n\tpng_image png;\n\tmemset(&png, 0, sizeof(png));\n\tpng.version = PNG_IMAGE_VERSION;\n\n\tpng_image_begin_read_from_file(&png, file);\n\n\tif (PNG_IMAGE_FAILED(png))\n\t{\n\t\tELOG(\"pngLoad: %s\", png.message);\n\t\treturn 0;\n\t}\n\t*pwidth = png.width;\n\t*pheight = png.height;\n\tpng.format = PNG_FORMAT_RGBA;\n\n\tint stride = PNG_IMAGE_ROW_STRIDE(png);\n\t*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));\n\tpng_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);\n#endif\n\n\treturn 1;\n}\n\nint pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr,\n\tbool flip) {\n#ifdef USING_QT_UI\n\tQImage image;\n\tif (!image.loadFromData(input_ptr, input_len)) {\n\t\tELOG(\"pngLoad: Error loading image\");\n\t\treturn 0;\n\t}\n\tif (flip)\n\t\timage = image.mirrored();\n\timage.convertToFormat(QImage::Format_RGB32);\n\t*pwidth = image.width();\n\t*pheight = image.height();\n\t*image_data_ptr = (unsigned char *)malloc(image.byteCount());\n\tmemcpy(image.bits(), *image_data_ptr, image.byteCount());\n#else\n\tif (flip)\n\t\tELOG(\"pngLoad: flip flag not supported, image will be loaded upside down\");\n\tpng_image png;\n\tmemset(&png, 0, sizeof(png));\n\tpng.version = PNG_IMAGE_VERSION;\n\n\tpng_image_begin_read_from_memory(&png, input_ptr, input_len);\n\n\tif (PNG_IMAGE_FAILED(png))\n\t{\n\t\tELOG(\"pngLoad: %s\", png.message);\n\t\treturn 0;\n\t}\n\t*pwidth = png.width;\n\t*pheight = png.height;\n\tpng.format = PNG_FORMAT_RGBA;\n\n\tint stride = PNG_IMAGE_ROW_STRIDE(png);\n\t*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));\n\tpng_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);\n#endif\n\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"xchainer\/elementwise.h\"\n\n#include <tuple>\n\n#include <gtest\/gtest.h>\n\n#include \"xchainer\/array.h\"\n#include \"xchainer\/axes.h\"\n#include \"xchainer\/shape.h\"\n#include \"xchainer\/strides.h\"\n#include \"xchainer\/testing\/array.h\"\n#include \"xchainer\/testing\/context_session.h\"\n\nnamespace xchainer {\nnamespace {\n\nTEST(ElementwiseTest, GetSquashedStrides) {\n {\n Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {0, 1, 2, 3});\n EXPECT_EQ(4, squashed.ndim());\n EXPECT_EQ(3, squashed[0]);\n EXPECT_EQ(2, squashed[1]);\n EXPECT_EQ(5, squashed[2]);\n EXPECT_EQ(4, squashed[3]);\n }\n {\n Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {1, 2});\n EXPECT_EQ(2, squashed.ndim());\n EXPECT_EQ(2, squashed[0]);\n EXPECT_EQ(5, squashed[1]);\n }\n {\n Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {});\n EXPECT_EQ(0, squashed.ndim());\n }\n {\n Strides squashed = GetSquashedStrides({}, {});\n EXPECT_EQ(0, squashed.ndim());\n }\n}\n\nTEST(ElementwiseTest, SquashAllDimensions) {\n testing::ContextSession context_session;\n Shape shape{3, 2, 5, 4};\n Array a = testing::BuildArray(shape).WithLinearData<float>();\n\n Shape squashed{};\n Axes keep{};\n std::tie(squashed, keep) = SquashShape(a);\n\n EXPECT_EQ(1, squashed.ndim());\n EXPECT_EQ(shape[0] * shape[1] * shape[2] * shape[3], squashed[0]);\n EXPECT_EQ(1, keep.ndim());\n EXPECT_EQ(3, keep[0]);\n}\n\nTEST(ElementwiseTest, SquashPartialDimensions) {\n testing::ContextSession context_session;\n Shape shape{3, 2, 5, 4};\n Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 2, 0, 0});\n\n Shape squashed{};\n Axes keep{};\n std::tie(squashed, keep) = SquashShape(a);\n\n EXPECT_EQ(2, squashed.ndim());\n EXPECT_EQ(shape[0] * shape[1], squashed[0]);\n EXPECT_EQ(shape[2] * shape[3], squashed[1]);\n EXPECT_EQ(2, keep.ndim());\n EXPECT_EQ(1, keep[0]);\n EXPECT_EQ(3, keep[1]);\n}\n\nTEST(ElementwiseTest, SquashUnitLengthDimensions) {\n testing::ContextSession context_session;\n Shape shape{3, 2, 1, 4};\n Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding(1);\n\n Shape squashed{};\n Axes keep{};\n std::tie(squashed, keep) = SquashShape(a);\n\n EXPECT_EQ(3, squashed.ndim());\n EXPECT_EQ(shape[0], squashed[0]);\n EXPECT_EQ(shape[1], squashed[1]);\n EXPECT_EQ(shape[3], squashed[2]);\n EXPECT_EQ(3, keep.ndim());\n EXPECT_EQ(0, keep[0]);\n EXPECT_EQ(1, keep[1]);\n EXPECT_EQ(3, keep[2]);\n}\n\nTEST(ElementwiseTest, SquashMultipleArraysDimensions) {\n testing::ContextSession context_session;\n Shape shape{3, 2, 5, 4};\n Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 2, 0, 0});\n Array b = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 0, 1, 0});\n\n Shape squashed{};\n Axes keep{};\n std::tie(squashed, keep) = SquashShape(a, b);\n\n EXPECT_EQ(3, squashed.ndim());\n EXPECT_EQ(shape[0] * shape[1], squashed[0]);\n EXPECT_EQ(shape[2], squashed[1]);\n EXPECT_EQ(shape[3], squashed[2]);\n EXPECT_EQ(3, keep.ndim());\n EXPECT_EQ(1, keep[0]);\n EXPECT_EQ(2, keep[1]);\n EXPECT_EQ(3, keep[2]);\n}\n\n} \/\/ namespace\n} \/\/ namespace xchainer\n<commit_msg>Avoid copies in test<commit_after>#include \"xchainer\/elementwise.h\"\n\n#include <tuple>\n\n#include <gtest\/gtest.h>\n\n#include \"xchainer\/array.h\"\n#include \"xchainer\/axes.h\"\n#include \"xchainer\/shape.h\"\n#include \"xchainer\/strides.h\"\n#include \"xchainer\/testing\/array.h\"\n#include \"xchainer\/testing\/context_session.h\"\n\nnamespace xchainer {\nnamespace {\n\nTEST(ElementwiseTest, GetSquashedStrides) {\n {\n Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {0, 1, 2, 3});\n EXPECT_EQ(4, squashed.ndim());\n EXPECT_EQ(3, squashed[0]);\n EXPECT_EQ(2, squashed[1]);\n EXPECT_EQ(5, squashed[2]);\n EXPECT_EQ(4, squashed[3]);\n }\n {\n Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {1, 2});\n EXPECT_EQ(2, squashed.ndim());\n EXPECT_EQ(2, squashed[0]);\n EXPECT_EQ(5, squashed[1]);\n }\n {\n Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {});\n EXPECT_EQ(0, squashed.ndim());\n }\n {\n Strides squashed = GetSquashedStrides({}, {});\n EXPECT_EQ(0, squashed.ndim());\n }\n}\n\nTEST(ElementwiseTest, SquashAllDimensions) {\n testing::ContextSession context_session;\n Shape shape{3, 2, 5, 4};\n Array a = testing::BuildArray(shape).WithLinearData<float>();\n\n std::tuple<Shape, Axes> squashed_result = SquashShape(a);\n const Shape& squashed = std::get<0>(squashed_result);\n const Axes& keep = std::get<1>(squashed_result);\n\n EXPECT_EQ(1, squashed.ndim());\n EXPECT_EQ(shape[0] * shape[1] * shape[2] * shape[3], squashed[0]);\n EXPECT_EQ(1, keep.ndim());\n EXPECT_EQ(3, keep[0]);\n}\n\nTEST(ElementwiseTest, SquashPartialDimensions) {\n testing::ContextSession context_session;\n Shape shape{3, 2, 5, 4};\n Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 2, 0, 0});\n\n std::tuple<Shape, Axes> squashed_result = SquashShape(a);\n const Shape& squashed = std::get<0>(squashed_result);\n const Axes& keep = std::get<1>(squashed_result);\n\n EXPECT_EQ(2, squashed.ndim());\n EXPECT_EQ(shape[0] * shape[1], squashed[0]);\n EXPECT_EQ(shape[2] * shape[3], squashed[1]);\n EXPECT_EQ(2, keep.ndim());\n EXPECT_EQ(1, keep[0]);\n EXPECT_EQ(3, keep[1]);\n}\n\nTEST(ElementwiseTest, SquashUnitLengthDimensions) {\n testing::ContextSession context_session;\n Shape shape{3, 2, 1, 4};\n Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding(1);\n\n std::tuple<Shape, Axes> squashed_result = SquashShape(a);\n const Shape& squashed = std::get<0>(squashed_result);\n const Axes& keep = std::get<1>(squashed_result);\n\n EXPECT_EQ(3, squashed.ndim());\n EXPECT_EQ(shape[0], squashed[0]);\n EXPECT_EQ(shape[1], squashed[1]);\n EXPECT_EQ(shape[3], squashed[2]);\n EXPECT_EQ(3, keep.ndim());\n EXPECT_EQ(0, keep[0]);\n EXPECT_EQ(1, keep[1]);\n EXPECT_EQ(3, keep[2]);\n}\n\nTEST(ElementwiseTest, SquashMultipleArraysDimensions) {\n testing::ContextSession context_session;\n Shape shape{3, 2, 5, 4};\n Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 2, 0, 0});\n Array b = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 0, 1, 0});\n\n std::tuple<Shape, Axes> squashed_result = SquashShape(a, b);\n const Shape& squashed = std::get<0>(squashed_result);\n const Axes& keep = std::get<1>(squashed_result);\n\n EXPECT_EQ(3, squashed.ndim());\n EXPECT_EQ(shape[0] * shape[1], squashed[0]);\n EXPECT_EQ(shape[2], squashed[1]);\n EXPECT_EQ(shape[3], squashed[2]);\n EXPECT_EQ(3, keep.ndim());\n EXPECT_EQ(1, keep[0]);\n EXPECT_EQ(2, keep[1]);\n EXPECT_EQ(3, keep[2]);\n}\n\n} \/\/ namespace\n} \/\/ namespace xchainer\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPropAssembly.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkPropAssembly.h\"\n#include \"vtkViewport.h\"\n#include \"vtkAssemblyNode.h\"\n#include \"vtkObjectFactory.h\"\n\n\/\/-----------------------------------------------------------------------------\nvtkPropAssembly* vtkPropAssembly::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkPropAssembly\");\n if(ret)\n {\n return (vtkPropAssembly*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkPropAssembly;\n}\n\n\/\/ Construct object with no children.\nvtkPropAssembly::vtkPropAssembly()\n{\n this->Parts = vtkPropCollection::New();\n}\n\nvtkPropAssembly::~vtkPropAssembly()\n{\n this->Parts->Delete();\n this->Parts = NULL;\n}\n\n\/\/ Add a part to the list of Parts.\nvoid vtkPropAssembly::AddPart(vtkProp *prop)\n{\n if ( ! this->Parts->IsItemPresent(prop) )\n {\n this->Parts->AddItem(prop);\n this->Modified();\n } \n}\n\n\/\/ Remove a part from the list of parts,\nvoid vtkPropAssembly::RemovePart(vtkProp *prop)\n{\n if ( this->Parts->IsItemPresent(prop) )\n {\n this->Parts->RemoveItem(prop);\n this->Modified();\n } \n}\n\n\/\/ Get the list of parts for this prop assembly.\nvtkPropCollection *vtkPropAssembly::GetParts() \n{\n return this->Parts;\n}\n\n\/\/ Render this assembly and all of its Parts. The rendering process is recursive.\nint vtkPropAssembly::RenderTranslucentGeometry(vtkViewport *ren)\n{\n vtkProp *prop;\n vtkAssemblyPath *path;\n float fraction;\n int renderedSomething=0;\n\n fraction = this->AllocatedRenderTime \/ \n (float)this->Parts->GetNumberOfItems();\n \n \/\/ render the Paths\n for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )\n {\n prop = path->GetLastNode()->GetProp();\n if ( prop->GetVisibility() )\n {\n prop->SetAllocatedRenderTime(fraction, ren);\n prop->PokeMatrix(path->GetLastNode()->GetMatrix());\n renderedSomething += prop->RenderTranslucentGeometry(ren);\n prop->PokeMatrix(NULL);\n }\n }\n\n return renderedSomething;\n}\n\n\/\/ Render this assembly and all its parts. The rendering process is recursive.\nint vtkPropAssembly::RenderOpaqueGeometry(vtkViewport *ren)\n{\n vtkProp *prop;\n vtkAssemblyPath *path;\n float fraction;\n int renderedSomething=0;\n\n \/\/ Make sure the paths are up-to-date\n this->UpdatePaths();\n\n fraction = this->AllocatedRenderTime \/ \n (float)this->Parts->GetNumberOfItems();\n \n \/\/ render the Paths\n for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )\n {\n prop = path->GetLastNode()->GetProp();\n if ( prop->GetVisibility() )\n {\n prop->SetAllocatedRenderTime(fraction, ren);\n prop->PokeMatrix(path->GetLastNode()->GetMatrix());\n renderedSomething += prop->RenderOpaqueGeometry(ren);\n prop->PokeMatrix(NULL);\n }\n }\n\n return renderedSomething;\n}\n\n\/\/ Render this assembly and all its parts. The rendering process is recursive.\nint vtkPropAssembly::RenderOverlay(vtkViewport *ren)\n{\n vtkProp *prop;\n vtkAssemblyPath *path;\n float fraction;\n int renderedSomething=0;\n\n \/\/ Make sure the paths are up-to-date\n this->UpdatePaths();\n\n fraction = this->AllocatedRenderTime \/ \n (float)this->Parts->GetNumberOfItems();\n \n for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )\n {\n prop = path->GetLastNode()->GetProp();\n if ( prop->GetVisibility() )\n {\n prop->SetAllocatedRenderTime(fraction, ren);\n prop->PokeMatrix(path->GetLastNode()->GetMatrix());\n renderedSomething += prop->RenderOverlay(ren);\n prop->PokeMatrix(NULL);\n }\n }\n\n return renderedSomething;\n}\n\n\nvoid vtkPropAssembly::ReleaseGraphicsResources(vtkWindow *renWin)\n{\n vtkProp *part;\n\n vtkProp::ReleaseGraphicsResources(renWin);\n\n \/\/ broadcast the message down the Parts\n for ( this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )\n {\n part->ReleaseGraphicsResources(renWin);\n }\n}\n\n\/\/ Get the bounds for the assembly as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).\nfloat *vtkPropAssembly::GetBounds()\n{\n vtkProp *part;\n int i, n;\n float *bounds, bbox[24];\n int partVisible=0;\n\n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;\n \n for ( this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )\n {\n if ( part->GetVisibility() )\n {\n bounds = part->GetBounds();\n\n if ( bounds != NULL )\n {\n \/\/ For the purposes of GetBounds, an object is visisble only if\n \/\/ its visibility is on and it has visible parts.\n partVisible = 1;\n\n \/\/ fill out vertices of a bounding box\n bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5];\n bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5];\n bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5];\n bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5];\n bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4];\n bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4];\n bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4];\n bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4];\n\n for (i = 0; i < 8; i++)\n {\n for (n = 0; n < 3; n++)\n {\n if (bbox[i*3+n] < this->Bounds[n*2])\n {\n this->Bounds[n*2] = bbox[i*3+n];\n }\n if (bbox[i*3+n] > this->Bounds[n*2+1])\n {\n this->Bounds[n*2+1] = bbox[i*3+n];\n }\n }\n }\/\/for each point of box\n }\/\/if bounds\n }\/\/for each part\n }\/\/for each part\n\n if ( ! partVisible )\n {\n return NULL;\n }\n else\n {\n return this->Bounds;\n }\n}\n\nunsigned long int vtkPropAssembly::GetMTime()\n{\n unsigned long mTime=this->vtkProp::GetMTime();\n unsigned long time;\n vtkProp *part;\n\n for (this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )\n {\n time = part->GetMTime();\n mTime = ( time > mTime ? time : mTime );\n }\n\n return mTime;\n}\n\n\/\/ Shallow copy another vtkPropAssembly.\nvoid vtkPropAssembly::ShallowCopy(vtkProp *prop)\n{\n vtkPropAssembly *propAssembly = vtkPropAssembly::SafeDownCast(prop);\n if ( propAssembly != NULL )\n {\n this->Parts->RemoveAllItems();\n propAssembly->Parts->InitTraversal();\n for (int i=0; i<0; i++)\n {\n this->AddPart(propAssembly->Parts->GetNextProp());\n }\n }\n\n this->vtkProp::ShallowCopy(prop);\n}\n\nvoid vtkPropAssembly::InitPathTraversal()\n{\n this->UpdatePaths();\n this->Paths->InitTraversal();\n}\n\nvtkAssemblyPath *vtkPropAssembly::GetNextPath()\n{\n return this->Paths->GetNextItem();\n}\n\nint vtkPropAssembly::GetNumberOfPaths()\n{\n this->UpdatePaths();\n return this->Paths->GetNumberOfItems();\n}\n\n\n\/\/ Build the assembly paths if necessary.\nvoid vtkPropAssembly::UpdatePaths()\n{\n if ( this->GetMTime() > this->PathTime )\n {\n if ( this->Paths != NULL )\n {\n this->Paths->Delete();\n this->Paths = NULL;\n }\n\n \/\/ Create the list to hold all the paths\n this->Paths = vtkAssemblyPaths::New();\n vtkAssemblyPath *path = vtkAssemblyPath::New();\n\n \/\/add ourselves to the path to start things off\n path->AddNode(this,NULL);\n \n vtkProp *prop;\n \/\/ Add nodes as we proceed down the hierarchy\n for ( this->Parts->InitTraversal(); \n (prop = this->Parts->GetNextProp()); )\n {\n \/\/ add a matrix, if any\n path->AddNode(prop,prop->GetMatrix());\n\n \/\/ dive into the hierarchy\n prop->BuildPaths(this->Paths,path);\n \n \/\/ when returned, pop the last node off of the\n \/\/ current path\n path->DeleteLastNode();\n }\n \n path->Delete();\n this->PathTime.Modified();\n }\n}\n\nvoid vtkPropAssembly::BuildPaths(vtkAssemblyPaths *paths, \n vtkAssemblyPath *path)\n{\n vtkProp *prop;\n\n for ( this->Parts->InitTraversal(); \n (prop = this->Parts->GetNextProp()); )\n {\n path->AddNode(prop,NULL);\n\n \/\/ dive into the hierarchy\n prop->BuildPaths(paths,path);\n\n \/\/ when returned, pop the last node off of the\n \/\/ current path\n path->DeleteLastNode();\n }\n}\n\n\nvoid vtkPropAssembly::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkProp::PrintSelf(os,indent);\n\n os << indent << \"There are: \" << this->Parts->GetNumberOfItems()\n << \" parts in this assembly\\n\";\n}\n<commit_msg>ERR:Check for NULL and return as appropriate<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPropAssembly.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkPropAssembly.h\"\n#include \"vtkViewport.h\"\n#include \"vtkAssemblyNode.h\"\n#include \"vtkObjectFactory.h\"\n\n\/\/-----------------------------------------------------------------------------\nvtkPropAssembly* vtkPropAssembly::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkPropAssembly\");\n if(ret)\n {\n return (vtkPropAssembly*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkPropAssembly;\n}\n\n\/\/ Construct object with no children.\nvtkPropAssembly::vtkPropAssembly()\n{\n this->Parts = vtkPropCollection::New();\n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;\n}\n\nvtkPropAssembly::~vtkPropAssembly()\n{\n this->Parts->Delete();\n this->Parts = NULL;\n}\n\n\/\/ Add a part to the list of Parts.\nvoid vtkPropAssembly::AddPart(vtkProp *prop)\n{\n if ( ! this->Parts->IsItemPresent(prop) )\n {\n this->Parts->AddItem(prop);\n this->Modified();\n } \n}\n\n\/\/ Remove a part from the list of parts,\nvoid vtkPropAssembly::RemovePart(vtkProp *prop)\n{\n if ( this->Parts->IsItemPresent(prop) )\n {\n this->Parts->RemoveItem(prop);\n this->Modified();\n } \n}\n\n\/\/ Get the list of parts for this prop assembly.\nvtkPropCollection *vtkPropAssembly::GetParts() \n{\n return this->Parts;\n}\n\n\/\/ Render this assembly and all of its Parts. The rendering process is recursive.\nint vtkPropAssembly::RenderTranslucentGeometry(vtkViewport *ren)\n{\n vtkProp *prop;\n vtkAssemblyPath *path;\n float fraction;\n int renderedSomething=0;\n\n fraction = this->AllocatedRenderTime \/ \n (float)this->Parts->GetNumberOfItems();\n \n \/\/ render the Paths\n for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )\n {\n prop = path->GetLastNode()->GetProp();\n if ( prop->GetVisibility() )\n {\n prop->SetAllocatedRenderTime(fraction, ren);\n prop->PokeMatrix(path->GetLastNode()->GetMatrix());\n renderedSomething += prop->RenderTranslucentGeometry(ren);\n prop->PokeMatrix(NULL);\n }\n }\n\n return renderedSomething;\n}\n\n\/\/ Render this assembly and all its parts. The rendering process is recursive.\nint vtkPropAssembly::RenderOpaqueGeometry(vtkViewport *ren)\n{\n vtkProp *prop;\n vtkAssemblyPath *path;\n float fraction;\n int renderedSomething=0;\n\n \/\/ Make sure the paths are up-to-date\n this->UpdatePaths();\n\n fraction = this->AllocatedRenderTime \/ \n (float)this->Parts->GetNumberOfItems();\n \n \/\/ render the Paths\n for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )\n {\n prop = path->GetLastNode()->GetProp();\n if ( prop->GetVisibility() )\n {\n prop->SetAllocatedRenderTime(fraction, ren);\n prop->PokeMatrix(path->GetLastNode()->GetMatrix());\n renderedSomething += prop->RenderOpaqueGeometry(ren);\n prop->PokeMatrix(NULL);\n }\n }\n\n return renderedSomething;\n}\n\n\/\/ Render this assembly and all its parts. The rendering process is recursive.\nint vtkPropAssembly::RenderOverlay(vtkViewport *ren)\n{\n vtkProp *prop;\n vtkAssemblyPath *path;\n float fraction;\n int renderedSomething=0;\n\n \/\/ Make sure the paths are up-to-date\n this->UpdatePaths();\n\n fraction = this->AllocatedRenderTime \/ \n (float)this->Parts->GetNumberOfItems();\n \n for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )\n {\n prop = path->GetLastNode()->GetProp();\n if ( prop->GetVisibility() )\n {\n prop->SetAllocatedRenderTime(fraction, ren);\n prop->PokeMatrix(path->GetLastNode()->GetMatrix());\n renderedSomething += prop->RenderOverlay(ren);\n prop->PokeMatrix(NULL);\n }\n }\n\n return renderedSomething;\n}\n\n\nvoid vtkPropAssembly::ReleaseGraphicsResources(vtkWindow *renWin)\n{\n vtkProp *part;\n\n vtkProp::ReleaseGraphicsResources(renWin);\n\n \/\/ broadcast the message down the Parts\n for ( this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )\n {\n part->ReleaseGraphicsResources(renWin);\n }\n}\n\n\/\/ Get the bounds for the assembly as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).\nfloat *vtkPropAssembly::GetBounds()\n{\n vtkProp *part;\n int i, n;\n float *bounds, bbox[24];\n int partVisible=0;\n\n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;\n \n for ( this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )\n {\n if ( part->GetVisibility() )\n {\n bounds = part->GetBounds();\n\n if ( bounds != NULL )\n {\n \/\/ For the purposes of GetBounds, an object is visisble only if\n \/\/ its visibility is on and it has visible parts.\n partVisible = 1;\n\n \/\/ fill out vertices of a bounding box\n bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5];\n bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5];\n bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5];\n bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5];\n bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4];\n bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4];\n bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4];\n bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4];\n\n for (i = 0; i < 8; i++)\n {\n for (n = 0; n < 3; n++)\n {\n if (bbox[i*3+n] < this->Bounds[n*2])\n {\n this->Bounds[n*2] = bbox[i*3+n];\n }\n if (bbox[i*3+n] > this->Bounds[n*2+1])\n {\n this->Bounds[n*2+1] = bbox[i*3+n];\n }\n }\n }\/\/for each point of box\n }\/\/if bounds\n }\/\/for each part\n }\/\/for each part\n\n if ( ! partVisible )\n {\n return NULL;\n }\n else\n {\n return this->Bounds;\n }\n}\n\nunsigned long int vtkPropAssembly::GetMTime()\n{\n unsigned long mTime=this->vtkProp::GetMTime();\n unsigned long time;\n vtkProp *part;\n\n for (this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )\n {\n time = part->GetMTime();\n mTime = ( time > mTime ? time : mTime );\n }\n\n return mTime;\n}\n\n\/\/ Shallow copy another vtkPropAssembly.\nvoid vtkPropAssembly::ShallowCopy(vtkProp *prop)\n{\n vtkPropAssembly *propAssembly = vtkPropAssembly::SafeDownCast(prop);\n if ( propAssembly != NULL )\n {\n this->Parts->RemoveAllItems();\n propAssembly->Parts->InitTraversal();\n for (int i=0; i<0; i++)\n {\n this->AddPart(propAssembly->Parts->GetNextProp());\n }\n }\n\n this->vtkProp::ShallowCopy(prop);\n}\n\nvoid vtkPropAssembly::InitPathTraversal()\n{\n this->UpdatePaths();\n this->Paths->InitTraversal();\n}\n\nvtkAssemblyPath *vtkPropAssembly::GetNextPath()\n{\n if ( this->Paths )\n {\n return this->Paths->GetNextItem();\n }\n return NULL;\n}\n\nint vtkPropAssembly::GetNumberOfPaths()\n{\n this->UpdatePaths();\n return this->Paths->GetNumberOfItems();\n}\n\n\n\/\/ Build the assembly paths if necessary.\nvoid vtkPropAssembly::UpdatePaths()\n{\n if ( this->GetMTime() > this->PathTime )\n {\n if ( this->Paths != NULL )\n {\n this->Paths->Delete();\n this->Paths = NULL;\n }\n\n \/\/ Create the list to hold all the paths\n this->Paths = vtkAssemblyPaths::New();\n vtkAssemblyPath *path = vtkAssemblyPath::New();\n\n \/\/add ourselves to the path to start things off\n path->AddNode(this,NULL);\n \n vtkProp *prop;\n \/\/ Add nodes as we proceed down the hierarchy\n for ( this->Parts->InitTraversal(); \n (prop = this->Parts->GetNextProp()); )\n {\n \/\/ add a matrix, if any\n path->AddNode(prop,prop->GetMatrix());\n\n \/\/ dive into the hierarchy\n prop->BuildPaths(this->Paths,path);\n \n \/\/ when returned, pop the last node off of the\n \/\/ current path\n path->DeleteLastNode();\n }\n \n path->Delete();\n this->PathTime.Modified();\n }\n}\n\nvoid vtkPropAssembly::BuildPaths(vtkAssemblyPaths *paths, \n vtkAssemblyPath *path)\n{\n vtkProp *prop;\n\n for ( this->Parts->InitTraversal(); \n (prop = this->Parts->GetNextProp()); )\n {\n path->AddNode(prop,NULL);\n\n \/\/ dive into the hierarchy\n prop->BuildPaths(paths,path);\n\n \/\/ when returned, pop the last node off of the\n \/\/ current path\n path->DeleteLastNode();\n }\n}\n\n\nvoid vtkPropAssembly::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkProp::PrintSelf(os,indent);\n\n os << indent << \"There are: \" << this->Parts->GetNumberOfItems()\n << \" parts in this assembly\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\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#ifndef HTTP_MIME_TYPES_HPP\n#define HTTP_MIME_TYPES_HPP\n\n#include <string>\n#include <unordered_map>\n\nnamespace http {\n\/\/------------------------------------------------\nusing Extension = std::string;\nusing Mime_Type = std::string;\nusing Mime_Type_Table = std::unordered_map<Extension, Mime_Type>;\n\/\/------------------------------------------------\nconst Mime_Type_Table mime_types {\n \/\/< Text mimes\n {\"html\", \"text\/html\"},\n {\"htm\" , \"text\/html\"},\n {\"js\" , \"text\/javascript\"},\n {\"txt\" , \"text\/plain\"},\n {\"css\" , \"text\/css\"},\n {\"xml\" , \"text\/xml\"},\n\n \/\/< Image mimes\n {\"bmp\" , \"image\/bmp\"},\n {\"gif\" , \"image\/gif\"},\n {\"png\" , \"image\/png\"},\n {\"jpg\" , \"image\/jpeg\"},\n {\"jpeg\", \"image\/jpeg\"},\n {\"ico\" , \"image\/x-icon\"},\n {\"svg\" , \"image\/svg+xml\"},\n\n \/\/< Audio mimes\n {\"mid\" , \"audio\/midi\"},\n {\"midi\", \"audio\/midi\"},\n {\"kar\" , \"audio\/midi\"},\n {\"mp3\" , \"audio\/mpeg\"},\n {\"ogg\" , \"audio\/ogg\"},\n {\"m4a\" , \"audio\/x-m4a\"},\n {\"ra\" , \"audio\/x-realaudio\"},\n\n \/\/< Video mimes\n {\"3gp\" , \"video\/3gpp\"},\n {\"3gpp\", \"video\/3gpp\"},\n {\"ts\" , \"video\/mp2t\"},\n {\"mp4\" , \"video\/mp4\"},\n {\"mpg\" , \"video\/mpeg\"},\n {\"mpeg\", \"video\/mpeg\"},\n {\"mov\" , \"video\/quicktime\"},\n {\"webm\", \"video\/webm\"},\n {\"flv\" , \"video\/x-flv\"},\n {\"m4v\" , \"video\/x-m4v\"},\n {\"mng\" , \"video\/x-mng\"},\n {\"asf\" , \"video\/x-ms-asf\"},\n {\"asx\" , \"video\/x-ms-asf\"},\n {\"wmv\" , \"video\/x-ms-wmv\"},\n {\"avi\" , \"video\/x-msvideo\"},\n\n \/\/< Application mimes\n {\"zip\" , \"application\/zip\"},\n {\"7z\" , \"application\/x-7z-compressed\"},\n {\"jar\" , \"application\/java-archive\"},\n {\"war\" , \"application\/java-archive\"},\n {\"ear\" , \"application\/java-archive\"},\n {\"json\" , \"application\/json\"},\n {\"pdf\" , \"application\/pdf\"},\n {\"xhtml\", \"application\/xhtml+xml\"},\n {\"xspf\" , \"application\/xspf+xml\"},\n {\"der\" , \"application\/x-x509-ca-cert\"},\n {\"pem\" , \"application\/x-x509-ca-cert\"},\n {\"crt\" , \"application\/x-x509-ca-cert\"},\n {\"bin\" , \"application\/octet-stream\"},\n {\"exe\" , \"application\/octet-stream\"},\n {\"dll\" , \"application\/octet-stream\"},\n {\"deb\" , \"application\/octet-stream\"},\n {\"dmg\" , \"application\/octet-stream\"},\n {\"iso\" , \"application\/octet-stream\"},\n {\"img\" , \"application\/octet-stream\"},\n {\"msi\" , \"application\/octet-stream\"},\n {\"msp\" , \"application\/octet-stream\"},\n {\"msm\" , \"application\/octet-stream\"}\n}; \/\/< mime_types\n\ninline const Mime_Type& extension_to_type(const Extension& extension) noexcept {\n auto iter = mime_types.find(extension);\n \/\/------------------------------------------------\n return (iter not_eq mime_types.end())\n ? iter->second\n : const_cast<Mime_Type_Table&>(mime_types)[\"txt\"];\n}\n\n} \/\/< namespace http\n\n#endif \/\/< HTTP_MIME_TYPES_HPP\n<commit_msg>mime_types.hpp: Changed default mime type from txt to bin<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\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#ifndef HTTP_MIME_TYPES_HPP\n#define HTTP_MIME_TYPES_HPP\n\n#include <string>\n#include <unordered_map>\n\nnamespace http {\n\/\/------------------------------------------------\nusing Extension = std::string;\nusing Mime_type = std::string;\nusing Mime_type_table = std::unordered_map<Extension, Mime_type>;\n\/\/------------------------------------------------\nconst Mime_type_table mime_types {\n \/\/< Text mimes\n {\"html\", \"text\/html\"},\n {\"htm\" , \"text\/html\"},\n {\"js\" , \"text\/javascript\"},\n {\"txt\" , \"text\/plain\"},\n {\"css\" , \"text\/css\"},\n {\"xml\" , \"text\/xml\"},\n\n \/\/< Image mimes\n {\"bmp\" , \"image\/bmp\"},\n {\"gif\" , \"image\/gif\"},\n {\"png\" , \"image\/png\"},\n {\"jpg\" , \"image\/jpeg\"},\n {\"jpeg\", \"image\/jpeg\"},\n {\"ico\" , \"image\/x-icon\"},\n {\"svg\" , \"image\/svg+xml\"},\n\n \/\/< Audio mimes\n {\"mid\" , \"audio\/midi\"},\n {\"midi\", \"audio\/midi\"},\n {\"kar\" , \"audio\/midi\"},\n {\"mp3\" , \"audio\/mpeg\"},\n {\"ogg\" , \"audio\/ogg\"},\n {\"m4a\" , \"audio\/x-m4a\"},\n {\"ra\" , \"audio\/x-realaudio\"},\n\n \/\/< Video mimes\n {\"3gp\" , \"video\/3gpp\"},\n {\"3gpp\", \"video\/3gpp\"},\n {\"ts\" , \"video\/mp2t\"},\n {\"mp4\" , \"video\/mp4\"},\n {\"mpg\" , \"video\/mpeg\"},\n {\"mpeg\", \"video\/mpeg\"},\n {\"mov\" , \"video\/quicktime\"},\n {\"webm\", \"video\/webm\"},\n {\"flv\" , \"video\/x-flv\"},\n {\"m4v\" , \"video\/x-m4v\"},\n {\"mng\" , \"video\/x-mng\"},\n {\"asf\" , \"video\/x-ms-asf\"},\n {\"asx\" , \"video\/x-ms-asf\"},\n {\"wmv\" , \"video\/x-ms-wmv\"},\n {\"avi\" , \"video\/x-msvideo\"},\n\n \/\/< Application mimes\n {\"zip\" , \"application\/zip\"},\n {\"7z\" , \"application\/x-7z-compressed\"},\n {\"jar\" , \"application\/java-archive\"},\n {\"war\" , \"application\/java-archive\"},\n {\"ear\" , \"application\/java-archive\"},\n {\"json\" , \"application\/json\"},\n {\"pdf\" , \"application\/pdf\"},\n {\"xhtml\", \"application\/xhtml+xml\"},\n {\"xspf\" , \"application\/xspf+xml\"},\n {\"der\" , \"application\/x-x509-ca-cert\"},\n {\"pem\" , \"application\/x-x509-ca-cert\"},\n {\"crt\" , \"application\/x-x509-ca-cert\"},\n {\"bin\" , \"application\/octet-stream\"},\n {\"exe\" , \"application\/octet-stream\"},\n {\"dll\" , \"application\/octet-stream\"},\n {\"deb\" , \"application\/octet-stream\"},\n {\"dmg\" , \"application\/octet-stream\"},\n {\"iso\" , \"application\/octet-stream\"},\n {\"img\" , \"application\/octet-stream\"},\n {\"msi\" , \"application\/octet-stream\"},\n {\"msp\" , \"application\/octet-stream\"},\n {\"msm\" , \"application\/octet-stream\"}\n}; \/\/< mime_types\n\ninline const Mime_type& extension_to_type(const Extension& extension) noexcept {\n auto it = mime_types.find(extension);\n \/\/------------------------------------------------\n return (it not_eq mime_types.end())\n ? it->second\n : const_cast<Mime_type_table&>(mime_types)[\"bin\"];\n}\n\n} \/\/< namespace http\n\n#endif \/\/< HTTP_MIME_TYPES_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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\n#include <string>\n\n#include \"Document.h\"\n#include \"DOMWindow.h\"\n#include \"Frame.h\"\n#include \"InspectorController.h\"\n#include \"Node.h\"\n#include \"Page.h\"\n#include \"PlatformString.h\"\n#include \"SecurityOrigin.h\"\n#include \"V8Binding.h\"\n#include \"V8CustomBinding.h\"\n#include \"V8Proxy.h\"\n#include \"V8Utilities.h\"\n#include <wtf\/OwnPtr.h>\n#include <wtf\/Vector.h>\n#undef LOG\n\n#include \"base\/string_util.h\"\n#include \"base\/values.h\"\n#include \"webkit\/api\/public\/WebScriptSource.h\"\n#include \"webkit\/glue\/devtools\/bound_object.h\"\n#include \"webkit\/glue\/devtools\/debugger_agent.h\"\n#include \"webkit\/glue\/devtools\/devtools_rpc_js.h\"\n#include \"webkit\/glue\/devtools\/dom_agent.h\"\n#include \"webkit\/glue\/devtools\/tools_agent.h\"\n#include \"webkit\/glue\/glue_util.h\"\n#include \"webkit\/glue\/webdevtoolsclient_delegate.h\"\n#include \"webkit\/glue\/webdevtoolsclient_impl.h\"\n#include \"webkit\/glue\/webframe.h\"\n#include \"webkit\/glue\/webview_impl.h\"\n\nusing namespace WebCore;\nusing WebKit::WebScriptSource;\nusing WebKit::WebString;\n\nDEFINE_RPC_JS_BOUND_OBJ(DebuggerAgent, DEBUGGER_AGENT_STRUCT,\n DebuggerAgentDelegate, DEBUGGER_AGENT_DELEGATE_STRUCT)\nDEFINE_RPC_JS_BOUND_OBJ(DomAgent, DOM_AGENT_STRUCT,\n DomAgentDelegate, DOM_AGENT_DELEGATE_STRUCT)\nDEFINE_RPC_JS_BOUND_OBJ(ToolsAgent, TOOLS_AGENT_STRUCT,\n ToolsAgentDelegate, TOOLS_AGENT_DELEGATE_STRUCT)\n\nclass ToolsAgentNativeDelegateImpl : public ToolsAgentNativeDelegate {\n public:\n struct ResourceContentRequestData {\n String mime_type;\n RefPtr<Node> frame;\n };\n\n ToolsAgentNativeDelegateImpl(WebFrameImpl* frame) : frame_(frame) {}\n virtual ~ToolsAgentNativeDelegateImpl() {}\n\n \/\/ ToolsAgentNativeDelegate implementation.\n virtual void DidGetResourceContent(int request_id, const String& content) {\n if (!resource_content_requests_.contains(request_id)) {\n NOTREACHED();\n return;\n }\n ResourceContentRequestData request =\n resource_content_requests_.take(request_id);\n\n InspectorController* ic = frame_->frame()->page()->inspectorController();\n if (request.frame && request.frame->attached()) {\n ic->addSourceToFrame(request.mime_type, content, request.frame.get());\n }\n }\n\n bool WaitingForResponse(int resource_id, Node* frame) {\n if (resource_content_requests_.contains(resource_id)) {\n DCHECK(resource_content_requests_.get(resource_id).frame.get() == frame)\n << \"Only one frame is expected to display given resource\";\n return true;\n }\n return false;\n }\n\n void RequestSent(int resource_id, String mime_type, Node* frame) {\n ResourceContentRequestData data;\n data.mime_type = mime_type;\n data.frame = frame;\n DCHECK(!resource_content_requests_.contains(resource_id));\n resource_content_requests_.set(resource_id, data);\n }\n\n private:\n WebFrameImpl* frame_;\n HashMap<int, ResourceContentRequestData> resource_content_requests_;\n DISALLOW_COPY_AND_ASSIGN(ToolsAgentNativeDelegateImpl);\n};\n\nnamespace {\n\nclass RemoteDebuggerCommandExecutor : public CppBoundClass {\n public:\n RemoteDebuggerCommandExecutor(\n WebDevToolsClientDelegate* delegate,\n WebFrame* frame,\n const std::wstring& classname)\n : delegate_(delegate) {\n BindToJavascript(frame, classname);\n BindMethod(\"DebuggerCommand\",\n &RemoteDebuggerCommandExecutor::DebuggerCommand);\n }\n virtual ~RemoteDebuggerCommandExecutor() {}\n\n \/\/ The DebuggerCommand() function provided to Javascript.\n void DebuggerCommand(const CppArgumentList& args, CppVariant* result) {\n std::string command = args[0].ToString();\n result->SetNull();\n delegate_->SendDebuggerCommandToAgent(command);\n }\n\n private:\n WebDevToolsClientDelegate* delegate_;\n DISALLOW_COPY_AND_ASSIGN(RemoteDebuggerCommandExecutor);\n};\n\n} \/\/ namespace\n\n\/\/ static\nWebDevToolsClient* WebDevToolsClient::Create(\n WebView* view,\n WebDevToolsClientDelegate* delegate) {\n return new WebDevToolsClientImpl(static_cast<WebViewImpl*>(view), delegate);\n}\n\nWebDevToolsClientImpl::WebDevToolsClientImpl(\n WebViewImpl* web_view_impl,\n WebDevToolsClientDelegate* delegate)\n : web_view_impl_(web_view_impl),\n delegate_(delegate),\n loaded_(false) {\n WebFrameImpl* frame = web_view_impl_->main_frame();\n\n \/\/ Debugger commands should be sent using special method.\n debugger_command_executor_obj_.set(new RemoteDebuggerCommandExecutor(\n delegate, frame, L\"RemoteDebuggerCommandExecutor\"));\n debugger_agent_obj_.set(new JsDebuggerAgentBoundObj(\n this, frame, L\"RemoteDebuggerAgent\"));\n dom_agent_obj_.set(new JsDomAgentBoundObj(this, frame, L\"RemoteDomAgent\"));\n tools_agent_obj_.set(\n new JsToolsAgentBoundObj(this, frame, L\"RemoteToolsAgent\"));\n\n v8::HandleScope scope;\n v8::Handle<v8::Context> frame_context = V8Proxy::context(frame->frame());\n dev_tools_host_.set(new BoundObject(frame_context, this, \"DevToolsHost\"));\n dev_tools_host_->AddProtoFunction(\n \"reset\",\n WebDevToolsClientImpl::JsReset);\n dev_tools_host_->AddProtoFunction(\n \"addSourceToFrame\",\n WebDevToolsClientImpl::JsAddSourceToFrame);\n dev_tools_host_->AddProtoFunction(\n \"addResourceSourceToFrame\",\n WebDevToolsClientImpl::JsAddResourceSourceToFrame);\n dev_tools_host_->AddProtoFunction(\n \"loaded\",\n WebDevToolsClientImpl::JsLoaded);\n dev_tools_host_->AddProtoFunction(\n \"search\",\n WebCore::V8Custom::v8InspectorControllerSearchCallback);\n dev_tools_host_->AddProtoFunction(\n \"getPlatform\",\n WebDevToolsClientImpl::JsGetPlatform);\n dev_tools_host_->AddProtoFunction(\n \"activateWindow\",\n WebDevToolsClientImpl::JsActivateWindow);\n dev_tools_host_->AddProtoFunction(\n \"closeWindow\",\n WebDevToolsClientImpl::JsCloseWindow);\n dev_tools_host_->AddProtoFunction(\n \"dockWindow\",\n WebDevToolsClientImpl::JsDockWindow);\n dev_tools_host_->AddProtoFunction(\n \"undockWindow\",\n WebDevToolsClientImpl::JsUndockWindow);\n dev_tools_host_->AddProtoFunction(\n \"toggleInspectElementMode\",\n WebDevToolsClientImpl::JsToggleInspectElementMode);\n dev_tools_host_->Build();\n}\n\nWebDevToolsClientImpl::~WebDevToolsClientImpl() {\n}\n\nvoid WebDevToolsClientImpl::DispatchMessageFromAgent(\n const std::string& class_name,\n const std::string& method_name,\n const std::string& raw_msg) {\n if (ToolsAgentNativeDelegateDispatch::Dispatch(\n tools_agent_native_delegate_impl_.get(),\n class_name,\n method_name,\n raw_msg)) {\n return;\n }\n\n std::string expr = StringPrintf(\n \"devtools.dispatch('%s','%s',%s)\",\n class_name.c_str(),\n method_name.c_str(),\n raw_msg.c_str());\n if (!loaded_) {\n pending_incoming_messages_.append(expr);\n return;\n }\n ExecuteScript(expr);\n}\n\nvoid WebDevToolsClientImpl::AddResourceSourceToFrame(int resource_id,\n String mime_type,\n Node* frame) {\n if (tools_agent_native_delegate_impl_->WaitingForResponse(resource_id,\n frame)) {\n return;\n }\n tools_agent_obj_->GetResourceContent(resource_id, resource_id);\n tools_agent_native_delegate_impl_->RequestSent(resource_id, mime_type, frame);\n}\n\nvoid WebDevToolsClientImpl::ExecuteScript(const std::string& expr) {\n web_view_impl_->GetMainFrame()->ExecuteScript(\n WebScriptSource(WebString::fromUTF8(expr)));\n}\n\n\nvoid WebDevToolsClientImpl::SendRpcMessage(const std::string& class_name,\n const std::string& method_name,\n const std::string& raw_msg) {\n delegate_->SendMessageToAgent(class_name, method_name, raw_msg);\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsReset(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n WebFrameImpl* frame = client->web_view_impl_->main_frame();\n client->tools_agent_native_delegate_impl_.set(\n new ToolsAgentNativeDelegateImpl(frame));\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsAddSourceToFrame(\n const v8::Arguments& args) {\n if (args.Length() < 2) {\n return v8::Undefined();\n }\n\n v8::TryCatch exception_catcher;\n\n String mime_type = WebCore::toWebCoreStringWithNullCheck(args[0]);\n if (mime_type.isEmpty() || exception_catcher.HasCaught()) {\n return v8::Undefined();\n }\n String source_string = WebCore::toWebCoreStringWithNullCheck(args[1]);\n if (source_string.isEmpty() || exception_catcher.HasCaught()) {\n return v8::Undefined();\n }\n Node* node = V8DOMWrapper::convertDOMWrapperToNode<Node>(args[2]);\n if (!node || !node->attached()) {\n return v8::Undefined();\n }\n\n Page* page = V8Proxy::retrieveFrameForEnteredContext()->page();\n InspectorController* inspectorController = page->inspectorController();\n return WebCore::v8Boolean(inspectorController->\n addSourceToFrame(mime_type, source_string, node));\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsAddResourceSourceToFrame(\n const v8::Arguments& args) {\n int resource_id = static_cast<int>(args[0]->NumberValue());\n String mime_type = WebCore::toWebCoreStringWithNullCheck(args[1]);\n if (mime_type.isEmpty()) {\n return v8::Undefined();\n }\n Node* node = V8DOMWrapper::convertDOMWrapperToNode<Node>(args[2]);\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->AddResourceSourceToFrame(resource_id, mime_type, node);\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsLoaded(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->loaded_ = true;\n\n \/\/ Grant the devtools page the ability to have source view iframes.\n Page* page = V8Proxy::retrieveFrameForEnteredContext()->page();\n SecurityOrigin* origin = page->mainFrame()->domWindow()->securityOrigin();\n origin->grantUniversalAccess();\n\n for (Vector<std::string>::iterator it =\n client->pending_incoming_messages_.begin();\n it != client->pending_incoming_messages_.end();\n ++it) {\n client->ExecuteScript(*it);\n }\n client->pending_incoming_messages_.clear();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsGetPlatform(\n const v8::Arguments& args) {\n#if defined OS_MACOSX\n return v8String(\"mac-leopard\");\n#elif defined OS_LINUX\n return v8String(\"linux\");\n#else\n return v8String(\"windows\");\n#endif\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsActivateWindow(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->delegate_->ActivateWindow();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsCloseWindow(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->delegate_->CloseWindow();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsDockWindow(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->delegate_->DockWindow();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsUndockWindow(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->delegate_->UndockWindow();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsToggleInspectElementMode(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n int enabled = static_cast<int>(args[0]->BooleanValue());\n client->delegate_->ToggleInspectElementMode(enabled);\n return v8::Undefined();\n}\n<commit_msg>Land Anton's change to cast from v8::Value to v8::Object before converting a wrapper to a native Node pointer in devtools.<commit_after>\/\/ 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\n#include <string>\n\n#include \"Document.h\"\n#include \"DOMWindow.h\"\n#include \"Frame.h\"\n#include \"InspectorController.h\"\n#include \"Node.h\"\n#include \"Page.h\"\n#include \"PlatformString.h\"\n#include \"SecurityOrigin.h\"\n#include \"V8Binding.h\"\n#include \"V8CustomBinding.h\"\n#include \"V8Proxy.h\"\n#include \"V8Utilities.h\"\n#include <wtf\/OwnPtr.h>\n#include <wtf\/Vector.h>\n#undef LOG\n\n#include \"base\/string_util.h\"\n#include \"base\/values.h\"\n#include \"webkit\/api\/public\/WebScriptSource.h\"\n#include \"webkit\/glue\/devtools\/bound_object.h\"\n#include \"webkit\/glue\/devtools\/debugger_agent.h\"\n#include \"webkit\/glue\/devtools\/devtools_rpc_js.h\"\n#include \"webkit\/glue\/devtools\/dom_agent.h\"\n#include \"webkit\/glue\/devtools\/tools_agent.h\"\n#include \"webkit\/glue\/glue_util.h\"\n#include \"webkit\/glue\/webdevtoolsclient_delegate.h\"\n#include \"webkit\/glue\/webdevtoolsclient_impl.h\"\n#include \"webkit\/glue\/webframe.h\"\n#include \"webkit\/glue\/webview_impl.h\"\n\nusing namespace WebCore;\nusing WebKit::WebScriptSource;\nusing WebKit::WebString;\n\nDEFINE_RPC_JS_BOUND_OBJ(DebuggerAgent, DEBUGGER_AGENT_STRUCT,\n DebuggerAgentDelegate, DEBUGGER_AGENT_DELEGATE_STRUCT)\nDEFINE_RPC_JS_BOUND_OBJ(DomAgent, DOM_AGENT_STRUCT,\n DomAgentDelegate, DOM_AGENT_DELEGATE_STRUCT)\nDEFINE_RPC_JS_BOUND_OBJ(ToolsAgent, TOOLS_AGENT_STRUCT,\n ToolsAgentDelegate, TOOLS_AGENT_DELEGATE_STRUCT)\n\nclass ToolsAgentNativeDelegateImpl : public ToolsAgentNativeDelegate {\n public:\n struct ResourceContentRequestData {\n String mime_type;\n RefPtr<Node> frame;\n };\n\n ToolsAgentNativeDelegateImpl(WebFrameImpl* frame) : frame_(frame) {}\n virtual ~ToolsAgentNativeDelegateImpl() {}\n\n \/\/ ToolsAgentNativeDelegate implementation.\n virtual void DidGetResourceContent(int request_id, const String& content) {\n if (!resource_content_requests_.contains(request_id)) {\n NOTREACHED();\n return;\n }\n ResourceContentRequestData request =\n resource_content_requests_.take(request_id);\n\n InspectorController* ic = frame_->frame()->page()->inspectorController();\n if (request.frame && request.frame->attached()) {\n ic->addSourceToFrame(request.mime_type, content, request.frame.get());\n }\n }\n\n bool WaitingForResponse(int resource_id, Node* frame) {\n if (resource_content_requests_.contains(resource_id)) {\n DCHECK(resource_content_requests_.get(resource_id).frame.get() == frame)\n << \"Only one frame is expected to display given resource\";\n return true;\n }\n return false;\n }\n\n void RequestSent(int resource_id, String mime_type, Node* frame) {\n ResourceContentRequestData data;\n data.mime_type = mime_type;\n data.frame = frame;\n DCHECK(!resource_content_requests_.contains(resource_id));\n resource_content_requests_.set(resource_id, data);\n }\n\n private:\n WebFrameImpl* frame_;\n HashMap<int, ResourceContentRequestData> resource_content_requests_;\n DISALLOW_COPY_AND_ASSIGN(ToolsAgentNativeDelegateImpl);\n};\n\nnamespace {\n\nclass RemoteDebuggerCommandExecutor : public CppBoundClass {\n public:\n RemoteDebuggerCommandExecutor(\n WebDevToolsClientDelegate* delegate,\n WebFrame* frame,\n const std::wstring& classname)\n : delegate_(delegate) {\n BindToJavascript(frame, classname);\n BindMethod(\"DebuggerCommand\",\n &RemoteDebuggerCommandExecutor::DebuggerCommand);\n }\n virtual ~RemoteDebuggerCommandExecutor() {}\n\n \/\/ The DebuggerCommand() function provided to Javascript.\n void DebuggerCommand(const CppArgumentList& args, CppVariant* result) {\n std::string command = args[0].ToString();\n result->SetNull();\n delegate_->SendDebuggerCommandToAgent(command);\n }\n\n private:\n WebDevToolsClientDelegate* delegate_;\n DISALLOW_COPY_AND_ASSIGN(RemoteDebuggerCommandExecutor);\n};\n\n} \/\/ namespace\n\n\/\/ static\nWebDevToolsClient* WebDevToolsClient::Create(\n WebView* view,\n WebDevToolsClientDelegate* delegate) {\n return new WebDevToolsClientImpl(static_cast<WebViewImpl*>(view), delegate);\n}\n\nWebDevToolsClientImpl::WebDevToolsClientImpl(\n WebViewImpl* web_view_impl,\n WebDevToolsClientDelegate* delegate)\n : web_view_impl_(web_view_impl),\n delegate_(delegate),\n loaded_(false) {\n WebFrameImpl* frame = web_view_impl_->main_frame();\n\n \/\/ Debugger commands should be sent using special method.\n debugger_command_executor_obj_.set(new RemoteDebuggerCommandExecutor(\n delegate, frame, L\"RemoteDebuggerCommandExecutor\"));\n debugger_agent_obj_.set(new JsDebuggerAgentBoundObj(\n this, frame, L\"RemoteDebuggerAgent\"));\n dom_agent_obj_.set(new JsDomAgentBoundObj(this, frame, L\"RemoteDomAgent\"));\n tools_agent_obj_.set(\n new JsToolsAgentBoundObj(this, frame, L\"RemoteToolsAgent\"));\n\n v8::HandleScope scope;\n v8::Handle<v8::Context> frame_context = V8Proxy::context(frame->frame());\n dev_tools_host_.set(new BoundObject(frame_context, this, \"DevToolsHost\"));\n dev_tools_host_->AddProtoFunction(\n \"reset\",\n WebDevToolsClientImpl::JsReset);\n dev_tools_host_->AddProtoFunction(\n \"addSourceToFrame\",\n WebDevToolsClientImpl::JsAddSourceToFrame);\n dev_tools_host_->AddProtoFunction(\n \"addResourceSourceToFrame\",\n WebDevToolsClientImpl::JsAddResourceSourceToFrame);\n dev_tools_host_->AddProtoFunction(\n \"loaded\",\n WebDevToolsClientImpl::JsLoaded);\n dev_tools_host_->AddProtoFunction(\n \"search\",\n WebCore::V8Custom::v8InspectorControllerSearchCallback);\n dev_tools_host_->AddProtoFunction(\n \"getPlatform\",\n WebDevToolsClientImpl::JsGetPlatform);\n dev_tools_host_->AddProtoFunction(\n \"activateWindow\",\n WebDevToolsClientImpl::JsActivateWindow);\n dev_tools_host_->AddProtoFunction(\n \"closeWindow\",\n WebDevToolsClientImpl::JsCloseWindow);\n dev_tools_host_->AddProtoFunction(\n \"dockWindow\",\n WebDevToolsClientImpl::JsDockWindow);\n dev_tools_host_->AddProtoFunction(\n \"undockWindow\",\n WebDevToolsClientImpl::JsUndockWindow);\n dev_tools_host_->AddProtoFunction(\n \"toggleInspectElementMode\",\n WebDevToolsClientImpl::JsToggleInspectElementMode);\n dev_tools_host_->Build();\n}\n\nWebDevToolsClientImpl::~WebDevToolsClientImpl() {\n}\n\nvoid WebDevToolsClientImpl::DispatchMessageFromAgent(\n const std::string& class_name,\n const std::string& method_name,\n const std::string& raw_msg) {\n if (ToolsAgentNativeDelegateDispatch::Dispatch(\n tools_agent_native_delegate_impl_.get(),\n class_name,\n method_name,\n raw_msg)) {\n return;\n }\n\n std::string expr = StringPrintf(\n \"devtools.dispatch('%s','%s',%s)\",\n class_name.c_str(),\n method_name.c_str(),\n raw_msg.c_str());\n if (!loaded_) {\n pending_incoming_messages_.append(expr);\n return;\n }\n ExecuteScript(expr);\n}\n\nvoid WebDevToolsClientImpl::AddResourceSourceToFrame(int resource_id,\n String mime_type,\n Node* frame) {\n if (tools_agent_native_delegate_impl_->WaitingForResponse(resource_id,\n frame)) {\n return;\n }\n tools_agent_obj_->GetResourceContent(resource_id, resource_id);\n tools_agent_native_delegate_impl_->RequestSent(resource_id, mime_type, frame);\n}\n\nvoid WebDevToolsClientImpl::ExecuteScript(const std::string& expr) {\n web_view_impl_->GetMainFrame()->ExecuteScript(\n WebScriptSource(WebString::fromUTF8(expr)));\n}\n\n\nvoid WebDevToolsClientImpl::SendRpcMessage(const std::string& class_name,\n const std::string& method_name,\n const std::string& raw_msg) {\n delegate_->SendMessageToAgent(class_name, method_name, raw_msg);\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsReset(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n WebFrameImpl* frame = client->web_view_impl_->main_frame();\n client->tools_agent_native_delegate_impl_.set(\n new ToolsAgentNativeDelegateImpl(frame));\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsAddSourceToFrame(\n const v8::Arguments& args) {\n if (args.Length() < 2) {\n return v8::Undefined();\n }\n\n v8::TryCatch exception_catcher;\n\n String mime_type = WebCore::toWebCoreStringWithNullCheck(args[0]);\n if (mime_type.isEmpty() || exception_catcher.HasCaught()) {\n return v8::Undefined();\n }\n String source_string = WebCore::toWebCoreStringWithNullCheck(args[1]);\n if (source_string.isEmpty() || exception_catcher.HasCaught()) {\n return v8::Undefined();\n }\n v8::Handle<v8::Object> wrapper = v8::Handle<v8::Object>::Cast(args[2]);\n Node* node = V8DOMWrapper::convertDOMWrapperToNode<Node>(wrapper);\n if (!node || !node->attached()) {\n return v8::Undefined();\n }\n\n Page* page = V8Proxy::retrieveFrameForEnteredContext()->page();\n InspectorController* inspectorController = page->inspectorController();\n return WebCore::v8Boolean(inspectorController->\n addSourceToFrame(mime_type, source_string, node));\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsAddResourceSourceToFrame(\n const v8::Arguments& args) {\n int resource_id = static_cast<int>(args[0]->NumberValue());\n String mime_type = WebCore::toWebCoreStringWithNullCheck(args[1]);\n if (mime_type.isEmpty()) {\n return v8::Undefined();\n }\n v8::Handle<v8::Object> wrapper = v8::Handle<v8::Object>::Cast(args[2]);\n Node* node = V8DOMWrapper::convertDOMWrapperToNode<Node>(wrapper);\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->AddResourceSourceToFrame(resource_id, mime_type, node);\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsLoaded(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->loaded_ = true;\n\n \/\/ Grant the devtools page the ability to have source view iframes.\n Page* page = V8Proxy::retrieveFrameForEnteredContext()->page();\n SecurityOrigin* origin = page->mainFrame()->domWindow()->securityOrigin();\n origin->grantUniversalAccess();\n\n for (Vector<std::string>::iterator it =\n client->pending_incoming_messages_.begin();\n it != client->pending_incoming_messages_.end();\n ++it) {\n client->ExecuteScript(*it);\n }\n client->pending_incoming_messages_.clear();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsGetPlatform(\n const v8::Arguments& args) {\n#if defined OS_MACOSX\n return v8String(\"mac-leopard\");\n#elif defined OS_LINUX\n return v8String(\"linux\");\n#else\n return v8String(\"windows\");\n#endif\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsActivateWindow(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->delegate_->ActivateWindow();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsCloseWindow(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->delegate_->CloseWindow();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsDockWindow(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->delegate_->DockWindow();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsUndockWindow(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n client->delegate_->UndockWindow();\n return v8::Undefined();\n}\n\n\/\/ static\nv8::Handle<v8::Value> WebDevToolsClientImpl::JsToggleInspectElementMode(\n const v8::Arguments& args) {\n WebDevToolsClientImpl* client = static_cast<WebDevToolsClientImpl*>(\n v8::External::Cast(*args.Data())->Value());\n int enabled = static_cast<int>(args[0]->BooleanValue());\n client->delegate_->ToggleInspectElementMode(enabled);\n return v8::Undefined();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"chrome\/browser\/browser_window_gtk.h\"\n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/browser.h\"\n\nnamespace {\n\ngboolean MainWindowDestroyed(GtkWindow* window, BrowserWindowGtk* browser_win) {\n delete browser_win;\n return FALSE; \/\/ Don't stop this message.\n}\n\ngboolean MainWindowConfigured(GtkWindow* window, GdkEventConfigure* event,\n BrowserWindowGtk* browser_win) {\n gfx::Rect bounds = gfx::Rect(event->x, event->y, event->width, event->height);\n browser_win->OnBoundsChanged(bounds);\n return FALSE;\n}\n\ngboolean MainWindowStateChanged(GtkWindow* window, GdkEventWindowState* event,\n BrowserWindowGtk* browser_win) {\n browser_win->OnStateChanged(event->new_window_state);\n return FALSE;\n}\n\n\/\/ Using gtk_window_get_position\/size creates a race condition, so only use\n\/\/ this to get the initial bounds. After window creation, we pick up the\n\/\/ normal bounds by connecting to the configure-event signal.\ngfx::Rect GetInitialWindowBounds(GtkWindow* window) {\n gint x, y, width, height;\n gtk_window_get_position(window, &x, &y);\n gtk_window_get_size(window, &width, &height);\n return gfx::Rect(x, y, width, height);\n}\n\n} \/\/ namespace\n\nBrowserWindowGtk::BrowserWindowGtk(Browser* browser) : browser_(browser) {\n Init();\n}\n\nBrowserWindowGtk::~BrowserWindowGtk() {\n Close();\n}\n\nvoid BrowserWindowGtk::Init() {\n window_ = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));\n gtk_window_set_title(window_, \"Chromium\");\n gtk_window_set_default_size(window_, 640, 480);\n g_signal_connect(G_OBJECT(window_), \"destroy\",\n G_CALLBACK(MainWindowDestroyed), this);\n g_signal_connect(G_OBJECT(window_), \"configure-event\",\n G_CALLBACK(MainWindowConfigured), this);\n g_signal_connect(G_OBJECT(window_), \"window-state-event\",\n G_CALLBACK(MainWindowStateChanged), this);\n bounds_ = GetInitialWindowBounds(window_);\n}\n\nvoid BrowserWindowGtk::Show() {\n gtk_widget_show_all(GTK_WIDGET(window_));\n}\n\nvoid BrowserWindowGtk::SetBounds(const gfx::Rect& bounds) {\n gint x = static_cast<gint>(bounds.x());\n gint y = static_cast<gint>(bounds.y());\n gint width = static_cast<gint>(bounds.width());\n gint height = static_cast<gint>(bounds.height());\n\n gtk_window_move(window_, x, y);\n gtk_window_resize(window_, width, height);\n}\n\nvoid BrowserWindowGtk::Close() {\n if (!window_)\n return;\n\n gtk_widget_destroy(GTK_WIDGET(window_));\n window_ = NULL;\n}\n\nvoid BrowserWindowGtk::Activate() {\n gtk_window_present(window_);\n}\n\nvoid BrowserWindowGtk::FlashFrame() {\n \/\/ May not be respected by all window managers.\n gtk_window_set_urgency_hint(window_, TRUE);\n}\n\nvoid* BrowserWindowGtk::GetNativeHandle() {\n return window_;\n}\n\nBrowserWindowTesting* BrowserWindowGtk::GetBrowserWindowTesting() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nStatusBubble* BrowserWindowGtk::GetStatusBubble() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid BrowserWindowGtk::SelectedTabToolbarSizeChanged(bool is_animating) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::UpdateTitleBar() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::UpdateLoadingAnimations(bool should_animate) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::SetStarredState(bool is_starred) {\n NOTIMPLEMENTED();\n}\n\ngfx::Rect BrowserWindowGtk::GetNormalBounds() const {\n return bounds_;\n}\n\nbool BrowserWindowGtk::IsMaximized() const {\n return (state_ & GDK_WINDOW_STATE_MAXIMIZED);\n}\n\nLocationBar* BrowserWindowGtk::GetLocationBar() const {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid BrowserWindowGtk::UpdateStopGoState(bool is_loading) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::UpdateToolbar(TabContents* contents,\n bool should_restore_state) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::FocusToolbar() {\n NOTIMPLEMENTED();\n}\n\nbool BrowserWindowGtk::IsBookmarkBarVisible() const {\n NOTIMPLEMENTED();\n return false;\n}\n\ngfx::Rect BrowserWindowGtk::GetRootWindowResizerRect() const {\n NOTIMPLEMENTED();\n return gfx::Rect();\n}\n\nvoid BrowserWindowGtk::ToggleBookmarkBar() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowAboutChromeDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowBookmarkManager() {\n NOTIMPLEMENTED();\n}\n\nbool BrowserWindowGtk::IsBookmarkBubbleVisible() const {\n NOTIMPLEMENTED();\n return false;\n}\n\nvoid BrowserWindowGtk::ShowBookmarkBubble(const GURL& url,\n bool already_bookmarked) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowReportBugDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowClearBrowsingDataDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowImportDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowSearchEnginesDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowPasswordManager() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowSelectProfileDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowNewProfileDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowHTMLDialog(HtmlDialogContentsDelegate* delegate,\n void* parent_window) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::DestroyBrowser() {\n browser_.reset();\n}\n\nvoid BrowserWindowGtk::OnBoundsChanged(const gfx::Rect& bounds) {\n bounds_ = bounds;\n}\n\nvoid BrowserWindowGtk::OnStateChanged(GdkWindowState state) {\n state_ = state;\n}\n<commit_msg>Revert \"Linux build fix\" This reverts commit r9411.<commit_after>\/\/ 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 \"chrome\/browser\/browser_window_gtk.h\"\n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/browser.h\"\n\nnamespace {\n\ngboolean MainWindowDestroyed(GtkWindow* window, BrowserWindowGtk* browser_win) {\n delete browser_win;\n return FALSE; \/\/ Don't stop this message.\n}\n\ngboolean MainWindowConfigured(GtkWindow* window, GdkEventConfigure* event,\n BrowserWindowGtk* browser_win) {\n gfx::Rect bounds = gfx::Rect(event->x, event->y, event->width, event->height);\n browser_win->OnBoundsChanged(bounds);\n return FALSE;\n}\n\ngboolean MainWindowStateChanged(GtkWindow* window, GdkEventWindowState* event,\n BrowserWindowGtk* browser_win) {\n browser_win->OnStateChanged(event->new_window_state);\n return FALSE;\n}\n\n\/\/ Using gtk_window_get_position\/size creates a race condition, so only use\n\/\/ this to get the initial bounds. After window creation, we pick up the\n\/\/ normal bounds by connecting to the configure-event signal.\ngfx::Rect GetInitialWindowBounds(GtkWindow* window) {\n gint x, y, width, height;\n gtk_window_get_position(window, &x, &y);\n gtk_window_get_size(window, &width, &height);\n return gfx::Rect(x, y, width, height);\n}\n\n} \/\/ namespace\n\nBrowserWindowGtk::BrowserWindowGtk(Browser* browser) : browser_(browser) {\n Init();\n}\n\nBrowserWindowGtk::~BrowserWindowGtk() {\n Close();\n}\n\nvoid BrowserWindowGtk::Init() {\n window_ = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));\n gtk_window_set_title(window_, \"Chromium\");\n gtk_window_set_default_size(window_, 640, 480);\n g_signal_connect(G_OBJECT(window_), \"destroy\",\n G_CALLBACK(MainWindowDestroyed), this);\n g_signal_connect(G_OBJECT(window_), \"configure-event\",\n G_CALLBACK(MainWindowConfigured), this);\n g_signal_connect(G_OBJECT(window_), \"window-state-event\",\n G_CALLBACK(MainWindowStateChanged), this);\n bounds_ = GetInitialWindowBounds(window_);\n}\n\nvoid BrowserWindowGtk::Show() {\n gtk_widget_show_all(GTK_WIDGET(window_));\n}\n\nvoid BrowserWindowGtk::SetBounds(const gfx::Rect& bounds) {\n gint x = static_cast<gint>(bounds.x());\n gint y = static_cast<gint>(bounds.y());\n gint width = static_cast<gint>(bounds.width());\n gint height = static_cast<gint>(bounds.height());\n\n gtk_window_move(window_, x, y);\n gtk_window_resize(window_, width, height);\n}\n\nvoid BrowserWindowGtk::Close() {\n if (!window_)\n return;\n\n gtk_widget_destroy(GTK_WIDGET(window_));\n window_ = NULL;\n}\n\nvoid BrowserWindowGtk::Activate() {\n gtk_window_present(window_);\n}\n\nvoid BrowserWindowGtk::FlashFrame() {\n \/\/ May not be respected by all window managers.\n gtk_window_set_urgency_hint(window_, TRUE);\n}\n\nvoid* BrowserWindowGtk::GetNativeHandle() {\n return window_;\n}\n\nBrowserWindowTesting* BrowserWindowGtk::GetBrowserWindowTesting() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nStatusBubble* BrowserWindowGtk::GetStatusBubble() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid BrowserWindowGtk::SelectedTabToolbarSizeChanged(bool is_animating) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::UpdateTitleBar() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::UpdateLoadingAnimations(bool should_animate) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::SetStarredState(bool is_starred) {\n NOTIMPLEMENTED();\n}\n\ngfx::Rect BrowserWindowGtk::GetNormalBounds() const {\n return bounds_;\n}\n\nbool BrowserWindowGtk::IsMaximized() {\n return (state_ & GDK_WINDOW_STATE_MAXIMIZED);\n}\n\nLocationBar* BrowserWindowGtk::GetLocationBar() const {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid BrowserWindowGtk::UpdateStopGoState(bool is_loading) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::UpdateToolbar(TabContents* contents,\n bool should_restore_state) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::FocusToolbar() {\n NOTIMPLEMENTED();\n}\n\nbool BrowserWindowGtk::IsBookmarkBarVisible() const {\n NOTIMPLEMENTED();\n return false;\n}\n\nvoid BrowserWindowGtk::ToggleBookmarkBar() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowAboutChromeDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowBookmarkManager() {\n NOTIMPLEMENTED();\n}\n\nbool BrowserWindowGtk::IsBookmarkBubbleVisible() const {\n NOTIMPLEMENTED();\n return false;\n}\n\nvoid BrowserWindowGtk::ShowBookmarkBubble(const GURL& url,\n bool already_bookmarked) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowReportBugDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowClearBrowsingDataDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowImportDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowSearchEnginesDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowPasswordManager() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowSelectProfileDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowNewProfileDialog() {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::ShowHTMLDialog(HtmlDialogContentsDelegate* delegate,\n void* parent_window) {\n NOTIMPLEMENTED();\n}\n\nvoid BrowserWindowGtk::DestroyBrowser() {\n browser_.reset();\n}\n\nvoid BrowserWindowGtk::OnBoundsChanged(const gfx::Rect& bounds) {\n bounds_ = bounds;\n}\n\nvoid BrowserWindowGtk::OnStateChanged(GdkWindowState state) {\n state_ = state;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"DatabaseServer.h\"\n\n#include \"core\/global.h\"\n#include <fstream>\n\nConfigVariable<channel_t> control_channel(\"control\", 0);\nConfigVariable<unsigned int> id_start(\"generate\/min\", 1000);\nConfigVariable<unsigned int> id_end(\"generate\/max\", 2000);\nConfigVariable<std::string> storage_type(\"storage\/type\", \"yaml\");\nLogCategory db_log(\"db\", \"Database\");\n\nDatabaseServer::DatabaseServer(RoleConfig roleconfig) : Role(roleconfig)\n{\n\tm_log = &db_log;\n\tm_channel = control_channel.get_rval(roleconfig);\n\tm_db = DatabaseFactory::singleton.instantiate_db(storage_type.get_rval(roleconfig), roleconfig[\"storage\"]);\n\tif(!m_db) {\n\t\tm_log->fatal() << \"Database has no storage backend of type: \" << storage_type.get_rval(roleconfig) << std::endl;\n\t\texit(1);\n\t}\n\tm_start_id = m_free_id = id_start.get_rval(roleconfig);\n\tm_end_id = id_end.get_rval(roleconfig);\n\n\tsubscribe_channel(m_channel);\n}\n\nDatabaseServer::~DatabaseServer() {}\n\nvoid DatabaseServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi)\n{\n\tchannel_t sender = dgi.read_uint64();\n\tunsigned short msg_type = dgi.read_uint16();\n\tswitch(msg_type)\n\t{\n\t\tcase DBSERVER_CREATE_STORED_OBJECT:\n\t\t{\n\t\t\tunsigned int context = dgi.read_uint32();\n\t\t\tunsigned short dc_id = dgi.read_uint16();\n\t\t\tDCClass *dcc = gDCF->get_class(dc_id);\n\t\t\tunsigned short field_count = dgi.read_uint16();\n\t\t\tunsigned int do_id = m_free_id;\n\t\t\tif(do_id > m_end_id)\n\t\t\t{\n\t\t\t\tm_log->error() << \"Database ran out of DistributedObject ids\" << std::endl;\n\t\t\t\tDatagram resp;\n\t\t\t\tresp.add_server_header(sender, m_channel, DBSERVER_CREATE_STORED_OBJECT_RESP);\n\t\t\t\tresp.add_uint32(context);\n\t\t\t\tresp.add_uint32(0);\n\t\t\t\tsend(resp);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tm_free_id++;\n\n\t\t\tFieldList fields;\n\t\t\tfor(unsigned short i = 0; i < field_count; ++i)\n\t\t\t{\n\t\t\t\tunsigned short field_id = dgi.read_uint16();\n\t\t\t\tDCField *field = dcc->get_field(field_id);\n\t\t\t\tif(field && field->is_db())\n\t\t\t\t{\n\t\t\t\t\tfields.emplace(fields.end(), field, \"\");\n\t\t\t\t\tdgi.unpack_field(field, fields.back().second);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_db->create_object(do_id, fields);\n\n\t\t\tDatagram resp;\n\t\t\tresp.add_server_header(sender, m_channel, DBSERVER_CREATE_STORED_OBJECT_RESP);\n\t\t\tresp.add_uint32(context);\n\t\t\tresp.add_uint32(do_id);\n\t\t\tsend(resp);\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tdb_log.error() << \"DB recv'd unknown MsgType: \" << msg_type\n\t\t\t\t<< std::endl;\n\t};\n}\n\nRoleFactoryItem<DatabaseServer> dbserver_fact(\"database\");\n<commit_msg>DBServer: Clean debug messages (note, all messages prefixed with Database: already)<commit_after>#include \"DatabaseServer.h\"\n\n#include \"core\/global.h\"\n#include <fstream>\n\nConfigVariable<channel_t> control_channel(\"control\", 0);\nConfigVariable<unsigned int> id_start(\"generate\/min\", 1000);\nConfigVariable<unsigned int> id_end(\"generate\/max\", 2000);\nConfigVariable<std::string> storage_type(\"storage\/type\", \"yaml\");\nLogCategory db_log(\"db\", \"Database\");\n\nDatabaseServer::DatabaseServer(RoleConfig roleconfig) : Role(roleconfig)\n{\n\tm_log = &db_log;\n\tm_channel = control_channel.get_rval(roleconfig);\n\tm_db = DatabaseFactory::singleton.instantiate_db(storage_type.get_rval(roleconfig), roleconfig[\"storage\"]);\n\tif(!m_db) {\n\t\tm_log->fatal() << \"No storage backend of type '\" << storage_type.get_rval(roleconfig) << \"' exists.\" << std::endl;\n\t\texit(1);\n\t}\n\tm_start_id = m_free_id = id_start.get_rval(roleconfig);\n\tm_end_id = id_end.get_rval(roleconfig);\n\n\tsubscribe_channel(m_channel);\n}\n\nDatabaseServer::~DatabaseServer() {}\n\nvoid DatabaseServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi)\n{\n\tchannel_t sender = dgi.read_uint64();\n\tunsigned short msg_type = dgi.read_uint16();\n\tswitch(msg_type)\n\t{\n\t\tcase DBSERVER_CREATE_STORED_OBJECT:\n\t\t{\n\t\t\tunsigned int context = dgi.read_uint32();\n\t\t\tunsigned short dc_id = dgi.read_uint16();\n\t\t\tDCClass *dcc = gDCF->get_class(dc_id);\n\t\t\tunsigned short field_count = dgi.read_uint16();\n\t\t\tunsigned int do_id = m_free_id;\n\t\t\tif(do_id > m_end_id)\n\t\t\t{\n\t\t\t\tm_log->error() << \"Ran out of DistributedObject ids while creating new object.\" << std::endl;\n\t\t\t\tDatagram resp;\n\t\t\t\tresp.add_server_header(sender, m_channel, DBSERVER_CREATE_STORED_OBJECT_RESP);\n\t\t\t\tresp.add_uint32(context);\n\t\t\t\tresp.add_uint32(0);\n\t\t\t\tsend(resp);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tm_free_id++;\n\n\t\t\tm_log->spam() << \"Created stored object with ID: \" << do_id << std::endl;\n\n\t\t\tFieldList fields;\n\t\t\tfor(unsigned short i = 0; i < field_count; ++i)\n\t\t\t{\n\t\t\t\tunsigned short field_id = dgi.read_uint16();\n\t\t\t\tDCField *field = dcc->get_field(field_id);\n\t\t\t\tif(field && field->is_db())\n\t\t\t\t{\n\t\t\t\t\tfields.emplace(fields.end(), field, \"\");\n\t\t\t\t\tdgi.unpack_field(field, fields.back().second);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_db->create_object(do_id, fields);\n\n\t\t\tDatagram resp;\n\t\t\tresp.add_server_header(sender, m_channel, DBSERVER_CREATE_STORED_OBJECT_RESP);\n\t\t\tresp.add_uint32(context);\n\t\t\tresp.add_uint32(do_id);\n\t\t\tsend(resp);\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tdb_log.error() << \"Recieved unknown MsgType: \" << msg_type\n\t\t\t\t<< std::endl;\n\t};\n}\n\nRoleFactoryItem<DatabaseServer> dbserver_fact(\"database\");\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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\/browser\/views\/app_launcher.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/browser\/views\/dom_view.h\"\n#include \"chrome\/browser\/views\/info_bubble.h\"\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/views\/location_bar\/location_bar_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"views\/widget\/root_view.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/status\/status_area_view.h\"\n#endif\n\nnamespace {\n\n\/\/ Padding between the navigation bar and the render view contents.\nconst int kNavigationBarBottomPadding = 3;\n\n\/\/ NavigationBar constants.\nconst int kNavigationBarBorderThickness = 1;\n\n\/\/ The speed in pixels per milli-second at which the animation should progress.\n\/\/ It is easier to use a speed than a duration as the contents may report\n\/\/ several changes in size over-time.\nconst double kAnimationSpeedPxPerMS = 1.5;\n\nconst SkColor kBorderColor = SkColorSetRGB(205, 201, 201);\n\n\/\/ Command line switch for specifying url of the page.\n\/\/ TODO: nuke when we convert to the real app page. Also nuke code in\n\/\/ AddNewContents\nconst char kURLSwitch[] = \"main-menu-url\";\n\n\/\/ Returns the URL of the menu.\nstatic GURL GetMenuURL() {\n std::string url_string =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kURLSwitch);\n if (!url_string.empty())\n return GURL(url_string);\n return GURL(chrome::kChromeUIAppLauncherURL);\n}\n\n\/\/ Returns the location bar view of |browser|.\nstatic views::View* GetBrowserLocationBar(Browser* browser) {\n BrowserView* browser_view = static_cast<BrowserView*>(browser->window());\n views::RootView* root_view = views::Widget::GetWidgetFromNativeWindow(\n browser_view->GetNativeHandle())->GetRootView();\n return root_view->GetViewByID(VIEW_ID_LOCATION_BAR);\n}\n\n} \/\/ namespace\n\n\/\/ InfoBubbleContentsView\n\/\/\n\/\/ The view that contains the navigation bar and DOMUI.\n\/\/ It is displayed in an info-bubble.\n\nclass InfoBubbleContentsView : public views::View,\n public LocationBarView::Delegate,\n public CommandUpdater::CommandUpdaterDelegate {\n public:\n explicit InfoBubbleContentsView(AppLauncher* app_launcher);\n ~InfoBubbleContentsView();\n\n \/\/ Computes and sets the preferred size for the InfoBubbleContentsView based\n \/\/ on the preferred size of the DOMUI contents specified.\n void ComputePreferredSize(const gfx::Size& dom_view_preferred_size);\n\n \/\/ Sets the initial focus.\n \/\/ Should be called when the bubble that contains us is shown.\n void BubbleShown();\n\n \/\/ Returns the TabContents displaying the contents for this bubble.\n TabContents* GetBubbleTabContents();\n\n \/\/ views::View override:\n virtual gfx::Size GetPreferredSize();\n virtual void Layout();\n virtual void ViewHierarchyChanged(bool is_add,\n views::View* parent,\n views::View* child);\n\n \/\/ LocationBarView::Delegate implementation:\n\n \/\/ WARNING: this is not the TabContents of the bubble! Use\n \/\/ GetBubbleTabContents() to get the bubble's TabContents.\n virtual TabContents* GetTabContents();\n virtual void OnInputInProgress(bool in_progress) {}\n\n \/\/ CommandUpdater::CommandUpdaterDelegate implementation:\n virtual void ExecuteCommand(int id);\n\n private:\n \/\/ The application launcher displaying this info bubble.\n AppLauncher* app_launcher_;\n\n \/\/ The location bar.\n LocationBarView* location_bar_;\n\n \/\/ The view containing the renderer view.\n DOMView* dom_view_;\n\n \/\/ The preferred size for this view (at which it fits its contents).\n gfx::Size preferred_size_;\n\n \/\/ CommandUpdater the location bar sends commands to.\n CommandUpdater command_updater_;\n\n \/\/ The width of the browser's location bar.\n int browser_location_bar_width_;\n\n DISALLOW_COPY_AND_ASSIGN(InfoBubbleContentsView);\n};\n\nInfoBubbleContentsView::InfoBubbleContentsView(AppLauncher* app_launcher)\n : app_launcher_(app_launcher),\n location_bar_(NULL),\n dom_view_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(command_updater_(this)) {\n \/\/ Allow the location bar to open URLs.\n command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, true);\n DCHECK(app_launcher);\n\n browser_location_bar_width_ =\n GetBrowserLocationBar(app_launcher->browser())->width();\n}\n\nInfoBubbleContentsView::~InfoBubbleContentsView() {\n}\n\nvoid InfoBubbleContentsView::ComputePreferredSize(\n const gfx::Size& dom_view_preferred_size) {\n preferred_size_ = dom_view_preferred_size;\n\n \/\/ Add the padding and location bar height.\n preferred_size_.Enlarge(\n 0, location_bar_->height() + kNavigationBarBottomPadding);\n\n \/\/ Make sure the width is at least the browser location bar width.\n if (preferred_size_.width() < browser_location_bar_width_)\n preferred_size_.set_width(browser_location_bar_width_);\n}\n\nvoid InfoBubbleContentsView::BubbleShown() {\n location_bar_->RequestFocus();\n}\n\nTabContents* InfoBubbleContentsView::GetBubbleTabContents() {\n return dom_view_->tab_contents();\n}\n\nvoid InfoBubbleContentsView::ViewHierarchyChanged(\n bool is_add, views::View* parent, views::View* child) {\n if (!is_add || child != this)\n return;\n\n DCHECK(!dom_view_);\n dom_view_ = new DOMView();\n AddChildView(dom_view_);\n \/\/ We pass NULL for site instance so the renderer uses its own process.\n dom_view_->Init(app_launcher_->browser()->profile(), NULL);\n \/\/ We make the AppLauncher the TabContents delegate so we get notifications\n \/\/ from the page to open links.\n dom_view_->tab_contents()->set_delegate(app_launcher_);\n GURL url = GetMenuURL();\n std::string ref = url.ref();\n if (!app_launcher_->hash_params().empty()) {\n if (!ref.empty())\n ref += \"&\";\n ref += app_launcher_->hash_params();\n\n url_canon::Replacements<char> replacements;\n replacements.SetRef(ref.c_str(), url_parse::Component(0, ref.size()));\n url = url.ReplaceComponents(replacements);\n }\n dom_view_->LoadURL(url);\n\n Browser* browser = app_launcher_->browser();\n location_bar_ = new LocationBarView(browser->profile(),\n &command_updater_,\n browser->toolbar_model(),\n this,\n LocationBarView::APP_LAUNCHER);\n\n location_bar_->set_border(\n views::Border::CreateSolidBorder(kNavigationBarBorderThickness,\n kBorderColor));\n AddChildView(location_bar_);\n location_bar_->Init();\n \/\/ Size the location to its preferred size so ComputePreferredSize() computes\n \/\/ the right size.\n location_bar_->SizeToPreferredSize();\n ComputePreferredSize(gfx::Size(browser_location_bar_width_, 0));\n Layout();\n}\n\nTabContents* InfoBubbleContentsView::GetTabContents() {\n return app_launcher_->browser()->GetSelectedTabContents();\n}\n\ngfx::Size InfoBubbleContentsView::GetPreferredSize() {\n return preferred_size_;\n}\n\nvoid InfoBubbleContentsView::Layout() {\n if (bounds().IsEmpty() || GetChildViewCount() == 0)\n return;\n\n gfx::Rect bounds = GetLocalBounds(false);\n \/\/ The browser's location bar uses vertical padding that we need to take into\n \/\/ account to match its height.\n int location_bar_height = location_bar_->GetPreferredSize().height() -\n LocationBarView::kVerticalEdgeThickness;\n location_bar_->SetBounds(bounds.x(), bounds.y(), bounds.width(),\n location_bar_height);\n int render_y = location_bar_->bounds().bottom() + kNavigationBarBottomPadding;\n dom_view_->SetBounds(0, render_y,\n width(), app_launcher_->contents_pref_size_.height());\n}\n\nvoid InfoBubbleContentsView::ExecuteCommand(int id) {\n \/\/ The user navigated by typing or selecting an entry in the location bar.\n DCHECK_EQ(IDC_OPEN_CURRENT_URL, id);\n GURL url(WideToUTF8(location_bar_->GetInputString()));\n app_launcher_->AddTabWithURL(url, location_bar_->GetPageTransition());\n app_launcher_->Hide();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AppLauncher\n\nAppLauncher::AppLauncher(Browser* browser)\n : browser_(browser),\n info_bubble_(NULL) {\n DCHECK(browser);\n info_bubble_content_ = new InfoBubbleContentsView(this);\n#if defined(OS_WIN)\n animate_ = true;\n animation_.reset(new SlideAnimation(this));\n animation_->SetTweenType(Tween::LINEAR);\n#else\n animate_ = false;\n#endif\n}\n\nAppLauncher::~AppLauncher() {\n}\n\n\/\/ static\nAppLauncher* AppLauncher::Show(Browser* browser,\n const gfx::Rect& bounds,\n const gfx::Point& bubble_anchor,\n const std::string& hash_params) {\n AppLauncher* app_launcher = new AppLauncher(browser);\n BrowserView* browser_view = static_cast<BrowserView*>(browser->window());\n app_launcher->hash_params_ = hash_params;\n app_launcher->info_bubble_ =\n PinnedContentsInfoBubble::Show(browser_view->GetWidget(),\n bounds, BubbleBorder::TOP_LEFT, bubble_anchor,\n app_launcher->info_bubble_content_, app_launcher);\n app_launcher->info_bubble_content_->BubbleShown();\n\n \/\/ TODO(finnur): Change this so that we only fade out when the user launches\n \/\/ something from the bubble. This will fade out on dismiss as well.\n app_launcher->info_bubble_->set_fade_away_on_close(true);\n return app_launcher;\n}\n\n\/\/ static\nAppLauncher* AppLauncher::ShowForNewTab(Browser* browser,\n const std::string& hash_params) {\n BrowserView* browser_view = static_cast<BrowserView*>(browser->window());\n TabStrip* tabstrip = browser_view->tabstrip()->AsTabStrip();\n if (!tabstrip)\n return NULL;\n gfx::Rect bounds = tabstrip->GetNewTabButtonBounds();\n gfx::Point origin = bounds.origin();\n views::RootView::ConvertPointToScreen(tabstrip, &origin);\n bounds.set_origin(origin);\n\n \/\/ Figure out where the location bar is, so we can pin the bubble to\n \/\/ make our url bar appear exactly over it.\n views::View* location_bar = GetBrowserLocationBar(browser);\n gfx::Point location_bar_origin = location_bar->bounds().origin();\n views::RootView::ConvertPointToScreen(location_bar->GetParent(),\n &location_bar_origin);\n\n return Show(browser, bounds, location_bar_origin, hash_params);\n}\n\nvoid AppLauncher::Hide() {\n info_bubble_->Close();\n}\n\nvoid AppLauncher::OpenURLFromTab(TabContents* source,\n const GURL& url, const GURL& referrer,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n \/\/ TODO(jcivelli): we should call Browser::OpenApplicationTab(), we would need\n \/\/ to access the app for this URL.\n \/\/ The user clicked an item in the app launcher contents.\n AddTabWithURL(url, PageTransition::AUTO_BOOKMARK);\n Hide();\n}\n\nvoid AppLauncher::AddNewContents(TabContents* source,\n TabContents* new_contents,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n#if defined(OS_CHROMEOS)\n \/\/ ChromeOS uses the kURLSwitch to specify a page that opens popups. We need\n \/\/ to do this so the popups are opened when the user clicks on the page.\n \/\/ TODO: nuke when convert to the real app page.\n new_contents->set_delegate(NULL);\n browser_->GetSelectedTabContents()->AddNewContents(\n new_contents, disposition, initial_pos, user_gesture);\n Hide();\n#endif\n}\n\nvoid AppLauncher::UpdatePreferredSize(const gfx::Size& pref_size) {\n if (pref_size.width() == 0 || pref_size.height() == 0)\n return;\n\n previous_contents_pref_size_ = contents_pref_size_;\n contents_pref_size_ = pref_size;\n\n if (!animate_) {\n info_bubble_content_->ComputePreferredSize(pref_size);\n info_bubble_->SizeToContents();\n return;\n }\n\n int original_height = previous_contents_pref_size_.height();\n int new_height = contents_pref_size_.height();\n int new_duration;\n if (animation_->is_animating()) {\n \/\/ Modify the animation duration so that the current running animation does\n \/\/ not appear janky.\n new_duration = static_cast<int>(new_height \/ kAnimationSpeedPxPerMS);\n } else {\n \/\/ The animation is not running.\n animation_->Reset(); \/\/ It may have already been run.\n new_duration = static_cast<int>(abs(new_height - original_height) \/\n kAnimationSpeedPxPerMS);\n }\n animation_->SetSlideDuration(new_duration);\n animation_->Show(); \/\/ No-op if already showing.\n}\n\nvoid AppLauncher::AnimationProgressed(const Animation* animation) {\n gfx::Size contents_size(contents_pref_size_.width(),\n animation->CurrentValueBetween(previous_contents_pref_size_.height(),\n contents_pref_size_.height()));\n info_bubble_content_->ComputePreferredSize(contents_size);\n info_bubble_->SizeToContents();\n}\n\nvoid AppLauncher::InfoBubbleClosing(InfoBubble* info_bubble,\n bool closed_by_escape) {\n \/\/ Delay deleting to be safe (we, and our tabcontents may be on the stack).\n \/\/ Remove ourself as a delegate as on GTK the Widget destruction is\n \/\/ asynchronous and will happen after the AppLauncher has been deleted (and it\n \/\/ might notify us after we have been deleted).\n info_bubble_content_->GetBubbleTabContents()->set_delegate(NULL);\n MessageLoop::current()->PostTask(FROM_HERE,\n new DeleteTask<AppLauncher>(this));\n}\n\nvoid AppLauncher::AddTabWithURL(const GURL& url,\n PageTransition::Type transition) {\n browser_->AddTabWithURL(\n url, GURL(), transition, -1,\n TabStripModel::ADD_SELECTED | TabStripModel::ADD_FORCE_INDEX, NULL,\n std::string(), NULL);\n}\n\nvoid AppLauncher::Resize(const gfx::Size& contents_size) {\n info_bubble_content_->ComputePreferredSize(contents_size);\n info_bubble_->SizeToContents();\n}\n<commit_msg>Nukes --main-menu-url as it's not used anymore.<commit_after>\/\/ Copyright (c) 2010 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\/browser\/views\/app_launcher.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/browser\/views\/dom_view.h\"\n#include \"chrome\/browser\/views\/info_bubble.h\"\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/views\/location_bar\/location_bar_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"views\/widget\/root_view.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/status\/status_area_view.h\"\n#endif\n\nnamespace {\n\n\/\/ Padding between the navigation bar and the render view contents.\nconst int kNavigationBarBottomPadding = 3;\n\n\/\/ NavigationBar constants.\nconst int kNavigationBarBorderThickness = 1;\n\n\/\/ The speed in pixels per milli-second at which the animation should progress.\n\/\/ It is easier to use a speed than a duration as the contents may report\n\/\/ several changes in size over-time.\nconst double kAnimationSpeedPxPerMS = 1.5;\n\nconst SkColor kBorderColor = SkColorSetRGB(205, 201, 201);\n\n\/\/ Returns the location bar view of |browser|.\nstatic views::View* GetBrowserLocationBar(Browser* browser) {\n BrowserView* browser_view = static_cast<BrowserView*>(browser->window());\n views::RootView* root_view = views::Widget::GetWidgetFromNativeWindow(\n browser_view->GetNativeHandle())->GetRootView();\n return root_view->GetViewByID(VIEW_ID_LOCATION_BAR);\n}\n\n} \/\/ namespace\n\n\/\/ InfoBubbleContentsView\n\/\/\n\/\/ The view that contains the navigation bar and DOMUI.\n\/\/ It is displayed in an info-bubble.\n\nclass InfoBubbleContentsView : public views::View,\n public LocationBarView::Delegate,\n public CommandUpdater::CommandUpdaterDelegate {\n public:\n explicit InfoBubbleContentsView(AppLauncher* app_launcher);\n ~InfoBubbleContentsView();\n\n \/\/ Computes and sets the preferred size for the InfoBubbleContentsView based\n \/\/ on the preferred size of the DOMUI contents specified.\n void ComputePreferredSize(const gfx::Size& dom_view_preferred_size);\n\n \/\/ Sets the initial focus.\n \/\/ Should be called when the bubble that contains us is shown.\n void BubbleShown();\n\n \/\/ Returns the TabContents displaying the contents for this bubble.\n TabContents* GetBubbleTabContents();\n\n \/\/ views::View override:\n virtual gfx::Size GetPreferredSize();\n virtual void Layout();\n virtual void ViewHierarchyChanged(bool is_add,\n views::View* parent,\n views::View* child);\n\n \/\/ LocationBarView::Delegate implementation:\n\n \/\/ WARNING: this is not the TabContents of the bubble! Use\n \/\/ GetBubbleTabContents() to get the bubble's TabContents.\n virtual TabContents* GetTabContents();\n virtual void OnInputInProgress(bool in_progress) {}\n\n \/\/ CommandUpdater::CommandUpdaterDelegate implementation:\n virtual void ExecuteCommand(int id);\n\n private:\n \/\/ The application launcher displaying this info bubble.\n AppLauncher* app_launcher_;\n\n \/\/ The location bar.\n LocationBarView* location_bar_;\n\n \/\/ The view containing the renderer view.\n DOMView* dom_view_;\n\n \/\/ The preferred size for this view (at which it fits its contents).\n gfx::Size preferred_size_;\n\n \/\/ CommandUpdater the location bar sends commands to.\n CommandUpdater command_updater_;\n\n \/\/ The width of the browser's location bar.\n int browser_location_bar_width_;\n\n DISALLOW_COPY_AND_ASSIGN(InfoBubbleContentsView);\n};\n\nInfoBubbleContentsView::InfoBubbleContentsView(AppLauncher* app_launcher)\n : app_launcher_(app_launcher),\n location_bar_(NULL),\n dom_view_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(command_updater_(this)) {\n \/\/ Allow the location bar to open URLs.\n command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, true);\n DCHECK(app_launcher);\n\n browser_location_bar_width_ =\n GetBrowserLocationBar(app_launcher->browser())->width();\n}\n\nInfoBubbleContentsView::~InfoBubbleContentsView() {\n}\n\nvoid InfoBubbleContentsView::ComputePreferredSize(\n const gfx::Size& dom_view_preferred_size) {\n preferred_size_ = dom_view_preferred_size;\n\n \/\/ Add the padding and location bar height.\n preferred_size_.Enlarge(\n 0, location_bar_->height() + kNavigationBarBottomPadding);\n\n \/\/ Make sure the width is at least the browser location bar width.\n if (preferred_size_.width() < browser_location_bar_width_)\n preferred_size_.set_width(browser_location_bar_width_);\n}\n\nvoid InfoBubbleContentsView::BubbleShown() {\n location_bar_->RequestFocus();\n}\n\nTabContents* InfoBubbleContentsView::GetBubbleTabContents() {\n return dom_view_->tab_contents();\n}\n\nvoid InfoBubbleContentsView::ViewHierarchyChanged(\n bool is_add, views::View* parent, views::View* child) {\n if (!is_add || child != this)\n return;\n\n DCHECK(!dom_view_);\n dom_view_ = new DOMView();\n AddChildView(dom_view_);\n \/\/ We pass NULL for site instance so the renderer uses its own process.\n dom_view_->Init(app_launcher_->browser()->profile(), NULL);\n \/\/ We make the AppLauncher the TabContents delegate so we get notifications\n \/\/ from the page to open links.\n dom_view_->tab_contents()->set_delegate(app_launcher_);\n GURL url(chrome::kChromeUIAppLauncherURL);\n std::string ref = url.ref();\n if (!app_launcher_->hash_params().empty()) {\n if (!ref.empty())\n ref += \"&\";\n ref += app_launcher_->hash_params();\n\n url_canon::Replacements<char> replacements;\n replacements.SetRef(ref.c_str(), url_parse::Component(0, ref.size()));\n url = url.ReplaceComponents(replacements);\n }\n dom_view_->LoadURL(url);\n\n Browser* browser = app_launcher_->browser();\n location_bar_ = new LocationBarView(browser->profile(),\n &command_updater_,\n browser->toolbar_model(),\n this,\n LocationBarView::APP_LAUNCHER);\n\n location_bar_->set_border(\n views::Border::CreateSolidBorder(kNavigationBarBorderThickness,\n kBorderColor));\n AddChildView(location_bar_);\n location_bar_->Init();\n \/\/ Size the location to its preferred size so ComputePreferredSize() computes\n \/\/ the right size.\n location_bar_->SizeToPreferredSize();\n ComputePreferredSize(gfx::Size(browser_location_bar_width_, 0));\n Layout();\n}\n\nTabContents* InfoBubbleContentsView::GetTabContents() {\n return app_launcher_->browser()->GetSelectedTabContents();\n}\n\ngfx::Size InfoBubbleContentsView::GetPreferredSize() {\n return preferred_size_;\n}\n\nvoid InfoBubbleContentsView::Layout() {\n if (bounds().IsEmpty() || GetChildViewCount() == 0)\n return;\n\n gfx::Rect bounds = GetLocalBounds(false);\n \/\/ The browser's location bar uses vertical padding that we need to take into\n \/\/ account to match its height.\n int location_bar_height = location_bar_->GetPreferredSize().height() -\n LocationBarView::kVerticalEdgeThickness;\n location_bar_->SetBounds(bounds.x(), bounds.y(), bounds.width(),\n location_bar_height);\n int render_y = location_bar_->bounds().bottom() + kNavigationBarBottomPadding;\n dom_view_->SetBounds(0, render_y,\n width(), app_launcher_->contents_pref_size_.height());\n}\n\nvoid InfoBubbleContentsView::ExecuteCommand(int id) {\n \/\/ The user navigated by typing or selecting an entry in the location bar.\n DCHECK_EQ(IDC_OPEN_CURRENT_URL, id);\n GURL url(WideToUTF8(location_bar_->GetInputString()));\n app_launcher_->AddTabWithURL(url, location_bar_->GetPageTransition());\n app_launcher_->Hide();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AppLauncher\n\nAppLauncher::AppLauncher(Browser* browser)\n : browser_(browser),\n info_bubble_(NULL) {\n DCHECK(browser);\n info_bubble_content_ = new InfoBubbleContentsView(this);\n#if defined(OS_WIN)\n animate_ = true;\n animation_.reset(new SlideAnimation(this));\n animation_->SetTweenType(Tween::LINEAR);\n#else\n animate_ = false;\n#endif\n}\n\nAppLauncher::~AppLauncher() {\n}\n\n\/\/ static\nAppLauncher* AppLauncher::Show(Browser* browser,\n const gfx::Rect& bounds,\n const gfx::Point& bubble_anchor,\n const std::string& hash_params) {\n AppLauncher* app_launcher = new AppLauncher(browser);\n BrowserView* browser_view = static_cast<BrowserView*>(browser->window());\n app_launcher->hash_params_ = hash_params;\n app_launcher->info_bubble_ =\n PinnedContentsInfoBubble::Show(browser_view->GetWidget(),\n bounds, BubbleBorder::TOP_LEFT, bubble_anchor,\n app_launcher->info_bubble_content_, app_launcher);\n app_launcher->info_bubble_content_->BubbleShown();\n\n \/\/ TODO(finnur): Change this so that we only fade out when the user launches\n \/\/ something from the bubble. This will fade out on dismiss as well.\n app_launcher->info_bubble_->set_fade_away_on_close(true);\n return app_launcher;\n}\n\n\/\/ static\nAppLauncher* AppLauncher::ShowForNewTab(Browser* browser,\n const std::string& hash_params) {\n BrowserView* browser_view = static_cast<BrowserView*>(browser->window());\n TabStrip* tabstrip = browser_view->tabstrip()->AsTabStrip();\n if (!tabstrip)\n return NULL;\n gfx::Rect bounds = tabstrip->GetNewTabButtonBounds();\n gfx::Point origin = bounds.origin();\n views::RootView::ConvertPointToScreen(tabstrip, &origin);\n bounds.set_origin(origin);\n\n \/\/ Figure out where the location bar is, so we can pin the bubble to\n \/\/ make our url bar appear exactly over it.\n views::View* location_bar = GetBrowserLocationBar(browser);\n gfx::Point location_bar_origin = location_bar->bounds().origin();\n views::RootView::ConvertPointToScreen(location_bar->GetParent(),\n &location_bar_origin);\n\n return Show(browser, bounds, location_bar_origin, hash_params);\n}\n\nvoid AppLauncher::Hide() {\n info_bubble_->Close();\n}\n\nvoid AppLauncher::OpenURLFromTab(TabContents* source,\n const GURL& url, const GURL& referrer,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n \/\/ TODO(jcivelli): we should call Browser::OpenApplicationTab(), we would need\n \/\/ to access the app for this URL.\n \/\/ The user clicked an item in the app launcher contents.\n AddTabWithURL(url, PageTransition::AUTO_BOOKMARK);\n Hide();\n}\n\nvoid AppLauncher::AddNewContents(TabContents* source,\n TabContents* new_contents,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n}\n\nvoid AppLauncher::UpdatePreferredSize(const gfx::Size& pref_size) {\n if (pref_size.width() == 0 || pref_size.height() == 0)\n return;\n\n previous_contents_pref_size_ = contents_pref_size_;\n contents_pref_size_ = pref_size;\n\n if (!animate_) {\n info_bubble_content_->ComputePreferredSize(pref_size);\n info_bubble_->SizeToContents();\n return;\n }\n\n int original_height = previous_contents_pref_size_.height();\n int new_height = contents_pref_size_.height();\n int new_duration;\n if (animation_->is_animating()) {\n \/\/ Modify the animation duration so that the current running animation does\n \/\/ not appear janky.\n new_duration = static_cast<int>(new_height \/ kAnimationSpeedPxPerMS);\n } else {\n \/\/ The animation is not running.\n animation_->Reset(); \/\/ It may have already been run.\n new_duration = static_cast<int>(abs(new_height - original_height) \/\n kAnimationSpeedPxPerMS);\n }\n animation_->SetSlideDuration(new_duration);\n animation_->Show(); \/\/ No-op if already showing.\n}\n\nvoid AppLauncher::AnimationProgressed(const Animation* animation) {\n gfx::Size contents_size(contents_pref_size_.width(),\n animation->CurrentValueBetween(previous_contents_pref_size_.height(),\n contents_pref_size_.height()));\n info_bubble_content_->ComputePreferredSize(contents_size);\n info_bubble_->SizeToContents();\n}\n\nvoid AppLauncher::InfoBubbleClosing(InfoBubble* info_bubble,\n bool closed_by_escape) {\n \/\/ Delay deleting to be safe (we, and our tabcontents may be on the stack).\n \/\/ Remove ourself as a delegate as on GTK the Widget destruction is\n \/\/ asynchronous and will happen after the AppLauncher has been deleted (and it\n \/\/ might notify us after we have been deleted).\n info_bubble_content_->GetBubbleTabContents()->set_delegate(NULL);\n MessageLoop::current()->PostTask(FROM_HERE,\n new DeleteTask<AppLauncher>(this));\n}\n\nvoid AppLauncher::AddTabWithURL(const GURL& url,\n PageTransition::Type transition) {\n browser_->AddTabWithURL(\n url, GURL(), transition, -1,\n TabStripModel::ADD_SELECTED | TabStripModel::ADD_FORCE_INDEX, NULL,\n std::string(), NULL);\n}\n\nvoid AppLauncher::Resize(const gfx::Size& contents_size) {\n info_bubble_content_->ComputePreferredSize(contents_size);\n info_bubble_->SizeToContents();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Modifies the over-install behavior of setup to launch Chrome itself instead of letting Omaha do it.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Style issues: - Fix indentation. - Reorder typedefs according to style guide. - Add DISALLOW_COPY_AND_ASSIGN. Review URL: http:\/\/codereview.chromium.org\/42322<commit_after><|endoftext|>"} {"text":"<commit_before>\n#ifndef CHROMOSOME_HPP_\n#define CHROMOSOME_HPP_\n\n#include <vector>\t \/\/ vector\n#include <algorithm> \/\/ swap_ranges\n#include <random> \/\/ mt19937, uniform_int_distribution, random_device\n\n#define MINIMUM_NUMBER 0\n\ntemplate <class T>\nclass Chromosome {\n\nprotected:\n std::vector<T > chromosome;\n\n \/\/ random number generator values.\n static std::mt19937 random_engine;\n static std::uniform_int_distribution<int > rand_chrom_elem;\n \/\/ This only works with integer values\n static std::uniform_int_distribution<int > rand_value;\n\n\npublic:\n \n \/**\n * Default contructor to allow for easier creation.\n *\/\n Chromosome() {\n\n }\n\n \/**\n * Create a chromosome of the given size\n * @param chromosome_size The size of the chromosome.\n *\/\n Chromosome(unsigned int chromosome_size) : chromosome(chromosome_size){\n }\n\n ~Chromosome() {\n\n }\n\n \/**\n * Create a chromosome of the given size\n * @param chromosome_size The size of the chromosome.\n *\/\n Chromosome(std::vector<T > chromosome) {\n \tthis->chromosome = chromosome;\n }\n\n \/**\n * Initialize the population to random values. This only needs to be called on\n * the first generation during setup.\n * @param population The output population, note this will be cleared of any\n * existing values.\n * @param population_size The size of the population.\n * @param chromosome_size The size of the chromosomes within the population.\n *\/\n static void initPopulation(std::vector<Chromosome<T > > &population,\n \t\tunsigned int population_size, unsigned int chromosome_size) {\n \tpopulation.clear();\n \tfor(unsigned int i = 0; i < population_size; i++) {\n \t\tChromosome<T > chrom (chromosome_size);\n \t\tchrom.randChromosome();\n \t\tpopulation.push_back(chrom);\n \t}\n }\n\n \/**\n * Set up the random number generator engines to allow within the defined ranges.\n * @param chromosome_size The size of the chromosome.\n * @param min_chromosome_value The minimum value of a chromosome element.\n * @param max_chromosome_value The maximum value of a chromosome element.\n *\/\n static void initialize(unsigned int chromosome_size, T min_chromosome_value, T max_chromosome_value) {\n\n\t\t\/\/ Set up the random number generator engines.\n\t\tstd::random_device rd;\n\t\trandom_engine = std::mt19937 (rd());\n\t\trand_chrom_elem = std::uniform_int_distribution<int> (MINIMUM_NUMBER, chromosome_size - 1);\n\t\trand_value = std::uniform_int_distribution<int > (min_chromosome_value, max_chromosome_value);\n }\n\n \/**\n * Apply the mutation operation to the chromosome and put it into the next generation.\n * @param children The next generation of chromosomes (the next population) that is currently being bread.\n *\/\n void mutate() {\n \t\/\/clonning(children);\n\n \t\/\/ Identify element that will be changed\n \tunsigned int mutated_index = getRandomElement();\n\n \/\/ Mutate the element\n \tmutateElement(mutated_index);\n }\n\n \/**\n * Apply the crossover operation to the chromosome and the other chromosome provided.\n * This will produce two offspring that are placed in the next generation.\n * *Note, Assumed that the two chromosomes (this and other) are of the same length.\n * @param other The second chromosome involved in the crossover operation\n * @param children The next generation of the population.\n * \n * Note that there are two possible methods to apply this crossover: index inclusive and index exclusive.\n * Currently index inclusive is used, this is where the site where the chromosomes are crossed over is\n * included in the crossover. Exclusive is the opposite where the index where the chromosomes are\n * crossed over is not included in the crossover.\n * \n * The crossover will work as:\n * chromosome1 = l1 + r1\n * chromosome2 = l2 + r2\n * after the crossover:\n * chromosome1 = l1 + r2\n * chromosome2 = l2 + r1\n * Where l1 and l2 are subsets of the chromosome = chromosome[0..crossover_site-1] for each respective chromosome\n * and r1 and r2 are subsets of the chromosome = chromosome[crossover_site..chromosome.size()-1] for each respective chromosome.\n *\/\n void crossover(Chromosome<T > &other, std::vector<Chromosome<T > > &children) {\n \t\/\/ Copy value to the next population\n \tclonning(children);\n \t\/\/ Copy other to the next population\n \tother.clonning(children);\n\n \t\/\/ Randomly pick one point (where the cross over starts)\n \tint crossover_index = getRandomElement(7);\n\n \t\/\/ Using the index inclusive approach\n \t\/\/ First gets l1 + r2 and second gets l2 + r1\n \t\/\/ Note this approach does not work if crossover_index == 0\n \tstd::swap_ranges((*(children.end()-2)).chromosome.begin()+crossover_index, (*(children.end()-2)).chromosome.end(), (*(children.end()-1)).chromosome.begin()+crossover_index);\n\n \t\/\/ Alternative exclusive index approach\n \t\/\/ Note this approach does not work if crossover_index == 7, also this has been adjusted to hopefully work but has not been tested.\n \t\/\/std::swap_ranges((*(children.end()-2)).begin(), (*(children.end()-2)).begin()+(chromosome.size()-1-crossover_index)+1, (*(children.end()-1)).rbegin()+(chromosome.size()-1-crossover_index));\n\n }\n\n \/**\n * Copy the chromosome to the next generation.\n * @param children The next generation.\n *\/\n void clonning(std::vector<Chromosome<T > > &children) {\n \t\/\/ Copy value to the next population\n \tchildren.push_back(*this);\n }\n\n \/**\n * Overload the array operator.\n * @param n The index to retrieve the value at.\n * @return The value.\n *\/\n T operator[](unsigned int n) const {\n \treturn *this->chromosome[n];\n }\n\n \/**\n * Overload the array operator\n * @param n The index to retrieve the value at.\n * @return The reference to the value.\n *\/\n T& operator[](unsigned int n) {\n\t\treturn this->chromosome[n];\n\t}\n\n \/**\n * Overload the == operation.\n * @param other The Chromosome to compare too.\n * @return Whether the two chromosomes are the same.\n *\/\n inline bool operator==(const Chromosome<T >& other){ return this->chromosome == other.chromosome; }\n\n \/**\n * Overload the != operation, makes use of == operator overload\n * @param other The chromosome to check equality.\n * @return Whether the two chromosomes are different.\n *\/\n inline bool operator!=(const Chromosome<T >& other){ return !(*this == other); }\n\nprivate:\n\n \/**\n * Get a random index to allow for the retrieval a random element within the chromosome.\n * @return The random index.\n *\/\n unsigned int getRandomElement() {\n \treturn rand_chrom_elem(random_engine);\n }\n\n\t\/**\n\t * Get a random number between 0 and chromosome.size()-1 that is not index\n\t * @param index The only value within the range that the return cannot be.\n\t * @return A number within the defined range that is not index.\n\t *\/\n\tunsigned int getRandomElement(unsigned int index) {\n\t\tunsigned int val = getRandomElement();\n\n\t\twhile(val == index) {\n\t\t\tval = getRandomElement();\n\t\t}\n\t\treturn val;\n\t}\n\n\t\/**\n\t * Mutate the given element within the chromosome\n\t * @param mutated_index The index of the element within the chromosome that will be mutated.\n\t *\/\n void mutateElement(unsigned int mutated_index) {\n\n\t\/\/ Could check if it is none primitive and call an expected function\n\t\/\/ Aka all 'data' types that are passed (that are not bool or int) are a child of a abstract class Gene\n\t\/\/ This will define a abstract accessor methods static method Gene::randomElement(Gene)\n\t\/\/ And potential other types of data members.\n \t\/\/ Apply mutation operation to the chromosome\n \tif(std::is_same<T, bool>::value) {\n \t\t\/\/ Flip the bit\n \t\tthis->chromosome[mutated_index] = !this->chromosome[mutated_index];\n \t} else { \n \t\t\/\/ This will really only works for 'primitive types'\n \t\t\/\/ Choose a random number within the range\n \t\tthis->chromosome[mutated_index] = getRandomValue(this->chromosome[mutated_index]);\n \t}\n }\n\n \/**\n * Generate a random chromosome.\n *\/\n void randChromosome() {\n\t\tfor(unsigned int i = 0; i < chromosome.size(); i++) {\n\t\t\tchromosome[i] = getRandomValue();\n\t\t}\n }\n\n \/**\n * Generate a random value for a chromosome element.\n * @return\n *\/\n T getRandomValue() {\n \treturn rand_value(random_engine);\n }\n\n \/**\n * Generate a random value for the chromosome element that is not\n * equal to the one provided.\n * @param prev The value for which the return will not be equal to.\n * @return The random value for the chromosome element that is not\n * equal to prev.\n *\/\n T getRandomValue(T prev) {\n T val = getRandomValue();\n\n while(val == prev) {\n val = getRandomValue();\n }\n return val;\n }\n\n};\n\ntemplate<class T>\nstd::mt19937 Chromosome<T >::random_engine;\ntemplate<class T>\nstd::uniform_int_distribution<int > Chromosome<T >::rand_chrom_elem;\ntemplate<class T>\nstd::uniform_int_distribution<int > Chromosome<T >::rand_value;\n\n#endif \/* CHROMOSOME_HPP_ *\/\n<commit_msg>FIXED: crossover, 0 is not a valid index<commit_after>\n#ifndef CHROMOSOME_HPP_\n#define CHROMOSOME_HPP_\n\n#include <vector>\t \/\/ vector\n#include <algorithm> \/\/ swap_ranges\n#include <random> \/\/ mt19937, uniform_int_distribution, random_device\n\n#define MINIMUM_NUMBER 0\n\ntemplate <class T>\nclass Chromosome {\n\nprotected:\n std::vector<T > chromosome;\n\n \/\/ random number generator values.\n static std::mt19937 random_engine;\n static std::uniform_int_distribution<int > rand_chrom_elem;\n \/\/ This only works with integer values\n static std::uniform_int_distribution<int > rand_value;\n\n\npublic:\n \n \/**\n * Default contructor to allow for easier creation.\n *\/\n Chromosome() {\n\n }\n\n \/**\n * Create a chromosome of the given size\n * @param chromosome_size The size of the chromosome.\n *\/\n Chromosome(unsigned int chromosome_size) : chromosome(chromosome_size){\n }\n\n ~Chromosome() {\n\n }\n\n \/**\n * Create a chromosome of the given size\n * @param chromosome_size The size of the chromosome.\n *\/\n Chromosome(std::vector<T > chromosome) {\n \tthis->chromosome = chromosome;\n }\n\n \/**\n * Initialize the population to random values. This only needs to be called on\n * the first generation during setup.\n * @param population The output population, note this will be cleared of any\n * existing values.\n * @param population_size The size of the population.\n * @param chromosome_size The size of the chromosomes within the population.\n *\/\n static void initPopulation(std::vector<Chromosome<T > > &population,\n \t\tunsigned int population_size, unsigned int chromosome_size) {\n \tpopulation.clear();\n \tfor(unsigned int i = 0; i < population_size; i++) {\n \t\tChromosome<T > chrom (chromosome_size);\n \t\tchrom.randChromosome();\n \t\tpopulation.push_back(chrom);\n \t}\n }\n\n \/**\n * Set up the random number generator engines to allow within the defined ranges.\n * @param chromosome_size The size of the chromosome.\n * @param min_chromosome_value The minimum value of a chromosome element.\n * @param max_chromosome_value The maximum value of a chromosome element.\n *\/\n static void initialize(unsigned int chromosome_size, T min_chromosome_value, T max_chromosome_value) {\n\n\t\t\/\/ Set up the random number generator engines.\n\t\tstd::random_device rd;\n\t\trandom_engine = std::mt19937 (rd());\n\t\trand_chrom_elem = std::uniform_int_distribution<int> (MINIMUM_NUMBER, chromosome_size - 1);\n\t\trand_value = std::uniform_int_distribution<int > (min_chromosome_value, max_chromosome_value);\n }\n\n \/**\n * Apply the mutation operation to the chromosome and put it into the next generation.\n * @param children The next generation of chromosomes (the next population) that is currently being bread.\n *\/\n void mutate() {\n \t\/\/clonning(children);\n\n \t\/\/ Identify element that will be changed\n \tunsigned int mutated_index = getRandomElement();\n\n \/\/ Mutate the element\n \tmutateElement(mutated_index);\n }\n\n \/**\n * Apply the crossover operation to the chromosome and the other chromosome provided.\n * This will produce two offspring that are placed in the next generation.\n * *Note, Assumed that the two chromosomes (this and other) are of the same length.\n * @param other The second chromosome involved in the crossover operation\n * @param children The next generation of the population.\n * \n * Note that there are two possible methods to apply this crossover: index inclusive and index exclusive.\n * Currently index inclusive is used, this is where the site where the chromosomes are crossed over is\n * included in the crossover. Exclusive is the opposite where the index where the chromosomes are\n * crossed over is not included in the crossover.\n * \n * The crossover will work as:\n * chromosome1 = l1 + r1\n * chromosome2 = l2 + r2\n * after the crossover:\n * chromosome1 = l1 + r2\n * chromosome2 = l2 + r1\n * Where l1 and l2 are subsets of the chromosome = chromosome[0..crossover_site-1] for each respective chromosome\n * and r1 and r2 are subsets of the chromosome = chromosome[crossover_site..chromosome.size()-1] for each respective chromosome.\n *\/\n void crossover(Chromosome<T > &other, std::vector<Chromosome<T > > &children) {\n \t\/\/ Copy value to the next population\n \tclonning(children);\n \t\/\/ Copy other to the next population\n \tother.clonning(children);\n\n \t\/\/ Randomly pick one point (where the cross over starts)\n \tint crossover_index = getRandomElement(0);\n\n \t\/\/ Using the index inclusive approach\n \t\/\/ First gets l1 + r2 and second gets l2 + r1\n \t\/\/ Note this approach does not work if crossover_index == 0\n \tstd::swap_ranges((*(children.end()-2)).chromosome.begin()+crossover_index, (*(children.end()-2)).chromosome.end(), (*(children.end()-1)).chromosome.begin()+crossover_index);\n\n \t\/\/ Alternative exclusive index approach\n \t\/\/ Note this approach does not work if crossover_index == 7, also this has been adjusted to hopefully work but has not been tested.\n \t\/\/std::swap_ranges((*(children.end()-2)).begin(), (*(children.end()-2)).begin()+(chromosome.size()-1-crossover_index)+1, (*(children.end()-1)).rbegin()+(chromosome.size()-1-crossover_index));\n\n }\n\n \/**\n * Copy the chromosome to the next generation.\n * @param children The next generation.\n *\/\n void clonning(std::vector<Chromosome<T > > &children) {\n \t\/\/ Copy value to the next population\n \tchildren.push_back(*this);\n }\n\n \/**\n * Overload the array operator.\n * @param n The index to retrieve the value at.\n * @return The value.\n *\/\n T operator[](unsigned int n) const {\n \treturn *this->chromosome[n];\n }\n\n \/**\n * Get the size of the chromosome\n * @return\n *\/\n\tunsigned int size() {\n\t\treturn this->chromosome.size();\n\t}\n\n \/**\n * Overload the array operator\n * @param n The index to retrieve the value at.\n * @return The reference to the value.\n *\/\n T& operator[](unsigned int n) {\n\t\treturn this->chromosome[n];\n\t}\n\n \/**\n * Overload the == operation.\n * @param other The Chromosome to compare too.\n * @return Whether the two chromosomes are the same.\n *\/\n inline bool operator==(const Chromosome<T >& other){ return this->chromosome == other.chromosome; }\n\n \/**\n * Overload the != operation, makes use of == operator overload\n * @param other The chromosome to check equality.\n * @return Whether the two chromosomes are different.\n *\/\n inline bool operator!=(const Chromosome<T >& other){ return !(*this == other); }\n\nprivate:\n\n \/**\n * Get a random index to allow for the retrieval a random element within the chromosome.\n * @return The random index.\n *\/\n unsigned int getRandomElement() {\n \treturn rand_chrom_elem(random_engine);\n }\n\n\t\/**\n\t * Get a random number between 0 and chromosome.size()-1 that is not index\n\t * @param index The only value within the range that the return cannot be.\n\t * @return A number within the defined range that is not index.\n\t *\/\n\tunsigned int getRandomElement(unsigned int index) {\n\t\tunsigned int val = getRandomElement();\n\n\t\twhile(val == index) {\n\t\t\tval = getRandomElement();\n\t\t}\n\t\treturn val;\n\t}\n\n\t\/**\n\t * Mutate the given element within the chromosome\n\t * @param mutated_index The index of the element within the chromosome that will be mutated.\n\t *\/\n void mutateElement(unsigned int mutated_index) {\n\n\t\/\/ Could check if it is none primitive and call an expected function\n\t\/\/ Aka all 'data' types that are passed (that are not bool or int) are a child of a abstract class Gene\n\t\/\/ This will define a abstract accessor methods static method Gene::randomElement(Gene)\n\t\/\/ And potential other types of data members.\n \t\/\/ Apply mutation operation to the chromosome\n \tif(std::is_same<T, bool>::value) {\n \t\t\/\/ Flip the bit\n \t\tthis->chromosome[mutated_index] = !this->chromosome[mutated_index];\n \t} else { \n \t\t\/\/ This will really only works for 'primitive types'\n \t\t\/\/ Choose a random number within the range\n \t\tthis->chromosome[mutated_index] = getRandomValue(this->chromosome[mutated_index]);\n \t}\n }\n\n \/**\n * Generate a random chromosome.\n *\/\n void randChromosome() {\n\t\tfor(unsigned int i = 0; i < chromosome.size(); i++) {\n\t\t\tchromosome[i] = getRandomValue();\n\t\t}\n }\n\n \/**\n * Generate a random value for a chromosome element.\n * @return\n *\/\n T getRandomValue() {\n \treturn rand_value(random_engine);\n }\n\n \/**\n * Generate a random value for the chromosome element that is not\n * equal to the one provided.\n * @param prev The value for which the return will not be equal to.\n * @return The random value for the chromosome element that is not\n * equal to prev.\n *\/\n T getRandomValue(T prev) {\n T val = getRandomValue();\n\n while(val == prev) {\n val = getRandomValue();\n }\n return val;\n }\n\n};\n\ntemplate<class T>\nstd::mt19937 Chromosome<T >::random_engine;\ntemplate<class T>\nstd::uniform_int_distribution<int > Chromosome<T >::rand_chrom_elem;\ntemplate<class T>\nstd::uniform_int_distribution<int > Chromosome<T >::rand_value;\n\n#endif \/* CHROMOSOME_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"envoy\/config\/bootstrap\/v3\/bootstrap.pb.h\"\n#include \"envoy\/config\/cluster\/v3\/cluster.pb.h\"\n#include \"envoy\/config\/common\/key_value\/v3\/config.pb.validate.h\"\n#include \"envoy\/extensions\/filters\/network\/http_connection_manager\/v3\/http_connection_manager.pb.h\"\n#include \"envoy\/extensions\/key_value\/file_based\/v3\/config.pb.h\"\n#include \"envoy\/extensions\/transport_sockets\/tls\/v3\/cert.pb.h\"\n\n#include \"source\/extensions\/transport_sockets\/tls\/context_config_impl.h\"\n#include \"source\/extensions\/transport_sockets\/tls\/ssl_socket.h\"\n\n#include \"test\/integration\/http_integration.h\"\n#include \"test\/integration\/http_protocol_integration.h\"\n#include \"test\/integration\/ssl_utility.h\"\n\nnamespace Envoy {\nnamespace {\n\n#ifdef ENVOY_ENABLE_QUIC\n\nclass FilterIntegrationTest : public HttpProtocolIntegrationTest {\nprotected:\n void initialize() override {\n const std::string filename = TestEnvironment::temporaryPath(\"alt_svc_cache.txt\");\n envoy::config::core::v3::AlternateProtocolsCacheOptions alt_cache;\n alt_cache.set_name(\"default_alternate_protocols_cache\");\n envoy::extensions::key_value::file_based::v3::FileBasedKeyValueStoreConfig config;\n config.set_filename(filename);\n envoy::config::common::key_value::v3::KeyValueStoreConfig kv_config;\n kv_config.mutable_config()->set_name(\"envoy.key_value.file_based\");\n kv_config.mutable_config()->mutable_typed_config()->PackFrom(config);\n alt_cache.mutable_key_value_store_config()->set_name(\"envoy.common.key_value\");\n alt_cache.mutable_key_value_store_config()->mutable_typed_config()->PackFrom(kv_config);\n\n const std::string filter = fmt::format(R\"EOF(\nname: alternate_protocols_cache\ntyped_config:\n \"@type\": type.googleapis.com\/envoy.extensions.filters.http.alternate_protocols_cache.v3.FilterConfig\n alternate_protocols_cache_options:\n name: default_alternate_protocols_cache\n key_value_store_config:\n name: \"envoy.common.key_value\"\n typed_config:\n \"@type\": type.googleapis.com\/envoy.config.common.key_value.v3.KeyValueStoreConfig\n config:\n name: envoy.key_value.file_based\n typed_config:\n \"@type\": type.googleapis.com\/envoy.extensions.key_value.file_based.v3.FileBasedKeyValueStoreConfig\n filename: {}\n\n)EOF\",\n filename);\n config_helper_.prependFilter(filter);\n\n upstream_tls_ = true;\n config_helper_.configureUpstreamTls(\/*use_alpn=*\/true, \/*http3=*\/true, alt_cache);\n\n HttpProtocolIntegrationTest::initialize();\n }\n\n void createUpstreams() override {\n \/\/ The integration test infrastructure does not know how to create mixed protocol upstreams.\n \/\/ It will have created an HTTP\/3 upstream, so the test needs to create an additional\n \/\/ HTTP\/2 upstream manually.\n ASSERT_EQ(upstreamProtocol(), Http::CodecType::HTTP3);\n ASSERT_EQ(fake_upstreams_count_, 1);\n ASSERT_FALSE(autonomous_upstream_);\n\n auto config = configWithType(Http::CodecType::HTTP2);\n Network::TransportSocketFactoryPtr factory = createUpstreamTlsContext(config);\n addFakeUpstream(std::move(factory), Http::CodecType::HTTP2);\n }\n};\n\nTEST_P(FilterIntegrationTest, AltSvc) {\n const uint64_t request_size = 0;\n const uint64_t response_size = 0;\n const std::chrono::milliseconds timeout = TestUtility::DefaultTimeout;\n\n initialize();\n codec_client_ = makeHttpConnection(makeClientConnection((lookupPort(\"http\"))));\n\n Http::TestRequestHeaderMapImpl request_headers{\n {\":method\", \"POST\"}, {\":path\", \"\/test\/long\/url\"}, {\":scheme\", \"http\"},\n {\":authority\", \"host\"}, {\"x-lyft-user-id\", \"123\"}, {\"x-forwarded-for\", \"10.0.0.1\"}};\n int port = fake_upstreams_[0]->localAddress()->ip()->port();\n std::string alt_svc = absl::StrCat(\"h3=\\\":\", port, \"\\\"; ma=86400\");\n Http::TestResponseHeaderMapImpl response_headers{{\":status\", \"200\"}, {\"alt-svc\", alt_svc}};\n\n \/\/ First request should go out over HTTP\/2. The response includes an Alt-Svc header.\n auto response = sendRequestAndWaitForResponse(request_headers, request_size, response_headers,\n response_size, 0, timeout);\n checkSimpleRequestSuccess(request_size, response_size, response.get());\n test_server_->waitForCounterEq(\"cluster.cluster_0.upstream_cx_http2_total\", 1);\n\n \/\/ Second request should go out over HTTP\/3 because of the Alt-Svc information.\n auto response2 = sendRequestAndWaitForResponse(request_headers, request_size, response_headers,\n response_size, 0, timeout);\n checkSimpleRequestSuccess(request_size, response_size, response2.get());\n test_server_->waitForCounterEq(\"cluster.cluster_0.upstream_cx_http3_total\", 1);\n}\n\nINSTANTIATE_TEST_SUITE_P(Protocols, FilterIntegrationTest,\n testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(\n {Http::CodecType::HTTP2}, {Http::CodecType::HTTP3})),\n HttpProtocolIntegrationTest::protocolTestParamsToString);\n\nclass MixedUpstreamIntegrationTest : public FilterIntegrationTest {\nprotected:\n void writeFile() {\n const std::string filename = TestEnvironment::temporaryPath(\"alt_svc_cache.txt\");\n \/\/ There's no hostname here because we're not doing dynamic forward proxying so we infer the\n \/\/ hostname from the config (which does not set it)\n uint32_t port = fake_upstreams_[0]->localAddress()->ip()->port();\n std::string key = absl::StrCat(\"https:\/\/:\", port);\n\n size_t seconds = std::chrono::duration_cast<std::chrono::seconds>(\n timeSystem().monotonicTime().time_since_epoch())\n .count();\n std::string value = absl::StrCat(\"h3=\\\":\", port, \"\\\"; ma=\", 86400 + seconds);\n TestEnvironment::writeStringToFileForTest(\n \"alt_svc_cache.txt\", absl::StrCat(key.length(), \"\\n\", key, value.length(), \"\\n\", value));\n }\n\n void createUpstreams() override {\n ASSERT_EQ(upstreamProtocol(), Http::CodecType::HTTP3);\n ASSERT_EQ(fake_upstreams_count_, 1);\n ASSERT_FALSE(autonomous_upstream_);\n\n if (use_http2_) {\n auto config = configWithType(Http::CodecType::HTTP2);\n Network::TransportSocketFactoryPtr factory = createUpstreamTlsContext(config);\n addFakeUpstream(std::move(factory), Http::CodecType::HTTP2);\n } else {\n auto config = configWithType(Http::CodecType::HTTP3);\n Network::TransportSocketFactoryPtr factory = createUpstreamTlsContext(config);\n addFakeUpstream(std::move(factory), Http::CodecType::HTTP3);\n writeFile();\n }\n }\n\n bool use_http2_{false};\n};\n\nTEST_P(MixedUpstreamIntegrationTest, BasicRequestAutoWithHttp3) {\n testRouterRequestAndResponseWithBody(0, 0, false);\n}\n\nTEST_P(MixedUpstreamIntegrationTest, SimultaneousRequestsAutoWithHttp3) {\n simultaneousRequest(1024, 512, 1023, 513);\n}\n\nTEST_P(MixedUpstreamIntegrationTest, SimultaneousLargeRequestsAutoWithHttp3) {\n config_helper_.setBufferLimits(1024, 1024); \/\/ Set buffer limits upstream and downstream.\n simultaneousRequest(1024 * 20, 1024 * 14 + 2, 1024 * 10 + 5, 1024 * 16);\n}\n\nTEST_P(MixedUpstreamIntegrationTest, BasicRequestAutoWithHttp2) {\n use_http2_ = true;\n testRouterRequestAndResponseWithBody(0, 0, false);\n}\n\nTEST_P(MixedUpstreamIntegrationTest, SimultaneousRequestsAutoWithHttp2) {\n use_http2_ = true;\n simultaneousRequest(1024, 512, 1023, 513);\n}\n\nTEST_P(MixedUpstreamIntegrationTest, SimultaneousLargeRequestsAutoWithHttp2) {\n use_http2_ = true;\n config_helper_.setBufferLimits(1024, 1024); \/\/ Set buffer limits upstream and downstream.\n simultaneousRequest(1024 * 20, 1024 * 14 + 2, 1024 * 10 + 5, 1024 * 16);\n}\n\nINSTANTIATE_TEST_SUITE_P(Protocols, MixedUpstreamIntegrationTest,\n testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(\n {Http::CodecType::HTTP2}, {Http::CodecType::HTTP3})),\n HttpProtocolIntegrationTest::protocolTestParamsToString);\n\n#endif\n\n} \/\/ namespace\n} \/\/ namespace Envoy\n<commit_msg>http3: test fix (#19409)<commit_after>#include \"envoy\/config\/bootstrap\/v3\/bootstrap.pb.h\"\n#include \"envoy\/config\/cluster\/v3\/cluster.pb.h\"\n#include \"envoy\/config\/common\/key_value\/v3\/config.pb.validate.h\"\n#include \"envoy\/extensions\/filters\/network\/http_connection_manager\/v3\/http_connection_manager.pb.h\"\n#include \"envoy\/extensions\/key_value\/file_based\/v3\/config.pb.h\"\n#include \"envoy\/extensions\/transport_sockets\/tls\/v3\/cert.pb.h\"\n\n#include \"source\/extensions\/transport_sockets\/tls\/context_config_impl.h\"\n#include \"source\/extensions\/transport_sockets\/tls\/ssl_socket.h\"\n\n#include \"test\/integration\/http_integration.h\"\n#include \"test\/integration\/http_protocol_integration.h\"\n#include \"test\/integration\/ssl_utility.h\"\n\nnamespace Envoy {\nnamespace {\n\n#ifdef ENVOY_ENABLE_QUIC\n\n\/\/ This tests the alternative service filter getting updated, by creating both\n\/\/ HTTP\/2 and HTTP\/3 upstreams, and having the HTTP\/2 upstream direct Envoy to\n\/\/ the HTTP\/3 upstream using alt-svc response headers.\nclass FilterIntegrationTest : public HttpProtocolIntegrationTest {\nprotected:\n void initialize() override {\n const std::string filename = TestEnvironment::temporaryPath(\"alt_svc_cache.txt\");\n envoy::config::core::v3::AlternateProtocolsCacheOptions alt_cache;\n alt_cache.set_name(\"default_alternate_protocols_cache\");\n envoy::extensions::key_value::file_based::v3::FileBasedKeyValueStoreConfig config;\n config.set_filename(filename);\n envoy::config::common::key_value::v3::KeyValueStoreConfig kv_config;\n kv_config.mutable_config()->set_name(\"envoy.key_value.file_based\");\n kv_config.mutable_config()->mutable_typed_config()->PackFrom(config);\n alt_cache.mutable_key_value_store_config()->set_name(\"envoy.common.key_value\");\n alt_cache.mutable_key_value_store_config()->mutable_typed_config()->PackFrom(kv_config);\n\n const std::string filter = fmt::format(R\"EOF(\nname: alternate_protocols_cache\ntyped_config:\n \"@type\": type.googleapis.com\/envoy.extensions.filters.http.alternate_protocols_cache.v3.FilterConfig\n alternate_protocols_cache_options:\n name: default_alternate_protocols_cache\n key_value_store_config:\n name: \"envoy.common.key_value\"\n typed_config:\n \"@type\": type.googleapis.com\/envoy.config.common.key_value.v3.KeyValueStoreConfig\n config:\n name: envoy.key_value.file_based\n typed_config:\n \"@type\": type.googleapis.com\/envoy.extensions.key_value.file_based.v3.FileBasedKeyValueStoreConfig\n filename: {}\n\n)EOF\",\n filename);\n config_helper_.prependFilter(filter);\n\n upstream_tls_ = true;\n \/\/ This configures the upstream to use the connection grid (automatically\n \/\/ selecting protocol and allowing HTTP\/3)\n config_helper_.configureUpstreamTls(\/*use_alpn=*\/true, \/*http3=*\/true, alt_cache);\n\n HttpProtocolIntegrationTest::initialize();\n }\n\n \/\/ This function will create 2 upstreams, but Envoy will only point at the\n \/\/ first, the HTTP\/2 upstream.\n void createUpstreams() override {\n \/\/ The test is configured for one upstream (Envoy will only point to the HTTP\/2 upstream) but\n \/\/ we create two. Tell the test framework this is intentional.\n skipPortUsageValidation();\n ASSERT_FALSE(autonomous_upstream_);\n\n \/\/ Until alt-svc supports different ports, try to get a TCP and UDP fake upstream on the same\n \/\/ port.\n for (int i = 0; i < 10; ++i) {\n TRY_ASSERT_MAIN_THREAD {\n \/\/ Make the first upstream HTTP\/2\n auto http2_config = configWithType(Http::CodecType::HTTP2);\n Network::TransportSocketFactoryPtr http2_factory = createUpstreamTlsContext(http2_config);\n addFakeUpstream(std::move(http2_factory), Http::CodecType::HTTP2);\n\n \/\/ Make the next upstream is HTTP\/3\n auto http3_config = configWithType(Http::CodecType::HTTP3);\n Network::TransportSocketFactoryPtr http3_factory = createUpstreamTlsContext(http3_config);\n \/\/ If the UDP port is in use, this will throw an exception and get caught below.\n fake_upstreams_.emplace_back(std::make_unique<FakeUpstream>(\n std::move(http3_factory), fake_upstreams_[0]->localAddress()->ip()->port(), version_,\n http3_config));\n return;\n }\n END_TRY\n catch (const EnvoyException& e) {\n fake_upstreams_.clear();\n ENVOY_LOG_MISC(warn, \"Failed to use port {}\",\n fake_upstreams_[0]->localAddress()->ip()->port());\n }\n }\n throw EnvoyException(\"Failed to find a port after 10 tries\");\n }\n};\n\nTEST_P(FilterIntegrationTest, AltSvc) {\n const uint64_t request_size = 0;\n const uint64_t response_size = 0;\n const std::chrono::milliseconds timeout = TestUtility::DefaultTimeout;\n\n initialize();\n codec_client_ = makeHttpConnection(makeClientConnection((lookupPort(\"http\"))));\n\n Http::TestRequestHeaderMapImpl request_headers{\n {\":method\", \"POST\"}, {\":path\", \"\/test\/long\/url\"}, {\":scheme\", \"http\"},\n {\":authority\", \"host\"}, {\"x-lyft-user-id\", \"123\"}, {\"x-forwarded-for\", \"10.0.0.1\"}};\n int port = fake_upstreams_[1]->localAddress()->ip()->port();\n std::string alt_svc = absl::StrCat(\"h3=\\\":\", port, \"\\\"; ma=86400\");\n Http::TestResponseHeaderMapImpl response_headers{{\":status\", \"200\"}, {\"alt-svc\", alt_svc}};\n\n \/\/ First request should go out over HTTP\/2 (upstream index 0). The response includes an\n \/\/ Alt-Svc header.\n auto response = sendRequestAndWaitForResponse(request_headers, request_size, response_headers,\n response_size, 0, timeout);\n checkSimpleRequestSuccess(request_size, response_size, response.get());\n\n \/\/ Close the connection so the HTTP\/2 connection will not be used.\n test_server_->waitForCounterEq(\"cluster.cluster_0.upstream_cx_http2_total\", 1);\n ASSERT_TRUE(fake_upstream_connection_->close());\n test_server_->waitForCounterEq(\"cluster.cluster_0.upstream_cx_destroy\", 1);\n fake_upstream_connection_.reset();\n\n \/\/ Second request should go out over HTTP\/3 (upstream index 1) because of the Alt-Svc information.\n \/\/ This could arguably flake due to the race, at which point request #2 should go to {0, 1}\n \/\/ but for now it seems to pass.\n auto response2 = sendRequestAndWaitForResponse(request_headers, request_size, response_headers,\n response_size, 1, timeout);\n checkSimpleRequestSuccess(request_size, response_size, response2.get());\n test_server_->waitForCounterEq(\"cluster.cluster_0.upstream_cx_http3_total\", 1);\n}\n\nINSTANTIATE_TEST_SUITE_P(Protocols, FilterIntegrationTest,\n testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(\n {Http::CodecType::HTTP2}, {Http::CodecType::HTTP3})),\n HttpProtocolIntegrationTest::protocolTestParamsToString);\n\n\/\/ This tests the connection grid with pre-populated alt-svc entries, and either\n\/\/ an HTTP\/2 or an HTTP\/3 upstream (but not both).\nclass MixedUpstreamIntegrationTest : public FilterIntegrationTest {\nprotected:\n void writeFile() {\n const std::string filename = TestEnvironment::temporaryPath(\"alt_svc_cache.txt\");\n \/\/ There's no hostname here because we're not doing dynamic forward proxying so we infer the\n \/\/ hostname from the config (which does not set it)\n uint32_t port = fake_upstreams_[0]->localAddress()->ip()->port();\n std::string key = absl::StrCat(\"https:\/\/:\", port);\n\n size_t seconds = std::chrono::duration_cast<std::chrono::seconds>(\n timeSystem().monotonicTime().time_since_epoch())\n .count();\n std::string value = absl::StrCat(\"h3=\\\":\", port, \"\\\"; ma=\", 86400 + seconds);\n TestEnvironment::writeStringToFileForTest(\n \"alt_svc_cache.txt\", absl::StrCat(key.length(), \"\\n\", key, value.length(), \"\\n\", value));\n }\n\n void createUpstreams() override {\n ASSERT_EQ(upstreamProtocol(), Http::CodecType::HTTP3);\n ASSERT_EQ(fake_upstreams_count_, 1);\n ASSERT_FALSE(autonomous_upstream_);\n\n if (use_http2_) {\n auto config = configWithType(Http::CodecType::HTTP2);\n Network::TransportSocketFactoryPtr factory = createUpstreamTlsContext(config);\n addFakeUpstream(std::move(factory), Http::CodecType::HTTP2);\n } else {\n auto config = configWithType(Http::CodecType::HTTP3);\n Network::TransportSocketFactoryPtr factory = createUpstreamTlsContext(config);\n addFakeUpstream(std::move(factory), Http::CodecType::HTTP3);\n writeFile();\n }\n }\n\n bool use_http2_{false};\n};\n\n\/\/ Test auto-config with a pre-populated HTTP\/3 alt-svc entry. The upstream request will\n\/\/ occur over HTTP\/3.\nTEST_P(MixedUpstreamIntegrationTest, BasicRequestAutoWithHttp3) {\n testRouterRequestAndResponseWithBody(0, 0, false);\n}\n\n\/\/ Test simultaneous requests using auto-config and a pre-populated HTTP\/3 alt-svc entry. The\n\/\/ upstream request will occur over HTTP\/3.\nTEST_P(MixedUpstreamIntegrationTest, SimultaneousRequestsAutoWithHttp3) {\n simultaneousRequest(1024, 512, 1023, 513);\n}\n\n\/\/ Test large simultaneous requests using auto-config and a pre-populated HTTP\/3 alt-svc entry. The\n\/\/ upstream request will occur over HTTP\/3.\nTEST_P(MixedUpstreamIntegrationTest, SimultaneousLargeRequestsAutoWithHttp3) {\n config_helper_.setBufferLimits(1024, 1024); \/\/ Set buffer limits upstream and downstream.\n simultaneousRequest(1024 * 20, 1024 * 14 + 2, 1024 * 10 + 5, 1024 * 16);\n}\n\n\/\/ Test auto-config with a pre-populated HTTP\/3 alt-svc entry. With the HTTP\/3 upstream \"disabled\"\n\/\/ the upstream request will occur over HTTP\/3.\nTEST_P(MixedUpstreamIntegrationTest, BasicRequestAutoWithHttp2) {\n \/\/ Only create an HTTP\/2 upstream.\n use_http2_ = true;\n testRouterRequestAndResponseWithBody(0, 0, false);\n}\n\n\/\/ Same as above, only multiple requests.\nTEST_P(MixedUpstreamIntegrationTest, SimultaneousRequestsAutoWithHttp2) {\n use_http2_ = true;\n simultaneousRequest(1024, 512, 1023, 513);\n}\n\n\/\/ Same as above, only large multiple requests.\nTEST_P(MixedUpstreamIntegrationTest, SimultaneousLargeRequestsAutoWithHttp2) {\n use_http2_ = true;\n config_helper_.setBufferLimits(1024, 1024); \/\/ Set buffer limits upstream and downstream.\n simultaneousRequest(1024 * 20, 1024 * 14 + 2, 1024 * 10 + 5, 1024 * 16);\n}\n\nINSTANTIATE_TEST_SUITE_P(Protocols, MixedUpstreamIntegrationTest,\n testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(\n {Http::CodecType::HTTP2}, {Http::CodecType::HTTP3})),\n HttpProtocolIntegrationTest::protocolTestParamsToString);\n\n#endif\n\n} \/\/ namespace\n} \/\/ namespace Envoy\n<|endoftext|>"} {"text":"<commit_before>#ifndef __SPARSEMATRIX_HPP_INCLUDED\n#define __SPARSEMATRIX_HPP_INCLUDED\n#include <string>\n#include <iostream>\n#include <vector>\n#include <stdio.h>\n#include <fstream> \n#include \"mkl.h\"\n#include \"mkl_pardiso.h\"\n#include \"mkl_types.h\"\n#include <iomanip>\n#include \"math.h\"\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n\n\nusing namespace std;\n\nstruct int_int_dbl\n{\n int I;\n int J;\n double V;\n};\n\nbool myfunction (int i,int j);\n\nclass Matrix{\npublic:\n Matrix();\n Matrix(string );\n void zero_dense(int,int);\n vector < double > val;\n vector < int > i_ptr; \/\/ new MKL_INT[crs->m+1];\n vector < int > j_col; \/\/ new MKL_INT[crs->nnz];\n vector < int > i_coo_cmpr;\n vector < int > l2g_i_coo;\n int format; \/* COO, CSR, DNS *\/\n int symmetric; \/* 0-no, 1-lower triang., 2-upper triang. *\/\n int nnz;\n int n_row;\n int n_row_cmprs;\n int n_col;\n int numel;\n bool DNS_reducedZeroRows;\n bool DNS_transposed;\n\/\/ bool printCooOrDense;\n MKL_INT m;\n \/\/coo row compressed\n\n \/\/csr\n \/\/dns\n vector < double > dense; \/\/ ()\n void mv_csr(const double[], double [] , bool, int);\n void CsrElementByElement();\n void COO2CSR();\n void CSR2COO();\n void CSRorCOO2DNS(bool, bool);\n void dummyFunction(int,int, int, double);\n void DNS2CSR();\n void DNS2COO();\n void compresRows();\n Matrix CreateCopyFrom(const Matrix&);\n static void Acsr_mult_Bdns_is_Cdns(Matrix&, Matrix&, Matrix&);\n void readCooFromFile(string, int,int,int);\n void printToFile(string,int,bool);\n void InitializeSolve();\n void solve(Matrix&, Matrix&);\n void FinalizeSolve(int);\n MKL_INT iparm[64];\n MKL_INT mtype;\n MKL_INT nrhs;\n MKL_INT n;\n void *pt[64];\n MKL_INT maxfct, mnum, phase, error, msglvl;\n static void testPardiso();\n\n};\n#endif\n\n\n\n\n\n<commit_msg>migration of variable in file<commit_after>#ifndef __SPARSEMATRIX_HPP_INCLUDED\n#define __SPARSEMATRIX_HPP_INCLUDED\n#include <string>\n#include <iostream>\n#include <vector>\n#include <stdio.h>\n#include <fstream> \n#include \"mkl.h\"\n#include \"mkl_pardiso.h\"\n#include \"mkl_types.h\"\n#include <iomanip>\n#include \"math.h\"\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n\n\nusing namespace std;\n\nstruct int_int_dbl\n{\n int I;\n int J;\n double V;\n};\n\nbool myfunction (int i,int j);\n\nclass Matrix{\npublic:\n Matrix();\n Matrix(string );\n void zero_dense(int,int);\n vector < double > val;\n vector < int > i_ptr; \/\/ new MKL_INT[crs->m+1];\n vector < int > j_col; \/\/ new MKL_INT[crs->nnz];\n vector < int > i_coo_cmpr;\n vector < int > l2g_i_coo;\n vector < double > dense;\n int format; \/* COO, CSR, DNS *\/\n int symmetric; \/* 0-no, 1-lower triang., 2-upper triang. *\/\n int nnz;\n int n_row;\n int n_row_cmprs;\n int n_col;\n int numel;\n bool DNS_reducedZeroRows;\n bool DNS_transposed;\n\/\/ bool printCooOrDense;\n MKL_INT m;\n \/\/coo row compressed\n\n \/\/csr\n \/\/dns\n void mv_csr(const double[], double [] , bool, int);\n void CsrElementByElement();\n void COO2CSR();\n void CSR2COO();\n void CSRorCOO2DNS(bool, bool);\n void dummyFunction(int,int, int, double);\n void DNS2CSR();\n void DNS2COO();\n void compresRows();\n Matrix CreateCopyFrom(const Matrix&);\n static void Acsr_mult_Bdns_is_Cdns(Matrix&, Matrix&, Matrix&);\n void readCooFromFile(string, int,int,int);\n void printToFile(string,int,bool);\n void InitializeSolve();\n void solve(Matrix&, Matrix&);\n void FinalizeSolve(int);\n MKL_INT iparm[64];\n MKL_INT mtype;\n MKL_INT nrhs;\n MKL_INT n;\n void *pt[64];\n MKL_INT maxfct, mnum, phase, error, msglvl;\n static void testPardiso();\n\n};\n#endif\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014, webvariants GmbH, http:\/\/www.webvariants.de\n *\n * This file is released under the terms of the MIT license. You can find the\n * complete text in the attached LICENSE file or online at:\n *\n * http:\/\/www.opensource.org\/licenses\/mit-license.php\n *\n * @author: Tino Rusch (tino.rusch@webvariants.de), Thomas Krause (thomas.krause@webvariants.de)\n *\/\n\n#include \"webstack\/WebSocketRequestHandler.h\"\n\nSusi::WebSocketRequestHandler::WebSocketRequestHandler( std::shared_ptr<Susi::Api::ApiServerComponent> apiServer ) {\n _apiServer = apiServer;\n}\n\nvoid Susi::WebSocketRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& request,\n Poco::Net::HTTPServerResponse& response ) {\n Susi::Logger::debug( \"in ws handler\" );\n Poco::Net::WebSocket socket( request,response );\n Poco::Net::NameValueCollection cookies;\n request.getCookies( cookies );\n std::string id = cookies[\"susisession\"];\n Susi::Logger::debug( \"register sender in ws\" );\n _apiServer->registerSender( id,[&socket]( Susi::Util::Any & arg ) {\n std::string msg = arg.toJSONString();\n Susi::Logger::debug( \"send frame to websocket\" );\n socket.sendFrame( msg.data(), msg.length(), Poco::Net::WebSocket::FRAME_TEXT );\n } );\n\n _apiServer->onConnect( id );\n\n char buffer[4096];\n int flags;\n size_t n;\n\n while( true ) {\n n = socket.receiveFrame( buffer, sizeof( buffer ), flags );\n Susi::Logger::debug( \"got frame\" );\n Susi::Logger::debug( std::to_string( n ) );\n if( n==0 || ( flags & Poco::Net::WebSocket::FRAME_OP_BITMASK ) == Poco::Net::WebSocket::FRAME_OP_CLOSE ) {\n break;\n }\n std::string str( buffer, n );\n Susi::Util::Any packet = Susi::Util::Any::fromJSONString( str );\n _apiServer->onMessage( id,packet );\n }\n Susi::Logger::debug( \"closing websocket\" );\n _apiServer->onClose( id );\n}\n<commit_msg>[webstack] surrounded ws recv with try catch;<commit_after>\/*\n * Copyright (c) 2014, webvariants GmbH, http:\/\/www.webvariants.de\n *\n * This file is released under the terms of the MIT license. You can find the\n * complete text in the attached LICENSE file or online at:\n *\n * http:\/\/www.opensource.org\/licenses\/mit-license.php\n *\n * @author: Tino Rusch (tino.rusch@webvariants.de), Thomas Krause (thomas.krause@webvariants.de)\n *\/\n\n#include \"webstack\/WebSocketRequestHandler.h\"\n\nSusi::WebSocketRequestHandler::WebSocketRequestHandler( std::shared_ptr<Susi::Api::ApiServerComponent> apiServer ) {\n _apiServer = apiServer;\n}\n\nvoid Susi::WebSocketRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& request,\n Poco::Net::HTTPServerResponse& response ) {\n Susi::Logger::debug( \"in ws handler\" );\n Poco::Net::WebSocket socket( request,response );\n Poco::Net::NameValueCollection cookies;\n request.getCookies( cookies );\n std::string id = cookies[\"susisession\"];\n Susi::Logger::debug( \"register sender in ws\" );\n _apiServer->registerSender( id,[&socket]( Susi::Util::Any & arg ) {\n std::string msg = arg.toJSONString();\n Susi::Logger::debug( \"send frame to websocket\" );\n socket.sendFrame( msg.data(), msg.length(), Poco::Net::WebSocket::FRAME_TEXT );\n } );\n\n _apiServer->onConnect( id );\n\n char buffer[4096];\n int flags;\n size_t n;\n\n while( true ) {\n try{\n n = socket.receiveFrame( buffer, sizeof( buffer ), flags );\n Susi::Logger::debug( \"got frame\" );\n Susi::Logger::debug( std::to_string( n ) );\n if( n==0 || ( flags & Poco::Net::WebSocket::FRAME_OP_BITMASK ) == Poco::Net::WebSocket::FRAME_OP_CLOSE ) {\n break;\n }\n std::string str( buffer, n );\n Susi::Util::Any packet = Susi::Util::Any::fromJSONString( str );\n _apiServer->onMessage( id,packet );\n }catch(const Poco::TimeoutException &){}\n }\n Susi::Logger::debug( \"closing websocket\" );\n _apiServer->onClose( id );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 The Shaderc Authors. All rights reserved.\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 <cassert>\n#include <cctype>\n#include <cstdint>\n#include <cstring>\n#include <iostream>\n#include <list>\n#include <string>\n#include <utility>\n\n#include \"libshaderc_util\/string_piece.h\"\n#include \"spirv-tools\/libspirv.h\"\n\n#include \"file.h\"\n#include \"file_compiler.h\"\n#include \"shader_stage.h\"\n\nusing shaderc_util::string_piece;\n\nnamespace {\n\n\/\/ Prints the help message.\nvoid PrintHelp(std::ostream* out) {\n *out << R\"(glslc - Compile shaders into SPIR-V\n\nUsage: glslc [options] file...\n\nAn input file of - represents standard input.\n\nOptions:\n -c Only run preprocess, compile, and assemble steps.\n -Dmacro[=defn] Add an implicit macro definition.\n -E Outputs only the results of the preprocessing step.\n Output defaults to standard output.\n -fshader-stage=<stage>\n Treat subsequent input files as having stage <stage>.\n Valid stages are vertex, fragment, tesscontrol, tesseval,\n geometry, and compute.\n -g Generate source-level debug information.\n Currently this option has no effect.\n --help Display available options.\n --version Display compiler version information.\n -I <value> Add directory to include search path.\n -o <file> Write output to <file>.\n A file name of '-' represents standard output.\n -std=<value> Version and profile for input files. Possible values\n are concatenations of version and profile, e.g. 310es,\n 450core, etc.\n -M Generate make dependencies. Implies -E and -w.\n -MM An alias for -M.\n -MD Generate make dependencies and compile.\n -MF <file> Write dependency output to the given file.\n -MT <target> Specify the target of the rule emitted by dependency\n generation.\n -S Only run preprocess and compilation steps.\n --target-env=<environment>\n Set the target shader environment, and the semantics\n of warnings and errors. Valid values are 'opengl',\n 'opengl_compat' and 'vulkan'. The default value is 'vulkan'.\n -w Suppresses all warning messages.\n -Werror Treat all warnings as errors.\n -x <language> Treat subsequent input files as having type <language>.\n The only supported language is glsl.\n)\";\n}\n\n\/\/ Gets the option argument for the option at *index in argv in a way consistent\n\/\/ with clang\/gcc. On success, returns true and writes the parsed argument into\n\/\/ *option_argument. Returns false if any errors occur. After calling this\n\/\/ function, *index will the index of the last command line argument consumed.\nbool GetOptionArgument(int argc, char** argv, int* index,\n const std::string& option,\n string_piece* option_argument) {\n const string_piece arg = argv[*index];\n assert(arg.starts_with(option));\n if (arg.size() != option.size()) {\n *option_argument = arg.substr(option.size());\n return true;\n } else {\n if (option.back() == '=') {\n *option_argument = \"\";\n return true;\n }\n if (++(*index) >= argc) return false;\n *option_argument = argv[*index];\n return true;\n }\n}\n\nconst char kBuildVersion[] =\n#include \"build-version.inc\"\n ;\n} \/\/ anonymous namespace\n\nint main(int argc, char** argv) {\n std::vector<std::pair<std::string, shaderc_shader_kind>> input_files;\n shaderc_shader_kind current_fshader_stage = shaderc_glsl_infer_from_source;\n glslc::FileCompiler compiler;\n bool success = true;\n bool has_stdin_input = false;\n\n for (int i = 1; i < argc; ++i) {\n const string_piece arg = argv[i];\n if (arg == \"--help\") {\n ::PrintHelp(&std::cout);\n return 0;\n } else if (arg == \"--version\") {\n std::cout << kBuildVersion << std::endl;\n std::cout << \"Target: SPIR-V \" << SPV_SPIRV_VERSION_MAJOR << \".\"\n << SPV_SPIRV_VERSION_MINOR << \" rev \"\n << SPV_SPIRV_VERSION_REVISION << std::endl;\n return 0;\n } else if (arg.starts_with(\"-o\")) {\n string_piece file_name;\n if (!GetOptionArgument(argc, argv, &i, \"-o\", &file_name)) {\n std::cerr\n << \"glslc: error: argument to '-o' is missing (expected 1 value)\"\n << std::endl;\n return 1;\n }\n compiler.SetOutputFileName(file_name);\n } else if (arg.starts_with(\"-fshader-stage=\")) {\n const string_piece stage = arg.substr(std::strlen(\"-fshader-stage=\"));\n current_fshader_stage = glslc::GetForcedShaderKindFromCmdLine(arg);\n if (current_fshader_stage == shaderc_glsl_infer_from_source) {\n std::cerr << \"glslc: error: stage not recognized: '\" << stage << \"'\"\n << std::endl;\n return 1;\n }\n } else if (arg.starts_with(\"-std=\")) {\n const string_piece standard = arg.substr(std::strlen(\"-std=\"));\n int version;\n shaderc_profile profile;\n if (!shaderc_parse_version_profile(standard.begin(), &version,\n &profile)) {\n std::cerr << \"glslc: error: invalid value '\" << standard\n << \"' in '-std=\" << standard << \"'\" << std::endl;\n return 1;\n }\n compiler.options().SetForcedVersionProfile(version, profile);\n } else if (arg.starts_with(\"--target-env=\")) {\n shaderc_target_env target_env = shaderc_target_env_default;\n const string_piece target_env_str =\n arg.substr(std::strlen(\"--target-env=\"));\n if (target_env_str == \"vulkan\") {\n target_env = shaderc_target_env_vulkan;\n } else if (target_env_str == \"opengl\") {\n target_env = shaderc_target_env_opengl;\n } else if (target_env_str == \"opengl_compat\") {\n target_env = shaderc_target_env_opengl_compat;\n } else {\n std::cerr << \"glslc: error: invalid value '\" << target_env_str\n << \"' in '--target-env=\" << target_env_str << \"'\"\n << std::endl;\n return 1;\n }\n compiler.options().SetTargetEnvironment(target_env, 0);\n } else if (arg.starts_with(\"-x\")) {\n string_piece option_arg;\n if (!GetOptionArgument(argc, argv, &i, \"-x\", &option_arg)) {\n std::cerr\n << \"glslc: error: argument to '-x' is missing (expected 1 value)\"\n << std::endl;\n success = false;\n } else {\n if (option_arg != \"glsl\") {\n std::cerr << \"glslc: error: language not recognized: '\" << option_arg\n << \"'\" << std::endl;\n return 1;\n }\n }\n } else if (arg == \"-c\") {\n compiler.SetIndividualCompilationFlag();\n } else if (arg == \"-E\") {\n compiler.SetPreprocessingOnlyFlag();\n } else if (arg == \"-M\" || arg == \"-MM\") {\n \/\/ -M implies -E and -w\n compiler.SetPreprocessingOnlyFlag();\n compiler.options().SetSuppressWarnings();\n if (compiler.GetDependencyDumpingHandler()->DumpingModeNotSet()) {\n compiler.GetDependencyDumpingHandler()\n ->SetDumpAsNormalCompilationOutput();\n } else {\n std::cerr << \"glslc: error: both -M (or -MM) and -MD are specified. \"\n \"Only one should be used at one time.\"\n << std::endl;\n return 1;\n }\n } else if (arg == \"-MD\") {\n if (compiler.GetDependencyDumpingHandler()->DumpingModeNotSet()) {\n compiler.GetDependencyDumpingHandler()\n ->SetDumpToExtraDependencyInfoFiles();\n } else {\n std::cerr << \"glslc: error: both -M (or -MM) and -MD are specified. \"\n \"Only one should be used at one time.\"\n << std::endl;\n return 1;\n }\n } else if (arg == \"-MF\") {\n string_piece dep_file_name;\n if (!GetOptionArgument(argc, argv, &i, \"-MF\", &dep_file_name)) {\n std::cerr\n << \"glslc: error: missing dependency info filename after '-MF'\"\n << std::endl;\n return 1;\n }\n compiler.GetDependencyDumpingHandler()->SetDependencyFileName(\n std::string(dep_file_name.data(), dep_file_name.size()));\n } else if (arg == \"-MT\") {\n string_piece dep_file_name;\n if (!GetOptionArgument(argc, argv, &i, \"-MT\", &dep_file_name)) {\n std::cerr << \"glslc: error: missing dependency info target after '-MT'\"\n << std::endl;\n return 1;\n }\n compiler.GetDependencyDumpingHandler()->SetTarget(\n std::string(dep_file_name.data(), dep_file_name.size()));\n } else if (arg == \"-S\") {\n compiler.SetDisassemblyFlag();\n } else if (arg.starts_with(\"-D\")) {\n const size_t length = arg.size();\n if (length <= 2) {\n std::cerr << \"glslc: error: argument to '-D' is missing\" << std::endl;\n } else {\n const string_piece argument = arg.substr(2);\n \/\/ Get the exact length of the macro string.\n size_t equal_sign_loc = argument.find_first_of('=');\n size_t name_length = equal_sign_loc != shaderc_util::string_piece::npos\n ? equal_sign_loc\n : argument.size();\n const string_piece name_piece = argument.substr(0, name_length);\n if (name_piece.starts_with(\"GL_\")) {\n std::cerr\n << \"glslc: error: names beginning with 'GL_' cannot be defined: \"\n << arg << std::endl;\n return 1;\n }\n if (name_piece.find(\"__\") != string_piece::npos) {\n std::cerr\n << \"glslc: warning: names containing consecutive underscores \"\n \"are reserved: \"\n << arg << std::endl;\n }\n\n const string_piece value_piece =\n (equal_sign_loc == string_piece::npos ||\n equal_sign_loc == argument.size() - 1)\n ? \"\"\n : argument.substr(name_length + 1);\n \/\/ TODO(deki): check arg for newlines.\n compiler.options().AddMacroDefinition(\n name_piece.data(), name_piece.size(), value_piece.data(),\n value_piece.size());\n }\n } else if (arg.starts_with(\"-I\")) {\n string_piece option_arg;\n if (!GetOptionArgument(argc, argv, &i, \"-I\", &option_arg)) {\n std::cerr\n << \"glslc: error: argument to '-I' is missing (expected 1 value)\"\n << std::endl;\n success = false;\n } else {\n compiler.AddIncludeDirectory(option_arg.str());\n }\n } else if (arg == \"-g\") {\n compiler.options().SetGenerateDebugInfo();\n } else if (arg == \"-w\") {\n compiler.options().SetSuppressWarnings();\n } else if (arg == \"-Werror\") {\n compiler.options().SetWarningsAsErrors();\n } else if (!(arg == \"-\") && arg[0] == '-') {\n std::cerr << \"glslc: error: \"\n << (arg[1] == '-' ? \"unsupported option\" : \"unknown argument\")\n << \": '\" << arg << \"'\" << std::endl;\n return 1;\n } else {\n if (arg == \"-\") {\n if (has_stdin_input) {\n std::cerr << \"glslc: error: specifying standard input \\\"-\\\" as input \"\n << \"more than once is not allowed.\" << std::endl;\n return 1;\n }\n has_stdin_input = true;\n }\n\n \/\/ If current_fshader_stage is shaderc_glsl_infer_from_source, that means\n \/\/ we didn't set forced shader kinds (otherwise an error should have\n \/\/ already been emitted before). So we should deduce the shader kind\n \/\/ from the file name. If current_fshader_stage is specifed to one of\n \/\/ the forced shader kinds, use that for the following compilation.\n input_files.emplace_back(\n arg.str(), current_fshader_stage == shaderc_glsl_infer_from_source\n ? glslc::DeduceDefaultShaderKindFromFileName(arg)\n : current_fshader_stage);\n }\n }\n\n if (!compiler.ValidateOptions(input_files.size())) return 1;\n\n if (!success) return 1;\n\n for (const auto& input_file : input_files) {\n const std::string& name = input_file.first;\n const shaderc_shader_kind stage = input_file.second;\n\n success &= compiler.CompileShaderFile(name, stage);\n }\n\n compiler.OutputMessages();\n return success ? 0 : 1;\n}\n<commit_msg>libspirv.h in SPIRV-Tools removed macros for version and revision.<commit_after>\/\/ Copyright 2015 The Shaderc Authors. All rights reserved.\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 <cassert>\n#include <cctype>\n#include <cstdint>\n#include <cstring>\n#include <iostream>\n#include <list>\n#include <string>\n#include <utility>\n\n#include \"libshaderc_util\/string_piece.h\"\n#include \"spirv-tools\/libspirv.h\"\n\n#include \"file.h\"\n#include \"file_compiler.h\"\n#include \"shader_stage.h\"\n\nusing shaderc_util::string_piece;\n\nnamespace {\n\n\/\/ Prints the help message.\nvoid PrintHelp(std::ostream* out) {\n *out << R\"(glslc - Compile shaders into SPIR-V\n\nUsage: glslc [options] file...\n\nAn input file of - represents standard input.\n\nOptions:\n -c Only run preprocess, compile, and assemble steps.\n -Dmacro[=defn] Add an implicit macro definition.\n -E Outputs only the results of the preprocessing step.\n Output defaults to standard output.\n -fshader-stage=<stage>\n Treat subsequent input files as having stage <stage>.\n Valid stages are vertex, fragment, tesscontrol, tesseval,\n geometry, and compute.\n -g Generate source-level debug information.\n Currently this option has no effect.\n --help Display available options.\n --version Display compiler version information.\n -I <value> Add directory to include search path.\n -o <file> Write output to <file>.\n A file name of '-' represents standard output.\n -std=<value> Version and profile for input files. Possible values\n are concatenations of version and profile, e.g. 310es,\n 450core, etc.\n -M Generate make dependencies. Implies -E and -w.\n -MM An alias for -M.\n -MD Generate make dependencies and compile.\n -MF <file> Write dependency output to the given file.\n -MT <target> Specify the target of the rule emitted by dependency\n generation.\n -S Only run preprocess and compilation steps.\n --target-env=<environment>\n Set the target shader environment, and the semantics\n of warnings and errors. Valid values are 'opengl',\n 'opengl_compat' and 'vulkan'. The default value is 'vulkan'.\n -w Suppresses all warning messages.\n -Werror Treat all warnings as errors.\n -x <language> Treat subsequent input files as having type <language>.\n The only supported language is glsl.\n)\";\n}\n\n\/\/ Gets the option argument for the option at *index in argv in a way consistent\n\/\/ with clang\/gcc. On success, returns true and writes the parsed argument into\n\/\/ *option_argument. Returns false if any errors occur. After calling this\n\/\/ function, *index will the index of the last command line argument consumed.\nbool GetOptionArgument(int argc, char** argv, int* index,\n const std::string& option,\n string_piece* option_argument) {\n const string_piece arg = argv[*index];\n assert(arg.starts_with(option));\n if (arg.size() != option.size()) {\n *option_argument = arg.substr(option.size());\n return true;\n } else {\n if (option.back() == '=') {\n *option_argument = \"\";\n return true;\n }\n if (++(*index) >= argc) return false;\n *option_argument = argv[*index];\n return true;\n }\n}\n\nconst char kBuildVersion[] =\n#include \"build-version.inc\"\n ;\n} \/\/ anonymous namespace\n\nint main(int argc, char** argv) {\n std::vector<std::pair<std::string, shaderc_shader_kind>> input_files;\n shaderc_shader_kind current_fshader_stage = shaderc_glsl_infer_from_source;\n glslc::FileCompiler compiler;\n bool success = true;\n bool has_stdin_input = false;\n\n for (int i = 1; i < argc; ++i) {\n const string_piece arg = argv[i];\n if (arg == \"--help\") {\n ::PrintHelp(&std::cout);\n return 0;\n } else if (arg == \"--version\") {\n std::cout << kBuildVersion << std::endl;\n std::cout << \"Target: \"\n << spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_0_4)\n << std::endl;\n return 0;\n } else if (arg.starts_with(\"-o\")) {\n string_piece file_name;\n if (!GetOptionArgument(argc, argv, &i, \"-o\", &file_name)) {\n std::cerr\n << \"glslc: error: argument to '-o' is missing (expected 1 value)\"\n << std::endl;\n return 1;\n }\n compiler.SetOutputFileName(file_name);\n } else if (arg.starts_with(\"-fshader-stage=\")) {\n const string_piece stage = arg.substr(std::strlen(\"-fshader-stage=\"));\n current_fshader_stage = glslc::GetForcedShaderKindFromCmdLine(arg);\n if (current_fshader_stage == shaderc_glsl_infer_from_source) {\n std::cerr << \"glslc: error: stage not recognized: '\" << stage << \"'\"\n << std::endl;\n return 1;\n }\n } else if (arg.starts_with(\"-std=\")) {\n const string_piece standard = arg.substr(std::strlen(\"-std=\"));\n int version;\n shaderc_profile profile;\n if (!shaderc_parse_version_profile(standard.begin(), &version,\n &profile)) {\n std::cerr << \"glslc: error: invalid value '\" << standard\n << \"' in '-std=\" << standard << \"'\" << std::endl;\n return 1;\n }\n compiler.options().SetForcedVersionProfile(version, profile);\n } else if (arg.starts_with(\"--target-env=\")) {\n shaderc_target_env target_env = shaderc_target_env_default;\n const string_piece target_env_str =\n arg.substr(std::strlen(\"--target-env=\"));\n if (target_env_str == \"vulkan\") {\n target_env = shaderc_target_env_vulkan;\n } else if (target_env_str == \"opengl\") {\n target_env = shaderc_target_env_opengl;\n } else if (target_env_str == \"opengl_compat\") {\n target_env = shaderc_target_env_opengl_compat;\n } else {\n std::cerr << \"glslc: error: invalid value '\" << target_env_str\n << \"' in '--target-env=\" << target_env_str << \"'\"\n << std::endl;\n return 1;\n }\n compiler.options().SetTargetEnvironment(target_env, 0);\n } else if (arg.starts_with(\"-x\")) {\n string_piece option_arg;\n if (!GetOptionArgument(argc, argv, &i, \"-x\", &option_arg)) {\n std::cerr\n << \"glslc: error: argument to '-x' is missing (expected 1 value)\"\n << std::endl;\n success = false;\n } else {\n if (option_arg != \"glsl\") {\n std::cerr << \"glslc: error: language not recognized: '\" << option_arg\n << \"'\" << std::endl;\n return 1;\n }\n }\n } else if (arg == \"-c\") {\n compiler.SetIndividualCompilationFlag();\n } else if (arg == \"-E\") {\n compiler.SetPreprocessingOnlyFlag();\n } else if (arg == \"-M\" || arg == \"-MM\") {\n \/\/ -M implies -E and -w\n compiler.SetPreprocessingOnlyFlag();\n compiler.options().SetSuppressWarnings();\n if (compiler.GetDependencyDumpingHandler()->DumpingModeNotSet()) {\n compiler.GetDependencyDumpingHandler()\n ->SetDumpAsNormalCompilationOutput();\n } else {\n std::cerr << \"glslc: error: both -M (or -MM) and -MD are specified. \"\n \"Only one should be used at one time.\"\n << std::endl;\n return 1;\n }\n } else if (arg == \"-MD\") {\n if (compiler.GetDependencyDumpingHandler()->DumpingModeNotSet()) {\n compiler.GetDependencyDumpingHandler()\n ->SetDumpToExtraDependencyInfoFiles();\n } else {\n std::cerr << \"glslc: error: both -M (or -MM) and -MD are specified. \"\n \"Only one should be used at one time.\"\n << std::endl;\n return 1;\n }\n } else if (arg == \"-MF\") {\n string_piece dep_file_name;\n if (!GetOptionArgument(argc, argv, &i, \"-MF\", &dep_file_name)) {\n std::cerr\n << \"glslc: error: missing dependency info filename after '-MF'\"\n << std::endl;\n return 1;\n }\n compiler.GetDependencyDumpingHandler()->SetDependencyFileName(\n std::string(dep_file_name.data(), dep_file_name.size()));\n } else if (arg == \"-MT\") {\n string_piece dep_file_name;\n if (!GetOptionArgument(argc, argv, &i, \"-MT\", &dep_file_name)) {\n std::cerr << \"glslc: error: missing dependency info target after '-MT'\"\n << std::endl;\n return 1;\n }\n compiler.GetDependencyDumpingHandler()->SetTarget(\n std::string(dep_file_name.data(), dep_file_name.size()));\n } else if (arg == \"-S\") {\n compiler.SetDisassemblyFlag();\n } else if (arg.starts_with(\"-D\")) {\n const size_t length = arg.size();\n if (length <= 2) {\n std::cerr << \"glslc: error: argument to '-D' is missing\" << std::endl;\n } else {\n const string_piece argument = arg.substr(2);\n \/\/ Get the exact length of the macro string.\n size_t equal_sign_loc = argument.find_first_of('=');\n size_t name_length = equal_sign_loc != shaderc_util::string_piece::npos\n ? equal_sign_loc\n : argument.size();\n const string_piece name_piece = argument.substr(0, name_length);\n if (name_piece.starts_with(\"GL_\")) {\n std::cerr\n << \"glslc: error: names beginning with 'GL_' cannot be defined: \"\n << arg << std::endl;\n return 1;\n }\n if (name_piece.find(\"__\") != string_piece::npos) {\n std::cerr\n << \"glslc: warning: names containing consecutive underscores \"\n \"are reserved: \"\n << arg << std::endl;\n }\n\n const string_piece value_piece =\n (equal_sign_loc == string_piece::npos ||\n equal_sign_loc == argument.size() - 1)\n ? \"\"\n : argument.substr(name_length + 1);\n \/\/ TODO(deki): check arg for newlines.\n compiler.options().AddMacroDefinition(\n name_piece.data(), name_piece.size(), value_piece.data(),\n value_piece.size());\n }\n } else if (arg.starts_with(\"-I\")) {\n string_piece option_arg;\n if (!GetOptionArgument(argc, argv, &i, \"-I\", &option_arg)) {\n std::cerr\n << \"glslc: error: argument to '-I' is missing (expected 1 value)\"\n << std::endl;\n success = false;\n } else {\n compiler.AddIncludeDirectory(option_arg.str());\n }\n } else if (arg == \"-g\") {\n compiler.options().SetGenerateDebugInfo();\n } else if (arg == \"-w\") {\n compiler.options().SetSuppressWarnings();\n } else if (arg == \"-Werror\") {\n compiler.options().SetWarningsAsErrors();\n } else if (!(arg == \"-\") && arg[0] == '-') {\n std::cerr << \"glslc: error: \"\n << (arg[1] == '-' ? \"unsupported option\" : \"unknown argument\")\n << \": '\" << arg << \"'\" << std::endl;\n return 1;\n } else {\n if (arg == \"-\") {\n if (has_stdin_input) {\n std::cerr << \"glslc: error: specifying standard input \\\"-\\\" as input \"\n << \"more than once is not allowed.\" << std::endl;\n return 1;\n }\n has_stdin_input = true;\n }\n\n \/\/ If current_fshader_stage is shaderc_glsl_infer_from_source, that means\n \/\/ we didn't set forced shader kinds (otherwise an error should have\n \/\/ already been emitted before). So we should deduce the shader kind\n \/\/ from the file name. If current_fshader_stage is specifed to one of\n \/\/ the forced shader kinds, use that for the following compilation.\n input_files.emplace_back(\n arg.str(), current_fshader_stage == shaderc_glsl_infer_from_source\n ? glslc::DeduceDefaultShaderKindFromFileName(arg)\n : current_fshader_stage);\n }\n }\n\n if (!compiler.ValidateOptions(input_files.size())) return 1;\n\n if (!success) return 1;\n\n for (const auto& input_file : input_files) {\n const std::string& name = input_file.first;\n const shaderc_shader_kind stage = input_file.second;\n\n success &= compiler.CompileShaderFile(name, stage);\n }\n\n compiler.OutputMessages();\n return success ? 0 : 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012 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 \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColor.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkPath.h\"\n#include \"include\/core\/SkPathEffect.h\"\n#include \"include\/core\/SkScalar.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/core\/SkTypes.h\"\n#include \"include\/effects\/SkDashPathEffect.h\"\n#include \"include\/effects\/SkTrimPathEffect.h\"\n#include \"include\/private\/SkTArray.h\"\n#include \"include\/utils\/SkParsePath.h\"\n#include \"tools\/timer\/TimeUtils.h\"\n\n#include <math.h>\n#include <utility>\n\n\/*\n * Inspired by http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=112145\n *\/\nstatic void flower(SkCanvas* canvas, const SkPath& path, SkScalar intervals[2],\n SkPaint::Join join) {\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setStroke(true);\n paint.setStrokeJoin(join);\n paint.setStrokeWidth(42);\n canvas->drawPath(path, paint);\n\n paint.setColor(SK_ColorRED);\n paint.setStrokeWidth(21);\n paint.setPathEffect(SkDashPathEffect::Make(intervals, 2, 0));\n canvas->drawPath(path, paint);\n\n paint.setColor(SK_ColorGREEN);\n paint.setPathEffect(nullptr);\n paint.setStrokeWidth(0);\n canvas->drawPath(path, paint);\n}\n\nDEF_SIMPLE_GM(dashcubics, canvas, 865, 750) {\n SkPath path;\n const char* d = \"M 337,98 C 250,141 250,212 250,212 C 250,212 250,212 250,212\"\n \"C 250,212 250,212 250,212 C 250,212 250,141 163,98 C 156,195 217,231 217,231\"\n \"C 217,231 217,231 217,231 C 217,231 217,231 217,231 C 217,231 156,195 75,250\"\n \"C 156,305 217,269 217,269 C 217,269 217,269 217,269 C 217,269 217,269 217,269\"\n \"C 217,269 156,305 163,402 C 250,359 250,288 250,288 C 250,288 250,288 250,288\"\n \"C 250,288 250,288 250,288 C 250,288 250,359 338,402 C 345,305 283,269 283,269\"\n \"C 283,269 283,269 283,269 C 283,269 283,269 283,269 C 283,269 345,305 425,250\"\n \"C 344,195 283,231 283,231 C 283,231 283,231 283,231 C 283,231 283,231 283,231\"\n \"C 283,231 344,195 338,98\";\n\n SkParsePath::FromSVGString(d, &path);\n canvas->translate(-35.f, -55.f);\n for (int x = 0; x < 2; ++x) {\n for (int y = 0; y < 2; ++y) {\n canvas->save();\n canvas->translate(x * 430.f, y * 355.f);\n SkScalar intervals[] = { 5 + (x ? 0 : 0.0001f + 0.0001f), 10 };\n flower(canvas, path, intervals, y ? SkPaint::kDefault_Join : SkPaint::kRound_Join);\n canvas->restore();\n }\n }\n}\n\nclass TrimGM : public skiagm::GM {\npublic:\n TrimGM() {\n SkAssertResult(SkParsePath::FromSVGString(\n \"M 0,100 C 10, 50 190, 50 200,100\"\n \"M 200,100 C 210,150 390,150 400,100\"\n \"M 400,100 C 390, 50 210, 50 200,100\"\n \"M 200,100 C 190,150 10,150 0,100\",\n &fPaths.push_back()));\n\n SkAssertResult(SkParsePath::FromSVGString(\n \"M 0, 75 L 200, 75\"\n \"M 200, 91 L 200, 91\"\n \"M 200,108 L 200,108\"\n \"M 200,125 L 400,125\",\n &fPaths.push_back()));\n\n SkAssertResult(SkParsePath::FromSVGString(\n \"M 0,100 L 50, 50\"\n \"M 50, 50 L 150,150\"\n \"M 150,150 L 250, 50\"\n \"M 250, 50 L 350,150\"\n \"M 350,150 L 400,100\",\n &fPaths.push_back()));\n\n }\n\nprotected:\n SkString onShortName() override { return SkString(\"trimpatheffect\"); }\n\n SkISize onISize() override {\n return SkISize::Make(1400, 1000);\n }\n\n void onDraw(SkCanvas* canvas) override {\n static constexpr SkSize kCellSize = { 440, 150 };\n static constexpr SkScalar kOffsets[][2] = {\n { -0.33f, -0.66f },\n { 0 , 1 },\n { 0 , 0.25f},\n { 0.25f, 0.75f},\n { 0.75f, 1 },\n { 1 , 0.75f},\n };\n\n SkPaint hairlinePaint;\n hairlinePaint.setAntiAlias(true);\n hairlinePaint.setStroke(true);\n hairlinePaint.setStrokeCap(SkPaint::kRound_Cap);\n hairlinePaint.setStrokeWidth(2);\n SkPaint normalPaint = hairlinePaint;\n normalPaint.setStrokeWidth(10);\n normalPaint.setColor(0x8000ff00);\n SkPaint invertedPaint = normalPaint;\n invertedPaint.setColor(0x80ff0000);\n\n for (const auto& offset : kOffsets) {\n auto start = offset[0] + fOffset,\n stop = offset[1] + fOffset;\n\n auto normalMode = SkTrimPathEffect::Mode::kNormal,\n invertedMode = SkTrimPathEffect::Mode::kInverted;\n if (fOffset) {\n start -= SkScalarFloorToScalar(start);\n stop -= SkScalarFloorToScalar(stop);\n if (start > stop) {\n using std::swap;\n swap(start, stop);\n swap(normalMode, invertedMode);\n }\n }\n\n normalPaint.setPathEffect(SkTrimPathEffect::Make(start, stop, normalMode));\n invertedPaint.setPathEffect(SkTrimPathEffect::Make(start, stop, invertedMode));\n\n {\n SkAutoCanvasRestore acr(canvas, true);\n for (const auto& path : fPaths) {\n canvas->drawPath(path, normalPaint);\n canvas->drawPath(path, invertedPaint);\n canvas->drawPath(path, hairlinePaint);\n canvas->translate(kCellSize.width(), 0);\n }\n }\n\n canvas->translate(0, kCellSize.height());\n }\n }\n\n bool onAnimate(double nanos) override {\n fOffset = TimeUtils::NanosToMSec(nanos) \/ 2000.0f;\n fOffset -= floorf(fOffset);\n return true;\n }\n\nprivate:\n SkTArray<SkPath> fPaths;\n SkScalar fOffset = 0;\n\n using INHERITED = skiagm::GM;\n};\nDEF_GM(return new TrimGM;)\n\n<commit_msg>do work in onBefore, not in constructor<commit_after>\/*\n * Copyright 2012 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 \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColor.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkPath.h\"\n#include \"include\/core\/SkPathEffect.h\"\n#include \"include\/core\/SkScalar.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/core\/SkTypes.h\"\n#include \"include\/effects\/SkDashPathEffect.h\"\n#include \"include\/effects\/SkTrimPathEffect.h\"\n#include \"include\/private\/SkTArray.h\"\n#include \"include\/utils\/SkParsePath.h\"\n#include \"tools\/timer\/TimeUtils.h\"\n\n#include <math.h>\n#include <utility>\n\n\/*\n * Inspired by http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=112145\n *\/\nstatic void flower(SkCanvas* canvas, const SkPath& path, SkScalar intervals[2],\n SkPaint::Join join) {\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setStroke(true);\n paint.setStrokeJoin(join);\n paint.setStrokeWidth(42);\n canvas->drawPath(path, paint);\n\n paint.setColor(SK_ColorRED);\n paint.setStrokeWidth(21);\n paint.setPathEffect(SkDashPathEffect::Make(intervals, 2, 0));\n canvas->drawPath(path, paint);\n\n paint.setColor(SK_ColorGREEN);\n paint.setPathEffect(nullptr);\n paint.setStrokeWidth(0);\n canvas->drawPath(path, paint);\n}\n\nDEF_SIMPLE_GM(dashcubics, canvas, 865, 750) {\n SkPath path;\n const char* d = \"M 337,98 C 250,141 250,212 250,212 C 250,212 250,212 250,212\"\n \"C 250,212 250,212 250,212 C 250,212 250,141 163,98 C 156,195 217,231 217,231\"\n \"C 217,231 217,231 217,231 C 217,231 217,231 217,231 C 217,231 156,195 75,250\"\n \"C 156,305 217,269 217,269 C 217,269 217,269 217,269 C 217,269 217,269 217,269\"\n \"C 217,269 156,305 163,402 C 250,359 250,288 250,288 C 250,288 250,288 250,288\"\n \"C 250,288 250,288 250,288 C 250,288 250,359 338,402 C 345,305 283,269 283,269\"\n \"C 283,269 283,269 283,269 C 283,269 283,269 283,269 C 283,269 345,305 425,250\"\n \"C 344,195 283,231 283,231 C 283,231 283,231 283,231 C 283,231 283,231 283,231\"\n \"C 283,231 344,195 338,98\";\n\n SkParsePath::FromSVGString(d, &path);\n canvas->translate(-35.f, -55.f);\n for (int x = 0; x < 2; ++x) {\n for (int y = 0; y < 2; ++y) {\n canvas->save();\n canvas->translate(x * 430.f, y * 355.f);\n SkScalar intervals[] = { 5 + (x ? 0 : 0.0001f + 0.0001f), 10 };\n flower(canvas, path, intervals, y ? SkPaint::kDefault_Join : SkPaint::kRound_Join);\n canvas->restore();\n }\n }\n}\n\nclass TrimGM : public skiagm::GM {\npublic:\n TrimGM() {}\n\n void onOnceBeforeDraw() override {\n SkAssertResult(SkParsePath::FromSVGString(\n \"M 0,100 C 10, 50 190, 50 200,100\"\n \"M 200,100 C 210,150 390,150 400,100\"\n \"M 400,100 C 390, 50 210, 50 200,100\"\n \"M 200,100 C 190,150 10,150 0,100\",\n &fPaths.push_back()));\n\n SkAssertResult(SkParsePath::FromSVGString(\n \"M 0, 75 L 200, 75\"\n \"M 200, 91 L 200, 91\"\n \"M 200,108 L 200,108\"\n \"M 200,125 L 400,125\",\n &fPaths.push_back()));\n\n SkAssertResult(SkParsePath::FromSVGString(\n \"M 0,100 L 50, 50\"\n \"M 50, 50 L 150,150\"\n \"M 150,150 L 250, 50\"\n \"M 250, 50 L 350,150\"\n \"M 350,150 L 400,100\",\n &fPaths.push_back()));\n\n }\n\nprotected:\n SkString onShortName() override { return SkString(\"trimpatheffect\"); }\n\n SkISize onISize() override {\n return SkISize::Make(1400, 1000);\n }\n\n void onDraw(SkCanvas* canvas) override {\n static constexpr SkSize kCellSize = { 440, 150 };\n static constexpr SkScalar kOffsets[][2] = {\n { -0.33f, -0.66f },\n { 0 , 1 },\n { 0 , 0.25f},\n { 0.25f, 0.75f},\n { 0.75f, 1 },\n { 1 , 0.75f},\n };\n\n SkPaint hairlinePaint;\n hairlinePaint.setAntiAlias(true);\n hairlinePaint.setStroke(true);\n hairlinePaint.setStrokeCap(SkPaint::kRound_Cap);\n hairlinePaint.setStrokeWidth(2);\n SkPaint normalPaint = hairlinePaint;\n normalPaint.setStrokeWidth(10);\n normalPaint.setColor(0x8000ff00);\n SkPaint invertedPaint = normalPaint;\n invertedPaint.setColor(0x80ff0000);\n\n for (const auto& offset : kOffsets) {\n auto start = offset[0] + fOffset,\n stop = offset[1] + fOffset;\n\n auto normalMode = SkTrimPathEffect::Mode::kNormal,\n invertedMode = SkTrimPathEffect::Mode::kInverted;\n if (fOffset) {\n start -= SkScalarFloorToScalar(start);\n stop -= SkScalarFloorToScalar(stop);\n if (start > stop) {\n using std::swap;\n swap(start, stop);\n swap(normalMode, invertedMode);\n }\n }\n\n normalPaint.setPathEffect(SkTrimPathEffect::Make(start, stop, normalMode));\n invertedPaint.setPathEffect(SkTrimPathEffect::Make(start, stop, invertedMode));\n\n {\n SkAutoCanvasRestore acr(canvas, true);\n for (const auto& path : fPaths) {\n canvas->drawPath(path, normalPaint);\n canvas->drawPath(path, invertedPaint);\n canvas->drawPath(path, hairlinePaint);\n canvas->translate(kCellSize.width(), 0);\n }\n }\n\n canvas->translate(0, kCellSize.height());\n }\n }\n\n bool onAnimate(double nanos) override {\n fOffset = TimeUtils::NanosToMSec(nanos) \/ 2000.0f;\n fOffset -= floorf(fOffset);\n return true;\n }\n\nprivate:\n SkTArray<SkPath> fPaths;\n SkScalar fOffset = 0;\n\n using INHERITED = skiagm::GM;\n};\nDEF_GM(return new TrimGM;)\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 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#include \"gm.h\"\n#include \"SkTypeface.h\"\n\nnamespace skiagm {\n\nclass FontScalerGM : public GM {\npublic:\n FontScalerGM() {\n this->setBGColor(0xFFFFFFFF);\n }\n\n virtual ~FontScalerGM() {\n }\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"fontscaler\");\n }\n\n virtual SkISize onISize() {\n return make_isize(1450, 750);\n }\n\n static void rotate_about(SkCanvas* canvas,\n SkScalar degrees,\n SkScalar px, SkScalar py) {\n canvas->translate(px, py);\n canvas->rotate(degrees);\n canvas->translate(-px, -py);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkPaint paint;\n\n paint.setAntiAlias(true);\n paint.setLCDRenderText(true);\n \/\/With freetype the default (normal hinting) can be really ugly.\n \/\/Most distros now set slight (vertical hinting only) in any event.\n paint.setHinting(SkPaint::kSlight_Hinting);\n SkSafeUnref(paint.setTypeface(SkTypeface::CreateFromName(\"Times Roman\", SkTypeface::kNormal)));\n\n const char* text = \"Hamburgefons ooo mmm\";\n const size_t textLen = strlen(text);\n\n for (int j = 0; j < 2; ++j) {\n for (int i = 0; i < 6; ++i) {\n SkScalar x = SkIntToScalar(10);\n SkScalar y = SkIntToScalar(20);\n\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(SkIntToScalar(50 + i * 230),\n SkIntToScalar(20));\n rotate_about(canvas, SkIntToScalar(i * 5), x, y * 10);\n\n {\n SkPaint p;\n p.setAntiAlias(true);\n SkRect r;\n r.set(x - SkIntToScalar(3), SkIntToScalar(15),\n x - SkIntToScalar(1), SkIntToScalar(280));\n canvas->drawRect(r, p);\n }\n\n int index = 0;\n for (int ps = 6; ps <= 22; ps++) {\n paint.setTextSize(SkIntToScalar(ps));\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n index += 1;\n }\n }\n canvas->translate(0, SkIntToScalar(360));\n paint.setSubpixelText(true);\n }\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef SK_BUILD_FOR_ANDROID\nstatic GM* MyFactory(void*) { return new FontScalerGM; }\nstatic GMRegistry reg(MyFactory);\n#endif\n}\n\n<commit_msg>Re-enable gm fontscaler for Android<commit_after>\/*\n * Copyright 2011 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#include \"gm.h\"\n#include \"SkTypeface.h\"\n\nnamespace skiagm {\n\nclass FontScalerGM : public GM {\npublic:\n FontScalerGM() {\n this->setBGColor(0xFFFFFFFF);\n }\n\n virtual ~FontScalerGM() {\n }\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"fontscaler\");\n }\n\n virtual SkISize onISize() {\n return make_isize(1450, 750);\n }\n\n static void rotate_about(SkCanvas* canvas,\n SkScalar degrees,\n SkScalar px, SkScalar py) {\n canvas->translate(px, py);\n canvas->rotate(degrees);\n canvas->translate(-px, -py);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkPaint paint;\n\n paint.setAntiAlias(true);\n paint.setLCDRenderText(true);\n \/\/With freetype the default (normal hinting) can be really ugly.\n \/\/Most distros now set slight (vertical hinting only) in any event.\n paint.setHinting(SkPaint::kSlight_Hinting);\n SkSafeUnref(paint.setTypeface(SkTypeface::CreateFromName(\"Times Roman\", SkTypeface::kNormal)));\n\n const char* text = \"Hamburgefons ooo mmm\";\n const size_t textLen = strlen(text);\n\n for (int j = 0; j < 2; ++j) {\n for (int i = 0; i < 6; ++i) {\n SkScalar x = SkIntToScalar(10);\n SkScalar y = SkIntToScalar(20);\n\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(SkIntToScalar(50 + i * 230),\n SkIntToScalar(20));\n rotate_about(canvas, SkIntToScalar(i * 5), x, y * 10);\n\n {\n SkPaint p;\n p.setAntiAlias(true);\n SkRect r;\n r.set(x - SkIntToScalar(3), SkIntToScalar(15),\n x - SkIntToScalar(1), SkIntToScalar(280));\n canvas->drawRect(r, p);\n }\n\n int index = 0;\n for (int ps = 6; ps <= 22; ps++) {\n paint.setTextSize(SkIntToScalar(ps));\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n index += 1;\n }\n }\n canvas->translate(0, SkIntToScalar(360));\n paint.setSubpixelText(true);\n }\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new FontScalerGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: basmethnode.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 10:34:27 $\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_scripting.hxx\"\n\n#ifndef SCRIPTING_BASMETHNODE_HXX\n#include \"basmethnode.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_\n#include <com\/sun\/star\/frame\/XDesktop.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XDISPATCHHELPER_HPP_\n#include <com\/sun\/star\/frame\/XDispatchHelper.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_\n#include <com\/sun\/star\/frame\/XDispatchProvider.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiComponentFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SCRIPT_BROWSE_BROWSENODETYPES_HPP_\n#include <com\/sun\/star\/script\/browse\/BrowseNodeTypes.hpp>\n#endif\n\n#ifndef _VOS_MUTEX_HXX_\n#include <vos\/mutex.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _SB_SBSTAR_HXX\n#include <basic\/sbstar.hxx>\n#endif\n#ifndef _SB_SBMETH_HXX\n#include <basic\/sbmeth.hxx>\n#endif\n#ifndef _SB_SBMOD_HXX\n#include <basic\/sbmod.hxx>\n#endif\n\n#include <util\/MiscUtils.hxx>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::comphelper;\nusing namespace ::com::sun::star::script;\nusing namespace ::sf_misc;\n\n#define BASPROV_PROPERTY_ID_URI 1\n#define BASPROV_PROPERTY_ID_EDITABLE 2\n\n#define BASPROV_PROPERTY_URI ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"URI\" ) )\n#define BASPROV_PROPERTY_EDITABLE ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"Editable\" ) )\n\n#define BASPROV_DEFAULT_ATTRIBS() PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT | PropertyAttribute::READONLY\n\n\n\/\/.........................................................................\nnamespace basprov\n{\n\/\/.........................................................................\n\n \/\/ =============================================================================\n \/\/ BasicMethodNodeImpl\n \/\/ =============================================================================\n\n BasicMethodNodeImpl::BasicMethodNodeImpl( const Reference< XComponentContext >& rxContext,\n const ::rtl::OUString& sScriptingContext, SbMethod* pMethod, bool isAppScript )\n : ::scripting_helper::OBroadcastHelperHolder( m_aMutex )\n ,OPropertyContainer( GetBroadcastHelper() )\n ,m_xContext( rxContext )\n ,m_sScriptingContext( sScriptingContext )\n ,m_pMethod( pMethod )\n ,m_bIsAppScript( isAppScript )\n ,m_bEditable( sal_True )\n {\n if ( m_pMethod )\n {\n SbModule* pModule = m_pMethod->GetModule();\n if ( pModule )\n {\n StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );\n if ( pBasic )\n {\n m_sURI = ::rtl::OUString::createFromAscii( \"vnd.sun.star.script:\" );\n m_sURI += pBasic->GetName();\n m_sURI += ::rtl::OUString::createFromAscii( \".\" );\n m_sURI += pModule->GetName();\n m_sURI += ::rtl::OUString::createFromAscii( \".\" );\n m_sURI += m_pMethod->GetName();\n m_sURI += ::rtl::OUString::createFromAscii( \"?language=Basic&location=\" );\n if ( m_bIsAppScript )\n m_sURI += ::rtl::OUString::createFromAscii( \"application\" );\n else\n m_sURI += ::rtl::OUString::createFromAscii( \"document\" );\n }\n }\n }\n\n registerProperty( BASPROV_PROPERTY_URI, BASPROV_PROPERTY_ID_URI, BASPROV_DEFAULT_ATTRIBS(), &m_sURI, ::getCppuType( &m_sURI ) );\n registerProperty( BASPROV_PROPERTY_EDITABLE, BASPROV_PROPERTY_ID_EDITABLE, BASPROV_DEFAULT_ATTRIBS(), &m_bEditable, ::getCppuType( &m_bEditable ) );\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n BasicMethodNodeImpl::~BasicMethodNodeImpl()\n {\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XInterface\n \/\/ -----------------------------------------------------------------------------\n\n IMPLEMENT_FORWARD_XINTERFACE2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XTypeProvider\n \/\/ -----------------------------------------------------------------------------\n\n IMPLEMENT_FORWARD_XTYPEPROVIDER2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XBrowseNode\n \/\/ -----------------------------------------------------------------------------\n\n ::rtl::OUString BasicMethodNodeImpl::getName( ) throw (RuntimeException)\n {\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n ::rtl::OUString sMethodName;\n if ( m_pMethod )\n sMethodName = m_pMethod->GetName();\n\n return sMethodName;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n Sequence< Reference< browse::XBrowseNode > > BasicMethodNodeImpl::getChildNodes( ) throw (RuntimeException)\n {\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n return Sequence< Reference< browse::XBrowseNode > >();\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n sal_Bool BasicMethodNodeImpl::hasChildNodes( ) throw (RuntimeException)\n {\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n return sal_False;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n sal_Int16 BasicMethodNodeImpl::getType( ) throw (RuntimeException)\n {\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n return browse::BrowseNodeTypes::SCRIPT;\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ OPropertySetHelper\n \/\/ -----------------------------------------------------------------------------\n\n ::cppu::IPropertyArrayHelper& BasicMethodNodeImpl::getInfoHelper( )\n {\n return *getArrayHelper();\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ OPropertyArrayUsageHelper\n \/\/ -----------------------------------------------------------------------------\n\n ::cppu::IPropertyArrayHelper* BasicMethodNodeImpl::createArrayHelper( ) const\n {\n Sequence< Property > aProps;\n describeProperties( aProps );\n return new ::cppu::OPropertyArrayHelper( aProps );\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XPropertySet\n \/\/ -----------------------------------------------------------------------------\n\n Reference< XPropertySetInfo > BasicMethodNodeImpl::getPropertySetInfo( ) throw (RuntimeException)\n {\n Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );\n return xInfo;\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XInvocation\n \/\/ -----------------------------------------------------------------------------\n\n Reference< XIntrospectionAccess > BasicMethodNodeImpl::getIntrospection( ) throw (RuntimeException)\n {\n return Reference< XIntrospectionAccess >();\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n Any BasicMethodNodeImpl::invoke( const ::rtl::OUString& aFunctionName, const Sequence< Any >& aParams,\n Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )\n throw (IllegalArgumentException, script::CannotConvertException,\n reflection::InvocationTargetException, RuntimeException)\n {\n (void)aParams;\n (void)aOutParamIndex;\n (void)aOutParam;\n\n if ( aFunctionName == BASPROV_PROPERTY_EDITABLE )\n {\n ::rtl::OUString sDocURL, sLibName, sModName;\n USHORT nLine1 = 0, nLine2;\n\n if ( !m_bIsAppScript )\n {\n Reference< frame::XModel > xModel = MiscUtils::tDocUrlToModel( m_sScriptingContext );\n\n if ( xModel.is() )\n {\n sDocURL = xModel->getURL();\n if ( sDocURL.getLength() == 0 )\n {\n Sequence < PropertyValue > aProps = xModel->getArgs();\n sal_Int32 nProps = aProps.getLength();\n const PropertyValue* pProps = aProps.getConstArray();\n for ( sal_Int32 i = 0; i < nProps; ++i )\n {\n \/\/ TODO: according to MBA the property 'Title' may change in future\n if ( pProps[i].Name == ::rtl::OUString::createFromAscii( \"Title\" ) )\n {\n pProps[i].Value >>= sDocURL;\n break;\n }\n }\n }\n }\n }\n\n if ( m_pMethod )\n {\n m_pMethod->GetLineRange( nLine1, nLine2 );\n SbModule* pModule = m_pMethod->GetModule();\n if ( pModule )\n {\n sModName = pModule->GetName();\n StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );\n if ( pBasic )\n sLibName = pBasic->GetName();\n }\n }\n\n if ( m_xContext.is() )\n {\n Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );\n\n if ( xSMgr.is() )\n {\n Reference< frame::XDesktop > xDesktop( xSMgr->createInstanceWithContext(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.frame.Desktop\" ) ), m_xContext ), UNO_QUERY );\n\n if ( xDesktop.is() )\n {\n Reference < frame::XDispatchProvider > xProv( xDesktop->getCurrentFrame(), UNO_QUERY );\n\n if ( xProv.is() )\n {\n Reference< frame::XDispatchHelper > xHelper( xSMgr->createInstanceWithContext(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.frame.DispatchHelper\" ) ), m_xContext ), UNO_QUERY );\n\n if ( xHelper.is() )\n {\n Sequence < PropertyValue > aArgs(7);\n aArgs[0].Name = ::rtl::OUString::createFromAscii( \"Document\" );\n aArgs[0].Value <<= sDocURL;\n aArgs[1].Name = ::rtl::OUString::createFromAscii( \"LibName\" );\n aArgs[1].Value <<= sLibName;\n aArgs[2].Name = ::rtl::OUString::createFromAscii( \"Name\" );\n aArgs[2].Value <<= sModName;\n aArgs[3].Name = ::rtl::OUString::createFromAscii( \"Type\" );\n aArgs[3].Value <<= ::rtl::OUString::createFromAscii( \"Module\" );\n aArgs[4].Name = ::rtl::OUString::createFromAscii( \"Line\" );\n aArgs[4].Value <<= static_cast< sal_uInt32 >( nLine1 );\n xHelper->executeDispatch( xProv, ::rtl::OUString::createFromAscii( \".uno:BasicIDEAppear\" ), ::rtl::OUString(), 0, aArgs );\n }\n }\n }\n }\n }\n }\n else\n {\n throw IllegalArgumentException(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"BasicMethodNodeImpl::invoke: function name not supported!\" ) ),\n Reference< XInterface >(), 1 );\n }\n\n return Any();\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n void BasicMethodNodeImpl::setValue( const ::rtl::OUString& aPropertyName, const Any& aValue )\n throw (UnknownPropertyException, script::CannotConvertException,\n reflection::InvocationTargetException, RuntimeException)\n {\n (void)aPropertyName;\n (void)aValue;\n\n throw UnknownPropertyException(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"BasicMethodNodeImpl::setValue: property name is unknown!\" ) ),\n Reference< XInterface >() );\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n Any BasicMethodNodeImpl::getValue( const ::rtl::OUString& aPropertyName ) throw (UnknownPropertyException, RuntimeException)\n {\n (void)aPropertyName;\n\n throw UnknownPropertyException(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"BasicMethodNodeImpl::getValue: property name is unknown!\" ) ),\n Reference< XInterface >() );\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n sal_Bool BasicMethodNodeImpl::hasMethod( const ::rtl::OUString& aName ) throw (RuntimeException)\n {\n sal_Bool bReturn = sal_False;\n if ( aName == BASPROV_PROPERTY_EDITABLE )\n bReturn = sal_True;\n\n return bReturn;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n sal_Bool BasicMethodNodeImpl::hasProperty( const ::rtl::OUString& aName ) throw (RuntimeException)\n {\n (void)aName;\n\n return sal_False;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n\/\/.........................................................................\n} \/\/ namespace basprov\n\/\/.........................................................................\n<commit_msg>INTEGRATION: CWS changefileheader (1.13.70); FILE MERGED 2008\/04\/01 15:31:46 thb 1.13.70.3: #i85898# Stripping all external header guards 2008\/04\/01 12:37:19 thb 1.13.70.2: #i85898# Stripping all external header guards 2008\/03\/31 13:35:59 rt 1.13.70.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: basmethnode.cxx,v $\n * $Revision: 1.14 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_scripting.hxx\"\n#include \"basmethnode.hxx\"\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#include <com\/sun\/star\/frame\/XDesktop.hpp>\n#include <com\/sun\/star\/frame\/XDispatchHelper.hpp>\n#include <com\/sun\/star\/frame\/XDispatchProvider.hpp>\n#include <com\/sun\/star\/lang\/XMultiComponentFactory.hpp>\n#include <com\/sun\/star\/script\/browse\/BrowseNodeTypes.hpp>\n#include <vos\/mutex.hxx>\n#include <vcl\/svapp.hxx>\n#include <basic\/sbstar.hxx>\n#include <basic\/sbmeth.hxx>\n#include <basic\/sbmod.hxx>\n\n#include <util\/MiscUtils.hxx>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::comphelper;\nusing namespace ::com::sun::star::script;\nusing namespace ::sf_misc;\n\n#define BASPROV_PROPERTY_ID_URI 1\n#define BASPROV_PROPERTY_ID_EDITABLE 2\n\n#define BASPROV_PROPERTY_URI ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"URI\" ) )\n#define BASPROV_PROPERTY_EDITABLE ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"Editable\" ) )\n\n#define BASPROV_DEFAULT_ATTRIBS() PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT | PropertyAttribute::READONLY\n\n\n\/\/.........................................................................\nnamespace basprov\n{\n\/\/.........................................................................\n\n \/\/ =============================================================================\n \/\/ BasicMethodNodeImpl\n \/\/ =============================================================================\n\n BasicMethodNodeImpl::BasicMethodNodeImpl( const Reference< XComponentContext >& rxContext,\n const ::rtl::OUString& sScriptingContext, SbMethod* pMethod, bool isAppScript )\n : ::scripting_helper::OBroadcastHelperHolder( m_aMutex )\n ,OPropertyContainer( GetBroadcastHelper() )\n ,m_xContext( rxContext )\n ,m_sScriptingContext( sScriptingContext )\n ,m_pMethod( pMethod )\n ,m_bIsAppScript( isAppScript )\n ,m_bEditable( sal_True )\n {\n if ( m_pMethod )\n {\n SbModule* pModule = m_pMethod->GetModule();\n if ( pModule )\n {\n StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );\n if ( pBasic )\n {\n m_sURI = ::rtl::OUString::createFromAscii( \"vnd.sun.star.script:\" );\n m_sURI += pBasic->GetName();\n m_sURI += ::rtl::OUString::createFromAscii( \".\" );\n m_sURI += pModule->GetName();\n m_sURI += ::rtl::OUString::createFromAscii( \".\" );\n m_sURI += m_pMethod->GetName();\n m_sURI += ::rtl::OUString::createFromAscii( \"?language=Basic&location=\" );\n if ( m_bIsAppScript )\n m_sURI += ::rtl::OUString::createFromAscii( \"application\" );\n else\n m_sURI += ::rtl::OUString::createFromAscii( \"document\" );\n }\n }\n }\n\n registerProperty( BASPROV_PROPERTY_URI, BASPROV_PROPERTY_ID_URI, BASPROV_DEFAULT_ATTRIBS(), &m_sURI, ::getCppuType( &m_sURI ) );\n registerProperty( BASPROV_PROPERTY_EDITABLE, BASPROV_PROPERTY_ID_EDITABLE, BASPROV_DEFAULT_ATTRIBS(), &m_bEditable, ::getCppuType( &m_bEditable ) );\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n BasicMethodNodeImpl::~BasicMethodNodeImpl()\n {\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XInterface\n \/\/ -----------------------------------------------------------------------------\n\n IMPLEMENT_FORWARD_XINTERFACE2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XTypeProvider\n \/\/ -----------------------------------------------------------------------------\n\n IMPLEMENT_FORWARD_XTYPEPROVIDER2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XBrowseNode\n \/\/ -----------------------------------------------------------------------------\n\n ::rtl::OUString BasicMethodNodeImpl::getName( ) throw (RuntimeException)\n {\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n ::rtl::OUString sMethodName;\n if ( m_pMethod )\n sMethodName = m_pMethod->GetName();\n\n return sMethodName;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n Sequence< Reference< browse::XBrowseNode > > BasicMethodNodeImpl::getChildNodes( ) throw (RuntimeException)\n {\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n return Sequence< Reference< browse::XBrowseNode > >();\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n sal_Bool BasicMethodNodeImpl::hasChildNodes( ) throw (RuntimeException)\n {\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n return sal_False;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n sal_Int16 BasicMethodNodeImpl::getType( ) throw (RuntimeException)\n {\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n return browse::BrowseNodeTypes::SCRIPT;\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ OPropertySetHelper\n \/\/ -----------------------------------------------------------------------------\n\n ::cppu::IPropertyArrayHelper& BasicMethodNodeImpl::getInfoHelper( )\n {\n return *getArrayHelper();\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ OPropertyArrayUsageHelper\n \/\/ -----------------------------------------------------------------------------\n\n ::cppu::IPropertyArrayHelper* BasicMethodNodeImpl::createArrayHelper( ) const\n {\n Sequence< Property > aProps;\n describeProperties( aProps );\n return new ::cppu::OPropertyArrayHelper( aProps );\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XPropertySet\n \/\/ -----------------------------------------------------------------------------\n\n Reference< XPropertySetInfo > BasicMethodNodeImpl::getPropertySetInfo( ) throw (RuntimeException)\n {\n Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );\n return xInfo;\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XInvocation\n \/\/ -----------------------------------------------------------------------------\n\n Reference< XIntrospectionAccess > BasicMethodNodeImpl::getIntrospection( ) throw (RuntimeException)\n {\n return Reference< XIntrospectionAccess >();\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n Any BasicMethodNodeImpl::invoke( const ::rtl::OUString& aFunctionName, const Sequence< Any >& aParams,\n Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )\n throw (IllegalArgumentException, script::CannotConvertException,\n reflection::InvocationTargetException, RuntimeException)\n {\n (void)aParams;\n (void)aOutParamIndex;\n (void)aOutParam;\n\n if ( aFunctionName == BASPROV_PROPERTY_EDITABLE )\n {\n ::rtl::OUString sDocURL, sLibName, sModName;\n USHORT nLine1 = 0, nLine2;\n\n if ( !m_bIsAppScript )\n {\n Reference< frame::XModel > xModel = MiscUtils::tDocUrlToModel( m_sScriptingContext );\n\n if ( xModel.is() )\n {\n sDocURL = xModel->getURL();\n if ( sDocURL.getLength() == 0 )\n {\n Sequence < PropertyValue > aProps = xModel->getArgs();\n sal_Int32 nProps = aProps.getLength();\n const PropertyValue* pProps = aProps.getConstArray();\n for ( sal_Int32 i = 0; i < nProps; ++i )\n {\n \/\/ TODO: according to MBA the property 'Title' may change in future\n if ( pProps[i].Name == ::rtl::OUString::createFromAscii( \"Title\" ) )\n {\n pProps[i].Value >>= sDocURL;\n break;\n }\n }\n }\n }\n }\n\n if ( m_pMethod )\n {\n m_pMethod->GetLineRange( nLine1, nLine2 );\n SbModule* pModule = m_pMethod->GetModule();\n if ( pModule )\n {\n sModName = pModule->GetName();\n StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );\n if ( pBasic )\n sLibName = pBasic->GetName();\n }\n }\n\n if ( m_xContext.is() )\n {\n Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );\n\n if ( xSMgr.is() )\n {\n Reference< frame::XDesktop > xDesktop( xSMgr->createInstanceWithContext(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.frame.Desktop\" ) ), m_xContext ), UNO_QUERY );\n\n if ( xDesktop.is() )\n {\n Reference < frame::XDispatchProvider > xProv( xDesktop->getCurrentFrame(), UNO_QUERY );\n\n if ( xProv.is() )\n {\n Reference< frame::XDispatchHelper > xHelper( xSMgr->createInstanceWithContext(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.frame.DispatchHelper\" ) ), m_xContext ), UNO_QUERY );\n\n if ( xHelper.is() )\n {\n Sequence < PropertyValue > aArgs(7);\n aArgs[0].Name = ::rtl::OUString::createFromAscii( \"Document\" );\n aArgs[0].Value <<= sDocURL;\n aArgs[1].Name = ::rtl::OUString::createFromAscii( \"LibName\" );\n aArgs[1].Value <<= sLibName;\n aArgs[2].Name = ::rtl::OUString::createFromAscii( \"Name\" );\n aArgs[2].Value <<= sModName;\n aArgs[3].Name = ::rtl::OUString::createFromAscii( \"Type\" );\n aArgs[3].Value <<= ::rtl::OUString::createFromAscii( \"Module\" );\n aArgs[4].Name = ::rtl::OUString::createFromAscii( \"Line\" );\n aArgs[4].Value <<= static_cast< sal_uInt32 >( nLine1 );\n xHelper->executeDispatch( xProv, ::rtl::OUString::createFromAscii( \".uno:BasicIDEAppear\" ), ::rtl::OUString(), 0, aArgs );\n }\n }\n }\n }\n }\n }\n else\n {\n throw IllegalArgumentException(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"BasicMethodNodeImpl::invoke: function name not supported!\" ) ),\n Reference< XInterface >(), 1 );\n }\n\n return Any();\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n void BasicMethodNodeImpl::setValue( const ::rtl::OUString& aPropertyName, const Any& aValue )\n throw (UnknownPropertyException, script::CannotConvertException,\n reflection::InvocationTargetException, RuntimeException)\n {\n (void)aPropertyName;\n (void)aValue;\n\n throw UnknownPropertyException(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"BasicMethodNodeImpl::setValue: property name is unknown!\" ) ),\n Reference< XInterface >() );\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n Any BasicMethodNodeImpl::getValue( const ::rtl::OUString& aPropertyName ) throw (UnknownPropertyException, RuntimeException)\n {\n (void)aPropertyName;\n\n throw UnknownPropertyException(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"BasicMethodNodeImpl::getValue: property name is unknown!\" ) ),\n Reference< XInterface >() );\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n sal_Bool BasicMethodNodeImpl::hasMethod( const ::rtl::OUString& aName ) throw (RuntimeException)\n {\n sal_Bool bReturn = sal_False;\n if ( aName == BASPROV_PROPERTY_EDITABLE )\n bReturn = sal_True;\n\n return bReturn;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n sal_Bool BasicMethodNodeImpl::hasProperty( const ::rtl::OUString& aName ) throw (RuntimeException)\n {\n (void)aName;\n\n return sal_False;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n\/\/.........................................................................\n} \/\/ namespace basprov\n\/\/.........................................................................\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <iostream>\n\nusing namespace std;\n\nclass Matrix {\n\nprivate:\n\tint row, col, **mas;\npublic:\n\tMatrix(int length = 4);\n\tMatrix(int, int);\n\tMatrix(const Matrix&);\n\t\n int Element(int i, int j);\n\t~Matrix();\n\tvoid fill(const char*);\n\tvoid show() const;\n\tint rows();\n\tint columns();\n\tMatrix operator+(const Matrix&) const;\n\tMatrix operator*(const Matrix&) const;\n\tbool operator==(const Matrix&) const;\n\tMatrix operator=(const Matrix& x) const;\n\tfriend istream& operator >> (istream& is, Matrix& m);\n\tfriend ostream& operator << (std::ostream&, const Matrix&);\n};\n<commit_msg>Update matrix.hpp<commit_after>#include <fstream>\n#include <iostream>\n\nusing namespace std;\n\nclass Matrix {\n\nprivate:\n\tint row, col, **mas;\npublic:\n\tMatrix(int length = 4);\n\tMatrix(int, int);\n\tMatrix(const Matrix&);\n\t\n int Element(int i, int j) const;\n\t~Matrix();\n\tvoid fill(const char*);\n\tvoid show() const;\n\tint rows() const;\n\tint columns() const;\n\tMatrix operator+(const Matrix&) const;\n\tMatrix operator*(const Matrix&) const;\n\tbool operator==(const Matrix&) const;\n\tMatrix operator=(const Matrix& x) const;\n\tfriend istream& operator >> (istream& is, Matrix& m);\n\tfriend ostream& operator << (std::ostream&, const Matrix&);\n};\n<|endoftext|>"} {"text":"<commit_before>#ifndef AMGCL_OPERATIONS_VIENNACL_HPP\n#define AMGCL_OPERATIONS_VIENNACL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012 Denis Demidov <ddemidov@ksu.ru>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file operations_viennacl.hpp\n * \\author Denis Demidov <ddemidov@ksu.ru>\n * \\brief Adaptors for ViennaCL types.\n *\/\n\n#include <amgcl\/spmat.hpp>\n#include <viennacl\/compressed_matrix.hpp>\n#include <viennacl\/traits\/clear.hpp>\n\nnamespace amgcl {\n\nnamespace sparse {\n\ntemplate <class spmat>\nclass viennacl_matrix_adapter {\n public:\n typedef typename sparse::matrix_index<spmat>::type index_type;\n typedef typename sparse::matrix_value<spmat>::type value_type;\n\n class const_iterator1;\n\n class const_iterator2 {\n public:\n bool operator!=(const const_iterator2 &it) const {\n return pos != it.pos;\n }\n\n const const_iterator2& operator++() {\n ++pos;\n return *this;\n }\n\n index_type index1() const {\n return row;\n }\n\n index_type index2() const {\n return col[pos];\n }\n\n value_type operator*() const {\n return val[pos];\n }\n private:\n const_iterator2(index_type row, index_type pos,\n const index_type *col, const value_type *val)\n : row(row), pos(pos), col(col), val(val)\n { }\n\n index_type row;\n index_type pos;\n const index_type *col;\n const value_type *val;\n\n friend class const_iterator1;\n };\n\n class const_iterator1 {\n public:\n bool operator!=(const const_iterator1 &it) const {\n return pos != it.pos;\n }\n\n const const_iterator1& operator++() {\n ++pos;\n return *this;\n }\n\n index_type index1() const {\n return pos;\n }\n\n const const_iterator2 begin() const {\n return const_iterator2(pos, row[pos], col, val);\n }\n\n const const_iterator2 end() const {\n return const_iterator2(pos, row[pos + 1], col, val);\n }\n private:\n const_iterator1(index_type pos,\n const index_type *row,\n const index_type *col,\n const value_type *val\n )\n : pos(pos), row(row), col(col), val(val)\n { }\n\n index_type pos;\n const index_type *row;\n const index_type *col;\n const value_type *val;\n\n friend class viennacl_matrix_adapter;\n };\n\n viennacl_matrix_adapter(const spmat &A)\n : rows(sparse::matrix_rows(A)),\n cols(sparse::matrix_cols(A)),\n row(sparse::matrix_outer_index(A)),\n col(sparse::matrix_inner_index(A)),\n val(sparse::matrix_values(A))\n { }\n\n const_iterator1 begin1() const {\n return const_iterator1(0, row, col, val);\n }\n\n const_iterator1 end1() const {\n return const_iterator1(rows, row, col, val);\n }\n\n index_type size1() const {\n return rows;\n }\n\n index_type size2() const {\n return cols;\n }\n private:\n index_type rows;\n index_type cols;\n\n const index_type *row;\n const index_type *col;\n const value_type *val;\n};\n\ntemplate <class spmat>\nviennacl_matrix_adapter<spmat> viennacl_map(const spmat &A) {\n return viennacl_matrix_adapter<spmat>(A);\n}\n\n} \/\/ namespace sparse\n\n\/\/\/ Wrapper around amgcl::solver that is compatible with ViennaCL solvers.\n\/**\n * \\param vector Vector type that will be used with the preconditioner.\n * \\param AMG Type of amgcl::solver\n *\/\ntemplate <class vector, class AMG>\nclass viennacl_preconditioner {\n public:\n viennacl_preconditioner(const AMG &amg)\n : amg(amg), buf(amg.size()) {}\n\n void apply(vector &x) const {\n buf.swap(x);\n viennacl::traits::clear(x);\n amg.apply(buf, x);\n }\n private:\n const AMG &amg;\n mutable vector buf;\n};\n\n\/\/\/ Wrapper around amgcl::solver that is compatible with ViennaCL solvers.\ntemplate <class vector, class AMG>\nviennacl_preconditioner<vector, AMG> make_viennacl_precond(const AMG &amg) {\n return viennacl_preconditioner<vector, AMG>(amg);\n}\n\n} \/\/ namespace amgcl\n\n#endif\n<commit_msg>doc update<commit_after>#ifndef AMGCL_OPERATIONS_VIENNACL_HPP\n#define AMGCL_OPERATIONS_VIENNACL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012 Denis Demidov <ddemidov@ksu.ru>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file operations_viennacl.hpp\n * \\author Denis Demidov <ddemidov@ksu.ru>\n * \\brief Adaptors for ViennaCL types.\n *\/\n\n#include <amgcl\/spmat.hpp>\n#include <viennacl\/compressed_matrix.hpp>\n#include <viennacl\/traits\/clear.hpp>\n\nnamespace amgcl {\n\nnamespace sparse {\n\n\/\/\/ Provides proxy matrix class that may be used with ViennaCL.\n\/** No data is copied here. The proxy class does not own the data. *\/\ntemplate <class spmat>\nclass viennacl_matrix_adapter {\n public:\n typedef typename sparse::matrix_index<spmat>::type index_type;\n typedef typename sparse::matrix_value<spmat>::type value_type;\n\n class const_iterator1;\n\n class const_iterator2 {\n public:\n bool operator!=(const const_iterator2 &it) const {\n return pos != it.pos;\n }\n\n const const_iterator2& operator++() {\n ++pos;\n return *this;\n }\n\n index_type index1() const {\n return row;\n }\n\n index_type index2() const {\n return col[pos];\n }\n\n value_type operator*() const {\n return val[pos];\n }\n private:\n const_iterator2(index_type row, index_type pos,\n const index_type *col, const value_type *val)\n : row(row), pos(pos), col(col), val(val)\n { }\n\n index_type row;\n index_type pos;\n const index_type *col;\n const value_type *val;\n\n friend class const_iterator1;\n };\n\n class const_iterator1 {\n public:\n bool operator!=(const const_iterator1 &it) const {\n return pos != it.pos;\n }\n\n const const_iterator1& operator++() {\n ++pos;\n return *this;\n }\n\n index_type index1() const {\n return pos;\n }\n\n const const_iterator2 begin() const {\n return const_iterator2(pos, row[pos], col, val);\n }\n\n const const_iterator2 end() const {\n return const_iterator2(pos, row[pos + 1], col, val);\n }\n private:\n const_iterator1(index_type pos,\n const index_type *row,\n const index_type *col,\n const value_type *val\n )\n : pos(pos), row(row), col(col), val(val)\n { }\n\n index_type pos;\n const index_type *row;\n const index_type *col;\n const value_type *val;\n\n friend class viennacl_matrix_adapter;\n };\n\n viennacl_matrix_adapter(const spmat &A)\n : rows(sparse::matrix_rows(A)),\n cols(sparse::matrix_cols(A)),\n row(sparse::matrix_outer_index(A)),\n col(sparse::matrix_inner_index(A)),\n val(sparse::matrix_values(A))\n { }\n\n const_iterator1 begin1() const {\n return const_iterator1(0, row, col, val);\n }\n\n const_iterator1 end1() const {\n return const_iterator1(rows, row, col, val);\n }\n\n index_type size1() const {\n return rows;\n }\n\n index_type size2() const {\n return cols;\n }\n private:\n index_type rows;\n index_type cols;\n\n const index_type *row;\n const index_type *col;\n const value_type *val;\n};\n\ntemplate <class spmat>\nviennacl_matrix_adapter<spmat> viennacl_map(const spmat &A) {\n return viennacl_matrix_adapter<spmat>(A);\n}\n\n} \/\/ namespace sparse\n\n\/\/\/ Wrapper around amgcl::solver that is compatible with ViennaCL solvers.\n\/**\n * \\param vector Vector type that will be used with the preconditioner.\n * \\param AMG Type of amgcl::solver\n *\/\ntemplate <class vector, class AMG>\nclass viennacl_preconditioner {\n public:\n viennacl_preconditioner(const AMG &amg)\n : amg(amg), buf(amg.size()) {}\n\n void apply(vector &x) const {\n buf.swap(x);\n viennacl::traits::clear(x);\n amg.apply(buf, x);\n }\n private:\n const AMG &amg;\n mutable vector buf;\n};\n\n\/\/\/ Wrapper around amgcl::solver that is compatible with ViennaCL solvers.\ntemplate <class vector, class AMG>\nviennacl_preconditioner<vector, AMG> make_viennacl_precond(const AMG &amg) {\n return viennacl_preconditioner<vector, AMG>(amg);\n}\n\n} \/\/ namespace amgcl\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ logsum -- a port of Sean Eddy's fast table-driven log sum\n\/\/ This code was originally part of HMMER. This version is used with \n\/\/ Sean Eddy's permission as public domain code.\n\/\/\n\/\/ Modification Notice\n\/\/\n\/\/ By: Matei David, Ontario Institute for Cancer Research\n\/\/ When: 2015\n\/\/ Reason:\n\/\/ Reorganized as C++ header-only library,\n\/\/ with implicit lookup table initialization.\n\/\/\n\n\/* p7_FLogsum() function used in the Forward() algorithm.\n * \n * Contents:\n * 1. Floating point log sum.\n * 2. Benchmark driver.\n * 3. Unit tests.\n * 4. Test driver.\n * 5. Example.\n * 6. Copyright and license information.\n *\n * Exegesis:\n * \n * Internally, HMMER3 profile scores are in nats: floating point\n * log-odds probabilities, with the log odds taken relative to\n * background residue frequencies, and the log to the base e.\n * \n * The Forward algorithm needs to calculate sums of probabilities.\n * Given two log probabilities A and B, where s1 = \\log\n * \\frac{a}{f}, and s2 = \\log \\frac{b}{g}, we need to\n * calculate C = \\log \\frac{a + b}{h}.\n * \n * The Forward algorithm guarantees that the null model denominator\n * terms f = g = h, because it is always concerned with summing terms\n * that describe different parses of the same target sequence prefix,\n * and the product of the background frequencies for the same sequence\n * prefix is a constant.\n * \n * The naive solution is C = log(e^{A} + e^{B}), but this requires\n * expensive calls to log() and exp().\n * \n * A better solution is C = A + log(1 + e^{-(A-B)}), for A >= B. For\n * sufficiently small B << A, e^-{A-B} becomes less than the\n * machine's FLT_EPSILON, and C ~= A. (This is at about (A-B) >\n * -15.9, for the typical FLT_EPSILON of 1.2e-7.)\n * \n * With some loss of accuracy [1], we can precalculate log(1 +\n * e^{-(A-B)}) for a discretized range of differences (A-B), and\n * compute C = A + table_lookup(A-B). This is what HMMER's\n * p7_FLogsum() function does.\n *\n * This only applies to the generic (serial) implementation.\n * See footnote [2] for discussion of why we remain unable to \n * implement an efficient log-space SIMD vector implementation of\n * Forward.\n *\/\n\n#ifndef __LOGSUM_HPP\n#define __LOGSUM_HPP\n\n#include <cassert>\n#include <cmath>\n\n\/* p7_LOGSUM_SCALE defines the precision of the calculation; the\n * default of 1000.0 means rounding differences to the nearest 0.001\n * nat. p7_LOGSUM_TBL defines the size of the lookup table; the\n * default of 16000 means entries are calculated for differences of 0\n * to 16.000 nats (when p7_LOGSUM_SCALE is 1000.0). e^{-p7_LOGSUM_TBL \/\n * p7_LOGSUM_SCALE} should be on the order of the machine FLT_EPSILON,\n * typically 1.2e-7.\n *\/\n#define p7_LOGSUM_TBL 16000\n#define p7_LOGSUM_SCALE 1000.f\n#define ESL_MAX(a,b) (((a)>(b))?(a):(b))\n#define ESL_MIN(a,b) (((a)<(b))?(a):(b))\n#define eslINFINITY INFINITY\n#define TRUE 1\n#define FALSE 0\n#define eslOK 1\n\nnamespace logsum\n{\n\nstruct p7_FLogsum_Helper\n{\n \/* Function: flogsum_lookup()\n * Synposis: Holds the main lookup table used in logspace sum computations.\n *\n * Purpose: Encapsulate static array inside a function to avoid the need for a separate definition.\n *\/\n static inline float*\n flogsum_lookup(void)\n {\n static float _flogsum_lookup[p7_LOGSUM_TBL]; \/* p7_LOGSUM_TBL=16000: (A-B) = 0..16 nats, steps of 0.001 *\/\n return _flogsum_lookup;\n }\n\n \/* Function: p7_FLogsumInit()\n * Synopsis: Initialize the p7_Logsum() function.\n *\n * Purpose: Initialize the lookup table for <p7_FLogsum()>. \n * This function must be called once before any\n * call to <p7_FLogsum()>.\n * \n * The precision of the lookup table is determined\n * by the compile-time <p7_LOGSUM_TBL> constant.\n *\n * Returns: <eslOK> on success.\n *\/\n static int\n p7_FLogsumInit(void)\n {\n static int firsttime = TRUE;\n if (!firsttime) return eslOK;\n firsttime = FALSE;\n\n int i;\n for (i = 0; i < p7_LOGSUM_TBL; i++)\n {\n flogsum_lookup()[i] = std::log(1. + std::exp((double) -i \/ p7_LOGSUM_SCALE));\n }\n\n return eslOK;\n }\n\n \/* Function: p7_FLogsum()\n * Synopsis: Approximate $\\log(e^a + e^b)$.\n *\n * Purpose: Returns a fast table-driven approximation to\n * $\\log(e^a + e^b)$.\n * \n * Either <a> or <b> (or both) may be $-\\infty$,\n * but neither may be $+\\infty$ or <NaN>.\n *\n * Note: This function is a critical optimization target, because\n * it's in the inner loop of generic Forward() algorithms.\n *\/\n static inline float\n p7_FLogsum(float a, float b)\n {\n \/\/ static object whose constructor initializes the lookup table\n static Table_Initializer _init;\n (void)_init;\n\n const float max = ESL_MAX(a, b);\n const float min = ESL_MIN(a, b);\n\n return (min == -eslINFINITY || (max-min) >= 15.7f)\n ? max\n : max + flogsum_lookup()[(int)((max-min)*p7_LOGSUM_SCALE)];\n }\n\n \/* Function: p7_FLogsumError()\n * Synopsis: Compute absolute error in probability from Logsum.\n *\n * Purpose: Compute the absolute error in probability space\n * resulting from <p7_FLogsum()>'s table lookup \n * approximation: approximation result - exact result.\n * \n * This is of course computable analytically for\n * any <a,b> given <p7_LOGSUM_TBL>; but the function\n * is useful for some routines that want to determine\n * if <p7_FLogsum()> has been compiled in its\n * exact slow mode for debugging purposes. Testing\n * <p7_FLogsumError(-0.4, -0.5) > 0.0001>\n * for example, suffices to detect that the function\n * is compiled in its fast approximation mode given\n * the defaults. \n *\/\n static float\n p7_FLogsumError(float a, float b)\n {\n float approx = p7_FLogsum(a,b);\n float exact = std::log(std::exp(a) + std::exp(b));\n return (std::exp(approx) - std::exp(exact));\n }\n\n \/* Struct: Table_Initializer\n * Purpose: Initialize the lookup table on construction.\n *\n *\/\n struct Table_Initializer\n {\n Table_Initializer()\n {\n p7_FLogsumInit();\n }\n }; \/\/ struct Table_Initializer\n}; \/\/ struct p7_FLogsum_Helper\n\n\/*\n * Publish main methods outside of the helper struct.\n *\/\ninline float p7_FLogsum(float a, float b) { return p7_FLogsum_Helper::p7_FLogsum(a, b); }\ninline float p7_FLogsumError(float a, float b) { return p7_FLogsum_Helper::p7_FLogsumError(a, b); }\n\n} \/\/ namespace logsum\n\n#endif\n\n#ifdef SAMPLE_p7LOGSUM\n\n\/*\n\ng++ -std=c++11 -DSAMPLE_p7LOGSUM -x c++ logsum.hpp -o sample-logsum\n\n*\/\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\nusing namespace logsum;\n\nint main(int argc, char* argv[])\n{\n if (argc != 3)\n {\n cerr << \"use: \" << argv[0] << \" <a> <b>\" << endl;\n return EXIT_FAILURE;\n }\n\n float a;\n float b;\n float result;\n\n istringstream(argv[1]) >> a;\n istringstream(argv[2]) >> b;\n\n result = p7_FLogsum(a, b);\n cout << \"p7_FLogsum(\" << a << \", \" << b << \") = \" << result << endl;\n\n result = log(exp(a) + exp(b));\n cout << \"log(exp(\" << a << \") + exp(\" << b << \")) = \" << result << endl;\n\n cout << \"Absolute error in probability: \" << p7_FLogsumError(a, b) << endl;\n}\n\n#endif\n\n#ifdef BENCHMARK_p7LOGSUM\n\n\/*\n\nCompare with the original logsum.{h,cpp} (not included in this repo).\nAssuming they are in \/somedir.\n\nCompile:\nDIR=\/somedir; g++ -std=c++11 -DBENCHMARK_p7LOGSUM -x c++ -I${DIR} logsum.hpp ${DIR}\/logsum.cpp -o benchmark-logsum\n\nRun:\n.\/benchmark-logsum 42 0\n.\/benchmark-logsum 42 1\n\n*\/\n\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <set>\n#include <sstream>\n#include <vector>\n\n#include \"logsum.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n if (argc < 3)\n {\n cerr << \"use: \" << argv[0] << \" <seed> <version>\" << endl\n << \"where <version> is 0 for old, 1 for new\" << endl;\n return EXIT_FAILURE;\n }\n size_t seed = 0;\n unsigned version = 0;\n istringstream(argv[1]) >> seed;\n istringstream(argv[2]) >> version;\n if (seed == 0)\n {\n seed = chrono::high_resolution_clock::now().time_since_epoch().count();\n }\n clog << \"seed: \" << seed << endl;\n clog << \"version: \" << version << endl;\n const unsigned n = 1000000;\n set< float > s;\n mt19937 rg(seed);\n uniform_real_distribution< float > unif;\n for (unsigned i = 0; i < n; ++i)\n {\n s.insert(unif(rg));\n }\n p7_FLogsumInit();\n\n \/\/ start timer\n auto start_time = chrono::high_resolution_clock::now();\n\n if (version == 0)\n {\n while (s.size() > 1)\n {\n float a = *s.begin();\n s.erase(s.begin());\n float b = *s.begin();\n s.erase(s.begin());\n s.insert(::p7_FLogsum(a, b));\n }\n }\n else if (version == 1)\n {\n while (s.size() > 1)\n {\n float a = *s.begin();\n s.erase(s.begin());\n float b = *s.begin();\n s.erase(s.begin());\n s.insert(logsum::p7_FLogsum(a, b));\n }\n }\n\n \/\/ end timer\n auto end_time = chrono::high_resolution_clock::now();\n\n cout << \"time: \" << chrono::duration_cast< chrono::milliseconds >(end_time - start_time).count() << endl\n << \"result: \" << *s.begin() << endl;\n}\n\n#endif\n<commit_msg>tweak: round to nearest table index to improve approximation<commit_after>\/\/\n\/\/ logsum -- a port of Sean Eddy's fast table-driven log sum\n\/\/ This code was originally part of HMMER. This version is used with \n\/\/ Sean Eddy's permission as public domain code.\n\/\/\n\/\/ Modification Notice\n\/\/\n\/\/ By: Matei David, Ontario Institute for Cancer Research\n\/\/ When: 2015\n\/\/ Reason:\n\/\/ Reorganized as C++ header-only library,\n\/\/ with implicit lookup table initialization.\n\/\/\n\n\/* p7_FLogsum() function used in the Forward() algorithm.\n * \n * Contents:\n * 1. Floating point log sum.\n * 2. Benchmark driver.\n * 3. Unit tests.\n * 4. Test driver.\n * 5. Example.\n * 6. Copyright and license information.\n *\n * Exegesis:\n * \n * Internally, HMMER3 profile scores are in nats: floating point\n * log-odds probabilities, with the log odds taken relative to\n * background residue frequencies, and the log to the base e.\n * \n * The Forward algorithm needs to calculate sums of probabilities.\n * Given two log probabilities A and B, where s1 = \\log\n * \\frac{a}{f}, and s2 = \\log \\frac{b}{g}, we need to\n * calculate C = \\log \\frac{a + b}{h}.\n * \n * The Forward algorithm guarantees that the null model denominator\n * terms f = g = h, because it is always concerned with summing terms\n * that describe different parses of the same target sequence prefix,\n * and the product of the background frequencies for the same sequence\n * prefix is a constant.\n * \n * The naive solution is C = log(e^{A} + e^{B}), but this requires\n * expensive calls to log() and exp().\n * \n * A better solution is C = A + log(1 + e^{-(A-B)}), for A >= B. For\n * sufficiently small B << A, e^-{A-B} becomes less than the\n * machine's FLT_EPSILON, and C ~= A. (This is at about (A-B) >\n * -15.9, for the typical FLT_EPSILON of 1.2e-7.)\n * \n * With some loss of accuracy [1], we can precalculate log(1 +\n * e^{-(A-B)}) for a discretized range of differences (A-B), and\n * compute C = A + table_lookup(A-B). This is what HMMER's\n * p7_FLogsum() function does.\n *\n * This only applies to the generic (serial) implementation.\n * See footnote [2] for discussion of why we remain unable to \n * implement an efficient log-space SIMD vector implementation of\n * Forward.\n *\/\n\n#ifndef __LOGSUM_HPP\n#define __LOGSUM_HPP\n\n#include <cassert>\n#include <cmath>\n\n\/* p7_LOGSUM_SCALE defines the precision of the calculation; the\n * default of 1000.0 means rounding differences to the nearest 0.001\n * nat. p7_LOGSUM_TBL defines the size of the lookup table; the\n * default of 16000 means entries are calculated for differences of 0\n * to 16.000 nats (when p7_LOGSUM_SCALE is 1000.0). e^{-p7_LOGSUM_TBL \/\n * p7_LOGSUM_SCALE} should be on the order of the machine FLT_EPSILON,\n * typically 1.2e-7.\n *\/\n#define p7_LOGSUM_TBL 16000\n#define p7_LOGSUM_SCALE 1000.f\n#define ESL_MAX(a,b) (((a)>(b))?(a):(b))\n#define ESL_MIN(a,b) (((a)<(b))?(a):(b))\n#define eslINFINITY INFINITY\n#define TRUE 1\n#define FALSE 0\n#define eslOK 1\n\nnamespace logsum\n{\n\nstruct p7_FLogsum_Helper\n{\n \/* Function: flogsum_lookup()\n * Synposis: Holds the main lookup table used in logspace sum computations.\n *\n * Purpose: Encapsulate static array inside a function to avoid the need for a separate definition.\n *\/\n static inline float*\n flogsum_lookup(void)\n {\n static float _flogsum_lookup[p7_LOGSUM_TBL]; \/* p7_LOGSUM_TBL=16000: (A-B) = 0..16 nats, steps of 0.001 *\/\n return _flogsum_lookup;\n }\n\n \/* Function: p7_FLogsumInit()\n * Synopsis: Initialize the p7_Logsum() function.\n *\n * Purpose: Initialize the lookup table for <p7_FLogsum()>. \n * This function must be called once before any\n * call to <p7_FLogsum()>.\n * \n * The precision of the lookup table is determined\n * by the compile-time <p7_LOGSUM_TBL> constant.\n *\n * Returns: <eslOK> on success.\n *\/\n static int\n p7_FLogsumInit(void)\n {\n static int firsttime = TRUE;\n if (!firsttime) return eslOK;\n firsttime = FALSE;\n\n int i;\n for (i = 0; i < p7_LOGSUM_TBL; i++)\n {\n flogsum_lookup()[i] = std::log(1. + std::exp((double) -i \/ p7_LOGSUM_SCALE));\n }\n\n return eslOK;\n }\n\n \/* Function: p7_FLogsum()\n * Synopsis: Approximate $\\log(e^a + e^b)$.\n *\n * Purpose: Returns a fast table-driven approximation to\n * $\\log(e^a + e^b)$.\n * \n * Either <a> or <b> (or both) may be $-\\infty$,\n * but neither may be $+\\infty$ or <NaN>.\n *\n * Note: This function is a critical optimization target, because\n * it's in the inner loop of generic Forward() algorithms.\n *\/\n static inline float\n p7_FLogsum(float a, float b)\n {\n \/\/ static object whose constructor initializes the lookup table\n static Table_Initializer _init;\n (void)_init;\n\n const float max = ESL_MAX(a, b);\n const float min = ESL_MIN(a, b);\n\n int idx = std::round((max-min)*p7_LOGSUM_SCALE);\n return (min == -eslINFINITY || idx >= p7_LOGSUM_TBL)\n ? max\n : max + flogsum_lookup()[idx];\n }\n\n \/* Function: p7_FLogsumError()\n * Synopsis: Compute absolute error in probability from Logsum.\n *\n * Purpose: Compute the absolute error in probability space\n * resulting from <p7_FLogsum()>'s table lookup \n * approximation: approximation result - exact result.\n * \n * This is of course computable analytically for\n * any <a,b> given <p7_LOGSUM_TBL>; but the function\n * is useful for some routines that want to determine\n * if <p7_FLogsum()> has been compiled in its\n * exact slow mode for debugging purposes. Testing\n * <p7_FLogsumError(-0.4, -0.5) > 0.0001>\n * for example, suffices to detect that the function\n * is compiled in its fast approximation mode given\n * the defaults. \n *\/\n static float\n p7_FLogsumError(float a, float b)\n {\n float approx = p7_FLogsum(a,b);\n float exact = std::log(std::exp(a) + std::exp(b));\n return (std::exp(approx) - std::exp(exact));\n }\n\n \/* Struct: Table_Initializer\n * Purpose: Initialize the lookup table on construction.\n *\n *\/\n struct Table_Initializer\n {\n Table_Initializer()\n {\n p7_FLogsumInit();\n }\n }; \/\/ struct Table_Initializer\n}; \/\/ struct p7_FLogsum_Helper\n\n\/*\n * Publish main methods outside of the helper struct.\n *\/\ninline float p7_FLogsum(float a, float b) { return p7_FLogsum_Helper::p7_FLogsum(a, b); }\ninline float p7_FLogsumError(float a, float b) { return p7_FLogsum_Helper::p7_FLogsumError(a, b); }\n\n} \/\/ namespace logsum\n\n#endif\n\n#ifdef SAMPLE_p7LOGSUM\n\n\/*\n\ng++ -std=c++11 -DSAMPLE_p7LOGSUM -x c++ logsum.hpp -o sample-logsum\n\n*\/\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\nusing namespace logsum;\n\nint main(int argc, char* argv[])\n{\n if (argc != 3)\n {\n cerr << \"use: \" << argv[0] << \" <a> <b>\" << endl;\n return EXIT_FAILURE;\n }\n\n float a;\n float b;\n float result;\n\n istringstream(argv[1]) >> a;\n istringstream(argv[2]) >> b;\n\n result = p7_FLogsum(a, b);\n cout << \"p7_FLogsum(\" << a << \", \" << b << \") = \" << result << endl;\n\n result = log(exp(a) + exp(b));\n cout << \"log(exp(\" << a << \") + exp(\" << b << \")) = \" << result << endl;\n\n cout << \"Absolute error in probability: \" << p7_FLogsumError(a, b) << endl;\n}\n\n#endif\n\n#ifdef BENCHMARK_p7LOGSUM\n\n\/*\n\nCompare with the original logsum.{h,cpp} (not included in this repo).\nAssuming they are in \/somedir.\n\nCompile:\nDIR=\/somedir; g++ -std=c++11 -DBENCHMARK_p7LOGSUM -x c++ -I${DIR} logsum.hpp ${DIR}\/logsum.cpp -o benchmark-logsum\n\nRun:\n.\/benchmark-logsum 42 0\n.\/benchmark-logsum 42 1\n\n*\/\n\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <set>\n#include <sstream>\n#include <vector>\n\n#include \"logsum.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n if (argc < 3)\n {\n cerr << \"use: \" << argv[0] << \" <seed> <version>\" << endl\n << \"where <version> is 0 for old, 1 for new\" << endl;\n return EXIT_FAILURE;\n }\n size_t seed = 0;\n unsigned version = 0;\n istringstream(argv[1]) >> seed;\n istringstream(argv[2]) >> version;\n if (seed == 0)\n {\n seed = chrono::high_resolution_clock::now().time_since_epoch().count();\n }\n clog << \"seed: \" << seed << endl;\n clog << \"version: \" << version << endl;\n const unsigned n = 1000000;\n set< float > s;\n mt19937 rg(seed);\n uniform_real_distribution< float > unif;\n for (unsigned i = 0; i < n; ++i)\n {\n s.insert(unif(rg));\n }\n p7_FLogsumInit();\n\n \/\/ start timer\n auto start_time = chrono::high_resolution_clock::now();\n\n if (version == 0)\n {\n while (s.size() > 1)\n {\n float a = *s.begin();\n s.erase(s.begin());\n float b = *s.begin();\n s.erase(s.begin());\n s.insert(::p7_FLogsum(a, b));\n }\n }\n else if (version == 1)\n {\n while (s.size() > 1)\n {\n float a = *s.begin();\n s.erase(s.begin());\n float b = *s.begin();\n s.erase(s.begin());\n s.insert(logsum::p7_FLogsum(a, b));\n }\n }\n\n \/\/ end timer\n auto end_time = chrono::high_resolution_clock::now();\n\n cout << \"time: \" << chrono::duration_cast< chrono::milliseconds >(end_time - start_time).count() << endl\n << \"result: \" << *s.begin() << endl;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"comments.h\"\n#include \"commentTab.h\"\n#include <sqlite3.h>\n#include <stdexcept>\n#include <stdlib.h>\n#include <stdio.h>\n\nusing namespace std;\n\ntypedef unsigned char byte;\n\nstatic sqlite3* sDB;\n\n#define SQLT(func) do { int _res = (func); if(_res != SQLITE_OK) {\\\n\tsqlite3_finalize(stmt); stmt = NULL;\\\n\tprintf(\"%s:%i: %s\\n\", __FILE__, __LINE__, sqlite3_errmsg(sDB));\\\n\tthrow logic_error(\"sqlite\"); } } while(0)\n\nstatic void closeDb() {\n\tif(sDB) {\n\t\tsqlite3_stmt* stmt = NULL;\t\/\/dummy\n\t\tSQLT(sqlite3_close(sDB));\n\t}\n}\n\nTab* getComments(const char* type, int id) {\n\tsqlite3_stmt* stmt = NULL;\n\tif(!sDB) {\n\t\tSQLT(sqlite3_open(\"..\/wowfoot-import\/imports.db\", &sDB));\n\t\tatexit(&closeDb);\n\t}\n\n\tchar query[1024];\n\tsprintf(query, \"SELECT user, body, rating, date, indent\"\n\t\t\" FROM comments\"\n\t\t\" INNER JOIN %s_comments on commentId = id\"\n\t\t\" WHERE %s_comments.entry = %i\",\n\t\ttype, type, id);\n\n\tSQLT(sqlite3_prepare_v2(sDB, query, -1, &stmt, NULL));\n\n\tint res;\n\tcommentTabChtml* ct = new commentTabChtml();\n\twhile((res = sqlite3_step(stmt)) == SQLITE_ROW) {\n\t\tComment c;\n\t\tc.user = (const char*)sqlite3_column_text(stmt, 0);\n\t\tc.body = (const char*)sqlite3_column_text(stmt, 1);\n\t\tc.rating = sqlite3_column_int(stmt, 2);\n\t\tc.date = (const char*)sqlite3_column_text(stmt, 3);\n\t\tc.indent = sqlite3_column_int(stmt, 4);\n\t\tct->mComments.push_back(c);\n\t}\n\tif(res != SQLITE_DONE) {\n\t\tSQLT(res);\n\t}\n\tSQLT(sqlite3_finalize(stmt));\n\tct->id = \"comments\";\n\tct->title = \"Comments\";\n\tct->count = ct->mComments.size();\n\treturn ct;\n}\n<commit_msg>Started formatting comments.<commit_after>#include \"comments.h\"\n#include \"commentTab.h\"\n#include <sqlite3.h>\n#include <stdexcept>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sstream>\n#include <string.h>\n\nusing namespace std;\n\ntypedef unsigned char byte;\n\nstatic sqlite3* sDB;\n\n#define SQLT(func) do { int _res = (func); if(_res != SQLITE_OK) {\\\n\tsqlite3_finalize(stmt); stmt = NULL;\\\n\tprintf(\"%s:%i: %s\\n\", __FILE__, __LINE__, sqlite3_errmsg(sDB));\\\n\tthrow logic_error(\"sqlite\"); } } while(0)\n\nstatic void closeDb() {\n\tif(sDB) {\n\t\tsqlite3_stmt* stmt = NULL;\t\/\/dummy\n\t\tSQLT(sqlite3_close(sDB));\n\t}\n}\n\nstatic string formatComment(const char* src);\nstatic void formatTag(ostream& o, const char* tag, size_t len);\nstatic void formatUrl(ostream& o, const char* url, size_t len);\n\nTab* getComments(const char* type, int id) {\n\tsqlite3_stmt* stmt = NULL;\n\tif(!sDB) {\n\t\tSQLT(sqlite3_open(\"..\/wowfoot-import\/imports.db\", &sDB));\n\t\tatexit(&closeDb);\n\t}\n\n\tchar query[1024];\n\tsprintf(query, \"SELECT user, body, rating, date, indent\"\n\t\t\" FROM comments\"\n\t\t\" INNER JOIN %s_comments on commentId = id\"\n\t\t\" WHERE %s_comments.entry = %i\",\n\t\ttype, type, id);\n\n\tSQLT(sqlite3_prepare_v2(sDB, query, -1, &stmt, NULL));\n\n\tint res;\n\tcommentTabChtml* ct = new commentTabChtml();\n\twhile((res = sqlite3_step(stmt)) == SQLITE_ROW) {\n\t\tComment c;\n\t\tc.user = (const char*)sqlite3_column_text(stmt, 0);\n\t\tc.body = formatComment((const char*)sqlite3_column_text(stmt, 1));\n\t\tc.rating = sqlite3_column_int(stmt, 2);\n\t\tc.date = (const char*)sqlite3_column_text(stmt, 3);\n\t\tc.indent = sqlite3_column_int(stmt, 4);\n\t\tct->mComments.push_back(c);\n\t}\n\tif(res != SQLITE_DONE) {\n\t\tSQLT(res);\n\t}\n\tSQLT(sqlite3_finalize(stmt));\n\tct->id = \"comments\";\n\tct->title = \"Comments\";\n\tct->count = ct->mComments.size();\n\treturn ct;\n}\n\nstatic string formatComment(const char* src) {\n\tostringstream o;\n\tconst char* ptr = src;\n\twhile(*ptr) {\n\t\tchar c = *ptr;\n\t\tptr++;\n\t\tif(c == '[') {\t\/\/ start tag\n\t\t\tconst char* endPtr = strchr(ptr, ']');\n\t\t\tif(!endPtr) {\n\t\t\t\to << (ptr-1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tformatTag(o, ptr, endPtr - ptr);\n\t\t\tptr = endPtr + 1;\n\t\t} else {\n\t\t\to << c;\n\t\t}\n\t}\n\treturn o.str();\n}\n\n#define COMPLEX_TAG(src, dst) if(strncmp(src, tag, len) == 0) { o << dst; return; }\n#define SIMPLE_TAG(t) if(strncmp(t, tag, len) == 0) { o << \"<\" t \">\"; return; }\\\nif(strncmp(\"\/\" t, tag, len) == 0) { o << \"<\/\" t \">\"; return; }\n\nstatic void formatTag(ostream& o, const char* tag, size_t len) {\n\tif(strncmp(\"b\", tag, len) == 0) {\n\t\to << \"<b>\";\n\t\treturn;\n\t}\n\tSIMPLE_TAG(\"b\");\n\tSIMPLE_TAG(\"i\");\n\tSIMPLE_TAG(\"u\");\n\tSIMPLE_TAG(\"li\");\n\tCOMPLEX_TAG(\"ul\", \"<\/p><ul>\");\n\tCOMPLEX_TAG(\"\/ul\", \"<\/ul><p>\");\n\tCOMPLEX_TAG(\"ol\", \"<\/p><ol>\");\n\tCOMPLEX_TAG(\"\/ol\", \"<\/ol><p>\");\n\n\tif(strncmp(\"url=\", tag, 4) == 0) {\n\t\tconst char* url = tag + 4;\n\t\tsize_t urlLen = len - 4;\n\t\tprintf(\"%.*s\\n\", (int)urlLen, url);\n\t\to << \"<a href=\\\"\";\n\t\tformatUrl(o, url, urlLen);\n\t\to << \"\\\">\";\n\t\treturn;\n\t}\n\tCOMPLEX_TAG(\"\/url\", \"<\/a>\");\n\n\t\/\/ unknown tag\n\to << \"[\"<<o.write(tag, len)<<\"]\";\n}\n\nstatic void formatUrl(ostream& o, const char* url, size_t len) {\n\t\/\/ s\/http:\/\/*.wowhead.com\/\n\tconst char* wh = \".wowhead.com\/\";\n\tconst char* whf = strstr(url, wh);\n\tif(whf) {\n\t\tconst char* path = whf + strlen(wh);\n\t\tif(*path == '?')\n\t\t\tpath += 1;\n\t\tsize_t pathLen = len - (path - url);\n\t\to.write(path, pathLen);\n\t\treturn;\n\t}\n\n\to.write(url, len);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ibnu.yahya@toroo.org\n\n#include \"ign.h\"\n#include \"fs.h\"\n#include \"cmath\"\n#include <QtCore\/QVariant>\n#include <iostream>\nusing namespace std;\nign::ign(QObject *parent)\n : QObject(parent),\n m_sqldrv(0),\n m_ignsystem(0)\n{\n this->version = \"1.1.1\";\n frame = web.page()->mainFrame();\n connect(frame,SIGNAL(javaScriptWindowObjectCleared()), SLOT(ignJS()));\n this->filesystem = new fs;\n this->dl = new QtDownload;\n\n QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);\n web.settings()->setAttribute(QWebSettings::PluginsEnabled, true);\n web.settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);\n web.settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);\n web.settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, true);\n web.settings()->setAttribute(QWebSettings::JavascriptEnabled,true);\n web.settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows,true);\n web.settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard,true);\n web.settings()->setAttribute(QWebSettings::JavaEnabled,true);\n web.settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled,true);\n web.settings()->setAttribute(QWebSettings::WebGLEnabled,true);\n web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,false);\n \/\/webstorage\n QString home = QDir::homePath();\n home += \"\/.ignsdk\";\n web.settings()->setLocalStoragePath(home);\n web.settings()->enablePersistentStorage(home);\n web.settings()->setOfflineWebApplicationCachePath(home);\n \/\/stylesheet default\n web.settings()->setUserStyleSheetUrl(QUrl(\"qrc:\/css\/ign.css\"));\n \/\/config mode disable\n web.page()->action(QWebPage::Back)->setVisible(false);\n web.page()->action(QWebPage::Forward)->setVisible(false);\n web.page()->action(QWebPage::Reload)->setVisible(false);\n web.page()->action(QWebPage::Stop)->setVisible(false);\n \/\/set fullscrean mode default to false\n fullscreen = false;\n\n \/\/web.setWindowOpacity(0.1);\n}\n\nvoid ign::ignJS(){\n this->frame->addToJavaScriptWindowObject(\"ign\",this);\n}\nvoid ign::getToggleFullScreen(){\n if(this->fullscreen){\n this->web.showNormal();\n this->fullscreen = false;\n }\n else{\n this->web.showFullScreen();\n this->fullscreen = true;\n }\n}\n\nvoid ign::getFullScreen(bool screen){\n if(screen){\n this->web.showFullScreen();\n this->fullscreen = true;\n }\n else {\n this->web.showNormal();\n this->fullscreen = false;\n }\n}\n\nvoid ign::render(QString w){\n QString pwd(\"\");\n QString url_fix;\n char * PWD;\n PWD = getenv (\"PWD\");\n pwd.append(PWD);\n QStringList url_exp = w.split(\"\/\");\n if(url_exp.at(0) == \"http:\"){\n url_fix = w;\n }\n else if(url_exp.at(0) == \"..\"){\n url_fix = \"file:\/\/\"+pwd+\"\/\"+w;\n }\n else {\n url_fix = \"file:\/\/\"+w;\n }\n QUrl url(w);\n this->web.load(url_fix);\n qDebug() << w << url;\n}\n\nvoid ign::show(){\n this->web.show();\n}\n\nvoid ign::showMaximized(){\n this->web.showMaximized();\n}\n\nvoid ign::showMinimized(){\n this->web.showMinimized();\n}\n\nvoid ign::showMessage(const QString &msg)\n{\n QMessageBox::information(0, \"Information\", msg);\n}\n\nvoid ign::quit(){\n this->web.close();\n}\n\nvoid ign::back(){\n this->web.page()->action(QWebPage::Back)->setVisible(true);\n}\n\nvoid ign::forward(){\n this->web.page()->action(QWebPage::Forward)->setVisible(true);\n}\n\nvoid ign::stop(){\n this->web.page()->action(QWebPage::Stop)->setVisible(true);\n}\n\nvoid ign::reload(){\n this->web.page()->action(QWebPage::Reload)->setVisible(true);\n}\n\nvoid ign::setDev(bool v){\n this->web.settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, v);\n}\n\nvoid ign::websecurity(bool c){\n web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,c);\n}\n\nvoid ign::widgetSizeMax(int w, int h){\n this->web.setMaximumSize(w,h);\n}\n\nvoid ign::widgetSizeMin(int w, int h){\n this->web.setMinimumSize(w,h);\n}\n\nvoid ign::widgetSize(int w, int h){\n this->web.resize(w,h);\n}\n\nvoid ign::widgetNoFrame(){\n this->web.setWindowFlags(Qt::FramelessWindowHint);\n}\n\nvoid ign::widgetTransparent(){\n QPalette pal = this->web.palette();\n pal.setBrush(QPalette::Base, Qt::transparent);\n this->web.setPalette(pal);\n this->web.setAttribute(Qt::WA_OpaquePaintEvent, false);\n this->web.setAttribute(Qt::WA_TranslucentBackground, true);\n}\n\nQString ign::cliOut(const QString& cli){\n QProcess os;\n os.start(cli);\n int pid = os.pid();\n qDebug() << pid;\n os.waitForFinished(-1);\n return os.readAllStandardOutput();\n\n}\n\nvoid ign::exec(const QString &cli){\n QProcess os;\n os.startDetached(\"\/bin\/sh -c \\\"\"+cli+\"\\\"\");\n}\n\nQString ign::loadBin(const QString &script){\n QStringList list = this->pathApp.split(\"\/\");\n\n QString pwd(\"\");\n char * PWD;\n PWD = getenv (\"PWD\");\n pwd.append(PWD);\n\n QString path_bin;\n if(list.at(0) != \"\"){\n path_bin = pwd+\"\/\"+this->pathApp;\n }\n else{\n path_bin = this->pathApp;\n }\n return path_bin+\"\/bin\/\"+script;\n}\n\nvoid ign::mousePressEvent(QMouseEvent *event)\n{\n qDebug()<<event->type();\n}\n\nvoid ign::config(QString path){\n QFile config_file;\n QDir::setCurrent(path);\n config_file.setFileName(\"ignsdk.json\");\n QByteArray config;\n if(config_file.open(QIODevice::ReadOnly)){\n config = config_file.readAll();\n\n QJsonParseError *err = new QJsonParseError();\n\n QJsonDocument ignjson = QJsonDocument::fromJson(config, err);\n\n if (err->error != 0) {\n qDebug() << err->errorString();\n exit (1);\n }\n\n QJsonObject jObject = ignjson.object();\n\n \/\/convert the json object to variantmap\n QVariantMap result = jObject.toVariantMap();\n\n QVariantMap configure = result[\"config\"].toMap();\n if(configure[\"debug\"].toBool()){\n this->setDev(true);\n }\n if(configure[\"websecurity\"].toBool()){\n this->websecurity(true);\n }\n if(configure[\"name\"].toString() != \"\"){\n this->web.setWindowTitle(configure[\"name\"].toString());\n }\n\n QVariantMap window = result[\"window\"].toMap();\n if(window[\"transparent\"].toBool()){\n this->widgetTransparent();\n }\n if(window[\"noframe\"].toBool()){\n this->widgetNoFrame();\n }\n if(window[\"fullscreen\"].toBool()){\n this->getToggleFullScreen();\n }\n if(window[\"maximize\"].toBool()){\n this->showMaximized();\n }\n if(window[\"width\"].toInt() != 0){\n if(window[\"height\"].toInt() != 0){\n this->widgetSize(window[\"width\"].toInt(),window[\"height\"].toInt());\n }\n }\n\n foreach (QVariant button, result[\"button\"].toList()) {\n\n if (button.toString() == \"back\"){\n this->back();\n }\n if (button.toString() == \"forward\"){\n this->forward();\n }\n if (button.toString() == \"stop\"){\n this->stop();\n }\n if (button.toString() == \"reload\"){\n this->reload();\n }\n\n }\n\n }\n\n config_file.close();\n}\n\nQString ign::hash(const QString &data,QString hash_func){\n QByteArray hash;\n QByteArray byteArray = data.toLatin1();\n if(hash_func == \"md4\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md4);\n }\n else if(hash_func == \"md5\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md5);\n }\n else if(hash_func == \"sha1\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha1);\n }\n\n return hash.toHex();\n}\n\nQString ign::homePath(){\n return this->filesystem->home_path();\n}\n\nbool ign::createFile(const QString &path, const QString &data){\n return this->filesystem->create_file(path,data);\n}\n\nQString ign::readFile(const QString &path){\n return this->filesystem->read_file(path);\n}\n\nvoid ign::saveFile(const QByteArray &data, QString filename, QString path){\n QByteArray byteArray = QByteArray::fromBase64(data);\n QString home;\n home = path+\"\/\"+filename;\n QFile localFile(home);\n if (!localFile.open(QIODevice::WriteOnly))\n return;\n localFile.write(byteArray);\n localFile.close();\n}\n\nvoid ign::download(QString data,QString path){\n this->dl = new QtDownload;\n this->dl->setTarget(data);\n this->dl->save(path);\n this->dl->download();\n connect(this->dl, SIGNAL(download_signal(qint64,qint64)), this, SLOT(download_signal(qint64,qint64)));\n}\n\nvoid ign::download_signal(qint64 recieved, qint64 total){\n emit downloadProgress(recieved,total);\n}\n\n\/*IGN SQL*\/\nQObject *ign::sql(){\n if(!m_sqldrv)\n m_sqldrv = new ignsql;\n return m_sqldrv;\n}\n\n\/*IGN SYSTEM*\/\nQObject *ign::sys(){\n if(!m_ignsystem){\n m_ignsystem = new ignsystem;\n }\n return m_ignsystem;\n}\n\n\/*IGN FILESYSTEM*\/\nbool ign::mkdir(const QString &path){\n return this->filesystem->dir(path,\"create\");\n}\n\nbool ign::dirExist(const QString &path){\n return this->filesystem->dir(path,\"check\");\n}\n\nbool ign::rmdir(const QString &path){\n return this->filesystem->dir(path,\"remove\");\n}\n\nbool ign::fileExist(const QString &path){\n return this->filesystem->file(path,\"check\");\n}\n\nbool ign::fileRemove(const QString &path){\n return this->filesystem->file(path,\"remove\");\n}\n\n\/\/Check version\nQString ign::sdkVersion(){\n return this->version;\n}\n\n\/*void ign::mousePressEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n QMessageBox::information(0, \"Information\", \"press\");\n mMoving = true;\n mLastMousePosition = event->pos();\n }\n}\n\nvoid ign::mouseMoveEvent(QMouseEvent *event)\n{\n if( event->buttons().testFlag(Qt::LeftButton) && mMoving)\n {\n this->web.move(this->web.pos() + (event->pos() - mLastMousePosition));\n mLastMousePosition = event->pos();\n }\n}\n\nvoid ign::mouseReleaseEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n mMoving = false;\n }\n}*\/\n<commit_msg>FIX: relative path if path url is null<commit_after>\/\/ibnu.yahya@toroo.org\n\n#include \"ign.h\"\n#include \"fs.h\"\n#include \"cmath\"\n#include <QtCore\/QVariant>\n#include <iostream>\nusing namespace std;\nign::ign(QObject *parent)\n : QObject(parent),\n m_sqldrv(0),\n m_ignsystem(0)\n{\n this->version = \"1.1.1\";\n frame = web.page()->mainFrame();\n connect(frame,SIGNAL(javaScriptWindowObjectCleared()), SLOT(ignJS()));\n this->filesystem = new fs;\n this->dl = new QtDownload;\n\n QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);\n web.settings()->setAttribute(QWebSettings::PluginsEnabled, true);\n web.settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);\n web.settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);\n web.settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, true);\n web.settings()->setAttribute(QWebSettings::JavascriptEnabled,true);\n web.settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows,true);\n web.settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard,true);\n web.settings()->setAttribute(QWebSettings::JavaEnabled,true);\n web.settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled,true);\n web.settings()->setAttribute(QWebSettings::WebGLEnabled,true);\n web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,false);\n \/\/webstorage\n QString home = QDir::homePath();\n home += \"\/.ignsdk\";\n web.settings()->setLocalStoragePath(home);\n web.settings()->enablePersistentStorage(home);\n web.settings()->setOfflineWebApplicationCachePath(home);\n \/\/stylesheet default\n web.settings()->setUserStyleSheetUrl(QUrl(\"qrc:\/css\/ign.css\"));\n \/\/config mode disable\n web.page()->action(QWebPage::Back)->setVisible(false);\n web.page()->action(QWebPage::Forward)->setVisible(false);\n web.page()->action(QWebPage::Reload)->setVisible(false);\n web.page()->action(QWebPage::Stop)->setVisible(false);\n \/\/set fullscrean mode default to false\n fullscreen = false;\n\n \/\/web.setWindowOpacity(0.1);\n}\n\nvoid ign::ignJS(){\n this->frame->addToJavaScriptWindowObject(\"ign\",this);\n}\nvoid ign::getToggleFullScreen(){\n if(this->fullscreen){\n this->web.showNormal();\n this->fullscreen = false;\n }\n else{\n this->web.showFullScreen();\n this->fullscreen = true;\n }\n}\n\nvoid ign::getFullScreen(bool screen){\n if(screen){\n this->web.showFullScreen();\n this->fullscreen = true;\n }\n else {\n this->web.showNormal();\n this->fullscreen = false;\n }\n}\n\nvoid ign::render(QString w){\n QString pwd(\"\");\n QString url_fix;\n char * PWD;\n PWD = getenv (\"PWD\");\n pwd.append(PWD);\n QStringList url_exp = w.split(\"\/\");\n if(url_exp.at(0) == \"http:\"){\n url_fix = w;\n }\n else if(url_exp.at(0) == \"..\"){\n url_fix = \"file:\/\/\"+pwd+\"\/\"+w;\n }\n else if(url_exp.at(0) == \"\"){\n url_fix = \"file:\/\/\"+w;\n }\n else {\n url_fix = \"file:\/\/\"+pwd+\"\/\"+w;\n }\n QUrl url(w);\n this->web.load(url_fix);\n qDebug() << w << url;\n}\n\nvoid ign::show(){\n this->web.show();\n}\n\nvoid ign::showMaximized(){\n this->web.showMaximized();\n}\n\nvoid ign::showMinimized(){\n this->web.showMinimized();\n}\n\nvoid ign::showMessage(const QString &msg)\n{\n QMessageBox::information(0, \"Information\", msg);\n}\n\nvoid ign::quit(){\n this->web.close();\n}\n\nvoid ign::back(){\n this->web.page()->action(QWebPage::Back)->setVisible(true);\n}\n\nvoid ign::forward(){\n this->web.page()->action(QWebPage::Forward)->setVisible(true);\n}\n\nvoid ign::stop(){\n this->web.page()->action(QWebPage::Stop)->setVisible(true);\n}\n\nvoid ign::reload(){\n this->web.page()->action(QWebPage::Reload)->setVisible(true);\n}\n\nvoid ign::setDev(bool v){\n this->web.settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, v);\n}\n\nvoid ign::websecurity(bool c){\n web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,c);\n}\n\nvoid ign::widgetSizeMax(int w, int h){\n this->web.setMaximumSize(w,h);\n}\n\nvoid ign::widgetSizeMin(int w, int h){\n this->web.setMinimumSize(w,h);\n}\n\nvoid ign::widgetSize(int w, int h){\n this->web.resize(w,h);\n}\n\nvoid ign::widgetNoFrame(){\n this->web.setWindowFlags(Qt::FramelessWindowHint);\n}\n\nvoid ign::widgetTransparent(){\n QPalette pal = this->web.palette();\n pal.setBrush(QPalette::Base, Qt::transparent);\n this->web.setPalette(pal);\n this->web.setAttribute(Qt::WA_OpaquePaintEvent, false);\n this->web.setAttribute(Qt::WA_TranslucentBackground, true);\n}\n\nQString ign::cliOut(const QString& cli){\n QProcess os;\n os.start(cli);\n int pid = os.pid();\n qDebug() << pid;\n os.waitForFinished(-1);\n return os.readAllStandardOutput();\n\n}\n\nvoid ign::exec(const QString &cli){\n QProcess os;\n os.startDetached(\"\/bin\/sh -c \\\"\"+cli+\"\\\"\");\n}\n\nQString ign::loadBin(const QString &script){\n QStringList list = this->pathApp.split(\"\/\");\n\n QString pwd(\"\");\n char * PWD;\n PWD = getenv (\"PWD\");\n pwd.append(PWD);\n\n QString path_bin;\n if(list.at(0) != \"\"){\n path_bin = pwd+\"\/\"+this->pathApp;\n }\n else{\n path_bin = this->pathApp;\n }\n return path_bin+\"\/bin\/\"+script;\n}\n\nvoid ign::mousePressEvent(QMouseEvent *event)\n{\n qDebug()<<event->type();\n}\n\nvoid ign::config(QString path){\n QFile config_file;\n QDir::setCurrent(path);\n config_file.setFileName(\"ignsdk.json\");\n QByteArray config;\n if(config_file.open(QIODevice::ReadOnly)){\n config = config_file.readAll();\n\n QJsonParseError *err = new QJsonParseError();\n\n QJsonDocument ignjson = QJsonDocument::fromJson(config, err);\n\n if (err->error != 0) {\n qDebug() << err->errorString();\n exit (1);\n }\n\n QJsonObject jObject = ignjson.object();\n\n \/\/convert the json object to variantmap\n QVariantMap result = jObject.toVariantMap();\n\n QVariantMap configure = result[\"config\"].toMap();\n if(configure[\"debug\"].toBool()){\n this->setDev(true);\n }\n if(configure[\"websecurity\"].toBool()){\n this->websecurity(true);\n }\n if(configure[\"name\"].toString() != \"\"){\n this->web.setWindowTitle(configure[\"name\"].toString());\n }\n\n QVariantMap window = result[\"window\"].toMap();\n if(window[\"transparent\"].toBool()){\n this->widgetTransparent();\n }\n if(window[\"noframe\"].toBool()){\n this->widgetNoFrame();\n }\n if(window[\"fullscreen\"].toBool()){\n this->getToggleFullScreen();\n }\n if(window[\"maximize\"].toBool()){\n this->showMaximized();\n }\n if(window[\"width\"].toInt() != 0){\n if(window[\"height\"].toInt() != 0){\n this->widgetSize(window[\"width\"].toInt(),window[\"height\"].toInt());\n }\n }\n\n foreach (QVariant button, result[\"button\"].toList()) {\n\n if (button.toString() == \"back\"){\n this->back();\n }\n if (button.toString() == \"forward\"){\n this->forward();\n }\n if (button.toString() == \"stop\"){\n this->stop();\n }\n if (button.toString() == \"reload\"){\n this->reload();\n }\n\n }\n\n }\n\n config_file.close();\n}\n\nQString ign::hash(const QString &data,QString hash_func){\n QByteArray hash;\n QByteArray byteArray = data.toLatin1();\n if(hash_func == \"md4\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md4);\n }\n else if(hash_func == \"md5\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md5);\n }\n else if(hash_func == \"sha1\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha1);\n }\n\n return hash.toHex();\n}\n\nQString ign::homePath(){\n return this->filesystem->home_path();\n}\n\nbool ign::createFile(const QString &path, const QString &data){\n return this->filesystem->create_file(path,data);\n}\n\nQString ign::readFile(const QString &path){\n return this->filesystem->read_file(path);\n}\n\nvoid ign::saveFile(const QByteArray &data, QString filename, QString path){\n QByteArray byteArray = QByteArray::fromBase64(data);\n QString home;\n home = path+\"\/\"+filename;\n QFile localFile(home);\n if (!localFile.open(QIODevice::WriteOnly))\n return;\n localFile.write(byteArray);\n localFile.close();\n}\n\nvoid ign::download(QString data,QString path){\n this->dl = new QtDownload;\n this->dl->setTarget(data);\n this->dl->save(path);\n this->dl->download();\n connect(this->dl, SIGNAL(download_signal(qint64,qint64)), this, SLOT(download_signal(qint64,qint64)));\n}\n\nvoid ign::download_signal(qint64 recieved, qint64 total){\n emit downloadProgress(recieved,total);\n}\n\n\/*IGN SQL*\/\nQObject *ign::sql(){\n if(!m_sqldrv)\n m_sqldrv = new ignsql;\n return m_sqldrv;\n}\n\n\/*IGN SYSTEM*\/\nQObject *ign::sys(){\n if(!m_ignsystem){\n m_ignsystem = new ignsystem;\n }\n return m_ignsystem;\n}\n\n\/*IGN FILESYSTEM*\/\nbool ign::mkdir(const QString &path){\n return this->filesystem->dir(path,\"create\");\n}\n\nbool ign::dirExist(const QString &path){\n return this->filesystem->dir(path,\"check\");\n}\n\nbool ign::rmdir(const QString &path){\n return this->filesystem->dir(path,\"remove\");\n}\n\nbool ign::fileExist(const QString &path){\n return this->filesystem->file(path,\"check\");\n}\n\nbool ign::fileRemove(const QString &path){\n return this->filesystem->file(path,\"remove\");\n}\n\n\/\/Check version\nQString ign::sdkVersion(){\n return this->version;\n}\n\n\/*void ign::mousePressEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n QMessageBox::information(0, \"Information\", \"press\");\n mMoving = true;\n mLastMousePosition = event->pos();\n }\n}\n\nvoid ign::mouseMoveEvent(QMouseEvent *event)\n{\n if( event->buttons().testFlag(Qt::LeftButton) && mMoving)\n {\n this->web.move(this->web.pos() + (event->pos() - mLastMousePosition));\n mLastMousePosition = event->pos();\n }\n}\n\nvoid ign::mouseReleaseEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n mMoving = false;\n }\n}*\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix compile error after merge.<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\n\/**\n\t@file\n\t@brief definition of Op\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include <mcl\/gmp_util.hpp>\n#include <memory.h>\n#include <mcl\/array.hpp>\n\n#if defined(__EMSCRIPTEN__) || defined(__wasm__)\n\t#define MCL_DONT_USE_XBYAK\n\t#define MCL_DONT_USE_OPENSSL\n#endif\n#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8) && !defined(MCL_STATIC_CODE)\n\t#define MCL_USE_XBYAK\n#endif\n#if defined(MCL_USE_XBYAK) || defined(MCL_STATIC_CODE)\n\t#define MCL_X64_ASM\n\t#define MCL_XBYAK_DIRECT_CALL\n#endif\n\n#define MCL_MAX_HASH_BIT_SIZE 512\n\nnamespace mcl {\n\nstatic const int version = 0x134; \/* 0xABC = A.BC *\/\n\n\/*\n\tspecifies available string format mode for X::setIoMode()\n\t\/\/ for Fp, Fp2, Fp6, Fp12\n\tdefault(0) : IoDec\n\tprintable string(zero terminated, variable size)\n\tIoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix\n\n\tbyte string(not zero terminated, fixed size)\n\tIoArray | IoArrayRaw\n\tIoArray = IoSerialize\n\n\t\/\/ for Ec\n\taffine(0) | IoEcCompY | IoComp\n\tdefault : affine\n\n\taffine and IoEcCompY are available with ioMode for Fp\n\tIoSerialize ignores ioMode for Fp\n\n\tIoAuto\n\t\tdec or hex according to ios_base::fmtflags\n\tIoBin\n\t\tbinary number([01]+)\n\tIoDec\n\t\tdecimal number\n\tIoHex\n\t\thexadecimal number([0-9a-fA-F]+)\n\tIoBinPrefix\n\t\t0b + <binary number>\n\tIoHexPrefix\n\t\t0x + <hexadecimal number>\n\tIoArray\n\t\tarray of Unit(fixed size = Fp::getByteSize())\n\tIoArrayRaw\n\t\tarray of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion\n\n\t\/\/ for Ec::setIoMode()\n\tIoEcAffine(default)\n\t\"0\" ; infinity\n\t\"1 <x> <y>\" ; affine coordinate\n\n\tIoEcProj\n\t\"4\" <x> <y> <z> ; projective or jacobi coordinate\n\n\tIoEcCompY\n\t\t1-bit y prepresentation of elliptic curve\n\t\t\"2 <x>\" ; compressed for even y\n\t\t\"3 <x>\" ; compressed for odd y\n\n\tIoSerialize\n\t\tif isMSBserialize(): \/\/ p is not full bit\n\t\t\tsize = Fp::getByteSize()\n\t\t\tuse MSB of array of x for 1-bit y for prime p where (p % 8 != 0)\n\t\t\t[0] ; infinity\n\t\t\t<x> ; for even y\n\t\t\t<x>|1 ; for odd y ; |1 means set MSB of x\n\t\telse:\n\t\t\tsize = Fp::getByteSize() + 1\n\t\t\t[0] ; infinity\n\t\t\t2 <x> ; for even y\n\t\t\t3 <x> ; for odd y\n*\/\nenum IoMode {\n\tIoAuto = 0, \/\/ dec or hex according to ios_base::fmtflags\n\tIoBin = 2, \/\/ binary number without prefix\n\tIoDec = 10, \/\/ decimal number without prefix\n\tIoHex = 16, \/\/ hexadecimal number without prefix\n\tIoArray = 32, \/\/ array of Unit(fixed size)\n\tIoArrayRaw = 64, \/\/ raw array of Unit without Montgomery conversion\n\tIoPrefix = 128, \/\/ append '0b'(bin) or '0x'(hex)\n\tIoBinPrefix = IoBin | IoPrefix,\n\tIoHexPrefix = IoHex | IoPrefix,\n\tIoEcAffine = 0, \/\/ affine coordinate\n\tIoEcCompY = 256, \/\/ 1-bit y representation of elliptic curve\n\tIoSerialize = 512, \/\/ use MBS for 1-bit y\n\tIoFixedSizeByteSeq = IoSerialize, \/\/ obsolete\n\tIoEcProj = 1024, \/\/ projective or jacobi coordinate\n\tIoSerializeHexStr = 2048, \/\/ printable hex string\n\tIoEcAffineSerialize = 4096 \/\/ serialize [x:y]\n};\n\nnamespace fp {\n\ninline bool isIoSerializeMode(int ioMode)\n{\n\treturn ioMode & (IoArray | IoArrayRaw | IoSerialize | IoEcAffineSerialize | IoSerializeHexStr);\n}\n\nconst size_t UnitBitSize = sizeof(Unit) * 8;\n\nconst size_t maxUnitSize = (MCL_MAX_BIT_SIZE + UnitBitSize - 1) \/ UnitBitSize;\n#define MCL_MAX_UNIT_SIZE ((MCL_MAX_BIT_SIZE + MCL_UNIT_BIT_SIZE - 1) \/ MCL_UNIT_BIT_SIZE)\n\nconst size_t maxMulVecN = 32; \/\/ inner loop of mulVec\n\n#ifndef MCL_MAX_MUL_VEC_NGLV\n\t#define MCL_MAX_MUL_VEC_NGLV 16\n#endif\nconst size_t maxMulVecNGLV = MCL_MAX_MUL_VEC_NGLV; \/\/ inner loop of mulVec with GLV\n\nstruct FpGenerator;\nstruct Op;\n\ntypedef void (*void1u)(Unit*);\ntypedef void (*void2u)(Unit*, const Unit*);\ntypedef void (*void2uI)(Unit*, const Unit*, Unit);\ntypedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);\ntypedef void (*void2uOp)(Unit*, const Unit*, const Op&);\ntypedef void (*void3u)(Unit*, const Unit*, const Unit*);\ntypedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);\ntypedef int (*int2u)(Unit*, const Unit*);\n\ntypedef Unit (*u1uII)(Unit*, Unit, Unit);\ntypedef Unit (*u3u)(Unit*, const Unit*, const Unit*);\n\n\/*\n\tdisable -Wcast-function-type\n\tthe number of arguments of some JIT functions is smaller than that of T\n*\/\ntemplate<class T, class S>\nT func_ptr_cast(S func)\n{\n\treturn reinterpret_cast<T>(reinterpret_cast<void*>(func));\n}\nstruct Block {\n\tconst Unit *p; \/\/ pointer to original FpT.v_\n\tsize_t n;\n\tUnit v_[maxUnitSize];\n};\n\nenum Mode {\n\tFP_AUTO,\n\tFP_GMP,\n\tFP_GMP_MONT,\n\tFP_LLVM,\n\tFP_LLVM_MONT,\n\tFP_XBYAK\n};\n\nenum PrimeMode {\n\tPM_GENERIC = 0,\n\tPM_NIST_P192,\n\tPM_SECP256K1,\n\tPM_NIST_P521\n};\n\nenum MaskMode {\n\tNoMask = 0, \/\/ throw if greater or equal\n\tSmallMask = 1, \/\/ 1-bit smaller mask if greater or equal\n\tMaskAndMod = 2, \/\/ mask and substract if greater or equal\n\tMod = 3 \/\/ mod p\n};\n\nstruct Op {\n\t\/*\n\t\tdon't change the layout of rp and p\n\t\tasm code assumes &rp + 1 == p\n\t*\/\n\tUnit rp;\n\tUnit p[maxUnitSize];\n\tmpz_class mp;\n\tuint32_t pmod4;\n\tmcl::SquareRoot sq;\n\tmcl::Modp modp;\n\tUnit half[maxUnitSize]; \/\/ (p + 1) \/ 2\n\tUnit oneRep[maxUnitSize]; \/\/ 1(=inv R if Montgomery)\n\t\/*\n\t\tfor Montgomery\n\t\tone = 1\n\t\tR = (1 << (N * sizeof(Unit) * 8)) % p\n\t\tR2 = (R * R) % p\n\t\tR3 = RR^3\n\t*\/\n\tUnit one[maxUnitSize];\n\tUnit R2[maxUnitSize];\n\tUnit R3[maxUnitSize];\n#ifdef MCL_USE_XBYAK\n\tFpGenerator *fg;\n#endif\n#ifdef MCL_X64_ASM\n\tmcl::Array<Unit> invTbl;\n#endif\n\tvoid3u fp_addA_;\n\tvoid3u fp_subA_;\n\tvoid2u fp_negA_;\n\tvoid3u fp_mulA_;\n\tvoid2u fp_sqrA_;\n\tvoid2u fp_mul2A_;\n\tvoid3u fp2_addA_;\n\tvoid3u fp2_subA_;\n\tvoid2u fp2_negA_;\n\tvoid3u fp2_mulA_;\n\tvoid2u fp2_sqrA_;\n\tvoid2u fp2_mul2A_;\n\tvoid3u fpDbl_addA_;\n\tvoid3u fpDbl_subA_;\n\tvoid2u fpDbl_modA_;\n\tvoid3u fp2Dbl_mulPreA_;\n\tvoid2u fp2Dbl_sqrPreA_;\n\tvoid2u fp2Dbl_mul_xiA_;\n\tsize_t maxN;\n\tsize_t N;\n\tsize_t bitSize;\n\tbool (*fp_isZero)(const Unit*);\n\tvoid1u fp_clear;\n\tvoid2u fp_copy;\n\tvoid2u fp_shr1;\n\tvoid3u fp_neg;\n\tvoid4u fp_add;\n\tvoid4u fp_sub;\n\tvoid4u fp_mul;\n\tvoid3u fp_sqr;\n\tvoid3u fp_mul2;\n\tvoid2uOp fp_invOp;\n\tvoid2uIu fp_mulUnit; \/\/ fpN1_mod + fp_mulUnitPre\n\n\tvoid3u fpDbl_mulPre;\n\tvoid2u fpDbl_sqrPre;\n\tint2u fp_preInv;\n\tvoid2uI fp_mulUnitPre; \/\/ z[N + 1] = x[N] * y\n\tvoid3u fpN1_mod; \/\/ y[N] = x[N + 1] % p[N]\n\n\tvoid4u fpDbl_add;\n\tvoid4u fpDbl_sub;\n\tvoid3u fpDbl_mod;\n\n\tu3u fp_addPre; \/\/ without modulo p\n\tu3u fp_subPre; \/\/ without modulo p\n\tu3u fpDbl_addPre;\n\tu3u fpDbl_subPre;\n\t\/*\n\t\tfor Fp2 = F[u] \/ (u^2 + 1)\n\t\tx = a + bu\n\t*\/\n\tint xi_a; \/\/ xi = xi_a + u\n\tvoid4u fp2_mulNF;\n\tvoid2u fp2_inv;\n\tvoid2u fp2_mul_xiA_;\n\tuint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);\n\n\tPrimeMode primeMode;\n\tbool isFullBit; \/\/ true if bitSize % uniSize == 0\n\tbool isMont; \/\/ true if use Montgomery\n\tbool isFastMod; \/\/ true if modulo is fast\n\n\tOp()\n\t{\n\t\tclear();\n\t}\n\t~Op()\n\t{\n#ifdef MCL_USE_XBYAK\n\t\tdestroyFpGenerator(fg);\n#endif\n\t}\n\tvoid clear()\n\t{\n\t\trp = 0;\n\t\tmemset(p, 0, sizeof(p));\n\t\tmp = 0;\n\t\tpmod4 = 0;\n\t\tsq.clear();\n\t\t\/\/ fg is not set\n\t\tmemset(half, 0, sizeof(half));\n\t\tmemset(oneRep, 0, sizeof(oneRep));\n\t\tmemset(one, 0, sizeof(one));\n\t\tmemset(R2, 0, sizeof(R2));\n\t\tmemset(R3, 0, sizeof(R3));\n#ifdef MCL_X64_ASM\n\t\tinvTbl.clear();\n#endif\n\t\tfp_addA_ = 0;\n\t\tfp_subA_ = 0;\n\t\tfp_negA_ = 0;\n\t\tfp_mulA_ = 0;\n\t\tfp_sqrA_ = 0;\n\t\tfp_mul2A_ = 0;\n\t\tfp2_addA_ = 0;\n\t\tfp2_subA_ = 0;\n\t\tfp2_negA_ = 0;\n\t\tfp2_mulA_ = 0;\n\t\tfp2_sqrA_ = 0;\n\t\tfp2_mul2A_ = 0;\n\t\tfpDbl_addA_ = 0;\n\t\tfpDbl_subA_ = 0;\n\t\tfpDbl_modA_ = 0;\n\t\tfp2Dbl_mulPreA_ = 0;\n\t\tfp2Dbl_sqrPreA_ = 0;\n\t\tfp2Dbl_mul_xiA_ = 0;\n\t\tmaxN = 0;\n\t\tN = 0;\n\t\tbitSize = 0;\n\t\tfp_isZero = 0;\n\t\tfp_clear = 0;\n\t\tfp_copy = 0;\n\t\tfp_shr1 = 0;\n\t\tfp_neg = 0;\n\t\tfp_add = 0;\n\t\tfp_sub = 0;\n\t\tfp_mul = 0;\n\t\tfp_sqr = 0;\n\t\tfp_mul2 = 0;\n\t\tfp_invOp = 0;\n\t\tfp_mulUnit = 0;\n\n\t\tfpDbl_mulPre = 0;\n\t\tfpDbl_sqrPre = 0;\n\t\tfp_preInv = 0;\n\t\tfp_mulUnitPre = 0;\n\t\tfpN1_mod = 0;\n\n\t\tfpDbl_add = 0;\n\t\tfpDbl_sub = 0;\n\t\tfpDbl_mod = 0;\n\n\t\tfp_addPre = 0;\n\t\tfp_subPre = 0;\n\t\tfpDbl_addPre = 0;\n\t\tfpDbl_subPre = 0;\n\n\t\txi_a = 0;\n\t\tfp2_mulNF = 0;\n\t\tfp2_inv = 0;\n\t\tfp2_mul_xiA_ = 0;\n\t\thash = 0;\n\n\t\tprimeMode = PM_GENERIC;\n\t\tisFullBit = false;\n\t\tisMont = false;\n\t\tisFastMod = false;\n\t}\n\tvoid fromMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\tM(x, y) = xyR^-1\n\t\t\ty = M(x, 1) = xR^-1\n\t\t*\/\n\t\tfp_mul(y, x, one, p);\n\t}\n\tvoid toMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\ty = M(x, R2) = xR^2 R^-1 = xR\n\t\t*\/\n\t\tfp_mul(y, x, R2, p);\n\t}\n\tbool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);\n#ifdef MCL_USE_XBYAK\n\tstatic FpGenerator* createFpGenerator();\n\tstatic void destroyFpGenerator(FpGenerator *fg);\n#endif\nprivate:\n\tOp(const Op&);\n\tvoid operator=(const Op&);\n};\n\ninline const char* getIoSeparator(int ioMode)\n{\n\treturn (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr | IoEcAffineSerialize)) ? \"\" : \" \";\n}\n\ninline void dump(const void *buf, size_t n)\n{\n\tconst uint8_t *s = (const uint8_t *)buf;\n\tfor (size_t i = 0; i < n; i++) {\n\t\tprintf(\"%02x \", s[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\n#ifndef CYBOZU_DONT_USE_STRING\nint detectIoMode(int ioMode, const std::ios_base& ios);\n\ninline void dump(const std::string& s)\n{\n\tdump(s.c_str(), s.size());\n}\n#endif\n\n} } \/\/ mcl::fp\n<commit_msg>v1.35<commit_after>#pragma once\n\/**\n\t@file\n\t@brief definition of Op\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include <mcl\/gmp_util.hpp>\n#include <memory.h>\n#include <mcl\/array.hpp>\n\n#if defined(__EMSCRIPTEN__) || defined(__wasm__)\n\t#define MCL_DONT_USE_XBYAK\n\t#define MCL_DONT_USE_OPENSSL\n#endif\n#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8) && !defined(MCL_STATIC_CODE)\n\t#define MCL_USE_XBYAK\n#endif\n#if defined(MCL_USE_XBYAK) || defined(MCL_STATIC_CODE)\n\t#define MCL_X64_ASM\n\t#define MCL_XBYAK_DIRECT_CALL\n#endif\n\n#define MCL_MAX_HASH_BIT_SIZE 512\n\nnamespace mcl {\n\nstatic const int version = 0x135; \/* 0xABC = A.BC *\/\n\n\/*\n\tspecifies available string format mode for X::setIoMode()\n\t\/\/ for Fp, Fp2, Fp6, Fp12\n\tdefault(0) : IoDec\n\tprintable string(zero terminated, variable size)\n\tIoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix\n\n\tbyte string(not zero terminated, fixed size)\n\tIoArray | IoArrayRaw\n\tIoArray = IoSerialize\n\n\t\/\/ for Ec\n\taffine(0) | IoEcCompY | IoComp\n\tdefault : affine\n\n\taffine and IoEcCompY are available with ioMode for Fp\n\tIoSerialize ignores ioMode for Fp\n\n\tIoAuto\n\t\tdec or hex according to ios_base::fmtflags\n\tIoBin\n\t\tbinary number([01]+)\n\tIoDec\n\t\tdecimal number\n\tIoHex\n\t\thexadecimal number([0-9a-fA-F]+)\n\tIoBinPrefix\n\t\t0b + <binary number>\n\tIoHexPrefix\n\t\t0x + <hexadecimal number>\n\tIoArray\n\t\tarray of Unit(fixed size = Fp::getByteSize())\n\tIoArrayRaw\n\t\tarray of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion\n\n\t\/\/ for Ec::setIoMode()\n\tIoEcAffine(default)\n\t\"0\" ; infinity\n\t\"1 <x> <y>\" ; affine coordinate\n\n\tIoEcProj\n\t\"4\" <x> <y> <z> ; projective or jacobi coordinate\n\n\tIoEcCompY\n\t\t1-bit y prepresentation of elliptic curve\n\t\t\"2 <x>\" ; compressed for even y\n\t\t\"3 <x>\" ; compressed for odd y\n\n\tIoSerialize\n\t\tif isMSBserialize(): \/\/ p is not full bit\n\t\t\tsize = Fp::getByteSize()\n\t\t\tuse MSB of array of x for 1-bit y for prime p where (p % 8 != 0)\n\t\t\t[0] ; infinity\n\t\t\t<x> ; for even y\n\t\t\t<x>|1 ; for odd y ; |1 means set MSB of x\n\t\telse:\n\t\t\tsize = Fp::getByteSize() + 1\n\t\t\t[0] ; infinity\n\t\t\t2 <x> ; for even y\n\t\t\t3 <x> ; for odd y\n*\/\nenum IoMode {\n\tIoAuto = 0, \/\/ dec or hex according to ios_base::fmtflags\n\tIoBin = 2, \/\/ binary number without prefix\n\tIoDec = 10, \/\/ decimal number without prefix\n\tIoHex = 16, \/\/ hexadecimal number without prefix\n\tIoArray = 32, \/\/ array of Unit(fixed size)\n\tIoArrayRaw = 64, \/\/ raw array of Unit without Montgomery conversion\n\tIoPrefix = 128, \/\/ append '0b'(bin) or '0x'(hex)\n\tIoBinPrefix = IoBin | IoPrefix,\n\tIoHexPrefix = IoHex | IoPrefix,\n\tIoEcAffine = 0, \/\/ affine coordinate\n\tIoEcCompY = 256, \/\/ 1-bit y representation of elliptic curve\n\tIoSerialize = 512, \/\/ use MBS for 1-bit y\n\tIoFixedSizeByteSeq = IoSerialize, \/\/ obsolete\n\tIoEcProj = 1024, \/\/ projective or jacobi coordinate\n\tIoSerializeHexStr = 2048, \/\/ printable hex string\n\tIoEcAffineSerialize = 4096 \/\/ serialize [x:y]\n};\n\nnamespace fp {\n\ninline bool isIoSerializeMode(int ioMode)\n{\n\treturn ioMode & (IoArray | IoArrayRaw | IoSerialize | IoEcAffineSerialize | IoSerializeHexStr);\n}\n\nconst size_t UnitBitSize = sizeof(Unit) * 8;\n\nconst size_t maxUnitSize = (MCL_MAX_BIT_SIZE + UnitBitSize - 1) \/ UnitBitSize;\n#define MCL_MAX_UNIT_SIZE ((MCL_MAX_BIT_SIZE + MCL_UNIT_BIT_SIZE - 1) \/ MCL_UNIT_BIT_SIZE)\n\nconst size_t maxMulVecN = 32; \/\/ inner loop of mulVec\n\n#ifndef MCL_MAX_MUL_VEC_NGLV\n\t#define MCL_MAX_MUL_VEC_NGLV 16\n#endif\nconst size_t maxMulVecNGLV = MCL_MAX_MUL_VEC_NGLV; \/\/ inner loop of mulVec with GLV\n\nstruct FpGenerator;\nstruct Op;\n\ntypedef void (*void1u)(Unit*);\ntypedef void (*void2u)(Unit*, const Unit*);\ntypedef void (*void2uI)(Unit*, const Unit*, Unit);\ntypedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);\ntypedef void (*void2uOp)(Unit*, const Unit*, const Op&);\ntypedef void (*void3u)(Unit*, const Unit*, const Unit*);\ntypedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);\ntypedef int (*int2u)(Unit*, const Unit*);\n\ntypedef Unit (*u1uII)(Unit*, Unit, Unit);\ntypedef Unit (*u3u)(Unit*, const Unit*, const Unit*);\n\n\/*\n\tdisable -Wcast-function-type\n\tthe number of arguments of some JIT functions is smaller than that of T\n*\/\ntemplate<class T, class S>\nT func_ptr_cast(S func)\n{\n\treturn reinterpret_cast<T>(reinterpret_cast<void*>(func));\n}\nstruct Block {\n\tconst Unit *p; \/\/ pointer to original FpT.v_\n\tsize_t n;\n\tUnit v_[maxUnitSize];\n};\n\nenum Mode {\n\tFP_AUTO,\n\tFP_GMP,\n\tFP_GMP_MONT,\n\tFP_LLVM,\n\tFP_LLVM_MONT,\n\tFP_XBYAK\n};\n\nenum PrimeMode {\n\tPM_GENERIC = 0,\n\tPM_NIST_P192,\n\tPM_SECP256K1,\n\tPM_NIST_P521\n};\n\nenum MaskMode {\n\tNoMask = 0, \/\/ throw if greater or equal\n\tSmallMask = 1, \/\/ 1-bit smaller mask if greater or equal\n\tMaskAndMod = 2, \/\/ mask and substract if greater or equal\n\tMod = 3 \/\/ mod p\n};\n\nstruct Op {\n\t\/*\n\t\tdon't change the layout of rp and p\n\t\tasm code assumes &rp + 1 == p\n\t*\/\n\tUnit rp;\n\tUnit p[maxUnitSize];\n\tmpz_class mp;\n\tuint32_t pmod4;\n\tmcl::SquareRoot sq;\n\tmcl::Modp modp;\n\tUnit half[maxUnitSize]; \/\/ (p + 1) \/ 2\n\tUnit oneRep[maxUnitSize]; \/\/ 1(=inv R if Montgomery)\n\t\/*\n\t\tfor Montgomery\n\t\tone = 1\n\t\tR = (1 << (N * sizeof(Unit) * 8)) % p\n\t\tR2 = (R * R) % p\n\t\tR3 = RR^3\n\t*\/\n\tUnit one[maxUnitSize];\n\tUnit R2[maxUnitSize];\n\tUnit R3[maxUnitSize];\n#ifdef MCL_USE_XBYAK\n\tFpGenerator *fg;\n#endif\n#ifdef MCL_X64_ASM\n\tmcl::Array<Unit> invTbl;\n#endif\n\tvoid3u fp_addA_;\n\tvoid3u fp_subA_;\n\tvoid2u fp_negA_;\n\tvoid3u fp_mulA_;\n\tvoid2u fp_sqrA_;\n\tvoid2u fp_mul2A_;\n\tvoid3u fp2_addA_;\n\tvoid3u fp2_subA_;\n\tvoid2u fp2_negA_;\n\tvoid3u fp2_mulA_;\n\tvoid2u fp2_sqrA_;\n\tvoid2u fp2_mul2A_;\n\tvoid3u fpDbl_addA_;\n\tvoid3u fpDbl_subA_;\n\tvoid2u fpDbl_modA_;\n\tvoid3u fp2Dbl_mulPreA_;\n\tvoid2u fp2Dbl_sqrPreA_;\n\tvoid2u fp2Dbl_mul_xiA_;\n\tsize_t maxN;\n\tsize_t N;\n\tsize_t bitSize;\n\tbool (*fp_isZero)(const Unit*);\n\tvoid1u fp_clear;\n\tvoid2u fp_copy;\n\tvoid2u fp_shr1;\n\tvoid3u fp_neg;\n\tvoid4u fp_add;\n\tvoid4u fp_sub;\n\tvoid4u fp_mul;\n\tvoid3u fp_sqr;\n\tvoid3u fp_mul2;\n\tvoid2uOp fp_invOp;\n\tvoid2uIu fp_mulUnit; \/\/ fpN1_mod + fp_mulUnitPre\n\n\tvoid3u fpDbl_mulPre;\n\tvoid2u fpDbl_sqrPre;\n\tint2u fp_preInv;\n\tvoid2uI fp_mulUnitPre; \/\/ z[N + 1] = x[N] * y\n\tvoid3u fpN1_mod; \/\/ y[N] = x[N + 1] % p[N]\n\n\tvoid4u fpDbl_add;\n\tvoid4u fpDbl_sub;\n\tvoid3u fpDbl_mod;\n\n\tu3u fp_addPre; \/\/ without modulo p\n\tu3u fp_subPre; \/\/ without modulo p\n\tu3u fpDbl_addPre;\n\tu3u fpDbl_subPre;\n\t\/*\n\t\tfor Fp2 = F[u] \/ (u^2 + 1)\n\t\tx = a + bu\n\t*\/\n\tint xi_a; \/\/ xi = xi_a + u\n\tvoid4u fp2_mulNF;\n\tvoid2u fp2_inv;\n\tvoid2u fp2_mul_xiA_;\n\tuint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);\n\n\tPrimeMode primeMode;\n\tbool isFullBit; \/\/ true if bitSize % uniSize == 0\n\tbool isMont; \/\/ true if use Montgomery\n\tbool isFastMod; \/\/ true if modulo is fast\n\n\tOp()\n\t{\n\t\tclear();\n\t}\n\t~Op()\n\t{\n#ifdef MCL_USE_XBYAK\n\t\tdestroyFpGenerator(fg);\n#endif\n\t}\n\tvoid clear()\n\t{\n\t\trp = 0;\n\t\tmemset(p, 0, sizeof(p));\n\t\tmp = 0;\n\t\tpmod4 = 0;\n\t\tsq.clear();\n\t\t\/\/ fg is not set\n\t\tmemset(half, 0, sizeof(half));\n\t\tmemset(oneRep, 0, sizeof(oneRep));\n\t\tmemset(one, 0, sizeof(one));\n\t\tmemset(R2, 0, sizeof(R2));\n\t\tmemset(R3, 0, sizeof(R3));\n#ifdef MCL_X64_ASM\n\t\tinvTbl.clear();\n#endif\n\t\tfp_addA_ = 0;\n\t\tfp_subA_ = 0;\n\t\tfp_negA_ = 0;\n\t\tfp_mulA_ = 0;\n\t\tfp_sqrA_ = 0;\n\t\tfp_mul2A_ = 0;\n\t\tfp2_addA_ = 0;\n\t\tfp2_subA_ = 0;\n\t\tfp2_negA_ = 0;\n\t\tfp2_mulA_ = 0;\n\t\tfp2_sqrA_ = 0;\n\t\tfp2_mul2A_ = 0;\n\t\tfpDbl_addA_ = 0;\n\t\tfpDbl_subA_ = 0;\n\t\tfpDbl_modA_ = 0;\n\t\tfp2Dbl_mulPreA_ = 0;\n\t\tfp2Dbl_sqrPreA_ = 0;\n\t\tfp2Dbl_mul_xiA_ = 0;\n\t\tmaxN = 0;\n\t\tN = 0;\n\t\tbitSize = 0;\n\t\tfp_isZero = 0;\n\t\tfp_clear = 0;\n\t\tfp_copy = 0;\n\t\tfp_shr1 = 0;\n\t\tfp_neg = 0;\n\t\tfp_add = 0;\n\t\tfp_sub = 0;\n\t\tfp_mul = 0;\n\t\tfp_sqr = 0;\n\t\tfp_mul2 = 0;\n\t\tfp_invOp = 0;\n\t\tfp_mulUnit = 0;\n\n\t\tfpDbl_mulPre = 0;\n\t\tfpDbl_sqrPre = 0;\n\t\tfp_preInv = 0;\n\t\tfp_mulUnitPre = 0;\n\t\tfpN1_mod = 0;\n\n\t\tfpDbl_add = 0;\n\t\tfpDbl_sub = 0;\n\t\tfpDbl_mod = 0;\n\n\t\tfp_addPre = 0;\n\t\tfp_subPre = 0;\n\t\tfpDbl_addPre = 0;\n\t\tfpDbl_subPre = 0;\n\n\t\txi_a = 0;\n\t\tfp2_mulNF = 0;\n\t\tfp2_inv = 0;\n\t\tfp2_mul_xiA_ = 0;\n\t\thash = 0;\n\n\t\tprimeMode = PM_GENERIC;\n\t\tisFullBit = false;\n\t\tisMont = false;\n\t\tisFastMod = false;\n\t}\n\tvoid fromMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\tM(x, y) = xyR^-1\n\t\t\ty = M(x, 1) = xR^-1\n\t\t*\/\n\t\tfp_mul(y, x, one, p);\n\t}\n\tvoid toMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\ty = M(x, R2) = xR^2 R^-1 = xR\n\t\t*\/\n\t\tfp_mul(y, x, R2, p);\n\t}\n\tbool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);\n#ifdef MCL_USE_XBYAK\n\tstatic FpGenerator* createFpGenerator();\n\tstatic void destroyFpGenerator(FpGenerator *fg);\n#endif\nprivate:\n\tOp(const Op&);\n\tvoid operator=(const Op&);\n};\n\ninline const char* getIoSeparator(int ioMode)\n{\n\treturn (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr | IoEcAffineSerialize)) ? \"\" : \" \";\n}\n\ninline void dump(const void *buf, size_t n)\n{\n\tconst uint8_t *s = (const uint8_t *)buf;\n\tfor (size_t i = 0; i < n; i++) {\n\t\tprintf(\"%02x \", s[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\n#ifndef CYBOZU_DONT_USE_STRING\nint detectIoMode(int ioMode, const std::ios_base& ios);\n\ninline void dump(const std::string& s)\n{\n\tdump(s.c_str(), s.size());\n}\n#endif\n\n} } \/\/ mcl::fp\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\r\n * Copyright (c)2012 Jan Rheinlaender <jrheinlaender@users.sourceforge.net> *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ******************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include <BRepBuilderAPI_Transform.hxx>\r\n# include <BRepAlgoAPI_Fuse.hxx>\r\n# include <BRepAlgoAPI_Cut.hxx>\r\n# include <BRep_Builder.hxx>\r\n# include <TopExp.hxx>\r\n# include <TopExp_Explorer.hxx>\r\n# include <TopTools_IndexedMapOfShape.hxx>\r\n# include <Precision.hxx>\r\n# include <BRepBuilderAPI_Copy.hxx>\r\n#endif\r\n\r\n\r\n#include \"FeatureTransformed.h\"\r\n#include \"FeatureMultiTransform.h\"\r\n#include \"FeatureAdditive.h\"\r\n#include \"FeatureSubtractive.h\"\r\n#include \"FeatureMirrored.h\"\r\n\r\n#include <Base\/Console.h>\r\n\r\nusing namespace PartDesign;\r\n\r\nnamespace PartDesign {\r\n\r\nPROPERTY_SOURCE(PartDesign::Transformed, PartDesign::Feature)\r\n\r\nTransformed::Transformed() : rejected(0)\r\n{\r\n ADD_PROPERTY(Originals,(0));\r\n Originals.setSize(0);\r\n Placement.StatusBits.set(2, true);\r\n}\r\n\r\nvoid Transformed::positionBySupport(void)\r\n{\r\n Part::Feature *support = static_cast<Part::Feature*>(getSupportObject());\r\n if ((support != NULL) && support->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))\r\n this->Placement.setValue(support->Placement.getValue());\r\n}\r\n\r\nApp::DocumentObject* Transformed::getSupportObject() const\r\n{\r\n if (!Originals.getValues().empty())\r\n return Originals.getValues().front();\r\n else\r\n return NULL;\r\n}\r\n\r\nApp::DocumentObject* Transformed::getSketchObject() const\r\n{\r\n std::vector<DocumentObject*> originals = Originals.getValues();\r\n if (!originals.empty() && originals.front()->getTypeId().isDerivedFrom(PartDesign::SketchBased::getClassTypeId()))\r\n return (static_cast<PartDesign::SketchBased*>(originals.front()))->getVerifiedSketch();\r\n else\r\n return NULL;\r\n}\r\n\r\nshort Transformed::mustExecute() const\r\n{\r\n if (Originals.isTouched())\r\n return 1;\r\n return PartDesign::Feature::mustExecute();\r\n}\r\n\r\nApp::DocumentObjectExecReturn *Transformed::execute(void)\r\n{\r\n rejected.clear();\r\n\r\n std::vector<App::DocumentObject*> originals = Originals.getValues();\r\n if (originals.empty()) \/\/ typically InsideMultiTransform\r\n return App::DocumentObject::StdReturn;\r\n\r\n this->positionBySupport();\r\n\r\n \/\/ get transformations from subclass by calling virtual method\r\n std::list<gp_Trsf> transformations;\r\n try {\r\n transformations = getTransformations(originals);\r\n } catch (Base::Exception& e) {\r\n return new App::DocumentObjectExecReturn(e.what());\r\n }\r\n\r\n if (transformations.empty())\r\n return App::DocumentObject::StdReturn; \/\/ No transformations defined, exit silently\r\n\r\n \/\/ Get the support\r\n \/\/ NOTE: Because of the way we define the support, FeatureTransformed can only work on\r\n \/\/ one Body feature at a time\r\n \/\/ TODO: Currently, the support is simply the first Original. Change this to the Body feature later\r\n Part::Feature* supportFeature = static_cast<Part::Feature*>(getSupportObject());\r\n const Part::TopoShape& supportTopShape = supportFeature->Shape.getShape();\r\n if (supportTopShape._Shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Cannot transform invalid support shape\");\r\n\r\n \/\/ create an untransformed copy of the support shape\r\n Part::TopoShape supportShape(supportTopShape);\r\n supportShape.setTransform(Base::Matrix4D());\r\n TopoDS_Shape support = supportShape._Shape;\r\n\r\n \/\/ NOTE: It would be possible to build a compound from all original addShapes\/subShapes and then\r\n \/\/ transform the compounds as a whole. But we choose to apply the transformations to each\r\n \/\/ Original separately. This way it is easier to discover what feature causes a fuse\/cut\r\n \/\/ to fail. The downside is that performance suffers when there are many originals. But it seems\r\n \/\/ safe to assume that in most cases there are few originals and many transformations\r\n for (std::vector<App::DocumentObject*>::const_iterator o = originals.begin(); o != originals.end(); o++)\r\n {\r\n TopoDS_Shape shape;\r\n bool fuse;\r\n\r\n if ((*o)->getTypeId().isDerivedFrom(PartDesign::Additive::getClassTypeId())) {\r\n PartDesign::Additive* addFeature = static_cast<PartDesign::Additive*>(*o);\r\n shape = addFeature->AddShape.getShape()._Shape;\r\n if (shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Shape of additive feature is empty\");\r\n fuse = true;\r\n } else if ((*o)->getTypeId().isDerivedFrom(PartDesign::Subtractive::getClassTypeId())) {\r\n PartDesign::Subtractive* subFeature = static_cast<PartDesign::Subtractive*>(*o);\r\n shape = subFeature->SubShape.getShape()._Shape;\r\n if (shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Shape of subtractive feature is empty\");\r\n fuse = false;\r\n } else {\r\n return new App::DocumentObjectExecReturn(\"Only additive and subtractive features can be transformed\");\r\n }\r\n\r\n \/\/ Transform the add\/subshape and build a compound from the transformations, \r\n BRep_Builder builder;\r\n TopoDS_Compound transformedShapes;\r\n builder.MakeCompound(transformedShapes);\r\n std::vector<TopoDS_Shape> v_transformedShapes; \/\/ collect all the transformed shapes for intersection testing\r\n std::list<gp_Trsf>::const_iterator t = transformations.begin();\r\n t++; \/\/ Skip first transformation, which is always the identity transformation\r\n\r\n for (; t != transformations.end(); t++)\r\n {\r\n \/\/ Make an explicit copy of the shape because the \"true\" parameter to BRepBuilderAPI_Transform\r\n \/\/ seems to be pretty broken\r\n BRepBuilderAPI_Copy copy(shape);\r\n shape = copy.Shape();\r\n if (shape.IsNull())\r\n throw Base::Exception(\"Transformed: Linked shape object is empty\");\r\n\r\n BRepBuilderAPI_Transform mkTrf(shape, *t, false); \/\/ No need to copy, now\r\n if (!mkTrf.IsDone())\r\n return new App::DocumentObjectExecReturn(\"Transformation failed\", (*o));\r\n\r\n \/\/ Check for intersection with support\r\n if (!Part::checkIntersection(support, mkTrf.Shape(), false, true)) {\r\n Base::Console().Warning(\"Transformed shape does not intersect support %s: Removed\\n\", (*o)->getNameInDocument());\r\n \/\/ Note: The removal happens in getSolid() after the fuse\r\n rejected.push_back(*t);\r\n }\r\n builder.Add(transformedShapes, mkTrf.Shape());\r\n v_transformedShapes.push_back(mkTrf.Shape());\r\n\r\n \/*\r\n \/\/ Note: This method is only stable for Linear and Polar transformations. No need to\r\n \/\/ make an explicit copy of the shape, either\r\n TopoDS_Shape trfShape = shape.Moved(TopLoc_Location(*t));\r\n\r\n \/\/ Check for intersection with support\r\n Bnd_Box transformed_bb;\r\n BRepBndLib::Add(trfShape, transformed_bb);\r\n if (support_bb.Distance(transformed_bb) > Precision::Confusion()) {\r\n Base::Console().Warning(\"Transformed shape does not intersect support %s: Removed\\n\", (*o)->getNameInDocument());\r\n \/\/ Note: The removal happens in getSolid() after the fuse\r\n }\r\n builder.Add(transformedShapes, trfShape);\r\n v_transformedShapes.push_back(trfShape);\r\n *\/\r\n }\r\n\r\n \/\/ Check for intersection of the original and the transformed shape\r\n for (std::vector<TopoDS_Shape>::const_iterator s = v_transformedShapes.begin(); s != v_transformedShapes.end(); s++)\r\n {\r\n \/\/ If there is only one transformed feature, this check is not necessary (though it might seem\r\n \/\/ illogical to the user why we allow overlapping shapes in this case!\r\n if (v_transformedShapes.size() == 1)\r\n break;\r\n\r\n if (Part::checkIntersection(shape, *s, false, false))\r\n return new App::DocumentObjectExecReturn(\"Transformed objects are overlapping, try using a higher length or reducing the number of occurrences\", (*o));\r\n \/\/ Note: This limitation could be overcome by fusing the transformed features instead of\r\n \/\/ compounding them, probably at the expense of quite a bit of performance and complexity\r\n \/\/ in this code\r\n\r\n \/\/ For MultiTransform, just checking the first transformed shape is not sufficient - any two\r\n \/\/ features might overlap, even if the original and the first shape don't overlap!\r\n if (this->getTypeId() != PartDesign::MultiTransform::getClassTypeId())\r\n break;\r\n else {\r\n \/\/ Check intersection with all other transformed shapes as well\r\n std::vector<TopoDS_Shape>::const_iterator s2 = s;\r\n s2++;\r\n for (; s2 != v_transformedShapes.end(); s2++)\r\n if (Part::checkIntersection(*s, *s2, false, false))\r\n return new App::DocumentObjectExecReturn(\"Transformed objects are overlapping, try using a higher length or reducing the number of occurrences\", (*o));\r\n }\r\n }\r\n\r\n \/\/ Fuse\/Cut the compounded transformed shapes with the support\r\n TopoDS_Shape result;\r\n\r\n if (fuse) {\r\n BRepAlgoAPI_Fuse mkFuse(support, transformedShapes);\r\n if (!mkFuse.IsDone())\r\n return new App::DocumentObjectExecReturn(\"Fusion with support failed\", *o);\r\n \/\/ we have to get the solids (fuse sometimes creates compounds)\r\n \/\/ Note: Because getSolid() only returns the first solid in the explorer, all\r\n \/\/ solids that are outside the support automatically disappear!\r\n result = this->getSolid(mkFuse.Shape());\r\n \/\/ lets check if the result is a solid\r\n if (result.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Resulting shape is not a solid\", *o);\r\n \/\/ check if mkFuse created more than one solids\r\n TopExp_Explorer xp;\r\n xp.Init(mkFuse.Shape(),TopAbs_SOLID);\r\n if (xp.More())\r\n xp.Next();\r\n if (!xp.More()) \/\/ There are no rejected transformations even\r\n rejected.clear(); \/\/ if the bb check guessed that there would be\r\n } else {\r\n BRepAlgoAPI_Cut mkCut(support, transformedShapes);\r\n if (!mkCut.IsDone())\r\n return new App::DocumentObjectExecReturn(\"Cut out of support failed\", *o);\r\n result = mkCut.Shape();\r\n }\r\n\r\n support = result; \/\/ Use result of this operation for fuse\/cut of next original\r\n }\r\n\r\n this->Shape.setValue(support);\r\n\r\n return App::DocumentObject::StdReturn;\r\n}\r\n\r\n}\r\n<commit_msg>PartDesign: Show overlapping transformations as rejected<commit_after>\/******************************************************************************\r\n * Copyright (c)2012 Jan Rheinlaender <jrheinlaender@users.sourceforge.net> *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ******************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include <BRepBuilderAPI_Transform.hxx>\r\n# include <BRepAlgoAPI_Fuse.hxx>\r\n# include <BRepAlgoAPI_Cut.hxx>\r\n# include <BRep_Builder.hxx>\r\n# include <TopExp.hxx>\r\n# include <TopExp_Explorer.hxx>\r\n# include <TopTools_IndexedMapOfShape.hxx>\r\n# include <Precision.hxx>\r\n# include <BRepBuilderAPI_Copy.hxx>\r\n#endif\r\n\r\n\r\n#include \"FeatureTransformed.h\"\r\n#include \"FeatureMultiTransform.h\"\r\n#include \"FeatureAdditive.h\"\r\n#include \"FeatureSubtractive.h\"\r\n#include \"FeatureMirrored.h\"\r\n\r\n#include <Base\/Console.h>\r\n\r\nusing namespace PartDesign;\r\n\r\nnamespace PartDesign {\r\n\r\nPROPERTY_SOURCE(PartDesign::Transformed, PartDesign::Feature)\r\n\r\nTransformed::Transformed() : rejected(0)\r\n{\r\n ADD_PROPERTY(Originals,(0));\r\n Originals.setSize(0);\r\n Placement.StatusBits.set(2, true);\r\n}\r\n\r\nvoid Transformed::positionBySupport(void)\r\n{\r\n Part::Feature *support = static_cast<Part::Feature*>(getSupportObject());\r\n if ((support != NULL) && support->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))\r\n this->Placement.setValue(support->Placement.getValue());\r\n}\r\n\r\nApp::DocumentObject* Transformed::getSupportObject() const\r\n{\r\n if (!Originals.getValues().empty())\r\n return Originals.getValues().front();\r\n else\r\n return NULL;\r\n}\r\n\r\nApp::DocumentObject* Transformed::getSketchObject() const\r\n{\r\n std::vector<DocumentObject*> originals = Originals.getValues();\r\n if (!originals.empty() && originals.front()->getTypeId().isDerivedFrom(PartDesign::SketchBased::getClassTypeId()))\r\n return (static_cast<PartDesign::SketchBased*>(originals.front()))->getVerifiedSketch();\r\n else\r\n return NULL;\r\n}\r\n\r\nshort Transformed::mustExecute() const\r\n{\r\n if (Originals.isTouched())\r\n return 1;\r\n return PartDesign::Feature::mustExecute();\r\n}\r\n\r\nApp::DocumentObjectExecReturn *Transformed::execute(void)\r\n{\r\n rejected.clear();\r\n\r\n std::vector<App::DocumentObject*> originals = Originals.getValues();\r\n if (originals.empty()) \/\/ typically InsideMultiTransform\r\n return App::DocumentObject::StdReturn;\r\n\r\n this->positionBySupport();\r\n\r\n \/\/ get transformations from subclass by calling virtual method\r\n std::vector<gp_Trsf> transformations;\r\n try {\r\n std::list<gp_Trsf> t_list = getTransformations(originals);\r\n transformations.insert(transformations.end(), t_list.begin(), t_list.end());\r\n } catch (Base::Exception& e) {\r\n return new App::DocumentObjectExecReturn(e.what());\r\n }\r\n\r\n if (transformations.empty())\r\n return App::DocumentObject::StdReturn; \/\/ No transformations defined, exit silently\r\n\r\n \/\/ Get the support\r\n \/\/ NOTE: Because of the way we define the support, FeatureTransformed can only work on\r\n \/\/ one Body feature at a time\r\n \/\/ TODO: Currently, the support is simply the first Original. Change this to the Body feature later\r\n Part::Feature* supportFeature = static_cast<Part::Feature*>(getSupportObject());\r\n const Part::TopoShape& supportTopShape = supportFeature->Shape.getShape();\r\n if (supportTopShape._Shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Cannot transform invalid support shape\");\r\n\r\n \/\/ create an untransformed copy of the support shape\r\n Part::TopoShape supportShape(supportTopShape);\r\n supportShape.setTransform(Base::Matrix4D());\r\n TopoDS_Shape support = supportShape._Shape;\r\n\r\n std::set<std::vector<gp_Trsf>::const_iterator> nointersect_trsfms;\r\n std::set<std::vector<gp_Trsf>::const_iterator> overlapping_trsfms;\r\n\r\n \/\/ NOTE: It would be possible to build a compound from all original addShapes\/subShapes and then\r\n \/\/ transform the compounds as a whole. But we choose to apply the transformations to each\r\n \/\/ Original separately. This way it is easier to discover what feature causes a fuse\/cut\r\n \/\/ to fail. The downside is that performance suffers when there are many originals. But it seems\r\n \/\/ safe to assume that in most cases there are few originals and many transformations\r\n for (std::vector<App::DocumentObject*>::const_iterator o = originals.begin(); o != originals.end(); o++)\r\n {\r\n \/\/ Extract the original shape and determine whether to cut or to fuse\r\n TopoDS_Shape shape;\r\n bool fuse;\r\n\r\n if ((*o)->getTypeId().isDerivedFrom(PartDesign::Additive::getClassTypeId())) {\r\n PartDesign::Additive* addFeature = static_cast<PartDesign::Additive*>(*o);\r\n shape = addFeature->AddShape.getShape()._Shape;\r\n if (shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Shape of additive feature is empty\");\r\n fuse = true;\r\n } else if ((*o)->getTypeId().isDerivedFrom(PartDesign::Subtractive::getClassTypeId())) {\r\n PartDesign::Subtractive* subFeature = static_cast<PartDesign::Subtractive*>(*o);\r\n shape = subFeature->SubShape.getShape()._Shape;\r\n if (shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Shape of subtractive feature is empty\");\r\n fuse = false;\r\n } else {\r\n return new App::DocumentObjectExecReturn(\"Only additive and subtractive features can be transformed\");\r\n }\r\n\r\n \/\/ Transform the add\/subshape and collect the resulting shapes for overlap testing\r\n std::vector<std::vector<gp_Trsf>::const_iterator> v_transformations;\r\n std::vector<TopoDS_Shape> v_transformedShapes;\r\n\r\n std::vector<gp_Trsf>::const_iterator t = transformations.begin();\r\n t++; \/\/ Skip first transformation, which is always the identity transformation\r\n for (; t != transformations.end(); t++) {\r\n \/\/ Make an explicit copy of the shape because the \"true\" parameter to BRepBuilderAPI_Transform\r\n \/\/ seems to be pretty broken\r\n BRepBuilderAPI_Copy copy(shape);\r\n shape = copy.Shape();\r\n if (shape.IsNull())\r\n throw Base::Exception(\"Transformed: Linked shape object is empty\");\r\n\r\n BRepBuilderAPI_Transform mkTrf(shape, *t, false); \/\/ No need to copy, now\r\n if (!mkTrf.IsDone())\r\n return new App::DocumentObjectExecReturn(\"Transformation failed\", (*o));\r\n\r\n \/\/ Check for intersection with support\r\n if (!Part::checkIntersection(support, mkTrf.Shape(), false, true)) {\r\n Base::Console().Warning(\"Transformed shape does not intersect support %s: Removed\\n\", (*o)->getNameInDocument());\r\n nointersect_trsfms.insert(t);\r\n } else {\r\n v_transformations.push_back(t);\r\n v_transformedShapes.push_back(mkTrf.Shape());\r\n \/\/ Note: Transformations that do not intersect the support are ignored in the overlap tests\r\n }\r\n }\r\n\r\n if (v_transformedShapes.empty())\r\n break; \/\/ Skip the overlap check and go on to next original\r\n\r\n \/\/ Check for overlapping of the original and the transformed shapes, and remove the overlapping transformations\r\n if (this->getTypeId() != PartDesign::MultiTransform::getClassTypeId()) {\r\n \/\/ If there is only one transformed feature, we allow an overlap (though it might seem\r\n \/\/ illogical to the user why we allow overlapping shapes in this case!)\r\n if (v_transformedShapes.size() > 1)\r\n if (Part::checkIntersection(shape, v_transformedShapes.front(), false, false)) {\r\n \/\/ For single transformations, if one overlaps, all overlap, as long as we have uniform increments\r\n overlapping_trsfms.insert(v_transformations.begin(),v_transformations.end());\r\n v_transformedShapes.clear();\r\n }\r\n } else {\r\n \/\/ For MultiTransform, just checking the first transformed shape is not sufficient - any two\r\n \/\/ features might overlap, even if the original and the first shape don't overlap!\r\n\r\n std::set<std::vector<TopoDS_Shape>::iterator> rejected_iterators;\r\n\r\n std::vector<TopoDS_Shape>::iterator s1 = v_transformedShapes.begin();\r\n std::vector<TopoDS_Shape>::iterator s2 = s1;\r\n s2++;\r\n std::vector<std::vector<gp_Trsf>::const_iterator>::const_iterator t1 = v_transformations.begin();\r\n std::vector<std::vector<gp_Trsf>::const_iterator>::const_iterator t2 = t1;\r\n t2++;\r\n for (; s2 != v_transformedShapes.end();) {\r\n \/\/ Check intersection with the original\r\n if (Part::checkIntersection(shape, *s1, false, false)) {\r\n rejected_iterators.insert(s1);\r\n overlapping_trsfms.insert(*t1);\r\n }\r\n \/\/ Check intersection with other transformations\r\n for (; s2 != v_transformedShapes.end(); s2++, t2++)\r\n if (Part::checkIntersection(*s1, *s2, false, false)) {\r\n rejected_iterators.insert(s1);\r\n rejected_iterators.insert(s2);\r\n overlapping_trsfms.insert(*t1);\r\n overlapping_trsfms.insert(*t2);\r\n }\r\n s1++;\r\n s2 = s1;\r\n s2++;\r\n t1++;\r\n t2 = t1;\r\n t2++;\r\n }\r\n \/\/ Check intersection of last transformation with the original\r\n if (Part::checkIntersection(shape, *s1, false, false)) {\r\n rejected_iterators.insert(s1);\r\n overlapping_trsfms.insert(*t1);\r\n }\r\n\r\n for (std::set<std::vector<TopoDS_Shape>::iterator>::reverse_iterator it = rejected_iterators.rbegin();\r\n it != rejected_iterators.rend(); it++)\r\n v_transformedShapes.erase(*it);\r\n }\r\n\r\n if (v_transformedShapes.empty())\r\n break; \/\/ Skip the boolean operation and go on to next original\r\n\r\n \/\/ Build a compound from all the valid transformations\r\n BRep_Builder builder;\r\n TopoDS_Compound transformedShapes;\r\n builder.MakeCompound(transformedShapes);\r\n for (std::vector<TopoDS_Shape>::const_iterator s = v_transformedShapes.begin(); s != v_transformedShapes.end(); s++)\r\n builder.Add(transformedShapes, *s);\r\n\r\n \/\/ Fuse\/Cut the compounded transformed shapes with the support\r\n TopoDS_Shape result;\r\n\r\n if (fuse) {\r\n BRepAlgoAPI_Fuse mkFuse(support, transformedShapes);\r\n if (!mkFuse.IsDone())\r\n return new App::DocumentObjectExecReturn(\"Fusion with support failed\", *o);\r\n \/\/ we have to get the solids (fuse sometimes creates compounds)\r\n result = this->getSolid(mkFuse.Shape());\r\n \/\/ lets check if the result is a solid\r\n if (result.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Resulting shape is not a solid\", *o);\r\n } else {\r\n BRepAlgoAPI_Cut mkCut(support, transformedShapes);\r\n if (!mkCut.IsDone())\r\n return new App::DocumentObjectExecReturn(\"Cut out of support failed\", *o);\r\n result = mkCut.Shape();\r\n }\r\n\r\n support = result; \/\/ Use result of this operation for fuse\/cut of next original\r\n }\r\n\r\n if (!overlapping_trsfms.empty())\r\n \/\/ Concentrate on overlapping shapes since they are more serious\r\n for (std::set<std::vector<gp_Trsf>::const_iterator>::const_iterator it = overlapping_trsfms.begin();\r\n it != overlapping_trsfms.end(); it++)\r\n rejected.push_back(**it);\r\n else\r\n for (std::set<std::vector<gp_Trsf>::const_iterator>::const_iterator it = nointersect_trsfms.begin();\r\n it != nointersect_trsfms.end(); it++)\r\n rejected.push_back(**it);\r\n\r\n this->Shape.setValue(support);\r\n if (!overlapping_trsfms.empty())\r\n return new App::DocumentObjectExecReturn(\"Transformed objects are overlapping, try using a higher length or reducing the number of occurrences\");\r\n \/\/ Note: This limitation could be overcome by fusing the transformed features instead of\r\n \/\/ compounding them, probably at the expense of quite a bit of performance and complexity\r\n \/\/ in this code\r\n else\r\n return App::DocumentObject::StdReturn;\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#ifndef STRONG_STRONG_HPP\n#define STRONG_STRONG_HPP\n\n#include <type_traits>\n#include <utility>\n\n\/**\n * Namespace for creating strong typedefs.\n *\/\nnamespace strong {\n\n\/**\n * A strong typedef wrapper around some Type.\n *\n * Allows the programmer to define a strong type to avoid comparing values that have the same type\n * but are logically different. For example, IDs in a geographic map application for intersections\n * and streets may both be integers, but one should not logically compare an intersection ID with\n * a street ID.\n *\n * Strong typedefs that inherit from this class can be explicitly converted to their base Type,\n * but not implicitly converted. For more information please see:\n * http:\/\/en.cppreference.com\/w\/cpp\/language\/cast_operator\n *\n * @tparam Tag A unique identifier for this type\n * @tparam Type The actual type (e.g. int) to use\n *\/\ntemplate<class Tag, typename Type>\nclass type {\npublic:\n \/**\n * The default constructor of type will attempt to initialize the underlying value with its own\n * default constructor.\n *\/\n constexpr type() : value()\n {\n }\n\n \/**\n * Initialize the underlying value via a copy or move.\n *\n * @param v The value to copy.\n *\/\n explicit constexpr type(Type const &v) : value(v)\n {\n }\n\n \/**\n * Move constructor.\n *\n * If Type's move constructor does not throw, then this move constructor will have noexcept\n * enabled, which will allow for certain optimizations. For more information, please refer\n * to https:\/\/akrzemi1.wordpress.com\/2014\/04\/24\/noexcept-what-for\/\n *\n * @param v The value to move.\n *\/\n explicit constexpr type(Type && v) noexcept(std::is_nothrow_move_constructible<Type>::value)\n : value(static_cast<Type &&>(v))\n {\n }\n\n \/**\n * Enables explicit conversion of the type.\n *\n * @return The underlying value.\n *\/\n explicit operator Type &() noexcept\n {\n return value;\n }\n\n \/**\n * Enables const-correct explicit conversion of the type.\n *\n * @return The underlying value.\n *\/\n explicit constexpr operator Type const &() const noexcept\n {\n return value;\n }\nprivate:\n Type value;\n};\n\nnamespace detail {\n\/**\n * A dummy function used to help determine the type of the underlying value of a strong typedef.\n *\/\ntemplate <class Tag, typename Type>\nType dummy_function(type<Tag, Type>);\n}\n\n\/**\n * Determine the type of the underlying value of a strong typedef.\n *\/\ntemplate <class Typedef>\nusing underlying_type = decltype(detail::dummy_function(std::declval<Typedef>()));\n\n\/**\n * Operations to enable on strong typedefs.\n *\/\nnamespace op {\n\ntemplate<class Typedef, typename Result = bool>\nclass equality {\npublic:\n friend constexpr Result operator==(Typedef const &lhs, Typedef const &rhs) {\n using type = underlying_type<Typedef>;\n return static_cast<type const &>(lhs) == static_cast<type const &>(rhs);\n }\n\n friend constexpr Result operator!=(Typedef const &lhs, Typedef const &rhs) {\n return !(lhs == rhs);\n }\n};\n\ntemplate<class Typedef, typename OtherType = Typedef, typename Result = bool>\nclass mixed_equality {\npublic:\n friend constexpr Result operator==(Typedef const &lhs, OtherType const &rhs)\n {\n using type = underlying_type<Typedef>;\n return static_cast<type const &>(lhs) == static_cast<type const &>(rhs);\n }\n\n friend constexpr Result operator!=(Typedef const &lhs, OtherType const &rhs)\n {\n return !(lhs == rhs);\n }\n\n friend constexpr Result operator==(OtherType const &lhs, Typedef const &rhs)\n {\n using type = underlying_type<Typedef>;\n return static_cast<type const &>(lhs) == static_cast<type const &>(rhs);\n }\n\n friend constexpr Result operator!=(OtherType const &lhs, Typedef const &rhs)\n {\n return !(lhs == rhs);\n }\n};\n}\n\n}\n\n#endif \/\/STRONG_STRONG_HPP\n<commit_msg>Improve documentation of equality operator<commit_after>#ifndef STRONG_STRONG_HPP\n#define STRONG_STRONG_HPP\n\n#include <type_traits>\n#include <utility>\n\n\/**\n * Namespace for creating strong typedefs.\n *\/\nnamespace strong {\n\n\/**\n * A strong typedef wrapper around some Type.\n *\n * Allows the programmer to define a strong type to avoid comparing values that have the same type\n * but are logically different. For example, IDs in a geographic map application for intersections\n * and streets may both be integers, but one should not logically compare an intersection ID with\n * a street ID.\n *\n * Strong typedefs that inherit from this class can be explicitly converted to their base Type,\n * but not implicitly converted. For more information please see:\n * http:\/\/en.cppreference.com\/w\/cpp\/language\/cast_operator\n *\n * @tparam Tag A unique identifier for this type\n * @tparam Type The actual type (e.g. int) to use\n *\/\ntemplate<class Tag, typename Type>\nclass type {\npublic:\n \/**\n * The default constructor of type will attempt to initialize the underlying value with its own\n * default constructor.\n *\/\n constexpr type() : value()\n {\n }\n\n \/**\n * Initialize the underlying value via a copy or move.\n *\n * @param v The value to copy.\n *\/\n explicit constexpr type(Type const &v) : value(v)\n {\n }\n\n \/**\n * Move constructor.\n *\n * If Type's move constructor does not throw, then this move constructor will have noexcept\n * enabled, which will allow for certain optimizations. For more information, please refer\n * to https:\/\/akrzemi1.wordpress.com\/2014\/04\/24\/noexcept-what-for\/\n *\n * @param v The value to move.\n *\/\n explicit constexpr type(Type && v) noexcept(std::is_nothrow_move_constructible<Type>::value)\n : value(static_cast<Type &&>(v))\n {\n }\n\n \/**\n * Enables explicit conversion of the type.\n *\n * @return The underlying value.\n *\/\n explicit operator Type &() noexcept\n {\n return value;\n }\n\n \/**\n * Enables const-correct explicit conversion of the type.\n *\n * @return The underlying value.\n *\/\n explicit constexpr operator Type const &() const noexcept\n {\n return value;\n }\nprivate:\n Type value;\n};\n\nnamespace detail {\n\/**\n * A dummy function used to help determine the type of the underlying value of a strong typedef.\n *\/\ntemplate <class Tag, typename Type>\nType dummy_function(type<Tag, Type>);\n}\n\n\/**\n * Determine the type of the underlying value of a strong typedef.\n *\/\ntemplate <class Typedef>\nusing underlying_type = decltype(detail::dummy_function(std::declval<Typedef>()));\n\n\/**\n * Operations to enable on strong typedefs.\n *\/\nnamespace op {\n\n\/**\n * Tests for equality or inequality between identical strong types.\n *\n * @tparam Tag The strong typedef to compare.\n * @tparam Result The return type of the comparison\n *\/\ntemplate<class Tag, typename Result = bool>\nclass equality {\npublic:\n \/**\n * Test for equality.\n *\n * @param lhs The left-hand side of the relational expression.\n * @param rhs The right-hand side of the relational expression.\n * @return The result of the comparison.\n *\/\n friend constexpr Result operator==(Tag const &lhs, Tag const &rhs) {\n using type = underlying_type<Tag>;\n return static_cast<type const &>(lhs) == static_cast<type const &>(rhs);\n }\n\n \/**\n * Test for inequality.\n *\n * @param lhs The left-hand side of the relational expression.\n * @param rhs The right-hand side of the relational expression.\n * @return The result of the comparison.\n *\/\n friend constexpr Result operator!=(Tag const &lhs, Tag const &rhs) {\n return !(lhs == rhs);\n }\n};\n\n\/**\n * Tests for equality or inequality between different strong types.\n *\n * @tparam Tag The strong typedef to compare.\n * @tparam OtherTag The other strong typedef to compare.\n * @tparam Result The return type of the comparison\n *\/\ntemplate<class Tag, typename OtherTag, typename Result = bool>\nclass mixed_equality {\npublic:\n \/**\n * Test for equality.\n *\n * @param lhs The left-hand side of the relational expression.\n * @param rhs The right-hand side of the relational expression.\n * @return The result of the comparison.\n *\/\n friend constexpr Result operator==(Tag const &lhs, OtherTag const &rhs)\n {\n using type = underlying_type<Tag>;\n return static_cast<type const &>(lhs) == static_cast<type const &>(rhs);\n }\n\n \/**\n * Test for inequality.\n *\n * @param lhs The left-hand side of the relational expression.\n * @param rhs The right-hand side of the relational expression.\n * @return The result of the comparison.\n *\/\n friend constexpr Result operator!=(Tag const &lhs, OtherTag const &rhs)\n {\n return !(lhs == rhs);\n }\n\n \/**\n * Test for equality.\n *\n * @param lhs The left-hand side of the relational expression.\n * @param rhs The right-hand side of the relational expression.\n * @return The result of the comparison.\n *\/\n friend constexpr Result operator==(OtherTag const &lhs, Tag const &rhs)\n {\n using type = underlying_type<Tag>;\n return static_cast<type const &>(lhs) == static_cast<type const &>(rhs);\n }\n\n \/**\n * Test for inequality.\n *\n * @param lhs The left-hand side of the relational expression.\n * @param rhs The right-hand side of the relational expression.\n * @return The result of the comparison.\n *\/\n friend constexpr Result operator!=(OtherTag const &lhs, Tag const &rhs)\n {\n return !(lhs == rhs);\n }\n};\n}\n\n}\n\n#endif \/\/STRONG_STRONG_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: certvalidity.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 17:25:39 $\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#include <xmlsecurity\/certvalidity.hxx>\n\n#ifndef _COM_SUN_STAR_SECURITY_CERTIFICATEVALIDITY_HPP_\n#include <com\/sun\/star\/security\/CertificateValidity.hpp>\n#endif\n\nusing ::rtl::OUString ;\nusing namespace ::com::sun::star::security ;\n\n#define VALID_STR \"valid certificate\"\n#define INVALID_STR \"invalid certificate\"\n#define UNTRUSTED_STR \"untrusted certificate\"\n#define TIMEOUT_STR \"expired certificate\"\n#define REVOKED_STR \"revoked certificate\"\n#define UNKNOWN_REVOKATION_STR \"unknown certificate revocation status\"\n#define SIGNATURE_INVALID_STR \"invalid certificate signature\"\n#define EXTENSION_INVALID_STR \"invalid certificate extension\"\n#define EXTENSION_UNKNOWN_STR \"unknown critical certificate extension\"\n#define ISSUER_UNKNOWN_STR \"unknown certificate issuer\"\n#define ISSUER_UNTRUSTED_STR \"untrusted certificate issuer\"\n#define ISSUER_INVALID_STR \"invalid certificate issuer\"\n#define ROOT_UNKNOWN_STR \"unknown root certificate\"\n#define ROOT_UNTRUSTED_STR \"untrusted root certificate\"\n#define ROOT_INVALID_STR \"invalid root certificate\"\n#define CHAIN_INCOMPLETE_STR \"invalid certification path\"\n\nrtl::OUString certificateValidityToOUString( ::sal_Int32 certValidity ) {\n OUString aValidity ;\n\n if( !certValidity ) {\n aValidity = OUString::createFromAscii( ( const char* )VALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::INVALID ) == CertificateValidity::INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::UNTRUSTED ) == CertificateValidity::UNTRUSTED ) {\n aValidity = OUString::createFromAscii( ( const char* )UNTRUSTED_STR ) ;\n } else if( ( certValidity & CertificateValidity::TIMEOUT ) == CertificateValidity::TIMEOUT ) {\n aValidity = OUString::createFromAscii( ( const char* )TIMEOUT_STR ) ;\n } else if( ( certValidity & CertificateValidity::REVOKED ) == CertificateValidity::REVOKED ) {\n aValidity = OUString::createFromAscii( ( const char* )REVOKED_STR ) ;\n } else if( ( certValidity & CertificateValidity::UNKNOWN_REVOKATION ) == CertificateValidity::UNKNOWN_REVOKATION ) {\n aValidity = OUString::createFromAscii( ( const char* )UNKNOWN_REVOKATION_STR ) ;\n } else if( ( certValidity & CertificateValidity::SIGNATURE_INVALID ) == CertificateValidity::SIGNATURE_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )SIGNATURE_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::EXTENSION_INVALID ) == CertificateValidity::EXTENSION_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )EXTENSION_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::EXTENSION_UNKNOWN ) == CertificateValidity::EXTENSION_UNKNOWN ) {\n aValidity = OUString::createFromAscii( ( const char* )EXTENSION_UNKNOWN_STR ) ;\n } else if( ( certValidity & CertificateValidity::ISSUER_UNKNOWN ) == CertificateValidity::ISSUER_UNKNOWN ) {\n aValidity = OUString::createFromAscii( ( const char* )ISSUER_UNKNOWN_STR ) ;\n } else if( ( certValidity & CertificateValidity::ISSUER_UNTRUSTED ) == CertificateValidity::ISSUER_UNTRUSTED ) {\n aValidity = OUString::createFromAscii( ( const char* )ISSUER_UNTRUSTED_STR ) ;\n } else if( ( certValidity & CertificateValidity::ISSUER_INVALID ) == CertificateValidity::ISSUER_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )ISSUER_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::ROOT_UNKNOWN ) == CertificateValidity::ROOT_UNKNOWN ) {\n aValidity = OUString::createFromAscii( ( const char* )ROOT_UNKNOWN_STR ) ;\n } else if( ( certValidity & CertificateValidity::ROOT_UNTRUSTED ) == CertificateValidity::ROOT_UNTRUSTED ) {\n aValidity = OUString::createFromAscii( ( const char* )ROOT_UNTRUSTED_STR ) ;\n } else if( ( certValidity & CertificateValidity::ROOT_INVALID ) == CertificateValidity::ROOT_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )ROOT_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::CHAIN_INCOMPLETE ) == CertificateValidity::CHAIN_INCOMPLETE ) {\n aValidity = OUString::createFromAscii( ( const char* )CHAIN_INCOMPLETE_STR ) ;\n } else {\n aValidity = OUString::createFromAscii( ( const char* )INVALID_STR ) ;\n }\n\n return aValidity ;\n}\n\n<commit_msg>INTEGRATION: CWS xmlsec13 (1.3.24); FILE MERGED 2005\/10\/31 13:37:40 jl 1.3.24.2: RESYNC: (1.3-1.4); FILE MERGED 2005\/10\/25 08:19:19 jl 1.3.24.1: #54495# #54047# extra verification of certificates, better errorhandling<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: certvalidity.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-11-11 09:19:09 $\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#include <xmlsecurity\/certvalidity.hxx>\n\n#ifndef _COM_SUN_STAR_SECURITY_CERTIFICATEVALIDITY_HPP_\n#include <com\/sun\/star\/security\/CertificateValidity.hpp>\n#endif\n\nusing ::rtl::OUString ;\nusing namespace ::com::sun::star::security ;\n\n#define VALID_STR \"valid certificate\"\n#define INVALID_STR \"invalid certificate\"\n#define UNTRUSTED_STR \"untrusted certificate\"\n#define TIME_INVALID_STR \"expired certificate\"\n#define NOT_NESTED_TIME_STR \"invalid time nesting\"\n#define REVOKED_STR \"revoked certificate\"\n#define UNKNOWN_REVOKATION_STR \"unknown certificate revocation status\"\n#define SIGNATURE_INVALID_STR \"invalid certificate signature\"\n#define EXTENSION_INVALID_STR \"invalid certificate extension\"\n#define EXTENSION_UNKNOWN_STR \"unknown critical certificate extension\"\n#define ISSUER_UNKNOWN_STR \"unknown certificate issuer\"\n#define ISSUER_UNTRUSTED_STR \"untrusted certificate issuer\"\n#define ISSUER_INVALID_STR \"invalid certificate issuer\"\n#define ROOT_UNKNOWN_STR \"unknown root certificate\"\n#define ROOT_UNTRUSTED_STR \"untrusted root certificate\"\n#define ROOT_INVALID_STR \"invalid root certificate\"\n#define CHAIN_INCOMPLETE_STR \"invalid certification path\"\n\nrtl::OUString certificateValidityToOUString( ::sal_Int32 certValidity ) {\n OUString aValidity ;\n\n if( (certValidity & CertificateValidity::VALID) == CertificateValidity::VALID ) {\n aValidity = OUString::createFromAscii( ( const char* )VALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::INVALID ) == CertificateValidity::INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::UNTRUSTED ) == CertificateValidity::UNTRUSTED ) {\n aValidity = OUString::createFromAscii( ( const char* )UNTRUSTED_STR ) ;\n } else if( ( certValidity & CertificateValidity::TIME_INVALID ) == CertificateValidity::TIME_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )TIME_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::NOT_TIME_NESTED ) == CertificateValidity::NOT_TIME_NESTED ) {\n aValidity = OUString::createFromAscii( ( const char* )NOT_NESTED_TIME_STR ) ;\n } else if( ( certValidity & CertificateValidity::REVOKED ) == CertificateValidity::REVOKED ) {\n aValidity = OUString::createFromAscii( ( const char* )REVOKED_STR ) ;\n } else if( ( certValidity & CertificateValidity::UNKNOWN_REVOKATION ) == CertificateValidity::UNKNOWN_REVOKATION ) {\n aValidity = OUString::createFromAscii( ( const char* )UNKNOWN_REVOKATION_STR ) ;\n } else if( ( certValidity & CertificateValidity::SIGNATURE_INVALID ) == CertificateValidity::SIGNATURE_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )SIGNATURE_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::EXTENSION_INVALID ) == CertificateValidity::EXTENSION_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )EXTENSION_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::EXTENSION_UNKNOWN ) == CertificateValidity::EXTENSION_UNKNOWN ) {\n aValidity = OUString::createFromAscii( ( const char* )EXTENSION_UNKNOWN_STR ) ;\n } else if( ( certValidity & CertificateValidity::ISSUER_UNKNOWN ) == CertificateValidity::ISSUER_UNKNOWN ) {\n aValidity = OUString::createFromAscii( ( const char* )ISSUER_UNKNOWN_STR ) ;\n } else if( ( certValidity & CertificateValidity::ISSUER_UNTRUSTED ) == CertificateValidity::ISSUER_UNTRUSTED ) {\n aValidity = OUString::createFromAscii( ( const char* )ISSUER_UNTRUSTED_STR ) ;\n } else if( ( certValidity & CertificateValidity::ISSUER_INVALID ) == CertificateValidity::ISSUER_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )ISSUER_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::ROOT_UNKNOWN ) == CertificateValidity::ROOT_UNKNOWN ) {\n aValidity = OUString::createFromAscii( ( const char* )ROOT_UNKNOWN_STR ) ;\n } else if( ( certValidity & CertificateValidity::ROOT_UNTRUSTED ) == CertificateValidity::ROOT_UNTRUSTED ) {\n aValidity = OUString::createFromAscii( ( const char* )ROOT_UNTRUSTED_STR ) ;\n } else if( ( certValidity & CertificateValidity::ROOT_INVALID ) == CertificateValidity::ROOT_INVALID ) {\n aValidity = OUString::createFromAscii( ( const char* )ROOT_INVALID_STR ) ;\n } else if( ( certValidity & CertificateValidity::CHAIN_INCOMPLETE ) == CertificateValidity::CHAIN_INCOMPLETE ) {\n aValidity = OUString::createFromAscii( ( const char* )CHAIN_INCOMPLETE_STR ) ;\n } else {\n aValidity = OUString::createFromAscii( ( const char* )INVALID_STR ) ;\n }\n\n return aValidity ;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"chain_factory.h\"\n#include \"path\/radix_tree.h\"\n#include \"..\/chain_of_responsibility\/node_interface.h\"\n\n#include <memory>\n\nnamespace endpoints \n{\n\n\nclass chain_maker {\n\tradix_tree<chain_generator_t, '\/', false> t_;\n\npublic:\n\tchain_maker(radix_tree<chain_generator_t, '\/', false> tree) noexcept\n\t\t: t_{std::move(tree)}\n\t{}\n\tradix_tree<chain_generator_t, '\/', false>* operator()() noexcept { return &t_; }\n};\n\n\nchain_factory::chain_factory(chain_generator_t fallback_logic) noexcept\n\t: fallback_logic{std::move(fallback_logic)}\n{}\n\nchain_factory::~chain_factory() noexcept\n{}\n\nvoid chain_factory::get(const std::string& host, const std::string &path, chain_generator_t logic)\n{\n\taddPattern(GET, host, path, std::move(logic));\n}\n\n\nvoid chain_factory::post(const std::string& host, const std::string &path, chain_generator_t logic)\n{\n\taddPattern(POST, host, path, std::move(logic));\n}\n\nvoid chain_factory::put(const std::string& host, const std::string &path, chain_generator_t logic)\n{\n\taddPattern(PUT, host, path, std::move(logic));\n}\n\nchain_factory::chain_ptr chain_factory::get_chain(const http::http_request &original_request) const\n{\n\treturn get_chain_private(original_request);\n}\n\nchain_factory::chain_ptr chain_factory::get_chain_and_params(http::http_request &original_request) const\n{\n\treturn get_chain_private<true>(original_request);\n}\n\nvoid chain_factory::addPattern(chain_factory::method m, const std::string& host, const std::string& path, chain_generator_t logic)\n{\n\tif ( ! host_trees[m] )\n\t\thost_trees[m] = std::make_unique<radix_tree<tree_generator_t, '.', true>>();\n\n\tradix_tree<chain_generator_t, '\/', false> tree;\n\ttree.addPattern(path, std::move(logic));\n\tchain_maker maker{std::move(tree)};\n\n\thost_trees[m]->addPattern(host.empty() ? \"*\" : host, std::move(maker));\n}\n\n\n}\n<commit_msg>fixed chain_factory<commit_after>#include \"chain_factory.h\"\n#include \"path\/radix_tree.h\"\n#include \"..\/chain_of_responsibility\/node_interface.h\"\n\n#include <memory>\n\nnamespace endpoints \n{\n\n\nclass chain_maker {\n\tradix_tree<chain_generator_t, '\/', false> t_;\n\npublic:\n\tchain_maker(radix_tree<chain_generator_t, '\/', false> tree) noexcept\n\t\t: t_{std::move(tree)}\n\t{}\n\tradix_tree<chain_generator_t, '\/', false>* operator()() noexcept { return &t_; }\n};\n\n\nchain_factory::chain_factory(chain_generator_t fallback_logic) noexcept\n\t: fallback_logic{std::move(fallback_logic)}\n{}\n\nchain_factory::~chain_factory() noexcept\n{}\n\nvoid chain_factory::get(const std::string& host, const std::string &path, chain_generator_t logic)\n{\n\taddPattern(GET, host, path, std::move(logic));\n}\n\n\nvoid chain_factory::post(const std::string& host, const std::string &path, chain_generator_t logic)\n{\n\taddPattern(POST, host, path, std::move(logic));\n}\n\nvoid chain_factory::put(const std::string& host, const std::string &path, chain_generator_t logic)\n{\n\taddPattern(PUT, host, path, std::move(logic));\n}\n\nchain_factory::chain_ptr chain_factory::get_chain(const http::http_request &original_request) const\n{\n\treturn get_chain_private(original_request);\n}\n\nchain_factory::chain_ptr chain_factory::get_chain_and_params(http::http_request &original_request) const\n{\n\treturn get_chain_private<true>(original_request);\n}\n\nvoid chain_factory::addPattern(chain_factory::method m, const std::string& host, const std::string& path, chain_generator_t logic)\n{\n\tif ( ! host_trees[m] )\n\t\thost_trees[m] = std::make_unique<radix_tree<tree_generator_t, '.', true>>();\n\n\tif(host_trees[m]->matches(host)) {\n\t\tauto ptr = host_trees[m]->get(host);\n\t\tif(ptr != nullptr)\n\t\t\treturn ptr->addPattern(host, std::move(logic));\n\t}\n\n\tradix_tree<chain_generator_t, '\/', false> tree;\n\ttree.addPattern(path, std::move(logic));\n\tchain_maker maker{std::move(tree)};\n\thost_trees[m]->addPattern(host.empty() ? \"*\" : host, std::move(maker));\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX64M\/RX71M グループ FLASH 制御\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <cstring>\r\n#include \"common\/delay.hpp\"\r\n#include \"common\/format.hpp\"\r\n\r\nnamespace device {\r\n\r\n\/\/\/ F_FCLK は変換パラメーター計算で必要で、設定が無いとエラーにします。\r\n#ifndef F_FCLK\r\n# error \"flash_io.hpp requires F_FCLK to be defined\"\r\n#endif\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief FLASH 制御クラス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass flash_io {\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief データ・フラッシュ構成(全体64Kバイト、ブロック64バイト)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic const uint32_t data_flash_block = 64; \/\/\/< データ・フラッシュのブロックサイズ\r\n\t\tstatic const uint32_t data_flash_size = 65536; \/\/\/< データ・フラッシュの容量\r\n\t\tstatic const uint32_t data_flash_bank = 1024; \/\/\/< データ・フラッシュのバンク数\r\n\r\n\tprivate:\r\n\t\tbool\ttrans_farm_;\r\n\r\n\t\t\/\/\/ FACIコマンド発行領域 007E 0000h 4バイト\r\n\t\tstatic rw8_t<0x007E0000> FACI_CMD_AREA;\t\t\/\/\/< byte 書き込み\r\n\r\n\t\tstatic rw16_t<0x007E0000> FACI_CMD_AREA16;\t\/\/\/< word(16) 書き込み\r\n\r\n\t\t\/\/ return 「true」正常、「false」ロック状態\r\n\t\tbool turn_break_() const\r\n\t\t{\r\n\t\t\tFACI_CMD_AREA = 0xB3;\r\n\r\n\t\t\t\/\/ break (4 bytes): FCLK 20MHz to 60MHz max 20us\r\n\t\t\t\/\/ FCLK 4MHz max 32us\r\n\t\t\t\/\/ * 1.1\r\n\t\t\tuint32_t cnt = 22;\r\n\t\t\tif(F_FCLK < 20000000) cnt = 36;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(1);\r\n\t\t\t\t--cnt;\r\n\t\t\t\tif(cnt == 0) break;\r\n\t\t\t}\r\n\t\t\tif(cnt == 0) {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'turn_break_' timeout\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(device::FLASH::FASTAT.CMDLK() == 0) {\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'turn_break_' fail\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tvoid turn_rd_() const\r\n\t\t{\r\n\t\t\tuint32_t n = 5;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(1);\r\n\t\t\t\t--n;\r\n\t\t\t\tif(n == 0) break;\r\n\t\t\t} \r\n\t\t\tif(n == 0 || device::FLASH::FASTAT.CMDLK() != 0) {\r\n\t\t\t\tturn_break_();\r\n\t\t\t}\r\n\t\t\r\n\t\t\tdevice::FLASH::FENTRYR = 0xAA00;\r\n\r\n\t\t\tif(device::FLASH::FENTRYR() != 0x0000) {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'turn_rd_' fail\\n\"); \r\n#endif\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tvoid turn_pe_() const\r\n\t\t{\r\n\t\t\tdevice::FLASH::FENTRYR = 0xAA80;\r\n\r\n\t\t\tif(device::FLASH::FENTRYR() != 0x0080) {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'turn_pe_' fail\\n\"); \r\n#endif\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/\/ FCUファームウェア格納領域 FEFF F000h~FEFF FFFFh 4Kバイト\r\n\t\t\/\/\/ FCURAM領域 007F 8000h~007F 8FFFh 4Kバイト\r\n\t\t\/\/\/ コンフィギュレーション設定領域 0012 0040h~0012 007Fh 64バイト\r\n\t\tvoid init_fcu_()\r\n\t\t{\r\n\t\t\tif(trans_farm_) return;\r\n\r\n\t\t\tif(device::FLASH::FENTRYR() != 0) {\r\n\t\t\t\tdevice::FLASH::FENTRYR = 0xAA00;\r\n\t\t\t}\r\n\r\n\t\t\tdevice::FLASH::FCURAME = 0xC403; \/\/ Write only\r\n\r\n\t\t\tconst uint32_t* src = reinterpret_cast<const uint32_t*>(0xFEFFF000); \/\/ Farm master\r\n\t\t\tuint32_t* dst = reinterpret_cast<uint32_t*>(0x007F8000); \/\/ Farm section\r\n\t\t\tfor(uint32_t i = 0; i < (4096 \/ 4); ++i) {\r\n\t\t\t\t*dst++ = *src++;\r\n\t\t\t}\r\n\r\n\t\t\tdevice::FLASH::FCURAME = 0xC400;\r\n\r\n\t\t\tturn_pe_();\r\n\r\n\t\t\tauto f = turn_break_();\t\t\t\r\n\t\t\tif(f) {\r\n\t\t\t\tturn_rd_();\r\n\r\n\t\t\t\ttrans_farm_ = true;\r\n\t\t\t} else {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI Lock...\\n\");\r\n#endif\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/ 4 バイト書き込み\r\n\t\t\/\/ org: align 4 bytes\r\n\t\tbool write32_(const void* src, uint32_t org) const\r\n\t\t{\r\n\t\t\tdevice::FLASH::FPROTR = 0x5501;\r\n\t\t\tdevice::FLASH::FSADDR = org;\r\n\r\n\t\t\tFACI_CMD_AREA = 0xE8;\r\n\t\t\tFACI_CMD_AREA = 0x02;\r\n\r\n\t\t\tconst uint8_t* p = static_cast<const uint8_t*>(src);\r\n\t\t\tFACI_CMD_AREA16 = (static_cast<uint16_t>(p[1]) << 8) | static_cast<uint16_t>(p[0]);\r\n\r\n\t\t\twhile(device::FLASH::FSTATR.DBFULL() != 0) {\r\n\t\t\t\tasm(\"nop\");\r\n\t\t\t}\r\n\r\n\t\t\tFACI_CMD_AREA16 = (static_cast<uint16_t>(p[3]) << 8) | static_cast<uint16_t>(p[2]);\r\n\r\n\t\t\twhile(device::FLASH::FSTATR.DBFULL() != 0) {\r\n\t\t\t\tasm(\"nop\");\r\n\t\t\t}\r\n\r\n\t\t\tFACI_CMD_AREA = 0xD0;\r\n\r\n\r\n\t\t\t\/\/ write (4 bytes): FCLK 20MHz to 60MHz max 1.7ms\r\n\t\t\t\/\/ FCLK 4MHz max 3.8ms\r\n\t\t\t\/\/ * 1.1\r\n\t\t\tuint32_t cnt = 1870;\r\n\t\t\tif(F_FCLK < 20000000) cnt = 4180;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(1);\r\n\t\t\t\t--cnt;\r\n\t\t\t\tif(cnt == 0) break;\r\n\t\t\t}\r\n\t\t\tif(cnt == 0) { \/\/ time out\r\n\t\t\t\tturn_break_();\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'write32_' timeout\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(device::FLASH::FASTAT.CMDLK() != 0) {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'write32_' CMD Lock fail\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\tコンストラクター\r\n\t\t *\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tflash_io() : trans_farm_(false) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\t開始\r\n\t\t *\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid start()\r\n\t\t{\r\n\t\t\tdevice::FLASH::FWEPROR.FLWE = 1;\r\n\t\t\tinit_fcu_();\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 読み出し\r\n\t\t\t@param[in]\torg\t開始アドレス\r\n\t\t\t@return データ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint8_t read(uint32_t org) const\r\n\t\t{\r\n\t\t\tif(org >= data_flash_size) return 0;\r\n\t\t\tturn_rd_();\r\n\t\t\treturn device::rd8_(0x00100000 + org);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 読み出し\r\n\t\t\t@param[in]\torg\t開始アドレス\r\n\t\t\t@param[in]\tlen\tバイト数\r\n\t\t\t@param[out]\tdst\t先\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid read(uint32_t org, uint32_t len, void* dst) const\r\n\t\t{\r\n\t\t\tif(org >= data_flash_size) return;\r\n\t\t\tif((org + len) > data_flash_size) {\r\n\t\t\t\tlen = data_flash_size - org;\r\n\t\t\t}\r\n\t\t\tturn_rd_();\r\n\t\t\tconst void* src = reinterpret_cast<const void*>(0x00100000 + org);\r\n\t\t\tstd::memcpy(dst, src, len);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 消去チェック\r\n\t\t\t@param[in]\tbank\tバンク\r\n\t\t\t@return エラーがあれば「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool erase_check(uint32_t bank) const\r\n\t\t{\r\n\t\t\tif(bank >= data_flash_bank) return false;\r\n\r\n\t\t\tdevice::FLASH::FBCCNT = 0x00; \/\/ address increment\r\n\t\t\tdevice::FLASH::FSADDR = bank * data_flash_block;\r\n\t\t\tdevice::FLASH::FEADDR = ((bank + 1) * data_flash_block) - 1;\r\n\r\n\t\t\tFACI_CMD_AREA = 0x71;\r\n\t\t\tFACI_CMD_AREA = 0xD0;\r\n\r\n\t\t\t\/\/ erase cheak (4 bytes): FCLK 20MHz to 60MHz max 30us\r\n\t\t\t\/\/ FCLK 4MHz max 84us\r\n\t\t\t\/\/ * 1.1\r\n\t\t\tuint32_t cnt = 33 * 64 \/ 4;\r\n\t\t\tif(F_FCLK < 20000000) cnt = 93 * 64 \/ 4;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(1);\r\n\t\t\t\t--cnt;\r\n\t\t\t\tif(cnt == 0) break;\r\n\t\t\t}\r\n\t\t\tif(cnt == 0) { \/\/ time out\r\n\t\t\t\tturn_break_();\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'erase_check' timeout\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(device::FLASH::FASTAT.CMDLK() == 0) {\r\n\t\t\t\tif(device::FLASH::FBCSTAT.BCST() != 0) {\r\n\t\t\t\t\tutils::format(\"FACI 'erase_check' blank check fail: %04X\\n\") % device::FLASH::FPSADDR();\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'erase_check' fail\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 消去\r\n\t\t\t@param[in]\tbank\tバンク\r\n\t\t\t@return エラーがあれば「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool erase(uint32_t bank) const\r\n\t\t{\r\n\t\t\tif(bank >= data_flash_bank) return false;\r\n\r\n\t\t\tturn_pe_();\r\n\r\n\t\t\tdevice::FLASH::FPROTR = 0x5501;\r\n\t\t\tdevice::FLASH::FCPSR = 0x0000; \/\/ サスペンド優先\r\n\t\t\tdevice::FLASH::FSADDR = bank * data_flash_block;\r\n\r\n\t\t\tFACI_CMD_AREA = 0x20;\r\n\t\t\tFACI_CMD_AREA = 0xD0;\r\n\r\n\t\t\t\/\/ 64 bytes erase: FCLK 20MHz to 60MHz max 10ms\r\n\t\t\t\/\/ FCLK 4MHz max 18ms\r\n\t\t\t\/\/ * 1.1\r\n\t\t\tuint32_t cnt = 1100;\r\n\t\t\tif(F_FCLK < 20000000) cnt = 1980;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(10);\r\n\t\t\t\t--cnt;\r\n\t\t\t\tif(cnt == 0) break;\r\n\t\t\t}\r\n\t\t\tif(cnt == 0) { \/\/ time out\r\n\t\t\t\tturn_break_();\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'erase' timeout\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(device::FLASH::FASTAT.CMDLK() == 0) {\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'erase' fail\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 書き込み\r\n\t\t\t@param[in]\tsrc ソース\r\n\t\t\t@param[in]\torg\t開始オフセット\r\n\t\t\t@param[in]\tlen\tバイト数(4の倍数)\r\n\t\t\t@return エラーがあれば「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool write(const void* src, uint32_t org, uint32_t len) const\r\n\t\t{\r\n\/\/\/\t\t\tif((len & 3) != 0 || (org & 3) != 0) return false;\r\n\r\n\t\t\tif(org >= data_flash_size) return false;\r\n\r\n\t\t\tif((org + len) > data_flash_size) {\r\n\t\t\t\tlen = data_flash_size - org;\r\n\t\t\t}\r\n\r\n\t\t\tturn_pe_();\r\n\r\n\t\t\tconst uint8_t* p = static_cast<const uint8_t*>(src);\r\n\t\t\tbool f = false;\r\n\t\t\tint32_t l = static_cast<int32_t>(len);\r\n\t\t\twhile(l > 0) {\r\n\t\t\t\tuint32_t mod = org & 3;\r\n\t\t\t\tif(mod != 0) {\r\n\t\t\t\t\tuint8_t tmp[4];\r\n\t\t\t\t\ttmp[0] = 0xFF;\r\n\t\t\t\t\ttmp[1] = 0xFF;\r\n\t\t\t\t\ttmp[2] = 0xFF;\r\n\t\t\t\t\ttmp[3] = 0xFF;\r\n\t\t\t\t\tl -= 4 - mod;\r\n\t\t\t\t\twhile(mod < 3) {\r\n\t\t\t\t\t\ttmp[mod] = *p++;\r\n\t\t\t\t\t\t++mod;\r\n\t\t\t\t\t}\r\n\t\t\t\t\torg &= 0xFFFFFFFC;\r\n\t\t\t\t\tf = write32_(tmp, org);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tf = write32_(p, org);\r\n\t\t\t\t\tp += 4;\r\n\t\t\t\t\tl -= 4;\r\n\t\t\t\t}\r\n\t\t\t\tif(!f) break;\r\n\t\t\t\torg += 4;\r\n\t\t\t}\r\n\t\t\treturn f;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 書き込み\r\n\t\t\t@param[in]\torg\t開始オフセット\r\n\t\t\t@param[in]\tdata\t書き込みデータ\r\n\t\t\t@return エラーがあれば「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool write(uint32_t org, uint8_t data) const\r\n\t\t{\r\n\t\t\tuint8_t d = data;\r\n\t\t\treturn write(&d, org, 1);\r\n\t\t}\r\n\t};\r\n}\r\n<commit_msg>cleanup<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX64M\/RX71M グループ FLASH 制御\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <cstring>\r\n#include \"common\/delay.hpp\"\r\n#include \"common\/format.hpp\"\r\n\r\nnamespace device {\r\n\r\n\/\/\/ F_FCLK は変換パラメーター計算で必要で、設定が無いとエラーにします。\r\n#ifndef F_FCLK\r\n# error \"flash_io.hpp requires F_FCLK to be defined\"\r\n#endif\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief FLASH 制御クラス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass flash_io {\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief データ・フラッシュ構成 @n\r\n\t\t\t\t\t(全体64Kバイト、ブロック64個、バンク1024個)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic const uint32_t data_flash_block = 64; \/\/\/< データ・フラッシュのブロックサイズ\r\n\t\tstatic const uint32_t data_flash_size = 65536; \/\/\/< データ・フラッシュの容量\r\n\t\tstatic const uint32_t data_flash_bank = 1024; \/\/\/< データ・フラッシュのバンク数\r\n\r\n\tprivate:\r\n\t\tbool\ttrans_farm_;\r\n\r\n\t\t\/\/\/ FACIコマンド発行領域 007E 0000h 4バイト\r\n\t\tstatic rw8_t<0x007E0000> FACI_CMD_AREA;\t\t\/\/\/< byte 書き込み\r\n\r\n\t\tstatic rw16_t<0x007E0000> FACI_CMD_AREA16;\t\/\/\/< word(16) 書き込み\r\n\r\n\t\t\/\/ return 「true」正常、「false」ロック状態\r\n\t\tbool turn_break_() const\r\n\t\t{\r\n\t\t\tFACI_CMD_AREA = 0xB3;\r\n\r\n\t\t\t\/\/ break (4 bytes): FCLK 20MHz to 60MHz max 20us\r\n\t\t\t\/\/ FCLK 4MHz max 32us\r\n\t\t\t\/\/ * 1.1\r\n\t\t\tuint32_t cnt = 22;\r\n\t\t\tif(F_FCLK < 20000000) cnt = 36;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(1);\r\n\t\t\t\t--cnt;\r\n\t\t\t\tif(cnt == 0) break;\r\n\t\t\t}\r\n\t\t\tif(cnt == 0) {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'turn_break_' timeout\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(device::FLASH::FASTAT.CMDLK() == 0) {\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'turn_break_' fail\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tvoid turn_rd_() const\r\n\t\t{\r\n\t\t\tuint32_t n = 5;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(1);\r\n\t\t\t\t--n;\r\n\t\t\t\tif(n == 0) break;\r\n\t\t\t} \r\n\t\t\tif(n == 0 || device::FLASH::FASTAT.CMDLK() != 0) {\r\n\t\t\t\tturn_break_();\r\n\t\t\t}\r\n\t\t\r\n\t\t\tdevice::FLASH::FENTRYR = 0xAA00;\r\n\r\n\t\t\tif(device::FLASH::FENTRYR() != 0x0000) {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'turn_rd_' fail\\n\"); \r\n#endif\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tvoid turn_pe_() const\r\n\t\t{\r\n\t\t\tdevice::FLASH::FENTRYR = 0xAA80;\r\n\r\n\t\t\tif(device::FLASH::FENTRYR() != 0x0080) {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'turn_pe_' fail\\n\"); \r\n#endif\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/\/ FCUファームウェア格納領域 FEFF F000h~FEFF FFFFh 4Kバイト\r\n\t\t\/\/\/ FCURAM領域 007F 8000h~007F 8FFFh 4Kバイト\r\n\t\t\/\/\/ コンフィギュレーション設定領域 0012 0040h~0012 007Fh 64バイト\r\n\t\tvoid init_fcu_()\r\n\t\t{\r\n\t\t\tif(trans_farm_) return;\r\n\r\n\t\t\tif(device::FLASH::FENTRYR() != 0) {\r\n\t\t\t\tdevice::FLASH::FENTRYR = 0xAA00;\r\n\t\t\t}\r\n\r\n\t\t\tdevice::FLASH::FCURAME = 0xC403; \/\/ Write only\r\n\r\n\t\t\tconst uint32_t* src = reinterpret_cast<const uint32_t*>(0xFEFFF000); \/\/ Farm master\r\n\t\t\tuint32_t* dst = reinterpret_cast<uint32_t*>(0x007F8000); \/\/ Farm section\r\n\t\t\tfor(uint32_t i = 0; i < (4096 \/ 4); ++i) {\r\n\t\t\t\t*dst++ = *src++;\r\n\t\t\t}\r\n\r\n\t\t\tdevice::FLASH::FCURAME = 0xC400;\r\n\r\n\t\t\tturn_pe_();\r\n\r\n\t\t\tauto f = turn_break_();\t\t\t\r\n\t\t\tif(f) {\r\n\t\t\t\tturn_rd_();\r\n\r\n\t\t\t\ttrans_farm_ = true;\r\n\t\t\t} else {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI Lock...\\n\");\r\n#endif\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/ 4 バイト書き込み\r\n\t\t\/\/ org: align 4 bytes\r\n\t\tbool write32_(const void* src, uint32_t org) const\r\n\t\t{\r\n\t\t\tdevice::FLASH::FPROTR = 0x5501;\r\n\t\t\tdevice::FLASH::FSADDR = org;\r\n\r\n\t\t\tFACI_CMD_AREA = 0xE8;\r\n\t\t\tFACI_CMD_AREA = 0x02;\r\n\r\n\t\t\tconst uint8_t* p = static_cast<const uint8_t*>(src);\r\n\t\t\tFACI_CMD_AREA16 = (static_cast<uint16_t>(p[1]) << 8) | static_cast<uint16_t>(p[0]);\r\n\r\n\t\t\twhile(device::FLASH::FSTATR.DBFULL() != 0) {\r\n\t\t\t\tasm(\"nop\");\r\n\t\t\t}\r\n\r\n\t\t\tFACI_CMD_AREA16 = (static_cast<uint16_t>(p[3]) << 8) | static_cast<uint16_t>(p[2]);\r\n\r\n\t\t\twhile(device::FLASH::FSTATR.DBFULL() != 0) {\r\n\t\t\t\tasm(\"nop\");\r\n\t\t\t}\r\n\r\n\t\t\tFACI_CMD_AREA = 0xD0;\r\n\r\n\r\n\t\t\t\/\/ write (4 bytes): FCLK 20MHz to 60MHz max 1.7ms\r\n\t\t\t\/\/ FCLK 4MHz max 3.8ms\r\n\t\t\t\/\/ * 1.1\r\n\t\t\tuint32_t cnt = 1870;\r\n\t\t\tif(F_FCLK < 20000000) cnt = 4180;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(1);\r\n\t\t\t\t--cnt;\r\n\t\t\t\tif(cnt == 0) break;\r\n\t\t\t}\r\n\t\t\tif(cnt == 0) { \/\/ time out\r\n\t\t\t\tturn_break_();\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'write32_' timeout\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(device::FLASH::FASTAT.CMDLK() != 0) {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'write32_' CMD Lock fail\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\tコンストラクター\r\n\t\t *\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tflash_io() : trans_farm_(false) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\t開始\r\n\t\t *\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid start()\r\n\t\t{\r\n\t\t\tdevice::FLASH::FWEPROR.FLWE = 1;\r\n\t\t\tinit_fcu_();\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 読み出し\r\n\t\t\t@param[in]\torg\t開始アドレス\r\n\t\t\t@return データ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint8_t read(uint32_t org) const\r\n\t\t{\r\n\t\t\tif(org >= data_flash_size) return 0;\r\n\t\t\tturn_rd_();\r\n\t\t\treturn device::rd8_(0x00100000 + org);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 読み出し\r\n\t\t\t@param[in]\torg\t開始アドレス\r\n\t\t\t@param[in]\tlen\tバイト数\r\n\t\t\t@param[out]\tdst\t先\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid read(uint32_t org, uint32_t len, void* dst) const\r\n\t\t{\r\n\t\t\tif(org >= data_flash_size) return;\r\n\t\t\tif((org + len) > data_flash_size) {\r\n\t\t\t\tlen = data_flash_size - org;\r\n\t\t\t}\r\n\t\t\tturn_rd_();\r\n\t\t\tconst void* src = reinterpret_cast<const void*>(0x00100000 + org);\r\n\t\t\tstd::memcpy(dst, src, len);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 消去チェック\r\n\t\t\t@param[in]\tbank\tバンク\r\n\t\t\t@return エラーがあれば「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool erase_check(uint32_t bank) const\r\n\t\t{\r\n\t\t\tif(bank >= data_flash_bank) return false;\r\n\r\n\t\t\tdevice::FLASH::FBCCNT = 0x00; \/\/ address increment\r\n\t\t\tdevice::FLASH::FSADDR = bank * data_flash_block;\r\n\t\t\tdevice::FLASH::FEADDR = ((bank + 1) * data_flash_block) - 1;\r\n\r\n\t\t\tFACI_CMD_AREA = 0x71;\r\n\t\t\tFACI_CMD_AREA = 0xD0;\r\n\r\n\t\t\t\/\/ erase cheak (4 bytes): FCLK 20MHz to 60MHz max 30us\r\n\t\t\t\/\/ FCLK 4MHz max 84us\r\n\t\t\t\/\/ * 1.1\r\n\t\t\tuint32_t cnt = 33 * 64 \/ 4;\r\n\t\t\tif(F_FCLK < 20000000) cnt = 93 * 64 \/ 4;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(1);\r\n\t\t\t\t--cnt;\r\n\t\t\t\tif(cnt == 0) break;\r\n\t\t\t}\r\n\t\t\tif(cnt == 0) { \/\/ time out\r\n\t\t\t\tturn_break_();\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'erase_check' timeout\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(device::FLASH::FASTAT.CMDLK() == 0) {\r\n\t\t\t\tif(device::FLASH::FBCSTAT.BCST() != 0) {\r\n\t\t\t\t\tutils::format(\"FACI 'erase_check' blank check fail: %04X\\n\") % device::FLASH::FPSADDR();\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'erase_check' fail\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 消去\r\n\t\t\t@param[in]\tbank\tバンク\r\n\t\t\t@return エラーがあれば「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool erase(uint32_t bank) const\r\n\t\t{\r\n\t\t\tif(bank >= data_flash_bank) return false;\r\n\r\n\t\t\tturn_pe_();\r\n\r\n\t\t\tdevice::FLASH::FPROTR = 0x5501;\r\n\t\t\tdevice::FLASH::FCPSR = 0x0000; \/\/ サスペンド優先\r\n\t\t\tdevice::FLASH::FSADDR = bank * data_flash_block;\r\n\r\n\t\t\tFACI_CMD_AREA = 0x20;\r\n\t\t\tFACI_CMD_AREA = 0xD0;\r\n\r\n\t\t\t\/\/ 64 bytes erase: FCLK 20MHz to 60MHz max 10ms\r\n\t\t\t\/\/ FCLK 4MHz max 18ms\r\n\t\t\t\/\/ * 1.1\r\n\t\t\tuint32_t cnt = 1100;\r\n\t\t\tif(F_FCLK < 20000000) cnt = 1980;\r\n\t\t\twhile(device::FLASH::FSTATR.FRDY() == 0) {\r\n\t\t\t\tutils::delay::micro_second(10);\r\n\t\t\t\t--cnt;\r\n\t\t\t\tif(cnt == 0) break;\r\n\t\t\t}\r\n\t\t\tif(cnt == 0) { \/\/ time out\r\n\t\t\t\tturn_break_();\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'erase' timeout\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(device::FLASH::FASTAT.CMDLK() == 0) {\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n#ifndef NDEBUG\r\n\t\t\t\tutils::format(\"FACI 'erase' fail\\n\");\r\n#endif\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 書き込み\r\n\t\t\t@param[in]\tsrc ソース\r\n\t\t\t@param[in]\torg\t開始オフセット\r\n\t\t\t@param[in]\tlen\tバイト数(4の倍数)\r\n\t\t\t@return エラーがあれば「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool write(const void* src, uint32_t org, uint32_t len) const\r\n\t\t{\r\n\/\/\/\t\t\tif((len & 3) != 0 || (org & 3) != 0) return false;\r\n\r\n\t\t\tif(org >= data_flash_size) return false;\r\n\r\n\t\t\tif((org + len) > data_flash_size) {\r\n\t\t\t\tlen = data_flash_size - org;\r\n\t\t\t}\r\n\r\n\t\t\tturn_pe_();\r\n\r\n\t\t\tconst uint8_t* p = static_cast<const uint8_t*>(src);\r\n\t\t\tbool f = false;\r\n\t\t\tint32_t l = static_cast<int32_t>(len);\r\n\t\t\twhile(l > 0) {\r\n\t\t\t\tuint32_t mod = org & 3;\r\n\t\t\t\tif(mod != 0) {\r\n\t\t\t\t\tuint8_t tmp[4];\r\n\t\t\t\t\ttmp[0] = 0xFF;\r\n\t\t\t\t\ttmp[1] = 0xFF;\r\n\t\t\t\t\ttmp[2] = 0xFF;\r\n\t\t\t\t\ttmp[3] = 0xFF;\r\n\t\t\t\t\tl -= 4 - mod;\r\n\t\t\t\t\twhile(mod < 3) {\r\n\t\t\t\t\t\ttmp[mod] = *p++;\r\n\t\t\t\t\t\t++mod;\r\n\t\t\t\t\t}\r\n\t\t\t\t\torg &= 0xFFFFFFFC;\r\n\t\t\t\t\tf = write32_(tmp, org);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tf = write32_(p, org);\r\n\t\t\t\t\tp += 4;\r\n\t\t\t\t\tl -= 4;\r\n\t\t\t\t}\r\n\t\t\t\tif(!f) break;\r\n\t\t\t\torg += 4;\r\n\t\t\t}\r\n\t\t\treturn f;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 書き込み\r\n\t\t\t@param[in]\torg\t開始オフセット\r\n\t\t\t@param[in]\tdata\t書き込みデータ\r\n\t\t\t@return エラーがあれば「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool write(uint32_t org, uint8_t data) const\r\n\t\t{\r\n\t\t\tuint8_t d = data;\r\n\t\t\treturn write(&d, org, 1);\r\n\t\t}\r\n\t};\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#ifndef JUBATUS_CORE_COMMON_EXCEPTION_HPP_\n#define JUBATUS_CORE_COMMON_EXCEPTION_HPP_\n\n#include <exception>\n#include <stdexcept>\n#include <ios>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <pficommon\/lang\/shared_ptr.h>\n#include <pficommon\/lang\/demangle.h>\n#include \"exception_info.hpp\"\n\nnamespace jubatus {\nnamespace core {\nnamespace common {\nnamespace exception {\n\ntypedef error_info<struct error_at_file_, std::string> error_at_file;\ntypedef error_info<struct error_at_func_, std::string> error_at_func;\ntypedef error_info<struct error_at_line_, int> error_at_line;\ntypedef error_info<struct error_errno_, int> error_errno;\ninline std::string to_string(const error_errno& info) {\n char buf[256];\n std::string msg(strerror_r(info.value(), buf, 256));\n msg += \" (\" + pfi::lang::lexical_cast<std::string>(info.value()) + \")\";\n return msg;\n}\n\ntypedef error_info<struct error_file_name_, std::string> error_file_name;\ntypedef error_info<struct error_api_func_, std::string> error_api_func;\ntypedef error_info<struct error_message_, std::string> error_message;\n\ntypedef error_info<struct error_splitter_, void> error_splitter;\n\nstruct exception_thrower_binder_type {\n};\n\/\/ for exception_thrower\n\n#if defined(__GNUC__)\n#define JUBATUS_ERROR_FUNC \\\n jubatus::core::common::exception::error_at_func(__PRETTY_FUNCTION__)\n#else\n#define JUBATUS_ERROR_FUNC \\\n jubatus::core::common::exception::error_at_func(__func__)\n#endif\n\n#define JUBATUS_CURRENT_ERROR_INFO() \\\n jubatus::core::common::exception::error_at_file(__FILE__) \\\n << jubatus::core::common::exception::error_at_line(__LINE__) \\\n << JUBATUS_ERROR_FUNC << jubatus::core::common::exception::error_splitter()\n#define JUBATUS_EXCEPTION(e) e << \\\n jubatus::core::common::exception::exception_thrower_binder_type() \\\n << JUBATUS_CURRENT_ERROR_INFO()\n\nclass exception_thrower_base;\ntypedef pfi::lang::shared_ptr<exception_thrower_base> exception_thrower_ptr;\n\ntypedef std::vector<pfi::lang::shared_ptr<error_info_base> > error_info_list_t;\n\nclass jubatus_exception : public std::exception {\n public:\n jubatus_exception() throw () {\n }\n virtual ~jubatus_exception() throw () {\n }\n\n virtual exception_thrower_ptr thrower() const = 0;\n\n template<class Exception>\n friend const Exception& add_info(\n const Exception& e,\n pfi::lang::shared_ptr<error_info_base> info);\n\n std::string name() const throw () {\n \/\/ does not assume multithreading\n if (exception_class_name_.empty()) {\n exception_class_name_ = pfi::lang::demangle(typeid(*this).name());\n }\n\n return exception_class_name_;\n }\n\n virtual const char* what() const throw () {\n name();\n return exception_class_name_.c_str();\n }\n\n error_info_list_t error_info() const;\n std::string diagnostic_information(bool display_what = false) const;\n\n private:\n mutable std::string exception_class_name_;\n mutable error_info_list_t info_list_;\n};\n\ntemplate<class Exception>\ninline const Exception& add_info(\n const Exception& e,\n pfi::lang::shared_ptr<error_info_base> info) {\n e.info_list_.push_back(info);\n return e;\n}\n\ntemplate<class Exception, class Tag, class V>\ninline const Exception& operator <<(\n const Exception& e,\n const error_info<Tag, V>& info) {\n return add_info(\n e, pfi::lang::shared_ptr<error_info_base>(new error_info<Tag, V>(info)));\n}\n\ntemplate<class Exception>\ninline const Exception& operator <<(\n const Exception& e,\n pfi::lang::shared_ptr<error_info_base> info) {\n return add_info(e, info);\n}\n\nclass exception_thrower_base {\n public:\n exception_thrower_base() {\n }\n virtual ~exception_thrower_base() {\n }\n\n virtual void throw_exception() const = 0;\n};\n\ntemplate<class Exception>\nclass exception_thrower_impl : public exception_thrower_base {\n public:\n explicit exception_thrower_impl(const Exception& e)\n : exception_(e) {\n }\n\n private:\n \/\/ noncopyable\n exception_thrower_impl(const exception_thrower_impl&);\n exception_thrower_impl& operator=(const exception_thrower_impl&);\n\n public:\n void throw_exception() const {\n throw exception_;\n }\n\n private:\n Exception exception_;\n};\n\ntemplate<class Exception>\nclass jubaexception : public jubatus_exception {\n public:\n jubaexception() {\n }\n virtual ~jubaexception() throw () {\n }\n\n exception_thrower_ptr thrower() const {\n if (thrower_) {\n return thrower_;\n } else {\n return exception_thrower_ptr(\n new exception_thrower_impl<Exception>(\n *(static_cast<const Exception*>(this))));\n }\n }\n\n \/\/ This is desireble in private\n void bind_thrower(exception_thrower_ptr thrower) const {\n thrower_ = thrower;\n }\n\n private:\n mutable exception_thrower_ptr thrower_;\n};\n\ntemplate<class Exception>\ninline const Exception& operator <<(\n const Exception& e,\n const exception_thrower_binder_type&) {\n e.bind_thrower(\n exception_thrower_ptr(new exception_thrower_impl<Exception>(e)));\n return e;\n}\n\nclass unknown_exception : public jubaexception<unknown_exception> {\n public:\n explicit unknown_exception() {\n \/\/ TODO(kashihara): push unknown_exception\n }\n\n const char* what() const throw () {\n return \"unknown exception\";\n }\n};\n\nclass runtime_error : public jubaexception<runtime_error> {\n public:\n explicit runtime_error(const std::string& what)\n : what_(what) {\n }\n\n ~runtime_error() throw () {\n }\n\n const char* what() const throw () {\n return what_.c_str();\n }\n private:\n std::string what_;\n};\n\nnamespace detail {\ntemplate<class Exception>\nexception_thrower_ptr current_std_exception(const Exception& e) {\n return exception_thrower_ptr(new exception_thrower_impl<Exception>(e));\n}\n\n} \/\/ namespace detail\n\n\/\/ Don't call without catch blocks\ninline exception_thrower_ptr get_current_exception() {\n exception_thrower_ptr ptr;\n\n try {\n throw;\n } catch (const std::bad_alloc& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::bad_cast& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::bad_exception& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::bad_typeid& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::domain_error& e) { \/\/ logic_error\n ptr = detail::current_std_exception(e);\n } catch (const std::invalid_argument& e) { \/\/ logic_error\n ptr = detail::current_std_exception(e);\n } catch (const std::length_error& e) { \/\/ logic_error\n ptr = detail::current_std_exception(e);\n } catch (const std::out_of_range& e) { \/\/ logic_error\n ptr = detail::current_std_exception(e);\n } catch (const std::logic_error& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::range_error& e) { \/\/ runtime_error\n ptr = detail::current_std_exception(e);\n } catch (const std::overflow_error& e) { \/\/ runtime_error\n ptr = detail::current_std_exception(e);\n } catch (const std::underflow_error& e) { \/\/ runtime_error\n ptr = detail::current_std_exception(e);\n } catch (const std::runtime_error& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::ios_base::failure& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const jubatus_exception& e) {\n ptr = e.thrower();\n } catch (const std::exception& e) {\n ptr = detail::current_std_exception(e);\n } catch (...) {\n ptr = unknown_exception().thrower();\n }\n\n return ptr;\n}\n\n} \/\/ namespace exception\n\nclass config_exception : public exception::jubaexception<config_exception> {\n};\n\nclass storage_not_set : public exception::jubaexception<storage_not_set> {\n};\n\nclass config_not_set : public exception::jubaexception<config_not_set> {\n const char* what() const throw () {\n return \"config_not_set\";\n }\n};\n\nclass unsupported_method : public exception::runtime_error {\n public:\n explicit unsupported_method(const std::string& n)\n : jubatus::core::common::exception::runtime_error(\n std::string(\"unsupported method (\") + n + \")\") {\n }\n};\n\nclass bad_storage_type : public exception::runtime_error {\n public:\n explicit bad_storage_type(const std::string& n)\n : jubatus::core::common::exception::runtime_error(n) {\n }\n};\n\nclass membership_error : public exception::runtime_error {\n public:\n explicit membership_error(const std::string& n)\n : jubatus::core::common::exception::runtime_error(n) {\n }\n};\n\nclass not_found : public membership_error {\n public:\n explicit not_found(const std::string& n)\n : membership_error(n) {\n }\n};\n\nclass argv_error : public exception::runtime_error {\n public:\n explicit argv_error(const std::string& n)\n : jubatus::core::common::exception::runtime_error(n) {\n }\n};\n\n} \/\/ namespace common\n} \/\/ namespace core\n} \/\/ namespace jubatus\n\n#endif \/\/ JUBATUS_CORE_COMMON_EXCEPTION_HPP_\n<commit_msg>#495 change buffer size from 256 to 1024<commit_after>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#ifndef JUBATUS_CORE_COMMON_EXCEPTION_HPP_\n#define JUBATUS_CORE_COMMON_EXCEPTION_HPP_\n\n#include <exception>\n#include <stdexcept>\n#include <ios>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <pficommon\/lang\/shared_ptr.h>\n#include <pficommon\/lang\/demangle.h>\n#include \"exception_info.hpp\"\n\nnamespace jubatus {\nnamespace core {\nnamespace common {\nnamespace exception {\n\ntypedef error_info<struct error_at_file_, std::string> error_at_file;\ntypedef error_info<struct error_at_func_, std::string> error_at_func;\ntypedef error_info<struct error_at_line_, int> error_at_line;\ntypedef error_info<struct error_errno_, int> error_errno;\ninline std::string to_string(const error_errno& info) {\n char buf[1024];\n std::string msg(strerror_r(info.value(), buf, 1024));\n msg += \" (\" + pfi::lang::lexical_cast<std::string>(info.value()) + \")\";\n return msg;\n}\n\ntypedef error_info<struct error_file_name_, std::string> error_file_name;\ntypedef error_info<struct error_api_func_, std::string> error_api_func;\ntypedef error_info<struct error_message_, std::string> error_message;\n\ntypedef error_info<struct error_splitter_, void> error_splitter;\n\nstruct exception_thrower_binder_type {\n};\n\/\/ for exception_thrower\n\n#if defined(__GNUC__)\n#define JUBATUS_ERROR_FUNC \\\n jubatus::core::common::exception::error_at_func(__PRETTY_FUNCTION__)\n#else\n#define JUBATUS_ERROR_FUNC \\\n jubatus::core::common::exception::error_at_func(__func__)\n#endif\n\n#define JUBATUS_CURRENT_ERROR_INFO() \\\n jubatus::core::common::exception::error_at_file(__FILE__) \\\n << jubatus::core::common::exception::error_at_line(__LINE__) \\\n << JUBATUS_ERROR_FUNC << jubatus::core::common::exception::error_splitter()\n#define JUBATUS_EXCEPTION(e) e << \\\n jubatus::core::common::exception::exception_thrower_binder_type() \\\n << JUBATUS_CURRENT_ERROR_INFO()\n\nclass exception_thrower_base;\ntypedef pfi::lang::shared_ptr<exception_thrower_base> exception_thrower_ptr;\n\ntypedef std::vector<pfi::lang::shared_ptr<error_info_base> > error_info_list_t;\n\nclass jubatus_exception : public std::exception {\n public:\n jubatus_exception() throw () {\n }\n virtual ~jubatus_exception() throw () {\n }\n\n virtual exception_thrower_ptr thrower() const = 0;\n\n template<class Exception>\n friend const Exception& add_info(\n const Exception& e,\n pfi::lang::shared_ptr<error_info_base> info);\n\n std::string name() const throw () {\n \/\/ does not assume multithreading\n if (exception_class_name_.empty()) {\n exception_class_name_ = pfi::lang::demangle(typeid(*this).name());\n }\n\n return exception_class_name_;\n }\n\n virtual const char* what() const throw () {\n name();\n return exception_class_name_.c_str();\n }\n\n error_info_list_t error_info() const;\n std::string diagnostic_information(bool display_what = false) const;\n\n private:\n mutable std::string exception_class_name_;\n mutable error_info_list_t info_list_;\n};\n\ntemplate<class Exception>\ninline const Exception& add_info(\n const Exception& e,\n pfi::lang::shared_ptr<error_info_base> info) {\n e.info_list_.push_back(info);\n return e;\n}\n\ntemplate<class Exception, class Tag, class V>\ninline const Exception& operator <<(\n const Exception& e,\n const error_info<Tag, V>& info) {\n return add_info(\n e, pfi::lang::shared_ptr<error_info_base>(new error_info<Tag, V>(info)));\n}\n\ntemplate<class Exception>\ninline const Exception& operator <<(\n const Exception& e,\n pfi::lang::shared_ptr<error_info_base> info) {\n return add_info(e, info);\n}\n\nclass exception_thrower_base {\n public:\n exception_thrower_base() {\n }\n virtual ~exception_thrower_base() {\n }\n\n virtual void throw_exception() const = 0;\n};\n\ntemplate<class Exception>\nclass exception_thrower_impl : public exception_thrower_base {\n public:\n explicit exception_thrower_impl(const Exception& e)\n : exception_(e) {\n }\n\n private:\n \/\/ noncopyable\n exception_thrower_impl(const exception_thrower_impl&);\n exception_thrower_impl& operator=(const exception_thrower_impl&);\n\n public:\n void throw_exception() const {\n throw exception_;\n }\n\n private:\n Exception exception_;\n};\n\ntemplate<class Exception>\nclass jubaexception : public jubatus_exception {\n public:\n jubaexception() {\n }\n virtual ~jubaexception() throw () {\n }\n\n exception_thrower_ptr thrower() const {\n if (thrower_) {\n return thrower_;\n } else {\n return exception_thrower_ptr(\n new exception_thrower_impl<Exception>(\n *(static_cast<const Exception*>(this))));\n }\n }\n\n \/\/ This is desireble in private\n void bind_thrower(exception_thrower_ptr thrower) const {\n thrower_ = thrower;\n }\n\n private:\n mutable exception_thrower_ptr thrower_;\n};\n\ntemplate<class Exception>\ninline const Exception& operator <<(\n const Exception& e,\n const exception_thrower_binder_type&) {\n e.bind_thrower(\n exception_thrower_ptr(new exception_thrower_impl<Exception>(e)));\n return e;\n}\n\nclass unknown_exception : public jubaexception<unknown_exception> {\n public:\n explicit unknown_exception() {\n \/\/ TODO(kashihara): push unknown_exception\n }\n\n const char* what() const throw () {\n return \"unknown exception\";\n }\n};\n\nclass runtime_error : public jubaexception<runtime_error> {\n public:\n explicit runtime_error(const std::string& what)\n : what_(what) {\n }\n\n ~runtime_error() throw () {\n }\n\n const char* what() const throw () {\n return what_.c_str();\n }\n private:\n std::string what_;\n};\n\nnamespace detail {\ntemplate<class Exception>\nexception_thrower_ptr current_std_exception(const Exception& e) {\n return exception_thrower_ptr(new exception_thrower_impl<Exception>(e));\n}\n\n} \/\/ namespace detail\n\n\/\/ Don't call without catch blocks\ninline exception_thrower_ptr get_current_exception() {\n exception_thrower_ptr ptr;\n\n try {\n throw;\n } catch (const std::bad_alloc& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::bad_cast& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::bad_exception& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::bad_typeid& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::domain_error& e) { \/\/ logic_error\n ptr = detail::current_std_exception(e);\n } catch (const std::invalid_argument& e) { \/\/ logic_error\n ptr = detail::current_std_exception(e);\n } catch (const std::length_error& e) { \/\/ logic_error\n ptr = detail::current_std_exception(e);\n } catch (const std::out_of_range& e) { \/\/ logic_error\n ptr = detail::current_std_exception(e);\n } catch (const std::logic_error& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::range_error& e) { \/\/ runtime_error\n ptr = detail::current_std_exception(e);\n } catch (const std::overflow_error& e) { \/\/ runtime_error\n ptr = detail::current_std_exception(e);\n } catch (const std::underflow_error& e) { \/\/ runtime_error\n ptr = detail::current_std_exception(e);\n } catch (const std::runtime_error& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const std::ios_base::failure& e) { \/\/ exception\n ptr = detail::current_std_exception(e);\n } catch (const jubatus_exception& e) {\n ptr = e.thrower();\n } catch (const std::exception& e) {\n ptr = detail::current_std_exception(e);\n } catch (...) {\n ptr = unknown_exception().thrower();\n }\n\n return ptr;\n}\n\n} \/\/ namespace exception\n\nclass config_exception : public exception::jubaexception<config_exception> {\n};\n\nclass storage_not_set : public exception::jubaexception<storage_not_set> {\n};\n\nclass config_not_set : public exception::jubaexception<config_not_set> {\n const char* what() const throw () {\n return \"config_not_set\";\n }\n};\n\nclass unsupported_method : public exception::runtime_error {\n public:\n explicit unsupported_method(const std::string& n)\n : jubatus::core::common::exception::runtime_error(\n std::string(\"unsupported method (\") + n + \")\") {\n }\n};\n\nclass bad_storage_type : public exception::runtime_error {\n public:\n explicit bad_storage_type(const std::string& n)\n : jubatus::core::common::exception::runtime_error(n) {\n }\n};\n\nclass membership_error : public exception::runtime_error {\n public:\n explicit membership_error(const std::string& n)\n : jubatus::core::common::exception::runtime_error(n) {\n }\n};\n\nclass not_found : public membership_error {\n public:\n explicit not_found(const std::string& n)\n : membership_error(n) {\n }\n};\n\nclass argv_error : public exception::runtime_error {\n public:\n explicit argv_error(const std::string& n)\n : jubatus::core::common::exception::runtime_error(n) {\n }\n};\n\n} \/\/ namespace common\n} \/\/ namespace core\n} \/\/ namespace jubatus\n\n#endif \/\/ JUBATUS_CORE_COMMON_EXCEPTION_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <set>\n#include <string>\n#include <memory>\n#include <cassert>\n#include <iostream>\n#include <stdexcept>\n\n#include \"config.h\"\n#include \"parsers\/cli.h\"\n#include \"solvers\/dpll.h\"\n#include \"solvers\/tseitin.h\"\n#include \"structures\/difference_atom.h\"\n#include \"structures\/extended_formula.h\"\n#include \"solvers\/difference_assistant.h\"\n#include \"extended_formula.y.hpp\"\n\n#define EF satsolver::ExtendedFormula\n#define SPEF std::shared_ptr<EF>\n#define DA theorysolver::DifferenceAtom\n#define SPDA std::shared_ptr<DA>\n\nextern FILE *yyin;\nextern int yyparse();\n\nbool VERBOSE = false;\nbool WITH_WL = false;\nbool DISPLAY_SAT;\nbool DISPLAY_ATOMS;\nbool DISPLAY_FORMULA;\nsatsolver::Heuristic HEURISTIC = satsolver::DUMB ;\n\nvoid parser_result(SPEF ext_formula, std::vector<SPDA> &literal_to_DA) {\n \/*********************\n * Reduce\n ********************\/\n theorysolver::DifferenceAssistant *assistant;\n satsolver::Affectation *sat_solution;\n std::vector<unsigned int> affected_literals;\n std::shared_ptr<std::map<std::string, int>> name_to_variable;\n std::map<int, std::string> variable_to_name;\n std::shared_ptr<std::unordered_set<std::string>> literals = ext_formula->get_literals();\n std::shared_ptr<satsolver::Formula> formula;\n\n if (VERBOSE || DISPLAY_FORMULA)\n std::cout << \"Interpreted formula as: \" << ext_formula->to_string() << std::endl;\n if (VERBOSE || DISPLAY_ATOMS) {\n std::cout << \"Atoms:\" << std::endl;\n for (unsigned int i=0; i<literal_to_DA.size(); i++)\n std::cout << \"\\t#\" << i+1 << \": \" << literal_to_DA[i]->to_string() << std::endl;\n }\n ext_formula = theorysolver::DifferenceAssistant::canonize_formula(ext_formula, literal_to_DA);\n if (VERBOSE || DISPLAY_FORMULA)\n std::cout << \"Canonized formula as: \" << ext_formula->to_string() << std::endl;\n if (VERBOSE || DISPLAY_ATOMS) {\n std::cout << \"Atoms:\" << std::endl;\n for (unsigned int i=0; i<literal_to_DA.size(); i++)\n std::cout << \"\\t#\" << i+1 << \": \" << literal_to_DA[i]->to_string() << std::endl;\n }\n if (!tseitin_reduction(DISPLAY_SAT, ext_formula, name_to_variable, formula, &affected_literals)) {\n \/\/ The formula is always false\n if (DISPLAY_SAT)\n std::cout << \"c The formula is so obviously wrong it is not even needed to convert it to conjonctive form.\" << std::endl;\n std::cout << \"s UNSATISFIABLE\" << std::endl;\n return;\n }\n if (!name_to_variable) {\n switch (ext_formula->get_type()) {\n case EF::TRUE:\n std::cout << \"s SATISFIABLE (tautology)\" << std::endl;\n return;\n case EF::FALSE:\n std::cout << \"s UNSATISFIABLE\" << std::endl;\n return;\n default:\n assert(false);\n }\n }\n assistant = new theorysolver::DifferenceAssistant(literal_to_DA, name_to_variable, formula);\n for (auto it : affected_literals) {\n if (!assistant->on_flip(it)) {\n std::cout << \"s UNSATISFIABLE\" << std::endl;\n return;\n }\n }\n\n \/*********************\n * Solve\n ********************\/\n try {\n sat_solution = satsolver::solve(formula, assistant);\n }\n catch (satsolver::Conflict) {\n std::cout << \"s UNSATISFIABLE\" << std::endl;\n return;\n }\n \/*********************\n * Display solution\n ********************\/\n assert(assistant->is_state_consistent());\n if (VERBOSE) {\n std::cout << \"Solution to SAT problem: \" << sat_solution->to_string() << std::endl;\n std::cout << assistant->get_graph().to_string() << std::endl;\n }\n for (auto literal : *literals) {\n try {\n std::cout << literal << \" = \" << (sat_solution->is_true(name_to_variable->at(literal)) ? \"true\" : \"false\") << std::endl;\n }\n catch (std::out_of_range) {\n SPEF f = literal_to_DA[atoi(literal.c_str()+1)-1]->canonical;\n std::cout << literal << \" (inferred from \" << f->to_string() << \")\" << \" = \";\n try {\n std::cout << (f->is_true(formula->get_aff(), name_to_variable) ? \"true\" : \"false\") << std::endl;\n }\n catch (std::out_of_range) {\n std::cout << \"can be true or false\" << std::endl ;\n }\n }\n }\n delete assistant;\n}\n\nint main (int argc, char *argv[]) {\n \/*********************\n * Get input\n ********************\/\n CommandLineParser cli_parser(argc, argv, std::unordered_set<std::string>({\"-print-interpretation\", \"-print-sat\", \"-print-atoms\"}), \"[-print-interpretation] [-print-sat] [-print-atoms] [<filename>]\");\n if (cli_parser.get_nb_parsed_args() == -1)\n return 1;\n int nb_remaining_args = argc - cli_parser.get_nb_parsed_args();\n if (nb_remaining_args == 0) {\n \/\/ No other option\n }\n else if (nb_remaining_args == 1) {\n \/\/ One option left; hopefully the file name\n yyin = fopen(argv[argc-nb_remaining_args], \"r\");\n }\n else {\n \/\/ Too many unknown options\n cli_parser.print_syntax_error(argv[0]);\n return 1;\n }\n DISPLAY_SAT = cli_parser.get_arg(\"-print-sat\");\n DISPLAY_ATOMS = cli_parser.get_arg(\"-print-atoms\");\n DISPLAY_FORMULA = cli_parser.get_arg(\"-print-interpretation\");\n return yyparse();\n}\n\n<commit_msg>Correct a little mistake.<commit_after>#include <set>\n#include <string>\n#include <memory>\n#include <cassert>\n#include <iostream>\n#include <stdexcept>\n\n#include \"config.h\"\n#include \"parsers\/cli.h\"\n#include \"solvers\/dpll.h\"\n#include \"solvers\/tseitin.h\"\n#include \"structures\/difference_atom.h\"\n#include \"structures\/extended_formula.h\"\n#include \"solvers\/difference_assistant.h\"\n#include \"extended_formula.y.hpp\"\n\n#define EF satsolver::ExtendedFormula\n#define SPEF std::shared_ptr<EF>\n#define DA theorysolver::DifferenceAtom\n#define SPDA std::shared_ptr<DA>\n\nextern FILE *yyin;\nextern int yyparse();\n\nbool VERBOSE = false;\nbool WITH_WL = false;\nbool DISPLAY_SAT;\nbool DISPLAY_ATOMS;\nbool DISPLAY_FORMULA;\nsatsolver::Heuristic HEURISTIC = satsolver::DUMB ;\n\nvoid parser_result(SPEF ext_formula, std::vector<SPDA> &literal_to_DA) {\n \/*********************\n * Reduce\n ********************\/\n theorysolver::DifferenceAssistant *assistant;\n satsolver::Affectation *sat_solution;\n std::vector<unsigned int> affected_literals;\n std::shared_ptr<std::map<std::string, int>> name_to_variable;\n std::map<int, std::string> variable_to_name;\n std::shared_ptr<std::unordered_set<std::string>> literals = ext_formula->get_literals();\n std::shared_ptr<satsolver::Formula> formula;\n\n if (VERBOSE || DISPLAY_FORMULA)\n std::cout << \"Interpreted formula as: \" << ext_formula->to_string() << std::endl;\n if (VERBOSE || DISPLAY_ATOMS) {\n std::cout << \"Atoms:\" << std::endl;\n for (unsigned int i=0; i<literal_to_DA.size(); i++)\n std::cout << \"\\t#\" << i+1 << \": \" << literal_to_DA[i]->to_string() << std::endl;\n }\n ext_formula = theorysolver::DifferenceAssistant::canonize_formula(ext_formula, literal_to_DA);\n if (VERBOSE || DISPLAY_FORMULA)\n std::cout << \"Canonized formula as: \" << ext_formula->to_string() << std::endl;\n if (VERBOSE || DISPLAY_ATOMS) {\n std::cout << \"Atoms:\" << std::endl;\n for (unsigned int i=0; i<literal_to_DA.size(); i++)\n std::cout << \"\\t#\" << i+1 << \": \" << literal_to_DA[i]->to_string() << std::endl;\n }\n if (!tseitin_reduction(DISPLAY_SAT, ext_formula, name_to_variable, formula, &affected_literals)) {\n \/\/ The formula is always false\n if (DISPLAY_SAT)\n std::cout << \"c The formula is so obviously wrong it is not even needed to convert it to conjonctive form.\" << std::endl;\n std::cout << \"s UNSATISFIABLE\" << std::endl;\n return;\n }\n if (!name_to_variable) {\n switch (ext_formula->get_type()) {\n case EF::TRUE:\n std::cout << \"s SATISFIABLE (tautology)\" << std::endl;\n return;\n case EF::FALSE:\n std::cout << \"s UNSATISFIABLE\" << std::endl;\n return;\n default:\n assert(false);\n }\n }\n assistant = new theorysolver::DifferenceAssistant(literal_to_DA, name_to_variable, formula);\n for (auto it : affected_literals) {\n if (1!=assistant->on_flip(it)) {\n std::cout << \"s UNSATISFIABLE\" << std::endl;\n return;\n }\n }\n\n \/*********************\n * Solve\n ********************\/\n try {\n sat_solution = satsolver::solve(formula, assistant);\n }\n catch (satsolver::Conflict) {\n std::cout << \"s UNSATISFIABLE\" << std::endl;\n return;\n }\n \/*********************\n * Display solution\n ********************\/\n assert(assistant->is_state_consistent());\n if (VERBOSE) {\n std::cout << \"Solution to SAT problem: \" << sat_solution->to_string() << std::endl;\n std::cout << assistant->get_graph().to_string() << std::endl;\n }\n for (auto literal : *literals) {\n try {\n std::cout << literal << \" = \" << (sat_solution->is_true(name_to_variable->at(literal)) ? \"true\" : \"false\") << std::endl;\n }\n catch (std::out_of_range) {\n SPEF f = literal_to_DA[atoi(literal.c_str()+1)-1]->canonical;\n std::cout << literal << \" (inferred from \" << f->to_string() << \")\" << \" = \";\n try {\n std::cout << (f->is_true(formula->get_aff(), name_to_variable) ? \"true\" : \"false\") << std::endl;\n }\n catch (std::out_of_range) {\n std::cout << \"can be true or false\" << std::endl ;\n }\n }\n }\n delete assistant;\n}\n\nint main (int argc, char *argv[]) {\n \/*********************\n * Get input\n ********************\/\n CommandLineParser cli_parser(argc, argv, std::unordered_set<std::string>({\"-print-interpretation\", \"-print-sat\", \"-print-atoms\"}), \"[-print-interpretation] [-print-sat] [-print-atoms] [<filename>]\");\n if (cli_parser.get_nb_parsed_args() == -1)\n return 1;\n int nb_remaining_args = argc - cli_parser.get_nb_parsed_args();\n if (nb_remaining_args == 0) {\n \/\/ No other option\n }\n else if (nb_remaining_args == 1) {\n \/\/ One option left; hopefully the file name\n yyin = fopen(argv[argc-nb_remaining_args], \"r\");\n }\n else {\n \/\/ Too many unknown options\n cli_parser.print_syntax_error(argv[0]);\n return 1;\n }\n DISPLAY_SAT = cli_parser.get_arg(\"-print-sat\");\n DISPLAY_ATOMS = cli_parser.get_arg(\"-print-atoms\");\n DISPLAY_FORMULA = cli_parser.get_arg(\"-print-interpretation\");\n return yyparse();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\n\n#include \"MenuController.h\"\n#include \"IOpenableControlViewModel.h\"\n\nnamespace ExampleApp\n{\n namespace Menu\n {\n namespace View\n {\n void MenuController::OnOpenableStateChanged(OpenableControl::View::IOpenableControlViewModel& viewModel, float& state)\n {\n if(m_dragInProgress)\n {\n return;\n }\n\n if (m_viewModel.IsFullyClosed())\n {\n m_view.SetFullyOnScreenClosed();\n }\n else if (m_viewModel.IsFullyOpen())\n {\n m_view.SetFullyOnScreenOpen();\n }\n else\n {\n m_view.SetOnScreenStateToIntermediateValue(state);\n }\n }\n\n void MenuController::OnScreenControlStateChanged(ScreenControl::View::IScreenControlViewModel& viewModel, float& state)\n {\n if (m_viewModel.IsFullyOnScreen())\n {\n m_view.SetFullyOnScreenClosed();\n }\n else if (m_viewModel.IsFullyOffScreen())\n {\n m_view.SetFullyOffScreen();\n }\n else\n {\n m_view.SetOnScreenStateToIntermediateValue(state);\n }\n }\n\n bool MenuController::TryDrag()\n {\n if(m_viewModel.TryAcquireReactorControl())\n {\n return true;\n }\n return false;\n }\n\n void MenuController::RefreshPresentation()\n {\n const int numSections = m_viewModel.SectionsCount();\n TSections sections;\n sections.reserve(numSections);\n\n for(size_t groupIndex = 0; groupIndex < numSections; groupIndex++)\n {\n IMenuSectionViewModel& section = m_viewModel.GetMenuSection(groupIndex);\n sections.push_back(§ion);\n }\n\n m_view.UpdateMenuSectionViews(sections);\n m_presentationDirty = false;\n }\n\n void MenuController::UpdateUiThread(float dt)\n {\n if(m_presentationDirty)\n {\n RefreshPresentation();\n }\n\n if(m_dragInProgress)\n {\n return;\n }\n\n const bool isAnimating = m_view.IsAnimating();\n\n if(isAnimating)\n {\n m_view.UpdateAnimation(dt);\n\n if(m_viewModel.HasReactorControl())\n {\n const float normalisedAnimationProgress = m_view.GetAnimationProgress();\n m_viewModel.UpdateOpenState(normalisedAnimationProgress);\n }\n }\n\n m_view.SetCanInteract(m_viewModel.IsFullyOpen());\n }\n\n void MenuController::OnViewClicked()\n {\n Eegeo_ASSERT(!m_dragInProgress, \"Cannot click on view while dragging it\");\n\n if(!m_viewModel.TryAcquireReactorControl())\n {\n return;\n }\n\n if(m_viewModel.IsFullyClosed())\n {\n m_view.SetFullyOnScreenOpen();\n }\n else if(m_viewModel.IsFullyOpen())\n {\n m_view.SetFullyOnScreenClosed();\n }\n else\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n void MenuController::OnViewOpened()\n {\n Eegeo_ASSERT(!m_dragInProgress, \"identity %d\\n\", Identity());\n\n if(!m_viewModel.IsFullyOpen())\n {\n m_viewModel.Open();\n }\n\n if(m_viewModel.HasReactorControl())\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n void MenuController::OnViewClosed()\n {\n Eegeo_ASSERT(!m_dragInProgress, \"identity %d\\n\", Identity());\n\n if(!m_viewModel.IsFullyClosed())\n {\n m_viewModel.Close();\n }\n\n if(m_viewModel.HasReactorControl())\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n Eegeo::Helpers::TIdentity MenuController::Identity() const\n {\n return static_cast<OpenableControl::View::IOpenableControlViewModel&>(m_viewModel).GetIdentity();\n }\n\n void MenuController::OnDragStarted()\n {\n Eegeo_ASSERT(!m_dragInProgress, \"identity %d\\n\", Identity());\n\n {\n const bool acquiredReactorControl = m_viewModel.TryAcquireReactorControl();\n Eegeo_ASSERT(acquiredReactorControl, \"%d failed to acquire reactor control.\\n\", Identity());\n }\n\n m_dragInProgress = true;\n }\n\n void MenuController::OnDrag(float& value)\n {\n Eegeo_ASSERT(m_dragInProgress);\n\n {\n const bool acquiredReactorControl = m_viewModel.TryAcquireReactorControl();\n Eegeo_ASSERT(acquiredReactorControl, \"%d failed to acquire reactor control.\\n\", Identity());\n }\n\n m_viewModel.UpdateOpenState(value);\n }\n\n void MenuController::OnDragCompleted()\n {\n Eegeo_ASSERT(m_dragInProgress);\n\n {\n const bool acquiredReactorControl = m_viewModel.TryAcquireReactorControl();\n Eegeo_ASSERT(acquiredReactorControl, \"%d failed to acquire reactor control.\\n\", Identity());\n }\n\n m_dragInProgress = false;\n }\n\n void MenuController::OnItemAdded(MenuItemModel& item)\n {\n m_presentationDirty = true;\n }\n\n void MenuController::OnItemRemoved(MenuItemModel& item)\n {\n m_presentationDirty = true;\n }\n\n void MenuController::OnItemSelected(int& sectionIndex, int& itemIndex)\n {\n Eegeo_ASSERT(!m_dragInProgress, \"Cannot select item on menu while dragging it\");\n\n IMenuSectionViewModel& section = m_viewModel.GetMenuSection(sectionIndex);\n if (section.IsExpandable() && itemIndex == 0)\n {\n if(section.IsExpanded())\n {\n section.Contract();\n }\n else\n {\n section.Expand();\n }\n m_presentationDirty = true;\n return;\n }\n else\n {\n int index = section.IsExpandable() ? itemIndex - 1 : itemIndex;\n MenuItemModel item = section.GetItemAtIndex(index);\n item.Select();\n }\n }\n\n MenuController::MenuController(\n IMenuModel& model,\n IMenuViewModel& viewModel,\n IMenuView& view\n )\n : m_model(model)\n , m_viewModel(viewModel)\n , m_view(view)\n , m_onClickedCallback(this, &MenuController::OnViewClicked)\n , m_onViewOpenedCallback(this, &MenuController::OnViewOpened)\n , m_onViewClosedCallback(this, &MenuController::OnViewClosed)\n , m_onDragStartedCallback(this, &MenuController::OnDragStarted)\n , m_onDragCallback(this, &MenuController::OnDrag)\n , m_onDragCompletedCallback(this, &MenuController::OnDragCompleted)\n , m_onItemSelectedCallback(this, &MenuController::OnItemSelected)\n , m_onItemAddedCallback(this, &MenuController::OnItemAdded)\n , m_onItemRemovedCallback(this, &MenuController::OnItemRemoved)\n , m_onScreenStateChanged(this, &MenuController::OnScreenControlStateChanged)\n , m_onOpenableStateChanged(this, &MenuController::OnOpenableStateChanged)\n , m_tryDragFunc(this, &MenuController::TryDrag)\n , m_dragInProgress(false)\n , m_presentationDirty(false)\n {\n m_viewModel.InsertOpenStateChangedCallback(m_onOpenableStateChanged);\n m_viewModel.InsertOnScreenStateChangedCallback(m_onScreenStateChanged);\n m_view.InsertOnDrag(m_onDragCallback);\n m_view.InsertOnDragCompleted(m_onDragCompletedCallback);\n m_view.InsertOnDragStarted(m_onDragStartedCallback);\n m_view.InsertOnItemSelected(m_onItemSelectedCallback);\n m_view.InsertOnViewClicked(m_onClickedCallback);\n m_view.InsertOnViewClosed(m_onViewClosedCallback);\n m_view.InsertOnViewOpened(m_onViewOpenedCallback);\n m_view.SetTryDragFunc(m_tryDragFunc);\n\n if(m_viewModel.IsFullyOnScreen())\n {\n float value = m_viewModel.OpenState();\n OnOpenableStateChanged(m_viewModel, value);\n }\n\n m_presentationDirty = true;\n \n for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)\n {\n IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));\n IMenuModel& model = section.GetModel();\n model.InsertItemAddedCallback(m_onItemAddedCallback);\n model.InsertItemRemovedCallback(m_onItemRemovedCallback);\n }\n }\n\n MenuController::~MenuController()\n {\n for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)\n {\n IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));\n IMenuModel& model = section.GetModel();\n model.RemoveItemAddedCallback(m_onItemAddedCallback);\n model.RemoveItemRemovedCallback(m_onItemRemovedCallback);\n }\n \n m_view.ClearTryDragFunc();\n m_view.RemoveOnViewOpened(m_onViewOpenedCallback);\n m_view.RemoveOnViewClosed(m_onViewClosedCallback);\n m_view.RemoveOnViewClicked(m_onClickedCallback);\n m_view.RemoveOnItemSelected(m_onItemSelectedCallback);\n m_view.RemoveOnDragStarted(m_onDragStartedCallback);\n m_view.RemoveOnDragCompleted(m_onDragCompletedCallback);\n m_view.RemoveOnDrag(m_onDragCallback);\n m_viewModel.RemoveOnScreenStateChangedCallback(m_onScreenStateChanged);\n m_viewModel.RemoveOpenStateChangedCallback(m_onOpenableStateChanged);\n }\n }\n }\n}\n<commit_msg>Attempt to address MPLY-5449. Menus no longer refresh their layout when closed, moving the iOS Stall when updating search results to a minor layout stall when opening results menu, Buddy: Tim, Scott<commit_after>\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\n\n#include \"MenuController.h\"\n#include \"IOpenableControlViewModel.h\"\n\nnamespace ExampleApp\n{\n namespace Menu\n {\n namespace View\n {\n void MenuController::OnOpenableStateChanged(OpenableControl::View::IOpenableControlViewModel& viewModel, float& state)\n {\n if(m_dragInProgress)\n {\n return;\n }\n\n if (m_viewModel.IsFullyClosed())\n {\n m_view.SetFullyOnScreenClosed();\n }\n else if (m_viewModel.IsFullyOpen())\n {\n m_view.SetFullyOnScreenOpen();\n }\n else\n {\n m_view.SetOnScreenStateToIntermediateValue(state);\n }\n }\n\n void MenuController::OnScreenControlStateChanged(ScreenControl::View::IScreenControlViewModel& viewModel, float& state)\n {\n if (m_viewModel.IsFullyOnScreen())\n {\n m_view.SetFullyOnScreenClosed();\n }\n else if (m_viewModel.IsFullyOffScreen())\n {\n m_view.SetFullyOffScreen();\n }\n else\n {\n m_view.SetOnScreenStateToIntermediateValue(state);\n }\n }\n\n bool MenuController::TryDrag()\n {\n if(m_viewModel.TryAcquireReactorControl())\n {\n return true;\n }\n return false;\n }\n\n void MenuController::RefreshPresentation()\n {\n const int numSections = m_viewModel.SectionsCount();\n TSections sections;\n sections.reserve(numSections);\n\n for(size_t groupIndex = 0; groupIndex < numSections; groupIndex++)\n {\n IMenuSectionViewModel& section = m_viewModel.GetMenuSection(groupIndex);\n sections.push_back(§ion);\n }\n\n if(!m_viewModel.IsFullyClosed())\n {\n m_view.UpdateMenuSectionViews(sections);\n m_presentationDirty = false;\n }\n }\n\n void MenuController::UpdateUiThread(float dt)\n {\n if(m_presentationDirty)\n {\n RefreshPresentation();\n }\n\n if(m_dragInProgress)\n {\n return;\n }\n\n const bool isAnimating = m_view.IsAnimating();\n\n if(isAnimating)\n {\n m_view.UpdateAnimation(dt);\n\n if(m_viewModel.HasReactorControl())\n {\n const float normalisedAnimationProgress = m_view.GetAnimationProgress();\n m_viewModel.UpdateOpenState(normalisedAnimationProgress);\n }\n }\n\n m_view.SetCanInteract(m_viewModel.IsFullyOpen());\n }\n\n void MenuController::OnViewClicked()\n {\n Eegeo_ASSERT(!m_dragInProgress, \"Cannot click on view while dragging it\");\n\n if(!m_viewModel.TryAcquireReactorControl())\n {\n return;\n }\n\n if(m_viewModel.IsFullyClosed())\n {\n m_view.SetFullyOnScreenOpen();\n }\n else if(m_viewModel.IsFullyOpen())\n {\n m_view.SetFullyOnScreenClosed();\n }\n else\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n void MenuController::OnViewOpened()\n {\n Eegeo_ASSERT(!m_dragInProgress, \"identity %d\\n\", Identity());\n\n if(!m_viewModel.IsFullyOpen())\n {\n m_viewModel.Open();\n }\n\n if(m_viewModel.HasReactorControl())\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n void MenuController::OnViewClosed()\n {\n Eegeo_ASSERT(!m_dragInProgress, \"identity %d\\n\", Identity());\n\n if(!m_viewModel.IsFullyClosed())\n {\n m_viewModel.Close();\n }\n\n if(m_viewModel.HasReactorControl())\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n Eegeo::Helpers::TIdentity MenuController::Identity() const\n {\n return static_cast<OpenableControl::View::IOpenableControlViewModel&>(m_viewModel).GetIdentity();\n }\n\n void MenuController::OnDragStarted()\n {\n Eegeo_ASSERT(!m_dragInProgress, \"identity %d\\n\", Identity());\n\n {\n const bool acquiredReactorControl = m_viewModel.TryAcquireReactorControl();\n Eegeo_ASSERT(acquiredReactorControl, \"%d failed to acquire reactor control.\\n\", Identity());\n }\n\n m_dragInProgress = true;\n }\n\n void MenuController::OnDrag(float& value)\n {\n Eegeo_ASSERT(m_dragInProgress);\n\n {\n const bool acquiredReactorControl = m_viewModel.TryAcquireReactorControl();\n Eegeo_ASSERT(acquiredReactorControl, \"%d failed to acquire reactor control.\\n\", Identity());\n }\n\n m_viewModel.UpdateOpenState(value);\n }\n\n void MenuController::OnDragCompleted()\n {\n Eegeo_ASSERT(m_dragInProgress);\n\n {\n const bool acquiredReactorControl = m_viewModel.TryAcquireReactorControl();\n Eegeo_ASSERT(acquiredReactorControl, \"%d failed to acquire reactor control.\\n\", Identity());\n }\n\n m_dragInProgress = false;\n }\n\n void MenuController::OnItemAdded(MenuItemModel& item)\n {\n m_presentationDirty = true;\n }\n\n void MenuController::OnItemRemoved(MenuItemModel& item)\n {\n m_presentationDirty = true;\n }\n\n void MenuController::OnItemSelected(int& sectionIndex, int& itemIndex)\n {\n Eegeo_ASSERT(!m_dragInProgress, \"Cannot select item on menu while dragging it\");\n\n IMenuSectionViewModel& section = m_viewModel.GetMenuSection(sectionIndex);\n if (section.IsExpandable() && itemIndex == 0)\n {\n if(section.IsExpanded())\n {\n section.Contract();\n }\n else\n {\n section.Expand();\n }\n m_presentationDirty = true;\n return;\n }\n else\n {\n int index = section.IsExpandable() ? itemIndex - 1 : itemIndex;\n MenuItemModel item = section.GetItemAtIndex(index);\n item.Select();\n }\n }\n\n MenuController::MenuController(\n IMenuModel& model,\n IMenuViewModel& viewModel,\n IMenuView& view\n )\n : m_model(model)\n , m_viewModel(viewModel)\n , m_view(view)\n , m_onClickedCallback(this, &MenuController::OnViewClicked)\n , m_onViewOpenedCallback(this, &MenuController::OnViewOpened)\n , m_onViewClosedCallback(this, &MenuController::OnViewClosed)\n , m_onDragStartedCallback(this, &MenuController::OnDragStarted)\n , m_onDragCallback(this, &MenuController::OnDrag)\n , m_onDragCompletedCallback(this, &MenuController::OnDragCompleted)\n , m_onItemSelectedCallback(this, &MenuController::OnItemSelected)\n , m_onItemAddedCallback(this, &MenuController::OnItemAdded)\n , m_onItemRemovedCallback(this, &MenuController::OnItemRemoved)\n , m_onScreenStateChanged(this, &MenuController::OnScreenControlStateChanged)\n , m_onOpenableStateChanged(this, &MenuController::OnOpenableStateChanged)\n , m_tryDragFunc(this, &MenuController::TryDrag)\n , m_dragInProgress(false)\n , m_presentationDirty(false)\n {\n m_viewModel.InsertOpenStateChangedCallback(m_onOpenableStateChanged);\n m_viewModel.InsertOnScreenStateChangedCallback(m_onScreenStateChanged);\n m_view.InsertOnDrag(m_onDragCallback);\n m_view.InsertOnDragCompleted(m_onDragCompletedCallback);\n m_view.InsertOnDragStarted(m_onDragStartedCallback);\n m_view.InsertOnItemSelected(m_onItemSelectedCallback);\n m_view.InsertOnViewClicked(m_onClickedCallback);\n m_view.InsertOnViewClosed(m_onViewClosedCallback);\n m_view.InsertOnViewOpened(m_onViewOpenedCallback);\n m_view.SetTryDragFunc(m_tryDragFunc);\n\n if(m_viewModel.IsFullyOnScreen())\n {\n float value = m_viewModel.OpenState();\n OnOpenableStateChanged(m_viewModel, value);\n }\n\n m_presentationDirty = true;\n \n for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)\n {\n IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));\n IMenuModel& model = section.GetModel();\n model.InsertItemAddedCallback(m_onItemAddedCallback);\n model.InsertItemRemovedCallback(m_onItemRemovedCallback);\n }\n }\n\n MenuController::~MenuController()\n {\n for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)\n {\n IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));\n IMenuModel& model = section.GetModel();\n model.RemoveItemAddedCallback(m_onItemAddedCallback);\n model.RemoveItemRemovedCallback(m_onItemRemovedCallback);\n }\n \n m_view.ClearTryDragFunc();\n m_view.RemoveOnViewOpened(m_onViewOpenedCallback);\n m_view.RemoveOnViewClosed(m_onViewClosedCallback);\n m_view.RemoveOnViewClicked(m_onClickedCallback);\n m_view.RemoveOnItemSelected(m_onItemSelectedCallback);\n m_view.RemoveOnDragStarted(m_onDragStartedCallback);\n m_view.RemoveOnDragCompleted(m_onDragCompletedCallback);\n m_view.RemoveOnDrag(m_onDragCallback);\n m_viewModel.RemoveOnScreenStateChangedCallback(m_onScreenStateChanged);\n m_viewModel.RemoveOpenStateChangedCallback(m_onOpenableStateChanged);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AccessiblePageShape.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 04:58:49 $\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\n#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PAGE_SHAPE_HXX\n#define _SD_ACCESSIBILITY_ACCESSIBLE_PAGE_SHAPE_HXX\n\n#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_HXX\n#include <svx\/AccessibleShape.hxx>\n#endif\n#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_TREE_INFO_HXX\n#include <svx\/AccessibleShapeTreeInfo.hxx>\n#endif\n#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_LISTENER_HXX\n#include <svx\/IAccessibleViewForwarderListener.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessible.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleExtendedComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_\n#include <com\/sun\/star\/drawing\/XDrawPage.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n\n#ifndef _SVX_UNOEDACC_HXX_\n#include <svx\/AccessibleTextHelper.hxx>\n#endif\n\nnamespace accessibility {\n\n\/** A page shape represents the actual page as seen on the screen.\n*\/\nclass AccessiblePageShape\n : public AccessibleShape\n{\npublic:\n \/\/===== internal ========================================================\n\n \/** Create a new accessible object that makes the given shape accessible.\n @param rxParent\n The accessible parent object. It will be used, for example when\n the <member>getIndexInParent<\/member> method is called.\n @param rShapeTreeInfo\n Bundel of information passed to this shape and all of its desendants.\n @param nIndex\n Index used to disambiguate between objects that have the same\n name. Passing a value of -1 leads to the use of the object's\n z-order instead. Because that is not a good substitute, better\n pass an ever increasing counter.\n @attention\n Always call the <member>init<\/member> method after creating a\n new accessible shape. This is one way to overcome the potential\n problem of registering the new object with e.g. event\n broadcasters. That would delete the new object if a broadcaster\n would not keep a strong reference to the new object.\n *\/\n AccessiblePageShape (\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage>& rxPage,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible>& rxParent,\n const AccessibleShapeTreeInfo& rShapeTreeInfo,\n long nIndex = -1);\n\n virtual ~AccessiblePageShape (void);\n\n \/** Initialize a new shape. See the documentation of the constructor\n for the reason of this method's existence.\n *\/\n virtual void Init (void);\n\n \/\/===== XAccessibleContext ==============================================\n\n \/\/\/ Returns always 0 because there can be no children.\n virtual long SAL_CALL\n getAccessibleChildCount (void)\n throw ();\n\n \/** Return the specified child.\n @param nIndex\n Index of the requested child.\n @return\n Reference of the requested child which is the accessible object\n of a visible shape.\n @raises IndexOutOfBoundsException\n Throws always an exception because there are no children.\n *\/\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible> SAL_CALL\n getAccessibleChild (long nIndex)\n throw (::com::sun::star::uno::RuntimeException);\n\n\n \/\/===== XAccessibleComponent ============================================\n\n virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Int32 SAL_CALL getForeground (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Int32 SAL_CALL getBackground (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/===== XComponent ======================================================\n\n virtual void SAL_CALL\n dispose (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n\n \/\/===== XServiceInfo ====================================================\n\n virtual ::rtl::OUString SAL_CALL\n getImplementationName (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL\n getSupportedServiceNames (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n\n \/\/===== lang::XEventListener ============================================\n\n virtual void SAL_CALL\n disposing (const ::com::sun::star::lang::EventObject& Source)\n throw (::com::sun::star::uno::RuntimeException);\n\n\nprotected:\n \/** Create a base name string that contains the accessible name.\n *\/\n virtual ::rtl::OUString\n CreateAccessibleBaseName (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual ::rtl::OUString\n CreateAccessibleName (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Create a description string that contains the accessible description.\n virtual ::rtl::OUString\n CreateAccessibleDescription (void)\n throw (::com::sun::star::uno::RuntimeException);\n\nprivate:\n ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage> mxPage;\n\n \/** Don't use the default constructor. Use the public constructor that\n takes the original shape and the parent as arguments instead.\n *\/\n explicit AccessiblePageShape (void);\n \/\/\/ Don't use the copy constructor. Is there any use for it?\n explicit AccessiblePageShape (const AccessiblePageShape&);\n \/\/\/ Don't use the assignment operator. Do we need this?\n AccessibleShape& operator= (const AccessiblePageShape&);\n};\n\n} \/\/ end of namespace accessibility\n\n#endif\n<commit_msg>INTEGRATION: CWS long2int (1.7.50); FILE MERGED 2005\/10\/26 18:06:47 kendy 1.7.50.1: #i56715# Trivial long\/ULONG -> sal_Int32\/sal_uInt32 patches extracted from ooo64bit02 CWS.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AccessiblePageShape.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: vg $ $Date: 2006-03-31 09:06:21 $\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\n#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PAGE_SHAPE_HXX\n#define _SD_ACCESSIBILITY_ACCESSIBLE_PAGE_SHAPE_HXX\n\n#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_HXX\n#include <svx\/AccessibleShape.hxx>\n#endif\n#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_TREE_INFO_HXX\n#include <svx\/AccessibleShapeTreeInfo.hxx>\n#endif\n#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_LISTENER_HXX\n#include <svx\/IAccessibleViewForwarderListener.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessible.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleExtendedComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_\n#include <com\/sun\/star\/drawing\/XDrawPage.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n\n#ifndef _SVX_UNOEDACC_HXX_\n#include <svx\/AccessibleTextHelper.hxx>\n#endif\n\nnamespace accessibility {\n\n\/** A page shape represents the actual page as seen on the screen.\n*\/\nclass AccessiblePageShape\n : public AccessibleShape\n{\npublic:\n \/\/===== internal ========================================================\n\n \/** Create a new accessible object that makes the given shape accessible.\n @param rxParent\n The accessible parent object. It will be used, for example when\n the <member>getIndexInParent<\/member> method is called.\n @param rShapeTreeInfo\n Bundel of information passed to this shape and all of its desendants.\n @param nIndex\n Index used to disambiguate between objects that have the same\n name. Passing a value of -1 leads to the use of the object's\n z-order instead. Because that is not a good substitute, better\n pass an ever increasing counter.\n @attention\n Always call the <member>init<\/member> method after creating a\n new accessible shape. This is one way to overcome the potential\n problem of registering the new object with e.g. event\n broadcasters. That would delete the new object if a broadcaster\n would not keep a strong reference to the new object.\n *\/\n AccessiblePageShape (\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage>& rxPage,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible>& rxParent,\n const AccessibleShapeTreeInfo& rShapeTreeInfo,\n long nIndex = -1);\n\n virtual ~AccessiblePageShape (void);\n\n \/** Initialize a new shape. See the documentation of the constructor\n for the reason of this method's existence.\n *\/\n virtual void Init (void);\n\n \/\/===== XAccessibleContext ==============================================\n\n \/\/\/ Returns always 0 because there can be no children.\n virtual sal_Int32 SAL_CALL\n getAccessibleChildCount (void)\n throw ();\n\n \/** Return the specified child.\n @param nIndex\n Index of the requested child.\n @return\n Reference of the requested child which is the accessible object\n of a visible shape.\n @raises IndexOutOfBoundsException\n Throws always an exception because there are no children.\n *\/\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible> SAL_CALL\n getAccessibleChild (long nIndex)\n throw (::com::sun::star::uno::RuntimeException);\n\n\n \/\/===== XAccessibleComponent ============================================\n\n virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Int32 SAL_CALL getForeground (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Int32 SAL_CALL getBackground (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/===== XComponent ======================================================\n\n virtual void SAL_CALL\n dispose (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n\n \/\/===== XServiceInfo ====================================================\n\n virtual ::rtl::OUString SAL_CALL\n getImplementationName (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL\n getSupportedServiceNames (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n\n \/\/===== lang::XEventListener ============================================\n\n virtual void SAL_CALL\n disposing (const ::com::sun::star::lang::EventObject& Source)\n throw (::com::sun::star::uno::RuntimeException);\n\n\nprotected:\n \/** Create a base name string that contains the accessible name.\n *\/\n virtual ::rtl::OUString\n CreateAccessibleBaseName (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual ::rtl::OUString\n CreateAccessibleName (void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Create a description string that contains the accessible description.\n virtual ::rtl::OUString\n CreateAccessibleDescription (void)\n throw (::com::sun::star::uno::RuntimeException);\n\nprivate:\n ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage> mxPage;\n\n \/** Don't use the default constructor. Use the public constructor that\n takes the original shape and the parent as arguments instead.\n *\/\n explicit AccessiblePageShape (void);\n \/\/\/ Don't use the copy constructor. Is there any use for it?\n explicit AccessiblePageShape (const AccessiblePageShape&);\n \/\/\/ Don't use the assignment operator. Do we need this?\n AccessibleShape& operator= (const AccessiblePageShape&);\n};\n\n} \/\/ end of namespace accessibility\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <thread>\n#include <eventql\/util\/util\/Base64.h>\n#include <eventql\/util\/fnv.h>\n#include <eventql\/util\/protobuf\/msg.h>\n#include <eventql\/util\/io\/fileutil.h>\n#include <eventql\/io\/sstable\/sstablereader.h>\n#include <eventql\/db\/partition_map.h>\n#include <eventql\/db\/PartitionState.pb.h>\n#include <eventql\/db\/PartitionReplication.h>\n\n#include \"eventql\/eventql.h\"\n\nnamespace eventql {\n\nstatic mdb::MDBOptions tsdb_mdb_opts() {\n mdb::MDBOptions opts;\n opts.data_filename = \"index.db\";\n opts.lock_filename = \"index.db.lck\";\n return opts;\n};\n\nPartitionMap::PartitionMap(\n ServerCfg* cfg) :\n cfg_(cfg),\n db_(mdb::MDB::open(cfg_->db_path, tsdb_mdb_opts())) {}\n\nOption<RefPtr<Table>> PartitionMap::findTable(\n const String& stream_ns,\n const String& table_name) const {\n std::unique_lock<std::mutex> lk(mutex_);\n return findTableWithLock(stream_ns, table_name);\n}\n\nOption<RefPtr<Table>> PartitionMap::findTableWithLock(\n const String& stream_ns,\n const String& table_name) const {\n auto stream_ns_key = stream_ns + \"~\" + table_name;\n\n const auto& iter = tables_.find(stream_ns_key);\n if (iter == tables_.end()) {\n return None<RefPtr<Table>>();\n } else {\n return Some(iter->second);\n }\n}\n\nvoid PartitionMap::configureTable(\n const TableDefinition& table,\n Set<SHA1Hash>* affected_partitions \/* = nullptr *\/) {\n std::unique_lock<std::mutex> lk(mutex_);\n auto tbl_key = table.customer() + \"~\" + table.table_name();\n bool metadata_changed = false;\n\n {\n auto iter = tables_.find(tbl_key);\n if (iter == tables_.end()) {\n tables_.emplace(tbl_key, new Table(table));\n } else {\n auto last_metadata_txn = iter->second->getLastMetadataTransaction();\n if (table.metadata_txnseq() > last_metadata_txn.getSequenceNumber()) {\n metadata_changed = true;\n }\n\n iter->second->updateConfig(table);\n }\n }\n\n if (metadata_changed && affected_partitions != nullptr) {\n auto key_prefix = tbl_key + \"~\";\n auto iter = partitions_.lower_bound(key_prefix);\n for (; iter != partitions_.end(); ++iter) {\n if (!StringUtil::beginsWith(iter->first, key_prefix)) {\n break;\n }\n\n auto partition_id_str = iter->first.substr(key_prefix.size());\n affected_partitions->emplace(\n SHA1Hash(partition_id_str.data(), partition_id_str.size()));\n }\n }\n}\n\nvoid PartitionMap::open() {\n auto txn = db_->startTransaction(false);\n auto cursor = txn->getCursor();\n\n Vector<PartitionKey> partitions;\n for (int i = 0; ; ++i) {\n Buffer key;\n Buffer value;\n if (i == 0) {\n if (!cursor->getFirst(&key, &value)) {\n break;\n }\n } else {\n if (!cursor->getNext(&key, &value)) {\n break;\n }\n }\n\n auto db_key = key.toString();\n if (db_key.size() == 0) {\n continue;\n }\n\n if (db_key[0] == 0x1b) {\n continue;\n }\n\n auto tsdb_namespace_off = StringUtil::find(db_key, '~');\n if (tsdb_namespace_off == String::npos) {\n RAISEF(kRuntimeError, \"invalid partition key: $0\", db_key);\n }\n\n auto tsdb_namespace = db_key.substr(0, tsdb_namespace_off);\n SHA1Hash partition_key(\n db_key.data() + tsdb_namespace_off + 1,\n db_key.size() - tsdb_namespace_off - 1);\n\n auto table_key = value.toString();\n auto table = findTableWithLock(tsdb_namespace, table_key);\n\n auto mem_key = tsdb_namespace + \"~\" + table_key + \"~\";\n mem_key.append((char*) partition_key.data(), partition_key.size());\n\n partitions_.emplace(mem_key, mkScoped(new LazyPartition()));\n\n if (table.isEmpty()) {\n logWarning(\n \"tsdb\",\n \"Orphaned partition: $0\/$1\",\n table_key,\n partition_key.toString());\n continue;\n }\n\n partitions.emplace_back(\n std::make_tuple(tsdb_namespace, table_key, partition_key));\n }\n\n cursor->close();\n txn->abort();\n\n auto background_load_thread = std::thread(\n std::bind(&PartitionMap::loadPartitions, this, partitions));\n\n background_load_thread.detach();\n}\n\nvoid PartitionMap::loadPartitions(const Vector<PartitionKey>& partitions) {\n for (const auto& p : partitions) {\n try {\n findPartition(std::get<0>(p), std::get<1>(p), std::get<2>(p));\n } catch (const StandardException& e) {\n logError(\n \"tsdb\",\n e,\n \"error while loading partition $0\/$1\/$2\",\n std::get<0>(p),\n std::get<1>(p),\n std::get<2>(p).toString());\n }\n }\n}\n\nRefPtr<Partition> PartitionMap::findOrCreatePartition(\n const String& tsdb_namespace,\n const String& table_name,\n const SHA1Hash& partition_key) {\n auto db_key = tsdb_namespace + \"~\";\n db_key.append((char*) partition_key.data(), partition_key.size());\n\n auto mem_key = tsdb_namespace + \"~\" + table_name + \"~\";\n mem_key.append((char*) partition_key.data(), partition_key.size());\n\n std::unique_lock<std::mutex> lk(mutex_);\n auto iter = partitions_.find(mem_key);\n if (iter != partitions_.end()) {\n if (iter->second->isLoaded()) {\n return iter->second->getPartition();\n }\n }\n\n auto table = findTableWithLock(tsdb_namespace, table_name);\n if (table.isEmpty()) {\n RAISEF(kNotFoundError, \"table not found: $0\", table_name);\n }\n\n if (iter != partitions_.end()) {\n auto partition = iter->second.get();\n lk.unlock();\n\n return partition->getPartition(\n tsdb_namespace,\n table.get(),\n partition_key,\n cfg_,\n this);\n }\n\n auto partition = Partition::create(\n tsdb_namespace,\n table.get(),\n partition_key,\n cfg_);\n\n partitions_.emplace(mem_key, mkScoped(new LazyPartition(partition)));\n\n auto txn = db_->startTransaction(false);\n txn->update(\n db_key.data(),\n db_key.size(),\n table_name.data(),\n table_name.size());\n\n txn->commit();\n lk.unlock();\n\n auto change = mkRef(new PartitionChangeNotification());\n change->partition = partition;\n publishPartitionChange(change);\n\n return partition;\n}\n\nOption<RefPtr<Partition>> PartitionMap::findPartition(\n const String& tsdb_namespace,\n const String& table_name,\n const SHA1Hash& partition_key) {\n auto db_key = tsdb_namespace + \"~\";\n db_key.append((char*) partition_key.data(), partition_key.size());\n\n auto mem_key = tsdb_namespace + \"~\" + table_name + \"~\";\n mem_key.append((char*) partition_key.data(), partition_key.size());\n\n std::unique_lock<std::mutex> lk(mutex_);\n auto iter = partitions_.find(mem_key);\n if (iter == partitions_.end()) {\n return None<RefPtr<Partition>>();\n } else {\n if (iter->second->isLoaded()) {\n return Some(iter->second->getPartition());\n }\n\n auto table = findTableWithLock(tsdb_namespace, table_name);\n if (table.isEmpty()) {\n RAISEF(kNotFoundError, \"table not found: $0\", table_name);\n }\n\n auto partition = iter->second.get();\n lk.unlock();\n\n return Some(\n partition->getPartition(\n tsdb_namespace,\n table.get(),\n partition_key,\n cfg_,\n this));\n }\n}\n\nvoid PartitionMap::listTables(\n const String& tsdb_namespace,\n Function<void (const TSDBTableInfo& table)> fn) const {\n for (const auto& tbl : tables_) {\n if (tbl.second->tsdbNamespace() != tsdb_namespace) {\n continue;\n }\n\n TSDBTableInfo ti;\n ti.table_name = tbl.second->name();\n ti.config = tbl.second->config();\n ti.schema = tbl.second->schema();\n fn(ti);\n }\n}\n\nvoid PartitionMap::listTablesReverse(\n const String& tsdb_namespace,\n Function<void (const TSDBTableInfo& table)> fn) const {\n for (auto cur = tables_.rbegin(); cur != tables_.rend(); ++cur) {\n if (cur->second->tsdbNamespace() != tsdb_namespace) {\n continue;\n }\n\n TSDBTableInfo ti;\n ti.table_name = cur->second->name();\n ti.config = cur->second->config();\n ti.schema = cur->second->schema();\n fn(ti);\n }\n}\n\nbool PartitionMap::dropLocalPartition(\n const String& tsdb_namespace,\n const String& table_name,\n const SHA1Hash& partition_key) {\n auto partition_opt = findPartition(tsdb_namespace, table_name, partition_key);\n if (partition_opt.isEmpty()) {\n RAISE(kNotFoundError, \"partition not found\");\n }\n\n auto partition = partition_opt.get();\n auto partition_writer = partition->getWriter();\n\n \/* lock partition *\/\n partition_writer->lock();\n\n \/* check preconditions *\/\n size_t full_copies = 0;\n try {\n auto repl_scheme = cfg_->repl_scheme;\n\n full_copies = partition\n ->getReplicationStrategy(repl_scheme, nullptr)\n ->numFullRemoteCopies();\n\n if (repl_scheme->hasLocalReplica(partition_key) ||\n full_copies < repl_scheme->minNumCopies()) {\n RAISE(kIllegalStateError, \"can't delete partition\");\n }\n } catch (const StandardException& e) {\n \/* unlock partition and bail *\/\n partition_writer->unlock();\n return false;\n }\n\n \/* start deletion *\/\n logInfo(\n \"z1.core\",\n \"Partition $0\/$1\/$2 is not owned by this node and has $3 other \" \\\n \"full copies, trying to unload and drop\",\n tsdb_namespace,\n table_name,\n partition_key.toString(),\n full_copies);\n\n \/* freeze partition and unlock waiting writers (they will fail) *\/\n partition_writer->freeze();\n partition_writer->unlock();\n\n auto db_key = tsdb_namespace + \"~\";\n db_key.append((char*) partition_key.data(), partition_key.size());\n\n auto mem_key = tsdb_namespace + \"~\" + table_name + \"~\";\n mem_key.append((char*) partition_key.data(), partition_key.size());\n\n \/* grab the main lock *\/\n std::unique_lock<std::mutex> lk(mutex_);\n\n \/* delete from in memory partition map *\/\n auto iter = partitions_.find(mem_key);\n if (iter == partitions_.end()) {\n \/* somebody else already deleted this partition *\/\n return true;\n } else {\n partitions_.erase(iter);\n }\n\n \/* delete from on disk partition map *\/\n auto txn = db_->startTransaction(false);\n txn->del(db_key);\n txn->commit();\n\n \/* delete partition data from disk (move to trash) *\/\n {\n auto src_path = FileUtil::joinPaths(\n cfg_->db_path,\n StringUtil::format(\n \"$0\/$1\/$2\",\n tsdb_namespace,\n SHA1::compute(table_name).toString(),\n partition_key.toString()));\n\n auto dst_path = FileUtil::joinPaths(\n cfg_->db_path,\n StringUtil::format(\n \"..\/..\/trash\/$0~$1~$2~$3\",\n tsdb_namespace,\n SHA1::compute(table_name).toString(),\n partition_key.toString(),\n Random::singleton()->hex64()));\n\n FileUtil::mv(src_path, dst_path);\n }\n\n return true;\n}\n\nOption<TSDBTableInfo> PartitionMap::tableInfo(\n const String& tsdb_namespace,\n const String& table_key) const {\n auto table = findTable(tsdb_namespace, table_key);\n if (table.isEmpty()) {\n return None<TSDBTableInfo>();\n }\n\n TSDBTableInfo ti;\n ti.table_name = table.get()->name();\n ti.config = table.get()->config();\n ti.schema = table.get()->schema();\n return Some(ti);\n}\n\nvoid PartitionMap::subscribeToPartitionChanges(PartitionChangeCallbackFn fn) {\n callbacks_.emplace_back(fn);\n}\n\nvoid PartitionMap::publishPartitionChange(\n RefPtr<PartitionChangeNotification> change) {\n for (const auto& cb : callbacks_) {\n cb(change);\n }\n}\n\n\n} \/\/ namespace tdsb\n\n<commit_msg>deliver metadata change notification only for timeseries partitions<commit_after>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <thread>\n#include <eventql\/util\/util\/Base64.h>\n#include <eventql\/util\/fnv.h>\n#include <eventql\/util\/protobuf\/msg.h>\n#include <eventql\/util\/io\/fileutil.h>\n#include <eventql\/io\/sstable\/sstablereader.h>\n#include <eventql\/db\/partition_map.h>\n#include <eventql\/db\/PartitionState.pb.h>\n#include <eventql\/db\/PartitionReplication.h>\n\n#include \"eventql\/eventql.h\"\n\nnamespace eventql {\n\nstatic mdb::MDBOptions tsdb_mdb_opts() {\n mdb::MDBOptions opts;\n opts.data_filename = \"index.db\";\n opts.lock_filename = \"index.db.lck\";\n return opts;\n};\n\nPartitionMap::PartitionMap(\n ServerCfg* cfg) :\n cfg_(cfg),\n db_(mdb::MDB::open(cfg_->db_path, tsdb_mdb_opts())) {}\n\nOption<RefPtr<Table>> PartitionMap::findTable(\n const String& stream_ns,\n const String& table_name) const {\n std::unique_lock<std::mutex> lk(mutex_);\n return findTableWithLock(stream_ns, table_name);\n}\n\nOption<RefPtr<Table>> PartitionMap::findTableWithLock(\n const String& stream_ns,\n const String& table_name) const {\n auto stream_ns_key = stream_ns + \"~\" + table_name;\n\n const auto& iter = tables_.find(stream_ns_key);\n if (iter == tables_.end()) {\n return None<RefPtr<Table>>();\n } else {\n return Some(iter->second);\n }\n}\n\nvoid PartitionMap::configureTable(\n const TableDefinition& table,\n Set<SHA1Hash>* affected_partitions \/* = nullptr *\/) {\n std::unique_lock<std::mutex> lk(mutex_);\n auto tbl_key = table.customer() + \"~\" + table.table_name();\n bool metadata_changed = false;\n\n {\n auto iter = tables_.find(tbl_key);\n if (iter == tables_.end()) {\n tables_.emplace(tbl_key, new Table(table));\n } else {\n if (table.config().partitioner() == TBL_PARTITION_TIMEWINDOW) {\n auto last_metadata_txn = iter->second->getLastMetadataTransaction();\n if (table.metadata_txnseq() > last_metadata_txn.getSequenceNumber()) {\n metadata_changed = true;\n }\n }\n\n iter->second->updateConfig(table);\n }\n }\n\n if (metadata_changed && affected_partitions != nullptr) {\n auto key_prefix = tbl_key + \"~\";\n auto iter = partitions_.lower_bound(key_prefix);\n for (; iter != partitions_.end(); ++iter) {\n if (!StringUtil::beginsWith(iter->first, key_prefix)) {\n break;\n }\n\n auto partition_id_str = iter->first.substr(key_prefix.size());\n affected_partitions->emplace(\n SHA1Hash(partition_id_str.data(), partition_id_str.size()));\n }\n }\n}\n\nvoid PartitionMap::open() {\n auto txn = db_->startTransaction(false);\n auto cursor = txn->getCursor();\n\n Vector<PartitionKey> partitions;\n for (int i = 0; ; ++i) {\n Buffer key;\n Buffer value;\n if (i == 0) {\n if (!cursor->getFirst(&key, &value)) {\n break;\n }\n } else {\n if (!cursor->getNext(&key, &value)) {\n break;\n }\n }\n\n auto db_key = key.toString();\n if (db_key.size() == 0) {\n continue;\n }\n\n if (db_key[0] == 0x1b) {\n continue;\n }\n\n auto tsdb_namespace_off = StringUtil::find(db_key, '~');\n if (tsdb_namespace_off == String::npos) {\n RAISEF(kRuntimeError, \"invalid partition key: $0\", db_key);\n }\n\n auto tsdb_namespace = db_key.substr(0, tsdb_namespace_off);\n SHA1Hash partition_key(\n db_key.data() + tsdb_namespace_off + 1,\n db_key.size() - tsdb_namespace_off - 1);\n\n auto table_key = value.toString();\n auto table = findTableWithLock(tsdb_namespace, table_key);\n\n auto mem_key = tsdb_namespace + \"~\" + table_key + \"~\";\n mem_key.append((char*) partition_key.data(), partition_key.size());\n\n partitions_.emplace(mem_key, mkScoped(new LazyPartition()));\n\n if (table.isEmpty()) {\n logWarning(\n \"tsdb\",\n \"Orphaned partition: $0\/$1\",\n table_key,\n partition_key.toString());\n continue;\n }\n\n partitions.emplace_back(\n std::make_tuple(tsdb_namespace, table_key, partition_key));\n }\n\n cursor->close();\n txn->abort();\n\n auto background_load_thread = std::thread(\n std::bind(&PartitionMap::loadPartitions, this, partitions));\n\n background_load_thread.detach();\n}\n\nvoid PartitionMap::loadPartitions(const Vector<PartitionKey>& partitions) {\n for (const auto& p : partitions) {\n try {\n findPartition(std::get<0>(p), std::get<1>(p), std::get<2>(p));\n } catch (const StandardException& e) {\n logError(\n \"tsdb\",\n e,\n \"error while loading partition $0\/$1\/$2\",\n std::get<0>(p),\n std::get<1>(p),\n std::get<2>(p).toString());\n }\n }\n}\n\nRefPtr<Partition> PartitionMap::findOrCreatePartition(\n const String& tsdb_namespace,\n const String& table_name,\n const SHA1Hash& partition_key) {\n auto db_key = tsdb_namespace + \"~\";\n db_key.append((char*) partition_key.data(), partition_key.size());\n\n auto mem_key = tsdb_namespace + \"~\" + table_name + \"~\";\n mem_key.append((char*) partition_key.data(), partition_key.size());\n\n std::unique_lock<std::mutex> lk(mutex_);\n auto iter = partitions_.find(mem_key);\n if (iter != partitions_.end()) {\n if (iter->second->isLoaded()) {\n return iter->second->getPartition();\n }\n }\n\n auto table = findTableWithLock(tsdb_namespace, table_name);\n if (table.isEmpty()) {\n RAISEF(kNotFoundError, \"table not found: $0\", table_name);\n }\n\n if (iter != partitions_.end()) {\n auto partition = iter->second.get();\n lk.unlock();\n\n return partition->getPartition(\n tsdb_namespace,\n table.get(),\n partition_key,\n cfg_,\n this);\n }\n\n auto partition = Partition::create(\n tsdb_namespace,\n table.get(),\n partition_key,\n cfg_);\n\n partitions_.emplace(mem_key, mkScoped(new LazyPartition(partition)));\n\n auto txn = db_->startTransaction(false);\n txn->update(\n db_key.data(),\n db_key.size(),\n table_name.data(),\n table_name.size());\n\n txn->commit();\n lk.unlock();\n\n auto change = mkRef(new PartitionChangeNotification());\n change->partition = partition;\n publishPartitionChange(change);\n\n return partition;\n}\n\nOption<RefPtr<Partition>> PartitionMap::findPartition(\n const String& tsdb_namespace,\n const String& table_name,\n const SHA1Hash& partition_key) {\n auto db_key = tsdb_namespace + \"~\";\n db_key.append((char*) partition_key.data(), partition_key.size());\n\n auto mem_key = tsdb_namespace + \"~\" + table_name + \"~\";\n mem_key.append((char*) partition_key.data(), partition_key.size());\n\n std::unique_lock<std::mutex> lk(mutex_);\n auto iter = partitions_.find(mem_key);\n if (iter == partitions_.end()) {\n return None<RefPtr<Partition>>();\n } else {\n if (iter->second->isLoaded()) {\n return Some(iter->second->getPartition());\n }\n\n auto table = findTableWithLock(tsdb_namespace, table_name);\n if (table.isEmpty()) {\n RAISEF(kNotFoundError, \"table not found: $0\", table_name);\n }\n\n auto partition = iter->second.get();\n lk.unlock();\n\n return Some(\n partition->getPartition(\n tsdb_namespace,\n table.get(),\n partition_key,\n cfg_,\n this));\n }\n}\n\nvoid PartitionMap::listTables(\n const String& tsdb_namespace,\n Function<void (const TSDBTableInfo& table)> fn) const {\n for (const auto& tbl : tables_) {\n if (tbl.second->tsdbNamespace() != tsdb_namespace) {\n continue;\n }\n\n TSDBTableInfo ti;\n ti.table_name = tbl.second->name();\n ti.config = tbl.second->config();\n ti.schema = tbl.second->schema();\n fn(ti);\n }\n}\n\nvoid PartitionMap::listTablesReverse(\n const String& tsdb_namespace,\n Function<void (const TSDBTableInfo& table)> fn) const {\n for (auto cur = tables_.rbegin(); cur != tables_.rend(); ++cur) {\n if (cur->second->tsdbNamespace() != tsdb_namespace) {\n continue;\n }\n\n TSDBTableInfo ti;\n ti.table_name = cur->second->name();\n ti.config = cur->second->config();\n ti.schema = cur->second->schema();\n fn(ti);\n }\n}\n\nbool PartitionMap::dropLocalPartition(\n const String& tsdb_namespace,\n const String& table_name,\n const SHA1Hash& partition_key) {\n auto partition_opt = findPartition(tsdb_namespace, table_name, partition_key);\n if (partition_opt.isEmpty()) {\n RAISE(kNotFoundError, \"partition not found\");\n }\n\n auto partition = partition_opt.get();\n auto partition_writer = partition->getWriter();\n\n \/* lock partition *\/\n partition_writer->lock();\n\n \/* check preconditions *\/\n size_t full_copies = 0;\n try {\n auto repl_scheme = cfg_->repl_scheme;\n\n full_copies = partition\n ->getReplicationStrategy(repl_scheme, nullptr)\n ->numFullRemoteCopies();\n\n if (repl_scheme->hasLocalReplica(partition_key) ||\n full_copies < repl_scheme->minNumCopies()) {\n RAISE(kIllegalStateError, \"can't delete partition\");\n }\n } catch (const StandardException& e) {\n \/* unlock partition and bail *\/\n partition_writer->unlock();\n return false;\n }\n\n \/* start deletion *\/\n logInfo(\n \"z1.core\",\n \"Partition $0\/$1\/$2 is not owned by this node and has $3 other \" \\\n \"full copies, trying to unload and drop\",\n tsdb_namespace,\n table_name,\n partition_key.toString(),\n full_copies);\n\n \/* freeze partition and unlock waiting writers (they will fail) *\/\n partition_writer->freeze();\n partition_writer->unlock();\n\n auto db_key = tsdb_namespace + \"~\";\n db_key.append((char*) partition_key.data(), partition_key.size());\n\n auto mem_key = tsdb_namespace + \"~\" + table_name + \"~\";\n mem_key.append((char*) partition_key.data(), partition_key.size());\n\n \/* grab the main lock *\/\n std::unique_lock<std::mutex> lk(mutex_);\n\n \/* delete from in memory partition map *\/\n auto iter = partitions_.find(mem_key);\n if (iter == partitions_.end()) {\n \/* somebody else already deleted this partition *\/\n return true;\n } else {\n partitions_.erase(iter);\n }\n\n \/* delete from on disk partition map *\/\n auto txn = db_->startTransaction(false);\n txn->del(db_key);\n txn->commit();\n\n \/* delete partition data from disk (move to trash) *\/\n {\n auto src_path = FileUtil::joinPaths(\n cfg_->db_path,\n StringUtil::format(\n \"$0\/$1\/$2\",\n tsdb_namespace,\n SHA1::compute(table_name).toString(),\n partition_key.toString()));\n\n auto dst_path = FileUtil::joinPaths(\n cfg_->db_path,\n StringUtil::format(\n \"..\/..\/trash\/$0~$1~$2~$3\",\n tsdb_namespace,\n SHA1::compute(table_name).toString(),\n partition_key.toString(),\n Random::singleton()->hex64()));\n\n FileUtil::mv(src_path, dst_path);\n }\n\n return true;\n}\n\nOption<TSDBTableInfo> PartitionMap::tableInfo(\n const String& tsdb_namespace,\n const String& table_key) const {\n auto table = findTable(tsdb_namespace, table_key);\n if (table.isEmpty()) {\n return None<TSDBTableInfo>();\n }\n\n TSDBTableInfo ti;\n ti.table_name = table.get()->name();\n ti.config = table.get()->config();\n ti.schema = table.get()->schema();\n return Some(ti);\n}\n\nvoid PartitionMap::subscribeToPartitionChanges(PartitionChangeCallbackFn fn) {\n callbacks_.emplace_back(fn);\n}\n\nvoid PartitionMap::publishPartitionChange(\n RefPtr<PartitionChangeNotification> change) {\n for (const auto& cb : callbacks_) {\n cb(change);\n }\n}\n\n\n} \/\/ namespace tdsb\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other 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\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"sphere_user.h\"\n\nstatic fclaw2d_vtable_t fclaw2d_vt;\nstatic fc2d_clawpack46_vtable_t classic_claw46;\nstatic fc2d_clawpack5_vtable_t classic_claw5;\n\nvoid sphere_link_solvers(fclaw2d_domain_t *domain)\n{\n const user_options_t *user = sphere_user_get_options(domain);\n\n if (user->claw_version == 4)\n {\n fclaw2d_init_vtable(&fclaw2d_vt);\n fc2d_clawpack46_set_vtable_defaults(&fclaw2d_vt, &classic_claw46);\n\n fclaw2d_vt.problem_setup = &sphere_problem_setup;\n fclaw2d_vt.patch_setup = &sphere_patch_setup;\n\n \/* Needed to avoid triggering refinement around block corners *\/\n fclaw2d_vt.fort_tag4refinement = &CLAWPACK46_TAG4REFINEMENT;\n fclaw2d_vt.fort_tag4coarsening = &CLAWPACK46_TAG4COARSENING;\n\n classic_claw46.qinit = &CLAWPACK46_QINIT;\n classic_claw46.rpn2 = &CLAWPACK46_RPN2ADV_MANIFOLD;\n classic_claw46.rpt2 = &CLAWPACK46_RPT2ADV_MANIFOLD;\n\n fc2d_clawpack46_set_vtable(classic_claw46);\n\n }\n else if (user->claw_version == 5)\n {\n fclaw2d_init_vtable(&fclaw2d_vt);\n fc2d_clawpack5_set_vtable_defaults(&fclaw2d_vt, &classic_claw5);\n\n fclaw2d_vt.problem_setup = &sphere_problem_setup;\n fclaw2d_vt.patch_setup = &sphere_patch_setup;\n\n \/* Needed to avoid triggering refinement around block corners *\/\n fclaw2d_vt.fort_tag4refinement = &CLAWPACK5_TAG4REFINEMENT;\n fclaw2d_vt.fort_tag4coarsening = &CLAWPACK5_TAG4COARSENING;\n\n classic_claw5.qinit = &CLAWPACK5_QINIT;\n classic_claw5.rpn2 = &CLAWPACK5_RPN2ADV_MANIFOLD;\n classic_claw5.rpt2 = &CLAWPACK5_RPT2ADV_MANIFOLD;\n\n fc2d_clawpack5_set_vtable(classic_claw5);\n }\n fclaw2d_set_vtable(domain,&fclaw2d_vt);\n}\n\nvoid sphere_problem_setup(fclaw2d_domain_t* domain)\n{\n const user_options_t *user = sphere_user_get_options(domain);\n\n SPHERE_SETPROB(&user->revs_per_second);\n}\n\n\nvoid sphere_patch_setup(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx)\n{\n int mx,my,mbc,maux;\n double xlower,ylower,dx,dy;\n double *aux,*xd,*yd,*zd,*area;\n double *xp,*yp,*zp;\n const user_options_t* user = sphere_user_get_options(domain);\n\n if (fclaw2d_patch_is_ghost(this_patch))\n {\n return;\n }\n\n fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,\n &xlower,&ylower,&dx,&dy);\n\n fclaw2d_clawpatch_metric_data(domain,this_patch,&xp,&yp,&zp,\n &xd,&yd,&zd,&area);\n\n if (user->claw_version == 4)\n {\n fc2d_clawpack46_define_auxarray(domain,this_patch);\n fc2d_clawpack46_aux_data(domain,this_patch,&aux,&maux);\n\n USER46_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,\n &maux,aux,&this_block_idx,xd,yd,zd,area);\n }\n else if(user->claw_version == 5)\n {\n fc2d_clawpack5_define_auxarray(domain,this_patch);\n fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);\n\n USER5_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,\n &maux,aux,&this_block_idx,xd,yd,zd,area);\n }\n}\n<commit_msg>(sphere) Clean up problem setup<commit_after>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other 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\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"sphere_user.h\"\n\nstatic fclaw2d_vtable_t fclaw2d_vt;\nstatic fc2d_clawpack46_vtable_t classic_claw46;\nstatic fc2d_clawpack5_vtable_t classic_claw5;\n\nvoid sphere_link_solvers(fclaw2d_domain_t *domain)\n{\n const user_options_t *user = sphere_user_get_options(domain);\n\n fclaw2d_init_vtable(&fclaw2d_vt);\n fclaw2d_vt.problem_setup = &sphere_problem_setup;\n\n if (user->claw_version == 4)\n {\n fc2d_clawpack46_set_vtable_defaults(&fclaw2d_vt, &classic_claw46);\n\n fclaw2d_vt.patch_setup = &sphere_patch_setup;\n\n \/* Needed to avoid triggering refinement around block corners *\/\n fclaw2d_vt.fort_tag4refinement = &CLAWPACK46_TAG4REFINEMENT;\n fclaw2d_vt.fort_tag4coarsening = &CLAWPACK46_TAG4COARSENING;\n\n classic_claw46.qinit = &CLAWPACK46_QINIT;\n classic_claw46.rpn2 = &CLAWPACK46_RPN2ADV_MANIFOLD;\n classic_claw46.rpt2 = &CLAWPACK46_RPT2ADV_MANIFOLD;\n\n fc2d_clawpack46_set_vtable(classic_claw46);\n\n }\n else if (user->claw_version == 5)\n {\n fc2d_clawpack5_set_vtable_defaults(&fclaw2d_vt, &classic_claw5);\n\n fclaw2d_vt.patch_setup = &sphere_patch_setup;\n\n \/* Avoid triggering refinement around block corners *\/\n fclaw2d_vt.fort_tag4refinement = &CLAWPACK5_TAG4REFINEMENT;\n fclaw2d_vt.fort_tag4coarsening = &CLAWPACK5_TAG4COARSENING;\n\n classic_claw5.qinit = &CLAWPACK5_QINIT;\n classic_claw5.rpn2 = &CLAWPACK5_RPN2ADV_MANIFOLD;\n classic_claw5.rpt2 = &CLAWPACK5_RPT2ADV_MANIFOLD;\n\n fc2d_clawpack5_set_vtable(classic_claw5);\n }\n fclaw2d_set_vtable(domain,&fclaw2d_vt);\n}\n\nvoid sphere_problem_setup(fclaw2d_domain_t* domain)\n{\n const user_options_t *user = sphere_user_get_options(domain);\n\n SPHERE_SETPROB(&user->revs_per_second);\n}\n\n\nvoid sphere_patch_setup(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx)\n{\n int mx,my,mbc,maux;\n double xlower,ylower,dx,dy;\n double *aux,*xd,*yd,*zd,*area;\n double *xp,*yp,*zp;\n const user_options_t* user = sphere_user_get_options(domain);\n\n if (fclaw2d_patch_is_ghost(this_patch))\n {\n return;\n }\n\n fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,\n &xlower,&ylower,&dx,&dy);\n\n fclaw2d_clawpatch_metric_data(domain,this_patch,&xp,&yp,&zp,\n &xd,&yd,&zd,&area);\n\n if (user->claw_version == 4)\n {\n fc2d_clawpack46_define_auxarray(domain,this_patch);\n fc2d_clawpack46_aux_data(domain,this_patch,&aux,&maux);\n\n USER46_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,\n &maux,aux,&this_block_idx,xd,yd,zd,area);\n }\n else if(user->claw_version == 5)\n {\n fc2d_clawpack5_define_auxarray(domain,this_patch);\n fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);\n\n USER5_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,\n &maux,aux,&this_block_idx,xd,yd,zd,area);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n * - Laura Schlimmer <laura@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n\n#include <assert.h>\n#include <eventql\/sql\/table_schema.h>\n\nnamespace csql {\n\nTableSchema::TableSchema(const TableSchema& other) {\n HashMap<ColumnDefinition const*, ColumnDefinition const*> ptr_map;\n\n for (auto col : other.columns_) {\n auto new_col = new ColumnDefinition(*col);\n ptr_map.emplace(col, new_col);\n columns_.emplace_back(new_col);\n\n for (auto subcol : col->column_schema) {\n auto new_subcol = ptr_map[subcol];\n\n \/**\n * N.B. we require the column list to be built up so that a given column\n * Ci is only ever referenced by another column Cj where j > i.\n *\/\n assert(new_subcol != nullptr); \/\/ invalid reference order\n new_col->column_schema.emplace_back(new_subcol);\n }\n }\n\n for (auto col : other.root_columns_) {\n auto new_col = ptr_map[col];\n assert(new_col != nullptr); \/\/ invalid reference\n root_columns_.emplace_back(new_col);\n }\n}\n\nTableSchema::TableSchema(\n TableSchema&& other) :\n columns_(other.columns_),\n root_columns_(other.root_columns_) {\n other.columns_.clear();\n other.root_columns_.clear();\n}\n\nTableSchema::~TableSchema() {\n for (auto c : columns_) {\n delete c;\n }\n}\n\nTableSchema::ColumnList TableSchema::getColumns() const {\n return root_columns_;\n}\n\nTableSchema::ColumnList TableSchema::getFlatColumnList() const {\n return columns_;\n}\n\nvoid TableSchemaBuilder::addScalarColumn(\n const String& column_name,\n const String& column_type,\n Vector<TableSchema::ColumnOptions> column_options) {\n auto col_def = new TableSchema::ColumnDefinition();\n col_def->column_class = TableSchema::ColumnClass::SCALAR;\n col_def->column_name = column_name;\n col_def->column_type = column_type;\n col_def->column_options = column_options;\n schema_.columns_.emplace_back(col_def);\n schema_.root_columns_.emplace_back(col_def);\n}\n\nvoid TableSchemaBuilder::addRecordColumn(\n const String& column_name,\n Vector<TableSchema::ColumnOptions> column_options,\n TableSchema&& column_schema) {\n auto col_def = new TableSchema::ColumnDefinition();\n col_def->column_class = TableSchema::ColumnClass::RECORD;\n col_def->column_name = column_name;\n col_def->column_type = \"RECORD\";\n col_def->column_options = column_options;\n col_def->column_schema = column_schema.root_columns_;\n\n schema_.columns_.insert(\n schema_.columns_.end(),\n column_schema.columns_.begin(),\n column_schema.columns_.end());\n\n schema_.columns_.emplace_back(col_def);\n schema_.root_columns_.emplace_back(col_def);\n\n column_schema.columns_.clear();\n column_schema.root_columns_.clear();\n}\n\nTableSchema&& TableSchemaBuilder::getTableSchema() {\n return std::move(schema_);\n}\n\n} \/\/ namespace csql\n\n\n\n<commit_msg>reverse nested column order<commit_after>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n * - Laura Schlimmer <laura@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n\n#include <assert.h>\n#include <eventql\/sql\/table_schema.h>\n\nnamespace csql {\n\nTableSchema::TableSchema(const TableSchema& other) {\n HashMap<ColumnDefinition const*, ColumnDefinition const*> ptr_map;\n\n for (auto col = other.columns_.rbegin(); col != other.columns_.rend(); ++col) {\n auto new_col = new ColumnDefinition(**col);\n ptr_map.emplace(*col, new_col);\n columns_.emplace_back(new_col);\n\n for (auto subcol : (*col)->column_schema) {\n auto new_subcol = ptr_map[subcol];\n\n \/**\n * N.B. we require the column list to be built up so that a given column\n * Ci is only ever referenced by another column Cj where j < i.\n *\/\n assert(new_subcol != nullptr); \/\/ invalid reference order\n new_col->column_schema.emplace_back(new_subcol);\n }\n }\n\n for (auto col : other.root_columns_) {\n auto new_col = ptr_map[col];\n assert(new_col != nullptr); \/\/ invalid reference\n root_columns_.emplace_back(new_col);\n }\n}\n\nTableSchema::TableSchema(\n TableSchema&& other) :\n columns_(other.columns_),\n root_columns_(other.root_columns_) {\n other.columns_.clear();\n other.root_columns_.clear();\n}\n\nTableSchema::~TableSchema() {\n for (auto c : columns_) {\n delete c;\n }\n}\n\nTableSchema::ColumnList TableSchema::getColumns() const {\n return root_columns_;\n}\n\nTableSchema::ColumnList TableSchema::getFlatColumnList() const {\n return columns_;\n}\n\nvoid TableSchemaBuilder::addScalarColumn(\n const String& column_name,\n const String& column_type,\n Vector<TableSchema::ColumnOptions> column_options) {\n auto col_def = new TableSchema::ColumnDefinition();\n col_def->column_class = TableSchema::ColumnClass::SCALAR;\n col_def->column_name = column_name;\n col_def->column_type = column_type;\n col_def->column_options = column_options;\n schema_.columns_.emplace_back(col_def);\n schema_.root_columns_.emplace_back(col_def);\n}\n\nvoid TableSchemaBuilder::addRecordColumn(\n const String& column_name,\n Vector<TableSchema::ColumnOptions> column_options,\n TableSchema&& column_schema) {\n auto col_def = new TableSchema::ColumnDefinition();\n col_def->column_class = TableSchema::ColumnClass::RECORD;\n col_def->column_name = column_name;\n col_def->column_type = \"RECORD\";\n col_def->column_options = column_options;\n col_def->column_schema = column_schema.root_columns_;\n\n schema_.columns_.emplace_back(col_def);\n schema_.root_columns_.emplace_back(col_def);\n schema_.columns_.insert(\n schema_.columns_.end(),\n column_schema.columns_.begin(),\n column_schema.columns_.end());\n\n column_schema.columns_.clear();\n column_schema.root_columns_.clear();\n}\n\nTableSchema&& TableSchemaBuilder::getTableSchema() {\n return std::move(schema_);\n}\n\n} \/\/ namespace csql\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n * - Laura Schlimmer <laura@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/eventql.h>\n#include <eventql\/util\/stdtypes.h>\n#include <eventql\/util\/application.h>\n#include <eventql\/util\/cli\/flagparser.h>\n#include <eventql\/util\/csv\/BinaryCSVOutputStream.h>\n#include <eventql\/util\/http\/httpclient.h>\n#include <eventql\/util\/json\/jsonoutputstream.h>\n#include \"eventql\/util\/thread\/FixedSizeThreadPool.h\"\n#include \"eventql\/util\/util\/SimpleRateLimit.h\"\n#include <eventql\/util\/mysql\/MySQL.h>\n#include <eventql\/util\/mysql\/MySQLConnection.h>\n\nusing namespace eventql;\n\nstruct UploadShard {\n Buffer data;\n size_t nrows;\n};\n\nbool run(const cli::FlagParser& flags) {\n auto source_table = flags.getString(\"source_table\");\n auto destination_table = flags.getString(\"destination_table\");\n auto shard_size = flags.getInt(\"shard_size\");\n auto num_upload_threads = flags.getInt(\"upload_threads\");\n auto mysql_addr = flags.getString(\"mysql\");\n auto host = flags.getString(\"host\");\n auto port = flags.getInt(\"port\");\n auto db = flags.getString(\"database\");\n auto max_retries = flags.getInt(\"max_retries\");\n\n logInfo(\"mysql2evql\", \"Connecting to MySQL Server...\");\n\n util::mysql::mysqlInit();\n auto mysql_conn = util::mysql::MySQLConnection::openConnection(URI(mysql_addr));\n\n logInfo(\n \"mysql2evql\",\n \"Analyzing the input table. This might take a few minutes...\");\n\n auto schema = mysql_conn->getTableSchema(source_table);\n logDebug(\"mysql2evql\", \"Table Schema:\\n$0\", schema->toString());\n Vector<String> column_names;\n for (const auto& field : schema->fields()) {\n column_names.emplace_back(field.name);\n }\n\n \/* status line *\/\n std::atomic<size_t> num_rows_uploaded(0);\n util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {\n logInfo(\n \"mysql2evql\",\n \"Uploading... $0 rows\",\n num_rows_uploaded.load());\n });\n\n \/* start upload threads *\/\n http::HTTPMessage::HeaderList auth_headers;\n if (flags.isSet(\"auth_token\")) {\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", flags.getString(\"auth_token\")));\n \/\/} else if (!cfg_.getPassword().isEmpty()) {\n \/\/ auth_headers.emplace_back(\n \/\/ \"Authorization\",\n \/\/ StringUtil::format(\"Basic $0\",\n \/\/ util::Base64::encode(\n \/\/ cfg_.getUser() + \":\" + cfg_.getPassword().get())));\n }\n\n auto insert_uri = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/tables\/insert\",\n host,\n port);\n\n bool upload_done = false;\n bool upload_error = false;\n thread::Queue<UploadShard> upload_queue(1);\n Vector<std::thread> upload_threads(num_upload_threads);\n for (size_t i = 0; i < num_upload_threads; ++i) {\n upload_threads[i] = std::thread([&] {\n while (!upload_done) {\n auto shard = upload_queue.interruptiblePop();\n if (shard.isEmpty()) {\n continue;\n }\n\n auto retry = 0;\n size_t status_code;\n\n for (; ;) {\n logDebug(\n \"mysql2evql\",\n \"Uploading batch; target=$0:$1 size=$2MB\",\n host,\n port,\n shard.get().data.size() \/ 1000000.0);\n\n try {\n\n http::HTTPClient http_client;\n auto upload_res = http_client.executeRequest(\n http::HTTPRequest::mkPost(\n insert_uri,\n \"[\" + shard.get().data.toString() + \"]\",\n auth_headers));\n\n if (upload_res.statusCode() != 201) {\n status_code = upload_res.statusCode();\n logError(\n \"mysql2evql\", \"[FATAL ERROR]: HTTP Status Code $0 $1\",\n upload_res.statusCode(),\n upload_res.body().toString());\n RAISE(kRuntimeError, upload_res.body().toString());\n }\n\n num_rows_uploaded += shard.get().nrows;\n status_line.runMaybe();\n break;\n\n } catch (const std::exception& e) {\n logError(\"mysql2evql\", e, \"error while uploading table data\");\n\n \/* retry upload kMaxRetries times unless an authentication failure occurs *\/\n if (++retry < max_retries && status_code != 403) {\n auto base_wait = 2;\n auto increased_wait = base_wait * (pow(base_wait, retry));\n sleep(increased_wait);\n continue;\n } else {\n upload_error = true;\n break;\n }\n }\n }\n }\n });\n }\n\n \/* fetch rows from mysql *\/\n UploadShard shard;\n shard.nrows = 0;\n json::JSONOutputStream json(BufferOutputStream::fromBuffer(&shard.data));\n\n String where_expr;\n if (flags.isSet(\"filter\")) {\n where_expr = \"WHERE \" + flags.getString(\"filter\");\n }\n\n auto get_rows_qry = StringUtil::format(\n \"SELECT * FROM `$0` $1;\",\n source_table,\n where_expr);\n\n mysql_conn->executeQuery(\n get_rows_qry,\n [&] (const Vector<String>& column_values) -> bool {\n ++shard.nrows;\n\n if (shard.nrows > 1) {\n json.addComma();\n }\n\n json.beginObject();\n json.addObjectEntry(\"database\");\n json.addString(db);\n json.addComma();\n json.addObjectEntry(\"table\");\n json.addString(destination_table);\n json.addComma();\n json.addObjectEntry(\"data\");\n json.beginObject();\n\n for (size_t i = 0; i < column_names.size() && i < column_values.size(); ++i) {\n if (i > 0 ){\n json.addComma();\n }\n\n json.addObjectEntry(column_names[i]);\n json.addString(column_values[i]);\n }\n\n json.endObject();\n json.endObject();\n\n if (shard.nrows == shard_size) {\n upload_queue.insert(shard, true);\n shard.data.clear();\n shard.nrows = 0;\n }\n\n status_line.runMaybe();\n return true;\n });\n\n if (shard.nrows > 0) {\n upload_queue.insert(shard, true);\n }\n\n upload_queue.waitUntilEmpty();\n upload_done = true;\n upload_queue.wakeup();\n for (auto& t : upload_threads) {\n t.join();\n }\n\n status_line.runForce();\n\n if (upload_error) {\n logInfo(\"mysql2evql\", \"Upload finished with errors\");\n return false;\n } else {\n logInfo(\"mysql2evql\", \"Upload finished successfully :)\");\n return true;\n }\n}\n\nint main(int argc, const char** argv) {\n Application::init();\n Application::logToStderr(\"mysql2evql\");\n\n cli::FlagParser flags;\n\n flags.defineFlag(\n \"loglevel\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.defineFlag(\n \"source_table\",\n cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"<name>\");\n\n flags.defineFlag(\n \"destination_table\",\n cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"<name>\");\n\n flags.defineFlag(\n \"host\",\n cli::FlagParser::T_STRING,\n true,\n \"h\",\n NULL,\n \"eventql server hostname\",\n \"<host>\");\n\n flags.defineFlag(\n \"port\",\n cli::FlagParser::T_INTEGER,\n true,\n \"p\",\n NULL,\n \"eventql server port\",\n \"<port>\");\n\n flags.defineFlag(\n \"database\",\n cli::FlagParser::T_STRING,\n true,\n \"db\",\n \"\",\n \"eventql database\",\n \"<database>\");\n\n flags.defineFlag(\n \"auth_token\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"auth token\",\n \"<token>\");\n\n flags.defineFlag(\n \"mysql\",\n cli::FlagParser::T_STRING,\n true,\n \"x\",\n \"mysql:\/\/localhost:3306\/mydb?user=root\",\n \"MySQL connection string\",\n \"<url>\");\n\n flags.defineFlag(\n \"filter\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"boolean sql expression\",\n \"<sql_expr>\");\n\n\n flags.defineFlag(\n \"shard_size\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"128\",\n \"shard size\",\n \"<num>\");\n\n flags.defineFlag(\n \"upload_threads\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"8\",\n \"concurrent uploads\",\n \"<num>\");\n\n flags.defineFlag(\n \"max_retries\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"20\",\n \"max number of upload retries\",\n \"<num>\");\n\n try {\n flags.parseArgv(argc, argv);\n } catch (const StandardException& e) {\n logError(\"mysql2evql\", \"$0\", e.what());\n auto stdout_os = OutputStream::getStdout();\n flags.printUsage(stdout_os.get());\n return 0;\n }\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n try {\n if (run(flags)) {\n return 0;\n } else {\n return 1;\n }\n } catch (const StandardException& e) {\n logFatal(\"mysql2evql\", \"$0\", e.what());\n return 1;\n }\n}\n<commit_msg>formatting<commit_after>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n * - Laura Schlimmer <laura@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/eventql.h>\n#include <eventql\/util\/stdtypes.h>\n#include <eventql\/util\/application.h>\n#include <eventql\/util\/cli\/flagparser.h>\n#include <eventql\/util\/csv\/BinaryCSVOutputStream.h>\n#include <eventql\/util\/http\/httpclient.h>\n#include <eventql\/util\/json\/jsonoutputstream.h>\n#include \"eventql\/util\/thread\/FixedSizeThreadPool.h\"\n#include \"eventql\/util\/util\/SimpleRateLimit.h\"\n#include <eventql\/util\/mysql\/MySQL.h>\n#include <eventql\/util\/mysql\/MySQLConnection.h>\n\nusing namespace eventql;\n\nstruct UploadShard {\n Buffer data;\n size_t nrows;\n};\n\nbool run(const cli::FlagParser& flags) {\n auto source_table = flags.getString(\"source_table\");\n auto destination_table = flags.getString(\"destination_table\");\n auto shard_size = flags.getInt(\"shard_size\");\n auto num_upload_threads = flags.getInt(\"upload_threads\");\n auto mysql_addr = flags.getString(\"mysql\");\n auto host = flags.getString(\"host\");\n auto port = flags.getInt(\"port\");\n auto db = flags.getString(\"database\");\n auto max_retries = flags.getInt(\"max_retries\");\n\n logInfo(\"mysql2evql\", \"Connecting to MySQL Server...\");\n\n util::mysql::mysqlInit();\n auto mysql_conn = util::mysql::MySQLConnection::openConnection(URI(mysql_addr));\n\n logInfo(\n \"mysql2evql\",\n \"Analyzing the input table. This might take a few minutes...\");\n\n auto schema = mysql_conn->getTableSchema(source_table);\n logDebug(\"mysql2evql\", \"Table Schema:\\n$0\", schema->toString());\n Vector<String> column_names;\n for (const auto& field : schema->fields()) {\n column_names.emplace_back(field.name);\n }\n\n \/* status line *\/\n std::atomic<size_t> num_rows_uploaded(0);\n util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {\n logInfo(\n \"mysql2evql\",\n \"Uploading... $0 rows\",\n num_rows_uploaded.load());\n });\n\n \/* start upload threads *\/\n http::HTTPMessage::HeaderList auth_headers;\n if (flags.isSet(\"auth_token\")) {\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", flags.getString(\"auth_token\")));\n \/\/} else if (!cfg_.getPassword().isEmpty()) {\n \/\/ auth_headers.emplace_back(\n \/\/ \"Authorization\",\n \/\/ StringUtil::format(\"Basic $0\",\n \/\/ util::Base64::encode(\n \/\/ cfg_.getUser() + \":\" + cfg_.getPassword().get())));\n }\n\n auto insert_uri = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/tables\/insert\",\n host,\n port);\n\n bool upload_done = false;\n bool upload_error = false;\n thread::Queue<UploadShard> upload_queue(1);\n Vector<std::thread> upload_threads(num_upload_threads);\n for (size_t i = 0; i < num_upload_threads; ++i) {\n upload_threads[i] = std::thread([&] {\n while (!upload_done) {\n auto shard = upload_queue.interruptiblePop();\n if (shard.isEmpty()) {\n continue;\n }\n\n auto retry = 0;\n size_t status_code;\n for (; ;) {\n logDebug(\n \"mysql2evql\",\n \"Uploading batch; target=$0:$1 size=$2MB\",\n host,\n port,\n shard.get().data.size() \/ 1000000.0);\n\n try {\n\n http::HTTPClient http_client;\n auto upload_res = http_client.executeRequest(\n http::HTTPRequest::mkPost(\n insert_uri,\n \"[\" + shard.get().data.toString() + \"]\",\n auth_headers));\n\n if (upload_res.statusCode() != 201) {\n status_code = upload_res.statusCode();\n logError(\n \"mysql2evql\", \"[FATAL ERROR]: HTTP Status Code $0 $1\",\n upload_res.statusCode(),\n upload_res.body().toString());\n RAISE(kRuntimeError, upload_res.body().toString());\n }\n\n num_rows_uploaded += shard.get().nrows;\n status_line.runMaybe();\n break;\n\n } catch (const std::exception& e) {\n logError(\"mysql2evql\", e, \"error while uploading table data\");\n \/* retry upload kMaxRetries times unless an authentication failure occurs *\/\n if (++retry < max_retries && status_code != 403) {\n auto base_wait = 2;\n sleep(base_wait * (pow(base_wait, retry));\n continue;\n } else {\n upload_error = true;\n break;\n }\n }\n }\n }\n });\n }\n\n \/* fetch rows from mysql *\/\n UploadShard shard;\n shard.nrows = 0;\n json::JSONOutputStream json(BufferOutputStream::fromBuffer(&shard.data));\n\n String where_expr;\n if (flags.isSet(\"filter\")) {\n where_expr = \"WHERE \" + flags.getString(\"filter\");\n }\n\n auto get_rows_qry = StringUtil::format(\n \"SELECT * FROM `$0` $1;\",\n source_table,\n where_expr);\n\n mysql_conn->executeQuery(\n get_rows_qry,\n [&] (const Vector<String>& column_values) -> bool {\n ++shard.nrows;\n\n if (shard.nrows > 1) {\n json.addComma();\n }\n\n json.beginObject();\n json.addObjectEntry(\"database\");\n json.addString(db);\n json.addComma();\n json.addObjectEntry(\"table\");\n json.addString(destination_table);\n json.addComma();\n json.addObjectEntry(\"data\");\n json.beginObject();\n\n for (size_t i = 0; i < column_names.size() && i < column_values.size(); ++i) {\n if (i > 0 ){\n json.addComma();\n }\n\n json.addObjectEntry(column_names[i]);\n json.addString(column_values[i]);\n }\n\n json.endObject();\n json.endObject();\n\n if (shard.nrows == shard_size) {\n upload_queue.insert(shard, true);\n shard.data.clear();\n shard.nrows = 0;\n }\n\n status_line.runMaybe();\n return true;\n });\n\n if (shard.nrows > 0) {\n upload_queue.insert(shard, true);\n }\n\n upload_queue.waitUntilEmpty();\n upload_done = true;\n upload_queue.wakeup();\n for (auto& t : upload_threads) {\n t.join();\n }\n\n status_line.runForce();\n\n if (upload_error) {\n logInfo(\"mysql2evql\", \"Upload finished with errors\");\n return false;\n } else {\n logInfo(\"mysql2evql\", \"Upload finished successfully :)\");\n return true;\n }\n}\n\nint main(int argc, const char** argv) {\n Application::init();\n Application::logToStderr(\"mysql2evql\");\n\n cli::FlagParser flags;\n\n flags.defineFlag(\n \"loglevel\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.defineFlag(\n \"source_table\",\n cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"<name>\");\n\n flags.defineFlag(\n \"destination_table\",\n cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"<name>\");\n\n flags.defineFlag(\n \"host\",\n cli::FlagParser::T_STRING,\n true,\n \"h\",\n NULL,\n \"eventql server hostname\",\n \"<host>\");\n\n flags.defineFlag(\n \"port\",\n cli::FlagParser::T_INTEGER,\n true,\n \"p\",\n NULL,\n \"eventql server port\",\n \"<port>\");\n\n flags.defineFlag(\n \"database\",\n cli::FlagParser::T_STRING,\n true,\n \"db\",\n \"\",\n \"eventql database\",\n \"<database>\");\n\n flags.defineFlag(\n \"auth_token\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"auth token\",\n \"<token>\");\n\n flags.defineFlag(\n \"mysql\",\n cli::FlagParser::T_STRING,\n true,\n \"x\",\n \"mysql:\/\/localhost:3306\/mydb?user=root\",\n \"MySQL connection string\",\n \"<url>\");\n\n flags.defineFlag(\n \"filter\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"boolean sql expression\",\n \"<sql_expr>\");\n\n\n flags.defineFlag(\n \"shard_size\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"128\",\n \"shard size\",\n \"<num>\");\n\n flags.defineFlag(\n \"upload_threads\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"8\",\n \"concurrent uploads\",\n \"<num>\");\n\n flags.defineFlag(\n \"max_retries\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"20\",\n \"max number of upload retries\",\n \"<num>\");\n\n try {\n flags.parseArgv(argc, argv);\n } catch (const StandardException& e) {\n logError(\"mysql2evql\", \"$0\", e.what());\n auto stdout_os = OutputStream::getStdout();\n flags.printUsage(stdout_os.get());\n return 0;\n }\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n try {\n if (run(flags)) {\n return 0;\n } else {\n return 1;\n }\n } catch (const StandardException& e) {\n logFatal(\"mysql2evql\", \"$0\", e.what());\n return 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>AliAnalysisTask *AddTask_miweber_LMEE_pp(){\n\n\n \/\/get the current analysis manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTask_miweber_LMEE_pp\", \"No analysis manager found.\");\n return 0;\n }\n\n Bool_t bESDANA=kFALSE; \/\/Autodetect via InputHandler\n\n TString configBasePath(\"$ALICE_PHYSICS\/PWGDQ\/dielectron\/macrosLMEE\/\");\n TString configFile(\"Config_miweber_LMEE_pp.C\");\n TString configLMEECutLib(\"LMEECutLib_miweber.C\");\n TString configFilePath(configBasePath+configFile);\n TString configLMEECutLibPath(configBasePath+configLMEECutLib);\n \n \n \/\/load dielectron configuration files\n if (!gROOT->GetListOfGlobalFunctions()->FindObject(configLMEECutLib.Data()))\n gROOT->LoadMacro(configLMEECutLibPath.Data());\n if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))\n gROOT->LoadMacro(configFilePath.Data());\n\n \/\/ cut lib\n LMEECutLib* cutlib = new LMEECutLib();\n\n \/\/Do we have an MC handler?\n Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);\n\n \/\/AOD Usage currently tested with Input handler\n if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){\n ::Info(\"AddTaskLMEEPbPb2011\", \"no dedicated AOD configuration\");\n }\n else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){\n ::Info(\"AddTaskLMEEPbPb2011AOD\",\"switching on ESD specific code\");\n bESDANA=kTRUE;\n }\n \n \/\/create task and add it to the manager\n AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron(\"MultiDiEData_miweber_pp\");\n if (!hasMC) task->UsePhysicsSelection();\n\n \/\/Add event filter\n Int_t triggerNames=(AliVEvent::kINT7+AliVEvent::kMB+AliVEvent::kINT8);\/\/pp 2010\/2011 Min Bias?\n task->SetEventFilter(cutlib->GetEventCuts(LMEECutLib::kpp2010All));\n task->SetRejectPileup();\n \/\/ Note: event cuts are identical for all analysis 'cutDefinition's that run together!\n\n \/\/ Add the task to the manager\n mgr->AddTask(task);\n \n \/\/add dielectron analysis with different cuts to the task\n for (Int_t i=0; i<nDie; ++i){ \/\/nDie defined in config file\n \/\/MB\n AliDielectron *diel_low = Config_miweber_pp(i,hasMC,bESDANA);\n if(!diel_low)continue;\n task->AddDielectron(diel_low);\n printf(\"successfully added AliDielectron: %s\\n\",diel_low->GetName());\n }\/\/loop\n\n\n \/\/create output container\n AliAnalysisDataContainer *coutput1 =\n mgr->CreateContainer(\"miweber_LMEE_pp_tree\",\n TTree::Class(),\n AliAnalysisManager::kExchangeContainer,\n \"AnalysisResults.root\");\n \n AliAnalysisDataContainer *cOutputHist1 =\n mgr->CreateContainer(\"miweber_LMEE_pp_out\",\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n \"AnalysisResults.root\");\n \n AliAnalysisDataContainer *cOutputHist2 =\n mgr->CreateContainer(\"miweber_LMEE_pp_CF\",\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n \"AnalysisResults.root\");\n \/\/ \"miweber_LMEE_pp_CF.root\");\n \n AliAnalysisDataContainer *cOutputHist3 =\n mgr->CreateContainer(\"miweber_EventStat\",\n TH1D::Class(),\n AliAnalysisManager::kOutputContainer,\n \"AnalysisResults.root\");\n \n \n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 0, coutput1 );\n mgr->ConnectOutput(task, 1, cOutputHist1);\n mgr->ConnectOutput(task, 2, cOutputHist2);\n mgr->ConnectOutput(task, 3, cOutputHist3);\n \n return task;\n}\n<commit_msg>o updated macro (Michael Weber)<commit_after>AliAnalysisTask *AddTask_miweber_LMEE_pp(TString outputFileName = \"AnalysisResult.root\"){\n\n\n \/\/get the current analysis manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTask_miweber_LMEE_pp\", \"No analysis manager found.\");\n return 0;\n }\n\n Bool_t bESDANA=kFALSE; \/\/Autodetect via InputHandler\n\n TString configBasePath(\"$ALICE_PHYSICS\/PWGDQ\/dielectron\/macrosLMEE\/\");\n TString configFile(\"Config_miweber_LMEE_pp.C\");\n TString configLMEECutLib(\"LMEECutLib_miweber.C\");\n TString configFilePath(configBasePath+configFile);\n TString configLMEECutLibPath(configBasePath+configLMEECutLib);\n \n \n \/\/load dielectron configuration files\n if (!gROOT->GetListOfGlobalFunctions()->FindObject(configLMEECutLib.Data()))\n gROOT->LoadMacro(configLMEECutLibPath.Data());\n if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))\n gROOT->LoadMacro(configFilePath.Data());\n\n \/\/ cut lib\n LMEECutLib* cutlib = new LMEECutLib();\n\n \/\/Do we have an MC handler?\n Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);\n\n \/\/AOD Usage currently tested with Input handler\n if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){\n ::Info(\"AddTaskLMEEPbPb2011\", \"no dedicated AOD configuration\");\n }\n else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){\n ::Info(\"AddTaskLMEEPbPb2011AOD\",\"switching on ESD specific code\");\n bESDANA=kTRUE;\n }\n \n \/\/create task and add it to the manager\n AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron(\"MultiDiEData_miweber_pp\");\n if (!hasMC) task->UsePhysicsSelection();\n\n \/\/Add event filter\n Int_t triggerNames=(AliVEvent::kINT7+AliVEvent::kMB+AliVEvent::kINT8);\/\/pp 2010\/2011 Min Bias?\n task->SetEventFilter(cutlib->GetEventCuts(LMEECutLib::kpp2010All));\n task->SetRejectPileup();\n \/\/ Note: event cuts are identical for all analysis 'cutDefinition's that run together!\n\n \/\/ Add the task to the manager\n mgr->AddTask(task);\n \n \/\/add dielectron analysis with different cuts to the task\n for (Int_t i=0; i<nDie; ++i){ \/\/nDie defined in config file\n \/\/MB\n AliDielectron *diel_low = Config_miweber_pp(i,hasMC,bESDANA);\n if(!diel_low)continue;\n task->AddDielectron(diel_low);\n printf(\"successfully added AliDielectron: %s\\n\",diel_low->GetName());\n }\/\/loop\n\n\n \/\/create output container\n AliAnalysisDataContainer *coutput1 =\n mgr->CreateContainer(\"miweber_LMEE_pp_tree\",\n TTree::Class(),\n AliAnalysisManager::kExchangeContainer,\n outputFileName.Data());\n \n AliAnalysisDataContainer *cOutputHist1 =\n mgr->CreateContainer(\"miweber_LMEE_pp_out\",\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName.Data());\n \n AliAnalysisDataContainer *cOutputHist2 =\n mgr->CreateContainer(\"miweber_LMEE_pp_CF\",\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName.Data());\n \/\/ \"miweber_LMEE_pp_CF.root\");\n \n AliAnalysisDataContainer *cOutputHist3 =\n mgr->CreateContainer(\"miweber_EventStat\",\n TH1D::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName.Data());\n \n \n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 0, coutput1 );\n mgr->ConnectOutput(task, 1, cOutputHist1);\n mgr->ConnectOutput(task, 2, cOutputHist2);\n mgr->ConnectOutput(task, 3, cOutputHist3);\n \n return task;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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 <activemq\/connector\/openwire\/marshal\/V2\/MarshallerFactory.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQBytesMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQMapMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQObjectMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQQueueMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQStreamMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQTempQueueMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQTempTopicMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQTextMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQTopicMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/BrokerIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/BrokerInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConnectionControlMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConnectionErrorMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConnectionIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConnectionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConsumerControlMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConsumerIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConsumerInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ControlCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/DataArrayResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/DataResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/DestinationInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/DiscoveryEventMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ExceptionResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/FlushCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/IntegerResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/JournalQueueAckMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/JournalTopicAckMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/JournalTraceMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/JournalTransactionMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/KeepAliveInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/LastPartialCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/LocalTransactionIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessageAckMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessageDispatchMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessageDispatchNotificationMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessageIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessagePullMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/NetworkBridgeFilterMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/PartialCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ProducerIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ProducerInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/RemoveInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/RemoveSubscriptionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ReplayCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/SessionIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/SessionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ShutdownInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/SubscriptionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/TransactionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/WireFormatInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/XATransactionIdMarshaller.h>\n\n\/*\n *\n * Command and marshalling code for OpenWire format for MarshallerFactory\n *\n *\n * NOTE!: This file is autogenerated - do not modify!\n * if you need to make a change, please see the Java Classes\n * in the activemq-openwire-generator module\n *\n *\/\n\nusing namespace activemq;\nusing namespace activemq::connector;\nusing namespace activemq::connector::openwire;\nusing namespace activemq::connector::openwire::marshal;\nusing namespace activemq::connector::openwire::marshal::v2;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid MarshallerFactory::configure( OpenWireFormat* format ) {\n format->addMarshaller( new ActiveMQBytesMessageMarshaller());\n format->addMarshaller( new ActiveMQMapMessageMarshaller());\n format->addMarshaller( new ActiveMQMessageMarshaller());\n format->addMarshaller( new ActiveMQObjectMessageMarshaller());\n format->addMarshaller( new ActiveMQQueueMarshaller());\n format->addMarshaller( new ActiveMQStreamMessageMarshaller());\n format->addMarshaller( new ActiveMQTempQueueMarshaller());\n format->addMarshaller( new ActiveMQTempTopicMarshaller());\n format->addMarshaller( new ActiveMQTextMessageMarshaller());\n format->addMarshaller( new ActiveMQTopicMarshaller());\n format->addMarshaller( new BrokerIdMarshaller());\n format->addMarshaller( new BrokerInfoMarshaller());\n format->addMarshaller( new ConnectionControlMarshaller());\n format->addMarshaller( new ConnectionErrorMarshaller());\n format->addMarshaller( new ConnectionIdMarshaller());\n format->addMarshaller( new ConnectionInfoMarshaller());\n format->addMarshaller( new ConsumerControlMarshaller());\n format->addMarshaller( new ConsumerIdMarshaller());\n format->addMarshaller( new ConsumerInfoMarshaller());\n format->addMarshaller( new ControlCommandMarshaller());\n format->addMarshaller( new DataArrayResponseMarshaller());\n format->addMarshaller( new DataResponseMarshaller());\n format->addMarshaller( new DestinationInfoMarshaller());\n format->addMarshaller( new DiscoveryEventMarshaller());\n format->addMarshaller( new ExceptionResponseMarshaller());\n format->addMarshaller( new FlushCommandMarshaller());\n format->addMarshaller( new IntegerResponseMarshaller());\n format->addMarshaller( new JournalQueueAckMarshaller());\n format->addMarshaller( new JournalTopicAckMarshaller());\n format->addMarshaller( new JournalTraceMarshaller());\n format->addMarshaller( new JournalTransactionMarshaller());\n format->addMarshaller( new KeepAliveInfoMarshaller());\n format->addMarshaller( new LastPartialCommandMarshaller());\n format->addMarshaller( new LocalTransactionIdMarshaller());\n format->addMarshaller( new MessageAckMarshaller());\n format->addMarshaller( new MessageDispatchMarshaller());\n format->addMarshaller( new MessageDispatchNotificationMarshaller());\n format->addMarshaller( new MessageIdMarshaller());\n format->addMarshaller( new MessagePullMarshaller());\n format->addMarshaller( new NetworkBridgeFilterMarshaller());\n format->addMarshaller( new PartialCommandMarshaller());\n format->addMarshaller( new ProducerIdMarshaller());\n format->addMarshaller( new ProducerInfoMarshaller());\n format->addMarshaller( new RemoveInfoMarshaller());\n format->addMarshaller( new RemoveSubscriptionInfoMarshaller());\n format->addMarshaller( new ReplayCommandMarshaller());\n format->addMarshaller( new ResponseMarshaller());\n format->addMarshaller( new SessionIdMarshaller());\n format->addMarshaller( new SessionInfoMarshaller());\n format->addMarshaller( new ShutdownInfoMarshaller());\n format->addMarshaller( new SubscriptionInfoMarshaller());\n format->addMarshaller( new TransactionInfoMarshaller());\n format->addMarshaller( new WireFormatInfoMarshaller());\n format->addMarshaller( new XATransactionIdMarshaller());\n}\n\n<commit_msg>https:\/\/issues.apache.org\/activemq\/browse\/AMQCPP-21<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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 <activemq\/connector\/openwire\/marshal\/v2\/MarshallerFactory.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQBytesMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQMapMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQObjectMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQQueueMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQStreamMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQTempQueueMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQTempTopicMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQTextMessageMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ActiveMQTopicMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/BrokerIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/BrokerInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConnectionControlMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConnectionErrorMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConnectionIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConnectionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConsumerControlMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConsumerIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ConsumerInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ControlCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/DataArrayResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/DataResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/DestinationInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/DiscoveryEventMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ExceptionResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/FlushCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/IntegerResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/JournalQueueAckMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/JournalTopicAckMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/JournalTraceMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/JournalTransactionMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/KeepAliveInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/LastPartialCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/LocalTransactionIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessageAckMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessageDispatchMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessageDispatchNotificationMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessageIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/MessagePullMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/NetworkBridgeFilterMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/PartialCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ProducerIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ProducerInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/RemoveInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/RemoveSubscriptionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ReplayCommandMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ResponseMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/SessionIdMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/SessionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/ShutdownInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/SubscriptionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/TransactionInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/WireFormatInfoMarshaller.h>\n#include <activemq\/connector\/openwire\/marshal\/v2\/XATransactionIdMarshaller.h>\n\n\/*\n *\n * Command and marshalling code for OpenWire format for MarshallerFactory\n *\n *\n * NOTE!: This file is autogenerated - do not modify!\n * if you need to make a change, please see the Java Classes\n * in the activemq-openwire-generator module\n *\n *\/\n\nusing namespace activemq;\nusing namespace activemq::connector;\nusing namespace activemq::connector::openwire;\nusing namespace activemq::connector::openwire::marshal;\nusing namespace activemq::connector::openwire::marshal::v2;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid MarshallerFactory::configure( OpenWireFormat* format ) {\n format->addMarshaller( new ActiveMQBytesMessageMarshaller());\n format->addMarshaller( new ActiveMQMapMessageMarshaller());\n format->addMarshaller( new ActiveMQMessageMarshaller());\n format->addMarshaller( new ActiveMQObjectMessageMarshaller());\n format->addMarshaller( new ActiveMQQueueMarshaller());\n format->addMarshaller( new ActiveMQStreamMessageMarshaller());\n format->addMarshaller( new ActiveMQTempQueueMarshaller());\n format->addMarshaller( new ActiveMQTempTopicMarshaller());\n format->addMarshaller( new ActiveMQTextMessageMarshaller());\n format->addMarshaller( new ActiveMQTopicMarshaller());\n format->addMarshaller( new BrokerIdMarshaller());\n format->addMarshaller( new BrokerInfoMarshaller());\n format->addMarshaller( new ConnectionControlMarshaller());\n format->addMarshaller( new ConnectionErrorMarshaller());\n format->addMarshaller( new ConnectionIdMarshaller());\n format->addMarshaller( new ConnectionInfoMarshaller());\n format->addMarshaller( new ConsumerControlMarshaller());\n format->addMarshaller( new ConsumerIdMarshaller());\n format->addMarshaller( new ConsumerInfoMarshaller());\n format->addMarshaller( new ControlCommandMarshaller());\n format->addMarshaller( new DataArrayResponseMarshaller());\n format->addMarshaller( new DataResponseMarshaller());\n format->addMarshaller( new DestinationInfoMarshaller());\n format->addMarshaller( new DiscoveryEventMarshaller());\n format->addMarshaller( new ExceptionResponseMarshaller());\n format->addMarshaller( new FlushCommandMarshaller());\n format->addMarshaller( new IntegerResponseMarshaller());\n format->addMarshaller( new JournalQueueAckMarshaller());\n format->addMarshaller( new JournalTopicAckMarshaller());\n format->addMarshaller( new JournalTraceMarshaller());\n format->addMarshaller( new JournalTransactionMarshaller());\n format->addMarshaller( new KeepAliveInfoMarshaller());\n format->addMarshaller( new LastPartialCommandMarshaller());\n format->addMarshaller( new LocalTransactionIdMarshaller());\n format->addMarshaller( new MessageAckMarshaller());\n format->addMarshaller( new MessageDispatchMarshaller());\n format->addMarshaller( new MessageDispatchNotificationMarshaller());\n format->addMarshaller( new MessageIdMarshaller());\n format->addMarshaller( new MessagePullMarshaller());\n format->addMarshaller( new NetworkBridgeFilterMarshaller());\n format->addMarshaller( new PartialCommandMarshaller());\n format->addMarshaller( new ProducerIdMarshaller());\n format->addMarshaller( new ProducerInfoMarshaller());\n format->addMarshaller( new RemoveInfoMarshaller());\n format->addMarshaller( new RemoveSubscriptionInfoMarshaller());\n format->addMarshaller( new ReplayCommandMarshaller());\n format->addMarshaller( new ResponseMarshaller());\n format->addMarshaller( new SessionIdMarshaller());\n format->addMarshaller( new SessionInfoMarshaller());\n format->addMarshaller( new ShutdownInfoMarshaller());\n format->addMarshaller( new SubscriptionInfoMarshaller());\n format->addMarshaller( new TransactionInfoMarshaller());\n format->addMarshaller( new WireFormatInfoMarshaller());\n format->addMarshaller( new XATransactionIdMarshaller());\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Streamlined sun update changes. Added night\/day detection<commit_after><|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ bzflag common header\n#include \"common.h\"\n\n\/\/ interface header\n#include \"LaserSceneNode.h\"\n\n\/\/ system headers\n#include <math.h>\n\n\/\/ common implementation headers\n#include \"StateDatabase.h\"\n#include \"BZDBCache.h\"\n\n\/\/ FIXME (SceneRenderer.cxx is in src\/bzflag)\n#include \"SceneRenderer.h\"\n\nconst GLfloat\t\tLaserRadius = 0.1f;\n\nLaserSceneNode::LaserSceneNode(const GLfloat pos[3], const GLfloat forward[3]) :\n\t\t\t\ttexturing(false),\n\t\t\t\trenderNode(this)\n{\n \/\/ prepare rendering info\n azimuth = (float)(180.0 \/ M_PI*atan2f(forward[1], forward[0]));\n elevation = (float)(-180.0 \/ M_PI*atan2f(forward[2], hypotf(forward[0],forward[1])));\n length = hypotf(forward[0], hypotf(forward[1], forward[2]));\n\n \/\/ setup sphere\n setCenter(pos);\n setRadius(length * length);\n\n OpenGLGStateBuilder builder(gstate);\n builder.setCulling(GL_NONE);\n gstate = builder.getState();\n}\n\nLaserSceneNode::~LaserSceneNode()\n{\n \/\/ do nothing\n}\n\nvoid\t\t\tLaserSceneNode::setTexture(const int texture)\n{\n OpenGLGStateBuilder builder(gstate);\n builder.setTexture(texture);\n builder.enableTexture(texture>=0);\n gstate = builder.getState();\n}\n\nbool\t\t\tLaserSceneNode::cull(const ViewFrustum&) const\n{\n \/\/ no culling\n return false;\n}\n\nvoid\t\t\tLaserSceneNode::notifyStyleChange()\n{\n texturing = BZDBCache::texture && BZDBCache::blend;\n OpenGLGStateBuilder builder(gstate);\n builder.enableTexture(texturing);\n if (BZDBCache::blend) {\n \/\/ add in contribution from laser\n builder.setBlending(GL_SRC_ALPHA, GL_ONE);\n builder.setSmoothing(BZDB.isTrue(\"smooth\"));\n }\n else {\n builder.resetBlending();\n builder.setSmoothing(false);\n }\n gstate = builder.getState();\n}\n\nvoid\t\t\tLaserSceneNode::addRenderNodes(\n\t\t\t\tSceneRenderer& renderer)\n{\n renderer.addRenderNode(&renderNode, &gstate);\n}\n\n\/\/\n\/\/ LaserSceneNode::LaserRenderNode\n\/\/\n\nGLfloat\t\t\tLaserSceneNode::LaserRenderNode::geom[6][2];\n\nLaserSceneNode::LaserRenderNode::LaserRenderNode(\n\t\t\t\tconst LaserSceneNode* _sceneNode) :\n\t\t\t\tsceneNode(_sceneNode)\n{\n \/\/ initialize geometry if first instance\n static bool init = false;\n if (!init) {\n init = true;\n for (int i = 0; i < 6; i++) {\n geom[i][0] = (float)(-LaserRadius * cosf(2.0 * M_PI * float(i) \/ 6.0));\n geom[i][1] = (float)(LaserRadius * sinf(2.0 * M_PI * float(i) \/ 6.0));\n }\n }\n}\n\nLaserSceneNode::LaserRenderNode::~LaserRenderNode()\n{\n \/\/ do nothing\n}\n\nvoid\t\t\tLaserSceneNode::LaserRenderNode::render()\n{\n const GLfloat length = sceneNode->length;\n const GLfloat* sphere = sceneNode->getSphere();\n glPushMatrix();\n glTranslatef(sphere[0], sphere[1], sphere[2]);\n glRotatef(sceneNode->azimuth, 0.0f, 0.0f, 1.0f);\n glRotatef(sceneNode->elevation, 0.0f, 1.0f, 0.0f);\n\n if (sceneNode->texturing) {\n myColor3f(1.0f, 1.0f, 1.0f);\n glBegin(GL_TRIANGLE_FAN);\n\tglTexCoord2f(0.5f, 0.5f);\n\tglVertex3f( 0.0f, 0.0f, 0.0f);\n\tglTexCoord2f(0.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, 1.0f);\n\tglVertex3f( 0.0f, 1.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, -1.0f);\n\tglVertex3f( 0.0f, -1.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, 1.0f);\n glEnd();\n\n glBegin(GL_QUADS);\n\tglTexCoord2f(0.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, 1.0f);\n\tglTexCoord2f(0.0f, 1.0f);\n\tglVertex3f(length, 0.0f, 1.0f);\n\tglTexCoord2f(1.0f, 1.0f);\n\tglVertex3f(length, 0.0f, -1.0f);\n\tglTexCoord2f(1.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, -1.0f);\n\n\tglTexCoord2f(0.0f, 0.0f);\n\tglVertex3f( 0.0f, 1.0f, 0.0f);\n\tglTexCoord2f(0.0f, 1.0f);\n\tglVertex3f(length, 1.0f, 0.0f);\n\tglTexCoord2f(1.0f, 1.0f);\n\tglVertex3f(length, -1.0f, 0.0f);\n\tglTexCoord2f(1.0f, 0.0f);\n\tglVertex3f( 0.0f, -1.0f, 0.0f);\n glEnd();\n }\n\n else {\n \/\/ draw beam\n myColor4f(1.0f, 0.25f, 0.0f, 0.85f);\n glBegin(GL_QUAD_STRIP);\n\tglVertex3f( 0.0f, geom[0][0], geom[0][1]);\n\tglVertex3f(length, geom[0][0], geom[0][1]);\n\tglVertex3f( 0.0f, geom[1][0], geom[1][1]);\n\tglVertex3f(length, geom[1][0], geom[1][1]);\n\tglVertex3f( 0.0f, geom[2][0], geom[2][1]);\n\tglVertex3f(length, geom[2][0], geom[2][1]);\n\tglVertex3f( 0.0f, geom[3][0], geom[3][1]);\n\tglVertex3f(length, geom[3][0], geom[3][1]);\n\tglVertex3f( 0.0f, geom[4][0], geom[4][1]);\n\tglVertex3f(length, geom[4][0], geom[4][1]);\n\tglVertex3f( 0.0f, geom[5][0], geom[5][1]);\n\tglVertex3f(length, geom[5][0], geom[5][1]);\n\tglVertex3f( 0.0f, geom[0][0], geom[0][1]);\n\tglVertex3f(length, geom[0][0], geom[0][1]);\n glEnd();\n\n \/\/ also draw a line down the middle (so the beam is visible even\n \/\/ if very far away). this will also give the beam an extra bright\n \/\/ center.\n glBegin(GL_LINES);\n\tglVertex3f( 0.0f, 0.0f, 0.0f);\n\tglVertex3f(length, 0.0f, 0.0f);\n glEnd();\n }\n\n glPopMatrix();\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<commit_msg>warnings cleanup<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ bzflag common header\n#include \"common.h\"\n\n\/\/ interface header\n#include \"LaserSceneNode.h\"\n\n\/\/ system headers\n#include <math.h>\n\n\/\/ common implementation headers\n#include \"StateDatabase.h\"\n#include \"BZDBCache.h\"\n\n\/\/ FIXME (SceneRenderer.cxx is in src\/bzflag)\n#include \"SceneRenderer.h\"\n\nconst GLfloat\t\tLaserRadius = 0.1f;\n\nLaserSceneNode::LaserSceneNode(const GLfloat pos[3], const GLfloat forward[3]) :\n\t\t\t\ttexturing(false),\n\t\t\t\trenderNode(this)\n{\n \/\/ prepare rendering info\n azimuth = (float)(180.0 \/ M_PI*atan2f(forward[1], forward[0]));\n elevation = (float)(-180.0 \/ M_PI*atan2f(forward[2], hypotf(forward[0],forward[1])));\n length = hypotf(forward[0], hypotf(forward[1], forward[2]));\n\n \/\/ setup sphere\n setCenter(pos);\n setRadius(length * length);\n\n OpenGLGStateBuilder builder(gstate);\n builder.setCulling(GL_NONE);\n gstate = builder.getState();\n}\n\nLaserSceneNode::~LaserSceneNode()\n{\n \/\/ do nothing\n}\n\nvoid\t\t\tLaserSceneNode::setTexture(const int texture)\n{\n OpenGLGStateBuilder builder(gstate);\n builder.setTexture(texture);\n builder.enableTexture(texture>=0);\n gstate = builder.getState();\n}\n\nbool\t\t\tLaserSceneNode::cull(const ViewFrustum&) const\n{\n \/\/ no culling\n return false;\n}\n\nvoid\t\t\tLaserSceneNode::notifyStyleChange()\n{\n texturing = BZDBCache::texture && BZDBCache::blend;\n OpenGLGStateBuilder builder(gstate);\n builder.enableTexture(texturing);\n if (BZDBCache::blend) {\n \/\/ add in contribution from laser\n builder.setBlending(GL_SRC_ALPHA, GL_ONE);\n builder.setSmoothing(BZDB.isTrue(\"smooth\"));\n }\n else {\n builder.resetBlending();\n builder.setSmoothing(false);\n }\n gstate = builder.getState();\n}\n\nvoid\t\t\tLaserSceneNode::addRenderNodes(\n\t\t\t\tSceneRenderer& renderer)\n{\n renderer.addRenderNode(&renderNode, &gstate);\n}\n\n\/\/\n\/\/ LaserSceneNode::LaserRenderNode\n\/\/\n\nGLfloat\t\t\tLaserSceneNode::LaserRenderNode::geom[6][2];\n\nLaserSceneNode::LaserRenderNode::LaserRenderNode(\n\t\t\t\tconst LaserSceneNode* _sceneNode) :\n\t\t\t\tsceneNode(_sceneNode)\n{\n \/\/ initialize geometry if first instance\n static bool init = false;\n if (!init) {\n init = true;\n for (int i = 0; i < 6; i++) {\n geom[i][0] = -LaserRadius * cosf((float)(2.0 * M_PI * double(i) \/ 6.0));\n geom[i][1] = LaserRadius * sinf((float)(2.0 * M_PI * double(i) \/ 6.0));\n }\n }\n}\n\nLaserSceneNode::LaserRenderNode::~LaserRenderNode()\n{\n \/\/ do nothing\n}\n\nvoid\t\t\tLaserSceneNode::LaserRenderNode::render()\n{\n const GLfloat length = sceneNode->length;\n const GLfloat* sphere = sceneNode->getSphere();\n glPushMatrix();\n glTranslatef(sphere[0], sphere[1], sphere[2]);\n glRotatef(sceneNode->azimuth, 0.0f, 0.0f, 1.0f);\n glRotatef(sceneNode->elevation, 0.0f, 1.0f, 0.0f);\n\n if (sceneNode->texturing) {\n myColor3f(1.0f, 1.0f, 1.0f);\n glBegin(GL_TRIANGLE_FAN);\n\tglTexCoord2f(0.5f, 0.5f);\n\tglVertex3f( 0.0f, 0.0f, 0.0f);\n\tglTexCoord2f(0.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, 1.0f);\n\tglVertex3f( 0.0f, 1.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, -1.0f);\n\tglVertex3f( 0.0f, -1.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, 1.0f);\n glEnd();\n\n glBegin(GL_QUADS);\n\tglTexCoord2f(0.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, 1.0f);\n\tglTexCoord2f(0.0f, 1.0f);\n\tglVertex3f(length, 0.0f, 1.0f);\n\tglTexCoord2f(1.0f, 1.0f);\n\tglVertex3f(length, 0.0f, -1.0f);\n\tglTexCoord2f(1.0f, 0.0f);\n\tglVertex3f( 0.0f, 0.0f, -1.0f);\n\n\tglTexCoord2f(0.0f, 0.0f);\n\tglVertex3f( 0.0f, 1.0f, 0.0f);\n\tglTexCoord2f(0.0f, 1.0f);\n\tglVertex3f(length, 1.0f, 0.0f);\n\tglTexCoord2f(1.0f, 1.0f);\n\tglVertex3f(length, -1.0f, 0.0f);\n\tglTexCoord2f(1.0f, 0.0f);\n\tglVertex3f( 0.0f, -1.0f, 0.0f);\n glEnd();\n }\n\n else {\n \/\/ draw beam\n myColor4f(1.0f, 0.25f, 0.0f, 0.85f);\n glBegin(GL_QUAD_STRIP);\n\tglVertex3f( 0.0f, geom[0][0], geom[0][1]);\n\tglVertex3f(length, geom[0][0], geom[0][1]);\n\tglVertex3f( 0.0f, geom[1][0], geom[1][1]);\n\tglVertex3f(length, geom[1][0], geom[1][1]);\n\tglVertex3f( 0.0f, geom[2][0], geom[2][1]);\n\tglVertex3f(length, geom[2][0], geom[2][1]);\n\tglVertex3f( 0.0f, geom[3][0], geom[3][1]);\n\tglVertex3f(length, geom[3][0], geom[3][1]);\n\tglVertex3f( 0.0f, geom[4][0], geom[4][1]);\n\tglVertex3f(length, geom[4][0], geom[4][1]);\n\tglVertex3f( 0.0f, geom[5][0], geom[5][1]);\n\tglVertex3f(length, geom[5][0], geom[5][1]);\n\tglVertex3f( 0.0f, geom[0][0], geom[0][1]);\n\tglVertex3f(length, geom[0][0], geom[0][1]);\n glEnd();\n\n \/\/ also draw a line down the middle (so the beam is visible even\n \/\/ if very far away). this will also give the beam an extra bright\n \/\/ center.\n glBegin(GL_LINES);\n\tglVertex3f( 0.0f, 0.0f, 0.0f);\n\tglVertex3f(length, 0.0f, 0.0f);\n glEnd();\n }\n\n glPopMatrix();\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*! @file\r\n\t@brief Emulator Tools クラス @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n\t@author 平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"widgets\/widget_terminal.hpp\"\r\n\r\n#include \"emu\/cpu\/nes6502.h\"\r\n\r\n#include \"emu\/cpu\/dis6502.hpp\"\r\n\r\nnamespace emu {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief\tエミュレーター Tools クラス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass tools {\r\n\r\n\t\tstatic gui::widget_terminal*\tterminal_;\r\n\r\n\t\tcpu::dis6502\tdis_;\r\n\r\n\t\tuint16_t\tdisasm_org_;\r\n\t\tuint16_t\tdump_org_;\r\n\r\n\t\tuint16_t\tadr_;\r\n\t\tuint16_t \tncnt_;\r\n\r\n\t\tbool\t\tenable_;\r\n\r\n\t\tvoid dump_() {\r\n\t\t\tif(ncnt_ > 0) { dump_org_ = adr_; adr_ = 0; ncnt_ = 0; }\r\n\t\t\tstd::string list = dis_.dump(dump_org_);\r\n\t\t\tterminal_->output(list + \"\\n\"); \r\n\t\t\t++dump_org_;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttools() : disasm_org_(0), dump_org_(0), adr_(0), ncnt_(0), enable_(false) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ターミナル・コンテキストを設定\r\n\t\t\t@param[in]\tterm\tターミナル・コンテキスト\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic void set_terminal(gui::widget_terminal* t) {\r\n\t\t\tterminal_ = t;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 出力\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic void put(const char* text) {\r\n\t\t\tif(terminal_ == nullptr) return;\r\n\t\t\tterminal_->output(text);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 初期化\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid init()\r\n\t\t{\r\n\t\t\tdis_.at_getbyte() = nes6502_getbyte;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 許可\r\n\t\t\t@param[in]\tf\t不許可なら「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid enable(bool f = true) { enable_ = f; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コマンド\r\n\t\t\t@param[in]\tcmd\tコマンド\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid command(const std::string& cmd)\r\n\t\t{\r\n\t\t\tif(cmd == \"state\") {\r\n\t\t\t\tif(enable_) {\r\n\t\t\t\t\tterminal_->output(\"ROM active\\n\");\r\n\t\t\t\t} else {\r\n\t\t\t\t\tterminal_->output(\"ROM not active\\n\"); \r\n\t\t\t\t}\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tif(!enable_) return;\r\n\r\n\t\t\tadr_ = 0;\r\n\t\t\tncnt_ = 0;\r\n\t\t\tbool dump = true;\r\n\t\t\tfor(char ch : cmd) {\r\n\t\t\t\tif(ch == ' ') {\r\n\t\t\t\t\tdump_();\r\n\t\t\t\t} else if(ch >= '0' && ch <= '9') {\r\n\t\t\t\t\tadr_ <<= 4;\r\n\t\t\t\t\tadr_ += ch - '0';\r\n\t\t\t\t\t++ncnt_;\r\n\t\t\t\t} else if(ch >= 'A' && ch <= 'F') {\r\n\t\t\t\t\tadr_ <<= 4;\r\n\t\t\t\t\tadr_ += ch - 'A' + 10;\r\n\t\t\t\t\t++ncnt_;\r\n\t\t\t\t} else if(ch >= 'a' && ch <= 'f') {\r\n\t\t\t\t\tadr_ <<= 4;\r\n\t\t\t\t\tadr_ += ch - 'a' + 10;\r\n\t\t\t\t\t++ncnt_;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(ch == 'l' || ch == 'L') {\r\n\t\t\t\t\t\tif(ncnt_ > 0) { disasm_org_ = adr_; adr_ = 0; ncnt_ = 0; }\r\n\t\t\t\t\t\tfor(int i = 0; i < 16; ++i) {\r\n\t\t\t\t\t\t\tstd::string list = dis_.disasm(disasm_org_);\r\n\t\t\t\t\t\t\tterminal_->output(list + \"\\n\"); \r\n\t\t\t\t\t\t\tdisasm_org_ = dis_.get_pc();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tstd::string s;\r\n\t\t\t\t\t\ts = \"Command error: '\";\r\n\t\t\t\t\t\tterminal_->output(s + ch + \"'\\n\"); \r\n\t\t\t\t\t}\r\n\t\t\t\t\tdump = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(dump) {\r\n\t\t\t\tdump_();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ツール・サービス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid service()\r\n\t\t{\r\n\t\t}\r\n\t};\r\n}\r\n<commit_msg>update<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*! @file\r\n\t@brief Emulator Tools クラス @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n\t@author 平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"widgets\/widget_terminal.hpp\"\r\n\r\n#include \"emu\/cpu\/nes6502.h\"\r\n\r\n#include \"emu\/cpu\/dis6502.hpp\"\r\n#include \"emu\/cpu\/nes6502.hpp\"\r\n\r\nnamespace emu {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief\tエミュレーター Tools クラス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass tools {\r\n\r\n\t\tstatic gui::widget_terminal*\tterminal_;\r\n\r\n\t\tcpu::dis6502\tdis_;\r\n\r\n\t\tuint16_t\tdisasm_org_;\r\n\t\tuint16_t\tdump_org_;\r\n\r\n\t\tuint16_t\tadr_;\r\n\t\tuint16_t \tncnt_;\r\n\r\n\t\tbool\t\tenable_;\r\n\r\n\t\tvoid dump_() {\r\n\t\t\tif(ncnt_ > 0) { dump_org_ = adr_; adr_ = 0; ncnt_ = 0; }\r\n\t\t\tstd::string list = dis_.dump(dump_org_);\r\n\t\t\tterminal_->output(list + \"\\n\"); \r\n\t\t\t++dump_org_;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttools() : disasm_org_(0), dump_org_(0), adr_(0), ncnt_(0), enable_(false) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ターミナル・コンテキストを設定\r\n\t\t\t@param[in]\tterm\tターミナル・コンテキスト\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic void set_terminal(gui::widget_terminal* t) {\r\n\t\t\tterminal_ = t;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 出力\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic void put(const char* text) {\r\n\t\t\tif(terminal_ == nullptr) return;\r\n\t\t\tterminal_->output(text);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 初期化\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid init()\r\n\t\t{\r\n\t\t\tdis_.at_getbyte() = nes6502_getbyte;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 許可\r\n\t\t\t@param[in]\tf\t不許可なら「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid enable(bool f = true) { enable_ = f; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コマンド\r\n\t\t\t@param[in]\tcmd\tコマンド\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid command(const std::string& cmd)\r\n\t\t{\r\n\t\t\tif(cmd == \"state\") {\r\n\t\t\t\tif(enable_) {\r\n\t\t\t\t\tterminal_->output(\"ROM active\\n\");\r\n\t\t\t\t} else {\r\n\t\t\t\t\tterminal_->output(\"ROM not active\\n\"); \r\n\t\t\t\t}\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tif(!enable_) return;\r\n\r\n\t\t\tadr_ = 0;\r\n\t\t\tncnt_ = 0;\r\n\t\t\tbool dump = true;\r\n\t\t\tfor(char ch : cmd) {\r\n\t\t\t\tif(ch == ' ') {\r\n\t\t\t\t\tdump_();\r\n\t\t\t\t} else if(ch >= '0' && ch <= '9') {\r\n\t\t\t\t\tadr_ <<= 4;\r\n\t\t\t\t\tadr_ += ch - '0';\r\n\t\t\t\t\t++ncnt_;\r\n\t\t\t\t} else if(ch >= 'A' && ch <= 'F') {\r\n\t\t\t\t\tadr_ <<= 4;\r\n\t\t\t\t\tadr_ += ch - 'A' + 10;\r\n\t\t\t\t\t++ncnt_;\r\n\t\t\t\t} else if(ch >= 'a' && ch <= 'f') {\r\n\t\t\t\t\tadr_ <<= 4;\r\n\t\t\t\t\tadr_ += ch - 'a' + 10;\r\n\t\t\t\t\t++ncnt_;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(ch == 'l' || ch == 'L') {\r\n\t\t\t\t\t\tif(ncnt_ > 0) { disasm_org_ = adr_; adr_ = 0; ncnt_ = 0; }\r\n\t\t\t\t\t\tfor(int i = 0; i < 16; ++i) {\r\n\t\t\t\t\t\t\tstd::string list = dis_.disasm(disasm_org_);\r\n\t\t\t\t\t\t\tterminal_->output(list + \"\\n\"); \r\n\t\t\t\t\t\t\tdisasm_org_ = dis_.get_pc();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tstd::string s;\r\n\t\t\t\t\t\ts = \"Command error: '\";\r\n\t\t\t\t\t\tterminal_->output(s + ch + \"'\\n\"); \r\n\t\t\t\t\t}\r\n\t\t\t\t\tdump = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(dump) {\r\n\t\t\t\tdump_();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ツール・サービス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid service()\r\n\t\t{\r\n\t\t}\r\n\t};\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"dynet\/io.h\"\n#include \"dynet\/tensor.h\"\n#include \"dynet\/except.h\"\n\nusing namespace std;\nusing namespace dynet;\n\nbool valid_key(const std::string & s) {\n if (s == \"\/\") return false;\n auto it = std::find_if(s.begin(), s.end(),\n [] (char ch) { return ch == ' ' || ch == '#';});\n return it == s.end();\n}\n\nTextFileSaver::TextFileSaver(const string & filename, bool append) :\n datastream(filename, append ? ofstream::app : ofstream::out) {\n if(!datastream)\n DYNET_RUNTIME_ERR(\"Could not write model to \" << filename);\n}\n\nvoid TextFileSaver::save(const ParameterCollection & model,\n const string & key) {\n if (!valid_key(key)) \n DYNET_INVALID_ARG(\"Key could not include ' ' or '#': \" << key);\n const ParameterCollectionStorage & storage = model.get_storage();\n if(key.size() == 0) {\n for (auto & p : storage.params) save(*p, key);\n for (auto & p : storage.lookup_params) save(*p, key);\n } else {\n size_t strip_size = model.get_fullname().size();\n for (auto & p : storage.params) \n save(*p, key + p->name.substr(strip_size));\n for (auto & p : storage.lookup_params) \n save(*p, key + p->name.substr(strip_size));\n }\n}\n\nvoid TextFileSaver::save(const Parameter & param,\n const string & key) {\n if (!valid_key(key))\n DYNET_INVALID_ARG(\"Key could not include ' ' or '#': \" << key);\n save(*param.p, key);\n}\n\nvoid TextFileSaver::save(const LookupParameter & param,\n const string & key) {\n if (!valid_key(key))\n DYNET_INVALID_ARG(\"Key could not include ' ' or '#': \" << key);\n save(*param.p, key);\n}\n\nvoid TextFileSaver::save(const ParameterStorage & p,\n const string & key) {\n std::ostringstream buffer;\n buffer << dynet::as_vector(p.values) << endl;\n buffer << dynet::as_vector(p.g) << endl;\n datastream << \"#Parameter# \" << (key.size() > 0 ? key : p.name) << ' '\n << p.dim << ' ' << buffer.str().size() << endl;\n datastream.write(buffer.str().c_str(), buffer.str().size());\n}\n\nvoid TextFileSaver::save(const LookupParameterStorage & p,\n const string & key) {\n std::ostringstream buffer;\n buffer << dynet::as_vector(p.all_values) << endl;\n buffer << dynet::as_vector(p.all_grads) << endl;\n datastream << \"#LookupParameter# \" << (key.size() > 0 ? key : p.name) << ' ' << p.all_dim << ' ' << buffer.str().size() << endl;\n datastream.write(buffer.str().c_str(), buffer.str().size());\n}\n\nTextFileLoader::TextFileLoader(const string & filename) :\n dataname(filename) { }\n\nvoid TextFileLoader::populate(ParameterCollection & model, const string & key) {\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n vector<float> values;\n Tensor *value_t, *grad_t;\n size_t param_id = 0, lookup_id = 0;\n ParameterCollectionStorage & storage = model.get_storage();\n string key_ = key;\n if (key_.back() != '\/') key_ += \"\/\";\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n \/\/ Skip ones that don't match\n if(key.size() != 0 && name.substr(0, key_.size()) != key_) {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n continue;\n \/\/ Load a parameter\n } else if(type == \"#Parameter#\") {\n values.resize(dim.size());\n if(param_id >= storage.params.size())\n DYNET_RUNTIME_ERR(\"Too many parameters to load in populated model at \" << name);\n ParameterStorage & param = *storage.params[param_id++];\n if(param.dim != dim)\n DYNET_RUNTIME_ERR(\"Dimensions of parameter \" << name << \" looked up from file (\" << dim << \n \") do not match parameters to be populated (\" << param.dim << \")\");\n value_t = ¶m.values;\n grad_t = ¶m.g;\n \/\/ Load a lookup parameter\n } else if(type == \"#LookupParameter#\") {\n values.resize(dim.size());\n if(lookup_id >= storage.lookup_params.size())\n DYNET_RUNTIME_ERR(\"Too many lookup parameters in populated model at \" << name);\n LookupParameterStorage & param = *storage.lookup_params[lookup_id++];\n if(param.all_dim != dim)\n DYNET_RUNTIME_ERR(\"Dimensions of lookup parameter \" << name << \" lookup up from file (\" << dim << \n \") do not match parameters to be populated (\" << param.all_dim << \")\");\n value_t = ¶m.all_values;\n grad_t = ¶m.all_grads;\n } else {\n DYNET_RUNTIME_ERR(\"Bad parameter specification in model: \" << line);\n }\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(*value_t, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(*grad_t, values);\n }\n if(param_id != storage.params.size() || lookup_id != storage.lookup_params.size())\n DYNET_RUNTIME_ERR(\"Number of parameter\/lookup parameter objects loaded from file (\" << \n param_id << '\/' << lookup_id << \") did not match number to be populated (\" <<\n storage.params.size() << '\/' << storage.lookup_params.size() << ')');\n}\n\nvoid TextFileLoader::populate(Parameter & param,\n const string & key) {\n if(key == \"\")\n DYNET_INVALID_ARG(\"TextFileLoader.populate() requires non-empty key\");\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n if(type == \"#Parameter#\" && name == key) {\n if(param.p->dim != dim)\n DYNET_RUNTIME_ERR(\"Attempted to populate parameter where arguments don't match (\" << param.p->dim << \" != \" << dim << \")\");\n vector<float> values(dim.size());\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(param.get_storage().values, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(param.get_storage().g, values);\n return;\n } else {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n }\n }\n DYNET_RUNTIME_ERR(\"Could not find key \" << key << \" in the model file\");\n}\n\nvoid TextFileLoader::populate(LookupParameter & lookup_param,\n const string & key) {\n if(key == \"\")\n DYNET_INVALID_ARG(\"TextFileLoader.populate() requires non-empty key\");\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n if(type == \"#LookupParameter#\" && name == key) {\n if(lookup_param.p->all_dim != dim)\n DYNET_RUNTIME_ERR(\"Attempted to populate lookup parameter where arguments don't match (\" << lookup_param.p->all_dim << \" != \" << dim << \")\");\n vector<float> values(dim.size());\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(lookup_param.get_storage().all_values, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(lookup_param.get_storage().all_grads, values);\n return;\n } else {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n }\n }\n DYNET_RUNTIME_ERR(\"Could not find key \" << key << \" in the model file\");\n}\n\nParameter TextFileLoader::load_param(ParameterCollection & model,\n const string & key) {\n if(key == \"\")\n DYNET_INVALID_ARG(\"TextFileLoader.load_param() requires non-empty key\");\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n if(type == \"#Parameter#\" && name == key) {\n Parameter param = model.add_parameters(dim);\n param.get_storage().name = name;\n vector<float> values(dim.size());\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(param.get_storage().values, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(param.get_storage().g, values);\n return param;\n } else {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n }\n }\n DYNET_RUNTIME_ERR(\"Could not find key \" << key << \" in the model file\");\n}\n\nLookupParameter TextFileLoader::load_lookup_param(ParameterCollection & model,\n const string & key) {\n if(key == \"\")\n DYNET_INVALID_ARG(\"TextFileLoader.load_lookup_param() requires non-empty key\");\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n if(type == \"#LookupParameter#\" && name == key) {\n vector<float> values(dim.size());\n size_t size = dim[dim.nd-1]; dim.nd--;\n LookupParameter lookup_param = model.add_lookup_parameters(size, dim);\n lookup_param.get_storage().name = name;\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(lookup_param.get_storage().all_values, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(lookup_param.get_storage().all_grads, values);\n return lookup_param;\n } else {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n }\n }\n DYNET_RUNTIME_ERR(\"Could not find key \" << key << \" in the model file\");\n}\n<commit_msg>add key check for ParameterCollection<commit_after>#include \"dynet\/io.h\"\n#include \"dynet\/tensor.h\"\n#include \"dynet\/except.h\"\n#include \"dynet\/str-util.h\"\n\nusing namespace std;\nusing namespace dynet;\n\nbool valid_key(const std::string & s) {\n if (s.size() == 0) return true;\n if (s == \"\/\") return false;\n auto it = std::find_if(s.begin(), s.end(),\n [] (char ch) { return ch == ' ' || ch == '#';});\n return it == s.end();\n}\n\nbool valid_pc_key(const std::string & s) {\n if (s.size() == 0) return true;\n if (!(startswith(s, \"\/\") && endswith(s, \"\/\"))) return false;\n return valid_key(s);\n}\n\nTextFileSaver::TextFileSaver(const string & filename, bool append) :\n datastream(filename, append ? ofstream::app : ofstream::out) {\n if(!datastream)\n DYNET_RUNTIME_ERR(\"Could not write model to \" << filename);\n}\n\nvoid TextFileSaver::save(const ParameterCollection & model,\n const string & key) {\n if (!valid_pc_key(key))\n DYNET_INVALID_ARG(\"Key should start with, end with '\/' and could not include ' ' or '#': \" << key);\n const ParameterCollectionStorage & storage = model.get_storage();\n if(key.size() == 0) {\n for (auto & p : storage.params) save(*p, key);\n for (auto & p : storage.lookup_params) save(*p, key);\n } else {\n size_t strip_size = model.get_fullname().size();\n for (auto & p : storage.params) \n save(*p, key + p->name.substr(strip_size));\n for (auto & p : storage.lookup_params) \n save(*p, key + p->name.substr(strip_size));\n }\n}\n\nvoid TextFileSaver::save(const Parameter & param,\n const string & key) {\n if (!valid_key(key))\n DYNET_INVALID_ARG(\"Key could not include ' ' or '#': \" << key);\n save(*param.p, key);\n}\n\nvoid TextFileSaver::save(const LookupParameter & param,\n const string & key) {\n if (!valid_key(key))\n DYNET_INVALID_ARG(\"Key could not include ' ' or '#': \" << key);\n save(*param.p, key);\n}\n\nvoid TextFileSaver::save(const ParameterStorage & p,\n const string & key) {\n std::ostringstream buffer;\n buffer << dynet::as_vector(p.values) << endl;\n buffer << dynet::as_vector(p.g) << endl;\n datastream << \"#Parameter# \" << (key.size() > 0 ? key : p.name) << ' '\n << p.dim << ' ' << buffer.str().size() << endl;\n datastream.write(buffer.str().c_str(), buffer.str().size());\n}\n\nvoid TextFileSaver::save(const LookupParameterStorage & p,\n const string & key) {\n std::ostringstream buffer;\n buffer << dynet::as_vector(p.all_values) << endl;\n buffer << dynet::as_vector(p.all_grads) << endl;\n datastream << \"#LookupParameter# \" << (key.size() > 0 ? key : p.name) << ' ' << p.all_dim << ' ' << buffer.str().size() << endl;\n datastream.write(buffer.str().c_str(), buffer.str().size());\n}\n\nTextFileLoader::TextFileLoader(const string & filename) :\n dataname(filename) { }\n\nvoid TextFileLoader::populate(ParameterCollection & model, const string & key) {\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n vector<float> values;\n Tensor *value_t, *grad_t;\n size_t param_id = 0, lookup_id = 0;\n ParameterCollectionStorage & storage = model.get_storage();\n string key_ = key;\n if (key_.back() != '\/') key_ += \"\/\";\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n \/\/ Skip ones that don't match\n if(key.size() != 0 && name.substr(0, key_.size()) != key_) {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n continue;\n \/\/ Load a parameter\n } else if(type == \"#Parameter#\") {\n values.resize(dim.size());\n if(param_id >= storage.params.size())\n DYNET_RUNTIME_ERR(\"Too many parameters to load in populated model at \" << name);\n ParameterStorage & param = *storage.params[param_id++];\n if(param.dim != dim)\n DYNET_RUNTIME_ERR(\"Dimensions of parameter \" << name << \" looked up from file (\" << dim << \n \") do not match parameters to be populated (\" << param.dim << \")\");\n value_t = ¶m.values;\n grad_t = ¶m.g;\n \/\/ Load a lookup parameter\n } else if(type == \"#LookupParameter#\") {\n values.resize(dim.size());\n if(lookup_id >= storage.lookup_params.size())\n DYNET_RUNTIME_ERR(\"Too many lookup parameters in populated model at \" << name);\n LookupParameterStorage & param = *storage.lookup_params[lookup_id++];\n if(param.all_dim != dim)\n DYNET_RUNTIME_ERR(\"Dimensions of lookup parameter \" << name << \" lookup up from file (\" << dim << \n \") do not match parameters to be populated (\" << param.all_dim << \")\");\n value_t = ¶m.all_values;\n grad_t = ¶m.all_grads;\n } else {\n DYNET_RUNTIME_ERR(\"Bad parameter specification in model: \" << line);\n }\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(*value_t, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(*grad_t, values);\n }\n if(param_id != storage.params.size() || lookup_id != storage.lookup_params.size())\n DYNET_RUNTIME_ERR(\"Number of parameter\/lookup parameter objects loaded from file (\" << \n param_id << '\/' << lookup_id << \") did not match number to be populated (\" <<\n storage.params.size() << '\/' << storage.lookup_params.size() << ')');\n}\n\nvoid TextFileLoader::populate(Parameter & param,\n const string & key) {\n if(key == \"\")\n DYNET_INVALID_ARG(\"TextFileLoader.populate() requires non-empty key\");\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n if(type == \"#Parameter#\" && name == key) {\n if(param.p->dim != dim)\n DYNET_RUNTIME_ERR(\"Attempted to populate parameter where arguments don't match (\" << param.p->dim << \" != \" << dim << \")\");\n vector<float> values(dim.size());\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(param.get_storage().values, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(param.get_storage().g, values);\n return;\n } else {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n }\n }\n DYNET_RUNTIME_ERR(\"Could not find key \" << key << \" in the model file\");\n}\n\nvoid TextFileLoader::populate(LookupParameter & lookup_param,\n const string & key) {\n if(key == \"\")\n DYNET_INVALID_ARG(\"TextFileLoader.populate() requires non-empty key\");\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n if(type == \"#LookupParameter#\" && name == key) {\n if(lookup_param.p->all_dim != dim)\n DYNET_RUNTIME_ERR(\"Attempted to populate lookup parameter where arguments don't match (\" << lookup_param.p->all_dim << \" != \" << dim << \")\");\n vector<float> values(dim.size());\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(lookup_param.get_storage().all_values, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(lookup_param.get_storage().all_grads, values);\n return;\n } else {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n }\n }\n DYNET_RUNTIME_ERR(\"Could not find key \" << key << \" in the model file\");\n}\n\nParameter TextFileLoader::load_param(ParameterCollection & model,\n const string & key) {\n if(key == \"\")\n DYNET_INVALID_ARG(\"TextFileLoader.load_param() requires non-empty key\");\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n if(type == \"#Parameter#\" && name == key) {\n Parameter param = model.add_parameters(dim);\n param.get_storage().name = name;\n vector<float> values(dim.size());\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(param.get_storage().values, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(param.get_storage().g, values);\n return param;\n } else {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n }\n }\n DYNET_RUNTIME_ERR(\"Could not find key \" << key << \" in the model file\");\n}\n\nLookupParameter TextFileLoader::load_lookup_param(ParameterCollection & model,\n const string & key) {\n if(key == \"\")\n DYNET_INVALID_ARG(\"TextFileLoader.load_lookup_param() requires non-empty key\");\n ifstream datastream(dataname);\n if(!datastream) DYNET_RUNTIME_ERR(\"Could not read model from \" << dataname);\n string line, type, name;\n Dim dim;\n size_t byte_count = 0;\n while(getline(datastream, line)) {\n { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }\n if(type == \"#LookupParameter#\" && name == key) {\n vector<float> values(dim.size());\n size_t size = dim[dim.nd-1]; dim.nd--;\n LookupParameter lookup_param = model.add_lookup_parameters(size, dim);\n lookup_param.get_storage().name = name;\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(lookup_param.get_storage().all_values, values);\n { getline(datastream, line); istringstream iss(line); iss >> values; }\n TensorTools::set_elements(lookup_param.get_storage().all_grads, values);\n return lookup_param;\n } else {\n size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;\n datastream.seekg(offset);\n }\n }\n DYNET_RUNTIME_ERR(\"Could not find key \" << key << \" in the model file\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (C) 2014 GraphLab Inc.\n * All rights reserved.\n *\n * This software may be modified and distributed under the terms\n * of the BSD license. See the LICENSE file for details.\n *\/\n\n#ifndef GRAPHLAB_UNITY_GL_GFRAME_HPP\n#define GRAPHLAB_UNITY_GL_GFRAME_HPP\n\n#include \"gl_sframe.hpp\"\n\nnamespace graphlab {\nclass gl_sframe;\nclass gl_sgraph;\nclass gl_sarray;\n\n\/\/ Possible types of gl_gframe\nenum class gframe_type_enum:int {VERTEX_GFRAME, EDGE_GFRAME};\n\n\/**\n * \\ingroup gl_sdk\n *\n * A proxy for the \\ref gl_sframe for the vertex and edge data of the SGRaph\n *\/\nclass gl_gframe : public gl_sframe {\n public:\n gl_gframe() = delete;\n gl_gframe(const gl_gframe&) = default;\n gl_gframe(gl_gframe&&) = default;\n gl_gframe& operator=(const gl_gframe&) = default;\n gl_gframe& operator=(gl_gframe&&) = default;\n\n \/*\n * Construct gl_gframe from sgraph, and sframe.\n *\/\n gl_gframe(gl_sgraph*, gframe_type_enum);\n\n \/*\n * Implicit converters\n *\/\n operator gl_sframe() const;\n operator std::shared_ptr<unity_sframe>() const;\n operator std::shared_ptr<unity_sframe_base>() const;\n\n \/**\n * Returns number of rows. If type is VERTEX_GFRAME, the value\n * is also the number of vertices (or edges if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\n * \\see gl_sgraph::num_vertices\n * \\see gl_sgraph::num_edges\n *\/\n size_t size() const override;\n\n \/**\n * Returns number of columns. If type is VERTEX_GFRAME, the value\n * is also the number of vertex fields (or edge fields if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\/\n size_t num_columns() const override;\n\n \/**\n * Returns a list of column names. If type is VERTEX_GFRAME, the value\n * is also the names of the vertex fields (or edge fields if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\n * \\see gl_sgraph::get_vertex_fields\n * \\see gl_sgraph::get_edge_fields\n *\/\n std::vector<std::string> column_names() const override;\n\n \/**\n * Returns a list of column types. If type is VERTEX_GFRAME, the value\n * is also the names of the vertex fields (or edge fields if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\n * \\see gl_sgraph::get_vertex_field_types\n * \\see gl_sgraph::get_edge_field_types\n *\/\n std::vector<flex_type_enum> column_types() const override;\n\n \/**\n * Add a new column with constant value. If type is VERTEX_GFRAME, the column\n * is added as a new vertex field (or edge field if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\n * \\param data the constant value to fill the column\n * \\param name the name of the new column\n *\n * \\see gl_sgraph::add_vertex_field(const flexible_type&, const std::string&)\n * \\see gl_sgraph::add_edge_field(const flexible_type&, const std::stirng&)\n *\/\n void add_column(const flexible_type& data, const std::string& name) override;\n\n \/**\n * Add a new column with given column name and data. If type is\n * VERTEX_GFRAME, the column is added as a new vertex field (or edge field if\n * type is EDGE_GFRAME) in the \\ref gl_sgraph.\n *\n * \\param data the constant value to fill the column\n * \\param name the name of the new column\n *\n * \\see gl_sgraph::add_vertex_field(const gl_sarray&, const std::string&)\n * \\see gl_sgraph::add_edge_field(const gl_sarray&, const std::string&)\n *\/\n void add_column(const gl_sarray& data, const std::string& name) override;\n\n \/**\n * Batch version of \\ref add_column.\n *\n * \\param data a map from column name to column data\n *\/\n void add_columns(const gl_sframe& data) override;\n\n \/**\n * Remove a column with the given name. If type is\n * VERTEX_GFRAME, the column is removed from vertex data (or edge data if\n * type is EDGE_GFRAME) from the \\ref gl_sgraph.\n *\n * \\param name the column name to be removed\n *\n * \\see gl_sgraph::remove_vertex_field\n * \\see gl_sgraph::remove_edge_field\n *\/\n void remove_column(const std::string& name) override;\n\n \/**\n * Rename columns.\n *\n * \\param old_to_new_names map from old column name to new column name.\n *\n * \\see gl_sgraph::rename_vertex_fields\n * \\see gl_sgraph::rename_edge_fields\n *\/\n void rename(const std::map<std::string, std::string>& old_to_new_names) override;\n\n \/**\n * Swap the order of two columns\n *\/\n void swap_columns(const std::string& column_1, const std::string& column_2) override;\n\n virtual std::shared_ptr<unity_sframe> get_proxy() const override;\n\n private:\n gl_sgraph* m_sgraph;\n gframe_type_enum m_gframe_type;\n};\n\n}\n\n#endif\n<commit_msg>remove unnecessary implicit converter which cause complication warning<commit_after>\/**\n * Copyright (C) 2014 GraphLab Inc.\n * All rights reserved.\n *\n * This software may be modified and distributed under the terms\n * of the BSD license. See the LICENSE file for details.\n *\/\n\n#ifndef GRAPHLAB_UNITY_GL_GFRAME_HPP\n#define GRAPHLAB_UNITY_GL_GFRAME_HPP\n\n#include \"gl_sframe.hpp\"\n\nnamespace graphlab {\nclass gl_sframe;\nclass gl_sgraph;\nclass gl_sarray;\n\n\/\/ Possible types of gl_gframe\nenum class gframe_type_enum:int {VERTEX_GFRAME, EDGE_GFRAME};\n\n\/**\n * \\ingroup gl_sdk\n *\n * A proxy for the \\ref gl_sframe for the vertex and edge data of the SGRaph\n *\/\nclass gl_gframe : public gl_sframe {\n public:\n gl_gframe() = delete;\n gl_gframe(const gl_gframe&) = default;\n gl_gframe(gl_gframe&&) = default;\n gl_gframe& operator=(const gl_gframe&) = default;\n gl_gframe& operator=(gl_gframe&&) = default;\n\n \/*\n * Construct gl_gframe from sgraph, and sframe.\n *\/\n gl_gframe(gl_sgraph*, gframe_type_enum);\n\n \/*\n * Implicit converters\n *\/\n operator std::shared_ptr<unity_sframe>() const;\n operator std::shared_ptr<unity_sframe_base>() const;\n\n \/**\n * Returns number of rows. If type is VERTEX_GFRAME, the value\n * is also the number of vertices (or edges if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\n * \\see gl_sgraph::num_vertices\n * \\see gl_sgraph::num_edges\n *\/\n size_t size() const override;\n\n \/**\n * Returns number of columns. If type is VERTEX_GFRAME, the value\n * is also the number of vertex fields (or edge fields if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\/\n size_t num_columns() const override;\n\n \/**\n * Returns a list of column names. If type is VERTEX_GFRAME, the value\n * is also the names of the vertex fields (or edge fields if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\n * \\see gl_sgraph::get_vertex_fields\n * \\see gl_sgraph::get_edge_fields\n *\/\n std::vector<std::string> column_names() const override;\n\n \/**\n * Returns a list of column types. If type is VERTEX_GFRAME, the value\n * is also the names of the vertex fields (or edge fields if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\n * \\see gl_sgraph::get_vertex_field_types\n * \\see gl_sgraph::get_edge_field_types\n *\/\n std::vector<flex_type_enum> column_types() const override;\n\n \/**\n * Add a new column with constant value. If type is VERTEX_GFRAME, the column\n * is added as a new vertex field (or edge field if type is EDGE_GFRAME)\n * in the \\ref gl_sgraph.\n *\n * \\param data the constant value to fill the column\n * \\param name the name of the new column\n *\n * \\see gl_sgraph::add_vertex_field(const flexible_type&, const std::string&)\n * \\see gl_sgraph::add_edge_field(const flexible_type&, const std::stirng&)\n *\/\n void add_column(const flexible_type& data, const std::string& name) override;\n\n \/**\n * Add a new column with given column name and data. If type is\n * VERTEX_GFRAME, the column is added as a new vertex field (or edge field if\n * type is EDGE_GFRAME) in the \\ref gl_sgraph.\n *\n * \\param data the constant value to fill the column\n * \\param name the name of the new column\n *\n * \\see gl_sgraph::add_vertex_field(const gl_sarray&, const std::string&)\n * \\see gl_sgraph::add_edge_field(const gl_sarray&, const std::string&)\n *\/\n void add_column(const gl_sarray& data, const std::string& name) override;\n\n \/**\n * Batch version of \\ref add_column.\n *\n * \\param data a map from column name to column data\n *\/\n void add_columns(const gl_sframe& data) override;\n\n \/**\n * Remove a column with the given name. If type is\n * VERTEX_GFRAME, the column is removed from vertex data (or edge data if\n * type is EDGE_GFRAME) from the \\ref gl_sgraph.\n *\n * \\param name the column name to be removed\n *\n * \\see gl_sgraph::remove_vertex_field\n * \\see gl_sgraph::remove_edge_field\n *\/\n void remove_column(const std::string& name) override;\n\n \/**\n * Rename columns.\n *\n * \\param old_to_new_names map from old column name to new column name.\n *\n * \\see gl_sgraph::rename_vertex_fields\n * \\see gl_sgraph::rename_edge_fields\n *\/\n void rename(const std::map<std::string, std::string>& old_to_new_names) override;\n\n \/**\n * Swap the order of two columns\n *\/\n void swap_columns(const std::string& column_1, const std::string& column_2) override;\n\n virtual std::shared_ptr<unity_sframe> get_proxy() const override;\n\n private:\n gl_sgraph* m_sgraph;\n gframe_type_enum m_gframe_type;\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_multicore\n\/\/\/ Fill histograms in parallel with automatic binning.\n\/\/\/ Illustrates use of power-of-two autobin algorithm\n\/\/\/\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\author Gerardo Ganis\n\/\/\/ \\date November 2017\n\n\/\/ The number of workers\nconst UInt_t nWorkers = 8U;\n\n\/\/ Reference boundaries\nconst Double_t xmiref = -1.;\nconst Double_t xmaref = 7.;\n\nInt_t mt304_fillHistos(UInt_t nNumbers = 1001)\n{\n\n \/\/ The first, fundamental operation to be performed in order to make ROOT\n \/\/ thread-aware.\n ROOT::EnableThreadSafety();\n\n \/\/ Histograms to be filled in parallel\n ROOT::TThreadedObject<TH1D> h1d(\"h1d\", \"1D test histogram\", 64, 0., -1.);\n ROOT::TThreadedObject<TH1D> h1dr(\"h1dr\", \"1D test histogram w\/ ref boundaries\", 64, xmiref, xmaref);\n\n \/\/ We define our work item\n auto workItem = [&](UInt_t workerID) {\n \/\/ One generator, file and ntuple per worker\n TRandom3 workerRndm(workerID); \/\/ Change the seed\n\n auto wh1d = h1d.Get();\n wh1d->SetBit(TH1::kAutoBinPTwo);\n auto wh1dr = h1dr.Get();\n\n Double_t x;\n for (UInt_t i = 0; i < nNumbers; ++i) {\n x = workerRndm.Gaus(3.);\n wh1d->Fill(x);\n wh1dr->Fill(x);\n }\n };\n\n \/\/ Create the collection which will hold the threads, our \"pool\"\n std::vector<std::thread> workers;\n\n \/\/ Fill the \"pool\" with workers\n for (auto workerID : ROOT::TSeqI(nWorkers)) {\n workers.emplace_back(workItem, workerID);\n }\n\n \/\/ Now join them\n for (auto &&worker : workers)\n worker.join();\n\n \/\/ Merge\n auto fh1d = h1d.Merge();\n auto fh1dr = h1dr.Merge();\n\n \/\/ Make the canvas\n auto c = new TCanvas(\"c\", \"c\", 800, 800);\n c->Divide(1, 2);\n\n gStyle->SetOptStat(111110);\n c->cd(1);\n fh1d->DrawCopy();\n c->cd(2);\n fh1dr->DrawCopy();\n\n c->Update();\n\n return 0;\n}\n<commit_msg>[Doc] Add mt304 tutorial to the online documentation<commit_after>\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_multicore\n\/\/\/ \\notebook -draw\n\/\/\/ Fill histograms in parallel with automatic binning.\n\/\/\/ Illustrates use of power-of-two autobin algorithm\n\/\/\/\n\/\/\/ \\macro_code\n\/\/\/ \\macro_image\n\/\/\/\n\/\/\/ \\date November 2017\n\/\/\/ \\author Gerardo Ganis\n\n\/\/ The number of workers\nconst UInt_t nWorkers = 8U;\n\n\/\/ Reference boundaries\nconst Double_t xmiref = -1.;\nconst Double_t xmaref = 7.;\n\nInt_t mt304_fillHistos(UInt_t nNumbers = 1001)\n{\n\n \/\/ The first, fundamental operation to be performed in order to make ROOT\n \/\/ thread-aware.\n ROOT::EnableThreadSafety();\n\n \/\/ Histograms to be filled in parallel\n ROOT::TThreadedObject<TH1D> h1d(\"h1d\", \"1D test histogram\", 64, 0., -1.);\n ROOT::TThreadedObject<TH1D> h1dr(\"h1dr\", \"1D test histogram w\/ ref boundaries\", 64, xmiref, xmaref);\n\n \/\/ We define our work item\n auto workItem = [&](UInt_t workerID) {\n \/\/ One generator, file and ntuple per worker\n TRandom3 workerRndm(workerID); \/\/ Change the seed\n\n auto wh1d = h1d.Get();\n wh1d->SetBit(TH1::kAutoBinPTwo);\n auto wh1dr = h1dr.Get();\n\n Double_t x;\n for (UInt_t i = 0; i < nNumbers; ++i) {\n x = workerRndm.Gaus(3.);\n wh1d->Fill(x);\n wh1dr->Fill(x);\n }\n };\n\n \/\/ Create the collection which will hold the threads, our \"pool\"\n std::vector<std::thread> workers;\n\n \/\/ Fill the \"pool\" with workers\n for (auto workerID : ROOT::TSeqI(nWorkers)) {\n workers.emplace_back(workItem, workerID);\n }\n\n \/\/ Now join them\n for (auto &&worker : workers)\n worker.join();\n\n \/\/ Merge\n auto fh1d = h1d.Merge();\n auto fh1dr = h1dr.Merge();\n\n \/\/ Make the canvas\n auto c = new TCanvas(\"c\", \"c\", 800, 800);\n c->Divide(1, 2);\n\n gStyle->SetOptStat(111110);\n c->cd(1);\n fh1d->DrawCopy();\n c->cd(2);\n fh1dr->DrawCopy();\n\n c->Update();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 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 \"athena\/extensions\/public\/extension_app_model_builder.h\"\n\n#include \"athena\/activity\/public\/activity_factory.h\"\n#include \"athena\/activity\/public\/activity_manager.h\"\n#include \"athena\/extensions\/public\/extensions_delegate.h\"\n#include \"extensions\/browser\/extension_icon_image.h\"\n#include \"extensions\/common\/constants.h\"\n#include \"extensions\/common\/extension_set.h\"\n#include \"extensions\/common\/manifest_handlers\/icons_handler.h\"\n#include \"extensions\/grit\/extensions_browser_resources.h\"\n#include \"ui\/app_list\/app_list_item.h\"\n#include \"ui\/app_list\/app_list_model.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\nnamespace athena {\n\nnamespace {\n\nclass AppItem : public app_list::AppListItem {\n public:\n AppItem(scoped_refptr<const extensions::Extension> extension,\n content::BrowserContext* browser_context)\n : app_list::AppListItem(extension->id()),\n extension_(extension),\n browser_context_(browser_context),\n icon_image_(browser_context_,\n extension.get(),\n extensions::IconsInfo::GetIcons(extension.get()),\n extension_misc::EXTENSION_ICON_MEDIUM,\n *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(\n IDR_APP_DEFAULT_ICON),\n NULL) {\n icon_image_.image_skia().EnsureRepsForSupportedScales();\n SetIcon(icon_image_.image_skia(), false);\n SetName(extension->name());\n }\n\n private:\n \/\/ Overridden from app_list::AppListItem:\n virtual void Activate(int event_flags) override {\n ExtensionsDelegate::Get(browser_context_)->LaunchApp(extension_->id());\n }\n\n scoped_refptr<const extensions::Extension> extension_;\n content::BrowserContext* browser_context_;\n extensions::IconImage icon_image_;\n\n DISALLOW_COPY_AND_ASSIGN(AppItem);\n};\n\n} \/\/ namespace\n\nExtensionAppModelBuilder::ExtensionAppModelBuilder(\n content::BrowserContext* browser_context)\n : browser_context_(browser_context) {\n}\n\nExtensionAppModelBuilder::~ExtensionAppModelBuilder() {\n}\n\nvoid ExtensionAppModelBuilder::PopulateApps(app_list::AppListModel* model) {\n ExtensionsDelegate* bridge = ExtensionsDelegate::Get(browser_context_);\n const extensions::ExtensionSet& extensions = bridge->GetInstalledExtensions();\n for (extensions::ExtensionSet::const_iterator iter = extensions.begin();\n iter != extensions.end();\n ++iter) {\n \/\/ TODO(mukai): use chrome\/browser\/extension_ui_util.\n if ((*iter)->ShouldDisplayInAppLauncher()) {\n model->AddItem(scoped_ptr<app_list::AppListItem>(\n new AppItem(*iter, browser_context_)));\n }\n }\n}\n\n} \/\/ namespace athena\n<commit_msg>Skips Chrome icon in Athena home card.<commit_after>\/\/ Copyright 2014 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 \"athena\/extensions\/public\/extension_app_model_builder.h\"\n\n#include \"athena\/activity\/public\/activity_factory.h\"\n#include \"athena\/activity\/public\/activity_manager.h\"\n#include \"athena\/extensions\/public\/extensions_delegate.h\"\n#include \"extensions\/browser\/extension_icon_image.h\"\n#include \"extensions\/common\/constants.h\"\n#include \"extensions\/common\/extension_set.h\"\n#include \"extensions\/common\/manifest_handlers\/icons_handler.h\"\n#include \"extensions\/grit\/extensions_browser_resources.h\"\n#include \"ui\/app_list\/app_list_item.h\"\n#include \"ui\/app_list\/app_list_model.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\nnamespace athena {\n\nnamespace {\n\n\/\/ Copied from chrome\/common\/extensions\/extension_constants.h\n\/\/ TODO(mukai): move constants to src\/extensions\nconst char kChromeAppId[] = \"mgndgikekgjfcpckkfioiadnlibdjbkf\";\n\nclass AppItem : public app_list::AppListItem {\n public:\n AppItem(scoped_refptr<const extensions::Extension> extension,\n content::BrowserContext* browser_context)\n : app_list::AppListItem(extension->id()),\n extension_(extension),\n browser_context_(browser_context),\n icon_image_(browser_context_,\n extension.get(),\n extensions::IconsInfo::GetIcons(extension.get()),\n extension_misc::EXTENSION_ICON_MEDIUM,\n *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(\n IDR_APP_DEFAULT_ICON),\n NULL) {\n icon_image_.image_skia().EnsureRepsForSupportedScales();\n SetIcon(icon_image_.image_skia(), false);\n SetName(extension->name());\n }\n\n private:\n \/\/ Overridden from app_list::AppListItem:\n virtual void Activate(int event_flags) override {\n ExtensionsDelegate::Get(browser_context_)->LaunchApp(extension_->id());\n }\n\n scoped_refptr<const extensions::Extension> extension_;\n content::BrowserContext* browser_context_;\n extensions::IconImage icon_image_;\n\n DISALLOW_COPY_AND_ASSIGN(AppItem);\n};\n\n} \/\/ namespace\n\nExtensionAppModelBuilder::ExtensionAppModelBuilder(\n content::BrowserContext* browser_context)\n : browser_context_(browser_context) {\n}\n\nExtensionAppModelBuilder::~ExtensionAppModelBuilder() {\n}\n\nvoid ExtensionAppModelBuilder::PopulateApps(app_list::AppListModel* model) {\n ExtensionsDelegate* bridge = ExtensionsDelegate::Get(browser_context_);\n const extensions::ExtensionSet& extensions = bridge->GetInstalledExtensions();\n for (extensions::ExtensionSet::const_iterator iter = extensions.begin();\n iter != extensions.end();\n ++iter) {\n \/\/ Chrome icon is currently disabled for homecard since it's not meaningful.\n \/\/ http:\/\/crbug.com\/421677\n \/\/ TODO(mukai): use chrome\/browser\/extension_ui_util.\n if ((*iter)->ShouldDisplayInAppLauncher() &&\n (*iter)->id() != kChromeAppId) {\n model->AddItem(scoped_ptr<app_list::AppListItem>(\n new AppItem(*iter, browser_context_)));\n }\n }\n}\n\n} \/\/ namespace athena\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Add return 1<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/crash_reporter\/crash_reporter_win.h\"\n\n#include <string>\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n\nnamespace crash_reporter {\n\nnamespace {\n\n\/\/ Minidump with stacks, PEB, TEB, and unloaded module list.\nconst MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>(\n MiniDumpWithProcessThreadData | \/\/ Get PEB and TEB.\n MiniDumpWithUnloadedModules); \/\/ Get unloaded modules when available.\n\nconst wchar_t kPipeNameFormat[] = L\"\\\\\\\\.\\\\pipe\\\\$1 Crash Service\";\n\n} \/\/ namespace\n\nCrashReporterWin::CrashReporterWin() {\n}\n\nCrashReporterWin::~CrashReporterWin() {\n}\n\nvoid CrashReporterWin::InitBreakpad(const std::string& product_name,\n const std::string& version,\n const std::string& company_name,\n const std::string& submit_url,\n bool auto_submit,\n bool skip_system_crash_handler) {\n skip_system_crash_handler_ = skip_system_crash_handler;\n\n base::FilePath temp_dir;\n if (!base::GetTempDir(&temp_dir)) {\n LOG(ERROR) << \"Cannot get temp directory\";\n return;\n }\n\n base::string16 pipe_name = ReplaceStringPlaceholders(\n kPipeNameFormat, base::UTF8ToUTF16(product_name), NULL);\n\n \/\/ Wait until the crash service is started.\n HANDLE waiting_event =\n ::CreateEventW(NULL, TRUE, FALSE, L\"g_atom_shell_crash_service\");\n if (waiting_event != INVALID_HANDLE_VALUE)\n WaitForSingleObject(waiting_event, 1000);\n\n breakpad_.reset(new google_breakpad::ExceptionHandler(\n temp_dir.value(),\n FilterCallback,\n MinidumpCallback,\n this,\n google_breakpad::ExceptionHandler::HANDLER_ALL,\n kSmallDumpType,\n pipe_name.c_str(),\n GetCustomInfo(product_name, version, company_name)));\n\n if (!breakpad_->IsOutOfProcess())\n LOG(ERROR) << \"Cannot initialize out-of-process crash handler\";\n}\n\nvoid CrashReporterWin::SetUploadParameters() {\n upload_parameters_[\"platform\"] = \"win32\";\n}\n\n\/\/ static\nbool CrashReporterWin::FilterCallback(void* context,\n EXCEPTION_POINTERS* exinfo,\n MDRawAssertionInfo* assertion) {\n return true;\n}\n\n\/\/ static\nbool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path,\n const wchar_t* minidump_id,\n void* context,\n EXCEPTION_POINTERS* exinfo,\n MDRawAssertionInfo* assertion,\n bool succeeded) {\n CrashReporterWin* self = static_cast<CrashReporterWin*>(context);\n if (succeeded && !self->skip_system_crash_handler_)\n return true;\n else\n return false;\n}\n\ngoogle_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo(\n const std::string& product_name,\n const std::string& version,\n const std::string& company_name) {\n custom_info_entries_.clear();\n custom_info_entries_.reserve(2 + upload_parameters_.size());\n\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n L\"prod\", L\"Atom-Shell\"));\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n L\"ver\", base::UTF8ToWide(version).c_str()));\n\n for (StringMap::const_iterator iter = upload_parameters_.begin();\n iter != upload_parameters_.end(); ++iter) {\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n base::UTF8ToWide(iter->first).c_str(),\n base::UTF8ToWide(iter->second).c_str()));\n }\n\n custom_info_.entries = &custom_info_entries_.front();\n custom_info_.count = custom_info_entries_.size();\n return &custom_info_;\n}\n\n\/\/ static\nCrashReporterWin* CrashReporterWin::GetInstance() {\n return Singleton<CrashReporterWin>::get();\n}\n\n\/\/ static\nCrashReporter* CrashReporter::GetInstance() {\n return CrashReporterWin::GetInstance();\n}\n\n} \/\/ namespace crash_reporter\n<commit_msg>win: Don't crash on invalid parameter error.<commit_after>\/\/ Copyright (c) 2013 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/crash_reporter\/crash_reporter_win.h\"\n\n#include <string>\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n\nnamespace crash_reporter {\n\nnamespace {\n\n\/\/ Minidump with stacks, PEB, TEB, and unloaded module list.\nconst MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>(\n MiniDumpWithProcessThreadData | \/\/ Get PEB and TEB.\n MiniDumpWithUnloadedModules); \/\/ Get unloaded modules when available.\n\nconst wchar_t kPipeNameFormat[] = L\"\\\\\\\\.\\\\pipe\\\\$1 Crash Service\";\n\n} \/\/ namespace\n\nCrashReporterWin::CrashReporterWin() {\n}\n\nCrashReporterWin::~CrashReporterWin() {\n}\n\nvoid CrashReporterWin::InitBreakpad(const std::string& product_name,\n const std::string& version,\n const std::string& company_name,\n const std::string& submit_url,\n bool auto_submit,\n bool skip_system_crash_handler) {\n skip_system_crash_handler_ = skip_system_crash_handler;\n\n base::FilePath temp_dir;\n if (!base::GetTempDir(&temp_dir)) {\n LOG(ERROR) << \"Cannot get temp directory\";\n return;\n }\n\n base::string16 pipe_name = ReplaceStringPlaceholders(\n kPipeNameFormat, base::UTF8ToUTF16(product_name), NULL);\n\n \/\/ Wait until the crash service is started.\n HANDLE waiting_event =\n ::CreateEventW(NULL, TRUE, FALSE, L\"g_atom_shell_crash_service\");\n if (waiting_event != INVALID_HANDLE_VALUE)\n WaitForSingleObject(waiting_event, 1000);\n\n int handler_types = google_breakpad::ExceptionHandler::HANDLER_EXCEPTION |\n google_breakpad::ExceptionHandler::HANDLER_PURECALL;\n breakpad_.reset(new google_breakpad::ExceptionHandler(\n temp_dir.value(),\n FilterCallback,\n MinidumpCallback,\n this,\n handler_types,\n kSmallDumpType,\n pipe_name.c_str(),\n GetCustomInfo(product_name, version, company_name)));\n\n if (!breakpad_->IsOutOfProcess())\n LOG(ERROR) << \"Cannot initialize out-of-process crash handler\";\n}\n\nvoid CrashReporterWin::SetUploadParameters() {\n upload_parameters_[\"platform\"] = \"win32\";\n}\n\n\/\/ static\nbool CrashReporterWin::FilterCallback(void* context,\n EXCEPTION_POINTERS* exinfo,\n MDRawAssertionInfo* assertion) {\n return true;\n}\n\n\/\/ static\nbool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path,\n const wchar_t* minidump_id,\n void* context,\n EXCEPTION_POINTERS* exinfo,\n MDRawAssertionInfo* assertion,\n bool succeeded) {\n CrashReporterWin* self = static_cast<CrashReporterWin*>(context);\n if (succeeded && !self->skip_system_crash_handler_)\n return true;\n else\n return false;\n}\n\ngoogle_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo(\n const std::string& product_name,\n const std::string& version,\n const std::string& company_name) {\n custom_info_entries_.clear();\n custom_info_entries_.reserve(2 + upload_parameters_.size());\n\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n L\"prod\", L\"Atom-Shell\"));\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n L\"ver\", base::UTF8ToWide(version).c_str()));\n\n for (StringMap::const_iterator iter = upload_parameters_.begin();\n iter != upload_parameters_.end(); ++iter) {\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n base::UTF8ToWide(iter->first).c_str(),\n base::UTF8ToWide(iter->second).c_str()));\n }\n\n custom_info_.entries = &custom_info_entries_.front();\n custom_info_.count = custom_info_entries_.size();\n return &custom_info_;\n}\n\n\/\/ static\nCrashReporterWin* CrashReporterWin::GetInstance() {\n return Singleton<CrashReporterWin>::get();\n}\n\n\/\/ static\nCrashReporter* CrashReporter::GetInstance() {\n return CrashReporterWin::GetInstance();\n}\n\n} \/\/ namespace crash_reporter\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Facebook, Inc.\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#include \"folly\/experimental\/io\/AsyncIO.h\"\n\n#include <sys\/eventfd.h>\n#include <unistd.h>\n#include <cerrno>\n#include <stdexcept>\n#include <string>\n\n#include <boost\/intrusive\/parent_from_member.hpp>\n#include <glog\/logging.h>\n\n#include \"folly\/Exception.h\"\n#include \"folly\/Format.h\"\n#include \"folly\/Likely.h\"\n#include \"folly\/String.h\"\n\nnamespace folly {\n\nAsyncIOOp::AsyncIOOp(NotificationCallback cb)\n : cb_(std::move(cb)),\n state_(State::UNINITIALIZED),\n result_(-EINVAL) {\n memset(&iocb_, 0, sizeof(iocb_));\n}\n\nvoid AsyncIOOp::reset(NotificationCallback cb) {\n CHECK_NE(state_, State::PENDING);\n cb_ = std::move(cb);\n state_ = State::UNINITIALIZED;\n result_ = -EINVAL;\n memset(&iocb_, 0, sizeof(iocb_));\n}\n\nAsyncIOOp::~AsyncIOOp() {\n CHECK_NE(state_, State::PENDING);\n}\n\nvoid AsyncIOOp::start() {\n DCHECK_EQ(state_, State::INITIALIZED);\n state_ = State::PENDING;\n}\n\nvoid AsyncIOOp::complete(ssize_t result) {\n DCHECK_EQ(state_, State::PENDING);\n state_ = State::COMPLETED;\n result_ = result;\n if (cb_) {\n cb_(this);\n }\n}\n\nssize_t AsyncIOOp::result() const {\n CHECK_EQ(state_, State::COMPLETED);\n return result_;\n}\n\nvoid AsyncIOOp::pread(int fd, void* buf, size_t size, off_t start) {\n init();\n io_prep_pread(&iocb_, fd, buf, size, start);\n}\n\nvoid AsyncIOOp::pread(int fd, Range<unsigned char*> range, off_t start) {\n pread(fd, range.begin(), range.size(), start);\n}\n\nvoid AsyncIOOp::preadv(int fd, const iovec* iov, int iovcnt, off_t start) {\n init();\n io_prep_preadv(&iocb_, fd, iov, iovcnt, start);\n}\n\nvoid AsyncIOOp::pwrite(int fd, const void* buf, size_t size, off_t start) {\n init();\n io_prep_pwrite(&iocb_, fd, const_cast<void*>(buf), size, start);\n}\n\nvoid AsyncIOOp::pwrite(int fd, Range<const unsigned char*> range, off_t start) {\n pwrite(fd, range.begin(), range.size(), start);\n}\n\nvoid AsyncIOOp::pwritev(int fd, const iovec* iov, int iovcnt, off_t start) {\n init();\n io_prep_pwritev(&iocb_, fd, iov, iovcnt, start);\n}\n\nvoid AsyncIOOp::init() {\n CHECK_EQ(state_, State::UNINITIALIZED);\n state_ = State::INITIALIZED;\n}\n\nAsyncIO::AsyncIO(size_t capacity, PollMode pollMode)\n : ctx_(0),\n ctxSet_(false),\n pending_(0),\n capacity_(capacity),\n pollFd_(-1) {\n CHECK_GT(capacity_, 0);\n completed_.reserve(capacity_);\n if (pollMode == POLLABLE) {\n pollFd_ = eventfd(0, EFD_NONBLOCK);\n checkUnixError(pollFd_, \"AsyncIO: eventfd creation failed\");\n }\n}\n\nAsyncIO::~AsyncIO() {\n CHECK_EQ(pending_, 0);\n if (ctx_) {\n int rc = io_queue_release(ctx_);\n CHECK_EQ(rc, 0) << \"io_queue_release: \" << errnoStr(-rc);\n }\n if (pollFd_ != -1) {\n CHECK_ERR(close(pollFd_));\n }\n}\n\nvoid AsyncIO::decrementPending() {\n ssize_t p = pending_.fetch_add(-1, std::memory_order_acq_rel);\n DCHECK_GE(p, 1);\n}\n\nvoid AsyncIO::initializeContext() {\n if (!ctxSet_.load(std::memory_order_acquire)) {\n std::lock_guard<std::mutex> lock(initMutex_);\n if (!ctxSet_.load(std::memory_order_relaxed)) {\n int rc = io_queue_init(capacity_, &ctx_);\n \/\/ returns negative errno\n checkKernelError(rc, \"AsyncIO: io_queue_init failed\");\n DCHECK(ctx_);\n ctxSet_.store(true, std::memory_order_release);\n }\n }\n}\n\nvoid AsyncIO::submit(Op* op) {\n CHECK_EQ(op->state(), Op::State::INITIALIZED);\n initializeContext(); \/\/ on demand\n\n \/\/ We can increment past capacity, but we'll clean up after ourselves.\n ssize_t p = pending_.fetch_add(1, std::memory_order_acq_rel);\n if (p >= capacity_) {\n decrementPending();\n throw std::range_error(\"AsyncIO: too many pending requests\");\n }\n iocb* cb = &op->iocb_;\n cb->data = nullptr; \/\/ unused\n if (pollFd_ != -1) {\n io_set_eventfd(cb, pollFd_);\n }\n int rc = io_submit(ctx_, 1, &cb);\n if (rc < 0) {\n decrementPending();\n throwSystemErrorExplicit(-rc, \"AsyncIO: io_submit failed\");\n }\n DCHECK_EQ(rc, 1);\n op->start();\n}\n\nRange<AsyncIO::Op**> AsyncIO::wait(size_t minRequests) {\n CHECK(ctx_);\n CHECK_EQ(pollFd_, -1) << \"wait() only allowed on non-pollable object\";\n ssize_t p = pending_.load(std::memory_order_acquire);\n CHECK_LE(minRequests, p);\n return doWait(minRequests, p);\n}\n\nRange<AsyncIO::Op**> AsyncIO::pollCompleted() {\n CHECK(ctx_);\n CHECK_NE(pollFd_, -1) << \"pollCompleted() only allowed on pollable object\";\n uint64_t numEvents;\n \/\/ This sets the eventFd counter to 0, see\n \/\/ http:\/\/www.kernel.org\/doc\/man-pages\/online\/pages\/man2\/eventfd.2.html\n ssize_t rc;\n do {\n rc = ::read(pollFd_, &numEvents, 8);\n } while (rc == -1 && errno == EINTR);\n if (UNLIKELY(rc == -1 && errno == EAGAIN)) {\n return Range<Op**>(); \/\/ nothing completed\n }\n checkUnixError(rc, \"AsyncIO: read from event fd failed\");\n DCHECK_EQ(rc, 8);\n\n DCHECK_GT(numEvents, 0);\n DCHECK_LE(numEvents, pending_);\n\n \/\/ Don't reap more than numEvents, as we've just reset the counter to 0.\n return doWait(numEvents, numEvents);\n}\n\nRange<AsyncIO::Op**> AsyncIO::doWait(size_t minRequests, size_t maxRequests) {\n io_event events[maxRequests];\n int count;\n do {\n \/\/ Wait forever\n count = io_getevents(ctx_, minRequests, maxRequests, events, nullptr);\n } while (count == -EINTR);\n checkKernelError(count, \"AsyncIO: io_getevents failed\");\n DCHECK_GE(count, minRequests); \/\/ the man page says so\n DCHECK_LE(count, maxRequests);\n\n completed_.clear();\n if (count == 0) {\n return folly::Range<Op**>();\n }\n\n for (size_t i = 0; i < count; ++i) {\n DCHECK(events[i].obj);\n Op* op = boost::intrusive::get_parent_from_member(\n events[i].obj, &AsyncIOOp::iocb_);\n decrementPending();\n op->complete(events[i].res);\n completed_.push_back(op);\n }\n\n return folly::Range<Op**>(&completed_.front(), count);\n}\n\nAsyncIOQueue::AsyncIOQueue(AsyncIO* asyncIO)\n : asyncIO_(asyncIO) {\n}\n\nAsyncIOQueue::~AsyncIOQueue() {\n CHECK_EQ(asyncIO_->pending(), 0);\n}\n\nvoid AsyncIOQueue::submit(AsyncIOOp* op) {\n submit([op]() { return op; });\n}\n\nvoid AsyncIOQueue::submit(OpFactory op) {\n queue_.push_back(op);\n maybeDequeue();\n}\n\nvoid AsyncIOQueue::onCompleted(AsyncIOOp* op) {\n maybeDequeue();\n}\n\nvoid AsyncIOQueue::maybeDequeue() {\n while (!queue_.empty() && asyncIO_->pending() < asyncIO_->capacity()) {\n auto& opFactory = queue_.front();\n auto op = opFactory();\n queue_.pop_front();\n\n \/\/ Interpose our completion callback\n auto& nextCb = op->notificationCallback();\n op->setNotificationCallback([this, nextCb](AsyncIOOp* op) {\n this->onCompleted(op);\n if (nextCb) nextCb(op);\n });\n\n asyncIO_->submit(op);\n }\n}\n\n\/\/ debugging helpers:\n\nnamespace {\n\n#define X(c) case c: return #c\n\nconst char* asyncIoOpStateToString(AsyncIOOp::State state) {\n switch (state) {\n X(AsyncIOOp::State::UNINITIALIZED);\n X(AsyncIOOp::State::INITIALIZED);\n X(AsyncIOOp::State::PENDING);\n X(AsyncIOOp::State::COMPLETED);\n }\n return \"<INVALID AsyncIOOp::State>\";\n}\n\nconst char* iocbCmdToString(short int cmd_short) {\n io_iocb_cmd cmd = static_cast<io_iocb_cmd>(cmd_short);\n switch (cmd) {\n X(IO_CMD_PREAD);\n X(IO_CMD_PWRITE);\n X(IO_CMD_FSYNC);\n X(IO_CMD_FDSYNC);\n X(IO_CMD_POLL);\n X(IO_CMD_NOOP);\n X(IO_CMD_PREADV);\n X(IO_CMD_PWRITEV);\n };\n return \"<INVALID io_iocb_cmd>\";\n}\n\n#undef X\n\nstd::string fd2name(int fd) {\n std::string path = folly::to<std::string>(\"\/proc\/self\/fd\/\", fd);\n char link[PATH_MAX];\n const ssize_t length =\n std::max<ssize_t>(readlink(path.c_str(), link, PATH_MAX), 0);\n return path.assign(link, length);\n}\n\nstd::ostream& operator<<(std::ostream& os, const iocb& cb) {\n os << folly::format(\n \"data={}, key={}, opcode={}, reqprio={}, fd={}, f={}, \",\n cb.data, cb.key, iocbCmdToString(cb.aio_lio_opcode),\n cb.aio_reqprio, cb.aio_fildes, fd2name(cb.aio_fildes));\n\n switch (cb.aio_lio_opcode) {\n case IO_CMD_PREAD:\n case IO_CMD_PWRITE:\n os << folly::format(\"buf={}, off={}, size={}, \",\n cb.u.c.buf, cb.u.c.nbytes, cb.u.c.offset);\n default:\n os << \"[TODO: write debug string for \"\n << iocbCmdToString(cb.aio_lio_opcode) << \"] \";\n }\n\n return os;\n}\n\n} \/\/ anonymous namespace\n\nstd::ostream& operator<<(std::ostream& os, const AsyncIOOp& op) {\n os << \"{\" << op.state_ << \", \";\n\n if (op.state_ != AsyncIOOp::State::UNINITIALIZED) {\n os << op.iocb_;\n }\n\n if (op.state_ == AsyncIOOp::State::COMPLETED) {\n os << \"result=\" << op.result_ << \", \";\n }\n\n return os << \"}\";\n}\n\nstd::ostream& operator<<(std::ostream& os, AsyncIOOp::State state) {\n return os << asyncIoOpStateToString(state);\n}\n\n} \/\/ namespace folly\n\n<commit_msg>AsyncIO::initializeContext() should provide more debug output when io_queue_init fails<commit_after>\/*\n * Copyright 2013 Facebook, Inc.\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#include \"folly\/experimental\/io\/AsyncIO.h\"\n\n#include <sys\/eventfd.h>\n#include <unistd.h>\n#include <cerrno>\n#include <stdexcept>\n#include <string>\n#include <fstream>\n\n#include <boost\/intrusive\/parent_from_member.hpp>\n#include <glog\/logging.h>\n\n#include \"folly\/Exception.h\"\n#include \"folly\/Format.h\"\n#include \"folly\/Likely.h\"\n#include \"folly\/String.h\"\n\nnamespace folly {\n\nAsyncIOOp::AsyncIOOp(NotificationCallback cb)\n : cb_(std::move(cb)),\n state_(State::UNINITIALIZED),\n result_(-EINVAL) {\n memset(&iocb_, 0, sizeof(iocb_));\n}\n\nvoid AsyncIOOp::reset(NotificationCallback cb) {\n CHECK_NE(state_, State::PENDING);\n cb_ = std::move(cb);\n state_ = State::UNINITIALIZED;\n result_ = -EINVAL;\n memset(&iocb_, 0, sizeof(iocb_));\n}\n\nAsyncIOOp::~AsyncIOOp() {\n CHECK_NE(state_, State::PENDING);\n}\n\nvoid AsyncIOOp::start() {\n DCHECK_EQ(state_, State::INITIALIZED);\n state_ = State::PENDING;\n}\n\nvoid AsyncIOOp::complete(ssize_t result) {\n DCHECK_EQ(state_, State::PENDING);\n state_ = State::COMPLETED;\n result_ = result;\n if (cb_) {\n cb_(this);\n }\n}\n\nssize_t AsyncIOOp::result() const {\n CHECK_EQ(state_, State::COMPLETED);\n return result_;\n}\n\nvoid AsyncIOOp::pread(int fd, void* buf, size_t size, off_t start) {\n init();\n io_prep_pread(&iocb_, fd, buf, size, start);\n}\n\nvoid AsyncIOOp::pread(int fd, Range<unsigned char*> range, off_t start) {\n pread(fd, range.begin(), range.size(), start);\n}\n\nvoid AsyncIOOp::preadv(int fd, const iovec* iov, int iovcnt, off_t start) {\n init();\n io_prep_preadv(&iocb_, fd, iov, iovcnt, start);\n}\n\nvoid AsyncIOOp::pwrite(int fd, const void* buf, size_t size, off_t start) {\n init();\n io_prep_pwrite(&iocb_, fd, const_cast<void*>(buf), size, start);\n}\n\nvoid AsyncIOOp::pwrite(int fd, Range<const unsigned char*> range, off_t start) {\n pwrite(fd, range.begin(), range.size(), start);\n}\n\nvoid AsyncIOOp::pwritev(int fd, const iovec* iov, int iovcnt, off_t start) {\n init();\n io_prep_pwritev(&iocb_, fd, iov, iovcnt, start);\n}\n\nvoid AsyncIOOp::init() {\n CHECK_EQ(state_, State::UNINITIALIZED);\n state_ = State::INITIALIZED;\n}\n\nAsyncIO::AsyncIO(size_t capacity, PollMode pollMode)\n : ctx_(0),\n ctxSet_(false),\n pending_(0),\n capacity_(capacity),\n pollFd_(-1) {\n CHECK_GT(capacity_, 0);\n completed_.reserve(capacity_);\n if (pollMode == POLLABLE) {\n pollFd_ = eventfd(0, EFD_NONBLOCK);\n checkUnixError(pollFd_, \"AsyncIO: eventfd creation failed\");\n }\n}\n\nAsyncIO::~AsyncIO() {\n CHECK_EQ(pending_, 0);\n if (ctx_) {\n int rc = io_queue_release(ctx_);\n CHECK_EQ(rc, 0) << \"io_queue_release: \" << errnoStr(-rc);\n }\n if (pollFd_ != -1) {\n CHECK_ERR(close(pollFd_));\n }\n}\n\nvoid AsyncIO::decrementPending() {\n ssize_t p = pending_.fetch_add(-1, std::memory_order_acq_rel);\n DCHECK_GE(p, 1);\n}\n\nvoid AsyncIO::initializeContext() {\n if (!ctxSet_.load(std::memory_order_acquire)) {\n std::lock_guard<std::mutex> lock(initMutex_);\n if (!ctxSet_.load(std::memory_order_relaxed)) {\n int rc = io_queue_init(capacity_, &ctx_);\n \/\/ returns negative errno\n if (rc == -EAGAIN) {\n long aio_nr, aio_max;\n std::unique_ptr<FILE, int(*)(FILE*)>\n fp(fopen(\"\/proc\/sys\/fs\/aio-nr\", \"r\"), fclose);\n PCHECK(fp);\n CHECK_EQ(fscanf(fp.get(), \"%ld\", &aio_nr), 1);\n\n std::unique_ptr<FILE, int(*)(FILE*)>\n aio_max_fp(fopen(\"\/proc\/sys\/fs\/aio-max-nr\", \"r\"), fclose);\n PCHECK(aio_max_fp);\n CHECK_EQ(fscanf(aio_max_fp.get(), \"%ld\", &aio_max), 1);\n\n LOG(ERROR) << \"No resources for requested capacity of \" << capacity_;\n LOG(ERROR) << \"aio_nr \" << aio_nr << \", aio_max_nr \" << aio_max;\n }\n\n checkKernelError(rc, \"AsyncIO: io_queue_init failed\");\n DCHECK(ctx_);\n ctxSet_.store(true, std::memory_order_release);\n }\n }\n}\n\nvoid AsyncIO::submit(Op* op) {\n CHECK_EQ(op->state(), Op::State::INITIALIZED);\n initializeContext(); \/\/ on demand\n\n \/\/ We can increment past capacity, but we'll clean up after ourselves.\n ssize_t p = pending_.fetch_add(1, std::memory_order_acq_rel);\n if (p >= capacity_) {\n decrementPending();\n throw std::range_error(\"AsyncIO: too many pending requests\");\n }\n iocb* cb = &op->iocb_;\n cb->data = nullptr; \/\/ unused\n if (pollFd_ != -1) {\n io_set_eventfd(cb, pollFd_);\n }\n int rc = io_submit(ctx_, 1, &cb);\n if (rc < 0) {\n decrementPending();\n throwSystemErrorExplicit(-rc, \"AsyncIO: io_submit failed\");\n }\n DCHECK_EQ(rc, 1);\n op->start();\n}\n\nRange<AsyncIO::Op**> AsyncIO::wait(size_t minRequests) {\n CHECK(ctx_);\n CHECK_EQ(pollFd_, -1) << \"wait() only allowed on non-pollable object\";\n ssize_t p = pending_.load(std::memory_order_acquire);\n CHECK_LE(minRequests, p);\n return doWait(minRequests, p);\n}\n\nRange<AsyncIO::Op**> AsyncIO::pollCompleted() {\n CHECK(ctx_);\n CHECK_NE(pollFd_, -1) << \"pollCompleted() only allowed on pollable object\";\n uint64_t numEvents;\n \/\/ This sets the eventFd counter to 0, see\n \/\/ http:\/\/www.kernel.org\/doc\/man-pages\/online\/pages\/man2\/eventfd.2.html\n ssize_t rc;\n do {\n rc = ::read(pollFd_, &numEvents, 8);\n } while (rc == -1 && errno == EINTR);\n if (UNLIKELY(rc == -1 && errno == EAGAIN)) {\n return Range<Op**>(); \/\/ nothing completed\n }\n checkUnixError(rc, \"AsyncIO: read from event fd failed\");\n DCHECK_EQ(rc, 8);\n\n DCHECK_GT(numEvents, 0);\n DCHECK_LE(numEvents, pending_);\n\n \/\/ Don't reap more than numEvents, as we've just reset the counter to 0.\n return doWait(numEvents, numEvents);\n}\n\nRange<AsyncIO::Op**> AsyncIO::doWait(size_t minRequests, size_t maxRequests) {\n io_event events[maxRequests];\n int count;\n do {\n \/\/ Wait forever\n count = io_getevents(ctx_, minRequests, maxRequests, events, nullptr);\n } while (count == -EINTR);\n checkKernelError(count, \"AsyncIO: io_getevents failed\");\n DCHECK_GE(count, minRequests); \/\/ the man page says so\n DCHECK_LE(count, maxRequests);\n\n completed_.clear();\n if (count == 0) {\n return folly::Range<Op**>();\n }\n\n for (size_t i = 0; i < count; ++i) {\n DCHECK(events[i].obj);\n Op* op = boost::intrusive::get_parent_from_member(\n events[i].obj, &AsyncIOOp::iocb_);\n decrementPending();\n op->complete(events[i].res);\n completed_.push_back(op);\n }\n\n return folly::Range<Op**>(&completed_.front(), count);\n}\n\nAsyncIOQueue::AsyncIOQueue(AsyncIO* asyncIO)\n : asyncIO_(asyncIO) {\n}\n\nAsyncIOQueue::~AsyncIOQueue() {\n CHECK_EQ(asyncIO_->pending(), 0);\n}\n\nvoid AsyncIOQueue::submit(AsyncIOOp* op) {\n submit([op]() { return op; });\n}\n\nvoid AsyncIOQueue::submit(OpFactory op) {\n queue_.push_back(op);\n maybeDequeue();\n}\n\nvoid AsyncIOQueue::onCompleted(AsyncIOOp* op) {\n maybeDequeue();\n}\n\nvoid AsyncIOQueue::maybeDequeue() {\n while (!queue_.empty() && asyncIO_->pending() < asyncIO_->capacity()) {\n auto& opFactory = queue_.front();\n auto op = opFactory();\n queue_.pop_front();\n\n \/\/ Interpose our completion callback\n auto& nextCb = op->notificationCallback();\n op->setNotificationCallback([this, nextCb](AsyncIOOp* op) {\n this->onCompleted(op);\n if (nextCb) nextCb(op);\n });\n\n asyncIO_->submit(op);\n }\n}\n\n\/\/ debugging helpers:\n\nnamespace {\n\n#define X(c) case c: return #c\n\nconst char* asyncIoOpStateToString(AsyncIOOp::State state) {\n switch (state) {\n X(AsyncIOOp::State::UNINITIALIZED);\n X(AsyncIOOp::State::INITIALIZED);\n X(AsyncIOOp::State::PENDING);\n X(AsyncIOOp::State::COMPLETED);\n }\n return \"<INVALID AsyncIOOp::State>\";\n}\n\nconst char* iocbCmdToString(short int cmd_short) {\n io_iocb_cmd cmd = static_cast<io_iocb_cmd>(cmd_short);\n switch (cmd) {\n X(IO_CMD_PREAD);\n X(IO_CMD_PWRITE);\n X(IO_CMD_FSYNC);\n X(IO_CMD_FDSYNC);\n X(IO_CMD_POLL);\n X(IO_CMD_NOOP);\n X(IO_CMD_PREADV);\n X(IO_CMD_PWRITEV);\n };\n return \"<INVALID io_iocb_cmd>\";\n}\n\n#undef X\n\nstd::string fd2name(int fd) {\n std::string path = folly::to<std::string>(\"\/proc\/self\/fd\/\", fd);\n char link[PATH_MAX];\n const ssize_t length =\n std::max<ssize_t>(readlink(path.c_str(), link, PATH_MAX), 0);\n return path.assign(link, length);\n}\n\nstd::ostream& operator<<(std::ostream& os, const iocb& cb) {\n os << folly::format(\n \"data={}, key={}, opcode={}, reqprio={}, fd={}, f={}, \",\n cb.data, cb.key, iocbCmdToString(cb.aio_lio_opcode),\n cb.aio_reqprio, cb.aio_fildes, fd2name(cb.aio_fildes));\n\n switch (cb.aio_lio_opcode) {\n case IO_CMD_PREAD:\n case IO_CMD_PWRITE:\n os << folly::format(\"buf={}, off={}, size={}, \",\n cb.u.c.buf, cb.u.c.nbytes, cb.u.c.offset);\n default:\n os << \"[TODO: write debug string for \"\n << iocbCmdToString(cb.aio_lio_opcode) << \"] \";\n }\n\n return os;\n}\n\n} \/\/ anonymous namespace\n\nstd::ostream& operator<<(std::ostream& os, const AsyncIOOp& op) {\n os << \"{\" << op.state_ << \", \";\n\n if (op.state_ != AsyncIOOp::State::UNINITIALIZED) {\n os << op.iocb_;\n }\n\n if (op.state_ == AsyncIOOp::State::COMPLETED) {\n os << \"result=\" << op.result_ << \", \";\n }\n\n return os << \"}\";\n}\n\nstd::ostream& operator<<(std::ostream& os, AsyncIOOp::State state) {\n return os << asyncIoOpStateToString(state);\n}\n\n} \/\/ namespace folly\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n @file max_of_2_solution1.cpp\n @author Altantur Bayarsaikhan (altantur)\n @purpose Find max of 2 integers\n @version 1.0 26\/10\/17 \n*\/\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\n\nint main(){\n ifstream test_file;\n int a = 0, b = 0, max = 0;\n int temp = 0;\n\n \/\/ Read from test files\n test_file.open (\"..\/test\/test1.txt\");\n test_file >> a;\n test_file >> b;\n test_file.close();\n\n \/\/ Finding max integer without using comparation operator\n max = a + b;\n temp = (a - b);\n temp *= temp;\n temp = sqrt(temp);\n max += temp;\n max \/= 2;\n \n\n cout << \"Max number is : \" << max << endl;\n\n return 0;\n}\n\n<commit_msg>commented about abs to simple solution<commit_after>\/**\n @file max_of_2_solution1.cpp\n @author Altantur Bayarsaikhan (altantur)\n @purpose Find max of 2 integers\n @version 1.0 26\/10\/17 \n*\/\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\n\nint main(){\n ifstream test_file;\n int a = 0, b = 0, max = 0;\n int temp = 0;\n\n \/\/ Read from test files\n test_file.open (\"..\/test\/test1.txt\");\n test_file >> a;\n test_file >> b;\n test_file.close();\n\n \/\/ Finding max integer without using comparation operator\n max = a + b;\n \/\/ We can also use cmath lib - abs(a - b)\n temp = (a - b);\n temp *= temp;\n temp = sqrt(temp);\n max += temp;\n max \/= 2;\n \n\n cout << \"Max number is : \" << max << endl;\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2006 Ulrich von Zadow\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"FilterHighpass.h\"\n#include \"Filterfill.h\"\n#include \"Pixel8.h\"\n#include \"Bitmap.h\"\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nnamespace avg {\n \nFilterHighpass::FilterHighpass()\n{\n}\n\nFilterHighpass::~FilterHighpass()\n{\n}\n\nBitmapPtr FilterHighpass::apply(BitmapPtr pBmpSrc)\n{\n assert(pBmpSrc->getPixelFormat() == I8);\n BitmapPtr pBmpDest = BitmapPtr(new Bitmap(pBmpSrc->getSize(), I8,\n pBmpSrc->getName()));\n int SrcStride = pBmpSrc->getStride();\n int DestStride = pBmpDest->getStride();\n unsigned char * pSrcLine = pBmpSrc->getPixels()+3*SrcStride;\n unsigned char * pDestLine = pBmpDest->getPixels()+3*DestStride;\n IntPoint size = pBmpDest->getSize();\n for (int y = 3; y<size.y-3; ++y) {\n unsigned char * pSrcPixel = pSrcLine+3;\n unsigned char * pDstPixel = pDestLine;\n *pDstPixel++ = 128;\n *pDstPixel++ = 128;\n *pDstPixel++ = 128;\n for (int x = 3; x < size.x-3; ++x) {\n \/\/ Convolution Matrix is\n \/\/ -1 0 0 0 -1\n \/\/ 0 -1 0 -1 0\n \/\/ 0 0 8 0 0\n \/\/ 0 -1 0 -1 0\n \/\/ -1 0 0 0 -1\n \/\/ Actually, it's 7x7, but you get the idea.\n *pDstPixel = \n 128 - int(*(pSrcPixel-2*SrcStride-2) + *(pSrcPixel-2*SrcStride+2) + \n *(pSrcPixel-SrcStride-1) + *(pSrcPixel-1*SrcStride+1) +\n *(pSrcPixel+SrcStride-1) + *(pSrcPixel+1*SrcStride+1) + \n *(pSrcPixel+2*SrcStride-2) + *(pSrcPixel+2*SrcStride+2))\/16 +\n *(pSrcPixel)*3\/4;\n *pDstPixel -= int(*(pSrcPixel-3*SrcStride-3) + *(pSrcPixel-3*SrcStride+3) +\n *(pSrcPixel+3*SrcStride-3) + *(pSrcPixel+3*SrcStride+3))\/16; \n\/*\n unsigned char *pSrc = pSrcPixel-3*SrcStride;\n int Dest = *pSrc;\n pSrc += SrcStride;\n Dest += *pSrc;\n pSrc += SrcStride;\n Dest += *pSrc;\n pSrc += SrcStride-3;\n Dest += *pSrc++;\n Dest += *pSrc++;\n Dest += *pSrc++;\n pSrc++;\n Dest += *pSrc++;\n Dest += *pSrc++;\n Dest += *pSrc;\n pSrc += SrcStride-3;\n Dest += *pSrc;\n pSrc += SrcStride;\n Dest += *pSrc;\n pSrc += SrcStride;\n Dest += *pSrc;\n Dest \/= 16;\n *pDstPixel = 128-Dest+*(pSrcPixel)*3\/4;\n\/* \n *pDstPixel = \n 128 - int(*(pSrcPixel-3*SrcStride) + \n *(pSrcPixel-2*SrcStride) + \n *(pSrcPixel-SrcStride) + \n *(pSrcPixel-3) + *(pSrcPixel-2) + *(pSrcPixel-1) +\n *(pSrcPixel+3) + *(pSrcPixel+2) + *(pSrcPixel+1) +\n *(pSrcPixel+1*SrcStride) + \n *(pSrcPixel+2*SrcStride) + \n *(pSrcPixel+3*SrcStride))\/16 +\n *(pSrcPixel)*3\/4;\n*\/\n ++pSrcPixel;\n ++pDstPixel;\n }\n *pDstPixel++ = 128;\n *pDstPixel++ = 128;\n *pDstPixel++ = 128;\n pSrcLine += SrcStride;\n pDestLine += DestStride;\n }\n \/\/ Set top and bottom borders.\n memset(pBmpDest->getPixels(), 128, DestStride*3);\n memset(pBmpDest->getPixels()+DestStride*(size.y-3), 128, DestStride*3);\n return pBmpDest;\n}\n\n}\n<commit_msg>Added optimized version of highpass (commented out)<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2006 Ulrich von Zadow\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"FilterHighpass.h\"\n#include \"Filterfill.h\"\n#include \"Pixel8.h\"\n#include \"Bitmap.h\"\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nnamespace avg {\n \nFilterHighpass::FilterHighpass()\n{\n}\n\nFilterHighpass::~FilterHighpass()\n{\n}\n\nBitmapPtr FilterHighpass::apply(BitmapPtr pBmpSrc)\n{\n assert(pBmpSrc->getPixelFormat() == I8);\n BitmapPtr pBmpDest = BitmapPtr(new Bitmap(pBmpSrc->getSize(), I8,\n pBmpSrc->getName()));\n int SrcStride = pBmpSrc->getStride();\n int DestStride = pBmpDest->getStride();\n unsigned char * pSrcLine = pBmpSrc->getPixels()+3*SrcStride;\n unsigned char * pDestLine = pBmpDest->getPixels()+3*DestStride;\n IntPoint size = pBmpDest->getSize();\n for (int y = 3; y<size.y-3; ++y) {\n unsigned char * pSrcPixel = pSrcLine+3;\n unsigned char * pDstPixel = pDestLine;\n *pDstPixel++ = 128;\n *pDstPixel++ = 128;\n *pDstPixel++ = 128;\n for (int x = 3; x < size.x-3; ++x) {\n \/\/ Convolution Matrix is\n \/\/ -1 0 0 0 -1\n \/\/ 0 -1 0 -1 0\n \/\/ 0 0 8 0 0\n \/\/ 0 -1 0 -1 0\n \/\/ -1 0 0 0 -1\n \/\/ Actually, it's 7x7, but you get the idea.\n *pDstPixel = \n 128 - int(*(pSrcPixel-2*SrcStride-2) + *(pSrcPixel-2*SrcStride+2) + \n *(pSrcPixel-SrcStride-1) + *(pSrcPixel-1*SrcStride+1) +\n *(pSrcPixel+SrcStride-1) + *(pSrcPixel+1*SrcStride+1) + \n *(pSrcPixel+2*SrcStride-2) + *(pSrcPixel+2*SrcStride+2))\/16 +\n *(pSrcPixel)*3\/4;\n *pDstPixel -= int(*(pSrcPixel-3*SrcStride-3) + *(pSrcPixel-3*SrcStride+3) +\n *(pSrcPixel+3*SrcStride-3) + *(pSrcPixel+3*SrcStride+3))\/16; \n\/*\n unsigned char *pSrc = pSrcPixel-3*SrcStride-3;\n int Dest = *pSrc;\n pSrc += 6;\n Dest += *pSrc;\n pSrc += SrcStride-5;\n Dest += *pSrc;\n pSrc += 4;\n Dest += *pSrc;\n pSrc += 4*SrcStride-4;\n Dest += *pSrc;\n pSrc += 4;\n Dest += *pSrc;\n pSrc += SrcStride-5;\n Dest += *pSrc;\n pSrc += 6;\n Dest += *pSrc;\n Dest \/= 8;\n *pDstPixel = 128+(*pSrcPixel)-Dest;\n*\/\n\/*\n unsigned char *pSrc = pSrcPixel-3*SrcStride;\n int Dest = *pSrc;\n pSrc += SrcStride;\n Dest += *pSrc;\n pSrc += SrcStride;\n Dest += *pSrc;\n pSrc += SrcStride-3;\n Dest += *pSrc++;\n Dest += *pSrc++;\n Dest += *pSrc++;\n pSrc++;\n Dest += *pSrc++;\n Dest += *pSrc++;\n Dest += *pSrc;\n pSrc += SrcStride-3;\n Dest += *pSrc;\n pSrc += SrcStride;\n Dest += *pSrc;\n pSrc += SrcStride;\n Dest += *pSrc;\n Dest \/= 16;\n *pDstPixel = 128-Dest+*(pSrcPixel)*3\/4;\n*\/ \n\/* \n *pDstPixel = \n 128 - int(*(pSrcPixel-3*SrcStride) + \n *(pSrcPixel-2*SrcStride) + \n *(pSrcPixel-SrcStride) + \n *(pSrcPixel-3) + *(pSrcPixel-2) + *(pSrcPixel-1) +\n *(pSrcPixel+3) + *(pSrcPixel+2) + *(pSrcPixel+1) +\n *(pSrcPixel+1*SrcStride) + \n *(pSrcPixel+2*SrcStride) + \n *(pSrcPixel+3*SrcStride))\/16 +\n *(pSrcPixel)*3\/4;\n*\/\n ++pSrcPixel;\n ++pDstPixel;\n }\n *pDstPixel++ = 128;\n *pDstPixel++ = 128;\n *pDstPixel++ = 128;\n pSrcLine += SrcStride;\n pDestLine += DestStride;\n }\n \/\/ Set top and bottom borders.\n memset(pBmpDest->getPixels(), 128, DestStride*3);\n memset(pBmpDest->getPixels()+DestStride*(size.y-3), 128, DestStride*3);\n return pBmpDest;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"precompile.h\"\n\n#include \"hwplib.h\"\n#include \"hinfo.h\"\n#include \"hwpfile.h\"\n\n\/\/ Info Block\n\n\nstatic bool HWPReadInfoBlock(void *ptr, int len, HWPFile & hwpf)\n{\n hwpf.info_block_len = len;\n if (0 == len)\n return true;\n else\n return hwpf.ReadBlock(ptr, len) ? true : false;\n}\n\n\n\/\/ Document Information\nHWPInfo::HWPInfo()\n : cur_col(0)\n , cur_row(0)\n , readonly(false)\n , encrypted(false)\n , beginpagenum(0)\n , beginfnnum(0)\n , countfn(0)\n , splinetext(0)\n , splinefn(0)\n , spfnfn(0)\n , fnchar(0)\n , fnlinetype(0)\n , borderline(0)\n , empty_line_hide(0)\n , table_move(0)\n , compressed(0)\n , reserved3(0)\n , info_block_len(0)\n , info_block(NULL)\n{\n back_info.isset = false;\n memset(reserved1, 0, sizeof(reserved1));\n memset(annotation, 0, sizeof(annotation));\n memset(bordermargin, 0, sizeof(bordermargin));\n}\n\nHWPInfo::~HWPInfo(void)\n{\n if (info_block)\n delete[]info_block;\n info_block = 0;\n}\n\n\n\/**\n * 문서정보를 읽어들이는 함수 ( 128 bytes )\n * 문서정보는 파일인식정보( 30 bytes ) 다음에 위치한 정보이다.\n *\/\nbool HWPInfo::Read(HWPFile & hwpf)\n{\n hwpf.Read2b(&cur_col, 1); \/* 문서를 저장할 당시의 커서가 위치한 문단번호 *\/\n hwpf.Read2b(&cur_row, 1); \/* 문단 칸 *\/\n\n hwpf.Read1b(&paper.paper_kind, 1); \/* 용지 종류 *\/\n hwpf.Read1b(&paper.paper_direction, 1); \/* 용지 방향 *\/\n\n\/\/ paper geometry information\n paper.paper_height = (short) hwpf.Read2b(); \/* 용지 길이 *\/\n paper.paper_width = (short) hwpf.Read2b(); \/* 용지 너비 *\/\n paper.top_margin = (short) hwpf.Read2b(); \/* 위쪽 여백 *\/\n paper.bottom_margin = (short) hwpf.Read2b(); \/* 아래쪽 여백 *\/\n paper.left_margin = (short) hwpf.Read2b(); \/* 왼쪽 여백 *\/\n paper.right_margin = (short) hwpf.Read2b(); \/* 오른쪽 여백 *\/\n paper.header_length = (short) hwpf.Read2b(); \/* 머리말 길이 *\/\n paper.footer_length = (short) hwpf.Read2b(); \/* 꼬리말 길이 *\/\n paper.gutter_length = (short) hwpf.Read2b(); \/* 제본여백 *\/\n hwpf.Read2b(&readonly, 1); \/* 예약 *\/\n hwpf.Read1b(reserved1, 4); \/* 예약 *\/\n hwpf.Read1b(&chain_info.chain_page_no, 1); \/* 쪽 번호 연결 1-연결, 0-새로시작 (연결인쇄에서 사용) *\/\n hwpf.Read1b(&chain_info.chain_footnote_no, 1);\/* 각주번호 연결 1-연결 0-새로시작 *\/\n \/* 연결인쇄할 파일의 이름 *\/\n hwpf.Read1b(chain_info.chain_filename, CHAIN_MAX_PATH);\n\n hwpf.Read1b(annotation, ANNOTATION_LEN); \/* 덧붙이는 말 ( 파일 저장할 때 덧붙이는 말에 지정한 내용 ) *\/\n hwpf.Read2b(&encrypted, 1); \/* 암호 여부 0-보통파일, 그외-암호걸린 파일 *\/\n\/\/hwpf.Read1b(reserved2, 6); \/* 아래 3개의값으로 바뀌었다. *\/\n hwpf.Read2b(&beginpagenum,1); \/* 페이지시작번호 *\/\n\n\/\/ footnote\n hwpf.Read2b(&beginfnnum,1); \/* 각주 시작번호 *\/\n hwpf.Read2b(&countfn,1); \/* 각주 갯수 *\/\n splinetext = (short) hwpf.Read2b();\n splinefn = (short) hwpf.Read2b();\n spfnfn = (short) hwpf.Read2b();\n hwpf.Read1b(&fnchar, 1);\n hwpf.Read1b(&fnlinetype, 1);\n\/\/ border layout\n for (int ii = 0; ii < 4; ++ii)\n bordermargin[ii] = (short) hwpf.Read2b();\n hwpf.Read2b(&borderline, 1);\n\n hwpf.Read1b(&empty_line_hide, 1);\n hwpf.Read1b(&table_move, 1);\n hwpf.Read1b(&compressed, 1);\n\n hwpf.Read1b(&reserved3, 1);\n\n hwpf.Read2b(&info_block_len, 1);\n if (hwpf.State())\n return false;\n\n\/* 문서 요약을 읽는다. *\/\n if (!summary.Read(hwpf))\n return false;\n if (info_block_len > 0)\n {\n info_block = new unsigned char[info_block_len + 1];\n\n if (0 == info_block ||\n !HWPReadInfoBlock(info_block, info_block_len, hwpf))\n return false;\n }\n\n\/* hwpf의 값을 재설정 한다. *\/\n hwpf.compressed = compressed ? true : false;\n hwpf.encrypted = encrypted ? true : false;\n hwpf.info_block_len = info_block_len;\n hwpf.SetCompressed(hwpf.compressed);\n\n return (!hwpf.State());\n}\n\n\n\/\/ Document Summary\n\nbool HWPSummary::Read(HWPFile & hwpf)\n{\n hwpf.Read2b(title, 56);\n hwpf.Read2b(subject, 56);\n hwpf.Read2b(author, 56);\n hwpf.Read2b(date, 56);\n hwpf.Read2b(keyword[0], 56);\n hwpf.Read2b(keyword[1], 56);\n hwpf.Read2b(etc[0], 56);\n hwpf.Read2b(etc[1], 56);\n hwpf.Read2b(etc[2], 56);\n\n return (!hwpf.State());\n}\n\n\nbool ParaShape::Read(HWPFile & hwpf)\n{\n pagebreak = 0;\n left_margin = (short) hwpf.Read2b();\n right_margin = (short) hwpf.Read2b();\n indent = (short) hwpf.Read2b();\n lspacing = (short) hwpf.Read2b();\n pspacing_next = (short) hwpf.Read2b();\n\n hwpf.Read1b(&condense, 1);\n hwpf.Read1b(&arrange_type, 1);\n for (int ii = 0; ii < MAXTABS; ii++)\n {\n hwpf.Read1b(&tabs[ii].type, 1);\n hwpf.Read1b(&tabs[ii].dot_continue, 1);\n tabs[ii].position = (short) hwpf.Read2b();\n }\n hwpf.Read1b(&coldef.ncols, 1);\n hwpf.Read1b(&coldef.separator, 1);\n coldef.spacing = (short) hwpf.Read2b();\n coldef.columnlen = (short) hwpf.Read2b();\n coldef.columnlen0 = (short) hwpf.Read2b();\n hwpf.Read1b(&shade, 1);\n hwpf.Read1b(&outline, 1);\n hwpf.Read1b(&outline_continue, 1);\n pspacing_prev = (short) hwpf.Read2b();\n\n hwpf.Read1b(reserved, 2);\n return (!hwpf.State());\n}\n\n\nbool CharShape::Read(HWPFile & hwpf)\n{\n size = (short) hwpf.Read2b();\n hwpf.Read1b(font, NLanguage);\n hwpf.Read1b(ratio, NLanguage);\n hwpf.Read1b(space, NLanguage);\n hwpf.Read1b(color, 2);\n hwpf.Read1b(&shade, 1);\n hwpf.Read1b(&attr, 1);\n hwpf.Read1b(reserved, 4);\n\n return (!hwpf.State());\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>WaE: implicit conversion from bool to 'short'<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"precompile.h\"\n\n#include \"hwplib.h\"\n#include \"hinfo.h\"\n#include \"hwpfile.h\"\n\n\/\/ Info Block\n\n\nstatic bool HWPReadInfoBlock(void *ptr, int len, HWPFile & hwpf)\n{\n hwpf.info_block_len = len;\n if (0 == len)\n return true;\n else\n return hwpf.ReadBlock(ptr, len) ? true : false;\n}\n\n\n\/\/ Document Information\nHWPInfo::HWPInfo()\n : cur_col(0)\n , cur_row(0)\n , readonly(0)\n , encrypted(0)\n , beginpagenum(0)\n , beginfnnum(0)\n , countfn(0)\n , splinetext(0)\n , splinefn(0)\n , spfnfn(0)\n , fnchar(0)\n , fnlinetype(0)\n , borderline(0)\n , empty_line_hide(0)\n , table_move(0)\n , compressed(0)\n , reserved3(0)\n , info_block_len(0)\n , info_block(NULL)\n{\n back_info.isset = false;\n memset(reserved1, 0, sizeof(reserved1));\n memset(annotation, 0, sizeof(annotation));\n memset(bordermargin, 0, sizeof(bordermargin));\n}\n\nHWPInfo::~HWPInfo(void)\n{\n if (info_block)\n delete[]info_block;\n info_block = 0;\n}\n\n\n\/**\n * 문서정보를 읽어들이는 함수 ( 128 bytes )\n * 문서정보는 파일인식정보( 30 bytes ) 다음에 위치한 정보이다.\n *\/\nbool HWPInfo::Read(HWPFile & hwpf)\n{\n hwpf.Read2b(&cur_col, 1); \/* 문서를 저장할 당시의 커서가 위치한 문단번호 *\/\n hwpf.Read2b(&cur_row, 1); \/* 문단 칸 *\/\n\n hwpf.Read1b(&paper.paper_kind, 1); \/* 용지 종류 *\/\n hwpf.Read1b(&paper.paper_direction, 1); \/* 용지 방향 *\/\n\n\/\/ paper geometry information\n paper.paper_height = (short) hwpf.Read2b(); \/* 용지 길이 *\/\n paper.paper_width = (short) hwpf.Read2b(); \/* 용지 너비 *\/\n paper.top_margin = (short) hwpf.Read2b(); \/* 위쪽 여백 *\/\n paper.bottom_margin = (short) hwpf.Read2b(); \/* 아래쪽 여백 *\/\n paper.left_margin = (short) hwpf.Read2b(); \/* 왼쪽 여백 *\/\n paper.right_margin = (short) hwpf.Read2b(); \/* 오른쪽 여백 *\/\n paper.header_length = (short) hwpf.Read2b(); \/* 머리말 길이 *\/\n paper.footer_length = (short) hwpf.Read2b(); \/* 꼬리말 길이 *\/\n paper.gutter_length = (short) hwpf.Read2b(); \/* 제본여백 *\/\n hwpf.Read2b(&readonly, 1); \/* 예약 *\/\n hwpf.Read1b(reserved1, 4); \/* 예약 *\/\n hwpf.Read1b(&chain_info.chain_page_no, 1); \/* 쪽 번호 연결 1-연결, 0-새로시작 (연결인쇄에서 사용) *\/\n hwpf.Read1b(&chain_info.chain_footnote_no, 1);\/* 각주번호 연결 1-연결 0-새로시작 *\/\n \/* 연결인쇄할 파일의 이름 *\/\n hwpf.Read1b(chain_info.chain_filename, CHAIN_MAX_PATH);\n\n hwpf.Read1b(annotation, ANNOTATION_LEN); \/* 덧붙이는 말 ( 파일 저장할 때 덧붙이는 말에 지정한 내용 ) *\/\n hwpf.Read2b(&encrypted, 1); \/* 암호 여부 0-보통파일, 그외-암호걸린 파일 *\/\n\/\/hwpf.Read1b(reserved2, 6); \/* 아래 3개의값으로 바뀌었다. *\/\n hwpf.Read2b(&beginpagenum,1); \/* 페이지시작번호 *\/\n\n\/\/ footnote\n hwpf.Read2b(&beginfnnum,1); \/* 각주 시작번호 *\/\n hwpf.Read2b(&countfn,1); \/* 각주 갯수 *\/\n splinetext = (short) hwpf.Read2b();\n splinefn = (short) hwpf.Read2b();\n spfnfn = (short) hwpf.Read2b();\n hwpf.Read1b(&fnchar, 1);\n hwpf.Read1b(&fnlinetype, 1);\n\/\/ border layout\n for (int ii = 0; ii < 4; ++ii)\n bordermargin[ii] = (short) hwpf.Read2b();\n hwpf.Read2b(&borderline, 1);\n\n hwpf.Read1b(&empty_line_hide, 1);\n hwpf.Read1b(&table_move, 1);\n hwpf.Read1b(&compressed, 1);\n\n hwpf.Read1b(&reserved3, 1);\n\n hwpf.Read2b(&info_block_len, 1);\n if (hwpf.State())\n return false;\n\n\/* 문서 요약을 읽는다. *\/\n if (!summary.Read(hwpf))\n return false;\n if (info_block_len > 0)\n {\n info_block = new unsigned char[info_block_len + 1];\n\n if (0 == info_block ||\n !HWPReadInfoBlock(info_block, info_block_len, hwpf))\n return false;\n }\n\n\/* hwpf의 값을 재설정 한다. *\/\n hwpf.compressed = compressed ? true : false;\n hwpf.encrypted = encrypted ? true : false;\n hwpf.info_block_len = info_block_len;\n hwpf.SetCompressed(hwpf.compressed);\n\n return (!hwpf.State());\n}\n\n\n\/\/ Document Summary\n\nbool HWPSummary::Read(HWPFile & hwpf)\n{\n hwpf.Read2b(title, 56);\n hwpf.Read2b(subject, 56);\n hwpf.Read2b(author, 56);\n hwpf.Read2b(date, 56);\n hwpf.Read2b(keyword[0], 56);\n hwpf.Read2b(keyword[1], 56);\n hwpf.Read2b(etc[0], 56);\n hwpf.Read2b(etc[1], 56);\n hwpf.Read2b(etc[2], 56);\n\n return (!hwpf.State());\n}\n\n\nbool ParaShape::Read(HWPFile & hwpf)\n{\n pagebreak = 0;\n left_margin = (short) hwpf.Read2b();\n right_margin = (short) hwpf.Read2b();\n indent = (short) hwpf.Read2b();\n lspacing = (short) hwpf.Read2b();\n pspacing_next = (short) hwpf.Read2b();\n\n hwpf.Read1b(&condense, 1);\n hwpf.Read1b(&arrange_type, 1);\n for (int ii = 0; ii < MAXTABS; ii++)\n {\n hwpf.Read1b(&tabs[ii].type, 1);\n hwpf.Read1b(&tabs[ii].dot_continue, 1);\n tabs[ii].position = (short) hwpf.Read2b();\n }\n hwpf.Read1b(&coldef.ncols, 1);\n hwpf.Read1b(&coldef.separator, 1);\n coldef.spacing = (short) hwpf.Read2b();\n coldef.columnlen = (short) hwpf.Read2b();\n coldef.columnlen0 = (short) hwpf.Read2b();\n hwpf.Read1b(&shade, 1);\n hwpf.Read1b(&outline, 1);\n hwpf.Read1b(&outline_continue, 1);\n pspacing_prev = (short) hwpf.Read2b();\n\n hwpf.Read1b(reserved, 2);\n return (!hwpf.State());\n}\n\n\nbool CharShape::Read(HWPFile & hwpf)\n{\n size = (short) hwpf.Read2b();\n hwpf.Read1b(font, NLanguage);\n hwpf.Read1b(ratio, NLanguage);\n hwpf.Read1b(space, NLanguage);\n hwpf.Read1b(color, 2);\n hwpf.Read1b(&shade, 1);\n hwpf.Read1b(&attr, 1);\n hwpf.Read1b(reserved, 4);\n\n return (!hwpf.State());\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <queue>\n#include <map>\n#include <set>\n#include <stack>\n#include <cstring>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <cmath>\n#include <list>\n#include <bitset>\n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pair<int, int>pii;\ntypedef pair<ll, ll>pll;\ntypedef pair<double, double>pdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<<endl;\n#define IOS ios::sync_with_stdio(0);cin.tie(0);\n\n\n\nint p[2017],dp[2017];\nint n;\nvoid Init(){\n\n\tmemset(p,2017*sizeof(int),0);\n\tmemset(dp,2017*sizeof(int),0);\n\n\tREP(i,1,n)\n\t\tscanf(\"%d\",p+i);\n\n\tsort(p+1,p+1+n);\n\treturn ;\n}\n\nvoid Solve(){\n\t\n\tint Max=p[n];\n\tint m;\n\tscanf(\"%d\",&m);\n\n\tm-=5;\n\n\tREP(i,1,n-1)\n\tREP(j,m,p[i])\n\tdp[j]=max(dp[j],dp[j-p[i]]+p[i]);\n\n\tprint(m+5-dp[m]-Max);\n\n\treturn ;\n}\n\nint main(){\n\n\tfreopen(\"hdu2546.in\",\"r\",stdin);\n\n\n\t\n\twhile(scanf(\"%d\",&n)&&n)\n\tInit(),Solve();\n\treturn 0;\n}<commit_msg>update hdu2546<commit_after>#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <queue>\n#include <map>\n#include <set>\n#include <stack>\n#include <cstring>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <cmath>\n#include <list>\n#include <bitset>\n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pair<int, int>pii;\ntypedef pair<ll, ll>pll;\ntypedef pair<double, double>pdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<<endl;\n#define IOS ios::sync_with_stdio(0);cin.tie(0);\n\n\n\nint p[2017],dp[2017];\nint n;\nvoid Init(){\n\n\tmemset(p,2017*sizeof(int),0);\n\tmemset(dp,2017*sizeof(int),0);\n\n\tREP(i,1,n)\n\t\tscanf(\"%d\",p+i);\n\n\tsort(p+1,p+1+n);\n\treturn ;\n}\n\nvoid Solve(){\n\t\n\tint Max=p[n];\n\tint m;\n\tscanf(\"%d\",&m);\n\n\tif(m<5){\n\n\t\tprint(m);\n\t\treturn ;\n\t}\n\tm-=5;\n\n\tREP(i,1,n-1)\n\tREP(j,m,p[i])\n\tdp[j]=max(dp[j],dp[j-p[i]]+p[i]);\n\n\tprint(m+5-dp[m]-Max);\n\n\treturn ;\n}\n\nint main(){\n\n\tfreopen(\"hdu2546.in\",\"r\",stdin);\n\n\n\t\n\twhile(scanf(\"%d\",&n)&&n)\n\tInit(),Solve();\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*! \\file version.hpp\n \\brief Macros to detect cereal version\n\n These macros can assist in determining the version of cereal. Be\n warned that cereal is not guaranteed to be compatible across\n different versions. For more information on releases of cereal,\n see https:\/\/github.com\/USCiLab\/cereal\/releases.\n\n \\ingroup utility *\/\n\/*\n Copyright (c) 2018, Shane Grant\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 met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of cereal nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY 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\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#ifndef CEREAL_VERSION_HPP_\n#define CEREAL_VERSION_HPP_\n\n\/\/! The major version\n#define CEREAL_VERSION_MAJOR 1\n\/\/! The minor version\n#define CEREAL_VERSION_MINOR 2\n\/\/! The patch version\n#define CEREAL_VERSION_PATCH 3\n\n\/\/! The full version as a single number\n#define CEREAL_VERSION (CEREAL_VERSION_MAJOR * 10000 \\\n + CEREAL_VERSION_MINOR * 100 \\\n + CEREAL_VERSION_PATCH)\n\n#endif \/\/ CEREAL_VERSION_HPP_\n<commit_msg>Update version to 1.3.0<commit_after>\/*! \\file version.hpp\n \\brief Macros to detect cereal version\n\n These macros can assist in determining the version of cereal. Be\n warned that cereal is not guaranteed to be compatible across\n different versions. For more information on releases of cereal,\n see https:\/\/github.com\/USCiLab\/cereal\/releases.\n\n \\ingroup utility *\/\n\/*\n Copyright (c) 2018, Shane Grant\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 met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of cereal nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY 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\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#ifndef CEREAL_VERSION_HPP_\n#define CEREAL_VERSION_HPP_\n\n\/\/! The major version\n#define CEREAL_VERSION_MAJOR 1\n\/\/! The minor version\n#define CEREAL_VERSION_MINOR 3\n\/\/! The patch version\n#define CEREAL_VERSION_PATCH 0\n\n\/\/! The full version as a single number\n#define CEREAL_VERSION (CEREAL_VERSION_MAJOR * 10000 \\\n + CEREAL_VERSION_MINOR * 100 \\\n + CEREAL_VERSION_PATCH)\n\n#endif \/\/ CEREAL_VERSION_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: msci.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: dbo $ $Date: 2001-08-01 10:09:58 $\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#include <windows.h>\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#define MSVC_ExceptionCode 0xe06d7363\n\nclass type_info;\ntypedef struct _uno_Any uno_Any;\ntypedef struct _uno_Mapping uno_Mapping;\n\nnamespace CPPU_CURRENT_NAMESPACE\n{\n\n\/\/==================================================================================================\ntype_info * msci_getRTTI(\n ::rtl::OUString const & rUNOname ) throw ();\n\n\/\/==================================================================================================\nsal_Int32 msci_filterCppException(\n LPEXCEPTION_POINTERS pPointers, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno );\n\n\/\/==================================================================================================\nvoid msci_raiseException(\n uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );\n\n}\n\n<commit_msg>INTEGRATION: CWS unopkg (1.3.100); FILE MERGED 2003\/09\/26 12:58:00 dbo 1.3.100.1: #112449# fixing msci bridge rethrow<commit_after>\/*************************************************************************\n *\n * $RCSfile: msci.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2003-10-06 13: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#include <windows.h>\n#include \"rtl\/ustring.hxx\"\n\n\nclass type_info;\ntypedef struct _uno_Any uno_Any;\ntypedef struct _uno_Mapping uno_Mapping;\n\nnamespace CPPU_CURRENT_NAMESPACE\n{\n\nconst long MSVC_ExceptionCode = 0xe06d7363;\nconst long MSVC_magic_number = 0x19930520L;\n\n\/\/==============================================================================\ntype_info * msci_getRTTI( ::rtl::OUString const & rUNOname );\n\n\/\/==============================================================================\nint msci_filterCppException(\n EXCEPTION_POINTERS * pPointers, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno );\n\n\/\/==============================================================================\nvoid msci_raiseException(\n uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Load transforms and build RGB volumes from images\n\n#include \"boost\/filesystem.hpp\"\n\n#include \"itkRGBPixel.h\"\n#include \"itkVectorResampleImageFilter.h\"\n\n\/\/ my files\n#include \"Stack.hpp\"\n#include \"StackInitializers.hpp\"\n#include \"RegistrationBuilder.hpp\"\n#include \"StackAligner.hpp\"\n#include \"StackIOHelpers.hpp\"\n#include \"IOHelpers.hpp\"\n#include \"StackTransforms.hpp\"\n#include \"Dirs.hpp\"\n#include \"Parameters.hpp\"\n#include \"Profiling.hpp\"\n\n\nvoid checkUsage(int argc, char const *argv[]) {\n if( argc < 3 )\n {\n cerr << \"\\nUsage: \" << endl;\n cerr << argv[0] << \" dataSet outputDir (loResDSRatio hiResDSRatio roi)\\n\\n\";\n exit(EXIT_FAILURE);\n }\n}\n\nint main(int argc, char const *argv[]) {\n\t\/\/ Verify the number of parameters in the command line\n\tcheckUsage(argc, argv);\n\t\n\t\/\/ Process command line arguments\n Dirs::SetDataSet(argv[1]);\n Dirs::SetOutputDirName(argv[2]);\n \n \/\/ set region of interest\n string roi;\n if(argc >=6) roi = argv[5];\n else roi = \"whole_heart\";\n \n \/\/ get file names\n vector< string > LoResFilePaths, HiResFilePaths;\n LoResFilePaths = getFilePaths(Dirs::BlockDir(), Dirs::SliceFile());\n HiResFilePaths = getFilePaths(Dirs::SliceDir(), Dirs::SliceFile());\n\t\n \/\/ initialise stack with correct spacings, sizes, transforms etc\n typedef itk::RGBPixel< unsigned char > PixelType;\n typedef Stack< PixelType, itk::VectorResampleImageFilter, itk::VectorLinearInterpolateImageFunction > StackType;\n StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFilePaths);\n StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFilePaths);\n boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImages, roi);\n boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImages, roi);\n \n HiResStack->SetDefaultPixelValue( 255 );\n \n \/\/ Load transforms from files\n \/\/ get downsample ratios\n string LoResDownsampleRatio, HiResDownsampleRatio;\n if( argc >= 5 )\n {\n LoResDownsampleRatio = argv[3];\n HiResDownsampleRatio = argv[4];\n }\n else\n {\n boost::shared_ptr<YAML::Node> downsample_ratios = config(Dirs::GetDataSet() + \"\/downsample_ratios.yml\");\n (*downsample_ratios)[\"LoRes\"] >> LoResDownsampleRatio;\n (*downsample_ratios)[\"HiRes\"] >> HiResDownsampleRatio;\n }\n \n \/\/ read transforms from directories labeled by both ds ratios\n using namespace boost::filesystem;\n string LoResTransformsDir = Dirs::ResultsDir() + \"LoResTransforms_\" + LoResDownsampleRatio + \"_\" + HiResDownsampleRatio;\n string HiResTransformsDir = Dirs::ResultsDir() + \"HiResTransforms_\" + LoResDownsampleRatio + \"_\" + HiResDownsampleRatio;\n \n Load(*LoResStack, LoResFilePaths, LoResTransformsDir);\n Load(*HiResStack, HiResFilePaths, HiResTransformsDir);\n \n \/\/ move stack origins to ROI\n itk::Vector< double, 2 > translation = StackTransforms::GetLoResTranslation(roi) - StackTransforms::GetLoResTranslation(\"whole_heart\");\n StackTransforms::Translate(*LoResStack, translation);\n StackTransforms::Translate(*HiResStack, translation);\n \n \/\/ generate images\n LoResStack->updateVolumes();\n HiResStack->updateVolumes();\n \n \/\/ Write bmps\n using namespace boost::filesystem;\n create_directory( Dirs::ColourDir() );\n \n writeImage< StackType::VolumeType >( LoResStack->GetVolume(), (path( Dirs::ColourDir() ) \/ \"LoRes.mha\").string());\n writeImage< StackType::VolumeType >( HiResStack->GetVolume(), (path( Dirs::ColourDir() ) \/ \"HiRes.mha\").string());\n \n return EXIT_SUCCESS;\n}\n<commit_msg>Tidied up string initialisation.<commit_after>\/\/ Load transforms and build RGB volumes from images\n\n#include \"boost\/filesystem.hpp\"\n\n#include \"itkRGBPixel.h\"\n#include \"itkVectorResampleImageFilter.h\"\n\n\/\/ my files\n#include \"Stack.hpp\"\n#include \"StackInitializers.hpp\"\n#include \"RegistrationBuilder.hpp\"\n#include \"StackAligner.hpp\"\n#include \"StackIOHelpers.hpp\"\n#include \"IOHelpers.hpp\"\n#include \"StackTransforms.hpp\"\n#include \"Dirs.hpp\"\n#include \"Parameters.hpp\"\n#include \"Profiling.hpp\"\n\n\nvoid checkUsage(int argc, char const *argv[]) {\n if( argc < 3 )\n {\n cerr << \"\\nUsage: \" << endl;\n cerr << argv[0] << \" dataSet outputDir (loResDSRatio hiResDSRatio roi)\\n\\n\";\n exit(EXIT_FAILURE);\n }\n}\n\nint main(int argc, char const *argv[]) {\n\t\/\/ Verify the number of parameters in the command line\n\tcheckUsage(argc, argv);\n\t\n\t\/\/ Process command line arguments\n Dirs::SetDataSet(argv[1]);\n Dirs::SetOutputDirName(argv[2]);\n \n \/\/ set region of interest\n string roi = argc >=6 ? argv[5] : \"whole_heart\";\n \n \/\/ get file names\n vector< string > LoResFilePaths, HiResFilePaths;\n LoResFilePaths = getFilePaths(Dirs::BlockDir(), Dirs::SliceFile());\n HiResFilePaths = getFilePaths(Dirs::SliceDir(), Dirs::SliceFile());\n\t\n \/\/ initialise stack with correct spacings, sizes, transforms etc\n typedef itk::RGBPixel< unsigned char > PixelType;\n typedef Stack< PixelType, itk::VectorResampleImageFilter, itk::VectorLinearInterpolateImageFunction > StackType;\n StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFilePaths);\n StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFilePaths);\n boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImages, roi);\n boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImages, roi);\n \n HiResStack->SetDefaultPixelValue( 255 );\n \n \/\/ Load transforms from files\n \/\/ get downsample ratios\n string LoResDownsampleRatio, HiResDownsampleRatio;\n if( argc >= 5 )\n {\n LoResDownsampleRatio = argv[3];\n HiResDownsampleRatio = argv[4];\n }\n else\n {\n boost::shared_ptr<YAML::Node> downsample_ratios = config(Dirs::GetDataSet() + \"\/downsample_ratios.yml\");\n (*downsample_ratios)[\"LoRes\"] >> LoResDownsampleRatio;\n (*downsample_ratios)[\"HiRes\"] >> HiResDownsampleRatio;\n }\n \n \/\/ read transforms from directories labeled by both ds ratios\n using namespace boost::filesystem;\n string LoResTransformsDir = Dirs::ResultsDir() + \"LoResTransforms_\" + LoResDownsampleRatio + \"_\" + HiResDownsampleRatio;\n string HiResTransformsDir = Dirs::ResultsDir() + \"HiResTransforms_\" + LoResDownsampleRatio + \"_\" + HiResDownsampleRatio;\n \n Load(*LoResStack, LoResFilePaths, LoResTransformsDir);\n Load(*HiResStack, HiResFilePaths, HiResTransformsDir);\n \n \/\/ move stack origins to ROI\n itk::Vector< double, 2 > translation = StackTransforms::GetLoResTranslation(roi) - StackTransforms::GetLoResTranslation(\"whole_heart\");\n StackTransforms::Translate(*LoResStack, translation);\n StackTransforms::Translate(*HiResStack, translation);\n \n \/\/ generate images\n LoResStack->updateVolumes();\n HiResStack->updateVolumes();\n \n \/\/ Write bmps\n using namespace boost::filesystem;\n create_directory( Dirs::ColourDir() );\n \n writeImage< StackType::VolumeType >( LoResStack->GetVolume(), (path( Dirs::ColourDir() ) \/ \"LoRes.mha\").string());\n writeImage< StackType::VolumeType >( HiResStack->GetVolume(), (path( Dirs::ColourDir() ) \/ \"HiRes.mha\").string());\n \n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"responseserializer.h\"\n#include \"responsedata.h\"\n#include <sstream>\n\nstd::string ApiMock::ResponseSerializer::statusCodeDescription(HTTP_RESPONSE_CODE responseCode) {\n\tswitch (responseCode) {\n\tcase HTTP_CONTINUE:\t\t\t\t\t\t\treturn \"Continue\";\n\tcase HTTP_SWITCHING_PROTOCOLS:\t\t\t\treturn \"Switching Protocols\";\n\tcase HTTP_OK:\t\t\t\t\t\t\t\treturn \"OK\";\n\tcase HTTP_CREATED:\t\t\t\t\t\t\treturn \"Created\";\n\tcase HTTP_ACCEPTED:\t\t\t\t\t\t\treturn \"Accepted\";\n\tcase HTTP_NON_AUTHORATIVE_INFO:\t\t\t\treturn \"Non-Authoritative Information\";\n\tcase HTTP_NO_CONTENT:\t\t\t\t\t\treturn \"No Content\";\n\tcase HTTP_RESET_CONTENT:\t\t\t\t\treturn \"Reset Content\";\n\tcase HTTP_PARTIAL_CONTENT:\t\t\t\t\treturn \"Partial Content\";\n\tcase HTTP_MULTIPLE_CHOICES:\t\t\t\t\treturn \"Multiple Choices\";\n\tcase HTTP_MOVED_PERMANENTLY:\t\t\t\treturn \"Moved Permanently\";\n\tcase HTTP_FOUND:\t\t\t\t\t\t\treturn \"Found\";\n\tcase HTTP_SEE_OTHER:\t\t\t\t\t\treturn \"See Other\";\n\tcase HTTP_NOT_MODIFIED:\t\t\t\t\t\treturn \"Not Modified\";\n\tcase HTTP_USE_PROXY:\t\t\t\t\t\treturn \"Use Proxy\";\n\tcase HTTP_TEMPORARY_REDIRECT:\t\t\t\treturn \"Temporary Redirect\";\n\tcase HTTP_BAD_REQUEST:\t\t\t\t\t\treturn \"Bad Request\";\n\tcase HTTP_UNAUTHORIZED:\t\t\t\t\t\treturn \"Unauthorized\";\n\tcase HTTP_FORBIDDEN:\t\t\t\t\t\treturn \"Forbidden\";\n\tcase HTTP_NOT_FOUND:\t\t\t\t\t\treturn \"Not Found\";\n\tcase HTTP_METHOD_NOT_ALLOWED:\t\t\t\treturn \"Method Not Allowed\";\n\tcase HTTP_NOT_ACCEPTABLE:\t\t\t\t\treturn \"Not Acceptable\";\n\tcase HTTP_PROXY_AUTH_REQUIRED:\t\t\t\treturn \"Proxy Authentication Required\";\n\tcase HTTP_REQUEST_TIMEOUT:\t\t\t\t\treturn \"Request Timeout\";\n\tcase HTTP_CONFLICT:\t\t\t\t\t\t\treturn \"Conflict\";\n\tcase HTTP_GONE:\t\t\t\t\t\t\t\treturn \"Gone\";\n\tcase HTTP_LENGTH_REQUIRED:\t\t\t\t\treturn \"Length Required\";\n\tcase HTTP_PRECONDITION_FAILED:\t\t\t\treturn \"Precondition Failed\";\n\tcase HTTP_REQUEST_ENTITY_TOO_LARGE:\t\t\treturn \"Request Entity Too Large\";\n\tcase HTTP_REQUEST_URI_TOO_LONG:\t\t\t\treturn \"Request-URI Too Long\";\n\tcase HTTP_UNSUPPORTED_MEDIA_TYPE:\t\t\treturn \"Unsupported Media Type\";\n\tcase HTTP_REQUREST_RANGE_NOT_SATISFIABLE:\treturn \"Requested Range Not Satisfiable\";\n\tcase HTTP_EXPECTATION_FAILED:\t\t\t\treturn \"Expectation Failed\";\n\tcase HTTP_INTERNAL_SERVER_ERROR:\t\t\treturn \"Internal Server Error\";\n\tcase HTTP_NOT_IMPLEMENTED:\t\t\t\t\treturn \"Not Implemented\";\n\tcase HTTP_BAD_GATEWAY:\t\t\t\t\t\treturn \"Bad Gateway\";\n\tcase HTTP_SERVICE_UNAVAILABLE:\t\t\t\treturn \"Service Unavailable\";\n\tcase HTTP_GATEWAY_TIMEOUT:\t\t\t\t\treturn \"Gateway Timeout\";\n\tcase HTTP_VERSION_NOT_SUPPORTED:\t\t\treturn \"Version Not Supported\";\n\tdefault:\t\t\t\t\t\t\t\t\treturn \"\";\n\n\n\t}\n}\n\nstd::string ApiMock::ResponseSerializer::serialize(ResponseData response) {\n\tconst std::string CRLF = \"\\r\\n\";\n\tstd::stringstream ss;\n\n\treturn ss.str();\n}<commit_msg>Implement a simple response serializer<commit_after>#include \"responseserializer.h\"\n#include \"responsedata.h\"\n#include <sstream>\n\nstd::string ApiMock::ResponseSerializer::statusCodeDescription(HTTP_RESPONSE_CODE responseCode) {\n\tswitch (responseCode) {\n\tcase HTTP_CONTINUE:\t\t\t\t\t\t\treturn \"Continue\";\n\tcase HTTP_SWITCHING_PROTOCOLS:\t\t\t\treturn \"Switching Protocols\";\n\tcase HTTP_OK:\t\t\t\t\t\t\t\treturn \"OK\";\n\tcase HTTP_CREATED:\t\t\t\t\t\t\treturn \"Created\";\n\tcase HTTP_ACCEPTED:\t\t\t\t\t\t\treturn \"Accepted\";\n\tcase HTTP_NON_AUTHORATIVE_INFO:\t\t\t\treturn \"Non-Authoritative Information\";\n\tcase HTTP_NO_CONTENT:\t\t\t\t\t\treturn \"No Content\";\n\tcase HTTP_RESET_CONTENT:\t\t\t\t\treturn \"Reset Content\";\n\tcase HTTP_PARTIAL_CONTENT:\t\t\t\t\treturn \"Partial Content\";\n\tcase HTTP_MULTIPLE_CHOICES:\t\t\t\t\treturn \"Multiple Choices\";\n\tcase HTTP_MOVED_PERMANENTLY:\t\t\t\treturn \"Moved Permanently\";\n\tcase HTTP_FOUND:\t\t\t\t\t\t\treturn \"Found\";\n\tcase HTTP_SEE_OTHER:\t\t\t\t\t\treturn \"See Other\";\n\tcase HTTP_NOT_MODIFIED:\t\t\t\t\t\treturn \"Not Modified\";\n\tcase HTTP_USE_PROXY:\t\t\t\t\t\treturn \"Use Proxy\";\n\tcase HTTP_TEMPORARY_REDIRECT:\t\t\t\treturn \"Temporary Redirect\";\n\tcase HTTP_BAD_REQUEST:\t\t\t\t\t\treturn \"Bad Request\";\n\tcase HTTP_UNAUTHORIZED:\t\t\t\t\t\treturn \"Unauthorized\";\n\tcase HTTP_FORBIDDEN:\t\t\t\t\t\treturn \"Forbidden\";\n\tcase HTTP_NOT_FOUND:\t\t\t\t\t\treturn \"Not Found\";\n\tcase HTTP_METHOD_NOT_ALLOWED:\t\t\t\treturn \"Method Not Allowed\";\n\tcase HTTP_NOT_ACCEPTABLE:\t\t\t\t\treturn \"Not Acceptable\";\n\tcase HTTP_PROXY_AUTH_REQUIRED:\t\t\t\treturn \"Proxy Authentication Required\";\n\tcase HTTP_REQUEST_TIMEOUT:\t\t\t\t\treturn \"Request Timeout\";\n\tcase HTTP_CONFLICT:\t\t\t\t\t\t\treturn \"Conflict\";\n\tcase HTTP_GONE:\t\t\t\t\t\t\t\treturn \"Gone\";\n\tcase HTTP_LENGTH_REQUIRED:\t\t\t\t\treturn \"Length Required\";\n\tcase HTTP_PRECONDITION_FAILED:\t\t\t\treturn \"Precondition Failed\";\n\tcase HTTP_REQUEST_ENTITY_TOO_LARGE:\t\t\treturn \"Request Entity Too Large\";\n\tcase HTTP_REQUEST_URI_TOO_LONG:\t\t\t\treturn \"Request-URI Too Long\";\n\tcase HTTP_UNSUPPORTED_MEDIA_TYPE:\t\t\treturn \"Unsupported Media Type\";\n\tcase HTTP_REQUREST_RANGE_NOT_SATISFIABLE:\treturn \"Requested Range Not Satisfiable\";\n\tcase HTTP_EXPECTATION_FAILED:\t\t\t\treturn \"Expectation Failed\";\n\tcase HTTP_INTERNAL_SERVER_ERROR:\t\t\treturn \"Internal Server Error\";\n\tcase HTTP_NOT_IMPLEMENTED:\t\t\t\t\treturn \"Not Implemented\";\n\tcase HTTP_BAD_GATEWAY:\t\t\t\t\t\treturn \"Bad Gateway\";\n\tcase HTTP_SERVICE_UNAVAILABLE:\t\t\t\treturn \"Service Unavailable\";\n\tcase HTTP_GATEWAY_TIMEOUT:\t\t\t\t\treturn \"Gateway Timeout\";\n\tcase HTTP_VERSION_NOT_SUPPORTED:\t\t\treturn \"Version Not Supported\";\n\tdefault:\t\t\t\t\t\t\t\t\treturn \"\";\n\n\n\t}\n}\n\nstd::string ApiMock::ResponseSerializer::serialize(ResponseData response) {\n\tconst std::string CRLF = \"\\r\\n\";\n\tstd::stringstream ss;\n\n\t\/\/ Status line\n\tss << \"HTTP\/1.1 \";\n\tss << std::to_string(response.statusCode) << \" \" << statusCodeDescription(response.statusCode);\n\tss << CRLF;\n\t\n\t\/\/ Response headers\n\tfor (auto header : response.headers)\n\t\tss << header.first << \": \" << header.second << CRLF;\n\n\t\/\/ Body\n\tss << CRLF;\n\tss << response.body;\n\n\tauto r = ss.str();\n\treturn r;\n}<|endoftext|>"} {"text":"<commit_before>\/*\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 <vector>\n#include <iostream>\n#include <cctype>\n#include <iomanip>\n#include <sstream>\n#include <algorithm>\n\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/gzip.hpp\"\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/bind.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/tracker_manager.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n#include \"libtorrent\/http_connection.hpp\"\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/socket.hpp\"\n\nusing namespace libtorrent;\nusing boost::bind;\n\nnamespace libtorrent\n{\n\t\n\thttp_tracker_connection::http_tracker_connection(\n\t\tio_service& ios\n\t\t, connection_queue& cc\n\t\t, tracker_manager& man\n\t\t, tracker_request const& req\n\t\t, address bind_infc\n\t\t, boost::weak_ptr<request_callback> c\n\t\t, session_settings const& stn\n\t\t, proxy_settings const& ps\n\t\t, std::string const& auth)\n\t\t: tracker_connection(man, req, ios, bind_infc, c)\n\t\t, m_man(man)\n\t{\n\t\t\/\/ TODO: authentication\n\t\tstd::string url = req.url;\n\n\t\tif (req.kind == tracker_request::scrape_request)\n\t\t{\n\t\t\t\/\/ find and replace \"announce\" with \"scrape\"\n\t\t\t\/\/ in request\n\n\t\t\tstd::size_t pos = url.find(\"announce\");\n\t\t\tif (pos == std::string::npos)\n\t\t\t{\n\t\t\t\tfail(-1, (\"scrape is not available on url: '\"\n\t\t\t\t\t+ req.url +\"'\").c_str());\n\t\t\t\treturn;\n\t\t\t}\n\t\t\turl.replace(pos, 8, \"scrape\");\n\t\t}\n\t\t\n\t\t\/\/ if request-string already contains\n\t\t\/\/ some parameters, append an ampersand instead\n\t\t\/\/ of a question mark\n\t\tsize_t arguments_start = url.find('?');\n\t\tif (arguments_start != std::string::npos)\n\t\t\turl += \"&\";\n\t\telse\n\t\t\turl += \"?\";\n\n\t\turl += \"info_hash=\";\n\t\turl += escape_string(\n\t\t\treinterpret_cast<const char*>(req.info_hash.begin()), 20);\n\t\t\n\t\tif (req.kind == tracker_request::announce_request)\n\t\t{\n\t\t\turl += \"&peer_id=\";\n\t\t\turl += escape_string(\n\t\t\t\treinterpret_cast<const char*>(req.pid.begin()), 20);\n\n\t\t\turl += \"&port=\";\n\t\t\turl += boost::lexical_cast<std::string>(req.listen_port);\n\n\t\t\turl += \"&uploaded=\";\n\t\t\turl += boost::lexical_cast<std::string>(req.uploaded);\n\n\t\t\turl += \"&downloaded=\";\n\t\t\turl += boost::lexical_cast<std::string>(req.downloaded);\n\n\t\t\turl += \"&left=\";\n\t\t\turl += boost::lexical_cast<std::string>(req.left);\n\n\t\t\tif (req.event != tracker_request::none)\n\t\t\t{\n\t\t\t\tconst char* event_string[] = {\"completed\", \"started\", \"stopped\"};\n\t\t\t\turl += \"&event=\";\n\t\t\t\turl += event_string[req.event - 1];\n\t\t\t}\n\n\t\t\turl += \"&key=\";\n\t\t\tstd::stringstream key_string;\n\t\t\tkey_string << std::hex << req.key;\n\t\t\turl += key_string.str();\n\n\t\t\turl += \"&compact=1\";\n\n\t\t\turl += \"&numwant=\";\n\t\t\turl += boost::lexical_cast<std::string>(\n\t\t\t\t(std::min)(req.num_want, 999));\n\n\t\t\tif (stn.announce_ip != address())\n\t\t\t{\n\t\t\t\turl += \"&ip=\";\n\t\t\t\turl += stn.announce_ip.to_string();\n\t\t\t}\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\t\t\turl += \"&supportcrypto=1\";\n#endif\n\t\t\turl += \"&ipv6=\";\n\t\t\turl += req.ipv6;\n\n\t\t\t\/\/ extension that tells the tracker that\n\t\t\t\/\/ we don't need any peer_id's in the response\n\t\t\turl += \"&no_peer_id=1\";\n\t\t}\n\n\t\tm_tracker_connection.reset(new http_connection(ios, cc\n\t\t\t, boost::bind(&http_tracker_connection::on_response, self(), _1, _2, _3, _4)));\n\n\t\tint timeout = req.event==tracker_request::stopped\n\t\t\t?stn.stop_tracker_timeout\n\t\t\t:stn.tracker_completion_timeout;\n\n\t\tm_tracker_connection->get(url, seconds(timeout)\n\t\t\t, 1, &ps, 5, stn.user_agent, bind_infc);\n\n#if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING)\n\n\t\tboost::shared_ptr<request_callback> cb = requester();\n\t\tif (cb)\n\t\t{\n\t\t\tcb->debug_log(\"==> TRACKER_REQUEST [ url: \" + url + \" ]\");\n\t\t}\n#endif\n\t}\n\n\tvoid http_tracker_connection::close()\n\t{\n\t\tif (m_tracker_connection)\n\t\t{\n\t\t\tm_tracker_connection->close();\n\t\t\tm_tracker_connection.reset();\n\t\t}\n\t\ttracker_connection::close();\n\t}\n\n\tvoid http_tracker_connection::on_response(error_code const& ec\n\t\t, http_parser const& parser, char const* data, int size)\n\t{\n\t\t\/\/ keep this alive\n\t\tboost::intrusive_ptr<http_tracker_connection> me(this);\n\n\t\tif (ec && ec != asio::error::eof)\n\t\t{\n\t\t\tfail(-1, ec.message().c_str());\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (!parser.header_finished())\n\t\t{\n\t\t\tfail(-1, \"premature end of file\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (parser.status_code() != 200)\n\t\t{\n\t\t\tfail(parser.status_code(), parser.message().c_str());\n\t\t\treturn;\n\t\t}\n\t\n\t\tif (ec && ec != asio::error::eof)\n\t\t{\n\t\t\tfail(parser.status_code(), ec.message().c_str());\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t\/\/ handle tracker response\n\t\tentry e = bdecode(data, data + size);\n\n\t\tif (e.type() != entry::undefined_t)\n\t\t{\n\t\t\tparse(parser.status_code(), e);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::string error_str(\"invalid bencoding of tracker response: \\\"\");\n\t\t\tfor (char const* i = data, *end(data + size); i != end; ++i)\n\t\t\t{\n\t\t\t\tif (std::isprint(*i)) error_str += *i;\n\t\t\t\telse error_str += \"0x\" + boost::lexical_cast<std::string>((unsigned int)*i) + \" \";\n\t\t\t}\n\t\t\terror_str += \"\\\"\";\n\t\t\tfail(parser.status_code(), error_str.c_str());\n\t\t}\n\t\tclose();\n\t}\n\n\tbool http_tracker_connection::extract_peer_info(const entry& info, peer_entry& ret)\n\t{\n\t\t\/\/ extract peer id (if any)\n\t\tif (info.type() != entry::dictionary_t)\n\t\t{\n\t\t\tfail(-1, \"invalid response from tracker (invalid peer entry)\");\n\t\t\treturn false;\n\t\t}\n\t\tentry const* i = info.find_key(\"peer id\");\n\t\tif (i != 0)\n\t\t{\n\t\t\tif (i->type() != entry::string_t || i->string().length() != 20)\n\t\t\t{\n\t\t\t\tfail(-1, \"invalid response from tracker (invalid peer id)\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tstd::copy(i->string().begin(), i->string().end(), ret.pid.begin());\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ if there's no peer_id, just initialize it to a bunch of zeroes\n\t\t\tstd::fill_n(ret.pid.begin(), 20, 0);\n\t\t}\n\n\t\t\/\/ extract ip\n\t\ti = info.find_key(\"ip\");\n\t\tif (i == 0 || i->type() != entry::string_t)\n\t\t{\n\t\t\tfail(-1, \"invalid response from tracker\");\n\t\t\treturn false;\n\t\t}\n\t\tret.ip = i->string();\n\n\t\t\/\/ extract port\n\t\ti = info.find_key(\"port\");\n\t\tif (i == 0 || i->type() != entry::int_t)\n\t\t{\n\t\t\tfail(-1, \"invalid response from tracker\");\n\t\t\treturn false;\n\t\t}\n\t\tret.port = (unsigned short)i->integer();\n\n\t\treturn true;\n\t}\n\n\tvoid http_tracker_connection::parse(int status_code, entry const& e)\n\t{\n\t\tboost::shared_ptr<request_callback> cb = requester();\n\t\tif (!cb) return;\n\n\t\t\/\/ parse the response\n\t\tentry const* failure = e.find_key(\"failure reason\");\n\t\tif (failure && failure->type() == entry::string_t)\n\t\t{\n\t\t\tfail(status_code, failure->string().c_str());\n\t\t\treturn;\n\t\t}\n\n\t\tentry const* warning = e.find_key(\"warning message\");\n\t\tif (warning && warning->type() == entry::string_t)\n\t\t{\n\t\t\tcb->tracker_warning(tracker_req(), warning->string());\n\t\t}\n\n\t\tstd::vector<peer_entry> peer_list;\n\n\t\tif (tracker_req().kind == tracker_request::scrape_request)\n\t\t{\n\t\t\tstd::string ih = tracker_req().info_hash.to_string();\n\n\t\t\tentry const* files = e.find_key(\"files\");\n\t\t\tif (files == 0 || files->type() != entry::dictionary_t)\n\t\t\t{\n\t\t\t\tfail(-1, \"invalid or missing 'files' entry in scrape response\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tentry const* scrape_data = files->find_key(ih);\n\t\t\tif (scrape_data == 0 || scrape_data->type() != entry::dictionary_t)\n\t\t\t{\n\t\t\t\tfail(-1, \"missing or invalid info-hash entry in scrape response\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry const* complete = scrape_data->find_key(\"complete\");\n\t\t\tentry const* incomplete = scrape_data->find_key(\"incomplete\");\n\t\t\tentry const* downloaded = scrape_data->find_key(\"downloaded\");\n\t\t\tif (complete == 0 || incomplete == 0 || downloaded == 0\n\t\t\t\t|| complete->type() != entry::int_t\n\t\t\t\t|| incomplete->type() != entry::int_t\n\t\t\t\t|| downloaded->type() != entry::int_t)\n\t\t\t{\n\t\t\t\tfail(-1, \"missing 'complete' or 'incomplete' entries in scrape response\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcb->tracker_scrape_response(tracker_req(), int(complete->integer())\n\t\t\t\t, int(incomplete->integer()), int(downloaded->integer()));\n\t\t\treturn;\n\t\t}\n\n\t\tentry const* interval = e.find_key(\"interval\");\n\t\tif (interval == 0 || interval->type() != entry::int_t)\n\t\t{\n\t\t\tfail(-1, \"missing or invalid 'interval' entry in tracker response\");\n\t\t\treturn;\n\t\t}\n\n\t\tentry const* peers_ent = e.find_key(\"peers\");\n\t\tif (peers_ent == 0)\n\t\t{\n\t\t\tfail(-1, \"missing 'peers' entry in tracker response\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (peers_ent->type() == entry::string_t)\n\t\t{\n\t\t\tstd::string const& peers = peers_ent->string();\n\t\t\tfor (std::string::const_iterator i = peers.begin();\n\t\t\t\ti != peers.end();)\n\t\t\t{\n\t\t\t\tif (std::distance(i, peers.end()) < 6) break;\n\n\t\t\t\tpeer_entry p;\n\t\t\t\tp.pid.clear();\n\t\t\t\tp.ip = detail::read_v4_address(i).to_string();\n\t\t\t\tp.port = detail::read_uint16(i);\n\t\t\t\tpeer_list.push_back(p);\n\t\t\t}\n\t\t}\n\t\telse if (peers_ent->type() == entry::list_t)\n\t\t{\n\t\t\tentry::list_type const& l = peers_ent->list();\n\t\t\tfor(entry::list_type::const_iterator i = l.begin(); i != l.end(); ++i)\n\t\t\t{\n\t\t\t\tpeer_entry p;\n\t\t\t\tif (!extract_peer_info(*i, p)) return;\n\t\t\t\tpeer_list.push_back(p);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfail(-1, \"invalid 'peers' entry in tracker response\");\n\t\t\treturn;\n\t\t}\n\n\t\tentry const* ipv6_peers = e.find_key(\"peers6\");\n\t\tif (ipv6_peers && ipv6_peers->type() == entry::string_t)\n\t\t{\n\t\t\tstd::string const& peers = ipv6_peers->string();\n\t\t\tfor (std::string::const_iterator i = peers.begin();\n\t\t\t\ti != peers.end();)\n\t\t\t{\n\t\t\t\tif (std::distance(i, peers.end()) < 18) break;\n\n\t\t\t\tpeer_entry p;\n\t\t\t\tp.pid.clear();\n\t\t\t\tp.ip = detail::read_v6_address(i).to_string();\n\t\t\t\tp.port = detail::read_uint16(i);\n\t\t\t\tpeer_list.push_back(p);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ look for optional scrape info\n\t\tint complete = -1;\n\t\tint incomplete = -1;\n\t\taddress external_ip;\n\n\t\tentry const* ip_ent = e.find_key(\"external ip\");\n\t\tif (ip_ent && ip_ent->type() == entry::string_t)\n\t\t{\n\t\t\tstd::string const& ip = ip_ent->string();\n\t\t\tchar const* p = &ip[0];\n\t\t\tif (ip.size() == address_v4::bytes_type::static_size)\n\t\t\t\texternal_ip = detail::read_v4_address(p);\n\t\t\telse if (ip.size() == address_v6::bytes_type::static_size)\n\t\t\t\texternal_ip = detail::read_v6_address(p);\n\t\t}\n\t\t\n\t\tentry const* complete_ent = e.find_key(\"complete\");\n\t\tif (complete_ent && complete_ent->type() == entry::int_t)\n\t\t\tcomplete = int(complete_ent->integer());\n\n\t\tentry const* incomplete_ent = e.find_key(\"incomplete\");\n\t\tif (incomplete_ent && incomplete_ent->type() == entry::int_t)\n\t\t\tincomplete = int(incomplete_ent->integer());\n\n\t\tcb->tracker_response(tracker_req(), peer_list, interval->integer(), complete\n\t\t\t, incomplete, external_ip);\n\t}\n\n}\n\n<commit_msg>fixed exception issue when tracker sends invalid response<commit_after>\/*\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 <vector>\n#include <iostream>\n#include <cctype>\n#include <iomanip>\n#include <sstream>\n#include <algorithm>\n\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/gzip.hpp\"\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/bind.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/tracker_manager.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n#include \"libtorrent\/http_connection.hpp\"\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/socket.hpp\"\n\nusing namespace libtorrent;\nusing boost::bind;\n\nnamespace libtorrent\n{\n\t\n\thttp_tracker_connection::http_tracker_connection(\n\t\tio_service& ios\n\t\t, connection_queue& cc\n\t\t, tracker_manager& man\n\t\t, tracker_request const& req\n\t\t, address bind_infc\n\t\t, boost::weak_ptr<request_callback> c\n\t\t, session_settings const& stn\n\t\t, proxy_settings const& ps\n\t\t, std::string const& auth)\n\t\t: tracker_connection(man, req, ios, bind_infc, c)\n\t\t, m_man(man)\n\t{\n\t\t\/\/ TODO: authentication\n\t\tstd::string url = req.url;\n\n\t\tif (req.kind == tracker_request::scrape_request)\n\t\t{\n\t\t\t\/\/ find and replace \"announce\" with \"scrape\"\n\t\t\t\/\/ in request\n\n\t\t\tstd::size_t pos = url.find(\"announce\");\n\t\t\tif (pos == std::string::npos)\n\t\t\t{\n\t\t\t\tfail(-1, (\"scrape is not available on url: '\"\n\t\t\t\t\t+ req.url +\"'\").c_str());\n\t\t\t\treturn;\n\t\t\t}\n\t\t\turl.replace(pos, 8, \"scrape\");\n\t\t}\n\t\t\n\t\t\/\/ if request-string already contains\n\t\t\/\/ some parameters, append an ampersand instead\n\t\t\/\/ of a question mark\n\t\tsize_t arguments_start = url.find('?');\n\t\tif (arguments_start != std::string::npos)\n\t\t\turl += \"&\";\n\t\telse\n\t\t\turl += \"?\";\n\n\t\turl += \"info_hash=\";\n\t\turl += escape_string(\n\t\t\treinterpret_cast<const char*>(req.info_hash.begin()), 20);\n\t\t\n\t\tif (req.kind == tracker_request::announce_request)\n\t\t{\n\t\t\turl += \"&peer_id=\";\n\t\t\turl += escape_string(\n\t\t\t\treinterpret_cast<const char*>(req.pid.begin()), 20);\n\n\t\t\turl += \"&port=\";\n\t\t\turl += boost::lexical_cast<std::string>(req.listen_port);\n\n\t\t\turl += \"&uploaded=\";\n\t\t\turl += boost::lexical_cast<std::string>(req.uploaded);\n\n\t\t\turl += \"&downloaded=\";\n\t\t\turl += boost::lexical_cast<std::string>(req.downloaded);\n\n\t\t\turl += \"&left=\";\n\t\t\turl += boost::lexical_cast<std::string>(req.left);\n\n\t\t\tif (req.event != tracker_request::none)\n\t\t\t{\n\t\t\t\tconst char* event_string[] = {\"completed\", \"started\", \"stopped\"};\n\t\t\t\turl += \"&event=\";\n\t\t\t\turl += event_string[req.event - 1];\n\t\t\t}\n\n\t\t\turl += \"&key=\";\n\t\t\tstd::stringstream key_string;\n\t\t\tkey_string << std::hex << req.key;\n\t\t\turl += key_string.str();\n\n\t\t\turl += \"&compact=1\";\n\n\t\t\turl += \"&numwant=\";\n\t\t\turl += boost::lexical_cast<std::string>(\n\t\t\t\t(std::min)(req.num_want, 999));\n\n\t\t\tif (stn.announce_ip != address())\n\t\t\t{\n\t\t\t\turl += \"&ip=\";\n\t\t\t\turl += stn.announce_ip.to_string();\n\t\t\t}\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\t\t\turl += \"&supportcrypto=1\";\n#endif\n\t\t\turl += \"&ipv6=\";\n\t\t\turl += req.ipv6;\n\n\t\t\t\/\/ extension that tells the tracker that\n\t\t\t\/\/ we don't need any peer_id's in the response\n\t\t\turl += \"&no_peer_id=1\";\n\t\t}\n\n\t\tm_tracker_connection.reset(new http_connection(ios, cc\n\t\t\t, boost::bind(&http_tracker_connection::on_response, self(), _1, _2, _3, _4)));\n\n\t\tint timeout = req.event==tracker_request::stopped\n\t\t\t?stn.stop_tracker_timeout\n\t\t\t:stn.tracker_completion_timeout;\n\n\t\tm_tracker_connection->get(url, seconds(timeout)\n\t\t\t, 1, &ps, 5, stn.user_agent, bind_infc);\n\n#if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING)\n\n\t\tboost::shared_ptr<request_callback> cb = requester();\n\t\tif (cb)\n\t\t{\n\t\t\tcb->debug_log(\"==> TRACKER_REQUEST [ url: \" + url + \" ]\");\n\t\t}\n#endif\n\t}\n\n\tvoid http_tracker_connection::close()\n\t{\n\t\tif (m_tracker_connection)\n\t\t{\n\t\t\tm_tracker_connection->close();\n\t\t\tm_tracker_connection.reset();\n\t\t}\n\t\ttracker_connection::close();\n\t}\n\n\tvoid http_tracker_connection::on_response(error_code const& ec\n\t\t, http_parser const& parser, char const* data, int size)\n\t{\n\t\t\/\/ keep this alive\n\t\tboost::intrusive_ptr<http_tracker_connection> me(this);\n\n\t\tif (ec && ec != asio::error::eof)\n\t\t{\n\t\t\tfail(-1, ec.message().c_str());\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (!parser.header_finished())\n\t\t{\n\t\t\tfail(-1, \"premature end of file\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (parser.status_code() != 200)\n\t\t{\n\t\t\tfail(parser.status_code(), parser.message().c_str());\n\t\t\treturn;\n\t\t}\n\t\n\t\tif (ec && ec != asio::error::eof)\n\t\t{\n\t\t\tfail(parser.status_code(), ec.message().c_str());\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t\/\/ handle tracker response\n\t\tentry e;\n#ifndef BOOST_NO_EXCEPTIONS\n\t\ttry {\n#endif\n\t\te = bdecode(data, data + size);\n#ifndef BOOST_NO_EXCEPTIONS\n\t\t} catch (std::exception&) {}\n#endif\n\n\t\tif (e.type() != entry::undefined_t)\n\t\t{\n\t\t\tparse(parser.status_code(), e);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::string error_str(\"invalid bencoding of tracker response: \\\"\");\n\t\t\tfor (char const* i = data, *end(data + size); i != end; ++i)\n\t\t\t{\n\t\t\t\tif (std::isprint(*i)) error_str += *i;\n\t\t\t\telse error_str += \"0x\" + boost::lexical_cast<std::string>((unsigned int)*i) + \" \";\n\t\t\t}\n\t\t\terror_str += \"\\\"\";\n\t\t\tfail(parser.status_code(), error_str.c_str());\n\t\t}\n\t\tclose();\n\t}\n\n\tbool http_tracker_connection::extract_peer_info(const entry& info, peer_entry& ret)\n\t{\n\t\t\/\/ extract peer id (if any)\n\t\tif (info.type() != entry::dictionary_t)\n\t\t{\n\t\t\tfail(-1, \"invalid response from tracker (invalid peer entry)\");\n\t\t\treturn false;\n\t\t}\n\t\tentry const* i = info.find_key(\"peer id\");\n\t\tif (i != 0)\n\t\t{\n\t\t\tif (i->type() != entry::string_t || i->string().length() != 20)\n\t\t\t{\n\t\t\t\tfail(-1, \"invalid response from tracker (invalid peer id)\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tstd::copy(i->string().begin(), i->string().end(), ret.pid.begin());\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ if there's no peer_id, just initialize it to a bunch of zeroes\n\t\t\tstd::fill_n(ret.pid.begin(), 20, 0);\n\t\t}\n\n\t\t\/\/ extract ip\n\t\ti = info.find_key(\"ip\");\n\t\tif (i == 0 || i->type() != entry::string_t)\n\t\t{\n\t\t\tfail(-1, \"invalid response from tracker\");\n\t\t\treturn false;\n\t\t}\n\t\tret.ip = i->string();\n\n\t\t\/\/ extract port\n\t\ti = info.find_key(\"port\");\n\t\tif (i == 0 || i->type() != entry::int_t)\n\t\t{\n\t\t\tfail(-1, \"invalid response from tracker\");\n\t\t\treturn false;\n\t\t}\n\t\tret.port = (unsigned short)i->integer();\n\n\t\treturn true;\n\t}\n\n\tvoid http_tracker_connection::parse(int status_code, entry const& e)\n\t{\n\t\tboost::shared_ptr<request_callback> cb = requester();\n\t\tif (!cb) return;\n\n\t\t\/\/ parse the response\n\t\tentry const* failure = e.find_key(\"failure reason\");\n\t\tif (failure && failure->type() == entry::string_t)\n\t\t{\n\t\t\tfail(status_code, failure->string().c_str());\n\t\t\treturn;\n\t\t}\n\n\t\tentry const* warning = e.find_key(\"warning message\");\n\t\tif (warning && warning->type() == entry::string_t)\n\t\t{\n\t\t\tcb->tracker_warning(tracker_req(), warning->string());\n\t\t}\n\n\t\tstd::vector<peer_entry> peer_list;\n\n\t\tif (tracker_req().kind == tracker_request::scrape_request)\n\t\t{\n\t\t\tstd::string ih = tracker_req().info_hash.to_string();\n\n\t\t\tentry const* files = e.find_key(\"files\");\n\t\t\tif (files == 0 || files->type() != entry::dictionary_t)\n\t\t\t{\n\t\t\t\tfail(-1, \"invalid or missing 'files' entry in scrape response\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tentry const* scrape_data = files->find_key(ih);\n\t\t\tif (scrape_data == 0 || scrape_data->type() != entry::dictionary_t)\n\t\t\t{\n\t\t\t\tfail(-1, \"missing or invalid info-hash entry in scrape response\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry const* complete = scrape_data->find_key(\"complete\");\n\t\t\tentry const* incomplete = scrape_data->find_key(\"incomplete\");\n\t\t\tentry const* downloaded = scrape_data->find_key(\"downloaded\");\n\t\t\tif (complete == 0 || incomplete == 0 || downloaded == 0\n\t\t\t\t|| complete->type() != entry::int_t\n\t\t\t\t|| incomplete->type() != entry::int_t\n\t\t\t\t|| downloaded->type() != entry::int_t)\n\t\t\t{\n\t\t\t\tfail(-1, \"missing 'complete' or 'incomplete' entries in scrape response\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcb->tracker_scrape_response(tracker_req(), int(complete->integer())\n\t\t\t\t, int(incomplete->integer()), int(downloaded->integer()));\n\t\t\treturn;\n\t\t}\n\n\t\tentry const* interval = e.find_key(\"interval\");\n\t\tif (interval == 0 || interval->type() != entry::int_t)\n\t\t{\n\t\t\tfail(-1, \"missing or invalid 'interval' entry in tracker response\");\n\t\t\treturn;\n\t\t}\n\n\t\tentry const* peers_ent = e.find_key(\"peers\");\n\t\tif (peers_ent == 0)\n\t\t{\n\t\t\tfail(-1, \"missing 'peers' entry in tracker response\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (peers_ent->type() == entry::string_t)\n\t\t{\n\t\t\tstd::string const& peers = peers_ent->string();\n\t\t\tfor (std::string::const_iterator i = peers.begin();\n\t\t\t\ti != peers.end();)\n\t\t\t{\n\t\t\t\tif (std::distance(i, peers.end()) < 6) break;\n\n\t\t\t\tpeer_entry p;\n\t\t\t\tp.pid.clear();\n\t\t\t\tp.ip = detail::read_v4_address(i).to_string();\n\t\t\t\tp.port = detail::read_uint16(i);\n\t\t\t\tpeer_list.push_back(p);\n\t\t\t}\n\t\t}\n\t\telse if (peers_ent->type() == entry::list_t)\n\t\t{\n\t\t\tentry::list_type const& l = peers_ent->list();\n\t\t\tfor(entry::list_type::const_iterator i = l.begin(); i != l.end(); ++i)\n\t\t\t{\n\t\t\t\tpeer_entry p;\n\t\t\t\tif (!extract_peer_info(*i, p)) return;\n\t\t\t\tpeer_list.push_back(p);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfail(-1, \"invalid 'peers' entry in tracker response\");\n\t\t\treturn;\n\t\t}\n\n\t\tentry const* ipv6_peers = e.find_key(\"peers6\");\n\t\tif (ipv6_peers && ipv6_peers->type() == entry::string_t)\n\t\t{\n\t\t\tstd::string const& peers = ipv6_peers->string();\n\t\t\tfor (std::string::const_iterator i = peers.begin();\n\t\t\t\ti != peers.end();)\n\t\t\t{\n\t\t\t\tif (std::distance(i, peers.end()) < 18) break;\n\n\t\t\t\tpeer_entry p;\n\t\t\t\tp.pid.clear();\n\t\t\t\tp.ip = detail::read_v6_address(i).to_string();\n\t\t\t\tp.port = detail::read_uint16(i);\n\t\t\t\tpeer_list.push_back(p);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ look for optional scrape info\n\t\tint complete = -1;\n\t\tint incomplete = -1;\n\t\taddress external_ip;\n\n\t\tentry const* ip_ent = e.find_key(\"external ip\");\n\t\tif (ip_ent && ip_ent->type() == entry::string_t)\n\t\t{\n\t\t\tstd::string const& ip = ip_ent->string();\n\t\t\tchar const* p = &ip[0];\n\t\t\tif (ip.size() == address_v4::bytes_type::static_size)\n\t\t\t\texternal_ip = detail::read_v4_address(p);\n\t\t\telse if (ip.size() == address_v6::bytes_type::static_size)\n\t\t\t\texternal_ip = detail::read_v6_address(p);\n\t\t}\n\t\t\n\t\tentry const* complete_ent = e.find_key(\"complete\");\n\t\tif (complete_ent && complete_ent->type() == entry::int_t)\n\t\t\tcomplete = int(complete_ent->integer());\n\n\t\tentry const* incomplete_ent = e.find_key(\"incomplete\");\n\t\tif (incomplete_ent && incomplete_ent->type() == entry::int_t)\n\t\t\tincomplete = int(incomplete_ent->integer());\n\n\t\tcb->tracker_response(tracker_req(), peer_list, interval->integer(), complete\n\t\t\t, incomplete, external_ip);\n\t}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2021 Baldur Karlsson\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\n#include \"RGPInterop.h\"\n#include <QApplication>\n#include <QTcpServer>\n#include <QTcpSocket>\n\nbool RGPInterop::RGPSupportsInterop(const QString &RGPPath)\n{\n uint32_t majorVersion = 0;\n uint32_t minorVersion = 0;\n\n const char *searchString = \"RGPVersion=\";\n const int searchStringLength = (int)strlen(searchString);\n\n \/\/ look for an embedded string in the exe\n QFile f(RGPPath);\n if(f.open(QIODevice::ReadOnly))\n {\n QByteArray contents = f.readAll();\n\n int search = 0;\n do\n {\n int needle = contents.indexOf(\"RGPVersion=\", search);\n\n if(needle == -1)\n break;\n\n search = needle + searchStringLength;\n\n \/\/ bail if there isn't enough room for the string plus X.Y\n if(contents.size() - needle < searchStringLength + 3)\n break;\n\n \/\/ get the major version number\n const char *major = contents.data() + search;\n\n const char *sep = major;\n\n \/\/ find the separator\n while(*sep >= '0' && *sep <= '9')\n sep++;\n\n \/\/ get the minor version number\n const char *minor = sep + 1;\n\n const char *end = minor;\n\n \/\/ find the end\n while(*end >= '0' && *end <= '9')\n end++;\n\n \/\/ convert the strings to integers\n QByteArray majorStr(major, sep - major);\n QByteArray minorStr(minor, end - minor);\n\n bool ok = false;\n majorVersion = majorStr.toUInt(&ok);\n\n if(!ok)\n {\n majorVersion = 0;\n continue;\n }\n\n minorVersion = minorStr.toUInt(&ok);\n\n if(!ok)\n {\n majorVersion = minorVersion = 0;\n continue;\n }\n\n \/\/ found the version\n break;\n\n } while(search >= 0);\n }\n\n \/\/ interop supported in RGP V1.2 and higher\n if(majorVersion > 1 || (majorVersion == 1 && minorVersion > 1))\n {\n return true;\n }\n\n return false;\n}\n\ntemplate <>\nrdcstr DoStringise(const RGPCommand &el)\n{\n BEGIN_ENUM_STRINGISE(RGPCommand);\n {\n STRINGISE_ENUM_CLASS_NAMED(Initialize, \"initialize\");\n STRINGISE_ENUM_CLASS_NAMED(SetEvent, \"set_event\");\n STRINGISE_ENUM_CLASS_NAMED(Terminate, \"terminate\");\n }\n END_ENUM_STRINGISE();\n}\n\nRGPInterop::RGPInterop(ICaptureContext &ctx) : m_Ctx(ctx)\n{\n m_Server = new QTcpServer(NULL);\n m_Server->listen(QHostAddress::Any, Port);\n\n QObject::connect(m_Server, &QTcpServer::newConnection, [this]() {\n if(m_Socket == NULL)\n {\n m_Socket = m_Server->nextPendingConnection();\n ConnectionEstablished();\n }\n else\n {\n \/\/ close any other connections while we already have one\n delete m_Server->nextPendingConnection();\n }\n });\n}\n\nRGPInterop::~RGPInterop()\n{\n RGPInteropTerminate terminate;\n QString encoded = EncodeCommand(RGPCommand::Terminate, terminate.toParams(m_Version));\n\n if(m_Socket)\n {\n m_Socket->write(encoded.trimmed().toUtf8().data());\n m_Socket->waitForBytesWritten();\n }\n\n m_Server->close();\n delete m_Server;\n}\n\nvoid RGPInterop::InitializeRGP()\n{\n RGPInteropInit init;\n\n init.interop_version = 1;\n init.interop_name = lit(\"RenderDoc\");\n\n QString encoded = EncodeCommand(RGPCommand::Initialize, init.toParams(m_Version));\n\n if(m_Socket)\n {\n m_Socket->write(encoded.trimmed().toUtf8().data());\n }\n}\n\nbool RGPInterop::HasRGPEvent(uint32_t eventId)\n{\n if(m_Version == 0)\n return false;\n\n if(m_Socket == NULL)\n return false;\n\n return m_Event2RGP[eventId].interoplinearid != 0;\n}\n\nbool RGPInterop::SelectRGPEvent(uint32_t eventId)\n{\n if(m_Version == 0)\n return false;\n\n RGPInteropEvent ev = m_Event2RGP[eventId];\n\n if(ev.interoplinearid == 0)\n return false;\n\n QString encoded = EncodeCommand(RGPCommand::SetEvent, ev.toParams(m_Version));\n\n if(m_Socket)\n {\n m_Socket->write(encoded.trimmed().toUtf8().data());\n return true;\n }\n\n return false;\n}\n\nvoid RGPInterop::EventSelected(RGPInteropEvent event)\n{\n uint32_t eventId = m_RGP2Event[event.interoplinearid];\n\n if(eventId == 0)\n {\n qWarning() << \"RGP Event \" << event.interoplinearid << event.cmdbufid << event.eventname\n << \" did not correspond to a known eventId\";\n return;\n }\n\n const ActionDescription *action = m_Ctx.GetAction(eventId);\n\n const SDFile &file = m_Ctx.GetStructuredFile();\n\n if(action && QString(file.chunks[action->events.back().chunkIndex]->name) != event.eventname)\n qWarning() << \"Action name mismatch. Expected \" << event.eventname << \" but got \"\n << QString(file.chunks[action->events.back().chunkIndex]->name);\n\n m_Ctx.SetEventID({}, eventId, eventId);\n\n BringToForeground(m_Ctx.GetMainWindow()->Widget());\n}\n\nvoid RGPInterop::ConnectionEstablished()\n{\n QObject::connect(m_Socket, &QAbstractSocket::disconnected, [this]() {\n m_Socket->deleteLater();\n m_Socket = NULL;\n });\n\n \/\/ initial handshake and protocol version\n InitializeRGP();\n\n \/\/ TODO: negotiate mapping version\n uint32_t version = 1;\n CreateMapping(version);\n\n \/\/ add a handler that appends all data to the read buffer and processes each time more comes in.\n QObject::connect(m_Socket, &QIODevice::readyRead, [this]() {\n \/\/ append all available data\n m_ReadBuffer += m_Socket->readAll();\n\n \/\/ process the read buffer\n ProcessReadBuffer();\n });\n}\n\nvoid RGPInterop::CreateMapping(const rdcarray<ActionDescription> &actions)\n{\n const SDFile &file = m_Ctx.GetStructuredFile();\n\n for(const ActionDescription &action : actions)\n {\n for(const APIEvent &ev : action.events)\n {\n if(ev.chunkIndex == 0 || ev.chunkIndex == APIEvent::NoChunk ||\n ev.chunkIndex >= file.chunks.size())\n continue;\n\n const SDChunk *chunk = file.chunks[ev.chunkIndex];\n\n if(m_EventNames.contains(chunk->name, Qt::CaseSensitive))\n {\n m_Event2RGP[ev.eventId].interoplinearid = (uint32_t)m_RGP2Event.size();\n rdcstr n = chunk->name;\n if(n.contains(':'))\n n.erase(0, n.find_last_of(\":\") + 1);\n n += \"(\";\n bool first = true;\n for(size_t i = 0; i < chunk->NumChildren(); i++)\n {\n const SDObject *o = chunk->GetChild(i);\n if(o->type.flags & SDTypeFlags::Important)\n {\n if(first)\n n += \", \";\n first = false;\n n += ToStr(o->AsUInt32());\n }\n }\n n += \")\";\n\n m_Event2RGP[ev.eventId].eventname = n;\n\n m_RGP2Event.push_back(ev.eventId);\n }\n }\n\n \/\/ if we have children, step into them first before going to our next sibling\n if(!action.children.empty())\n CreateMapping(action.children);\n }\n}\n\nvoid RGPInterop::CreateMapping(uint32_t version)\n{\n m_Version = version;\n\n if(m_Ctx.APIProps().pipelineType == GraphicsAPI::Vulkan)\n {\n if(version == 1)\n {\n m_EventNames << lit(\"vkCmdDispatch\") << lit(\"vkCmdDraw\") << lit(\"vkCmdDrawIndexed\");\n }\n }\n else if(m_Ctx.APIProps().pipelineType == GraphicsAPI::D3D12)\n {\n \/\/ these names must match those in DoStringise(const D3D12Chunk &el) for the chunks\n\n if(version == 1)\n {\n m_EventNames << lit(\"ID3D12GraphicsCommandList::Dispatch\")\n << lit(\"ID3D12GraphicsCommandList::DrawInstanced\")\n << lit(\"ID3D12GraphicsCommandList::DrawIndexedInstanced\");\n }\n }\n\n \/\/ if we don't have any event names, this API doesn't have a mapping or this was an unrecognised\n \/\/ version.\n if(m_EventNames.isEmpty())\n return;\n\n m_Event2RGP.resize(m_Ctx.GetLastAction()->eventId + 1);\n\n \/\/ linearId 0 is invalid, so map to eventId 0.\n \/\/ the first real event will be linearId 1\n m_RGP2Event.push_back(0);\n\n CreateMapping(m_Ctx.CurRootActions());\n}\n\nQString RGPInterop::EncodeCommand(RGPCommand command, QVariantList params)\n{\n QString ret;\n\n QString cmd = ToQStr(command);\n\n ret += lit(\"command=%1\\n\").arg(cmd);\n\n \/\/ iterate params in pair, name and value\n for(int i = 0; i + 1 < params.count(); i += 2)\n ret += QFormatStr(\"%1.%2=%3\\n\").arg(cmd).arg(params[i].toString()).arg(params[i + 1].toString());\n\n ret += lit(\"endcommand=%1\\n\").arg(cmd);\n\n return ret;\n}\n\nbool RGPInterop::DecodeCommand(QString command)\n{\n QStringList lines = command.trimmed().split(QLatin1Char('\\n'));\n\n if(lines[0].indexOf(lit(\"command=\")) != 0 || lines.last().indexOf(lit(\"endcommand=\")) != 0)\n {\n qWarning() << \"Malformed RGP command:\\n\" << command;\n return false;\n }\n\n QString commandName = lines[0].split(QLatin1Char('='))[1];\n\n if(lines.last().split(QLatin1Char('='))[1] != commandName)\n {\n qWarning() << \"Mismatch between command and endcommand:\\n\" << command;\n return false;\n }\n\n lines.pop_front();\n lines.pop_back();\n\n QVariantList params;\n\n QString prefix = commandName + lit(\".\");\n\n for(QString ¶m : lines)\n {\n int eq = param.indexOf(QLatin1Char('='));\n\n if(eq < 0)\n {\n qWarning() << \"Malformed param: \" << param;\n continue;\n }\n\n QString key = param.left(eq);\n QString value = param.mid(eq + 1);\n\n if(!key.startsWith(prefix))\n {\n qWarning() << \"Malformed param key for\" << commandName << \": \" << key;\n continue;\n }\n\n key = key.mid(prefix.count());\n\n params << key << value;\n }\n\n if(commandName == ToQStr(RGPCommand::SetEvent))\n {\n RGPInteropEvent ev;\n ev.fromParams(m_Version, params);\n\n EventSelected(ev);\n\n return true;\n }\n else if(commandName == ToQStr(RGPCommand::Initialize))\n {\n RGPInteropInit init;\n init.fromParams(m_Version, params);\n\n \/\/ TODO: decode the params here. This will contain the interop\n \/\/ version and the name of the tool connected to RenderDoc\n\n return true;\n }\n else if(commandName == ToQStr(RGPCommand::Terminate))\n {\n \/\/ RGP has shut down so disconnect the socket etc\n emit m_Socket->disconnected();\n return true;\n }\n else\n {\n qWarning() << \"Unrecognised command: \" << commandName;\n }\n\n return false;\n}\n\nvoid RGPInterop::ProcessReadBuffer()\n{\n \/\/ we might have partial data, so wait until we have a full command\n do\n {\n int idx = m_ReadBuffer.indexOf(\"endcommand=\");\n\n \/\/ if we don't have endcommand= yet, we don't have a full command\n if(idx < 0)\n return;\n\n idx = m_ReadBuffer.indexOf('\\n', idx);\n\n \/\/ also break if we don't have the full line yet including newline.\n if(idx < 0)\n return;\n\n \/\/ extract the command and decode as UTF-8\n QString command = QString::fromUtf8(m_ReadBuffer.data(), idx + 1);\n\n \/\/ remove the command from our buffer, to retain any partial subsequent command we might have\n m_ReadBuffer.remove(0, idx + 1);\n\n \/\/ process this command\n DecodeCommand(command);\n\n \/\/ loop again - we might have read multiple commands\n } while(true);\n}\n<commit_msg>Fix parameter generation for RGP event names<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2021 Baldur Karlsson\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\n#include \"RGPInterop.h\"\n#include <QApplication>\n#include <QTcpServer>\n#include <QTcpSocket>\n\nbool RGPInterop::RGPSupportsInterop(const QString &RGPPath)\n{\n uint32_t majorVersion = 0;\n uint32_t minorVersion = 0;\n\n const char *searchString = \"RGPVersion=\";\n const int searchStringLength = (int)strlen(searchString);\n\n \/\/ look for an embedded string in the exe\n QFile f(RGPPath);\n if(f.open(QIODevice::ReadOnly))\n {\n QByteArray contents = f.readAll();\n\n int search = 0;\n do\n {\n int needle = contents.indexOf(\"RGPVersion=\", search);\n\n if(needle == -1)\n break;\n\n search = needle + searchStringLength;\n\n \/\/ bail if there isn't enough room for the string plus X.Y\n if(contents.size() - needle < searchStringLength + 3)\n break;\n\n \/\/ get the major version number\n const char *major = contents.data() + search;\n\n const char *sep = major;\n\n \/\/ find the separator\n while(*sep >= '0' && *sep <= '9')\n sep++;\n\n \/\/ get the minor version number\n const char *minor = sep + 1;\n\n const char *end = minor;\n\n \/\/ find the end\n while(*end >= '0' && *end <= '9')\n end++;\n\n \/\/ convert the strings to integers\n QByteArray majorStr(major, sep - major);\n QByteArray minorStr(minor, end - minor);\n\n bool ok = false;\n majorVersion = majorStr.toUInt(&ok);\n\n if(!ok)\n {\n majorVersion = 0;\n continue;\n }\n\n minorVersion = minorStr.toUInt(&ok);\n\n if(!ok)\n {\n majorVersion = minorVersion = 0;\n continue;\n }\n\n \/\/ found the version\n break;\n\n } while(search >= 0);\n }\n\n \/\/ interop supported in RGP V1.2 and higher\n if(majorVersion > 1 || (majorVersion == 1 && minorVersion > 1))\n {\n return true;\n }\n\n return false;\n}\n\ntemplate <>\nrdcstr DoStringise(const RGPCommand &el)\n{\n BEGIN_ENUM_STRINGISE(RGPCommand);\n {\n STRINGISE_ENUM_CLASS_NAMED(Initialize, \"initialize\");\n STRINGISE_ENUM_CLASS_NAMED(SetEvent, \"set_event\");\n STRINGISE_ENUM_CLASS_NAMED(Terminate, \"terminate\");\n }\n END_ENUM_STRINGISE();\n}\n\nRGPInterop::RGPInterop(ICaptureContext &ctx) : m_Ctx(ctx)\n{\n m_Server = new QTcpServer(NULL);\n m_Server->listen(QHostAddress::Any, Port);\n\n QObject::connect(m_Server, &QTcpServer::newConnection, [this]() {\n if(m_Socket == NULL)\n {\n m_Socket = m_Server->nextPendingConnection();\n ConnectionEstablished();\n }\n else\n {\n \/\/ close any other connections while we already have one\n delete m_Server->nextPendingConnection();\n }\n });\n}\n\nRGPInterop::~RGPInterop()\n{\n RGPInteropTerminate terminate;\n QString encoded = EncodeCommand(RGPCommand::Terminate, terminate.toParams(m_Version));\n\n if(m_Socket)\n {\n m_Socket->write(encoded.trimmed().toUtf8().data());\n m_Socket->waitForBytesWritten();\n }\n\n m_Server->close();\n delete m_Server;\n}\n\nvoid RGPInterop::InitializeRGP()\n{\n RGPInteropInit init;\n\n init.interop_version = 1;\n init.interop_name = lit(\"RenderDoc\");\n\n QString encoded = EncodeCommand(RGPCommand::Initialize, init.toParams(m_Version));\n\n if(m_Socket)\n {\n m_Socket->write(encoded.trimmed().toUtf8().data());\n }\n}\n\nbool RGPInterop::HasRGPEvent(uint32_t eventId)\n{\n if(m_Version == 0)\n return false;\n\n if(m_Socket == NULL)\n return false;\n\n return m_Event2RGP[eventId].interoplinearid != 0;\n}\n\nbool RGPInterop::SelectRGPEvent(uint32_t eventId)\n{\n if(m_Version == 0)\n return false;\n\n RGPInteropEvent ev = m_Event2RGP[eventId];\n\n if(ev.interoplinearid == 0)\n return false;\n\n QString encoded = EncodeCommand(RGPCommand::SetEvent, ev.toParams(m_Version));\n\n if(m_Socket)\n {\n m_Socket->write(encoded.trimmed().toUtf8().data());\n return true;\n }\n\n return false;\n}\n\nvoid RGPInterop::EventSelected(RGPInteropEvent event)\n{\n uint32_t eventId = m_RGP2Event[event.interoplinearid];\n\n if(eventId == 0)\n {\n qWarning() << \"RGP Event \" << event.interoplinearid << event.cmdbufid << event.eventname\n << \" did not correspond to a known eventId\";\n return;\n }\n\n const ActionDescription *action = m_Ctx.GetAction(eventId);\n\n const SDFile &file = m_Ctx.GetStructuredFile();\n\n if(action && QString(file.chunks[action->events.back().chunkIndex]->name) != event.eventname)\n qWarning() << \"Action name mismatch. Expected \" << event.eventname << \" but got \"\n << QString(file.chunks[action->events.back().chunkIndex]->name);\n\n m_Ctx.SetEventID({}, eventId, eventId);\n\n BringToForeground(m_Ctx.GetMainWindow()->Widget());\n}\n\nvoid RGPInterop::ConnectionEstablished()\n{\n QObject::connect(m_Socket, &QAbstractSocket::disconnected, [this]() {\n m_Socket->deleteLater();\n m_Socket = NULL;\n });\n\n \/\/ initial handshake and protocol version\n InitializeRGP();\n\n \/\/ TODO: negotiate mapping version\n uint32_t version = 1;\n CreateMapping(version);\n\n \/\/ add a handler that appends all data to the read buffer and processes each time more comes in.\n QObject::connect(m_Socket, &QIODevice::readyRead, [this]() {\n \/\/ append all available data\n m_ReadBuffer += m_Socket->readAll();\n\n \/\/ process the read buffer\n ProcessReadBuffer();\n });\n}\n\nvoid RGPInterop::CreateMapping(const rdcarray<ActionDescription> &actions)\n{\n const SDFile &file = m_Ctx.GetStructuredFile();\n\n for(const ActionDescription &action : actions)\n {\n for(const APIEvent &ev : action.events)\n {\n if(ev.chunkIndex == 0 || ev.chunkIndex == APIEvent::NoChunk ||\n ev.chunkIndex >= file.chunks.size())\n continue;\n\n const SDChunk *chunk = file.chunks[ev.chunkIndex];\n\n if(m_EventNames.contains(chunk->name, Qt::CaseSensitive))\n {\n m_Event2RGP[ev.eventId].interoplinearid = (uint32_t)m_RGP2Event.size();\n rdcstr n = chunk->name;\n if(n.contains(':'))\n n.erase(0, n.find_last_of(\":\") + 1);\n n += \"(\";\n bool first = true;\n for(size_t i = 0; i < chunk->NumChildren(); i++)\n {\n const SDObject *o = chunk->GetChild(i);\n if(o->type.flags & SDTypeFlags::Important)\n {\n if(!first)\n n += \", \";\n first = false;\n n += ToStr(o->AsUInt32());\n }\n }\n n += \")\";\n\n m_Event2RGP[ev.eventId].eventname = n;\n\n m_RGP2Event.push_back(ev.eventId);\n }\n }\n\n \/\/ if we have children, step into them first before going to our next sibling\n if(!action.children.empty())\n CreateMapping(action.children);\n }\n}\n\nvoid RGPInterop::CreateMapping(uint32_t version)\n{\n m_Version = version;\n\n if(m_Ctx.APIProps().pipelineType == GraphicsAPI::Vulkan)\n {\n if(version == 1)\n {\n m_EventNames << lit(\"vkCmdDispatch\") << lit(\"vkCmdDraw\") << lit(\"vkCmdDrawIndexed\");\n }\n }\n else if(m_Ctx.APIProps().pipelineType == GraphicsAPI::D3D12)\n {\n \/\/ these names must match those in DoStringise(const D3D12Chunk &el) for the chunks\n\n if(version == 1)\n {\n m_EventNames << lit(\"ID3D12GraphicsCommandList::Dispatch\")\n << lit(\"ID3D12GraphicsCommandList::DrawInstanced\")\n << lit(\"ID3D12GraphicsCommandList::DrawIndexedInstanced\");\n }\n }\n\n \/\/ if we don't have any event names, this API doesn't have a mapping or this was an unrecognised\n \/\/ version.\n if(m_EventNames.isEmpty())\n return;\n\n m_Event2RGP.resize(m_Ctx.GetLastAction()->eventId + 1);\n\n \/\/ linearId 0 is invalid, so map to eventId 0.\n \/\/ the first real event will be linearId 1\n m_RGP2Event.push_back(0);\n\n CreateMapping(m_Ctx.CurRootActions());\n}\n\nQString RGPInterop::EncodeCommand(RGPCommand command, QVariantList params)\n{\n QString ret;\n\n QString cmd = ToQStr(command);\n\n ret += lit(\"command=%1\\n\").arg(cmd);\n\n \/\/ iterate params in pair, name and value\n for(int i = 0; i + 1 < params.count(); i += 2)\n ret += QFormatStr(\"%1.%2=%3\\n\").arg(cmd).arg(params[i].toString()).arg(params[i + 1].toString());\n\n ret += lit(\"endcommand=%1\\n\").arg(cmd);\n\n return ret;\n}\n\nbool RGPInterop::DecodeCommand(QString command)\n{\n QStringList lines = command.trimmed().split(QLatin1Char('\\n'));\n\n if(lines[0].indexOf(lit(\"command=\")) != 0 || lines.last().indexOf(lit(\"endcommand=\")) != 0)\n {\n qWarning() << \"Malformed RGP command:\\n\" << command;\n return false;\n }\n\n QString commandName = lines[0].split(QLatin1Char('='))[1];\n\n if(lines.last().split(QLatin1Char('='))[1] != commandName)\n {\n qWarning() << \"Mismatch between command and endcommand:\\n\" << command;\n return false;\n }\n\n lines.pop_front();\n lines.pop_back();\n\n QVariantList params;\n\n QString prefix = commandName + lit(\".\");\n\n for(QString ¶m : lines)\n {\n int eq = param.indexOf(QLatin1Char('='));\n\n if(eq < 0)\n {\n qWarning() << \"Malformed param: \" << param;\n continue;\n }\n\n QString key = param.left(eq);\n QString value = param.mid(eq + 1);\n\n if(!key.startsWith(prefix))\n {\n qWarning() << \"Malformed param key for\" << commandName << \": \" << key;\n continue;\n }\n\n key = key.mid(prefix.count());\n\n params << key << value;\n }\n\n if(commandName == ToQStr(RGPCommand::SetEvent))\n {\n RGPInteropEvent ev;\n ev.fromParams(m_Version, params);\n\n EventSelected(ev);\n\n return true;\n }\n else if(commandName == ToQStr(RGPCommand::Initialize))\n {\n RGPInteropInit init;\n init.fromParams(m_Version, params);\n\n \/\/ TODO: decode the params here. This will contain the interop\n \/\/ version and the name of the tool connected to RenderDoc\n\n return true;\n }\n else if(commandName == ToQStr(RGPCommand::Terminate))\n {\n \/\/ RGP has shut down so disconnect the socket etc\n emit m_Socket->disconnected();\n return true;\n }\n else\n {\n qWarning() << \"Unrecognised command: \" << commandName;\n }\n\n return false;\n}\n\nvoid RGPInterop::ProcessReadBuffer()\n{\n \/\/ we might have partial data, so wait until we have a full command\n do\n {\n int idx = m_ReadBuffer.indexOf(\"endcommand=\");\n\n \/\/ if we don't have endcommand= yet, we don't have a full command\n if(idx < 0)\n return;\n\n idx = m_ReadBuffer.indexOf('\\n', idx);\n\n \/\/ also break if we don't have the full line yet including newline.\n if(idx < 0)\n return;\n\n \/\/ extract the command and decode as UTF-8\n QString command = QString::fromUtf8(m_ReadBuffer.data(), idx + 1);\n\n \/\/ remove the command from our buffer, to retain any partial subsequent command we might have\n m_ReadBuffer.remove(0, idx + 1);\n\n \/\/ process this command\n DecodeCommand(command);\n\n \/\/ loop again - we might have read multiple commands\n } while(true);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"resizeHandler.h\"\n\n#include <algorithm>\n\t\nResizeHandler::ResizeHandler(\n\t\tNodeElement* const resizingNode\n\t\t, ElementImpl* const elementImpl\n\t\t)\n\t: mResizingNode(resizingNode)\n\t, mElementImpl(elementImpl)\n{\n}\n\nvoid ResizeHandler::resize(QRectF newContents, QPointF newPos) const\n{\n\tnewContents.moveTo(0, 0);\n\n\tsortChildrenIfNeeded();\n\tgripeIfMinimizesToChildrenContainer(newContents);\n\n\tif (!mResizingNode->isFolded()) {\n\t\tresizeAccordingToChildren(newContents, newPos);\n\t}\n\n\tnormalizeSize(newContents);\n\n\tnewContents.moveTo(newPos);\n\tmResizingNode->setGeometry(newContents);\n\tmResizingNode->storeGeometry();\n\n\tparentResizeCall();\n\n\tif (SettingsManager::value(\"ActivateGrid\").toBool()) {\n\t\tmResizingNode->alignToGrid();\n\t}\n}\n\nqreal ResizeHandler::maxChildWidth() const\n{\n\tqreal maxChildWidthValue = 0;\n\n\tforeach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tconst NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);\n\t\tif (!curItem) {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tmaxChildWidthValue = std::max(maxChildWidthValue, curItem->contents().width());\n\t}\n\tif (maxChildWidthValue == 0) {\n\t\tmaxChildWidthValue = mResizingNode->childrenBoundingRect().width();\n\t}\n\n\treturn maxChildWidthValue;\n}\n\nvoid ResizeHandler::sortChildrenIfNeeded() const\n{\n\tif (!mElementImpl->isSortingContainer()) {\n\t\treturn;\n\t}\n\n\tint const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\tqreal curChildY = sizeOfForestalling + mTitlePadding;\n\tqreal maxChildWidthValue = maxChildWidth();\n\n\tforeach (QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tQGraphicsRectItem* const placeholder = mResizingNode->placeholder();\n\n\t\tif(placeholder != NULL && childItem == placeholder){\n\t\t\tQRectF const rect(sizeOfForestalling, curChildY,\n\t\t\t\tmaxChildWidthValue, placeholder->rect().height());\n\t\t\tplaceholder->setRect(rect);\n\t\t\tcurChildY += placeholder->rect().height() + mChildSpacing;\n\t\t}\n\n\t\tNodeElement* const curItem = dynamic_cast<NodeElement* const>(childItem);\n\t\tif (!curItem) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tqreal const necessaryWidth =\n\t\t\tmElementImpl->maximizesChildren()\n\t\t\t? maxChildWidthValue\n\t\t\t: curItem->contents().width();\n\t\tQRectF const rect(sizeOfForestalling, curChildY, necessaryWidth, curItem->contents().height());\n\n\t\tcurItem->setGeometry(rect);\n\t\tcurItem->storeGeometry();\n\t\tcurChildY += curItem->contents().height() + mElementImpl->sizeOfChildrenForestalling() + mChildSpacing;\n\t}\n}\n\nvoid ResizeHandler::gripeIfMinimizesToChildrenContainer(QRectF& contents) const\n{\n\tif (mElementImpl->minimizesToChildren()) {\n\t\tcontents = QRectF();\n\t}\n}\n\nvoid ResizeHandler::parentResizeCall() const {\n\tNodeElement* const parItem = dynamic_cast<NodeElement* const>(mResizingNode->parentItem());\n\tif (parItem) {\n\t\tResizeHandler handler(parItem, parItem->elementImpl());\n\t\thandler.resize(parItem->contents(), parItem->pos());\n\t}\n}\n\nvoid ResizeHandler::normalizeSize(QRectF& newContents) const {\n\tif (newContents.width() < mMinSize) {\n\t\tnewContents.setWidth(mResizingNode->foldedContents().width());\n\t}\n\n\tif (newContents.height() < mMinSize) {\n\t\tnewContents.setHeight(mResizingNode->foldedContents().height());\n\t}\n}\n\nvoid ResizeHandler::resizeAccordingToChildren(QRectF& newContents, QPointF& newPos) const {\n\t\/* \n\t* AAAA!!! Who knows why is this code existed????!!!\n\t*\n\tforeach (QGraphicsItem *childItem, childItems()) {\n\t\tNodeElement* curItem = dynamic_cast<NodeElement*>(childItem);\n\t\tif (curItem && curItem->isPort() && newContents != mContents) {\n\t\t\tcurItem->resizeChild(newContents, mContents);\n\t\t}\n\t}\n\t*\/\n\n\t\/\/\/ Vector of minimum negative XY child deflection from top left corner.\n\tQPointF const childDeflectionVector = childDeflection();\n\n\tmoveChildren(-childDeflectionVector);\n\t\/\/newPos += childDeflectionVector;\n\n\texpandByChildren(newContents);\n}\n\nQPointF ResizeHandler::childDeflection() const\n{\n\tQPointF childDeflectionVector = QPointF(0, 0);\n\tint const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\n\tforeach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tconst NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);\n\t\tif (!curItem || curItem->isPort()) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tchildDeflectionVector.setX(\n\t\t\t\tstd::min(curItem->pos().x() - sizeOfForestalling, childDeflectionVector.x())\n\t\t\t\t);\n\t\tchildDeflectionVector.setY(\n\t\t\t\tstd::min(curItem->pos().y() - sizeOfForestalling, childDeflectionVector.y())\n\t\t\t\t);\n\t}\n\n\treturn childDeflectionVector;\n}\n\nvoid ResizeHandler::moveChildren(QPointF const &shift) const\n{\n\tqreal const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\n\tforeach (QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tNodeElement* const curItem = dynamic_cast<NodeElement* const>(childItem);\n\t\tif (!curItem || !curItem->isPort()) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurItem->moveBy(shift.x(), shift.y());\n\t\n\t\tQPointF pos(\n\t\t\t\tstd::max(curItem->pos().x(), sizeOfForestalling)\n\t\t\t\t, std::max(curItem->pos().y(), sizeOfForestalling)\n\t\t\t);\n\t\t\/\/\/returns object to the parent area\n\t\tcurItem->setPos(pos);\n\t}\n}\n\nvoid ResizeHandler::expandByChildren(QRectF& contents) const\n{\n\tint const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\n\tforeach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tQRectF curChildItemBoundingRect = childBoundingRect(childItem, contents);\n\n\t\tif (\n\t\t\tcurChildItemBoundingRect.width() == 0\n\t\t\t||\n\t\t\tcurChildItemBoundingRect.height() == 0\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ it seems to be more appropriate to use childItem->pos() but it causes\n\t\t\/\/ bad behaviour when dropping one element to another\n\t\tcurChildItemBoundingRect.translate(childItem->scenePos() - mResizingNode->scenePos());\n\n\t\tcontents.setLeft(\n\t\t\t\tstd::min(curChildItemBoundingRect.left() - sizeOfForestalling\n\t\t\t\t \t, contents.left())\n\t\t\t\t);\n\n\t\tcontents.setRight(\n\t\t\t\tstd::max(curChildItemBoundingRect.right() + sizeOfForestalling\n\t\t\t\t \t, contents.right())\n\t\t\t\t);\n\n\t\tcontents.setTop(\n\t\t\t\tstd::min(curChildItemBoundingRect.top() - sizeOfForestalling\n\t\t\t\t \t, contents.top())\n\t\t\t\t);\n\n\t\tcontents.setBottom(\n\t\t\t\tstd::max(curChildItemBoundingRect.bottom() + sizeOfForestalling\n\t\t\t\t \t, contents.bottom())\n\t\t\t\t);\n\t}\n}\n\nQRectF ResizeHandler::childBoundingRect(const QGraphicsItem* const childItem, QRectF const &contents) const\n{\n\tQRectF boundingRect;\n\n\tif (childItem == mResizingNode->placeholder()) {\n\t\tboundingRect = childItem->boundingRect();\n\n\t\tint const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\t\tboundingRect.setLeft(contents.left() + sizeOfForestalling);\n\t\tboundingRect.setRight(contents.right() - sizeOfForestalling);\n\t\t\n\t\treturn boundingRect;\n\t}\n\n\tconst NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);\n\tif (curItem && !curItem->isPort()) {\n\t\tboundingRect = curItem->contents();\n\t}\n\n\treturn boundingRect;\n}\n<commit_msg>Changed std::max\/min to qMax\/qMin.<commit_after>#include \"resizeHandler.h\"\n\n#include <algorithm>\n\t\nResizeHandler::ResizeHandler(\n\t\tNodeElement* const resizingNode\n\t\t, ElementImpl* const elementImpl\n\t\t)\n\t: mResizingNode(resizingNode)\n\t, mElementImpl(elementImpl)\n{\n}\n\nvoid ResizeHandler::resize(QRectF newContents, QPointF newPos) const\n{\n\tnewContents.moveTo(0, 0);\n\n\tsortChildrenIfNeeded();\n\tgripeIfMinimizesToChildrenContainer(newContents);\n\n\tif (!mResizingNode->isFolded()) {\n\t\tresizeAccordingToChildren(newContents, newPos);\n\t}\n\n\tnormalizeSize(newContents);\n\n\tnewContents.moveTo(newPos);\n\tmResizingNode->setGeometry(newContents);\n\tmResizingNode->storeGeometry();\n\n\tparentResizeCall();\n\n\tif (SettingsManager::value(\"ActivateGrid\").toBool()) {\n\t\tmResizingNode->alignToGrid();\n\t}\n}\n\nqreal ResizeHandler::maxChildWidth() const\n{\n\tqreal maxChildWidthValue = 0;\n\n\tforeach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tconst NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);\n\t\tif (!curItem) {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tmaxChildWidthValue = qMax(maxChildWidthValue, curItem->contents().width());\n\t}\n\tif (maxChildWidthValue == 0) {\n\t\tmaxChildWidthValue = mResizingNode->childrenBoundingRect().width();\n\t}\n\n\treturn maxChildWidthValue;\n}\n\nvoid ResizeHandler::sortChildrenIfNeeded() const\n{\n\tif (!mElementImpl->isSortingContainer()) {\n\t\treturn;\n\t}\n\n\tint const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\tqreal curChildY = sizeOfForestalling + mTitlePadding;\n\tqreal maxChildWidthValue = maxChildWidth();\n\n\tforeach (QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tQGraphicsRectItem* const placeholder = mResizingNode->placeholder();\n\n\t\tif(placeholder != NULL && childItem == placeholder){\n\t\t\tQRectF const rect(sizeOfForestalling, curChildY,\n\t\t\t\tmaxChildWidthValue, placeholder->rect().height());\n\t\t\tplaceholder->setRect(rect);\n\t\t\tcurChildY += placeholder->rect().height() + mChildSpacing;\n\t\t}\n\n\t\tNodeElement* const curItem = dynamic_cast<NodeElement* const>(childItem);\n\t\tif (!curItem) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tqreal const necessaryWidth =\n\t\t\tmElementImpl->maximizesChildren()\n\t\t\t? maxChildWidthValue\n\t\t\t: curItem->contents().width();\n\t\tQRectF const rect(sizeOfForestalling, curChildY, necessaryWidth, curItem->contents().height());\n\n\t\tcurItem->setGeometry(rect);\n\t\tcurItem->storeGeometry();\n\t\tcurChildY += curItem->contents().height() + mElementImpl->sizeOfChildrenForestalling() + mChildSpacing;\n\t}\n}\n\nvoid ResizeHandler::gripeIfMinimizesToChildrenContainer(QRectF& contents) const\n{\n\tif (mElementImpl->minimizesToChildren()) {\n\t\tcontents = QRectF();\n\t}\n}\n\nvoid ResizeHandler::parentResizeCall() const\n{\n\tNodeElement* const parItem = dynamic_cast<NodeElement* const>(mResizingNode->parentItem());\n\tif (parItem) {\n\t\tResizeHandler handler(parItem, parItem->elementImpl());\n\t\thandler.resize(parItem->contents(), parItem->pos());\n\t}\n}\n\nvoid ResizeHandler::normalizeSize(QRectF& newContents) const\n{\n\tif (newContents.width() < mMinSize) {\n\t\tnewContents.setWidth(mResizingNode->foldedContents().width());\n\t}\n\n\tif (newContents.height() < mMinSize) {\n\t\tnewContents.setHeight(mResizingNode->foldedContents().height());\n\t}\n}\n\nvoid ResizeHandler::resizeAccordingToChildren(QRectF& newContents, QPointF& newPos) const\n{\n\t\/* \n\t* AAAA!!! Who knows why is this code existed????!!!\n\t*\n\tforeach (QGraphicsItem *childItem, childItems()) {\n\t\tNodeElement* curItem = dynamic_cast<NodeElement*>(childItem);\n\t\tif (curItem && curItem->isPort() && newContents != mContents) {\n\t\t\tcurItem->resizeChild(newContents, mContents);\n\t\t}\n\t}\n\t*\/\n\n\t\/\/\/ Vector of minimum negative XY child deflection from top left corner.\n\tQPointF const childDeflectionVector = childDeflection();\n\n\tmoveChildren(-childDeflectionVector);\n\t\/\/newPos += childDeflectionVector;\n\n\texpandByChildren(newContents);\n}\n\nQPointF ResizeHandler::childDeflection() const\n{\n\tQPointF childDeflectionVector = QPointF(0, 0);\n\tint const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\n\tforeach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tconst NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);\n\t\tif (!curItem || curItem->isPort()) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tchildDeflectionVector.setX(\n\t\t\t\tqMin(curItem->pos().x() - sizeOfForestalling, childDeflectionVector.x())\n\t\t\t\t);\n\t\tchildDeflectionVector.setY(\n\t\t\t\tqMin(curItem->pos().y() - sizeOfForestalling, childDeflectionVector.y())\n\t\t\t\t);\n\t}\n\n\treturn childDeflectionVector;\n}\n\nvoid ResizeHandler::moveChildren(QPointF const &shift) const\n{\n\tqreal const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\n\tforeach (QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tNodeElement* const curItem = dynamic_cast<NodeElement* const>(childItem);\n\t\tif (!curItem || !curItem->isPort()) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurItem->moveBy(shift.x(), shift.y());\n\t\n\t\tQPointF pos(\n\t\t\t\tqMax(curItem->pos().x(), sizeOfForestalling)\n\t\t\t\t, qMax(curItem->pos().y(), sizeOfForestalling)\n\t\t\t);\n\t\t\/\/\/returns object to the parent area\n\t\tcurItem->setPos(pos);\n\t}\n}\n\nvoid ResizeHandler::expandByChildren(QRectF& contents) const\n{\n\tint const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\n\tforeach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {\n\t\tQRectF curChildItemBoundingRect = childBoundingRect(childItem, contents);\n\n\t\tif (\n\t\t\tcurChildItemBoundingRect.width() == 0\n\t\t\t||\n\t\t\tcurChildItemBoundingRect.height() == 0\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ it seems to be more appropriate to use childItem->pos() but it causes\n\t\t\/\/ bad behaviour when dropping one element to another\n\t\tcurChildItemBoundingRect.translate(childItem->scenePos() - mResizingNode->scenePos());\n\n\t\tcontents.setLeft(\n\t\t\t\tqMin(curChildItemBoundingRect.left() - sizeOfForestalling\n\t\t\t\t \t, contents.left())\n\t\t\t\t);\n\n\t\tcontents.setRight(\n\t\t\t\tqMax(curChildItemBoundingRect.right() + sizeOfForestalling\n\t\t\t\t \t, contents.right())\n\t\t\t\t);\n\n\t\tcontents.setTop(\n\t\t\t\tqMin(curChildItemBoundingRect.top() - sizeOfForestalling\n\t\t\t\t \t, contents.top())\n\t\t\t\t);\n\n\t\tcontents.setBottom(\n\t\t\t\tqMax(curChildItemBoundingRect.bottom() + sizeOfForestalling\n\t\t\t\t \t, contents.bottom())\n\t\t\t\t);\n\t}\n}\n\nQRectF ResizeHandler::childBoundingRect(const QGraphicsItem* const childItem, QRectF const &contents) const\n{\n\tQRectF boundingRect;\n\n\tif (childItem == mResizingNode->placeholder()) {\n\t\tboundingRect = childItem->boundingRect();\n\n\t\tint const sizeOfForestalling = mElementImpl->sizeOfForestalling();\n\t\tboundingRect.setLeft(contents.left() + sizeOfForestalling);\n\t\tboundingRect.setRight(contents.right() - sizeOfForestalling);\n\t\t\n\t\treturn boundingRect;\n\t}\n\n\tconst NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);\n\tif (curItem && !curItem->isPort()) {\n\t\tboundingRect = curItem->contents();\n\t}\n\n\treturn boundingRect;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * %injeqt copyright begin%\n * Copyright 2014 Rafał Malinowski (rafal.przemyslaw.malinowski@gmail.com)\n * %injeqt copyright end%\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\n#include \"factory-method.h\"\n\n#include \"extract-interfaces.h\"\n\n#include <cassert>\n\nnamespace injeqt { namespace internal {\n\nfactory_method::factory_method()\n{\n}\n\nfactory_method::factory_method(QMetaMethod meta_method) :\n\t_object_type{meta_method.enclosingMetaObject()},\n\t_result_type{QMetaType::metaObjectForType(meta_method.returnType())},\n\t_meta_method{std::move(meta_method)}\n{\n\tassert(meta_method.methodType() == QMetaMethod::Method || meta_method.methodType() == QMetaMethod::Slot);\n\tassert(meta_method.parameterCount() == 0);\n\tassert(meta_method.enclosingMetaObject() != nullptr);\n\n}\n\nbool factory_method::is_empty() const\n{\n\treturn !_meta_method.isValid();\n}\n\nconst type & factory_method::object_type() const\n{\n\tassert(!is_empty());\n\n\treturn _object_type;\n}\n\nconst type & factory_method::result_type() const\n{\n\tassert(!is_empty());\n\n\treturn _result_type;\n}\n\nconst QMetaMethod & factory_method::meta_method() const\n{\n\treturn _meta_method;\n}\n\nstd::unique_ptr<QObject> factory_method::invoke(QObject *on) const\n{\n\tassert(!is_empty());\n\tassert(on != nullptr);\n\tassert(meta_method().enclosingMetaObject() == on->metaObject());\n\n\tQObject *result = nullptr;\n\t_meta_method.invoke(on, QReturnArgument<QObject *>((_result_type.name() + \"*\").c_str(), result)); \/\/ TODO: check for false result\n\treturn std::unique_ptr<QObject>{result};\n}\n\nbool operator == (const factory_method &x, const factory_method &y)\n{\n\tif (x.object_type() != y.object_type())\n\t\treturn false;\n\n\tif (x.result_type() != y.result_type())\n\t\treturn false;\n\n\treturn true;\n}\n\nbool operator != (const factory_method &x, const factory_method &y)\n{\n\treturn !(x == y);\n}\n\nfactory_method make_factory_method(const type &t, const type &f)\n{\n\tassert(!t.is_empty());\n\tassert(!t.is_qobject());\n\tassert(!f.is_empty());\n\tassert(!f.is_qobject());\n\n\tauto meta_object = f.meta_object();\n\tauto method_count = meta_object->methodCount();\n\tauto factory_methods = std::vector<factory_method>{};\n\n\tfor (decltype(method_count) i = 0; i < method_count; i++)\n\t{\n\t\tauto method = meta_object->method(i);\n\t\tif (method.parameterCount() != 0)\n\t\t\tcontinue;\n\t\tauto return_type_meta_object = QMetaType::metaObjectForType(method.returnType());\n\t\tif (!return_type_meta_object)\n\t\t\tcontinue;\n\t\tauto return_type = type{return_type_meta_object};\n\t\tauto interfaces = extract_interfaces(return_type);\n\t\tif (interfaces.contains(t))\n\t\t\tfactory_methods.emplace_back(method);\n\t}\n\n\tif (factory_methods.empty())\n\t\treturn factory_method{};\n\telse if (factory_methods.size() > 1)\n\t\treturn factory_method{};\n\telse\n\t\treturn factory_methods.front();\n}\n\n}}\n<commit_msg>simplify make_factory_method<commit_after>\/*\n * %injeqt copyright begin%\n * Copyright 2014 Rafał Malinowski (rafal.przemyslaw.malinowski@gmail.com)\n * %injeqt copyright end%\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\n#include \"factory-method.h\"\n\n#include \"extract-interfaces.h\"\n\n#include <cassert>\n\nnamespace injeqt { namespace internal {\n\nfactory_method::factory_method()\n{\n}\n\nfactory_method::factory_method(QMetaMethod meta_method) :\n\t_object_type{meta_method.enclosingMetaObject()},\n\t_result_type{QMetaType::metaObjectForType(meta_method.returnType())},\n\t_meta_method{std::move(meta_method)}\n{\n\tassert(meta_method.methodType() == QMetaMethod::Method || meta_method.methodType() == QMetaMethod::Slot);\n\tassert(meta_method.parameterCount() == 0);\n\tassert(meta_method.enclosingMetaObject() != nullptr);\n\n}\n\nbool factory_method::is_empty() const\n{\n\treturn !_meta_method.isValid();\n}\n\nconst type & factory_method::object_type() const\n{\n\tassert(!is_empty());\n\n\treturn _object_type;\n}\n\nconst type & factory_method::result_type() const\n{\n\tassert(!is_empty());\n\n\treturn _result_type;\n}\n\nconst QMetaMethod & factory_method::meta_method() const\n{\n\treturn _meta_method;\n}\n\nstd::unique_ptr<QObject> factory_method::invoke(QObject *on) const\n{\n\tassert(!is_empty());\n\tassert(on != nullptr);\n\tassert(meta_method().enclosingMetaObject() == on->metaObject());\n\n\tQObject *result = nullptr;\n\t_meta_method.invoke(on, QReturnArgument<QObject *>((_result_type.name() + \"*\").c_str(), result)); \/\/ TODO: check for false result\n\treturn std::unique_ptr<QObject>{result};\n}\n\nbool operator == (const factory_method &x, const factory_method &y)\n{\n\tif (x.object_type() != y.object_type())\n\t\treturn false;\n\n\tif (x.result_type() != y.result_type())\n\t\treturn false;\n\n\treturn true;\n}\n\nbool operator != (const factory_method &x, const factory_method &y)\n{\n\treturn !(x == y);\n}\n\nfactory_method make_factory_method(const type &t, const type &f)\n{\n\tassert(!t.is_empty());\n\tassert(!t.is_qobject());\n\tassert(!f.is_empty());\n\tassert(!f.is_qobject());\n\n\tauto meta_object = f.meta_object();\n\tauto method_count = meta_object->methodCount();\n\tauto factory_methods = std::vector<factory_method>{};\n\n\tfor (decltype(method_count) i = 0; i < method_count; i++)\n\t{\n\t\tauto method = meta_object->method(i);\n\t\tif (method.parameterCount() != 0)\n\t\t\tcontinue;\n\t\tauto return_type_meta_object = QMetaType::metaObjectForType(method.returnType());\n\t\tif (!return_type_meta_object)\n\t\t\tcontinue;\n\t\tauto return_type = type{return_type_meta_object};\n\t\tauto interfaces = extract_interfaces(return_type);\n\t\tif (interfaces.contains(t))\n\t\t\tfactory_methods.emplace_back(method);\n\t}\n\n\tif (factory_methods.size() == 1)\n\t\treturn factory_methods.front();\n\telse\n\t\treturn factory_method{};\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Process CM4all commands in a HTML stream, e.g. embeddings.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_replace.hxx\"\n#include \"FacadeIstream.hxx\"\n#include \"Sink.hxx\"\n#include \"growing_buffer.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"pool.hxx\"\n\n#include <inline\/poison.h>\n#include <daemon\/log.h>\n\n#include <glib.h>\n\n#include <assert.h>\n\nstruct ReplaceIstream final : FacadeIstream {\n struct Substitution final : IstreamSink {\n Substitution *next = nullptr;\n ReplaceIstream &replace;\n const off_t start;\n off_t end;\n\n Substitution(ReplaceIstream &_replace, off_t _start, off_t _end,\n Istream &_input)\n :IstreamSink(_input),\n replace(_replace),\n start(_start), end(_end)\n {\n }\n\n bool IsDefined() const {\n return input.IsDefined();\n }\n\n off_t GetAvailable(bool partial) const {\n return input.GetAvailable(partial);\n }\n\n void Read() {\n input.Read();\n }\n\n using IstreamSink::ClearAndCloseInput;\n\n gcc_pure\n bool IsActive() const;\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n void OnEof() override;\n void OnError(GError *error) override;\n };\n\n bool finished = false, read_locked = false;\n bool had_input, had_output;\n\n GrowingBuffer *const buffer;\n off_t source_length = 0, position = 0;\n\n \/**\n * The offset given by istream_replace_settle() or the end offset\n * of the last substitution (whichever is bigger).\n *\/\n off_t settled_position = 0;\n\n GrowingBufferReader reader;\n\n Substitution *first_substitution = nullptr,\n **append_substitution_p = &first_substitution;\n\n#ifndef NDEBUG\n off_t last_substitution_end = 0;\n#endif\n\n ReplaceIstream(struct pool &p, Istream &_input);\n\n using FacadeIstream::GetPool;\n using FacadeIstream::HasInput;\n\n void DestroyReplace();\n\n \/**\n * Is the buffer at the end-of-file position?\n *\/\n bool IsBufferAtEOF() const {\n return position == source_length;\n }\n\n \/**\n * Is the object at end-of-file?\n *\/\n bool IsEOF() const {\n return !input.IsDefined() && finished &&\n first_substitution == nullptr &&\n IsBufferAtEOF();\n }\n\n \/**\n * Copy the next chunk from the source buffer to the istream\n * handler.\n *\n * @return 0 if the istream handler is not blocking; the number of\n * bytes remaining in the buffer if it is blocking\n *\/\n size_t TryReadFromBuffer();\n\n \/**\n * Copy data from the source buffer to the istream handler.\n *\n * @return 0 if the istream handler is not blocking; the number of\n * bytes remaining in the buffer if it is blocking\n *\/\n size_t ReadFromBuffer(size_t max_length);\n\n size_t ReadFromBufferLoop(off_t end);\n\n void TryRead();\n\n void ReadCheckEmpty();\n\n \/**\n * Read data from substitution objects.\n *\/\n bool ReadSubstitution();\n\n \/**\n * Activate the next substitution object after s.\n *\/\n void ToNextSubstitution(ReplaceIstream::Substitution *s);\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n void OnEof() override;\n void OnError(GError *error) override;\n\n \/* virtual methods from class Istream *\/\n\n off_t _GetAvailable(bool partial) override;\n void _Read() override;\n void _Close() override;\n};\n\nstatic GQuark\nreplace_quark(void)\n{\n return g_quark_from_static_string(\"replace\");\n}\n\n\/**\n * Is this substitution object is active, i.e. its data is the next\n * being written?\n *\/\nbool\nReplaceIstream::Substitution::IsActive() const\n{\n assert(replace.first_substitution != nullptr);\n assert(replace.first_substitution->start <= start);\n assert(start >= replace.position);\n\n return this == replace.first_substitution && replace.position == start;\n}\n\nvoid\nReplaceIstream::ToNextSubstitution(ReplaceIstream::Substitution *s)\n{\n assert(first_substitution == s);\n assert(s->IsActive());\n assert(!s->IsDefined());\n assert(s->start <= s->end);\n\n reader.Skip(s->end - s->start);\n position = s->end;\n\n first_substitution = s->next;\n if (first_substitution == nullptr) {\n assert(append_substitution_p == &s->next);\n append_substitution_p = &first_substitution;\n }\n\n p_free(&GetPool(), s);\n\n assert(first_substitution == nullptr ||\n first_substitution->start >= position);\n\n if (IsEOF()) {\n DestroyEof();\n return;\n }\n\n \/* don't recurse if we're being called from ReadSubstitution() *\/\n if (!read_locked) {\n const ScopePoolRef ref(GetPool() TRACE_ARGS);\n TryRead();\n }\n}\n\n\/*\n * istream handler\n *\n *\/\n\ninline size_t\nReplaceIstream::Substitution::OnData(const void *data, size_t length)\n{\n if (IsActive()) {\n replace.had_output = true;\n return replace.InvokeData(data, length);\n } else\n return 0;\n}\n\ninline void\nReplaceIstream::Substitution::OnEof()\n{\n input.Clear();\n\n if (IsActive())\n replace.ToNextSubstitution(this);\n}\n\ninline void\nReplaceIstream::Substitution::OnError(GError *error)\n{\n ClearInput();\n\n replace.DestroyReplace();\n\n if (replace.HasInput())\n replace.ClearAndCloseInput();\n\n replace.DestroyError(error);\n}\n\n\/*\n * misc methods\n *\n *\/\n\nvoid\nReplaceIstream::DestroyReplace()\n{\n assert(source_length != (off_t)-1);\n\n \/* source_length -1 is the \"destroyed\" marker *\/\n source_length = (off_t)-1;\n\n while (first_substitution != nullptr) {\n auto *s = first_substitution;\n first_substitution = s->next;\n\n if (s->IsDefined())\n s->ClearAndCloseInput();\n }\n}\n\n\nbool\nReplaceIstream::ReadSubstitution()\n{\n while (first_substitution != nullptr && first_substitution->IsActive()) {\n auto *s = first_substitution;\n\n read_locked = true;\n\n if (s->IsDefined())\n s->Read();\n else\n ToNextSubstitution(s);\n\n read_locked = false;\n\n \/* we assume the substitution object is blocking if it hasn't\n reached EOF with this one call *\/\n if (s == first_substitution)\n return true;\n }\n\n return false;\n}\n\ninline size_t\nReplaceIstream::ReadFromBuffer(size_t max_length)\n{\n assert(max_length > 0);\n\n auto src = reader.Read();\n assert(!src.IsNull());\n assert(!src.IsEmpty());\n\n if (src.size > max_length)\n src.size = max_length;\n\n had_output = true;\n size_t nbytes = InvokeData(src.data, src.size);\n assert(nbytes <= src.size);\n\n if (nbytes == 0)\n \/* istream_replace has been closed *\/\n return src.size;\n\n reader.Consume(nbytes);\n position += nbytes;\n\n assert(position <= source_length);\n\n return src.size - nbytes;\n}\n\ninline size_t\nReplaceIstream::ReadFromBufferLoop(off_t end)\n{\n assert(end > position);\n assert(end <= source_length);\n\n \/* this loop is required to cross the GrowingBuffer borders *\/\n size_t rest;\n do {\n#ifndef NDEBUG\n PoolNotify notify(GetPool());\n#endif\n\n size_t max_length = (size_t)(end - position);\n rest = ReadFromBuffer(max_length);\n\n#ifndef NDEBUG\n if (notify.Denotify()) {\n assert(rest > 0);\n break;\n }\n#endif\n\n assert(position <= end);\n } while (rest == 0 && position < end);\n\n return rest;\n}\n\nsize_t\nReplaceIstream::TryReadFromBuffer()\n{\n off_t end;\n if (first_substitution == nullptr) {\n if (finished)\n end = source_length;\n else if (position < settled_position)\n end = settled_position;\n else\n \/* block after the last substitution, unless the caller\n has already set the \"finished\" flag *\/\n return 1;\n\n assert(position < source_length);\n } else {\n end = first_substitution->start;\n assert(end >= position);\n\n if (end == position)\n return 0;\n }\n\n size_t rest = ReadFromBufferLoop(end);\n if (rest == 0 && position == source_length &&\n first_substitution == nullptr &&\n !input.IsDefined())\n DestroyEof();\n\n return rest;\n}\n\nvoid\nReplaceIstream::TryRead()\n{\n assert(position <= source_length);\n\n \/* read until someone (input or output) blocks *\/\n size_t rest;\n do {\n bool blocking = ReadSubstitution();\n if (blocking || IsBufferAtEOF() || source_length == (off_t)-1)\n break;\n\n rest = TryReadFromBuffer();\n } while (rest == 0 && first_substitution != nullptr);\n}\n\nvoid\nReplaceIstream::ReadCheckEmpty()\n{\n assert(finished);\n assert(!input.IsDefined());\n\n if (IsEOF())\n DestroyEof();\n else {\n const ScopePoolRef ref(GetPool() TRACE_ARGS);\n TryRead();\n }\n}\n\n\n\/*\n * input handler\n *\n *\/\n\ninline size_t\nReplaceIstream::OnData(const void *data, size_t length)\n{\n had_input = true;\n\n if (source_length >= 8 * 1024 * 1024) {\n ClearAndCloseInput();\n DestroyReplace();\n\n GError *error =\n g_error_new_literal(replace_quark(), 0,\n \"file too large for processor\");\n DestroyError(error);\n return 0;\n }\n\n growing_buffer_write_buffer(buffer, data, length);\n source_length += (off_t)length;\n\n reader.Update();\n\n const ScopePoolRef ref(GetPool() TRACE_ARGS);\n\n TryReadFromBuffer();\n if (!input.IsDefined())\n \/* the istream API mandates that we must return 0 if the\n stream is finished *\/\n length = 0;\n\n return length;\n}\n\ninline void\nReplaceIstream::OnEof()\n{\n input.Clear();\n\n if (finished)\n ReadCheckEmpty();\n}\n\ninline void\nReplaceIstream::OnError(GError *error)\n{\n DestroyReplace();\n input.Clear();\n DestroyError(error);\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nReplaceIstream::_GetAvailable(bool partial)\n{\n off_t length, position2 = 0, l;\n\n if (!partial && !finished)\n \/* we don't know yet how many substitutions will come, so we\n cannot calculate the exact rest *\/\n return (off_t)-1;\n\n \/* get available bytes from input *\/\n\n if (HasInput() && finished) {\n length = input.GetAvailable(partial);\n if (length == (off_t)-1) {\n if (!partial)\n return (off_t)-1;\n length = 0;\n }\n } else\n length = 0;\n\n \/* add available bytes from substitutions (and the source buffers\n before the substitutions) *\/\n\n position2 = position;\n\n for (auto subst = first_substitution;\n subst != nullptr; subst = subst->next) {\n assert(position2 <= subst->start);\n\n length += subst->start - position2;\n\n if (subst->IsDefined()) {\n l = subst->GetAvailable(partial);\n if (l != (off_t)-1)\n length += l;\n else if (!partial)\n return (off_t)-1;\n }\n\n position2 = subst->end;\n }\n\n \/* add available bytes from tail (if known yet) *\/\n\n if (finished)\n length += source_length - position2;\n\n return length;\n}\n\nvoid\nReplaceIstream::_Read()\n{\n const ScopePoolRef ref(GetPool() TRACE_ARGS);\n\n TryRead();\n\n if (!HasInput())\n return;\n\n had_output = false;\n\n do {\n had_input = false;\n input.Read();\n } while (had_input && !had_output && HasInput());\n}\n\nvoid\nReplaceIstream::_Close()\n{\n DestroyReplace();\n\n if (HasInput())\n ClearAndCloseInput();\n\n Destroy();\n}\n\n\/*\n * constructor\n *\n *\/\n\ninline ReplaceIstream::ReplaceIstream(struct pool &p, Istream &_input)\n :FacadeIstream(p, _input),\n buffer(growing_buffer_new(&p, 4096)),\n reader(*buffer)\n{\n}\n\nIstream *\nistream_replace_new(struct pool &pool, Istream &input)\n{\n return NewIstream<ReplaceIstream>(pool, input);\n}\n\nvoid\nistream_replace_add(Istream &istream, off_t start, off_t end,\n Istream *contents)\n{\n auto &replace = (ReplaceIstream &)istream;\n\n assert(!replace.finished);\n assert(start >= 0);\n assert(start <= end);\n assert(start >= replace.settled_position);\n assert(start >= replace.last_substitution_end);\n\n if (contents == nullptr && start == end)\n return;\n\n auto s =\n NewFromPool<ReplaceIstream::Substitution>(replace.GetPool(),\n replace, start, end,\n *contents);\n\n replace.settled_position = end;\n\n#ifndef NDEBUG\n replace.last_substitution_end = end;\n#endif\n\n *replace.append_substitution_p = s;\n replace.append_substitution_p = &s->next;\n}\n\nstatic ReplaceIstream::Substitution *\nreplace_get_last_substitution(ReplaceIstream &replace)\n{\n auto *substitution = replace.first_substitution;\n assert(substitution != nullptr);\n\n while (substitution->next != nullptr)\n substitution = substitution->next;\n\n assert(substitution->end <= replace.settled_position);\n assert(substitution->end == replace.last_substitution_end);\n return substitution;\n}\n\nvoid\nistream_replace_extend(Istream &istream, gcc_unused off_t start, off_t end)\n{\n auto &replace = (ReplaceIstream &)istream;\n assert(!replace.finished);\n\n auto *substitution = replace_get_last_substitution(replace);\n assert(substitution->start == start);\n assert(substitution->end == replace.settled_position);\n assert(substitution->end == replace.last_substitution_end);\n assert(end >= substitution->end);\n\n substitution->end = end;\n replace.settled_position = end;\n#ifndef NDEBUG\n replace.last_substitution_end = end;\n#endif\n}\n\nvoid\nistream_replace_settle(Istream &istream, off_t offset)\n{\n auto &replace = (ReplaceIstream &)istream;\n assert(!replace.finished);\n assert(offset >= replace.settled_position);\n\n replace.settled_position = offset;\n}\n\nvoid\nistream_replace_finish(Istream &istream)\n{\n auto &replace = (ReplaceIstream &)istream;\n assert(!replace.finished);\n\n replace.finished = true;\n\n if (!replace.HasInput())\n replace.ReadCheckEmpty();\n}\n<commit_msg>istream\/replace: fix nullptr dereference<commit_after>\/*\n * Process CM4all commands in a HTML stream, e.g. embeddings.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_replace.hxx\"\n#include \"FacadeIstream.hxx\"\n#include \"Sink.hxx\"\n#include \"growing_buffer.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"pool.hxx\"\n\n#include <inline\/poison.h>\n#include <daemon\/log.h>\n\n#include <glib.h>\n\n#include <assert.h>\n\nstruct ReplaceIstream final : FacadeIstream {\n struct Substitution final : IstreamSink {\n Substitution *next = nullptr;\n ReplaceIstream &replace;\n const off_t start;\n off_t end;\n\n Substitution(ReplaceIstream &_replace, off_t _start, off_t _end,\n std::nullptr_t)\n :replace(_replace),\n start(_start), end(_end)\n {\n }\n\n Substitution(ReplaceIstream &_replace, off_t _start, off_t _end,\n Istream &_input)\n :IstreamSink(_input),\n replace(_replace),\n start(_start), end(_end)\n {\n }\n\n bool IsDefined() const {\n return input.IsDefined();\n }\n\n off_t GetAvailable(bool partial) const {\n return input.GetAvailable(partial);\n }\n\n void Read() {\n input.Read();\n }\n\n using IstreamSink::ClearAndCloseInput;\n\n gcc_pure\n bool IsActive() const;\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n void OnEof() override;\n void OnError(GError *error) override;\n };\n\n bool finished = false, read_locked = false;\n bool had_input, had_output;\n\n GrowingBuffer *const buffer;\n off_t source_length = 0, position = 0;\n\n \/**\n * The offset given by istream_replace_settle() or the end offset\n * of the last substitution (whichever is bigger).\n *\/\n off_t settled_position = 0;\n\n GrowingBufferReader reader;\n\n Substitution *first_substitution = nullptr,\n **append_substitution_p = &first_substitution;\n\n#ifndef NDEBUG\n off_t last_substitution_end = 0;\n#endif\n\n ReplaceIstream(struct pool &p, Istream &_input);\n\n using FacadeIstream::GetPool;\n using FacadeIstream::HasInput;\n\n void DestroyReplace();\n\n \/**\n * Is the buffer at the end-of-file position?\n *\/\n bool IsBufferAtEOF() const {\n return position == source_length;\n }\n\n \/**\n * Is the object at end-of-file?\n *\/\n bool IsEOF() const {\n return !input.IsDefined() && finished &&\n first_substitution == nullptr &&\n IsBufferAtEOF();\n }\n\n \/**\n * Copy the next chunk from the source buffer to the istream\n * handler.\n *\n * @return 0 if the istream handler is not blocking; the number of\n * bytes remaining in the buffer if it is blocking\n *\/\n size_t TryReadFromBuffer();\n\n \/**\n * Copy data from the source buffer to the istream handler.\n *\n * @return 0 if the istream handler is not blocking; the number of\n * bytes remaining in the buffer if it is blocking\n *\/\n size_t ReadFromBuffer(size_t max_length);\n\n size_t ReadFromBufferLoop(off_t end);\n\n void TryRead();\n\n void ReadCheckEmpty();\n\n \/**\n * Read data from substitution objects.\n *\/\n bool ReadSubstitution();\n\n \/**\n * Activate the next substitution object after s.\n *\/\n void ToNextSubstitution(ReplaceIstream::Substitution *s);\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n void OnEof() override;\n void OnError(GError *error) override;\n\n \/* virtual methods from class Istream *\/\n\n off_t _GetAvailable(bool partial) override;\n void _Read() override;\n void _Close() override;\n};\n\nstatic GQuark\nreplace_quark(void)\n{\n return g_quark_from_static_string(\"replace\");\n}\n\n\/**\n * Is this substitution object is active, i.e. its data is the next\n * being written?\n *\/\nbool\nReplaceIstream::Substitution::IsActive() const\n{\n assert(replace.first_substitution != nullptr);\n assert(replace.first_substitution->start <= start);\n assert(start >= replace.position);\n\n return this == replace.first_substitution && replace.position == start;\n}\n\nvoid\nReplaceIstream::ToNextSubstitution(ReplaceIstream::Substitution *s)\n{\n assert(first_substitution == s);\n assert(s->IsActive());\n assert(!s->IsDefined());\n assert(s->start <= s->end);\n\n reader.Skip(s->end - s->start);\n position = s->end;\n\n first_substitution = s->next;\n if (first_substitution == nullptr) {\n assert(append_substitution_p == &s->next);\n append_substitution_p = &first_substitution;\n }\n\n p_free(&GetPool(), s);\n\n assert(first_substitution == nullptr ||\n first_substitution->start >= position);\n\n if (IsEOF()) {\n DestroyEof();\n return;\n }\n\n \/* don't recurse if we're being called from ReadSubstitution() *\/\n if (!read_locked) {\n const ScopePoolRef ref(GetPool() TRACE_ARGS);\n TryRead();\n }\n}\n\n\/*\n * istream handler\n *\n *\/\n\ninline size_t\nReplaceIstream::Substitution::OnData(const void *data, size_t length)\n{\n if (IsActive()) {\n replace.had_output = true;\n return replace.InvokeData(data, length);\n } else\n return 0;\n}\n\ninline void\nReplaceIstream::Substitution::OnEof()\n{\n input.Clear();\n\n if (IsActive())\n replace.ToNextSubstitution(this);\n}\n\ninline void\nReplaceIstream::Substitution::OnError(GError *error)\n{\n ClearInput();\n\n replace.DestroyReplace();\n\n if (replace.HasInput())\n replace.ClearAndCloseInput();\n\n replace.DestroyError(error);\n}\n\n\/*\n * misc methods\n *\n *\/\n\nvoid\nReplaceIstream::DestroyReplace()\n{\n assert(source_length != (off_t)-1);\n\n \/* source_length -1 is the \"destroyed\" marker *\/\n source_length = (off_t)-1;\n\n while (first_substitution != nullptr) {\n auto *s = first_substitution;\n first_substitution = s->next;\n\n if (s->IsDefined())\n s->ClearAndCloseInput();\n }\n}\n\n\nbool\nReplaceIstream::ReadSubstitution()\n{\n while (first_substitution != nullptr && first_substitution->IsActive()) {\n auto *s = first_substitution;\n\n read_locked = true;\n\n if (s->IsDefined())\n s->Read();\n else\n ToNextSubstitution(s);\n\n read_locked = false;\n\n \/* we assume the substitution object is blocking if it hasn't\n reached EOF with this one call *\/\n if (s == first_substitution)\n return true;\n }\n\n return false;\n}\n\ninline size_t\nReplaceIstream::ReadFromBuffer(size_t max_length)\n{\n assert(max_length > 0);\n\n auto src = reader.Read();\n assert(!src.IsNull());\n assert(!src.IsEmpty());\n\n if (src.size > max_length)\n src.size = max_length;\n\n had_output = true;\n size_t nbytes = InvokeData(src.data, src.size);\n assert(nbytes <= src.size);\n\n if (nbytes == 0)\n \/* istream_replace has been closed *\/\n return src.size;\n\n reader.Consume(nbytes);\n position += nbytes;\n\n assert(position <= source_length);\n\n return src.size - nbytes;\n}\n\ninline size_t\nReplaceIstream::ReadFromBufferLoop(off_t end)\n{\n assert(end > position);\n assert(end <= source_length);\n\n \/* this loop is required to cross the GrowingBuffer borders *\/\n size_t rest;\n do {\n#ifndef NDEBUG\n PoolNotify notify(GetPool());\n#endif\n\n size_t max_length = (size_t)(end - position);\n rest = ReadFromBuffer(max_length);\n\n#ifndef NDEBUG\n if (notify.Denotify()) {\n assert(rest > 0);\n break;\n }\n#endif\n\n assert(position <= end);\n } while (rest == 0 && position < end);\n\n return rest;\n}\n\nsize_t\nReplaceIstream::TryReadFromBuffer()\n{\n off_t end;\n if (first_substitution == nullptr) {\n if (finished)\n end = source_length;\n else if (position < settled_position)\n end = settled_position;\n else\n \/* block after the last substitution, unless the caller\n has already set the \"finished\" flag *\/\n return 1;\n\n assert(position < source_length);\n } else {\n end = first_substitution->start;\n assert(end >= position);\n\n if (end == position)\n return 0;\n }\n\n size_t rest = ReadFromBufferLoop(end);\n if (rest == 0 && position == source_length &&\n first_substitution == nullptr &&\n !input.IsDefined())\n DestroyEof();\n\n return rest;\n}\n\nvoid\nReplaceIstream::TryRead()\n{\n assert(position <= source_length);\n\n \/* read until someone (input or output) blocks *\/\n size_t rest;\n do {\n bool blocking = ReadSubstitution();\n if (blocking || IsBufferAtEOF() || source_length == (off_t)-1)\n break;\n\n rest = TryReadFromBuffer();\n } while (rest == 0 && first_substitution != nullptr);\n}\n\nvoid\nReplaceIstream::ReadCheckEmpty()\n{\n assert(finished);\n assert(!input.IsDefined());\n\n if (IsEOF())\n DestroyEof();\n else {\n const ScopePoolRef ref(GetPool() TRACE_ARGS);\n TryRead();\n }\n}\n\n\n\/*\n * input handler\n *\n *\/\n\ninline size_t\nReplaceIstream::OnData(const void *data, size_t length)\n{\n had_input = true;\n\n if (source_length >= 8 * 1024 * 1024) {\n ClearAndCloseInput();\n DestroyReplace();\n\n GError *error =\n g_error_new_literal(replace_quark(), 0,\n \"file too large for processor\");\n DestroyError(error);\n return 0;\n }\n\n growing_buffer_write_buffer(buffer, data, length);\n source_length += (off_t)length;\n\n reader.Update();\n\n const ScopePoolRef ref(GetPool() TRACE_ARGS);\n\n TryReadFromBuffer();\n if (!input.IsDefined())\n \/* the istream API mandates that we must return 0 if the\n stream is finished *\/\n length = 0;\n\n return length;\n}\n\ninline void\nReplaceIstream::OnEof()\n{\n input.Clear();\n\n if (finished)\n ReadCheckEmpty();\n}\n\ninline void\nReplaceIstream::OnError(GError *error)\n{\n DestroyReplace();\n input.Clear();\n DestroyError(error);\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nReplaceIstream::_GetAvailable(bool partial)\n{\n off_t length, position2 = 0, l;\n\n if (!partial && !finished)\n \/* we don't know yet how many substitutions will come, so we\n cannot calculate the exact rest *\/\n return (off_t)-1;\n\n \/* get available bytes from input *\/\n\n if (HasInput() && finished) {\n length = input.GetAvailable(partial);\n if (length == (off_t)-1) {\n if (!partial)\n return (off_t)-1;\n length = 0;\n }\n } else\n length = 0;\n\n \/* add available bytes from substitutions (and the source buffers\n before the substitutions) *\/\n\n position2 = position;\n\n for (auto subst = first_substitution;\n subst != nullptr; subst = subst->next) {\n assert(position2 <= subst->start);\n\n length += subst->start - position2;\n\n if (subst->IsDefined()) {\n l = subst->GetAvailable(partial);\n if (l != (off_t)-1)\n length += l;\n else if (!partial)\n return (off_t)-1;\n }\n\n position2 = subst->end;\n }\n\n \/* add available bytes from tail (if known yet) *\/\n\n if (finished)\n length += source_length - position2;\n\n return length;\n}\n\nvoid\nReplaceIstream::_Read()\n{\n const ScopePoolRef ref(GetPool() TRACE_ARGS);\n\n TryRead();\n\n if (!HasInput())\n return;\n\n had_output = false;\n\n do {\n had_input = false;\n input.Read();\n } while (had_input && !had_output && HasInput());\n}\n\nvoid\nReplaceIstream::_Close()\n{\n DestroyReplace();\n\n if (HasInput())\n ClearAndCloseInput();\n\n Destroy();\n}\n\n\/*\n * constructor\n *\n *\/\n\ninline ReplaceIstream::ReplaceIstream(struct pool &p, Istream &_input)\n :FacadeIstream(p, _input),\n buffer(growing_buffer_new(&p, 4096)),\n reader(*buffer)\n{\n}\n\nIstream *\nistream_replace_new(struct pool &pool, Istream &input)\n{\n return NewIstream<ReplaceIstream>(pool, input);\n}\n\nvoid\nistream_replace_add(Istream &istream, off_t start, off_t end,\n Istream *contents)\n{\n auto &replace = (ReplaceIstream &)istream;\n\n assert(!replace.finished);\n assert(start >= 0);\n assert(start <= end);\n assert(start >= replace.settled_position);\n assert(start >= replace.last_substitution_end);\n\n if (contents == nullptr && start == end)\n return;\n\n auto s = contents != nullptr\n ? NewFromPool<ReplaceIstream::Substitution>(replace.GetPool(),\n replace, start, end,\n *contents)\n : NewFromPool<ReplaceIstream::Substitution>(replace.GetPool(),\n replace, start, end,\n nullptr);\n\n replace.settled_position = end;\n\n#ifndef NDEBUG\n replace.last_substitution_end = end;\n#endif\n\n *replace.append_substitution_p = s;\n replace.append_substitution_p = &s->next;\n}\n\nstatic ReplaceIstream::Substitution *\nreplace_get_last_substitution(ReplaceIstream &replace)\n{\n auto *substitution = replace.first_substitution;\n assert(substitution != nullptr);\n\n while (substitution->next != nullptr)\n substitution = substitution->next;\n\n assert(substitution->end <= replace.settled_position);\n assert(substitution->end == replace.last_substitution_end);\n return substitution;\n}\n\nvoid\nistream_replace_extend(Istream &istream, gcc_unused off_t start, off_t end)\n{\n auto &replace = (ReplaceIstream &)istream;\n assert(!replace.finished);\n\n auto *substitution = replace_get_last_substitution(replace);\n assert(substitution->start == start);\n assert(substitution->end == replace.settled_position);\n assert(substitution->end == replace.last_substitution_end);\n assert(end >= substitution->end);\n\n substitution->end = end;\n replace.settled_position = end;\n#ifndef NDEBUG\n replace.last_substitution_end = end;\n#endif\n}\n\nvoid\nistream_replace_settle(Istream &istream, off_t offset)\n{\n auto &replace = (ReplaceIstream &)istream;\n assert(!replace.finished);\n assert(offset >= replace.settled_position);\n\n replace.settled_position = offset;\n}\n\nvoid\nistream_replace_finish(Istream &istream)\n{\n auto &replace = (ReplaceIstream &)istream;\n assert(!replace.finished);\n\n replace.finished = true;\n\n if (!replace.HasInput())\n replace.ReadCheckEmpty();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\nThe Battle Grounds 3 - A Source modification\r\nCopyright (C) 2017, The Battle Grounds 3 Team and Contributors\r\n\r\nThe Battle Grounds 3 free software; you can redistribute it and\/or\r\nmodify it under the terms of the GNU Lesser General Public\r\nLicense as published by the Free Software Foundation; either\r\nversion 2.1 of the License, or (at your option) any later version.\r\n\r\nThe Battle Grounds 3 is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\nLesser General Public License for more details.\r\n\r\nYou should have received a copy of the GNU Lesser General Public\r\nLicense along with this library; if not, write to the Free Software\r\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\nContact information:\r\nChel \"Awesome\" Trunk\t\tmail, in reverse: com . gmail @ latrunkster\r\n\r\nYou may also contact the (future) team via the Battle Grounds website and\/or forum at:\r\nbattlegrounds3.com\r\n\r\nNote that because of the sheer volume of files in the Source SDK this\r\nnotice cannot be put in all of them, but merely the ones that have any\r\nchanges from the original SDK.\r\nIn order to facilitate easy searching, all changes are and must be\r\ncommented on the following form:\r\n\r\n\/\/BG3 - <name of contributer>[ - <small description>]\r\n*\/\r\n\r\n#include \"cbase.h\"\r\n#include \"bg3_soft_info.h\"\r\n#include \"..\/shared\/bg3\/bg3_class.h\"\r\n#include \"hl2mp\/c_hl2mp_player.h\"\r\n\r\nnamespace NSoftInfo {\r\n\r\n\tstatic int g_iAmericanClassCounts[TOTAL_AMER_CLASSES];\r\n\tstatic int g_iBritishClassCounts[TOTAL_BRIT_CLASSES];\r\n\r\n\tstatic float g_flNextUpdateTime = -FLT_MAX;\r\n\r\n\tvoid Reset() {\r\n\t\tg_flNextUpdateTime = -FLT_MAX;\r\n\t\tUpdate();\r\n\t}\r\n\r\n\tvoid UpdateClasses() {\r\n\t\tmemset(g_iAmericanClassCounts, 0, sizeof(g_iAmericanClassCounts));\r\n\t\tmemset(g_iBritishClassCounts, 0, sizeof(g_iBritishClassCounts));\r\n\t\tfor (int i = 1; i <= gpGlobals->maxClients; i++) {\r\n\t\t\tCHL2MP_Player* pPlayer = ToHL2MPPlayer(UTIL_PlayerByIndex(i));\r\n\t\t\tif (pPlayer && pPlayer->GetNextClass() >= 0) {\r\n\t\t\t\tif (pPlayer->GetTeamNumber() == TEAM_AMERICANS) {\r\n\t\t\t\t\tg_iAmericanClassCounts[pPlayer->GetNextClass()]++;\r\n\t\t\t\t}\r\n\t\t\t\telse if (pPlayer->GetTeamNumber() == TEAM_BRITISH) {\r\n\t\t\t\t\tg_iBritishClassCounts[pPlayer->GetNextClass()]++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tstatic const float UPDATE_INTERVAL = 1.f;\r\n\tvoid Update() {\r\n\t\tif (gpGlobals->curtime > g_flNextUpdateTime) {\r\n\t\t\tg_flNextUpdateTime = gpGlobals->curtime + UPDATE_INTERVAL;\r\n\r\n\t\t\tUpdateClasses();\r\n\t\t}\r\n\t}\r\n\r\n\tint GetNumPlayersOfClass(const CPlayerClass* pClass) {\r\n\t\tif (pClass->m_iDefaultTeam == TEAM_AMERICANS)\r\n\t\t\treturn g_iAmericanClassCounts[pClass->m_iClassNumber];\r\n\t\telse\r\n\t\t\treturn g_iBritishClassCounts[pClass->m_iClassNumber];\r\n\t\t\t\r\n\t}\r\n}<commit_msg>Added csv_export command, will finally move off this branch after this commit<commit_after>\/*\r\nThe Battle Grounds 3 - A Source modification\r\nCopyright (C) 2017, The Battle Grounds 3 Team and Contributors\r\n\r\nThe Battle Grounds 3 free software; you can redistribute it and\/or\r\nmodify it under the terms of the GNU Lesser General Public\r\nLicense as published by the Free Software Foundation; either\r\nversion 2.1 of the License, or (at your option) any later version.\r\n\r\nThe Battle Grounds 3 is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\nLesser General Public License for more details.\r\n\r\nYou should have received a copy of the GNU Lesser General Public\r\nLicense along with this library; if not, write to the Free Software\r\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\nContact information:\r\nChel \"Awesome\" Trunk\t\tmail, in reverse: com . gmail @ latrunkster\r\n\r\nYou may also contact the (future) team via the Battle Grounds website and\/or forum at:\r\nbattlegrounds3.com\r\n\r\nNote that because of the sheer volume of files in the Source SDK this\r\nnotice cannot be put in all of them, but merely the ones that have any\r\nchanges from the original SDK.\r\nIn order to facilitate easy searching, all changes are and must be\r\ncommented on the following form:\r\n\r\n\/\/BG3 - <name of contributer>[ - <small description>]\r\n*\/\r\n\r\n#include \"cbase.h\"\r\n#include \"bg3_soft_info.h\"\r\n#include \"..\/shared\/bg3\/bg3_class.h\"\r\n#include \"..\/shared\/hl2mp\/hl2mp_gamerules.h\"\r\n#include \"hl2mp\/c_hl2mp_player.h\"\r\n#include \"c_team.h\"\r\n#include \"clientsteamcontext.h\"\r\n#include \"filesystem.h\"\r\n\r\nnamespace NSoftInfo {\r\n\r\n\tstatic int g_iAmericanClassCounts[TOTAL_AMER_CLASSES];\r\n\tstatic int g_iBritishClassCounts[TOTAL_BRIT_CLASSES];\r\n\r\n\tstatic float g_flNextUpdateTime = -FLT_MAX;\r\n\r\n\tvoid Reset() {\r\n\t\tg_flNextUpdateTime = -FLT_MAX;\r\n\t\tUpdate();\r\n\t}\r\n\r\n\tvoid UpdateClasses() {\r\n\t\tmemset(g_iAmericanClassCounts, 0, sizeof(g_iAmericanClassCounts));\r\n\t\tmemset(g_iBritishClassCounts, 0, sizeof(g_iBritishClassCounts));\r\n\t\tfor (int i = 1; i <= gpGlobals->maxClients; i++) {\r\n\t\t\tCHL2MP_Player* pPlayer = ToHL2MPPlayer(UTIL_PlayerByIndex(i));\r\n\t\t\tif (pPlayer && pPlayer->GetNextClass() >= 0) {\r\n\t\t\t\tif (pPlayer->GetTeamNumber() == TEAM_AMERICANS) {\r\n\t\t\t\t\tg_iAmericanClassCounts[pPlayer->GetNextClass()]++;\r\n\t\t\t\t}\r\n\t\t\t\telse if (pPlayer->GetTeamNumber() == TEAM_BRITISH) {\r\n\t\t\t\t\tg_iBritishClassCounts[pPlayer->GetNextClass()]++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tstatic const float UPDATE_INTERVAL = 1.f;\r\n\tvoid Update() {\r\n\t\tif (gpGlobals->curtime > g_flNextUpdateTime) {\r\n\t\t\tg_flNextUpdateTime = gpGlobals->curtime + UPDATE_INTERVAL;\r\n\r\n\t\t\tUpdateClasses();\r\n\t\t}\r\n\t}\r\n\r\n\tint GetNumPlayersOfClass(const CPlayerClass* pClass) {\r\n\t\tif (pClass->m_iDefaultTeam == TEAM_AMERICANS)\r\n\t\t\treturn g_iAmericanClassCounts[pClass->m_iClassNumber];\r\n\t\telse\r\n\t\t\treturn g_iBritishClassCounts[pClass->m_iClassNumber];\r\n\t\t\t\r\n\t}\r\n}\r\n\r\nvoid convertSteamIDToString(const CSteamID& id, char* buffer, int bufferSize);\r\n\r\nCON_COMMAND(csv_export, \"Generates a CSV inside a \\'csv\\' folder containing current player stats, name paramater optional\") {\r\n\tchar filename[128];\r\n\r\n\tif (args.ArgC() == 2) {\r\n\t\t\/\/block custom point_clientcommand entities from writing to other directories\r\n\t\tif (args[1][0] == '.') {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tQ_snprintf(filename, sizeof(filename), \"%s.csv\", args[1]);\r\n\t}\r\n\telse {\r\n\t\tint americanScore = g_Teams[TEAM_AMERICANS]->Get_Score();\r\n\t\tint britishScore = g_Teams[TEAM_BRITISH]->Get_Score();\r\n\t\tQ_snprintf(filename, sizeof(filename), \"%s_%i_%i.csv\", g_pGameRules->MapName(), americanScore, britishScore);\r\n\t}\r\n\r\n\tCUtlBuffer buffer;\r\n\tbuffer.SetBufferType(true, false);\r\n\tbuffer.PutString(\"steamid,name,team,score,damage,ping\\n\");\r\n\tfor (int i = 0; i <= gpGlobals->maxClients; i++) {\r\n\t\tif (g_PR->IsConnected(i)) {\r\n\r\n\r\n\t\t\t\/\/steamid\r\n\t\t\tCSteamID id;\r\n\t\t\tplayer_info_t pi;\r\n\t\t\tbool bSteamIdFound = false;\r\n\t\t\tif (engine->GetPlayerInfo(i, &pi))\r\n\t\t\t{\r\n\t\t\t\tif (pi.friendsID && steamapicontext && steamapicontext->SteamUtils())\r\n\t\t\t\t{\r\n\t\t\t\t\tstatic EUniverse universe = k_EUniverseInvalid;\r\n\r\n\t\t\t\t\tif (universe == k_EUniverseInvalid)\r\n\t\t\t\t\t\tuniverse = steamapicontext->SteamUtils()->GetConnectedUniverse();\r\n\r\n\t\t\t\t\tid.InstancedSet(pi.friendsID, 1, universe, k_EAccountTypeIndividual);\r\n\t\t\t\t\tbSteamIdFound = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (bSteamIdFound) {\r\n\t\t\t\tchar idBuffer[64];\r\n\t\t\t\tconvertSteamIDToString(id, idBuffer, 64);\r\n\t\t\t\tbuffer.PutString(idBuffer);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tbuffer.PutString(\"NULL\");\r\n\t\t\t}\r\n\t\t\tbuffer.PutChar(',');\r\n\t\t\t\r\n\r\n\r\n\r\n\t\t\t\/\/name, convert commas to periods\r\n\t\t\tchar nameBuffer[MAX_PLAYER_NAME_LENGTH + 1];\r\n\t\t\tstrcpy_s(nameBuffer, g_PR->GetPlayerName(i));\r\n\t\t\tfor (int j = 0; j < MAX_PLAYER_NAME_LENGTH + 1; j++) {\r\n\t\t\t\tif (nameBuffer[j] == ',') { \r\n\t\t\t\t\tnameBuffer[j] = '.';\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbuffer.PutString(nameBuffer);\r\n\t\t\tbuffer.PutChar(',');\r\n\t\t\t\r\n\t\t\t\/\/team\r\n\t\t\tbuffer.PutInt(g_PR->GetTeam(i));\r\n\t\t\tbuffer.PutChar(',');\r\n\r\n\t\t\t\/\/score\r\n\t\t\tbuffer.PutInt(g_PR->GetPlayerScore(i));\r\n\t\t\tbuffer.PutChar(',');\r\n\r\n\t\t\t\/\/damage score\r\n\t\t\tbuffer.PutInt(g_PR->GetDamageScore(i));\r\n\t\t\tbuffer.PutChar(',');\r\n\r\n\t\t\t\/\/ping\r\n\t\t\tbuffer.PutInt(g_PR->GetPing(i));\r\n\t\t\tbuffer.PutChar(',');\r\n\r\n\t\t\t\/\/line delimiter\r\n\t\t\tbuffer.PutChar('\\n');\r\n\t\t}\r\n\t}\r\n\r\n\tfilesystem->WriteFile(filename, \"\", buffer);\r\n\r\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Summary: Exceptions for the C++ interface\n *\n * Copy: See Copyright for the status of this software.\n *\n *\/\n\n\/**\n * @file\n * @brief Exception declarations\n *\/\n\n#ifndef LIBMEMACHED_EXCEPTION_HPP\n#define LIBMEMACHED_EXCEPTION_HPP\n\n#include <stdexcept>\n\n\nnamespace memcache \n{\n class Exception : public std::runtime_error\n {\n public:\n Exception(const std::string& msg, bool in_errno)\n : \n std::runtime_error(msg), \n errno(in_errno) \n {}\n\n Exception(const char *msg, bool in_errno)\n : \n std::runtime_error(msg), \n errno(in_errno) {}\n\n virtual ~Exception() throw() {}\n\n int getErrno() const \n { \n return errno; \n }\n\n private:\n int errno;\n };\n\n class Warning : public Exception\n {\n public:\n Warning(const std::string& msg, bool errno) : Exception(msg, errno) {}\n Warning(const char *msg, bool errno) : Exception(msg, errno) {}\n };\n\n class Error : public Exception\n {\n public:\n Error(const std::string& msg, bool errno) : Exception(msg, errno) {}\n Error(const char *msg, bool errno) : Exception(msg, errno) {}\n virtual ~Error() throw() {}\n };\n\n} \/* namespace libmemcached *\/\n\n#endif \/* LIBMEMACHED_EXCEPTION_HPP *\/\n<commit_msg>Correcting mistake I made in exceptions header file.<commit_after>\/*\n * Summary: Exceptions for the C++ interface\n *\n * Copy: See Copyright for the status of this software.\n *\n *\/\n\n\/**\n * @file\n * @brief Exception declarations\n *\/\n\n#ifndef LIBMEMACHED_EXCEPTION_HPP\n#define LIBMEMACHED_EXCEPTION_HPP\n\n#include <stdexcept>\n\n\nnamespace memcache \n{\n class Exception : public std::runtime_error\n {\n public:\n Exception(const std::string& msg, bool in_errno)\n : \n std::runtime_error(msg), \n errno(in_errno) \n {}\n\n Exception(const char *msg, bool in_errno)\n : \n std::runtime_error(msg), \n errno(in_errno) {}\n\n virtual ~Exception() throw() {}\n\n int getErrno() const \n { \n return errno; \n }\n\n private:\n int errno;\n };\n\n class Warning : public Exception\n {\n public:\n Warning(const std::string& msg, bool in_errno) : Exception(msg, in_errno) {}\n Warning(const char *msg, bool in_errno) : Exception(msg, in_errno) {}\n };\n\n class Error : public Exception\n {\n public:\n Error(const std::string& msg, bool in_errno) : Exception(msg, in_errno) {}\n Error(const char *msg, bool in_errno) : Exception(msg, in_errno) {}\n virtual ~Error() throw() {}\n };\n\n} \/* namespace libmemcached *\/\n\n#endif \/* LIBMEMACHED_EXCEPTION_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"views\/controls\/button\/custom_button.h\"\n\n#include \"app\/throb_animation.h\"\n#include \"base\/keyboard_codes.h\"\n#include \"views\/screen.h\"\n\nnamespace views {\n\n\/\/ How long the hover animation takes if uninterrupted.\nstatic const int kHoverFadeDurationMs = 150;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, public:\n\nCustomButton::~CustomButton() {\n}\n\nvoid CustomButton::SetState(ButtonState state) {\n if (state == state_)\n return;\n\n if (animate_on_state_change_ || !hover_animation_->is_animating()) {\n animate_on_state_change_ = true;\n if (state_ == BS_NORMAL && state == BS_HOT) {\n \/\/ Button is hovered from a normal state, start hover animation.\n hover_animation_->Show();\n } else if (state_ == BS_HOT && state == BS_NORMAL) {\n \/\/ Button is returning to a normal state from hover, start hover\n \/\/ fade animation.\n hover_animation_->Hide();\n } else {\n hover_animation_->Stop();\n }\n }\n\n state_ = state;\n SchedulePaint();\n}\n\nvoid CustomButton::StartThrobbing(int cycles_til_stop) {\n animate_on_state_change_ = false;\n hover_animation_->StartThrobbing(cycles_til_stop);\n}\n\nvoid CustomButton::SetAnimationDuration(int duration) {\n hover_animation_->SetSlideDuration(duration);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, View overrides:\n\nbool CustomButton::GetAccessibleState(AccessibilityTypes::State* state) {\n *state = 0;\n switch (state_) {\n case BS_HOT:\n *state = AccessibilityTypes::STATE_HOTTRACKED;\n case BS_PUSHED:\n *state = AccessibilityTypes::STATE_PRESSED;\n case BS_DISABLED:\n *state = AccessibilityTypes::STATE_UNAVAILABLE;\n case BS_NORMAL:\n case BS_COUNT:\n \/\/ No additional accessibility state set for this button state.\n break;\n }\n\n return true;\n}\n\nvoid CustomButton::SetEnabled(bool enabled) {\n if (enabled ? (state_ != BS_DISABLED) : (state_ == BS_DISABLED))\n return;\n\n if (enabled)\n SetState(IsMouseHovered() ? BS_HOT : BS_NORMAL);\n else\n SetState(BS_DISABLED);\n}\n\nbool CustomButton::IsEnabled() const {\n return state_ != BS_DISABLED;\n}\n\nbool CustomButton::IsFocusable() const {\n return (state_ != BS_DISABLED) && View::IsFocusable();\n}\n\nbool CustomButton::IsMouseHovered() const {\n \/\/ If we haven't yet been placed in an onscreen view hierarchy, we can't be\n \/\/ hovered.\n if (!GetWidget())\n return false;\n\n gfx::Point cursor_pos(Screen::GetCursorScreenPoint());\n ConvertPointToView(NULL, this, &cursor_pos);\n return HitTest(cursor_pos);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, protected:\n\nCustomButton::CustomButton(ButtonListener* listener)\n : Button(listener),\n state_(BS_NORMAL),\n animate_on_state_change_(true),\n triggerable_event_flags_(MouseEvent::EF_LEFT_BUTTON_DOWN),\n request_focus_on_press_(true) {\n hover_animation_.reset(new ThrobAnimation(this));\n hover_animation_->SetSlideDuration(kHoverFadeDurationMs);\n}\n\nbool CustomButton::IsTriggerableEvent(const MouseEvent& e) {\n return (triggerable_event_flags_ & e.GetFlags()) != 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, View overrides (protected):\n\nbool CustomButton::AcceleratorPressed(const Accelerator& accelerator) {\n if (!enabled_)\n return false;\n\n SetState(BS_NORMAL);\n KeyEvent key_event(Event::ET_KEY_RELEASED, accelerator.GetKeyCode(),\n accelerator.modifiers(), 0, 0);\n NotifyClick(key_event);\n return true;\n}\n\nbool CustomButton::OnMousePressed(const MouseEvent& e) {\n if (state_ != BS_DISABLED) {\n if (ShouldEnterPushedState(e) && HitTest(e.location()))\n SetState(BS_PUSHED);\n if (request_focus_on_press_)\n RequestFocus();\n }\n return true;\n}\n\nbool CustomButton::OnMouseDragged(const MouseEvent& e) {\n if (state_ != BS_DISABLED) {\n if (HitTest(e.location()))\n SetState(ShouldEnterPushedState(e) ? BS_PUSHED : BS_HOT);\n else\n SetState(BS_NORMAL);\n }\n return true;\n}\n\nvoid CustomButton::OnMouseReleased(const MouseEvent& e, bool canceled) {\n \/\/ Starting a drag results in a MouseReleased, we need to ignore it.\n if ((state_ == BS_DISABLED) || InDrag())\n return;\n\n if (!HitTest(e.location())) {\n SetState(BS_NORMAL);\n return;\n }\n\n SetState(BS_HOT);\n if (!canceled && IsTriggerableEvent(e)) {\n NotifyClick(e);\n \/\/ NOTE: We may be deleted at this point (by the listener's notification\n \/\/ handler).\n }\n}\n\nvoid CustomButton::OnMouseEntered(const MouseEvent& e) {\n if (state_ != BS_DISABLED)\n SetState(BS_HOT);\n}\n\nvoid CustomButton::OnMouseMoved(const MouseEvent& e) {\n if (state_ != BS_DISABLED)\n SetState(HitTest(e.location()) ? BS_HOT : BS_NORMAL);\n}\n\nvoid CustomButton::OnMouseExited(const MouseEvent& e) {\n \/\/ Starting a drag results in a MouseExited, we need to ignore it.\n if (state_ != BS_DISABLED && !InDrag())\n SetState(BS_NORMAL);\n}\n\nbool CustomButton::OnKeyPressed(const KeyEvent& e) {\n if (state_ == BS_DISABLED)\n return false;\n\n \/\/ Space sets button state to pushed. Enter clicks the button. This matches\n \/\/ the Windows native behavior of buttons, where Space clicks the button on\n \/\/ KeyRelease and Enter clicks the button on KeyPressed.\n if (e.GetKeyCode() == base::VKEY_SPACE) {\n SetState(BS_PUSHED);\n } else if (e.GetKeyCode() == base::VKEY_RETURN) {\n SetState(BS_NORMAL);\n NotifyClick(e);\n }\n return true;\n}\n\nbool CustomButton::OnKeyReleased(const KeyEvent& e) {\n if ((state_ == BS_DISABLED) || (e.GetKeyCode() != base::VKEY_SPACE))\n return false;\n\n SetState(BS_NORMAL);\n NotifyClick(e);\n return true;\n}\n\nvoid CustomButton::OnDragDone() {\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::ShowContextMenu(const gfx::Point& p, bool is_mouse_gesture) {\n if (!GetContextMenuController())\n return;\n\n \/\/ We're about to show the context menu. Showing the context menu likely means\n \/\/ we won't get a mouse exited and reset state. Reset it now to be sure.\n if (state_ != BS_DISABLED)\n SetState(BS_NORMAL);\n View::ShowContextMenu(p, is_mouse_gesture);\n}\n\nvoid CustomButton::ViewHierarchyChanged(bool is_add, View *parent,\n View *child) {\n if (!is_add && state_ != BS_DISABLED)\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::SetHotTracked(bool flag) {\n if (state_ != BS_DISABLED)\n SetState(flag ? BS_HOT : BS_NORMAL);\n\n if (flag)\n NotifyAccessibilityEvent(AccessibilityTypes::EVENT_FOCUS);\n}\n\nbool CustomButton::IsHotTracked() const {\n return state_ == BS_HOT;\n}\n\nvoid CustomButton::WillLoseFocus() {\n if (IsHotTracked())\n SetState(BS_NORMAL);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, AnimationDelegate implementation:\n\nvoid CustomButton::AnimationProgressed(const Animation* animation) {\n SchedulePaint();\n}\n\nbool CustomButton::ShouldEnterPushedState(const MouseEvent& e) {\n return IsTriggerableEvent(e);\n}\n\n} \/\/ namespace views\n<commit_msg>Fix a regression in r56766 CustomButton::OnKeyEvent should return false when the event is not handled<commit_after>\/\/ Copyright (c) 2010 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 \"views\/controls\/button\/custom_button.h\"\n\n#include \"app\/throb_animation.h\"\n#include \"base\/keyboard_codes.h\"\n#include \"views\/screen.h\"\n\nnamespace views {\n\n\/\/ How long the hover animation takes if uninterrupted.\nstatic const int kHoverFadeDurationMs = 150;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, public:\n\nCustomButton::~CustomButton() {\n}\n\nvoid CustomButton::SetState(ButtonState state) {\n if (state == state_)\n return;\n\n if (animate_on_state_change_ || !hover_animation_->is_animating()) {\n animate_on_state_change_ = true;\n if (state_ == BS_NORMAL && state == BS_HOT) {\n \/\/ Button is hovered from a normal state, start hover animation.\n hover_animation_->Show();\n } else if (state_ == BS_HOT && state == BS_NORMAL) {\n \/\/ Button is returning to a normal state from hover, start hover\n \/\/ fade animation.\n hover_animation_->Hide();\n } else {\n hover_animation_->Stop();\n }\n }\n\n state_ = state;\n SchedulePaint();\n}\n\nvoid CustomButton::StartThrobbing(int cycles_til_stop) {\n animate_on_state_change_ = false;\n hover_animation_->StartThrobbing(cycles_til_stop);\n}\n\nvoid CustomButton::SetAnimationDuration(int duration) {\n hover_animation_->SetSlideDuration(duration);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, View overrides:\n\nbool CustomButton::GetAccessibleState(AccessibilityTypes::State* state) {\n *state = 0;\n switch (state_) {\n case BS_HOT:\n *state = AccessibilityTypes::STATE_HOTTRACKED;\n case BS_PUSHED:\n *state = AccessibilityTypes::STATE_PRESSED;\n case BS_DISABLED:\n *state = AccessibilityTypes::STATE_UNAVAILABLE;\n case BS_NORMAL:\n case BS_COUNT:\n \/\/ No additional accessibility state set for this button state.\n break;\n }\n\n return true;\n}\n\nvoid CustomButton::SetEnabled(bool enabled) {\n if (enabled ? (state_ != BS_DISABLED) : (state_ == BS_DISABLED))\n return;\n\n if (enabled)\n SetState(IsMouseHovered() ? BS_HOT : BS_NORMAL);\n else\n SetState(BS_DISABLED);\n}\n\nbool CustomButton::IsEnabled() const {\n return state_ != BS_DISABLED;\n}\n\nbool CustomButton::IsFocusable() const {\n return (state_ != BS_DISABLED) && View::IsFocusable();\n}\n\nbool CustomButton::IsMouseHovered() const {\n \/\/ If we haven't yet been placed in an onscreen view hierarchy, we can't be\n \/\/ hovered.\n if (!GetWidget())\n return false;\n\n gfx::Point cursor_pos(Screen::GetCursorScreenPoint());\n ConvertPointToView(NULL, this, &cursor_pos);\n return HitTest(cursor_pos);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, protected:\n\nCustomButton::CustomButton(ButtonListener* listener)\n : Button(listener),\n state_(BS_NORMAL),\n animate_on_state_change_(true),\n triggerable_event_flags_(MouseEvent::EF_LEFT_BUTTON_DOWN),\n request_focus_on_press_(true) {\n hover_animation_.reset(new ThrobAnimation(this));\n hover_animation_->SetSlideDuration(kHoverFadeDurationMs);\n}\n\nbool CustomButton::IsTriggerableEvent(const MouseEvent& e) {\n return (triggerable_event_flags_ & e.GetFlags()) != 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, View overrides (protected):\n\nbool CustomButton::AcceleratorPressed(const Accelerator& accelerator) {\n if (!enabled_)\n return false;\n\n SetState(BS_NORMAL);\n KeyEvent key_event(Event::ET_KEY_RELEASED, accelerator.GetKeyCode(),\n accelerator.modifiers(), 0, 0);\n NotifyClick(key_event);\n return true;\n}\n\nbool CustomButton::OnMousePressed(const MouseEvent& e) {\n if (state_ != BS_DISABLED) {\n if (ShouldEnterPushedState(e) && HitTest(e.location()))\n SetState(BS_PUSHED);\n if (request_focus_on_press_)\n RequestFocus();\n }\n return true;\n}\n\nbool CustomButton::OnMouseDragged(const MouseEvent& e) {\n if (state_ != BS_DISABLED) {\n if (HitTest(e.location()))\n SetState(ShouldEnterPushedState(e) ? BS_PUSHED : BS_HOT);\n else\n SetState(BS_NORMAL);\n }\n return true;\n}\n\nvoid CustomButton::OnMouseReleased(const MouseEvent& e, bool canceled) {\n \/\/ Starting a drag results in a MouseReleased, we need to ignore it.\n if ((state_ == BS_DISABLED) || InDrag())\n return;\n\n if (!HitTest(e.location())) {\n SetState(BS_NORMAL);\n return;\n }\n\n SetState(BS_HOT);\n if (!canceled && IsTriggerableEvent(e)) {\n NotifyClick(e);\n \/\/ NOTE: We may be deleted at this point (by the listener's notification\n \/\/ handler).\n }\n}\n\nvoid CustomButton::OnMouseEntered(const MouseEvent& e) {\n if (state_ != BS_DISABLED)\n SetState(BS_HOT);\n}\n\nvoid CustomButton::OnMouseMoved(const MouseEvent& e) {\n if (state_ != BS_DISABLED)\n SetState(HitTest(e.location()) ? BS_HOT : BS_NORMAL);\n}\n\nvoid CustomButton::OnMouseExited(const MouseEvent& e) {\n \/\/ Starting a drag results in a MouseExited, we need to ignore it.\n if (state_ != BS_DISABLED && !InDrag())\n SetState(BS_NORMAL);\n}\n\nbool CustomButton::OnKeyPressed(const KeyEvent& e) {\n if (state_ == BS_DISABLED)\n return false;\n\n \/\/ Space sets button state to pushed. Enter clicks the button. This matches\n \/\/ the Windows native behavior of buttons, where Space clicks the button on\n \/\/ KeyRelease and Enter clicks the button on KeyPressed.\n if (e.GetKeyCode() == base::VKEY_SPACE) {\n SetState(BS_PUSHED);\n } else if (e.GetKeyCode() == base::VKEY_RETURN) {\n SetState(BS_NORMAL);\n NotifyClick(e);\n } else {\n return false;\n }\n return true;\n}\n\nbool CustomButton::OnKeyReleased(const KeyEvent& e) {\n if ((state_ == BS_DISABLED) || (e.GetKeyCode() != base::VKEY_SPACE))\n return false;\n\n SetState(BS_NORMAL);\n NotifyClick(e);\n return true;\n}\n\nvoid CustomButton::OnDragDone() {\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::ShowContextMenu(const gfx::Point& p, bool is_mouse_gesture) {\n if (!GetContextMenuController())\n return;\n\n \/\/ We're about to show the context menu. Showing the context menu likely means\n \/\/ we won't get a mouse exited and reset state. Reset it now to be sure.\n if (state_ != BS_DISABLED)\n SetState(BS_NORMAL);\n View::ShowContextMenu(p, is_mouse_gesture);\n}\n\nvoid CustomButton::ViewHierarchyChanged(bool is_add, View *parent,\n View *child) {\n if (!is_add && state_ != BS_DISABLED)\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::SetHotTracked(bool flag) {\n if (state_ != BS_DISABLED)\n SetState(flag ? BS_HOT : BS_NORMAL);\n\n if (flag)\n NotifyAccessibilityEvent(AccessibilityTypes::EVENT_FOCUS);\n}\n\nbool CustomButton::IsHotTracked() const {\n return state_ == BS_HOT;\n}\n\nvoid CustomButton::WillLoseFocus() {\n if (IsHotTracked())\n SetState(BS_NORMAL);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, AnimationDelegate implementation:\n\nvoid CustomButton::AnimationProgressed(const Animation* animation) {\n SchedulePaint();\n}\n\nbool CustomButton::ShouldEnterPushedState(const MouseEvent& e) {\n return IsTriggerableEvent(e);\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/vsm\/vsm\/docsumconfig.h>\n#include <vespa\/searchsummary\/docsummary\/docsumfieldwriter.h>\n\nusing search::docsummary::IDocsumFieldWriter;\nusing search::docsummary::EmptyDFW;\n\nnamespace vsm {\n\nIDocsumFieldWriter::UP\nDynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc)\n{\n IDocsumFieldWriter::UP fieldWriter;\n if ((overrideName == \"staticrank\") ||\n (overrideName == \"ranklog\") ||\n (overrideName == \"label\") ||\n (overrideName == \"project\") ||\n (overrideName == \"positions\") ||\n (overrideName == \"absdist\") ||\n (overrideName == \"subproject\"))\n {\n fieldWriter.reset(new EmptyDFW());\n rc = true;\n } else if ((overrideName == \"attribute\") ||\n ((overrideName == \"geopos\"))) {\n rc = true;\n } else {\n fieldWriter = search::docsummary::DynamicDocsumConfig::createFieldWriter(fieldName, overrideName, argument, rc);\n }\n return fieldWriter;\n}\n\n}\n<commit_msg>Ignore attributecombiner rewriter for streaming search.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/vsm\/vsm\/docsumconfig.h>\n#include <vespa\/searchsummary\/docsummary\/docsumfieldwriter.h>\n\nusing search::docsummary::IDocsumFieldWriter;\nusing search::docsummary::EmptyDFW;\n\nnamespace vsm {\n\nIDocsumFieldWriter::UP\nDynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc)\n{\n IDocsumFieldWriter::UP fieldWriter;\n if ((overrideName == \"staticrank\") ||\n (overrideName == \"ranklog\") ||\n (overrideName == \"label\") ||\n (overrideName == \"project\") ||\n (overrideName == \"positions\") ||\n (overrideName == \"absdist\") ||\n (overrideName == \"subproject\"))\n {\n fieldWriter.reset(new EmptyDFW());\n rc = true;\n } else if ((overrideName == \"attribute\") ||\n (overrideName == \"attributecombiner\") ||\n (overrideName == \"geopos\")) {\n rc = true;\n } else {\n fieldWriter = search::docsummary::DynamicDocsumConfig::createFieldWriter(fieldName, overrideName, argument, rc);\n }\n return fieldWriter;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010 Google Inc. All Rights Reserved.\n\/\/ Author: jacobsa@google.com (Aaron Jacobs)\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 \"gjstest\/internal\/cpp\/run_tests.h\"\n\n#include <string>\n#include <vector>\n\n#include <re2\/re2.h>\n#include <v8.h>\n\n#include \"base\/basictypes.h\"\n#include \"base\/integral_types.h\"\n#include \"base\/logging.h\"\n#include \"base\/macros.h\"\n#include \"base\/stl_decl.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/timer.h\"\n#include \"gjstest\/internal\/cpp\/test_case.h\"\n#include \"gjstest\/internal\/cpp\/v8_utils.h\"\n#include \"gjstest\/internal\/proto\/named_scripts.pb.h\"\n#include \"strings\/strutil.h\"\n#include \"util\/gtl\/map-util.h\"\n#include \"util\/hash\/hash.h\"\n#include \"webutil\/xml\/xml_writer.h\"\n\nusing v8::Array;\nusing v8::Arguments;\nusing v8::Context;\nusing v8::Function;\nusing v8::Handle;\nusing v8::HandleScope;\nusing v8::Local;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::Persistent;\nusing v8::String;\nusing v8::TryCatch;\nusing v8::Undefined;\nusing v8::Value;\n\nnamespace gjstest {\n\n\/\/ Create XML output given an overall duration in seconds, a list of test names\n\/\/ in the order of execution, a map from test names to durations, and a map from\n\/\/ failed test names to failure messages.\nstatic string MakeXml(\n uint32 duration_ms,\n const vector<string>& tests_run,\n const hash_map<string, double>& test_durations,\n const hash_map<string, string>& test_failure_messages) {\n webutil_xml::XmlWriter xml_writer(\"UTF-8\", true);\n xml_writer.StartDocument(\"UTF-8\");\n\n xml_writer.StartElement(\"testsuite\");\n xml_writer.AddAttribute(\"name\", \"Google JS tests\");\n xml_writer.AddAttribute(\"failures\", SimpleItoa(test_failure_messages.size()));\n xml_writer.AddAttribute(\"time\", SimpleDtoa(duration_ms \/ 1000.0));\n\n for (uint32 i = 0; i < tests_run.size(); ++i) {\n const string& name = tests_run[i];\n\n \/\/ Skip the tests that weren't actually run.\n if (!ContainsKey(test_durations, name)) continue;\n\n const double duration = FindOrDie(test_durations, name);\n\n xml_writer.StartElement(\"testcase\");\n xml_writer.AddAttribute(\"name\", name);\n xml_writer.AddAttribute(\"time\", SimpleDtoa(duration));\n\n \/\/ Add a failure element if the test failed.\n if (ContainsKey(test_failure_messages, name)) {\n const string& failure_message = FindOrDie(test_failure_messages, name);\n\n xml_writer.StartElement(\"failure\");\n xml_writer.WriteCData(failure_message);\n xml_writer.EndElement(); \/\/ failure\n }\n\n xml_writer.EndElement(); \/\/ testcase\n }\n\n xml_writer.EndElement(); \/\/ testsuite\n\n\n return xml_writer.GetContent();\n}\n\n\/\/ Get a reference to the function of the supplied name.\nstatic Local<Function> GetFunctionNamed(const string& name) {\n const Local<Value> result = ExecuteJs(name, \"\");\n CHECK(!result.IsEmpty());\n CHECK(result->IsFunction());\n\n return Local<Function>::Cast(result);\n}\n\nstatic void ProcessTestCase(\n const string& name,\n const Handle<Function>& test_function,\n bool* success,\n string* output,\n hash_map<string, string>* test_failure_messages,\n hash_map<string, double>* test_durations) {\n \/\/ Run the test.\n TestCase test_case(test_function);\n test_case.Run();\n\n \/\/ Append the appropriate stuff to our output.\n StringAppendF(output, \"[ RUN ] %s\\n\", name.c_str());\n\n string status_message = \"[ OK ]\";\n if (!test_case.succeeded) {\n *success = false;\n status_message = \"[ FAILED ]\";\n\n \/\/ Record the failure output for use in the XML later. Strip any\n \/\/ surrounding whitespace first.\n StripWhiteSpace(&test_case.failure_output);\n InsertOrDie(test_failure_messages, name, test_case.failure_output);\n }\n\n \/\/ Append the test output and the status message.\n StringAppendF(\n output,\n \"%s%s %s (%u ms)\\n\",\n test_case.output.c_str(),\n status_message.c_str(),\n name.c_str(),\n test_case.duration_ms);\n\n \/\/ Record test duration.\n InsertOrDie(test_durations, name, test_case.duration_ms \/ 1000.0);\n}\n\n\/\/ Iterate over a map from test names to test functions, running each test\n\/\/ function.\nstatic void ProcessTestSuite(\n const RE2& test_filter,\n const Handle<Object>& test_functions,\n bool* success,\n string* output,\n vector<string>* tests_run,\n hash_map<string, string>* test_failure_messages,\n hash_map<string, double>* test_durations) {\n StringAppendF(output, \"[----------]\\n\");\n\n const Local<Array> test_names = test_functions->GetPropertyNames();\n for (uint32 i = 0; i < test_names->Length(); ++i) {\n const Local<Value> name = test_names->Get(i);\n const Local<Value> test_function = test_functions->Get(name);\n CHECK(test_function->IsFunction());\n\n \/\/ Skip this test if it doesn't match our filter.\n const string string_name = ConvertToString(name);\n if (!RE2::FullMatch(string_name, test_filter)) continue;\n\n tests_run->push_back(string_name);\n ProcessTestCase(\n string_name,\n Local<Function>::Cast(test_function),\n success,\n output,\n test_failure_messages,\n test_durations);\n }\n\n StringAppendF(output, \"[----------]\\n\\n\");\n}\n\nbool RunTests(\n const NamedScripts& scripts,\n const string& test_filter_string,\n string* output,\n string* xml) {\n const RE2 test_filter(test_filter_string.empty() ? \".*\" : test_filter_string);\n\n \/\/ Take ownership of all handles created.\n HandleScope handle_owner;\n\n \/\/ Create a context in which to run scripts and ensure that it's used whenever\n \/\/ a context is needed below. Export the global functions configured above.\n Persistent<Context> context = Context::New();\n Context::Scope context_scope(context);\n\n \/\/ Run all of the scripts.\n for (uint32 i = 0; i < scripts.script_size(); ++i) {\n const NamedScript& script = scripts.script(i);\n\n TryCatch try_catch;\n const Local<Value> result = ExecuteJs(script.source(), script.name());\n if (result.IsEmpty()) {\n *output += DescribeError(try_catch);\n return false;\n }\n }\n\n \/\/ Get a reference to gjstest.internal.getTestFunctions for later.\n const Local<Function> get_test_functions =\n GetFunctionNamed(\"gjstest.internal.getTestFunctions\");\n\n \/\/ Keep maps from test name to failure message (if the test failed) and\n \/\/ duration in seconds.\n hash_map<string, string> test_failure_messages;\n hash_map<string, double> test_durations;\n vector<string> tests_run;\n\n \/\/ Keep track of how long the whole process takes, and whether there are any\n \/\/ failures.\n CycleTimer overall_timer;\n overall_timer.Start();\n bool success = true;\n\n \/\/ Iterate over all of the registered test suites.\n const Local<Value> test_suites_value =\n ExecuteJs(\"gjstest.internal.testSuites\", \"\");\n CHECK(test_suites_value->IsArray());\n const Local<Array> test_suites = Local<Array>::Cast(test_suites_value);\n\n for (uint32 i = 0; i < test_suites->Length(); ++i) {\n const Local<Value> test_suite = test_suites->Get(i);\n CHECK(test_suite->IsObject());\n\n \/\/ Get the map of test functions registered for this test suite.\n Handle<Value> args[] = { test_suite };\n const Local<Value> test_functions_value =\n get_test_functions->Call(\n context->Global(),\n arraysize(args),\n args);\n CHECK(test_functions_value->IsObject());\n const Local<Object> test_functions =\n Local<Object>::Cast(test_functions_value);\n\n \/\/ Process this test suite.\n ProcessTestSuite(\n test_filter,\n test_functions,\n &success,\n output,\n &tests_run,\n &test_failure_messages,\n &test_durations);\n }\n\n overall_timer.Stop();\n\n StringAppendF(\n output,\n success ? \"[ PASSED ]\\n\" : \"[ FAILED ]\\n\");\n\n \/\/ Make sure that at least one test ran. This catches common errors with\n \/\/ mis-registering tests and so on.\n if (test_durations.empty()) {\n *output = \"No tests found.\\n\";\n return false;\n }\n\n \/\/ Create an XML document describing the execution.\n *xml =\n MakeXml(\n overall_timer.GetInMs(),\n tests_run,\n test_durations,\n test_failure_messages);\n\n return success;\n}\n\n} \/\/ namespace gjstest\n<commit_msg>Added a missing newline.<commit_after>\/\/ Copyright 2010 Google Inc. All Rights Reserved.\n\/\/ Author: jacobsa@google.com (Aaron Jacobs)\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 \"gjstest\/internal\/cpp\/run_tests.h\"\n\n#include <string>\n#include <vector>\n\n#include <re2\/re2.h>\n#include <v8.h>\n\n#include \"base\/basictypes.h\"\n#include \"base\/integral_types.h\"\n#include \"base\/logging.h\"\n#include \"base\/macros.h\"\n#include \"base\/stl_decl.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/timer.h\"\n#include \"gjstest\/internal\/cpp\/test_case.h\"\n#include \"gjstest\/internal\/cpp\/v8_utils.h\"\n#include \"gjstest\/internal\/proto\/named_scripts.pb.h\"\n#include \"strings\/strutil.h\"\n#include \"util\/gtl\/map-util.h\"\n#include \"util\/hash\/hash.h\"\n#include \"webutil\/xml\/xml_writer.h\"\n\nusing v8::Array;\nusing v8::Arguments;\nusing v8::Context;\nusing v8::Function;\nusing v8::Handle;\nusing v8::HandleScope;\nusing v8::Local;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::Persistent;\nusing v8::String;\nusing v8::TryCatch;\nusing v8::Undefined;\nusing v8::Value;\n\nnamespace gjstest {\n\n\/\/ Create XML output given an overall duration in seconds, a list of test names\n\/\/ in the order of execution, a map from test names to durations, and a map from\n\/\/ failed test names to failure messages.\nstatic string MakeXml(\n uint32 duration_ms,\n const vector<string>& tests_run,\n const hash_map<string, double>& test_durations,\n const hash_map<string, string>& test_failure_messages) {\n webutil_xml::XmlWriter xml_writer(\"UTF-8\", true);\n xml_writer.StartDocument(\"UTF-8\");\n\n xml_writer.StartElement(\"testsuite\");\n xml_writer.AddAttribute(\"name\", \"Google JS tests\");\n xml_writer.AddAttribute(\"failures\", SimpleItoa(test_failure_messages.size()));\n xml_writer.AddAttribute(\"time\", SimpleDtoa(duration_ms \/ 1000.0));\n\n for (uint32 i = 0; i < tests_run.size(); ++i) {\n const string& name = tests_run[i];\n\n \/\/ Skip the tests that weren't actually run.\n if (!ContainsKey(test_durations, name)) continue;\n\n const double duration = FindOrDie(test_durations, name);\n\n xml_writer.StartElement(\"testcase\");\n xml_writer.AddAttribute(\"name\", name);\n xml_writer.AddAttribute(\"time\", SimpleDtoa(duration));\n\n \/\/ Add a failure element if the test failed.\n if (ContainsKey(test_failure_messages, name)) {\n const string& failure_message = FindOrDie(test_failure_messages, name);\n\n xml_writer.StartElement(\"failure\");\n xml_writer.WriteCData(failure_message);\n xml_writer.EndElement(); \/\/ failure\n }\n\n xml_writer.EndElement(); \/\/ testcase\n }\n\n xml_writer.EndElement(); \/\/ testsuite\n\n\n return xml_writer.GetContent();\n}\n\n\/\/ Get a reference to the function of the supplied name.\nstatic Local<Function> GetFunctionNamed(const string& name) {\n const Local<Value> result = ExecuteJs(name, \"\");\n CHECK(!result.IsEmpty());\n CHECK(result->IsFunction());\n\n return Local<Function>::Cast(result);\n}\n\nstatic void ProcessTestCase(\n const string& name,\n const Handle<Function>& test_function,\n bool* success,\n string* output,\n hash_map<string, string>* test_failure_messages,\n hash_map<string, double>* test_durations) {\n \/\/ Run the test.\n TestCase test_case(test_function);\n test_case.Run();\n\n \/\/ Append the appropriate stuff to our output.\n StringAppendF(output, \"[ RUN ] %s\\n\", name.c_str());\n\n string status_message = \"[ OK ]\";\n if (!test_case.succeeded) {\n *success = false;\n status_message = \"[ FAILED ]\";\n\n \/\/ Record the failure output for use in the XML later. Strip any\n \/\/ surrounding whitespace first.\n StripWhiteSpace(&test_case.failure_output);\n InsertOrDie(test_failure_messages, name, test_case.failure_output);\n }\n\n \/\/ Append the test output and the status message.\n StringAppendF(\n output,\n \"%s%s %s (%u ms)\\n\",\n test_case.output.c_str(),\n status_message.c_str(),\n name.c_str(),\n test_case.duration_ms);\n\n \/\/ Record test duration.\n InsertOrDie(test_durations, name, test_case.duration_ms \/ 1000.0);\n}\n\n\/\/ Iterate over a map from test names to test functions, running each test\n\/\/ function.\nstatic void ProcessTestSuite(\n const RE2& test_filter,\n const Handle<Object>& test_functions,\n bool* success,\n string* output,\n vector<string>* tests_run,\n hash_map<string, string>* test_failure_messages,\n hash_map<string, double>* test_durations) {\n StringAppendF(output, \"[----------]\\n\");\n\n const Local<Array> test_names = test_functions->GetPropertyNames();\n for (uint32 i = 0; i < test_names->Length(); ++i) {\n const Local<Value> name = test_names->Get(i);\n const Local<Value> test_function = test_functions->Get(name);\n CHECK(test_function->IsFunction());\n\n \/\/ Skip this test if it doesn't match our filter.\n const string string_name = ConvertToString(name);\n if (!RE2::FullMatch(string_name, test_filter)) continue;\n\n tests_run->push_back(string_name);\n ProcessTestCase(\n string_name,\n Local<Function>::Cast(test_function),\n success,\n output,\n test_failure_messages,\n test_durations);\n }\n\n StringAppendF(output, \"[----------]\\n\\n\");\n}\n\nbool RunTests(\n const NamedScripts& scripts,\n const string& test_filter_string,\n string* output,\n string* xml) {\n const RE2 test_filter(test_filter_string.empty() ? \".*\" : test_filter_string);\n\n \/\/ Take ownership of all handles created.\n HandleScope handle_owner;\n\n \/\/ Create a context in which to run scripts and ensure that it's used whenever\n \/\/ a context is needed below. Export the global functions configured above.\n Persistent<Context> context = Context::New();\n Context::Scope context_scope(context);\n\n \/\/ Run all of the scripts.\n for (uint32 i = 0; i < scripts.script_size(); ++i) {\n const NamedScript& script = scripts.script(i);\n\n TryCatch try_catch;\n const Local<Value> result = ExecuteJs(script.source(), script.name());\n if (result.IsEmpty()) {\n *output += DescribeError(try_catch) + \"\\n\";\n return false;\n }\n }\n\n \/\/ Get a reference to gjstest.internal.getTestFunctions for later.\n const Local<Function> get_test_functions =\n GetFunctionNamed(\"gjstest.internal.getTestFunctions\");\n\n \/\/ Keep maps from test name to failure message (if the test failed) and\n \/\/ duration in seconds.\n hash_map<string, string> test_failure_messages;\n hash_map<string, double> test_durations;\n vector<string> tests_run;\n\n \/\/ Keep track of how long the whole process takes, and whether there are any\n \/\/ failures.\n CycleTimer overall_timer;\n overall_timer.Start();\n bool success = true;\n\n \/\/ Iterate over all of the registered test suites.\n const Local<Value> test_suites_value =\n ExecuteJs(\"gjstest.internal.testSuites\", \"\");\n CHECK(test_suites_value->IsArray());\n const Local<Array> test_suites = Local<Array>::Cast(test_suites_value);\n\n for (uint32 i = 0; i < test_suites->Length(); ++i) {\n const Local<Value> test_suite = test_suites->Get(i);\n CHECK(test_suite->IsObject());\n\n \/\/ Get the map of test functions registered for this test suite.\n Handle<Value> args[] = { test_suite };\n const Local<Value> test_functions_value =\n get_test_functions->Call(\n context->Global(),\n arraysize(args),\n args);\n CHECK(test_functions_value->IsObject());\n const Local<Object> test_functions =\n Local<Object>::Cast(test_functions_value);\n\n \/\/ Process this test suite.\n ProcessTestSuite(\n test_filter,\n test_functions,\n &success,\n output,\n &tests_run,\n &test_failure_messages,\n &test_durations);\n }\n\n overall_timer.Stop();\n\n StringAppendF(\n output,\n success ? \"[ PASSED ]\\n\" : \"[ FAILED ]\\n\");\n\n \/\/ Make sure that at least one test ran. This catches common errors with\n \/\/ mis-registering tests and so on.\n if (test_durations.empty()) {\n *output = \"No tests found.\\n\";\n return false;\n }\n\n \/\/ Create an XML document describing the execution.\n *xml =\n MakeXml(\n overall_timer.GetInMs(),\n tests_run,\n test_durations,\n test_failure_messages);\n\n return success;\n}\n\n} \/\/ namespace gjstest\n<|endoftext|>"} {"text":"<commit_before>\/* GStreamer\n * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>\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\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *\/\n\n#include <string.h>\n#include <gst\/gst.h>\n\n#include \"gstmonkeydec.h\"\n#include \"gstmonkeyenc.h\"\n\nextern GstElementDetails gst_monkeydec_details;\nextern GstElementDetails gst_monkeyenc_details;\n\nstatic GstCaps* monkey_type_find (GstBuffer *buf, gpointer priv);\n\nGstPadTemplate *monkeydec_sink_template, *monkeydec_src_template;\nGstPadTemplate *monkeyenc_sink_template, *monkeyenc_src_template;\n\nstatic GstCaps*\nmonkey_caps_factory (void)\n{\n return gst_caps_new (\"monkey_application\", \n \"application\/x-ape\", \n NULL\n\t\t );\n}\n\n\nstatic GstCaps*\nraw_caps_factory (void)\n{ \n return gst_caps_new (\"monkey_raw\", \n \"audio\/raw\",\n gst_props_new (\n \"format\", GST_PROPS_STRING (\"int\"),\n \"law\", GST_PROPS_INT (0),\n \"endianness\", GST_PROPS_INT (G_BYTE_ORDER),\n \"signed\", GST_PROPS_BOOLEAN (TRUE),\n \"width\", GST_PROPS_INT (16),\n \"depth\", GST_PROPS_INT (16), \n \"rate\", GST_PROPS_INT_RANGE (11025, 44100),\n \"channels\", GST_PROPS_INT_RANGE (1, 2),\n NULL \n ));\n}\n\nstatic GstCaps*\nwav_caps_factory (void)\n{ \n return gst_caps_new (\"monkey_wav\", \n \"audio\/x-wav\", \n NULL );\n}\n\n\nstatic GstTypeDefinition monkeydefinition = {\n \"monkey_application\/x-ape\", \"application\/x-ape\", \".ape\", monkey_type_find, \n};\n\n\nstatic GstCaps* \nmonkey_type_find (GstBuffer *buf, gpointer priv) \n{\n if (strncmp ((gchar *)GST_BUFFER_DATA (buf), \"MAC \", 4) != 0)\n return NULL;\n\n return gst_caps_new (\"monkey_type_find\", \"application\/x-ape\", NULL);\n}\n\n\nstatic gboolean\nplugin_init (GModule * module, GstPlugin * plugin)\n{\n GstElementFactory *monkey_dec, *monkey_enc;\n GstTypeFactory *type;\n GstCaps *raw_caps, *wav_caps, *monkey_caps;\n\n \/* this filter needs the bytestream package *\/\n if (!gst_library_load (\"gstbytestream\"))\n return FALSE;\n\n raw_caps = raw_caps_factory ();\n monkey_caps = monkey_caps_factory ();\n wav_caps = wav_caps_factory ();\n\n \/* create an elementfactory for the monkeydec element *\/\n monkey_dec = gst_element_factory_new (\"monkeydec\", GST_TYPE_MONKEYDEC, &gst_monkeydec_details);\n g_return_val_if_fail(monkey_dec != NULL, FALSE); \n\n \/* register sink pads *\/\n monkeydec_sink_template = gst_pad_template_new (\"sink\", GST_PAD_SINK,\n\t\t\t\t\t\t GST_PAD_ALWAYS,\n \t\t\t\t\t\t monkey_caps, NULL);\n gst_element_factory_add_pad_template (monkey_dec, monkeydec_sink_template);\n \n\n \/* register src pads *\/\n monkeydec_src_template = gst_pad_template_new (\"src\", GST_PAD_SRC,\n \t\t\t\t\t GST_PAD_ALWAYS,\n \t\t\t\t\t raw_caps, NULL);\n gst_element_factory_add_pad_template (monkey_dec, monkeydec_src_template);\n \n gst_element_factory_set_rank (monkey_dec, GST_ELEMENT_RANK_PRIMARY);\n gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (monkey_dec)); \n\n\n \/* create an elementfactory for the monkeydec element *\/\n monkey_enc = gst_element_factory_new (\"monkeyenc\", GST_TYPE_MONKEYENC, &gst_monkeyenc_details);\n g_return_val_if_fail(monkey_enc != NULL, FALSE); \n\n \/* register sink pads *\/\n monkeyenc_sink_template = gst_pad_template_new (\"sink\", GST_PAD_SINK,\n\t\t\t\t\t\t GST_PAD_ALWAYS,\n \t\t\t\t\t\t raw_caps, NULL);\n gst_element_factory_add_pad_template (monkey_enc, monkeyenc_sink_template);\n \n\n \/* register src pads *\/\n monkeyenc_src_template = gst_pad_template_new (\"src\", GST_PAD_SRC,\n \t\t\t GST_PAD_ALWAYS,\n \t\t\t\t\t monkey_caps, NULL);\n gst_element_factory_add_pad_template (monkey_enc, monkeyenc_src_template);\n \n gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (monkey_enc)); \n\n \n type = gst_type_factory_new (&monkeydefinition);\n gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (type));\n\n return TRUE;\n}\n\nGstPluginDesc plugin_desc = {\n GST_VERSION_MAJOR,\n GST_VERSION_MINOR,\n \"monkey audio\",\n plugin_init\n};\n<commit_msg>MonkeyAudio support little endian data only<commit_after>\/* GStreamer\n * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>\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\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *\/\n\n#include <string.h>\n#include <gst\/gst.h>\n\n#include \"gstmonkeydec.h\"\n#include \"gstmonkeyenc.h\"\n\nextern GstElementDetails gst_monkeydec_details;\nextern GstElementDetails gst_monkeyenc_details;\n\nstatic GstCaps* monkey_type_find (GstBuffer *buf, gpointer priv);\n\nGstPadTemplate *monkeydec_sink_template, *monkeydec_src_template;\nGstPadTemplate *monkeyenc_sink_template, *monkeyenc_src_template;\n\nstatic GstCaps*\nmonkey_caps_factory (void)\n{\n return gst_caps_new (\"monkey_application\", \n \"application\/x-ape\", \n NULL\n\t\t );\n}\n\n\nstatic GstCaps*\nraw_caps_factory (void)\n{ \n return gst_caps_new (\"monkey_raw\", \n \"audio\/raw\",\n gst_props_new (\n \"format\", GST_PROPS_STRING (\"int\"),\n \"law\", GST_PROPS_INT (0),\n \"endianness\", GST_PROPS_INT (G_LITTLE_ENDIAN),\n \"signed\", GST_PROPS_BOOLEAN (TRUE),\n \"width\", GST_PROPS_INT (16),\n \"depth\", GST_PROPS_INT (16), \n \"rate\", GST_PROPS_INT_RANGE (11025, 44100),\n \"channels\", GST_PROPS_INT_RANGE (1, 2),\n NULL \n ));\n}\n\nstatic GstCaps*\nwav_caps_factory (void)\n{ \n return gst_caps_new (\"monkey_wav\", \n \"audio\/x-wav\", \n NULL );\n}\n\n\nstatic GstTypeDefinition monkeydefinition = {\n \"monkey_application\/x-ape\", \"application\/x-ape\", \".ape\", monkey_type_find, \n};\n\n\nstatic GstCaps* \nmonkey_type_find (GstBuffer *buf, gpointer priv) \n{\n if (strncmp ((gchar *)GST_BUFFER_DATA (buf), \"MAC \", 4) != 0)\n return NULL;\n\n return gst_caps_new (\"monkey_type_find\", \"application\/x-ape\", NULL);\n}\n\n\nstatic gboolean\nplugin_init (GModule * module, GstPlugin * plugin)\n{\n GstElementFactory *monkey_dec, *monkey_enc;\n GstTypeFactory *type;\n GstCaps *raw_caps, *wav_caps, *monkey_caps;\n\n \/* this filter needs the bytestream package *\/\n if (!gst_library_load (\"gstbytestream\"))\n return FALSE;\n\n raw_caps = raw_caps_factory ();\n monkey_caps = monkey_caps_factory ();\n wav_caps = wav_caps_factory ();\n\n \/* create an elementfactory for the monkeydec element *\/\n monkey_dec = gst_element_factory_new (\"monkeydec\", GST_TYPE_MONKEYDEC, &gst_monkeydec_details);\n g_return_val_if_fail(monkey_dec != NULL, FALSE); \n\n \/* register sink pads *\/\n monkeydec_sink_template = gst_pad_template_new (\"sink\", GST_PAD_SINK,\n\t\t\t\t\t\t GST_PAD_ALWAYS,\n \t\t\t\t\t\t monkey_caps, NULL);\n gst_element_factory_add_pad_template (monkey_dec, monkeydec_sink_template);\n \n\n \/* register src pads *\/\n monkeydec_src_template = gst_pad_template_new (\"src\", GST_PAD_SRC,\n \t\t\t\t\t GST_PAD_ALWAYS,\n \t\t\t\t\t raw_caps, NULL);\n gst_element_factory_add_pad_template (monkey_dec, monkeydec_src_template);\n \n gst_element_factory_set_rank (monkey_dec, GST_ELEMENT_RANK_PRIMARY);\n gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (monkey_dec)); \n\n\n \/* create an elementfactory for the monkeydec element *\/\n monkey_enc = gst_element_factory_new (\"monkeyenc\", GST_TYPE_MONKEYENC, &gst_monkeyenc_details);\n g_return_val_if_fail(monkey_enc != NULL, FALSE); \n\n \/* register sink pads *\/\n monkeyenc_sink_template = gst_pad_template_new (\"sink\", GST_PAD_SINK,\n\t\t\t\t\t\t GST_PAD_ALWAYS,\n \t\t\t\t\t\t raw_caps, NULL);\n gst_element_factory_add_pad_template (monkey_enc, monkeyenc_sink_template);\n \n\n \/* register src pads *\/\n monkeyenc_src_template = gst_pad_template_new (\"src\", GST_PAD_SRC,\n \t\t\t GST_PAD_ALWAYS,\n \t\t\t\t\t monkey_caps, NULL);\n gst_element_factory_add_pad_template (monkey_enc, monkeyenc_src_template);\n \n gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (monkey_enc)); \n\n \n type = gst_type_factory_new (&monkeydefinition);\n gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (type));\n\n return TRUE;\n}\n\nGstPluginDesc plugin_desc = {\n GST_VERSION_MAJOR,\n GST_VERSION_MINOR,\n \"monkey audio\",\n plugin_init\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>\n\n This file is part of the KDE project\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 License\n aint with this library see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QStringList>\n\n#include \"GeoDataFolder.h\"\n\n#include \"GeoDataParser.h\"\n#include \"GeoDataDocument.h\"\n\n#include \"GeoSceneDocument.h\"\n#include \"GeoSceneHead.h\"\n#include \"GeoSceneIcon.h\"\n#include \"GeoSceneLayer.h\"\n#include \"GeoSceneMap.h\"\n#include \"GeoSceneParser.h\"\n#include \"GeoSceneProperty.h\"\n#include \"GeoSceneSettings.h\"\n#include \"GeoSceneZoom.h\"\n\n#ifdef Q_OS_WIN\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid myMessageOutput(QtMsgType type, const char *msg)\n{\n switch (type) {\n case QtDebugMsg:\n fprintf(stdout, \"Debug: %s\\n\", msg);\n break;\n case QtWarningMsg:\n fprintf(stdout, \"Warning: %s\\n\", msg);\n break;\n case QtCriticalMsg:\n fprintf(stdout, \"Critical: %s\\n\", msg);\n break;\n case QtFatalMsg:\n fprintf(stdout, \"Fatal: %s\\n\", msg);\n abort();\n }\n}\n#endif\n\nusing namespace Marble;\n\nvoid dumpGeoDataDocument(GeoDataDocument*);\nvoid dumpGeoSceneDocument(GeoSceneDocument*);\n\nint main(int argc, char** argv)\n{\n#ifdef Q_OS_WIN\n qInstallMsgHandler(myMessageOutput);\n#endif\n QCoreApplication app(argc, argv);\n\n \/\/ Expect document as first command line argument\n if (app.arguments().size() <= 1) {\n qWarning(\"Pass file name as first argument!\");\n return -1;\n }\n\n \/\/ Check whether file exists\n QFile file(app.arguments().at(1));\n if (!file.exists()) {\n qWarning(\"File does not exist!\");\n return -1;\n }\n\n \/\/ Open file in right mode\n file.open(QIODevice::ReadOnly);\n\n GeoParser* parser = 0;\n const QString& fileName = file.fileName().toLower();\n\n \/\/ A real application, would use other heuristics to determine the source type!\n if (fileName.endsWith(\".dgml\"))\n parser = new GeoSceneParser(GeoScene_DGML);\n else if (fileName.endsWith(\".kml\"))\n parser = new GeoDataParser(GeoData_KML);\n else if (fileName.endsWith(\".gpx\"))\n parser = new GeoDataParser(GeoData_GPX);\n\n if (!parser) {\n qWarning(\"Could not determine file format!\");\n return -1;\n }\n\n if (!parser->read(&file)) {\n qWarning(\"Could not parse file!\");\n return -1;\n }\n\n \/\/ Get result document\n GeoDocument* document = parser->releaseDocument();\n Q_ASSERT(document);\n\n if (document->isGeoDataDocument()) {\n GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>(document);\n QVector<GeoDataFeature>::const_iterator it = dataDocument->features().constBegin();\n QVector<GeoDataFeature>::const_iterator end = dataDocument->features().constEnd();\n qDebug() << \"---------------------------------------------------------\";\n for (; it != end; ++it) {\n qDebug() << \"Name: \" << it->name();\n }\n dumpGeoDataDocument(static_cast<GeoDataDocument*>(document));\n } else if (document->isGeoSceneDocument()) {\n GeoSceneDocument *sceneDocument = static_cast<GeoSceneDocument*>(document);\n qDebug() << \"Name: \" << sceneDocument->head()->name(); \n qDebug() << \"Target: \" << sceneDocument->head()->target(); \n qDebug() << \"Theme: \" << sceneDocument->head()->theme(); \n qDebug() << \"Icon (pixmap): \" << sceneDocument->head()->icon()->pixmap(); \n qDebug() << \"Icon (color) : \" << sceneDocument->head()->icon()->color(); \n qDebug() << \"Description: \" << sceneDocument->head()->description(); \n qDebug() << \"Visible: \" << sceneDocument->head()->visible(); \n qDebug() << \"Discrete: \" << sceneDocument->head()->zoom()->discrete(); \n qDebug() << \"Minimum: \" << sceneDocument->head()->zoom()->minimum(); \n qDebug() << \"Maximum: \" << sceneDocument->head()->zoom()->maximum(); \n if(sceneDocument->settings() && \n sceneDocument->settings()->property( \"cities\" ) && \n sceneDocument->settings()->property( \"relief\" )) {\n qDebug() << \"CitiesName: \" << sceneDocument->settings()->property( \"cities\" )->name(); \n qDebug() << \"Available: \" << sceneDocument->settings()->property( \"cities\" )->available(); \n qDebug() << \"Value: \" << sceneDocument->settings()->property( \"cities\" )->value(); \n qDebug() << \"ReliefName: \" << sceneDocument->settings()->property( \"relief\" )->name(); \n qDebug() << \"Available: \" << sceneDocument->settings()->property( \"relief\" )->available(); \n qDebug() << \"Value: \" << sceneDocument->settings()->property( \"relief\" )->value(); \n qDebug() << \"Test query a nonexistent property: \" << sceneDocument->settings()->property( \"nonexistent\" )->name();\n }\n if(sceneDocument->map()) {\n qDebug() << \"layers:\" << sceneDocument->map()->layers().size();\n QVector<GeoSceneLayer*>::const_iterator it = sceneDocument->map()->layers().constBegin();\n QVector<GeoSceneLayer*>::const_iterator end = sceneDocument->map()->layers().constEnd();\n for (; it != end; it++) {\n GeoSceneLayer* layer = *it;\n qDebug() << \"\\t---------------------------------------------------------\";\n qDebug() << \"\\tLayerName: \" << layer->name();\n qDebug() << \"\\tBackend: \" << layer->backend();\n QVector<GeoSceneAbstractDataset*>::const_iterator it = layer->datasets().constBegin();\n QVector<GeoSceneAbstractDataset*>::const_iterator end = layer->datasets().constEnd();\n for (; it != end; ++it) {\n GeoSceneAbstractDataset* dataset = *it;\n qDebug() << \"\\t\\tDatasetName: \" << dataset->name();\n qDebug() << \"\\t\\tFileformat: \" << dataset->fileFormat();\n qDebug() << \"\\t\\tType: \" << dataset->type();\n }\n }\n }\n dumpGeoSceneDocument(static_cast<GeoSceneDocument*>(document));\n }\n else {\n \/\/ A parsed document should either be a GeoDataDocument or a GeoSceneDocument!\n Q_ASSERT(false);\n }\n\n qDebug() << \"\\nSuccessfully parsed file!\";\n delete document;\n qDebug() << \"\\nSuccessfully deleted file!\";\n return 0;\n}\n\nQString formatOutput(int depth)\n{\n QString result;\n for (int i = 0; i < depth; ++i)\n result += \" \";\n\n return result;\n}\n\nvoid dumpFoldersRecursively(const GeoDataContainer& container, int depth)\n{\n QVector<GeoDataFolder> folders = container.folders();\n QString format = formatOutput(depth);\n\n fprintf(stderr, \"%s\", qPrintable(format + QString(\"Dumping container with %1 child folders!\\n\").arg(folders.size())));\n\n QVector<GeoDataFolder>::const_iterator it = folders.constBegin();\n const QVector<GeoDataFolder>::const_iterator end = folders.constEnd();\n\n for (; it != end; ++it) {\n fprintf(stderr, \"%s\", qPrintable(format + QString(\"Dumping child %1\\n\").arg(it - folders.constBegin() + 1)));\n dumpFoldersRecursively(*it, ++depth);\n }\n}\n\nvoid dumpGeoDataDocument(GeoDataDocument* document)\n{\n dumpFoldersRecursively(*document, 0);\n \/\/ TODO: Dump all features!\n} \n\nvoid dumpGeoSceneDocument(GeoSceneDocument* document)\n{\n \/\/ TODO: Maybe dump parsed datastructures here!\n}\n<commit_msg>add function to dump placemarks<commit_after>\/*\n Copyright (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>\n\n This file is part of the KDE project\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 License\n aint with this library see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QStringList>\n\n#include \"GeoDataParser.h\"\n#include \"GeoDataDocument.h\"\n#include \"GeoDataFolder.h\"\n#include \"GeoDataPlacemark.h\"\n\n#include \"GeoSceneDocument.h\"\n#include \"GeoSceneHead.h\"\n#include \"GeoSceneIcon.h\"\n#include \"GeoSceneLayer.h\"\n#include \"GeoSceneMap.h\"\n#include \"GeoSceneParser.h\"\n#include \"GeoSceneProperty.h\"\n#include \"GeoSceneSettings.h\"\n#include \"GeoSceneZoom.h\"\n\n#ifdef Q_OS_WIN\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid myMessageOutput(QtMsgType type, const char *msg)\n{\n switch (type) {\n case QtDebugMsg:\n fprintf(stdout, \"Debug: %s\\n\", msg);\n break;\n case QtWarningMsg:\n fprintf(stdout, \"Warning: %s\\n\", msg);\n break;\n case QtCriticalMsg:\n fprintf(stdout, \"Critical: %s\\n\", msg);\n break;\n case QtFatalMsg:\n fprintf(stdout, \"Fatal: %s\\n\", msg);\n abort();\n }\n}\n#endif\n\nusing namespace Marble;\n\nvoid dumpGeoDataDocument(GeoDataDocument*);\nvoid dumpGeoSceneDocument(GeoSceneDocument*);\n\nint main(int argc, char** argv)\n{\n#ifdef Q_OS_WIN\n qInstallMsgHandler(myMessageOutput);\n#endif\n QCoreApplication app(argc, argv);\n\n \/\/ Expect document as first command line argument\n if (app.arguments().size() <= 1) {\n qWarning(\"Pass file name as first argument!\");\n return -1;\n }\n\n \/\/ Check whether file exists\n QFile file(app.arguments().at(1));\n if (!file.exists()) {\n qWarning(\"File does not exist!\");\n return -1;\n }\n\n \/\/ Open file in right mode\n file.open(QIODevice::ReadOnly);\n\n GeoParser* parser = 0;\n const QString& fileName = file.fileName().toLower();\n\n \/\/ A real application, would use other heuristics to determine the source type!\n if (fileName.endsWith(\".dgml\"))\n parser = new GeoSceneParser(GeoScene_DGML);\n else if (fileName.endsWith(\".kml\"))\n parser = new GeoDataParser(GeoData_KML);\n else if (fileName.endsWith(\".gpx\"))\n parser = new GeoDataParser(GeoData_GPX);\n\n if (!parser) {\n qWarning(\"Could not determine file format!\");\n return -1;\n }\n\n if (!parser->read(&file)) {\n qWarning(\"Could not parse file!\");\n return -1;\n }\n\n \/\/ Get result document\n GeoDocument* document = parser->releaseDocument();\n Q_ASSERT(document);\n\n if (document->isGeoDataDocument()) {\n GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>(document);\n QVector<GeoDataFeature>::const_iterator it = dataDocument->features().constBegin();\n QVector<GeoDataFeature>::const_iterator end = dataDocument->features().constEnd();\n qDebug() << \"---------------------------------------------------------\";\n for (; it != end; ++it) {\n qDebug() << \"Name: \" << it->name();\n }\n dumpGeoDataDocument(static_cast<GeoDataDocument*>(document));\n } else if (document->isGeoSceneDocument()) {\n GeoSceneDocument *sceneDocument = static_cast<GeoSceneDocument*>(document);\n qDebug() << \"Name: \" << sceneDocument->head()->name(); \n qDebug() << \"Target: \" << sceneDocument->head()->target(); \n qDebug() << \"Theme: \" << sceneDocument->head()->theme(); \n qDebug() << \"Icon (pixmap): \" << sceneDocument->head()->icon()->pixmap(); \n qDebug() << \"Icon (color) : \" << sceneDocument->head()->icon()->color(); \n qDebug() << \"Description: \" << sceneDocument->head()->description(); \n qDebug() << \"Visible: \" << sceneDocument->head()->visible(); \n qDebug() << \"Discrete: \" << sceneDocument->head()->zoom()->discrete(); \n qDebug() << \"Minimum: \" << sceneDocument->head()->zoom()->minimum(); \n qDebug() << \"Maximum: \" << sceneDocument->head()->zoom()->maximum(); \n if(sceneDocument->settings() && \n sceneDocument->settings()->property( \"cities\" ) && \n sceneDocument->settings()->property( \"relief\" )) {\n qDebug() << \"CitiesName: \" << sceneDocument->settings()->property( \"cities\" )->name(); \n qDebug() << \"Available: \" << sceneDocument->settings()->property( \"cities\" )->available(); \n qDebug() << \"Value: \" << sceneDocument->settings()->property( \"cities\" )->value(); \n qDebug() << \"ReliefName: \" << sceneDocument->settings()->property( \"relief\" )->name(); \n qDebug() << \"Available: \" << sceneDocument->settings()->property( \"relief\" )->available(); \n qDebug() << \"Value: \" << sceneDocument->settings()->property( \"relief\" )->value(); \n qDebug() << \"Test query a nonexistent property: \" << sceneDocument->settings()->property( \"nonexistent\" )->name();\n }\n if(sceneDocument->map()) {\n qDebug() << \"layers:\" << sceneDocument->map()->layers().size();\n QVector<GeoSceneLayer*>::const_iterator it = sceneDocument->map()->layers().constBegin();\n QVector<GeoSceneLayer*>::const_iterator end = sceneDocument->map()->layers().constEnd();\n for (; it != end; it++) {\n GeoSceneLayer* layer = *it;\n qDebug() << \"\\t---------------------------------------------------------\";\n qDebug() << \"\\tLayerName: \" << layer->name();\n qDebug() << \"\\tBackend: \" << layer->backend();\n QVector<GeoSceneAbstractDataset*>::const_iterator it = layer->datasets().constBegin();\n QVector<GeoSceneAbstractDataset*>::const_iterator end = layer->datasets().constEnd();\n for (; it != end; ++it) {\n GeoSceneAbstractDataset* dataset = *it;\n qDebug() << \"\\t\\tDatasetName: \" << dataset->name();\n qDebug() << \"\\t\\tFileformat: \" << dataset->fileFormat();\n qDebug() << \"\\t\\tType: \" << dataset->type();\n }\n }\n }\n dumpGeoSceneDocument(static_cast<GeoSceneDocument*>(document));\n }\n else {\n \/\/ A parsed document should either be a GeoDataDocument or a GeoSceneDocument!\n Q_ASSERT(false);\n }\n\n qDebug() << \"\\nSuccessfully parsed file!\";\n delete document;\n qDebug() << \"\\nSuccessfully deleted file!\";\n return 0;\n}\n\nQString formatOutput(int depth)\n{\n QString result;\n for (int i = 0; i < depth; ++i)\n result += \" \";\n\n return result;\n}\n\nvoid dumpGeoDataPlacemark(const GeoDataPlacemark& placemark)\n{\n qDebug() << placemark.name() << placemark.population() << placemark.coordinate().toString();\n}\n\nvoid dumpFoldersRecursively(const GeoDataContainer& container, int depth)\n{\n qDebug() << \"dumping container with\" << container.size() << \"children...\";\n\n QVector<GeoDataFolder> folders = container.folders();\n QVector<GeoDataPlacemark> placemarks = container.placemarks();\n QString format = formatOutput(depth);\n\n fprintf(stderr, \"%s\", qPrintable(format + QString(\"Dumping container with %1 child folders!\\n\").arg(folders.size())));\n\n QVector<GeoDataFolder>::const_iterator it = folders.constBegin();\n const QVector<GeoDataFolder>::const_iterator end = folders.constEnd();\n\n for (; it != end; ++it) {\n fprintf(stderr, \"%s\", qPrintable(format + QString(\"Dumping child %1\\n\").arg(it - folders.constBegin() + 1)));\n dumpFoldersRecursively(*it, ++depth);\n }\n\n fprintf(stderr, \"%s\", qPrintable(format + QString(\"Dumping container with %1 child placemarks!\\n\").arg(placemarks.size())));\n\n QVector<GeoDataPlacemark>::const_iterator pit = placemarks.constBegin();\n const QVector<GeoDataPlacemark>::const_iterator pend = placemarks.constEnd();\n\n for (; pit != pend; ++pit) {\n fprintf(stderr, \"%s\", qPrintable(format + QString(\"Dumping child %1\\n\").arg(pit - placemarks.constBegin() + 1)));\n dumpGeoDataPlacemark(*pit);\n }\n}\n\nvoid dumpGeoDataDocument(GeoDataDocument* document)\n{\n dumpFoldersRecursively(*document, 0);\n \/\/ TODO: Dump all features!\n} \n\nvoid dumpGeoSceneDocument(GeoSceneDocument* document)\n{\n \/\/ TODO: Maybe dump parsed datastructures here!\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ simplest make is g++ -O2 -std=c++11 fastavoidance.cpp -g -o fastavoidance\n#include <bitset>\n#include <cassert>\n#include <cmath>\n#include <cstdint>\n#include <cstdio> \/* printf, scanf, puts, NULL *\/\n#include <cstdlib>\n#include <cstring>\n#include <ctime> \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <sys\/time.h>\n#include <vector>\n#include \"hashdb.h\"\n#include \"fastavoidance.h\"\n#include \"perm.h\"\nusing namespace std;\n\n\/\/ 1 to use a bithack inspired by permlab. Upshot: Code runs about a third faster. Downshot: Code is around 1\/4 less memory efficient\n#define USEBITHACK 1\n#define USEPREFIXMAP 1\n\n\/\/ Input: perm, inverse (which needs to be right in pos length - index - 1), perm length, index, complement of normalization of index - 1 largest letters in perm, a bitmap which should start off at zero for index = 0\n\/\/ Output: bitmap is updated. answer is updated to be complement of normalization of index largest letters in perm\nvoid extendnormalizetop(uint64_t perm, uint64_t inverse, int length, int index, uint64_t &answer, uint32_t & seenpos) {\n int i = length - index - 1;\n int oldpos = getdigit(inverse, i);\n int newpos = 0;\n if (oldpos != 0){\n uint32_t temp = seenpos << (32 - oldpos); \/\/ Note: shifting by 32 is ill-defined, which is why we explicitly eliminate digit = 0 case.\n newpos = __builtin_popcount(temp);\n }\n answer = setdigit(addpos(answer, newpos), newpos, index);\n seenpos = seenpos | (1 << oldpos);\n}\n\nvoid addprefixeshelper(uint64_t perm, int length, hashdb &table) {\n uint64_t entry = 0;\n uint64_t inverse = getinverse(perm, length);\n uint32_t seenpos = 0; \/\/ bit map of which letters we've seen so far\n for (int i = 0; i < length; i++) {\n extendnormalizetop(perm, inverse, length, i, entry, seenpos);\n \/\/cout<<entry<<endl;\n if (!table.contains(entry)) table.add(entry);\n }\n}\n\n\/\/ build prefix table\nvoid addprefixes(const hashdb &permset, hashdb &table) {\n vector <unsigned long long> patterns;\n permset.getvals(patterns);\n for (int i = 0; i < patterns.size(); i++) {\n uint64_t perm = patterns[i];\n int length = getmaxdigit(perm) + 1;\n displayperm(perm,length);\n addprefixeshelper(perm, length, table);\n }\n}\n\nunsigned long long stat1 = 0, stat2 = 0;\n\n\/\/ THIS IS HOW YOU KEEP A FUNCTION FROM INLINING!\n__attribute__((noinline)) uint64_t getinversecover(uint64_t perm, size_t length) {\n \/\/__attribute__((noinline));\n return getinverse(perm, length);\n}\n\n\/\/ Detects if perm is in S_{length}(patternset), where maxavoidsize is the length of the longest pattern in patternset.\n\/\/ Prerequisite:\n\/\/ -- The subset of S_{n-1} contained in avoidset is exactly S_{n-1}(patternset)\n\/\/ -- If USEBITHACK, then we also require that the user has already verified that all patterns in perm use both n and n-1.\nstatic bool isavoider(uint64_t perm, uint64_t inverse, int maxavoidsize, int length, const hashdb &avoidset, const hashdb &patternset, const hashdb &prefixmap) {\n stat1++;\n if (length <= maxavoidsize && patternset.contains(perm)) { \/\/ if perm is an offending pattern\n return false;\n }\n uint32_t seenpos = 0;\n uint64_t prefixentry = 0;\n uint64_t currentperm = perm;\n if (length > 1) { \/\/ don't deal with permutations of size zero\n for (int i = length - 1; i >= 0 && i >= length - maxavoidsize - 1; i--) { \/\/ for i ranging from the largest-valued letter in perm to the (maxavoidsize + 1)-th largest-valued letter in perm\n if (i < length - 1) { \/\/ add back in digit we deleted a moment ago, but with value one smaller\n currentperm = addpos(currentperm, getdigit(inverse, i + 1));\n\tcurrentperm = setdigit(currentperm, getdigit(inverse, i + 1), i);\n }\n currentperm = killpos(currentperm, getdigit(inverse, i)); \/\/ now currentperm is perm, except with the letter of value i removed, and the permutation normalized to be on the letters 0,...,(length - 2)\n \/\/displayperm(currentperm)\n if (!USEBITHACK || i < length - 2) stat2++;\n if ((!USEBITHACK || i < length - 2) && !avoidset.contains(currentperm)) { \/\/ Check if this sub-permutation of perm is in S_{length - 1}(patternset)\n\treturn false; \/\/ found a subword not avoiding the patterns\n }\n\n if (USEPREFIXMAP) {\n\textendnormalizetop(perm, inverse, length, length - 1 - i, prefixentry, seenpos);\n\tif (i < length - 1 && !prefixmap.contains(prefixentry)) return true;\n\tif (i == length - maxavoidsize) return false;\n }\n \/\/ The next two lines are special for when there is a single pattern and it is the identity. They reduce cache misses significantly. For |pi|=5, this gets roughly a x2 speedup\n \/\/ Can this hack be extended efficiently to arbitrary choices of pattern-sets?\n \/\/ if (i < length - 1 && getdigit(inverse, i) > getdigit(inverse, i + 1)) return true;\n \/\/ if (i == length - maxavoidsize) return false;\n }\n }\n return true;\n}\n\n\/\/ Get pos-th bit from bitmap. Indexing starts at 0\ninline uint64_t getbit(uint64_t word, int pos) {\n return (word >> pos) & 1;\n}\n\n\/\/ Set pos-th bit from bitmap. Indexing starts at 0\ninline uint64_t setbit(uint64_t word, uint64_t pos, uint64_t val) { \/\/ val is 1 or 0\n return (word & (~(0L) - (1<<pos))) + (1<<pos)*val;\n}\n\n\/\/ Shift the bits in positions pos, pos+1, ... to the right and insert bit with value val in position pos. Indexing starts at 0\n\/\/ Note that due to bit-shift setup, is not capable to inserting in final position ==> Prereq: pos < 63\ninline uint64_t insertbit(uint64_t word, uint64_t pos, uint64_t val) { \/\/ val is 1 or 0\n return (word & ((1 << pos) - 1) ) + ((word >> pos) << (pos + 1)) + val * (1 << pos);\n}\n\n\/\/ Builds the permutations in $S_1, ..., S_maxsize$ avoiding the\n\/\/ patterns in patternset, the longest of which is length\n\/\/ maxavoidsize. If justcount, does nothing with avoidervector but\n\/\/ makes nuavoiders[i] be the number of avoiders in S_i (for i >\n\/\/ 0). If !justcount, does nothing with numavoiders, but makes\n\/\/ avoidervector contain a vector of all permutations in S_i in\n\/\/ avoidervector[i] (for i > 0). plannedavoisetsize should be large if\n\/\/ we expect a major computation and small otherwise (dictates how\n\/\/ much memory is initially allocated to data structures at start of\n\/\/ algorithm.).\n\/\/ Note: Patternset patterns required to be size >= 2\nvoid buildavoiders(const hashdb &patternset, int maxavoidsize, int maxsize, vector < vector < uint64_t > > &avoidervector, vector < uint64_t > &numavoiders, bool justcount, uint64_t plannedavoidsetsize) {\n if (!justcount) avoidervector.resize(maxsize + 1);\n else numavoiders.resize(maxsize + 1);\n\n hashdb prefixmap(1<<3);\n addprefixes(patternset, prefixmap);\n hashdb avoidset = hashdb(plannedavoidsetsize); \/\/ hash table containing avoiders of all sizes\n uint64_t startperm = 0;\n avoidset.add(startperm); \/\/ identity in S_1\n if (!justcount) avoidervector[1].push_back(startperm);\n else numavoiders[1] = 1;\n \n std::queue<unsigned long long> avoiderstoextend; \/\/ queue of avoiders built so far.\n \/\/ when we find an avoider, we will add it to this queue. We will\n \/\/ then later take it out of the queue and use it to generate\n \/\/ options for avoiders of length one larger\n std::queue<unsigned long long> bitmaps; \/\/ Contains a bitmap associated with each avoider in avoiderstoextendd (if USEBITHACK)\n \/\/ The bitmap for a permutation w \\in S_n has a 1 in position i iff\n \/\/ inserting letter (n + 1) in position i of w would result in\n \/\/ permutation w' such that if you removed the letter n from w', the\n \/\/ result would be a patternset-avoiding word. Thus when checking\n \/\/ whether w' is an avoider, we do not have to explicitly check for\n \/\/ this property, preventing a cache-miss.\n \n avoiderstoextend.push(startperm);\n if (USEBITHACK) bitmaps.push(3L);\n\n int currentlength = 1; \/\/ maintain as length of next permutation to be popped from avoiderstoextend\n int numleftcurrentlength = 1; \/\/ number of permutations left in avoiderstoextend until we have to increment currentlength\n int numnextlength = 0; \/\/ number of permutations of size currentlength + 1 in avoiderstoextend\n\n while (avoiderstoextend.size() > 0) {\n if (numleftcurrentlength == 0) {\n \/\/cout<<\"Finished n = \"<<currentlength + 1<<\" with \"<<numavoiders[currentlength + 1]<<\" avoiders\"<<endl; \/\/ MEMORY EFFICIENCY NOTE: I TEMPORARILY LOOSE A FACTOR OF 1\/3 WHEN I RESIZE\n numleftcurrentlength = numnextlength;\n numnextlength = 0;\n currentlength++;\n }\n uint64_t perm = avoiderstoextend.front();\n uint64_t bitmap = bitmaps.front();\n avoiderstoextend.pop();\n if (USEBITHACK) bitmaps.pop();\n numleftcurrentlength--;\n uint64_t inverse = getinversecover(perm, currentlength);\n uint64_t newinverse = setdigit(inverse, currentlength, currentlength); \/\/ inverse of the extended permutation\n for (int i = currentlength; i >= 0; i--) {\n \/\/ need to increment newinverse[perm[i]], decrement newinverse[currentlength]\n if (i < currentlength) newinverse = newinverse + (1L << (4 * getdigit(perm, i))) - (1L << (4 * currentlength));\n if (!USEBITHACK || getbit(bitmap, i) == 1) { \/\/ If we are using bithack, then we only bother extending perm by inserting value currentlength in i-th position if the bitmap tells tells us the result is a potential avoider\n\tuint64_t extendedperm = setdigit(addpos(perm, i), i, currentlength); \/\/ insert currentlength in i-th position (remember, values are indexed starting at 0)\n\tif (isavoider(extendedperm, newinverse, maxavoidsize, currentlength + 1, avoidset, patternset, prefixmap)) { \/\/ if extended permutation is avoider\n\t if (!justcount) avoidervector[currentlength + 1].push_back(extendedperm);\n\t else numavoiders[currentlength + 1]++;\n\t if (currentlength + 1 < maxsize) {\n\t avoiderstoextend.push(extendedperm);\n\t avoidset.add(extendedperm);\n\t numnextlength++; \n\t }\n\t} else {\n\t if (USEBITHACK) bitmap = setbit(bitmap, i, 0); \/\/ keep track of which insertion positions resulted in an avoider\n\t}\n }\n }\n if (USEBITHACK && currentlength + 1 < maxsize) {\n for (int i = currentlength; i >= 0; i--) {\n\tif (getbit(bitmap, i) == 1) {\n\t bitmaps.push(insertbit(bitmap, i + 1, 1)); \/\/ using which insertion positions resulted in an avoider, build bitmap for each new avoider\n\t}\n }\n }\n }\n}\n\n\/\/ Example:\n\/\/ string patternlist = \"1234 3214\"; \/\/ space separated list of patterns; need not be same sizes; must be in S_{<10}\n\/\/ vector < vector < uint64_t > > avoidervector;\n\/\/ buildavoidersfrompatternlist(patternlist, 10, avoidervector); \/\/ now avoidervector contains S_n(patternlist) stored in avoidervector[n] for 0 < n < 11\nvoid buildavoidersfrompatternlist(string patternlist, int maxpermsize, vector < vector < uint64_t > > &avoidervector) {\n int maxpatternsize;\n hashdb patternset = hashdb(1<<3);\n makepatterns(patternlist, patternset, maxpatternsize);\n vector < uint64_t > numavoiders;\n buildavoiders(patternset, maxpatternsize, maxpermsize, avoidervector, numavoiders, false, (1L << 10)); \/\/ for large cases, make last argument much larger!\n}\n\n\/\/ Example:\n\/\/ string patternlist = \"1234 3214\"; \/\/ space separated list of patterns; need not be same sizes; must be in S_{<10}\n\/\/ vector < uint64_t > numavoiders;\n\/\/ buildavoidersfrompatternlist(patternlist, 10, numavoiders); \/\/ now avoidervector contains |S_n(patternlist)| stored in numavoiders[n] for 0 < n < 11.\nvoid countavoidersfrompatternlist(string patternlist, int maxpermsize, vector < uint64_t > &numavoiders) {\n int maxpatternsize;\n hashdb patternset = hashdb(1<<3);\n makepatterns(patternlist, patternset, maxpatternsize);\n vector < vector < uint64_t > > avoidervector;\n buildavoiders(patternset, maxpatternsize, maxpermsize, avoidervector, numavoiders, true, (1L << 10)); \/\/ for large cases, make last argument much larger!\n}\n\n\/\/ Inputs file stream containing string list of patterns on each line. \n\/\/ e.g., infile might contain\n\/\/ 1234 312\n\/\/ 231 4132 312\n\/\/ Outputs file stream alternating every other line\n\/\/ (1) #<list of patterns>\n\/\/ (2) |S_1(list of patterns)| |S_2(list of patterns)| ... |S_maxpermsize(list of patterns)|\n\/\/ e.g., output file might contain\n\/\/ #1234 312\n\/\/ 0 2 5 13 31 66 127 225 373 586 \n\/\/ #231 4132 312\n\/\/ 0 2 4 8 16 32 64 128 256 512\nvoid countavoidersfromfile(ifstream &infile, ofstream &outfile, int maxpermsize, bool verbose) {\n string line;\n while (getline(infile, line)) {\n outfile<<\"#\"<<line<<endl;\n if (verbose) cout<<line<<endl;\n vector < uint64_t > numavoiders;\n timestamp_t start_time = get_timestamp();\n countavoidersfrompatternlist(line, maxpermsize, numavoiders);\n timestamp_t end_time = get_timestamp();\n for (int i = 1; i < numavoiders.size(); i++) {\n if (verbose) cout<<numavoiders[i]<<\" \";\n outfile<<numavoiders[i]<<\" \";\n }\n if (verbose) cout<<endl;\n outfile<<endl;\n if (verbose) cout<< \"Time elapsed (s): \"<<(end_time - start_time)\/1000000.0L<<endl;\n }\n cout<<(double)stat2\/(double)stat1<<endl;\n return;\n}\n<commit_msg>added a third statistic<commit_after>\/\/ simplest make is g++ -O2 -std=c++11 fastavoidance.cpp -g -o fastavoidance\n#include <bitset>\n#include <cassert>\n#include <cmath>\n#include <cstdint>\n#include <cstdio> \/* printf, scanf, puts, NULL *\/\n#include <cstdlib>\n#include <cstring>\n#include <ctime> \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <sys\/time.h>\n#include <vector>\n#include \"hashdb.h\"\n#include \"fastavoidance.h\"\n#include \"perm.h\"\nusing namespace std;\n\n\/\/ 1 to use a bithack inspired by permlab. Upshot: Code runs about a third faster. Downshot: Code is around 1\/4 less memory efficient\n#define USEBITHACK 1\n#define USEPREFIXMAP 1\n\n\/\/ Input: perm, inverse (which needs to be right in pos length - index - 1), perm length, index, complement of normalization of index - 1 largest letters in perm, a bitmap which should start off at zero for index = 0\n\/\/ Output: bitmap is updated. answer is updated to be complement of normalization of index largest letters in perm\nvoid extendnormalizetop(uint64_t perm, uint64_t inverse, int length, int index, uint64_t &answer, uint32_t & seenpos) {\n int i = length - index - 1;\n int oldpos = getdigit(inverse, i);\n int newpos = 0;\n if (oldpos != 0){\n uint32_t temp = seenpos << (32 - oldpos); \/\/ Note: shifting by 32 is ill-defined, which is why we explicitly eliminate digit = 0 case.\n newpos = __builtin_popcount(temp);\n }\n answer = setdigit(addpos(answer, newpos), newpos, index);\n seenpos = seenpos | (1 << oldpos);\n}\n\nvoid addprefixeshelper(uint64_t perm, int length, hashdb &table) {\n uint64_t entry = 0;\n uint64_t inverse = getinverse(perm, length);\n uint32_t seenpos = 0; \/\/ bit map of which letters we've seen so far\n for (int i = 0; i < length; i++) {\n extendnormalizetop(perm, inverse, length, i, entry, seenpos);\n \/\/cout<<entry<<endl;\n if (!table.contains(entry)) table.add(entry);\n }\n}\n\n\/\/ build prefix table\nvoid addprefixes(const hashdb &permset, hashdb &table) {\n vector <unsigned long long> patterns;\n permset.getvals(patterns);\n for (int i = 0; i < patterns.size(); i++) {\n uint64_t perm = patterns[i];\n int length = getmaxdigit(perm) + 1;\n displayperm(perm,length);\n addprefixeshelper(perm, length, table);\n }\n}\n\nunsigned long long stat1 = 0, stat2 = 0, stat3 = 0;\n\n\/\/ THIS IS HOW YOU KEEP A FUNCTION FROM INLINING!\n__attribute__((noinline)) uint64_t getinversecover(uint64_t perm, size_t length) {\n \/\/__attribute__((noinline));\n return getinverse(perm, length);\n}\n\n\/\/ Detects if perm is in S_{length}(patternset), where maxavoidsize is the length of the longest pattern in patternset.\n\/\/ Prerequisite:\n\/\/ -- The subset of S_{n-1} contained in avoidset is exactly S_{n-1}(patternset)\n\/\/ -- If USEBITHACK, then we also require that the user has already verified that all patterns in perm use both n and n-1.\nstatic bool isavoider(uint64_t perm, uint64_t inverse, int maxavoidsize, int length, const hashdb &avoidset, const hashdb &patternset, const hashdb &prefixmap) {\n stat1++;\n if (length <= maxavoidsize && patternset.contains(perm)) { \/\/ if perm is an offending pattern\n return false;\n }\n uint32_t seenpos = 0;\n uint64_t prefixentry = 0;\n uint64_t currentperm = perm;\n if (length > 1) { \/\/ don't deal with permutations of size zero\n for (int i = length - 1; i >= 0 && i >= length - maxavoidsize - 1; i--) { \/\/ for i ranging from the largest-valued letter in perm to the (maxavoidsize + 1)-th largest-valued letter in perm\n if (i < length - 1) { \/\/ add back in digit we deleted a moment ago, but with value one smaller\n currentperm = addpos(currentperm, getdigit(inverse, i + 1));\n\tcurrentperm = setdigit(currentperm, getdigit(inverse, i + 1), i);\n }\n currentperm = killpos(currentperm, getdigit(inverse, i)); \/\/ now currentperm is perm, except with the letter of value i removed, and the permutation normalized to be on the letters 0,...,(length - 2)\n \/\/displayperm(currentperm)\n if (!USEBITHACK || i < length - 2) stat2++;\n if ((!USEBITHACK || i < length - 2) && !avoidset.contains(currentperm)) { \/\/ Check if this sub-permutation of perm is in S_{length - 1}(patternset)\n\treturn false; \/\/ found a subword not avoiding the patterns\n }\n\n if (USEPREFIXMAP) {\n\textendnormalizetop(perm, inverse, length, length - 1 - i, prefixentry, seenpos);\n\tif (i < length - 1 && !prefixmap.contains(prefixentry)) return true;\n\tif (i == length - maxavoidsize) return false;\n }\n \/\/ The next two lines are special for when there is a single pattern and it is the identity. They reduce cache misses significantly. For |pi|=5, this gets roughly a x2 speedup\n \/\/ Can this hack be extended efficiently to arbitrary choices of pattern-sets?\n \/\/ if (i < length - 1 && getdigit(inverse, i) > getdigit(inverse, i + 1)) return true;\n \/\/ if (i == length - maxavoidsize) return false;\n }\n }\n return true;\n}\n\n\/\/ Get pos-th bit from bitmap. Indexing starts at 0\ninline uint64_t getbit(uint64_t word, int pos) {\n return (word >> pos) & 1;\n}\n\n\/\/ Set pos-th bit from bitmap. Indexing starts at 0\ninline uint64_t setbit(uint64_t word, uint64_t pos, uint64_t val) { \/\/ val is 1 or 0\n return (word & (~(0L) - (1<<pos))) + (1<<pos)*val;\n}\n\n\/\/ Shift the bits in positions pos, pos+1, ... to the right and insert bit with value val in position pos. Indexing starts at 0\n\/\/ Note that due to bit-shift setup, is not capable to inserting in final position ==> Prereq: pos < 63\ninline uint64_t insertbit(uint64_t word, uint64_t pos, uint64_t val) { \/\/ val is 1 or 0\n return (word & ((1 << pos) - 1) ) + ((word >> pos) << (pos + 1)) + val * (1 << pos);\n}\n\n\/\/ Builds the permutations in $S_1, ..., S_maxsize$ avoiding the\n\/\/ patterns in patternset, the longest of which is length\n\/\/ maxavoidsize. If justcount, does nothing with avoidervector but\n\/\/ makes nuavoiders[i] be the number of avoiders in S_i (for i >\n\/\/ 0). If !justcount, does nothing with numavoiders, but makes\n\/\/ avoidervector contain a vector of all permutations in S_i in\n\/\/ avoidervector[i] (for i > 0). plannedavoisetsize should be large if\n\/\/ we expect a major computation and small otherwise (dictates how\n\/\/ much memory is initially allocated to data structures at start of\n\/\/ algorithm.).\n\/\/ Note: Patternset patterns required to be size >= 2\nvoid buildavoiders(const hashdb &patternset, int maxavoidsize, int maxsize, vector < vector < uint64_t > > &avoidervector, vector < uint64_t > &numavoiders, bool justcount, uint64_t plannedavoidsetsize) {\n if (!justcount) avoidervector.resize(maxsize + 1);\n else numavoiders.resize(maxsize + 1);\n\n hashdb prefixmap(1<<3);\n addprefixes(patternset, prefixmap);\n hashdb avoidset = hashdb(plannedavoidsetsize); \/\/ hash table containing avoiders of all sizes\n uint64_t startperm = 0;\n avoidset.add(startperm); \/\/ identity in S_1\n if (!justcount) avoidervector[1].push_back(startperm);\n else numavoiders[1] = 1;\n \n std::queue<unsigned long long> avoiderstoextend; \/\/ queue of avoiders built so far.\n \/\/ when we find an avoider, we will add it to this queue. We will\n \/\/ then later take it out of the queue and use it to generate\n \/\/ options for avoiders of length one larger\n std::queue<unsigned long long> bitmaps; \/\/ Contains a bitmap associated with each avoider in avoiderstoextendd (if USEBITHACK)\n \/\/ The bitmap for a permutation w \\in S_n has a 1 in position i iff\n \/\/ inserting letter (n + 1) in position i of w would result in\n \/\/ permutation w' such that if you removed the letter n from w', the\n \/\/ result would be a patternset-avoiding word. Thus when checking\n \/\/ whether w' is an avoider, we do not have to explicitly check for\n \/\/ this property, preventing a cache-miss.\n \n avoiderstoextend.push(startperm);\n if (USEBITHACK) bitmaps.push(3L);\n\n int currentlength = 1; \/\/ maintain as length of next permutation to be popped from avoiderstoextend\n int numleftcurrentlength = 1; \/\/ number of permutations left in avoiderstoextend until we have to increment currentlength\n int numnextlength = 0; \/\/ number of permutations of size currentlength + 1 in avoiderstoextend\n\n while (avoiderstoextend.size() > 0) {\n if (numleftcurrentlength == 0) {\n \/\/cout<<\"Finished n = \"<<currentlength + 1<<\" with \"<<numavoiders[currentlength + 1]<<\" avoiders\"<<endl; \/\/ MEMORY EFFICIENCY NOTE: I TEMPORARILY LOOSE A FACTOR OF 1\/3 WHEN I RESIZE\n numleftcurrentlength = numnextlength;\n numnextlength = 0;\n currentlength++;\n }\n uint64_t perm = avoiderstoextend.front();\n uint64_t bitmap = bitmaps.front();\n avoiderstoextend.pop();\n if (USEBITHACK) bitmaps.pop();\n numleftcurrentlength--;\n uint64_t inverse = getinversecover(perm, currentlength);\n uint64_t newinverse = setdigit(inverse, currentlength, currentlength); \/\/ inverse of the extended permutation\n for (int i = currentlength; i >= 0; i--) {\n \/\/ need to increment newinverse[perm[i]], decrement newinverse[currentlength]\n stat3++;\n if (i < currentlength) newinverse = newinverse + (1L << (4 * getdigit(perm, i))) - (1L << (4 * currentlength));\n if (!USEBITHACK || getbit(bitmap, i) == 1) { \/\/ If we are using bithack, then we only bother extending perm by inserting value currentlength in i-th position if the bitmap tells tells us the result is a potential avoider\n\tuint64_t extendedperm = setdigit(addpos(perm, i), i, currentlength); \/\/ insert currentlength in i-th position (remember, values are indexed starting at 0)\n\tif (isavoider(extendedperm, newinverse, maxavoidsize, currentlength + 1, avoidset, patternset, prefixmap)) { \/\/ if extended permutation is avoider\n\t if (!justcount) avoidervector[currentlength + 1].push_back(extendedperm);\n\t else numavoiders[currentlength + 1]++;\n\t if (currentlength + 1 < maxsize) {\n\t avoiderstoextend.push(extendedperm);\n\t avoidset.add(extendedperm);\n\t numnextlength++; \n\t }\n\t} else {\n\t if (USEBITHACK) bitmap = setbit(bitmap, i, 0); \/\/ keep track of which insertion positions resulted in an avoider\n\t}\n }\n }\n if (USEBITHACK && currentlength + 1 < maxsize) {\n for (int i = currentlength; i >= 0; i--) {\n\tif (getbit(bitmap, i) == 1) {\n\t bitmaps.push(insertbit(bitmap, i + 1, 1)); \/\/ using which insertion positions resulted in an avoider, build bitmap for each new avoider\n\t}\n }\n }\n }\n}\n\n\/\/ Example:\n\/\/ string patternlist = \"1234 3214\"; \/\/ space separated list of patterns; need not be same sizes; must be in S_{<10}\n\/\/ vector < vector < uint64_t > > avoidervector;\n\/\/ buildavoidersfrompatternlist(patternlist, 10, avoidervector); \/\/ now avoidervector contains S_n(patternlist) stored in avoidervector[n] for 0 < n < 11\nvoid buildavoidersfrompatternlist(string patternlist, int maxpermsize, vector < vector < uint64_t > > &avoidervector) {\n int maxpatternsize;\n hashdb patternset = hashdb(1<<3);\n makepatterns(patternlist, patternset, maxpatternsize);\n vector < uint64_t > numavoiders;\n buildavoiders(patternset, maxpatternsize, maxpermsize, avoidervector, numavoiders, false, (1L << 10)); \/\/ for large cases, make last argument much larger!\n}\n\n\/\/ Example:\n\/\/ string patternlist = \"1234 3214\"; \/\/ space separated list of patterns; need not be same sizes; must be in S_{<10}\n\/\/ vector < uint64_t > numavoiders;\n\/\/ buildavoidersfrompatternlist(patternlist, 10, numavoiders); \/\/ now avoidervector contains |S_n(patternlist)| stored in numavoiders[n] for 0 < n < 11.\nvoid countavoidersfrompatternlist(string patternlist, int maxpermsize, vector < uint64_t > &numavoiders) {\n int maxpatternsize;\n hashdb patternset = hashdb(1<<3);\n makepatterns(patternlist, patternset, maxpatternsize);\n vector < vector < uint64_t > > avoidervector;\n buildavoiders(patternset, maxpatternsize, maxpermsize, avoidervector, numavoiders, true, (1L << 10)); \/\/ for large cases, make last argument much larger!\n}\n\n\/\/ Inputs file stream containing string list of patterns on each line. \n\/\/ e.g., infile might contain\n\/\/ 1234 312\n\/\/ 231 4132 312\n\/\/ Outputs file stream alternating every other line\n\/\/ (1) #<list of patterns>\n\/\/ (2) |S_1(list of patterns)| |S_2(list of patterns)| ... |S_maxpermsize(list of patterns)|\n\/\/ e.g., output file might contain\n\/\/ #1234 312\n\/\/ 0 2 5 13 31 66 127 225 373 586 \n\/\/ #231 4132 312\n\/\/ 0 2 4 8 16 32 64 128 256 512\nvoid countavoidersfromfile(ifstream &infile, ofstream &outfile, int maxpermsize, bool verbose) {\n string line;\n while (getline(infile, line)) {\n outfile<<\"#\"<<line<<endl;\n if (verbose) cout<<line<<endl;\n vector < uint64_t > numavoiders;\n timestamp_t start_time = get_timestamp();\n countavoidersfrompatternlist(line, maxpermsize, numavoiders);\n timestamp_t end_time = get_timestamp();\n for (int i = 1; i < numavoiders.size(); i++) {\n if (verbose) cout<<numavoiders[i]<<\" \";\n outfile<<numavoiders[i]<<\" \";\n }\n if (verbose) cout<<endl;\n outfile<<endl;\n if (verbose) cout<< \"Time elapsed (s): \"<<(end_time - start_time)\/1000000.0L<<endl;\n }\n cout<<(double)stat2\/(double)stat3<<endl;\n return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * (c) 2009-2016 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n *\n * QGroundControl is licensed according to the terms in the file\n * COPYING.md in the root of the source code directory.\n *\n ****************************************************************************\/\n\n\n#include <QStringList>\n#include <QDebug>\n\n#include \"RallyPoint.h\"\n\nconst char* RallyPoint::_longitudeFactName = \"Longitude\";\nconst char* RallyPoint::_latitudeFactName = \"Latitude\";\nconst char* RallyPoint::_altitudeFactName = \"Altitude\";\n\nQMap<QString, FactMetaData*> RallyPoint::_metaDataMap;\n\nRallyPoint::RallyPoint(const QGeoCoordinate& coordinate, QObject* parent)\n : QObject(parent)\n , _dirty(false)\n , _longitudeFact(0, _longitudeFactName, FactMetaData::valueTypeDouble)\n , _latitudeFact(0, _latitudeFactName, FactMetaData::valueTypeDouble)\n , _altitudeFact(0, _altitudeFactName, FactMetaData::valueTypeDouble)\n{\n setCoordinate(coordinate);\n\n _factSetup();\n}\n\nRallyPoint::RallyPoint(const RallyPoint& other, QObject* parent)\n : QObject(parent)\n , _dirty(false)\n , _longitudeFact(0, _longitudeFactName, FactMetaData::valueTypeDouble)\n , _latitudeFact(0, _latitudeFactName, FactMetaData::valueTypeDouble)\n , _altitudeFact(0, _altitudeFactName, FactMetaData::valueTypeDouble)\n{\n _longitudeFact.setRawValue(other._longitudeFact.rawValue());\n _latitudeFact.setRawValue(other._latitudeFact.rawValue());\n _altitudeFact.setRawValue(other._altitudeFact.rawValue());\n\n _factSetup();\n}\n\nconst RallyPoint& RallyPoint::operator=(const RallyPoint& other)\n{\n _longitudeFact.setRawValue(other._longitudeFact.rawValue());\n _latitudeFact.setRawValue(other._latitudeFact.rawValue());\n _altitudeFact.setRawValue(other._altitudeFact.rawValue());\n\n emit coordinateChanged(coordinate());\n\n return *this;\n}\n\nRallyPoint::~RallyPoint()\n{ \n\n}\n\nvoid RallyPoint::_factSetup(void)\n{\n if (_metaDataMap.isEmpty()) {\n _metaDataMap = FactMetaData::createMapFromJsonFile(QStringLiteral(\":\/json\/RallyPoint.json\"), NULL \/* metaDataParent *\/);\n }\n\n _longitudeFact.setMetaData(_metaDataMap[_longitudeFactName]);\n _latitudeFact.setMetaData(_metaDataMap[_latitudeFactName]);\n _altitudeFact.setMetaData(_metaDataMap[_altitudeFactName]);\n\n _textFieldFacts.append(QVariant::fromValue(&_longitudeFact));\n _textFieldFacts.append(QVariant::fromValue(&_latitudeFact));\n _textFieldFacts.append(QVariant::fromValue(&_altitudeFact));\n\n connect(&_longitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);\n connect(&_latitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);\n connect(&_altitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);\n}\n\nvoid RallyPoint::setCoordinate(const QGeoCoordinate& coordinate)\n{\n if (coordinate != this->coordinate()) {\n _longitudeFact.setRawValue(coordinate.longitude());\n _latitudeFact.setRawValue(coordinate.latitude());\n _altitudeFact.setRawValue(coordinate.altitude());\n emit coordinateChanged(coordinate);\n setDirty(true);\n }\n}\n\nvoid RallyPoint::setDirty(bool dirty)\n{\n if (dirty != _dirty) {\n _dirty = dirty;\n emit dirtyChanged(dirty);\n }\n}\n\nQGeoCoordinate RallyPoint::coordinate(void) const\n{\n return QGeoCoordinate(_latitudeFact.rawValue().toDouble(), _longitudeFact.rawValue().toDouble(), _altitudeFact.rawValue().toDouble());\n}\n\nvoid RallyPoint::_sendCoordinateChanged(void)\n{\n emit coordinateChanged(coordinate());\n}\n<commit_msg>Use GridLayout for better layout<commit_after>\/****************************************************************************\n *\n * (c) 2009-2016 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n *\n * QGroundControl is licensed according to the terms in the file\n * COPYING.md in the root of the source code directory.\n *\n ****************************************************************************\/\n\n\n#include <QStringList>\n#include <QDebug>\n\n#include \"RallyPoint.h\"\n\nconst char* RallyPoint::_longitudeFactName = \"Longitude\";\nconst char* RallyPoint::_latitudeFactName = \"Latitude\";\nconst char* RallyPoint::_altitudeFactName = \"Altitude\";\n\nQMap<QString, FactMetaData*> RallyPoint::_metaDataMap;\n\nRallyPoint::RallyPoint(const QGeoCoordinate& coordinate, QObject* parent)\n : QObject(parent)\n , _dirty(false)\n , _longitudeFact(0, _longitudeFactName, FactMetaData::valueTypeDouble)\n , _latitudeFact(0, _latitudeFactName, FactMetaData::valueTypeDouble)\n , _altitudeFact(0, _altitudeFactName, FactMetaData::valueTypeDouble)\n{\n setCoordinate(coordinate);\n\n _factSetup();\n}\n\nRallyPoint::RallyPoint(const RallyPoint& other, QObject* parent)\n : QObject(parent)\n , _dirty(false)\n , _longitudeFact(0, _longitudeFactName, FactMetaData::valueTypeDouble)\n , _latitudeFact(0, _latitudeFactName, FactMetaData::valueTypeDouble)\n , _altitudeFact(0, _altitudeFactName, FactMetaData::valueTypeDouble)\n{\n _longitudeFact.setRawValue(other._longitudeFact.rawValue());\n _latitudeFact.setRawValue(other._latitudeFact.rawValue());\n _altitudeFact.setRawValue(other._altitudeFact.rawValue());\n\n _factSetup();\n}\n\nconst RallyPoint& RallyPoint::operator=(const RallyPoint& other)\n{\n _longitudeFact.setRawValue(other._longitudeFact.rawValue());\n _latitudeFact.setRawValue(other._latitudeFact.rawValue());\n _altitudeFact.setRawValue(other._altitudeFact.rawValue());\n\n emit coordinateChanged(coordinate());\n\n return *this;\n}\n\nRallyPoint::~RallyPoint()\n{ \n\n}\n\nvoid RallyPoint::_factSetup(void)\n{\n if (_metaDataMap.isEmpty()) {\n _metaDataMap = FactMetaData::createMapFromJsonFile(QStringLiteral(\":\/json\/RallyPoint.FactMetaData.json\"), NULL \/* metaDataParent *\/);\n }\n\n _longitudeFact.setMetaData(_metaDataMap[_longitudeFactName]);\n _latitudeFact.setMetaData(_metaDataMap[_latitudeFactName]);\n _altitudeFact.setMetaData(_metaDataMap[_altitudeFactName]);\n\n _textFieldFacts.append(QVariant::fromValue(&_longitudeFact));\n _textFieldFacts.append(QVariant::fromValue(&_latitudeFact));\n _textFieldFacts.append(QVariant::fromValue(&_altitudeFact));\n\n connect(&_longitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);\n connect(&_latitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);\n connect(&_altitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);\n}\n\nvoid RallyPoint::setCoordinate(const QGeoCoordinate& coordinate)\n{\n if (coordinate != this->coordinate()) {\n _longitudeFact.setRawValue(coordinate.longitude());\n _latitudeFact.setRawValue(coordinate.latitude());\n _altitudeFact.setRawValue(coordinate.altitude());\n emit coordinateChanged(coordinate);\n setDirty(true);\n }\n}\n\nvoid RallyPoint::setDirty(bool dirty)\n{\n if (dirty != _dirty) {\n _dirty = dirty;\n emit dirtyChanged(dirty);\n }\n}\n\nQGeoCoordinate RallyPoint::coordinate(void) const\n{\n return QGeoCoordinate(_latitudeFact.rawValue().toDouble(), _longitudeFact.rawValue().toDouble(), _altitudeFact.rawValue().toDouble());\n}\n\nvoid RallyPoint::_sendCoordinateChanged(void)\n{\n emit coordinateChanged(coordinate());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2016 Andreas Bjerkeholt\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"Label.h\"\n#include <SDL.h>\n#include \"..\/graphics_utils.h\"\n#include <sstream>\n#include <limits.h>\n#include \"..\/ScreenSystem\/Screen.h\"\n\nusing namespace std;\n\nLabel::Label()\n{\n\ttexture = NULL;\n\ttext = \"\";\n\ttextSize = 12;\n\ttextColor = Color(0xff, 0xff, 0xff, 0xff);\n\tfont = \"semibold\";\n\tttfFont = NULL;\n}\n\nLabel::~Label()\n{\n\tif (texture != NULL)\n\t\tSDL_DestroyTexture(texture);\n}\n\nbool Label::OnInitialize()\n{\n\tttfFont = context->GetResourceManager()->GetTTFFont(font, textSize);\n\n\tif (ttfFont == NULL)\n\t\treturn false;\n\n\tif (!RenderText(UINT_MAX))\n\t\treturn false;\n\n\treturn true;\n}\n\nbool Label::RenderText(Uint32 textAreaWidth)\n{\n\tif (ttfFont == NULL)\n\t\treturn false;\n\n\tif (texture != NULL)\n\t\tSDL_DestroyTexture(texture);\n\n\ttexture = NULL;\n\n\tSDL_Color color;\n\tcolor.r = 0xff;\n\tcolor.g = 0xff;\n\tcolor.b = 0xff;\n\tcolor.a = 0xff;\n\tSDL_Surface* tempSurface = TTF_RenderText_Blended_Wrapped(ttfFont, text.c_str(), color, textAreaWidth);\n\tif (tempSurface == NULL)\n\t\treturn false;\n\n\tSDL_Surface* clippedSurface = NULL;\n\n\tint areaWidth = size.w;\n\tif (size.w == SIZE_FILL_PARENT)\n\t\tareaWidth = calculatedSize.w;\n\telse if (size.w == SIZE_WRAP_CONTENT)\n\t\tareaWidth = tempSurface->w;\n\n\tif (areaWidth > 0 && tempSurface->w > areaWidth)\n\t{\n\t\tSDL_Rect r;\n\t\tr.x = 0;\n\t\tr.y = 0;\n\t\tr.w = areaWidth;\n\t\tr.h = tempSurface->h;\n\t\tclippedSurface = ClipSurface(tempSurface, &r);\n\n\t\tSDL_FreeSurface(tempSurface);\n\n\t\t\/\/ Apply alpha fadeout at end if text doesn't fit completely\n\t\tFadeOutSurface(clippedSurface, 16);\n\t}\n\telse\n\t{\n\t\tclippedSurface = tempSurface;\n\t}\n\n\tif (clippedSurface == NULL)\n\t\treturn false;\n\n\ttexture = SDL_CreateTextureFromSurface(context->GetRenderer(), clippedSurface);\n\tSDL_FreeSurface(clippedSurface);\n\tif (texture == NULL)\n\t\treturn false;\n\n\tSDL_QueryTexture(texture, NULL, NULL, &contentSize.w, &contentSize.h);\n\n\treturn true;\n}\n\nvoid Label::OnDraw(SDL_Renderer* renderer, Position offset)\n{\n\tif (texture == NULL)\n\t\treturn;\n\n\tSDL_Rect r;\n\tr.x = absolutePosition.x + offset.x;\n\tr.y = absolutePosition.y + offset.y;\n\tr.w = contentSize.w;\n\tr.h = contentSize.h;\n\n\tPosition gravityOffset = GetGravityOffset(contentSize, calculatedSize, gravity);\n\tr.x += gravityOffset.x;\n\tr.y += gravityOffset.y;\n\n\tSDL_SetTextureColorMod(texture, textColor.r, textColor.g, textColor.b);\n\n\tdrawTexture(&r, texture, renderer);\n}\n\nvoid Label::OnLayoutChange()\n{\n\tif (size.w == SIZE_FILL_PARENT || size.h == SIZE_FILL_PARENT)\n\t\tRenderText(UINT_MAX);\n}\n\nView* Label::Copy()\n{\n\tLabel* view = new Label();\n\n\tCopyBase(view);\n\tview->SetText(text);\n\tview->SetTextSize(textSize);\n\tview->SetTextColor(textColor);\n\tview->SetFont(font);\n\n\treturn view;\n}\n\nstring Label::GetText()\n{\n\treturn text;\n}\n\nvoid Label::SetText(string text)\n{\n\tthis->text = text;\n\n\tif (IsInitialized())\n\t{\n\t\tRenderText(UINT_MAX);\n\n\t\tif (size.w == SIZE_WRAP_CONTENT || size.h == SIZE_WRAP_CONTENT)\n\t\t{\n\t\t\tView* parent = GetParentView();\n\t\t\tif (parent != NULL)\n\t\t\t\tparent->RecalculateLayout();\n\t\t}\n\t}\n}\n\nint Label::GetTextSize()\n{\n\treturn textSize;\n}\n\nvoid Label::SetTextSize(int textSize)\n{\n\tthis->textSize = textSize;\n}\n\nColor Label::GetTextColor()\n{\n\treturn textColor;\n}\n\nvoid Label::SetTextColor(Color textColor)\n{\n\tthis->textColor = textColor;\n}\n\nstring Label::GetFont()\n{\n\treturn font;\n}\n\nvoid Label::SetFont(string font)\n{\n\tthis->font = font;\n}\n\nbool Label::SetProperty(string name, string value)\n{\n\tbool propertyHandled = View::SetProperty(name, value);\n\n\tif (propertyHandled)\n\t\treturn true;\n\n\tif (name == \"text\")\n\t{\n\t\tSetText(value);\n\t\treturn true;\n\t}\n\telse if (name == \"textSize\")\n\t{\n\t\ttextSize = atoi(value.c_str());\n\n\t\tif (textSize <= 0)\n\t\t\tthrow runtime_error(\"invalid textSize value\");\n\n\t\treturn true;\n\t}\n\telse if (name == \"textColor\")\n\t{\n\t\tif (value.length() != 7 || value[0] != '#')\n\t\t\tthrow runtime_error(\"invalid textColor value\");\n\n\t\tistringstream(value.substr(1, 2)) >> std::hex >> textColor.r;\n\t\tistringstream(value.substr(3, 2)) >> std::hex >> textColor.g;\n\t\tistringstream(value.substr(5, 2)) >> std::hex >> textColor.b;\n\n\t\treturn true;\n\t}\n\telse if (name == \"font\")\n\t{\n\t\tfont = value;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid Label::FillData(map<string, string>& data)\n{\n\ttext = FindAndReplace(text, data);\n\n\tif (IsInitialized())\n\t{\n\t\tRenderText(UINT_MAX);\n\t\tRecalculateLayout();\n\t}\n}\n<commit_msg>Use general function to parse color in Label<commit_after>\/*\nCopyright 2016 Andreas Bjerkeholt\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"Label.h\"\n#include <SDL.h>\n#include \"..\/graphics_utils.h\"\n#include <sstream>\n#include <limits.h>\n#include \"..\/ScreenSystem\/Screen.h\"\n\nusing namespace std;\n\nLabel::Label()\n{\n\ttexture = NULL;\n\ttext = \"\";\n\ttextSize = 12;\n\ttextColor = Color(0xff, 0xff, 0xff, 0xff);\n\tfont = \"semibold\";\n\tttfFont = NULL;\n}\n\nLabel::~Label()\n{\n\tif (texture != NULL)\n\t\tSDL_DestroyTexture(texture);\n}\n\nbool Label::OnInitialize()\n{\n\tttfFont = context->GetResourceManager()->GetTTFFont(font, textSize);\n\n\tif (ttfFont == NULL)\n\t\treturn false;\n\n\tif (!RenderText(UINT_MAX))\n\t\treturn false;\n\n\treturn true;\n}\n\nbool Label::RenderText(Uint32 textAreaWidth)\n{\n\tif (ttfFont == NULL)\n\t\treturn false;\n\n\tif (texture != NULL)\n\t\tSDL_DestroyTexture(texture);\n\n\ttexture = NULL;\n\n\tSDL_Color color;\n\tcolor.r = 0xff;\n\tcolor.g = 0xff;\n\tcolor.b = 0xff;\n\tcolor.a = 0xff;\n\tSDL_Surface* tempSurface = TTF_RenderText_Blended_Wrapped(ttfFont, text.c_str(), color, textAreaWidth);\n\tif (tempSurface == NULL)\n\t\treturn false;\n\n\tSDL_Surface* clippedSurface = NULL;\n\n\tint areaWidth = size.w;\n\tif (size.w == SIZE_FILL_PARENT)\n\t\tareaWidth = calculatedSize.w;\n\telse if (size.w == SIZE_WRAP_CONTENT)\n\t\tareaWidth = tempSurface->w;\n\n\tif (areaWidth > 0 && tempSurface->w > areaWidth)\n\t{\n\t\tSDL_Rect r;\n\t\tr.x = 0;\n\t\tr.y = 0;\n\t\tr.w = areaWidth;\n\t\tr.h = tempSurface->h;\n\t\tclippedSurface = ClipSurface(tempSurface, &r);\n\n\t\tSDL_FreeSurface(tempSurface);\n\n\t\t\/\/ Apply alpha fadeout at end if text doesn't fit completely\n\t\tFadeOutSurface(clippedSurface, 16);\n\t}\n\telse\n\t{\n\t\tclippedSurface = tempSurface;\n\t}\n\n\tif (clippedSurface == NULL)\n\t\treturn false;\n\n\ttexture = SDL_CreateTextureFromSurface(context->GetRenderer(), clippedSurface);\n\tSDL_FreeSurface(clippedSurface);\n\tif (texture == NULL)\n\t\treturn false;\n\n\tSDL_QueryTexture(texture, NULL, NULL, &contentSize.w, &contentSize.h);\n\n\treturn true;\n}\n\nvoid Label::OnDraw(SDL_Renderer* renderer, Position offset)\n{\n\tif (texture == NULL)\n\t\treturn;\n\n\tSDL_Rect r;\n\tr.x = absolutePosition.x + offset.x;\n\tr.y = absolutePosition.y + offset.y;\n\tr.w = contentSize.w;\n\tr.h = contentSize.h;\n\n\tPosition gravityOffset = GetGravityOffset(contentSize, calculatedSize, gravity);\n\tr.x += gravityOffset.x;\n\tr.y += gravityOffset.y;\n\n\tSDL_SetTextureColorMod(texture, textColor.r, textColor.g, textColor.b);\n\n\tdrawTexture(&r, texture, renderer);\n}\n\nvoid Label::OnLayoutChange()\n{\n\tif (size.w == SIZE_FILL_PARENT || size.h == SIZE_FILL_PARENT)\n\t\tRenderText(UINT_MAX);\n}\n\nView* Label::Copy()\n{\n\tLabel* view = new Label();\n\n\tCopyBase(view);\n\tview->SetText(text);\n\tview->SetTextSize(textSize);\n\tview->SetTextColor(textColor);\n\tview->SetFont(font);\n\n\treturn view;\n}\n\nstring Label::GetText()\n{\n\treturn text;\n}\n\nvoid Label::SetText(string text)\n{\n\tthis->text = text;\n\n\tif (IsInitialized())\n\t{\n\t\tRenderText(UINT_MAX);\n\n\t\tif (size.w == SIZE_WRAP_CONTENT || size.h == SIZE_WRAP_CONTENT)\n\t\t{\n\t\t\tView* parent = GetParentView();\n\t\t\tif (parent != NULL)\n\t\t\t\tparent->RecalculateLayout();\n\t\t}\n\t}\n}\n\nint Label::GetTextSize()\n{\n\treturn textSize;\n}\n\nvoid Label::SetTextSize(int textSize)\n{\n\tthis->textSize = textSize;\n}\n\nColor Label::GetTextColor()\n{\n\treturn textColor;\n}\n\nvoid Label::SetTextColor(Color textColor)\n{\n\tthis->textColor = textColor;\n}\n\nstring Label::GetFont()\n{\n\treturn font;\n}\n\nvoid Label::SetFont(string font)\n{\n\tthis->font = font;\n}\n\nbool Label::SetProperty(string name, string value)\n{\n\tbool propertyHandled = View::SetProperty(name, value);\n\n\tif (propertyHandled)\n\t\treturn true;\n\n\tif (name == \"text\")\n\t{\n\t\tSetText(value);\n\t\treturn true;\n\t}\n\telse if (name == \"textSize\")\n\t{\n\t\ttextSize = atoi(value.c_str());\n\n\t\tif (textSize <= 0)\n\t\t\tthrow runtime_error(\"invalid textSize value\");\n\n\t\treturn true;\n\t}\n\telse if (name == \"textColor\")\n\t{\n\t\tthis->textColor = ParseColor(value);\n\t\treturn true;\n\t}\n\telse if (name == \"font\")\n\t{\n\t\tfont = value;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid Label::FillData(map<string, string>& data)\n{\n\ttext = FindAndReplace(text, data);\n\n\tif (IsInitialized())\n\t{\n\t\tRenderText(UINT_MAX);\n\t\tRecalculateLayout();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <mlfe\/core.h>\n#include <mlfe\/operators.h>\n\nusing namespace mlfe;\nnamespace fn = functional;\n\nTEST(unary_op, negative){\n using T = float;\n auto var = fn::create_variable({2, 2});\n auto result = fn::negative(var);\n var.mutable_data<T>()[0] = -1.35;\n var.mutable_data<T>()[1] = 357.5;\n var.mutable_data<T>()[2] = -3.5;\n var.mutable_data<T>()[3] = 3.15;\n result.eval();\n EXPECT_EQ(result.data<T>()[0], -var.data<T>()[0]);\n EXPECT_EQ(result.data<T>()[1], -var.data<T>()[1]);\n EXPECT_EQ(result.data<T>()[2], -var.data<T>()[2]);\n EXPECT_EQ(result.data<T>()[3], -var.data<T>()[3]);\n}\n\nTEST(unary_op, sigmoid){\n using T = float;\n auto var = fn::create_variable({2, 2});\n auto result = fn::sigmoid(var);\n var.mutable_data<T>()[0] = 0;\n var.mutable_data<T>()[1] = -0.5;\n var.mutable_data<T>()[2] = 0.5;\n var.mutable_data<T>()[3] = 1;\n result.eval();\n EXPECT_EQ(result.data<T>()[0], 0.5);\n\n EXPECT_LE(result.data<T>()[1], 0.3775 + 1e-4);\n EXPECT_GE(result.data<T>()[1], 0.3775 - 1e-4);\n\n EXPECT_LE(result.data<T>()[2], 0.6225 + 1e-4);\n EXPECT_GE(result.data<T>()[2], 0.6225 - 1e-4);\n\n EXPECT_LE(result.data<T>()[3], 0.7311 + 1e-4);\n EXPECT_GE(result.data<T>()[3], 0.7311 - 1e-4);\n}\n\nTEST(unary_op, relu){\n using T = float;\n auto var = fn::create_variable({2, 2});\n auto result = fn::relu(var);\n var.mutable_data<T>()[0] = -1.35;\n var.mutable_data<T>()[1] = 357.5;\n var.mutable_data<T>()[2] = -3.5;\n var.mutable_data<T>()[3] = 3.15;\n result.eval();\n EXPECT_EQ(result.data<T>()[0], 0);\n EXPECT_EQ(result.data<T>()[1], var.data<T>()[1]);\n EXPECT_EQ(result.data<T>()[2], 0);\n EXPECT_EQ(result.data<T>()[3], var.data<T>()[3]);\n}<commit_msg>add gradient unit test as below: grad of negative op. grad of sigmoid op. grad of relu op.<commit_after>#include <gtest\/gtest.h>\n#include <mlfe\/core.h>\n#include <mlfe\/operators.h>\n#include <mlfe\/utils\/gradient_checker.h>\n#include <random>\n\nusing namespace mlfe;\nnamespace fn = functional;\n\nTEST(unary_op, negative){\n using T = float;\n auto var = fn::create_variable({2, 2});\n auto result = fn::negative(var);\n var.mutable_data<T>()[0] = -1.35;\n var.mutable_data<T>()[1] = 357.5;\n var.mutable_data<T>()[2] = -3.5;\n var.mutable_data<T>()[3] = 3.15;\n result.eval();\n EXPECT_EQ(result.data<T>()[0], -var.data<T>()[0]);\n EXPECT_EQ(result.data<T>()[1], -var.data<T>()[1]);\n EXPECT_EQ(result.data<T>()[2], -var.data<T>()[2]);\n EXPECT_EQ(result.data<T>()[3], -var.data<T>()[3]);\n}\n\nTEST(unary_op, negative_grad){\n using T = float;\n constexpr T grad_eps = 1e-4;\n constexpr T pass_eps = 1e-3;\n auto var = fn::create_variable({2, 2});\n auto result = fn::negative(var);\n auto analytical = std::vector<T>(var.size());\n std::mt19937 rng;\n std::uniform_real_distribution<T> dist(-1, 1);\n \n std::generate(var.begin<T>(), var.end<T>(), [&rng, &dist](){\n return dist(rng);\n });\n result.eval();\n result.backprop();\n std::copy(var.grad().begin<T>(), var.grad().end<T>(), analytical.begin());\n auto numerical = numerical_gradient(grad_eps, result, var);\n \n for(int n = 0; n < var.size(); ++n){\n auto diff = std::abs(analytical.data()[n] - numerical.data<T>()[n]);\n EXPECT_LE(diff, pass_eps);\n EXPECT_GE(diff, -pass_eps);\n }\n}\n\nTEST(unary_op, sigmoid){\n using T = float;\n auto var = fn::create_variable({2, 2});\n auto result = fn::sigmoid(var);\n var.mutable_data<T>()[0] = 0;\n var.mutable_data<T>()[1] = -0.5;\n var.mutable_data<T>()[2] = 0.5;\n var.mutable_data<T>()[3] = 1;\n result.eval();\n EXPECT_EQ(result.data<T>()[0], 0.5);\n\n EXPECT_LE(result.data<T>()[1], 0.3775 + 1e-4);\n EXPECT_GE(result.data<T>()[1], 0.3775 - 1e-4);\n\n EXPECT_LE(result.data<T>()[2], 0.6225 + 1e-4);\n EXPECT_GE(result.data<T>()[2], 0.6225 - 1e-4);\n\n EXPECT_LE(result.data<T>()[3], 0.7311 + 1e-4);\n EXPECT_GE(result.data<T>()[3], 0.7311 - 1e-4);\n}\n\nTEST(unary_op, sigmoid_grad){\n using T = float;\n constexpr T grad_eps = 1e-4;\n constexpr T pass_eps = 1e-3;\n auto var = fn::create_variable({2, 2});\n auto result = fn::sigmoid(var);\n auto analytical = std::vector<T>(var.size());\n std::mt19937 rng;\n std::uniform_real_distribution<T> dist(-1, 1);\n rng.seed(std::random_device()());\n \n std::generate(var.begin<T>(), var.end<T>(), [&rng, &dist](){\n return dist(rng);\n });\n result.eval();\n result.backprop();\n std::copy(var.grad().begin<T>(), var.grad().end<T>(), analytical.begin());\n auto numerical = numerical_gradient(grad_eps, result, var);\n \n for(int n = 0; n < var.size(); ++n){\n auto diff = std::abs(analytical.data()[n] - numerical.data<T>()[n]);\n EXPECT_LE(diff, pass_eps);\n EXPECT_GE(diff, -pass_eps);\n }\n}\n\nTEST(unary_op, relu){\n using T = float;\n auto var = fn::create_variable({2, 2});\n auto result = fn::relu(var);\n var.mutable_data<T>()[0] = -1.35;\n var.mutable_data<T>()[1] = 357.5;\n var.mutable_data<T>()[2] = -3.5;\n var.mutable_data<T>()[3] = 3.15;\n result.eval();\n EXPECT_EQ(result.data<T>()[0], 0);\n EXPECT_EQ(result.data<T>()[1], var.data<T>()[1]);\n EXPECT_EQ(result.data<T>()[2], 0);\n EXPECT_EQ(result.data<T>()[3], var.data<T>()[3]);\n}\n\nTEST(unary_op, relu_grad){\n using T = float;\n constexpr T grad_eps = 1e-4;\n constexpr T pass_eps = 1e-3;\n auto var = fn::create_variable({2, 2});\n auto result = fn::relu(var);\n auto analytical = std::vector<T>(var.size());\n std::mt19937 rng;\n std::uniform_real_distribution<T> dist(-1, 1);\n \n std::generate(var.begin<T>(), var.end<T>(), [&rng, &dist](){\n return dist(rng);\n });\n result.eval();\n result.backprop();\n std::copy(var.grad().begin<T>(), var.grad().end<T>(), analytical.begin());\n auto numerical = numerical_gradient(grad_eps, result, var);\n \n for(int n = 0; n < var.size(); ++n){\n auto diff = std::abs(analytical.data()[n] - numerical.data<T>()[n]);\n EXPECT_LE(diff, pass_eps);\n EXPECT_GE(diff, -pass_eps);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: VisAreaExport.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: dvo $ $Date: 2001-06-29 21:07:17 $\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 _COM_SUN_STAR_AWT_RECTANGLE_HPP_\n#include <com\/sun\/star\/awt\/Rectangle.hpp>\n#endif\n\n#ifndef _XMLOFF_VISAREAEXPORT_HXX\n#include \"VisAreaExport.hxx\"\n#endif\n#ifndef _XMLOFF_XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include \"xmlnmspe.hxx\"\n#endif\n\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include \"nmspmap.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \"xmltoken.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include \"xmluconv.hxx\"\n#endif\n\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n\nusing namespace ::xmloff::token;\n\n\nXMLVisAreaExport::XMLVisAreaExport(SvXMLExport& rExport, const sal_Char *pName,\n const Rectangle& aRect, const MapUnit aMapUnit)\n{\n SvXMLUnitConverter& rUnitConv = rExport.GetMM100UnitConverter();\n\n \/\/ write VisArea Element and its Attributes\n rtl::OUStringBuffer sBuffer;\n rUnitConv.convertMeasure(sBuffer, aRect.getX(), aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_X, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.getY(), aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_Y, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.getWidth(), aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_WIDTH, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.getHeight(), aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_HEIGHT, sBuffer.makeStringAndClear());\n SvXMLElementExport aVisAreaElem(rExport, XML_NAMESPACE_OFFICE, pName, sal_True, sal_True);\n}\n\nXMLVisAreaExport::XMLVisAreaExport(SvXMLExport& rExport, const sal_Char *pName,\n const com::sun::star::awt::Rectangle& aRect, const sal_Int16 nMeasureUnit )\n{\n MapUnit aMapUnit = (MapUnit)nMeasureUnit;\n\n SvXMLUnitConverter& rUnitConv = rExport.GetMM100UnitConverter();\n\n \/\/ write VisArea Element and its Attributes\n rtl::OUStringBuffer sBuffer;\n rUnitConv.convertMeasure(sBuffer, aRect.X, aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_X, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.Y, aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_Y, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.Width, aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_WIDTH, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.Height, aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_HEIGHT, sBuffer.makeStringAndClear());\n SvXMLElementExport aVisAreaElem(rExport, XML_NAMESPACE_OFFICE, pName, sal_True, sal_True);\n}\n\nXMLVisAreaExport::~XMLVisAreaExport()\n{\n}\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.636); FILE MERGED 2005\/09\/05 14:39:16 rt 1.3.636.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: VisAreaExport.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 14:30:46 $\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 _COM_SUN_STAR_AWT_RECTANGLE_HPP_\n#include <com\/sun\/star\/awt\/Rectangle.hpp>\n#endif\n\n#ifndef _XMLOFF_VISAREAEXPORT_HXX\n#include \"VisAreaExport.hxx\"\n#endif\n#ifndef _XMLOFF_XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include \"xmlnmspe.hxx\"\n#endif\n\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include \"nmspmap.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \"xmltoken.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include \"xmluconv.hxx\"\n#endif\n\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n\nusing namespace ::xmloff::token;\n\n\nXMLVisAreaExport::XMLVisAreaExport(SvXMLExport& rExport, const sal_Char *pName,\n const Rectangle& aRect, const MapUnit aMapUnit)\n{\n SvXMLUnitConverter& rUnitConv = rExport.GetMM100UnitConverter();\n\n \/\/ write VisArea Element and its Attributes\n rtl::OUStringBuffer sBuffer;\n rUnitConv.convertMeasure(sBuffer, aRect.getX(), aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_X, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.getY(), aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_Y, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.getWidth(), aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_WIDTH, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.getHeight(), aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_HEIGHT, sBuffer.makeStringAndClear());\n SvXMLElementExport aVisAreaElem(rExport, XML_NAMESPACE_OFFICE, pName, sal_True, sal_True);\n}\n\nXMLVisAreaExport::XMLVisAreaExport(SvXMLExport& rExport, const sal_Char *pName,\n const com::sun::star::awt::Rectangle& aRect, const sal_Int16 nMeasureUnit )\n{\n MapUnit aMapUnit = (MapUnit)nMeasureUnit;\n\n SvXMLUnitConverter& rUnitConv = rExport.GetMM100UnitConverter();\n\n \/\/ write VisArea Element and its Attributes\n rtl::OUStringBuffer sBuffer;\n rUnitConv.convertMeasure(sBuffer, aRect.X, aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_X, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.Y, aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_Y, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.Width, aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_WIDTH, sBuffer.makeStringAndClear());\n rUnitConv.convertMeasure(sBuffer, aRect.Height, aMapUnit);\n rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_HEIGHT, sBuffer.makeStringAndClear());\n SvXMLElementExport aVisAreaElem(rExport, XML_NAMESPACE_OFFICE, pName, sal_True, sal_True);\n}\n\nXMLVisAreaExport::~XMLVisAreaExport()\n{\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"helpclass.h\"\n\nHelpClass::HelpClass()\n{\n}\n\nHelpClass::~HelpClass()\n{\n}\n\n<commit_msg>Added serialize and deserialize members to serialization object<commit_after>#include \"helpclass.h\"\n\nHelpClass::HelpClass()\n{\n}\n\nHelpClass::~HelpClass()\n{\n}\n\nvoid HelpClass::Serialize(const Serializator &s)\n{\n\t\n}\n\nNObject *HelpClass::Deserialize(const Serializator &s)\n{\n\t\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>button colour change success<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\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#include <wangle\/channel\/FileRegion.h>\n#include <folly\/io\/async\/test\/AsyncSocketTest.h>\n#include <folly\/portability\/GTest.h>\n\n#ifdef SPLICE_F_NONBLOCK\nusing namespace folly;\nusing namespace wangle;\nusing namespace testing;\n\nstruct FileRegionTest : public Test {\n FileRegionTest() {\n \/\/ Connect\n socket = AsyncSocket::newSocket(&evb);\n socket->connect(&ccb, server.getAddress(), 30);\n\n \/\/ Accept the connection\n acceptedSocket = server.acceptAsync(&evb);\n acceptedSocket->setReadCB(&rcb);\n\n \/\/ Create temp file\n char path[] = \"\/tmp\/AsyncSocketTest.WriteFile.XXXXXX\";\n fd = mkostemp(path, O_RDWR);\n EXPECT_TRUE(fd > 0);\n EXPECT_EQ(0, unlink(path));\n }\n\n ~FileRegionTest() override {\n \/\/ Close up shop\n close(fd);\n acceptedSocket->close();\n socket->close();\n }\n\n TestServer server;\n EventBase evb;\n std::shared_ptr<AsyncSocket> socket;\n std::shared_ptr<AsyncSocket> acceptedSocket;\n ConnCallback ccb;\n ReadCallback rcb;\n int fd;\n};\n\nTEST_F(FileRegionTest, Basic) {\n const size_t count = 1000000000; \/\/ 1 GB\n std::unique_ptr<uint8_t[]> zeroBuf = std::make_unique<uint8_t[]>(count);\n write(fd, zeroBuf.get(), count);\n\n FileRegion fileRegion(fd, 0, count);\n auto f = fileRegion.transferTo(socket);\n try {\n f.getVia(&evb);\n } catch (std::exception& e) {\n LOG(FATAL) << exceptionStr(e);\n }\n\n \/\/ Let the reads run to completion\n socket->shutdownWrite();\n evb.loopIgnoreKeepAlive();\n\n ASSERT_EQ(rcb.state, STATE_SUCCEEDED);\n\n size_t receivedBytes = 0;\n for (auto& buf : rcb.buffers) {\n receivedBytes += buf.length;\n ASSERT_EQ(memcmp(buf.buffer, zeroBuf.get(), buf.length), 0);\n }\n ASSERT_EQ(receivedBytes, count);\n}\n\nTEST_F(FileRegionTest, Repeated) {\n const size_t count = 1000000;\n std::unique_ptr<uint8_t[]> zeroBuf = std::make_unique<uint8_t[]>(count);\n write(fd, zeroBuf.get(), count);\n\n int sendCount = 1000;\n\n FileRegion fileRegion(fd, 0, count);\n std::vector<Future<Unit>> fs;\n for (int i = 0; i < sendCount; i++) {\n fs.push_back(fileRegion.transferTo(socket));\n }\n auto f = collectSemiFuture(fs).via(&evb);\n ASSERT_NO_THROW(f.getVia(&evb));\n\n \/\/ Let the reads run to completion\n socket->shutdownWrite();\n evb.loopIgnoreKeepAlive();\n\n ASSERT_EQ(rcb.state, STATE_SUCCEEDED);\n\n size_t receivedBytes = 0;\n for (auto& buf : rcb.buffers) {\n receivedBytes += buf.length;\n }\n ASSERT_EQ(receivedBytes, sendCount*count);\n}\n#endif\n<commit_msg>Rename collectXSemiFuture to collectX<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\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#include <wangle\/channel\/FileRegion.h>\n#include <folly\/io\/async\/test\/AsyncSocketTest.h>\n#include <folly\/portability\/GTest.h>\n\n#ifdef SPLICE_F_NONBLOCK\nusing namespace folly;\nusing namespace wangle;\nusing namespace testing;\n\nstruct FileRegionTest : public Test {\n FileRegionTest() {\n \/\/ Connect\n socket = AsyncSocket::newSocket(&evb);\n socket->connect(&ccb, server.getAddress(), 30);\n\n \/\/ Accept the connection\n acceptedSocket = server.acceptAsync(&evb);\n acceptedSocket->setReadCB(&rcb);\n\n \/\/ Create temp file\n char path[] = \"\/tmp\/AsyncSocketTest.WriteFile.XXXXXX\";\n fd = mkostemp(path, O_RDWR);\n EXPECT_TRUE(fd > 0);\n EXPECT_EQ(0, unlink(path));\n }\n\n ~FileRegionTest() override {\n \/\/ Close up shop\n close(fd);\n acceptedSocket->close();\n socket->close();\n }\n\n TestServer server;\n EventBase evb;\n std::shared_ptr<AsyncSocket> socket;\n std::shared_ptr<AsyncSocket> acceptedSocket;\n ConnCallback ccb;\n ReadCallback rcb;\n int fd;\n};\n\nTEST_F(FileRegionTest, Basic) {\n const size_t count = 1000000000; \/\/ 1 GB\n std::unique_ptr<uint8_t[]> zeroBuf = std::make_unique<uint8_t[]>(count);\n write(fd, zeroBuf.get(), count);\n\n FileRegion fileRegion(fd, 0, count);\n auto f = fileRegion.transferTo(socket);\n try {\n f.getVia(&evb);\n } catch (std::exception& e) {\n LOG(FATAL) << exceptionStr(e);\n }\n\n \/\/ Let the reads run to completion\n socket->shutdownWrite();\n evb.loopIgnoreKeepAlive();\n\n ASSERT_EQ(rcb.state, STATE_SUCCEEDED);\n\n size_t receivedBytes = 0;\n for (auto& buf : rcb.buffers) {\n receivedBytes += buf.length;\n ASSERT_EQ(memcmp(buf.buffer, zeroBuf.get(), buf.length), 0);\n }\n ASSERT_EQ(receivedBytes, count);\n}\n\nTEST_F(FileRegionTest, Repeated) {\n const size_t count = 1000000;\n std::unique_ptr<uint8_t[]> zeroBuf = std::make_unique<uint8_t[]>(count);\n write(fd, zeroBuf.get(), count);\n\n int sendCount = 1000;\n\n FileRegion fileRegion(fd, 0, count);\n std::vector<Future<Unit>> fs;\n for (int i = 0; i < sendCount; i++) {\n fs.push_back(fileRegion.transferTo(socket));\n }\n auto f = collect(fs).via(&evb);\n ASSERT_NO_THROW(f.getVia(&evb));\n\n \/\/ Let the reads run to completion\n socket->shutdownWrite();\n evb.loopIgnoreKeepAlive();\n\n ASSERT_EQ(rcb.state, STATE_SUCCEEDED);\n\n size_t receivedBytes = 0;\n for (auto& buf : rcb.buffers) {\n receivedBytes += buf.length;\n }\n ASSERT_EQ(receivedBytes, sendCount*count);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"sodiumpp.h\"\n#include <string>\n#include <iostream>\nusing namespace sodiumpp;\n\nint main(int argc, const char ** argv) {\n secret_key sk_client;\n secret_key sk_server;\n\n \/\/ Create a nonce type that has a 32-bit sequential counter and constant random bytes for the remaining bytes\n typedef nonce<crypto_box_NONCEBYTES-4, 4> nonce32;\n\n boxer<nonce32> client_boxer(sk_server.pk, sk_client);\n unboxer<nonce32> server_unboxer(sk_client.pk, sk_server, client_boxer.nonce_constant());\n\n std::string boxed = client_boxer.box(\"Hello, world!\\n\");\n std::string unboxed = server_unboxer.unbox(boxed);\n std::cout << unboxed;\n\n boxed = client_boxer.box(\"From sodiumpp!\\n\");\n unboxed = server_unboxer.unbox(boxed);\n std::cout << unboxed;\n return 0;\n}\n<commit_msg>Added copyright header to example<commit_after>\/\/ example.cpp\n\/\/\n\/\/ Copyright (c) 2014, Ruben De Visscher\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 met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n\/\/ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY 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\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"sodiumpp.h\"\n#include <string>\n#include <iostream>\nusing namespace sodiumpp;\n\nint main(int argc, const char ** argv) {\n secret_key sk_client;\n secret_key sk_server;\n\n \/\/ Create a nonce type that has a 32-bit sequential counter and constant random bytes for the remaining bytes\n typedef nonce<crypto_box_NONCEBYTES-4, 4> nonce32;\n\n boxer<nonce32> client_boxer(sk_server.pk, sk_client);\n unboxer<nonce32> server_unboxer(sk_client.pk, sk_server, client_boxer.nonce_constant());\n\n std::string boxed = client_boxer.box(\"Hello, world!\\n\");\n std::string unboxed = server_unboxer.unbox(boxed);\n std::cout << unboxed;\n\n boxed = client_boxer.box(\"From sodiumpp!\\n\");\n unboxed = server_unboxer.unbox(boxed);\n std::cout << unboxed;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * File: example.cpp\n * Author: vlad\n *\n * Created on December 12, 2013, 10:38 PM\n *\/\n\n#include \"qpp.h\"\n#include <set>\n\n\/\/#include \"matlab.h\" \/\/ support for MATLAB\n\n\/\/ TODO: testing\n\/\/ TODO: write documentation\n\/\/ TODO: more robust exception parameter checking\n\/\/ TODO: change loops to column major order, better OpenMP implementation\n\/\/ TODO: Gates::applyCTRL without need for fully specifying CTRL matrix,\n\t\t \/\/ should be faster than apply(...CTRL...)\n\nusing namespace std;\n\nusing namespace qpp;\nusing namespace qpp::types;\nusing namespace qpp::ct;\n\ncplx pow3(const cplx& z)\n{\n\treturn std::pow(z, 3);\n}\n\nint main()\n{\n\tcout << \"Starting qpp...\" << endl;\n\n\t\/\/ output format\n\t\/\/cout << std::scientific;\n\tcout << std::fixed; \/\/ use fixed format for nice formatting\n\tcout << std::setprecision(4); \/\/ only for fixed or scientific modes\n\n\/\/\t\/*\n\t \/\/ TESTING\n\n\t \/\/ testing channel and Gates::apply\n\t cout << endl << \"Testing channel(...) and Gates::apply(...).\" << endl;\n\t cmat rho = randrho(16);\n\t cmat K = kron(gt.Id2, gt.X, gt.Y, gt.Z);\n\t vector<std::size_t> p = randperm(4); \/\/ permutation\n\t cout << \"Permutation: \";\n\t displn(p, \", \");\n\t vector<std::size_t> invp = invperm(p); \/\/ inverse permutation\n\t cout << \"Inverse permutation: \";\n\t displn(invp, \", \");\n\t cmat r1 = channel(rho, { K }, p, { 2, 2, 2, 2 });\n\t cmat r2 = syspermute(channel(syspermute(rho, p, { 2, 2, 2, 2 }), { K }, { 0,\n\t 1, 2, 3 }, { 2, 2, 2, 2 }), invp, { 2, 2, 2, 2 });\n\t cout << norm(r1 - r2) << endl << endl;\n\n\t r1 = gt.apply(rho, K, p, { 2, 2, 2, 2 });\n\t r2 = syspermute(\n\t gt.apply(syspermute(rho, p, { 2, 2, 2, 2 }), K, { 0, 1, 2, 3 }, { 2,\n\t 2, 2, 2 }), invp, { 2, 2, 2, 2 });\n\t cout << norm(r1 - r2) << endl << endl;\n\n\t displn(channel(prj(mket( { 0, 1 })), { gt.CNOTab }, { 1, 0 }, { 2, 2 }));\n\t cout << endl;\n\t displn(gt.apply(mket( { 0, 0 }), gt.CNOTab, { 0, 1 }, { 2, 2 }));\n\n\t \/\/ quantum teleportation\n\t cout << endl << \"Qudit teleportation.\" << endl;\n\t ket psi = randket(2); \/\/ a random state;\n\t cout << \"|psi><psi|:\" << endl;\n\t displn(prj(psi));\n\t cmat telecircuit = expandout(gt.H, { 0 }, { 2, 2, 2 })\n\t * gt.CTRL(gt.X, { 0 }, { 1 }, 3);\n\t ket psiin = kron(psi, st.b00); \/\/ input state\n\t ket psiout = telecircuit * psiin; \/\/ output state before measurement\n\t \/\/ measure Alice's qubits, measurement results are 1 0\n\t psiout = kron(prj(st.z1), prj(st.z0), gt.Id2) * psiout;\n\t \/\/ apply correction\n\t psiout = expandout(powm(gt.Z, 1) * powm(gt.X, 0), { 2 }, { 2, 2, 2 })\n\t * psiout;\n\t \/\/ not necessary to normalize, prj() takes care of it below\n\t cmat rhoout = ptrace(prj(psiout), { 0, 1 }, { 2, 2, 2 });\n\t cout << endl << \"Teleported state:\" << endl;\n\t displn(rhoout);\n\t cout << \"Difference in norm: \" << norm(prj(psi) - rhoout) << endl;\n\n\t \/\/ qudit measurements\n\t cout << endl << \"Qudit measurements.\" << endl;\n\t cout << \"Initially in state |0><0|.\" << endl;\n\t ket zd0(3);\n\t zd0 << 1, 0, 0;\n\t Qudit q(prj(zd0));\n\t cout << \"Measuring Z operator non-destructively. Results:\" << endl;\n\t cout << q.measure() << endl;\n\t cout << q.measure() << endl;\n\t cout << q.measure() << endl;\n\t cout << \"Measuring X operator non-destructively. Results:\" << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t \/\/ von Neumann projective measurement\n\t cout << \"Measuring X operator destructively (collapse). Results:\" << endl;\n\t cout << q.measure(gt.Xd(3), true) << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t cout << \"Finally measuring Z operator destructively. Results:\" << endl;\n\t cout << q.measure(true) << endl;\n\t cout << q.measure() << endl;\n\t cout << q.measure() << endl;\n\t cout << \"Final state of qudit:\" << endl;\n\t displn(q.getRho());\n\n\t \/\/ Bell state generator\n\t cout << endl << \"Bell state generator: \" << endl;\n\t cmat circuit;\n\t circuit = gt.CTRL(gt.X, { 0 }, { 1 }, 2) * expandout(gt.H, 0, { 2, 2 });\n\t cmat input = kron(st.z0, st.z0);\n\t cmat output = circuit * input;\n\t cout << \"Circuit matrix representation: \" << endl;\n\t displn(circuit);\n\t cout << endl << \"Output (|Bell_0> state) of the circuit on |00>: \" << endl;\n\t displn(output);\n\n\t \/\/ 3-qubit repetion code\n\t cout << endl << \"3-qubit repetition code: \" << endl;\n\t cmat rep;\n\t rep = gt.CTRL(gt.X, { 0 }, { 2 }, 3) * gt.CTRL(gt.X, { 0 }, { 1 }, 3);\n\t input = kron(st.z1, st.z0, st.z0);\n\t output = rep * input;\n\t cout << \"Circuit acting on |000> produces |111>. Check: \" << endl;\n\t displn(output);\n\n\t \/\/ functor test\n\t cout << endl << \"Functor z^3 acting on:\" << endl;\n\t cmat a(2, 2);\n\t a << 1, 2, 3, 4;\n\t displn(a);\n\t cout << \"Result (with lambda):\" << endl;\n\t \/\/ functor z^3 componentwise, specify OutputScalar and Derived for lambdas\n\t displn(cwise<cplx, cmat>(a, [](const cplx& z)->cplx\n\t {\treturn z*z*z;}));\n\t cout << \"Result (with proper function):\" << endl;\n\t \/\/ automatic type deduction for proper functions\n\t displn(cwise(a, &pow3));\n\n\t \/\/ Gram-Schmidt\n\t cout << endl << \"Gram-Schmidt on matrix:\" << endl;\n\t cmat A(3, 3);\n\t A << 1, 1, 0, 0, 2, 0, 0, 0, 0;\n\t displn(A);\n\t cmat Ags = grams(A);\n\t cout << endl << \"Result:\" << endl;\n\t displn(Ags);\n\t cout << endl << \"Projector is:\" << endl;\n\t displn(Ags * adjoint(Ags));\n\n\t \/\/ spectral decomposition test\n\t cout << endl << \"Spectral decomposition tests.\" << endl;\n\t std::size_t D = 4;\n\t cmat rH = randH(D);\n\t dmat evalsH = hevals(rH);\n\t cmat evectsH = hevects(rH);\n\t cmat spec = cmat::Zero(D, D);\n\t for (std::size_t i = 0; i < D; i++)\n\t spec += evalsH(i) * prj((cmat) evectsH.col(i));\n\t cout << \"Original matrix: \" << endl;\n\t displn(rH);\n\t cout << endl << \"Reconstructed from spectral decomposition: \" << endl;\n\t displn(spec);\n\t cout << \"Difference in norm: \" << norm(spec - rH) << endl;\n\n\t \/\/ channel tests\n\t cout << endl << \"Channel tests.\" << endl;\n\t std::size_t nk = 10, d = 2; \/\/ nk Kraus on d-dimensional system\n\t cout << \"Generating a random channel with \" << nk\n\t << \" Kraus operators on a \" << d << \" dimensional space...\" << endl;\n\t std::vector<cmat> Ks = randkraus(nk, d);\n\n\t cmat rho_in = randrho(d); \/\/ input state\n\t cmat rho_out = channel(rho_in, Ks); \/\/ output state\n\n\t cout << \"Computing its Choi matrix...\" << endl;\n\t cmat choim = choi(Ks);\n\t cout << \"Choi matrix:\" << endl;\n\t displn(choim);\n\t cout << endl << \"The eigenvalues of the Choi matrix are: \" << endl;\n\t displn(transpose(hevals(choim)));\n\t cout << endl << \"Their sum is: \" << sum(hevals(choim)) << endl;\n\t std::vector<cmat> Kperps = choi2kraus(choim);\n\t cout << endl << \"The Kraus rank of the channel is: \" << Kperps.size()\n\t << endl;\n\t cmat rho_out1 = channel(rho_in, Kperps);\n\t cout << endl << \"Difference in norm on output states: \"\n\t << norm(rho_out1 - rho_out) << endl;\n\t cout << endl << \"Superoperator matrix:\" << endl;\n\t cmat smat = super(Ks);\n\t displn(smat);\n\t cout << endl << \"The eigenvalues of the superoperator matrix are: \" << endl;\n\t cmat evalsupop = evals(smat);\n\t displn(transpose(evalsupop));\n\t cout << endl << \"Their absolute values are: \" << endl;\n\t for (std::size_t i = 0; i < (std::size_t) evalsupop.size(); i++)\n\t cout << std::abs((cplx) evalsupop(i)) << \" \";\n\t cout << endl << endl << \"Diference in norm for superoperator action: \";\n\t cmat rho_out2 = transpose(\n\t (cmat) reshape(smat * reshape(transpose(rho_in), d * d, 1), d, d));\n\t cout << norm(rho_out - rho_out2) << endl;\n\n\t \/\/ statistics tests\n\t cout << endl << \"Statistics tests.\" << endl;\n\t std::vector<cplx> ampl = { 1. + 1_i, 1. - 1_i };\n\t cmat va(1, 4);\n\t va << 0.1, 1, 1. + 1_i, 1. + 2_i;\n\t DiscreteDistributionAbsSquare dc(va);\n\t cout << \"The probabilities are: \";\n\t displn(dc.probabilities(), \", \", \"{\", \"}\");\n\n\t \/\/ \t\/\/ TIMING tests\n\t cout << endl << \"Timing tests...\" << endl;\n\t std::size_t n = 12; \/\/ number of qubits\n\t std::size_t N = std::pow(2, n);\n\t vector<std::size_t> dims(n, 2); \/\/ local dimensions\n\t cout << \"n = \" << n << \" qubits, matrix size \" << N << \" x \" << N << \".\"\n\t << endl;\n\n\t \/\/ matrix initialization\n\t cout << endl << \"Matrix initialization timing.\" << endl;\n\t \/\/ start the timer, automatic tic() in the constructor\n\t Timer t, total;\n\t cmat randcmat = cmat::Random(N, N);\n\t t.toc(); \/\/ read the time\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ lazy matrix product\n\t cout << endl << \"Lazy matrix product timing.\" << endl;\n\t t.tic();\n\t auto lazyprod = randcmat * randcmat; \/\/ lazyprod has type GenMatProduct\n\t t.toc(); \/\/ read the time\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ ptrace1 timing\n\t cout << endl << \"ptrace1 timing.\" << endl;\n\t t.tic(); \/\/ reset the chronometer\n\t \/\/ trace away half of the qubits\n\t ptrace1(randcmat,\n\t { (std::size_t) std::sqrt(N), (std::size_t) std::sqrt(N) });\n\t t.toc(); \/\/ read the time\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ ptrace2 timing\n\t cout << endl << \"ptrace2 timing.\" << endl;\n\t t.tic(); \/\/ reset the chronometer\n\t \/\/ trace away half of the qubits\n\t ptrace2(randcmat,\n\t { (std::size_t) std::sqrt(N), (std::size_t) std::sqrt(N) });\n\t t.toc(); \/\/ read the time\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ ptrace\n\t cout << endl << \"ptrace timing.\" << endl;\n\t vector<std::size_t> subsys_ptrace = { 0 };\n\t cout << \"Subsytem(s): \";\n\t displn(subsys_ptrace, \", \");\n\t t.tic();\n\t ptrace(randcmat, subsys_ptrace, dims);\n\t t.toc();\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ ptranspose\n\t cout << endl << \"ptranspose timing.\" << endl;\n\t vector<std::size_t> subsys_ptranspose; \/\/ partially transpose n-1 subsystems\n\t for (std::size_t i = 0; i < n - 1; i++)\n\t subsys_ptranspose.push_back(i);\n\t cout << \"Subsytem(s): \";\n\t displn(subsys_ptranspose, \", \");\n\t t.tic();\n\t ptranspose(randcmat, subsys_ptranspose, dims);\n\t t.toc();\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ syspermute\n\t cout << endl << \"syspermute timing.\" << endl;\n\t vector<std::size_t> perm; \/\/ left-shift all subsystems by 1\n\t for (std::size_t i = 0; i < n; i++)\n\t perm.push_back((i + 1) % n);\n\t cout << \"Subsytem(s): \";\n\t displn(perm, \", \");\n\t t.tic();\n\t syspermute(randcmat, perm, dims);\n\t t.toc();\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/\t \/\/ matrix product\n\t \/\/\t cout << endl << \"Matrix product timing.\" << endl;\n\t \/\/\t t.tic(); \/\/ reset the chronometer\n\t \/\/\t cmat prodmat = randcmat * randcmat; \/\/ explicit cmat now\n\t \/\/\t t.toc(); \/\/ read the time\n\t \/\/\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ END TIMING\n\t total.toc(); \/\/ read the total running time\n\t cout << endl << \"Total time: \" << total.seconds() << \" seconds.\";\n\/\/\t *\/\n\n\tcout << endl << \"Exiting qpp...\" << endl;\n}\n<commit_msg>applyCTRL<commit_after>\/*\n * File: example.cpp\n * Author: vlad\n *\n * Created on December 12, 2013, 10:38 PM\n *\/\n\n#include \"qpp.h\"\n#include <set>\n\n\/\/#include \"matlab.h\" \/\/ support for MATLAB\n\n\/\/ TODO: testing\n\/\/ TODO: write documentation\n\/\/ TODO: more robust exception parameter checking\n\/\/ TODO: change loops to column major order, better OpenMP implementation\n\/\/ TODO: Gates::applyCTRL without need for fully specifying CTRL matrix,\n\t\t \/\/ should be faster than apply(...CTRL...)\n\/\/ TODO: parallelize everything!\n\nusing namespace std;\n\nusing namespace qpp;\nusing namespace qpp::types;\nusing namespace qpp::ct;\n\ncplx pow3(const cplx& z)\n{\n\treturn std::pow(z, 3);\n}\n\nint main()\n{\n\tcout << \"Starting qpp...\" << endl;\n\n\t\/\/ output format\n\t\/\/cout << std::scientific;\n\tcout << std::fixed; \/\/ use fixed format for nice formatting\n\tcout << std::setprecision(4); \/\/ only for fixed or scientific modes\n\n\/\/\t\/*\n\t \/\/ TESTING\n\n\t \/\/ testing channel and Gates::apply\n\t cout << endl << \"Testing channel(...) and Gates::apply(...).\" << endl;\n\t cmat rho = randrho(16);\n\t cmat K = kron(gt.Id2, gt.X, gt.Y, gt.Z);\n\t vector<std::size_t> p = randperm(4); \/\/ permutation\n\t cout << \"Permutation: \";\n\t displn(p, \", \");\n\t vector<std::size_t> invp = invperm(p); \/\/ inverse permutation\n\t cout << \"Inverse permutation: \";\n\t displn(invp, \", \");\n\t cmat r1 = channel(rho, { K }, p, { 2, 2, 2, 2 });\n\t cmat r2 = syspermute(channel(syspermute(rho, p, { 2, 2, 2, 2 }), { K }, { 0,\n\t 1, 2, 3 }, { 2, 2, 2, 2 }), invp, { 2, 2, 2, 2 });\n\t cout << norm(r1 - r2) << endl << endl;\n\n\t r1 = gt.apply(rho, K, p, { 2, 2, 2, 2 });\n\t r2 = syspermute(\n\t gt.apply(syspermute(rho, p, { 2, 2, 2, 2 }), K, { 0, 1, 2, 3 }, { 2,\n\t 2, 2, 2 }), invp, { 2, 2, 2, 2 });\n\t cout << norm(r1 - r2) << endl << endl;\n\n\t displn(channel(prj(mket( { 0, 1 })), { gt.CNOTab }, { 1, 0 }, { 2, 2 }));\n\t cout << endl;\n\t displn(gt.apply(mket( { 0, 0 }), gt.CNOTab, { 0, 1 }, { 2, 2 }));\n\n\t \/\/ quantum teleportation\n\t cout << endl << \"Qudit teleportation.\" << endl;\n\t ket psi = randket(2); \/\/ a random state;\n\t cout << \"|psi><psi|:\" << endl;\n\t displn(prj(psi));\n\t cmat telecircuit = expandout(gt.H, { 0 }, { 2, 2, 2 })\n\t * gt.CTRL(gt.X, { 0 }, { 1 }, 3);\n\t ket psiin = kron(psi, st.b00); \/\/ input state\n\t ket psiout = telecircuit * psiin; \/\/ output state before measurement\n\t \/\/ measure Alice's qubits, measurement results are 1 0\n\t psiout = kron(prj(st.z1), prj(st.z0), gt.Id2) * psiout;\n\t \/\/ apply correction\n\t psiout = expandout(powm(gt.Z, 1) * powm(gt.X, 0), { 2 }, { 2, 2, 2 })\n\t * psiout;\n\t \/\/ not necessary to normalize, prj() takes care of it below\n\t cmat rhoout = ptrace(prj(psiout), { 0, 1 }, { 2, 2, 2 });\n\t cout << endl << \"Teleported state:\" << endl;\n\t displn(rhoout);\n\t cout << \"Difference in norm: \" << norm(prj(psi) - rhoout) << endl;\n\n\t \/\/ qudit measurements\n\t cout << endl << \"Qudit measurements.\" << endl;\n\t cout << \"Initially in state |0><0|.\" << endl;\n\t ket zd0(3);\n\t zd0 << 1, 0, 0;\n\t Qudit q(prj(zd0));\n\t cout << \"Measuring Z operator non-destructively. Results:\" << endl;\n\t cout << q.measure() << endl;\n\t cout << q.measure() << endl;\n\t cout << q.measure() << endl;\n\t cout << \"Measuring X operator non-destructively. Results:\" << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t \/\/ von Neumann projective measurement\n\t cout << \"Measuring X operator destructively (collapse). Results:\" << endl;\n\t cout << q.measure(gt.Xd(3), true) << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t cout << q.measure(gt.Xd(3)) << endl;\n\t cout << \"Finally measuring Z operator destructively. Results:\" << endl;\n\t cout << q.measure(true) << endl;\n\t cout << q.measure() << endl;\n\t cout << q.measure() << endl;\n\t cout << \"Final state of qudit:\" << endl;\n\t displn(q.getRho());\n\n\t \/\/ Bell state generator\n\t cout << endl << \"Bell state generator: \" << endl;\n\t cmat circuit;\n\t circuit = gt.CTRL(gt.X, { 0 }, { 1 }, 2) * expandout(gt.H, 0, { 2, 2 });\n\t cmat input = kron(st.z0, st.z0);\n\t cmat output = circuit * input;\n\t cout << \"Circuit matrix representation: \" << endl;\n\t displn(circuit);\n\t cout << endl << \"Output (|Bell_0> state) of the circuit on |00>: \" << endl;\n\t displn(output);\n\n\t \/\/ 3-qubit repetion code\n\t cout << endl << \"3-qubit repetition code: \" << endl;\n\t cmat rep;\n\t rep = gt.CTRL(gt.X, { 0 }, { 2 }, 3) * gt.CTRL(gt.X, { 0 }, { 1 }, 3);\n\t input = kron(st.z1, st.z0, st.z0);\n\t output = rep * input;\n\t cout << \"Circuit acting on |000> produces |111>. Check: \" << endl;\n\t displn(output);\n\n\t \/\/ functor test\n\t cout << endl << \"Functor z^3 acting on:\" << endl;\n\t cmat a(2, 2);\n\t a << 1, 2, 3, 4;\n\t displn(a);\n\t cout << \"Result (with lambda):\" << endl;\n\t \/\/ functor z^3 componentwise, specify OutputScalar and Derived for lambdas\n\t displn(cwise<cplx, cmat>(a, [](const cplx& z)->cplx\n\t {\treturn z*z*z;}));\n\t cout << \"Result (with proper function):\" << endl;\n\t \/\/ automatic type deduction for proper functions\n\t displn(cwise(a, &pow3));\n\n\t \/\/ Gram-Schmidt\n\t cout << endl << \"Gram-Schmidt on matrix:\" << endl;\n\t cmat A(3, 3);\n\t A << 1, 1, 0, 0, 2, 0, 0, 0, 0;\n\t displn(A);\n\t cmat Ags = grams(A);\n\t cout << endl << \"Result:\" << endl;\n\t displn(Ags);\n\t cout << endl << \"Projector is:\" << endl;\n\t displn(Ags * adjoint(Ags));\n\n\t \/\/ spectral decomposition test\n\t cout << endl << \"Spectral decomposition tests.\" << endl;\n\t std::size_t D = 4;\n\t cmat rH = randH(D);\n\t dmat evalsH = hevals(rH);\n\t cmat evectsH = hevects(rH);\n\t cmat spec = cmat::Zero(D, D);\n\t for (std::size_t i = 0; i < D; i++)\n\t spec += evalsH(i) * prj((cmat) evectsH.col(i));\n\t cout << \"Original matrix: \" << endl;\n\t displn(rH);\n\t cout << endl << \"Reconstructed from spectral decomposition: \" << endl;\n\t displn(spec);\n\t cout << \"Difference in norm: \" << norm(spec - rH) << endl;\n\n\t \/\/ channel tests\n\t cout << endl << \"Channel tests.\" << endl;\n\t std::size_t nk = 10, d = 2; \/\/ nk Kraus on d-dimensional system\n\t cout << \"Generating a random channel with \" << nk\n\t << \" Kraus operators on a \" << d << \" dimensional space...\" << endl;\n\t std::vector<cmat> Ks = randkraus(nk, d);\n\n\t cmat rho_in = randrho(d); \/\/ input state\n\t cmat rho_out = channel(rho_in, Ks); \/\/ output state\n\n\t cout << \"Computing its Choi matrix...\" << endl;\n\t cmat choim = choi(Ks);\n\t cout << \"Choi matrix:\" << endl;\n\t displn(choim);\n\t cout << endl << \"The eigenvalues of the Choi matrix are: \" << endl;\n\t displn(transpose(hevals(choim)));\n\t cout << endl << \"Their sum is: \" << sum(hevals(choim)) << endl;\n\t std::vector<cmat> Kperps = choi2kraus(choim);\n\t cout << endl << \"The Kraus rank of the channel is: \" << Kperps.size()\n\t << endl;\n\t cmat rho_out1 = channel(rho_in, Kperps);\n\t cout << endl << \"Difference in norm on output states: \"\n\t << norm(rho_out1 - rho_out) << endl;\n\t cout << endl << \"Superoperator matrix:\" << endl;\n\t cmat smat = super(Ks);\n\t displn(smat);\n\t cout << endl << \"The eigenvalues of the superoperator matrix are: \" << endl;\n\t cmat evalsupop = evals(smat);\n\t displn(transpose(evalsupop));\n\t cout << endl << \"Their absolute values are: \" << endl;\n\t for (std::size_t i = 0; i < (std::size_t) evalsupop.size(); i++)\n\t cout << std::abs((cplx) evalsupop(i)) << \" \";\n\t cout << endl << endl << \"Diference in norm for superoperator action: \";\n\t cmat rho_out2 = transpose(\n\t (cmat) reshape(smat * reshape(transpose(rho_in), d * d, 1), d, d));\n\t cout << norm(rho_out - rho_out2) << endl;\n\n\t \/\/ statistics tests\n\t cout << endl << \"Statistics tests.\" << endl;\n\t std::vector<cplx> ampl = { 1. + 1_i, 1. - 1_i };\n\t cmat va(1, 4);\n\t va << 0.1, 1, 1. + 1_i, 1. + 2_i;\n\t DiscreteDistributionAbsSquare dc(va);\n\t cout << \"The probabilities are: \";\n\t displn(dc.probabilities(), \", \", \"{\", \"}\");\n\n\t \/\/ \t\/\/ TIMING tests\n\t cout << endl << \"Timing tests...\" << endl;\n\t std::size_t n = 12; \/\/ number of qubits\n\t std::size_t N = std::pow(2, n);\n\t vector<std::size_t> dims(n, 2); \/\/ local dimensions\n\t cout << \"n = \" << n << \" qubits, matrix size \" << N << \" x \" << N << \".\"\n\t << endl;\n\n\t \/\/ matrix initialization\n\t cout << endl << \"Matrix initialization timing.\" << endl;\n\t \/\/ start the timer, automatic tic() in the constructor\n\t Timer t, total;\n\t cmat randcmat = cmat::Random(N, N);\n\t t.toc(); \/\/ read the time\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ lazy matrix product\n\t cout << endl << \"Lazy matrix product timing.\" << endl;\n\t t.tic();\n\t auto lazyprod = randcmat * randcmat; \/\/ lazyprod has type GenMatProduct\n\t t.toc(); \/\/ read the time\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ ptrace1 timing\n\t cout << endl << \"ptrace1 timing.\" << endl;\n\t t.tic(); \/\/ reset the chronometer\n\t \/\/ trace away half of the qubits\n\t ptrace1(randcmat,\n\t { (std::size_t) std::sqrt(N), (std::size_t) std::sqrt(N) });\n\t t.toc(); \/\/ read the time\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ ptrace2 timing\n\t cout << endl << \"ptrace2 timing.\" << endl;\n\t t.tic(); \/\/ reset the chronometer\n\t \/\/ trace away half of the qubits\n\t ptrace2(randcmat,\n\t { (std::size_t) std::sqrt(N), (std::size_t) std::sqrt(N) });\n\t t.toc(); \/\/ read the time\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ ptrace\n\t cout << endl << \"ptrace timing.\" << endl;\n\t vector<std::size_t> subsys_ptrace = { 0 };\n\t cout << \"Subsytem(s): \";\n\t displn(subsys_ptrace, \", \");\n\t t.tic();\n\t ptrace(randcmat, subsys_ptrace, dims);\n\t t.toc();\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ ptranspose\n\t cout << endl << \"ptranspose timing.\" << endl;\n\t vector<std::size_t> subsys_ptranspose; \/\/ partially transpose n-1 subsystems\n\t for (std::size_t i = 0; i < n - 1; i++)\n\t subsys_ptranspose.push_back(i);\n\t cout << \"Subsytem(s): \";\n\t displn(subsys_ptranspose, \", \");\n\t t.tic();\n\t ptranspose(randcmat, subsys_ptranspose, dims);\n\t t.toc();\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ syspermute\n\t cout << endl << \"syspermute timing.\" << endl;\n\t vector<std::size_t> perm; \/\/ left-shift all subsystems by 1\n\t for (std::size_t i = 0; i < n; i++)\n\t perm.push_back((i + 1) % n);\n\t cout << \"Subsytem(s): \";\n\t displn(perm, \", \");\n\t t.tic();\n\t syspermute(randcmat, perm, dims);\n\t t.toc();\n\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/\t \/\/ matrix product\n\t \/\/\t cout << endl << \"Matrix product timing.\" << endl;\n\t \/\/\t t.tic(); \/\/ reset the chronometer\n\t \/\/\t cmat prodmat = randcmat * randcmat; \/\/ explicit cmat now\n\t \/\/\t t.toc(); \/\/ read the time\n\t \/\/\t cout << \"Took \" << t << \" seconds.\" << endl;\n\n\t \/\/ END TIMING\n\t total.toc(); \/\/ read the total running time\n\t cout << endl << \"Total time: \" << total.seconds() << \" seconds.\";\n\/\/\t *\/\n\n\tcout << endl << \"Exiting qpp...\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Pointers to pointers are very useful for tracking a node.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Remove trace buffer flush at end of shutdown path<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"sp\/sp.h\"\n#include \"sp\/system\/FileSystem.h\"\n\n#include \"sp\/system\/Memory.h\"\n\n#include <unistd.h>\n#include <sys\/stat.h>\n\nnamespace sp {\n\n\tbool FileSystem::FileExists(const String& path)\n\t{\n\t\treturn access(path.c_str(), F_OK) == 0;\n\t}\n\n\tint64 FileSystem::GetFileSize(const String& path)\n\t{\n\t\treturn 0;\n\t}\n\n\tbool FileSystem::ReadFile(const String& path, void* buffer, int64 size)\n\t{\n\t\treturn false;\n\t}\n\n\tbyte* FileSystem::ReadFile(const String& path)\n\t{\n\t\treturn nullptr;\n\t}\n\n\tString FileSystem::ReadTextFile(const String& path)\n\t{\n\t\treturn String();\n\t}\n\n\tbool FileSystem::WriteFile(const String& path, byte* buffer)\n\t{\n\t\treturn false;\n\t}\n\n\tbool FileSystem::WriteTextFile(const String& path, const String& text)\n\t{\n\t\treturn false;\n\t}\n}\n<commit_msg>Implemented PosixFileSystem<commit_after>#include \"sp\/sp.h\"\n#include \"sp\/system\/FileSystem.h\"\n\n#include \"sp\/system\/Memory.h\"\n\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\nnamespace sp {\n\n\tbool FileSystem::FileExists(const String& path)\n\t{\n\t\treturn access(path.c_str(), F_OK) == 0;\n\t}\n\n\tint64 FileSystem::GetFileSize(const String& path)\n\t{\n\t\tstruct stat st;\n\t\tif (stat(path.c_str(), &st) == -1) return -1;\n\t\treturn (int64) st.st_size;\n\t}\n\n\tbool ReadFileInternal(const String& path, void* buffer, int64 size) {\n\t\tint fd = open(path.c_str(), O_RDONLY);\n\t\tif (fd == -1) return false;\n\t\tif (size < 0) size = FileSystem::GetFileSize(path);\n\t\tssize_t result = read(fd, buffer, (size_t) size);\n\t\tclose(fd);\n\t\treturn result == size;\n\t}\n\n\tbool FileSystem::ReadFile(const String& path, void* buffer, int64 size)\n\t{\n\t\treturn ReadFileInternal(path, buffer, size);\n\t}\n\n\tbyte* FileSystem::ReadFile(const String& path)\n\t{\n\t\tint64 size = FileSystem::GetFileSize(path);\n\t\tif (size == -1) return nullptr;\n\t\tbyte* buffer = spnew byte[size];\n\t\treturn ReadFileInternal(path, buffer, size) ? buffer : nullptr;\n\t}\n\n\tString FileSystem::ReadTextFile(const String& path)\n\t{\n\t\tint64 size = FileSystem::GetFileSize(path);\n\t\tString result(size, 0);\n\t\tif (ReadFileInternal(path, &result[0], size))\n\t\t{\n\t\t\t\/\/ Strip carriage returns\n\t\t\tresult.erase(std::remove(result.begin(), result.end(), '\\r'), result.end());\n\t\t\treturn result;\n\t\t}\n\t\treturn String();\n\t}\n\n\tbool FileSystem::WriteFile(const String& path, byte* buffer)\n\t{\n\t\treturn false;\n\t}\n\n\tbool FileSystem::WriteTextFile(const String& path, const String& text)\n\t{\n\t\treturn false;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS pchfix02 (1.3.92); FILE MERGED 2006\/09\/01 17:43:11 kaib 1.3.92.1: #i68856# Added header markers and pch files<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"SoundComponent.h\"\n#include \"..\/..\/Sound.h\"\n\nnamespace thomas\n{\n\tnamespace object\n\t{\n\t\tnamespace component\n\t\t{\n\t\t\tSoundComponent::SoundComponent()\n\t\t\t{\n\t\t\t\tm_name == \"\";\n\t\t\t\tm_volume = 1;\n\t\t\t\tm_looping = true;\n\t\t\t}\n\n\t\t\tSoundComponent::~SoundComponent()\n\t\t\t{\n\n\t\t\t}\n\n\t\t\tbool SoundComponent::SetClip(std::string name)\n\t\t\t{\n\t\t\t\tm_instance = Sound::CreateInstance(name);\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->SetVolume(m_volume);\n\t\t\t\t\tm_name = name;\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\n\t\t\tstd::string SoundComponent::GetName()\n\t\t\t{\n\t\t\t\treturn m_name;\n\t\t\t}\n\n\t\t\tbool SoundComponent::SetVolume(float volume)\n\t\t\t{\n\t\t\t\tif (volume > 5)\n\t\t\t\t\treturn false;\n\t\t\t\tm_volume = volume;\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->SetVolume(volume*Sound::GetMusicVolume());\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tfloat SoundComponent::GetVolume()\n\t\t\t{\n\t\t\t\treturn m_volume;\n\t\t\t}\n\n\t\t\tbool SoundComponent::Play()\n\t\t\t{\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->Play(m_looping);\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\t\n\t\t\t}\n\n\t\t\tbool SoundComponent::PlayOneShot(std::string name, float volume)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t\treturn Sound::Play(name, volume);\n\t\t\t}\n\n\t\t\tvoid SoundComponent::Pause()\n\t\t\t{\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->Pause();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid SoundComponent::Resume()\n\t\t\t{\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->Resume();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid SoundComponent::SetLooping(bool loop)\n\t\t\t{\n\t\t\t\tm_looping = loop;\n\t\t\t}\n\n\t\t\tbool SoundComponent::IsLooping()\n\t\t\t{\n\t\t\t\treturn m_looping;\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Added temporary fix for loading sound waves and wavebanks into the sound engine<commit_after>#include \"SoundComponent.h\"\n#include \"..\/..\/Sound.h\"\n\nnamespace thomas\n{\n\tnamespace object\n\t{\n\t\tnamespace component\n\t\t{\n\t\t\tSoundComponent::SoundComponent()\n\t\t\t{\n\t\t\t\tm_name == \"\";\n\t\t\t\tm_volume = 1;\n\t\t\t\tm_looping = true;\n\t\t\t}\n\n\t\t\tSoundComponent::~SoundComponent()\n\t\t\t{\n\n\t\t\t}\n\n\t\t\tbool SoundComponent::SetClip(std::string name)\n\t\t\t{\n\t\t\t\tm_instance = Sound::CreateInstance(name);\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->SetVolume(m_volume);\n\t\t\t\t\tm_name = name;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSound::LoadWaveBank(name);\n\t\t\t\t\tSound::LoadWave(name);\n\n\t\t\t\t\tm_instance = Sound::CreateInstance(name);\n\t\t\t\t\tm_instance->SetVolume(m_volume);\n\t\t\t\t\tm_name = name;\n\t\t\t\t\treturn true;\n\t\t\t\t\t\/\/return false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::string SoundComponent::GetName()\n\t\t\t{\n\t\t\t\treturn m_name;\n\t\t\t}\n\n\t\t\tbool SoundComponent::SetVolume(float volume)\n\t\t\t{\n\t\t\t\tif (volume > 5)\n\t\t\t\t\treturn false;\n\t\t\t\tm_volume = volume;\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->SetVolume(volume*Sound::GetMusicVolume());\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tfloat SoundComponent::GetVolume()\n\t\t\t{\n\t\t\t\treturn m_volume;\n\t\t\t}\n\n\t\t\tbool SoundComponent::Play()\n\t\t\t{\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->Play(m_looping);\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\t\n\t\t\t}\n\n\t\t\tbool SoundComponent::PlayOneShot(std::string name, float volume)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t\treturn Sound::Play(name, volume);\n\t\t\t}\n\n\t\t\tvoid SoundComponent::Pause()\n\t\t\t{\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->Pause();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid SoundComponent::Resume()\n\t\t\t{\n\t\t\t\tif (m_instance)\n\t\t\t\t{\n\t\t\t\t\tm_instance->Resume();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid SoundComponent::SetLooping(bool loop)\n\t\t\t{\n\t\t\t\tm_looping = loop;\n\t\t\t}\n\n\t\t\tbool SoundComponent::IsLooping()\n\t\t\t{\n\t\t\t\treturn m_looping;\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkOptImageToImageMetricsTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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 \"itkImage.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkRigid2DTransform.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkLinearInterpolateImageFunction.h\"\n\n#include \"itkMeanSquaresImageToImageMetric.h\"\n#include \"itkMattesMutualInformationImageToImageMetric.h\"\n#include \"itkMutualInformationImageToImageMetric.h\"\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\n#include \"itkOptImageToImageMetricsTest.h\"\n\nint itkOptImageToImageMetricsTest(int , char* argv[])\n{\n#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS\n std::cout << \"OPTIMIZED ON\" << std::endl;\n#else\n std::cout << \"OPTIMIZED OFF\" << std::endl; \n#endif\n\n std::cout << \"Default number of threads : \" \n << itk::MultiThreader::GetGlobalDefaultNumberOfThreads() \n << std::endl;\n\n typedef itk::Image< unsigned int > FixedImageType;\n typedef itk::Image< unsigned int > MovingImageType;\n\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n itk::TranslationLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n itk::RigidLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n itk::AffineLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS\n std::cout << \"OPTIMIZED ON\" << std::endl;\n#else\n std::cout << \"OPTIMIZED OFF\" << std::endl; \n#endif\n\n \/\/ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \/\/ DO EXPERIMENTS WITH NUMBER OF THREADS SET TO 1!!!\n \/\/ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n std::cout << \"Running tests with : \" << std::endl;\n std::cout << \"\\t itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1); \" << std::endl;\n std::cout << \"\\t itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1); \" << std::endl;\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n std::cout << std::endl;\n\n itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1);\n itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);\n\n itk::TranslationLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n itk::RigidLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n itk::AffineLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS\n std::cout << \"OPTIMIZED ON\" << std::endl;\n#else\n std::cout << \"OPTIMIZED OFF\" << std::endl; \n#endif\n\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: Clarifying that the test is first running the experiments with the default number of threads, and then they are run again by forcing the number of threads to 1. Previous comments were misleading.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkOptImageToImageMetricsTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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 \"itkImage.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkRigid2DTransform.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkLinearInterpolateImageFunction.h\"\n\n#include \"itkMeanSquaresImageToImageMetric.h\"\n#include \"itkMattesMutualInformationImageToImageMetric.h\"\n#include \"itkMutualInformationImageToImageMetric.h\"\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\n#include \"itkOptImageToImageMetricsTest.h\"\n\nint itkOptImageToImageMetricsTest(int , char* argv[])\n{\n#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS\n std::cout << \"OPTIMIZED ON\" << std::endl;\n#else\n std::cout << \"OPTIMIZED OFF\" << std::endl; \n#endif\n\n std::cout << \"Default number of threads : \" \n << itk::MultiThreader::GetGlobalDefaultNumberOfThreads() \n << std::endl;\n\n typedef itk::Image< unsigned int > FixedImageType;\n typedef itk::Image< unsigned int > MovingImageType;\n\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n\n \/\/ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \/\/ First run the experiments with the default number of threads,\n \/\/ as set from the command line arguments, the system defaults \n \/\/ or the ITK environment variable:\n \/\/ ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS\n \/\/ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n std::cout << \"Now Running tests with : \" << std::endl;\n std::cout << \"\\t Global Default Number of Threads \" << itk::MultiThreader::GetGlobalDefaultNumberOfThreads() << std::endl;\n std::cout << \"\\t Global Maximum Number of Threads \" << itk::MultiThreader::GetGlobalMaximumNumberOfThreads() << std::endl;\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n std::cout << std::endl;\n\n\n itk::TranslationLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n itk::RigidLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n itk::AffineLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS\n std::cout << \"OPTIMIZED ON\" << std::endl;\n#else\n std::cout << \"OPTIMIZED OFF\" << std::endl; \n#endif\n\n \/\/ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \/\/ Then, do experiments with number of threads set to 1!!!!!!!!!!\n \/\/ In this way we can compare the results with N threads versus 1.\n \/\/ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n std::cout << \"Now Running tests with : \" << std::endl;\n std::cout << \"\\t itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1); \" << std::endl;\n std::cout << \"\\t itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1); \" << std::endl;\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n std::cout << std::endl;\n\n itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1);\n itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);\n\n itk::TranslationLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n itk::RigidLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n itk::AffineLinearTest( fixedImageReader.GetPointer(), \n movingImageReader.GetPointer() );\n\n#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS\n std::cout << \"OPTIMIZED ON\" << std::endl;\n#else\n std::cout << \"OPTIMIZED OFF\" << std::endl; \n#endif\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- llvm\/CodeGen\/MachineBasicBlock.cpp ----------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Collect the sequence of machine instructions for a basic block.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/MachineBasicBlock.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/Target\/MRegisterInfo.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Support\/LeakDetector.h\"\n#include <algorithm>\nusing namespace llvm;\n\nMachineBasicBlock::~MachineBasicBlock() {\n LeakDetector::removeGarbageObject(this);\n}\n\nstd::ostream& llvm::operator<<(std::ostream &OS, const MachineBasicBlock &MBB) {\n MBB.print(OS);\n return OS;\n}\n\n\/\/ MBBs start out as #-1. When a MBB is added to a MachineFunction, it\n\/\/ gets the next available unique MBB number. If it is removed from a\n\/\/ MachineFunction, it goes back to being #-1.\nvoid ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) {\n assert(N->Parent == 0 && \"machine instruction already in a basic block\");\n N->Parent = Parent;\n N->Number = Parent->addToMBBNumbering(N);\n LeakDetector::removeGarbageObject(N);\n}\n\nvoid ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) {\n assert(N->Parent != 0 && \"machine instruction not in a basic block\");\n N->Parent->removeFromMBBNumbering(N->Number);\n N->Number = -1;\n N->Parent = 0;\n LeakDetector::addGarbageObject(N);\n}\n\n\nMachineInstr* ilist_traits<MachineInstr>::createSentinel() {\n MachineInstr* dummy = new MachineInstr();\n LeakDetector::removeGarbageObject(dummy);\n return dummy;\n}\n\nvoid ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) {\n assert(N->parent == 0 && \"machine instruction already in a basic block\");\n N->parent = parent;\n LeakDetector::removeGarbageObject(N);\n}\n\nvoid ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) {\n assert(N->parent != 0 && \"machine instruction not in a basic block\");\n N->parent = 0;\n LeakDetector::addGarbageObject(N);\n}\n\nvoid ilist_traits<MachineInstr>::transferNodesFromList(\n iplist<MachineInstr, ilist_traits<MachineInstr> >& fromList,\n ilist_iterator<MachineInstr> first,\n ilist_iterator<MachineInstr> last) {\n if (parent != fromList.parent)\n for (; first != last; ++first)\n first->parent = parent;\n}\n\nMachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {\n const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo();\n iterator I = end();\n while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode()));\n if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I;\n return I;\n}\n\nvoid MachineBasicBlock::dump() const {\n print(*cerr.stream());\n}\n\nstatic inline void OutputReg(std::ostream &os, unsigned RegNo,\n const MRegisterInfo *MRI = 0) {\n if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {\n if (MRI)\n os << \" %\" << MRI->get(RegNo).Name;\n else\n os << \" %mreg(\" << RegNo << \")\";\n } else\n os << \" %reg\" << RegNo;\n}\n\nvoid MachineBasicBlock::print(std::ostream &OS) const {\n const MachineFunction *MF = getParent();\n if(!MF) {\n OS << \"Can't print out MachineBasicBlock because parent MachineFunction\"\n << \" is null\\n\";\n return;\n }\n\n const BasicBlock *LBB = getBasicBlock();\n OS << \"\\n\";\n if (LBB) OS << LBB->getName();\n OS << \" (\" << (const void*)this\n << \", LLVM BB @\" << (const void*) LBB << \", ID#\" << getNumber()<< \"):\\n\";\n\n const MRegisterInfo *MRI = MF->getTarget().getRegisterInfo(); \n if (livein_begin() != livein_end()) {\n OS << \"Live Ins:\";\n for (const_livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)\n OutputReg(OS, *I, MRI);\n OS << \"\\n\";\n }\n \/\/ Print the preds of this block according to the CFG.\n if (!pred_empty()) {\n OS << \" Predecessors according to CFG:\";\n for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)\n OS << \" \" << *PI;\n OS << \"\\n\";\n }\n \n for (const_iterator I = begin(); I != end(); ++I) {\n OS << \"\\t\";\n I->print(OS, &getParent()->getTarget());\n }\n\n \/\/ Print the successors of this block according to the CFG.\n if (!succ_empty()) {\n OS << \" Successors according to CFG:\";\n for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)\n OS << \" \" << *SI;\n OS << \"\\n\";\n }\n}\n\nvoid MachineBasicBlock::removeLiveIn(unsigned Reg) {\n livein_iterator I = std::find(livein_begin(), livein_end(), Reg);\n assert(I != livein_end() && \"Not a live in!\");\n LiveIns.erase(I);\n}\n\nvoid MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {\n MachineFunction::BasicBlockListType &BBList =getParent()->getBasicBlockList();\n getParent()->getBasicBlockList().splice(NewAfter, BBList, this);\n}\n\nvoid MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {\n MachineFunction::BasicBlockListType &BBList =getParent()->getBasicBlockList();\n MachineFunction::iterator BBI = NewBefore;\n getParent()->getBasicBlockList().splice(++BBI, BBList, this);\n}\n\n\nvoid MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {\n Successors.push_back(succ);\n succ->addPredecessor(this);\n}\n\nvoid MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {\n succ->removePredecessor(this);\n succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);\n assert(I != Successors.end() && \"Not a current successor!\");\n Successors.erase(I);\n}\n\nvoid MachineBasicBlock::removeSuccessor(succ_iterator I) {\n assert(I != Successors.end() && \"Not a current successor!\");\n (*I)->removePredecessor(this);\n Successors.erase(I);\n}\n\nvoid MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {\n Predecessors.push_back(pred);\n}\n\nvoid MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {\n std::vector<MachineBasicBlock *>::iterator I =\n std::find(Predecessors.begin(), Predecessors.end(), pred);\n assert(I != Predecessors.end() && \"Pred is not a predecessor of this block!\");\n Predecessors.erase(I);\n}\n<commit_msg>Print preds \/ succs BB numbers.<commit_after>\/\/===-- llvm\/CodeGen\/MachineBasicBlock.cpp ----------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Collect the sequence of machine instructions for a basic block.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/MachineBasicBlock.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/Target\/MRegisterInfo.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Support\/LeakDetector.h\"\n#include <algorithm>\nusing namespace llvm;\n\nMachineBasicBlock::~MachineBasicBlock() {\n LeakDetector::removeGarbageObject(this);\n}\n\nstd::ostream& llvm::operator<<(std::ostream &OS, const MachineBasicBlock &MBB) {\n MBB.print(OS);\n return OS;\n}\n\n\/\/ MBBs start out as #-1. When a MBB is added to a MachineFunction, it\n\/\/ gets the next available unique MBB number. If it is removed from a\n\/\/ MachineFunction, it goes back to being #-1.\nvoid ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) {\n assert(N->Parent == 0 && \"machine instruction already in a basic block\");\n N->Parent = Parent;\n N->Number = Parent->addToMBBNumbering(N);\n LeakDetector::removeGarbageObject(N);\n}\n\nvoid ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) {\n assert(N->Parent != 0 && \"machine instruction not in a basic block\");\n N->Parent->removeFromMBBNumbering(N->Number);\n N->Number = -1;\n N->Parent = 0;\n LeakDetector::addGarbageObject(N);\n}\n\n\nMachineInstr* ilist_traits<MachineInstr>::createSentinel() {\n MachineInstr* dummy = new MachineInstr();\n LeakDetector::removeGarbageObject(dummy);\n return dummy;\n}\n\nvoid ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) {\n assert(N->parent == 0 && \"machine instruction already in a basic block\");\n N->parent = parent;\n LeakDetector::removeGarbageObject(N);\n}\n\nvoid ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) {\n assert(N->parent != 0 && \"machine instruction not in a basic block\");\n N->parent = 0;\n LeakDetector::addGarbageObject(N);\n}\n\nvoid ilist_traits<MachineInstr>::transferNodesFromList(\n iplist<MachineInstr, ilist_traits<MachineInstr> >& fromList,\n ilist_iterator<MachineInstr> first,\n ilist_iterator<MachineInstr> last) {\n if (parent != fromList.parent)\n for (; first != last; ++first)\n first->parent = parent;\n}\n\nMachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {\n const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo();\n iterator I = end();\n while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode()));\n if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I;\n return I;\n}\n\nvoid MachineBasicBlock::dump() const {\n print(*cerr.stream());\n}\n\nstatic inline void OutputReg(std::ostream &os, unsigned RegNo,\n const MRegisterInfo *MRI = 0) {\n if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {\n if (MRI)\n os << \" %\" << MRI->get(RegNo).Name;\n else\n os << \" %mreg(\" << RegNo << \")\";\n } else\n os << \" %reg\" << RegNo;\n}\n\nvoid MachineBasicBlock::print(std::ostream &OS) const {\n const MachineFunction *MF = getParent();\n if(!MF) {\n OS << \"Can't print out MachineBasicBlock because parent MachineFunction\"\n << \" is null\\n\";\n return;\n }\n\n const BasicBlock *LBB = getBasicBlock();\n OS << \"\\n\";\n if (LBB) OS << LBB->getName();\n OS << \" (\" << (const void*)this\n << \", LLVM BB @\" << (const void*) LBB << \", ID#\" << getNumber()<< \"):\\n\";\n\n const MRegisterInfo *MRI = MF->getTarget().getRegisterInfo(); \n if (livein_begin() != livein_end()) {\n OS << \"Live Ins:\";\n for (const_livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)\n OutputReg(OS, *I, MRI);\n OS << \"\\n\";\n }\n \/\/ Print the preds of this block according to the CFG.\n if (!pred_empty()) {\n OS << \" Predecessors according to CFG:\";\n for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)\n OS << \" \" << *PI << \" (#\" << (*PI)->getNumber() << \")\";\n OS << \"\\n\";\n }\n \n for (const_iterator I = begin(); I != end(); ++I) {\n OS << \"\\t\";\n I->print(OS, &getParent()->getTarget());\n }\n\n \/\/ Print the successors of this block according to the CFG.\n if (!succ_empty()) {\n OS << \" Successors according to CFG:\";\n for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)\n OS << \" \" << *SI << \" (#\" << (*SI)->getNumber() << \")\";\n OS << \"\\n\";\n }\n}\n\nvoid MachineBasicBlock::removeLiveIn(unsigned Reg) {\n livein_iterator I = std::find(livein_begin(), livein_end(), Reg);\n assert(I != livein_end() && \"Not a live in!\");\n LiveIns.erase(I);\n}\n\nvoid MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {\n MachineFunction::BasicBlockListType &BBList =getParent()->getBasicBlockList();\n getParent()->getBasicBlockList().splice(NewAfter, BBList, this);\n}\n\nvoid MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {\n MachineFunction::BasicBlockListType &BBList =getParent()->getBasicBlockList();\n MachineFunction::iterator BBI = NewBefore;\n getParent()->getBasicBlockList().splice(++BBI, BBList, this);\n}\n\n\nvoid MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {\n Successors.push_back(succ);\n succ->addPredecessor(this);\n}\n\nvoid MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {\n succ->removePredecessor(this);\n succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);\n assert(I != Successors.end() && \"Not a current successor!\");\n Successors.erase(I);\n}\n\nvoid MachineBasicBlock::removeSuccessor(succ_iterator I) {\n assert(I != Successors.end() && \"Not a current successor!\");\n (*I)->removePredecessor(this);\n Successors.erase(I);\n}\n\nvoid MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {\n Predecessors.push_back(pred);\n}\n\nvoid MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {\n std::vector<MachineBasicBlock *>::iterator I =\n std::find(Predecessors.begin(), Predecessors.end(), pred);\n assert(I != Predecessors.end() && \"Pred is not a predecessor of this block!\");\n Predecessors.erase(I);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ThreadPlanRunToAddress.cpp ------------------------------*- C++ -*-===\/\/\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#include \"lldb\/Target\/ThreadPlanRunToAddress.h\"\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"lldb\/lldb-private-log.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Target\/Process.h\"\n#include \"lldb\/Target\/Thread.h\"\n#include \"lldb\/Target\/RegisterContext.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n\/\/----------------------------------------------------------------------\n\/\/ ThreadPlanRunToAddress: Continue plan\n\/\/----------------------------------------------------------------------\n\nThreadPlanRunToAddress::ThreadPlanRunToAddress\n(\n Thread &thread,\n Address &address,\n bool stop_others\n) :\n ThreadPlan (ThreadPlan::eKindRunToAddress, \"Run to address plan\", thread, eVoteNoOpinion, eVoteNoOpinion),\n m_stop_others (stop_others),\n m_addresses (),\n m_break_ids ()\n{\n m_addresses.push_back (address.GetLoadAddress(&m_thread.GetProcess().GetTarget()));\n SetInitialBreakpoints();\n}\n\nThreadPlanRunToAddress::ThreadPlanRunToAddress\n(\n Thread &thread,\n lldb::addr_t address,\n bool stop_others\n) :\n ThreadPlan (ThreadPlan::eKindRunToAddress, \"Run to address plan\", thread, eVoteNoOpinion, eVoteNoOpinion),\n m_stop_others (stop_others),\n m_addresses (),\n m_break_ids ()\n{\n m_addresses.push_back(address);\n SetInitialBreakpoints();\n}\n\nThreadPlanRunToAddress::ThreadPlanRunToAddress\n(\n Thread &thread,\n std::vector<lldb::addr_t> &addresses,\n bool stop_others\n) :\n ThreadPlan (ThreadPlan::eKindRunToAddress, \"Run to address plan\", thread, eVoteNoOpinion, eVoteNoOpinion),\n m_stop_others (stop_others),\n m_addresses (addresses),\n m_break_ids ()\n{\n SetInitialBreakpoints();\n}\n\nvoid\nThreadPlanRunToAddress::SetInitialBreakpoints ()\n{\n size_t num_addresses = m_addresses.size();\n m_break_ids.resize(num_addresses);\n \n for (size_t i = 0; i < num_addresses; i++)\n {\n Breakpoint *breakpoint;\n breakpoint = m_thread.GetProcess().GetTarget().CreateBreakpoint (m_addresses[i], true).get();\n if (breakpoint != NULL)\n {\n m_break_ids[i] = breakpoint->GetID();\n breakpoint->SetThreadID(m_thread.GetID());\n }\n }\n}\n\nThreadPlanRunToAddress::~ThreadPlanRunToAddress ()\n{\n size_t num_break_ids = m_break_ids.size();\n for (size_t i = 0; i < num_break_ids; i++)\n {\n m_thread.GetProcess().GetTarget().RemoveBreakpointByID (m_break_ids[i]);\n }\n}\n\nvoid\nThreadPlanRunToAddress::GetDescription (Stream *s, lldb::DescriptionLevel level)\n{\n size_t num_addresses = m_addresses.size();\n \n if (level == lldb::eDescriptionLevelBrief)\n {\n if (num_addresses == 0)\n {\n s->Printf (\"run to address with no addresses given.\");\n return;\n }\n else if (num_addresses == 1)\n s->Printf (\"run to address: \");\n else\n s->Printf (\"run to addresses: \");\n \n for (size_t i = 0; i < num_addresses; i++)\n {\n s->Address (m_addresses[i], sizeof (addr_t));\n s->Printf(\" \");\n }\n }\n else\n {\n if (num_addresses == 0)\n {\n s->Printf (\"run to address with no addresses given.\");\n return;\n }\n else if (num_addresses == 1)\n s->Printf (\"Run to address: \");\n else\n {\n s->Printf (\"Run to addresses: \");\n }\n \n for (size_t i = 0; i < num_addresses; i++)\n {\n if (num_addresses > 1)\n {\n s->Printf(\"\\n\");\n s->Indent();\n }\n \n s->Address(m_addresses[i], sizeof (addr_t));\n s->Printf (\" using breakpoint: %d - \", m_break_ids[i]);\n Breakpoint *breakpoint = m_thread.GetProcess().GetTarget().GetBreakpointByID (m_break_ids[i]).get();\n if (breakpoint)\n breakpoint->Dump (s);\n else\n s->Printf (\"but the breakpoint has been deleted.\");\n }\n }\n}\n\nbool\nThreadPlanRunToAddress::ValidatePlan (Stream *error)\n{\n \/\/ If we couldn't set the breakpoint for some reason, then this won't\n \/\/ work.\n bool all_bps_good = true;\n size_t num_break_ids = m_break_ids.size();\n \n for (size_t i = 0; i < num_break_ids; i++)\n {\n if (m_break_ids[i] == LLDB_INVALID_BREAK_ID)\n {\n all_bps_good = false;\n if (error)\n {\n error->Printf (\"Could not set breakpoint for address: \");\n error->Address (m_addresses[i], sizeof (addr_t));\n error->Printf (\"\\n\");\n }\n }\n }\n return all_bps_good;\n}\n\nbool\nThreadPlanRunToAddress::PlanExplainsStop ()\n{\n return AtOurAddress();\n}\n\nbool\nThreadPlanRunToAddress::ShouldStop (Event *event_ptr)\n{\n return false;\n}\n\nbool\nThreadPlanRunToAddress::StopOthers ()\n{\n return m_stop_others;\n}\n\nvoid\nThreadPlanRunToAddress::SetStopOthers (bool new_value)\n{\n m_stop_others = new_value;\n}\n\nStateType\nThreadPlanRunToAddress::GetPlanRunState ()\n{\n return eStateRunning;\n}\n\nbool\nThreadPlanRunToAddress::WillStop ()\n{\n return true;\n}\n\nbool\nThreadPlanRunToAddress::MischiefManaged ()\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n\n if (AtOurAddress())\n {\n \/\/ Remove the breakpoint\n size_t num_break_ids = m_break_ids.size();\n \n for (size_t i = 0; i < num_break_ids; i++)\n {\n if (m_break_ids[i] != LLDB_INVALID_BREAK_ID)\n {\n m_thread.GetProcess().GetTarget().RemoveBreakpointByID (m_break_ids[i]);\n m_break_ids[i] = LLDB_INVALID_BREAK_ID;\n }\n }\n if (log)\n log->Printf(\"Completed run to address plan.\");\n ThreadPlan::MischiefManaged ();\n return true;\n }\n else\n return false;\n}\n\nbool\nThreadPlanRunToAddress::AtOurAddress ()\n{\n lldb::addr_t current_address = m_thread.GetRegisterContext()->GetPC();\n bool found_it = false;\n for (size_t i = 0; i < m_addresses[i]; i++)\n {\n if (m_addresses[i] == current_address)\n {\n found_it = true;\n break;\n }\n }\n return found_it;\n}\n<commit_msg>Typo in looking up the stored address breakpoints, could cause us to look too far for breakpoints.<commit_after>\/\/===-- ThreadPlanRunToAddress.cpp ------------------------------*- C++ -*-===\/\/\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#include \"lldb\/Target\/ThreadPlanRunToAddress.h\"\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"lldb\/lldb-private-log.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Target\/Process.h\"\n#include \"lldb\/Target\/Thread.h\"\n#include \"lldb\/Target\/RegisterContext.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n\/\/----------------------------------------------------------------------\n\/\/ ThreadPlanRunToAddress: Continue plan\n\/\/----------------------------------------------------------------------\n\nThreadPlanRunToAddress::ThreadPlanRunToAddress\n(\n Thread &thread,\n Address &address,\n bool stop_others\n) :\n ThreadPlan (ThreadPlan::eKindRunToAddress, \"Run to address plan\", thread, eVoteNoOpinion, eVoteNoOpinion),\n m_stop_others (stop_others),\n m_addresses (),\n m_break_ids ()\n{\n m_addresses.push_back (address.GetLoadAddress(&m_thread.GetProcess().GetTarget()));\n SetInitialBreakpoints();\n}\n\nThreadPlanRunToAddress::ThreadPlanRunToAddress\n(\n Thread &thread,\n lldb::addr_t address,\n bool stop_others\n) :\n ThreadPlan (ThreadPlan::eKindRunToAddress, \"Run to address plan\", thread, eVoteNoOpinion, eVoteNoOpinion),\n m_stop_others (stop_others),\n m_addresses (),\n m_break_ids ()\n{\n m_addresses.push_back(address);\n SetInitialBreakpoints();\n}\n\nThreadPlanRunToAddress::ThreadPlanRunToAddress\n(\n Thread &thread,\n std::vector<lldb::addr_t> &addresses,\n bool stop_others\n) :\n ThreadPlan (ThreadPlan::eKindRunToAddress, \"Run to address plan\", thread, eVoteNoOpinion, eVoteNoOpinion),\n m_stop_others (stop_others),\n m_addresses (addresses),\n m_break_ids ()\n{\n SetInitialBreakpoints();\n}\n\nvoid\nThreadPlanRunToAddress::SetInitialBreakpoints ()\n{\n size_t num_addresses = m_addresses.size();\n m_break_ids.resize(num_addresses);\n \n for (size_t i = 0; i < num_addresses; i++)\n {\n Breakpoint *breakpoint;\n breakpoint = m_thread.GetProcess().GetTarget().CreateBreakpoint (m_addresses[i], true).get();\n if (breakpoint != NULL)\n {\n m_break_ids[i] = breakpoint->GetID();\n breakpoint->SetThreadID(m_thread.GetID());\n }\n }\n}\n\nThreadPlanRunToAddress::~ThreadPlanRunToAddress ()\n{\n size_t num_break_ids = m_break_ids.size();\n for (size_t i = 0; i < num_break_ids; i++)\n {\n m_thread.GetProcess().GetTarget().RemoveBreakpointByID (m_break_ids[i]);\n }\n}\n\nvoid\nThreadPlanRunToAddress::GetDescription (Stream *s, lldb::DescriptionLevel level)\n{\n size_t num_addresses = m_addresses.size();\n \n if (level == lldb::eDescriptionLevelBrief)\n {\n if (num_addresses == 0)\n {\n s->Printf (\"run to address with no addresses given.\");\n return;\n }\n else if (num_addresses == 1)\n s->Printf (\"run to address: \");\n else\n s->Printf (\"run to addresses: \");\n \n for (size_t i = 0; i < num_addresses; i++)\n {\n s->Address (m_addresses[i], sizeof (addr_t));\n s->Printf(\" \");\n }\n }\n else\n {\n if (num_addresses == 0)\n {\n s->Printf (\"run to address with no addresses given.\");\n return;\n }\n else if (num_addresses == 1)\n s->Printf (\"Run to address: \");\n else\n {\n s->Printf (\"Run to addresses: \");\n }\n \n for (size_t i = 0; i < num_addresses; i++)\n {\n if (num_addresses > 1)\n {\n s->Printf(\"\\n\");\n s->Indent();\n }\n \n s->Address(m_addresses[i], sizeof (addr_t));\n s->Printf (\" using breakpoint: %d - \", m_break_ids[i]);\n Breakpoint *breakpoint = m_thread.GetProcess().GetTarget().GetBreakpointByID (m_break_ids[i]).get();\n if (breakpoint)\n breakpoint->Dump (s);\n else\n s->Printf (\"but the breakpoint has been deleted.\");\n }\n }\n}\n\nbool\nThreadPlanRunToAddress::ValidatePlan (Stream *error)\n{\n \/\/ If we couldn't set the breakpoint for some reason, then this won't\n \/\/ work.\n bool all_bps_good = true;\n size_t num_break_ids = m_break_ids.size();\n \n for (size_t i = 0; i < num_break_ids; i++)\n {\n if (m_break_ids[i] == LLDB_INVALID_BREAK_ID)\n {\n all_bps_good = false;\n if (error)\n {\n error->Printf (\"Could not set breakpoint for address: \");\n error->Address (m_addresses[i], sizeof (addr_t));\n error->Printf (\"\\n\");\n }\n }\n }\n return all_bps_good;\n}\n\nbool\nThreadPlanRunToAddress::PlanExplainsStop ()\n{\n return AtOurAddress();\n}\n\nbool\nThreadPlanRunToAddress::ShouldStop (Event *event_ptr)\n{\n return false;\n}\n\nbool\nThreadPlanRunToAddress::StopOthers ()\n{\n return m_stop_others;\n}\n\nvoid\nThreadPlanRunToAddress::SetStopOthers (bool new_value)\n{\n m_stop_others = new_value;\n}\n\nStateType\nThreadPlanRunToAddress::GetPlanRunState ()\n{\n return eStateRunning;\n}\n\nbool\nThreadPlanRunToAddress::WillStop ()\n{\n return true;\n}\n\nbool\nThreadPlanRunToAddress::MischiefManaged ()\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n\n if (AtOurAddress())\n {\n \/\/ Remove the breakpoint\n size_t num_break_ids = m_break_ids.size();\n \n for (size_t i = 0; i < num_break_ids; i++)\n {\n if (m_break_ids[i] != LLDB_INVALID_BREAK_ID)\n {\n m_thread.GetProcess().GetTarget().RemoveBreakpointByID (m_break_ids[i]);\n m_break_ids[i] = LLDB_INVALID_BREAK_ID;\n }\n }\n if (log)\n log->Printf(\"Completed run to address plan.\");\n ThreadPlan::MischiefManaged ();\n return true;\n }\n else\n return false;\n}\n\nbool\nThreadPlanRunToAddress::AtOurAddress ()\n{\n lldb::addr_t current_address = m_thread.GetRegisterContext()->GetPC();\n bool found_it = false;\n size_t num_addresses = m_addresses.size();\n for (size_t i = 0; i < num_addresses; i++)\n {\n if (m_addresses[i] == current_address)\n {\n found_it = true;\n break;\n }\n }\n return found_it;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ARMMCInstLower.cpp - Convert ARM MachineInstr to an MCInst --------===\/\/\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\/\/ This file contains code to lower ARM MachineInstrs to their corresponding\n\/\/ MCInst records.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ARM.h\"\n#include \"ARMAsmPrinter.h\"\n#include \"ARMMCExpr.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/CodeGen\/MachineBasicBlock.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/MC\/MCInst.h\"\n#include \"llvm\/Target\/Mangler.h\"\nusing namespace llvm;\n\n\nstatic MCOperand GetSymbolRef(const MachineOperand &MO, const MCSymbol *Symbol,\n ARMAsmPrinter &Printer) {\n MCContext &Ctx = Printer.OutContext;\n const MCExpr *Expr;\n switch (MO.getTargetFlags()) {\n default: {\n Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, Ctx);\n switch (MO.getTargetFlags()) {\n default:\n assert(0 && \"Unknown target flag on symbol operand\");\n case 0:\n break;\n case ARMII::MO_LO16:\n Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, Ctx);\n Expr = ARMMCExpr::CreateLower16(Expr, Ctx);\n break;\n case ARMII::MO_HI16:\n Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, Ctx);\n Expr = ARMMCExpr::CreateUpper16(Expr, Ctx);\n break;\n }\n break;\n }\n\n case ARMII::MO_PLT:\n Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_ARM_PLT, Ctx);\n break;\n }\n\n if (!MO.isJTI() && MO.getOffset())\n Expr = MCBinaryExpr::CreateAdd(Expr,\n MCConstantExpr::Create(MO.getOffset(), Ctx),\n Ctx);\n return MCOperand::CreateExpr(Expr);\n\n}\n\nvoid llvm::LowerARMMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI,\n ARMAsmPrinter &AP) {\n OutMI.setOpcode(MI->getOpcode());\n\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n\n MCOperand MCOp;\n switch (MO.getType()) {\n default:\n MI->dump();\n assert(0 && \"unknown operand type\");\n case MachineOperand::MO_Register:\n \/\/ Ignore all non-CPSR implicit register operands.\n if (MO.isImplicit() && MO.getReg() != ARM::CPSR) continue;\n assert(!MO.getSubReg() && \"Subregs should be eliminated!\");\n MCOp = MCOperand::CreateReg(MO.getReg());\n break;\n case MachineOperand::MO_Immediate:\n MCOp = MCOperand::CreateImm(MO.getImm());\n break;\n case MachineOperand::MO_MachineBasicBlock:\n MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(\n MO.getMBB()->getSymbol(), AP.OutContext));\n break;\n case MachineOperand::MO_GlobalAddress:\n MCOp = GetSymbolRef(MO, AP.Mang->getSymbol(MO.getGlobal()), AP);\n break;\n case MachineOperand::MO_ExternalSymbol:\n MCOp = GetSymbolRef(MO,\n AP.GetExternalSymbolSymbol(MO.getSymbolName()), AP);\n break;\n case MachineOperand::MO_JumpTableIndex:\n MCOp = GetSymbolRef(MO, AP.GetJTISymbol(MO.getIndex()), AP);\n break;\n case MachineOperand::MO_ConstantPoolIndex:\n MCOp = GetSymbolRef(MO, AP.GetCPISymbol(MO.getIndex()), AP);\n break;\n case MachineOperand::MO_BlockAddress:\n MCOp = GetSymbolRef(MO,AP.GetBlockAddressSymbol(MO.getBlockAddress()),AP);\n break;\n case MachineOperand::MO_FPImmediate:\n APFloat Val = MO.getFPImm()->getValueAPF();\n bool ignored;\n Val.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);\n MCOp = MCOperand::CreateFPImm(Val.convertToDouble());\n break;\n }\n\n OutMI.addOperand(MCOp);\n }\n}\n<commit_msg>Add needed braces.<commit_after>\/\/===-- ARMMCInstLower.cpp - Convert ARM MachineInstr to an MCInst --------===\/\/\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\/\/ This file contains code to lower ARM MachineInstrs to their corresponding\n\/\/ MCInst records.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ARM.h\"\n#include \"ARMAsmPrinter.h\"\n#include \"ARMMCExpr.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/CodeGen\/MachineBasicBlock.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/MC\/MCInst.h\"\n#include \"llvm\/Target\/Mangler.h\"\nusing namespace llvm;\n\n\nstatic MCOperand GetSymbolRef(const MachineOperand &MO, const MCSymbol *Symbol,\n ARMAsmPrinter &Printer) {\n MCContext &Ctx = Printer.OutContext;\n const MCExpr *Expr;\n switch (MO.getTargetFlags()) {\n default: {\n Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, Ctx);\n switch (MO.getTargetFlags()) {\n default:\n assert(0 && \"Unknown target flag on symbol operand\");\n case 0:\n break;\n case ARMII::MO_LO16:\n Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, Ctx);\n Expr = ARMMCExpr::CreateLower16(Expr, Ctx);\n break;\n case ARMII::MO_HI16:\n Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, Ctx);\n Expr = ARMMCExpr::CreateUpper16(Expr, Ctx);\n break;\n }\n break;\n }\n\n case ARMII::MO_PLT:\n Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_ARM_PLT, Ctx);\n break;\n }\n\n if (!MO.isJTI() && MO.getOffset())\n Expr = MCBinaryExpr::CreateAdd(Expr,\n MCConstantExpr::Create(MO.getOffset(), Ctx),\n Ctx);\n return MCOperand::CreateExpr(Expr);\n\n}\n\nvoid llvm::LowerARMMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI,\n ARMAsmPrinter &AP) {\n OutMI.setOpcode(MI->getOpcode());\n\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n\n MCOperand MCOp;\n switch (MO.getType()) {\n default:\n MI->dump();\n assert(0 && \"unknown operand type\");\n case MachineOperand::MO_Register:\n \/\/ Ignore all non-CPSR implicit register operands.\n if (MO.isImplicit() && MO.getReg() != ARM::CPSR) continue;\n assert(!MO.getSubReg() && \"Subregs should be eliminated!\");\n MCOp = MCOperand::CreateReg(MO.getReg());\n break;\n case MachineOperand::MO_Immediate:\n MCOp = MCOperand::CreateImm(MO.getImm());\n break;\n case MachineOperand::MO_MachineBasicBlock:\n MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(\n MO.getMBB()->getSymbol(), AP.OutContext));\n break;\n case MachineOperand::MO_GlobalAddress:\n MCOp = GetSymbolRef(MO, AP.Mang->getSymbol(MO.getGlobal()), AP);\n break;\n case MachineOperand::MO_ExternalSymbol:\n MCOp = GetSymbolRef(MO,\n AP.GetExternalSymbolSymbol(MO.getSymbolName()), AP);\n break;\n case MachineOperand::MO_JumpTableIndex:\n MCOp = GetSymbolRef(MO, AP.GetJTISymbol(MO.getIndex()), AP);\n break;\n case MachineOperand::MO_ConstantPoolIndex:\n MCOp = GetSymbolRef(MO, AP.GetCPISymbol(MO.getIndex()), AP);\n break;\n case MachineOperand::MO_BlockAddress:\n MCOp = GetSymbolRef(MO,AP.GetBlockAddressSymbol(MO.getBlockAddress()),AP);\n break;\n case MachineOperand::MO_FPImmediate: {\n APFloat Val = MO.getFPImm()->getValueAPF();\n bool ignored;\n Val.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);\n MCOp = MCOperand::CreateFPImm(Val.convertToDouble());\n break;\n }\n }\n\n OutMI.addOperand(MCOp);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2015, Youssef Kashef\n\/\/ Copyright (c) 2015, ELM Library Project\n\/\/ 3-clause BSD License\n\/\/\n\/\/M*\/\n#include \"elm\/layers\/layers_interim\/learning\/base_SupervisedBatch.h\"\n\n#include <memory>\n\n#include \"gtest\/gtest.h\"\n\n#include \"elm\/core\/defs.h\"\n#include \"elm\/core\/exception.h\"\n#include \"elm\/core\/layerconfig.h\"\n#include \"elm\/ts\/learninglayer_assertions.h\"\n\nusing namespace elm;\n\nclass DummySupervisedBatch : public base_SupervisedBatch\n{\npublic:\n DummySupervisedBatch()\n : base_SupervisedBatch(),\n flag(false)\n {}\n\n DummySupervisedBatch(const elm::LayerConfig &cfg)\n : base_SupervisedBatch(cfg),\n flag(false)\n {}\n\n void Learn(const cv::Mat1f& features, const cv::Mat1f &labels)\n {\n flag = true;\n }\n\n void Clear()\n {}\n\n void Reset(const elm::LayerConfig &cfg)\n {}\n\n void Reconfigure(const elm::LayerConfig &cfg)\n {}\n\n void Activate(const Signal &signal)\n {}\n\n void Response(Signal &signal)\n {}\n\n bool getFlag() const\n {\n return flag;\n }\n\nprotected:\n bool flag;\n};\n\nclass SupervisedBatchTest : public ::testing::Test\n{\nprotected:\n void SetUp()\n {\n to_.reset(new DummySupervisedBatch(LayerConfig()));\n }\n\n std::shared_ptr<base_Layer> to_;\n};\n\nTEST_F(SupervisedBatchTest, Constructor)\n{\n EXPECT_NO_THROW(DummySupervisedBatch());\n}\n\nTEST_F(SupervisedBatchTest, Learn_batch)\n{\n ASSERT_FALSE(ELM_DYN_CAST(DummySupervisedBatch, to_)->getFlag());\n\n EXPECT_NO_THROW(ELM_DYN_CAST(base_LearningLayer, to_)->Learn(cv::Mat(), cv::Mat()));\n\n EXPECT_TRUE(ELM_DYN_CAST(DummySupervisedBatch, to_)->getFlag());\n}\n\nTEST_F(SupervisedBatchTest, Learn_online)\n{\n EXPECT_THROW(ELM_DYN_CAST(base_LearningLayer, to_)->Learn(), ExceptionNotImpl);\n}\n\nELM_INSTANTIATE_LEARNING_LAYER_TYPED_TEST_CASE_P(DummySupervisedBatch);\n\n\/**\n * @brief Repeat above with pointer declared of type base_SupervisedBatch\n * Only relevant for Constructor and Destructor coverage, irrelevant for methods.\n *\/\nclass SupervisedBatchInstTest : public ::testing::Test\n{\nprotected:\n void SetUp()\n {\n to_.reset(new DummySupervisedBatch(LayerConfig()));\n }\n\n std::shared_ptr<base_SupervisedBatch> to_;\n};\n\nTEST_F(SupervisedBatchInstTest, Constructor)\n{\n EXPECT_NO_THROW(DummySupervisedBatch());\n}\n\nTEST_F(SupervisedBatchInstTest, Destructor)\n{\n EXPECT_NO_THROW(to_.reset());\n}\n\nTEST_F(SupervisedBatchInstTest, Learn_batch)\n{\n ASSERT_FALSE(ELM_DYN_CAST(DummySupervisedBatch, to_)->getFlag());\n\n EXPECT_NO_THROW(ELM_DYN_CAST(base_LearningLayer, to_)->Learn(cv::Mat(), cv::Mat()));\n\n EXPECT_TRUE(ELM_DYN_CAST(DummySupervisedBatch, to_)->getFlag());\n}\n\nTEST_F(SupervisedBatchInstTest, Learn_online)\n{\n EXPECT_THROW(ELM_DYN_CAST(base_LearningLayer, to_)->Learn(), ExceptionNotImpl);\n}\n<commit_msg>remove redundant tests of Learn()<commit_after>\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2015, Youssef Kashef\n\/\/ Copyright (c) 2015, ELM Library Project\n\/\/ 3-clause BSD License\n\/\/\n\/\/M*\/\n#include \"elm\/layers\/layers_interim\/learning\/base_SupervisedBatch.h\"\n\n#include <memory>\n\n#include \"gtest\/gtest.h\"\n\n#include \"elm\/core\/defs.h\"\n#include \"elm\/core\/exception.h\"\n#include \"elm\/core\/layerconfig.h\"\n#include \"elm\/ts\/learninglayer_assertions.h\"\n\nusing namespace elm;\n\nclass DummySupervisedBatch : public base_SupervisedBatch\n{\npublic:\n DummySupervisedBatch()\n : base_SupervisedBatch(),\n flag(false)\n {}\n\n DummySupervisedBatch(const elm::LayerConfig &cfg)\n : base_SupervisedBatch(cfg),\n flag(false)\n {}\n\n void Learn(const cv::Mat1f& features, const cv::Mat1f &labels)\n {\n flag = true;\n }\n\n void Clear()\n {}\n\n void Reset(const elm::LayerConfig &cfg)\n {}\n\n void Reconfigure(const elm::LayerConfig &cfg)\n {}\n\n void Activate(const Signal &signal)\n {}\n\n void Response(Signal &signal)\n {}\n\n bool getFlag() const\n {\n return flag;\n }\n\nprotected:\n bool flag;\n};\n\nclass SupervisedBatchTest : public ::testing::Test\n{\nprotected:\n void SetUp()\n {\n to_.reset(new DummySupervisedBatch(LayerConfig()));\n }\n\n std::shared_ptr<base_Layer> to_;\n};\n\nTEST_F(SupervisedBatchTest, Constructor)\n{\n EXPECT_NO_THROW(DummySupervisedBatch());\n}\n\nTEST_F(SupervisedBatchTest, Learn_batch)\n{\n ASSERT_FALSE(ELM_DYN_CAST(DummySupervisedBatch, to_)->getFlag());\n\n EXPECT_NO_THROW(ELM_DYN_CAST(base_LearningLayer, to_)->Learn(cv::Mat(), cv::Mat()));\n\n EXPECT_TRUE(ELM_DYN_CAST(DummySupervisedBatch, to_)->getFlag());\n}\n\nTEST_F(SupervisedBatchTest, Learn_online)\n{\n EXPECT_THROW(ELM_DYN_CAST(base_LearningLayer, to_)->Learn(), ExceptionNotImpl);\n}\n\nELM_INSTANTIATE_LEARNING_LAYER_TYPED_TEST_CASE_P(DummySupervisedBatch);\n\n\/**\n * @brief Repeat above with pointer declared of type base_SupervisedBatch\n * Only relevant for Constructor and Destructor coverage, irrelevant for methods.\n *\/\nclass SupervisedBatchInstTest : public ::testing::Test\n{\nprotected:\n void SetUp()\n {\n to_.reset(new DummySupervisedBatch(LayerConfig()));\n }\n\n std::shared_ptr<base_SupervisedBatch> to_;\n};\n\nTEST_F(SupervisedBatchInstTest, Constructor)\n{\n EXPECT_NO_THROW(DummySupervisedBatch());\n}\n\nTEST_F(SupervisedBatchInstTest, Destructor)\n{\n EXPECT_NO_THROW(to_.reset());\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight\n Project home: https:\/\/github.com\/puuu\/MQTT433gateway\/\n\n The MIT License (MIT)\n\n Copyright (c) 2017 Jan Losinski\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and\/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include <WString.h>\n\n#include <ArduinoJson.h>\n\n#include <ArduinoSimpleLogging.h>\n#include <ESP8266WebServer.h>\n#include <WiFiUdp.h>\n\n#include \"..\/..\/dist\/index.html.gz.h\"\n#include \"ConfigWebServer.h\"\n\nconst char TEXT_PLAIN[] PROGMEM = \"text\/plain\";\nconst char APPLICATION_JSON[] = \"application\/json\";\n\nvoid ConfigWebServer::begin(Settings& settings) {\n updateSettings(settings);\n\n server.on(F(\"\/\"), authenticated([this]() {\n server.sendHeader(F(\"Content-Encoding\"), \"gzip\");\n server.setContentLength(index_html_gz_len);\n server.send(200, F(\"text\/html\"), \"\");\n server.sendContent_P(index_html_gz, index_html_gz_len);\n }));\n\n server.on(F(\"\/system\"), HTTP_GET, authenticated([this]() {\n server.send_P(200, TEXT_PLAIN, PSTR(\"POST your commands here\"));\n }));\n\n server.on(\n F(\"\/system\"), HTTP_POST,\n authenticated(std::bind(&::ConfigWebServer::onSystemCommand, this)));\n\n server.on(F(\"\/config\"), HTTP_GET, authenticated([&]() {\n String buff;\n settings.serialize(buff, true, false);\n server.send(200, APPLICATION_JSON, buff);\n }));\n\n server.on(F(\"\/config\"), HTTP_PUT, authenticated([&]() {\n settings.deserialize(server.arg(\"plain\"));\n settings.save();\n server.send(200, APPLICATION_JSON, F(\"true\"));\n }));\n\n server.on(F(\"\/protocols\"), HTTP_GET, authenticated([this]() {\n const RfHandler* handler(getRfHandler());\n if (handler) {\n server.send(200, APPLICATION_JSON,\n handler->availableProtocols());\n } else {\n server.send(200, APPLICATION_JSON, F(\"[]\"));\n }\n }));\n\n server.on(F(\"\/debug\"), HTTP_GET, authenticated([this]() {\n const RfHandler* handler(getRfHandler());\n\n if (!handler) {\n server.send(200, APPLICATION_JSON, F(\"{}\"));\n return;\n }\n\n DynamicJsonBuffer buff;\n JsonObject& root = buff.createObject();\n root[F(\"protocolRaw\")] = handler->isRawModeEnabled();\n\n String result;\n root.printTo(result);\n\n server.send(200, APPLICATION_JSON, result);\n }));\n\n server.on(F(\"\/debug\"), HTTP_PUT, authenticated([this]() {\n RfHandler* handler(rfHandlerProvider());\n\n if (!handler) {\n server.send(500, APPLICATION_JSON, F(\"false\"));\n return;\n }\n\n DynamicJsonBuffer buff;\n JsonObject& parsed = buff.parse(server.arg(F(\"plain\")));\n\n if (!parsed.success()) {\n server.send(500, APPLICATION_JSON, F(\"false\"));\n return;\n }\n\n if (parsed.containsKey(F(\"protocolRaw\"))) {\n handler->setRawMode(parsed.get<bool>(F(\"protocolRaw\")));\n }\n\n server.send(200, APPLICATION_JSON, F(\"true\"));\n }));\n\n server.on(F(\"\/firmware\"), HTTP_GET, authenticated([this]() {\n server.send_P(\n 200, APPLICATION_JSON,\n PSTR(\"{\\\"version\\\": \\\"\" QUOTE(FIRMWARE_VERSION) \"\\\"}\"));\n }));\n\n server.on(\n F(\"\/firmware\"), HTTP_POST, authenticated([this]() {\n server.sendHeader(F(\"Connection\"), F(\"close\"));\n\n Logger.info.println(F(\"Got an update. Reboot.\"));\n if (Update.hasError()) {\n server.send_P(\n 200, TEXT_PLAIN,\n PSTR(\"Update failed. You may need to reflash the device.\"));\n } else {\n server.sendHeader(F(\"Refresh\"), F(\"20; URL=\/\"));\n server.send_P(200, TEXT_PLAIN,\n PSTR(\"Update successful.\\n\\nDevice will reboot and try \"\n \"to reconnect in 20 seconds.\"));\n }\n delay(500);\n ESP.restart();\n }),\n authenticated([this]() {\n HTTPUpload& upload = server.upload();\n if (upload.status == UPLOAD_FILE_START) {\n Serial.setDebugOutput(true);\n WiFiUDP::stopAll();\n\n RfHandler* handler = getRfHandler();\n if (handler) {\n handler->disableReceiver();\n }\n\n Serial.print(F(\"Update: \"));\n Serial.println(upload.filename.c_str());\n uint32_t maxSketchSpace =\n (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;\n if (!Update.begin(maxSketchSpace)) { \/\/ start with max available size\n Update.printError(Serial);\n }\n } else if (upload.status == UPLOAD_FILE_WRITE) {\n if (Update.write(upload.buf, upload.currentSize) !=\n upload.currentSize) {\n Update.printError(Serial);\n }\n } else if (upload.status == UPLOAD_FILE_END) {\n if (Update.end(\n true)) { \/\/ true to set the size to the current progress\n Serial.print(F(\"Update Success: \"));\n Serial.print(upload.totalSize);\n Serial.print(F(\"\\nRebooting...\\n\"));\n } else {\n Update.printError(Serial);\n }\n Serial.setDebugOutput(false);\n }\n yield();\n }));\n\n wsLogTarget.begin();\n server.begin();\n}\n\nvoid ConfigWebServer::registerSystemCommandHandler(\n const String& command, const ConfigWebServer::SystemCommandCb& cb) {\n systemCommandHandlers.emplace_front(command, cb);\n}\n\nvoid ConfigWebServer::onSystemCommand() {\n DynamicJsonBuffer buffer;\n JsonObject& request = buffer.parse(server.arg(F(\"plain\")));\n\n if (!request.success()) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"Cannot parse command!\"));\n return;\n }\n\n if (!request.containsKey(F(\"command\"))) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"No command found!\"));\n return;\n }\n\n for (const auto& systemCommandHandler : systemCommandHandlers) {\n if (systemCommandHandler.command == request[F(\"command\")]) {\n server.send_P(200, TEXT_PLAIN, PSTR(\"Run command!\"));\n systemCommandHandler.cb();\n return;\n }\n }\n\n server.send_P(400, TEXT_PLAIN, PSTR(\"Unknown command\"));\n}\n\nvoid ConfigWebServer::handleClient() {\n wsLogTarget.loop();\n server.handleClient();\n}\n\nvoid ConfigWebServer::updateSettings(const Settings& settings) {\n password = settings.configPassword;\n}\n\nPrint& ConfigWebServer::logTarget() { return wsLogTarget; }\n\nESP8266WebServer::THandlerFunction ConfigWebServer::authenticated(\n const ESP8266WebServer::THandlerFunction& handler) {\n return [=]() {\n if (!server.authenticate(ADMIN_USERNAME, this->password.c_str())) {\n server.sendHeader(F(\"WWW-Authenticate\"),\n F(\"Basic realm=\\\"Login Required\\\"\"));\n server.send_P(401, TEXT_PLAIN, PSTR(\"Authentication required!\"));\n } else {\n handler();\n }\n };\n}\n<commit_msg>ConfigWebServer.cpp: clean up #include order<commit_after>\/**\n MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight\n Project home: https:\/\/github.com\/puuu\/MQTT433gateway\/\n\n The MIT License (MIT)\n\n Copyright (c) 2017 Jan Losinski\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and\/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include <ESP8266WebServer.h>\n#include <WString.h>\n#include <WiFiUdp.h>\n\n#include <ArduinoJson.h>\n#include <ArduinoSimpleLogging.h>\n\n#include \"..\/..\/dist\/index.html.gz.h\"\n#include \"ConfigWebServer.h\"\n\nconst char TEXT_PLAIN[] PROGMEM = \"text\/plain\";\nconst char APPLICATION_JSON[] = \"application\/json\";\n\nvoid ConfigWebServer::begin(Settings& settings) {\n updateSettings(settings);\n\n server.on(F(\"\/\"), authenticated([this]() {\n server.sendHeader(F(\"Content-Encoding\"), \"gzip\");\n server.setContentLength(index_html_gz_len);\n server.send(200, F(\"text\/html\"), \"\");\n server.sendContent_P(index_html_gz, index_html_gz_len);\n }));\n\n server.on(F(\"\/system\"), HTTP_GET, authenticated([this]() {\n server.send_P(200, TEXT_PLAIN, PSTR(\"POST your commands here\"));\n }));\n\n server.on(\n F(\"\/system\"), HTTP_POST,\n authenticated(std::bind(&::ConfigWebServer::onSystemCommand, this)));\n\n server.on(F(\"\/config\"), HTTP_GET, authenticated([&]() {\n String buff;\n settings.serialize(buff, true, false);\n server.send(200, APPLICATION_JSON, buff);\n }));\n\n server.on(F(\"\/config\"), HTTP_PUT, authenticated([&]() {\n settings.deserialize(server.arg(\"plain\"));\n settings.save();\n server.send(200, APPLICATION_JSON, F(\"true\"));\n }));\n\n server.on(F(\"\/protocols\"), HTTP_GET, authenticated([this]() {\n const RfHandler* handler(getRfHandler());\n if (handler) {\n server.send(200, APPLICATION_JSON,\n handler->availableProtocols());\n } else {\n server.send(200, APPLICATION_JSON, F(\"[]\"));\n }\n }));\n\n server.on(F(\"\/debug\"), HTTP_GET, authenticated([this]() {\n const RfHandler* handler(getRfHandler());\n\n if (!handler) {\n server.send(200, APPLICATION_JSON, F(\"{}\"));\n return;\n }\n\n DynamicJsonBuffer buff;\n JsonObject& root = buff.createObject();\n root[F(\"protocolRaw\")] = handler->isRawModeEnabled();\n\n String result;\n root.printTo(result);\n\n server.send(200, APPLICATION_JSON, result);\n }));\n\n server.on(F(\"\/debug\"), HTTP_PUT, authenticated([this]() {\n RfHandler* handler(rfHandlerProvider());\n\n if (!handler) {\n server.send(500, APPLICATION_JSON, F(\"false\"));\n return;\n }\n\n DynamicJsonBuffer buff;\n JsonObject& parsed = buff.parse(server.arg(F(\"plain\")));\n\n if (!parsed.success()) {\n server.send(500, APPLICATION_JSON, F(\"false\"));\n return;\n }\n\n if (parsed.containsKey(F(\"protocolRaw\"))) {\n handler->setRawMode(parsed.get<bool>(F(\"protocolRaw\")));\n }\n\n server.send(200, APPLICATION_JSON, F(\"true\"));\n }));\n\n server.on(F(\"\/firmware\"), HTTP_GET, authenticated([this]() {\n server.send_P(\n 200, APPLICATION_JSON,\n PSTR(\"{\\\"version\\\": \\\"\" QUOTE(FIRMWARE_VERSION) \"\\\"}\"));\n }));\n\n server.on(\n F(\"\/firmware\"), HTTP_POST, authenticated([this]() {\n server.sendHeader(F(\"Connection\"), F(\"close\"));\n\n Logger.info.println(F(\"Got an update. Reboot.\"));\n if (Update.hasError()) {\n server.send_P(\n 200, TEXT_PLAIN,\n PSTR(\"Update failed. You may need to reflash the device.\"));\n } else {\n server.sendHeader(F(\"Refresh\"), F(\"20; URL=\/\"));\n server.send_P(200, TEXT_PLAIN,\n PSTR(\"Update successful.\\n\\nDevice will reboot and try \"\n \"to reconnect in 20 seconds.\"));\n }\n delay(500);\n ESP.restart();\n }),\n authenticated([this]() {\n HTTPUpload& upload = server.upload();\n if (upload.status == UPLOAD_FILE_START) {\n Serial.setDebugOutput(true);\n WiFiUDP::stopAll();\n\n RfHandler* handler = getRfHandler();\n if (handler) {\n handler->disableReceiver();\n }\n\n Serial.print(F(\"Update: \"));\n Serial.println(upload.filename.c_str());\n uint32_t maxSketchSpace =\n (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;\n if (!Update.begin(maxSketchSpace)) { \/\/ start with max available size\n Update.printError(Serial);\n }\n } else if (upload.status == UPLOAD_FILE_WRITE) {\n if (Update.write(upload.buf, upload.currentSize) !=\n upload.currentSize) {\n Update.printError(Serial);\n }\n } else if (upload.status == UPLOAD_FILE_END) {\n if (Update.end(\n true)) { \/\/ true to set the size to the current progress\n Serial.print(F(\"Update Success: \"));\n Serial.print(upload.totalSize);\n Serial.print(F(\"\\nRebooting...\\n\"));\n } else {\n Update.printError(Serial);\n }\n Serial.setDebugOutput(false);\n }\n yield();\n }));\n\n wsLogTarget.begin();\n server.begin();\n}\n\nvoid ConfigWebServer::registerSystemCommandHandler(\n const String& command, const ConfigWebServer::SystemCommandCb& cb) {\n systemCommandHandlers.emplace_front(command, cb);\n}\n\nvoid ConfigWebServer::onSystemCommand() {\n DynamicJsonBuffer buffer;\n JsonObject& request = buffer.parse(server.arg(F(\"plain\")));\n\n if (!request.success()) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"Cannot parse command!\"));\n return;\n }\n\n if (!request.containsKey(F(\"command\"))) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"No command found!\"));\n return;\n }\n\n for (const auto& systemCommandHandler : systemCommandHandlers) {\n if (systemCommandHandler.command == request[F(\"command\")]) {\n server.send_P(200, TEXT_PLAIN, PSTR(\"Run command!\"));\n systemCommandHandler.cb();\n return;\n }\n }\n\n server.send_P(400, TEXT_PLAIN, PSTR(\"Unknown command\"));\n}\n\nvoid ConfigWebServer::handleClient() {\n wsLogTarget.loop();\n server.handleClient();\n}\n\nvoid ConfigWebServer::updateSettings(const Settings& settings) {\n password = settings.configPassword;\n}\n\nPrint& ConfigWebServer::logTarget() { return wsLogTarget; }\n\nESP8266WebServer::THandlerFunction ConfigWebServer::authenticated(\n const ESP8266WebServer::THandlerFunction& handler) {\n return [=]() {\n if (!server.authenticate(ADMIN_USERNAME, this->password.c_str())) {\n server.sendHeader(F(\"WWW-Authenticate\"),\n F(\"Basic realm=\\\"Login Required\\\"\"));\n server.send_P(401, TEXT_PLAIN, PSTR(\"Authentication required!\"));\n } else {\n handler();\n }\n };\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Exceptions.h\"\n#include \"ToolBase.h\"\n#include \"ChromosomalIndex.h\"\n#include \"VariantList.h\"\n#include \"BedFile.h\"\n#include \"NGSD.h\"\n#include \"GPD.h\"\n#include \"Log.h\"\n#include \"Settings.h\"\n\nclass ConcreteTool\n\t\t: public ToolBase\n{\n\tQ_OBJECT\n\npublic:\n\tConcreteTool(int& argc, char *argv[])\n\t\t: ToolBase(argc, argv)\n\t{\n\t}\n\n\tvirtual void setup()\n\t{\n\t\tsetDescription(\"Annotates a variant list with information from the NGSD.\");\n\t\taddInfile(\"in\", \"Input variant list.\", false, true);\n\t\taddOutfile(\"out\", \"Output variant list.\", false, true);\n\t\t\/\/optional\n\t\taddString(\"psname\", \"Processed sample name. If set, this name is used instead of the file name to find the sample in the DB.\", true, \"\");\n\t\taddEnum(\"mode\", \"Determines annotation mode.\", true, QStringList() << \"germline\" << \"somatic\", \"germline\");\n\t\taddFlag(\"test\", \"Uses the test database instead of on the production database.\");\n\t}\n\n\tvirtual void main()\n\t{\n\t\t\/\/init\n\t\tQString psname = getString(\"psname\");\n\t\tif (psname==\"\") psname = getInfile(\"in\");\n\n\t\t\/\/load\n\t\tVariantList variants;\n\t\tvariants.load(getInfile(\"in\"));\n\n\t\t\/\/annotate\n\t\tbool test = getFlag(\"test\");\n\t\tQString mode = getEnum(\"mode\");\n\t\tif(mode==\"germline\")\n\t\t{\n\t\t\tif (!test) GPD().annotate(variants); \/\/TODO update when GPD is integrated into NGSD\n\t\t\tNGSD(test).annotate(variants, psname);\n\t\t}\n\t\telse if(mode==\"somatic\")\n\t\t{\n\t\t\tif (!test) GPD().annotateSomatic(variants); \/\/TODO update when GPD is integrated into NGSD\n\t\t\tNGSD(test).annotateSomatic(variants, psname);\n\t\t}\n\n\t\t\/\/store\n\t\tvariants.store(getOutfile(\"out\"));\n\t}\n};\n\n#include \"main.moc\"\n\nint main(int argc, char *argv[])\n{\n\tConcreteTool tool(argc, argv);\n\treturn tool.execute();\n}\n<commit_msg>VariantAnnotateNGSD: GPD is no longer required - errors are logged bug no longer abort execution.<commit_after>#include \"Exceptions.h\"\n#include \"ToolBase.h\"\n#include \"ChromosomalIndex.h\"\n#include \"VariantList.h\"\n#include \"BedFile.h\"\n#include \"NGSD.h\"\n#include \"GPD.h\"\n#include \"Log.h\"\n#include \"Settings.h\"\n\nclass ConcreteTool\n\t\t: public ToolBase\n{\n\tQ_OBJECT\n\npublic:\n\tConcreteTool(int& argc, char *argv[])\n\t\t: ToolBase(argc, argv)\n\t{\n\t}\n\n\tvirtual void setup()\n\t{\n\t\tsetDescription(\"Annotates a variant list with information from the NGSD.\");\n\t\taddInfile(\"in\", \"Input variant list.\", false, true);\n\t\taddOutfile(\"out\", \"Output variant list.\", false, true);\n\t\t\/\/optional\n\t\taddString(\"psname\", \"Processed sample name. If set, this name is used instead of the file name to find the sample in the DB.\", true, \"\");\n\t\taddEnum(\"mode\", \"Determines annotation mode.\", true, QStringList() << \"germline\" << \"somatic\", \"germline\");\n\t\taddFlag(\"test\", \"Uses the test database instead of on the production database.\");\n\t}\n\n\tvirtual void main()\n\t{\n\t\t\/\/init\n\t\tQString psname = getString(\"psname\");\n\t\tif (psname==\"\") psname = getInfile(\"in\");\n\n\t\t\/\/load\n\t\tVariantList variants;\n\t\tvariants.load(getInfile(\"in\"));\n\n\t\t\/\/annotate\n\t\tbool test = getFlag(\"test\");\n\t\tQString mode = getEnum(\"mode\");\n\t\tif(mode==\"germline\")\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tGPD().annotate(variants);\n\t\t\t}\n\t\t\tcatch (DatabaseException& e)\n\t\t\t{\n\t\t\t\tLog::error(\"GPD database error: \" + e.message());\n\t\t\t}\n\t\t\tNGSD(test).annotate(variants, psname);\n\t\t}\n\t\telse if(mode==\"somatic\")\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tGPD().annotateSomatic(variants);\n\t\t\t}\n\t\t\tcatch (DatabaseException& e)\n\t\t\t{\n\t\t\t\tLog::error(\"GPD database error: \" + e.message());\n\t\t\t}\n\t\t\tNGSD(test).annotateSomatic(variants, psname);\n\t\t}\n\n\t\t\/\/store\n\t\tvariants.store(getOutfile(\"out\"));\n\t}\n};\n\n#include \"main.moc\"\n\nint main(int argc, char *argv[])\n{\n\tConcreteTool tool(argc, argv);\n\treturn tool.execute();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"CppUnitTest.h\"\n#include <algorithm>\n#include <sstream>\n#include <cctype>\n#include <string>\n#include <vector>\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\n\nnamespace algo\n{\n struct token\n {\n enum toktype { root_node, named_node, edge_name, horizontal_edge, ascending_edge_part, descending_edge_part, vertical_edge_part };\n toktype type;\n string name;\n };\n\n bool operator==(const token& lhs, const token& rhs)\n {\n return lhs.type == rhs.type\n && lhs.name == rhs.name;\n }\n\n struct ascii_tree\n {\n static vector<token> tokenize(const string& s)\n {\n vector<token> tokens;\n enum { none, open_square_brace, close_square_brace, asterisk, dash, name_char } prev = none;\n size_t marker = 0, marked_length = 0;\n\n for (size_t i = 0; i < s.size(); ++i)\n {\n auto ch = s[i];\n\n if (ch == '[')\n {\n prev = open_square_brace;\n }\n else if (ch == ']')\n {\n if (prev == asterisk)\n {\n tokens.emplace_back(token { token::root_node, \"\" });\n }\n else\n {\n tokens.emplace_back(token { token::named_node, s.substr(marker, marked_length) });\n }\n\n prev = close_square_brace;\n }\n else if (ch == '*')\n {\n prev = asterisk;\n }\n else if (ch == '-')\n {\n if (prev == name_char)\n {\n tokens.emplace_back(token { token::horizontal_edge, s.substr(marker, marked_length) });\n }\n\n prev = dash;\n }\n else if (ch == '\/')\n {\n tokens.emplace_back(token { token::ascending_edge_part, \"\" });\n }\n else if (ch == '\\\\')\n {\n tokens.emplace_back(token { token::descending_edge_part, \"\" });\n }\n else if (ch == '|')\n {\n tokens.emplace_back(token { token::vertical_edge_part, \"\" });\n }\n else if (isalnum(ch) || ch == '_')\n {\n if (prev != name_char)\n {\n marker = i;\n marked_length = 0;\n }\n\n prev = name_char;\n ++marked_length;\n }\n }\n\n if (prev == name_char)\n {\n tokens.emplace_back(token { token::edge_name, s.substr(marker, marked_length) });\n }\n\n return tokens;\n }\n };\n}\n\nnamespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework\n{\n template<>\n wstring ToString<algo::token::toktype>(const algo::token::toktype& type)\n {\n switch (type)\n {\n case algo::token::root_node:\n return L\"root_node\";\n case algo::token::named_node:\n return L\"named_node\";\n case algo::token::edge_name:\n return L\"edge_name\";\n case algo::token::horizontal_edge:\n return L\"horizontal_edge\";\n case algo::token::ascending_edge_part:\n return L\"ascending_edge_part\";\n case algo::token::descending_edge_part:\n return L\"descending_edge_part\";\n case algo::token::vertical_edge_part:\n return L\"vertical_edge_part\";\n default:\n return L\"unknown token\";\n }\n }\n}}}\n\nnamespace algo { namespace spec\n{\n TEST_CLASS(can_recognize_ascii_tree_tokens)\n {\n void tokens_should_match_(std::initializer_list<token> expected, vector<token>& actual)\n {\n auto mismatch_pair = std::mismatch(expected.begin(), expected.end(), actual.begin());\n\n if (mismatch_pair.first != expected.end() || mismatch_pair.second != actual.end())\n {\n wstring expectedName(mismatch_pair.first->name.begin(), mismatch_pair.first->name.end());\n wstring actualName(mismatch_pair.second->name.begin(), mismatch_pair.second->name.end());\n\n wstring message = L\"Expected: \" + ToString(mismatch_pair.first->type) + L\" \\\"\" + expectedName + L\"\\\" \"\n + L\"Actual: \" + ToString(mismatch_pair.second->type) + L\" \\\"\" + actualName + L\"\\\"\";\n\n Assert::Fail(message.c_str());\n }\n }\n\n public:\n \n TEST_METHOD(should_not_recognize_any_tokens_in_an_empty_string)\n {\n auto tokens = ascii_tree::tokenize(\"\");\n Assert::IsTrue(tokens.empty());\n }\n\n TEST_METHOD(should_recognize_a_root_node)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_root_node_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" [ * ]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_named_node)\n {\n const string all_chars = \"_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n auto tokens = ascii_tree::tokenize(\"[\" + all_chars + \"]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(all_chars.c_str(), tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_named_node_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" [ a ]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"a\");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" a \");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"\/\");\n Assert::AreEqual(token::ascending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_an_ascending_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" \/ \");\n Assert::AreEqual(token::ascending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"\\\\\");\n Assert::AreEqual(token::descending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_descending_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" \\\\ \");\n Assert::AreEqual(token::descending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"|\");\n Assert::AreEqual(token::vertical_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_vertical_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" | \");\n Assert::AreEqual(token::vertical_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"-a-\");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" - a - \");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[*][a]\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::named_node, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"[*]-a-\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::horizontal_edge, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"-a-[b]\");\n tokens_should_match_({ { token::horizontal_edge, \"a\" }, { token::named_node, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\\\\\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::descending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\/\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::ascending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]|\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::vertical_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"[*]a\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::edge_name, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_root_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a][*]\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::root_node, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a][b]\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::named_node, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"[a]-b-\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::horizontal_edge, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[a]\\\\\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::descending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[a]\/\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::ascending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[a]|\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::vertical_edge_part, \"\" } }, tokens);\n }\n\n };\n}}\n<commit_msg>recognize a named node next to an edge name<commit_after>#include \"CppUnitTest.h\"\n#include <algorithm>\n#include <sstream>\n#include <cctype>\n#include <string>\n#include <vector>\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\n\nnamespace algo\n{\n struct token\n {\n enum toktype { root_node, named_node, edge_name, horizontal_edge, ascending_edge_part, descending_edge_part, vertical_edge_part };\n toktype type;\n string name;\n };\n\n bool operator==(const token& lhs, const token& rhs)\n {\n return lhs.type == rhs.type\n && lhs.name == rhs.name;\n }\n\n struct ascii_tree\n {\n static vector<token> tokenize(const string& s)\n {\n vector<token> tokens;\n enum { none, open_square_brace, close_square_brace, asterisk, dash, name_char } prev = none;\n size_t marker = 0, marked_length = 0;\n\n for (size_t i = 0; i < s.size(); ++i)\n {\n auto ch = s[i];\n\n if (ch == '[')\n {\n prev = open_square_brace;\n }\n else if (ch == ']')\n {\n if (prev == asterisk)\n {\n tokens.emplace_back(token { token::root_node, \"\" });\n }\n else\n {\n tokens.emplace_back(token { token::named_node, s.substr(marker, marked_length) });\n }\n\n prev = close_square_brace;\n }\n else if (ch == '*')\n {\n prev = asterisk;\n }\n else if (ch == '-')\n {\n if (prev == name_char)\n {\n tokens.emplace_back(token { token::horizontal_edge, s.substr(marker, marked_length) });\n }\n\n prev = dash;\n }\n else if (ch == '\/')\n {\n tokens.emplace_back(token { token::ascending_edge_part, \"\" });\n }\n else if (ch == '\\\\')\n {\n tokens.emplace_back(token { token::descending_edge_part, \"\" });\n }\n else if (ch == '|')\n {\n tokens.emplace_back(token { token::vertical_edge_part, \"\" });\n }\n else if (isalnum(ch) || ch == '_')\n {\n if (prev != name_char)\n {\n marker = i;\n marked_length = 0;\n }\n\n prev = name_char;\n ++marked_length;\n }\n }\n\n if (prev == name_char)\n {\n tokens.emplace_back(token { token::edge_name, s.substr(marker, marked_length) });\n }\n\n return tokens;\n }\n };\n}\n\nnamespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework\n{\n template<>\n wstring ToString<algo::token::toktype>(const algo::token::toktype& type)\n {\n switch (type)\n {\n case algo::token::root_node:\n return L\"root_node\";\n case algo::token::named_node:\n return L\"named_node\";\n case algo::token::edge_name:\n return L\"edge_name\";\n case algo::token::horizontal_edge:\n return L\"horizontal_edge\";\n case algo::token::ascending_edge_part:\n return L\"ascending_edge_part\";\n case algo::token::descending_edge_part:\n return L\"descending_edge_part\";\n case algo::token::vertical_edge_part:\n return L\"vertical_edge_part\";\n default:\n return L\"unknown token\";\n }\n }\n}}}\n\nnamespace algo { namespace spec\n{\n TEST_CLASS(can_recognize_ascii_tree_tokens)\n {\n void tokens_should_match_(std::initializer_list<token> expected, vector<token>& actual)\n {\n auto mismatch_pair = std::mismatch(expected.begin(), expected.end(), actual.begin());\n\n if (mismatch_pair.first != expected.end() || mismatch_pair.second != actual.end())\n {\n wstring expectedName(mismatch_pair.first->name.begin(), mismatch_pair.first->name.end());\n wstring actualName(mismatch_pair.second->name.begin(), mismatch_pair.second->name.end());\n\n wstring message = L\"Expected: \" + ToString(mismatch_pair.first->type) + L\" \\\"\" + expectedName + L\"\\\" \"\n + L\"Actual: \" + ToString(mismatch_pair.second->type) + L\" \\\"\" + actualName + L\"\\\"\";\n\n Assert::Fail(message.c_str());\n }\n }\n\n public:\n \n TEST_METHOD(should_not_recognize_any_tokens_in_an_empty_string)\n {\n auto tokens = ascii_tree::tokenize(\"\");\n Assert::IsTrue(tokens.empty());\n }\n\n TEST_METHOD(should_recognize_a_root_node)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_root_node_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" [ * ]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_named_node)\n {\n const string all_chars = \"_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n auto tokens = ascii_tree::tokenize(\"[\" + all_chars + \"]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(all_chars.c_str(), tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_named_node_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" [ a ]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"a\");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" a \");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"\/\");\n Assert::AreEqual(token::ascending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_an_ascending_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" \/ \");\n Assert::AreEqual(token::ascending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"\\\\\");\n Assert::AreEqual(token::descending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_descending_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" \\\\ \");\n Assert::AreEqual(token::descending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"|\");\n Assert::AreEqual(token::vertical_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_vertical_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" | \");\n Assert::AreEqual(token::vertical_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"-a-\");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" - a - \");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[*][a]\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::named_node, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"[*]-a-\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::horizontal_edge, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"-a-[b]\");\n tokens_should_match_({ { token::horizontal_edge, \"a\" }, { token::named_node, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\\\\\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::descending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\/\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::ascending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]|\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::vertical_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"[*]a\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::edge_name, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_root_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a][*]\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::root_node, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a][b]\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::named_node, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"[a]-b-\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::horizontal_edge, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[a]\\\\\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::descending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[a]\/\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::ascending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[a]|\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::vertical_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"[a]b\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::edge_name, \"b\" } }, tokens);\n }\n\n };\n}}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright (c) 2015-2022 Agalmic Ventures LLC (www.agalmicventures.com)\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\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include <atomic>\n#include <cassert>\n#include <cstdarg>\n#include <cstdint>\n#include <limits>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"Werk\/Logging\/Log.hpp\"\n#include \"Werk\/Utility\/Action.hpp\"\n#include \"Werk\/Utility\/Attributes.hpp\"\n#include \"Werk\/Utility\/Latch.hpp\"\n\nnamespace werk\n{\n\nclass Config;\n\n\/**\n * Adapter for the Config class that allows keys to be read from a number of scopes,\n * allowing for cascading configurations.\n *\/\nclass ScopedConfig\n{\npublic:\n\tScopedConfig(Config &config) : _config(config) { }\n\tScopedConfig(Config &config, const std::string &scope) : ScopedConfig(config)\n\t{\n\t\t_scopes.push_back(scope);\n\t}\n\tScopedConfig(Config &config, const std::string &scope1, const std::string scope2) :\n\t\tScopedConfig(config)\n\t{\n\t\t_scopes.push_back(scope1);\n\t\t_scopes.push_back(scope2);\n\t}\n\tScopedConfig(Config &config, const std::string &scope1, const std::string scope2, const std::string scope3) :\n\t\tScopedConfig(config)\n\t{\n\t\t_scopes.push_back(scope1);\n\t\t_scopes.push_back(scope2);\n\t\t_scopes.push_back(scope3);\n\t}\n\tScopedConfig(Config &config, const std::string &scope1, const std::string scope2, const std::string scope3, const std::string scope4) :\n\t\tScopedConfig(config)\n\t{\n\t\t_scopes.push_back(scope1);\n\t\t_scopes.push_back(scope2);\n\t\t_scopes.push_back(scope3);\n\t\t_scopes.push_back(scope4);\n\t}\n\n\t\/\/Accessors\n\tCHECKED std::vector<std::string> &scopes() { return _scopes; }\n\tCHECKED const std::vector<std::string> &scopes() const { return _scopes; }\n\n\t\/\/Base config accessors\n\tvoid addConfigurable(Configurable *configurable);\n\n\t\/\/Basic types\n\tCHECKED const char *getString(const std::string &key, const char *defaultValue=nullptr, const char *help=nullptr) const;\n\tCHECKED bool getBool(const std::string &key, bool defaultValue=false, const char *help=nullptr) const;\n\tCHECKED double getDouble(const std::string &key, double defaultValue=0, const char *help=nullptr) const;\n\tCHECKED int64_t getInt64(const std::string &key, int64_t defaultValue=0, const char *help=nullptr) const;\n\tCHECKED uint64_t getUint64(const std::string &key, uint64_t defaultValue=0, const char *help=nullptr) const;\n\tCHECKED uint64_t getStorageAmount(const std::string &key, uint64_t defaultValue=0, const char *help=nullptr) const;\n\tCHECKED uint64_t getTimeAmount(const std::string &key, uint64_t defaultValue=0, const char *help=nullptr) const;\n\n\t\/\/List types\n\tconst char *getStrings(const std::string &key, std::vector<std::string> &values,\n\t\tconst char *defaultValue=nullptr, const char *help=nullptr, const char *delimiters=\",\") const;\n\nprotected:\n\t\/\/Config\n\tConfig &_config;\n\tstd::vector<std::string> _scopes;\n\n\tvoid findScopedKey(const std::string &key, std::string &specificKey, std::string &foundKey) const;\n};\n\n}\n<commit_msg>Fix missing line in last commit<commit_after>\n\/*\n * Copyright (c) 2015-2022 Agalmic Ventures LLC (www.agalmicventures.com)\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\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include <atomic>\n#include <cassert>\n#include <cstdarg>\n#include <cstdint>\n#include <limits>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"Werk\/Logging\/Log.hpp\"\n#include \"Werk\/Utility\/Action.hpp\"\n#include \"Werk\/Utility\/Attributes.hpp\"\n#include \"Werk\/Utility\/Latch.hpp\"\n\nnamespace werk\n{\n\nclass Config;\nclass Configurable;\n\n\/**\n * Adapter for the Config class that allows keys to be read from a number of scopes,\n * allowing for cascading configurations.\n *\/\nclass ScopedConfig\n{\npublic:\n\tScopedConfig(Config &config) : _config(config) { }\n\tScopedConfig(Config &config, const std::string &scope) : ScopedConfig(config)\n\t{\n\t\t_scopes.push_back(scope);\n\t}\n\tScopedConfig(Config &config, const std::string &scope1, const std::string scope2) :\n\t\tScopedConfig(config)\n\t{\n\t\t_scopes.push_back(scope1);\n\t\t_scopes.push_back(scope2);\n\t}\n\tScopedConfig(Config &config, const std::string &scope1, const std::string scope2, const std::string scope3) :\n\t\tScopedConfig(config)\n\t{\n\t\t_scopes.push_back(scope1);\n\t\t_scopes.push_back(scope2);\n\t\t_scopes.push_back(scope3);\n\t}\n\tScopedConfig(Config &config, const std::string &scope1, const std::string scope2, const std::string scope3, const std::string scope4) :\n\t\tScopedConfig(config)\n\t{\n\t\t_scopes.push_back(scope1);\n\t\t_scopes.push_back(scope2);\n\t\t_scopes.push_back(scope3);\n\t\t_scopes.push_back(scope4);\n\t}\n\n\t\/\/Accessors\n\tCHECKED std::vector<std::string> &scopes() { return _scopes; }\n\tCHECKED const std::vector<std::string> &scopes() const { return _scopes; }\n\n\t\/\/Base config accessors\n\tvoid addConfigurable(Configurable *configurable);\n\n\t\/\/Basic types\n\tCHECKED const char *getString(const std::string &key, const char *defaultValue=nullptr, const char *help=nullptr) const;\n\tCHECKED bool getBool(const std::string &key, bool defaultValue=false, const char *help=nullptr) const;\n\tCHECKED double getDouble(const std::string &key, double defaultValue=0, const char *help=nullptr) const;\n\tCHECKED int64_t getInt64(const std::string &key, int64_t defaultValue=0, const char *help=nullptr) const;\n\tCHECKED uint64_t getUint64(const std::string &key, uint64_t defaultValue=0, const char *help=nullptr) const;\n\tCHECKED uint64_t getStorageAmount(const std::string &key, uint64_t defaultValue=0, const char *help=nullptr) const;\n\tCHECKED uint64_t getTimeAmount(const std::string &key, uint64_t defaultValue=0, const char *help=nullptr) const;\n\n\t\/\/List types\n\tconst char *getStrings(const std::string &key, std::vector<std::string> &values,\n\t\tconst char *defaultValue=nullptr, const char *help=nullptr, const char *delimiters=\",\") const;\n\nprotected:\n\t\/\/Config\n\tConfig &_config;\n\tstd::vector<std::string> _scopes;\n\n\tvoid findScopedKey(const std::string &key, std::string &specificKey, std::string &foundKey) const;\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"CppUnitTest.h\"\n#include <string>\n#include <vector>\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\n\nnamespace algo\n{\n struct token\n {\n enum toktype { root_node, named_node, edge_name };\n toktype type;\n string name;\n };\n\n bool operator==(const token& lhs, const token& rhs)\n {\n return true;\n }\n\n struct ascii_tree\n {\n static vector<token> tokenize(const string& s)\n {\n enum { none, open_square_brace, asterisk, edge_name } prev = none;\n\n for (auto ch : s)\n {\n if (ch == '[')\n {\n prev = open_square_brace;\n }\n else if (ch == ']')\n {\n if (prev == asterisk)\n {\n token newtok = { token::root_node, \"\" };\n return vector<token>(1, newtok);\n }\n else\n {\n string name = s.substr(1, s.size() - 2);\n token newtok = { token::named_node, name };\n return vector<token>(1, newtok);\n }\n }\n else if (ch == '*')\n {\n prev = asterisk;\n }\n else\n {\n if (prev == none)\n {\n prev = edge_name;\n }\n }\n }\n\n return (prev == edge_name)\n ? vector<token>(1, token { token::edge_name, s })\n : vector<token>();\n }\n };\n}\n\nnamespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework\n{\n template<>\n wstring ToString<algo::token::toktype>(const algo::token::toktype& type)\n {\n switch (type)\n {\n case algo::token::root_node:\n return L\"root_node\";\n case algo::token::named_node:\n return L\"named_node\";\n case algo::token::edge_name:\n return L\"edge_name\";\n default:\n return L\"unknown token\";\n }\n }\n}}}\n\nnamespace algo { namespace spec\n{\n\tTEST_CLASS(can_recognize_ascii_tree_tokens)\n\t{\n\tpublic:\n\t\t\n TEST_METHOD(should_not_recognize_any_tokens_in_an_empty_string)\n {\n auto tokens = ascii_tree::tokenize(\"\");\n Assert::IsTrue(tokens.empty());\n }\n\n\t\tTEST_METHOD(should_recognize_a_root_node)\n\t\t{\n auto tokens = ascii_tree::tokenize(\"[*]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"a\");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n };\n}}\n<commit_msg>recognize a horizontal edge<commit_after>#include \"CppUnitTest.h\"\n#include <string>\n#include <vector>\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\n\nnamespace algo\n{\n struct token\n {\n enum toktype { root_node, named_node, edge_name, horizontal_edge };\n toktype type;\n string name;\n };\n\n bool operator==(const token& lhs, const token& rhs)\n {\n return true;\n }\n\n struct ascii_tree\n {\n static vector<token> tokenize(const string& s)\n {\n enum { none, open_square_brace, asterisk, dash, edge_name } prev = none;\n\n for (auto ch : s)\n {\n if (ch == '[')\n {\n prev = open_square_brace;\n }\n else if (ch == ']')\n {\n if (prev == asterisk)\n {\n token newtok = { token::root_node, \"\" };\n return vector<token>(1, newtok);\n }\n else\n {\n string name = s.substr(1, s.size() - 2);\n token newtok = { token::named_node, name };\n return vector<token>(1, newtok);\n }\n }\n else if (ch == '*')\n {\n prev = asterisk;\n }\n else if (ch == '-')\n {\n if (prev == dash)\n {\n string name = s.substr(2, s.size() - 4);\n token newtok = { token::horizontal_edge, name };\n return vector<token>(1, newtok);\n }\n prev = dash;\n }\n else\n {\n if (prev == none)\n {\n prev = edge_name;\n }\n }\n }\n\n return (prev == edge_name)\n ? vector<token>(1, token { token::edge_name, s })\n : vector<token>();\n }\n };\n}\n\nnamespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework\n{\n template<>\n wstring ToString<algo::token::toktype>(const algo::token::toktype& type)\n {\n switch (type)\n {\n case algo::token::root_node:\n return L\"root_node\";\n case algo::token::named_node:\n return L\"named_node\";\n case algo::token::edge_name:\n return L\"edge_name\";\n case algo::token::horizontal_edge:\n return L\"horizontal_edge\";\n default:\n return L\"unknown token\";\n }\n }\n}}}\n\nnamespace algo { namespace spec\n{\n\tTEST_CLASS(can_recognize_ascii_tree_tokens)\n\t{\n\tpublic:\n\t\t\n TEST_METHOD(should_not_recognize_any_tokens_in_an_empty_string)\n {\n auto tokens = ascii_tree::tokenize(\"\");\n Assert::IsTrue(tokens.empty());\n }\n\n\t\tTEST_METHOD(should_recognize_a_root_node)\n\t\t{\n auto tokens = ascii_tree::tokenize(\"[*]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"a\");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"--a--\");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n };\n}}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- coding: us-ascii-unix -*-\n\/\/ Copyright 2012 Lukas Kemmer\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License. You\n\/\/ 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\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#include \"wx\/textctrl.h\" \/\/ for wxEVT_TEXT_ENTER and such\n#include \"wx\/sizer.h\"\n#include \"wx\/spinctrl.h\"\n#include \"gui\/events.hh\"\n#include \"gui\/spin-ctrl.hh\"\n#include \"util-wx\/bind-event.hh\"\n#include \"util-wx\/fwd-bind.hh\"\n#include \"util-wx\/fwd-wx.hh\"\n#include \"util-wx\/layout-wx.hh\"\n#include \"util\/convenience.hh\"\n\nnamespace faint{\n\n\/\/ Fixme: The controls in this class file duplicate eachother a lot.\n\nclass FocusRelayingSpinCtrl : public wxSpinCtrl{\npublic:\n FocusRelayingSpinCtrl(wxWindow* parent, wxSize size) :\n wxSpinCtrl(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, size,\n wxSP_ARROW_KEYS | wxTE_PROCESS_ENTER)\n {\n events::on_set_focus(this, [this](){\n wxCommandEvent newEvent(EVT_FAINT_SetFocusEntryControl, wxID_ANY);\n newEvent.SetEventObject(this);\n GetEventHandler()->ProcessEvent(newEvent);\n });\n\n events::on_kill_focus(this, [this](){\n wxCommandEvent newEvent(EVT_FAINT_KillFocusEntryControl, wxID_ANY);\n newEvent.SetEventObject(this);\n GetEventHandler()->ProcessEvent(newEvent);\n });\n }\n};\n\nclass FocusRelayingSpinCtrlDouble : public wxSpinCtrlDouble{\npublic:\n FocusRelayingSpinCtrlDouble(wxWindow* parent, wxSize size) :\n wxSpinCtrlDouble(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, size,\n wxSP_ARROW_KEYS | wxTE_PROCESS_ENTER)\n {\n events::on_set_focus(this, [this](){\n wxCommandEvent newEvent(EVT_FAINT_SetFocusEntryControl, wxID_ANY);\n newEvent.SetEventObject(this);\n GetEventHandler()->ProcessEvent(newEvent);\n });\n\n events::on_kill_focus(this, [this](){\n wxCommandEvent newEvent(EVT_FAINT_KillFocusEntryControl, wxID_ANY);\n newEvent.SetEventObject(this);\n GetEventHandler()->ProcessEvent(newEvent);\n });\n }\n};\n\nclass IntSizeControl : public IntSettingCtrl{\npublic:\n IntSizeControl(wxWindow* parent,\n wxSize size,\n const IntSetting& setting,\n int value,\n const std::string& label) \/\/ Fixme: Why std::string?\n : IntSettingCtrl(parent, setting),\n m_changed(false)\n {\n auto sizer = new wxBoxSizer(wxVERTICAL);\n if (label.size() > 0){\n layout::add(sizer, create_label(this, label.c_str()));\n }\n m_spinCtrl = new FocusRelayingSpinCtrl(this, size);\n m_spinCtrl->SetValue(value);\n m_spinCtrl->SetRange(1, 255);\n m_spinCtrl->SetBackgroundColour(wxColour(255, 255, 255));\n sizer->Add(m_spinCtrl, 0, wxALIGN_CENTER_HORIZONTAL);\n SetSizerAndFit(sizer);\n\n events::on_idle(this, [this](){\n if (then_false(m_changed)){\n SendChangeEvent();\n }\n });\n\n bind_fwd(this, wxEVT_SPINCTRL,\n [this](wxSpinEvent& event){\n event.Skip();\n SendChangeEvent();\n });\n\n bind(this, wxEVT_TEXT_ENTER,\n [this](){\n SendChangeEvent();\n });\n }\n\n int GetValue() const override{\n return m_spinCtrl->GetValue();\n }\n\n void SetValue(int value) override{\n m_spinCtrl->SetValue(value);\n }\n\nprivate:\n bool m_changed;\n wxSpinCtrl* m_spinCtrl;\n};\n\nIntSettingCtrl* create_int_spinner(wxWindow* parent, const wxSize& size,\n const IntSetting& setting, int value, const std::string& label)\n{\n return new IntSizeControl(parent, size, setting, value, label);\n}\n\nclass FloatSizeControl : public FloatSettingControl{\npublic:\n FloatSizeControl(wxWindow* parent, wxSize size, const FloatSetting& setting,\n coord value, const std::string& label)\n : FloatSettingControl(parent, setting),\n m_changed(false)\n {\n auto sizer = new wxBoxSizer(wxVERTICAL);\n if (label.size() > 0){\n layout::add(sizer, create_label(this, label.c_str()));\n }\n m_spinCtrl = new wxSpinCtrlDouble(this, wxID_ANY, wxEmptyString,\n wxDefaultPosition, size, wxSP_ARROW_KEYS | wxTE_PROCESS_ENTER);\n m_spinCtrl->SetValue(value);\n m_spinCtrl->SetRange(0.1, 255);\n m_spinCtrl->SetBackgroundColour(wxColour(255, 255, 255));\n\n sizer->Add(m_spinCtrl, 0, wxALIGN_CENTER_HORIZONTAL);\n SetSizerAndFit(sizer);\n\n events::on_idle(this, [this](){\n if (then_false(m_changed)){\n SendChangeEvent();\n }\n });\n\n bind_fwd(this, wxEVT_SPINCTRLDOUBLE,\n [this](wxSpinDoubleEvent& event){\n m_changed = true;\n event.Skip();\n });\n\n bind(this, wxEVT_TEXT_ENTER,\n [this](){\n SendChangeEvent();\n });\n }\n\n coord GetValue() const override{\n return m_spinCtrl->GetValue();\n }\n\n void SetValue(coord value) override{\n m_spinCtrl->SetValue(value);\n }\n\nprivate:\n bool m_changed;\n wxSpinCtrlDouble* m_spinCtrl;\n};\n\nFloatSettingControl* create_float_spinner(wxWindow* parent, const wxSize& size,\n const FloatSetting& setting, coord value, const std::string& label)\n{\n return new FloatSizeControl(parent, size, setting, value, label);\n}\n\nclass SemiFloatSizeControl : public FloatSettingControl{\npublic:\n SemiFloatSizeControl(wxWindow* parent, wxSize size, const FloatSetting& setting,\n coord value, const std::string& label)\n : FloatSettingControl(parent, setting)\n {\n auto sizer = new wxBoxSizer(wxVERTICAL);\n if (label.size() > 0){\n layout::add(sizer, create_label(this, label.c_str()));\n }\n m_spinCtrl = new FocusRelayingSpinCtrl(this, size);\n m_spinCtrl->SetValue(static_cast<int>(value));\n m_spinCtrl->SetRange(1, 255);\n m_spinCtrl->SetBackgroundColour(wxColour(255, 255, 255));\n m_lastValue = static_cast<int>(value);\n sizer->Add(m_spinCtrl, 0, wxALIGN_CENTER_HORIZONTAL);\n SetSizerAndFit(sizer);\n\n bind_fwd(this, wxEVT_SPINCTRL,\n [this](wxSpinEvent& event){\n m_changed = true;\n event.Skip();\n });\n\n bind(this, wxEVT_TEXT_ENTER,\n [this](){\n m_lastValue = m_spinCtrl->GetValue();\n SendChangeEvent();\n });\n\n events::on_idle(this, [this](){\n if (then_false(m_changed)){\n m_lastValue = m_spinCtrl->GetValue();\n SendChangeEvent();\n }\n });\n\n bind_fwd(this, EVT_FAINT_KillFocusEntryControl,\n [this](wxEvent& event){\n event.Skip();\n if (m_lastValue != m_spinCtrl->GetValue()){\n SendChangeEvent();\n }\n });\n }\n\n coord GetValue() const override{\n return static_cast<coord>(m_spinCtrl->GetValue());\n }\n\n virtual void SetValue(coord value) override{\n m_spinCtrl->SetValue(static_cast<int>(value));\n }\n\nprivate:\n wxSpinCtrl* m_spinCtrl;\n bool m_changed;\n int m_lastValue;\n};\n\nFloatSettingControl* create_semi_float_spinner(wxWindow* parent, const wxSize& size,\n const FloatSetting& setting, coord value, const std::string& label)\n{\n return new SemiFloatSizeControl(parent, size, setting, value, label);\n}\n\n} \/\/ namespace\n<commit_msg>Reduced duplication in spin-ctrl.cpp.<commit_after>\/\/ -*- coding: us-ascii-unix -*-\n\/\/ Copyright 2012 Lukas Kemmer\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License. You\n\/\/ 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\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#include \"wx\/textctrl.h\" \/\/ for wxEVT_TEXT_ENTER and such\n#include \"wx\/sizer.h\"\n#include \"wx\/spinctrl.h\"\n#include \"gui\/events.hh\"\n#include \"gui\/spin-ctrl.hh\"\n#include \"util-wx\/bind-event.hh\"\n#include \"util-wx\/fwd-bind.hh\"\n#include \"util-wx\/fwd-wx.hh\"\n#include \"util-wx\/layout-wx.hh\"\n#include \"util\/convenience.hh\"\n\nnamespace faint{\n\n\/\/ Fixme: The controls in this class file duplicate eachother a lot.\n\ntemplate<typename WXCTRL_T>\nclass FocusRelayingCtrl : public WXCTRL_T{\npublic:\n FocusRelayingCtrl(wxWindow* parent, const wxSize& size)\n : WXCTRL_T(parent,\n wxID_ANY,\n wxEmptyString,\n wxDefaultPosition,\n size,\n wxSP_ARROW_KEYS | wxTE_PROCESS_ENTER)\n {\n events::on_set_focus(this, [this](){\n wxCommandEvent newEvent(EVT_FAINT_SetFocusEntryControl, wxID_ANY);\n newEvent.SetEventObject(this);\n GetEventHandler()->ProcessEvent(newEvent);\n });\n\n events::on_kill_focus(this, [this](){\n wxCommandEvent newEvent(EVT_FAINT_KillFocusEntryControl, wxID_ANY);\n newEvent.SetEventObject(this);\n GetEventHandler()->ProcessEvent(newEvent);\n });\n }\n};\n\nusing FocusRelayingSpinCtrl = FocusRelayingCtrl<wxSpinCtrl>;\nusing FocusRelayingSpinCtrlDouble = FocusRelayingCtrl<wxSpinCtrlDouble>;\n\nclass IntSizeControl : public IntSettingCtrl{\npublic:\n IntSizeControl(wxWindow* parent,\n wxSize size,\n const IntSetting& setting,\n int value,\n const std::string& label) \/\/ Fixme: Why std::string?\n : IntSettingCtrl(parent, setting),\n m_changed(false)\n {\n auto sizer = new wxBoxSizer(wxVERTICAL);\n if (label.size() > 0){\n layout::add(sizer, create_label(this, label.c_str()));\n }\n m_spinCtrl = new FocusRelayingSpinCtrl(this, size);\n m_spinCtrl->SetValue(value);\n m_spinCtrl->SetRange(1, 255);\n m_spinCtrl->SetBackgroundColour(wxColour(255, 255, 255));\n sizer->Add(m_spinCtrl, 0, wxALIGN_CENTER_HORIZONTAL);\n SetSizerAndFit(sizer);\n\n events::on_idle(this, [this](){\n if (then_false(m_changed)){\n SendChangeEvent();\n }\n });\n\n bind_fwd(this, wxEVT_SPINCTRL,\n [this](wxSpinEvent& event){\n event.Skip();\n SendChangeEvent();\n });\n\n bind(this, wxEVT_TEXT_ENTER,\n [this](){\n SendChangeEvent();\n });\n }\n\n int GetValue() const override{\n return m_spinCtrl->GetValue();\n }\n\n void SetValue(int value) override{\n m_spinCtrl->SetValue(value);\n }\n\nprivate:\n bool m_changed;\n wxSpinCtrl* m_spinCtrl;\n};\n\nIntSettingCtrl* create_int_spinner(wxWindow* parent, const wxSize& size,\n const IntSetting& setting, int value, const std::string& label)\n{\n return new IntSizeControl(parent, size, setting, value, label);\n}\n\nclass FloatSizeControl : public FloatSettingControl{\npublic:\n FloatSizeControl(wxWindow* parent, wxSize size, const FloatSetting& setting,\n coord value, const std::string& label)\n : FloatSettingControl(parent, setting),\n m_changed(false)\n {\n auto sizer = new wxBoxSizer(wxVERTICAL);\n if (label.size() > 0){\n layout::add(sizer, create_label(this, label.c_str()));\n }\n m_spinCtrl = new wxSpinCtrlDouble(this, wxID_ANY, wxEmptyString,\n wxDefaultPosition, size, wxSP_ARROW_KEYS | wxTE_PROCESS_ENTER);\n m_spinCtrl->SetValue(value);\n m_spinCtrl->SetRange(0.1, 255);\n m_spinCtrl->SetBackgroundColour(wxColour(255, 255, 255));\n\n sizer->Add(m_spinCtrl, 0, wxALIGN_CENTER_HORIZONTAL);\n SetSizerAndFit(sizer);\n\n events::on_idle(this, [this](){\n if (then_false(m_changed)){\n SendChangeEvent();\n }\n });\n\n bind_fwd(this, wxEVT_SPINCTRLDOUBLE,\n [this](wxSpinDoubleEvent& event){\n m_changed = true;\n event.Skip();\n });\n\n bind(this, wxEVT_TEXT_ENTER,\n [this](){\n SendChangeEvent();\n });\n }\n\n coord GetValue() const override{\n return m_spinCtrl->GetValue();\n }\n\n void SetValue(coord value) override{\n m_spinCtrl->SetValue(value);\n }\n\nprivate:\n bool m_changed;\n wxSpinCtrlDouble* m_spinCtrl;\n};\n\nFloatSettingControl* create_float_spinner(wxWindow* parent, const wxSize& size,\n const FloatSetting& setting, coord value, const std::string& label)\n{\n return new FloatSizeControl(parent, size, setting, value, label);\n}\n\nclass SemiFloatSizeControl : public FloatSettingControl{\npublic:\n SemiFloatSizeControl(wxWindow* parent, wxSize size, const FloatSetting& setting,\n coord value, const std::string& label)\n : FloatSettingControl(parent, setting)\n {\n auto sizer = new wxBoxSizer(wxVERTICAL);\n if (label.size() > 0){\n layout::add(sizer, create_label(this, label.c_str()));\n }\n m_spinCtrl = new FocusRelayingSpinCtrl(this, size);\n m_spinCtrl->SetValue(static_cast<int>(value));\n m_spinCtrl->SetRange(1, 255);\n m_spinCtrl->SetBackgroundColour(wxColour(255, 255, 255));\n m_lastValue = static_cast<int>(value);\n sizer->Add(m_spinCtrl, 0, wxALIGN_CENTER_HORIZONTAL);\n SetSizerAndFit(sizer);\n\n bind_fwd(this, wxEVT_SPINCTRL,\n [this](wxSpinEvent& event){\n m_changed = true;\n event.Skip();\n });\n\n bind(this, wxEVT_TEXT_ENTER,\n [this](){\n m_lastValue = m_spinCtrl->GetValue();\n SendChangeEvent();\n });\n\n events::on_idle(this, [this](){\n if (then_false(m_changed)){\n m_lastValue = m_spinCtrl->GetValue();\n SendChangeEvent();\n }\n });\n\n bind_fwd(this, EVT_FAINT_KillFocusEntryControl,\n [this](wxEvent& event){\n event.Skip();\n if (m_lastValue != m_spinCtrl->GetValue()){\n SendChangeEvent();\n }\n });\n }\n\n coord GetValue() const override{\n return static_cast<coord>(m_spinCtrl->GetValue());\n }\n\n virtual void SetValue(coord value) override{\n m_spinCtrl->SetValue(static_cast<int>(value));\n }\n\nprivate:\n wxSpinCtrl* m_spinCtrl;\n bool m_changed;\n int m_lastValue;\n};\n\nFloatSettingControl* create_semi_float_spinner(wxWindow* parent,\n const wxSize& size,\n const FloatSetting& setting,\n coord value,\n const std::string& label)\n{\n return new SemiFloatSizeControl(parent, size, setting, value, label);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ Unit Tests\n\/\/\n\/\/ Created by Evan McCartney-Melstad on 12\/31\/14.\n\/\/ Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.\n\/\/\n\n#define CATCH_CONFIG_MAIN \/\/ This tells Catch to provide a main() - only do this in one cpp file\n#include \"..\/cPWP\/generateSimulatedData.h\"\n#include \"..\/cPWP\/bamsToPWP.h\"\n#include \"catch.hpp\"\n#include <string>\n\n\n\n\nTEST_CASE( \"Simulated reads are generated\", \"[generateReads]\" ) {\n \/\/ Make sure that the read simulation finishes\n REQUIRE( generateReadsAndMap(1, 0.01, \"0.0\", \"300\", \"50\", \"100000\", \"100\", \"1234\", \"scaffold_0.fasta\") == 0);\n\n}\n\n\nTEST_CASE( \"Run ANGSD on simulated reads\", \"[runANGSD]\" ) {\n REQUIRE( runANGSDforReadCounts(\"bamlist.txt\", \"angsdOut\", \"10\", \"angsdOutLog.txt\") == 0);\n}\n\nTEST_CASE( \"Convert ANGSD read counts to unsigned chars for major and minor counts\", \"[convertCountsToBinary]\") {\n REQUIRE( convertANGSDcountsToBinary(\"angsdOut\", \"angsdOut.readCounts.binary\", 2, 5000) == 0); \/\/ 2 individuals, not 1, because generateReadsAndMap actually generates n+1 individuals, since one individual is identical to the reference genome. And 5000 as a max because we don't want to exclude any loci for this test\n}\n\nTEST_CASE( \"Calculate PWP from the binary representations of the ANGSD readcounts\", \"[calcPWP]\") {\n REQUIRE( calcPWPfromBinaryFile (\"angsdOut.readCounts.binary\", 70000, 2) == 0);\n}\n<commit_msg>Troubleshooting<commit_after>\/\/\n\/\/ main.cpp\n\/\/ Unit Tests\n\/\/\n\/\/ Created by Evan McCartney-Melstad on 12\/31\/14.\n\/\/ Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.\n\/\/\n\n#define CATCH_CONFIG_MAIN \/\/ This tells Catch to provide a main() - only do this in one cpp file\n#include \"..\/cPWP\/generateSimulatedData.h\"\n#include \"..\/cPWP\/bamsToPWP.h\"\n#include \"catch.hpp\"\n#include <string>\n\n\n\n\nTEST_CASE( \"Simulated reads are generated\", \"[generateReads]\" ) {\n \/\/ Make sure that the read simulation finishes\n REQUIRE( generateReadsAndMap(1, 0.01, \"0.0\", \"300\", \"50\", \"1000000\", \"100\", \"1234\", \"scaffold_0.fasta\") == 0);\n\n}\n\n\nTEST_CASE( \"Run ANGSD on simulated reads\", \"[runANGSD]\" ) {\n REQUIRE( runANGSDforReadCounts(\"bamlist.txt\", \"angsdOut\", \"10\", \"angsdOutLog.txt\") == 0);\n}\n\nTEST_CASE( \"Convert ANGSD read counts to unsigned chars for major and minor counts\", \"[convertCountsToBinary]\") {\n REQUIRE( convertANGSDcountsToBinary(\"angsdOut\", \"angsdOut.readCounts.binary\", 2, 5000) == 0); \/\/ 2 individuals, not 1, because generateReadsAndMap actually generates n+1 individuals, since one individual is identical to the reference genome. And 5000 as a max because we don't want to exclude any loci for this test\n}\n\nTEST_CASE( \"Calculate PWP from the binary representations of the ANGSD readcounts\", \"[calcPWP]\") {\n REQUIRE( calcPWPfromBinaryFile (\"angsdOut.readCounts.binary\", 70000, 2) == 0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 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 \"ash\/content\/display\/display_color_manager_chromeos.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/format_macros.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"chromeos\/chromeos_paths.h\"\n#include \"chromeos\/chromeos_switches.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"third_party\/qcms\/src\/qcms.h\"\n#include \"ui\/display\/types\/display_snapshot.h\"\n#include \"ui\/display\/types\/gamma_ramp_rgb_entry.h\"\n#include \"ui\/display\/types\/native_display_delegate.h\"\n#include \"ui\/gfx\/display.h\"\n#include \"ui\/gfx\/screen.h\"\n\nusing content::BrowserThread;\n\nnamespace ash {\n\nnamespace {\n\nbool ParseFile(const base::FilePath& path,\n DisplayColorManager::ColorCalibrationData* data) {\n qcms_profile* display_profile = qcms_profile_from_path(path.value().c_str());\n\n if (!display_profile) {\n LOG(WARNING) << \"Unable to load ICC file: \" << path.value();\n return false;\n }\n\n size_t vcgt_channel_length =\n qcms_profile_get_vcgt_channel_length(display_profile);\n if (!vcgt_channel_length) {\n LOG(WARNING) << \"No vcgt table in ICC file: \" << path.value();\n return false;\n }\n\n std::vector<uint16_t> vcgt_data;\n vcgt_data.resize(vcgt_channel_length * 3);\n if (!qcms_profile_get_vcgt_rgb_channels(display_profile, &vcgt_data[0])) {\n LOG(WARNING) << \"Unable to get vcgt data\";\n qcms_profile_release(display_profile);\n return false;\n }\n\n data->lut.resize(vcgt_channel_length);\n for (size_t i = 0; i < vcgt_channel_length; ++i) {\n data->lut[i].r = vcgt_data[i];\n data->lut[i].g = vcgt_data[vcgt_channel_length + i];\n data->lut[i].b = vcgt_data[(vcgt_channel_length * 2) + i];\n }\n qcms_profile_release(display_profile);\n return true;\n}\n\nbase::FilePath PathForDisplaySnapshot(const ui::DisplaySnapshot* snapshot) {\n if (gfx::Display::IsInternalDisplayId(snapshot->display_id())) {\n const base::CommandLine* command_line =\n base::CommandLine::ForCurrentProcess();\n if (command_line->HasSwitch(\n chromeos::switches::kInternalDisplayColorProfileFile)) {\n const base::FilePath& path = command_line->GetSwitchValuePath(\n chromeos::switches::kInternalDisplayColorProfileFile);\n return base::FilePath(path);\n }\n }\n\n base::FilePath path;\n CHECK(\n PathService::Get(chromeos::DIR_DEVICE_COLOR_CALIBRATION_PROFILES, &path));\n path = path.Append(\n base::StringPrintf(\"%08\" PRIx64 \".icc\", snapshot->product_id()));\n return path;\n}\n\n} \/\/ namespace\n\nDisplayColorManager::DisplayColorManager(ui::DisplayConfigurator* configurator)\n : configurator_(configurator) {\n configurator_->AddObserver(this);\n}\n\nDisplayColorManager::~DisplayColorManager() {\n configurator_->RemoveObserver(this);\n STLDeleteValues(&calibration_map_);\n}\n\nvoid DisplayColorManager::OnDisplayModeChanged(\n const ui::DisplayConfigurator::DisplayStateList& display_states) {\n for (const ui::DisplaySnapshot* state : display_states) {\n if (calibration_map_[state->product_id()]) {\n ApplyDisplayColorCalibration(state->display_id(), state->product_id());\n } else {\n if (state->product_id() != ui::DisplaySnapshot::kInvalidProductID)\n LoadCalibrationForDisplay(state);\n }\n }\n}\n\nvoid DisplayColorManager::ApplyDisplayColorCalibration(int64_t display_id,\n int64_t product_id) {\n if (calibration_map_.find(product_id) != calibration_map_.end()) {\n ColorCalibrationData* ramp = calibration_map_[product_id];\n if (!configurator_->SetGammaRamp(display_id, ramp->lut))\n LOG(WARNING) << \"Error applying gamma ramp\";\n }\n}\n\nvoid DisplayColorManager::LoadCalibrationForDisplay(\n const ui::DisplaySnapshot* display) {\n if (display->display_id() == gfx::Display::kInvalidDisplayID) {\n LOG(WARNING) << \"Trying to load calibration data for invalid display id\";\n return;\n }\n\n base::FilePath path = PathForDisplaySnapshot(display);\n VLOG(1) << \"Checking ICC file \" << path.value()\n << \" for display id: \" << display->display_id()\n << \" with product id: \" << display->product_id();\n if (!base::PathExists(path)) \/\/ No icc file for this display.\n return;\n\n scoped_ptr<ColorCalibrationData> data(new ColorCalibrationData());\n base::Callback<bool(void)> request(\n base::Bind(&ParseFile, path, base::Unretained(data.get())));\n base::PostTaskAndReplyWithResult(\n BrowserThread::GetBlockingPool(), FROM_HERE, request,\n base::Bind(&DisplayColorManager::UpdateCalibrationData, AsWeakPtr(),\n display->display_id(), display->product_id(),\n base::Passed(data.Pass())));\n}\n\nvoid DisplayColorManager::UpdateCalibrationData(\n int64_t display_id,\n int64_t product_id,\n scoped_ptr<ColorCalibrationData> data,\n bool success) {\n DCHECK_CURRENTLY_ON(BrowserThread::UI);\n if (success) {\n \/\/ The map takes over ownership of the underlying memory.\n calibration_map_[product_id] = data.release();\n ApplyDisplayColorCalibration(display_id, product_id);\n }\n}\n\nDisplayColorManager::ColorCalibrationData::ColorCalibrationData() {\n}\n\nDisplayColorManager::ColorCalibrationData::~ColorCalibrationData() {\n}\n\n} \/\/ namespace ash\n<commit_msg>Revert of Don't try to load non-existent icc file (patchset #2 id:20001 of https:\/\/codereview.chromium.org\/1302273006\/ )<commit_after>\/\/ Copyright 2015 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 \"ash\/content\/display\/display_color_manager_chromeos.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/format_macros.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"chromeos\/chromeos_paths.h\"\n#include \"chromeos\/chromeos_switches.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"third_party\/qcms\/src\/qcms.h\"\n#include \"ui\/display\/types\/display_snapshot.h\"\n#include \"ui\/display\/types\/gamma_ramp_rgb_entry.h\"\n#include \"ui\/display\/types\/native_display_delegate.h\"\n#include \"ui\/gfx\/display.h\"\n#include \"ui\/gfx\/screen.h\"\n\nusing content::BrowserThread;\n\nnamespace ash {\n\nnamespace {\n\nbool ParseFile(const base::FilePath& path,\n DisplayColorManager::ColorCalibrationData* data) {\n qcms_profile* display_profile = qcms_profile_from_path(path.value().c_str());\n\n if (!display_profile) {\n LOG(WARNING) << \"Unable to load ICC file: \" << path.value();\n return false;\n }\n\n size_t vcgt_channel_length =\n qcms_profile_get_vcgt_channel_length(display_profile);\n if (!vcgt_channel_length) {\n LOG(WARNING) << \"No vcgt table in ICC file: \" << path.value();\n return false;\n }\n\n std::vector<uint16_t> vcgt_data;\n vcgt_data.resize(vcgt_channel_length * 3);\n if (!qcms_profile_get_vcgt_rgb_channels(display_profile, &vcgt_data[0])) {\n LOG(WARNING) << \"Unable to get vcgt data\";\n qcms_profile_release(display_profile);\n return false;\n }\n\n data->lut.resize(vcgt_channel_length);\n for (size_t i = 0; i < vcgt_channel_length; ++i) {\n data->lut[i].r = vcgt_data[i];\n data->lut[i].g = vcgt_data[vcgt_channel_length + i];\n data->lut[i].b = vcgt_data[(vcgt_channel_length * 2) + i];\n }\n qcms_profile_release(display_profile);\n return true;\n}\n\nbase::FilePath PathForDisplaySnapshot(const ui::DisplaySnapshot* snapshot) {\n if (gfx::Display::IsInternalDisplayId(snapshot->display_id())) {\n const base::CommandLine* command_line =\n base::CommandLine::ForCurrentProcess();\n if (command_line->HasSwitch(\n chromeos::switches::kInternalDisplayColorProfileFile)) {\n const base::FilePath& path = command_line->GetSwitchValuePath(\n chromeos::switches::kInternalDisplayColorProfileFile);\n return base::FilePath(path);\n }\n }\n\n base::FilePath path;\n CHECK(\n PathService::Get(chromeos::DIR_DEVICE_COLOR_CALIBRATION_PROFILES, &path));\n path = path.Append(\n base::StringPrintf(\"%08\" PRIx64 \".icc\", snapshot->product_id()));\n return path;\n}\n\n} \/\/ namespace\n\nDisplayColorManager::DisplayColorManager(ui::DisplayConfigurator* configurator)\n : configurator_(configurator) {\n configurator_->AddObserver(this);\n}\n\nDisplayColorManager::~DisplayColorManager() {\n configurator_->RemoveObserver(this);\n STLDeleteValues(&calibration_map_);\n}\n\nvoid DisplayColorManager::OnDisplayModeChanged(\n const ui::DisplayConfigurator::DisplayStateList& display_states) {\n for (const ui::DisplaySnapshot* state : display_states) {\n if (calibration_map_[state->product_id()]) {\n ApplyDisplayColorCalibration(state->display_id(), state->product_id());\n } else {\n if (state->product_id() != ui::DisplaySnapshot::kInvalidProductID)\n LoadCalibrationForDisplay(state);\n }\n }\n}\n\nvoid DisplayColorManager::ApplyDisplayColorCalibration(int64_t display_id,\n int64_t product_id) {\n if (calibration_map_.find(product_id) != calibration_map_.end()) {\n ColorCalibrationData* ramp = calibration_map_[product_id];\n if (!configurator_->SetGammaRamp(display_id, ramp->lut))\n LOG(WARNING) << \"Error applying gamma ramp\";\n }\n}\n\nvoid DisplayColorManager::LoadCalibrationForDisplay(\n const ui::DisplaySnapshot* display) {\n if (display->display_id() == gfx::Display::kInvalidDisplayID) {\n LOG(WARNING) << \"Trying to load calibration data for invalid display id\";\n return;\n }\n\n base::FilePath path = PathForDisplaySnapshot(display);\n VLOG(1) << \"Loading ICC file \" << path.value()\n << \" for display id: \" << display->display_id()\n << \" with product id: \" << display->product_id();\n\n scoped_ptr<ColorCalibrationData> data(new ColorCalibrationData());\n base::Callback<bool(void)> request(\n base::Bind(&ParseFile, path, base::Unretained(data.get())));\n base::PostTaskAndReplyWithResult(\n BrowserThread::GetBlockingPool(), FROM_HERE, request,\n base::Bind(&DisplayColorManager::UpdateCalibrationData, AsWeakPtr(),\n display->display_id(), display->product_id(),\n base::Passed(data.Pass())));\n}\n\nvoid DisplayColorManager::UpdateCalibrationData(\n int64_t display_id,\n int64_t product_id,\n scoped_ptr<ColorCalibrationData> data,\n bool success) {\n DCHECK_CURRENTLY_ON(BrowserThread::UI);\n if (success) {\n \/\/ The map takes over ownership of the underlying memory.\n calibration_map_[product_id] = data.release();\n ApplyDisplayColorCalibration(display_id, product_id);\n }\n}\n\nDisplayColorManager::ColorCalibrationData::ColorCalibrationData() {\n}\n\nDisplayColorManager::ColorCalibrationData::~ColorCalibrationData() {\n}\n\n} \/\/ namespace ash\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of CAF, the C++ Actor Framework. See the file LICENSE in\n\/\/ the main distribution directory for license terms and copyright or visit\n\/\/ https:\/\/github.com\/actor-framework\/actor-framework\/blob\/master\/LICENSE.\n\n#pragma once\n\n#include \"caf\/async\/batch.hpp\"\n#include \"caf\/async\/producer.hpp\"\n#include \"caf\/defaults.hpp\"\n#include \"caf\/detail\/type_traits.hpp\"\n#include \"caf\/disposable.hpp\"\n#include \"caf\/error.hpp\"\n#include \"caf\/flow\/coordinator.hpp\"\n#include \"caf\/flow\/subscription.hpp\"\n#include \"caf\/intrusive_ptr.hpp\"\n#include \"caf\/logger.hpp\"\n#include \"caf\/make_counted.hpp\"\n#include \"caf\/ref_counted.hpp\"\n#include \"caf\/span.hpp\"\n#include \"caf\/unit.hpp\"\n\nnamespace caf::flow {\n\n\/\/\/ Handle to a consumer of items.\ntemplate <class T>\nclass observer {\npublic:\n \/\/\/ Internal interface of an `observer`.\n class impl : public disposable::impl {\n public:\n using input_type = T;\n\n virtual void on_subscribe(subscription sub) = 0;\n\n virtual void on_next(span<const T> items) = 0;\n\n virtual void on_complete() = 0;\n\n virtual void on_error(const error& what) = 0;\n\n observer as_observer() noexcept {\n return observer{intrusive_ptr<impl>(this)};\n }\n };\n\n using input_type = T;\n\n explicit observer(intrusive_ptr<impl> pimpl) noexcept\n : pimpl_(std::move(pimpl)) {\n \/\/ nop\n }\n\n observer& operator=(std::nullptr_t) noexcept {\n pimpl_.reset();\n return *this;\n }\n\n observer() noexcept = default;\n observer(observer&&) noexcept = default;\n observer(const observer&) noexcept = default;\n observer& operator=(observer&&) noexcept = default;\n observer& operator=(const observer&) noexcept = default;\n\n disposable as_disposable() const& noexcept {\n return disposable{pimpl_};\n }\n\n disposable as_disposable() && noexcept {\n return disposable{std::move(pimpl_)};\n }\n\n \/\/\/ @pre `valid()`\n void on_complete() {\n pimpl_->on_complete();\n }\n\n \/\/\/ @pre `valid()`\n void on_error(const error& what) {\n pimpl_->on_error(what);\n }\n\n \/\/\/ @pre `valid()`\n void on_subscribe(subscription sub) {\n pimpl_->on_subscribe(std::move(sub));\n }\n\n \/\/\/ @pre `valid()`\n void on_batch(const async::batch& buf) {\n pimpl_->on_batch(buf);\n }\n\n \/\/\/ @pre `valid()`\n void on_next(span<const T> items) {\n pimpl_->on_next(items);\n }\n\n \/\/\/ Creates a new observer from `Impl`.\n template <class Impl, class... Ts>\n [[nodiscard]] static observer make(Ts&&... xs) {\n static_assert(std::is_base_of_v<impl, Impl>);\n return observer{make_counted<Impl>(std::forward<Ts>(xs)...)};\n }\n\n bool valid() const noexcept {\n return pimpl_ != nullptr;\n }\n\n explicit operator bool() const noexcept {\n return valid();\n }\n\n bool operator!() const noexcept {\n return !valid();\n }\n\n impl* ptr() {\n return pimpl_.get();\n }\n\n const impl* ptr() const {\n return pimpl_.get();\n }\n\n const intrusive_ptr<impl>& as_intrusive_ptr() const& noexcept {\n return pimpl_;\n }\n\n intrusive_ptr<impl>&& as_intrusive_ptr() && noexcept {\n return std::move(pimpl_);\n }\n\n void swap(observer& other) {\n pimpl_.swap(other.pimpl_);\n }\n\nprivate:\n intrusive_ptr<impl> pimpl_;\n};\n\ntemplate <class T>\nusing observer_impl = typename observer<T>::impl;\n\n\/\/ -- writing observed values to a buffer --------------------------------------\n\n\/\/\/ Writes observed values to a bounded buffer.\ntemplate <class Buffer>\nclass buffer_writer_impl : public ref_counted,\n public observer_impl<typename Buffer::value_type>,\n public async::producer {\npublic:\n \/\/ -- member types -----------------------------------------------------------\n\n using buffer_ptr = intrusive_ptr<Buffer>;\n\n using value_type = typename Buffer::value_type;\n\n \/\/ -- friends ----------------------------------------------------------------\n\n CAF_INTRUSIVE_PTR_FRIENDS(buffer_writer_impl)\n\n \/\/ -- constructors, destructors, and assignment operators --------------------\n\n buffer_writer_impl(coordinator* ctx, buffer_ptr buf)\n : ctx_(ctx), buf_(std::move(buf)) {\n CAF_ASSERT(ctx_ != nullptr);\n CAF_ASSERT(buf_ != nullptr);\n }\n\n ~buffer_writer_impl() {\n if (buf_)\n buf_->close();\n }\n\n \/\/ -- implementation of disposable::impl -------------------------------------\n\n void dispose() override {\n CAF_LOG_TRACE(\"\");\n on_complete();\n }\n\n bool disposed() const noexcept override {\n return buf_ == nullptr;\n }\n\n void ref_disposable() const noexcept final {\n this->ref();\n }\n\n void deref_disposable() const noexcept final {\n this->deref();\n }\n\n \/\/ -- implementation of observer<T>::impl ------------------------------------\n\n void on_next(span<const value_type> items) override {\n CAF_LOG_TRACE(CAF_ARG(items));\n if (buf_)\n buf_->push(items);\n }\n\n void on_complete() override {\n CAF_LOG_TRACE(\"\");\n if (buf_) {\n buf_->close();\n buf_ = nullptr;\n sub_ = nullptr;\n }\n }\n\n void on_error(const error& what) override {\n CAF_LOG_TRACE(CAF_ARG(what));\n if (buf_) {\n buf_->abort(what);\n buf_ = nullptr;\n sub_ = nullptr;\n }\n }\n\n void on_subscribe(subscription sub) override {\n CAF_LOG_TRACE(\"\");\n if (buf_ && !sub_) {\n CAF_LOG_DEBUG(\"add subscription\");\n sub_ = std::move(sub);\n sub_.request(buf_->capacity());\n } else {\n CAF_LOG_DEBUG(\"already have a subscription or buffer no longer valid\");\n sub.cancel();\n }\n }\n\n \/\/ -- implementation of async::producer: these may get called concurrently ---\n\n void on_consumer_ready() override {\n \/\/ nop\n }\n\n void on_consumer_cancel() override {\n CAF_LOG_TRACE(\"\");\n ctx_->schedule_fn([ptr{strong_ptr()}] {\n CAF_LOG_TRACE(\"\");\n ptr->on_cancel();\n });\n }\n\n void on_consumer_demand(size_t demand) override {\n CAF_LOG_TRACE(CAF_ARG(demand));\n ctx_->schedule_fn([ptr{strong_ptr()}, demand] { \/\/\n CAF_LOG_TRACE(CAF_ARG(demand));\n ptr->on_demand(demand);\n });\n }\n\n void ref_producer() const noexcept final {\n this->ref();\n }\n\n void deref_producer() const noexcept final {\n this->deref();\n }\n\nprivate:\n void on_demand(size_t n) {\n CAF_LOG_TRACE(CAF_ARG(n));\n if (sub_)\n sub_.request(n);\n }\n\n void on_cancel() {\n CAF_LOG_TRACE(\"\");\n if (sub_) {\n sub_.cancel();\n sub_ = nullptr;\n }\n buf_ = nullptr;\n }\n\n intrusive_ptr<buffer_writer_impl> strong_ptr() {\n return {this};\n }\n\n coordinator_ptr ctx_;\n buffer_ptr buf_;\n subscription sub_;\n};\n\n} \/\/ namespace caf::flow\n\nnamespace caf::detail {\n\ntemplate <class OnNextSignature>\nstruct on_next_trait;\n\ntemplate <class T>\nstruct on_next_trait<void(T)> {\n using value_type = T;\n\n template <class F>\n static void apply(F& f, span<const T> items) {\n for (auto&& item : items)\n f(item);\n }\n};\n\ntemplate <class T>\nstruct on_next_trait<void(const T&)> {\n using value_type = T;\n\n template <class F>\n static void apply(F& f, span<const T> items) {\n for (auto&& item : items)\n f(item);\n }\n};\n\ntemplate <class T>\nstruct on_next_trait<void(span<const T>)> {\n using value_type = T;\n\n template <class F>\n static void apply(F& f, span<const T> items) {\n f(items);\n }\n};\n\ntemplate <class F>\nusing on_next_trait_t\n = on_next_trait<typename get_callable_trait_t<F>::fun_sig>;\n\ntemplate <class F>\nusing on_next_value_type = typename on_next_trait_t<F>::value_type;\n\ntemplate <class OnNext, class OnError = unit_t, class OnComplete = unit_t>\nclass default_observer_impl\n : public ref_counted,\n public flow::observer_impl<on_next_value_type<OnNext>> {\npublic:\n static_assert(std::is_invocable_v<OnError, const error&>);\n\n static_assert(std::is_invocable_v<OnComplete>);\n\n using input_type = on_next_value_type<OnNext>;\n\n CAF_INTRUSIVE_PTR_FRIENDS(default_observer_impl)\n\n explicit default_observer_impl(OnNext&& on_next_fn)\n : on_next_(std::move(on_next_fn)) {\n \/\/ nop\n }\n\n default_observer_impl(OnNext&& on_next_fn, OnError&& on_error_fn)\n : on_next_(std::move(on_next_fn)), on_error_(std::move(on_error_fn)) {\n \/\/ nop\n }\n\n default_observer_impl(OnNext&& on_next_fn, OnError&& on_error_fn,\n OnComplete&& on_complete_fn)\n : on_next_(std::move(on_next_fn)),\n on_error_(std::move(on_error_fn)),\n on_complete_(std::move(on_complete_fn)) {\n \/\/ nop\n }\n\n void ref_disposable() const noexcept final {\n this->ref();\n }\n\n void deref_disposable() const noexcept final {\n this->deref();\n }\n\n void on_next(span<const input_type> items) override {\n if (!completed_) {\n on_next_trait_t<OnNext>::apply(on_next_, items);\n sub_.request(items.size());\n }\n }\n\n void on_error(const error& what) override {\n if (!completed_) {\n on_error_(what);\n sub_ = nullptr;\n completed_ = true;\n }\n }\n\n void on_complete() override {\n if (!completed_) {\n on_complete_();\n sub_ = nullptr;\n completed_ = true;\n }\n }\n\n void on_subscribe(flow::subscription sub) override {\n if (!completed_ && !sub_) {\n sub_ = std::move(sub);\n sub_.request(defaults::flow::buffer_size);\n } else {\n sub.cancel();\n }\n }\n\n void dispose() override {\n if (!completed_) {\n on_complete_();\n if (sub_) {\n sub_.cancel();\n sub_ = nullptr;\n }\n completed_ = true;\n }\n }\n\n bool disposed() const noexcept override {\n return completed_;\n }\n\nprivate:\n bool completed_ = false;\n OnNext on_next_;\n OnError on_error_;\n OnComplete on_complete_;\n flow::subscription sub_;\n};\n\n} \/\/ namespace caf::detail\n\nnamespace caf::flow {\n\ntemplate <class OnNext, class OnError, class OnComplete>\nauto make_observer(OnNext on_next, OnError on_error, OnComplete on_complete) {\n using impl_type = detail::default_observer_impl<OnNext, OnError, OnComplete>;\n using input_type = typename impl_type::input_type;\n auto ptr = make_counted<impl_type>(std::move(on_next), std::move(on_error),\n std::move(on_complete));\n return observer<input_type>{std::move(ptr)};\n}\n\ntemplate <class OnNext, class OnError>\nauto make_observer(OnNext on_next, OnError on_error) {\n using impl_type = detail::default_observer_impl<OnNext, OnError>;\n using input_type = typename impl_type::input_type;\n auto ptr = make_counted<impl_type>(std::move(on_next), std::move(on_error));\n return observer<input_type>{std::move(ptr)};\n}\n\ntemplate <class OnNext>\nauto make_observer(OnNext on_next) {\n using impl_type = detail::default_observer_impl<OnNext>;\n using input_type = typename impl_type::input_type;\n auto ptr = make_counted<impl_type>(std::move(on_next));\n return observer<input_type>{std::move(ptr)};\n}\n\n} \/\/ namespace caf::flow\n<commit_msg>Fix demand handling on buffer writers<commit_after>\/\/ This file is part of CAF, the C++ Actor Framework. See the file LICENSE in\n\/\/ the main distribution directory for license terms and copyright or visit\n\/\/ https:\/\/github.com\/actor-framework\/actor-framework\/blob\/master\/LICENSE.\n\n#pragma once\n\n#include \"caf\/async\/batch.hpp\"\n#include \"caf\/async\/producer.hpp\"\n#include \"caf\/defaults.hpp\"\n#include \"caf\/detail\/type_traits.hpp\"\n#include \"caf\/disposable.hpp\"\n#include \"caf\/error.hpp\"\n#include \"caf\/flow\/coordinator.hpp\"\n#include \"caf\/flow\/subscription.hpp\"\n#include \"caf\/intrusive_ptr.hpp\"\n#include \"caf\/logger.hpp\"\n#include \"caf\/make_counted.hpp\"\n#include \"caf\/ref_counted.hpp\"\n#include \"caf\/span.hpp\"\n#include \"caf\/unit.hpp\"\n\nnamespace caf::flow {\n\n\/\/\/ Handle to a consumer of items.\ntemplate <class T>\nclass observer {\npublic:\n \/\/\/ Internal interface of an `observer`.\n class impl : public disposable::impl {\n public:\n using input_type = T;\n\n virtual void on_subscribe(subscription sub) = 0;\n\n virtual void on_next(span<const T> items) = 0;\n\n virtual void on_complete() = 0;\n\n virtual void on_error(const error& what) = 0;\n\n observer as_observer() noexcept {\n return observer{intrusive_ptr<impl>(this)};\n }\n };\n\n using input_type = T;\n\n explicit observer(intrusive_ptr<impl> pimpl) noexcept\n : pimpl_(std::move(pimpl)) {\n \/\/ nop\n }\n\n observer& operator=(std::nullptr_t) noexcept {\n pimpl_.reset();\n return *this;\n }\n\n observer() noexcept = default;\n observer(observer&&) noexcept = default;\n observer(const observer&) noexcept = default;\n observer& operator=(observer&&) noexcept = default;\n observer& operator=(const observer&) noexcept = default;\n\n disposable as_disposable() const& noexcept {\n return disposable{pimpl_};\n }\n\n disposable as_disposable() && noexcept {\n return disposable{std::move(pimpl_)};\n }\n\n \/\/\/ @pre `valid()`\n void on_complete() {\n pimpl_->on_complete();\n }\n\n \/\/\/ @pre `valid()`\n void on_error(const error& what) {\n pimpl_->on_error(what);\n }\n\n \/\/\/ @pre `valid()`\n void on_subscribe(subscription sub) {\n pimpl_->on_subscribe(std::move(sub));\n }\n\n \/\/\/ @pre `valid()`\n void on_batch(const async::batch& buf) {\n pimpl_->on_batch(buf);\n }\n\n \/\/\/ @pre `valid()`\n void on_next(span<const T> items) {\n pimpl_->on_next(items);\n }\n\n \/\/\/ Creates a new observer from `Impl`.\n template <class Impl, class... Ts>\n [[nodiscard]] static observer make(Ts&&... xs) {\n static_assert(std::is_base_of_v<impl, Impl>);\n return observer{make_counted<Impl>(std::forward<Ts>(xs)...)};\n }\n\n bool valid() const noexcept {\n return pimpl_ != nullptr;\n }\n\n explicit operator bool() const noexcept {\n return valid();\n }\n\n bool operator!() const noexcept {\n return !valid();\n }\n\n impl* ptr() {\n return pimpl_.get();\n }\n\n const impl* ptr() const {\n return pimpl_.get();\n }\n\n const intrusive_ptr<impl>& as_intrusive_ptr() const& noexcept {\n return pimpl_;\n }\n\n intrusive_ptr<impl>&& as_intrusive_ptr() && noexcept {\n return std::move(pimpl_);\n }\n\n void swap(observer& other) {\n pimpl_.swap(other.pimpl_);\n }\n\nprivate:\n intrusive_ptr<impl> pimpl_;\n};\n\ntemplate <class T>\nusing observer_impl = typename observer<T>::impl;\n\n\/\/ -- writing observed values to a buffer --------------------------------------\n\n\/\/\/ Writes observed values to a bounded buffer.\ntemplate <class Buffer>\nclass buffer_writer_impl : public ref_counted,\n public observer_impl<typename Buffer::value_type>,\n public async::producer {\npublic:\n \/\/ -- member types -----------------------------------------------------------\n\n using buffer_ptr = intrusive_ptr<Buffer>;\n\n using value_type = typename Buffer::value_type;\n\n \/\/ -- friends ----------------------------------------------------------------\n\n CAF_INTRUSIVE_PTR_FRIENDS(buffer_writer_impl)\n\n \/\/ -- constructors, destructors, and assignment operators --------------------\n\n buffer_writer_impl(coordinator* ctx, buffer_ptr buf)\n : ctx_(ctx), buf_(std::move(buf)) {\n CAF_ASSERT(ctx_ != nullptr);\n CAF_ASSERT(buf_ != nullptr);\n }\n\n ~buffer_writer_impl() {\n if (buf_)\n buf_->close();\n }\n\n \/\/ -- implementation of disposable::impl -------------------------------------\n\n void dispose() override {\n CAF_LOG_TRACE(\"\");\n on_complete();\n }\n\n bool disposed() const noexcept override {\n return buf_ == nullptr;\n }\n\n void ref_disposable() const noexcept final {\n this->ref();\n }\n\n void deref_disposable() const noexcept final {\n this->deref();\n }\n\n \/\/ -- implementation of observer<T>::impl ------------------------------------\n\n void on_next(span<const value_type> items) override {\n CAF_LOG_TRACE(CAF_ARG(items));\n if (buf_)\n buf_->push(items);\n }\n\n void on_complete() override {\n CAF_LOG_TRACE(\"\");\n if (buf_) {\n buf_->close();\n buf_ = nullptr;\n sub_ = nullptr;\n }\n }\n\n void on_error(const error& what) override {\n CAF_LOG_TRACE(CAF_ARG(what));\n if (buf_) {\n buf_->abort(what);\n buf_ = nullptr;\n sub_ = nullptr;\n }\n }\n\n void on_subscribe(subscription sub) override {\n CAF_LOG_TRACE(\"\");\n if (buf_ && !sub_) {\n CAF_LOG_DEBUG(\"add subscription\");\n sub_ = std::move(sub);\n } else {\n CAF_LOG_DEBUG(\"already have a subscription or buffer no longer valid\");\n sub.cancel();\n }\n }\n\n \/\/ -- implementation of async::producer: these may get called concurrently ---\n\n void on_consumer_ready() override {\n \/\/ nop\n }\n\n void on_consumer_cancel() override {\n CAF_LOG_TRACE(\"\");\n ctx_->schedule_fn([ptr{strong_ptr()}] {\n CAF_LOG_TRACE(\"\");\n ptr->on_cancel();\n });\n }\n\n void on_consumer_demand(size_t demand) override {\n CAF_LOG_TRACE(CAF_ARG(demand));\n ctx_->schedule_fn([ptr{strong_ptr()}, demand] { \/\/\n CAF_LOG_TRACE(CAF_ARG(demand));\n ptr->on_demand(demand);\n });\n }\n\n void ref_producer() const noexcept final {\n this->ref();\n }\n\n void deref_producer() const noexcept final {\n this->deref();\n }\n\nprivate:\n void on_demand(size_t n) {\n CAF_LOG_TRACE(CAF_ARG(n));\n if (sub_)\n sub_.request(n);\n }\n\n void on_cancel() {\n CAF_LOG_TRACE(\"\");\n if (sub_) {\n sub_.cancel();\n sub_ = nullptr;\n }\n buf_ = nullptr;\n }\n\n intrusive_ptr<buffer_writer_impl> strong_ptr() {\n return {this};\n }\n\n coordinator_ptr ctx_;\n buffer_ptr buf_;\n subscription sub_;\n};\n\n} \/\/ namespace caf::flow\n\nnamespace caf::detail {\n\ntemplate <class OnNextSignature>\nstruct on_next_trait;\n\ntemplate <class T>\nstruct on_next_trait<void(T)> {\n using value_type = T;\n\n template <class F>\n static void apply(F& f, span<const T> items) {\n for (auto&& item : items)\n f(item);\n }\n};\n\ntemplate <class T>\nstruct on_next_trait<void(const T&)> {\n using value_type = T;\n\n template <class F>\n static void apply(F& f, span<const T> items) {\n for (auto&& item : items)\n f(item);\n }\n};\n\ntemplate <class T>\nstruct on_next_trait<void(span<const T>)> {\n using value_type = T;\n\n template <class F>\n static void apply(F& f, span<const T> items) {\n f(items);\n }\n};\n\ntemplate <class F>\nusing on_next_trait_t\n = on_next_trait<typename get_callable_trait_t<F>::fun_sig>;\n\ntemplate <class F>\nusing on_next_value_type = typename on_next_trait_t<F>::value_type;\n\ntemplate <class OnNext, class OnError = unit_t, class OnComplete = unit_t>\nclass default_observer_impl\n : public ref_counted,\n public flow::observer_impl<on_next_value_type<OnNext>> {\npublic:\n static_assert(std::is_invocable_v<OnError, const error&>);\n\n static_assert(std::is_invocable_v<OnComplete>);\n\n using input_type = on_next_value_type<OnNext>;\n\n CAF_INTRUSIVE_PTR_FRIENDS(default_observer_impl)\n\n explicit default_observer_impl(OnNext&& on_next_fn)\n : on_next_(std::move(on_next_fn)) {\n \/\/ nop\n }\n\n default_observer_impl(OnNext&& on_next_fn, OnError&& on_error_fn)\n : on_next_(std::move(on_next_fn)), on_error_(std::move(on_error_fn)) {\n \/\/ nop\n }\n\n default_observer_impl(OnNext&& on_next_fn, OnError&& on_error_fn,\n OnComplete&& on_complete_fn)\n : on_next_(std::move(on_next_fn)),\n on_error_(std::move(on_error_fn)),\n on_complete_(std::move(on_complete_fn)) {\n \/\/ nop\n }\n\n void ref_disposable() const noexcept final {\n this->ref();\n }\n\n void deref_disposable() const noexcept final {\n this->deref();\n }\n\n void on_next(span<const input_type> items) override {\n if (!completed_) {\n on_next_trait_t<OnNext>::apply(on_next_, items);\n sub_.request(items.size());\n }\n }\n\n void on_error(const error& what) override {\n if (!completed_) {\n on_error_(what);\n sub_ = nullptr;\n completed_ = true;\n }\n }\n\n void on_complete() override {\n if (!completed_) {\n on_complete_();\n sub_ = nullptr;\n completed_ = true;\n }\n }\n\n void on_subscribe(flow::subscription sub) override {\n if (!completed_ && !sub_) {\n sub_ = std::move(sub);\n sub_.request(defaults::flow::buffer_size);\n } else {\n sub.cancel();\n }\n }\n\n void dispose() override {\n if (!completed_) {\n on_complete_();\n if (sub_) {\n sub_.cancel();\n sub_ = nullptr;\n }\n completed_ = true;\n }\n }\n\n bool disposed() const noexcept override {\n return completed_;\n }\n\nprivate:\n bool completed_ = false;\n OnNext on_next_;\n OnError on_error_;\n OnComplete on_complete_;\n flow::subscription sub_;\n};\n\n} \/\/ namespace caf::detail\n\nnamespace caf::flow {\n\ntemplate <class OnNext, class OnError, class OnComplete>\nauto make_observer(OnNext on_next, OnError on_error, OnComplete on_complete) {\n using impl_type = detail::default_observer_impl<OnNext, OnError, OnComplete>;\n using input_type = typename impl_type::input_type;\n auto ptr = make_counted<impl_type>(std::move(on_next), std::move(on_error),\n std::move(on_complete));\n return observer<input_type>{std::move(ptr)};\n}\n\ntemplate <class OnNext, class OnError>\nauto make_observer(OnNext on_next, OnError on_error) {\n using impl_type = detail::default_observer_impl<OnNext, OnError>;\n using input_type = typename impl_type::input_type;\n auto ptr = make_counted<impl_type>(std::move(on_next), std::move(on_error));\n return observer<input_type>{std::move(ptr)};\n}\n\ntemplate <class OnNext>\nauto make_observer(OnNext on_next) {\n using impl_type = detail::default_observer_impl<OnNext>;\n using input_type = typename impl_type::input_type;\n auto ptr = make_counted<impl_type>(std::move(on_next));\n return observer<input_type>{std::move(ptr)};\n}\n\n} \/\/ namespace caf::flow\n<|endoftext|>"} {"text":"<commit_before>#include <libdariadb\/storage\/memstorage.h>\n#include <libdariadb\/flags.h>\n#include <memory>\n#include <tuple>\n#include <unordered_map>\n#include <cstring>\n#include <cassert>\n\nusing namespace dariadb;\nusing namespace dariadb::storage;\n\nMemChunkAllocator::MemChunkAllocator(size_t maxSize, size_t bufferSize) {\n _maxSize = maxSize;\n _bufferSize = bufferSize;\n _allocated = size_t(0);\n size_t one_sz = sizeof(ChunkHeader) + bufferSize;\n _capacity = (int)(float(_maxSize) \/ one_sz);\n\n _headers.resize(_capacity);\n _buffers = new uint8_t[_capacity * _bufferSize];\n for(size_t i=0;i<_capacity;++i){\n _free_list.push_back(i);\n }\n}\n\nMemChunkAllocator::~MemChunkAllocator() {\n delete[] _buffers;\n}\n\nMemChunkAllocator::allocated_data MemChunkAllocator::allocate() {\n _locker.lock();\n if(_free_list.empty()){\n _locker.unlock();\n return EMPTY;\n }\n auto pos=_free_list.front();\n _free_list.pop_front();\n _allocated++;\n _locker.unlock();\n memset(&_headers[pos], 0, sizeof(ChunkHeader));\n memset(&_buffers[pos * _bufferSize], 0, sizeof(_bufferSize));\n return allocated_data(&_headers[pos], &_buffers[pos * _bufferSize], pos);\n}\n\nvoid MemChunkAllocator::free(const MemChunkAllocator::allocated_data &d) {\n auto header = std::get<0>(d);\n auto buffer = std::get<1>(d);\n auto position = std::get<2>(d);\n memset(header, 0, sizeof(ChunkHeader));\n memset(buffer, 0, _bufferSize);\n _locker.lock();\n _allocated--;\n _free_list.push_back(position);\n _locker.unlock();\n}\n\n\/**\nMap:\n Meas.id -> TimeTrack{ MemChunkList[MemChunk{data}]}\n*\/\n\nstruct MemChunk : public ZippedChunk {\n ChunkHeader *index_ptr;\n uint8_t *buffer_ptr;\n MemChunkAllocator::allocated_data _a_data;\n MemChunk(ChunkHeader *index, uint8_t *buffer, size_t size, Meas first_m)\n : ZippedChunk(index, buffer, size, first_m) {\n index_ptr = index;\n buffer_ptr = buffer;\n }\n MemChunk(ChunkHeader *index, uint8_t *buffer) : ZippedChunk(index, buffer) {\n index_ptr = index;\n buffer_ptr = buffer;\n }\n ~MemChunk() {}\n};\n\nusing MemChunk_Ptr = std::shared_ptr<MemChunk>;\nusing MemChunkList = std::list<MemChunk_Ptr>;\n\nclass TimeTrack : public IMeasStorage {\npublic:\n TimeTrack(const Time step, Id meas_id, MemChunkAllocator*allocator) {\n\t _allocator = allocator;\n _meas_id = meas_id;\n _step = step;\n\t_minTime = MAX_TIME;\n\t_maxTime = MIN_TIME;\n }\n ~TimeTrack() {}\n\n MemChunkAllocator*_allocator;\n Id _meas_id;\n Time _minTime;\n Time _maxTime;\n Time _step;\n MemChunkList _chunks;\n MemChunk_Ptr _cur_chunk;\n utils::Locker _locker;\n\n void updateMinMax(const Meas&value) {\n\t _minTime = std::min(_minTime, value.time);\n\t _maxTime = std::max(_maxTime, value.time);\n }\n virtual append_result append(const Meas &value) override {\n std::lock_guard<utils::Locker> lg(_locker);\n if (_chunks.empty() || _chunks.back()->is_full()) {\n\t\tif (!create_new_chunk(value)) {\n\t\t\treturn append_result(0,1);\n\t\t}\n\t\telse {\n\t\t\tupdateMinMax(value);\n\t\t\treturn append_result(1, 0);\n\t\t}\n }\n\tif (!_cur_chunk->append(value)) {\n\t\tif (!create_new_chunk(value)) {\n\t\t\treturn append_result(0, 1);\n\t\t}\n\t\telse {\n\t\t\tupdateMinMax(value);\n\t\t\treturn append_result(1, 0);\n\t\t}\n\t}\n\tupdateMinMax(value);\n return append_result(1, 0);\n }\n\n virtual void flush() {}\n \n virtual Time minTime() override {\n\t return _minTime;\n }\n\n virtual Time maxTime() override { \n\t return _maxTime;\n }\n\n virtual bool minMaxTime(dariadb::Id id, dariadb::Time *minResult,\n dariadb::Time *maxResult) override {\n\t if (id != this->_meas_id) {\n\t\t return false;\n\t } \n\t std::lock_guard<utils::Locker> lg(_locker);\n\t *minResult = MAX_TIME;\n\t *maxResult = MIN_TIME;\n\t for (auto c : _chunks) {\n\t\t *minResult = std::min(c->header->minTime, *minResult);\n\t\t *maxResult = std::max(c->header->maxTime, *maxResult);\n\t }\n\t return true;\n }\n\n \/\/TODO use b+tree for fast search;\n virtual void foreach (const QueryInterval &q, IReaderClb * clbk) override {\n std::lock_guard<utils::Locker> lg(_locker);\n for (auto c : _chunks) {\n if (utils::inInterval(c->header->minTime, c->header->maxTime, q.from)\n\t\t ||utils::inInterval(c->header->minTime, c->header->maxTime, q.to)\n\t\t || utils::inInterval(q.from, q.to, c->header->minTime)\n\t\t || utils::inInterval(q.from, q.to, c->header->maxTime)) {\n auto rdr = c->get_reader();\n\n while (!rdr->is_end()) {\n auto v = rdr->readNext();\n\t\t if (utils::inInterval(q.from, q.to, v.time)) {\n\t\t\t clbk->call(v);\n\t\t }\n }\n }\n }\n }\n\n \/\/TODO use b+tree for fast search;\n virtual Id2Meas readTimePoint(const QueryTimePoint &q) override { \n\t std::lock_guard<utils::Locker> lg(_locker);\n\t Id2Meas result;\n\t result[this->_meas_id].flag = Flags::_NO_DATA;\n\t for (auto c : _chunks) {\n\t\t if (c->header->minTime >= q.time_point && c->header->maxTime <= q.time_point) {\n\t\t\t auto rdr = c->get_reader();\n\n\t\t\t while (!rdr->is_end()) {\n\t\t\t\t auto v = rdr->readNext();\n\t\t\t\t if (v.time > result[this->_meas_id].time && v.time<=q.time_point) {\n\t\t\t\t\t result[this->_meas_id] = v;\n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t }\n\t if (result[this->_meas_id].flag == Flags::_NO_DATA) {\n\t\t result[this->_meas_id].time = q.time_point;\n\t }\n\t return result;\n }\n\n virtual Id2Meas currentValue(const IdArray &ids, const Flag &flag) override {\n assert(ids.size() == size_t(1));\n assert(ids[0]==this->_meas_id);\n\t std::lock_guard<utils::Locker> lg(_locker);\n\t Id2Meas result;\n\t result[_meas_id] = _chunks.back()->header->last;\n\t return result;\n }\n\n\n bool create_new_chunk(const Meas&value) {\n\t auto new_chunk_data = _allocator->allocate();\n\t if (std::get<0>(new_chunk_data) == nullptr) {\n\t\t return false;\n\t }\n\t auto mc = MemChunk_Ptr{ new MemChunk{ std::get<0>(new_chunk_data),\n\t\t std::get<1>(new_chunk_data),\n\t\t _allocator->_bufferSize, value } };\n\t this->_chunks.push_back(mc);\n\t _cur_chunk = mc;\n\t return true;\n }\n};\n\nusing TimeTrack_ptr = std::shared_ptr<TimeTrack>;\nusing Id2Track = std::unordered_map<Id, TimeTrack_ptr>;\n\nstruct MemStorage::Private : public IMeasStorage {\n\tPrivate(const MemStorage::Params &p) : _chunk_allocator(p.max_size, p.chunk_size) {}\n\n\tMemStorage::Description description()const {\n\t\tMemStorage::Description result;\n result.allocated = _chunk_allocator._allocated;\n result.allocator_capacity = _chunk_allocator._capacity;\n\t\treturn result;\n\t}\n append_result append(const Meas &value) override { \n\t auto track = _id2track.find(value.id);\n\t if (track == _id2track.end()) {\n\t\t std::lock_guard<utils::Locker> lg(_all_tracks_locker);\n\t\t track = _id2track.find(value.id);\n\t\t if (track == _id2track.end()) {\n\t\t\t auto new_track = std::make_shared<TimeTrack>(Time(0), value.id, &_chunk_allocator);\n\t\t\t _id2track.insert(std::make_pair(value.id, new_track));\n\t\t\t new_track->append(value);\n\t\t\t return append_result(1,0);\n\t\t }\n\t }\n\t return track->second->append(value);\n }\n Time minTime() override { \n\t Time result = MAX_TIME;\n\t for (auto t : _id2track) {\n\t\t result=std::min(result, t.second->minTime());\n\t }\n\t return result;\n }\n virtual Time maxTime() override { \n\t Time result = MIN_TIME;\n\t for (auto t : _id2track) {\n\t\t result = std::max(result, t.second->maxTime());\n\t }\n\t return result;\n }\n virtual bool minMaxTime(dariadb::Id id, dariadb::Time *minResult,\n dariadb::Time *maxResult) override {\n\t auto tracker = _id2track.find(id);\n\t if (tracker != _id2track.end()) {\n\t\t return tracker->second->minMaxTime(id, minResult, maxResult);\n\t }\n\t return false;\n }\n \n void foreach (const QueryInterval &q, IReaderClb * clbk) override {\n\t QueryInterval local_q({}, q.flag, q.from,q.to);\n\t local_q.ids.resize(1);\n\t for (auto id : q.ids) {\n\t\t auto tracker = _id2track.find(id);\n\t\t if (tracker != _id2track.end()) {\n\t\t\t local_q.ids[0] = id;\n\t\t\t tracker->second->foreach(local_q,clbk);\n\t\t }\n\t }\n\t clbk->is_end();\n }\n\n virtual Id2Meas readTimePoint(const QueryTimePoint &q) override { \n\t QueryTimePoint local_q({}, q.flag, q.time_point);\n\t local_q.ids.resize(1);\n\t Id2Meas result;\n\t for (auto id : q.ids) {\n\t\t auto tracker = _id2track.find(id);\n\t\t if (tracker != _id2track.end()) {\n\t\t\t local_q.ids[0] = id;\n\t\t\t auto sub_res = tracker->second->readTimePoint(local_q);\n\t\t\t result[id] = sub_res[id];\n\t\t }\n\t\t else {\n\t\t\t result[id].flag = Flags::_NO_DATA;\n\t\t }\n\t }\n\t return result;\n }\n virtual Id2Meas currentValue(const IdArray &ids, const Flag &flag) override {\n\t IdArray local_ids;\n local_ids.resize(1);\n\t Id2Meas result;\n\t for (auto id : ids) {\n\t\t auto tracker = _id2track.find(id);\n\t\t if (tracker != _id2track.end()) {\n\t\t\t local_ids[0] = id;\n\t\t\t auto sub_res = tracker->second->currentValue(local_ids, flag);\n\t\t\t result[id] = sub_res[id];\n\t\t }\n\t\t else {\n\t\t\t result[id].flag = Flags::_NO_DATA;\n\t\t }\n\t }\n\t return result;\n }\n\n\n void flush() override {}\n\n Id2Track _id2track;\n MemChunkAllocator _chunk_allocator;\n utils::Locker _all_tracks_locker;\n};\n\nMemStorage::MemStorage(const MemStorage::Params &p) : _impl(new MemStorage::Private(p)) {}\n\nMemStorage::~MemStorage() {\n _impl = nullptr;\n}\n\nMemStorage::Description MemStorage::description() const{\n\treturn _impl->description();\n}\n\nTime dariadb::storage::MemStorage::minTime() {\n return _impl->minTime();\n}\n\nTime dariadb::storage::MemStorage::maxTime() {\n return _impl->maxTime();\n}\n\nbool dariadb::storage::MemStorage::minMaxTime(dariadb::Id id, dariadb::Time *minResult,\n dariadb::Time *maxResult) {\n return _impl->minMaxTime(id, minResult, maxResult);\n}\n\nvoid dariadb::storage::MemStorage::foreach (const QueryInterval &q, IReaderClb * clbk) {\n _impl->foreach (q, clbk);\n}\n\nId2Meas dariadb::storage::MemStorage::readTimePoint(const QueryTimePoint &q) {\n return _impl->readTimePoint(q);\n}\n\nId2Meas dariadb::storage::MemStorage::currentValue(const IdArray &ids, const Flag &flag) {\n return _impl->currentValue(ids, flag);\n}\n\nappend_result dariadb::storage::MemStorage::append(const Meas &value) {\n return _impl->append(value);\n}\n\nvoid dariadb::storage::MemStorage::flush() {\n _impl->flush();\n}\n<commit_msg>MemChunkAllocator: memset for buffer.<commit_after>#include <libdariadb\/storage\/memstorage.h>\n#include <libdariadb\/flags.h>\n#include <memory>\n#include <tuple>\n#include <unordered_map>\n#include <cstring>\n#include <cassert>\n\nusing namespace dariadb;\nusing namespace dariadb::storage;\n\nMemChunkAllocator::MemChunkAllocator(size_t maxSize, size_t bufferSize) {\n _maxSize = maxSize;\n _bufferSize = bufferSize;\n _allocated = size_t(0);\n size_t one_chunk_size = sizeof(ChunkHeader) + bufferSize;\n _capacity = (int)(float(_maxSize) \/ one_chunk_size);\n size_t buffers_size=_capacity * _bufferSize;\n\n _headers.resize(_capacity);\n _buffers = new uint8_t[buffers_size];\n\n memset(_buffers,0,buffers_size);\n for(size_t i=0;i<_capacity;++i){\n memset(&_headers[i],0,sizeof(ChunkHeader));\n _free_list.push_back(i);\n }\n}\n\nMemChunkAllocator::~MemChunkAllocator() {\n delete[] _buffers;\n}\n\nMemChunkAllocator::allocated_data MemChunkAllocator::allocate() {\n _locker.lock();\n if(_free_list.empty()){\n _locker.unlock();\n return EMPTY;\n }\n auto pos=_free_list.front();\n _free_list.pop_front();\n _allocated++;\n _locker.unlock();\n return allocated_data(&_headers[pos], &_buffers[pos * _bufferSize], pos);\n}\n\nvoid MemChunkAllocator::free(const MemChunkAllocator::allocated_data &d) {\n auto header = std::get<0>(d);\n auto buffer = std::get<1>(d);\n auto position = std::get<2>(d);\n memset(header, 0, sizeof(ChunkHeader));\n memset(buffer, 0, _bufferSize);\n _locker.lock();\n _allocated--;\n _free_list.push_back(position);\n _locker.unlock();\n}\n\n\/**\nMap:\n Meas.id -> TimeTrack{ MemChunkList[MemChunk{data}]}\n*\/\n\nstruct MemChunk : public ZippedChunk {\n ChunkHeader *index_ptr;\n uint8_t *buffer_ptr;\n MemChunkAllocator::allocated_data _a_data;\n MemChunk(ChunkHeader *index, uint8_t *buffer, size_t size, Meas first_m)\n : ZippedChunk(index, buffer, size, first_m) {\n index_ptr = index;\n buffer_ptr = buffer;\n }\n MemChunk(ChunkHeader *index, uint8_t *buffer) : ZippedChunk(index, buffer) {\n index_ptr = index;\n buffer_ptr = buffer;\n }\n ~MemChunk() {}\n};\n\nusing MemChunk_Ptr = std::shared_ptr<MemChunk>;\nusing MemChunkList = std::list<MemChunk_Ptr>;\n\nclass TimeTrack : public IMeasStorage {\npublic:\n TimeTrack(const Time step, Id meas_id, MemChunkAllocator*allocator) {\n\t _allocator = allocator;\n _meas_id = meas_id;\n _step = step;\n\t_minTime = MAX_TIME;\n\t_maxTime = MIN_TIME;\n }\n ~TimeTrack() {}\n\n MemChunkAllocator*_allocator;\n Id _meas_id;\n Time _minTime;\n Time _maxTime;\n Time _step;\n MemChunkList _chunks;\n MemChunk_Ptr _cur_chunk;\n utils::Locker _locker;\n\n void updateMinMax(const Meas&value) {\n\t _minTime = std::min(_minTime, value.time);\n\t _maxTime = std::max(_maxTime, value.time);\n }\n virtual append_result append(const Meas &value) override {\n std::lock_guard<utils::Locker> lg(_locker);\n if (_chunks.empty() || _chunks.back()->is_full()) {\n\t\tif (!create_new_chunk(value)) {\n\t\t\treturn append_result(0,1);\n\t\t}\n\t\telse {\n\t\t\tupdateMinMax(value);\n\t\t\treturn append_result(1, 0);\n\t\t}\n }\n\tif (!_cur_chunk->append(value)) {\n\t\tif (!create_new_chunk(value)) {\n\t\t\treturn append_result(0, 1);\n\t\t}\n\t\telse {\n\t\t\tupdateMinMax(value);\n\t\t\treturn append_result(1, 0);\n\t\t}\n\t}\n\tupdateMinMax(value);\n return append_result(1, 0);\n }\n\n virtual void flush() {}\n \n virtual Time minTime() override {\n\t return _minTime;\n }\n\n virtual Time maxTime() override { \n\t return _maxTime;\n }\n\n virtual bool minMaxTime(dariadb::Id id, dariadb::Time *minResult,\n dariadb::Time *maxResult) override {\n\t if (id != this->_meas_id) {\n\t\t return false;\n\t } \n\t std::lock_guard<utils::Locker> lg(_locker);\n\t *minResult = MAX_TIME;\n\t *maxResult = MIN_TIME;\n\t for (auto c : _chunks) {\n\t\t *minResult = std::min(c->header->minTime, *minResult);\n\t\t *maxResult = std::max(c->header->maxTime, *maxResult);\n\t }\n\t return true;\n }\n\n \/\/TODO use b+tree for fast search;\n virtual void foreach (const QueryInterval &q, IReaderClb * clbk) override {\n std::lock_guard<utils::Locker> lg(_locker);\n for (auto c : _chunks) {\n if (utils::inInterval(c->header->minTime, c->header->maxTime, q.from)\n\t\t ||utils::inInterval(c->header->minTime, c->header->maxTime, q.to)\n\t\t || utils::inInterval(q.from, q.to, c->header->minTime)\n\t\t || utils::inInterval(q.from, q.to, c->header->maxTime)) {\n auto rdr = c->get_reader();\n\n while (!rdr->is_end()) {\n auto v = rdr->readNext();\n\t\t if (utils::inInterval(q.from, q.to, v.time)) {\n\t\t\t clbk->call(v);\n\t\t }\n }\n }\n }\n }\n\n \/\/TODO use b+tree for fast search;\n virtual Id2Meas readTimePoint(const QueryTimePoint &q) override { \n\t std::lock_guard<utils::Locker> lg(_locker);\n\t Id2Meas result;\n\t result[this->_meas_id].flag = Flags::_NO_DATA;\n\t for (auto c : _chunks) {\n\t\t if (c->header->minTime >= q.time_point && c->header->maxTime <= q.time_point) {\n\t\t\t auto rdr = c->get_reader();\n\n\t\t\t while (!rdr->is_end()) {\n\t\t\t\t auto v = rdr->readNext();\n\t\t\t\t if (v.time > result[this->_meas_id].time && v.time<=q.time_point) {\n\t\t\t\t\t result[this->_meas_id] = v;\n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t }\n\t if (result[this->_meas_id].flag == Flags::_NO_DATA) {\n\t\t result[this->_meas_id].time = q.time_point;\n\t }\n\t return result;\n }\n\n virtual Id2Meas currentValue(const IdArray &ids, const Flag &flag) override {\n assert(ids.size() == size_t(1));\n assert(ids[0]==this->_meas_id);\n\t std::lock_guard<utils::Locker> lg(_locker);\n\t Id2Meas result;\n\t result[_meas_id] = _chunks.back()->header->last;\n\t return result;\n }\n\n\n bool create_new_chunk(const Meas&value) {\n\t auto new_chunk_data = _allocator->allocate();\n\t if (std::get<0>(new_chunk_data) == nullptr) {\n\t\t return false;\n\t }\n\t auto mc = MemChunk_Ptr{ new MemChunk{ std::get<0>(new_chunk_data),\n\t\t std::get<1>(new_chunk_data),\n\t\t _allocator->_bufferSize, value } };\n\t this->_chunks.push_back(mc);\n\t _cur_chunk = mc;\n\t return true;\n }\n};\n\nusing TimeTrack_ptr = std::shared_ptr<TimeTrack>;\nusing Id2Track = std::unordered_map<Id, TimeTrack_ptr>;\n\nstruct MemStorage::Private : public IMeasStorage {\n\tPrivate(const MemStorage::Params &p) : _chunk_allocator(p.max_size, p.chunk_size) {}\n\n\tMemStorage::Description description()const {\n\t\tMemStorage::Description result;\n result.allocated = _chunk_allocator._allocated;\n result.allocator_capacity = _chunk_allocator._capacity;\n\t\treturn result;\n\t}\n append_result append(const Meas &value) override { \n\t auto track = _id2track.find(value.id);\n\t if (track == _id2track.end()) {\n\t\t std::lock_guard<utils::Locker> lg(_all_tracks_locker);\n\t\t track = _id2track.find(value.id);\n\t\t if (track == _id2track.end()) {\n\t\t\t auto new_track = std::make_shared<TimeTrack>(Time(0), value.id, &_chunk_allocator);\n\t\t\t _id2track.insert(std::make_pair(value.id, new_track));\n\t\t\t new_track->append(value);\n\t\t\t return append_result(1,0);\n\t\t }\n\t }\n\t return track->second->append(value);\n }\n Time minTime() override { \n\t Time result = MAX_TIME;\n\t for (auto t : _id2track) {\n\t\t result=std::min(result, t.second->minTime());\n\t }\n\t return result;\n }\n virtual Time maxTime() override { \n\t Time result = MIN_TIME;\n\t for (auto t : _id2track) {\n\t\t result = std::max(result, t.second->maxTime());\n\t }\n\t return result;\n }\n virtual bool minMaxTime(dariadb::Id id, dariadb::Time *minResult,\n dariadb::Time *maxResult) override {\n\t auto tracker = _id2track.find(id);\n\t if (tracker != _id2track.end()) {\n\t\t return tracker->second->minMaxTime(id, minResult, maxResult);\n\t }\n\t return false;\n }\n \n void foreach (const QueryInterval &q, IReaderClb * clbk) override {\n\t QueryInterval local_q({}, q.flag, q.from,q.to);\n\t local_q.ids.resize(1);\n\t for (auto id : q.ids) {\n\t\t auto tracker = _id2track.find(id);\n\t\t if (tracker != _id2track.end()) {\n\t\t\t local_q.ids[0] = id;\n\t\t\t tracker->second->foreach(local_q,clbk);\n\t\t }\n\t }\n\t clbk->is_end();\n }\n\n virtual Id2Meas readTimePoint(const QueryTimePoint &q) override { \n\t QueryTimePoint local_q({}, q.flag, q.time_point);\n\t local_q.ids.resize(1);\n\t Id2Meas result;\n\t for (auto id : q.ids) {\n\t\t auto tracker = _id2track.find(id);\n\t\t if (tracker != _id2track.end()) {\n\t\t\t local_q.ids[0] = id;\n\t\t\t auto sub_res = tracker->second->readTimePoint(local_q);\n\t\t\t result[id] = sub_res[id];\n\t\t }\n\t\t else {\n\t\t\t result[id].flag = Flags::_NO_DATA;\n\t\t }\n\t }\n\t return result;\n }\n virtual Id2Meas currentValue(const IdArray &ids, const Flag &flag) override {\n\t IdArray local_ids;\n local_ids.resize(1);\n\t Id2Meas result;\n\t for (auto id : ids) {\n\t\t auto tracker = _id2track.find(id);\n\t\t if (tracker != _id2track.end()) {\n\t\t\t local_ids[0] = id;\n\t\t\t auto sub_res = tracker->second->currentValue(local_ids, flag);\n\t\t\t result[id] = sub_res[id];\n\t\t }\n\t\t else {\n\t\t\t result[id].flag = Flags::_NO_DATA;\n\t\t }\n\t }\n\t return result;\n }\n\n\n void flush() override {}\n\n Id2Track _id2track;\n MemChunkAllocator _chunk_allocator;\n utils::Locker _all_tracks_locker;\n};\n\nMemStorage::MemStorage(const MemStorage::Params &p) : _impl(new MemStorage::Private(p)) {}\n\nMemStorage::~MemStorage() {\n _impl = nullptr;\n}\n\nMemStorage::Description MemStorage::description() const{\n\treturn _impl->description();\n}\n\nTime dariadb::storage::MemStorage::minTime() {\n return _impl->minTime();\n}\n\nTime dariadb::storage::MemStorage::maxTime() {\n return _impl->maxTime();\n}\n\nbool dariadb::storage::MemStorage::minMaxTime(dariadb::Id id, dariadb::Time *minResult,\n dariadb::Time *maxResult) {\n return _impl->minMaxTime(id, minResult, maxResult);\n}\n\nvoid dariadb::storage::MemStorage::foreach (const QueryInterval &q, IReaderClb * clbk) {\n _impl->foreach (q, clbk);\n}\n\nId2Meas dariadb::storage::MemStorage::readTimePoint(const QueryTimePoint &q) {\n return _impl->readTimePoint(q);\n}\n\nId2Meas dariadb::storage::MemStorage::currentValue(const IdArray &ids, const Flag &flag) {\n return _impl->currentValue(ids, flag);\n}\n\nappend_result dariadb::storage::MemStorage::append(const Meas &value) {\n return _impl->append(value);\n}\n\nvoid dariadb::storage::MemStorage::flush() {\n _impl->flush();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ------------------------------------------------------------------------\n\/\/ audioio-db-client.cpp: Client class for double-buffering providing \n\/\/ additional layer of buffering for objects\n\/\/ derived from AUDIO_IO.\n\/\/ Copyright (C) 2000-2005,2009 Kai Vehmanen\n\/\/\n\/\/ Attributes:\n\/\/ eca-style-version: 3\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; 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. 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, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ ------------------------------------------------------------------------\n\n#include <unistd.h> \/* open(), close() *\/\n\n#include <kvu_dbc.h>\n#include <kvu_numtostr.h>\n\n#include \"samplebuffer.h\"\n#include \"eca-logger.h\"\n#include \"audioio-db-client.h\"\n\n\/**\n * Constructor. The given client object is registered to \n * the given db server as a client object.\n *\n * Ownership of 'aobject' is transfered to this db client\n * object if 'transfer_ownership' is true.\n *\/\nAUDIO_IO_DB_CLIENT::AUDIO_IO_DB_CLIENT (AUDIO_IO_DB_SERVER *pserver, \n\t\t\t\t\tAUDIO_IO* aobject,\n\t\t\t\t\tbool transfer_ownership) \n : pserver_repp(pserver),\n free_child_rep(transfer_ownership) \n{\n set_child(aobject);\n pbuffer_repp = 0;\n xruns_rep = 0;\n finished_rep = false;\n recursing_rep = false;\n\n ECA_LOG_MSG(ECA_LOGGER::user_objects, \n\t\tstd::string(\"DB-client created for \") +\n\t\tchild()->label() +\n\t\t\".\");\n\n \/\/ just in case the child object has already been configured\n fetch_initial_child_data();\n}\n\n\/**\n * Copy attributes from the proxied (child) object.\n *\/\nvoid AUDIO_IO_DB_CLIENT::fetch_initial_child_data(void)\n{\n \/\/ note! the child object is one that is configured\n \/\/ at this point\n set_audio_format(child()->audio_format());\n set_position_in_samples(child()->position_in_samples());\n set_length_in_samples(child()->length_in_samples());\n set_buffersize(child()->buffersize());\n set_io_mode(child()->io_mode());\n set_label(child()->label());\n toggle_nonblocking_mode(child()->nonblocking_mode());\n}\n\n\/**\n * Desctructor. Unregisters the client from the db\n * server.\n *\/\nAUDIO_IO_DB_CLIENT::~AUDIO_IO_DB_CLIENT(void)\n{\n ECA_LOG_MSG(ECA_LOGGER::user_objects, \"destructor \" + label() + \".\");\n\n if (is_open() == true) {\n close();\n }\n\n if (pserver_repp != 0) {\n bool was_running = false;\n if (pserver_repp->is_running() == true) {\n was_running = true;\n pserver_repp->stop();\n pserver_repp->wait_for_stop();\n DBC_CHECK(pserver_repp->is_running() != true);\n }\n\n pserver_repp->unregister_client(child());\n pbuffer_repp = 0;\n\n if (was_running == true) {\n pserver_repp->start();\n }\n }\n \n if (free_child_rep != true) {\n \/* to avoid deleting the original registered child *\/\n release_child_no_delete();\n }\n \n if (xruns_rep > 0) \n std::cerr << \"(audioio-db-client) There were total \" << xruns_rep << \" xruns.\" << std::endl;\n}\n\n\/**\n * Whether all data has been processed? If opened in mode 'io_read', \n * this means that end of stream has been reached. If opened in \n * 'io_write' or 'io_readwrite' modes, finished status usually\n * means that an error has occured (no space left, etc). After \n * finished() has returned 'true', further calls to read_buffer() \n * and\/or write_buffer() won't process any data.\n *\/\nbool AUDIO_IO_DB_CLIENT::finished(void) const { return finished_rep; }\n\n\/**\n * Reads samples to buffer pointed by 'sbuf'. If necessary, the target \n * buffer will be resized.\n *\/\nvoid AUDIO_IO_DB_CLIENT::read_buffer(SAMPLE_BUFFER* sbuf)\n{\n DBC_CHECK(pbuffer_repp != 0);\n\n if (pbuffer_repp->read_space() > 0) {\n SAMPLE_BUFFER* source = pbuffer_repp->sbufs_rep[pbuffer_repp->readptr_rep.get()];\n sbuf->copy_all_content(*source);\n pbuffer_repp->advance_read_pointer();\n pserver_repp->signal_client_activity();\n change_position_in_samples(sbuf->length_in_samples());\n }\n else {\n sbuf->number_of_channels(channels());\n if (pbuffer_repp->finished_rep.get() == 1) {\n finished_rep = true;\n sbuf->length_in_samples(0);\n }\n else {\n xruns_rep++;\n sbuf->length_in_samples(0);\n\n std::cerr << \"(audioio-db-client) WARNING: Underrun in reading from \\\"\" \n\t\t<< child()->label() \n\t\t<< \"\\\". Trying to recover.\" << std::endl;\n }\n }\n}\n\n\/**\n * Writes all data from sample buffer pointed by 'sbuf'. Notes\n * concerning read_buffer() also apply to this routine.\n *\/\nvoid AUDIO_IO_DB_CLIENT::write_buffer(SAMPLE_BUFFER* sbuf)\n{\n DBC_CHECK(pbuffer_repp != 0);\n\n if (pbuffer_repp->write_space() > 0) {\n SAMPLE_BUFFER* target = pbuffer_repp->sbufs_rep[pbuffer_repp->writeptr_rep.get()];\n target->copy_all_content(*sbuf);\n target->number_of_channels(channels());\n pbuffer_repp->advance_write_pointer();\n pserver_repp->signal_client_activity();\n change_position_in_samples(sbuf->length_in_samples());\n extend_position();\n }\n else {\n if (pbuffer_repp->finished_rep.get() == 1) finished_rep = true;\n else {\n \/* NOTE: not always rt-safe, but it's better to break rt-safety than\n * to lose recorded data *\/\n\n std::cerr << \"(audioio-db-client) WARNING: Overrun in writing to \\\"\" \n\t\t<< child()->label() \n\t\t<< \"\\\". Trying to recover.\" << std::endl;\n\n xruns_rep++;\n\n pserver_repp->wait_for_full();\n if (recursing_rep != true && pbuffer_repp->write_space() > 0) {\n\trecursing_rep = true;\n\tthis->write_buffer(sbuf);\n\trecursing_rep = false;\n }\n else {\n\tseek_position(position_in_samples()); \/\/ hack to force a restart of the db server\n\tstd::cerr << \"(audioio-db-client) Serious trouble with the disk-io subsystem! (output)\" << std::endl;\n }\n }\n }\n}\n\n\/**\n * Stops the DB server in case it's running. \n * Returns true if server was running. The return\n * value should be passed to restore_db_server_state()\n * function.\n *\/\nbool AUDIO_IO_DB_CLIENT::pause_db_server_if_running(void)\n{\n bool was_running = false;\n if (pserver_repp->is_running() == true) {\n was_running = true;\n pserver_repp->stop();\n pserver_repp->wait_for_stop();\n DBC_CHECK(pserver_repp->is_running() != true);\n }\n\n return was_running;\n}\n\nvoid AUDIO_IO_DB_CLIENT::restore_db_server_state(bool was_running)\n{\n if (was_running == true) {\n pserver_repp->start();\n pserver_repp->wait_for_full();\n DBC_CHECK(pserver_repp->is_running() == true);\n }\n}\n\n\/**\n * Seeks to the current position.\n *\n * Note! Seeking involves stopping the whole db \n * server, so it's a costly operation.\n *\/\nSAMPLE_SPECS::sample_pos_t AUDIO_IO_DB_CLIENT::seek_position(SAMPLE_SPECS::sample_pos_t pos)\n{ \n ECA_LOG_MSG(ECA_LOGGER::user_objects, \n\t \"seek \" + label() + \n\t \" to pos \" + kvu_numtostr(pos) + \".\");\n SAMPLE_SPECS::sample_pos_t res =\n child()->position_in_samples();\n \n if (child()->supports_seeking() == true) {\n bool was_running = pause_db_server_if_running();\n\n child()->seek_position_in_samples(pos);\n res = child()->position_in_samples();\n if (pbuffer_repp != 0) {\n pbuffer_repp->reset();\n }\n\n finished_rep = false;\n\n restore_db_server_state(was_running);\n }\n\n return AUDIO_IO_PROXY::seek_position(res);\n}\n\n\/**\n * Opens the child audio object (possibly in exclusive mode).\n * This routine is meant for opening files and devices,\n * loading libraries, etc. \n *\/\nvoid AUDIO_IO_DB_CLIENT::open(void) throw(AUDIO_IO::SETUP_ERROR&) \n{\n ECA_LOG_MSG(ECA_LOGGER::user_objects, \"open \" + label() + \".\");\n\n if (child()->is_open() != true) {\n child()->open();\n }\n\n set_audio_format(child()->audio_format());\n set_length_in_samples(child()->length_in_samples());\n\n if (pbuffer_repp == 0) {\n pserver_repp->register_client(child());\n pbuffer_repp = pserver_repp->get_client_buffer(child());\n\n for(unsigned int n = 0; n < pbuffer_repp->sbufs_rep.size(); n++) {\n pbuffer_repp->sbufs_rep[n]->number_of_channels(channels());\n pbuffer_repp->sbufs_rep[n]->length_in_samples(buffersize());\n }\n\n if (io_mode() == AUDIO_IO::io_read) \n pbuffer_repp->io_mode_rep = AUDIO_IO::io_read;\n else\n pbuffer_repp->io_mode_rep = AUDIO_IO::io_write;\n }\n\n AUDIO_IO::open();\n}\n\n\/**\n * Closes the child audio object. After calling this routine, \n * all resources (ie. soundcard) must be freed\n * (they can be used by other processes).\n *\/\nvoid AUDIO_IO_DB_CLIENT::close(void)\n{\n ECA_LOG_MSG(ECA_LOGGER::user_objects, \"close \" + label() + \".\");\n\n if (child()->is_open() == true) child()->close();\n\n AUDIO_IO::close();\n}\n\nvoid AUDIO_IO_DB_CLIENT::start_io(void)\n{\n AUDIO_IO_PROXY::start_io();\n\n \/* note: child may have changed its position after \n * start_io() is issued (via AUDIO_IO_PROXY::start_io() *\/\n\n if (child()->supports_seeking() != true) {\n bool was_running = pause_db_server_if_running();\n\n set_position_in_samples(child()->position_in_samples());\n\n \/* as position might have changed, flush the buffers *\/\n if (pbuffer_repp != 0) {\n pbuffer_repp->reset();\n }\n\n restore_db_server_state(was_running);\n }\n}\n\nvoid AUDIO_IO_DB_CLIENT::stop_io(void)\n{\n AUDIO_IO_PROXY::stop_io();\n}\n<commit_msg>Added a dbc check to AUDIO_IO_DB_CLIENT<commit_after>\/\/ ------------------------------------------------------------------------\n\/\/ audioio-db-client.cpp: Client class for double-buffering providing \n\/\/ additional layer of buffering for objects\n\/\/ derived from AUDIO_IO.\n\/\/ Copyright (C) 2000-2005,2009 Kai Vehmanen\n\/\/\n\/\/ Attributes:\n\/\/ eca-style-version: 3\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; 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. 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, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ ------------------------------------------------------------------------\n\n#include <unistd.h> \/* open(), close() *\/\n\n#include <kvu_dbc.h>\n#include <kvu_numtostr.h>\n\n#include \"samplebuffer.h\"\n#include \"eca-logger.h\"\n#include \"audioio-db-client.h\"\n\n\/**\n * Constructor. The given client object is registered to \n * the given db server as a client object.\n *\n * Ownership of 'aobject' is transfered to this db client\n * object if 'transfer_ownership' is true.\n *\/\nAUDIO_IO_DB_CLIENT::AUDIO_IO_DB_CLIENT (AUDIO_IO_DB_SERVER *pserver, \n\t\t\t\t\tAUDIO_IO* aobject,\n\t\t\t\t\tbool transfer_ownership) \n : pserver_repp(pserver),\n free_child_rep(transfer_ownership) \n{\n set_child(aobject);\n pbuffer_repp = 0;\n xruns_rep = 0;\n finished_rep = false;\n recursing_rep = false;\n\n ECA_LOG_MSG(ECA_LOGGER::user_objects, \n\t\tstd::string(\"DB-client created for \") +\n\t\tchild()->label() +\n\t\t\".\");\n\n \/\/ just in case the child object has already been configured\n fetch_initial_child_data();\n}\n\n\/**\n * Copy attributes from the proxied (child) object.\n *\/\nvoid AUDIO_IO_DB_CLIENT::fetch_initial_child_data(void)\n{\n \/\/ note! the child object is one that is configured\n \/\/ at this point\n set_audio_format(child()->audio_format());\n set_position_in_samples(child()->position_in_samples());\n set_length_in_samples(child()->length_in_samples());\n set_buffersize(child()->buffersize());\n set_io_mode(child()->io_mode());\n set_label(child()->label());\n toggle_nonblocking_mode(child()->nonblocking_mode());\n}\n\n\/**\n * Desctructor. Unregisters the client from the db\n * server.\n *\/\nAUDIO_IO_DB_CLIENT::~AUDIO_IO_DB_CLIENT(void)\n{\n ECA_LOG_MSG(ECA_LOGGER::user_objects, \"destructor \" + label() + \".\");\n\n if (is_open() == true) {\n close();\n }\n\n if (pserver_repp != 0) {\n bool was_running = false;\n if (pserver_repp->is_running() == true) {\n was_running = true;\n pserver_repp->stop();\n pserver_repp->wait_for_stop();\n DBC_CHECK(pserver_repp->is_running() != true);\n }\n\n pserver_repp->unregister_client(child());\n pbuffer_repp = 0;\n\n if (was_running == true) {\n pserver_repp->start();\n }\n }\n \n if (free_child_rep != true) {\n \/* to avoid deleting the original registered child *\/\n release_child_no_delete();\n }\n \n if (xruns_rep > 0) \n std::cerr << \"(audioio-db-client) There were total \" << xruns_rep << \" xruns.\" << std::endl;\n}\n\n\/**\n * Whether all data has been processed? If opened in mode 'io_read', \n * this means that end of stream has been reached. If opened in \n * 'io_write' or 'io_readwrite' modes, finished status usually\n * means that an error has occured (no space left, etc). After \n * finished() has returned 'true', further calls to read_buffer() \n * and\/or write_buffer() won't process any data.\n *\/\nbool AUDIO_IO_DB_CLIENT::finished(void) const { return finished_rep; }\n\n\/**\n * Reads samples to buffer pointed by 'sbuf'. If necessary, the target \n * buffer will be resized.\n *\/\nvoid AUDIO_IO_DB_CLIENT::read_buffer(SAMPLE_BUFFER* sbuf)\n{\n DBC_CHECK(pbuffer_repp != 0);\n\n if (pbuffer_repp->read_space() > 0) {\n SAMPLE_BUFFER* source = pbuffer_repp->sbufs_rep[pbuffer_repp->readptr_rep.get()];\n sbuf->copy_all_content(*source);\n pbuffer_repp->advance_read_pointer();\n pserver_repp->signal_client_activity();\n change_position_in_samples(sbuf->length_in_samples());\n }\n else {\n sbuf->number_of_channels(channels());\n if (pbuffer_repp->finished_rep.get() == 1) {\n finished_rep = true;\n sbuf->length_in_samples(0);\n }\n else {\n xruns_rep++;\n sbuf->length_in_samples(0);\n\n std::cerr << \"(audioio-db-client) WARNING: Underrun in reading from \\\"\" \n\t\t<< child()->label() \n\t\t<< \"\\\". Trying to recover.\" << std::endl;\n }\n }\n\n \/\/ --------\n DBC_ENSURE(sbuf->number_of_channels() == channels());\n \/\/ --------\n}\n\n\/**\n * Writes all data from sample buffer pointed by 'sbuf'. Notes\n * concerning read_buffer() also apply to this routine.\n *\/\nvoid AUDIO_IO_DB_CLIENT::write_buffer(SAMPLE_BUFFER* sbuf)\n{\n DBC_CHECK(pbuffer_repp != 0);\n\n if (pbuffer_repp->write_space() > 0) {\n SAMPLE_BUFFER* target = pbuffer_repp->sbufs_rep[pbuffer_repp->writeptr_rep.get()];\n target->copy_all_content(*sbuf);\n target->number_of_channels(channels());\n pbuffer_repp->advance_write_pointer();\n pserver_repp->signal_client_activity();\n change_position_in_samples(sbuf->length_in_samples());\n extend_position();\n }\n else {\n if (pbuffer_repp->finished_rep.get() == 1) finished_rep = true;\n else {\n \/* NOTE: not always rt-safe, but it's better to break rt-safety than\n * to lose recorded data *\/\n\n std::cerr << \"(audioio-db-client) WARNING: Overrun in writing to \\\"\" \n\t\t<< child()->label() \n\t\t<< \"\\\". Trying to recover.\" << std::endl;\n\n xruns_rep++;\n\n pserver_repp->wait_for_full();\n if (recursing_rep != true && pbuffer_repp->write_space() > 0) {\n\trecursing_rep = true;\n\tthis->write_buffer(sbuf);\n\trecursing_rep = false;\n }\n else {\n\tseek_position(position_in_samples()); \/\/ hack to force a restart of the db server\n\tstd::cerr << \"(audioio-db-client) Serious trouble with the disk-io subsystem! (output)\" << std::endl;\n }\n }\n }\n}\n\n\/**\n * Stops the DB server in case it's running. \n * Returns true if server was running. The return\n * value should be passed to restore_db_server_state()\n * function.\n *\/\nbool AUDIO_IO_DB_CLIENT::pause_db_server_if_running(void)\n{\n bool was_running = false;\n if (pserver_repp->is_running() == true) {\n was_running = true;\n pserver_repp->stop();\n pserver_repp->wait_for_stop();\n DBC_CHECK(pserver_repp->is_running() != true);\n }\n\n return was_running;\n}\n\nvoid AUDIO_IO_DB_CLIENT::restore_db_server_state(bool was_running)\n{\n if (was_running == true) {\n pserver_repp->start();\n pserver_repp->wait_for_full();\n DBC_CHECK(pserver_repp->is_running() == true);\n }\n}\n\n\/**\n * Seeks to the current position.\n *\n * Note! Seeking involves stopping the whole db \n * server, so it's a costly operation.\n *\/\nSAMPLE_SPECS::sample_pos_t AUDIO_IO_DB_CLIENT::seek_position(SAMPLE_SPECS::sample_pos_t pos)\n{ \n ECA_LOG_MSG(ECA_LOGGER::user_objects, \n\t \"seek \" + label() + \n\t \" to pos \" + kvu_numtostr(pos) + \".\");\n SAMPLE_SPECS::sample_pos_t res =\n child()->position_in_samples();\n \n if (child()->supports_seeking() == true) {\n bool was_running = pause_db_server_if_running();\n\n child()->seek_position_in_samples(pos);\n res = child()->position_in_samples();\n if (pbuffer_repp != 0) {\n pbuffer_repp->reset();\n }\n\n finished_rep = false;\n\n restore_db_server_state(was_running);\n }\n\n return AUDIO_IO_PROXY::seek_position(res);\n}\n\n\/**\n * Opens the child audio object (possibly in exclusive mode).\n * This routine is meant for opening files and devices,\n * loading libraries, etc. \n *\/\nvoid AUDIO_IO_DB_CLIENT::open(void) throw(AUDIO_IO::SETUP_ERROR&) \n{\n ECA_LOG_MSG(ECA_LOGGER::user_objects, \"open \" + label() + \".\");\n\n if (child()->is_open() != true) {\n child()->open();\n }\n\n set_audio_format(child()->audio_format());\n set_length_in_samples(child()->length_in_samples());\n\n if (pbuffer_repp == 0) {\n pserver_repp->register_client(child());\n pbuffer_repp = pserver_repp->get_client_buffer(child());\n\n for(unsigned int n = 0; n < pbuffer_repp->sbufs_rep.size(); n++) {\n pbuffer_repp->sbufs_rep[n]->number_of_channels(channels());\n pbuffer_repp->sbufs_rep[n]->length_in_samples(buffersize());\n }\n\n if (io_mode() == AUDIO_IO::io_read) \n pbuffer_repp->io_mode_rep = AUDIO_IO::io_read;\n else\n pbuffer_repp->io_mode_rep = AUDIO_IO::io_write;\n }\n\n AUDIO_IO::open();\n}\n\n\/**\n * Closes the child audio object. After calling this routine, \n * all resources (ie. soundcard) must be freed\n * (they can be used by other processes).\n *\/\nvoid AUDIO_IO_DB_CLIENT::close(void)\n{\n ECA_LOG_MSG(ECA_LOGGER::user_objects, \"close \" + label() + \".\");\n\n if (child()->is_open() == true) child()->close();\n\n AUDIO_IO::close();\n}\n\nvoid AUDIO_IO_DB_CLIENT::start_io(void)\n{\n AUDIO_IO_PROXY::start_io();\n\n \/* note: child may have changed its position after \n * start_io() is issued (via AUDIO_IO_PROXY::start_io() *\/\n\n if (child()->supports_seeking() != true) {\n bool was_running = pause_db_server_if_running();\n\n set_position_in_samples(child()->position_in_samples());\n\n \/* as position might have changed, flush the buffers *\/\n if (pbuffer_repp != 0) {\n pbuffer_repp->reset();\n }\n\n restore_db_server_state(was_running);\n }\n}\n\nvoid AUDIO_IO_DB_CLIENT::stop_io(void)\n{\n AUDIO_IO_PROXY::stop_io();\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Zowi LED Matrix Library\n* \n* @version 20150710\n* @author Raul de Pablos Martin\n* José Alberca Pita-Romero (Mouth's definitions)\n******************************************************************************\/\n\n#include \"LedMatrix.h\"\n\n#if defined(ARDUINO) && ARDUINO >= 100\n #include \"Arduino.h\"\n#else\n #include \"WProgram.h\"\n#endif\n\nLedMatrix::LedMatrix(char ser_pin, char clk_pin, char rck_pin) {\n\tmemory = 0x00000000;\n\tSER = ser_pin;\n\tCLK = clk_pin;\n\tRCK = rck_pin;\n\tpinMode(SER, OUTPUT);\n\tpinMode(CLK, OUTPUT);\n\tpinMode(RCK, OUTPUT);\n\tdigitalWrite(SER, LOW);\n\tdigitalWrite(CLK, LOW);\n\tdigitalWrite(RCK, LOW);\n\tsendMemory();\n}\n\nvoid LedMatrix::writeFull(unsigned long value) {\n\tmemory = value;\n\tsendMemory();\n}\n\nunsigned long LedMatrix::readFull(void) {\n\treturn memory;\n}\n\nvoid LedMatrix::setLed(char row, char column) {\n\tif(row >= 1 && row <= ROWS && column >= 1 && column <= COLUMNS) {\n\t\tmemory |= (1L << (MATRIX_LENGTH - (row-1)*COLUMNS - (column)));\n\t\tsendMemory();\n\t}\n}\n\nvoid LedMatrix::unsetLed(char row, char column) {\n\tif(row >= 1 && row <= ROWS && column >= 1 && column <= COLUMNS) {\n\t\tmemory &= ~(1L << (MATRIX_LENGTH - (row-1)*COLUMNS - (column)));\n\t\tsendMemory();\n\t}\n}\n\nvoid LedMatrix::clearMatrix(void) {\n\tmemory = 0x00000000;\n\tsendMemory();\n}\n\nvoid LedMatrix::setEntireMatrix(void) {\n\tmemory = 0x3FFFFFFF;\n\tsendMemory();\n}\n\nvoid LedMatrix::sendMemory(void) {\n\tint i;\n\t\n\tfor(i = 0; i < MATRIX_LENGTH; i++) {\n\t\tdigitalWrite(SER, 1L & (memory >> i));\t\n\t\t\/\/ ## adjust this delay to match with 74HC595 timing\n\t\tasm volatile (\"nop\");\n\t\tasm volatile (\"nop\");\n\t\tasm volatile (\"nop\");\n\t\tdigitalWrite(CLK, 1);\n\t\t\/\/ ## adjust this delay to match with 74HC595 timing\n\t\tasm volatile (\"nop\");\n\t\tasm volatile (\"nop\");\n\t\tasm volatile (\"nop\");\n\t\tdigitalWrite(CLK, 0);\t\n\t}\n\t\n\tdigitalWrite(RCK, 1);\n\t\/\/ ## adjust this delay to match with 74HC595 timing\n\tasm volatile (\"nop\");\n\tasm volatile (\"nop\");\n\tasm volatile (\"nop\");\n\tdigitalWrite(RCK, 0);\t\n}\n\n<commit_msg>Delete LedMatrix.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Stepper.cpp - Stepper library for Wiring\/Arduino - Version 1.1.0\n *\n * Original library (0.1) by Tom Igoe.\n * Two-wire modifications (0.2) by Sebastian Gassner\n * Combination version (0.3) by Tom Igoe and David Mellis\n * Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley\n * High-speed stepping mod by Eugene Kozlenko\n * Timer rollover fix by Eugene Kozlenko\n * Five phase five wire (1.1.0) by Ryan Orendorff\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\n * Drives a unipolar, bipolar, or five phase stepper motor.\n *\n * When wiring multiple stepper motors to a microcontroller, you quickly run\n * out of output pins, with each motor requiring 4 connections.\n *\n * By making use of the fact that at any time two of the four motor coils are\n * the inverse of the other two, the number of control connections can be\n * reduced from 4 to 2 for the unipolar and bipolar motors.\n *\n * A slightly modified circuit around a Darlington transistor array or an\n * L293 H-bridge connects to only 2 microcontroler pins, inverts the signals\n * received, and delivers the 4 (2 plus 2 inverted ones) output signals\n * required for driving a stepper motor. Similarly the Arduino motor shields\n * 2 direction pins may be used.\n *\n * The sequence of control signals for 5 phase, 5 control wires is as follows:\n *\n * Step C0 C1 C2 C3 C4\n * 1 0 1 1 0 1\n * 2 0 1 0 0 1\n * 3 0 1 0 1 1\n * 4 0 1 0 1 0\n * 5 1 1 0 1 0\n * 6 1 0 0 1 0\n * 7 1 0 1 1 0\n * 8 1 0 1 0 0\n * 9 1 0 1 0 1\n * 10 0 0 1 0 1\n *\n * The sequence of control signals for 4 control wires is as follows:\n *\n * Step C0 C1 C2 C3\n * 1 1 0 1 0\n * 2 0 1 1 0\n * 3 0 1 0 1\n * 4 1 0 0 1\n *\n * The sequence of controls signals for 2 control wires is as follows\n * (columns C1 and C2 from above):\n *\n * Step C0 C1\n * 1 0 1\n * 2 1 1\n * 3 1 0\n * 4 0 0\n *\n * The circuits can be found at\n *\n * http:\/\/www.arduino.cc\/en\/Tutorial\/Stepper\n *\/\n\n#include \"Arduino.h\"\n#include \"Stepper.h\"\n\n\/*\n * two-wire constructor.\n * Sets which wires should control the motor.\n *\/\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2)\n{\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in us of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n\n \/\/ When there are only 2 pins, set the others to 0:\n this->motor_pin_3 = 0;\n this->motor_pin_4 = 0;\n this->motor_pin_5 = 0;\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 2;\n}\n\n\n\/*\n * constructor for four-pin version\n * Sets which wires should control the motor.\n *\/\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2,\n int motor_pin_3, int motor_pin_4)\n{\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in us of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n this->motor_pin_3 = motor_pin_3;\n this->motor_pin_4 = motor_pin_4;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n pinMode(this->motor_pin_3, OUTPUT);\n pinMode(this->motor_pin_4, OUTPUT);\n\n \/\/ When there are 4 pins, set the others to 0:\n this->motor_pin_5 = 0;\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 4;\n}\n\n\/*\n * constructor for five phase motor with five wires\n * Sets which wires should control the motor.\n *\/\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2,\n int motor_pin_3, int motor_pin_4,\n int motor_pin_5)\n{\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in us of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n this->motor_pin_3 = motor_pin_3;\n this->motor_pin_4 = motor_pin_4;\n this->motor_pin_5 = motor_pin_5;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n pinMode(this->motor_pin_3, OUTPUT);\n pinMode(this->motor_pin_4, OUTPUT);\n pinMode(this->motor_pin_5, OUTPUT);\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 5;\n}\n\n\/*\n * Sets the speed in revs per minute\n *\/\nvoid Stepper::setSpeed(long whatSpeed)\n{\n this->step_delay = 60L * 1000L * 1000L \/ this->number_of_steps \/ whatSpeed;\n}\n\n\/*\n * Moves the motor steps_to_move steps. If the number is negative,\n * the motor moves in the reverse direction.\n *\/\nvoid Stepper::step(int steps_to_move)\n{\n int steps_left = abs(steps_to_move); \/\/ how many steps to take\n\n \/\/ determine direction based on whether steps_to_mode is + or -:\n if (steps_to_move > 0) {this->direction = 1;}\n if (steps_to_move < 0) {this->direction = 0;}\n\n\n \/\/ decrement the number of steps, moving one step each time:\n while(steps_left > 0) {\n \/\/ move only if the appropriate delay has passed:\n if (micros() - this->last_step_time >= this->step_delay || micros() < this->last_step_time) {\n \/\/ get the timeStamp of when you stepped:\n this->last_step_time = micros();\n \/\/ increment or decrement the step number,\n \/\/ depending on direction:\n if (this->direction == 1) {\n this->step_number++;\n if (this->step_number == this->number_of_steps) {\n this->step_number = 0;\n }\n }\n else {\n if (this->step_number == 0) {\n this->step_number = this->number_of_steps;\n }\n this->step_number--;\n }\n \/\/ decrement the steps left:\n steps_left--;\n \/\/ step the motor to step number 0, 1, ..., {3 or 10}\n if (this->pin_count == 5)\n stepMotor(this->step_number % 10);\n else\n stepMotor(this->step_number % 4);\n }\n }\n}\n\n\/*\n * Moves the motor forward or backwards.\n *\/\nvoid Stepper::stepMotor(int thisStep)\n{\n if (this->pin_count == 2) {\n switch (thisStep) {\n case 0: \/\/ 01\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n break;\n case 1: \/\/ 11\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, HIGH);\n break;\n case 2: \/\/ 10\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n break;\n case 3: \/\/ 00\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, LOW);\n break;\n }\n }\n if (this->pin_count == 4) {\n switch (thisStep) {\n case 0: \/\/ 1010\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n break;\n case 1: \/\/ 0110\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n break;\n case 2: \/\/0101\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n break;\n case 3: \/\/1001\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n break;\n }\n }\n\n if (this->pin_count == 5) {\n switch (thisStep) {\n case 0: \/\/ 01101\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, HIGH);\n break;\n case 1: \/\/ 01001\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, HIGH);\n break;\n case 2: \/\/ 01011\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, HIGH);\n break;\n case 3: \/\/ 01010\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 4: \/\/ 11010\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 5: \/\/ 10010\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 6: \/\/ 10110\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 7: \/\/ 10100\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 8: \/\/ 10101\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, HIGH);\n break;\n case 9: \/\/ 00101\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, HIGH);\n break;\n }\n }\n}\n\n\/*\n version() returns the version of the library:\n*\/\nint Stepper::version(void)\n{\n return 5;\n}\n<commit_msg>Stepper: optimization on timing calculations<commit_after>\/*\n * Stepper.cpp - Stepper library for Wiring\/Arduino - Version 1.1.0\n *\n * Original library (0.1) by Tom Igoe.\n * Two-wire modifications (0.2) by Sebastian Gassner\n * Combination version (0.3) by Tom Igoe and David Mellis\n * Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley\n * High-speed stepping mod by Eugene Kozlenko\n * Timer rollover fix by Eugene Kozlenko\n * Five phase five wire (1.1.0) by Ryan Orendorff\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\n * Drives a unipolar, bipolar, or five phase stepper motor.\n *\n * When wiring multiple stepper motors to a microcontroller, you quickly run\n * out of output pins, with each motor requiring 4 connections.\n *\n * By making use of the fact that at any time two of the four motor coils are\n * the inverse of the other two, the number of control connections can be\n * reduced from 4 to 2 for the unipolar and bipolar motors.\n *\n * A slightly modified circuit around a Darlington transistor array or an\n * L293 H-bridge connects to only 2 microcontroler pins, inverts the signals\n * received, and delivers the 4 (2 plus 2 inverted ones) output signals\n * required for driving a stepper motor. Similarly the Arduino motor shields\n * 2 direction pins may be used.\n *\n * The sequence of control signals for 5 phase, 5 control wires is as follows:\n *\n * Step C0 C1 C2 C3 C4\n * 1 0 1 1 0 1\n * 2 0 1 0 0 1\n * 3 0 1 0 1 1\n * 4 0 1 0 1 0\n * 5 1 1 0 1 0\n * 6 1 0 0 1 0\n * 7 1 0 1 1 0\n * 8 1 0 1 0 0\n * 9 1 0 1 0 1\n * 10 0 0 1 0 1\n *\n * The sequence of control signals for 4 control wires is as follows:\n *\n * Step C0 C1 C2 C3\n * 1 1 0 1 0\n * 2 0 1 1 0\n * 3 0 1 0 1\n * 4 1 0 0 1\n *\n * The sequence of controls signals for 2 control wires is as follows\n * (columns C1 and C2 from above):\n *\n * Step C0 C1\n * 1 0 1\n * 2 1 1\n * 3 1 0\n * 4 0 0\n *\n * The circuits can be found at\n *\n * http:\/\/www.arduino.cc\/en\/Tutorial\/Stepper\n *\/\n\n#include \"Arduino.h\"\n#include \"Stepper.h\"\n\n\/*\n * two-wire constructor.\n * Sets which wires should control the motor.\n *\/\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2)\n{\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in us of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n\n \/\/ When there are only 2 pins, set the others to 0:\n this->motor_pin_3 = 0;\n this->motor_pin_4 = 0;\n this->motor_pin_5 = 0;\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 2;\n}\n\n\n\/*\n * constructor for four-pin version\n * Sets which wires should control the motor.\n *\/\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2,\n int motor_pin_3, int motor_pin_4)\n{\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in us of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n this->motor_pin_3 = motor_pin_3;\n this->motor_pin_4 = motor_pin_4;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n pinMode(this->motor_pin_3, OUTPUT);\n pinMode(this->motor_pin_4, OUTPUT);\n\n \/\/ When there are 4 pins, set the others to 0:\n this->motor_pin_5 = 0;\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 4;\n}\n\n\/*\n * constructor for five phase motor with five wires\n * Sets which wires should control the motor.\n *\/\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2,\n int motor_pin_3, int motor_pin_4,\n int motor_pin_5)\n{\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in us of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n this->motor_pin_3 = motor_pin_3;\n this->motor_pin_4 = motor_pin_4;\n this->motor_pin_5 = motor_pin_5;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n pinMode(this->motor_pin_3, OUTPUT);\n pinMode(this->motor_pin_4, OUTPUT);\n pinMode(this->motor_pin_5, OUTPUT);\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 5;\n}\n\n\/*\n * Sets the speed in revs per minute\n *\/\nvoid Stepper::setSpeed(long whatSpeed)\n{\n this->step_delay = 60L * 1000L * 1000L \/ this->number_of_steps \/ whatSpeed;\n}\n\n\/*\n * Moves the motor steps_to_move steps. If the number is negative,\n * the motor moves in the reverse direction.\n *\/\nvoid Stepper::step(int steps_to_move)\n{\n int steps_left = abs(steps_to_move); \/\/ how many steps to take\n\n \/\/ determine direction based on whether steps_to_mode is + or -:\n if (steps_to_move > 0) {this->direction = 1;}\n if (steps_to_move < 0) {this->direction = 0;}\n\n\n \/\/ decrement the number of steps, moving one step each time:\n while(steps_left > 0) {\n unsigned long now = micros();\n \/\/ move only if the appropriate delay has passed:\n if (now - this->last_step_time >= this->step_delay) {\n \/\/ get the timeStamp of when you stepped:\n this->last_step_time = now;\n \/\/ increment or decrement the step number,\n \/\/ depending on direction:\n if (this->direction == 1) {\n this->step_number++;\n if (this->step_number == this->number_of_steps) {\n this->step_number = 0;\n }\n }\n else {\n if (this->step_number == 0) {\n this->step_number = this->number_of_steps;\n }\n this->step_number--;\n }\n \/\/ decrement the steps left:\n steps_left--;\n \/\/ step the motor to step number 0, 1, ..., {3 or 10}\n if (this->pin_count == 5)\n stepMotor(this->step_number % 10);\n else\n stepMotor(this->step_number % 4);\n }\n }\n}\n\n\/*\n * Moves the motor forward or backwards.\n *\/\nvoid Stepper::stepMotor(int thisStep)\n{\n if (this->pin_count == 2) {\n switch (thisStep) {\n case 0: \/\/ 01\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n break;\n case 1: \/\/ 11\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, HIGH);\n break;\n case 2: \/\/ 10\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n break;\n case 3: \/\/ 00\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, LOW);\n break;\n }\n }\n if (this->pin_count == 4) {\n switch (thisStep) {\n case 0: \/\/ 1010\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n break;\n case 1: \/\/ 0110\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n break;\n case 2: \/\/0101\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n break;\n case 3: \/\/1001\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n break;\n }\n }\n\n if (this->pin_count == 5) {\n switch (thisStep) {\n case 0: \/\/ 01101\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, HIGH);\n break;\n case 1: \/\/ 01001\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, HIGH);\n break;\n case 2: \/\/ 01011\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, HIGH);\n break;\n case 3: \/\/ 01010\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 4: \/\/ 11010\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 5: \/\/ 10010\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 6: \/\/ 10110\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, HIGH);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 7: \/\/ 10100\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, LOW);\n break;\n case 8: \/\/ 10101\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, HIGH);\n break;\n case 9: \/\/ 00101\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n digitalWrite(motor_pin_5, HIGH);\n break;\n }\n }\n}\n\n\/*\n version() returns the version of the library:\n*\/\nint Stepper::version(void)\n{\n return 5;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\r\n#include <windows.h>\r\n#include <shellapi.h>\r\n#include \"..\/Config.h\"\r\n#include \"resource.h\"\r\n#include \"Win32App.h\"\r\n#include <stdio.h>\r\n\r\n#if defined(_MSC_VER) && _MSC_VER < 1900\r\n#define snprintf _snprintf\r\n#endif\r\n\r\n#define ID_ABOUT 2000\r\n#define ID_EXIT 2001\r\n#define ID_CONSOLE 2002\r\n#define ID_APP 2003\r\n\r\n#define ID_TRAY_ICON 2050\r\n#define WM_TRAYICON (WM_USER + 1)\r\n\r\nnamespace i2p\r\n{\r\nnamespace win32\r\n{\r\n static void ShowPopupMenu (HWND hWnd, POINT *curpos, int wDefaultItem)\r\n {\r\n HMENU hPopup = CreatePopupMenu();\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_CONSOLE, \"Open &console\");\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_APP, \"Show app\");\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_ABOUT, \"&About...\");\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_SEPARATOR, NULL, NULL);\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_EXIT, \"E&xit\");\r\n SetMenuDefaultItem (hPopup, ID_CONSOLE, FALSE);\r\n SendMessage (hWnd, WM_INITMENUPOPUP, (WPARAM)hPopup, 0);\r\n\r\n POINT p;\r\n if (!curpos)\r\n {\r\n GetCursorPos (&p);\r\n curpos = &p;\r\n }\r\n\r\n WORD cmd = TrackPopupMenu (hPopup, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY, curpos->x, curpos->y, 0, hWnd, NULL);\r\n SendMessage (hWnd, WM_COMMAND, cmd, 0);\r\n\r\n DestroyMenu(hPopup);\r\n }\r\n\r\n static void AddTrayIcon (HWND hWnd)\r\n {\r\n NOTIFYICONDATA nid;\r\n memset(&nid, 0, sizeof(nid));\r\n nid.cbSize = sizeof(nid);\r\n nid.hWnd = hWnd;\r\n nid.uID = ID_TRAY_ICON;\r\n nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;\r\n nid.uCallbackMessage = WM_TRAYICON;\r\n nid.hIcon = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE (MAINICON));\r\n strcpy (nid.szTip, \"i2pd\");\r\n strcpy (nid.szInfo, \"i2pd is running\");\r\n Shell_NotifyIcon(NIM_ADD, &nid );\r\n }\r\n\r\n static void RemoveTrayIcon (HWND hWnd)\r\n {\r\n NOTIFYICONDATA nid;\r\n nid.hWnd = hWnd;\r\n nid.uID = ID_TRAY_ICON;\r\n Shell_NotifyIcon (NIM_DELETE, &nid);\r\n }\r\n\r\n static LRESULT CALLBACK WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\r\n {\r\n switch (uMsg)\r\n {\r\n case WM_CREATE:\r\n {\r\n AddTrayIcon (hWnd);\r\n break;\r\n }\r\n case WM_CLOSE:\r\n {\r\n RemoveTrayIcon (hWnd);\r\n PostQuitMessage (0);\r\n break;\r\n }\r\n case WM_COMMAND:\r\n {\r\n switch (LOWORD(wParam))\r\n {\r\n case ID_ABOUT:\r\n {\r\n MessageBox( hWnd, TEXT(\"i2pd\"), TEXT(\"About\"), MB_ICONINFORMATION | MB_OK );\r\n return 0;\r\n }\r\n case ID_EXIT:\r\n {\r\n PostMessage (hWnd, WM_CLOSE, 0, 0);\r\n return 0;\r\n }\r\n case ID_CONSOLE:\r\n {\r\n char buf[30];\r\n std::string httpAddr; i2p::config::GetOption(\"http.address\", httpAddr);\r\n uint16_t httpPort; i2p::config::GetOption(\"http.port\", httpPort);\r\n snprintf(buf, 30, \"http:\/\/%s:%d\", httpAddr.c_str(), httpPort);\r\n ShellExecute(NULL, \"open\", buf, NULL, NULL, SW_SHOWNORMAL);\r\n return 0;\r\n }\r\n case ID_APP:\r\n {\r\n ShowWindow(hWnd, SW_SHOW);\r\n return 0;\r\n }\r\n }\r\n break;\r\n }\r\n case WM_SYSCOMMAND:\r\n {\r\n switch (wParam)\r\n {\r\n case SC_MINIMIZE:\r\n {\r\n ShowWindow(hWnd, SW_HIDE);\r\n return 0;\r\n }\r\n case SC_CLOSE:\r\n {\r\n std::string close; i2p::config::GetOption(\"close\", close);\r\n if (0 == close.compare(\"ask\"))\r\n switch(::MessageBox(hWnd, \"Would you like to minimize instead of exiting?\"\r\n \" You can add 'close' configuration option. Valid values are: ask, minimize, exit.\",\r\n \"Minimize instead of exiting?\", MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON1))\r\n {\r\n case IDYES: close = \"minimize\"; break;\r\n case IDNO: close = \"exit\"; break;\r\n default: return 0;\r\n }\r\n if (0 == close.compare(\"minimize\"))\r\n {\r\n ShowWindow(hWnd, SW_HIDE);\r\n return 0;\r\n }\r\n if (0 != close.compare(\"exit\"))\r\n {\r\n ::MessageBox(hWnd, close.c_str(), \"Unknown close action in config\", MB_OK | MB_ICONWARNING);\r\n return 0;\r\n }\r\n }\r\n }\r\n }\r\n case WM_TRAYICON:\r\n {\r\n switch (lParam)\r\n {\r\n case WM_LBUTTONUP:\r\n case WM_RBUTTONUP:\r\n {\r\n SetForegroundWindow (hWnd);\r\n ShowPopupMenu(hWnd, NULL, -1);\r\n PostMessage (hWnd, WM_APP + 1, 0, 0);\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n\t\t case WM_PAINT:\r\n\t\t {\r\n\t\t\tPAINTSTRUCT ps;\r\n\t\t\tauto hDC = BeginPaint (hWnd, &ps);\r\n\t\t\tauto mascot = LoadBitmap (GetModuleHandle(NULL), MAKEINTRESOURCE (MASCOT));\r\n\t\t\tauto mascotDC = CreateCompatibleDC (hDC);\r\n\t\t\tSelectObject (mascotDC, mascot);\r\n\t\t\tBitBlt (hDC, 0,0, 533, 700, mascotDC, 0, 0, SRCCOPY);\t\r\n\t\t\tDeleteDC (mascotDC);\r\n\t\t\tDeleteObject (mascot);\r\n\t\t\tEndPaint (hWnd, &ps);\r\n\t\t\tbreak;\r\n\t\t }\t \t \t\r\n }\r\n return DefWindowProc( hWnd, uMsg, wParam, lParam);\r\n }\r\n\r\n bool StartWin32App ()\r\n {\r\n if (FindWindow (I2PD_WIN32_CLASSNAME, TEXT(\"i2pd\")))\r\n {\r\n MessageBox(NULL, TEXT(\"I2Pd is running already\"), TEXT(\"Warning\"), MB_OK);\r\n return false;\r\n }\r\n \/\/ register main window\r\n auto hInst = GetModuleHandle(NULL);\r\n WNDCLASSEX wclx;\r\n memset (&wclx, 0, sizeof(wclx));\r\n wclx.cbSize = sizeof(wclx);\r\n wclx.style = 0;\r\n wclx.lpfnWndProc = WndProc;\r\n wclx.cbClsExtra = 0;\r\n wclx.cbWndExtra = 0;\r\n wclx.hInstance = hInst;\r\n wclx.hIcon = LoadIcon (hInst, MAKEINTRESOURCE(MAINICON));\r\n wclx.hCursor = LoadCursor (NULL, IDC_ARROW);\r\n wclx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);\r\n wclx.lpszMenuName = NULL;\r\n wclx.lpszClassName = I2PD_WIN32_CLASSNAME;\r\n RegisterClassEx (&wclx);\r\n \/\/ create new window\r\n if (!CreateWindow(I2PD_WIN32_CLASSNAME, TEXT(\"i2pd\"), WS_OVERLAPPEDWINDOW, 100, 100, 549, 738, NULL, NULL, hInst, NULL))\r\n {\r\n MessageBox(NULL, \"Failed to create main window\", TEXT(\"Warning!\"), MB_ICONERROR | MB_OK | MB_TOPMOST);\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n int RunWin32App ()\r\n {\r\n MSG msg;\r\n while (GetMessage (&msg, NULL, 0, 0 ))\r\n {\r\n TranslateMessage (&msg);\r\n DispatchMessage (&msg);\r\n }\r\n return msg.wParam;\r\n }\r\n\r\n void StopWin32App ()\r\n {\r\n UnregisterClass (I2PD_WIN32_CLASSNAME, GetModuleHandle(NULL));\r\n }\r\n}\r\n}\r\n<commit_msg>show version in the 'About' window<commit_after>#include <string.h>\r\n#include <windows.h>\r\n#include <shellapi.h>\r\n#include \"..\/Config.h\"\r\n#include \"..\/version.h\"\r\n#include \"resource.h\"\r\n#include \"Win32App.h\"\r\n#include <stdio.h>\r\n\r\n#if defined(_MSC_VER) && _MSC_VER < 1900\r\n#define snprintf _snprintf\r\n#endif\r\n\r\n#define ID_ABOUT 2000\r\n#define ID_EXIT 2001\r\n#define ID_CONSOLE 2002\r\n#define ID_APP 2003\r\n\r\n#define ID_TRAY_ICON 2050\r\n#define WM_TRAYICON (WM_USER + 1)\r\n\r\nnamespace i2p\r\n{\r\nnamespace win32\r\n{\r\n static void ShowPopupMenu (HWND hWnd, POINT *curpos, int wDefaultItem)\r\n {\r\n HMENU hPopup = CreatePopupMenu();\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_CONSOLE, \"Open &console\");\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_APP, \"Show app\");\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_ABOUT, \"&About...\");\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_SEPARATOR, NULL, NULL);\r\n InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_EXIT, \"E&xit\");\r\n SetMenuDefaultItem (hPopup, ID_CONSOLE, FALSE);\r\n SendMessage (hWnd, WM_INITMENUPOPUP, (WPARAM)hPopup, 0);\r\n\r\n POINT p;\r\n if (!curpos)\r\n {\r\n GetCursorPos (&p);\r\n curpos = &p;\r\n }\r\n\r\n WORD cmd = TrackPopupMenu (hPopup, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY, curpos->x, curpos->y, 0, hWnd, NULL);\r\n SendMessage (hWnd, WM_COMMAND, cmd, 0);\r\n\r\n DestroyMenu(hPopup);\r\n }\r\n\r\n static void AddTrayIcon (HWND hWnd)\r\n {\r\n NOTIFYICONDATA nid;\r\n memset(&nid, 0, sizeof(nid));\r\n nid.cbSize = sizeof(nid);\r\n nid.hWnd = hWnd;\r\n nid.uID = ID_TRAY_ICON;\r\n nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;\r\n nid.uCallbackMessage = WM_TRAYICON;\r\n nid.hIcon = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE (MAINICON));\r\n strcpy (nid.szTip, \"i2pd\");\r\n strcpy (nid.szInfo, \"i2pd is running\");\r\n Shell_NotifyIcon(NIM_ADD, &nid );\r\n }\r\n\r\n static void RemoveTrayIcon (HWND hWnd)\r\n {\r\n NOTIFYICONDATA nid;\r\n nid.hWnd = hWnd;\r\n nid.uID = ID_TRAY_ICON;\r\n Shell_NotifyIcon (NIM_DELETE, &nid);\r\n }\r\n\r\n static LRESULT CALLBACK WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\r\n {\r\n switch (uMsg)\r\n {\r\n case WM_CREATE:\r\n {\r\n AddTrayIcon (hWnd);\r\n break;\r\n }\r\n case WM_CLOSE:\r\n {\r\n RemoveTrayIcon (hWnd);\r\n PostQuitMessage (0);\r\n break;\r\n }\r\n case WM_COMMAND:\r\n {\r\n switch (LOWORD(wParam))\r\n {\r\n case ID_ABOUT:\r\n {\r\n std::stringstream text;\r\n text << \"Version: \" << I2PD_VERSION << \" \" << CODENAME;\r\n MessageBox( hWnd, TEXT(text.str ().c_str ()), TEXT(\"i2pd\"), MB_ICONINFORMATION | MB_OK );\r\n return 0;\r\n }\r\n case ID_EXIT:\r\n {\r\n PostMessage (hWnd, WM_CLOSE, 0, 0);\r\n return 0;\r\n }\r\n case ID_CONSOLE:\r\n {\r\n char buf[30];\r\n std::string httpAddr; i2p::config::GetOption(\"http.address\", httpAddr);\r\n uint16_t httpPort; i2p::config::GetOption(\"http.port\", httpPort);\r\n snprintf(buf, 30, \"http:\/\/%s:%d\", httpAddr.c_str(), httpPort);\r\n ShellExecute(NULL, \"open\", buf, NULL, NULL, SW_SHOWNORMAL);\r\n return 0;\r\n }\r\n case ID_APP:\r\n {\r\n ShowWindow(hWnd, SW_SHOW);\r\n return 0;\r\n }\r\n }\r\n break;\r\n }\r\n case WM_SYSCOMMAND:\r\n {\r\n switch (wParam)\r\n {\r\n case SC_MINIMIZE:\r\n {\r\n ShowWindow(hWnd, SW_HIDE);\r\n return 0;\r\n }\r\n case SC_CLOSE:\r\n {\r\n std::string close; i2p::config::GetOption(\"close\", close);\r\n if (0 == close.compare(\"ask\"))\r\n switch(::MessageBox(hWnd, \"Would you like to minimize instead of exiting?\"\r\n \" You can add 'close' configuration option. Valid values are: ask, minimize, exit.\",\r\n \"Minimize instead of exiting?\", MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON1))\r\n {\r\n case IDYES: close = \"minimize\"; break;\r\n case IDNO: close = \"exit\"; break;\r\n default: return 0;\r\n }\r\n if (0 == close.compare(\"minimize\"))\r\n {\r\n ShowWindow(hWnd, SW_HIDE);\r\n return 0;\r\n }\r\n if (0 != close.compare(\"exit\"))\r\n {\r\n ::MessageBox(hWnd, close.c_str(), \"Unknown close action in config\", MB_OK | MB_ICONWARNING);\r\n return 0;\r\n }\r\n }\r\n }\r\n }\r\n case WM_TRAYICON:\r\n {\r\n switch (lParam)\r\n {\r\n case WM_LBUTTONUP:\r\n case WM_RBUTTONUP:\r\n {\r\n SetForegroundWindow (hWnd);\r\n ShowPopupMenu(hWnd, NULL, -1);\r\n PostMessage (hWnd, WM_APP + 1, 0, 0);\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n\t\t case WM_PAINT:\r\n\t\t {\r\n\t\t\tPAINTSTRUCT ps;\r\n\t\t\tauto hDC = BeginPaint (hWnd, &ps);\r\n\t\t\tauto mascot = LoadBitmap (GetModuleHandle(NULL), MAKEINTRESOURCE (MASCOT));\r\n\t\t\tauto mascotDC = CreateCompatibleDC (hDC);\r\n\t\t\tSelectObject (mascotDC, mascot);\r\n\t\t\tBitBlt (hDC, 0,0, 533, 700, mascotDC, 0, 0, SRCCOPY);\r\n\t\t\tDeleteDC (mascotDC);\r\n\t\t\tDeleteObject (mascot);\r\n\t\t\tEndPaint (hWnd, &ps);\r\n\t\t\tbreak;\r\n\t\t }\r\n }\r\n return DefWindowProc( hWnd, uMsg, wParam, lParam);\r\n }\r\n\r\n bool StartWin32App ()\r\n {\r\n if (FindWindow (I2PD_WIN32_CLASSNAME, TEXT(\"i2pd\")))\r\n {\r\n MessageBox(NULL, TEXT(\"I2Pd is running already\"), TEXT(\"Warning\"), MB_OK);\r\n return false;\r\n }\r\n \/\/ register main window\r\n auto hInst = GetModuleHandle(NULL);\r\n WNDCLASSEX wclx;\r\n memset (&wclx, 0, sizeof(wclx));\r\n wclx.cbSize = sizeof(wclx);\r\n wclx.style = 0;\r\n wclx.lpfnWndProc = WndProc;\r\n wclx.cbClsExtra = 0;\r\n wclx.cbWndExtra = 0;\r\n wclx.hInstance = hInst;\r\n wclx.hIcon = LoadIcon (hInst, MAKEINTRESOURCE(MAINICON));\r\n wclx.hCursor = LoadCursor (NULL, IDC_ARROW);\r\n wclx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);\r\n wclx.lpszMenuName = NULL;\r\n wclx.lpszClassName = I2PD_WIN32_CLASSNAME;\r\n RegisterClassEx (&wclx);\r\n \/\/ create new window\r\n if (!CreateWindow(I2PD_WIN32_CLASSNAME, TEXT(\"i2pd\"), WS_OVERLAPPEDWINDOW, 100, 100, 549, 738, NULL, NULL, hInst, NULL))\r\n {\r\n MessageBox(NULL, \"Failed to create main window\", TEXT(\"Warning!\"), MB_ICONERROR | MB_OK | MB_TOPMOST);\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n int RunWin32App ()\r\n {\r\n MSG msg;\r\n while (GetMessage (&msg, NULL, 0, 0 ))\r\n {\r\n TranslateMessage (&msg);\r\n DispatchMessage (&msg);\r\n }\r\n return msg.wParam;\r\n }\r\n\r\n void StopWin32App ()\r\n {\r\n UnregisterClass (I2PD_WIN32_CLASSNAME, GetModuleHandle(NULL));\r\n }\r\n}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdio>\n#include <cmath>\n#include <string>\n#include <unordered_map>\n\nusing namespace std;\n\nlong long get_factor(long long x) {\n for (long long j = 2; j < sqrt(x); j++) {\n if (x % j == 0) {\n return j;\n }\n }\n\n return -1;\n}\n\nint main() {\n unordered_map<long long, long long> factors;\n\n int n_cases;\n cin >> n_cases;\n\n for (int i_case = 0; i_case < n_cases; i_case++) {\n printf(\"Case #%d:\\n\", i_case + 1);\n\n int n, count;\n cin >> n >> count;\n\n long long pows[10 - 2 + 1][n];\n for (int j = 2; j <= 10; j++) {\n long long temp_pow = 1;\n\n for (int k = 0; k < n; k++) {\n pows[j - 2][k] = temp_pow;\n temp_pow *= j;\n }\n }\n\n for (long long i = 0; i < (int)pow(2, n - 2); i++){\n \/\/ Get binary representation\n bool digits[n];\n digits[0] = true;\n digits[n - 1] = true;\n for (int j = 0; j < n - 2; j++) { digits[j + 1] = false; }\n\n long long temp = i;\n int temp_index = 1;\n while (temp > 0) {\n digits[temp_index] = (temp % 2 == 1);\n temp \/= 2;\n temp_index++;\n }\n\n \/\/ Check 2->10\n long long ans[10 - 2 + 1];\n bool works = true;\n for (int j = 2; j <= 10; j++) {\n long long total = 0;\n for (int k = 0; k < n; k++) {\n if (digits[k]) { total += pows[j - 2][k]; }\n }\n\n if (factors.find(total) == factors.end()) {\n factors[total] = get_factor(total);\n }\n\n if (factors.at(total) == -1) {\n works = false;\n break;\n }\n\n ans[j - 2] = factors.at(total);\n }\n\n if (works) {\n count--;\n\n for (int j = n - 1; j >= 0; j--) {\n cout << (digits[j] ? '1' : '0');\n }\n\n for (int j = 2; j <= 10; j++) {\n cout << \" \" << ans[j - 2];\n }\n cout << endl;\n }\n\n if (count == 0) { break; }\n }\n }\n\n return 0;\n}\n<commit_msg>Update 2016-C<commit_after>#include <iostream>\n#include <cstdio>\n#include <cmath>\n#include <string>\n#include <unordered_map>\n\nusing namespace std;\n\n#define MAX_TRY 10000000\n\nunsigned long long get_factor(unsigned long long x) {\n for (unsigned long long j = 2; j < sqrt(x); j++) {\n if (x % j == 0) { return j; }\n if (j > MAX_TRY) { return -1; }\n }\n\n return -1;\n}\n\nint main() {\n unordered_map<unsigned long long, unsigned long long> factors;\n\n int n_cases;\n cin >> n_cases;\n\n for (int i_case = 0; i_case < n_cases; i_case++) {\n printf(\"Case #%d:\\n\", i_case + 1);\n\n int n, count;\n cin >> n >> count;\n\n unsigned long long pows[10 - 2 + 1][n];\n for (int j = 2; j <= 10; j++) {\n unsigned long long temp_pow = 1;\n\n for (int k = 0; k < n; k++) {\n pows[j - 2][k] = temp_pow;\n temp_pow *= j;\n }\n }\n\n for (unsigned long long i = 0; i < (int)pow(2, n - 2); i++){\n \/\/ cout << \"********** NEW NUM **************\" << endl;\n \/\/ Get binary representation\n bool digits[n];\n digits[0] = true;\n digits[n - 1] = true;\n for (int j = 0; j < n - 2; j++) { digits[j + 1] = false; }\n\n unsigned long long temp = i;\n int temp_index = 1;\n while (temp > 0) {\n digits[temp_index] = (temp % 2 == 1);\n temp \/= 2;\n temp_index++;\n }\n\n \/\/ Check 2->10\n unsigned long long ans[10 - 2 + 1];\n bool works = true;\n for (int j = 2; j <= 10; j++) {\n unsigned long long total = 0;\n for (int k = 0; k < n; k++) {\n if (digits[k]) { total += pows[j - 2][k]; }\n }\n \/\/ cout << \" trying base \" << j << \" and TOTAL \" << total << endl;\n\n if (factors.find(total) == factors.end()) {\n factors[total] = get_factor(total);\n }\n\n if (factors.at(total) == -1) {\n works = false;\n break;\n }\n\n ans[j - 2] = factors.at(total);\n }\n\n if (works) {\n count--;\n\n for (int j = n - 1; j >= 0; j--) {\n cout << (digits[j] ? '1' : '0');\n }\n\n for (int j = 2; j <= 10; j++) {\n cout << \" \" << ans[j - 2];\n }\n cout << endl;\n }\n\n if (count == 0) { break; }\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ConfigurationAccess.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 00:34:21 $\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#include \"ConfigurationAccess.hxx\"\n#include \"macros.hxx\"\n\n\/\/ header for class SvtSysLocale\n#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX\n#include <svtools\/syslocale.hxx>\n#endif\n\/\/ header for class ConfigItem\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\nusing namespace ::com::sun::star;\n\nnamespace\n{\nbool lcl_IsMetric()\n{\n SvtSysLocale aSysLocale;\n const LocaleDataWrapper* pLocWrapper = aSysLocale.GetLocaleDataPtr();\n MeasurementSystem eSys = pLocWrapper->getMeasurementSystemEnum();\n\n return ( eSys == MEASURE_METRIC );\n}\n}\/\/end anonymous namespace\n\nclass CalcConfigItem : public ::utl::ConfigItem\n{\npublic:\n CalcConfigItem();\n virtual ~CalcConfigItem();\n\n FieldUnit getFieldUnit();\n};\n\nCalcConfigItem::CalcConfigItem()\n : ConfigItem( ::rtl::OUString( C2U( \"Office.Calc\/Layout\" )))\n{\n}\nCalcConfigItem::~CalcConfigItem()\n{\n}\n\nFieldUnit CalcConfigItem::getFieldUnit()\n{\n FieldUnit eResult( FUNIT_CM );\n\n uno::Sequence< ::rtl::OUString > aNames( 1 );\n if( lcl_IsMetric() )\n aNames[ 0 ] = ::rtl::OUString( C2U( \"Other\/MeasureUnit\/Metric\" ));\n else\n aNames[ 0 ] = ::rtl::OUString( C2U( \"Other\/MeasureUnit\/NonMetric\" ));\n\n uno::Sequence< uno::Any > aResult( GetProperties( aNames ));\n sal_Int32 nValue;\n if( aResult[ 0 ] >>= nValue )\n eResult = static_cast< FieldUnit >( nValue );\n\n return eResult;\n}\n\nConfigurationAccess::ConfigurationAccess()\n : m_pCalcConfigItem(0)\n{\n m_pCalcConfigItem = new CalcConfigItem();\n}\nConfigurationAccess::~ConfigurationAccess()\n{\n delete m_pCalcConfigItem;\n}\nFieldUnit ConfigurationAccess::getFieldUnit()\n{\n FieldUnit aUnit( m_pCalcConfigItem->getFieldUnit() );\n return aUnit;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n<commit_msg>INTEGRATION: CWS pchfix02 (1.2.82); FILE MERGED 2006\/09\/01 17:18:40 kaib 1.2.82.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ConfigurationAccess.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 13:06: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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n\n#include \"ConfigurationAccess.hxx\"\n#include \"macros.hxx\"\n\n\/\/ header for class SvtSysLocale\n#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX\n#include <svtools\/syslocale.hxx>\n#endif\n\/\/ header for class ConfigItem\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\nusing namespace ::com::sun::star;\n\nnamespace\n{\nbool lcl_IsMetric()\n{\n SvtSysLocale aSysLocale;\n const LocaleDataWrapper* pLocWrapper = aSysLocale.GetLocaleDataPtr();\n MeasurementSystem eSys = pLocWrapper->getMeasurementSystemEnum();\n\n return ( eSys == MEASURE_METRIC );\n}\n}\/\/end anonymous namespace\n\nclass CalcConfigItem : public ::utl::ConfigItem\n{\npublic:\n CalcConfigItem();\n virtual ~CalcConfigItem();\n\n FieldUnit getFieldUnit();\n};\n\nCalcConfigItem::CalcConfigItem()\n : ConfigItem( ::rtl::OUString( C2U( \"Office.Calc\/Layout\" )))\n{\n}\nCalcConfigItem::~CalcConfigItem()\n{\n}\n\nFieldUnit CalcConfigItem::getFieldUnit()\n{\n FieldUnit eResult( FUNIT_CM );\n\n uno::Sequence< ::rtl::OUString > aNames( 1 );\n if( lcl_IsMetric() )\n aNames[ 0 ] = ::rtl::OUString( C2U( \"Other\/MeasureUnit\/Metric\" ));\n else\n aNames[ 0 ] = ::rtl::OUString( C2U( \"Other\/MeasureUnit\/NonMetric\" ));\n\n uno::Sequence< uno::Any > aResult( GetProperties( aNames ));\n sal_Int32 nValue;\n if( aResult[ 0 ] >>= nValue )\n eResult = static_cast< FieldUnit >( nValue );\n\n return eResult;\n}\n\nConfigurationAccess::ConfigurationAccess()\n : m_pCalcConfigItem(0)\n{\n m_pCalcConfigItem = new CalcConfigItem();\n}\nConfigurationAccess::~ConfigurationAccess()\n{\n delete m_pCalcConfigItem;\n}\nFieldUnit ConfigurationAccess::getFieldUnit()\n{\n FieldUnit aUnit( m_pCalcConfigItem->getFieldUnit() );\n return aUnit;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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 <vector>\n\n#include \"base\/file_path.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autofill\/autofill_manager.h\"\n#include \"chrome\/browser\/autofill\/data_driven_test.h\"\n#include \"chrome\/browser\/autofill\/form_structure.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nnamespace {\n\nconst FilePath::CharType kTestName[] = FILE_PATH_LITERAL(\"heuristics\");\nconst FilePath::CharType kFileNamePattern[] = FILE_PATH_LITERAL(\"*.html\");\n\n\/\/ Convert the |html| snippet to a data URI.\nGURL HTMLToDataURI(const std::string& html) {\n return GURL(std::string(\"data:text\/html;charset=utf-8,\") + html);\n}\n\n} \/\/ namespace\n\n\/\/ A data-driven test for verifying AutoFill heuristics. Each input is an HTML\n\/\/ file that contains one or more forms. The corresponding output file lists the\n\/\/ heuristically detected type for eachfield.\nclass FormStructureBrowserTest : public InProcessBrowserTest,\n public DataDrivenTest {\n protected:\n FormStructureBrowserTest();\n virtual ~FormStructureBrowserTest();\n\n \/\/ DataDrivenTest:\n virtual void GenerateResults(const std::string& input,\n std::string* output);\n\n \/\/ Serializes the given |forms| into a string.\n std::string FormStructuresToString(const std::vector<FormStructure*>& forms);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(FormStructureBrowserTest);\n};\n\nFormStructureBrowserTest::FormStructureBrowserTest() {\n}\n\nFormStructureBrowserTest::~FormStructureBrowserTest() {\n}\n\nvoid FormStructureBrowserTest::GenerateResults(const std::string& input,\n std::string* output) {\n LOG(WARNING) << \"Before NavigateToURL\";\n ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),\n HTMLToDataURI(input)));\n LOG(WARNING) << \"Before ClickOnView\";\n ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),\n VIEW_ID_TAB_CONTAINER));\n LOG(WARNING) << \"Before IsViewFocused\";\n ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));\n LOG(WARNING) << \"After IsViewFocused\";\n\n AutoFillManager* autofill_manager =\n browser()->GetSelectedTabContents()->autofill_manager();\n ASSERT_NE(static_cast<AutoFillManager*>(NULL), autofill_manager);\n std::vector<FormStructure*> forms = autofill_manager->form_structures_.get();\n *output = FormStructureBrowserTest::FormStructuresToString(forms);\n}\n\nstd::string FormStructureBrowserTest::FormStructuresToString(\n const std::vector<FormStructure*>& forms) {\n std::string forms_string;\n for (std::vector<FormStructure*>::const_iterator iter = forms.begin();\n iter != forms.end();\n ++iter) {\n\n for (std::vector<AutoFillField*>::const_iterator field_iter =\n (*iter)->begin();\n field_iter != (*iter)->end();\n ++field_iter) {\n \/\/ The field list is NULL-terminated. Exit loop when at the end.\n if (!*field_iter)\n break;\n forms_string += AutoFillType::FieldTypeToString((*field_iter)->type());\n forms_string += \"\\n\";\n }\n }\n return forms_string;\n}\n\nIN_PROC_BROWSER_TEST_F(FormStructureBrowserTest,\n DISABLED_DataDrivenHeuristics) {\n LOG(WARNING) << \"Before BringBrowserWindowToFront\";\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n LOG(WARNING) << \"After BringBrowserWindowToFront\";\n RunDataDrivenTest(GetInputDirectory(kTestName),\n GetOutputDirectory(kTestName),\n kFileNamePattern);\n}\n<commit_msg>Reenable FormStructureBrowserTest.DataDrivenHeuristics for debugging<commit_after>\/\/ Copyright (c) 2011 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 <vector>\n\n#include \"base\/file_path.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autofill\/autofill_manager.h\"\n#include \"chrome\/browser\/autofill\/data_driven_test.h\"\n#include \"chrome\/browser\/autofill\/form_structure.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nnamespace {\n\nconst FilePath::CharType kTestName[] = FILE_PATH_LITERAL(\"heuristics\");\nconst FilePath::CharType kFileNamePattern[] = FILE_PATH_LITERAL(\"*.html\");\n\n\/\/ Convert the |html| snippet to a data URI.\nGURL HTMLToDataURI(const std::string& html) {\n return GURL(std::string(\"data:text\/html;charset=utf-8,\") + html);\n}\n\n} \/\/ namespace\n\n\/\/ A data-driven test for verifying AutoFill heuristics. Each input is an HTML\n\/\/ file that contains one or more forms. The corresponding output file lists the\n\/\/ heuristically detected type for eachfield.\nclass FormStructureBrowserTest : public InProcessBrowserTest,\n public DataDrivenTest {\n protected:\n FormStructureBrowserTest();\n virtual ~FormStructureBrowserTest();\n\n \/\/ DataDrivenTest:\n virtual void GenerateResults(const std::string& input,\n std::string* output);\n\n \/\/ Serializes the given |forms| into a string.\n std::string FormStructuresToString(const std::vector<FormStructure*>& forms);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(FormStructureBrowserTest);\n};\n\nFormStructureBrowserTest::FormStructureBrowserTest() {\n}\n\nFormStructureBrowserTest::~FormStructureBrowserTest() {\n}\n\nvoid FormStructureBrowserTest::GenerateResults(const std::string& input,\n std::string* output) {\n LOG(WARNING) << \"Before NavigateToURL\";\n ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),\n HTMLToDataURI(input)));\n LOG(WARNING) << \"Before ClickOnView\";\n ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),\n VIEW_ID_TAB_CONTAINER));\n LOG(WARNING) << \"Before IsViewFocused\";\n ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));\n LOG(WARNING) << \"After IsViewFocused\";\n\n AutoFillManager* autofill_manager =\n browser()->GetSelectedTabContents()->autofill_manager();\n ASSERT_NE(static_cast<AutoFillManager*>(NULL), autofill_manager);\n std::vector<FormStructure*> forms = autofill_manager->form_structures_.get();\n *output = FormStructureBrowserTest::FormStructuresToString(forms);\n}\n\nstd::string FormStructureBrowserTest::FormStructuresToString(\n const std::vector<FormStructure*>& forms) {\n std::string forms_string;\n for (std::vector<FormStructure*>::const_iterator iter = forms.begin();\n iter != forms.end();\n ++iter) {\n\n for (std::vector<AutoFillField*>::const_iterator field_iter =\n (*iter)->begin();\n field_iter != (*iter)->end();\n ++field_iter) {\n \/\/ The field list is NULL-terminated. Exit loop when at the end.\n if (!*field_iter)\n break;\n forms_string += AutoFillType::FieldTypeToString((*field_iter)->type());\n forms_string += \"\\n\";\n }\n }\n return forms_string;\n}\n\nIN_PROC_BROWSER_TEST_F(FormStructureBrowserTest, DataDrivenHeuristics) {\n LOG(WARNING) << \"Before BringBrowserWindowToFront\";\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n LOG(WARNING) << \"After BringBrowserWindowToFront\";\n RunDataDrivenTest(GetInputDirectory(kTestName),\n GetOutputDirectory(kTestName),\n kFileNamePattern);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Author: http:\/\/lemming.life\n\/\/ Language: C++\n\/\/ Description: Example of creating and using an object.\n\n\/\/ At terminal:\n\/\/ g++ pointers.cpp\n\/\/ .\/a.out\n\n#include <iostream>\n\nclass Shape {\nprivate:\n int id;\npublic:\n Shape(int id) {\n this->id = id;\n }\n int getId() { return id; }\n\n ~Shape() {\n std::cout << \"Destroying shape\" << id << \"\\n\";\n }\n};\n\n\n\/\/ Pass a Shape* \nvoid PrintShape(Shape* shape) {\n std::cout << \"Shape ID: \" << shape->getId() << \"\\n\"; \n}\n\nint main() {\n int id = 0;\n\n { \/\/ Deepen the scope\n \n \/\/ Create shape1\n Shape shape1(++id);\n PrintShape(&shape1); \/\/ Pass the address of shape\n\n Shape* shapePtr; \/\/ A pointer holds the address of an object type specified (in this case Shape)\n \/\/ The pointer itself is in the stack section of a program\n\n {\n Shape shape2(++id); \/\/ Create shape2 on the stack.\n PrintShape(&shape2);\n shapePtr = &shape2;\n\n \/\/ Ways to use the pointer\n std::cout << \"Via pointer, arrow operator. ID: \" << shapePtr->getId() << \"\\n\";\n std::cout << \"Via pointer, derefencing. ID: \" << (*shapePtr).getId() << \"\\n\";\n\n } \/\/ Destroying shape2 because the object goes out of scope\n\n \/\/ the shapePtr still has the address of the shape2 object\n PrintShape(shapePtr); \/\/ Expect: Shape ID: 2\n\n shapePtr = new Shape(++id); \/\/ Creates an object on the heap portion of a program.\n PrintShape(shapePtr); \/\/ Shape ID: 3\n delete shapePtr; \/\/ Deletes the object pointed by the shapePtr \n\n shapePtr = new Shape(++id); \/\/ This is Shape with id 4\n\n } \/\/ Destroying shape1 automatically because the object goes out of scope\n\n \/\/ Note that shape with id 4 was never deleted. This is a memory leak!\n \/\/ Other languages have garbage collection -- cleans memory automatically.\n \/\/ C++ 11 has shared pointers that can be used for automatically doing clean up.\n\n return 0;\n}\n\n\n\/\/ Expected Output:\n\/*\nShape ID: 1\nShape ID: 2\nVia pointer, arrow operator. ID: 2\nVia pointer, derefencing. ID: 2\nDestroying shape2\nShape ID: 2\nShape ID: 3\nDestroying shape3\nDestroying shape1\n*\/<commit_msg>Added pointers C++ example.<commit_after>\/\/ Author: http:\/\/lemming.life\n\/\/ Language: C++\n\/\/ Description: Example of creating and using an object.\n\n\/* At terminal do:\n g++ pointers.cpp\n .\/a.out\n*\/\n\n#include <iostream>\n\nclass Shape {\nprivate:\n int id;\npublic:\n Shape(int id) {\n this->id = id;\n }\n int getId() { return id; }\n\n ~Shape() {\n std::cout << \"Destroying shape\" << id << \"\\n\";\n }\n};\n\n\n\/\/ Pass a Shape* \nvoid PrintShape(Shape* shape) {\n std::cout << \"Shape ID: \" << shape->getId() << \"\\n\"; \n}\n\nint main() {\n int id = 0;\n\n { \/\/ Deepen the scope\n \n \/\/ Create shape1\n Shape shape1(++id);\n PrintShape(&shape1); \/\/ Pass the address of shape\n\n Shape* shapePtr; \/\/ A pointer holds the address of an object type specified (in this case Shape)\n \/\/ The pointer itself is in the stack section of a program\n\n {\n Shape shape2(++id); \/\/ Create shape2 on the stack.\n PrintShape(&shape2);\n shapePtr = &shape2;\n\n \/\/ Ways to use the pointer\n std::cout << \"Via pointer, arrow operator. ID: \" << shapePtr->getId() << \"\\n\";\n std::cout << \"Via pointer, derefencing. ID: \" << (*shapePtr).getId() << \"\\n\";\n\n } \/\/ Destroying shape2 because the object goes out of scope\n\n \/\/ the shapePtr still has the address of the shape2 object\n PrintShape(shapePtr); \/\/ Expect: Shape ID: 2\n\n shapePtr = new Shape(++id); \/\/ Creates an object on the heap portion of a program.\n PrintShape(shapePtr); \/\/ Shape ID: 3\n delete shapePtr; \/\/ Deletes the object pointed by the shapePtr \n\n shapePtr = new Shape(++id); \/\/ This is Shape with id 4\n\n } \/\/ Destroying shape1 automatically because the object goes out of scope\n\n \/\/ Note that shape with id 4 was never deleted. This is a memory leak!\n \/\/ Other languages have garbage collection -- cleans memory automatically.\n \/\/ C++ 11 has shared pointers that can be used for automatically doing clean up.\n\n return 0;\n}\n\n\n\/\/ Expected Output:\n\/*\nShape ID: 1\nShape ID: 2\nVia pointer, arrow operator. ID: 2\nVia pointer, derefencing. ID: 2\nDestroying shape2\nShape ID: 2\nShape ID: 3\nDestroying shape3\nDestroying shape1\n*\/<|endoftext|>"} {"text":"<commit_before>\/\/===- fpcmp.cpp - A fuzzy \"cmp\" that permits floating point noise --------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ fpcmp is a tool that basically works like the 'cmp' tool, except that it can\n\/\/ tolerate errors due to floating point noise, with the -r option.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileUtilities.h\"\n#include <iostream>\n#include <cmath>\n\nusing namespace llvm;\n\nnamespace {\n cl::opt<std::string>\n File1(cl::Positional, cl::desc(\"<input file #1>\"), cl::Required);\n cl::opt<std::string>\n File2(cl::Positional, cl::desc(\"<input file #2>\"), cl::Required);\n\n cl::opt<double>\n RelTolerance(\"r\", cl::desc(\"Relative error tolerated\"), cl::init(0));\n cl::opt<double>\n AbsTolerance(\"a\", cl::desc(\"Absolute error tolerated\"), cl::init(0));\n}\n\n\n\/\/\/ OpenFile - mmap the specified file into the address space for reading, and\n\/\/\/ return the length and address of the buffer.\nstatic void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){\n BufPtr = (char*)ReadFileIntoAddressSpace(Filename, Len);\n if (BufPtr == 0) {\n std::cerr << \"Error: cannot open file '\" << Filename << \"'\\n\";\n exit(2);\n }\n}\n\nstatic bool isNumberChar(char C) {\n switch (C) {\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9': \n case '.': case '+': case '-':\n case 'e':\n case 'E': return true;\n default: return false;\n }\n}\n\nstatic char *BackupNumber(char *Pos, char *FirstChar) {\n \/\/ If we didn't stop in the middle of a number, don't backup.\n if (!isNumberChar(*Pos)) return Pos;\n\n \/\/ Otherwise, return to the start of the number.\n while (Pos > FirstChar && isNumberChar(Pos[-1]))\n --Pos;\n return Pos;\n}\n\nstatic void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) {\n char *F1NumEnd, *F2NumEnd;\n double V1 = 0.0, V2 = 0.0; \n \/\/ If we stop on numbers, compare their difference.\n if (isNumberChar(*F1P) && isNumberChar(*F2P)) {\n V1 = strtod(F1P, &F1NumEnd);\n V2 = strtod(F2P, &F2NumEnd);\n } else {\n \/\/ Otherwise, the diff failed.\n F1NumEnd = F1P;\n F2NumEnd = F2P;\n }\n\n if (F1NumEnd == F1P || F2NumEnd == F2P) {\n std::cerr << \"Comparison failed, not a numeric difference.\\n\";\n exit(1);\n }\n\n \/\/ Check to see if these are inside the absolute tolerance\n if (AbsTolerance < std::abs(V1-V2)) {\n \/\/ Nope, check the relative tolerance...\n double Diff;\n if (V2)\n Diff = std::abs(V1\/V2 - 1.0);\n else if (V1)\n Diff = std::abs(V2\/V1 - 1.0);\n else\n Diff = 0; \/\/ Both zero.\n if (Diff > RelTolerance) {\n std::cerr << \"Compared: \" << V1 << \" and \" << V2 << \": diff = \"\n << Diff << \"\\n\";\n std::cerr << \"Out of tolerance: rel\/abs: \" << RelTolerance\n << \"\/\" << AbsTolerance << \"\\n\";\n exit(1);\n }\n }\n\n \/\/ Otherwise, advance our read pointers to the end of the numbers.\n F1P = F1NumEnd; F2P = F2NumEnd;\n}\n\n\/\/ PadFileIfNeeded - If the files are not identical, we will have to be doing\n\/\/ numeric comparisons in here. There are bad cases involved where we (i.e.,\n\/\/ strtod) might run off the beginning or end of the file if it starts or ends\n\/\/ with a number. Because of this, if needed, we pad the file so that it starts\n\/\/ and ends with a null character.\nstatic void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) {\n if (isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) {\n unsigned FileLen = FileEnd-FileStart;\n char *NewFile = new char[FileLen+2];\n NewFile[0] = 0; \/\/ Add null padding\n NewFile[FileLen+1] = 0; \/\/ Add null padding\n memcpy(NewFile+1, FileStart, FileLen);\n FP = NewFile+(FP-FileStart)+1;\n FileStart = NewFile+1;\n FileEnd = FileStart+FileLen;\n }\n}\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv);\n\n \/\/ mmap in the files.\n unsigned File1Len, File2Len;\n char *File1Start, *File2Start;\n OpenFile(File1, File1Len, File1Start);\n OpenFile(File2, File2Len, File2Start);\n\n \/\/ Okay, now that we opened the files, scan them for the first difference.\n char *File1End = File1Start+File1Len;\n char *File2End = File2Start+File2Len;\n char *F1P = File1Start;\n char *F2P = File2Start;\n\n \/\/ Scan for the end of file or first difference.\n while (F1P < File1End && F2P < File2End && *F1P == *F2P)\n ++F1P, ++F2P;\n\n \/\/ Common case: identifical files.\n if (F1P == File1End && F2P == File2End) return 0;\n\n \/\/ If the files need padding, do so now.\n PadFileIfNeeded(File1Start, File1End, F1P);\n PadFileIfNeeded(File2Start, File2End, F2P);\n \n while (1) {\n \/\/ Scan for the end of file or next difference.\n while (F1P < File1End && F2P < File2End && *F1P == *F2P)\n ++F1P, ++F2P;\n\n if (F1P >= File1End || F2P >= File2End) break;\n\n \/\/ Okay, we must have found a difference. Backup to the start of the\n \/\/ current number each stream is at so that we can compare from the\n \/\/ beginning.\n F1P = BackupNumber(F1P, File1Start);\n F2P = BackupNumber(F2P, File2Start);\n\n \/\/ Now that we are at the start of the numbers, compare them, exiting if\n \/\/ they don't match.\n CompareNumbers(F1P, F2P, File1End, File2End);\n }\n\n \/\/ Okay, we reached the end of file. If both files are at the end, we\n \/\/ succeeded.\n bool F1AtEnd = F1P >= File1End;\n bool F2AtEnd = F2P >= File2End;\n if (F1AtEnd & F2AtEnd) return 0;\n\n \/\/ Otherwise, we might have run off the end due to a number: backup and retry.\n if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;\n if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;\n F1P = BackupNumber(F1P, File1Start);\n F2P = BackupNumber(F2P, File2Start);\n\n \/\/ Now that we are at the start of the numbers, compare them, exiting if\n \/\/ they don't match.\n CompareNumbers(F1P, F2P, File1End, File2End);\n\n \/\/ If we found the end, we succeeded.\n if (F1P >= File1End && F2P >= File2End) return 0;\n\n return 1;\n}\n\n<commit_msg>For PR351: * Change use of ReadFileIntoAddressSpace to sys::MappedFile use. * Shorten a line > 80 chars.<commit_after>\/\/===- fpcmp.cpp - A fuzzy \"cmp\" that permits floating point noise --------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ fpcmp is a tool that basically works like the 'cmp' tool, except that it can\n\/\/ tolerate errors due to floating point noise, with the -r option.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/System\/MappedFile.h\"\n#include <iostream>\n#include <cmath>\n\nusing namespace llvm;\n\nnamespace {\n cl::opt<std::string>\n File1(cl::Positional, cl::desc(\"<input file #1>\"), cl::Required);\n cl::opt<std::string>\n File2(cl::Positional, cl::desc(\"<input file #2>\"), cl::Required);\n\n cl::opt<double>\n RelTolerance(\"r\", cl::desc(\"Relative error tolerated\"), cl::init(0));\n cl::opt<double>\n AbsTolerance(\"a\", cl::desc(\"Absolute error tolerated\"), cl::init(0));\n}\n\nstatic bool isNumberChar(char C) {\n switch (C) {\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9': \n case '.': case '+': case '-':\n case 'e':\n case 'E': return true;\n default: return false;\n }\n}\n\nstatic char *BackupNumber(char *Pos, char *FirstChar) {\n \/\/ If we didn't stop in the middle of a number, don't backup.\n if (!isNumberChar(*Pos)) return Pos;\n\n \/\/ Otherwise, return to the start of the number.\n while (Pos > FirstChar && isNumberChar(Pos[-1]))\n --Pos;\n return Pos;\n}\n\nstatic void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) {\n char *F1NumEnd, *F2NumEnd;\n double V1 = 0.0, V2 = 0.0; \n \/\/ If we stop on numbers, compare their difference.\n if (isNumberChar(*F1P) && isNumberChar(*F2P)) {\n V1 = strtod(F1P, &F1NumEnd);\n V2 = strtod(F2P, &F2NumEnd);\n } else {\n \/\/ Otherwise, the diff failed.\n F1NumEnd = F1P;\n F2NumEnd = F2P;\n }\n\n if (F1NumEnd == F1P || F2NumEnd == F2P) {\n std::cerr << \"Comparison failed, not a numeric difference.\\n\";\n exit(1);\n }\n\n \/\/ Check to see if these are inside the absolute tolerance\n if (AbsTolerance < std::abs(V1-V2)) {\n \/\/ Nope, check the relative tolerance...\n double Diff;\n if (V2)\n Diff = std::abs(V1\/V2 - 1.0);\n else if (V1)\n Diff = std::abs(V2\/V1 - 1.0);\n else\n Diff = 0; \/\/ Both zero.\n if (Diff > RelTolerance) {\n std::cerr << \"Compared: \" << V1 << \" and \" << V2 << \": diff = \"\n << Diff << \"\\n\";\n std::cerr << \"Out of tolerance: rel\/abs: \" << RelTolerance\n << \"\/\" << AbsTolerance << \"\\n\";\n exit(1);\n }\n }\n\n \/\/ Otherwise, advance our read pointers to the end of the numbers.\n F1P = F1NumEnd; F2P = F2NumEnd;\n}\n\n\/\/ PadFileIfNeeded - If the files are not identical, we will have to be doing\n\/\/ numeric comparisons in here. There are bad cases involved where we (i.e.,\n\/\/ strtod) might run off the beginning or end of the file if it starts or ends\n\/\/ with a number. Because of this, if needed, we pad the file so that it starts\n\/\/ and ends with a null character.\nstatic void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) {\n if (isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) {\n unsigned FileLen = FileEnd-FileStart;\n char *NewFile = new char[FileLen+2];\n NewFile[0] = 0; \/\/ Add null padding\n NewFile[FileLen+1] = 0; \/\/ Add null padding\n memcpy(NewFile+1, FileStart, FileLen);\n FP = NewFile+(FP-FileStart)+1;\n FileStart = NewFile+1;\n FileEnd = FileStart+FileLen;\n }\n}\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv);\n\n try {\n \/\/ map in the files into memory\n sys::Path F1Path(File1);\n sys::Path F2Path(File2);\n sys::MappedFile F1 ( F1Path );\n sys::MappedFile F2 ( F2Path );\n F1.map();\n F2.map();\n\n \/\/ Okay, now that we opened the files, scan them for the first difference.\n char *File1Start = F1.charBase();\n char *File2Start = F2.charBase();\n char *File1End = File1Start+F1.size();\n char *File2End = File2Start+F2.size();\n char *F1P = File1Start;\n char *F2P = File2Start;\n\n \/\/ Scan for the end of file or first difference.\n while (F1P < File1End && F2P < File2End && *F1P == *F2P)\n ++F1P, ++F2P;\n\n \/\/ Common case: identifical files.\n if (F1P == File1End && F2P == File2End) return 0;\n\n \/\/ If the files need padding, do so now.\n PadFileIfNeeded(File1Start, File1End, F1P);\n PadFileIfNeeded(File2Start, File2End, F2P);\n \n while (1) {\n \/\/ Scan for the end of file or next difference.\n while (F1P < File1End && F2P < File2End && *F1P == *F2P)\n ++F1P, ++F2P;\n\n if (F1P >= File1End || F2P >= File2End) break;\n\n \/\/ Okay, we must have found a difference. Backup to the start of the\n \/\/ current number each stream is at so that we can compare from the\n \/\/ beginning.\n F1P = BackupNumber(F1P, File1Start);\n F2P = BackupNumber(F2P, File2Start);\n\n \/\/ Now that we are at the start of the numbers, compare them, exiting if\n \/\/ they don't match.\n CompareNumbers(F1P, F2P, File1End, File2End);\n }\n\n \/\/ Okay, we reached the end of file. If both files are at the end, we\n \/\/ succeeded.\n bool F1AtEnd = F1P >= File1End;\n bool F2AtEnd = F2P >= File2End;\n if (F1AtEnd & F2AtEnd) return 0;\n\n \/\/ Else, we might have run off the end due to a number: backup and retry.\n if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;\n if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;\n F1P = BackupNumber(F1P, File1Start);\n F2P = BackupNumber(F2P, File2Start);\n\n \/\/ Now that we are at the start of the numbers, compare them, exiting if\n \/\/ they don't match.\n CompareNumbers(F1P, F2P, File1End, File2End);\n\n \/\/ If we found the end, we succeeded.\n if (F1P >= File1End && F2P >= File2End) return 0;\n\n } catch (const std::string& msg) {\n std::cerr << argv[0] << \": error: \" << msg << \"\\n\";\n return 2;\n }\n\n return 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <tiramisu\/tiramisu.h>\n#include <vector>\n#include \"configure.h\"\n\nusing namespace tiramisu;\n\nint main()\n{\n init(\"densenet_block\");\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n var x(\"x\", 0, N), y(\"y\", 0, N), z(\"z\", 0, 4*GR), n(\"n\", 0, BATCH_SIZE);\n\n var x_pad(\"x\", 0, N + 2), y_pad(\"y\", 0, N + 2);\n var k_x(\"k_x\", 0, K_X), k_y(\"k_y\", 0, K_Y);\n\n var fin_b(\"fin_b\", 0, FIN_NB_BLOCKS), ffin(\"ffin\", 0, FIN_BLOCKING);\n var fout_b(\"fout_b\", 0, FOUT_NB_BLOCKS), ffout(\"ffout\", 0, FOUT_BLOCKING);\n\n input c_input(\"c_input\", {n, fin_b, y_pad, x_pad, ffin}, p_float32);\n input bn_scale(\"bn_scale\", {fin_b, ffin}, p_float32);\n input bn_shift(\"bn_shift\", {fin_b, ffin}, p_float32);\n\n input conv_filter(\"conv_filter\", {fin_b, fout_b, k_y, k_x, ffin, ffout}, p_float32);\n input conv_bias(\"conv_bias\", {fout_b, ffout}, p_float32);\n\n \/\/ Batch normalization followed by ReLU\n \/\/ Compute the sum over the features dimension (z)\n computation input_sum_init(\"input_sum_init\", {fin_b, ffin}, cast(p_float32, 0));\n computation input_sum(\n \"input_sum\", \n {fin_b, n, y_pad, x_pad, ffin}, \n input_sum_init(fin_b, ffin) + c_input(n, fin_b, y_pad, x_pad, ffin)\n );\n\n \/\/ Compute the sum of squares over the features dimension (z)\n computation input_sum_squares_init(\"input_sum_squares_init\", {fin_b, ffin}, cast(p_float32, 0));\n computation input_sum_squares(\n \"input_sum_squares\", \n {fin_b, n, y_pad, x_pad, ffin}, \n input_sum_squares_init(fin_b, ffin) + c_input(n, fin_b, y_pad, x_pad, ffin) * c_input(n, fin_b, y_pad, x_pad, ffin)\n );\n\n computation input_mean(\n \"input_mean\", \n {fin_b, ffin}, \n input_sum(fin_b, 0, 0, 0, ffin) \/ cast(p_float32, BATCH_SIZE*(N+2)*(N+2))\n );\n\n computation input_sd(\n \"input_sd\", \n {fin_b, ffin}, \n expr(\n o_sqrt, \n input_sum_squares(fin_b, 0, 0, 0, ffin) \/ cast(p_float32, BATCH_SIZE*(N+2)*(N+2)) - input_mean(fin_b, ffin) * input_mean(fin_b, ffin) + cast(p_float32, EPSILON)\n )\n );\n \n \/\/ Compute BN followed by ReLU\n computation bn(\n \"bn\", \n {n, fin_b, y_pad, x_pad, ffin}, \n bn_scale(fin_b, ffin) * ((c_input(n, fin_b, y_pad, x_pad, ffin) - input_mean(fin_b, ffin)) \/ input_sd(fin_b, ffin)) + bn_shift(fin_b, ffin)\n );\n\n computation relu(\n \"relu\", \n {n, fin_b, y_pad, x_pad, ffin}, \n expr(\n o_max, \n cast(p_float32, 0), \n bn(n, fin_b, y_pad, x_pad, ffin)\n )\n );\n\n computation conv_init(\"conv_init\", {n, y, fout_b, x, ffout}, conv_bias(fout_b, ffout));\n view conv_out(\"conv_out\", {n, y, x, fout_b, ffout}, p_float32);\n\n \/\/ Convolution computation\n \/\/ x_bound is used to have the width dimension divisible by X_BLOCKING\n \/\/ in the conv computation.\n var x_bound(\"x_bound\", 0, X_BOUND);\n var x_conclude(\"x_conclude\", X_BOUND, N);\n\n \/\/ Compute convolution from 0 to x_bound\n computation conv(\n \"conv\",\n {n, fin_b, y, x_bound, k_y, k_x, ffin, fout_b, ffout},\n conv_out(n, y, x_bound, fout_b, ffout) + conv_filter(fin_b, fout_b, k_y, k_x, ffin, ffout) * relu(n, fin_b, y + k_y, x_bound + k_x, ffin)\n );\n\n \/\/ Compute convolution from x_bound to N\n computation conv_conclude(\n \"conv_conclude\",\n {n, fin_b, y, k_y, k_x, ffin, fout_b, ffout, x_conclude},\n conv_out(n, y, x_conclude, fout_b, ffout) + conv_filter(fin_b, fout_b, k_y, k_x, ffin, ffout) * relu(n, fin_b, y + k_y, x_conclude + k_x, ffin)\n );\n \n \/\/ -------------------------------------------------------\n \/\/ Layer II\n \/\/ -------------------------------------------------------\n input_sum.vectorize(ffin, VEC_LEN);\n input_sum.tag_parallel_level(fin_b);\n\n bn.vectorize(ffin, VEC_LEN);\n\n \/*\n * Schedule for conv\n *\/\n \/\/ We introduce those two computations to do register blocking\n computation reg_load(\n \"reg_load\",\n {n, fin_b, y, x_bound, fout_b, ffout},\n conv_init(n, y, fout_b, x_bound, ffout)\n );\n\n computation reg_store(\n \"reg_store\",\n {n, fin_b, y, x_bound, fout_b, ffout},\n conv(n, fin_b, y, x_bound, 0, 0, 0, fout_b, ffout)\n );\n\n \/\/ Split over dimension x\n var x_b, xx;\n conv.split(x_bound, X_BLOCKING, x_b, xx);\n\n conv.interchange(xx, k_y);\n conv.interchange(xx, k_x);\n conv.interchange(xx, ffin);\n conv.interchange(xx, fout_b);\n conv.interchange(xx, ffout);\n\n reg_load.split(x_bound, X_BLOCKING, x_b, xx);\n reg_store.split(x_bound, X_BLOCKING, x_b, xx);\n\n reg_load.interchange(xx, fout_b);\n reg_load.interchange(xx, ffout);\n\n reg_store.interchange(xx, fout_b);\n reg_store.interchange(xx, ffout);\n\n \/\/ Vectorize and unroll\n reg_load.vectorize(ffout, VEC_LEN);\n conv.vectorize(ffout, VEC_LEN);\n reg_store.vectorize(ffout, VEC_LEN);\n\n conv.tag_unroll_level(xx);\n conv.tag_unroll_level(fout_b);\n\n reg_load.tag_unroll_level(xx);\n reg_load.tag_unroll_level(fout_b);\n\n reg_store.tag_unroll_level(xx);\n reg_store.tag_unroll_level(fout_b);\n\n \/\/ schedule for conv_conclude\n \/\/ This schedule is the same as conv computation\n computation reg_load_conclude(\n \"reg_load_conclude\",\n {n, fin_b, y, fout_b, ffout, x_conclude},\n conv_init(n, y, fout_b, x_conclude, ffout)\n );\n\n computation reg_store_conclude(\n \"reg_store_conclude\",\n {n, fin_b, y, fout_b, ffout, x_conclude},\n conv_conclude(n, fin_b, y, 0, 0, 0, fout_b, ffout, x_conclude)\n );\n\n reg_load_conclude.vectorize(ffout, VEC_LEN);\n conv_conclude.vectorize(ffout, VEC_LEN);\n reg_store_conclude.vectorize(ffout, VEC_LEN);\n\n conv_conclude.tag_unroll_level(x_conclude);\n conv_conclude.tag_unroll_level(fout_b);\n\n reg_load_conclude.tag_unroll_level(x_conclude);\n reg_load_conclude.tag_unroll_level(fout_b);\n\n reg_store_conclude.tag_unroll_level(x_conclude);\n reg_store_conclude.tag_unroll_level(fout_b);\n\n \/\/ Parallelize and order\n conv.tag_parallel_level(n);\n\n input_sum_init.then(input_sum_squares_init, ffin)\n .then(input_sum, fin_b)\n .then(input_sum_squares, ffin)\n .then(input_mean, fin_b)\n .then(input_sd, ffin)\n .then(conv_init, computation::root)\n .then(bn, n)\n .then(relu, ffin)\n .then(reg_load, fin_b)\n .then(conv, x_b)\n .then(reg_store, x_b)\n .then(reg_load_conclude, y)\n .then(conv_conclude, y)\n .then(reg_store_conclude, y);\n\n \/\/ -------------------------------------------------------\n \/\/ Layer III\n \/\/ -------------------------------------------------------\n buffer output_buf(\"output_buf\", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output);\n\n buffer input_mean_buf(\"input_mean_buf\", {FIN_NB_BLOCKS, FIN_BLOCKING}, p_float32, a_input);\n buffer input_sd_buf(\"input_sd_buf\", {FIN_NB_BLOCKS, FIN_BLOCKING}, p_float32, a_input);\n\n buffer workspace_buf(\"workspace_buf\", {BATCH_SIZE, N + 2, N + 2, FIN_BLOCKING}, p_float32, a_input);\n\n \/\/ This is where intermediate results of convolution will be stored.\n \/\/ We rely on the compiler to detect that this buffer can be mapped to CPU registers.\n buffer reg_buf(\"reg_buf\", {FOUT_NB_BLOCKS, X_BLOCKING, FOUT_BLOCKING}, p_float32, a_temporary);\n\n input_sum_init.store_in(&input_mean_buf);\n input_sum.store_in(&input_mean_buf, {fin_b, ffin});\n input_mean.store_in(&input_mean_buf);\n \n input_sum_squares_init.store_in(&input_sd_buf);\n input_sum_squares.store_in(&input_sd_buf, {fin_b, ffin});\n input_sd.store_in(&input_sd_buf);\n\n bn.store_in(&workspace_buf, {n, y_pad, x_pad, ffin});\n relu.store_in(&workspace_buf, {n, y_pad, x_pad, ffin});\n\n \/*\n * Storage for conv\n *\/\n conv_init.store_in(&output_buf, {n, fout_b, y, x, ffout});\n conv_out.store_in(®_buf, {fout_b, x%X_BLOCKING, ffout});\n\n reg_load.store_in(®_buf, {fout_b, x_bound%X_BLOCKING, ffout});\n conv.store_in(®_buf, {fout_b, x_bound%X_BLOCKING, ffout});\n reg_store.store_in(&output_buf, {n, fout_b, y, x_bound, ffout});\n\n reg_load_conclude.store_in(®_buf, {fout_b, x_conclude%X_BLOCKING, ffout});\n conv_conclude.store_in(®_buf, {fout_b, x_conclude%X_BLOCKING, ffout});\n reg_store_conclude.store_in(&output_buf, {n, fout_b, y, x_conclude, ffout});\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n codegen({\n c_input.get_buffer(),\n bn_scale.get_buffer(), \n bn_shift.get_buffer(),\n conv_filter.get_buffer(), \n conv_bias.get_buffer(),\n &input_mean_buf,\n &input_sd_buf,\n &workspace_buf,\n &output_buf\n }, \"densenet_block_tiramisu.o\");\n\n return 0;\n}\n<commit_msg>DenseNet block : apply fusion<commit_after>#include <tiramisu\/tiramisu.h>\n#include <vector>\n#include \"configure.h\"\n\nusing namespace tiramisu;\n\nint main()\n{\n init(\"densenet_block\");\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n var x(\"x\", 0, N), y(\"y\", 0, N), z(\"z\", 0, 4*GR), n(\"n\", 0, BATCH_SIZE);\n\n var x_pad(\"x\", 0, N + 2), y_pad(\"y\", 0, N + 2);\n var k_x(\"k_x\", 0, K_X), k_y(\"k_y\", 0, K_Y);\n\n var fin_b(\"fin_b\", 0, FIN_NB_BLOCKS), ffin(\"ffin\", 0, FIN_BLOCKING);\n var fout_b(\"fout_b\", 0, FOUT_NB_BLOCKS), ffout(\"ffout\", 0, FOUT_BLOCKING);\n\n input c_input(\"c_input\", {n, fin_b, y_pad, x_pad, ffin}, p_float32);\n input bn_scale(\"bn_scale\", {fin_b, ffin}, p_float32);\n input bn_shift(\"bn_shift\", {fin_b, ffin}, p_float32);\n\n input conv_filter(\"conv_filter\", {fin_b, fout_b, k_y, k_x, ffin, ffout}, p_float32);\n input conv_bias(\"conv_bias\", {fout_b, ffout}, p_float32);\n\n \/\/ Batch normalization followed by ReLU\n \/\/ Compute the sum over the features dimension (z)\n computation input_sum_init(\"input_sum_init\", {fin_b, ffin}, cast(p_float32, 0));\n computation input_sum(\n \"input_sum\", \n {fin_b, n, y_pad, x_pad, ffin}, \n input_sum_init(fin_b, ffin) + c_input(n, fin_b, y_pad, x_pad, ffin)\n );\n\n \/\/ Compute the sum of squares over the features dimension (z)\n computation input_sum_squares_init(\"input_sum_squares_init\", {fin_b, ffin}, cast(p_float32, 0));\n computation input_sum_squares(\n \"input_sum_squares\", \n {fin_b, n, y_pad, x_pad, ffin}, \n input_sum_squares_init(fin_b, ffin) + c_input(n, fin_b, y_pad, x_pad, ffin) * c_input(n, fin_b, y_pad, x_pad, ffin)\n );\n\n computation input_mean(\n \"input_mean\", \n {fin_b, ffin}, \n input_sum(fin_b, 0, 0, 0, ffin) \/ cast(p_float32, BATCH_SIZE*(N+2)*(N+2))\n );\n\n computation input_sd(\n \"input_sd\", \n {fin_b, ffin}, \n expr(\n o_sqrt, \n input_sum_squares(fin_b, 0, 0, 0, ffin) \/ cast(p_float32, BATCH_SIZE*(N+2)*(N+2)) - input_mean(fin_b, ffin) * input_mean(fin_b, ffin) + cast(p_float32, EPSILON)\n )\n );\n \n \/\/ Compute BN followed by ReLU\n\n \/\/ Compute BN-ReLU for y = 0, 1\n var y_prelude(\"y_prelude\", 0, 2);\n computation bn_prelude(\n \"bn_prelude\",\n {n, fin_b, y_prelude, x_pad, ffin},\n bn_scale(fin_b, ffin) * ((c_input(n, fin_b, y_prelude, x_pad, ffin) - input_mean(fin_b, ffin)) \/ input_sd(fin_b, ffin)) + bn_shift(fin_b, ffin)\n );\n\n computation relu_prelude(\n \"relu_prelude\", \n {n, fin_b, y_prelude, x_pad, ffin}, \n expr(\n o_max, \n cast(p_float32, 0), \n bn_prelude(n, fin_b, y_prelude, x_pad, ffin)\n )\n );\n\n \/\/ Compute BN-ReLU for y = 2, .... N + 1\n computation bn(\n \"bn\", \n {n, fin_b, y, x_pad, ffin}, \n bn_scale(fin_b, ffin) * ((c_input(n, fin_b, y + 2, x_pad, ffin) - input_mean(fin_b, ffin)) \/ input_sd(fin_b, ffin)) + bn_shift(fin_b, ffin)\n );\n\n computation relu(\n \"relu\", \n {n, fin_b, y, x_pad, ffin}, \n expr(\n o_max, \n cast(p_float32, 0), \n bn(n, fin_b, y, x_pad, ffin)\n )\n );\n\n computation conv_init(\"conv_init\", {n, fout_b, y, x, ffout}, conv_bias(fout_b, ffout));\n view conv_out(\"conv_out\", {n, y, x, fout_b, ffout}, p_float32);\n\n \/\/ Convolution computation\n \/\/ x_bound is used to have the width dimension divisible by X_BLOCKING\n \/\/ in the conv computation.\n var x_bound(\"x_bound\", 0, X_BOUND);\n var x_conclude(\"x_conclude\", X_BOUND, N);\n\n view relu_view(\"relu_view\", {n, fin_b, y_pad, x_pad, ffin}, p_float32);\n\n \/\/ Compute convolution from 0 to x_bound\n computation conv(\n \"conv\",\n {n, fin_b, y, x_bound, k_y, k_x, ffin, fout_b, ffout},\n conv_out(n, y, x_bound, fout_b, ffout) + conv_filter(fin_b, fout_b, k_y, k_x, ffin, ffout) * relu_view(n, fin_b, y + k_y, x_bound + k_x, ffin)\n );\n\n \/\/ Compute convolution from x_bound to N\n computation conv_conclude(\n \"conv_conclude\",\n {n, fin_b, y, k_y, k_x, ffin, fout_b, ffout, x_conclude},\n conv_out(n, y, x_conclude, fout_b, ffout) + conv_filter(fin_b, fout_b, k_y, k_x, ffin, ffout) * relu_view(n, fin_b, y + k_y, x_conclude + k_x, ffin)\n );\n \n \/\/ -------------------------------------------------------\n \/\/ Layer II\n \/\/ -------------------------------------------------------\n input_sum.vectorize(ffin, VEC_LEN);\n input_sum.tag_parallel_level(fin_b);\n\n bn_prelude.vectorize(ffin, VEC_LEN);\n bn.vectorize(ffin, VEC_LEN);\n\n \/*\n * Schedule for conv\n *\/\n \/\/ We introduce those two computations to do register blocking\n computation reg_load(\n \"reg_load\",\n {n, fin_b, y, x_bound, fout_b, ffout},\n conv_init(n, fout_b, y, x_bound, ffout)\n );\n\n computation reg_store(\n \"reg_store\",\n {n, fin_b, y, x_bound, fout_b, ffout},\n conv(n, fin_b, y, x_bound, 0, 0, 0, fout_b, ffout)\n );\n\n \/\/ Split over dimension x\n var x_b, xx;\n conv.split(x_bound, X_BLOCKING, x_b, xx);\n\n conv.interchange(xx, k_y);\n conv.interchange(xx, k_x);\n conv.interchange(xx, ffin);\n conv.interchange(xx, fout_b);\n conv.interchange(xx, ffout);\n\n reg_load.split(x_bound, X_BLOCKING, x_b, xx);\n reg_store.split(x_bound, X_BLOCKING, x_b, xx);\n\n reg_load.interchange(xx, fout_b);\n reg_load.interchange(xx, ffout);\n\n reg_store.interchange(xx, fout_b);\n reg_store.interchange(xx, ffout);\n\n \/\/ Vectorize and unroll\n reg_load.vectorize(ffout, VEC_LEN);\n conv.vectorize(ffout, VEC_LEN);\n reg_store.vectorize(ffout, VEC_LEN);\n\n conv.tag_unroll_level(xx);\n conv.tag_unroll_level(fout_b);\n\n reg_load.tag_unroll_level(xx);\n reg_load.tag_unroll_level(fout_b);\n\n reg_store.tag_unroll_level(xx);\n reg_store.tag_unroll_level(fout_b);\n\n \/\/ schedule for conv_conclude\n \/\/ This schedule is the same as conv computation\n computation reg_load_conclude(\n \"reg_load_conclude\",\n {n, fin_b, y, fout_b, ffout, x_conclude},\n conv_init(n, fout_b, y, x_conclude, ffout)\n );\n\n computation reg_store_conclude(\n \"reg_store_conclude\",\n {n, fin_b, y, fout_b, ffout, x_conclude},\n conv_conclude(n, fin_b, y, 0, 0, 0, fout_b, ffout, x_conclude)\n );\n\n reg_load_conclude.vectorize(ffout, VEC_LEN);\n conv_conclude.vectorize(ffout, VEC_LEN);\n reg_store_conclude.vectorize(ffout, VEC_LEN);\n\n conv_conclude.tag_unroll_level(x_conclude);\n conv_conclude.tag_unroll_level(fout_b);\n\n reg_load_conclude.tag_unroll_level(x_conclude);\n reg_load_conclude.tag_unroll_level(fout_b);\n\n reg_store_conclude.tag_unroll_level(x_conclude);\n reg_store_conclude.tag_unroll_level(fout_b);\n\n \/\/ Parallelize and order\n conv.tag_parallel_level(n);\n\n input_sum_init.then(input_sum_squares_init, ffin)\n .then(input_sum, fin_b)\n .then(input_sum_squares, ffin)\n .then(input_mean, fin_b)\n .then(input_sd, ffin)\n .then(conv_init, computation::root)\n .then(bn_prelude, n)\n .then(relu_prelude, ffin)\n .then(bn, fin_b)\n .then(relu, ffin)\n .then(reg_load, y)\n .then(conv, x_b)\n .then(reg_store, x_b)\n .then(reg_load_conclude, y)\n .then(conv_conclude, y)\n .then(reg_store_conclude, y);\n\n \/\/ -------------------------------------------------------\n \/\/ Layer III\n \/\/ -------------------------------------------------------\n buffer output_buf(\"output_buf\", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output);\n\n buffer input_mean_buf(\"input_mean_buf\", {FIN_NB_BLOCKS, FIN_BLOCKING}, p_float32, a_input);\n buffer input_sd_buf(\"input_sd_buf\", {FIN_NB_BLOCKS, FIN_BLOCKING}, p_float32, a_input);\n\n buffer workspace_buf(\"workspace_buf\", {BATCH_SIZE, N + 2, N + 2, FIN_BLOCKING}, p_float32, a_input);\n\n \/\/ This is where intermediate results of convolution will be stored.\n \/\/ We rely on the compiler to detect that this buffer can be mapped to CPU registers.\n buffer reg_buf(\"reg_buf\", {FOUT_NB_BLOCKS, X_BLOCKING, FOUT_BLOCKING}, p_float32, a_temporary);\n\n input_sum_init.store_in(&input_mean_buf);\n input_sum.store_in(&input_mean_buf, {fin_b, ffin});\n input_mean.store_in(&input_mean_buf);\n \n input_sum_squares_init.store_in(&input_sd_buf);\n input_sum_squares.store_in(&input_sd_buf, {fin_b, ffin});\n input_sd.store_in(&input_sd_buf);\n\n bn_prelude.store_in(&workspace_buf, {n, y_prelude, x_pad, ffin});\n relu_prelude.store_in(&workspace_buf, {n, y_prelude, x_pad, ffin});\n \n bn.store_in(&workspace_buf, {n, y + 2, x_pad, ffin});\n relu.store_in(&workspace_buf, {n, y + 2, x_pad, ffin});\n\n \/*\n * Storage for conv\n *\/\n relu_view.store_in(&workspace_buf, {n, y_pad, x_pad, ffin});\n\n conv_init.store_in(&output_buf, {n, fout_b, y, x, ffout});\n conv_out.store_in(®_buf, {fout_b, x%X_BLOCKING, ffout});\n\n reg_load.store_in(®_buf, {fout_b, x_bound%X_BLOCKING, ffout});\n conv.store_in(®_buf, {fout_b, x_bound%X_BLOCKING, ffout});\n reg_store.store_in(&output_buf, {n, fout_b, y, x_bound, ffout});\n\n reg_load_conclude.store_in(®_buf, {fout_b, x_conclude%X_BLOCKING, ffout});\n conv_conclude.store_in(®_buf, {fout_b, x_conclude%X_BLOCKING, ffout});\n reg_store_conclude.store_in(&output_buf, {n, fout_b, y, x_conclude, ffout});\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n codegen({\n c_input.get_buffer(),\n bn_scale.get_buffer(), \n bn_shift.get_buffer(),\n conv_filter.get_buffer(), \n conv_bias.get_buffer(),\n &input_mean_buf,\n &input_sd_buf,\n &workspace_buf,\n &output_buf\n }, \"densenet_block_tiramisu.o\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2004-2006 Matthias Kretz <kretz@kde.org>\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 version 2 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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"factory.h\"\n#include \"base_p.h\"\n\n#include <kservicetypetrader.h>\n#include <klibloader.h>\n#include <kmessagebox.h>\n#include <QFile>\n#include <QList>\n#include <klocale.h>\n#include <kmimetype.h>\n#include <kdebug.h>\n#include <kstaticdeleter.h>\n\n#include <QtDBus\/QtDBus>\n\nstatic KStaticDeleter<Phonon::Factory> sd;\n\n#define PHONON_LOAD_BACKEND_GLOBAL 1\n\nnamespace Phonon\n{\nclass Factory::Private\n{\n\tpublic:\n\t\tPrivate()\n\t\t\t: backend( 0 )\n\t\t{\n\t\t\tqRegisterMetaType<qint64>( \"qint64\" );\n\t\t\tqRegisterMetaType<qint32>( \"qint32\" );\n\t\t}\n\n\t\tvoid createBackend()\n\t\t{\n\t\t\tconst KService::List offers = KServiceTypeTrader::self()->query( \"PhononBackend\",\n\t\t\t\t\t\"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1\" );\n\t\t\tKService::List::const_iterator it = offers.begin();\n\t\t\tconst KService::List::const_iterator end = offers.end();\n\t\t\tQStringList errormsg;\n\t\t\tfor( ; it != end; ++it )\n\t\t\t{\n\t\t\t\tKService::Ptr ptr = *it;\n\t\t\t\tKLibFactory* factory = 0;\n#ifdef PHONON_LOAD_BACKEND_GLOBAL\n\t\t\t\t\/\/ This code is in here temporarily until NMM gets fixed.\n\t\t\t\t\/\/ Currently the NMM backend will fail with undefined symbols if\n\t\t\t\t\/\/ the backend is not loaded with global symbol resolution\n\t\t\t\tKLibrary* library = KLibLoader::self()->library( QFile::encodeName( ptr->library() ), QLibrary::ExportExternalSymbolsHint );\n\t\t\t\tif( library )\n\t\t\t\t\tfactory = library->factory();\n#else\n\t\t\t\tfactory = KLibLoader::self()->factory( QFile::encodeName( ptr->library() ) );\n#endif\n\t\t\t\tif( factory )\n\t\t\t\t{\n\t\t\t\t\tbackend = factory->create();\n\t\t\t\t\tif( 0 == backend )\n\t\t\t\t\t{\n\t\t\t\t\t\tQString e = i18n( \"create method returned 0\" );\n\t\t\t\t\t\terrormsg.append( e );\n\t\t\t\t\t\tkDebug( 600 ) << \"Error getting backend from factory for \" <<\n\t\t\t\t\t\t\tptr->name() << \", \" << ptr->library() << \":\\n\" << e << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tservice = ptr;\n\t\t\t\t\t\tkDebug( 600 ) << \"using backend: \" << ptr->name() << endl;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tQString e = KLibLoader::self()->lastErrorMessage();\n\t\t\t\t\terrormsg.append( e );\n\t\t\t\t\tkDebug( 600 ) << \"Error getting factory for \" << ptr->name() <<\n\t\t\t\t\t\t\":\\n\" << e << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif( 0 == backend )\n\t\t\t{\n\t\t\t\tif( offers.size() == 0 )\n\t\t\t\t\tKMessageBox::error( 0, i18n( \"Unable to find a Multimedia Backend\" ) );\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tQString details = \"<qt><table>\";\n\t\t\t\t\tQStringList::Iterator eit = errormsg.begin();\n\t\t\t\t\tQStringList::Iterator eend = errormsg.end();\n\t\t\t\t\tKService::List::const_iterator oit = offers.begin();\n\t\t\t\t\tconst KService::List::const_iterator oend = offers.end();\n\t\t\t\t\tfor( ; eit != eend || oit != oend; ++eit, ++oit )\n\t\t\t\t\t\tdetails += QString( \"<tr><td><b>%1<\/b><\/td><td>%2<\/td><\/tr>\" )\n\t\t\t\t\t\t\t.arg( ( *oit )->name() ).arg( *eit );\n\t\t\t\t\tdetails += \"<\/table><\/qt>\";\n\n\t\t\t\t\tKMessageBox::detailedError( 0,\n\t\t\t\t\t\t\ti18n( \"Unable to use any of the available Multimedia Backends\" ), details );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tQObject* backend;\n\t\tKService::Ptr service;\n\n\t\tQList<QObject*> objects;\n\t\tQList<BasePrivate*> basePrivateList;\n};\n\nFactory * Factory::m_self = 0;\n\nFactory * Factory::self()\n{\n\tif( ! m_self )\n\t{\n\t\tm_self = new Factory();\n\t\t::sd.setObject( m_self, m_self );\n\t}\n\treturn m_self;\n}\n\nFactory::Factory()\n\t: d( new Private )\n{\n\tQDBusConnection::sessionBus().connect(QString(), QString(), \"org.kde.Phonon.Factory\",\n\t\t\t\"phononBackendChanged\", this, SLOT(phononBackendChanged()));\n}\n\nFactory::~Factory()\n{\n\t\/\/kDebug( 600 ) << k_funcinfo << endl;\n\temit aboutToBeDestroyed();\n\n\tforeach( BasePrivate* bp, d->basePrivateList )\n\t\tbp->deleteIface();\n\tqDeleteAll(d->objects);\n\tdelete d->backend;\n\tdelete d;\n}\n\nvoid Factory::registerFrontendObject( BasePrivate* bp )\n{\n\td->basePrivateList.append( bp );\n}\n\nvoid Factory::deregisterFrontendObject( BasePrivate* bp )\n{\n\td->basePrivateList.removeAll( bp );\n}\n\nvoid Factory::phononBackendChanged()\n{\n\tif( d->backend )\n\t{\n\t\tforeach( BasePrivate* bp, d->basePrivateList )\n\t\t\tbp->deleteIface();\n\t\tif( d->objects.size() > 0 )\n\t\t{\n\t\t\tkWarning( 600 ) << \"we were asked to change the backend but the application did\\n\"\n\t\t\t\t\"not free all references to objects created by the factory. Therefore we can not\\n\"\n\t\t\t\t\"change the backend without crashing. Now we have to wait for a restart to make\\n\"\n\t\t\t\t\"backendswitching possible.\" << endl;\n\t\t\t\/\/ in case there were objects deleted give 'em a chance to recreate\n\t\t\t\/\/ them now\n\t\t\tforeach( BasePrivate* bp, d->basePrivateList )\n\t\t\t\tbp->createIface();\n\t\t\treturn;\n\t\t}\n\t\tdelete d->backend;\n\t\td->backend = 0;\n\t}\n\td->createBackend();\n\tforeach( BasePrivate* bp, d->basePrivateList )\n\t\tbp->createIface();\n\temit backendChanged();\n}\n\n\/\/X void Factory::freeSoundcardDevices()\n\/\/X {\n\/\/X \tif( d->backend )\n\/\/X \t{\n\/\/X \t\td->backend->freeSoundcardDevices();\n\/\/X \t}\n\/\/X }\n\nvoid Factory::objectDestroyed( QObject * obj )\n{\n\t\/\/kDebug( 600 ) << k_funcinfo << obj << endl;\n\td->objects.removeAll( obj );\n}\n\n#define FACTORY_IMPL( classname ) \\\nQObject* Factory::create ## classname( QObject* parent ) \\\n{ \\\n\tif( backend() ) \\\n\t{ \\\n\t\tQObject* ret; \\\n\t\tif( QMetaObject::invokeMethod( d->backend, \"create\"#classname, Qt::DirectConnection, Q_RETURN_ARG( QObject*, ret ), Q_ARG( QObject*, parent ) ) ) \\\n\t\t\treturn registerQObject( ret ); \\\n\t} \\\n\treturn 0; \\\n}\n#define FACTORY_IMPL_1ARG( type1, classname ) \\\nQObject* Factory::create ## classname( type1 name1, QObject* parent ) \\\n{ \\\n\tif( backend() ) \\\n\t{ \\\n\t\tQObject* ret; \\\n\t\tif( QMetaObject::invokeMethod( d->backend, \"create\"#classname, Qt::DirectConnection, Q_RETURN_ARG( QObject*, ret ), Q_ARG( type1, name1 ), Q_ARG( QObject*, parent ) ) ) \\\n\t\t\treturn registerQObject( ret ); \\\n\t} \\\n\treturn 0; \\\n}\n\nFACTORY_IMPL( MediaObject )\nFACTORY_IMPL( MediaQueue )\nFACTORY_IMPL( AvCapture )\nFACTORY_IMPL( ByteStream )\nFACTORY_IMPL( AudioPath )\nFACTORY_IMPL_1ARG( int, AudioEffect )\nFACTORY_IMPL( VolumeFaderEffect )\nFACTORY_IMPL( AudioOutput )\nFACTORY_IMPL( AudioDataOutput )\nFACTORY_IMPL( Visualization )\nFACTORY_IMPL( VideoPath )\nFACTORY_IMPL_1ARG( int, VideoEffect )\nFACTORY_IMPL( BrightnessControl )\nFACTORY_IMPL( VideoDataOutput )\n\n#undef FACTORY_IMPL\n\nQObject* Factory::backend( bool createWhenNull )\n{\n\tif( createWhenNull && d->backend == 0 )\n\t{\n\t\td->createBackend();\n\t\t\/\/ XXX: might create \"reentrancy\" problems:\n\t\t\/\/ a method calls this method and is called again because the\n\t\t\/\/ backendChanged signal is emitted\n\t\temit backendChanged();\n\t}\n\treturn d->backend;\n}\n\nconst char* Factory::uiLibrary()\n{\n\tif( !backend() )\n\t\treturn 0;\n\tconst char* ret = 0;\n\tQMetaObject::invokeMethod( d->backend, \"uiLibrary\", Qt::DirectConnection, Q_RETURN_ARG( const char*, ret ) );\n\treturn ret;\n}\n\nconst char* Factory::uiSymbol()\n{\n\tif( !backend() )\n\t\treturn 0;\n\tconst char* ret = 0;\n\t\/\/ the backend doesn't have to implement the symbol - the default factory\n\t\/\/ symbol will be used then\n\tif( QMetaObject::invokeMethod( d->backend, \"uiSymbol\", Qt::DirectConnection, Q_RETURN_ARG( const char*, ret ) ) )\n\t\treturn ret;\n\treturn 0;\n}\n\nQString Factory::backendName() const\n{\n\tif( d->service )\n\t\treturn d->service->name();\n\telse\n\t\treturn QString();\n}\n\nQString Factory::backendComment() const\n{\n\tif( d->service )\n\t\treturn d->service->comment();\n\telse\n\t\treturn QString();\n}\n\nQString Factory::backendVersion() const\n{\n\tif( d->service )\n\t\treturn d->service->property( \"X-KDE-PhononBackendInfo-Version\" ).toString();\n\telse\n\t\treturn QString();\n}\n\nQString Factory::backendIcon() const\n{\n\tif( d->service )\n\t\treturn d->service->icon();\n\telse\n\t\treturn QString();\n}\n\nQString Factory::backendWebsite() const\n{\n\tif( d->service )\n\t\treturn d->service->property( \"X-KDE-PhononBackendInfo-Website\" ).toString();\n\telse\n\t\treturn QString();\n}\n\nQObject* Factory::registerQObject( QObject* o )\n{\n\tconnect( o, SIGNAL( destroyed( QObject* ) ), SLOT( objectDestroyed( QObject* ) ), Qt::DirectConnection );\n\td->objects.append( o );\n\treturn o;\n}\n\n} \/\/namespace Phonon\n\n#include \"factory.moc\"\n\n\/\/ vim: sw=4 ts=4 noet\n<commit_msg>ignore null pointers<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2004-2006 Matthias Kretz <kretz@kde.org>\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 version 2 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 Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"factory.h\"\n#include \"base_p.h\"\n\n#include <kservicetypetrader.h>\n#include <klibloader.h>\n#include <kmessagebox.h>\n#include <QFile>\n#include <QList>\n#include <klocale.h>\n#include <kmimetype.h>\n#include <kdebug.h>\n#include <kstaticdeleter.h>\n\n#include <QtDBus\/QtDBus>\n\nstatic KStaticDeleter<Phonon::Factory> sd;\n\n#define PHONON_LOAD_BACKEND_GLOBAL 1\n\nnamespace Phonon\n{\nclass Factory::Private\n{\n\tpublic:\n\t\tPrivate()\n\t\t\t: backend( 0 )\n\t\t{\n\t\t\tqRegisterMetaType<qint64>( \"qint64\" );\n\t\t\tqRegisterMetaType<qint32>( \"qint32\" );\n\t\t}\n\n\t\tvoid createBackend()\n\t\t{\n\t\t\tconst KService::List offers = KServiceTypeTrader::self()->query( \"PhononBackend\",\n\t\t\t\t\t\"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1\" );\n\t\t\tKService::List::const_iterator it = offers.begin();\n\t\t\tconst KService::List::const_iterator end = offers.end();\n\t\t\tQStringList errormsg;\n\t\t\tfor( ; it != end; ++it )\n\t\t\t{\n\t\t\t\tKService::Ptr ptr = *it;\n\t\t\t\tKLibFactory* factory = 0;\n#ifdef PHONON_LOAD_BACKEND_GLOBAL\n\t\t\t\t\/\/ This code is in here temporarily until NMM gets fixed.\n\t\t\t\t\/\/ Currently the NMM backend will fail with undefined symbols if\n\t\t\t\t\/\/ the backend is not loaded with global symbol resolution\n\t\t\t\tKLibrary* library = KLibLoader::self()->library( QFile::encodeName( ptr->library() ), QLibrary::ExportExternalSymbolsHint );\n\t\t\t\tif( library )\n\t\t\t\t\tfactory = library->factory();\n#else\n\t\t\t\tfactory = KLibLoader::self()->factory( QFile::encodeName( ptr->library() ) );\n#endif\n\t\t\t\tif( factory )\n\t\t\t\t{\n\t\t\t\t\tbackend = factory->create();\n\t\t\t\t\tif( 0 == backend )\n\t\t\t\t\t{\n\t\t\t\t\t\tQString e = i18n( \"create method returned 0\" );\n\t\t\t\t\t\terrormsg.append( e );\n\t\t\t\t\t\tkDebug( 600 ) << \"Error getting backend from factory for \" <<\n\t\t\t\t\t\t\tptr->name() << \", \" << ptr->library() << \":\\n\" << e << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tservice = ptr;\n\t\t\t\t\t\tkDebug( 600 ) << \"using backend: \" << ptr->name() << endl;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tQString e = KLibLoader::self()->lastErrorMessage();\n\t\t\t\t\terrormsg.append( e );\n\t\t\t\t\tkDebug( 600 ) << \"Error getting factory for \" << ptr->name() <<\n\t\t\t\t\t\t\":\\n\" << e << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif( 0 == backend )\n\t\t\t{\n\t\t\t\tif( offers.size() == 0 )\n\t\t\t\t\tKMessageBox::error( 0, i18n( \"Unable to find a Multimedia Backend\" ) );\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tQString details = \"<qt><table>\";\n\t\t\t\t\tQStringList::Iterator eit = errormsg.begin();\n\t\t\t\t\tQStringList::Iterator eend = errormsg.end();\n\t\t\t\t\tKService::List::const_iterator oit = offers.begin();\n\t\t\t\t\tconst KService::List::const_iterator oend = offers.end();\n\t\t\t\t\tfor( ; eit != eend || oit != oend; ++eit, ++oit )\n\t\t\t\t\t\tdetails += QString( \"<tr><td><b>%1<\/b><\/td><td>%2<\/td><\/tr>\" )\n\t\t\t\t\t\t\t.arg( ( *oit )->name() ).arg( *eit );\n\t\t\t\t\tdetails += \"<\/table><\/qt>\";\n\n\t\t\t\t\tKMessageBox::detailedError( 0,\n\t\t\t\t\t\t\ti18n( \"Unable to use any of the available Multimedia Backends\" ), details );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tQObject* backend;\n\t\tKService::Ptr service;\n\n\t\tQList<QObject*> objects;\n\t\tQList<BasePrivate*> basePrivateList;\n};\n\nFactory * Factory::m_self = 0;\n\nFactory * Factory::self()\n{\n\tif( ! m_self )\n\t{\n\t\tm_self = new Factory();\n\t\t::sd.setObject( m_self, m_self );\n\t}\n\treturn m_self;\n}\n\nFactory::Factory()\n\t: d( new Private )\n{\n\tQDBusConnection::sessionBus().connect(QString(), QString(), \"org.kde.Phonon.Factory\",\n\t\t\t\"phononBackendChanged\", this, SLOT(phononBackendChanged()));\n}\n\nFactory::~Factory()\n{\n\t\/\/kDebug( 600 ) << k_funcinfo << endl;\n\temit aboutToBeDestroyed();\n\n\tforeach( BasePrivate* bp, d->basePrivateList )\n\t\tbp->deleteIface();\n\tqDeleteAll(d->objects);\n\tdelete d->backend;\n\tdelete d;\n}\n\nvoid Factory::registerFrontendObject( BasePrivate* bp )\n{\n\td->basePrivateList.append( bp );\n}\n\nvoid Factory::deregisterFrontendObject( BasePrivate* bp )\n{\n\td->basePrivateList.removeAll( bp );\n}\n\nvoid Factory::phononBackendChanged()\n{\n\tif( d->backend )\n\t{\n\t\tforeach( BasePrivate* bp, d->basePrivateList )\n\t\t\tbp->deleteIface();\n\t\tif( d->objects.size() > 0 )\n\t\t{\n\t\t\tkWarning( 600 ) << \"we were asked to change the backend but the application did\\n\"\n\t\t\t\t\"not free all references to objects created by the factory. Therefore we can not\\n\"\n\t\t\t\t\"change the backend without crashing. Now we have to wait for a restart to make\\n\"\n\t\t\t\t\"backendswitching possible.\" << endl;\n\t\t\t\/\/ in case there were objects deleted give 'em a chance to recreate\n\t\t\t\/\/ them now\n\t\t\tforeach( BasePrivate* bp, d->basePrivateList )\n\t\t\t\tbp->createIface();\n\t\t\treturn;\n\t\t}\n\t\tdelete d->backend;\n\t\td->backend = 0;\n\t}\n\td->createBackend();\n\tforeach( BasePrivate* bp, d->basePrivateList )\n\t\tbp->createIface();\n\temit backendChanged();\n}\n\n\/\/X void Factory::freeSoundcardDevices()\n\/\/X {\n\/\/X \tif( d->backend )\n\/\/X \t{\n\/\/X \t\td->backend->freeSoundcardDevices();\n\/\/X \t}\n\/\/X }\n\nvoid Factory::objectDestroyed( QObject * obj )\n{\n\t\/\/kDebug( 600 ) << k_funcinfo << obj << endl;\n\td->objects.removeAll( obj );\n}\n\n#define FACTORY_IMPL( classname ) \\\nQObject* Factory::create ## classname( QObject* parent ) \\\n{ \\\n\tif( backend() ) \\\n\t{ \\\n\t\tQObject* ret; \\\n\t\tif( QMetaObject::invokeMethod( d->backend, \"create\"#classname, Qt::DirectConnection, Q_RETURN_ARG( QObject*, ret ), Q_ARG( QObject*, parent ) ) ) \\\n\t\t\treturn registerQObject( ret ); \\\n\t} \\\n\treturn 0; \\\n}\n#define FACTORY_IMPL_1ARG( type1, classname ) \\\nQObject* Factory::create ## classname( type1 name1, QObject* parent ) \\\n{ \\\n\tif( backend() ) \\\n\t{ \\\n\t\tQObject* ret; \\\n\t\tif( QMetaObject::invokeMethod( d->backend, \"create\"#classname, Qt::DirectConnection, Q_RETURN_ARG( QObject*, ret ), Q_ARG( type1, name1 ), Q_ARG( QObject*, parent ) ) ) \\\n\t\t\treturn registerQObject( ret ); \\\n\t} \\\n\treturn 0; \\\n}\n\nFACTORY_IMPL( MediaObject )\nFACTORY_IMPL( MediaQueue )\nFACTORY_IMPL( AvCapture )\nFACTORY_IMPL( ByteStream )\nFACTORY_IMPL( AudioPath )\nFACTORY_IMPL_1ARG( int, AudioEffect )\nFACTORY_IMPL( VolumeFaderEffect )\nFACTORY_IMPL( AudioOutput )\nFACTORY_IMPL( AudioDataOutput )\nFACTORY_IMPL( Visualization )\nFACTORY_IMPL( VideoPath )\nFACTORY_IMPL_1ARG( int, VideoEffect )\nFACTORY_IMPL( BrightnessControl )\nFACTORY_IMPL( VideoDataOutput )\n\n#undef FACTORY_IMPL\n\nQObject* Factory::backend( bool createWhenNull )\n{\n\tif( createWhenNull && d->backend == 0 )\n\t{\n\t\td->createBackend();\n\t\t\/\/ XXX: might create \"reentrancy\" problems:\n\t\t\/\/ a method calls this method and is called again because the\n\t\t\/\/ backendChanged signal is emitted\n\t\temit backendChanged();\n\t}\n\treturn d->backend;\n}\n\nconst char* Factory::uiLibrary()\n{\n\tif( !backend() )\n\t\treturn 0;\n\tconst char* ret = 0;\n\tQMetaObject::invokeMethod( d->backend, \"uiLibrary\", Qt::DirectConnection, Q_RETURN_ARG( const char*, ret ) );\n\treturn ret;\n}\n\nconst char* Factory::uiSymbol()\n{\n\tif( !backend() )\n\t\treturn 0;\n\tconst char* ret = 0;\n\t\/\/ the backend doesn't have to implement the symbol - the default factory\n\t\/\/ symbol will be used then\n\tif( QMetaObject::invokeMethod( d->backend, \"uiSymbol\", Qt::DirectConnection, Q_RETURN_ARG( const char*, ret ) ) )\n\t\treturn ret;\n\treturn 0;\n}\n\nQString Factory::backendName() const\n{\n\tif( d->service )\n\t\treturn d->service->name();\n\telse\n\t\treturn QString();\n}\n\nQString Factory::backendComment() const\n{\n\tif( d->service )\n\t\treturn d->service->comment();\n\telse\n\t\treturn QString();\n}\n\nQString Factory::backendVersion() const\n{\n\tif( d->service )\n\t\treturn d->service->property( \"X-KDE-PhononBackendInfo-Version\" ).toString();\n\telse\n\t\treturn QString();\n}\n\nQString Factory::backendIcon() const\n{\n\tif( d->service )\n\t\treturn d->service->icon();\n\telse\n\t\treturn QString();\n}\n\nQString Factory::backendWebsite() const\n{\n\tif( d->service )\n\t\treturn d->service->property( \"X-KDE-PhononBackendInfo-Website\" ).toString();\n\telse\n\t\treturn QString();\n}\n\nQObject* Factory::registerQObject( QObject* o )\n{\n\tif( o )\n\t{\n\t\tconnect( o, SIGNAL( destroyed( QObject* ) ), SLOT( objectDestroyed( QObject* ) ), Qt::DirectConnection );\n\t\td->objects.append( o );\n\t}\n\treturn o;\n}\n\n} \/\/namespace Phonon\n\n#include \"factory.moc\"\n\n\/\/ vim: sw=4 ts=4 noet\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Edited comments.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*###############################################################\n## MODULE: hdp_medoids.cpp\n## VERSION: 2.0 \n## SINCE 2014-07-21\n## AUTHOR:\n## Jimmy Lin (xl5224) - JimmyLin@utexas.edu \n##\n## DESCRIPTION: \n## Convex relaxation for hdp_medoids resolution\n################################################################# \n## Edited by MacVim\n## Class Info auto-generated by Snippet \n################################################################*\/\n\n#include \"hdp_medoids.h\"\n#include <set>\nusing namespace std;\n\n\/* Compute the mutual distance of input instances contained within \"data\" *\/\nvoid compute_dist_mat (Esmat* dist_mat, Lookups* tables, int N, int D) {\n \/\/ STEP ZERO: parse input\n vector< pair<int,int> > doc_lookup = *(tables->doc_lookup);\n vector< pair<int,int> > word_lookup = *(tables->word_lookup); \n \/\/ STEP ONE: compute distribution for each document\n vector< map<int, double> > distributions (D, map<int, double>());\n for (int d = 0; d < D; d ++) {\n \/\/ a. compute sum of word frequency\n int sumFreq = 0;\n for (int w = doc_lookup[d].first; w < doc_lookup[d].second; w++) {\n sumFreq += word_lookup[w].second;\n }\n \/\/ b. compute distribution\n for (int w = doc_lookup[d].first; w < doc_lookup[d].second; w++) {\n int voc_index = word_lookup[w].first;\n double prob = 1.0 * word_lookup[w].second \/ sumFreq;\n distributions[d].insert(pair<int, double> (voc_index, prob));\n }\n }\n \/\/ STEP TWO: compute weight of word within one document\n esmat_zeros(dist_mat);\n for (int j = 0; j < D; j ++) {\n for (int d = 0; d < D; d ++) {\n for (int w = doc_lookup[d].first; w < doc_lookup[d].second; w++) {\n int voc_index = word_lookup[w].first;\n int count_w_d1 = word_lookup[w].second; \n double prob_w_d2;\n double dist;\n map<int, double>::const_iterator iter;\n iter = distributions[j].find(voc_index);\n if (iter == distributions[j].end()) {\n prob_w_d2 = 0.0;\n dist = INF;\n } else {\n prob_w_d2 = iter->second;\n \/\/ dist(w, d2) = - count_w_d1 * log( prob_d2(w) )\n dist = - count_w_d1 * log(prob_w_d2);\n }\n int esmat_index = w + N * j;\n#ifdef DIST_MAT_DUMP\n cout << \"index: \" << esmat_index << \", dist: \" << dist << \", \";\n cout << \"count_w_d1: \" << count_w_d1 << \", prob_w_d2: \" << prob_w_d2 << endl;\n#endif\n dist_mat->val.push_back(make_pair(esmat_index, dist));\n }\n }\n }\n}\nvoid output_objective (vector<int> z, vector< vector<int> > v, double** dist_mat, Lookups* tables) {\n int N = tables->nWords;\n int D = tables->nDocs;\n double obj = 0.0; \n fstream obj_out(\"opt_objective\");\n for (int d = 0; d < D; d ++) {\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i++) {\n int g = v[d][z[i]];\n double dist = dist_mat[i][g];\n obj += dist;\n }\n }\n obj_out << obj;\n}\nvoid output_medoids (vector<int> global_medoids, Lookups* tables) {\n int N = tables->nWords;\n int D = tables->nDocs;\n int local_medoids = 0;\n fstream medoids_out(\"opt_medoids\");\n int nGlobalMedoids = global_medoids.size();\n for (int i = 0; i < nGlobalMedoids; i ++) {\n cout << \"Medoids\" << global_medoids[i] << endl;\n }\n medoids_out.close();\n}\nvoid output_medoids () {\n int N = tables->nWords; \n}\nvoid hdp_medoids (Esmat* dist_mat, vector<double> LAMBDAs, Lookups* tables) {\n \/\/ SET MODEL-RELEVANT PARAMETERS \n assert (LAMBDAs.size() == 2);\n double lambda_global = LAMBDAs[0];\n double lambda_local = LAMBDAs[1];\n double ALPHA = 1.0;\n double RHO = 1.0;\n int N = tables->nWords;\n int D = tables->nDocs;\n vector< pair<int,int> > doc_lookup = *(tables->doc_lookup);\n vector< pair<int,int> > word_lookup = *(tables->word_lookup); \n\n \/* A. DECLARE AND INITIALIZE INVOLVED VARIABLES AND MATRICES *\/\n vector<int> global_medoids (1,0);\n \/\/ vector< vector<int> > local_medoids (D,vector<int>(1,0));\n vector<int> z (N, 0);\n vector< vector<int> > v (D,vector<int>(1,0));\n \/\/ 1) randomize initial global cluster medoid \n global_medoids[0] = random() % D;\n \/\/ 2) randomize initial local cluster medoids for each document j\n ;\n \/\/ 3) initialize local cluster indicator z_ij = 1 for all j = 1\n for (int d = 0; d < D; d ++) {\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i++) {\n z[i] = 0;\n }\n }\n \/\/ 4) initialize global cluster association v_j1 = 1\n for (int d = 0; d < D; d ++) {\n v[d][0] = global_medoids[0];\n }\n \/* B. Repetition until Convergence *\/\n int iter = 0;\n int MAX_ITER = 1000;\n while (iter < MAX_ITER) {\n for (int d = 0; d < D; d++) {\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i ++) {\n \/\/ 1) preprocess distance\n double[] processed_dist_mat = new double [D];\n for (int examplar = 0; examplar < D; examplar ++) {\n int esmat_index = i + examplar * N;\n int value = dist_mat[i][examplar];\n processed_dist_mat[examplar] = value;\n }\n set<int> temp;\n int nGlobalMedoids= global_medoids.size();\n for (int g = 0; g < nGlobalMedoids; g++) \n temp.insert(global_medoids[g]);\n \/\/ int nLocalMedoids = local_medoids[d].size();\n int nLocalMedoids = v[d].size();\n for (int l = 0; l < nLocalMedoids; l++) \n \/\/ temp.erase(local_medoids[d][l]);\n temp.erase(v[d][l]);\n for (set<int>::iterator it=myset.begin();it!=myset.end();++it) \n processed_dist_mat[*it] += lambda_local;\n \/\/ 2) if .., global and local augmentation\n \/\/ if min_p d_ijp > \\lambda_l + \\lambda_g\n int min_index = -1;\n double min_value = INF; \n for (int index = 0; index < D; index ++) {\n if (processed_dist_mat[index] < min_value) {\n min_index = index;\n min_value = processed_dist_mat[index];\n }\n }\n if (min_value > lambda_local+lambda_global) {\n global_medoids.push_back(min_index);\n v[d].push_back(min_index);\n z[i] = nLocalMedoids;\n nLocalMedoids ++;\n }\n \/\/ 3) otherwise, local assignment or local augmentation\n else {\n bool is_c_exist = false;\n nLocalMedoids = v[d].size();\n for (int l = 0; l < nLocalMedoids; l ++) {\n if (v[d][l] == min_index) {\n z[i] = l;\n is_c_exist = true;\n break;\n }\n }\n if (!is_c_exist) { \/\/ local augmentation\n v[d].push_back(min_index);\n z[i] = nLocalMedoids;\n nLocalMedoids ++;\n }\n }\n delete[] processed_dist_mat;\n }\n }\n \/\/ 4) re-elect medoids for all local clusters\n for (int d = 0; d < D; d++) {\n int nLocalMedoids = v[d].size();\n for (int l = 0; l < nLocalMedoids; l++) {\n vector<int> words;\n \/\/ set<int> examplars;\n \/\/ examplars.insert(d);\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i++) {\n if (z[i] == l) {\n words.push_back(i);\n \/\/ examplars.insert(z[i]);\n }\n }\n int nDocWords = words.size();\n double ** temp_dist_mat = mat_init(nDocWords, D);\n for (int w = 0; w < nDocWords; w++) \n for (int td = 0; td < D; td++) \n temp_dist_mat[w][td] = dist_mat[words[w]][td];\n double * sum_temp_dist_col = new double [D];\n mat_sum_col (temp_dist_mat, sum_temp_dist_col, nDocWords, D);\n int min_index = -1; \n double min_value = INF; \/\/ min sum mu_jc\n for (int td = 0; td < D; td++) {\n if (sum_temp_dist_col[td] < min_value) {\n min_index = td;\n min_value = sum_temp_dist_col[td];\n }\n }\n v[d][l] = min_index; \/\/ update the better medoid\n delete[] sum_temp_dist_col;\n mat_free (temp_dist_mat, nDocWords, D);\n \/*\n \/\/ 5) if .., global augmentation\n \/\/ if min_p d_jcp > \\lambda_g + ... \n if (min_d_jcp > lambda_global+) {\n global_medoids.push_back(new_g);\n local_medoids[][] = new_g;\n }\n \/\/ 6) otherwise, update global association\n else {\n local_medoids[][] = new_g;\n }\n *\/\n }\n }\n\n \/\/ 7) re-elect medoids for global cluster\n int nGlobalMedoids = global_medoids.size();\n for (int g = 0; g < nGlobalMedoids; g++) {\n p = global_medoids[g];\n vector<int> words;\n set<int> examplar_set;\n for (int d = 0; d < D; d++) {\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i ++) {\n if (v[z[i]] == p) {\n words.push_back(i);\n examplar_set.insert(d);\n }\n }\n }\n vector<int> examplars;\n for (set<int>::iterator it=myset.begin();it!=myset.end();++it) \n examplars.push_back(*it);\n }\n int R = words.size(); \n int C = examplars.size();\n double** candidate_dist_mat = mat_init (R,C);\n for (int r = 0; r < R; r ++) {\n for (int c = 0; c < C; c ++) {\n candidate_dist_mat[r][c] = dist_mat[words[r]][examplars[c]];\n }\n }\n double* min_d_rc = new double [C];\n mat_sum_col (candidate_dist_mat, min_d_rc, R,C);\n int min_index;\n double min_value = INF;\n for (int m = 0; m < C; m ++) {\n if (min_d_rc[m] < min_value) {\n min_index = m;\n min_value = min_d_rc[m];\n }\n }\n int new_p = examplars[m];\n global_medoids[g] = new_p; \/\/ update\n delete[] min_d_rc;\n mat_free (candidate_dist_mat, R,C);\n }\n }\n \/* Put converged solution to destinated W*\/\n}\n\n\/\/ entry main function\nint main (int argc, char ** argv) {\n\n \/\/ EXCEPTION control: illustrate the usage if get input of wrong format\n if (argc < 5) {\n cerr << \"Usage: \" << endl;\n cerr << \"\\thdp_medoids [voc_dataFile] [doc_dataFile] [lambda_global] [lambda_local]\" << endl;\n exit(-1);\n }\n\n \/\/ PARSE arguments\n string voc_file (argv[1]);\n string doc_file (argv[2]);\n vector<double> LAMBDAs (2, 0.0);\n LAMBDAs[0] = atof(argv[3]); \/\/ lambda_document\n LAMBDAs[1] = atof(argv[4]); \/\/ lambda_topic\n\n \/\/ preprocess the input dataset\n vector<string> voc_list;\n voc_list_read (voc_file, &voc_list);\n int nVocs = voc_list.size();\n\n \/\/ init lookup_tables\n vector< pair<int,int> > doc_lookup;\n vector< pair<int,int> > word_lookup;\n vector< vector<int> > voc_lookup (nVocs, vector<int>());\n Lookups lookup_tables;\n lookup_tables.doc_lookup = &doc_lookup;\n lookup_tables.word_lookup = &word_lookup;\n lookup_tables.voc_lookup = &voc_lookup;\n\n document_list_read (doc_file, &lookup_tables);\n lookup_tables.nDocs = lookup_tables.doc_lookup->size();\n lookup_tables.nWords = lookup_tables.word_lookup->size();\n lookup_tables.nVocs = nVocs;\n\n int seed = time(NULL);\n srand (seed);\n cerr << \"###########################################\" << endl;\n cerr << \"nVocs = \" << lookup_tables.nVocs << endl; \/\/ # vocabularies\n cerr << \"nDocs = \" << lookup_tables.nDocs << endl; \/\/ # documents\n cerr << \"nWords = \" << lookup_tables.nWords << endl; \/\/ # words\n cerr << \"lambda_global = \" << LAMBDAs[0] << endl;\n cerr << \"lambda_local = \" << LAMBDAs[1] << endl;\n cerr << \"TRIM_THRESHOLD = \" << TRIM_THRESHOLD << endl;\n cerr << \"seed = \" << seed << endl;\n cerr << \"###########################################\" << endl;\n\n \/\/ Run sparse convex clustering\n int N = lookup_tables.nWords;\n int D = lookup_tables.nDocs;\n Esmat* W = esmat_init (lookup_tables.nWords, lookup_tables.nDocs);\n Esmat* dist_mat = esmat_init (N, D);\n compute_dist_mat (dist_mat, &lookup_tables, N, D);\n\n ofstream dmat_out (\"dist_mat\");\n dmat_out << esmat_toInfo(dist_mat);\n dmat_out << esmat_toString(dist_mat);\n hdp_medoids (dist_mat, LAMBDAs, W, &lookup_tables);\n\n \/* Output objective *\/\n output_objective(clustering_objective (dist_mat, W));\n\n \/* Output cluster centroids *\/\n output_model (W);\n\n \/* Output assignment *\/\n output_assignment (W, &word_lookup);\n\n \/* reallocation *\/\n esmat_free (W);\n esmat_free (dist_mat);\n}\n<commit_msg>more pushed<commit_after>\/*###############################################################\n## MODULE: hdp_medoids.cpp\n## VERSION: 2.0 \n## SINCE 2014-07-21\n## AUTHOR:\n## Jimmy Lin (xl5224) - JimmyLin@utexas.edu \n##\n## DESCRIPTION: \n## Convex relaxation for hdp_medoids resolution\n################################################################# \n## Edited by MacVim\n## Class Info auto-generated by Snippet \n################################################################*\/\n\n#include \"hdp_medoids.h\"\n#include <set>\nusing namespace std;\n\n\/* Compute the mutual distance of input instances contained within \"data\" *\/\nvoid compute_dist_mat (Esmat* dist_mat, Lookups* tables, int N, int D) {\n \/\/ STEP ZERO: parse input\n vector< pair<int,int> > doc_lookup = *(tables->doc_lookup);\n vector< pair<int,int> > word_lookup = *(tables->word_lookup); \n \/\/ STEP ONE: compute distribution for each document\n vector< map<int, double> > distributions (D, map<int, double>());\n for (int d = 0; d < D; d ++) {\n \/\/ a. compute sum of word frequency\n int sumFreq = 0;\n for (int w = doc_lookup[d].first; w < doc_lookup[d].second; w++) {\n sumFreq += word_lookup[w].second;\n }\n \/\/ b. compute distribution\n for (int w = doc_lookup[d].first; w < doc_lookup[d].second; w++) {\n int voc_index = word_lookup[w].first;\n double prob = 1.0 * word_lookup[w].second \/ sumFreq;\n distributions[d].insert(pair<int, double> (voc_index, prob));\n }\n }\n \/\/ STEP TWO: compute weight of word within one document\n esmat_zeros(dist_mat);\n for (int j = 0; j < D; j ++) {\n for (int d = 0; d < D; d ++) {\n for (int w = doc_lookup[d].first; w < doc_lookup[d].second; w++) {\n int voc_index = word_lookup[w].first;\n int count_w_d1 = word_lookup[w].second; \n double prob_w_d2;\n double dist;\n map<int, double>::const_iterator iter;\n iter = distributions[j].find(voc_index);\n if (iter == distributions[j].end()) {\n prob_w_d2 = 0.0;\n dist = INF;\n } else {\n prob_w_d2 = iter->second;\n \/\/ dist(w, d2) = - count_w_d1 * log( prob_d2(w) )\n dist = - count_w_d1 * log(prob_w_d2);\n }\n int esmat_index = w + N * j;\n#ifdef DIST_MAT_DUMP\n cout << \"index: \" << esmat_index << \", dist: \" << dist << \", \";\n cout << \"count_w_d1: \" << count_w_d1 << \", prob_w_d2: \" << prob_w_d2 << endl;\n#endif\n dist_mat->val.push_back(make_pair(esmat_index, dist));\n }\n }\n }\n}\nvoid output_objective (vector<int> z, vector< vector<int> > v, double** dist_mat, Lookups* tables) {\n int N = tables->nWords;\n double obj = 0.0; \n fstream obj_out(\"opt_objective\");\n for (int d = 0; d < D; d ++) {\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i++) {\n int g = v[d][z[i]];\n double dist = dist_mat[i][g];\n obj += dist;\n }\n }\n obj_out << \"Main: \" << obj << endl;\n obj_out << \"Global: \" << global << endl;\n obj_out << \"Local: \" << local << endl;\n obj_out.close();\n}\nvoid output_medoids (vector<int> global_medoids, Lookups* tables) {\n int N = tables->nWords;\n int local_medoids = 0;\n fstream medoids_out(\"opt_medoids\");\n int nGlobalMedoids = global_medoids.size();\n for (int i = 0; i < nGlobalMedoids; i ++) {\n cout << \"Medoids[\" << i << \"]\" << global_medoids[i] << endl;\n }\n medoids_out.close();\n}\nvoid output_assignment (vector<int> z, vector<vector<int> > v, Lookups* tables) {\n int D = tables->nDocs;\n fstream asgn_out(\"opt_assignments\");\n for (int d = 0; d < D; d ++) {\n asgn_out << \"d = \" << d << endl;\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i++) {\n asgn_out << \"id=\" << i+1 << \", \" << v[d][z[i]] << \"(1)\" << endl;\n }\n }\n asgn_out.close();\n}\nvoid hdp_medoids (Esmat* dist_mat, vector<double> LAMBDAs, Lookups* tables) {\n \/\/ SET MODEL-RELEVANT PARAMETERS \n assert (LAMBDAs.size() == 2);\n double lambda_global = LAMBDAs[0];\n double lambda_local = LAMBDAs[1];\n double ALPHA = 1.0;\n double RHO = 1.0;\n int N = tables->nWords;\n int D = tables->nDocs;\n vector< pair<int,int> > doc_lookup = *(tables->doc_lookup);\n vector< pair<int,int> > word_lookup = *(tables->word_lookup); \n\n \/* A. DECLARE AND INITIALIZE INVOLVED VARIABLES AND MATRICES *\/\n vector<int> global_medoids (1,0);\n \/\/ vector< vector<int> > local_medoids (D,vector<int>(1,0));\n vector<int> z (N, 0);\n vector< vector<int> > v (D,vector<int>(1,0));\n \/\/ 1) randomize initial global cluster medoid \n global_medoids[0] = random() % D;\n \/\/ 2) randomize initial local cluster medoids for each document j\n ;\n \/\/ 3) initialize local cluster indicator z_ij = 1 for all j = 1\n for (int d = 0; d < D; d ++) {\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i++) {\n z[i] = 0;\n }\n }\n \/\/ 4) initialize global cluster association v_j1 = 1\n for (int d = 0; d < D; d ++) {\n v[d][0] = global_medoids[0];\n }\n \/* B. Repetition until Convergence *\/\n int iter = 0;\n int MAX_ITER = 1000;\n while (iter < MAX_ITER) {\n for (int d = 0; d < D; d++) {\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i ++) {\n \/\/ 1) preprocess distance\n double[] processed_dist_mat = new double [D];\n for (int examplar = 0; examplar < D; examplar ++) {\n int esmat_index = i + examplar * N;\n int value = dist_mat[i][examplar];\n processed_dist_mat[examplar] = value;\n }\n set<int> temp;\n int nGlobalMedoids= global_medoids.size();\n for (int g = 0; g < nGlobalMedoids; g++) \n temp.insert(global_medoids[g]);\n \/\/ int nLocalMedoids = local_medoids[d].size();\n int nLocalMedoids = v[d].size();\n for (int l = 0; l < nLocalMedoids; l++) \n \/\/ temp.erase(local_medoids[d][l]);\n temp.erase(v[d][l]);\n for (set<int>::iterator it=myset.begin();it!=myset.end();++it) \n processed_dist_mat[*it] += lambda_local;\n \/\/ 2) if .., global and local augmentation\n \/\/ if min_p d_ijp > \\lambda_l + \\lambda_g\n int min_index = -1;\n double min_value = INF; \n for (int index = 0; index < D; index ++) {\n if (processed_dist_mat[index] < min_value) {\n min_index = index;\n min_value = processed_dist_mat[index];\n }\n }\n if (min_value > lambda_local+lambda_global) {\n global_medoids.push_back(min_index);\n v[d].push_back(min_index);\n z[i] = nLocalMedoids;\n nLocalMedoids ++;\n }\n \/\/ 3) otherwise, local assignment or local augmentation\n else {\n bool is_c_exist = false;\n nLocalMedoids = v[d].size();\n for (int l = 0; l < nLocalMedoids; l ++) {\n if (v[d][l] == min_index) {\n z[i] = l;\n is_c_exist = true;\n break;\n }\n }\n if (!is_c_exist) { \/\/ local augmentation\n v[d].push_back(min_index);\n z[i] = nLocalMedoids;\n nLocalMedoids ++;\n }\n }\n delete[] processed_dist_mat;\n }\n }\n \/\/ 4) re-elect medoids for all local clusters\n for (int d = 0; d < D; d++) {\n int nLocalMedoids = v[d].size();\n for (int l = 0; l < nLocalMedoids; l++) {\n vector<int> words;\n \/\/ set<int> examplars;\n \/\/ examplars.insert(d);\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i++) {\n if (z[i] == l) {\n words.push_back(i);\n \/\/ examplars.insert(z[i]);\n }\n }\n int nDocWords = words.size();\n double ** temp_dist_mat = mat_init(nDocWords, D);\n for (int w = 0; w < nDocWords; w++) \n for (int td = 0; td < D; td++) \n temp_dist_mat[w][td] = dist_mat[words[w]][td];\n double * sum_temp_dist_col = new double [D];\n mat_sum_col (temp_dist_mat, sum_temp_dist_col, nDocWords, D);\n int min_index = -1; \n double min_value = INF; \/\/ min sum mu_jc\n for (int td = 0; td < D; td++) {\n if (sum_temp_dist_col[td] < min_value) {\n min_index = td;\n min_value = sum_temp_dist_col[td];\n }\n }\n v[d][l] = min_index; \/\/ update the better medoid\n delete[] sum_temp_dist_col;\n mat_free (temp_dist_mat, nDocWords, D);\n \/*\n \/\/ 5) if .., global augmentation\n \/\/ if min_p d_jcp > \\lambda_g + ... \n if (min_d_jcp > lambda_global+) {\n global_medoids.push_back(new_g);\n local_medoids[][] = new_g;\n }\n \/\/ 6) otherwise, update global association\n else {\n local_medoids[][] = new_g;\n }\n *\/\n }\n }\n\n \/\/ 7) re-elect medoids for global cluster\n int nGlobalMedoids = global_medoids.size();\n for (int g = 0; g < nGlobalMedoids; g++) {\n p = global_medoids[g];\n vector<int> words;\n set<int> examplar_set;\n for (int d = 0; d < D; d++) {\n for (int i = doc_lookup[d].first; i < doc_lookup[d].second; i ++) {\n if (v[z[i]] == p) {\n words.push_back(i);\n examplar_set.insert(d);\n }\n }\n }\n vector<int> examplars;\n for (set<int>::iterator it=myset.begin();it!=myset.end();++it) \n examplars.push_back(*it);\n }\n int R = words.size(); \n int C = examplars.size();\n double** candidate_dist_mat = mat_init (R,C);\n for (int r = 0; r < R; r ++) {\n for (int c = 0; c < C; c ++) {\n candidate_dist_mat[r][c] = dist_mat[words[r]][examplars[c]];\n }\n }\n double* min_d_rc = new double [C];\n mat_sum_col (candidate_dist_mat, min_d_rc, R,C);\n int min_index;\n double min_value = INF;\n for (int m = 0; m < C; m ++) {\n if (min_d_rc[m] < min_value) {\n min_index = m;\n min_value = min_d_rc[m];\n }\n }\n int new_p = examplars[m];\n global_medoids[g] = new_p; \/\/ update\n delete[] min_d_rc;\n mat_free (candidate_dist_mat, R,C);\n }\n }\n \/* Put converged solution to destinated W*\/\n}\n\n\/\/ entry main function\nint main (int argc, char ** argv) {\n\n \/\/ EXCEPTION control: illustrate the usage if get input of wrong format\n if (argc < 5) {\n cerr << \"Usage: \" << endl;\n cerr << \"\\thdp_medoids [voc_dataFile] [doc_dataFile] [lambda_global] [lambda_local]\" << endl;\n exit(-1);\n }\n\n \/\/ PARSE arguments\n string voc_file (argv[1]);\n string doc_file (argv[2]);\n vector<double> LAMBDAs (2, 0.0);\n LAMBDAs[0] = atof(argv[3]); \/\/ lambda_document\n LAMBDAs[1] = atof(argv[4]); \/\/ lambda_topic\n\n \/\/ preprocess the input dataset\n vector<string> voc_list;\n voc_list_read (voc_file, &voc_list);\n int nVocs = voc_list.size();\n\n \/\/ init lookup_tables\n vector< pair<int,int> > doc_lookup;\n vector< pair<int,int> > word_lookup;\n vector< vector<int> > voc_lookup (nVocs, vector<int>());\n Lookups lookup_tables;\n lookup_tables.doc_lookup = &doc_lookup;\n lookup_tables.word_lookup = &word_lookup;\n lookup_tables.voc_lookup = &voc_lookup;\n\n document_list_read (doc_file, &lookup_tables);\n lookup_tables.nDocs = lookup_tables.doc_lookup->size();\n lookup_tables.nWords = lookup_tables.word_lookup->size();\n lookup_tables.nVocs = nVocs;\n\n int seed = time(NULL);\n srand (seed);\n cerr << \"###########################################\" << endl;\n cerr << \"nVocs = \" << lookup_tables.nVocs << endl; \/\/ # vocabularies\n cerr << \"nDocs = \" << lookup_tables.nDocs << endl; \/\/ # documents\n cerr << \"nWords = \" << lookup_tables.nWords << endl; \/\/ # words\n cerr << \"lambda_global = \" << LAMBDAs[0] << endl;\n cerr << \"lambda_local = \" << LAMBDAs[1] << endl;\n cerr << \"TRIM_THRESHOLD = \" << TRIM_THRESHOLD << endl;\n cerr << \"seed = \" << seed << endl;\n cerr << \"###########################################\" << endl;\n\n \/\/ Run sparse convex clustering\n int N = lookup_tables.nWords;\n int D = lookup_tables.nDocs;\n Esmat* W = esmat_init (lookup_tables.nWords, lookup_tables.nDocs);\n Esmat* dist_mat = esmat_init (N, D);\n compute_dist_mat (dist_mat, &lookup_tables, N, D);\n\n ofstream dmat_out (\"dist_mat\");\n dmat_out << esmat_toInfo(dist_mat);\n dmat_out << esmat_toString(dist_mat);\n hdp_medoids (dist_mat, LAMBDAs, W, &lookup_tables);\n\n \/* Output objective *\/\n output_objective (z, v, dist_mat, &lookup_tables) {\n \/* Output cluster centroids *\/\n output_medoids (global_medoids, &lookup_tables) {\n \/* Output assignment *\/\n output_assignment (z, v, &lookup_tables) {\n\n \/* reallocation *\/\n esmat_free (W);\n esmat_free (dist_mat);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * edison_i2c.cpp\n *\n * Created on: 2016. 2. 26.\n * Author: hwang\n *\/\n\n#include \"edison_i2c.hpp\"\n#include <cossb.hpp>\n#include <mraa.hpp>\n#include <algorithm>\n\nUSE_COMPONENT_INTERFACE(edison_i2c)\n\nedison_i2c::edison_i2c()\n:cossb::interface::icomponent(COMPONENT(edison_i2c)){\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nedison_i2c::~edison_i2c() {\n\tif(_i2c)\n\t\tdelete _i2c;\n}\n\nbool edison_i2c::setup()\n{\n\tif(!_i2c)\n\t\t_i2c = new mraa::I2c(0);\n\n\t\/\/set address\n\tfor(auto value: get_profile()->get(profile::section::property, \"address\")) {\n\t\tint address = value.asInt(0);\n\t\taddress += ((address\/16)+1)*6;\n\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Set I2C Address : 0x{0:x}\", address));\n\n\t\tif(address) {\n\t\t\tif(_i2c->address(address)!=mraa::Result::SUCCESS)\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Set I2C Address : {}\", value.asString(\"\")));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/set mode\n\tfor(auto mode: get_profile()->get(profile::section::property, \"mode\")) {\n\t\tstring m = mode.asString(\"\");\n\t\tstd::transform(m.begin(), m.end(), m.begin(), ::tolower);\n\t\tif(m.compare(\"i2c_std\")==0)\t_i2c->frequency(mraa::I2cMode::I2C_STD);\t\/\/up to 100khz\n\t\telse if(m.compare(\"i2c_high\")==0)\t_i2c->frequency(mraa::I2cMode::I2C_HIGH); \/\/up to 3.4Mhz\n\t\telse if(m.compare(\"i2c_fast\")==0)\t_i2c->frequency(mraa::I2cMode::I2C_FAST);\/\/up to 400khz\n\t}\n\treturn true;\n}\n\nbool edison_i2c::run()\n{\n\treturn true;\n}\n\nbool edison_i2c::stop()\n{\n\treturn true;\n}\n\nvoid edison_i2c::request(cossb::base::message* const msg)\n{\n\tif(!_i2c) {\n\t\tcossb_log->log(log::loglevel::ERROR, \"No I2C Device\");\n\t\treturn;\n\t}\n\n\tswitch(msg->get_frame()->type) {\n\tcase cossb::base::msg_type::REQUEST: {\n\t\tif(!msg->get_frame()->topic.compare(\"service\/i2c\/write\")) {\n\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Received message (I2C) : {}\", msg->show().c_str()));\n\t\t}\n\t}\n\t\tbreak;\n\tcase cossb::base::msg_type::DATA: break;\n\tdefault:\n\t\tcossb_log->log(log::loglevel::INFO, \"Received message has unsupported type.\");\n\t}\n\n}\n<commit_msg>update for edison i2c component write<commit_after>\/*\n * edison_i2c.cpp\n *\n * Created on: 2016. 2. 26.\n * Author: hwang\n *\/\n\n#include \"edison_i2c.hpp\"\n#include <cossb.hpp>\n#include <mraa.hpp>\n#include <algorithm>\n\nUSE_COMPONENT_INTERFACE(edison_i2c)\n\nedison_i2c::edison_i2c()\n:cossb::interface::icomponent(COMPONENT(edison_i2c)){\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nedison_i2c::~edison_i2c() {\n\tif(_i2c)\n\t\tdelete _i2c;\n}\n\nbool edison_i2c::setup()\n{\n\tif(!_i2c)\n\t\t_i2c = new mraa::I2c(0);\n\n\t\/\/set address\n\tfor(auto value: get_profile()->get(profile::section::property, \"address\")) {\n\t\tint address = value.asInt(0);\n\t\taddress += ((address\/16)+1)*6;\n\n\t\tif(address) {\n\t\t\tif(_i2c->address(address)==mraa::Result::SUCCESS) {\n\t\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Set I2C Address : 0x{0:x}\", address));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Cannot Set I2C Address : 0x{0:x}\", address));\n\t\t}\n\t}\n\n\t\/\/set mode\n\tfor(auto mode: get_profile()->get(profile::section::property, \"mode\")) {\n\t\tstring m = mode.asString(\"\");\n\t\tstd::transform(m.begin(), m.end(), m.begin(), ::tolower);\n\t\tif(m.compare(\"i2c_std\")==0)\t_i2c->frequency(mraa::I2cMode::I2C_STD);\t\/\/up to 100khz\n\t\telse if(m.compare(\"i2c_high\")==0)\t_i2c->frequency(mraa::I2cMode::I2C_HIGH); \/\/up to 3.4Mhz\n\t\telse if(m.compare(\"i2c_fast\")==0)\t_i2c->frequency(mraa::I2cMode::I2C_FAST);\/\/up to 400khz\n\t}\n\treturn true;\n}\n\nbool edison_i2c::run()\n{\n\treturn true;\n}\n\nbool edison_i2c::stop()\n{\n\treturn true;\n}\n\nvoid edison_i2c::request(cossb::base::message* const msg)\n{\n\tif(!_i2c) {\n\t\tcossb_log->log(log::loglevel::ERROR, \"No I2C Device\");\n\t\treturn;\n\t}\n\n\tswitch(msg->get_frame()->type) {\n\tcase cossb::base::msg_type::REQUEST: {\n\t\tif(!msg->get_frame()->topic.compare(\"service\/i2c\/write\")) {\n\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Received message (I2C) : {}\", msg->show().c_str()));\n\t\t}\n\t}\n\t\tbreak;\n\tcase cossb::base::msg_type::DATA: break;\n\tdefault:\n\t\tcossb_log->log(log::loglevel::INFO, \"Received message has unsupported type.\");\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"antsUtilities.h\"\n#include <algorithm>\n\n#include <stdio.h>\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkResampleImageFilter.h\"\n\n#include \"itkConstantBoundaryCondition.h\"\n#include \"itkIdentityTransform.h\"\n#include \"itkBSplineInterpolateImageFunction.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkGaussianInterpolateImageFunction.h\"\n#include \"itkNearestNeighborInterpolateImageFunction.h\"\n#include \"itkWindowedSincInterpolateImageFunction.h\"\n#include \"ReadWriteData.h\"\n#include <string>\n#include <vector>\n\nnamespace ants\n{\n\ntemplate <unsigned int ImageDimension>\nint ResampleImage( int argc, char *argv[] )\n{\n typedef double RealType;\n typedef double PixelType;\n typedef itk::Image<PixelType, ImageDimension> ImageType;\n\n typename ImageType::Pointer image = ITK_NULLPTR;\n ReadImage<ImageType>( image, argv[2] );\n\n typedef itk::IdentityTransform<RealType, ImageDimension> TransformType;\n typename TransformType::Pointer transform = TransformType::New();\n transform->SetIdentity();\n\n typedef itk::LinearInterpolateImageFunction<ImageType, RealType>\n LinearInterpolatorType;\n typename LinearInterpolatorType::Pointer interpolator\n = LinearInterpolatorType::New();\n interpolator->SetInputImage( image );\n\n typedef itk::NearestNeighborInterpolateImageFunction<ImageType, RealType>\n NearestNeighborInterpolatorType;\n typename NearestNeighborInterpolatorType::Pointer nn_interpolator\n = NearestNeighborInterpolatorType::New();\n nn_interpolator->SetInputImage( image );\n\n typedef itk::BSplineInterpolateImageFunction<ImageType, RealType>\n BSplineInterpolatorType;\n typename BSplineInterpolatorType::Pointer bs_interpolator\n = BSplineInterpolatorType::New();\n bs_interpolator->SetInputImage( image );\n\n typedef itk::GaussianInterpolateImageFunction<ImageType, RealType>\n GaussianInterpolatorType;\n typename GaussianInterpolatorType::Pointer g_interpolator\n = GaussianInterpolatorType::New();\n g_interpolator->SetInputImage( image );\n\n typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3> HammingInterpolatorType;\n typename HammingInterpolatorType::Pointer sh_interpolator = HammingInterpolatorType::New();\n sh_interpolator->SetInputImage( image );\n\n typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3,\n itk::Function::CosineWindowFunction<3> > Sinc1InterpolatorType;\n typename Sinc1InterpolatorType::Pointer sc_interpolator = Sinc1InterpolatorType::New();\n sc_interpolator->SetInputImage( image );\n\n typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3,\n itk::Function::WelchWindowFunction<3> > Sinc2InterpolatorType;\n typename Sinc2InterpolatorType::Pointer sw_interpolator = Sinc2InterpolatorType::New();\n sw_interpolator->SetInputImage( image );\n\n typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3,\n itk::Function::LanczosWindowFunction<3> > Sinc3InterpolatorType;\n typename Sinc3InterpolatorType::Pointer sl_interpolator = Sinc3InterpolatorType::New();\n sl_interpolator->SetInputImage( image );\n\n typename Sinc3InterpolatorType::Pointer sb_interpolator = Sinc3InterpolatorType::New();\n sb_interpolator->SetInputImage( image );\n\n typedef itk::ResampleImageFilter<ImageType, ImageType, RealType> ResamplerType;\n typename ResamplerType::Pointer resampler = ResamplerType::New();\n typename ResamplerType::SpacingType spacing;\n typename ResamplerType::SizeType size;\n typename ImageType::IndexType oldStartIndex = image->GetLargestPossibleRegion().GetIndex();\ntypename ImageType::IndexType newStartIndex;\n newStartIndex.Fill(0); \/\/ should be \"same\" as original start index but in new physical space\n\n std::vector<RealType> sp = ConvertVector<RealType>( std::string( argv[4] ) );\n\n if( argc <= 5 || atoi( argv[5] ) == 0 )\n {\n if( sp.size() == 1 )\n {\n spacing.Fill( sp[0] );\n }\n else if( sp.size() == ImageDimension )\n {\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n spacing[d] = sp[d];\n }\n }\n else\n {\n std::cout << \"Invalid spacing.\" << std::endl;\n }\n for( unsigned int i = 0; i < ImageDimension; i++ )\n {\n RealType spacing_old = image->GetSpacing()[i];\n RealType size_old = image->GetLargestPossibleRegion().GetSize()[i];\n size[i] = static_cast<int>( ( spacing_old * size_old ) \/ spacing[i] + 0.5 );\n RealType oldstart = static_cast<float>( oldStartIndex[i] );\n newStartIndex[i] = static_cast<int>( ( spacing_old * oldstart ) \/ spacing[i] + 0.5 );\n }\n }\n else\n {\n if( sp.size() == 1 )\n {\n size.Fill( static_cast<unsigned int>( sp[0] ) );\n }\n else if( sp.size() == ImageDimension )\n {\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n size[d] = static_cast<unsigned int>( sp[d] );\n }\n }\n else\n {\n std::cout << \"Invalid size.\" << std::endl;\n }\n for( unsigned int i = 0; i < ImageDimension; i++ )\n {\n RealType spacing_old = image->GetSpacing()[i];\n RealType size_old = image->GetLargestPossibleRegion().GetSize()[i];\n float ratio = static_cast<float>( size_old - 1.0 )\n \/ static_cast<float>( size[i] - 1.0 );\n spacing[i] = spacing_old * ratio;\n RealType oldstart = static_cast<float>( oldStartIndex[i] );\n newStartIndex[i] = static_cast<int>( oldstart * ratio + 0.5 );\n }\n }\n\n char arg7 = '\\0';\n if( argc > 7 )\n {\n arg7 = *argv[7];\n }\n\n resampler->SetTransform( transform );\n resampler->SetInterpolator( interpolator );\n if( argc > 6 && atoi( argv[6] ) )\n {\n switch( atoi( argv[6] ) )\n {\n case 0: default:\n {\n resampler->SetInterpolator( interpolator );\n }\n break;\n case 1:\n {\n resampler->SetInterpolator( nn_interpolator );\n }\n break;\n case 2:\n {\n double sigma[ImageDimension];\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n sigma[d] = image->GetSpacing()[d];\n }\n double alpha = 1.0;\n\n if( argc > 7 )\n {\n std::vector<RealType> sg = ConvertVector<RealType>( std::string( argv[7] ) );\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n sigma[d] = sg[d];\n }\n }\n if( argc > 8 )\n {\n alpha = static_cast<double>( atof( argv[8] ) );\n }\n g_interpolator->SetParameters( sigma, alpha );\n\n resampler->SetInterpolator( g_interpolator );\n }\n break;\n case 3:\n {\n switch( arg7 )\n {\n case 'h': default:\n {\n resampler->SetInterpolator( sh_interpolator );\n }\n break;\n case 'c':\n {\n resampler->SetInterpolator( sc_interpolator );\n }\n break;\n case 'l':\n {\n resampler->SetInterpolator( sl_interpolator );\n }\n break;\n case 'w':\n {\n resampler->SetInterpolator( sw_interpolator );\n }\n break;\n case 'b':\n {\n resampler->SetInterpolator( sb_interpolator );\n }\n break;\n }\n }\n case 4:\n {\n if( argc > 7 && atoi( argv[7] ) >= 0 && atoi( argv[7] ) <= 5 )\n {\n bs_interpolator->SetSplineOrder( atoi( argv[7] ) );\n }\n else\n {\n bs_interpolator->SetSplineOrder( 3 );\n }\n resampler->SetInterpolator( bs_interpolator );\n }\n break;\n }\n }\n resampler->SetInput( image );\n resampler->SetSize( size );\n resampler->SetOutputOrigin( image->GetOrigin() );\n resampler->SetOutputDirection( image->GetDirection() );\n resampler->SetOutputSpacing( spacing );\n\/\/ resampler->SetOutputStartIndex( newStartIndex );\n resampler->SetDefaultPixelValue( 0 );\n resampler->Update();\n typename ImageType::Pointer outimage = resampler->GetOutput();\n\/\/ typename ImageType::RegionType region = outimage->GetLargestPossibleRegion();\n\/\/ region.SetIndex( newStartIndex );\n\/\/ outimage->SetLargestPossibleRegion( region );\n WriteImage<ImageType>( outimage , argv[3] );\n return EXIT_SUCCESS;\n}\n\n\/\/ entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to\n\/\/ 'main()'\nint ResampleImage( std::vector<std::string> args, std::ostream* \/*out_stream = NULL *\/ )\n{\n \/\/ put the arguments coming in as 'args' into standard (argc,argv) format;\n \/\/ 'args' doesn't have the command name as first, argument, so add it manually;\n \/\/ 'args' may have adjacent arguments concatenated into one argument,\n \/\/ which the parser should handle\n args.insert( args.begin(), \"ResampleImage\" );\n\n int argc = args.size();\n char* * argv = new char *[args.size() + 1];\n for( unsigned int i = 0; i < args.size(); ++i )\n {\n \/\/ allocate space for the string plus a null character\n argv[i] = new char[args[i].length() + 1];\n std::strncpy( argv[i], args[i].c_str(), args[i].length() );\n \/\/ place the null character in the end\n argv[i][args[i].length()] = '\\0';\n }\n argv[argc] = ITK_NULLPTR;\n \/\/ class to automatically cleanup argv upon destruction\n class Cleanup_argv\n {\npublic:\n Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )\n {\n }\n\n ~Cleanup_argv()\n {\n for( unsigned int i = 0; i < argc_plus_one; ++i )\n {\n delete[] argv[i];\n }\n delete[] argv;\n }\n\nprivate:\n char* * argv;\n unsigned int argc_plus_one;\n };\n Cleanup_argv cleanup_argv( argv, argc + 1 );\n\n \/\/ antscout->set_stream( out_stream );\n\n if( argc < 5 )\n {\n std::cout << \"Usage: \" << argv[0] << \" imageDimension inputImage \"\n << \"outputImage MxNxO [size=1,spacing=0] [interpolate type]\" << std::endl;\n std::cout << \" Interpolation type: \" << std::endl;\n std::cout << \" 0. linear (default)\" << std::endl;\n std::cout << \" 1. nn \" << std::endl;\n std::cout << \" 2. gaussian [sigma=imageSpacing] [alpha=1.0]\" << std::endl;\n std::cout << \" 3. windowedSinc [type = 'c'osine, 'w'elch, 'b'lackman, 'l'anczos, 'h'amming]\" << std::endl;\n std::cout << \" 4. B-Spline [order=3]\" << std::endl;\n if( argc >= 2 &&\n ( std::string( argv[1] ) == std::string(\"--help\") || std::string( argv[1] ) == std::string(\"-h\") ) )\n {\n return EXIT_SUCCESS;\n }\n return EXIT_FAILURE;\n }\n\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n return ResampleImage<2>( argc, argv );\n }\n break;\n case 3:\n {\n return ResampleImage<3>( argc, argv );\n }\n break;\n case 4:\n {\n return ResampleImage<4>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n} \/\/ namespace ants\n<commit_msg>ENH: add pixeltype option to resampleImage<commit_after>\n#include \"antsUtilities.h\"\n#include <algorithm>\n\n#include <stdio.h>\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkResampleImageFilter.h\"\n\n#include \"itkConstantBoundaryCondition.h\"\n#include \"itkIdentityTransform.h\"\n#include \"itkBSplineInterpolateImageFunction.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkGaussianInterpolateImageFunction.h\"\n#include \"itkNearestNeighborInterpolateImageFunction.h\"\n#include \"itkWindowedSincInterpolateImageFunction.h\"\n#include \"ReadWriteData.h\"\n#include <string>\n#include <vector>\n\nnamespace ants\n{\n\ntemplate <unsigned int ImageDimension, class PixelType>\nint ResampleImage( int argc, char *argv[] )\n{\n typedef double RealType;\n typedef itk::Image<PixelType, ImageDimension> ImageType;\n\n typename ImageType::Pointer image = ITK_NULLPTR;\n ReadImage<ImageType>( image, argv[2] );\n\n typedef itk::IdentityTransform<RealType, ImageDimension> TransformType;\n typename TransformType::Pointer transform = TransformType::New();\n transform->SetIdentity();\n\n typedef itk::LinearInterpolateImageFunction<ImageType, RealType>\n LinearInterpolatorType;\n typename LinearInterpolatorType::Pointer interpolator\n = LinearInterpolatorType::New();\n interpolator->SetInputImage( image );\n\n typedef itk::NearestNeighborInterpolateImageFunction<ImageType, RealType>\n NearestNeighborInterpolatorType;\n typename NearestNeighborInterpolatorType::Pointer nn_interpolator\n = NearestNeighborInterpolatorType::New();\n nn_interpolator->SetInputImage( image );\n\n typedef itk::BSplineInterpolateImageFunction<ImageType, RealType>\n BSplineInterpolatorType;\n typename BSplineInterpolatorType::Pointer bs_interpolator\n = BSplineInterpolatorType::New();\n bs_interpolator->SetInputImage( image );\n\n typedef itk::GaussianInterpolateImageFunction<ImageType, RealType>\n GaussianInterpolatorType;\n typename GaussianInterpolatorType::Pointer g_interpolator\n = GaussianInterpolatorType::New();\n g_interpolator->SetInputImage( image );\n\n typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3> HammingInterpolatorType;\n typename HammingInterpolatorType::Pointer sh_interpolator = HammingInterpolatorType::New();\n sh_interpolator->SetInputImage( image );\n\n typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3,\n itk::Function::CosineWindowFunction<3> > Sinc1InterpolatorType;\n typename Sinc1InterpolatorType::Pointer sc_interpolator = Sinc1InterpolatorType::New();\n sc_interpolator->SetInputImage( image );\n\n typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3,\n itk::Function::WelchWindowFunction<3> > Sinc2InterpolatorType;\n typename Sinc2InterpolatorType::Pointer sw_interpolator = Sinc2InterpolatorType::New();\n sw_interpolator->SetInputImage( image );\n\n typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3,\n itk::Function::LanczosWindowFunction<3> > Sinc3InterpolatorType;\n typename Sinc3InterpolatorType::Pointer sl_interpolator = Sinc3InterpolatorType::New();\n sl_interpolator->SetInputImage( image );\n\n typename Sinc3InterpolatorType::Pointer sb_interpolator = Sinc3InterpolatorType::New();\n sb_interpolator->SetInputImage( image );\n\n typedef itk::ResampleImageFilter<ImageType, ImageType, RealType> ResamplerType;\n typename ResamplerType::Pointer resampler = ResamplerType::New();\n typename ResamplerType::SpacingType spacing;\n typename ResamplerType::SizeType size;\n typename ImageType::IndexType oldStartIndex = image->GetLargestPossibleRegion().GetIndex();\ntypename ImageType::IndexType newStartIndex;\n newStartIndex.Fill(0); \/\/ should be \"same\" as original start index but in new physical space\n\n std::vector<RealType> sp = ConvertVector<RealType>( std::string( argv[4] ) );\n\n if( argc <= 5 || atoi( argv[5] ) == 0 )\n {\n if( sp.size() == 1 )\n {\n spacing.Fill( sp[0] );\n }\n else if( sp.size() == ImageDimension )\n {\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n spacing[d] = sp[d];\n }\n }\n else\n {\n std::cout << \"Invalid spacing.\" << std::endl;\n }\n for( unsigned int i = 0; i < ImageDimension; i++ )\n {\n RealType spacing_old = image->GetSpacing()[i];\n RealType size_old = image->GetLargestPossibleRegion().GetSize()[i];\n size[i] = static_cast<int>( ( spacing_old * size_old ) \/ spacing[i] + 0.5 );\n RealType oldstart = static_cast<float>( oldStartIndex[i] );\n newStartIndex[i] = static_cast<int>( ( spacing_old * oldstart ) \/ spacing[i] + 0.5 );\n }\n }\n else\n {\n if( sp.size() == 1 )\n {\n size.Fill( static_cast<unsigned int>( sp[0] ) );\n }\n else if( sp.size() == ImageDimension )\n {\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n size[d] = static_cast<unsigned int>( sp[d] );\n }\n }\n else\n {\n std::cout << \"Invalid size.\" << std::endl;\n }\n for( unsigned int i = 0; i < ImageDimension; i++ )\n {\n RealType spacing_old = image->GetSpacing()[i];\n RealType size_old = image->GetLargestPossibleRegion().GetSize()[i];\n float ratio = static_cast<float>( size_old - 1.0 )\n \/ static_cast<float>( size[i] - 1.0 );\n spacing[i] = spacing_old * ratio;\n RealType oldstart = static_cast<float>( oldStartIndex[i] );\n newStartIndex[i] = static_cast<int>( oldstart * ratio + 0.5 );\n }\n }\n\n char arg7 = '\\0';\n if( argc > 7 )\n {\n arg7 = *argv[7];\n }\n\n resampler->SetTransform( transform );\n resampler->SetInterpolator( interpolator );\n if( argc > 6 && atoi( argv[6] ) )\n {\n switch( atoi( argv[6] ) )\n {\n case 0: default:\n {\n resampler->SetInterpolator( interpolator );\n }\n break;\n case 1:\n {\n resampler->SetInterpolator( nn_interpolator );\n }\n break;\n case 2:\n {\n double sigma[ImageDimension];\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n sigma[d] = image->GetSpacing()[d];\n }\n double alpha = 1.0;\n\n if( argc > 7 )\n {\n std::vector<RealType> sg = ConvertVector<RealType>( std::string( argv[7] ) );\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n sigma[d] = sg[d];\n }\n }\n if( argc > 8 )\n {\n alpha = static_cast<double>( atof( argv[8] ) );\n }\n g_interpolator->SetParameters( sigma, alpha );\n\n resampler->SetInterpolator( g_interpolator );\n }\n break;\n case 3:\n {\n switch( arg7 )\n {\n case 'h': default:\n {\n resampler->SetInterpolator( sh_interpolator );\n }\n break;\n case 'c':\n {\n resampler->SetInterpolator( sc_interpolator );\n }\n break;\n case 'l':\n {\n resampler->SetInterpolator( sl_interpolator );\n }\n break;\n case 'w':\n {\n resampler->SetInterpolator( sw_interpolator );\n }\n break;\n case 'b':\n {\n resampler->SetInterpolator( sb_interpolator );\n }\n break;\n }\n }\n case 4:\n {\n if( argc > 7 && atoi( argv[7] ) >= 0 && atoi( argv[7] ) <= 5 )\n {\n bs_interpolator->SetSplineOrder( atoi( argv[7] ) );\n }\n else\n {\n bs_interpolator->SetSplineOrder( 3 );\n }\n resampler->SetInterpolator( bs_interpolator );\n }\n break;\n }\n }\n resampler->SetInput( image );\n resampler->SetSize( size );\n resampler->SetOutputOrigin( image->GetOrigin() );\n resampler->SetOutputDirection( image->GetDirection() );\n resampler->SetOutputSpacing( spacing );\n\/\/ resampler->SetOutputStartIndex( newStartIndex );\n resampler->SetDefaultPixelValue( 0 );\n resampler->Update();\n typename ImageType::Pointer outimage = resampler->GetOutput();\n\/\/ typename ImageType::RegionType region = outimage->GetLargestPossibleRegion();\n\/\/ region.SetIndex( newStartIndex );\n\/\/ outimage->SetLargestPossibleRegion( region );\n WriteImage<ImageType>( outimage , argv[3] );\n return EXIT_SUCCESS;\n}\n\n\/\/ entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to\n\/\/ 'main()'\nint ResampleImage( std::vector<std::string> args, std::ostream* \/*out_stream = NULL *\/ )\n{\n \/\/ put the arguments coming in as 'args' into standard (argc,argv) format;\n \/\/ 'args' doesn't have the command name as first, argument, so add it manually;\n \/\/ 'args' may have adjacent arguments concatenated into one argument,\n \/\/ which the parser should handle\n args.insert( args.begin(), \"ResampleImage\" );\n\n int argc = args.size();\n char* * argv = new char *[args.size() + 1];\n for( unsigned int i = 0; i < args.size(); ++i )\n {\n \/\/ allocate space for the string plus a null character\n argv[i] = new char[args[i].length() + 1];\n std::strncpy( argv[i], args[i].c_str(), args[i].length() );\n \/\/ place the null character in the end\n argv[i][args[i].length()] = '\\0';\n }\n argv[argc] = ITK_NULLPTR;\n \/\/ class to automatically cleanup argv upon destruction\n class Cleanup_argv\n {\npublic:\n Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )\n {\n }\n\n ~Cleanup_argv()\n {\n for( unsigned int i = 0; i < argc_plus_one; ++i )\n {\n delete[] argv[i];\n }\n delete[] argv;\n }\n\nprivate:\n char* * argv;\n unsigned int argc_plus_one;\n };\n Cleanup_argv cleanup_argv( argv, argc + 1 );\n\n \/\/ antscout->set_stream( out_stream );\n\n if( argc < 5 )\n {\n std::cout << \"Usage: \" << argv[0] << \" imageDimension inputImage \"\n << \"outputImage MxNxO [size=1,spacing=0] [interpolate type] [pixeltype]\" << std::endl;\n std::cout << \" Interpolation type: \" << std::endl;\n std::cout << \" 0. linear (default)\" << std::endl;\n std::cout << \" 1. nn \" << std::endl;\n std::cout << \" 2. gaussian [sigma=imageSpacing] [alpha=1.0]\" << std::endl;\n std::cout << \" 3. windowedSinc [type = 'c'osine, 'w'elch, 'b'lackman, 'l'anczos, 'h'amming]\" << std::endl;\n std::cout << \" 4. B-Spline [order=3]\" << std::endl;\n std::cout << \" pixeltype : TYPE \" << std::endl;\n std::cout << \" 0 : char \" << std::endl;\n std::cout << \" 1 : unsigned char \" << std::endl;\n std::cout << \" 2 : short \" << std::endl;\n std::cout << \" 3 : unsigned short \" << std::endl;\n std::cout << \" 4 : int \" << std::endl;\n std::cout << \" 5 : unsigned int \" << std::endl;\n std::cout << \" 6 : float (default) \" << std::endl;\n if( argc >= 2 &&\n ( std::string( argv[1] ) == std::string(\"--help\") || std::string( argv[1] ) == std::string(\"-h\") ) )\n {\n return EXIT_SUCCESS;\n }\n return EXIT_FAILURE;\n }\n\n unsigned int typeoption = 6;\n if( argc > 7 )\n {\n typeoption = atoi(argv[7]);\n }\n\n switch ( typeoption )\n {\n case 0:\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n return ResampleImage<2,char>( argc, argv );\n }\n break;\n case 3:\n {\n return ResampleImage<3,char>( argc, argv );\n }\n break;\n case 4:\n {\n return ResampleImage<4,char>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n break;\n case 1:\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n return ResampleImage<2,unsigned char>( argc, argv );\n }\n break;\n case 3:\n {\n return ResampleImage<3,unsigned char>( argc, argv );\n }\n break;\n case 4:\n {\n return ResampleImage<4,unsigned char>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n break;\n \/\/\n case 2:\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n return ResampleImage<2,short>( argc, argv );\n }\n break;\n case 3:\n {\n return ResampleImage<3,short>( argc, argv );\n }\n break;\n case 4:\n {\n return ResampleImage<4,short>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n case 3:\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n return ResampleImage<2,unsigned short>( argc, argv );\n }\n break;\n case 3:\n {\n return ResampleImage<3,unsigned short>( argc, argv );\n }\n break;\n case 4:\n {\n return ResampleImage<4,unsigned short>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n case 4:\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n return ResampleImage<2,int>( argc, argv );\n }\n break;\n case 3:\n {\n return ResampleImage<3,int>( argc, argv );\n }\n break;\n case 4:\n {\n return ResampleImage<4,int>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n case 5:\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n return ResampleImage<2,unsigned int>( argc, argv );\n }\n break;\n case 3:\n {\n return ResampleImage<3,unsigned int>( argc, argv );\n }\n break;\n case 4:\n {\n return ResampleImage<4,unsigned int>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n case 6:\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n return ResampleImage<2,float>( argc, argv );\n }\n break;\n case 3:\n {\n return ResampleImage<3,float>( argc, argv );\n }\n break;\n case 4:\n {\n return ResampleImage<4,float>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n default:\n std::cout << \"Unsupported pixel type\" << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n} \/\/ end of function\n} \/\/ namespace ants\n<|endoftext|>"} {"text":"<commit_before>#include <VolViz\/VolViz.h>\n\n#include <Eigen\/Core>\n#include <igl\/readOBJ.h>\n#include <igl\/readOFF.h>\n#include <igl\/readPLY.h>\n#include <igl\/readSTL.h>\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <thread>\n\nauto generateVolume();\n\nauto generateVolume() {\n using namespace VolViz;\n using namespace VolViz::literals;\n Size3 const size(256, 256, 128);\n auto const nVoxels = size(0) * size(1) * size(2);\n\n std::vector<Color> data;\n data.reserve(3 * nVoxels);\n Color c = Colors::Black();\n for (unsigned int z = 0; z < size(2); ++z) {\n c(2) = (static_cast<float>(z) \/ static_cast<float>(size(2) - 1));\n for (unsigned int y = 0; y < size(1); ++y) {\n c(1) = (static_cast<float>(y) \/ static_cast<float>(size(1) - 1));\n for (unsigned int x = 0; x < size(0); ++x) {\n c(0) = (static_cast<float>(x) \/ static_cast<float>(size(0) - 1));\n data.push_back(c);\n }\n }\n }\n\n VolumeDescriptor v;\n v.size = size;\n v.voxelSize = {{100_um, 100_um, 200_um}};\n v.type = VolumeType::ColorRGB;\n\n return std::make_pair(v, data);\n}\n\nint main(int argc, char **argv) {\n using namespace VolViz;\n using namespace VolViz::literals;\n using Eigen::Vector3d;\n using Vertices = Eigen::MatrixXd;\n using Triangles = Eigen::MatrixXi;\n\n if (argc != 2) {\n std::cerr << \"Usage: \" << argv[0] << \" meshFile\" << std::endl;\n return EXIT_FAILURE;\n }\n\n auto f = std::ifstream(argv[1]);\n auto const filename = std::string(argv[1]);\n auto const ext = filename.substr(filename.size() - 3, 3);\n std::cout << \"Loading mesh \" << argv[1] << \"... \" << std::flush;\n Vertices V;\n Triangles T;\n if (ext == \"off\")\n igl::readOFF(filename, V, T);\n else if (ext == \"ply\")\n igl::readPLY(filename, V, T);\n else if (ext == \"stl\") {\n Vertices N;\n igl::readSTL(filename, V, T, N);\n } else if (ext == \"obj\")\n igl::readOBJ(filename, V, T);\n else {\n std::cerr << std::endl << \"Unrecognized mesh format: \" << ext << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"done.\" << std::endl;\n std::cout << V.rows() << \" vertices, \" << T.rows() << \" triangles.\"\n << std::endl;\n\n Eigen::Vector3d const min = V.colwise().minCoeff();\n Eigen::Vector3d const max = V.colwise().maxCoeff();\n\n Length meshScale = 5_cm;\n\n std::cout << \"bbox: \" << min.transpose() << \" - \" << max.transpose()\n << std::endl;\n std::cout << \"bbox size: \"\n << ((max - min).transpose() * static_cast<double>(meshScale \/ 1_mm))\n << \" mm\" << std::endl;\n\n \/\/ Eigen::MatrixXd V(3, 3);\n \/\/ V << 0, 1, 0, -1, -1, 0, 1, -1, 0;\n \/\/ Eigen::MatrixXi T(1, 3);\n \/\/ T << 0, 1, 2;\n\n auto viewer = Visualizer{};\n\n \/\/ Add mesh\n MeshDescriptor mesh;\n mesh.vertices = V.cast<float>();\n mesh.indices = T.cast<std::uint32_t>();\n mesh.movable = true;\n mesh.scale = 50_mm;\n mesh.color = Colors::White();\n viewer.addGeometry(\"Mesh\", mesh);\n\n viewer.showGrid = true;\n\n Light light;\n light.ambientFactor = 1.0f;\n light.color = Colors::White();\n light.position = PositionH(1, 1, 1, 0);\n\n viewer.addLight(0, light);\n\n light.position = PositionH(2, 1, 1, 0);\n viewer.addLight(1, light);\n\n light.position = PositionH(1, 2, 1, 0);\n viewer.addLight(2, light);\n\n viewer.scale = 1_mm;\n\n AxisAlignedPlaneDescriptor plane;\n plane.axis = Axis::X;\n \/\/ plane.color = Colors::Green();\n plane.color = Colors::White();\n plane.intercept = 0_mm;\n\n viewer.addGeometry(\"X-Plane\", plane);\n\n plane.axis = Axis::Y;\n \/\/ plane.color = Colors::Blue();\n plane.color = Colors::White();\n plane.intercept = 0_mm;\n viewer.addGeometry(\"Y-Plane\", plane);\n\n plane.axis = Axis::Z;\n \/\/ plane.color = Colors::Red();\n plane.color = Colors::White();\n plane.intercept = 0_mm;\n viewer.addGeometry(\"Z-Plane\", plane);\n\n std::cout << \"Generating volume... \" << std::flush;\n auto const vol = generateVolume();\n std::cout << \"done.\" << std::endl;\n\n viewer.setVolume(vol.first, as_span(vol.second));\n\n viewer.enableMultithreading();\n std::thread viewerThread([&viewer]() {\n viewer.start();\n viewer.renderAtFPS(60);\n });\n\n using Clock = std::chrono::steady_clock;\n using namespace std::chrono_literals;\n auto constexpr updateIntervall = 1s \/ 30.f;\n int count{0};\n while (viewer) {\n auto const t0 = Clock::now();\n mesh.vertices *= count < 10 ? 1.01f : 0.99f;\n viewer.updateGeometry(\"Mesh\", mesh);\n if (++count > 20) count = 0;\n auto const timeLeft = -(Clock::now() - t0) + updateIntervall;\n if (timeLeft > 0s) std::this_thread::sleep_for(timeLeft);\n }\n\n viewerThread.join();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Let the viewer run on the main thread<commit_after>#include <VolViz\/VolViz.h>\n\n#include <Eigen\/Core>\n#include <igl\/readOBJ.h>\n#include <igl\/readOFF.h>\n#include <igl\/readPLY.h>\n#include <igl\/readSTL.h>\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <thread>\n\nauto generateVolume();\n\nauto generateVolume() {\n using namespace VolViz;\n using namespace VolViz::literals;\n Size3 const size(256, 256, 128);\n auto const nVoxels = size(0) * size(1) * size(2);\n\n std::vector<Color> data;\n data.reserve(3 * nVoxels);\n Color c = Colors::Black();\n for (unsigned int z = 0; z < size(2); ++z) {\n c(2) = (static_cast<float>(z) \/ static_cast<float>(size(2) - 1));\n for (unsigned int y = 0; y < size(1); ++y) {\n c(1) = (static_cast<float>(y) \/ static_cast<float>(size(1) - 1));\n for (unsigned int x = 0; x < size(0); ++x) {\n c(0) = (static_cast<float>(x) \/ static_cast<float>(size(0) - 1));\n data.push_back(c);\n }\n }\n }\n\n VolumeDescriptor v;\n v.size = size;\n v.voxelSize = {{100_um, 100_um, 200_um}};\n v.type = VolumeType::ColorRGB;\n\n return std::make_pair(v, data);\n}\n\nint main(int argc, char **argv) {\n using namespace VolViz;\n using namespace VolViz::literals;\n using Eigen::Vector3d;\n using Vertices = Eigen::MatrixXd;\n using Triangles = Eigen::MatrixXi;\n\n if (argc != 2) {\n std::cerr << \"Usage: \" << argv[0] << \" meshFile\" << std::endl;\n return EXIT_FAILURE;\n }\n\n auto f = std::ifstream(argv[1]);\n auto const filename = std::string(argv[1]);\n auto const ext = filename.substr(filename.size() - 3, 3);\n std::cout << \"Loading mesh \" << argv[1] << \"... \" << std::flush;\n Vertices V;\n Triangles T;\n if (ext == \"off\")\n igl::readOFF(filename, V, T);\n else if (ext == \"ply\")\n igl::readPLY(filename, V, T);\n else if (ext == \"stl\") {\n Vertices N;\n igl::readSTL(filename, V, T, N);\n } else if (ext == \"obj\")\n igl::readOBJ(filename, V, T);\n else {\n std::cerr << std::endl << \"Unrecognized mesh format: \" << ext << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"done.\" << std::endl;\n std::cout << V.rows() << \" vertices, \" << T.rows() << \" triangles.\"\n << std::endl;\n\n Eigen::Vector3d const min = V.colwise().minCoeff();\n Eigen::Vector3d const max = V.colwise().maxCoeff();\n\n Length meshScale = 5_cm;\n\n std::cout << \"bbox: \" << min.transpose() << \" - \" << max.transpose()\n << std::endl;\n std::cout << \"bbox size: \"\n << ((max - min).transpose() * static_cast<double>(meshScale \/ 1_mm))\n << \" mm\" << std::endl;\n\n \/\/ Eigen::MatrixXd V(3, 3);\n \/\/ V << 0, 1, 0, -1, -1, 0, 1, -1, 0;\n \/\/ Eigen::MatrixXi T(1, 3);\n \/\/ T << 0, 1, 2;\n\n auto viewer = Visualizer{};\n\n \/\/ Add mesh\n MeshDescriptor mesh;\n mesh.vertices = V.cast<float>();\n mesh.indices = T.cast<std::uint32_t>();\n mesh.movable = true;\n mesh.scale = 50_mm;\n mesh.color = Colors::White();\n viewer.addGeometry(\"Mesh\", mesh);\n\n viewer.showGrid = true;\n\n Light light;\n light.ambientFactor = 1.0f;\n light.color = Colors::White();\n light.position = PositionH(1, 1, 1, 0);\n\n viewer.addLight(0, light);\n\n light.position = PositionH(2, 1, 1, 0);\n viewer.addLight(1, light);\n\n light.position = PositionH(1, 2, 1, 0);\n viewer.addLight(2, light);\n\n viewer.scale = 1_mm;\n\n AxisAlignedPlaneDescriptor plane;\n plane.axis = Axis::X;\n \/\/ plane.color = Colors::Green();\n plane.color = Colors::White();\n plane.intercept = 0_mm;\n\n viewer.addGeometry(\"X-Plane\", plane);\n\n plane.axis = Axis::Y;\n \/\/ plane.color = Colors::Blue();\n plane.color = Colors::White();\n plane.intercept = 0_mm;\n viewer.addGeometry(\"Y-Plane\", plane);\n\n plane.axis = Axis::Z;\n \/\/ plane.color = Colors::Red();\n plane.color = Colors::White();\n plane.intercept = 0_mm;\n viewer.addGeometry(\"Z-Plane\", plane);\n\n std::cout << \"Generating volume... \" << std::flush;\n auto const vol = generateVolume();\n std::cout << \"done.\" << std::endl;\n\n viewer.setVolume(vol.first, as_span(vol.second));\n\n viewer.enableMultithreading();\n viewer.start();\n\n std::thread workerThread([&viewer, &mesh]() {\n using Clock = std::chrono::steady_clock;\n using namespace std::chrono_literals;\n auto constexpr updateIntervall = 1s \/ 30.f;\n int count{0};\n while (viewer) {\n auto const t0 = Clock::now();\n mesh.vertices *= count < 10 ? 1.01f : 0.99f;\n viewer.updateGeometry(\"Mesh\", mesh);\n if (++count > 20) count = 0;\n auto const timeLeft = -(Clock::now() - t0) + updateIntervall;\n if (timeLeft > 0s) std::this_thread::sleep_for(timeLeft);\n }\n });\n\n viewer.renderAtFPS(60);\n\n workerThread.join();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\/**\n * File : H.cpp\n * Author : Kazune Takahashi\n * Created : 2019\/12\/30 18:11:35\n * Powered by Visual Studio Code\n *\/\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n\/\/ ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- PrimeNums -----\n\nclass PrimeNums\n{\n static constexpr ll MAX_SIZE{1000010LL};\n ll N;\n vector<bool> isprime;\n vector<int> prime_nums;\n\npublic:\n PrimeNums(ll N = MAX_SIZE) : N{N}, isprime(N, true), prime_nums{}\n {\n isprime[0] = isprime[1] = false;\n for (auto i = 2; i < N; i++)\n {\n if (isprime[i])\n {\n prime_nums.push_back(i);\n for (auto j = 2 * i; j < N; j += i)\n {\n isprime[j] = false;\n }\n }\n }\n }\n\n bool is_prime(long long x)\n { \/\/ 2 \\leq x \\leq MAX_SIZE^2\n if (x < N)\n {\n return isprime[x];\n }\n for (auto e : prime_nums)\n {\n if (x % e == 0)\n return false;\n }\n return true;\n }\n\n vector<int> const &primes() const\n {\n return prime_nums;\n }\n};\n\n\/\/ ----- main() -----\nclass Solve\n{\n int H, W;\n vector<string> S;\n PrimeNums pn;\n\npublic:\n Solve(int H, int W, vector<string> const &S) : H{H}, W{W}, S(S), pn{} {}\n\n int calc()\n {\n int ans{0};\n for (auto i = 0; i < H; i++)\n {\n ans += calc(S[i]);\n }\n return ans;\n };\n\nprivate:\n int calc(string const &T)\n {\n if (is_zero(T))\n {\n return 0;\n }\n auto V{make_vec(T)};\n#if DEBUG == 1\n cerr << \"V = {\";\n for (auto x : V)\n {\n cerr << x << \", \";\n }\n cerr << \"}\" << endl;\n#endif\n if (is_one(V))\n {\n return 1;\n }\n if (is_two(V))\n {\n return 2;\n }\n return 3;\n }\n\n bool is_zero(string const &T)\n {\n for (auto x : T)\n {\n if (x == '.')\n {\n return false;\n }\n }\n return true;\n }\n\n vector<int> make_vec(string const &T)\n {\n int first{-1};\n vector<int> V;\n for (auto i = 0; i < W; i++)\n {\n if (T[i] == '.')\n {\n if (first == -1)\n {\n first = i;\n }\n V.push_back(i - first);\n }\n }\n return V;\n }\n\n bool is_one(vector<int> const &V)\n {\n if (V.size() < size_t{2})\n {\n return true;\n }\n assert(V[0] == 0);\n int g{V[1]};\n for (auto it = V.begin() + 1; it != V.end(); it++)\n {\n g = gcd(g, *it);\n }\n for (auto i = 0; i < 20; i++)\n {\n if ((g >> i) == 1)\n {\n return false;\n }\n }\n return true;\n }\n\n bool is_two(vector<int> const &V)\n {\n for (auto it = pn.primes().begin() + 1; it != pn.primes().end(); it++)\n {\n int p{static_cast<int>(*it)};\n int X{static_cast<int>(V.size())};\n if (W \/ p + 1 < X \/ 2)\n {\n return false;\n }\n for (auto k = 0; k < 2; k++)\n {\n int m{V[k]};\n int first{-1};\n vector<int> W;\n for (auto x : V)\n {\n if (x - m >= 0 && (x - m) % p == 0)\n {\n continue;\n }\n if (first == -1)\n {\n first = x;\n }\n W.push_back(x - first);\n }\n if (is_one(W))\n {\n return true;\n }\n }\n }\n assert(false);\n return false;\n }\n};\n\nint main()\n{\n int H, W;\n cin >> H >> W;\n vector<string> S(H);\n for (auto i = 0; i < H; i++)\n {\n cin >> S[i];\n }\n Solve solve(H, W, S);\n cout << solve.calc() << endl;\n}\n<commit_msg>tried H.cpp to 'H'<commit_after>#define DEBUG 1\n\/**\n * File : H.cpp\n * Author : Kazune Takahashi\n * Created : 2019\/12\/30 18:11:35\n * Powered by Visual Studio Code\n *\/\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n\/\/ ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- PrimeNums -----\n\nclass PrimeNums\n{\n static constexpr ll MAX_SIZE{1000010LL};\n ll N;\n vector<bool> isprime;\n vector<int> prime_nums;\n\npublic:\n PrimeNums(ll N = MAX_SIZE) : N{N}, isprime(N, true), prime_nums{}\n {\n isprime[0] = isprime[1] = false;\n for (auto i = 2; i < N; i++)\n {\n if (isprime[i])\n {\n prime_nums.push_back(i);\n for (auto j = 2 * i; j < N; j += i)\n {\n isprime[j] = false;\n }\n }\n }\n }\n\n bool is_prime(long long x)\n { \/\/ 2 \\leq x \\leq MAX_SIZE^2\n if (x < N)\n {\n return isprime[x];\n }\n for (auto e : prime_nums)\n {\n if (x % e == 0)\n return false;\n }\n return true;\n }\n\n vector<int> const &primes() const\n {\n return prime_nums;\n }\n};\n\n\/\/ ----- main() -----\nclass Solve\n{\n int H, W;\n vector<string> S;\n PrimeNums pn;\n\npublic:\n Solve(int H, int W, vector<string> const &S) : H{H}, W{W}, S(S), pn{} {}\n\n int calc()\n {\n int ans{0};\n for (auto i = 0; i < H; i++)\n {\n ans += calc(S[i]);\n }\n return ans;\n };\n\nprivate:\n int calc(string const &T)\n {\n if (is_zero(T))\n {\n return 0;\n }\n auto V{make_vec(T)};\n#if DEBUG == 1\n cerr << \"V = {\";\n for (auto x : V)\n {\n cerr << x << \", \";\n }\n cerr << \"}\" << endl;\n#endif\n if (is_one(V))\n {\n return 1;\n }\n if (is_two(V))\n {\n return 2;\n }\n return 3;\n }\n\n bool is_zero(string const &T)\n {\n for (auto x : T)\n {\n if (x == '.')\n {\n return false;\n }\n }\n return true;\n }\n\n vector<int> make_vec(string const &T)\n {\n int first{-1};\n vector<int> V;\n for (auto i = 0; i < W; i++)\n {\n if (T[i] == '.')\n {\n if (first == -1)\n {\n first = i;\n }\n V.push_back(i - first);\n }\n }\n return V;\n }\n\n bool is_one(vector<int> const &V)\n {\n if (V.size() < size_t{2})\n {\n return true;\n }\n assert(V[0] == 0);\n int g{V[1]};\n for (auto it = V.begin() + 1; it != V.end(); it++)\n {\n g = gcd(g, *it);\n }\n for (auto i = 0; i < 20; i++)\n {\n if ((g >> i) == 1)\n {\n return false;\n }\n }\n return true;\n }\n\n bool is_two(vector<int> const &V)\n {\n for (auto it = pn.primes().begin() + 1; it != pn.primes().end(); it++)\n {\n int p{static_cast<int>(*it)};\n int X{static_cast<int>(V.size())};\n if (W \/ p + 1 < X \/ 2)\n {\n return false;\n }\n for (auto k = 0; k < 2; k++)\n {\n int m{V[k]};\n int first{-1};\n vector<int> W;\n for (auto x : V)\n {\n if ((x - m) % p == 0)\n {\n continue;\n }\n if (first == -1)\n {\n first = x;\n }\n W.push_back(x - first);\n }\n#if DEBUG == 1\n cerr << \"p = \" << p << \", m = \" << m << endl;\n cerr << \"W = {\";\n for (auto x : W)\n {\n cerr << x << \", \";\n }\n cerr << \"}\" << endl;\n#endif\n if (is_one(W))\n {\n return true;\n }\n }\n }\n assert(false);\n return false;\n }\n};\n\nint main()\n{\n int H, W;\n cin >> H >> W;\n vector<string> S(H);\n for (auto i = 0; i < H; i++)\n {\n cin >> S[i];\n }\n Solve solve(H, W, S);\n cout << solve.calc() << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"AliReaderAOD.h\"\n\/\/______________________________________________________________________________\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ class AliReaderAOD \/\/\n\/\/ \/\/\n\/\/ Reader and Writer for AOD format. \/\/\n\/\/ AODs are stored in a tree named by the variable fgkTreeName. \/\/\n\/\/ There is stored 1 or 2 branches. Each of them stores AOD objects \/\/\n\/\/ First branch is named by the variable fgkReconstructedDataBranchName \/\/\n\/\/ (\"reconstructed.\") and keeps reconstructed data. \/\/\n\/\/ Second branch is called by the variable fgkSimulatedDataBranchName \/\/\n\/\/ (\"simulated.\") and stores Monte carlo truth. If both branches are present \/\/\n\/\/ AODs are parallel, i.e. nth particle in one branch corresponds to the nth \/\/\n\/\/ particle in the other one. \/\/\n\/\/ \/\/\n\/\/ Since we accept different formats of particles that are stored in AODs \/\/\n\/\/ reader must take care of that fact: clean buffer if the next file contains \/\/\n\/\/ different particle type. \/\/\n\/\/ \/\/\n\/\/ Piotr.Skowronski@cern.ch \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClassImp(AliReaderAOD)\n\n#include <TError.h>\n#include <TFile.h>\n#include <TTree.h>\n#include <TH1.h>\n#include \"AliAOD.h\"\n\n\nconst TString AliReaderAOD::fgkTreeName(\"TAOD\");\nconst TString AliReaderAOD::fgkReconstructedDataBranchName(\"reconstructed.\");\nconst TString AliReaderAOD::fgkSimulatedDataBranchName(\"simulated.\");\n\nAliReaderAOD::AliReaderAOD(const Char_t* aodfilename):\n fFileName(aodfilename),\n fReadSim(kFALSE),\n fReadRec(kTRUE),\n fTree(0x0),\n fFile(0x0),\n fSimBuffer(0x0),\n fRecBuffer(0x0)\n{\n \/\/ctor\n}\n\/********************************************************************\/\n\nAliReaderAOD::~AliReaderAOD()\n{\n\/\/dtor\n if (fEventSim == fSimBuffer )\n {\n fEventSim = 0x0;\n fEventRec = 0x0;\n }\n delete fSimBuffer;\n delete fRecBuffer;\n \n delete fTree;\n delete fFile;\n}\n\/********************************************************************\/\n\nvoid AliReaderAOD::Rewind()\n{\n\/\/Rewinds reading\n delete fTree;\n fTree = 0x0;\n delete fFile;\n fFile = 0x0;\n fCurrentDir = 0;\n fNEventsRead= 0;\n}\n\/********************************************************************\/\nInt_t AliReaderAOD::ReadNext()\n{\n\/\/Reads next event\n \n Info(\"ReadNext\",\"Entered\");\n do \/\/do{}while; is OK even if 0 dirs specified. In that case we try to read from \".\/\"\n {\n if (fFile == 0x0)\n {\n Int_t openfailed = OpenFile(fCurrentDir);\/\/rl is opened here\n if (openfailed)\n {\n \/\/Error(\"ReadNext\",\"Error Occured while opening directory number %d\",fCurrentDir);\n fCurrentDir++;\n continue;\n }\n fCurrentEvent = 0;\n }\n \/\/Tree must exist because OpenFile would reuturn error in the other case\n if ( fCurrentEvent >= fTree->GetEntries() )\n {\n delete fTree;\n fTree = 0x0;\n delete fFile;\n fFile = 0x0;\n fSimBuffer = 0x0;\n fRecBuffer = 0x0;\n fCurrentDir++;\n continue;\n }\n \n Info(\"ReadNext\",\"Getting event %d\",fCurrentEvent);\n fTree->GetEvent(fCurrentEvent);\n Info(\"ReadNext\",\"Getting event %d Done\",fCurrentEvent);\n \n Int_t retval = 0;\n if (fReadRec && fReadSim)\n {\n retval = ReadRecAndSim();\n }\n else\n {\n if (fReadRec) retval = ReadRec();\n if (fReadSim) retval = ReadSim();\n } \n\n fCurrentEvent++;\n if (retval == 0) fNEventsRead++;\n\n return retval;\/\/success -> read one event\n \n }while(fCurrentDir < GetNumberOfDirs());\/\/end of loop over directories specified in fDirs Obj Array \n \n return 1; \/\/no more directories to read\n \n \n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::ReadRecAndSim()\n{\n\/\/Reads raconstructed and simulated data \n\n Info(\"ReadRecAndSim\",\"Found %d reconstructed tracks and %d simulated particles\",\n fRecBuffer->GetNumberOfParticles(),fSimBuffer->GetNumberOfParticles());\n\n if (fCuts->GetEntriesFast() == 0x0)\n {\/\/if there is no cuts we return pointer to the buffer\n if (fEventRec != fRecBuffer)\n {\n delete fEventRec;\n delete fEventSim;\n }\n fEventRec = fRecBuffer;\/\/fEventRec is the pointer that the user gets when he asks about an event\n fEventSim = fSimBuffer;\n }\n else\n {\/\/if there are cuts specified\n if ( (fEventRec == 0x0) || (fEventRec == fRecBuffer) )\n {\/\/we need to create a new event, if it is not existing or it is the same as branch buffer\n fEventRec = new AliAOD();\n fEventSim = new AliAOD();\n\n fEventRec->SetParticleClass( fRecBuffer->GetParticleClass() );\n fEventSim->SetParticleClass( fSimBuffer->GetParticleClass() );\n } \n else\n {\/\/or simply reset it in case it already exists\n fEventRec->Reset();\n fEventSim->Reset();\n }\n\n Int_t npart = fRecBuffer->GetNumberOfParticles();\n for (Int_t i = 0; i < npart; i++)\n {\n AliVAODParticle* prec = fRecBuffer->GetParticle(i);\n if (Rejected(prec)) continue;\/\/we make cuts only on simulated data\n\n fEventRec->AddParticle(prec);\n fEventSim->AddParticle( fSimBuffer->GetParticle(i));\n }\n }\n\n Info(\"ReadRecAndSim\",\"Read %d reconstructed tracks and %d simulated particles\",\n fEventRec->GetNumberOfParticles(),fEventSim->GetNumberOfParticles());\n \n fTrackCounter->Fill(fEventRec->GetNumberOfParticles());\n \n return 0;\n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::ReadRec()\n{\n\/\/Reads reconstructed data only\n\n Info(\"ReadRec\",\"Found %d reconstructed tracks\",fRecBuffer->GetNumberOfParticles());\n\n if (fCuts->GetEntriesFast() == 0x0)\n {\/\/if there is no cuts we return pointer to the buffer\n if (fEventRec != fRecBuffer)\n {\n delete fEventRec;\n }\n fEventRec = fRecBuffer;\/\/fEventRec is the pointer that the user gets when he asks about an event\n }\n else\n {\/\/if there are cuts specified\n if ( (fEventRec == 0x0) || (fEventRec == fRecBuffer) )\n {\/\/we need to create a new event, if it is not existing or it is the same as branch buffer\n fEventRec = new AliAOD();\n\n fEventRec->SetParticleClass( fRecBuffer->GetParticleClass() );\n } \n else\n {\/\/or simply reset it in case it already exists\n fEventRec->Reset();\n }\n\n Int_t npart = fRecBuffer->GetNumberOfParticles();\n for (Int_t i = 0; i < npart; i++)\n {\n AliVAODParticle* prec = fRecBuffer->GetParticle(i);\n if (Rejected(prec)) continue;\/\/we make cuts only on simulated data\n\n fEventRec->AddParticle(prec);\n }\n }\n\n Info(\"ReadRec\",\"Read %d reconstructed tracks\",fEventRec->GetNumberOfParticles());\n fTrackCounter->Fill(fEventRec->GetNumberOfParticles());\n\n return 0;\n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::ReadSim()\n{\n\/\/Reads simulated data only\n\n Info(\"ReadSim\",\"Found %d simulated particles\",fSimBuffer->GetNumberOfParticles());\n\n if (fCuts->GetEntriesFast() == 0x0)\n {\/\/if there is no cuts we return pointer to the buffer\n if (fEventSim != fSimBuffer)\n {\n delete fEventSim;\n }\n fEventSim = fSimBuffer;\n }\n else\n {\/\/if there are cuts specified\n if ( (fEventSim == 0x0) || (fEventSim == fSimBuffer) )\n {\/\/we need to create a new event, if it is not existing or it is the same as branch buffer\n fEventSim = new AliAOD();\n\n fEventSim->SetParticleClass( fSimBuffer->GetParticleClass() );\n } \n else\n {\/\/or simply reset it in case it already exists\n fEventSim->Reset();\n }\n\n Int_t npart = fSimBuffer->GetNumberOfParticles();\n for (Int_t i = 0; i < npart; i++)\n {\n AliVAODParticle* prec = fSimBuffer->GetParticle(i);\n if (Rejected(prec)) continue;\/\/we make cuts only on simulated data\n fEventSim->AddParticle(prec);\n }\n }\n\n Info(\"ReadSim\",\"Read %d simulated particles\",fEventSim->GetNumberOfParticles());\n fTrackCounter->Fill(fEventSim->GetNumberOfParticles());\n\n\n return 0;\n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::OpenFile(Int_t n)\n{\n\/\/opens fFile with tree\n\n\/\/ Info(\"ReadNext\",\"Opening File %d\",n);\n const TString dirname = GetDirName(n);\n if (dirname == \"\")\n {\n if (AliVAODParticle::GetDebug() > 2 )\n {\n Info(\"OpenFile\",\"Got empty string as a directory name.\"); \n }\n return 1;\n }\n \n TString filename = dirname +\"\/\"+ fFileName;\n fFile = TFile::Open(filename.Data()); \n if ( fFile == 0x0)\n {\n Error(\"OpenFile\",\"Can't open fFile %s\",filename.Data());\n return 2;\n }\n if (!fFile->IsOpen())\n {\n Error(\"OpenFile\",\"Can't open fFile %s\",filename.Data());\n delete fFile;\n fFile = 0x0;\n return 3;\n }\n\n Info(\"ReadNext\",\"File Is Opened, Getting the TREE\");\n \n fTree = dynamic_cast<TTree*>(fFile->Get(fgkTreeName));\n if (fTree == 0x0)\n {\n if (AliVAODParticle::GetDebug() > 2 )\n {\n Info(\"ReadNext\",\"Can not find TTree object named %s\",fgkTreeName.Data());\n }\n delete fFile;\n fFile = 0x0;\n return 4;\n }\n\n\/\/ Info(\"ReadNext\",\"Got TREE, Setting branch addresses\");\n\n if (fReadRec)\n {\n TBranch* branch = fTree->GetBranch(fgkReconstructedDataBranchName);\n if (branch == 0x0)\n {\n Error(\"OpenFile\",\"Can not find branch %s in file %s\",\n fgkReconstructedDataBranchName.Data(),filename.Data());\n \n delete fTree;\n fTree = 0x0;\n delete fFile;\n fFile = 0x0;\n return 5;\n }\n fTree->SetBranchAddress(fgkReconstructedDataBranchName,&fRecBuffer);\n }\n \n\n if (fReadSim)\n {\n TBranch* branch = fTree->GetBranch(fgkSimulatedDataBranchName);\n if (branch == 0x0)\n {\n Error(\"OpenFile\",\"Can not find branch %s in file %s\",\n fgkSimulatedDataBranchName.Data(),filename.Data());\n \n delete fTree;\n fTree = 0x0;\n delete fFile;\n fFile = 0x0;\n return 6;\n }\n fTree->SetBranchAddress(fgkSimulatedDataBranchName,&fSimBuffer);\n }\n\/\/ Info(\"ReadNext\",\"Got TREE, Addresses are set.\");\n\/\/ Info(\"ReadNext\",\"Quitting the method.\");\n \n return 0;\n \n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::WriteAOD(AliReader* reader, const char* outfilename, const char* pclassname, Bool_t \/*multcheck*\/)\n{\n\/\/reads tracks from runs and writes them to file\n ::Info(\"AliReaderAOD::Write\",\"________________________________________________________\");\n ::Info(\"AliReaderAOD::Write\",\"________________________________________________________\");\n ::Info(\"AliReaderAOD::Write\",\"________________________________________________________\");\n \n if (reader == 0x0)\n {\n ::Error(\"AliReaderAOD::Write\",\"Input Reader is NULL\");\n return -1;\n }\n TFile *outfile = TFile::Open(outfilename,\"recreate\");\n if (outfile == 0x0)\n {\n ::Error(\"AliReaderAOD::Write\",\"Can not open output file %s\",outfilename);\n return -1;\n }\n\n TTree *tree = new TTree(fgkTreeName,\"Tree with tracks\");\n \n TBranch *recbranch = 0x0, *simbranch = 0x0;\n \n AliAOD* eventrec = new AliAOD();\/\/must be created before Branch is called. Otherwise clones array is not splitted\n AliAOD* eventsim = new AliAOD();\/\/AOD together with fParticles clones array knowing exact type of particles\n \n eventrec->SetParticleClassName(pclassname);\n eventsim->SetParticleClassName(pclassname);\n \n AliAOD* recbuffer = eventrec;\n AliAOD* simbuffer = eventsim;\n \n if (reader->ReadsRec()) recbranch = tree->Branch(fgkReconstructedDataBranchName,\"AliAOD\",&recbuffer,32000,99);\n if (reader->ReadsSim()) simbranch = tree->Branch(fgkSimulatedDataBranchName,\"AliAOD\",&simbuffer,32000,99);\n\n reader->Rewind();\n while (reader->Next() == kFALSE)\n {\n \n if (reader->ReadsRec())\n {\/\/here we can get AOD that has different particle type\n AliAOD* event = reader->GetEventRec();\n if ( eventrec->GetParticleClass() != event->GetParticleClass() )\n {\/\/if class type is not what what we whant we copy particles\n eventrec->CopyData(event);\n recbuffer = eventrec;\n }\n else\n {\/\/else just pointer to event from input reader is passed\n recbuffer = event;\n } \n }\n\n if (reader->ReadsSim())\n {\n AliAOD* event = reader->GetEventSim();\n if ( eventsim->GetParticleClass() != event->GetParticleClass() )\n {\/\/if class type is not what what we whant we copy particles\n eventsim->CopyData(event);\n simbuffer = eventrec;\n }\n else\n {\/\/else just pointer to event from input reader is passed\n simbuffer = event;\n } \n }\n recbuffer->GetParticle(0)->Print();\n simbuffer->GetParticle(0)->Print();\n tree->Fill();\n }\n \n ::Info(\"AliReaderAOD::Write\",\"Written %d events\",tree->GetEntries());\n outfile->cd();\n tree->Write();\n\n delete eventsim;\n delete eventrec;\n \n delete tree;\n delete outfile;\n return 0; \n}\n\n<commit_msg>Bug correction. (C.Finck)<commit_after>#include \"AliReaderAOD.h\"\n\/\/______________________________________________________________________________\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ class AliReaderAOD \/\/\n\/\/ \/\/\n\/\/ Reader and Writer for AOD format. \/\/\n\/\/ AODs are stored in a tree named by the variable fgkTreeName. \/\/\n\/\/ There is stored 1 or 2 branches. Each of them stores AOD objects \/\/\n\/\/ First branch is named by the variable fgkReconstructedDataBranchName \/\/\n\/\/ (\"reconstructed.\") and keeps reconstructed data. \/\/\n\/\/ Second branch is called by the variable fgkSimulatedDataBranchName \/\/\n\/\/ (\"simulated.\") and stores Monte carlo truth. If both branches are present \/\/\n\/\/ AODs are parallel, i.e. nth particle in one branch corresponds to the nth \/\/\n\/\/ particle in the other one. \/\/\n\/\/ \/\/\n\/\/ Since we accept different formats of particles that are stored in AODs \/\/\n\/\/ reader must take care of that fact: clean buffer if the next file contains \/\/\n\/\/ different particle type. \/\/\n\/\/ \/\/\n\/\/ Piotr.Skowronski@cern.ch \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClassImp(AliReaderAOD)\n\n#include <TError.h>\n#include <TFile.h>\n#include <TTree.h>\n#include <TH1.h>\n#include \"AliAOD.h\"\n\n\nconst TString AliReaderAOD::fgkTreeName(\"TAOD\");\nconst TString AliReaderAOD::fgkReconstructedDataBranchName(\"reconstructed.\");\nconst TString AliReaderAOD::fgkSimulatedDataBranchName(\"simulated.\");\n\nAliReaderAOD::AliReaderAOD(const Char_t* aodfilename):\n fFileName(aodfilename),\n fReadSim(kFALSE),\n fReadRec(kTRUE),\n fTree(0x0),\n fFile(0x0),\n fSimBuffer(0x0),\n fRecBuffer(0x0)\n{\n \/\/ctor\n}\n\/********************************************************************\/\n\nAliReaderAOD::~AliReaderAOD()\n{\n\/\/dtor\n if (fEventSim == fSimBuffer )\n {\n fEventSim = 0x0;\n fEventRec = 0x0;\n }\n delete fSimBuffer;\n delete fRecBuffer;\n \n delete fTree;\n delete fFile;\n}\n\/********************************************************************\/\n\nvoid AliReaderAOD::Rewind()\n{\n\/\/Rewinds reading\n delete fTree;\n fTree = 0x0;\n delete fFile;\n fFile = 0x0;\n fCurrentDir = 0;\n fNEventsRead= 0;\n}\n\/********************************************************************\/\nInt_t AliReaderAOD::ReadNext()\n{\n\/\/Reads next event\n \n Info(\"ReadNext\",\"Entered\");\n do \/\/do{}while; is OK even if 0 dirs specified. In that case we try to read from \".\/\"\n {\n if (fFile == 0x0)\n {\n Int_t openfailed = OpenFile(fCurrentDir);\/\/rl is opened here\n if (openfailed)\n {\n \/\/Error(\"ReadNext\",\"Error Occured while opening directory number %d\",fCurrentDir);\n fCurrentDir++;\n continue;\n }\n fCurrentEvent = 0;\n }\n \/\/Tree must exist because OpenFile would reuturn error in the other case\n if ( fCurrentEvent >= fTree->GetEntries() )\n {\n delete fTree;\n fTree = 0x0;\n delete fFile;\n fFile = 0x0;\n fSimBuffer = 0x0;\n fRecBuffer = 0x0;\n fCurrentDir++;\n continue;\n }\n \n Info(\"ReadNext\",\"Getting event %d\",fCurrentEvent);\n fTree->GetEvent(fCurrentEvent);\n Info(\"ReadNext\",\"Getting event %d Done\",fCurrentEvent);\n \n Int_t retval = 0;\n if (fReadRec && fReadSim)\n {\n retval = ReadRecAndSim();\n }\n else\n {\n if (fReadRec) retval = ReadRec();\n if (fReadSim) retval = ReadSim();\n } \n\n fCurrentEvent++;\n if (retval == 0) fNEventsRead++;\n\n return retval;\/\/success -> read one event\n \n }while(fCurrentDir < GetNumberOfDirs());\/\/end of loop over directories specified in fDirs Obj Array \n \n return 1; \/\/no more directories to read\n \n \n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::ReadRecAndSim()\n{\n\/\/Reads raconstructed and simulated data \n\n Info(\"ReadRecAndSim\",\"Found %d reconstructed tracks and %d simulated particles\",\n fRecBuffer->GetNumberOfParticles(),fSimBuffer->GetNumberOfParticles());\n\n if (fCuts->GetEntriesFast() == 0x0)\n {\/\/if there is no cuts we return pointer to the buffer\n if (fEventRec != fRecBuffer)\n {\n delete fEventRec;\n delete fEventSim;\n }\n fEventRec = fRecBuffer;\/\/fEventRec is the pointer that the user gets when he asks about an event\n fEventSim = fSimBuffer;\n }\n else\n {\/\/if there are cuts specified\n if ( (fEventRec == 0x0) || (fEventRec == fRecBuffer) )\n {\/\/we need to create a new event, if it is not existing or it is the same as branch buffer\n fEventRec = new AliAOD();\n fEventSim = new AliAOD();\n\n fEventRec->SetParticleClass( fRecBuffer->GetParticleClass() );\n fEventSim->SetParticleClass( fSimBuffer->GetParticleClass() );\n } \n else\n {\/\/or simply reset it in case it already exists\n fEventRec->Reset();\n fEventSim->Reset();\n }\n\n Int_t npart = fRecBuffer->GetNumberOfParticles();\n for (Int_t i = 0; i < npart; i++)\n {\n AliVAODParticle* prec = fRecBuffer->GetParticle(i);\n if (Rejected(prec)) continue;\/\/we make cuts only on simulated data\n\n fEventRec->AddParticle(prec);\n fEventSim->AddParticle( fSimBuffer->GetParticle(i));\n }\n }\n\n Info(\"ReadRecAndSim\",\"Read %d reconstructed tracks and %d simulated particles\",\n fEventRec->GetNumberOfParticles(),fEventSim->GetNumberOfParticles());\n \n fTrackCounter->Fill(fEventRec->GetNumberOfParticles());\n \n return 0;\n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::ReadRec()\n{\n\/\/Reads reconstructed data only\n\n Info(\"ReadRec\",\"Found %d reconstructed tracks\",fRecBuffer->GetNumberOfParticles());\n\n if (fCuts->GetEntriesFast() == 0x0)\n {\/\/if there is no cuts we return pointer to the buffer\n if (fEventRec != fRecBuffer)\n {\n delete fEventRec;\n }\n fEventRec = fRecBuffer;\/\/fEventRec is the pointer that the user gets when he asks about an event\n }\n else\n {\/\/if there are cuts specified\n if ( (fEventRec == 0x0) || (fEventRec == fRecBuffer) )\n {\/\/we need to create a new event, if it is not existing or it is the same as branch buffer\n fEventRec = new AliAOD();\n\n fEventRec->SetParticleClass( fRecBuffer->GetParticleClass() );\n } \n else\n {\/\/or simply reset it in case it already exists\n fEventRec->Reset();\n }\n\n Int_t npart = fRecBuffer->GetNumberOfParticles();\n for (Int_t i = 0; i < npart; i++)\n {\n AliVAODParticle* prec = fRecBuffer->GetParticle(i);\n if (Rejected(prec)) continue;\/\/we make cuts only on simulated data\n\n fEventRec->AddParticle(prec);\n }\n }\n\n Info(\"ReadRec\",\"Read %d reconstructed tracks\",fEventRec->GetNumberOfParticles());\n fTrackCounter->Fill(fEventRec->GetNumberOfParticles());\n\n return 0;\n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::ReadSim()\n{\n\/\/Reads simulated data only\n\n Info(\"ReadSim\",\"Found %d simulated particles\",fSimBuffer->GetNumberOfParticles());\n\n if (fCuts->GetEntriesFast() == 0x0)\n {\/\/if there is no cuts we return pointer to the buffer\n if (fEventSim != fSimBuffer)\n {\n delete fEventSim;\n }\n fEventSim = fSimBuffer;\n }\n else\n {\/\/if there are cuts specified\n if ( (fEventSim == 0x0) || (fEventSim == fSimBuffer) )\n {\/\/we need to create a new event, if it is not existing or it is the same as branch buffer\n fEventSim = new AliAOD();\n\n fEventSim->SetParticleClass( fSimBuffer->GetParticleClass() );\n } \n else\n {\/\/or simply reset it in case it already exists\n fEventSim->Reset();\n }\n\n Int_t npart = fSimBuffer->GetNumberOfParticles();\n for (Int_t i = 0; i < npart; i++)\n {\n AliVAODParticle* prec = fSimBuffer->GetParticle(i);\n if (Rejected(prec)) continue;\/\/we make cuts only on simulated data\n fEventSim->AddParticle(prec);\n }\n }\n\n Info(\"ReadSim\",\"Read %d simulated particles\",fEventSim->GetNumberOfParticles());\n fTrackCounter->Fill(fEventSim->GetNumberOfParticles());\n\n\n return 0;\n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::OpenFile(Int_t n)\n{\n\/\/opens fFile with tree\n\n\/\/ Info(\"ReadNext\",\"Opening File %d\",n);\n const TString dirname = GetDirName(n);\n if (dirname == \"\")\n {\n if (AliVAODParticle::GetDebug() > 2 )\n {\n Info(\"OpenFile\",\"Got empty string as a directory name.\"); \n }\n return 1;\n }\n \n TString filename = dirname +\"\/\"+ fFileName;\n fFile = TFile::Open(filename.Data()); \n if ( fFile == 0x0)\n {\n Error(\"OpenFile\",\"Can't open fFile %s\",filename.Data());\n return 2;\n }\n if (!fFile->IsOpen())\n {\n Error(\"OpenFile\",\"Can't open fFile %s\",filename.Data());\n delete fFile;\n fFile = 0x0;\n return 3;\n }\n\n Info(\"ReadNext\",\"File Is Opened, Getting the TREE\");\n \n fTree = dynamic_cast<TTree*>(fFile->Get(fgkTreeName));\n if (fTree == 0x0)\n {\n if (AliVAODParticle::GetDebug() > 2 )\n {\n Info(\"ReadNext\",\"Can not find TTree object named %s\",fgkTreeName.Data());\n }\n delete fFile;\n fFile = 0x0;\n return 4;\n }\n\n\/\/ Info(\"ReadNext\",\"Got TREE, Setting branch addresses\");\n\n if (fReadRec)\n {\n TBranch* branch = fTree->GetBranch(fgkReconstructedDataBranchName);\n if (branch == 0x0)\n {\n Error(\"OpenFile\",\"Can not find branch %s in file %s\",\n fgkReconstructedDataBranchName.Data(),filename.Data());\n \n delete fTree;\n fTree = 0x0;\n delete fFile;\n fFile = 0x0;\n return 5;\n }\n fTree->SetBranchAddress(fgkReconstructedDataBranchName,&fRecBuffer);\n }\n \n\n if (fReadSim)\n {\n TBranch* branch = fTree->GetBranch(fgkSimulatedDataBranchName);\n if (branch == 0x0)\n {\n Error(\"OpenFile\",\"Can not find branch %s in file %s\",\n fgkSimulatedDataBranchName.Data(),filename.Data());\n \n delete fTree;\n fTree = 0x0;\n delete fFile;\n fFile = 0x0;\n return 6;\n }\n fTree->SetBranchAddress(fgkSimulatedDataBranchName,&fSimBuffer);\n }\n\/\/ Info(\"ReadNext\",\"Got TREE, Addresses are set.\");\n\/\/ Info(\"ReadNext\",\"Quitting the method.\");\n \n return 0;\n \n}\n\/********************************************************************\/\n\nInt_t AliReaderAOD::WriteAOD(AliReader* reader, const char* outfilename, const char* pclassname, Bool_t \/*multcheck*\/)\n{\n\/\/reads tracks from runs and writes them to file\n ::Info(\"AliReaderAOD::Write\",\"________________________________________________________\");\n ::Info(\"AliReaderAOD::Write\",\"________________________________________________________\");\n ::Info(\"AliReaderAOD::Write\",\"________________________________________________________\");\n \n if (reader == 0x0)\n {\n ::Error(\"AliReaderAOD::Write\",\"Input Reader is NULL\");\n return -1;\n }\n TFile *outfile = TFile::Open(outfilename,\"recreate\");\n if (outfile == 0x0)\n {\n ::Error(\"AliReaderAOD::Write\",\"Can not open output file %s\",outfilename);\n return -1;\n }\n\n TTree *tree = new TTree(fgkTreeName,\"Tree with tracks\");\n \n TBranch *recbranch = 0x0, *simbranch = 0x0;\n \n AliAOD* eventrec = new AliAOD();\/\/must be created before Branch is called. Otherwise clones array is not splitted\n AliAOD* eventsim = new AliAOD();\/\/AOD together with fParticles clones array knowing exact type of particles\n \n eventrec->SetParticleClassName(pclassname);\n eventsim->SetParticleClassName(pclassname);\n \n AliAOD* recbuffer = eventrec;\n AliAOD* simbuffer = eventsim;\n \n if (reader->ReadsRec()) recbranch = tree->Branch(fgkReconstructedDataBranchName,\"AliAOD\",&recbuffer,32000,99);\n if (reader->ReadsSim()) simbranch = tree->Branch(fgkSimulatedDataBranchName,\"AliAOD\",&simbuffer,32000,99);\n\n reader->Rewind();\n while (reader->Next() == kFALSE)\n {\n \n if (reader->ReadsRec())\n {\/\/here we can get AOD that has different particle type\n AliAOD* event = reader->GetEventRec();\n if ( eventrec->GetParticleClass() != event->GetParticleClass() )\n {\/\/if class type is not what what we whant we copy particles\n eventrec->CopyData(event);\n recbuffer = eventrec;\n }\n else\n {\/\/else just pointer to event from input reader is passed\n recbuffer = event;\n } \n\trecbuffer->GetParticle(0)->Print();\n }\n\n if (reader->ReadsSim())\n {\n AliAOD* event = reader->GetEventSim();\n if ( eventsim->GetParticleClass() != event->GetParticleClass() )\n {\/\/if class type is not what what we whant we copy particles\n eventsim->CopyData(event);\n simbuffer = eventrec;\n }\n else\n {\/\/else just pointer to event from input reader is passed\n simbuffer = event;\n } \n\tsimbuffer->GetParticle(0)->Print();\n }\n tree->Fill();\n }\n \n ::Info(\"AliReaderAOD::Write\",\"Written %d events\",tree->GetEntries());\n outfile->cd();\n tree->Write();\n\n delete eventsim;\n delete eventrec;\n \n delete tree;\n delete outfile;\n return 0; \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file AssemblyDebuggerModel.cpp\n * @author Yann yann@ethdev.com\n * @date 2014\n * used as a model to debug contract assembly code.\n *\/\n\n#include <QApplication>\n#include <libdevcore\/Common.h>\n#include <libevm\/VM.h>\n#include <libethereum\/Executive.h>\n#include <libethereum\/Transaction.h>\n#include <libethereum\/ExtVM.h>\n#include \"AppContext.h\"\n#include \"TransactionListModel.h\"\n#include \"AssemblyDebuggerModel.h\"\n#include \"ConstantCompilationModel.h\"\n#include \"DebuggingStateWrapper.h\"\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\nusing namespace dev::mix;\n\nAssemblyDebuggerModel::AssemblyDebuggerModel():\n\tm_userAccount(KeyPair::create()),\n\tm_baseState(Address(), m_overlayDB, BaseState::Empty)\n{\n\tm_baseState.addBalance(m_userAccount.address(), 10000000 * ether);\n\tm_executiveState = m_baseState;\n\tm_currentExecution = std::unique_ptr<Executive>(new Executive(m_executiveState, LastHashes(), 0));\n}\n\nDebuggingContent AssemblyDebuggerModel::executeTransaction(bytesConstRef const& _rawTransaction)\n{\n\tQList<DebuggingState> machineStates;\n\tm_currentExecution.reset(new Executive(m_executiveState, LastHashes(), 0));\n\tm_currentExecution->setup(_rawTransaction);\n\tstd::vector<DebuggingState const*> levels;\n\tbytes code;\n\tbytesConstRef data;\n\tbool firstIteration = true;\n\tauto onOp = [&](uint64_t steps, Instruction inst, dev::bigint newMemSize, dev::bigint gasCost, void* voidVM, void const* voidExt)\n\t{\n\t\tVM& vm = *(VM*)voidVM;\n\t\tExtVM const& ext = *(ExtVM const*)voidExt;\n\n\t\tif (firstIteration)\n\t\t{\n\t\t\tcode = ext.code;\n\t\t\tdata = ext.data;\n\t\t\tfirstIteration = false;\n\t\t}\n\n\t\tif (levels.size() < ext.depth)\n\t\t\tlevels.push_back(&machineStates.back());\n\t\telse\n\t\t\tlevels.resize(ext.depth);\n\n\t\tmachineStates.append(DebuggingState({steps, ext.myAddress, vm.curPC(), inst, newMemSize, vm.gas(),\n\t\t\t\t\t\t\t\t\t vm.stack(), vm.memory(), gasCost, ext.state().storage(ext.myAddress), levels}));\n\t};\n\n\tm_currentExecution->go(onOp);\n\tm_currentExecution->finalize(onOp);\n\tm_executiveState.completeMine();\n\n\tDebuggingContent d;\n\td.returnValue = m_currentExecution->out().toVector();\n\td.machineStates = machineStates;\n\td.executionCode = code;\n\td.executionData = data;\n\td.contentAvailable = true;\n\td.message = \"ok\";\n\treturn d;\n}\n\nDebuggingContent AssemblyDebuggerModel::deployContract(bytes const& _code)\n{\n\tu256 gasPrice = 10000000000000;\n\tu256 gas = 1000000;\n\tu256 amount = 100;\n\tTransaction _tr(amount, gasPrice, min(gas, m_baseState.gasLimitRemaining()), _code, m_executiveState.transactionsFrom(dev::toAddress(m_userAccount.secret())), m_userAccount.secret());\n\tbytes b = _tr.rlp();\n\tdev::bytesConstRef bytesRef = &b;\n\tDebuggingContent d = executeTransaction(bytesRef);\n\th256 th = sha3(rlpList(_tr.sender(), _tr.nonce()));\n\td.contractAddress = right160(th);\n\treturn d;\n}\n\nDebuggingContent AssemblyDebuggerModel::callContract(Address const& _contract, bytes const& _data, TransactionSettings const& _tr)\n{\n\tTransaction tr = Transaction(_tr.value, _tr.gasPrice, min(_tr.gas, m_baseState.gasLimitRemaining()), _contract, _data, m_executiveState.transactionsFrom(dev::toAddress(m_userAccount.secret())), m_userAccount.secret());\n\tbytes b = tr.rlp();\n\tdev::bytesConstRef bytesRef = &b;\n\tDebuggingContent d = executeTransaction(bytesRef);\n\td.contractAddress = tr.receiveAddress();\n\treturn d;\n}\n\nvoid AssemblyDebuggerModel::resetState()\n{\n\t\/\/ Reset the state back to our clean premine.\n\tm_executiveState = m_baseState;\n}\n<commit_msg>Various fixes. Initial portion of NatSpec integration.<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file AssemblyDebuggerModel.cpp\n * @author Yann yann@ethdev.com\n * @date 2014\n * used as a model to debug contract assembly code.\n *\/\n\n#include <QApplication>\n#include <libdevcore\/Common.h>\n#include <libevm\/VM.h>\n#include <libethereum\/Executive.h>\n#include <libethereum\/Transaction.h>\n#include <libethereum\/ExtVM.h>\n#include \"AppContext.h\"\n#include \"TransactionListModel.h\"\n#include \"AssemblyDebuggerModel.h\"\n#include \"ConstantCompilationModel.h\"\n#include \"DebuggingStateWrapper.h\"\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\nusing namespace dev::mix;\n\nAssemblyDebuggerModel::AssemblyDebuggerModel():\n\tm_userAccount(KeyPair::create()),\n\tm_baseState(Address(), m_overlayDB, BaseState::Empty)\n{\n\tm_baseState.addBalance(m_userAccount.address(), 10000000 * ether);\n\tm_executiveState = m_baseState;\n\tm_currentExecution = std::unique_ptr<Executive>(new Executive(m_executiveState, LastHashes(), 0));\n}\n\nDebuggingContent AssemblyDebuggerModel::executeTransaction(bytesConstRef const& _rawTransaction)\n{\n\tQList<DebuggingState> machineStates;\n\tm_currentExecution.reset(new Executive(m_executiveState, LastHashes(), 0));\n\tm_currentExecution->setup(_rawTransaction);\n\tstd::vector<DebuggingState const*> levels;\n\tbytes code;\n\tbytesConstRef data;\n\tbool firstIteration = true;\n\tauto onOp = [&](uint64_t steps, Instruction inst, dev::bigint newMemSize, dev::bigint gasCost, void* voidVM, void const* voidExt)\n\t{\n\t\tVM& vm = *(VM*)voidVM;\n\t\tExtVM const& ext = *(ExtVM const*)voidExt;\n\n\t\tif (firstIteration)\n\t\t{\n\t\t\tcode = ext.code;\n\t\t\tdata = ext.data;\n\t\t\tfirstIteration = false;\n\t\t}\n\n\t\tif (levels.size() < ext.depth)\n\t\t\tlevels.push_back(&machineStates.back());\n\t\telse\n\t\t\tlevels.resize(ext.depth);\n\n\t\tmachineStates.append(DebuggingState({steps, ext.myAddress, vm.curPC(), inst, newMemSize, vm.gas(),\n\t\t\t\t\t\t\t\t\t vm.stack(), vm.memory(), gasCost, ext.state().storage(ext.myAddress), levels}));\n\t};\n\n\tm_currentExecution->go(onOp);\n\tm_currentExecution->finalize();\n\tm_executiveState.completeMine();\n\n\tDebuggingContent d;\n\td.returnValue = m_currentExecution->out().toVector();\n\td.machineStates = machineStates;\n\td.executionCode = code;\n\td.executionData = data;\n\td.contentAvailable = true;\n\td.message = \"ok\";\n\treturn d;\n}\n\nDebuggingContent AssemblyDebuggerModel::deployContract(bytes const& _code)\n{\n\tu256 gasPrice = 10000000000000;\n\tu256 gas = 1000000;\n\tu256 amount = 100;\n\tTransaction _tr(amount, gasPrice, min(gas, m_baseState.gasLimitRemaining()), _code, m_executiveState.transactionsFrom(dev::toAddress(m_userAccount.secret())), m_userAccount.secret());\n\tbytes b = _tr.rlp();\n\tdev::bytesConstRef bytesRef = &b;\n\tDebuggingContent d = executeTransaction(bytesRef);\n\th256 th = sha3(rlpList(_tr.sender(), _tr.nonce()));\n\td.contractAddress = right160(th);\n\treturn d;\n}\n\nDebuggingContent AssemblyDebuggerModel::callContract(Address const& _contract, bytes const& _data, TransactionSettings const& _tr)\n{\n\tTransaction tr = Transaction(_tr.value, _tr.gasPrice, min(_tr.gas, m_baseState.gasLimitRemaining()), _contract, _data, m_executiveState.transactionsFrom(dev::toAddress(m_userAccount.secret())), m_userAccount.secret());\n\tbytes b = tr.rlp();\n\tdev::bytesConstRef bytesRef = &b;\n\tDebuggingContent d = executeTransaction(bytesRef);\n\td.contractAddress = tr.receiveAddress();\n\treturn d;\n}\n\nvoid AssemblyDebuggerModel::resetState()\n{\n\t\/\/ Reset the state back to our clean premine.\n\tm_executiveState = m_baseState;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"AutoPacketFactoryTest.h\"\n#include \"CoreThread.h\"\n\nclass IssuesPacketWaitsThenQuits:\n public CoreThread\n{\npublic:\n IssuesPacketWaitsThenQuits(void) :\n m_hasQuit(false)\n {\n \/\/ Note: Don't do this in practice. This only works because we only inject this type\n \/\/ into a context that's already running; normally, creating a packet from our ctor can\n \/\/ cause an exception if we are being injected before Initiate is called.\n AutoRequired<AutoPacketFactory> factory;\n m_packet = factory->NewPacket();\n }\n\n bool m_hasQuit;\n std::shared_ptr<AutoPacket> m_packet;\n\n void Run(void) override {\n \/\/ Move the shared pointer here:\n auto packet = std::move(m_packet);\n \/\/ After moving the object, reset it to a known state\n m_packet.reset();\n\n \/\/ Just wait a bit, then return, just like we said we would\n this->ThreadSleep(boost::chrono::milliseconds(50));\n\n \/\/ Update our variable and then return out:\n m_hasQuit = true;\n }\n};\n\nTEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileNotStarted) {\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_THROW(factory->NewPacket(), autowiring_error) << \"Issuing a packet in a context that has not yet been started should throw an exception\";\n}\n\nTEST_F(AutoPacketFactoryTest, StopReallyStops) {\n AutoCurrentContext()->SignalShutdown();\n\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_TRUE(factory->ShouldStop()) << \"Expected that an attempt to insert a packet factory to an already-stopped context would stop the packet factory\";\n}\n\nTEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileStopped) {\n AutoCurrentContext()->SignalShutdown();\n\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_THROW(factory->NewPacket(), autowiring_error) << \"Issuing a packet in a context that has already been stopped should throw an exception\";\n}\n\nTEST_F(AutoPacketFactoryTest, WaitRunsDownAllPackets) {\n AutoCurrentContext()->Initiate();\n\n \/\/ Create a factory in our context, factory had better be started:\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_TRUE(factory->IsRunning()) << \"Factory was not started even though it was a member of an initiated context\";\n\n \/\/ Make the thread create and hold a packet, and then return\n AutoRequired<IssuesPacketWaitsThenQuits> ipwtq;\n \n \/\/ Shutdown context\n AutoCurrentContext()->SignalShutdown();\n\n \/\/ Now we're going to try to run down the factory:\n factory->Wait();\n\n \/\/ Verify that the thread has quit:\n ASSERT_TRUE(ipwtq->m_hasQuit) << \"AutoPacketFactory::Wait returned prematurely\";\n}\n\nclass HoldsAutoPacketFactoryReference {\npublic:\n HoldsAutoPacketFactoryReference(void):\n m_value(0)\n {}\n\n AutoRequired<AutoPacketFactory> m_factory;\n int m_value;\n\n \/\/ Just a dummy AutoFilter method so that this class is recognized as an AutoFilter\n void AutoFilter(int value) {\n m_value = value;\n }\n};\n\nTEST_F(AutoPacketFactoryTest, AutoPacketFactoryCycle) {\n std::weak_ptr<CoreContext> ctxtWeak;\n std::weak_ptr<HoldsAutoPacketFactoryReference> hapfrWeak;\n std::shared_ptr<AutoPacket> packet;\n\n {\n \/\/ Create a context, fill it up, kick it off:\n AutoCreateContext ctxt;\n AutoRequired<HoldsAutoPacketFactoryReference> hapfr(ctxt);\n ctxt->Initiate();\n \n \/\/ A weak pointer is used to detect object destruction\n ctxtWeak = ctxt;\n hapfrWeak = hapfr;\n\n \/\/ Trivial validation-of-reciept:\n AutoRequired<AutoPacketFactory> factory;\n {\n auto trivial = factory->NewPacket();\n trivial->Decorate((int) 54);\n ASSERT_EQ(54, hapfr->m_value) << \"A simple packet was not received as expected by an AutoFilter\";\n }\n\n \/\/ Create a packet which will force in a back-reference:\n packet = factory->NewPacket();\n\n \/\/ Terminate the context:\n ctxt->SignalShutdown();\n }\n\n \/\/ Verify that the context went out of scope as expected\n ASSERT_TRUE(ctxtWeak.expired()) << \"AutoPacketFactory incorrectly held a cyclic reference even after the context was shut down\";\n\n \/\/ Verify that we can still decorate the packet and also that the packet is delivered to the factory:\n packet->Decorate((int) 55);\n\n \/\/ Relock, verify the value was received by the hapfr:\n {\n auto locked = hapfrWeak.lock();\n ASSERT_TRUE(!!locked) << \"Failed to lock a shared pointer which should not have been expired yet\";\n ASSERT_EQ(55, locked->m_value) << \"AutoFilter did not receive a packet as expected\";\n }\n\n \/\/ Now we can release the packet and verify that everything gets cleaned up:\n packet.reset();\n ASSERT_TRUE(hapfrWeak.expired()) << \"The last packet from a factory was released; this should have resulted in teardown, but it did not\";\n}<commit_msg>Updating tests to validate packet delivery while the context is still resident<commit_after>#include \"stdafx.h\"\n#include \"AutoPacketFactoryTest.h\"\n#include \"CoreThread.h\"\n\nclass IssuesPacketWaitsThenQuits:\n public CoreThread\n{\npublic:\n IssuesPacketWaitsThenQuits(void) :\n m_hasQuit(false)\n {\n \/\/ Note: Don't do this in practice. This only works because we only inject this type\n \/\/ into a context that's already running; normally, creating a packet from our ctor can\n \/\/ cause an exception if we are being injected before Initiate is called.\n AutoRequired<AutoPacketFactory> factory;\n m_packet = factory->NewPacket();\n }\n\n bool m_hasQuit;\n std::shared_ptr<AutoPacket> m_packet;\n\n void Run(void) override {\n \/\/ Move the shared pointer here:\n auto packet = std::move(m_packet);\n \/\/ After moving the object, reset it to a known state\n m_packet.reset();\n\n \/\/ Just wait a bit, then return, just like we said we would\n this->ThreadSleep(boost::chrono::milliseconds(50));\n\n \/\/ Update our variable and then return out:\n m_hasQuit = true;\n }\n};\n\nTEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileNotStarted) {\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_THROW(factory->NewPacket(), autowiring_error) << \"Issuing a packet in a context that has not yet been started should throw an exception\";\n}\n\nTEST_F(AutoPacketFactoryTest, StopReallyStops) {\n AutoCurrentContext()->SignalShutdown();\n\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_TRUE(factory->ShouldStop()) << \"Expected that an attempt to insert a packet factory to an already-stopped context would stop the packet factory\";\n}\n\nTEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileStopped) {\n AutoCurrentContext()->SignalShutdown();\n\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_THROW(factory->NewPacket(), autowiring_error) << \"Issuing a packet in a context that has already been stopped should throw an exception\";\n}\n\nTEST_F(AutoPacketFactoryTest, WaitRunsDownAllPackets) {\n AutoCurrentContext()->Initiate();\n\n \/\/ Create a factory in our context, factory had better be started:\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_TRUE(factory->IsRunning()) << \"Factory was not started even though it was a member of an initiated context\";\n\n \/\/ Make the thread create and hold a packet, and then return\n AutoRequired<IssuesPacketWaitsThenQuits> ipwtq;\n \n \/\/ Shutdown context\n AutoCurrentContext()->SignalShutdown();\n\n \/\/ Now we're going to try to run down the factory:\n factory->Wait();\n\n \/\/ Verify that the thread has quit:\n ASSERT_TRUE(ipwtq->m_hasQuit) << \"AutoPacketFactory::Wait returned prematurely\";\n}\n\nclass HoldsAutoPacketFactoryReference {\npublic:\n HoldsAutoPacketFactoryReference(void):\n m_value(0)\n {}\n\n AutoRequired<AutoPacketFactory> m_factory;\n int m_value;\n\n \/\/ Just a dummy AutoFilter method so that this class is recognized as an AutoFilter\n void AutoFilter(int value) {\n m_value = value;\n }\n};\n\nTEST_F(AutoPacketFactoryTest, AutoPacketFactoryCycle) {\n std::weak_ptr<CoreContext> ctxtWeak;\n std::weak_ptr<HoldsAutoPacketFactoryReference> hapfrWeak;\n std::shared_ptr<AutoPacket> packet;\n\n {\n \/\/ Create a context, fill it up, kick it off:\n AutoCreateContext ctxt;\n AutoRequired<HoldsAutoPacketFactoryReference> hapfr(ctxt);\n ctxt->Initiate();\n \n \/\/ A weak pointer is used to detect object destruction\n ctxtWeak = ctxt;\n hapfrWeak = hapfr;\n\n \/\/ Trivial validation-of-reciept:\n AutoRequired<AutoPacketFactory> factory;\n {\n auto trivial = factory->NewPacket();\n trivial->Decorate((int) 54);\n ASSERT_EQ(54, hapfr->m_value) << \"A simple packet was not received as expected by an AutoFilter\";\n }\n\n \/\/ Create a packet which will force in a back-reference:\n packet = factory->NewPacket();\n\n \/\/ Terminate the context:\n ctxt->SignalShutdown();\n\n \/\/ Verify that we can still decorate the packet and also that the packet is delivered to the factory:\n packet->Decorate((int) 55);\n\n \/\/ Relock, verify the value was received by the hapfr:\n ASSERT_EQ(55, hapfr->m_value) << \"AutoFilter did not receive a packet as expected\";\n }\n\n \/\/ Verify that the context went out of scope as expected\n ASSERT_TRUE(ctxtWeak.expired()) << \"AutoPacketFactory incorrectly held a cyclic reference even after the context was shut down\";\n\n \/\/ Now we can release the packet and verify that everything gets cleaned up:\n packet.reset();\n ASSERT_TRUE(hapfrWeak.expired()) << \"The last packet from a factory was released; this should have resulted in teardown, but it did not\";\n}<|endoftext|>"} {"text":"<commit_before>\/*\n**\n** Author(s):\n** - Pierre ROULLON <proullon@aldebaran-robotics.com>\n**\n** Copyright (C) 2012, 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#include <qi\/anyobject.hpp>\n#include <qi\/jsoncodec.hpp>\n\n#include <jnitools.hpp>\n#include <object.hpp>\n#include <callbridge.hpp>\n#include <jobjectconverter.hpp>\n\nqiLogCategory(\"qimessaging.jni\");\n\nextern MethodInfoHandler gInfoHandler;\n\nstatic void adaptFuture(qi::Future<void> f, qi::Promise<qi::AnyValue> p)\n{\n if (f.hasError())\n p.setError(f.error());\n else\n p.setValue(qi::AnyValue(qi::typeOf<void>()));\n}\n\njlong Java_com_aldebaran_qi_AnyObject_property(JNIEnv* env, jobject jobj, jlong pObj, jstring name)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject*>(pObj));\n std::string propName = qi::jni::toString(name);\n\n qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();\n\n qi::jni::JNIAttach attach(env);\n\n try\n {\n *ret = obj.property<qi::AnyValue>(propName);\n } catch (qi::FutureUserException& e)\n {\n delete ret;\n throwJavaError(env, e.what());\n return 0;\n }\n\n return (jlong) ret;\n}\n\njlong Java_com_aldebaran_qi_AnyObject_setProperty(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObj, jstring name, jobject property)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject*>(pObj));\n std::string propName = qi::jni::toString(name);\n\n qi::jni::JNIAttach attach(env);\n\n qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();\n\n qi::Future<void> f = obj.setProperty(propName, qi::AnyValue::from<jobject>(property)).async();\n qi::Promise<qi::AnyValue> promise;\n *ret = promise.future();\n f.connect(adaptFuture, _1, promise);\n return (jlong) ret;\n}\n\njlong Java_com_aldebaran_qi_AnyObject_asyncCall(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject, jstring jmethod, jobjectArray args)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject*>(pObject));\n std::string method;\n qi::Future<qi::AnyValue>* fut = 0;\n\n qi::jni::JNIAttach attach(env);\n\n if (!obj)\n {\n qiLogError() << \"Given object not valid.\";\n throwJavaError(env, \"Given object is not valid.\");\n return 0;\n }\n\n \/\/ Get method name and parameters C style.\n method = qi::jni::toString(jmethod);\n try {\n fut = call_from_java(env, obj, method, args);\n } catch (std::exception& e)\n {\n throwJavaError(env, e.what());\n return 0;\n }\n\n return (jlong) fut;\n}\n\njstring Java_com_aldebaran_qi_AnyObject_printMetaObject(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject*>(pObject));\n std::stringstream ss;\n\n qi::details::printMetaObject(ss, obj.metaObject());\n return qi::jni::toJstring(ss.str());\n}\n\nvoid Java_com_aldebaran_qi_AnyObject_destroy(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(jobj), jlong pObject)\n{\n qi::AnyObject* obj = reinterpret_cast<qi::AnyObject*>(pObject);\n\n delete obj;\n}\n\n\njlong Java_com_aldebaran_qi_AnyObject_disconnect(JNIEnv *env, jobject jobj, jlong pObject, jlong subscriberId)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n try {\n obj.disconnect(subscriberId);\n } catch (std::exception& e)\n {\n throwJavaError(env, e.what());\n }\n return 0;\n}\n\n\njlong Java_com_aldebaran_qi_AnyObject_connect(JNIEnv *env, jobject jobj, jlong pObject, jstring method, jobject instance, jstring service, jstring eventName)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n std::string signature = qi::jni::toString(method);\n std::string event = qi::jni::toString(eventName);\n qi_method_info* data;\n std::vector<std::string> sigInfo;\n\n \/\/ Keep a pointer on JavaVM singleton if not already set.\n JVM(env);\n\n \/\/ Create a new global reference on object instance.\n \/\/ jobject structure are local reference and are destroyed when returning to JVM\n instance = env->NewGlobalRef(instance);\n\n \/\/ Remove return value\n sigInfo = qi::signatureSplit(signature);\n signature = sigInfo[1];\n signature.append(\"::\");\n signature.append(sigInfo[2]);\n\n \/\/ Create a struct holding a jobject instance, jmethodId id and other needed thing for callback\n \/\/ Pass it to void * data to register_method\n data = new qi_method_info(instance, signature, jobj);\n gInfoHandler.push(data);\n\n\n try {\n qi::SignalLink link =obj.connect(event,\n qi::SignalSubscriber(\n qi::AnyFunction::fromDynamicFunction(\n boost::bind(&event_callback_to_java, (void*) data, _1))).setCallType(qi::MetaCallType_Direct));\n return link;\n } catch (std::exception& e)\n {\n throwJavaError(env, e.what());\n return 0;\n }\n}\n\nvoid Java_com_aldebaran_qi_AnyObject_post(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pObject, jstring eventName, jobjectArray jargs)\n{\n qi::AnyObject obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n std::string event = qi::jni::toString(eventName);\n qi::GenericFunctionParameters params;\n std::string signature;\n jsize size;\n jsize i = 0;\n\n qi::jni::JNIAttach attach(env);\n\n size = env->GetArrayLength(jargs);\n i = 0;\n while (i < size)\n {\n jobject current = env->NewGlobalRef(env->GetObjectArrayElement(jargs, i));\n qi::AnyReference val = qi::AnyReference(AnyValue_from_JObject(current).first);\n params.push_back(val);\n i++;\n }\n\n \/\/ Signature construction\n signature = event + \"::(\";\n for (unsigned i=0; i< params.size(); ++i)\n signature += params[i].signature(true).toString();\n signature += \")\";\n\n try {\n obj.metaPost(event, params);\n } catch (std::exception& e)\n {\n throwJavaError(env, e.what());\n }\n\n \/\/ Destroy arguments\n i = 0;\n for(qi::GenericFunctionParameters::iterator it = params.begin(); it != params.end(); ++it)\n (*it).destroy();\n return;\n}\n\njobject Java_com_aldebaran_qi_AnyObject_decodeJSON(JNIEnv* env, jclass, jstring what)\n{\n std::string str = qi::jni::toString(what);\n qi::AnyValue val = qi::decodeJSON(str);\n return JObject_from_AnyValue(val.asReference());\n}\n\njstring Java_com_aldebaran_qi_AnyObject_encodeJSON(JNIEnv* env, jclass, jobject what)\n{\n std::string res = qi::encodeJSON(what);\n return qi::jni::toJstring(res);\n}\n<commit_msg>AnyObject.post: fix memory leak on arguments #21714<commit_after>\/*\n**\n** Author(s):\n** - Pierre ROULLON <proullon@aldebaran-robotics.com>\n**\n** Copyright (C) 2012, 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#include <qi\/anyobject.hpp>\n#include <qi\/jsoncodec.hpp>\n\n#include <jnitools.hpp>\n#include <object.hpp>\n#include <callbridge.hpp>\n#include <jobjectconverter.hpp>\n\nqiLogCategory(\"qimessaging.jni\");\n\nextern MethodInfoHandler gInfoHandler;\n\nstatic void adaptFuture(qi::Future<void> f, qi::Promise<qi::AnyValue> p)\n{\n if (f.hasError())\n p.setError(f.error());\n else\n p.setValue(qi::AnyValue(qi::typeOf<void>()));\n}\n\njlong Java_com_aldebaran_qi_AnyObject_property(JNIEnv* env, jobject jobj, jlong pObj, jstring name)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject*>(pObj));\n std::string propName = qi::jni::toString(name);\n\n qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();\n\n qi::jni::JNIAttach attach(env);\n\n try\n {\n *ret = obj.property<qi::AnyValue>(propName);\n } catch (qi::FutureUserException& e)\n {\n delete ret;\n throwJavaError(env, e.what());\n return 0;\n }\n\n return (jlong) ret;\n}\n\njlong Java_com_aldebaran_qi_AnyObject_setProperty(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObj, jstring name, jobject property)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject*>(pObj));\n std::string propName = qi::jni::toString(name);\n\n qi::jni::JNIAttach attach(env);\n\n qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();\n\n qi::Future<void> f = obj.setProperty(propName, qi::AnyValue::from<jobject>(property)).async();\n qi::Promise<qi::AnyValue> promise;\n *ret = promise.future();\n f.connect(adaptFuture, _1, promise);\n return (jlong) ret;\n}\n\njlong Java_com_aldebaran_qi_AnyObject_asyncCall(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject, jstring jmethod, jobjectArray args)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject*>(pObject));\n std::string method;\n qi::Future<qi::AnyValue>* fut = 0;\n\n qi::jni::JNIAttach attach(env);\n\n if (!obj)\n {\n qiLogError() << \"Given object not valid.\";\n throwJavaError(env, \"Given object is not valid.\");\n return 0;\n }\n\n \/\/ Get method name and parameters C style.\n method = qi::jni::toString(jmethod);\n try {\n fut = call_from_java(env, obj, method, args);\n } catch (std::exception& e)\n {\n throwJavaError(env, e.what());\n return 0;\n }\n\n return (jlong) fut;\n}\n\njstring Java_com_aldebaran_qi_AnyObject_printMetaObject(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject*>(pObject));\n std::stringstream ss;\n\n qi::details::printMetaObject(ss, obj.metaObject());\n return qi::jni::toJstring(ss.str());\n}\n\nvoid Java_com_aldebaran_qi_AnyObject_destroy(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(jobj), jlong pObject)\n{\n qi::AnyObject* obj = reinterpret_cast<qi::AnyObject*>(pObject);\n\n delete obj;\n}\n\n\njlong Java_com_aldebaran_qi_AnyObject_disconnect(JNIEnv *env, jobject jobj, jlong pObject, jlong subscriberId)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n try {\n obj.disconnect(subscriberId);\n } catch (std::exception& e)\n {\n throwJavaError(env, e.what());\n }\n return 0;\n}\n\n\njlong Java_com_aldebaran_qi_AnyObject_connect(JNIEnv *env, jobject jobj, jlong pObject, jstring method, jobject instance, jstring service, jstring eventName)\n{\n qi::AnyObject& obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n std::string signature = qi::jni::toString(method);\n std::string event = qi::jni::toString(eventName);\n qi_method_info* data;\n std::vector<std::string> sigInfo;\n\n \/\/ Keep a pointer on JavaVM singleton if not already set.\n JVM(env);\n\n \/\/ Create a new global reference on object instance.\n \/\/ jobject structure are local reference and are destroyed when returning to JVM\n instance = env->NewGlobalRef(instance);\n\n \/\/ Remove return value\n sigInfo = qi::signatureSplit(signature);\n signature = sigInfo[1];\n signature.append(\"::\");\n signature.append(sigInfo[2]);\n\n \/\/ Create a struct holding a jobject instance, jmethodId id and other needed thing for callback\n \/\/ Pass it to void * data to register_method\n data = new qi_method_info(instance, signature, jobj);\n gInfoHandler.push(data);\n\n\n try {\n qi::SignalLink link =obj.connect(event,\n qi::SignalSubscriber(\n qi::AnyFunction::fromDynamicFunction(\n boost::bind(&event_callback_to_java, (void*) data, _1))).setCallType(qi::MetaCallType_Direct));\n return link;\n } catch (std::exception& e)\n {\n throwJavaError(env, e.what());\n return 0;\n }\n}\n\nvoid Java_com_aldebaran_qi_AnyObject_post(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pObject, jstring eventName, jobjectArray jargs)\n{\n qi::AnyObject obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n std::string event = qi::jni::toString(eventName);\n qi::GenericFunctionParameters params;\n std::string signature;\n jsize size;\n jsize i = 0;\n\n qi::jni::JNIAttach attach(env);\n\n size = env->GetArrayLength(jargs);\n i = 0;\n while (i < size)\n {\n jobject current = env->GetObjectArrayElement(jargs, i);\n qi::AnyReference val = qi::AnyReference(AnyValue_from_JObject(current).first);\n params.push_back(val);\n i++;\n }\n\n \/\/ Signature construction\n signature = event + \"::(\";\n for (unsigned i=0; i< params.size(); ++i)\n signature += params[i].signature(true).toString();\n signature += \")\";\n\n try {\n obj.metaPost(event, params);\n } catch (std::exception& e)\n {\n throwJavaError(env, e.what());\n }\n\n \/\/ Destroy arguments\n i = 0;\n for(qi::GenericFunctionParameters::iterator it = params.begin(); it != params.end(); ++it)\n (*it).destroy();\n return;\n}\n\njobject Java_com_aldebaran_qi_AnyObject_decodeJSON(JNIEnv* env, jclass, jstring what)\n{\n std::string str = qi::jni::toString(what);\n qi::AnyValue val = qi::decodeJSON(str);\n return JObject_from_AnyValue(val.asReference());\n}\n\njstring Java_com_aldebaran_qi_AnyObject_encodeJSON(JNIEnv* env, jclass, jobject what)\n{\n std::string res = qi::encodeJSON(what);\n return qi::jni::toJstring(res);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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\n#include \"CachedCSSStyleSheet.h\"\n#include \"CachedResource.h\"\n#include \"CachedScript.h\"\n#include \"CachedXSLStyleSheet.h\"\n#include \"DocLoader.h\"\n#include \"Document.h\"\n#include \"DocumentLoader.h\"\n#include \"FrameLoader.h\"\n#include \"PlatformString.h\"\n#include \"ResourceError.h\"\n#include \"ResourceRequest.h\"\n#include \"ResourceResponse.h\"\n#include \"ScriptString.h\"\n#include \"TextEncoding.h\"\n#include <wtf\/CurrentTime.h>\n#undef LOG\n\n#include \"base\/basictypes.h\"\n#include \"base\/values.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"webkit\/glue\/devtools\/net_agent_impl.h\"\n#include \"webkit\/glue\/glue_util.h\"\n\nusing namespace WebCore;\n\nNetAgentImpl::NetAgentImpl(NetAgentDelegate* delegate)\n : delegate_(delegate),\n document_(NULL),\n main_loader_(NULL),\n last_cached_identifier_(-2),\n attached_(false) {\n}\n\nNetAgentImpl::~NetAgentImpl() {\n SetDocument(NULL);\n DidCommitMainResourceLoad();\n deleteAllValues(pending_resources_);\n pending_resources_.clear();\n}\n\nvoid NetAgentImpl::SetDocument(Document* doc) {\n document_ = doc;\n}\n\nvoid NetAgentImpl::Attach() {\n for (FinishedResources::iterator it = finished_resources_.begin();\n it != finished_resources_.end(); ++it) {\n DictionaryValue value;\n Serialize(*it->second, &value);\n delegate_->DidFinishLoading(it->first, value);\n }\n attached_ = true;\n}\n\nvoid NetAgentImpl::Detach() {\n attached_ = false;\n}\n\nvoid NetAgentImpl::DidCommitMainResourceLoad() {\n for (FinishedResources::iterator it = finished_resources_.begin();\n it != finished_resources_.end(); ++it) {\n delete it->second;\n }\n finished_resources_.clear();\n main_loader_ = NULL;\n}\n\nvoid NetAgentImpl::AssignIdentifierToRequest(\n DocumentLoader* loader,\n int identifier,\n const ResourceRequest& request) {\n}\n\nvoid NetAgentImpl::WillSendRequest(\n DocumentLoader* loader,\n int identifier,\n const ResourceRequest& request) {\n if (pending_resources_.contains(identifier)) {\n \/\/ We are going through redirect, nuke old resource.\n delete pending_resources_.get(identifier);\n }\n\n Resource* resource = new Resource();\n pending_resources_.set(identifier, resource);\n KURL url = request.url();\n resource->start_time = WTF::currentTime();\n resource->url = request.url();\n resource->request_headers = request.httpHeaderFields();\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->WillSendRequest(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidReceiveResponse(\n DocumentLoader* loader,\n int identifier,\n const ResourceResponse &response) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n\n KURL url = response.url();\n Resource* resource = pending_resources_.get(identifier);\n resource->response_received_time = WTF::currentTime();\n resource->expected_content_length =\n static_cast<int>(response.expectedContentLength());\n resource->http_status_code = response.httpStatusCode();\n resource->mime_type = response.mimeType();\n resource->suggested_filename = response.suggestedFilename();\n resource->response_headers = response.httpHeaderFields();\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->DidReceiveResponse(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidReceiveContentLength(\n DocumentLoader* loader,\n int identifier,\n int length) {\n}\n\nvoid NetAgentImpl::DidFinishLoading(\n DocumentLoader* loader,\n int identifier) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n\n \/\/ This is the first command being dispatched after\n \/\/ DidCommitMainResourceLoad, we know that the first resource to be reported\n \/\/ as loaded is main resource.\n if (!main_loader_.get()) {\n main_loader_ = loader;\n }\n\n Resource* resource = pending_resources_.get(identifier);\n resource->end_time = WTF::currentTime();\n\n pending_resources_.remove(identifier);\n finished_resources_.append(std::make_pair(identifier, resource));\n\n \/\/ Start removing resources from the cache once there are too many of them.\n if (finished_resources_.size() > 200) {\n for (int i = 0; i < 50; ++i) {\n xml_http_sources_.remove(finished_resources_[i].first);\n delete finished_resources_[i].second;\n }\n finished_resources_.remove(0, 50);\n }\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->DidFinishLoading(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidFailLoading(\n DocumentLoader* loader,\n int identifier,\n const ResourceError& error) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n Resource* resource = pending_resources_.get(identifier);\n resource->error_code = error.errorCode();\n resource->error_description = error.localizedDescription();\n DidFinishLoading(loader, identifier);\n}\n\nvoid NetAgentImpl::DidLoadResourceFromMemoryCache(\n DocumentLoader* loader,\n const ResourceRequest& request,\n const ResourceResponse& response,\n int length) {\n int identifier = last_cached_identifier_--;\n}\n\nvoid NetAgentImpl::DidLoadResourceByXMLHttpRequest(\n int identifier,\n const WebCore::ScriptString& source) {\n xml_http_sources_.set(identifier, source);\n}\n\nvoid NetAgentImpl::GetResourceContent(\n int call_id,\n int identifier,\n const String& url) {\n if (!document_) {\n return;\n }\n\n String source;\n\n WebCore::ScriptString script = xml_http_sources_.get(identifier);\n if (!script.isNull()) {\n source = String(script);\n } else if (main_loader_.get() && main_loader_->requestURL() == url) {\n RefPtr<SharedBuffer> buffer = main_loader_->mainResourceData();\n String text_encoding_name = document_->inputEncoding();\n if (buffer) {\n WebCore::TextEncoding encoding(text_encoding_name);\n if (!encoding.isValid())\n encoding = WindowsLatin1Encoding();\n source = encoding.decode(buffer->data(), buffer->size());\n }\n } else {\n CachedResource* cached_resource = document_->\n docLoader()->cachedResource(url);\n if (!cached_resource) {\n delegate_->GetResourceContentResult(call_id, \"\");\n return;\n }\n if (cached_resource->isPurgeable()) {\n \/\/ If the resource is purgeable then make it unpurgeable to get its data.\n \/\/ This might fail, in which case we return an empty string.\n if (!cached_resource->makePurgeable(false)) {\n delegate_->GetResourceContentResult(call_id, \"\");\n return;\n }\n }\n\n \/\/ Try to get the decoded source. Only applies to some CachedResource\n \/\/ types.\n switch (cached_resource->type()) {\n case CachedResource::CSSStyleSheet: {\n CachedCSSStyleSheet *sheet =\n reinterpret_cast<CachedCSSStyleSheet*>(cached_resource);\n source = sheet->sheetText();\n break;\n }\n case CachedResource::Script: {\n CachedScript *script =\n reinterpret_cast<CachedScript*>(cached_resource);\n source = script->script();\n break;\n }\n#if ENABLE(XSLT)\n case CachedResource::XSLStyleSheet: {\n CachedXSLStyleSheet *sheet =\n reinterpret_cast<CachedXSLStyleSheet*>(cached_resource);\n source = sheet->sheet();\n break;\n }\n#endif\n default:\n break;\n }\n }\n delegate_->GetResourceContentResult(call_id,\n webkit_glue::StringToStdString(source));\n}\n\n\/\/ static\nValue* NetAgentImpl::BuildValueForHeaders(const HTTPHeaderMap& headers) {\n OwnPtr<DictionaryValue> value(new DictionaryValue());\n HTTPHeaderMap::const_iterator end = headers.end();\n for (HTTPHeaderMap::const_iterator it = headers.begin(); it != end; ++it) {\n value->SetString(webkit_glue::StringToStdWString(it->first),\n webkit_glue::StringToStdString(it->second));\n }\n return value.release();\n}\n\n\/\/ static\nvoid NetAgentImpl::Serialize(const Resource& resource,\n DictionaryValue* value) {\n value->SetReal(L\"startTime\", resource.start_time);\n value->SetReal(L\"responseReceivedTime\", resource.response_received_time);\n value->SetReal(L\"endTime\", resource.end_time);\n\n value->SetString(L\"url\",\n webkit_glue::StringToStdString(resource.url.string()));\n value->SetString(L\"domain\",\n webkit_glue::StringToStdString(resource.url.host()));\n value->SetString(L\"path\",\n webkit_glue::StringToStdString(resource.url.path()));\n value->SetString(\n L\"lastPathComponent\",\n webkit_glue::StringToStdString(resource.url.lastPathComponent()));\n\n value->SetString(L\"mimeType\",\n webkit_glue::StringToStdWString(resource.mime_type));\n value->SetString(L\"suggestedFilename\",\n webkit_glue::StringToStdWString(resource.suggested_filename));\n\n value->SetInteger(L\"expectedContentLength\",\n resource.expected_content_length);\n value->SetInteger(L\"responseStatusCode\", resource.http_status_code);\n\n value->Set(L\"requestHeaders\",\n BuildValueForHeaders(resource.request_headers));\n value->Set(L\"responseHeaders\",\n BuildValueForHeaders(resource.response_headers));\n\n if (resource.error_code) {\n value->SetInteger(L\"errorCode\", resource.error_code);\n value->SetString(L\"localizedDescription\",\n webkit_glue::StringToStdString(resource.error_description));\n }\n}\n<commit_msg>DevTools: do not cache xmlhttp when client is not attached; reduce agent cache size. Review URL: http:\/\/codereview.chromium.org\/115508<commit_after>\/\/ 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\n#include \"CachedCSSStyleSheet.h\"\n#include \"CachedResource.h\"\n#include \"CachedScript.h\"\n#include \"CachedXSLStyleSheet.h\"\n#include \"DocLoader.h\"\n#include \"Document.h\"\n#include \"DocumentLoader.h\"\n#include \"FrameLoader.h\"\n#include \"PlatformString.h\"\n#include \"ResourceError.h\"\n#include \"ResourceRequest.h\"\n#include \"ResourceResponse.h\"\n#include \"ScriptString.h\"\n#include \"TextEncoding.h\"\n#include <wtf\/CurrentTime.h>\n#undef LOG\n\n#include \"base\/basictypes.h\"\n#include \"base\/values.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"webkit\/glue\/devtools\/net_agent_impl.h\"\n#include \"webkit\/glue\/glue_util.h\"\n\nusing namespace WebCore;\n\nNetAgentImpl::NetAgentImpl(NetAgentDelegate* delegate)\n : delegate_(delegate),\n document_(NULL),\n main_loader_(NULL),\n last_cached_identifier_(-2),\n attached_(false) {\n}\n\nNetAgentImpl::~NetAgentImpl() {\n SetDocument(NULL);\n DidCommitMainResourceLoad();\n deleteAllValues(pending_resources_);\n pending_resources_.clear();\n}\n\nvoid NetAgentImpl::SetDocument(Document* doc) {\n document_ = doc;\n}\n\nvoid NetAgentImpl::Attach() {\n for (FinishedResources::iterator it = finished_resources_.begin();\n it != finished_resources_.end(); ++it) {\n DictionaryValue value;\n Serialize(*it->second, &value);\n delegate_->DidFinishLoading(it->first, value);\n }\n attached_ = true;\n}\n\nvoid NetAgentImpl::Detach() {\n attached_ = false;\n xml_http_sources_.clear();\n ExpireFinishedResourcesCache();\n}\n\nvoid NetAgentImpl::DidCommitMainResourceLoad() {\n for (FinishedResources::iterator it = finished_resources_.begin();\n it != finished_resources_.end(); ++it) {\n delete it->second;\n }\n finished_resources_.clear();\n main_loader_ = NULL;\n}\n\nvoid NetAgentImpl::AssignIdentifierToRequest(\n DocumentLoader* loader,\n int identifier,\n const ResourceRequest& request) {\n}\n\nvoid NetAgentImpl::WillSendRequest(\n DocumentLoader* loader,\n int identifier,\n const ResourceRequest& request) {\n if (pending_resources_.contains(identifier)) {\n \/\/ We are going through redirect, nuke old resource.\n delete pending_resources_.get(identifier);\n }\n\n Resource* resource = new Resource();\n pending_resources_.set(identifier, resource);\n KURL url = request.url();\n resource->start_time = WTF::currentTime();\n resource->url = request.url();\n resource->request_headers = request.httpHeaderFields();\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->WillSendRequest(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidReceiveResponse(\n DocumentLoader* loader,\n int identifier,\n const ResourceResponse &response) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n\n KURL url = response.url();\n Resource* resource = pending_resources_.get(identifier);\n resource->response_received_time = WTF::currentTime();\n resource->expected_content_length =\n static_cast<int>(response.expectedContentLength());\n resource->http_status_code = response.httpStatusCode();\n resource->mime_type = response.mimeType();\n resource->suggested_filename = response.suggestedFilename();\n resource->response_headers = response.httpHeaderFields();\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->DidReceiveResponse(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidReceiveContentLength(\n DocumentLoader* loader,\n int identifier,\n int length) {\n}\n\nvoid NetAgentImpl::DidFinishLoading(\n DocumentLoader* loader,\n int identifier) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n\n \/\/ This is the first command being dispatched after\n \/\/ DidCommitMainResourceLoad, we know that the first resource to be reported\n \/\/ as loaded is main resource.\n if (!main_loader_.get()) {\n main_loader_ = loader;\n }\n\n Resource* resource = pending_resources_.get(identifier);\n resource->end_time = WTF::currentTime();\n\n pending_resources_.remove(identifier);\n finished_resources_.append(std::make_pair(identifier, resource));\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->DidFinishLoading(identifier, value);\n } else {\n ExpireFinishedResourcesCache();\n }\n}\n\nvoid NetAgentImpl::DidFailLoading(\n DocumentLoader* loader,\n int identifier,\n const ResourceError& error) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n Resource* resource = pending_resources_.get(identifier);\n resource->error_code = error.errorCode();\n resource->error_description = error.localizedDescription();\n DidFinishLoading(loader, identifier);\n}\n\nvoid NetAgentImpl::DidLoadResourceFromMemoryCache(\n DocumentLoader* loader,\n const ResourceRequest& request,\n const ResourceResponse& response,\n int length) {\n int identifier = last_cached_identifier_--;\n}\n\nvoid NetAgentImpl::DidLoadResourceByXMLHttpRequest(\n int identifier,\n const WebCore::ScriptString& source) {\n if (attached_) {\n \/\/ Only store XmlHttpRequests data when client is attached.\n xml_http_sources_.set(identifier, source);\n }\n}\n\nvoid NetAgentImpl::GetResourceContent(\n int call_id,\n int identifier,\n const String& url) {\n if (!document_) {\n return;\n }\n\n String source;\n\n WebCore::ScriptString script = xml_http_sources_.get(identifier);\n if (!script.isNull()) {\n source = String(script);\n } else if (main_loader_.get() && main_loader_->requestURL() == url) {\n RefPtr<SharedBuffer> buffer = main_loader_->mainResourceData();\n String text_encoding_name = document_->inputEncoding();\n if (buffer) {\n WebCore::TextEncoding encoding(text_encoding_name);\n if (!encoding.isValid())\n encoding = WindowsLatin1Encoding();\n source = encoding.decode(buffer->data(), buffer->size());\n }\n } else {\n CachedResource* cached_resource = document_->\n docLoader()->cachedResource(url);\n if (!cached_resource) {\n delegate_->GetResourceContentResult(call_id, \"\");\n return;\n }\n if (cached_resource->isPurgeable()) {\n \/\/ If the resource is purgeable then make it unpurgeable to get its data.\n \/\/ This might fail, in which case we return an empty string.\n if (!cached_resource->makePurgeable(false)) {\n delegate_->GetResourceContentResult(call_id, \"\");\n return;\n }\n }\n\n \/\/ Try to get the decoded source. Only applies to some CachedResource\n \/\/ types.\n switch (cached_resource->type()) {\n case CachedResource::CSSStyleSheet: {\n CachedCSSStyleSheet *sheet =\n reinterpret_cast<CachedCSSStyleSheet*>(cached_resource);\n source = sheet->sheetText();\n break;\n }\n case CachedResource::Script: {\n CachedScript *script =\n reinterpret_cast<CachedScript*>(cached_resource);\n source = script->script();\n break;\n }\n#if ENABLE(XSLT)\n case CachedResource::XSLStyleSheet: {\n CachedXSLStyleSheet *sheet =\n reinterpret_cast<CachedXSLStyleSheet*>(cached_resource);\n source = sheet->sheet();\n break;\n }\n#endif\n default:\n break;\n }\n }\n delegate_->GetResourceContentResult(call_id,\n webkit_glue::StringToStdString(source));\n}\n\n\/\/ static\nValue* NetAgentImpl::BuildValueForHeaders(const HTTPHeaderMap& headers) {\n OwnPtr<DictionaryValue> value(new DictionaryValue());\n HTTPHeaderMap::const_iterator end = headers.end();\n for (HTTPHeaderMap::const_iterator it = headers.begin(); it != end; ++it) {\n value->SetString(webkit_glue::StringToStdWString(it->first),\n webkit_glue::StringToStdString(it->second));\n }\n return value.release();\n}\n\n\/\/ static\nvoid NetAgentImpl::Serialize(const Resource& resource,\n DictionaryValue* value) {\n value->SetReal(L\"startTime\", resource.start_time);\n value->SetReal(L\"responseReceivedTime\", resource.response_received_time);\n value->SetReal(L\"endTime\", resource.end_time);\n\n value->SetString(L\"url\",\n webkit_glue::StringToStdString(resource.url.string()));\n value->SetString(L\"domain\",\n webkit_glue::StringToStdString(resource.url.host()));\n value->SetString(L\"path\",\n webkit_glue::StringToStdString(resource.url.path()));\n value->SetString(\n L\"lastPathComponent\",\n webkit_glue::StringToStdString(resource.url.lastPathComponent()));\n\n value->SetString(L\"mimeType\",\n webkit_glue::StringToStdWString(resource.mime_type));\n value->SetString(L\"suggestedFilename\",\n webkit_glue::StringToStdWString(resource.suggested_filename));\n\n value->SetInteger(L\"expectedContentLength\",\n resource.expected_content_length);\n value->SetInteger(L\"responseStatusCode\", resource.http_status_code);\n\n value->Set(L\"requestHeaders\",\n BuildValueForHeaders(resource.request_headers));\n value->Set(L\"responseHeaders\",\n BuildValueForHeaders(resource.response_headers));\n\n if (resource.error_code) {\n value->SetInteger(L\"errorCode\", resource.error_code);\n value->SetString(L\"localizedDescription\",\n webkit_glue::StringToStdString(resource.error_description));\n }\n}\n\nvoid NetAgentImpl::ExpireFinishedResourcesCache() {\n if (finished_resources_.size() > 100) {\n for (int i = 0; i < 20; ++i) {\n delete finished_resources_[i].second;\n }\n finished_resources_.remove(0, 20);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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\n#include \"CachedCSSStyleSheet.h\"\n#include \"CachedResource.h\"\n#include \"CachedScript.h\"\n#include \"CachedXSLStyleSheet.h\"\n#include \"DocLoader.h\"\n#include \"Document.h\"\n#include \"DocumentLoader.h\"\n#include \"FrameLoader.h\"\n#include \"PlatformString.h\"\n#include \"ResourceError.h\"\n#include \"ResourceRequest.h\"\n#include \"ResourceResponse.h\"\n#include \"ScriptString.h\"\n#include \"TextEncoding.h\"\n#include <wtf\/CurrentTime.h>\n#undef LOG\n\n#include \"base\/basictypes.h\"\n#include \"base\/values.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"webkit\/glue\/devtools\/net_agent_impl.h\"\n#include \"webkit\/glue\/glue_util.h\"\n\nusing namespace WebCore;\n\nNetAgentImpl::NetAgentImpl(NetAgentDelegate* delegate)\n : delegate_(delegate),\n document_(NULL),\n main_loader_(NULL),\n last_cached_identifier_(-2),\n attached_(false) {\n}\n\nNetAgentImpl::~NetAgentImpl() {\n SetDocument(NULL);\n DidCommitMainResourceLoad();\n deleteAllValues(pending_resources_);\n pending_resources_.clear();\n}\n\nvoid NetAgentImpl::SetDocument(Document* doc) {\n document_ = doc;\n}\n\nvoid NetAgentImpl::Attach() {\n for (FinishedResources::iterator it = finished_resources_.begin();\n it != finished_resources_.end(); ++it) {\n DictionaryValue value;\n Serialize(*it->second, &value);\n delegate_->DidFinishLoading(it->first, value);\n }\n attached_ = true;\n}\n\nvoid NetAgentImpl::Detach() {\n attached_ = false;\n}\n\nvoid NetAgentImpl::DidCommitMainResourceLoad() {\n for (FinishedResources::iterator it = finished_resources_.begin();\n it != finished_resources_.end(); ++it) {\n delete it->second;\n }\n finished_resources_.clear();\n main_loader_ = NULL;\n}\n\nvoid NetAgentImpl::AssignIdentifierToRequest(\n DocumentLoader* loader,\n int identifier,\n const ResourceRequest& request) {\n}\n\nvoid NetAgentImpl::WillSendRequest(\n DocumentLoader* loader,\n int identifier,\n const ResourceRequest& request) {\n if (pending_resources_.contains(identifier)) {\n \/\/ We are going through redirect, nuke old resource.\n delete pending_resources_.get(identifier);\n }\n\n Resource* resource = new Resource();\n pending_resources_.set(identifier, resource);\n KURL url = request.url();\n resource->start_time = WTF::currentTime();\n resource->url = request.url();\n resource->request_headers = request.httpHeaderFields();\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->WillSendRequest(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidReceiveResponse(\n DocumentLoader* loader,\n int identifier,\n const ResourceResponse &response) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n\n KURL url = response.url();\n Resource* resource = pending_resources_.get(identifier);\n resource->response_received_time = WTF::currentTime();\n resource->expected_content_length =\n static_cast<int>(response.expectedContentLength());\n resource->http_status_code = response.httpStatusCode();\n resource->mime_type = response.mimeType();\n resource->suggested_filename = response.suggestedFilename();\n resource->response_headers = response.httpHeaderFields();\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->DidReceiveResponse(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidReceiveContentLength(\n DocumentLoader* loader,\n int identifier,\n int length) {\n}\n\nvoid NetAgentImpl::DidFinishLoading(\n DocumentLoader* loader,\n int identifier) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n\n \/\/ This is the first command being dispatched after\n \/\/ DidCommitMainResourceLoad, we know that the first resource to be reported\n \/\/ as loaded is main resource.\n if (!main_loader_.get()) {\n main_loader_ = loader;\n }\n\n Resource* resource = pending_resources_.get(identifier);\n resource->end_time = WTF::currentTime();\n\n pending_resources_.remove(identifier);\n finished_resources_.append(std::make_pair(identifier, resource));\n\n \/\/ Start removing resources from the cache once there are too many of them.\n if (finished_resources_.size() > 200) {\n for (int i = 0; i < 50; ++i) {\n xml_http_sources_.remove(finished_resources_[i].first);\n delete finished_resources_[i].second;\n }\n finished_resources_.remove(0, 50);\n }\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->DidFinishLoading(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidFailLoading(\n DocumentLoader* loader,\n int identifier,\n const ResourceError& error) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n Resource* resource = pending_resources_.get(identifier);\n resource->error_code = error.errorCode();\n resource->error_description = error.localizedDescription();\n DidFinishLoading(loader, identifier);\n}\n\nvoid NetAgentImpl::DidLoadResourceFromMemoryCache(\n DocumentLoader* loader,\n const ResourceRequest& request,\n const ResourceResponse& response,\n int length) {\n int identifier = last_cached_identifier_--;\n}\n\nvoid NetAgentImpl::DidLoadResourceByXMLHttpRequest(\n int identifier,\n const WebCore::ScriptString& source) {\n xml_http_sources_.set(identifier, source);\n}\n\nvoid NetAgentImpl::GetResourceContent(\n int call_id,\n int identifier,\n const String& url) {\n if (!document_) {\n return;\n }\n\n String source;\n\n WebCore::ScriptString script = xml_http_sources_.get(identifier);\n if (!script.isNull()) {\n source = String(script);\n } else if (main_loader_.get() && main_loader_->requestURL() == url) {\n RefPtr<SharedBuffer> buffer = main_loader_->mainResourceData();\n String text_encoding_name = document_->inputEncoding();\n if (buffer) {\n WebCore::TextEncoding encoding(text_encoding_name);\n if (!encoding.isValid())\n encoding = WindowsLatin1Encoding();\n source = encoding.decode(buffer->data(), buffer->size());\n }\n } else {\n CachedResource* cached_resource = document_->\n docLoader()->cachedResource(url);\n if (!cached_resource) {\n delegate_->GetResourceContentResult(call_id, \"\");\n return;\n }\n if (cached_resource->isPurgeable()) {\n \/\/ If the resource is purgeable then make it unpurgeable to get its data.\n \/\/ This might fail, in which case we return an empty string.\n if (!cached_resource->makePurgeable(false)) {\n delegate_->GetResourceContentResult(call_id, \"\");\n return;\n }\n }\n\n \/\/ Try to get the decoded source. Only applies to some CachedResource\n \/\/ types.\n switch (cached_resource->type()) {\n case CachedResource::CSSStyleSheet: {\n CachedCSSStyleSheet *sheet =\n reinterpret_cast<CachedCSSStyleSheet*>(cached_resource);\n source = sheet->sheetText();\n break;\n }\n case CachedResource::Script: {\n CachedScript *script =\n reinterpret_cast<CachedScript*>(cached_resource);\n source = script->script();\n break;\n }\n#if ENABLE(XSLT)\n case CachedResource::XSLStyleSheet: {\n CachedXSLStyleSheet *sheet =\n reinterpret_cast<CachedXSLStyleSheet*>(cached_resource);\n source = sheet->sheet();\n break;\n }\n#endif\n default:\n break;\n }\n }\n delegate_->GetResourceContentResult(call_id,\n webkit_glue::StringToStdString(source));\n}\n\n\/\/ static\nValue* NetAgentImpl::BuildValueForHeaders(const HTTPHeaderMap& headers) {\n OwnPtr<DictionaryValue> value(new DictionaryValue());\n HTTPHeaderMap::const_iterator end = headers.end();\n for (HTTPHeaderMap::const_iterator it = headers.begin(); it != end; ++it) {\n value->SetString(webkit_glue::StringToStdWString(it->first),\n webkit_glue::StringToStdString(it->second));\n }\n return value.release();\n}\n\n\/\/ static\nvoid NetAgentImpl::Serialize(const Resource& resource,\n DictionaryValue* value) {\n value->SetReal(L\"startTime\", resource.start_time);\n value->SetReal(L\"responseReceivedTime\", resource.response_received_time);\n value->SetReal(L\"endTime\", resource.end_time);\n\n value->SetString(L\"url\",\n webkit_glue::StringToStdString(resource.url.string()));\n value->SetString(L\"domain\",\n webkit_glue::StringToStdString(resource.url.host()));\n value->SetString(L\"path\",\n webkit_glue::StringToStdString(resource.url.path()));\n value->SetString(\n L\"lastPathComponent\",\n webkit_glue::StringToStdString(resource.url.lastPathComponent()));\n\n value->SetString(L\"mimeType\",\n webkit_glue::StringToStdWString(resource.mime_type));\n value->SetString(L\"suggestedFilename\",\n webkit_glue::StringToStdWString(resource.suggested_filename));\n\n value->SetInteger(L\"expectedContentLength\",\n resource.expected_content_length);\n value->SetInteger(L\"responseStatusCode\", resource.http_status_code);\n\n value->Set(L\"requestHeaders\",\n BuildValueForHeaders(resource.request_headers));\n value->Set(L\"responseHeaders\",\n BuildValueForHeaders(resource.response_headers));\n\n if (resource.error_code) {\n value->SetInteger(L\"errorCode\", resource.error_code);\n value->SetString(L\"localizedDescription\",\n webkit_glue::StringToStdString(resource.error_description));\n }\n}\n<commit_msg>DevTools: do not cache xmlhttp when client is not attached; reduce agent cache size. Review URL: http:\/\/codereview.chromium.org\/115508<commit_after>\/\/ 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\n#include \"CachedCSSStyleSheet.h\"\n#include \"CachedResource.h\"\n#include \"CachedScript.h\"\n#include \"CachedXSLStyleSheet.h\"\n#include \"DocLoader.h\"\n#include \"Document.h\"\n#include \"DocumentLoader.h\"\n#include \"FrameLoader.h\"\n#include \"PlatformString.h\"\n#include \"ResourceError.h\"\n#include \"ResourceRequest.h\"\n#include \"ResourceResponse.h\"\n#include \"ScriptString.h\"\n#include \"TextEncoding.h\"\n#include <wtf\/CurrentTime.h>\n#undef LOG\n\n#include \"base\/basictypes.h\"\n#include \"base\/values.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"webkit\/glue\/devtools\/net_agent_impl.h\"\n#include \"webkit\/glue\/glue_util.h\"\n\nusing namespace WebCore;\n\nNetAgentImpl::NetAgentImpl(NetAgentDelegate* delegate)\n : delegate_(delegate),\n document_(NULL),\n main_loader_(NULL),\n last_cached_identifier_(-2),\n attached_(false) {\n}\n\nNetAgentImpl::~NetAgentImpl() {\n SetDocument(NULL);\n DidCommitMainResourceLoad();\n deleteAllValues(pending_resources_);\n pending_resources_.clear();\n}\n\nvoid NetAgentImpl::SetDocument(Document* doc) {\n document_ = doc;\n}\n\nvoid NetAgentImpl::Attach() {\n for (FinishedResources::iterator it = finished_resources_.begin();\n it != finished_resources_.end(); ++it) {\n DictionaryValue value;\n Serialize(*it->second, &value);\n delegate_->DidFinishLoading(it->first, value);\n }\n attached_ = true;\n}\n\nvoid NetAgentImpl::Detach() {\n attached_ = false;\n xml_http_sources_.clear();\n ExpireFinishedResourcesCache();\n}\n\nvoid NetAgentImpl::DidCommitMainResourceLoad() {\n for (FinishedResources::iterator it = finished_resources_.begin();\n it != finished_resources_.end(); ++it) {\n delete it->second;\n }\n finished_resources_.clear();\n main_loader_ = NULL;\n}\n\nvoid NetAgentImpl::AssignIdentifierToRequest(\n DocumentLoader* loader,\n int identifier,\n const ResourceRequest& request) {\n}\n\nvoid NetAgentImpl::WillSendRequest(\n DocumentLoader* loader,\n int identifier,\n const ResourceRequest& request) {\n if (pending_resources_.contains(identifier)) {\n \/\/ We are going through redirect, nuke old resource.\n delete pending_resources_.get(identifier);\n }\n\n Resource* resource = new Resource();\n pending_resources_.set(identifier, resource);\n KURL url = request.url();\n resource->start_time = WTF::currentTime();\n resource->url = request.url();\n resource->request_headers = request.httpHeaderFields();\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->WillSendRequest(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidReceiveResponse(\n DocumentLoader* loader,\n int identifier,\n const ResourceResponse &response) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n\n KURL url = response.url();\n Resource* resource = pending_resources_.get(identifier);\n resource->response_received_time = WTF::currentTime();\n resource->expected_content_length =\n static_cast<int>(response.expectedContentLength());\n resource->http_status_code = response.httpStatusCode();\n resource->mime_type = response.mimeType();\n resource->suggested_filename = response.suggestedFilename();\n resource->response_headers = response.httpHeaderFields();\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->DidReceiveResponse(identifier, value);\n }\n}\n\nvoid NetAgentImpl::DidReceiveContentLength(\n DocumentLoader* loader,\n int identifier,\n int length) {\n}\n\nvoid NetAgentImpl::DidFinishLoading(\n DocumentLoader* loader,\n int identifier) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n\n \/\/ This is the first command being dispatched after\n \/\/ DidCommitMainResourceLoad, we know that the first resource to be reported\n \/\/ as loaded is main resource.\n if (!main_loader_.get()) {\n main_loader_ = loader;\n }\n\n Resource* resource = pending_resources_.get(identifier);\n resource->end_time = WTF::currentTime();\n\n pending_resources_.remove(identifier);\n finished_resources_.append(std::make_pair(identifier, resource));\n\n if (attached_) {\n DictionaryValue value;\n Serialize(*resource, &value);\n delegate_->DidFinishLoading(identifier, value);\n } else {\n ExpireFinishedResourcesCache();\n }\n}\n\nvoid NetAgentImpl::DidFailLoading(\n DocumentLoader* loader,\n int identifier,\n const ResourceError& error) {\n if (!pending_resources_.contains(identifier)) {\n return;\n }\n Resource* resource = pending_resources_.get(identifier);\n resource->error_code = error.errorCode();\n resource->error_description = error.localizedDescription();\n DidFinishLoading(loader, identifier);\n}\n\nvoid NetAgentImpl::DidLoadResourceFromMemoryCache(\n DocumentLoader* loader,\n const ResourceRequest& request,\n const ResourceResponse& response,\n int length) {\n int identifier = last_cached_identifier_--;\n}\n\nvoid NetAgentImpl::DidLoadResourceByXMLHttpRequest(\n int identifier,\n const WebCore::ScriptString& source) {\n if (attached_) {\n \/\/ Only store XmlHttpRequests data when client is attached.\n xml_http_sources_.set(identifier, source);\n }\n}\n\nvoid NetAgentImpl::GetResourceContent(\n int call_id,\n int identifier,\n const String& url) {\n if (!document_) {\n return;\n }\n\n String source;\n\n WebCore::ScriptString script = xml_http_sources_.get(identifier);\n if (!script.isNull()) {\n source = String(script);\n } else if (main_loader_.get() && main_loader_->requestURL() == url) {\n RefPtr<SharedBuffer> buffer = main_loader_->mainResourceData();\n String text_encoding_name = document_->inputEncoding();\n if (buffer) {\n WebCore::TextEncoding encoding(text_encoding_name);\n if (!encoding.isValid())\n encoding = WindowsLatin1Encoding();\n source = encoding.decode(buffer->data(), buffer->size());\n }\n } else {\n CachedResource* cached_resource = document_->\n docLoader()->cachedResource(url);\n if (!cached_resource) {\n delegate_->GetResourceContentResult(call_id, \"\");\n return;\n }\n if (cached_resource->isPurgeable()) {\n \/\/ If the resource is purgeable then make it unpurgeable to get its data.\n \/\/ This might fail, in which case we return an empty string.\n if (!cached_resource->makePurgeable(false)) {\n delegate_->GetResourceContentResult(call_id, \"\");\n return;\n }\n }\n\n \/\/ Try to get the decoded source. Only applies to some CachedResource\n \/\/ types.\n switch (cached_resource->type()) {\n case CachedResource::CSSStyleSheet: {\n CachedCSSStyleSheet *sheet =\n reinterpret_cast<CachedCSSStyleSheet*>(cached_resource);\n source = sheet->sheetText();\n break;\n }\n case CachedResource::Script: {\n CachedScript *script =\n reinterpret_cast<CachedScript*>(cached_resource);\n source = script->script();\n break;\n }\n#if ENABLE(XSLT)\n case CachedResource::XSLStyleSheet: {\n CachedXSLStyleSheet *sheet =\n reinterpret_cast<CachedXSLStyleSheet*>(cached_resource);\n source = sheet->sheet();\n break;\n }\n#endif\n default:\n break;\n }\n }\n delegate_->GetResourceContentResult(call_id,\n webkit_glue::StringToStdString(source));\n}\n\n\/\/ static\nValue* NetAgentImpl::BuildValueForHeaders(const HTTPHeaderMap& headers) {\n OwnPtr<DictionaryValue> value(new DictionaryValue());\n HTTPHeaderMap::const_iterator end = headers.end();\n for (HTTPHeaderMap::const_iterator it = headers.begin(); it != end; ++it) {\n value->SetString(webkit_glue::StringToStdWString(it->first),\n webkit_glue::StringToStdString(it->second));\n }\n return value.release();\n}\n\n\/\/ static\nvoid NetAgentImpl::Serialize(const Resource& resource,\n DictionaryValue* value) {\n value->SetReal(L\"startTime\", resource.start_time);\n value->SetReal(L\"responseReceivedTime\", resource.response_received_time);\n value->SetReal(L\"endTime\", resource.end_time);\n\n value->SetString(L\"url\",\n webkit_glue::StringToStdString(resource.url.string()));\n value->SetString(L\"domain\",\n webkit_glue::StringToStdString(resource.url.host()));\n value->SetString(L\"path\",\n webkit_glue::StringToStdString(resource.url.path()));\n value->SetString(\n L\"lastPathComponent\",\n webkit_glue::StringToStdString(resource.url.lastPathComponent()));\n\n value->SetString(L\"mimeType\",\n webkit_glue::StringToStdWString(resource.mime_type));\n value->SetString(L\"suggestedFilename\",\n webkit_glue::StringToStdWString(resource.suggested_filename));\n\n value->SetInteger(L\"expectedContentLength\",\n resource.expected_content_length);\n value->SetInteger(L\"responseStatusCode\", resource.http_status_code);\n\n value->Set(L\"requestHeaders\",\n BuildValueForHeaders(resource.request_headers));\n value->Set(L\"responseHeaders\",\n BuildValueForHeaders(resource.response_headers));\n\n if (resource.error_code) {\n value->SetInteger(L\"errorCode\", resource.error_code);\n value->SetString(L\"localizedDescription\",\n webkit_glue::StringToStdString(resource.error_description));\n }\n}\n\nvoid NetAgentImpl::ExpireFinishedResourcesCache() {\n if (finished_resources_.size() > 100) {\n for (int i = 0; i < 20; ++i) {\n delete finished_resources_[i].second;\n }\n finished_resources_.remove(0, 20);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===========================================================================*\\\n * *\n * OpenMesh *\n * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen *\n * www.openmesh.org *\n * *\n *---------------------------------------------------------------------------* \n * This file is part of OpenMesh. *\n * *\n * OpenMesh is free software: you can redistribute it and\/or modify * \n * it under the terms of the GNU Lesser General Public License as *\n * published by the Free Software Foundation, either version 3 of *\n * the License, or (at your option) any later version with the *\n * following exceptions: *\n * *\n * If other files instantiate templates or use macros *\n * or inline functions from this file, or you compile this file and *\n * link it with other files to produce an executable, this file does *\n * not by itself cause the resulting executable to be covered by the *\n * GNU Lesser General Public License. This exception does not however *\n * invalidate any other reasons why the executable file might be *\n * covered by the GNU Lesser General Public License. *\n * *\n * OpenMesh 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 for more details. *\n * *\n * You should have received a copy of the GNU LesserGeneral Public *\n * License along with OpenMesh. If not, *\n * see <http:\/\/www.gnu.org\/licenses\/>. *\n * *\n\\*===========================================================================*\/ \n\n\/*===========================================================================*\\\n * * \n * $Revision$ *\n * $Date$ *\n * *\n\\*===========================================================================*\/\n\n\/** \\file ModBaseT.hh\n Base class for all decimation modules.\n *\/\n\n\/\/=============================================================================\n\/\/\n\/\/ CLASS ModBaseT\n\/\/\n\/\/=============================================================================\n\n#ifndef OPENMESH_DECIMATER_MODBASET_HH\n#define OPENMESH_DECIMATER_MODBASET_HH\n\n\n\/\/== INCLUDES =================================================================\n\n#include <OpenMesh\/Core\/Utils\/Noncopyable.hh>\n#include <OpenMesh\/Tools\/Decimater\/CollapseInfoT.hh>\n#include <string>\n\n\n\/\/== NAMESPACE ================================================================\n\nnamespace OpenMesh {\nnamespace Decimater {\n\n\n\/\/== FORWARD DECLARATIONS =====================================================\n\ntemplate <typename Mesh> class BaseDecimaterT;\n\n\n\/\/== CLASS DEFINITION =========================================================\n\n\/** Handle for mesh decimation modules\n \\internal\n *\/\n\ntemplate <typename Module>\nclass ModHandleT : private Utils::Noncopyable\n{\npublic:\n\n typedef ModHandleT<Module> Self;\n typedef Module module_type;\n\npublic:\n\n \/\/\/ Default constructor\n ModHandleT() : mod_(NULL) {} \n\n \/\/\/ Destructor\n ~ModHandleT() { \/* don't delete mod_, since handle is not owner! *\/ }\n \n \/\/\/ Check handle status\n \/\/\/ \\return \\c true, if handle is valid, else \\c false.\n bool is_valid() const { return mod_ != NULL; }\n\nprivate:\n\n#if defined(OM_CC_MSVC)\n friend class BaseDecimaterT;\n#else\n template <typename Mesh> friend class BaseDecimaterT;\n#endif\n\n void clear() { mod_ = NULL; }\n void init(Module* _m) { mod_ = _m; }\n Module* module() { return mod_; }\n\n\nprivate:\n\n Module* mod_;\n\n};\n\n\n\n\n\/\/== CLASS DEFINITION =========================================================\n\n\n\n\/\/\/ Macro that sets up the name() function\n\/\/\/ \\internal\n#define DECIMATER_MODNAME(_mod_name) \\\n virtual const std::string& name() const { \\\n static std::string _s_modname_(#_mod_name); return _s_modname_; \\\n}\n\n\n\/** Convenience macro, to be used in derived modules\n * The macro defines the types \n * - \\c Handle, type of the module's handle.\n * - \\c Base, type of ModBaseT<>.\n * - \\c Mesh, type of the associated mesh passed by the decimater type.\n * - \\c CollapseInfo, to your convenience\n * and uses DECIMATER_MODNAME() to define the name of the module.\n * \n * \\param Classname The name of the derived class.\n * \\param DecimaterT Pass here the decimater type, which is the \n * template parameter passed to ModBaseT.\n * \\param Name Give the module a name.\n *\/\n#define DECIMATING_MODULE(Classname, MeshT, Name)\t\\\n typedef Classname < MeshT > Self;\t\t\\\n typedef OpenMesh::Decimater::ModHandleT< Self > Handle; \\\n typedef OpenMesh::Decimater::ModBaseT< MeshT > Base; \\\n typedef typename Base::Mesh Mesh;\t\t\\\n typedef typename Base::CollapseInfo CollapseInfo;\t\\\n DECIMATER_MODNAME( Name )\n\n\n\n\/\/== CLASS DEFINITION =========================================================\n\n\n\/** Base class for all decimation modules.\n\n Each module has to implement this interface.\n To build your own module you have to \n -# derive from this class.\n -# create the basic settings with DECIMATING_MODULE().\n -# override collapse_priority(), if necessary.\n -# override initialize(), if necessary.\n -# override postprocess_collapse(), if necessary.\n\n A module has two major working modes:\n -# binary mode\n -# non-binary mode\n\n In the binary mode collapse_priority() checks a constraint and\n returns LEGAL_COLLAPSE or ILLEGAL_COLLAPSE.\n\n In the non-binary mode the module computes a float error value in\n the range [0, inf) and returns it. In the case a constraint has\n been set, e.g. the error must be lower than a upper bound, and the\n constraint is violated, collapse_priority() must return\n ILLEGAL_COLLAPSE.\n\n \\see collapse_priority()\n\n \\todo \"Tutorial on building a custom decimation module.\"\n\n*\/\n\ntemplate <typename MeshT>\nclass ModBaseT\n{\npublic:\n typedef MeshT Mesh;\n typedef CollapseInfoT<MeshT> CollapseInfo;\n\n enum {\n ILLEGAL_COLLAPSE = -1, \/\/\/< indicates an illegal collapse\n LEGAL_COLLAPSE = 0 \/\/\/< indicates a legal collapse\n };\n\nprotected:\n \n \/\/\/ Default constructor\n \/\/\/ \\see \\ref decimater_docu\n ModBaseT(MeshT& _mesh, bool _is_binary)\n : mesh_(_mesh), is_binary_(_is_binary) {}\n\npublic:\n\n \/\/\/ Virtual desctructor\n virtual ~ModBaseT() { } \n\n \/\/\/ Set module's name (using DECIMATER_MODNAME macro)\n DECIMATER_MODNAME(ModBase);\n \n\n \/\/\/ Returns true if criteria returns a binary value.\n bool is_binary(void) const { return is_binary_; }\n\n \/\/\/ Set whether module is binary or not.\n void set_binary(bool _b) { is_binary_ = _b; }\n\n\npublic: \/\/ common interface\n \n \/\/\/ Initialize module-internal stuff\n virtual void initialize() { }\n\n \/** Return collapse priority. \n *\n * In the binary mode collapse_priority() checks a constraint and\n * returns LEGAL_COLLAPSE or ILLEGAL_COLLAPSE.\n *\n * In the non-binary mode the module computes a float error value in\n * the range [0, inf) and returns it. In the case a constraint has\n * been set, e.g. the error must be lower than a upper bound, and the\n * constraint is violated, collapse_priority() must return\n * ILLEGAL_COLLAPSE.\n *\n * \\return Collapse priority in the range [0,inf), \n * \\c LEGAL_COLLAPSE or \\c ILLEGAL_COLLAPSE.\n *\/\n virtual float collapse_priority(const CollapseInfoT<MeshT>& \/* _ci *\/)\n { return LEGAL_COLLAPSE; }\n\n \/** Before _from_vh has been collapsed into _to_vh, this method\n will be called.\n *\/\n virtual void preprocess_collapse(const CollapseInfoT<MeshT>& \/* _ci *\/)\n {}\n\n \/** After _from_vh has been collapsed into _to_vh, this method\n will be called. \n *\/\n virtual void postprocess_collapse(const CollapseInfoT<MeshT>& \/* _ci *\/)\n {}\n\n\n\nprotected:\n\n \/\/\/ Access the mesh associated with the decimater.\n MeshT& mesh() { return mesh_; }\n\nprivate:\n\n \/\/ hide copy constructor & assignemnt\n ModBaseT(const ModBaseT& _cpy);\n ModBaseT& operator=(const ModBaseT& );\n\n MeshT& mesh_;\n\n bool is_binary_;\n};\n\n\n\/\/=============================================================================\n} \/\/ namespace Decimater\n} \/\/ namespace OpenMesh\n\/\/=============================================================================\n#endif \/\/ OPENMESH_DECIMATER_MODBASE_HH defined\n\/\/=============================================================================\n\n<commit_msg>- fix doc warning<commit_after>\/*===========================================================================*\\\n * *\n * OpenMesh *\n * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen *\n * www.openmesh.org *\n * *\n *---------------------------------------------------------------------------* \n * This file is part of OpenMesh. *\n * *\n * OpenMesh is free software: you can redistribute it and\/or modify * \n * it under the terms of the GNU Lesser General Public License as *\n * published by the Free Software Foundation, either version 3 of *\n * the License, or (at your option) any later version with the *\n * following exceptions: *\n * *\n * If other files instantiate templates or use macros *\n * or inline functions from this file, or you compile this file and *\n * link it with other files to produce an executable, this file does *\n * not by itself cause the resulting executable to be covered by the *\n * GNU Lesser General Public License. This exception does not however *\n * invalidate any other reasons why the executable file might be *\n * covered by the GNU Lesser General Public License. *\n * *\n * OpenMesh 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 for more details. *\n * *\n * You should have received a copy of the GNU LesserGeneral Public *\n * License along with OpenMesh. If not, *\n * see <http:\/\/www.gnu.org\/licenses\/>. *\n * *\n\\*===========================================================================*\/ \n\n\/*===========================================================================*\\\n * * \n * $Revision$ *\n * $Date$ *\n * *\n\\*===========================================================================*\/\n\n\/** \\file ModBaseT.hh\n Base class for all decimation modules.\n *\/\n\n\/\/=============================================================================\n\/\/\n\/\/ CLASS ModBaseT\n\/\/\n\/\/=============================================================================\n\n#ifndef OPENMESH_DECIMATER_MODBASET_HH\n#define OPENMESH_DECIMATER_MODBASET_HH\n\n\n\/\/== INCLUDES =================================================================\n\n#include <OpenMesh\/Core\/Utils\/Noncopyable.hh>\n#include <OpenMesh\/Tools\/Decimater\/CollapseInfoT.hh>\n#include <string>\n\n\n\/\/== NAMESPACE ================================================================\n\nnamespace OpenMesh {\nnamespace Decimater {\n\n\n\/\/== FORWARD DECLARATIONS =====================================================\n\ntemplate <typename Mesh> class BaseDecimaterT;\n\n\n\/\/== CLASS DEFINITION =========================================================\n\n\/** Handle for mesh decimation modules\n \\internal\n *\/\n\ntemplate <typename Module>\nclass ModHandleT : private Utils::Noncopyable\n{\npublic:\n\n typedef ModHandleT<Module> Self;\n typedef Module module_type;\n\npublic:\n\n \/\/\/ Default constructor\n ModHandleT() : mod_(NULL) {} \n\n \/\/\/ Destructor\n ~ModHandleT() { \/* don't delete mod_, since handle is not owner! *\/ }\n \n \/\/\/ Check handle status\n \/\/\/ \\return \\c true, if handle is valid, else \\c false.\n bool is_valid() const { return mod_ != NULL; }\n\nprivate:\n\n#if defined(OM_CC_MSVC)\n friend class BaseDecimaterT;\n#else\n template <typename Mesh> friend class BaseDecimaterT;\n#endif\n\n void clear() { mod_ = NULL; }\n void init(Module* _m) { mod_ = _m; }\n Module* module() { return mod_; }\n\n\nprivate:\n\n Module* mod_;\n\n};\n\n\n\n\n\/\/== CLASS DEFINITION =========================================================\n\n\n\n\/\/\/ Macro that sets up the name() function\n\/\/\/ \\internal\n#define DECIMATER_MODNAME(_mod_name) \\\n virtual const std::string& name() const { \\\n static std::string _s_modname_(#_mod_name); return _s_modname_; \\\n}\n\n\n\/** Convenience macro, to be used in derived modules\n * The macro defines the types \n * - \\c Handle, type of the module's handle.\n * - \\c Base, type of ModBaseT<>.\n * - \\c Mesh, type of the associated mesh passed by the decimater type.\n * - \\c CollapseInfo, to your convenience\n * and uses DECIMATER_MODNAME() to define the name of the module.\n * \n * \\param Classname The name of the derived class.\n * \\param MeshT Pass here the mesh type, which is the\n * template parameter passed to ModBaseT.\n * \\param Name Give the module a name.\n *\/\n#define DECIMATING_MODULE(Classname, MeshT, Name)\t\\\n typedef Classname < MeshT > Self;\t\t\\\n typedef OpenMesh::Decimater::ModHandleT< Self > Handle; \\\n typedef OpenMesh::Decimater::ModBaseT< MeshT > Base; \\\n typedef typename Base::Mesh Mesh;\t\t\\\n typedef typename Base::CollapseInfo CollapseInfo;\t\\\n DECIMATER_MODNAME( Name )\n\n\n\n\/\/== CLASS DEFINITION =========================================================\n\n\n\/** Base class for all decimation modules.\n\n Each module has to implement this interface.\n To build your own module you have to \n -# derive from this class.\n -# create the basic settings with DECIMATING_MODULE().\n -# override collapse_priority(), if necessary.\n -# override initialize(), if necessary.\n -# override postprocess_collapse(), if necessary.\n\n A module has two major working modes:\n -# binary mode\n -# non-binary mode\n\n In the binary mode collapse_priority() checks a constraint and\n returns LEGAL_COLLAPSE or ILLEGAL_COLLAPSE.\n\n In the non-binary mode the module computes a float error value in\n the range [0, inf) and returns it. In the case a constraint has\n been set, e.g. the error must be lower than a upper bound, and the\n constraint is violated, collapse_priority() must return\n ILLEGAL_COLLAPSE.\n\n \\see collapse_priority()\n\n \\todo \"Tutorial on building a custom decimation module.\"\n\n*\/\n\ntemplate <typename MeshT>\nclass ModBaseT\n{\npublic:\n typedef MeshT Mesh;\n typedef CollapseInfoT<MeshT> CollapseInfo;\n\n enum {\n ILLEGAL_COLLAPSE = -1, \/\/\/< indicates an illegal collapse\n LEGAL_COLLAPSE = 0 \/\/\/< indicates a legal collapse\n };\n\nprotected:\n \n \/\/\/ Default constructor\n \/\/\/ \\see \\ref decimater_docu\n ModBaseT(MeshT& _mesh, bool _is_binary)\n : mesh_(_mesh), is_binary_(_is_binary) {}\n\npublic:\n\n \/\/\/ Virtual desctructor\n virtual ~ModBaseT() { } \n\n \/\/\/ Set module's name (using DECIMATER_MODNAME macro)\n DECIMATER_MODNAME(ModBase);\n \n\n \/\/\/ Returns true if criteria returns a binary value.\n bool is_binary(void) const { return is_binary_; }\n\n \/\/\/ Set whether module is binary or not.\n void set_binary(bool _b) { is_binary_ = _b; }\n\n\npublic: \/\/ common interface\n \n \/\/\/ Initialize module-internal stuff\n virtual void initialize() { }\n\n \/** Return collapse priority. \n *\n * In the binary mode collapse_priority() checks a constraint and\n * returns LEGAL_COLLAPSE or ILLEGAL_COLLAPSE.\n *\n * In the non-binary mode the module computes a float error value in\n * the range [0, inf) and returns it. In the case a constraint has\n * been set, e.g. the error must be lower than a upper bound, and the\n * constraint is violated, collapse_priority() must return\n * ILLEGAL_COLLAPSE.\n *\n * \\return Collapse priority in the range [0,inf), \n * \\c LEGAL_COLLAPSE or \\c ILLEGAL_COLLAPSE.\n *\/\n virtual float collapse_priority(const CollapseInfoT<MeshT>& \/* _ci *\/)\n { return LEGAL_COLLAPSE; }\n\n \/** Before _from_vh has been collapsed into _to_vh, this method\n will be called.\n *\/\n virtual void preprocess_collapse(const CollapseInfoT<MeshT>& \/* _ci *\/)\n {}\n\n \/** After _from_vh has been collapsed into _to_vh, this method\n will be called. \n *\/\n virtual void postprocess_collapse(const CollapseInfoT<MeshT>& \/* _ci *\/)\n {}\n\n\n\nprotected:\n\n \/\/\/ Access the mesh associated with the decimater.\n MeshT& mesh() { return mesh_; }\n\nprivate:\n\n \/\/ hide copy constructor & assignemnt\n ModBaseT(const ModBaseT& _cpy);\n ModBaseT& operator=(const ModBaseT& );\n\n MeshT& mesh_;\n\n bool is_binary_;\n};\n\n\n\/\/=============================================================================\n} \/\/ namespace Decimater\n} \/\/ namespace OpenMesh\n\/\/=============================================================================\n#endif \/\/ OPENMESH_DECIMATER_MODBASE_HH defined\n\/\/=============================================================================\n\n<|endoftext|>"} {"text":"<commit_before>#include <GL\/glew.h>\n#include \"EditorWindow.hpp\"\n\n#include \"Util\/EditorSettings.hpp\"\n#include <Engine\/Util\/Log.hpp>\n\n#include \"GUI\/ImageButton.hpp\"\n#include \"GUI\/ImageTextButton.hpp\"\n#include <Engine\/Resources.hpp>\n#include <File.png.hpp>\n#include <Options.png.hpp>\n#include <Play.png.hpp>\n#include <NewHymn.png.hpp>\n#include <OpenHymn.png.hpp>\n#include <ABeeZee.ttf.hpp>\n#include <Engine\/Hymn.hpp>\n#include <Engine\/Util\/FileSystem.hpp>\n\nEditorWindow::EditorWindow() : Container(nullptr) {\n glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);\n\n \/\/ Enable debug context and set message callback.\n if (EditorSettings::GetInstance().GetBool(\"Debug Context\"))\n glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);\n \n window = glfwCreateWindow(640, 480, \"Hymn to Beauty\", nullptr, nullptr);\n if (!window) {\n glfwTerminate();\n \/\/\/ @todo Print error to log.\n }\n\n glfwMakeContextCurrent(window);\n\n gameWindow = nullptr;\n childWindow = nullptr;\n input = new InputHandler(window);\n}\n\nEditorWindow::~EditorWindow() {\n delete fileButton;\n delete optionsButton;\n delete playButton;\n delete menuBar;\n \n delete newHymnButton;\n delete openHymnButton;\n delete fileMenu;\n \n Resources().FreeTexture2D(fileTexture);\n Resources().FreeTexture2D(optionsTexture);\n Resources().FreeTexture2D(playTexture);\n \n Resources().FreeTexture2D(newHymnTexture);\n Resources().FreeTexture2D(openHymnTexture);\n \n delete input;\n \n Resources().FreeFont(font);\n \n glfwDestroyWindow(window);\n}\n\nvoid EditorWindow::Init() {\n int width, height;\n glfwGetWindowSize(window, &width, &height);\n \n font = Resources().CreateFontEmbedded(ABEEZEE_TTF, ABEEZEE_TTF_LENGTH, 24.f);\n \n \/\/ Menu bar.\n menuBar = new GUI::HorizontalLayout(this);\n menuBar->SetSize(glm::vec2(static_cast<float>(width), 64.f));\n AddWidget(menuBar);\n \n fileTexture = Resources().CreateTexture2D(FILE_PNG, FILE_PNG_LENGTH);\n fileButton = new GUI::ImageButton(menuBar, fileTexture);\n fileButton->SetClickedCallback(std::bind(&OpenFileMenu, this));\n menuBar->AddWidget(fileButton);\n \n optionsTexture = Resources().CreateTexture2D(OPTIONS_PNG, OPTIONS_PNG_LENGTH);\n optionsButton = new GUI::ImageButton(menuBar, optionsTexture);\n optionsButton->SetClickedCallback(std::bind(&OpenProjectOptions, this));\n menuBar->AddWidget(optionsButton);\n \n playTexture = Resources().CreateTexture2D(PLAY_PNG, PLAY_PNG_LENGTH);\n playButton = new GUI::ImageButton(menuBar, playTexture);\n playButton->SetClickedCallback(std::bind(&Play, this));\n menuBar->AddWidget(playButton);\n \n \/\/ File menu.\n fileMenu = new GUI::VerticalLayout(this);\n fileMenu->SetSize(glm::vec2(256.f, 2.f * 64.f));\n fileMenu->SetPosition(glm::vec2(0.f, 64.f));\n fileMenu->SetVisible(false);\n AddWidget(fileMenu);\n \n newHymnTexture = Resources().CreateTexture2D(NEWHYMN_PNG, NEWHYMN_PNG_LENGTH);\n newHymnButton = new GUI::ImageTextButton(fileMenu, newHymnTexture, font, \"New Hymn\");\n newHymnButton->SetSize(glm::vec2(256.f, 64.f));\n newHymnButton->SetClickedCallback(std::bind(&NewHymn, this));\n fileMenu->AddWidget(newHymnButton);\n \n openHymnTexture = Resources().CreateTexture2D(OPENHYMN_PNG, OPENHYMN_PNG_LENGTH);\n openHymnButton = new GUI::ImageTextButton(fileMenu, openHymnTexture, font, \"Open Hymn\");\n openHymnButton->SetSize(glm::vec2(256.f, 64.f));\n openHymnButton->SetClickedCallback(std::bind(&OpenHymn, this));\n fileMenu->AddWidget(openHymnButton);\n \n glEnable(GL_DEPTH_TEST);\n}\n\nbool EditorWindow::ShouldClose() const {\n return (glfwWindowShouldClose(window) != 0);\n}\n\nvoid EditorWindow::Update() {\n \/\/ Handle running game.\n if (gameWindow != nullptr) {\n gameWindow->Update();\n if (gameWindow->ShouldClose()) {\n delete gameWindow;\n gameWindow = nullptr;\n }\n } else if (childWindow != nullptr) {\n input->Update();\n input->SetActive();\n childWindow->Update();\n } else if (glfwGetKey(window, GLFW_KEY_F5) == GLFW_PRESS) {\n Play();\n } else {\n input->Update();\n input->SetActive();\n UpdateWidgets();\n }\n}\n\nvoid EditorWindow::Render() {\n int width, height;\n glfwGetWindowSize(window, &width, &height);\n \n Render(glm::vec2(static_cast<float>(width), static_cast<float>(height)));\n}\n\nvoid EditorWindow::Render(const glm::vec2& screenSize) {\n if (gameWindow != nullptr) {\n gameWindow->Render();\n } else {\n glfwMakeContextCurrent(window);\n \n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n \n RenderWidgets(screenSize);\n \n if (childWindow != nullptr)\n childWindow->Render(screenSize);\n \n glfwSwapBuffers(window);\n }\n}\n\nglm::vec2 EditorWindow::Size() const {\n int width, height;\n glfwGetWindowSize(window, &width, &height);\n \n return glm::vec2(static_cast<float>(width), static_cast<float>(height));\n}\n\nvoid EditorWindow::SetSize(const glm::vec2& size) {\n \/\/\/ @todo Resize window.\n}\n\nvoid EditorWindow::OpenFileMenu() {\n fileMenu->SetVisible(!fileMenu->Visible());\n}\n\nvoid EditorWindow::OpenProjectOptions() {\n \/\/\/@todo Project options\n Log() << \"Click test!\\n\";\n}\n\nvoid EditorWindow::Play() {\n gameWindow = new GameWindow();\n}\n\nvoid EditorWindow::NewHymn() {\n childWindow = new GUI::SelectHymnWindow(this);\n childWindow->SetPosition(glm::vec2(0.f, 0.f));\n childWindow->SetSize(Size());\n childWindow->SetClosedCallback(std::bind(&NewHymnClosed, this, std::placeholders::_1));\n}\n\nvoid EditorWindow::NewHymnClosed(const std::string& hymn) {\n \/\/ Create new hymn\n if (!hymn.empty()) {\n Hymn().Clear();\n Hymn().SetPath(FileSystem::DataPath(\"Hymn to Beauty\", hymn.c_str()));\n }\n \n delete childWindow;\n childWindow = nullptr;\n}\n\nvoid EditorWindow::OpenHymn() {\n childWindow = new GUI::SelectHymnWindow(this);\n childWindow->SetPosition(glm::vec2(0.f, 0.f));\n childWindow->SetSize(Size());\n childWindow->SetClosedCallback(std::bind(&OpenHymnClosed, this, std::placeholders::_1));\n}\n\nvoid EditorWindow::OpenHymnClosed(const std::string& hymn) {\n \/\/ Open hymn.\n if (!hymn.empty())\n Hymn().Load(FileSystem::DataPath(\"Hymn to Beauty\", hymn.c_str()));\n \n delete childWindow;\n childWindow = nullptr;\n}\n<commit_msg>Hide file menu after selecting a hymn.<commit_after>#include <GL\/glew.h>\n#include \"EditorWindow.hpp\"\n\n#include \"Util\/EditorSettings.hpp\"\n#include <Engine\/Util\/Log.hpp>\n\n#include \"GUI\/ImageButton.hpp\"\n#include \"GUI\/ImageTextButton.hpp\"\n#include <Engine\/Resources.hpp>\n#include <File.png.hpp>\n#include <Options.png.hpp>\n#include <Play.png.hpp>\n#include <NewHymn.png.hpp>\n#include <OpenHymn.png.hpp>\n#include <ABeeZee.ttf.hpp>\n#include <Engine\/Hymn.hpp>\n#include <Engine\/Util\/FileSystem.hpp>\n\nEditorWindow::EditorWindow() : Container(nullptr) {\n glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);\n\n \/\/ Enable debug context and set message callback.\n if (EditorSettings::GetInstance().GetBool(\"Debug Context\"))\n glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);\n \n window = glfwCreateWindow(640, 480, \"Hymn to Beauty\", nullptr, nullptr);\n if (!window) {\n glfwTerminate();\n \/\/\/ @todo Print error to log.\n }\n\n glfwMakeContextCurrent(window);\n\n gameWindow = nullptr;\n childWindow = nullptr;\n input = new InputHandler(window);\n}\n\nEditorWindow::~EditorWindow() {\n delete fileButton;\n delete optionsButton;\n delete playButton;\n delete menuBar;\n \n delete newHymnButton;\n delete openHymnButton;\n delete fileMenu;\n \n Resources().FreeTexture2D(fileTexture);\n Resources().FreeTexture2D(optionsTexture);\n Resources().FreeTexture2D(playTexture);\n \n Resources().FreeTexture2D(newHymnTexture);\n Resources().FreeTexture2D(openHymnTexture);\n \n delete input;\n \n Resources().FreeFont(font);\n \n glfwDestroyWindow(window);\n}\n\nvoid EditorWindow::Init() {\n int width, height;\n glfwGetWindowSize(window, &width, &height);\n \n font = Resources().CreateFontEmbedded(ABEEZEE_TTF, ABEEZEE_TTF_LENGTH, 24.f);\n \n \/\/ Menu bar.\n menuBar = new GUI::HorizontalLayout(this);\n menuBar->SetSize(glm::vec2(static_cast<float>(width), 64.f));\n AddWidget(menuBar);\n \n fileTexture = Resources().CreateTexture2D(FILE_PNG, FILE_PNG_LENGTH);\n fileButton = new GUI::ImageButton(menuBar, fileTexture);\n fileButton->SetClickedCallback(std::bind(&OpenFileMenu, this));\n menuBar->AddWidget(fileButton);\n \n optionsTexture = Resources().CreateTexture2D(OPTIONS_PNG, OPTIONS_PNG_LENGTH);\n optionsButton = new GUI::ImageButton(menuBar, optionsTexture);\n optionsButton->SetClickedCallback(std::bind(&OpenProjectOptions, this));\n menuBar->AddWidget(optionsButton);\n \n playTexture = Resources().CreateTexture2D(PLAY_PNG, PLAY_PNG_LENGTH);\n playButton = new GUI::ImageButton(menuBar, playTexture);\n playButton->SetClickedCallback(std::bind(&Play, this));\n menuBar->AddWidget(playButton);\n \n \/\/ File menu.\n fileMenu = new GUI::VerticalLayout(this);\n fileMenu->SetSize(glm::vec2(256.f, 2.f * 64.f));\n fileMenu->SetPosition(glm::vec2(0.f, 64.f));\n fileMenu->SetVisible(false);\n AddWidget(fileMenu);\n \n newHymnTexture = Resources().CreateTexture2D(NEWHYMN_PNG, NEWHYMN_PNG_LENGTH);\n newHymnButton = new GUI::ImageTextButton(fileMenu, newHymnTexture, font, \"New Hymn\");\n newHymnButton->SetSize(glm::vec2(256.f, 64.f));\n newHymnButton->SetClickedCallback(std::bind(&NewHymn, this));\n fileMenu->AddWidget(newHymnButton);\n \n openHymnTexture = Resources().CreateTexture2D(OPENHYMN_PNG, OPENHYMN_PNG_LENGTH);\n openHymnButton = new GUI::ImageTextButton(fileMenu, openHymnTexture, font, \"Open Hymn\");\n openHymnButton->SetSize(glm::vec2(256.f, 64.f));\n openHymnButton->SetClickedCallback(std::bind(&OpenHymn, this));\n fileMenu->AddWidget(openHymnButton);\n \n glEnable(GL_DEPTH_TEST);\n}\n\nbool EditorWindow::ShouldClose() const {\n return (glfwWindowShouldClose(window) != 0);\n}\n\nvoid EditorWindow::Update() {\n \/\/ Handle running game.\n if (gameWindow != nullptr) {\n gameWindow->Update();\n if (gameWindow->ShouldClose()) {\n delete gameWindow;\n gameWindow = nullptr;\n }\n } else if (childWindow != nullptr) {\n input->Update();\n input->SetActive();\n childWindow->Update();\n } else if (glfwGetKey(window, GLFW_KEY_F5) == GLFW_PRESS) {\n Play();\n } else {\n input->Update();\n input->SetActive();\n UpdateWidgets();\n }\n}\n\nvoid EditorWindow::Render() {\n int width, height;\n glfwGetWindowSize(window, &width, &height);\n \n Render(glm::vec2(static_cast<float>(width), static_cast<float>(height)));\n}\n\nvoid EditorWindow::Render(const glm::vec2& screenSize) {\n if (gameWindow != nullptr) {\n gameWindow->Render();\n } else {\n glfwMakeContextCurrent(window);\n \n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n \n RenderWidgets(screenSize);\n \n if (childWindow != nullptr)\n childWindow->Render(screenSize);\n \n glfwSwapBuffers(window);\n }\n}\n\nglm::vec2 EditorWindow::Size() const {\n int width, height;\n glfwGetWindowSize(window, &width, &height);\n \n return glm::vec2(static_cast<float>(width), static_cast<float>(height));\n}\n\nvoid EditorWindow::SetSize(const glm::vec2& size) {\n \/\/\/ @todo Resize window.\n}\n\nvoid EditorWindow::OpenFileMenu() {\n fileMenu->SetVisible(!fileMenu->Visible());\n}\n\nvoid EditorWindow::OpenProjectOptions() {\n \/\/\/@todo Project options\n Log() << \"Click test!\\n\";\n}\n\nvoid EditorWindow::Play() {\n gameWindow = new GameWindow();\n}\n\nvoid EditorWindow::NewHymn() {\n childWindow = new GUI::SelectHymnWindow(this);\n childWindow->SetPosition(glm::vec2(0.f, 0.f));\n childWindow->SetSize(Size());\n childWindow->SetClosedCallback(std::bind(&NewHymnClosed, this, std::placeholders::_1));\n}\n\nvoid EditorWindow::NewHymnClosed(const std::string& hymn) {\n \/\/ Create new hymn\n if (!hymn.empty()) {\n Hymn().Clear();\n Hymn().SetPath(FileSystem::DataPath(\"Hymn to Beauty\", hymn.c_str()));\n }\n \n delete childWindow;\n childWindow = nullptr;\n \n fileMenu->SetVisible(false);\n}\n\nvoid EditorWindow::OpenHymn() {\n childWindow = new GUI::SelectHymnWindow(this);\n childWindow->SetPosition(glm::vec2(0.f, 0.f));\n childWindow->SetSize(Size());\n childWindow->SetClosedCallback(std::bind(&OpenHymnClosed, this, std::placeholders::_1));\n}\n\nvoid EditorWindow::OpenHymnClosed(const std::string& hymn) {\n \/\/ Open hymn.\n if (!hymn.empty())\n Hymn().Load(FileSystem::DataPath(\"Hymn to Beauty\", hymn.c_str()));\n \n delete childWindow;\n childWindow = nullptr;\n \n fileMenu->SetVisible(false);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ovassvepCSSVEPFlickeringObject.h\"\n#include <iostream>\n\nusing namespace OpenViBESSVEP;\n\nCSSVEPFlickeringObject::CSSVEPFlickeringObject(Ogre::SceneNode* poObjectNode, OpenViBE::uint32 ui32LitFrames, OpenViBE::uint32 ui32DarkFrames) :\n\tm_poObjectNode( poObjectNode ),\n\tm_ui32LitFrames( ui32LitFrames ),\n\tm_ui32DarkFrames( ui32DarkFrames ),\n\tm_bVisible( true )\n{\n\tstd::cout << \"lit \" << ui32LitFrames << \" dark \" << ui32DarkFrames << \"\\n\";\n}\n\nvoid CSSVEPFlickeringObject::setVisible( bool bVisibility )\n{\n\tif ( (!m_bVisible && bVisibility) || (m_bVisible && !bVisibility) )\n\t{\n\t\tm_poObjectNode->flipVisibility();\n\t}\n\tm_bVisible = bVisibility;\n}\n\nvoid CSSVEPFlickeringObject::processFrame(OpenViBE::uint32 ui32CurrentFrame)\n{\n\tif (ui32CurrentFrame % ( m_ui32LitFrames + m_ui32DarkFrames ) < m_ui32LitFrames)\n\t{\n\t\tthis->setVisible( true );\n\t}\n\telse\n\t{\n\t\tthis->setVisible( false );\n\t}\n}\n<commit_msg>openvibe-applications\/ssvep: - removed a debug message<commit_after>#include \"ovassvepCSSVEPFlickeringObject.h\"\n#include <iostream>\n\nusing namespace OpenViBESSVEP;\n\nCSSVEPFlickeringObject::CSSVEPFlickeringObject(Ogre::SceneNode* poObjectNode, OpenViBE::uint32 ui32LitFrames, OpenViBE::uint32 ui32DarkFrames) :\n\tm_poObjectNode( poObjectNode ),\n\tm_ui32LitFrames( ui32LitFrames ),\n\tm_ui32DarkFrames( ui32DarkFrames ),\n\tm_bVisible( true )\n{\n}\n\nvoid CSSVEPFlickeringObject::setVisible( bool bVisibility )\n{\n\tif ( (!m_bVisible && bVisibility) || (m_bVisible && !bVisibility) )\n\t{\n\t\tm_poObjectNode->flipVisibility();\n\t}\n\tm_bVisible = bVisibility;\n}\n\nvoid CSSVEPFlickeringObject::processFrame(OpenViBE::uint32 ui32CurrentFrame)\n{\n\tif (ui32CurrentFrame % ( m_ui32LitFrames + m_ui32DarkFrames ) < m_ui32LitFrames)\n\t{\n\t\tthis->setVisible( true );\n\t}\n\telse\n\t{\n\t\tthis->setVisible( false );\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n\n#include <glog\/logging.h>\n\n#include \"simple_allocator.hpp\"\n\n\nusing std::max;\nusing std::sort;\n\nusing namespace mesos;\nusing namespace mesos::internal;\nusing namespace mesos::internal::master;\n\n\nvoid SimpleAllocator::frameworkAdded(Framework* framework)\n{\n LOG(INFO) << \"Added \" << framework;\n makeNewOffers();\n}\n\n\nvoid SimpleAllocator::frameworkRemoved(Framework* framework)\n{\n LOG(INFO) << \"Removed \" << framework;\n foreachpair (Slave* s, unordered_set<Framework*>& refs, refusers)\n refs.erase(framework);\n \/\/ TODO: Re-offer just the slaves that the framework had tasks on?\n \/\/ Alternatively, comment this out and wait for a timer tick\n makeNewOffers();\n}\n\n\nvoid SimpleAllocator::slaveAdded(Slave* slave)\n{\n LOG(INFO) << \"Added \" << slave;\n refusers[slave] = unordered_set<Framework*>();\n totalResources += slave->resources;\n makeNewOffers(slave);\n}\n\n\nvoid SimpleAllocator::slaveRemoved(Slave* slave)\n{\n LOG(INFO) << \"Removed \" << slave;\n totalResources -= slave->resources;\n refusers.erase(slave);\n}\n\n\nvoid SimpleAllocator::taskRemoved(Task* task, TaskRemovalReason reason)\n{\n LOG(INFO) << \"Removed \" << task;\n \/\/ Remove all refusers from this slave since it has more resources free\n Slave* slave = master->lookupSlave(task->slaveId);\n CHECK(slave != 0);\n refusers[slave].clear();\n \/\/ Re-offer the resources, unless this task was removed due to a lost\n \/\/ slave or a lost framework (in which case we'll get another callback)\n if (reason == TRR_TASK_ENDED || reason == TRR_EXECUTOR_LOST)\n makeNewOffers(slave);\n}\n\n\nvoid SimpleAllocator::offerReturned(SlotOffer* offer,\n OfferReturnReason reason,\n const vector<SlaveResources>& resLeft)\n{\n LOG(INFO) << \"Offer returned: \" << offer << \", reason = \" << reason;\n \/\/ If this offer returned due to the framework replying, add it to refusers\n if (reason == ORR_FRAMEWORK_REPLIED) {\n Framework* framework = master->lookupFramework(offer->frameworkId);\n CHECK(framework != 0);\n foreach (const SlaveResources& r, resLeft) {\n VLOG(1) << \"Framework reply leaves \" << r.resources \n << \" free on \" << r.slave;\n if (r.resources.cpus > 0 || r.resources.mem > 0) {\n VLOG(1) << \"Inserting \" << framework << \" as refuser for \" << r.slave;\n refusers[r.slave].insert(framework);\n }\n }\n }\n \/\/ Make new offers, unless the offer returned due to a lost framework or slave\n \/\/ (in those cases, frameworkRemoved and slaveRemoved will be called later)\n if (reason != ORR_SLAVE_LOST && reason != ORR_FRAMEWORK_LOST) {\n vector<Slave*> slaves;\n foreach (const SlaveResources& r, resLeft)\n slaves.push_back(r.slave);\n makeNewOffers(slaves);\n }\n}\n\n\nvoid SimpleAllocator::offersRevived(Framework* framework)\n{\n LOG(INFO) << \"Filters removed for \" << framework;\n makeNewOffers();\n}\n\n\nvoid SimpleAllocator::timerTick()\n{\n \/\/ TODO: Is this necessary?\n makeNewOffers();\n}\n\n\nnamespace {\n \nstruct DominantShareComparator\n{\n Resources total;\n \n DominantShareComparator(Resources _total) : total(_total)\n {\n if (total.cpus == 0) \/\/ Prevent division by zero if there are no slaves\n total.cpus = 1;\n if (total.mem == 0)\n total.mem = 1;\n }\n \n bool operator() (Framework* f1, Framework* f2)\n {\n double share1 = max(f1->resources.cpus \/ (double) total.cpus,\n f1->resources.mem \/ (double) total.mem);\n double share2 = max(f2->resources.cpus \/ (double) total.cpus,\n f2->resources.mem \/ (double) total.mem);\n if (share1 == share2)\n return f1->id < f2->id; \/\/ Make the sort deterministic for unit testing\n else\n return share1 < share2;\n }\n};\n\n}\n\n\nvector<Framework*> SimpleAllocator::getAllocationOrdering()\n{\n vector<Framework*> frameworks = master->getActiveFrameworks();\n DominantShareComparator comp(totalResources);\n sort(frameworks.begin(), frameworks.end(), comp);\n return frameworks;\n}\n\n\nvoid SimpleAllocator::makeNewOffers()\n{\n \/\/ TODO: Create a method in master so that we don't return the whole list of slaves\n vector<Slave*> slaves = master->getActiveSlaves();\n makeNewOffers(slaves);\n}\n\n\nvoid SimpleAllocator::makeNewOffers(Slave* slave)\n{\n vector<Slave*> slaves;\n slaves.push_back(slave);\n makeNewOffers(slaves);\n}\n\n\nvoid SimpleAllocator::makeNewOffers(const vector<Slave*>& slaves)\n{\n \/\/ Get an ordering of frameworks to send offers to\n vector<Framework*> ordering = getAllocationOrdering();\n if (ordering.size() == 0) {\n VLOG(1) << \"makeNewOffers returning because no frameworks are connected\";\n return;\n }\n \n \/\/ Find all the free resources that can be allocated\n unordered_map<Slave* , Resources> freeResources;\n foreach (Slave* slave, slaves) {\n if (slave->active) {\n Resources res = slave->resourcesFree();\n if (res.cpus >= MIN_CPUS && res.mem >= MIN_MEM) {\n VLOG(1) << \"Found free resources: \" << res << \" on \" << slave;\n freeResources[slave] = res;\n }\n }\n }\n if (freeResources.size() == 0) {\n VLOG(1) << \"makeNewOffers returning because there are no free resources\";\n return;\n }\n \n \/\/ Clear refusers on any slave that has been refused by everyone\n foreachpair (Slave* slave, _, freeResources) {\n unordered_set<Framework*>& refs = refusers[slave];\n if (refs.size() == ordering.size()) {\n VLOG(1) << \"Clearing refusers for \" << slave\n << \" because everyone refused it\";\n refs.clear();\n }\n }\n \n foreach (Framework* framework, ordering) {\n \/\/ See which resources this framework can take (given filters & refusals)\n vector<SlaveResources> offerable;\n foreachpair (Slave* slave, Resources resources, freeResources) {\n if (refusers[slave].find(framework) == refusers[slave].end() &&\n !framework->filters(slave, resources)) {\n VLOG(1) << \"Offering \" << resources << \" on \" << slave\n << \" to framework \" << framework->id;\n offerable.push_back(SlaveResources(slave, resources));\n }\n }\n if (offerable.size() > 0) {\n foreach (SlaveResources& r, offerable) {\n freeResources.erase(r.slave);\n }\n master->makeOffer(framework, offerable);\n }\n }\n}\n<commit_msg>Fixed a bug with offerReturned in simple_allocator: When offerReturned is called due to a framework failover, the framework's new PID will not be set yet, so we shouldn't reoffer resources right away. This was probably not a problem before the issue 108 patch because the old Framework object was marked as inactive so the allocator reoffered to other frameworks. However, it seems weird to mark the framework as inactive when we're going to mark it as active again later in the failover case, and it's easier to just wait for the next timer tick to reoffer those resources.<commit_after>#include <algorithm>\n\n#include <glog\/logging.h>\n\n#include \"simple_allocator.hpp\"\n\n\nusing std::max;\nusing std::sort;\n\nusing namespace mesos;\nusing namespace mesos::internal;\nusing namespace mesos::internal::master;\n\n\nvoid SimpleAllocator::frameworkAdded(Framework* framework)\n{\n LOG(INFO) << \"Added \" << framework;\n makeNewOffers();\n}\n\n\nvoid SimpleAllocator::frameworkRemoved(Framework* framework)\n{\n LOG(INFO) << \"Removed \" << framework;\n foreachpair (Slave* s, unordered_set<Framework*>& refs, refusers)\n refs.erase(framework);\n \/\/ TODO: Re-offer just the slaves that the framework had tasks on?\n \/\/ Alternatively, comment this out and wait for a timer tick\n makeNewOffers();\n}\n\n\nvoid SimpleAllocator::slaveAdded(Slave* slave)\n{\n LOG(INFO) << \"Added \" << slave;\n refusers[slave] = unordered_set<Framework*>();\n totalResources += slave->resources;\n makeNewOffers(slave);\n}\n\n\nvoid SimpleAllocator::slaveRemoved(Slave* slave)\n{\n LOG(INFO) << \"Removed \" << slave;\n totalResources -= slave->resources;\n refusers.erase(slave);\n}\n\n\nvoid SimpleAllocator::taskRemoved(Task* task, TaskRemovalReason reason)\n{\n LOG(INFO) << \"Removed \" << task;\n \/\/ Remove all refusers from this slave since it has more resources free\n Slave* slave = master->lookupSlave(task->slaveId);\n CHECK(slave != 0);\n refusers[slave].clear();\n \/\/ Re-offer the resources, unless this task was removed due to a lost\n \/\/ slave or a lost framework (in which case we'll get another callback)\n if (reason == TRR_TASK_ENDED || reason == TRR_EXECUTOR_LOST)\n makeNewOffers(slave);\n}\n\n\nvoid SimpleAllocator::offerReturned(SlotOffer* offer,\n OfferReturnReason reason,\n const vector<SlaveResources>& resLeft)\n{\n LOG(INFO) << \"Offer returned: \" << offer << \", reason = \" << reason;\n \/\/ If this offer returned due to the framework replying, add it to refusers\n if (reason == ORR_FRAMEWORK_REPLIED) {\n Framework* framework = master->lookupFramework(offer->frameworkId);\n CHECK(framework != 0);\n foreach (const SlaveResources& r, resLeft) {\n VLOG(1) << \"Framework reply leaves \" << r.resources \n << \" free on \" << r.slave;\n if (r.resources.cpus > 0 || r.resources.mem > 0) {\n VLOG(1) << \"Inserting \" << framework << \" as refuser for \" << r.slave;\n refusers[r.slave].insert(framework);\n }\n }\n }\n \/\/ Make new offers unless the offer returned due to a lost framework or slave\n \/\/ (in those cases, frameworkRemoved and slaveRemoved will be called later),\n \/\/ or returned due to a framework failover (in which case the framework's\n \/\/ new PID won't be set yet so we just wait for the next timer tick).\n if (reason != ORR_SLAVE_LOST && reason != ORR_FRAMEWORK_LOST &&\n reason != ORR_FRAMEWORK_FAILOVER) {\n vector<Slave*> slaves;\n foreach (const SlaveResources& r, resLeft)\n slaves.push_back(r.slave);\n makeNewOffers(slaves);\n }\n}\n\n\nvoid SimpleAllocator::offersRevived(Framework* framework)\n{\n LOG(INFO) << \"Filters removed for \" << framework;\n makeNewOffers();\n}\n\n\nvoid SimpleAllocator::timerTick()\n{\n \/\/ TODO: Is this necessary?\n makeNewOffers();\n}\n\n\nnamespace {\n \nstruct DominantShareComparator\n{\n Resources total;\n \n DominantShareComparator(Resources _total) : total(_total)\n {\n if (total.cpus == 0) \/\/ Prevent division by zero if there are no slaves\n total.cpus = 1;\n if (total.mem == 0)\n total.mem = 1;\n }\n \n bool operator() (Framework* f1, Framework* f2)\n {\n double share1 = max(f1->resources.cpus \/ (double) total.cpus,\n f1->resources.mem \/ (double) total.mem);\n double share2 = max(f2->resources.cpus \/ (double) total.cpus,\n f2->resources.mem \/ (double) total.mem);\n if (share1 == share2)\n return f1->id < f2->id; \/\/ Make the sort deterministic for unit testing\n else\n return share1 < share2;\n }\n};\n\n}\n\n\nvector<Framework*> SimpleAllocator::getAllocationOrdering()\n{\n vector<Framework*> frameworks = master->getActiveFrameworks();\n DominantShareComparator comp(totalResources);\n sort(frameworks.begin(), frameworks.end(), comp);\n return frameworks;\n}\n\n\nvoid SimpleAllocator::makeNewOffers()\n{\n \/\/ TODO: Create a method in master so that we don't return the whole list of slaves\n vector<Slave*> slaves = master->getActiveSlaves();\n makeNewOffers(slaves);\n}\n\n\nvoid SimpleAllocator::makeNewOffers(Slave* slave)\n{\n vector<Slave*> slaves;\n slaves.push_back(slave);\n makeNewOffers(slaves);\n}\n\n\nvoid SimpleAllocator::makeNewOffers(const vector<Slave*>& slaves)\n{\n \/\/ Get an ordering of frameworks to send offers to\n vector<Framework*> ordering = getAllocationOrdering();\n if (ordering.size() == 0) {\n VLOG(1) << \"makeNewOffers returning because no frameworks are connected\";\n return;\n }\n \n \/\/ Find all the free resources that can be allocated\n unordered_map<Slave* , Resources> freeResources;\n foreach (Slave* slave, slaves) {\n if (slave->active) {\n Resources res = slave->resourcesFree();\n if (res.cpus >= MIN_CPUS && res.mem >= MIN_MEM) {\n VLOG(1) << \"Found free resources: \" << res << \" on \" << slave;\n freeResources[slave] = res;\n }\n }\n }\n if (freeResources.size() == 0) {\n VLOG(1) << \"makeNewOffers returning because there are no free resources\";\n return;\n }\n \n \/\/ Clear refusers on any slave that has been refused by everyone\n foreachpair (Slave* slave, _, freeResources) {\n unordered_set<Framework*>& refs = refusers[slave];\n if (refs.size() == ordering.size()) {\n VLOG(1) << \"Clearing refusers for \" << slave\n << \" because everyone refused it\";\n refs.clear();\n }\n }\n \n foreach (Framework* framework, ordering) {\n \/\/ See which resources this framework can take (given filters & refusals)\n vector<SlaveResources> offerable;\n foreachpair (Slave* slave, Resources resources, freeResources) {\n if (refusers[slave].find(framework) == refusers[slave].end() &&\n !framework->filters(slave, resources)) {\n VLOG(1) << \"Offering \" << resources << \" on \" << slave\n << \" to framework \" << framework->id;\n offerable.push_back(SlaveResources(slave, resources));\n }\n }\n if (offerable.size() > 0) {\n foreach (SlaveResources& r, offerable) {\n freeResources.erase(r.slave);\n }\n master->makeOffer(framework, offerable);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <time.h>\n#include <sys\/time.h>\n#include <opencv\/cv.h>\n#include <opencv\/cxcore.h>\n#include <opencv\/highgui.h>\n#include <opencv\/cvaux.h>\n#include <libusb-1.0\/libusb.h>\n#include <libuvc\/libuvc.h>\n#include <libuvc\/libuvc_config.h>\n#include \"libuvc\/include\/libuvc\/libuvc_internal.h\"\n\n\nvoid smd_cmd(uvc_device_handle_t *devh);\n\nvoid cb(uvc_frame_t *frame, void *ptr)\n{\n uvc_frame_t *bgr=NULL;\n uvc_error_t ret=(uvc_error_t)0;\n IplImage* cvImg=NULL;\n IplImage *leftim = cvCreateImage(cvSize(640,480),8,3);\n IplImage *rightim = cvCreateImage(cvSize(640,480),8,3);\n IplImage *tmp = NULL;\n IplImage* depth = cvCreateImage(cvGetSize(leftim),8,1);\n IplImage* l = cvCreateImage(cvGetSize(leftim),8,1);\n IplImage* r = cvCreateImage(cvGetSize(leftim),8,1);\n IplImage* dest = cvCreateImage(cvGetSize(leftim),8,3);\n\n printf(\"callback! length = %u, ptr = %d\\n\", (unsigned int)frame->data_bytes, (int)ptr);\n bgr = uvc_allocate_frame(frame->width * frame->height * 3);\n if(!bgr){\n printf(\"unable to allocate bgr frame!\\n\");\n return;\n }\n ret = uvc_any2bgr(frame, bgr);\n if(ret){\n uvc_perror(ret, \"uvc_any2bgr\");\n return;\n }\n\n cvImg = cvCreateImageHeader(\n\t\t\t cvSize(bgr->width, bgr->height),\n\t\t\t IPL_DEPTH_8U,\n\t\t\t 3);\n\n cvSetData(cvImg, bgr->data, bgr->width * 3);\n\n tmp=cvCloneImage(cvImg);\n cvSetImageROI(tmp,cvRect(0,0,320,480));\n cvResize(tmp,leftim,CV_INTER_LINEAR);\n cvSetImageROI(tmp,cvRect(320,0,320,480));\n cvResize(tmp,rightim,CV_INTER_LINEAR);\n cvReleaseImage(&tmp);\n\n cvNamedWindow(\"Left\", CV_WINDOW_AUTOSIZE);\n cvShowImage(\"Left\", leftim);\n cvWaitKey(10);\n\n cvNamedWindow(\"Right\", CV_WINDOW_AUTOSIZE);\n cvShowImage(\"Right\", rightim);\n cvWaitKey(10);\n\n cvCvtColor(leftim,l,CV_BGR2GRAY);\n cvCvtColor(rightim,r,CV_BGR2GRAY);\n cvFindStereoCorrespondence( l, r, CV_DISPARITY_BIRCHFIELD, depth, 100, \n15, 3, 6, 8, 15 );\n cvCvtColor(depth,dest,CV_GRAY2BGR);\n cvScale(dest,dest,255\/100);\n cvNamedWindow(\"Depth\", CV_WINDOW_AUTOSIZE);\n cvShowImage(\"Depth\", dest);\n cvWaitKey(10);\n\n cvReleaseImage(&depth);\n cvReleaseImage(&l);\n cvReleaseImage(&r);\n cvReleaseImage(&dest);\n\n cvReleaseImageHeader(&cvImg);\n cvReleaseImageHeader(&leftim);\n cvReleaseImageHeader(&rightim);\n\n uvc_free_frame(bgr);\n}\n\nint main()\n{\n uvc_context_t *ctx=NULL;\n uvc_device_t *dev=NULL;\n uvc_device_handle_t *devh=NULL;\n uvc_stream_ctrl_t ctrl;\n uvc_error_t res=(uvc_error_t)0;\n uvc_error_t resAEMODE=(uvc_error_t)0;\n uvc_error_t resEXP=(uvc_error_t)0;\n\n\n unsigned int i,j;\n\n res = uvc_init(&ctx, NULL);\n\n if (res < 0) {\n uvc_perror(res, \"uvc_init\");\n return res;\n }\n puts(\"UVC initialized\");\n\n\n res = uvc_find_device(\n\t\t\tctx, &dev,\n\t\t\t0, 0, NULL);\n if (res < 0) {\n uvc_perror(res, \"uvc_find_device\"); \/* no devices found *\/\n } else {\n puts(\"Device found\");\n \n \n res = uvc_open(dev, &devh);\n if (res < 0) {\n uvc_perror(res, \"uvc_open\"); \/* unable to open device *\/\n } else {\n puts(\"Device opened\");\n uvc_print_diag(devh, stderr);\n \n \/* Try to negotiate a 640x480 30 fps YUYV stream profile *\/\n res = uvc_get_stream_ctrl_format_size(\n\t\t\t\t\t devh, &ctrl, \/* result stored in ctrl *\/\n\t\t\t\t\t UVC_FRAME_FORMAT_YUYV, \/* YUV 422, aka YUV 4:2:2. try _COMPRESSED *\/\n\t\t\t\t\t 640, 480, 30 \/* width, height, fps *\/\n\t\t\t\t\t );\n \/* Print out the result *\/\n uvc_print_stream_ctrl(&ctrl, stderr);\n \n if(res < 0){\n\tuvc_perror(res, \"get_mode\");\n }else{\n\tres = uvc_start_streaming(devh, &ctrl, cb, (void *)12345, 0);\n\tsmd_cmd(devh);\n\tif(res < 0){\n\t uvc_perror(res, \"start_streaming\");\n\t}else{\n\t puts(\"Streaming for 10 seconds...\");\n\t resAEMODE = uvc_set_ae_mode(devh, 1);\n\t uvc_perror(resAEMODE, \"set_ae_mode\");\n\n\t while(1){\n\t scanf(\"%d\",&i);\n\t }\n\t uvc_stop_streaming(devh);\n\t puts(\"Done streaming.\");\n\t \n\t}\n\t \n\tuvc_close(devh);\n\tputs(\"Device closed\");\n }\n uvc_unref_device(dev);\n }\n }\n uvc_exit(ctx);\n puts(\"UVC exited\");\n \n return 0;\n}\n \nvoid smd_cmd(uvc_device_handle_t *devh)\n{\n char buf[2];\n int res=0;\n\n libusb_device_handle *dev_handle=NULL;\n \n buf[0] = 0x76;\n buf[1] = 0xc3;\n dev_handle = devh->usb_devh;\n res = libusb_claim_interface(dev_handle, 0);\n if(res != LIBUSB_SUCCESS) printf(\"claim 0 is failed!\\n\");\n res = libusb_control_transfer(devh->usb_devh,\n\t\t\t\t0x21,\n\t\t\t\t0x01,\n\t\t\t\t0x0800,\n\t\t\t\t0x0600,\n\t\t\t\t(unsigned char *)buf,\n\t\t\t\tsizeof(buf),\n\t\t\t\t0);\n printf(\"res = %d\\n\",res);\n if(res == sizeof(buf))printf(\"Control transfer Success!\\n\");\n else printf(\"Control transfer Failed!\\n\");\n \n buf[0] = 0x04;\n buf[1] = 0x00;\n res = libusb_control_transfer(devh->usb_devh,\n\t\t\t\t0x21,\n\t\t\t\t0x01,\n\t\t\t\t0xa00,\n\t\t\t\t0x600,\n\t\t\t\t(unsigned char *)buf,\n\t\t\t\tsizeof(buf),\n\t\t\t\t0);\n if(res == sizeof(buf))printf(\"Control transfer Success!\\n\");\n else printf(\"Control transfer Failed!\\n\");\n}\n\n<commit_msg>remove stereo correspondanse temporery<commit_after>#include <stdio.h>\n#include <time.h>\n#include <unistd.h>\n#include <sys\/time.h>\n#include <opencv\/cv.h>\n#include <opencv\/cxcore.h>\n#include <opencv\/highgui.h>\n#include <opencv\/cvaux.h>\n#include <libusb-1.0\/libusb.h>\n#include <libuvc\/libuvc.h>\n#include <libuvc\/libuvc_config.h>\n#include \"libuvc\/include\/libuvc\/libuvc_internal.h\"\n\n\nvoid smd_cmd(uvc_device_handle_t *devh);\n\nvoid cb(uvc_frame_t *frame, void *ptr)\n{\n uvc_frame_t *bgr=NULL;\n uvc_error_t ret=(uvc_error_t)0;\n IplImage* cvImg=NULL;\n IplImage *leftim = cvCreateImage(cvSize(320,480),8,3);\n IplImage *rightim = cvCreateImage(cvSize(320,480),8,3);\n IplImage *tmp = NULL;\n IplImage* depth = cvCreateImage(cvGetSize(leftim),8,1);\n IplImage* l = cvCreateImage(cvGetSize(leftim),8,1);\n IplImage* r = cvCreateImage(cvGetSize(leftim),8,1);\n IplImage* dest = cvCreateImage(cvGetSize(leftim),8,3);\n\n printf(\"callback! length = %u, ptr = %d\\n\", (unsigned int)frame->data_bytes, (int)ptr);\n bgr = uvc_allocate_frame(frame->width * frame->height * 3);\n if(!bgr){\n printf(\"unable to allocate bgr frame!\\n\");\n return;\n }\n ret = uvc_any2bgr(frame, bgr);\n if(ret){\n uvc_perror(ret, \"uvc_any2bgr\");\n return;\n }\n\n cvImg = cvCreateImageHeader(\n\t\t\t cvSize(bgr->width, bgr->height),\n\t\t\t IPL_DEPTH_8U,\n\t\t\t 3);\n\n cvSetData(cvImg, bgr->data, bgr->width * 3);\n\n tmp=cvCloneImage(cvImg);\n cvSetImageROI(tmp,cvRect(0,0,320,480));\n cvResize(tmp,leftim,CV_INTER_LINEAR);\n cvSetImageROI(tmp,cvRect(320,0,320,480));\n cvResize(tmp,rightim,CV_INTER_LINEAR);\n cvReleaseImage(&tmp);\n\n cvNamedWindow(\"Left\", CV_WINDOW_AUTOSIZE);\n cvShowImage(\"Left\", leftim);\n cvWaitKey(10);\n\n cvNamedWindow(\"Right\", CV_WINDOW_AUTOSIZE);\n cvShowImage(\"Right\", rightim);\n\n cvCvtColor(leftim,l,CV_BGR2GRAY);\n cvCvtColor(rightim,r,CV_BGR2GRAY);\n\/\/ cvFindStereoCorrespondence( l, r, CV_DISPARITY_BIRCHFIELD, depth, 127,\n\/\/15, 3, 6, 8, 15 ); \n\/\/ cvCvtColor(depth,dest,CV_GRAY2BGR);\n\/\/ cvScale(dest,dest,255\/100);\n\/\/ cvNamedWindow(\"Depth\", CV_WINDOW_AUTOSIZE);\n\/\/ cvShowImage(\"Depth\", dest);\n cvNamedWindow(\"Original\", CV_WINDOW_AUTOSIZE);\n cvShowImage(\"Original\", cvImg);\n\n\/\/ cvWaitKey(10);\n\n cvReleaseImage(&depth);\n cvReleaseImage(&l);\n cvReleaseImage(&r);\n cvReleaseImage(&dest);\n\n cvReleaseImageHeader(&cvImg);\n cvReleaseImageHeader(&leftim);\n cvReleaseImageHeader(&rightim);\n\n uvc_free_frame(bgr);\n}\n\nint main()\n{\n uvc_context_t *ctx=NULL;\n uvc_device_t *dev=NULL;\n uvc_device_handle_t *devh=NULL;\n uvc_stream_ctrl_t ctrl;\n uvc_error_t res=(uvc_error_t)0;\n uvc_error_t resAEMODE=(uvc_error_t)0;\n uvc_error_t resEXP=(uvc_error_t)0;\n\n\n unsigned int i,j;\n\n res = uvc_init(&ctx, NULL);\n\n if (res < 0) {\n uvc_perror(res, \"uvc_init\");\n return res;\n }\n puts(\"UVC initialized\");\n\n\n res = uvc_find_device(\n\t\t\tctx, &dev,\n\t\t\t0, 0, NULL);\n if (res < 0) {\n uvc_perror(res, \"uvc_find_device\"); \/* no devices found *\/\n } else {\n puts(\"Device found\");\n \n \n res = uvc_open(dev, &devh);\n if (res < 0) {\n uvc_perror(res, \"uvc_open\"); \/* unable to open device *\/\n } else {\n puts(\"Device opened\");\n uvc_print_diag(devh, stderr);\n \n \/* Try to negotiate a 640x480 30 fps YUYV stream profile *\/\n res = uvc_get_stream_ctrl_format_size(\n\t\t\t\t\t devh, &ctrl, \/* result stored in ctrl *\/\n\t\t\t\t\t UVC_FRAME_FORMAT_YUYV, \/* YUV 422, aka YUV 4:2:2. try _COMPRESSED *\/\n\t\t\t\t\t 640, 480, 30 \/* width, height, fps *\/\n\t\t\t\t\t );\n \/* Print out the result *\/\n uvc_print_stream_ctrl(&ctrl, stderr);\n \n if(res < 0){\n\tuvc_perror(res, \"get_mode\");\n }else{\n\tres = uvc_start_streaming(devh, &ctrl, cb, (void *)12345, 0);\n\tsmd_cmd(devh);\n\tif(res < 0){\n\t uvc_perror(res, \"start_streaming\");\n\t}else{\n\t puts(\"Streaming for 10 seconds...\");\n\t resAEMODE = uvc_set_ae_mode(devh, 1);\n\t uvc_perror(resAEMODE, \"set_ae_mode\");\n\n\t while(1){\n\t scanf(\"%d\",i);\n\/\/\t usleep(500000);\n\t }\n\t uvc_stop_streaming(devh);\n\t puts(\"Done streaming.\");\n\t \n\t}\n\t \n\tuvc_close(devh);\n\tputs(\"Device closed\");\n }\n uvc_unref_device(dev);\n }\n }\n uvc_exit(ctx);\n puts(\"UVC exited\");\n \n return 0;\n}\n \nvoid smd_cmd(uvc_device_handle_t *devh)\n{\n char buf[2];\n int res=0;\n\n libusb_device_handle *dev_handle=NULL;\n \n buf[0] = 0x76;\n buf[1] = 0xc3;\n dev_handle = devh->usb_devh;\n res = libusb_claim_interface(dev_handle, 0);\n if(res != LIBUSB_SUCCESS) printf(\"claim 0 is failed!\\n\");\n res = libusb_control_transfer(devh->usb_devh,\n\t\t\t\t0x21,\n\t\t\t\t0x01,\n\t\t\t\t0x0800,\n\t\t\t\t0x0600,\n\t\t\t\t(unsigned char *)buf,\n\t\t\t\tsizeof(buf),\n\t\t\t\t0);\n printf(\"res = %d\\n\",res);\n if(res == sizeof(buf))printf(\"Control transfer Success!\\n\");\n else printf(\"Control transfer Failed!\\n\");\n \n buf[0] = 0x04;\n buf[1] = 0x00;\n res = libusb_control_transfer(devh->usb_devh,\n\t\t\t\t0x21,\n\t\t\t\t0x01,\n\t\t\t\t0xa00,\n\t\t\t\t0x600,\n\t\t\t\t(unsigned char *)buf,\n\t\t\t\tsizeof(buf),\n\t\t\t\t0);\n if(res == sizeof(buf))printf(\"Control transfer Success!\\n\");\n else printf(\"Control transfer Failed!\\n\");\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ lib.hpp\n\/\/\n\/\/ Copyright (c) 2016-2017 Jeff Hutchinson\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 all\n\/\/ 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 THE\n\/\/ SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#ifndef _JBL_LIB_HPP_\n#define _JBL_LIB_HPP_\n\n\/\/ Exception: These are compile time and do not link with the code. \n\/\/ Thus I will allow it.\n#include <type_traits>\n\n#include <string.h>\n#include \"compiler.hpp\"\n#include \"types.hpp\"\n\ntemplate<typename T>\nFORCE_INLINE T&& move_cast(T &ref)\n{\n\treturn static_cast<T&&>(ref);\n}\n\ntemplate<typename T>\nFORCE_INLINE T max(T a, T b)\n{\n\treturn (a > b) ? a : b;\n}\n\ntemplate<typename T>\nFORCE_INLINE T min(T a, T b)\n{\n\treturn (a < b) ? a : b;\n}\n\n\/\/ Equals override.\ntemplate<typename T> FORCE_INLINE bool equals(const T &lhs, const T &rhs);\n\ntemplate<typename T>\nFORCE_INLINE bool equals(const T &lhs, const T &rhs)\n{\n\treturn lhs == rhs;\n}\n\ntemplate<>\nFORCE_INLINE bool equals(const char* const &lhs, const char *const &rhs)\n{\n\treturn strcmp(lhs, rhs) == 0;\n}\n\n#endif \/\/ _JBL_LIB_H_\n<commit_msg>remove type traits header. MacOS using libstdc++ doesn't have it as its C++98<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ lib.hpp\n\/\/\n\/\/ Copyright (c) 2016-2017 Jeff Hutchinson\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 all\n\/\/ 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 THE\n\/\/ SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#ifndef _JBL_LIB_HPP_\n#define _JBL_LIB_HPP_\n\n#include <string.h>\n#include \"compiler.hpp\"\n#include \"types.hpp\"\n\ntemplate<typename T>\nFORCE_INLINE T&& move_cast(T &ref)\n{\n\treturn static_cast<T&&>(ref);\n}\n\ntemplate<typename T>\nFORCE_INLINE T max(T a, T b)\n{\n\treturn (a > b) ? a : b;\n}\n\ntemplate<typename T>\nFORCE_INLINE T min(T a, T b)\n{\n\treturn (a < b) ? a : b;\n}\n\n\/\/ Equals override.\ntemplate<typename T> FORCE_INLINE bool equals(const T &lhs, const T &rhs);\n\ntemplate<typename T>\nFORCE_INLINE bool equals(const T &lhs, const T &rhs)\n{\n\treturn lhs == rhs;\n}\n\ntemplate<>\nFORCE_INLINE bool equals(const char* const &lhs, const char *const &rhs)\n{\n\treturn strcmp(lhs, rhs) == 0;\n}\n\n#endif \/\/ _JBL_LIB_H_\n<|endoftext|>"} {"text":"<commit_before>\/* www.nalug.net\r\n * www.linuxdaynapoli.org\r\n * www.gbr1technologies.altervista.org\r\n *\r\n *\t Open Data Day Napoli 2015\r\n *\r\n * Giovanni di Dio Bruno ;)\r\n *\r\n *\r\n *\/\r\n\r\n\r\n\r\n#include \"mbed.h\"\r\n#include \"EthernetInterface.h\"\r\n#include \"TMP102.h\"\r\n#include <string>\r\n#include <cstring>\r\n#include \"TextLCD.h\"\r\n \r\nTextLCD lcd(p15, p16, p21, p22, p23, p24); \/\/ rs, e, d4-d7\r\n\r\n\r\n\r\n\r\n\r\nfloat LAT= 40.86;\r\nfloat LONG=14.17;\r\nfloat ALT=100;\r\n\r\n\r\n\r\n \r\nTMP102 temperature(p9,p10, 0x90); \r\nDigitalOut l1(LED1);\r\nDigitalOut l2(LED2);\r\nDigitalOut l3(LED3);\r\nDigitalOut l4(LED4);\r\n\r\nfloat temp=0;\r\nchar command[1024];\r\nchar s[1024];\r\nchar wk[5];\r\n\r\nstring id = \"***************\"; \/\/username:password with base64\r\n\r\nTCPSocketConnection sock;\r\n\r\nvoid send_temp(void const *args) {\r\n while (true) {\r\n l3=1;\r\n sock.connect(\"openweathermap.org\",80);\r\n printf(\"socket connesso\\r\\n\");\r\n int len=0;\r\n len=sprintf(s,\"temp=%f&lat=%2f&long=%f&alt=%f\",temp,LAT,LONG,ALT);\r\n printf(\"%s\",s);\r\n sprintf(wk,\"%d\",len);\r\n string http_cmd = \"POST \/data\/post HTTP\/1.1\\r\\nAuthorization: Basic \"+id+\"\\r\\nHost: openweathermap.org\\r\\nAccept: *\/*\\r\\nContent-Length: \"+string(wk)+\"\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\n\\r\\n\"+string(s);\r\n int n = sprintf(command,http_cmd.c_str());\r\n printf(\"%s\",command);\r\n printf(\"\\r\\n%d\\r\\n\",n);\r\n sock.send_all(command, n);\r\n sock.receive(command,1024);\r\n l3=0;\r\n printf(\"\\r\\n\\r\\n%s\\r\\n\\r\\n\",command);\r\n wait(19.9); \r\n sock.close();\r\n Thread::wait(20000);\r\n \r\n }\r\n}\r\n\r\nvoid update_screen(void const *args) {\r\n while (true) {\r\n l2=1;\r\n temp=temperature.read();\r\n printf(\"temp: %f\\r\\n\",temp);\r\n wait(0.1); \r\n l2=0;\r\n lcd.cls();\r\n lcd.printf(\"%3.3f C\\nNalug Weather\",temp);\r\n Thread::wait(5000);\r\n }\r\n}\r\n\r\n\r\n\r\nint main() {\r\n l1=0;\r\n l2=0;\r\n l3=0;\r\n l4=0;\r\n l1=1;\r\n lcd.printf(\"Open Data Day 15Nalug Weather\");\r\n EthernetInterface eth;\r\n eth.init(); \/\/Use DHCP\r\n eth.connect();\r\n printf(\"IP Address is %s\\r\\n\", eth.getIPAddress());\r\n l1=0;\r\n l4=1;\r\n \r\n Thread thread(send_temp);\r\n Thread thread2(update_screen);\r\n \r\n while(1){\r\n }\r\n eth.disconnect();\r\n}\r\n<commit_msg>comments added in main.cpp<commit_after>\/* www.nalug.net\r\n * www.linuxdaynapoli.org\r\n * www.gbr1technologies.altervista.org\r\n *\r\n *\t Open Data Day Napoli 2015\r\n *\r\n * Giovanni di Dio Bruno ;)\r\n *\r\n *\r\n *\/\r\n\r\n\r\n\r\n#include \"mbed.h\"\r\n#include \"EthernetInterface.h\"\r\n#include \"TMP102.h\"\r\n#include <string>\r\n#include <cstring>\r\n#include \"TextLCD.h\"\r\n \r\n \r\n\/\/lcd pinout \r\nTextLCD lcd(p15, p16, p21, p22, p23, p24); \/\/ rs, e, d4-d7\r\n\r\n\r\n\r\n\r\n\/\/your latitude, longitude and altitude\r\nfloat LAT= 40.86;\r\nfloat LONG=14.17;\r\nfloat ALT=100;\r\n\r\n\r\n\r\n\/\/cheap but powerfull temperature sensor\r\nTMP102 temperature(p9,p10, 0x90); \r\n\r\nDigitalOut l1(LED1); \/\/ip OK\r\nDigitalOut l2(LED2); \/\/temp read\r\nDigitalOut l3(LED3); \/\/openweathermap connction\r\nDigitalOut l4(LED4); \/\/working\r\n\r\nfloat temp=0; \/\/temperature\r\nchar command[1024]; \/\/string for http post\r\nchar s[1024];\r\nchar wk[5];\r\n\r\nstring id = \"***************\"; \/\/username:password with base64\r\n\r\nTCPSocketConnection sock;\r\n\r\n\r\n\/\/thread to send temperature to openweathermap.org -> every 20s\r\nvoid send_temp(void const *args) {\r\n while (true) {\r\n l3=1; \/\/active led 3\r\n sock.connect(\"openweathermap.org\",80); \/\/open socket connection\r\n printf(\"socket connesso\\r\\n\");\r\n int len=0;\r\n len=sprintf(s,\"temp=%f&lat=%2f&long=%f&alt=%f\",temp,LAT,LONG,ALT); \/\/create data to send to server and his length\r\n printf(\"%s\",s);\r\n sprintf(wk,\"%d\",len); \/\/convert int to char[]\r\n \/\/complete command to do http post to openweathermap.org server\r\n string http_cmd = \"POST \/data\/post HTTP\/1.1\\r\\nAuthorization: Basic \"+id+\"\\r\\nHost: openweathermap.org\\r\\nAccept: *\/*\\r\\nContent-Length: \"+string(wk)+\"\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\n\\r\\n\"+string(s);\r\n int n = sprintf(command,http_cmd.c_str()); \/\/string to char[] and its length\r\n printf(\"%s\",command);\r\n printf(\"\\r\\n%d\\r\\n\",n);\r\n \/\/send\r\n sock.send_all(command, n);\r\n \/\/receive response from openweeathermap server \r\n sock.receive(command,1024);\r\n l3=0;\r\n printf(\"\\r\\n\\r\\n%s\\r\\n\\r\\n\",command);\r\n \/\/close socket\r\n sock.close();\r\n \/\/thread every 20s\r\n Thread::wait(20000);\r\n \r\n }\r\n}\r\n\r\n\r\n\/\/thread for updating screen\r\nvoid update_screen(void const *args) {\r\n while (true) {\r\n l2=1; \/\/update temperature\r\n temp=temperature.read();\r\n printf(\"temp: %f\\r\\n\",temp);\r\n wait(0.1); \r\n l2=0;\r\n \/\/lcd print\r\n lcd.cls();\r\n lcd.printf(\"%3.3f C\\nNalug Weather\",temp);\r\n \/\/thread every 5s\r\n Thread::wait(5000);\r\n }\r\n}\r\n\r\n\r\n\r\nint main() {\r\n \/\/init leds\r\n l1=0;\r\n l2=0;\r\n l3=0;\r\n l4=0;\r\n \r\n \/\/getting ip and ethernet connection\r\n l1=1;\r\n lcd.printf(\"Open Data Day 15Nalug Weather\");\r\n EthernetInterface eth;\r\n eth.init(); \/\/Use DHCP\r\n eth.connect();\r\n printf(\"IP Address is %s\\r\\n\", eth.getIPAddress());\r\n l1=0;\r\n l4=1;\r\n \r\n \/\/starting threads\r\n Thread thread(send_temp);\r\n Thread thread2(update_screen);\r\n \r\n while(1){\r\n }\r\n \r\n \/\/close ethernet\r\n eth.disconnect();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* This file exists to provide some stat monitors for process statistics and the like. *\/\n\n#include <vector>\n#include <string.h>\n#include <stdlib.h>\n#include <sys\/syscall.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\n#include \"perfmon.hpp\"\n#include \"logger.hpp\"\n\n\/* Class to represent and parse the contents of \/proc\/[pid]\/stat *\/\n\nstruct proc_pid_stat_t {\n int pid;\n char name[500];\n char state;\n int ppid, pgrp, session, tty_nr, tpgid;\n unsigned int flags;\n unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime;\n long int cutime, cstime, priority, nice, num_threads, itrealvalue;\n long long unsigned int starttime;\n long unsigned int vsize;\n long int rss;\n long unsigned int rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,\n sigignore, sigcatch, wchan, nswap, cnswap;\n int exit_signal, processor;\n unsigned int rt_priority, policy;\n long long unsigned int delayacct_blkio_ticks;\n long unsigned int guest_time;\n long int cguest_time;\n \n bool read_stats(pid_t pid) {\n char path[100];\n snprintf(path, sizeof(path), \"\/proc\/%d\/stat\", pid);\n return read(path);\n }\n\n bool read_task_stats(pid_t pid, pid_t tid) {\n char path[100];\n snprintf(path, sizeof(path), \"\/proc\/%d\/task\/%d\/stat\", pid, tid);\n return read(path);\n }\n\nprivate:\n bool read(char * path) {\n int stat_file = open(path, O_RDONLY);\n if (stat_file == -1) {\n logWRN(\"Could not open '%s': %s (errno = %d)\", path, strerror(errno), errno);\n return false;\n }\n \n char buffer[1000];\n int res = ::read(stat_file, buffer, sizeof(buffer));\n if (res <= 0) {\n logWRN(\"Could not read '%s': %s (errno = %d)\", path, strerror(errno), errno);\n close(stat_file);\n return false;\n }\n\n buffer[res] = '\\0';\n \n close(stat_file);\n \n \/\/ TODO rewrite this mess to use something more safe and sane, e.g. iostreams\n const int items_to_parse = 44;\n int res2 = sscanf(buffer, \"%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld \"\n \"%ld %ld %ld %ld %llu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d \"\n \"%d %u %u %u %u %llu %lu %ld\",\n &pid, name, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,\n &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,\n &cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,\n &starttime, &vsize, &rss, &rsslim, &startcode, &endcode, &startstack,\n &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan,\n &nswap, &cnswap, &exit_signal, &processor, &rt_priority, &processor,\n &rt_priority, &policy, &delayacct_blkio_ticks, &guest_time, &cguest_time);\n if (res2 != items_to_parse) {\n logWRN(\"Could not parse '%s': expected to parse %d items, parsed %d. Buffer contents: %s\", path, items_to_parse, res2, buffer);\n return false;\n }\n return true;\n }\n};\n\n\/* perfmon_system_t is used to monitor system stats that do not need to be polled. *\/\n\nclass perfmon_system_t :\n public perfmon_t\n{\n void *begin_stats() {\n return NULL;\n }\n void visit_stats(void *) {\n }\n void end_stats(void *, perfmon_stats_t *dest) {\n proc_pid_stat_t pid_stat;\n if (pid_stat.read_stats(getpid())) {\n (*dest)[\"pid\"] = format(pid_stat.pid);\n (*dest)[\"memory_virtual[bytes]\"] = format(pid_stat.vsize);\n (*dest)[\"memory_real[bytes]\"] = format(pid_stat.rss * sysconf(_SC_PAGESIZE));\n }\n }\n} pm_system;\n\n\/* Some of the stats need to be polled periodically. Call this function periodically on each\nthread to ensure that stats are up to date. It takes a void* so that it can be called as a timer\ncallback. *\/\n\nperfmon_sampler_t\n pm_cpu_user(\"cpu_user\", secs_to_ticks(5)),\n pm_cpu_system(\"cpu_system\", secs_to_ticks(5)),\n pm_memory_faults(\"memory_faults\", secs_to_ticks(5));\n\nstatic __thread proc_pid_stat_t last_stats;\nstatic __thread ticks_t last_ticks = 0;\n\nvoid poll_system_stats(void *) {\n pid_t tid = syscall(SYS_gettid);\n \n proc_pid_stat_t current_stats;\n current_stats.read_task_stats(getpid(), tid);\n ticks_t current_ticks = get_ticks();\n \n if (last_ticks == 0) {\n last_stats = current_stats;\n last_ticks = current_ticks;\n } else if (current_ticks > last_ticks + secs_to_ticks(1)) {\n double realtime_elapsed = ticks_to_secs(current_ticks - last_ticks) * sysconf(_SC_CLK_TCK);\n pm_cpu_user.record((current_stats.utime - last_stats.utime) \/ realtime_elapsed);\n pm_cpu_system.record((current_stats.stime - last_stats.stime) \/ realtime_elapsed);\n pm_memory_faults.record((current_stats.majflt - last_stats.majflt) \/ realtime_elapsed);\n \n last_stats = current_stats;\n last_ticks = current_ticks;\n }\n}\n\n<commit_msg>Added a third CPU usage monitor for combined user+system usage.<commit_after>\/* This file exists to provide some stat monitors for process statistics and the like. *\/\n\n#include <vector>\n#include <string.h>\n#include <stdlib.h>\n#include <sys\/syscall.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\n#include \"perfmon.hpp\"\n#include \"logger.hpp\"\n\n\/* Class to represent and parse the contents of \/proc\/[pid]\/stat *\/\n\nstruct proc_pid_stat_t {\n int pid;\n char name[500];\n char state;\n int ppid, pgrp, session, tty_nr, tpgid;\n unsigned int flags;\n unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime;\n long int cutime, cstime, priority, nice, num_threads, itrealvalue;\n long long unsigned int starttime;\n long unsigned int vsize;\n long int rss;\n long unsigned int rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,\n sigignore, sigcatch, wchan, nswap, cnswap;\n int exit_signal, processor;\n unsigned int rt_priority, policy;\n long long unsigned int delayacct_blkio_ticks;\n long unsigned int guest_time;\n long int cguest_time;\n \n bool read_stats(pid_t pid) {\n char path[100];\n snprintf(path, sizeof(path), \"\/proc\/%d\/stat\", pid);\n return read(path);\n }\n\n bool read_task_stats(pid_t pid, pid_t tid) {\n char path[100];\n snprintf(path, sizeof(path), \"\/proc\/%d\/task\/%d\/stat\", pid, tid);\n return read(path);\n }\n\nprivate:\n bool read(char * path) {\n int stat_file = open(path, O_RDONLY);\n if (stat_file == -1) {\n logWRN(\"Could not open '%s': %s (errno = %d)\", path, strerror(errno), errno);\n return false;\n }\n \n char buffer[1000];\n int res = ::read(stat_file, buffer, sizeof(buffer));\n if (res <= 0) {\n logWRN(\"Could not read '%s': %s (errno = %d)\", path, strerror(errno), errno);\n close(stat_file);\n return false;\n }\n\n buffer[res] = '\\0';\n \n close(stat_file);\n \n \/\/ TODO rewrite this mess to use something more safe and sane, e.g. iostreams\n const int items_to_parse = 44;\n int res2 = sscanf(buffer, \"%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld \"\n \"%ld %ld %ld %ld %llu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d \"\n \"%d %u %u %u %u %llu %lu %ld\",\n &pid, name, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,\n &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,\n &cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,\n &starttime, &vsize, &rss, &rsslim, &startcode, &endcode, &startstack,\n &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan,\n &nswap, &cnswap, &exit_signal, &processor, &rt_priority, &processor,\n &rt_priority, &policy, &delayacct_blkio_ticks, &guest_time, &cguest_time);\n if (res2 != items_to_parse) {\n logWRN(\"Could not parse '%s': expected to parse %d items, parsed %d. Buffer contents: %s\", path, items_to_parse, res2, buffer);\n return false;\n }\n return true;\n }\n};\n\n\/* perfmon_system_t is used to monitor system stats that do not need to be polled. *\/\n\nclass perfmon_system_t :\n public perfmon_t\n{\n void *begin_stats() {\n return NULL;\n }\n void visit_stats(void *) {\n }\n void end_stats(void *, perfmon_stats_t *dest) {\n proc_pid_stat_t pid_stat;\n if (pid_stat.read_stats(getpid())) {\n (*dest)[\"pid\"] = format(pid_stat.pid);\n (*dest)[\"memory_virtual[bytes]\"] = format(pid_stat.vsize);\n (*dest)[\"memory_real[bytes]\"] = format(pid_stat.rss * sysconf(_SC_PAGESIZE));\n }\n }\n} pm_system;\n\n\/* Some of the stats need to be polled periodically. Call this function periodically on each\nthread to ensure that stats are up to date. It takes a void* so that it can be called as a timer\ncallback. *\/\n\nperfmon_sampler_t\n pm_cpu_user(\"cpu_user\", secs_to_ticks(5)),\n pm_cpu_system(\"cpu_system\", secs_to_ticks(5)),\n pm_cpu_combined(\"cpu_combined\", secs_to_ticks(5)),\n pm_memory_faults(\"memory_faults\", secs_to_ticks(5));\n\nstatic __thread proc_pid_stat_t last_stats;\nstatic __thread ticks_t last_ticks = 0;\n\nvoid poll_system_stats(void *) {\n pid_t tid = syscall(SYS_gettid);\n \n proc_pid_stat_t current_stats;\n current_stats.read_task_stats(getpid(), tid);\n ticks_t current_ticks = get_ticks();\n \n if (last_ticks == 0) {\n last_stats = current_stats;\n last_ticks = current_ticks;\n } else if (current_ticks > last_ticks + secs_to_ticks(1)) {\n double realtime_elapsed = ticks_to_secs(current_ticks - last_ticks) * sysconf(_SC_CLK_TCK);\n pm_cpu_user.record((current_stats.utime - last_stats.utime) \/ realtime_elapsed);\n pm_cpu_system.record((current_stats.stime - last_stats.stime) \/ realtime_elapsed);\n pm_cpu_combined.record(\n (current_stats.utime - last_stats.utime +\n current_stats.stime - last_stats.stime) \/\n realtime_elapsed);\n pm_memory_faults.record((current_stats.majflt - last_stats.majflt) \/ realtime_elapsed);\n \n last_stats = current_stats;\n last_ticks = current_ticks;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the Orbbec Astra SDK [https:\/\/orbbec3d.com]\n\/\/ Copyright (c) 2015 Orbbec 3D\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\/\/ Be excellent to each other.\n#ifndef ASTRA_LOGGING_H\n#define ASTRA_LOGGING_H\n\n\/\/ TODO valgrind will go bananas with the default crash handler enabled\n\/\/ #define ELPP_DISABLE_DEFAULT_CRASH_HANDLING\n#define ELPP_NO_DEFAULT_LOG_FILE\n\n\/\/ enable stacktraces for GCC\/Clang on *nixes\n#if ! defined(__ANDROID__) && ! defined(_MSC_VER)\n#define ELPP_STACKTRACE_ON_CRASH\n#endif\n\n#include \"easylogging++.h\"\n#include <astra_core\/capi\/astra_types.h>\n\n#define INITIALIZE_LOGGING INITIALIZE_EASYLOGGINGPP\n\nnamespace astra {\n void initialize_logging(const char* logFilePath, astra_log_severity_t severity, bool consoleOutput, bool fileOutput);\n}\n\n#endif \/* ASTRA_LOGGING_H *\/\n<commit_msg>Mute warning generated by easylogging code<commit_after>\/\/ This file is part of the Orbbec Astra SDK [https:\/\/orbbec3d.com]\n\/\/ Copyright (c) 2015 Orbbec 3D\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\/\/ Be excellent to each other.\n#ifndef ASTRA_LOGGING_H\n#define ASTRA_LOGGING_H\n\n\/\/ TODO valgrind will go bananas with the default crash handler enabled\n\/\/ #define ELPP_DISABLE_DEFAULT_CRASH_HANDLING\n#define ELPP_NO_DEFAULT_LOG_FILE\n\n\/\/ enable stacktraces for GCC\/Clang on *nixes\n#if ! defined(__ANDROID__) && ! defined(_MSC_VER)\n#define ELPP_STACKTRACE_ON_CRASH\n#endif\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wpessimizing-move\"\n#endif\n#include \"easylogging++.h\"\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n#include <astra_core\/capi\/astra_types.h>\n\n#define INITIALIZE_LOGGING INITIALIZE_EASYLOGGINGPP\n\nnamespace astra {\n void initialize_logging(const char* logFilePath, astra_log_severity_t severity, bool consoleOutput, bool fileOutput);\n}\n\n#endif \/* ASTRA_LOGGING_H *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * filter_qtext.cpp -- text overlay filter\n * Copyright (c) 2018 Meltytech, LLC\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\n#include \"common.h\"\n#include <framework\/mlt.h>\n#include <framework\/mlt_log.h>\n#include <QPainter>\n#include <QString>\n\nstatic QRectF get_text_path( QPainterPath* qpath, mlt_properties filter_properties, const char* text )\n{\n\tint outline = mlt_properties_get_int( filter_properties, \"outline\" );\n\tchar halign = mlt_properties_get( filter_properties, \"halign\" )[0];\n\tchar style = mlt_properties_get( filter_properties, \"style\" )[0];\n\tint pad = mlt_properties_get_int( filter_properties, \"pad\" );\n\tint offset = pad + ( outline \/ 2 );\n\tint width = 0;\n\tint height = 0;\n\n\tqpath->setFillRule( Qt::WindingFill );\n\n\t\/\/ Get the strings to display\n\tQString s = QString::fromUtf8(text);\n\tQStringList lines = s.split( \"\\n\" );\n\n\t\/\/ Configure the font\n\tQFont font;\n\tfont.setPixelSize( mlt_properties_get_int( filter_properties, \"size\" ) );\n\tfont.setFamily( mlt_properties_get( filter_properties, \"family\" ) );\n\tfont.setWeight( ( mlt_properties_get_int( filter_properties, \"weight\" ) \/ 10 ) -1 );\n\tswitch( style )\n\t{\n\tcase 'i':\n\tcase 'I':\n\t\tfont.setStyle( QFont::StyleItalic );\n\t\tbreak;\n\t}\n\tQFontMetrics fm( font );\n\n\t\/\/ Determine the text rectangle size\n\theight = fm.lineSpacing() * lines.size();\n\tfor( int i = 0; i < lines.size(); ++i )\n\t{\n\t\tconst QString line = lines[i];\n\t\tint line_width = fm.width(line);\n\t\tint bearing = (line.size() > 0) ? fm.leftBearing(line.at(0)) : 0;\n\t\tif (bearing < 0)\n\t\t\tline_width -= bearing;\n\t\tbearing = (line.size() > 0) ? fm.rightBearing(line.at(line.size() - 1)) : 0;\n\t\tif (bearing < 0)\n\t\t\tline_width -= bearing;\n\t\tif (line_width > width)\n\t\t\twidth = line_width;\n\t}\n\n\t\/\/ Lay out the text in the path\n\tint x = 0;\n\tint y = fm.ascent() + offset;\n\tfor( int i = 0; i < lines.size(); ++i )\n\t{\n\t\tQString line = lines.at(i);\n\t\tx = offset;\n\t\tint line_width = fm.width(line);\n\t\tint bearing = (line.size() > 0)? fm.leftBearing(line.at(0)) : 0;\n\n\t\tif (bearing < 0) {\n\t\t\tline_width -= bearing;\n\t\t\tx -= bearing;\n\t\t}\n\t\tbearing = (line.size() > 0)? fm.rightBearing(line.at(line.size() - 1)) : 0;\n\t\tif (bearing < 0)\n\t\t\tline_width -= bearing;\n\n\t\tswitch( halign )\n\t\t{\n\t\t\tdefault:\n\t\t\tcase 'l':\n\t\t\tcase 'L':\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\tcase 'C':\n\t\t\t\tx += ( width - line_width ) \/ 2;\n\t\t\t\tbreak;\n\t\t\tcase 'r':\n\t\t\tcase 'R':\n\t\t\t\tx += width - line_width;\n\t\t\t\tbreak;\n\t\t}\n\t\tqpath->addText( x, y, font, line );\n\t\ty += fm.lineSpacing();\n\t}\n\n\t\/\/ Account for outline and pad\n\twidth += offset * 2;\n\theight += offset * 2;\n\t\/\/ Sanity check\n\tif( width == 0 ) width = 1;\n\theight += 2; \/\/ I found some fonts whose descenders get cut off.\n\n\treturn QRectF( 0, 0, width, height );\n}\n\nstatic QColor get_qcolor( mlt_properties filter_properties, const char* name )\n{\n\tmlt_color color = mlt_properties_get_color( filter_properties, name );\n\treturn QColor( color.r, color.g, color.b, color.a );\n}\n\nstatic QPen get_qpen( mlt_properties filter_properties )\n{\n\tQColor color;\n\tint outline = mlt_properties_get_int( filter_properties, \"outline\" );\n\tQPen pen;\n\n\tpen.setWidth( outline );\n\tif( outline )\n\t{\n\t\tcolor = get_qcolor( filter_properties, \"olcolour\" );\n\t}\n\telse\n\t{\n\t\tcolor = get_qcolor( filter_properties, \"bgcolour\" );\n\t}\n\tpen.setColor( color );\n\n\treturn pen;\n}\n\nstatic QBrush get_qbrush( mlt_properties filter_properties )\n{\n\tQColor color = get_qcolor( filter_properties, \"fgcolour\" );\n\treturn QBrush ( color );\n}\n\nstatic void transform_painter( QPainter* painter, mlt_rect frame_rect, QRectF path_rect, mlt_properties filter_properties, mlt_profile profile )\n{\n\tqreal sx = 1.0;\n\tqreal sy = mlt_profile_sar( profile );\n\tqreal path_width = path_rect.width() * sx;\n\tif( path_width > frame_rect.w )\n\t{\n\t\tsx *= frame_rect.w \/ path_width;\n\t\tsy *= frame_rect.w \/ path_width;\n\t}\n\tqreal path_height = path_rect.height() * sy;\n\tif( path_height > frame_rect.h )\n\t{\n\t\tsx *= frame_rect.h \/ path_height;\n\t\tsy *= frame_rect.h \/ path_height;\n\t}\n\n\tqreal dx = frame_rect.x;\n\tqreal dy = frame_rect.y;\n\tchar halign = mlt_properties_get( filter_properties, \"halign\" )[0];\n\tswitch( halign )\n\t{\n\t\tdefault:\n\t\tcase 'l':\n\t\tcase 'L':\n\t\t\tbreak;\n\t\tcase 'c':\n\t\tcase 'C':\n\t\t\tdx += ( frame_rect.w - ( sx * path_rect.width() ) ) \/ 2;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\tcase 'R':\n\t\t\tdx += frame_rect.w - ( sx * path_rect.width() );\n\t\t\tbreak;\n\t}\n\tchar valign = mlt_properties_get( filter_properties, \"valign\" )[0];\n\tswitch( valign )\n\t{\n\t\tdefault:\n\t\tcase 't':\n\t\tcase 'T':\n\t\t\tbreak;\n\t\tcase 'm':\n\t\tcase 'M':\n\t\t\tdy += ( frame_rect.h - ( sy * path_rect.height() ) ) \/ 2;\n\t\t\tbreak;\n\t\tcase 'b':\n\t\tcase 'B':\n\t\t\tdy += frame_rect.h - ( sy * path_rect.height() );\n\t\t\tbreak;\n\t}\n\n\tQTransform transform;\n\ttransform.translate( dx, dy );\n\ttransform.scale( sx, sy );\n\tpainter->setTransform( transform );\n}\n\nstatic void paint_background( QPainter* painter, QRectF path_rect, mlt_properties filter_properties )\n{\n\tQColor bg_color = get_qcolor( filter_properties, \"bgcolour\" );\n\tpainter->fillRect( path_rect, bg_color );\n}\n\nstatic void paint_text( QPainter* painter, QPainterPath* qpath, mlt_properties filter_properties )\n{\n\tQPen pen = get_qpen( filter_properties );\n\tpainter->setPen( pen );\n\tQBrush brush = get_qbrush( filter_properties );\n\tpainter->setBrush( brush );\n\tpainter->drawPath( *qpath );\n}\n\nstatic mlt_properties get_filter_properties( mlt_filter filter, mlt_frame frame )\n{\n\tmlt_properties properties = mlt_frame_get_unique_properties( frame, MLT_FILTER_SERVICE(filter) );\n\tif ( !properties )\n\t\tproperties = MLT_FILTER_PROPERTIES(filter);\n\treturn properties;\n}\n\nstatic int filter_get_image( mlt_frame frame, uint8_t **image, mlt_image_format *image_format, int *width, int *height, int writable )\n{\n\tint error = 0;\n\tmlt_filter filter = (mlt_filter)mlt_frame_pop_service( frame );\n\tchar* argument = (char*)mlt_frame_pop_service( frame );\n\tmlt_properties filter_properties = get_filter_properties( filter, frame );\n\tmlt_profile profile = mlt_service_profile(MLT_FILTER_SERVICE(filter));\n\tmlt_position position = mlt_filter_get_position( filter, frame );\n\tmlt_position length = mlt_filter_get_length2( filter, frame );\n\tQString geom_str = QString::fromLatin1( mlt_properties_get( filter_properties, \"geometry\" ) );\n\tif( geom_str.isEmpty() )\n\t{\n\t\tmlt_log_warning( MLT_FILTER_SERVICE(filter), \"geometry property not set\\n\" );\n\t\tmlt_frame_get_image( frame, image, image_format, width, height, writable );\n\t\tfree( argument );\n\t\treturn 1;\n\t}\n\tmlt_rect rect = mlt_properties_anim_get_rect( filter_properties, \"geometry\", position, length );\n\n\t\/\/ Get the current image\n\t*image_format = mlt_image_rgb24a;\n\tmlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), \"resize_alpha\", 255 );\n\terror = mlt_frame_get_image( frame, image, image_format, width, height, writable );\n\n\tif( !error )\n\t{\n\t\tif ( geom_str.contains('%') )\n\t\t{\n\t\t\trect.x *= *width;\n\t\t\trect.w *= *width;\n\t\t\trect.y *= *height;\n\t\t\trect.h *= *height;\n\t\t}\n\n\t\tQImage qimg( *width, *height, QImage::Format_ARGB32 );\n\t\tconvert_mlt_to_qimage_rgba( *image, &qimg, *width, *height );\n\n\t\tQPainterPath text_path;\n\t\tQRectF path_rect = get_text_path( &text_path, filter_properties, argument );\n\t\tQPainter painter( &qimg );\n\t\tpainter.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing );\n\t\ttransform_painter( &painter, rect, path_rect, filter_properties, profile );\n\t\tpaint_background( &painter, path_rect, filter_properties );\n\t\tpaint_text( &painter, &text_path, filter_properties );\n\t\tpainter.end();\n\n\t\tconvert_qimage_to_mlt_rgba( &qimg, *image, *width, *height );\n\t}\n\tfree( argument );\n\n\treturn error;\n}\n\n\/** Filter processing.\n*\/\n\nstatic mlt_frame filter_process( mlt_filter filter, mlt_frame frame )\n{\n\tmlt_properties properties = get_filter_properties( filter, frame );\n\tchar* argument = mlt_properties_get( properties, \"argument\" );\n\tif ( !argument || !strcmp( \"\", argument ) )\n\t\treturn frame;\n\n\t\/\/ Save the text to be used by get_image() to support parallel processing\n\t\/\/ when this filter is encapsulated by other filters.\n\tmlt_frame_push_service( frame, strdup( argument ) );\n\n\t\/\/ Push the filter on to the stack\n\tmlt_frame_push_service( frame, filter );\n\n\t\/\/ Push the get_image on to the stack\n\tmlt_frame_push_get_image( frame, filter_get_image );\n\n\treturn frame;\n}\n\n\/** Constructor for the filter.\n*\/\n\nextern \"C\" {\n\nmlt_filter filter_qtext_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )\n{\n\tmlt_filter filter = mlt_filter_new();\n\n\tif( !filter ) return NULL;\n\n\tif ( !createQApplicationIfNeeded( MLT_FILTER_SERVICE(filter) ) ) {\n\t\tmlt_filter_close( filter );\n\t\treturn NULL;\n\t}\n\n\tfilter->process = filter_process;\n\n\tmlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );\n\t\/\/ Assign default values\n\tmlt_properties_set( filter_properties, \"argument\", arg ? arg: \"text\" );\n\tmlt_properties_set( filter_properties, \"geometry\", \"0%\/0%:100%x100%:100%\" );\n\tmlt_properties_set( filter_properties, \"family\", \"Sans\" );\n\tmlt_properties_set( filter_properties, \"size\", \"48\" );\n\tmlt_properties_set( filter_properties, \"weight\", \"400\" );\n\tmlt_properties_set( filter_properties, \"style\", \"normal\" );\n\tmlt_properties_set( filter_properties, \"fgcolour\", \"0x000000ff\" );\n\tmlt_properties_set( filter_properties, \"bgcolour\", \"0x00000020\" );\n\tmlt_properties_set( filter_properties, \"olcolour\", \"0x00000000\" );\n\tmlt_properties_set( filter_properties, \"pad\", \"0\" );\n\tmlt_properties_set( filter_properties, \"halign\", \"left\" );\n\tmlt_properties_set( filter_properties, \"valign\", \"top\" );\n\tmlt_properties_set( filter_properties, \"outline\", \"0\" );\n\tmlt_properties_set_int( filter_properties, \"_filter_private\", 1 );\n\n\treturn filter;\n}\n\n}\n<commit_msg>Fix white flash on property changes.<commit_after>\/*\n * filter_qtext.cpp -- text overlay filter\n * Copyright (c) 2018 Meltytech, LLC\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\n#include \"common.h\"\n#include <framework\/mlt.h>\n#include <framework\/mlt_log.h>\n#include <QPainter>\n#include <QString>\n\nstatic QRectF get_text_path( QPainterPath* qpath, mlt_properties filter_properties, const char* text )\n{\n\tint outline = mlt_properties_get_int( filter_properties, \"outline\" );\n\tchar halign = mlt_properties_get( filter_properties, \"halign\" )[0];\n\tchar style = mlt_properties_get( filter_properties, \"style\" )[0];\n\tint pad = mlt_properties_get_int( filter_properties, \"pad\" );\n\tint offset = pad + ( outline \/ 2 );\n\tint width = 0;\n\tint height = 0;\n\n\tqpath->setFillRule( Qt::WindingFill );\n\n\t\/\/ Get the strings to display\n\tQString s = QString::fromUtf8(text);\n\tQStringList lines = s.split( \"\\n\" );\n\n\t\/\/ Configure the font\n\tQFont font;\n\tfont.setPixelSize( mlt_properties_get_int( filter_properties, \"size\" ) );\n\tfont.setFamily( mlt_properties_get( filter_properties, \"family\" ) );\n\tfont.setWeight( ( mlt_properties_get_int( filter_properties, \"weight\" ) \/ 10 ) -1 );\n\tswitch( style )\n\t{\n\tcase 'i':\n\tcase 'I':\n\t\tfont.setStyle( QFont::StyleItalic );\n\t\tbreak;\n\t}\n\tQFontMetrics fm( font );\n\n\t\/\/ Determine the text rectangle size\n\theight = fm.lineSpacing() * lines.size();\n\tfor( int i = 0; i < lines.size(); ++i )\n\t{\n\t\tconst QString line = lines[i];\n\t\tint line_width = fm.width(line);\n\t\tint bearing = (line.size() > 0) ? fm.leftBearing(line.at(0)) : 0;\n\t\tif (bearing < 0)\n\t\t\tline_width -= bearing;\n\t\tbearing = (line.size() > 0) ? fm.rightBearing(line.at(line.size() - 1)) : 0;\n\t\tif (bearing < 0)\n\t\t\tline_width -= bearing;\n\t\tif (line_width > width)\n\t\t\twidth = line_width;\n\t}\n\n\t\/\/ Lay out the text in the path\n\tint x = 0;\n\tint y = fm.ascent() + offset;\n\tfor( int i = 0; i < lines.size(); ++i )\n\t{\n\t\tQString line = lines.at(i);\n\t\tx = offset;\n\t\tint line_width = fm.width(line);\n\t\tint bearing = (line.size() > 0)? fm.leftBearing(line.at(0)) : 0;\n\n\t\tif (bearing < 0) {\n\t\t\tline_width -= bearing;\n\t\t\tx -= bearing;\n\t\t}\n\t\tbearing = (line.size() > 0)? fm.rightBearing(line.at(line.size() - 1)) : 0;\n\t\tif (bearing < 0)\n\t\t\tline_width -= bearing;\n\n\t\tswitch( halign )\n\t\t{\n\t\t\tdefault:\n\t\t\tcase 'l':\n\t\t\tcase 'L':\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\tcase 'C':\n\t\t\t\tx += ( width - line_width ) \/ 2;\n\t\t\t\tbreak;\n\t\t\tcase 'r':\n\t\t\tcase 'R':\n\t\t\t\tx += width - line_width;\n\t\t\t\tbreak;\n\t\t}\n\t\tqpath->addText( x, y, font, line );\n\t\ty += fm.lineSpacing();\n\t}\n\n\t\/\/ Account for outline and pad\n\twidth += offset * 2;\n\theight += offset * 2;\n\t\/\/ Sanity check\n\tif( width == 0 ) width = 1;\n\theight += 2; \/\/ I found some fonts whose descenders get cut off.\n\n\treturn QRectF( 0, 0, width, height );\n}\n\nstatic QColor get_qcolor( mlt_properties filter_properties, const char* name )\n{\n\tmlt_color color = mlt_properties_get_color( filter_properties, name );\n\treturn QColor( color.r, color.g, color.b, color.a );\n}\n\nstatic QPen get_qpen( mlt_properties filter_properties )\n{\n\tQColor color;\n\tint outline = mlt_properties_get_int( filter_properties, \"outline\" );\n\tQPen pen;\n\n\tpen.setWidth( outline );\n\tif( outline )\n\t{\n\t\tcolor = get_qcolor( filter_properties, \"olcolour\" );\n\t}\n\telse\n\t{\n\t\tcolor = get_qcolor( filter_properties, \"bgcolour\" );\n\t}\n\tpen.setColor( color );\n\n\treturn pen;\n}\n\nstatic QBrush get_qbrush( mlt_properties filter_properties )\n{\n\tQColor color = get_qcolor( filter_properties, \"fgcolour\" );\n\treturn QBrush ( color );\n}\n\nstatic void transform_painter( QPainter* painter, mlt_rect frame_rect, QRectF path_rect, mlt_properties filter_properties, mlt_profile profile )\n{\n\tqreal sx = 1.0;\n\tqreal sy = mlt_profile_sar( profile );\n\tqreal path_width = path_rect.width() * sx;\n\tif( path_width > frame_rect.w )\n\t{\n\t\tsx *= frame_rect.w \/ path_width;\n\t\tsy *= frame_rect.w \/ path_width;\n\t}\n\tqreal path_height = path_rect.height() * sy;\n\tif( path_height > frame_rect.h )\n\t{\n\t\tsx *= frame_rect.h \/ path_height;\n\t\tsy *= frame_rect.h \/ path_height;\n\t}\n\n\tqreal dx = frame_rect.x;\n\tqreal dy = frame_rect.y;\n\tchar halign = mlt_properties_get( filter_properties, \"halign\" )[0];\n\tswitch( halign )\n\t{\n\t\tdefault:\n\t\tcase 'l':\n\t\tcase 'L':\n\t\t\tbreak;\n\t\tcase 'c':\n\t\tcase 'C':\n\t\t\tdx += ( frame_rect.w - ( sx * path_rect.width() ) ) \/ 2;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\tcase 'R':\n\t\t\tdx += frame_rect.w - ( sx * path_rect.width() );\n\t\t\tbreak;\n\t}\n\tchar valign = mlt_properties_get( filter_properties, \"valign\" )[0];\n\tswitch( valign )\n\t{\n\t\tdefault:\n\t\tcase 't':\n\t\tcase 'T':\n\t\t\tbreak;\n\t\tcase 'm':\n\t\tcase 'M':\n\t\t\tdy += ( frame_rect.h - ( sy * path_rect.height() ) ) \/ 2;\n\t\t\tbreak;\n\t\tcase 'b':\n\t\tcase 'B':\n\t\t\tdy += frame_rect.h - ( sy * path_rect.height() );\n\t\t\tbreak;\n\t}\n\n\tQTransform transform;\n\ttransform.translate( dx, dy );\n\ttransform.scale( sx, sy );\n\tpainter->setTransform( transform );\n}\n\nstatic void paint_background( QPainter* painter, QRectF path_rect, mlt_properties filter_properties )\n{\n\tQColor bg_color = get_qcolor( filter_properties, \"bgcolour\" );\n\tpainter->fillRect( path_rect, bg_color );\n}\n\nstatic void paint_text( QPainter* painter, QPainterPath* qpath, mlt_properties filter_properties )\n{\n\tQPen pen = get_qpen( filter_properties );\n\tpainter->setPen( pen );\n\tQBrush brush = get_qbrush( filter_properties );\n\tpainter->setBrush( brush );\n\tpainter->drawPath( *qpath );\n}\n\nstatic mlt_properties get_filter_properties( mlt_filter filter, mlt_frame frame )\n{\n\tmlt_properties properties = mlt_frame_get_unique_properties( frame, MLT_FILTER_SERVICE(filter) );\n\tif ( !properties )\n\t\tproperties = MLT_FILTER_PROPERTIES(filter);\n\treturn properties;\n}\n\nstatic int filter_get_image( mlt_frame frame, uint8_t **image, mlt_image_format *image_format, int *width, int *height, int writable )\n{\n\tint error = 0;\n\tmlt_filter filter = (mlt_filter)mlt_frame_pop_service( frame );\n\tchar* argument = (char*)mlt_frame_pop_service( frame );\n\tmlt_properties filter_properties = get_filter_properties( filter, frame );\n\tmlt_profile profile = mlt_service_profile(MLT_FILTER_SERVICE(filter));\n\tmlt_position position = mlt_filter_get_position( filter, frame );\n\tmlt_position length = mlt_filter_get_length2( filter, frame );\n\tQString geom_str = QString::fromLatin1( mlt_properties_get( filter_properties, \"geometry\" ) );\n\tif( geom_str.isEmpty() )\n\t{\n\t\tfree( argument );\n\t\tmlt_log_warning( MLT_FILTER_SERVICE(filter), \"geometry property not set\\n\" );\n\t\treturn mlt_frame_get_image( frame, image, image_format, width, height, writable );\n\t}\n\tmlt_rect rect = mlt_properties_anim_get_rect( filter_properties, \"geometry\", position, length );\n\n\t\/\/ Get the current image\n\t*image_format = mlt_image_rgb24a;\n\tmlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), \"resize_alpha\", 255 );\n\terror = mlt_frame_get_image( frame, image, image_format, width, height, writable );\n\n\tif( !error )\n\t{\n\t\tif ( geom_str.contains('%') )\n\t\t{\n\t\t\trect.x *= *width;\n\t\t\trect.w *= *width;\n\t\t\trect.y *= *height;\n\t\t\trect.h *= *height;\n\t\t}\n\n\t\tQImage qimg( *width, *height, QImage::Format_ARGB32 );\n\t\tconvert_mlt_to_qimage_rgba( *image, &qimg, *width, *height );\n\n\t\tQPainterPath text_path;\n\t\tQRectF path_rect = get_text_path( &text_path, filter_properties, argument );\n\t\tQPainter painter( &qimg );\n\t\tpainter.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing );\n\t\ttransform_painter( &painter, rect, path_rect, filter_properties, profile );\n\t\tpaint_background( &painter, path_rect, filter_properties );\n\t\tpaint_text( &painter, &text_path, filter_properties );\n\t\tpainter.end();\n\n\t\tconvert_qimage_to_mlt_rgba( &qimg, *image, *width, *height );\n\t}\n\tfree( argument );\n\n\treturn error;\n}\n\n\/** Filter processing.\n*\/\n\nstatic mlt_frame filter_process( mlt_filter filter, mlt_frame frame )\n{\n\tmlt_properties properties = get_filter_properties( filter, frame );\n\tchar* argument = mlt_properties_get( properties, \"argument\" );\n\tif ( !argument || !strcmp( \"\", argument ) )\n\t\treturn frame;\n\n\t\/\/ Save the text to be used by get_image() to support parallel processing\n\t\/\/ when this filter is encapsulated by other filters.\n\tmlt_frame_push_service( frame, strdup( argument ) );\n\n\t\/\/ Push the filter on to the stack\n\tmlt_frame_push_service( frame, filter );\n\n\t\/\/ Push the get_image on to the stack\n\tmlt_frame_push_get_image( frame, filter_get_image );\n\n\treturn frame;\n}\n\n\/** Constructor for the filter.\n*\/\n\nextern \"C\" {\n\nmlt_filter filter_qtext_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )\n{\n\tmlt_filter filter = mlt_filter_new();\n\n\tif( !filter ) return NULL;\n\n\tif ( !createQApplicationIfNeeded( MLT_FILTER_SERVICE(filter) ) ) {\n\t\tmlt_filter_close( filter );\n\t\treturn NULL;\n\t}\n\n\tfilter->process = filter_process;\n\n\tmlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );\n\t\/\/ Assign default values\n\tmlt_properties_set( filter_properties, \"argument\", arg ? arg: \"text\" );\n\tmlt_properties_set( filter_properties, \"geometry\", \"0%\/0%:100%x100%:100%\" );\n\tmlt_properties_set( filter_properties, \"family\", \"Sans\" );\n\tmlt_properties_set( filter_properties, \"size\", \"48\" );\n\tmlt_properties_set( filter_properties, \"weight\", \"400\" );\n\tmlt_properties_set( filter_properties, \"style\", \"normal\" );\n\tmlt_properties_set( filter_properties, \"fgcolour\", \"0x000000ff\" );\n\tmlt_properties_set( filter_properties, \"bgcolour\", \"0x00000020\" );\n\tmlt_properties_set( filter_properties, \"olcolour\", \"0x00000000\" );\n\tmlt_properties_set( filter_properties, \"pad\", \"0\" );\n\tmlt_properties_set( filter_properties, \"halign\", \"left\" );\n\tmlt_properties_set( filter_properties, \"valign\", \"top\" );\n\tmlt_properties_set( filter_properties, \"outline\", \"0\" );\n\tmlt_properties_set_int( filter_properties, \"_filter_private\", 1 );\n\n\treturn filter;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"LnkdLst.h\"\n#include \"CircularLL.h\"\n#include \"DoublyLL.h\"\n#include \"PriorityLL.h\"\n#include \"SortedLL.h\"\n#include \"Queue.h\"\n#include \"Stack.h\"\n\nint main()\n{\n\t\/\/Linked List\n\tcout << \"Linked List\" << endl;\n\tcout << \"=============\" << endl;\n\tLnkdLst<float> list1(0);\n\tLnkdLst<float> list2(list1);\n\n\tlist2.append(4);\n\tlist2.append(8);\n\tlist2.append(10);\n\n\tlist1.append(3);\n\tlist1.append(5);\n\tlist1.prepend(2);\n\tlist1.prepend(7);\n\tlist1.extract(5);\n\tlist1.extract(2);\n\tlist1.insertAfter(3, 9);\n\tlist1.insertAfter(0, 1);\n\tlist1.insertBefore(7, 3);\n\tlist1.insertBefore(1, 8);\n\n\tLnkdLst<float> list3(list1);\n\n\tcout << \"This is list [1]\" << endl;\n\tcout << \"================\" << endl;\n\tcout << \"The first value is: \" << list1.getHead() << endl;\n\tcout << \"The last value is: \" << list1.getTail() << endl;\n\tcout << list1.toString() << endl;\n\n\tcout << \"This is list [2]\" << endl;\n\tcout << \"================\" << endl;\n\tcout << \"The first value is: \" << list2.getHead() << endl;\n\tcout << \"The last value is: \" << list2.getTail() << endl;\n\tcout << list2.toString() << endl;\n\n\tcout << \"Setting list[1] = list[2]\" << endl;\n\tlist1 = list2;\n\tcout << \"================\" << endl;\n\tcout << \"The first value is: \" << list1.getHead() << endl;\n\tcout << \"The last value is: \" << list1.getTail() << endl;\n\tcout << list1.toString() << endl;\n\n\tcout << \"This is list [3]\" << endl;\n\tcout << \"================\" << endl;\n\tcout << \"The first value is: \" << list3.getHead() << endl;\n\tcout << \"The last value is: \" << list3.getTail() << endl;\n\tcout << list3.toString() << endl; \n\n\n\t\/\/Stack\n\tcout << \"Stack\" << endl;\n\tcout << \"=============\" << endl;\n\tStack<float> stack(2);\n\tstack.push(4);\n\tstack.push(8);\n\tstack.toString();\n\tcout << \"Stack top: \" << stack.top() << endl;\n\tcout << \"Stack size: \" << stack.size() << endl;\n\tstack.pop();\n\tstack.pop();\n cout << \"Pop twice\" << endl;\n\tstack.toString(); \n\tcout << \"Final Stack size: \" << stack.size() << endl; \n\n\t\/\/Queue\n\tcout << \"Queue\" << endl;\n\tcout << \"=============\" << endl;\n\tQueue<float> queue(4);\n\tqueue.enqueue(7);\n\tqueue.enqueue(0);\n\tqueue.toString();\n cout << \"Make Queue empty\" << endl;\n\tqueue.makeEmpty();\n\tqueue.enqueue(2);\n cout << \"Final Queue Contents\" << endl;\n\tqueue.toString(); \n\n\t\/\/Doubly LL\n\tcout << \"Doubly Linked List\" << endl;\n\tcout << \"=============\" << endl;\n\tDoublyLL<float> doubly(8);\n\tdoubly.prepend(4);\n\tdoubly.prepend(0);\n\tdoubly.append(7);\n\tdoubly.append(9);\n\tdoubly.extract(0);\n\tdoubly.extract(1);\n\tdoubly.insertBefore(9, 2);\n\tdoubly.insertBefore(2, 3);\n\tdoubly.insertAfter(4, 1);\n\tdoubly.insertAfter(1, 5);\n\tdoubly.toString(); \n\n\tDoublyLL<float> doubly2(doubly);\n\tcout << \"List 2\" << endl;\n\tdoubly2.toString();\n\n\tDoublyLL<float> doubly3(4);\n\tcout << \"List 3\" << endl;\n\tdoubly3 = doubly2;\n\tdoubly3.toString(); \n\n\t\/\/Circular LL\n\tcout << \"Circular Linked List\" << endl;\n\tcout << \"=============\" << endl;\n\tCircularLL<float> circList(8);\n\tcircList.prepend(3);\n\tcircList.append(2);\n\tcircList.append(4);\n\tcircList.extract(2);\n\tcircList.insertBefore(8, 0);\n\tcircList.insertAfter(4, 7);\n\tcircList.toString();\n\tcout << \"This is the tail: \" << circList.getTail() << endl;\n\n cout << \"Circular List 2\" << endl;\n\tCircularLL<float> circList2(circList);\n\tcircList2.toString();\n\n\t\/\/Sorted LL\n\tcout << \"Sorted Linked List\" << endl;\n\tcout << \"=============\" << endl;\n\tSortedLL<float> sorted(4);\n\tsorted.insert(7);\n\tsorted.insert(5);\n\tsorted.insert(2);\n\tsorted.insert(4.5);\n\tsorted.insert(9);\n\tsorted.toString();\n\n\tcout << \"Sorted List 2\" << endl;\n\tSortedLL<float> sorted2(sorted);\n\tsorted2.insert(3);\n\tsorted2.toString();\n\n\tsorted = sorted2;\n\tsorted.toString(); \n\t\n\t\/*\n\tPriorityLL<float> priority(2);\n\tpriority.appendP(8);\n\tpriority.prependP(7);\n\tpriority.extract(2);\n\tpriority.toString(); *\/\n\n\t\/\/To exit\n\tchar c;\n\tcin >> c;\n\n\treturn 0;\n}\n<commit_msg>added \"==\" for consistency<commit_after>#include \"LnkdLst.h\"\n#include \"CircularLL.h\"\n#include \"DoublyLL.h\"\n#include \"PriorityLL.h\"\n#include \"SortedLL.h\"\n#include \"Queue.h\"\n#include \"Stack.h\"\n\nint main()\n{\n\t\/\/Linked List\n\tcout << \"Linked List\" << endl;\n\tcout << \"=============\" << endl;\n\tLnkdLst<float> list1(0);\n\tLnkdLst<float> list2(list1);\n\n\tlist2.append(4);\n\tlist2.append(8);\n\tlist2.append(10);\n\n\tlist1.append(3);\n\tlist1.append(5);\n\tlist1.prepend(2);\n\tlist1.prepend(7);\n\tlist1.extract(5);\n\tlist1.extract(2);\n\tlist1.insertAfter(3, 9);\n\tlist1.insertAfter(0, 1);\n\tlist1.insertBefore(7, 3);\n\tlist1.insertBefore(1, 8);\n\n\tLnkdLst<float> list3(list1);\n\n\tcout << \"This is list [1]\" << endl;\n\tcout << \"================\" << endl;\n\tcout << \"The first value is: \" << list1.getHead() << endl;\n\tcout << \"The last value is: \" << list1.getTail() << endl;\n\tcout << list1.toString() << endl;\n\n\tcout << \"This is list [2]\" << endl;\n\tcout << \"================\" << endl;\n\tcout << \"The first value is: \" << list2.getHead() << endl;\n\tcout << \"The last value is: \" << list2.getTail() << endl;\n\tcout << list2.toString() << endl;\n\n\tcout << \"Setting list[1] = list[2]\" << endl;\n\tlist1 = list2;\n\tcout << \"================\" << endl;\n\tcout << \"The first value is: \" << list1.getHead() << endl;\n\tcout << \"The last value is: \" << list1.getTail() << endl;\n\tcout << list1.toString() << endl;\n\n\tcout << \"This is list [3]\" << endl;\n\tcout << \"================\" << endl;\n\tcout << \"The first value is: \" << list3.getHead() << endl;\n\tcout << \"The last value is: \" << list3.getTail() << endl;\n\tcout << list3.toString() << endl; \n\n\n\t\/\/Stack\n\tcout << \"Stack\" << endl;\n\tcout << \"=============\" << endl;\n\tStack<float> stack(2);\n\tstack.push(4);\n\tstack.push(8);\n\tstack.toString();\n\tcout << \"Stack top: \" << stack.top() << endl;\n\tcout << \"Stack size: \" << stack.size() << endl;\n\tstack.pop();\n\tstack.pop();\n cout << \"Pop twice\" << endl;\n\tstack.toString(); \n\tcout << \"Final Stack size: \" << stack.size() << endl; \n\n\t\/\/Queue\n\tcout << \"Queue\" << endl;\n\tcout << \"=============\" << endl;\n\tQueue<float> queue(4);\n\tqueue.enqueue(7);\n\tqueue.enqueue(0);\n\tqueue.toString();\n cout << \"Make Queue empty\" << endl;\n\tqueue.makeEmpty();\n\tqueue.enqueue(2);\n cout << \"Final Queue Contents\" << endl;\n\tqueue.toString(); \n\n\t\/\/Doubly LL\n\tcout << \"Doubly Linked List\" << endl;\n\tcout << \"=============\" << endl;\n\tDoublyLL<float> doubly(8);\n\tdoubly.prepend(4);\n\tdoubly.prepend(0);\n\tdoubly.append(7);\n\tdoubly.append(9);\n\tdoubly.extract(0);\n\tdoubly.extract(1);\n\tdoubly.insertBefore(9, 2);\n\tdoubly.insertBefore(2, 3);\n\tdoubly.insertAfter(4, 1);\n\tdoubly.insertAfter(1, 5);\n\tdoubly.toString(); \n\n\tDoublyLL<float> doubly2(doubly);\n\tcout << \"List 2\" << endl;\n\tcout << \"=============\" << endl;\n\tdoubly2.toString();\n\n\tDoublyLL<float> doubly3(4);\n\tcout << \"List 3\" << endl;\n\tcout << \"=============\" << endl;\n\tdoubly3 = doubly2;\n\tdoubly3.toString(); \n\n\t\/\/Circular LL\n\tcout << \"Circular Linked List\" << endl;\n\tcout << \"=============\" << endl;\n\tCircularLL<float> circList(8);\n\tcircList.prepend(3);\n\tcircList.append(2);\n\tcircList.append(4);\n\tcircList.extract(2);\n\tcircList.insertBefore(8, 0);\n\tcircList.insertAfter(4, 7);\n\tcircList.toString();\n\tcout << \"This is the tail: \" << circList.getTail() << endl;\n\n cout << \"Circular List 2\" << endl;\n cout << \"=============\" << endl;\n\tCircularLL<float> circList2(circList);\n\tcircList2.toString();\n\n\t\/\/Sorted LL\n\tcout << \"Sorted Linked List\" << endl;\n\tcout << \"=============\" << endl;\n\tSortedLL<float> sorted(4);\n\tsorted.insert(7);\n\tsorted.insert(5);\n\tsorted.insert(2);\n\tsorted.insert(4.5);\n\tsorted.insert(9);\n\tsorted.toString();\n\n\tcout << \"Sorted List 2\" << endl;\n\tcout << \"=============\" << endl;\n\tSortedLL<float> sorted2(sorted);\n\tsorted2.insert(3);\n\tsorted2.toString();\n\n\tsorted = sorted2;\n\tsorted.toString(); \n\t\n\t\/*\n\tPriorityLL<float> priority(2);\n\tpriority.appendP(8);\n\tpriority.prependP(7);\n\tpriority.extract(2);\n\tpriority.toString(); *\/\n\n\t\/\/To exit\n\tchar c;\n\tcin >> c;\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DffImpl.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hbrinkm $ $Date: 2006-11-01 09:14:29 $\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#include \"resources.hxx\"\n\nnamespace doctok\n{\nclass ShapeTypeToString\n{\n typedef boost::shared_ptr<ShapeTypeToString> Pointer_t;\n\n static Pointer_t pInstance;\n\n typedef map<sal_uInt32, string> Map_t;\n Map_t mMap;\n\nprotected:\n ShapeTypeToString();\n\npublic:\n static Pointer_t Instance()\n {\n if (pInstance == NULL)\n pInstance = Pointer_t(new ShapeTypeToString());\n\n return pInstance;\n }\n\n string operator()(sal_uInt32 nShapeType)\n {\n return mMap[nShapeType];\n }\n};\n\nShapeTypeToString::Pointer_t ShapeTypeToString::pInstance;\n\nShapeTypeToString::ShapeTypeToString()\n{\n mMap[0]=\"NotPrimitive\";\n mMap[1]=\"Rectangle\";\n mMap[2]=\"RoundRectangle\";\n mMap[3]=\"Ellipse\";\n mMap[4]=\"Diamond\";\n mMap[5]=\"IsocelesTriangle\";\n mMap[6]=\"RightTriangle\";\n mMap[7]=\"Parallelogram\";\n mMap[8]=\"Trapezoid\";\n mMap[9]=\"Hexagon\";\n mMap[10]=\"Octagon\";\n mMap[11]=\"Plus\";\n mMap[12]=\"Star\";\n mMap[13]=\"Arrow\";\n mMap[14]=\"ThickArrow\";\n mMap[15]=\"HomePlate\";\n mMap[16]=\"Cube\";\n mMap[17]=\"Balloon\";\n mMap[18]=\"Seal\";\n mMap[19]=\"Arc\";\n mMap[20]=\"Line\";\n mMap[21]=\"Plaque\";\n mMap[22]=\"Can\";\n mMap[23]=\"Donut\";\n mMap[24]=\"TextSimple\";\n mMap[25]=\"TextOctagon\";\n mMap[26]=\"TextHexagon\";\n mMap[27]=\"TextCurve\";\n mMap[28]=\"TextWave\";\n mMap[29]=\"TextRing\";\n mMap[30]=\"TextOnCurve\";\n mMap[31]=\"TextOnRing\";\n mMap[32]=\"StraightConnector1\";\n mMap[33]=\"BentConnector2\";\n mMap[34]=\"BentConnector3\";\n mMap[35]=\"BentConnector4\";\n mMap[36]=\"BentConnector5\";\n mMap[37]=\"CurvedConnector2\";\n mMap[38]=\"CurvedConnector3\";\n mMap[39]=\"CurvedConnector4\";\n mMap[40]=\"CurvedConnector5\";\n mMap[41]=\"Callout1\";\n mMap[42]=\"Callout2\";\n mMap[43]=\"Callout3\";\n mMap[44]=\"AccentCallout1\";\n mMap[45]=\"AccentCallout2\";\n mMap[46]=\"AccentCallout3\";\n mMap[47]=\"BorderCallout1\";\n mMap[48]=\"BorderCallout2\";\n mMap[49]=\"BorderCallout3\";\n mMap[50]=\"AccentBorderCallout1\";\n mMap[51]=\"AccentBorderCallout2\";\n mMap[52]=\"AccentBorderCallout3\";\n mMap[53]=\"Ribbon\";\n mMap[54]=\"Ribbon2\";\n mMap[55]=\"Chevron\";\n mMap[56]=\"Pentagon\";\n mMap[57]=\"NoSmoking\";\n mMap[58]=\"Seal8\";\n mMap[59]=\"Seal16\";\n mMap[60]=\"Seal32\";\n mMap[61]=\"WedgeRectCallout\";\n mMap[62]=\"WedgeRRectCallout\";\n mMap[63]=\"WedgeEllipseCallout\";\n mMap[64]=\"Wave\";\n mMap[65]=\"FoldedCorner\";\n mMap[66]=\"LeftArrow\";\n mMap[67]=\"DownArrow\";\n mMap[68]=\"UpArrow\";\n mMap[69]=\"LeftRightArrow\";\n mMap[70]=\"UpDownArrow\";\n mMap[71]=\"IrregularSeal1\";\n mMap[72]=\"IrregularSeal2\";\n mMap[73]=\"LightningBolt\";\n mMap[74]=\"Heart\";\n mMap[75]=\"PictureFrame\";\n mMap[76]=\"QuadArrow\";\n mMap[77]=\"LeftArrowCallout\";\n mMap[78]=\"RightArrowCallout\";\n mMap[79]=\"UpArrowCallout\";\n mMap[80]=\"DownArrowCallout\";\n mMap[81]=\"LeftRightArrowCallout\";\n mMap[82]=\"UpDownArrowCallout\";\n mMap[83]=\"QuadArrowCallout\";\n mMap[84]=\"Bevel\";\n mMap[85]=\"LeftBracket\";\n mMap[86]=\"RightBracket\";\n mMap[87]=\"LeftBrace\";\n mMap[88]=\"RightBrace\";\n mMap[89]=\"LeftUpArrow\";\n mMap[90]=\"BentUpArrow\";\n mMap[91]=\"BentArrow\";\n mMap[92]=\"Seal24\";\n mMap[93]=\"StripedRightArrow\";\n mMap[94]=\"NotchedRightArrow\";\n mMap[95]=\"BlockArc\";\n mMap[96]=\"SmileyFace\";\n mMap[97]=\"VerticalScroll\";\n mMap[98]=\"HorizontalScroll\";\n mMap[99]=\"CircularArrow\";\n mMap[100]=\"NotchedCircularArrow\";\n mMap[101]=\"UturnArrow\";\n mMap[102]=\"CurvedRightArrow\";\n mMap[103]=\"CurvedLeftArrow\";\n mMap[104]=\"CurvedUpArrow\";\n mMap[105]=\"CurvedDownArrow\";\n mMap[106]=\"CloudCallout\";\n mMap[107]=\"EllipseRibbon\";\n mMap[108]=\"EllipseRibbon2\";\n mMap[109]=\"FlowChartProcess\";\n mMap[110]=\"FlowChartDecision\";\n mMap[111]=\"FlowChartInputOutput\";\n mMap[112]=\"FlowChartPredefinedProcess\";\n mMap[113]=\"FlowChartInternalStorage\";\n mMap[114]=\"FlowChartDocument\";\n mMap[115]=\"FlowChartMultidocument\";\n mMap[116]=\"FlowChartTerminator\";\n mMap[117]=\"FlowChartPreparation\";\n mMap[118]=\"FlowChartManualInput\";\n mMap[119]=\"FlowChartManualOperation\";\n mMap[120]=\"FlowChartConnector\";\n mMap[121]=\"FlowChartPunchedCard\";\n mMap[122]=\"FlowChartPunchedTape\";\n mMap[123]=\"FlowChartSummingJunction\";\n mMap[124]=\"FlowChartOr\";\n mMap[125]=\"FlowChartCollate\";\n mMap[126]=\"FlowChartSort\";\n mMap[127]=\"FlowChartExtract\";\n mMap[128]=\"FlowChartMerge\";\n mMap[129]=\"FlowChartOfflineStorage\";\n mMap[130]=\"FlowChartOnlineStorage\";\n mMap[131]=\"FlowChartMagneticTape\";\n mMap[132]=\"FlowChartMagneticDisk\";\n mMap[133]=\"FlowChartMagneticDrum\";\n mMap[134]=\"FlowChartDisplay\";\n mMap[135]=\"FlowChartDelay\";\n mMap[136]=\"TextPlainText\";\n mMap[137]=\"TextStop\";\n mMap[138]=\"TextTriangle\";\n mMap[139]=\"TextTriangleInverted\";\n mMap[140]=\"TextChevron\";\n mMap[141]=\"TextChevronInverted\";\n mMap[142]=\"TextRingInside\";\n mMap[143]=\"TextRingOutside\";\n mMap[144]=\"TextArchUpCurve\";\n mMap[145]=\"TextArchDownCurve\";\n mMap[146]=\"TextCircleCurve\";\n mMap[147]=\"TextButtonCurve\";\n mMap[148]=\"TextArchUpPour\";\n mMap[149]=\"TextArchDownPour\";\n mMap[150]=\"TextCirclePour\";\n mMap[151]=\"TextButtonPour\";\n mMap[152]=\"TextCurveUp\";\n mMap[153]=\"TextCurveDown\";\n mMap[154]=\"TextCascadeUp\";\n mMap[155]=\"TextCascadeDown\";\n mMap[156]=\"TextWave1\";\n mMap[157]=\"TextWave2\";\n mMap[158]=\"TextWave3\";\n mMap[159]=\"TextWave4\";\n mMap[160]=\"TextInflate\";\n mMap[161]=\"TextDeflate\";\n mMap[162]=\"TextInflateBottom\";\n mMap[163]=\"TextDeflateBottom\";\n mMap[164]=\"TextInflateTop\";\n mMap[165]=\"TextDeflateTop\";\n mMap[166]=\"TextDeflateInflate\";\n mMap[167]=\"TextDeflateInflateDeflate\";\n mMap[168]=\"TextFadeRight\";\n mMap[169]=\"TextFadeLeft\";\n mMap[170]=\"TextFadeUp\";\n mMap[171]=\"TextFadeDown\";\n mMap[172]=\"TextSlantUp\";\n mMap[173]=\"TextSlantDown\";\n mMap[174]=\"TextCanUp\";\n mMap[175]=\"TextCanDown\";\n mMap[176]=\"FlowChartAlternateProcess\";\n mMap[177]=\"FlowChartOffpageConnector\";\n mMap[178]=\"Callout90\";\n mMap[179]=\"AccentCallout90\";\n mMap[180]=\"BorderCallout90\";\n mMap[181]=\"AccentBorderCallout90\";\n mMap[182]=\"LeftRightUpArrow\";\n mMap[183]=\"Sun\";\n mMap[184]=\"Moon\";\n mMap[185]=\"BracketPair\";\n mMap[186]=\"BracePair\";\n mMap[187]=\"Seal4\";\n mMap[188]=\"DoubleWave\";\n mMap[189]=\"ActionButtonBlank\";\n mMap[190]=\"ActionButtonHome\";\n mMap[191]=\"ActionButtonHelp\";\n mMap[192]=\"ActionButtonInformation\";\n mMap[193]=\"ActionButtonForwardNext\";\n mMap[194]=\"ActionButtonBackPrevious\";\n mMap[195]=\"ActionButtonEnd\";\n mMap[196]=\"ActionButtonBeginning\";\n mMap[197]=\"ActionButtonReturn\";\n mMap[198]=\"ActionButtonDocument\";\n mMap[199]=\"ActionButtonSound\";\n mMap[200]=\"ActionButtonMovie\";\n mMap[201]=\"HostControl\";\n mMap[202]=\"TextBox\";\n}\n\n\/\/ DffOPT\n\nsal_uInt32 DffOPT::get_property_count()\n{\n return getInstance();\n}\n\ndoctok::Reference<Properties>::Pointer_t\nDffOPT::get_property(sal_uInt32 nPos)\n{\n WW8FOPTE * pTmp = new WW8FOPTE(this, 0x8 + nPos * WW8FOPTE::getSize());\n pTmp->setIndex(nPos);\n\n return doctok::Reference<Properties>::Pointer_t(pTmp);\n}\n\nsal_uInt32 DffOPT::get_extraoffset_count()\n{\n return get_property_count();\n}\n\nsal_uInt32 DffOPT::get_extraoffset(sal_uInt32 pos)\n{\n sal_uInt32 nResult;\n sal_uInt32 nCount = get_property_count();\n\n if (pos < nCount)\n {\n nResult = 0x8 + nCount * WW8FOPTE::getSize();\n\n for (sal_uInt32 n = 0; n < pos; ++n)\n {\n WW8FOPTE aFOPTE(this, 0x8 + n * WW8FOPTE::getSize());\n\n if (aFOPTE.get_fComplex())\n {\n sal_uInt32 nValue = aFOPTE.get_op();\n nResult += nValue;\n }\n }\n }\n else\n nResult = getCount();\n\n return nResult;\n}\n\n\/\/DffDGG\n\nsal_uInt32 DffDGG::get_fidcl_count()\n{\n return (getCount() - 0x18) \/ WW8FIDCL::getSize();\n}\n\ndoctok::Reference<Properties>::Pointer_t\nDffDGG::get_fidcl(sal_uInt32 pos)\n{\n return doctok::Reference<Properties>::Pointer_t\n (new WW8FIDCL(this, 0x18 + pos * WW8FIDCL::getSize()));\n}\n\n\n\/\/ DffBSE\n\nrtl::OUString DffBSE::get_blipname()\n{\n rtl::OUString sResult;\n WW8FBSE aFBSE(this, 0x8);\n\n if (aFBSE.get_cbName() > 0)\n sResult = getString(0x24, aFBSE.get_cbName());\n\n return sResult;\n}\n\nWW8BinaryObjReference::Pointer_t DffBSE::get_binary()\n{\n return WW8BinaryObjReference::Pointer_t\n (new WW8BinaryObjReference(this, WW8FBSE::getSize() + 0x8,\n getCount() - WW8FBSE::getSize() - 0x8));\n}\n\n\/\/ WW8FOPTE\nvoid WW8FOPTE::resolveNoAuto(Properties & rHandler)\n{\n sal_uInt16 nId = get_pid() + 1;\n sal_uInt32 nOp = get_op();\n sal_uInt32 nMask = 2;\n\n while (isBooleanDffOpt(nId))\n {\n WW8Value::Pointer_t pVal = createValue(getDffOptName(nId));\n rHandler.attribute(NS_rtf::LN_shpname, *pVal);\n\n pVal = createValue((nOp & nMask) != 0);\n rHandler.attribute(NS_rtf::LN_shpvalue, *pVal);\n\n --nId;\n nMask = nMask << 1;\n }\n}\n\n\/\/ DffFSP\n\nrtl::OUString DffFSP::get_shptypename()\n{\n string aName = (*ShapeTypeToString::Instance())(get_shptype());\n\n return rtl::OUString::createFromAscii(aName.c_str());\n}\n\n}\n<commit_msg>corrected offset for binary content of picture data<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DffImpl.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hbrinkm $ $Date: 2006-11-06 10:48:06 $\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#include \"resources.hxx\"\n\nnamespace doctok\n{\nclass ShapeTypeToString\n{\n typedef boost::shared_ptr<ShapeTypeToString> Pointer_t;\n\n static Pointer_t pInstance;\n\n typedef map<sal_uInt32, string> Map_t;\n Map_t mMap;\n\nprotected:\n ShapeTypeToString();\n\npublic:\n static Pointer_t Instance()\n {\n if (pInstance == NULL)\n pInstance = Pointer_t(new ShapeTypeToString());\n\n return pInstance;\n }\n\n string operator()(sal_uInt32 nShapeType)\n {\n return mMap[nShapeType];\n }\n};\n\nShapeTypeToString::Pointer_t ShapeTypeToString::pInstance;\n\nShapeTypeToString::ShapeTypeToString()\n{\n mMap[0]=\"NotPrimitive\";\n mMap[1]=\"Rectangle\";\n mMap[2]=\"RoundRectangle\";\n mMap[3]=\"Ellipse\";\n mMap[4]=\"Diamond\";\n mMap[5]=\"IsocelesTriangle\";\n mMap[6]=\"RightTriangle\";\n mMap[7]=\"Parallelogram\";\n mMap[8]=\"Trapezoid\";\n mMap[9]=\"Hexagon\";\n mMap[10]=\"Octagon\";\n mMap[11]=\"Plus\";\n mMap[12]=\"Star\";\n mMap[13]=\"Arrow\";\n mMap[14]=\"ThickArrow\";\n mMap[15]=\"HomePlate\";\n mMap[16]=\"Cube\";\n mMap[17]=\"Balloon\";\n mMap[18]=\"Seal\";\n mMap[19]=\"Arc\";\n mMap[20]=\"Line\";\n mMap[21]=\"Plaque\";\n mMap[22]=\"Can\";\n mMap[23]=\"Donut\";\n mMap[24]=\"TextSimple\";\n mMap[25]=\"TextOctagon\";\n mMap[26]=\"TextHexagon\";\n mMap[27]=\"TextCurve\";\n mMap[28]=\"TextWave\";\n mMap[29]=\"TextRing\";\n mMap[30]=\"TextOnCurve\";\n mMap[31]=\"TextOnRing\";\n mMap[32]=\"StraightConnector1\";\n mMap[33]=\"BentConnector2\";\n mMap[34]=\"BentConnector3\";\n mMap[35]=\"BentConnector4\";\n mMap[36]=\"BentConnector5\";\n mMap[37]=\"CurvedConnector2\";\n mMap[38]=\"CurvedConnector3\";\n mMap[39]=\"CurvedConnector4\";\n mMap[40]=\"CurvedConnector5\";\n mMap[41]=\"Callout1\";\n mMap[42]=\"Callout2\";\n mMap[43]=\"Callout3\";\n mMap[44]=\"AccentCallout1\";\n mMap[45]=\"AccentCallout2\";\n mMap[46]=\"AccentCallout3\";\n mMap[47]=\"BorderCallout1\";\n mMap[48]=\"BorderCallout2\";\n mMap[49]=\"BorderCallout3\";\n mMap[50]=\"AccentBorderCallout1\";\n mMap[51]=\"AccentBorderCallout2\";\n mMap[52]=\"AccentBorderCallout3\";\n mMap[53]=\"Ribbon\";\n mMap[54]=\"Ribbon2\";\n mMap[55]=\"Chevron\";\n mMap[56]=\"Pentagon\";\n mMap[57]=\"NoSmoking\";\n mMap[58]=\"Seal8\";\n mMap[59]=\"Seal16\";\n mMap[60]=\"Seal32\";\n mMap[61]=\"WedgeRectCallout\";\n mMap[62]=\"WedgeRRectCallout\";\n mMap[63]=\"WedgeEllipseCallout\";\n mMap[64]=\"Wave\";\n mMap[65]=\"FoldedCorner\";\n mMap[66]=\"LeftArrow\";\n mMap[67]=\"DownArrow\";\n mMap[68]=\"UpArrow\";\n mMap[69]=\"LeftRightArrow\";\n mMap[70]=\"UpDownArrow\";\n mMap[71]=\"IrregularSeal1\";\n mMap[72]=\"IrregularSeal2\";\n mMap[73]=\"LightningBolt\";\n mMap[74]=\"Heart\";\n mMap[75]=\"PictureFrame\";\n mMap[76]=\"QuadArrow\";\n mMap[77]=\"LeftArrowCallout\";\n mMap[78]=\"RightArrowCallout\";\n mMap[79]=\"UpArrowCallout\";\n mMap[80]=\"DownArrowCallout\";\n mMap[81]=\"LeftRightArrowCallout\";\n mMap[82]=\"UpDownArrowCallout\";\n mMap[83]=\"QuadArrowCallout\";\n mMap[84]=\"Bevel\";\n mMap[85]=\"LeftBracket\";\n mMap[86]=\"RightBracket\";\n mMap[87]=\"LeftBrace\";\n mMap[88]=\"RightBrace\";\n mMap[89]=\"LeftUpArrow\";\n mMap[90]=\"BentUpArrow\";\n mMap[91]=\"BentArrow\";\n mMap[92]=\"Seal24\";\n mMap[93]=\"StripedRightArrow\";\n mMap[94]=\"NotchedRightArrow\";\n mMap[95]=\"BlockArc\";\n mMap[96]=\"SmileyFace\";\n mMap[97]=\"VerticalScroll\";\n mMap[98]=\"HorizontalScroll\";\n mMap[99]=\"CircularArrow\";\n mMap[100]=\"NotchedCircularArrow\";\n mMap[101]=\"UturnArrow\";\n mMap[102]=\"CurvedRightArrow\";\n mMap[103]=\"CurvedLeftArrow\";\n mMap[104]=\"CurvedUpArrow\";\n mMap[105]=\"CurvedDownArrow\";\n mMap[106]=\"CloudCallout\";\n mMap[107]=\"EllipseRibbon\";\n mMap[108]=\"EllipseRibbon2\";\n mMap[109]=\"FlowChartProcess\";\n mMap[110]=\"FlowChartDecision\";\n mMap[111]=\"FlowChartInputOutput\";\n mMap[112]=\"FlowChartPredefinedProcess\";\n mMap[113]=\"FlowChartInternalStorage\";\n mMap[114]=\"FlowChartDocument\";\n mMap[115]=\"FlowChartMultidocument\";\n mMap[116]=\"FlowChartTerminator\";\n mMap[117]=\"FlowChartPreparation\";\n mMap[118]=\"FlowChartManualInput\";\n mMap[119]=\"FlowChartManualOperation\";\n mMap[120]=\"FlowChartConnector\";\n mMap[121]=\"FlowChartPunchedCard\";\n mMap[122]=\"FlowChartPunchedTape\";\n mMap[123]=\"FlowChartSummingJunction\";\n mMap[124]=\"FlowChartOr\";\n mMap[125]=\"FlowChartCollate\";\n mMap[126]=\"FlowChartSort\";\n mMap[127]=\"FlowChartExtract\";\n mMap[128]=\"FlowChartMerge\";\n mMap[129]=\"FlowChartOfflineStorage\";\n mMap[130]=\"FlowChartOnlineStorage\";\n mMap[131]=\"FlowChartMagneticTape\";\n mMap[132]=\"FlowChartMagneticDisk\";\n mMap[133]=\"FlowChartMagneticDrum\";\n mMap[134]=\"FlowChartDisplay\";\n mMap[135]=\"FlowChartDelay\";\n mMap[136]=\"TextPlainText\";\n mMap[137]=\"TextStop\";\n mMap[138]=\"TextTriangle\";\n mMap[139]=\"TextTriangleInverted\";\n mMap[140]=\"TextChevron\";\n mMap[141]=\"TextChevronInverted\";\n mMap[142]=\"TextRingInside\";\n mMap[143]=\"TextRingOutside\";\n mMap[144]=\"TextArchUpCurve\";\n mMap[145]=\"TextArchDownCurve\";\n mMap[146]=\"TextCircleCurve\";\n mMap[147]=\"TextButtonCurve\";\n mMap[148]=\"TextArchUpPour\";\n mMap[149]=\"TextArchDownPour\";\n mMap[150]=\"TextCirclePour\";\n mMap[151]=\"TextButtonPour\";\n mMap[152]=\"TextCurveUp\";\n mMap[153]=\"TextCurveDown\";\n mMap[154]=\"TextCascadeUp\";\n mMap[155]=\"TextCascadeDown\";\n mMap[156]=\"TextWave1\";\n mMap[157]=\"TextWave2\";\n mMap[158]=\"TextWave3\";\n mMap[159]=\"TextWave4\";\n mMap[160]=\"TextInflate\";\n mMap[161]=\"TextDeflate\";\n mMap[162]=\"TextInflateBottom\";\n mMap[163]=\"TextDeflateBottom\";\n mMap[164]=\"TextInflateTop\";\n mMap[165]=\"TextDeflateTop\";\n mMap[166]=\"TextDeflateInflate\";\n mMap[167]=\"TextDeflateInflateDeflate\";\n mMap[168]=\"TextFadeRight\";\n mMap[169]=\"TextFadeLeft\";\n mMap[170]=\"TextFadeUp\";\n mMap[171]=\"TextFadeDown\";\n mMap[172]=\"TextSlantUp\";\n mMap[173]=\"TextSlantDown\";\n mMap[174]=\"TextCanUp\";\n mMap[175]=\"TextCanDown\";\n mMap[176]=\"FlowChartAlternateProcess\";\n mMap[177]=\"FlowChartOffpageConnector\";\n mMap[178]=\"Callout90\";\n mMap[179]=\"AccentCallout90\";\n mMap[180]=\"BorderCallout90\";\n mMap[181]=\"AccentBorderCallout90\";\n mMap[182]=\"LeftRightUpArrow\";\n mMap[183]=\"Sun\";\n mMap[184]=\"Moon\";\n mMap[185]=\"BracketPair\";\n mMap[186]=\"BracePair\";\n mMap[187]=\"Seal4\";\n mMap[188]=\"DoubleWave\";\n mMap[189]=\"ActionButtonBlank\";\n mMap[190]=\"ActionButtonHome\";\n mMap[191]=\"ActionButtonHelp\";\n mMap[192]=\"ActionButtonInformation\";\n mMap[193]=\"ActionButtonForwardNext\";\n mMap[194]=\"ActionButtonBackPrevious\";\n mMap[195]=\"ActionButtonEnd\";\n mMap[196]=\"ActionButtonBeginning\";\n mMap[197]=\"ActionButtonReturn\";\n mMap[198]=\"ActionButtonDocument\";\n mMap[199]=\"ActionButtonSound\";\n mMap[200]=\"ActionButtonMovie\";\n mMap[201]=\"HostControl\";\n mMap[202]=\"TextBox\";\n}\n\n\/\/ DffOPT\n\nsal_uInt32 DffOPT::get_property_count()\n{\n return getInstance();\n}\n\ndoctok::Reference<Properties>::Pointer_t\nDffOPT::get_property(sal_uInt32 nPos)\n{\n WW8FOPTE * pTmp = new WW8FOPTE(this, 0x8 + nPos * WW8FOPTE::getSize());\n pTmp->setIndex(nPos);\n\n return doctok::Reference<Properties>::Pointer_t(pTmp);\n}\n\nsal_uInt32 DffOPT::get_extraoffset_count()\n{\n return get_property_count();\n}\n\nsal_uInt32 DffOPT::get_extraoffset(sal_uInt32 pos)\n{\n sal_uInt32 nResult;\n sal_uInt32 nCount = get_property_count();\n\n if (pos < nCount)\n {\n nResult = 0x8 + nCount * WW8FOPTE::getSize();\n\n for (sal_uInt32 n = 0; n < pos; ++n)\n {\n WW8FOPTE aFOPTE(this, 0x8 + n * WW8FOPTE::getSize());\n\n if (aFOPTE.get_fComplex())\n {\n sal_uInt32 nValue = aFOPTE.get_op();\n nResult += nValue;\n }\n }\n }\n else\n nResult = getCount();\n\n return nResult;\n}\n\n\/\/DffDGG\n\nsal_uInt32 DffDGG::get_fidcl_count()\n{\n return (getCount() - 0x18) \/ WW8FIDCL::getSize();\n}\n\ndoctok::Reference<Properties>::Pointer_t\nDffDGG::get_fidcl(sal_uInt32 pos)\n{\n return doctok::Reference<Properties>::Pointer_t\n (new WW8FIDCL(this, 0x18 + pos * WW8FIDCL::getSize()));\n}\n\n\n\/\/ DffBSE\n\nrtl::OUString DffBSE::get_blipname()\n{\n rtl::OUString sResult;\n WW8FBSE aFBSE(this, 0x8);\n\n if (aFBSE.get_cbName() > 0)\n sResult = getString(0x24, aFBSE.get_cbName());\n\n return sResult;\n}\n\nWW8BinaryObjReference::Pointer_t DffBSE::get_binary()\n{\n WW8BinaryObjReference::Pointer_t pResult;\n\n if (getCount() > 0x45)\n pResult = WW8BinaryObjReference::Pointer_t\n (new WW8BinaryObjReference(this, 0x45,\n getCount() - 0x45));\n\n return pResult;\n}\n\n\/\/ WW8FOPTE\nvoid WW8FOPTE::resolveNoAuto(Properties & rHandler)\n{\n sal_uInt16 nId = get_pid() + 1;\n sal_uInt32 nOp = get_op();\n sal_uInt32 nMask = 2;\n\n while (isBooleanDffOpt(nId))\n {\n WW8Value::Pointer_t pVal = createValue(getDffOptName(nId));\n rHandler.attribute(NS_rtf::LN_shpname, *pVal);\n\n pVal = createValue((nOp & nMask) != 0);\n rHandler.attribute(NS_rtf::LN_shpvalue, *pVal);\n\n --nId;\n nMask = nMask << 1;\n }\n}\n\n\/\/ DffFSP\n\nrtl::OUString DffFSP::get_shptypename()\n{\n string aName = (*ShapeTypeToString::Instance())(get_shptype());\n\n return rtl::OUString::createFromAscii(aName.c_str());\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"fastlib\/fastlib.h\"\n#include \"..\/fastica\/lin_alg.h\"\n\nvoid SaveCorrectly(const char *filename, Matrix a) {\n Matrix a_transpose;\n la::TransposeInit(a, &a_transpose);\n data::Save(filename, a_transpose);\n}\n\n\nint compare_doubles_ascending(const void* a, const void* b) {\n double* arg1 = (double*) a;\n double* arg2 = (double*) b;\n if(*arg1 < *arg2) {\n return -1;\n }\n else if(*arg1 == *arg2) {\n return 0;\n }\n else {\n return 1;\n }\n}\n \n\ndouble vasicekm(Vector v, index_t m) {\n\n Vector sorted_v;\n\n index_t n = v.length();\n\n sorted_v.Copy(v);\n\n qsort(sorted_v.ptr(), n, sizeof(double), compare_doubles_ascending);\n\n double sum_logs = 0;\n\n for(index_t i = 0; i < n; i++) {\n if((i + m) > (n - 1)) {\n sum_logs = sum_logs + log(sorted_v[n - 1] - sorted_v[i - m]);\n }\n else if((i - m) < 0) {\n sum_logs = sum_logs + log(sorted_v[i + m] - sorted_v[0]);\n }\n else {\n sum_logs = sum_logs + log(sorted_v[i + m] - sorted_v[i - m]);\n }\n }\n\n double h = (sum_logs \/ n) + log(n \/ (2 * m));\n\n return h;\n\n}\n\n\n\nvoid RADICALOptTheta(Matrix X_t, double std_dev, index_t m,\n\t\t index_t reps, double new_k, double range,\n\t\t double *theta_star, Matrix* rotator_star) {\n Matrix X_aug_t;\n\n index_t d = X_t.n_cols();\n index_t n = X_t.n_rows();\n\n \n if(reps == 1) {\n X_aug_t.Alias(X_t);\n }\n else {\n Matrix noise_matrix;\n Scale(std_dev,\n\t RandNormalInit(n * reps, d, &noise_matrix));\n \n X_aug_t.Init(n * reps, d);\n \n double* X_t_elements = X_t.ptr();\n double* X_aug_t_elements = X_aug_t.ptr();\n \n index_t num_elements = d * n;\n for(index_t rep_num = 0; rep_num < reps; rep_num++) {\n memcpy(X_aug_t_elements + (rep_num * num_elements) * sizeof(double),\n\t X_t_elements,\n\t num_elements * sizeof(double));\n }\n\n la::AddTo(noise_matrix, &X_aug_t);\n }\n\n double perc = range \/ (M_PI \/ 2);\n double number_k = perc * k;\n index_t start = (index_t) floor((k - number_k) \/ 2) + 1;\n index_t end_point = (index_t) ceil((k - number_k) \/ 2);\n\n for(index_t i = 0; i < k; i++) {\n double theta =\n ((double) (i - 1) \/ (double) (k - 1) * M_PI \/ 2) - (M_PI \/ 4);\n\n double cos_theta = cos(theta);\n double sin_theta = sin(theta);\n Matrix rotator;\n rotator.Init(2,2);\n rotator.set(0,0, cos_theta);\n rotator.set(0,1, sin_theta);\n rotator.set(1,0, -sin_theta);\n rotator.set(1,1, cos_theta);\n Matrix rotated_X_aug_t;\n la::MulTransBInit(X_aug_t, rotator, &rotated_X_aug_t);\n\n Vector marginal_at_theta;\n marginal_at_theta.Init(d);\n for(index_t j = 0; j < d; j++) {\n Vector col_vector;\n rotated_X_aug_t.MakeColumnVector(j, &col_vector);\n marginal_at_theta[j] = vasicekm(col_vector, m);\n }\n \n \n\t\t \n\n \n}\n\n\n\nvoid RADICAL(Matrix X, Matrix whitening_matrix, Matrix X_whitened,\n\t index_t k, bool aug_flag, index_t reps, double std_dev, index_t m,\n\t Matrix* W, Matrix* Y) {\n\n index_t d = X.n_rows();\n index_t n = X.n_cols();\n \n \n Matrix X_t, X_current_t, X_whitened_t;\n la::TransposeInit(X, &X_t);\n la::TransposeInit(X_whitened, &X_current_t);\n X_whitened_t.Copy(X_current_t);\n \n\n index_t sweeps = d - 1;\n Matrix* old_total_rotator;\n Matrix* total_rotator;\n Matrix* temp_total_rotator;\n DiagMatrixInit(d, 1, old_total_rotator);\n DiagMatrixInit(d, 1, total_rotator);\n\n index_t sweep_iteration = 0;\n\n\n\n index_t final_k = k;\n double start_k_float = final_k \/ pow(1.3, ceil(sweeps \/ 2));\n double new_k_float = start_k_float;\n\n for(index_t sweep_num = 1; sweep_num < sweeps; sweep_num++) {\n printf(\"Sweep # %d of %d.\\n\", sweep_num, sweeps);\n double range = M_PI \/ 2;\n\n double new_k;\n if(sweep_num > ((double) sweeps \/ 2)) {\n new_k_float *= 1.3;\n new_k = floor(new_k_float);\n }\n else {\n new_k_float = start_k_float;\n new_k = max(30, (int) floor(new_k_float));\n }\n\n for(index_t i = 0; i < d - 1; i++) {\n for(index_t j = i + 1; j < d; j++) {\n\tMatrix cur_subspace_t;\n\tVector selected_columns;\n\tselected_columns.Init(2);\n\tselected_columns[0] = i;\n\tselected_columns[1] = j;\n\tMakeSubMatrixByColumns(selected_columns, X_current_t, &cur_subspace_t);\n\n\tdouble theta_star;\n\tMatrix rotator_star;\n\tRADICALOptTheta(cur_subspace_t, std_dev, m, reps, new_k, range,\n\t\t\t&theta_star, &rotator_star);\n\n\tMatrix new_rotator;\n\tDiagMatrixInit(d, 1, &new_rotator);\n\n\tnew_rotator.set(i, i, cos(theta_star));\n\tnew_rotator.set(i, j, -sin(theta_star));\n\tnew_rotator.set(j, i, sin(theta_star));\n\tnew_rotator.set(j, j, cos(theta_star));\n\t\n\ttemp_total_rotator = old_total_rotator;\n\told_total_rotator = total_rotator;\n\ttotal_rotator = temp_total_rotator;\n\tla::MulInit(new_rotator, *old_total_rotator, total_rotator);\n\t \n\tla::MulTransAOverwrite(X_whitened_t, *total_rotator, &X_current_t);\n }\n }\n }\n\n\n la::MulInit(*total_rotator, whitening_matrix, W);\n la::MulInit(*W, X, Y);\n}\n\n\n\n \n \n \n\n\n\t\n\n\n\n\/\/ there should be some way to wrap X, W, and Y into our module no? ask ryan\n\nint RADICALMain(datanode *module, Matrix X, Matrix *W, Matrix *Y) {\n\n Matrix X_centered, X_whitened, whitening_matrix;\n \n index_t k = 150;\n bool aug_flag = false;\n index_t reps = 30;\n double std_dev = 0.175;\n\n index_t m = (index_t) floor(sqrt(n));\n\n Center(X, &X_centered);\n WhitenUsingSVD(X_centered, &X_whitened, &whitening_matrix);\n\n\n RADICAL(X, whitening_matrix, X_whitened,\n\t k, aug_flag, reps, std_dev, m,\n\t W, Y);\n\n\n\n return SUCCESS_PASS;\n}\n\n\n\nint main(int argc, char *argv[]) {\n fx_init(argc, argv);\n\n srand48(time(0));\n\n Matrix X, W, Y;\n\n const char *data = fx_param_str_req(NULL, \"data\");\n data::Load(data, &X);\n \n int ret_val = RADICALMain(fx_root, X, &W, &Y);\n\n \/\/SaveCorrectly(\"unmixing_matrix.dat\", W);\n \/\/SaveCorrectly(\"indep_comps.dat\", Y);\n\n fx_done();\n\n return ret_val;\n}\n<commit_msg>updated niche\/radical<commit_after>#include \"fastlib\/fastlib.h\"\n#include \"..\/fastica\/lin_alg.h\"\n\nvoid SaveCorrectly(const char *filename, Matrix a) {\n Matrix a_transpose;\n la::TransposeInit(a, &a_transpose);\n data::Save(filename, a_transpose);\n}\n\n\nint compare_doubles_ascending(const void* a, const void* b) {\n double* arg1 = (double*) a;\n double* arg2 = (double*) b;\n if(*arg1 < *arg2) {\n return -1;\n }\n else if(*arg1 == *arg2) {\n return 0;\n }\n else {\n return 1;\n }\n}\n \n\ndouble vasicekm(Vector v, index_t m) {\n\n Vector sorted_v;\n\n index_t n = v.length();\n\n sorted_v.Copy(v);\n\n qsort(sorted_v.ptr(), n, sizeof(double), compare_doubles_ascending);\n\n double sum_logs = 0;\n\n for(index_t i = 0; i < n; i++) {\n if((i + m) > (n - 1)) {\n sum_logs = sum_logs + log(sorted_v[n - 1] - sorted_v[i - m]);\n }\n else if((i - m) < 0) {\n sum_logs = sum_logs + log(sorted_v[i + m] - sorted_v[0]);\n }\n else {\n sum_logs = sum_logs + log(sorted_v[i + m] - sorted_v[i - m]);\n }\n }\n\n double h = (sum_logs \/ n) + log(n \/ (2 * m));\n\n return h;\n\n}\n\n\n\nvoid RADICALOptTheta(Matrix X_t, double std_dev, index_t m,\n\t\t index_t reps, double k, double range,\n\t\t double *theta_star, Matrix* rotator_star) {\n Matrix X_aug_t;\n\n index_t d = X_t.n_cols();\n index_t n = X_t.n_rows();\n\n \n if(reps == 1) {\n X_aug_t.Alias(X_t);\n }\n else {\n Matrix noise_matrix;\n Scale(std_dev,\n\t RandNormalInit(n * reps, d, &noise_matrix));\n \n X_aug_t.Init(n * reps, d);\n \n double* X_t_elements = X_t.ptr();\n double* X_aug_t_elements = X_aug_t.ptr();\n \n index_t num_elements = d * n;\n for(index_t rep_num = 0; rep_num < reps; rep_num++) {\n memcpy(X_aug_t_elements + (rep_num * num_elements) * sizeof(double),\n\t X_t_elements,\n\t num_elements * sizeof(double));\n }\n\n la::AddTo(noise_matrix, &X_aug_t);\n }\n\n Vector entropy;\n entropy.Init((index_t) k);\n\n for(index_t i = 0; i < k; i++) {\n double theta =\n ((double) (i - 1) \/ (k - 1) * M_PI \/ 2) - (M_PI \/ 4);\n\n double cos_theta = cos(theta);\n double sin_theta = sin(theta);\n Matrix rotator;\n rotator.Init(2,2);\n rotator.set(0,0, cos_theta);\n rotator.set(0,1, -sin_theta);\n rotator.set(1,0, sin_theta);\n rotator.set(1,1, cos_theta);\n Matrix rotated_X_aug_t;\n la::MulTransBInit(X_aug_t, rotator, &rotated_X_aug_t);\n\n Vector marginal_at_theta;\n marginal_at_theta.Init(d);\n for(index_t j = 0; j < d; j++) {\n Vector col_vector;\n rotated_X_aug_t.MakeColumnVector(j, &col_vector);\n marginal_at_theta[j] = vasicekm(col_vector, m);\n }\n\n entropy[i] = Sum(&marginal_at_theta);\n }\n\n double min_entropy = DBL_MAX;\n index_t arg_min_entropy = 0;\n\n for(index_t i = 0; i < k; i++) {\n if(entropy[i] < min_entropy) {\n arg_min_entropy = i;\n min_entropy = entropy[i];\n }\n }\n \n *theta_star = ((arg_min_entropy - 1) \/ (k - 1) * M_PI \/ 2) - (M_PI \/ 4);\n\n printf(\"rotated %5.2f degrees.\\n\", (*theta_star) \/ (2 * M_PI) * 360);\n\n rotator_star -> Init(2, 2);\n\n double cos_theta_star = cos(*theta_star);\n double sin_theta_star = sin(*theta_star);\n rotator_star -> set(0, 0, cos_theta_star);\n rotator_star -> set(0, 1, -sin_theta_star);\n rotator_star -> set(1, 0, sin_theta_star);\n rotator_star -> set(1, 1, cos_theta_star);\n \n}\n\n\n\n void RADICAL(Matrix X, Matrix whitening_matrix, Matrix X_whitened,\n\t index_t k, bool aug_flag, index_t reps, double std_dev, index_t m,\n\t Matrix* W, Matrix* Y) { \n\n index_t d = X.n_rows();\n \/\/ index_t n = X.n_cols();\n \n \n Matrix X_t, X_current_t, X_whitened_t;\n la::TransposeInit(X, &X_t);\n la::TransposeInit(X_whitened, &X_current_t);\n X_whitened_t.Copy(X_current_t);\n \n\n index_t sweeps = d - 1;\n Matrix* old_total_rotator = NULL;\n Matrix* total_rotator = NULL;\n Matrix* temp_total_rotator = NULL;\n DiagMatrixInit(d, 1, old_total_rotator);\n DiagMatrixInit(d, 1, total_rotator);\n\n\n\n index_t final_k = k;\n double start_k_float = final_k \/ pow(1.3, ceil(sweeps \/ 2));\n double new_k_float = start_k_float;\n\n for(index_t sweep_num = 1; sweep_num < sweeps; sweep_num++) {\n printf(\"Sweep # %d of %d.\\n\", sweep_num, sweeps);\n double range = M_PI \/ 2;\n\n double new_k;\n if(sweep_num > ((double) sweeps \/ 2)) {\n new_k_float *= 1.3;\n new_k = floor(new_k_float);\n }\n else {\n new_k_float = start_k_float;\n new_k = max(30, (int) floor(new_k_float));\n }\n\n for(index_t i = 0; i < d - 1; i++) {\n for(index_t j = i + 1; j < d; j++) {\n\tMatrix cur_subspace_t;\n\tVector selected_columns;\n\tselected_columns.Init(2);\n\tselected_columns[0] = i;\n\tselected_columns[1] = j;\n\tMakeSubMatrixByColumns(selected_columns, X_current_t, &cur_subspace_t);\n\n\tdouble theta_star;\n\tMatrix rotator_star;\n\tRADICALOptTheta(cur_subspace_t, std_dev, m, reps, new_k, range,\n\t\t\t&theta_star, &rotator_star);\n\n\tMatrix new_rotator;\n\tDiagMatrixInit(d, 1, &new_rotator);\n\n\tnew_rotator.set(i, i, cos(theta_star));\n\tnew_rotator.set(i, j, -sin(theta_star));\n\tnew_rotator.set(j, i, sin(theta_star));\n\tnew_rotator.set(j, j, cos(theta_star));\n\t\n\ttemp_total_rotator = old_total_rotator;\n\told_total_rotator = total_rotator;\n\ttotal_rotator = temp_total_rotator;\n\tla::MulInit(new_rotator, *old_total_rotator, total_rotator);\n\t \n\tla::MulTransAOverwrite(X_whitened_t, *total_rotator, &X_current_t);\n }\n }\n }\n\n\n la::MulInit(*total_rotator, whitening_matrix, W);\n la::MulInit(*W, X, Y);\n}\n\n\n\n \n \n \n\n\n\t\n\n\n\n\/\/ there should be some way to wrap X, W, and Y into our module no? ask ryan\n\nint RADICALMain(datanode *module, Matrix X, Matrix *W, Matrix *Y) {\n\n Matrix X_centered, X_whitened, whitening_matrix;\n\n index_t n = X.n_cols();\n \n index_t k = 150;\n bool aug_flag = false;\n index_t reps = 30;\n double std_dev = 0.175;\n\n index_t m = (index_t) floor(sqrt(n));\n\n Center(X, &X_centered);\n WhitenUsingSVD(X_centered, &X_whitened, &whitening_matrix);\n\n\n RADICAL(X, whitening_matrix, X_whitened,\n\t k, aug_flag, reps, std_dev, m,\n\t W, Y);\n\n\n\n return SUCCESS_PASS;\n}\n\n\n\nint main(int argc, char *argv[]) {\n fx_init(argc, argv);\n\n srand48(time(0));\n\n Matrix X, W, Y;\n\n const char *data = fx_param_str_req(NULL, \"data\");\n data::Load(data, &X);\n \n int ret_val = RADICALMain(fx_root, X, &W, &Y);\n\n \/\/SaveCorrectly(\"unmixing_matrix.dat\", W);\n \/\/SaveCorrectly(\"indep_comps.dat\", Y);\n\n fx_done();\n\n return ret_val;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkVTKImageIO.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n Portions of this code are covered under the VTK copyright.\n See VTKCopyright.txt or http:\/\/www.kitware.com\/VTKCopyright.htm for details.\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#include \"itkVTKImageIO.h\"\n#include <stdio.h>\n\nnamespace itk\n{\n\nVTKImageIO::VTKImageIO()\n{\n this->SetNumberOfDimensions(2);\n m_ByteOrder = LittleEndian;\n m_FileType = ASCII;\n \n}\n\nVTKImageIO::~VTKImageIO()\n{\n}\n\nbool VTKImageIO::OpenVTKFileForReading(std::ifstream& os, \n const char* filename)\n \n{\n \/\/ Make sure that we have a file to \n if ( filename == \"\" )\n {\n itkExceptionMacro(<<\"A FileName must be specified.\");\n return false;\n }\n\n \/\/ Close file from any previous image\n if ( os.is_open() )\n {\n os.close();\n }\n \n \/\/ Open the new file for reading\n itkDebugMacro(<< \"Initialize: opening file \" << filename);\n\n \/\/ Actually open the file\n int openMode = std::ios::in;\n\n#ifdef _WIN32\n openMode |= std::ios::binary;\n#endif\n#if defined(__GNUC__) && __GNUC__ >= 3\n os.open(filename, static_cast<std::ios_base::openmode>(openMode));\n#else\n os.open(filename, openMode);\n#endif\n if ( os.fail() )\n {\n itkExceptionMacro(<< \"Could not open file for reading: \" << filename);\n return false;\n }\n\n return true;\n}\n\nbool VTKImageIO::OpenVTKFileForWriting(std::ofstream& os, \n const char* filename)\n \n{\n \/\/ Make sure that we have a file to \n if ( filename == \"\" )\n {\n itkExceptionMacro(<<\"A FileName must be specified.\");\n return false;\n }\n\n \/\/ Close file from any previous image\n if ( os.is_open() )\n {\n os.close();\n }\n \n \/\/ Open the new file for writing\n itkDebugMacro(<< \"Initialize: opening file \" << filename);\n\n \/\/ Actually open the file\n int openMode = std::ios::out;\n\n#ifdef _WIN32\n openMode |= std::ios::binary;\n#endif\n#if defined(__GNUC__) && __GNUC__ >= 3\n os.open(filename, static_cast<std::ios_base::openmode>(openMode));\n#else\n os.open(filename, openMode);\n#endif\n if ( os.fail() )\n {\n itkExceptionMacro(<< \"Could not open file for writing: \" << filename);\n return false;\n }\n\n return true;\n}\n\n\nbool VTKImageIO::CanReadFile(const char* filename) \n{ \n std::ifstream file;\n char buffer[256];\n std::string fname(filename);\n\n if ( fname.find(\".vtk\") >= fname.length() )\n {\n return false;\n }\n\n if ( ! this->OpenVTKFileForReading(file, filename) )\n {\n return false;\n }\n\n \/\/ Check to see if its a vtk structured points file\n file.getline(buffer,255);\n file.getline(buffer,255);\n file.getline(buffer,255);\n file.getline(buffer,255);\n\n fname = buffer;\n\n if ( fname.find(\"STRUCTURED_POINTS\") < fname.length() ||\n fname.find(\"structured_points\") < fname.length() )\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n \n \nvoid VTKImageIO::Read(void* buffer)\n{\n std::ifstream file;\n char line[255];\n std::string text;\n\n \/\/ Check the input\n \/\/\n if ( ! this->OpenVTKFileForReading(file, m_FileName.c_str()) )\n {\n itkExceptionMacro(<< \"Cannot read requested file\");\n }\n\n file.getline(line,255);\n file.getline(line,255);\n file.getline(line,255);\n text = line;\n if ( text.find(\"ASCII\") < text.length() || \n text.find(\"ascii\") < text.length() )\n {\n this->SetFileTypeToASCII();\n }\n else if ( text.find(\"BINARY\") < text.length() ||\n text.find(\"binary\") < text.length() )\n {\n this->SetFileTypeToBinary();\n }\n else\n {\n itkExceptionMacro(<< \"Unrecognized type\");\n }\n file.getline(line,255);\n text = line;\n if ( text.find(\"STRUCTURED_POINTS\") >= text.length() &&\n text.find(\"structured_points\") >= text.length() )\n {\n itkExceptionMacro(<< \"Not structured points, can't read\");\n }\n\n \/\/extract dimensions, spacing, origin\n unsigned int dims[3];\n float spacing[3];\n float origin[3];\n file.getline(line,255);\n text = line;\n int i;\n\n if ( text.find(\"DIMENSIONS\") < text.length() || \n text.find(\"dimensions\") < text.length() )\n {\n sscanf(line, \"%*s %d %d %d\", dims, dims+1, dims+2);\n if ( dims[2] <= 1 )\n {\n this->SetNumberOfDimensions(2);\n }\n else\n {\n this->SetNumberOfDimensions(3);\n }\n for ( i=0; i < m_NumberOfDimensions; i++ )\n {\n m_Dimensions[i] = dims[i];\n }\n }\n else\n {\n itkExceptionMacro(<<\"No dimensions defined\");\n }\n\n file.getline(line,255);\n text = line;\n if ( text.find(\"SPACING\") < text.length() || \n text.find(\"spacing\") < text.length() )\n {\n sscanf(line, \"%*s %f %f %f\", spacing, spacing+1, spacing+2);\n for ( i=0; i < m_NumberOfDimensions; i++ )\n {\n m_Spacing[i] = spacing[i];\n }\n }\n else\n {\n itkExceptionMacro(<<\"No spacing defined\");\n }\n\n file.getline(line,255);\n text = line;\n if ( text.find(\"ORIGIN\") < text.length() || \n text.find(\"origin\") < text.length() )\n {\n sscanf(line, \"%*s %f %f %f\", origin, origin+1, origin+2);\n for ( i=0; i < m_NumberOfDimensions; i++ )\n {\n m_Origin[i] = origin[i];\n }\n }\n else\n {\n itkExceptionMacro(<<\"No origin defined\");\n }\n \n \/\/Now grab the data; need to determine the pixel type\n file.getline(line,255);\n text = line;\n while ( text.find(\"SCALARS\") >= text.length() ||\n text.find(\"scalars\") >= text.length() )\n {\n file.getline(line,255);\n text = line;\n }\n char pixelType[256];\n sscanf(line, \"%*s %*s %s\", pixelType);\n text = pixelType;\n if ( text.find(\"float\") < text.length() )\n {\n SetPixelType(FLOAT);\n SetComponentType(FLOAT);\n }\n else if ( text.find(\"double\") < text.length() )\n {\n SetPixelType(DOUBLE);\n SetComponentType(DOUBLE);\n }\n else if ( text.find(\"unsigned_char\") < text.length() )\n {\n SetPixelType(UCHAR);\n SetComponentType(UCHAR);\n }\n else if ( text.find(\"char\") < text.length() )\n {\n SetPixelType(CHAR);\n SetComponentType(CHAR);\n }\n else if ( text.find(\"unsigned_short\") < text.length() )\n {\n SetPixelType(USHORT);\n SetComponentType(USHORT);\n }\n else if ( text.find(\"short\") < text.length() )\n {\n SetPixelType(SHORT);\n SetComponentType(SHORT);\n }\n else if ( text.find(\"unsigned_int\") < text.length() )\n {\n SetPixelType(UINT);\n SetComponentType(UINT);\n }\n else if ( text.find(\"int\") < text.length() )\n {\n SetPixelType(INT);\n SetComponentType(INT);\n }\n else if ( text.find(\"unsigned_long\") < text.length() )\n {\n SetPixelType(ULONG);\n SetComponentType(ULONG);\n }\n else if ( text.find(\"long\") < text.length() )\n {\n SetPixelType(LONG);\n SetComponentType(LONG);\n }\n else\n {\n itkExceptionMacro(<<\"Unrecognized type\");\n }\n\n \/\/ grab the trailing lookup table line\n file.getline(line,255);\n \/\/We are positioned at the data. The data is read depending on whether \n \/\/it is ASCII or binary.\n if ( m_FileType == ASCII )\n {\n this->ReadBufferAsASCII(file, buffer, this->GetComponentType(),\n this->GetImageSizeInComponents());\n }\n else\n {\n file.read(static_cast<char*>(buffer), this->GetImageSizeInBytes());\n }\n}\n\nvoid VTKImageIO::ReadImageInformation()\n{\n}\n\nbool VTKImageIO::CanWriteFile(const char*)\n{\n if ( m_FileName != \"\" &&\n m_FileName.find(\".vtk\") < m_FileName.length() )\n {\n return true;\n }\n return false;\n}\n\nvoid VTKImageIO::Write(void* buffer)\n{\n std::ofstream file;\n if ( ! this->OpenVTKFileForWriting(file,m_FileName.c_str()) )\n {\n return;\n }\n\n \/\/ Check the image region for proper dimensions, etc.\n unsigned int numDims = this->GetNumberOfDimensions();\n if ( numDims < 2 || numDims > 3 )\n {\n itkExceptionMacro(<<\"VTK Writer can only write 2 or 3-dimensional images\");\n return;\n }\n ImageIORegion ioRegion = this->GetIORegion();\n\n \/\/ Write the VTK header information\n file << \"# vtk DataFile Version 3.0\\n\"; \n file << \"VTK File Generated by Insight Segmentation and Registration Toolkit (ITK)\\n\";\n\n if ( this->GetFileType() == ASCII ) { file << \"ASCII\\n\"; }\n else { file << \"BINARY\\n\"; }\n\n \/\/ Write characteristics of the data\n file << \"DATASET STRUCTURED_POINTS\\n\";\n if ( numDims == 2 )\n {\n file << \"DIMENSIONS \" << this->GetDimensions(0) << \" \"\n << this->GetDimensions(1) << \" 1\\n\";\n file << \"SPACING \" << m_Spacing[0] << \" \" << m_Spacing[1] << \" 1.0\\n\";\n file << \"ORIGIN \" << m_Origin[0] << \" \" << m_Origin[1] << \" 0.0\\n\";\n }\n else \/\/numDims == 3\n {\n file << \"DIMENSIONS \" << this->GetDimensions(0) << \" \"\n << this->GetDimensions(1) << \" \" << this->GetDimensions(2) << \"\\n\";\n file << \"SPACING \" << m_Spacing[0] << \" \" \n << m_Spacing[1] << \" \" << m_Spacing[2] << \"\\n\";\n file << \"ORIGIN \" << m_Origin[0] << \" \"\n << m_Origin[1] << \" \" << m_Origin[2] << \"\\n\";\n }\n\n file << \"POINT_DATA \" << this->GetImageSizeInPixels() << \"\\n\";\n file << \"SCALARS scalars \" \n << this->ReturnTypeAsString(this->GetComponentType()) << \" \"\n << this->GetNumberOfComponents() << \"\\n\";\n file << \"LOOKUP_TABLE default\\n\";\n\n \/\/ Write the actual pixel data\n if ( m_FileType == ASCII )\n {\n this->WriteBufferAsASCII(file, buffer, this->GetComponentType(),\n this->GetImageSizeInComponents());\n }\n else \/\/binary\n {\n file.write(static_cast<char*>(buffer), this->GetImageSizeInBytes());\n }\n}\n\nvoid VTKImageIO::PrintSelf(std::ostream& os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n}\n\n\n} \/\/ end namespace itk\n<commit_msg>ERR: unsigned\/signed comparision.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkVTKImageIO.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n Portions of this code are covered under the VTK copyright.\n See VTKCopyright.txt or http:\/\/www.kitware.com\/VTKCopyright.htm for details.\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#include \"itkVTKImageIO.h\"\n#include <stdio.h>\n\nnamespace itk\n{\n\nVTKImageIO::VTKImageIO()\n{\n this->SetNumberOfDimensions(2);\n m_ByteOrder = LittleEndian;\n m_FileType = ASCII;\n \n}\n\nVTKImageIO::~VTKImageIO()\n{\n}\n\nbool VTKImageIO::OpenVTKFileForReading(std::ifstream& os, \n const char* filename)\n \n{\n \/\/ Make sure that we have a file to \n if ( filename == \"\" )\n {\n itkExceptionMacro(<<\"A FileName must be specified.\");\n return false;\n }\n\n \/\/ Close file from any previous image\n if ( os.is_open() )\n {\n os.close();\n }\n \n \/\/ Open the new file for reading\n itkDebugMacro(<< \"Initialize: opening file \" << filename);\n\n \/\/ Actually open the file\n int openMode = std::ios::in;\n\n#ifdef _WIN32\n openMode |= std::ios::binary;\n#endif\n#if defined(__GNUC__) && __GNUC__ >= 3\n os.open(filename, static_cast<std::ios_base::openmode>(openMode));\n#else\n os.open(filename, openMode);\n#endif\n if ( os.fail() )\n {\n itkExceptionMacro(<< \"Could not open file for reading: \" << filename);\n return false;\n }\n\n return true;\n}\n\nbool VTKImageIO::OpenVTKFileForWriting(std::ofstream& os, \n const char* filename)\n \n{\n \/\/ Make sure that we have a file to \n if ( filename == \"\" )\n {\n itkExceptionMacro(<<\"A FileName must be specified.\");\n return false;\n }\n\n \/\/ Close file from any previous image\n if ( os.is_open() )\n {\n os.close();\n }\n \n \/\/ Open the new file for writing\n itkDebugMacro(<< \"Initialize: opening file \" << filename);\n\n \/\/ Actually open the file\n int openMode = std::ios::out;\n\n#ifdef _WIN32\n openMode |= std::ios::binary;\n#endif\n#if defined(__GNUC__) && __GNUC__ >= 3\n os.open(filename, static_cast<std::ios_base::openmode>(openMode));\n#else\n os.open(filename, openMode);\n#endif\n if ( os.fail() )\n {\n itkExceptionMacro(<< \"Could not open file for writing: \" << filename);\n return false;\n }\n\n return true;\n}\n\n\nbool VTKImageIO::CanReadFile(const char* filename) \n{ \n std::ifstream file;\n char buffer[256];\n std::string fname(filename);\n\n if ( fname.find(\".vtk\") >= fname.length() )\n {\n return false;\n }\n\n if ( ! this->OpenVTKFileForReading(file, filename) )\n {\n return false;\n }\n\n \/\/ Check to see if its a vtk structured points file\n file.getline(buffer,255);\n file.getline(buffer,255);\n file.getline(buffer,255);\n file.getline(buffer,255);\n\n fname = buffer;\n\n if ( fname.find(\"STRUCTURED_POINTS\") < fname.length() ||\n fname.find(\"structured_points\") < fname.length() )\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n \n \nvoid VTKImageIO::Read(void* buffer)\n{\n std::ifstream file;\n char line[255];\n std::string text;\n\n \/\/ Check the input\n \/\/\n if ( ! this->OpenVTKFileForReading(file, m_FileName.c_str()) )\n {\n itkExceptionMacro(<< \"Cannot read requested file\");\n }\n\n file.getline(line,255);\n file.getline(line,255);\n file.getline(line,255);\n text = line;\n if ( text.find(\"ASCII\") < text.length() || \n text.find(\"ascii\") < text.length() )\n {\n this->SetFileTypeToASCII();\n }\n else if ( text.find(\"BINARY\") < text.length() ||\n text.find(\"binary\") < text.length() )\n {\n this->SetFileTypeToBinary();\n }\n else\n {\n itkExceptionMacro(<< \"Unrecognized type\");\n }\n file.getline(line,255);\n text = line;\n if ( text.find(\"STRUCTURED_POINTS\") >= text.length() &&\n text.find(\"structured_points\") >= text.length() )\n {\n itkExceptionMacro(<< \"Not structured points, can't read\");\n }\n\n \/\/extract dimensions, spacing, origin\n unsigned int dims[3];\n float spacing[3];\n float origin[3];\n file.getline(line,255);\n text = line;\n unsigned int i;\n\n if ( text.find(\"DIMENSIONS\") < text.length() || \n text.find(\"dimensions\") < text.length() )\n {\n sscanf(line, \"%*s %d %d %d\", dims, dims+1, dims+2);\n if ( dims[2] <= 1 )\n {\n this->SetNumberOfDimensions(2);\n }\n else\n {\n this->SetNumberOfDimensions(3);\n }\n for ( i=0; i < m_NumberOfDimensions; i++ )\n {\n m_Dimensions[i] = dims[i];\n }\n }\n else\n {\n itkExceptionMacro(<<\"No dimensions defined\");\n }\n\n file.getline(line,255);\n text = line;\n if ( text.find(\"SPACING\") < text.length() || \n text.find(\"spacing\") < text.length() )\n {\n sscanf(line, \"%*s %f %f %f\", spacing, spacing+1, spacing+2);\n for ( i=0; i < m_NumberOfDimensions; i++ )\n {\n m_Spacing[i] = spacing[i];\n }\n }\n else\n {\n itkExceptionMacro(<<\"No spacing defined\");\n }\n\n file.getline(line,255);\n text = line;\n if ( text.find(\"ORIGIN\") < text.length() || \n text.find(\"origin\") < text.length() )\n {\n sscanf(line, \"%*s %f %f %f\", origin, origin+1, origin+2);\n for ( i=0; i < m_NumberOfDimensions; i++ )\n {\n m_Origin[i] = origin[i];\n }\n }\n else\n {\n itkExceptionMacro(<<\"No origin defined\");\n }\n \n \/\/Now grab the data; need to determine the pixel type\n file.getline(line,255);\n text = line;\n while ( text.find(\"SCALARS\") >= text.length() ||\n text.find(\"scalars\") >= text.length() )\n {\n file.getline(line,255);\n text = line;\n }\n char pixelType[256];\n sscanf(line, \"%*s %*s %s\", pixelType);\n text = pixelType;\n if ( text.find(\"float\") < text.length() )\n {\n SetPixelType(FLOAT);\n SetComponentType(FLOAT);\n }\n else if ( text.find(\"double\") < text.length() )\n {\n SetPixelType(DOUBLE);\n SetComponentType(DOUBLE);\n }\n else if ( text.find(\"unsigned_char\") < text.length() )\n {\n SetPixelType(UCHAR);\n SetComponentType(UCHAR);\n }\n else if ( text.find(\"char\") < text.length() )\n {\n SetPixelType(CHAR);\n SetComponentType(CHAR);\n }\n else if ( text.find(\"unsigned_short\") < text.length() )\n {\n SetPixelType(USHORT);\n SetComponentType(USHORT);\n }\n else if ( text.find(\"short\") < text.length() )\n {\n SetPixelType(SHORT);\n SetComponentType(SHORT);\n }\n else if ( text.find(\"unsigned_int\") < text.length() )\n {\n SetPixelType(UINT);\n SetComponentType(UINT);\n }\n else if ( text.find(\"int\") < text.length() )\n {\n SetPixelType(INT);\n SetComponentType(INT);\n }\n else if ( text.find(\"unsigned_long\") < text.length() )\n {\n SetPixelType(ULONG);\n SetComponentType(ULONG);\n }\n else if ( text.find(\"long\") < text.length() )\n {\n SetPixelType(LONG);\n SetComponentType(LONG);\n }\n else\n {\n itkExceptionMacro(<<\"Unrecognized type\");\n }\n\n \/\/ grab the trailing lookup table line\n file.getline(line,255);\n \/\/We are positioned at the data. The data is read depending on whether \n \/\/it is ASCII or binary.\n if ( m_FileType == ASCII )\n {\n this->ReadBufferAsASCII(file, buffer, this->GetComponentType(),\n this->GetImageSizeInComponents());\n }\n else\n {\n file.read(static_cast<char*>(buffer), this->GetImageSizeInBytes());\n }\n}\n\nvoid VTKImageIO::ReadImageInformation()\n{\n}\n\nbool VTKImageIO::CanWriteFile(const char*)\n{\n if ( m_FileName != \"\" &&\n m_FileName.find(\".vtk\") < m_FileName.length() )\n {\n return true;\n }\n return false;\n}\n\nvoid VTKImageIO::Write(void* buffer)\n{\n std::ofstream file;\n if ( ! this->OpenVTKFileForWriting(file,m_FileName.c_str()) )\n {\n return;\n }\n\n \/\/ Check the image region for proper dimensions, etc.\n unsigned int numDims = this->GetNumberOfDimensions();\n if ( numDims < 2 || numDims > 3 )\n {\n itkExceptionMacro(<<\"VTK Writer can only write 2 or 3-dimensional images\");\n return;\n }\n ImageIORegion ioRegion = this->GetIORegion();\n\n \/\/ Write the VTK header information\n file << \"# vtk DataFile Version 3.0\\n\"; \n file << \"VTK File Generated by Insight Segmentation and Registration Toolkit (ITK)\\n\";\n\n if ( this->GetFileType() == ASCII ) { file << \"ASCII\\n\"; }\n else { file << \"BINARY\\n\"; }\n\n \/\/ Write characteristics of the data\n file << \"DATASET STRUCTURED_POINTS\\n\";\n if ( numDims == 2 )\n {\n file << \"DIMENSIONS \" << this->GetDimensions(0) << \" \"\n << this->GetDimensions(1) << \" 1\\n\";\n file << \"SPACING \" << m_Spacing[0] << \" \" << m_Spacing[1] << \" 1.0\\n\";\n file << \"ORIGIN \" << m_Origin[0] << \" \" << m_Origin[1] << \" 0.0\\n\";\n }\n else \/\/numDims == 3\n {\n file << \"DIMENSIONS \" << this->GetDimensions(0) << \" \"\n << this->GetDimensions(1) << \" \" << this->GetDimensions(2) << \"\\n\";\n file << \"SPACING \" << m_Spacing[0] << \" \" \n << m_Spacing[1] << \" \" << m_Spacing[2] << \"\\n\";\n file << \"ORIGIN \" << m_Origin[0] << \" \"\n << m_Origin[1] << \" \" << m_Origin[2] << \"\\n\";\n }\n\n file << \"POINT_DATA \" << this->GetImageSizeInPixels() << \"\\n\";\n file << \"SCALARS scalars \" \n << this->ReturnTypeAsString(this->GetComponentType()) << \" \"\n << this->GetNumberOfComponents() << \"\\n\";\n file << \"LOOKUP_TABLE default\\n\";\n\n \/\/ Write the actual pixel data\n if ( m_FileType == ASCII )\n {\n this->WriteBufferAsASCII(file, buffer, this->GetComponentType(),\n this->GetImageSizeInComponents());\n }\n else \/\/binary\n {\n file.write(static_cast<char*>(buffer), this->GetImageSizeInBytes());\n }\n}\n\nvoid VTKImageIO::PrintSelf(std::ostream& os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n}\n\n\n} \/\/ end namespace itk\n<|endoftext|>"} {"text":"<commit_before>#include \"TextLabel.hpp\"\n\n#include \"..\/App.hpp\"\n\n\nusing namespace morda;\n\n\n\nTextLabel::TextLabel(){\n\tthis->font = App::Inst().ResMan().Load<morda::ResFont>(\"fnt_main\");\n}\n\n\n\nvoid TextLabel::SetText(const std::string& text){\n\tthis->text = text;\n\t\n\ttride::Rect2f bb = this->font->Fnt().StringBoundingBox(this->text);\n\t\n\tthis->pivot = -bb.p;\n\tthis->Resize(bb.d);\n}\n\n\n\n\/\/override\nvoid TextLabel::Render(const tride::Matr4f& matrix)const{\n\t{\n\t\ttride::Matr4f matr(matrix);\n\t\tmatr.Scale(this->Rect().d);\n\t\tSimpleSingleColoringShader& s = App::Inst().shaders.simpleSingleColoring;\n\t\ts.Bind();\n\t\ts.SetColor(tride::Vec3f(0.5, 0.5, 0.5));\n\t\ts.SetMatrix(matr);\n\t\ts.DrawQuad01();\n\t}\n\t\n\t\/\/render text\n\tmorda::SimpleTexturingShader &s = morda::App::Inst().shaders.simpleTexturing;\n\ts.Bind();\n\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\tglEnable(GL_BLEND);\n\ttride::Matr4f matr(matrix);\n\tmatr.Translate(this->pivot);\n\tthis->font->Fnt().RenderString(s, matr, this->text);\n}\n<commit_msg>commenting debug code<commit_after>#include \"TextLabel.hpp\"\n\n#include \"..\/App.hpp\"\n\n\nusing namespace morda;\n\n\n\nTextLabel::TextLabel(){\n\tthis->font = App::Inst().ResMan().Load<morda::ResFont>(\"fnt_main\");\n}\n\n\n\nvoid TextLabel::SetText(const std::string& text){\n\tthis->text = text;\n\t\n\ttride::Rect2f bb = this->font->Fnt().StringBoundingBox(this->text);\n\t\n\tthis->pivot = -bb.p;\n\tthis->Resize(bb.d);\n}\n\n\n\n\/\/override\nvoid TextLabel::Render(const tride::Matr4f& matrix)const{\n\/\/\t{\n\/\/\t\ttride::Matr4f matr(matrix);\n\/\/\t\tmatr.Scale(this->Rect().d);\n\/\/\t\tSimpleSingleColoringShader& s = App::Inst().shaders.simpleSingleColoring;\n\/\/\t\ts.Bind();\n\/\/\t\ts.SetColor(tride::Vec3f(0.5, 0.5, 0.5));\n\/\/\t\ts.SetMatrix(matr);\n\/\/\t\ts.DrawQuad01();\n\/\/\t}\n\t\n\t\/\/render text\n\tmorda::SimpleTexturingShader &s = morda::App::Inst().shaders.simpleTexturing;\n\ts.Bind();\n\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\tglEnable(GL_BLEND);\n\ttride::Matr4f matr(matrix);\n\tmatr.Translate(this->pivot);\n\tthis->font->Fnt().RenderString(s, matr, this->text);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: controlelement.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: fs $ $Date: 2001-01-03 16:25:34 $\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 EXPRESS 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 _XMLOFF_FORMS_CONTROLELEMENT_HXX_\n#define _XMLOFF_FORMS_CONTROLELEMENT_HXX_\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n\/\/.........................................................................\nnamespace xmloff\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= OControlElement\n \/\/=====================================================================\n \/** helper for translating between control types and XML tags\n *\/\n class OControlElement\n {\n public:\n enum ElementType\n {\n TEXT = 0,\n TEXT_AREA,\n PASSWORD,\n FILE,\n FORMATTED_TEXT,\n FIXED_TEXT,\n COMBOBOX,\n LISTBOX,\n BUTTON,\n IMAGE,\n CHECKBOX,\n RADIO,\n FRAME,\n IMAGE_FRAME,\n HIDDEN,\n GRID,\n GENERIC_CONTROL,\n\n UNKNOWN \/\/ must be the last element\n };\n\n protected:\n \/** ctor.\n <p>This default constructor is protected, 'cause this class is not intended to be instantiated\n directly. Instead, the derived classes should be used.<\/p>\n *\/\n OControlElement() { }\n\n public:\n \/** retrieves the tag name to be used to describe a control of the given type\n\n <p>The retuned string is the pure element name, without any namespace.<\/p>\n\n @param _eType\n the element type\n *\/\n static const sal_Char* getElementName(ElementType _eType);\n };\n\n\/\/.........................................................................\n} \/\/ namespace xmloff\n\/\/.........................................................................\n\n#endif _XMLOFF_FORMS_CONTROLELEMENT_HXX_\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.1 2000\/12\/06 17:30:27 fs\n * initial checkin - implementations for formlayer import\/export - still under construction\n *\n *\n * Revision 1.0 06.12.00 14:00:25 fs\n ************************************************************************\/\n\n<commit_msg>INTEGRATION: CWS mh11rc (1.2.152); FILE MERGED 2003\/06\/06 11:08:47 mh 1.2.152.1: join: from cws_srx644_ooo11beta2<commit_after>\/*************************************************************************\n *\n * $RCSfile: controlelement.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-06-12 09:49:08 $\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 EXPRESS 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 _XMLOFF_FORMS_CONTROLELEMENT_HXX_\n#define _XMLOFF_FORMS_CONTROLELEMENT_HXX_\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n\/\/.........................................................................\nnamespace xmloff\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= OControlElement\n \/\/=====================================================================\n \/** helper for translating between control types and XML tags\n *\/\n class OControlElement\n {\n public:\n enum ElementType\n {\n TEXT = 0,\n TEXT_AREA,\n PASSWORD,\n FILE,\n FORMATTED_TEXT,\n FIXED_TEXT,\n COMBOBOX,\n LISTBOX,\n BUTTON,\n IMAGE,\n CHECKBOX,\n RADIO,\n FRAME,\n IMAGE_FRAME,\n HIDDEN,\n GRID,\n GENERIC_CONTROL,\n\n UNKNOWN \/\/ must be the last element\n };\n\n protected:\n \/** ctor.\n <p>This default constructor is protected, 'cause this class is not intended to be instantiated\n directly. Instead, the derived classes should be used.<\/p>\n *\/\n OControlElement() { }\n\n public:\n \/** retrieves the tag name to be used to describe a control of the given type\n\n <p>The retuned string is the pure element name, without any namespace.<\/p>\n\n @param _eType\n the element type\n *\/\n static const sal_Char* getElementName(ElementType _eType);\n };\n\n\/\/.........................................................................\n} \/\/ namespace xmloff\n\/\/.........................................................................\n\n#endif \/\/ _XMLOFF_FORMS_CONTROLELEMENT_HXX_\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.2.152.1 2003\/06\/06 11:08:47 mh\n * join: from cws_srx644_ooo11beta2\n *\n * Revision 1.2.130.1 2003\/05\/21 13:37:06 waratah\n * 1858: Simple patch to comment out trailing text after #endif, waring removal\n *\n * Revision 1.2 2001\/01\/03 16:25:34 fs\n * file format change (extra wrapper element for controls, similar to columns)\n *\n * Revision 1.1 2000\/12\/06 17:30:27 fs\n * initial checkin - implementations for formlayer import\/export - still under construction\n *\n *\n * Revision 1.0 06.12.00 14:00:25 fs\n ************************************************************************\/\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Created by TekuConcept on 8\/3\/2016.\n *\/\n\n#include \"C_Thrusters.h\"\n\t\n#define MOD_COUNT 6u \/\/ thruster modifiers\n#define THRUST_COUNT 6u\nfloat hw_modifiers_[MOD_COUNT];\nfloat hw_trim_[THRUST_COUNT];\nuint16_t hw_thrust_mem_[THRUST_COUNT];\n\/\/Servo hw_servos_[THRUST_COUNT];\n\nvoid update_pair(uint8_t,uint8_t,uint8_t,uint8_t);\n\nvoid HW_configure(\n\tint aPairFirst, int aPairSecond,\n\tint bPairFirst, int bPairSecond,\n\tint cPairFirst, int cPairSecond) {\n\t\/\/hw_servos_[HW_A_FIRST ].attach(aPairFirst );\n\t\/\/hw_servos_[HW_A_SECOND].attach(aPairSecond);\n\t\/\/hw_servos_[HW_B_FIRST ].attach(bPairFirst );\n\t\/\/hw_servos_[HW_B_SECOND].attach(bPairSecond);\n\t\/\/hw_servos_[HW_C_FIRST ].attach(cPairFirst );\n\t\/\/hw_servos_[HW_C_SECOND].attach(cPairSecond);\n\tHW_hard_reset();\n}\n\n\/* - - - - - - - - - - - - - - - - - - - - - - - - - *\\\n * Thruster Modifier Functions *\n\\* - - - - - - - - - - - - - - - - - - - - - - - - - *\/\n\nvoid HW_set_modifier(uint8_t index, float value) {\n\tif(index >= MOD_COUNT)\n\t\treturn;\n\n\tif(value > 1)\n\t\tvalue = 1;\n\telse if(value < -1)\n\t\tvalue = -1;\n\thw_modifiers_[index] = value;\n\n\t\/\/ update thrust output\n\tswitch(index) {\n\tcase HW_MOD_LIN1:\n\tcase HW_MOD_ANG1:\n\t\tupdate_pair(HW_A_FIRST, HW_A_SECOND, HW_MOD_LIN1, HW_MOD_ANG1);\n\t\tbreak;\n\tcase HW_MOD_LIN2:\n\tcase HW_MOD_ANG2:\n\t\tupdate_pair(HW_B_FIRST, HW_B_SECOND, HW_MOD_LIN2, HW_MOD_ANG2);\n\t\tbreak;\n\tcase HW_MOD_LIN3:\n\tcase HW_MOD_ANG3:\n\t\tupdate_pair(HW_C_FIRST, HW_C_SECOND, HW_MOD_LIN3, HW_MOD_ANG3);\n\t\tbreak;\n\t}\n}\n\nfloat HW_get_modifier(uint8_t index) {\n\tif(index >= MOD_COUNT)\n\t\treturn -2;\n\treturn hw_modifiers_[index];\n}\n\n\/**\n * Warning: This does not guarantee the thrusters\n * will turn off because of offset and\n * trim values.\n *\/\nvoid HW_reset_modifiers() {\n\tfor(int i = 0; i < MOD_COUNT; i++) {\n\t\thw_modifiers_[i] = 0;\n\t}\n\tupdate_pair(HW_A_FIRST, HW_A_SECOND, HW_MOD_LIN1, HW_MOD_ANG1);\n\tupdate_pair(HW_B_FIRST, HW_B_SECOND, HW_MOD_LIN2, HW_MOD_ANG2);\n\tupdate_pair(HW_C_FIRST, HW_C_SECOND, HW_MOD_LIN3, HW_MOD_ANG3);\n}\n\n\/* - - - - - - - - - - - - - - - - - - - - - - - - - *\\\n * Core Thruster Functions *\n\\* - - - - - - - - - - - - - - - - - - - - - - - - - *\/\n\nvoid HW_soft_reset() {\n\tfor(int i = 0; i < MOD_COUNT; i++) {\n\t\thw_modifiers_[i] = 0;\n\t}\n\tfor(int i = 0; i < THRUST_COUNT; i++) {\n\t\t\/\/hw_servos_[i].writeMicroseconds(HW_IDLE);\n\t\thw_thrust_mem_[i] = HW_IDLE;\n\t}\n}\n\nvoid HW_hard_reset() {\n\tHW_soft_reset();\n\tfor(int i = 0; i < THRUST_COUNT; i++) {\n\t\thw_trim_[i] = 1;\n\t}\n}\n\nvoid set_safe_ratio(float* a, float* b) {\n\tif(*a > 1)\t{\n\t\t*b \/= *a;\n\t\t*a = 1;\n\t}\n\telse if(*a < -1) {\n\t\t*b \/= -*a;\n\t\t*a = -1;\n\t}\n\telse if(*b > 1) {\n\t\t*a \/= *b;\n\t\t*b = 1;\n\t}\n\telse if(*b < -1) {\n\t\t*a \/= -*b;\n\t\t*b = -1;\n\t}\n}\n\nvoid update_pair(uint8_t hw_left, uint8_t hw_right,\n\tuint8_t linear_mod, uint8_t angular_mod) {\n\tfloat left = 0, right = 0, temp = 0;\n\n\t\/\/ blend move and yaw\n\tleft = hw_modifiers_[linear_mod];\n\tright = left;\n\ttemp = hw_modifiers_[angular_mod];\n\tleft += temp;\n\tright -= temp;\n\n\t\/\/ set safe ranges as a ratio of the current values\n\tset_safe_ratio(&left, &right);\n\n\tHW_set_thruster(hw_left,\n\t\t(uint16_t)(HW_IDLE + left *hw_trim_[hw_left ]*HW_DIFF));\n\tHW_set_thruster(hw_right,\n\t\t(uint16_t)(HW_IDLE + right*hw_trim_[hw_right]*HW_DIFF));\n}\n\nvoid HW_set_thruster(uint8_t index, uint16_t value) {\n\tif(index >= THRUST_COUNT)\n\t\treturn;\n\t\/\/hw_servos_[index].writeMicroseconds(value);\n\thw_thrust_mem_[index] = value;\n}\n\nuint16_t HW_get_thruster(uint8_t index) {\n\tif(index >= THRUST_COUNT)\n\t\treturn 0;\n\treturn hw_thrust_mem_[index];\n}\n\nvoid HW_set_trim(uint8_t index, float value) {\n\tif(index >= THRUST_COUNT)\n\t\treturn;\n\tif(value > 1)\n\t\tvalue = 1;\n\telse if(value < -1)\n\t\tvalue = -1;\n\n\thw_trim_[index] = value;\n\tswitch(index) {\n\tcase HW_A_FIRST:\n\tcase HW_A_SECOND:\n\t\tupdate_pair(HW_A_FIRST, HW_A_SECOND, HW_MOD_LIN1, HW_MOD_ANG1);\n\t\tbreak;\n\tcase HW_B_FIRST:\n\tcase HW_B_SECOND:\n\t\tupdate_pair(HW_B_FIRST, HW_B_SECOND, HW_MOD_LIN2, HW_MOD_ANG2);\n\t\tbreak;\n\tcase HW_C_FIRST:\n\tcase HW_C_SECOND:\n\t\tupdate_pair(HW_C_FIRST, HW_C_SECOND, HW_MOD_LIN3, HW_MOD_ANG3);\n\t\tbreak;\n\t}\n}\n\nfloat HW_get_trim(uint8_t index) {\n\tif(index >= THRUST_COUNT)\n\t\treturn -2;\n\treturn hw_trim_[index];\n}\n\nvoid HW_reset_trim() {\n\tfor(int i = 0; i < THRUST_COUNT; i++) {\n\t\thw_trim_[i] = 1;\n\t}\n\tupdate_pair(HW_A_FIRST, HW_A_SECOND, HW_MOD_LIN1, HW_MOD_ANG1);\n\tupdate_pair(HW_B_FIRST, HW_B_SECOND, HW_MOD_LIN2, HW_MOD_ANG2);\n\tupdate_pair(HW_C_FIRST, HW_C_SECOND, HW_MOD_LIN3, HW_MOD_ANG3);\n}<commit_msg>Enable Servo Control<commit_after>\/**\n * Created by TekuConcept on 8\/3\/2016.\n *\/\n\n#include \"C_Thrusters.h\"\n\t\n#define MOD_COUNT 6u \/\/ thruster modifiers\n#define THRUST_COUNT 6u\nfloat hw_modifiers_[MOD_COUNT];\nfloat hw_trim_[THRUST_COUNT];\nuint16_t hw_thrust_mem_[THRUST_COUNT];\nServo hw_servos_[THRUST_COUNT];\n\nvoid update_pair(uint8_t,uint8_t,uint8_t,uint8_t);\n\nvoid HW_configure(\n\tint aPairFirst, int aPairSecond,\n\tint bPairFirst, int bPairSecond,\n\tint cPairFirst, int cPairSecond) {\n\thw_servos_[HW_A_FIRST ].attach(aPairFirst );\n\thw_servos_[HW_A_SECOND].attach(aPairSecond);\n\thw_servos_[HW_B_FIRST ].attach(bPairFirst );\n\thw_servos_[HW_B_SECOND].attach(bPairSecond);\n\thw_servos_[HW_C_FIRST ].attach(cPairFirst );\n\thw_servos_[HW_C_SECOND].attach(cPairSecond);\n\tHW_hard_reset();\n}\n\n\/* - - - - - - - - - - - - - - - - - - - - - - - - - *\\\n * Thruster Modifier Functions *\n\\* - - - - - - - - - - - - - - - - - - - - - - - - - *\/\n\nvoid HW_set_modifier(uint8_t index, float value) {\n\tif(index >= MOD_COUNT)\n\t\treturn;\n\n\tif(value > 1)\n\t\tvalue = 1;\n\telse if(value < -1)\n\t\tvalue = -1;\n\thw_modifiers_[index] = value;\n\n\t\/\/ update thrust output\n\tswitch(index) {\n\tcase HW_MOD_LIN1:\n\tcase HW_MOD_ANG1:\n\t\tupdate_pair(HW_A_FIRST, HW_A_SECOND, HW_MOD_LIN1, HW_MOD_ANG1);\n\t\tbreak;\n\tcase HW_MOD_LIN2:\n\tcase HW_MOD_ANG2:\n\t\tupdate_pair(HW_B_FIRST, HW_B_SECOND, HW_MOD_LIN2, HW_MOD_ANG2);\n\t\tbreak;\n\tcase HW_MOD_LIN3:\n\tcase HW_MOD_ANG3:\n\t\tupdate_pair(HW_C_FIRST, HW_C_SECOND, HW_MOD_LIN3, HW_MOD_ANG3);\n\t\tbreak;\n\t}\n}\n\nfloat HW_get_modifier(uint8_t index) {\n\tif(index >= MOD_COUNT)\n\t\treturn -2;\n\treturn hw_modifiers_[index];\n}\n\n\/**\n * Warning: This does not guarantee the thrusters\n * will turn off because of offset and\n * trim values.\n *\/\nvoid HW_reset_modifiers() {\n\tfor(int i = 0; i < MOD_COUNT; i++) {\n\t\thw_modifiers_[i] = 0;\n\t}\n\tupdate_pair(HW_A_FIRST, HW_A_SECOND, HW_MOD_LIN1, HW_MOD_ANG1);\n\tupdate_pair(HW_B_FIRST, HW_B_SECOND, HW_MOD_LIN2, HW_MOD_ANG2);\n\tupdate_pair(HW_C_FIRST, HW_C_SECOND, HW_MOD_LIN3, HW_MOD_ANG3);\n}\n\n\/* - - - - - - - - - - - - - - - - - - - - - - - - - *\\\n * Core Thruster Functions *\n\\* - - - - - - - - - - - - - - - - - - - - - - - - - *\/\n\nvoid HW_soft_reset() {\n\tfor(int i = 0; i < MOD_COUNT; i++) {\n\t\thw_modifiers_[i] = 0;\n\t}\n\tfor(int i = 0; i < THRUST_COUNT; i++) {\n\t\thw_servos_[i].writeMicroseconds(HW_IDLE);\n\t\thw_thrust_mem_[i] = HW_IDLE;\n\t}\n}\n\nvoid HW_hard_reset() {\n\tHW_soft_reset();\n\tfor(int i = 0; i < THRUST_COUNT; i++) {\n\t\thw_trim_[i] = 1;\n\t}\n}\n\nvoid set_safe_ratio(float* a, float* b) {\n\tif(*a > 1)\t{\n\t\t*b \/= *a;\n\t\t*a = 1;\n\t}\n\telse if(*a < -1) {\n\t\t*b \/= -*a;\n\t\t*a = -1;\n\t}\n\telse if(*b > 1) {\n\t\t*a \/= *b;\n\t\t*b = 1;\n\t}\n\telse if(*b < -1) {\n\t\t*a \/= -*b;\n\t\t*b = -1;\n\t}\n}\n\nvoid update_pair(uint8_t hw_left, uint8_t hw_right,\n\tuint8_t linear_mod, uint8_t angular_mod) {\n\tfloat left = 0, right = 0, temp = 0;\n\n\t\/\/ blend move and yaw\n\tleft = hw_modifiers_[linear_mod];\n\tright = left;\n\ttemp = hw_modifiers_[angular_mod];\n\tleft += temp;\n\tright -= temp;\n\n\t\/\/ set safe ranges as a ratio of the current values\n\tset_safe_ratio(&left, &right);\n\n\tHW_set_thruster(hw_left,\n\t\t(uint16_t)(HW_IDLE + left *hw_trim_[hw_left ]*HW_DIFF));\n\tHW_set_thruster(hw_right,\n\t\t(uint16_t)(HW_IDLE + right*hw_trim_[hw_right]*HW_DIFF));\n}\n\nvoid HW_set_thruster(uint8_t index, uint16_t value) {\n\tif(index >= THRUST_COUNT)\n\t\treturn;\n\thw_servos_[index].writeMicroseconds(value);\n\thw_thrust_mem_[index] = value;\n}\n\nuint16_t HW_get_thruster(uint8_t index) {\n\tif(index >= THRUST_COUNT)\n\t\treturn 0;\n\treturn hw_thrust_mem_[index];\n}\n\nvoid HW_set_trim(uint8_t index, float value) {\n\tif(index >= THRUST_COUNT)\n\t\treturn;\n\tif(value > 1)\n\t\tvalue = 1;\n\telse if(value < -1)\n\t\tvalue = -1;\n\n\thw_trim_[index] = value;\n\tswitch(index) {\n\tcase HW_A_FIRST:\n\tcase HW_A_SECOND:\n\t\tupdate_pair(HW_A_FIRST, HW_A_SECOND, HW_MOD_LIN1, HW_MOD_ANG1);\n\t\tbreak;\n\tcase HW_B_FIRST:\n\tcase HW_B_SECOND:\n\t\tupdate_pair(HW_B_FIRST, HW_B_SECOND, HW_MOD_LIN2, HW_MOD_ANG2);\n\t\tbreak;\n\tcase HW_C_FIRST:\n\tcase HW_C_SECOND:\n\t\tupdate_pair(HW_C_FIRST, HW_C_SECOND, HW_MOD_LIN3, HW_MOD_ANG3);\n\t\tbreak;\n\t}\n}\n\nfloat HW_get_trim(uint8_t index) {\n\tif(index >= THRUST_COUNT)\n\t\treturn -2;\n\treturn hw_trim_[index];\n}\n\nvoid HW_reset_trim() {\n\tfor(int i = 0; i < THRUST_COUNT; i++) {\n\t\thw_trim_[i] = 1;\n\t}\n\tupdate_pair(HW_A_FIRST, HW_A_SECOND, HW_MOD_LIN1, HW_MOD_ANG1);\n\tupdate_pair(HW_B_FIRST, HW_B_SECOND, HW_MOD_LIN2, HW_MOD_ANG2);\n\tupdate_pair(HW_C_FIRST, HW_C_SECOND, HW_MOD_LIN3, HW_MOD_ANG3);\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkIdList.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkIdList.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkStandardNewMacro(vtkIdList);\n\nvtkIdList::vtkIdList()\n{\n this->NumberOfIds = 0;\n this->Size = 0;\n this->Ids = NULL;\n}\n\nvtkIdList::~vtkIdList()\n{\n delete [] this->Ids;\n}\n\nvoid vtkIdList::Initialize()\n{\n delete [] this->Ids;\n this->Ids = NULL;\n this->NumberOfIds = 0;\n this->Size = 0;\n}\n\nint vtkIdList::Allocate(const vtkIdType sz, const int vtkNotUsed(strategy))\n{\n if ( sz > this->Size)\n {\n this->Initialize();\n this->Size = ( sz > 0 ? sz : 1);\n if ( (this->Ids = new vtkIdType[this->Size]) == NULL )\n {\n return 0;\n }\n }\n this->NumberOfIds = 0;\n return 1;\n}\n\nvoid vtkIdList::SetNumberOfIds(const vtkIdType number)\n{\n this->Allocate(number,0);\n this->NumberOfIds = number;\n}\n\nvtkIdType vtkIdList::InsertUniqueId(const vtkIdType vtkid)\n{\n for (vtkIdType i=0; i < this->NumberOfIds; i++)\n {\n if ( vtkid == this->Ids[i] )\n {\n return i;\n }\n }\n\n return this->InsertNextId(vtkid);\n}\n\nvtkIdType *vtkIdList::WritePointer(const vtkIdType i, const vtkIdType number)\n{\n vtkIdType newSize=i+number;\n if ( newSize > this->Size )\n {\n this->Resize(newSize);\n }\n if ( newSize > this->NumberOfIds )\n {\n this->NumberOfIds = newSize;\n }\n return this->Ids + i;\n}\n\nvoid vtkIdList::DeleteId(vtkIdType vtkid)\n{\n vtkIdType i=0;\n\n \/\/ while loop is necessary to delete all occurrences of vtkid\n while ( i < this->NumberOfIds )\n {\n for ( ; i < this->NumberOfIds; i++)\n {\n if ( this->Ids[i] == vtkid )\n {\n break;\n }\n }\n\n \/\/ if found; replace current id with last\n if ( i < this->NumberOfIds )\n {\n this->SetId(i,this->Ids[this->NumberOfIds-1]);\n this->NumberOfIds--;\n }\n }\n}\n\nvoid vtkIdList::DeepCopy(vtkIdList *ids)\n{\n this->SetNumberOfIds(ids->NumberOfIds);\n std::copy(ids->Ids, ids->Ids + ids->NumberOfIds, this->Ids);\n this->Squeeze();\n}\n\nvtkIdType *vtkIdList::Resize(const vtkIdType sz)\n{\n vtkIdType *newIds;\n vtkIdType newSize;\n\n if ( sz > this->Size )\n {\n newSize = this->Size + sz;\n }\n else if (sz == this->Size)\n {\n return this->Ids;\n }\n else\n {\n newSize = sz;\n }\n\n if (newSize <= 0)\n {\n this->Initialize();\n return 0;\n }\n\n if ( (newIds = new vtkIdType[newSize]) == NULL )\n {\n vtkErrorMacro(<< \"Cannot allocate memory\\n\");\n return 0;\n }\n\n if (this->Ids)\n {\n memcpy(newIds, this->Ids,\n static_cast<size_t>(sz < this->Size ? sz : this->Size) * sizeof(vtkIdType));\n delete [] this->Ids;\n }\n\n this->Size = newSize;\n this->Ids = newIds;\n return this->Ids;\n}\n\n#define VTK_TMP_ARRAY_SIZE 500\n\/\/ Intersect this list with another vtkIdList. Updates current list according\n\/\/ to result of intersection operation.\nvoid vtkIdList::IntersectWith(vtkIdList* otherIds)\n{\n \/\/ Fast method due to Dr. Andreas Mueller of ISE Integrated Systems\n \/\/ Engineering (CH).\n vtkIdType thisNumIds = this->GetNumberOfIds();\n\n if (thisNumIds <= VTK_TMP_ARRAY_SIZE)\n {\/\/Use fast method if we can fit in temporary storage\n vtkIdType thisIds[VTK_TMP_ARRAY_SIZE];\n vtkIdType i, vtkid;\n\n for (i=0; i < thisNumIds; i++)\n {\n thisIds[i] = this->GetId(i);\n }\n for (this->Reset(), i=0; i < thisNumIds; i++)\n {\n vtkid = thisIds[i];\n if ( otherIds->IsId(vtkid) != (-1) )\n {\n this->InsertNextId(vtkid);\n }\n }\n }\n else\n {\/\/use slower method for extreme cases\n vtkIdType *thisIds = new vtkIdType [thisNumIds];\n vtkIdType i, vtkid;\n\n for (i=0; i < thisNumIds; i++)\n {\n *(thisIds + i) = this->GetId(i);\n }\n for (this->Reset(), i=0; i < thisNumIds; i++)\n {\n vtkid = *(thisIds + i);\n if ( otherIds->IsId(vtkid) != (-1) )\n {\n this->InsertNextId(vtkid);\n }\n }\n delete [] thisIds;\n }\n}\n#undef VTK_TMP_ARRAY_SIZE\n\nvoid vtkIdList::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"Number of Ids: \" << this->NumberOfIds << \"\\n\";\n}\n<commit_msg>BUG: Fix NULL dereference in std::copy argument<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkIdList.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkIdList.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkStandardNewMacro(vtkIdList);\n\nvtkIdList::vtkIdList()\n{\n this->NumberOfIds = 0;\n this->Size = 0;\n this->Ids = NULL;\n}\n\nvtkIdList::~vtkIdList()\n{\n delete [] this->Ids;\n}\n\nvoid vtkIdList::Initialize()\n{\n delete [] this->Ids;\n this->Ids = NULL;\n this->NumberOfIds = 0;\n this->Size = 0;\n}\n\nint vtkIdList::Allocate(const vtkIdType sz, const int vtkNotUsed(strategy))\n{\n if ( sz > this->Size)\n {\n this->Initialize();\n this->Size = ( sz > 0 ? sz : 1);\n if ( (this->Ids = new vtkIdType[this->Size]) == NULL )\n {\n return 0;\n }\n }\n this->NumberOfIds = 0;\n return 1;\n}\n\nvoid vtkIdList::SetNumberOfIds(const vtkIdType number)\n{\n this->Allocate(number,0);\n this->NumberOfIds = number;\n}\n\nvtkIdType vtkIdList::InsertUniqueId(const vtkIdType vtkid)\n{\n for (vtkIdType i=0; i < this->NumberOfIds; i++)\n {\n if ( vtkid == this->Ids[i] )\n {\n return i;\n }\n }\n\n return this->InsertNextId(vtkid);\n}\n\nvtkIdType *vtkIdList::WritePointer(const vtkIdType i, const vtkIdType number)\n{\n vtkIdType newSize=i+number;\n if ( newSize > this->Size )\n {\n this->Resize(newSize);\n }\n if ( newSize > this->NumberOfIds )\n {\n this->NumberOfIds = newSize;\n }\n return this->Ids + i;\n}\n\nvoid vtkIdList::DeleteId(vtkIdType vtkid)\n{\n vtkIdType i=0;\n\n \/\/ while loop is necessary to delete all occurrences of vtkid\n while ( i < this->NumberOfIds )\n {\n for ( ; i < this->NumberOfIds; i++)\n {\n if ( this->Ids[i] == vtkid )\n {\n break;\n }\n }\n\n \/\/ if found; replace current id with last\n if ( i < this->NumberOfIds )\n {\n this->SetId(i,this->Ids[this->NumberOfIds-1]);\n this->NumberOfIds--;\n }\n }\n}\n\nvoid vtkIdList::DeepCopy(vtkIdList *ids)\n{\n this->SetNumberOfIds(ids->NumberOfIds);\n if (ids->NumberOfIds > 0)\n {\n std::copy(ids->Ids, ids->Ids + ids->NumberOfIds, this->Ids);\n }\n this->Squeeze();\n}\n\nvtkIdType *vtkIdList::Resize(const vtkIdType sz)\n{\n vtkIdType *newIds;\n vtkIdType newSize;\n\n if ( sz > this->Size )\n {\n newSize = this->Size + sz;\n }\n else if (sz == this->Size)\n {\n return this->Ids;\n }\n else\n {\n newSize = sz;\n }\n\n if (newSize <= 0)\n {\n this->Initialize();\n return 0;\n }\n\n if ( (newIds = new vtkIdType[newSize]) == NULL )\n {\n vtkErrorMacro(<< \"Cannot allocate memory\\n\");\n return 0;\n }\n\n if (this->Ids)\n {\n memcpy(newIds, this->Ids,\n static_cast<size_t>(sz < this->Size ? sz : this->Size) * sizeof(vtkIdType));\n delete [] this->Ids;\n }\n\n this->Size = newSize;\n this->Ids = newIds;\n return this->Ids;\n}\n\n#define VTK_TMP_ARRAY_SIZE 500\n\/\/ Intersect this list with another vtkIdList. Updates current list according\n\/\/ to result of intersection operation.\nvoid vtkIdList::IntersectWith(vtkIdList* otherIds)\n{\n \/\/ Fast method due to Dr. Andreas Mueller of ISE Integrated Systems\n \/\/ Engineering (CH).\n vtkIdType thisNumIds = this->GetNumberOfIds();\n\n if (thisNumIds <= VTK_TMP_ARRAY_SIZE)\n {\/\/Use fast method if we can fit in temporary storage\n vtkIdType thisIds[VTK_TMP_ARRAY_SIZE];\n vtkIdType i, vtkid;\n\n for (i=0; i < thisNumIds; i++)\n {\n thisIds[i] = this->GetId(i);\n }\n for (this->Reset(), i=0; i < thisNumIds; i++)\n {\n vtkid = thisIds[i];\n if ( otherIds->IsId(vtkid) != (-1) )\n {\n this->InsertNextId(vtkid);\n }\n }\n }\n else\n {\/\/use slower method for extreme cases\n vtkIdType *thisIds = new vtkIdType [thisNumIds];\n vtkIdType i, vtkid;\n\n for (i=0; i < thisNumIds; i++)\n {\n *(thisIds + i) = this->GetId(i);\n }\n for (this->Reset(), i=0; i < thisNumIds; i++)\n {\n vtkid = *(thisIds + i);\n if ( otherIds->IsId(vtkid) != (-1) )\n {\n this->InsertNextId(vtkid);\n }\n }\n delete [] thisIds;\n }\n}\n#undef VTK_TMP_ARRAY_SIZE\n\nvoid vtkIdList::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"Number of Ids: \" << this->NumberOfIds << \"\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <seqan\/graph_types.h>\r\nusing namespace seqan;\r\n\/\/ part 2\r\nint main ()\r\n{\r\n\ttypedef unsigned int TCargo;\r\n\ttypedef Graph<Undirected<TCargo> > TGraph;\r\n\ttypedef VertexDescriptor<TGraph>::Type TVertexDescriptor;\r\n\/\/ part 3\r\n\tTGraph g;\r\n\r\n\tTVertexDescriptor vertBerlin = addVertex(g);\r\n\tTVertexDescriptor vertHamburg = addVertex(g);\r\n\tTVertexDescriptor vertHannover = addVertex(g);\r\n\tTVertexDescriptor vertMainz = addVertex(g);\r\n\tTVertexDescriptor vertMuenchen = addVertex(g);\r\n\r\n\taddEdge(g, vertBerlin, vertHamburg, 289);\r\n\taddEdge(g, vertBerlin, vertHannover, 286);\r\n\taddEdge(g, vertBerlin, vertMainz, 573);\r\n\taddEdge(g, vertBerlin, vertMuenchen, 586);\r\n\taddEdge(g, vertHannover, vertMuenchen, 572);\r\n\taddEdge(g, vertHamburg, vertMainz, 521);\r\n\/\/ part 4\r\n\tFILE* strmWrite = fopen(\"graph.dot\", \"w\");\r\n\twrite(strmWrite, g, DotDrawing());\r\n\tfclose(strmWrite);\r\n\r\n\treturn 0;\r\n}\r\n<commit_msg>Using new-style FRAGMENT markers to mark fragments.<commit_after>\/\/ The lines FRAGMENT(fragment-name) mark the begin of fragments for being\r\n\/\/ included in the documentation. You can ignore them.\r\n\/\/ FRAGMENT(includes)\r\n#include <iostream>\r\n#include <seqan\/graph_types.h>\r\nusing namespace seqan;\r\n\/\/ FRAGMENT(main-typedefs)\r\nint main ()\r\n{\r\n\ttypedef unsigned int TCargo;\r\n\ttypedef Graph<Undirected<TCargo> > TGraph;\r\n\ttypedef VertexDescriptor<TGraph>::Type TVertexDescriptor;\r\n\/\/ FRAGMENT(main-graph-construction)\r\n\tTGraph g;\r\n\r\n\tTVertexDescriptor vertBerlin = addVertex(g);\r\n\tTVertexDescriptor vertHamburg = addVertex(g);\r\n\tTVertexDescriptor vertHannover = addVertex(g);\r\n\tTVertexDescriptor vertMainz = addVertex(g);\r\n\tTVertexDescriptor vertMuenchen = addVertex(g);\r\n\r\n\taddEdge(g, vertBerlin, vertHamburg, 289);\r\n\taddEdge(g, vertBerlin, vertHannover, 286);\r\n\taddEdge(g, vertBerlin, vertMainz, 573);\r\n\taddEdge(g, vertBerlin, vertMuenchen, 586);\r\n\taddEdge(g, vertHannover, vertMuenchen, 572);\r\n\taddEdge(g, vertHamburg, vertMainz, 521);\r\n\/\/ FRAGMENT(main-graph-io)\r\n\tFILE* strmWrite = fopen(\"graph.dot\", \"w\");\r\n\twrite(strmWrite, g, DotDrawing());\r\n\tfclose(strmWrite);\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\/* enchant\n * Copyright (C) 2003 Joan Moratinos <jmo@softcatala.org>, Dom Lachowicz\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.\t 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\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * In addition, as a special exception, Dom Lachowicz\n * gives permission to link the code of this program with\n * non-LGPL Spelling Provider libraries (eg: a MSFT Office\n * spell checker backend) and distribute linked combinations including\n * the two. You must obey the GNU General Public License in all\n * respects for all of the code used other than said providers. If you modify\n * this file, you may extend this exception to your version of the\n * file, but you are not obligated to do so. If you do not wish to\n * do so, delete this exception statement from your version.\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h> \n\n#include <vector>\n\n#include \"myspell_checker.h\"\n#include \"enchant.h\"\n#include \"enchant-provider.h\"\n\n#define G_ICONV_INVALID (GIConv)-1\n\n\/***************************************************************************\/\n\n\/* in preparation for using win32 registry keys, if necessary *\/\n\nstatic char *\nmyspell_checker_get_prefix (void)\n{\n#ifdef ENCHANT_MYSPELL_DICT_DIR\n\treturn g_strdup (ENCHANT_MYSPELL_DICT_DIR);\n#else\n\treturn NULL;\n#endif\n}\n\nstatic bool\ng_iconv_is_valid(GIConv i)\n{\n\treturn (i != G_ICONV_INVALID);\n}\n\nMySpellChecker::MySpellChecker()\n{\n\tmyspell = 0;\n\tm_translate_in = 0;\n\tm_translate_out = 0;\n}\n\nMySpellChecker::~MySpellChecker()\n{\n\tdelete myspell;\n\tif (g_iconv_is_valid (m_translate_in ))\n\t\tg_iconv_close(m_translate_in);\n\tm_translate_in = G_ICONV_INVALID;\n\tif (g_iconv_is_valid(m_translate_out))\n\t\tg_iconv_close(m_translate_out);\n\tm_translate_out = G_ICONV_INVALID;\n}\n\nbool\nMySpellChecker::checkWord(const char *utf8Word, size_t len)\n{\n\tif (len > MAXWORDLEN || !g_iconv_is_valid(m_translate_in))\n\t\treturn false;\n\n\tstd::string word (utf8Word, len);\n\tif (m_personal[word])\n\t\treturn true;\n\tif (m_session[word])\n\t\treturn true;\n\n\tchar *in = (char*) utf8Word;\n\tchar word8[MAXWORDLEN + 1];\n\tchar *out = word8;\n\tsize_t len_in = len * sizeof(char);\n\tsize_t len_out = sizeof( word8 ) - 1;\n\tg_iconv(m_translate_in, &in, &len_in, &out, &len_out);\n\t*out = '\\0';\n\tif (myspell->spell(word8))\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nchar**\nMySpellChecker::suggestWord(const char* const utf8Word, size_t len, size_t *nsug)\n{\n\tif (len > MAXWORDLEN \n\t\t|| !g_iconv_is_valid(m_translate_in)\n\t\t|| !g_iconv_is_valid(m_translate_out))\n\t\treturn 0;\n\tchar *in = (char*) utf8Word;\n\tchar word8[MAXWORDLEN + 1];\n\tchar *out = word8;\n\tsize_t len_in = len;\n\tsize_t len_out = sizeof(word8) - 1;\n\tg_iconv(m_translate_in, &in, &len_in, &out, &len_out);\n\t*out = '\\0';\n\tchar **sugMS;\n\t*nsug = myspell->suggest(&sugMS, word8);\n\tif (*nsug > 0) {\n\t\tchar **sug = g_new0 (char *, *nsug + 1);\n\t\tfor (int i=0; i<*nsug; i++) {\n\t\t\tin = sugMS[i];\n\t\t\tlen_in = strlen(in);\n\t\t\tlen_out = sizeof(char) * (len_in + 1);\n\t\t\tchar *word = g_new0(char, len_out);\n\t\t\tout = reinterpret_cast<char *>(word);\n\t\t\tg_iconv(m_translate_out, &in, &len_in, &out, &len_out);\n\t\t\t*(out) = 0;\n\t\t\tsug[i] = word;\n\t\t\tfree(sugMS[i]);\n\t\t}\n\t\tfree(sugMS);\n\t\treturn sug;\n\t}\n\telse\n\t\treturn 0;\n}\n\nstatic void\ns_buildHashNames (std::vector<std::string> & names, const char * dict)\n{\n\tchar * tmp, * private_dir, * home_dir, * ispell_prefix;\n\n\tnames.clear ();\n\n\thome_dir = enchant_get_user_home_dir ();\n\n\tif (home_dir) {\n\t\tprivate_dir = g_build_filename (home_dir, \".enchant\", \n\t\t\t\t\t\t\"myspell\", NULL);\n\t\t\n\t\ttmp = g_build_filename (private_dir, dict, NULL);\n\t\tnames.push_back (tmp);\n\t\tg_free (tmp);\n\n\t\tg_free (private_dir);\n\t\tg_free (home_dir);\n\t}\n\n\tispell_prefix = myspell_checker_get_prefix ();\n\tif (ispell_prefix) {\n\t\ttmp = g_build_filename (ispell_prefix, dict, NULL);\n\t\tnames.push_back (tmp);\n\t\tg_free (tmp);\n\t\tg_free (ispell_prefix);\n\t}\n}\n\nstatic char *\nmyspell_request_dictionary (const char * tag) \n{\n\tchar * dic = NULL;\n\n\tstd::vector<std::string> names;\n\n\ts_buildHashNames (names, tag);\n\n\tfor (size_t i = 0; i < names.size () && !dic; i++) {\n\t\tif (g_file_test(names[i].c_str(), G_FILE_TEST_EXISTS))\n\t\t\tdic = g_strdup (names[i].c_str());\n\t}\n\t\n\treturn dic;\n}\n\nbool\nMySpellChecker::requestDictionary(const char *szLang)\n{\n\tconst char *dictBase = NULL;\n\tchar *dic = NULL, *aff = NULL;\n\tchar *home_dir = enchant_get_user_home_dir();\n\n\tdic = myspell_request_dictionary (szLang);\n\tif (!dic) {\n\t\tstd::string shortened_dict (szLang);\n\t\tsize_t uscore_pos;\n\t\t\n\t\t\/\/ try abbreviated form\n\t\tif ((uscore_pos = shortened_dict.rfind ('_')) != ((size_t)-1)) {\n\t\t\tshortened_dict = shortened_dict.substr(0, uscore_pos);\n\t\t\tdic = myspell_request_dictionary (shortened_dict.c_str());\n\t\t}\n\t}\n\tif (!dic)\n\t\treturn false;\n\n\taff = g_strdup(dic);\n\tint len_dic = strlen(dic);\n\tstrcpy(aff+len_dic-3, \"aff\");\n\tmyspell = new MySpell(aff, dic);\n\tg_free(dic);\n\tg_free(aff);\n\tchar *enc = myspell->get_dic_encoding();\n\n\tm_translate_in = g_iconv_open(enc, \"UTF-8\");\n\tm_translate_out = g_iconv_open(\"UTF-8\", enc);\n\n\treturn true;\n}\n\n\/*\n * Enchant\n *\/\n\nstatic char **\nmyspell_dict_suggest (EnchantDict * me, const char *const word,\n\t\t size_t len, size_t * out_n_suggs)\n{\n\tMySpellChecker * checker;\n\t\n\tchecker = (MySpellChecker *) me->user_data;\n\treturn checker->suggestWord (word, len, out_n_suggs);\n}\n\nstatic int\nmyspell_dict_check (EnchantDict * me, const char *const word, size_t len)\n{\n\tMySpellChecker * checker;\n\t\n\tchecker = (MySpellChecker *) me->user_data;\n\t\n\tif (checker->checkWord(word, len))\n\t\treturn 0;\n\t\n\treturn 1;\n}\n\nstatic void\nmyspell_dict_add_to_personal (EnchantDict * me,\n\t\t\t const char *const word, size_t len)\n{\n\tMySpellChecker * checker;\n\t\n\t\/\/ emulate adding to a personal dictionary via a session-like\n\t\/\/ interface\n\n\tchecker = (MySpellChecker *) me->user_data;\n\tchecker->addToPersonal(word, len);\n}\n\nstatic void\nmyspell_dict_add_to_session(EnchantDict * me,\n\t\t\t const char *const word, size_t len)\n{\n\tMySpellChecker * checker;\n\t\n\t\/\/ implement a session interface\n\n\tchecker = (MySpellChecker *) me->user_data;\n\tchecker->addToSession(word, len);\n}\n\nstatic void\nmyspell_dict_free_suggestions (EnchantDict * me, char **str_list)\n{\n\tg_strfreev (str_list);\n}\n\nstatic EnchantDict *\nmyspell_provider_request_dict(EnchantProvider * me, const char *const tag)\n{\n\tEnchantDict *dict;\n\tMySpellChecker * checker;\n\t\n\tchecker = new MySpellChecker();\n\t\n\tif (!checker)\n\t\treturn NULL;\n\t\n\tif (!checker->requestDictionary(tag)) {\n\t\tdelete checker;\n\t\treturn NULL;\n\t}\n\t\n\tdict = g_new0(EnchantDict, 1);\n\tdict->user_data = (void *) checker;\n\tdict->check = myspell_dict_check;\n\tdict->suggest = myspell_dict_suggest;\n\tdict->add_to_personal = myspell_dict_add_to_personal;\n\tdict->add_to_session = myspell_dict_add_to_session;\n\tdict->free_suggestions = myspell_dict_free_suggestions;\n\t\n\treturn dict;\n}\n\nstatic void\nmyspell_provider_dispose_dict (EnchantProvider * me, EnchantDict * dict)\n{\n\tMySpellChecker *checker;\n\t\n\tchecker = (MySpellChecker *) dict->user_data;\n\tdelete checker;\n\t\n\tg_free (dict);\n}\n\nstatic EnchantDictStatus\nmyspell_provider_dictionary_status (struct str_enchant_provider * me,\n\t\t\t\t const char *const tag)\n{\n\tstd::vector <std::string> names;\n\n\ts_buildHashNames (names, tag);\n\tfor (size_t i = 0; i < names.size(); i++) {\n\t\tif (g_file_test (names[i].c_str(), G_FILE_TEST_EXISTS))\n\t\t\treturn EDS_EXISTS;\n\t}\n\n\tstd::string shortened_dict (tag);\n\tsize_t uscore_pos;\n\t\n\tif ((uscore_pos = shortened_dict.rfind ('_')) != ((size_t)-1)) {\n\t\tshortened_dict = shortened_dict.substr(0, uscore_pos);\n\n\t\ts_buildHashNames (names, shortened_dict.c_str());\n\t\tfor (size_t i = 0; i < names.size(); i++) {\n\t\t\tif (g_file_test (names[i].c_str(), G_FILE_TEST_EXISTS))\n\t\t\t\treturn EDS_EXISTS;\n\t\t}\n\t}\n\n\treturn EDS_DOESNT_EXIST;\n}\n\nstatic void\nmyspell_provider_dispose (EnchantProvider * me)\n{\n\tg_free (me);\n}\n\nstatic char *\nmyspell_provider_identify (EnchantProvider * me)\n{\n\treturn \"myspell\";\n}\n\nstatic char *\nmyspell_provider_describe (EnchantProvider * me)\n{\n\treturn \"Myspell Provider\";\n}\n\nextern \"C\" {\n\nENCHANT_MODULE_EXPORT (EnchantProvider *) \ninit_enchant_provider (void)\n{\n\tEnchantProvider *provider;\n\t\n\tprovider = g_new0(EnchantProvider, 1);\n\tprovider->dispose = myspell_provider_dispose;\n\tprovider->request_dict = myspell_provider_request_dict;\n\tprovider->dispose_dict = myspell_provider_dispose_dict;\n\tprovider->dictionary_status = myspell_provider_dictionary_status;\n\tprovider->identify = myspell_provider_identify;\n\tprovider->describe = myspell_provider_describe;\n\n\treturn provider;\n}\n\n} \/\/ extern C linkage\n<commit_msg>fix myspell<commit_after>\/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\/* enchant\n * Copyright (C) 2003 Joan Moratinos <jmo@softcatala.org>, Dom Lachowicz\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.\t 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\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * In addition, as a special exception, Dom Lachowicz\n * gives permission to link the code of this program with\n * non-LGPL Spelling Provider libraries (eg: a MSFT Office\n * spell checker backend) and distribute linked combinations including\n * the two. You must obey the GNU General Public License in all\n * respects for all of the code used other than said providers. If you modify\n * this file, you may extend this exception to your version of the\n * file, but you are not obligated to do so. If you do not wish to\n * do so, delete this exception statement from your version.\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h> \n\n#include <vector>\n\n#include \"myspell_checker.h\"\n#include \"enchant.h\"\n#include \"enchant-provider.h\"\n\n#define G_ICONV_INVALID (GIConv)-1\n\n\/***************************************************************************\/\n\n\/* in preparation for using win32 registry keys, if necessary *\/\n\nstatic char *\nmyspell_checker_get_prefix (void)\n{\n#ifdef ENCHANT_MYSPELL_DICT_DIR\n\treturn g_strdup (ENCHANT_MYSPELL_DICT_DIR);\n#else\n\treturn NULL;\n#endif\n}\n\nstatic bool\ng_iconv_is_valid(GIConv i)\n{\n\treturn (i != G_ICONV_INVALID);\n}\n\nMySpellChecker::MySpellChecker()\n{\n\tmyspell = 0;\n\tm_translate_in = 0;\n\tm_translate_out = 0;\n}\n\nMySpellChecker::~MySpellChecker()\n{\n\tdelete myspell;\n\tif (g_iconv_is_valid (m_translate_in ))\n\t\tg_iconv_close(m_translate_in);\n\tm_translate_in = G_ICONV_INVALID;\n\tif (g_iconv_is_valid(m_translate_out))\n\t\tg_iconv_close(m_translate_out);\n\tm_translate_out = G_ICONV_INVALID;\n}\n\nbool\nMySpellChecker::checkWord(const char *utf8Word, size_t len)\n{\n\tif (len > MAXWORDLEN || !g_iconv_is_valid(m_translate_in))\n\t\treturn false;\n\n\tstd::string word (utf8Word, len);\n\tif (m_personal[word])\n\t\treturn true;\n\tif (m_session[word])\n\t\treturn true;\n\n\tchar *in = (char*) utf8Word;\n\tchar word8[MAXWORDLEN + 1];\n\tchar *out = word8;\n\tsize_t len_in = len * sizeof(char);\n\tsize_t len_out = sizeof( word8 ) - 1;\n\tg_iconv(m_translate_in, &in, &len_in, &out, &len_out);\n\t*out = '\\0';\n\tif (myspell->spell(word8))\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nchar**\nMySpellChecker::suggestWord(const char* const utf8Word, size_t len, size_t *nsug)\n{\n\tif (len > MAXWORDLEN \n\t\t|| !g_iconv_is_valid(m_translate_in)\n\t\t|| !g_iconv_is_valid(m_translate_out))\n\t\treturn 0;\n\tchar *in = (char*) utf8Word;\n\tchar word8[MAXWORDLEN + 1];\n\tchar *out = word8;\n\tsize_t len_in = len;\n\tsize_t len_out = sizeof(word8) - 1;\n\tg_iconv(m_translate_in, &in, &len_in, &out, &len_out);\n\t*out = '\\0';\n\tchar **sugMS;\n\t*nsug = myspell->suggest(&sugMS, word8);\n\tif (*nsug > 0) {\n\t\tchar **sug = g_new0 (char *, *nsug + 1);\n\t\tfor (int i=0; i<*nsug; i++) {\n\t\t\tin = sugMS[i];\n\t\t\tlen_in = strlen(in);\n\t\t\tlen_out = sizeof(char) * (len_in + 1);\n\t\t\tchar *word = g_new0(char, len_out);\n\t\t\tout = reinterpret_cast<char *>(word);\n\t\t\tg_iconv(m_translate_out, &in, &len_in, &out, &len_out);\n\t\t\t*(out) = 0;\n\t\t\tsug[i] = word;\n\t\t\tfree(sugMS[i]);\n\t\t}\n\t\tfree(sugMS);\n\t\treturn sug;\n\t}\n\telse\n\t\treturn 0;\n}\n\nstatic void\ns_buildHashNames (std::vector<std::string> & names, const char * dict)\n{\n\tchar * tmp, * private_dir, * home_dir, * ispell_prefix, * dict_dic;\n\n\tnames.clear ();\n\n\tdict_dic = g_strconcat(dict, \".dic\", NULL);\n\n\thome_dir = enchant_get_user_home_dir ();\n\tif (home_dir) {\n\t\tprivate_dir = g_build_filename (home_dir, \".enchant\", \n\t\t\t\t\t\t\"myspell\", NULL);\n\t\t\n\t\ttmp = g_build_filename (private_dir, dict_dic, NULL);\n\t\tnames.push_back (tmp);\n\t\tg_free (tmp);\n\n\t\tg_free (private_dir);\n\t\tg_free (home_dir);\n\t}\n\n\tmyspell_prefix = myspell_checker_get_prefix ();\n\tif (myspell_prefix) {\n\t\ttmp = g_build_filename (myspell_prefix, dict_dict, NULL);\n\t\tnames.push_back (tmp);\n\t\tg_free (tmp);\n\t\tg_free (myspell_prefix);\n\t}\n\n\tg_free(dict_dic);\n}\n\nstatic char *\nmyspell_request_dictionary (const char * tag) \n{\n\tchar * dic = NULL;\n\n\tstd::vector<std::string> names;\n\n\ts_buildHashNames (names, tag);\n\n\tfor (size_t i = 0; i < names.size () && !dic; i++) {\n\t\tif (g_file_test(names[i].c_str(), G_FILE_TEST_EXISTS))\n\t\t\tdic = g_strdup (names[i].c_str());\n\t}\n\t\n\treturn dic;\n}\n\nbool\nMySpellChecker::requestDictionary(const char *szLang)\n{\n\tconst char *dictBase = NULL;\n\tchar *dic = NULL, *aff = NULL;\n\tchar *home_dir = enchant_get_user_home_dir();\n\n\tdic = myspell_request_dictionary (szLang);\n\tif (!dic) {\n\t\tstd::string shortened_dict (szLang);\n\t\tsize_t uscore_pos;\n\t\t\n\t\t\/\/ try abbreviated form\n\t\tif ((uscore_pos = shortened_dict.rfind ('_')) != ((size_t)-1)) {\n\t\t\tshortened_dict = shortened_dict.substr(0, uscore_pos);\n\t\t\tdic = myspell_request_dictionary (shortened_dict.c_str());\n\t\t}\n\t}\n\tif (!dic)\n\t\treturn false;\n\n\taff = g_strdup(dic);\n\tint len_dic = strlen(dic);\n\tstrcpy(aff+len_dic-3, \"aff\");\n\tmyspell = new MySpell(aff, dic);\n\tg_free(dic);\n\tg_free(aff);\n\tchar *enc = myspell->get_dic_encoding();\n\n\tm_translate_in = g_iconv_open(enc, \"UTF-8\");\n\tm_translate_out = g_iconv_open(\"UTF-8\", enc);\n\n\treturn true;\n}\n\n\/*\n * Enchant\n *\/\n\nstatic char **\nmyspell_dict_suggest (EnchantDict * me, const char *const word,\n\t\t size_t len, size_t * out_n_suggs)\n{\n\tMySpellChecker * checker;\n\t\n\tchecker = (MySpellChecker *) me->user_data;\n\treturn checker->suggestWord (word, len, out_n_suggs);\n}\n\nstatic int\nmyspell_dict_check (EnchantDict * me, const char *const word, size_t len)\n{\n\tMySpellChecker * checker;\n\t\n\tchecker = (MySpellChecker *) me->user_data;\n\t\n\tif (checker->checkWord(word, len))\n\t\treturn 0;\n\t\n\treturn 1;\n}\n\nstatic void\nmyspell_dict_add_to_personal (EnchantDict * me,\n\t\t\t const char *const word, size_t len)\n{\n\tMySpellChecker * checker;\n\t\n\t\/\/ emulate adding to a personal dictionary via a session-like\n\t\/\/ interface\n\n\tchecker = (MySpellChecker *) me->user_data;\n\tchecker->addToPersonal(word, len);\n}\n\nstatic void\nmyspell_dict_add_to_session(EnchantDict * me,\n\t\t\t const char *const word, size_t len)\n{\n\tMySpellChecker * checker;\n\t\n\t\/\/ implement a session interface\n\n\tchecker = (MySpellChecker *) me->user_data;\n\tchecker->addToSession(word, len);\n}\n\nstatic void\nmyspell_dict_free_suggestions (EnchantDict * me, char **str_list)\n{\n\tg_strfreev (str_list);\n}\n\nstatic EnchantDict *\nmyspell_provider_request_dict(EnchantProvider * me, const char *const tag)\n{\n\tEnchantDict *dict;\n\tMySpellChecker * checker;\n\t\n\tchecker = new MySpellChecker();\n\t\n\tif (!checker)\n\t\treturn NULL;\n\t\n\tif (!checker->requestDictionary(tag)) {\n\t\tdelete checker;\n\t\treturn NULL;\n\t}\n\t\n\tdict = g_new0(EnchantDict, 1);\n\tdict->user_data = (void *) checker;\n\tdict->check = myspell_dict_check;\n\tdict->suggest = myspell_dict_suggest;\n\tdict->add_to_personal = myspell_dict_add_to_personal;\n\tdict->add_to_session = myspell_dict_add_to_session;\n\tdict->free_suggestions = myspell_dict_free_suggestions;\n\t\n\treturn dict;\n}\n\nstatic void\nmyspell_provider_dispose_dict (EnchantProvider * me, EnchantDict * dict)\n{\n\tMySpellChecker *checker;\n\t\n\tchecker = (MySpellChecker *) dict->user_data;\n\tdelete checker;\n\t\n\tg_free (dict);\n}\n\nstatic EnchantDictStatus\nmyspell_provider_dictionary_status (struct str_enchant_provider * me,\n\t\t\t\t const char *const tag)\n{\n\tstd::vector <std::string> names;\n\n\ts_buildHashNames (names, tag);\n\tfor (size_t i = 0; i < names.size(); i++) {\n\t\tif (g_file_test (names[i].c_str(), G_FILE_TEST_EXISTS))\n\t\t\treturn EDS_EXISTS;\n\t}\n\n\tstd::string shortened_dict (tag);\n\tsize_t uscore_pos;\n\t\n\tif ((uscore_pos = shortened_dict.rfind ('_')) != ((size_t)-1)) {\n\t\tshortened_dict = shortened_dict.substr(0, uscore_pos);\n\n\t\ts_buildHashNames (names, shortened_dict.c_str());\n\t\tfor (size_t i = 0; i < names.size(); i++) {\n\t\t\tif (g_file_test (names[i].c_str(), G_FILE_TEST_EXISTS))\n\t\t\t\treturn EDS_EXISTS;\n\t\t}\n\t}\n\n\treturn EDS_DOESNT_EXIST;\n}\n\nstatic void\nmyspell_provider_dispose (EnchantProvider * me)\n{\n\tg_free (me);\n}\n\nstatic char *\nmyspell_provider_identify (EnchantProvider * me)\n{\n\treturn \"myspell\";\n}\n\nstatic char *\nmyspell_provider_describe (EnchantProvider * me)\n{\n\treturn \"Myspell Provider\";\n}\n\nextern \"C\" {\n\nENCHANT_MODULE_EXPORT (EnchantProvider *) \ninit_enchant_provider (void)\n{\n\tEnchantProvider *provider;\n\t\n\tprovider = g_new0(EnchantProvider, 1);\n\tprovider->dispose = myspell_provider_dispose;\n\tprovider->request_dict = myspell_provider_request_dict;\n\tprovider->dispose_dict = myspell_provider_dispose_dict;\n\tprovider->dictionary_status = myspell_provider_dictionary_status;\n\tprovider->identify = myspell_provider_identify;\n\tprovider->describe = myspell_provider_describe;\n\n\treturn provider;\n}\n\n} \/\/ extern C linkage\n<|endoftext|>"} {"text":"<commit_before>#include \"task_mnist.h\"\n#include \"common\/logger.h\"\n#include \"common\/cast.hpp\"\n#include \"common\/io_arch.h\"\n#include \"common\/io_stream.h\"\n#include \"loss.h\"\n\nnamespace ncv\n{\n mnist_task_t::mnist_task_t(const string_t& configuration)\n : task_t(configuration)\n {\n }\n\n bool mnist_task_t::load(const string_t& dir)\n {\n const string_t test_ifile = dir + \"\/t10k-images-idx3-ubyte.gz\";\n const string_t test_gfile = dir + \"\/t10k-labels-idx1-ubyte.gz\";\n const size_t n_test_samples = 10000;\n\n const string_t train_ifile = dir + \"\/train-images-idx3-ubyte.gz\";\n const string_t train_gfile = dir + \"\/train-labels-idx1-ubyte.gz\";\n const size_t n_train_samples = 60000;\n\n clear_memory(n_train_samples + n_test_samples);\n\n return load(train_ifile, train_gfile, protocol::train, n_train_samples) &&\n load(test_ifile, test_gfile, protocol::test, n_test_samples);\n }\n\n bool mnist_task_t::load(const string_t& ifile, const string_t& gfile, protocol p, size_t count)\n {\n size_t icount = 0;\n size_t gcount = 0;\n\n std::vector<char> vbuffer(n_rows() * n_cols());\n char* buffer = vbuffer.data();\n char label[2];\n\n \/\/ load image file\n const auto iop = [&] (const string_t&, const io::data_t& data)\n {\n io::stream_t stream(data.data(), data.size());\n\n stream.read(buffer, 16);\n while (stream.read(buffer, vbuffer.size()) && stream.gcount() == vbuffer.size())\n {\n image_t image;\n image.load_luma(buffer, n_rows(), n_cols());\n m_images.push_back(image);\n\n ++ icount;\n } \n \n return true;\n };\n\n log_info() << \"MNIST: loading file <\" << ifile << \"> ...\";\n if (!io::decode(ifile, \"MNIST: \", iop))\n {\n log_error() << \"MNIST: failed to load file <\" << ifile << \">!\";\n return 0;\n }\n\n \/\/ load ground truth file\n const auto gop = [&] (const string_t&, const io::data_t& data)\n {\n io::stream_t stream(data.data(), data.size());\n\n stream.read(buffer, 8);\n while (stream.read(label, 1) && stream.gcount() == 1)\n {\n const size_t ilabel = math::cast<size_t>(label[0]);\n\n sample_t sample(m_samples.size(), sample_region(0, 0));\n sample.m_label = \"digit\" + text::to_string(ilabel);\n sample.m_target = ncv::class_target(ilabel, n_outputs());\n sample.m_fold = { 0, p };\n m_samples.push_back(sample);\n\n ++ gcount;\n }\n \n return true;\n };\n\n log_info() << \"MNIST: loading file <\" << gfile << \"> ...\";\n if (!io::decode(gfile, \"MNIST: \", gop))\n {\n log_error() << \"MNIST: failed to load file <\" << gfile << \">!\";\n return 0;\n }\n\n \/\/ OK\n log_info() << \"MNIST: loaded \" << icount << \"\/\" << gcount << \" samples.\";\n return (icount == gcount == count) > 0;\n }\n}\n<commit_msg>fix MNIST loading<commit_after>#include \"task_mnist.h\"\n#include \"common\/logger.h\"\n#include \"common\/cast.hpp\"\n#include \"common\/io_arch.h\"\n#include \"common\/io_stream.h\"\n#include \"loss.h\"\n\nnamespace ncv\n{\n mnist_task_t::mnist_task_t(const string_t& configuration)\n : task_t(configuration)\n {\n }\n\n bool mnist_task_t::load(const string_t& dir)\n {\n const string_t test_ifile = dir + \"\/t10k-images-idx3-ubyte.gz\";\n const string_t test_gfile = dir + \"\/t10k-labels-idx1-ubyte.gz\";\n const size_t n_test_samples = 10000;\n\n const string_t train_ifile = dir + \"\/train-images-idx3-ubyte.gz\";\n const string_t train_gfile = dir + \"\/train-labels-idx1-ubyte.gz\";\n const size_t n_train_samples = 60000;\n\n clear_memory(n_train_samples + n_test_samples);\n\n return load(train_ifile, train_gfile, protocol::train, n_train_samples) &&\n load(test_ifile, test_gfile, protocol::test, n_test_samples);\n }\n\n bool mnist_task_t::load(const string_t& ifile, const string_t& gfile, protocol p, size_t count)\n {\n size_t icount = 0;\n size_t gcount = 0;\n\n std::vector<char> vbuffer(n_rows() * n_cols());\n char* buffer = vbuffer.data();\n char label[2];\n\n \/\/ load image file\n const auto iop = [&] (const string_t&, const io::data_t& data)\n {\n io::stream_t stream(data.data(), data.size());\n\n stream.read(buffer, 16);\n while (stream.read(buffer, vbuffer.size()) && stream.gcount() == vbuffer.size())\n {\n image_t image;\n image.load_luma(buffer, n_rows(), n_cols());\n m_images.push_back(image);\n\n ++ icount;\n } \n \n return true;\n };\n\n log_info() << \"MNIST: loading file <\" << ifile << \"> ...\";\n if (!io::decode(ifile, \"MNIST: \", iop))\n {\n log_error() << \"MNIST: failed to load file <\" << ifile << \">!\";\n return false;\n }\n\n \/\/ load ground truth file\n const auto gop = [&] (const string_t&, const io::data_t& data)\n {\n io::stream_t stream(data.data(), data.size());\n\n stream.read(buffer, 8);\n while (stream.read(label, 1) && stream.gcount() == 1)\n {\n const size_t ilabel = math::cast<size_t>(label[0]);\n\n sample_t sample(m_samples.size(), sample_region(0, 0));\n sample.m_label = \"digit\" + text::to_string(ilabel);\n sample.m_target = ncv::class_target(ilabel, n_outputs());\n sample.m_fold = { 0, p };\n m_samples.push_back(sample);\n\n ++ gcount;\n }\n \n return true;\n };\n\n log_info() << \"MNIST: loading file <\" << gfile << \"> ...\";\n if (!io::decode(gfile, \"MNIST: \", gop))\n {\n log_error() << \"MNIST: failed to load file <\" << gfile << \">!\";\n return false;\n }\n\n \/\/ OK\n log_info() << \"MNIST: loaded \" << icount << \"\/\" << gcount << \" samples.\";\n return (count == gcount) && (count == icount);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ \\file nested_traversal_finder.cpp: Contains implementation for a TraversalFinder that works on non-leaf Snarls.\n\n#include \"genotypekit.hpp\"\n\nnamespace vg {\n\nusing namespace std;\n\n\/**\n * This TraversalFinder emits at least one traversal representing every node,\n * edge, or child Snarl. Only works on ultrabubbles, and so does not handle\n * cycles.\n *\/\nclass NestedTraversalFinder : public TraversalFinder {\n\nprotected:\n \/\/\/ The annotated, augmented graph we're finding traversals in\n AugmentedGraph& augmented;\n \/\/\/ The SnarlManager managiung the snarls we use\n SnarlManager& snarl_manager;\n \n \/**\n * Given an edge or node or child snarl in the augmented graph, look out\n * from the edge or node or child in both directions to find a shortest\n * bubble connecting the start and end of the given site.\n *\n * Exactly one of edge and node and child must be non-null.\n *\n * Return the found traversal as a vector of Visits, including anchoring\n * Visits to the site's start and end nodes. Also return the minimum support\n * found on any edge or node in the bubble that is not contained within a\n * child.\n *\/\n pair<Support, vector<Visit>> find_bubble(Node* node, Edge* edge, Snarl* child, const Snarl& site);\n \n \/**\n * Get the minimum support of all nodes and edges used in the given path\n * that are not inside child snarls.\n *\/\n Support min_support_in_path(const vector<Visit>& path);\n \n \/**\n * Do a breadth-first search left from the given node traversal, and return\n * lengths (in visits) and paths starting at the given node and ending on\n * the given indexed path. Refuses to visit nodes with no support.\n *\n * Lengths are included so that shorter paths sort first.\n *\/\n set<pair<size_t, list<Visit>>> search_left(Visit root, const Snarl& site,\n const map<NodeTraversal, const Snarl*>& child_boundary_index);\n \n \/**\n * Do a breadth-first search right from the given node traversal, and return\n * lengths (in visits) and paths starting at the given node and ending on\n * the given indexed path.\n *\n * Lengths are included so that shorter paths sort first.\n *\/\n set<pair<size_t, list<Visit>>> search_right(Visit root, const Snarl& site,\n const map<NodeTraversal, const Snarl*>& child_boundary_index);\n \n \/**\n * Get the length of a path through nodes and child sites, in base pairs.\n * Ignores any bases inside child sites.\n *\/\n size_t bp_length(const list<Visit>& path);\n \npublic:\n\n NestedTraversalFinder(AugmentedGraph& augmented, SnarlManager& snarl_manager);\n \n \/\/\/ Should we emit verbose debugging info?\n bool verbose = false;\n \n virtual ~NestedTraversalFinder() = default;\n \n \/**\n * Find traversals to cover the nodes, edges, and children of the snarl.\n * Always emits the primary path traversal first, if applicable.\n *\/\n virtual vector<SnarlTraversal> find_traversals(const Snarl& site);\n \n};\n\n\nNestedTraversalFinder::NestedTraversalFinder(AugmentedGraph& augmented,\n SnarlManager& snarl_manager) : augmented(augmented), snarl_manager(snarl_manager) {\n \n \/\/ Nothing to do!\n\n}\n\nvector<SnarlTraversal> NestedTraversalFinder::find_traversals(const Snarl& site) {\n \n \/\/ TODO: implement\n}\n\npair<Support, vector<Visit>> NestedTraversalFinder::find_bubble(Node* node, Edge* edge, Snarl* child, const Snarl& site) {\n\n \/\/ TODO: implement\n \n}\n\nSupport NestedTraversalFinder::min_support_in_path(const vector<Visit>& path) {\n \n \/\/ TODO: implement\n}\n\nset<pair<size_t, list<Visit>>> NestedTraversalFinder::search_left(Visit root, const Snarl& site,\n const map<NodeTraversal, const Snarl*>& child_boundary_index) {\n \n \/\/ Find paths left from the given visit to the start or end of the given\n \/\/ ultrabubble.\n \n \/\/ Right now just finds the shortest path in nodes.\n\n \/\/ Holds partial paths we want to return, with their lengths in visits.\n set<pair<size_t, list<Visit>>> to_return;\n \n \/\/ Do a BFS\n \n \/\/ This holds the parent of each Visit in the queue, back to the initial\n \/\/ rooting visit.\n map<Visit, Visit> parents;\n \n \/\/ This holds all the visits we need to look at.\n list<Visit> queue {root};\n \n while(!queue.empty()) {\n \/\/ Keep going until we've emptied the queue\n \n \/\/ Dequeue a visit to continue from.\n Visit to_extend_from = queue.front();\n queue.pop_front();\n \n if (to_extend_from == site.start() || to_extend_from == site.end()) {\n \/\/ We're done! Do a trace back.\n \n \/\/ Fill in this path\n list<Visit> path; \n \n \/\/ With this cursor\n Visit v = to_extend_from;\n \n while (v != root) {\n \/\/ Until we get to the root, put this node on the path and get\n \/\/ its parent.\n path.push_back(v);\n v = parents.at(v);\n }\n \/\/ We hit the root so add it to the path too.\n path.push_back(v);\n \n \/\/ Add the path and its length to the list to return\n to_return.insert(make_pair(path.size(), path));\n \n \/\/ And go ahead and return it right now (since it's maximally short)\n return to_return;\n } else {\n \/\/ We haven't reached a boundary, so just keep searching left from\n \/\/ this visit.\n vector<Visit> neighbors = visits_left(to_extend_from, augmented.graph, child_boundary_index);\n \n \n \/\/ TODO: implement\n \/\/ For each thing off the left\n \n \/\/ Check the edge to it to make sure it has coverage\n \n \/\/ If the next thing is a node, check it to make sure it has coverage\n \n \/\/ If the next thing is a snarl, maybe check its attached boundary node to make sure it has coverage?\n \n \/\/ If it checks out, queue each neighbor with this visit as its parent\n \n }\n \n }\n \n \/\/ We should never get here becuase we should eventually reach the end of\n \/\/ the site we're searching.\n throw runtime_error(\"Got lost in site in search_left!\");\n}\n\nset<pair<size_t, list<Visit>>> NestedTraversalFinder::search_right(Visit root, const Snarl& site,\n const map<NodeTraversal, const Snarl*>& child_boundary_index) {\n\n \/\/ Make a backwards version of the root\n Visit root_rev = root;\n root_rev.set_backward(!root_rev.backward());\n\n \/\/ Look left from the backward version of the root\n auto to_convert = search_left(root_rev, site, child_boundary_index);\n \n \/\/ Since we can't modify set records in place, we need to do a copy\n set<pair<size_t, list<Visit>>> to_return;\n \n for(auto length_and_path : to_convert) {\n \/\/ Flip every path to run the other way\n length_and_path.second.reverse();\n for(auto& visit : length_and_path.second) {\n \/\/ And invert the orientation of every visit in the path in place.\n visit.set_backward(!visit.backward());\n }\n \/\/ Stick it in the new set\n to_return.emplace(move(length_and_path));\n }\n \n return to_return;\n}\n\n}\n<commit_msg>Add more implementations<commit_after>\/\/\/ \\file nested_traversal_finder.cpp: Contains implementation for a TraversalFinder that works on non-leaf Snarls.\n\n#include \"genotypekit.hpp\"\n\nnamespace vg {\n\nusing namespace std;\n\n\/**\n * This TraversalFinder emits at least one traversal representing every node,\n * edge, or child Snarl. Only works on ultrabubbles, and so does not handle\n * cycles.\n *\/\nclass NestedTraversalFinder : public TraversalFinder {\n\nprotected:\n \/\/\/ The annotated, augmented graph we're finding traversals in\n AugmentedGraph& augmented;\n \/\/\/ The SnarlManager managiung the snarls we use\n SnarlManager& snarl_manager;\n \n \/**\n * Given an edge or node or child snarl in the augmented graph, look out\n * from the edge or node or child in both directions to find a shortest\n * bubble connecting the start and end of the given site.\n *\n * Exactly one of edge and node and child must be non-null.\n *\n * Return the found traversal as a vector of Visits, including anchoring\n * Visits to the site's start and end nodes. Also return the minimum support\n * found on any edge or node in the bubble that is not contained within a\n * child.\n *\n * If there is no path with any support, returns a zero Support and an empty\n * vector.\n *\/\n pair<Support, vector<Visit>> find_bubble(Node* node, Edge* edge, Snarl* child,\n const Snarl& site, const map<NodeTraversal, const Snarl*>& child_boundary_index);\n \n \/**\n * Get the minimum support of all nodes and edges used in the given path\n * that are not inside child snarls.\n *\/\n Support min_support_in_path(const vector<Visit>& path);\n \n \/**\n * Do a breadth-first search left from the given node traversal, and return\n * lengths (in visits) and paths starting at the given node and ending on\n * the given indexed path. Refuses to visit nodes with no support.\n *\n * Lengths are included so that shorter paths sort first.\n *\/\n set<pair<size_t, list<Visit>>> search_left(const Visit& root, const Snarl& site,\n const map<NodeTraversal, const Snarl*>& child_boundary_index);\n \n \/**\n * Do a breadth-first search right from the given node traversal, and return\n * lengths (in visits) and paths starting at the given node and ending on\n * the given indexed path.\n *\n * Lengths are included so that shorter paths sort first.\n *\/\n set<pair<size_t, list<Visit>>> search_right(const Visit& root, const Snarl& site,\n const map<NodeTraversal, const Snarl*>& child_boundary_index);\n \n \/**\n * Get the length of a path through nodes and child sites, in base pairs.\n * Ignores any bases inside child sites.\n *\/\n size_t bp_length(const list<Visit>& path);\n \npublic:\n\n NestedTraversalFinder(AugmentedGraph& augmented, SnarlManager& snarl_manager);\n \n \/\/\/ Should we emit verbose debugging info?\n bool verbose = false;\n \n virtual ~NestedTraversalFinder() = default;\n \n \/**\n * Find traversals to cover the nodes, edges, and children of the snarl.\n * Always emits the primary path traversal first, if applicable.\n *\/\n virtual vector<SnarlTraversal> find_traversals(const Snarl& site);\n \n};\n\n\nNestedTraversalFinder::NestedTraversalFinder(AugmentedGraph& augmented,\n SnarlManager& snarl_manager) : augmented(augmented), snarl_manager(snarl_manager) {\n \n \/\/ Nothing to do!\n\n}\n\nvector<SnarlTraversal> NestedTraversalFinder::find_traversals(const Snarl& site) {\n \n \/\/ For each node, edge, and child snarl, try and find a traversal that visits it\n}\n\npair<Support, vector<Visit>> NestedTraversalFinder::find_bubble(Node* node, Edge* edge, Snarl* child, const Snarl& site, const map<NodeTraversal, const Snarl*>& child_boundary_index) {\n\n \/\/ What are we going to find our left and right path halves based on?\n Visit left_visit;\n Visit right_visit;\n\n if(edge != nullptr) {\n \/\/ Be edge-based\n \n \/\/ TODO: if the edge has no support, don't go looking for a path\n \n \/\/ Find the nodes at the ends of the edges. Look at them traversed in the\n \/\/ edge's local orientation.\n left_visit.set_node_id(edge->from());\n left_visit.set_backward(edge->from_start());\n \n right_visit.set_node_id(edge->to());\n right_visit.set_backward(edge->to_end());\n } else if (node != nullptr) {\n \/\/ Be node-based. Both roots are the same visit\n left_visit.set_node_id(node->id());\n right_visit = left_visit;\n } else {\n \/\/ We must be child-based\n assert(child != nullptr);\n \n \/\/ Both roots are the same child snarl visit\n transfer_boundary_info(*child, *left_visit.mutable_snarl());\n right_visit = left_visit;\n }\n \n \/\/ Find paths on both sides, anchored into the outside of our snarl. Returns\n \/\/ path lengths (in visits) and paths in pairs in a set.\n auto left_paths = search_left(left_visit, site, child_boundary_index);\n auto right_paths = search_right(right_visit, site, child_boundary_index);\n \n \/\/ Now splice the paths together to get max support.\n \n \/\/ TODO: implement that. For now just get any path with nonzero support.\n \n for (auto& left : left_paths) {\n for (auto& right : right_paths) {\n \/\/ Splice together the first path from each set\n \n \/\/ Start witht he whole left path\n vector<Visit> spliced_path {left.second.begin(), left.second.end()};\n \n auto it = right.second.begin();\n if (it != right.second.end() && !spliced_path.empty() && *it == spliced_path.back()) {\n \/\/ If the right path starts with the same visit the left path ended with, skip it.\n ++it;\n }\n \n \/\/ Copy over the rest of the right side path\n copy(it, right.second.end(), back_inserter(spliced_path));\n \n \/\/ Return this spliced-together path with its support\n return make_pair(min_support_in_path(spliced_path), spliced_path);\n \n }\n }\n \n \/\/ If we get here there's no pair of paths to combine. Return the zero value.\n return pair<Support, vector<Visit>>();\n \n}\n\nSupport NestedTraversalFinder::min_support_in_path(const vector<Visit>& path) {\n \n if (path.empty()) {\n return Support();\n }\n \/\/ We look at the current visit and the next visit so we can think about\n \/\/ edges.\n auto cur = path.begin();\n auto next = path.begin();\n ++next;\n \n \/\/ We have a function to get the support for a visit\n function<Support(const Visit&)> support_for_visit = [&](const Visit& v) { \n if (v.node_id()) {\n \/\/ This is a node visit\n Node* node = augmented.graph.get_node(v.node_id());\n \n \/\/ Return the support for it, or 0 if it's not in the map.\n return augmented.node_supports.count(node) ? augmented.node_supports.at(node) : Support();\n } else {\n \/\/ It's a snarl visit. We assume it goes in one side and out the\n \/\/ other.\n \n \/\/ We don't inspect the whole snarl, but we know you have to visit\n \/\/ the start and end nodes, so we look at them.\n return support_min(support_for_visit(v.snarl().start()), support_for_visit(v.snarl().end()));\n }\n }; \n \n \/\/ Start out with the support for the current visit.\n Support min_support = support_for_visit(*cur);\n for (; next != path.end(); ++cur, ++next) {\n \/\/ For each subsequent node next\n \n \/\/ check the node support\n min_support = support_min(min_support, support_for_visit(*next));\n \n \/\/ check the edge support\n Edge* edge = augmented.graph.get_edge(to_left_side(*cur), to_right_side(*next));\n assert(edge != NULL);\n Support edge_support = augmented.edge_supports.count(edge) ? augmented.edge_supports.at(edge) : Support();\n min_support = support_min(min_support, edge_support);\n }\n\n return min_support;\n}\n\nset<pair<size_t, list<Visit>>> NestedTraversalFinder::search_left(const Visit& root, const Snarl& site,\n const map<NodeTraversal, const Snarl*>& child_boundary_index) {\n \n \/\/ Find paths left from the given visit to the start or end of the given\n \/\/ ultrabubble.\n \n \/\/ Right now just finds the shortest path in nodes.\n\n \/\/ Holds partial paths we want to return, with their lengths in visits.\n set<pair<size_t, list<Visit>>> to_return;\n \n \/\/ Do a BFS\n \n \/\/ This holds the parent of each Visit in the queue, back to the initial\n \/\/ rooting visit.\n map<Visit, Visit> parents;\n \n \/\/ This holds all the visits we need to look at.\n list<Visit> queue {root};\n \n while(!queue.empty()) {\n \/\/ Keep going until we've emptied the queue\n \n \/\/ Dequeue a visit to continue from.\n Visit to_extend_from = queue.front();\n queue.pop_front();\n \n if (to_extend_from == site.start() || to_extend_from == site.end()) {\n \/\/ We're done! Do a trace back.\n \n \/\/ Fill in this path\n list<Visit> path; \n \n \/\/ With this cursor\n Visit v = to_extend_from;\n \n while (v != root) {\n \/\/ Until we get to the root, put this node on the path and get\n \/\/ its parent.\n path.push_back(v);\n v = parents.at(v);\n }\n \/\/ We hit the root so add it to the path too.\n path.push_back(v);\n \n \/\/ Add the path and its length to the list to return\n to_return.insert(make_pair(path.size(), path));\n \n \/\/ And go ahead and return it right now (since it's maximally short)\n return to_return;\n } else {\n \/\/ We haven't reached a boundary, so just keep searching left from\n \/\/ this visit.\n vector<Visit> neighbors = visits_left(to_extend_from, augmented.graph, child_boundary_index);\n \n for (auto& extension : neighbors) {\n \/\/ For each thing off the left\n \n if (parents.count(extension)) {\n \/\/ This next node is already reachable by a path this short or shorter.\n continue;\n }\n \n \/\/ Check the edge to it to make sure it has coverage\n Edge* edge = augmented.graph.get_edge(to_right_side(extension), to_left_side(to_extend_from));\n \n if (!augmented.edge_supports.count(edge) || total(augmented.edge_supports.at(edge)) == 0) {\n \/\/ This edge is not supported, so don't explore this extension.\n continue;\n }\n\n \/\/ Look up the node we're entering (either the snarl boundary or\n \/\/ just the node we're going to visit), so we can check to make\n \/\/ sure it has coverage.\n Node* node = augmented.graph.get_node(to_right_side(extension).node);\n \n if (!augmented.node_supports.count(node) || total(augmented.node_supports.at(node)) == 0) {\n \/\/ This node is not supported, so don't explore this extension.\n continue;\n }\n \n \/\/ If it checks out, queue the neighbor with this visit as its parent\n parents[extension] = to_extend_from;\n queue.push_back(extension);\n }\n \n }\n \n }\n \n \/\/ If we get here, no path with any support was found. Return our still-empty set.\n return to_return;\n}\n\nset<pair<size_t, list<Visit>>> NestedTraversalFinder::search_right(const Visit& root, const Snarl& site,\n const map<NodeTraversal, const Snarl*>& child_boundary_index) {\n\n \/\/ Make a backwards version of the root\n Visit root_rev = root;\n root_rev.set_backward(!root_rev.backward());\n\n \/\/ Look left from the backward version of the root\n auto to_convert = search_left(root_rev, site, child_boundary_index);\n \n \/\/ Since we can't modify set records in place, we need to do a copy\n set<pair<size_t, list<Visit>>> to_return;\n \n for(auto length_and_path : to_convert) {\n \/\/ Flip every path to run the other way\n length_and_path.second.reverse();\n for(auto& visit : length_and_path.second) {\n \/\/ And invert the orientation of every visit in the path in place.\n visit.set_backward(!visit.backward());\n }\n \/\/ Stick it in the new set\n to_return.emplace(move(length_and_path));\n }\n \n return to_return;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <qcstring.h>\n#include <qdatetime.h>\n#include <qstring.h>\n#include <qtimer.h>\n\n#include <kiconloader.h>\n\n#include \"kapplication.h\" \/\/ kapp\n#include \"kdebug.h\"\n\n#include \"event.h\"\n\n#include \"karmutility.h\"\n#include \"task.h\"\n#include \"taskview.h\"\n#include \"preferences.h\"\n\n\nconst int gSecondsPerMinute = 60;\n\n\nQPtrVector<QPixmap> *Task::icons = 0;\n\nTask::Task( const QString& taskName, long minutes, long sessionTime,\n DesktopList desktops, TaskView *parent)\n : QObject(), QListViewItem(parent)\n{\n init(taskName, minutes, sessionTime, desktops, 0);\n}\n\nTask::Task( const QString& taskName, long minutes, long sessionTime,\n DesktopList desktops, Task *parent)\n : QObject(), QListViewItem(parent)\n{\n init(taskName, minutes, sessionTime, desktops, 0);\n}\n\nTask::Task( KCal::Todo* todo, TaskView* parent )\n : QObject(), QListViewItem( parent )\n{\n long minutes = 0;\n QString name;\n long sessionTime = 0;\n int percent_complete = 0;\n DesktopList desktops;\n\n parseIncidence(todo, minutes, sessionTime, name, desktops, percent_complete);\n init(name, minutes, sessionTime, desktops, percent_complete);\n}\n\nvoid Task::init( const QString& taskName, long minutes, long sessionTime,\n DesktopList desktops, int percent_complete)\n{\n \/\/ If our parent is the taskview then connect our totalTimesChanged\n \/\/ signal to its receiver\n if ( ! parent() )\n connect( this, SIGNAL( totalTimesChanged ( long, long ) ),\n listView(), SLOT( taskTotalTimesChanged( long, long) ));\n\n connect( this, SIGNAL( deletingTask( Task* ) ),\n listView(), SLOT( deletingTask( Task* ) ));\n\n if (icons == 0) {\n icons = new QPtrVector<QPixmap>(8);\n for (int i=0; i<8; i++)\n {\n QPixmap *icon = new QPixmap();\n QString name;\n name.sprintf(\"watch-%d.xpm\",i);\n *icon = UserIcon(name);\n icons->insert(i,icon);\n }\n }\n\n \/\/kdDebug(5970) << \"Task::init(\" << taskName << \", \" << minutes << \", \"\n \/\/ << sessionTime << \", desktops)\" << endl;\n\n _name = taskName.stripWhiteSpace();\n _lastStart = QDateTime::currentDateTime();\n _totalTime = _time = minutes;\n _totalSessionTime = _sessionTime = sessionTime;\n noNegativeTimes();\n _timer = new QTimer(this);\n _desktops = desktops;\n connect(_timer, SIGNAL(timeout()), this, SLOT(updateActiveIcon()));\n setPixmap(1, UserIcon(QString::fromLatin1(\"empty-watch.xpm\")));\n _currentPic = 0;\n _percentcomplete = percent_complete;\n\n update();\n changeParentTotalTimes( _sessionTime, _time);\n}\n\nTask::~Task() {\n emit deletingTask(this);\n delete _timer;\n}\n\nvoid Task::setRunning( bool on, KarmStorage* storage )\n{\n if ( on ) {\n if (!_timer->isActive()) {\n _timer->start(1000);\n storage->startTimer(this);\n _currentPic=7;\n _lastStart = QDateTime::currentDateTime();\n updateActiveIcon();\n }\n }\n else {\n if (_timer->isActive()) {\n _timer->stop();\n storage->stopTimer(this);\n setPixmap(1, UserIcon(QString::fromLatin1(\"empty-watch.xpm\")));\n }\n }\n}\n\nvoid Task::setUid(QString uid) {\n _uid = uid;\n}\n\nbool Task::isRunning() const\n{\n return _timer->isActive();\n}\n\nvoid Task::setName( const QString& name, KarmStorage* storage )\n{\n kdDebug(5970) << \"Task:setName: \" << name << endl;\n\n QString oldname = _name;\n if ( oldname != name ) {\n _name = name;\n storage->setName(this, oldname);\n update();\n }\n}\n\nvoid Task::setPercentComplete(const int percent, KarmStorage *storage)\n{\n kdDebug(5970) << \"Task::setPercentComplete(\" << percent << \", storage): \"\n << _uid << endl;\n\n if (isRunning()) setRunning(false, storage);\n\n setEnabled(false);\n setOpen(false);\n\n if (!percent)\n _percentcomplete = 0;\n else if (percent > 100)\n _percentcomplete = 100;\n else if (percent < 0)\n _percentcomplete = 0;\n else\n _percentcomplete = percent;\n\n \/\/ When parent marked as complete, mark all children as complete as well.\n \/\/ Complete tasks are not displayed in the task view, so if a parent is\n \/\/ marked as complete and some of the children are not, then we get an error\n \/\/ message. KArm actually keep chugging along in this case and displays the\n \/\/ child tasks just fine, so an alternative solution is to remove that error\n \/\/ message (from KarmStorage::load). But I think it makes more sense that\n \/\/ if you mark a parent task as complete, then all children should be\n \/\/ complete as well.\n \/\/\n \/\/ This behavior is consistent with KOrganizer (as of 2003-09-24).\n if (_percentcomplete == 100)\n {\n for (Task* child= this->firstChild(); child; child = child->nextSibling())\n child->setPercentComplete(_percentcomplete, storage);\n }\n}\n\nbool Task::isComplete() { return _percentcomplete == 100; }\n\nvoid Task::removeFromView()\n{\n for (Task* child= this->firstChild(); child; child= child->nextSibling())\n child->removeFromView();\n delete this;\n}\n\nvoid Task::setDesktopList ( DesktopList desktopList )\n{\n _desktops = desktopList;\n}\n\nvoid Task::changeTime( long minutes, KarmStorage* storage )\n{\n changeTimes( minutes, minutes, storage); \n}\n\nvoid Task::changeTimes( long minutesSession, long minutes, KarmStorage* storage)\n{\n if( minutesSession != 0 || minutes != 0) \n {\n _sessionTime += minutesSession;\n _time += minutes;\n if ( storage ) storage->changeTime(this, minutes * gSecondsPerMinute);\n noNegativeTimes();\n changeTotalTimes( minutesSession, minutes );\n }\n}\n\nvoid Task::changeTotalTimes( long minutesSession, long minutes )\n{\n \/\/kdDebug(5970)\n \/\/ << \"Task::changeTotalTimes(\" << minutesSession << \", \"\n \/\/ << minutes << \") for \" << name() << endl;\n\n _totalSessionTime += minutesSession;\n _totalTime += minutes;\n noNegativeTimes();\n update();\n changeParentTotalTimes( minutesSession, minutes );\n}\n\nvoid Task::resetTimes()\n{\n _totalSessionTime -= _sessionTime;\n _totalTime -= _time;\n changeParentTotalTimes( -_sessionTime, -_time);\n _sessionTime = 0;\n _time = 0;\n update();\n}\n\nvoid Task::changeParentTotalTimes( long minutesSession, long minutes )\n{\n \/\/kdDebug(5970)\n \/\/ << \"Task::changeParentTotalTimes(\" << minutesSession << \", \"\n \/\/ << minutes << \") for \" << name() << endl;\n\n if ( isRoot() )\n emit totalTimesChanged( minutesSession, minutes );\n else\n parent()->changeTotalTimes( minutesSession, minutes );\n}\n\nbool Task::remove( QPtrList<Task>& activeTasks, KarmStorage* storage)\n{\n kdDebug(5970) << \"Task::remove: \" << _name << endl;\n\n bool ok = true;\n\n storage->removeTask(this);\n\n if( isRunning() ) setRunning( false, storage );\n\n for (Task* child = this->firstChild(); child; child = child->nextSibling())\n {\n if (child->isRunning())\n child->setRunning(false, storage);\n child->remove(activeTasks, storage);\n }\n\n changeParentTotalTimes( -_sessionTime, -_time);\n\n return ok;\n}\n\nvoid Task::updateActiveIcon()\n{\n _currentPic = (_currentPic+1) % 8;\n setPixmap(1, *(*icons)[_currentPic]);\n}\n\nvoid Task::noNegativeTimes()\n{\n if ( _time < 0 )\n _time = 0;\n if ( _sessionTime < 0 )\n _sessionTime = 0;\n}\n\nQString Task::fullName() const\n{\n if (isRoot())\n return name();\n else\n return parent()->fullName() + QString::fromLatin1(\"\/\") + name();\n}\n\nKCal::Todo* Task::asTodo(KCal::Todo* todo) const\n{\n\n todo->setSummary( name() );\n\n \/\/ Note: if the date start is empty, the KOrganizer GUI will have the\n \/\/ checkbox blank, but will prefill the todo's starting datetime to the\n \/\/ time the file is opened.\n \/\/ todo->setDtStart( current );\n\n todo->setCustomProperty( kapp->instanceName(),\n QCString( \"totalTaskTime\" ), QString::number( _time ) );\n todo->setCustomProperty( kapp->instanceName(),\n QCString( \"totalSessionTime\" ), QString::number( _sessionTime) );\n\n if (getDesktopStr().isEmpty())\n todo->removeCustomProperty(kapp->instanceName(), QCString(\"desktopList\"));\n else\n todo->setCustomProperty( kapp->instanceName(),\n QCString( \"desktopList\" ), getDesktopStr() );\n\n todo->setOrganizer( Preferences::instance()->userRealName() );\n\n todo->setPercentComplete(_percentcomplete);\n\n return todo;\n}\n\nbool Task::parseIncidence( KCal::Incidence* incident, long& minutes,\n long& sessionMinutes, QString& name, DesktopList& desktops,\n int& percent_complete )\n{\n bool ok;\n\n name = incident->summary();\n _uid = incident->uid();\n\n _comment = incident->description();\n\n ok = false;\n minutes = incident->customProperty( kapp->instanceName(),\n QCString( \"totalTaskTime\" )).toInt( &ok );\n if ( !ok )\n minutes = 0;\n\n ok = false;\n sessionMinutes = incident->customProperty( kapp->instanceName(),\n QCString( \"totalSessionTime\" )).toInt( &ok );\n if ( !ok )\n sessionMinutes = 0;\n\n QString desktopList = incident->customProperty( kapp->instanceName(),\n QCString( \"desktopList\" ) );\n QStringList desktopStrList = QStringList::split( QString::fromLatin1(\",\"),\n desktopList );\n desktops.clear();\n\n for ( QStringList::iterator iter = desktopStrList.begin();\n iter != desktopStrList.end();\n ++iter ) {\n int desktopInt = (*iter).toInt( &ok );\n if ( ok ) {\n desktops.push_back( desktopInt );\n }\n }\n\n percent_complete = static_cast<KCal::Todo*>(incident)->percentComplete();\n\n \/\/kdDebug(5970) << \"Task::parseIncidence: \"\n \/\/ << name << \", Minutes: \" << minutes\n \/\/ << \", desktop: \" << desktopList << endl;\n\n return true;\n}\n\nQString Task::getDesktopStr() const\n{\n if ( _desktops.empty() )\n return QString();\n\n QString desktopstr;\n for ( DesktopList::const_iterator iter = _desktops.begin();\n iter != _desktops.end();\n ++iter ) {\n desktopstr += QString::number( *iter ) + QString::fromLatin1( \",\" );\n }\n desktopstr.remove( desktopstr.length() - 1, 1 );\n return desktopstr;\n}\n\nvoid Task::cut()\n{\n \/\/kdDebug(5970) << \"Task::cut - \" << name() << endl;\n changeParentTotalTimes( -_totalSessionTime, -_totalTime);\n if ( ! parent())\n listView()->takeItem(this);\n else\n parent()->takeItem(this);\n}\n\nvoid Task::move(Task* destination)\n{\n cut();\n paste(destination);\n}\n\nvoid Task::paste(Task* destination)\n{\n destination->insertItem(this);\n changeParentTotalTimes( _totalSessionTime, _totalTime);\n}\n\nvoid Task::update()\n{\n setText(0, _name);\n setText(1, formatTime(_sessionTime));\n setText(2, formatTime(_time));\n setText(3, formatTime(_totalSessionTime));\n setText(4, formatTime(_totalTime));\n}\n\nvoid Task::addComment( QString comment, KarmStorage* storage )\n{\n _comment = _comment + QString::fromLatin1(\"\\n\") + comment;\n storage->addComment(this, comment);\n}\n\nQString Task::comment() const\n{\n return _comment;\n}\n\nint Task::compare ( QListViewItem * i, int col, bool ascending ) const\n{\n long thistime = 0;\n long thattime = 0;\n Task *task = static_cast<Task*>(i);\n\n switch ( col )\n {\n case 1: \n thistime = _sessionTime;\n thattime = task->sessionTime();\n break;\n case 2:\n thistime = _time;\n thattime = task->time();\n break;\n case 3:\n thistime = _totalSessionTime;\n thattime = task->totalSessionTime();\n break;\n case 4:\n thistime = _totalTime;\n thattime = task->totalTime();\n break;\n default:\n return key(col, ascending).localeAwareCompare( i->key(col, ascending) );\n }\n\n if ( thistime < thattime ) return -1;\n if ( thistime > thattime ) return 1;\n return 0;\n\n}\n\n#include \"task.moc\"\n<commit_msg>Allow negative task times. Fixes data loss bug.<commit_after>#include <qcstring.h>\n#include <qdatetime.h>\n#include <qstring.h>\n#include <qtimer.h>\n\n#include <kiconloader.h>\n\n#include \"kapplication.h\" \/\/ kapp\n#include \"kdebug.h\"\n\n#include \"event.h\"\n\n#include \"karmutility.h\"\n#include \"task.h\"\n#include \"taskview.h\"\n#include \"preferences.h\"\n\n\nconst int gSecondsPerMinute = 60;\n\n\nQPtrVector<QPixmap> *Task::icons = 0;\n\nTask::Task( const QString& taskName, long minutes, long sessionTime,\n DesktopList desktops, TaskView *parent)\n : QObject(), QListViewItem(parent)\n{\n init(taskName, minutes, sessionTime, desktops, 0);\n}\n\nTask::Task( const QString& taskName, long minutes, long sessionTime,\n DesktopList desktops, Task *parent)\n : QObject(), QListViewItem(parent)\n{\n init(taskName, minutes, sessionTime, desktops, 0);\n}\n\nTask::Task( KCal::Todo* todo, TaskView* parent )\n : QObject(), QListViewItem( parent )\n{\n long minutes = 0;\n QString name;\n long sessionTime = 0;\n int percent_complete = 0;\n DesktopList desktops;\n\n parseIncidence(todo, minutes, sessionTime, name, desktops, percent_complete);\n init(name, minutes, sessionTime, desktops, percent_complete);\n}\n\nvoid Task::init( const QString& taskName, long minutes, long sessionTime,\n DesktopList desktops, int percent_complete)\n{\n \/\/ If our parent is the taskview then connect our totalTimesChanged\n \/\/ signal to its receiver\n if ( ! parent() )\n connect( this, SIGNAL( totalTimesChanged ( long, long ) ),\n listView(), SLOT( taskTotalTimesChanged( long, long) ));\n\n connect( this, SIGNAL( deletingTask( Task* ) ),\n listView(), SLOT( deletingTask( Task* ) ));\n\n if (icons == 0) {\n icons = new QPtrVector<QPixmap>(8);\n for (int i=0; i<8; i++)\n {\n QPixmap *icon = new QPixmap();\n QString name;\n name.sprintf(\"watch-%d.xpm\",i);\n *icon = UserIcon(name);\n icons->insert(i,icon);\n }\n }\n\n \/\/kdDebug(5970) << \"Task::init(\" << taskName << \", \" << minutes << \", \"\n \/\/ << sessionTime << \", desktops)\" << endl;\n\n _name = taskName.stripWhiteSpace();\n _lastStart = QDateTime::currentDateTime();\n _totalTime = _time = minutes;\n _totalSessionTime = _sessionTime = sessionTime;\n _timer = new QTimer(this);\n _desktops = desktops;\n connect(_timer, SIGNAL(timeout()), this, SLOT(updateActiveIcon()));\n setPixmap(1, UserIcon(QString::fromLatin1(\"empty-watch.xpm\")));\n _currentPic = 0;\n _percentcomplete = percent_complete;\n\n update();\n changeParentTotalTimes( _sessionTime, _time);\n}\n\nTask::~Task() {\n emit deletingTask(this);\n delete _timer;\n}\n\nvoid Task::setRunning( bool on, KarmStorage* storage )\n{\n if ( on ) {\n if (!_timer->isActive()) {\n _timer->start(1000);\n storage->startTimer(this);\n _currentPic=7;\n _lastStart = QDateTime::currentDateTime();\n updateActiveIcon();\n }\n }\n else {\n if (_timer->isActive()) {\n _timer->stop();\n storage->stopTimer(this);\n setPixmap(1, UserIcon(QString::fromLatin1(\"empty-watch.xpm\")));\n }\n }\n}\n\nvoid Task::setUid(QString uid) {\n _uid = uid;\n}\n\nbool Task::isRunning() const\n{\n return _timer->isActive();\n}\n\nvoid Task::setName( const QString& name, KarmStorage* storage )\n{\n kdDebug(5970) << \"Task:setName: \" << name << endl;\n\n QString oldname = _name;\n if ( oldname != name ) {\n _name = name;\n storage->setName(this, oldname);\n update();\n }\n}\n\nvoid Task::setPercentComplete(const int percent, KarmStorage *storage)\n{\n kdDebug(5970) << \"Task::setPercentComplete(\" << percent << \", storage): \"\n << _uid << endl;\n\n if (isRunning()) setRunning(false, storage);\n\n setEnabled(false);\n setOpen(false);\n\n if (!percent)\n _percentcomplete = 0;\n else if (percent > 100)\n _percentcomplete = 100;\n else if (percent < 0)\n _percentcomplete = 0;\n else\n _percentcomplete = percent;\n\n \/\/ When parent marked as complete, mark all children as complete as well.\n \/\/ Complete tasks are not displayed in the task view, so if a parent is\n \/\/ marked as complete and some of the children are not, then we get an error\n \/\/ message. KArm actually keep chugging along in this case and displays the\n \/\/ child tasks just fine, so an alternative solution is to remove that error\n \/\/ message (from KarmStorage::load). But I think it makes more sense that\n \/\/ if you mark a parent task as complete, then all children should be\n \/\/ complete as well.\n \/\/\n \/\/ This behavior is consistent with KOrganizer (as of 2003-09-24).\n if (_percentcomplete == 100)\n {\n for (Task* child= this->firstChild(); child; child = child->nextSibling())\n child->setPercentComplete(_percentcomplete, storage);\n }\n}\n\nbool Task::isComplete() { return _percentcomplete == 100; }\n\nvoid Task::removeFromView()\n{\n for (Task* child= this->firstChild(); child; child= child->nextSibling())\n child->removeFromView();\n delete this;\n}\n\nvoid Task::setDesktopList ( DesktopList desktopList )\n{\n _desktops = desktopList;\n}\n\nvoid Task::changeTime( long minutes, KarmStorage* storage )\n{\n changeTimes( minutes, minutes, storage); \n}\n\nvoid Task::changeTimes( long minutesSession, long minutes, KarmStorage* storage)\n{\n if( minutesSession != 0 || minutes != 0) \n {\n _sessionTime += minutesSession;\n _time += minutes;\n if ( storage ) storage->changeTime(this, minutes * gSecondsPerMinute);\n changeTotalTimes( minutesSession, minutes );\n }\n}\n\nvoid Task::changeTotalTimes( long minutesSession, long minutes )\n{\n \/\/kdDebug(5970)\n \/\/ << \"Task::changeTotalTimes(\" << minutesSession << \", \"\n \/\/ << minutes << \") for \" << name() << endl;\n\n _totalSessionTime += minutesSession;\n _totalTime += minutes;\n update();\n changeParentTotalTimes( minutesSession, minutes );\n}\n\nvoid Task::resetTimes()\n{\n _totalSessionTime -= _sessionTime;\n _totalTime -= _time;\n changeParentTotalTimes( -_sessionTime, -_time);\n _sessionTime = 0;\n _time = 0;\n update();\n}\n\nvoid Task::changeParentTotalTimes( long minutesSession, long minutes )\n{\n \/\/kdDebug(5970)\n \/\/ << \"Task::changeParentTotalTimes(\" << minutesSession << \", \"\n \/\/ << minutes << \") for \" << name() << endl;\n\n if ( isRoot() )\n emit totalTimesChanged( minutesSession, minutes );\n else\n parent()->changeTotalTimes( minutesSession, minutes );\n}\n\nbool Task::remove( QPtrList<Task>& activeTasks, KarmStorage* storage)\n{\n kdDebug(5970) << \"Task::remove: \" << _name << endl;\n\n bool ok = true;\n\n storage->removeTask(this);\n\n if( isRunning() ) setRunning( false, storage );\n\n for (Task* child = this->firstChild(); child; child = child->nextSibling())\n {\n if (child->isRunning())\n child->setRunning(false, storage);\n child->remove(activeTasks, storage);\n }\n\n changeParentTotalTimes( -_sessionTime, -_time);\n\n return ok;\n}\n\nvoid Task::updateActiveIcon()\n{\n _currentPic = (_currentPic+1) % 8;\n setPixmap(1, *(*icons)[_currentPic]);\n}\n\nQString Task::fullName() const\n{\n if (isRoot())\n return name();\n else\n return parent()->fullName() + QString::fromLatin1(\"\/\") + name();\n}\n\nKCal::Todo* Task::asTodo(KCal::Todo* todo) const\n{\n\n todo->setSummary( name() );\n\n \/\/ Note: if the date start is empty, the KOrganizer GUI will have the\n \/\/ checkbox blank, but will prefill the todo's starting datetime to the\n \/\/ time the file is opened.\n \/\/ todo->setDtStart( current );\n\n todo->setCustomProperty( kapp->instanceName(),\n QCString( \"totalTaskTime\" ), QString::number( _time ) );\n todo->setCustomProperty( kapp->instanceName(),\n QCString( \"totalSessionTime\" ), QString::number( _sessionTime) );\n\n if (getDesktopStr().isEmpty())\n todo->removeCustomProperty(kapp->instanceName(), QCString(\"desktopList\"));\n else\n todo->setCustomProperty( kapp->instanceName(),\n QCString( \"desktopList\" ), getDesktopStr() );\n\n todo->setOrganizer( Preferences::instance()->userRealName() );\n\n todo->setPercentComplete(_percentcomplete);\n\n return todo;\n}\n\nbool Task::parseIncidence( KCal::Incidence* incident, long& minutes,\n long& sessionMinutes, QString& name, DesktopList& desktops,\n int& percent_complete )\n{\n bool ok;\n\n name = incident->summary();\n _uid = incident->uid();\n\n _comment = incident->description();\n\n ok = false;\n minutes = incident->customProperty( kapp->instanceName(),\n QCString( \"totalTaskTime\" )).toInt( &ok );\n if ( !ok )\n minutes = 0;\n\n ok = false;\n sessionMinutes = incident->customProperty( kapp->instanceName(),\n QCString( \"totalSessionTime\" )).toInt( &ok );\n if ( !ok )\n sessionMinutes = 0;\n\n QString desktopList = incident->customProperty( kapp->instanceName(),\n QCString( \"desktopList\" ) );\n QStringList desktopStrList = QStringList::split( QString::fromLatin1(\",\"),\n desktopList );\n desktops.clear();\n\n for ( QStringList::iterator iter = desktopStrList.begin();\n iter != desktopStrList.end();\n ++iter ) {\n int desktopInt = (*iter).toInt( &ok );\n if ( ok ) {\n desktops.push_back( desktopInt );\n }\n }\n\n percent_complete = static_cast<KCal::Todo*>(incident)->percentComplete();\n\n \/\/kdDebug(5970) << \"Task::parseIncidence: \"\n \/\/ << name << \", Minutes: \" << minutes\n \/\/ << \", desktop: \" << desktopList << endl;\n\n return true;\n}\n\nQString Task::getDesktopStr() const\n{\n if ( _desktops.empty() )\n return QString();\n\n QString desktopstr;\n for ( DesktopList::const_iterator iter = _desktops.begin();\n iter != _desktops.end();\n ++iter ) {\n desktopstr += QString::number( *iter ) + QString::fromLatin1( \",\" );\n }\n desktopstr.remove( desktopstr.length() - 1, 1 );\n return desktopstr;\n}\n\nvoid Task::cut()\n{\n \/\/kdDebug(5970) << \"Task::cut - \" << name() << endl;\n changeParentTotalTimes( -_totalSessionTime, -_totalTime);\n if ( ! parent())\n listView()->takeItem(this);\n else\n parent()->takeItem(this);\n}\n\nvoid Task::move(Task* destination)\n{\n cut();\n paste(destination);\n}\n\nvoid Task::paste(Task* destination)\n{\n destination->insertItem(this);\n changeParentTotalTimes( _totalSessionTime, _totalTime);\n}\n\nvoid Task::update()\n{\n setText(0, _name);\n setText(1, formatTime(_sessionTime));\n setText(2, formatTime(_time));\n setText(3, formatTime(_totalSessionTime));\n setText(4, formatTime(_totalTime));\n}\n\nvoid Task::addComment( QString comment, KarmStorage* storage )\n{\n _comment = _comment + QString::fromLatin1(\"\\n\") + comment;\n storage->addComment(this, comment);\n}\n\nQString Task::comment() const\n{\n return _comment;\n}\n\nint Task::compare ( QListViewItem * i, int col, bool ascending ) const\n{\n long thistime = 0;\n long thattime = 0;\n Task *task = static_cast<Task*>(i);\n\n switch ( col )\n {\n case 1: \n thistime = _sessionTime;\n thattime = task->sessionTime();\n break;\n case 2:\n thistime = _time;\n thattime = task->time();\n break;\n case 3:\n thistime = _totalSessionTime;\n thattime = task->totalSessionTime();\n break;\n case 4:\n thistime = _totalTime;\n thattime = task->totalTime();\n break;\n default:\n return key(col, ascending).localeAwareCompare( i->key(col, ascending) );\n }\n\n if ( thistime < thattime ) return -1;\n if ( thistime > thattime ) return 1;\n return 0;\n\n}\n\n#include \"task.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"NodeSpotify.h\"\n#include \"..\/..\/Application.h\"\n#include \"..\/..\/exceptions.h\"\n#include \"..\/..\/common_macros.h\"\n#include \"..\/..\/callbacks\/SessionCallbacks.h\"\n#include \"..\/spotify\/SpotifyOptions.h\"\n#include \"NodePlaylist.h\"\n#include \"NodePlaylistFolder.h\"\n#include \"NodePlaylistContainer.h\"\n#include \"NodePlayer.h\"\n#include \"NodeArtist.h\"\n#include \"NodeAlbum.h\"\n#include \"NodeTrack.h\"\n#include \"NodeUser.h\"\n#include \"..\/..\/utils\/V8Utils.h\"\n\nextern Application* application;\n\nNodeSpotify::NodeSpotify(Handle<Object> options) {\n \/*\n * Important note: The session callbacks must be initialized before\n * the sp_session is started. The uv timer and async handle must be set up\n * as they will be used as soon as the sp_session is created, which happens in the\n * NodeSpotify ctor.\n *\/\n \/\/initiate uv_timer and uv_async\n SessionCallbacks::init();\n\n SpotifyOptions _options;\n HandleScope scope;\n Handle<String> settingsFolderKey = String::New(\"settingsFolder\");\n Handle<String> cacheFolderKey = String::New(\"cacheFolder\");\n Handle<String> traceFileKey = String::New(\"traceFile\");\n Handle<String> appkeyFileKey = String::New(\"appkeyFile\");\n if(options->Has(settingsFolderKey)) {\n String::Utf8Value settingsFolderValue(options->Get(settingsFolderKey)->ToString());\n _options.settingsFolder = *settingsFolderValue;\n } else {\n _options.settingsFolder = \"settings\";\n }\n if(options->Has(cacheFolderKey)) {\n String::Utf8Value cacheFolderValue(options->Get(cacheFolderKey)->ToString());\n _options.cacheFolder = *cacheFolderValue;\n } else {\n _options.cacheFolder = \"cache\";\n }\n if(options->Has(traceFileKey)) {\n String::Utf8Value traceFileValue(options->Get(traceFileKey)->ToString());\n _options.traceFile = *traceFileValue;\n }\n if(options->Has(appkeyFileKey)) {\n String::Utf8Value appkeyFileValue(options->Get(appkeyFileKey)->ToString());\n _options.appkeyFile = *appkeyFileValue;\n }\n spotify = std::unique_ptr<Spotify>(new Spotify(_options));\n scope.Close(Undefined());\n}\n\nNodeSpotify::~NodeSpotify() {\n\n}\n\nHandle<Value> NodeSpotify::createFromLink(const Arguments& args) {\n HandleScope scope;\n Handle<Value> out;\n String::Utf8Value linkToParse(args[0]->ToString());\n sp_link* parsedLink = sp_link_create_from_string(*linkToParse);\n if(parsedLink != nullptr) {\n sp_linktype linkType = sp_link_type(parsedLink);\n switch(linkType) {\n case SP_LINKTYPE_TRACK:\n {\n sp_track* track = sp_link_as_track(parsedLink);\n NodeTrack* nodeTrack = new NodeTrack(std::make_shared<Track>(track));\n out = nodeTrack->getV8Object();\n break;\n }\n case SP_LINKTYPE_ALBUM:\n {\n sp_album* album = sp_link_as_album(parsedLink);\n NodeAlbum* nodeAlbum = new NodeAlbum(std::make_shared<Album>(album));\n out = nodeAlbum->getV8Object();\n break;\n }\n case SP_LINKTYPE_ARTIST:\n {\n sp_artist* artist = sp_link_as_artist(parsedLink);\n NodeArtist* nodeArtist = new NodeArtist(std::make_shared<Artist>(artist));\n out = nodeArtist->getV8Object();\n break;\n }\n case SP_LINKTYPE_PROFILE:\n {\n sp_user* user = sp_link_as_user(parsedLink);\n NodeUser* nodeUser = new NodeUser(std::make_shared<User>(user));\n out = nodeUser->getV8Object();\n break;\n }\n case SP_LINKTYPE_PLAYLIST:\n {\n sp_playlist* spPlaylist = sp_playlist_create(application->session, parsedLink);\n auto playlist = Playlist::fromCache(spPlaylist);\n NodePlaylist* nodePlaylist = new NodePlaylist(playlist);\n out = nodePlaylist->getV8Object();\n break;\n }\n default:\n out = Undefined();\n }\n sp_link_release(parsedLink);\n } else {\n out = Undefined();\n }\n return scope.Close(out);\n}\n\nHandle<Value> NodeSpotify::login(const Arguments& args) {\n HandleScope scope;\n NodeSpotify* nodeSpotify = node::ObjectWrap::Unwrap<NodeSpotify>(args.This());\n String::Utf8Value v8User(args[0]->ToString());\n String::Utf8Value v8Password(args[1]->ToString());\n bool rememberMe = args[2]->ToBoolean()->Value();\n bool withRemembered = args[3]->ToBoolean()->Value();\n std::string user(*v8User);\n std::string password(*v8Password);\n nodeSpotify->spotify->login(user, password, rememberMe, withRemembered);\n return scope.Close(Undefined());\n}\n\nHandle<Value> NodeSpotify::logout(const Arguments& args) {\n HandleScope scope;\n if(args.Length() > 0) {\n Handle<Function> fun = Handle<Function>::Cast(args[0]);\n Persistent<Function> p = Persistent<Function>::New(fun);\n SessionCallbacks::logoutCallback = p;\n }\n NodeSpotify* nodeSpotify = node::ObjectWrap::Unwrap<NodeSpotify>(args.This());\n nodeSpotify->spotify->logout();\n return scope.Close(Undefined());\n}\n\nHandle<Value> NodeSpotify::getPlaylistContainer(Local<String> property, const AccessorInfo& info) {\n HandleScope scope;\n NodePlaylistContainer* nodePlaylistContainer = new NodePlaylistContainer(application->playlistContainer);\n return scope.Close(nodePlaylistContainer->getV8Object());\n}\n\nHandle<Value> NodeSpotify::getRememberedUser(Local<String> property, const AccessorInfo& info) {\n HandleScope scope;\n NodeSpotify* nodeSpotify = node::ObjectWrap::Unwrap<NodeSpotify>(info.Holder());\n return scope.Close(String::New(nodeSpotify->spotify->rememberedUser().c_str()));\n}\n\nHandle<Value> NodeSpotify::getSessionUser(Local<String> property, const AccessorInfo& info) {\n HandleScope scope;\n NodeSpotify* nodeSpotify = node::ObjectWrap::Unwrap<NodeSpotify>(info.Holder());\n NodeUser* nodeUser = new NodeUser(nodeSpotify->spotify->sessionUser());\n return scope.Close(nodeUser->getV8Object());\n}\n\nHandle<Value> NodeSpotify::getConstants(Local<String> property, const AccessorInfo& info) {\n HandleScope scope;\n Local<Object> constants = Object::New();\n constants->Set(String::NewSymbol(\"ARTISTBROWSE_FULL\"), Number::New(SP_ARTISTBROWSE_FULL));\n constants->Set(String::NewSymbol(\"ARTISTBROWSE_NO_TRACKS\"), Number::New(SP_ARTISTBROWSE_NO_TRACKS));\n constants->Set(String::NewSymbol(\"ARTISTBROWSE_NO_ALBUMS\"), Number::New(SP_ARTISTBROWSE_NO_ALBUMS));\n\n constants->Set(String::NewSymbol(\"PLAYLIST_TYPE_PLAYLIST\"), Number::New(SP_PLAYLIST_TYPE_PLAYLIST));\n constants->Set(String::NewSymbol(\"PLAYLIST_TYPE_START_FOLDER\"), Number::New(SP_PLAYLIST_TYPE_START_FOLDER));\n constants->Set(String::NewSymbol(\"PLAYLIST_TYPE_END_FOLDER\"), Number::New(SP_PLAYLIST_TYPE_END_FOLDER));\n return scope.Close(constants);\n}\n\nHandle<Value> NodeSpotify::on(const Arguments& args) {\n HandleScope scope;\n if(args.Length() < 1 || !args[0]->IsObject()) {\n return scope.Close(V8_EXCEPTION(\"on needs an object as its first argument.\"));\n }\n Handle<Object> callbacks = args[0]->ToObject();\n Handle<String> metadataUpdatedKey = String::New(\"metadataUpdated\");\n Handle<String> readyKey = String::New(\"ready\");\n Handle<String> logoutKey = String::New(\"logout\");\n SessionCallbacks::metadataUpdatedCallback = V8Utils::getFunctionFromObject(callbacks, metadataUpdatedKey);\n SessionCallbacks::loginCallback = V8Utils::getFunctionFromObject(callbacks, readyKey);\n SessionCallbacks::logoutCallback = V8Utils::getFunctionFromObject(callbacks, logoutKey);\n return scope.Close(Undefined());\n}\n\nvoid NodeSpotify::init() {\n HandleScope scope;\n Handle<FunctionTemplate> constructorTemplate = NodeWrapped::init(\"Spotify\");\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"login\", login);\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"logout\", logout);\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"createFromLink\", createFromLink);\n \/\/Because of the special metadataUpdated callback with convenience functions we provide _on here, will provide \"on\" in spotify.js\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"_on\", on);\n constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol(\"rememberedUser\"), getRememberedUser);\n constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol(\"sessionUser\"), getSessionUser);\n constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol(\"playlistContainer\"), getPlaylistContainer);\n constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol(\"constants\"), getConstants);\n\n constructor = Persistent<Function>::New(constructorTemplate->GetFunction());\n scope.Close(Undefined());\n}\n<commit_msg>PLAYLIST_TYPE_PLACEHOLDER constant<commit_after>#include \"NodeSpotify.h\"\n#include \"..\/..\/Application.h\"\n#include \"..\/..\/exceptions.h\"\n#include \"..\/..\/common_macros.h\"\n#include \"..\/..\/callbacks\/SessionCallbacks.h\"\n#include \"..\/spotify\/SpotifyOptions.h\"\n#include \"NodePlaylist.h\"\n#include \"NodePlaylistFolder.h\"\n#include \"NodePlaylistContainer.h\"\n#include \"NodePlayer.h\"\n#include \"NodeArtist.h\"\n#include \"NodeAlbum.h\"\n#include \"NodeTrack.h\"\n#include \"NodeUser.h\"\n#include \"..\/..\/utils\/V8Utils.h\"\n\nextern Application* application;\n\nNodeSpotify::NodeSpotify(Handle<Object> options) {\n \/*\n * Important note: The session callbacks must be initialized before\n * the sp_session is started. The uv timer and async handle must be set up\n * as they will be used as soon as the sp_session is created, which happens in the\n * NodeSpotify ctor.\n *\/\n \/\/initiate uv_timer and uv_async\n SessionCallbacks::init();\n\n SpotifyOptions _options;\n HandleScope scope;\n Handle<String> settingsFolderKey = String::New(\"settingsFolder\");\n Handle<String> cacheFolderKey = String::New(\"cacheFolder\");\n Handle<String> traceFileKey = String::New(\"traceFile\");\n Handle<String> appkeyFileKey = String::New(\"appkeyFile\");\n if(options->Has(settingsFolderKey)) {\n String::Utf8Value settingsFolderValue(options->Get(settingsFolderKey)->ToString());\n _options.settingsFolder = *settingsFolderValue;\n } else {\n _options.settingsFolder = \"settings\";\n }\n if(options->Has(cacheFolderKey)) {\n String::Utf8Value cacheFolderValue(options->Get(cacheFolderKey)->ToString());\n _options.cacheFolder = *cacheFolderValue;\n } else {\n _options.cacheFolder = \"cache\";\n }\n if(options->Has(traceFileKey)) {\n String::Utf8Value traceFileValue(options->Get(traceFileKey)->ToString());\n _options.traceFile = *traceFileValue;\n }\n if(options->Has(appkeyFileKey)) {\n String::Utf8Value appkeyFileValue(options->Get(appkeyFileKey)->ToString());\n _options.appkeyFile = *appkeyFileValue;\n }\n spotify = std::unique_ptr<Spotify>(new Spotify(_options));\n scope.Close(Undefined());\n}\n\nNodeSpotify::~NodeSpotify() {\n\n}\n\nHandle<Value> NodeSpotify::createFromLink(const Arguments& args) {\n HandleScope scope;\n Handle<Value> out;\n String::Utf8Value linkToParse(args[0]->ToString());\n sp_link* parsedLink = sp_link_create_from_string(*linkToParse);\n if(parsedLink != nullptr) {\n sp_linktype linkType = sp_link_type(parsedLink);\n switch(linkType) {\n case SP_LINKTYPE_TRACK:\n {\n sp_track* track = sp_link_as_track(parsedLink);\n NodeTrack* nodeTrack = new NodeTrack(std::make_shared<Track>(track));\n out = nodeTrack->getV8Object();\n break;\n }\n case SP_LINKTYPE_ALBUM:\n {\n sp_album* album = sp_link_as_album(parsedLink);\n NodeAlbum* nodeAlbum = new NodeAlbum(std::make_shared<Album>(album));\n out = nodeAlbum->getV8Object();\n break;\n }\n case SP_LINKTYPE_ARTIST:\n {\n sp_artist* artist = sp_link_as_artist(parsedLink);\n NodeArtist* nodeArtist = new NodeArtist(std::make_shared<Artist>(artist));\n out = nodeArtist->getV8Object();\n break;\n }\n case SP_LINKTYPE_PROFILE:\n {\n sp_user* user = sp_link_as_user(parsedLink);\n NodeUser* nodeUser = new NodeUser(std::make_shared<User>(user));\n out = nodeUser->getV8Object();\n break;\n }\n case SP_LINKTYPE_PLAYLIST:\n {\n sp_playlist* spPlaylist = sp_playlist_create(application->session, parsedLink);\n auto playlist = Playlist::fromCache(spPlaylist);\n NodePlaylist* nodePlaylist = new NodePlaylist(playlist);\n out = nodePlaylist->getV8Object();\n break;\n }\n default:\n out = Undefined();\n }\n sp_link_release(parsedLink);\n } else {\n out = Undefined();\n }\n return scope.Close(out);\n}\n\nHandle<Value> NodeSpotify::login(const Arguments& args) {\n HandleScope scope;\n NodeSpotify* nodeSpotify = node::ObjectWrap::Unwrap<NodeSpotify>(args.This());\n String::Utf8Value v8User(args[0]->ToString());\n String::Utf8Value v8Password(args[1]->ToString());\n bool rememberMe = args[2]->ToBoolean()->Value();\n bool withRemembered = args[3]->ToBoolean()->Value();\n std::string user(*v8User);\n std::string password(*v8Password);\n nodeSpotify->spotify->login(user, password, rememberMe, withRemembered);\n return scope.Close(Undefined());\n}\n\nHandle<Value> NodeSpotify::logout(const Arguments& args) {\n HandleScope scope;\n if(args.Length() > 0) {\n Handle<Function> fun = Handle<Function>::Cast(args[0]);\n Persistent<Function> p = Persistent<Function>::New(fun);\n SessionCallbacks::logoutCallback = p;\n }\n NodeSpotify* nodeSpotify = node::ObjectWrap::Unwrap<NodeSpotify>(args.This());\n nodeSpotify->spotify->logout();\n return scope.Close(Undefined());\n}\n\nHandle<Value> NodeSpotify::getPlaylistContainer(Local<String> property, const AccessorInfo& info) {\n HandleScope scope;\n NodePlaylistContainer* nodePlaylistContainer = new NodePlaylistContainer(application->playlistContainer);\n return scope.Close(nodePlaylistContainer->getV8Object());\n}\n\nHandle<Value> NodeSpotify::getRememberedUser(Local<String> property, const AccessorInfo& info) {\n HandleScope scope;\n NodeSpotify* nodeSpotify = node::ObjectWrap::Unwrap<NodeSpotify>(info.Holder());\n return scope.Close(String::New(nodeSpotify->spotify->rememberedUser().c_str()));\n}\n\nHandle<Value> NodeSpotify::getSessionUser(Local<String> property, const AccessorInfo& info) {\n HandleScope scope;\n NodeSpotify* nodeSpotify = node::ObjectWrap::Unwrap<NodeSpotify>(info.Holder());\n NodeUser* nodeUser = new NodeUser(nodeSpotify->spotify->sessionUser());\n return scope.Close(nodeUser->getV8Object());\n}\n\nHandle<Value> NodeSpotify::getConstants(Local<String> property, const AccessorInfo& info) {\n HandleScope scope;\n Local<Object> constants = Object::New();\n constants->Set(String::NewSymbol(\"ARTISTBROWSE_FULL\"), Number::New(SP_ARTISTBROWSE_FULL));\n constants->Set(String::NewSymbol(\"ARTISTBROWSE_NO_TRACKS\"), Number::New(SP_ARTISTBROWSE_NO_TRACKS));\n constants->Set(String::NewSymbol(\"ARTISTBROWSE_NO_ALBUMS\"), Number::New(SP_ARTISTBROWSE_NO_ALBUMS));\n\n constants->Set(String::NewSymbol(\"PLAYLIST_TYPE_PLAYLIST\"), Number::New(SP_PLAYLIST_TYPE_PLAYLIST));\n constants->Set(String::NewSymbol(\"PLAYLIST_TYPE_START_FOLDER\"), Number::New(SP_PLAYLIST_TYPE_START_FOLDER));\n constants->Set(String::NewSymbol(\"PLAYLIST_TYPE_END_FOLDER\"), Number::New(SP_PLAYLIST_TYPE_END_FOLDER));\n constants->Set(String::NewSymbol(\"PLAYLIST_TYPE_PLACEHOLDER\"), Number::New(SP_PLAYLIST_TYPE_PLACEHOLDER));\n return scope.Close(constants);\n}\n\nHandle<Value> NodeSpotify::on(const Arguments& args) {\n HandleScope scope;\n if(args.Length() < 1 || !args[0]->IsObject()) {\n return scope.Close(V8_EXCEPTION(\"on needs an object as its first argument.\"));\n }\n Handle<Object> callbacks = args[0]->ToObject();\n Handle<String> metadataUpdatedKey = String::New(\"metadataUpdated\");\n Handle<String> readyKey = String::New(\"ready\");\n Handle<String> logoutKey = String::New(\"logout\");\n SessionCallbacks::metadataUpdatedCallback = V8Utils::getFunctionFromObject(callbacks, metadataUpdatedKey);\n SessionCallbacks::loginCallback = V8Utils::getFunctionFromObject(callbacks, readyKey);\n SessionCallbacks::logoutCallback = V8Utils::getFunctionFromObject(callbacks, logoutKey);\n return scope.Close(Undefined());\n}\n\nvoid NodeSpotify::init() {\n HandleScope scope;\n Handle<FunctionTemplate> constructorTemplate = NodeWrapped::init(\"Spotify\");\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"login\", login);\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"logout\", logout);\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"createFromLink\", createFromLink);\n \/\/Because of the special metadataUpdated callback with convenience functions we provide _on here, will provide \"on\" in spotify.js\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"_on\", on);\n constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol(\"rememberedUser\"), getRememberedUser);\n constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol(\"sessionUser\"), getSessionUser);\n constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol(\"playlistContainer\"), getPlaylistContainer);\n constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol(\"constants\"), getConstants);\n\n constructor = Persistent<Function>::New(constructorTemplate->GetFunction());\n scope.Close(Undefined());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra\n *\n * This file is part of Essentia\n *\n * Essentia is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License as published by the Free\n * Software Foundation (FSF), either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the Affero GNU General Public License\n * version 3 along with this program. If not, see http:\/\/www.gnu.org\/licenses\/\n *\/\n\n#include \"chordsdetection.h\"\n#include \"essentiamath.h\"\n\nusing namespace std;\n\nnamespace essentia {\nnamespace standard {\n\nconst char* ChordsDetection::name = \"ChordsDetection\";\nconst char* ChordsDetection::category = \"Tonal\";\nconst char* ChordsDetection::description = DOC(\"This algorithm estimates chords using pitch profile classes. It finds the best matching major or minor triad and outputs the result as a string (e.g. A#, Bm, G#m, C). This algorithm uses the Sharp versions of each Flatted note (i.e. Bb -> A#).\\n\"\n\"\\n\"\n\"Note:\\n\"\n\" - This algorithm assumes that input pcps have been computed with framesize = 2*hopsize\\n\"\n\"\\n\"\n\"Quality: experimental (prone to errors, algorithm needs improvement)\\n\"\n\"\\n\"\n\"References:\\n\"\n\" [1] E. Gómez, \\\"Tonal Description of Polyphonic Audio for Music Content\\n\"\n\" Processing,\\\" INFORMS Journal on Computing, vol. 18, no. 3, pp. 294–304,\\n\"\n\" 2006.\\n\\n\"\n\" [2] D. Temperley, \\\"What's key for key? The Krumhansl-Schmuckler\\n\"\n\" key-finding algorithm reconsidered\\\", Music Perception vol. 17, no. 1,\\n\"\n\" pp. 65-100, 1999.\");\n\nvoid ChordsDetection::configure() {\n Real wsize = parameter(\"windowSize\").toReal();\n Real sampleRate = parameter(\"sampleRate\").toReal();\n int hopSize = parameter(\"hopSize\").toInt();\n\n \/\/ NB: this assumes that frameSize = hopSize * 2, so that we don't have to\n \/\/ require frameSize as well as parameter.\n _numFramesWindow = int((wsize * sampleRate) \/ hopSize) - 1;\n}\n\nvoid ChordsDetection::compute() {\n const vector<vector<Real> >& hpcp = _pcp.get();\n vector<string>& chords= _chords.get();\n vector<Real>& strength= _strength.get();\n\n string key;\n string scale;\n Real firstToSecondRelativeStrength;\n Real str; \/\/ strength\n\n chords.reserve(int(hpcp.size()\/_numFramesWindow));\n strength.reserve(int(hpcp.size()\/_numFramesWindow));\n\n for (int i=0; i<int(hpcp.size()); ++i) {\n\n int indexStart = max(0, i - _numFramesWindow\/2);\n int indexEnd = min(i + _numFramesWindow\/2, (int)hpcp.size());\n\n vector<Real> hpcpAverage = meanFrames(hpcp, indexStart, indexEnd);\n normalize(hpcpAverage);\n\n _chordsAlgo->input(\"pcp\").set(hpcpAverage);\n _chordsAlgo->output(\"key\").set(key);\n _chordsAlgo->output(\"scale\").set(scale);\n _chordsAlgo->output(\"strength\").set(str);\n _chordsAlgo->output(\"firstToSecondRelativeStrength\").set(firstToSecondRelativeStrength);\n _chordsAlgo->compute();\n\n if (scale == \"minor\") {\n chords.push_back(key + 'm');\n }\n else {\n chords.push_back(key);\n }\n\n strength.push_back(str);\n\n }\n}\n\n} \/\/ namespace standard\n} \/\/ namespace essentia\n\n\n#include \"poolstorage.h\"\n\nnamespace essentia {\nnamespace streaming {\n\nconst char* ChordsDetection::name = standard::ChordsDetection::name;\nconst char* ChordsDetection::description = standard::ChordsDetection::description;\n\nChordsDetection::ChordsDetection() : AlgorithmComposite() {\n\n declareInput(_pcp, \"pcp\", \"the pitch class profile from which to detect the chord\");\n declareOutput(_chords, 1, \"chords\", \"the resulting chords, from A to G\");\n declareOutput(_strength, 1, \"strength\", \"the strength of the chord\");\n\n _chordsAlgo = standard::AlgorithmFactory::create(\"Key\");\n _chordsAlgo->configure(\"profileType\", \"tonictriad\", \"usePolyphony\", false);\n _poolStorage = new PoolStorage<vector<Real> >(&_pool, \"internal.hpcp\");\n\n \/\/ FIXME: this is just a temporary hack...\n \/\/ the correct way to do this is to have the algorithm output the chords\n \/\/ continuously while processing, which requires a FrameCutter for vectors\n \/\/ Need to set the buffer type to multiple frames as all the chords\n \/\/ are output all at once\n _chords.setBufferType(BufferUsage::forMultipleFrames);\n _strength.setBufferType(BufferUsage::forMultipleFrames);\n\n attach(_pcp, _poolStorage->input(\"data\"));\n}\n\nChordsDetection::~ChordsDetection() {\n delete _chordsAlgo;\n delete _poolStorage;\n}\n\nvoid ChordsDetection::configure() {\n Real wsize = parameter(\"windowSize\").toReal();\n Real sampleRate = parameter(\"sampleRate\").toReal();\n int hopSize = parameter(\"hopSize\").toInt();\n\n \/\/ NB: this assumes that frameSize = hopSize * 2, so that we don't have to\n \/\/ require frameSize as well as parameter.\n _numFramesWindow = int((wsize * sampleRate) \/ hopSize) - 1;\n}\n\nAlgorithmStatus ChordsDetection::process() {\n if (!shouldStop()) return PASS;\n\n const vector<vector<Real> >& hpcp = _pool.value<vector<vector<Real> > >(\"internal.hpcp\");\n string key;\n string scale;\n Real strength;\n Real firstToSecondRelativeStrength;\n\n \/\/ This is very strange, because we jump by a single frame each time, not by\n \/\/ the defined windowSize. Is that the expected behavior or is it a bug?\n \/\/ eaylon: windowSize is not intended for advancing, but for searching\n \/\/ nwack: maybe it could be a smart idea to jump from 1 beat to another instead\n \/\/ of a fixed amount a time (arbitrary frame size)\n\n for (int i=0; i<(int)hpcp.size(); i++) {\n\n int indexStart = max(0, i - _numFramesWindow\/2);\n int indexEnd = min(i + _numFramesWindow\/2, (int)hpcp.size());\n\n vector<Real> hpcpAverage = meanFrames(hpcp, indexStart, indexEnd);\n normalize(hpcpAverage);\n\n _chordsAlgo->input(\"pcp\").set(hpcpAverage);\n _chordsAlgo->output(\"key\").set(key);\n _chordsAlgo->output(\"scale\").set(scale);\n _chordsAlgo->output(\"strength\").set(strength);\n _chordsAlgo->output(\"firstToSecondRelativeStrength\").set(firstToSecondRelativeStrength);\n _chordsAlgo->compute();\n\n if (scale == \"minor\") {\n _chords.push(key + 'm');\n }\n else {\n _chords.push(key);\n }\n\n _strength.push(strength);\n }\n\n return FINISHED;\n}\n\nvoid ChordsDetection::reset() {\n AlgorithmComposite::reset();\n _chordsAlgo->reset();\n}\n\n\n} \/\/ namespace streaming\n} \/\/ namespace essentia\n<commit_msg>Improve documentation for the ChordsDetection algo<commit_after>\/*\n * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra\n *\n * This file is part of Essentia\n *\n * Essentia is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License as published by the Free\n * Software Foundation (FSF), either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the Affero GNU General Public License\n * version 3 along with this program. If not, see http:\/\/www.gnu.org\/licenses\/\n *\/\n\n#include \"chordsdetection.h\"\n#include \"essentiamath.h\"\n\nusing namespace std;\n\nnamespace essentia {\nnamespace standard {\n\nconst char* ChordsDetection::name = \"ChordsDetection\";\nconst char* ChordsDetection::category = \"Tonal\";\nconst char* ChordsDetection::description = DOC(\"This algorithm estimates chords given an input sequence of harmonic pitch class profiles (HPCPs). It finds the best matching major or minor triad and outputs the result as a string (e.g. A#, Bm, G#m, C). This algorithm uses the Sharp versions of each Flatted note (i.e. Bb -> A#).\\n\"\n\"\\n\"\n\"Note:\\n\"\n\" - The algorithm assumes that the sequence of the input HPCP frames has been computed with framesize = 2*hopsize\\n\"\n\" - The algorithm estimates a sequence of chord values corresponding to the input HPCP frames (one chord value for each frame, estimated using a temporal window of HPCPs centered at that frame).\\n\"\n\"\\n\"\n\"Quality: experimental (prone to errors, algorithm needs improvement)\\n\"\n\"\\n\"\n\"References:\\n\"\n\" [1] E. Gómez, \\\"Tonal Description of Polyphonic Audio for Music Content\\n\"\n\" Processing,\\\" INFORMS Journal on Computing, vol. 18, no. 3, pp. 294–304,\\n\"\n\" 2006.\\n\\n\"\n\" [2] D. Temperley, \\\"What's key for key? The Krumhansl-Schmuckler\\n\"\n\" key-finding algorithm reconsidered\\\", Music Perception vol. 17, no. 1,\\n\"\n\" pp. 65-100, 1999.\");\n\nvoid ChordsDetection::configure() {\n Real wsize = parameter(\"windowSize\").toReal();\n Real sampleRate = parameter(\"sampleRate\").toReal();\n int hopSize = parameter(\"hopSize\").toInt();\n\n \/\/ NB: this assumes that frameSize = hopSize * 2, so that we don't have to\n \/\/ require frameSize as well as parameter.\n _numFramesWindow = int((wsize * sampleRate) \/ hopSize) - 1;\n}\n\nvoid ChordsDetection::compute() {\n const vector<vector<Real> >& hpcp = _pcp.get();\n vector<string>& chords= _chords.get();\n vector<Real>& strength= _strength.get();\n\n string key;\n string scale;\n Real firstToSecondRelativeStrength;\n Real str; \/\/ strength\n\n chords.reserve(int(hpcp.size()\/_numFramesWindow));\n strength.reserve(int(hpcp.size()\/_numFramesWindow));\n\n for (int i=0; i<int(hpcp.size()); ++i) {\n\n int indexStart = max(0, i - _numFramesWindow\/2);\n int indexEnd = min(i + _numFramesWindow\/2, (int)hpcp.size());\n\n vector<Real> hpcpAverage = meanFrames(hpcp, indexStart, indexEnd);\n normalize(hpcpAverage);\n\n _chordsAlgo->input(\"pcp\").set(hpcpAverage);\n _chordsAlgo->output(\"key\").set(key);\n _chordsAlgo->output(\"scale\").set(scale);\n _chordsAlgo->output(\"strength\").set(str);\n _chordsAlgo->output(\"firstToSecondRelativeStrength\").set(firstToSecondRelativeStrength);\n _chordsAlgo->compute();\n\n if (scale == \"minor\") {\n chords.push_back(key + 'm');\n }\n else {\n chords.push_back(key);\n }\n\n strength.push_back(str);\n\n }\n}\n\n} \/\/ namespace standard\n} \/\/ namespace essentia\n\n\n#include \"poolstorage.h\"\n\nnamespace essentia {\nnamespace streaming {\n\nconst char* ChordsDetection::name = standard::ChordsDetection::name;\nconst char* ChordsDetection::description = standard::ChordsDetection::description;\n\nChordsDetection::ChordsDetection() : AlgorithmComposite() {\n\n declareInput(_pcp, \"pcp\", \"the pitch class profile from which to detect the chord\");\n declareOutput(_chords, 1, \"chords\", \"the resulting chords, from A to G\");\n declareOutput(_strength, 1, \"strength\", \"the strength of the chord\");\n\n _chordsAlgo = standard::AlgorithmFactory::create(\"Key\");\n _chordsAlgo->configure(\"profileType\", \"tonictriad\", \"usePolyphony\", false);\n _poolStorage = new PoolStorage<vector<Real> >(&_pool, \"internal.hpcp\");\n\n \/\/ FIXME: this is just a temporary hack...\n \/\/ the correct way to do this is to have the algorithm output the chords\n \/\/ continuously while processing, which requires a FrameCutter for vectors\n \/\/ Need to set the buffer type to multiple frames as all the chords\n \/\/ are output all at once\n _chords.setBufferType(BufferUsage::forMultipleFrames);\n _strength.setBufferType(BufferUsage::forMultipleFrames);\n\n attach(_pcp, _poolStorage->input(\"data\"));\n}\n\nChordsDetection::~ChordsDetection() {\n delete _chordsAlgo;\n delete _poolStorage;\n}\n\nvoid ChordsDetection::configure() {\n Real wsize = parameter(\"windowSize\").toReal();\n Real sampleRate = parameter(\"sampleRate\").toReal();\n int hopSize = parameter(\"hopSize\").toInt();\n\n \/\/ NB: this assumes that frameSize = hopSize * 2, so that we don't have to\n \/\/ require frameSize as well as parameter.\n _numFramesWindow = int((wsize * sampleRate) \/ hopSize) - 1;\n}\n\nAlgorithmStatus ChordsDetection::process() {\n if (!shouldStop()) return PASS;\n\n const vector<vector<Real> >& hpcp = _pool.value<vector<vector<Real> > >(\"internal.hpcp\");\n string key;\n string scale;\n Real strength;\n Real firstToSecondRelativeStrength;\n\n \/\/ This is very strange, because we jump by a single frame each time, not by\n \/\/ the defined windowSize. Is that the expected behavior or is it a bug?\n \/\/ eaylon: windowSize is not intended for advancing, but for searching\n \/\/ nwack: maybe it could be a smart idea to jump from 1 beat to another instead\n \/\/ of a fixed amount a time (arbitrary frame size)\n\n for (int i=0; i<(int)hpcp.size(); i++) {\n\n int indexStart = max(0, i - _numFramesWindow\/2);\n int indexEnd = min(i + _numFramesWindow\/2, (int)hpcp.size());\n\n vector<Real> hpcpAverage = meanFrames(hpcp, indexStart, indexEnd);\n normalize(hpcpAverage);\n\n _chordsAlgo->input(\"pcp\").set(hpcpAverage);\n _chordsAlgo->output(\"key\").set(key);\n _chordsAlgo->output(\"scale\").set(scale);\n _chordsAlgo->output(\"strength\").set(strength);\n _chordsAlgo->output(\"firstToSecondRelativeStrength\").set(firstToSecondRelativeStrength);\n _chordsAlgo->compute();\n\n if (scale == \"minor\") {\n _chords.push(key + 'm');\n }\n else {\n _chords.push(key);\n }\n\n _strength.push(strength);\n }\n\n return FINISHED;\n}\n\nvoid ChordsDetection::reset() {\n AlgorithmComposite::reset();\n _chordsAlgo->reset();\n}\n\n\n} \/\/ namespace streaming\n} \/\/ namespace essentia\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2012, Zeex\r\n\/\/ All rights reserved.\r\n\/\/\r\n\/\/ Redistribution and use in source and binary forms, with or without\r\n\/\/ modification, are permitted provided that the following conditions are met: \r\n\/\/\r\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this\r\n\/\/ list of conditions and the following disclaimer. \r\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\r\n\/\/ this list of conditions and the following disclaimer in the documentation\r\n\/\/ and\/or other materials provided with the distribution. \r\n\/\/\r\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r\n\/\/ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n\/\/ \/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n#include <algorithm>\r\n#include <cstdio>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#ifdef HAVE_BOOST_DATE_TIME\r\n\t#include <boost\/date_time.hpp>\r\n#endif\r\n#include \"function.h\"\r\n#include \"function_info.h\"\r\n#include \"profile_writer_html.h\"\r\n#include \"performance_counter.h\"\r\n\r\nnamespace amx_profiler {\r\n\r\nProfileWriterHtml::ProfileWriterHtml(std::ostream *stream, const std::string script_name)\r\n\t: stream_(stream)\r\n\t, script_name_(script_name)\r\n{\r\n}\r\n\r\nvoid ProfileWriterHtml::Write(const std::vector<std::shared_ptr<FunctionInfo>> &stats)\r\n{\r\n\t*stream_ <<\r\n\t\"<html>\\n\"\r\n\t\"<head>\\n\"\r\n\t\"\t<title>\" << \"Profile of '\" << script_name_ << \"'<\/title>\\n\"\r\n\t\"<\/head>\\n\"\r\n\t\"<body>\\n\"\r\n\t\"\t<h1>\\n\" <<\r\n\t\"\t\tProfile of '\" << script_name_ << \"'\\n\"\r\n\t\"\t<\/h1>\\n\"\r\n\t\"\t<table id=\\\"stats\\\" class=\\\"tablesorter\\\" border=\\\"1\\\" width=\\\"100%\\\">\\n\"\r\n\t\"\t\t<thead>\\n\"\r\n\t\"\t\t\t<tr>\\n\"\r\n\t\"\t\t\t\t<th>Type<\/th>\\n\"\r\n\t\"\t\t\t\t<th>Name<\/th>\\n\"\r\n\t\"\t\t\t\t<th>Calls<\/th>\\n\"\r\n\t\"\t\t\t\t<th>Self Time<\/th>\\n\"\r\n\t\"\t\t\t\t<th>Total Time<\/th>\\n\"\r\n\t\"\t\t\t<\/tr>\\n\"\r\n\t\"\t\t<\/thead>\\n\"\r\n\t\"\t\t<tbody>\\n\"\r\n\t;\r\n\r\n\tTimeInterval time_all = 0;\r\n\tstd::for_each(stats.begin(), stats.end(), [&](const std::shared_ptr<FunctionInfo> &info) { \r\n\t\ttime_all += info->total_time() - info->child_time(); \r\n\t});\r\n\r\n\tTimeInterval total_time_all = 0;\r\n\tstd::for_each(stats.begin(), stats.end(), [&](const std::shared_ptr<FunctionInfo> &info) { \r\n\t\ttotal_time_all += info->total_time(); \r\n\t});\r\n\r\n\tstd::for_each(stats.begin(), stats.end(), [&](const std::shared_ptr<FunctionInfo> &info) {\r\n\t\t*stream_\r\n\t\t<< \"\t\t<tr>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << info->function()->type() << \"<\/td>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << info->function()->name() << \"<\/td>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << info->num_calls() << \"<\/td>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << std::fixed << std::setprecision(2)\r\n\t\t\t<< static_cast<double>(info->GetSelfTime() * 100) \/ time_all << \"<\/td>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << std::fixed << std::setprecision(2)\r\n\t\t\t<< static_cast<double>(info->total_time() * 100) \/ total_time_all << \"<\/td>\\n\"\r\n\t\t<< \"\t\t<\/tr>\\n\";\r\n\t});\r\n\r\n\t*stream_ <<\r\n\t\"\t\t<\/tbody>\\n\"\r\n\t\"\t<\/table>\\n\"\r\n\t;\r\n\r\n\t*stream_ <<\r\n\t\"\t<script type=\\\"text\/javascript\\\"\\n\"\r\n\t\"\t\tsrc=\\\"http:\/\/code.jquery.com\/jquery-latest.min.js\\\"><\/script>\\n\"\r\n\t\"\t<script type=\\\"text\/javascript\\\"\\n\"\r\n\t\"\t\tsrc=\\\"http:\/\/autobahn.tablesorter.com\/jquery.tablesorter.min.js\\\"><\/script>\\n\"\r\n\t\"\t<script type=\\\"text\/javascript\\\">\\n\"\r\n\t\"\t$(document).ready(function() {\\n\"\r\n\t\"\t\t$(\\\"#stats\\\").tablesorter();\\n\"\r\n\t\"\t});\\n\"\r\n\t\"\t<\/script>\\n\"\r\n\t#ifdef HAVE_BOOST_DATE_TIME\r\n\t\"\t<br\/>\\n\"\r\n\t\"\t<footer>\\n\"\r\n\t\"\t\tGenerated on \" << boost::posix_time::second_clock::local_time() << \"\\n\"\r\n\t\"\t<\/footer>\\n\"\r\n\t#endif\r\n\t\"<\/body>\\n\"\r\n\t\"<\/html>\\n\"\r\n\t;\r\n}\r\n\r\n} \/\/ namespace amx_profiler\r\n<commit_msg>changed the tablesorter URL to one that works<commit_after>\/\/ Copyright (c) 2011-2012, Zeex\r\n\/\/ All rights reserved.\r\n\/\/\r\n\/\/ Redistribution and use in source and binary forms, with or without\r\n\/\/ modification, are permitted provided that the following conditions are met: \r\n\/\/\r\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this\r\n\/\/ list of conditions and the following disclaimer. \r\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\r\n\/\/ this list of conditions and the following disclaimer in the documentation\r\n\/\/ and\/or other materials provided with the distribution. \r\n\/\/\r\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r\n\/\/ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n\/\/ \/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n#include <algorithm>\r\n#include <cstdio>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#ifdef HAVE_BOOST_DATE_TIME\r\n\t#include <boost\/date_time.hpp>\r\n#endif\r\n#include \"function.h\"\r\n#include \"function_info.h\"\r\n#include \"profile_writer_html.h\"\r\n#include \"performance_counter.h\"\r\n\r\nnamespace amx_profiler {\r\n\r\nProfileWriterHtml::ProfileWriterHtml(std::ostream *stream, const std::string script_name)\r\n\t: stream_(stream)\r\n\t, script_name_(script_name)\r\n{\r\n}\r\n\r\nvoid ProfileWriterHtml::Write(const std::vector<std::shared_ptr<FunctionInfo>> &stats)\r\n{\r\n\t*stream_ <<\r\n\t\"<html>\\n\"\r\n\t\"<head>\\n\"\r\n\t\"\t<title>\" << \"Profile of '\" << script_name_ << \"'<\/title>\\n\"\r\n\t\"<\/head>\\n\"\r\n\t\"<body>\\n\"\r\n\t\"\t<h1>\\n\" <<\r\n\t\"\t\tProfile of '\" << script_name_ << \"'\\n\"\r\n\t\"\t<\/h1>\\n\"\r\n\t\"\t<table id=\\\"stats\\\" class=\\\"tablesorter\\\" border=\\\"1\\\" width=\\\"100%\\\">\\n\"\r\n\t\"\t\t<thead>\\n\"\r\n\t\"\t\t\t<tr>\\n\"\r\n\t\"\t\t\t\t<th>Type<\/th>\\n\"\r\n\t\"\t\t\t\t<th>Name<\/th>\\n\"\r\n\t\"\t\t\t\t<th>Calls<\/th>\\n\"\r\n\t\"\t\t\t\t<th>Self Time<\/th>\\n\"\r\n\t\"\t\t\t\t<th>Total Time<\/th>\\n\"\r\n\t\"\t\t\t<\/tr>\\n\"\r\n\t\"\t\t<\/thead>\\n\"\r\n\t\"\t\t<tbody>\\n\"\r\n\t;\r\n\r\n\tTimeInterval time_all = 0;\r\n\tstd::for_each(stats.begin(), stats.end(), [&](const std::shared_ptr<FunctionInfo> &info) { \r\n\t\ttime_all += info->total_time() - info->child_time(); \r\n\t});\r\n\r\n\tTimeInterval total_time_all = 0;\r\n\tstd::for_each(stats.begin(), stats.end(), [&](const std::shared_ptr<FunctionInfo> &info) { \r\n\t\ttotal_time_all += info->total_time(); \r\n\t});\r\n\r\n\tstd::for_each(stats.begin(), stats.end(), [&](const std::shared_ptr<FunctionInfo> &info) {\r\n\t\t*stream_\r\n\t\t<< \"\t\t<tr>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << info->function()->type() << \"<\/td>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << info->function()->name() << \"<\/td>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << info->num_calls() << \"<\/td>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << std::fixed << std::setprecision(2)\r\n\t\t\t<< static_cast<double>(info->GetSelfTime() * 100) \/ time_all << \"<\/td>\\n\"\r\n\t\t<< \"\t\t\t<td>\" << std::fixed << std::setprecision(2)\r\n\t\t\t<< static_cast<double>(info->total_time() * 100) \/ total_time_all << \"<\/td>\\n\"\r\n\t\t<< \"\t\t<\/tr>\\n\";\r\n\t});\r\n\r\n\t*stream_ <<\r\n\t\"\t\t<\/tbody>\\n\"\r\n\t\"\t<\/table>\\n\"\r\n\t;\r\n\r\n\t*stream_ <<\r\n\t\"\t<script type=\\\"text\/javascript\\\"\\n\"\r\n\t\"\t\tsrc=\\\"http:\/\/code.jquery.com\/jquery-latest.min.js\\\"><\/script>\\n\"\r\n\t\"\t<script type=\\\"text\/javascript\\\"\\n\"\r\n\t\"\t\tsrc=\\\"http:\/\/tablesorter.com\/__jquery.tablesorter.min.js\\\"><\/script>\\n\"\r\n\t\"\t<script type=\\\"text\/javascript\\\">\\n\"\r\n\t\"\t$(document).ready(function() {\\n\"\r\n\t\"\t\t$(\\\"#stats\\\").tablesorter();\\n\"\r\n\t\"\t});\\n\"\r\n\t\"\t<\/script>\\n\"\r\n\t#ifdef HAVE_BOOST_DATE_TIME\r\n\t\"\t<br\/>\\n\"\r\n\t\"\t<footer>\\n\"\r\n\t\"\t\tGenerated on \" << boost::posix_time::second_clock::local_time() << \"\\n\"\r\n\t\"\t<\/footer>\\n\"\r\n\t#endif\r\n\t\"<\/body>\\n\"\r\n\t\"<\/html>\\n\"\r\n\t;\r\n}\r\n\r\n} \/\/ namespace amx_profiler\r\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_MATCHING_METRIC_H\n#define OPENMVG_MATCHING_METRIC_H\n\n#include \"openMVG\/matching\/metric_hamming.hpp\"\n#include \"openMVG\/numeric\/accumulator_trait.hpp\"\n#include <cstddef>\n\nnamespace openMVG {\nnamespace matching {\n\n\/\/\/ Squared Euclidean distance functor.\ntemplate<class T>\nstruct L2_Simple\n{\n typedef T ElementType;\n typedef typename Accumulator<T>::Type ResultType;\n\n template <typename Iterator1, typename Iterator2>\n inline ResultType operator()(Iterator1 a, Iterator2 b, size_t size) const\n {\n ResultType result = ResultType();\n ResultType diff;\n for(size_t i = 0; i < size; ++i ) {\n diff = *a++ - *b++;\n result += diff*diff;\n }\n return result;\n }\n};\n\n\/\/\/ Squared Euclidean distance functor (vectorized version)\ntemplate<class T>\nstruct L2_Vectorized\n{\n typedef T ElementType;\n typedef typename Accumulator<T>::Type ResultType;\n\n template <typename Iterator1, typename Iterator2>\n inline ResultType operator()(Iterator1 a, Iterator2 b, size_t size) const\n {\n ResultType result = ResultType();\n ResultType diff0, diff1, diff2, diff3;\n Iterator1 last = a + size;\n Iterator1 lastgroup = last - 3;\n\n \/\/ Process 4 items with each loop for efficiency.\n while (a < lastgroup) {\n diff0 = a[0] - b[0];\n diff1 = a[1] - b[1];\n diff2 = a[2] - b[2];\n diff3 = a[3] - b[3];\n result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;\n a += 4;\n b += 4;\n }\n \/\/ Process last 0-3 pixels. Not needed for standard vector lengths.\n while (a < last) {\n diff0 = *a++ - *b++;\n result += diff0 * diff0;\n }\n return result;\n }\n};\n\n#ifdef OPENVMG_USE_SSE\n\nnamespace optim_ss2{\n\n#include <xmmintrin.h>\n\n \/\/\/ Union to switch between SSE and float array\n union sseRegisterHelper\n {\n __m128 m;\n float f[4];\n };\n\n \/\/ Euclidean distance (SSE method) (squared result)\n inline float l2_sse(float * b1, float * b2, int size)\n {\n float* b1Pt = (float*)b1;\n float* b2Pt = (float*)b2;\n if(size%4 == 0)\n {\n __m128 srcA, srcB, temp, cumSum;\n float zeros[4] = {0.f,0.f,0.f,0.f};\n cumSum = _mm_load_ps( zeros );\n for(int i = 0 ; i < size; i+=4)\n {\n srcA = _mm_load_ps(b1Pt+i);\n srcB = _mm_load_ps(b2Pt+i);\n \/\/-- Subtract\n temp = _mm_sub_ps( srcA, srcB );\n \/\/-- Multiply\n temp = _mm_mul_ps( temp, temp );\n \/\/-- sum\n cumSum = _mm_add_ps( cumSum, temp );\n }\n sseRegisterHelper res;\n res.m = cumSum;\n return (res.f[0]+res.f[1]+res.f[2]+res.f[3]);\n }\n else\n {\n std::cerr <<\"\\n\/!\\\\ size is not modulus 4,\"\n << \" distance cannot be performed in SSE\"<< std::endl;\n return 0.0f;\n }\n }\n} \/\/ namespace optim_ss2\n\n\/\/ Template specification to run SSE L2 squared distance\n\/\/ on float vector\ntemplate<>\nstruct L2_Vectorized<float>\n{\n typedef float ElementType;\n typedef Accumulator<float>::Type ResultType;\n\n template <typename Iterator1, typename Iterator2>\n inline ResultType operator()(Iterator1 a, Iterator2 b, size_t size) const\n {\n return optim_ss2::l2_sse(a,b,size);\n }\n};\n\n#endif \/\/ OPENVMG_USE_SSE\n\n} \/\/ namespace matching\n} \/\/ namespace openMVG\n\n#endif \/\/ OPENMVG_MATCHING_METRIC_H\n<commit_msg>[matching] Fix a typo in the preprocessor used to detect SSE support - This L2 distance specialization is only used for floating point based descriptors. - So the impact will be visible only if you are using AKAZE_FLOAT. - Fast experiments show that SSE distance can be up to 40% faster.<commit_after>\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_MATCHING_METRIC_H\n#define OPENMVG_MATCHING_METRIC_H\n\n#include \"openMVG\/matching\/metric_hamming.hpp\"\n#include \"openMVG\/numeric\/accumulator_trait.hpp\"\n#include <cstddef>\n\nnamespace openMVG {\nnamespace matching {\n\n\/\/\/ Squared Euclidean distance functor.\ntemplate<class T>\nstruct L2_Simple\n{\n typedef T ElementType;\n typedef typename Accumulator<T>::Type ResultType;\n\n template <typename Iterator1, typename Iterator2>\n inline ResultType operator()(Iterator1 a, Iterator2 b, size_t size) const\n {\n ResultType result = ResultType();\n ResultType diff;\n for(size_t i = 0; i < size; ++i ) {\n diff = *a++ - *b++;\n result += diff*diff;\n }\n return result;\n }\n};\n\n\/\/\/ Squared Euclidean distance functor (vectorized version)\ntemplate<class T>\nstruct L2_Vectorized\n{\n typedef T ElementType;\n typedef typename Accumulator<T>::Type ResultType;\n\n template <typename Iterator1, typename Iterator2>\n inline ResultType operator()(Iterator1 a, Iterator2 b, size_t size) const\n {\n ResultType result = ResultType();\n ResultType diff0, diff1, diff2, diff3;\n Iterator1 last = a + size;\n Iterator1 lastgroup = last - 3;\n\n \/\/ Process 4 items with each loop for efficiency.\n while (a < lastgroup) {\n diff0 = a[0] - b[0];\n diff1 = a[1] - b[1];\n diff2 = a[2] - b[2];\n diff3 = a[3] - b[3];\n result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;\n a += 4;\n b += 4;\n }\n \/\/ Process last 0-3 pixels. Not needed for standard vector lengths.\n while (a < last) {\n diff0 = *a++ - *b++;\n result += diff0 * diff0;\n }\n return result;\n }\n};\n\n#ifdef OPENMVG_USE_SSE\n\nnamespace optim_ss2{\n\n#include <xmmintrin.h>\n\n \/\/\/ Union to switch between SSE and float array\n union sseRegisterHelper\n {\n __m128 m;\n float f[4];\n };\n\n \/\/ Euclidean distance (SSE method) (squared result)\n inline float l2_sse(const float * b1, const float * b2, int size)\n {\n float* b1Pt = (float*)b1;\n float* b2Pt = (float*)b2;\n if(size%4 == 0)\n {\n __m128 srcA, srcB, temp, cumSum;\n float zeros[4] = {0.f,0.f,0.f,0.f};\n cumSum = _mm_load_ps( zeros );\n for(int i = 0 ; i < size; i+=4)\n {\n srcA = _mm_load_ps(b1Pt+i);\n srcB = _mm_load_ps(b2Pt+i);\n \/\/-- Subtract\n temp = _mm_sub_ps( srcA, srcB );\n \/\/-- Multiply\n temp = _mm_mul_ps( temp, temp );\n \/\/-- sum\n cumSum = _mm_add_ps( cumSum, temp );\n }\n sseRegisterHelper res;\n res.m = cumSum;\n return (res.f[0]+res.f[1]+res.f[2]+res.f[3]);\n }\n else\n {\n std::cerr <<\"\\n\/!\\\\ size is not modulus 4,\"\n << \" distance cannot be performed in SSE\"<< std::endl;\n return 0.0f;\n }\n }\n} \/\/ namespace optim_ss2\n\n\/\/ Template specification to run SSE L2 squared distance\n\/\/ on float vector\ntemplate<>\nstruct L2_Vectorized<float>\n{\n typedef float ElementType;\n typedef Accumulator<float>::Type ResultType;\n\n template <typename Iterator1, typename Iterator2>\n inline ResultType operator()(Iterator1 a, Iterator2 b, size_t size) const\n {\n return optim_ss2::l2_sse(a,b,size);\n }\n};\n\n#endif \/\/ OPENMVG_USE_SSE\n\n} \/\/ namespace matching\n} \/\/ namespace openMVG\n\n#endif \/\/ OPENMVG_MATCHING_METRIC_H\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(nlogn)\n\/\/ Space: O(n)\n\n\/\/ Binary search solution with STL.\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums) {\n vector<int> LIS;\n\n for (const auto& num : nums) {\n insert(&LIS, num);\n }\n\n return LIS.size();\n }\n\nprivate:\n void insert(vector<int> *LIS, const int target) {\n \/\/ Find the first index \"left\" which satisfies LIS[left] >= target\n auto it = lower_bound(LIS->begin(), LIS->end(), target);\n\n \/\/ If not found, append the target.\n if (it != LIS->end()) {\n *it = target;\n } else {\n LIS->emplace_back(target);\n }\n }\n};\n\n\/\/ Binary search solution.\nclass Solution2 {\npublic:\n int lengthOfLIS(vector<int>& nums) {\n vector<int> LIS;\n\n for (const auto& num : nums) {\n insert(&LIS, num);\n }\n\n return LIS.size();\n }\n\nprivate:\n void insert(vector<int> *LIS, const int target) {\n int left = 0, right = LIS->size() - 1;\n auto comp = [](int x, int target) { return x >= target; };\n\n \/\/ Find the first index \"left\" which satisfies LIS[left] >= target\n while (left <= right) {\n int mid = left + (right - left) \/ 2;\n if (comp((*LIS)[mid], target)) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n \/\/ If not found, append the target.\n if (left == LIS->size()) {\n LIS->emplace_back(target);\n } else {\n (*LIS)[left] = target;\n }\n }\n};\n\n\/\/ Time: O(n^2)\n\/\/ Space: O(n)\n\/\/ Traditional DP solution.\nclass Solution3 {\npublic:\n int lengthOfLIS(vector<int>& nums) {\n const int n = nums.size();\n vector<int> dp(n, 1);\n int res = 0;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < i; ++j) {\n if (nums[j] < nums[i]) {\n dp[i] = max(dp[i], dp[j] + 1);\n }\n }\n res = max(res, dp[i]);\n }\n return res;\n }\n};\n<commit_msg>Update longest-increasing-subsequence.cpp<commit_after>\/\/ Time: O(nlogn)\n\/\/ Space: O(n)\n\n\/\/ Binary search solution with STL.\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums) {\n vector<int> LIS;\n\n for (const auto& num : nums) {\n insert(&LIS, num);\n }\n\n return LIS.size();\n }\n\nprivate:\n void insert(vector<int> *LIS, const int target) {\n \/\/ Find the first index \"left\" which satisfies LIS[left] >= target\n auto it = lower_bound(LIS->begin(), LIS->end(), target);\n\n \/\/ If not found, append the target.\n if (it != LIS->end()) {\n *it = target;\n } else {\n LIS->emplace_back(target);\n }\n }\n};\n\n\/\/ Binary search solution.\nclass Solution2 {\npublic:\n int lengthOfLIS(vector<int>& nums) {\n vector<int> LIS;\n\n for (const auto& num : nums) {\n insert(&LIS, num);\n }\n\n return LIS.size();\n }\n\nprivate:\n void insert(vector<int> *LIS, const int target) {\n int left = 0, right = LIS->size() - 1;\n auto comp = [](int x, int target) { return x >= target; };\n\n \/\/ Find the first index \"left\" which satisfies LIS[left] >= target\n while (left <= right) {\n int mid = left + (right - left) \/ 2;\n if (comp((*LIS)[mid], target)) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n \/\/ If not found, append the target.\n if (left == LIS->size()) {\n LIS->emplace_back(target);\n } else {\n (*LIS)[left] = target;\n }\n }\n};\n\n\/\/ Time: O(n^2)\n\/\/ Space: O(n)\n\/\/ Traditional DP solution.\nclass Solution3 {\npublic:\n int lengthOfLIS(vector<int>& nums) {\n const int n = nums.size();\n vector<int> dp(n, 1); \/\/ dp[i]: the length of LIS ends with nums[i]\n int res = 0;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < i; ++j) {\n if (nums[j] < nums[i]) {\n dp[i] = max(dp[i], dp[j] + 1);\n }\n }\n res = max(res, dp[i]);\n }\n return res;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Facebook, Inc.\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 <folly\/ThreadLocal.h>\n\nnamespace folly { namespace threadlocal_detail {\n\nPthreadKeyUnregister PthreadKeyUnregister::instance_;\n\n}}\n<commit_msg>Add MAX_STATIC_CONSTRUCTOR_PRIORITY to PthreadKeyUnregister<commit_after>\/*\n * Copyright 2015 Facebook, Inc.\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 <folly\/ThreadLocal.h>\n\nnamespace folly { namespace threadlocal_detail {\n\nMAX_STATIC_CONSTRUCTOR_PRIORITY\nPthreadKeyUnregister PthreadKeyUnregister::instance_;\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\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#include <memory>\n#include <thread>\n\n#include <folly\/Function.h>\n#include <folly\/SharedMutex.h>\n#include <folly\/Singleton.h>\n#include <folly\/executors\/CPUThreadPoolExecutor.h>\n#include <folly\/executors\/GlobalExecutor.h>\n#include <folly\/executors\/IOExecutor.h>\n#include <folly\/executors\/IOThreadPoolExecutor.h>\n#include <folly\/system\/HardwareConcurrency.h>\n\nusing namespace folly;\n\nnamespace {\n\nclass GlobalTag {};\n\n\/\/ aka InlineExecutor\nclass DefaultCPUExecutor : public Executor {\n public:\n FOLLY_NOINLINE void add(Func f) override {\n f();\n }\n};\n\nSingleton<std::shared_ptr<DefaultCPUExecutor>> gDefaultGlobalCPUExecutor([] {\n return new std::shared_ptr<DefaultCPUExecutor>(new DefaultCPUExecutor{});\n});\n\nSingleton<std::shared_ptr<CPUThreadPoolExecutor>, GlobalTag>\n gImmutableGlobalCPUExecutor([] {\n return new std::shared_ptr<CPUThreadPoolExecutor>(\n new CPUThreadPoolExecutor(\n folly::hardware_concurrency(),\n std::make_shared<NamedThreadFactory>(\"GlobalCPUThreadPool\")));\n });\n\nSingleton<std::shared_ptr<IOThreadPoolExecutor>, GlobalTag>\n gImmutableGlobalIOExecutor([] {\n return new std::shared_ptr<IOThreadPoolExecutor>(new IOThreadPoolExecutor(\n folly::hardware_concurrency(),\n std::make_shared<NamedThreadFactory>(\"GlobalIOThreadPool\")));\n });\n\ntemplate <class ExecutorBase>\nstd::shared_ptr<ExecutorBase> getImmutable();\n\ntemplate <>\nstd::shared_ptr<Executor> getImmutable() {\n if (auto executorPtrPtr = gImmutableGlobalCPUExecutor.try_get()) {\n return *executorPtrPtr;\n }\n return nullptr;\n}\n\ntemplate <>\nstd::shared_ptr<IOExecutor> getImmutable() {\n if (auto executorPtrPtr = gImmutableGlobalIOExecutor.try_get()) {\n return *executorPtrPtr;\n }\n return nullptr;\n}\n\ntemplate <class ExecutorBase>\nclass GlobalExecutor {\n public:\n explicit GlobalExecutor(\n Function<std::shared_ptr<ExecutorBase>()> constructDefault)\n : getDefault_(std::move(constructDefault)) {}\n\n std::shared_ptr<ExecutorBase> get() {\n SharedMutex::ReadHolder guard(mutex_);\n if (auto executor = executor_.lock()) {\n return executor; \/\/ Fast path.\n }\n\n return getDefault_();\n }\n\n void set(std::weak_ptr<ExecutorBase> executor) {\n SharedMutex::WriteHolder guard(mutex_);\n executor_.swap(executor);\n }\n\n \/\/ Replace the constructDefault function to use the immutable singleton\n \/\/ rather than the default singleton\n void setFromImmutable() {\n SharedMutex::WriteHolder guard(mutex_);\n\n getDefault_ = [] { return getImmutable<ExecutorBase>(); };\n executor_ = std::weak_ptr<ExecutorBase>{};\n }\n\n private:\n SharedMutex mutex_;\n std::weak_ptr<ExecutorBase> executor_;\n Function<std::shared_ptr<ExecutorBase>()> getDefault_;\n};\n\nLeakySingleton<GlobalExecutor<Executor>> gGlobalCPUExecutor([] {\n return new GlobalExecutor<Executor>(\n \/\/ Default global CPU executor is an InlineExecutor.\n [] {\n if (auto executorPtrPtr = gDefaultGlobalCPUExecutor.try_get()) {\n return *executorPtrPtr;\n }\n return std::shared_ptr<DefaultCPUExecutor>{};\n });\n});\n\nLeakySingleton<GlobalExecutor<IOExecutor>> gGlobalIOExecutor([] {\n return new GlobalExecutor<IOExecutor>(\n \/\/ Default global IO executor is an IOThreadPoolExecutor.\n [] { return getImmutable<IOExecutor>(); });\n});\n\n} \/\/ namespace\n\nnamespace folly {\n\nExecutor::KeepAlive<> getGlobalCPUExecutor() {\n auto executorPtr = getImmutable<Executor>();\n if (!executorPtr) {\n throw std::runtime_error(\"Requested global CPU executor during shutdown.\");\n }\n return folly::getKeepAliveToken(executorPtr.get());\n}\n\nExecutor::KeepAlive<> getGlobalIOExecutor() {\n auto executorPtr = getImmutable<IOExecutor>();\n if (!executorPtr) {\n throw std::runtime_error(\"Requested global IO executor during shutdown.\");\n }\n return folly::getKeepAliveToken(executorPtr.get());\n}\n\nstd::shared_ptr<Executor> getCPUExecutor() {\n auto& singleton = gGlobalCPUExecutor.get();\n return singleton.get();\n}\n\nvoid setCPUExecutorToGlobalCPUExecutor() {\n gGlobalCPUExecutor.get().setFromImmutable();\n}\n\nvoid setCPUExecutor(std::weak_ptr<Executor> executor) {\n gGlobalCPUExecutor.get().set(std::move(executor));\n}\n\nstd::shared_ptr<IOExecutor> getIOExecutor() {\n return gGlobalIOExecutor.get().get();\n}\n\nvoid setIOExecutor(std::weak_ptr<IOExecutor> executor) {\n gGlobalIOExecutor.get().set(std::move(executor));\n}\n\nEventBase* getEventBase() {\n auto executor = getIOExecutor();\n if (FOLLY_LIKELY(!!executor)) {\n return executor->getEventBase();\n }\n\n return nullptr;\n}\n\n} \/\/ namespace folly\n<commit_msg>Add tracing to global executors<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\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#include <memory>\n#include <thread>\n\n#include <folly\/Function.h>\n#include <folly\/SharedMutex.h>\n#include <folly\/Singleton.h>\n#include <folly\/detail\/AsyncTrace.h>\n#include <folly\/executors\/CPUThreadPoolExecutor.h>\n#include <folly\/executors\/GlobalExecutor.h>\n#include <folly\/executors\/IOExecutor.h>\n#include <folly\/executors\/IOThreadPoolExecutor.h>\n#include <folly\/system\/HardwareConcurrency.h>\n\nusing namespace folly;\n\nnamespace {\n\nclass GlobalTag {};\n\n\/\/ aka InlineExecutor\nclass DefaultCPUExecutor : public Executor {\n public:\n FOLLY_NOINLINE void add(Func f) override {\n f();\n }\n};\n\nSingleton<std::shared_ptr<DefaultCPUExecutor>> gDefaultGlobalCPUExecutor([] {\n return new std::shared_ptr<DefaultCPUExecutor>(new DefaultCPUExecutor{});\n});\n\nSingleton<std::shared_ptr<CPUThreadPoolExecutor>, GlobalTag>\n gImmutableGlobalCPUExecutor([] {\n return new std::shared_ptr<CPUThreadPoolExecutor>(\n new CPUThreadPoolExecutor(\n folly::hardware_concurrency(),\n std::make_shared<NamedThreadFactory>(\"GlobalCPUThreadPool\")));\n });\n\nSingleton<std::shared_ptr<IOThreadPoolExecutor>, GlobalTag>\n gImmutableGlobalIOExecutor([] {\n return new std::shared_ptr<IOThreadPoolExecutor>(new IOThreadPoolExecutor(\n folly::hardware_concurrency(),\n std::make_shared<NamedThreadFactory>(\"GlobalIOThreadPool\")));\n });\n\ntemplate <class ExecutorBase>\nstd::shared_ptr<ExecutorBase> getImmutable();\n\ntemplate <>\nstd::shared_ptr<Executor> getImmutable() {\n if (auto executorPtrPtr = gImmutableGlobalCPUExecutor.try_get()) {\n return *executorPtrPtr;\n }\n return nullptr;\n}\n\ntemplate <>\nstd::shared_ptr<IOExecutor> getImmutable() {\n if (auto executorPtrPtr = gImmutableGlobalIOExecutor.try_get()) {\n return *executorPtrPtr;\n }\n return nullptr;\n}\n\ntemplate <class ExecutorBase>\nclass GlobalExecutor {\n public:\n explicit GlobalExecutor(\n Function<std::shared_ptr<ExecutorBase>()> constructDefault)\n : getDefault_(std::move(constructDefault)) {}\n\n std::shared_ptr<ExecutorBase> get() {\n SharedMutex::ReadHolder guard(mutex_);\n if (auto executor = executor_.lock()) {\n return executor; \/\/ Fast path.\n }\n\n return getDefault_();\n }\n\n void set(std::weak_ptr<ExecutorBase> executor) {\n SharedMutex::WriteHolder guard(mutex_);\n executor_.swap(executor);\n }\n\n \/\/ Replace the constructDefault function to use the immutable singleton\n \/\/ rather than the default singleton\n void setFromImmutable() {\n SharedMutex::WriteHolder guard(mutex_);\n\n getDefault_ = [] { return getImmutable<ExecutorBase>(); };\n executor_ = std::weak_ptr<ExecutorBase>{};\n }\n\n private:\n SharedMutex mutex_;\n std::weak_ptr<ExecutorBase> executor_;\n Function<std::shared_ptr<ExecutorBase>()> getDefault_;\n};\n\nLeakySingleton<GlobalExecutor<Executor>> gGlobalCPUExecutor([] {\n return new GlobalExecutor<Executor>(\n \/\/ Default global CPU executor is an InlineExecutor.\n [] {\n if (auto executorPtrPtr = gDefaultGlobalCPUExecutor.try_get()) {\n return *executorPtrPtr;\n }\n return std::shared_ptr<DefaultCPUExecutor>{};\n });\n});\n\nLeakySingleton<GlobalExecutor<IOExecutor>> gGlobalIOExecutor([] {\n return new GlobalExecutor<IOExecutor>(\n \/\/ Default global IO executor is an IOThreadPoolExecutor.\n [] { return getImmutable<IOExecutor>(); });\n});\n\n} \/\/ namespace\n\nnamespace folly {\n\nExecutor::KeepAlive<> getGlobalCPUExecutor() {\n auto executorPtr = getImmutable<Executor>();\n if (!executorPtr) {\n throw std::runtime_error(\"Requested global CPU executor during shutdown.\");\n }\n async_tracing::logGetImmutableCPUExecutor(executorPtr.get());\n return folly::getKeepAliveToken(executorPtr.get());\n}\n\nExecutor::KeepAlive<> getGlobalIOExecutor() {\n auto executorPtr = getImmutable<IOExecutor>();\n if (!executorPtr) {\n throw std::runtime_error(\"Requested global IO executor during shutdown.\");\n }\n async_tracing::logGetImmutableIOExecutor(executorPtr.get());\n return folly::getKeepAliveToken(executorPtr.get());\n}\n\nstd::shared_ptr<Executor> getCPUExecutor() {\n auto& singleton = gGlobalCPUExecutor.get();\n auto executor = singleton.get();\n async_tracing::logGetGlobalCPUExecutor(executor.get());\n return executor;\n}\n\nvoid setCPUExecutorToGlobalCPUExecutor() {\n async_tracing::logSetGlobalCPUExecutorToImmutable();\n gGlobalCPUExecutor.get().setFromImmutable();\n}\n\nvoid setCPUExecutor(std::weak_ptr<Executor> executor) {\n async_tracing::logSetGlobalCPUExecutor(executor.lock().get());\n gGlobalCPUExecutor.get().set(std::move(executor));\n}\n\nstd::shared_ptr<IOExecutor> getIOExecutor() {\n auto& singleton = gGlobalIOExecutor.get();\n auto executor = singleton.get();\n async_tracing::logGetGlobalCPUExecutor(executor.get());\n return executor;\n}\n\nvoid setIOExecutor(std::weak_ptr<IOExecutor> executor) {\n async_tracing::logSetGlobalIOExecutor(executor.lock().get());\n gGlobalIOExecutor.get().set(std::move(executor));\n}\n\nEventBase* getEventBase() {\n auto executor = getIOExecutor();\n if (FOLLY_LIKELY(!!executor)) {\n return executor->getEventBase();\n }\n\n return nullptr;\n}\n\n} \/\/ namespace folly\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\n\/\/ ASM76\/VM.cpp\n\/\/==============================================================================\n\/\/ Virtual Machine\n\/\/==============================================================================\n\n#include \"ASM76.hpp\"\n\nnamespace ASM76 {\n\n\tuint8_t* global_memory;\n\n\tvoid init_environment() {\n\t\t\/\/ 4MB program useable\n\t\t\/\/ 12MB IO interface\n\t\tprintf(\"Init ASM76 env\\n\");\n\t\tglobal_memory = new uint8_t[0x1000000];\n\t\tmemset(global_memory, 0, 0x1000000);\n\t}\n\n\tVM::VM(Instruct* program, size_t prg_size) {\n\t\t\/\/ 16K local memory in default\n\t\tlocal_memory = new uint8_t[local_mem_size];\n\t\tmemset(local_memory, 0, local_mem_size);\n\t\tinstruct_memory = (Instruct*) local_memory;\n\t\tprintf(\"init memory with program sized %zu\\n\", prg_size);\n\t\tmemcpy(instruct_memory, program, prg_size);\n\n\t\t\/\/ 99 registers\n\t\treg = new uint8_t[100];\n\t\tmemset(reg, 0, 99);\n\n\t\t\/\/ Setup registers\n\t\t\/\/ Instruction pointer\n\t\tREG(uint32_t, 86) = 0x1000000;\n\t\t\/\/ Stack bottom pointer\n\t\tREG(uint32_t, 90) = 0x1003000;\n\n\t\tREG86 = (uint32_t*) (reg + 86);\n\t\tREG90 = (uint32_t*) (reg + 90);\n\t\tREG97 = (uint8_t*) (reg + 97);\n\t\tREG98 = (uint8_t*) (reg + 98);\n\t\tREG99 = (uint8_t*) (reg + 99);\n\t}\n\n\t#define OPC(code) (now->opcode == code)\n\n\tvoid VM::execute() {\n\t\tInstruct* now = memfetch<Instruct>(*REG86);\n\t\twhile (!OPC(_HLT)) {\n\t\t\tprintf(\"%x : %x, %x, %x\\n\", *REG86, now->opcode, now->f, now->t);\n\n\t\t\t\/\/ ===========================\n\t\t\t\/\/ 76-Base\n\t\t\t\/\/ ===========================\n\t\t\t\/\/ LCMM\n\t\t\tif OPC(LCMM) {\n\t\t\t\tuint8_t* new_mem = new uint8_t[now->f];\n\t\t\t\tmemset(new_mem, 0, now->f);\n\t\t\t\tsize_t copied_size = now->f < local_mem_size ? now->f : local_mem_size;\n\t\t\t\tmemcpy(new_mem, local_memory, copied_size);\n\t\t\t\tfree(local_memory);\n\t\t\t\tlocal_mem_size = now->f;\n\t\t\t\tlocal_memory = new_mem;\n\t\t\t\tinstruct_memory = (Instruct*) new_mem;\n\n\t\t\t\tprintf(\"Changed local size to %zu bytes\\n\", local_mem_size);\n\t\t\t}\n\t\t\t\/\/ Load Data\n\t\t\telse if OPC(LDLA) {\n\t\t\t\tREG(uint64_t, now->t) = *memfetch<uint64_t>(now->f);\n\t\t\t} else if OPC(LDIA) {\n\t\t\t\tREG(uint32_t, now->t) = *memfetch<uint32_t>(now->f);\n\t\t\t} else if OPC(LDBA) {\n\t\t\t\tREG(uint8_t, now->t) = *memfetch<uint8_t>(now->f);\n\t\t\t} else if OPC(LDLR) {\n\t\t\t\tREG(uint64_t, now->t) = *memfetch<uint64_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(LDIR) {\n\t\t\t\tREG(uint32_t, now->t) = *memfetch<uint32_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(LDBR) {\n\t\t\t\tREG(uint8_t, now->t) = *memfetch<uint8_t>(REG(uint32_t, now->f));\n\t\t\t}\n\t\t\t\/\/ Store data\n\t\t\telse if OPC(SLLA) {\n\t\t\t\t*memfetch<uint64_t>(now->f) = REG(uint64_t, now->t);\n\t\t\t} else if OPC(SLIA) {\n\t\t\t\t*memfetch<uint32_t>(now->f) = REG(uint32_t, now->t);\n\t\t\t} else if OPC(SLBA) {\n\t\t\t\t*memfetch<uint8_t>(now->f) = REG(uint8_t, now->t);\n\t\t\t} else if OPC(SLLR) {\n\t\t\t\t*memfetch<uint64_t>(REG(uint32_t, now->f)) = REG(uint64_t, now->t);\n\t\t\t} else if OPC(SLIR) {\n\t\t\t\t*memfetch<uint32_t>(REG(uint32_t, now->f)) = REG(uint32_t, now->t);\n\t\t\t} else if OPC(SLBR) {\n\t\t\t\t*memfetch<uint8_t>(REG(uint32_t, now->f)) = REG(uint8_t, now->t);\n\t\t\t} else if OPC(DATI) {\n\t\t\t\tREG(uint32_t, now->t) = (uint32_t) now->f;\n\t\t\t} else if OPC(DATB) {\n\t\t\t\tREG(uint8_t, now->t) = (uint8_t) now->f;\n\t\t\t}\n\t\t\t\/\/ Mem operation\n\t\t\telse if OPC(MOVL) {\n\t\t\t\t*memfetch<uint64_t>(now->t) = *memfetch<uint64_t>(now->f);\n\t\t\t} else if OPC(MOVI) {\n\t\t\t\t*memfetch<uint32_t>(now->t) = *memfetch<uint32_t>(now->f);\n\t\t\t} else if OPC(MOVB) {\n\t\t\t\t*memfetch<uint8_t>(now->t) = *memfetch<uint8_t>(now->f);\n\t\t\t} else if OPC(MVPL) {\n\t\t\t\t*memfetch<uint64_t>(REG(uint32_t, now->t)) = *memfetch<uint64_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(MVPI) {\n\t\t\t\t*memfetch<uint32_t>(REG(uint32_t, now->t)) = *memfetch<uint32_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(MVPB) {\n\t\t\t\t*memfetch<uint8_t>(REG(uint32_t, now->t)) = *memfetch<uint8_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(MVRL) {\n\t\t\t\tREG(uint64_t, now->t) = REG(uint64_t, now->f);\n\t\t\t} else if OPC(MVRI) {\n\t\t\t\tREG(uint32_t, now->t) = REG(uint32_t, now->f);\n\t\t\t} else if OPC(MVRB) {\n\t\t\t\tREG(uint8_t, now->t) = REG(uint8_t, now->f);\n\t\t\t}\n\t\t\t\/\/ Basic Algebra\n\t\t\telse if OPC(ADDL) {\n\t\t\t\tREG(uint64_t, now->f) += REG(uint64_t, now->t);\n\t\t\t} else if OPC(ADDI) {\n\t\t\t\tREG(uint32_t, now->f) += REG(uint32_t, now->t);\n\t\t\t} else if OPC(ADDB) {\n\t\t\t\tREG(uint8_t, now->f) += REG(uint8_t, now->t);\n\t\t\t} else if OPC(MINL) {\n\t\t\t\tREG(uint64_t, now->f) -= REG(uint64_t, now->t);\n\t\t\t} else if OPC(MINI) {\n\t\t\t\tREG(uint32_t, now->f) -= REG(uint32_t, now->t);\n\t\t\t} else if OPC(MINB) {\n\t\t\t\tREG(uint8_t, now->f) -= REG(uint8_t, now->t);\n\t\t\t} else if OPC(MTPL) {\n\t\t\t\tREG(uint64_t, now->f) *= REG(uint64_t, now->t);\n\t\t\t} else if OPC(MTPI) {\n\t\t\t\tREG(uint32_t, now->f) *= REG(uint32_t, now->t);\n\t\t\t} else if OPC(MTPB) {\n\t\t\t\tREG(uint8_t, now->f) *= REG(uint8_t, now->t);\n\t\t\t} else if OPC(DIVL) {\n\t\t\t\tREG(uint64_t, now->f) \/= REG(uint64_t, now->t);\n\t\t\t} else if OPC(DIVI) {\n\t\t\t\tREG(uint32_t, now->f) \/= REG(uint32_t, now->t);\n\t\t\t} else if OPC(DIVB) {\n\t\t\t\tREG(uint8_t, now->f) \/= REG(uint8_t, now->t);\n\t\t\t} else if OPC(MODL) {\n\t\t\t\tREG(uint64_t, now->f) = REG(uint64_t, now->f) % REG(uint64_t, now->t);\n\t\t\t} else if OPC(MODI) {\n\t\t\t\tREG(uint32_t, now->f) = REG(uint32_t, now->t) % REG(uint32_t, now->t);\n\t\t\t} else if OPC(MODB) {\n\t\t\t\tREG(uint8_t, now->f) = REG(uint8_t, now->t) % REG(uint8_t, now->t);\n\t\t\t}\n\t\t\t\/\/ ===========================\n\t\t\t\/\/ Logistics & Flow control\n\t\t\t\/\/ ===========================\n\t\t\tif (now->opcode >= ANDL) {\n\t\t\t\tif OPC(ANDL) {\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t*REG86 += sizeof(Instruct);\n\t\t\tnow = memfetch<Instruct>(*REG86);\n\t\t}\n\t}\n\n\tvoid VM::dump_registers() {\n\t\tprintf(\"Registers: \\n\");\n\t\tfor (int i = 1; i < 100; i++) {\n\t\t\tprintf(\"%02x \", reg[i]);\n\t\t\tif (i % 10 == 0) printf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tvoid VM::dump_memory() {\n\t\tprintf(\"Local Memory: \\n\");\n\t\tfor (uint32_t i = 1; i < local_mem_size \/ 8; i++) {\n\t\t\tprintf(\"%08x \", *((uint32_t*)local_memory + i));\n\t\t\tif (i % 8 == 0) printf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tchar* VM::decompile(Instruct* prg) {\n\t\treturn NULL;\n\t}\n\n\tInstruct* VM::compile(const char* prg) {\n\t\treturn NULL;\n\t}\n\n\tVM::~VM() {\n\t\tfree(local_memory);\n\t\tfree(reg);\n\t}\n\n}\n<commit_msg>完成逻辑运算和CMP<commit_after>\/\/==============================================================================\n\/\/ ASM76\/VM.cpp\n\/\/==============================================================================\n\/\/ Virtual Machine\n\/\/==============================================================================\n\n#include \"ASM76.hpp\"\n\nnamespace ASM76 {\n\n\tuint8_t* global_memory;\n\n\tvoid init_environment() {\n\t\t\/\/ 4MB program useable\n\t\t\/\/ 12MB IO interface\n\t\tprintf(\"Init ASM76 env\\n\");\n\t\tglobal_memory = new uint8_t[0x1000000];\n\t\tmemset(global_memory, 0, 0x1000000);\n\t}\n\n\tVM::VM(Instruct* program, size_t prg_size) {\n\t\t\/\/ 16K local memory in default\n\t\tlocal_memory = new uint8_t[local_mem_size];\n\t\tmemset(local_memory, 0, local_mem_size);\n\t\tinstruct_memory = (Instruct*) local_memory;\n\t\tprintf(\"init memory with program sized %zu\\n\", prg_size);\n\t\tmemcpy(instruct_memory, program, prg_size);\n\n\t\t\/\/ 99 registers\n\t\treg = new uint8_t[100];\n\t\tmemset(reg, 0, 99);\n\n\t\t\/\/ Setup registers\n\t\t\/\/ Instruction pointer\n\t\tREG(uint32_t, 86) = 0x1000000;\n\t\t\/\/ Stack bottom pointer\n\t\tREG(uint32_t, 90) = 0x1003000;\n\n\t\tREG86 = (uint32_t*) (reg + 86);\n\t\tREG90 = (uint32_t*) (reg + 90);\n\t\tREG97 = (uint8_t*) (reg + 97);\n\t\tREG98 = (uint8_t*) (reg + 98);\n\t\tREG99 = (uint8_t*) (reg + 99);\n\t}\n\n\t#define OPC(code) (now->opcode == code)\n\n\tvoid VM::execute() {\n\t\tInstruct* now = memfetch<Instruct>(*REG86);\n\t\twhile (!OPC(_HLT)) {\n\t\t\tprintf(\"%08x : %04x, %x, %x\\n\", *REG86, now->opcode, now->f, now->t);\n\n\t\t\t\/\/ ===========================\n\t\t\t\/\/ 76-Base\n\t\t\t\/\/ ===========================\n\t\t\t\/\/ LCMM\n\t\t\tif OPC(LCMM) {\n\t\t\t\tuint8_t* new_mem = new uint8_t[now->f];\n\t\t\t\tmemset(new_mem, 0, now->f);\n\t\t\t\tsize_t copied_size = now->f < local_mem_size ? now->f : local_mem_size;\n\t\t\t\tmemcpy(new_mem, local_memory, copied_size);\n\t\t\t\tfree(local_memory);\n\t\t\t\tlocal_mem_size = now->f;\n\t\t\t\tlocal_memory = new_mem;\n\t\t\t\tinstruct_memory = (Instruct*) new_mem;\n\n\t\t\t\tprintf(\"Changed local size to %zu bytes\\n\", local_mem_size);\n\t\t\t}\n\t\t\t\/\/ Load Data\n\t\t\telse if OPC(LDLA) {\n\t\t\t\tREG(uint64_t, now->t) = *memfetch<uint64_t>(now->f);\n\t\t\t} else if OPC(LDIA) {\n\t\t\t\tREG(uint32_t, now->t) = *memfetch<uint32_t>(now->f);\n\t\t\t} else if OPC(LDBA) {\n\t\t\t\tREG(uint8_t, now->t) = *memfetch<uint8_t>(now->f);\n\t\t\t} else if OPC(LDLR) {\n\t\t\t\tREG(uint64_t, now->t) = *memfetch<uint64_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(LDIR) {\n\t\t\t\tREG(uint32_t, now->t) = *memfetch<uint32_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(LDBR) {\n\t\t\t\tREG(uint8_t, now->t) = *memfetch<uint8_t>(REG(uint32_t, now->f));\n\t\t\t}\n\t\t\t\/\/ Store data\n\t\t\telse if OPC(SLLA) {\n\t\t\t\t*memfetch<uint64_t>(now->f) = REG(uint64_t, now->t);\n\t\t\t} else if OPC(SLIA) {\n\t\t\t\t*memfetch<uint32_t>(now->f) = REG(uint32_t, now->t);\n\t\t\t} else if OPC(SLBA) {\n\t\t\t\t*memfetch<uint8_t>(now->f) = REG(uint8_t, now->t);\n\t\t\t} else if OPC(SLLR) {\n\t\t\t\t*memfetch<uint64_t>(REG(uint32_t, now->f)) = REG(uint64_t, now->t);\n\t\t\t} else if OPC(SLIR) {\n\t\t\t\t*memfetch<uint32_t>(REG(uint32_t, now->f)) = REG(uint32_t, now->t);\n\t\t\t} else if OPC(SLBR) {\n\t\t\t\t*memfetch<uint8_t>(REG(uint32_t, now->f)) = REG(uint8_t, now->t);\n\t\t\t} else if OPC(DATI) {\n\t\t\t\tREG(uint32_t, now->t) = (uint32_t) now->f;\n\t\t\t} else if OPC(DATB) {\n\t\t\t\tREG(uint8_t, now->t) = (uint8_t) now->f;\n\t\t\t}\n\t\t\t\/\/ Mem operation\n\t\t\telse if OPC(MOVL) {\n\t\t\t\t*memfetch<uint64_t>(now->t) = *memfetch<uint64_t>(now->f);\n\t\t\t} else if OPC(MOVI) {\n\t\t\t\t*memfetch<uint32_t>(now->t) = *memfetch<uint32_t>(now->f);\n\t\t\t} else if OPC(MOVB) {\n\t\t\t\t*memfetch<uint8_t>(now->t) = *memfetch<uint8_t>(now->f);\n\t\t\t} else if OPC(MVPL) {\n\t\t\t\t*memfetch<uint64_t>(REG(uint32_t, now->t)) = *memfetch<uint64_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(MVPI) {\n\t\t\t\t*memfetch<uint32_t>(REG(uint32_t, now->t)) = *memfetch<uint32_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(MVPB) {\n\t\t\t\t*memfetch<uint8_t>(REG(uint32_t, now->t)) = *memfetch<uint8_t>(REG(uint32_t, now->f));\n\t\t\t} else if OPC(MVRL) {\n\t\t\t\tREG(uint64_t, now->t) = REG(uint64_t, now->f);\n\t\t\t} else if OPC(MVRI) {\n\t\t\t\tREG(uint32_t, now->t) = REG(uint32_t, now->f);\n\t\t\t} else if OPC(MVRB) {\n\t\t\t\tREG(uint8_t, now->t) = REG(uint8_t, now->f);\n\t\t\t}\n\t\t\t\/\/ Basic Algebra\n\t\t\telse if OPC(ADDL) {\n\t\t\t\tREG(uint64_t, now->f) += REG(uint64_t, now->t);\n\t\t\t} else if OPC(ADDI) {\n\t\t\t\tREG(uint32_t, now->f) += REG(uint32_t, now->t);\n\t\t\t} else if OPC(ADDB) {\n\t\t\t\tREG(uint8_t, now->f) += REG(uint8_t, now->t);\n\t\t\t} else if OPC(MINL) {\n\t\t\t\tREG(uint64_t, now->f) -= REG(uint64_t, now->t);\n\t\t\t} else if OPC(MINI) {\n\t\t\t\tREG(uint32_t, now->f) -= REG(uint32_t, now->t);\n\t\t\t} else if OPC(MINB) {\n\t\t\t\tREG(uint8_t, now->f) -= REG(uint8_t, now->t);\n\t\t\t} else if OPC(MTPL) {\n\t\t\t\tREG(uint64_t, now->f) *= REG(uint64_t, now->t);\n\t\t\t} else if OPC(MTPI) {\n\t\t\t\tREG(uint32_t, now->f) *= REG(uint32_t, now->t);\n\t\t\t} else if OPC(MTPB) {\n\t\t\t\tREG(uint8_t, now->f) *= REG(uint8_t, now->t);\n\t\t\t} else if OPC(DIVL) {\n\t\t\t\tREG(uint64_t, now->f) \/= REG(uint64_t, now->t);\n\t\t\t} else if OPC(DIVI) {\n\t\t\t\tREG(uint32_t, now->f) \/= REG(uint32_t, now->t);\n\t\t\t} else if OPC(DIVB) {\n\t\t\t\tREG(uint8_t, now->f) \/= REG(uint8_t, now->t);\n\t\t\t} else if OPC(MODL) {\n\t\t\t\tREG(uint64_t, now->f) = REG(uint64_t, now->f) % REG(uint64_t, now->t);\n\t\t\t} else if OPC(MODI) {\n\t\t\t\tREG(uint32_t, now->f) = REG(uint32_t, now->t) % REG(uint32_t, now->t);\n\t\t\t} else if OPC(MODB) {\n\t\t\t\tREG(uint8_t, now->f) = REG(uint8_t, now->t) % REG(uint8_t, now->t);\n\t\t\t}\n\t\t\t\/\/ ===========================\n\t\t\t\/\/ Logistics & Flow control\n\t\t\t\/\/ ===========================\n\t\t\tif (now->opcode >= ANDL) {\n\t\t\t\tif OPC(ANDL) {\n\t\t\t\t\tREG(uint64_t, now->f) &= REG(uint64_t, now->t);\n\t\t\t\t} else if OPC(ANDI) {\n\t\t\t\t\tREG(uint32_t, now->f) &= REG(uint32_t, now->t);\n\t\t\t\t} else if OPC(ANDB) {\n\t\t\t\t\tREG(uint8_t, now->f) &= REG(uint8_t, now->t);\n\t\t\t\t} else if OPC(OR_L) {\n\t\t\t\t\tREG(uint64_t, now->f) |= REG(uint64_t, now->t);\n\t\t\t\t} else if OPC(OR_I) {\n\t\t\t\t\tREG(uint32_t, now->f) |= REG(uint32_t, now->t);\n\t\t\t\t} else if OPC(OR_B) {\n\t\t\t\t\tREG(uint8_t, now->f) |= REG(uint8_t, now->t);\n\t\t\t\t} else if OPC(NOTL) {\n\t\t\t\t\tREG(uint64_t, now->f) = !(REG(uint64_t, now->f));\n\t\t\t\t} else if OPC(NOTI) {\n\t\t\t\t\tREG(uint32_t, now->f) = !(REG(uint32_t, now->f));\n\t\t\t\t} else if OPC(NOTB) {\n\t\t\t\t\tREG(uint8_t, now->f) = !(REG(uint8_t, now->f));\n\t\t\t\t} else if OPC(XORL) {\n\t\t\t\t\tREG(uint64_t, now->f) ^= (REG(uint64_t, now->f));\n\t\t\t\t} else if OPC(XORI) {\n\t\t\t\t\tREG(uint32_t, now->f) ^= (REG(uint32_t, now->f));\n\t\t\t\t} else if OPC(XORB) {\n\t\t\t\t\tREG(uint8_t, now->f) ^= (REG(uint8_t, now->f));\n\t\t\t\t} else if OPC(CMPL) {\n\t\t\t\t\tif (REG(uint64_t, now->f) > REG(uint64_t, now->t)) {\n\t\t\t\t\t\t*REG99 = 0xFF; *REG98 = 0x0; *REG97 = 0x0;\n\t\t\t\t\t} else if (REG(uint64_t, now->f) == REG(uint64_t, now->t)) {\n\t\t\t\t\t\t*REG99 = 0x0; *REG98 = 0xFF; *REG97 = 0x0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t*REG99 = 0x0; *REG98 = 0x0; *REG97 = 0xFF;\n\t\t\t\t\t}\n\t\t\t\t} else if OPC(CMPI) {\n\t\t\t\t\tif (REG(uint32_t, now->f) > REG(uint32_t, now->t)) {\n\t\t\t\t\t\t*REG99 = 0xFF; *REG98 = 0x0; *REG97 = 0x0;\n\t\t\t\t\t} else if (REG(uint32_t, now->f) == REG(uint32_t, now->t)) {\n\t\t\t\t\t\t*REG99 = 0x0; *REG98 = 0xFF; *REG97 = 0x0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t*REG99 = 0x0; *REG98 = 0x0; *REG97 = 0xFF;\n\t\t\t\t\t}\n\t\t\t\t} else if OPC(CMPB) {\n\t\t\t\t\tif (REG(uint8_t, now->f) > REG(uint8_t, now->t)) {\n\t\t\t\t\t\t*REG99 = 0xFF; *REG98 = 0x0; *REG97 = 0x0;\n\t\t\t\t\t} else if (REG(uint8_t, now->f) == REG(uint8_t, now->t)) {\n\t\t\t\t\t\t*REG99 = 0x0; *REG98 = 0xFF; *REG97 = 0x0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t*REG99 = 0x0; *REG98 = 0x0; *REG97 = 0xFF;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t*REG86 += sizeof(Instruct);\n\t\t\tnow = memfetch<Instruct>(*REG86);\n\t\t}\n\t}\n\n\tvoid VM::dump_registers() {\n\t\tprintf(\"Registers: \\n\");\n\t\tfor (int i = 1; i < 100; i++) {\n\t\t\tprintf(\"%02x \", reg[i]);\n\t\t\tif (i % 10 == 0) printf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tvoid VM::dump_memory() {\n\t\tprintf(\"Local Memory: \\n\");\n\t\tfor (uint32_t i = 1; i < local_mem_size \/ 8; i++) {\n\t\t\tprintf(\"%08x \", *((uint32_t*)local_memory + i));\n\t\t\tif (i % 8 == 0) printf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tchar* VM::decompile(Instruct* prg) {\n\t\treturn NULL;\n\t}\n\n\tInstruct* VM::compile(const char* prg) {\n\t\treturn NULL;\n\t}\n\n\tVM::~VM() {\n\t\tfree(local_memory);\n\t\tfree(reg);\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\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: Numeric.hxx,v $\n * $Revision: 1.10 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _FORMS_NUMERIC_HXX_\n#define _FORMS_NUMERIC_HXX_\n\n#include \"EditBase.hxx\"\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\n\/\/==================================================================\n\/\/= ONumericModel\n\/\/==================================================================\nclass ONumericModel\n :public OEditBaseModel\n{\nprivate:\n ::com::sun::star::uno::Any m_aSaveValue;\nprotected:\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();\n\npublic:\n DECLARE_DEFAULT_LEAF_XTOR( ONumericModel );\n\n \/\/ ::com::sun::star::lang::XServiceInfo\n IMPLEMENTATION_NAME(ONumericModel);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw();\n\n \/\/ ::com::sun::star::io::XPersistObject\n virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);\n\n \/\/ OControlModel's property handling\n virtual void describeFixedProperties(\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& \/* [out] *\/ _rProps\n ) const;\n\nprotected:\n \/\/ OBoundControlModel overridables\n virtual ::com::sun::star::uno::Any\n translateDbColumnToControlValue( );\n virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );\n\n virtual ::com::sun::star::uno::Any\n getDefaultForReset() const;\n\n virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );\n\nprotected:\n DECLARE_XCLONEABLE();\n};\n\n\/\/==================================================================\n\/\/= ONumericControl\n\/\/==================================================================\nclass ONumericControl: public OBoundControl\n{\nprotected:\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();\n\npublic:\n ONumericControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);\n\n \/\/ ::com::sun::star::lang::XServiceInfo\n IMPLEMENTATION_NAME(ONumericControl);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw();\n};\n\n\/\/.........................................................................\n} \/\/ namespace frm\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_NUMERIC_HXX_\n\n<commit_msg>INTEGRATION: CWS dba30d (1.10.18); FILE MERGED 2008\/05\/27 12:28:02 fs 1.10.18.1: #i89657# refactoring, so that our binding's getValue is only called when our mutex is not locked<commit_after>\/*************************************************************************\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: Numeric.hxx,v $\n * $Revision: 1.11 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _FORMS_NUMERIC_HXX_\n#define _FORMS_NUMERIC_HXX_\n\n#include \"EditBase.hxx\"\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\n\/\/==================================================================\n\/\/= ONumericModel\n\/\/==================================================================\nclass ONumericModel\n :public OEditBaseModel\n{\nprivate:\n ::com::sun::star::uno::Any m_aSaveValue;\nprotected:\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();\n\npublic:\n DECLARE_DEFAULT_LEAF_XTOR( ONumericModel );\n\n \/\/ ::com::sun::star::lang::XServiceInfo\n IMPLEMENTATION_NAME(ONumericModel);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw();\n\n \/\/ ::com::sun::star::io::XPersistObject\n virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);\n\n \/\/ OControlModel's property handling\n virtual void describeFixedProperties(\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& \/* [out] *\/ _rProps\n ) const;\n\nprotected:\n \/\/ OBoundControlModel overridables\n virtual ::com::sun::star::uno::Any\n translateDbColumnToControlValue( );\n virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );\n\n virtual ::com::sun::star::uno::Any\n getDefaultForReset() const;\n\nprotected:\n DECLARE_XCLONEABLE();\n};\n\n\/\/==================================================================\n\/\/= ONumericControl\n\/\/==================================================================\nclass ONumericControl: public OBoundControl\n{\nprotected:\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();\n\npublic:\n ONumericControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);\n\n \/\/ ::com::sun::star::lang::XServiceInfo\n IMPLEMENTATION_NAME(ONumericControl);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw();\n};\n\n\/\/.........................................................................\n} \/\/ namespace frm\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_NUMERIC_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: levdis.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 17:22:53 $\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 INCLUDED_I18NPOOL_LEVDIS_HXX\n#define INCLUDED_I18NPOOL_LEVDIS_HXX\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n\/*\n maximal X Ersetzungen (User: gefundenes darf X Zeichen anders sein)\n maximal Y Einfuegungen (User: gefundenes darf Y Zeichen kuerzer sein)\n maximal Z Loeschungen (User: gefundenes darf Z Zeichen laenger sein)\n mathematische WLD oder SplitCount (User: strikt oder relaxed)\n\n Joker ('?' und '*') fallen natuerlich nicht unter diese Bedingungen.\n Bei einem '?' wird eine Ersetzung nicht gezahlt, bei einem '*' darf\n der gefundene String an dieser Stelle beliebig viele Zeichen laenger sein.\n\n Strikt: entweder maximal X anders oder Y kuerzer oder Z laenger\n Relaxed: maximal X anders und\/oder Y kuerzer und\/oder Z laenger\n\n Wertebereich fuer X,Y,Z ist 0..33 um mit Limit sicher unter\n 16-bit-signed-int-max zu bleiben, 31*32*33 gibt das Maximum\n KGV(31,32,33) == 32736\n *\/\n\n#define LEVDISDEFAULT_XOTHER 2\n#define LEVDISDEFAULT_YSHORTER 1\n#define LEVDISDEFAULT_ZLONGER 3\n#define LEVDISDEFAULT_RELAXED TRUE\n\n#define LEVDISDEFAULTLIMIT 6 \/\/ default nLimit, passt zu x=2, y=1, z=3,\n \/\/ p=3, q=6, r=2\n#define LEVDISDEFAULT_P0 3 \/\/ default nRepP0, Gewichtung Ersetzen\n#define LEVDISDEFAULT_Q0 6 \/\/ default nInsQ0, Gewichtung Einfuegen\n#define LEVDISDEFAULT_R0 2 \/\/ default nDelR0, Gewichtung Loeschen\n\/*\n Berechnung von angegebenen Userwerten max Ersetzen, Kuerzer, Laenger mittels\n CalcLPQR(). Unschoen: wenn in WLD z.B. nLimit durch nDelR0 erreicht ist\n (String ist nZ laenger als Pattern), kann kein Zeichen mehr ersetzt werden.\n Dies kann durch Erhoehung von nX oder\/und nZ vermieden werden, natuerlich\n mit den entsprechenden Seiteneffekten.. oder aber mit SplitCount (s.u.), was\n der Default bei CalcLPQR() ist.\n\n Achtung: Kuerzer = WLD.Insert, Laenger = WLD.Delete\n\n Gezaehlt wird von String nach Pattern (eine Loeschung bedeutet, dass aus\n String etwas geloescht werden muss, um auf Pattern zu kommen)\n\n Loeschungen zaehlen in diesem Beispiel am wenigsten, da meistens weniger\n bekannt ist, als gesucht wird. Ersetzungen erhalten mittlere Gewichtung\n wegen z.B. falscher Schreibweisen. Einfuegungen werden teuer.\n\n Oder z.B.: P0 = 1, Q0 = 4, R0 = 4, Limit = 3\n Erlaubt sind maximal 4 Ersetzungen, keine Einfuegung, keine Loeschung\n Entspricht den Userangaben X = 3, Y = 0, Z = 0\n\n bSplitCount: wenn TRUE, werden Rep\/Ins\/Del anders gezaehlt. Der\n Rueckgabewert von WLD ist dann nicht mehr unbedingt die Levenshtein-Distanz,\n sondern kann negativ (-WLD) sein, wenn die WLD groesser als nLimit ist, aber\n die Einzelwerte jeweils innerhalb der Grenzen liegen.\n Bei den Default-Werten hiesse das z.B.: auch wenn der gefundene String 2\n Zeichen laenger ist (nLongerZ), koennen noch 3 Ersetzungen (nOtherX)\n erfolgen. Zusatz-Gimmick: Buchstabendreher zaehlen als eine Ersetzung.\n Mathematisch voellig unkorrekt, aber gut fuer den User ;-)\n\n Zur Erlaeuterung: bei der echten WLD schoepfen alle Aktionen aus einem\n gemeinsamen 100%-Pool, wenn einer alles hat, ist fuer die anderen nichts\n mehr da. Mit bSplitCount hat Replace sein eigenes Wildwasser..\n *\/\n\nclass WLevDisPatternMem \/\/ \"sichere\" Speicheranforderung im cTor\n{\n sal_Unicode *cp;\n bool *bp;\npublic:\n WLevDisPatternMem( sal_Int32 s ) { cp = new sal_Unicode[ s ];\n bp = new bool[ s ];\n }\n ~WLevDisPatternMem() { if (cp) delete [] cp;\n if (bp) delete [] bp;\n }\n sal_Unicode* GetcPtr() const { return cp; }\n bool* GetbPtr() const { return bp; }\n};\n\nclass WLevDisDistanceMem\n{\n int* p;\npublic:\n WLevDisDistanceMem( size_t s ) { p = 0; NewMem(s); }\n ~WLevDisDistanceMem() { if (p) delete [] p; }\n int* GetPtr() const { return p; }\n int* NewMem( size_t s ) { if (p) delete [] p;\n return (p = new int[ s<3 ? 3 : s ]);\n }\n};\n\nclass WLevDistance\n{\n sal_Int32 nPatternLen; \/\/ Laenge des Pattern\n WLevDisPatternMem aPatMem; \/\/ Verwaltung des Pattern Arrays\n sal_Unicode* cpPattern; \/\/ Pointer auf Pattern Array\n bool* bpPatIsWild; \/\/ Pointer auf bool Array, ob Pattern Wildcard ist\n sal_Int32 nArrayLen; \/\/ Laenge des Distanz Arrays\n WLevDisDistanceMem aDisMem; \/\/ Verwaltung des Distanz Arrays\n int* npDistance; \/\/ Pointer auf Distanz Array\n int nLimit; \/\/ WLD Limit Ersetzungen\/Einfuegungen\/Loeschungen\n int nRepP0; \/\/ Ersetzen Gewichtung\n int nInsQ0; \/\/ Einfuegen Gewichtung\n int nDelR0; \/\/ Loeschen Gewichtung\n int nStars; \/\/ Anzahl '*' Joker im Pattern\n bool bSplitCount; \/\/ wenn TRUE, werden Rep\/Ins\/Del getrennt gezaehlt\n\n void InitData( const sal_Unicode* cPattern ); \/\/ fuer die CToren\n inline int Min3( int x, int y, int z ); \/\/ inline wegen Schleife\n int Mid3( int x, int y, int z );\n int Max3( int x, int y, int z );\n int GGT( int a, int b ); \/\/ Groesster Gemeinsamer Teiler\n int KGV( int a, int b ); \/\/ Kleinstes Gemeinsames Vielfaches\n\npublic:\n \/\/ CToren fuer direktes Setzen der Gewichtung mit Set...()\n \/\/ im CTor werden die Defaultwerte fuer Limit\/Rep\/Ins\/Del gesetzt\n WLevDistance( const sal_Unicode* cPattern );\n WLevDistance( const ::rtl::OUString& rPattern );\n\n \/\/ CToren mit Userangaben, danach mit GetLimit() Limit holen\n \/\/ interner Aufruf von CalcLPQR()\n \/\/ die mathematisch unkorrekte Berechnung wird als Default genommen!\n WLevDistance( const sal_Unicode* cPattern, int nOtherX, int nShorterY,\n int nLongerZ, bool bRelaxed = true );\n\n WLevDistance( const WLevDistance& rWLD );\n ~WLevDistance();\n\n \/\/ Berechnung der Levenshtein-Distanz von String zu Pattern\n int WLD( const sal_Unicode* cString, sal_Int32 nStringLen ); \/\/ prefered\n int WLD( const sal_Unicode* cString );\n int WLD( const ::rtl::OUString& rString );\n\n \/\/ Berechnung der Gewichtung aus Userangaben, return nLimit\n int CalcLPQR( int nOtherX, int nShorterY, int nLongerZ,\n bool bRelaxed = true );\n\n inline int GetLimit() const { return( nLimit ); } \/\/ Limit holen\n inline int GetReplaceP0() const { return( nRepP0 ); } \/\/ Gewichtungen holen\n inline int GetInsertQ0() const { return( nInsQ0 ); }\n inline int GetDeleteR0() const { return( nDelR0 ); }\n inline bool GetSplit() const { return( bSplitCount ); }\n inline int SetLimit( int nNewLimit ); \/\/ Limit setzen,\n inline int SetReplaceP0( int nNewP0 ); \/\/ Gewichtungen setzen,\n inline int SetInsertQ0( int nNewQ0 ); \/\/ returnen bisherigen Wert\n inline int SetDeleteR0( int nNewR0 );\n inline bool SetSplit( bool bNewSplit );\n \/\/ SetSplit( TRUE ) macht nur mit Werten nach CalcLPQR() Sinn!\n\n inline bool IsNormal( sal_Int32 nPos ) const { return( !bpPatIsWild[nPos] ); }\n\n#ifdef erTEST\n void ShowTest();\n#ifdef erTESTMAT\n void ShowMatrix( const char* cString );\n#endif\n#endif\n\n};\n\ninline int WLevDistance::SetLimit( int nNewLimit )\n{\n int nTmp = nLimit;\n nLimit = nNewLimit;\n return( nTmp );\n}\n\ninline int WLevDistance::SetReplaceP0( int nNewP0 )\n{\n int nTmp = nRepP0;\n nRepP0 = nNewP0;\n return( nTmp );\n}\n\ninline int WLevDistance::SetInsertQ0( int nNewQ0 )\n{\n int nTmp = nInsQ0;\n nInsQ0 = nNewQ0;\n return( nTmp );\n}\n\ninline int WLevDistance::SetDeleteR0( int nNewR0 )\n{\n int nTmp = nDelR0;\n nDelR0 = nNewR0;\n return( nTmp );\n}\n\ninline bool WLevDistance::SetSplit( bool bNewSplit )\n{\n bool bTmp = bSplitCount;\n bSplitCount = bNewSplit;\n return( bTmp );\n}\n\n#endif \/\/ _LEVDIS_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.216); FILE MERGED 2008\/04\/01 15:20:08 thb 1.3.216.2: #i85898# Stripping all external header guards 2008\/03\/31 16:01:29 rt 1.3.216.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: levdis.hxx,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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_I18NPOOL_LEVDIS_HXX\n#define INCLUDED_I18NPOOL_LEVDIS_HXX\n\n#include <rtl\/ustring.hxx>\n\n\/*\n maximal X Ersetzungen (User: gefundenes darf X Zeichen anders sein)\n maximal Y Einfuegungen (User: gefundenes darf Y Zeichen kuerzer sein)\n maximal Z Loeschungen (User: gefundenes darf Z Zeichen laenger sein)\n mathematische WLD oder SplitCount (User: strikt oder relaxed)\n\n Joker ('?' und '*') fallen natuerlich nicht unter diese Bedingungen.\n Bei einem '?' wird eine Ersetzung nicht gezahlt, bei einem '*' darf\n der gefundene String an dieser Stelle beliebig viele Zeichen laenger sein.\n\n Strikt: entweder maximal X anders oder Y kuerzer oder Z laenger\n Relaxed: maximal X anders und\/oder Y kuerzer und\/oder Z laenger\n\n Wertebereich fuer X,Y,Z ist 0..33 um mit Limit sicher unter\n 16-bit-signed-int-max zu bleiben, 31*32*33 gibt das Maximum\n KGV(31,32,33) == 32736\n *\/\n\n#define LEVDISDEFAULT_XOTHER 2\n#define LEVDISDEFAULT_YSHORTER 1\n#define LEVDISDEFAULT_ZLONGER 3\n#define LEVDISDEFAULT_RELAXED TRUE\n\n#define LEVDISDEFAULTLIMIT 6 \/\/ default nLimit, passt zu x=2, y=1, z=3,\n \/\/ p=3, q=6, r=2\n#define LEVDISDEFAULT_P0 3 \/\/ default nRepP0, Gewichtung Ersetzen\n#define LEVDISDEFAULT_Q0 6 \/\/ default nInsQ0, Gewichtung Einfuegen\n#define LEVDISDEFAULT_R0 2 \/\/ default nDelR0, Gewichtung Loeschen\n\/*\n Berechnung von angegebenen Userwerten max Ersetzen, Kuerzer, Laenger mittels\n CalcLPQR(). Unschoen: wenn in WLD z.B. nLimit durch nDelR0 erreicht ist\n (String ist nZ laenger als Pattern), kann kein Zeichen mehr ersetzt werden.\n Dies kann durch Erhoehung von nX oder\/und nZ vermieden werden, natuerlich\n mit den entsprechenden Seiteneffekten.. oder aber mit SplitCount (s.u.), was\n der Default bei CalcLPQR() ist.\n\n Achtung: Kuerzer = WLD.Insert, Laenger = WLD.Delete\n\n Gezaehlt wird von String nach Pattern (eine Loeschung bedeutet, dass aus\n String etwas geloescht werden muss, um auf Pattern zu kommen)\n\n Loeschungen zaehlen in diesem Beispiel am wenigsten, da meistens weniger\n bekannt ist, als gesucht wird. Ersetzungen erhalten mittlere Gewichtung\n wegen z.B. falscher Schreibweisen. Einfuegungen werden teuer.\n\n Oder z.B.: P0 = 1, Q0 = 4, R0 = 4, Limit = 3\n Erlaubt sind maximal 4 Ersetzungen, keine Einfuegung, keine Loeschung\n Entspricht den Userangaben X = 3, Y = 0, Z = 0\n\n bSplitCount: wenn TRUE, werden Rep\/Ins\/Del anders gezaehlt. Der\n Rueckgabewert von WLD ist dann nicht mehr unbedingt die Levenshtein-Distanz,\n sondern kann negativ (-WLD) sein, wenn die WLD groesser als nLimit ist, aber\n die Einzelwerte jeweils innerhalb der Grenzen liegen.\n Bei den Default-Werten hiesse das z.B.: auch wenn der gefundene String 2\n Zeichen laenger ist (nLongerZ), koennen noch 3 Ersetzungen (nOtherX)\n erfolgen. Zusatz-Gimmick: Buchstabendreher zaehlen als eine Ersetzung.\n Mathematisch voellig unkorrekt, aber gut fuer den User ;-)\n\n Zur Erlaeuterung: bei der echten WLD schoepfen alle Aktionen aus einem\n gemeinsamen 100%-Pool, wenn einer alles hat, ist fuer die anderen nichts\n mehr da. Mit bSplitCount hat Replace sein eigenes Wildwasser..\n *\/\n\nclass WLevDisPatternMem \/\/ \"sichere\" Speicheranforderung im cTor\n{\n sal_Unicode *cp;\n bool *bp;\npublic:\n WLevDisPatternMem( sal_Int32 s ) { cp = new sal_Unicode[ s ];\n bp = new bool[ s ];\n }\n ~WLevDisPatternMem() { if (cp) delete [] cp;\n if (bp) delete [] bp;\n }\n sal_Unicode* GetcPtr() const { return cp; }\n bool* GetbPtr() const { return bp; }\n};\n\nclass WLevDisDistanceMem\n{\n int* p;\npublic:\n WLevDisDistanceMem( size_t s ) { p = 0; NewMem(s); }\n ~WLevDisDistanceMem() { if (p) delete [] p; }\n int* GetPtr() const { return p; }\n int* NewMem( size_t s ) { if (p) delete [] p;\n return (p = new int[ s<3 ? 3 : s ]);\n }\n};\n\nclass WLevDistance\n{\n sal_Int32 nPatternLen; \/\/ Laenge des Pattern\n WLevDisPatternMem aPatMem; \/\/ Verwaltung des Pattern Arrays\n sal_Unicode* cpPattern; \/\/ Pointer auf Pattern Array\n bool* bpPatIsWild; \/\/ Pointer auf bool Array, ob Pattern Wildcard ist\n sal_Int32 nArrayLen; \/\/ Laenge des Distanz Arrays\n WLevDisDistanceMem aDisMem; \/\/ Verwaltung des Distanz Arrays\n int* npDistance; \/\/ Pointer auf Distanz Array\n int nLimit; \/\/ WLD Limit Ersetzungen\/Einfuegungen\/Loeschungen\n int nRepP0; \/\/ Ersetzen Gewichtung\n int nInsQ0; \/\/ Einfuegen Gewichtung\n int nDelR0; \/\/ Loeschen Gewichtung\n int nStars; \/\/ Anzahl '*' Joker im Pattern\n bool bSplitCount; \/\/ wenn TRUE, werden Rep\/Ins\/Del getrennt gezaehlt\n\n void InitData( const sal_Unicode* cPattern ); \/\/ fuer die CToren\n inline int Min3( int x, int y, int z ); \/\/ inline wegen Schleife\n int Mid3( int x, int y, int z );\n int Max3( int x, int y, int z );\n int GGT( int a, int b ); \/\/ Groesster Gemeinsamer Teiler\n int KGV( int a, int b ); \/\/ Kleinstes Gemeinsames Vielfaches\n\npublic:\n \/\/ CToren fuer direktes Setzen der Gewichtung mit Set...()\n \/\/ im CTor werden die Defaultwerte fuer Limit\/Rep\/Ins\/Del gesetzt\n WLevDistance( const sal_Unicode* cPattern );\n WLevDistance( const ::rtl::OUString& rPattern );\n\n \/\/ CToren mit Userangaben, danach mit GetLimit() Limit holen\n \/\/ interner Aufruf von CalcLPQR()\n \/\/ die mathematisch unkorrekte Berechnung wird als Default genommen!\n WLevDistance( const sal_Unicode* cPattern, int nOtherX, int nShorterY,\n int nLongerZ, bool bRelaxed = true );\n\n WLevDistance( const WLevDistance& rWLD );\n ~WLevDistance();\n\n \/\/ Berechnung der Levenshtein-Distanz von String zu Pattern\n int WLD( const sal_Unicode* cString, sal_Int32 nStringLen ); \/\/ prefered\n int WLD( const sal_Unicode* cString );\n int WLD( const ::rtl::OUString& rString );\n\n \/\/ Berechnung der Gewichtung aus Userangaben, return nLimit\n int CalcLPQR( int nOtherX, int nShorterY, int nLongerZ,\n bool bRelaxed = true );\n\n inline int GetLimit() const { return( nLimit ); } \/\/ Limit holen\n inline int GetReplaceP0() const { return( nRepP0 ); } \/\/ Gewichtungen holen\n inline int GetInsertQ0() const { return( nInsQ0 ); }\n inline int GetDeleteR0() const { return( nDelR0 ); }\n inline bool GetSplit() const { return( bSplitCount ); }\n inline int SetLimit( int nNewLimit ); \/\/ Limit setzen,\n inline int SetReplaceP0( int nNewP0 ); \/\/ Gewichtungen setzen,\n inline int SetInsertQ0( int nNewQ0 ); \/\/ returnen bisherigen Wert\n inline int SetDeleteR0( int nNewR0 );\n inline bool SetSplit( bool bNewSplit );\n \/\/ SetSplit( TRUE ) macht nur mit Werten nach CalcLPQR() Sinn!\n\n inline bool IsNormal( sal_Int32 nPos ) const { return( !bpPatIsWild[nPos] ); }\n\n#ifdef erTEST\n void ShowTest();\n#ifdef erTESTMAT\n void ShowMatrix( const char* cString );\n#endif\n#endif\n\n};\n\ninline int WLevDistance::SetLimit( int nNewLimit )\n{\n int nTmp = nLimit;\n nLimit = nNewLimit;\n return( nTmp );\n}\n\ninline int WLevDistance::SetReplaceP0( int nNewP0 )\n{\n int nTmp = nRepP0;\n nRepP0 = nNewP0;\n return( nTmp );\n}\n\ninline int WLevDistance::SetInsertQ0( int nNewQ0 )\n{\n int nTmp = nInsQ0;\n nInsQ0 = nNewQ0;\n return( nTmp );\n}\n\ninline int WLevDistance::SetDeleteR0( int nNewR0 )\n{\n int nTmp = nDelR0;\n nDelR0 = nNewR0;\n return( nTmp );\n}\n\ninline bool WLevDistance::SetSplit( bool bNewSplit )\n{\n bool bTmp = bSplitCount;\n bSplitCount = bNewSplit;\n return( bTmp );\n}\n\n#endif \/\/ _LEVDIS_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file rvo_planner.cpp\n * @brief RVO Planner class\n * @author Alejandro Bordallo <alex.bordallo@ed.ac.uk>\n * @date 2015-06-30\n * @copyright (MIT) 2015 Edinferno\n *\/\n\n#include <planner\/rvo_planner.hpp>\n\nRVOPlanner::RVOPlanner(ros::NodeHandle* nh) {\n nh_ = nh;\n this->rosSetup();\n this->createPlanner();\n}\n\nRVOPlanner::~RVOPlanner() {;}\n\nvoid RVOPlanner::init() {\n PLANNER_ROBOT_ = 0;\n planner_settings_.request.sim_num = 0;\n planner_settings_.request.time_step = 0.1f;\n planner_settings_.request.defaults.neighbor_dist = 2.0f;\n planner_settings_.request.defaults.max_neighbors = 20;\n planner_settings_.request.defaults.time_horizon_agent = 5.0f;\n planner_settings_.request.defaults.time_horizon_obst = 5.0f;\n planner_settings_.request.defaults.radius = 0.5f;\n planner_settings_.request.defaults.max_speed = 0.3f;\n}\n\nvoid RVOPlanner::rosSetup() {\n ros::service::waitForService(\"\/rvo_wrapper\/add_agent\");\n ros::service::waitForService(\"\/rvo_wrapper\/check_reached_goal\");\n ros::service::waitForService(\"\/rvo_wrapper\/calc_pref_velocities\");\n ros::service::waitForService(\"\/rvo_wrapper\/create_rvosim\");\n ros::service::waitForService(\"\/rvo_wrapper\/do_step\");\n ros::service::waitForService(\"\/rvo_wrapper\/get_agent_position\");\n ros::service::waitForService(\"\/rvo_wrapper\/get_agent_velocity\");\n ros::service::waitForService(\"\/rvo_wrapper\/get_num_agents\");\n ros::service::waitForService(\"\/rvo_wrapper\/set_agent_goals\");\n ros::service::waitForService(\"\/rvo_wrapper\/set_agent_defaults\");\n ros::service::waitForService(\"\/rvo_wrapper\/set_agent_position\");\n ros::service::waitForService(\"\/rvo_wrapper\/set_time_step\");\n add_planner_agent_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::AddAgent>(\n \"\/rvo_wrapper\/add_agent\", true);\n check_reached_goal_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::CheckReachedGoal>(\n \"\/rvo_wrapper\/check_reached_goal\", true);\n calc_pref_velocities_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::CalcPrefVelocities>(\n \"\/rvo_wrapper\/calc_pref_velocities\", true);\n create_planner_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::CreateRVOSim>(\n \"\/rvo_wrapper\/create_rvosim\", true);\n do_planner_step_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::DoStep>(\n \"\/rvo_wrapper\/do_step\", true);\n get_agent_pos_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::GetAgentPosition>(\n \"\/rvo_wrapper\/get_agent_position\", true);\n get_agent_vel_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::GetAgentVelocity>(\n \"\/rvo_wrapper\/get_agent_velocity\", true);\n get_num_agents_ =\n nh_->serviceClient<rvo_wrapper_msgs::GetNumAgents>(\n \"\/rvo_wrapper\/get_num_agents\", true);\n set_agent_goals_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::SetAgentGoals>(\n \"\/rvo_wrapper\/set_agent_goals\", true);\n set_agent_defaults_ =\n nh_->serviceClient<rvo_wrapper_msgs::SetAgentDefaults>(\n \"\/rvo_wrapper\/set_agent_defaults\", true);\n set_agent_position_ =\n nh_->serviceClient<rvo_wrapper_msgs::SetAgentPosition>(\n \"\/rvo_wrapper\/set_agent_position\", true);\n set_time_step_ =\n nh_->serviceClient<rvo_wrapper_msgs::SetTimeStep>(\n \"\/rvo_wrapper\/set_time_step\", true);\n}\n\nsize_t RVOPlanner::addPlannerAgent(common_msgs::Vector2 agent_pos) {\n rvo_wrapper_msgs::AddAgent msg;\n msg.request.position = agent_pos;\n add_planner_agent_client_.call(msg);\n return msg.response.agent_id;\n}\n\nvoid RVOPlanner::calcPrefVelocities() {\n rvo_wrapper_msgs::CalcPrefVelocities msg;\n calc_pref_velocities_client_.call(msg);\n}\n\nbool RVOPlanner::checkReachedGoal() {\n rvo_wrapper_msgs::CheckReachedGoal msg;\n check_reached_goal_client_.call(msg);\n return msg.response.reached;\n}\n\nvoid RVOPlanner::createPlanner() {\n create_planner_client_.call(planner_settings_);\n if (planner_settings_.response.res) {\n ROS_INFO(\"Planner created\");\n } else { ROS_ERROR(\"Planner not created!\"); };\n}\n\nvoid RVOPlanner::doSimStep() {\n rvo_wrapper_msgs::DoStep msg;\n do_planner_step_client_.call(msg);\n}\n\ncommon_msgs::Vector2 RVOPlanner::getAgentPos(size_t agent_no) {\n rvo_wrapper_msgs::GetAgentPosition msg;\n msg.request.agent_id = agent_no;\n get_agent_pos_client_.call(msg);\n return msg.response.position;\n}\n\nvoid RVOPlanner::setPlannerGoal(common_msgs::Vector2 goal) {\n rvo_wrapper_msgs::GetNumAgents num_agents_msg;\n get_num_agents_.call(num_agents_msg);\n rvo_wrapper_msgs::SetAgentGoals agent_goal_msg;\n rvo_wrapper_msgs::SimGoals empty;\n agent_goal_msg.request.sim.push_back(empty);\n for (uint32_t i = 0; i < num_agents_msg.response.num_agents; ++i) {\n agent_goal_msg.request.sim[0].agent.push_back(goal);\n }\n set_agent_goals_client_.call(agent_goal_msg);\n}\n\nvoid RVOPlanner::setPlannerSettings(float time_step,\n rvo_wrapper_msgs::AgentDefaults defaults) {\n \/\/ Save for new planner generation\n planner_settings_.request.time_step = time_step;\n planner_settings_.request.defaults.neighbor_dist = defaults.neighbor_dist;\n planner_settings_.request.defaults.max_neighbors = defaults.max_neighbors;\n planner_settings_.request.defaults.time_horizon_agent =\n defaults.time_horizon_agent;\n planner_settings_.request.defaults.time_horizon_obst =\n defaults.time_horizon_obst;\n planner_settings_.request.defaults.radius = defaults.radius;\n planner_settings_.request.defaults.max_speed = defaults.max_speed;\n \/\/ Set new planner settings\n rvo_wrapper_msgs::SetTimeStep planner_time_step;\n \/\/ planner_time_step.request.sim_ids = planner_settings_.request.sim_num;\n planner_time_step.request.time_step = planner_settings_.request.time_step;\n set_time_step_.call(planner_time_step);\n rvo_wrapper_msgs::SetAgentDefaults agent_defaults;\n \/\/ agent_defaults.request.sim_ids = planner_settings_.request.sim_num;\n agent_defaults.request.defaults = planner_settings_.request.defaults;\n set_agent_defaults_.call(agent_defaults);\n}\n\nvoid RVOPlanner::planStep() {\n this->calcPrefVelocities();\n this->doSimStep();\n}\n\ncommon_msgs::Vector2 RVOPlanner::getPlannerVel() {\n rvo_wrapper_msgs::GetAgentVelocity msg;\n msg.request.agent_id = PLANNER_ROBOT_;\n get_agent_vel_client_.call(msg);\n if (!msg.response.res) {\n msg.response.velocity.x = 0.0f;\n msg.response.velocity.y = 0.0f;\n }\n return msg.response.velocity;\n}\n\nvoid RVOPlanner::setCurrPose(common_msgs::Vector2 curr_pose) {\n rvo_wrapper_msgs::SetAgentPosition msg;\n msg.request.agent_id = PLANNER_ROBOT_;\n msg.request.position.x = curr_pose.x;\n msg.request.position.y = curr_pose.y;\n set_agent_position_.call(msg);\n}\n<commit_msg>Fix initialisation of rvo_planner<commit_after>\/**\n * @file rvo_planner.cpp\n * @brief RVO Planner class\n * @author Alejandro Bordallo <alex.bordallo@ed.ac.uk>\n * @date 2015-06-30\n * @copyright (MIT) 2015 Edinferno\n *\/\n\n#include <planner\/rvo_planner.hpp>\n\nRVOPlanner::RVOPlanner(ros::NodeHandle* nh) {\n nh_ = nh;\n this->init();\n this->rosSetup();\n this->createPlanner();\n}\n\nRVOPlanner::~RVOPlanner() {;}\n\nvoid RVOPlanner::init() {\n PLANNER_ROBOT_ = 0;\n planner_settings_.request.sim_num = 0;\n planner_settings_.request.time_step = 0.1f;\n planner_settings_.request.defaults.neighbor_dist = 2.0f;\n planner_settings_.request.defaults.max_neighbors = 20;\n planner_settings_.request.defaults.time_horizon_agent = 5.0f;\n planner_settings_.request.defaults.time_horizon_obst = 5.0f;\n planner_settings_.request.defaults.radius = 0.5f;\n planner_settings_.request.defaults.max_speed = 0.3f;\n}\n\nvoid RVOPlanner::rosSetup() {\n ros::service::waitForService(\"\/rvo_wrapper\/add_agent\");\n ros::service::waitForService(\"\/rvo_wrapper\/check_reached_goal\");\n ros::service::waitForService(\"\/rvo_wrapper\/calc_pref_velocities\");\n ros::service::waitForService(\"\/rvo_wrapper\/create_rvosim\");\n ros::service::waitForService(\"\/rvo_wrapper\/do_step\");\n ros::service::waitForService(\"\/rvo_wrapper\/get_agent_position\");\n ros::service::waitForService(\"\/rvo_wrapper\/get_agent_velocity\");\n ros::service::waitForService(\"\/rvo_wrapper\/get_num_agents\");\n ros::service::waitForService(\"\/rvo_wrapper\/set_agent_goals\");\n ros::service::waitForService(\"\/rvo_wrapper\/set_agent_defaults\");\n ros::service::waitForService(\"\/rvo_wrapper\/set_agent_position\");\n ros::service::waitForService(\"\/rvo_wrapper\/set_time_step\");\n add_planner_agent_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::AddAgent>(\n \"\/rvo_wrapper\/add_agent\", true);\n check_reached_goal_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::CheckReachedGoal>(\n \"\/rvo_wrapper\/check_reached_goal\", true);\n calc_pref_velocities_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::CalcPrefVelocities>(\n \"\/rvo_wrapper\/calc_pref_velocities\", true);\n create_planner_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::CreateRVOSim>(\n \"\/rvo_wrapper\/create_rvosim\", true);\n do_planner_step_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::DoStep>(\n \"\/rvo_wrapper\/do_step\", true);\n get_agent_pos_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::GetAgentPosition>(\n \"\/rvo_wrapper\/get_agent_position\", true);\n get_agent_vel_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::GetAgentVelocity>(\n \"\/rvo_wrapper\/get_agent_velocity\", true);\n get_num_agents_ =\n nh_->serviceClient<rvo_wrapper_msgs::GetNumAgents>(\n \"\/rvo_wrapper\/get_num_agents\", true);\n set_agent_goals_client_ =\n nh_->serviceClient<rvo_wrapper_msgs::SetAgentGoals>(\n \"\/rvo_wrapper\/set_agent_goals\", true);\n set_agent_defaults_ =\n nh_->serviceClient<rvo_wrapper_msgs::SetAgentDefaults>(\n \"\/rvo_wrapper\/set_agent_defaults\", true);\n set_agent_position_ =\n nh_->serviceClient<rvo_wrapper_msgs::SetAgentPosition>(\n \"\/rvo_wrapper\/set_agent_position\", true);\n set_time_step_ =\n nh_->serviceClient<rvo_wrapper_msgs::SetTimeStep>(\n \"\/rvo_wrapper\/set_time_step\", true);\n}\n\nsize_t RVOPlanner::addPlannerAgent(common_msgs::Vector2 agent_pos) {\n rvo_wrapper_msgs::AddAgent msg;\n msg.request.position = agent_pos;\n add_planner_agent_client_.call(msg);\n return msg.response.agent_id;\n}\n\nvoid RVOPlanner::calcPrefVelocities() {\n rvo_wrapper_msgs::CalcPrefVelocities msg;\n calc_pref_velocities_client_.call(msg);\n}\n\nbool RVOPlanner::checkReachedGoal() {\n rvo_wrapper_msgs::CheckReachedGoal msg;\n check_reached_goal_client_.call(msg);\n return msg.response.reached;\n}\n\nvoid RVOPlanner::createPlanner() {\n create_planner_client_.call(planner_settings_);\n if (planner_settings_.response.res) {\n ROS_INFO(\"RVO Planner created\");\n } else { ROS_ERROR(\"Planner not created!\"); };\n}\n\nvoid RVOPlanner::doSimStep() {\n rvo_wrapper_msgs::DoStep msg;\n do_planner_step_client_.call(msg);\n}\n\ncommon_msgs::Vector2 RVOPlanner::getAgentPos(size_t agent_no) {\n rvo_wrapper_msgs::GetAgentPosition msg;\n msg.request.agent_id = agent_no;\n get_agent_pos_client_.call(msg);\n return msg.response.position;\n}\n\nvoid RVOPlanner::setPlannerGoal(common_msgs::Vector2 goal) {\n rvo_wrapper_msgs::GetNumAgents num_agents_msg;\n get_num_agents_.call(num_agents_msg);\n rvo_wrapper_msgs::SetAgentGoals agent_goal_msg;\n rvo_wrapper_msgs::SimGoals empty;\n agent_goal_msg.request.sim.push_back(empty);\n agent_goal_msg.request.sim[0].agent.push_back(goal);\n \/\/ for (uint32_t i = 0; i < num_agents_msg.response.num_agents; ++i) {\n \/\/ agent_goal_msg.request.sim[0].agent.push_back(goal);\n \/\/ }\n set_agent_goals_client_.call(agent_goal_msg);\n}\n\nvoid RVOPlanner::setPlannerSettings(float time_step,\n rvo_wrapper_msgs::AgentDefaults defaults) {\n \/\/ Save for new planner generation\n planner_settings_.request.time_step = time_step;\n planner_settings_.request.defaults.neighbor_dist = defaults.neighbor_dist;\n planner_settings_.request.defaults.max_neighbors = defaults.max_neighbors;\n planner_settings_.request.defaults.time_horizon_agent =\n defaults.time_horizon_agent;\n planner_settings_.request.defaults.time_horizon_obst =\n defaults.time_horizon_obst;\n planner_settings_.request.defaults.radius = defaults.radius;\n planner_settings_.request.defaults.max_speed = defaults.max_speed;\n \/\/ Set new planner settings\n rvo_wrapper_msgs::SetTimeStep planner_time_step;\n \/\/ planner_time_step.request.sim_ids = planner_settings_.request.sim_num;\n planner_time_step.request.time_step = planner_settings_.request.time_step;\n set_time_step_.call(planner_time_step);\n rvo_wrapper_msgs::SetAgentDefaults agent_defaults;\n \/\/ agent_defaults.request.sim_ids = planner_settings_.request.sim_num;\n agent_defaults.request.defaults = planner_settings_.request.defaults;\n set_agent_defaults_.call(agent_defaults);\n}\n\nvoid RVOPlanner::planStep() {\n ROS_INFO(\"rvo_planner plan_step\");\n \/\/ this->createPlanner();\n \/\/ ROS_INFO(\"rvo_planner create_planner\");\n \/\/ this->setupPlanner();\n \/\/ ROS_INFO(\"rvo_planner setup_planner\");\n this->calcPrefVelocities();\n this->doSimStep();\n}\n\ncommon_msgs::Vector2 RVOPlanner::getPlannerVel() {\n rvo_wrapper_msgs::GetAgentVelocity msg;\n msg.request.agent_id = PLANNER_ROBOT_;\n get_agent_vel_client_.call(msg);\n if (!msg.response.res) {\n msg.response.velocity.x = 0.0f;\n msg.response.velocity.y = 0.0f;\n }\n return msg.response.velocity;\n}\n\nvoid RVOPlanner::setCurrPose(common_msgs::Vector2 curr_pose) {\n rvo_wrapper_msgs::SetAgentPosition msg;\n msg.request.agent_id = PLANNER_ROBOT_;\n msg.request.position.x = curr_pose.x;\n msg.request.position.y = curr_pose.y;\n set_agent_position_.call(msg);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2005 by Volker Krause <vkrause@kde.org>\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; either version 2 of the License, or\n (at your option) any later version.\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US\n*\/\n\n#include \"nntpjobs.h\"\n\n#include \"kngroup.h\"\n#include \"kngroupmanager.h\"\n#include \"knserverinfo.h\"\n#include <kdebug.h>\n#include <klocale.h>\n#include <QDir>\n\n\nKNode::GroupListJob::GroupListJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool incremental ) :\n KNJobData( KNJobData::JTFetchGroups, c, a, i ),\n mIncremental( incremental )\n{\n}\n\nvoid KNode::GroupListJob::execute()\n{\n mGroupList.clear();\n\n KNGroupListData *target = static_cast<KNGroupListData *>( data() );\n\n KUrl destination = baseUrl();\n QStringList query;\n if ( target->getDescriptions )\n query << \"desc=true\";\n if ( mIncremental )\n query << QString( \"since=%1%2%3+000000\" )\n .arg( target->fetchSince.year() % 100, 2, 10, QChar( '0' ) )\n .arg( target->fetchSince.month(), 2, 10, QChar( '0' ) )\n .arg( target->fetchSince.day(), 2, 10, QChar( '0' ) );\n destination.setQuery( query.join( \"&\" ) );\n KIO::Job* job = KIO::listDir( destination, KIO::HideProgressInfo, true );\n connect( job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)),\n SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&)) );\n connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) );\n setupKIOJob( job );\n}\n\nvoid KNode::GroupListJob::slotEntries( KIO::Job * job, const KIO::UDSEntryList & list )\n{\n Q_UNUSED( job );\n KNGroupListData *target = static_cast<KNGroupListData *>( data() );\n\n QString name, desc;\n bool subscribed;\n KNGroup::Status access;\n for( KIO::UDSEntryList::ConstIterator it = list.begin(); it != list.end(); ++it ) {\n access = KNGroup::unknown;\n name = (*it).stringValue( KIO::UDSEntry::UDS_NAME );\n desc = (*it).stringValue( KIO::UDSEntry::UDS_EXTRA );\n\n int value = (*it).numberValue( KIO::UDSEntry::UDS_ACCESS, -1 );\n if ( value != -1 ) {\n if( value & S_IWOTH )\n access = KNGroup::postingAllowed;\n else if ( value & S_IWGRP )\n access = KNGroup::moderated;\n else\n access = KNGroup::readOnly;\n }\n\n if ( name.isEmpty() )\n continue;\n if ( target->subscribed.contains( name ) ) {\n target->subscribed.removeAll( name ); \/\/ group names are unique, we wont find it again anyway...\n subscribed = true;\n } else {\n subscribed = false;\n }\n kDebug() << \"Found group \" << name;\n if ( mIncremental )\n mGroupList.append(KNGroupInfo( name, desc, true, subscribed, access ) );\n else\n target->groups->append(KNGroupInfo( name, desc, false, subscribed, access ) );\n }\n}\n\nvoid KNode::GroupListJob::slotResult( KJob * job )\n{\n if ( job->error() )\n setError( job->error(), job->errorString() );\n else {\n KNGroupListData *target = static_cast<KNGroupListData *>( data() );\n\n \/\/ TODO: use thread weaver here?\n if ( mIncremental ) {\n setStatus( i18n(\"Loading group list from disk...\") );\n if ( !target->readIn( this ) ) {\n setError( KIO::ERR_COULD_NOT_READ, i18n(\"Unable to read the group list file\") );\n emitFinished();\n return;\n }\n target->merge( &mGroupList );\n }\n setStatus( i18n(\"Writing group list to disk...\") );\n\n if ( !target->writeOut() )\n setError( KIO::ERR_COULD_NOT_WRITE, i18n(\"Unable to write the group list file\") );\n }\n\n emitFinished();\n}\n\n\n\nKNode::GroupLoadJob::GroupLoadJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i ) :\n KNJobData( KNJobData::JTLoadGroups, c, a, i )\n{\n}\n\nvoid KNode::GroupLoadJob::execute( )\n{\n KNGroupListData *target = static_cast<KNGroupListData *>( data() );\n\n setStatus( i18n(\"Loading group list from disk...\") );\n \/\/ TODO: use the thread weaver here\n if ( !target->readIn( this ) )\n setError( KIO::ERR_COULD_NOT_READ, i18n(\"Unable to read the group list file\") );\n\n emitFinished();\n}\n\n\n\nKNode::ArticleListJob::ArticleListJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool silent ) :\n KNJobData( JTfetchNewHeaders, c, a, i ),\n mSilent( silent )\n{\n}\n\nvoid KNode::ArticleListJob::execute()\n{\n mArticleList.clear();\n\n KNGroup* target = static_cast<KNGroup*>( data() );\n\n KUrl destination = baseUrl();\n destination.setPath( target->groupname() );\n QStringList query;\n query << \"first=\" + QString::number( target->lastNr() + 1 );\n if ( target->lastNr() <= 0 ) \/\/ first fetch\n query << \"max=\" + QString::number( target->maxFetch() );\n destination.setQuery( query.join( \"&\" ) );\n KIO::Job* job = KIO::listDir( destination, KIO::HideProgressInfo, true );\n connect( job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)),\n SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&)) );\n connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) );\n setupKIOJob( job );\n}\n\nvoid KNode::ArticleListJob::slotEntries( KIO::Job * job, const KIO::UDSEntryList & list )\n{\n Q_UNUSED( job );\n mArticleList += list;\n}\n\nvoid KNode::ArticleListJob::slotResult( KJob * _job )\n{\n Q_ASSERT( mJob == _job );\n KIO::Job *job = static_cast<KIO::Job*>( _job );\n if ( job->error() )\n setError( job->error(), job->errorString() );\n else {\n createProgressItem();\n\n KNGroup* target = static_cast<KNGroup*>( data() );\n target->setLastFetchCount( 0 );\n\n setStatus( i18n(\"Sorting...\") );\n\n if ( job->metaData().contains( \"FirstSerialNumber\" ) ) {\n int firstSerNum = job->metaData()[\"FirstSerialNumber\"].toInt();\n target->setFirstNr( firstSerNum );\n }\n\n target->insortNewHeaders( mArticleList, this );\n\n if ( job->metaData().contains( \"LastSerialNumber\" ) ) {\n int lastSerNum = job->metaData()[\"LastSerialNumber\"].toInt();\n target->setLastNr( lastSerNum );\n }\n }\n\n setComplete();\n\n emitFinished();\n}\n\n\n\nKNode::ArticleFetchJob::ArticleFetchJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool parse ) :\n KNJobData( JTfetchArticle, c, a, i ),\n mParseArticle( parse )\n{\n}\n\nvoid KNode::ArticleFetchJob::execute()\n{\n KNRemoteArticle *target = static_cast<KNRemoteArticle*>( data() );\n QString path = static_cast<KNGroup*>( target->collection() )->groupname();\n\n KUrl url = baseUrl();\n path += QDir::separator();\n\n \/\/ By default, fetch articles by their server-side Id.\n \/\/ (some server does not understand the \"ARTICLE <msg-id>\" command correctly (bug #193550))\n if ( target->articleNumber() != -1 ) {\n path += QString::number( target->articleNumber() );\n } else {\n \/\/ User asked to fetch a message by its msg-id\n path += target->messageID()->as7BitString( false );\n }\n url.setPath( path );\n\n KIO::Job* job = KIO::storedGet( url, KIO::NoReload, KIO::HideProgressInfo );\n connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) );\n setupKIOJob( job );\n}\n\nvoid KNode::ArticleFetchJob::slotResult( KJob * job )\n{\n if ( job->error() )\n setError( job->error(), job->errorString() );\n else {\n KNRemoteArticle *target = static_cast<KNRemoteArticle*>( data() );\n KIO::StoredTransferJob *j = static_cast<KIO::StoredTransferJob*>( job );\n QByteArray buffer = j->data();\n buffer.replace( \"\\r\\n\", \"\\n\" ); \/\/ TODO: do this in the io-slave?\n target->setContent( buffer );\n if ( mParseArticle )\n target->parse();\n }\n\n emitFinished();\n}\n\n\n\nKNode::ArticlePostJob::ArticlePostJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i ) :\n KNJobData( JTpostArticle, c, a, i )\n{\n}\n\nvoid KNode::ArticlePostJob::execute( )\n{\n KNLocalArticle *target = static_cast<KNLocalArticle*>( data() );\n\n KUrl url = baseUrl();\n\n KIO::Job* job = KIO::storedPut( target->encodedContent( true ), url, -1, KIO::Overwrite | KIO::HideProgressInfo );\n connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) );\n setupKIOJob( job );\n}\n\nvoid KNode::ArticlePostJob::slotResult( KJob * job )\n{\n if ( job->error() )\n setError( job->error(), job->errorString() );\n\n emitFinished();\n}\n\n#include \"nntpjobs.moc\"\n<commit_msg>Correctly set the path of the url of ArticleFetchJob<commit_after>\/*\n Copyright (c) 2005 by Volker Krause <vkrause@kde.org>\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; either version 2 of the License, or\n (at your option) any later version.\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US\n*\/\n\n#include \"nntpjobs.h\"\n\n#include \"kngroup.h\"\n#include \"kngroupmanager.h\"\n#include \"knserverinfo.h\"\n#include <kdebug.h>\n#include <klocale.h>\n#include <QDir>\n\n\nKNode::GroupListJob::GroupListJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool incremental ) :\n KNJobData( KNJobData::JTFetchGroups, c, a, i ),\n mIncremental( incremental )\n{\n}\n\nvoid KNode::GroupListJob::execute()\n{\n mGroupList.clear();\n\n KNGroupListData *target = static_cast<KNGroupListData *>( data() );\n\n KUrl destination = baseUrl();\n QStringList query;\n if ( target->getDescriptions )\n query << \"desc=true\";\n if ( mIncremental )\n query << QString( \"since=%1%2%3+000000\" )\n .arg( target->fetchSince.year() % 100, 2, 10, QChar( '0' ) )\n .arg( target->fetchSince.month(), 2, 10, QChar( '0' ) )\n .arg( target->fetchSince.day(), 2, 10, QChar( '0' ) );\n destination.setQuery( query.join( \"&\" ) );\n KIO::Job* job = KIO::listDir( destination, KIO::HideProgressInfo, true );\n connect( job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)),\n SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&)) );\n connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) );\n setupKIOJob( job );\n}\n\nvoid KNode::GroupListJob::slotEntries( KIO::Job * job, const KIO::UDSEntryList & list )\n{\n Q_UNUSED( job );\n KNGroupListData *target = static_cast<KNGroupListData *>( data() );\n\n QString name, desc;\n bool subscribed;\n KNGroup::Status access;\n for( KIO::UDSEntryList::ConstIterator it = list.begin(); it != list.end(); ++it ) {\n access = KNGroup::unknown;\n name = (*it).stringValue( KIO::UDSEntry::UDS_NAME );\n desc = (*it).stringValue( KIO::UDSEntry::UDS_EXTRA );\n\n int value = (*it).numberValue( KIO::UDSEntry::UDS_ACCESS, -1 );\n if ( value != -1 ) {\n if( value & S_IWOTH )\n access = KNGroup::postingAllowed;\n else if ( value & S_IWGRP )\n access = KNGroup::moderated;\n else\n access = KNGroup::readOnly;\n }\n\n if ( name.isEmpty() )\n continue;\n if ( target->subscribed.contains( name ) ) {\n target->subscribed.removeAll( name ); \/\/ group names are unique, we wont find it again anyway...\n subscribed = true;\n } else {\n subscribed = false;\n }\n kDebug() << \"Found group \" << name;\n if ( mIncremental )\n mGroupList.append(KNGroupInfo( name, desc, true, subscribed, access ) );\n else\n target->groups->append(KNGroupInfo( name, desc, false, subscribed, access ) );\n }\n}\n\nvoid KNode::GroupListJob::slotResult( KJob * job )\n{\n if ( job->error() )\n setError( job->error(), job->errorString() );\n else {\n KNGroupListData *target = static_cast<KNGroupListData *>( data() );\n\n \/\/ TODO: use thread weaver here?\n if ( mIncremental ) {\n setStatus( i18n(\"Loading group list from disk...\") );\n if ( !target->readIn( this ) ) {\n setError( KIO::ERR_COULD_NOT_READ, i18n(\"Unable to read the group list file\") );\n emitFinished();\n return;\n }\n target->merge( &mGroupList );\n }\n setStatus( i18n(\"Writing group list to disk...\") );\n\n if ( !target->writeOut() )\n setError( KIO::ERR_COULD_NOT_WRITE, i18n(\"Unable to write the group list file\") );\n }\n\n emitFinished();\n}\n\n\n\nKNode::GroupLoadJob::GroupLoadJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i ) :\n KNJobData( KNJobData::JTLoadGroups, c, a, i )\n{\n}\n\nvoid KNode::GroupLoadJob::execute( )\n{\n KNGroupListData *target = static_cast<KNGroupListData *>( data() );\n\n setStatus( i18n(\"Loading group list from disk...\") );\n \/\/ TODO: use the thread weaver here\n if ( !target->readIn( this ) )\n setError( KIO::ERR_COULD_NOT_READ, i18n(\"Unable to read the group list file\") );\n\n emitFinished();\n}\n\n\n\nKNode::ArticleListJob::ArticleListJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool silent ) :\n KNJobData( JTfetchNewHeaders, c, a, i ),\n mSilent( silent )\n{\n}\n\nvoid KNode::ArticleListJob::execute()\n{\n mArticleList.clear();\n\n KNGroup* target = static_cast<KNGroup*>( data() );\n\n KUrl destination = baseUrl();\n destination.setPath( target->groupname() );\n QStringList query;\n query << \"first=\" + QString::number( target->lastNr() + 1 );\n if ( target->lastNr() <= 0 ) \/\/ first fetch\n query << \"max=\" + QString::number( target->maxFetch() );\n destination.setQuery( query.join( \"&\" ) );\n KIO::Job* job = KIO::listDir( destination, KIO::HideProgressInfo, true );\n connect( job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)),\n SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&)) );\n connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) );\n setupKIOJob( job );\n}\n\nvoid KNode::ArticleListJob::slotEntries( KIO::Job * job, const KIO::UDSEntryList & list )\n{\n Q_UNUSED( job );\n mArticleList += list;\n}\n\nvoid KNode::ArticleListJob::slotResult( KJob * _job )\n{\n Q_ASSERT( mJob == _job );\n KIO::Job *job = static_cast<KIO::Job*>( _job );\n if ( job->error() )\n setError( job->error(), job->errorString() );\n else {\n createProgressItem();\n\n KNGroup* target = static_cast<KNGroup*>( data() );\n target->setLastFetchCount( 0 );\n\n setStatus( i18n(\"Sorting...\") );\n\n if ( job->metaData().contains( \"FirstSerialNumber\" ) ) {\n int firstSerNum = job->metaData()[\"FirstSerialNumber\"].toInt();\n target->setFirstNr( firstSerNum );\n }\n\n target->insortNewHeaders( mArticleList, this );\n\n if ( job->metaData().contains( \"LastSerialNumber\" ) ) {\n int lastSerNum = job->metaData()[\"LastSerialNumber\"].toInt();\n target->setLastNr( lastSerNum );\n }\n }\n\n setComplete();\n\n emitFinished();\n}\n\n\n\nKNode::ArticleFetchJob::ArticleFetchJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool parse ) :\n KNJobData( JTfetchArticle, c, a, i ),\n mParseArticle( parse )\n{\n}\n\nvoid KNode::ArticleFetchJob::execute()\n{\n KNRemoteArticle *target = static_cast<KNRemoteArticle*>( data() );\n\n KUrl url = baseUrl();\n\n url.addPath( static_cast<KNGroup*>( target->collection() )->groupname() );\n\n \/\/ By default, fetch articles by their server-side Id.\n \/\/ (some server does not understand the \"ARTICLE <msg-id>\" command correctly (bug #193550))\n if ( target->articleNumber() != -1 ) {\n url.addPath( QString::number( target->articleNumber() ) );\n } else {\n \/\/ User asked to fetch a message by its msg-id\n url.addPath( target->messageID()->as7BitString( false ) );\n }\n\n KIO::Job* job = KIO::storedGet( url, KIO::NoReload, KIO::HideProgressInfo );\n connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) );\n setupKIOJob( job );\n}\n\nvoid KNode::ArticleFetchJob::slotResult( KJob * job )\n{\n if ( job->error() )\n setError( job->error(), job->errorString() );\n else {\n KNRemoteArticle *target = static_cast<KNRemoteArticle*>( data() );\n KIO::StoredTransferJob *j = static_cast<KIO::StoredTransferJob*>( job );\n QByteArray buffer = j->data();\n buffer.replace( \"\\r\\n\", \"\\n\" ); \/\/ TODO: do this in the io-slave?\n target->setContent( buffer );\n if ( mParseArticle )\n target->parse();\n }\n\n emitFinished();\n}\n\n\n\nKNode::ArticlePostJob::ArticlePostJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i ) :\n KNJobData( JTpostArticle, c, a, i )\n{\n}\n\nvoid KNode::ArticlePostJob::execute( )\n{\n KNLocalArticle *target = static_cast<KNLocalArticle*>( data() );\n\n KUrl url = baseUrl();\n\n KIO::Job* job = KIO::storedPut( target->encodedContent( true ), url, -1, KIO::Overwrite | KIO::HideProgressInfo );\n connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) );\n setupKIOJob( job );\n}\n\nvoid KNode::ArticlePostJob::slotResult( KJob * job )\n{\n if ( job->error() )\n setError( job->error(), job->errorString() );\n\n emitFinished();\n}\n\n#include \"nntpjobs.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"DGKernel.h\"\n#include \"Moose.h\"\n#include \"AsmBlock.h\"\n#include \"MooseVariable.h\"\n#include \"Problem.h\"\n#include \"SubProblem.h\"\n#include \"SystemBase.h\"\n#include \"MaterialData.h\"\n#include \"ParallelUniqueId.h\"\n\n\/\/ libMesh includes\n#include \"dof_map.h\"\n#include \"dense_vector.h\"\n#include \"numeric_vector.h\"\n#include \"dense_subvector.h\"\n#include \"libmesh_common.h\"\n\nconst unsigned int DGKernel::InternalBndId = 123456789;\n\ntemplate<>\nInputParameters validParams<DGKernel>()\n{\n InputParameters params = validParams<MooseObject>();\n params.addRequiredParam<std::string>(\"variable\", \"The name of the variable that this boundary condition applies to\");\n params.addPrivateParam<unsigned int>(\"_boundary_id\", DGKernel::InternalBndId);\n\n params.addPrivateParam<std::string>(\"built_by_action\", \"add_dg_kernel\");\n return params;\n}\n\n\nDGKernel::DGKernel(const std::string & name, InputParameters parameters) :\n MooseObject(name, parameters),\n Coupleable(parameters, false),\n TwoMaterialPropertyInterface(parameters),\n\n _problem(*parameters.get<Problem *>(\"_problem\")),\n _subproblem(*parameters.get<SubProblemInterface *>(\"_subproblem\")),\n _sys(*parameters.get<SystemBase *>(\"_sys\")),\n _tid(parameters.get<THREAD_ID>(\"_tid\")),\n _asmb(_subproblem.asmBlock(_tid)),\n _asm_data(_subproblem.assembly(_tid)),\n _var(_sys.getVariable(_tid, parameters.get<std::string>(\"variable\"))),\n _mesh(_subproblem.mesh()),\n _dim(_mesh.dimension()),\n\n _current_elem(_asm_data.elem()),\n _neighbor_elem(_asm_data.neighbor()),\n\n _current_side(_asm_data.side()),\n _current_side_elem(_asm_data.sideElem()),\n\n _q_point(_subproblem.pointsFace(_tid)),\n _qrule(_subproblem.qRuleFace(_tid)),\n _JxW(_subproblem.JxWFace(_tid)),\n\n _boundary_id(parameters.get<unsigned int>(\"_boundary_id\")),\n\n _u(_var.sln()),\n _u_old(_var.slnOld()),\n _u_older(_var.slnOlder()),\n\n _grad_u(_var.gradSln()),\n _grad_u_old(_var.gradSlnOld()),\n _grad_u_older(_var.gradSlnOlder()),\n\n _second_u(_var.secondSln()),\n _second_u_old(_var.secondSlnOld()),\n _second_u_older(_var.secondSlnOlder()),\n\n _phi(_asmb.phiFace()),\n _grad_phi(_asmb.gradPhiFace()),\n _second_phi(_asmb.secondPhiFace()),\n\n _test(_var.phiFace()),\n _grad_test(_var.gradPhiFace()),\n _second_test(_var.secondPhiFace()),\n\n _normals(_var.normals()),\n\n _phi_neighbor(_asmb.phiFaceNeighbor()),\n _grad_phi_neighbor(_asmb.gradPhiFaceNeighbor()),\n _second_phi_neighbor(_asmb.secondPhiFaceNeighbor()),\n\n _test_neighbor(_var.phiFaceNeighbor()),\n _grad_test_neighbor(_var.gradPhiFaceNeighbor()),\n _second_test_neighbor(_var.secondPhiFaceNeighbor()),\n\n _u_neighbor(_var.slnNeighbor()),\n _u_old_neighbor(_var.slnOldNeighbor()),\n _u_older_neighbor(_var.slnOlderNeighbor()),\n\n _grad_u_neighbor(_var.gradSlnNeighbor()),\n _grad_u_old_neighbor(_var.gradSlnOldNeighbor()),\n _grad_u_older_neighbor(_var.gradSlnOlderNeighbor()),\n\n _second_u_neighbor(_var.secondSlnNeighbor())\n{\n}\n\nDGKernel::~DGKernel()\n{\n}\n\nvoid\nDGKernel::computeResidual()\n{\n Moose::perf_log.push(\"computeResidual()\",\"DGKernel\");\n\n DenseVector<Number> & re = _asmb.residualBlock(_var.number());\n DenseVector<Number> & neighbor_re = _asmb.residualBlockNeighbor(_var.number());\n\n for (_qp=0; _qp<_qrule->n_points(); _qp++)\n {\n for (_i=0; _i<_test.size(); _i++)\n re(_i) += _JxW[_qp]*computeQpResidual(Moose::Element);\n\n for (_i=0; _i<_test_neighbor.size(); _i++)\n neighbor_re(_i) += _JxW[_qp]*computeQpResidual(Moose::Neighbor);\n }\n\n Moose::perf_log.pop(\"computeResidual()\",\"DGKernel\");\n}\n\nvoid\nDGKernel::computeJacobian()\n{\n Moose::perf_log.push(\"computeJacobian()\",\"DGKernel\");\n\n DenseMatrix<Number> & Kee = _asmb.jacobianBlock(_var.number(), _var.number());\n DenseMatrix<Number> & Ken = _asmb.jacobianBlockNeighbor(Moose::ElementElement, _var.number(), _var.number());\n\n DenseMatrix<Number> & Kne = _asmb.jacobianBlockNeighbor(Moose::NeighborElement, _var.number(), _var.number());\n DenseMatrix<Number> & Knn = _asmb.jacobianBlockNeighbor(Moose::NeighborNeighbor, _var.number(), _var.number());\n\n for (_qp=0; _qp<_qrule->n_points(); _qp++)\n {\n for (_i=0; _i<_test.size(); _i++)\n for (_j=0; _j<_phi.size(); _j++)\n Kee(_i,_j) += _JxW[_qp]*computeQpJacobian(Moose::ElementElement);\n\n for (_i=0; _i<_test.size(); _i++)\n for (_j=0; _j<_phi_neighbor.size(); _j++)\n Ken(_i,_j) += _JxW[_qp]*computeQpJacobian(Moose::ElementNeighbor);\n\n for (_i=0; _i<_test_neighbor.size(); _i++)\n for (_j=0; _j<_phi.size(); _j++)\n Kne(_i,_j) += _JxW[_qp]*computeQpJacobian(Moose::NeighborElement);\n\n for (_i=0; _i<_test_neighbor.size(); _i++)\n for (_j=0; _j<_phi_neighbor.size(); _j++)\n Knn(_i,_j) += _JxW[_qp]*computeQpJacobian(Moose::NeighborNeighbor);\n }\n\n Moose::perf_log.pop(\"computeJacobian()\",\"DGKernel\");\n}\n\n\nVariableValue &\nDGKernel::coupledNeighborValue(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->slnNeighbor();\n}\n\n\nVariableValue &\nDGKernel::coupledNeighborValueOld(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->slnOldNeighbor();\n}\n\nVariableValue &\nDGKernel::coupledNeighborValueOlder(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->slnOlderNeighbor();\n}\n\nVariableGradient &\nDGKernel::coupledNeighborGradient(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->gradSlnNeighbor();\n}\n\nVariableGradient &\nDGKernel::coupledNeighborGradientOld(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->gradSlnOldNeighbor();\n}\n\nVariableSecond &\nDGKernel::coupledNeighborSecond(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->secondSlnNeighbor();\n}\n<commit_msg>Fixing #630<commit_after>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"DGKernel.h\"\n#include \"Moose.h\"\n#include \"AsmBlock.h\"\n#include \"MooseVariable.h\"\n#include \"Problem.h\"\n#include \"SubProblem.h\"\n#include \"SystemBase.h\"\n#include \"MaterialData.h\"\n#include \"ParallelUniqueId.h\"\n\n\/\/ libMesh includes\n#include \"dof_map.h\"\n#include \"dense_vector.h\"\n#include \"numeric_vector.h\"\n#include \"dense_subvector.h\"\n#include \"libmesh_common.h\"\n\nconst unsigned int DGKernel::InternalBndId = 123456789;\n\ntemplate<>\nInputParameters validParams<DGKernel>()\n{\n InputParameters params = validParams<MooseObject>();\n params.addRequiredParam<std::string>(\"variable\", \"The name of the variable that this boundary condition applies to\");\n params.addPrivateParam<unsigned int>(\"_boundary_id\", DGKernel::InternalBndId);\n\n params.addPrivateParam<std::string>(\"built_by_action\", \"add_dg_kernel\");\n return params;\n}\n\n\nDGKernel::DGKernel(const std::string & name, InputParameters parameters) :\n MooseObject(name, parameters),\n Coupleable(parameters, false),\n TwoMaterialPropertyInterface(parameters),\n\n _problem(*parameters.get<Problem *>(\"_problem\")),\n _subproblem(*parameters.get<SubProblemInterface *>(\"_subproblem\")),\n _sys(*parameters.get<SystemBase *>(\"_sys\")),\n _tid(parameters.get<THREAD_ID>(\"_tid\")),\n _asmb(_subproblem.asmBlock(_tid)),\n _asm_data(_subproblem.assembly(_tid)),\n _var(_sys.getVariable(_tid, parameters.get<std::string>(\"variable\"))),\n _mesh(_subproblem.mesh()),\n _dim(_mesh.dimension()),\n\n _current_elem(_asm_data.elem()),\n _neighbor_elem(_asm_data.neighbor()),\n\n _current_side(_asm_data.side()),\n _current_side_elem(_asm_data.sideElem()),\n\n _q_point(_subproblem.pointsFace(_tid)),\n _qrule(_subproblem.qRuleFace(_tid)),\n _JxW(_subproblem.JxWFace(_tid)),\n\n _boundary_id(parameters.get<unsigned int>(\"_boundary_id\")),\n\n _u(_var.sln()),\n _u_old(_var.slnOld()),\n _u_older(_var.slnOlder()),\n\n _grad_u(_var.gradSln()),\n _grad_u_old(_var.gradSlnOld()),\n _grad_u_older(_var.gradSlnOlder()),\n\n _second_u(_var.secondSln()),\n _second_u_old(_var.secondSlnOld()),\n _second_u_older(_var.secondSlnOlder()),\n\n _phi(_asmb.phiFace()),\n _grad_phi(_asmb.gradPhiFace()),\n _second_phi(_asmb.secondPhiFace()),\n\n _test(_var.phiFace()),\n _grad_test(_var.gradPhiFace()),\n _second_test(_var.secondPhiFace()),\n\n _normals(_var.normals()),\n\n _phi_neighbor(_asmb.phiFaceNeighbor()),\n _grad_phi_neighbor(_asmb.gradPhiFaceNeighbor()),\n _second_phi_neighbor(_asmb.secondPhiFaceNeighbor()),\n\n _test_neighbor(_var.phiFaceNeighbor()),\n _grad_test_neighbor(_var.gradPhiFaceNeighbor()),\n _second_test_neighbor(_var.secondPhiFaceNeighbor()),\n\n _u_neighbor(_var.slnNeighbor()),\n _u_old_neighbor(_var.slnOldNeighbor()),\n _u_older_neighbor(_var.slnOlderNeighbor()),\n\n _grad_u_neighbor(_var.gradSlnNeighbor()),\n _grad_u_old_neighbor(_var.gradSlnOldNeighbor()),\n _grad_u_older_neighbor(_var.gradSlnOlderNeighbor()),\n\n _second_u_neighbor(_var.secondSlnNeighbor())\n{\n}\n\nDGKernel::~DGKernel()\n{\n}\n\nvoid\nDGKernel::computeResidual()\n{\n Moose::perf_log.push(\"computeResidual()\",\"DGKernel\");\n\n DenseVector<Number> & re = _asmb.residualBlock(_var.number());\n DenseVector<Number> & neighbor_re = _asmb.residualBlockNeighbor(_var.number());\n\n for (_qp=0; _qp<_qrule->n_points(); _qp++)\n {\n for (_i=0; _i<_test.size(); _i++)\n re(_i) += _JxW[_qp]*computeQpResidual(Moose::Element);\n\n for (_i=0; _i<_test_neighbor.size(); _i++)\n neighbor_re(_i) += _JxW[_qp]*computeQpResidual(Moose::Neighbor);\n }\n\n Moose::perf_log.pop(\"computeResidual()\",\"DGKernel\");\n}\n\nvoid\nDGKernel::computeJacobian()\n{\n Moose::perf_log.push(\"computeJacobian()\",\"DGKernel\");\n\n DenseMatrix<Number> & Kee = _asmb.jacobianBlock(_var.number(), _var.number());\n DenseMatrix<Number> & Ken = _asmb.jacobianBlockNeighbor(Moose::ElementNeighbor, _var.number(), _var.number());\n\n DenseMatrix<Number> & Kne = _asmb.jacobianBlockNeighbor(Moose::NeighborElement, _var.number(), _var.number());\n DenseMatrix<Number> & Knn = _asmb.jacobianBlockNeighbor(Moose::NeighborNeighbor, _var.number(), _var.number());\n\n for (_qp=0; _qp<_qrule->n_points(); _qp++)\n {\n for (_i=0; _i<_test.size(); _i++)\n for (_j=0; _j<_phi.size(); _j++)\n Kee(_i,_j) += _JxW[_qp]*computeQpJacobian(Moose::ElementElement);\n\n for (_i=0; _i<_test.size(); _i++)\n for (_j=0; _j<_phi_neighbor.size(); _j++)\n Ken(_i,_j) += _JxW[_qp]*computeQpJacobian(Moose::ElementNeighbor);\n\n for (_i=0; _i<_test_neighbor.size(); _i++)\n for (_j=0; _j<_phi.size(); _j++)\n Kne(_i,_j) += _JxW[_qp]*computeQpJacobian(Moose::NeighborElement);\n\n for (_i=0; _i<_test_neighbor.size(); _i++)\n for (_j=0; _j<_phi_neighbor.size(); _j++)\n Knn(_i,_j) += _JxW[_qp]*computeQpJacobian(Moose::NeighborNeighbor);\n }\n\n Moose::perf_log.pop(\"computeJacobian()\",\"DGKernel\");\n}\n\n\nVariableValue &\nDGKernel::coupledNeighborValue(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->slnNeighbor();\n}\n\n\nVariableValue &\nDGKernel::coupledNeighborValueOld(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->slnOldNeighbor();\n}\n\nVariableValue &\nDGKernel::coupledNeighborValueOlder(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->slnOlderNeighbor();\n}\n\nVariableGradient &\nDGKernel::coupledNeighborGradient(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->gradSlnNeighbor();\n}\n\nVariableGradient &\nDGKernel::coupledNeighborGradientOld(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->gradSlnOldNeighbor();\n}\n\nVariableSecond &\nDGKernel::coupledNeighborSecond(const std::string & var_name, unsigned int comp)\n{\n return getVar(var_name, comp)->secondSlnNeighbor();\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2015 Estimation and Control Library (ECL). 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name ECL nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 * @file terrain_estimator.cpp\n * Function for fusing rangefinder measurements to estimate terrain vertical position\/\n *\n * @author Paul Riseborough <p_riseborough@live.com.au>\n *\n *\/\n\n#include \"ekf.h\"\n#include <ecl.h>\n#include <mathlib\/mathlib.h>\n\nbool Ekf::initHagl()\n{\n\tbool initialized = false;\n\n\tif (!_control_status.flags.in_air) {\n\t\t\/\/ if on ground, do not trust the range sensor, but assume a ground clearance\n\t\t_terrain_vpos = _state.pos(2) + _params.rng_gnd_clearance;\n\t\t\/\/ use the ground clearance value as our uncertainty\n\t\t_terrain_var = sq(_params.rng_gnd_clearance);\n\t\t_time_last_fake_hagl_fuse = _time_last_imu;\n\t\tinitialized = true;\n\n\t} else if (shouldUseRangeFinderForHagl()\n\t\t && _range_sensor.isDataHealthy()) {\n\t\t\/\/ if we have a fresh measurement, use it to initialise the terrain estimator\n\t\t_terrain_vpos = _state.pos(2) + _range_sensor.getDistBottom();\n\t\t\/\/ initialise state variance to variance of measurement\n\t\t_terrain_var = sq(_params.range_noise);\n\t\t\/\/ success\n\t\tinitialized = true;\n\n\t} else if (shouldUseOpticalFlowForHagl()\n\t\t && _flow_for_terrain_data_ready) {\n\t\t\/\/ initialise terrain vertical position to origin as this is the best guess we have\n\t\t_terrain_vpos = fmaxf(0.0f, _state.pos(2));\n\t\t_terrain_var = 100.0f;\n\t\tinitialized = true;\n\n\t} else {\n\t\t\/\/ no information - cannot initialise\n\t}\n\n\tif (initialized) {\n\t\t\/\/ has initialized with valid data\n\t\t_time_last_hagl_fuse = _time_last_imu;\n\t}\n\n\treturn initialized;\n}\n\nbool Ekf::shouldUseRangeFinderForHagl() const\n{\n\treturn (_params.terrain_fusion_mode & TerrainFusionMask::TerrainFuseRangeFinder);\n}\n\nbool Ekf::shouldUseOpticalFlowForHagl() const\n{\n\treturn (_params.terrain_fusion_mode & TerrainFusionMask::TerrainFuseOpticalFlow);\n}\n\nvoid Ekf::runTerrainEstimator()\n{\n\t\/\/ If we are on ground, store the local position and time to use as a reference\n\tif (!_control_status.flags.in_air) {\n\t\t_last_on_ground_posD = _state.pos(2);\n\t}\n\n\t\/\/ Perform initialisation check and\n\t\/\/ on ground, continuously reset the terrain estimator\n\tif (!_terrain_initialised || !_control_status.flags.in_air) {\n\t\t_terrain_initialised = initHagl();\n\n\t} else {\n\n\t\t\/\/ predict the state variance growth where the state is the vertical position of the terrain underneath the vehicle\n\n\t\t\/\/ process noise due to errors in vehicle height estimate\n\t\t_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_p_noise);\n\n\t\t\/\/ process noise due to terrain gradient\n\t\t_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_gradient)\n\t\t\t\t* (sq(_state.vel(0)) + sq(_state.vel(1)));\n\n\t\t\/\/ limit the variance to prevent it becoming badly conditioned\n\t\t_terrain_var = math::constrain(_terrain_var, 0.0f, 1e4f);\n\n\t\t\/\/ Fuse range finder data if available\n\t\tif (shouldUseRangeFinderForHagl()\n\t\t && _range_sensor.isDataHealthy()) {\n\t\t\tfuseHagl();\n\t\t}\n\n\t\tif (shouldUseOpticalFlowForHagl()\n\t\t && _flow_for_terrain_data_ready) {\n\t\t\tfuseFlowForTerrain();\n\t\t\t_flow_for_terrain_data_ready = false;\n\t\t}\n\n\t\t\/\/ constrain _terrain_vpos to be a minimum of _params.rng_gnd_clearance larger than _state.pos(2)\n\t\tif (_terrain_vpos - _state.pos(2) < _params.rng_gnd_clearance) {\n\t\t\t_terrain_vpos = _params.rng_gnd_clearance + _state.pos(2);\n\t\t}\n\t}\n\n\tupdateTerrainValidity();\n}\n\nvoid Ekf::fuseHagl()\n{\n\t\/\/ get a height above ground measurement from the range finder assuming a flat earth\n\tconst float meas_hagl = _range_sensor.getDistBottom();\n\n\t\/\/ predict the hagl from the vehicle position and terrain height\n\tconst float pred_hagl = _terrain_vpos - _state.pos(2);\n\n\t\/\/ calculate the innovation\n\t_hagl_innov = pred_hagl - meas_hagl;\n\n\t\/\/ calculate the observation variance adding the variance of the vehicles own height uncertainty\n\tconst float obs_variance = fmaxf(P(9,9) * _params.vehicle_variance_scaler, 0.0f)\n\t\t\t + sq(_params.range_noise)\n\t\t\t + sq(_params.range_noise_scaler * _range_sensor.getRange());\n\n\t\/\/ calculate the innovation variance - limiting it to prevent a badly conditioned fusion\n\t_hagl_innov_var = fmaxf(_terrain_var + obs_variance, obs_variance);\n\n\t\/\/ perform an innovation consistency check and only fuse data if it passes\n\tconst float gate_size = fmaxf(_params.range_innov_gate, 1.0f);\n\t_hagl_test_ratio = sq(_hagl_innov) \/ (sq(gate_size) * _hagl_innov_var);\n\n\tif (_hagl_test_ratio <= 1.0f) {\n\t\t\/\/ calculate the Kalman gain\n\t\tfloat gain = _terrain_var \/ _hagl_innov_var;\n\t\t\/\/ correct the state\n\t\t_terrain_vpos -= gain * _hagl_innov;\n\t\t\/\/ correct the variance\n\t\t_terrain_var = fmaxf(_terrain_var * (1.0f - gain), 0.0f);\n\t\t\/\/ record last successful fusion event\n\t\t_time_last_hagl_fuse = _time_last_imu;\n\t\t_innov_check_fail_status.flags.reject_hagl = false;\n\n\t} else {\n\t\t\/\/ If we have been rejecting range data for too long, reset to measurement\n\t\tif (isTimedOut(_time_last_hagl_fuse, (uint64_t)10E6)) {\n\t\t\t_terrain_vpos = _state.pos(2) + meas_hagl;\n\t\t\t_terrain_var = obs_variance;\n\n\t\t} else {\n\t\t\t_innov_check_fail_status.flags.reject_hagl = true;\n\t\t}\n\t}\n}\n\nvoid Ekf::fuseFlowForTerrain()\n{\n\t\/\/ calculate optical LOS rates using optical flow rates that have had the body angular rate contribution removed\n\t\/\/ correct for gyro bias errors in the data used to do the motion compensation\n\t\/\/ Note the sign convention used: A positive LOS rate is a RH rotation of the scene about that axis.\n\tconst Vector2f opt_flow_rate = Vector2f(_flow_compensated_XY_rad) \/ _flow_sample_delayed.dt + Vector2f(_flow_gyro_bias);\n\n\t\/\/ get latest estimated orientation\n\tconst float q0 = _state.quat_nominal(0);\n\tconst float q1 = _state.quat_nominal(1);\n\tconst float q2 = _state.quat_nominal(2);\n\tconst float q3 = _state.quat_nominal(3);\n\n\t\/\/ calculate the optical flow observation variance\n\tconst float R_LOS = calcOptFlowMeasVar();\n\n\t\/\/ get rotation matrix from earth to body\n\tconst Dcmf earth_to_body = quatToInverseRotMat(_state.quat_nominal);\n\n\t\/\/ calculate the sensor position relative to the IMU\n\tconst Vector3f pos_offset_body = _params.flow_pos_body - _params.imu_pos_body;\n\n\t\/\/ calculate the velocity of the sensor relative to the imu in body frame\n\t\/\/ Note: _flow_sample_delayed.gyro_xyz is the negative of the body angular velocity, thus use minus sign\n\tconst Vector3f vel_rel_imu_body = Vector3f(-_flow_sample_delayed.gyro_xyz \/ _flow_sample_delayed.dt) % pos_offset_body;\n\n\t\/\/ calculate the velocity of the sensor in the earth frame\n\tconst Vector3f vel_rel_earth = _state.vel + _R_to_earth * vel_rel_imu_body;\n\n\t\/\/ rotate into body frame\n\tconst Vector3f vel_body = earth_to_body * vel_rel_earth;\n\n\tconst float t0 = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3;\n\n\t\/\/ constrain terrain to minimum allowed value and predict height above ground\n\t_terrain_vpos = fmaxf(_terrain_vpos, _params.rng_gnd_clearance + _state.pos(2));\n\tconst float pred_hagl = _terrain_vpos - _state.pos(2);\n\n\t\/\/ Calculate observation matrix for flow around the vehicle x axis\n\tconst float Hx = vel_body(1) * t0 \/ (pred_hagl * pred_hagl);\n\n\t\/\/ Constrain terrain variance to be non-negative\n\t_terrain_var = fmaxf(_terrain_var, 0.0f);\n\n\t\/\/ Cacluate innovation variance\n\t_flow_innov_var[0] = Hx * Hx * _terrain_var + R_LOS;\n\n\t\/\/ calculate the kalman gain for the flow x measurement\n\tconst float Kx = _terrain_var * Hx \/ _flow_innov_var[0];\n\n\t\/\/ calculate prediced optical flow about x axis\n\tconst float pred_flow_x = vel_body(1) * earth_to_body(2, 2) \/ pred_hagl;\n\n\t\/\/ calculate flow innovation (x axis)\n\t_flow_innov[0] = pred_flow_x - opt_flow_rate(0);\n\n\t\/\/ calculate correction term for terrain variance\n\tconst float KxHxP = Kx * Hx * _terrain_var;\n\n\t\/\/ innovation consistency check\n\tconst float gate_size = fmaxf(_params.flow_innov_gate, 1.0f);\n\tfloat flow_test_ratio = sq(_flow_innov[0]) \/ (sq(gate_size) * _flow_innov_var[0]);\n\n\t\/\/ do not perform measurement update if badly conditioned\n\tif (flow_test_ratio <= 1.0f) {\n\t\t_terrain_vpos += Kx * _flow_innov[0];\n\t\t\/\/ guard against negative variance\n\t\t_terrain_var = fmaxf(_terrain_var - KxHxP, 0.0f);\n\t\t_time_last_of_fuse = _time_last_imu;\n\t}\n\n\t\/\/ Calculate observation matrix for flow around the vehicle y axis\n\tconst float Hy = -vel_body(0) * t0 \/ (pred_hagl * pred_hagl);\n\n\t\/\/ Calculuate innovation variance\n\t_flow_innov_var[1] = Hy * Hy * _terrain_var + R_LOS;\n\n\t\/\/ calculate the kalman gain for the flow y measurement\n\tconst float Ky = _terrain_var * Hy \/ _flow_innov_var[1];\n\n\t\/\/ calculate prediced optical flow about y axis\n\tconst float pred_flow_y = -vel_body(0) * earth_to_body(2, 2) \/ pred_hagl;\n\n\t\/\/ calculate flow innovation (y axis)\n\t_flow_innov[1] = pred_flow_y - opt_flow_rate(1);\n\n\t\/\/ calculate correction term for terrain variance\n\tconst float KyHyP = Ky * Hy * _terrain_var;\n\n\t\/\/ innovation consistency check\n\tflow_test_ratio = sq(_flow_innov[1]) \/ (sq(gate_size) * _flow_innov_var[1]);\n\n\tif (flow_test_ratio <= 1.0f) {\n\t\t_terrain_vpos += Ky * _flow_innov[1];\n\t\t\/\/ guard against negative variance\n\t\t_terrain_var = fmaxf(_terrain_var - KyHyP, 0.0f);\n\t\t_time_last_of_fuse = _time_last_imu;\n\t}\n}\n\nbool Ekf::isTerrainEstimateValid() const\n{\n\treturn _hagl_valid;\n}\n\nvoid Ekf::updateTerrainValidity()\n{\n\t\/\/ we have been fusing range finder measurements in the last 5 seconds\n\tconst bool recent_range_fusion = isRecent(_time_last_hagl_fuse, (uint64_t)5e6);\n\n\t\/\/ we have been fusing optical flow measurements for terrain estimation within the last 5 seconds\n\t\/\/ this can only be the case if the main filter does not fuse optical flow\n\tconst bool recent_flow_for_terrain_fusion = isRecent(_time_last_of_fuse, (uint64_t)5e6)\n\t\t\t\t\t\t && !_control_status.flags.opt_flow;\n\n\t_hagl_valid = (_terrain_initialised && (recent_range_fusion || recent_flow_for_terrain_fusion));\n\n\t_hagl_sensor_status.flags.range_finder = shouldUseRangeFinderForHagl()\n\t\t\t\t\t\t && recent_range_fusion\n\t\t\t\t\t\t && (_time_last_fake_hagl_fuse != _time_last_hagl_fuse);\n\t_hagl_sensor_status.flags.flow = shouldUseOpticalFlowForHagl()\n\t\t\t\t\t && recent_flow_for_terrain_fusion;\n}\n\n\/\/ get the estimated vertical position of the terrain relative to the NED origin\nfloat Ekf::getTerrainVertPos() const\n{\n\treturn _terrain_vpos;\n}\n<commit_msg>Get rid of non functional piece of code<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2015 Estimation and Control Library (ECL). 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name ECL nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 * @file terrain_estimator.cpp\n * Function for fusing rangefinder measurements to estimate terrain vertical position\/\n *\n * @author Paul Riseborough <p_riseborough@live.com.au>\n *\n *\/\n\n#include \"ekf.h\"\n#include <ecl.h>\n#include <mathlib\/mathlib.h>\n\nbool Ekf::initHagl()\n{\n\tbool initialized = false;\n\n\tif (!_control_status.flags.in_air) {\n\t\t\/\/ if on ground, do not trust the range sensor, but assume a ground clearance\n\t\t_terrain_vpos = _state.pos(2) + _params.rng_gnd_clearance;\n\t\t\/\/ use the ground clearance value as our uncertainty\n\t\t_terrain_var = sq(_params.rng_gnd_clearance);\n\t\t_time_last_fake_hagl_fuse = _time_last_imu;\n\t\tinitialized = true;\n\n\t} else if (shouldUseRangeFinderForHagl()\n\t\t && _range_sensor.isDataHealthy()) {\n\t\t\/\/ if we have a fresh measurement, use it to initialise the terrain estimator\n\t\t_terrain_vpos = _state.pos(2) + _range_sensor.getDistBottom();\n\t\t\/\/ initialise state variance to variance of measurement\n\t\t_terrain_var = sq(_params.range_noise);\n\t\t\/\/ success\n\t\tinitialized = true;\n\n\t} else if (shouldUseOpticalFlowForHagl()\n\t\t && _flow_for_terrain_data_ready) {\n\t\t\/\/ initialise terrain vertical position to origin as this is the best guess we have\n\t\t_terrain_vpos = fmaxf(0.0f, _state.pos(2));\n\t\t_terrain_var = 100.0f;\n\t\tinitialized = true;\n\n\t} else {\n\t\t\/\/ no information - cannot initialise\n\t}\n\n\tif (initialized) {\n\t\t\/\/ has initialized with valid data\n\t\t_time_last_hagl_fuse = _time_last_imu;\n\t}\n\n\treturn initialized;\n}\n\nbool Ekf::shouldUseRangeFinderForHagl() const\n{\n\treturn (_params.terrain_fusion_mode & TerrainFusionMask::TerrainFuseRangeFinder);\n}\n\nbool Ekf::shouldUseOpticalFlowForHagl() const\n{\n\treturn (_params.terrain_fusion_mode & TerrainFusionMask::TerrainFuseOpticalFlow);\n}\n\nvoid Ekf::runTerrainEstimator()\n{\n\t\/\/ If we are on ground, store the local position and time to use as a reference\n\tif (!_control_status.flags.in_air) {\n\t\t_last_on_ground_posD = _state.pos(2);\n\t}\n\n\t\/\/ Perform initialisation check and\n\t\/\/ on ground, continuously reset the terrain estimator\n\tif (!_terrain_initialised || !_control_status.flags.in_air) {\n\t\t_terrain_initialised = initHagl();\n\n\t} else {\n\n\t\t\/\/ predict the state variance growth where the state is the vertical position of the terrain underneath the vehicle\n\n\t\t\/\/ process noise due to errors in vehicle height estimate\n\t\t_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_p_noise);\n\n\t\t\/\/ process noise due to terrain gradient\n\t\t_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_gradient)\n\t\t\t\t* (sq(_state.vel(0)) + sq(_state.vel(1)));\n\n\t\t\/\/ limit the variance to prevent it becoming badly conditioned\n\t\t_terrain_var = math::constrain(_terrain_var, 0.0f, 1e4f);\n\n\t\t\/\/ Fuse range finder data if available\n\t\tif (shouldUseRangeFinderForHagl()\n\t\t && _range_sensor.isDataHealthy()) {\n\t\t\tfuseHagl();\n\t\t}\n\n\t\tif (shouldUseOpticalFlowForHagl()\n\t\t && _flow_for_terrain_data_ready) {\n\t\t\tfuseFlowForTerrain();\n\t\t\t_flow_for_terrain_data_ready = false;\n\t\t}\n\n\t\t\/\/ constrain _terrain_vpos to be a minimum of _params.rng_gnd_clearance larger than _state.pos(2)\n\t\tif (_terrain_vpos - _state.pos(2) < _params.rng_gnd_clearance) {\n\t\t\t_terrain_vpos = _params.rng_gnd_clearance + _state.pos(2);\n\t\t}\n\t}\n\n\tupdateTerrainValidity();\n}\n\nvoid Ekf::fuseHagl()\n{\n\t\/\/ get a height above ground measurement from the range finder assuming a flat earth\n\tconst float meas_hagl = _range_sensor.getDistBottom();\n\n\t\/\/ predict the hagl from the vehicle position and terrain height\n\tconst float pred_hagl = _terrain_vpos - _state.pos(2);\n\n\t\/\/ calculate the innovation\n\t_hagl_innov = pred_hagl - meas_hagl;\n\n\t\/\/ calculate the observation variance adding the variance of the vehicles own height uncertainty\n\tconst float obs_variance = fmaxf(P(9,9) * _params.vehicle_variance_scaler, 0.0f)\n\t\t\t + sq(_params.range_noise)\n\t\t\t + sq(_params.range_noise_scaler * _range_sensor.getRange());\n\n\t\/\/ calculate the innovation variance - limiting it to prevent a badly conditioned fusion\n\t_hagl_innov_var = fmaxf(_terrain_var + obs_variance, obs_variance);\n\n\t\/\/ perform an innovation consistency check and only fuse data if it passes\n\tconst float gate_size = fmaxf(_params.range_innov_gate, 1.0f);\n\t_hagl_test_ratio = sq(_hagl_innov) \/ (sq(gate_size) * _hagl_innov_var);\n\n\tif (_hagl_test_ratio <= 1.0f) {\n\t\t\/\/ calculate the Kalman gain\n\t\tfloat gain = _terrain_var \/ _hagl_innov_var;\n\t\t\/\/ correct the state\n\t\t_terrain_vpos -= gain * _hagl_innov;\n\t\t\/\/ correct the variance\n\t\t_terrain_var = fmaxf(_terrain_var * (1.0f - gain), 0.0f);\n\t\t\/\/ record last successful fusion event\n\t\t_time_last_hagl_fuse = _time_last_imu;\n\t\t_innov_check_fail_status.flags.reject_hagl = false;\n\n\t} else {\n\t\t\/\/ If we have been rejecting range data for too long, reset to measurement\n\t\tif (isTimedOut(_time_last_hagl_fuse, (uint64_t)10E6)) {\n\t\t\t_terrain_vpos = _state.pos(2) + meas_hagl;\n\t\t\t_terrain_var = obs_variance;\n\n\t\t} else {\n\t\t\t_innov_check_fail_status.flags.reject_hagl = true;\n\t\t}\n\t}\n}\n\nvoid Ekf::fuseFlowForTerrain()\n{\n\t\/\/ calculate optical LOS rates using optical flow rates that have had the body angular rate contribution removed\n\t\/\/ correct for gyro bias errors in the data used to do the motion compensation\n\t\/\/ Note the sign convention used: A positive LOS rate is a RH rotation of the scene about that axis.\n\tconst Vector2f opt_flow_rate = _flow_compensated_XY_rad \/ _flow_sample_delayed.dt + Vector2f(_flow_gyro_bias);\n\n\t\/\/ get latest estimated orientation\n\tconst float q0 = _state.quat_nominal(0);\n\tconst float q1 = _state.quat_nominal(1);\n\tconst float q2 = _state.quat_nominal(2);\n\tconst float q3 = _state.quat_nominal(3);\n\n\t\/\/ calculate the optical flow observation variance\n\tconst float R_LOS = calcOptFlowMeasVar();\n\n\t\/\/ get rotation matrix from earth to body\n\tconst Dcmf earth_to_body = quatToInverseRotMat(_state.quat_nominal);\n\n\t\/\/ calculate the sensor position relative to the IMU\n\tconst Vector3f pos_offset_body = _params.flow_pos_body - _params.imu_pos_body;\n\n\t\/\/ calculate the velocity of the sensor relative to the imu in body frame\n\t\/\/ Note: _flow_sample_delayed.gyro_xyz is the negative of the body angular velocity, thus use minus sign\n\tconst Vector3f vel_rel_imu_body = Vector3f(-_flow_sample_delayed.gyro_xyz \/ _flow_sample_delayed.dt) % pos_offset_body;\n\n\t\/\/ calculate the velocity of the sensor in the earth frame\n\tconst Vector3f vel_rel_earth = _state.vel + _R_to_earth * vel_rel_imu_body;\n\n\t\/\/ rotate into body frame\n\tconst Vector3f vel_body = earth_to_body * vel_rel_earth;\n\n\tconst float t0 = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3;\n\n\t\/\/ constrain terrain to minimum allowed value and predict height above ground\n\t_terrain_vpos = fmaxf(_terrain_vpos, _params.rng_gnd_clearance + _state.pos(2));\n\tconst float pred_hagl = _terrain_vpos - _state.pos(2);\n\n\t\/\/ Calculate observation matrix for flow around the vehicle x axis\n\tconst float Hx = vel_body(1) * t0 \/ (pred_hagl * pred_hagl);\n\n\t\/\/ Constrain terrain variance to be non-negative\n\t_terrain_var = fmaxf(_terrain_var, 0.0f);\n\n\t\/\/ Cacluate innovation variance\n\t_flow_innov_var[0] = Hx * Hx * _terrain_var + R_LOS;\n\n\t\/\/ calculate the kalman gain for the flow x measurement\n\tconst float Kx = _terrain_var * Hx \/ _flow_innov_var[0];\n\n\t\/\/ calculate prediced optical flow about x axis\n\tconst float pred_flow_x = vel_body(1) * earth_to_body(2, 2) \/ pred_hagl;\n\n\t\/\/ calculate flow innovation (x axis)\n\t_flow_innov[0] = pred_flow_x - opt_flow_rate(0);\n\n\t\/\/ calculate correction term for terrain variance\n\tconst float KxHxP = Kx * Hx * _terrain_var;\n\n\t\/\/ innovation consistency check\n\tconst float gate_size = fmaxf(_params.flow_innov_gate, 1.0f);\n\tfloat flow_test_ratio = sq(_flow_innov[0]) \/ (sq(gate_size) * _flow_innov_var[0]);\n\n\t\/\/ do not perform measurement update if badly conditioned\n\tif (flow_test_ratio <= 1.0f) {\n\t\t_terrain_vpos += Kx * _flow_innov[0];\n\t\t\/\/ guard against negative variance\n\t\t_terrain_var = fmaxf(_terrain_var - KxHxP, 0.0f);\n\t\t_time_last_of_fuse = _time_last_imu;\n\t}\n\n\t\/\/ Calculate observation matrix for flow around the vehicle y axis\n\tconst float Hy = -vel_body(0) * t0 \/ (pred_hagl * pred_hagl);\n\n\t\/\/ Calculuate innovation variance\n\t_flow_innov_var[1] = Hy * Hy * _terrain_var + R_LOS;\n\n\t\/\/ calculate the kalman gain for the flow y measurement\n\tconst float Ky = _terrain_var * Hy \/ _flow_innov_var[1];\n\n\t\/\/ calculate prediced optical flow about y axis\n\tconst float pred_flow_y = -vel_body(0) * earth_to_body(2, 2) \/ pred_hagl;\n\n\t\/\/ calculate flow innovation (y axis)\n\t_flow_innov[1] = pred_flow_y - opt_flow_rate(1);\n\n\t\/\/ calculate correction term for terrain variance\n\tconst float KyHyP = Ky * Hy * _terrain_var;\n\n\t\/\/ innovation consistency check\n\tflow_test_ratio = sq(_flow_innov[1]) \/ (sq(gate_size) * _flow_innov_var[1]);\n\n\tif (flow_test_ratio <= 1.0f) {\n\t\t_terrain_vpos += Ky * _flow_innov[1];\n\t\t\/\/ guard against negative variance\n\t\t_terrain_var = fmaxf(_terrain_var - KyHyP, 0.0f);\n\t\t_time_last_of_fuse = _time_last_imu;\n\t}\n}\n\nbool Ekf::isTerrainEstimateValid() const\n{\n\treturn _hagl_valid;\n}\n\nvoid Ekf::updateTerrainValidity()\n{\n\t\/\/ we have been fusing range finder measurements in the last 5 seconds\n\tconst bool recent_range_fusion = isRecent(_time_last_hagl_fuse, (uint64_t)5e6);\n\n\t\/\/ we have been fusing optical flow measurements for terrain estimation within the last 5 seconds\n\t\/\/ this can only be the case if the main filter does not fuse optical flow\n\tconst bool recent_flow_for_terrain_fusion = isRecent(_time_last_of_fuse, (uint64_t)5e6)\n\t\t\t\t\t\t && !_control_status.flags.opt_flow;\n\n\t_hagl_valid = (_terrain_initialised && (recent_range_fusion || recent_flow_for_terrain_fusion));\n\n\t_hagl_sensor_status.flags.range_finder = shouldUseRangeFinderForHagl()\n\t\t\t\t\t\t && recent_range_fusion\n\t\t\t\t\t\t && (_time_last_fake_hagl_fuse != _time_last_hagl_fuse);\n\t_hagl_sensor_status.flags.flow = shouldUseOpticalFlowForHagl()\n\t\t\t\t\t && recent_flow_for_terrain_fusion;\n}\n\n\/\/ get the estimated vertical position of the terrain relative to the NED origin\nfloat Ekf::getTerrainVertPos() const\n{\n\treturn _terrain_vpos;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestLinePlot.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkChartXY.h\"\n#include \"vtkPlotPoints.h\"\n#include \"vtkTable.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkContextView.h\"\n#include \"vtkContextScene.h\"\n#include \"vtkRenderWindowInteractor.h\"\n\n\/\/----------------------------------------------------------------------------\nint TestScatterPlot(int , char * [])\n{\n \/\/ Set up a 2D scene, add an XY chart to it\n vtkSmartPointer<vtkContextView> view =\n vtkSmartPointer<vtkContextView>::New();\n view->GetRenderer()->SetBackground(1.0, 1.0, 1.0);\n view->GetRenderWindow()->SetSize(400, 300);\n vtkSmartPointer<vtkChartXY> chart = vtkSmartPointer<vtkChartXY>::New();\n view->GetScene()->AddItem(chart);\n chart->SetShowLegend(true);\n\n \/\/ Create a table with some points in it...\n vtkSmartPointer<vtkTable> table = vtkSmartPointer<vtkTable>::New();\n vtkSmartPointer<vtkFloatArray> arrX = vtkSmartPointer<vtkFloatArray>::New();\n arrX->SetName(\"X Axis\");\n table->AddColumn(arrX);\n vtkSmartPointer<vtkFloatArray> arrC = vtkSmartPointer<vtkFloatArray>::New();\n arrC->SetName(\"Cosine\");\n table->AddColumn(arrC);\n vtkSmartPointer<vtkFloatArray> arrS = vtkSmartPointer<vtkFloatArray>::New();\n arrS->SetName(\"Sine\");\n table->AddColumn(arrS);\n vtkSmartPointer<vtkFloatArray> arrT = vtkSmartPointer<vtkFloatArray>::New();\n arrT->SetName(\"Tan\");\n table->AddColumn(arrT);\n \/\/ Test charting with a few more points...\n int numPoints = 40;\n float inc = 7.5 \/ (numPoints-1);\n table->SetNumberOfRows(numPoints);\n for (int i = 0; i < numPoints; ++i)\n {\n table->SetValue(i, 0, i * inc);\n table->SetValue(i, 1, cos(i * inc) + 0.0);\n table->SetValue(i, 2, sin(i * inc) + 0.0);\n table->SetValue(i, 3, tan(i * inc) + 0.5);\n }\n\n \/\/ Add multiple line plots, setting the colors etc\n vtkPlot *points = chart->AddPlot(vtkChart::POINTS);\n points->SetInput(table, 0, 1);\n points->SetColor(0, 0, 0, 255);\n points->SetWidth(1.0);\n vtkPlotPoints::SafeDownCast(points)->SetMarkerStyle(vtkPlotPoints::CROSS);\n points = chart->AddPlot(vtkChart::POINTS);\n points->SetInput(table, 0, 2);\n points->SetColor(0, 0, 0, 255);\n points->SetWidth(1.0);\n vtkPlotPoints::SafeDownCast(points)->SetMarkerStyle(vtkPlotPoints::PLUS);\n points = chart->AddPlot(vtkChart::POINTS);\n points->SetInput(table, 0, 3);\n points->SetColor(0, 0, 255, 255);\n points->SetWidth(4.0);\n\n \/\/Finally render the scene and compare the image to a reference image\n view->GetRenderWindow()->SetMultiSamples(0);\n view->GetInteractor()->Initialize();\n view->GetInteractor()->Start();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: Use vtkNew instead of vtkSmartPointer.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestLinePlot.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkNew.h\"\n#include \"vtkChartXY.h\"\n#include \"vtkPlotPoints.h\"\n#include \"vtkTable.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkContextView.h\"\n#include \"vtkContextScene.h\"\n#include \"vtkRenderWindowInteractor.h\"\n\n\/\/----------------------------------------------------------------------------\nint TestScatterPlot(int , char * [])\n{\n \/\/ Set up a 2D scene, add an XY chart to it\n vtkNew<vtkContextView> view;\n view->GetRenderer()->SetBackground(1.0, 1.0, 1.0);\n view->GetRenderWindow()->SetSize(400, 300);\n vtkNew<vtkChartXY> chart;\n view->GetScene()->AddItem(chart.GetPointer());\n chart->SetShowLegend(true);\n\n \/\/ Create a table with some points in it...\n vtkNew<vtkTable> table;\n vtkNew<vtkFloatArray> arrX;\n arrX->SetName(\"X Axis\");\n table->AddColumn(arrX.GetPointer());\n vtkNew<vtkFloatArray> arrC;\n arrC->SetName(\"Cosine\");\n table->AddColumn(arrC.GetPointer());\n vtkNew<vtkFloatArray> arrS;\n arrS->SetName(\"Sine\");\n table->AddColumn(arrS.GetPointer());\n vtkNew<vtkFloatArray> arrT;\n arrT->SetName(\"Tan\");\n table->AddColumn(arrT.GetPointer());\n\n \/\/ Test charting with a few more points...\n int numPoints = 40;\n float inc = 7.5 \/ (numPoints-1);\n table->SetNumberOfRows(numPoints);\n for (int i = 0; i < numPoints; ++i)\n {\n table->SetValue(i, 0, i * inc);\n table->SetValue(i, 1, cos(i * inc) + 0.0);\n table->SetValue(i, 2, sin(i * inc) + 0.0);\n table->SetValue(i, 3, tan(i * inc) + 0.5);\n }\n\n \/\/ Add multiple line plots, setting the colors etc\n vtkPlot *points = chart->AddPlot(vtkChart::POINTS);\n points->SetInput(table.GetPointer(), 0, 1);\n points->SetColor(0, 0, 0, 255);\n points->SetWidth(1.0);\n vtkPlotPoints::SafeDownCast(points)->SetMarkerStyle(vtkPlotPoints::CROSS);\n points = chart->AddPlot(vtkChart::POINTS);\n points->SetInput(table.GetPointer(), 0, 2);\n points->SetColor(0, 0, 0, 255);\n points->SetWidth(1.0);\n vtkPlotPoints::SafeDownCast(points)->SetMarkerStyle(vtkPlotPoints::PLUS);\n points = chart->AddPlot(vtkChart::POINTS);\n points->SetInput(table.GetPointer(), 0, 3);\n points->SetColor(0, 0, 255, 255);\n points->SetWidth(4.0);\n\n \/\/Finally render the scene and compare the image to a reference image\n view->GetRenderWindow()->SetMultiSamples(0);\n view->GetInteractor()->Initialize();\n view->GetInteractor()->Start();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ScoreDefinition.h\"\n#include \"..\/common.h\"\n#include \"..\/mahjong-algorithm\/points_calculator.h\"\n\nUSING_NS_CC;\n\nstatic std::vector<std::string> g_vec;\n\nScene *ScoreDefinitionScene::createScene(size_t idx) {\n if (g_vec.empty()) {\n ValueVector valueVec = FileUtils::getInstance()->getValueVectorFromFile(\"score_definition.xml\");\n g_vec.reserve(valueVec.size());\n std::transform(valueVec.begin(), valueVec.end(), std::back_inserter(g_vec), std::bind(&Value::asString, std::placeholders::_1));\n }\n\n auto scene = Scene::create();\n auto layer = new (std::nothrow) ScoreDefinitionScene();\n layer->initWithIndex(idx);\n\n scene->addChild(layer);\n return scene;\n}\n\nbool ScoreDefinitionScene::initWithIndex(size_t idx) {\n if (!Layer::init()) {\n return false;\n }\n\n auto listener = EventListenerKeyboard::create();\n listener->onKeyReleased = CC_CALLBACK_2(Layer::onKeyReleased, this);\n _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);\n\n Size visibleSize = Director::getInstance()->getVisibleSize();\n Vec2 origin = Director::getInstance()->getVisibleOrigin();\n\n Label *tileLabel = Label::createWithSystemFont(mahjong::points_name[idx], \"Arial\", 20);\n this->addChild(tileLabel);\n tileLabel->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,\n origin.y + visibleSize.height - tileLabel->getContentSize().height * 0.5f));\n\n ui::Button *backBtn = ui::Button::create();\n this->addChild(backBtn);\n backBtn->setScale9Enabled(true);\n backBtn->setContentSize(Size(45, 20));\n backBtn->setTitleFontSize(16);\n backBtn->setTitleText(\"返回\");\n backBtn->setPosition(Vec2(origin.x + 15, origin.y + visibleSize.height - 10));\n backBtn->addClickEventListener([](Ref *) {\n Director::getInstance()->popScene();\n });\n\n std::string &text = g_vec[idx];\n float scale = 1.0f;\n float maxWidth = (visibleSize.width - 10) \/ 18;\n if (maxWidth < 25) {\n scale = maxWidth \/ 27;\n }\n\n char tilesStr[128];\n mahjong::TILE tiles[14];\n long tilesCnt;\n char imgStr[1024];\n\n std::string::size_type pos = text.find('[');\n while (pos != std::string::npos) {\n const char *str = text.c_str();\n int readLen;\n if (sscanf(str + pos + 1, \"%[^]]%n\", tilesStr, &readLen) != EOF && str[pos + readLen + 1] == ']'\n && mahjong::parse_tiles(tilesStr, tiles, &tilesCnt) != nullptr) {\n size_t totalWriteLen = 0;\n for (long i = 0; i < tilesCnt; ++i) {\n int writeLen = snprintf(imgStr + totalWriteLen , sizeof(imgStr) - totalWriteLen, \"<img src=\\\"%s\\\" width=\\\"%d\\\" height=\\\"%d\\\"\/>\", tilesImageName[tiles[i]], (int)(27 * scale), (int)(39 * scale));\n totalWriteLen += writeLen;\n }\n text.replace(pos, readLen + 2, imgStr);\n pos = text.find('[', pos + totalWriteLen);\n }\n else {\n pos = text.find('[', pos + 1);\n }\n }\n\n ui::RichText *richText = ui::RichText::createWithXML(text);\n richText->setContentSize(Size(visibleSize.width - 10, 0));\n richText->ignoreContentAdaptWithSize(false);\n richText->setVerticalSpace(2);\n richText->formatText();\n this->addChild(richText);\n richText->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height - 40));\n return true;\n}\n\nvoid ScoreDefinitionScene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event *unusedEvent) {\n if (keyCode == EventKeyboard::KeyCode::KEY_BACK) {\n Director::getInstance()->popScene();\n }\n}\n<commit_msg>封装成一个函数<commit_after>#include \"ScoreDefinition.h\"\n#include \"..\/common.h\"\n#include \"..\/mahjong-algorithm\/points_calculator.h\"\n\nUSING_NS_CC;\n\nstatic std::vector<std::string> g_vec;\n\nstatic void replaceTilesToImage(std::string &text, float scale) {\n char tilesStr[128];\n mahjong::TILE tiles[14];\n long tilesCnt;\n char imgStr[1024];\n\n std::string::size_type pos = text.find('[');\n while (pos != std::string::npos) {\n const char *str = text.c_str();\n int readLen;\n if (sscanf(str + pos + 1, \"%[^]]%n\", tilesStr, &readLen) != EOF\n && str[pos + readLen + 1] == ']'\n && mahjong::parse_tiles(tilesStr, tiles, &tilesCnt) != nullptr) {\n size_t totalWriteLen = 0;\n for (long i = 0; i < tilesCnt; ++i) {\n int writeLen = snprintf(imgStr + totalWriteLen, sizeof(imgStr) - totalWriteLen,\n \"<img src=\\\"%s\\\" width=\\\"%d\\\" height=\\\"%d\\\"\/>\", tilesImageName[tiles[i]],\n (int)(27 * scale), (int)(39 * scale));\n totalWriteLen += writeLen;\n }\n text.replace(pos, readLen + 2, imgStr);\n pos = text.find('[', pos + totalWriteLen);\n }\n else {\n pos = text.find('[', pos + 1);\n }\n }\n}\n\nScene *ScoreDefinitionScene::createScene(size_t idx) {\n if (g_vec.empty()) {\n ValueVector valueVec = FileUtils::getInstance()->getValueVectorFromFile(\"score_definition.xml\");\n g_vec.reserve(valueVec.size());\n std::transform(valueVec.begin(), valueVec.end(), std::back_inserter(g_vec), std::bind(&Value::asString, std::placeholders::_1));\n }\n\n auto scene = Scene::create();\n auto layer = new (std::nothrow) ScoreDefinitionScene();\n layer->initWithIndex(idx);\n\n scene->addChild(layer);\n return scene;\n}\n\nbool ScoreDefinitionScene::initWithIndex(size_t idx) {\n if (!Layer::init()) {\n return false;\n }\n\n auto listener = EventListenerKeyboard::create();\n listener->onKeyReleased = CC_CALLBACK_2(Layer::onKeyReleased, this);\n _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);\n\n Size visibleSize = Director::getInstance()->getVisibleSize();\n Vec2 origin = Director::getInstance()->getVisibleOrigin();\n\n Label *tileLabel = Label::createWithSystemFont(mahjong::points_name[idx], \"Arial\", 20);\n this->addChild(tileLabel);\n tileLabel->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,\n origin.y + visibleSize.height - tileLabel->getContentSize().height * 0.5f));\n\n ui::Button *backBtn = ui::Button::create();\n this->addChild(backBtn);\n backBtn->setScale9Enabled(true);\n backBtn->setContentSize(Size(45, 20));\n backBtn->setTitleFontSize(16);\n backBtn->setTitleText(\"返回\");\n backBtn->setPosition(Vec2(origin.x + 15, origin.y + visibleSize.height - 10));\n backBtn->addClickEventListener([](Ref *) {\n Director::getInstance()->popScene();\n });\n\n std::string &text = g_vec[idx];\n float scale = 1.0f;\n float maxWidth = (visibleSize.width - 10) \/ 18;\n if (maxWidth < 25) {\n scale = maxWidth \/ 27;\n }\n replaceTilesToImage(text, scale);\n\n ui::RichText *richText = ui::RichText::createWithXML(text);\n richText->setContentSize(Size(visibleSize.width - 10, 0));\n richText->ignoreContentAdaptWithSize(false);\n richText->setVerticalSpace(2);\n richText->formatText();\n this->addChild(richText);\n richText->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height - 40));\n return true;\n}\n\nvoid ScoreDefinitionScene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event *unusedEvent) {\n if (keyCode == EventKeyboard::KeyCode::KEY_BACK) {\n Director::getInstance()->popScene();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkDataObjectTree.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkDataObjectTree.h\"\n\n#include \"vtkDataObjectTreeIterator.h\"\n#include \"vtkDataObjectTreeInternals.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationStringKey.h\"\n#include \"vtkInformationIntegerKey.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\/\/----------------------------------------------------------------------------\nvtkDataObjectTree::vtkDataObjectTree()\n{\n this->Internals = new vtkDataObjectTreeInternals;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObjectTree::~vtkDataObjectTree()\n{\n delete this->Internals;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetNumberOfChildren(unsigned int num)\n{\n this->Internals->Children.resize(num);\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned int vtkDataObjectTree::GetNumberOfChildren()\n{\n return static_cast<unsigned int>(this->Internals->Children.size());\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetChild(unsigned int index, vtkDataObject* dobj)\n{\n if (this->Internals->Children.size() <= index)\n {\n this->SetNumberOfChildren(index+1);\n }\n\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n if(item.DataObject!=dobj)\n {\n item.DataObject = dobj;\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::RemoveChild(unsigned int index)\n{\n if (this->Internals->Children.size() <= index)\n {\n vtkErrorMacro(\"The input index is out of range.\");\n return;\n }\n\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n item.DataObject = NULL;\n this->Internals->Children.erase(this->Internals->Children.begin()+index);\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObject* vtkDataObjectTree::GetChild(unsigned int index)\n{\n if (index < this->Internals->Children.size())\n {\n return this->Internals->Children[index].DataObject;\n }\n\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInformation* vtkDataObjectTree::GetChildMetaData(unsigned int index)\n{\n if (index < this->Internals->Children.size())\n {\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n if (!item.MetaData)\n {\n \/\/ New vtkInformation is allocated is none is already present.\n item.MetaData.TakeReference(vtkInformation::New());\n }\n return item.MetaData;\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetChildMetaData(unsigned int index, vtkInformation* info)\n{\n if (this->Internals->Children.size() <= index)\n {\n this->SetNumberOfChildren(index+1);\n }\n\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n item.MetaData = info;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkDataObjectTree::HasChildMetaData(unsigned int index)\n{\n if (index < this->Internals->Children.size())\n {\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n return (item.MetaData.GetPointer() != NULL)? 1 : 0;\n }\n\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::CopyStructure(vtkCompositeDataSet* compositeSource)\n{\n if(!compositeSource)\n {\n return;\n }\n vtkDataObjectTree* source = vtkDataObjectTree::SafeDownCast(compositeSource);\n if (source == this)\n {\n return;\n }\n\n this->Internals->Children.clear();\n if (!source)\n {\n \/\/WARNING:\n \/\/If we copy the structure of from a non-tree composite data set\n \/\/the \"structure\" is just is the total number of blocks (nill or not)\n \/\/To do: We should probably also copy meta data as well.\n int totalNumBlocks=0;\n vtkCompositeDataIterator* iter = compositeSource->NewIterator();\n iter->SkipEmptyNodesOff();\n for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())\n {\n totalNumBlocks++;\n }\n this->Internals->Children.resize(totalNumBlocks);\n iter->Delete();\n return;\n }\n\n this->Internals->Children.resize(source->Internals->Children.size());\n\n vtkDataObjectTreeInternals::Iterator srcIter =\n source->Internals->Children.begin();\n vtkDataObjectTreeInternals::Iterator myIter =\n this->Internals->Children.begin();\n for (; srcIter != source->Internals->Children.end(); ++srcIter, myIter++)\n {\n vtkDataObjectTree* compositeSrc =\n vtkDataObjectTree::SafeDownCast(srcIter->DataObject);\n if (compositeSrc)\n {\n vtkDataObjectTree* copy = compositeSrc->NewInstance();\n myIter->DataObject.TakeReference(copy);\n copy->CopyStructure(compositeSrc);\n }\n\n \/\/ shallow copy meta data.\n if (srcIter->MetaData)\n {\n vtkInformation* info = vtkInformation::New();\n info->Copy(srcIter->MetaData, \/*deep=*\/0);\n myIter->MetaData = info;\n info->FastDelete();\n }\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkCompositeDataIterator* vtkDataObjectTree::NewIterator()\n{\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::New();\n iter->SetDataSet(this);\n return iter;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetDataSet(vtkCompositeDataIterator* iter,\n vtkDataObject* dataObj)\n{\n vtkDataObjectTreeIterator* treeIter = vtkDataObjectTreeIterator::SafeDownCast(iter);\n if(treeIter)\n {\n this->SetDataSetFrom(treeIter,dataObj);\n return;\n }\n\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return;\n }\n\n\n vtkDataObjectTree* parent = this;\n unsigned int index = iter->GetCurrentFlatIndex();\n parent->SetChild(index, dataObj);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetDataSetFrom(vtkDataObjectTreeIterator* iter,\n vtkDataObject* dataObj)\n{\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return;\n }\n\n vtkDataObjectTreeIndex index = iter->GetCurrentIndex();\n\n if (index.size() == 0)\n {\n \/\/ Sanity check.\n vtkErrorMacro(\"Invalid index returned by iterator.\");\n return;\n }\n\n vtkDataObjectTree* parent = this;\n int numIndices = static_cast<int>(index.size());\n for (int cc=0; cc < numIndices-1; cc++)\n {\n if (!parent || parent->GetNumberOfChildren() <= index[cc])\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return;\n }\n parent = vtkDataObjectTree::SafeDownCast(parent->GetChild(index[cc]));\n }\n\n if (!parent || parent->GetNumberOfChildren() <= index.back())\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return;\n }\n\n parent->SetChild(index.back(), dataObj);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObject* vtkDataObjectTree::GetDataSet(vtkCompositeDataIterator* compositeIter)\n{\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(compositeIter);\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return 0;\n }\n\n vtkDataObjectTreeIndex index = iter->GetCurrentIndex();\n\n if (index.size() == 0)\n {\n \/\/ Sanity check.\n vtkErrorMacro(\"Invalid index returned by iterator.\");\n return 0;\n }\n\n vtkDataObjectTree* parent = this;\n int numIndices = static_cast<int>(index.size());\n for (int cc=0; cc < numIndices-1; cc++)\n {\n if (!parent || parent->GetNumberOfChildren() <= index[cc])\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n parent = vtkDataObjectTree::SafeDownCast(parent->GetChild(index[cc]));\n }\n\n if (!parent || parent->GetNumberOfChildren() <= index.back())\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n\n return parent->GetChild(index.back());\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInformation* vtkDataObjectTree::GetMetaData(vtkCompositeDataIterator* compositeIter)\n{\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(compositeIter);\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return 0;\n }\n\n vtkDataObjectTreeIndex index = iter->GetCurrentIndex();\n\n if (index.size() == 0)\n {\n \/\/ Sanity check.\n vtkErrorMacro(\"Invalid index returned by iterator.\");\n return 0;\n }\n\n vtkDataObjectTree* parent = this;\n int numIndices = static_cast<int>(index.size());\n for (int cc=0; cc < numIndices-1; cc++)\n {\n if (!parent || parent->GetNumberOfChildren() <= index[cc])\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n parent = vtkDataObjectTree::SafeDownCast(parent->GetChild(index[cc]));\n }\n\n if (!parent || parent->GetNumberOfChildren() <= index.back())\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n\n return parent->GetChildMetaData(index.back());\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkDataObjectTree::HasMetaData(vtkCompositeDataIterator* compositeIter)\n{\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(compositeIter);\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return 0;\n }\n\n vtkDataObjectTreeIndex index = iter->GetCurrentIndex();\n\n if (index.size() == 0)\n {\n \/\/ Sanity check.\n vtkErrorMacro(\"Invalid index returned by iterator.\");\n return 0;\n }\n\n vtkDataObjectTree* parent = this;\n int numIndices = static_cast<int>(index.size());\n for (int cc=0; cc < numIndices-1; cc++)\n {\n if (!parent || parent->GetNumberOfChildren() <= index[cc])\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n parent = vtkDataObjectTree::SafeDownCast(parent->GetChild(index[cc]));\n }\n\n if (!parent || parent->GetNumberOfChildren() <= index.back())\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n\n return parent->HasChildMetaData(index.back());\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::ShallowCopy(vtkDataObject* src)\n{\n if (src == this)\n {\n return;\n }\n\n this->Internals->Children.clear();\n this->Superclass::ShallowCopy(src);\n\n vtkDataObjectTree* from = vtkDataObjectTree::SafeDownCast(src);\n if (from)\n {\n unsigned int numChildren = from->GetNumberOfChildren();\n this->SetNumberOfChildren(numChildren);\n for (unsigned int cc=0; cc < numChildren; cc++)\n {\n vtkDataObject* child = from->GetChild(cc);\n if (child)\n {\n if (child->IsA(\"vtkDataObjectTree\"))\n {\n vtkDataObject* clone = child->NewInstance();\n clone->ShallowCopy(child);\n this->SetChild(cc, clone);\n clone->FastDelete();\n }\n else\n {\n this->SetChild(cc, child);\n }\n }\n if (from->HasChildMetaData(cc))\n {\n vtkInformation* toInfo = this->GetChildMetaData(cc);\n toInfo->Copy(from->GetChildMetaData(cc), \/*deep=*\/0);\n }\n }\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::DeepCopy(vtkDataObject* src)\n{\n if (src == this)\n {\n return;\n }\n\n this->Internals->Children.clear();\n this->Superclass::DeepCopy(src);\n\n vtkDataObjectTree* from = vtkDataObjectTree::SafeDownCast(src);\n if (from)\n {\n unsigned int numChildren = from->GetNumberOfChildren();\n this->SetNumberOfChildren(numChildren);\n for (unsigned int cc=0; cc < numChildren; cc++)\n {\n vtkDataObject* fromChild = from->GetChild(cc);\n if (fromChild)\n {\n vtkDataObject* toChild = fromChild->NewInstance();\n toChild->DeepCopy(fromChild);\n this->SetChild(cc, toChild);\n toChild->FastDelete();\n if (from->HasChildMetaData(cc))\n {\n vtkInformation* toInfo = this->GetChildMetaData(cc);\n toInfo->Copy(from->GetChildMetaData(cc), \/*deep=*\/1);\n }\n }\n }\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::Initialize()\n{\n this->Internals->Children.clear();\n this->Superclass::Initialize();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkDataObjectTree::GetNumberOfPoints()\n{\n vtkIdType numPts = 0;\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(this->NewIterator());\n for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())\n {\n vtkDataSet* ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject());\n if (ds)\n {\n numPts += ds->GetNumberOfPoints();\n }\n }\n iter->Delete();\n return numPts;\n}\n\n\n\/\/----------------------------------------------------------------------------\nunsigned long vtkDataObjectTree::GetActualMemorySize()\n{\n unsigned long memSize = 0;\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(this->NewIterator());\n for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())\n {\n vtkDataObject* dobj = iter->GetCurrentDataObject();\n memSize += dobj->GetActualMemorySize();\n }\n iter->Delete();\n return memSize;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Number Of Children: \" << this->GetNumberOfChildren() << endl;\n for (unsigned int cc=0; cc < this->GetNumberOfChildren(); cc++)\n {\n vtkDataObject* child = this->GetChild(cc);\n if (child)\n {\n os << indent << \"Child \" << cc << \": \" << child->GetClassName() << endl;\n child->PrintSelf(os, indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Child \" << cc << \": NULL\" << endl;\n }\n }\n}\n<commit_msg>Fix bug in vtkDataObjectTree::GetDataSet(vtkCompositeDataIterator*)<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkDataObjectTree.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkDataObjectTree.h\"\n\n#include \"vtkDataObjectTreeIterator.h\"\n#include \"vtkDataObjectTreeInternals.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationStringKey.h\"\n#include \"vtkInformationIntegerKey.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\/\/----------------------------------------------------------------------------\nvtkDataObjectTree::vtkDataObjectTree()\n{\n this->Internals = new vtkDataObjectTreeInternals;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObjectTree::~vtkDataObjectTree()\n{\n delete this->Internals;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetNumberOfChildren(unsigned int num)\n{\n this->Internals->Children.resize(num);\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned int vtkDataObjectTree::GetNumberOfChildren()\n{\n return static_cast<unsigned int>(this->Internals->Children.size());\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetChild(unsigned int index, vtkDataObject* dobj)\n{\n if (this->Internals->Children.size() <= index)\n {\n this->SetNumberOfChildren(index+1);\n }\n\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n if(item.DataObject!=dobj)\n {\n item.DataObject = dobj;\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::RemoveChild(unsigned int index)\n{\n if (this->Internals->Children.size() <= index)\n {\n vtkErrorMacro(\"The input index is out of range.\");\n return;\n }\n\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n item.DataObject = NULL;\n this->Internals->Children.erase(this->Internals->Children.begin()+index);\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObject* vtkDataObjectTree::GetChild(unsigned int index)\n{\n if (index < this->Internals->Children.size())\n {\n return this->Internals->Children[index].DataObject;\n }\n\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInformation* vtkDataObjectTree::GetChildMetaData(unsigned int index)\n{\n if (index < this->Internals->Children.size())\n {\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n if (!item.MetaData)\n {\n \/\/ New vtkInformation is allocated is none is already present.\n item.MetaData.TakeReference(vtkInformation::New());\n }\n return item.MetaData;\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetChildMetaData(unsigned int index, vtkInformation* info)\n{\n if (this->Internals->Children.size() <= index)\n {\n this->SetNumberOfChildren(index+1);\n }\n\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n item.MetaData = info;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkDataObjectTree::HasChildMetaData(unsigned int index)\n{\n if (index < this->Internals->Children.size())\n {\n vtkDataObjectTreeItem& item = this->Internals->Children[index];\n return (item.MetaData.GetPointer() != NULL)? 1 : 0;\n }\n\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::CopyStructure(vtkCompositeDataSet* compositeSource)\n{\n if(!compositeSource)\n {\n return;\n }\n vtkDataObjectTree* source = vtkDataObjectTree::SafeDownCast(compositeSource);\n if (source == this)\n {\n return;\n }\n\n this->Internals->Children.clear();\n if (!source)\n {\n \/\/WARNING:\n \/\/If we copy the structure of from a non-tree composite data set\n \/\/the \"structure\" is just is the total number of blocks (nill or not)\n \/\/To do: We should probably also copy meta data as well.\n int totalNumBlocks=0;\n vtkCompositeDataIterator* iter = compositeSource->NewIterator();\n iter->SkipEmptyNodesOff();\n for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())\n {\n totalNumBlocks++;\n }\n this->Internals->Children.resize(totalNumBlocks);\n iter->Delete();\n return;\n }\n\n this->Internals->Children.resize(source->Internals->Children.size());\n\n vtkDataObjectTreeInternals::Iterator srcIter =\n source->Internals->Children.begin();\n vtkDataObjectTreeInternals::Iterator myIter =\n this->Internals->Children.begin();\n for (; srcIter != source->Internals->Children.end(); ++srcIter, myIter++)\n {\n vtkDataObjectTree* compositeSrc =\n vtkDataObjectTree::SafeDownCast(srcIter->DataObject);\n if (compositeSrc)\n {\n vtkDataObjectTree* copy = compositeSrc->NewInstance();\n myIter->DataObject.TakeReference(copy);\n copy->CopyStructure(compositeSrc);\n }\n\n \/\/ shallow copy meta data.\n if (srcIter->MetaData)\n {\n vtkInformation* info = vtkInformation::New();\n info->Copy(srcIter->MetaData, \/*deep=*\/0);\n myIter->MetaData = info;\n info->FastDelete();\n }\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkCompositeDataIterator* vtkDataObjectTree::NewIterator()\n{\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::New();\n iter->SetDataSet(this);\n return iter;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetDataSet(vtkCompositeDataIterator* iter,\n vtkDataObject* dataObj)\n{\n vtkDataObjectTreeIterator* treeIter = vtkDataObjectTreeIterator::SafeDownCast(iter);\n if(treeIter)\n {\n this->SetDataSetFrom(treeIter,dataObj);\n return;\n }\n\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return;\n }\n\n\n vtkDataObjectTree* parent = this;\n unsigned int index = iter->GetCurrentFlatIndex();\n parent->SetChild(index, dataObj);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::SetDataSetFrom(vtkDataObjectTreeIterator* iter,\n vtkDataObject* dataObj)\n{\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return;\n }\n\n vtkDataObjectTreeIndex index = iter->GetCurrentIndex();\n\n if (index.size() == 0)\n {\n \/\/ Sanity check.\n vtkErrorMacro(\"Invalid index returned by iterator.\");\n return;\n }\n\n vtkDataObjectTree* parent = this;\n int numIndices = static_cast<int>(index.size());\n for (int cc=0; cc < numIndices-1; cc++)\n {\n if (!parent || parent->GetNumberOfChildren() <= index[cc])\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return;\n }\n parent = vtkDataObjectTree::SafeDownCast(parent->GetChild(index[cc]));\n }\n\n if (!parent || parent->GetNumberOfChildren() <= index.back())\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return;\n }\n\n parent->SetChild(index.back(), dataObj);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObject* vtkDataObjectTree::GetDataSet(vtkCompositeDataIterator* compositeIter)\n{\n if (!compositeIter || compositeIter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return 0;\n }\n\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(compositeIter);\n if (!iter)\n {\n \/\/It might be the case that the multiblock data set is a flat\n \/\/ tree with the same number of data sets as pointed by compsiteIter.\n \/\/So we will try to work with it here.\n \/\/To do: More clear check of structures here. At least something like this->Depth()==1\n unsigned int currentFlatIndex = compositeIter->GetCurrentFlatIndex();\n if(currentFlatIndex < this->GetNumberOfChildren())\n {\n return this->GetChild(currentFlatIndex);\n }\n else\n {\n return 0;\n }\n }\n\n vtkDataObjectTreeIndex index = iter->GetCurrentIndex();\n\n if (index.size() == 0)\n {\n \/\/ Sanity check.\n vtkErrorMacro(\"Invalid index returned by iterator.\");\n return 0;\n }\n\n vtkDataObjectTree* parent = this;\n int numIndices = static_cast<int>(index.size());\n for (int cc=0; cc < numIndices-1; cc++)\n {\n if (!parent || parent->GetNumberOfChildren() <= index[cc])\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n parent = vtkDataObjectTree::SafeDownCast(parent->GetChild(index[cc]));\n }\n\n if (!parent || parent->GetNumberOfChildren() <= index.back())\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n\n return parent->GetChild(index.back());\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInformation* vtkDataObjectTree::GetMetaData(vtkCompositeDataIterator* compositeIter)\n{\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(compositeIter);\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return 0;\n }\n\n vtkDataObjectTreeIndex index = iter->GetCurrentIndex();\n\n if (index.size() == 0)\n {\n \/\/ Sanity check.\n vtkErrorMacro(\"Invalid index returned by iterator.\");\n return 0;\n }\n\n vtkDataObjectTree* parent = this;\n int numIndices = static_cast<int>(index.size());\n for (int cc=0; cc < numIndices-1; cc++)\n {\n if (!parent || parent->GetNumberOfChildren() <= index[cc])\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n parent = vtkDataObjectTree::SafeDownCast(parent->GetChild(index[cc]));\n }\n\n if (!parent || parent->GetNumberOfChildren() <= index.back())\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n\n return parent->GetChildMetaData(index.back());\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkDataObjectTree::HasMetaData(vtkCompositeDataIterator* compositeIter)\n{\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(compositeIter);\n if (!iter || iter->IsDoneWithTraversal())\n {\n vtkErrorMacro(\"Invalid iterator location.\");\n return 0;\n }\n\n vtkDataObjectTreeIndex index = iter->GetCurrentIndex();\n\n if (index.size() == 0)\n {\n \/\/ Sanity check.\n vtkErrorMacro(\"Invalid index returned by iterator.\");\n return 0;\n }\n\n vtkDataObjectTree* parent = this;\n int numIndices = static_cast<int>(index.size());\n for (int cc=0; cc < numIndices-1; cc++)\n {\n if (!parent || parent->GetNumberOfChildren() <= index[cc])\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n parent = vtkDataObjectTree::SafeDownCast(parent->GetChild(index[cc]));\n }\n\n if (!parent || parent->GetNumberOfChildren() <= index.back())\n {\n vtkErrorMacro(\"Structure does not match. \"\n \"You must use CopyStructure before calling this method.\");\n return 0;\n }\n\n return parent->HasChildMetaData(index.back());\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::ShallowCopy(vtkDataObject* src)\n{\n if (src == this)\n {\n return;\n }\n\n this->Internals->Children.clear();\n this->Superclass::ShallowCopy(src);\n\n vtkDataObjectTree* from = vtkDataObjectTree::SafeDownCast(src);\n if (from)\n {\n unsigned int numChildren = from->GetNumberOfChildren();\n this->SetNumberOfChildren(numChildren);\n for (unsigned int cc=0; cc < numChildren; cc++)\n {\n vtkDataObject* child = from->GetChild(cc);\n if (child)\n {\n if (child->IsA(\"vtkDataObjectTree\"))\n {\n vtkDataObject* clone = child->NewInstance();\n clone->ShallowCopy(child);\n this->SetChild(cc, clone);\n clone->FastDelete();\n }\n else\n {\n this->SetChild(cc, child);\n }\n }\n if (from->HasChildMetaData(cc))\n {\n vtkInformation* toInfo = this->GetChildMetaData(cc);\n toInfo->Copy(from->GetChildMetaData(cc), \/*deep=*\/0);\n }\n }\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::DeepCopy(vtkDataObject* src)\n{\n if (src == this)\n {\n return;\n }\n\n this->Internals->Children.clear();\n this->Superclass::DeepCopy(src);\n\n vtkDataObjectTree* from = vtkDataObjectTree::SafeDownCast(src);\n if (from)\n {\n unsigned int numChildren = from->GetNumberOfChildren();\n this->SetNumberOfChildren(numChildren);\n for (unsigned int cc=0; cc < numChildren; cc++)\n {\n vtkDataObject* fromChild = from->GetChild(cc);\n if (fromChild)\n {\n vtkDataObject* toChild = fromChild->NewInstance();\n toChild->DeepCopy(fromChild);\n this->SetChild(cc, toChild);\n toChild->FastDelete();\n if (from->HasChildMetaData(cc))\n {\n vtkInformation* toInfo = this->GetChildMetaData(cc);\n toInfo->Copy(from->GetChildMetaData(cc), \/*deep=*\/1);\n }\n }\n }\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::Initialize()\n{\n this->Internals->Children.clear();\n this->Superclass::Initialize();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkDataObjectTree::GetNumberOfPoints()\n{\n vtkIdType numPts = 0;\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(this->NewIterator());\n for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())\n {\n vtkDataSet* ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject());\n if (ds)\n {\n numPts += ds->GetNumberOfPoints();\n }\n }\n iter->Delete();\n return numPts;\n}\n\n\n\/\/----------------------------------------------------------------------------\nunsigned long vtkDataObjectTree::GetActualMemorySize()\n{\n unsigned long memSize = 0;\n vtkDataObjectTreeIterator* iter = vtkDataObjectTreeIterator::SafeDownCast(this->NewIterator());\n for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())\n {\n vtkDataObject* dobj = iter->GetCurrentDataObject();\n memSize += dobj->GetActualMemorySize();\n }\n iter->Delete();\n return memSize;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkDataObjectTree::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Number Of Children: \" << this->GetNumberOfChildren() << endl;\n for (unsigned int cc=0; cc < this->GetNumberOfChildren(); cc++)\n {\n vtkDataObject* child = this->GetChild(cc);\n if (child)\n {\n os << indent << \"Child \" << cc << \": \" << child->GetClassName() << endl;\n child->PrintSelf(os, indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Child \" << cc << \": NULL\" << endl;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 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#pragma once\n\n#include \"dll\/base_conf.hpp\"\n#include \"dll\/contrastive_divergence.hpp\"\n#include \"dll\/watcher.hpp\"\n#include \"dll\/util\/tmp.hpp\"\n\nnamespace dll {\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine. *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::layer_t member returns the type of the configured RBM.\n *\/\ntemplate <size_t NC_T, size_t NV_1, size_t NV_2, size_t K_T, size_t NW_1, size_t NW_2, typename... Parameters>\nstruct conv_rbm_desc {\n static constexpr size_t NV1 = NV_1; \/\/\/< The first dimension of the input\n static constexpr size_t NV2 = NV_2; \/\/\/< The second dimension of the input\n static constexpr size_t NW1 = NW_1; \/\/\/< The first dimension of the output\n static constexpr size_t NW2 = NW_2; \/\/\/< The second dimension of the output\n static constexpr size_t NC = NC_T; \/\/\/< The number of input channels\n static constexpr size_t K = K_T; \/\/\/< The number of filters\n\n \/*!\n * \\brief A list of all the parameters of the descriptor\n *\/\n using parameters = cpp::type_list<Parameters...>;\n\n \/*!\n * \\brief The batch size for training this layer\n *\/\n static constexpr size_t BatchSize = detail::get_value_v<batch_size<1>, Parameters...>;\n\n \/*!\n * \\brief The type of visible unit\n *\/\n static constexpr unit_type visible_unit = detail::get_value_v<visible<unit_type::BINARY>, Parameters...>;\n\n \/*!\n * \\brief The type of hidden unit\n *\/\n static constexpr unit_type hidden_unit = detail::get_value_v<hidden<unit_type::BINARY>, Parameters...>;\n\n \/*!\n * \\brief The sparsity penalty for pretraining\n *\/\n static constexpr sparsity_method Sparsity = detail::get_value_v<sparsity<sparsity_method::NONE>, Parameters...>;\n\n \/*!\n * \\brief The sparsity bias mode (LEE)\n *\/\n static constexpr bias_mode Bias = detail::get_value_v<bias<bias_mode::SIMPLE>, Parameters...>;\n\n \/*! The type used to store the weights *\/\n using weight = detail::get_type_t<weight_type<float>, Parameters...>;\n\n \/*! The type of the trainer to use to train the RBM *\/\n template <typename RBM>\n using trainer_t = typename detail::get_template_type<trainer_rbm<cd1_trainer_t>, Parameters...>::template value<RBM>;\n\n \/*! The type of the watched to use during training *\/\n template <typename RBM>\n using watcher_t = typename detail::get_template_type<watcher<default_rbm_watcher>, Parameters...>::template value<RBM>;\n\n \/*! The layer type *\/\n using layer_t = conv_rbm_impl<conv_rbm_desc<NC_T, NV1, NV2, K_T, NW1, NW2, Parameters...>>;\n\nprivate:\n template <typename... Args>\n struct dyn_layer_t_impl {\n using sequence = remove_type_id<batch_size_id, Args...>;\n\n using type = typename build_dyn_layer_t<dyn_conv_rbm_impl, dyn_conv_rbm_desc, sequence, Args...>::type;\n };\n\npublic:\n \/*!\n * The dynamic layer type\n *\/\n using dyn_layer_t = typename dyn_layer_t_impl<Parameters...>::type;\n\n \/\/Validate all parameters\n\n static_assert(NV1 > 0, \"A matrix of at least 1x1 is necessary for the visible units\");\n static_assert(NV2 > 0, \"A matrix of at least 1x1 is necessary for the visible units\");\n static_assert(NW1 > 0, \"A matrix of at least 1x1 is necessary for the kernel\");\n static_assert(NW2 > 0, \"A matrix of at least 1x1 is necessary for the kernel\");\n static_assert(NC > 0, \"At least one channel is necessary\");\n static_assert(K > 0, \"At least one group is necessary\");\n static_assert(BatchSize > 0, \"Batch size must be at least 1\");\n\n \/\/Make sure only valid types are passed to the configuration list\n static_assert(\n detail::is_valid_v<cpp::type_list<\n momentum_id, batch_size_id, visible_id, hidden_id, dbn_only_id,\n weight_decay_id, sparsity_id, trainer_rbm_id, watcher_id, clip_gradients_id,\n bias_id, weight_type_id, shuffle_id, verbose_id, nop_id>,\n Parameters...>,\n \"Invalid parameters type\");\n\n static_assert(Sparsity == sparsity_method::NONE || hidden_unit == unit_type::BINARY,\n \"Sparsity only works with binary hidden units\");\n};\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine with square inputs and filters.\n *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::rbm_t member returns the type of the configured RBM.\n *\/\ntemplate <size_t NC_T, size_t NV_T, size_t K_T, size_t NW_T, typename... Parameters>\nusing conv_rbm_square_desc = conv_rbm_desc<NC_T, NV_T, NV_T, K_T, NW_T, NW_T, Parameters...>;\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine. *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::layer_t member returns the type of the configured RBM.\n *\/\ntemplate <size_t NC_T, size_t NV_1, size_t NV_2, size_t K_T, size_t NW_1, size_t NW_2, typename... Parameters>\nusing conv_rbm = typename conv_rbm_desc<NC_T, NV_1, NV_2, K_T, NW_1, NW_2, Parameters...>::layer;\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine with square inputs and filters.\n *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::rbm_t member returns the type of the configured RBM.\n *\/\ntemplate <size_t NC_T, size_t NV_T, size_t K_T, size_t NW_T, typename... Parameters>\nusing conv_rbm_square = typename conv_rbm_desc<NC_T, NV_T, NV_T, K_T, NW_T, NW_T, Parameters...>::layer;\n\n} \/\/end of dll namespace\n<commit_msg>Fix bug for conv_rbm<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 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#pragma once\n\n#include \"dll\/base_conf.hpp\"\n#include \"dll\/contrastive_divergence.hpp\"\n#include \"dll\/watcher.hpp\"\n#include \"dll\/util\/tmp.hpp\"\n\nnamespace dll {\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine. *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::layer_t member returns the type of the configured RBM.\n *\/\ntemplate <size_t NC_T, size_t NV_1, size_t NV_2, size_t K_T, size_t NW_1, size_t NW_2, typename... Parameters>\nstruct conv_rbm_desc {\n static constexpr size_t NV1 = NV_1; \/\/\/< The first dimension of the input\n static constexpr size_t NV2 = NV_2; \/\/\/< The second dimension of the input\n static constexpr size_t NW1 = NW_1; \/\/\/< The first dimension of the output\n static constexpr size_t NW2 = NW_2; \/\/\/< The second dimension of the output\n static constexpr size_t NC = NC_T; \/\/\/< The number of input channels\n static constexpr size_t K = K_T; \/\/\/< The number of filters\n\n \/*!\n * \\brief A list of all the parameters of the descriptor\n *\/\n using parameters = cpp::type_list<Parameters...>;\n\n \/*!\n * \\brief The batch size for training this layer\n *\/\n static constexpr size_t BatchSize = detail::get_value_v<batch_size<1>, Parameters...>;\n\n \/*!\n * \\brief The type of visible unit\n *\/\n static constexpr unit_type visible_unit = detail::get_value_v<visible<unit_type::BINARY>, Parameters...>;\n\n \/*!\n * \\brief The type of hidden unit\n *\/\n static constexpr unit_type hidden_unit = detail::get_value_v<hidden<unit_type::BINARY>, Parameters...>;\n\n \/*!\n * \\brief The sparsity penalty for pretraining\n *\/\n static constexpr sparsity_method Sparsity = detail::get_value_v<sparsity<sparsity_method::NONE>, Parameters...>;\n\n \/*!\n * \\brief The sparsity bias mode (LEE)\n *\/\n static constexpr bias_mode Bias = detail::get_value_v<bias<bias_mode::SIMPLE>, Parameters...>;\n\n \/*! The type used to store the weights *\/\n using weight = detail::get_type_t<weight_type<float>, Parameters...>;\n\n \/*! The type of the trainer to use to train the RBM *\/\n template <typename RBM>\n using trainer_t = typename detail::get_template_type<trainer_rbm<cd1_trainer_t>, Parameters...>::template value<RBM>;\n\n \/*! The type of the watched to use during training *\/\n template <typename RBM>\n using watcher_t = typename detail::get_template_type<watcher<default_rbm_watcher>, Parameters...>::template value<RBM>;\n\n \/*! The layer type *\/\n using layer_t = conv_rbm_impl<conv_rbm_desc<NC_T, NV1, NV2, K_T, NW1, NW2, Parameters...>>;\n\nprivate:\n template <typename... Args>\n struct dyn_layer_t_impl {\n using sequence = remove_type_id<batch_size_id, Args...>;\n\n using type = typename build_dyn_layer_t<dyn_conv_rbm_impl, dyn_conv_rbm_desc, sequence, Args...>::type;\n };\n\npublic:\n \/*!\n * The dynamic layer type\n *\/\n using dyn_layer_t = typename dyn_layer_t_impl<Parameters...>::type;\n\n \/\/Validate all parameters\n\n static_assert(NV1 > 0, \"A matrix of at least 1x1 is necessary for the visible units\");\n static_assert(NV2 > 0, \"A matrix of at least 1x1 is necessary for the visible units\");\n static_assert(NW1 > 0, \"A matrix of at least 1x1 is necessary for the kernel\");\n static_assert(NW2 > 0, \"A matrix of at least 1x1 is necessary for the kernel\");\n static_assert(NC > 0, \"At least one channel is necessary\");\n static_assert(K > 0, \"At least one group is necessary\");\n static_assert(BatchSize > 0, \"Batch size must be at least 1\");\n\n \/\/Make sure only valid types are passed to the configuration list\n static_assert(\n detail::is_valid_v<cpp::type_list<\n momentum_id, batch_size_id, visible_id, hidden_id, dbn_only_id,\n weight_decay_id, sparsity_id, trainer_rbm_id, watcher_id, clip_gradients_id,\n bias_id, weight_type_id, shuffle_id, verbose_id, nop_id>,\n Parameters...>,\n \"Invalid parameters type\");\n\n static_assert(Sparsity == sparsity_method::NONE || hidden_unit == unit_type::BINARY,\n \"Sparsity only works with binary hidden units\");\n};\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine with square inputs and filters.\n *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::rbm_t member returns the type of the configured RBM.\n *\/\ntemplate <size_t NC_T, size_t NV_T, size_t K_T, size_t NW_T, typename... Parameters>\nusing conv_rbm_square_desc = conv_rbm_desc<NC_T, NV_T, NV_T, K_T, NW_T, NW_T, Parameters...>;\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine. *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::layer_t member returns the type of the configured RBM.\n *\/\ntemplate <size_t NC_T, size_t NV_1, size_t NV_2, size_t K_T, size_t NW_1, size_t NW_2, typename... Parameters>\nusing conv_rbm = typename conv_rbm_desc<NC_T, NV_1, NV_2, K_T, NW_1, NW_2, Parameters...>::layer_t;\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine with square inputs and filters.\n *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::rbm_t member returns the type of the configured RBM.\n *\/\ntemplate <size_t NC_T, size_t NV_T, size_t K_T, size_t NW_T, typename... Parameters>\nusing conv_rbm_square = typename conv_rbm_desc<NC_T, NV_T, NV_T, K_T, NW_T, NW_T, Parameters...>::layer_t;\n\n} \/\/end of dll namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of libigl, a simple c++ geometry processing library.\n\/\/ \n\/\/ Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n\/\/ \n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n#ifdef __AVX__\n#include \"svd3x3_avx.h\"\n\n#include <cmath>\n#include <algorithm>\n\n#undef USE_SCALAR_IMPLEMENTATION\n#undef USE_SSE_IMPLEMENTATION\n#define USE_AVX_IMPLEMENTATION\n#define COMPUTE_U_AS_MATRIX\n#define COMPUTE_V_AS_MATRIX\n#include \"Singular_Value_Decomposition_Preamble.hpp\"\n\n#pragma runtime_checks( \"u\", off ) \/\/ disable runtime asserts on xor eax,eax type of stuff (doesn't always work, disable explicitly in compiler settings)\ntemplate<typename T>\nIGL_INLINE void igl::svd3x3_avx(\n const Eigen::Matrix<T, 3*8, 3>& A, \n Eigen::Matrix<T, 3*8, 3> &U, \n Eigen::Matrix<T, 3*8, 1> &S, \n Eigen::Matrix<T, 3*8, 3>&V)\n{\n \/\/ this code assumes USE_AVX_IMPLEMENTATION is defined \n float Ashuffle[9][8], Ushuffle[9][8], Vshuffle[9][8], Sshuffle[3][8];\n for (int i=0; i<3; i++)\n {\n for (int j=0; j<3; j++)\n {\n for (int k=0; k<8; k++)\n {\n Ashuffle[i + j*3][k] = A(i + 3*k, j);\n }\n }\n }\n\n#include \"Singular_Value_Decomposition_Kernel_Declarations.hpp\"\n\n ENABLE_AVX_IMPLEMENTATION(Va11=_mm256_loadu_ps(Ashuffle[0]);)\n ENABLE_AVX_IMPLEMENTATION(Va21=_mm256_loadu_ps(Ashuffle[1]);)\n ENABLE_AVX_IMPLEMENTATION(Va31=_mm256_loadu_ps(Ashuffle[2]);)\n ENABLE_AVX_IMPLEMENTATION(Va12=_mm256_loadu_ps(Ashuffle[3]);)\n ENABLE_AVX_IMPLEMENTATION(Va22=_mm256_loadu_ps(Ashuffle[4]);)\n ENABLE_AVX_IMPLEMENTATION(Va32=_mm256_loadu_ps(Ashuffle[5]);)\n ENABLE_AVX_IMPLEMENTATION(Va13=_mm256_loadu_ps(Ashuffle[6]);)\n ENABLE_AVX_IMPLEMENTATION(Va23=_mm256_loadu_ps(Ashuffle[7]);)\n ENABLE_AVX_IMPLEMENTATION(Va33=_mm256_loadu_ps(Ashuffle[8]);)\n\n#include \"Singular_Value_Decomposition_Main_Kernel_Body.hpp\"\n\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[0],Vu11);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[1],Vu21);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[2],Vu31);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[3],Vu12);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[4],Vu22);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[5],Vu32);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[6],Vu13);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[7],Vu23);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[8],Vu33);)\n\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[0],Vv11);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[1],Vv21);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[2],Vv31);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[3],Vv12);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[4],Vv22);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[5],Vv32);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[6],Vv13);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[7],Vv23);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[8],Vv33);)\n\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Sshuffle[0],Va11);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Sshuffle[1],Va22);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Sshuffle[2],Va33);)\n\n for (int i=0; i<3; i++)\n {\n for (int j=0; j<3; j++)\n {\n for (int k=0; k<8; k++)\n {\n U(i + 3*k, j) = Ushuffle[i + j*3][k];\n V(i + 3*k, j) = Vshuffle[i + j*3][k];\n }\n }\n }\n\n for (int i=0; i<3; i++)\n {\n for (int k=0; k<8; k++)\n {\n S(i + 3*k, 0) = Sshuffle[i][k];\n }\n }\n}\n#pragma runtime_checks( \"u\", restore )\n\n\/\/ forced instantiation\ntemplate void igl::svd3x3_avx(const Eigen::Matrix<float, 3*8, 3>& A, Eigen::Matrix<float, 3*8, 3> &U, Eigen::Matrix<float, 3*8, 1> &S, Eigen::Matrix<float, 3*8, 3>&V);\n\/\/ doesn't even make sense with double because the wunder-SVD code is only single precision anyway...\ntemplate void igl::svd3x3_avx<float>(Eigen::Matrix<float, 24, 3, 0, 24, 3> const&, Eigen::Matrix<float, 24, 3, 0, 24, 3>&, Eigen::Matrix<float, 24, 1, 0, 24, 1>&, Eigen::Matrix<float, 24, 3, 0, 24, 3>&);\n#endif\n<commit_msg>Fixed explicit instantiation problem when compiling as header-only.<commit_after>\/\/ This file is part of libigl, a simple c++ geometry processing library.\n\/\/ \n\/\/ Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n\/\/ \n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n#ifdef __AVX__\n#include \"svd3x3_avx.h\"\n\n#include <cmath>\n#include <algorithm>\n\n#undef USE_SCALAR_IMPLEMENTATION\n#undef USE_SSE_IMPLEMENTATION\n#define USE_AVX_IMPLEMENTATION\n#define COMPUTE_U_AS_MATRIX\n#define COMPUTE_V_AS_MATRIX\n#include \"Singular_Value_Decomposition_Preamble.hpp\"\n\n#pragma runtime_checks( \"u\", off ) \/\/ disable runtime asserts on xor eax,eax type of stuff (doesn't always work, disable explicitly in compiler settings)\ntemplate<typename T>\nIGL_INLINE void igl::svd3x3_avx(\n const Eigen::Matrix<T, 3*8, 3>& A, \n Eigen::Matrix<T, 3*8, 3> &U, \n Eigen::Matrix<T, 3*8, 1> &S, \n Eigen::Matrix<T, 3*8, 3>&V)\n{\n \/\/ this code assumes USE_AVX_IMPLEMENTATION is defined \n float Ashuffle[9][8], Ushuffle[9][8], Vshuffle[9][8], Sshuffle[3][8];\n for (int i=0; i<3; i++)\n {\n for (int j=0; j<3; j++)\n {\n for (int k=0; k<8; k++)\n {\n Ashuffle[i + j*3][k] = A(i + 3*k, j);\n }\n }\n }\n\n#include \"Singular_Value_Decomposition_Kernel_Declarations.hpp\"\n\n ENABLE_AVX_IMPLEMENTATION(Va11=_mm256_loadu_ps(Ashuffle[0]);)\n ENABLE_AVX_IMPLEMENTATION(Va21=_mm256_loadu_ps(Ashuffle[1]);)\n ENABLE_AVX_IMPLEMENTATION(Va31=_mm256_loadu_ps(Ashuffle[2]);)\n ENABLE_AVX_IMPLEMENTATION(Va12=_mm256_loadu_ps(Ashuffle[3]);)\n ENABLE_AVX_IMPLEMENTATION(Va22=_mm256_loadu_ps(Ashuffle[4]);)\n ENABLE_AVX_IMPLEMENTATION(Va32=_mm256_loadu_ps(Ashuffle[5]);)\n ENABLE_AVX_IMPLEMENTATION(Va13=_mm256_loadu_ps(Ashuffle[6]);)\n ENABLE_AVX_IMPLEMENTATION(Va23=_mm256_loadu_ps(Ashuffle[7]);)\n ENABLE_AVX_IMPLEMENTATION(Va33=_mm256_loadu_ps(Ashuffle[8]);)\n\n#include \"Singular_Value_Decomposition_Main_Kernel_Body.hpp\"\n\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[0],Vu11);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[1],Vu21);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[2],Vu31);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[3],Vu12);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[4],Vu22);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[5],Vu32);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[6],Vu13);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[7],Vu23);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Ushuffle[8],Vu33);)\n\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[0],Vv11);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[1],Vv21);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[2],Vv31);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[3],Vv12);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[4],Vv22);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[5],Vv32);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[6],Vv13);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[7],Vv23);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Vshuffle[8],Vv33);)\n\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Sshuffle[0],Va11);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Sshuffle[1],Va22);)\n ENABLE_AVX_IMPLEMENTATION(_mm256_storeu_ps(Sshuffle[2],Va33);)\n\n for (int i=0; i<3; i++)\n {\n for (int j=0; j<3; j++)\n {\n for (int k=0; k<8; k++)\n {\n U(i + 3*k, j) = Ushuffle[i + j*3][k];\n V(i + 3*k, j) = Vshuffle[i + j*3][k];\n }\n }\n }\n\n for (int i=0; i<3; i++)\n {\n for (int k=0; k<8; k++)\n {\n S(i + 3*k, 0) = Sshuffle[i][k];\n }\n }\n}\n#pragma runtime_checks( \"u\", restore )\n\n#ifdef IGL_STATIC_LIBRARY\n\/\/ forced instantiation\ntemplate void igl::svd3x3_avx(const Eigen::Matrix<float, 3*8, 3>& A, Eigen::Matrix<float, 3*8, 3> &U, Eigen::Matrix<float, 3*8, 1> &S, Eigen::Matrix<float, 3*8, 3>&V);\n\/\/ doesn't even make sense with double because the wunder-SVD code is only single precision anyway...\ntemplate void igl::svd3x3_avx<float>(Eigen::Matrix<float, 24, 3, 0, 24, 3> const&, Eigen::Matrix<float, 24, 3, 0, 24, 3>&, Eigen::Matrix<float, 24, 1, 0, 24, 1>&, Eigen::Matrix<float, 24, 3, 0, 24, 3>&);\n#endif\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file pod_vector.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POD_VECTOR_HPP\n#define POD_VECTOR_HPP\n\n#include \"macros.hpp\"\n\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <type_traits>\n#include <utility>\n\nnamespace primesieve {\n\n\/\/\/ pod_vector is a dynamically growing array.\n\/\/\/ It has the same API (though not complete) as std::vector but its\n\/\/\/ resize() method does not default initialize memory for built-in\n\/\/\/ integer types. It does however default initialize classes and\n\/\/\/ struct types if they have a constructor. It also prevents\n\/\/\/ bounds checks which is important for primesieve's performance, e.g.\n\/\/\/ the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS\n\/\/\/ which enables std::vector bounds checks.\n\/\/\/\ntemplate <typename T>\nclass pod_vector\n{\npublic:\n static_assert(std::is_trivially_destructible<T>::value,\n \"pod_vector<T> only supports types with trivial destructors!\");\n\n using value_type = T;\n pod_vector() noexcept = default;\n\n pod_vector(std::size_t size)\n {\n resize(size);\n }\n\n ~pod_vector()\n {\n delete [] array_;\n }\n\n \/\/\/ Free all memory, the pod_vector\n \/\/\/ can be reused afterwards.\n void free() noexcept\n {\n delete [] array_;\n array_ = nullptr;\n end_ = nullptr;\n capacity_ = nullptr;\n }\n\n \/\/\/ Reset the pod_vector, but do not free its\n \/\/\/ memory. Same as std::vector.clear().\n void clear() noexcept\n {\n end_ = array_;\n }\n\n \/\/\/ Copying is slow, we prevent it\n pod_vector(const pod_vector&) = delete;\n pod_vector& operator=(const pod_vector&) = delete;\n\n \/\/\/ Move constructor\n pod_vector(pod_vector&& other) noexcept\n {\n std::swap(array_, other.array_);\n std::swap(end_, other.end_);\n std::swap(capacity_, other.capacity_);\n }\n\n \/\/\/ Move assignment operator\n pod_vector& operator=(pod_vector&& other) noexcept\n {\n if (this != &other)\n {\n std::swap(array_, other.array_);\n std::swap(end_, other.end_);\n std::swap(capacity_, other.capacity_);\n }\n\n return *this;\n }\n\n bool empty() const noexcept\n {\n return array_ == end_;\n }\n\n T& operator[] (std::size_t pos) noexcept\n {\n \/\/ For performance reasons primesieve is allowed to access\n \/\/ memory with pos > size() but <= capacity().\n assert(pos <= capacity());\n return array_[pos];\n }\n\n T& operator[] (std::size_t pos) const noexcept\n {\n \/\/ For performance reasons primesieve is allowed to access\n \/\/ memory with pos > size() but <= capacity().\n assert(pos <= capacity());\n return array_[pos];\n }\n\n T* data() noexcept\n {\n return array_;\n }\n\n T* data() const noexcept\n {\n return array_;\n }\n\n std::size_t size() const noexcept\n {\n assert(end_ >= array_);\n return (std::size_t)(end_ - array_);\n }\n\n std::size_t capacity() const noexcept\n {\n assert(capacity_ >= array_);\n return (std::size_t)(capacity_ - array_);\n }\n\n T* begin() noexcept\n {\n return array_;\n }\n\n T* begin() const noexcept\n {\n return array_;\n }\n\n T* end() noexcept\n {\n return end_;\n }\n\n T* end() const noexcept\n {\n return end_;\n }\n\n T& front() noexcept\n {\n return *array_;\n }\n\n T& front() const noexcept\n {\n return *array_;\n }\n\n T& back() noexcept\n {\n assert(end_ != nullptr);\n return *(end_ - 1);\n }\n\n T& back() const noexcept\n {\n assert(end_ != nullptr);\n return *(end_ - 1);\n }\n\n ALWAYS_INLINE void push_back(const T& value)\n {\n if_unlikely(end_ == capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = value;\n }\n\n ALWAYS_INLINE void push_back(T&& value)\n {\n if_unlikely(end_ == capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = value;\n }\n\n template <class... Args>\n ALWAYS_INLINE void emplace_back(Args&&... args)\n {\n if_unlikely(end_ == capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = T(std::forward<Args>(args)...);\n }\n\n void reserve(std::size_t n)\n {\n if (n > capacity())\n {\n T* old = array_;\n std::size_t old_size = size();\n std::size_t new_capacity = get_new_capacity<T>(n);\n assert(new_capacity >= n);\n assert(new_capacity > old_size);\n\n \/\/ This default initializes memory of classes and\n \/\/ structs with constructors. But it does not default\n \/\/ initialize memory for POD types like int, long.\n array_ = new T[new_capacity];\n end_ = array_ + old_size;\n capacity_ = array_ + new_capacity;\n\n if (old)\n {\n std::copy_n(old, old_size, array_);\n delete [] old;\n }\n }\n }\n\n \/\/\/ Resize without default initializing memory.\n \/\/\/ If the pod_vector is not empty the current content\n \/\/\/ will be copied into the new array.\n \/\/\/\n void resize(std::size_t n)\n {\n if (n == size())\n return;\n else if (n <= capacity())\n {\n assert(capacity() > 0);\n\n \/\/ This will only be used for classes\n \/\/ and structs with constructors.\n if (n > size())\n default_initialize_range(end_, array_ + n);\n\n end_ = array_ + n;\n }\n else\n {\n T* old = array_;\n std::size_t old_size = size();\n std::size_t new_capacity = get_new_capacity<T>(n);\n assert(new_capacity >= n);\n assert(new_capacity > old_size);\n\n \/\/ This default initializes memory of classes and\n \/\/ structs with constructors. But it does not default\n \/\/ initialize memory for POD types like int, long.\n array_ = new T[new_capacity];\n end_ = array_ + n;\n capacity_ = array_ + new_capacity;\n\n if (old)\n {\n std::copy_n(old, old_size, array_);\n delete [] old;\n }\n }\n }\n\nprivate:\n T* array_ = nullptr;\n T* end_ = nullptr;\n T* capacity_ = nullptr;\n\n template <typename U>\n ALWAYS_INLINE typename std::enable_if<std::is_trivial<U>::value>::type\n default_initialize_range(U*, U*)\n { }\n\n template <typename U>\n ALWAYS_INLINE typename std::enable_if<!std::is_trivial<U>::value>::type\n default_initialize_range(U* first, U* last)\n {\n std::fill(first, last, U());\n }\n\n template <typename U>\n ALWAYS_INLINE typename std::enable_if<std::is_trivial<U>::value, std::size_t>::type\n get_new_capacity(std::size_t size)\n {\n assert(size > 0);\n \/\/ GCC & Clang's std::vector grow the capacity by at least\n \/\/ 2x for every call to resize() with n > capacity(). We\n \/\/ grow by at least 1.5x as we tend to accurately calculate\n \/\/ the amount of memory we need upfront.\n std::size_t new_capacity = (std::size_t)(capacity() * 1.5);\n constexpr std::size_t min_alignment = sizeof(long) * 2;\n constexpr std::size_t min_capacity = min_alignment \/ sizeof(U);\n return std::max({min_capacity, size, new_capacity});\n }\n\n template <typename U>\n ALWAYS_INLINE typename std::enable_if<!std::is_trivial<U>::value, std::size_t>::type\n get_new_capacity(std::size_t size)\n {\n assert(size > 0);\n \/\/ GCC & Clang's std::vector grow the capacity by at least\n \/\/ 2x for every call to resize() with n > capacity(). We\n \/\/ grow by at least 1.5x as we tend to accurately calculate\n \/\/ the amount of memory we need upfront.\n std::size_t new_capacity = (std::size_t)(capacity() * 1.5);\n return std::max(size, new_capacity);\n }\n};\n\n} \/\/ namespace\n\n#endif\n<commit_msg>Refactor resize()<commit_after>\/\/\/\n\/\/\/ @file pod_vector.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POD_VECTOR_HPP\n#define POD_VECTOR_HPP\n\n#include \"macros.hpp\"\n\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <type_traits>\n#include <utility>\n\nnamespace primesieve {\n\n\/\/\/ pod_vector is a dynamically growing array.\n\/\/\/ It has the same API (though not complete) as std::vector but its\n\/\/\/ resize() method does not default initialize memory for built-in\n\/\/\/ integer types. It does however default initialize classes and\n\/\/\/ struct types if they have a constructor. It also prevents\n\/\/\/ bounds checks which is important for primesieve's performance, e.g.\n\/\/\/ the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS\n\/\/\/ which enables std::vector bounds checks.\n\/\/\/\ntemplate <typename T>\nclass pod_vector\n{\npublic:\n static_assert(std::is_trivially_destructible<T>::value,\n \"pod_vector<T> only supports types with trivial destructors!\");\n\n using value_type = T;\n pod_vector() noexcept = default;\n\n pod_vector(std::size_t size)\n {\n resize(size);\n }\n\n ~pod_vector()\n {\n delete [] array_;\n }\n\n \/\/\/ Free all memory, the pod_vector\n \/\/\/ can be reused afterwards.\n void free() noexcept\n {\n delete [] array_;\n array_ = nullptr;\n end_ = nullptr;\n capacity_ = nullptr;\n }\n\n \/\/\/ Reset the pod_vector, but do not free its\n \/\/\/ memory. Same as std::vector.clear().\n void clear() noexcept\n {\n end_ = array_;\n }\n\n \/\/\/ Copying is slow, we prevent it\n pod_vector(const pod_vector&) = delete;\n pod_vector& operator=(const pod_vector&) = delete;\n\n \/\/\/ Move constructor\n pod_vector(pod_vector&& other) noexcept\n {\n std::swap(array_, other.array_);\n std::swap(end_, other.end_);\n std::swap(capacity_, other.capacity_);\n }\n\n \/\/\/ Move assignment operator\n pod_vector& operator=(pod_vector&& other) noexcept\n {\n if (this != &other)\n {\n std::swap(array_, other.array_);\n std::swap(end_, other.end_);\n std::swap(capacity_, other.capacity_);\n }\n\n return *this;\n }\n\n bool empty() const noexcept\n {\n return array_ == end_;\n }\n\n T& operator[](std::size_t pos) noexcept\n {\n \/\/ For performance reasons primesieve is allowed to access\n \/\/ memory with pos > size() but <= capacity().\n assert(pos <= capacity());\n return array_[pos];\n }\n\n T& operator[](std::size_t pos) const noexcept\n {\n \/\/ For performance reasons primesieve is allowed to access\n \/\/ memory with pos > size() but <= capacity().\n assert(pos <= capacity());\n return array_[pos];\n }\n\n T* data() noexcept\n {\n return array_;\n }\n\n T* data() const noexcept\n {\n return array_;\n }\n\n std::size_t size() const noexcept\n {\n assert(end_ >= array_);\n return (std::size_t)(end_ - array_);\n }\n\n std::size_t capacity() const noexcept\n {\n assert(capacity_ >= array_);\n return (std::size_t)(capacity_ - array_);\n }\n\n T* begin() noexcept\n {\n return array_;\n }\n\n T* begin() const noexcept\n {\n return array_;\n }\n\n T* end() noexcept\n {\n return end_;\n }\n\n T* end() const noexcept\n {\n return end_;\n }\n\n T& front() noexcept\n {\n return *array_;\n }\n\n T& front() const noexcept\n {\n return *array_;\n }\n\n T& back() noexcept\n {\n assert(end_ != nullptr);\n return *(end_ - 1);\n }\n\n T& back() const noexcept\n {\n assert(end_ != nullptr);\n return *(end_ - 1);\n }\n\n ALWAYS_INLINE void push_back(const T& value)\n {\n if_unlikely(end_ == capacity_)\n reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = value;\n }\n\n ALWAYS_INLINE void push_back(T&& value)\n {\n if_unlikely(end_ == capacity_)\n reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = value;\n }\n\n template <class... Args>\n ALWAYS_INLINE void emplace_back(Args&&... args)\n {\n if_unlikely(end_ == capacity_)\n reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = T(std::forward<Args>(args)...);\n }\n\n void reserve(std::size_t n)\n {\n if (n > capacity())\n reserve_unchecked(n);\n }\n\n \/\/\/ Resize without default initializing memory.\n \/\/\/ If the pod_vector is not empty the current content\n \/\/\/ will be copied into the new array.\n \/\/\/\n void resize(std::size_t n)\n {\n if (n > capacity())\n reserve_unchecked(n);\n else if (!std::is_trivial<T>::value && n > size())\n {\n \/\/ This will only be used for classes\n \/\/ and structs with constructors.\n assert(n <= capacity());\n std::fill(end_, array_ + n, T());\n }\n\n end_ = array_ + n;\n }\n\nprivate:\n T* array_ = nullptr;\n T* end_ = nullptr;\n T* capacity_ = nullptr;\n\n void reserve_unchecked(std::size_t n)\n {\n assert(n > capacity());\n std::size_t new_capacity = get_new_capacity<T>(n);\n std::size_t old_size = size();\n assert(new_capacity >= n);\n assert(new_capacity > old_size);\n\n \/\/ This default initializes memory of classes and\n \/\/ structs with constructors. But it does not default\n \/\/ initialize memory for POD types like int, long.\n T* old = array_;\n array_ = new T[new_capacity];\n end_ = array_ + old_size;\n capacity_ = array_ + new_capacity;\n\n if (old)\n {\n std::copy_n(old, old_size, array_);\n delete [] old;\n }\n }\n\n template <typename U>\n ALWAYS_INLINE typename std::enable_if<std::is_trivial<U>::value, std::size_t>::type\n get_new_capacity(std::size_t size)\n {\n assert(size > 0);\n \/\/ GCC & Clang's std::vector grow the capacity by at least\n \/\/ 2x for every call to resize() with n > capacity(). We\n \/\/ grow by at least 1.5x as we tend to accurately calculate\n \/\/ the amount of memory we need upfront.\n std::size_t new_capacity = (std::size_t)(capacity() * 1.5);\n constexpr std::size_t min_alignment = sizeof(long) * 2;\n constexpr std::size_t min_capacity = min_alignment \/ sizeof(U);\n return std::max({min_capacity, size, new_capacity});\n }\n\n template <typename U>\n ALWAYS_INLINE typename std::enable_if<!std::is_trivial<U>::value, std::size_t>::type\n get_new_capacity(std::size_t size)\n {\n assert(size > 0);\n \/\/ GCC & Clang's std::vector grow the capacity by at least\n \/\/ 2x for every call to resize() with n > capacity(). We\n \/\/ grow by at least 1.5x as we tend to accurately calculate\n \/\/ the amount of memory we need upfront.\n std::size_t new_capacity = (std::size_t)(capacity() * 1.5);\n return std::max(size, new_capacity);\n }\n};\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef TWISTEDCPP_PROTOCOL_CORE\n#define TWISTEDCPP_PROTOCOL_CORE\n\n#include \"detail\/sockets.hpp\"\n\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/asio\/steady_timer.hpp>\n#include <boost\/optional.hpp>\n#include <boost\/asio\/spawn.hpp>\n#include <boost\/asio\/write.hpp>\n#include <boost\/asio\/high_resolution_timer.hpp>\n#include <boost\/ref.hpp>\n\n#ifndef NDEBUG\n#include <iostream>\n#endif\n\nnamespace twisted {\n\ntemplate <typename ChildProtocol, typename BufferType>\nclass protocol_core : public std::enable_shared_from_this<ChildProtocol> {\npublic:\n typedef detail::socket_base socket_type;\n typedef boost::asio::steady_timer timer_type;\n typedef boost::asio::io_service::strand strand_type;\n typedef BufferType buffer_type;\n typedef typename buffer_type::iterator buffer_iterator;\n typedef typename buffer_type::const_iterator const_buffer_iterator;\n\n protocol_core() = default;\n protocol_core(protocol_core&&) = default;\n protocol_core& operator=(protocol_core&&) = default;\n\n void set_socket(std::unique_ptr<socket_type> socket) {\n _socket = std::move(socket);\n }\n\n void run_protocol() {\n auto self = this_protocol().shared_from_this();\n boost::asio::spawn(_socket->get_io_service(),\n [this, self](boost::asio::yield_context yield) {\n _yield = boost::in_place(yield);\n\n try {\n _socket->do_handshake(*_yield);\n\n while (_socket->is_open()) {\n auto bytes_read =\n _socket->async_read_some(asio_buffer(), yield);\n this_protocol().on_message(\n buffer_begin(), std::next(buffer_begin(), bytes_read));\n }\n }\n catch (boost::system::system_error& connection_error) {\n handle_network_error(connection_error);\n }\n catch (...) {\n handle_user_error(std::current_exception());\n }\n });\n }\n\n template <typename Duration, typename Callable>\n void call_later(Duration duration, Callable callable) {\n auto self = this_protocol().shared_from_this();\n \/\/ we pass our existing yield_context and not the io_service such that\n \/\/ both contexts run under the same strand\n boost::asio::spawn(*_yield, [this, duration, callable, self](\n boost::asio::yield_context yield) {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(yield);\n\n \/\/ we need to exchange the yield context so that that the user can\n \/\/ use the send_message function in the right context\n boost::optional<boost::asio::yield_context> old_yield(\n boost::in_place(*_yield));\n _yield = boost::in_place(yield);\n callable();\n _yield = boost::in_place(*old_yield);\n });\n }\n\n template <typename Callable, typename... Args>\n void call_from_thread(Callable&& callable, Args&&... args) {\n _socket->get_io_service().post(std::bind(\n std::forward<Callable>(callable), std::forward<Args>(args)...));\n }\n\n template <typename Duration>\n void wait_for(const Duration& duration) const {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(*_yield);\n }\n\n template <typename Iter>\n void send_message(Iter begin, Iter end) {\n _socket->async_write(\n boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);\n }\n\n void send_buffers(const std::array<boost::asio::const_buffer, 2>& buffers) {\n _socket->async_write(buffers, *_yield);\n }\n\n \/*\n * @brief default on_disconnect implementation; does nothing\n *\/\n void on_disconnect() {}\n\n \/*\n * @brief default on_error implementation; swallows everything\n *\/\n void on_error(std::exception_ptr eptr) {\n try {\n std::rethrow_exception(eptr);\n }\n catch (const std::exception& excep) {\n print_exception_what(excep);\n }\n }\n\n void lose_connection() { _socket->close(); }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n ChildProtocol& this_protocol() {\n return *static_cast<ChildProtocol*>(this);\n }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n const ChildProtocol& this_protocol() const {\n return *static_cast<ChildProtocol*>(this);\n }\n\nprivate:\n#ifdef NDEBUG\n void handle_network_error(boost::system::system_error&) {\n#else\n void handle_network_error(boost::system::system_error& connection_error) {\n print_connection_error(connection_error);\n#endif\n this_protocol().on_disconnect();\n }\n\n void handle_user_error(const std::exception_ptr& excep) {\n this_protocol().on_error(excep);\n }\n\n void print_connection_error(\n const boost::system::system_error& connection_error) const {\n std::cerr << \"Client disconnected with code \" << connection_error.what()\n << std::endl;\n }\n\n void print_exception_what(const std::exception& excep) {\n std::cerr << \"Killing connection, exception in client handler: \"\n << excep.what() << std::endl;\n }\n\n buffer_iterator buffer_begin() {\n return this_protocol().read_buffer().begin();\n }\n\n buffer_iterator buffer_begin() const {\n return this_protocol().read_buffer().begin();\n }\n\n buffer_iterator buffer_end() { return this_protocol().read_buffer().end(); }\n\n buffer_iterator buffer_end() const {\n return this_protocol().read_buffer().end();\n }\n\n boost::asio::mutable_buffers_1 asio_buffer() {\n return boost::asio::buffer(&*buffer_begin(),\n std::distance(buffer_begin(), buffer_end()));\n }\n\nprivate:\n boost::optional<boost::asio::yield_context> _yield;\n std::unique_ptr<socket_type> _socket;\n};\n\n} \/\/ namespace twisted\n\n#endif\n<commit_msg>added is_connected<commit_after>#ifndef TWISTEDCPP_PROTOCOL_CORE\n#define TWISTEDCPP_PROTOCOL_CORE\n\n#include \"detail\/sockets.hpp\"\n\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/asio\/steady_timer.hpp>\n#include <boost\/optional.hpp>\n#include <boost\/asio\/spawn.hpp>\n#include <boost\/asio\/write.hpp>\n#include <boost\/asio\/high_resolution_timer.hpp>\n#include <boost\/ref.hpp>\n\n#ifndef NDEBUG\n#include <iostream>\n#endif\n\nnamespace twisted {\n\ntemplate <typename ChildProtocol, typename BufferType>\nclass protocol_core : public std::enable_shared_from_this<ChildProtocol> {\npublic:\n typedef detail::socket_base socket_type;\n typedef boost::asio::steady_timer timer_type;\n typedef boost::asio::io_service::strand strand_type;\n typedef BufferType buffer_type;\n typedef typename buffer_type::iterator buffer_iterator;\n typedef typename buffer_type::const_iterator const_buffer_iterator;\n\n protocol_core() = default;\n protocol_core(protocol_core&&) = default;\n protocol_core& operator=(protocol_core&&) = default;\n\n void set_socket(std::unique_ptr<socket_type> socket) {\n _socket = std::move(socket);\n }\n\n void run_protocol() {\n auto self = this_protocol().shared_from_this();\n boost::asio::spawn(_socket->get_io_service(),\n [this, self](boost::asio::yield_context yield) {\n _yield = boost::in_place(yield);\n\n try {\n _socket->do_handshake(*_yield);\n\n while (_socket->is_open()) {\n auto bytes_read =\n _socket->async_read_some(asio_buffer(), yield);\n this_protocol().on_message(\n buffer_begin(), std::next(buffer_begin(), bytes_read));\n }\n }\n catch (boost::system::system_error& connection_error) {\n handle_network_error(connection_error);\n }\n catch (...) {\n handle_user_error(std::current_exception());\n }\n });\n }\n\n template <typename Duration, typename Callable>\n void call_later(Duration duration, Callable callable) {\n auto self = this_protocol().shared_from_this();\n \/\/ we pass our existing yield_context and not the io_service such that\n \/\/ both contexts run under the same strand\n boost::asio::spawn(*_yield, [this, duration, callable, self](\n boost::asio::yield_context yield) {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(yield);\n\n \/\/ we need to exchange the yield context so that that the user can\n \/\/ use the send_message function in the right context\n boost::optional<boost::asio::yield_context> old_yield(\n boost::in_place(*_yield));\n _yield = boost::in_place(yield);\n callable();\n _yield = boost::in_place(*old_yield);\n });\n }\n\n template <typename Callable, typename... Args>\n void call_from_thread(Callable&& callable, Args&&... args) {\n _socket->get_io_service().post(std::bind(\n std::forward<Callable>(callable), std::forward<Args>(args)...));\n }\n\n template <typename Duration>\n void wait_for(const Duration& duration) const {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(*_yield);\n }\n\n template <typename Iter>\n void send_message(Iter begin, Iter end) {\n _socket->async_write(\n boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);\n }\n\n void send_buffers(const std::array<boost::asio::const_buffer, 2>& buffers) {\n _socket->async_write(buffers, *_yield);\n }\n\n \/*\n * @brief default on_disconnect implementation; does nothing\n *\/\n void on_disconnect() {}\n\n \/*\n * @brief default on_error implementation; swallows everything\n *\/\n void on_error(std::exception_ptr eptr) {\n try {\n std::rethrow_exception(eptr);\n }\n catch (const std::exception& excep) {\n print_exception_what(excep);\n }\n }\n\n bool is_connected() const { return _socket->is_open(); }\n\n void lose_connection() { _socket->close(); }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n ChildProtocol& this_protocol() {\n return *static_cast<ChildProtocol*>(this);\n }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n const ChildProtocol& this_protocol() const {\n return *static_cast<ChildProtocol*>(this);\n }\n\nprivate:\n#ifdef NDEBUG\n void handle_network_error(boost::system::system_error&) {\n#else\n void handle_network_error(boost::system::system_error& connection_error) {\n print_connection_error(connection_error);\n#endif\n this_protocol().on_disconnect();\n }\n\n void handle_user_error(const std::exception_ptr& excep) {\n this_protocol().on_error(excep);\n }\n\n void print_connection_error(\n const boost::system::system_error& connection_error) const {\n std::cerr << \"Client disconnected with code \" << connection_error.what()\n << std::endl;\n }\n\n void print_exception_what(const std::exception& excep) {\n std::cerr << \"Killing connection, exception in client handler: \"\n << excep.what() << std::endl;\n }\n\n buffer_iterator buffer_begin() {\n return this_protocol().read_buffer().begin();\n }\n\n buffer_iterator buffer_begin() const {\n return this_protocol().read_buffer().begin();\n }\n\n buffer_iterator buffer_end() { return this_protocol().read_buffer().end(); }\n\n buffer_iterator buffer_end() const {\n return this_protocol().read_buffer().end();\n }\n\n boost::asio::mutable_buffers_1 asio_buffer() {\n return boost::asio::buffer(&*buffer_begin(),\n std::distance(buffer_begin(), buffer_end()));\n }\n\nprivate:\n boost::optional<boost::asio::yield_context> _yield;\n std::unique_ptr<socket_type> _socket;\n};\n\n} \/\/ namespace twisted\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n#ifndef INCLUDED_UNOTOOLS_UCBLOCKBYTES_HXX\n#define INCLUDED_UNOTOOLS_UCBLOCKBYTES_HXX\n\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#include <com\/sun\/star\/ucb\/XContent.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <unotools\/unotoolsdllapi.h>\n\n#include <osl\/thread.hxx>\n#include <osl\/conditn.hxx>\n#include <osl\/mutex.hxx>\n#include <rtl\/ustring.hxx>\n#include <tools\/stream.hxx>\n#include <tools\/link.hxx>\n#include <tools\/errcode.hxx>\n#include <tools\/datetime.hxx>\n\nnamespace com\n{\n namespace sun\n {\n namespace star\n {\n namespace task\n {\n class XInteractionHandler;\n }\n namespace io\n {\n class XStream;\n class XInputStream;\n class XOutputStream;\n class XSeekable;\n }\n namespace ucb\n {\n class XContent;\n }\n namespace beans\n {\n struct PropertyValue;\n }\n }\n }\n}\n\nnamespace utl\n{\nSV_DECL_REF( UcbLockBytes )\n\nclass UcbLockBytesHandler : public SvRefBase\n{\n bool m_bActive;\npublic:\n enum LoadHandlerItem\n {\n DATA_AVAILABLE,\n DONE,\n CANCEL\n };\n\n UcbLockBytesHandler()\n : m_bActive( true )\n {}\n\n virtual void Handle( LoadHandlerItem nWhich, UcbLockBytesRef xLockBytes ) = 0;\n void Activate( bool bActivate = true ) { m_bActive = bActivate; }\n bool IsActive() const { return m_bActive; }\n};\n\nSV_DECL_IMPL_REF( UcbLockBytesHandler )\n\nclass UNOTOOLS_DLLPUBLIC UcbLockBytes : public virtual SvLockBytes\n{\n osl::Condition m_aInitialized;\n osl::Condition m_aTerminated;\n osl::Mutex m_aMutex;\n\n OUString m_aContentType;\n OUString m_aRealURL;\n DateTime m_aExpireDate;\n\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > m_xInputStream;\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > m_xOutputStream;\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XSeekable > m_xSeekable;\n void* m_pCommandThread; \/\/ is alive only for compatibility reasons\n UcbLockBytesHandlerRef m_xHandler;\n\n sal_uInt32 m_nRead;\n sal_uInt32 m_nSize;\n ErrCode m_nError;\n\n bool m_bTerminated;\n bool m_bDontClose;\n bool m_bStreamValid;\n\n DECL_LINK( DataAvailHdl, void * );\n\n UcbLockBytes( UcbLockBytesHandler* pHandler=NULL );\nprotected:\n virtual ~UcbLockBytes (void);\n\npublic:\n \/\/ properties: Referer, PostMimeType\n static UcbLockBytesRef CreateLockBytes( const ::com::sun::star::uno::Reference < ::com::sun::star::ucb::XContent >& xContent,\n const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >& rProps,\n StreamMode eMode,\n const ::com::sun::star::uno::Reference < ::com::sun::star::task::XInteractionHandler >& xInter,\n UcbLockBytesHandler* pHandler=0 );\n\n static UcbLockBytesRef CreateInputLockBytes( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xContent );\n static UcbLockBytesRef CreateLockBytes( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xContent );\n\n \/\/ SvLockBytes\n virtual void SetSynchronMode (bool bSynchron) SAL_OVERRIDE;\n virtual ErrCode ReadAt(sal_uInt64 nPos, void *pBuffer, sal_uLong nCount, sal_uLong *pRead) const SAL_OVERRIDE;\n virtual ErrCode WriteAt(sal_uInt64, const void*, sal_uLong, sal_uLong *pWritten) SAL_OVERRIDE;\n virtual ErrCode Flush() const SAL_OVERRIDE;\n virtual ErrCode SetSize(sal_uInt64) SAL_OVERRIDE;\n virtual ErrCode Stat ( SvLockBytesStat *pStat, SvLockBytesStatFlag) const SAL_OVERRIDE;\n\n void SetError( ErrCode nError )\n { m_nError = nError; }\n\n ErrCode GetError() const\n { return m_nError; }\n\n \/\/ the following properties are available when and after the first DataAvailable callback has been executed\n OUString GetContentType() const;\n OUString GetRealURL() const;\n DateTime GetExpireDate() const;\n\n \/\/ calling this method delegates the responsibility to call closeinput to the caller!\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > getInputStream();\n\n bool setInputStream_Impl( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > &rxInputStream,\n bool bSetXSeekable = true );\n bool setStream_Impl( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream > &rxStream );\n void terminate_Impl (void);\n\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > getInputStream_Impl() const\n {\n osl::MutexGuard aGuard( (const_cast< UcbLockBytes* >(this))->m_aMutex );\n return m_xInputStream;\n }\n\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > getOutputStream_Impl() const\n {\n osl::MutexGuard aGuard( (const_cast< UcbLockBytes* >(this))->m_aMutex );\n return m_xOutputStream;\n }\n\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XSeekable > getSeekable_Impl() const\n {\n osl::MutexGuard aGuard( (const_cast< UcbLockBytes* >(this))->m_aMutex );\n return m_xSeekable;\n }\n\n bool hasInputStream_Impl() const\n {\n osl::MutexGuard aGuard( (const_cast< UcbLockBytes* >(this))->m_aMutex );\n return m_xInputStream.is();\n }\n\n void setDontClose_Impl()\n { m_bDontClose = true; }\n\n void SetContentType_Impl( const OUString& rType ) { m_aContentType = rType; }\n void SetRealURL_Impl( const OUString& rURL ) { m_aRealURL = rURL; }\n void SetExpireDate_Impl( const DateTime& rDateTime ) { m_aExpireDate = rDateTime; }\n void SetStreamValid_Impl();\n};\n\nSV_IMPL_REF( UcbLockBytes );\n\n}\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>coverity#708567 unused member variables<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n#ifndef INCLUDED_UNOTOOLS_UCBLOCKBYTES_HXX\n#define INCLUDED_UNOTOOLS_UCBLOCKBYTES_HXX\n\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#include <com\/sun\/star\/ucb\/XContent.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <unotools\/unotoolsdllapi.h>\n\n#include <osl\/thread.hxx>\n#include <osl\/conditn.hxx>\n#include <osl\/mutex.hxx>\n#include <rtl\/ustring.hxx>\n#include <tools\/stream.hxx>\n#include <tools\/link.hxx>\n#include <tools\/errcode.hxx>\n#include <tools\/datetime.hxx>\n\nnamespace com\n{\n namespace sun\n {\n namespace star\n {\n namespace task\n {\n class XInteractionHandler;\n }\n namespace io\n {\n class XStream;\n class XInputStream;\n class XOutputStream;\n class XSeekable;\n }\n namespace ucb\n {\n class XContent;\n }\n namespace beans\n {\n struct PropertyValue;\n }\n }\n }\n}\n\nnamespace utl\n{\nSV_DECL_REF( UcbLockBytes )\n\nclass UcbLockBytesHandler : public SvRefBase\n{\n bool m_bActive;\npublic:\n enum LoadHandlerItem\n {\n DATA_AVAILABLE,\n DONE,\n CANCEL\n };\n\n UcbLockBytesHandler()\n : m_bActive( true )\n {}\n\n virtual void Handle( LoadHandlerItem nWhich, UcbLockBytesRef xLockBytes ) = 0;\n void Activate( bool bActivate = true ) { m_bActive = bActivate; }\n bool IsActive() const { return m_bActive; }\n};\n\nSV_DECL_IMPL_REF( UcbLockBytesHandler )\n\nclass UNOTOOLS_DLLPUBLIC UcbLockBytes : public virtual SvLockBytes\n{\n osl::Condition m_aInitialized;\n osl::Condition m_aTerminated;\n osl::Mutex m_aMutex;\n\n OUString m_aContentType;\n OUString m_aRealURL;\n DateTime m_aExpireDate;\n\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > m_xInputStream;\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > m_xOutputStream;\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XSeekable > m_xSeekable;\n void* m_pCommandThread; \/\/ is alive only for compatibility reasons\n UcbLockBytesHandlerRef m_xHandler;\n\n ErrCode m_nError;\n\n bool m_bTerminated;\n bool m_bDontClose;\n bool m_bStreamValid;\n\n DECL_LINK( DataAvailHdl, void * );\n\n UcbLockBytes( UcbLockBytesHandler* pHandler=NULL );\nprotected:\n virtual ~UcbLockBytes (void);\n\npublic:\n \/\/ properties: Referer, PostMimeType\n static UcbLockBytesRef CreateLockBytes( const ::com::sun::star::uno::Reference < ::com::sun::star::ucb::XContent >& xContent,\n const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >& rProps,\n StreamMode eMode,\n const ::com::sun::star::uno::Reference < ::com::sun::star::task::XInteractionHandler >& xInter,\n UcbLockBytesHandler* pHandler=0 );\n\n static UcbLockBytesRef CreateInputLockBytes( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xContent );\n static UcbLockBytesRef CreateLockBytes( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xContent );\n\n \/\/ SvLockBytes\n virtual void SetSynchronMode (bool bSynchron) SAL_OVERRIDE;\n virtual ErrCode ReadAt(sal_uInt64 nPos, void *pBuffer, sal_uLong nCount, sal_uLong *pRead) const SAL_OVERRIDE;\n virtual ErrCode WriteAt(sal_uInt64, const void*, sal_uLong, sal_uLong *pWritten) SAL_OVERRIDE;\n virtual ErrCode Flush() const SAL_OVERRIDE;\n virtual ErrCode SetSize(sal_uInt64) SAL_OVERRIDE;\n virtual ErrCode Stat ( SvLockBytesStat *pStat, SvLockBytesStatFlag) const SAL_OVERRIDE;\n\n void SetError( ErrCode nError )\n { m_nError = nError; }\n\n ErrCode GetError() const\n { return m_nError; }\n\n \/\/ the following properties are available when and after the first DataAvailable callback has been executed\n OUString GetContentType() const;\n OUString GetRealURL() const;\n DateTime GetExpireDate() const;\n\n \/\/ calling this method delegates the responsibility to call closeinput to the caller!\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > getInputStream();\n\n bool setInputStream_Impl( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > &rxInputStream,\n bool bSetXSeekable = true );\n bool setStream_Impl( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream > &rxStream );\n void terminate_Impl (void);\n\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > getInputStream_Impl() const\n {\n osl::MutexGuard aGuard( (const_cast< UcbLockBytes* >(this))->m_aMutex );\n return m_xInputStream;\n }\n\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > getOutputStream_Impl() const\n {\n osl::MutexGuard aGuard( (const_cast< UcbLockBytes* >(this))->m_aMutex );\n return m_xOutputStream;\n }\n\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XSeekable > getSeekable_Impl() const\n {\n osl::MutexGuard aGuard( (const_cast< UcbLockBytes* >(this))->m_aMutex );\n return m_xSeekable;\n }\n\n bool hasInputStream_Impl() const\n {\n osl::MutexGuard aGuard( (const_cast< UcbLockBytes* >(this))->m_aMutex );\n return m_xInputStream.is();\n }\n\n void setDontClose_Impl()\n { m_bDontClose = true; }\n\n void SetContentType_Impl( const OUString& rType ) { m_aContentType = rType; }\n void SetRealURL_Impl( const OUString& rURL ) { m_aRealURL = rURL; }\n void SetExpireDate_Impl( const DateTime& rDateTime ) { m_aExpireDate = rDateTime; }\n void SetStreamValid_Impl();\n};\n\nSV_IMPL_REF( UcbLockBytes );\n\n}\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\/\n\/* *\/\n\/* Copyright 2013-2014 by Martin Bidlingmaier and Ullrich Koethe *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/hci.iwr.uni-heidelberg.de\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* ullrich.koethe@iwr.uni-heidelberg.de or *\/\n\/* vigra@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person *\/\n\/* obtaining a copy of this software and associated documentation *\/\n\/* files (the \"Software\"), to deal in the Software without *\/\n\/* restriction, including without limitation the rights to use, *\/\n\/* copy, modify, merge, publish, distribute, sublicense, and\/or *\/\n\/* sell copies of the Software, and to permit persons to whom the *\/\n\/* Software is furnished to do so, subject to the following *\/\n\/* conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the *\/\n\/* Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *\/\n\/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *\/\n\/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\/\n\/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *\/\n\/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\/\n\/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\/\n\/* OTHER DEALINGS IN THE SOFTWARE. *\/\n\/* *\/\n\/************************************************************************\/\n\n#ifndef VIGRA_PRINT_BACKTRACE_HXX\n#define VIGRA_PRINT_BACKTRACE_HXX\n\n\/* Quick-and-dirty way to print a backtrace upon a signal in Linux.\n\n Especially useful if you can't use a debugger (e.g. on TravisCI).\n \n Usage:\n \n Make sure to compile in debug mode.\n Have \"addr2line\" installed (was already present on TravisCI and our local machines).\n \n #include <vigra\/print_backtrace.hxx>\n \n int main(int argc, char** argv)\n {\n program_name = argv[0];\n signal(SIGFPE, &vigra_print_stack_trace); \/\/ catch the desired signal\n \n run_buggy_code();\n } \n*\/\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n\t\n\nstatic char * program_name;\n\nstatic int vigra_addr2line(void const * const addr)\n{\n char addr2line_cmd[512] = {0};\n sprintf(addr2line_cmd,\"addr2line -C -f -p -i -e %.256s %p\", program_name, addr);\n return system(addr2line_cmd);\n}\n\nstatic void vigra_print_stack_trace(int)\n{\n int i, trace_size = 0;\n char **messages = (char **)NULL;\n static const int BACKTRACE_SIZE = 100;\n void *stack_traces[BACKTRACE_SIZE];\n\n trace_size = backtrace(stack_traces, BACKTRACE_SIZE);\n messages = backtrace_symbols(stack_traces, trace_size);\n\n for (i = 0; i < trace_size; ++i)\n {\n if (vigra_addr2line(stack_traces[i]) != 0)\n {\n printf(\" error determining line # for: %sn\", messages[i]);\n }\n }\n if (messages) { free(messages); }\n exit(1);\n}\n \n#endif \/\/ VIGRA_PRINT_BACKTRACE_HXX\n<commit_msg>minor improvement of vigra_print_backtrace()<commit_after>\/************************************************************************\/\n\/* *\/\n\/* Copyright 2013-2014 by Martin Bidlingmaier and Ullrich Koethe *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/hci.iwr.uni-heidelberg.de\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* ullrich.koethe@iwr.uni-heidelberg.de or *\/\n\/* vigra@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person *\/\n\/* obtaining a copy of this software and associated documentation *\/\n\/* files (the \"Software\"), to deal in the Software without *\/\n\/* restriction, including without limitation the rights to use, *\/\n\/* copy, modify, merge, publish, distribute, sublicense, and\/or *\/\n\/* sell copies of the Software, and to permit persons to whom the *\/\n\/* Software is furnished to do so, subject to the following *\/\n\/* conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the *\/\n\/* Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *\/\n\/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *\/\n\/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\/\n\/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *\/\n\/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\/\n\/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\/\n\/* OTHER DEALINGS IN THE SOFTWARE. *\/\n\/* *\/\n\/************************************************************************\/\n\n#ifndef VIGRA_PRINT_BACKTRACE_HXX\n#define VIGRA_PRINT_BACKTRACE_HXX\n\n\/* Quick-and-dirty way to print a backtrace upon a signal in Linux.\n\n Especially useful if you can't use a debugger (e.g. on TravisCI).\n \n Usage:\n \n Make sure to compile in debug mode.\n Have \"addr2line\" installed (was already present on TravisCI and our local machines).\n \n #include <vigra\/print_backtrace.hxx>\n \n int main(int argc, char** argv)\n {\n program_name = argv[0];\n signal(SIGSEGV, &vigra_print_backtrace); \/\/ catch the desired signal\n \n run_buggy_code();\n } \n*\/\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n\t\n\nstatic char * program_name;\n\nstatic int vigra_addr2line(void const * const addr)\n{\n char addr2line_cmd[512] = {0};\n sprintf(addr2line_cmd,\"addr2line -C -f -p -i -e %.256s %p\", program_name, addr);\n return system(addr2line_cmd);\n}\n\nstatic void vigra_print_backtrace(int sig)\n{\n int i, trace_size = 0;\n char **messages = (char **)NULL;\n static const int BACKTRACE_SIZE = 100;\n void *stack_traces[BACKTRACE_SIZE];\n \n fprintf(stderr, \"caught signal %d, printing backtrace\\n\\n\", sig);\n\n trace_size = backtrace(stack_traces, BACKTRACE_SIZE);\n messages = backtrace_symbols(stack_traces, trace_size);\n\n for (i = 0; i < trace_size; ++i)\n {\n if (vigra_addr2line(stack_traces[i]) != 0)\n {\n fprintf(stderr, \" error determining line # for: %sn\", messages[i]);\n }\n }\n if (messages) { free(messages); }\n exit(1);\n}\n \n#endif \/\/ VIGRA_PRINT_BACKTRACE_HXX\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ bind_node_visitor.cpp\n\/\/\n\/\/ Identification: src\/binder\/binder_node_visitor.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"binder\/bind_node_visitor.h\"\n#include \"catalog\/catalog.h\"\n#include \"type\/type_id.h\"\n\n#include \"expression\/aggregate_expression.h\"\n#include \"expression\/case_expression.h\"\n#include \"expression\/function_expression.h\"\n#include \"expression\/operator_expression.h\"\n#include \"expression\/star_expression.h\"\n#include \"expression\/tuple_value_expression.h\"\n\nnamespace peloton {\nnamespace binder {\n\nBindNodeVisitor::BindNodeVisitor(concurrency::Transaction *txn,\n std::string default_database_name)\n : txn_(txn), default_database_name_(default_database_name) {\n context_ = nullptr;\n}\n\nvoid BindNodeVisitor::BindNameToNode(parser::SQLStatement *tree) {\n tree->Accept(this);\n}\n\nvoid BindNodeVisitor::Visit(parser::SelectStatement *node) {\n \/\/ Save the upper level context\n auto pre_context = context_;\n context_ = std::make_shared<BinderContext>();\n context_->upper_context = pre_context;\n if (node->from_table != nullptr) {\n node->from_table->Accept(this);\n }\n\n if (node->where_clause != nullptr) node->where_clause->Accept(this);\n if (node->order != nullptr) node->order->Accept(this);\n if (node->limit != nullptr) node->limit->Accept(this);\n if (node->group_by != nullptr) node->group_by->Accept(this);\n for (auto &select_element : node->select_list) {\n select_element->Accept(this);\n }\n\n \/\/ Restore the upper level context\n context_ = context_->upper_context;\n}\n\n\/\/ Some sub query nodes inside SelectStatement\nvoid BindNodeVisitor::Visit(parser::JoinDefinition *node) {\n \/\/ The columns in join condition can only bind to the join tables\n node->left->Accept(this);\n node->right->Accept(this);\n node->condition->Accept(this);\n}\n\nvoid BindNodeVisitor::Visit(parser::TableRef *node) {\n \/\/ Nested select. Not supported in the current executors\n if (node->select != nullptr) node->select->Accept(this);\n \/\/ Join\n else if (node->join != nullptr)\n node->join->Accept(this);\n \/\/ Multiple tables\n else if (!node->list.empty()) {\n for (auto &table : node->list) table->Accept(this);\n }\n \/\/ Single table\n else {\n context_->AddTable(node, default_database_name_, txn_);\n }\n}\n\nvoid BindNodeVisitor::Visit(parser::GroupByDescription *node) {\n for (auto &col : node->columns) {\n col->Accept(this);\n }\n if (node->having != nullptr) node->having->Accept(this);\n}\nvoid BindNodeVisitor::Visit(parser::OrderDescription *node) {\n for (auto &expr : node->exprs)\n if (expr != nullptr) expr->Accept(this);\n}\n\nvoid BindNodeVisitor::Visit(parser::UpdateStatement *node) {\n context_ = std::make_shared<BinderContext>();\n\n node->table->Accept(this);\n if (node->where != nullptr) node->where->Accept(this);\n for (auto &update : node->updates) {\n update->value->Accept(this);\n }\n\n \/\/ TODO: Update columns are not bound because they are char*\n \/\/ not TupleValueExpression in update_statement.h\n\n context_ = nullptr;\n}\n\nvoid BindNodeVisitor::Visit(parser::DeleteStatement *node) {\n context_ = std::make_shared<BinderContext>();\n node->TryBindDatabaseName(default_database_name_);\n context_->AddTable(node->GetDatabaseName(), node->GetTableName(), txn_);\n\n if (node->expr != nullptr) node->expr->Accept(this);\n\n context_ = nullptr;\n}\n\nvoid BindNodeVisitor::Visit(parser::LimitDescription *) {}\nvoid BindNodeVisitor::Visit(parser::CopyStatement *) {}\nvoid BindNodeVisitor::Visit(parser::CreateStatement *node) {\n node->TryBindDatabaseName(default_database_name_);\n}\nvoid BindNodeVisitor::Visit(parser::InsertStatement *node) {\n node->TryBindDatabaseName(default_database_name_);\n if (node->select != nullptr) node->select->Accept(this);\n context_ = nullptr;\n}\nvoid BindNodeVisitor::Visit(parser::DropStatement *) {}\nvoid BindNodeVisitor::Visit(parser::PrepareStatement *) {}\nvoid BindNodeVisitor::Visit(parser::ExecuteStatement *) {}\nvoid BindNodeVisitor::Visit(parser::TransactionStatement *) {}\nvoid BindNodeVisitor::Visit(parser::AnalyzeStatement *node) {\n node->TryBindDatabaseName(default_database_name_);\n}\n\n\/\/ void BindNodeVisitor::Visit(const parser::ConstantValueExpression *) {}\n\nvoid BindNodeVisitor::Visit(expression::TupleValueExpression *expr) {\n if (!expr->GetIsBound()) {\n std::tuple<oid_t, oid_t, oid_t> col_pos_tuple;\n std::tuple<oid_t, oid_t> table_id_tuple;\n\n std::string table_name = expr->GetTableName();\n std::string col_name = expr->GetColumnName();\n\n \/\/ Convert all the names to lower cases\n std::transform(table_name.begin(), table_name.end(), table_name.begin(),\n ::tolower);\n std::transform(col_name.begin(), col_name.end(), col_name.begin(),\n ::tolower);\n\n type::TypeId value_type;\n \/\/ Table name not specified in the expression\n if (table_name.empty()) {\n if (!BinderContext::GetColumnPosTuple(context_, col_name, col_pos_tuple,\n table_name, value_type, txn_))\n throw BinderException(\"Cannot find column \" + col_name);\n expr->SetTableName(table_name);\n }\n \/\/ Table name is present\n else {\n \/\/ Find the corresponding table in the context\n if (!BinderContext::GetTableIdTuple(context_, table_name,\n &table_id_tuple))\n throw BinderException(\"Invalid table reference \" +\n expr->GetTableName());\n \/\/ Find the column offset in that table\n if (!BinderContext::GetColumnPosTuple(col_name, table_id_tuple,\n col_pos_tuple, value_type, txn_))\n throw BinderException(\"Cannot find column \" + col_name);\n }\n expr->SetValueType(value_type);\n expr->SetBoundOid(col_pos_tuple);\n }\n}\n\nvoid BindNodeVisitor::Visit(expression::CaseExpression *expr) {\n for (size_t i = 0; i < expr->GetWhenClauseSize(); ++i) {\n expr->GetWhenClauseCond(i)->Accept(this);\n }\n}\n\nvoid BindNodeVisitor::Visit(expression::StarExpression *expr) {\n if (!BinderContext::HasTables(context_))\n throw BinderException(\"Invalid expression\" + expr->GetInfo());\n}\n\n\/\/ Deduce value type for these expressions\nvoid BindNodeVisitor::Visit(expression::OperatorExpression *expr) {\n SqlNodeVisitor::Visit(expr);\n expr->DeduceExpressionType();\n}\nvoid BindNodeVisitor::Visit(expression::AggregateExpression *expr) {\n SqlNodeVisitor::Visit(expr);\n expr->DeduceExpressionType();\n}\n\nvoid BindNodeVisitor::Visit(expression::FunctionExpression *expr) {\n \/\/ Visit the subtree first\n SqlNodeVisitor::Visit(expr);\n\n \/\/ Specialize the first argument (DatePartType) for date functions, otherwise\n \/\/ we have to do the string comparison to find out the corresponding\n \/\/ DatePartType when scanning every tuple.\n auto func_name = expr->GetFuncName();\n if (func_name == \"date_trunc\" or expr->GetFuncName() == \"extract\") {\n \/\/ Check the type of the first argument. Should be VARCHAR\n auto date_part = expr->GetChild(0);\n if (date_part->GetValueType() != type::TypeId::VARCHAR) {\n throw Exception(EXCEPTION_TYPE_EXPRESSION,\n \"Incorrect argument type to function: \" + func_name +\n \". Argument 0 expected type VARCHAR but found \" +\n TypeIdToString(date_part->GetValueType()) + \".\");\n }\n\n \/\/ Convert the first argument to DatePartType\n auto date_part_type = StringToDatePartType(\n date_part->Evaluate(nullptr, nullptr, nullptr).ToString());\n auto date_part_integer = type::ValueFactory::GetIntegerValue(\n static_cast<int32_t>(date_part_type));\n\n \/\/ Replace the first argument with an Integer expression of the DatePartType\n expr->SetChild(0,\n new expression::ConstantValueExpression(date_part_integer));\n }\n\n \/\/ Check catalog and bind function\n std::vector<type::TypeId> argtypes;\n for (size_t i = 0; i < expr->GetChildrenSize(); i++)\n argtypes.push_back(expr->GetChild(i)->GetValueType());\n \/\/ Check and set the function ptr\n auto catalog = catalog::Catalog::GetInstance();\n const catalog::FunctionData &func_data =\n catalog->GetFunction(expr->GetFuncName(), argtypes);\n LOG_DEBUG(\"Function %s found in the catalog\", func_data.func_name_.c_str());\n LOG_DEBUG(\"Argument num: %ld\", func_data.argument_types_.size());\n expr->SetFunctionExpressionParameters(func_data.func_, func_data.return_type_,\n func_data.argument_types_);\n}\n\n} \/\/ namespace binder\n} \/\/ namespace peloton\n<commit_msg>Small fix for code consistency.<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ bind_node_visitor.cpp\n\/\/\n\/\/ Identification: src\/binder\/binder_node_visitor.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"binder\/bind_node_visitor.h\"\n#include \"catalog\/catalog.h\"\n#include \"type\/type_id.h\"\n\n#include \"expression\/aggregate_expression.h\"\n#include \"expression\/case_expression.h\"\n#include \"expression\/function_expression.h\"\n#include \"expression\/operator_expression.h\"\n#include \"expression\/star_expression.h\"\n#include \"expression\/tuple_value_expression.h\"\n\nnamespace peloton {\nnamespace binder {\n\nBindNodeVisitor::BindNodeVisitor(concurrency::Transaction *txn,\n std::string default_database_name)\n : txn_(txn), default_database_name_(default_database_name) {\n context_ = nullptr;\n}\n\nvoid BindNodeVisitor::BindNameToNode(parser::SQLStatement *tree) {\n tree->Accept(this);\n}\n\nvoid BindNodeVisitor::Visit(parser::SelectStatement *node) {\n \/\/ Save the upper level context\n auto pre_context = context_;\n context_ = std::make_shared<BinderContext>();\n context_->upper_context = pre_context;\n if (node->from_table != nullptr) {\n node->from_table->Accept(this);\n }\n\n if (node->where_clause != nullptr) node->where_clause->Accept(this);\n if (node->order != nullptr) node->order->Accept(this);\n if (node->limit != nullptr) node->limit->Accept(this);\n if (node->group_by != nullptr) node->group_by->Accept(this);\n for (auto &select_element : node->select_list) {\n select_element->Accept(this);\n }\n\n \/\/ Restore the upper level context\n context_ = context_->upper_context;\n}\n\n\/\/ Some sub query nodes inside SelectStatement\nvoid BindNodeVisitor::Visit(parser::JoinDefinition *node) {\n \/\/ The columns in join condition can only bind to the join tables\n node->left->Accept(this);\n node->right->Accept(this);\n node->condition->Accept(this);\n}\n\nvoid BindNodeVisitor::Visit(parser::TableRef *node) {\n \/\/ Nested select. Not supported in the current executors\n if (node->select != nullptr) node->select->Accept(this);\n \/\/ Join\n else if (node->join != nullptr)\n node->join->Accept(this);\n \/\/ Multiple tables\n else if (!node->list.empty()) {\n for (auto &table : node->list) table->Accept(this);\n }\n \/\/ Single table\n else {\n context_->AddTable(node, default_database_name_, txn_);\n }\n}\n\nvoid BindNodeVisitor::Visit(parser::GroupByDescription *node) {\n for (auto &col : node->columns) {\n col->Accept(this);\n }\n if (node->having != nullptr) node->having->Accept(this);\n}\nvoid BindNodeVisitor::Visit(parser::OrderDescription *node) {\n for (auto &expr : node->exprs)\n if (expr != nullptr) expr->Accept(this);\n}\n\nvoid BindNodeVisitor::Visit(parser::UpdateStatement *node) {\n context_ = std::make_shared<BinderContext>();\n\n node->table->Accept(this);\n if (node->where != nullptr) node->where->Accept(this);\n for (auto &update : node->updates) {\n update->value->Accept(this);\n }\n\n \/\/ TODO: Update columns are not bound because they are char*\n \/\/ not TupleValueExpression in update_statement.h\n\n context_ = nullptr;\n}\n\nvoid BindNodeVisitor::Visit(parser::DeleteStatement *node) {\n context_ = std::make_shared<BinderContext>();\n node->TryBindDatabaseName(default_database_name_);\n context_->AddTable(node->GetDatabaseName(), node->GetTableName(), txn_);\n\n if (node->expr != nullptr) node->expr->Accept(this);\n\n context_ = nullptr;\n}\n\nvoid BindNodeVisitor::Visit(parser::LimitDescription *) {}\nvoid BindNodeVisitor::Visit(parser::CopyStatement *) {}\nvoid BindNodeVisitor::Visit(parser::CreateStatement *node) {\n node->TryBindDatabaseName(default_database_name_);\n}\nvoid BindNodeVisitor::Visit(parser::InsertStatement *node) {\n node->TryBindDatabaseName(default_database_name_);\n if (node->select != nullptr) node->select->Accept(this);\n context_ = nullptr;\n}\nvoid BindNodeVisitor::Visit(parser::DropStatement *) {}\nvoid BindNodeVisitor::Visit(parser::PrepareStatement *) {}\nvoid BindNodeVisitor::Visit(parser::ExecuteStatement *) {}\nvoid BindNodeVisitor::Visit(parser::TransactionStatement *) {}\nvoid BindNodeVisitor::Visit(parser::AnalyzeStatement *node) {\n node->TryBindDatabaseName(default_database_name_);\n}\n\n\/\/ void BindNodeVisitor::Visit(const parser::ConstantValueExpression *) {}\n\nvoid BindNodeVisitor::Visit(expression::TupleValueExpression *expr) {\n if (!expr->GetIsBound()) {\n std::tuple<oid_t, oid_t, oid_t> col_pos_tuple;\n std::tuple<oid_t, oid_t> table_id_tuple;\n\n std::string table_name = expr->GetTableName();\n std::string col_name = expr->GetColumnName();\n\n \/\/ Convert all the names to lower cases\n std::transform(table_name.begin(), table_name.end(), table_name.begin(),\n ::tolower);\n std::transform(col_name.begin(), col_name.end(), col_name.begin(),\n ::tolower);\n\n type::TypeId value_type;\n \/\/ Table name not specified in the expression\n if (table_name.empty()) {\n if (!BinderContext::GetColumnPosTuple(context_, col_name, col_pos_tuple,\n table_name, value_type, txn_))\n throw BinderException(\"Cannot find column \" + col_name);\n expr->SetTableName(table_name);\n }\n \/\/ Table name is present\n else {\n \/\/ Find the corresponding table in the context\n if (!BinderContext::GetTableIdTuple(context_, table_name,\n &table_id_tuple))\n throw BinderException(\"Invalid table reference \" +\n expr->GetTableName());\n \/\/ Find the column offset in that table\n if (!BinderContext::GetColumnPosTuple(col_name, table_id_tuple,\n col_pos_tuple, value_type, txn_))\n throw BinderException(\"Cannot find column \" + col_name);\n }\n expr->SetValueType(value_type);\n expr->SetBoundOid(col_pos_tuple);\n }\n}\n\nvoid BindNodeVisitor::Visit(expression::CaseExpression *expr) {\n for (size_t i = 0; i < expr->GetWhenClauseSize(); ++i) {\n expr->GetWhenClauseCond(i)->Accept(this);\n }\n}\n\nvoid BindNodeVisitor::Visit(expression::StarExpression *expr) {\n if (!BinderContext::HasTables(context_))\n throw BinderException(\"Invalid expression\" + expr->GetInfo());\n}\n\n\/\/ Deduce value type for these expressions\nvoid BindNodeVisitor::Visit(expression::OperatorExpression *expr) {\n SqlNodeVisitor::Visit(expr);\n expr->DeduceExpressionType();\n}\nvoid BindNodeVisitor::Visit(expression::AggregateExpression *expr) {\n SqlNodeVisitor::Visit(expr);\n expr->DeduceExpressionType();\n}\n\nvoid BindNodeVisitor::Visit(expression::FunctionExpression *expr) {\n \/\/ Visit the subtree first\n SqlNodeVisitor::Visit(expr);\n\n \/\/ Specialize the first argument (DatePartType) for date functions, otherwise\n \/\/ we have to do the string comparison to find out the corresponding\n \/\/ DatePartType when scanning every tuple.\n auto func_name = expr->GetFuncName();\n if (func_name == \"date_trunc\" or func_name == \"extract\") {\n \/\/ Check the type of the first argument. Should be VARCHAR\n auto date_part = expr->GetChild(0);\n if (date_part->GetValueType() != type::TypeId::VARCHAR) {\n throw Exception(EXCEPTION_TYPE_EXPRESSION,\n \"Incorrect argument type to function: \" + func_name +\n \". Argument 0 expected type VARCHAR but found \" +\n TypeIdToString(date_part->GetValueType()) + \".\");\n }\n\n \/\/ Convert the first argument to DatePartType\n auto date_part_type = StringToDatePartType(\n date_part->Evaluate(nullptr, nullptr, nullptr).ToString());\n auto date_part_integer = type::ValueFactory::GetIntegerValue(\n static_cast<int32_t>(date_part_type));\n\n \/\/ Replace the first argument with an Integer expression of the DatePartType\n expr->SetChild(0,\n new expression::ConstantValueExpression(date_part_integer));\n }\n\n \/\/ Check catalog and bind function\n std::vector<type::TypeId> argtypes;\n for (size_t i = 0; i < expr->GetChildrenSize(); i++)\n argtypes.push_back(expr->GetChild(i)->GetValueType());\n \/\/ Check and set the function ptr\n auto catalog = catalog::Catalog::GetInstance();\n const catalog::FunctionData &func_data =\n catalog->GetFunction(expr->GetFuncName(), argtypes);\n LOG_DEBUG(\"Function %s found in the catalog\", func_data.func_name_.c_str());\n LOG_DEBUG(\"Argument num: %ld\", func_data.argument_types_.size());\n expr->SetFunctionExpressionParameters(func_data.func_, func_data.return_type_,\n func_data.argument_types_);\n}\n\n} \/\/ namespace binder\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <array>\n#include <iostream>\n#include <cstdint>\n#include <initializer_list>\n#include <iterator>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <vector>\n\n#include <boost\/mpl\/set.hpp>\n#include <boost\/optional.hpp>\n\n#include \"blackhole\/attribute\/set.hpp\"\n#include \"blackhole\/config.hpp\"\n#include \"blackhole\/detail\/array.hpp\"\n#include \"blackhole\/detail\/iterator\/join.hpp\"\n#include \"blackhole\/detail\/traits\/tuple.hpp\"\n#include \"blackhole\/detail\/traits\/unique.hpp\"\n\nnamespace blackhole {\n\nnamespace attribute {\n\ntemplate<class T>\nstruct extractor;\n\ntemplate<class... Args>\nstruct tuple_empty;\n\nnamespace compare_by {\n\nstruct name_t {\n const std::string name;\n\n bool operator()(const set_t::value_type& v) const {\n return v.first == name;\n }\n};\n\n} \/\/ namespace\n\nclass set_view_t {\n template<class T> friend struct extractor;\n template<class... Args> friend struct tuple_empty;\n\npublic:\n typedef aux::iterator::join_t<set_t, true> const_iterator;\n\n struct internal_set_t { set_t v; };\n struct external_set_t { set_t v; };\n\nprivate:\n internal_set_t internal; \/\/ Severity, message, timestamp. Maybe pid, tid.\n external_set_t external; \/\/ All other.\n\npublic:\n set_view_t() = default;\n\n set_view_t(set_t external, set_t&& internal) :\n internal({ std::move(internal) }),\n external({ std::move(external) })\n {}\n\n bool\n empty() const BLACKHOLE_NOEXCEPT {\n return internal.v.empty() && external.v.empty();\n }\n\n \/\/! Message is the only(?) late attribute allowed to set internally.\n void message(const std::string& message) {\n internal.v.emplace_back(\"message\", message);\n }\n\n void message(std::string&& message) {\n internal.v.emplace_back(\"message\", std::move(message));\n }\n\n \/\/! Intentionally allow to insert only into external attribute set.\n void insert(pair_t pair) {\n external.v.emplace_back(std::move(pair));\n }\n\n \/\/! Intentionally allow to insert only into external attribute set.\n template<typename InputIterator>\n void insert(InputIterator first, InputIterator last) {\n std::copy(first, last, std::back_inserter(external.v));\n }\n\n const_iterator begin() const BLACKHOLE_NOEXCEPT {\n return const_iterator(aux::make_array(&internal.v, &external.v));\n }\n\n const_iterator end() const BLACKHOLE_NOEXCEPT {\n return const_iterator::invalid(aux::make_array(&internal.v, &external.v));\n }\n\n boost::optional<const attribute_t&>\n find(const std::string& name) const BLACKHOLE_NOEXCEPT {\n const compare_by::name_t action { name };\n\n auto it = std::find_if(internal.v.begin(), internal.v.end(), action);\n if (it != internal.v.end()) {\n return it->second;\n }\n\n it = std::find_if(external.v.begin(), external.v.end(), action);\n if (it != external.v.end()) {\n return it->second;\n }\n\n return boost::none;\n }\n\n const attribute_t& at(const std::string& name) const {\n auto value = find(name);\n if (!value) {\n throw std::out_of_range(name);\n }\n\n return *value;\n }\n};\n\ntemplate<>\nstruct tuple_empty<> {\n static inline bool empty(const set_view_t&) {\n return true;\n }\n};\n\ntemplate<>\nstruct tuple_empty<set_view_t::internal_set_t> {\n static inline bool empty(const set_view_t& view) {\n return view.internal.v.empty();\n }\n};\n\ntemplate<>\nstruct tuple_empty<set_view_t::external_set_t> {\n static inline bool empty(const set_view_t& view) {\n return view.external.v.empty();\n }\n};\n\ntemplate<class T, class... Args>\nstruct tuple_empty<T, Args...> {\n static inline bool empty(const set_view_t& view) {\n return tuple_empty<T>::empty(view) &&\n tuple_empty<Args...>::empty(view);\n }\n};\n\ntemplate<>\nstruct extractor<set_view_t::internal_set_t> {\n static\n inline\n const set_t*\n extract(const set_view_t& view) {\n return &view.internal.v;\n }\n};\n\ntemplate<>\nstruct extractor<set_view_t::external_set_t> {\n static\n inline\n const set_t*\n extract(const set_view_t& view) {\n return &view.external.v;\n }\n};\n\ntemplate<class... T>\nclass partial_view_t {\n static_assert(unique<T...>::value, \"all attribute set types must be unique\");\n\n typedef std::array<const set_t*, sizeof...(T)> array_type;\n\npublic:\n typedef set_view_t::const_iterator const_iterator;\n\nprivate:\n const set_view_t& view;\n\npublic:\n partial_view_t(const set_view_t& view) :\n view(view)\n {}\n\n bool\n empty() const BLACKHOLE_NOEXCEPT {\n return tuple_empty<T...>::empty(view);\n }\n\n const_iterator\n begin() const BLACKHOLE_NOEXCEPT {\n return const_iterator(\n array_type {{ extractor<T>::extract(view)... }}\n );\n }\n\n const_iterator\n end() const BLACKHOLE_NOEXCEPT {\n return const_iterator::invalid(\n array_type {{ extractor<T>::extract(view)... }}\n );\n }\n};\n\n} \/\/ namespace attribute\n\n} \/\/ namespace blackhole\n<commit_msg>[Detail] Avoid unnecessary copying.<commit_after>#pragma once\n\n#include <array>\n#include <iostream>\n#include <cstdint>\n#include <initializer_list>\n#include <iterator>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <vector>\n\n#include <boost\/mpl\/set.hpp>\n#include <boost\/optional.hpp>\n\n#include \"blackhole\/attribute\/set.hpp\"\n#include \"blackhole\/config.hpp\"\n#include \"blackhole\/detail\/array.hpp\"\n#include \"blackhole\/detail\/iterator\/join.hpp\"\n#include \"blackhole\/detail\/traits\/tuple.hpp\"\n#include \"blackhole\/detail\/traits\/unique.hpp\"\n\nnamespace blackhole {\n\nnamespace attribute {\n\ntemplate<class T>\nstruct extractor;\n\ntemplate<class... Args>\nstruct tuple_empty;\n\nnamespace compare_by {\n\nstruct name_t {\n const std::string& name;\n\n bool operator()(const set_t::value_type& v) const {\n return v.first == name;\n }\n};\n\n} \/\/ namespace\n\nclass set_view_t {\n template<class T> friend struct extractor;\n template<class... Args> friend struct tuple_empty;\n\npublic:\n typedef aux::iterator::join_t<set_t, true> const_iterator;\n\n struct internal_set_t { set_t v; };\n struct external_set_t { set_t v; };\n\nprivate:\n internal_set_t internal; \/\/ Severity, message, timestamp. Maybe pid, tid.\n external_set_t external; \/\/ All other.\n\npublic:\n set_view_t() = default;\n\n set_view_t(set_t external, set_t&& internal) :\n internal({ std::move(internal) }),\n external({ std::move(external) })\n {}\n\n bool\n empty() const BLACKHOLE_NOEXCEPT {\n return internal.v.empty() && external.v.empty();\n }\n\n \/\/! Message is the only(?) late attribute allowed to set internally.\n void message(const std::string& message) {\n internal.v.emplace_back(\"message\", message);\n }\n\n void message(std::string&& message) {\n internal.v.emplace_back(\"message\", std::move(message));\n }\n\n \/\/! Intentionally allow to insert only into external attribute set.\n void insert(pair_t pair) {\n external.v.emplace_back(std::move(pair));\n }\n\n \/\/! Intentionally allow to insert only into external attribute set.\n template<typename InputIterator>\n void insert(InputIterator first, InputIterator last) {\n std::copy(first, last, std::back_inserter(external.v));\n }\n\n const_iterator begin() const BLACKHOLE_NOEXCEPT {\n return const_iterator(aux::make_array(&internal.v, &external.v));\n }\n\n const_iterator end() const BLACKHOLE_NOEXCEPT {\n return const_iterator::invalid(aux::make_array(&internal.v, &external.v));\n }\n\n boost::optional<const attribute_t&>\n find(const std::string& name) const BLACKHOLE_NOEXCEPT {\n const compare_by::name_t action { name };\n\n auto it = std::find_if(internal.v.begin(), internal.v.end(), action);\n if (it != internal.v.end()) {\n return it->second;\n }\n\n it = std::find_if(external.v.begin(), external.v.end(), action);\n if (it != external.v.end()) {\n return it->second;\n }\n\n return boost::none;\n }\n\n const attribute_t& at(const std::string& name) const {\n auto value = find(name);\n if (!value) {\n throw std::out_of_range(name);\n }\n\n return *value;\n }\n};\n\ntemplate<>\nstruct tuple_empty<> {\n static inline bool empty(const set_view_t&) {\n return true;\n }\n};\n\ntemplate<>\nstruct tuple_empty<set_view_t::internal_set_t> {\n static inline bool empty(const set_view_t& view) {\n return view.internal.v.empty();\n }\n};\n\ntemplate<>\nstruct tuple_empty<set_view_t::external_set_t> {\n static inline bool empty(const set_view_t& view) {\n return view.external.v.empty();\n }\n};\n\ntemplate<class T, class... Args>\nstruct tuple_empty<T, Args...> {\n static inline bool empty(const set_view_t& view) {\n return tuple_empty<T>::empty(view) &&\n tuple_empty<Args...>::empty(view);\n }\n};\n\ntemplate<>\nstruct extractor<set_view_t::internal_set_t> {\n static\n inline\n const set_t*\n extract(const set_view_t& view) {\n return &view.internal.v;\n }\n};\n\ntemplate<>\nstruct extractor<set_view_t::external_set_t> {\n static\n inline\n const set_t*\n extract(const set_view_t& view) {\n return &view.external.v;\n }\n};\n\ntemplate<class... T>\nclass partial_view_t {\n static_assert(unique<T...>::value, \"all attribute set types must be unique\");\n\n typedef std::array<const set_t*, sizeof...(T)> array_type;\n\npublic:\n typedef set_view_t::const_iterator const_iterator;\n\nprivate:\n const set_view_t& view;\n\npublic:\n partial_view_t(const set_view_t& view) :\n view(view)\n {}\n\n bool\n empty() const BLACKHOLE_NOEXCEPT {\n return tuple_empty<T...>::empty(view);\n }\n\n const_iterator\n begin() const BLACKHOLE_NOEXCEPT {\n return const_iterator(\n array_type {{ extractor<T>::extract(view)... }}\n );\n }\n\n const_iterator\n end() const BLACKHOLE_NOEXCEPT {\n return const_iterator::invalid(\n array_type {{ extractor<T>::extract(view)... }}\n );\n }\n};\n\n} \/\/ namespace attribute\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"bin\/dartdev_isolate.h\"\n\n#if !defined(DART_PRECOMPILED_RUNTIME)\n\n#include <functional>\n#include <memory>\n\n#include \"bin\/directory.h\"\n#include \"bin\/error_exit.h\"\n#include \"bin\/exe_utils.h\"\n#include \"bin\/file.h\"\n#include \"bin\/lockers.h\"\n#include \"bin\/platform.h\"\n#include \"bin\/process.h\"\n#include \"include\/dart_embedder_api.h\"\n#include \"platform\/utils.h\"\n\n#define CHECK_RESULT(result) \\\n if (Dart_IsError(result)) { \\\n ProcessError(Dart_GetError(result), kErrorExitCode); \\\n if (send_port_id != ILLEGAL_PORT) { \\\n Dart_CloseNativePort(send_port_id); \\\n } \\\n Dart_ExitScope(); \\\n Dart_ExitIsolate(); \\\n return; \\\n }\n\nnamespace dart {\nnamespace bin {\n\nDartDevIsolate::DartDevRunner DartDevIsolate::runner_ =\n DartDevIsolate::DartDevRunner();\nbool DartDevIsolate::should_run_dart_dev_ = false;\nMonitor* DartDevIsolate::DartDevRunner::monitor_ = new Monitor();\nDartDevIsolate::DartDev_Result DartDevIsolate::DartDevRunner::result_ =\n DartDevIsolate::DartDev_Result_Unknown;\nchar** DartDevIsolate::DartDevRunner::script_ = nullptr;\nstd::unique_ptr<char*[], void (*)(char*[])>\n DartDevIsolate::DartDevRunner::argv_ =\n std::unique_ptr<char*[], void (*)(char**)>(nullptr, [](char**) {});\nintptr_t DartDevIsolate::DartDevRunner::argc_ = 0;\n\nbool DartDevIsolate::ShouldParseCommand(const char* script_uri) {\n \/\/ If script_uri is not a file path or of a known URI scheme, we can assume\n \/\/ that this is a DartDev command.\n return (!File::ExistsUri(nullptr, script_uri) &&\n (strncmp(script_uri, \"http:\/\/\", 7) != 0) &&\n (strncmp(script_uri, \"https:\/\/\", 8) != 0) &&\n (strncmp(script_uri, \"file:\/\/\", 7) != 0) &&\n (strncmp(script_uri, \"package:\", 8) != 0) &&\n (strncmp(script_uri, \"google3:\/\/\", 10) != 0));\n}\n\nconst char* DartDevIsolate::TryResolveDartDevSnapshotPath() {\n \/\/ |dir_prefix| includes the last path seperator.\n auto dir_prefix = EXEUtils::GetDirectoryPrefixFromExeName();\n\n \/\/ First assume we're in dart-sdk\/bin.\n char* snapshot_path =\n Utils::SCreate(\"%ssnapshots\/dartdev.dart.snapshot\", dir_prefix.get());\n if (File::Exists(nullptr, snapshot_path)) {\n return snapshot_path;\n }\n free(snapshot_path);\n\n \/\/ If we're not in dart-sdk\/bin, we might be in one of the $SDK\/out\/*\n \/\/ directories. Try to use a snapshot rom a previously built SDK.\n snapshot_path = Utils::SCreate(\"%sdartdev.dart.snapshot\", dir_prefix.get());\n if (File::Exists(nullptr, snapshot_path)) {\n return snapshot_path;\n }\n free(snapshot_path);\n\n Syslog::PrintErr(\"Could not find DartDev snapshot.\\n\");\n return nullptr;\n}\n\nvoid DartDevIsolate::DartDevRunner::Run(\n Dart_IsolateGroupCreateCallback create_isolate,\n const char* packages_file,\n char** script,\n CommandLineOptions* dart_options) {\n create_isolate_ = create_isolate;\n dart_options_ = dart_options;\n packages_file_ = packages_file;\n script_ = script;\n\n MonitorLocker locker(monitor_);\n int result = Thread::Start(\"DartDev Runner\", RunCallback,\n reinterpret_cast<uword>(this));\n if (result != 0) {\n FATAL1(\"Failed to start DartDev thread: %d\", result);\n }\n monitor_->WaitMicros(Monitor::kNoTimeout);\n\n if (result_ == DartDevIsolate::DartDev_Result_Run) {\n \/\/ Clear the DartDev dart_options and replace them with the processed\n \/\/ options provided by DartDev.\n dart_options_->Reset();\n for (intptr_t i = 0; i < argc_; ++i) {\n dart_options_->AddArguments(const_cast<const char**>(argv_.get()), argc_);\n }\n }\n}\n\nstatic Dart_CObject* GetArrayItem(Dart_CObject* message, intptr_t index) {\n return message->value.as_array.values[index];\n}\n\nvoid DartDevIsolate::DartDevRunner::DartDevResultCallback(\n Dart_Port dest_port_id,\n Dart_CObject* message) {\n ASSERT(message->type == Dart_CObject_kArray);\n int32_t type = GetArrayItem(message, 0)->value.as_int32;\n switch (type) {\n case DartDevIsolate::DartDev_Result_Run: {\n result_ = DartDevIsolate::DartDev_Result_Run;\n ASSERT(GetArrayItem(message, 1)->type == Dart_CObject_kString);\n if (*script_ != nullptr) {\n free(*script_);\n }\n *script_ = Utils::StrDup(GetArrayItem(message, 1)->value.as_string);\n ASSERT(GetArrayItem(message, 2)->type == Dart_CObject_kArray);\n Dart_CObject* args = GetArrayItem(message, 2);\n argc_ = args->value.as_array.length;\n Dart_CObject** dart_args = args->value.as_array.values;\n\n auto deleter = [](char** args) {\n for (intptr_t i = 0; i < argc_; ++i) {\n free(args[i]);\n }\n delete[] args;\n };\n\n argv_ =\n std::unique_ptr<char*[], void (*)(char**)>(new char*[argc_], deleter);\n for (intptr_t i = 0; i < argc_; ++i) {\n argv_[i] = Utils::StrDup(dart_args[i]->value.as_string);\n }\n break;\n }\n case DartDevIsolate::DartDev_Result_Exit: {\n ASSERT(GetArrayItem(message, 1)->type == Dart_CObject_kInt32);\n int32_t dartdev_exit_code = GetArrayItem(message, 1)->value.as_int32;\n\n \/\/ If we're given a non-zero exit code, DartDev is signaling for us to\n \/\/ shutdown.\n if (dartdev_exit_code != 0) {\n Process::SetGlobalExitCode(dartdev_exit_code);\n }\n\n \/\/ If DartDev hasn't signaled for us to do anything else, we can assume\n \/\/ there's nothing else for the VM to run and that we can exit.\n if (result_ == DartDevIsolate::DartDev_Result_Unknown) {\n result_ = DartDevIsolate::DartDev_Result_Exit;\n }\n\n \/\/ DartDev is done processing the command. Unblock the main thread and\n \/\/ continue the launch procedure.\n DartDevRunner::monitor_->Notify();\n break;\n }\n default:\n UNREACHABLE();\n }\n}\n\nvoid DartDevIsolate::DartDevRunner::RunCallback(uword args) {\n MonitorLocker locker_(DartDevRunner::monitor_);\n DartDevRunner* runner = reinterpret_cast<DartDevRunner*>(args);\n const char* dartdev_path = DartDevIsolate::TryResolveDartDevSnapshotPath();\n if (dartdev_path == nullptr) {\n ProcessError(\"Failed to find DartDev snapshot.\", kErrorExitCode);\n return;\n }\n Dart_IsolateFlags flags;\n Dart_IsolateFlagsInitialize(&flags);\n char* error;\n Dart_Isolate dartdev_isolate = runner->create_isolate_(\n dartdev_path, \"dartdev\", nullptr, runner->packages_file_, &flags,\n NULL \/* callback_data *\/, const_cast<char**>(&error));\n free(const_cast<char*>(dartdev_path));\n\n if (dartdev_isolate == nullptr) {\n ProcessError(error, kErrorExitCode);\n return;\n }\n\n Dart_EnterIsolate(dartdev_isolate);\n Dart_EnterScope();\n\n \/\/ Retrieve the DartDev entrypoint.\n Dart_Port send_port_id = ILLEGAL_PORT;\n Dart_Handle root_lib = Dart_RootLibrary();\n Dart_Handle main_closure =\n Dart_GetField(root_lib, Dart_NewStringFromCString(\"main\"));\n CHECK_RESULT(main_closure);\n\n if (!Dart_IsClosure(main_closure)) {\n ProcessError(\"Unable to find 'main' in root library 'dartdev'\",\n kErrorExitCode);\n Dart_ExitScope();\n Dart_ExitIsolate();\n return;\n }\n\n \/\/ Create a SendPort that DartDev can use to communicate its results over.\n send_port_id = Dart_NewNativePort(\"dartdev\", DartDevResultCallback, false);\n ASSERT(send_port_id != ILLEGAL_PORT);\n Dart_Handle send_port = Dart_NewSendPort(send_port_id);\n CHECK_RESULT(send_port);\n\n const intptr_t kNumIsolateArgs = 7;\n Dart_Handle isolate_args[kNumIsolateArgs];\n isolate_args[0] = Dart_Null(); \/\/ parentPort\n isolate_args[1] = main_closure; \/\/ entryPoint\n isolate_args[2] = runner->dart_options_->CreateRuntimeOptions(); \/\/ args\n isolate_args[3] = send_port; \/\/ message\n isolate_args[4] = Dart_True(); \/\/ isSpawnUri\n isolate_args[5] = Dart_Null(); \/\/ controlPort\n isolate_args[6] = Dart_Null(); \/\/ capabilities\n\n Dart_Handle isolate_lib =\n Dart_LookupLibrary(Dart_NewStringFromCString(\"dart:isolate\"));\n Dart_Handle result =\n Dart_Invoke(isolate_lib, Dart_NewStringFromCString(\"_startIsolate\"),\n kNumIsolateArgs, isolate_args);\n CHECK_RESULT(result);\n CHECK_RESULT(Dart_RunLoop());\n\n Dart_CloseNativePort(send_port_id);\n\n Dart_ExitScope();\n Dart_ShutdownIsolate();\n}\n\nvoid DartDevIsolate::DartDevRunner::ProcessError(const char* msg,\n int32_t exit_code) {\n Syslog::PrintErr(\"%s\\n\", msg);\n Process::SetGlobalExitCode(exit_code);\n result_ = DartDevIsolate::DartDev_Result_Exit;\n DartDevRunner::monitor_->Notify();\n}\n\nDartDevIsolate::DartDev_Result DartDevIsolate::RunDartDev(\n Dart_IsolateGroupCreateCallback create_isolate,\n const char* packages_file,\n char** script,\n CommandLineOptions* dart_options) {\n runner_.Run(create_isolate, packages_file, script, dart_options);\n return runner_.result();\n}\n\n#endif \/\/ if !defined(DART_PRECOMPILED_RUNTIME)\n\n} \/\/ namespace bin\n} \/\/ namespace dart\n<commit_msg>[ VM \/ DartDev ] Spawn DartDev isolate with flags matching those used to generate the snapshot<commit_after>\/\/ Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"bin\/dartdev_isolate.h\"\n\n#if !defined(DART_PRECOMPILED_RUNTIME)\n\n#include <functional>\n#include <memory>\n\n#include \"bin\/directory.h\"\n#include \"bin\/error_exit.h\"\n#include \"bin\/exe_utils.h\"\n#include \"bin\/file.h\"\n#include \"bin\/lockers.h\"\n#include \"bin\/platform.h\"\n#include \"bin\/process.h\"\n#include \"include\/dart_embedder_api.h\"\n#include \"platform\/utils.h\"\n\n#define CHECK_RESULT(result) \\\n if (Dart_IsError(result)) { \\\n ProcessError(Dart_GetError(result), kErrorExitCode); \\\n if (send_port_id != ILLEGAL_PORT) { \\\n Dart_CloseNativePort(send_port_id); \\\n } \\\n Dart_ExitScope(); \\\n Dart_ExitIsolate(); \\\n return; \\\n }\n\nnamespace dart {\nnamespace bin {\n\nDartDevIsolate::DartDevRunner DartDevIsolate::runner_ =\n DartDevIsolate::DartDevRunner();\nbool DartDevIsolate::should_run_dart_dev_ = false;\nMonitor* DartDevIsolate::DartDevRunner::monitor_ = new Monitor();\nDartDevIsolate::DartDev_Result DartDevIsolate::DartDevRunner::result_ =\n DartDevIsolate::DartDev_Result_Unknown;\nchar** DartDevIsolate::DartDevRunner::script_ = nullptr;\nstd::unique_ptr<char*[], void (*)(char*[])>\n DartDevIsolate::DartDevRunner::argv_ =\n std::unique_ptr<char*[], void (*)(char**)>(nullptr, [](char**) {});\nintptr_t DartDevIsolate::DartDevRunner::argc_ = 0;\n\nbool DartDevIsolate::ShouldParseCommand(const char* script_uri) {\n \/\/ If script_uri is not a file path or of a known URI scheme, we can assume\n \/\/ that this is a DartDev command.\n return (!File::ExistsUri(nullptr, script_uri) &&\n (strncmp(script_uri, \"http:\/\/\", 7) != 0) &&\n (strncmp(script_uri, \"https:\/\/\", 8) != 0) &&\n (strncmp(script_uri, \"file:\/\/\", 7) != 0) &&\n (strncmp(script_uri, \"package:\", 8) != 0) &&\n (strncmp(script_uri, \"google3:\/\/\", 10) != 0));\n}\n\nconst char* DartDevIsolate::TryResolveDartDevSnapshotPath() {\n \/\/ |dir_prefix| includes the last path seperator.\n auto dir_prefix = EXEUtils::GetDirectoryPrefixFromExeName();\n\n \/\/ First assume we're in dart-sdk\/bin.\n char* snapshot_path =\n Utils::SCreate(\"%ssnapshots\/dartdev.dart.snapshot\", dir_prefix.get());\n if (File::Exists(nullptr, snapshot_path)) {\n return snapshot_path;\n }\n free(snapshot_path);\n\n \/\/ If we're not in dart-sdk\/bin, we might be in one of the $SDK\/out\/*\n \/\/ directories. Try to use a snapshot rom a previously built SDK.\n snapshot_path = Utils::SCreate(\"%sdartdev.dart.snapshot\", dir_prefix.get());\n if (File::Exists(nullptr, snapshot_path)) {\n return snapshot_path;\n }\n free(snapshot_path);\n\n Syslog::PrintErr(\"Could not find DartDev snapshot.\\n\");\n return nullptr;\n}\n\nvoid DartDevIsolate::DartDevRunner::Run(\n Dart_IsolateGroupCreateCallback create_isolate,\n const char* packages_file,\n char** script,\n CommandLineOptions* dart_options) {\n create_isolate_ = create_isolate;\n dart_options_ = dart_options;\n packages_file_ = packages_file;\n script_ = script;\n\n MonitorLocker locker(monitor_);\n int result = Thread::Start(\"DartDev Runner\", RunCallback,\n reinterpret_cast<uword>(this));\n if (result != 0) {\n FATAL1(\"Failed to start DartDev thread: %d\", result);\n }\n monitor_->WaitMicros(Monitor::kNoTimeout);\n\n if (result_ == DartDevIsolate::DartDev_Result_Run) {\n \/\/ Clear the DartDev dart_options and replace them with the processed\n \/\/ options provided by DartDev.\n dart_options_->Reset();\n for (intptr_t i = 0; i < argc_; ++i) {\n dart_options_->AddArguments(const_cast<const char**>(argv_.get()), argc_);\n }\n }\n}\n\nstatic Dart_CObject* GetArrayItem(Dart_CObject* message, intptr_t index) {\n return message->value.as_array.values[index];\n}\n\nvoid DartDevIsolate::DartDevRunner::DartDevResultCallback(\n Dart_Port dest_port_id,\n Dart_CObject* message) {\n ASSERT(message->type == Dart_CObject_kArray);\n int32_t type = GetArrayItem(message, 0)->value.as_int32;\n switch (type) {\n case DartDevIsolate::DartDev_Result_Run: {\n result_ = DartDevIsolate::DartDev_Result_Run;\n ASSERT(GetArrayItem(message, 1)->type == Dart_CObject_kString);\n if (*script_ != nullptr) {\n free(*script_);\n }\n *script_ = Utils::StrDup(GetArrayItem(message, 1)->value.as_string);\n ASSERT(GetArrayItem(message, 2)->type == Dart_CObject_kArray);\n Dart_CObject* args = GetArrayItem(message, 2);\n argc_ = args->value.as_array.length;\n Dart_CObject** dart_args = args->value.as_array.values;\n\n auto deleter = [](char** args) {\n for (intptr_t i = 0; i < argc_; ++i) {\n free(args[i]);\n }\n delete[] args;\n };\n\n argv_ =\n std::unique_ptr<char*[], void (*)(char**)>(new char*[argc_], deleter);\n for (intptr_t i = 0; i < argc_; ++i) {\n argv_[i] = Utils::StrDup(dart_args[i]->value.as_string);\n }\n break;\n }\n case DartDevIsolate::DartDev_Result_Exit: {\n ASSERT(GetArrayItem(message, 1)->type == Dart_CObject_kInt32);\n int32_t dartdev_exit_code = GetArrayItem(message, 1)->value.as_int32;\n\n \/\/ If we're given a non-zero exit code, DartDev is signaling for us to\n \/\/ shutdown.\n if (dartdev_exit_code != 0) {\n Process::SetGlobalExitCode(dartdev_exit_code);\n }\n\n \/\/ If DartDev hasn't signaled for us to do anything else, we can assume\n \/\/ there's nothing else for the VM to run and that we can exit.\n if (result_ == DartDevIsolate::DartDev_Result_Unknown) {\n result_ = DartDevIsolate::DartDev_Result_Exit;\n }\n\n \/\/ DartDev is done processing the command. Unblock the main thread and\n \/\/ continue the launch procedure.\n DartDevRunner::monitor_->Notify();\n break;\n }\n default:\n UNREACHABLE();\n }\n}\n\nvoid DartDevIsolate::DartDevRunner::RunCallback(uword args) {\n MonitorLocker locker_(DartDevRunner::monitor_);\n DartDevRunner* runner = reinterpret_cast<DartDevRunner*>(args);\n\n \/\/ TODO(bkonyi): bring up DartDev from kernel instead of a app-jit snapshot.\n \/\/ See https:\/\/github.com\/dart-lang\/sdk\/issues\/42804\n const char* dartdev_path = DartDevIsolate::TryResolveDartDevSnapshotPath();\n if (dartdev_path == nullptr) {\n ProcessError(\"Failed to find DartDev snapshot.\", kErrorExitCode);\n return;\n }\n\n \/\/ Hardcode flags to match those used to generate the DartDev snapshot.\n Dart_IsolateFlags flags;\n Dart_IsolateFlagsInitialize(&flags);\n flags.enable_asserts = false;\n flags.null_safety = false;\n flags.use_field_guards = true;\n flags.use_osr = true;\n\n char* error;\n Dart_Isolate dartdev_isolate = runner->create_isolate_(\n dartdev_path, \"dartdev\", nullptr, runner->packages_file_, &flags,\n NULL \/* callback_data *\/, const_cast<char**>(&error));\n free(const_cast<char*>(dartdev_path));\n\n if (dartdev_isolate == nullptr) {\n ProcessError(error, kErrorExitCode);\n return;\n }\n\n Dart_EnterIsolate(dartdev_isolate);\n Dart_EnterScope();\n\n \/\/ Retrieve the DartDev entrypoint.\n Dart_Port send_port_id = ILLEGAL_PORT;\n Dart_Handle root_lib = Dart_RootLibrary();\n Dart_Handle main_closure =\n Dart_GetField(root_lib, Dart_NewStringFromCString(\"main\"));\n CHECK_RESULT(main_closure);\n\n if (!Dart_IsClosure(main_closure)) {\n ProcessError(\"Unable to find 'main' in root library 'dartdev'\",\n kErrorExitCode);\n Dart_ExitScope();\n Dart_ExitIsolate();\n return;\n }\n\n \/\/ Create a SendPort that DartDev can use to communicate its results over.\n send_port_id = Dart_NewNativePort(\"dartdev\", DartDevResultCallback, false);\n ASSERT(send_port_id != ILLEGAL_PORT);\n Dart_Handle send_port = Dart_NewSendPort(send_port_id);\n CHECK_RESULT(send_port);\n\n const intptr_t kNumIsolateArgs = 7;\n Dart_Handle isolate_args[kNumIsolateArgs];\n isolate_args[0] = Dart_Null(); \/\/ parentPort\n isolate_args[1] = main_closure; \/\/ entryPoint\n isolate_args[2] = runner->dart_options_->CreateRuntimeOptions(); \/\/ args\n isolate_args[3] = send_port; \/\/ message\n isolate_args[4] = Dart_True(); \/\/ isSpawnUri\n isolate_args[5] = Dart_Null(); \/\/ controlPort\n isolate_args[6] = Dart_Null(); \/\/ capabilities\n\n Dart_Handle isolate_lib =\n Dart_LookupLibrary(Dart_NewStringFromCString(\"dart:isolate\"));\n Dart_Handle result =\n Dart_Invoke(isolate_lib, Dart_NewStringFromCString(\"_startIsolate\"),\n kNumIsolateArgs, isolate_args);\n CHECK_RESULT(result);\n CHECK_RESULT(Dart_RunLoop());\n\n Dart_CloseNativePort(send_port_id);\n\n Dart_ExitScope();\n Dart_ShutdownIsolate();\n}\n\nvoid DartDevIsolate::DartDevRunner::ProcessError(const char* msg,\n int32_t exit_code) {\n Syslog::PrintErr(\"%s\\n\", msg);\n Process::SetGlobalExitCode(exit_code);\n result_ = DartDevIsolate::DartDev_Result_Exit;\n DartDevRunner::monitor_->Notify();\n}\n\nDartDevIsolate::DartDev_Result DartDevIsolate::RunDartDev(\n Dart_IsolateGroupCreateCallback create_isolate,\n const char* packages_file,\n char** script,\n CommandLineOptions* dart_options) {\n runner_.Run(create_isolate, packages_file, script, dart_options);\n return runner_.result();\n}\n\n#endif \/\/ if !defined(DART_PRECOMPILED_RUNTIME)\n\n} \/\/ namespace bin\n} \/\/ namespace dart\n<|endoftext|>"} {"text":"<commit_before>#include \"TrackingWorker.hpp\"\n\n#include <boost\/chrono\/duration.hpp>\n#include <ros\/console.h>\n\nTrackingWorker::TrackingWorker(IPositionReceiver *receiver)\n{\n\tassert(receiver != 0);\n\t\n\tthis->receiver = receiver;\n\tstop = false;\n\t\n\tthread = new boost::thread(boost::bind(&TrackingWorker::run, this));\n}\n\nTrackingWorker::~TrackingWorker()\n{\n\tstop = true;\n\tthread->join();\n}\n\nvoid TrackingWorker::run()\n{\n\tROS_INFO(\"Started tracking thread\");\n\t\n\tbool receivedFirstPosition = false;\n\t\n\twhile (!stop) {\n\t\tCameraData data = dequeue();\n\t\t\n\t\tif (data.valid) {\n\t\t\tROS_DEBUG(\"Got valid data\");\n\t\t\treceivedFirstPosition = true;\n\t\t\tVector position = tracker.updatePosition(data.cameraVector, data.camNo, data.quadcopterId);\n\t\t\t\n\t\t\tstd::vector<Vector> positions;\n\t\t\tstd::vector<int> ids;\n\t\t\tstd::vector<int> updates;\n\t\t\tpositions.push_back(position);\n\t\t\tids.push_back(data.quadcopterId);\n\t\t\tupdates.push_back(1);\n\t\t\t\n\t\t\tif (position.isValid()) {\n\t\t\t\treceiver->updatePositions(positions, ids, updates);\n\t\t\t} else {\n\t\t\t\tROS_DEBUG(\"Not enough information to get position of quadcopter %d\", data.quadcopterId);\n\t\t\t}\n\t\t} else if (receivedFirstPosition == true) {\n\t\t\tROS_WARN(\"Position update buffer is empty!\");\n\t\t}\n\t}\n\t\n\tROS_INFO(\"Stopped tracking thread\");\n}\n\nvoid TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId)\n{\n\tCameraData data;\n\tdata.cameraVector = cameraVector;\n\tdata.camNo = camNo;\n\tdata.quadcopterId = quadcopterId;\n\tdata.valid = true;\n\t\n\tupdatePosition(data);\n}\n\nvoid TrackingWorker::updatePosition(CameraData data)\n{\n\tenqueue(data);\n}\n\nvoid TrackingWorker::enqueue(CameraData data)\n{\n\tROS_DEBUG(\"Inserting CameraData\");\n\t\n\t{\n\t\tboost::mutex::scoped_lock lock(positionsMutex);\n\t\tpositions.push(data);\n\t\t\n\t\tif (positions.size() > 25) {\n\t\t\tROS_WARN(\"Position update buffer is running full (%ld entries). Seems like the position updating can't keep up!\", positions.size());\n\t\t}\n\t}\n\t\n\tROS_DEBUG(\"Notifying about new CameraData\");\n\t\n\tpositionsEmpty.notify_one();\n\t\n\tROS_DEBUG(\"Finished insertion process\");\n}\n\nCameraData TrackingWorker::dequeue()\n{\n\tROS_DEBUG(\"Getting positions lock\");\n\t\n\t{\n\t\tboost::mutex::scoped_lock lock(positionsMutex);\n\t\t\n\t\tROS_DEBUG(\"Got positions lock\");\n\t\t\n\t\tif (!dataAvailable()) {\n\t\t\tROS_DEBUG(\"Waiting...\");\n\t\t\tpositionsEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100));\n\t\t\tROS_DEBUG(\"Finished waiting\");\n\t\t}\n\t\t\n\t\tif (dataAvailable()) {\n\t\t\tCameraData data = positions.back();\n\t\t\tpositions.pop();\n\t\t\treturn data;\n\t\t} else {\n\t\t\tCameraData data;\n\t\t\tdata.valid = false;\n\t\t\treturn data;\n\t\t}\n\t}\n\t\n\tROS_DEBUG(\"Released positions lock\");\n}\n\nbool TrackingWorker::dataAvailable()\n{\n\treturn positions.size() > 0;\n}\n\nbool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo)\n{\n\treturn tracker.calibrate(chessboard, camNo);\n}<commit_msg>Uncommented debug output<commit_after>#include \"TrackingWorker.hpp\"\n\n#include <boost\/chrono\/duration.hpp>\n#include <ros\/console.h>\n\nTrackingWorker::TrackingWorker(IPositionReceiver *receiver)\n{\n\tassert(receiver != 0);\n\t\n\tthis->receiver = receiver;\n\tstop = false;\n\t\n\tthread = new boost::thread(boost::bind(&TrackingWorker::run, this));\n}\n\nTrackingWorker::~TrackingWorker()\n{\n\tstop = true;\n\tthread->join();\n}\n\nvoid TrackingWorker::run()\n{\n\tROS_INFO(\"Started tracking thread\");\n\t\n\tbool receivedFirstPosition = false;\n\t\n\twhile (!stop) {\n\t\tCameraData data = dequeue();\n\t\t\n\t\tif (data.valid) {\n\t\t\t\/\/ ROS_DEBUG(\"Got valid data\");\n\t\t\treceivedFirstPosition = true;\n\t\t\tVector position = tracker.updatePosition(data.cameraVector, data.camNo, data.quadcopterId);\n\t\t\t\n\t\t\tstd::vector<Vector> positions;\n\t\t\tstd::vector<int> ids;\n\t\t\tstd::vector<int> updates;\n\t\t\tpositions.push_back(position);\n\t\t\tids.push_back(data.quadcopterId);\n\t\t\tupdates.push_back(1);\n\t\t\t\n\t\t\tif (position.isValid()) {\n\t\t\t\treceiver->updatePositions(positions, ids, updates);\n\t\t\t} else {\n\t\t\t\tROS_DEBUG(\"Not enough information to get position of quadcopter %d\", data.quadcopterId);\n\t\t\t}\n\t\t} else if (receivedFirstPosition == true) {\n\t\t\t\/\/ ROS_WARN(\"Position update buffer is empty!\");\n\t\t}\n\t}\n\t\n\tROS_INFO(\"Stopped tracking thread\");\n}\n\nvoid TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId)\n{\n\tCameraData data;\n\tdata.cameraVector = cameraVector;\n\tdata.camNo = camNo;\n\tdata.quadcopterId = quadcopterId;\n\tdata.valid = true;\n\t\n\tupdatePosition(data);\n}\n\nvoid TrackingWorker::updatePosition(CameraData data)\n{\n\tenqueue(data);\n}\n\nvoid TrackingWorker::enqueue(CameraData data)\n{\n\t\/\/ ROS_DEBUG(\"Inserting CameraData\");\n\t\n\t{\n\t\tboost::mutex::scoped_lock lock(positionsMutex);\n\t\tpositions.push(data);\n\t\t\n\t\tif (positions.size() > 25) {\n\t\t\tROS_WARN(\"Position update buffer is running full (%ld entries). Seems like the position updating can't keep up!\", positions.size());\n\t\t}\n\t}\n\t\n\t\/\/ ROS_DEBUG(\"Notifying about new CameraData\");\n\t\n\tpositionsEmpty.notify_one();\n\t\n\t\/\/ ROS_DEBUG(\"Finished insertion process\");\n}\n\nCameraData TrackingWorker::dequeue()\n{\n\t\/\/ ROS_DEBUG(\"Getting positions lock\");\n\t\n\t{\n\t\tboost::mutex::scoped_lock lock(positionsMutex);\n\t\t\n\t\t\/\/ ROS_DEBUG(\"Got positions lock\");\n\t\t\n\t\tif (!dataAvailable()) {\n\t\t\tpositionsEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100));\n\t\t}\n\t\t\n\t\tif (dataAvailable()) {\n\t\t\tCameraData data = positions.back();\n\t\t\tpositions.pop();\n\t\t\treturn data;\n\t\t} else {\n\t\t\tCameraData data;\n\t\t\tdata.valid = false;\n\t\t\treturn data;\n\t\t}\n\t}\n\t\n\t\/\/ ROS_DEBUG(\"Released positions lock\");\n}\n\nbool TrackingWorker::dataAvailable()\n{\n\treturn positions.size() > 0;\n}\n\nbool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo)\n{\n\treturn tracker.calibrate(chessboard, camNo);\n}<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n#include <memory>\n#include <type_traits>\n\n#include \"base\/macros.hpp\"\n#include \"base\/not_constructible.hpp\"\n#include \"base\/traits.hpp\"\n#include \"glog\/logging.h\"\n\n\/\/ This file defines a pointer wrapper |not_null| that statically ensures\n\/\/ non-nullness where possible, and performs runtime checks at the point of\n\/\/ conversion otherwise.\n\/\/ The point is to replace cases of undefined behaviour (dereferencing a null\n\/\/ pointer) by well-defined, localized, failure.\n\/\/ For instance, when dereferencing a null pointer into a reference, a segfault\n\/\/ will generally not occur when the pointer is dereferenced, but where the\n\/\/ reference is used instead, making it hard to track where an invariant was\n\/\/ violated.\n\/\/ The static typing of |not_null| also optimizes away some unneeded checks:\n\/\/ a function taking a |not_null| argument will not need to check its arguments,\n\/\/ the caller has to provide a |not_null| pointer instead. If the object passed\n\/\/ is already a |not_null|, no check needs to be performed.\n\/\/ The syntax is as follows:\n\/\/ not_null<int*> p \/\/ non-null pointer to an |int|.\n\/\/ not_null<std::unique_ptr<int>> p \/\/ non-null unique pointer to an |int|.\n\/\/ |not_null| does not have a default constructor, since there is no non-null\n\/\/ default valid pointer. The only ways to construct a |not_null| pointer,\n\/\/ other than from existing instances of |not_null|, are (implicit) conversion\n\/\/ from a nullable pointer, the factory |check_not_null|, and\n\/\/ |make_not_null_unique|.\n\/\/\n\/\/ The following example shows uses of |not_null|:\n\/\/ void Accumulate(not_null<int*> const accumulator,\n\/\/ not_null<int const*> const term) {\n\/\/ *accumulator += *term; \/\/ This will not dereference a null pointer.\n\/\/ }\n\/\/\n\/\/ void InterfaceAccumulator(int* const dubious_accumulator,\n\/\/ int const* const term_of_dubious_c_provenance) {\n\/\/ \/\/ The call below performs two checks. If either parameter is null, the\n\/\/ \/\/ program will fail (through a glog |CHECK|) at the callsite.\n\/\/ Accumulate(dubious_accumulator, term_of_dubious_c_provenance);\n\/\/ }\n\/\/\n\/\/ void UseAccumulator() {\n\/\/ not_null<std::unique_ptr<int>> accumulator =\n\/\/ make_not_null_unique<int>(0);\n\/\/ not_null<int> term = \/\/ ...\n\/\/ \/\/ This compiles, no check is performed.\n\/\/ Accumulate(accumulator.get(), term);\n\/\/ \/\/ ...\n\/\/ }\n\/\/\n\/\/ If implicit conversion from a nullable pointer to |not_null| does not work,\n\/\/ e.g. for template deduction, use the factory |check_not_null|.\n\/\/ template<typename T>\n\/\/ void Foo(not_null<T*> not_null_ptr);\n\/\/\n\/\/ SomeType* ptr;\n\/\/ \/\/ The following will not compile:\n\/\/ Foo(ptr);\n\/\/ \/\/ The following works:\n\/\/ Foo(check_not_null(ptr));\n\/\/ \/\/ It is more concise than the alternative:\n\/\/ Foo(not_null<SomeType*>(ptr))\n\/\/\n\/\/ The following optimization is made possible by the use of |not_null|:\n\/\/ |term == nullptr| can be expanded to false through inlining, so the branch\n\/\/ will likely be optimized away.\n\/\/ if (term == nullptr) \/\/ ...\n\/\/ \/\/ Same as above.\n\/\/ if (term) \/\/ ...\n\nnamespace principia {\nnamespace base {\n\ntemplate<typename Pointer>\nclass not_null;\n\n\/\/ Type traits.\n\n\/\/ |remove_not_null<not_null<T>>::type| is |remove_not_null<T>::type|.\n\/\/ The recurrence ends when |T| is not an instance of |not_null|, in which case\n\/\/ |remove_not_null<T>::type| is |T|.\ntemplate<typename Pointer>\nstruct remove_not_null : not_constructible {\n using type = Pointer;\n};\ntemplate<typename Pointer>\nstruct remove_not_null<not_null<Pointer>> {\n using type = typename remove_not_null<Pointer>::type;\n};\n\n\/\/ When |T| is not a reference, |_checked_not_null<T>| is |not_null<T>| if |T|\n\/\/ is not already an instance of |not_null|. It fails otherwise.\n\/\/ |_checked_not_null| is invariant under application of reference or rvalue\n\/\/ reference to its template argument.\ntemplate<typename Pointer>\nusing _checked_not_null = typename std::enable_if<\n !is_instance_of_v<not_null, typename std::remove_reference<Pointer>::type>,\n not_null<typename std::remove_reference<Pointer>::type>>::type;\n\n\/\/ We cannot refer to the template |not_null| inside of |not_null|.\ntemplate<typename Pointer>\ninline constexpr bool is_instance_of_not_null_v =\n is_instance_of_v<not_null, Pointer>;\n\n\/\/ |not_null<Pointer>| is a wrapper for a non-null object of type |Pointer|.\n\/\/ |Pointer| should be a C-style pointer or a smart pointer. |Pointer| must not\n\/\/ be a const, reference, rvalue reference, or |not_null|. |not_null<Pointer>|\n\/\/ is movable and may be left in an invalid state when moved, i.e., its\n\/\/ |pointer_| may become null.\n\/\/ |not_null<not_null<Pointer>>| and |not_null<Pointer>| are equivalent.\n\/\/ This is useful when a |template<typename T>| using a |not_null<T>| is\n\/\/ instanced with an instance of |not_null|.\ntemplate<typename Pointer>\nclass not_null final {\n public:\n \/\/ The type of the pointer being wrapped.\n \/\/ This follows the naming convention from |std::unique_ptr|.\n using pointer = typename remove_not_null<Pointer>::type;\n\n \/\/ Smart pointers define this type.\n using element_type = typename std::pointer_traits<pointer>::element_type;\n\n not_null() = delete;\n\n \/\/ Copy constructor from an other |not_null<Pointer>|.\n not_null(not_null const&) = default;\n \/\/ Copy contructor for implicitly convertible pointers.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value>::type>\n not_null(not_null<OtherPointer> const& other);\n \/\/ Constructor from a nullable pointer, performs a null check.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value &&\n !is_instance_of_not_null_v<pointer>>::type>\n not_null(OtherPointer other); \/\/ NOLINT(runtime\/explicit)\n \/\/ Explicit copy constructor for static_cast'ing.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n !std::is_convertible<OtherPointer, pointer>::value>::type,\n typename = decltype(static_cast<pointer>(\n std::declval<OtherPointer>()))>\n explicit not_null(not_null<OtherPointer> const& other);\n\n \/\/ Move constructor from an other |not_null<Pointer>|. This constructor may\n \/\/ invalidate its argument.\n not_null(not_null&&) = default;\n \/\/ Move contructor for implicitly convertible pointers. This constructor may\n \/\/ invalidate its argument.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value>::type>\n not_null(not_null<OtherPointer>&& other);\n \/\/ Explicit move constructor for static_cast'ing. This constructor may\n \/\/ invalidate its argument.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n !std::is_convertible<OtherPointer, pointer>::value>::type,\n typename = decltype(static_cast<pointer>(\n std::declval<OtherPointer>()))>\n explicit not_null(not_null<OtherPointer>&& other);\n\n \/\/ Copy assigment operators.\n not_null& operator=(not_null const&) = default;\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value>::type>\n not_null& operator=(not_null<OtherPointer> const& other);\n\n \/\/ Move assignment operators.\n \/\/ Implemented as a swap, so the argument remains valid.\n not_null& operator=(not_null&& other);\n \/\/ This operator may invalidate its argument.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value>::type>\n not_null& operator=(not_null<OtherPointer>&& other);\n\n \/\/ Returns |pointer_|, by const reference to avoid a copy if |pointer| is\n \/\/ |unique_ptr|.\n \/\/ If this were to return by |const&|, ambiguities would arise where an rvalue\n \/\/ of type |not_null<pointer>| is given as an argument to a function that has\n \/\/ overloads for both |pointer const&| and |pointer&&|.\n \/\/ Note that the preference for |T&&| over |T const&| for overload resolution\n \/\/ is not relevant here since both go through a user-defined conversion,\n \/\/ see 13.3.3.2.\n \/\/ GCC nevertheless incorrectly prefers |T&&| in that case, while clang and\n \/\/ MSVC recognize the ambiguity.\n \/\/ The |RValue| test gives two examples of this.\n operator pointer const&&() const&;\n\n template<typename OtherPointer,\n typename = std::enable_if_t<\n std::is_convertible<pointer, OtherPointer>::value &&\n !std::is_same<pointer, OtherPointer>::value &&\n !is_instance_of_not_null_v<OtherPointer>>>\n operator OtherPointer() const&;\n\n \/\/ Used to convert a |not_null<unique_ptr<>>| to |unique_ptr<>|.\n operator pointer&&() &&;\n\n template<typename OtherPointer,\n typename = std::enable_if_t<\n std::is_convertible<pointer, OtherPointer>::value &&\n !is_instance_of_not_null_v<OtherPointer>>>\n operator OtherPointer() &&; \/\/ NOLINT(whitespace\/operators)\n\n \/\/ Returns |*pointer_|.\n std::add_lvalue_reference_t<element_type> operator*() const;\n std::add_pointer_t<element_type> operator->() const;\n\n \/\/ When |pointer| has a |get()| member function, this returns\n \/\/ |pointer_.get()|.\n template<typename P = pointer, typename = decltype(std::declval<P>().get())>\n not_null<decltype(std::declval<P>().get())> get() const;\n\n \/\/ When |pointer| has a |release()| member function, this returns\n \/\/ |pointer_.release()|. May invalidate its argument.\n template<typename P = pointer,\n typename = decltype(std::declval<P>().release())>\n not_null<decltype(std::declval<P>().release())> release();\n\n \/\/ When |pointer| has a |reset()| member function, this calls\n \/\/ |pointer_.reset()|.\n template<typename Q,\n typename P = pointer,\n typename = decltype(std::declval<P>().reset())>\n void reset(not_null<Q> ptr);\n\n \/\/ The following operators are redundant for valid |not_null<Pointer>|s with\n \/\/ the implicit conversion to |pointer|, but they should allow some\n \/\/ optimization.\n\n \/\/ Returns |false|.\n bool operator==(std::nullptr_t other) const;\n \/\/ Returns |true|.\n bool operator!=(std::nullptr_t other) const;\n \/\/ Returns |true|.\n operator bool() const;\n\n \/\/ Equality.\n bool operator==(pointer other) const;\n bool operator==(not_null other) const;\n bool operator!=(pointer other) const;\n bool operator!=(not_null other) const;\n\n \/\/ Ordering.\n bool operator<(not_null other) const;\n bool operator<=(not_null other) const;\n bool operator>=(not_null other) const;\n bool operator>(not_null other) const;\n\n private:\n struct unchecked_tag final {};\n\n \/\/ Creates a |not_null<Pointer>| whose |pointer_| equals the given |pointer|,\n \/\/ dawg. The constructor does *not* perform a null check. Callers must\n \/\/ perform one if needed before using it.\n explicit not_null(pointer other, unchecked_tag tag);\n\n pointer pointer_;\n\n static constexpr unchecked_tag unchecked_tag_{};\n\n template<typename OtherPointer>\n friend class not_null;\n\n template<typename P>\n friend _checked_not_null<P> check_not_null(P pointer);\n template<typename T, typename... Args>\n friend not_null<std::shared_ptr<T>> make_not_null_shared(Args&&... args);\n template<typename T, typename... Args>\n friend not_null<std::unique_ptr<T>> make_not_null_unique(Args&&... args);\n};\n\n\/\/ We want only one way of doing things, and we can't make\n\/\/ |not_null<Pointer> const| and |not_null<Pointer const>| etc. equivalent\n\/\/ easily.\n\n\/\/ Use |not_null<Pointer> const| instead.\ntemplate<typename Pointer>\nclass not_null<Pointer const>;\n\/\/ Use |not_null<Pointer>&| instead.\ntemplate<typename Pointer>\nclass not_null<Pointer&>;\n\/\/ Use |not_null<Pointer>&&| instead.\ntemplate<typename Pointer>\nclass not_null<Pointer&&>;\n\n\/\/ Factory taking advantage of template argument deduction. Returns a\n\/\/ |not_null<Pointer>| to |*pointer|. |CHECK|s that |pointer| is not null.\ntemplate<typename Pointer>\n_checked_not_null<Pointer> check_not_null(Pointer pointer);\n\n#if 0\n\/\/ While the above factory would cover this case using the implicit\n\/\/ conversion, this results in a redundant |CHECK|.\n\/\/ This function returns its argument.\ntemplate<typename Pointer>\nnot_null<Pointer> check_not_null(not_null<Pointer> pointer);\n#endif\n\n\/\/ Factory for a |not_null<std::unique_ptr<T>>|, forwards the arguments to the\n\/\/ constructor of T. |make_not_null_unique<T>(args)| is interchangeable with\n\/\/ |check_not_null(make_unique<T>(args))|, but does not perform a |CHECK|, since\n\/\/ the result of |make_unique| is not null.\ntemplate<typename T, typename... Args>\nnot_null<std::unique_ptr<T>> make_not_null_unique(Args&&... args);\n\n\/\/ For logging.\ntemplate<typename Pointer>\nstd::ostream& operator<<(std::ostream& stream,\n not_null<Pointer> const& pointer);\n\n} \/\/ namespace base\n} \/\/ namespace principia\n\n#include \"base\/not_null_body.hpp\"\n<commit_msg>Embarrassing.<commit_after>\n#pragma once\n\n#include <memory>\n#include <type_traits>\n\n#include \"base\/macros.hpp\"\n#include \"base\/not_constructible.hpp\"\n#include \"base\/traits.hpp\"\n#include \"glog\/logging.h\"\n\n\/\/ This file defines a pointer wrapper |not_null| that statically ensures\n\/\/ non-nullness where possible, and performs runtime checks at the point of\n\/\/ conversion otherwise.\n\/\/ The point is to replace cases of undefined behaviour (dereferencing a null\n\/\/ pointer) by well-defined, localized, failure.\n\/\/ For instance, when dereferencing a null pointer into a reference, a segfault\n\/\/ will generally not occur when the pointer is dereferenced, but where the\n\/\/ reference is used instead, making it hard to track where an invariant was\n\/\/ violated.\n\/\/ The static typing of |not_null| also optimizes away some unneeded checks:\n\/\/ a function taking a |not_null| argument will not need to check its arguments,\n\/\/ the caller has to provide a |not_null| pointer instead. If the object passed\n\/\/ is already a |not_null|, no check needs to be performed.\n\/\/ The syntax is as follows:\n\/\/ not_null<int*> p \/\/ non-null pointer to an |int|.\n\/\/ not_null<std::unique_ptr<int>> p \/\/ non-null unique pointer to an |int|.\n\/\/ |not_null| does not have a default constructor, since there is no non-null\n\/\/ default valid pointer. The only ways to construct a |not_null| pointer,\n\/\/ other than from existing instances of |not_null|, are (implicit) conversion\n\/\/ from a nullable pointer, the factory |check_not_null|, and\n\/\/ |make_not_null_unique|.\n\/\/\n\/\/ The following example shows uses of |not_null|:\n\/\/ void Accumulate(not_null<int*> const accumulator,\n\/\/ not_null<int const*> const term) {\n\/\/ *accumulator += *term; \/\/ This will not dereference a null pointer.\n\/\/ }\n\/\/\n\/\/ void InterfaceAccumulator(int* const dubious_accumulator,\n\/\/ int const* const term_of_dubious_c_provenance) {\n\/\/ \/\/ The call below performs two checks. If either parameter is null, the\n\/\/ \/\/ program will fail (through a glog |CHECK|) at the callsite.\n\/\/ Accumulate(dubious_accumulator, term_of_dubious_c_provenance);\n\/\/ }\n\/\/\n\/\/ void UseAccumulator() {\n\/\/ not_null<std::unique_ptr<int>> accumulator =\n\/\/ make_not_null_unique<int>(0);\n\/\/ not_null<int> term = \/\/ ...\n\/\/ \/\/ This compiles, no check is performed.\n\/\/ Accumulate(accumulator.get(), term);\n\/\/ \/\/ ...\n\/\/ }\n\/\/\n\/\/ If implicit conversion from a nullable pointer to |not_null| does not work,\n\/\/ e.g. for template deduction, use the factory |check_not_null|.\n\/\/ template<typename T>\n\/\/ void Foo(not_null<T*> not_null_ptr);\n\/\/\n\/\/ SomeType* ptr;\n\/\/ \/\/ The following will not compile:\n\/\/ Foo(ptr);\n\/\/ \/\/ The following works:\n\/\/ Foo(check_not_null(ptr));\n\/\/ \/\/ It is more concise than the alternative:\n\/\/ Foo(not_null<SomeType*>(ptr))\n\/\/\n\/\/ The following optimization is made possible by the use of |not_null|:\n\/\/ |term == nullptr| can be expanded to false through inlining, so the branch\n\/\/ will likely be optimized away.\n\/\/ if (term == nullptr) \/\/ ...\n\/\/ \/\/ Same as above.\n\/\/ if (term) \/\/ ...\n\nnamespace principia {\nnamespace base {\n\ntemplate<typename Pointer>\nclass not_null;\n\n\/\/ Type traits.\n\n\/\/ |remove_not_null<not_null<T>>::type| is |remove_not_null<T>::type|.\n\/\/ The recurrence ends when |T| is not an instance of |not_null|, in which case\n\/\/ |remove_not_null<T>::type| is |T|.\ntemplate<typename Pointer>\nstruct remove_not_null : not_constructible {\n using type = Pointer;\n};\ntemplate<typename Pointer>\nstruct remove_not_null<not_null<Pointer>> {\n using type = typename remove_not_null<Pointer>::type;\n};\n\n\/\/ When |T| is not a reference, |_checked_not_null<T>| is |not_null<T>| if |T|\n\/\/ is not already an instance of |not_null|. It fails otherwise.\n\/\/ |_checked_not_null| is invariant under application of reference or rvalue\n\/\/ reference to its template argument.\ntemplate<typename Pointer>\nusing _checked_not_null = typename std::enable_if<\n !is_instance_of_v<not_null, typename std::remove_reference<Pointer>::type>,\n not_null<typename std::remove_reference<Pointer>::type>>::type;\n\n\/\/ We cannot refer to the template |not_null| inside of |not_null|.\ntemplate<typename Pointer>\ninline constexpr bool is_instance_of_not_null_v =\n is_instance_of_v<not_null, Pointer>;\n\n\/\/ |not_null<Pointer>| is a wrapper for a non-null object of type |Pointer|.\n\/\/ |Pointer| should be a C-style pointer or a smart pointer. |Pointer| must not\n\/\/ be a const, reference, rvalue reference, or |not_null|. |not_null<Pointer>|\n\/\/ is movable and may be left in an invalid state when moved, i.e., its\n\/\/ |pointer_| may become null.\n\/\/ |not_null<not_null<Pointer>>| and |not_null<Pointer>| are equivalent.\n\/\/ This is useful when a |template<typename T>| using a |not_null<T>| is\n\/\/ instanced with an instance of |not_null|.\ntemplate<typename Pointer>\nclass not_null final {\n public:\n \/\/ The type of the pointer being wrapped.\n \/\/ This follows the naming convention from |std::unique_ptr|.\n using pointer = typename remove_not_null<Pointer>::type;\n\n \/\/ Smart pointers define this type.\n using element_type = typename std::pointer_traits<pointer>::element_type;\n\n not_null() = delete;\n\n \/\/ Copy constructor from an other |not_null<Pointer>|.\n not_null(not_null const&) = default;\n \/\/ Copy contructor for implicitly convertible pointers.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value>::type>\n not_null(not_null<OtherPointer> const& other);\n \/\/ Constructor from a nullable pointer, performs a null check.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value &&\n !is_instance_of_not_null_v<pointer>>::type>\n not_null(OtherPointer other); \/\/ NOLINT(runtime\/explicit)\n \/\/ Explicit copy constructor for static_cast'ing.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n !std::is_convertible<OtherPointer, pointer>::value>::type,\n typename = decltype(static_cast<pointer>(\n std::declval<OtherPointer>()))>\n explicit not_null(not_null<OtherPointer> const& other);\n\n \/\/ Move constructor from an other |not_null<Pointer>|. This constructor may\n \/\/ invalidate its argument.\n not_null(not_null&&) = default;\n \/\/ Move contructor for implicitly convertible pointers. This constructor may\n \/\/ invalidate its argument.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value>::type>\n not_null(not_null<OtherPointer>&& other);\n \/\/ Explicit move constructor for static_cast'ing. This constructor may\n \/\/ invalidate its argument.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n !std::is_convertible<OtherPointer, pointer>::value>::type,\n typename = decltype(static_cast<pointer>(\n std::declval<OtherPointer>()))>\n explicit not_null(not_null<OtherPointer>&& other);\n\n \/\/ Copy assigment operators.\n not_null& operator=(not_null const&) = default;\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value>::type>\n not_null& operator=(not_null<OtherPointer> const& other);\n\n \/\/ Move assignment operators.\n \/\/ Implemented as a swap, so the argument remains valid.\n not_null& operator=(not_null&& other);\n \/\/ This operator may invalidate its argument.\n template<typename OtherPointer,\n typename = typename std::enable_if<\n std::is_convertible<OtherPointer, pointer>::value>::type>\n not_null& operator=(not_null<OtherPointer>&& other);\n\n \/\/ Returns |pointer_|, by const reference to avoid a copy if |pointer| is\n \/\/ |unique_ptr|.\n \/\/ If this were to return by |const&|, ambiguities would arise where an rvalue\n \/\/ of type |not_null<pointer>| is given as an argument to a function that has\n \/\/ overloads for both |pointer const&| and |pointer&&|.\n \/\/ Note that the preference for |T&&| over |T const&| for overload resolution\n \/\/ is not relevant here since both go through a user-defined conversion,\n \/\/ see 13.3.3.2.\n \/\/ GCC nevertheless incorrectly prefers |T&&| in that case, while clang and\n \/\/ MSVC recognize the ambiguity.\n \/\/ The |RValue| test gives two examples of this.\n operator pointer const&&() const&;\n\n template<typename OtherPointer,\n typename = std::enable_if_t<\n std::is_convertible<pointer, OtherPointer>::value &&\n !std::is_same<pointer, OtherPointer>::value &&\n !is_instance_of_not_null_v<OtherPointer>>>\n operator OtherPointer() const&;\n\n \/\/ Used to convert a |not_null<unique_ptr<>>| to |unique_ptr<>|.\n operator pointer&&() &&;\n\n template<typename OtherPointer,\n typename = std::enable_if_t<\n std::is_convertible<pointer, OtherPointer>::value &&\n !is_instance_of_not_null_v<OtherPointer>>>\n operator OtherPointer() &&; \/\/ NOLINT(whitespace\/operators)\n\n \/\/ Returns |*pointer_|.\n std::add_lvalue_reference_t<element_type> operator*() const;\n std::add_pointer_t<element_type> operator->() const;\n\n \/\/ When |pointer| has a |get()| member function, this returns\n \/\/ |pointer_.get()|.\n template<typename P = pointer, typename = decltype(std::declval<P>().get())>\n not_null<decltype(std::declval<P>().get())> get() const;\n\n \/\/ When |pointer| has a |release()| member function, this returns\n \/\/ |pointer_.release()|. May invalidate its argument.\n template<typename P = pointer,\n typename = decltype(std::declval<P>().release())>\n not_null<decltype(std::declval<P>().release())> release();\n\n \/\/ When |pointer| has a |reset()| member function, this calls\n \/\/ |pointer_.reset()|.\n template<typename Q,\n typename P = pointer,\n typename = decltype(std::declval<P>().reset())>\n void reset(not_null<Q> ptr);\n\n \/\/ The following operators are redundant for valid |not_null<Pointer>|s with\n \/\/ the implicit conversion to |pointer|, but they should allow some\n \/\/ optimization.\n\n \/\/ Returns |false|.\n bool operator==(std::nullptr_t other) const;\n \/\/ Returns |true|.\n bool operator!=(std::nullptr_t other) const;\n \/\/ Returns |true|.\n operator bool() const;\n\n \/\/ Equality.\n bool operator==(pointer other) const;\n bool operator==(not_null other) const;\n bool operator!=(pointer other) const;\n bool operator!=(not_null other) const;\n\n \/\/ Ordering.\n bool operator<(not_null other) const;\n bool operator<=(not_null other) const;\n bool operator>=(not_null other) const;\n bool operator>(not_null other) const;\n\n private:\n struct unchecked_tag final {};\n\n \/\/ Creates a |not_null<Pointer>| whose |pointer_| equals the given |pointer|,\n \/\/ dawg. The constructor does *not* perform a null check. Callers must\n \/\/ perform one if needed before using it.\n explicit not_null(pointer other, unchecked_tag tag);\n\n pointer pointer_;\n\n static constexpr unchecked_tag unchecked_tag_{};\n\n template<typename OtherPointer>\n friend class not_null;\n\n template<typename P>\n friend _checked_not_null<P> check_not_null(P pointer);\n template<typename T, typename... Args>\n friend not_null<std::shared_ptr<T>> make_not_null_shared(Args&&... args);\n template<typename T, typename... Args>\n friend not_null<std::unique_ptr<T>> make_not_null_unique(Args&&... args);\n};\n\n\/\/ We want only one way of doing things, and we can't make\n\/\/ |not_null<Pointer> const| and |not_null<Pointer const>| etc. equivalent\n\/\/ easily.\n\n\/\/ Use |not_null<Pointer> const| instead.\ntemplate<typename Pointer>\nclass not_null<Pointer const>;\n\/\/ Use |not_null<Pointer>&| instead.\ntemplate<typename Pointer>\nclass not_null<Pointer&>;\n\/\/ Use |not_null<Pointer>&&| instead.\ntemplate<typename Pointer>\nclass not_null<Pointer&&>;\n\n\/\/ Factory taking advantage of template argument deduction. Returns a\n\/\/ |not_null<Pointer>| to |*pointer|. |CHECK|s that |pointer| is not null.\ntemplate<typename Pointer>\n_checked_not_null<Pointer> check_not_null(Pointer pointer);\n\n#if 0\n\/\/ While the above factory would cover this case using the implicit\n\/\/ conversion, this results in a redundant |CHECK|.\n\/\/ This function returns its argument.\ntemplate<typename Pointer>\nnot_null<Pointer> check_not_null(not_null<Pointer> pointer);\n#endif\n\n\/\/ Factory for a |not_null<std::unique_ptr<T>>|, forwards the arguments to the\n\/\/ constructor of T. |make_not_null_unique<T>(args)| is interchangeable with\n\/\/ |check_not_null(make_unique<T>(args))|, but does not perform a |CHECK|, since\n\/\/ the result of |make_unique| is not null.\ntemplate<typename T, typename... Args>\nnot_null<std::unique_ptr<T>> make_not_null_unique(Args&&... args);\n\n\/\/ For logging.\ntemplate<typename Pointer>\nstd::ostream& operator<<(std::ostream& stream,\n not_null<Pointer> const& pointer);\n\ntemplate<typename Result, typename T>\nnot_null<Result> dynamic_cast_not_null(not_null<T*> const pointer);\n\ntemplate<typename Result, typename T>\nnot_null<Result> dynamic_cast_not_null(not_null<std::unique_ptr<T>>&& pointer);\n\n} \/\/ namespace base\n} \/\/ namespace principia\n\n#include \"base\/not_null_body.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Vulkan Samples\n *\n * Copyright (C) 2015-2016 Valve Corporation\n * Copyright (C) 2015-2016 LunarG, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is 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 OR\n * 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n\n#define GLM_FORCE_RADIANS\n\/\/#include \"glm\/glm.hpp\"\n\/\/#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"linmath.h\"\n\n#ifdef _WIN32\n#pragma comment(linker, \"\/subsystem:console\")\n#define WIN32_LEAN_AND_MEAN\n#define VK_USE_PLATFORM_WIN32_KHR\n#define NOMINMAX \/* Don't let Windows define min() or max() *\/\n#define APP_NAME_STR_LEN 80\n#elif defined(__ANDROID__)\n\/\/ Include files for Android\n#include <unistd.h>\n#include <android\/log.h>\n#include \"vulkan_wrapper.h\" \/\/ Include Vulkan_wrapper and dynamically load symbols.\n#else \/\/__ANDROID__\n#define VK_USE_PLATFORM_XCB_KHR\n#include <unistd.h>\n#include \"vulkan\/vk_sdk_platform.h\"\n#endif \/\/ _WIN32\n\n#include <vulkan\/vulkan.h>\n\n\/* Number of descriptor sets needs to be the same at alloc, *\/\n\/* pipeline layout creation, and descriptor set layout creation *\/\n#define NUM_DESCRIPTOR_SETS 1\n\n\/* Number of samples needs to be the same at image creation, *\/\n\/* renderpass creation and pipeline creation. *\/\n#define NUM_SAMPLES VK_SAMPLE_COUNT_1_BIT\n\n\/* Number of viewports and number of scissors have to be the same *\/\n\/* at pipeline creation and in any call to set them dynamically *\/\n\/* They also have to be the same as each other *\/\n#define NUM_VIEWPORTS 1\n#define NUM_SCISSORS NUM_VIEWPORTS\n\n\/* Amount of time, in nanoseconds, to wait for a command buffer to complete *\/\n#define FENCE_TIMEOUT 100000000\n\n#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \\\n { \\\n info.fp##entrypoint = \\\n (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, \"vk\" #entrypoint); \\\n if (info.fp##entrypoint == NULL) { \\\n std::cout << \"vkGetDeviceProcAddr failed to find vk\" #entrypoint; \\\n exit(-1); \\\n } \\\n }\n\n#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \\\n { \\\n info.fp##entrypoint = \\\n (PFN_vk##entrypoint)vkGetDeviceProcAddr(dev, \"vk\" #entrypoint); \\\n if (info.fp##entrypoint == NULL) { \\\n std::cout << \"vkGetDeviceProcAddr failed to find vk\" #entrypoint; \\\n exit(-1); \\\n } \\\n }\n\n#if defined(NDEBUG) && defined(__GNUC__)\n#define U_ASSERT_ONLY __attribute__((unused))\n#else\n#define U_ASSERT_ONLY\n#endif\n\nstd::string get_base_data_dir();\nstd::string get_data_dir(std::string filename);\n\n\/*\n * structure to track all objects related to a texture.\n *\/\nstruct texture_object {\n VkSampler sampler;\n\n VkImage image;\n VkImageLayout imageLayout;\n\n VkDeviceMemory mem;\n VkImageView view;\n int32_t tex_width, tex_height;\n};\n\n\/*\n * Keep each of our swap chain buffers' image, command buffer and view in one\n * spot\n *\/\ntypedef struct _swap_chain_buffers {\n VkImage image;\n VkImageView view;\n} swap_chain_buffer;\n\n\/*\n * A layer can expose extensions, keep track of those\n * extensions here.\n *\/\ntypedef struct {\n VkLayerProperties properties;\n std::vector<VkExtensionProperties> extensions;\n} layer_properties;\n\n\/*\n * Structure for tracking information used \/ created \/ modified\n * by utility functions.\n *\/\nstruct sample_info {\n#ifdef _WIN32\n#define APP_NAME_STR_LEN 80\n HINSTANCE connection; \/\/ hInstance - Windows Instance\n char name[APP_NAME_STR_LEN]; \/\/ Name to put on the window\/icon\n HWND window; \/\/ hWnd - window handle\n#elif defined(__ANDROID__)\n PFN_vkCreateAndroidSurfaceKHR fpCreateAndroidSurfaceKHR;\n#else \/\/ _WIN32\n xcb_connection_t *connection;\n xcb_screen_t *screen;\n xcb_window_t window;\n xcb_intern_atom_reply_t *atom_wm_delete_window;\n#endif \/\/ _WIN32\n VkSurfaceKHR surface;\n bool prepared;\n bool use_staging_buffer;\n bool save_images;\n\n std::vector<const char *> instance_layer_names;\n std::vector<const char *> instance_extension_names;\n std::vector<layer_properties> instance_layer_properties;\n std::vector<VkExtensionProperties> instance_extension_properties;\n VkInstance inst;\n\n std::vector<const char *> device_layer_names;\n std::vector<const char *> device_extension_names;\n std::vector<layer_properties> device_layer_properties;\n std::vector<VkExtensionProperties> device_extension_properties;\n std::vector<VkPhysicalDevice> gpus;\n VkDevice device;\n VkQueue queue;\n uint32_t graphics_queue_family_index;\n VkPhysicalDeviceProperties gpu_props;\n std::vector<VkQueueFamilyProperties> queue_props;\n VkPhysicalDeviceMemoryProperties memory_properties;\n\n VkFramebuffer *framebuffers;\n int width, height;\n VkFormat format;\n\n uint32_t swapchainImageCount;\n VkSwapchainKHR swap_chain;\n std::vector<swap_chain_buffer> buffers;\n VkSemaphore presentCompleteSemaphore;\n\n VkCommandPool cmd_pool;\n\n struct {\n VkFormat format;\n\n VkImage image;\n VkDeviceMemory mem;\n VkImageView view;\n } depth;\n\n std::vector<struct texture_object> textures;\n\n struct {\n VkBuffer buf;\n VkDeviceMemory mem;\n VkDescriptorBufferInfo buffer_info;\n } uniform_data;\n\n struct {\n VkDescriptorImageInfo image_info;\n } texture_data;\n VkDeviceMemory stagingMemory;\n VkImage stagingImage;\n\n struct {\n VkBuffer buf;\n VkDeviceMemory mem;\n VkDescriptorBufferInfo buffer_info;\n } vertex_buffer;\n VkVertexInputBindingDescription vi_binding;\n VkVertexInputAttributeDescription vi_attribs[2];\n\n \/*************\n glm::mat4 Projection;\n glm::mat4 View;\n glm::mat4 Model;\n glm::mat4 Clip;\n glm::mat4 MVP;\n *************\/\n\n mat4x4 Projection;\n mat4x4 View;\n mat4x4 Model;\n mat4x4 Clip;\n mat4x4 MVP;\n\n VkCommandBuffer cmd; \/\/ Buffer for initialization commands\n VkPipelineLayout pipeline_layout;\n std::vector<VkDescriptorSetLayout> desc_layout;\n VkPipelineCache pipelineCache;\n VkRenderPass render_pass;\n VkPipeline pipeline;\n\n VkPipelineShaderStageCreateInfo shaderStages[2];\n\n VkDescriptorPool desc_pool;\n std::vector<VkDescriptorSet> desc_set;\n\n PFN_vkCreateDebugReportCallbackEXT dbgCreateDebugReportCallback;\n PFN_vkDestroyDebugReportCallbackEXT dbgDestroyDebugReportCallback;\n PFN_vkDebugReportMessageEXT dbgBreakCallback;\n std::vector<VkDebugReportCallbackEXT> debug_report_callbacks;\n\n uint32_t current_buffer;\n uint32_t queue_count;\n\n VkViewport viewport;\n VkRect2D scissor;\n};\nvoid process_command_line_args(struct sample_info &info, int argc,\n char *argv[]);\nbool memory_type_from_properties(struct sample_info &info, uint32_t typeBits,\n VkFlags requirements_mask,\n uint32_t *typeIndex);\n\nvoid set_image_layout(struct sample_info &demo, VkImage image,\n VkImageAspectFlags aspectMask,\n VkImageLayout old_image_layout,\n VkImageLayout new_image_layout);\n\nbool read_ppm(char const *const filename, int &width, int &height,\n uint64_t rowPitch, unsigned char *dataPtr);\nvoid write_ppm(struct sample_info &info, const char *basename);\nvoid extract_version(uint32_t version, uint32_t &major, uint32_t &minor,\n uint32_t &patch);\nbool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader,\n std::vector<unsigned int> &spirv);\nvoid init_glslang();\nvoid finalize_glslang();\nvoid wait_seconds(int seconds);\nvoid print_UUID(uint8_t *pipelineCacheUUID);\nstd::string get_file_directory();\n\ntypedef unsigned long long timestamp_t;\ntimestamp_t get_milliseconds();\n\n\/\/ Main entry point of samples\nint sample_main(int argc, char *argv[]);\n\n#ifdef __ANDROID__\n\/\/ Android specific definitions & helpers.\n#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, \"threaded_app\", __VA_ARGS__))\n#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, \"threaded_app\", __VA_ARGS__))\n\/\/ Replace printf to logcat output.\n#define printf(...) __android_log_print(ANDROID_LOG_DEBUG, \"TAG\", __VA_ARGS__);\n\nbool Android_process_command();\nANativeWindow* AndroidGetApplicationWindow();\nFILE* AndroidFopen(const char* fname, const char* mode);\nvoid AndroidGetWindowSize(int32_t *width, int32_t *height);\nbool AndroidLoadFile(const char* filePath, std::string *data);\n\n#ifndef VK_API_VERSION_1_0\n\/\/ On Android, NDK would include slightly older version of headers that is missing the definition.\n#define VK_API_VERSION_1_0 VK_API_VERSION\n#endif\n\n#endif\n<commit_msg>Update util.hpp<commit_after>\/*\n * Vulkan Samples\n *\n * Copyright (C) 2015-2016 Valve Corporation\n * Copyright (C) 2015-2016 LunarG, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is 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 OR\n * 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n\n#include \"linmath.h\"\n\n#ifdef _WIN32\n#pragma comment(linker, \"\/subsystem:console\")\n#define WIN32_LEAN_AND_MEAN\n#define VK_USE_PLATFORM_WIN32_KHR\n#define NOMINMAX \/* Don't let Windows define min() or max() *\/\n#define APP_NAME_STR_LEN 80\n#elif defined(__ANDROID__)\n\/\/ Include files for Android\n#include <unistd.h>\n#include <android\/log.h>\n#include \"vulkan_wrapper.h\" \/\/ Include Vulkan_wrapper and dynamically load symbols.\n#else \/\/__ANDROID__\n#define VK_USE_PLATFORM_XCB_KHR\n#include <unistd.h>\n#include \"vulkan\/vk_sdk_platform.h\"\n#endif \/\/ _WIN32\n\n#include <vulkan\/vulkan.h>\n\n\/* Number of descriptor sets needs to be the same at alloc, *\/\n\/* pipeline layout creation, and descriptor set layout creation *\/\n#define NUM_DESCRIPTOR_SETS 1\n\n\/* Number of samples needs to be the same at image creation, *\/\n\/* renderpass creation and pipeline creation. *\/\n#define NUM_SAMPLES VK_SAMPLE_COUNT_1_BIT\n\n\/* Number of viewports and number of scissors have to be the same *\/\n\/* at pipeline creation and in any call to set them dynamically *\/\n\/* They also have to be the same as each other *\/\n#define NUM_VIEWPORTS 1\n#define NUM_SCISSORS NUM_VIEWPORTS\n\n\/* Amount of time, in nanoseconds, to wait for a command buffer to complete *\/\n#define FENCE_TIMEOUT 100000000\n\n#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \\\n { \\\n info.fp##entrypoint = \\\n (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, \"vk\" #entrypoint); \\\n if (info.fp##entrypoint == NULL) { \\\n std::cout << \"vkGetDeviceProcAddr failed to find vk\" #entrypoint; \\\n exit(-1); \\\n } \\\n }\n\n#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \\\n { \\\n info.fp##entrypoint = \\\n (PFN_vk##entrypoint)vkGetDeviceProcAddr(dev, \"vk\" #entrypoint); \\\n if (info.fp##entrypoint == NULL) { \\\n std::cout << \"vkGetDeviceProcAddr failed to find vk\" #entrypoint; \\\n exit(-1); \\\n } \\\n }\n\n#if defined(NDEBUG) && defined(__GNUC__)\n#define U_ASSERT_ONLY __attribute__((unused))\n#else\n#define U_ASSERT_ONLY\n#endif\n\nstd::string get_base_data_dir();\nstd::string get_data_dir(std::string filename);\n\n\/*\n * structure to track all objects related to a texture.\n *\/\nstruct texture_object {\n VkSampler sampler;\n\n VkImage image;\n VkImageLayout imageLayout;\n\n VkDeviceMemory mem;\n VkImageView view;\n int32_t tex_width, tex_height;\n};\n\n\/*\n * Keep each of our swap chain buffers' image, command buffer and view in one\n * spot\n *\/\ntypedef struct _swap_chain_buffers {\n VkImage image;\n VkImageView view;\n} swap_chain_buffer;\n\n\/*\n * A layer can expose extensions, keep track of those\n * extensions here.\n *\/\ntypedef struct {\n VkLayerProperties properties;\n std::vector<VkExtensionProperties> extensions;\n} layer_properties;\n\n\/*\n * Structure for tracking information used \/ created \/ modified\n * by utility functions.\n *\/\nstruct sample_info {\n#ifdef _WIN32\n#define APP_NAME_STR_LEN 80\n HINSTANCE connection; \/\/ hInstance - Windows Instance\n char name[APP_NAME_STR_LEN]; \/\/ Name to put on the window\/icon\n HWND window; \/\/ hWnd - window handle\n#elif defined(__ANDROID__)\n PFN_vkCreateAndroidSurfaceKHR fpCreateAndroidSurfaceKHR;\n#else \/\/ _WIN32\n xcb_connection_t *connection;\n xcb_screen_t *screen;\n xcb_window_t window;\n xcb_intern_atom_reply_t *atom_wm_delete_window;\n#endif \/\/ _WIN32\n VkSurfaceKHR surface;\n bool prepared;\n bool use_staging_buffer;\n bool save_images;\n\n std::vector<const char *> instance_layer_names;\n std::vector<const char *> instance_extension_names;\n std::vector<layer_properties> instance_layer_properties;\n std::vector<VkExtensionProperties> instance_extension_properties;\n VkInstance inst;\n\n std::vector<const char *> device_layer_names;\n std::vector<const char *> device_extension_names;\n std::vector<layer_properties> device_layer_properties;\n std::vector<VkExtensionProperties> device_extension_properties;\n std::vector<VkPhysicalDevice> gpus;\n VkDevice device;\n VkQueue queue;\n uint32_t graphics_queue_family_index;\n VkPhysicalDeviceProperties gpu_props;\n std::vector<VkQueueFamilyProperties> queue_props;\n VkPhysicalDeviceMemoryProperties memory_properties;\n\n VkFramebuffer *framebuffers;\n int width, height;\n VkFormat format;\n\n uint32_t swapchainImageCount;\n VkSwapchainKHR swap_chain;\n std::vector<swap_chain_buffer> buffers;\n VkSemaphore presentCompleteSemaphore;\n\n VkCommandPool cmd_pool;\n\n struct {\n VkFormat format;\n\n VkImage image;\n VkDeviceMemory mem;\n VkImageView view;\n } depth;\n\n std::vector<struct texture_object> textures;\n\n struct {\n VkBuffer buf;\n VkDeviceMemory mem;\n VkDescriptorBufferInfo buffer_info;\n } uniform_data;\n\n struct {\n VkDescriptorImageInfo image_info;\n } texture_data;\n VkDeviceMemory stagingMemory;\n VkImage stagingImage;\n\n struct {\n VkBuffer buf;\n VkDeviceMemory mem;\n VkDescriptorBufferInfo buffer_info;\n } vertex_buffer;\n VkVertexInputBindingDescription vi_binding;\n VkVertexInputAttributeDescription vi_attribs[2];\n\n \/*************\n glm::mat4 Projection;\n glm::mat4 View;\n glm::mat4 Model;\n glm::mat4 Clip;\n glm::mat4 MVP;\n *************\/\n\n mat4x4 Projection;\n mat4x4 View;\n mat4x4 Model;\n mat4x4 Clip;\n mat4x4 MVP;\n\n VkCommandBuffer cmd; \/\/ Buffer for initialization commands\n VkPipelineLayout pipeline_layout;\n std::vector<VkDescriptorSetLayout> desc_layout;\n VkPipelineCache pipelineCache;\n VkRenderPass render_pass;\n VkPipeline pipeline;\n\n VkPipelineShaderStageCreateInfo shaderStages[2];\n\n VkDescriptorPool desc_pool;\n std::vector<VkDescriptorSet> desc_set;\n\n PFN_vkCreateDebugReportCallbackEXT dbgCreateDebugReportCallback;\n PFN_vkDestroyDebugReportCallbackEXT dbgDestroyDebugReportCallback;\n PFN_vkDebugReportMessageEXT dbgBreakCallback;\n std::vector<VkDebugReportCallbackEXT> debug_report_callbacks;\n\n uint32_t current_buffer;\n uint32_t queue_count;\n\n VkViewport viewport;\n VkRect2D scissor;\n};\nvoid process_command_line_args(struct sample_info &info, int argc,\n char *argv[]);\nbool memory_type_from_properties(struct sample_info &info, uint32_t typeBits,\n VkFlags requirements_mask,\n uint32_t *typeIndex);\n\nvoid set_image_layout(struct sample_info &demo, VkImage image,\n VkImageAspectFlags aspectMask,\n VkImageLayout old_image_layout,\n VkImageLayout new_image_layout);\n\nbool read_ppm(char const *const filename, int &width, int &height,\n uint64_t rowPitch, unsigned char *dataPtr);\nvoid write_ppm(struct sample_info &info, const char *basename);\nvoid extract_version(uint32_t version, uint32_t &major, uint32_t &minor,\n uint32_t &patch);\nbool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader,\n std::vector<unsigned int> &spirv);\nvoid init_glslang();\nvoid finalize_glslang();\nvoid wait_seconds(int seconds);\nvoid print_UUID(uint8_t *pipelineCacheUUID);\nstd::string get_file_directory();\n\ntypedef unsigned long long timestamp_t;\ntimestamp_t get_milliseconds();\n\n\/\/ Main entry point of samples\nint sample_main(int argc, char *argv[]);\n\n#ifdef __ANDROID__\n\/\/ Android specific definitions & helpers.\n#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, \"threaded_app\", __VA_ARGS__))\n#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, \"threaded_app\", __VA_ARGS__))\n\/\/ Replace printf to logcat output.\n#define printf(...) __android_log_print(ANDROID_LOG_DEBUG, \"TAG\", __VA_ARGS__);\n\nbool Android_process_command();\nANativeWindow* AndroidGetApplicationWindow();\nFILE* AndroidFopen(const char* fname, const char* mode);\nvoid AndroidGetWindowSize(int32_t *width, int32_t *height);\nbool AndroidLoadFile(const char* filePath, std::string *data);\n\n#ifndef VK_API_VERSION_1_0\n\/\/ On Android, NDK would include slightly older version of headers that is missing the definition.\n#define VK_API_VERSION_1_0 VK_API_VERSION\n#endif\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <QPushButton>\n#include <QDebug>\n#include <QContextMenuEvent>\n#include <QMenu>\n#include <QHeaderView>\n#include \"..\/model\/modadapter.h\"\n#include \"astreewidget.h\"\n#include \"astreeitem.h\"\n\nAsTreeWidget::AsTreeWidget(QWidget* parent): QTreeWidget(parent)\n{\n setContextMenuPolicy(Qt::CustomContextMenu);\n connect(this, &AsTreeWidget::customContextMenuRequested, this, &AsTreeWidget::showContextMenu);\n header()->setStretchLastSection(false);\n setExpandsOnDoubleClick(false);\n}\n\nvoid AsTreeWidget::update()\n{\n for (AsTreeItem* treeItem : items)\n {\n treeItem->update();\n }\n}\n\nvoid AsTreeWidget::showContextMenu(const QPoint& point)\n{\n AsTreeItem* item = (AsTreeItem*) itemAt(point);\n if (item != nullptr)\n {\n QMenu menu(this);\n ISyncItem* syncItem = item->syncItem();\n IRepository* repository = dynamic_cast<IRepository*>(syncItem);\n if(repository != nullptr)\n {\n menu.addAction(\"Force join\", [=] ()\n {\n repository->join();\n });\n menu.addAction(\"Force start\", [=] ()\n {\n repository->start();\n });\n menu.addAction(\"Recheck\", [=] ()\n {\n syncItem->check();\n });\n }\n else\n {\n const ModAdapter* modAdapter = dynamic_cast<ModAdapter*>(syncItem);\n menu.addAction(\"Recheck\", [=] () {\n modAdapter->forceCheck();\n });\n }\n menu.exec(QCursor::pos());\n }\n}\n\nvoid AsTreeWidget::setRepositories(QList<IRepository*> repositories)\n{\n clear();\n items.clear();\n addRepositories(repositories);\n header()->resizeSections(QHeaderView::ResizeToContents);\n header()->resizeSection(2, header()->sectionSize(2) + 50); \/\/Status\n header()->resizeSection(4, header()->sectionSize(4) + 25); \/\/Size\n \/\/Hack to make name column take remaining space\n header()->setSectionResizeMode(1, QHeaderView::Stretch);\n header()->sectionSize(1); \/\/This is required!\n header()->setSectionResizeMode(1, QHeaderView::Interactive);\n}\n\nvoid AsTreeWidget::addRepositories(QList<IRepository*> repositories)\n{\n for (IRepository* repo : repositories)\n {\n QCheckBox* repoCheckBox = new QCheckBox(this);\n\n QPushButton* startButton = new QPushButton(\"Start Game\", this);\n QPushButton* joinButton = new QPushButton(\"Join Server\", this);\n AsTreeItem* repoItem = new AsTreeItem(this, repo, repoCheckBox, startButton, joinButton);\n addTopLevelItem(repoItem);\n\n connect(startButton, &QPushButton::pressed, [=] () {\n repo->start();\n });\n connect(joinButton, &QPushButton::pressed, [=] () {\n repo->join();\n });\n connect(this, &AsTreeWidget::itemClicked, [=] (QTreeWidgetItem* item, int) {\n if (item->isExpanded())\n {\n collapseItem(item);\n return;\n }\n expandItem(item);\n });\n\n setItemWidget(repoItem, 0, repoCheckBox);\n setItemWidget(repoItem, 5, startButton);\n setItemWidget(repoItem, 6, joinButton);\n items.append(repoItem);\n for (ISyncItem* mod : repo->uiMods())\n {\n QCheckBox* modCheckBox = new QCheckBox(this);\n AsTreeItem* modItem = new AsTreeItem(repoItem, mod, modCheckBox);\n setItemWidget(modItem, 0, modCheckBox);\n repoItem->addChild(modItem);\n items.append(modItem);\n }\n }\n}\n<commit_msg>Fixed expand bug<commit_after>#include <QPushButton>\n#include <QDebug>\n#include <QContextMenuEvent>\n#include <QMenu>\n#include <QHeaderView>\n#include \"..\/model\/modadapter.h\"\n#include \"astreewidget.h\"\n#include \"astreeitem.h\"\n\nAsTreeWidget::AsTreeWidget(QWidget* parent): QTreeWidget(parent)\n{\n setContextMenuPolicy(Qt::CustomContextMenu);\n setExpandsOnDoubleClick(false);\n header()->setStretchLastSection(false);\n\n connect(this, &AsTreeWidget::customContextMenuRequested, this, &AsTreeWidget::showContextMenu);\n connect(this, &AsTreeWidget::itemClicked, [=] (QTreeWidgetItem* item, int) {\n if (item->isExpanded())\n {\n collapseItem(item);\n return;\n }\n expandItem(item);\n });\n}\n\nvoid AsTreeWidget::update()\n{\n for (AsTreeItem* treeItem : items)\n {\n treeItem->update();\n }\n}\n\nvoid AsTreeWidget::showContextMenu(const QPoint& point)\n{\n AsTreeItem* item = (AsTreeItem*) itemAt(point);\n if (item != nullptr)\n {\n QMenu menu(this);\n ISyncItem* syncItem = item->syncItem();\n IRepository* repository = dynamic_cast<IRepository*>(syncItem);\n if(repository != nullptr)\n {\n menu.addAction(\"Force join\", [=] ()\n {\n repository->join();\n });\n menu.addAction(\"Force start\", [=] ()\n {\n repository->start();\n });\n menu.addAction(\"Recheck\", [=] ()\n {\n syncItem->check();\n });\n }\n else\n {\n const ModAdapter* modAdapter = dynamic_cast<ModAdapter*>(syncItem);\n menu.addAction(\"Recheck\", [=] () {\n modAdapter->forceCheck();\n });\n }\n menu.exec(QCursor::pos());\n }\n}\n\nvoid AsTreeWidget::setRepositories(QList<IRepository*> repositories)\n{\n clear();\n items.clear();\n addRepositories(repositories);\n header()->resizeSections(QHeaderView::ResizeToContents);\n header()->resizeSection(2, header()->sectionSize(2) + 50); \/\/Status\n header()->resizeSection(4, header()->sectionSize(4) + 25); \/\/Size\n \/\/Hack to make name column take remaining space\n header()->setSectionResizeMode(1, QHeaderView::Stretch);\n header()->sectionSize(1); \/\/This is required!\n header()->setSectionResizeMode(1, QHeaderView::Interactive);\n}\n\nvoid AsTreeWidget::addRepositories(QList<IRepository*> repositories)\n{\n for (IRepository* repo : repositories)\n {\n QCheckBox* repoCheckBox = new QCheckBox(this);\n\n QPushButton* startButton = new QPushButton(\"Start Game\", this);\n QPushButton* joinButton = new QPushButton(\"Join Server\", this);\n AsTreeItem* repoItem = new AsTreeItem(this, repo, repoCheckBox, startButton, joinButton);\n addTopLevelItem(repoItem);\n\n connect(startButton, &QPushButton::pressed, [=] () {\n repo->start();\n });\n connect(joinButton, &QPushButton::pressed, [=] () {\n repo->join();\n });\n\n setItemWidget(repoItem, 0, repoCheckBox);\n setItemWidget(repoItem, 5, startButton);\n setItemWidget(repoItem, 6, joinButton);\n items.append(repoItem);\n for (ISyncItem* mod : repo->uiMods())\n {\n QCheckBox* modCheckBox = new QCheckBox(this);\n AsTreeItem* modItem = new AsTreeItem(repoItem, mod, modCheckBox);\n setItemWidget(modItem, 0, modCheckBox);\n repoItem->addChild(modItem);\n items.append(modItem);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXYZMolReader2.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkXYZMolReader2.h\"\n\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n\n#include \"vtkMolecule.h\"\n#include \"vtkPeriodicTable.h\"\n\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n\n#include <math.h>\n#include <string.h>\n\n#include <sstream>\n\/\/----------------------------------------------------------------------------\nvtkStandardNewMacro(vtkXYZMolReader2);\n\n\/\/----------------------------------------------------------------------------\nvtkXYZMolReader2::vtkXYZMolReader2()\n : FileName(NULL)\n{\n this->SetNumberOfInputPorts(0);\n this->NumberOfTimeSteps = 0;\n this->NumberOfAtoms = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkXYZMolReader2::~vtkXYZMolReader2()\n{\n this->SetFileName(NULL);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMolecule *vtkXYZMolReader2::GetOutput()\n{\n return vtkMolecule::SafeDownCast(this->GetOutputDataObject(0));\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXYZMolReader2::SetOutput(vtkMolecule *output)\n{\n this->GetExecutive()->SetOutputData(0, output);\n}\n\nint vtkXYZMolReader2::RequestInformation(\n vtkInformation *vtkNotUsed(request),\n vtkInformationVector **vtkNotUsed(inputVector),\n vtkInformationVector *outputVector)\n{\n vtkInformation* outInfo = outputVector->GetInformationObject(0);\n\n if (!this->FileName)\n {\n return 0;\n }\n\n ifstream file_in(this->FileName);\n\n if(!file_in.is_open())\n {\n vtkErrorMacro (\"vtkXYZMolReader2 error opening file: \" << this->FileName);\n return 0;\n }\n\n while(file_in)\n {\n int natoms;\n istream::pos_type current_pos = file_in.tellg();\n std::string title;\n getline(file_in, title); \/\/ first title line\n std::istringstream tmp(title);\n tmp >> natoms;\n if (!file_in)\n break; \/\/ reached after last timestep\n\n file_positions.push_back(current_pos);\n\n if (!this->NumberOfAtoms) \/\/ first read\n {\n this->NumberOfAtoms = natoms;\n }\n else\n {\n\/\/ do a consistency check with previous step. Assume there should be same # of atoms\n if(this->NumberOfAtoms != natoms)\n vtkWarningMacro (\"XYZMolReader2 has different number of atoms at each timestep \"\n << this->NumberOfAtoms << \" \" << natoms);\n }\n\n getline(file_in, title); \/\/ second title line\n if(!title.empty())\n {\n \/\/ second title line may have a time index, time value and E?\n \/\/ search now for an optional \"time = value\" field and assign it if found\n std::size_t found = title.find(std::string(\"time\"));\n if (found!=std::string::npos)\n {\n std::istringstream tmp(&title[found+6]);\n double timeValue;\n tmp >> timeValue;\n this->TimeSteps.push_back(timeValue);\n }\n }\n else\n {\n this->TimeSteps.push_back(this->NumberOfTimeSteps);\n }\n\n this->NumberOfTimeSteps++;\n for(int i=0; i < natoms; i++)\n {\n getline(file_in, title); \/\/ for each atom a line with symbol, x, y, z\n }\n }\n file_in.close();\n\n outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),\n &this->TimeSteps[0], this->NumberOfTimeSteps);\n double timeRange[2];\n timeRange[0] = this->TimeSteps[0];\n timeRange[1] = this->TimeSteps[this->NumberOfTimeSteps - 1];\n outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);\n return 1;\n}\n\nint vtkXYZMolReader2::RequestData(\n vtkInformation *,\n vtkInformationVector **,\n vtkInformationVector *outputVector)\n{\n vtkInformation* outInfo = outputVector->GetInformationObject(0);\n vtkMolecule *output = vtkMolecule::SafeDownCast\n (vtkDataObject::GetData(outputVector));\n\n if (!output)\n {\n vtkErrorMacro(<<\"vtkXYZMolReader2 does not have a vtkMolecule \"\n \"as output.\");\n return 1;\n }\n\n if (!this->FileName)\n {\n return 0;\n }\n\n ifstream file_in(this->FileName);\n\n if(!file_in.is_open())\n {\n vtkErrorMacro (\"vtkXYZMolReader2 error opening file: \" << this->FileName);\n return 0;\n }\n\n int timestep=0;\n std::vector<double>::iterator it = this->TimeSteps.begin();\n\n if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))\n {\n \/\/ Get the requested time step.\n double requestedTimeStep =\n outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());\n\n \/\/find the timestep with the closest value\n if(requestedTimeStep < *it)\n {\n requestedTimeStep = *it;\n vtkWarningMacro (\"XYZMolReader2 using its first timestep value of \"\n << requestedTimeStep);\n }\n for (it = this->TimeSteps.begin(); it < this->TimeSteps.end(); it++, timestep++)\n {\n if ((*it > requestedTimeStep))\n break;\n }\n\n if(it != this->TimeSteps.end())\n {\n it--;\n timestep--;\n if(fabs(*it - requestedTimeStep) > fabs(*(it+1) - requestedTimeStep))\n {\n \/\/ closer to next timestep value\n timestep++;\n it++;\n }\n }\n else\n {\n it--; timestep--;\n }\n }\n else\n {\n timestep = 0;\n }\n\n file_in.seekg(file_positions[timestep]);\n int nbAtoms;\n std::string title;\n getline(file_in, title); \/\/ first title line\n std::istringstream tmp(title);\n tmp >> nbAtoms;\n\n if(nbAtoms != this->NumberOfAtoms)\n {\n vtkErrorMacro (\"vtkXYZMolReader2 error reading file: \" << this->FileName\n << \" Premature EOF while reading molecule.\");\n file_in.close();\n return 0;\n }\n\n getline(file_in, title); \/\/ second title line\n\n\/\/ construct vtkMolecule\n output->Initialize();\n\n vtkPeriodicTable *pT = vtkPeriodicTable::New();\n for(int i = 0; i < this->NumberOfAtoms; i++)\n {\n char atomType[16];\n float x, y, z;\n getline(file_in, title); \/\/ an atom's position line\n std::istringstream tmp(title);\n tmp >> atomType >> x >> y >> z;\n if (!tmp) \/\/ checking we are at end of line\n {\n vtkErrorMacro (\"vtkXYZMolReader2 error reading file: \" << this->FileName\n << \" Problem reading atoms' positions.\");\n file_in.close();\n return 0;\n }\n output->AppendAtom(pT->GetAtomicNumber(atomType), x, y, z);\n }\n pT->Delete();\n file_in.close();\n\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXYZMolReader2::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n os << indent << \"Number of Atoms: \" << this->NumberOfAtoms << endl;\n os << indent << \"Number of TimeSteps: \" << this->NumberOfTimeSteps;\n}\n<commit_msg>removed shadow var and clean up the scanning of atoms<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXYZMolReader2.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkXYZMolReader2.h\"\n\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n\n#include \"vtkMolecule.h\"\n#include \"vtkPeriodicTable.h\"\n\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n\n#include <math.h>\n#include <string.h>\n\n#include <sstream>\n\/\/----------------------------------------------------------------------------\nvtkStandardNewMacro(vtkXYZMolReader2);\n\n\/\/----------------------------------------------------------------------------\nvtkXYZMolReader2::vtkXYZMolReader2()\n : FileName(NULL)\n{\n this->SetNumberOfInputPorts(0);\n this->NumberOfTimeSteps = 0;\n this->NumberOfAtoms = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkXYZMolReader2::~vtkXYZMolReader2()\n{\n this->SetFileName(NULL);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMolecule *vtkXYZMolReader2::GetOutput()\n{\n return vtkMolecule::SafeDownCast(this->GetOutputDataObject(0));\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXYZMolReader2::SetOutput(vtkMolecule *output)\n{\n this->GetExecutive()->SetOutputData(0, output);\n}\n\nint vtkXYZMolReader2::RequestInformation(\n vtkInformation *vtkNotUsed(request),\n vtkInformationVector **vtkNotUsed(inputVector),\n vtkInformationVector *outputVector)\n{\n vtkInformation* outInfo = outputVector->GetInformationObject(0);\n\n if (!this->FileName)\n {\n return 0;\n }\n\n ifstream file_in(this->FileName);\n\n if(!file_in.is_open())\n {\n vtkErrorMacro (\"vtkXYZMolReader2 error opening file: \" << this->FileName);\n return 0;\n }\n\n while(file_in)\n {\n int natoms;\n istream::pos_type current_pos = file_in.tellg();\n file_in >> natoms;\n file_in.get(); \/\/ end of line char\n if (!file_in)\n break; \/\/ reached after last timestep\n\n file_positions.push_back(current_pos);\n\n if (!this->NumberOfAtoms) \/\/ first read\n {\n this->NumberOfAtoms = natoms;\n }\n else\n {\n\/\/ do a consistency check with previous step. Assume there should be same # of atoms\n if(this->NumberOfAtoms != natoms)\n vtkWarningMacro (\"XYZMolReader2 has different number of atoms at each timestep \"\n << this->NumberOfAtoms << \" \" << natoms);\n }\n std::string title;\n getline(file_in, title); \/\/ second title line\n if(!title.empty())\n {\n \/\/ second title line may have a time index, time value and E?\n \/\/ search now for an optional \"time = value\" field and assign it if found\n std::size_t found = title.find(std::string(\"time\"));\n if (found!=std::string::npos)\n {\n std::istringstream tmp(&title[found+6]);\n double timeValue;\n tmp >> timeValue;\n this->TimeSteps.push_back(timeValue);\n }\n }\n else\n {\n this->TimeSteps.push_back(this->NumberOfTimeSteps);\n }\n\n this->NumberOfTimeSteps++;\n for(int i=0; i < natoms; i++)\n {\n getline(file_in, title); \/\/ for each atom a line with symbol, x, y, z\n }\n }\n file_in.close();\n\n outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),\n &this->TimeSteps[0], this->NumberOfTimeSteps);\n double timeRange[2];\n timeRange[0] = this->TimeSteps[0];\n timeRange[1] = this->TimeSteps[this->NumberOfTimeSteps - 1];\n outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);\n return 1;\n}\n\nint vtkXYZMolReader2::RequestData(\n vtkInformation *,\n vtkInformationVector **,\n vtkInformationVector *outputVector)\n{\n vtkInformation* outInfo = outputVector->GetInformationObject(0);\n vtkMolecule *output = vtkMolecule::SafeDownCast\n (vtkDataObject::GetData(outputVector));\n\n if (!output)\n {\n vtkErrorMacro(<<\"vtkXYZMolReader2 does not have a vtkMolecule \"\n \"as output.\");\n return 1;\n }\n\n if (!this->FileName)\n {\n return 0;\n }\n\n ifstream file_in(this->FileName);\n\n if(!file_in.is_open())\n {\n vtkErrorMacro (\"vtkXYZMolReader2 error opening file: \" << this->FileName);\n return 0;\n }\n\n int timestep=0;\n std::vector<double>::iterator it = this->TimeSteps.begin();\n\n if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))\n {\n \/\/ Get the requested time step.\n double requestedTimeStep =\n outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());\n\n \/\/find the timestep with the closest value\n if(requestedTimeStep < *it)\n {\n requestedTimeStep = *it;\n vtkWarningMacro (\"XYZMolReader2 using its first timestep value of \"\n << requestedTimeStep);\n }\n for (it = this->TimeSteps.begin(); it < this->TimeSteps.end(); it++, timestep++)\n {\n if ((*it > requestedTimeStep))\n break;\n }\n\n if(it != this->TimeSteps.end())\n {\n it--;\n timestep--;\n if(fabs(*it - requestedTimeStep) > fabs(*(it+1) - requestedTimeStep))\n {\n \/\/ closer to next timestep value\n timestep++;\n it++;\n }\n }\n else\n {\n it--; timestep--;\n }\n }\n else\n {\n timestep = 0;\n }\n\n file_in.seekg(file_positions[timestep]);\n int nbAtoms;\n\n file_in >> nbAtoms;\n file_in.get(); \/\/ end of line char\n\n if(nbAtoms != this->NumberOfAtoms)\n {\n vtkErrorMacro (\"vtkXYZMolReader2 error reading file: \" << this->FileName\n << \" Premature EOF while reading molecule.\");\n file_in.close();\n return 0;\n }\n std::string title;\n getline(file_in, title); \/\/ second title line\n\n\/\/ construct vtkMolecule\n output->Initialize();\n\n vtkPeriodicTable *pT = vtkPeriodicTable::New();\n for(int i = 0; i < this->NumberOfAtoms; i++)\n {\n char atomType[16];\n float x, y, z;\n file_in >> atomType >> x >> y >> z;\n if (file_in.fail()) \/\/ checking we are at end of line\n {\n vtkErrorMacro (\"vtkXYZMolReader2 error reading file: \" << this->FileName\n << \" Problem reading atoms' positions.\");\n file_in.close();\n return 0;\n }\n output->AppendAtom(pT->GetAtomicNumber(atomType), x, y, z);\n }\n pT->Delete();\n file_in.close();\n\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXYZMolReader2::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n os << indent << \"Number of Atoms: \" << this->NumberOfAtoms << endl;\n os << indent << \"Number of TimeSteps: \" << this->NumberOfTimeSteps;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 1.2.0, packaged on September 2009.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib 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 GLC-lib 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 GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n*****************************************************************************\/\n\n\/\/! \\file glc_factory.cpp implementation of the GLC_Factory class.\n\n#include \"glc_factory.h\"\n#include \"io\/glc_objtoworld.h\"\n#include \"io\/glc_stltoworld.h\"\n#include \"io\/glc_offtoworld.h\"\n#include \"io\/glc_3dstoworld.h\"\n#include \"io\/glc_3dxmltoworld.h\"\n#include \"io\/glc_colladatoworld.h\"\n\n#include \"viewport\/glc_panmover.h\"\n#include \"viewport\/glc_zoommover.h\"\n#include \"viewport\/glc_settargetmover.h\"\n#include \"viewport\/glc_trackballmover.h\"\n#include \"viewport\/glc_turntablemover.h\"\n#include \"viewport\/glc_repcrossmover.h\"\n#include \"viewport\/glc_reptrackballmover.h\"\n\n\/\/ init static member\nGLC_Factory* GLC_Factory::m_pFactory= NULL;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ static method\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Return the unique instance of the factory\nGLC_Factory* GLC_Factory::instance(const QGLContext *pContext)\n{\n\tif(m_pFactory == NULL)\n\t{\n\t\tm_pFactory= new GLC_Factory(pContext);\n\t}\n\treturn m_pFactory;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constructor destructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Protected constructor\nGLC_Factory::GLC_Factory(const QGLContext *pContext)\n: m_pQGLContext(const_cast<QGLContext*>(pContext))\n{\n\n}\n\n\/\/ Destructor\nGLC_Factory::~GLC_Factory()\n{\n\tm_pFactory= NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Create a GLC_Point\nGLC_3DRep GLC_Factory::createPoint(const GLC_Point3d &coord) const\n{\n\tGLC_3DRep newPoint(new GLC_Point(coord));\n\treturn newPoint;\n}\n\/\/ Create a GLC_Point\nGLC_3DRep GLC_Factory::createPoint(double x, double y, double z) const\n{\n\tGLC_3DRep newPoint(new GLC_Point(x, y, z));\n\treturn newPoint;\n}\n\n\/\/ Create a GLC_PointSprite\nGLC_3DRep GLC_Factory::createPointSprite(float size, GLC_Material* pMaterial) const\n{\n\tGLC_3DRep newPoint(new GLC_PointSprite(size, pMaterial));\n\treturn newPoint;\n}\n\n\/\/ Create a GLC_Line\nGLC_3DRep GLC_Factory::createLine(const GLC_Point3d& point1, const GLC_Point3d& point2) const\n{\n\tGLC_3DRep newPoint(new GLC_Line(point1, point2));\n\treturn newPoint;\n}\n\n\/\/ Create a GLC_Circle\nGLC_3DRep GLC_Factory::createCircle(double radius, double angle) const\n{\n\tGLC_3DRep newCircle(new GLC_Circle(radius, angle));\n\treturn newCircle;\n}\n\/\/ Create a GLC_Box\nGLC_3DRep GLC_Factory::createBox(double lx, double ly, double lz) const\n{\n\n\tGLC_3DRep newBox(new GLC_Box(lx, ly, lz));\n\treturn newBox;\n}\n\n\/\/ Create a GLC_Box\nGLC_3DViewInstance GLC_Factory::createBox(const GLC_BoundingBox& boundingBox) const\n{\n\tconst double lx= boundingBox.upperCorner().X() - boundingBox.lowerCorner().X();\n\tconst double ly= boundingBox.upperCorner().Y() - boundingBox.lowerCorner().Y();\n\tconst double lz= boundingBox.upperCorner().Z() - boundingBox.lowerCorner().Z();\n\tGLC_Box* pBox= new GLC_Box(lx, ly, lz);\n\tGLC_3DViewInstance newBox(pBox);\n\tnewBox.translate(boundingBox.center().X(), boundingBox.center().Y()\n\t\t\t\t\t, boundingBox.center().Z());\n\treturn newBox;\n}\n\n\/\/ Create a GLC_Cylinder\nGLC_3DRep GLC_Factory::createCylinder(double radius, double length) const\n{\n\n\tGLC_3DRep newCylinder(new GLC_Cylinder(radius, length));\n\treturn newCylinder;\n}\n\n\/\/ Create a GLC_Rectangle\nGLC_3DRep GLC_Factory::createRectangle(double l1, double l2)\n{\n\tGLC_3DRep newRectangle(new GLC_Rectangle(l1, l2));\n\treturn newRectangle;\n}\n\n\/\/ Create a GLC_World* with a QFile\nGLC_World* GLC_Factory::createWorld(QFile &file, QStringList* pAttachedFileName) const\n{\n\tGLC_World* pWorld= NULL;\n\tif (QFileInfo(file).suffix().toLower() == \"obj\")\n\t{\n\t\tGLC_ObjToWorld objToWorld(m_pQGLContext);\n\t\tconnect(&objToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= objToWorld.CreateWorldFromObj(file);\n\t\tif (NULL != pAttachedFileName)\n\t\t{\n\t\t\t(*pAttachedFileName)= objToWorld.listOfAttachedFileName();\n\t\t}\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"stl\")\n\t{\n\t\tGLC_StlToWorld stlToWorld;\n\t\tconnect(&stlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= stlToWorld.CreateWorldFromStl(file);\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"off\")\n\t{\n\t\tGLC_OffToWorld offToWorld;\n\t\tconnect(&offToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= offToWorld.CreateWorldFromOff(file);\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"3ds\")\n\t{\n\t\tGLC_3dsToWorld studioToWorld(m_pQGLContext);\n\t\tconnect(&studioToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= studioToWorld.CreateWorldFrom3ds(file);\n\t\tif (NULL != pAttachedFileName)\n\t\t{\n\t\t\t(*pAttachedFileName)= studioToWorld.listOfAttachedFileName();\n\t\t}\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"3dxml\")\n\t{\n\t\tGLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);\n\t\tconnect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= d3dxmlToWorld.createWorldFrom3dxml(file, false);\n\t\tif (NULL != pAttachedFileName)\n\t\t{\n\t\t\t(*pAttachedFileName)= d3dxmlToWorld.listOfAttachedFileName();\n\t\t}\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"dae\")\n\t{\n\t\tGLC_ColladaToWorld colladaToWorld(m_pQGLContext);\n\t\tconnect(&colladaToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= colladaToWorld.CreateWorldFromCollada(file);\n\t\tif (NULL != pAttachedFileName)\n\t\t{\n\t\t\t(*pAttachedFileName)= colladaToWorld.listOfAttachedFileName();\n\t\t}\n\t}\n\n\n\treturn pWorld;\n}\n\n\/\/ Create a GLC_World containing only the 3dxml structure\nGLC_World* GLC_Factory::createWorldStructureFrom3dxml(QFile &file) const\n{\n\tGLC_World* pWorld= NULL;\n\n\tif (QFileInfo(file).suffix().toLower() == \"3dxml\")\n\t{\n\t\tGLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);\n\t\tconnect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= d3dxmlToWorld.createWorldFrom3dxml(file, true);\n\t}\n\n\treturn pWorld;\n}\n\n\/\/ Create 3DRep from 3dxml or 3DRep file\nGLC_3DRep GLC_Factory::create3DrepFromFile(const QString& fileName) const\n{\n\tGLC_3DRep rep;\n\n\tif ((QFileInfo(fileName).suffix().toLower() == \"3dxml\") || (QFileInfo(fileName).suffix().toLower() == \"3drep\"))\n\t{\n\t\tGLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);\n\t\tconnect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\trep= d3dxmlToWorld.create3DrepFrom3dxmlRep(fileName);\n\t}\n\n\treturn rep;\n\n}\n\n\/\/ Create a GLC_Material\nGLC_Material* GLC_Factory::createMaterial() const\n{\n\treturn new GLC_Material();\n}\n\n\/\/ Create a GLC_Material\nGLC_Material* GLC_Factory::createMaterial(const GLfloat *pAmbiantColor) const\n{\n\treturn new GLC_Material(\"Material\", pAmbiantColor);\n}\n\/\/ Create a GLC_Material\nGLC_Material* GLC_Factory::createMaterial(const QColor &color) const\n{\n\treturn new GLC_Material(color);\n}\n\nGLC_Material* GLC_Factory::createMaterial(GLC_Texture* pTexture) const\n{\n\treturn new GLC_Material(pTexture, \"TextureMaterial\");\n}\n\/\/ create a material textured with a image file name\nGLC_Material* GLC_Factory::createMaterial(const QString &textureFullFileName) const\n{\n\tGLC_Texture* pTexture= createTexture(textureFullFileName);\n\treturn createMaterial(pTexture);\n}\n\n\/\/ create a material textured with a QImage\nGLC_Material* GLC_Factory::createMaterial(const QImage &image) const\n{\n\tGLC_Texture* pTexture= createTexture(image);\n\treturn createMaterial(pTexture);\n}\n\n\/\/ Create a GLC_Texture\n\nGLC_Texture* GLC_Factory::createTexture(const QString &textureFullFileName) const\n{\n\treturn new GLC_Texture(m_pQGLContext, textureFullFileName);\n}\n\n\/\/ Create a GLC_Texture with a QImage\nGLC_Texture* GLC_Factory::createTexture(const QImage & image) const\n{\n\treturn new GLC_Texture(m_pQGLContext, image);\n}\n\n\/\/ Create the default mover controller\nGLC_MoverController GLC_Factory::createDefaultMoverController(const QColor& color, GLC_Viewport* pViewport)\n{\n\tGLC_MoverController defaultController;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Pan Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Create Pan Mover representation\n\tGLC_RepMover* pRepMover= new GLC_RepCrossMover(pViewport);\n\tpRepMover->setMainColor(color);\n\tQList<GLC_RepMover*> listOfRep;\n\tlistOfRep.append(pRepMover);\n\t\/\/ Create the Pan Mover\n\tGLC_Mover* pMover= new GLC_PanMover(pViewport, listOfRep);\n\t\/\/ Add the Pan Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::Pan);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Zoom Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Copy the pan Mover representation\n\tpRepMover= pRepMover->clone();\n\tlistOfRep.clear();\n\tlistOfRep.append(pRepMover);\n\t\/\/ Create the Zoom Mover\n\tpMover= new GLC_ZoomMover(pViewport, listOfRep);\n\t\/\/ Add the Zoom Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::Zoom);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Set Target Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Create the Zoom Mover\n\tpMover= new GLC_SetTargetMover(pViewport);\n\t\/\/ Add the Zoom Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::Target);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Track Ball Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Copy the pan Mover representation\n\tpRepMover= pRepMover->clone();\n\tlistOfRep.clear();\n\tlistOfRep.append(pRepMover);\n\t\/\/ Create the track ball representation\n\tpRepMover= new GLC_RepTrackBallMover(pViewport);\n\tpRepMover->setMainColor(color);\n\tlistOfRep.append(pRepMover);\n\t\/\/ Create the Track Ball Mover\n\tpMover= new GLC_TrackBallMover(pViewport, listOfRep);\n\t\/\/ Add the Track ball Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::TrackBall);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Turn Table Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Create the Turn Table Mover\n\tpMover= new GLC_TurnTableMover(pViewport);\n\t\/\/ Add the Turn Table Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::TurnTable);\n\n\treturn defaultController;\n}\n<commit_msg>Update call of refactored GLC_Vector3d methods.<commit_after>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 1.2.0, packaged on September 2009.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib 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 GLC-lib 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 GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n*****************************************************************************\/\n\n\/\/! \\file glc_factory.cpp implementation of the GLC_Factory class.\n\n#include \"glc_factory.h\"\n#include \"io\/glc_objtoworld.h\"\n#include \"io\/glc_stltoworld.h\"\n#include \"io\/glc_offtoworld.h\"\n#include \"io\/glc_3dstoworld.h\"\n#include \"io\/glc_3dxmltoworld.h\"\n#include \"io\/glc_colladatoworld.h\"\n\n#include \"viewport\/glc_panmover.h\"\n#include \"viewport\/glc_zoommover.h\"\n#include \"viewport\/glc_settargetmover.h\"\n#include \"viewport\/glc_trackballmover.h\"\n#include \"viewport\/glc_turntablemover.h\"\n#include \"viewport\/glc_repcrossmover.h\"\n#include \"viewport\/glc_reptrackballmover.h\"\n\n\/\/ init static member\nGLC_Factory* GLC_Factory::m_pFactory= NULL;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ static method\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Return the unique instance of the factory\nGLC_Factory* GLC_Factory::instance(const QGLContext *pContext)\n{\n\tif(m_pFactory == NULL)\n\t{\n\t\tm_pFactory= new GLC_Factory(pContext);\n\t}\n\treturn m_pFactory;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constructor destructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Protected constructor\nGLC_Factory::GLC_Factory(const QGLContext *pContext)\n: m_pQGLContext(const_cast<QGLContext*>(pContext))\n{\n\n}\n\n\/\/ Destructor\nGLC_Factory::~GLC_Factory()\n{\n\tm_pFactory= NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Create functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Create a GLC_Point\nGLC_3DRep GLC_Factory::createPoint(const GLC_Point3d &coord) const\n{\n\tGLC_3DRep newPoint(new GLC_Point(coord));\n\treturn newPoint;\n}\n\/\/ Create a GLC_Point\nGLC_3DRep GLC_Factory::createPoint(double x, double y, double z) const\n{\n\tGLC_3DRep newPoint(new GLC_Point(x, y, z));\n\treturn newPoint;\n}\n\n\/\/ Create a GLC_PointSprite\nGLC_3DRep GLC_Factory::createPointSprite(float size, GLC_Material* pMaterial) const\n{\n\tGLC_3DRep newPoint(new GLC_PointSprite(size, pMaterial));\n\treturn newPoint;\n}\n\n\/\/ Create a GLC_Line\nGLC_3DRep GLC_Factory::createLine(const GLC_Point3d& point1, const GLC_Point3d& point2) const\n{\n\tGLC_3DRep newPoint(new GLC_Line(point1, point2));\n\treturn newPoint;\n}\n\n\/\/ Create a GLC_Circle\nGLC_3DRep GLC_Factory::createCircle(double radius, double angle) const\n{\n\tGLC_3DRep newCircle(new GLC_Circle(radius, angle));\n\treturn newCircle;\n}\n\/\/ Create a GLC_Box\nGLC_3DRep GLC_Factory::createBox(double lx, double ly, double lz) const\n{\n\n\tGLC_3DRep newBox(new GLC_Box(lx, ly, lz));\n\treturn newBox;\n}\n\n\/\/ Create a GLC_Box\nGLC_3DViewInstance GLC_Factory::createBox(const GLC_BoundingBox& boundingBox) const\n{\n\tconst double lx= boundingBox.upperCorner().x() - boundingBox.lowerCorner().x();\n\tconst double ly= boundingBox.upperCorner().y() - boundingBox.lowerCorner().y();\n\tconst double lz= boundingBox.upperCorner().z() - boundingBox.lowerCorner().z();\n\tGLC_Box* pBox= new GLC_Box(lx, ly, lz);\n\tGLC_3DViewInstance newBox(pBox);\n\tnewBox.translate(boundingBox.center().x(), boundingBox.center().y()\n\t\t\t\t\t, boundingBox.center().z());\n\treturn newBox;\n}\n\n\/\/ Create a GLC_Cylinder\nGLC_3DRep GLC_Factory::createCylinder(double radius, double length) const\n{\n\n\tGLC_3DRep newCylinder(new GLC_Cylinder(radius, length));\n\treturn newCylinder;\n}\n\n\/\/ Create a GLC_Rectangle\nGLC_3DRep GLC_Factory::createRectangle(double l1, double l2)\n{\n\tGLC_3DRep newRectangle(new GLC_Rectangle(l1, l2));\n\treturn newRectangle;\n}\n\n\/\/ Create a GLC_World* with a QFile\nGLC_World* GLC_Factory::createWorld(QFile &file, QStringList* pAttachedFileName) const\n{\n\tGLC_World* pWorld= NULL;\n\tif (QFileInfo(file).suffix().toLower() == \"obj\")\n\t{\n\t\tGLC_ObjToWorld objToWorld(m_pQGLContext);\n\t\tconnect(&objToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= objToWorld.CreateWorldFromObj(file);\n\t\tif (NULL != pAttachedFileName)\n\t\t{\n\t\t\t(*pAttachedFileName)= objToWorld.listOfAttachedFileName();\n\t\t}\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"stl\")\n\t{\n\t\tGLC_StlToWorld stlToWorld;\n\t\tconnect(&stlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= stlToWorld.CreateWorldFromStl(file);\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"off\")\n\t{\n\t\tGLC_OffToWorld offToWorld;\n\t\tconnect(&offToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= offToWorld.CreateWorldFromOff(file);\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"3ds\")\n\t{\n\t\tGLC_3dsToWorld studioToWorld(m_pQGLContext);\n\t\tconnect(&studioToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= studioToWorld.CreateWorldFrom3ds(file);\n\t\tif (NULL != pAttachedFileName)\n\t\t{\n\t\t\t(*pAttachedFileName)= studioToWorld.listOfAttachedFileName();\n\t\t}\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"3dxml\")\n\t{\n\t\tGLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);\n\t\tconnect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= d3dxmlToWorld.createWorldFrom3dxml(file, false);\n\t\tif (NULL != pAttachedFileName)\n\t\t{\n\t\t\t(*pAttachedFileName)= d3dxmlToWorld.listOfAttachedFileName();\n\t\t}\n\t}\n\telse if (QFileInfo(file).suffix().toLower() == \"dae\")\n\t{\n\t\tGLC_ColladaToWorld colladaToWorld(m_pQGLContext);\n\t\tconnect(&colladaToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= colladaToWorld.CreateWorldFromCollada(file);\n\t\tif (NULL != pAttachedFileName)\n\t\t{\n\t\t\t(*pAttachedFileName)= colladaToWorld.listOfAttachedFileName();\n\t\t}\n\t}\n\n\n\treturn pWorld;\n}\n\n\/\/ Create a GLC_World containing only the 3dxml structure\nGLC_World* GLC_Factory::createWorldStructureFrom3dxml(QFile &file) const\n{\n\tGLC_World* pWorld= NULL;\n\n\tif (QFileInfo(file).suffix().toLower() == \"3dxml\")\n\t{\n\t\tGLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);\n\t\tconnect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\tpWorld= d3dxmlToWorld.createWorldFrom3dxml(file, true);\n\t}\n\n\treturn pWorld;\n}\n\n\/\/ Create 3DRep from 3dxml or 3DRep file\nGLC_3DRep GLC_Factory::create3DrepFromFile(const QString& fileName) const\n{\n\tGLC_3DRep rep;\n\n\tif ((QFileInfo(fileName).suffix().toLower() == \"3dxml\") || (QFileInfo(fileName).suffix().toLower() == \"3drep\"))\n\t{\n\t\tGLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);\n\t\tconnect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));\n\t\trep= d3dxmlToWorld.create3DrepFrom3dxmlRep(fileName);\n\t}\n\n\treturn rep;\n\n}\n\n\/\/ Create a GLC_Material\nGLC_Material* GLC_Factory::createMaterial() const\n{\n\treturn new GLC_Material();\n}\n\n\/\/ Create a GLC_Material\nGLC_Material* GLC_Factory::createMaterial(const GLfloat *pAmbiantColor) const\n{\n\treturn new GLC_Material(\"Material\", pAmbiantColor);\n}\n\/\/ Create a GLC_Material\nGLC_Material* GLC_Factory::createMaterial(const QColor &color) const\n{\n\treturn new GLC_Material(color);\n}\n\nGLC_Material* GLC_Factory::createMaterial(GLC_Texture* pTexture) const\n{\n\treturn new GLC_Material(pTexture, \"TextureMaterial\");\n}\n\/\/ create a material textured with a image file name\nGLC_Material* GLC_Factory::createMaterial(const QString &textureFullFileName) const\n{\n\tGLC_Texture* pTexture= createTexture(textureFullFileName);\n\treturn createMaterial(pTexture);\n}\n\n\/\/ create a material textured with a QImage\nGLC_Material* GLC_Factory::createMaterial(const QImage &image) const\n{\n\tGLC_Texture* pTexture= createTexture(image);\n\treturn createMaterial(pTexture);\n}\n\n\/\/ Create a GLC_Texture\n\nGLC_Texture* GLC_Factory::createTexture(const QString &textureFullFileName) const\n{\n\treturn new GLC_Texture(m_pQGLContext, textureFullFileName);\n}\n\n\/\/ Create a GLC_Texture with a QImage\nGLC_Texture* GLC_Factory::createTexture(const QImage & image) const\n{\n\treturn new GLC_Texture(m_pQGLContext, image);\n}\n\n\/\/ Create the default mover controller\nGLC_MoverController GLC_Factory::createDefaultMoverController(const QColor& color, GLC_Viewport* pViewport)\n{\n\tGLC_MoverController defaultController;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Pan Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Create Pan Mover representation\n\tGLC_RepMover* pRepMover= new GLC_RepCrossMover(pViewport);\n\tpRepMover->setMainColor(color);\n\tQList<GLC_RepMover*> listOfRep;\n\tlistOfRep.append(pRepMover);\n\t\/\/ Create the Pan Mover\n\tGLC_Mover* pMover= new GLC_PanMover(pViewport, listOfRep);\n\t\/\/ Add the Pan Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::Pan);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Zoom Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Copy the pan Mover representation\n\tpRepMover= pRepMover->clone();\n\tlistOfRep.clear();\n\tlistOfRep.append(pRepMover);\n\t\/\/ Create the Zoom Mover\n\tpMover= new GLC_ZoomMover(pViewport, listOfRep);\n\t\/\/ Add the Zoom Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::Zoom);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Set Target Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Create the Zoom Mover\n\tpMover= new GLC_SetTargetMover(pViewport);\n\t\/\/ Add the Zoom Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::Target);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Track Ball Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Copy the pan Mover representation\n\tpRepMover= pRepMover->clone();\n\tlistOfRep.clear();\n\tlistOfRep.append(pRepMover);\n\t\/\/ Create the track ball representation\n\tpRepMover= new GLC_RepTrackBallMover(pViewport);\n\tpRepMover->setMainColor(color);\n\tlistOfRep.append(pRepMover);\n\t\/\/ Create the Track Ball Mover\n\tpMover= new GLC_TrackBallMover(pViewport, listOfRep);\n\t\/\/ Add the Track ball Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::TrackBall);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Turn Table Mover\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Create the Turn Table Mover\n\tpMover= new GLC_TurnTableMover(pViewport);\n\t\/\/ Add the Turn Table Mover to the controller\n\tdefaultController.addMover(pMover, GLC_MoverController::TurnTable);\n\n\treturn defaultController;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2020 Google LLC\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 \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkFont.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkPath.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/utils\/SkCustomTypeface.h\"\n#include \"tools\/Resources.h\"\n\nstatic sk_sp<SkTypeface> make_tf() {\n SkCustomTypefaceBuilder builder;\n SkFont font;\n font.setSize(1.0f);\n font.setHinting(SkFontHinting::kNone);\n\n \/\/ Steal the first 128 chars from the default font\n for (SkGlyphID index = 0; index <= 127; ++index) {\n SkGlyphID glyph = font.unicharToGlyph(index);\n\n SkScalar width;\n font.getWidths(&glyph, 1, &width);\n SkPath path;\n font.getPath(glyph, &path);\n\n \/\/ we use the charcode to be our glyph index, since we have no cmap table\n builder.setGlyph(index, width, path);\n }\n\n return builder.detach();\n}\n\n#include \"include\/core\/SkTextBlob.h\"\n\nclass UserFontGM : public skiagm::GM {\n sk_sp<SkTypeface> fTF;\n sk_sp<SkTextBlob> fBlob;\n\n SkPath fPath;\npublic:\n UserFontGM() {}\n\n void onOnceBeforeDraw() override {\n fTF = make_tf();\n\n SkFont font(fTF);\n font.setSize(100);\n font.setEdging(SkFont::Edging::kAntiAlias);\n\n fBlob = SkTextBlob::MakeFromString(\"User Typeface\", font);\n }\n\n bool runAsBench() const override { return true; }\n\n SkString onShortName() override { return SkString(\"user_typeface\"); }\n\n SkISize onISize() override { return {512, 512}; }\n\n void onDraw(SkCanvas* canvas) override {\n SkScalar x = 20,\n y = 250;\n\n SkPaint paint;\n paint.setStyle(SkPaint::kStroke_Style);\n canvas->drawRect(fBlob->bounds().makeOffset(x, y), paint);\n\n paint.setStyle(SkPaint::kFill_Style);\n paint.setColor(SK_ColorRED);\n canvas->drawTextBlob(fBlob, x, y, paint);\n }\n};\nDEF_GM(return new UserFontGM;)\n<commit_msg>extend custom typeface gm<commit_after>\/*\n * Copyright 2020 Google LLC\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 \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkFont.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkPath.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/utils\/SkCustomTypeface.h\"\n#include \"tools\/Resources.h\"\n\nstatic sk_sp<SkTypeface> make_tf() {\n SkCustomTypefaceBuilder builder;\n SkFont font;\n font.setSize(1.0f);\n font.setHinting(SkFontHinting::kNone);\n\n \/\/ Steal the first 128 chars from the default font\n for (SkGlyphID index = 0; index <= 127; ++index) {\n SkGlyphID glyph = font.unicharToGlyph(index);\n\n SkScalar width;\n font.getWidths(&glyph, 1, &width);\n SkPath path;\n font.getPath(glyph, &path);\n\n \/\/ we use the charcode to be our glyph index, since we have no cmap table\n builder.setGlyph(index, width, path);\n }\n\n return builder.detach();\n}\n\n#include \"include\/core\/SkTextBlob.h\"\n\nclass UserFontGM : public skiagm::GM {\n sk_sp<SkTypeface> fTF;\n\npublic:\n UserFontGM() {}\n\n void onOnceBeforeDraw() override {\n fTF = make_tf();\n }\n\n static sk_sp<SkTextBlob> make_blob(sk_sp<SkTypeface> tf, float size) {\n SkFont font(tf);\n font.setSize(size);\n font.setEdging(SkFont::Edging::kAntiAlias);\n return SkTextBlob::MakeFromString(\"Typeface\", font);\n }\n\n bool runAsBench() const override { return true; }\n\n SkString onShortName() override { return SkString(\"user_typeface\"); }\n\n SkISize onISize() override { return {810, 512}; }\n\n void onDraw(SkCanvas* canvas) override {\n auto waterfall = [&](sk_sp<SkTypeface> tf) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n float x = 20,\n y = 16;\n for (float size = 9; size <= 100; size *= 1.25f) {\n auto blob = make_blob(tf, size);\n\n paint.setColor(0xFFCCCCCC);\n paint.setStyle(SkPaint::kStroke_Style);\n canvas->drawRect(blob->bounds().makeOffset(x, y), paint);\n\n paint.setStyle(SkPaint::kFill_Style);\n paint.setColor(SK_ColorBLACK);\n canvas->drawTextBlob(blob, x, y, paint);\n\n y += size * 1.5f;\n }\n };\n\n waterfall(nullptr);\n canvas->translate(400, 0);\n waterfall(fTF);\n }\n};\nDEF_GM(return new UserFontGM;)\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file llurldispatcher.cpp\n * @brief Central registry for all URL handlers\n *\n * $LicenseInfo:firstyear=2007&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010, Linden Research, Inc.\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;\n * version 2.1 of the License only.\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 * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"llurldispatcher.h\"\n\n\/\/ viewer includes\n#include \"llagent.h\"\t\t\t\/\/ teleportViaLocation()\n#include \"llcommandhandler.h\"\n#include \"llfloaterhelpbrowser.h\"\n#include \"llfloaterreg.h\"\n#include \"llfloatersidepanelcontainer.h\"\n#include \"llfloaterworldmap.h\"\n#include \"llpanellogin.h\"\n#include \"llregionhandle.h\"\n#include \"llslurl.h\"\n#include \"llstartup.h\"\t\t\t\/\/ gStartupState\n#include \"llweb.h\"\n#include \"llworldmapmessage.h\"\n#include \"llurldispatcherlistener.h\"\n#include \"llviewernetwork.h\"\n#include \"llviewercontrol.h\"\n\n\/\/ library includes\n#include \"llnotificationsutil.h\"\n#include \"llsd.h\"\n\nstatic LLURLDispatcherListener sURLDispatcherListener;\n\nclass LLURLDispatcherImpl\n{\npublic:\n\tstatic bool dispatch(const LLSLURL& slurl,\n\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t bool trusted_browser);\n\t\t\/\/ returns true if handled or explicitly blocked.\n\n\tstatic bool dispatchRightClick(const LLSLURL& slurl);\n\nprivate:\n\tstatic bool dispatchCore(const LLSLURL& slurl, \n\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t bool right_mouse,\n\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t bool trusted_browser);\n\t\t\/\/ handles both left and right click\n\n\tstatic bool dispatchHelp(const LLSLURL& slurl, bool right_mouse);\n\t\t\/\/ Handles sl:\/\/app.floater.html.help by showing Help floater.\n\t\t\/\/ Returns true if handled.\n\n\tstatic bool dispatchApp(const LLSLURL& slurl,\n\t\t\t\t\t\t\tconst std::string& nav_type,\n\t\t\t\t\t\t\tbool right_mouse,\n\t\t\t\t\t\t\tLLMediaCtrl* web,\n\t\t\t\t\t\t\tbool trusted_browser);\n\t\t\/\/ Handles secondlife:\/\/\/app\/agent\/<agent_id>\/about and similar\n\t\t\/\/ by showing panel in Search floater.\n\t\t\/\/ Returns true if handled or explicitly blocked.\n\n\tstatic bool dispatchRegion(const LLSLURL& slurl, const std::string& nav_type, bool right_mouse);\n\t\t\/\/ handles secondlife:\/\/Ahern\/123\/45\/67\/\n\t\t\/\/ Returns true if handled.\n\n\tstatic void regionHandleCallback(U64 handle, const LLSLURL& slurl,\n\t\tconst LLUUID& snapshot_id, bool teleport);\n\t\t\/\/ Called by LLWorldMap when a location has been resolved to a\n\t \/\/ region name\n\n\tstatic void regionNameCallback(U64 handle, const LLSLURL& slurl,\n\t\tconst LLUUID& snapshot_id, bool teleport);\n\t\t\/\/ Called by LLWorldMap when a region name has been resolved to a\n\t\t\/\/ location in-world, used by places-panel display.\n\n\tfriend class LLTeleportHandler;\n};\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatchCore(const LLSLURL& slurl,\n\t\t\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t\t\t bool right_mouse,\n\t\t\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t\t\t bool trusted_browser)\n{\n\t\/\/if (dispatchHelp(slurl, right_mouse)) return true;\n\tswitch(slurl.getType())\n\t{\n\t\tcase LLSLURL::APP: \n\t\t\treturn dispatchApp(slurl, nav_type, right_mouse, web, trusted_browser);\n\t\tcase LLSLURL::LOCATION:\n\t\t\treturn dispatchRegion(slurl, nav_type, right_mouse);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n\n\t\/*\n\t\/\/ Inform the user we can't handle this\n\tstd::map<std::string, std::string> args;\n\targs[\"SLURL\"] = slurl;\n\tr;\n\t*\/\n}\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatch(const LLSLURL& slurl,\n\t\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t\t bool trusted_browser)\n{\n\tconst bool right_click = false;\n\treturn dispatchCore(slurl, nav_type, right_click, web, trusted_browser);\n}\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatchRightClick(const LLSLURL& slurl)\n{\n\tconst bool right_click = true;\n\tLLMediaCtrl* web = NULL;\n\tconst bool trusted_browser = false;\n\treturn dispatchCore(slurl, \"clicked\", right_click, web, trusted_browser);\n}\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatchApp(const LLSLURL& slurl, \n\t\t\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t\t\t bool right_mouse,\n\t\t\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t\t\t bool trusted_browser)\n{\n\tllinfos << \"cmd: \" << slurl.getAppCmd() << \" path: \" << slurl.getAppPath() << \" query: \" << slurl.getAppQuery() << llendl;\n\tconst LLSD& query_map = LLURI::queryMap(slurl.getAppQuery());\n\n\/\/ <FS:AW handle hop app teleports properly>\n\/\/ \tbool handled = LLCommandDispatcher::dispatch(\n\/\/ \t\t\tslurl.getAppCmd(), slurl.getAppPath(), query_map, web, nav_type, trusted_browser);\n\tLLSD path;\n#ifdef OPENSIM \/\/ <FS:AW optional opensim support>\n\tif (\"teleport\" == slurl.getAppCmd())\n\t{\n\t\tpath = LLSD::emptyArray();\n\t\tpath.append(slurl.getGrid());\n\t\tfor(int i=0; slurl.getAppPath().size() > i; i++)\n\t\t{\n\t\t\tpath.append(slurl.getAppPath()[i].asString());\n\t\t}\n\t}\n\telse\n#endif \/\/ OPENSIM \/\/ <FS:AW optional opensim support>\n\t{\n\t\tpath = slurl.getAppPath();\n\t}\n\n\tbool handled = LLCommandDispatcher::dispatch(\n\t\t\tslurl.getAppCmd(), path, query_map, web, nav_type, trusted_browser);\n\/\/ <\/FS:AW handle hop app teleports properly>\n\n\t\/\/ alert if we didn't handle this secondlife:\/\/\/app\/ SLURL\n\t\/\/ (but still return true because it is a valid app SLURL)\n\tif (! handled)\n\t{\n\t\tLLNotificationsUtil::add(\"UnsupportedCommandSLURL\");\n\t}\n\treturn true;\n}\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatchRegion(const LLSLURL& slurl, const std::string& nav_type, bool right_mouse)\n{\n\tif(slurl.getType() != LLSLURL::LOCATION)\n {\n\t\treturn false;\n }\n\t\/\/ Before we're logged in, need to update the startup screen\n\t\/\/ to tell the user where they are going.\n\tif (LLStartUp::getStartupState() < STATE_LOGIN_CLEANUP)\n\t{\n\t\t\/\/ We're at the login screen, so make sure user can see\n\t\t\/\/ the login location box to know where they are going.\n\t\t\n\t\tLLPanelLogin::setLocation(slurl);\n\t\treturn true;\n\t}\n\/\/ <FS:AW hypergrid support >\n\/\/ \tLLWorldMapMessage::getInstance()->sendNamedRegionRequest(slurl.getRegion(),\n\/\/ \n\/\/ \t\t\t\t\t\t\t\t\t LLURLDispatcherImpl::regionNameCallback,\n\/\/ \t\t\t\t\t\t\t\t\t slurl.getSLURLString(),\n\tLLSLURL hyper = slurl;\n#ifdef OPENSIM \/\/ <FS:AW optional opensim support>\n\tstd::string grid = slurl.getGrid();\n\tstd::string current_grid = LLGridManager::getInstance()->getGrid();\n\n\tstd::string gatekeeper = LLGridManager::getInstance()->getGatekeeper(grid);\n\n\tstd::string current = LLGridManager::getInstance()->getGrid();\n\tif((grid != current ) && (!LLGridManager::getInstance()->isInOpenSim() || (!slurl.getHypergrid() && gatekeeper.empty())))\n\t{\n\t\tstd::string dest = hyper.getSLURLString();\n\t\tif (!dest.empty())\n\t\t{\n\t\t\tLLSD args;\n\t\t\targs[\"SLURL\"] = dest;\n\t\t\targs[\"GRID\"] = slurl.getGrid();\n\t\t\targs[\"CURRENT_GRID\"] = current_grid;\n\t\t\tLLNotificationsUtil::add(\"CantTeleportToGrid\", args);\n\t\t\treturn true;\n\t\t}\n\t}\n\telse if(!gatekeeper.empty())\n\t{\n\t\thyper = LLSLURL(gatekeeper + \":\" + slurl.getRegion(), slurl.getPosition(), true);\n\t}\n\n#endif \/\/OPENSIM\n\/\/ <\/FS:AW optional opensim support>\n\t\/\/ Request a region handle by name\n\tLLWorldMapMessage::getInstance()->sendNamedRegionRequest(hyper.getRegion(), LLURLDispatcherImpl::regionNameCallback, hyper.getSLURLString(), LLUI::sSettingGroups[\"config\"]->getBOOL(\"SLURLTeleportDirectly\"));\t\/\/ don't teleport\n\treturn true;\n}\n\n\/*static*\/\nvoid LLURLDispatcherImpl::regionNameCallback(U64 region_handle, const LLSLURL& slurl, const LLUUID& snapshot_id, bool teleport)\n{\n \n if(slurl.getType() == LLSLURL::LOCATION)\n { \n regionHandleCallback(region_handle, slurl, snapshot_id, teleport);\n }\n}\n\n\/* static *\/\nvoid LLURLDispatcherImpl::regionHandleCallback(U64 region_handle, const LLSLURL& slurl, const LLUUID& snapshot_id, bool teleport)\n{\n \/\/ <FS:AW optional opensim support>\n#ifndef OPENSIM\n \/\/ we can't teleport cross grid at this point\n\tif (LLGridManager::getInstance()->getGrid(slurl.getGrid()) != LLGridManager::getInstance()->getGrid())\n\t{\n\t\tLLSD args;\n\t\targs[\"SLURL\"] = slurl.getLocationString();\n\t\targs[\"CURRENT_GRID\"] = LLGridManager::getInstance()->getGridLabel();\n\t\targs[\"GRID\"] = LLGridManager::getInstance()->getGridLabel(slurl.getGrid());\n\t\tLLNotificationsUtil::add(\"CantTeleportToGrid\", args);\n\t\treturn;\n\t}\n\n#endif \/\/ OPENSIM\n\/\/ <\/FS:AW optional opensim support>\n\n\tLLVector3d global_pos = from_region_handle(region_handle);\n\tglobal_pos += LLVector3d(slurl.getPosition());\n\n\tif (teleport)\n\t{\t\n\t\tgAgent.teleportViaLocation(global_pos);\n\t\tLLFloaterWorldMap* instance = LLFloaterWorldMap::getInstance();\n\t\tif(instance)\n\t\t{\n\t\t\tinstance->trackLocation(global_pos);\n\t\t}\n\t}\n\telse\n\t{\n\t\tLLSD key;\n\t\tkey[\"type\"] = \"remote_place\";\n\t\tkey[\"x\"] = global_pos.mdV[VX];\n\t\tkey[\"y\"] = global_pos.mdV[VY];\n\t\tkey[\"z\"] = global_pos.mdV[VZ];\n\n\t\t\/\/ <FS:Ansariel> FIRE-817: Separate place details floater\n\t\t\/\/LLFloaterSidePanelContainer::showPanel(\"places\", key);\n\t\tif (gSavedSettings.getBOOL(\"FSUseStandalonePlaceDetailsFloater\"))\n\t\t{\n\t\t\tLLFloaterReg::showInstance(\"fs_placedetails\", key);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLLFloaterSidePanelContainer::showPanel(\"places\", key);\n\t\t}\n\t\t\/\/ <\/FS:Ansariel>\n\t}\n}\n\n\/\/---------------------------------------------------------------------------\n\/\/ Teleportation links are handled here because they are tightly coupled\n\/\/ to SLURL parsing and sim-fragment parsing\nclass LLTeleportHandler : public LLCommandHandler\n{\npublic:\n\t\/\/ Teleport requests *must* come from a trusted browser\n\t\/\/ inside the app, otherwise a malicious web page could\n\t\/\/ cause a constant teleport loop. JC\n\tLLTeleportHandler() : LLCommandHandler(\"teleport\", UNTRUSTED_BLOCK) { }\n\n\tbool handle(const LLSD& tokens, const LLSD& query_map,\n\t\t\t\tLLMediaCtrl* web)\n\t{\n\t\t\/\/ construct a \"normal\" SLURL, resolve the region to\n\t\t\/\/ a global position, and teleport to it\n\t\tif (tokens.size() < 1) return false;\n \/\/ <FS:AW optional opensim support>\n#ifdef OPENSIM\n\t\tLLSLURL slurl(tokens, true);\n\n\t\tstd::string grid = slurl.getGrid();\n\t\tstd::string gatekeeper = LLGridManager::getInstance()->getGatekeeper(grid);\n\t\tstd::string region_name = slurl.getRegion();\n\t\tstd::string dest;\n\t\tstd::string current = LLGridManager::getInstance()->getGrid();\n\t\tif((grid != current) && (!LLGridManager::getInstance()->isInOpenSim() || (!slurl.getHypergrid() && gatekeeper.empty())))\n\t\t{\n\t\t\tdest = slurl.getSLURLString();\n\t\t\tif (!dest.empty())\n\t\t\t{\n\t\t\t\tLLSD args;\n\t\t\t\targs[\"SLURL\"] = dest;\n\t\t\t\targs[\"GRID\"] = grid;\n\t\t\t\targs[\"CURRENT_GRID\"] = current;\n\t\t\t\tLLNotificationsUtil::add(\"CantTeleportToGrid\", args);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if(!gatekeeper.empty() && gatekeeper != LLGridManager::getInstance()->getGatekeeper())\n\t\t{\n\t\t\tregion_name = gatekeeper + \":\" + region_name;\n\t\t}\n\n\t\tdest = \"hop:\/\/\" + current + \"\/\" + region_name;\n\n\t\tfor(int i=2; tokens.size() > i; i++)\n\t\t{\n\t\t\tdest.append(\"\/\" + tokens[i].asString());\n\t\t}\n\n\t\tLLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name,\n\t\t\tLLURLDispatcherImpl::regionHandleCallback,\n\t\t\tLLSLURL(dest).getSLURLString(),\n\t\t\ttrue);\t\/\/ teleport\n#else \/\/ OPENSIM\n\t\tLLVector3 coords(128, 128, 0);\n\t\tif (tokens.size() <= 4)\n\t\t{\n\t\t\tcoords = LLVector3(tokens[1].asReal(), \n\t\t\t\t\t\t\t tokens[2].asReal(), \n\t\t\t\t\t\t\t tokens[3].asReal());\n\t\t}\n\t\t\n\t\t\/\/ Region names may be %20 escaped.\n\t\t\n\t\tstd::string region_name = LLURI::unescape(tokens[0]);\n\n\t\tLLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name, LLURLDispatcherImpl::regionHandleCallback, LLSLURL(region_name, coords).getSLURLString(), true);\/\/ teleport\n#endif \/\/ OPENSIM\n\/\/ <\/FS:AW optional opensim support>\n\n\t\treturn true;\n\t}\n};\nLLTeleportHandler gTeleportHandler;\n\n\/\/---------------------------------------------------------------------------\n\n\/\/ static\nbool LLURLDispatcher::dispatch(const std::string& slurl,\n\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t bool trusted_browser)\n{\n\treturn LLURLDispatcherImpl::dispatch(LLSLURL(slurl), nav_type, web, trusted_browser);\n}\n\n\/\/ static\nbool LLURLDispatcher::dispatchRightClick(const std::string& slurl)\n{\n\treturn LLURLDispatcherImpl::dispatchRightClick(LLSLURL(slurl));\n}\n\n\/\/ static\nbool LLURLDispatcher::dispatchFromTextEditor(const std::string& slurl)\n{\n\t\/\/ *NOTE: Text editors are considered sources of trusted URLs\n\t\/\/ in order to make avatar profile links in chat history work.\n\t\/\/ While a malicious resident could chat an app SLURL, the\n\t\/\/ receiving resident will see it and must affirmatively\n\t\/\/ click on it.\n\t\/\/ *TODO: Make this trust model more refined. JC\n\tconst bool trusted_browser = true;\n\tLLMediaCtrl* web = NULL;\n\treturn LLURLDispatcherImpl::dispatch(LLSLURL(slurl), \"clicked\", web, trusted_browser);\n}\n\n\n<commit_msg>Remove an unnecessary variable from llurldispatcher.cpp<commit_after>\/**\n * @file llurldispatcher.cpp\n * @brief Central registry for all URL handlers\n *\n * $LicenseInfo:firstyear=2007&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010, Linden Research, Inc.\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;\n * version 2.1 of the License only.\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 * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"llurldispatcher.h\"\n\n\/\/ viewer includes\n#include \"llagent.h\"\t\t\t\/\/ teleportViaLocation()\n#include \"llcommandhandler.h\"\n#include \"llfloaterhelpbrowser.h\"\n#include \"llfloaterreg.h\"\n#include \"llfloatersidepanelcontainer.h\"\n#include \"llfloaterworldmap.h\"\n#include \"llpanellogin.h\"\n#include \"llregionhandle.h\"\n#include \"llslurl.h\"\n#include \"llstartup.h\"\t\t\t\/\/ gStartupState\n#include \"llweb.h\"\n#include \"llworldmapmessage.h\"\n#include \"llurldispatcherlistener.h\"\n#include \"llviewernetwork.h\"\n#include \"llviewercontrol.h\"\n\n\/\/ library includes\n#include \"llnotificationsutil.h\"\n#include \"llsd.h\"\n\nstatic LLURLDispatcherListener sURLDispatcherListener;\n\nclass LLURLDispatcherImpl\n{\npublic:\n\tstatic bool dispatch(const LLSLURL& slurl,\n\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t bool trusted_browser);\n\t\t\/\/ returns true if handled or explicitly blocked.\n\n\tstatic bool dispatchRightClick(const LLSLURL& slurl);\n\nprivate:\n\tstatic bool dispatchCore(const LLSLURL& slurl, \n\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t bool right_mouse,\n\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t bool trusted_browser);\n\t\t\/\/ handles both left and right click\n\n\tstatic bool dispatchHelp(const LLSLURL& slurl, bool right_mouse);\n\t\t\/\/ Handles sl:\/\/app.floater.html.help by showing Help floater.\n\t\t\/\/ Returns true if handled.\n\n\tstatic bool dispatchApp(const LLSLURL& slurl,\n\t\t\t\t\t\t\tconst std::string& nav_type,\n\t\t\t\t\t\t\tbool right_mouse,\n\t\t\t\t\t\t\tLLMediaCtrl* web,\n\t\t\t\t\t\t\tbool trusted_browser);\n\t\t\/\/ Handles secondlife:\/\/\/app\/agent\/<agent_id>\/about and similar\n\t\t\/\/ by showing panel in Search floater.\n\t\t\/\/ Returns true if handled or explicitly blocked.\n\n\tstatic bool dispatchRegion(const LLSLURL& slurl, const std::string& nav_type, bool right_mouse);\n\t\t\/\/ handles secondlife:\/\/Ahern\/123\/45\/67\/\n\t\t\/\/ Returns true if handled.\n\n\tstatic void regionHandleCallback(U64 handle, const LLSLURL& slurl,\n\t\tconst LLUUID& snapshot_id, bool teleport);\n\t\t\/\/ Called by LLWorldMap when a location has been resolved to a\n\t \/\/ region name\n\n\tstatic void regionNameCallback(U64 handle, const LLSLURL& slurl,\n\t\tconst LLUUID& snapshot_id, bool teleport);\n\t\t\/\/ Called by LLWorldMap when a region name has been resolved to a\n\t\t\/\/ location in-world, used by places-panel display.\n\n\tfriend class LLTeleportHandler;\n};\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatchCore(const LLSLURL& slurl,\n\t\t\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t\t\t bool right_mouse,\n\t\t\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t\t\t bool trusted_browser)\n{\n\t\/\/if (dispatchHelp(slurl, right_mouse)) return true;\n\tswitch(slurl.getType())\n\t{\n\t\tcase LLSLURL::APP: \n\t\t\treturn dispatchApp(slurl, nav_type, right_mouse, web, trusted_browser);\n\t\tcase LLSLURL::LOCATION:\n\t\t\treturn dispatchRegion(slurl, nav_type, right_mouse);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n\n\t\/*\n\t\/\/ Inform the user we can't handle this\n\tstd::map<std::string, std::string> args;\n\targs[\"SLURL\"] = slurl;\n\tr;\n\t*\/\n}\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatch(const LLSLURL& slurl,\n\t\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t\t bool trusted_browser)\n{\n\tconst bool right_click = false;\n\treturn dispatchCore(slurl, nav_type, right_click, web, trusted_browser);\n}\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatchRightClick(const LLSLURL& slurl)\n{\n\tconst bool right_click = true;\n\tLLMediaCtrl* web = NULL;\n\tconst bool trusted_browser = false;\n\treturn dispatchCore(slurl, \"clicked\", right_click, web, trusted_browser);\n}\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatchApp(const LLSLURL& slurl, \n\t\t\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t\t\t bool right_mouse,\n\t\t\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t\t\t bool trusted_browser)\n{\n\tllinfos << \"cmd: \" << slurl.getAppCmd() << \" path: \" << slurl.getAppPath() << \" query: \" << slurl.getAppQuery() << llendl;\n\tconst LLSD& query_map = LLURI::queryMap(slurl.getAppQuery());\n\n\/\/ <FS:AW handle hop app teleports properly>\n\/\/ \tbool handled = LLCommandDispatcher::dispatch(\n\/\/ \t\t\tslurl.getAppCmd(), slurl.getAppPath(), query_map, web, nav_type, trusted_browser);\n\tLLSD path;\n#ifdef OPENSIM \/\/ <FS:AW optional opensim support>\n\tif (\"teleport\" == slurl.getAppCmd())\n\t{\n\t\tpath = LLSD::emptyArray();\n\t\tpath.append(slurl.getGrid());\n\t\tfor(int i=0; slurl.getAppPath().size() > i; i++)\n\t\t{\n\t\t\tpath.append(slurl.getAppPath()[i].asString());\n\t\t}\n\t}\n\telse\n#endif \/\/ OPENSIM \/\/ <FS:AW optional opensim support>\n\t{\n\t\tpath = slurl.getAppPath();\n\t}\n\n\tbool handled = LLCommandDispatcher::dispatch(\n\t\t\tslurl.getAppCmd(), path, query_map, web, nav_type, trusted_browser);\n\/\/ <\/FS:AW handle hop app teleports properly>\n\n\t\/\/ alert if we didn't handle this secondlife:\/\/\/app\/ SLURL\n\t\/\/ (but still return true because it is a valid app SLURL)\n\tif (! handled)\n\t{\n\t\tLLNotificationsUtil::add(\"UnsupportedCommandSLURL\");\n\t}\n\treturn true;\n}\n\n\/\/ static\nbool LLURLDispatcherImpl::dispatchRegion(const LLSLURL& slurl, const std::string& nav_type, bool right_mouse)\n{\n\tif(slurl.getType() != LLSLURL::LOCATION)\n {\n\t\treturn false;\n }\n\t\/\/ Before we're logged in, need to update the startup screen\n\t\/\/ to tell the user where they are going.\n\tif (LLStartUp::getStartupState() < STATE_LOGIN_CLEANUP)\n\t{\n\t\t\/\/ We're at the login screen, so make sure user can see\n\t\t\/\/ the login location box to know where they are going.\n\t\t\n\t\tLLPanelLogin::setLocation(slurl);\n\t\treturn true;\n\t}\n\/\/ <FS:AW hypergrid support >\n\/\/ \tLLWorldMapMessage::getInstance()->sendNamedRegionRequest(slurl.getRegion(),\n\/\/ \n\/\/ \t\t\t\t\t\t\t\t\t LLURLDispatcherImpl::regionNameCallback,\n\/\/ \t\t\t\t\t\t\t\t\t slurl.getSLURLString(),\n\tLLSLURL hyper = slurl;\n#ifdef OPENSIM \/\/ <FS:AW optional opensim support>\n\tstd::string grid = slurl.getGrid();\n\tstd::string current_grid = LLGridManager::getInstance()->getGrid();\n\tstd::string gatekeeper = LLGridManager::getInstance()->getGatekeeper(grid);\n\n\tif ((grid != current_grid)\n\t\t&& (!LLGridManager::getInstance()->isInOpenSim() || (!slurl.getHypergrid() && gatekeeper.empty())))\n\t{\n\t\tstd::string dest = hyper.getSLURLString();\n\t\tif (!dest.empty())\n\t\t{\n\t\t\tLLSD args;\n\t\t\targs[\"SLURL\"] = dest;\n\t\t\targs[\"GRID\"] = grid;\n\t\t\targs[\"CURRENT_GRID\"] = current_grid;\n\t\t\tLLNotificationsUtil::add(\"CantTeleportToGrid\", args);\n\t\t\treturn true;\n\t\t}\n\t}\n\telse if(!gatekeeper.empty())\n\t{\n\t\thyper = LLSLURL(gatekeeper + \":\" + slurl.getRegion(), slurl.getPosition(), true);\n\t}\n\n#endif \/\/OPENSIM\n\/\/ <\/FS:AW optional opensim support>\n\t\/\/ Request a region handle by name\n\tLLWorldMapMessage::getInstance()->sendNamedRegionRequest(hyper.getRegion(), LLURLDispatcherImpl::regionNameCallback, hyper.getSLURLString(), LLUI::sSettingGroups[\"config\"]->getBOOL(\"SLURLTeleportDirectly\"));\t\/\/ don't teleport\n\treturn true;\n}\n\n\/*static*\/\nvoid LLURLDispatcherImpl::regionNameCallback(U64 region_handle, const LLSLURL& slurl, const LLUUID& snapshot_id, bool teleport)\n{\n \n if(slurl.getType() == LLSLURL::LOCATION)\n { \n regionHandleCallback(region_handle, slurl, snapshot_id, teleport);\n }\n}\n\n\/* static *\/\nvoid LLURLDispatcherImpl::regionHandleCallback(U64 region_handle, const LLSLURL& slurl, const LLUUID& snapshot_id, bool teleport)\n{\n \/\/ <FS:AW optional opensim support>\n#ifndef OPENSIM\n \/\/ we can't teleport cross grid at this point\n\tif (LLGridManager::getInstance()->getGrid(slurl.getGrid()) != LLGridManager::getInstance()->getGrid())\n\t{\n\t\tLLSD args;\n\t\targs[\"SLURL\"] = slurl.getLocationString();\n\t\targs[\"CURRENT_GRID\"] = LLGridManager::getInstance()->getGridLabel();\n\t\targs[\"GRID\"] = LLGridManager::getInstance()->getGridLabel(slurl.getGrid());\n\t\tLLNotificationsUtil::add(\"CantTeleportToGrid\", args);\n\t\treturn;\n\t}\n\n#endif \/\/ OPENSIM\n\/\/ <\/FS:AW optional opensim support>\n\n\tLLVector3d global_pos = from_region_handle(region_handle);\n\tglobal_pos += LLVector3d(slurl.getPosition());\n\n\tif (teleport)\n\t{\t\n\t\tgAgent.teleportViaLocation(global_pos);\n\t\tLLFloaterWorldMap* instance = LLFloaterWorldMap::getInstance();\n\t\tif(instance)\n\t\t{\n\t\t\tinstance->trackLocation(global_pos);\n\t\t}\n\t}\n\telse\n\t{\n\t\tLLSD key;\n\t\tkey[\"type\"] = \"remote_place\";\n\t\tkey[\"x\"] = global_pos.mdV[VX];\n\t\tkey[\"y\"] = global_pos.mdV[VY];\n\t\tkey[\"z\"] = global_pos.mdV[VZ];\n\n\t\t\/\/ <FS:Ansariel> FIRE-817: Separate place details floater\n\t\t\/\/LLFloaterSidePanelContainer::showPanel(\"places\", key);\n\t\tif (gSavedSettings.getBOOL(\"FSUseStandalonePlaceDetailsFloater\"))\n\t\t{\n\t\t\tLLFloaterReg::showInstance(\"fs_placedetails\", key);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLLFloaterSidePanelContainer::showPanel(\"places\", key);\n\t\t}\n\t\t\/\/ <\/FS:Ansariel>\n\t}\n}\n\n\/\/---------------------------------------------------------------------------\n\/\/ Teleportation links are handled here because they are tightly coupled\n\/\/ to SLURL parsing and sim-fragment parsing\nclass LLTeleportHandler : public LLCommandHandler\n{\npublic:\n\t\/\/ Teleport requests *must* come from a trusted browser\n\t\/\/ inside the app, otherwise a malicious web page could\n\t\/\/ cause a constant teleport loop. JC\n\tLLTeleportHandler() : LLCommandHandler(\"teleport\", UNTRUSTED_BLOCK) { }\n\n\tbool handle(const LLSD& tokens, const LLSD& query_map,\n\t\t\t\tLLMediaCtrl* web)\n\t{\n\t\t\/\/ construct a \"normal\" SLURL, resolve the region to\n\t\t\/\/ a global position, and teleport to it\n\t\tif (tokens.size() < 1) return false;\n \/\/ <FS:AW optional opensim support>\n#ifdef OPENSIM\n\t\tLLSLURL slurl(tokens, true);\n\n\t\tstd::string grid = slurl.getGrid();\n\t\tstd::string gatekeeper = LLGridManager::getInstance()->getGatekeeper(grid);\n\t\tstd::string region_name = slurl.getRegion();\n\t\tstd::string dest;\n\t\tstd::string current = LLGridManager::getInstance()->getGrid();\n\t\tif((grid != current) && (!LLGridManager::getInstance()->isInOpenSim() || (!slurl.getHypergrid() && gatekeeper.empty())))\n\t\t{\n\t\t\tdest = slurl.getSLURLString();\n\t\t\tif (!dest.empty())\n\t\t\t{\n\t\t\t\tLLSD args;\n\t\t\t\targs[\"SLURL\"] = dest;\n\t\t\t\targs[\"GRID\"] = grid;\n\t\t\t\targs[\"CURRENT_GRID\"] = current;\n\t\t\t\tLLNotificationsUtil::add(\"CantTeleportToGrid\", args);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if(!gatekeeper.empty() && gatekeeper != LLGridManager::getInstance()->getGatekeeper())\n\t\t{\n\t\t\tregion_name = gatekeeper + \":\" + region_name;\n\t\t}\n\n\t\tdest = \"hop:\/\/\" + current + \"\/\" + region_name;\n\n\t\tfor(int i=2; tokens.size() > i; i++)\n\t\t{\n\t\t\tdest.append(\"\/\" + tokens[i].asString());\n\t\t}\n\n\t\tLLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name,\n\t\t\tLLURLDispatcherImpl::regionHandleCallback,\n\t\t\tLLSLURL(dest).getSLURLString(),\n\t\t\ttrue);\t\/\/ teleport\n#else \/\/ OPENSIM\n\t\tLLVector3 coords(128, 128, 0);\n\t\tif (tokens.size() <= 4)\n\t\t{\n\t\t\tcoords = LLVector3(tokens[1].asReal(), \n\t\t\t\t\t\t\t tokens[2].asReal(), \n\t\t\t\t\t\t\t tokens[3].asReal());\n\t\t}\n\t\t\n\t\t\/\/ Region names may be %20 escaped.\n\t\t\n\t\tstd::string region_name = LLURI::unescape(tokens[0]);\n\n\t\tLLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name, LLURLDispatcherImpl::regionHandleCallback, LLSLURL(region_name, coords).getSLURLString(), true);\/\/ teleport\n#endif \/\/ OPENSIM\n\/\/ <\/FS:AW optional opensim support>\n\n\t\treturn true;\n\t}\n};\nLLTeleportHandler gTeleportHandler;\n\n\/\/---------------------------------------------------------------------------\n\n\/\/ static\nbool LLURLDispatcher::dispatch(const std::string& slurl,\n\t\t\t\t\t\t\t const std::string& nav_type,\n\t\t\t\t\t\t\t LLMediaCtrl* web,\n\t\t\t\t\t\t\t bool trusted_browser)\n{\n\treturn LLURLDispatcherImpl::dispatch(LLSLURL(slurl), nav_type, web, trusted_browser);\n}\n\n\/\/ static\nbool LLURLDispatcher::dispatchRightClick(const std::string& slurl)\n{\n\treturn LLURLDispatcherImpl::dispatchRightClick(LLSLURL(slurl));\n}\n\n\/\/ static\nbool LLURLDispatcher::dispatchFromTextEditor(const std::string& slurl)\n{\n\t\/\/ *NOTE: Text editors are considered sources of trusted URLs\n\t\/\/ in order to make avatar profile links in chat history work.\n\t\/\/ While a malicious resident could chat an app SLURL, the\n\t\/\/ receiving resident will see it and must affirmatively\n\t\/\/ click on it.\n\t\/\/ *TODO: Make this trust model more refined. JC\n\tconst bool trusted_browser = true;\n\tLLMediaCtrl* web = NULL;\n\treturn LLURLDispatcherImpl::dispatch(LLSLURL(slurl), \"clicked\", web, trusted_browser);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * For conditions of distribution and use, see copyright notice in license.txt\n *\n * @file EC_Ruler.cpp\n * @brief EC_Ruler enables visual highlighting effect for of scene entity.\n * @note The entity must have EC_OgrePlaceable and EC_OgreMesh (if mesh) or\n * EC_OgreCustomObject (if prim) components available in advance.\n *\/\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n#include \"EC_Ruler.h\"\n#include \"ModuleInterface.h\"\n#include \"Entity.h\"\n#include \"Renderer.h\"\n#include \"OgreMaterialUtils.h\"\n#include \"EC_OgrePlaceable.h\"\n#include \"EC_OgreMesh.h\"\n#include \"EC_OgreCustomObject.h\"\n#include \"LoggingFunctions.h\"\n#include <Ogre.h>\n\nDEFINE_POCO_LOGGING_FUNCTIONS(\"EC_Ruler\")\n\n#include \"MemoryLeakCheck.h\"\n\nEC_Ruler::EC_Ruler(Foundation::ModuleInterface *module) :\n Foundation::ComponentInterface(module->GetFramework()),\n typeAttr_(this, \"ruler type\", EC_Ruler::Rotation),\n visibleAttr_(this, \"visible\", false),\n axisAttr_(this, \"axis\", EC_Ruler::X),\n localAttr_(this, \"local\", false),\n radiusAttr_(this, \"radius\", 5),\n segmentsAttr_(this, \"segments\", 29),\n rulerObject(0),\n sceneNode_(0),\n type(EC_Ruler::Rotation)\n{\n renderer_ = module->GetFramework()->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer);\n \n QObject::connect(this, SIGNAL(OnChanged()), this, SLOT(UpdateRuler()));\n}\n\nEC_Ruler::~EC_Ruler()\n{\n \/\/ OgreRendering module might be already deleted. If so, the cloned entity is also already deleted.\n \/\/ In this case, just set pointer to 0.\n if (!renderer_.expired())\n {\n Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();\n sceneMgr->destroyManualObject(rulerObject);\n }\n else\n {\n rulerObject = 0;\n sceneNode_ = 0;\n }\n}\n\nvoid EC_Ruler::Show()\n{\n if (!rulerObject)\n Create();\n\n if (!rulerObject)\n {\n LogError(\"EC_Ruler not initialized properly.\");\n return;\n }\n\n if (rulerObject)\n rulerObject->setVisible(true);\n}\n\nvoid EC_Ruler::Hide()\n{\n if (!rulerObject)\n Create();\n \n if (!rulerObject)\n {\n LogError(\"EC_Ruler not initialized properly.\");\n return;\n }\n \n if (rulerObject)\n rulerObject->setVisible(false);\n}\n\nbool EC_Ruler::IsVisible() const\n{\n if (rulerObject)\n return rulerObject->isVisible();\n\n return false;\n}\n\nvoid EC_Ruler::Create()\n{\n if (renderer_.expired())\n return;\n\n Ogre::SceneManager *scene_mgr= renderer_.lock()->GetSceneManager();\n assert(scene_mgr);\n if (!scene_mgr)\n return;\n\n Scene::Entity *entity = GetParentEntity();\n assert(entity);\n if (!entity)\n return;\n\n OgreRenderer::EC_OgrePlaceable *placeable = entity->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();\n assert(placeable);\n if (!placeable)\n return;\n sceneNode_ = placeable->GetSceneNode();\n\n assert(sceneNode_);\n if (!sceneNode_)\n return;\n \n if(scene_mgr->hasManualObject(\"translateRuler\")){\n rulerObject = scene_mgr->getManualObject(\"translateRuler\");\n if(rulerObject->isAttached())\n#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1\n rulerObject->detatchFromParent();\n#else\n rulerObject->detachFromParent();\n#endif\n } else {\n rulerObject = scene_mgr->createManualObject(\"translateRuler\");\n }\n \n switch(typeAttr_.Get()) {\n case EC_Ruler::Rotation:\n SetupRotationRuler();\n break;\n case EC_Ruler::Translation:\n SetupTranslateRuler();\n break;\n case EC_Ruler::Scale:\n SetupScaleRuler();\n break;\n }\n\n if(localAttr_.Get()) {\n sceneNode_->attachObject(rulerObject);\n } else {\n \/\/ get translateNode only when we are working in world space\n if(scene_mgr->hasSceneNode(\"translateNode\")) {\n globalSceneNode = scene_mgr->getSceneNode(\"translateNode\");\n } else {\n globalSceneNode = scene_mgr->getRootSceneNode()->createChildSceneNode(\"translateNode\");\n globalSceneNode->setVisible(true);\n }\n assert(globalSceneNode);\n if(!globalSceneNode)\n return;\n \n globalSceneNode->setPosition(sceneNode_->getParent()->getPosition());\n globalSceneNode->attachObject(rulerObject);\n }\n}\n\nvoid EC_Ruler::SetupScaleRuler()\n{\n if(!rulerObject)\n return;\n \n float x, y, z;\n x = y = z = 0;\n \n float size = radiusAttr_.Get();\n\n switch(axisAttr_.Get()) {\n case EC_Ruler::X:\n x = size;\n break;\n case EC_Ruler::Y:\n y = size;\n break;\n case EC_Ruler::Z:\n z = size;\n break;\n default:\n x = size;\n y = size;\n }\n rulerObject->clear();\n rulerObject->begin(\"BaseWhiteNoLighting\", Ogre::RenderOperation::OT_LINE_LIST);\n rulerObject->position(0, 0, 0);\n rulerObject->position(x, y, z);\n rulerObject->end();\n}\n\nvoid EC_Ruler::SetupRotationRuler()\n{\n if(!rulerObject)\n return;\n float const radius = radiusAttr_.Get();\n float const segments = segmentsAttr_.Get();\n\n rulerObject->clear();\n rulerObject->begin(\"BaseWhiteNoLighting\", Ogre::RenderOperation::OT_LINE_STRIP);\n\n unsigned i = 0;\n for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI \/ segments) {\n switch(axisAttr_.Get()) {\n case EC_Ruler::X:\n rulerObject->position(0, radius * cos(theta), radius * sin(theta));\n break;\n case EC_Ruler::Y:\n rulerObject->position(radius * cos(theta), radius * sin(theta), 0);\n break;\n case EC_Ruler::Z:\n rulerObject->position(radius * cos(theta), 0, radius * sin(theta));\n break;\n }\n rulerObject->index(i++);\n }\n rulerObject->index(0); \/\/ Close the line = circle\n rulerObject->end();\n}\n\nvoid EC_Ruler::SetupTranslateRuler() {\n if(!rulerObject)\n return;\n\n float x, y, z;\n x = y = z = 0;\n \n float size = radiusAttr_.Get();\n\n \/\/ Note, this arbitrary order is result from Py Code\n \/\/ TODO: Fix this to something more unified (0 = x, 1 = y, 2 = z) throughout\n \/\/ manipulator widget code\n switch(axisAttr_.Get()) {\n case EC_Ruler::X:\n x = size;\n break;\n case EC_Ruler::Y:\n y = size;\n break;\n case EC_Ruler::Z:\n z = size;\n break;\n default:\n x = size;\n y = size;\n }\n rulerObject->clear();\n rulerObject->begin(\"BaseWhiteNoLighting\", Ogre::RenderOperation::OT_LINE_LIST);\n rulerObject->position(x, y, z);\n rulerObject->position(-x, -y, -z);\n rulerObject->end();\n}\n\nvoid EC_Ruler::SetType(EC_Ruler::Type type) {\n}\n\nvoid EC_Ruler::StartDrag() {}\n\nvoid EC_Ruler::EndDrag() {}\n\nvoid EC_Ruler::UpdateRuler() {\n Create();\n \n if(visibleAttr_.Get()) {\n Show();\n } else {\n Hide();\n }\n}\n\n<commit_msg>Disable shadows on transform rulers.<commit_after>\/**\n * For conditions of distribution and use, see copyright notice in license.txt\n *\n * @file EC_Ruler.cpp\n * @brief EC_Ruler enables visual highlighting effect for of scene entity.\n * @note The entity must have EC_OgrePlaceable and EC_OgreMesh (if mesh) or\n * EC_OgreCustomObject (if prim) components available in advance.\n *\/\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n#include \"EC_Ruler.h\"\n#include \"ModuleInterface.h\"\n#include \"Entity.h\"\n#include \"Renderer.h\"\n#include \"OgreMaterialUtils.h\"\n#include \"EC_OgrePlaceable.h\"\n#include \"EC_OgreMesh.h\"\n#include \"EC_OgreCustomObject.h\"\n#include \"LoggingFunctions.h\"\n#include <Ogre.h>\n\nDEFINE_POCO_LOGGING_FUNCTIONS(\"EC_Ruler\")\n\n#include \"MemoryLeakCheck.h\"\n\nEC_Ruler::EC_Ruler(Foundation::ModuleInterface *module) :\n Foundation::ComponentInterface(module->GetFramework()),\n typeAttr_(this, \"ruler type\", EC_Ruler::Rotation),\n visibleAttr_(this, \"visible\", false),\n axisAttr_(this, \"axis\", EC_Ruler::X),\n localAttr_(this, \"local\", false),\n radiusAttr_(this, \"radius\", 5),\n segmentsAttr_(this, \"segments\", 29),\n rulerObject(0),\n sceneNode_(0),\n type(EC_Ruler::Rotation)\n{\n renderer_ = module->GetFramework()->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer);\n \n QObject::connect(this, SIGNAL(OnChanged()), this, SLOT(UpdateRuler()));\n}\n\nEC_Ruler::~EC_Ruler()\n{\n \/\/ OgreRendering module might be already deleted. If so, the cloned entity is also already deleted.\n \/\/ In this case, just set pointer to 0.\n if (!renderer_.expired())\n {\n Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();\n sceneMgr->destroyManualObject(rulerObject);\n }\n else\n {\n rulerObject = 0;\n sceneNode_ = 0;\n }\n}\n\nvoid EC_Ruler::Show()\n{\n if (!rulerObject)\n Create();\n\n if (!rulerObject)\n {\n LogError(\"EC_Ruler not initialized properly.\");\n return;\n }\n\n if (rulerObject)\n rulerObject->setVisible(true);\n}\n\nvoid EC_Ruler::Hide()\n{\n if (!rulerObject)\n Create();\n \n if (!rulerObject)\n {\n LogError(\"EC_Ruler not initialized properly.\");\n return;\n }\n \n if (rulerObject)\n rulerObject->setVisible(false);\n}\n\nbool EC_Ruler::IsVisible() const\n{\n if (rulerObject)\n return rulerObject->isVisible();\n\n return false;\n}\n\nvoid EC_Ruler::Create()\n{\n if (renderer_.expired())\n return;\n\n Ogre::SceneManager *scene_mgr= renderer_.lock()->GetSceneManager();\n assert(scene_mgr);\n if (!scene_mgr)\n return;\n\n Scene::Entity *entity = GetParentEntity();\n assert(entity);\n if (!entity)\n return;\n\n OgreRenderer::EC_OgrePlaceable *placeable = entity->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();\n assert(placeable);\n if (!placeable)\n return;\n sceneNode_ = placeable->GetSceneNode();\n\n assert(sceneNode_);\n if (!sceneNode_)\n return;\n \n if(scene_mgr->hasManualObject(\"translateRuler\")){\n rulerObject = scene_mgr->getManualObject(\"translateRuler\");\n if(rulerObject->isAttached())\n#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1\n rulerObject->detatchFromParent();\n#else\n rulerObject->detachFromParent();\n#endif\n } else {\n rulerObject = scene_mgr->createManualObject(\"translateRuler\");\n }\n \n switch(typeAttr_.Get()) {\n case EC_Ruler::Rotation:\n SetupRotationRuler();\n break;\n case EC_Ruler::Translation:\n SetupTranslateRuler();\n break;\n case EC_Ruler::Scale:\n SetupScaleRuler();\n break;\n }\n\n if(localAttr_.Get()) {\n sceneNode_->attachObject(rulerObject);\n } else {\n \/\/ get translateNode only when we are working in world space\n if(scene_mgr->hasSceneNode(\"translateNode\")) {\n globalSceneNode = scene_mgr->getSceneNode(\"translateNode\");\n } else {\n globalSceneNode = scene_mgr->getRootSceneNode()->createChildSceneNode(\"translateNode\");\n globalSceneNode->setVisible(true);\n }\n assert(globalSceneNode);\n if(!globalSceneNode)\n return;\n \n globalSceneNode->setPosition(sceneNode_->getParent()->getPosition());\n globalSceneNode->attachObject(rulerObject);\n }\n}\n\nvoid EC_Ruler::SetupScaleRuler()\n{\n if(!rulerObject)\n return;\n \n float x, y, z;\n x = y = z = 0;\n \n float size = radiusAttr_.Get();\n\n switch(axisAttr_.Get()) {\n case EC_Ruler::X:\n x = size;\n break;\n case EC_Ruler::Y:\n y = size;\n break;\n case EC_Ruler::Z:\n z = size;\n break;\n default:\n x = size;\n y = size;\n }\n rulerObject->clear();\n rulerObject->setCastShadows(false);\n rulerObject->begin(\"BaseWhiteNoLighting\", Ogre::RenderOperation::OT_LINE_LIST);\n rulerObject->position(0, 0, 0);\n rulerObject->position(x, y, z);\n rulerObject->end();\n}\n\nvoid EC_Ruler::SetupRotationRuler()\n{\n if(!rulerObject)\n return;\n float const radius = radiusAttr_.Get();\n float const segments = segmentsAttr_.Get();\n\n rulerObject->clear();\n rulerObject->setCastShadows(false);\n rulerObject->begin(\"BaseWhiteNoLighting\", Ogre::RenderOperation::OT_LINE_STRIP);\n\n unsigned i = 0;\n for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI \/ segments) {\n switch(axisAttr_.Get()) {\n case EC_Ruler::X:\n rulerObject->position(0, radius * cos(theta), radius * sin(theta));\n break;\n case EC_Ruler::Y:\n rulerObject->position(radius * cos(theta), radius * sin(theta), 0);\n break;\n case EC_Ruler::Z:\n rulerObject->position(radius * cos(theta), 0, radius * sin(theta));\n break;\n }\n rulerObject->index(i++);\n }\n rulerObject->index(0); \/\/ Close the line = circle\n rulerObject->end();\n}\n\nvoid EC_Ruler::SetupTranslateRuler() {\n if(!rulerObject)\n return;\n\n float x, y, z;\n x = y = z = 0;\n \n float size = radiusAttr_.Get();\n\n \/\/ Note, this arbitrary order is result from Py Code\n \/\/ TODO: Fix this to something more unified (0 = x, 1 = y, 2 = z) throughout\n \/\/ manipulator widget code\n switch(axisAttr_.Get()) {\n case EC_Ruler::X:\n x = size;\n break;\n case EC_Ruler::Y:\n y = size;\n break;\n case EC_Ruler::Z:\n z = size;\n break;\n default:\n x = size;\n y = size;\n }\n rulerObject->clear();\n rulerObject->setCastShadows(false);\n rulerObject->begin(\"BaseWhiteNoLighting\", Ogre::RenderOperation::OT_LINE_LIST);\n rulerObject->position(x, y, z);\n rulerObject->position(-x, -y, -z);\n rulerObject->end();\n}\n\nvoid EC_Ruler::SetType(EC_Ruler::Type type) {\n}\n\nvoid EC_Ruler::StartDrag() {}\n\nvoid EC_Ruler::EndDrag() {}\n\nvoid EC_Ruler::UpdateRuler() {\n Create();\n \n if(visibleAttr_.Get()) {\n Show();\n } else {\n Hide();\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Siconos-sample , Copyright INRIA 2005-2011.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a 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 * Siconos 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 Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY vincent.acary@inrialpes.fr\n *\/\n\n\/*!\\file Disks.cpp\n\n Some Disks (2D), friction, and walls.\n Direct description of the model without XML input. Simulation with\n a Time-Stepping scheme.\n*\/\n\n\/\/ Siconos\n#include <SiconosPointers.hpp>\n\n#include <TimeStepping.hpp>\n#include <FrictionContact.hpp>\n#include <MoreauJeanOSI.hpp>\n#include <NewtonImpactFrictionNSL.hpp>\n\/\/#include <Siconos\/IO\/SiconosRestart.hpp>\n\n#include \"Disks.hpp\"\n\n#include <Disk.hpp>\n#include <Circle.hpp>\n#include <DiskPlanR.hpp>\n#include <SpaceFilter.hpp>\n\n\nusing namespace std;\n\n\/* do nothing if solver does not converge *\/\nvoid localCheckSolverOuput(int, Simulation*)\n{};\n\ndouble A(double t)\n{\n return 0. ;\n}\ndouble B(double t)\n{\n return 1. ;\n}\ndouble C(double t)\n{\n return 0.0;\/\/1.1*cos(32.*M_PI*t) ;\n}\ndouble DA(double t)\n{\n return 0. ;\n}\ndouble DB(double t)\n{\n return 0. ;\n}\ndouble DC(double t)\n{\n return 0.0;\/\/-1.1*32.*M_PI*sin(32.*M_PI*t) ;\n}\n\n\n\/\/ ================= Creation of the model =======================\nvoid Disks::init()\n{\n\n SP::TimeDiscretisation timedisc_;\n SP::TimeStepping simulation_;\n SP::FrictionContact osnspb_;\n\n \/\/ User-defined main parameters\n\n double t0 = 0; \/\/ initial computation time\n\n double T = std::numeric_limits<double>::infinity();\n\n double h = 0.01; \/\/ time step\n double g = 9.81;\n\n double theta = 0.5; \/\/ theta for MoreauJeanOSI integrator\n\n std::string solverName = \"NSGS\";\n\n \/\/ -----------------------------------------\n \/\/ --- Dynamical systems && interactions ---\n \/\/ -----------------------------------------\n\n double R;\n double m;\n\n try\n {\n\n \/\/ ------------\n \/\/ --- Init ---\n \/\/ ------------\n\n std::cout << \"====> Model loading ...\" << std::endl << std::endl;\n\n _plans.reset(new SimpleMatrix(\"plans.dat\", true));\n if (_plans->size(0) == 0)\n {\n \/* default plans *\/\n double A1 = P1A;\n double B1 = P1B;\n double C1 = P1C;\n\n double A2 = P2A;\n double B2 = P2B;\n double C2 = P2C;\n\n _plans.reset(new SimpleMatrix(6, 6));\n _plans->zero();\n (*_plans)(0, 0) = 0;\n (*_plans)(0, 1) = 1;\n (*_plans)(0, 2) = -GROUND;\n\n (*_plans)(1, 0) = 1;\n (*_plans)(1, 1) = 0;\n (*_plans)(1, 2) = WALL;\n\n (*_plans)(2, 0) = 1;\n (*_plans)(2, 1) = 0;\n (*_plans)(2, 2) = -WALL;\n\n (*_plans)(3, 0) = 0;\n (*_plans)(3, 1) = 1;\n (*_plans)(3, 2) = -TOP;\n\n (*_plans)(4, 0) = A1;\n (*_plans)(4, 1) = B1;\n (*_plans)(4, 2) = C1;\n\n (*_plans)(5, 0) = A2;\n (*_plans)(5, 1) = B2;\n (*_plans)(5, 2) = C2;\n\n }\n\n \/* set center positions *\/\n for (unsigned int i = 0 ; i < _plans->size(0); ++i)\n {\n SP::DiskPlanR tmpr;\n tmpr.reset(new DiskPlanR(1, (*_plans)(i, 0), (*_plans)(i, 1), (*_plans)(i, 2),\n (*_plans)(i, 3), (*_plans)(i, 4), (*_plans)(i, 5)));\n (*_plans)(i, 3) = tmpr->getXCenter();\n (*_plans)(i, 4) = tmpr->getYCenter();\n }\n\n \/* _moving_plans.reset(new FMatrix(1,6));\n (*_moving_plans)(0,0) = &A;\n (*_moving_plans)(0,1) = &B;\n (*_moving_plans)(0,2) = &C;\n (*_moving_plans)(0,3) = &DA;\n (*_moving_plans)(0,4) = &DB;\n (*_moving_plans)(0,5) = &DC;*\/\n\n\n\n SP::SiconosMatrix Disks;\n Disks.reset(new SimpleMatrix(\"disks.dat\", true));\n\n \/\/ -- OneStepIntegrators --\n SP::OneStepIntegrator osi;\n osi.reset(new MoreauJeanOSI(theta));\n\n \/\/ -- Model --\n _model.reset(new Model(t0, T));\n\n for (unsigned int i = 0; i < Disks->size(0); i++)\n {\n R = Disks->getValue(i, 2);\n m = Disks->getValue(i, 3);\n\n SP::SiconosVector qTmp;\n SP::SiconosVector vTmp;\n\n qTmp.reset(new SiconosVector(NDOF));\n vTmp.reset(new SiconosVector(NDOF));\n vTmp->zero();\n (*qTmp)(0) = (*Disks)(i, 0);\n (*qTmp)(1) = (*Disks)(i, 1);\n\n SP::LagrangianDS body;\n if (R > 0)\n body.reset(new Disk(R, m, qTmp, vTmp));\n else\n body.reset(new Circle(-R, m, qTmp, vTmp));\n\n \/\/ -- Set external forces (weight) --\n SP::SiconosVector FExt;\n FExt.reset(new SiconosVector(NDOF));\n FExt->zero();\n FExt->setValue(1, -m * g);\n body->setFExtPtr(FExt);\n\n \/\/ add the dynamical system to the one step integrator\n osi->insertDynamicalSystem(body);\n\n \/\/ add the dynamical system in the non smooth dynamical system\n _model->nonSmoothDynamicalSystem()->insertDynamicalSystem(body);\n\n }\n\n\n _model->nonSmoothDynamicalSystem()->setSymmetric(true);\n\n\n \/\/ ------------------\n \/\/ --- Simulation ---\n \/\/ ------------------\n\n \/\/ -- Time discretisation --\n timedisc_.reset(new TimeDiscretisation(t0, h));\n\n \/\/ -- OneStepNsProblem --\n osnspb_.reset(new FrictionContact(2));\n\n osnspb_->numericsSolverOptions()->iparam[0] = 100; \/\/ Max number of\n \/\/ iterations\n osnspb_->numericsSolverOptions()->iparam[1] = 20; \/\/ compute error\n \/\/ iterations\n osnspb_->numericsSolverOptions()->dparam[0] = 1e-3; \/\/ Tolerance\n\n\n osnspb_->setMaxSize(6 * ((3 * Ll * Ll + 3 * Ll) \/ 2 - Ll));\n osnspb_->setMStorageType(1); \/\/ Sparse storage\n osnspb_->setNumericsVerboseMode(0);\n\n osnspb_->setKeepLambdaAndYState(true); \/\/ inject previous solution\n\n \/\/ -- Simulation --\n simulation_.reset(new TimeStepping(timedisc_));\n\n std11::static_pointer_cast<TimeStepping>(simulation_)->setNewtonMaxIteration(3);\n\n simulation_->insertIntegrator(osi);\n simulation_->insertNonSmoothProblem(osnspb_);\n\n simulation_->setCheckSolverFunction(localCheckSolverOuput);\n\n \/\/ --- Simulation initialization ---\n\n std::cout << \"====> Simulation initialisation ...\" << std::endl << std::endl;\n\n SP::NonSmoothLaw nslaw(new NewtonImpactFrictionNSL(0, 0, 0.3, 2));\n\n _playground.reset(new SpaceFilter(3, 6, _model, nslaw, _plans, _moving_plans));\n\n _model->initialize(simulation_);\n\n }\n\n catch (SiconosException e)\n {\n std::cout << e.report() << std::endl;\n exit(1);\n }\n catch (...)\n {\n std::cout << \"Exception caught in Disks::init()\" << std::endl;\n exit(1);\n }\n}\n\n\n\n\n\n\/\/ =========================== End of model definition ===========================\n\n\/\/ ================================= Computation =================================\n\nvoid Disks::compute()\n{\n try\n {\n\n _playground->buildInteractions(_model->currentTime());\n\n _model->simulation()->advanceToEvent();\n\n _model->simulation()->processEvents();\n\n \/\/ Siconos::save(_model, \"Disks.bin\");\n\n }\n\n catch (SiconosException e)\n {\n std::cout << e.report() << std::endl;\n }\n catch (...)\n {\n std::cout << \"Exception caught in SiconosBodies::compute()\" << std::endl;\n }\n}\n<commit_msg>Update Disks example<commit_after>\/* Siconos-sample , Copyright INRIA 2005-2011.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a 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 * Siconos 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 Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY vincent.acary@inrialpes.fr\n *\/\n\n\/*!\\file Disks.cpp\n\n Some Disks (2D), friction, and walls.\n Direct description of the model without XML input. Simulation with\n a Time-Stepping scheme.\n*\/\n\n\/\/ Siconos\n#include <SiconosPointers.hpp>\n\n#include <TimeStepping.hpp>\n#include <FrictionContact.hpp>\n#include <MoreauJeanOSI.hpp>\n#include <NewtonImpactFrictionNSL.hpp>\n\/\/#include <Siconos\/IO\/SiconosRestart.hpp>\n\n#include \"Disks.hpp\"\n#include \"Model.hpp\"\n#include \"NonSmoothDynamicalSystem.hpp\"\n#include \"TimeDiscretisation.hpp\"\n#include <Disk.hpp>\n#include <Circle.hpp>\n#include <DiskPlanR.hpp>\n#include <SpaceFilter.hpp>\n\n\nusing namespace std;\n\n\/* do nothing if solver does not converge *\/\nvoid localCheckSolverOuput(int, Simulation*)\n{};\n\ndouble A(double t)\n{\n return 0. ;\n}\ndouble B(double t)\n{\n return 1. ;\n}\ndouble C(double t)\n{\n return 0.0;\/\/1.1*cos(32.*M_PI*t) ;\n}\ndouble DA(double t)\n{\n return 0. ;\n}\ndouble DB(double t)\n{\n return 0. ;\n}\ndouble DC(double t)\n{\n return 0.0;\/\/-1.1*32.*M_PI*sin(32.*M_PI*t) ;\n}\n\n\n\/\/ ================= Creation of the model =======================\nvoid Disks::init()\n{\n\n SP::TimeDiscretisation timedisc_;\n SP::TimeStepping simulation_;\n SP::FrictionContact osnspb_;\n\n \/\/ User-defined main parameters\n\n double t0 = 0; \/\/ initial computation time\n\n double T = std::numeric_limits<double>::infinity();\n\n double h = 0.01; \/\/ time step\n double g = 9.81;\n\n double theta = 0.5; \/\/ theta for MoreauJeanOSI integrator\n\n std::string solverName = \"NSGS\";\n\n \/\/ -----------------------------------------\n \/\/ --- Dynamical systems && interactions ---\n \/\/ -----------------------------------------\n\n double R;\n double m;\n\n try\n {\n\n \/\/ ------------\n \/\/ --- Init ---\n \/\/ ------------\n\n std::cout << \"====> Model loading ...\" << std::endl << std::endl;\n\n _plans.reset(new SimpleMatrix(\"plans.dat\", true));\n if (_plans->size(0) == 0)\n {\n \/* default plans *\/\n double A1 = P1A;\n double B1 = P1B;\n double C1 = P1C;\n\n double A2 = P2A;\n double B2 = P2B;\n double C2 = P2C;\n\n _plans.reset(new SimpleMatrix(6, 6));\n _plans->zero();\n (*_plans)(0, 0) = 0;\n (*_plans)(0, 1) = 1;\n (*_plans)(0, 2) = -GROUND;\n\n (*_plans)(1, 0) = 1;\n (*_plans)(1, 1) = 0;\n (*_plans)(1, 2) = WALL;\n\n (*_plans)(2, 0) = 1;\n (*_plans)(2, 1) = 0;\n (*_plans)(2, 2) = -WALL;\n\n (*_plans)(3, 0) = 0;\n (*_plans)(3, 1) = 1;\n (*_plans)(3, 2) = -TOP;\n\n (*_plans)(4, 0) = A1;\n (*_plans)(4, 1) = B1;\n (*_plans)(4, 2) = C1;\n\n (*_plans)(5, 0) = A2;\n (*_plans)(5, 1) = B2;\n (*_plans)(5, 2) = C2;\n\n }\n\n \/* set center positions *\/\n for (unsigned int i = 0 ; i < _plans->size(0); ++i)\n {\n SP::DiskPlanR tmpr;\n tmpr.reset(new DiskPlanR(1, (*_plans)(i, 0), (*_plans)(i, 1), (*_plans)(i, 2),\n (*_plans)(i, 3), (*_plans)(i, 4), (*_plans)(i, 5)));\n (*_plans)(i, 3) = tmpr->getXCenter();\n (*_plans)(i, 4) = tmpr->getYCenter();\n }\n\n \/* _moving_plans.reset(new FMatrix(1,6));\n (*_moving_plans)(0,0) = &A;\n (*_moving_plans)(0,1) = &B;\n (*_moving_plans)(0,2) = &C;\n (*_moving_plans)(0,3) = &DA;\n (*_moving_plans)(0,4) = &DB;\n (*_moving_plans)(0,5) = &DC;*\/\n\n\n\n SP::SiconosMatrix Disks;\n Disks.reset(new SimpleMatrix(\"disks.dat\", true));\n\n \/\/ -- OneStepIntegrators --\n SP::OneStepIntegrator osi;\n osi.reset(new MoreauJeanOSI(theta));\n\n \/\/ -- Model --\n _model.reset(new Model(t0, T));\n\n for (unsigned int i = 0; i < Disks->size(0); i++)\n {\n R = Disks->getValue(i, 2);\n m = Disks->getValue(i, 3);\n\n SP::SiconosVector qTmp;\n SP::SiconosVector vTmp;\n\n qTmp.reset(new SiconosVector(NDOF));\n vTmp.reset(new SiconosVector(NDOF));\n vTmp->zero();\n (*qTmp)(0) = (*Disks)(i, 0);\n (*qTmp)(1) = (*Disks)(i, 1);\n\n SP::LagrangianDS body;\n if (R > 0)\n body.reset(new Disk(R, m, qTmp, vTmp));\n else\n body.reset(new Circle(-R, m, qTmp, vTmp));\n\n \/\/ -- Set external forces (weight) --\n SP::SiconosVector FExt;\n FExt.reset(new SiconosVector(NDOF));\n FExt->zero();\n FExt->setValue(1, -m * g);\n body->setFExtPtr(FExt);\n\n \/\/ add the dynamical system to the one step integrator\n osi->insertDynamicalSystem(body);\n\n \/\/ add the dynamical system in the non smooth dynamical system\n _model->nonSmoothDynamicalSystem()->insertDynamicalSystem(body);\n\n }\n\n\n _model->nonSmoothDynamicalSystem()->setSymmetric(true);\n\n\n \/\/ ------------------\n \/\/ --- Simulation ---\n \/\/ ------------------\n\n \/\/ -- Time discretisation --\n timedisc_.reset(new TimeDiscretisation(t0, h));\n\n \/\/ -- OneStepNsProblem --\n osnspb_.reset(new FrictionContact(2));\n\n osnspb_->numericsSolverOptions()->iparam[0] = 100; \/\/ Max number of\n \/\/ iterations\n osnspb_->numericsSolverOptions()->iparam[1] = 20; \/\/ compute error\n \/\/ iterations\n osnspb_->numericsSolverOptions()->dparam[0] = 1e-3; \/\/ Tolerance\n\n\n osnspb_->setMaxSize(6 * ((3 * Ll * Ll + 3 * Ll) \/ 2 - Ll));\n osnspb_->setMStorageType(1); \/\/ Sparse storage\n osnspb_->setNumericsVerboseMode(0);\n\n osnspb_->setKeepLambdaAndYState(true); \/\/ inject previous solution\n\n \/\/ -- Simulation --\n simulation_.reset(new TimeStepping(timedisc_));\n\n std11::static_pointer_cast<TimeStepping>(simulation_)->setNewtonMaxIteration(3);\n\n simulation_->insertIntegrator(osi);\n simulation_->insertNonSmoothProblem(osnspb_);\n\n simulation_->setCheckSolverFunction(localCheckSolverOuput);\n\n \/\/ --- Simulation initialization ---\n\n std::cout << \"====> Simulation initialisation ...\" << std::endl << std::endl;\n\n SP::NonSmoothLaw nslaw(new NewtonImpactFrictionNSL(0, 0, 0.3, 2));\n\n _playground.reset(new SpaceFilter(3, 6, _model, nslaw, _plans, _moving_plans));\n\n _model->initialize(simulation_);\n\n }\n\n catch (SiconosException e)\n {\n std::cout << e.report() << std::endl;\n exit(1);\n }\n catch (...)\n {\n std::cout << \"Exception caught in Disks::init()\" << std::endl;\n exit(1);\n }\n}\n\n\n\n\n\n\/\/ =========================== End of model definition ===========================\n\n\/\/ ================================= Computation =================================\n\nvoid Disks::compute()\n{\n try\n {\n\n _playground->buildInteractions(_model->currentTime());\n\n _model->simulation()->advanceToEvent();\n\n _model->simulation()->processEvents();\n\n \/\/ Siconos::save(_model, \"Disks.bin\");\n\n }\n\n catch (SiconosException e)\n {\n std::cout << e.report() << std::endl;\n }\n catch (...)\n {\n std::cout << \"Exception caught in SiconosBodies::compute()\" << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <bits\/stdc++.h>\nusing namespace std;\n\nvoid insertionSort(int array[], int size)\n{\n\tint i = 0, j = 0, tempElement = 0, tempIndex = 0, flag = 0;\n\tfor (i = 1; i < size; i++)\n\t{\n\t\ttempElement = array[i];\n\t\tfor (j = i - 1; j >= 0; j--)\n\t\t{\n\t\t\tif (array[j] > tempElement)\n\t\t\t\tarray[j + 1] = array[j];\n\t\t\telse\n\t\t\t\tflag = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (flag == 1 || j == -1)\n\t\t{\n\t\t\tflag = 0;\n\t\t\tarray[j + 1] = tempElement;\n\t\t}\n\t}\n}\n\nvoid display(int array[], int size)\n{\n\tint i = 0;\n\tfor (i = 0; i < size; i++)\n\t\tcout << array[i] << \" \";\n\tcout << endl;\n}\n\nint main()\n{\n\tint array[] = {5, 4, 233, 32, 1, 4, 34, 3, 23};\n\tint size = sizeof(array) \/ sizeof(array[0]);\n\tcout << \"unsorted array is :\" << endl;\n\tdisplay(array, size);\n\tinsertionSort(array, size);\n\tcout << \"sorted array is :\" << endl;\n\tdisplay(array, size);\n}\n<commit_msg>minute changes updated comments<commit_after>#include <bits\/stdc++.h>\nusing namespace std;\n\nvoid insertionSort(int array[], int size)\n{\n\tint i = 0, j = 0, tempElement = 0, tempIndex = 0, flag = 0;\n\tfor (i = 1; i < size; i++)\n\t{\n\t\ttempElement = array[i]; \/\/taking an array element into tempElement\n\t\tfor (j = i - 1; j >= 0; j--)\n\t\t{\n\t\t\tif (array[j] > tempElement)\n\t\t\t\tarray[j + 1] = array[j];\n\t\t\telse\n\t\t\t\tflag = 1; \/\/checking if we got the correct position of tempElement\n\t\t\tbreak;\n\t\t}\n\t\tif (flag == 1 || j == -1) \/\/condition checking if we got correct position of tempElement or not\n\t\t{\n\t\t\tflag = 0;\n\t\t\tarray[j + 1] = tempElement; \/\/putting tempElement to it correct position\n\t\t}\n\t}\n}\n\nvoid display(int array[], int size)\n{\n\tint i = 0;\n\tfor (i = 0; i < size; i++)\n\t\tcout << array[i] << \" \";\n\tcout << endl;\n}\n\nint main()\n{\n\tint array[] = {5, 4, 233, 32, 1, 4, 34, 3, 23};\n\tint size = sizeof(array) \/ sizeof(array[0]);\n\tcout << \"unsorted array is :\" << endl;\n\tdisplay(array, size); \/\/display unsorted array\n\tinsertionSort(array, size);\n\tcout << \"sorted array is :\" << endl;\n\tdisplay(array, size); \/\/display the sorted array\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n**\n** Author(s):\n** - Pierre ROULLON <proullon@aldebaran-robotics.com>\n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include <qi\/log.hpp>\n#include <qitype\/signature.hpp>\n#include <qitype\/genericobjectbuilder.hpp>\n#include <qitype\/genericobject.hpp>\n#include <qitype\/genericvalue.hpp>\n#include <qitype\/typedispatcher.hpp>\n#include <qitype\/type.hpp>\n\n#include <jnitools.hpp>\n#include <jobjectconverter.hpp>\n#include <map_jni.hpp>\n#include <list_jni.hpp>\n#include <tuple_jni.hpp>\n\nusing namespace qi;\n\nstruct toJObject\n{\n toJObject(jobject *result)\n : result(result), jni_version(QI_JNI_MIN_VERSION)\n {\n if (JVM()->GetEnv((void **) &env, jni_version) != JNI_OK)\n qiLogFatal(\"qimessaging.jni\") << \"Cannot initialize Java environment.\";\n }\n\n void visitUnknown(qi::GenericValuePtr value)\n {\n throwJavaError(env, \"Error in conversion: Unable to convert unknown type in Java\");\n }\n\n void visitInt(qi::int64_t value, bool isSigned, int byteSize)\n {\n \/\/ Clear all remaining exceptions\n env->ExceptionClear();\n\n \/\/ Get Integer class template\n \/\/ ... or Boolean if byteSize is 0\n jclass cls = env->FindClass(byteSize == 0 ? \"java\/lang\/Boolean\" : \"java\/lang\/Integer\");\n if (env->ExceptionCheck())\n {\n throwJavaError(env, \"GenericValue to Integer : FindClass error\");\n return;\n }\n\n \/\/ Find constructor method ID\n jmethodID mid = env->GetMethodID(cls, \"<init>\", byteSize == 0 ? \"(Z)V\" : \"(I)V\");\n if (!mid)\n {\n env->DeleteLocalRef(cls);\n throwJavaError(env, \"GenericValue to Integer : GetMethodID error\");\n return;\n }\n\n \/\/ Instanciate new Integer, yeah !\n jint jval = value;\n *result = env->NewObject(cls, mid, jval);\n checkForError();\n env->DeleteLocalRef(cls);\n }\n\n void visitString(char *data, size_t len)\/\/qi::TypeString* type, void* storage)\n {\n if (data)\n *result = (jobject) env->NewStringUTF(data);\n else\n *result = (jobject) env->NewStringUTF(\"\");\n checkForError();\n }\n\n void visitVoid()\n {\n jclass cls = env->FindClass(\"java\/lang\/Void\");\n jmethodID mid = env->GetMethodID(cls, \"<init>\", \"()V\");\n *result = env->NewObject(cls, mid);\n checkForError();\n }\n\n void visitFloat(double value, int byteSize)\n {\n \/\/ Clear all remaining exceptions\n env->ExceptionClear();\n\n \/\/ Get Float class template\n jclass cls = env->FindClass(\"java\/lang\/Float\");\n if (env->ExceptionCheck())\n {\n throwJavaError(env, \"GenericValue to Float : FindClass error\");\n return;\n }\n\n \/\/ Find constructor method ID\n jmethodID mid = env->GetMethodID(cls, \"<init>\",\"(F)V\");\n if (!mid)\n {\n env->DeleteLocalRef(cls);\n throwJavaError(env, \"GenericValue to Float : GetMethodID error\");\n return;\n }\n\n \/\/ Instanciate new Float, yeah !\n jfloat jval = value;\n *result = env->NewObject(cls, mid, jval);\n env->DeleteLocalRef(cls);\n checkForError();\n }\n\n void visitList(qi::GenericIterator it, qi::GenericIterator end)\n {\n JNIList list; \/\/ this is OK.\n\n for(; it != end; ++it)\n {\n jobject current = (*it).to<jobject>();\n list.push_back(current);\n }\n\n it.destroy();\n end.destroy();\n *result = list.object();\n }\n\n void visitMap(qi::GenericIterator it, qi::GenericIterator end)\n {\n jobject key, value;\n JNIHashTable ht;\n\n for (; it != end; ++it)\n {\n key = JObject_from_GenericValue((*it)[0]);\n value = JObject_from_GenericValue((*it)[1]);\n\n ht.setItem(key, value);\n }\n\n *result = ht.object();\n it.destroy();\n end.destroy();\n }\n\n void visitObject(qi::GenericObject obj)\n {\n throw std::runtime_error(\"Cannot convert GenericObject to Jobject.\");\n\n \/*jclass cls = env->FindClass(\"com\/aldebaran\/qimessaging\/GenericObject\");\n if (!cls)\n {\n qiLogError(\"qimessaging.jni\") << \"Cannot convert GenericObject to Java object\";\n return;\n }\n\n jmethodID mid = env->GetMethodID(cls, \"<init>\", \"(J)V\");\n if (!cls)\n {\n qiLogError(\"qimessaging.jni\") << \"Cannot convert GenericObject to Java object\";\n return;\n }\n\n *result = env->NewObject(cls, mid, (jlong) ptr);*\/\n }\n\n void visitPointer(qi::GenericValuePtr pointee)\n {\n throwJavaError(env, \"Error in conversion: Unable to convert pointer in Java\");\n }\n\n void visitTuple(const std::vector<qi::GenericValuePtr>& tuple)\n {\n JNITuple jtuple(tuple.size());\n int i = 0;\n\n for(std::vector<qi::GenericValuePtr>::const_iterator it = tuple.begin(); it != tuple.end(); ++it)\n {\n jobject current = (*it).to<jobject>();\n jtuple.set(i++, current);\n }\n\n *result = jtuple.object();\n }\n\n void visitDynamic(qi::GenericValuePtr pointee)\n {\n *result = JObject_from_GenericValue(pointee);\n }\n\n void visitRaw(qi::GenericValuePtr value)\n {\n \/\/ Not tested.\n \/* Encapuslate the buffer in ByteBuffer *\/\n qi::Buffer buf = value.as<qi::Buffer>();\n\n \/\/ Create a new ByteBuffer and reserve enough space\n jclass cls = env->FindClass(\"java\/lang\/ByteBuffer\");\n jmethodID mid = env->GetMethodID(cls, \"init\",\"(I)V\");\n jobject ar = env->NewObject(cls, mid, buf.size() + 1);\n\n\n \/\/ Put qi::Buffer content into ByteByffer\n mid = env->GetMethodID(cls, \"put\",\"([B]II)[LJava\/lang\/ByteBuffer;\");\n *result = env->CallObjectMethod(ar, mid, buf.data(), 0, buf.size());\n\n checkForError();\n env->DeleteLocalRef(cls);\n env->DeleteLocalRef(ar);\n }\n\n void visitIterator(qi::GenericValuePtr v)\n {\n visitUnknown(v);\n }\n\n void checkForError()\n {\n if (result == NULL)\n throwJavaError(env, \"Error in conversion to JObject\");\n }\n\n jobject* result;\n int jni_version;\n JNIEnv* env;\n\n}; \/\/ !toJObject\n\njobject JObject_from_GenericValue(qi::GenericValuePtr val)\n{\n jobject result= NULL;\n toJObject tjo(&result);\n qi::typeDispatch<toJObject>(tjo, val);\n return result;\n}\n\nvoid JObject_from_GenericValue(qi::GenericValuePtr val, jobject* target)\n{\n toJObject tal(target);\n qi::typeDispatch<toJObject>(tal, val);\n}\n\nqi::GenericValuePtr GenericValue_from_JObject_List(jobject val)\n{\n JNIEnv* env;\n JNIList list(val);\n std::vector<qi::GenericValue>& res = *new std::vector<qi::GenericValue>();\n int size = 0;\n\n JVM()->GetEnv((void **) &env, QI_JNI_MIN_VERSION);\n\n size = list.size();\n res.reserve(size);\n for (int i = 0; i < size; i++)\n {\n jobject current = list.get(i);\n \/\/qi::GenericValuePtr currentGVP = qi::GenericValuePtr(current);\n res.push_back(qi::GenericValue(GenericValue_from_JObject(current).first));\n }\n\n return qi::GenericValueRef(res);\n}\n\nqi::GenericValuePtr GenericValue_from_JObject_Map(jobject hashtable)\n{\n JNIEnv* env;\n std::map<qi::GenericValue, qi::GenericValue>& res = *new std::map<qi::GenericValue, qi::GenericValue>();\n JNIHashTable ht(hashtable);\n jobject key, value;\n\n JVM()->GetEnv((void **) &env, QI_JNI_MIN_VERSION);\n\n JNIEnumeration keys = ht.keys();\n while (keys.hasNextElement())\n {\n key = keys.nextElement();\n value = ht.at(key);\n qi::GenericValuePtr newKey = GenericValue_from_JObject(key).first;\n qi::GenericValuePtr newValue = GenericValue_from_JObject(value).first;\n res[qi::GenericValue(newKey)] = newValue;\n env->DeleteLocalRef(key);\n env->DeleteLocalRef(value);\n }\n return qi::GenericValueRef(res);\n}\n\nqi::GenericValuePtr GenericValue_from_JObject_Tuple(jobject val)\n{\n JNITuple tuple(val);\n int i = 0;\n std::vector<qi::GenericValuePtr>& res = *new std::vector<qi::GenericValuePtr>();\n\n while (i < tuple.size())\n {\n qi::GenericValuePtr value = GenericValue_from_JObject(tuple.get(i)).first;\n res.push_back(value);\n i++;\n }\n\n return qi::makeGenericTuple(res);\n}\n\nstd::pair<qi::GenericValuePtr, bool> GenericValue_from_JObject(jobject val)\n{\n qi::GenericValuePtr res;\n JNIEnv* env;\n bool copy = false;\n\n if (!val)\n throw std::runtime_error(\"Unable to convert JObject in GenericValue (Value is null)\");\n\n if (JVM()->AttachCurrentThread((envPtr) &env, (void *) 0) != JNI_OK)\n throw std::runtime_error(\"Cannot attach current thread to JVM for conversion.\");\n\n if (JVM()->GetEnv((void **) &env, QI_JNI_MIN_VERSION) != JNI_OK)\n throw std::runtime_error(\"No JNIEnvironment available for conversion.\");\n\n jclass stringClass = env->FindClass(\"java\/lang\/String\");\n jclass int32Class = env->FindClass(\"java\/lang\/Integer\");\n jclass floatClass = env->FindClass(\"java\/lang\/Float\");\n jclass doubleClass = env->FindClass(\"java\/lang\/Double\");\n jclass boolClass = env->FindClass(\"java\/lang\/Boolean\");\n jclass longClass = env->FindClass(\"java\/lang\/Long\");\n jclass mapClass = env->FindClass(\"java\/util\/Map\");\n jclass listClass = env->FindClass(\"java\/util\/ArrayList\");\n jclass tupleClass = env->FindClass(\"com\/aldebaran\/qimessaging\/Tuple\");\n\n if (val == NULL)\n {\n res = qi::GenericValuePtr(qi::typeOf<void>());\n }\n else if (env->IsInstanceOf(val, stringClass))\n {\n std::string tmp = std::string(env->GetStringUTFChars((jstring) val, 0));\n res = qi::GenericValueRef(*new std::string(tmp));\n copy = true;\n }\n else if (env->IsInstanceOf(val, floatClass))\n {\n jmethodID mid = env->GetMethodID(floatClass, \"floatValue\",\"()F\");\n jfloat v = env->CallFloatMethod(val, mid);\n res = qi::GenericValueRef((float)v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, doubleClass)) \/\/ If double, convert to float\n {\n jmethodID mid = env->GetMethodID(doubleClass, \"doubleValue\",\"()D\");\n jfloat v = (jfloat) env->CallDoubleMethod(val, mid);\n res = qi::GenericValueRef((float)v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, longClass))\n {\n jmethodID mid = env->GetMethodID(longClass, \"longValue\",\"()L\");\n jlong v = env->CallLongMethod(val, mid);\n res = qi::GenericValueRef(v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, boolClass))\n {\n jmethodID mid = env->GetMethodID(boolClass, \"booleanValue\",\"()Z\");\n jboolean v = env->CallBooleanMethod(val, mid);\n res = qi::GenericValueRef((bool) v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, int32Class))\n {\n jmethodID mid = env->GetMethodID(int32Class, \"intValue\",\"()I\");\n jint v = env->CallIntMethod(val, mid);\n res = qi::GenericValueRef((int) v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, listClass))\n {\n copy = true;\n res = GenericValue_from_JObject_List(val);\n }\n else if (env->IsInstanceOf(val, mapClass))\n {\n copy = true;\n res = GenericValue_from_JObject_Map(val);\n }\n else if (env->IsInstanceOf(val, tupleClass))\n {\n res = GenericValue_from_JObject_Tuple(val);\n }\n else\n {\n throw std::runtime_error(\"Unable to convert JObject in GenericValue\");\n }\n\n env->DeleteLocalRef(stringClass);\n env->DeleteLocalRef(int32Class);\n env->DeleteLocalRef(floatClass);\n env->DeleteLocalRef(doubleClass);\n env->DeleteLocalRef(boolClass);\n env->DeleteLocalRef(longClass);\n env->DeleteLocalRef(mapClass);\n env->DeleteLocalRef(listClass);\n env->DeleteLocalRef(tupleClass);\n\n return std::make_pair(res, copy);\n}\n\n\n\/*\n * Define this struct to add jobject to the type system.\n * That way we can manipulate jobject transparently.\n * - We have to override clone and destroy here to be compliant\n * with the java reference counting. Otherwise, the value could\n * be Garbage Collected as we try to manipulate it.\n * - We register the type as 'jobject' since java methods manipulates\n * objects only by this typedef pointer, never by value and we do not want to copy\n * a jobject.\n *\/\nclass JObjectType: public qi::TypeDynamic\n{\n public:\n\n virtual const qi::TypeInfo& info()\n {\n \/\/qiLogFatal(\"qimessaging.jni\") << \"info\";\n static qi::TypeInfo* result = 0;\n if (!result)\n {\n result = new qi::TypeInfo(typeid(jobject));\n std::cout << result->asString() << std::endl;\n }\n\n return *result;\n }\n\n virtual void* initializeStorage(void* ptr = 0)\n {\n \/\/ ptr is jobject* (aka _jobject**)\n return ptr;\n }\n\n virtual void* ptrFromStorage(void** s)\n {\n jobject* tmp = (jobject*) s;\n return *tmp;\n }\n\n virtual qi::GenericValuePtr get(void* storage)\n {\n return GenericValue_from_JObject(*((jobject*)ptrFromStorage(&storage))).first;\n }\n\n virtual void set(void** storage, qi::GenericValuePtr src)\n {\n \/\/ storage is jobject*\n \/\/ We will assign *storage to target, so we need it to be allocated\n jobject *target = new jobject;\n\n \/\/ Giving jobject* to JObject_from_GenericValue\n JObject_from_GenericValue(src, target);\n\n JNIEnv *env;\n JVM()->GetEnv((void **) &env, QI_JNI_MIN_VERSION);\n JVM()->AttachCurrentThread((envPtr) &env, (void *) 0);\n env->NewGlobalRef(*target);\n\n *storage = target;\n }\n\n virtual void* clone(void* obj)\n {\n jobject* ginstance = (jobject*) obj;\n\n if (!obj)\n return 0;\n\n jobject* cloned = new jobject;\n *cloned = JObject_from_GenericValue(qi::GenericValueRef(*ginstance));\n\n return cloned;\n }\n\n virtual void destroy(void* obj)\n {\n \/\/ void* obj is a jobject\n\n \/\/ We cannot delete GlobalRef, because it's shared with JVM.\n \/\/ FIXME: Find a way to delete the local one.\n \/\/ Atm it destroys object because JVM hasn't set its ref onto jobject\n \/\/ when destroy is called.\n }\n\n virtual bool less(void* a, void* b)\n {\n jobject* pa = (jobject*) ptrFromStorage(&a);\n jobject* pb = (jobject*) ptrFromStorage(&b);\n\n \/\/ call Object.compare\n return *pa < *pb;\n }\n};\n\n\/* Register jobject -> See the above comment for explanations *\/\nQI_TYPE_REGISTER_CUSTOM(jobject, JObjectType);\n\n<commit_msg>Java bindings: Add visitObjectPtr to converter.<commit_after>\/*\n**\n** Author(s):\n** - Pierre ROULLON <proullon@aldebaran-robotics.com>\n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include <qi\/log.hpp>\n#include <qitype\/signature.hpp>\n#include <qitype\/genericobjectbuilder.hpp>\n#include <qitype\/genericobject.hpp>\n#include <qitype\/genericvalue.hpp>\n#include <qitype\/typedispatcher.hpp>\n#include <qitype\/type.hpp>\n\n#include <jnitools.hpp>\n#include <jobjectconverter.hpp>\n#include <map_jni.hpp>\n#include <list_jni.hpp>\n#include <tuple_jni.hpp>\n\nusing namespace qi;\n\nstruct toJObject\n{\n toJObject(jobject *result)\n : result(result), jni_version(QI_JNI_MIN_VERSION)\n {\n if (JVM()->GetEnv((void **) &env, jni_version) != JNI_OK)\n qiLogFatal(\"qimessaging.jni\") << \"Cannot initialize Java environment.\";\n }\n\n void visitUnknown(qi::GenericValuePtr value)\n {\n throwJavaError(env, \"Error in conversion: Unable to convert unknown type in Java\");\n }\n\n void visitInt(qi::int64_t value, bool isSigned, int byteSize)\n {\n \/\/ Clear all remaining exceptions\n env->ExceptionClear();\n\n \/\/ Get Integer class template\n \/\/ ... or Boolean if byteSize is 0\n jclass cls = env->FindClass(byteSize == 0 ? \"java\/lang\/Boolean\" : \"java\/lang\/Integer\");\n if (env->ExceptionCheck())\n {\n throwJavaError(env, \"GenericValue to Integer : FindClass error\");\n return;\n }\n\n \/\/ Find constructor method ID\n jmethodID mid = env->GetMethodID(cls, \"<init>\", byteSize == 0 ? \"(Z)V\" : \"(I)V\");\n if (!mid)\n {\n env->DeleteLocalRef(cls);\n throwJavaError(env, \"GenericValue to Integer : GetMethodID error\");\n return;\n }\n\n \/\/ Instanciate new Integer, yeah !\n jint jval = value;\n *result = env->NewObject(cls, mid, jval);\n checkForError();\n env->DeleteLocalRef(cls);\n }\n\n void visitString(char *data, size_t len)\/\/qi::TypeString* type, void* storage)\n {\n if (data)\n *result = (jobject) env->NewStringUTF(data);\n else\n *result = (jobject) env->NewStringUTF(\"\");\n checkForError();\n }\n\n void visitVoid()\n {\n jclass cls = env->FindClass(\"java\/lang\/Void\");\n jmethodID mid = env->GetMethodID(cls, \"<init>\", \"()V\");\n *result = env->NewObject(cls, mid);\n checkForError();\n }\n\n void visitFloat(double value, int byteSize)\n {\n \/\/ Clear all remaining exceptions\n env->ExceptionClear();\n\n \/\/ Get Float class template\n jclass cls = env->FindClass(\"java\/lang\/Float\");\n if (env->ExceptionCheck())\n {\n throwJavaError(env, \"GenericValue to Float : FindClass error\");\n return;\n }\n\n \/\/ Find constructor method ID\n jmethodID mid = env->GetMethodID(cls, \"<init>\",\"(F)V\");\n if (!mid)\n {\n env->DeleteLocalRef(cls);\n throwJavaError(env, \"GenericValue to Float : GetMethodID error\");\n return;\n }\n\n \/\/ Instanciate new Float, yeah !\n jfloat jval = value;\n *result = env->NewObject(cls, mid, jval);\n env->DeleteLocalRef(cls);\n checkForError();\n }\n\n void visitList(qi::GenericIterator it, qi::GenericIterator end)\n {\n JNIList list; \/\/ this is OK.\n\n for(; it != end; ++it)\n {\n jobject current = (*it).to<jobject>();\n list.push_back(current);\n }\n\n it.destroy();\n end.destroy();\n *result = list.object();\n }\n\n void visitMap(qi::GenericIterator it, qi::GenericIterator end)\n {\n jobject key, value;\n JNIHashTable ht;\n\n for (; it != end; ++it)\n {\n key = JObject_from_GenericValue((*it)[0]);\n value = JObject_from_GenericValue((*it)[1]);\n\n ht.setItem(key, value);\n }\n\n *result = ht.object();\n it.destroy();\n end.destroy();\n }\n\n void visitObject(qi::GenericObject obj)\n {\n throw std::runtime_error(\"Cannot convert GenericObject to Jobject.\");\n\n \/*jclass cls = env->FindClass(\"com\/aldebaran\/qimessaging\/GenericObject\");\n if (!cls)\n {\n qiLogError(\"qimessaging.jni\") << \"Cannot convert GenericObject to Java object\";\n return;\n }\n\n jmethodID mid = env->GetMethodID(cls, \"<init>\", \"(J)V\");\n if (!cls)\n {\n qiLogError(\"qimessaging.jni\") << \"Cannot convert GenericObject to Java object\";\n return;\n }\n\n *result = env->NewObject(cls, mid, (jlong) ptr);*\/\n }\n\n void visitObjectPtr(qi::ObjectPtr o)\n {\n throw std::runtime_error(\"Cannot convert ObjectPtr to Jobject.\");\n }\n\n void visitPointer(qi::GenericValuePtr pointee)\n {\n throwJavaError(env, \"Error in conversion: Unable to convert pointer in Java\");\n }\n\n void visitTuple(const std::vector<qi::GenericValuePtr>& tuple)\n {\n JNITuple jtuple(tuple.size());\n int i = 0;\n\n for(std::vector<qi::GenericValuePtr>::const_iterator it = tuple.begin(); it != tuple.end(); ++it)\n {\n jobject current = (*it).to<jobject>();\n jtuple.set(i++, current);\n }\n\n *result = jtuple.object();\n }\n\n void visitDynamic(qi::GenericValuePtr pointee)\n {\n *result = JObject_from_GenericValue(pointee);\n }\n\n void visitRaw(qi::GenericValuePtr value)\n {\n \/\/ Not tested.\n \/* Encapuslate the buffer in ByteBuffer *\/\n qi::Buffer buf = value.as<qi::Buffer>();\n\n \/\/ Create a new ByteBuffer and reserve enough space\n jclass cls = env->FindClass(\"java\/lang\/ByteBuffer\");\n jmethodID mid = env->GetMethodID(cls, \"init\",\"(I)V\");\n jobject ar = env->NewObject(cls, mid, buf.size() + 1);\n\n\n \/\/ Put qi::Buffer content into ByteByffer\n mid = env->GetMethodID(cls, \"put\",\"([B]II)[LJava\/lang\/ByteBuffer;\");\n *result = env->CallObjectMethod(ar, mid, buf.data(), 0, buf.size());\n\n checkForError();\n env->DeleteLocalRef(cls);\n env->DeleteLocalRef(ar);\n }\n\n void visitIterator(qi::GenericValuePtr v)\n {\n visitUnknown(v);\n }\n\n void checkForError()\n {\n if (result == NULL)\n throwJavaError(env, \"Error in conversion to JObject\");\n }\n\n jobject* result;\n int jni_version;\n JNIEnv* env;\n\n}; \/\/ !toJObject\n\njobject JObject_from_GenericValue(qi::GenericValuePtr val)\n{\n jobject result= NULL;\n toJObject tjo(&result);\n qi::typeDispatch<toJObject>(tjo, val);\n return result;\n}\n\nvoid JObject_from_GenericValue(qi::GenericValuePtr val, jobject* target)\n{\n toJObject tal(target);\n qi::typeDispatch<toJObject>(tal, val);\n}\n\nqi::GenericValuePtr GenericValue_from_JObject_List(jobject val)\n{\n JNIEnv* env;\n JNIList list(val);\n std::vector<qi::GenericValue>& res = *new std::vector<qi::GenericValue>();\n int size = 0;\n\n JVM()->GetEnv((void **) &env, QI_JNI_MIN_VERSION);\n\n size = list.size();\n res.reserve(size);\n for (int i = 0; i < size; i++)\n {\n jobject current = list.get(i);\n \/\/qi::GenericValuePtr currentGVP = qi::GenericValuePtr(current);\n res.push_back(qi::GenericValue(GenericValue_from_JObject(current).first));\n }\n\n return qi::GenericValueRef(res);\n}\n\nqi::GenericValuePtr GenericValue_from_JObject_Map(jobject hashtable)\n{\n JNIEnv* env;\n std::map<qi::GenericValue, qi::GenericValue>& res = *new std::map<qi::GenericValue, qi::GenericValue>();\n JNIHashTable ht(hashtable);\n jobject key, value;\n\n JVM()->GetEnv((void **) &env, QI_JNI_MIN_VERSION);\n\n JNIEnumeration keys = ht.keys();\n while (keys.hasNextElement())\n {\n key = keys.nextElement();\n value = ht.at(key);\n qi::GenericValuePtr newKey = GenericValue_from_JObject(key).first;\n qi::GenericValuePtr newValue = GenericValue_from_JObject(value).first;\n res[qi::GenericValue(newKey)] = newValue;\n env->DeleteLocalRef(key);\n env->DeleteLocalRef(value);\n }\n return qi::GenericValueRef(res);\n}\n\nqi::GenericValuePtr GenericValue_from_JObject_Tuple(jobject val)\n{\n JNITuple tuple(val);\n int i = 0;\n std::vector<qi::GenericValuePtr>& res = *new std::vector<qi::GenericValuePtr>();\n\n while (i < tuple.size())\n {\n qi::GenericValuePtr value = GenericValue_from_JObject(tuple.get(i)).first;\n res.push_back(value);\n i++;\n }\n\n return qi::makeGenericTuple(res);\n}\n\nstd::pair<qi::GenericValuePtr, bool> GenericValue_from_JObject(jobject val)\n{\n qi::GenericValuePtr res;\n JNIEnv* env;\n bool copy = false;\n\n if (!val)\n throw std::runtime_error(\"Unable to convert JObject in GenericValue (Value is null)\");\n\n if (JVM()->AttachCurrentThread((envPtr) &env, (void *) 0) != JNI_OK)\n throw std::runtime_error(\"Cannot attach current thread to JVM for conversion.\");\n\n if (JVM()->GetEnv((void **) &env, QI_JNI_MIN_VERSION) != JNI_OK)\n throw std::runtime_error(\"No JNIEnvironment available for conversion.\");\n\n jclass stringClass = env->FindClass(\"java\/lang\/String\");\n jclass int32Class = env->FindClass(\"java\/lang\/Integer\");\n jclass floatClass = env->FindClass(\"java\/lang\/Float\");\n jclass doubleClass = env->FindClass(\"java\/lang\/Double\");\n jclass boolClass = env->FindClass(\"java\/lang\/Boolean\");\n jclass longClass = env->FindClass(\"java\/lang\/Long\");\n jclass mapClass = env->FindClass(\"java\/util\/Map\");\n jclass listClass = env->FindClass(\"java\/util\/ArrayList\");\n jclass tupleClass = env->FindClass(\"com\/aldebaran\/qimessaging\/Tuple\");\n\n if (val == NULL)\n {\n res = qi::GenericValuePtr(qi::typeOf<void>());\n }\n else if (env->IsInstanceOf(val, stringClass))\n {\n std::string tmp = std::string(env->GetStringUTFChars((jstring) val, 0));\n res = qi::GenericValueRef(*new std::string(tmp));\n copy = true;\n }\n else if (env->IsInstanceOf(val, floatClass))\n {\n jmethodID mid = env->GetMethodID(floatClass, \"floatValue\",\"()F\");\n jfloat v = env->CallFloatMethod(val, mid);\n res = qi::GenericValueRef((float)v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, doubleClass)) \/\/ If double, convert to float\n {\n jmethodID mid = env->GetMethodID(doubleClass, \"doubleValue\",\"()D\");\n jfloat v = (jfloat) env->CallDoubleMethod(val, mid);\n res = qi::GenericValueRef((float)v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, longClass))\n {\n jmethodID mid = env->GetMethodID(longClass, \"longValue\",\"()L\");\n jlong v = env->CallLongMethod(val, mid);\n res = qi::GenericValueRef(v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, boolClass))\n {\n jmethodID mid = env->GetMethodID(boolClass, \"booleanValue\",\"()Z\");\n jboolean v = env->CallBooleanMethod(val, mid);\n res = qi::GenericValueRef((bool) v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, int32Class))\n {\n jmethodID mid = env->GetMethodID(int32Class, \"intValue\",\"()I\");\n jint v = env->CallIntMethod(val, mid);\n res = qi::GenericValueRef((int) v).clone();\n copy = true;\n }\n else if (env->IsInstanceOf(val, listClass))\n {\n copy = true;\n res = GenericValue_from_JObject_List(val);\n }\n else if (env->IsInstanceOf(val, mapClass))\n {\n copy = true;\n res = GenericValue_from_JObject_Map(val);\n }\n else if (env->IsInstanceOf(val, tupleClass))\n {\n res = GenericValue_from_JObject_Tuple(val);\n }\n else\n {\n throw std::runtime_error(\"Unable to convert JObject in GenericValue\");\n }\n\n env->DeleteLocalRef(stringClass);\n env->DeleteLocalRef(int32Class);\n env->DeleteLocalRef(floatClass);\n env->DeleteLocalRef(doubleClass);\n env->DeleteLocalRef(boolClass);\n env->DeleteLocalRef(longClass);\n env->DeleteLocalRef(mapClass);\n env->DeleteLocalRef(listClass);\n env->DeleteLocalRef(tupleClass);\n\n return std::make_pair(res, copy);\n}\n\n\n\/*\n * Define this struct to add jobject to the type system.\n * That way we can manipulate jobject transparently.\n * - We have to override clone and destroy here to be compliant\n * with the java reference counting. Otherwise, the value could\n * be Garbage Collected as we try to manipulate it.\n * - We register the type as 'jobject' since java methods manipulates\n * objects only by this typedef pointer, never by value and we do not want to copy\n * a jobject.\n *\/\nclass JObjectType: public qi::TypeDynamic\n{\n public:\n\n virtual const qi::TypeInfo& info()\n {\n \/\/qiLogFatal(\"qimessaging.jni\") << \"info\";\n static qi::TypeInfo* result = 0;\n if (!result)\n {\n result = new qi::TypeInfo(typeid(jobject));\n std::cout << result->asString() << std::endl;\n }\n\n return *result;\n }\n\n virtual void* initializeStorage(void* ptr = 0)\n {\n \/\/ ptr is jobject* (aka _jobject**)\n return ptr;\n }\n\n virtual void* ptrFromStorage(void** s)\n {\n jobject* tmp = (jobject*) s;\n return *tmp;\n }\n\n virtual qi::GenericValuePtr get(void* storage)\n {\n return GenericValue_from_JObject(*((jobject*)ptrFromStorage(&storage))).first;\n }\n\n virtual void set(void** storage, qi::GenericValuePtr src)\n {\n \/\/ storage is jobject*\n \/\/ We will assign *storage to target, so we need it to be allocated\n jobject *target = new jobject;\n\n \/\/ Giving jobject* to JObject_from_GenericValue\n JObject_from_GenericValue(src, target);\n\n JNIEnv *env;\n JVM()->GetEnv((void **) &env, QI_JNI_MIN_VERSION);\n JVM()->AttachCurrentThread((envPtr) &env, (void *) 0);\n env->NewGlobalRef(*target);\n\n *storage = target;\n }\n\n virtual void* clone(void* obj)\n {\n jobject* ginstance = (jobject*) obj;\n\n if (!obj)\n return 0;\n\n jobject* cloned = new jobject;\n *cloned = JObject_from_GenericValue(qi::GenericValueRef(*ginstance));\n\n return cloned;\n }\n\n virtual void destroy(void* obj)\n {\n \/\/ void* obj is a jobject\n\n \/\/ We cannot delete GlobalRef, because it's shared with JVM.\n \/\/ FIXME: Find a way to delete the local one.\n \/\/ Atm it destroys object because JVM hasn't set its ref onto jobject\n \/\/ when destroy is called.\n }\n\n virtual bool less(void* a, void* b)\n {\n jobject* pa = (jobject*) ptrFromStorage(&a);\n jobject* pb = (jobject*) ptrFromStorage(&b);\n\n \/\/ call Object.compare\n return *pa < *pb;\n }\n};\n\n\/* Register jobject -> See the above comment for explanations *\/\nQI_TYPE_REGISTER_CUSTOM(jobject, JObjectType);\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_TABLE\n#define MFEM_TABLE\n\n\/\/ Data types for Table.\n\n#include \"mem_alloc.hpp\"\n#include \"array.hpp\"\n\nnamespace mfem\n{\n\n\/\/\/ Helper struct for defining a connectivity table, see Table::MakeFromList.\nstruct Connection\n{\n int from, to;\n Connection(int from, int to) : from(from), to(to) {}\n\n bool operator== (const Connection &rhs) const\n { return (from == rhs.from) && (to == rhs.to); }\n bool operator< (const Connection &rhs) const\n { return (from == rhs.from) ? (to < rhs.to) : (from < rhs.from); }\n};\n\n\n\/** Data type Table. Table stores the connectivity of elements of TYPE I\n to elements of TYPE II, for example, it may be Element-To-Face\n connectivity table, etc. *\/\nclass Table\n{\nprotected:\n\n \/\/\/ size is the number of TYPE I elements.\n int size;\n\n \/** Arrays for the connectivity information in the CSR storage.\n I is of size \"size+1\", J is of size the number of connections\n between TYPE I to TYPE II elements (actually stored I[size]). *\/\n int *I, *J;\n\npublic:\n \/\/\/ Creates an empty table\n Table() { size = -1; I = J = NULL; }\n\n \/\/\/ Copy constructor\n Table(const Table &);\n\n \/\/\/ Create a table with an upper limit for the number of connections.\n explicit Table (int dim, int connections_per_row = 3);\n\n \/** Create a table from a list of connections, see MakeFromList. *\/\n Table(int nrows, Array<Connection> &list) : size(-1), I(NULL), J(NULL)\n { MakeFromList(nrows, list); }\n\n \/** Create a table with one entry per row with column indices given\n by 'partitioning'. *\/\n Table (int nrows, int *partitioning);\n\n \/\/\/ Next 7 methods are used together with the default constructor\n void MakeI (int nrows);\n void AddAColumnInRow (int r) { I[r]++; }\n void AddColumnsInRow (int r, int ncol) { I[r] += ncol; }\n void MakeJ();\n void AddConnection (int r, int c) { J[I[r]++] = c; }\n void AddConnections (int r, const int *c, int nc);\n void ShiftUpI();\n\n \/\/\/ Set the size and the number of connections for the table.\n void SetSize(int dim, int connections_per_row);\n\n \/** Set the rows and the number of all connections for the table.\n Does NOT initialize the whole array I ! (I[0]=0 and I[rows]=nnz only) *\/\n void SetDims(int rows, int nnz);\n\n \/\/\/ Returns the number of TYPE I elements.\n inline int Size() const { return size; }\n\n \/** Returns the number of connections in the table. If Finalize() is\n not called, it returns the number of possible connections established\n by the used constructor. Otherwise, it is exactly the number of\n established connections before calling Finalize(). *\/\n inline int Size_of_connections() const { return I[size]; }\n\n \/** Returns index of the connection between element i of TYPE I and\n element j of TYPE II. If there is no connection between element i\n and element j established in the table, then the return value is -1. *\/\n int operator() (int i, int j) const;\n\n \/\/\/ Return row i in array row (the Table must be finalized)\n void GetRow(int i, Array<int> &row) const;\n\n int RowSize(int i) const { return I[i+1]-I[i]; }\n\n const int *GetRow(int i) const { return J+I[i]; }\n int *GetRow(int i) { return J+I[i]; }\n\n int *GetI() { return I; }\n int *GetJ() { return J; }\n const int *GetI() const { return I; }\n const int *GetJ() const { return J; }\n\n \/\/\/ @brief Sort the column (TYPE II) indices in each row.\n void SortRows();\n\n void SetIJ(int *newI, int *newJ, int newsize = -1);\n\n \/** Establish connection between element i and element j in the table.\n The return value is the index of the connection. It returns -1 if it\n fails to establish the connection. Possibilities are there is not\n enough memory on row i to establish connection to j, an attempt to\n establish new connection after calling Finalize(). *\/\n int Push( int i, int j );\n\n \/** Finalize the table initialization. The function may be called\n only once, after the table has been initialized, in order to compress\n array J (by getting rid of -1's in array J). Calling this function\n will \"freeze\" the table and function Push will work no more.\n Note: The table is functional even without calling Finalize(). *\/\n void Finalize();\n\n \/** Create the table from a list of connections {(from, to)}, where 'from'\n is a TYPE I index and 'to' is a TYPE II index. The list is assumed to be\n sorted and free of duplicities, i.e., you need to call Array::Sort and\n Array::Unique before calling this method. *\/\n void MakeFromList(int nrows, const Array<Connection> &list);\n\n \/\/\/ Returns the number of TYPE II elements (after Finalize() is called).\n int Width() const;\n\n \/\/\/ Call this if data has been stolen.\n void LoseData() { size = -1; I = J = NULL; }\n\n \/\/\/ Prints the table to stream out.\n void Print(std::ostream & out = std::cout, int width = 4) const;\n void PrintMatlab(std::ostream & out) const;\n\n void Save(std::ostream &out) const;\n void Load(std::istream &in);\n\n void Copy(Table & copy) const;\n void Swap(Table & other);\n\n void Clear();\n\n long MemoryUsage() const;\n\n \/\/\/ Destroys Table.\n ~Table();\n};\n\n\/\/\/ Specialization of the template function Swap<> for class Table\ntemplate <> inline void Swap<Table>(Table &a, Table &b)\n{\n a.Swap(b);\n}\n\n\/\/\/ Transpose a Table\nvoid Transpose (const Table &A, Table &At, int _ncols_A = -1);\nTable * Transpose (const Table &A);\n\n\/\/\/ Transpose an Array<int>\nvoid Transpose(const Array<int> &A, Table &At, int _ncols_A = -1);\n\n\/\/\/ C = A * B (as boolean matrices)\nvoid Mult (const Table &A, const Table &B, Table &C);\nTable * Mult (const Table &A, const Table &B);\n\n\n\/** Data type STable. STable is similar to Table, but it's for symmetric\n connectivity, i.e. TYPE I is equivalent to TYPE II. In the first\n dimension we put the elements with smaller index. *\/\n\nclass STable : public Table\n{\npublic:\n \/\/\/ Creates table with fixed number of connections.\n STable (int dim, int connections_per_row = 3);\n\n \/** Returns index of the connection between element i of TYPE I and\n element j of TYPE II. If there is no connection between element i\n and element j established in the table, then the return value is -1. *\/\n int operator() (int i, int j) const;\n\n \/** Establish connection between element i and element j in the table.\n The return value is the index of the connection. It returns -1 if it\n fails to establish the connection. Possibilities are there is not\n enough memory on row i to establish connection to j, an attempt to\n establish new connection after calling Finalize(). *\/\n int Push( int i, int j );\n\n \/\/\/ Destroys STable.\n ~STable() {}\n};\n\n\nclass DSTable\n{\nprivate:\n class Node\n {\n public:\n Node *Prev;\n int Column, Index;\n };\n\n int NumRows, NumEntries;\n Node **Rows;\n#ifdef MFEM_USE_MEMALLOC\n MemAlloc <Node, 1024> NodesMem;\n#endif\n\n int Push_(int r, int c);\n int Index(int r, int c) const;\n\npublic:\n DSTable(int nrows);\n int NumberOfRows() const { return (NumRows); }\n int NumberOfEntries() const { return (NumEntries); }\n int Push(int a, int b)\n { return ((a <= b) ? Push_(a, b) : Push_(b, a)); }\n int operator()(int a, int b) const\n { return ((a <= b) ? Index(a, b) : Index(b, a)); }\n ~DSTable();\n\n class RowIterator\n {\n private:\n Node *n;\n public:\n RowIterator (const DSTable &t, int r) { n = t.Rows[r]; }\n int operator!() { return (n != NULL); }\n void operator++() { n = n->Prev; }\n int Column() { return (n->Column); }\n int Index() { return (n->Index); }\n };\n};\n\n}\n\n#endif\n<commit_msg>Table.hpp uses std::ostream and std::istream. Add missing headers from STL<commit_after>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_TABLE\n#define MFEM_TABLE\n\n\/\/ Data types for Table.\n\n#include \"mem_alloc.hpp\"\n#include \"array.hpp\"\n#include <ostream>\n#include <istream>\n\nnamespace mfem\n{\n\n\/\/\/ Helper struct for defining a connectivity table, see Table::MakeFromList.\nstruct Connection\n{\n int from, to;\n Connection(int from, int to) : from(from), to(to) {}\n\n bool operator== (const Connection &rhs) const\n { return (from == rhs.from) && (to == rhs.to); }\n bool operator< (const Connection &rhs) const\n { return (from == rhs.from) ? (to < rhs.to) : (from < rhs.from); }\n};\n\n\n\/** Data type Table. Table stores the connectivity of elements of TYPE I\n to elements of TYPE II, for example, it may be Element-To-Face\n connectivity table, etc. *\/\nclass Table\n{\nprotected:\n\n \/\/\/ size is the number of TYPE I elements.\n int size;\n\n \/** Arrays for the connectivity information in the CSR storage.\n I is of size \"size+1\", J is of size the number of connections\n between TYPE I to TYPE II elements (actually stored I[size]). *\/\n int *I, *J;\n\npublic:\n \/\/\/ Creates an empty table\n Table() { size = -1; I = J = NULL; }\n\n \/\/\/ Copy constructor\n Table(const Table &);\n\n \/\/\/ Create a table with an upper limit for the number of connections.\n explicit Table (int dim, int connections_per_row = 3);\n\n \/** Create a table from a list of connections, see MakeFromList. *\/\n Table(int nrows, Array<Connection> &list) : size(-1), I(NULL), J(NULL)\n { MakeFromList(nrows, list); }\n\n \/** Create a table with one entry per row with column indices given\n by 'partitioning'. *\/\n Table (int nrows, int *partitioning);\n\n \/\/\/ Next 7 methods are used together with the default constructor\n void MakeI (int nrows);\n void AddAColumnInRow (int r) { I[r]++; }\n void AddColumnsInRow (int r, int ncol) { I[r] += ncol; }\n void MakeJ();\n void AddConnection (int r, int c) { J[I[r]++] = c; }\n void AddConnections (int r, const int *c, int nc);\n void ShiftUpI();\n\n \/\/\/ Set the size and the number of connections for the table.\n void SetSize(int dim, int connections_per_row);\n\n \/** Set the rows and the number of all connections for the table.\n Does NOT initialize the whole array I ! (I[0]=0 and I[rows]=nnz only) *\/\n void SetDims(int rows, int nnz);\n\n \/\/\/ Returns the number of TYPE I elements.\n inline int Size() const { return size; }\n\n \/** Returns the number of connections in the table. If Finalize() is\n not called, it returns the number of possible connections established\n by the used constructor. Otherwise, it is exactly the number of\n established connections before calling Finalize(). *\/\n inline int Size_of_connections() const { return I[size]; }\n\n \/** Returns index of the connection between element i of TYPE I and\n element j of TYPE II. If there is no connection between element i\n and element j established in the table, then the return value is -1. *\/\n int operator() (int i, int j) const;\n\n \/\/\/ Return row i in array row (the Table must be finalized)\n void GetRow(int i, Array<int> &row) const;\n\n int RowSize(int i) const { return I[i+1]-I[i]; }\n\n const int *GetRow(int i) const { return J+I[i]; }\n int *GetRow(int i) { return J+I[i]; }\n\n int *GetI() { return I; }\n int *GetJ() { return J; }\n const int *GetI() const { return I; }\n const int *GetJ() const { return J; }\n\n \/\/\/ @brief Sort the column (TYPE II) indices in each row.\n void SortRows();\n\n void SetIJ(int *newI, int *newJ, int newsize = -1);\n\n \/** Establish connection between element i and element j in the table.\n The return value is the index of the connection. It returns -1 if it\n fails to establish the connection. Possibilities are there is not\n enough memory on row i to establish connection to j, an attempt to\n establish new connection after calling Finalize(). *\/\n int Push( int i, int j );\n\n \/** Finalize the table initialization. The function may be called\n only once, after the table has been initialized, in order to compress\n array J (by getting rid of -1's in array J). Calling this function\n will \"freeze\" the table and function Push will work no more.\n Note: The table is functional even without calling Finalize(). *\/\n void Finalize();\n\n \/** Create the table from a list of connections {(from, to)}, where 'from'\n is a TYPE I index and 'to' is a TYPE II index. The list is assumed to be\n sorted and free of duplicities, i.e., you need to call Array::Sort and\n Array::Unique before calling this method. *\/\n void MakeFromList(int nrows, const Array<Connection> &list);\n\n \/\/\/ Returns the number of TYPE II elements (after Finalize() is called).\n int Width() const;\n\n \/\/\/ Call this if data has been stolen.\n void LoseData() { size = -1; I = J = NULL; }\n\n \/\/\/ Prints the table to stream out.\n void Print(std::ostream & out = std::cout, int width = 4) const;\n void PrintMatlab(std::ostream & out) const;\n\n void Save(std::ostream &out) const;\n void Load(std::istream &in);\n\n void Copy(Table & copy) const;\n void Swap(Table & other);\n\n void Clear();\n\n long MemoryUsage() const;\n\n \/\/\/ Destroys Table.\n ~Table();\n};\n\n\/\/\/ Specialization of the template function Swap<> for class Table\ntemplate <> inline void Swap<Table>(Table &a, Table &b)\n{\n a.Swap(b);\n}\n\n\/\/\/ Transpose a Table\nvoid Transpose (const Table &A, Table &At, int _ncols_A = -1);\nTable * Transpose (const Table &A);\n\n\/\/\/ Transpose an Array<int>\nvoid Transpose(const Array<int> &A, Table &At, int _ncols_A = -1);\n\n\/\/\/ C = A * B (as boolean matrices)\nvoid Mult (const Table &A, const Table &B, Table &C);\nTable * Mult (const Table &A, const Table &B);\n\n\n\/** Data type STable. STable is similar to Table, but it's for symmetric\n connectivity, i.e. TYPE I is equivalent to TYPE II. In the first\n dimension we put the elements with smaller index. *\/\n\nclass STable : public Table\n{\npublic:\n \/\/\/ Creates table with fixed number of connections.\n STable (int dim, int connections_per_row = 3);\n\n \/** Returns index of the connection between element i of TYPE I and\n element j of TYPE II. If there is no connection between element i\n and element j established in the table, then the return value is -1. *\/\n int operator() (int i, int j) const;\n\n \/** Establish connection between element i and element j in the table.\n The return value is the index of the connection. It returns -1 if it\n fails to establish the connection. Possibilities are there is not\n enough memory on row i to establish connection to j, an attempt to\n establish new connection after calling Finalize(). *\/\n int Push( int i, int j );\n\n \/\/\/ Destroys STable.\n ~STable() {}\n};\n\n\nclass DSTable\n{\nprivate:\n class Node\n {\n public:\n Node *Prev;\n int Column, Index;\n };\n\n int NumRows, NumEntries;\n Node **Rows;\n#ifdef MFEM_USE_MEMALLOC\n MemAlloc <Node, 1024> NodesMem;\n#endif\n\n int Push_(int r, int c);\n int Index(int r, int c) const;\n\npublic:\n DSTable(int nrows);\n int NumberOfRows() const { return (NumRows); }\n int NumberOfEntries() const { return (NumEntries); }\n int Push(int a, int b)\n { return ((a <= b) ? Push_(a, b) : Push_(b, a)); }\n int operator()(int a, int b) const\n { return ((a <= b) ? Index(a, b) : Index(b, a)); }\n ~DSTable();\n\n class RowIterator\n {\n private:\n Node *n;\n public:\n RowIterator (const DSTable &t, int r) { n = t.Rows[r]; }\n int operator!() { return (n != NULL); }\n void operator++() { n = n->Prev; }\n int Column() { return (n->Column); }\n int Index() { return (n->Index); }\n };\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"nova_renderer\/frontend\/ui_renderer.hpp\"\n\n#include \"nova_renderer\/rhi\/render_engine.hpp\"\n#include \"nova_renderer\/util\/logger.hpp\"\n\nnamespace nova::renderer {\n UiRenderpass::UiRenderpass(rhi::RenderEngine* device, const glm::vec2& framebuffer_size) {\n shaderpack::RenderPassCreateInfo rp_info = {};\n rp_info.name = UI_RENDER_PASS_NAME;\n rp_info.texture_inputs = {SCENE_OUTPUT_RENDER_TARGET_NAME};\n rp_info.texture_outputs = {{BACKBUFFER_NAME, shaderpack::PixelFormatEnum::RGBA8, false}};\n\n device->create_renderpass(rp_info, framebuffer_size)\n .map([&](rhi::Renderpass* rp) {\n renderpass = rp;\n return true;\n })\n .on_error([](const ntl::NovaError& err) { NOVA_LOG(ERROR) << \"Could not create UI renderpass: \" << err.to_string(); });\n }\n\n void UiRenderpass::render_renderpass_contents(rhi::CommandList* cmds, FrameContext& ctx) {}\n\n NullUiRenderpass::NullUiRenderpass(rhi::RenderEngine* device, const glm::vec2& framebuffer_size)\n : UiRenderpass(device, framebuffer_size) {}\n\n void NullUiRenderpass::render(rhi::CommandList* \/* cmds *\/, FrameContext& \/* ctx *\/) {\n \/\/ Intentionally empty\n }\n\n void NullUiRenderpass::render_ui(rhi::CommandList* \/* cmds *\/, FrameContext& \/* ctx *\/) {\n \/\/ Intentionally empty\n }\n} \/\/ namespace nova::renderer\n<commit_msg>[frontend] UI pass is marked as writing to backbuffer<commit_after>#include \"nova_renderer\/frontend\/ui_renderer.hpp\"\n\n#include \"nova_renderer\/rhi\/render_engine.hpp\"\n#include \"nova_renderer\/util\/logger.hpp\"\n\nnamespace nova::renderer {\n UiRenderpass::UiRenderpass(rhi::RenderEngine* device, const glm::vec2& framebuffer_size) {\n shaderpack::RenderPassCreateInfo rp_info = {};\n rp_info.name = UI_RENDER_PASS_NAME;\n rp_info.texture_inputs = {SCENE_OUTPUT_RENDER_TARGET_NAME};\n rp_info.texture_outputs = {{BACKBUFFER_NAME, shaderpack::PixelFormatEnum::RGBA8, false}};\n\n device->create_renderpass(rp_info, framebuffer_size)\n .map([&](rhi::Renderpass* rp) {\n renderpass = rp;\n return true;\n })\n .on_error([](const ntl::NovaError& err) { NOVA_LOG(ERROR) << \"Could not create UI renderpass: \" << err.to_string(); });\n\n writes_to_backbuffer = true;\n }\n\n void UiRenderpass::render_renderpass_contents(rhi::CommandList* cmds, FrameContext& ctx) {}\n\n NullUiRenderpass::NullUiRenderpass(rhi::RenderEngine* device, const glm::vec2& framebuffer_size)\n : UiRenderpass(device, framebuffer_size) {}\n\n void NullUiRenderpass::render(rhi::CommandList* \/* cmds *\/, FrameContext& \/* ctx *\/) {\n \/\/ Intentionally empty\n }\n\n void NullUiRenderpass::render_ui(rhi::CommandList* \/* cmds *\/, FrameContext& \/* ctx *\/) {\n \/\/ Intentionally empty\n }\n} \/\/ namespace nova::renderer\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2018, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \"..\/include\/rapidjson\/document.h\"\n#include \"..\/include\/rapidjson\/error\/en.h\"\n#include <boost\/asio.hpp>\n\n#include \"routing\/orshttp_wrapper.h\"\n#include \"utils\/exception.h\"\n\nusing boost::asio::ip::tcp;\n\nnamespace vroom {\nnamespace routing {\n\nOrsHttpWrapper::OrsHttpWrapper(const std::string& profile, const Server& server)\n : OSRMWrapper(profile), _server(server) {\n}\n\nstd::string OrsHttpWrapper::build_query(const std::vector<Location>& locations,\n std::string service,\n std::string extra_args = \"\") const {\n \/\/ Building query for ORS\n std::string query = \"GET \/v2\/\" + service;\n\n query += \"?profile=\" + _profile;\n\n \/\/ Adding locations.\n if (service == \"routes\") {\n query += \"&coordinates=\";\n } else {\n query += \"&locations=\";\n }\n for (auto const& location : locations) {\n query += std::to_string(location.lon()) + \",\" +\n std::to_string(location.lat()) + \"|\";\n }\n query.pop_back(); \/\/ Remove trailing '|'.\n\n if (!extra_args.empty()) {\n query += \"&\" + extra_args;\n }\n\n query += \" HTTP\/1.1\\r\\n\";\n query += \"Host: \" + _server.host + \"\\r\\n\";\n query += \"Accept: *\/*\\r\\n\";\n query += \"Connection: close\\r\\n\\r\\n\";\n\n return query;\n}\n\nstd::string OrsHttpWrapper::send_then_receive(std::string query) const {\n std::string response;\n\n try {\n boost::asio::io_service io_service;\n\n tcp::resolver r(io_service);\n\n tcp::resolver::query q(_server.host, _server.port);\n\n tcp::socket s(io_service);\n boost::asio::connect(s, r.resolve(q));\n\n boost::asio::write(s, boost::asio::buffer(query));\n\n char buf[512];\n boost::system::error_code error;\n for (;;) {\n std::size_t len = s.read_some(boost::asio::buffer(buf), error);\n response.append(buf, len);\n if (error == boost::asio::error::eof) {\n \/\/ Connection closed cleanly.\n break;\n } else {\n if (error) {\n throw boost::system::system_error(error);\n }\n }\n }\n } catch (boost::system::system_error& e) {\n throw Exception(ERROR::ROUTING,\n \"Failed to connect to ORS at \" + _server.host + \":\" +\n _server.port);\n }\n return response;\n}\n\nMatrix<Cost>\nOrsHttpWrapper::get_matrix(const std::vector<Location>& locs) const {\n std::string query = this->build_query(locs, \"matrix\");\n\n std::string response = this->send_then_receive(query);\n\n \/\/ Removing headers.\n std::string json_content = response.substr(response.find(\"{\"));\n\n \/\/ Expected matrix size.\n std::size_t m_size = locs.size();\n\n \/\/ Checking everything is fine in the response.\n rapidjson::Document infos;\n#ifdef NDEBUG\n infos.Parse(json_content.c_str());\n#else\n assert(!infos.Parse(json_content.c_str()).HasParseError());\n#endif\n if (infos.HasMember(\"error\")) {\n throw Exception(ERROR::ROUTING,\n \"ORS matrix:\" +\n std::string(infos[\"error\"][\"message\"].GetString()));\n }\n assert(infos[\"durations\"].Size() == m_size);\n\n \/\/ Build matrix while checking for unfound routes to avoid\n \/\/ unexpected behavior (ORS raises 'null').\n Matrix<Cost> m(m_size);\n\n std::vector<unsigned> nb_unfound_from_loc(m_size, 0);\n std::vector<unsigned> nb_unfound_to_loc(m_size, 0);\n\n for (rapidjson::SizeType i = 0; i < infos[\"durations\"].Size(); ++i) {\n const auto& line = infos[\"durations\"][i];\n assert(line.Size() == m_size);\n for (rapidjson::SizeType j = 0; j < line.Size(); ++j) {\n if (line[j].IsNull()) {\n \/\/ No route found between i and j. Just storing info as we\n \/\/ don't know yet which location is responsible between i\n \/\/ and j.\n ++nb_unfound_from_loc[i];\n ++nb_unfound_to_loc[j];\n } else {\n auto cost = round_cost(line[j].GetDouble());\n m[i][j] = cost;\n }\n }\n }\n\n check_unfound(locs, nb_unfound_from_loc, nb_unfound_to_loc);\n\n return m;\n}\n\nvoid OrsHttpWrapper::add_route_info(Route& route) const {\n \/\/ Ordering locations for the given steps.\n std::vector<Location> ordered_locations;\n for (const auto& step : route.steps) {\n ordered_locations.push_back(step.location);\n }\n\n std::string extra_args = \"geometry_simplify=false&continue_straight=false\";\n\n std::string query =\n this->build_query(ordered_locations, \"routes\", extra_args);\n std::string response = this->send_then_receive(query);\n\n \/\/ Removing headers\n std::string json_content = response.substr(response.find(\"{\"));\n\n \/\/ Checking everything is fine in the response.\n rapidjson::Document infos;\n#ifdef NDEBUG\n infos.Parse(json_content.c_str());\n#else\n assert(!infos.Parse(json_content.c_str()).HasParseError());\n#endif\n if (infos.HasMember(\"error\")) {\n throw Exception(ERROR::ROUTING,\n \"ORS routes: \" +\n std::string(infos[\"error\"][\"message\"].GetString()));\n }\n\n \/\/ Total distance and route geometry.\n route.distance =\n round_cost(infos[\"routes\"][0][\"summary\"][\"distance\"].GetDouble());\n route.geometry = std::move(infos[\"routes\"][0][\"geometry\"].GetString());\n\n auto nb_legs = infos[\"routes\"][0][\"segments\"].Size();\n assert(nb_legs == route.steps.size() - 1);\n\n \/\/ Accumulated travel distance stored for each step.\n double current_distance = 0;\n\n route.steps[0].distance = 0;\n\n for (rapidjson::SizeType i = 0; i < nb_legs; ++i) {\n \/\/ Update distance for step after current route leg.\n current_distance +=\n infos[\"routes\"][0][\"segments\"][i][\"distance\"].GetDouble();\n route.steps[i + 1].distance = round_cost(current_distance);\n }\n}\n\n} \/\/ namespace routing\n} \/\/ namespace vroom\n<commit_msg>Update to ORS API version 2.<commit_after>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2018, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \"..\/include\/rapidjson\/document.h\"\n#include \"..\/include\/rapidjson\/error\/en.h\"\n#include <boost\/asio.hpp>\n\n#include \"routing\/orshttp_wrapper.h\"\n#include \"utils\/exception.h\"\n\nusing boost::asio::ip::tcp;\n\nnamespace vroom {\nnamespace routing {\n\nOrsHttpWrapper::OrsHttpWrapper(const std::string& profile, const Server& server)\n : OSRMWrapper(profile), _server(server) {\n}\n\nstd::string OrsHttpWrapper::build_query(const std::vector<Location>& locations,\n std::string service,\n std::string extra_args = \"\") const {\n \/\/ Adding locations.\n std::string body = \"{\\\"\";\n if (service == \"routes\") {\n body += \"coordinates\";\n } else {\n body += \"locations\";\n }\n body += \"\\\":[\";\n for (auto const& location : locations) {\n body += \"[\" + std::to_string(location.lon()) + \",\" +\n std::to_string(location.lat()) + \"],\";\n }\n body.pop_back(); \/\/ Remove trailing ','.\n body +=\"]}\";\n\n \/\/ Building query for ORS\n\n std::string query = \"POST \/ors\/v2\/\" + service + \"\/\" + _profile;\n\n if (!extra_args.empty()) {\n query += \"?\" + extra_args;\n }\n\n query += \" HTTP\/1.1\\r\\n\";\n query += \"Accept: *\/*\\r\\n\";\n query += \"Content-Type: application\/json\\r\\n\";\n query += \"Content-Length: \" + std::to_string(body.size()) + \"\\r\\n\";\n query += \"Host: \" + _server.host + \":\" + _server.port + \"\\r\\n\";\n query += \"Connection: close\\r\\n\";\n query += \"\\r\\n\" + body;\n\n return query;\n}\n\nstd::string OrsHttpWrapper::send_then_receive(std::string query) const {\n std::string response;\n\n try {\n boost::asio::io_service io_service;\n\n tcp::resolver r(io_service);\n\n tcp::resolver::query q(_server.host, _server.port);\n\n tcp::socket s(io_service);\n boost::asio::connect(s, r.resolve(q));\n\n boost::asio::write(s, boost::asio::buffer(query));\n\n char buf[512];\n boost::system::error_code error;\n for (;;) {\n std::size_t len = s.read_some(boost::asio::buffer(buf), error);\n response.append(buf, len);\n if (error == boost::asio::error::eof) {\n \/\/ Connection closed cleanly.\n break;\n } else {\n if (error) {\n throw boost::system::system_error(error);\n }\n }\n }\n } catch (boost::system::system_error& e) {\n throw Exception(ERROR::ROUTING,\n \"Failed to connect to ORS at \" + _server.host + \":\" +\n _server.port);\n }\n return response;\n}\n\nMatrix<Cost>\nOrsHttpWrapper::get_matrix(const std::vector<Location>& locs) const {\n std::string query = this->build_query(locs, \"matrix\");\n std::string response = this->send_then_receive(query);\n\n \/\/ Removing headers.\n size_t json_start = response.find(\"{\");\n size_t json_length = response.rfind(\"}\") - json_start + 1;\n std::string json_content = response.substr(json_start, json_length);\n\n \/\/ Expected matrix size.\n std::size_t m_size = locs.size();\n\n \/\/ Checking everything is fine in the response.\n rapidjson::Document infos;\n#ifdef NDEBUG\n infos.Parse(json_content.c_str());\n#else\n assert(!infos.Parse(json_content.c_str()).HasParseError());\n#endif\n if (infos.HasMember(\"error\")) {\n throw Exception(ERROR::ROUTING,\n \"ORS matrix:\" +\n std::string(infos[\"error\"][\"message\"].GetString()));\n }\n\n assert(infos[\"durations\"].Size() == m_size);\n\n \/\/ Build matrix while checking for unfound routes to avoid\n \/\/ unexpected behavior (ORS raises 'null').\n Matrix<Cost> m(m_size);\n\n std::vector<unsigned> nb_unfound_from_loc(m_size, 0);\n std::vector<unsigned> nb_unfound_to_loc(m_size, 0);\n\n for (rapidjson::SizeType i = 0; i < infos[\"durations\"].Size(); ++i) {\n const auto& line = infos[\"durations\"][i];\n assert(line.Size() == m_size);\n for (rapidjson::SizeType j = 0; j < line.Size(); ++j) {\n if (line[j].IsNull()) {\n \/\/ No route found between i and j. Just storing info as we\n \/\/ don't know yet which location is responsible between i\n \/\/ and j.\n ++nb_unfound_from_loc[i];\n ++nb_unfound_to_loc[j];\n } else {\n auto cost = round_cost(line[j].GetDouble());\n m[i][j] = cost;\n }\n }\n }\n\n check_unfound(locs, nb_unfound_from_loc, nb_unfound_to_loc);\n\n return m;\n}\n\nvoid OrsHttpWrapper::add_route_info(Route& route) const {\n \/\/ Ordering locations for the given steps.\n std::vector<Location> ordered_locations;\n for (const auto& step : route.steps) {\n ordered_locations.push_back(step.location);\n }\n\n std::string extra_args = \"geometry_simplify=false&continue_straight=false\";\n\n std::string query =\n this->build_query(ordered_locations, \"routes\", extra_args);\n std::string response = this->send_then_receive(query);\n\n \/\/ Removing headers\n std::string json_content = response.substr(response.find(\"{\"));\n\n \/\/ Checking everything is fine in the response.\n rapidjson::Document infos;\n#ifdef NDEBUG\n infos.Parse(json_content.c_str());\n#else\n assert(!infos.Parse(json_content.c_str()).HasParseError());\n#endif\n if (infos.HasMember(\"error\")) {\n throw Exception(ERROR::ROUTING,\n \"ORS routes: \" +\n std::string(infos[\"error\"][\"message\"].GetString()));\n }\n\n \/\/ Total distance and route geometry.\n route.distance =\n round_cost(infos[\"routes\"][0][\"summary\"][\"distance\"].GetDouble());\n route.geometry = std::move(infos[\"routes\"][0][\"geometry\"].GetString());\n\n auto nb_legs = infos[\"routes\"][0][\"segments\"].Size();\n assert(nb_legs == route.steps.size() - 1);\n\n \/\/ Accumulated travel distance stored for each step.\n double current_distance = 0;\n\n route.steps[0].distance = 0;\n\n for (rapidjson::SizeType i = 0; i < nb_legs; ++i) {\n \/\/ Update distance for step after current route leg.\n current_distance +=\n infos[\"routes\"][0][\"segments\"][i][\"distance\"].GetDouble();\n route.steps[i + 1].distance = round_cost(current_distance);\n }\n}\n\n} \/\/ namespace routing\n} \/\/ namespace vroom\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- MainThreadCheckerRuntime.cpp ----------------------------*- C++ -*-===\/\/\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#include \"MainThreadCheckerRuntime.h\"\n\n#include \"lldb\/Breakpoint\/StoppointCallbackContext.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/PluginManager.h\"\n#include \"lldb\/Symbol\/Symbol.h\"\n#include \"lldb\/Symbol\/SymbolContext.h\"\n#include \"lldb\/Symbol\/Variable.h\"\n#include \"lldb\/Symbol\/VariableList.h\"\n#include \"lldb\/Target\/InstrumentationRuntimeStopInfo.h\"\n#include \"lldb\/Target\/RegisterContext.h\"\n#include \"lldb\/Target\/SectionLoadList.h\"\n#include \"lldb\/Target\/StopInfo.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Target\/Thread.h\"\n#include \"lldb\/Utility\/RegularExpression.h\"\n#include \"Plugins\/Process\/Utility\/HistoryThread.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/NameLookup.h\"\n#include \"swift\/ClangImporter\/ClangImporter.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nMainThreadCheckerRuntime::~MainThreadCheckerRuntime() {\n Deactivate();\n}\n\nlldb::InstrumentationRuntimeSP\nMainThreadCheckerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {\n return InstrumentationRuntimeSP(new MainThreadCheckerRuntime(process_sp));\n}\n\nvoid MainThreadCheckerRuntime::Initialize() {\n PluginManager::RegisterPlugin(\n GetPluginNameStatic(), \"MainThreadChecker instrumentation runtime plugin.\",\n CreateInstance, GetTypeStatic);\n}\n\nvoid MainThreadCheckerRuntime::Terminate() {\n PluginManager::UnregisterPlugin(CreateInstance);\n}\n\nlldb_private::ConstString MainThreadCheckerRuntime::GetPluginNameStatic() {\n return ConstString(\"MainThreadChecker\");\n}\n\nlldb::InstrumentationRuntimeType MainThreadCheckerRuntime::GetTypeStatic() {\n return eInstrumentationRuntimeTypeMainThreadChecker;\n}\n\nconst RegularExpression &\nMainThreadCheckerRuntime::GetPatternForRuntimeLibrary() {\n static RegularExpression regex(llvm::StringRef(\"libMainThreadChecker.dylib\"));\n return regex;\n}\n\nbool MainThreadCheckerRuntime::CheckIfRuntimeIsValid(\n const lldb::ModuleSP module_sp) {\n static ConstString test_sym(\"__main_thread_checker_on_report\");\n const Symbol *symbol =\n module_sp->FindFirstSymbolWithNameAndType(test_sym, lldb::eSymbolTypeAny);\n return symbol != nullptr;\n}\n\nstatic std::string TranslateObjCNameToSwiftName(std::string className,\n std::string selector,\n StackFrameSP swiftFrame) {\n if (className.empty() || selector.empty())\n return \"\";\n ModuleSP swiftModule = swiftFrame->GetFrameCodeAddress().GetModule();\n if (!swiftModule)\n return \"\";\n SwiftASTContext *ctx = llvm::dyn_cast_or_null<SwiftASTContext>(\n swiftModule->GetTypeSystemForLanguage(lldb::eLanguageTypeSwift));\n if (!ctx)\n return \"\";\n swift::ClangImporter *imp = ctx->GetClangImporter();\n if (!imp)\n return \"\";\n\n size_t numArguments = llvm::StringRef(selector).count(':');\n llvm::SmallVector<llvm::StringRef, 4> parts;\n llvm::StringRef(selector).split(parts, \":\", \/*MaxSplit*\/ -1,\n \/*KeepEmpty*\/ false);\n\n llvm::SmallVector<swift::Identifier, 2> selectorIdentifiers;\n for (size_t i = 0; i < parts.size(); i++) {\n selectorIdentifiers.push_back(ctx->GetIdentifier(parts[i]));\n }\n\n class MyConsumer : public swift::VisibleDeclConsumer {\n public:\n swift::ObjCSelector selectorToLookup;\n swift::DeclName result;\n\n MyConsumer(swift::ObjCSelector selector) : selectorToLookup(selector) {}\n\n virtual void foundDecl(swift::ValueDecl *VD,\n swift::DeclVisibilityKind Reason) {\n if (result)\n return; \/\/ Take the first result.\n swift::ClassDecl *cls = llvm::dyn_cast<swift::ClassDecl>(VD);\n if (!cls)\n return;\n auto funcs = cls->lookupDirect(selectorToLookup, true);\n if (funcs.size() == 0)\n return;\n\n \/\/ If the decl is actually an accessor, use the property name instead.\n swift::AbstractFunctionDecl *decl = funcs.front();\n if (auto func = llvm::dyn_cast<swift::FuncDecl>(decl)) {\n swift::DeclContext *funcCtx = func->getParent();\n \/\/ We need to loadAllMembers(), otherwise 'isAccessor' returns false.\n if (auto extension = llvm::dyn_cast<swift::ExtensionDecl>(funcCtx)) {\n extension->loadAllMembers();\n } else if (auto nominal =\n llvm::dyn_cast<swift::NominalTypeDecl>(funcCtx)) {\n nominal->loadAllMembers();\n }\n\n if (func->isAccessor()) {\n result = func->getAccessorStorageDecl()->getFullName();\n return;\n }\n }\n\n result = decl->getFullName();\n }\n };\n\n MyConsumer consumer(swift::ObjCSelector(*ctx->GetASTContext(), numArguments,\n selectorIdentifiers));\n \/\/ FIXME(mracek): Switch to a new API that translates the Clang class name\n \/\/ to Swift class name, once this API exists. Now we assume they are the same.\n imp->lookupValue(ctx->GetIdentifier(className), consumer);\n\n if (!consumer.result)\n return \"\";\n llvm::SmallString<32> scratchSpace;\n return className + \".\" + consumer.result.getString(scratchSpace).str();\n}\n\nStructuredData::ObjectSP\nMainThreadCheckerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {\n ProcessSP process_sp = GetProcessSP();\n if (!process_sp)\n return StructuredData::ObjectSP();\n\n ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();\n StackFrameSP frame_sp = thread_sp->GetSelectedFrame();\n ModuleSP runtime_module_sp = GetRuntimeModuleSP();\n Target &target = process_sp->GetTarget();\n\n if (!frame_sp)\n return StructuredData::ObjectSP();\n\n RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();\n if (!regctx_sp)\n return StructuredData::ObjectSP();\n\n const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName(\"arg1\");\n if (!reginfo)\n return StructuredData::ObjectSP();\n\n uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);\n if (!apiname_ptr)\n return StructuredData::ObjectSP();\n\n std::string apiName = \"\";\n Status read_error;\n target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);\n if (read_error.Fail())\n return StructuredData::ObjectSP();\n\n std::string className = \"\";\n std::string selector = \"\";\n if (apiName.substr(0, 2) == \"-[\") {\n size_t spacePos = apiName.find(\" \");\n if (spacePos != std::string::npos) {\n className = apiName.substr(2, spacePos - 2);\n selector = apiName.substr(spacePos + 1, apiName.length() - spacePos - 2);\n }\n }\n\n \/\/ Gather the PCs of the user frames in the backtrace.\n StructuredData::Array *trace = new StructuredData::Array();\n auto trace_sp = StructuredData::ObjectSP(trace);\n StackFrameSP responsible_frame;\n for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {\n StackFrameSP frame = thread_sp->GetStackFrameAtIndex(I);\n Address addr = frame->GetFrameCodeAddress();\n if (addr.GetModule() == runtime_module_sp) \/\/ Skip PCs from the runtime.\n continue;\n\n \/\/ The first non-runtime frame is responsible for the bug.\n if (!responsible_frame)\n responsible_frame = frame;\n\n \/\/ First frame in stacktrace should point to a real PC, not return address.\n if (I != 0 && trace->GetSize() == 0) {\n addr.Slide(-1);\n }\n\n lldb::addr_t PC = addr.GetLoadAddress(&target);\n trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(PC)));\n }\n \n if (responsible_frame) {\n if (responsible_frame->GetLanguage() == eLanguageTypeSwift) {\n std::string swiftApiName =\n TranslateObjCNameToSwiftName(className, selector, responsible_frame);\n if (swiftApiName != \"\")\n apiName = swiftApiName;\n }\n }\n \n auto *d = new StructuredData::Dictionary();\n auto dict_sp = StructuredData::ObjectSP(d);\n d->AddStringItem(\"instrumentation_class\", \"MainThreadChecker\");\n d->AddStringItem(\"api_name\", apiName);\n d->AddStringItem(\"class_name\", className);\n d->AddStringItem(\"selector\", selector);\n d->AddStringItem(\"description\",\n apiName + \" must be used from main thread only\");\n d->AddIntegerItem(\"tid\", thread_sp->GetIndexID());\n d->AddItem(\"trace\", trace_sp);\n return dict_sp;\n}\n\nbool MainThreadCheckerRuntime::NotifyBreakpointHit(\n void *baton, StoppointCallbackContext *context, user_id_t break_id,\n user_id_t break_loc_id) {\n assert(baton && \"null baton\");\n if (!baton)\n return false; \/\/< false => resume execution.\n\n MainThreadCheckerRuntime *const instance =\n static_cast<MainThreadCheckerRuntime *>(baton);\n\n ProcessSP process_sp = instance->GetProcessSP();\n ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();\n if (!process_sp || !thread_sp ||\n process_sp != context->exe_ctx_ref.GetProcessSP())\n return false;\n\n if (process_sp->GetModIDRef().IsLastResumeForUserExpression())\n return false;\n\n StructuredData::ObjectSP report =\n instance->RetrieveReportData(context->exe_ctx_ref);\n\n if (report) {\n std::string description = report->GetAsDictionary()\n ->GetValueForKey(\"description\")\n ->GetAsString()\n ->GetValue();\n thread_sp->SetStopInfo(\n InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(\n *thread_sp, description, report));\n return true;\n }\n\n return false;\n}\n\nvoid MainThreadCheckerRuntime::Activate() {\n if (IsActive())\n return;\n\n ProcessSP process_sp = GetProcessSP();\n if (!process_sp)\n return;\n\n ModuleSP runtime_module_sp = GetRuntimeModuleSP();\n\n ConstString symbol_name(\"__main_thread_checker_on_report\");\n const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(\n symbol_name, eSymbolTypeCode);\n\n if (symbol == nullptr)\n return;\n\n if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())\n return;\n\n Target &target = process_sp->GetTarget();\n addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);\n\n if (symbol_address == LLDB_INVALID_ADDRESS)\n return;\n\n Breakpoint *breakpoint =\n process_sp->GetTarget()\n .CreateBreakpoint(symbol_address, \/*internal=*\/true,\n \/*hardware=*\/false)\n .get();\n breakpoint->SetCallback(MainThreadCheckerRuntime::NotifyBreakpointHit, this,\n true);\n breakpoint->SetBreakpointKind(\"main-thread-checker-report\");\n SetBreakpointID(breakpoint->GetID());\n\n SetActive(true);\n}\n\nvoid MainThreadCheckerRuntime::Deactivate() {\n SetActive(false);\n\n auto BID = GetBreakpointID();\n if (BID == LLDB_INVALID_BREAK_ID)\n return;\n\n if (ProcessSP process_sp = GetProcessSP()) {\n process_sp->GetTarget().RemoveBreakpointByID(BID);\n SetBreakpointID(LLDB_INVALID_BREAK_ID);\n }\n}\n\nlldb::ThreadCollectionSP\nMainThreadCheckerRuntime::GetBacktracesFromExtendedStopInfo(\n StructuredData::ObjectSP info) {\n ThreadCollectionSP threads;\n threads.reset(new ThreadCollection());\n \n ProcessSP process_sp = GetProcessSP();\n \n if (info->GetObjectForDotSeparatedPath(\"instrumentation_class\")\n ->GetStringValue() != \"MainThreadChecker\")\n return threads;\n \n std::vector<lldb::addr_t> PCs;\n auto trace = info->GetObjectForDotSeparatedPath(\"trace\")->GetAsArray();\n trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {\n PCs.push_back(PC->GetAsInteger()->GetValue());\n return true;\n });\n \n if (PCs.empty())\n return threads;\n \n StructuredData::ObjectSP thread_id_obj =\n info->GetObjectForDotSeparatedPath(\"tid\");\n tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;\n \n uint32_t stop_id = 0;\n bool stop_id_is_valid = false;\n HistoryThread *history_thread =\n new HistoryThread(*process_sp, tid, PCs, stop_id, stop_id_is_valid);\n ThreadSP new_thread_sp(history_thread);\n \n \/\/ Save this in the Process' ExtendedThreadList so a strong pointer\n \/\/ retains the object\n process_sp->GetExtendedThreadList().AddThread(new_thread_sp);\n threads->AddThread(new_thread_sp);\n\n return threads;\n}\n<commit_msg>Update for the changes to Swift accessor declarations (Swift PR #13866).<commit_after>\/\/===-- MainThreadCheckerRuntime.cpp ----------------------------*- C++ -*-===\/\/\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#include \"MainThreadCheckerRuntime.h\"\n\n#include \"lldb\/Breakpoint\/StoppointCallbackContext.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/PluginManager.h\"\n#include \"lldb\/Symbol\/Symbol.h\"\n#include \"lldb\/Symbol\/SymbolContext.h\"\n#include \"lldb\/Symbol\/Variable.h\"\n#include \"lldb\/Symbol\/VariableList.h\"\n#include \"lldb\/Target\/InstrumentationRuntimeStopInfo.h\"\n#include \"lldb\/Target\/RegisterContext.h\"\n#include \"lldb\/Target\/SectionLoadList.h\"\n#include \"lldb\/Target\/StopInfo.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Target\/Thread.h\"\n#include \"lldb\/Utility\/RegularExpression.h\"\n#include \"Plugins\/Process\/Utility\/HistoryThread.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/NameLookup.h\"\n#include \"swift\/ClangImporter\/ClangImporter.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nMainThreadCheckerRuntime::~MainThreadCheckerRuntime() {\n Deactivate();\n}\n\nlldb::InstrumentationRuntimeSP\nMainThreadCheckerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {\n return InstrumentationRuntimeSP(new MainThreadCheckerRuntime(process_sp));\n}\n\nvoid MainThreadCheckerRuntime::Initialize() {\n PluginManager::RegisterPlugin(\n GetPluginNameStatic(), \"MainThreadChecker instrumentation runtime plugin.\",\n CreateInstance, GetTypeStatic);\n}\n\nvoid MainThreadCheckerRuntime::Terminate() {\n PluginManager::UnregisterPlugin(CreateInstance);\n}\n\nlldb_private::ConstString MainThreadCheckerRuntime::GetPluginNameStatic() {\n return ConstString(\"MainThreadChecker\");\n}\n\nlldb::InstrumentationRuntimeType MainThreadCheckerRuntime::GetTypeStatic() {\n return eInstrumentationRuntimeTypeMainThreadChecker;\n}\n\nconst RegularExpression &\nMainThreadCheckerRuntime::GetPatternForRuntimeLibrary() {\n static RegularExpression regex(llvm::StringRef(\"libMainThreadChecker.dylib\"));\n return regex;\n}\n\nbool MainThreadCheckerRuntime::CheckIfRuntimeIsValid(\n const lldb::ModuleSP module_sp) {\n static ConstString test_sym(\"__main_thread_checker_on_report\");\n const Symbol *symbol =\n module_sp->FindFirstSymbolWithNameAndType(test_sym, lldb::eSymbolTypeAny);\n return symbol != nullptr;\n}\n\nstatic std::string TranslateObjCNameToSwiftName(std::string className,\n std::string selector,\n StackFrameSP swiftFrame) {\n if (className.empty() || selector.empty())\n return \"\";\n ModuleSP swiftModule = swiftFrame->GetFrameCodeAddress().GetModule();\n if (!swiftModule)\n return \"\";\n SwiftASTContext *ctx = llvm::dyn_cast_or_null<SwiftASTContext>(\n swiftModule->GetTypeSystemForLanguage(lldb::eLanguageTypeSwift));\n if (!ctx)\n return \"\";\n swift::ClangImporter *imp = ctx->GetClangImporter();\n if (!imp)\n return \"\";\n\n size_t numArguments = llvm::StringRef(selector).count(':');\n llvm::SmallVector<llvm::StringRef, 4> parts;\n llvm::StringRef(selector).split(parts, \":\", \/*MaxSplit*\/ -1,\n \/*KeepEmpty*\/ false);\n\n llvm::SmallVector<swift::Identifier, 2> selectorIdentifiers;\n for (size_t i = 0; i < parts.size(); i++) {\n selectorIdentifiers.push_back(ctx->GetIdentifier(parts[i]));\n }\n\n class MyConsumer : public swift::VisibleDeclConsumer {\n public:\n swift::ObjCSelector selectorToLookup;\n swift::DeclName result;\n\n MyConsumer(swift::ObjCSelector selector) : selectorToLookup(selector) {}\n\n virtual void foundDecl(swift::ValueDecl *VD,\n swift::DeclVisibilityKind Reason) {\n if (result)\n return; \/\/ Take the first result.\n swift::ClassDecl *cls = llvm::dyn_cast<swift::ClassDecl>(VD);\n if (!cls)\n return;\n auto funcs = cls->lookupDirect(selectorToLookup, true);\n if (funcs.size() == 0)\n return;\n\n \/\/ If the decl is actually an accessor, use the property name instead.\n swift::AbstractFunctionDecl *decl = funcs.front();\n if (auto func = llvm::dyn_cast<swift::FuncDecl>(decl)) {\n swift::DeclContext *funcCtx = func->getParent();\n \/\/ We need to loadAllMembers(), otherwise 'isAccessor' returns false.\n if (auto extension = llvm::dyn_cast<swift::ExtensionDecl>(funcCtx)) {\n extension->loadAllMembers();\n } else if (auto nominal =\n llvm::dyn_cast<swift::NominalTypeDecl>(funcCtx)) {\n nominal->loadAllMembers();\n }\n\n if (auto accessor = llvm::dyn_cast<swift::AccessorDecl>(func)) {\n result = accessor->getStorage()->getFullName();\n return;\n }\n }\n\n result = decl->getFullName();\n }\n };\n\n MyConsumer consumer(swift::ObjCSelector(*ctx->GetASTContext(), numArguments,\n selectorIdentifiers));\n \/\/ FIXME(mracek): Switch to a new API that translates the Clang class name\n \/\/ to Swift class name, once this API exists. Now we assume they are the same.\n imp->lookupValue(ctx->GetIdentifier(className), consumer);\n\n if (!consumer.result)\n return \"\";\n llvm::SmallString<32> scratchSpace;\n return className + \".\" + consumer.result.getString(scratchSpace).str();\n}\n\nStructuredData::ObjectSP\nMainThreadCheckerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {\n ProcessSP process_sp = GetProcessSP();\n if (!process_sp)\n return StructuredData::ObjectSP();\n\n ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();\n StackFrameSP frame_sp = thread_sp->GetSelectedFrame();\n ModuleSP runtime_module_sp = GetRuntimeModuleSP();\n Target &target = process_sp->GetTarget();\n\n if (!frame_sp)\n return StructuredData::ObjectSP();\n\n RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();\n if (!regctx_sp)\n return StructuredData::ObjectSP();\n\n const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName(\"arg1\");\n if (!reginfo)\n return StructuredData::ObjectSP();\n\n uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);\n if (!apiname_ptr)\n return StructuredData::ObjectSP();\n\n std::string apiName = \"\";\n Status read_error;\n target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);\n if (read_error.Fail())\n return StructuredData::ObjectSP();\n\n std::string className = \"\";\n std::string selector = \"\";\n if (apiName.substr(0, 2) == \"-[\") {\n size_t spacePos = apiName.find(\" \");\n if (spacePos != std::string::npos) {\n className = apiName.substr(2, spacePos - 2);\n selector = apiName.substr(spacePos + 1, apiName.length() - spacePos - 2);\n }\n }\n\n \/\/ Gather the PCs of the user frames in the backtrace.\n StructuredData::Array *trace = new StructuredData::Array();\n auto trace_sp = StructuredData::ObjectSP(trace);\n StackFrameSP responsible_frame;\n for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {\n StackFrameSP frame = thread_sp->GetStackFrameAtIndex(I);\n Address addr = frame->GetFrameCodeAddress();\n if (addr.GetModule() == runtime_module_sp) \/\/ Skip PCs from the runtime.\n continue;\n\n \/\/ The first non-runtime frame is responsible for the bug.\n if (!responsible_frame)\n responsible_frame = frame;\n\n \/\/ First frame in stacktrace should point to a real PC, not return address.\n if (I != 0 && trace->GetSize() == 0) {\n addr.Slide(-1);\n }\n\n lldb::addr_t PC = addr.GetLoadAddress(&target);\n trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(PC)));\n }\n \n if (responsible_frame) {\n if (responsible_frame->GetLanguage() == eLanguageTypeSwift) {\n std::string swiftApiName =\n TranslateObjCNameToSwiftName(className, selector, responsible_frame);\n if (swiftApiName != \"\")\n apiName = swiftApiName;\n }\n }\n \n auto *d = new StructuredData::Dictionary();\n auto dict_sp = StructuredData::ObjectSP(d);\n d->AddStringItem(\"instrumentation_class\", \"MainThreadChecker\");\n d->AddStringItem(\"api_name\", apiName);\n d->AddStringItem(\"class_name\", className);\n d->AddStringItem(\"selector\", selector);\n d->AddStringItem(\"description\",\n apiName + \" must be used from main thread only\");\n d->AddIntegerItem(\"tid\", thread_sp->GetIndexID());\n d->AddItem(\"trace\", trace_sp);\n return dict_sp;\n}\n\nbool MainThreadCheckerRuntime::NotifyBreakpointHit(\n void *baton, StoppointCallbackContext *context, user_id_t break_id,\n user_id_t break_loc_id) {\n assert(baton && \"null baton\");\n if (!baton)\n return false; \/\/< false => resume execution.\n\n MainThreadCheckerRuntime *const instance =\n static_cast<MainThreadCheckerRuntime *>(baton);\n\n ProcessSP process_sp = instance->GetProcessSP();\n ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();\n if (!process_sp || !thread_sp ||\n process_sp != context->exe_ctx_ref.GetProcessSP())\n return false;\n\n if (process_sp->GetModIDRef().IsLastResumeForUserExpression())\n return false;\n\n StructuredData::ObjectSP report =\n instance->RetrieveReportData(context->exe_ctx_ref);\n\n if (report) {\n std::string description = report->GetAsDictionary()\n ->GetValueForKey(\"description\")\n ->GetAsString()\n ->GetValue();\n thread_sp->SetStopInfo(\n InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(\n *thread_sp, description, report));\n return true;\n }\n\n return false;\n}\n\nvoid MainThreadCheckerRuntime::Activate() {\n if (IsActive())\n return;\n\n ProcessSP process_sp = GetProcessSP();\n if (!process_sp)\n return;\n\n ModuleSP runtime_module_sp = GetRuntimeModuleSP();\n\n ConstString symbol_name(\"__main_thread_checker_on_report\");\n const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(\n symbol_name, eSymbolTypeCode);\n\n if (symbol == nullptr)\n return;\n\n if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())\n return;\n\n Target &target = process_sp->GetTarget();\n addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);\n\n if (symbol_address == LLDB_INVALID_ADDRESS)\n return;\n\n Breakpoint *breakpoint =\n process_sp->GetTarget()\n .CreateBreakpoint(symbol_address, \/*internal=*\/true,\n \/*hardware=*\/false)\n .get();\n breakpoint->SetCallback(MainThreadCheckerRuntime::NotifyBreakpointHit, this,\n true);\n breakpoint->SetBreakpointKind(\"main-thread-checker-report\");\n SetBreakpointID(breakpoint->GetID());\n\n SetActive(true);\n}\n\nvoid MainThreadCheckerRuntime::Deactivate() {\n SetActive(false);\n\n auto BID = GetBreakpointID();\n if (BID == LLDB_INVALID_BREAK_ID)\n return;\n\n if (ProcessSP process_sp = GetProcessSP()) {\n process_sp->GetTarget().RemoveBreakpointByID(BID);\n SetBreakpointID(LLDB_INVALID_BREAK_ID);\n }\n}\n\nlldb::ThreadCollectionSP\nMainThreadCheckerRuntime::GetBacktracesFromExtendedStopInfo(\n StructuredData::ObjectSP info) {\n ThreadCollectionSP threads;\n threads.reset(new ThreadCollection());\n \n ProcessSP process_sp = GetProcessSP();\n \n if (info->GetObjectForDotSeparatedPath(\"instrumentation_class\")\n ->GetStringValue() != \"MainThreadChecker\")\n return threads;\n \n std::vector<lldb::addr_t> PCs;\n auto trace = info->GetObjectForDotSeparatedPath(\"trace\")->GetAsArray();\n trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {\n PCs.push_back(PC->GetAsInteger()->GetValue());\n return true;\n });\n \n if (PCs.empty())\n return threads;\n \n StructuredData::ObjectSP thread_id_obj =\n info->GetObjectForDotSeparatedPath(\"tid\");\n tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;\n \n uint32_t stop_id = 0;\n bool stop_id_is_valid = false;\n HistoryThread *history_thread =\n new HistoryThread(*process_sp, tid, PCs, stop_id, stop_id_is_valid);\n ThreadSP new_thread_sp(history_thread);\n \n \/\/ Save this in the Process' ExtendedThreadList so a strong pointer\n \/\/ retains the object\n process_sp->GetExtendedThreadList().AddThread(new_thread_sp);\n threads->AddThread(new_thread_sp);\n\n return threads;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Single cell view information solvers widget\n\/\/==============================================================================\n\n#include \"cellmlfileruntime.h\"\n#include \"corecliutils.h\"\n#include \"singlecellviewinformationsolverswidget.h\"\n#include \"singlecellviewplugin.h\"\n#include \"singlecellviewsimulation.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace SingleCellView {\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData::SingleCellViewInformationSolversWidgetData(const QMap<QString, SolverInterface *> &pSolversInterfaces,\n Core::Property *pSolversProperty,\n Core::Property *pSolversListProperty,\n const QMap<QString, Core::Properties> &pSolversProperties) :\n mSolversInterfaces(pSolversInterfaces),\n mSolversProperty(pSolversProperty),\n mSolversListProperty(pSolversListProperty),\n mSolversProperties(pSolversProperties)\n{\n}\n\n\/\/==============================================================================\n\nQMap<QString, SolverInterface *> SingleCellViewInformationSolversWidgetData::solversInterfaces() const\n{\n \/\/ Return our solvers interfaces\n\n return mSolversInterfaces;\n}\n\n\/\/==============================================================================\n\nCore::Property * SingleCellViewInformationSolversWidgetData::solversProperty() const\n{\n \/\/ Return our solvers property\n\n return mSolversProperty;\n}\n\n\/\/==============================================================================\n\nCore::Property * SingleCellViewInformationSolversWidgetData::solversListProperty() const\n{\n \/\/ Return our solvers list property\n\n return mSolversListProperty;\n}\n\n\/\/==============================================================================\n\nQMap<QString, Core::Properties> SingleCellViewInformationSolversWidgetData::solversProperties() const\n{\n \/\/ Return our solvers properties\n\n return mSolversProperties;\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidget::SingleCellViewInformationSolversWidget(SingleCellViewPlugin *pPlugin,\n QWidget *pParent) :\n PropertyEditorWidget(true, pParent),\n mDescriptions(QMap<Core::Property *, Descriptions>())\n{\n \/\/ Remove all our properties\n\n removeAllProperties();\n\n \/\/ Add properties for our different solvers\n\n mOdeSolverData = addSolverProperties(pPlugin->solverInterfaces(), Solver::Ode);\n mDaeSolverData = addSolverProperties(pPlugin->solverInterfaces(), Solver::Dae);\n mNlaSolverData = addSolverProperties(pPlugin->solverInterfaces(), Solver::Nla);\n\n \/\/ Show\/hide the relevant properties\n\n if (mOdeSolverData)\n doSolverChanged(mOdeSolverData, mOdeSolverData->solversListProperty()->value());\n\n if (mDaeSolverData)\n doSolverChanged(mDaeSolverData, mDaeSolverData->solversListProperty()->value());\n\n if (mNlaSolverData)\n doSolverChanged(mNlaSolverData, mNlaSolverData->solversListProperty()->value());\n\n \/\/ Expand all our properties\n\n expandAll();\n\n \/\/ Keep track of changes to list properties\n\n connect(this, SIGNAL(propertyChanged(Core::Property *)),\n this, SLOT(solverChanged(Core::Property *)));\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidget::~SingleCellViewInformationSolversWidget()\n{\n \/\/ Delete some internal objects\n\n delete mOdeSolverData;\n delete mDaeSolverData;\n delete mNlaSolverData;\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::retranslateUi()\n{\n \/\/ Update our property names\n\n if (mOdeSolverData) {\n mOdeSolverData->solversProperty()->setName(tr(\"ODE solver\"));\n mOdeSolverData->solversListProperty()->setName(tr(\"Name\"));\n\n mOdeSolverData->solversListProperty()->setEmptyListValue(tr(\"None available\"));\n }\n\n if (mDaeSolverData) {\n mDaeSolverData->solversProperty()->setName(tr(\"DAE solver\"));\n mDaeSolverData->solversListProperty()->setName(tr(\"Name\"));\n\n mDaeSolverData->solversListProperty()->setEmptyListValue(tr(\"None available\"));\n }\n\n if (mNlaSolverData) {\n mNlaSolverData->solversProperty()->setName(tr(\"NLA solver\"));\n mNlaSolverData->solversListProperty()->setName(tr(\"Name\"));\n\n mNlaSolverData->solversListProperty()->setEmptyListValue(tr(\"None available\"));\n }\n\n \/\/ Update the name of our various properties, should they have a description\n \/\/ associated with them\n \/\/ Note: this is effectively to have the description of our solvers'\n \/\/ properties properly updated...\n\n foreach (Core::Property *property, properties()) {\n if (mDescriptions.contains(property)) {\n \/\/ The property has a description associated with it, so retrieve\n \/\/ the version, if any, which corresponds to our current locale\n\n Descriptions descriptions = mDescriptions.value(property);\n QString description = descriptions.value(Core::locale());\n\n if (description.isEmpty()) {\n \/\/ No description exists for the current locale, so retrieve the\n \/\/ English description (which, hopefully, exists)\n\n description = descriptions.value(\"en\");\n }\n\n \/\/ Set the name of the property to the description\n\n property->setName(description);\n }\n }\n\n \/\/ Default retranslation\n \/\/ Note: we must do it last since we set the empty list value of some\n \/\/ properties above...\n\n PropertyEditorWidget::retranslateUi();\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces,\n const Solver::Type &pSolverType)\n{\n \/\/ Make sure that we have at least one solver interface\n\n if (pSolverInterfaces.isEmpty())\n return 0;\n\n \/\/ Retrieve the name of the solvers which type is the one in which we are\n \/\/ interested\n\n QMap<QString, SolverInterface *> solversInterfaces = QMap<QString, SolverInterface *>();\n Core::Property *solversProperty = 0;\n Core::Property *solversListProperty = 0;\n QStringList solversNames = QStringList();\n QMap<QString, Core::Properties> solversProperties = QMap<QString, Core::Properties>();\n\n foreach (SolverInterface *solverInterface, pSolverInterfaces) {\n if (solverInterface->solverType() == pSolverType) {\n \/\/ Keep track of the solver's interface\n\n solversInterfaces.insert(solverInterface->solverName(), solverInterface);\n\n \/\/ Keep track of the solver's name\n\n solversNames << solverInterface->solverName();\n\n \/\/ Add our solvers section property and list property for our\n \/\/ solvers, if needed\n\n if (!solversProperty) {\n solversProperty = addSectionProperty();\n\n solversListProperty = addListProperty(solversProperty);\n }\n\n \/\/ Add the solver's properties\n\n Core::Property *property;\n Core::Properties properties = Core::Properties();\n\n foreach (const Solver::Property &solverInterfaceProperty,\n solverInterface->solverProperties()) {\n \/\/ Add the solver's property and set its default value\n\n switch (solverInterfaceProperty.type()) {\n case Solver::Property::Boolean:\n property = addBooleanProperty(solverInterfaceProperty.defaultValue().toBool(),\n solversProperty);\n\n break;\n case Solver::Property::Integer:\n property = addIntegerProperty(solverInterfaceProperty.defaultValue().toInt(),\n solversProperty);\n\n break;\n case Solver::Property::Double:\n property = addDoubleProperty(solverInterfaceProperty.defaultValue().toDouble(),\n solversProperty);\n\n break;\n case Solver::Property::List:\n property = addListProperty(solverInterfaceProperty.listValues(),\n solverInterfaceProperty.defaultValue().toString(),\n solversProperty);\n\n break;\n }\n\n property->setId(solverInterfaceProperty.id());\n\n \/\/ Make the property editable\n\n property->setEditable(true);\n\n \/\/ Set the solver's property's 'unit', if needed\n\n if (solverInterfaceProperty.hasVoiUnit())\n property->setUnit(\"???\");\n \/\/ Note: to assign a non-empty string to our unit item is\n \/\/ just a way for us to make sure that the property's\n \/\/ will get initialised (see setPropertiesUnit())...\n\n \/\/ Keep track of the solver's property\n\n properties << property;\n\n \/\/ Keep track of the solver's property's descriptions\n\n mDescriptions.insert(property, solverInterfaceProperty.descriptions());\n }\n\n \/\/ Keep track of the solver's properties\n\n solversProperties.insert(solverInterface->solverName(), properties);\n }\n }\n\n \/\/ Check whether we have at least one solver\n\n if (solversListProperty) {\n \/\/ We have a solvers list property, which means that we have at least\n \/\/ one solver, so sort our list\n\n solversNames.sort();\n\n \/\/ Assign the list of solvers to our list property\n\n solversListProperty->setListValues(solversNames);\n\n \/\/ Create and return our solver data\n\n return new SingleCellViewInformationSolversWidgetData(solversInterfaces,\n solversProperty,\n solversListProperty,\n solversProperties);\n } else {\n return 0;\n }\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::setPropertiesUnit(SingleCellViewInformationSolversWidgetData *pSolverData,\n const QString &pVoiUnit)\n{\n \/\/ Make sure that we have some solver's data\n\n if (!pSolverData)\n return;\n\n \/\/ Go through the solvers' properties and set the unit of the relevant ones\n\n foreach (const Core::Properties &properties, pSolverData->solversProperties())\n foreach (Core::Property *property, properties)\n if (!property->unit().isEmpty())\n property->setUnit(pVoiUnit);\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::initialize(SingleCellViewSimulation *pSimulation)\n{\n \/\/ Make sure that the CellML file runtime is valid\n\n if (pSimulation->runtime()->isValid()) {\n \/\/ Show\/hide the ODE\/DAE\/NLA solver information\n\n if (mOdeSolverData)\n mOdeSolverData->solversProperty()->setVisible(pSimulation->runtime()->needOdeSolver());\n\n if (mDaeSolverData)\n mDaeSolverData->solversProperty()->setVisible(pSimulation->runtime()->needDaeSolver());\n\n if (mNlaSolverData)\n mNlaSolverData->solversProperty()->setVisible(pSimulation->runtime()->needNlaSolver());\n }\n\n \/\/ Set the unit of our different properties, if needed\n\n QString voiUnit = pSimulation->runtime()->variableOfIntegration()->unit();\n\n setPropertiesUnit(mOdeSolverData, voiUnit);\n setPropertiesUnit(mDaeSolverData, voiUnit);\n setPropertiesUnit(mNlaSolverData, voiUnit);\n\n \/\/ Initialise our simulation's NLA solver's properties, so that we can then\n \/\/ properly reset our simulation the first time round\n\n if (mNlaSolverData) {\n pSimulation->data()->setNlaSolverName(mNlaSolverData->solversListProperty()->value(), false);\n\n foreach (Core::Property *property, mNlaSolverData->solversProperties().value(pSimulation->data()->nlaSolverName())) {\n pSimulation->data()->addNlaSolverProperty(property->id(),\n (property->type() == Core::Property::Integer)?\n property->integerValue():\n property->doubleValue(),\n false);\n }\n }\n}\n\n\/\/==============================================================================\n\nQStringList SingleCellViewInformationSolversWidget::odeSolvers() const\n{\n \/\/ Return the available ODE solvers, if any\n\n return mOdeSolverData?mOdeSolverData->solversListProperty()->listValues():QStringList();\n}\n\n\/\/==============================================================================\n\nQStringList SingleCellViewInformationSolversWidget::daeSolvers() const\n{\n \/\/ Return the available DAE solvers, if any\n\n return mDaeSolverData?mDaeSolverData->solversListProperty()->listValues():QStringList();\n}\n\n\/\/==============================================================================\n\nQStringList SingleCellViewInformationSolversWidget::nlaSolvers() const\n{\n \/\/ Return the available NLA solvers, if any\n\n return mNlaSolverData?mNlaSolverData->solversListProperty()->listValues():QStringList();\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::odeSolverData() const\n{\n \/\/ Return our ODE solver data\n\n return mOdeSolverData;\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::daeSolverData() const\n{\n \/\/ Return our DAE solver data\n\n return mDaeSolverData;\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::nlaSolverData() const\n{\n \/\/ Return our NLA solver data\n\n return mNlaSolverData;\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::updateSolverGui(SingleCellViewInformationSolversWidgetData *pSolverData)\n{\n \/\/ Make sure that we have some solver data\n\n if (!pSolverData)\n return;\n\n \/\/ Update our solver properties visibility\n\n QString solverName = pSolverData->solversListProperty()->value();\n SolverInterface *solverInterface = pSolverData->solversInterfaces().value(solverName);\n Core::Properties solverProperties = pSolverData->solversProperties().value(solverName);\n\n \/\/ Retrieve our solver properties values\n\n QMap<QString, QString> solverPropertiesValues = QMap<QString, QString>();\n\n foreach (Core::Property *solverProperty, solverProperties)\n solverPropertiesValues.insert(solverProperty->id(),solverProperty->value());\n\n \/\/ Ask our solver interface to tell us about the visibility of its\n \/\/ properties based on their values\n\n QMap<QString, bool> solverPropertiesVisibility = solverInterface->solverPropertiesVisibility(solverPropertiesValues);\n\n \/\/ Update the visilibity of our solver properties\n \/\/ Note: if there is no visibility information for a given solver property,\n \/\/ then it means that it should be visible...\n\n foreach (Core::Property *solverProperty, solverProperties)\n solverProperty->setVisible(solverPropertiesVisibility.value(solverProperty->id(), true));\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::updateGui(SingleCellViewInformationSolversWidgetData *pSolverData)\n{\n \/\/ Update our solver(s) properties visibility\n\n if (mOdeSolverData && (!pSolverData || (pSolverData == mOdeSolverData)))\n updateSolverGui(mOdeSolverData);\n\n if (mDaeSolverData && (!pSolverData || (pSolverData == mDaeSolverData)))\n updateSolverGui(mDaeSolverData);\n\n if (mNlaSolverData && (!pSolverData || (pSolverData == mNlaSolverData)))\n updateSolverGui(mNlaSolverData);\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::doSolverChanged(SingleCellViewInformationSolversWidgetData *pSolverData,\n const QString &pSolverName)\n{\n \/\/ Make sure that we have some solver data\n\n if (!pSolverData)\n return;\n\n \/\/ Go through the different properties for the given type of solver and\n \/\/ show\/hide whatever needs showing\/hiding\n\n for (auto solverProperties = pSolverData->solversProperties().constBegin(),\n solverPropertiesEnd = pSolverData->solversProperties().constEnd();\n solverProperties != solverPropertiesEnd; ++solverProperties) {\n bool solverPropertiesVisible = !solverProperties.key().compare(pSolverName);\n\n foreach (Core::Property *solverProperty, solverProperties.value())\n solverProperty->setVisible(solverPropertiesVisible);\n }\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::solverChanged(Core::Property *pProperty)\n{\n \/\/ Try, for the ODE\/DAE\/NLA solvers list property, to handle the change in\n \/\/ the list property\n \/\/ Note: the ODE\/DAE\/NLA solvers list property is our first property, hence\n \/\/ we make sure that its row number is equal to zero (in case there is\n \/\/ one or several other list properties, as is the case for the CVODE\n \/\/ and IDA solvers)...\n\n if (!pProperty->row()) {\n doSolverChanged((mOdeSolverData && (pProperty == mOdeSolverData->solversListProperty()))?\n mOdeSolverData:\n (mDaeSolverData && (pProperty == mDaeSolverData->solversListProperty()))?\n mDaeSolverData:\n mNlaSolverData,\n pProperty->value());\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace SingleCellView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Some minor cleaning up [ci skip].<commit_after>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Single cell view information solvers widget\n\/\/==============================================================================\n\n#include \"cellmlfileruntime.h\"\n#include \"corecliutils.h\"\n#include \"singlecellviewinformationsolverswidget.h\"\n#include \"singlecellviewplugin.h\"\n#include \"singlecellviewsimulation.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace SingleCellView {\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData::SingleCellViewInformationSolversWidgetData(const QMap<QString, SolverInterface *> &pSolversInterfaces,\n Core::Property *pSolversProperty,\n Core::Property *pSolversListProperty,\n const QMap<QString, Core::Properties> &pSolversProperties) :\n mSolversInterfaces(pSolversInterfaces),\n mSolversProperty(pSolversProperty),\n mSolversListProperty(pSolversListProperty),\n mSolversProperties(pSolversProperties)\n{\n}\n\n\/\/==============================================================================\n\nQMap<QString, SolverInterface *> SingleCellViewInformationSolversWidgetData::solversInterfaces() const\n{\n \/\/ Return our solvers interfaces\n\n return mSolversInterfaces;\n}\n\n\/\/==============================================================================\n\nCore::Property * SingleCellViewInformationSolversWidgetData::solversProperty() const\n{\n \/\/ Return our solvers property\n\n return mSolversProperty;\n}\n\n\/\/==============================================================================\n\nCore::Property * SingleCellViewInformationSolversWidgetData::solversListProperty() const\n{\n \/\/ Return our solvers list property\n\n return mSolversListProperty;\n}\n\n\/\/==============================================================================\n\nQMap<QString, Core::Properties> SingleCellViewInformationSolversWidgetData::solversProperties() const\n{\n \/\/ Return our solvers properties\n\n return mSolversProperties;\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidget::SingleCellViewInformationSolversWidget(SingleCellViewPlugin *pPlugin,\n QWidget *pParent) :\n PropertyEditorWidget(true, pParent),\n mDescriptions(QMap<Core::Property *, Descriptions>())\n{\n \/\/ Remove all our properties\n\n removeAllProperties();\n\n \/\/ Add properties for our different solvers\n\n mOdeSolverData = addSolverProperties(pPlugin->solverInterfaces(), Solver::Ode);\n mDaeSolverData = addSolverProperties(pPlugin->solverInterfaces(), Solver::Dae);\n mNlaSolverData = addSolverProperties(pPlugin->solverInterfaces(), Solver::Nla);\n\n \/\/ Show\/hide the relevant properties\n\n if (mOdeSolverData)\n doSolverChanged(mOdeSolverData, mOdeSolverData->solversListProperty()->value());\n\n if (mDaeSolverData)\n doSolverChanged(mDaeSolverData, mDaeSolverData->solversListProperty()->value());\n\n if (mNlaSolverData)\n doSolverChanged(mNlaSolverData, mNlaSolverData->solversListProperty()->value());\n\n \/\/ Expand all our properties\n\n expandAll();\n\n \/\/ Keep track of changes to list properties\n\n connect(this, SIGNAL(propertyChanged(Core::Property *)),\n this, SLOT(solverChanged(Core::Property *)));\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidget::~SingleCellViewInformationSolversWidget()\n{\n \/\/ Delete some internal objects\n\n delete mOdeSolverData;\n delete mDaeSolverData;\n delete mNlaSolverData;\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::retranslateUi()\n{\n \/\/ Update our property names\n\n if (mOdeSolverData) {\n mOdeSolverData->solversProperty()->setName(tr(\"ODE solver\"));\n mOdeSolverData->solversListProperty()->setName(tr(\"Name\"));\n\n mOdeSolverData->solversListProperty()->setEmptyListValue(tr(\"None available\"));\n }\n\n if (mDaeSolverData) {\n mDaeSolverData->solversProperty()->setName(tr(\"DAE solver\"));\n mDaeSolverData->solversListProperty()->setName(tr(\"Name\"));\n\n mDaeSolverData->solversListProperty()->setEmptyListValue(tr(\"None available\"));\n }\n\n if (mNlaSolverData) {\n mNlaSolverData->solversProperty()->setName(tr(\"NLA solver\"));\n mNlaSolverData->solversListProperty()->setName(tr(\"Name\"));\n\n mNlaSolverData->solversListProperty()->setEmptyListValue(tr(\"None available\"));\n }\n\n \/\/ Update the name of our various properties, should they have a description\n \/\/ associated with them\n \/\/ Note: this is effectively to have the description of our solvers'\n \/\/ properties properly updated...\n\n foreach (Core::Property *property, properties()) {\n if (mDescriptions.contains(property)) {\n \/\/ The property has a description associated with it, so retrieve\n \/\/ the version, if any, which corresponds to our current locale\n\n Descriptions descriptions = mDescriptions.value(property);\n QString description = descriptions.value(Core::locale());\n\n if (description.isEmpty()) {\n \/\/ No description exists for the current locale, so retrieve the\n \/\/ English description (which, hopefully, exists)\n\n description = descriptions.value(\"en\");\n }\n\n \/\/ Set the name of the property to the description\n\n property->setName(description);\n }\n }\n\n \/\/ Default retranslation\n \/\/ Note: we must do it last since we set the empty list value of some\n \/\/ properties above...\n\n PropertyEditorWidget::retranslateUi();\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces,\n const Solver::Type &pSolverType)\n{\n \/\/ Make sure that we have at least one solver interface\n\n if (pSolverInterfaces.isEmpty())\n return 0;\n\n \/\/ Retrieve the name of the solvers which type is the one in which we are\n \/\/ interested\n\n QMap<QString, SolverInterface *> solversInterfaces = QMap<QString, SolverInterface *>();\n Core::Property *solversProperty = 0;\n Core::Property *solversListProperty = 0;\n QStringList solversNames = QStringList();\n QMap<QString, Core::Properties> solversProperties = QMap<QString, Core::Properties>();\n\n foreach (SolverInterface *solverInterface, pSolverInterfaces) {\n if (solverInterface->solverType() == pSolverType) {\n \/\/ Keep track of the solver's interface\n\n solversInterfaces.insert(solverInterface->solverName(), solverInterface);\n\n \/\/ Keep track of the solver's name\n\n solversNames << solverInterface->solverName();\n\n \/\/ Add our solvers section property and list property for our\n \/\/ solvers, if needed\n\n if (!solversProperty) {\n solversProperty = addSectionProperty();\n\n solversListProperty = addListProperty(solversProperty);\n }\n\n \/\/ Add the solver's properties\n\n Core::Property *property = 0;\n Core::Properties properties = Core::Properties();\n\n foreach (const Solver::Property &solverInterfaceProperty,\n solverInterface->solverProperties()) {\n \/\/ Add the solver's property and set its default value\n\n switch (solverInterfaceProperty.type()) {\n case Solver::Property::Boolean:\n property = addBooleanProperty(solverInterfaceProperty.defaultValue().toBool(),\n solversProperty);\n\n break;\n case Solver::Property::Integer:\n property = addIntegerProperty(solverInterfaceProperty.defaultValue().toInt(),\n solversProperty);\n\n break;\n case Solver::Property::Double:\n property = addDoubleProperty(solverInterfaceProperty.defaultValue().toDouble(),\n solversProperty);\n\n break;\n case Solver::Property::List:\n property = addListProperty(solverInterfaceProperty.listValues(),\n solverInterfaceProperty.defaultValue().toString(),\n solversProperty);\n\n break;\n }\n\n property->setId(solverInterfaceProperty.id());\n\n \/\/ Make the property editable\n\n property->setEditable(true);\n\n \/\/ Set the solver's property's 'unit', if needed\n\n if (solverInterfaceProperty.hasVoiUnit())\n property->setUnit(\"???\");\n \/\/ Note: to assign a non-empty string to our unit item is\n \/\/ just a way for us to make sure that the property's\n \/\/ will get initialised (see setPropertiesUnit())...\n\n \/\/ Keep track of the solver's property\n\n properties << property;\n\n \/\/ Keep track of the solver's property's descriptions\n\n mDescriptions.insert(property, solverInterfaceProperty.descriptions());\n }\n\n \/\/ Keep track of the solver's properties\n\n solversProperties.insert(solverInterface->solverName(), properties);\n }\n }\n\n \/\/ Check whether we have at least one solver\n\n if (solversListProperty) {\n \/\/ We have a solvers list property, which means that we have at least\n \/\/ one solver, so sort our list\n\n solversNames.sort();\n\n \/\/ Assign the list of solvers to our list property\n\n solversListProperty->setListValues(solversNames);\n\n \/\/ Create and return our solver data\n\n return new SingleCellViewInformationSolversWidgetData(solversInterfaces,\n solversProperty,\n solversListProperty,\n solversProperties);\n } else {\n return 0;\n }\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::setPropertiesUnit(SingleCellViewInformationSolversWidgetData *pSolverData,\n const QString &pVoiUnit)\n{\n \/\/ Make sure that we have some solver's data\n\n if (!pSolverData)\n return;\n\n \/\/ Go through the solvers' properties and set the unit of the relevant ones\n\n foreach (const Core::Properties &properties, pSolverData->solversProperties())\n foreach (Core::Property *property, properties)\n if (!property->unit().isEmpty())\n property->setUnit(pVoiUnit);\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::initialize(SingleCellViewSimulation *pSimulation)\n{\n \/\/ Make sure that the CellML file runtime is valid\n\n if (pSimulation->runtime()->isValid()) {\n \/\/ Show\/hide the ODE\/DAE\/NLA solver information\n\n if (mOdeSolverData)\n mOdeSolverData->solversProperty()->setVisible(pSimulation->runtime()->needOdeSolver());\n\n if (mDaeSolverData)\n mDaeSolverData->solversProperty()->setVisible(pSimulation->runtime()->needDaeSolver());\n\n if (mNlaSolverData)\n mNlaSolverData->solversProperty()->setVisible(pSimulation->runtime()->needNlaSolver());\n }\n\n \/\/ Set the unit of our different properties, if needed\n\n QString voiUnit = pSimulation->runtime()->variableOfIntegration()->unit();\n\n setPropertiesUnit(mOdeSolverData, voiUnit);\n setPropertiesUnit(mDaeSolverData, voiUnit);\n setPropertiesUnit(mNlaSolverData, voiUnit);\n\n \/\/ Initialise our simulation's NLA solver's properties, so that we can then\n \/\/ properly reset our simulation the first time round\n\n if (mNlaSolverData) {\n pSimulation->data()->setNlaSolverName(mNlaSolverData->solversListProperty()->value(), false);\n\n foreach (Core::Property *property, mNlaSolverData->solversProperties().value(pSimulation->data()->nlaSolverName())) {\n pSimulation->data()->addNlaSolverProperty(property->id(),\n (property->type() == Core::Property::Integer)?\n property->integerValue():\n property->doubleValue(),\n false);\n }\n }\n}\n\n\/\/==============================================================================\n\nQStringList SingleCellViewInformationSolversWidget::odeSolvers() const\n{\n \/\/ Return the available ODE solvers, if any\n\n return mOdeSolverData?mOdeSolverData->solversListProperty()->listValues():QStringList();\n}\n\n\/\/==============================================================================\n\nQStringList SingleCellViewInformationSolversWidget::daeSolvers() const\n{\n \/\/ Return the available DAE solvers, if any\n\n return mDaeSolverData?mDaeSolverData->solversListProperty()->listValues():QStringList();\n}\n\n\/\/==============================================================================\n\nQStringList SingleCellViewInformationSolversWidget::nlaSolvers() const\n{\n \/\/ Return the available NLA solvers, if any\n\n return mNlaSolverData?mNlaSolverData->solversListProperty()->listValues():QStringList();\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::odeSolverData() const\n{\n \/\/ Return our ODE solver data\n\n return mOdeSolverData;\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::daeSolverData() const\n{\n \/\/ Return our DAE solver data\n\n return mDaeSolverData;\n}\n\n\/\/==============================================================================\n\nSingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::nlaSolverData() const\n{\n \/\/ Return our NLA solver data\n\n return mNlaSolverData;\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::updateSolverGui(SingleCellViewInformationSolversWidgetData *pSolverData)\n{\n \/\/ Make sure that we have some solver data\n\n if (!pSolverData)\n return;\n\n \/\/ Update our solver properties visibility\n\n QString solverName = pSolverData->solversListProperty()->value();\n SolverInterface *solverInterface = pSolverData->solversInterfaces().value(solverName);\n Core::Properties solverProperties = pSolverData->solversProperties().value(solverName);\n\n \/\/ Retrieve our solver properties values\n\n QMap<QString, QString> solverPropertiesValues = QMap<QString, QString>();\n\n foreach (Core::Property *solverProperty, solverProperties)\n solverPropertiesValues.insert(solverProperty->id(),solverProperty->value());\n\n \/\/ Ask our solver interface to tell us about the visibility of its\n \/\/ properties based on their values\n\n QMap<QString, bool> solverPropertiesVisibility = solverInterface->solverPropertiesVisibility(solverPropertiesValues);\n\n \/\/ Update the visilibity of our solver properties\n \/\/ Note: if there is no visibility information for a given solver property,\n \/\/ then it means that it should be visible...\n\n foreach (Core::Property *solverProperty, solverProperties)\n solverProperty->setVisible(solverPropertiesVisibility.value(solverProperty->id(), true));\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::updateGui(SingleCellViewInformationSolversWidgetData *pSolverData)\n{\n \/\/ Update our solver(s) properties visibility\n\n if (mOdeSolverData && (!pSolverData || (pSolverData == mOdeSolverData)))\n updateSolverGui(mOdeSolverData);\n\n if (mDaeSolverData && (!pSolverData || (pSolverData == mDaeSolverData)))\n updateSolverGui(mDaeSolverData);\n\n if (mNlaSolverData && (!pSolverData || (pSolverData == mNlaSolverData)))\n updateSolverGui(mNlaSolverData);\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::doSolverChanged(SingleCellViewInformationSolversWidgetData *pSolverData,\n const QString &pSolverName)\n{\n \/\/ Make sure that we have some solver data\n\n if (!pSolverData)\n return;\n\n \/\/ Go through the different properties for the given type of solver and\n \/\/ show\/hide whatever needs showing\/hiding\n\n for (auto solverProperties = pSolverData->solversProperties().constBegin(),\n solverPropertiesEnd = pSolverData->solversProperties().constEnd();\n solverProperties != solverPropertiesEnd; ++solverProperties) {\n bool solverPropertiesVisible = !solverProperties.key().compare(pSolverName);\n\n foreach (Core::Property *solverProperty, solverProperties.value())\n solverProperty->setVisible(solverPropertiesVisible);\n }\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewInformationSolversWidget::solverChanged(Core::Property *pProperty)\n{\n \/\/ Try, for the ODE\/DAE\/NLA solvers list property, to handle the change in\n \/\/ the list property\n \/\/ Note: the ODE\/DAE\/NLA solvers list property is our first property, hence\n \/\/ we make sure that its row number is equal to zero (in case there is\n \/\/ one or several other list properties, as is the case for the CVODE\n \/\/ and IDA solvers)...\n\n if (!pProperty->row()) {\n doSolverChanged((mOdeSolverData && (pProperty == mOdeSolverData->solversListProperty()))?\n mOdeSolverData:\n (mDaeSolverData && (pProperty == mDaeSolverData->solversListProperty()))?\n mDaeSolverData:\n mNlaSolverData,\n pProperty->value());\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace SingleCellView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <type_traits>\n#include <boost\/iterator\/transform_iterator.hpp>\n#include <boost\/range\/iterator_range.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n\n#include <amgcl\/relaxation\/runtime.hpp>\n#include <amgcl\/coarsening\/runtime.hpp>\n#include <amgcl\/solver\/runtime.hpp>\n#include <amgcl\/make_solver.hpp>\n#include <amgcl\/amg.hpp>\n#include <amgcl\/backend\/builtin.hpp>\n#include <amgcl\/adapter\/crs_tuple.hpp>\n\n#include \"amgcl.h\"\n\n#ifdef AMGCL_PROFILING\n#include <amgcl\/profiler.hpp>\nnamespace amgcl {\n profiler<> prof;\n}\n#endif\n\n\/\/---------------------------------------------------------------------------\ntypedef amgcl::backend::builtin<double> Backend;\ntypedef amgcl::amg<Backend, amgcl::runtime::coarsening::wrapper, amgcl::runtime::relaxation::wrapper> AMG;\ntypedef amgcl::runtime::solver::wrapper<Backend> ISolver;\ntypedef amgcl::make_solver<AMG, ISolver> Solver;\ntypedef boost::property_tree::ptree Params;\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_params_create() {\n return static_cast<amgclHandle>( new Params() );\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_seti(amgclHandle prm, const char *name, int value) {\n static_cast<Params*>(prm)->put(name, value);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_setf(amgclHandle prm, const char *name, float value) {\n static_cast<Params*>(prm)->put(name, value);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_sets(amgclHandle prm, const char *name, const char *value) {\n static_cast<Params*>(prm)->put(name, value);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_read_json(amgclHandle prm, const char *fname) {\n read_json(fname, *static_cast<Params*>(prm));\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_destroy(amgclHandle prm) {\n delete static_cast<Params*>(prm);\n}\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_precond_create(\n int n,\n const int *ptr,\n const int *col,\n const double *val,\n amgclHandle prm\n )\n{\n auto A = std::make_tuple(n,\n boost::make_iterator_range(ptr, ptr + n + 1),\n boost::make_iterator_range(col, col + ptr[n]),\n boost::make_iterator_range(val, val + ptr[n])\n );\n\n if (prm)\n return static_cast<amgclHandle>(new AMG(A, *static_cast<Params*>(prm)));\n else\n return static_cast<amgclHandle>(new AMG(A));\n}\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_precond_create_f(\n int n,\n const int *ptr,\n const int *col,\n const double *val,\n amgclHandle prm\n )\n{\n auto ptr_c = boost::make_transform_iterator(ptr, [](int i){ return i - 1; });\n auto col_c = boost::make_transform_iterator(col, [](int i){ return i - 1; });\n\n auto A = std::make_tuple(n,\n boost::make_iterator_range(ptr_c, ptr_c + n + 1),\n boost::make_iterator_range(col_c, col_c + ptr[n]),\n boost::make_iterator_range(val, val + ptr[n])\n );\n\n if (prm)\n return static_cast<amgclHandle>(new AMG(A, *static_cast<Params*>(prm)));\n else\n return static_cast<amgclHandle>(new AMG(A));\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_precond_apply(amgclHandle handle, const double *rhs, double *x)\n{\n AMG *amg = static_cast<AMG*>(handle);\n\n size_t n = amgcl::backend::rows(amg->system_matrix());\n\n boost::iterator_range<double*> x_range =\n boost::make_iterator_range(x, x + n);\n\n amg->apply(boost::make_iterator_range(rhs, rhs + n), x_range);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_precond_report(amgclHandle handle) {\n std::cout << *static_cast<AMG*>(handle) << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_precond_destroy(amgclHandle handle) {\n delete static_cast<AMG*>(handle);\n}\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_solver_create(\n int n,\n const int *ptr,\n const int *col,\n const double *val,\n amgclHandle prm\n )\n{\n auto A = std::make_tuple(n,\n boost::make_iterator_range(ptr, ptr + n + 1),\n boost::make_iterator_range(col, col + ptr[n]),\n boost::make_iterator_range(val, val + ptr[n])\n );\n\n if (prm)\n return static_cast<amgclHandle>(new Solver(A, *static_cast<Params*>(prm)));\n else\n return static_cast<amgclHandle>(new Solver(A));\n}\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_solver_create_f(\n int n,\n const int *ptr,\n const int *col,\n const double *val,\n amgclHandle prm\n )\n{\n auto ptr_c = boost::make_transform_iterator(ptr, [](int i){ return i - 1; });\n auto col_c = boost::make_transform_iterator(col, [](int i){ return i - 1; });\n\n auto A = std::make_tuple(n,\n boost::make_iterator_range(ptr_c, ptr_c + n + 1),\n boost::make_iterator_range(col_c, col_c + ptr[n]),\n boost::make_iterator_range(val, val + ptr[n])\n );\n\n if (prm)\n return static_cast<amgclHandle>(new Solver(A, *static_cast<Params*>(prm)));\n else\n return static_cast<amgclHandle>(new Solver(A));\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_solver_report(amgclHandle handle) {\n std::cout << static_cast<Solver*>(handle)->precond() << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_solver_destroy(amgclHandle handle) {\n delete static_cast<Solver*>(handle);\n}\n\n\/\/---------------------------------------------------------------------------\nconv_info STDCALL amgcl_solver_solve(\n amgclHandle handle,\n const double *rhs,\n double *x\n )\n{\n Solver *slv = static_cast<Solver*>(handle);\n\n size_t n = slv->size();\n\n conv_info cnv;\n\n boost::iterator_range<double*> x_range = boost::make_iterator_range(x, x + n);\n\n std::tie(cnv.iterations, cnv.residual) = (*slv)(\n boost::make_iterator_range(rhs, rhs + n), x_range\n );\n\n return cnv;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_solver_solve_f(\n amgclHandle handle,\n const double *rhs,\n double *x,\n conv_info *cnv\n )\n{\n *cnv = amgcl_solver_solve(handle, rhs, x);\n}\n\n\/\/---------------------------------------------------------------------------\nconv_info STDCALL amgcl_solver_solve_mtx(\n amgclHandle handle,\n int const * A_ptr,\n int const * A_col,\n double const * A_val,\n const double *rhs,\n double *x\n )\n{\n Solver *slv = static_cast<Solver*>(handle);\n\n size_t n = slv->size();\n\n conv_info cnv;\n\n boost::iterator_range<double*> x_range = boost::make_iterator_range(x, x + n);\n\n std::tie(cnv.iterations, cnv.residual) = (*slv)(\n std::make_tuple(\n n,\n boost::make_iterator_range(A_ptr, A_ptr + n),\n boost::make_iterator_range(A_col, A_col + A_ptr[n]),\n boost::make_iterator_range(A_val, A_val + A_ptr[n])\n ),\n boost::make_iterator_range(rhs, rhs + n), x_range\n );\n\n return cnv;\n}\n<commit_msg>Fix off-by-one error in lib\/amgcl.cpp<commit_after>#include <iostream>\n\n#include <type_traits>\n#include <boost\/iterator\/transform_iterator.hpp>\n#include <boost\/range\/iterator_range.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n\n#include <amgcl\/relaxation\/runtime.hpp>\n#include <amgcl\/coarsening\/runtime.hpp>\n#include <amgcl\/solver\/runtime.hpp>\n#include <amgcl\/make_solver.hpp>\n#include <amgcl\/amg.hpp>\n#include <amgcl\/backend\/builtin.hpp>\n#include <amgcl\/adapter\/crs_tuple.hpp>\n\n#include \"amgcl.h\"\n\n#ifdef AMGCL_PROFILING\n#include <amgcl\/profiler.hpp>\nnamespace amgcl {\n profiler<> prof;\n}\n#endif\n\n\/\/---------------------------------------------------------------------------\ntypedef amgcl::backend::builtin<double> Backend;\ntypedef amgcl::amg<Backend, amgcl::runtime::coarsening::wrapper, amgcl::runtime::relaxation::wrapper> AMG;\ntypedef amgcl::runtime::solver::wrapper<Backend> ISolver;\ntypedef amgcl::make_solver<AMG, ISolver> Solver;\ntypedef boost::property_tree::ptree Params;\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_params_create() {\n return static_cast<amgclHandle>( new Params() );\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_seti(amgclHandle prm, const char *name, int value) {\n static_cast<Params*>(prm)->put(name, value);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_setf(amgclHandle prm, const char *name, float value) {\n static_cast<Params*>(prm)->put(name, value);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_sets(amgclHandle prm, const char *name, const char *value) {\n static_cast<Params*>(prm)->put(name, value);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_read_json(amgclHandle prm, const char *fname) {\n read_json(fname, *static_cast<Params*>(prm));\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_params_destroy(amgclHandle prm) {\n delete static_cast<Params*>(prm);\n}\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_precond_create(\n int n,\n const int *ptr,\n const int *col,\n const double *val,\n amgclHandle prm\n )\n{\n auto A = std::make_tuple(n,\n boost::make_iterator_range(ptr, ptr + n + 1),\n boost::make_iterator_range(col, col + ptr[n]),\n boost::make_iterator_range(val, val + ptr[n])\n );\n\n if (prm)\n return static_cast<amgclHandle>(new AMG(A, *static_cast<Params*>(prm)));\n else\n return static_cast<amgclHandle>(new AMG(A));\n}\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_precond_create_f(\n int n,\n const int *ptr,\n const int *col,\n const double *val,\n amgclHandle prm\n )\n{\n auto ptr_c = boost::make_transform_iterator(ptr, [](int i){ return i - 1; });\n auto col_c = boost::make_transform_iterator(col, [](int i){ return i - 1; });\n\n auto A = std::make_tuple(n,\n boost::make_iterator_range(ptr_c, ptr_c + n + 1),\n boost::make_iterator_range(col_c, col_c + ptr[n]),\n boost::make_iterator_range(val, val + ptr[n])\n );\n\n if (prm)\n return static_cast<amgclHandle>(new AMG(A, *static_cast<Params*>(prm)));\n else\n return static_cast<amgclHandle>(new AMG(A));\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_precond_apply(amgclHandle handle, const double *rhs, double *x)\n{\n AMG *amg = static_cast<AMG*>(handle);\n\n size_t n = amgcl::backend::rows(amg->system_matrix());\n\n boost::iterator_range<double*> x_range =\n boost::make_iterator_range(x, x + n);\n\n amg->apply(boost::make_iterator_range(rhs, rhs + n), x_range);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_precond_report(amgclHandle handle) {\n std::cout << *static_cast<AMG*>(handle) << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_precond_destroy(amgclHandle handle) {\n delete static_cast<AMG*>(handle);\n}\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_solver_create(\n int n,\n const int *ptr,\n const int *col,\n const double *val,\n amgclHandle prm\n )\n{\n auto A = std::make_tuple(n,\n boost::make_iterator_range(ptr, ptr + n + 1),\n boost::make_iterator_range(col, col + ptr[n]),\n boost::make_iterator_range(val, val + ptr[n])\n );\n\n if (prm)\n return static_cast<amgclHandle>(new Solver(A, *static_cast<Params*>(prm)));\n else\n return static_cast<amgclHandle>(new Solver(A));\n}\n\n\/\/---------------------------------------------------------------------------\namgclHandle STDCALL amgcl_solver_create_f(\n int n,\n const int *ptr,\n const int *col,\n const double *val,\n amgclHandle prm\n )\n{\n auto ptr_c = boost::make_transform_iterator(ptr, [](int i){ return i - 1; });\n auto col_c = boost::make_transform_iterator(col, [](int i){ return i - 1; });\n\n auto A = std::make_tuple(n,\n boost::make_iterator_range(ptr_c, ptr_c + n + 1),\n boost::make_iterator_range(col_c, col_c + ptr[n]),\n boost::make_iterator_range(val, val + ptr[n])\n );\n\n if (prm)\n return static_cast<amgclHandle>(new Solver(A, *static_cast<Params*>(prm)));\n else\n return static_cast<amgclHandle>(new Solver(A));\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_solver_report(amgclHandle handle) {\n std::cout << static_cast<Solver*>(handle)->precond() << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_solver_destroy(amgclHandle handle) {\n delete static_cast<Solver*>(handle);\n}\n\n\/\/---------------------------------------------------------------------------\nconv_info STDCALL amgcl_solver_solve(\n amgclHandle handle,\n const double *rhs,\n double *x\n )\n{\n Solver *slv = static_cast<Solver*>(handle);\n\n size_t n = slv->size();\n\n conv_info cnv;\n\n boost::iterator_range<double*> x_range = boost::make_iterator_range(x, x + n);\n\n std::tie(cnv.iterations, cnv.residual) = (*slv)(\n boost::make_iterator_range(rhs, rhs + n), x_range\n );\n\n return cnv;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid STDCALL amgcl_solver_solve_f(\n amgclHandle handle,\n const double *rhs,\n double *x,\n conv_info *cnv\n )\n{\n *cnv = amgcl_solver_solve(handle, rhs, x);\n}\n\n\/\/---------------------------------------------------------------------------\nconv_info STDCALL amgcl_solver_solve_mtx(\n amgclHandle handle,\n int const * A_ptr,\n int const * A_col,\n double const * A_val,\n const double *rhs,\n double *x\n )\n{\n Solver *slv = static_cast<Solver*>(handle);\n\n size_t n = slv->size();\n\n conv_info cnv;\n\n boost::iterator_range<double*> x_range = boost::make_iterator_range(x, x + n);\n\n std::tie(cnv.iterations, cnv.residual) = (*slv)(\n std::make_tuple(\n n,\n boost::make_iterator_range(A_ptr, A_ptr + n + 1),\n boost::make_iterator_range(A_col, A_col + A_ptr[n]),\n boost::make_iterator_range(A_val, A_val + A_ptr[n])\n ),\n boost::make_iterator_range(rhs, rhs + n), x_range\n );\n\n return cnv;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>acmacs::chart::SelectedAntigens and SelectedSera<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Create 1216 - Getline One.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: langselect.cxx,v $\n *\n * $Revision: 1.9 $\n * last change: $Author: kz $ $Date: 2004-07-26 15:11:22 $\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#include \"app.hxx\"\n#include \"langselect.hxx\"\n#include \"langselect.hrc\"\n#include <stdio.h>\n\n#ifndef _RTL_STRING_HXX\n#include <rtl\/string.hxx>\n#endif\n#ifndef _SVTOOLS_PATHOPTIONS_HXX\n#include <svtools\/pathoptions.hxx>\n#endif\n#ifndef _TOOLS_RESID_HXX\n#include <tools\/resid.hxx>\n#endif\n#ifndef _TOOLS_ISOLANG_HXX\n#include <tools\/isolang.hxx>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/beans\/NamedValue.hpp>\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/lang\/XLocalizable.hpp>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <rtl\/locale.hxx>\n#ifndef INCLUDED_RTL_INSTANCE_HXX\n#include <rtl\/instance.hxx>\n#endif\n#include <osl\/process.h>\n\nusing namespace rtl;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::beans;\n\nnamespace desktop {\n\nLanguageSelectionDialog::LanguageSelectionDialog(ResMgr *pResMgr) :\n ModalDialog(NULL,ResId(DLG_LANGSELECT, pResMgr)),\n m_aText(this, ResId(TXT_DLG_LANGSELECT, pResMgr)),\n m_aListBox(this, ResId(LST_DLG_LANGSELECT, pResMgr)),\n m_aButton(this, ResId(BTN_DLG_LANGSELECT_OK, pResMgr))\n{\n FreeResource();\n}\n\nnamespace { struct lLanguages : public rtl::Static<IsoList, lLanguages> {}; }\n\n\/\/ execute the language selection\n\/\/ display a dialog if more than one language is installed\n\/\/ XXX this is a temporary solution\nstatic sal_Bool bFoundLanguage = sal_False;\n\/\/static LanguageType aFoundLanguageType = LANGUAGE_DONTKNOW;\nstatic OUString aFoundLanguage;\n\nLocale LanguageSelection::IsoStringToLocale(const OUString& str)\n{\n Locale l;\n sal_Int32 index=0;\n l.Language = str.getToken(0, '-', index);\n if (index >= 0) l.Country = str.getToken(0, '-', index);\n if (index >= 0) l.Variant = str.getToken(0, '-', index);\n return l;\n}\n\nvoid LanguageSelection::prepareLanguage()\n{\n \/\/ XXX make everything works without assertions in first run\n \/\/ in multi-language installations, some things might fail in first run\n if (getUserLanguage().getLength() > 0) return;\n IsoList l = getInstalledIsoLanguages();\n if (l.size() >= 1)\n {\n \/\/ throw any away existing default config\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n Reference< XLocalizable > theConfigProvider(\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY );\n OSL_ENSURE(theConfigProvider.is(), \"cannot localize config manager.\");\n if (theConfigProvider.is())\n {\n OUString aLocaleString = *l.begin();\n Locale loc = LanguageSelection::IsoStringToLocale(aLocaleString);\n theConfigProvider->setLocale(loc);\n }\n }\n}\n\nOUString LanguageSelection::getLanguageString()\n{\n\n if (bFoundLanguage)\n return aFoundLanguage;\n\n \/\/ check whether there was aleady a language selected by the user\n OUString aUserLanguage = getUserLanguage();\n if (aUserLanguage.getLength() > 0 )\n {\n bFoundLanguage = sal_True;\n aFoundLanguage = aUserLanguage;\n \/\/ return aFoundLanguageType;\n \/\/ we can not return yet, we need to check whether this instance supports\n \/\/ the language that was previously chosen by the user...\n }\n\n \/\/ fill list\n IsoList &rLanguages = lLanguages::get();\n if (rLanguages.size() < 1)\n rLanguages = getInstalledIsoLanguages();\n \/\/ check whether found language is available\n if (bFoundLanguage)\n {\n IsoList::const_iterator iLang = rLanguages.begin();\n while (iLang != rLanguages.end())\n {\n if (iLang->equals(aFoundLanguage))\n return aFoundLanguage;\n else\n iLang++;\n }\n }\n if (rLanguages.size() > 1) {\n \/\/ are there multiple languages installed?\n \/\/ get resource\n rtl::OString aMgrName = OString(\"langselect\") + OString::valueOf((sal_Int32)SUPD, 10);\n ::com::sun::star::lang::Locale aLocale;\n ResMgr* pResMgr = ResMgr::SearchCreateResMgr( aMgrName, aLocale );\n LanguageSelectionDialog lsd(pResMgr);\n StrList languages(getLanguageStrings(rLanguages));\n for (StrList::iterator str_iter = languages.begin(); str_iter != languages.end(); str_iter++)\n {\n lsd.m_aListBox.InsertEntry(*str_iter);\n }\n\n lsd.Execute();\n short nSelected = lsd.m_aListBox.GetSelectEntryPos();\n IsoList::const_iterator i = rLanguages.begin();\n for (sal_Int32 n=0; n<nSelected; n++) i++;\n bFoundLanguage = sal_True;\n aFoundLanguage = *i;\n return aFoundLanguage;\n } else {\n \/\/ if there is only one language, use it\n if (rLanguages.size() == 1) {\n bFoundLanguage = sal_True;\n aFoundLanguage = *(rLanguages.begin());\n return aFoundLanguage;\n } else {\n \/\/ last resort\n \/\/ don't save\n return ConvertLanguageToIsoString((LanguageType) SvtPathOptions().SubstituteVariable(\n String::CreateFromAscii(\"$(langid)\")).ToInt32()) ;\n \/*\n ::com::sun::star::lang::Locale aLocale;\n OUString aLocString( aLocale.Language );\n if ( aLocale.Country.getLength() != 0 )\n {\n aLocString += OUString::createFromAscii(\"-\")\n + aLocale.Country;\n if ( aLocale.Variant.getLength() != 0 )\n {\n aLocString += OUString::createFromAscii(\"-\")\n + aLocale.Variant;\n }\n }\n return aLocString;\n *\/\n }\n }\n}\n\n\n\/\/ Get the localized selection strings for the list of languages\nStrList LanguageSelection::getLanguageStrings(const IsoList& langLst)\n{\n StrList aList;\n rtl::OString aMgrName = OString(\"langselect\") + OString::valueOf((sal_Int32)SUPD, 10);\n for (IsoList::const_iterator lang_iter = langLst.begin(); lang_iter != langLst.end(); lang_iter++)\n {\n rtl::OUString lang = static_cast<OUString>(*lang_iter);\n ::com::sun::star::lang::Locale aLocale = LanguageSelection::IsoStringToLocale(lang);\n ResMgr* pResMgr = ResMgr::SearchCreateResMgr( aMgrName, aLocale );\n if (pResMgr != NULL) {\n String aString(ResId(STR_LANGSELECT, pResMgr));\n aList.push_back(aString);\n delete pResMgr;\n }\n }\n return aList;\n}\n\n\/\/ get a language choosen by the user\nOUString LanguageSelection::getUserLanguage()\n{\n OUString aLanguage;\n try{\n\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n OUString sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationAccess\");\n OUString sConfigURL = OUString::createFromAscii(\"org.openoffice.Setup\/L10N\/\");\n OUString sLocales = OUString::createFromAscii(\"ooLocale\");\n\n \/\/ get configuration provider\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > (\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY );\n \/\/ check provider\n if (!theConfigProvider.is()) return aLanguage;\n\n \/\/ access the provider\n Sequence< Any > theArgs(1);\n theArgs[ 0 ] <<= sConfigURL;\n Reference< XNameAccess > theNameAccess = Reference< XNameAccess > (\n theConfigProvider->createInstanceWithArguments(\n sAccessSrvc, theArgs ), UNO_QUERY );\n \/\/ check access\n if (!theNameAccess.is()) return aLanguage;\n \/\/ run query\n Any aResult = theNameAccess->getByName( sLocales );\n OUString aLangString;\n if (aResult >>= aLangString)\n {\n aLanguage = aLangString;\n }\n } catch (com::sun::star::uno::RuntimeException)\n {\n \/\/ didn't work - return dontknow\n return aLanguage;\n }\n return aLanguage;\n}\n\n\/\/ get a list with the languages that are installed\nIsoList LanguageSelection::getInstalledIsoLanguages()\n{\n IsoList aList;\n \/\/ read language list from org.openoffice.Setup\/Office\/ooSetupLocales\n try{\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n OUString sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationAccess\");\n OUString sConfigURL = OUString::createFromAscii(\"org.openoffice.Setup\/Office\/InstalledLocales\");\n\n \/\/ get configuration provider\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > (\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY );\n \/\/ check provider\n if (!theConfigProvider.is()) return aList;\n\n \/\/ access the provider\n Sequence< Any > theArgs(1);\n theArgs[ 0 ] <<= sConfigURL;\n Reference< XNameAccess > theNameAccess = Reference< XNameAccess > (\n theConfigProvider->createInstanceWithArguments(\n sAccessSrvc, theArgs ), UNO_QUERY );\n \/\/check access\n if (!theNameAccess.is()) return aList;\n\n Sequence< OUString > aLangSeq = theNameAccess->getElementNames();\n\n for (int i=0; i<aLangSeq.getLength(); i++)\n aList.push_back(aLangSeq[i]);\n } catch (com::sun::star::uno::RuntimeException)\n {\n \/\/ didn't work - return empty list\n }\n return aList;\n}\n\n\/*\n\/\/ get a list with the languages that are installed\nLangList LanguageSelection::getInstalledLanguages()\n{\n LangList aList;\n \/\/ read language list from org.openoffice.Setup\/Office\/ooSetupLocales\n try{\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n OUString sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationAccess\");\n OUString sConfigURL = OUString::createFromAscii(\"org.openoffice.Setup\/Office\/InstalledLocales\");\n\n \/\/ get configuration provider\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > (\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY );\n \/\/ check provider\n if (!theConfigProvider.is()) return aList;\n\n \/\/ access the provider\n Sequence< Any > theArgs(1);\n theArgs[ 0 ] <<= sConfigURL;\n Reference< XNameAccess > theNameAccess = Reference< XNameAccess > (\n theConfigProvider->createInstanceWithArguments(\n sAccessSrvc, theArgs ), UNO_QUERY );\n \/\/check access\n if (!theNameAccess.is()) return aList;\n\n Sequence< OUString > aLangSeq = theNameAccess->getElementNames();\n\n for (int i=0; i<aLangSeq.getLength(); i++)\n aList.push_back(ConvertIsoStringToLanguage(aLangSeq[i]));\n\n } catch (com::sun::star::uno::Exception&)\n {\n \/\/ didn't work - return empty list\n }\n return aList;\n}\n*\/\n} \/\/ namespace desktop\n<commit_msg>INTEGRATION: CWS cfgruggedised (1.7.10); FILE MERGED 2004\/07\/23 13:43:11 jb 1.7.10.1: #i28654# Configuration can fail with more than RuntimeException -> catch them all<commit_after>\/*************************************************************************\n *\n * $RCSfile: langselect.cxx,v $\n *\n * $Revision: 1.10 $\n * last change: $Author: rt $ $Date: 2004-08-20 13:00:26 $\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#include \"app.hxx\"\n#include \"langselect.hxx\"\n#include \"langselect.hrc\"\n#include <stdio.h>\n\n#ifndef _RTL_STRING_HXX\n#include <rtl\/string.hxx>\n#endif\n#ifndef _SVTOOLS_PATHOPTIONS_HXX\n#include <svtools\/pathoptions.hxx>\n#endif\n#ifndef _TOOLS_RESID_HXX\n#include <tools\/resid.hxx>\n#endif\n#ifndef _TOOLS_ISOLANG_HXX\n#include <tools\/isolang.hxx>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/beans\/NamedValue.hpp>\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/lang\/XLocalizable.hpp>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <rtl\/locale.hxx>\n#ifndef INCLUDED_RTL_INSTANCE_HXX\n#include <rtl\/instance.hxx>\n#endif\n#include <osl\/process.h>\n\nusing namespace rtl;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::beans;\n\nnamespace desktop {\n\nLanguageSelectionDialog::LanguageSelectionDialog(ResMgr *pResMgr) :\n ModalDialog(NULL,ResId(DLG_LANGSELECT, pResMgr)),\n m_aText(this, ResId(TXT_DLG_LANGSELECT, pResMgr)),\n m_aListBox(this, ResId(LST_DLG_LANGSELECT, pResMgr)),\n m_aButton(this, ResId(BTN_DLG_LANGSELECT_OK, pResMgr))\n{\n FreeResource();\n}\n\nnamespace { struct lLanguages : public rtl::Static<IsoList, lLanguages> {}; }\n\n\/\/ execute the language selection\n\/\/ display a dialog if more than one language is installed\n\/\/ XXX this is a temporary solution\nstatic sal_Bool bFoundLanguage = sal_False;\n\/\/static LanguageType aFoundLanguageType = LANGUAGE_DONTKNOW;\nstatic OUString aFoundLanguage;\n\nLocale LanguageSelection::IsoStringToLocale(const OUString& str)\n{\n Locale l;\n sal_Int32 index=0;\n l.Language = str.getToken(0, '-', index);\n if (index >= 0) l.Country = str.getToken(0, '-', index);\n if (index >= 0) l.Variant = str.getToken(0, '-', index);\n return l;\n}\n\nvoid LanguageSelection::prepareLanguage()\n{\n \/\/ XXX make everything works without assertions in first run\n \/\/ in multi-language installations, some things might fail in first run\n if (getUserLanguage().getLength() > 0) return;\n IsoList l = getInstalledIsoLanguages();\n if (l.size() >= 1)\n {\n \/\/ throw any away existing default config\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n Reference< XLocalizable > theConfigProvider(\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY );\n OSL_ENSURE(theConfigProvider.is(), \"cannot localize config manager.\");\n if (theConfigProvider.is())\n {\n OUString aLocaleString = *l.begin();\n Locale loc = LanguageSelection::IsoStringToLocale(aLocaleString);\n theConfigProvider->setLocale(loc);\n }\n }\n}\n\nOUString LanguageSelection::getLanguageString()\n{\n\n if (bFoundLanguage)\n return aFoundLanguage;\n\n \/\/ check whether there was aleady a language selected by the user\n OUString aUserLanguage = getUserLanguage();\n if (aUserLanguage.getLength() > 0 )\n {\n bFoundLanguage = sal_True;\n aFoundLanguage = aUserLanguage;\n \/\/ return aFoundLanguageType;\n \/\/ we can not return yet, we need to check whether this instance supports\n \/\/ the language that was previously chosen by the user...\n }\n\n \/\/ fill list\n IsoList &rLanguages = lLanguages::get();\n if (rLanguages.size() < 1)\n rLanguages = getInstalledIsoLanguages();\n \/\/ check whether found language is available\n if (bFoundLanguage)\n {\n IsoList::const_iterator iLang = rLanguages.begin();\n while (iLang != rLanguages.end())\n {\n if (iLang->equals(aFoundLanguage))\n return aFoundLanguage;\n else\n iLang++;\n }\n }\n if (rLanguages.size() > 1) {\n \/\/ are there multiple languages installed?\n \/\/ get resource\n rtl::OString aMgrName = OString(\"langselect\") + OString::valueOf((sal_Int32)SUPD, 10);\n ::com::sun::star::lang::Locale aLocale;\n ResMgr* pResMgr = ResMgr::SearchCreateResMgr( aMgrName, aLocale );\n LanguageSelectionDialog lsd(pResMgr);\n StrList languages(getLanguageStrings(rLanguages));\n for (StrList::iterator str_iter = languages.begin(); str_iter != languages.end(); str_iter++)\n {\n lsd.m_aListBox.InsertEntry(*str_iter);\n }\n\n lsd.Execute();\n short nSelected = lsd.m_aListBox.GetSelectEntryPos();\n IsoList::const_iterator i = rLanguages.begin();\n for (sal_Int32 n=0; n<nSelected; n++) i++;\n bFoundLanguage = sal_True;\n aFoundLanguage = *i;\n return aFoundLanguage;\n } else {\n \/\/ if there is only one language, use it\n if (rLanguages.size() == 1) {\n bFoundLanguage = sal_True;\n aFoundLanguage = *(rLanguages.begin());\n return aFoundLanguage;\n } else {\n \/\/ last resort\n \/\/ don't save\n return ConvertLanguageToIsoString((LanguageType) SvtPathOptions().SubstituteVariable(\n String::CreateFromAscii(\"$(langid)\")).ToInt32()) ;\n \/*\n ::com::sun::star::lang::Locale aLocale;\n OUString aLocString( aLocale.Language );\n if ( aLocale.Country.getLength() != 0 )\n {\n aLocString += OUString::createFromAscii(\"-\")\n + aLocale.Country;\n if ( aLocale.Variant.getLength() != 0 )\n {\n aLocString += OUString::createFromAscii(\"-\")\n + aLocale.Variant;\n }\n }\n return aLocString;\n *\/\n }\n }\n}\n\n\n\/\/ Get the localized selection strings for the list of languages\nStrList LanguageSelection::getLanguageStrings(const IsoList& langLst)\n{\n StrList aList;\n rtl::OString aMgrName = OString(\"langselect\") + OString::valueOf((sal_Int32)SUPD, 10);\n for (IsoList::const_iterator lang_iter = langLst.begin(); lang_iter != langLst.end(); lang_iter++)\n {\n rtl::OUString lang = static_cast<OUString>(*lang_iter);\n ::com::sun::star::lang::Locale aLocale = LanguageSelection::IsoStringToLocale(lang);\n ResMgr* pResMgr = ResMgr::SearchCreateResMgr( aMgrName, aLocale );\n if (pResMgr != NULL) {\n String aString(ResId(STR_LANGSELECT, pResMgr));\n aList.push_back(aString);\n delete pResMgr;\n }\n }\n return aList;\n}\n\n\/\/ get a language choosen by the user\nOUString LanguageSelection::getUserLanguage()\n{\n OUString aLanguage;\n try{\n\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n OUString sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationAccess\");\n OUString sConfigURL = OUString::createFromAscii(\"org.openoffice.Setup\/L10N\/\");\n OUString sLocales = OUString::createFromAscii(\"ooLocale\");\n\n \/\/ get configuration provider\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > (\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY );\n \/\/ check provider\n if (!theConfigProvider.is()) return aLanguage;\n\n \/\/ access the provider\n Sequence< Any > theArgs(1);\n theArgs[ 0 ] <<= sConfigURL;\n Reference< XNameAccess > theNameAccess = Reference< XNameAccess > (\n theConfigProvider->createInstanceWithArguments(\n sAccessSrvc, theArgs ), UNO_QUERY );\n \/\/ check access\n if (!theNameAccess.is()) return aLanguage;\n \/\/ run query\n Any aResult = theNameAccess->getByName( sLocales );\n OUString aLangString;\n if (aResult >>= aLangString)\n {\n aLanguage = aLangString;\n }\n } catch (com::sun::star::uno::Exception)\n {\n \/\/ didn't work - return dontknow\n return aLanguage;\n }\n return aLanguage;\n}\n\n\/\/ get a list with the languages that are installed\nIsoList LanguageSelection::getInstalledIsoLanguages()\n{\n IsoList aList;\n \/\/ read language list from org.openoffice.Setup\/Office\/ooSetupLocales\n try{\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n OUString sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationAccess\");\n OUString sConfigURL = OUString::createFromAscii(\"org.openoffice.Setup\/Office\/InstalledLocales\");\n\n \/\/ get configuration provider\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > (\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY );\n \/\/ check provider\n if (!theConfigProvider.is()) return aList;\n\n \/\/ access the provider\n Sequence< Any > theArgs(1);\n theArgs[ 0 ] <<= sConfigURL;\n Reference< XNameAccess > theNameAccess = Reference< XNameAccess > (\n theConfigProvider->createInstanceWithArguments(\n sAccessSrvc, theArgs ), UNO_QUERY );\n \/\/check access\n if (!theNameAccess.is()) return aList;\n\n Sequence< OUString > aLangSeq = theNameAccess->getElementNames();\n\n for (int i=0; i<aLangSeq.getLength(); i++)\n aList.push_back(aLangSeq[i]);\n } catch (com::sun::star::uno::Exception)\n {\n \/\/ didn't work - return empty list\n }\n return aList;\n}\n\n\/*\n\/\/ get a list with the languages that are installed\nLangList LanguageSelection::getInstalledLanguages()\n{\n LangList aList;\n \/\/ read language list from org.openoffice.Setup\/Office\/ooSetupLocales\n try{\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n OUString sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationAccess\");\n OUString sConfigURL = OUString::createFromAscii(\"org.openoffice.Setup\/Office\/InstalledLocales\");\n\n \/\/ get configuration provider\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > (\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY );\n \/\/ check provider\n if (!theConfigProvider.is()) return aList;\n\n \/\/ access the provider\n Sequence< Any > theArgs(1);\n theArgs[ 0 ] <<= sConfigURL;\n Reference< XNameAccess > theNameAccess = Reference< XNameAccess > (\n theConfigProvider->createInstanceWithArguments(\n sAccessSrvc, theArgs ), UNO_QUERY );\n \/\/check access\n if (!theNameAccess.is()) return aList;\n\n Sequence< OUString > aLangSeq = theNameAccess->getElementNames();\n\n for (int i=0; i<aLangSeq.getLength(); i++)\n aList.push_back(ConvertIsoStringToLanguage(aLangSeq[i]));\n\n } catch (com::sun::star::uno::Exception&)\n {\n \/\/ didn't work - return empty list\n }\n return aList;\n}\n*\/\n} \/\/ namespace desktop\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012, Andre Caron (andre.l.caron@gmail.com)\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\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\/\/ HOLDER 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#include \"SocketChannel.hpp\"\n#include \"Engine.hpp\"\n#include \"Hub.hpp\" \/\/ TODO: include \"Slave.hpp\"\n\n#include \"FileReader.hpp\"\n#include \"FileWriter.hpp\"\n\n#include \"trace.hpp\"\n\nnamespace {\n\n w32::net::Socket::Handle create_socket ()\n {\n const ::SOCKET result = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if ( result == INVALID_SOCKET ) {\n const int error = ::WSAGetLastError();\n UNCHECKED_WIN32C_ERROR(socket, error);\n }\n return (w32::net::Socket::claim(result));\n }\n\n \/\/ Create a bound, unconnected stream socket.\n w32::net::StreamSocket create_socket (w32::net::ipv4::EndPoint host)\n {\n cz_trace(\" >> Creating socket.\");\n\n w32::net::tcp::Stream stream(create_socket());\n\n cz_trace(\" >> Binding to local address.\");\n\n const ::BOOL result = ::bind(stream.handle(), host.raw(), host.size());\n if (result == SOCKET_ERROR)\n {\n const int error = ::WSAGetLastError();\n UNCHECKED_WIN32C_ERROR(bind, error);\n }\n\n return (stream);\n }\n\n}\n\nnamespace cz {\n\n SocketChannel::SocketChannel (Engine& engine,\n w32::net::StreamSocket& stream,\n w32::net::ipv4::EndPoint host,\n w32::net::ipv4::EndPoint peer)\n : myEngine(engine)\n , myStream(stream)\n , myHost(host)\n , myPeer(peer)\n {\n \/\/ Note: stream is already bound to the completion port at this point.\n }\n\n const w32::net::ipv4::EndPoint& SocketChannel::host () const\n {\n return (myHost);\n }\n\n const w32::net::ipv4::EndPoint& SocketChannel::peer () const\n {\n return (myPeer);\n }\n\n size_t SocketChannel::get (void * data, size_t size)\n {\n Hub::Slave& self = Hub::Slave::self();\n\n \/\/ Start the I\/O operation.\n GetRequest request(myEngine, myStream);\n request.start(data, size);\n\n \/\/ Switch to master, it will resume us when it receives a completion\n \/\/ notification for the asynchronous I\/O operation.\n self.hub().resume();\n\n return (request.close());\n }\n\n size_t SocketChannel::put (const void * data, size_t size)\n {\n Hub::Slave& self = Hub::Slave::self();\n\n \/\/ Start the I\/O operation.\n PutRequest request(myEngine, myStream);\n request.start(data, size);\n\n \/\/ Switch to master, it will resume us when it receives a completion\n \/\/ notification for the asynchronous I\/O operation.\n self.hub().resume();\n\n return (request.close());\n }\n\n ConnectRequest::ConnectRequest (Engine& engine,\n w32::net::ipv4::EndPoint host,\n w32::net::ipv4::EndPoint peer)\n : myRequest(engine)\n , myHost(host)\n , myPeer(peer)\n , mySent(0)\n , myStream(::create_socket(myHost))\n {\n Hub::Slave& self = Hub::Slave::self();\n\n \/\/ Make sure we receive I\/O completion notifications :-)\n engine.completion_port().bind(myStream, &engine);\n }\n\n void ConnectRequest::start ()\n {\n w32::net::tcp::Stream::ConnectEx connect_ex =\n w32::net::tcp::Stream(myStream.handle()).connect_ex();\n\n cz_trace(\" >> Starting connect request.\");\n\n \/\/ Start the asynchronous connection request.\n const ::BOOL result = connect_ex(myStream.handle(),\n myPeer.raw(),\n myPeer.size(),\n 0, 0, \/\/ initial payload.\n &mySent,\n &myRequest.data());\n if (result == FALSE)\n {\n const ::DWORD error = ::GetLastError();\n if (error != ERROR_IO_PENDING) {\n UNCHECKED_WIN32C_ERROR(ConnectEx, error);\n }\n }\n }\n\n bool ConnectRequest::ready () const\n {\n return (myRequest.ready());\n }\n\n SocketChannel * ConnectRequest::close()\n {\n \/\/ The hub has resume us, collect results!\n const w32::io::Notification notification = myRequest.notification();\n\n \/\/ Connect requests can be cancelled :-(\n if (notification.aborted()) {\n cz_trace(\" >> Connect request cancelled.\");\n return (0);\n }\n\n \/\/ Propagate I\/O exception to the caller if necessary.\n notification.report_error();\n\n cz_trace(\" >> Connected!\");\n cz_trace(\" >> Host: \" << myHost);\n cz_trace(\" >> Peer: \" << myPeer);\n\n \/\/ Patch socket for shutdown() and others to work as expected.\n const int result = ::setsockopt(myStream.handle(), SOL_SOCKET,\n SO_UPDATE_CONNECT_CONTEXT, 0, 0);\n if (result == SOCKET_ERROR)\n {\n const int error = ::WSAGetLastError();\n UNCHECKED_WIN32C_ERROR(setsockopt, error);\n }\n\n return (new SocketChannel(myRequest.engine(), myStream, myHost, myPeer));\n }\n\n}\n<commit_msg>Implements declared but unimplemented method.<commit_after>\/\/ Copyright (c) 2012, Andre Caron (andre.l.caron@gmail.com)\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\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\/\/ HOLDER 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#include \"SocketChannel.hpp\"\n#include \"Engine.hpp\"\n#include \"Hub.hpp\" \/\/ TODO: include \"Slave.hpp\"\n\n#include \"FileReader.hpp\"\n#include \"FileWriter.hpp\"\n\n#include \"trace.hpp\"\n\nnamespace {\n\n w32::net::Socket::Handle create_socket ()\n {\n const ::SOCKET result = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if ( result == INVALID_SOCKET ) {\n const int error = ::WSAGetLastError();\n UNCHECKED_WIN32C_ERROR(socket, error);\n }\n return (w32::net::Socket::claim(result));\n }\n\n \/\/ Create a bound, unconnected stream socket.\n w32::net::StreamSocket create_socket (w32::net::ipv4::EndPoint host)\n {\n cz_trace(\" >> Creating socket.\");\n\n w32::net::tcp::Stream stream(create_socket());\n\n cz_trace(\" >> Binding to local address.\");\n\n const ::BOOL result = ::bind(stream.handle(), host.raw(), host.size());\n if (result == SOCKET_ERROR)\n {\n const int error = ::WSAGetLastError();\n UNCHECKED_WIN32C_ERROR(bind, error);\n }\n\n return (stream);\n }\n\n}\n\nnamespace cz {\n\n SocketChannel::SocketChannel (Engine& engine,\n w32::net::StreamSocket& stream,\n w32::net::ipv4::EndPoint host,\n w32::net::ipv4::EndPoint peer)\n : myEngine(engine)\n , myStream(stream)\n , myHost(host)\n , myPeer(peer)\n {\n \/\/ Note: stream is already bound to the completion port at this point.\n }\n\n const w32::net::ipv4::EndPoint& SocketChannel::host () const\n {\n return (myHost);\n }\n\n const w32::net::ipv4::EndPoint& SocketChannel::peer () const\n {\n return (myPeer);\n }\n\n w32::net::StreamSocket& SocketChannel::socket ()\n {\n return (myStream);\n }\n\n size_t SocketChannel::get (void * data, size_t size)\n {\n Hub::Slave& self = Hub::Slave::self();\n\n \/\/ Start the I\/O operation.\n GetRequest request(myEngine, myStream);\n request.start(data, size);\n\n \/\/ Switch to master, it will resume us when it receives a completion\n \/\/ notification for the asynchronous I\/O operation.\n self.hub().resume();\n\n return (request.close());\n }\n\n size_t SocketChannel::put (const void * data, size_t size)\n {\n Hub::Slave& self = Hub::Slave::self();\n\n \/\/ Start the I\/O operation.\n PutRequest request(myEngine, myStream);\n request.start(data, size);\n\n \/\/ Switch to master, it will resume us when it receives a completion\n \/\/ notification for the asynchronous I\/O operation.\n self.hub().resume();\n\n return (request.close());\n }\n\n ConnectRequest::ConnectRequest (Engine& engine,\n w32::net::ipv4::EndPoint host,\n w32::net::ipv4::EndPoint peer)\n : myRequest(engine)\n , myHost(host)\n , myPeer(peer)\n , mySent(0)\n , myStream(::create_socket(myHost))\n {\n Hub::Slave& self = Hub::Slave::self();\n\n \/\/ Make sure we receive I\/O completion notifications :-)\n engine.completion_port().bind(myStream, &engine);\n }\n\n void ConnectRequest::start ()\n {\n w32::net::tcp::Stream::ConnectEx connect_ex =\n w32::net::tcp::Stream(myStream.handle()).connect_ex();\n\n cz_trace(\" >> Starting connect request.\");\n\n \/\/ Start the asynchronous connection request.\n const ::BOOL result = connect_ex(myStream.handle(),\n myPeer.raw(),\n myPeer.size(),\n 0, 0, \/\/ initial payload.\n &mySent,\n &myRequest.data());\n if (result == FALSE)\n {\n const ::DWORD error = ::GetLastError();\n if (error != ERROR_IO_PENDING) {\n UNCHECKED_WIN32C_ERROR(ConnectEx, error);\n }\n }\n }\n\n bool ConnectRequest::ready () const\n {\n return (myRequest.ready());\n }\n\n SocketChannel * ConnectRequest::close()\n {\n \/\/ The hub has resume us, collect results!\n const w32::io::Notification notification = myRequest.notification();\n\n \/\/ Connect requests can be cancelled :-(\n if (notification.aborted()) {\n cz_trace(\" >> Connect request cancelled.\");\n return (0);\n }\n\n \/\/ Propagate I\/O exception to the caller if necessary.\n notification.report_error();\n\n cz_trace(\" >> Connected!\");\n cz_trace(\" >> Host: \" << myHost);\n cz_trace(\" >> Peer: \" << myPeer);\n\n \/\/ Patch socket for shutdown() and others to work as expected.\n const int result = ::setsockopt(myStream.handle(), SOL_SOCKET,\n SO_UPDATE_CONNECT_CONTEXT, 0, 0);\n if (result == SOCKET_ERROR)\n {\n const int error = ::WSAGetLastError();\n UNCHECKED_WIN32C_ERROR(setsockopt, error);\n }\n\n return (new SocketChannel(myRequest.engine(), myStream, myHost, myPeer));\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _crumbs_configure_hpp__\n#define _crumbs_configure_hpp__\n\n\/\/ Copyright (c) 2012, Andre Caron (andre.l.caron@gmail.com)\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\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\/\/ HOLDER 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\/\/ Unless explicitly disabled.\n#ifndef CRUMBS_ENABLED\n# define CRUMBS_ENABLED 1\n#endif\n\n\/\/ Default to single threaded mode.\n#if CRUMBS_ENABLED\n# ifndef CRUMBS_SINGLE_THREADED\n# define CRUMBS_SINGLE_THREADED 1\n# endif\n#else\n#endif\n\n\/\/ Introspection is not portable :-(\n#ifdef _MSC_VER\n# define CRUMBS_CURRENT_FUNCTION() __FUNCSIG__\n#else\n# error \"CRUMBS_CURRENT_FUNCTION() is not defined for current compiler.\"\n#endif\n\n#endif \/* _crumbs_configure_hpp__ *\/\n<commit_msg>Adds support for G++.<commit_after>#ifndef _crumbs_configure_hpp__\n#define _crumbs_configure_hpp__\n\n\/\/ Copyright (c) 2012, Andre Caron (andre.l.caron@gmail.com)\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\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\/\/ HOLDER 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\/\/ Unless explicitly disabled.\n#ifndef CRUMBS_ENABLED\n# define CRUMBS_ENABLED 1\n#endif\n\n\/\/ Default to single threaded mode.\n#if CRUMBS_ENABLED\n# ifndef CRUMBS_SINGLE_THREADED\n# define CRUMBS_SINGLE_THREADED 1\n# endif\n#else\n#endif\n\n\/\/ Introspection is not portable :-(\n#ifdef _MSC_VER\n# define CRUMBS_CURRENT_FUNCTION() __FUNCSIG__\n#elif defined(__GNUC__)\n# define CRUMBS_CURRENT_FUNCTION() __PRETTY_FUNCTION__\n#else\n# error \"CRUMBS_CURRENT_FUNCTION() is not defined for current compiler.\"\n#endif\n\n#endif \/* _crumbs_configure_hpp__ *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Delete json.hpp<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Remove noexcept from lazy<commit_after><|endoftext|>"} {"text":"<commit_before>5bf673fc-2d16-11e5-af21-0401358ea401<commit_msg>5bf673fd-2d16-11e5-af21-0401358ea401<commit_after>5bf673fd-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before><commit_msg>d0db1bae-327f-11e5-bac9-9cf387a8033e<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/optimization\/COptMethodSA.cpp,v $\n $Revision: 1.5 $\n $Name: $\n $Author: shoops $ \n $Date: 2003\/10\/30 17:58:53 $\n End CVS Header *\/\n\n\/* COptMethodSA code *\/\n\n\/***************************************************************************************\n * This is the implementation of the Simulated Annealing for Optimization. The\n * class is inherited from the COptAlgorithm class\n *\n * Implemented by Dingjun Chen\n * Starting Date: 09\/22\/03\n *\n ***************************************************************************************\/\n\n#define BESTFOUNDSOFAR 2\n#define NumDirection 10\n#define TRUE 1\n#define FALSE 0 \n\/\/ #define PI 3.1415926\n\n#include <vector>\n#include <math.h>\n\n#include \"copasi.h\"\n#include \"COptMethod.h\"\n#include \"COptMethodSA.h\"\n#include \"CRealProblem.h\"\n#include \"randomGenerator\/CRandom.h\"\n\nstatic double PI = 4.0 * atan(1.0);\n\nCOptMethodSA::COptMethodSA():\n COptMethod(CCopasiMethod::SimulatedAnnealing)\n{\n addParameter(\"SimulatedAnnealing.Iterations\",\n CCopasiParameter::UINT,\n (unsigned C_INT32) 10000);\n addParameter(\"SimulatedAnnealing.RandomGenerator.Type\",\n CCopasiParameter::INT,\n (C_INT32) CRandom::mt19937);\n addParameter(\"SimulatedAnnealing.RandomGenerator.Seed\",\n CCopasiParameter::INT,\n (C_INT32) 0);\n}\n\nCOptMethodSA::COptMethodSA(const COptMethodSA & src):\n COptMethod(src)\n{}\n\n\/**\n * Destructor\n *\/\nCOptMethodSA::~COptMethodSA(){}\n\n\/**\n * Optimizer Function\n * Returns: nothing\n *\/\n\nC_INT32 COptMethodSA::optimise()\n{\n C_FLOAT64 la;\n C_INT32 NumSignificantPoint, NumTempChange, NumIteration = (C_INT32) getValue(\"SimulatedAnnealing.Iterations\");\n C_INT32 j, NumParameter = mParameters->size();\n\n \/\/variable settings neccessary for SA\n CVector<double> candparameter(NumParameter); \/\/one-dimentional array of candidate value for parameters\n double candFuncValue; \/\/ candidate value of objective function\n\n CVector<double> thisparameter(NumParameter); \/\/current parameters\n double thisFuncValue; \/\/current value of the objective function\n\n CVector <double> newparameter(NumParameter); \/\/new parameter value\n double newFuncValue; \/\/function value of new point\n\n CVector <double> step(NumParameter); \/\/array of maximum steps for each parameter\n CVector <int> NumStepAccep(NumParameter); \/\/number of steps accepted\n\n double TempDecreaseRate = 0.85; \/\/temperature decrease rate\n double BoltzmannConstant = 1.0; \/\/Boltzmann constant\n\n double InitialTemp = 1.0; \/\/initial temperature\n double t; \/\/current temperature\n\n double ConvgCriterion = 0.00001; \/\/ convergence criterion or program termination criterion\n double ChangeValue, EnergyDifference;\n\n CVector <double> fk(BESTFOUNDSOFAR);\n bool ready, linear;\n\n \/* Create a random number generator *\/\n CRandom::Type Type;\n Type = (CRandom::Type) (C_INT32) getValue(\"SimulatedAnnealing.RandomGenerator.Type\");\n unsigned C_INT32 Seed;\n Seed = (unsigned C_INT32) getValue(\"SimulatedAnnealing.RandomGenerator.Seed\");\n CRandom * pRand = CRandom::createGenerator(Type, Seed);\n\n assert(pRand);\n\n double * Minimum = mParameterMin->array();\n double * Maximum = mParameterMax->array();\n double * Parameter = mParameters->array();\n\n \/\/dump_datafile_init()\n\n \/\/inital temperature\n t = InitialTemp;\n\n \/\/inital point\n NumSignificantPoint = 0;\n\n \/\/generate initial parameters randomly\n for (j = 0; j < NumParameter; j++)\n {\n linear = false;\n la = 1.0;\n\n if (Minimum[j] == 0.0) Minimum[j] = DBL_EPSILON;\n\n if ((Maximum[j] <= 0.0) || (Minimum[j] <= 0.0)) linear = true;\n\n else\n {\n la = log10(Maximum[j]) - log10(Minimum[j]);\n if (la < 1.8) linear = true;\n }\n\n if (linear)\n Parameter[j] =\n Minimum[j] + pRand->getRandomCC() * (Maximum[j] - Minimum[j]);\n else\n Parameter[j] = Minimum[j] * pow(10, la * pRand->getRandomCC());\n } \/\/ Initialization ends\n\n for (int kk = 0; kk < NumParameter; kk++)\n candparameter[kk] = thisparameter[kk] = newparameter[kk] = Parameter[kk];\n\n \/\/ calculate the function fitness value\n double FitnessValue = mOptProblem->calculate();\n thisFuncValue = candFuncValue = FitnessValue;\n\n \/\/Remember them\n for (int mm = 0; mm < BESTFOUNDSOFAR; mm++) fk[mm] = thisFuncValue;\n\n \/\/initial step sizes\n for (int jj = 0; jj < NumParameter; jj++)\n {\n NumStepAccep[jj] = 0;\n step[jj] = fabs(candparameter[jj]);\n }\n\n \/\/no temperature reductions yet\n NumTempChange = 0;\n\n do\n {\n for (int ff = 0; ff < NumIteration; ff++) \/\/step adjustments\n {\n std::cout << \"New iteration begins ......\" << std::endl;\n std::cout << \"Current Temperature: \" << t << std::endl;\n std::cout << \"Number of Temperature Change: \" << NumTempChange << std::endl;\n\n for (j = 0; j < NumDirection; j++) \/\/ adjustment in all directions\n {\n for (int hh = 0; hh < NumParameter; hh++)\n {\n \/\/ ChangeValue=tan(2*PI*rand()\/RAND_MAX)*(t\/pow(pow(2,2.0)+t*t,(NumParameter+1)\/2.0));\n ChangeValue = tan(2 * PI * pRand->getRandomCC()) * (t \/ pow(pow(2, 2.0) + t * t, (NumParameter + 1) \/ 2.0));\n newparameter[hh] = thisparameter[hh] + step[hh] * ChangeValue;\n\n if (newparameter[hh] < Minimum[hh]) newparameter[hh] = Minimum[hh] + pRand->getRandomCC() * (Maximum[hh] - Minimum[hh]);\n if (newparameter[hh] > Maximum[hh]) newparameter[hh] = Minimum[hh] + pRand->getRandomCC() * (Maximum[hh] - Minimum[hh]);\n for (int exchange = 0; exchange < NumParameter; exchange++)\n {\n Parameter[exchange] = newparameter[exchange];\n }\n\n \/\/ calculate the function value\n double FitnessValue = mOptProblem->calculate();\n newFuncValue = FitnessValue;\n\n \/\/Calculate the energy difference\n EnergyDifference = newFuncValue - thisFuncValue;\n\n \/\/keep newparameter if energy is reduced\n if (newFuncValue <= thisFuncValue)\n {\n for (int exchange = 0; exchange < NumParameter; exchange++)\n {\n thisparameter[exchange] = newparameter[exchange];\n }\n thisFuncValue = newFuncValue;\n\n NumSignificantPoint++; \/\/ a new point counted\n NumStepAccep[hh]++; \/\/a new point in this coordinate counted\n\n if (thisFuncValue < candFuncValue)\n {\n for (int aa = 0; aa < NumParameter; aa++)\n Parameter[aa] = candparameter[aa] = thisparameter[aa];\n candFuncValue = thisFuncValue;\n\n if (!mOptProblem->checkFunctionalConstraints())\n continue;\n\n \/\/set the best function value\n mOptProblem->setBestValue(candFuncValue);\n std::cout << \"the Best value (\" << NumSignificantPoint << \"): \" << candFuncValue << std::endl;\n\n \/\/store the combination of the best parameter values found so far at current temperature\n mOptProblem->getBestParameter() = *mParameters;\n\n std::cout << \"the Best Parameters: (\";\n for (int kk = 0; kk < mOptProblem->getParameterNum(); kk++)\n std::cout << mOptProblem->getParameter(kk) << \", \";\n\n std::cout << \")\" << std::endl;\n }\n }\n else\n {\n \/\/keep newparameter with probability, if newFuncValue is increased\n double Probability = exp(-(newFuncValue - thisFuncValue) \/ (BoltzmannConstant * t));\n if (Probability > pRand->getRandomCC())\n {\n \/\/Keep the new point\n for (int exchange = 0; exchange < NumParameter; exchange++)\n {\n thisparameter[exchange] = newparameter[exchange];\n }\n thisFuncValue = newFuncValue;\n NumSignificantPoint++; \/\/ a new point counted\n NumStepAccep[hh]++; \/\/a new point in this coordinate counted\n }\n }\n }\n }\n\n \/\/update the step sizes\n for (int nn = 0; nn < NumParameter; nn++)\n {\n double StepAdjustment = (double) NumStepAccep[nn] \/ (double)NumDirection;\n if (StepAdjustment > 0.6) step[nn] *= 1 + 5 * (StepAdjustment - 0.6);\n if (StepAdjustment < 0.4) step[nn] \/= 1 + 5 * (0.4 - StepAdjustment);\n NumStepAccep[nn] = 0;\n }\n }\n\n \/\/update the temperature\n t *= TempDecreaseRate;\n NumTempChange++;\n\n \/\/ if this is the first cycle then ignore the convergence test\n if (NumTempChange == 1) ready = FALSE;\n else\n {\n ready = TRUE;\n \/\/check if there is not much change for termination criterion since last BESTFOUNDSOFAR times\n for (int ii = 0; ii < BESTFOUNDSOFAR; ii++)\n if (fabs(fk[ii] - thisFuncValue) > ConvgCriterion)\n {\n ready = FALSE;\n break;\n }\n if (!ready)\n {\n for (int aa = 0; aa < BESTFOUNDSOFAR - 1; aa++)\n fk[aa] = fk[aa + 1];\n fk[BESTFOUNDSOFAR - 1] = thisFuncValue;\n }\n else\n \/\/check the termination criterion of not much larger than last optimal\n if (fabs(thisFuncValue - candFuncValue) > ConvgCriterion)ready = FALSE;\n }\n\n if (!ready)\n {\n NumSignificantPoint++;\n for (int kk = 0; kk < NumParameter; kk++)\n thisparameter[kk] = candparameter[kk];\n thisFuncValue = candFuncValue;\n }\n }\n while (!ready); \/\/ do-while loop ends\n\n pdelete(pRand);\n return 0;\n}\n<commit_msg>use the M_PI constant from math.h (assuming this is standard and also available on windows)<commit_after>\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/optimization\/COptMethodSA.cpp,v $\n $Revision: 1.6 $\n $Name: $\n $Author: ssahle $ \n $Date: 2004\/06\/22 11:01:17 $\n End CVS Header *\/\n\n\/* COptMethodSA code *\/\n\n\/***************************************************************************************\n * This is the implementation of the Simulated Annealing for Optimization. The\n * class is inherited from the COptAlgorithm class\n *\n * Implemented by Dingjun Chen\n * Starting Date: 09\/22\/03\n *\n ***************************************************************************************\/\n\n#define BESTFOUNDSOFAR 2\n#define NumDirection 10\n#define TRUE 1\n#define FALSE 0\n\n#include <vector>\n#include <math.h>\n\n#include \"copasi.h\"\n#include \"COptMethod.h\"\n#include \"COptMethodSA.h\"\n#include \"CRealProblem.h\"\n#include \"randomGenerator\/CRandom.h\"\n\n\/\/static double PI = 4.0 * atan(1.0);\n\nCOptMethodSA::COptMethodSA():\n COptMethod(CCopasiMethod::SimulatedAnnealing)\n{\n addParameter(\"SimulatedAnnealing.Iterations\",\n CCopasiParameter::UINT,\n (unsigned C_INT32) 10000);\n addParameter(\"SimulatedAnnealing.RandomGenerator.Type\",\n CCopasiParameter::INT,\n (C_INT32) CRandom::mt19937);\n addParameter(\"SimulatedAnnealing.RandomGenerator.Seed\",\n CCopasiParameter::INT,\n (C_INT32) 0);\n}\n\nCOptMethodSA::COptMethodSA(const COptMethodSA & src):\n COptMethod(src)\n{}\n\n\/**\n * Destructor\n *\/\nCOptMethodSA::~COptMethodSA(){}\n\n\/**\n * Optimizer Function\n * Returns: nothing\n *\/\n\nC_INT32 COptMethodSA::optimise()\n{\n C_FLOAT64 la;\n C_INT32 NumSignificantPoint, NumTempChange, NumIteration = (C_INT32) getValue(\"SimulatedAnnealing.Iterations\");\n C_INT32 j, NumParameter = mParameters->size();\n\n \/\/variable settings neccessary for SA\n CVector<double> candparameter(NumParameter); \/\/one-dimentional array of candidate value for parameters\n double candFuncValue; \/\/ candidate value of objective function\n\n CVector<double> thisparameter(NumParameter); \/\/current parameters\n double thisFuncValue; \/\/current value of the objective function\n\n CVector <double> newparameter(NumParameter); \/\/new parameter value\n double newFuncValue; \/\/function value of new point\n\n CVector <double> step(NumParameter); \/\/array of maximum steps for each parameter\n CVector <int> NumStepAccep(NumParameter); \/\/number of steps accepted\n\n double TempDecreaseRate = 0.85; \/\/temperature decrease rate\n double BoltzmannConstant = 1.0; \/\/Boltzmann constant\n\n double InitialTemp = 1.0; \/\/initial temperature\n double t; \/\/current temperature\n\n double ConvgCriterion = 0.00001; \/\/ convergence criterion or program termination criterion\n double ChangeValue, EnergyDifference;\n\n CVector <double> fk(BESTFOUNDSOFAR);\n bool ready, linear;\n\n \/* Create a random number generator *\/\n CRandom::Type Type;\n Type = (CRandom::Type) (C_INT32) getValue(\"SimulatedAnnealing.RandomGenerator.Type\");\n unsigned C_INT32 Seed;\n Seed = (unsigned C_INT32) getValue(\"SimulatedAnnealing.RandomGenerator.Seed\");\n CRandom * pRand = CRandom::createGenerator(Type, Seed);\n\n assert(pRand);\n\n double * Minimum = mParameterMin->array();\n double * Maximum = mParameterMax->array();\n double * Parameter = mParameters->array();\n\n \/\/dump_datafile_init()\n\n \/\/inital temperature\n t = InitialTemp;\n\n \/\/inital point\n NumSignificantPoint = 0;\n\n \/\/generate initial parameters randomly\n for (j = 0; j < NumParameter; j++)\n {\n linear = false;\n la = 1.0;\n\n if (Minimum[j] == 0.0) Minimum[j] = DBL_EPSILON;\n\n if ((Maximum[j] <= 0.0) || (Minimum[j] <= 0.0)) linear = true;\n\n else\n {\n la = log10(Maximum[j]) - log10(Minimum[j]);\n if (la < 1.8) linear = true;\n }\n\n if (linear)\n Parameter[j] =\n Minimum[j] + pRand->getRandomCC() * (Maximum[j] - Minimum[j]);\n else\n Parameter[j] = Minimum[j] * pow(10, la * pRand->getRandomCC());\n } \/\/ Initialization ends\n\n for (int kk = 0; kk < NumParameter; kk++)\n candparameter[kk] = thisparameter[kk] = newparameter[kk] = Parameter[kk];\n\n \/\/ calculate the function fitness value\n double FitnessValue = mOptProblem->calculate();\n thisFuncValue = candFuncValue = FitnessValue;\n\n \/\/Remember them\n for (int mm = 0; mm < BESTFOUNDSOFAR; mm++) fk[mm] = thisFuncValue;\n\n \/\/initial step sizes\n for (int jj = 0; jj < NumParameter; jj++)\n {\n NumStepAccep[jj] = 0;\n step[jj] = fabs(candparameter[jj]);\n }\n\n \/\/no temperature reductions yet\n NumTempChange = 0;\n\n do\n {\n for (int ff = 0; ff < NumIteration; ff++) \/\/step adjustments\n {\n std::cout << \"New iteration begins ......\" << std::endl;\n std::cout << \"Current Temperature: \" << t << std::endl;\n std::cout << \"Number of Temperature Change: \" << NumTempChange << std::endl;\n\n for (j = 0; j < NumDirection; j++) \/\/ adjustment in all directions\n {\n for (int hh = 0; hh < NumParameter; hh++)\n {\n \/\/ ChangeValue=tan(2*PI*rand()\/RAND_MAX)*(t\/pow(pow(2,2.0)+t*t,(NumParameter+1)\/2.0));\n ChangeValue = tan(2 * M_PI * pRand->getRandomCC()) * (t \/ pow(pow(2, 2.0) + t * t, (NumParameter + 1) \/ 2.0));\n newparameter[hh] = thisparameter[hh] + step[hh] * ChangeValue;\n\n if (newparameter[hh] < Minimum[hh]) newparameter[hh] = Minimum[hh] + pRand->getRandomCC() * (Maximum[hh] - Minimum[hh]);\n if (newparameter[hh] > Maximum[hh]) newparameter[hh] = Minimum[hh] + pRand->getRandomCC() * (Maximum[hh] - Minimum[hh]);\n for (int exchange = 0; exchange < NumParameter; exchange++)\n {\n Parameter[exchange] = newparameter[exchange];\n }\n\n \/\/ calculate the function value\n double FitnessValue = mOptProblem->calculate();\n newFuncValue = FitnessValue;\n\n \/\/Calculate the energy difference\n EnergyDifference = newFuncValue - thisFuncValue;\n\n \/\/keep newparameter if energy is reduced\n if (newFuncValue <= thisFuncValue)\n {\n for (int exchange = 0; exchange < NumParameter; exchange++)\n {\n thisparameter[exchange] = newparameter[exchange];\n }\n thisFuncValue = newFuncValue;\n\n NumSignificantPoint++; \/\/ a new point counted\n NumStepAccep[hh]++; \/\/a new point in this coordinate counted\n\n if (thisFuncValue < candFuncValue)\n {\n for (int aa = 0; aa < NumParameter; aa++)\n Parameter[aa] = candparameter[aa] = thisparameter[aa];\n candFuncValue = thisFuncValue;\n\n if (!mOptProblem->checkFunctionalConstraints())\n continue;\n\n \/\/set the best function value\n mOptProblem->setBestValue(candFuncValue);\n std::cout << \"the Best value (\" << NumSignificantPoint << \"): \" << candFuncValue << std::endl;\n\n \/\/store the combination of the best parameter values found so far at current temperature\n mOptProblem->getBestParameter() = *mParameters;\n\n std::cout << \"the Best Parameters: (\";\n for (int kk = 0; kk < mOptProblem->getParameterNum(); kk++)\n std::cout << mOptProblem->getParameter(kk) << \", \";\n\n std::cout << \")\" << std::endl;\n }\n }\n else\n {\n \/\/keep newparameter with probability, if newFuncValue is increased\n double Probability = exp(-(newFuncValue - thisFuncValue) \/ (BoltzmannConstant * t));\n if (Probability > pRand->getRandomCC())\n {\n \/\/Keep the new point\n for (int exchange = 0; exchange < NumParameter; exchange++)\n {\n thisparameter[exchange] = newparameter[exchange];\n }\n thisFuncValue = newFuncValue;\n NumSignificantPoint++; \/\/ a new point counted\n NumStepAccep[hh]++; \/\/a new point in this coordinate counted\n }\n }\n }\n }\n\n \/\/update the step sizes\n for (int nn = 0; nn < NumParameter; nn++)\n {\n double StepAdjustment = (double) NumStepAccep[nn] \/ (double)NumDirection;\n if (StepAdjustment > 0.6) step[nn] *= 1 + 5 * (StepAdjustment - 0.6);\n if (StepAdjustment < 0.4) step[nn] \/= 1 + 5 * (0.4 - StepAdjustment);\n NumStepAccep[nn] = 0;\n }\n }\n\n \/\/update the temperature\n t *= TempDecreaseRate;\n NumTempChange++;\n\n \/\/ if this is the first cycle then ignore the convergence test\n if (NumTempChange == 1) ready = FALSE;\n else\n {\n ready = TRUE;\n \/\/check if there is not much change for termination criterion since last BESTFOUNDSOFAR times\n for (int ii = 0; ii < BESTFOUNDSOFAR; ii++)\n if (fabs(fk[ii] - thisFuncValue) > ConvgCriterion)\n {\n ready = FALSE;\n break;\n }\n if (!ready)\n {\n for (int aa = 0; aa < BESTFOUNDSOFAR - 1; aa++)\n fk[aa] = fk[aa + 1];\n fk[BESTFOUNDSOFAR - 1] = thisFuncValue;\n }\n else\n \/\/check the termination criterion of not much larger than last optimal\n if (fabs(thisFuncValue - candFuncValue) > ConvgCriterion)ready = FALSE;\n }\n\n if (!ready)\n {\n NumSignificantPoint++;\n for (int kk = 0; kk < NumParameter; kk++)\n thisparameter[kk] = candparameter[kk];\n thisFuncValue = candFuncValue;\n }\n }\n while (!ready); \/\/ do-while loop ends\n\n pdelete(pRand);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>be492d9c-2747-11e6-86c6-e0f84713e7b8<commit_msg>fix for the previous fix<commit_after>be58b09e-2747-11e6-8316-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before><commit_msg>f643358a-2d3d-11e5-8620-c82a142b6f9b<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>fix HIP-clang compile<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>cc65d280-2e4e-11e5-b5e1-28cfe91dbc4b<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>9b39833d-327f-11e5-93be-9cf387a8033e<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>I'm done<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>6afd6954-2fa5-11e5-b17f-00012e3d3f12<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>1d57c2a8-2e4f-11e5-b462-28cfe91dbc4b<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>ca7da651-352a-11e5-b477-34363b65e550<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/\/ `krbn::event_tap_manager` can be used safely in a multi-threaded environment.\n\n#include \"boost_defs.hpp\"\n\n#include \"cf_utility.hpp\"\n#include \"logger.hpp\"\n#include <CoreGraphics\/CoreGraphics.h>\n#include <boost\/optional.hpp>\n#include <boost\/signals2.hpp>\n\nnamespace krbn {\nclass event_tap_manager final {\npublic:\n \/\/ Signals\n\n boost::signals2::signal<void(bool)> caps_lock_state_changed;\n boost::signals2::signal<void(CGEventType, CGEventRef _Nullable)> pointing_device_event_arrived;\n\n \/\/ Methods\n\n event_tap_manager(const event_tap_manager&) = delete;\n\n event_tap_manager(void) : event_tap_(nullptr),\n run_loop_source_(nullptr) {\n run_loop_thread_ = std::make_unique<cf_utility::run_loop_thread>();\n }\n\n ~event_tap_manager(void) {\n run_loop_thread_->enqueue(^{\n if (event_tap_) {\n CGEventTapEnable(event_tap_, false);\n\n if (run_loop_source_) {\n CFRunLoopRemoveSource(run_loop_thread_->get_run_loop(),\n run_loop_source_,\n kCFRunLoopCommonModes);\n CFRelease(run_loop_source_);\n run_loop_source_ = nullptr;\n }\n\n CFRelease(event_tap_);\n event_tap_ = nullptr;\n }\n logger::get_logger().info(\"event_tap_manager terminated\");\n });\n\n run_loop_thread_ = nullptr;\n }\n\n void async_start(void) {\n run_loop_thread_->enqueue(^{\n if (event_tap_) {\n return;\n }\n\n \/\/ Observe flags changed in order to get the caps lock state and pointing device events from Apple trackpads.\n \/\/\n \/\/ Note:\n \/\/ We cannot catch pointing device events from Apple trackpads without eventtap.\n \/\/ (Apple trackpad driver does not send events to IOKit.)\n\n auto mask = CGEventMaskBit(kCGEventFlagsChanged) |\n CGEventMaskBit(kCGEventLeftMouseDown) |\n CGEventMaskBit(kCGEventLeftMouseUp) |\n CGEventMaskBit(kCGEventRightMouseDown) |\n CGEventMaskBit(kCGEventRightMouseUp) |\n CGEventMaskBit(kCGEventMouseMoved) |\n CGEventMaskBit(kCGEventLeftMouseDragged) |\n CGEventMaskBit(kCGEventRightMouseDragged) |\n CGEventMaskBit(kCGEventScrollWheel) |\n CGEventMaskBit(kCGEventOtherMouseDown) |\n CGEventMaskBit(kCGEventOtherMouseUp) |\n CGEventMaskBit(kCGEventOtherMouseDragged);\n\n event_tap_ = CGEventTapCreate(kCGHIDEventTap,\n kCGTailAppendEventTap,\n kCGEventTapOptionListenOnly,\n mask,\n event_tap_manager::static_callback,\n this);\n\n if (event_tap_) {\n run_loop_source_ = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, event_tap_, 0);\n if (run_loop_source_) {\n CFRunLoopAddSource(run_loop_thread_->get_run_loop(),\n run_loop_source_,\n kCFRunLoopCommonModes);\n CGEventTapEnable(event_tap_, true);\n\n logger::get_logger().info(\"event_tap_manager initialized\");\n }\n }\n });\n }\n\nprivate:\n static CGEventRef _Nullable static_callback(CGEventTapProxy _Nullable proxy, CGEventType type, CGEventRef _Nullable event, void* _Nonnull refcon) {\n auto self = static_cast<event_tap_manager*>(refcon);\n if (self) {\n return self->callback(proxy, type, event);\n }\n return nullptr;\n }\n\n CGEventRef _Nullable callback(CGEventTapProxy _Nullable proxy, CGEventType type, CGEventRef _Nullable event) {\n switch (type) {\n case kCGEventTapDisabledByTimeout:\n logger::get_logger().info(\"Re-enable event_tap_ by kCGEventTapDisabledByTimeout\");\n CGEventTapEnable(event_tap_, true);\n break;\n\n case kCGEventTapDisabledByUserInput:\n break;\n\n case kCGEventFlagsChanged:\n \/\/ The caps lock key event from keyboard might be ignored by caps lock delay.\n \/\/ Thus, we need to observe kCGEventFlagsChanged event in EventTap to detect the caps lock state change.\n if (event) {\n auto old_caps_lock_state = get_caps_lock_state();\n last_flags_ = CGEventGetFlags(event);\n auto new_caps_lock_state = get_caps_lock_state();\n\n if (old_caps_lock_state &&\n new_caps_lock_state &&\n *old_caps_lock_state == *new_caps_lock_state) {\n \/\/ the caps lock state is not changed.\n } else {\n caps_lock_state_changed(*new_caps_lock_state);\n }\n }\n break;\n\n case kCGEventLeftMouseDown:\n case kCGEventLeftMouseUp:\n case kCGEventRightMouseDown:\n case kCGEventRightMouseUp:\n case kCGEventMouseMoved:\n case kCGEventLeftMouseDragged:\n case kCGEventRightMouseDragged:\n case kCGEventScrollWheel:\n case kCGEventOtherMouseDown:\n case kCGEventOtherMouseUp:\n case kCGEventOtherMouseDragged:\n pointing_device_event_arrived(type, event);\n break;\n\n case kCGEventNull:\n case kCGEventKeyDown:\n case kCGEventKeyUp:\n case kCGEventTabletPointer:\n case kCGEventTabletProximity:\n \/\/ These events are not captured.\n break;\n }\n\n return event;\n }\n\n boost::optional<bool> get_caps_lock_state(void) const {\n if (last_flags_) {\n return (*last_flags_ & NX_ALPHASHIFTMASK);\n }\n return boost::none;\n }\n\n std::unique_ptr<cf_utility::run_loop_thread> run_loop_thread_;\n CFMachPortRef _Nullable event_tap_;\n CFRunLoopSourceRef _Nullable run_loop_source_;\n boost::optional<CGEventFlags> last_flags_;\n};\n} \/\/ namespace krbn\n<commit_msg>call run_loop_thread::terminate in event_tap_manager<commit_after>#pragma once\n\n\/\/ `krbn::event_tap_manager` can be used safely in a multi-threaded environment.\n\n#include \"boost_defs.hpp\"\n\n#include \"cf_utility.hpp\"\n#include \"logger.hpp\"\n#include <CoreGraphics\/CoreGraphics.h>\n#include <boost\/optional.hpp>\n#include <boost\/signals2.hpp>\n\nnamespace krbn {\nclass event_tap_manager final {\npublic:\n \/\/ Signals\n\n boost::signals2::signal<void(bool)> caps_lock_state_changed;\n boost::signals2::signal<void(CGEventType, CGEventRef _Nullable)> pointing_device_event_arrived;\n\n \/\/ Methods\n\n event_tap_manager(const event_tap_manager&) = delete;\n\n event_tap_manager(void) : event_tap_(nullptr),\n run_loop_source_(nullptr) {\n run_loop_thread_ = std::make_unique<cf_utility::run_loop_thread>();\n }\n\n ~event_tap_manager(void) {\n run_loop_thread_->enqueue(^{\n if (event_tap_) {\n CGEventTapEnable(event_tap_, false);\n\n if (run_loop_source_) {\n CFRunLoopRemoveSource(run_loop_thread_->get_run_loop(),\n run_loop_source_,\n kCFRunLoopCommonModes);\n CFRelease(run_loop_source_);\n run_loop_source_ = nullptr;\n }\n\n CFRelease(event_tap_);\n event_tap_ = nullptr;\n }\n logger::get_logger().info(\"event_tap_manager terminated\");\n });\n\n run_loop_thread_->terminate();\n run_loop_thread_ = nullptr;\n }\n\n void async_start(void) {\n run_loop_thread_->enqueue(^{\n if (event_tap_) {\n return;\n }\n\n \/\/ Observe flags changed in order to get the caps lock state and pointing device events from Apple trackpads.\n \/\/\n \/\/ Note:\n \/\/ We cannot catch pointing device events from Apple trackpads without eventtap.\n \/\/ (Apple trackpad driver does not send events to IOKit.)\n\n auto mask = CGEventMaskBit(kCGEventFlagsChanged) |\n CGEventMaskBit(kCGEventLeftMouseDown) |\n CGEventMaskBit(kCGEventLeftMouseUp) |\n CGEventMaskBit(kCGEventRightMouseDown) |\n CGEventMaskBit(kCGEventRightMouseUp) |\n CGEventMaskBit(kCGEventMouseMoved) |\n CGEventMaskBit(kCGEventLeftMouseDragged) |\n CGEventMaskBit(kCGEventRightMouseDragged) |\n CGEventMaskBit(kCGEventScrollWheel) |\n CGEventMaskBit(kCGEventOtherMouseDown) |\n CGEventMaskBit(kCGEventOtherMouseUp) |\n CGEventMaskBit(kCGEventOtherMouseDragged);\n\n event_tap_ = CGEventTapCreate(kCGHIDEventTap,\n kCGTailAppendEventTap,\n kCGEventTapOptionListenOnly,\n mask,\n event_tap_manager::static_callback,\n this);\n\n if (event_tap_) {\n run_loop_source_ = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, event_tap_, 0);\n if (run_loop_source_) {\n CFRunLoopAddSource(run_loop_thread_->get_run_loop(),\n run_loop_source_,\n kCFRunLoopCommonModes);\n CGEventTapEnable(event_tap_, true);\n\n logger::get_logger().info(\"event_tap_manager initialized\");\n }\n }\n });\n }\n\nprivate:\n static CGEventRef _Nullable static_callback(CGEventTapProxy _Nullable proxy, CGEventType type, CGEventRef _Nullable event, void* _Nonnull refcon) {\n auto self = static_cast<event_tap_manager*>(refcon);\n if (self) {\n return self->callback(proxy, type, event);\n }\n return nullptr;\n }\n\n CGEventRef _Nullable callback(CGEventTapProxy _Nullable proxy, CGEventType type, CGEventRef _Nullable event) {\n switch (type) {\n case kCGEventTapDisabledByTimeout:\n logger::get_logger().info(\"Re-enable event_tap_ by kCGEventTapDisabledByTimeout\");\n CGEventTapEnable(event_tap_, true);\n break;\n\n case kCGEventTapDisabledByUserInput:\n break;\n\n case kCGEventFlagsChanged:\n \/\/ The caps lock key event from keyboard might be ignored by caps lock delay.\n \/\/ Thus, we need to observe kCGEventFlagsChanged event in EventTap to detect the caps lock state change.\n if (event) {\n auto old_caps_lock_state = get_caps_lock_state();\n last_flags_ = CGEventGetFlags(event);\n auto new_caps_lock_state = get_caps_lock_state();\n\n if (old_caps_lock_state &&\n new_caps_lock_state &&\n *old_caps_lock_state == *new_caps_lock_state) {\n \/\/ the caps lock state is not changed.\n } else {\n caps_lock_state_changed(*new_caps_lock_state);\n }\n }\n break;\n\n case kCGEventLeftMouseDown:\n case kCGEventLeftMouseUp:\n case kCGEventRightMouseDown:\n case kCGEventRightMouseUp:\n case kCGEventMouseMoved:\n case kCGEventLeftMouseDragged:\n case kCGEventRightMouseDragged:\n case kCGEventScrollWheel:\n case kCGEventOtherMouseDown:\n case kCGEventOtherMouseUp:\n case kCGEventOtherMouseDragged:\n pointing_device_event_arrived(type, event);\n break;\n\n case kCGEventNull:\n case kCGEventKeyDown:\n case kCGEventKeyUp:\n case kCGEventTabletPointer:\n case kCGEventTabletProximity:\n \/\/ These events are not captured.\n break;\n }\n\n return event;\n }\n\n boost::optional<bool> get_caps_lock_state(void) const {\n if (last_flags_) {\n return (*last_flags_ & NX_ALPHASHIFTMASK);\n }\n return boost::none;\n }\n\n std::unique_ptr<cf_utility::run_loop_thread> run_loop_thread_;\n CFMachPortRef _Nullable event_tap_;\n CFRunLoopSourceRef _Nullable run_loop_source_;\n boost::optional<CGEventFlags> last_flags_;\n};\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fcb47547-2e4e-11e5-a909-28cfe91dbc4b<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>e6d6e4e8-2e4e-11e5-a489-28cfe91dbc4b<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"WinImpl.h\"\n\n#ifdef SFML_SYSTEM_WINDOWS\n#include <Windows.h>\n#endif\n\n\nWinImpl::WinImpl()\n{\n}\n\n\nWinImpl::~WinImpl()\n{\n}\n\n\/\/ Windows Implementation\n\n#if defined SFML_SYSTEM_WINDOWS\n\nunsigned window_count = 0;\n\nLRESULT CALLBACK globalCallback(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)\n{\n\t\/\/ Associate handle and Window instance when the creation message is received\n\tif (message == WM_CREATE)\n\t{\n\t\t\/\/ Get Gwindow instance (it was passed as the last argument of CreateWindow)\n\t\tLONG_PTR window = (LONG_PTR)reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams;\n\n\t\t\/\/ Set as the \"user data\" parameter of the window\n\t\tSetWindowLongPtrW(handle, GWLP_USERDATA, window);\n\t}\n\n\t\/\/\/\/ Get the WindowImpl instance corresponding to the window handle\n\t\/\/gWindow* window = handle ? reinterpret_cast<gWindow*>(GetWindowLongPtr(handle, GWLP_USERDATA)) : NULL;\n\n\t\/\/\/\/ Forward the event to the appropriate function\n\t\/\/if (window)\n\t\/\/{\n\t\/\/\twindow->processEvent(message, wParam, lParam);\n\n\t\/\/\tif (window->m_callback)\n\t\/\/\t\treturn CallWindowProcW(reinterpret_cast<WNDPROC>(window->m_callback), handle, message, wParam, lParam);\n\t\/\/}\n\n\t\/\/ We don't forward the WM_CLOSE message to prevent the OS from automatically destroying the window\n\tif (message == WM_CLOSE)\n\t\treturn 0;\n\n\t\/\/ Don't forward the menu system command, so that pressing ALT or F10 doesn't steal the focus\n\tif ((message == WM_SYSCOMMAND) && (wParam == SC_KEYMENU))\n\t\treturn 0;\n\n\treturn DefWindowProcW(handle, message, wParam, lParam);\n}\n\ngWindowHandle WinImpl::createHandle(int x, int y, int width, int height) {\n\tif (window_count == 0) {\n\t\tWNDCLASSW window_class;\n\t\twindow_class.style = CS_DROPSHADOW;\n\t\twindow_class.lpfnWndProc = &globalCallback;\n\t\twindow_class.cbClsExtra = 0;\n\t\twindow_class.cbWndExtra = 0;\n\t\twindow_class.hInstance = GetModuleHandleW(NULL);\n\t\twindow_class.hIcon = NULL;\n\t\twindow_class.hCursor = 0;\n\t\twindow_class.hbrBackground = 0;\n\t\twindow_class.lpszMenuName = NULL;\n\t\twindow_class.lpszClassName = L\"gSplasher_Window\";\n\t\tRegisterClassW(&window_class);\n\t}\n\n\tDWORD win_style = WS_EX_LAYERED | WS_POPUP;\n\n\tRECT rect = { 0, 0, width, height };\n\tAdjustWindowRect(&rect, win_style, false);\n\twidth = rect.right - rect.left;\n\theight = rect.bottom - rect.top;\n\n\tHWND w_hwnd = CreateWindowExW(\n\t\tWS_EX_LAYERED | WS_EX_TOOLWINDOW,\n\t\tL\"gSplasher_Window\",\n\t\tnullptr,\n\t\tWS_POPUP | WS_VISIBLE,\n\t\tx,\n\t\ty,\n\t\twidth,\n\t\theight,\n\t\tnullptr,\n\t\tnullptr,\n\t\tGetModuleHandle(nullptr),\n\t\tthis\n\t\t);\n\t++window_count;\n\n\treturn w_hwnd;\n}\n\nvoid WinImpl::processEvents() {\n\tMSG message;\n\twhile (PeekMessageW(&message, NULL, 0, 0, PM_REMOVE))\n\t{\n\t\tTranslateMessage(&message);\n\t\tDispatchMessageW(&message);\n\t}\n}\n\nvoid WinImpl::setTransparency(gWindowHandle handle, unsigned char alpha) {\n\tSetLayeredWindowAttributes(handle, 0, alpha, LWA_ALPHA);\n}\n\nvoid WinImpl::redraw(gWindowHandle handle, int x, int y, int width, int height) {\n\tint m = 20;\n\tint btm_x = x + width - (m + 3);\n\tint btm_y = y + height;\n\tint c_offset_x = x + width - m;\n\tint c_offset_y = y;\n\n\tHRGN window_shape = CreateRoundRectRgn(\n\t\tx,\n\t\ty,\n\t\tbtm_x,\n\t\tbtm_y,\n\t\t3,\n\t\t3);\n\n\tHRGN exit_shape = CreateEllipticRgn(\n\t\tc_offset_x,\n\t\tc_offset_y,\n\t\tc_offset_x + m,\n\t\tc_offset_y + m\n\t\t);\n\n\tc_offset_y += 10;\n\tHRGN minimize_shape = CreateEllipticRgn(\n\t\tc_offset_x,\n\t\tc_offset_y,\n\t\tc_offset_x + m,\n\t\tc_offset_y + m\n\t\t);\n\n\tCombineRgn(window_shape, exit_shape, window_shape, RGN_OR);\n\n\n\tSetWindowRgn(handle, window_shape, true);\n\tDeleteObject(window_shape);\n\tDeleteObject(exit_shape);\n\tDeleteObject(minimize_shape);\n}\n#endif\n<commit_msg>Customized exit shape;<commit_after>#include \"WinImpl.h\"\n#include <string>\n#include <SFML\/Graphics\/Image.hpp>\n\n#ifdef SFML_SYSTEM_WINDOWS\n#include <Windows.h>\n#endif\n\n\nWinImpl::WinImpl()\n{\n}\n\n\nWinImpl::~WinImpl()\n{\n}\n\n\/\/ Windows Implementation\n\n#if defined SFML_SYSTEM_WINDOWS\n\nunsigned window_count = 0;\n\nLRESULT CALLBACK globalCallback(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)\n{\n\t\/\/ Associate handle and Window instance when the creation message is received\n\tif (message == WM_CREATE)\n\t{\n\t\t\/\/ Get Gwindow instance (it was passed as the last argument of CreateWindow)\n\t\tLONG_PTR window = (LONG_PTR)reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams;\n\n\t\t\/\/ Set as the \"user data\" parameter of the window\n\t\tSetWindowLongPtrW(handle, GWLP_USERDATA, window);\n\t}\n\n\t\/\/\/\/ Get the WindowImpl instance corresponding to the window handle\n\t\/\/gWindow* window = handle ? reinterpret_cast<gWindow*>(GetWindowLongPtr(handle, GWLP_USERDATA)) : NULL;\n\n\t\/\/\/\/ Forward the event to the appropriate function\n\t\/\/if (window)\n\t\/\/{\n\t\/\/\twindow->processEvent(message, wParam, lParam);\n\n\t\/\/\tif (window->m_callback)\n\t\/\/\t\treturn CallWindowProcW(reinterpret_cast<WNDPROC>(window->m_callback), handle, message, wParam, lParam);\n\t\/\/}\n\n\t\/\/ We don't forward the WM_CLOSE message to prevent the OS from automatically destroying the window\n\tif (message == WM_CLOSE)\n\t\treturn 0;\n\n\t\/\/ Don't forward the menu system command, so that pressing ALT or F10 doesn't steal the focus\n\tif ((message == WM_SYSCOMMAND) && (wParam == SC_KEYMENU))\n\t\treturn 0;\n\n\treturn DefWindowProcW(handle, message, wParam, lParam);\n}\n\ngWindowHandle WinImpl::createHandle(int x, int y, int width, int height) {\n\tif (window_count == 0) {\n\t\tWNDCLASSW window_class;\n\t\twindow_class.style = CS_DROPSHADOW;\n\t\twindow_class.lpfnWndProc = &globalCallback;\n\t\twindow_class.cbClsExtra = 0;\n\t\twindow_class.cbWndExtra = 0;\n\t\twindow_class.hInstance = GetModuleHandleW(NULL);\n\t\twindow_class.hIcon = NULL;\n\t\twindow_class.hCursor = 0;\n\t\twindow_class.hbrBackground = 0;\n\t\twindow_class.lpszMenuName = NULL;\n\t\twindow_class.lpszClassName = L\"gSplasher_Window\";\n\t\tRegisterClassW(&window_class);\n\t}\n\n\tDWORD win_style = WS_EX_LAYERED | WS_POPUP;\n\n\tRECT rect = { 0, 0, width, height };\n\tAdjustWindowRect(&rect, win_style, false);\n\twidth = rect.right - rect.left;\n\theight = rect.bottom - rect.top;\n\n\tHWND w_hwnd = CreateWindowExW(\n\t\tWS_EX_LAYERED | WS_EX_TOOLWINDOW,\n\t\tL\"gSplasher_Window\",\n\t\tnullptr,\n\t\tWS_POPUP | WS_VISIBLE,\n\t\tx,\n\t\ty,\n\t\twidth,\n\t\theight,\n\t\tnullptr,\n\t\tnullptr,\n\t\tGetModuleHandle(nullptr),\n\t\tthis\n\t\t);\n\t++window_count;\n\n\treturn w_hwnd;\n}\n\nvoid WinImpl::processEvents() {\n\tMSG message;\n\twhile (PeekMessageW(&message, NULL, 0, 0, PM_REMOVE))\n\t{\n\t\tTranslateMessage(&message);\n\t\tDispatchMessageW(&message);\n\t}\n}\n\nvoid WinImpl::setTransparency(gWindowHandle handle, unsigned char alpha) {\n\tSetLayeredWindowAttributes(handle, 0, alpha, LWA_ALPHA);\n}\n\nHRGN createShape(std::string path_to_file, int x, int y) {\n\tsf::Image image;\n\timage.loadFromFile(path_to_file) ? printf(\"true\") : printf(\"false\");\n\n\tint offset_x = x + image.getSize().x;\n\tint offset_y = y + image.getSize().y;\n\n\tconst sf::Uint8* pixelData = image.getPixelsPtr();\n\tHRGN hRegion = CreateRectRgn(x, y, offset_x, offset_y);\n\n\t\/\/ Determine the visible region\n\tfor (unsigned y2 = 0; y2 < image.getSize().y; y2++)\n\t{\n\t\tfor (unsigned x2 = 0; x2 < image.getSize().x; x2++)\n\t\t{\n\t\t\tif (pixelData[y2 * image.getSize().x * 4 + x2 * 4 + 3] == 0)\n\t\t\t{\n\t\t\t\tHRGN hRegionPixel = CreateRectRgn(x+x2, y+y2, x+x2 + 1, y+y2 + 1);\n\t\t\t\tCombineRgn(hRegion, hRegion, hRegionPixel, RGN_XOR);\n\t\t\t\tDeleteObject(hRegionPixel);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ WARNING: remember to delete object!!!\n\treturn hRegion;\n}\n\nvoid WinImpl::redraw(gWindowHandle handle, int x, int y, int width, int height) {\n\tint m = 30;\n\tint btm_x = x + width - (m + 3);\n\tint btm_y = y + height;\n\tint c_offset_x = x + width - m;\n\tint c_offset_y = y;\n\n\tHRGN window_shape = CreateRoundRectRgn(\n\t\tx,\n\t\ty,\n\t\tbtm_x,\n\t\tbtm_y,\n\t\t3,\n\t\t3);\n\n\tHRGN exit_shape = createShape(\n\t\t\"C:\/Users\/Autriche\/Documents\/Code\/gSplasher\/gSplasher\/Reference\/icon\/add_normal.png\",\n\t\tc_offset_x, c_offset_y);\n\n\tc_offset_y += 10;\n\tHRGN minimize_shape = CreateEllipticRgn(\n\t\tc_offset_x,\n\t\tc_offset_y,\n\t\tc_offset_x + m,\n\t\tc_offset_y + m\n\t\t);\n\n\tCombineRgn(window_shape, exit_shape, window_shape, RGN_OR);\n\n\n\tSetWindowRgn(handle, window_shape, true);\n\tDeleteObject(window_shape);\n\tDeleteObject(exit_shape);\n\tDeleteObject(minimize_shape);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef __STAN__IO__STAN_CSV_READER_HPP__\n#define __STAN__IO__STAN_CSV_READER_HPP__\n\n#include <istream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <stan\/math\/matrix.hpp>\n\nnamespace stan {\n namespace io {\n\n \/\/ FIXME: should consolidate with the options from the command line in stan::gm\n struct stan_csv_metadata {\n int stan_version_major;\n int stan_version_minor;\n int stan_version_patch;\n \n std::string model;\n std::string data;\n std::string init;\n bool append_samples;\n bool save_warmup;\n size_t seed;\n bool random_seed;\n size_t chain_id;\n size_t iter;\n size_t warmup;\n size_t thin;\n bool equal_step_sizes;\n bool nondiag_mass;\n int leapfrog_steps;\n int max_treedepth;\n double epsilon;\n double epsilon_pm;\n double delta;\n double gamma;\n std::string algorithm;\n };\n\n struct stan_csv_adaptation {\n double step_size;\n Eigen::MatrixXd metric;\n };\n \n struct stan_csv_timing {\n double warmup;\n double sampling;\n };\n\n struct stan_csv {\n stan_csv_metadata metadata;\n Eigen::Matrix<std::string, Eigen::Dynamic, 1> header;\n stan_csv_adaptation adaptation;\n Eigen::MatrixXd samples;\n stan_csv_timing timing;\n };\n\n \/**\n * Reads from a Stan output csv file.\n *\/\n class stan_csv_reader {\n \n public:\n \n stan_csv_reader() {}\n ~stan_csv_reader() {}\n\n static bool read_metadata(std::istream& in, stan_csv_metadata& metadata) {\n\n std::stringstream ss;\n std::string line;\n\n if (in.peek() != '#')\n return false;\n while (in.peek() == '#') {\n std::getline(in, line);\n ss << line << '\\n';\n }\n ss.seekg(std::ios_base::beg); \n\n char comment;\n std::string lhs;\n\n \/\/ Skip first two lines\n std::getline(ss, line);\n std::getline(ss, line);\n\n while (ss.good()) {\n \n ss >> comment;\n std::getline(ss, lhs, '=');\n boost::trim(lhs);\n \n if (lhs.compare(\"\") == 0) { \/\/ no-op\n } else if (lhs.compare(\"stan_version_major\") == 0) {\n ss >> metadata.stan_version_major;\n } else if (lhs.compare(\"stan_version_minor\") == 0) {\n ss >> metadata.stan_version_minor;\n } else if (lhs.compare(\"stan_version_patch\") == 0) {\n ss >> metadata.stan_version_patch;\n } else if (lhs.compare(\"model\") == 0) {\n ss >> metadata.model;\n } else if (lhs.compare(\"data\") == 0) {\n ss >> metadata.data; \n } else if (lhs.compare(\"init\") == 0) {\n std::getline(ss, metadata.init);\n boost::trim(metadata.init);\n ss.unget();\n } else if (lhs.compare(\"append_samples\") == 0) {\n ss >> metadata.append_samples;\n } else if (lhs.compare(\"save_warmup\") == 0) {\n ss >> metadata.save_warmup;\n } else if (lhs.compare(\"seed\") == 0) {\n ss >> metadata.seed;\n metadata.random_seed = false;\n } else if (lhs.compare(\"chain_id\") == 0) {\n ss >> metadata.chain_id;\n } else if (lhs.compare(\"iter\") == 0) {\n ss >> metadata.iter;\n } else if (lhs.compare(\"warmup\") == 0) {\n ss >> metadata.warmup;\n } else if (lhs.compare(\"thin\") == 0) {\n ss >> metadata.thin;\n } else if (lhs.compare(\"equal_step_sizes\") == 0) {\n ss >> metadata.equal_step_sizes;\n } else if (lhs.compare(\"nondiag_mass\") == 0) {\n ss >> metadata.nondiag_mass;\n } else if (lhs.compare(\"leapfrog_steps\") == 0) {\n ss >> metadata.leapfrog_steps;\n } else if (lhs.compare(\"max_treedepth\") == 0) {\n ss >> metadata.max_treedepth;\n } else if (lhs.compare(\"epsilon\") == 0) {\n ss >> metadata.epsilon;\n } else if (lhs.compare(\"epsilon_pm\") == 0) {\n ss >> metadata.epsilon_pm;\n } else if (lhs.compare(\"delta\") == 0) {\n ss >> metadata.delta;\n } else if (lhs.compare(\"gamma\") == 0) {\n ss >> metadata.gamma;\n } else if (lhs.compare(\"algorithm\") == 0) {\n std::getline(ss, metadata.algorithm);\n boost::trim(metadata.algorithm);\n ss.unget();\n } else {\n std::cout << \"unused option: \" << lhs << std::endl;\n }\n \n std::getline(ss, line);\n \n }\n \n if (ss.good() == true)\n return false;\n \n return true;\n \n } \/\/ read_metadata\n \n static bool read_header(std::istream& in, Eigen::Matrix<std::string, Eigen::Dynamic, 1>& header) {\n \n std::string line;\n\n if (in.peek() != 'l')\n return false;\n \n std::getline(in, line);\n std::stringstream ss(line);\n \n header.resize(std::count(line.begin(), line.end(), ',') + 1);\n int idx = 0;\n while (ss.good()) {\n std::string token;\n std::getline(ss, token, ',');\n boost::trim(token);\n \n int pos = token.find('.');\n if (pos > 0) {\n token.replace(pos, 1, \"[\");\n std::replace(token.begin(), token.end(), '.', ',');\n token += \"]\";\n }\n header(idx++) = token;\n }\n return true;\n }\n\n static bool read_adaptation(std::istream& in, stan_csv_adaptation& adaptation) {\n \n std::stringstream ss;\n std::string line;\n int lines = 0;\n\n if (in.peek() != '#' || in.good() == false)\n return false;\n \n while (in.peek() == '#') {\n std::getline(in, line);\n ss << line << std::endl;\n lines++;\n }\n ss.seekg(std::ios_base::beg);\n \n char comment; \/\/ Buffer for comment indicator, #\n \n \/\/ Skip first two lines\n std::getline(ss, line);\n \n \/\/ Stepsize\n std::getline(ss, line, '=');\n boost::trim(line);\n ss >> adaptation.step_size;\n \n \/\/ Metric parameters\n std::getline(ss, line);\n std::getline(ss, line);\n std::getline(ss, line);\n \n int rows = lines - 3;\n int cols = std::count(line.begin(), line.end(), ',') + 1;\n adaptation.metric.resize(rows, cols);\n \n for (int row = 0; row < rows; row++) {\n \n std::stringstream line_ss;\n line_ss.str(line);\n line_ss >> comment;\n \n for (int col = 0; col < cols; col++) {\n std::string token;\n std::getline(line_ss, token, ',');\n boost::trim(token);\n adaptation.metric(row, col) = boost::lexical_cast<double>(token);\n }\n \n std::getline(ss, line); \/\/ Read in next line\n \n }\n \n if (ss.good())\n return false;\n else\n return true;\n\n }\n \n static bool read_samples(std::istream& in, Eigen::MatrixXd& samples, stan_csv_timing& timing) {\n \n std::stringstream ss;\n std::string line;\n\n int rows = 0; \n int cols = -1;\n\n if (in.peek() == '#' || in.good() == false)\n return false;\n\n while (in.good()) {\n \n bool comment_line = (in.peek() == '#');\n bool empty_line = (in.peek() == '\\n');\n\n std::getline(in, line);\n \n if (empty_line) continue;\n if (!line.length()) break;\n \n if (comment_line) {\n\n if (line.find(\"(Warm-up)\") != std::string::npos) {\n int left = 16;\n int right = line.find(\" seconds\");\n timing.warmup += boost::lexical_cast<double>(line.substr(left, right - left));\n } else if (line.find(\"(Sampling)\") != std::string::npos) {\n int left = 16;\n int right = line.find(\" seconds\");\n timing.sampling += boost::lexical_cast<double>(line.substr(left, right - left));\n }\n \n }\n else {\n\n ss << line << '\\n';\n \n int current_cols = std::count(line.begin(), line.end(), ',') + 1;\n if (cols == -1) {\n cols = current_cols;\n } else if (cols != current_cols) {\n std::cout << \"Error: expected \" << cols << \" columns, but found \" \n << current_cols << \" instead for row \" << rows + 1 << std::endl;\n return false;\n }\n rows++;\n \n }\n \n in.peek();\n \n }\n \n ss.seekg(std::ios_base::beg);\n\n if (rows > 0) {\n samples.resize(rows, cols);\n for (int row = 0; row < rows; row++) {\n std::getline(ss, line);\n std::stringstream ls(line);\n for (int col = 0; col < cols; col++) {\n std::getline(ls, line, ',');\n boost::trim(line);\n samples(row, col) = boost::lexical_cast<double>(line);\n }\n }\n }\n return true;\n }\n \n \/** \n * Parses the file.\n * \n *\/\n static stan_csv parse(std::istream& in) {\n \n stan_csv data;\n \n if (!read_metadata(in, data.metadata)) {\n std::cout << \"Warning: non-fatal error reading metadata\" << std::endl;\n }\n \n if (!read_header(in, data.header)) {\n std::cout << \"Error: error reading header\" << std::endl;\n throw std::invalid_argument(\"Error with header of input file in parse\");\n }\n\n if (!read_adaptation(in, data.adaptation)) {\n std::cout << \"Warning: non-fatal error reading adapation data\" << std::endl;\n }\n\n data.timing.warmup = 0;\n data.timing.sampling = 0;\n \n if (!read_samples(in, data.samples, data.timing)) {\n std::cout << \"Warning: non-fatal error reading samples\" << std::endl;\n }\n \n return data;\n \n }\n \n };\n \n } \/\/ io\n \n} \/\/ stan\n\n#endif\n<commit_msg>adding default constructor for stan_csv_timing. Windows doesn't set the members to 0<commit_after>#ifndef __STAN__IO__STAN_CSV_READER_HPP__\n#define __STAN__IO__STAN_CSV_READER_HPP__\n\n#include <istream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <stan\/math\/matrix.hpp>\n\nnamespace stan {\n namespace io {\n\n \/\/ FIXME: should consolidate with the options from the command line in stan::gm\n struct stan_csv_metadata {\n int stan_version_major;\n int stan_version_minor;\n int stan_version_patch;\n \n std::string model;\n std::string data;\n std::string init;\n bool append_samples;\n bool save_warmup;\n size_t seed;\n bool random_seed;\n size_t chain_id;\n size_t iter;\n size_t warmup;\n size_t thin;\n bool equal_step_sizes;\n bool nondiag_mass;\n int leapfrog_steps;\n int max_treedepth;\n double epsilon;\n double epsilon_pm;\n double delta;\n double gamma;\n std::string algorithm;\n };\n\n struct stan_csv_adaptation {\n double step_size;\n Eigen::MatrixXd metric;\n };\n \n struct stan_csv_timing {\n double warmup;\n double sampling;\n \n stan_csv_timing() \n : warmup(0), sampling(0) { }\n };\n\n struct stan_csv {\n stan_csv_metadata metadata;\n Eigen::Matrix<std::string, Eigen::Dynamic, 1> header;\n stan_csv_adaptation adaptation;\n Eigen::MatrixXd samples;\n stan_csv_timing timing;\n };\n\n \/**\n * Reads from a Stan output csv file.\n *\/\n class stan_csv_reader {\n \n public:\n \n stan_csv_reader() {}\n ~stan_csv_reader() {}\n\n static bool read_metadata(std::istream& in, stan_csv_metadata& metadata) {\n\n std::stringstream ss;\n std::string line;\n\n if (in.peek() != '#')\n return false;\n while (in.peek() == '#') {\n std::getline(in, line);\n ss << line << '\\n';\n }\n ss.seekg(std::ios_base::beg); \n\n char comment;\n std::string lhs;\n\n \/\/ Skip first two lines\n std::getline(ss, line);\n std::getline(ss, line);\n\n while (ss.good()) {\n \n ss >> comment;\n std::getline(ss, lhs, '=');\n boost::trim(lhs);\n \n if (lhs.compare(\"\") == 0) { \/\/ no-op\n } else if (lhs.compare(\"stan_version_major\") == 0) {\n ss >> metadata.stan_version_major;\n } else if (lhs.compare(\"stan_version_minor\") == 0) {\n ss >> metadata.stan_version_minor;\n } else if (lhs.compare(\"stan_version_patch\") == 0) {\n ss >> metadata.stan_version_patch;\n } else if (lhs.compare(\"model\") == 0) {\n ss >> metadata.model;\n } else if (lhs.compare(\"data\") == 0) {\n ss >> metadata.data; \n } else if (lhs.compare(\"init\") == 0) {\n std::getline(ss, metadata.init);\n boost::trim(metadata.init);\n ss.unget();\n } else if (lhs.compare(\"append_samples\") == 0) {\n ss >> metadata.append_samples;\n } else if (lhs.compare(\"save_warmup\") == 0) {\n ss >> metadata.save_warmup;\n } else if (lhs.compare(\"seed\") == 0) {\n ss >> metadata.seed;\n metadata.random_seed = false;\n } else if (lhs.compare(\"chain_id\") == 0) {\n ss >> metadata.chain_id;\n } else if (lhs.compare(\"iter\") == 0) {\n ss >> metadata.iter;\n } else if (lhs.compare(\"warmup\") == 0) {\n ss >> metadata.warmup;\n } else if (lhs.compare(\"thin\") == 0) {\n ss >> metadata.thin;\n } else if (lhs.compare(\"equal_step_sizes\") == 0) {\n ss >> metadata.equal_step_sizes;\n } else if (lhs.compare(\"nondiag_mass\") == 0) {\n ss >> metadata.nondiag_mass;\n } else if (lhs.compare(\"leapfrog_steps\") == 0) {\n ss >> metadata.leapfrog_steps;\n } else if (lhs.compare(\"max_treedepth\") == 0) {\n ss >> metadata.max_treedepth;\n } else if (lhs.compare(\"epsilon\") == 0) {\n ss >> metadata.epsilon;\n } else if (lhs.compare(\"epsilon_pm\") == 0) {\n ss >> metadata.epsilon_pm;\n } else if (lhs.compare(\"delta\") == 0) {\n ss >> metadata.delta;\n } else if (lhs.compare(\"gamma\") == 0) {\n ss >> metadata.gamma;\n } else if (lhs.compare(\"algorithm\") == 0) {\n std::getline(ss, metadata.algorithm);\n boost::trim(metadata.algorithm);\n ss.unget();\n } else {\n std::cout << \"unused option: \" << lhs << std::endl;\n }\n \n std::getline(ss, line);\n \n }\n \n if (ss.good() == true)\n return false;\n \n return true;\n \n } \/\/ read_metadata\n \n static bool read_header(std::istream& in, Eigen::Matrix<std::string, Eigen::Dynamic, 1>& header) {\n \n std::string line;\n\n if (in.peek() != 'l')\n return false;\n \n std::getline(in, line);\n std::stringstream ss(line);\n \n header.resize(std::count(line.begin(), line.end(), ',') + 1);\n int idx = 0;\n while (ss.good()) {\n std::string token;\n std::getline(ss, token, ',');\n boost::trim(token);\n \n int pos = token.find('.');\n if (pos > 0) {\n token.replace(pos, 1, \"[\");\n std::replace(token.begin(), token.end(), '.', ',');\n token += \"]\";\n }\n header(idx++) = token;\n }\n return true;\n }\n\n static bool read_adaptation(std::istream& in, stan_csv_adaptation& adaptation) {\n \n std::stringstream ss;\n std::string line;\n int lines = 0;\n\n if (in.peek() != '#' || in.good() == false)\n return false;\n \n while (in.peek() == '#') {\n std::getline(in, line);\n ss << line << std::endl;\n lines++;\n }\n ss.seekg(std::ios_base::beg);\n \n char comment; \/\/ Buffer for comment indicator, #\n \n \/\/ Skip first two lines\n std::getline(ss, line);\n \n \/\/ Stepsize\n std::getline(ss, line, '=');\n boost::trim(line);\n ss >> adaptation.step_size;\n \n \/\/ Metric parameters\n std::getline(ss, line);\n std::getline(ss, line);\n std::getline(ss, line);\n \n int rows = lines - 3;\n int cols = std::count(line.begin(), line.end(), ',') + 1;\n adaptation.metric.resize(rows, cols);\n \n for (int row = 0; row < rows; row++) {\n \n std::stringstream line_ss;\n line_ss.str(line);\n line_ss >> comment;\n \n for (int col = 0; col < cols; col++) {\n std::string token;\n std::getline(line_ss, token, ',');\n boost::trim(token);\n adaptation.metric(row, col) = boost::lexical_cast<double>(token);\n }\n \n std::getline(ss, line); \/\/ Read in next line\n \n }\n \n if (ss.good())\n return false;\n else\n return true;\n\n }\n \n static bool read_samples(std::istream& in, Eigen::MatrixXd& samples, stan_csv_timing& timing) {\n \n std::stringstream ss;\n std::string line;\n\n int rows = 0; \n int cols = -1;\n\n if (in.peek() == '#' || in.good() == false)\n return false;\n\n while (in.good()) {\n \n bool comment_line = (in.peek() == '#');\n bool empty_line = (in.peek() == '\\n');\n\n std::getline(in, line);\n \n if (empty_line) continue;\n if (!line.length()) break;\n \n if (comment_line) {\n\n if (line.find(\"(Warm-up)\") != std::string::npos) {\n int left = 16;\n int right = line.find(\" seconds\");\n timing.warmup += boost::lexical_cast<double>(line.substr(left, right - left));\n } else if (line.find(\"(Sampling)\") != std::string::npos) {\n int left = 16;\n int right = line.find(\" seconds\");\n timing.sampling += boost::lexical_cast<double>(line.substr(left, right - left));\n }\n \n }\n else {\n\n ss << line << '\\n';\n \n int current_cols = std::count(line.begin(), line.end(), ',') + 1;\n if (cols == -1) {\n cols = current_cols;\n } else if (cols != current_cols) {\n std::cout << \"Error: expected \" << cols << \" columns, but found \" \n << current_cols << \" instead for row \" << rows + 1 << std::endl;\n return false;\n }\n rows++;\n \n }\n \n in.peek();\n \n }\n \n ss.seekg(std::ios_base::beg);\n\n if (rows > 0) {\n samples.resize(rows, cols);\n for (int row = 0; row < rows; row++) {\n std::getline(ss, line);\n std::stringstream ls(line);\n for (int col = 0; col < cols; col++) {\n std::getline(ls, line, ',');\n boost::trim(line);\n \/\/std::cout << \"line: !\" << line << \"@\" << std::endl;\n samples(row, col) = boost::lexical_cast<double>(line);\n \/\/std::cout << \"after\" << std::endl << std::endl;\n }\n }\n }\n return true;\n }\n \n \/** \n * Parses the file.\n * \n *\/\n static stan_csv parse(std::istream& in) {\n \n stan_csv data;\n \n if (!read_metadata(in, data.metadata)) {\n std::cout << \"Warning: non-fatal error reading metadata\" << std::endl;\n }\n \n if (!read_header(in, data.header)) {\n std::cout << \"Error: error reading header\" << std::endl;\n throw std::invalid_argument(\"Error with header of input file in parse\");\n }\n\n if (!read_adaptation(in, data.adaptation)) {\n std::cout << \"Warning: non-fatal error reading adapation data\" << std::endl;\n }\n\n data.timing.warmup = 0;\n data.timing.sampling = 0;\n \n if (!read_samples(in, data.samples, data.timing)) {\n std::cout << \"Warning: non-fatal error reading samples\" << std::endl;\n }\n \n return data;\n \n }\n \n };\n \n } \/\/ io\n \n} \/\/ stan\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ An example how to display PS, EPS, PDF files in canvas\n\/\/ To load a PS file in a TCanvas, the ghostscript program needs to be install.\n\/\/ - On most unix systems it is installed by default.\n\/\/ - On Windows it has to be installed from http:\/\/pages.cs.wisc.edu\/~ghost\/\n\/\/ also the place where gswin32c.exe sits should be added in the PATH. One\n\/\/ way to do it is: \n\/\/ 1. Start the Control Panel\n\/\/ 2. Double click on System\n\/\/ 3, Open the \"Advanced\" tab\n\/\/ 4. Click on the \"Environment Variables\" button\n\/\/ 5. Find \"Path\" in \"System varibale list\", click on it.\n\/\/ 6. Click on the \"Edit\" button.\n\/\/ 7. In the \"Variable value\" field add the path of gswin32c \n\/\/ (after a \";\") it should be something like:\n\/\/ \"C:\\Program Files\\gs\\gs8.13\\bin\"\n\/\/ 8. click \"OK\" as much as needed.\n\/\/\n\/\/Author: Valeriy Onoutchin\n \n#include \"TROOT.h\"\n#include \"TCanvas.h\"\n#include \"TImage.h\"\n\nvoid psview()\n{\n \/\/ set to batch mode -> do not display graphics\n gROOT->SetBatch(1);\n\n \/\/ create a PostScript file\n gROOT->Macro(\"feynman.C\");\n gPad->Print(\"feynman.ps\");\n\n \/\/ back to graphics mode\n gROOT->SetBatch(0);\n\n \/\/ create an image from PS file\n TImage *ps = TImage::Open(\"feynman.ps\");\n\n if (!ps) {\n printf(\"GhostScript (gs) program must be installed\\n\");\n return;\n }\n\n new TCanvas(\"psexam\", \"Example how to display PS file in canvas\", 500, 650);\n ps->Draw(\"xxx\"); \n}\n<commit_msg>- Better version.<commit_after>\/\/ An example how to display PS, EPS, PDF files in canvas\n\/\/ To load a PS file in a TCanvas, the ghostscript program needs to be install.\n\/\/ - On most unix systems it is installed by default.\n\/\/ - On Windows it has to be installed from http:\/\/pages.cs.wisc.edu\/~ghost\/\n\/\/ also the place where gswin32c.exe sits should be added in the PATH. One\n\/\/ way to do it is: \n\/\/ 1. Start the Control Panel\n\/\/ 2. Double click on System\n\/\/ 3, Open the \"Advanced\" tab\n\/\/ 4. Click on the \"Environment Variables\" button\n\/\/ 5. Find \"Path\" in \"System varibale list\", click on it.\n\/\/ 6. Click on the \"Edit\" button.\n\/\/ 7. In the \"Variable value\" field add the path of gswin32c \n\/\/ (after a \";\") it should be something like:\n\/\/ \"C:\\Program Files\\gs\\gs8.13\\bin\"\n\/\/ 8. click \"OK\" as much as needed.\n\/\/\n\/\/Author: Valeriy Onoutchin\n \n#include \"TROOT.h\"\n#include \"TCanvas.h\"\n#include \"TImage.h\"\n\nvoid psview()\n{\n \/\/ set to batch mode -> do not display graphics\n gROOT->SetBatch(1);\n\n \/\/ create a PostScript file\n gROOT->Macro(\"feynman.C\");\n gPad->Print(\"feynman.eps\");\n\n \/\/ back to graphics mode\n gROOT->SetBatch(0);\n\n \/\/ create an image from PS file\n TImage *ps = TImage::Open(\"feynman.eps\");\n\n if (!ps) {\n printf(\"GhostScript (gs) program must be installed\\n\");\n return;\n }\n\n new TCanvas(\"psexam\", \"Example how to display PS file in canvas\", 600, 400);\n TLatex *tex = new TLatex(0.06,0.9,\"The picture below has been loaded from a PS file:\");\n tex->Draw();\n\n TPad *eps = new TPad(\"eps\", \"eps\", 0., 0., 1., 0.75);\n eps->Draw();\n eps->cd();\n ps->Draw(\"xxx\"); \n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ This file is part of Swift2D. \/\/\n\/\/ \/\/\n\/\/ Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ includes -------------------------------------------------------------------\n#include <swift2d\/network\/Network.hpp>\n\n#include <swift2d\/network\/ReplicationManager.hpp>\n#include <swift2d\/utils\/Logger.hpp>\n#include <swift2d\/math\/operators.hpp>\n\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n\n#include <raknet\/MessageIdentifiers.h>\n#include <raknet\/RakNetTypes.h>\n#include <raknet\/RakPeerInterface.h>\n#include <raknet\/BitStream.h>\n#include <raknet\/FullyConnectedMesh2.h>\n#include <raknet\/PacketLogger.h>\n#include <raknet\/NatTypeDetectionClient.h>\n#include <raknet\/ConnectionGraph2.h>\n#include <raknet\/NatPunchthroughClient.h>\n#include <raknet\/NetworkIDManager.h>\n\n#include <sstream>\n\n#define USE_UPNP false\n\nnamespace swift {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNetwork::Network()\n : phase_(STARTED)\n , peer_ (RakNet::RakPeerInterface::GetInstance())\n , graph_ (RakNet::ConnectionGraph2::GetInstance())\n , mesh_ (RakNet::FullyConnectedMesh2::GetInstance())\n , npt_ (RakNet::NatPunchthroughClient::GetInstance())\n , id_manager_ (new RakNet::NetworkIDManager())\n , replica_ (new ReplicationManager())\n , internal_id_ (\"\")\n , external_id_ (\"\") {\n\n peer_->AttachPlugin(mesh_);\n peer_->AttachPlugin(graph_);\n peer_->AttachPlugin(npt_);\n peer_->AttachPlugin(replica_);\n\n replica_->SetNetworkIDManager(id_manager_);\n replica_->SetAutoManageConnections(false,true);\n\n mesh_->SetAutoparticipateConnections(false);\n mesh_->SetConnectOnNewRemoteConnection(false, \"\");\n\n RakNet::SocketDescriptor sd;\n sd.socketFamily = AF_INET;\n sd.port = 0;\n\n RakNet::StartupResult sr = peer_->Startup(8, &sd, 1);\n\n if (sr != RakNet::RAKNET_STARTED) {\n LOG_ERROR << \"Failed to start peer!\" << std::endl;\n }\n\n peer_->SetMaximumIncomingConnections(8);\n peer_->SetTimeoutTime(1000, RakNet::UNASSIGNED_SYSTEM_ADDRESS);\n\n phase_ = CONNECTING_TO_NAT_SERVER;\n RakNet::ConnectionAttemptResult car = peer_->Connect(\"natpunch.jenkinssoftware.com\", 61111, 0, 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNetwork::~Network() {\n peer_->Shutdown(100);\n RakNet::RakPeerInterface::DestroyInstance(peer_);\n RakNet::ConnectionGraph2::DestroyInstance(graph_);\n RakNet::FullyConnectedMesh2::DestroyInstance(mesh_);\n\n delete replica_;\n delete id_manager_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::connect(std::string const& other) {\n if (phase_ == STARTED) {\n\n auto o(RakNet::SystemAddress(other.c_str()));\n auto host(o.ToString(false));\n\n LOG_MESSAGE << \"Connecting to \" << host << \".\" << std::endl;\n\n if (is_in_same_network(other)) {\n phase_ = CONNECTING_TO_HOST;\n peer_->Connect(host, o.GetPort(), 0, 0);\n } else {\n phase_ = NAT_PUNCH_TO_HOST;\n npt_->OpenNAT(peer_->GetGuidFromSystemAddress(o),\n RakNet::SystemAddress(nat_server_address_.c_str()));\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ upnp_.on_success.connect([&](){\n \/\/ Logger::LOG_MESSAGE << \"Successfully opened UPNP.\" << std::endl;\n \/\/ enter_phase(SEARCHING_FOR_OTHER_INSTANCES);\n \/\/ });\n\n \/\/ upnp_.on_fail.connect([&](){\n \/\/ Logger::LOG_MESSAGE << \"Failed to open UPNP. Using NAT punch through.\" << std::endl;\n \/\/ enter_phase(OPENING_UPNP);\n \/\/ });\n\n \/\/ enter_phase(HOSTING_INSTANCE);\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::update() {\n\n \/\/ auto register_new_peer = [&](RakNet::RakNetGUID guid){\n \/\/ RakNet::Connection_RM3 *connection = replica_->AllocConnection(peer_->GetSystemAddressFromGuid(guid), guid);\n \/\/ if (replica_->PushConnection(connection) == false) {\n \/\/ replica_->DeallocConnection(connection);\n \/\/ }\n \/\/ };\n\n for (RakNet::Packet* packet=peer_->Receive(); packet; peer_->DeallocatePacket(packet), packet=peer_->Receive()) {\n switch (packet->data[0]) {\n\n \/\/ ##################### BASIC PACKETS ###################################\n \/\/ -----------------------------------------------------------------------\n case ID_CONNECTION_REQUEST_ACCEPTED:\n\n if (phase_ == CONNECTING_TO_NAT_SERVER) {\n\n \/\/ the nat server accepted our connection\n LOG_MESSAGE << \"Connected to NAT server.\" << std::endl;\n nat_server_address_ = packet->systemAddress.ToString();\n\n \/\/ save external ip\n external_id_ = peer_->GetExternalID(RakNet::UNASSIGNED_SYSTEM_ADDRESS).ToString();\n\n \/\/ broadcast on LAN to get internal ip\n peer_->AdvertiseSystem(\"255.255.255.255\", peer_->GetInternalID().GetPort(), 0, 0);\n\n } else if (phase_ == NAT_PUNCH_TO_HOST) {\n\n \/\/ nat punch was successfull, we got a connection!\n phase_ = CONNECTING_TO_HOST;\n request_join(packet->guid.g);\n\n } else if (phase_ == CONNECTING_TO_HOST) {\n request_join(packet->guid.g);\n }\n\n break;\n\n \/\/ -----------------------------------------------------------------------\n case ID_ADVERTISE_SYSTEM:\n if (packet->guid.g == peer_->GetMyGUID().g) {\n \/\/ save internal ip\n internal_id_ = packet->systemAddress.ToString();\n }\n\n break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_DISCONNECTION_NOTIFICATION:\n \/\/ Logger::LOG_MESSAGE << packet->guid.ToString() << \" disconnected.\" << std::endl;\n \/\/ break;\n\n \/\/ \/\/ ################ NAT PUNCH THROUGH PACKETS ############################\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_NAT_PUNCHTHROUGH_SUCCEEDED:\n \/\/ if (phase_ == CONNECTING_TO_HOST || phase_ == CONNECTING_TO_PEERS) {\n \/\/ Logger::LOG_MESSAGE << \"NAT punch succeeded. Connecting...\" << std::endl;\n \/\/ connect(packet->systemAddress.ToString(false), packet->systemAddress.GetPort());\n \/\/ }\n \/\/ break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_NAT_PUNCHTHROUGH_FAILED:\n \/\/ Logger::LOG_MESSAGE << \"NAT punch through failed.\" << std::endl;\n \/\/ break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_NAT_TYPE_DETECTION_RESULT: {\n \/\/ auto type = (RakNet::NATTypeDetectionResult) packet->data[1];\n \/\/ Logger::LOG_MESSAGE << \"NAT Type is \" << RakNet::NATTypeDetectionResultToString(type) << \" (\" << RakNet::NATTypeDetectionResultToStringFriendly(type) << \")\" << std::endl;\n\n \/\/ if (USE_UPNP) enter_phase(OPENING_UPNP);\n \/\/ else enter_phase(SEARCHING_FOR_OTHER_INSTANCES);\n \/\/ } break;\n\n \/\/ \/\/ ################## FULLY CONNECTED MESH ###############################\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_NEW_HOST: {\n \/\/ RakNet::BitStream bs(packet->data, packet->length, false);\n \/\/ bs.IgnoreBytes(1);\n \/\/ RakNet::RakNetGUID old_host;\n \/\/ bs.Read(old_host);\n\n \/\/ if (packet->guid.g == peer_->GetMyGUID().g) {\n \/\/ if (phase_ != HOSTING_INSTANCE) {\n \/\/ enter_phase(HOSTING_INSTANCE);\n \/\/ }\n \/\/ } else {\n \/\/ Logger::LOG_MESSAGE << packet->guid.ToString() << \" is host now.\" << std::endl;\n\n\n \/\/ if (old_host != RakNet::UNASSIGNED_RAKNET_GUID) {\n \/\/ Logger::LOG_MESSAGE << \"Old host was \" << old_host.ToString() << std::endl;\n \/\/ } else {\n \/\/ Logger::LOG_MESSAGE << \"There was no host before.\" << std::endl;\n \/\/ }\n \/\/ }\n\n \/\/ if (old_host == RakNet::UNASSIGNED_RAKNET_GUID) {\n \/\/ DataStructures::List<RakNet::RakNetGUID> peers;\n \/\/ mesh_->GetParticipantList(peers);\n \/\/ for (unsigned int i=0; i < peers.Size(); i++) {\n \/\/ register_new_peer(peers[i]);\n \/\/ }\n \/\/ }\n\n \/\/ } break;\n\n \/\/ -----------------------------------------------------------------------\n case (ID_USER_PACKET_ENUM + REQUEST_JOIN):\n Logger::LOG_MESSAGE << \"Got join request from \" << packet->guid.ToString() << \".\" << std::endl;\n start_join(packet->guid.g);\n break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_VERIFIED_JOIN_CAPABLE:\n \/\/ mesh_->RespondOnVerifiedJoinCapable(packet, true, 0);\n \/\/ break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_VERIFIED_JOIN_ACCEPTED: {\n \/\/ DataStructures::List<RakNet::RakNetGUID> peers;\n \/\/ bool this_was_accepted;\n \/\/ mesh_->GetVerifiedJoinAcceptedAdditionalData(packet, &this_was_accepted, peers, 0);\n \/\/ if (this_was_accepted) {\n \/\/ Logger::LOG_MESSAGE << \"Join accepted.\" << std::endl;\n \/\/ } else {\n \/\/ Logger::LOG_MESSAGE << \"Peer \" << peers[0].ToString() << \" joined the game.\" << std::endl;\n \/\/ }\n\n \/\/ if (mesh_->GetConnectedHost() != RakNet::UNASSIGNED_RAKNET_GUID) {\n \/\/ for (unsigned int i=0; i < peers.Size(); i++) {\n \/\/ register_new_peer(peers[i]);\n \/\/ }\n \/\/ }\n\n \/\/ if (this_was_accepted) {\n \/\/ enter_phase(PARTICIPATING);\n \/\/ }\n\n \/\/ } break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_VERIFIED_JOIN_REJECTED:\n \/\/ Logger::LOG_MESSAGE << \"Join rejected.\" << std::endl;\n \/\/ peer_->CloseConnection(packet->guid, true);\n \/\/ break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_VERIFIED_JOIN_FAILED:\n \/\/ Logger::LOG_MESSAGE << \"Join failed.\" << std::endl;\n \/\/ break;\n\n \/\/ -----------------------------------------------------------------------\n case ID_FCM2_VERIFIED_JOIN_START:\n Logger::LOG_MESSAGE << \"Connecting to other peers...\" << std::endl;\n \/\/ enter_phase(CONNECTING_TO_PEERS);\n \/\/ join(packet->guid.g, nat_server_address_);\n break;\n\n \/\/ ##################### OTHER PACKETS ###################################\n \/\/ -----------------------------------------------------------------------\n default:\n LOG_DEBUG << \"Got \" << RakNet::PacketLogger::BaseIDTOString(packet->data[0])\n << \" from \" << packet->guid.ToString() << std::endl;\n break;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::distribute_object(NetworkObjectBase* object) {\n replica_->Reference(object);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Network::is_in_same_network(std::string const& other) const {\n RakNet::SystemAddress o;\n RakNet::SystemAddress self;\n if (o.FromString(other.c_str()) && self.FromString(external_id_.c_str())) {\n if (o.EqualsExcludingPort(self)) {\n return true;\n }\n }\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string const& Network::get_internal_address() const {\n return internal_id_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string const& Network::get_external_address() const {\n return external_id_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Network::is_host() const {\n return mesh_->IsConnectedHost();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::enter_phase(Phase phase) {\n \/\/ phase_ = phase;\n\n \/\/ switch (phase) {\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case CONNECTING_TO_SERVER:\n \/\/ Logger::LOG_MESSAGE << \"Connecting to NAT server...\" << std::endl;\n \/\/ connect(\"natpunch.jenkinssoftware.com\", 61111);\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case OPENING_UPNP:\n \/\/ Logger::LOG_MESSAGE << \"Opening UPNP...\" << std::endl;\n \/\/ \/\/ upnp_.open(peer_);\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case SEARCHING_FOR_OTHER_INSTANCES:\n \/\/ Logger::LOG_MESSAGE << \"Downloading running instances from \"\n \/\/ << \"master server...\" << std::endl;\n \/\/ http_.get(\"masterserver2.raknet.com\/testServer?__gameId=\" + game_ID_,\n \/\/ \"masterserver2.raknet.com\", 80);\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case CONNECTING_TO_HOST:\n \/\/ Logger::LOG_MESSAGE << \"Found running instance. Searching route to host \"\n \/\/ << host_guid_ << \"...\" << std::endl;\n \/\/ open_nat(host_guid_, nat_server_address_);\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case STARTING_NEW_INSTANCE:\n \/\/ Logger::LOG_MESSAGE << \"No running instances found. \"\n \/\/ << \"Starting new instance...\" << std::endl;\n \/\/ mesh_->ResetHostCalculation();\n \/\/ \/\/ register_game();\n \/\/ \/\/ update_timer_.reset();\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case HOSTING_INSTANCE:\n \/\/ Logger::LOG_MESSAGE << \"I'm host now.\" << std::endl;\n \/\/ \/\/ register_game();\n \/\/ \/\/ update_timer_.reset();\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case PARTICIPATING:\n \/\/ Logger::LOG_MESSAGE << \"Participating game.\" << std::endl;\n \/\/ break;\n \/\/ }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::request_join(math::uint64 guid) {\n mesh_->ResetHostCalculation();\n\n RakNet::BitStream message;\n message.Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + Network::REQUEST_JOIN));\n peer_->Send(&message, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::RakNetGUID(guid), false);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::start_join(math::uint64 guid) {\n mesh_->StartVerifiedJoin(RakNet::RakNetGUID(guid));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ void Network::join(math::uint64 guid, std::string const& nat_server) {\n\/\/ DataStructures::List<RakNet::SystemAddress> addresses;\n\/\/ DataStructures::List<RakNet::RakNetGUID> guids;\n\/\/ DataStructures::List<RakNet::BitStream*> userData;\n\/\/ mesh_->GetVerifiedJoinRequiredProcessingList(RakNet::RakNetGUID(guid), addresses, guids, userData);\n\/\/ for (unsigned int i=0; i < guids.Size(); i++) {\n\/\/ \/\/ if (guids[i].g != get_guid()) {\n\/\/ npt_->OpenNAT(guids[i], RakNet::SystemAddress(nat_server.c_str()));\n\/\/ \/\/ }\n\/\/ }\n\/\/ }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n<commit_msg>added LAN connect<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ This file is part of Swift2D. \/\/\n\/\/ \/\/\n\/\/ Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ includes -------------------------------------------------------------------\n#include <swift2d\/network\/Network.hpp>\n\n#include <swift2d\/network\/ReplicationManager.hpp>\n#include <swift2d\/utils\/Logger.hpp>\n#include <swift2d\/math\/operators.hpp>\n\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n\n#include <raknet\/MessageIdentifiers.h>\n#include <raknet\/RakNetTypes.h>\n#include <raknet\/RakPeerInterface.h>\n#include <raknet\/BitStream.h>\n#include <raknet\/FullyConnectedMesh2.h>\n#include <raknet\/PacketLogger.h>\n#include <raknet\/NatTypeDetectionClient.h>\n#include <raknet\/ConnectionGraph2.h>\n#include <raknet\/NatPunchthroughClient.h>\n#include <raknet\/NetworkIDManager.h>\n\n#include <sstream>\n\n#define USE_UPNP false\n\nnamespace swift {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNetwork::Network()\n : phase_(STARTED)\n , peer_ (RakNet::RakPeerInterface::GetInstance())\n , graph_ (RakNet::ConnectionGraph2::GetInstance())\n , mesh_ (RakNet::FullyConnectedMesh2::GetInstance())\n , npt_ (RakNet::NatPunchthroughClient::GetInstance())\n , id_manager_ (new RakNet::NetworkIDManager())\n , replica_ (new ReplicationManager())\n , internal_id_ (\"\")\n , external_id_ (\"\") {\n\n peer_->AttachPlugin(mesh_);\n peer_->AttachPlugin(graph_);\n peer_->AttachPlugin(npt_);\n peer_->AttachPlugin(replica_);\n\n replica_->SetNetworkIDManager(id_manager_);\n replica_->SetAutoManageConnections(false,true);\n\n mesh_->SetAutoparticipateConnections(false);\n mesh_->SetConnectOnNewRemoteConnection(false, \"\");\n\n RakNet::SocketDescriptor sd;\n sd.socketFamily = AF_INET;\n sd.port = 0;\n\n RakNet::StartupResult sr = peer_->Startup(8, &sd, 1);\n\n\n\n if (sr != RakNet::RAKNET_STARTED) {\n LOG_ERROR << \"Failed to start peer!\" << std::endl;\n }\n\n peer_->SetMaximumIncomingConnections(8);\n peer_->SetTimeoutTime(1000, RakNet::UNASSIGNED_SYSTEM_ADDRESS);\n\n phase_ = CONNECTING_TO_NAT_SERVER;\n RakNet::ConnectionAttemptResult car = peer_->Connect(\"natpunch.jenkinssoftware.com\", 61111, 0, 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNetwork::~Network() {\n peer_->Shutdown(100);\n RakNet::RakPeerInterface::DestroyInstance(peer_);\n RakNet::ConnectionGraph2::DestroyInstance(graph_);\n RakNet::FullyConnectedMesh2::DestroyInstance(mesh_);\n\n delete replica_;\n delete id_manager_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::connect(std::string const& other) {\n auto o(RakNet::SystemAddress(other.c_str()));\n\n if (is_in_same_network(other)) {\n phase_ = CONNECTING_TO_HOST;\n LOG_MESSAGE << \"Connecting to \" << o.ToString() << \" via LAN...\" << std::endl;\n peer_->Connect(o.ToString(false), o.GetPort(), 0, 0);\n } else {\n phase_ = NAT_PUNCH_TO_HOST;\n LOG_MESSAGE << \"Connecting to \" << o.ToString() << \" via NatPunch...\" << std::endl;\n npt_->OpenNAT(peer_->GetGuidFromSystemAddress(o),\n RakNet::SystemAddress(nat_server_address_.c_str()));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ upnp_.on_success.connect([&](){\n \/\/ Logger::LOG_MESSAGE << \"Successfully opened UPNP.\" << std::endl;\n \/\/ enter_phase(SEARCHING_FOR_OTHER_INSTANCES);\n \/\/ });\n\n \/\/ upnp_.on_fail.connect([&](){\n \/\/ Logger::LOG_MESSAGE << \"Failed to open UPNP. Using NAT punch through.\" << std::endl;\n \/\/ enter_phase(OPENING_UPNP);\n \/\/ });\n\n \/\/ enter_phase(HOSTING_INSTANCE);\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::update() {\n\n \/\/ auto register_new_peer = [&](RakNet::RakNetGUID guid){\n \/\/ RakNet::Connection_RM3 *connection = replica_->AllocConnection(peer_->GetSystemAddressFromGuid(guid), guid);\n \/\/ if (replica_->PushConnection(connection) == false) {\n \/\/ replica_->DeallocConnection(connection);\n \/\/ }\n \/\/ };\n\n for (RakNet::Packet* packet=peer_->Receive(); packet; peer_->DeallocatePacket(packet), packet=peer_->Receive()) {\n switch (packet->data[0]) {\n\n \/\/ ##################### BASIC PACKETS ###################################\n \/\/ -----------------------------------------------------------------------\n case ID_CONNECTION_REQUEST_ACCEPTED:\n\n if (phase_ == CONNECTING_TO_NAT_SERVER) {\n\n \/\/ the nat server accepted our connection\n LOG_MESSAGE << \"Connected to NAT server.\" << std::endl;\n nat_server_address_ = packet->systemAddress.ToString();\n peer_->CloseConnection(packet->systemAddress, true);\n\n \/\/ save external ip\n external_id_ = peer_->GetExternalID(RakNet::UNASSIGNED_SYSTEM_ADDRESS).ToString();\n\n \/\/ broadcast on LAN to get internal ip\n peer_->AdvertiseSystem(\"255.255.255.255\", peer_->GetInternalID().GetPort(), 0, 0);\n\n } else if (phase_ == NAT_PUNCH_TO_HOST) {\n\n \/\/ nat punch was successfull, we got a connection!\n phase_ = CONNECTING_TO_HOST;\n request_join(packet->guid.g);\n\n } else if (phase_ == CONNECTING_TO_HOST) {\n request_join(packet->guid.g);\n }\n\n break;\n\n \/\/ -----------------------------------------------------------------------\n case ID_ADVERTISE_SYSTEM:\n if (packet->guid.g == peer_->GetMyGUID().g) {\n \/\/ save internal ip\n internal_id_ = packet->systemAddress.ToString();\n }\n\n break;\n\n \/\/ -----------------------------------------------------------------------\n case ID_DISCONNECTION_NOTIFICATION:\n Logger::LOG_MESSAGE << packet->guid.ToString() << \" disconnected.\" << std::endl;\n break;\n\n \/\/ \/\/ ################ NAT PUNCH THROUGH PACKETS ############################\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_NAT_PUNCHTHROUGH_SUCCEEDED:\n \/\/ if (phase_ == CONNECTING_TO_HOST || phase_ == CONNECTING_TO_PEERS) {\n \/\/ Logger::LOG_MESSAGE << \"NAT punch succeeded. Connecting...\" << std::endl;\n \/\/ connect(packet->systemAddress.ToString(false), packet->systemAddress.GetPort());\n \/\/ }\n \/\/ break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_NAT_PUNCHTHROUGH_FAILED:\n \/\/ Logger::LOG_MESSAGE << \"NAT punch through failed.\" << std::endl;\n \/\/ break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_NAT_TYPE_DETECTION_RESULT: {\n \/\/ auto type = (RakNet::NATTypeDetectionResult) packet->data[1];\n \/\/ Logger::LOG_MESSAGE << \"NAT Type is \" << RakNet::NATTypeDetectionResultToString(type) << \" (\" << RakNet::NATTypeDetectionResultToStringFriendly(type) << \")\" << std::endl;\n\n \/\/ if (USE_UPNP) enter_phase(OPENING_UPNP);\n \/\/ else enter_phase(SEARCHING_FOR_OTHER_INSTANCES);\n \/\/ } break;\n\n \/\/ \/\/ ################## FULLY CONNECTED MESH ###############################\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_NEW_HOST: {\n \/\/ RakNet::BitStream bs(packet->data, packet->length, false);\n \/\/ bs.IgnoreBytes(1);\n \/\/ RakNet::RakNetGUID old_host;\n \/\/ bs.Read(old_host);\n\n \/\/ if (packet->guid.g == peer_->GetMyGUID().g) {\n \/\/ if (phase_ != HOSTING_INSTANCE) {\n \/\/ enter_phase(HOSTING_INSTANCE);\n \/\/ }\n \/\/ } else {\n \/\/ Logger::LOG_MESSAGE << packet->guid.ToString() << \" is host now.\" << std::endl;\n\n\n \/\/ if (old_host != RakNet::UNASSIGNED_RAKNET_GUID) {\n \/\/ Logger::LOG_MESSAGE << \"Old host was \" << old_host.ToString() << std::endl;\n \/\/ } else {\n \/\/ Logger::LOG_MESSAGE << \"There was no host before.\" << std::endl;\n \/\/ }\n \/\/ }\n\n \/\/ if (old_host == RakNet::UNASSIGNED_RAKNET_GUID) {\n \/\/ DataStructures::List<RakNet::RakNetGUID> peers;\n \/\/ mesh_->GetParticipantList(peers);\n \/\/ for (unsigned int i=0; i < peers.Size(); i++) {\n \/\/ register_new_peer(peers[i]);\n \/\/ }\n \/\/ }\n\n \/\/ } break;\n\n \/\/ -----------------------------------------------------------------------\n case (ID_USER_PACKET_ENUM + REQUEST_JOIN):\n Logger::LOG_MESSAGE << \"Got join request from \" << packet->guid.ToString() << \".\" << std::endl;\n start_join(packet->guid.g);\n break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_VERIFIED_JOIN_CAPABLE:\n \/\/ mesh_->RespondOnVerifiedJoinCapable(packet, true, 0);\n \/\/ break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_VERIFIED_JOIN_ACCEPTED: {\n \/\/ DataStructures::List<RakNet::RakNetGUID> peers;\n \/\/ bool this_was_accepted;\n \/\/ mesh_->GetVerifiedJoinAcceptedAdditionalData(packet, &this_was_accepted, peers, 0);\n \/\/ if (this_was_accepted) {\n \/\/ Logger::LOG_MESSAGE << \"Join accepted.\" << std::endl;\n \/\/ } else {\n \/\/ Logger::LOG_MESSAGE << \"Peer \" << peers[0].ToString() << \" joined the game.\" << std::endl;\n \/\/ }\n\n \/\/ if (mesh_->GetConnectedHost() != RakNet::UNASSIGNED_RAKNET_GUID) {\n \/\/ for (unsigned int i=0; i < peers.Size(); i++) {\n \/\/ register_new_peer(peers[i]);\n \/\/ }\n \/\/ }\n\n \/\/ if (this_was_accepted) {\n \/\/ enter_phase(PARTICIPATING);\n \/\/ }\n\n \/\/ } break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_VERIFIED_JOIN_REJECTED:\n \/\/ Logger::LOG_MESSAGE << \"Join rejected.\" << std::endl;\n \/\/ peer_->CloseConnection(packet->guid, true);\n \/\/ break;\n\n \/\/ \/\/ -----------------------------------------------------------------------\n \/\/ case ID_FCM2_VERIFIED_JOIN_FAILED:\n \/\/ Logger::LOG_MESSAGE << \"Join failed.\" << std::endl;\n \/\/ break;\n\n \/\/ -----------------------------------------------------------------------\n case ID_FCM2_VERIFIED_JOIN_START:\n Logger::LOG_MESSAGE << \"Connecting to other peers...\" << std::endl;\n \/\/ enter_phase(CONNECTING_TO_PEERS);\n \/\/ join(packet->guid.g, nat_server_address_);\n break;\n\n \/\/ ##################### OTHER PACKETS ###################################\n \/\/ -----------------------------------------------------------------------\n default:\n LOG_DEBUG << \"Got \" << RakNet::PacketLogger::BaseIDTOString(packet->data[0])\n << \" from \" << packet->guid.ToString() << std::endl;\n break;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::distribute_object(NetworkObjectBase* object) {\n replica_->Reference(object);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Network::is_in_same_network(std::string const& other) const {\n RakNet::SystemAddress o;\n RakNet::SystemAddress self;\n if (o.FromString(other.c_str()) && self.FromString(external_id_.c_str())) {\n if (o.EqualsExcludingPort(self)) {\n return true;\n }\n }\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string const& Network::get_internal_address() const {\n return internal_id_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string const& Network::get_external_address() const {\n return external_id_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Network::is_host() const {\n return mesh_->IsConnectedHost();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::enter_phase(Phase phase) {\n \/\/ phase_ = phase;\n\n \/\/ switch (phase) {\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case CONNECTING_TO_SERVER:\n \/\/ Logger::LOG_MESSAGE << \"Connecting to NAT server...\" << std::endl;\n \/\/ connect(\"natpunch.jenkinssoftware.com\", 61111);\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case OPENING_UPNP:\n \/\/ Logger::LOG_MESSAGE << \"Opening UPNP...\" << std::endl;\n \/\/ \/\/ upnp_.open(peer_);\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case SEARCHING_FOR_OTHER_INSTANCES:\n \/\/ Logger::LOG_MESSAGE << \"Downloading running instances from \"\n \/\/ << \"master server...\" << std::endl;\n \/\/ http_.get(\"masterserver2.raknet.com\/testServer?__gameId=\" + game_ID_,\n \/\/ \"masterserver2.raknet.com\", 80);\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case CONNECTING_TO_HOST:\n \/\/ Logger::LOG_MESSAGE << \"Found running instance. Searching route to host \"\n \/\/ << host_guid_ << \"...\" << std::endl;\n \/\/ open_nat(host_guid_, nat_server_address_);\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case STARTING_NEW_INSTANCE:\n \/\/ Logger::LOG_MESSAGE << \"No running instances found. \"\n \/\/ << \"Starting new instance...\" << std::endl;\n \/\/ mesh_->ResetHostCalculation();\n \/\/ \/\/ register_game();\n \/\/ \/\/ update_timer_.reset();\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case HOSTING_INSTANCE:\n \/\/ Logger::LOG_MESSAGE << \"I'm host now.\" << std::endl;\n \/\/ \/\/ register_game();\n \/\/ \/\/ update_timer_.reset();\n \/\/ break;\n\n \/\/ \/\/ -------------------------------------------------------------------------\n \/\/ case PARTICIPATING:\n \/\/ Logger::LOG_MESSAGE << \"Participating game.\" << std::endl;\n \/\/ break;\n \/\/ }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::request_join(math::uint64 guid) {\n mesh_->ResetHostCalculation();\n\n RakNet::BitStream message;\n message.Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + Network::REQUEST_JOIN));\n peer_->Send(&message, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::RakNetGUID(guid), false);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Network::start_join(math::uint64 guid) {\n mesh_->StartVerifiedJoin(RakNet::RakNetGUID(guid));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ void Network::join(math::uint64 guid, std::string const& nat_server) {\n\/\/ DataStructures::List<RakNet::SystemAddress> addresses;\n\/\/ DataStructures::List<RakNet::RakNetGUID> guids;\n\/\/ DataStructures::List<RakNet::BitStream*> userData;\n\/\/ mesh_->GetVerifiedJoinRequiredProcessingList(RakNet::RakNetGUID(guid), addresses, guids, userData);\n\/\/ for (unsigned int i=0; i < guids.Size(); i++) {\n\/\/ \/\/ if (guids[i].g != get_guid()) {\n\/\/ npt_->OpenNAT(guids[i], RakNet::SystemAddress(nat_server.c_str()));\n\/\/ \/\/ }\n\/\/ }\n\/\/ }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"StableHeaders.h\"\r\n\r\n#include <sstream>\r\n#include <string>\r\n\r\n#include <QApplication>\r\n#include <QWidget>\r\n#include <QPushButton>\r\n#include <QHBoxLayout>\r\n\r\n#ifndef Q_WS_WIN\r\n#include <QX11Info>\r\n#endif\r\n\r\n#include \"Framework.h\"\r\n\r\n#include \"RexQEngine.h\"\r\n\r\nnamespace Foundation\r\n{\r\n\r\nRexQEngine::RexQEngine(Framework *owner)\r\n:owner_(owner)\r\n{\r\n int argc = 0;\r\n app_ = new QApplication(argc, 0);\r\n ogre_host_widget_ = new QWidget();\r\n\r\n ogre_host_widget_->setWindowTitle(\"Ogre3D Window\");\r\n#ifndef Q_WS_WIN \r\n \/\/ At the begin render window and widget should be same size. \r\n ogre_host_widget_->resize(800,600);\r\n \r\n#endif\r\n ogre_host_widget_->show();\r\n}\r\n\r\nRexQEngine::~RexQEngine()\r\n{\r\n delete app_;\r\n app_ = 0;\r\n}\r\n\r\nstd::string RexQEngine::GetMainWindowHandle() const\r\n{\r\n std::stringstream windowHandle;\r\n\r\n#ifndef Q_WS_WIN\r\n \r\n QX11Info info = ogre_host_widget_->x11Info();\r\n windowHandle << (unsigned long)(info.display());\r\n windowHandle << \":\";\r\n windowHandle << static_cast<unsigned int>(info.screen());\r\n windowHandle << \":\";\r\n \r\n \/\/ This which one is used depends that is widget allready created and is show()-method called. \r\n if (ogre_host_widget_->isHidden())\r\n windowHandle << static_cast<unsigned long>(ogre_host_widget_->effectiveWinId());\r\n else\r\n windowHandle << static_cast<unsigned long>(ogre_host_widget_->winId());\r\n\r\n #else\r\n \r\n windowHandle << (size_t)(HWND)ogre_host_widget_->winId();\r\n \r\n#endif\r\n \r\n return windowHandle.str(); \r\n\r\n}\r\n\r\nvoid RexQEngine::UpdateFrame()\r\n{\r\n assert(owner_);\r\n\r\n owner_->ProcessOneFrame();\r\n\r\n \/\/\/ \\todo Compute a new delta time. \\todo Break down update and render.\r\n frame_update_timer_.start(16);\r\n}\r\n\r\nvoid RexQEngine::Go()\r\n{\r\n assert(app_);\r\n\r\n QObject::connect(app_, SIGNAL(aboutToQuit()), this, SLOT(OnQuitQApp()));\r\n\r\n\r\n \/\/ Application frame updates are processed according to the periodic\r\n \/\/ ticks of this timer.\r\n QObject::connect(&frame_update_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrame()));\r\n frame_update_timer_.setSingleShot(true);\r\n frame_update_timer_.start(16);\r\n\r\n app_->exec();\r\n}\r\n\r\nvoid RexQEngine::OnQuitQApp()\r\n{\r\n owner_->Exit();\r\n app_->quit();\r\n}\r\n\r\n}\r\n<commit_msg>Qt timer set to 0 for lots of framerate :)<commit_after>#include \"StableHeaders.h\"\r\n\r\n#include <sstream>\r\n#include <string>\r\n\r\n#include <QApplication>\r\n#include <QWidget>\r\n#include <QPushButton>\r\n#include <QHBoxLayout>\r\n\r\n#ifndef Q_WS_WIN\r\n#include <QX11Info>\r\n#endif\r\n\r\n#include \"Framework.h\"\r\n\r\n#include \"RexQEngine.h\"\r\n\r\nnamespace Foundation\r\n{\r\n\r\nRexQEngine::RexQEngine(Framework *owner)\r\n:owner_(owner)\r\n{\r\n int argc = 0;\r\n app_ = new QApplication(argc, 0);\r\n ogre_host_widget_ = new QWidget();\r\n\r\n ogre_host_widget_->setWindowTitle(\"Ogre3D Window\");\r\n#ifndef Q_WS_WIN \r\n \/\/ At the begin render window and widget should be same size. \r\n ogre_host_widget_->resize(800,600);\r\n \r\n#endif\r\n ogre_host_widget_->show();\r\n}\r\n\r\nRexQEngine::~RexQEngine()\r\n{\r\n delete app_;\r\n app_ = 0;\r\n}\r\n\r\nstd::string RexQEngine::GetMainWindowHandle() const\r\n{\r\n std::stringstream windowHandle;\r\n\r\n#ifndef Q_WS_WIN\r\n \r\n QX11Info info = ogre_host_widget_->x11Info();\r\n windowHandle << (unsigned long)(info.display());\r\n windowHandle << \":\";\r\n windowHandle << static_cast<unsigned int>(info.screen());\r\n windowHandle << \":\";\r\n \r\n \/\/ This which one is used depends that is widget allready created and is show()-method called. \r\n if (ogre_host_widget_->isHidden())\r\n windowHandle << static_cast<unsigned long>(ogre_host_widget_->effectiveWinId());\r\n else\r\n windowHandle << static_cast<unsigned long>(ogre_host_widget_->winId());\r\n\r\n #else\r\n \r\n windowHandle << (size_t)(HWND)ogre_host_widget_->winId();\r\n \r\n#endif\r\n \r\n return windowHandle.str(); \r\n\r\n}\r\n\r\nvoid RexQEngine::UpdateFrame()\r\n{\r\n assert(owner_);\r\n\r\n owner_->ProcessOneFrame();\r\n\r\n \/\/\/ \\todo Compute a new delta time. \\todo Break down update and render.\r\n frame_update_timer_.start(0);\r\n}\r\n\r\nvoid RexQEngine::Go()\r\n{\r\n assert(app_);\r\n\r\n QObject::connect(app_, SIGNAL(aboutToQuit()), this, SLOT(OnQuitQApp()));\r\n\r\n\r\n \/\/ Application frame updates are processed according to the periodic\r\n \/\/ ticks of this timer.\r\n QObject::connect(&frame_update_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrame()));\r\n frame_update_timer_.setSingleShot(true);\r\n frame_update_timer_.start(0);\r\n\r\n app_->exec();\r\n}\r\n\r\nvoid RexQEngine::OnQuitQApp()\r\n{\r\n owner_->Exit();\r\n app_->quit();\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/pivx-config.h\"\n#endif\n\n#include \"consensus\/merkle.h\"\n#include \"primitives\/block.h\"\n#include \"addrman.h\"\n#include \"chain.h\"\n#include \"coins.h\"\n#include \"compressor.h\"\n#include \"net.h\"\n#include \"protocol.h\"\n#include \"streams.h\"\n#include \"undo.h\"\n#include \"version.h\"\n#include \"pubkey.h\"\n\n#include <stdint.h>\n#include <unistd.h>\n\n#include <algorithm>\n#include <vector>\n\nenum TEST_ID {\n CBLOCK_DESERIALIZE=0,\n CTRANSACTION_DESERIALIZE,\n CBLOCKLOCATOR_DESERIALIZE,\n CBLOCKMERKLEROOT,\n CADDRMAN_DESERIALIZE,\n CBLOCKHEADER_DESERIALIZE,\n CBANENTRY_DESERIALIZE,\n CTXUNDO_DESERIALIZE,\n CBLOCKUNDO_DESERIALIZE,\n CCOINS_DESERIALIZE,\n CNETADDR_DESERIALIZE,\n CSERVICE_DESERIALIZE,\n CMESSAGEHEADER_DESERIALIZE,\n CADDRESS_DESERIALIZE,\n CINV_DESERIALIZE,\n CBLOOMFILTER_DESERIALIZE,\n CDISKBLOCKINDEX_DESERIALIZE,\n CTXOUTCOMPRESSOR_DESERIALIZE,\n TEST_ID_END\n};\n\nbool read_stdin(std::vector<uint8_t> &data) {\n uint8_t buffer[1024];\n ssize_t length=0;\n while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {\n data.insert(data.end(), buffer, buffer+length);\n\n if (data.size() > (1<<20)) return false;\n }\n return length==0;\n}\n\nint test_one_input(std::vector<uint8_t> buffer) {\n if (buffer.size() < sizeof(uint32_t)) return 0;\n\n uint32_t test_id = 0xffffffff;\n memcpy(&test_id, &buffer[0], sizeof(uint32_t));\n buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));\n\n if (test_id >= TEST_ID_END) return 0;\n\n CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);\n try {\n int nVersion;\n ds >> nVersion;\n ds.SetVersion(nVersion);\n } catch (const std::ios_base::failure& e) {\n return 0;\n }\n\n switch(test_id) {\n case CBLOCK_DESERIALIZE:\n {\n try\n {\n CBlock block;\n ds >> block;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CTRANSACTION_DESERIALIZE:\n {\n try\n {\n CTransaction tx(deserialize, ds);\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOCKLOCATOR_DESERIALIZE:\n {\n try\n {\n CBlockLocator bl;\n ds >> bl;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOCKMERKLEROOT:\n {\n try\n {\n CBlock block;\n ds >> block;\n bool mutated;\n BlockMerkleRoot(block, &mutated);\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CADDRMAN_DESERIALIZE:\n {\n try\n {\n CAddrMan am;\n ds >> am;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOCKHEADER_DESERIALIZE:\n {\n try\n {\n CBlockHeader bh;\n ds >> bh;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBANENTRY_DESERIALIZE:\n {\n try\n {\n CBanEntry be;\n ds >> be;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CTXUNDO_DESERIALIZE:\n {\n try\n {\n CTxUndo tu;\n ds >> tu;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOCKUNDO_DESERIALIZE:\n {\n try\n {\n CBlockUndo bu;\n ds >> bu;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CCOINS_DESERIALIZE:\n {\n try\n {\n Coin block;\n ds >> block;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CNETADDR_DESERIALIZE:\n {\n try\n {\n CNetAddr na;\n ds >> na;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CSERVICE_DESERIALIZE:\n {\n try\n {\n CService s;\n ds >> s;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CMESSAGEHEADER_DESERIALIZE:\n {\n CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};\n try\n {\n CMessageHeader mh(pchMessageStart);\n ds >> mh;\n if (!mh.IsValid(pchMessageStart)) {return 0;}\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CADDRESS_DESERIALIZE:\n {\n try\n {\n CAddress a;\n ds >> a;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CINV_DESERIALIZE:\n {\n try\n {\n CInv i;\n ds >> i;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOOMFILTER_DESERIALIZE:\n {\n try\n {\n CBloomFilter bf;\n ds >> bf;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CDISKBLOCKINDEX_DESERIALIZE:\n {\n try\n {\n CDiskBlockIndex dbi;\n ds >> dbi;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CTXOUTCOMPRESSOR_DESERIALIZE:\n {\n CTxOut to;\n CTxOutCompressor toc(to);\n try\n {\n ds >> toc;\n } catch (const std::ios_base::failure& e) {return 0;}\n\n break;\n }\n default:\n return 0;\n }\n return 0;\n}\n\nstatic std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;\nvoid initialize() {\n globalVerifyHandle = std::unique_ptr<ECCVerifyHandle>(new ECCVerifyHandle());\n SelectParams(CBaseChainParams::MAIN);\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {\n test_one_input(std::vector<uint8_t>(data, data + size));\n return 0;\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerInitialize(int *argc, char ***argv) {\n initialize();\n return 0;\n}\n\n\/\/ Disabled under WIN32 due to clash with Cygwin's WinMain.\n#ifndef WIN32\n\/\/ Declare main(...) \"weak\" to allow for libFuzzer linking. libFuzzer provides\n\/\/ the main(...) function.\n__attribute__((weak))\n#endif\nint main(int argc, char **argv)\n{\n initialize();\n#ifdef __AFL_INIT\n \/\/ Enable AFL deferred forkserver mode. Requires compilation using\n \/\/ afl-clang-fast++. See fuzzing.md for details.\n __AFL_INIT();\n#endif\n\n#ifdef __AFL_LOOP\n \/\/ Enable AFL persistent mode. Requires compilation using afl-clang-fast++.\n \/\/ See fuzzing.md for details.\n int ret = 0;\n while (__AFL_LOOP(1000)) {\n std::vector<uint8_t> buffer;\n if (!read_stdin(buffer)) {\n continue;\n }\n ret = test_one_input(buffer);\n }\n return ret;\n#else\n std::vector<uint8_t> buffer;\n if (!read_stdin(buffer)) {\n return 0;\n }\n return test_one_input(buffer);\n#endif\n}\n<commit_msg>[test] fuzz: make test_one_input return void<commit_after>\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/pivx-config.h\"\n#endif\n\n#include \"consensus\/merkle.h\"\n#include \"primitives\/block.h\"\n#include \"addrman.h\"\n#include \"chain.h\"\n#include \"coins.h\"\n#include \"compressor.h\"\n#include \"net.h\"\n#include \"protocol.h\"\n#include \"streams.h\"\n#include \"undo.h\"\n#include \"version.h\"\n#include \"pubkey.h\"\n\n#include <stdint.h>\n#include <unistd.h>\n\n#include <algorithm>\n#include <vector>\n\nenum TEST_ID {\n CBLOCK_DESERIALIZE=0,\n CTRANSACTION_DESERIALIZE,\n CBLOCKLOCATOR_DESERIALIZE,\n CBLOCKMERKLEROOT,\n CADDRMAN_DESERIALIZE,\n CBLOCKHEADER_DESERIALIZE,\n CBANENTRY_DESERIALIZE,\n CTXUNDO_DESERIALIZE,\n CBLOCKUNDO_DESERIALIZE,\n CCOINS_DESERIALIZE,\n CNETADDR_DESERIALIZE,\n CSERVICE_DESERIALIZE,\n CMESSAGEHEADER_DESERIALIZE,\n CADDRESS_DESERIALIZE,\n CINV_DESERIALIZE,\n CBLOOMFILTER_DESERIALIZE,\n CDISKBLOCKINDEX_DESERIALIZE,\n CTXOUTCOMPRESSOR_DESERIALIZE,\n TEST_ID_END\n};\n\nstatic bool read_stdin(std::vector<uint8_t>& data)\n{\n uint8_t buffer[1024];\n ssize_t length = 0;\n while ((length = read(STDIN_FILENO, buffer, 1024)) > 0) {\n data.insert(data.end(), buffer, buffer + length);\n\n if (data.size() > (1 << 20)) return false;\n }\n return length == 0;\n}\n\nvoid test_one_input(std::vector<uint8_t> buffer)\n{\n if (buffer.size() < sizeof(uint32_t)) return;\n\n uint32_t test_id = 0xffffffff;\n memcpy(&test_id, &buffer[0], sizeof(uint32_t));\n buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));\n\n if (test_id >= TEST_ID_END) return;\n\n CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);\n try {\n int nVersion;\n ds >> nVersion;\n ds.SetVersion(nVersion);\n } catch (const std::ios_base::failure& e) {\n return;\n }\n\n switch(test_id) {\n case CBLOCK_DESERIALIZE:\n {\n try\n {\n CBlock block;\n ds >> block;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CTRANSACTION_DESERIALIZE:\n {\n try\n {\n CTransaction tx(deserialize, ds);\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOCKLOCATOR_DESERIALIZE:\n {\n try\n {\n CBlockLocator bl;\n ds >> bl;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOCKMERKLEROOT:\n {\n try\n {\n CBlock block;\n ds >> block;\n bool mutated;\n BlockMerkleRoot(block, &mutated);\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CADDRMAN_DESERIALIZE:\n {\n try\n {\n CAddrMan am;\n ds >> am;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOCKHEADER_DESERIALIZE:\n {\n try\n {\n CBlockHeader bh;\n ds >> bh;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBANENTRY_DESERIALIZE:\n {\n try\n {\n CBanEntry be;\n ds >> be;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CTXUNDO_DESERIALIZE:\n {\n try\n {\n CTxUndo tu;\n ds >> tu;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOCKUNDO_DESERIALIZE:\n {\n try\n {\n CBlockUndo bu;\n ds >> bu;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CCOINS_DESERIALIZE:\n {\n try\n {\n Coin coin;\n ds >> coin;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CNETADDR_DESERIALIZE:\n {\n try\n {\n CNetAddr na;\n ds >> na;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CSERVICE_DESERIALIZE:\n {\n try\n {\n CService s;\n ds >> s;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CMESSAGEHEADER_DESERIALIZE:\n {\n CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};\n try\n {\n CMessageHeader mh(pchMessageStart);\n ds >> mh;\n if (!mh.IsValid(pchMessageStart)) {return;}\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CADDRESS_DESERIALIZE:\n {\n try\n {\n CAddress a;\n ds >> a;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CINV_DESERIALIZE:\n {\n try\n {\n CInv i;\n ds >> i;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOOMFILTER_DESERIALIZE:\n {\n try\n {\n CBloomFilter bf;\n ds >> bf;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CDISKBLOCKINDEX_DESERIALIZE:\n {\n try\n {\n CDiskBlockIndex dbi;\n ds >> dbi;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CTXOUTCOMPRESSOR_DESERIALIZE:\n {\n CTxOut to;\n CTxOutCompressor toc(to);\n try\n {\n ds >> toc;\n } catch (const std::ios_base::failure& e) {return;}\n\n break;\n }\n default:\n return;\n }\n return;\n}\n\nstatic std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;\nvoid initialize() {\n globalVerifyHandle = std::unique_ptr<ECCVerifyHandle>(new ECCVerifyHandle());\n SelectParams(CBaseChainParams::MAIN);\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)\n{\n test_one_input(std::vector<uint8_t>(data, data + size));\n return 0;\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerInitialize(int* argc, char*** argv)\n{\n initialize();\n return 0;\n}\n\n\/\/ Disabled under WIN32 due to clash with Cygwin's WinMain.\n#ifndef WIN32\n\/\/ Declare main(...) \"weak\" to allow for libFuzzer linking. libFuzzer provides\n\/\/ the main(...) function.\n__attribute__((weak))\n#endif\nint main(int argc, char **argv)\n{\n initialize();\n#ifdef __AFL_INIT\n \/\/ Enable AFL deferred forkserver mode. Requires compilation using\n \/\/ afl-clang-fast++. See fuzzing.md for details.\n __AFL_INIT();\n#endif\n\n#ifdef __AFL_LOOP\n \/\/ Enable AFL persistent mode. Requires compilation using afl-clang-fast++.\n \/\/ See fuzzing.md for details.\n while (__AFL_LOOP(1000)) {\n std::vector<uint8_t> buffer;\n if (!read_stdin(buffer)) {\n continue;\n }\n test_one_input(buffer);\n }\n#else\n std::vector<uint8_t> buffer;\n if (!read_stdin(buffer)) {\n return 0;\n }\n test_one_input(buffer);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/CssTokenizer.h\"\n#include \"gtest\/gtest.h\"\n\n\/**\n * Test if the tokenizer reckognizes the tokens in the input string.\n *\/\nTEST(CssTokenizerTest, ReckognizesTokens) {\n istringstream in(\"identifier @atkeyword #hash 1234 100% 1.5em : ; { } ( ) [ ] \/* comment *\/ function( ~= |= ~ \");\n \n CssTokenizer t(&in);\n EXPECT_EQ(Token::IDENTIFIER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::ATKEYWORD, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::HASH, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::NUMBER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::PERCENTAGE, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::DIMENSION, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::COLON, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::DELIMITER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::BRACKET_OPEN, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::BRACKET_CLOSED, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::PAREN_OPEN, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::PAREN_CLOSED, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::BRACE_OPEN, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::BRACE_CLOSED, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::COMMENT, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::FUNCTION, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::INCLUDES, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::DASHMATCH, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::EOS, t.readNextToken());\n}\n\n\/**\n * Test strings quoted with double quotes, single quotes, strings\n * containing newlines, and strings containing unicode characters.\n *\/\nTEST(CssTokenizerTest, String) {\n istringstream in(\"\\\"string\\\" 'string' 'string\\\\\\nstring' '\\\\12EF'\"),\n inBad1(\"'string\\n'\"),\n inBad2(\"'string\"),\n newlines(\"'\\\\\\n \\\\\\r\\n \\\\\\r'\");\n\n CssTokenizer t(&in), tBad1(&inBad1), tBad2(&inBad2),\n tNewlines(&newlines);\n\n EXPECT_EQ(Token::STRING, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::STRING, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::STRING, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::STRING, t.readNextToken());\n\n EXPECT_THROW(tBad1.readNextToken(), ParseException*);\n EXPECT_THROW(tBad2.readNextToken(), ParseException*);\n\n ASSERT_EQ(Token::STRING, tNewlines.readNextToken());\n EXPECT_STREQ(\"'\\\\\\n \\\\\\r\\n \\\\\\r'\", tNewlines.getToken()->str.c_str());\n}\n\nTEST(CssTokenizerTest, URL) {\n istringstream in(\"url(..\/img\/img.png) url('http:\/\/example.com\/image.jpg')\");\n\n CssTokenizer t(&in);\n EXPECT_EQ(Token::URL, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::URL, t.readNextToken());\n}\n\nTEST(CssTokenizerTest, UnicodeRange) {\n istringstream in(\"u+123 u+123DEF-123\");\n CssTokenizer t(&in);\n EXPECT_EQ(Token::UNICODE_RANGE, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::UNICODE_RANGE, t.readNextToken());\n}\n\nTEST(CssTokenizerTest, NonAscii) {\n istringstream in(\"a\\xEE€\");\n CssTokenizer t(&in);\n EXPECT_EQ(Token::IDENTIFIER, t.readNextToken());\n EXPECT_STREQ(\"a\\xEE€\", t.getToken()->str.c_str());\n}\n\nTEST(CssTokenizerTest, Minus) {\n istringstream in(\"-10 -50% -5em -identifier -moz-border-radius( -\");\n CssTokenizer t(&in);\n EXPECT_EQ(Token::NUMBER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::PERCENTAGE, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::DIMENSION, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::IDENTIFIER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::FUNCTION, t.readNextToken());\n}\n<commit_msg>Added test case to CssTokenizer unit test checking if tokens of type Token::OTHER are reckognized.<commit_after>#include \"..\/CssTokenizer.h\"\n#include \"gtest\/gtest.h\"\n\n\/**\n * Test if the tokenizer reckognizes the tokens in the input string.\n *\/\nTEST(CssTokenizerTest, ReckognizesTokens) {\n istringstream in(\"identifier @atkeyword #hash 1234 100% 1.5em : ; { } ( ) [ ] \/* comment *\/ function( ~= |= ~ \");\n \n CssTokenizer t(&in);\n EXPECT_EQ(Token::IDENTIFIER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::ATKEYWORD, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::HASH, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::NUMBER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::PERCENTAGE, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::DIMENSION, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::COLON, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::DELIMITER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::BRACKET_OPEN, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::BRACKET_CLOSED, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::PAREN_OPEN, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::PAREN_CLOSED, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::BRACE_OPEN, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::BRACE_CLOSED, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::COMMENT, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::FUNCTION, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::INCLUDES, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::DASHMATCH, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::EOS, t.readNextToken());\n}\n\n\/**\n * Test strings quoted with double quotes, single quotes, strings\n * containing newlines, and strings containing unicode characters.\n *\/\nTEST(CssTokenizerTest, String) {\n istringstream in(\"\\\"string\\\" 'string' 'string\\\\\\nstring' '\\\\12EF'\"),\n inBad1(\"'string\\n'\"),\n inBad2(\"'string\"),\n newlines(\"'\\\\\\n \\\\\\r\\n \\\\\\r'\");\n\n CssTokenizer t(&in), tBad1(&inBad1), tBad2(&inBad2),\n tNewlines(&newlines);\n\n EXPECT_EQ(Token::STRING, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::STRING, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::STRING, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::STRING, t.readNextToken());\n\n EXPECT_THROW(tBad1.readNextToken(), ParseException*);\n EXPECT_THROW(tBad2.readNextToken(), ParseException*);\n\n ASSERT_EQ(Token::STRING, tNewlines.readNextToken());\n EXPECT_STREQ(\"'\\\\\\n \\\\\\r\\n \\\\\\r'\", tNewlines.getToken()->str.c_str());\n}\n\nTEST(CssTokenizerTest, URL) {\n istringstream in(\"url(..\/img\/img.png) url('http:\/\/example.com\/image.jpg')\");\n\n CssTokenizer t(&in);\n EXPECT_EQ(Token::URL, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::URL, t.readNextToken());\n}\n\nTEST(CssTokenizerTest, UnicodeRange) {\n istringstream in(\"u+123 u+123DEF-123\");\n CssTokenizer t(&in);\n EXPECT_EQ(Token::UNICODE_RANGE, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::UNICODE_RANGE, t.readNextToken());\n}\n\nTEST(CssTokenizerTest, NonAscii) {\n istringstream in(\"a\\xEE€\");\n CssTokenizer t(&in);\n EXPECT_EQ(Token::IDENTIFIER, t.readNextToken());\n EXPECT_STREQ(\"a\\xEE€\", t.getToken()->str.c_str());\n}\n\nTEST(CssTokenizerTest, Minus) {\n istringstream in(\"-10 -50% -5em -identifier -moz-border-radius( -\");\n CssTokenizer t(&in);\n EXPECT_EQ(Token::NUMBER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::PERCENTAGE, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::DIMENSION, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::IDENTIFIER, t.readNextToken());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::FUNCTION, t.readNextToken());\n}\nTEST(CssTokenizerTest, Other) {\n istringstream in(\"@ - ~ | \/ + =\");\n CssTokenizer t(&in);\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_STREQ(\"@\", t.getToken()->str.c_str());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_STREQ(\"-\", t.getToken()->str.c_str());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_STREQ(\"~\", t.getToken()->str.c_str());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_STREQ(\"|\", t.getToken()->str.c_str());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_STREQ(\"\/\", t.getToken()->str.c_str());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_STREQ(\"+\", t.getToken()->str.c_str());\n EXPECT_EQ(Token::WHITESPACE, t.readNextToken());\n EXPECT_EQ(Token::OTHER, t.readNextToken());\n EXPECT_STREQ(\"=\", t.getToken()->str.c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n* *\n* Author: The ALICE Off-line Project. *\n* Contributors are mentioned in the code where appropriate. *\n* *\n* Permission to use, copy, modify and distribute this software and its *\n* documentation strictly for non-commercial purposes is hereby granted *\n* without fee, provided that the above copyright notice appears in all *\n* copies and that both the copyright notice and this permission notice *\n* appear in the supporting documentation. The authors make no claims *\n* about the suitability of this software for any purpose. It is *\n* provided \"as is\" without express or implied warranty. *\n**************************************************************************\/\n\n\/\/ $Id$\n\/\/ $MpId: AliMpSlatSegmentation.cxx,v 1.4 2005\/09\/19 19:01:31 ivana Exp $\n\n#include \"AliMpSlatSegmentation.h\"\n\n#include \"AliLog.h\"\n#include \"AliMpConnection.h\"\n#include \"AliMpMotif.h\"\n#include \"AliMpMotifPosition.h\"\n#include \"AliMpMotifType.h\"\n#include \"AliMpPCB.h\"\n#include \"AliMpSlat.h\"\n#include \"AliMpSlatPadIterator.h\"\n\nClassImp(AliMpSlatSegmentation)\n\n\/\/_____________________________________________________________________________\nAliMpSlatSegmentation::AliMpSlatSegmentation() \n: AliMpVSegmentation(),\nfkSlat(0)\n{\n \/\/\n \/\/ Default ctor. Not to be used really.\n \/\/\n AliDebug(1,Form(\"this=%p Empty ctor\",this));\n}\n\n\/\/_____________________________________________________________________________\nAliMpSlatSegmentation::AliMpSlatSegmentation(const AliMpSlat* slat) \n: AliMpVSegmentation(), \nfkSlat(slat)\n{\n \/\/\n \/\/ Normal ctor.\n \/\/\n AliDebug(1,Form(\"this=%p Normal ctor slat=%p\",this,slat));\n}\n\n\/\/_____________________________________________________________________________\nAliMpSlatSegmentation::~AliMpSlatSegmentation()\n{\n \/\/\n \/\/ Dtor (empty).\n \/\/\n Int_t i(0);\/\/just to be able to put a breakpoint in gdb\n AliDebug(1,Form(\"this=%p\",this));\t\t\t\n}\n\n\/\/_____________________________________________________________________________\nAliMpVPadIterator*\nAliMpSlatSegmentation::CreateIterator(const AliMpArea& area) const\n{\n \/\/\n \/\/ Returns an iterator to loop over the pad contained within given area.\n \/\/\n \n return new AliMpSlatPadIterator(fkSlat,area);\n}\n\n\/\/_____________________________________________________________________________\nconst char*\nAliMpSlatSegmentation::GetName() const\n{\n TString name(\"SlatSegmentation\");\n if ( fkSlat) \n {\n name += \".\";\n name += fkSlat->GetName();\n }\n return name.Data();\n}\n\n\/\/_____________________________________________________________________________\nBool_t\nAliMpSlatSegmentation::HasPad(const AliMpIntPair& indices) const\n{\n \/\/\n \/\/ Test if this slat has a pad located at the position referenced\n \/\/ by the integer indices.\n \/\/\n \n return PadByIndices(indices,kFALSE) != AliMpPad::Invalid();\n}\n\n\/\/_____________________________________________________________________________\nInt_t \nAliMpSlatSegmentation::MaxPadIndexX()\n{\n \/\/\n \/\/ Returns the value of the largest pad index in x-direction.\n \/\/\n \n return fkSlat->GetMaxPadIndexX();\n}\n\n\/\/_____________________________________________________________________________\nInt_t \nAliMpSlatSegmentation::MaxPadIndexY()\n{\n \/\/\n \/\/ Returns the value of the largest pad index in y-direction.\n \/\/\n \n return fkSlat->GetMaxNofPadsY()-1;\n}\n\n\/\/_____________________________________________________________________________\nAliMpPad\nAliMpSlatSegmentation::PadByLocation(const AliMpIntPair& location, \n Bool_t warning) const\n{\n \/\/\n \/\/ Returns the pad specified by its location, where location is the \n \/\/ pair (ManuID,ManuChannel).\n \/\/ If warning=kTRUE and the pad does not exist, a warning message is \n \/\/ printed.\n \/\/\n \/\/ AliMpPad::Invalid() is returned if there's no pad at the given location.\n \/\/\n Int_t manuID = location.GetFirst();\n\t\n AliMpMotifPosition* motifPos = fkSlat->FindMotifPosition(manuID);\n\t\n if (!motifPos)\n\t{\n\t\tif (warning)\n\t\t{\n\t\t\tAliWarning(Form(\"Manu ID %d not found in slat %s\",\n\t\t\t manuID, fkSlat->GetID()));\n }\n return AliMpPad::Invalid();\n\t}\n AliMpVMotif* motif = motifPos->GetMotif();\n AliMpIntPair localIndices = \n motif->GetMotifType()->FindLocalIndicesByGassiNum(location.GetSecond());\n\t\n if (!localIndices.IsValid()) \n\t{\n\t\tif (warning) \n\t\t{\n\t\t\tAliWarning(Form(\"The pad number %d doesn't exists\",\n\t\t\t location.GetSecond()));\n\t\t}\n\t\treturn AliMpPad::Invalid();\n\t}\n\t\n return AliMpPad(location,\n motifPos->GlobalIndices(localIndices),\n motifPos->Position() \n + motif->PadPositionLocal(localIndices) \n - fkSlat->Position(),\n motif->GetPadDimensions(localIndices)); \n}\n\n\/\/_____________________________________________________________________________\nAliMpPad\nAliMpSlatSegmentation::PadByIndices(const AliMpIntPair& indices, \n Bool_t warning) const\n{\n \/\/\n \/\/ Returns the pad specified by its integer indices.\n \/\/ If warning=kTRUE and the pad does not exist, a warning message is \n \/\/ printed.\n \/\/\n \/\/ AliMpPad::Invalid() is returned if there's no pad at the given location.\n \/\/\n \/\/ \n \/\/ FIXME: except for the FindMotifPosition below, this method\n \/\/ is exactly as the one in AliMpSectorSegmentation.\n \/\/ See if we can merge them somehow.\n\t\n AliMpMotifPosition* motifPos = fkSlat->FindMotifPosition(indices.GetFirst(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t indices.GetSecond());\n if (!motifPos)\n\t{\n\t\tif ( warning ) \n\t\t{\n\t\t\tAliWarning(Form(\"No motif found containing pad location (%d,%d)\",\n\t\t\t indices.GetFirst(),indices.GetSecond()));\t \n\t\t}\n\t\treturn AliMpPad::Invalid();\n\t}\n\t\n AliMpVMotif* motif = motifPos->GetMotif();\n AliMpMotifType* motifType = motif->GetMotifType();\n AliMpIntPair localIndices(indices-motifPos->GetLowIndicesLimit());\n AliMpConnection* connection = motifType->FindConnectionByLocalIndices(localIndices);\n \n if (!connection)\n\t{\n\t\tif ( warning )\n\t\t{\n\t\t\tAliWarning(Form(\"No connection for pad location (%d,%d)\",\n\t\t\t indices.GetFirst(),indices.GetSecond()));\n }\n return AliMpPad::Invalid();\n\t}\n\t\n return AliMpPad(AliMpIntPair(motifPos->GetID(),connection->GetGassiNum()),\n indices,\n motifPos->Position()\n + motif->PadPositionLocal(localIndices)\n - fkSlat->Position(),\n motif->GetPadDimensions(localIndices));\n}\n\n\/\/_____________________________________________________________________________\nAliMpPad\nAliMpSlatSegmentation::PadByPosition(const TVector2& position, \n Bool_t warning) const\n{\n \/\/\n \/\/ Returns the pad specified by its (floating point) position.\n \/\/ If warning=kTRUE and the pad does not exist, a warning message is \n \/\/ printed.\n \/\/\n \/\/ AliMpPad::Invalid() is returned if there's no pad at the given location.\n \/\/\n \n AliMpMotifPosition* motifPos = fkSlat->FindMotifPosition(position.X(),position.Y());\n\t\n if (!motifPos)\n\t{\n\t\tif (warning) \n\t\t{\n\t\t\tAliWarning(Form(\"Slat %s Position (%e,%e) mm outside limits\",\n fkSlat->GetID(),position.X(),position.Y()));\n\t\t}\n\t\treturn AliMpPad::Invalid();\n\t}\n\t\n AliMpVMotif* motif = motifPos->GetMotif(); \n AliMpIntPair localIndices \n = motif->PadIndicesLocal(position-motifPos->Position());\n\t\n AliMpConnection* connect = \n motif->GetMotifType()->FindConnectionByLocalIndices(localIndices);\n\t\n if (!connect)\n\t{\n\t\tif (warning) \n\t\t{\n\t\t\tAliWarning(Form(\"Slat %s localIndices (%d,%d) outside motif %s limits\",\n fkSlat->GetID(),localIndices.GetFirst(),\n localIndices.GetSecond(),motif->GetID().Data()));\n\t\t}\n\t\treturn AliMpPad::Invalid();\n\t}\n \n return AliMpPad(AliMpIntPair(motifPos->GetID(),connect->GetGassiNum()),\n motifPos->GlobalIndices(localIndices),\n motifPos->Position()\n + motif->PadPositionLocal(localIndices)\n - fkSlat->Position(),\n motif->GetPadDimensions(localIndices)); \n}\n\n\/\/_____________________________________________________________________________\nconst AliMpSlat* \nAliMpSlatSegmentation::Slat() const\n{\n \/\/\n \/\/ Returns the pointer to the referenced slat.\n \/\/\n \n return fkSlat;\n}\n<commit_msg>Commented out declaration of unused variable (causing compiler warning)<commit_after>\/**************************************************************************\n* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n* *\n* Author: The ALICE Off-line Project. *\n* Contributors are mentioned in the code where appropriate. *\n* *\n* Permission to use, copy, modify and distribute this software and its *\n* documentation strictly for non-commercial purposes is hereby granted *\n* without fee, provided that the above copyright notice appears in all *\n* copies and that both the copyright notice and this permission notice *\n* appear in the supporting documentation. The authors make no claims *\n* about the suitability of this software for any purpose. It is *\n* provided \"as is\" without express or implied warranty. *\n**************************************************************************\/\n\n\/\/ $Id$\n\/\/ $MpId: AliMpSlatSegmentation.cxx,v 1.5 2005\/10\/28 15:26:01 ivana Exp $\n\n#include \"AliMpSlatSegmentation.h\"\n\n#include \"AliLog.h\"\n#include \"AliMpConnection.h\"\n#include \"AliMpMotif.h\"\n#include \"AliMpMotifPosition.h\"\n#include \"AliMpMotifType.h\"\n#include \"AliMpPCB.h\"\n#include \"AliMpSlat.h\"\n#include \"AliMpSlatPadIterator.h\"\n\nClassImp(AliMpSlatSegmentation)\n\n\/\/_____________________________________________________________________________\nAliMpSlatSegmentation::AliMpSlatSegmentation() \n: AliMpVSegmentation(),\nfkSlat(0)\n{\n \/\/\n \/\/ Default ctor. Not to be used really.\n \/\/\n AliDebug(1,Form(\"this=%p Empty ctor\",this));\n}\n\n\/\/_____________________________________________________________________________\nAliMpSlatSegmentation::AliMpSlatSegmentation(const AliMpSlat* slat) \n: AliMpVSegmentation(), \nfkSlat(slat)\n{\n \/\/\n \/\/ Normal ctor.\n \/\/\n AliDebug(1,Form(\"this=%p Normal ctor slat=%p\",this,slat));\n}\n\n\/\/_____________________________________________________________________________\nAliMpSlatSegmentation::~AliMpSlatSegmentation()\n{\n \/\/\n \/\/ Dtor (empty).\n \/\/\n \/\/ Int_t i(0);\/\/just to be able to put a breakpoint in gdb\n AliDebug(1,Form(\"this=%p\",this));\t\t\t\n}\n\n\/\/_____________________________________________________________________________\nAliMpVPadIterator*\nAliMpSlatSegmentation::CreateIterator(const AliMpArea& area) const\n{\n \/\/\n \/\/ Returns an iterator to loop over the pad contained within given area.\n \/\/\n \n return new AliMpSlatPadIterator(fkSlat,area);\n}\n\n\/\/_____________________________________________________________________________\nconst char*\nAliMpSlatSegmentation::GetName() const\n{\n TString name(\"SlatSegmentation\");\n if ( fkSlat) \n {\n name += \".\";\n name += fkSlat->GetName();\n }\n return name.Data();\n}\n\n\/\/_____________________________________________________________________________\nBool_t\nAliMpSlatSegmentation::HasPad(const AliMpIntPair& indices) const\n{\n \/\/\n \/\/ Test if this slat has a pad located at the position referenced\n \/\/ by the integer indices.\n \/\/\n \n return PadByIndices(indices,kFALSE) != AliMpPad::Invalid();\n}\n\n\/\/_____________________________________________________________________________\nInt_t \nAliMpSlatSegmentation::MaxPadIndexX()\n{\n \/\/\n \/\/ Returns the value of the largest pad index in x-direction.\n \/\/\n \n return fkSlat->GetMaxPadIndexX();\n}\n\n\/\/_____________________________________________________________________________\nInt_t \nAliMpSlatSegmentation::MaxPadIndexY()\n{\n \/\/\n \/\/ Returns the value of the largest pad index in y-direction.\n \/\/\n \n return fkSlat->GetMaxNofPadsY()-1;\n}\n\n\/\/_____________________________________________________________________________\nAliMpPad\nAliMpSlatSegmentation::PadByLocation(const AliMpIntPair& location, \n Bool_t warning) const\n{\n \/\/\n \/\/ Returns the pad specified by its location, where location is the \n \/\/ pair (ManuID,ManuChannel).\n \/\/ If warning=kTRUE and the pad does not exist, a warning message is \n \/\/ printed.\n \/\/\n \/\/ AliMpPad::Invalid() is returned if there's no pad at the given location.\n \/\/\n Int_t manuID = location.GetFirst();\n\t\n AliMpMotifPosition* motifPos = fkSlat->FindMotifPosition(manuID);\n\t\n if (!motifPos)\n\t{\n\t\tif (warning)\n\t\t{\n\t\t\tAliWarning(Form(\"Manu ID %d not found in slat %s\",\n\t\t\t manuID, fkSlat->GetID()));\n }\n return AliMpPad::Invalid();\n\t}\n AliMpVMotif* motif = motifPos->GetMotif();\n AliMpIntPair localIndices = \n motif->GetMotifType()->FindLocalIndicesByGassiNum(location.GetSecond());\n\t\n if (!localIndices.IsValid()) \n\t{\n\t\tif (warning) \n\t\t{\n\t\t\tAliWarning(Form(\"The pad number %d doesn't exists\",\n\t\t\t location.GetSecond()));\n\t\t}\n\t\treturn AliMpPad::Invalid();\n\t}\n\t\n return AliMpPad(location,\n motifPos->GlobalIndices(localIndices),\n motifPos->Position() \n + motif->PadPositionLocal(localIndices) \n - fkSlat->Position(),\n motif->GetPadDimensions(localIndices)); \n}\n\n\/\/_____________________________________________________________________________\nAliMpPad\nAliMpSlatSegmentation::PadByIndices(const AliMpIntPair& indices, \n Bool_t warning) const\n{\n \/\/\n \/\/ Returns the pad specified by its integer indices.\n \/\/ If warning=kTRUE and the pad does not exist, a warning message is \n \/\/ printed.\n \/\/\n \/\/ AliMpPad::Invalid() is returned if there's no pad at the given location.\n \/\/\n \/\/ \n \/\/ FIXME: except for the FindMotifPosition below, this method\n \/\/ is exactly as the one in AliMpSectorSegmentation.\n \/\/ See if we can merge them somehow.\n\t\n AliMpMotifPosition* motifPos = fkSlat->FindMotifPosition(indices.GetFirst(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t indices.GetSecond());\n if (!motifPos)\n\t{\n\t\tif ( warning ) \n\t\t{\n\t\t\tAliWarning(Form(\"No motif found containing pad location (%d,%d)\",\n\t\t\t indices.GetFirst(),indices.GetSecond()));\t \n\t\t}\n\t\treturn AliMpPad::Invalid();\n\t}\n\t\n AliMpVMotif* motif = motifPos->GetMotif();\n AliMpMotifType* motifType = motif->GetMotifType();\n AliMpIntPair localIndices(indices-motifPos->GetLowIndicesLimit());\n AliMpConnection* connection = motifType->FindConnectionByLocalIndices(localIndices);\n \n if (!connection)\n\t{\n\t\tif ( warning )\n\t\t{\n\t\t\tAliWarning(Form(\"No connection for pad location (%d,%d)\",\n\t\t\t indices.GetFirst(),indices.GetSecond()));\n }\n return AliMpPad::Invalid();\n\t}\n\t\n return AliMpPad(AliMpIntPair(motifPos->GetID(),connection->GetGassiNum()),\n indices,\n motifPos->Position()\n + motif->PadPositionLocal(localIndices)\n - fkSlat->Position(),\n motif->GetPadDimensions(localIndices));\n}\n\n\/\/_____________________________________________________________________________\nAliMpPad\nAliMpSlatSegmentation::PadByPosition(const TVector2& position, \n Bool_t warning) const\n{\n \/\/\n \/\/ Returns the pad specified by its (floating point) position.\n \/\/ If warning=kTRUE and the pad does not exist, a warning message is \n \/\/ printed.\n \/\/\n \/\/ AliMpPad::Invalid() is returned if there's no pad at the given location.\n \/\/\n \n AliMpMotifPosition* motifPos = fkSlat->FindMotifPosition(position.X(),position.Y());\n\t\n if (!motifPos)\n\t{\n\t\tif (warning) \n\t\t{\n\t\t\tAliWarning(Form(\"Slat %s Position (%e,%e) mm outside limits\",\n fkSlat->GetID(),position.X(),position.Y()));\n\t\t}\n\t\treturn AliMpPad::Invalid();\n\t}\n\t\n AliMpVMotif* motif = motifPos->GetMotif(); \n AliMpIntPair localIndices \n = motif->PadIndicesLocal(position-motifPos->Position());\n\t\n AliMpConnection* connect = \n motif->GetMotifType()->FindConnectionByLocalIndices(localIndices);\n\t\n if (!connect)\n\t{\n\t\tif (warning) \n\t\t{\n\t\t\tAliWarning(Form(\"Slat %s localIndices (%d,%d) outside motif %s limits\",\n fkSlat->GetID(),localIndices.GetFirst(),\n localIndices.GetSecond(),motif->GetID().Data()));\n\t\t}\n\t\treturn AliMpPad::Invalid();\n\t}\n \n return AliMpPad(AliMpIntPair(motifPos->GetID(),connect->GetGassiNum()),\n motifPos->GlobalIndices(localIndices),\n motifPos->Position()\n + motif->PadPositionLocal(localIndices)\n - fkSlat->Position(),\n motif->GetPadDimensions(localIndices)); \n}\n\n\/\/_____________________________________________________________________________\nconst AliMpSlat* \nAliMpSlatSegmentation::Slat() const\n{\n \/\/\n \/\/ Returns the pointer to the referenced slat.\n \/\/\n \n return fkSlat;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Library\n Module: Object.hh\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its \ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n\/\/ .NAME vlObject - abstract base class for visualization library\n\/\/ .SECTION Description\n\/\/ vlObject is the base class for many objects in the visualization \n\/\/ library. vlObject provides methods for tracking modification time, \n\/\/ debugging, and printing.\n\n#ifndef __vlObject_hh\n#define __vlObject_hh\n\n#include <iostream.h>\n#include \"TimeSt.hh\"\n#include \"SetGet.hh\"\n#include \"Indent.hh\"\n\nclass vlObject \n{\npublic:\n vlObject();\n virtual ~vlObject();\n virtual char *GetClassName() {return \"vlObject\";};\n\n \/\/ debugging\n void DebugOn();\n void DebugOff();\n int GetDebug();\n\n \/\/ modified time\n virtual unsigned long int GetMTime();\n virtual void Modified();\n\n \/\/ printing\n virtual void PrintSelf(ostream& os, vlIndent indent);\n void Print(ostream& os);\n virtual void PrintHeader(ostream& os, vlIndent indent);\n virtual void PrintTrailer(ostream& os, vlIndent indent);\n\nprotected:\n int Debug; \/\/ Enable debug messages\n vlTimeStamp MTime; \/\/ Keep track of modification time\n\nprivate:\n friend ostream& operator<<(ostream& os, vlObject& o);\n};\n\n\/\/ Description:\n\/\/ Update the modification time for this object.\ninline void vlObject::Modified()\n{\n this->MTime.Modified();\n}\n\n#endif\n\n<commit_msg>ENH: Multiple inheritance tweaks (with debug)<commit_after>\/*=========================================================================\n\n Program: Visualization Library\n Module: Object.hh\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its \ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n\/\/ .NAME vlObject - abstract base class for visualization library\n\/\/ .SECTION Description\n\/\/ vlObject is the base class for many objects in the visualization \n\/\/ library. vlObject provides methods for tracking modification time, \n\/\/ debugging, and printing.\n\n#ifndef __vlObject_hh\n#define __vlObject_hh\n\n#include <iostream.h>\n#include \"TimeSt.hh\"\n#include \"SetGet.hh\"\n#include \"Indent.hh\"\n\nclass vlObject \n{\npublic:\n vlObject();\n virtual ~vlObject();\n virtual char *GetClassName() {return \"vlObject\";};\n\n \/\/ debugging\n virtual void DebugOn();\n virtual void DebugOff();\n int GetDebug();\n\n \/\/ modified time\n virtual unsigned long int GetMTime();\n virtual void Modified();\n\n \/\/ printing\n virtual void PrintSelf(ostream& os, vlIndent indent);\n void Print(ostream& os);\n virtual void PrintHeader(ostream& os, vlIndent indent);\n virtual void PrintTrailer(ostream& os, vlIndent indent);\n\nprotected:\n int Debug; \/\/ Enable debug messages\n vlTimeStamp MTime; \/\/ Keep track of modification time\n\nprivate:\n friend ostream& operator<<(ostream& os, vlObject& o);\n};\n\n\/\/ Description:\n\/\/ Update the modification time for this object.\ninline void vlObject::Modified()\n{\n this->MTime.Modified();\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Video.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 18\/03\/2021.\n\/\/ Copyright © 2021 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Video_hpp\n#define Video_hpp\n\n#include \"..\/..\/..\/Outputs\/CRT\/CRT.hpp\"\n#include \"..\/..\/..\/ClockReceiver\/ClockReceiver.hpp\"\n\n#include <algorithm>\n\nnamespace Sinclair {\nnamespace ZXSpectrum {\n\nenum class VideoTiming {\n\tPlus3\n};\n\n\/*\n\tTiming notes:\n\n\tAs of the +2a\/+3:\n\n\t\t311 lines, 228 cycles\/line\n\t\tDelays begin at 14361, follow the pattern 1, 0, 7, 6, 5, 4, 3, 2; run for 129 cycles\/line.\n\t\tPossibly delays only affect actual reads and writes; documentation is unclear.\n\n\tUnknowns, to me, presently:\n\n\t\tHow long the interrupt line held for.\n\n\tSo...\n\n\t\tProbably two bytes of video and attribute are fetched in each 8-cycle block,\n\t\twith 16 such blocks therefore providing the whole visible display, an island\n\t\twithin 28.5 blocks horizontally.\n\n\t\t14364 is 228*63, so I I guess almost 63 lines run from the start of vertical\n\t\tblank through to the top of the display, implying 56 lines on to vertical blank.\n\n*\/\n\ntemplate <VideoTiming timing> class Video {\n\tprivate:\n\t\tstruct Timings {\n\t\t\tint cycles_per_line;\n\t\t\tint lines_per_frame;\n\t\t\tint first_delay;\n\t\t\tint contended_period;\n\t\t\tint first_fetch;\n\t\t\tint delays[16];\n\t\t};\n\n\t\tstatic constexpr Timings get_timings() {\n\t\t\tconstexpr Timings result = {\n\t\t\t\t.cycles_per_line = 228 * 2,\n\t\t\t\t.lines_per_frame = 311,\n\t\t\t\t.first_delay = 14361 * 2,\n\t\t\t\t.contended_period = (14490 - 14361) * 2,\n\t\t\t\t.first_fetch = 14364 * 2,\t\/\/ TODO: find a source for this, a guess.\n\t\t\t\t.delays = {\n\t\t\t\t\t2, 1,\n\t\t\t\t\t0, 0,\n\t\t\t\t\t14, 13,\n\t\t\t\t\t12, 11,\n\t\t\t\t\t10, 9,\n\t\t\t\t\t8, 7,\n\t\t\t\t\t6, 5,\n\t\t\t\t\t4, 3,\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn result;\n\t\t}\n\n\tpublic:\n\t\tvoid run_for(HalfCycles duration) {\n\t\t\tconstexpr auto timings = get_timings();\n\t\t\tconstexpr int first_line = timings.first_fetch \/ timings.cycles_per_line;\n\t\t\tconstexpr int sync_position = 166 * 2;\n\t\t\tconstexpr int sync_length = 17 * 2;\n\t\t\tconstexpr int burst_position = sync_position + 40;\n\t\t\tconstexpr int burst_length = 17;\n\n\t\t\tint cycles_remaining = duration.as<int>();\n\t\t\twhile(cycles_remaining) {\n\t\t\t\tint line = time_since_interrupt_ \/ timings.cycles_per_line;\n\t\t\t\tint offset = time_since_interrupt_ % timings.cycles_per_line;\n\t\t\t\tconst int cycles_this_line = std::min(cycles_remaining, timings.cycles_per_line - offset);\n\t\t\t\tconst int end_offset = offset + cycles_this_line;\n\n\t\t\t\tif(!offset) {\n\t\t\t\t\tis_alternate_line_ ^= true;\n\n\t\t\t\t\tif(!line) {\n\t\t\t\t\t\tflash_counter_ = (flash_counter_ + 1) & 31;\n\t\t\t\t\t\tflash_mask_ = uint8_t(flash_counter_ >> 4);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(line < 3) {\n\t\t\t\t\t\/\/ Output sync line.\n\t\t\t\t\tcrt_.output_sync(cycles_this_line);\n\t\t\t\t} else {\n\t\t\t\t\tif((line < first_line) || (line >= first_line+192)) {\n\t\t\t\t\t\t\/\/ Output plain border line.\n\t\t\t\t\t\tif(offset < sync_position) {\n\t\t\t\t\t\t\tconst int border_duration = std::min(sync_position, end_offset) - offset;\n\t\t\t\t\t\t\toutput_border(border_duration);\n\t\t\t\t\t\t\toffset += border_duration;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ Output pixel line.\n\t\t\t\t\t\tif(offset < 256) {\n\t\t\t\t\t\t\tconst int pixel_duration = std::min(256, end_offset) - offset;\n\n\t\t\t\t\t\t\tif(!offset) {\n\t\t\t\t\t\t\t\tconst int pixel_line = line - first_line;\n\n\t\t\t\t\t\t\t\tpixel_target_ = crt_.begin_data(256);\n\t\t\t\t\t\t\t\tattribute_address_ = ((pixel_line \/ 8) * 32) + 6144;\n\t\t\t\t\t\t\t\tpixel_address_ = ((pixel_line & 0x07) << 8) | ((pixel_line&0x38) << 2) | ((pixel_line&0xc0) << 5);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(pixel_target_) {\n\t\t\t\t\t\t\t\tconst int start_column = offset >> 4;\n\t\t\t\t\t\t\t\tconst int end_column = (offset + pixel_duration) >> 4;\n\t\t\t\t\t\t\t\tfor(int column = start_column; column < end_column; column++) {\n\t\t\t\t\t\t\t\t\tconst uint8_t attributes[2] = {\n\t\t\t\t\t\t\t\t\t\tmemory_[attribute_address_],\n\t\t\t\t\t\t\t\t\t\tmemory_[attribute_address_+1],\n\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\tconstexpr uint8_t masks[] = {0, 0xff};\n\t\t\t\t\t\t\t\t\tconst uint8_t pixels[2] = {\n\t\t\t\t\t\t\t\t\t\tuint8_t(memory_[pixel_address_] ^ masks[flash_mask_ & (attributes[0] >> 7)]),\n\t\t\t\t\t\t\t\t\t\tuint8_t(memory_[pixel_address_+1] ^ masks[flash_mask_ & (attributes[1] >> 7)]),\n\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconst uint8_t colours[2] = {\n\t\t\t\t\t\t\t\t\t\t\tpalette[(attributes[0] & 0x78) >> 3],\n\t\t\t\t\t\t\t\t\t\t\tpalette[((attributes[0] & 0x40) >> 3) | (attributes[0] & 0x07)],\n\t\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t\tpixel_target_[0] = colours[(pixels[0] >> 7) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[1] = colours[(pixels[0] >> 6) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[2] = colours[(pixels[0] >> 5) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[3] = colours[(pixels[0] >> 4) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[4] = colours[(pixels[0] >> 3) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[5] = colours[(pixels[0] >> 2) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[6] = colours[(pixels[0] >> 1) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[7] = colours[(pixels[0] >> 0) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_ += 8;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconst uint8_t colours[2] = {\n\t\t\t\t\t\t\t\t\t\t\tpalette[(attributes[1] & 0x78) >> 3],\n\t\t\t\t\t\t\t\t\t\t\tpalette[((attributes[1] & 0x40) >> 3) | (attributes[1] & 0x07)],\n\t\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t\tpixel_target_[0] = colours[(pixels[1] >> 7) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[1] = colours[(pixels[1] >> 6) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[2] = colours[(pixels[1] >> 5) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[3] = colours[(pixels[1] >> 4) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[4] = colours[(pixels[1] >> 3) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[5] = colours[(pixels[1] >> 2) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[6] = colours[(pixels[1] >> 1) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[7] = colours[(pixels[1] >> 0) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_ += 8;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tpixel_address_ += 2;\n\t\t\t\t\t\t\t\t\tattribute_address_ += 2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\toffset += pixel_duration;\n\t\t\t\t\t\t\tif(offset == 256) {\n\t\t\t\t\t\t\t\tcrt_.output_data(256);\n\t\t\t\t\t\t\t\tpixel_target_ = nullptr;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(offset >= 256 && offset < sync_position && end_offset > offset) {\n\t\t\t\t\t\t\tconst int border_duration = std::min(sync_position, end_offset) - offset;\n\t\t\t\t\t\t\toutput_border(border_duration);\n\t\t\t\t\t\t\toffset += border_duration;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Output the common tail to border and pixel lines: sync, blank, colour burst, border.\n\n\t\t\t\t\tif(offset >= sync_position && offset < sync_position + sync_length && end_offset > offset) {\n\t\t\t\t\t\tconst int sync_duration = std::min(sync_position + sync_length, end_offset) - offset;\n\t\t\t\t\t\tcrt_.output_sync(sync_duration);\n\t\t\t\t\t\toffset += sync_duration;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(offset >= sync_position + sync_length && offset < burst_position && end_offset > offset) {\n\t\t\t\t\t\tconst int blank_duration = std::min(burst_position, end_offset) - offset;\n\t\t\t\t\t\tcrt_.output_blank(blank_duration);\n\t\t\t\t\t\toffset += blank_duration;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(offset >= burst_position && offset < burst_position+burst_length && end_offset > offset) {\n\t\t\t\t\t\tconst int burst_duration = std::min(burst_position + burst_length, end_offset) - offset;\n\t\t\t\t\t\tcrt_.output_colour_burst(burst_duration, 0, is_alternate_line_);\n\t\t\t\t\t\toffset += burst_duration;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(offset >= burst_position+burst_length && end_offset > offset) {\n\t\t\t\t\t\tconst int border_duration = end_offset - offset;\n\t\t\t\t\t\toutput_border(border_duration);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcycles_remaining -= cycles_this_line;\n\t\t\t\ttime_since_interrupt_ = (time_since_interrupt_ + cycles_this_line) % (timings.cycles_per_line * timings.lines_per_frame);\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\t\/\/ TODO: how long is the interrupt line held for?\n\t\tstatic constexpr int interrupt_duration = 48;\n\n\t\tvoid output_border(int duration) {\n\t\t\tuint8_t *const colour_pointer = crt_.begin_data(1);\n\t\t\tif(colour_pointer) *colour_pointer = border_colour_;\n\t\t\tcrt_.output_level(duration);\n\t\t}\n\n\tpublic:\n\t\tVideo() :\n\t\t\tcrt_(227 * 2, 2, Outputs::Display::Type::PAL50, Outputs::Display::InputDataType::Red2Green2Blue2)\n\t\t{\n\t\t\t\/\/ Show only the centre 80% of the TV frame.\n\t\t\tcrt_.set_display_type(Outputs::Display::DisplayType::RGB);\n\t\t\tcrt_.set_visible_area(Outputs::Display::Rect(0.1f, 0.1f, 0.8f, 0.8f));\n\n\t\t}\n\n\t\tvoid set_video_source(const uint8_t *source) {\n\t\t\tmemory_ = source;\n\t\t}\n\n\t\tHalfCycles get_next_sequence_point() {\n\t\t\tif(time_since_interrupt_ < interrupt_duration) {\n\t\t\t\treturn HalfCycles(interrupt_duration - time_since_interrupt_);\n\t\t\t}\n\n\t\t\tconstexpr auto timings = get_timings();\n\t\t\treturn timings.cycles_per_line * timings.lines_per_frame - time_since_interrupt_;\n\t\t}\n\n\t\tbool get_interrupt_line() const {\n\t\t\treturn time_since_interrupt_ < interrupt_duration;\n\t\t}\n\n\t\tint access_delay(HalfCycles offset) const {\n\t\t\tconstexpr auto timings = get_timings();\n\t\t\tconst int delay_time = (time_since_interrupt_ + offset.as<int>()) % (timings.cycles_per_line * timings.lines_per_frame);\n\n\t\t\tif(delay_time < timings.first_delay) return 0;\n\n\t\t\tconst int time_since = delay_time - timings.first_delay;\n\t\t\tconst int lines = time_since \/ timings.cycles_per_line;\n\t\t\tif(lines >= 192) return 0;\n\n\t\t\tconst int line_position = time_since % timings.cycles_per_line;\n\t\t\tif(line_position >= timings.contended_period) return 0;\n\n\t\t\treturn timings.delays[line_position & 15];\n\t\t}\n\n\t\tvoid set_border_colour(uint8_t colour) {\n\t\t\tborder_colour_ = palette[colour];\n\t\t}\n\n\t\t\/\/\/ Sets the scan target.\n\t\tvoid set_scan_target(Outputs::Display::ScanTarget *scan_target) {\n\t\t\tcrt_.set_scan_target(scan_target);\n\t\t}\n\n\t\t\/\/\/ Gets the current scan status.\n\t\tOutputs::Display::ScanStatus get_scaled_scan_status() const {\n\t\t\treturn crt_.get_scaled_scan_status();\n\t\t}\n\n\t\t\/*! Sets the type of display the CRT will request. *\/\n\t\tvoid set_display_type(Outputs::Display::DisplayType type) {\n\t\t\tcrt_.set_display_type(type);\n\t\t}\n\n\tprivate:\n\t\tint time_since_interrupt_ = 0;\n\t\tOutputs::CRT::CRT crt_;\n\t\tconst uint8_t *memory_ = nullptr;\n\t\tuint8_t border_colour_ = 0;\n\n\t\tuint8_t *pixel_target_ = nullptr;\n\t\tint attribute_address_ = 0;\n\t\tint pixel_address_ = 0;\n\n\t\tuint8_t flash_mask_ = 0;\n\t\tint flash_counter_ = 0;\n\t\tbool is_alternate_line_ = false;\n\n#define RGB(r, g, b)\t(r << 4) | (g << 2) | b\n\t\tstatic constexpr uint8_t palette[] = {\n\t\t\tRGB(0, 0, 0),\tRGB(0, 0, 2),\tRGB(2, 0, 0),\tRGB(2, 0, 2),\n\t\t\tRGB(0, 2, 0),\tRGB(0, 2, 2),\tRGB(2, 2, 0),\tRGB(2, 2, 2),\n\t\t\tRGB(0, 0, 0),\tRGB(0, 0, 3),\tRGB(3, 0, 0),\tRGB(3, 0, 3),\n\t\t\tRGB(0, 3, 0),\tRGB(0, 3, 3),\tRGB(3, 3, 0),\tRGB(3, 3, 3),\n\t\t};\n#undef RGB\n};\n\n}\n}\n\n#endif \/* Video_hpp *\/\n<commit_msg>Makes another guess at total colour phase.<commit_after>\/\/\n\/\/ Video.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 18\/03\/2021.\n\/\/ Copyright © 2021 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Video_hpp\n#define Video_hpp\n\n#include \"..\/..\/..\/Outputs\/CRT\/CRT.hpp\"\n#include \"..\/..\/..\/ClockReceiver\/ClockReceiver.hpp\"\n\n#include <algorithm>\n\nnamespace Sinclair {\nnamespace ZXSpectrum {\n\nenum class VideoTiming {\n\tPlus3\n};\n\n\/*\n\tTiming notes:\n\n\tAs of the +2a\/+3:\n\n\t\t311 lines, 228 cycles\/line\n\t\tDelays begin at 14361, follow the pattern 1, 0, 7, 6, 5, 4, 3, 2; run for 129 cycles\/line.\n\t\tPossibly delays only affect actual reads and writes; documentation is unclear.\n\n\tUnknowns, to me, presently:\n\n\t\tHow long the interrupt line held for.\n\n\tSo...\n\n\t\tProbably two bytes of video and attribute are fetched in each 8-cycle block,\n\t\twith 16 such blocks therefore providing the whole visible display, an island\n\t\twithin 28.5 blocks horizontally.\n\n\t\t14364 is 228*63, so I I guess almost 63 lines run from the start of vertical\n\t\tblank through to the top of the display, implying 56 lines on to vertical blank.\n\n*\/\n\ntemplate <VideoTiming timing> class Video {\n\tprivate:\n\t\tstruct Timings {\n\t\t\tint cycles_per_line;\n\t\t\tint lines_per_frame;\n\t\t\tint first_delay;\n\t\t\tint contended_period;\n\t\t\tint first_fetch;\n\t\t\tint delays[16];\n\t\t};\n\n\t\tstatic constexpr Timings get_timings() {\n\t\t\tconstexpr Timings result = {\n\t\t\t\t.cycles_per_line = 228 * 2,\n\t\t\t\t.lines_per_frame = 311,\n\t\t\t\t.first_delay = 14361 * 2,\n\t\t\t\t.contended_period = (14490 - 14361) * 2,\n\t\t\t\t.first_fetch = 14364 * 2,\t\/\/ TODO: find a source for this, a guess.\n\t\t\t\t.delays = {\n\t\t\t\t\t2, 1,\n\t\t\t\t\t0, 0,\n\t\t\t\t\t14, 13,\n\t\t\t\t\t12, 11,\n\t\t\t\t\t10, 9,\n\t\t\t\t\t8, 7,\n\t\t\t\t\t6, 5,\n\t\t\t\t\t4, 3,\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn result;\n\t\t}\n\n\tpublic:\n\t\tvoid run_for(HalfCycles duration) {\n\t\t\tconstexpr auto timings = get_timings();\n\t\t\tconstexpr int first_line = timings.first_fetch \/ timings.cycles_per_line;\n\t\t\tconstexpr int sync_position = 166 * 2;\n\t\t\tconstexpr int sync_length = 17 * 2;\n\t\t\tconstexpr int burst_position = sync_position + 40;\n\t\t\tconstexpr int burst_length = 17;\n\n\t\t\tint cycles_remaining = duration.as<int>();\n\t\t\twhile(cycles_remaining) {\n\t\t\t\tint line = time_since_interrupt_ \/ timings.cycles_per_line;\n\t\t\t\tint offset = time_since_interrupt_ % timings.cycles_per_line;\n\t\t\t\tconst int cycles_this_line = std::min(cycles_remaining, timings.cycles_per_line - offset);\n\t\t\t\tconst int end_offset = offset + cycles_this_line;\n\n\t\t\t\tif(!offset) {\n\t\t\t\t\tis_alternate_line_ ^= true;\n\n\t\t\t\t\tif(!line) {\n\t\t\t\t\t\tflash_counter_ = (flash_counter_ + 1) & 31;\n\t\t\t\t\t\tflash_mask_ = uint8_t(flash_counter_ >> 4);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(line < 3) {\n\t\t\t\t\t\/\/ Output sync line.\n\t\t\t\t\tcrt_.output_sync(cycles_this_line);\n\t\t\t\t} else {\n\t\t\t\t\tif((line < first_line) || (line >= first_line+192)) {\n\t\t\t\t\t\t\/\/ Output plain border line.\n\t\t\t\t\t\tif(offset < sync_position) {\n\t\t\t\t\t\t\tconst int border_duration = std::min(sync_position, end_offset) - offset;\n\t\t\t\t\t\t\toutput_border(border_duration);\n\t\t\t\t\t\t\toffset += border_duration;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ Output pixel line.\n\t\t\t\t\t\tif(offset < 256) {\n\t\t\t\t\t\t\tconst int pixel_duration = std::min(256, end_offset) - offset;\n\n\t\t\t\t\t\t\tif(!offset) {\n\t\t\t\t\t\t\t\tconst int pixel_line = line - first_line;\n\n\t\t\t\t\t\t\t\tpixel_target_ = crt_.begin_data(256);\n\t\t\t\t\t\t\t\tattribute_address_ = ((pixel_line \/ 8) * 32) + 6144;\n\t\t\t\t\t\t\t\tpixel_address_ = ((pixel_line & 0x07) << 8) | ((pixel_line&0x38) << 2) | ((pixel_line&0xc0) << 5);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(pixel_target_) {\n\t\t\t\t\t\t\t\tconst int start_column = offset >> 4;\n\t\t\t\t\t\t\t\tconst int end_column = (offset + pixel_duration) >> 4;\n\t\t\t\t\t\t\t\tfor(int column = start_column; column < end_column; column++) {\n\t\t\t\t\t\t\t\t\tconst uint8_t attributes[2] = {\n\t\t\t\t\t\t\t\t\t\tmemory_[attribute_address_],\n\t\t\t\t\t\t\t\t\t\tmemory_[attribute_address_+1],\n\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\tconstexpr uint8_t masks[] = {0, 0xff};\n\t\t\t\t\t\t\t\t\tconst uint8_t pixels[2] = {\n\t\t\t\t\t\t\t\t\t\tuint8_t(memory_[pixel_address_] ^ masks[flash_mask_ & (attributes[0] >> 7)]),\n\t\t\t\t\t\t\t\t\t\tuint8_t(memory_[pixel_address_+1] ^ masks[flash_mask_ & (attributes[1] >> 7)]),\n\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconst uint8_t colours[2] = {\n\t\t\t\t\t\t\t\t\t\t\tpalette[(attributes[0] & 0x78) >> 3],\n\t\t\t\t\t\t\t\t\t\t\tpalette[((attributes[0] & 0x40) >> 3) | (attributes[0] & 0x07)],\n\t\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t\tpixel_target_[0] = colours[(pixels[0] >> 7) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[1] = colours[(pixels[0] >> 6) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[2] = colours[(pixels[0] >> 5) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[3] = colours[(pixels[0] >> 4) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[4] = colours[(pixels[0] >> 3) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[5] = colours[(pixels[0] >> 2) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[6] = colours[(pixels[0] >> 1) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[7] = colours[(pixels[0] >> 0) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_ += 8;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconst uint8_t colours[2] = {\n\t\t\t\t\t\t\t\t\t\t\tpalette[(attributes[1] & 0x78) >> 3],\n\t\t\t\t\t\t\t\t\t\t\tpalette[((attributes[1] & 0x40) >> 3) | (attributes[1] & 0x07)],\n\t\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t\tpixel_target_[0] = colours[(pixels[1] >> 7) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[1] = colours[(pixels[1] >> 6) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[2] = colours[(pixels[1] >> 5) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[3] = colours[(pixels[1] >> 4) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[4] = colours[(pixels[1] >> 3) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[5] = colours[(pixels[1] >> 2) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[6] = colours[(pixels[1] >> 1) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_[7] = colours[(pixels[1] >> 0) & 1];\n\t\t\t\t\t\t\t\t\t\tpixel_target_ += 8;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tpixel_address_ += 2;\n\t\t\t\t\t\t\t\t\tattribute_address_ += 2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\toffset += pixel_duration;\n\t\t\t\t\t\t\tif(offset == 256) {\n\t\t\t\t\t\t\t\tcrt_.output_data(256);\n\t\t\t\t\t\t\t\tpixel_target_ = nullptr;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(offset >= 256 && offset < sync_position && end_offset > offset) {\n\t\t\t\t\t\t\tconst int border_duration = std::min(sync_position, end_offset) - offset;\n\t\t\t\t\t\t\toutput_border(border_duration);\n\t\t\t\t\t\t\toffset += border_duration;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Output the common tail to border and pixel lines: sync, blank, colour burst, border.\n\n\t\t\t\t\tif(offset >= sync_position && offset < sync_position + sync_length && end_offset > offset) {\n\t\t\t\t\t\tconst int sync_duration = std::min(sync_position + sync_length, end_offset) - offset;\n\t\t\t\t\t\tcrt_.output_sync(sync_duration);\n\t\t\t\t\t\toffset += sync_duration;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(offset >= sync_position + sync_length && offset < burst_position && end_offset > offset) {\n\t\t\t\t\t\tconst int blank_duration = std::min(burst_position, end_offset) - offset;\n\t\t\t\t\t\tcrt_.output_blank(blank_duration);\n\t\t\t\t\t\toffset += blank_duration;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(offset >= burst_position && offset < burst_position+burst_length && end_offset > offset) {\n\t\t\t\t\t\tconst int burst_duration = std::min(burst_position + burst_length, end_offset) - offset;\n\t\t\t\t\t\tcrt_.output_colour_burst(burst_duration, 116, is_alternate_line_);\n\t\t\t\t\t\toffset += burst_duration;\n\t\t\t\t\t\t\/\/ The colour burst phase above is an empirical guess. I need to research further.\n\t\t\t\t\t}\n\n\t\t\t\t\tif(offset >= burst_position+burst_length && end_offset > offset) {\n\t\t\t\t\t\tconst int border_duration = end_offset - offset;\n\t\t\t\t\t\toutput_border(border_duration);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcycles_remaining -= cycles_this_line;\n\t\t\t\ttime_since_interrupt_ = (time_since_interrupt_ + cycles_this_line) % (timings.cycles_per_line * timings.lines_per_frame);\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\t\/\/ TODO: how long is the interrupt line held for?\n\t\tstatic constexpr int interrupt_duration = 48;\n\n\t\tvoid output_border(int duration) {\n\t\t\tuint8_t *const colour_pointer = crt_.begin_data(1);\n\t\t\tif(colour_pointer) *colour_pointer = border_colour_;\n\t\t\tcrt_.output_level(duration);\n\t\t}\n\n\tpublic:\n\t\tVideo() :\n\t\t\tcrt_(227 * 2, 2, Outputs::Display::Type::PAL50, Outputs::Display::InputDataType::Red2Green2Blue2)\n\t\t{\n\t\t\t\/\/ Show only the centre 80% of the TV frame.\n\t\t\tcrt_.set_display_type(Outputs::Display::DisplayType::RGB);\n\t\t\tcrt_.set_visible_area(Outputs::Display::Rect(0.1f, 0.1f, 0.8f, 0.8f));\n\n\t\t}\n\n\t\tvoid set_video_source(const uint8_t *source) {\n\t\t\tmemory_ = source;\n\t\t}\n\n\t\tHalfCycles get_next_sequence_point() {\n\t\t\tif(time_since_interrupt_ < interrupt_duration) {\n\t\t\t\treturn HalfCycles(interrupt_duration - time_since_interrupt_);\n\t\t\t}\n\n\t\t\tconstexpr auto timings = get_timings();\n\t\t\treturn timings.cycles_per_line * timings.lines_per_frame - time_since_interrupt_;\n\t\t}\n\n\t\tbool get_interrupt_line() const {\n\t\t\treturn time_since_interrupt_ < interrupt_duration;\n\t\t}\n\n\t\tint access_delay(HalfCycles offset) const {\n\t\t\tconstexpr auto timings = get_timings();\n\t\t\tconst int delay_time = (time_since_interrupt_ + offset.as<int>()) % (timings.cycles_per_line * timings.lines_per_frame);\n\n\t\t\tif(delay_time < timings.first_delay) return 0;\n\n\t\t\tconst int time_since = delay_time - timings.first_delay;\n\t\t\tconst int lines = time_since \/ timings.cycles_per_line;\n\t\t\tif(lines >= 192) return 0;\n\n\t\t\tconst int line_position = time_since % timings.cycles_per_line;\n\t\t\tif(line_position >= timings.contended_period) return 0;\n\n\t\t\treturn timings.delays[line_position & 15];\n\t\t}\n\n\t\tvoid set_border_colour(uint8_t colour) {\n\t\t\tborder_colour_ = palette[colour];\n\t\t}\n\n\t\t\/\/\/ Sets the scan target.\n\t\tvoid set_scan_target(Outputs::Display::ScanTarget *scan_target) {\n\t\t\tcrt_.set_scan_target(scan_target);\n\t\t}\n\n\t\t\/\/\/ Gets the current scan status.\n\t\tOutputs::Display::ScanStatus get_scaled_scan_status() const {\n\t\t\treturn crt_.get_scaled_scan_status();\n\t\t}\n\n\t\t\/*! Sets the type of display the CRT will request. *\/\n\t\tvoid set_display_type(Outputs::Display::DisplayType type) {\n\t\t\tcrt_.set_display_type(type);\n\t\t}\n\n\tprivate:\n\t\tint time_since_interrupt_ = 0;\n\t\tOutputs::CRT::CRT crt_;\n\t\tconst uint8_t *memory_ = nullptr;\n\t\tuint8_t border_colour_ = 0;\n\n\t\tuint8_t *pixel_target_ = nullptr;\n\t\tint attribute_address_ = 0;\n\t\tint pixel_address_ = 0;\n\n\t\tuint8_t flash_mask_ = 0;\n\t\tint flash_counter_ = 0;\n\t\tbool is_alternate_line_ = false;\n\n#define RGB(r, g, b)\t(r << 4) | (g << 2) | b\n\t\tstatic constexpr uint8_t palette[] = {\n\t\t\tRGB(0, 0, 0),\tRGB(0, 0, 2),\tRGB(2, 0, 0),\tRGB(2, 0, 2),\n\t\t\tRGB(0, 2, 0),\tRGB(0, 2, 2),\tRGB(2, 2, 0),\tRGB(2, 2, 2),\n\t\t\tRGB(0, 0, 0),\tRGB(0, 0, 3),\tRGB(3, 0, 0),\tRGB(3, 0, 3),\n\t\t\tRGB(0, 3, 0),\tRGB(0, 3, 3),\tRGB(3, 3, 0),\tRGB(3, 3, 3),\n\t\t};\n#undef RGB\n};\n\n}\n}\n\n#endif \/* Video_hpp *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * service.cpp\n *\n * Created on: Aug 21, 2015\n * Author: zmij\n *\/\n\n#include <tip\/http\/client\/service.hpp>\n#include <tip\/log.hpp>\n\n#include <set>\n#include <map>\n\n#include <tip\/http\/client\/session.hpp>\n#include <tip\/http\/client\/errors.hpp>\n#include <tip\/http\/common\/response.hpp>\n\nnamespace tip {\nnamespace http {\nnamespace client {\n\nLOCAL_LOGGING_FACILITY(HTTPCLIENT, TRACE);\n\nservice::io_service::id service::id;\n\nnamespace {\n\nconst iri::scheme HTTP_SCHEME = iri::scheme{\"http\"};\nconst iri::scheme HTTPS_SCHEME = iri::scheme{\"https\"};\n\nconst std::set< iri::scheme > SUPPORTED_SCHEMES { HTTP_SCHEME, HTTPS_SCHEME };\n\n} \/\/ namespace\n\nstruct service::impl : std::enable_shared_from_this<impl> {\n\ttypedef std::pair< iri::host, std::string > connection_id;\n\t\/\/ TODO multiple sessions per host\n\ttypedef std::map< connection_id, session_ptr > session_container;\n\n\tio_service&\t\t\towner_;\n\theaders\t\t\t\tdefault_headers_;\n\tsession_container\tsessions_;\n\n\timpl(io_service& owner, headers const& default_headers) :\n\t\towner_(owner), default_headers_(default_headers)\n\t{\n\t}\n\n\t~impl()\n\t{\n\t\tlocal_log() << \"service::impl::~impl\";\n\t}\n\n\tvoid\n\tget(std::string const& url, response_callback cb, error_callback ecb)\n\t{\n\t\trequest::iri_type iri;\n\t\tif (!request::parse_iri(url, iri)) {\n\t\t\ttry {\n\t\t\t\tthrow errors::http_client_error(\"Invalid IRI\");\n\t\t\t} catch (std::exception const& e) {\n\t\t\t\tif (ecb) {\n\t\t\t\t\tecb(std::current_exception());\n\t\t\t\t} else throw;\n\t\t\t}\n\t\t}\n\t\tsend_request(GET, iri, session::body_type(), cb, ecb);\n\t}\n\tvoid\n\tpost(std::string const& url, body_type const& body,\n\t\t\tresponse_callback cb, error_callback ecb)\n\t{\n\t\trequest::iri_type iri;\n\t\tif (!request::parse_iri(url, iri)) {\n\t\t\treturn;\n\t\t}\n\t\tsend_request(POST, iri, body, cb, ecb);\n\t}\n\tvoid\n\tpost(std::string const& url, body_type&& body,\n\t\t\tresponse_callback cb, error_callback ecb)\n\t{\n\t\trequest::iri_type iri;\n\t\tif (!request::parse_iri(url, iri)) {\n\t\t\treturn;\n\t\t}\n\t\tsend_request(POST, iri, std::move(body), cb, ecb);\n\t}\n\n\n\tvoid\n\tsend_request(request_method method, request::iri_type const& iri,\n\t\t\tsession::body_type const& body,\n\t\t\tresponse_callback cb, error_callback ecb)\n\t{\n\t\tusing std::placeholders::_1;\n\t\tusing std::placeholders::_2;\n\t\tsession_ptr s = get_session(iri);\n\t\ts->send_request(GET, iri, body,\n\t\t\t\tstd::bind(&impl::handle_response,\n\t\t\t\t\t\tshared_from_this(), _1, _2, cb, ecb), ecb);\n\t}\n\tvoid\n\tsend_request(request_method method, request::iri_type const& iri,\n\t\t\tsession::body_type&& body,\n\t\t\tresponse_callback cb, error_callback ecb)\n\t{\n\t\tusing std::placeholders::_1;\n\t\tusing std::placeholders::_2;\n\t\tsession_ptr s = get_session(iri);\n\t\ts->send_request(GET, iri, std::move(body),\n\t\t\t\tstd::bind(&impl::handle_response,\n\t\t\t\t\t\tshared_from_this(), _1, _2, cb, ecb), ecb);\n\t}\n\n\tsession_ptr\n\tget_session(request::iri_type const& iri)\n\t{\n\t\tif (SUPPORTED_SCHEMES.count(iri.scheme) == 0) {\n\t\t\t\/\/ TODO Throw an error - unsupported scheme\n\t\t\tlocal_log(logger::ERROR) << \"IRI scheme \"\n\t\t\t\t\t<< iri.scheme << \" is not supported\";\n\t\t\tthrow std::runtime_error(\"Scheme not supported\");\n\t\t}\n\t\tif (iri.authority.host.empty()) {\n\t\t\t\/\/ TODO Throw an error - empty host\n\t\t\tlocal_log(logger::ERROR) << \"Host is empty\";\n\t\t\tthrow std::runtime_error(\"Host is empty\");\n\t\t}\n\t\tconnection_id cid{ iri.authority.host,\n\t\t\tiri.authority.port.empty() ?\n\t\t\t\t\tstatic_cast<std::string const&>(iri.scheme) :\n\t\t\t\t\tstatic_cast<std::string const&>(iri.authority.port) };\n\t\t\/\/ FIXME Add mutex\n\t\tauto f = sessions_.find(cid);\n\t\tif (f == sessions_.end()) {\n\t\t\tsession_ptr s = create_session(iri);\n\t\t\tf = sessions_.insert(std::make_pair(cid, s)).first;\n\t\t}\n\t\treturn f->second;\n\t}\n\n\tsession_ptr\n\tcreate_session(request::iri_type const& iri)\n\t{\n\t\treturn session::create(owner_, iri,\n\t\t\t\tstd::bind(&impl::session_closed,\n\t\t\t\t\t\tshared_from_this(), std::placeholders::_1),\n\t\t\t\tdefault_headers_);\n\t}\n\n\tvoid\n\thandle_response(request_ptr req, response_ptr resp, response_callback cb,\n\t\t\terror_callback ecb)\n\t{\n\t\tusing std::placeholders::_1;\n\t\tusing std::placeholders::_2;\n\t\tint status = resp->status \/ 100;\n\t\tif (status == 3) {\n\t\t\t\/\/ Handle redirect\n\t\t\theaders::const_iterator f = resp->headers_.find(Location);\n\t\t\tif (f != resp->headers_.end()) {\n\t\t\t\tlocal_log(logger::DEBUG) << \"Request redirected to \" << f->second;\n\t\t\t\trequest::iri_type iri;\n\t\t\t\tif (!request::parse_iri(f->second, iri)) {\n\t\t\t\t\tlocal_log(logger::WARNING) << \"Invalid redirect location\";\n\t\t\t\t\tcb(resp);\n\t\t\t\t} else {\n\t\t\t\t\treq->path = iri.path;\n\t\t\t\t\treq->query = iri.query;\n\t\t\t\t\treq->fragment = iri.fragment;\n\t\t\t\t\treq->host( iri.authority.host );\n\n\t\t\t\t\tsession_ptr s = get_session(iri);\n\t\t\t\t\ts->send_request(req, std::bind(\n\t\t\t\t\t\t\t&impl::handle_response, this, _1, _2, cb, ecb), ecb);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlocal_log(logger::WARNING) << \"Request redirected, but no Location header set\";\n\t\t\t\tcb(resp);\n\t\t\t}\n\t\t} else if (status == 4) {\n\n\t\t\tlocal_log(logger::WARNING) << \"Received error response \" << resp->status\n\t\t\t\t\t<< \" \" << resp->status_line << \"\\n\" << *req;\n\n\t\t\tcb(resp);\n\t\t} else {\n\t\t\tcb(resp);\n\t\t}\n\t}\n\n\tvoid\n\tsession_closed(session_ptr s)\n\t{\n\t\tlocal_log() << \"Session closed\";\n\t\tsession_container::const_iterator p = sessions_.begin();\n\t\tfor (; p != sessions_.end(); ++p) {\n\t\t\tif (p->second == s) break;\n\t\t}\n\t\tif (p != sessions_.end()) {\n\t\t\tsessions_.erase(p);\n\t\t}\n\t}\n\n\tvoid\n\tshutdown()\n\t{\n\t\tsession_container save = sessions_;\n\t\tfor (session_container::const_iterator p = save.begin();\n\t\t\t\tp != save.end(); ++p) {\n\t\t\tp->second->close();\n\t\t}\n\t}\n};\n\nservice::service(io_service& owner) :\n\t\tbase_type(owner),\n\t\tpimpl_(new impl {\n\t\t\towner,\n\t\t\t{\n\t\t\t\t{ Connection, \"keep-alive\" },\n\t\t\t\t{ UserAgent, \"tip-http-client\" }\n\t\t\t}\n\t\t})\n{\n}\n\nservice::~service()\n{\n}\n\nvoid\nservice::shutdown_service()\n{\n\tlocal_log(logger::DEBUG) << \"Shutdown HTTP client service\";\n\tpimpl_->shutdown();\n}\n\nvoid\nservice::get(std::string const& url, response_callback cb, error_callback eb)\n{\n\tpimpl_->get(url, cb, eb);\n}\nvoid\nservice::post(std::string const& url, body_type const& body,\n\t\tresponse_callback cb, error_callback eb)\n{\n\tpimpl_->post(url, body, cb, eb);\n}\nvoid\nservice::post(std::string const& url, body_type&& body,\n\t\tresponse_callback cb, error_callback eb)\n{\n\tpimpl_->post(url, std::move(body), cb, eb);\n}\n\n} \/* namespace client *\/\n} \/* namespace http *\/\n} \/* namespace tip *\/\n<commit_msg>Call error callback if an exception is throwed in get_session<commit_after>\/*\n * service.cpp\n *\n * Created on: Aug 21, 2015\n * Author: zmij\n *\/\n\n#include <tip\/http\/client\/service.hpp>\n#include <tip\/log.hpp>\n\n#include <set>\n#include <map>\n\n#include <tip\/http\/client\/session.hpp>\n#include <tip\/http\/client\/errors.hpp>\n#include <tip\/http\/common\/response.hpp>\n\nnamespace tip {\nnamespace http {\nnamespace client {\n\nLOCAL_LOGGING_FACILITY(HTTPCLIENT, TRACE);\n\nservice::io_service::id service::id;\n\nnamespace {\n\nconst iri::scheme HTTP_SCHEME = iri::scheme{\"http\"};\nconst iri::scheme HTTPS_SCHEME = iri::scheme{\"https\"};\n\nconst std::set< iri::scheme > SUPPORTED_SCHEMES { HTTP_SCHEME, HTTPS_SCHEME };\n\n} \/\/ namespace\n\nstruct service::impl : std::enable_shared_from_this<impl> {\n\ttypedef std::pair< iri::host, std::string > connection_id;\n\t\/\/ TODO multiple sessions per host\n\ttypedef std::map< connection_id, session_ptr > session_container;\n\n\tio_service&\t\t\towner_;\n\theaders\t\t\t\tdefault_headers_;\n\tsession_container\tsessions_;\n\n\timpl(io_service& owner, headers const& default_headers) :\n\t\towner_(owner), default_headers_(default_headers)\n\t{\n\t}\n\n\t~impl()\n\t{\n\t\tlocal_log() << \"service::impl::~impl\";\n\t}\n\n\tvoid\n\tget(std::string const& url, response_callback cb, error_callback ecb)\n\t{\n\t\trequest::iri_type iri;\n\t\tif (!request::parse_iri(url, iri)) {\n\t\t\ttry {\n\t\t\t\tthrow errors::http_client_error(\"Invalid IRI\");\n\t\t\t} catch (std::exception const& e) {\n\t\t\t\tif (ecb) {\n\t\t\t\t\tecb(std::current_exception());\n\t\t\t\t} else throw;\n\t\t\t}\n\t\t}\n\t\tsend_request(GET, iri, session::body_type(), cb, ecb);\n\t}\n\tvoid\n\tpost(std::string const& url, body_type const& body,\n\t\t\tresponse_callback cb, error_callback ecb)\n\t{\n\t\trequest::iri_type iri;\n\t\tif (!request::parse_iri(url, iri)) {\n\t\t\treturn;\n\t\t}\n\t\tsend_request(POST, iri, body, cb, ecb);\n\t}\n\tvoid\n\tpost(std::string const& url, body_type&& body,\n\t\t\tresponse_callback cb, error_callback ecb)\n\t{\n\t\trequest::iri_type iri;\n\t\tif (!request::parse_iri(url, iri)) {\n\t\t\treturn;\n\t\t}\n\t\tsend_request(POST, iri, std::move(body), cb, ecb);\n\t}\n\n\n\tvoid\n\tsend_request(request_method method, request::iri_type const& iri,\n\t\t\tsession::body_type const& body,\n\t\t\tresponse_callback cb, error_callback ecb)\n\t{\n\t\tusing std::placeholders::_1;\n\t\tusing std::placeholders::_2;\n\t\ttry {\n\t\t\tsession_ptr s = get_session(iri);\n\t\t\ts->send_request(GET, iri, body,\n\t\t\t\t\tstd::bind(&impl::handle_response,\n\t\t\t\t\t\t\tshared_from_this(), _1, _2, cb, ecb), ecb);\n\t\t} catch (...) {\n\t\t\tif (ecb) {\n\t\t\t\tecb(std::current_exception());\n\t\t\t} else throw;\n\t\t}\n\t}\n\tvoid\n\tsend_request(request_method method, request::iri_type const& iri,\n\t\t\tsession::body_type&& body,\n\t\t\tresponse_callback cb, error_callback ecb)\n\t{\n\t\tusing std::placeholders::_1;\n\t\tusing std::placeholders::_2;\n\t\ttry {\n\t\t\tsession_ptr s = get_session(iri);\n\t\t\ts->send_request(GET, iri, std::move(body),\n\t\t\t\t\tstd::bind(&impl::handle_response,\n\t\t\t\t\t\t\tshared_from_this(), _1, _2, cb, ecb), ecb);\n\t\t} catch (...) {\n\t\t\tif (ecb) {\n\t\t\t\tecb(std::current_exception());\n\t\t\t} else throw;\n\t\t}\n\t}\n\n\tsession_ptr\n\tget_session(request::iri_type const& iri)\n\t{\n\t\tif (SUPPORTED_SCHEMES.count(iri.scheme) == 0) {\n\t\t\t\/\/ TODO Throw an error - unsupported scheme\n\t\t\tlocal_log(logger::ERROR) << \"IRI scheme \"\n\t\t\t\t\t<< iri.scheme << \" is not supported\";\n\t\t\tthrow std::runtime_error(\"Scheme not supported\");\n\t\t}\n\t\tif (iri.authority.host.empty()) {\n\t\t\t\/\/ TODO Throw an error - empty host\n\t\t\tlocal_log(logger::ERROR) << \"Host is empty\";\n\t\t\tthrow std::runtime_error(\"Host is empty\");\n\t\t}\n\t\tconnection_id cid{ iri.authority.host,\n\t\t\tiri.authority.port.empty() ?\n\t\t\t\t\tstatic_cast<std::string const&>(iri.scheme) :\n\t\t\t\t\tstatic_cast<std::string const&>(iri.authority.port) };\n\t\t\/\/ FIXME Add mutex\n\t\tauto f = sessions_.find(cid);\n\t\tif (f == sessions_.end()) {\n\t\t\tsession_ptr s = create_session(iri);\n\t\t\tf = sessions_.insert(std::make_pair(cid, s)).first;\n\t\t}\n\t\treturn f->second;\n\t}\n\n\tsession_ptr\n\tcreate_session(request::iri_type const& iri)\n\t{\n\t\treturn session::create(owner_, iri,\n\t\t\t\tstd::bind(&impl::session_closed,\n\t\t\t\t\t\tshared_from_this(), std::placeholders::_1),\n\t\t\t\tdefault_headers_);\n\t}\n\n\tvoid\n\thandle_response(request_ptr req, response_ptr resp, response_callback cb,\n\t\t\terror_callback ecb)\n\t{\n\t\tusing std::placeholders::_1;\n\t\tusing std::placeholders::_2;\n\t\tint status = resp->status \/ 100;\n\t\tif (status == 3) {\n\t\t\t\/\/ Handle redirect\n\t\t\theaders::const_iterator f = resp->headers_.find(Location);\n\t\t\tif (f != resp->headers_.end()) {\n\t\t\t\tlocal_log(logger::DEBUG) << \"Request redirected to \" << f->second;\n\t\t\t\trequest::iri_type iri;\n\t\t\t\tif (!request::parse_iri(f->second, iri)) {\n\t\t\t\t\tlocal_log(logger::WARNING) << \"Invalid redirect location\";\n\t\t\t\t\tcb(resp);\n\t\t\t\t} else {\n\t\t\t\t\treq->path = iri.path;\n\t\t\t\t\treq->query = iri.query;\n\t\t\t\t\treq->fragment = iri.fragment;\n\t\t\t\t\treq->host( iri.authority.host );\n\n\t\t\t\t\tsession_ptr s = get_session(iri);\n\t\t\t\t\ts->send_request(req, std::bind(\n\t\t\t\t\t\t\t&impl::handle_response, this, _1, _2, cb, ecb), ecb);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlocal_log(logger::WARNING) << \"Request redirected, but no Location header set\";\n\t\t\t\tcb(resp);\n\t\t\t}\n\t\t} else if (status == 4) {\n\n\t\t\tlocal_log(logger::WARNING) << \"Received error response \" << resp->status\n\t\t\t\t\t<< \" \" << resp->status_line << \"\\n\" << *req;\n\n\t\t\tcb(resp);\n\t\t} else {\n\t\t\tcb(resp);\n\t\t}\n\t}\n\n\tvoid\n\tsession_closed(session_ptr s)\n\t{\n\t\tlocal_log() << \"Session closed\";\n\t\tsession_container::const_iterator p = sessions_.begin();\n\t\tfor (; p != sessions_.end(); ++p) {\n\t\t\tif (p->second == s) break;\n\t\t}\n\t\tif (p != sessions_.end()) {\n\t\t\tsessions_.erase(p);\n\t\t}\n\t}\n\n\tvoid\n\tshutdown()\n\t{\n\t\tsession_container save = sessions_;\n\t\tfor (session_container::const_iterator p = save.begin();\n\t\t\t\tp != save.end(); ++p) {\n\t\t\tp->second->close();\n\t\t}\n\t}\n};\n\nservice::service(io_service& owner) :\n\t\tbase_type(owner),\n\t\tpimpl_(new impl {\n\t\t\towner,\n\t\t\t{\n\t\t\t\t{ Connection, \"keep-alive\" },\n\t\t\t\t{ UserAgent, \"tip-http-client\" }\n\t\t\t}\n\t\t})\n{\n}\n\nservice::~service()\n{\n}\n\nvoid\nservice::shutdown_service()\n{\n\tlocal_log(logger::DEBUG) << \"Shutdown HTTP client service\";\n\tpimpl_->shutdown();\n}\n\nvoid\nservice::get(std::string const& url, response_callback cb, error_callback eb)\n{\n\tpimpl_->get(url, cb, eb);\n}\nvoid\nservice::post(std::string const& url, body_type const& body,\n\t\tresponse_callback cb, error_callback eb)\n{\n\tpimpl_->post(url, body, cb, eb);\n}\nvoid\nservice::post(std::string const& url, body_type&& body,\n\t\tresponse_callback cb, error_callback eb)\n{\n\tpimpl_->post(url, std::move(body), cb, eb);\n}\n\n} \/* namespace client *\/\n} \/* namespace http *\/\n} \/* namespace tip *\/\n<|endoftext|>"} {"text":"<commit_before>#include <aleph\/containers\/PointCloud.hh>\n\n#include <aleph\/config\/FLANN.hh>\n\n#include <aleph\/geometry\/BruteForce.hh>\n#include <aleph\/geometry\/FLANN.hh>\n\n#include <aleph\/geometry\/distances\/Euclidean.hh>\n#include <aleph\/geometry\/distances\/Manhattan.hh>\n#include <aleph\/geometry\/distances\/Traits.hh>\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <getopt.h>\n\nusing DataType = double;\nusing PointCloud = aleph::containers::PointCloud<DataType>;\nusing EuclideanDistance = aleph::distances::Euclidean<DataType>;\nusing ManhattanDistance = aleph::distances::Manhattan<DataType>;\n\ntemplate <class Distance> std::vector<DataType> pairwiseDistances( const PointCloud& pointCloud, Distance distance = Distance() )\n{\n if( pointCloud.empty() )\n return {};\n\n std::vector<DataType> distances;\n distances.reserve( pointCloud.size() * ( pointCloud.size() - 1 ) \/ 2 );\n\n auto d = pointCloud.dimension();\n auto n = pointCloud.size();\n using Traits = aleph::distances::Traits<Distance>;\n\n Traits traits;\n for( decltype(n) i = 0; i < n; i++ )\n {\n for( decltype(n) j = i+1; j < n; j++ )\n {\n auto dist = distance( pointCloud[i].begin(),\n pointCloud[j].begin(),\n d );\n\n dist = traits.from( dist );\n\n distances.emplace_back( dist );\n }\n }\n\n return distances;\n}\n\nint main( int argc, char** argv )\n{\n static option commandLineOptions[] =\n {\n { \"distance\" , required_argument, nullptr, 'd' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n std::string selectedDistanceFunctor = \"euclidean\";\n\n {\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"d:\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'd':\n selectedDistanceFunctor = optarg;\n break;\n }\n }\n }\n\n if( (argc - optind) < 1 )\n return -1;\n\n auto filename = std::string( argv[optind++] );\n auto pointCloud = aleph::containers::load<DataType>( filename );\n\n std::cerr << \"* Loaded point cloud with \" << pointCloud.size() << \" points\\n\";\n\n std::vector<DataType> distances;\n\n if( selectedDistanceFunctor == \"euclidean\" )\n distances = pairwiseDistances( pointCloud, EuclideanDistance() );\n else if( selectedDistanceFunctor == \"manhattan\" )\n distances = pairwiseDistances( pointCloud, ManhattanDistance() );\n\n for( auto&& distance : distances )\n std::cout << distance << \"\\n\";\n}\n<commit_msg>Simple JSON output for distances<commit_after>#include <aleph\/containers\/PointCloud.hh>\n\n#include <aleph\/config\/FLANN.hh>\n\n#include <aleph\/geometry\/BruteForce.hh>\n#include <aleph\/geometry\/FLANN.hh>\n\n#include <aleph\/geometry\/distances\/Euclidean.hh>\n#include <aleph\/geometry\/distances\/Manhattan.hh>\n#include <aleph\/geometry\/distances\/Traits.hh>\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <getopt.h>\n\nusing DataType = double;\nusing PointCloud = aleph::containers::PointCloud<DataType>;\nusing EuclideanDistance = aleph::distances::Euclidean<DataType>;\nusing ManhattanDistance = aleph::distances::Manhattan<DataType>;\n\ntemplate <class Distance> std::vector<DataType> pairwiseDistances( const PointCloud& pointCloud, Distance distance = Distance() )\n{\n if( pointCloud.empty() )\n return {};\n\n std::vector<DataType> distances;\n distances.reserve( pointCloud.size() * ( pointCloud.size() - 1 ) \/ 2 );\n\n auto d = pointCloud.dimension();\n auto n = pointCloud.size();\n using Traits = aleph::distances::Traits<Distance>;\n\n Traits traits;\n for( decltype(n) i = 0; i < n; i++ )\n {\n for( decltype(n) j = i+1; j < n; j++ )\n {\n auto dist = distance( pointCloud[i].begin(),\n pointCloud[j].begin(),\n d );\n\n \/\/ I want to be sure that I get the *square* of the distance, but\n \/\/ I cannot take this transformation within the distance functor,\n \/\/ such as the Manhattan distance, for granted.\n dist = traits.from( dist );\n dist *= dist;\n\n distances.emplace_back( dist );\n }\n }\n\n return distances;\n}\n\ntemplate <class Container> void containerAsJSON( std::ostream& out, const Container& container, const std::string& name, unsigned indent = 2 )\n{\n out << std::string( indent, ' ' ) << \"\\\"\" << name << \"\\\": \"\n << \"[\";\n\n for( auto it = container.begin(); it != container.end(); ++it )\n {\n if( it != container.begin() )\n out << \",\";\n\n out << *it;\n }\n\n out << \"]\\n\";\n}\n\nint main( int argc, char** argv )\n{\n static option commandLineOptions[] =\n {\n { \"distance\" , required_argument, nullptr, 'd' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n std::string selectedDistanceFunctor = \"euclidean\";\n\n {\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"d:\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'd':\n selectedDistanceFunctor = optarg;\n break;\n }\n }\n }\n\n if( (argc - optind) < 1 )\n return -1;\n\n auto filename = std::string( argv[optind++] );\n auto pointCloud = aleph::containers::load<DataType>( filename );\n\n std::cerr << \"* Loaded point cloud with \" << pointCloud.size() << \" points\\n\";\n\n std::vector<DataType> distances;\n\n if( selectedDistanceFunctor == \"euclidean\" )\n distances = pairwiseDistances( pointCloud, EuclideanDistance() );\n else if( selectedDistanceFunctor == \"manhattan\" )\n distances = pairwiseDistances( pointCloud, ManhattanDistance() );\n\n std::cout << \"{\\n\";\n\n containerAsJSON( std::cout, distances, \"distances\" );\n\n std::cout << \"}\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <qml.h>\n#include \"qmlbindablevalue.h\"\n#include \"qmlbindablevalue_p.h\"\n#include <qmlcontext.h>\n#include <qmlinfo.h>\n#include <QVariant>\n#include <qfxperf.h>\n#include <QtCore\/qdebug.h>\n\nQ_DECLARE_METATYPE(QList<QObject *>);\n\nQT_BEGIN_NAMESPACE\n\nDEFINE_BOOL_CONFIG_OPTION(scriptWarnings, QML_SCRIPT_WARNINGS);\n\nQmlBindableValuePrivate::QmlBindableValuePrivate()\n: inited(false), updating(false), enabled(true), mePtr(0)\n{\n}\n\nQML_DEFINE_NOCREATE_TYPE(QmlBindableValue);\nQmlBindableValue::QmlBindableValue(void *data, QmlRefCount *rc, QObject *obj, QmlContext *ctxt, QObject *parent)\n: QmlPropertyValueSource(*new QmlBindableValuePrivate, parent), QmlExpression(ctxt, data, rc, obj)\n{\n}\n\nQmlBindableValue::QmlBindableValue(const QString &str, QObject *obj, QmlContext *ctxt, QObject *parent)\n: QmlPropertyValueSource(*new QmlBindableValuePrivate, parent), QmlExpression(ctxt, str, obj)\n{\n}\n\nQmlBindableValue::~QmlBindableValue()\n{\n Q_D(QmlBindableValue);\n if(d->mePtr)\n *(d->mePtr) = 0;\n}\n\nvoid QmlBindableValue::setTarget(const QmlMetaProperty &prop)\n{\n Q_D(QmlBindableValue);\n d->property = prop;\n\n update();\n}\n\nQmlMetaProperty QmlBindableValue::property() const \n{\n Q_D(const QmlBindableValue);\n return d->property; \n}\n\nvoid QmlBindableValue::init()\n{\n Q_D(QmlBindableValue);\n\n if (d->inited)\n return;\n d->inited = true;\n update();\n}\n\nvoid QmlBindableValue::setExpression(const QString &expr)\n{\n QmlExpression::setExpression(expr);\n update();\n}\n\nvoid QmlBindableValue::forceUpdate()\n{\n Q_D(QmlBindableValue);\n if (!d->inited)\n init();\n else\n update();\n}\n\nvoid QmlBindableValue::update()\n{\n Q_D(QmlBindableValue);\n\n#ifdef Q_ENABLE_PERFORMANCE_LOG\n QFxPerfTimer<QFxPerf::BindableValueUpdate> bu;\n#endif\n if (!d->inited || !d->enabled)\n return;\n\n if (!d->updating) {\n d->updating = true;\n\n if (d->property.propertyCategory() == QmlMetaProperty::Bindable) {\n\n int idx = d->property.coreIndex();\n Q_ASSERT(idx != -1);\n\n void *a[1];\n QmlBindableValue *t = this;\n a[0] = (void *)&t;\n QMetaObject::metacall(d->property.object(), \n QMetaObject::WriteProperty,\n idx, a);\n\n } else {\n\n QVariant value = this->value();\n if ((uint)d->property.propertyType() >= QVariant::UserType &&\n value.type() == QVariant::String) {\n QmlMetaType::StringConverter con = QmlMetaType::customStringConverter(d->property.propertyType());\n if (con)\n value = con(value.toString());\n }\n\n if (d->property.propertyType() == QVariant::Url && \n value.canConvert(QVariant::String) && !value.isNull()) \n value.setValue(context()->resolvedUrl(QUrl(value.toString())));\n\n d->property.write(value);\n }\n\n d->updating = false;\n } else {\n qmlInfo(d->property.object()) << \"Binding loop detected for property\" << d->property.name();\n }\n}\n\nvoid QmlBindableValue::valueChanged()\n{\n update();\n}\n\nvoid QmlBindableValue::setEnabled(bool e)\n{\n Q_D(QmlBindableValue);\n d->enabled = e;\n setTrackChange(e);\n}\n\nbool QmlBindableValue::enabled() const\n{\n Q_D(const QmlBindableValue);\n\n return d->enabled;\n}\n\nQT_END_NAMESPACE\n<commit_msg>URL can convert from string or bytearray.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <qml.h>\n#include \"qmlbindablevalue.h\"\n#include \"qmlbindablevalue_p.h\"\n#include <qmlcontext.h>\n#include <qmlinfo.h>\n#include <QVariant>\n#include <qfxperf.h>\n#include <QtCore\/qdebug.h>\n\nQ_DECLARE_METATYPE(QList<QObject *>);\n\nQT_BEGIN_NAMESPACE\n\nDEFINE_BOOL_CONFIG_OPTION(scriptWarnings, QML_SCRIPT_WARNINGS);\n\nQmlBindableValuePrivate::QmlBindableValuePrivate()\n: inited(false), updating(false), enabled(true), mePtr(0)\n{\n}\n\nQML_DEFINE_NOCREATE_TYPE(QmlBindableValue);\nQmlBindableValue::QmlBindableValue(void *data, QmlRefCount *rc, QObject *obj, QmlContext *ctxt, QObject *parent)\n: QmlPropertyValueSource(*new QmlBindableValuePrivate, parent), QmlExpression(ctxt, data, rc, obj)\n{\n}\n\nQmlBindableValue::QmlBindableValue(const QString &str, QObject *obj, QmlContext *ctxt, QObject *parent)\n: QmlPropertyValueSource(*new QmlBindableValuePrivate, parent), QmlExpression(ctxt, str, obj)\n{\n}\n\nQmlBindableValue::~QmlBindableValue()\n{\n Q_D(QmlBindableValue);\n if(d->mePtr)\n *(d->mePtr) = 0;\n}\n\nvoid QmlBindableValue::setTarget(const QmlMetaProperty &prop)\n{\n Q_D(QmlBindableValue);\n d->property = prop;\n\n update();\n}\n\nQmlMetaProperty QmlBindableValue::property() const \n{\n Q_D(const QmlBindableValue);\n return d->property; \n}\n\nvoid QmlBindableValue::init()\n{\n Q_D(QmlBindableValue);\n\n if (d->inited)\n return;\n d->inited = true;\n update();\n}\n\nvoid QmlBindableValue::setExpression(const QString &expr)\n{\n QmlExpression::setExpression(expr);\n update();\n}\n\nvoid QmlBindableValue::forceUpdate()\n{\n Q_D(QmlBindableValue);\n if (!d->inited)\n init();\n else\n update();\n}\n\nvoid QmlBindableValue::update()\n{\n Q_D(QmlBindableValue);\n\n#ifdef Q_ENABLE_PERFORMANCE_LOG\n QFxPerfTimer<QFxPerf::BindableValueUpdate> bu;\n#endif\n if (!d->inited || !d->enabled)\n return;\n\n if (!d->updating) {\n d->updating = true;\n\n if (d->property.propertyCategory() == QmlMetaProperty::Bindable) {\n\n int idx = d->property.coreIndex();\n Q_ASSERT(idx != -1);\n\n void *a[1];\n QmlBindableValue *t = this;\n a[0] = (void *)&t;\n QMetaObject::metacall(d->property.object(), \n QMetaObject::WriteProperty,\n idx, a);\n\n } else {\n\n QVariant value = this->value();\n if ((uint)d->property.propertyType() >= QVariant::UserType &&\n value.type() == QVariant::String) {\n QmlMetaType::StringConverter con = QmlMetaType::customStringConverter(d->property.propertyType());\n if (con)\n value = con(value.toString());\n }\n\n if (d->property.propertyType() == QVariant::Url && \n (value.type() == QVariant::String || value.type() == QVariant::ByteArray) && !value.isNull()) \n value.setValue(context()->resolvedUrl(QUrl(value.toString())));\n\n d->property.write(value);\n }\n\n d->updating = false;\n } else {\n qmlInfo(d->property.object()) << \"Binding loop detected for property\" << d->property.name();\n }\n}\n\nvoid QmlBindableValue::valueChanged()\n{\n update();\n}\n\nvoid QmlBindableValue::setEnabled(bool e)\n{\n Q_D(QmlBindableValue);\n d->enabled = e;\n setTrackChange(e);\n}\n\nbool QmlBindableValue::enabled() const\n{\n Q_D(const QmlBindableValue);\n\n return d->enabled;\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkAVIWriter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkWindows.h\"\n#include \"vtkAVIWriter.h\"\n\n#include \"vtkImageData.h\"\n#include \"vtkInformation.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n\n#include \"vtkErrorCode.h\"\n\n#ifdef _MSC_VER\n#pragma warning (push, 3)\n#endif\n\n#include <vfw.h>\n\n#ifdef _MSC_VER\n#pragma warning (pop)\n#endif\n\nclass vtkAVIWriterInternal\n{\npublic:\n PAVISTREAM Stream;\n PAVISTREAM StreamCompressed;\n PAVIFILE AVIFile;\n LPBITMAPINFOHEADER lpbi; \/\/ pointer to BITMAPINFOHEADER\n HANDLE hDIB; \/\/ handle to DIB, temp handle\n};\n\n\/\/---------------------------------------------------------------------------\nvtkStandardNewMacro(vtkAVIWriter);\n\n\/\/---------------------------------------------------------------------------\nvtkAVIWriter::vtkAVIWriter()\n{\n this->Internals = new vtkAVIWriterInternal;\n this->Internals->Stream = NULL;\n this->Internals->StreamCompressed = NULL;\n this->Internals->AVIFile = NULL;\n this->Time = 0;\n this->Quality = 10000;\n this->Rate = 1000;\n this->Internals->hDIB = NULL; \/\/ handle to DIB, temp handle\n this->PromptCompressionOptions = 0;\n this->CompressorFourCC = NULL;\n this->SetCompressorFourCC(\"MSVC\");\n}\n\n\/\/---------------------------------------------------------------------------\nvtkAVIWriter::~vtkAVIWriter()\n{\n if (this->Internals->AVIFile)\n {\n this->End();\n }\n delete this->Internals;\n this->SetCompressorFourCC(NULL);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkAVIWriter::Start()\n{\n \/\/ Error checking\n this->Error = 1;\n if ( this->GetInput() == NULL )\n {\n vtkErrorMacro(<<\"Write:Please specify an input!\");\n this->SetErrorCode(vtkGenericMovieWriter::NoInputError);\n return;\n }\n if (!this->FileName)\n {\n vtkErrorMacro(<<\"Write:Please specify a FileName\");\n this->SetErrorCode(vtkErrorCode::NoFileNameError);\n return;\n }\n\n \/\/ Fill in image information.\n this->GetInputAlgorithm(0, 0)->UpdateInformation();\n int wExtent[6];\n this->GetInputInformation(0,0)->Get(\n vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExtent);\n int inputAlgPort;\n vtkAlgorithm* inputAlg = this->GetInputAlgorithm(0, 0, inputAlgPort);\n inputAlg->SetUpdateExtentToWholeExtent(inputAlgPort);\n\n LONG hr;\n AVISTREAMINFO strhdr;\n\n AVIFileInit();\n \/\/ opens AVIFile library\n hr = AVIFileOpen(&this->Internals->AVIFile, this->FileName,\n OF_WRITE | OF_CREATE, 0L);\n if (hr != 0)\n {\n vtkErrorMacro(\"Unable to open \" << this->FileName);\n this->SetErrorCode(vtkErrorCode::CannotOpenFileError);\n return;\n }\n\n \/\/ Fill in the header for the video stream....\n \/\/ The video stream will run in 15ths of a second....\n memset(&strhdr, 0, sizeof(strhdr));\n strhdr.fccType = streamtypeVIDEO;\/\/ stream type\n strhdr.fccHandler = 0;\n strhdr.dwScale = 1;\n strhdr.dwRate = this->Rate;\n strhdr.dwQuality = (DWORD) -1;\n strhdr.dwSuggestedBufferSize = (wExtent[1] - wExtent[0] + 1)*\n (wExtent[3] - wExtent[2] + 1)*3;\n SetRect(&strhdr.rcFrame, 0, 0, wExtent[1] - wExtent[0] + 1,\n wExtent[3] - wExtent[2] + 1);\n\n \/\/ And create the stream;\n AVIFileCreateStream(this->Internals->AVIFile, \/\/ file pointer\n &this->Internals->Stream, \/\/ returned stream pointer\n &strhdr); \/\/ stream header\n\n \/\/ do not want to display this dialog\n AVICOMPRESSOPTIONS opts;\n AVICOMPRESSOPTIONS FAR * aopts[1] = {&opts};\n memset(&opts, 0, sizeof(opts));\n\n \/\/ need to setup opts\n opts.fccType = 0;\n char fourcc[4] = {' ', ' ', ' ', ' '};\n if (this->CompressorFourCC)\n {\n size_t len = strlen(this->CompressorFourCC);\n memcpy(fourcc, this->CompressorFourCC, len > 4 ? 4 : len);\n }\n opts.fccHandler=mmioFOURCC(fourcc[0], fourcc[1], fourcc[2], fourcc[3]);\n switch (this->GetQuality())\n {\n case 0:\n opts.dwQuality = 2500;\n break;\n case 1:\n opts.dwQuality = 5000;\n break;\n default:\n opts.dwQuality = 10000;\n break;\n }\n\n opts.dwBytesPerSecond = 0;\n opts.dwFlags = AVICOMPRESSF_VALID;\n\n if (this->PromptCompressionOptions)\n {\n if (!AVISaveOptions(NULL, 0,\n 1, &this->Internals->Stream,\n (LPAVICOMPRESSOPTIONS FAR *) &aopts))\n {\n vtkErrorMacro(\"Unable to save \" << this->FileName);\n return;\n }\n }\n\n if (AVIMakeCompressedStream(&this->Internals->StreamCompressed,\n this->Internals->Stream,\n &opts, NULL) != AVIERR_OK)\n {\n vtkErrorMacro(\"Unable to compress \" << this->FileName);\n this->SetErrorCode(vtkGenericMovieWriter::CanNotCompress);\n return;\n }\n\n DWORD dwLen; \/\/ size of memory block\n int dataWidth = (((wExtent[1] - wExtent[0] + 1)*3+3)\/4)*4;\n\n dwLen = sizeof(BITMAPINFOHEADER) + dataWidth*(wExtent[3] - wExtent[2] + 1);\n this->Internals->hDIB = ::GlobalAlloc(GHND, dwLen);\n this->Internals->lpbi = (LPBITMAPINFOHEADER) ::GlobalLock(this->Internals->hDIB);\n\n this->Internals->lpbi->biSize = sizeof(BITMAPINFOHEADER);\n this->Internals->lpbi->biWidth = wExtent[1] - wExtent[0] + 1;\n this->Internals->lpbi->biHeight = wExtent[3] - wExtent[2] + 1;\n this->Internals->lpbi->biPlanes = 1;\n this->Internals->lpbi->biBitCount = 24;\n this->Internals->lpbi->biCompression = BI_RGB;\n this->Internals->lpbi->biClrUsed = 0;\n this->Internals->lpbi->biClrImportant = 0;\n this->Internals->lpbi->biSizeImage = dataWidth*(wExtent[3] - wExtent[2] + 1);\n\n if (AVIStreamSetFormat(this->Internals->StreamCompressed, 0,\n this->Internals->lpbi, this->Internals->lpbi->biSize))\n {\n vtkErrorMacro(\"Unable to format \" << this->FileName << \" Most likely this means that the video compression scheme you seleted could not handle the data. Try selecting a different compression scheme.\" );\n this->SetErrorCode(vtkGenericMovieWriter::CanNotFormat);\n return;\n }\n\n this->Error = 0;\n this->Time = 0;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkAVIWriter::Write()\n{\n if (this->Error)\n {\n return;\n }\n\n \/\/ get the data\n vtkImageData* input = this->GetImageDataInput(0);\n this->GetInputAlgorithm(0, 0)->UpdateWholeExtent();\n int *wExtent = input->GetExtent();\n\n \/\/ get the pointer to the data\n unsigned char *ptr =\n (unsigned char *)(input->GetScalarPointer());\n\n int dataWidth = (((wExtent[1] - wExtent[0] + 1)*3+3)\/4)*4;\n int srcWidth = (wExtent[1] - wExtent[0] + 1)*3;\n\n \/\/ copy the data to the clipboard\n unsigned char *dest\n = (unsigned char *)this->Internals->lpbi + this->Internals->lpbi->biSize;\n int i,j;\n for (i = 0; i < this->Internals->lpbi->biHeight; i++)\n {\n for (j = 0; j < this->Internals->lpbi->biWidth; j++)\n {\n *dest++ = ptr[2];\n *dest++ = ptr[1];\n *dest++ = *ptr;\n ptr += 3;\n }\n dest = dest + (dataWidth - srcWidth);\n }\n\n AVIStreamWrite(this->Internals->StreamCompressed, \/\/ stream pointer\n this->Time, \/\/ time of this frame\n 1, \/\/ number to write\n (LPBYTE) this->Internals->lpbi + \/\/ pointer to data\n this->Internals->lpbi->biSize,\n this->Internals->lpbi->biSizeImage, \/\/ size of this frame\n AVIIF_KEYFRAME, \/\/ flags....\n NULL, NULL);\n this->Time++;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkAVIWriter::End()\n{\n ::GlobalUnlock(this->Internals->hDIB);\n if (this->Internals->Stream)\n {\n AVIStreamClose(this->Internals->Stream);\n this->Internals->Stream = NULL;\n }\n\n if (this->Internals->StreamCompressed)\n {\n AVIStreamClose(this->Internals->StreamCompressed);\n this->Internals->StreamCompressed = NULL;\n }\n\n if (this->Internals->AVIFile)\n {\n AVIFileClose(this->Internals->AVIFile);\n this->Internals->AVIFile = NULL;\n }\n\n AVIFileExit(); \/\/ releases AVIFile library\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkAVIWriter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Rate: \" << this->Rate << endl;\n os << indent << \"Quality: \" << this->Quality << endl;\n os << indent << \"PromptCompressionOptions: \" << (this->GetPromptCompressionOptions() ? \"on\":\"off\") << endl;\n os << indent << \"CompressorFourCC: \"\n << (this->CompressorFourCC ? this->CompressorFourCC : \"(None)\") << endl;\n}\n\n<commit_msg>vtkAVIWriter: make a more informative error message<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkAVIWriter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkWindows.h\"\n#include \"vtkAVIWriter.h\"\n\n#include \"vtkImageData.h\"\n#include \"vtkInformation.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n\n#include \"vtkErrorCode.h\"\n\n#ifdef _MSC_VER\n#pragma warning (push, 3)\n#endif\n\n#include <vfw.h>\n\n#ifdef _MSC_VER\n#pragma warning (pop)\n#endif\n\nclass vtkAVIWriterInternal\n{\npublic:\n PAVISTREAM Stream;\n PAVISTREAM StreamCompressed;\n PAVIFILE AVIFile;\n LPBITMAPINFOHEADER lpbi; \/\/ pointer to BITMAPINFOHEADER\n HANDLE hDIB; \/\/ handle to DIB, temp handle\n};\n\n\/\/---------------------------------------------------------------------------\nvtkStandardNewMacro(vtkAVIWriter);\n\n\/\/---------------------------------------------------------------------------\nvtkAVIWriter::vtkAVIWriter()\n{\n this->Internals = new vtkAVIWriterInternal;\n this->Internals->Stream = NULL;\n this->Internals->StreamCompressed = NULL;\n this->Internals->AVIFile = NULL;\n this->Time = 0;\n this->Quality = 10000;\n this->Rate = 1000;\n this->Internals->hDIB = NULL; \/\/ handle to DIB, temp handle\n this->PromptCompressionOptions = 0;\n this->CompressorFourCC = NULL;\n this->SetCompressorFourCC(\"MSVC\");\n}\n\n\/\/---------------------------------------------------------------------------\nvtkAVIWriter::~vtkAVIWriter()\n{\n if (this->Internals->AVIFile)\n {\n this->End();\n }\n delete this->Internals;\n this->SetCompressorFourCC(NULL);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkAVIWriter::Start()\n{\n \/\/ Error checking\n this->Error = 1;\n if ( this->GetInput() == NULL )\n {\n vtkErrorMacro(<<\"Write:Please specify an input!\");\n this->SetErrorCode(vtkGenericMovieWriter::NoInputError);\n return;\n }\n if (!this->FileName)\n {\n vtkErrorMacro(<<\"Write:Please specify a FileName\");\n this->SetErrorCode(vtkErrorCode::NoFileNameError);\n return;\n }\n\n \/\/ Fill in image information.\n this->GetInputAlgorithm(0, 0)->UpdateInformation();\n int wExtent[6];\n this->GetInputInformation(0,0)->Get(\n vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExtent);\n int inputAlgPort;\n vtkAlgorithm* inputAlg = this->GetInputAlgorithm(0, 0, inputAlgPort);\n inputAlg->SetUpdateExtentToWholeExtent(inputAlgPort);\n\n LONG hr;\n AVISTREAMINFO strhdr;\n\n AVIFileInit();\n \/\/ opens AVIFile library\n hr = AVIFileOpen(&this->Internals->AVIFile, this->FileName,\n OF_WRITE | OF_CREATE, 0L);\n if (hr != 0)\n {\n vtkErrorMacro(\"Unable to open \" << this->FileName);\n this->SetErrorCode(vtkErrorCode::CannotOpenFileError);\n return;\n }\n\n \/\/ Fill in the header for the video stream....\n \/\/ The video stream will run in 15ths of a second....\n memset(&strhdr, 0, sizeof(strhdr));\n strhdr.fccType = streamtypeVIDEO;\/\/ stream type\n strhdr.fccHandler = 0;\n strhdr.dwScale = 1;\n strhdr.dwRate = this->Rate;\n strhdr.dwQuality = (DWORD) -1;\n strhdr.dwSuggestedBufferSize = (wExtent[1] - wExtent[0] + 1)*\n (wExtent[3] - wExtent[2] + 1)*3;\n SetRect(&strhdr.rcFrame, 0, 0, wExtent[1] - wExtent[0] + 1,\n wExtent[3] - wExtent[2] + 1);\n\n \/\/ And create the stream;\n AVIFileCreateStream(this->Internals->AVIFile, \/\/ file pointer\n &this->Internals->Stream, \/\/ returned stream pointer\n &strhdr); \/\/ stream header\n\n \/\/ do not want to display this dialog\n AVICOMPRESSOPTIONS opts;\n AVICOMPRESSOPTIONS FAR * aopts[1] = {&opts};\n memset(&opts, 0, sizeof(opts));\n\n \/\/ need to setup opts\n opts.fccType = 0;\n char fourcc[4] = {' ', ' ', ' ', ' '};\n if (this->CompressorFourCC)\n {\n size_t len = strlen(this->CompressorFourCC);\n memcpy(fourcc, this->CompressorFourCC, len > 4 ? 4 : len);\n }\n opts.fccHandler=mmioFOURCC(fourcc[0], fourcc[1], fourcc[2], fourcc[3]);\n switch (this->GetQuality())\n {\n case 0:\n opts.dwQuality = 2500;\n break;\n case 1:\n opts.dwQuality = 5000;\n break;\n default:\n opts.dwQuality = 10000;\n break;\n }\n\n opts.dwBytesPerSecond = 0;\n opts.dwFlags = AVICOMPRESSF_VALID;\n\n if (this->PromptCompressionOptions)\n {\n if (!AVISaveOptions(NULL, 0,\n 1, &this->Internals->Stream,\n (LPAVICOMPRESSOPTIONS FAR *) &aopts))\n {\n vtkErrorMacro(\"Unable to save \" << this->FileName);\n return;\n }\n }\n\n int avierr = AVIMakeCompressedStream(&this->Internals->StreamCompressed,\n this->Internals->Stream,\n &opts, NULL);\n if (avierr != AVIERR_OK)\n {\n vtkErrorMacro(\"Unable to compress \" << this->FileName << \": \" <<\n (avierr == AVIERR_NOCOMPRESSOR ? \"unknown compressor\" :\n (avierr == AVIERR_MEMORY ? \"not enough memory\" :\n (avierr == AVIERR_UNSUPPORTED ? \"unsupported data type\" :\n \"unknown error\"))));\n this->SetErrorCode(vtkGenericMovieWriter::CanNotCompress);\n return;\n }\n\n DWORD dwLen; \/\/ size of memory block\n int dataWidth = (((wExtent[1] - wExtent[0] + 1)*3+3)\/4)*4;\n\n dwLen = sizeof(BITMAPINFOHEADER) + dataWidth*(wExtent[3] - wExtent[2] + 1);\n this->Internals->hDIB = ::GlobalAlloc(GHND, dwLen);\n this->Internals->lpbi = (LPBITMAPINFOHEADER) ::GlobalLock(this->Internals->hDIB);\n\n this->Internals->lpbi->biSize = sizeof(BITMAPINFOHEADER);\n this->Internals->lpbi->biWidth = wExtent[1] - wExtent[0] + 1;\n this->Internals->lpbi->biHeight = wExtent[3] - wExtent[2] + 1;\n this->Internals->lpbi->biPlanes = 1;\n this->Internals->lpbi->biBitCount = 24;\n this->Internals->lpbi->biCompression = BI_RGB;\n this->Internals->lpbi->biClrUsed = 0;\n this->Internals->lpbi->biClrImportant = 0;\n this->Internals->lpbi->biSizeImage = dataWidth*(wExtent[3] - wExtent[2] + 1);\n\n if (AVIStreamSetFormat(this->Internals->StreamCompressed, 0,\n this->Internals->lpbi, this->Internals->lpbi->biSize))\n {\n vtkErrorMacro(\"Unable to format \" << this->FileName << \" Most likely this means that the video compression scheme you seleted could not handle the data. Try selecting a different compression scheme.\" );\n this->SetErrorCode(vtkGenericMovieWriter::CanNotFormat);\n return;\n }\n\n this->Error = 0;\n this->Time = 0;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkAVIWriter::Write()\n{\n if (this->Error)\n {\n return;\n }\n\n \/\/ get the data\n vtkImageData* input = this->GetImageDataInput(0);\n this->GetInputAlgorithm(0, 0)->UpdateWholeExtent();\n int *wExtent = input->GetExtent();\n\n \/\/ get the pointer to the data\n unsigned char *ptr =\n (unsigned char *)(input->GetScalarPointer());\n\n int dataWidth = (((wExtent[1] - wExtent[0] + 1)*3+3)\/4)*4;\n int srcWidth = (wExtent[1] - wExtent[0] + 1)*3;\n\n \/\/ copy the data to the clipboard\n unsigned char *dest\n = (unsigned char *)this->Internals->lpbi + this->Internals->lpbi->biSize;\n int i,j;\n for (i = 0; i < this->Internals->lpbi->biHeight; i++)\n {\n for (j = 0; j < this->Internals->lpbi->biWidth; j++)\n {\n *dest++ = ptr[2];\n *dest++ = ptr[1];\n *dest++ = *ptr;\n ptr += 3;\n }\n dest = dest + (dataWidth - srcWidth);\n }\n\n AVIStreamWrite(this->Internals->StreamCompressed, \/\/ stream pointer\n this->Time, \/\/ time of this frame\n 1, \/\/ number to write\n (LPBYTE) this->Internals->lpbi + \/\/ pointer to data\n this->Internals->lpbi->biSize,\n this->Internals->lpbi->biSizeImage, \/\/ size of this frame\n AVIIF_KEYFRAME, \/\/ flags....\n NULL, NULL);\n this->Time++;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkAVIWriter::End()\n{\n ::GlobalUnlock(this->Internals->hDIB);\n if (this->Internals->Stream)\n {\n AVIStreamClose(this->Internals->Stream);\n this->Internals->Stream = NULL;\n }\n\n if (this->Internals->StreamCompressed)\n {\n AVIStreamClose(this->Internals->StreamCompressed);\n this->Internals->StreamCompressed = NULL;\n }\n\n if (this->Internals->AVIFile)\n {\n AVIFileClose(this->Internals->AVIFile);\n this->Internals->AVIFile = NULL;\n }\n\n AVIFileExit(); \/\/ releases AVIFile library\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkAVIWriter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Rate: \" << this->Rate << endl;\n os << indent << \"Quality: \" << this->Quality << endl;\n os << indent << \"PromptCompressionOptions: \" << (this->GetPromptCompressionOptions() ? \"on\":\"off\") << endl;\n os << indent << \"CompressorFourCC: \"\n << (this->CompressorFourCC ? this->CompressorFourCC : \"(None)\") << endl;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n* @file BodyStateProvider.h\n*\n* @author <a href=\"mailto:mellmann@informatik.hu-berlin.de\">Heinrich Mellmann<\/a>\n* Implementation of class BodyStateProvider\n*\/\n\n#include \"BodyStateProvider.h\"\n\n\/\/ Debug\n#include \"Tools\/Debug\/DebugModify.h\"\n\nBodyStateProvider::BodyStateProvider()\n{\n\n}\n\nvoid BodyStateProvider::execute()\n{\n \/\/ update the fall down state (written by Heinrich Mellmann at 1 am in Magdeburg)\n updateTheFallDownState();\n\n \/\/ ... :)\n updateTheFootState();\n PLOT(\"BodyStateProvider:standByLeftFoot\", getBodyState().standByLeftFoot);\n PLOT(\"BodyStateProvider:standByRightFoot\", getBodyState().standByRightFoot);\n PLOT(\"BodyStateProvider:foot_state_time\", getFrameInfo().getTimeSince(getBodyState().foot_state_time));\n\n \/\/ \n updateTheLegTemperature();\n \n}\/\/end execute\n\nvoid BodyStateProvider::updateTheFootState()\n{\n bool old_standByLeftFoot = getBodyState().standByLeftFoot;\n bool old_standByRightFoot = getBodyState().standByRightFoot;\n\n getBodyState().standByLeftFoot = getFSRData().forceLeft() > theParams.foot_threshold;\n getBodyState().standByRightFoot = getFSRData().forceRight() > theParams.foot_threshold;\n\n if(old_standByLeftFoot != getBodyState().standByLeftFoot ||\n old_standByRightFoot != getBodyState().standByRightFoot)\n {\n getBodyState().foot_state_time = getFrameInfo().getTime();\n }\n}\/\/end updateTheFootState\n\n\nvoid BodyStateProvider::updateTheFallDownState()\n{\n BodyState::State old_fall_down_state = getBodyState().fall_down_state;\n\n \/\/ buffer the inertial data\n inertialBuffer.add(getInertialSensorData().data);\n\n Vector2d avg = inertialBuffer.getAverage();\n double inertialXaverage = avg.x;\n double inertialYaverage = avg.y;\n\n getBodyState().fall_down_state = BodyState::upright;\n\n if(inertialXaverage < -theParams.getup_threshold) {\n getBodyState().fall_down_state = BodyState::lying_on_left_side;\n } else if(inertialXaverage > theParams.getup_threshold) {\n getBodyState().fall_down_state = BodyState::lying_on_right_side;\n }\n\n if(inertialYaverage < -theParams.getup_threshold) {\n getBodyState().fall_down_state = BodyState::lying_on_back;\n } else if(inertialYaverage > theParams.getup_threshold) {\n getBodyState().fall_down_state = BodyState::lying_on_front;\n }\n\n if(old_fall_down_state != getBodyState().fall_down_state) {\n getBodyState().fall_down_state_time = getFrameInfo().getTime();\n }\n}\/\/end updateTheFallDownState\n\n\nvoid BodyStateProvider::updateTheLegTemperature()\n{\n static naoth::JointData::JointID leftLegId[] = \n {\n naoth::JointData::LHipPitch,\n naoth::JointData::LHipRoll,\n naoth::JointData::LKneePitch,\n naoth::JointData::LAnklePitch,\n naoth::JointData::LAnkleRoll\n };\n\n static naoth::JointData::JointID rightLegId[] = \n {\n naoth::JointData::RHipPitch,\n naoth::JointData::RHipRoll,\n naoth::JointData::RKneePitch,\n naoth::JointData::RAnklePitch,\n naoth::JointData::RAnkleRoll\n };\n\n double tempL(0);\n double tempR(0);\n\n for(int i = 0; i < 5; i++)\n {\n tempL = std::max(tempL, getSensorJointData().temperature[leftLegId[i]]);\n tempR = std::max(tempR, getSensorJointData().temperature[rightLegId[i]]);\n }\n\n getBodyState().temperatureLeftLeg = tempL;\n getBodyState().temperatureRightLeg = tempR;\n}\/\/end updateTheLegTemperature\n\nvoid BodyStateProvider::updateIsLiftedUp(){\n getBodyState().isLiftedUp = getBodyState().fall_down_state == BodyState::upright && \n !getBodyState().standByLeftFoot && \n !getBodyState().standByRightFoot && \/\/ no foot is on the ground\n getFrameInfo().getTimeSince(getBodyState().foot_state_time) > theParams.maxTimeForLiftUp;\n\n \n}<commit_msg>oops call updateIsLiftedUp<commit_after>\/**\n* @file BodyStateProvider.h\n*\n* @author <a href=\"mailto:mellmann@informatik.hu-berlin.de\">Heinrich Mellmann<\/a>\n* Implementation of class BodyStateProvider\n*\/\n\n#include \"BodyStateProvider.h\"\n\n\/\/ Debug\n#include \"Tools\/Debug\/DebugModify.h\"\n\nBodyStateProvider::BodyStateProvider()\n{\n\n}\n\nvoid BodyStateProvider::execute()\n{\n \/\/ update the fall down state (written by Heinrich Mellmann at 1 am in Magdeburg)\n updateTheFallDownState();\n\n \/\/ ... :)\n updateTheFootState();\n PLOT(\"BodyStateProvider:standByLeftFoot\", getBodyState().standByLeftFoot);\n PLOT(\"BodyStateProvider:standByRightFoot\", getBodyState().standByRightFoot);\n PLOT(\"BodyStateProvider:foot_state_time\", getFrameInfo().getTimeSince(getBodyState().foot_state_time));\n\n \/\/ \n updateTheLegTemperature();\n updateIsLiftedUp();\n \n}\/\/end execute\n\nvoid BodyStateProvider::updateTheFootState()\n{\n bool old_standByLeftFoot = getBodyState().standByLeftFoot;\n bool old_standByRightFoot = getBodyState().standByRightFoot;\n\n getBodyState().standByLeftFoot = getFSRData().forceLeft() > theParams.foot_threshold;\n getBodyState().standByRightFoot = getFSRData().forceRight() > theParams.foot_threshold;\n\n if(old_standByLeftFoot != getBodyState().standByLeftFoot ||\n old_standByRightFoot != getBodyState().standByRightFoot)\n {\n getBodyState().foot_state_time = getFrameInfo().getTime();\n }\n}\/\/end updateTheFootState\n\n\nvoid BodyStateProvider::updateTheFallDownState()\n{\n BodyState::State old_fall_down_state = getBodyState().fall_down_state;\n\n \/\/ buffer the inertial data\n inertialBuffer.add(getInertialSensorData().data);\n\n Vector2d avg = inertialBuffer.getAverage();\n double inertialXaverage = avg.x;\n double inertialYaverage = avg.y;\n\n getBodyState().fall_down_state = BodyState::upright;\n\n if(inertialXaverage < -theParams.getup_threshold) {\n getBodyState().fall_down_state = BodyState::lying_on_left_side;\n } else if(inertialXaverage > theParams.getup_threshold) {\n getBodyState().fall_down_state = BodyState::lying_on_right_side;\n }\n\n if(inertialYaverage < -theParams.getup_threshold) {\n getBodyState().fall_down_state = BodyState::lying_on_back;\n } else if(inertialYaverage > theParams.getup_threshold) {\n getBodyState().fall_down_state = BodyState::lying_on_front;\n }\n\n if(old_fall_down_state != getBodyState().fall_down_state) {\n getBodyState().fall_down_state_time = getFrameInfo().getTime();\n }\n}\/\/end updateTheFallDownState\n\n\nvoid BodyStateProvider::updateTheLegTemperature()\n{\n static naoth::JointData::JointID leftLegId[] = \n {\n naoth::JointData::LHipPitch,\n naoth::JointData::LHipRoll,\n naoth::JointData::LKneePitch,\n naoth::JointData::LAnklePitch,\n naoth::JointData::LAnkleRoll\n };\n\n static naoth::JointData::JointID rightLegId[] = \n {\n naoth::JointData::RHipPitch,\n naoth::JointData::RHipRoll,\n naoth::JointData::RKneePitch,\n naoth::JointData::RAnklePitch,\n naoth::JointData::RAnkleRoll\n };\n\n double tempL(0);\n double tempR(0);\n\n for(int i = 0; i < 5; i++)\n {\n tempL = std::max(tempL, getSensorJointData().temperature[leftLegId[i]]);\n tempR = std::max(tempR, getSensorJointData().temperature[rightLegId[i]]);\n }\n\n getBodyState().temperatureLeftLeg = tempL;\n getBodyState().temperatureRightLeg = tempR;\n}\/\/end updateTheLegTemperature\n\nvoid BodyStateProvider::updateIsLiftedUp(){\n getBodyState().isLiftedUp = getBodyState().fall_down_state == BodyState::upright && \n !getBodyState().standByLeftFoot && \n !getBodyState().standByRightFoot && \/\/ no foot is on the ground\n getFrameInfo().getTimeSince(getBodyState().foot_state_time) > theParams.maxTimeForLiftUp;\n\n \n}<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\n University of Utah.\n\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is 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\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n \\file TransferFunction1D.cpp\n \\author Jens Krueger\n SCI Institute\n University of Utah\n \\version 1.0\n \\date September 2008\n*\/\n\n#include \"TransferFunction1D.h\"\n#include <fstream>\n#include <memory.h>\n\nusing namespace std;\n\nTransferFunction1D::TransferFunction1D(size_t iSize) :\n m_vValueBBox(0,0)\n{\n Resize(iSize);\n}\n\nTransferFunction1D::TransferFunction1D(const std::string& filename) {\n Load(filename);\n}\n\nTransferFunction1D::~TransferFunction1D(void)\n{\n}\n\nvoid TransferFunction1D::Resize(size_t iSize) {\n vColorData.resize(iSize);\n}\n\nfloat TransferFunction1D::Smoothstep(float x) const {\n return 3*x*x-2*x*x*x;\n}\n\nvoid TransferFunction1D::SetStdFunction(float fCenterPoint, float fInvGradient) {\n SetStdFunction(fCenterPoint, fInvGradient,0);\n SetStdFunction(fCenterPoint, fInvGradient,1);\n SetStdFunction(fCenterPoint, fInvGradient,2);\n SetStdFunction(fCenterPoint, fInvGradient,3);\n}\n\nvoid TransferFunction1D::SetStdFunction(float fCenterPoint, float fInvGradient, int iComponent) {\n size_t iCenterPoint = size_t((vColorData.size()-1) * float(std::min<float>(std::max<float>(0,fCenterPoint),1)));\n size_t iInvGradient = size_t((vColorData.size()-1) * float(std::min<float>(std::max<float>(0,fInvGradient),1)));\n\n size_t iRampStartPoint = (iInvGradient\/2 > iCenterPoint) ? 0 : iCenterPoint-(iInvGradient\/2); \n size_t iRampEndPoint = (iInvGradient\/2 + iCenterPoint > vColorData.size()) ? vColorData.size() : iCenterPoint+(iInvGradient\/2);\n\n for (size_t i = 0;i<iRampStartPoint;i++) \n vColorData[i][iComponent] = 0;\n\n for (size_t i = iRampStartPoint;i<iRampEndPoint;i++) {\n float fValue = Smoothstep(float(i-iCenterPoint+(iInvGradient\/2))\/float(iInvGradient));\n vColorData[i][iComponent] = fValue;\n }\n\n for (size_t i = iRampEndPoint;i<vColorData.size();i++)\n vColorData[i][iComponent] = 1;\n\n ComputeNonZeroLimits();\n}\n\nvoid TransferFunction1D::Clear() {\n for (size_t i = 0;i<vColorData.size();i++)\n vColorData[i] = FLOATVECTOR4(0,0,0,0);\n\n m_vValueBBox = UINT64VECTOR2(0,0);\n}\n\nvoid TransferFunction1D::Resample(size_t iTargetSize) {\n size_t iSourceSize = vColorData.size();\n\n if (iTargetSize == iSourceSize) return;\n\n vector< FLOATVECTOR4 > vTmpColorData(iTargetSize);\n\n if (iTargetSize < iSourceSize) {\n \/\/ downsample\n size_t iFrom = 0;\n for (size_t i = 0;i<vTmpColorData.size();i++) {\n\n size_t iTo = iFrom + iSourceSize\/iTargetSize;\n\n vTmpColorData[i] = 0;\n for (size_t j = iFrom;j<iTo;j++) {\n vTmpColorData[i] += vColorData[j];\n }\n vTmpColorData[i] \/= float(iTo-iFrom);\n\n iTargetSize -= 1;\n iSourceSize -= iTo-iFrom;\n\n iFrom = iTo;\n }\n } else {\n \/\/ upsample\n for (size_t i = 0;i<vTmpColorData.size();i++) {\n float fPos = float(i) * float(iSourceSize-1)\/float(iTargetSize);\n size_t iFloor = size_t(floor(fPos));\n size_t iCeil = std::min(iFloor+1, vColorData.size()-1);\n float fInterp = fPos - float(iFloor);\n\n vTmpColorData[i] = vColorData[iFloor] * (1-fInterp) + vColorData[iCeil] * fInterp;\n }\n\n }\n\n vColorData = vTmpColorData;\n ComputeNonZeroLimits();\n}\n\nbool TransferFunction1D::Load(const std::string& filename, size_t iTargetSize) {\n if (!Load(filename)) {\n return false;\n } else {\n Resample(iTargetSize);\n return true;\n }\n}\n\n\nbool TransferFunction1D::Load(const std::string& filename) {\n ifstream file(filename.c_str());\n if (!Load(file)) return false;\n file.close();\n ComputeNonZeroLimits();\n return true;\n}\n\nbool TransferFunction1D::Load(ifstream& file, size_t iTargetSize) {\n if (!Load(file)) {\n return false;\n } else {\n Resample(iTargetSize);\n return true;\n }\n}\n\nbool TransferFunction1D::Save(const std::string& filename) const {\n ofstream file(filename.c_str());\n if (!Save(file)) return false;\n file.close();\n return true;\n}\n\nbool TransferFunction1D::Load(ifstream& file) {\n UINT32 iSize;\n file >> iSize;\n vColorData.resize(iSize);\n\n for(size_t i=0;i<vColorData.size();++i){\n for(size_t j=0;j<4;++j){\n file >> vColorData[i][j];\n }\n }\n\n return true;\n}\n\n\nbool TransferFunction1D::Save(ofstream& file) const {\n if (!file.is_open()) return false;\n\n file << vColorData.size() << endl;\n\n for(size_t i=0;i<vColorData.size();++i){\n for(size_t j=0;j<4;++j){\n file << vColorData[i][j] << \" \";\n }\n file << endl;\n }\n\n return true;\n}\n\n\nvoid TransferFunction1D::GetByteArray(unsigned char** pcData,\n unsigned char cUsedRange) const {\n if (*pcData == NULL) *pcData = new unsigned char[vColorData.size()*4];\n\n unsigned char *pcDataIterator = *pcData;\n for (size_t i = 0;i<vColorData.size();i++) {\n *pcDataIterator++ = (unsigned char)(vColorData[i][0]*cUsedRange);\n *pcDataIterator++ = (unsigned char)(vColorData[i][1]*cUsedRange);\n *pcDataIterator++ = (unsigned char)(vColorData[i][2]*cUsedRange);\n *pcDataIterator++ = (unsigned char)(vColorData[i][3]*cUsedRange);\n }\n}\n\nvoid TransferFunction1D::GetShortArray(unsigned short** psData,\n unsigned short sUsedRange) const {\n if (*psData == NULL) *psData = new unsigned short[vColorData.size()*4];\n\n unsigned short *psDataIterator = *psData;\n for (size_t i = 0;i<vColorData.size();i++) {\n *psDataIterator++ = (unsigned short)(vColorData[i][0]*sUsedRange);\n *psDataIterator++ = (unsigned short)(vColorData[i][1]*sUsedRange);\n *psDataIterator++ = (unsigned short)(vColorData[i][2]*sUsedRange);\n *psDataIterator++ = (unsigned short)(vColorData[i][3]*sUsedRange);\n }\n}\n\nvoid TransferFunction1D::GetFloatArray(float** pfData) const {\n if (*pfData == NULL) *pfData = new float[4*vColorData.size()];\n memcpy(*pfData, &pfData[0], sizeof(float)*4*vColorData.size());\n}\n\n\nvoid TransferFunction1D::ComputeNonZeroLimits() { \n m_vValueBBox = UINT64VECTOR2(UINT64(vColorData.size()),0);\n\n for (size_t i = 0;i<vColorData.size();i++) {\n if (vColorData[i][3] != 0) {\n m_vValueBBox.x = MIN(m_vValueBBox.x, i);\n m_vValueBBox.y = i;\n }\n }\n}\n<commit_msg>Don't do the allocation if we have no data to copy.<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\n University of Utah.\n\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is 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\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n \\file TransferFunction1D.cpp\n \\author Jens Krueger\n SCI Institute\n University of Utah\n \\version 1.0\n \\date September 2008\n*\/\n\n#include \"TransferFunction1D.h\"\n#include <fstream>\n#include <memory.h>\n\nusing namespace std;\n\nTransferFunction1D::TransferFunction1D(size_t iSize) :\n m_vValueBBox(0,0)\n{\n Resize(iSize);\n}\n\nTransferFunction1D::TransferFunction1D(const std::string& filename) {\n Load(filename);\n}\n\nTransferFunction1D::~TransferFunction1D(void)\n{\n}\n\nvoid TransferFunction1D::Resize(size_t iSize) {\n vColorData.resize(iSize);\n}\n\nfloat TransferFunction1D::Smoothstep(float x) const {\n return 3*x*x-2*x*x*x;\n}\n\nvoid TransferFunction1D::SetStdFunction(float fCenterPoint, float fInvGradient) {\n SetStdFunction(fCenterPoint, fInvGradient,0);\n SetStdFunction(fCenterPoint, fInvGradient,1);\n SetStdFunction(fCenterPoint, fInvGradient,2);\n SetStdFunction(fCenterPoint, fInvGradient,3);\n}\n\nvoid TransferFunction1D::SetStdFunction(float fCenterPoint, float fInvGradient, int iComponent) {\n size_t iCenterPoint = size_t((vColorData.size()-1) * float(std::min<float>(std::max<float>(0,fCenterPoint),1)));\n size_t iInvGradient = size_t((vColorData.size()-1) * float(std::min<float>(std::max<float>(0,fInvGradient),1)));\n\n size_t iRampStartPoint = (iInvGradient\/2 > iCenterPoint) ? 0 : iCenterPoint-(iInvGradient\/2); \n size_t iRampEndPoint = (iInvGradient\/2 + iCenterPoint > vColorData.size()) ? vColorData.size() : iCenterPoint+(iInvGradient\/2);\n\n for (size_t i = 0;i<iRampStartPoint;i++) \n vColorData[i][iComponent] = 0;\n\n for (size_t i = iRampStartPoint;i<iRampEndPoint;i++) {\n float fValue = Smoothstep(float(i-iCenterPoint+(iInvGradient\/2))\/float(iInvGradient));\n vColorData[i][iComponent] = fValue;\n }\n\n for (size_t i = iRampEndPoint;i<vColorData.size();i++)\n vColorData[i][iComponent] = 1;\n\n ComputeNonZeroLimits();\n}\n\nvoid TransferFunction1D::Clear() {\n for (size_t i = 0;i<vColorData.size();i++)\n vColorData[i] = FLOATVECTOR4(0,0,0,0);\n\n m_vValueBBox = UINT64VECTOR2(0,0);\n}\n\nvoid TransferFunction1D::Resample(size_t iTargetSize) {\n size_t iSourceSize = vColorData.size();\n\n if (iTargetSize == iSourceSize) return;\n\n vector< FLOATVECTOR4 > vTmpColorData(iTargetSize);\n\n if (iTargetSize < iSourceSize) {\n \/\/ downsample\n size_t iFrom = 0;\n for (size_t i = 0;i<vTmpColorData.size();i++) {\n\n size_t iTo = iFrom + iSourceSize\/iTargetSize;\n\n vTmpColorData[i] = 0;\n for (size_t j = iFrom;j<iTo;j++) {\n vTmpColorData[i] += vColorData[j];\n }\n vTmpColorData[i] \/= float(iTo-iFrom);\n\n iTargetSize -= 1;\n iSourceSize -= iTo-iFrom;\n\n iFrom = iTo;\n }\n } else {\n \/\/ upsample\n for (size_t i = 0;i<vTmpColorData.size();i++) {\n float fPos = float(i) * float(iSourceSize-1)\/float(iTargetSize);\n size_t iFloor = size_t(floor(fPos));\n size_t iCeil = std::min(iFloor+1, vColorData.size()-1);\n float fInterp = fPos - float(iFloor);\n\n vTmpColorData[i] = vColorData[iFloor] * (1-fInterp) + vColorData[iCeil] * fInterp;\n }\n\n }\n\n vColorData = vTmpColorData;\n ComputeNonZeroLimits();\n}\n\nbool TransferFunction1D::Load(const std::string& filename, size_t iTargetSize) {\n if (!Load(filename)) {\n return false;\n } else {\n Resample(iTargetSize);\n return true;\n }\n}\n\n\nbool TransferFunction1D::Load(const std::string& filename) {\n ifstream file(filename.c_str());\n if (!Load(file)) return false;\n file.close();\n ComputeNonZeroLimits();\n return true;\n}\n\nbool TransferFunction1D::Load(ifstream& file, size_t iTargetSize) {\n if (!Load(file)) {\n return false;\n } else {\n Resample(iTargetSize);\n return true;\n }\n}\n\nbool TransferFunction1D::Save(const std::string& filename) const {\n ofstream file(filename.c_str());\n if (!Save(file)) return false;\n file.close();\n return true;\n}\n\nbool TransferFunction1D::Load(ifstream& file) {\n UINT32 iSize;\n file >> iSize;\n vColorData.resize(iSize);\n\n for(size_t i=0;i<vColorData.size();++i){\n for(size_t j=0;j<4;++j){\n file >> vColorData[i][j];\n }\n }\n\n return true;\n}\n\n\nbool TransferFunction1D::Save(ofstream& file) const {\n if (!file.is_open()) return false;\n\n file << vColorData.size() << endl;\n\n for(size_t i=0;i<vColorData.size();++i){\n for(size_t j=0;j<4;++j){\n file << vColorData[i][j] << \" \";\n }\n file << endl;\n }\n\n return true;\n}\n\n\nvoid TransferFunction1D::GetByteArray(unsigned char** pcData,\n unsigned char cUsedRange) const {\n \/\/ bail out immediately if we've got no data\n if(vColorData.empty()) { return; }\n\n if (*pcData == NULL) *pcData = new unsigned char[vColorData.size()*4];\n\n unsigned char *pcDataIterator = *pcData;\n for (size_t i = 0;i<vColorData.size();i++) {\n *pcDataIterator++ = (unsigned char)(vColorData[i][0]*cUsedRange);\n *pcDataIterator++ = (unsigned char)(vColorData[i][1]*cUsedRange);\n *pcDataIterator++ = (unsigned char)(vColorData[i][2]*cUsedRange);\n *pcDataIterator++ = (unsigned char)(vColorData[i][3]*cUsedRange);\n }\n}\n\nvoid TransferFunction1D::GetShortArray(unsigned short** psData,\n unsigned short sUsedRange) const {\n \/\/ bail out immediately if we've got no data\n if(vColorData.empty()) { return; }\n\n if (*psData == NULL) *psData = new unsigned short[vColorData.size()*4];\n\n unsigned short *psDataIterator = *psData;\n for (size_t i = 0;i<vColorData.size();i++) {\n *psDataIterator++ = (unsigned short)(vColorData[i][0]*sUsedRange);\n *psDataIterator++ = (unsigned short)(vColorData[i][1]*sUsedRange);\n *psDataIterator++ = (unsigned short)(vColorData[i][2]*sUsedRange);\n *psDataIterator++ = (unsigned short)(vColorData[i][3]*sUsedRange);\n }\n}\n\nvoid TransferFunction1D::GetFloatArray(float** pfData) const {\n \/\/ bail out immediately if we've got no data\n if(vColorData.empty()) { return; }\n\n if (*pfData == NULL) *pfData = new float[4*vColorData.size()];\n memcpy(*pfData, &pfData[0], sizeof(float)*4*vColorData.size());\n}\n\n\nvoid TransferFunction1D::ComputeNonZeroLimits() { \n m_vValueBBox = UINT64VECTOR2(UINT64(vColorData.size()),0);\n\n for (size_t i = 0;i<vColorData.size();i++) {\n if (vColorData[i][3] != 0) {\n m_vValueBBox.x = MIN(m_vValueBBox.x, i);\n m_vValueBBox.y = i;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2015, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All rights reserved.\n * \n * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed\n * 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 * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n*\/\n\n\/**\n * @file ScarrArmModel.cpp\n * @brief Contains the implementation of class ScarrArmModel. \n * Measurements are scaled to average adult male\n * $Id$\n *\/\n\n\/\/ This module\n#include \"ScarrArmModel.h\"\n\/\/ This library\n#include \"core\/tgBasicActuator.h\"\n#include \"core\/tgRod.h\"\n#include \"core\/abstractMarker.h\"\n#include \"tgcreator\/tgBuildSpec.h\"\n#include \"tgcreator\/tgBasicActuatorInfo.h\"\n#include \"tgcreator\/tgRodInfo.h\"\n#include \"tgcreator\/tgStructure.h\"\n#include \"tgcreator\/tgStructureInfo.h\"\n\/\/ The Bullet Physics library\n#include \"LinearMath\/btVector3.h\"\n\/\/ The C++ Standard Library\n#include <stdexcept>\n\nnamespace\n{\n \/\/ see tgBaseString.h for a descripton of some of these rod parameters\n \/\/ (specifically, those related to the motor moving the strings.)\n \/\/ NOTE that any parameter that depends on units of length will scale\n \/\/ with the current gravity scaling. E.g., with gravity as 98.1,\n \/\/ the length units below are in decimeters.\n\n \/\/ Note: This current model of the SUPERball rod is 1.5m long by 3 cm radius,\n \/\/ which is 0.00424 m^3.\n \/\/ For SUPERball v1.5, mass = 3.5kg per strut, which comes out to \n \/\/ 0.825 kg \/ (decimeter^3).\n\n \/\/ similarly, frictional parameters are for the tgRod objects.\n const struct Config\n {\n double density;\n double radius;\n double stiffness;\n double damping;\n double rod_length;\n double rod_space; \n double friction;\n double rollFriction;\n double restitution;\n double pretension;\n bool history; \n double maxTens;\n double targetVelocity;\n } c =\n {\n 0.825, \/\/ density (kg \/ length^3)\n 0.31, \/\/ radius (length)\n 3000.0, \/\/ stiffness (kg \/ sec^2)\n 200.0, \/\/ damping (kg \/ sec)\n 15.0, \/\/ rod_length (length)\n 7.5, \/\/ rod_space (length)\n 1.0, \/\/ friction (unitless)\n 0.01, \/\/ rollFriction (unitless)\n 0.2, \/\/ restitution (?)\n 0, \/\/ pretension (force)\n false, \/\/ history (boolean)\n 100000, \/\/ maxTens\n 10000 \/\/ targetVelocity\n#if (0)\n 20000 \/\/ maxAcc\n#endif\n \/\/ Use the below values for earlier versions of simulation.\n \/\/ 1.006, \n \/\/ 0.31, \n \/\/ 300000.0, \n \/\/ 3000.0, \n \/\/ 15.0, \n \/\/ 7.5, \n };\n} \/\/ namespace\n\n\/*\n * helper arrays for node and rod numbering schema\n *\/\n\/*returns the number of the rod for a given node *\/\n\/\/const int rodNumbersPerNode[11]={0,1,2,3,3,4,0,1,2,5,5,4,6};\n\n\/*returns the node that is at the other end of the given node *\/\n\/\/const int otherEndOfTheRod[11]={6,7,8,4,3,11,0,1,2,10,9,5,12};\n\n\/*returns the node that is at the parallel rod\n * and at the same end of the given node\n *\/\n\/\/const int parallelNode[11]={1,0,5,9,10,2,7,6,11,3,4,8,12};\n\nScarrArmModel::ScarrArmModel() : tgModel() \n{\n}\n\nScarrArmModel::~ScarrArmModel()\n{\n}\n\nvoid ScarrArmModel::addNodes(tgStructure& s)\n{\n const double scale = 0.1;\n const size_t nNodes = 11;\n \n \/\/ Average Adult Male Measurements with scale\n \/\/ Lengths are in mm\n const double a = 22 * scale; \/\/2.2cm\n const double b = 265 * scale;\n const double c = 334 * scale;\n const double d = 66 * scale;\n const double e = 246 * scale;\n const double f = 25 * scale;\n const double g = 17 * scale;\n const double sigma = 1; \/\/TODO: tinker\n const double ulna_diameter = g*2; \/\/TODO: tinker\n const double x = a\/2;\n const double z = c\/2;\n\n nodePositions.push_back(btVector3(a\/2, 0, 0));\n nodePositions.push_back(btVector3(0, 0, -g));\n nodePositions.push_back(btVector3(-a\/2, 0, 0));\n nodePositions.push_back(btVector3(0, f, 0));\n nodePositions.push_back(btVector3(0, -f, 0));\n nodePositions.push_back(btVector3(0, 0, d));\n nodePositions.push_back(btVector3(0, 0, c));\n nodePositions.push_back(btVector3(x, 0, z));\n nodePositions.push_back(btVector3(b+a\/2, 0, 0));\n nodePositions.push_back(btVector3(a\/2 + sigma, 0, -ulna_diameter));\n nodePositions.push_back(btVector3(a\/2 + sigma + e, 0, -ulna_diameter));\n\n for(size_t i=0;i<nNodes;i++) {\n\t\ts.addNode(nodePositions[i][0],nodePositions[i][1],nodePositions[i][2]);\n }\n}\n\nvoid ScarrArmModel::addRods(tgStructure& s)\n{\n s.addPair(5, 6, \"massless rod\");\n s.addPair(5, 6, \"rod\");\n s.addPair(3, 5, \"rod\");\n s.addPair(4, 5, \"rod\");\n\n s.addPair(0, 1, \"rod\");\n s.addPair(0, 8, \"rod\");\n s.addPair(1, 2, \"rod\");\n\n s.addPair(9, 10, \"rod\"); \n}\n\n\/*\nvoid ScarrArmModel::addMarkers(tgStructure &s)\n{\n std::vector<tgRod *> rods=find<tgRod>(\"rod\");\n\n\tfor(int i=0;i<10;i++)\n\t{\n\t\tconst btRigidBody* bt = rods[rodNumbersPerNode[i]]->getPRigidBody();\n\t\tbtTransform inverseTransform = bt->getWorldTransform().inverse();\n\t\tbtVector3 pos = inverseTransform * (nodePositions[i]);\n\t\tabstractMarker tmp=abstractMarker(bt,pos,btVector3(0.08*i,1.0 - 0.08*i,.0),i);\n\t\tthis->addMarker(tmp);\n\t}\n}\n*\/\n\nvoid ScarrArmModel::addMuscles(tgStructure& s)\n{\n s.addPair(0, 3, \"muscle\");\n s.addPair(0, 4, \"muscle\");\n s.addPair(1, 3, \"muscle\");\n s.addPair(1, 4, \"muscle\");\n s.addPair(2, 3, \"muscle\");\n s.addPair(2, 4, \"muscle\");\n s.addPair(3, 9, \"muscle\");\n s.addPair(4, 9, \"muscle\");\n \/\/s.addPair(5, 7, \"muscle\");\n \/\/s.addPair(6, 7, \"muscle\");\n \/\/s.addPair(7, 8, \"muscle\"); \n s.addPair(6, 8, \"muscle\"); \n s.addPair(8, 10, \"muscle\"); \n}\n\nvoid ScarrArmModel::setup(tgWorld& world)\n{\n\n const tgRod::Config rodConfig(c.radius, c.density, c.friction, c.rollFriction, c.restitution);\n const tgRod::Config rodConfigMassless(c.radius, 0.001\/*c.density*\/, c.friction, c.rollFriction, c.restitution); \/\/TODO: Fix\n \/\/\/ @todo acceleration constraint was removed on 12\/10\/14 Replace with tgKinematicActuator as appropreate\n tgBasicActuator::Config muscleConfig(c.stiffness, c.damping, c.pretension, c.history, c.maxTens, c.targetVelocity);\n \n \/\/ Start creating the structure\n tgStructure s;\n addNodes(s);\n addRods(s);\n addMuscles(s);\n\n\/\/ \/\/ Add a rotation. This is needed if the ground slopes too much, otherwise glitches put a rod below the ground.\n\/\/ btVector3 rotationPoint = btVector3(0, 0, 0); \/\/ origin\n\/\/ btVector3 rotationAxis = btVector3(0, 1, 0); \/\/ y-axis\n\/\/ double rotationAngle = M_PI\/2;\n\/\/ s.addRotation(rotationPoint, rotationAxis, rotationAngle);\n\/\/ s.move(btVector3(0,30,0));\n\n \/\/ Create the build spec that uses tags to turn the structure into a real model\n tgBuildSpec spec;\n spec.addBuilder(\"massless rod\", new tgRodInfo(rodConfigMassless));\n spec.addBuilder(\"rod\", new tgRodInfo(rodConfig));\n spec.addBuilder(\"muscle\", new tgBasicActuatorInfo(muscleConfig));\n \n \/\/ Create your structureInfo\n tgStructureInfo structureInfo(s, spec);\n\n \/\/ Use the structureInfo to build ourselves\n structureInfo.buildInto(*this, world);\n\n \/\/ We could now use tgCast::filter or similar to pull out the\n \/\/ models (e.g. muscles) that we want to control. \n allMuscles = tgCast::filter<tgModel, tgBasicActuator> (getDescendants());\n\n \/\/ call the onSetup methods of all observed things e.g. controllers\n notifySetup();\n\n \/\/ Actually setup the children\n tgModel::setup(world);\n\n \/\/map the rods and add the markers to them\n \/\/addMarkers(s);\n\n btVector3 location(0,10.0,0);\n \/\/btVector3 rotation(M_PI\/2,0,0);\n btVector3 rotation(0,0,0);\n \tbtVector3 speed(0,0,0);\n this->moveModel(location,rotation,speed);\n}\n\nvoid ScarrArmModel::step(double dt)\n{\n \/\/ Precondition\n if (dt <= 0.0)\n {\n throw std::invalid_argument(\"dt is not positive\");\n }\n else\n {\n \/\/ Notify observers (controllers) of the step so that they can take action\n notifyStep(dt);\n tgModel::step(dt); \/\/ Step any children\n }\n}\n\nvoid ScarrArmModel::onVisit(tgModelVisitor& r)\n{\n tgModel::onVisit(r);\n}\n\nconst std::vector<tgBasicActuator*>& ScarrArmModel::getAllMuscles() const\n{\n return allMuscles;\n}\n \nvoid ScarrArmModel::teardown()\n{\n tgModel::teardown();\n}\n\nvoid ScarrArmModel::moveModel(btVector3 positionVector,btVector3 rotationVector,btVector3 speedVector)\n{\n std::vector<tgRod *> rods=find<tgRod>(\"rod\");\n\n\tbtQuaternion initialRotationQuat;\n\tinitialRotationQuat.setEuler(rotationVector[0],rotationVector[1],rotationVector[2]);\n\tbtTransform initialTransform;\n\tinitialTransform.setIdentity();\n\tinitialTransform.setRotation(initialRotationQuat);\n\tinitialTransform.setOrigin(positionVector);\n\tfor(size_t i=0;i<rods.size();i++) {\n\t\t\trods[i]->getPRigidBody()->setLinearVelocity(speedVector);\n\t\t\trods[i]->getPRigidBody()->setWorldTransform(initialTransform * rods[i]->getPRigidBody()->getWorldTransform());\n\t}\n}\n<commit_msg>Added support rod, but it isn't massless<commit_after>\/*\n * Copyright © 2015, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All rights reserved.\n * \n * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed\n * 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 * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n*\/\n\n\/**\n * @file ScarrArmModel.cpp\n * @brief Contains the implementation of class ScarrArmModel. \n * Measurements are scaled to average adult male\n * $Id$\n *\/\n\n\/\/ This module\n#include \"ScarrArmModel.h\"\n\/\/ This library\n#include \"core\/tgBasicActuator.h\"\n#include \"core\/tgRod.h\"\n#include \"core\/abstractMarker.h\"\n#include \"tgcreator\/tgBuildSpec.h\"\n#include \"tgcreator\/tgBasicActuatorInfo.h\"\n#include \"tgcreator\/tgRodInfo.h\"\n#include \"tgcreator\/tgStructure.h\"\n#include \"tgcreator\/tgStructureInfo.h\"\n\/\/ The Bullet Physics library\n#include \"LinearMath\/btVector3.h\"\n\/\/ The C++ Standard Library\n#include <stdexcept>\n\nnamespace\n{\n \/\/ see tgBaseString.h for a descripton of some of these rod parameters\n \/\/ (specifically, those related to the motor moving the strings.)\n \/\/ NOTE that any parameter that depends on units of length will scale\n \/\/ with the current gravity scaling. E.g., with gravity as 98.1,\n \/\/ the length units below are in decimeters.\n\n \/\/ Note: This current model of the SUPERball rod is 1.5m long by 3 cm radius,\n \/\/ which is 0.00424 m^3.\n \/\/ For SUPERball v1.5, mass = 3.5kg per strut, which comes out to \n \/\/ 0.825 kg \/ (decimeter^3).\n\n \/\/ similarly, frictional parameters are for the tgRod objects.\n const struct Config\n {\n double density;\n double radius;\n double stiffness;\n double damping;\n double rod_length;\n double rod_space; \n double friction;\n double rollFriction;\n double restitution;\n double pretension;\n bool history; \n double maxTens;\n double targetVelocity;\n } c =\n {\n 0.825, \/\/ density (kg \/ length^3)\n 0.31, \/\/ radius (length)\n 3000.0, \/\/ stiffness (kg \/ sec^2)\n 200.0, \/\/ damping (kg \/ sec)\n 15.0, \/\/ rod_length (length)\n 7.5, \/\/ rod_space (length)\n 1.0, \/\/ friction (unitless)\n 0.01, \/\/ rollFriction (unitless)\n 0.2, \/\/ restitution (?)\n 0, \/\/ pretension (force)\n false, \/\/ history (boolean)\n 100000, \/\/ maxTens\n 10000 \/\/ targetVelocity\n#if (0)\n 20000 \/\/ maxAcc\n#endif\n \/\/ Use the below values for earlier versions of simulation.\n \/\/ 1.006, \n \/\/ 0.31, \n \/\/ 300000.0, \n \/\/ 3000.0, \n \/\/ 15.0, \n \/\/ 7.5, \n };\n} \/\/ namespace\n\n\/*\n * helper arrays for node and rod numbering schema\n *\/\n\/*returns the number of the rod for a given node *\/\n\/\/const int rodNumbersPerNode[11]={0,1,2,3,3,4,0,1,2,5,5,4,6};\n\n\/*returns the node that is at the other end of the given node *\/\n\/\/const int otherEndOfTheRod[11]={6,7,8,4,3,11,0,1,2,10,9,5,12};\n\n\/*returns the node that is at the parallel rod\n * and at the same end of the given node\n *\/\n\/\/const int parallelNode[11]={1,0,5,9,10,2,7,6,11,3,4,8,12};\n\nScarrArmModel::ScarrArmModel() : tgModel() \n{\n}\n\nScarrArmModel::~ScarrArmModel()\n{\n}\n\nvoid ScarrArmModel::addNodes(tgStructure& s)\n{\n const double scale = 0.1;\n const size_t nNodes = 11 + 2; \/\/2 for massless rod\n \n \/\/ Average Adult Male Measurements with scale\n \/\/ Lengths are in mm\n const double a = 22 * scale; \/\/2.2cm\n const double b = 265 * scale;\n const double c = 334 * scale;\n const double d = 66 * scale;\n const double e = 246 * scale;\n const double f = 25 * scale;\n const double g = 17 * scale;\n const double sigma = 1; \/\/TODO: tinker\n const double ulna_diameter = g*2; \/\/TODO: tinker\n const double x = a\/2;\n const double z = c\/2;\n\n nodePositions.push_back(btVector3(a\/2, 0, 0));\n nodePositions.push_back(btVector3(0, 0, -g));\n nodePositions.push_back(btVector3(-a\/2, 0, 0));\n nodePositions.push_back(btVector3(0, f, 0));\n nodePositions.push_back(btVector3(0, -f, 0));\n nodePositions.push_back(btVector3(0, 0, d));\n nodePositions.push_back(btVector3(0, 0, c));\n nodePositions.push_back(btVector3(x, 0, z));\n nodePositions.push_back(btVector3(b+a\/2, 0, 0));\n nodePositions.push_back(btVector3(a\/2 + sigma, 0, -ulna_diameter));\n nodePositions.push_back(btVector3(a\/2 + sigma + e, 0, -ulna_diameter));\n\n \/\/Massless rod\n nodePositions.push_back(btVector3(0, f, c+1));\n nodePositions.push_back(btVector3(0, -f, c+1));\n\n for(size_t i=0;i<nNodes;i++) {\n\t\ts.addNode(nodePositions[i][0],nodePositions[i][1],nodePositions[i][2]);\n }\n}\n\nvoid ScarrArmModel::addRods(tgStructure& s)\n{\n s.addPair(5, 6, \"rod\");\n s.addPair(3, 5, \"rod\");\n s.addPair(4, 5, \"rod\");\n\n s.addPair(0, 1, \"rod\");\n s.addPair(0, 8, \"rod\");\n s.addPair(1, 2, \"rod\");\n\n s.addPair(9, 10, \"rod\"); \n s.addPair(11, 12, \"massless rod\");\n}\n\n\/*\nvoid ScarrArmModel::addMarkers(tgStructure &s)\n{\n std::vector<tgRod *> rods=find<tgRod>(\"rod\");\n\n\tfor(int i=0;i<10;i++)\n\t{\n\t\tconst btRigidBody* bt = rods[rodNumbersPerNode[i]]->getPRigidBody();\n\t\tbtTransform inverseTransform = bt->getWorldTransform().inverse();\n\t\tbtVector3 pos = inverseTransform * (nodePositions[i]);\n\t\tabstractMarker tmp=abstractMarker(bt,pos,btVector3(0.08*i,1.0 - 0.08*i,.0),i);\n\t\tthis->addMarker(tmp);\n\t}\n}\n*\/\n\nvoid ScarrArmModel::addMuscles(tgStructure& s)\n{\n s.addPair(0, 3, \"muscle\");\n s.addPair(0, 4, \"muscle\");\n s.addPair(1, 3, \"muscle\");\n s.addPair(1, 4, \"muscle\");\n s.addPair(2, 3, \"muscle\");\n s.addPair(2, 4, \"muscle\");\n s.addPair(3, 9, \"muscle\");\n s.addPair(4, 9, \"muscle\");\n \/\/s.addPair(5, 7, \"muscle\");\n \/\/s.addPair(6, 7, \"muscle\");\n \/\/s.addPair(7, 8, \"muscle\"); \n s.addPair(6, 8, \"muscle\"); \n s.addPair(8, 10, \"muscle\"); \n\n \/\/Muscles to massless rod\n s.addPair(6, 11, \"muscle\"); \n s.addPair(6, 12, \"muscle\"); \n}\n\nvoid ScarrArmModel::setup(tgWorld& world)\n{\n\n const tgRod::Config rodConfig(c.radius, c.density, c.friction, c.rollFriction, c.restitution);\n const tgRod::Config rodConfigMassless(c.radius, 0\/*c.density*\/, c.friction, c.rollFriction, c.restitution);\n \/\/\/ @todo acceleration constraint was removed on 12\/10\/14 Replace with tgKinematicActuator as appropreate\n tgBasicActuator::Config muscleConfig(c.stiffness, c.damping, c.pretension, c.history, c.maxTens, c.targetVelocity);\n \n \/\/ Start creating the structure\n tgStructure s;\n addNodes(s);\n addRods(s);\n addMuscles(s);\n\n\/\/ \/\/ Add a rotation. This is needed if the ground slopes too much, otherwise glitches put a rod below the ground.\n\/\/ btVector3 rotationPoint = btVector3(0, 0, 0); \/\/ origin\n\/\/ btVector3 rotationAxis = btVector3(0, 1, 0); \/\/ y-axis\n\/\/ double rotationAngle = M_PI\/2;\n\/\/ s.addRotation(rotationPoint, rotationAxis, rotationAngle);\n\/\/ s.move(btVector3(0,30,0));\n\n \/\/ Create the build spec that uses tags to turn the structure into a real model\n tgBuildSpec spec;\n spec.addBuilder(\"massless rod\", new tgRodInfo(rodConfigMassless));\n spec.addBuilder(\"rod\", new tgRodInfo(rodConfig));\n spec.addBuilder(\"muscle\", new tgBasicActuatorInfo(muscleConfig));\n \n \/\/ Create your structureInfo\n tgStructureInfo structureInfo(s, spec);\n\n \/\/ Use the structureInfo to build ourselves\n structureInfo.buildInto(*this, world);\n\n \/\/ We could now use tgCast::filter or similar to pull out the\n \/\/ models (e.g. muscles) that we want to control. \n allMuscles = tgCast::filter<tgModel, tgBasicActuator> (getDescendants());\n\n \/\/ call the onSetup methods of all observed things e.g. controllers\n notifySetup();\n\n \/\/ Actually setup the children\n tgModel::setup(world);\n\n \/\/map the rods and add the markers to them\n \/\/addMarkers(s);\n\n btVector3 location(0,10.0,0);\n \/\/btVector3 rotation(M_PI\/2,0,0);\n btVector3 rotation(0,0,0);\n \tbtVector3 speed(0,0,0);\n this->moveModel(location,rotation,speed);\n}\n\nvoid ScarrArmModel::step(double dt)\n{\n \/\/ Precondition\n if (dt <= 0.0)\n {\n throw std::invalid_argument(\"dt is not positive\");\n }\n else\n {\n \/\/ Notify observers (controllers) of the step so that they can take action\n notifyStep(dt);\n tgModel::step(dt); \/\/ Step any children\n }\n}\n\nvoid ScarrArmModel::onVisit(tgModelVisitor& r)\n{\n tgModel::onVisit(r);\n}\n\nconst std::vector<tgBasicActuator*>& ScarrArmModel::getAllMuscles() const\n{\n return allMuscles;\n}\n \nvoid ScarrArmModel::teardown()\n{\n tgModel::teardown();\n}\n\nvoid ScarrArmModel::moveModel(btVector3 positionVector,btVector3 rotationVector,btVector3 speedVector)\n{\n std::vector<tgRod *> rods=find<tgRod>(\"rod\");\n\n\tbtQuaternion initialRotationQuat;\n\tinitialRotationQuat.setEuler(rotationVector[0],rotationVector[1],rotationVector[2]);\n\tbtTransform initialTransform;\n\tinitialTransform.setIdentity();\n\tinitialTransform.setRotation(initialRotationQuat);\n\tinitialTransform.setOrigin(positionVector);\n\tfor(size_t i=0;i<rods.size();i++) {\n\t\t\trods[i]->getPRigidBody()->setLinearVelocity(speedVector);\n\t\t\trods[i]->getPRigidBody()->setWorldTransform(initialTransform * rods[i]->getPRigidBody()->getWorldTransform());\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011, 2012 *\n * Dominik Charousset <dominik.charousset@haw-hamburg.de> *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation, either version 3 of the License *\n * or (at your option) any later version. *\n * *\n * libcppa 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 Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n\\******************************************************************************\/\n\n\n#include <stack>\n#include <sstream>\n#include <algorithm>\n\n#include \"cppa\/atom.hpp\"\n#include \"cppa\/object.hpp\"\n#include \"cppa\/to_string.hpp\"\n#include \"cppa\/serializer.hpp\"\n#include \"cppa\/from_string.hpp\"\n#include \"cppa\/deserializer.hpp\"\n#include \"cppa\/primitive_variant.hpp\"\n#include \"cppa\/uniform_type_info.hpp\"\n\nnamespace cppa {\n\nnamespace {\n\nclass string_serializer : public serializer {\n\n std::ostream& out;\n\n struct pt_writer {\n\n std::ostream& out;\n\n pt_writer(std::ostream& mout) : out(mout) { }\n\n template<typename T>\n void operator()(const T& value) {\n out << value;\n }\n\n void operator()(const std::string& str) {\n out << \"\\\"\";\/\/ << str << \"\\\"\";\n for (char c : str) {\n if (c == '\"') out << \"\\\\\\\"\";\n else out << c;\n }\n out << '\"';\n }\n\n void operator()(const std::u16string&) { }\n\n void operator()(const std::u32string&) { }\n\n };\n\n bool m_after_value;\n bool m_obj_just_opened;\n std::stack<std::string> m_open_objects;\n\n inline void clear() {\n if (m_after_value) {\n out << \", \";\n m_after_value = false;\n }\n else if (m_obj_just_opened) {\n out << \" ( \";\n m_obj_just_opened = false;\n }\n }\n\n public:\n\n string_serializer(std::ostream& mout)\n : out(mout), m_after_value(false), m_obj_just_opened(false) {\n }\n\n void begin_object(const std::string& type_name) {\n clear();\n m_open_objects.push(type_name);\n out << type_name;\/\/ << \" ( \";\n m_obj_just_opened = true;\n }\n void end_object() {\n if (m_obj_just_opened) {\n \/\/ no open brackets to close\n m_obj_just_opened = false;\n }\n else {\n out << (m_after_value ? \" )\" : \")\");\n }\n m_after_value = true;\n if (!m_open_objects.empty()) {\n m_open_objects.pop();\n }\n }\n\n void begin_sequence(size_t) {\n clear();\n out << \"{ \";\n }\n\n void end_sequence() {\n out << (m_after_value ? \" }\" : \"}\");\n m_after_value = true;\n }\n\n void write_value(const primitive_variant& value) {\n clear();\n if (m_open_objects.empty()) {\n throw std::runtime_error(\"write_value(): m_open_objects.empty()\");\n }\n if (m_open_objects.top() == \"@atom\") {\n if (value.ptype() != pt_uint64) {\n throw std::runtime_error(\"expected uint64 value after @atom\");\n }\n \/\/ write atoms as strings instead of integer values\n auto av = static_cast<atom_value>(get<std::uint64_t>(value));\n (pt_writer(out))(to_string(av));\n }\n else {\n value.apply(pt_writer(out));\n }\n m_after_value = true;\n }\n\n void write_tuple(size_t size, const primitive_variant* values) {\n clear();\n out << \"{\";\n const primitive_variant* end = values + size;\n for ( ; values != end; ++values) {\n write_value(*values);\n }\n out << (m_after_value ? \" }\" : \"}\");\n }\n\n void write_raw(size_t, const void*) {\n throw std::runtime_error(\"string_serializer::write_raw: \"\n \"not implemented yet\");\n }\n\n};\n\nclass string_deserializer : public deserializer {\n\n std::string m_str;\n std::string::iterator m_pos;\n \/\/size_t m_obj_count;\n std::stack<bool> m_obj_had_left_parenthesis;\n std::stack<std::string> m_open_objects;\n\n void skip_space_and_comma() {\n while (*m_pos == ' ' || *m_pos == ',') ++m_pos;\n }\n\n void throw_malformed(const std::string& error_msg) {\n throw std::logic_error(\"malformed string: \" + error_msg);\n }\n\n void consume(char c) {\n skip_space_and_comma();\n if (*m_pos != c) {\n std::string error;\n error += \"expected '\";\n error += c;\n error += \"' found '\";\n error += *m_pos;\n error += \"'\";\n if (m_open_objects.empty() == false) {\n error += \"during deserialization an instance of \";\n error += m_open_objects.top();\n }\n throw_malformed(error);\n }\n ++m_pos;\n }\n\n bool try_consume(char c) {\n skip_space_and_comma();\n if (*m_pos == c) {\n ++m_pos;\n return true;\n }\n return false;\n }\n\n inline std::string::iterator next_delimiter() {\n return std::find_if(m_pos, m_str.end(), [] (char c) -> bool {\n switch (c) {\n case '(':\n case ')':\n case '{':\n case '}':\n case ' ':\n case ',': {\n return true;\n }\n default: {\n return false;\n }\n }\n });\n }\n\n void integrity_check() {\n if (m_open_objects.empty() || m_obj_had_left_parenthesis.empty()) {\n throw_malformed(\"missing begin_object()\");\n }\n if (m_obj_had_left_parenthesis.top() == false) {\n throw_malformed(\"expected left parenthesis after \"\n \"begin_object call or void value\");\n }\n }\n\n public:\n\n string_deserializer(const std::string& str) : m_str(str) {\n m_pos = m_str.begin();\n }\n\n string_deserializer(std::string&& str) : m_str(std::move(str)) {\n m_pos = m_str.begin();\n }\n\n std::string seek_object() {\n skip_space_and_comma();\n auto substr_end = next_delimiter();\n if (m_pos == substr_end) {\n throw_malformed(\"could not seek object type name\");\n }\n std::string result(m_pos, substr_end);\n m_pos = substr_end;\n return result;\n }\n\n std::string peek_object() {\n std::string result = seek_object();\n \/\/ restore position in stream\n m_pos -= result.size();\n return result;\n }\n\n void begin_object(const std::string& type_name) {\n m_open_objects.push(type_name);\n \/\/++m_obj_count;\n skip_space_and_comma();\n m_obj_had_left_parenthesis.push(try_consume('('));\n \/\/consume('(');\n }\n\n void end_object() {\n if (m_obj_had_left_parenthesis.empty()) {\n throw_malformed(\"missing begin_object()\");\n }\n else {\n if (m_obj_had_left_parenthesis.top() == true) {\n consume(')');\n }\n m_obj_had_left_parenthesis.pop();\n }\n if (m_open_objects.empty()) {\n throw std::runtime_error(\"no object to end\");\n }\n m_open_objects.pop();\n if (m_open_objects.empty()) {\n skip_space_and_comma();\n if (m_pos != m_str.end()) {\n throw_malformed(\"expected end of of string\");\n }\n }\n }\n\n size_t begin_sequence() {\n integrity_check();\n consume('{');\n return std::count(m_pos, std::find(m_pos, m_str.end(), '}'), ',') + 1;\n }\n\n void end_sequence() {\n integrity_check();\n consume('}');\n }\n\n struct from_string {\n const std::string& str;\n from_string(const std::string& s) : str(s) { }\n template<typename T>\n void operator()(T& what) {\n std::istringstream s(str);\n s >> what;\n }\n void operator()(std::string& what) {\n what = str;\n }\n void operator()(std::u16string&) { }\n void operator()(std::u32string&) { }\n };\n\n primitive_variant read_value(primitive_type ptype) {\n integrity_check();\n if (m_open_objects.top() == \"@atom\") {\n if (ptype != pt_uint64) {\n throw_malformed(\"expected read of pt_uint64 after @atom\");\n }\n auto str_val = get<std::string>(read_value(pt_u8string));\n if (str_val.size() > 10) {\n throw_malformed(\"atom string size > 10\");\n }\n return detail::atom_val(str_val.c_str());\n }\n skip_space_and_comma();\n std::string::iterator substr_end;\n auto find_if_cond = [] (char c) -> bool {\n switch (c) {\n case ')':\n case '}':\n case ' ':\n case ',': return true;\n default : return false;\n }\n };\n if (ptype == pt_u8string) {\n if (*m_pos == '\"') {\n \/\/ skip leading \"\n ++m_pos;\n char last_char = '\"';\n auto find_if_str_cond = [&last_char] (char c) -> bool {\n if (c == '\"' && last_char != '\\\\') {\n return true;\n }\n last_char = c;\n return false;\n };\n substr_end = std::find_if(m_pos, m_str.end(), find_if_str_cond);\n }\n else {\n substr_end = std::find_if(m_pos, m_str.end(), find_if_cond);\n }\n }\n else {\n substr_end = std::find_if(m_pos, m_str.end(), find_if_cond);\n }\n if (substr_end == m_str.end()) {\n throw std::logic_error(\"malformed string (unterminated value)\");\n }\n std::string substr(m_pos, substr_end);\n m_pos += substr.size();\n if (ptype == pt_u8string) {\n \/\/ skip trailing \"\n if (*m_pos != '\"') {\n std::string error_msg;\n error_msg = \"malformed string, expected '\\\"' found '\";\n error_msg += *m_pos;\n error_msg += \"'\";\n throw std::logic_error(error_msg);\n }\n ++m_pos;\n \/\/ replace '\\\"' by '\"'\n char last_char = ' ';\n auto cond = [&last_char] (char c) -> bool {\n if (c == '\"' && last_char == '\\\\') {\n return true;\n }\n last_char = c;\n return false;\n };\n std::string tmp;\n auto sbegin = substr.begin();\n auto send = substr.end();\n for (auto i = std::find_if(sbegin, send, cond);\n i != send;\n i = std::find_if(i, send, cond)) {\n --i;\n tmp.append(sbegin, i);\n tmp += '\"';\n i += 2;\n sbegin = i;\n }\n if (sbegin != substr.begin()) {\n tmp.append(sbegin, send);\n }\n if (!tmp.empty()) {\n substr = std::move(tmp);\n }\n }\n primitive_variant result(ptype);\n result.apply(from_string(substr));\n return result;\n }\n\n void read_tuple(size_t size,\n const primitive_type* begin,\n primitive_variant* storage) {\n integrity_check();\n consume('{');\n const primitive_type* end = begin + size;\n for ( ; begin != end; ++begin) {\n *storage = std::move(read_value(*begin));\n ++storage;\n }\n consume('}');\n }\n\n void read_raw(size_t, void*) {\n throw std::runtime_error(\"string_deserializer::read_raw: \"\n \"not implemented yet\");\n }\n\n};\n\n} \/\/ namespace <anonymous>\n\nobject from_string(const std::string& what) {\n string_deserializer strd(what);\n std::string uname = strd.peek_object();\n auto utype = uniform_type_info::from(uname);\n if (utype == nullptr) {\n throw std::logic_error(uname + \" is not announced\");\n }\n return utype->deserialize(&strd);\n}\n\nnamespace detail {\n\nstd::string to_string_impl(const void *what, const uniform_type_info *utype) {\n std::ostringstream osstr;\n string_serializer strs(osstr);\n utype->serialize(what, &strs);\n return osstr.str();\n}\n\n} \/\/ namespace detail\n\n} \/\/ namespace cppa\n<commit_msg>implemented read_raw & write_raw<commit_after>\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011, 2012 *\n * Dominik Charousset <dominik.charousset@haw-hamburg.de> *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation, either version 3 of the License *\n * or (at your option) any later version. *\n * *\n * libcppa 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 Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n\\******************************************************************************\/\n\n\n#include <stack>\n#include <cctype>\n#include <sstream>\n#include <iomanip>\n#include <algorithm>\n\n#include \"cppa\/atom.hpp\"\n#include \"cppa\/object.hpp\"\n#include \"cppa\/to_string.hpp\"\n#include \"cppa\/serializer.hpp\"\n#include \"cppa\/from_string.hpp\"\n#include \"cppa\/deserializer.hpp\"\n#include \"cppa\/primitive_variant.hpp\"\n#include \"cppa\/uniform_type_info.hpp\"\n\nusing namespace std;\n\nnamespace cppa {\n\nnamespace {\n\nclass string_serializer : public serializer {\n\n ostream& out;\n\n struct pt_writer {\n\n ostream& out;\n\n pt_writer(ostream& mout) : out(mout) { }\n\n template<typename T>\n void operator()(const T& value) {\n out << value;\n }\n\n void operator()(const string& str) {\n out << \"\\\"\";\/\/ << str << \"\\\"\";\n for (char c : str) {\n if (c == '\"') out << \"\\\\\\\"\";\n else out << c;\n }\n out << '\"';\n }\n\n void operator()(const u16string&) { }\n\n void operator()(const u32string&) { }\n\n };\n\n bool m_after_value;\n bool m_obj_just_opened;\n stack<string> m_open_objects;\n\n inline void clear() {\n if (m_after_value) {\n out << \", \";\n m_after_value = false;\n }\n else if (m_obj_just_opened) {\n out << \" ( \";\n m_obj_just_opened = false;\n }\n }\n\n public:\n\n string_serializer(ostream& mout)\n : out(mout), m_after_value(false), m_obj_just_opened(false) {\n }\n\n void begin_object(const string& type_name) {\n clear();\n m_open_objects.push(type_name);\n out << type_name;\/\/ << \" ( \";\n m_obj_just_opened = true;\n }\n void end_object() {\n if (m_obj_just_opened) {\n \/\/ no open brackets to close\n m_obj_just_opened = false;\n }\n else {\n out << (m_after_value ? \" )\" : \")\");\n }\n m_after_value = true;\n if (!m_open_objects.empty()) {\n m_open_objects.pop();\n }\n }\n\n void begin_sequence(size_t) {\n clear();\n out << \"{ \";\n }\n\n void end_sequence() {\n out << (m_after_value ? \" }\" : \"}\");\n m_after_value = true;\n }\n\n void write_value(const primitive_variant& value) {\n clear();\n if (m_open_objects.empty()) {\n throw runtime_error(\"write_value(): m_open_objects.empty()\");\n }\n if (m_open_objects.top() == \"@atom\") {\n if (value.ptype() != pt_uint64) {\n throw runtime_error(\"expected uint64 value after @atom\");\n }\n \/\/ write atoms as strings instead of integer values\n auto av = static_cast<atom_value>(get<uint64_t>(value));\n (pt_writer(out))(to_string(av));\n }\n else {\n value.apply(pt_writer(out));\n }\n m_after_value = true;\n }\n\n void write_tuple(size_t size, const primitive_variant* values) {\n clear();\n out << \"{\";\n const primitive_variant* end = values + size;\n for ( ; values != end; ++values) {\n write_value(*values);\n }\n out << (m_after_value ? \" }\" : \"}\");\n }\n\n void write_raw(size_t num_bytes, const void* buf) {\n clear();\n auto first = reinterpret_cast<const unsigned char*>(buf);\n auto last = first + num_bytes;\n out << hex;\n out << setfill('0');\n copy(first, last, ostream_iterator<size_t>(out));\n out << dec;\n m_after_value = true;\n }\n\n};\n\nclass string_deserializer : public deserializer {\n\n string m_str;\n string::iterator m_pos;\n \/\/size_t m_obj_count;\n stack<bool> m_obj_had_left_parenthesis;\n stack<string> m_open_objects;\n\n void skip_space_and_comma() {\n while (*m_pos == ' ' || *m_pos == ',') ++m_pos;\n }\n\n void throw_malformed(const string& error_msg) {\n throw logic_error(\"malformed string: \" + error_msg);\n }\n\n void consume(char c) {\n skip_space_and_comma();\n if (*m_pos != c) {\n string error;\n error += \"expected '\";\n error += c;\n error += \"' found '\";\n error += *m_pos;\n error += \"'\";\n if (m_open_objects.empty() == false) {\n error += \"during deserialization an instance of \";\n error += m_open_objects.top();\n }\n throw_malformed(error);\n }\n ++m_pos;\n }\n\n bool try_consume(char c) {\n skip_space_and_comma();\n if (*m_pos == c) {\n ++m_pos;\n return true;\n }\n return false;\n }\n\n inline string::iterator next_delimiter() {\n return find_if(m_pos, m_str.end(), [] (char c) -> bool {\n switch (c) {\n case '(':\n case ')':\n case '{':\n case '}':\n case ' ':\n case ',': {\n return true;\n }\n default: {\n return false;\n }\n }\n });\n }\n\n void integrity_check() {\n if (m_open_objects.empty() || m_obj_had_left_parenthesis.empty()) {\n throw_malformed(\"missing begin_object()\");\n }\n if (m_obj_had_left_parenthesis.top() == false) {\n throw_malformed(\"expected left parenthesis after \"\n \"begin_object call or void value\");\n }\n }\n\n public:\n\n string_deserializer(const string& str) : m_str(str) {\n m_pos = m_str.begin();\n }\n\n string_deserializer(string&& str) : m_str(move(str)) {\n m_pos = m_str.begin();\n }\n\n string seek_object() {\n skip_space_and_comma();\n auto substr_end = next_delimiter();\n if (m_pos == substr_end) {\n throw_malformed(\"could not seek object type name\");\n }\n string result(m_pos, substr_end);\n m_pos = substr_end;\n return result;\n }\n\n string peek_object() {\n string result = seek_object();\n \/\/ restore position in stream\n m_pos -= result.size();\n return result;\n }\n\n void begin_object(const string& type_name) {\n m_open_objects.push(type_name);\n \/\/++m_obj_count;\n skip_space_and_comma();\n m_obj_had_left_parenthesis.push(try_consume('('));\n \/\/consume('(');\n }\n\n void end_object() {\n if (m_obj_had_left_parenthesis.empty()) {\n throw_malformed(\"missing begin_object()\");\n }\n else {\n if (m_obj_had_left_parenthesis.top() == true) {\n consume(')');\n }\n m_obj_had_left_parenthesis.pop();\n }\n if (m_open_objects.empty()) {\n throw runtime_error(\"no object to end\");\n }\n m_open_objects.pop();\n if (m_open_objects.empty()) {\n skip_space_and_comma();\n if (m_pos != m_str.end()) {\n throw_malformed(\"expected end of of string\");\n }\n }\n }\n\n size_t begin_sequence() {\n integrity_check();\n consume('{');\n return count(m_pos, find(m_pos, m_str.end(), '}'), ',') + 1;\n }\n\n void end_sequence() {\n integrity_check();\n consume('}');\n }\n\n struct from_string {\n const string& str;\n from_string(const string& s) : str(s) { }\n template<typename T>\n void operator()(T& what) {\n istringstream s(str);\n s >> what;\n }\n void operator()(string& what) {\n what = str;\n }\n void operator()(u16string&) { }\n void operator()(u32string&) { }\n };\n\n primitive_variant read_value(primitive_type ptype) {\n integrity_check();\n if (m_open_objects.top() == \"@atom\") {\n if (ptype != pt_uint64) {\n throw_malformed(\"expected read of pt_uint64 after @atom\");\n }\n auto str_val = get<string>(read_value(pt_u8string));\n if (str_val.size() > 10) {\n throw_malformed(\"atom string size > 10\");\n }\n return detail::atom_val(str_val.c_str());\n }\n skip_space_and_comma();\n string::iterator substr_end;\n auto find_if_cond = [] (char c) -> bool {\n switch (c) {\n case ')':\n case '}':\n case ' ':\n case ',': return true;\n default : return false;\n }\n };\n if (ptype == pt_u8string) {\n if (*m_pos == '\"') {\n \/\/ skip leading \"\n ++m_pos;\n char last_char = '\"';\n auto find_if_str_cond = [&last_char] (char c) -> bool {\n if (c == '\"' && last_char != '\\\\') {\n return true;\n }\n last_char = c;\n return false;\n };\n substr_end = find_if(m_pos, m_str.end(), find_if_str_cond);\n }\n else {\n substr_end = find_if(m_pos, m_str.end(), find_if_cond);\n }\n }\n else {\n substr_end = find_if(m_pos, m_str.end(), find_if_cond);\n }\n if (substr_end == m_str.end()) {\n throw logic_error(\"malformed string (unterminated value)\");\n }\n string substr(m_pos, substr_end);\n m_pos += substr.size();\n if (ptype == pt_u8string) {\n \/\/ skip trailing \"\n if (*m_pos != '\"') {\n string error_msg;\n error_msg = \"malformed string, expected '\\\"' found '\";\n error_msg += *m_pos;\n error_msg += \"'\";\n throw logic_error(error_msg);\n }\n ++m_pos;\n \/\/ replace '\\\"' by '\"'\n char last_char = ' ';\n auto cond = [&last_char] (char c) -> bool {\n if (c == '\"' && last_char == '\\\\') {\n return true;\n }\n last_char = c;\n return false;\n };\n string tmp;\n auto sbegin = substr.begin();\n auto send = substr.end();\n for (auto i = find_if(sbegin, send, cond);\n i != send;\n i = find_if(i, send, cond)) {\n --i;\n tmp.append(sbegin, i);\n tmp += '\"';\n i += 2;\n sbegin = i;\n }\n if (sbegin != substr.begin()) {\n tmp.append(sbegin, send);\n }\n if (!tmp.empty()) {\n substr = move(tmp);\n }\n }\n primitive_variant result(ptype);\n result.apply(from_string(substr));\n return result;\n }\n\n void read_tuple(size_t size,\n const primitive_type* begin,\n primitive_variant* storage) {\n integrity_check();\n consume('{');\n const primitive_type* end = begin + size;\n for ( ; begin != end; ++begin) {\n *storage = move(read_value(*begin));\n ++storage;\n }\n consume('}');\n }\n\n void read_raw(size_t buf_size, void* vbuf) {\n auto buf = reinterpret_cast<unsigned char*>(vbuf);\n integrity_check();\n skip_space_and_comma();\n auto next_nibble = [&]() -> size_t {\n if (*m_pos == '\\0') {\n throw_malformed(\"unexpected end-of-string\");\n }\n char c = *m_pos++;\n if (!isxdigit(c)) {\n throw_malformed(\"unexpected character, expected [0-9a-f]\");\n }\n return static_cast<size_t>(isdigit(c) ? c - '0' : (c - 'a' + 10));\n };\n for (size_t i = 0; i < buf_size; ++i) {\n auto nibble = next_nibble();\n *buf++ = static_cast<unsigned char>((nibble << 4) | next_nibble());\n }\n }\n\n};\n\n} \/\/ namespace <anonymous>\n\nobject from_string(const string& what) {\n string_deserializer strd(what);\n string uname = strd.peek_object();\n auto utype = uniform_type_info::from(uname);\n if (utype == nullptr) {\n throw logic_error(uname + \" is not announced\");\n }\n return utype->deserialize(&strd);\n}\n\nnamespace detail {\n\nstring to_string_impl(const void *what, const uniform_type_info *utype) {\n ostringstream osstr;\n string_serializer strs(osstr);\n utype->serialize(what, &strs);\n return osstr.str();\n}\n\n} \/\/ namespace detail\n\n} \/\/ namespace cppa\n<|endoftext|>"} {"text":"<commit_before>#include <v8.h>\n#include <node.h>\n\nusing namespace node;\nusing namespace v8;\n\n\n\/\/ We start with an empty global scope, but we need various JavaScript\n\/\/ primitives (Array, Object, encode, parseInt, etc). We're going to create\n\/\/ these primitives by running a script and assigning the result to a property\n\/\/ on the global scope.\n\/\/\n\/\/ There are two types of primitives: primitives we extract in the context\n\/\/ (e.g. constructor for String) and primitives we extract from Zombie's global\n\/\/ scope (e.g. Date object). The former has their InContext flag set to true.\n\/\/\n\/\/ Since there is no String in our global scope, we need to either get it from\n\/\/ another scope or create it in some other way. If we copy it from another\n\/\/ scope, we get a different function, and when we later try to do something\n\/\/ like this, if fails: \"foo\".constructor == String\n\/\/\n\/\/ So instead we're going to use the current context to get the constructor for\n\/\/ an empty string and assign that to the String property. We need to do this\n\/\/ in the same context in which we're going to use the global scope.\n\/\/\n\/\/ OTOH we have no way of obtaining a constructor for Date in that way, so we\n\/\/ copy it from Zombie's global scope, and to do that we need to execute the\n\/\/ script in the current context.\n\/\/\n\/\/ If we're just copying a function, the script is the same as the primitive\n\/\/ name and you can use the single argument constructor.\nclass SetPrimitive { private:\n \/\/ The script we're going to execute. Compile once for performance (this\n \/\/ really makes a difference of about 1 second in the test suite).\n Persistent<Script> script; const char *name; bool in_context;\n\npublic:\n \/\/ All powerful constructor. Specify primitive name, code we need to run to\n \/\/ extract its value, and whether or not we need to run it in context.\n \/\/\n \/\/ If called with two arguments, we assume this script needs to be evaluated\n \/\/ in context.\n \/\/\n \/\/ If called with one argument, we assume it's copying a property from the\n \/\/ current context, the code is the same as the primitive name and it\n \/\/ executes in the current context.\n SetPrimitive(const char *name, const char *code = NULL, bool in_context = true) {\n this->name = name;\n if (code == NULL) {\n code = name;\n in_context = false;\n }\n script = Persistent<Script>::New(Script::New(String::New(code)));\n this->in_context = in_context;\n }\n\n \/\/ Returns the name of this primitive (e.g. Array, escape).\n Handle<String> GetName() {\n return String::New(name);\n }\n\n \/\/ Returns the value of this primitive (e.g. array constructor, escape function).\n Handle<Value> GetValue() {\n return script->Run();\n }\n\n \/\/ Returns true if we need to run this primitive in context.\n bool InContext() {\n return in_context;\n }\n \n};\n\n\n\/\/ Isolated V8 Context\/global scope for evaluating JavaScript, with access to\n\/\/ all window methods\/properties.\nclass WindowContext: ObjectWrap {\nprivate:\n\n \/\/ V8 Context we evaluate all code in.\n Persistent<Context> context;\n \/\/ Global scope provides access to properties and methods.\n Persistent<Object> global;\n\npublic:\n\n static Persistent<FunctionTemplate> s_ct;\n static SetPrimitive *primitives[];\n\n\n static void Init(Handle<Object> target) {\n Local<FunctionTemplate> t = FunctionTemplate::New(New);\n\n s_ct = Persistent<FunctionTemplate>::New(t);\n s_ct->InstanceTemplate()->SetInternalFieldCount(1);\n s_ct->SetClassName(String::NewSymbol(\"WindowContext\"));\n\n Local<ObjectTemplate> instance_t = t->InstanceTemplate();\n instance_t->SetAccessor(String::New(\"global\"), GetGlobal);\n instance_t->SetAccessor(String::New(\"g\"), GetG);\n NODE_SET_PROTOTYPE_METHOD(s_ct, \"evaluate\", Evaluate);\n\n target->Set(String::NewSymbol(\"WindowContext\"), s_ct->GetFunction());\n }\n\n\n \/\/ Create a new wrapper context around the global object.\n WindowContext(Handle<Object> global) {\n Handle<ObjectTemplate> tmpl = ObjectTemplate::New();\n this->global = Persistent<Object>::New(global);\n tmpl->SetNamedPropertyHandler(GetProperty, SetProperty, QueryProperty, DeleteProperty, EnumerateProperties, this->global);\n context = Context::New(NULL, tmpl);\n\n \/\/ Copy primitivies in context.\n context->Enter();\n SetPrimitive *primitive;\n for (int i = 0 ; (primitive = primitives[i]) ; ++i)\n if (primitive->InContext())\n global->Set(primitive->GetName(), primitive->GetValue());\n context->Exit();\n \/\/ Copy primitivies outside context.\n for (int i = 0 ; (primitive = primitives[i]) ; ++i)\n if (!primitive->InContext())\n global->Set(primitive->GetName(), primitive->GetValue());\n }\n\n ~WindowContext() {\n global.Dispose();\n context.Dispose();\n }\n\n \/\/ Takes single argument, the global object.\n static Handle<Value> New(const Arguments& args) {\n WindowContext* wc = new WindowContext(Handle<Object>::Cast(args[0]));\n wc->Wrap(args.This());\n return args.This();\n }\n\n \/\/ Returns the global object.\n static Handle<Value> GetGlobal(Local<String> name, const AccessorInfo& info) {\n WindowContext* wc = ObjectWrap::Unwrap<WindowContext>(info.This());\n return wc->global;\n }\n\n static Handle<Value> GetG(Local<String> name, const AccessorInfo& info) {\n WindowContext* wc = ObjectWrap::Unwrap<WindowContext>(info.This());\n return wc->context->Global();\n }\n\n \/\/ Evaluate expression or function in this context. First argument is either\n \/\/ a function or a script (String). In the later case, second argument\n \/\/ specifies filename.\n static Handle<Value> Evaluate(const Arguments& args) {\n WindowContext* wc = ObjectWrap::Unwrap<WindowContext>(args.This());\n Handle<Value> result;\n TryCatch trycatch;\n wc->context->Enter();\n if (args[0]->IsFunction()) {\n \/\/ Execute function in the global scope.\n Function *fn = Function::Cast(*args[0]);\n result = fn->Call(wc->global, 0, NULL);\n } else {\n \/\/ Coerce argument into a string and execute that as a function.\n Local<String> source = args[0]->ToString();\n Local<String> filename = args[1]->ToString();\n Handle<Script> script = Script::New(source, filename);\n result = script->Run();\n }\n wc->context->Exit();\n if (result.IsEmpty())\n trycatch.ReThrow();\n return result;\n }\n\n \/\/ Returns the value of a property from the global scope.\n static Handle<Value> GetProperty(Local<String> name, const AccessorInfo &info) {\n Local<Object> self = Local<Object>::Cast(info.Data());\n return self->Get(name);\n }\n\n \/\/ Sets the value of a property in the global scope.\n static Handle<Value> SetProperty(Local<String> name, Local<Value> value, const AccessorInfo &info) {\n Local<Object> self = Local<Object>::Cast(info.Data());\n self->Set(name, Persistent<Value>::New(value));\n return value;\n }\n\n \/\/ Deletes a property from the global scope.\n static Handle<Boolean> DeleteProperty(Local<String> name, const AccessorInfo &info) {\n HandleScope scope;\n Local<Object> self = Local<Object>::Cast(info.Data());\n Persistent<Value> value = (Persistent<Value>) self->Get(name);\n bool deleted = self->Delete(name);\n if (deleted)\n value.Dispose();\n return scope.Close(Boolean::New(deleted));\n }\n\n \/\/ Enumerate all named properties in the global scope.\n static Handle<Array> EnumerateProperties(const AccessorInfo &info) {\n HandleScope scope;\n Local<Object> self = Local<Object>::Cast(info.Data());\n return scope.Close(self->GetPropertyNames());\n }\n\n static Handle<Integer> QueryProperty(Local<String> name, const AccessorInfo &info) {\n HandleScope scope;\n return scope.Close(Integer::New(None));\n }\n \n};\n\n\nPersistent<FunctionTemplate> WindowContext::s_ct;\nSetPrimitive *WindowContext::primitives[] = {\n new SetPrimitive(\"Array\", \"[].constructor\"),\n new SetPrimitive(\"Boolean\", \"true.constructor\"),\n new SetPrimitive(\"Function\", \"(function() {}).constructor\"),\n new SetPrimitive(\"Number\", \"(1).constructor\"),\n new SetPrimitive(\"Object\", \"({}).constructor\"),\n new SetPrimitive(\"RegExp\", \"\/.\/.constructor\"),\n new SetPrimitive(\"String\", \"''.constructor\"),\n new SetPrimitive(\"Date\"),\n new SetPrimitive(\"Error\"),\n new SetPrimitive(\"Image\", \"{}\", false),\n new SetPrimitive(\"Math\"),\n new SetPrimitive(\"decodeURI\"),\n new SetPrimitive(\"decodeURIComponent\"),\n new SetPrimitive(\"encodeURI\"),\n new SetPrimitive(\"encodeURIComponent\"),\n new SetPrimitive(\"escape\"),\n new SetPrimitive(\"eval\"),\n new SetPrimitive(\"isFinite\"),\n new SetPrimitive(\"isNaN\"),\n new SetPrimitive(\"parseFloat\"),\n new SetPrimitive(\"parseInt\"),\n new SetPrimitive(\"unescape\")\n};\n\n\nextern \"C\" {\n static void init(Handle<Object> target) {\n WindowContext::Init(target);\n }\n NODE_MODULE(window_context, init);\n}\n<commit_msg>Got to remember to not remove the terminating NULL.<commit_after>#include <v8.h>\n#include <node.h>\n\nusing namespace node;\nusing namespace v8;\n\n\n\/\/ We start with an empty global scope, but we need various JavaScript\n\/\/ primitives (Array, Object, encode, parseInt, etc). We're going to create\n\/\/ these primitives by running a script and assigning the result to a property\n\/\/ on the global scope.\n\/\/\n\/\/ There are two types of primitives: primitives we extract in the context\n\/\/ (e.g. constructor for String) and primitives we extract from Zombie's global\n\/\/ scope (e.g. Date object). The former has their InContext flag set to true.\n\/\/\n\/\/ Since there is no String in our global scope, we need to either get it from\n\/\/ another scope or create it in some other way. If we copy it from another\n\/\/ scope, we get a different function, and when we later try to do something\n\/\/ like this, if fails: \"foo\".constructor == String\n\/\/\n\/\/ So instead we're going to use the current context to get the constructor for\n\/\/ an empty string and assign that to the String property. We need to do this\n\/\/ in the same context in which we're going to use the global scope.\n\/\/\n\/\/ OTOH we have no way of obtaining a constructor for Date in that way, so we\n\/\/ copy it from Zombie's global scope, and to do that we need to execute the\n\/\/ script in the current context.\n\/\/\n\/\/ If we're just copying a function, the script is the same as the primitive\n\/\/ name and you can use the single argument constructor.\nclass SetPrimitive { private:\n \/\/ The script we're going to execute. Compile once for performance (this\n \/\/ really makes a difference of about 1 second in the test suite).\n Persistent<Script> script; const char *name; bool in_context;\n\npublic:\n \/\/ All powerful constructor. Specify primitive name, code we need to run to\n \/\/ extract its value, and whether or not we need to run it in context.\n \/\/\n \/\/ If called with two arguments, we assume this script needs to be evaluated\n \/\/ in context.\n \/\/\n \/\/ If called with one argument, we assume it's copying a property from the\n \/\/ current context, the code is the same as the primitive name and it\n \/\/ executes in the current context.\n SetPrimitive(const char *name, const char *code = NULL, bool in_context = true) {\n this->name = name;\n if (code == NULL) {\n code = name;\n in_context = false;\n }\n script = Persistent<Script>::New(Script::New(String::New(code)));\n this->in_context = in_context;\n }\n\n \/\/ Returns the name of this primitive (e.g. Array, escape).\n Handle<String> GetName() {\n return String::New(name);\n }\n\n \/\/ Returns the value of this primitive (e.g. array constructor, escape function).\n Handle<Value> GetValue() {\n return script->Run();\n }\n\n \/\/ Returns true if we need to run this primitive in context.\n bool InContext() {\n return in_context;\n }\n \n};\n\n\n\/\/ Isolated V8 Context\/global scope for evaluating JavaScript, with access to\n\/\/ all window methods\/properties.\nclass WindowContext: ObjectWrap {\nprivate:\n\n \/\/ V8 Context we evaluate all code in.\n Persistent<Context> context;\n \/\/ Global scope provides access to properties and methods.\n Persistent<Object> global;\n\npublic:\n\n static Persistent<FunctionTemplate> s_ct;\n static SetPrimitive *primitives[];\n\n\n static void Init(Handle<Object> target) {\n Local<FunctionTemplate> t = FunctionTemplate::New(New);\n\n s_ct = Persistent<FunctionTemplate>::New(t);\n s_ct->InstanceTemplate()->SetInternalFieldCount(1);\n s_ct->SetClassName(String::NewSymbol(\"WindowContext\"));\n\n Local<ObjectTemplate> instance_t = t->InstanceTemplate();\n instance_t->SetAccessor(String::New(\"global\"), GetGlobal);\n instance_t->SetAccessor(String::New(\"g\"), GetG);\n NODE_SET_PROTOTYPE_METHOD(s_ct, \"evaluate\", Evaluate);\n\n target->Set(String::NewSymbol(\"WindowContext\"), s_ct->GetFunction());\n }\n\n\n \/\/ Create a new wrapper context around the global object.\n WindowContext(Handle<Object> global) {\n Handle<ObjectTemplate> tmpl = ObjectTemplate::New();\n this->global = Persistent<Object>::New(global);\n tmpl->SetNamedPropertyHandler(GetProperty, SetProperty, QueryProperty, DeleteProperty, EnumerateProperties, this->global);\n context = Context::New(NULL, tmpl);\n\n \/\/ Copy primitivies in context.\n context->Enter();\n SetPrimitive *primitive;\n for (int i = 0 ; (primitive = primitives[i]) ; ++i)\n if (primitive->InContext())\n global->Set(primitive->GetName(), primitive->GetValue());\n context->Exit();\n \/\/ Copy primitivies outside context.\n for (int i = 0 ; (primitive = primitives[i]) ; ++i)\n if (!primitive->InContext())\n global->Set(primitive->GetName(), primitive->GetValue());\n }\n\n ~WindowContext() {\n global.Dispose();\n context.Dispose();\n }\n\n \/\/ Takes single argument, the global object.\n static Handle<Value> New(const Arguments& args) {\n WindowContext* wc = new WindowContext(Handle<Object>::Cast(args[0]));\n wc->Wrap(args.This());\n return args.This();\n }\n\n \/\/ Returns the global object.\n static Handle<Value> GetGlobal(Local<String> name, const AccessorInfo& info) {\n WindowContext* wc = ObjectWrap::Unwrap<WindowContext>(info.This());\n return wc->global;\n }\n\n static Handle<Value> GetG(Local<String> name, const AccessorInfo& info) {\n WindowContext* wc = ObjectWrap::Unwrap<WindowContext>(info.This());\n return wc->context->Global();\n }\n\n \/\/ Evaluate expression or function in this context. First argument is either\n \/\/ a function or a script (String). In the later case, second argument\n \/\/ specifies filename.\n static Handle<Value> Evaluate(const Arguments& args) {\n WindowContext* wc = ObjectWrap::Unwrap<WindowContext>(args.This());\n Handle<Value> result;\n TryCatch trycatch;\n wc->context->Enter();\n if (args[0]->IsFunction()) {\n \/\/ Execute function in the global scope.\n Function *fn = Function::Cast(*args[0]);\n result = fn->Call(wc->global, 0, NULL);\n } else {\n \/\/ Coerce argument into a string and execute that as a function.\n Local<String> source = args[0]->ToString();\n Local<String> filename = args[1]->ToString();\n Handle<Script> script = Script::New(source, filename);\n result = script->Run();\n }\n wc->context->Exit();\n if (result.IsEmpty())\n trycatch.ReThrow();\n return result;\n }\n\n \/\/ Returns the value of a property from the global scope.\n static Handle<Value> GetProperty(Local<String> name, const AccessorInfo &info) {\n Local<Object> self = Local<Object>::Cast(info.Data());\n return self->Get(name);\n }\n\n \/\/ Sets the value of a property in the global scope.\n static Handle<Value> SetProperty(Local<String> name, Local<Value> value, const AccessorInfo &info) {\n Local<Object> self = Local<Object>::Cast(info.Data());\n self->Set(name, Persistent<Value>::New(value));\n return value;\n }\n\n \/\/ Deletes a property from the global scope.\n static Handle<Boolean> DeleteProperty(Local<String> name, const AccessorInfo &info) {\n HandleScope scope;\n Local<Object> self = Local<Object>::Cast(info.Data());\n Persistent<Value> value = (Persistent<Value>) self->Get(name);\n bool deleted = self->Delete(name);\n if (deleted)\n value.Dispose();\n return scope.Close(Boolean::New(deleted));\n }\n\n \/\/ Enumerate all named properties in the global scope.\n static Handle<Array> EnumerateProperties(const AccessorInfo &info) {\n HandleScope scope;\n Local<Object> self = Local<Object>::Cast(info.Data());\n return scope.Close(self->GetPropertyNames());\n }\n\n static Handle<Integer> QueryProperty(Local<String> name, const AccessorInfo &info) {\n HandleScope scope;\n return scope.Close(Integer::New(None));\n }\n \n};\n\n\nPersistent<FunctionTemplate> WindowContext::s_ct;\nSetPrimitive *WindowContext::primitives[] = {\n new SetPrimitive(\"Array\", \"[].constructor\"),\n new SetPrimitive(\"Boolean\", \"true.constructor\"),\n new SetPrimitive(\"Function\", \"(function() {}).constructor\"),\n new SetPrimitive(\"Number\", \"(1).constructor\"),\n new SetPrimitive(\"Object\", \"({}).constructor\"),\n new SetPrimitive(\"RegExp\", \"\/.\/.constructor\"),\n new SetPrimitive(\"String\", \"''.constructor\"),\n new SetPrimitive(\"Date\"),\n new SetPrimitive(\"Error\"),\n new SetPrimitive(\"Image\", \"{}\", false),\n new SetPrimitive(\"Math\"),\n new SetPrimitive(\"decodeURI\"),\n new SetPrimitive(\"decodeURIComponent\"),\n new SetPrimitive(\"encodeURI\"),\n new SetPrimitive(\"encodeURIComponent\"),\n new SetPrimitive(\"escape\"),\n new SetPrimitive(\"eval\"),\n new SetPrimitive(\"isFinite\"),\n new SetPrimitive(\"isNaN\"),\n new SetPrimitive(\"parseFloat\"),\n new SetPrimitive(\"parseInt\"),\n new SetPrimitive(\"unescape\"),\n NULL \/\/ please don't remove\n};\n\n\nextern \"C\" {\n static void init(Handle<Object> target) {\n WindowContext::Init(target);\n }\n NODE_MODULE(window_context, init);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 BitPay Inc.\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <ctype.h>\n#include <stdio.h>\n#include \"univalue.h\"\n#include \"univalue_escapes.h\"\n\n\/\/ TODO: Using UTF8\n\nusing namespace std;\n\nstatic string json_escape(const string& inS)\n{\n string outS;\n outS.reserve(inS.size() * 2);\n\n for (unsigned int i = 0; i < inS.size(); i++) {\n unsigned char ch = inS[i];\n const char *escStr = escapes[ch];\n\n if (escStr)\n outS += escStr;\n\n else if (isprint(ch))\n outS += ch;\n\n else {\n char tmpesc[16];\n sprintf(tmpesc, \"\\\\u%04x\", ch);\n outS += tmpesc;\n }\n }\n\n return outS;\n}\n\nstring UniValue::write(unsigned int prettyIndent,\n unsigned int indentLevel) const\n{\n string s;\n s.reserve(1024);\n\n unsigned int modIndent = indentLevel;\n if (modIndent == 0)\n modIndent = 1;\n\n switch (typ) {\n case VNULL:\n s += \"null\";\n break;\n case VOBJ:\n writeObject(prettyIndent, modIndent, s);\n break;\n case VARR:\n writeArray(prettyIndent, modIndent, s);\n break;\n case VSTR:\n s += \"\\\"\" + json_escape(val) + \"\\\"\";\n break;\n case VNUM:\n s += val;\n break;\n case VBOOL:\n s += (val == \"1\" ? \"true\" : \"false\");\n break;\n }\n\n return s;\n}\n\nstatic string spaceStr;\n\nstatic string indentStr(unsigned int prettyIndent, unsigned int indentLevel)\n{\n unsigned int spaces = prettyIndent * indentLevel;\n while (spaceStr.size() < spaces)\n spaceStr += \" \";\n\n return spaceStr.substr(0, spaces);\n}\n\nvoid UniValue::writeArray(unsigned int prettyIndent, unsigned int indentLevel, string& s) const\n{\n s += \"[\";\n if (prettyIndent)\n s += \"\\n\";\n\n for (unsigned int i = 0; i < values.size(); i++) {\n if (prettyIndent)\n s += indentStr(prettyIndent, indentLevel);\n s += values[i].write(prettyIndent, indentLevel + 1);\n if (i != (values.size() - 1)) {\n s += \",\";\n if (prettyIndent)\n s += \" \";\n }\n if (prettyIndent)\n s += \"\\n\";\n }\n\n if (prettyIndent)\n s += indentStr(prettyIndent, indentLevel - 1);\n s += \"]\";\n}\n\nvoid UniValue::writeObject(unsigned int prettyIndent, unsigned int indentLevel, string& s) const\n{\n s += \"{\";\n if (prettyIndent)\n s += \"\\n\";\n\n for (unsigned int i = 0; i < keys.size(); i++) {\n if (prettyIndent)\n s += indentStr(prettyIndent, indentLevel);\n s += \"\\\"\" + json_escape(keys[i]) + \"\\\":\";\n if (prettyIndent)\n s += \" \";\n s += values[i].write(prettyIndent, indentLevel + 1);\n if (i != (values.size() - 1))\n s += \",\";\n if (prettyIndent)\n s += \"\\n\";\n }\n\n if (prettyIndent)\n s += indentStr(prettyIndent, indentLevel - 1);\n s += \"}\";\n}\n\n<commit_msg>univalue: make spaceStr thread-safe<commit_after>\/\/ Copyright 2014 BitPay Inc.\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <ctype.h>\n#include <stdio.h>\n#include \"univalue.h\"\n#include \"univalue_escapes.h\"\n\n\/\/ TODO: Using UTF8\n\nusing namespace std;\n\nstatic string json_escape(const string& inS)\n{\n string outS;\n outS.reserve(inS.size() * 2);\n\n for (unsigned int i = 0; i < inS.size(); i++) {\n unsigned char ch = inS[i];\n const char *escStr = escapes[ch];\n\n if (escStr)\n outS += escStr;\n\n else if (isprint(ch))\n outS += ch;\n\n else {\n char tmpesc[16];\n sprintf(tmpesc, \"\\\\u%04x\", ch);\n outS += tmpesc;\n }\n }\n\n return outS;\n}\n\nstring UniValue::write(unsigned int prettyIndent,\n unsigned int indentLevel) const\n{\n string s;\n s.reserve(1024);\n\n unsigned int modIndent = indentLevel;\n if (modIndent == 0)\n modIndent = 1;\n\n switch (typ) {\n case VNULL:\n s += \"null\";\n break;\n case VOBJ:\n writeObject(prettyIndent, modIndent, s);\n break;\n case VARR:\n writeArray(prettyIndent, modIndent, s);\n break;\n case VSTR:\n s += \"\\\"\" + json_escape(val) + \"\\\"\";\n break;\n case VNUM:\n s += val;\n break;\n case VBOOL:\n s += (val == \"1\" ? \"true\" : \"false\");\n break;\n }\n\n return s;\n}\n\nstatic void indentStr(unsigned int prettyIndent, unsigned int indentLevel, string& s)\n{\n s.append(prettyIndent * indentLevel, ' ');\n}\n\nvoid UniValue::writeArray(unsigned int prettyIndent, unsigned int indentLevel, string& s) const\n{\n s += \"[\";\n if (prettyIndent)\n s += \"\\n\";\n\n for (unsigned int i = 0; i < values.size(); i++) {\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel, s);\n s += values[i].write(prettyIndent, indentLevel + 1);\n if (i != (values.size() - 1)) {\n s += \",\";\n if (prettyIndent)\n s += \" \";\n }\n if (prettyIndent)\n s += \"\\n\";\n }\n\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel - 1, s);\n s += \"]\";\n}\n\nvoid UniValue::writeObject(unsigned int prettyIndent, unsigned int indentLevel, string& s) const\n{\n s += \"{\";\n if (prettyIndent)\n s += \"\\n\";\n\n for (unsigned int i = 0; i < keys.size(); i++) {\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel, s);\n s += \"\\\"\" + json_escape(keys[i]) + \"\\\":\";\n if (prettyIndent)\n s += \" \";\n s += values[i].write(prettyIndent, indentLevel + 1);\n if (i != (values.size() - 1))\n s += \",\";\n if (prettyIndent)\n s += \"\\n\";\n }\n\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel - 1, s);\n s += \"}\";\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef PARSER__HH\n#define PARSER__HH \n\n#include <map>\n#include <iostream>\n#include <string>\n#include <vector>\n\nnamespace optionparser\n{\n\ntypedef std::map<std::string, std::map<std::string, std::vector<std::string>>> Dictionary;\n\nenum storage_mode { store_true, store_value, store_mult_values };\n\n\n\nclass parser\n{\npublic:\n\tparser();\n\t~parser();\n\n\tvoid eat_arguments(int argc, char const *argv[]);\n\n\tvoid add_option(std::string longoption, std::string shortoption, storage_mode mode, std::string key = \"\", bool required = false);\n\tvoid add_option(std::string shortoption, storage_mode mode, std::string key = \"\", bool required = false);\n\n\ttemplate <class T>\n\tT get_value(std::string key);\n\nprivate:\n\tDictionary options;\n\n\t\n};\n\n\n\n\n\n}\n\n#endif<commit_msg>worked on option adding<commit_after>#ifndef PARSER__HH\n#define PARSER__HH \n\n#include <map>\n#include <iostream>\n#include <string>\n#include <vector>\n\nnamespace optionparser\n{\n\ninline std::string remove_character(std::string str, char c = ' ');\n\ntypedef std::map<std::string, std::map<std::string, std::vector<std::string>>> Archive;\n\ntypedef std::map<std::string, std::map<std::string, std::string>> Dictionary;\n\n\n\nenum storage_mode { store_true, store_value, store_mult_values };\n\n\n\nclass parser\n{\npublic:\n\tparser();\n\t~parser();\n\n\t\/\/ void eat_arguments(int argc, char const *argv[]);\n\n\tvoid add_option(std::string longoption, std::string shortoption, storage_mode mode, std::string key = \"\", bool required = false);\n\tvoid add_option(std::string shortoption, storage_mode mode, std::string key = \"\", bool required = false);\n\n\t\/\/ template <class T>\n\t\/\/ T get_value(std::string key);\n\nprivate:\n\tArchive m_options;\n\tDictionary m_long_flags, m_short_flags;\n};\n\nvoid parser::add_option(std::string longoption, std::string shortoption, \n\tstorage_mode mode, std::string key = \"\", bool required = false)\n{\n\tif (key == \"\")\n\t{\n\t\tkey = remove_character(longoption, '-');\n\t}\n\tif (required)\n\t{\n\t\tstd::string req_string = \"required\";\n\t}\n\telse\n\t{\n\t\tstd::string req_string = \"optional\";\n\t}\n\tm_long_flags[req_string][key] = shortoption;\n\tm_short_flags[req_string][key] = longoption;\n}\n\n\n\n\n\n\n\n\n\n\n\ninline std::string remove_character(std::string str, char c)\n{\n std::string::iterator end_pos = std::remove(str.begin(), str.end(), c);\n str.erase(end_pos, str.end());\n return str;\n}\n\n\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/*-------------Lanczos.cpp----------------------------------------------------\/\/\n*\n* Purpose: To diagonalize a random matrix using the Lanczos algorithm\n*\n* Notes: Compile with (for Arch systems):\n* g++ -I \/usr\/include\/eigen3\/ Lanczos.cpp\n* 0's along the prime diagonal. I don't know what this means.\n*\n*-----------------------------------------------------------------------------*\/\n \n#include <iostream>\n#include <Eigen\/Core>\n#include <Eigen\/QR>\n#include <random>\n#include <vector>\n#include <math.h>\n\nusing namespace Eigen;\n\n\/\/ Function for the lanczos algorithm, returns Tri-diagonal matrix\nMatrixXd lanczos(MatrixXd &d_matrix, int row_num);\n\n\/\/ Function for QR decomposition\nMatrixXd qrdecomp(MatrixXd &Tridiag);\n\n\/\/ Function to perform the Power Method\nvoid p_method(MatrixXd &Tridiag, MatrixXd &Q);\n\n\/\/ Function to return sign of value (signum function)\nint sign(double value);\n\n\/\/ Function to check eigenvectors and values\nvoid eigentest(MatrixXd &d_matrix, MatrixXd &Q);\n\n\/*----------------------------------------------------------------------------\/\/\n* MAIN\n*-----------------------------------------------------------------------------*\/\n\nint main(){\n\/*\n int size = 200;\n MatrixXd d_matrix(size,size);\n\n \/\/ set up random device\n static std::random_device rd;\n int seed = rd();\n static std::mt19937 gen(seed);\n std::uniform_real_distribution<double> dist(0,1);\n\n for (size_t i = 0; i < d_matrix.rows(); ++i){\n for (size_t j = 0; j <= i; ++j){\n d_matrix(i,j) = dist(gen);\n d_matrix(j,i) = d_matrix(i,j);\n }\n }\n\n Tridiag = lanczos(d_matrix, 5);\n\n std::cout << '\\n' << \"Tridiagonal matrix is: \\n\";\n\n for (size_t i = 0; i < Tridiag.rows(); ++i){\n for (size_t j = 0; j < Tridiag.cols(); ++j){\n std::cout << Tridiag(i, j) << '\\t';\n }\n std::cout << '\\n';\n }\n\n std::cout << '\\n';\n*\/\n\n MatrixXd Tridiag(4,4); \n Tridiag << 2, 1, 3, 5,\n -1, 0, 7, 1,\n 0,-1,-1,3,\n -3,7,4,3;\n\n Tridiag = lanczos(Tridiag, 3);\n\n MatrixXd Q = qrdecomp(Tridiag);\n\n MatrixXd Qtemp = Q;\n\n std::cout << \"Q is: \" << '\\n';\n std::cout << Q << '\\n';\n\n std::cout << \"Finding eigenvalues: \" << '\\n';\n p_method(Tridiag, Q);\n\n Qtemp = Qtemp - Q;\n std::cout << \"After the Power Method: \" << Qtemp.squaredNorm() << '\\n';\n eigentest(Tridiag, Q);\n\n}\n\n\/*----------------------------------------------------------------------------\/\/\n* SUBROUTINE\n*-----------------------------------------------------------------------------*\/\n\n\/\/ Function for the lanczos algorithm, returns Tri-diagonal matrix\nMatrixXd lanczos(MatrixXd &d_matrix, int row_num){\n\n \/\/ Creating random device\n static std::random_device rd;\n int seed = rd();\n static std::mt19937 gen(seed);\n std::uniform_real_distribution<double> dist(0,1); \n\n \/\/ Defining values\n double threshold = 0.01;\n int j = 0;\n int size = d_matrix.rows();\n\n \/\/ Setting beta arbitrarily large for now \n double beta = 10;\n\n \/\/ generating the first rayleigh vector\n \/\/ alpha is actually just a double... sorry about that.\n MatrixXd rayleigh(d_matrix.rows(),1), q(d_matrix.rows(),1),\n alpha(1, 1);\n MatrixXd identity = MatrixXd::Identity(d_matrix.rows(), d_matrix.cols());\n\n \/\/ krylov is the krylovian subspace... Note, there might be a dynamic way to\n \/\/ do this. Something like:\n \/\/std::vector <MatrixXd> krylov;\n MatrixXd krylov(d_matrix.rows(), row_num);\n\n for (size_t i = 0; i < size; ++i){\n rayleigh(i) = dist(gen);\n }\n\n \/\/std::cout << rayleigh << '\\n';\n\n \/\/while (beta > threshold){\n for (size_t i = 0; i < row_num; ++i){\n beta = rayleigh.norm();\n \/\/std::cout << \"beta is: \\n\" << beta << '\\n';\n\n q = rayleigh \/ beta;\n \/\/std::cout << \"q is: \\n\" << q << '\\n';\n\n alpha = q.transpose() * d_matrix * q;\n \/\/std::cout << \"alpha is \\n\" << alpha << '\\n';\n\n if (j == 0){\n rayleigh = (d_matrix - alpha(0,0) * identity) * q;\n }\n else{\n rayleigh = (d_matrix - alpha(0,0) * identity) * q \n - beta * krylov.col(j - 1);\n\n }\n \/\/std::cout << \"rayleigh is: \\n\" << rayleigh <<'\\n';\n \/\/std::cout << \"i is: \" << i << '\\n';\n\n \/\/krylov.push_back(q);\n krylov.col(j) = q;\n j = j+1;\n \/\/ std::cout << j << '\\n';\n }\n\n MatrixXd krylov_id = krylov.transpose() * krylov;\n std::cout << \"The identity matrix from the krylov subspace is: \\n\" \n << krylov_id << '\\n';\n\n MatrixXd T(row_num,row_num);\n T = krylov.transpose() * d_matrix * krylov;\n\n return T;\n}\n\n\/\/ Function for QR decomposition\n\/\/ Because we only need Q for the power method, I will retun only Q\nMatrixXd qrdecomp(MatrixXd &Tridiag){\n \/\/ Q is and orthonormal vector => Q'Q = 1\n MatrixXd Id = MatrixXd::Identity(Tridiag.rows(), Tridiag.cols());\n MatrixXd Q = Id;\n MatrixXd P(Tridiag.rows(), Tridiag.cols());\n\n \/\/ R is the upper triangular matrix\n MatrixXd R = Tridiag;\n\n int row_num = Tridiag.rows();\n int countx = 0, county = 0;\n\n \/\/ Scale R \n double sum = 0.0, sigma, tau, fak, max_val = 0;\n\n bool sing;\n\n \/\/ Defining vectors for algorithm\n MatrixXd diag(row_num,1);\n\n \/\/std::cout << R << '\\n';\n\n for (int i = 0; i < row_num-1; ++i){\n diag = MatrixXd::Zero(row_num, 1);\n\n sum = 0;\n for (size_t j = i; j < row_num; ++j){\n sum += R(j,i) * R(j,i);\n \/\/std::cout << R(j,i) << '\\n';\n }\n sum = sqrt(sum);\n\n if (R(i,i) > 0){\n sigma = -sum;\n }\n else{\n sigma = sum;\n }\n\n \/\/std::cout << \"sigma is: \" << sigma << '\\n';\n\n sum = 0;\n \/\/diag = R.block(i,i, row_num - i, 1);\n \/\/std::cout << \"diag is: \" << '\\n';\n for (int j = i; j < row_num; ++j){\n \/\/std::cout << i << '\\t' << j << '\\n';\n if (j == i){\n diag(j) = R(j,i) + sigma;\n }\n else{\n diag(j) = R(j, i);\n }\n \/\/std::cout << diag(j) << '\\n';\n sum = sum + diag(j) * diag(j);\n }\n sum = sqrt(sum);\n\n \/\/std::cout << \"sum is: \" << sum << '\\n';\n\n if (sum > 0.000000000000001){\n\n for (int j = i; j < row_num; ++j){\n diag(j) = diag(j) \/ sum;\n }\n \n \/\/std::cout << \"normalized diag is: \" << '\\n' << diag << '\\n';\n \n P = Id - (diag * diag.transpose()) * 2.0;\n \n R = P * R;\n Q = Q * P;\n }\n\n \/\/std::cout << \"R is: \" << R << '\\n';\n\n }\n \/\/std::cout << \"R is: \" << R << '\\n';\n \/\/std::cout << \"Q is: \" << Q << '\\n';\n\n \/\/std::cout << \"QR is: \" << '\\n' << Q*R << '\\n';\n\n std::cout << \"Q^T * Q is: \" << '\\n' << Q.transpose() * Q << '\\n' << '\\n';\n std::cout << \"QR - A is: \" << '\\n' << Q*R - Tridiag << '\\n';\n \/\/std::cout << \"Q^T * A - R: \" << '\\n'\n \/\/ << Q.transpose() * Tridiag - R << '\\n' << '\\n';\n\n return Q;\n}\n\n\/\/ Function to perform the Power Method\nvoid p_method(MatrixXd &Tridiag, MatrixXd &Q){\n\n std::cout << \"Q is: \" << '\\n' << Q << '\\n';\n std::cout << \"Tridiag is : \" << '\\n' << Tridiag << '\\n';\n\n \/\/ Find all eigenvectors\n MatrixXd eigenvectors(Tridiag.rows(), Tridiag.cols());\n MatrixXd Z(Tridiag.rows(), Tridiag.cols());\n MatrixXd Qtemp = Q;\n\n \/\/ Iteratively defines eigenvectors\n for (int i = 0; i < Tridiag.rows(); ++i){\n Z = Tridiag * Q;\n Q = qrdecomp(Z);\n\n }\n\n Qtemp = Qtemp - Q;\n std::cout << \"This should not be 0: \" << Qtemp.squaredNorm() << '\\n';\n\n}\n\n\/\/ Function to return sign of value (signum function)\nint sign(double value){\n if (value < 0.0){\n return -1;\n }\n else if (value > 0){\n return 1;\n }\n else {\n return 0;\n }\n}\n\n\/\/ Function to check eigenvectors and values\nvoid eigentest(MatrixXd &Tridiag, MatrixXd &Q){\n\n \/\/ Calculating the Rayleigh quotient (v^t * A * v) \/ (v^t * v)\n \/\/ Note, that this should be a representation of eigenvalues\n\n std::vector<double> eigenvalues(Tridiag.rows());\n MatrixXd checkvector(Tridiag.rows(),1);\n double QQ, QAQ;\n\n for (size_t i = 0; i < Tridiag.rows(); ++i){\n QQ = Q.col(i).transpose() * Q.col(i); \n QAQ = Q.col(i).transpose() * Tridiag * Q.col(i);\n eigenvalues[i] = QAQ \/ QQ;\n std::cout << \"eigenvalue is: \" << eigenvalues[i] << '\\n';\n\n checkvector = ((Tridiag * Q.col(i)) \/ eigenvalues[i]) - Q.col(i);\n std::cout << checkvector << '\\n' << '\\n';\n std::cout << \"This should be 0: \" << '\\t' \n << checkvector.squaredNorm() << '\\n';\n \n }\n\n}\n\n<commit_msg>commenting out unnecessary cout statements.<commit_after>\/*-------------Lanczos.cpp----------------------------------------------------\/\/\n*\n* Purpose: To diagonalize a random matrix using the Lanczos algorithm\n*\n* Notes: Compile with (for Arch systems):\n* g++ -I \/usr\/include\/eigen3\/ Lanczos.cpp\n* 0's along the prime diagonal. I don't know what this means.\n*\n*-----------------------------------------------------------------------------*\/\n \n#include <iostream>\n#include <Eigen\/Core>\n#include <Eigen\/QR>\n#include <random>\n#include <vector>\n#include <math.h>\n\nusing namespace Eigen;\n\n\/\/ Function for the lanczos algorithm, returns Tri-diagonal matrix\nMatrixXd lanczos(MatrixXd &d_matrix, int row_num);\n\n\/\/ Function for QR decomposition\nMatrixXd qrdecomp(MatrixXd &Tridiag);\n\n\/\/ Function to perform the Power Method\nvoid p_method(MatrixXd &Tridiag, MatrixXd &Q);\n\n\/\/ Function to return sign of value (signum function)\nint sign(double value);\n\n\/\/ Function to check eigenvectors and values\nvoid eigentest(MatrixXd &d_matrix, MatrixXd &Q);\n\n\/*----------------------------------------------------------------------------\/\/\n* MAIN\n*-----------------------------------------------------------------------------*\/\n\nint main(){\n\n int size = 200;\n MatrixXd d_matrix(size,size);\n\n \/\/ set up random device\n static std::random_device rd;\n int seed = rd();\n static std::mt19937 gen(seed);\n std::uniform_real_distribution<double> dist(0,1);\n\n for (size_t i = 0; i < d_matrix.rows(); ++i){\n for (size_t j = 0; j <= i; ++j){\n d_matrix(i,j) = dist(gen);\n d_matrix(j,i) = d_matrix(i,j);\n }\n }\n\n MatrixXd Tridiag = lanczos(d_matrix, 20);\n\n \/\/std::cout << '\\n' << \"Tridiagonal matrix is: \\n\" << Tridiag << '\\n';\n\n \/*\n \/\/ Testing for eigenvalue determination\n MatrixXd Tridiag(3,3);\n Tridiag << 1, 2, 0,\n 2, 1, 0,\n 0, 0, -3;\n\n MatrixXd Tridiag(5,5);\n Tridiag << 5, 0, 0, 0, 0,\n 0, 4, 0, 0, 0,\n 0, 0, 3, 0, 0,\n 0, 0, 0, 2, 0,\n 0, 0, 0, 0, 7;\n Tridiag = lanczos(Tridiag, 5);\n *\/\n\n \/\/std::cout << \"Tridiag is: \" << '\\n' << Tridiag << '\\n';\n\n MatrixXd Q = qrdecomp(Tridiag);\n\n MatrixXd Qtemp = Q;\n\n \/\/std::cout << \"Q is: \" << '\\n';\n \/\/std::cout << Q << '\\n';\n\n std::cout << \"Finding eigenvalues: \" << '\\n';\n p_method(Tridiag, Q);\n\n \/\/std::cout << \"Q is: \" << '\\n' << Q << '\\n';\n\n Qtemp = Qtemp - Q;\n \/\/std::cout << \"After the Power Method: \" << Qtemp.squaredNorm() << '\\n';\n eigentest(Tridiag, Q);\n\n}\n\n\/*----------------------------------------------------------------------------\/\/\n* SUBROUTINE\n*-----------------------------------------------------------------------------*\/\n\n\/\/ Function for the lanczos algorithm, returns Tri-diagonal matrix\nMatrixXd lanczos(MatrixXd &d_matrix, int row_num){\n\n \/\/ Creating random device\n static std::random_device rd;\n int seed = rd();\n static std::mt19937 gen(seed);\n std::uniform_real_distribution<double> dist(0,1); \n\n \/\/ Defining values\n double threshold = 0.01;\n int j = 0;\n int size = d_matrix.rows();\n\n \/\/ Setting beta arbitrarily large for now \n double beta = 10;\n\n \/\/ generating the first rayleigh vector\n \/\/ alpha is actually just a double... sorry about that.\n MatrixXd rayleigh(d_matrix.rows(),1), q(d_matrix.rows(),1),\n alpha(1, 1);\n MatrixXd identity = MatrixXd::Identity(d_matrix.rows(), d_matrix.cols());\n\n \/\/ krylov is the krylovian subspace... Note, there might be a dynamic way to\n \/\/ do this. Something like:\n \/\/std::vector <MatrixXd> krylov;\n MatrixXd krylov(d_matrix.rows(), row_num);\n\n for (size_t i = 0; i < size; ++i){\n rayleigh(i) = dist(gen);\n }\n\n \/\/std::cout << rayleigh << '\\n';\n\n \/\/while (beta > threshold){\n for (size_t i = 0; i < row_num; ++i){\n beta = rayleigh.norm();\n \/\/std::cout << \"beta is: \\n\" << beta << '\\n';\n\n q = rayleigh \/ beta;\n \/\/std::cout << \"q is: \\n\" << q << '\\n';\n\n alpha = q.transpose() * d_matrix * q;\n \/\/std::cout << \"alpha is \\n\" << alpha << '\\n';\n\n if (j == 0){\n rayleigh = (d_matrix - alpha(0,0) * identity) * q;\n }\n else{\n rayleigh = (d_matrix - alpha(0,0) * identity) * q \n - beta * krylov.col(j - 1);\n\n }\n \/\/std::cout << \"rayleigh is: \\n\" << rayleigh <<'\\n';\n \/\/std::cout << \"i is: \" << i << '\\n';\n\n \/\/krylov.push_back(q);\n krylov.col(j) = q;\n j = j+1;\n \/\/ std::cout << j << '\\n';\n }\n\n \/*\n MatrixXd krylov_id = krylov.transpose() * krylov;\n std::cout << \"The identity matrix from the krylov subspace is: \\n\" \n << krylov_id << '\\n';\n *\/\n\n MatrixXd T(row_num,row_num);\n T = krylov.transpose() * d_matrix * krylov;\n\n return T;\n}\n\n\/\/ Function for QR decomposition\n\/\/ Because we only need Q for the power method, I will retun only Q\nMatrixXd qrdecomp(MatrixXd &Tridiag){\n \/\/ Q is and orthonormal vector => Q'Q = 1\n MatrixXd Id = MatrixXd::Identity(Tridiag.rows(), Tridiag.cols());\n MatrixXd Q = Id;\n MatrixXd P(Tridiag.rows(), Tridiag.cols());\n\n \/\/ R is the upper triangular matrix\n MatrixXd R = Tridiag;\n\n int row_num = Tridiag.rows();\n int countx = 0, county = 0;\n\n \/\/ Scale R \n double sum = 0.0, sigma, tau, fak, max_val = 0;\n\n bool sing;\n\n \/\/ Defining vectors for algorithm\n MatrixXd diag(row_num,1);\n\n \/\/std::cout << R << '\\n';\n\n for (int i = 0; i < row_num-1; ++i){\n diag = MatrixXd::Zero(row_num, 1);\n\n sum = 0;\n for (size_t j = i; j < row_num; ++j){\n sum += R(j,i) * R(j,i);\n \/\/std::cout << R(j,i) << '\\n';\n }\n sum = sqrt(sum);\n\n if (R(i,i) > 0){\n sigma = -sum;\n }\n else{\n sigma = sum;\n }\n\n \/\/std::cout << \"sigma is: \" << sigma << '\\n';\n\n sum = 0;\n \/\/diag = R.block(i,i, row_num - i, 1);\n \/\/std::cout << \"diag is: \" << '\\n';\n for (int j = i; j < row_num; ++j){\n \/\/std::cout << i << '\\t' << j << '\\n';\n if (j == i){\n diag(j) = R(j,i) + sigma;\n }\n else{\n diag(j) = R(j, i);\n }\n \/\/std::cout << diag(j) << '\\n';\n sum = sum + diag(j) * diag(j);\n }\n sum = sqrt(sum);\n\n \/\/std::cout << \"sum is: \" << sum << '\\n';\n\n if (sum > 0.000000000000001){\n\n for (int j = i; j < row_num; ++j){\n diag(j) = diag(j) \/ sum;\n }\n \n \/\/std::cout << \"normalized diag is: \" << '\\n' << diag << '\\n';\n \n P = Id - (diag * diag.transpose()) * 2.0;\n \n R = P * R;\n Q = Q * P;\n }\n\n \/\/std::cout << \"R is: \" << R << '\\n';\n\n }\n \/\/std::cout << \"R is: \" << R << '\\n';\n \/\/std::cout << \"Q is: \" << Q << '\\n';\n\n \/\/std::cout << \"QR is: \" << '\\n' << Q*R << '\\n';\n\n \/\/std::cout << \"Q^T * Q is: \" << '\\n' << Q.transpose() * Q << '\\n' << '\\n';\n \/\/std::cout << \"QR - A is: \" << '\\n' << Q*R - Tridiag << '\\n';\n \/\/std::cout << \"Q^T * A - R: \" << '\\n'\n \/\/ << Q.transpose() * Tridiag - R << '\\n' << '\\n';\n\n return Q;\n}\n\n\/\/ Function to perform the Power Method\nvoid p_method(MatrixXd &Tridiag, MatrixXd &Q){\n\n \/\/std::cout << \"Q is: \" << '\\n' << Q << '\\n';\n \/\/std::cout << \"Tridiag is : \" << '\\n' << Tridiag << '\\n';\n\n \/\/ Find all eigenvectors\n MatrixXd eigenvectors(Tridiag.rows(), Tridiag.cols());\n MatrixXd Z(Tridiag.rows(), Tridiag.cols());\n MatrixXd Qtemp = Q;\n\n \/\/ Iteratively defines eigenvectors\n for (int i = 0; i < Tridiag.rows(); ++i){\n Z = Tridiag * Q;\n Q = qrdecomp(Z);\n\n }\n\n Qtemp = Qtemp - Q;\n \/\/std::cout << \"This should not be 0: \" << Qtemp.squaredNorm() << '\\n';\n\n}\n\n\/\/ Function to return sign of value (signum function)\nint sign(double value){\n if (value < 0.0){\n return -1;\n }\n else if (value > 0){\n return 1;\n }\n else {\n return 0;\n }\n}\n\n\/\/ Function to check eigenvectors and values\nvoid eigentest(MatrixXd &Tridiag, MatrixXd &Q){\n\n \/\/ Calculating the Rayleigh quotient (v^t * A * v) \/ (v^t * v)\n \/\/ Note, that this should be a representation of eigenvalues\n\n std::vector<double> eigenvalues(Tridiag.rows());\n MatrixXd checkvector(Tridiag.rows(),1);\n double QQ, QAQ;\n\n for (size_t i = 0; i < Tridiag.rows(); ++i){\n QQ = Q.col(i).transpose() * Q.col(i); \n QAQ = Q.col(i).transpose() * Tridiag * Q.col(i);\n eigenvalues[i] = QAQ \/ QQ;\n std::cout << \"eigenvalue is: \" << eigenvalues[i] << '\\n';\n\n checkvector = ((Tridiag * Q.col(i)) \/ eigenvalues[i]) - Q.col(i);\n \/\/std::cout << checkvector << '\\n' << '\\n';\n std::cout << \"This should be 0: \" << '\\t' \n << checkvector.squaredNorm() << '\\n';\n \n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2004, Industrial Light & Magic, a division of Lucas\n\/\/ Digital Ltd. LLC\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 are\n\/\/ met:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Industrial Light & Magic nor the names of\n\/\/ its 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 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\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/----------------------------------------------------------------------------\n\/\/\n\/\/\tAdd a preview image to an OpenEXR file.\n\/\/\n\/\/----------------------------------------------------------------------------\n\n\n#include <makePreview.h>\n\n#include <ImfInputFile.h>\n#include <ImfOutputFile.h>\n#include <ImfTiledOutputFile.h>\n#include <ImfRgbaFile.h>\n#include <ImfPreviewImage.h>\n#include <ImfArray.h>\n#include <ImathFun.h>\n#include <math.h>\n#include <iostream>\n\nusing namespace Imf;\nusing namespace Imath;\nusing namespace std;\n\n\nnamespace {\n\nfloat\nknee (float x, float f)\n{\n return log (x * f + 1) \/ f;\n}\n\n\nunsigned char\ngamma (half h, float m)\n{\n \/\/\n \/\/ Conversion from half to unsigned char pixel data,\n \/\/ with gamma correction. The conversion is the same\n \/\/ as in the exrdisplay program's ImageView class,\n \/\/ except with defog, kneeLow, and kneeHigh fixed\n \/\/ at 0.0, 0.0, and 5.0 respectively.\n \/\/\n\n float x = max (0.f, h * m);\n\n if (x > 1)\n\tx = 1 + knee (x - 1, 0.184874f);\n\n return (unsigned char) (clamp (pow (x, 0.4545f) * 84.66f, 0.f, 255.f));\n}\n\n\nvoid\ngeneratePreview (const char inFileName[],\n\t\t float exposure,\n\t\t int previewWidth,\n\t\t int &previewHeight,\n\t\t Array2D <PreviewRgba> &previewPixels)\n{\n \/\/\n \/\/ Read the input file\n \/\/\n\n RgbaInputFile in (inFileName);\n\n Box2i dw = in.dataWindow();\n float a = in.pixelAspectRatio();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n\n Array2D <Rgba> pixels (h, w);\n in.setFrameBuffer (&pixels[0][0] - dw.min.y * w - dw.min.x, 1, w);\n in.readPixels (dw.min.y, dw.max.y);\n\n \/\/\n \/\/ Make a preview image\n \/\/\n\n previewHeight = max (int (h \/ (w * a) * previewWidth + .5f), 1);\n previewPixels.resizeErase (previewHeight, previewWidth);\n\n float fx = (previewWidth > 0)? (float (w - 1) \/ (previewWidth - 1)): 1;\n float fy = (previewHeight > 0)? (float (h - 1) \/ (previewHeight - 1)): 1;\n float m = pow (2.f, clamp (exposure + 2.47393f, -20.f, 20.f));\n\n for (int y = 0; y < previewHeight; ++y)\n {\n\tfor (int x = 0; x < previewWidth; ++x)\n\t{\n\t PreviewRgba &preview = previewPixels[y][x];\n\t const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];\n\n\t preview.r = gamma (pixel.r, m);\n\t preview.g = gamma (pixel.g, m);\n\t preview.b = gamma (pixel.b, m);\n\t preview.a = int (clamp (pixel.a * 255.f, 0.f, 255.f) * .5f);\n\t}\n }\n}\n\n} \/\/ namespace\n\n\nvoid\nmakePreview (const char inFileName[],\n\t const char outFileName[],\n\t int previewWidth,\n\t float exposure,\n\t bool verbose)\n{\n if (verbose)\n\tcout << \"generating preview image\" << endl;\n\n Array2D <PreviewRgba> previewPixels;\n int previewHeight;\n\n generatePreview (inFileName,\n\t\t exposure,\n\t\t previewWidth,\n\t\t previewHeight,\n\t\t previewPixels);\n\n InputFile in (inFileName);\n Header header = in.header();\n\n header.setPreviewImage\n\t(PreviewImage (previewWidth, previewHeight, &previewPixels[0][0]));\n\n if (verbose)\n\tcout << \"copying \" << inFileName << \" to \" << outFileName << endl;\n\n if (header.hasTileDescription())\n {\n\tTiledOutputFile out (outFileName, header);\n\tout.copyPixels (in);\n }\n else\n {\n\tOutputFile out (outFileName, header);\n\tout.copyPixels (in);\n }\n\n if (verbose)\n\tcout << \"done.\" << endl;\n}\n<commit_msg><commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2004, Industrial Light & Magic, a division of Lucas\n\/\/ Digital Ltd. LLC\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 are\n\/\/ met:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Industrial Light & Magic nor the names of\n\/\/ its 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 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\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/----------------------------------------------------------------------------\n\/\/\n\/\/\tAdd a preview image to an OpenEXR file.\n\/\/\n\/\/----------------------------------------------------------------------------\n\n\n#include <makePreview.h>\n\n#include <ImfInputFile.h>\n#include <ImfOutputFile.h>\n#include <ImfTiledOutputFile.h>\n#include <ImfRgbaFile.h>\n#include <ImfPreviewImage.h>\n#include <ImfArray.h>\n#include <ImathMath.h>\n#include <ImathFun.h>\n#include <math.h>\n#include <iostream>\n\nusing namespace Imf;\nusing namespace Imath;\nusing namespace std;\n\n\nnamespace {\n\nfloat\nknee (float x, float f)\n{\n return log (x * f + 1) \/ f;\n}\n\n\nunsigned char\ngamma (half h, float m)\n{\n \/\/\n \/\/ Conversion from half to unsigned char pixel data,\n \/\/ with gamma correction. The conversion is the same\n \/\/ as in the exrdisplay program's ImageView class,\n \/\/ except with defog, kneeLow, and kneeHigh fixed\n \/\/ at 0.0, 0.0, and 5.0 respectively.\n \/\/\n\n float x = max (0.f, h * m);\n\n if (x > 1)\n\tx = 1 + knee (x - 1, 0.184874f);\n\n return (unsigned char) (clamp (Math<float>::pow (x, 0.4545f) * 84.66f, \n\t\t\t\t 0.f,\n\t\t\t\t 255.f));\n}\n\n\nvoid\ngeneratePreview (const char inFileName[],\n\t\t float exposure,\n\t\t int previewWidth,\n\t\t int &previewHeight,\n\t\t Array2D <PreviewRgba> &previewPixels)\n{\n \/\/\n \/\/ Read the input file\n \/\/\n\n RgbaInputFile in (inFileName);\n\n Box2i dw = in.dataWindow();\n float a = in.pixelAspectRatio();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n\n Array2D <Rgba> pixels (h, w);\n in.setFrameBuffer (&pixels[0][0] - dw.min.y * w - dw.min.x, 1, w);\n in.readPixels (dw.min.y, dw.max.y);\n\n \/\/\n \/\/ Make a preview image\n \/\/\n\n previewHeight = max (int (h \/ (w * a) * previewWidth + .5f), 1);\n previewPixels.resizeErase (previewHeight, previewWidth);\n\n float fx = (previewWidth > 0)? (float (w - 1) \/ (previewWidth - 1)): 1;\n float fy = (previewHeight > 0)? (float (h - 1) \/ (previewHeight - 1)): 1;\n float m = Math<float>::pow (2.f, clamp (exposure + 2.47393f, -20.f, 20.f));\n\n for (int y = 0; y < previewHeight; ++y)\n {\n\tfor (int x = 0; x < previewWidth; ++x)\n\t{\n\t PreviewRgba &preview = previewPixels[y][x];\n\t const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];\n\n\t preview.r = gamma (pixel.r, m);\n\t preview.g = gamma (pixel.g, m);\n\t preview.b = gamma (pixel.b, m);\n\t preview.a = int (clamp (pixel.a * 255.f, 0.f, 255.f) * .5f);\n\t}\n }\n}\n\n} \/\/ namespace\n\n\nvoid\nmakePreview (const char inFileName[],\n\t const char outFileName[],\n\t int previewWidth,\n\t float exposure,\n\t bool verbose)\n{\n if (verbose)\n\tcout << \"generating preview image\" << endl;\n\n Array2D <PreviewRgba> previewPixels;\n int previewHeight;\n\n generatePreview (inFileName,\n\t\t exposure,\n\t\t previewWidth,\n\t\t previewHeight,\n\t\t previewPixels);\n\n InputFile in (inFileName);\n Header header = in.header();\n\n header.setPreviewImage\n\t(PreviewImage (previewWidth, previewHeight, &previewPixels[0][0]));\n\n if (verbose)\n\tcout << \"copying \" << inFileName << \" to \" << outFileName << endl;\n\n if (header.hasTileDescription())\n {\n\tTiledOutputFile out (outFileName, header);\n\tout.copyPixels (in);\n }\n else\n {\n\tOutputFile out (outFileName, header);\n\tout.copyPixels (in);\n }\n\n if (verbose)\n\tcout << \"done.\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef stack_cpp\n#define stack_cpp\n#pragma once\n#include <iostream>\n#include <memory>\n\nclass bitset\n{\npublic:\n\texplicit\n\tbitset(size_t size);\n\n\tbitset(bitset const & other) = delete;\n\tauto operator =(bitset const & other)->bitset & = delete;\n\n\tbitset(bitset && other) = delete;\n\tauto operator =(bitset && other)->bitset & = delete;\n\n\tauto set(size_t index) -> void;\n\tauto reset(size_t index) -> void;\n\tauto test(size_t index) -> bool;\n\n\tauto size() const -> size_t;\n\tauto counter() const -> size_t;\n\nprivate:\n\tstd::unique_ptr<bool[]> ptr_;\n\tsize_t size_;\n\tsize_t counter_;\n};\n\nbitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {}\n\nauto bitset::set(size_t index) -> void\n{ \n\tif (index < size_) \n\t{\n\t\tptr_[index] = true; \n\t\t++counter_; \n\t}\n\telse throw(\"false_index\"); \n}\n\nauto bitset::reset(size_t index) -> void\n{\tif (index < size_)\n\t{\n\t\tptr_[index] = false;\n\t\t--counter_;\n\t}\n\telse throw(\"false_index\");\n}\n\nauto bitset::test(size_t index) -> bool\n{\n\tif (index < size_)\n\t{\n\t\treturn !ptr_[index];\n\t}\n\telse throw(\"false_index\");\n\t\n}\n\nauto bitset::size() const -> size_t\n{\n\treturn size_;\n}\n\nauto bitset::counter() const -> size_t\n{\n\treturn counter_;\n}\n\n\/*=====================================================================================*\/\n\ntemplate <typename T>\nclass allocator\n{\npublic:\n\texplicit\n\tallocator( std::size_t size = 0 );\n\tallocator( allocator const & other );\n\tauto operator =( allocator const & other ) -> allocator & = delete;\n\t~allocator();\n\tauto resize() -> void;\n\tauto construct(T * ptr, T const & value ) -> void;\n\tauto destroy( T * ptr ) -> void;\n\tauto get() -> T *;\n\tauto get() const -> T const *;\n\tauto count() const -> size_t;\n\tauto full() const -> bool;\n\tauto empty() const -> bool;\nprivate:\n\tauto destroy(T * first, T * last) -> void;\n\tauto swap(allocator & other) -> void;\n\tT * ptr_;\n\tsize_t size_;\n\tstd::unique_ptr<bitset> map_;\n\n};\n\ntemplate <typename T>\nallocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {};\n\n\ntemplate<typename T>\nallocator<T>::allocator(allocator const& other) :\nallocator<T>(other.size_)\n{\n\tfor (size_t i=0; i < size_; ++i)\n\t\tif (other.map_->test(i))\n\t\tconstruct(ptr_ + i, other.ptr_[i]);\n}\n\ntemplate<typename T>\nallocator<T>::~allocator()\n{ \n\tdestroy(ptr_, ptr_+size_);\n\toperator delete(ptr_); \n}\n\ntemplate<typename T>\nauto allocator<T>::resize() -> void\n{\n\tallocator<T> buff(size_ * 2 + (size_ == 0));\n\tfor (size_t i = 0; i < size_; ++i) construct(buff.ptr_ + i, ptr_[i]);\n\tthis->swap(buff);\n}\n\ntemplate<typename T>\nauto allocator<T>::construct(T * ptr, T const & value)->void \n{\n\tif (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) \n\t{\n\t\tnew(ptr)T(value);\n\t\tmap_->set(ptr - ptr_);\n\t}\n\telse throw(\"error\");\n}\n\ntemplate<typename T>\nauto allocator<T>::destroy(T * ptr) -> void \n{\n\tif(ptr>=ptr_&&ptr<=ptr_+this->count())\n\t{\n\t\tif (!map_->test(ptr-ptr_))\n\t\t{\n\t\tptr->~T();\n\t\tmap_->reset(ptr-ptr_);\n\t\t}\n\t}\n\telse throw(\"error\");\n}\n\ntemplate<typename T>\nauto allocator<T>::destroy(T * first, T * last) -> void\n{\t\n\tif(first>=ptr_&&last<=ptr_+this->count())\n\tfor (; first != last; ++first) \n\t{\n\t\tdestroy(&*first);\n\t}\n}\n\ntemplate<typename T>\nauto allocator<T>::get()-> T* \n{\n\treturn ptr_; \n}\n\ntemplate<typename T>\nauto allocator<T>::get() const -> T const * \n{ \n\treturn ptr_; \n}\n\ntemplate<typename T>\nauto allocator<T>::count() const -> size_t\n{\n\treturn map_->counter();\n}\n\ntemplate<typename T>\nauto allocator<T>::full() const -> bool\n{\n\treturn map_->counter()==size_;\n}\n\ntemplate<typename T>\nauto allocator<T>::empty() const -> bool\n{\n\treturn map_->counter()==0;\n}\n\ntemplate<typename T>\nauto allocator<T>::swap(allocator & other) -> void \n{\n\tstd::swap(ptr_, other.ptr_);\n\tstd::swap(count_, other.count_);\n\tstd::swap(size_, other.size_);\n}\n\n\/*=====================================================================================*\/\n\ntemplate <typename T>\nclass stack : private allocator<T>\n{\npublic:\n\texplicit\n\tstack(size_t size = 0);\t\t\t\t\t\t\t\t\/\/noexcept\n\tauto pop() -> void;\n\tauto top() -> T &;\n\tauto top() const -> T const &;\n\tauto push(T const &vaule) -> void;\t\t\t\t\t\t\t\/\/strong\n\tauto operator=(stack const & right)->stack &;\t\t\t\t\t\/\/strong\n\tauto empty() const -> bool; \t\t\t\t\t\t\t\/\/noexcept\n\tauto count() const -> size_t;\nprivate:\n\tallocator<T> allocator_;\n\tauto throw_is_empty() const -> void;\n};\n\ntemplate <typename T>\nsize_t stack<T>::count() const\n{\n\treturn allocator_.count();\n}\ntemplate <typename T>\nstack<T>::stack(size_t size):allocator_(size){}\n\ntemplate <typename T>\nvoid stack<T>::push(T const &item) \n{\n\tif (allocator_.full()) allocator_.resize(); \n\tallocator_.construct(allocator_.get() + this->count(), item);\n}\ntemplate<typename T>\nvoid stack<T>::pop() \n{\n\tif (this->count() > 0) \n\t\tallocator_.destroy(allocator_.get() + (this->count()-1));\n\telse \n\t\tthrow_is_empty();\n}\n\ntemplate<typename T>\nauto stack<T>::top() -> T &\n{\n\tif (allocator_.count() == 0) {\n\t\tthrow_is_empty();\n\t}\n\treturn (*(allocator_.get() + allocator_.count() - 1));\n}\n\ntemplate<typename T>\nauto stack<T>::top() const -> T const &\n{\n\tif (allocator_.count() == 0) \n\t{\n\t\tthrow_is_empty();\n\t}\n\treturn (*(allocator_.get() + allocator_.count() - 1));\n}\n\ntemplate<typename T>\nauto stack<T>::operator=(stack const & right)-> stack &\n{ \n\tif (this != &right) \n\t{\n\t\t(allocator<T>(right.allocator_)).swap(allocator_);\n\t}\n\treturn *this;\n}\n\ntemplate<typename T>\nauto stack<T>::empty() const -> bool \n{\n\treturn allocator_.empty(); \n}\n\ntemplate<typename T>\nauto stack<T>::throw_is_empty() const -> void\n{\n\t\tthrow(\"Stack is empty!\");\n}\n#endif\n<commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp\n#define stack_cpp\n#pragma once\n#include <iostream>\n#include <memory>\n\nclass bitset\n{\npublic:\n\texplicit\n\tbitset(size_t size);\n\n\tbitset(bitset const & other) = delete;\n\tauto operator =(bitset const & other)->bitset & = delete;\n\n\tbitset(bitset && other) = delete;\n\tauto operator =(bitset && other)->bitset & = delete;\n\n\tauto set(size_t index) -> void;\n\tauto reset(size_t index) -> void;\n\tauto test(size_t index) -> bool;\n\n\tauto size() const -> size_t;\n\tauto counter() const -> size_t;\n\nprivate:\n\tstd::unique_ptr<bool[]> ptr_;\n\tsize_t size_;\n\tsize_t counter_;\n};\n\nbitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {}\n\nauto bitset::set(size_t index) -> void\n{ \n\tif (index < size_) \n\t{\n\t\tptr_[index] = true; \n\t\t++counter_; \n\t}\n\telse throw(\"false_index\"); \n}\n\nauto bitset::reset(size_t index) -> void\n{\tif (index < size_)\n\t{\n\t\tptr_[index] = false;\n\t\t--counter_;\n\t}\n\telse throw(\"false_index\");\n}\n\nauto bitset::test(size_t index) -> bool\n{\n\tif (index < size_)\n\t{\n\t\treturn !ptr_[index];\n\t}\n\telse throw(\"false_index\");\n\t\n}\n\nauto bitset::size() const -> size_t\n{\n\treturn size_;\n}\n\nauto bitset::counter() const -> size_t\n{\n\treturn counter_;\n}\n\n\/*=====================================================================================*\/\n\ntemplate <typename T>\nclass allocator\n{\npublic:\n\texplicit\n\tallocator( std::size_t size = 0 );\n\tallocator( allocator const & other );\n\tauto operator =( allocator const & other ) -> allocator & = delete;\n\t~allocator();\n\tauto resize() -> void;\n\tauto construct(T * ptr, T const & value ) -> void;\n\tauto destroy( T * ptr ) -> void;\n\tauto get() -> T *;\n\tauto get() const -> T const *;\n\tauto count() const -> size_t;\n\tauto full() const -> bool;\n\tauto empty() const -> bool;\nprivate:\n\tauto destroy(T * first, T * last) -> void;\n\tauto swap(allocator & other) -> void;\n\tT * ptr_;\n\tsize_t size_;\n\tstd::unique_ptr<bitset> map_;\n\n};\n\ntemplate <typename T>\nallocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {};\n\n\ntemplate<typename T>\nallocator<T>::allocator(allocator const& other) :\nallocator<T>(other.size_)\n{\n\tfor (size_t i=0; i < size_; ++i)\n\t\tif (other.map_->test(i))\n\t\tconstruct(ptr_ + i, other.ptr_[i]);\n}\n\ntemplate<typename T>\nallocator<T>::~allocator()\n{ \n\tdestroy(ptr_, ptr_+size_);\n\toperator delete(ptr_); \n}\n\ntemplate<typename T>\nauto allocator<T>::resize() -> void\n{\n\tallocator<T> buff(size_ * 2 + (size_ == 0));\n\tfor (size_t i = 0; i < size_; ++i) construct(buff.ptr_ + i, ptr_[i]);\n\tthis->swap(buff);\n}\n\ntemplate<typename T>\nauto allocator<T>::construct(T * ptr, T const & value)->void \n{\n\tif (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) \n\t{\n\t\tnew(ptr)T(value);\n\t\tmap_->set(ptr - ptr_);\n\t}\n\telse throw(\"error\");\n}\n\ntemplate<typename T>\nauto allocator<T>::destroy(T * ptr) -> void \n{\n\tif(ptr>=ptr_&&ptr<=ptr_+this->count())\n\t{\n\t\tif (!map_->test(ptr-ptr_))\n\t\t{\n\t\tptr->~T();\n\t\tmap_->reset(ptr-ptr_);\n\t\t}\n\t}\n\telse throw(\"error\");\n}\n\ntemplate<typename T>\nauto allocator<T>::destroy(T * first, T * last) -> void\n{\t\n\tif(first>=ptr_&&last<=ptr_+this->count())\n\tfor (; first != last; ++first) \n\t{\n\t\tdestroy(&*first);\n\t}\n}\n\ntemplate<typename T>\nauto allocator<T>::get()-> T* \n{\n\treturn ptr_; \n}\n\ntemplate<typename T>\nauto allocator<T>::get() const -> T const * \n{ \n\treturn ptr_; \n}\n\ntemplate<typename T>\nauto allocator<T>::count() const -> size_t\n{\n\treturn map_->counter();\n}\n\ntemplate<typename T>\nauto allocator<T>::full() const -> bool\n{\n\treturn map_->counter()==size_;\n}\n\ntemplate<typename T>\nauto allocator<T>::empty() const -> bool\n{\n\treturn map_->counter()==0;\n}\n\ntemplate<typename T>\nauto allocator<T>::swap(allocator & other) -> void \n{\n\tstd::swap(ptr_, other.ptr_);\n\tstd::swap(map_, other.map_);\n\tstd::swap(size_, other.size_);\n}\n\n\/*=====================================================================================*\/\n\ntemplate <typename T>\nclass stack : private allocator<T>\n{\npublic:\n\texplicit\n\tstack(size_t size = 0);\t\t\t\t\t\t\t\t\/\/noexcept\n\tauto pop() -> void;\n\tauto top() -> T &;\n\tauto top() const -> T const &;\n\tauto push(T const &vaule) -> void;\t\t\t\t\t\t\t\/\/strong\n\tauto operator=(stack const & right)->stack &;\t\t\t\t\t\/\/strong\n\tauto empty() const -> bool; \t\t\t\t\t\t\t\/\/noexcept\n\tauto count() const -> size_t;\nprivate:\n\tallocator<T> allocator_;\n\tauto throw_is_empty() const -> void;\n};\n\ntemplate <typename T>\nsize_t stack<T>::count() const\n{\n\treturn allocator_.count();\n}\ntemplate <typename T>\nstack<T>::stack(size_t size):allocator_(size){}\n\ntemplate <typename T>\nvoid stack<T>::push(T const &item) \n{\n\tif (allocator_.full()) allocator_.resize(); \n\tallocator_.construct(allocator_.get() + this->count(), item);\n}\ntemplate<typename T>\nvoid stack<T>::pop() \n{\n\tif (this->count() > 0) \n\t\tallocator_.destroy(allocator_.get() + (this->count()-1));\n\telse \n\t\tthrow_is_empty();\n}\n\ntemplate<typename T>\nauto stack<T>::top() -> T &\n{\n\tif (allocator_.count() == 0) {\n\t\tthrow_is_empty();\n\t}\n\treturn (*(allocator_.get() + allocator_.count() - 1));\n}\n\ntemplate<typename T>\nauto stack<T>::top() const -> T const &\n{\n\tif (allocator_.count() == 0) \n\t{\n\t\tthrow_is_empty();\n\t}\n\treturn (*(allocator_.get() + allocator_.count() - 1));\n}\n\ntemplate<typename T>\nauto stack<T>::operator=(stack const & right)-> stack &\n{ \n\tif (this != &right) \n\t{\n\t\t(allocator<T>(right.allocator_)).swap(allocator_);\n\t}\n\treturn *this;\n}\n\ntemplate<typename T>\nauto stack<T>::empty() const -> bool \n{\n\treturn allocator_.empty(); \n}\n\ntemplate<typename T>\nauto stack<T>::throw_is_empty() const -> void\n{\n\t\tthrow(\"Stack is empty!\");\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef NEW_AIO_H\n#define NEW_AIO_H\n\n\/*Defines virtual AIO objects to be instantiated\nby concrete implementation in the src\/ file.\n*\/\n\n#include<string>\n#include<stdexcept>\n\n#include<boost\/shared_ptr.hpp>\n\nclass Process;\nclass Symbol;\n\n\/*\nThe \"new\" AIO is based on event objects. Event\nobjects are just passive requests; in order to\n\"arm\" an event, it should be added to the global\nevent waiting set object.\n\nEvents are:\n1. Write-to-I\/O event\n2. Read-from-I\/O event\n3. Accept-from-I\/O Socket event\n4. Sleep Event\n5. System Event (i.e. spawn child OS process)\n*\/\n\n\/*Details are handled by the AIO implementation\nThis include file deals only in abstractions;\nwe don't care how they are actually implemented.\n*\/\n\nclass Event;\nclass ProcessInvoker;\n\n\/*Errors in I\/O should throw this class*\/\n\/*Could use a Maybe T type I suppose though*\/\nclass IOError : public std::runtime_error {\n};\n\n\/*-----------------------------------------------------------------------------\nImplementation-specific\n-----------------------------------------------------------------------------*\/\n\n\/*I\/O Ports*\/\nclass IOPort {\npublic:\n\tvoid close(void);\n\n\tvirtual boost::shared_ptr<Event> read(\n\t\tboost::shared_ptr<ProcessInvoker>, size_t\n\t) =0;\n\tvirtual boost::shared_ptr<Event> write(boost::shared_ptr<ProcessInvoker>,\n\t\tstd::vector<unsigned char> const&\n\t) =0;\n\tvirtual boost::shared_ptr<Event> accept(\n\t\tboost::shared_ptr<ProcessInvoker>\n\t) =0;\n\n\tvirtual ~IOPort() { }\n};\n\n\/*Will only be called once, at init*\/\nboost::shared_ptr<IOPort> ioport_stdin(void);\nboost::shared_ptr<IOPort> ioport_stdout(void);\nboost::shared_ptr<IOPort> ioport_stderr(void);\n\nboost::shared_ptr<IOPort> infile(std::string);\nboost::shared_ptr<IOPort> outfile(std::string);\nboost::shared_ptr<IOPort> appendfile(std::string);\n\nclass Event {\npublic:\n\n\tvirtual ~Event() { }\n};\n\nboost::shared_ptr<Event> system_event(boost::shared_ptr<ProcessInvoker>,std::string);\nboost::shared_ptr<Event> sleep_event(boost::shared_ptr<ProcessInvoker>,size_t);\n\n\/*used as a Singleton, although we don't enforce it*\/\nclass EventSetImpl;\nclass EventSet {\nprivate:\n\tEventSetImpl* pimpl;\n\npublic:\n\tvoid add_event(boost::shared_ptr<Event>);\n\tvoid remove_event(boost::shared_ptr<Event>);\n\n\tEventSet(void);\n\t~EventSet();\n};\n\n\/*-----------------------------------------------------------------------------\nShared across Implementations\n-----------------------------------------------------------------------------*\/\n\n\/*implementations in src\/new_aio.cpp*\/\n\nclass ProcessInvoker {\nprivate:\n\tProcess* P;\npublic:\n\tvoid read_respond(\n\t\tboost::shared_ptr<IOPort>, std::vector<unsigned char> const&\n\t);\n\tvoid write_respond(\n\t\tboost::shared_ptr<IOPort>, std::vector<unsigned char> const&\n\t);\n\tvoid accept_respond(\n\t\tboost::shared_ptr<IOPort> socket, boost::shared_ptr<IOPort> new_socket\n\t);\n\tvoid sleep_respond(\n\t\tboost::shared_ptr<Event>, size_t\n\t);\n\tvoid system_respond(\n\t\tboost::shared_ptr<Event>, int term_code\n\t);\n};\n\n\n#endif \/\/ NEW_AIO_H\n\n<commit_msg>inc\/new_aio.hpp: Moved development of new AIO to its own branch, new_aio<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef stack_cpp\r\n#define stack_cpp\r\n#pragma once\r\n#include <iostream>\r\nusing namespace std;\r\ntemplate <typename T>\r\nclass stack\r\n{\r\npublic:\r\n\tstack();\r\n\tstack(stack const &);\r\n\t~stack();\r\n\tsize_t count() const;\r\n\tauto push(T const &) -> void;\r\n\tauto copy_(T * item, size_t size, size_t count) -> T*;\r\n\tT pop();\r\n\tauto operator=(stack const & right)->stack &;\r\nprivate:\r\n\tT * array_;\r\n\tsize_t array_size_;\r\n\tsize_t count_;\r\n};\r\n\r\n\r\ntemplate <typename T>\r\nsize_t stack<T>::count() const\r\n{\r\n\treturn count_;\r\n}\r\ntemplate <typename T>\r\nstack<T>::stack()\r\n{\r\n\tarray_size_ = 0;\r\n\tarray_ = new T[array_size_];\r\n\tcount_ = 0;\r\n}\r\n\r\ntemplate<typename T>\r\nstack<T>::stack(stack const & item):array_size_(item.array_size_), count_(item.count_),array_(copy_(item.array_, item.array_size_,item.count_))\r\n{\r\n\r\n}\r\n\r\ntemplate <typename T>\r\nstack<T>::~stack()\r\n{\r\n\tdelete[] array_;\r\n}\r\n\r\ntemplate<typename T>\r\nauto stack<T>::push(T const & item) -> void {\r\n\tif (count_ == array_size_) {\r\n\t\tsize_t size = array_size_ * 2 + (array_size_ == 0) ;\r\n\t\tdelete[] array_;\r\n\t\tarray_ = copy_(array_, size, array_size_);\r\n\t\tarray_size_ = size;\r\n\t}\r\n\t++count_;\r\n\tarray_[count_ - 1] = item;\r\n}\r\ntemplate<typename T>\r\nauto stack<T>::copy_(T * item, size_t size, size_t count) -> T* {\r\n\tT * buff = new T[size];\r\n\tcopy(item, item + count, buff);\r\n\treturn buff;\r\n}\r\n\r\ntemplate<typename T>\r\nT stack<T>::pop() {\r\n\tif (count_ == 0) {\r\n\t\tthrow std::logic_error(\"Stack is empty!\");\r\n\t}\r\n\treturn array_[--count_];\r\n}\r\ntemplate<typename T>\r\nauto stack<T>::operator=(stack const & right) -> stack & {\r\n\tif (this != &right) {\r\n\tdelete[] array_;\r\n\tcount_ = right.count_;\r\n\tarray_size_ = right.array_size_;\r\n\tcopy_(right.array_, array_size_, count_);\r\n\t}\r\n\treturn *this;\r\n}\r\n\r\n#endif\r\n<commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp\r\n#define stack_cpp\r\n#pragma once\r\n#include <iostream>\r\nusing namespace std;\r\ntemplate<typename>\r\nauto newcopy(T * item, size_t size, size_t count) -> T*\r\n{\r\n\tT * buff = new T[size];\r\n\tcopy(item, item + count, buff);\r\n\treturn buff;\t\r\n}\r\ntemplate <typename T>\r\nclass stack\r\n{\r\npublic:\r\n\tstack();\r\n\tstack(stack const &);\r\n\t~stack();\r\n\tsize_t count() const;\r\n\tauto push(T const &) -> void;\r\n\tT pop();\r\n\tauto operator=(stack const & right)->stack &;\r\nprivate:\r\n\tT * array_;\r\n\tsize_t array_size_;\r\n\tsize_t count_;\r\n};\r\ntemplate <typename T>\r\nsize_t stack<T>::count() const\r\n{\r\n\treturn count_;\r\n}\r\ntemplate <typename T>\r\nstack<T>::stack():array_size_(0), count(0), array_(new T[array_size_])\r\n{\r\n\r\n}\r\n\r\ntemplate<typename T>\r\nstack<T>::stack(stack const & item):array_size_(item.array_size_), count_(item.count_),array_(newcopy(item.array_, item.array_size_,item.count_))\r\n{\r\n\r\n}\r\n\r\ntemplate <typename T>\r\nstack<T>::~stack()\r\n{\r\n\tdelete[] array_;\r\n}\r\n\r\ntemplate<typename T>\r\nauto stack<T>::push(T const & item) -> void {\r\n\tif (count_ == array_size_) {\r\n\t\tsize_t size = array_size_ * 2 + (array_size_ == 0) ;\r\n\t\tdelete[] array_;\r\n\t\tarray_ = newcopy(array_, size, array_size_);\r\n\t\tarray_size_ = size;\r\n\t}\r\n\t++count_;\r\n\tarray_[count_ - 1] = item;\r\n}\r\n\r\ntemplate<typename T>\r\nT stack<T>::pop() {\r\n\tif (count_ == 0) {\r\n\t\tthrow std::logic_error(\"Stack is empty!\");\r\n\t}\r\n\treturn array_[--count_];\r\n}\r\ntemplate<typename T>\r\nauto stack<T>::operator=(stack const & right) -> stack & {\r\n\tif (this != &right) {\r\n\tdelete[] array_;\r\n\tcount_ = right.count_;\r\n\tarray_size_ = right.array_size_;\r\n\tnewcopy(right.array_, array_size_, count_);\r\n\t}\r\n\treturn *this;\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Creation of the Map.hpp.<commit_after>\/*******************************************************************************************\n * This file is created to implement the class Duck for our game called PapraGame.\t*\n * This file will allow us to have all the method to control the duck for the game.\t\t*\n * This file are under licence Mozilla Public License Version 2.0\t\t\t\t\t*\n * Author : Barbier Julien, julien.barbier@utbm.fr\t\t\t\t\t\t\t\t*\t\n * Date of creation : 01\/19\/2016\t\t\t\t\t\t\t\t\t\t\t*\n * *****************************************************************************************\/\n \n #ifndef MAP_HPP_INCLUDED\n #define MAP_HPP_INCLUDED\n \n #include <Coord>\n #include <SFML\/Graphics>\n #include <enum>\n \n #define NB_TEXTURE 8\n \n\n class Map {\n\t \n\t public : \n\t\t \n\t\t\/**\n\t\t * @brief Destroy the class Map\n\t\t *\/\n\t\t \n\t\t~Map();\t\t\n\t \n\t\t\/**\n\t\t * @brief Creation of Map by default.\n\t\t *\/\n\t\t\n\t\tMap () {};\n\t\t\n\t\t\/**\n\t\t * @brief Creation of map with all the parametre needed.\n\t\t * @param x The lenght of the map\n\t\t * @param y The width of the map\n\t\t * @param smap[x][y] The map himself with the lenght and the width.\n\t\t * @param texture[NB_TEXTURE] Array which will contain the texture for this game.\n\t\t * @param egg_texture Contain the texture of the egg.\n\t\t *\/\n\t\t\n\t\tMap(unsigned char x, unsigned char y, Area smap[x][y], const String& texture[NB_TEXTURE], const String& egg_texture); \n\t\t\t\n\t\t\/**\n\t\t * @brief Change the coordinates of the egg and print him.\n\t\t * @param egg_coord The coordinate of the egg to initialize coordinate_egg(Map) and \n\t\t *\/\n\t \n\t\tvoid popEgg (Coord egg_coord);\n\t\t\n\t\t\/**\t \n\t\t * @brief Print a send case in the screen.\n\t\t * @param coord The coordinate of the case we want to convert.\n\t\t *\/\n\t\t\n\t\tvoid print(Coord coord);\n\t \n\t\t\/**\n\t\t * @brief printAll Print all the map.\n\t\t *\/\n\t\t\n\t\tvoid printAll();\n\t \n\t private :\n\t\t\n\t\tunsigned char x_size;\n\t\tunsigned char y_size;\n\t\tsf::Texture sprites[NB_TEXTURE];\n\t\tCoord coordinate_egg;\n\t\tsf::Texture egg_sprite;\n\t\tArea map [] [];\n };\n \n #endif \/* MAPP_HPP_INCLUDED*\/\n \n <|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n#include <stdexcept>\n\ntemplate <typename T>\nclass stack\n{\npublic:\n\tstack() noexcept;\n\t~stack() noexcept;\n\tstack(stack<T> const&)\/*no safety*\/;\n\tstack& operator=(stack<T> const&)\/*no safety*\/;\n\tsize_t count()const noexcept;\n\tvoid push(T const&)\/*no safety*\/;\n\tvoid pop()\/*no safety*\/;\n\tT top()const \/*no safety*\/;\n\tvoid print(std::ostream&stream)const \/*strong*\/;\n\tvoid swap(stack<T>&)noexcept;\n\tbool empty()const noexcept;\nprivate:\n\tT * array_;\n\tsize_t array_size_;\n\tsize_t count_;\n};\n\ntemplate <typename T> \nstack<T>::stack() noexcept : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}\ntemplate <typename T>\nstack<T>::~stack()noexcept\n{\n\tdelete[] array_;\n}\ntemplate <typename T>\nstack<T>::stack(stack<T> const& other)\n{\n\tarray_size_ = other.array_size_;\n\tcount_ = other.count_;\t\n\tstd::copy(other.array_, other.array_ + count_, array_);\n}\ntemplate <typename T>\nstack<T>& stack<T>::operator=(stack<T> const & other)\n{\n\tif (&other != this)\n\t\tstack(other).swap(*this);\n\treturn *this;\n}\ntemplate <typename T>\nsize_t stack<T>::count()const noexcept\n{\n\treturn count_;\n}\ntemplate <typename T>\nvoid stack<T>::push(T const & value)\n{\n\tif (empty())\n\t{\n\t\tarray_size_ = 1;\n\t\tarray_ = new T[array_size_]();\n\t}\n\telse if (array_size_ == count_)\n\t{\n\t\tarray_size_ *= 2;\n\t\tT * new_array = new T[array_size_]();\n\t\tstd::copy(array_, array_ + count_, new_array);\n\t\tdelete[] array_;\n\t\tarray_ = new_array;\n\t}\n\tarray_[count_++] = value;\n}\ntemplate <typename T>\nvoid stack<T>::pop()\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\t--count_;\n}\ntemplate <typename T>\nT stack<T>::top()const \n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse return array_[count_ - 1];\n}\ntemplate <typename T>\nvoid stack<T>::print(std::ostream&stream)const \n{\n\tif(!empty())\n\t{\n\t for (unsigned int i = 0; i < count_; ++i)\n\t\t stream << array_[i] << \" \";\n\t stream << std::endl;\n\t}\n}\ntemplate <typename T>\nvoid stack<T>::swap(stack<T>& other)noexcept\n{\n\tstd::swap(array_, other.array_);\n\tstd::swap(array_size_, other.array_size_);\n\tstd::swap(count_, other.count_);\n}\ntemplate <typename T>\nbool stack<T>::empty()const noexcept\n{\n\treturn (count_ == 0);\n}\n<commit_msg>Update stack.hpp<commit_after>#include <iostream>\n#include <algorithm>\n#include <stdexcept>\n\ntemplate <typename T>\nclass stack\n{\npublic:\n\tstack() noexcept;\n\t~stack() noexcept;\n\tstack(stack<T> const&)\/*no safety*\/;\n\tstack& operator=(stack<T> const&)\/*no safety*\/;\n\tsize_t count()const noexcept;\n\tvoid push(T const&)\/*no safety*\/;\n\tvoid pop()\/*strong*\/;\n\tT top()const \/*strong*\/;\n\tvoid print(std::ostream&stream)const \/*strong*\/;\n\tvoid swap(stack<T>&)noexcept;\n\tbool empty()const noexcept;\nprivate:\n\tT * array_;\n\tsize_t array_size_;\n\tsize_t count_;\n};\n\ntemplate <typename T> \nstack<T>::stack() noexcept : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}\ntemplate <typename T>\nstack<T>::~stack()noexcept\n{\n\tdelete[] array_;\n}\ntemplate <typename T>\nstack<T>::stack(stack<T> const& other)\n{\n\tarray_size_ = other.array_size_;\n\tcount_ = other.count_;\t\n\tstd::copy(other.array_, other.array_ + count_, array_);\n}\ntemplate <typename T>\nstack<T>& stack<T>::operator=(stack<T> const & other)\n{\n\tif (&other != this)\n\t\tstack(other).swap(*this);\n\treturn *this;\n}\ntemplate <typename T>\nsize_t stack<T>::count()const noexcept\n{\n\treturn count_;\n}\ntemplate <typename T>\nvoid stack<T>::push(T const & value)\n{\n\tif (empty())\n\t{\n\t\tarray_size_ = 1;\n\t\tarray_ = new T[array_size_]();\n\t}\n\telse if (array_size_ == count_)\n\t{\n\t\tarray_size_ *= 2;\n\t\tT * new_array = new T[array_size_]();\n\t\tstd::copy(array_, array_ + count_, new_array);\n\t\tdelete[] array_;\n\t\tarray_ = new_array;\n\t}\n\tarray_[count_++] = value;\n}\ntemplate <typename T>\nvoid stack<T>::pop()\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\t--count_;\n}\ntemplate <typename T>\nT stack<T>::top()const \n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse return array_[count_ - 1];\n}\ntemplate <typename T>\nvoid stack<T>::print(std::ostream&stream)const \n{\n\tif(!empty())\n\t{\n\t for (unsigned int i = 0; i < count_; ++i)\n\t\t stream << array_[i] << \" \";\n\t stream << std::endl;\n\t}\n}\ntemplate <typename T>\nvoid stack<T>::swap(stack<T>& other)noexcept\n{\n\tstd::swap(array_, other.array_);\n\tstd::swap(array_size_, other.array_size_);\n\tstd::swap(count_, other.count_);\n}\ntemplate <typename T>\nbool stack<T>::empty()const noexcept\n{\n\treturn (count_ == 0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n#include <stdexcept>\n\ntemplate <typename T>\nclass stack\n{\npublic:\n\tstack();\n\t~stack()noexcept;\n\tstack(stack<T> const&)noexcept;\n\tstack& operator=(stack<T> const&)noexcept;\n\tsize_t count()const noexcept;\n\tsize_t array_size()const noexcept;\n\tvoid push(T const&)noexcept;\n\tvoid pop()noexcept;\n\tT top()noexcept;\n\tvoid print(std::ostream&stream)const noexcept;\n\tvoid swap(stack<T>&)noexcept;\n\tbool empty()noexcept;\nprivate:\n\tT * array_;\n\tsize_t array_size_;\n\tsize_t count_;\n};\n\ntemplate <typename T>\nstack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}\ntemplate <typename T>\nstack<T>::~stack()noexcept\n{\n\tdelete[] array_;\n}\ntemplate <typename T>\nstack<T>::stack(stack<T> const& other)noexcept\n{\n\tarray_size_ = other.array_size_;\n\tcount_ = other.count_;\t\n\tstd::copy(other.array_, other.array_ + count_, array_);\n}\ntemplate <typename T>\nstack<T>& stack<T>::operator=(stack<T> const & other)noexcept\n{\n\tif (&other != this)\n\t\tstack(other).swap(*this);\n\treturn *this;\n}\ntemplate <typename T>\nsize_t stack<T>::array_size()const noexcept\n{\n\treturn array_size_;\n}\ntemplate <typename T>\nsize_t stack<T>::count()const noexcept\n{\n\treturn count_;\n}\ntemplate <typename T>\nvoid stack<T>::push(T const & value)noexcept\n{\n\tif (empty())\n\t{\n\t\tarray_size_ = 1;\n\t\tarray_ = new T[array_size_]();\n\t}\n\telse if (array_size_ == count_)\n\t{\n\t\tarray_size_ *= 2;\n\t\tT * new_array = new T[array_size_]();\n\t\tstd::copy(array_, array_ + count_, new_array);\n\t\tdelete[] array_;\n\t\tarray_ = new_array;\n\t}\n\tarray_[count_++] = value;\n}\ntemplate <typename T>\nvoid stack<T>::pop()noexcept\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse\n\t{\n\t\tT * new_array = new T[array_size_]();\n\t\t--count_;\n\t\tstd::copy(array_, array_ + count_, new_array);\n\t\tdelete[] array_;\n\t\tarray_ = new_array;\n\t}\n}\ntemplate <typename T>\nT stack<T>::top()noexcept\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse return array_[count_ - 1];\n}\ntemplate <typename T>\nvoid stack<T>::print(std::ostream&stream)const noexcept\n{\n\tfor (unsigned int i = 0; i < count_; ++i)\n\t\tstream << array_[i] << \" \";\n\tstream << std::endl;\n}\ntemplate <typename T>\nvoid stack<T>::swap(stack<T>& other)noexcept\n{\n\tstd::swap(array_, other.array_);\n\tstd::swap(array_size_, other.array_size_);\n\tstd::swap(count_, other.count_);\n}\ntemplate <typename T>\nbool stack<T>::empty()noexcept\n{\n\treturn (count_ == 0);\n}\n<commit_msg>Update stack.hpp<commit_after>#include <iostream>\n#include <algorithm>\n#include <stdexcept>\n\ntemplate <typename T>\nclass stack\n{\npublic:\n\tstack();\n\t~stack()noexcept;\n\tstack(stack<T> const&)basic;\n\tstack& operator=(stack<T> const&)noexcept;\n\tsize_t count()const noexcept;\n\tsize_t array_size()const noexcept;\n\tvoid push(T const&)basic;\n\tvoid pop()basic;\n\tT top()const noexcept;\n\tvoid print(std::ostream&stream)const noexcept;\n\tvoid swap(stack<T>&)noexcept;\n\tbool empty()const noexcept;\nprivate:\n\tT * array_;\n\tsize_t array_size_;\n\tsize_t count_;\n};\n\ntemplate <typename T>\nstack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}\ntemplate <typename T>\nstack<T>::~stack()noexcept\n{\n\tdelete[] array_;\n}\ntemplate <typename T>\nstack<T>::stack(stack<T> const& other)basic\n{\n\tarray_size_ = other.array_size_;\n\tcount_ = other.count_;\t\n\tstd::copy(other.array_, other.array_ + count_, array_);\n}\ntemplate <typename T>\nstack<T>& stack<T>::operator=(stack<T> const & other)noexcept\n{\n\tif (&other != this)\n\t\tstack(other).swap(*this);\n\treturn *this;\n}\ntemplate <typename T>\nsize_t stack<T>::array_size()const noexcept\n{\n\treturn array_size_;\n}\ntemplate <typename T>\nsize_t stack<T>::count()const noexcept\n{\n\treturn count_;\n}\ntemplate <typename T>\nvoid stack<T>::push(T const & value)basic\n{\n\tif (empty())\n\t{\n\t\tarray_size_ = 1;\n\t\tarray_ = new T[array_size_]();\n\t}\n\telse if (array_size_ == count_)\n\t{\n\t\tarray_size_ *= 2;\n\t\tT * new_array = new T[array_size_]();\n\t\tstd::copy(array_, array_ + count_, new_array);\n\t\tdelete[] array_;\n\t\tarray_ = new_array;\n\t}\n\tarray_[count_++] = value;\n}\ntemplate <typename T>\nvoid stack<T>::pop()basic\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse\n\t{\n\t\tT * new_array = new T[array_size_]();\n\t\t--count_;\n\t\tstd::copy(array_, array_ + count_, new_array);\n\t\tdelete[] array_;\n\t\tarray_ = new_array;\n\t}\n}\ntemplate <typename T>\nT stack<T>::top()const noexcept\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse return array_[count_ - 1];\n}\ntemplate <typename T>\nvoid stack<T>::print(std::ostream&stream)const noexcept\n{\n\tfor (unsigned int i = 0; i < count_; ++i)\n\t\tstream << array_[i] << \" \";\n\tstream << std::endl;\n}\ntemplate <typename T>\nvoid stack<T>::swap(stack<T>& other)noexcept\n{\n\tstd::swap(array_, other.array_);\n\tstd::swap(array_size_, other.array_size_);\n\tstd::swap(count_, other.count_);\n}\ntemplate <typename T>\nbool stack<T>::empty()const noexcept\n{\n\treturn (count_ == 0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Simple version of std::bind that doesn't support placeholders\n\n#pragma once\n\n#include <tuple>\n#include <utility>\n\n\/\/ __bind_call generates a list of integers 0 .. N-1 ...\ntemplate <int N, typename F, typename Res, typename TArgs, int... list>\nstruct __bind_call {\n static Res call(F& f, TArgs& t) {\n return __bind_call<N - 1, F, Res, TArgs, N - 1, list...>::call(f, t);\n }\n};\n\n\/\/ ... which the __bind_call base case unpacks to get a sequence of\n\/\/ tuple indexes to pass to std::get to extract the saved arguments\n\/\/ from the tuple t.\ntemplate <typename F, typename Res, typename TArgs, int... list>\nstruct __bind_call<0, F, Res, TArgs, list...> {\n static Res call(F& f, TArgs& t) {\n return f(std::get<list>(t)...);\n }\n};\n\ntemplate <typename F, typename Res, typename... Args>\nstruct __bind_helper\n{\n typedef std::tuple<Args...> TArgs;\n\n F f_;\n TArgs args_;\n\n __bind_helper(F&& f, Args&&... args) : f_(f), args_(args...) { }\n\n Res operator()()\n {\n return __bind_call<sizeof...(Args), F, Res, TArgs>::\n call(f_, args_);\n }\n};\n\ntemplate <typename F, typename... Args>\nauto bind_simple(F&& f, Args&&... args)\n -> __bind_helper<F, decltype(f(args...)), Args...>\n{\n return __bind_helper<F, decltype(f(args...)), Args...>(\n std::forward<F>(f), std::forward<Args>(args)...);\n}\n<commit_msg>lib: Decay argument types to bind_simple<commit_after>\/\/ Simple version of std::bind that doesn't support placeholders\n\n#pragma once\n\n#include <tuple>\n#include <utility>\n\n\/\/ __bind_call generates a list of integers 0 .. N-1 ...\ntemplate <int N, typename F, typename Res, typename TArgs, int... list>\nstruct __bind_call {\n static Res call(F& f, TArgs& t) {\n return __bind_call<N - 1, F, Res, TArgs, N - 1, list...>::call(f, t);\n }\n};\n\n\/\/ ... which the __bind_call base case unpacks to get a sequence of\n\/\/ tuple indexes to pass to std::get to extract the saved arguments\n\/\/ from the tuple t.\ntemplate <typename F, typename Res, typename TArgs, int... list>\nstruct __bind_call<0, F, Res, TArgs, list...> {\n static Res call(F& f, TArgs& t) {\n return f(std::get<list>(t)...);\n }\n};\n\ntemplate <typename F, typename Res, typename... Args>\nstruct __bind_helper\n{\n typedef std::tuple<typename std::decay<Args>::type...> TArgs;\n\n F f_;\n TArgs args_;\n\n __bind_helper(F&& f, Args&&... args) : f_(f), args_(args...) { }\n\n Res operator()()\n {\n return __bind_call<sizeof...(Args), F, Res, TArgs>::\n call(f_, args_);\n }\n};\n\ntemplate <typename F, typename... Args>\nauto bind_simple(F&& f, Args&&... args)\n -> __bind_helper<F, decltype(f(args...)), Args...>\n{\n return __bind_helper<F, decltype(f(args...)), Args...>(\n std::forward<F>(f), std::forward<Args>(args)...);\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\n#include <vector>\n#include <iterator>\n\n\nnamespace helene\n{\n\n\ntemplate <class NodeType, class EdgeType>\nclass dag\n{\npublic:\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ public typedefs\n\n typedef NodeType value_type;\n typedef NodeType& reference;\n typedef const NodeType& const_reference;\n\n typedef typename std::vector<NodeType>::difference_type difference_type;\n typedef typename std::vector<NodeType>::size_type size_type;\n\n typedef typename std::vector<NodeType>::iterator iterator;\n typedef typename std::vector<NodeType>::const_iterator const_iterator;\n\n\n typedef EdgeType edge_value_type;\n typedef EdgeType& edge_reference;\n typedef const EdgeType& const_edge_reference;\n\n typedef typename std::vector<EdgeType>::size_type edge_size_type;\n typedef\n typename std::vector<EdgeType>::difference_type edge_difference_type;\n\n typedef typename std::vector<EdgeType>::iterator edge_iterator;\n typedef typename std::vector<EdgeType>::const_iterator edge_const_iterator;\n\nprivate:\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ internal classes\n\n \/\/ indices to properties of the associated edge\n struct edge\n {\n edge(size_type from, size_type to, edge_size_type edge_index)\n : from_property(from), to_property(to), edge_property(edge_index)\n {\n }\n\n size_type from_property;\n size_type to_property;\n edge_size_type edge_property;\n\n bool\n operator==(const edge& other) const\n {\n return (from_property == other.from_property) &&\n (to_property == other.to_property) &&\n (edge_property == other.edge_property);\n }\n };\n\npublic:\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Container concept member functions\n\n dag() = default;\n dag(const dag&) = default;\n\n dag& operator=(const dag&) = default;\n\n iterator\n begin()\n {\n return node_properties_.begin();\n }\n\n iterator\n end()\n {\n return node_properties_.end();\n }\n\n const_iterator\n cbegin() const\n {\n return node_properties_.cbegin();\n }\n\n const_iterator\n cend() const\n {\n return node_properties_.cend();\n }\n\n edge_iterator\n edge_begin()\n {\n return edge_properties_.begin();\n }\n\n edge_iterator\n edge_end()\n {\n return edge_properties_.end();\n }\n\n edge_const_iterator\n edge_cbegin() const\n {\n return edge_properties_.cbegin();\n }\n\n edge_const_iterator\n edge_cend() const\n {\n return edge_properties_.cend();\n }\n\n\n bool\n operator==(const dag& other) const\n {\n return (node_properties_ == other.node_properties_) &&\n (edge_properties_ == other.edge_properties_) &&\n (edges_ == other.edges_);\n }\n\n\n bool\n operator!=(const dag& other) const\n {\n return !(*this == other);\n }\n\n\n void\n swap(dag& other)\n {\n node_properties_.swap(other.node_properties_);\n edge_properties_.swap(other.edge_properties_);\n edges_.swap(other.edges_);\n }\n\npublic:\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ dag specific member functions\n\n\n \/\/ Add node\n iterator\n add_node(const NodeType& prop)\n {\n node_properties_.push_back(prop);\n return std::prev(node_properties_.end());\n }\n\n\n \/\/ Add edge between nodes.\n \/\/ If edge introduces cycle edge will not be inserted.\n \/\/ Returns iterator to edge property or edge_end() if edge was prevented\n \/\/ from being inserted.\n edge_iterator\n add_edge(const_iterator from, const_iterator to, const EdgeType& prop)\n {\n \/\/ TODO: check for cycle\n edges_.emplace_back(from - cbegin(), to - cbegin(), edges_.size());\n edge_properties_.push_back(prop);\n return std::prev(edge_properties_.end());\n }\n\nprivate:\n std::vector<NodeType> node_properties_;\n std::vector<EdgeType> edge_properties_;\n\n std::vector<edge> edges_;\n};\n}\n<commit_msg>Add empty declaration of start_node_iterator_ and typedefs in dag. \tmodified: include\/dag.hpp<commit_after>#pragma once\n\n\n#include <vector>\n#include <iterator>\n\n\nnamespace helene\n{\n\n\nclass start_node_iterator_\n{\n};\n\ntemplate <class NodeType, class EdgeType>\nclass dag\n{\npublic:\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ public typedefs\n\n typedef NodeType value_type;\n typedef NodeType& reference;\n typedef const NodeType& const_reference;\n\n typedef typename std::vector<NodeType>::difference_type difference_type;\n typedef typename std::vector<NodeType>::size_type size_type;\n\n typedef typename std::vector<NodeType>::iterator iterator;\n typedef typename std::vector<NodeType>::const_iterator const_iterator;\n\n\n typedef EdgeType edge_value_type;\n typedef EdgeType& edge_reference;\n typedef const EdgeType& const_edge_reference;\n\n typedef typename std::vector<EdgeType>::size_type edge_size_type;\n typedef\n typename std::vector<EdgeType>::difference_type edge_difference_type;\n\n typedef typename std::vector<EdgeType>::iterator edge_iterator;\n typedef typename std::vector<EdgeType>::const_iterator edge_const_iterator;\n\n\n \/\/ iterator typedefs\n typedef start_node_iterator_ start_node_iterator;\n typedef const start_node_iterator const_start_node_iterator;\n\nprivate:\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ internal classes\n\n \/\/ indices to properties of the associated edge\n struct edge\n {\n edge(size_type from, size_type to, edge_size_type edge_index)\n : from_property(from), to_property(to), edge_property(edge_index)\n {\n }\n\n size_type from_property;\n size_type to_property;\n edge_size_type edge_property;\n\n bool\n operator==(const edge& other) const\n {\n return (from_property == other.from_property) &&\n (to_property == other.to_property) &&\n (edge_property == other.edge_property);\n }\n };\n\npublic:\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Container concept member functions\n\n dag() = default;\n dag(const dag&) = default;\n\n dag& operator=(const dag&) = default;\n\n iterator\n begin()\n {\n return node_properties_.begin();\n }\n\n iterator\n end()\n {\n return node_properties_.end();\n }\n\n const_iterator\n cbegin() const\n {\n return node_properties_.cbegin();\n }\n\n const_iterator\n cend() const\n {\n return node_properties_.cend();\n }\n\n edge_iterator\n edge_begin()\n {\n return edge_properties_.begin();\n }\n\n edge_iterator\n edge_end()\n {\n return edge_properties_.end();\n }\n\n edge_const_iterator\n edge_cbegin() const\n {\n return edge_properties_.cbegin();\n }\n\n edge_const_iterator\n edge_cend() const\n {\n return edge_properties_.cend();\n }\n\n\n bool\n operator==(const dag& other) const\n {\n return (node_properties_ == other.node_properties_) &&\n (edge_properties_ == other.edge_properties_) &&\n (edges_ == other.edges_);\n }\n\n\n bool\n operator!=(const dag& other) const\n {\n return !(*this == other);\n }\n\n\n void\n swap(dag& other)\n {\n node_properties_.swap(other.node_properties_);\n edge_properties_.swap(other.edge_properties_);\n edges_.swap(other.edges_);\n }\n\npublic:\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ dag specific member functions\n\n\n \/\/ Add node\n iterator\n add_node(const NodeType& prop)\n {\n node_properties_.push_back(prop);\n return std::prev(node_properties_.end());\n }\n\n\n \/\/ Add edge between nodes.\n \/\/ If edge introduces cycle edge will not be inserted.\n \/\/ Returns iterator to edge property or edge_end() if edge was prevented\n \/\/ from being inserted.\n edge_iterator\n add_edge(const_iterator from, const_iterator to, const EdgeType& prop)\n {\n \/\/ TODO: check for cycle\n edges_.emplace_back(from - cbegin(), to - cbegin(), edges_.size());\n edge_properties_.push_back(prop);\n return std::prev(edge_properties_.end());\n }\n\nprivate:\n std::vector<NodeType> node_properties_;\n std::vector<EdgeType> edge_properties_;\n\n std::vector<edge> edges_;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 Istio Authors. All Rights Reserved.\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 \"src\/grpc_transport.h\"\n#include <mutex>\n#include <thread>\n\nnamespace istio {\nnamespace mixer_client {\nnamespace {\n\n\/\/ A gRPC stream\ntemplate <class RequestType, class ResponseType>\nclass GrpcStream final : public WriteInterface<RequestType> {\n public:\n typedef std::unique_ptr<\n ::grpc::ClientReaderWriterInterface<RequestType, ResponseType>>\n StreamPtr;\n typedef std::function<StreamPtr(::grpc::ClientContext&)> StreamNewFunc;\n\n GrpcStream(ReadInterface<ResponseType>* reader, StreamNewFunc create_func)\n : reader_(reader), write_closed_(false) {\n context_.set_fail_fast(true);\n stream_ = create_func(context_);\n }\n\n static void Start(\n std::shared_ptr<GrpcStream<RequestType, ResponseType>> grpc_stream) {\n std::thread t([grpc_stream]() { grpc_stream->ReadMainLoop(); });\n t.detach();\n }\n\n void Write(const RequestType& request) override {\n std::lock_guard<std::mutex> lock(write_mutex_);\n if (!stream_->Write(request)) {\n write_closed_ = true;\n }\n }\n\n void WritesDone() override {\n std::lock_guard<std::mutex> lock(write_mutex_);\n stream_->WritesDone();\n write_closed_ = true;\n }\n\n bool is_write_closed() const override { return write_closed_; }\n\n private:\n \/\/ The worker loop to read response messages.\n void ReadMainLoop() {\n ResponseType response;\n while (stream_->Read(&response)) {\n reader_->OnRead(response);\n }\n ::grpc::Status status = stream_->Finish();\n \/\/ Convert grpc status to protobuf status.\n ::google::protobuf::util::Status pb_status(\n ::google::protobuf::util::error::Code(status.error_code()),\n ::google::protobuf::StringPiece(status.error_message()));\n reader_->OnClose(pb_status);\n }\n\n \/\/ The client context.\n ::grpc::ClientContext context_;\n \/\/ Mutex to make sure not calling stream_->Write() parallelly.\n std::mutex write_mutex_;\n \/\/ The reader writer stream.\n StreamPtr stream_;\n \/\/ The reader interface from caller.\n ReadInterface<ResponseType>* reader_;\n \/\/ Indicates if write is closed.\n bool write_closed_;\n};\n\ntypedef GrpcStream<::istio::mixer::v1::CheckRequest,\n ::istio::mixer::v1::CheckResponse>\n CheckGrpcStream;\ntypedef GrpcStream<::istio::mixer::v1::ReportRequest,\n ::istio::mixer::v1::ReportResponse>\n ReportGrpcStream;\ntypedef GrpcStream<::istio::mixer::v1::QuotaRequest,\n ::istio::mixer::v1::QuotaResponse>\n QuotaGrpcStream;\n\n} \/\/ namespace\n\nGrpcTransport::GrpcTransport(const std::string& mixer_server) {\n channel_ = CreateChannel(mixer_server, ::grpc::InsecureChannelCredentials());\n stub_ = ::istio::mixer::v1::Mixer::NewStub(channel_);\n}\n\nCheckWriterPtr GrpcTransport::NewStream(CheckReaderRawPtr reader) {\n auto writer = std::make_shared<CheckGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> CheckGrpcStream::StreamPtr {\n return stub_->Check(&context);\n });\n CheckGrpcStream::Start(writer);\n return writer;\n}\n\nReportWriterPtr GrpcTransport::NewStream(ReportReaderRawPtr reader) {\n auto writer = std::make_shared<ReportGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> ReportGrpcStream::StreamPtr {\n return stub_->Report(&context);\n });\n ReportGrpcStream::Start(writer);\n return writer;\n}\n\nQuotaWriterPtr GrpcTransport::NewStream(QuotaReaderRawPtr reader) {\n auto writer = std::make_shared<QuotaGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> QuotaGrpcStream::StreamPtr {\n return stub_->Quota(&context);\n });\n QuotaGrpcStream::Start(writer);\n return writer;\n}\n\n} \/\/ namespace mixer_client\n} \/\/ namespace istio\n<commit_msg>Log message when Stream close. (#66)<commit_after>\/* Copyright 2017 Istio Authors. All Rights Reserved.\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 \"src\/grpc_transport.h\"\n#include <mutex>\n#include <thread>\n\nnamespace istio {\nnamespace mixer_client {\nnamespace {\n\n\/\/ A gRPC stream\ntemplate <class RequestType, class ResponseType>\nclass GrpcStream final : public WriteInterface<RequestType> {\n public:\n typedef std::unique_ptr<\n ::grpc::ClientReaderWriterInterface<RequestType, ResponseType>>\n StreamPtr;\n typedef std::function<StreamPtr(::grpc::ClientContext&)> StreamNewFunc;\n\n GrpcStream(ReadInterface<ResponseType>* reader, StreamNewFunc create_func)\n : reader_(reader), write_closed_(false) {\n context_.set_fail_fast(true);\n stream_ = create_func(context_);\n }\n\n static void Start(\n std::shared_ptr<GrpcStream<RequestType, ResponseType>> grpc_stream) {\n std::thread t([grpc_stream]() { grpc_stream->ReadMainLoop(); });\n t.detach();\n }\n\n void Write(const RequestType& request) override {\n std::lock_guard<std::mutex> lock(write_mutex_);\n if (!stream_->Write(request)) {\n GOOGLE_LOG(INFO) << \"Stream Write failed: half close\";\n write_closed_ = true;\n }\n }\n\n void WritesDone() override {\n std::lock_guard<std::mutex> lock(write_mutex_);\n stream_->WritesDone();\n write_closed_ = true;\n }\n\n bool is_write_closed() const override { return write_closed_; }\n\n private:\n \/\/ The worker loop to read response messages.\n void ReadMainLoop() {\n ResponseType response;\n while (stream_->Read(&response)) {\n reader_->OnRead(response);\n }\n ::grpc::Status status = stream_->Finish();\n GOOGLE_LOG(INFO) << \"Stream Finished with status: \"\n << status.error_message();\n \/\/ Convert grpc status to protobuf status.\n ::google::protobuf::util::Status pb_status(\n ::google::protobuf::util::error::Code(status.error_code()),\n ::google::protobuf::StringPiece(status.error_message()));\n reader_->OnClose(pb_status);\n }\n\n \/\/ The client context.\n ::grpc::ClientContext context_;\n \/\/ Mutex to make sure not calling stream_->Write() parallelly.\n std::mutex write_mutex_;\n \/\/ The reader writer stream.\n StreamPtr stream_;\n \/\/ The reader interface from caller.\n ReadInterface<ResponseType>* reader_;\n \/\/ Indicates if write is closed.\n bool write_closed_;\n};\n\ntypedef GrpcStream<::istio::mixer::v1::CheckRequest,\n ::istio::mixer::v1::CheckResponse>\n CheckGrpcStream;\ntypedef GrpcStream<::istio::mixer::v1::ReportRequest,\n ::istio::mixer::v1::ReportResponse>\n ReportGrpcStream;\ntypedef GrpcStream<::istio::mixer::v1::QuotaRequest,\n ::istio::mixer::v1::QuotaResponse>\n QuotaGrpcStream;\n\n} \/\/ namespace\n\nGrpcTransport::GrpcTransport(const std::string& mixer_server) {\n channel_ = CreateChannel(mixer_server, ::grpc::InsecureChannelCredentials());\n stub_ = ::istio::mixer::v1::Mixer::NewStub(channel_);\n}\n\nCheckWriterPtr GrpcTransport::NewStream(CheckReaderRawPtr reader) {\n auto writer = std::make_shared<CheckGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> CheckGrpcStream::StreamPtr {\n return stub_->Check(&context);\n });\n CheckGrpcStream::Start(writer);\n return writer;\n}\n\nReportWriterPtr GrpcTransport::NewStream(ReportReaderRawPtr reader) {\n auto writer = std::make_shared<ReportGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> ReportGrpcStream::StreamPtr {\n return stub_->Report(&context);\n });\n ReportGrpcStream::Start(writer);\n return writer;\n}\n\nQuotaWriterPtr GrpcTransport::NewStream(QuotaReaderRawPtr reader) {\n auto writer = std::make_shared<QuotaGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> QuotaGrpcStream::StreamPtr {\n return stub_->Quota(&context);\n });\n QuotaGrpcStream::Start(writer);\n return writer;\n}\n\n} \/\/ namespace mixer_client\n} \/\/ namespace istio\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_READ_INPUT_FILE\n#define MJOLNIR_READ_INPUT_FILE\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/BoundaryCondition.hpp>\n#include <mjolnir\/core\/constants.hpp>\n#include <mjolnir\/core\/SimulatorBase.hpp>\n#include <mjolnir\/core\/SimulatorTraits.hpp>\n#include <mjolnir\/util\/get_toml_value.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/input\/read_units.hpp>\n#include <memory>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT>\nstd::unique_ptr<SimulatorBase>\nread_boundary(const toml::Table& data)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_boundary(const toml::Table& data), 0);\n\n const auto& general = get_toml_value<toml::Table>(data, \"general\", \"<root>\");\n const auto boundary =\n get_toml_value<std::string>(general, \"boundary\", \"[general]\");\n\n if(boundary == \"Unlimited\")\n {\n MJOLNIR_LOG_INFO(\"boundary is UnlimitedBoundary\");\n return read_units<SimulatorTraits<realT, UnlimitedBoundary>>(data);\n }\n else if(boundary == \"PeriodicCuboid\")\n {\n MJOLNIR_LOG_INFO(\"boundary is CuboidalPeriodicBoudanry\");\n return read_units<SimulatorTraits<realT, CuboidalPeriodicBoundary>>(data);\n }\n else\n {\n throw std::runtime_error(\n \"invalid boundary setting (Unlimited|PeriodicCuboid): \" + boundary);\n }\n}\n\ninline std::unique_ptr<SimulatorBase>\nread_precision(const toml::Table& data)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_precision(const toml::Table& data), 0);\n\n const auto& general = get_toml_value<toml::Table>(data, \"general\", \"<root>\");\n const auto prec =\n get_toml_value<std::string>(general, \"precision\", \"[general]\");\n\n if(prec == \"double\")\n {\n MJOLNIR_LOG_INFO(\"precision is double\");\n return read_boundary<double>(data);\n }\n else if(prec == \"float\")\n {\n MJOLNIR_LOG_INFO(\"precision is float\");\n return read_boundary<float>(data);\n }\n else\n {\n throw std::runtime_error(\n \"invalid precision setting (double|float): \" + prec);\n }\n}\n\ninline std::unique_ptr<SimulatorBase>\nread_input_file(const std::string& filename)\n{\n const auto data = toml::parse(filename);\n\n \/\/ setting logger ...\n const auto& general = get_toml_value<toml::Table>(data, \"general\", \"<root>\");\n std::string path = get_toml_value<std::string>(general, \"output_path\", \"[general]\");\n if(path.back() != '\/') {path += '\/';\/*XXX assuming posix *\/}\n\n const std::string logger_name = path + get_toml_value<std::string>(\n general, \"output_prefix\", \"[general]\") + \".log\";\n MJOLNIR_SET_DEFAULT_LOGGER(logger_name);\n\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_input_file(const toml::Table& data), 0);\n\n return read_precision(data); \/\/ read all the settings recursively...\n}\n\n}\/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_INPUT_FILE\n<commit_msg>update top level read_input_file<commit_after>#ifndef MJOLNIR_READ_INPUT_FILE\n#define MJOLNIR_READ_INPUT_FILE\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/BoundaryCondition.hpp>\n#include <mjolnir\/core\/constants.hpp>\n#include <mjolnir\/core\/SimulatorBase.hpp>\n#include <mjolnir\/core\/SimulatorTraits.hpp>\n#include <mjolnir\/util\/get_toml_value.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/input\/read_units.hpp>\n#include <memory>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT>\nstd::unique_ptr<SimulatorBase>\nread_boundary(const toml::Table& data)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_boundary(const toml::Table& data), 0);\n\n \/\/ [simulator] can be provided in a different file. in that case, the table\n \/\/ has `file_name` field. In that case, input_path is also needed to\n \/\/ determine the location of the file.\n\n std::string boundary;\n\n const auto& simulator =\n get_toml_value<toml::Table>(data, \"simulator\", \"<root>\");\n\n if(simulator.count(\"file_name\") == 1)\n {\n const auto filename = toml::get<std::string>(simulator.at(\"file_name\"));\n std::string input_path; \/\/default: empty\n\n const auto& files = get_toml_value<toml::Table>(data, \"files\", \"<root>\");\n if(files.count(\"input_path\") == 1)\n {\n input_path = toml::get<std::string>(files.at(\"input_path\"));\n }\n\n const auto& sim = toml::parse(input_path + filename);\n boundary = get_toml_value<std::string>(\n sim, \"boundary_type\", \"[simulator]\");\n }\n else\n {\n boundary = get_toml_value<std::string>(\n simulator, \"boundary_type\", \"[simulator]\");\n }\n\n if(boundary == \"Unlimited\")\n {\n MJOLNIR_LOG_INFO(\"boundary is UnlimitedBoundary\");\n return read_units<SimulatorTraits<realT, UnlimitedBoundary>>(data);\n }\n else if(boundary == \"PeriodicCuboid\")\n {\n MJOLNIR_LOG_INFO(\"boundary is CuboidalPeriodicBoudanry\");\n return read_units<SimulatorTraits<realT, CuboidalPeriodicBoundary>>(data);\n }\n else\n {\n throw_exception<std::runtime_error>(\"mjolnir::read_boundary: \"\n \"invalid boundary: neither 'Unlimited' or 'PeriodicCuboid' -> \",\n boundary);\n }\n}\n\ninline std::unique_ptr<SimulatorBase>\nread_precision(const toml::Table& data)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_precision(const toml::Table& data), 0);\n\n \/\/ [simulator] can be provided in a different file. in that case, the table\n \/\/ has `file_name` field. In that case, input_path is also needed to\n \/\/ determine the location of the file.\n\n std::string prec;\n\n const auto& simulator =\n get_toml_value<toml::Table>(data, \"simulator\", \"<root>\");\n\n if(simulator.count(\"file_name\") == 1)\n {\n const auto filename = toml::get<std::string>(simulator.at(\"file_name\"));\n std::string input_path; \/\/default: empty\n\n const auto& files = get_toml_value<toml::Table>(data, \"files\", \"<root>\");\n if(files.count(\"input_path\") == 1)\n {\n input_path = toml::get<std::string>(files.at(\"input_path\"));\n }\n\n const auto& sim = toml::parse(input_path + filename);\n prec = get_toml_value<std::string>(sim, \"precision\", \"[simulator]\");\n }\n else\n {\n prec = get_toml_value<std::string>(simulator, \"precision\", \"[simulator]\");\n }\n\n if(prec == \"double\")\n {\n MJOLNIR_LOG_INFO(\"precision is double\");\n return read_boundary<double>(data);\n }\n else if(prec == \"float\")\n {\n MJOLNIR_LOG_INFO(\"precision is float\");\n return read_boundary<float>(data);\n }\n else\n {\n throw_exception<std::runtime_error>(\"mjolnir::read_precision: \"\n \"invalid precision: neither 'double' or 'float' -> \", prec);\n }\n}\n\ninline std::unique_ptr<SimulatorBase>\nread_input_file(const std::string& filename)\n{\n const auto data = toml::parse(filename);\n\n \/\/ initializing logger by using output_path and output_prefix ...\n const auto& files = get_toml_value<toml::Table>(data, \"files\", \"<root>\");\n const auto path = get_toml_value<std::string>(files, \"output_path\", \"[files]\");\n\n \/\/ XXX: Here, this code assumes POSIX. it does not support windows.\n \/\/ TODO: Consider using Boost.filesystem to manage path and files\n \/\/ in more elegant and powerful way? After switching C++17,\n \/\/ we can re-write that into std::filesystem.\n\n const std::string logger_name = path + get_toml_value<std::string>(\n files, \"output_prefix\", \"[files]\") + \".log\";\n MJOLNIR_SET_DEFAULT_LOGGER(logger_name);\n\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_input_file(const toml::Table& data), 0);\n\n return read_precision(data); \/\/ read all the settings recursively...\n}\n\n}\/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_INPUT_FILE\n<|endoftext|>"} {"text":"<commit_before>#include \"Globals.h\"\n#include \"Application.h\"\n#include \"ModuleInput.h\"\n#include \"ImGui\/imgui_impl_sdl_gl3.h\"\n\n#define MAX_KEYS 300\n\nModuleInput::ModuleInput(Application* app, bool start_enabled) : Module(app, start_enabled)\n{\n\tkeyboard = new KEY_STATE[MAX_KEYS];\n\tmemset(keyboard, KEY_IDLE, sizeof(KEY_STATE) * MAX_KEYS);\n\tmemset(mouseButtons, KEY_IDLE, sizeof(KEY_STATE) * MAX_MOUSE_BUTTONS);\n}\n\n\/\/ Destructor\nModuleInput::~ModuleInput()\n{\n\tdelete[] keyboard;\n}\n\n\/\/ Called before render is available\nbool ModuleInput::Init()\n{\n\tMYLOG(\"Init SDL input event system\");\n\tbool ret = true;\n\tSDL_Init(0);\n\n\tif(SDL_InitSubSystem(SDL_INIT_EVENTS) < 0)\n\t{\n\t\tMYLOG(\"SDL_EVENTS could not initialize! SDL_Error: %s\\n\", SDL_GetError());\n\t\tret = false;\n\t}\n\n\treturn ret;\n}\n\n\/\/ Called every draw update\nupdate_status ModuleInput::PreUpdate(float dt)\n{\n\tSDL_PumpEvents();\n\n\tconst Uint8* keys = SDL_GetKeyboardState(NULL);\n\t\n\tfor(int i = 0; i < MAX_KEYS; ++i)\n\t{\n\t\tif(keys[i] == 1)\n\t\t{\n\t\t\tif(keyboard[i] == KEY_IDLE)\n\t\t\t\tkeyboard[i] = KEY_DOWN;\n\t\t\telse\n\t\t\t\tkeyboard[i] = KEY_REPEAT;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(keyboard[i] == KEY_REPEAT || keyboard[i] == KEY_DOWN)\n\t\t\t\tkeyboard[i] = KEY_UP;\n\t\t\telse\n\t\t\t\tkeyboard[i] = KEY_IDLE;\n\t\t}\n\t}\n\n\tUint32 buttons = SDL_GetMouseState(&mouseX, &mouseY);\n\n\tmouseX \/= SCREEN_SIZE;\n\tmouseY \/= SCREEN_SIZE;\n\tmouseZ = 0;\n\n\tfor(int i = 0; i < 5; ++i)\n\t{\n\t\tif(buttons & SDL_BUTTON(i))\n\t\t{\n\t\t\tif(mouseButtons[i] == KEY_IDLE)\n\t\t\t\tmouseButtons[i] = KEY_DOWN;\n\t\t\telse\n\t\t\t\tmouseButtons[i] = KEY_REPEAT;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(mouseButtons[i] == KEY_REPEAT || mouseButtons[i] == KEY_DOWN)\n\t\t\t\tmouseButtons[i] = KEY_UP;\n\t\t\telse\n\t\t\t\tmouseButtons[i] = KEY_IDLE;\n\t\t}\n\t}\n\n\tmouseXMotion = mouseYMotion = 0;\n\n\tbool quit = false;\n\tSDL_Event e;\n\twhile(SDL_PollEvent(&e))\n\t{\n\t\tImGui_ImplSdlGL3_ProcessEvent(&e);\n\n\t\tswitch(e.type)\n\t\t{\n\t\t\tcase SDL_MOUSEWHEEL:\n\t\t\tmouseZ = e.wheel.y;\n\t\t\tbreak;\n\n\t\t\tcase SDL_MOUSEMOTION:\n\t\t\t{\n\t\t\t\tmouseX = e.motion.x \/ SCREEN_SIZE;\n\t\t\t\tmouseY = e.motion.y \/ SCREEN_SIZE;\n\n\t\t\t\tmouseXMotion = e.motion.xrel \/ SCREEN_SIZE;\n\t\t\t\tmouseYMotion = e.motion.yrel \/ SCREEN_SIZE;\n\t\t\tbreak;\n\t\t\t}\n\t\t\n\t\t\tcase SDL_DROPFILE:\n\t\t\t{\n\t\t\t\tfile_path = e.drop.file; \/\/BE ES LA RUTA\n\t\t\t\thas_dropped = true;\n\t\t\t\tSDL_free(e.drop.file);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase SDL_QUIT:\n\t\t\tquit = true;\n\t\t\tbreak;\n\n\t\t\tcase SDL_WINDOWEVENT:\n\t\t\t{\n\t\t\t\tif (e.window.event == SDL_WINDOWEVENT_RESIZED)\n\t\t\t\t{\n\t\t\t\t\tApp->window->UpdateWindowSize();\n\t\t\t\t\tApp->renderer3D->OnResize(e.window.data1, e.window.data2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif(quit == true || keyboard[SDL_SCANCODE_ESCAPE] == KEY_UP)\n\t\treturn UPDATE_STOP;\n\n\treturn UPDATE_CONTINUE;\n}\n\nvoid ModuleInput::AddImGui()\n{\n\n}\n\n\/\/ Called before quitting\nbool ModuleInput::CleanUp()\n{\n\tMYLOG(\"Quitting SDL input event subsystem\");\n\tSDL_QuitSubSystem(SDL_INIT_EVENTS);\n\treturn true;\n}\n\nconst char * ModuleInput::GetFileDropped()\n{\n\tif (has_dropped)\n\t{\n\t\treturn file_path;\n\t}\n\telse return nullptr;\n\treturn nullptr;\n}\n<commit_msg>ModuleInput finished<commit_after>#include \"Globals.h\"\n#include \"Application.h\"\n#include \"ModuleInput.h\"\n#include \"ImGui\/imgui_impl_sdl_gl3.h\"\n\n#define MAX_KEYS 300\n\nModuleInput::ModuleInput(Application* app, bool start_enabled) : Module(app, start_enabled)\n{\n\tkeyboard = new KEY_STATE[MAX_KEYS];\n\tmemset(keyboard, KEY_IDLE, sizeof(KEY_STATE) * MAX_KEYS);\n\tmemset(mouseButtons, KEY_IDLE, sizeof(KEY_STATE) * MAX_MOUSE_BUTTONS);\n}\n\n\/\/ Destructor\nModuleInput::~ModuleInput()\n{\n\tdelete[] keyboard;\n}\n\n\/\/ Called before render is available\nbool ModuleInput::Init()\n{\n\tMYLOG(\"Init SDL input event system\");\n\tbool ret = true;\n\tSDL_Init(0);\n\n\tif(SDL_InitSubSystem(SDL_INIT_EVENTS) < 0)\n\t{\n\t\tMYLOG(\"SDL_EVENTS could not initialize! SDL_Error: %s\\n\", SDL_GetError());\n\t\tret = false;\n\t}\n\n\treturn ret;\n}\n\n\/\/ Called every draw update\nupdate_status ModuleInput::PreUpdate(float dt)\n{\n\tSDL_PumpEvents();\n\n\tconst Uint8* keys = SDL_GetKeyboardState(NULL);\n\t\n\tfor(int i = 0; i < MAX_KEYS; ++i)\n\t{\n\t\tif(keys[i] == 1)\n\t\t{\n\t\t\tif(keyboard[i] == KEY_IDLE)\n\t\t\t\tkeyboard[i] = KEY_DOWN;\n\t\t\telse\n\t\t\t\tkeyboard[i] = KEY_REPEAT;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(keyboard[i] == KEY_REPEAT || keyboard[i] == KEY_DOWN)\n\t\t\t\tkeyboard[i] = KEY_UP;\n\t\t\telse\n\t\t\t\tkeyboard[i] = KEY_IDLE;\n\t\t}\n\t}\n\n\tUint32 buttons = SDL_GetMouseState(&mouseX, &mouseY);\n\n\tmouseX \/= SCREEN_SIZE;\n\tmouseY \/= SCREEN_SIZE;\n\tmouseZ = 0;\n\n\tfor(int i = 0; i < 5; ++i)\n\t{\n\t\tif(buttons & SDL_BUTTON(i))\n\t\t{\n\t\t\tif(mouseButtons[i] == KEY_IDLE)\n\t\t\t\tmouseButtons[i] = KEY_DOWN;\n\t\t\telse\n\t\t\t\tmouseButtons[i] = KEY_REPEAT;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(mouseButtons[i] == KEY_REPEAT || mouseButtons[i] == KEY_DOWN)\n\t\t\t\tmouseButtons[i] = KEY_UP;\n\t\t\telse\n\t\t\t\tmouseButtons[i] = KEY_IDLE;\n\t\t}\n\t}\n\n\tmouseXMotion = mouseYMotion = 0;\n\n\tbool quit = false;\n\tSDL_Event e;\n\twhile(SDL_PollEvent(&e))\n\t{\n\t\tImGui_ImplSdlGL3_ProcessEvent(&e);\n\n\t\tswitch(e.type)\n\t\t{\n\t\t\tcase SDL_MOUSEWHEEL:\n\t\t\tmouseZ = e.wheel.y;\n\t\t\tbreak;\n\n\t\t\tcase SDL_MOUSEMOTION:\n\t\t\t{\n\t\t\t\tmouseX = e.motion.x \/ SCREEN_SIZE;\n\t\t\t\tmouseY = e.motion.y \/ SCREEN_SIZE;\n\n\t\t\t\tmouseXMotion = e.motion.xrel \/ SCREEN_SIZE;\n\t\t\t\tmouseYMotion = e.motion.yrel \/ SCREEN_SIZE;\n\t\t\tbreak;\n\t\t\t}\n\t\t\n\t\t\tcase SDL_DROPFILE:\n\t\t\t{\n\t\t\t\tfile_path = e.drop.file; \/\/BE ES LA RUTA\n\t\t\t\thas_dropped = true;\n\t\t\t\tSDL_free(e.drop.file);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase SDL_QUIT:\n\t\t\tquit = true;\n\t\t\tbreak;\n\n\t\t\tcase SDL_WINDOWEVENT:\n\t\t\t{\n\t\t\t\tif (e.window.event == SDL_WINDOWEVENT_RESIZED)\n\t\t\t\t{\n\t\t\t\t\tApp->window->UpdateWindowSize();\n\t\t\t\t\tApp->renderer3D->OnResize(e.window.data1, e.window.data2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif(quit == true || keyboard[SDL_SCANCODE_ESCAPE] == KEY_UP)\n\t\treturn UPDATE_STOP;\n\n\treturn UPDATE_CONTINUE;\n}\n\nvoid ModuleInput::AddImGui()\n{\n\tstatic char* name = \"\";\n\tif (GetFileDropped() != nullptr)\n\t{\n\t\tname = (char*)GetFileDropped();\n\t}\n\n\tif (ImGui::CollapsingHeader(\"Input\"))\n\t{\n\t\tif (ImGui::TreeNodeEx(\"Mouse\", ImGuiTreeNodeFlags_DefaultOpen))\n\t\t{\n\t\t\tImGui::BeginGroup();\n\t\t\t{\n\t\t\t\tImGui::Text(\"Mouse position:\");\n\t\t\t\tImGui::Text(\"Mouse motion:\");\n\t\t\t\tImGui::Text(\"Mouse wheel:\");\n\t\t\t\tImGui::EndGroup();\n\t\t\t}\n\t\t\tImGui::SameLine();\n\t\t\tImGui::BeginGroup();\n\t\t\t{\n\t\t\t\tImGui::Text(\"%i, %i\", GetMouseX(), GetMouseY());\n\t\t\t\tImGui::Text(\"%i, %i\", GetMouseXMotion(), GetMouseYMotion());\n\t\t\t\tImGui::Text(\"%i\", GetMouseZ());\n\t\t\t\tImGui::EndGroup();\n\t\t\t}\n\t\t\tImGui::TreePop();\n\t\t}\n\t\tif (ImGui::TreeNodeEx(\"Files\", ImGuiTreeNodeFlags_DefaultOpen))\n\t\t{\n\t\t\tImGui::TextWrapped(\"Latest dropped file:\\n%s\", name);\n\t\t\tImGui::TreePop();\n\t\t}\n\t}\n}\n\n\/\/ Called before quitting\nbool ModuleInput::CleanUp()\n{\n\tMYLOG(\"Quitting SDL input event subsystem\");\n\tSDL_QuitSubSystem(SDL_INIT_EVENTS);\n\treturn true;\n}\n\nconst char * ModuleInput::GetFileDropped()\n{\n\tif (has_dropped)\n\t{\n\t\treturn file_path;\n\t}\n\telse return nullptr;\n\treturn nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_INPUT_READ_INTEGRATOR_HPP\n#define MJOLNIR_INPUT_READ_INTEGRATOR_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/VelocityVerletIntegrator.hpp>\n#include <mjolnir\/core\/UnderdampedLangevinIntegrator.hpp>\n#include <mjolnir\/core\/BAOABLangevinIntegrator.hpp>\n#include <mjolnir\/core\/SystemMotionRemover.hpp>\n#include <mjolnir\/input\/utility.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/util\/throw_exception.hpp>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nSystemMotionRemover<traitsT>\nread_system_motion_remover(const toml::value& simulator)\n{\n const auto& integrator = toml::find(simulator, \"integrator\");\n\n if(!integrator.contains(\"remove\"))\n {\n return SystemMotionRemover<traitsT>(false, false, false);\n }\n const auto& remove = toml::find(integrator.at(\"remove\"));\n\n const bool translation = toml::find_or(remove, \"translation\");\n const bool rotation = toml::find_or(remove, \"rotation\");\n const bool rescale = toml::find_or(remove, \"rescale\");\n\n return SystemMotionRemover<traitsT>(translation, rotation, rescale);\n}\n\n\ntemplate<typename traitsT>\nVelocityVerletIntegrator<traitsT>\nread_velocity_verlet_integrator(const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n using real_type = typename traitsT::real_type;\n\n const real_type delta_t = toml::find<real_type>(simulator, \"delta_t\");\n MJOLNIR_LOG_INFO(\"delta_t = \", delta_t);\n\n return VelocityVerletIntegrator<traitsT>(delta_t,\n read_system_motion_remover<traitsT>(simulator));\n}\n\ntemplate<typename traitsT>\nUnderdampedLangevinIntegrator<traitsT>\nread_underdamped_langevin_integrator(const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n using real_type = typename traitsT::real_type;\n\n const real_type delta_t = toml::find<real_type>(simulator, \"delta_t\");\n MJOLNIR_LOG_INFO(\"delta_t = \", delta_t);\n\n const auto& integrator = toml::find(simulator, \"integrator\");\n\n check_keys_available(integrator, {\"type\"_s, \"seed\"_s, \"parameters\"_s});\n\n const auto parameters = toml::find<toml::array >(integrator, \"parameters\");\n\n std::vector<real_type> gamma(parameters.size());\n for(const auto& params : parameters)\n {\n const auto idx = toml::find<std::size_t>(params, \"index\");\n const auto gm = toml::expect<real_type>(params, u8\"γ\").or_other(\n toml::expect<real_type>(params, \"gamma\")).unwrap();\n if(gamma.size() <= idx){gamma.resize(idx+1);}\n gamma.at(idx) = gm;\n\n MJOLNIR_LOG_INFO(\"idx = \", idx, \", gamma = \", gm);\n }\n return UnderdampedLangevinIntegrator<traitsT>(delta_t, std::move(gamma),\n read_system_motion_remover<traitsT>(simulator));\n}\n\ntemplate<typename traitsT>\nBAOABLangevinIntegrator<traitsT>\nread_BAOAB_langevin_integrator(const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n using real_type = typename traitsT::real_type;\n\n const real_type delta_t = toml::find<real_type>(simulator, \"delta_t\");\n MJOLNIR_LOG_INFO(\"delta_t = \", delta_t);\n\n const auto& integrator = toml::find(simulator, \"integrator\");\n\n check_keys_available(integrator, {\"type\"_s, \"seed\"_s, \"parameters\"_s});\n\n const auto parameters = toml::find<toml::array >(integrator, \"parameters\");\n\n std::vector<real_type> gamma(parameters.size());\n for(const auto& params : parameters)\n {\n const auto idx = toml::find<std::size_t>(params, \"index\");\n const auto gm = toml::expect<real_type>(params, u8\"γ\").or_other(\n toml::expect<real_type>(params, \"gamma\")).unwrap();\n if(gamma.size() <= idx) {gamma.resize(idx+1);}\n gamma.at(idx) = gm;\n\n MJOLNIR_LOG_INFO(\"idx = \", idx, \", gamma = \", gm);\n }\n return BAOABLangevinIntegrator<traitsT>(delta_t, std::move(gamma),\n read_system_motion_remover<traitsT>(simulator));\n}\n\n\/\/ A mapping object from type information (template parameter) to the actual\n\/\/ read_xxx_integrator function\ntemplate<typename T>\nstruct read_integrator_impl;\n\ntemplate<typename traitsT>\nstruct read_integrator_impl<VelocityVerletIntegrator<traitsT>>\n{\n static VelocityVerletIntegrator<traitsT> invoke(const toml::value& sim)\n {\n return read_velocity_verlet_integrator<traitsT>(sim);\n }\n};\n\ntemplate<typename traitsT>\nstruct read_integrator_impl<UnderdampedLangevinIntegrator<traitsT>>\n{\n static UnderdampedLangevinIntegrator<traitsT> invoke(const toml::value& sim)\n {\n return read_underdamped_langevin_integrator<traitsT>(sim);\n }\n};\n\ntemplate<typename traitsT>\nstruct read_integrator_impl<BAOABLangevinIntegrator<traitsT>>\n{\n static BAOABLangevinIntegrator<traitsT> invoke(const toml::value& sim)\n {\n return read_BAOAB_langevin_integrator<traitsT>(sim);\n }\n};\n\ntemplate<typename integratorT>\nintegratorT read_integrator(const toml::value& sim)\n{\n if(sim.as_table().count(\"integrator\") == 0)\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_integrator: No integrator defined: \", sim, \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"VelocityVerlet\\\" : simple and standard Velocity Verlet integrator.\",\n \"- \\\"UnderdampedLangevin\\\": simple Underdamped Langevin Integrator\"\n \" based on the Velocity Verlet\",\n \"- \\\"BAOABLangevin\\\" : well-known BAOAB Langevin Integrator\"\n }));\n }\n return read_integrator_impl<integratorT>::invoke(sim);\n}\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template VelocityVerletIntegrator<SimulatorTraits<double, UnlimitedBoundary> > read_velocity_verlet_integrator(const toml::value& simulator);\nextern template VelocityVerletIntegrator<SimulatorTraits<float, UnlimitedBoundary> > read_velocity_verlet_integrator(const toml::value& simulator);\nextern template VelocityVerletIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_velocity_verlet_integrator(const toml::value& simulator);\nextern template VelocityVerletIntegrator<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_velocity_verlet_integrator(const toml::value& simulator);\n\nextern template UnderdampedLangevinIntegrator<SimulatorTraits<double, UnlimitedBoundary> > read_underdamped_langevin_integrator(const toml::value& simulator);\nextern template UnderdampedLangevinIntegrator<SimulatorTraits<float, UnlimitedBoundary> > read_underdamped_langevin_integrator(const toml::value& simulator);\nextern template UnderdampedLangevinIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_underdamped_langevin_integrator(const toml::value& simulator);\nextern template UnderdampedLangevinIntegrator<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_underdamped_langevin_integrator(const toml::value& simulator);\n\nextern template BAOABLangevinIntegrator<SimulatorTraits<double, UnlimitedBoundary> > read_BAOAB_langevin_integrator(const toml::value& simulator);\nextern template BAOABLangevinIntegrator<SimulatorTraits<float, UnlimitedBoundary> > read_BAOAB_langevin_integrator(const toml::value& simulator);\nextern template BAOABLangevinIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_BAOAB_langevin_integrator(const toml::value& simulator);\nextern template BAOABLangevinIntegrator<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_BAOAB_langevin_integrator(const toml::value& simulator);\n#endif\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_INTEGRATOR\n<commit_msg>fix: integrator table can be omitted<commit_after>#ifndef MJOLNIR_INPUT_READ_INTEGRATOR_HPP\n#define MJOLNIR_INPUT_READ_INTEGRATOR_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/VelocityVerletIntegrator.hpp>\n#include <mjolnir\/core\/UnderdampedLangevinIntegrator.hpp>\n#include <mjolnir\/core\/BAOABLangevinIntegrator.hpp>\n#include <mjolnir\/core\/SystemMotionRemover.hpp>\n#include <mjolnir\/input\/utility.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/util\/throw_exception.hpp>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nSystemMotionRemover<traitsT>\nread_system_motion_remover(const toml::value& simulator)\n{\n if(!simulator.contains(\"integrator\") ||\n !simulator.at(\"integrator\").contains(\"remove\"))\n {\n return SystemMotionRemover<traitsT>(false, false, false);\n }\n\n const auto& remove = toml::find(simulator, \"integrator\", \"remove\");\n\n const bool translation = toml::find_or(remove, \"translation\", false);\n const bool rotation = toml::find_or(remove, \"rotation\", false);\n const bool rescale = toml::find_or(remove, \"rescale\", false);\n\n return SystemMotionRemover<traitsT>(translation, rotation, rescale);\n}\n\n\ntemplate<typename traitsT>\nVelocityVerletIntegrator<traitsT>\nread_velocity_verlet_integrator(const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n using real_type = typename traitsT::real_type;\n\n const real_type delta_t = toml::find<real_type>(simulator, \"delta_t\");\n MJOLNIR_LOG_INFO(\"delta_t = \", delta_t);\n\n return VelocityVerletIntegrator<traitsT>(delta_t,\n read_system_motion_remover<traitsT>(simulator));\n}\n\ntemplate<typename traitsT>\nUnderdampedLangevinIntegrator<traitsT>\nread_underdamped_langevin_integrator(const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n using real_type = typename traitsT::real_type;\n\n const real_type delta_t = toml::find<real_type>(simulator, \"delta_t\");\n MJOLNIR_LOG_INFO(\"delta_t = \", delta_t);\n\n const auto& integrator = toml::find(simulator, \"integrator\");\n\n check_keys_available(integrator, {\"type\"_s, \"seed\"_s, \"parameters\"_s});\n\n const auto parameters = toml::find<toml::array >(integrator, \"parameters\");\n\n std::vector<real_type> gamma(parameters.size());\n for(const auto& params : parameters)\n {\n const auto idx = toml::find<std::size_t>(params, \"index\");\n const auto gm = toml::expect<real_type>(params, u8\"γ\").or_other(\n toml::expect<real_type>(params, \"gamma\")).unwrap();\n if(gamma.size() <= idx){gamma.resize(idx+1);}\n gamma.at(idx) = gm;\n\n MJOLNIR_LOG_INFO(\"idx = \", idx, \", gamma = \", gm);\n }\n return UnderdampedLangevinIntegrator<traitsT>(delta_t, std::move(gamma),\n read_system_motion_remover<traitsT>(simulator));\n}\n\ntemplate<typename traitsT>\nBAOABLangevinIntegrator<traitsT>\nread_BAOAB_langevin_integrator(const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n using real_type = typename traitsT::real_type;\n\n const real_type delta_t = toml::find<real_type>(simulator, \"delta_t\");\n MJOLNIR_LOG_INFO(\"delta_t = \", delta_t);\n\n const auto& integrator = toml::find(simulator, \"integrator\");\n\n check_keys_available(integrator, {\"type\"_s, \"seed\"_s, \"parameters\"_s});\n\n const auto parameters = toml::find<toml::array >(integrator, \"parameters\");\n\n std::vector<real_type> gamma(parameters.size());\n for(const auto& params : parameters)\n {\n const auto idx = toml::find<std::size_t>(params, \"index\");\n const auto gm = toml::expect<real_type>(params, u8\"γ\").or_other(\n toml::expect<real_type>(params, \"gamma\")).unwrap();\n if(gamma.size() <= idx) {gamma.resize(idx+1);}\n gamma.at(idx) = gm;\n\n MJOLNIR_LOG_INFO(\"idx = \", idx, \", gamma = \", gm);\n }\n return BAOABLangevinIntegrator<traitsT>(delta_t, std::move(gamma),\n read_system_motion_remover<traitsT>(simulator));\n}\n\n\/\/ A mapping object from type information (template parameter) to the actual\n\/\/ read_xxx_integrator function\ntemplate<typename T>\nstruct read_integrator_impl;\n\ntemplate<typename traitsT>\nstruct read_integrator_impl<VelocityVerletIntegrator<traitsT>>\n{\n static VelocityVerletIntegrator<traitsT> invoke(const toml::value& sim)\n {\n return read_velocity_verlet_integrator<traitsT>(sim);\n }\n};\n\ntemplate<typename traitsT>\nstruct read_integrator_impl<UnderdampedLangevinIntegrator<traitsT>>\n{\n static UnderdampedLangevinIntegrator<traitsT> invoke(const toml::value& sim)\n {\n return read_underdamped_langevin_integrator<traitsT>(sim);\n }\n};\n\ntemplate<typename traitsT>\nstruct read_integrator_impl<BAOABLangevinIntegrator<traitsT>>\n{\n static BAOABLangevinIntegrator<traitsT> invoke(const toml::value& sim)\n {\n return read_BAOAB_langevin_integrator<traitsT>(sim);\n }\n};\n\ntemplate<typename integratorT>\nintegratorT read_integrator(const toml::value& sim)\n{\n if(sim.as_table().count(\"integrator\") == 0)\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_integrator: No integrator defined: \", sim, \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"VelocityVerlet\\\" : simple and standard Velocity Verlet integrator.\",\n \"- \\\"UnderdampedLangevin\\\": simple Underdamped Langevin Integrator\"\n \" based on the Velocity Verlet\",\n \"- \\\"BAOABLangevin\\\" : well-known BAOAB Langevin Integrator\"\n }));\n }\n return read_integrator_impl<integratorT>::invoke(sim);\n}\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template VelocityVerletIntegrator<SimulatorTraits<double, UnlimitedBoundary> > read_velocity_verlet_integrator(const toml::value& simulator);\nextern template VelocityVerletIntegrator<SimulatorTraits<float, UnlimitedBoundary> > read_velocity_verlet_integrator(const toml::value& simulator);\nextern template VelocityVerletIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_velocity_verlet_integrator(const toml::value& simulator);\nextern template VelocityVerletIntegrator<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_velocity_verlet_integrator(const toml::value& simulator);\n\nextern template UnderdampedLangevinIntegrator<SimulatorTraits<double, UnlimitedBoundary> > read_underdamped_langevin_integrator(const toml::value& simulator);\nextern template UnderdampedLangevinIntegrator<SimulatorTraits<float, UnlimitedBoundary> > read_underdamped_langevin_integrator(const toml::value& simulator);\nextern template UnderdampedLangevinIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_underdamped_langevin_integrator(const toml::value& simulator);\nextern template UnderdampedLangevinIntegrator<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_underdamped_langevin_integrator(const toml::value& simulator);\n\nextern template BAOABLangevinIntegrator<SimulatorTraits<double, UnlimitedBoundary> > read_BAOAB_langevin_integrator(const toml::value& simulator);\nextern template BAOABLangevinIntegrator<SimulatorTraits<float, UnlimitedBoundary> > read_BAOAB_langevin_integrator(const toml::value& simulator);\nextern template BAOABLangevinIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_BAOAB_langevin_integrator(const toml::value& simulator);\nextern template BAOABLangevinIntegrator<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_BAOAB_langevin_integrator(const toml::value& simulator);\n#endif\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_INTEGRATOR\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMaskPoints.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkMaskPoints.h\"\n\n#include \"vtkCellArray.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPoints.h\"\n#include \"vtkPolyData.h\"\n\nvtkCxxRevisionMacro(vtkMaskPoints, \"1.41\");\nvtkStandardNewMacro(vtkMaskPoints);\n\n\/\/----------------------------------------------------------------------------\nvtkMaskPoints::vtkMaskPoints()\n{\n this->OnRatio = 2;\n this->Offset = 0;\n this->RandomMode = 0;\n this->MaximumNumberOfPoints = VTK_LARGE_ID;\n this->GenerateVertices = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMaskPoints::Execute()\n{\n vtkPoints *newPts;\n vtkPointData *pd;\n vtkIdType numNewPts;\n float *x;\n vtkIdType ptId, id;\n vtkPolyData *output = this->GetOutput();\n vtkPointData *outputPD = output->GetPointData();\n vtkDataSet *input= this->GetInput();\n vtkIdType numPts=input->GetNumberOfPoints();\n \n \/\/ Check input\n \/\/\n vtkDebugMacro(<<\"Masking points\");\n\n if ( numPts < 1 )\n {\n vtkErrorMacro(<<\"No data to mask!\");\n return;\n }\n\n pd = input->GetPointData();\n id = 0;\n \n \/\/ Allocate space\n \/\/\n numNewPts = numPts \/ this->OnRatio;\n if (numNewPts > this->MaximumNumberOfPoints)\n {\n numNewPts = this->MaximumNumberOfPoints;\n }\n newPts = vtkPoints::New();\n newPts->Allocate(numNewPts);\n outputPD->CopyAllocate(pd);\n\n \/\/ Traverse points and copy\n \/\/\n int abort=0;\n vtkIdType progressInterval=numPts\/20 +1;\n if ( this->RandomMode ) \/\/ retro mode\n {\n float cap;\n \n if (((float)numPts\/this->OnRatio) > this->MaximumNumberOfPoints)\n {\n cap = 2.0*numPts\/this->MaximumNumberOfPoints - 1;\n }\n else \n {\n cap = 2.0*this->OnRatio - 1;\n }\n\n for (ptId = this->Offset; \n (ptId < numPts) && (id < this->MaximumNumberOfPoints) && !abort; \n ptId += (1 + (int)((float)vtkMath::Random()*cap)) )\n {\n x = input->GetPoint(ptId);\n id = newPts->InsertNextPoint(x);\n outputPD->CopyData(pd,ptId,id);\n if ( ! (id % progressInterval) ) \/\/abort\/progress\n {\n this->UpdateProgress (0.5*id\/numPts);\n abort = this->GetAbortExecute();\n }\n }\n }\n else \/\/ a.r. mode\n {\n for ( ptId = this->Offset; \n (ptId < numPts) && (id < (this->MaximumNumberOfPoints-1)) && !abort;\n ptId += this->OnRatio )\n {\n x = input->GetPoint(ptId);\n id = newPts->InsertNextPoint(x);\n outputPD->CopyData(pd,ptId,id);\n if ( ! (id % progressInterval) ) \/\/abort\/progress\n {\n this->UpdateProgress (0.5*id\/numPts);\n abort = this->GetAbortExecute();\n }\n }\n }\n\n \/\/ Generate vertices if requested\n \/\/\n if ( this->GenerateVertices )\n {\n vtkCellArray *verts = vtkCellArray::New();\n verts->Allocate(verts->EstimateSize(1,id+1));\n verts->InsertNextCell(id+1);\n for ( ptId=0; ptId<(id+1) && !abort; ptId++)\n {\n if ( ! (ptId % progressInterval) ) \/\/abort\/progress\n {\n this->UpdateProgress (0.5+0.5*ptId\/(id+1));\n abort = this->GetAbortExecute();\n }\n verts->InsertCellPoint(ptId);\n }\n output->SetVerts(verts);\n verts->Delete();\n }\n\n \/\/ Update ourselves\n \/\/\n output->SetPoints(newPts);\n newPts->Delete();\n \n output->Squeeze();\n\n vtkDebugMacro(<<\"Masked \" << numPts << \" original points to \" \n << id+1 << \" points\");\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMaskPoints::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"Generate Vertices: \" \n << (this->GenerateVertices ? \"On\\n\" : \"Off\\n\");\n os << indent << \"MaximumNumberOfPoints: \" \n << this->MaximumNumberOfPoints << \"\\n\";\n os << indent << \"On Ratio: \" << this->OnRatio << \"\\n\";\n os << indent << \"Offset: \" << this->Offset << \"\\n\";\n os << indent << \"Random Mode: \" << (this->RandomMode ? \"On\\n\" : \"Off\\n\");\n}\n<commit_msg>Empty input should not produce an error, just an empty output<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMaskPoints.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkMaskPoints.h\"\n\n#include \"vtkCellArray.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPoints.h\"\n#include \"vtkPolyData.h\"\n\nvtkCxxRevisionMacro(vtkMaskPoints, \"1.42\");\nvtkStandardNewMacro(vtkMaskPoints);\n\n\/\/----------------------------------------------------------------------------\nvtkMaskPoints::vtkMaskPoints()\n{\n this->OnRatio = 2;\n this->Offset = 0;\n this->RandomMode = 0;\n this->MaximumNumberOfPoints = VTK_LARGE_ID;\n this->GenerateVertices = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMaskPoints::Execute()\n{\n vtkPoints *newPts;\n vtkPointData *pd;\n vtkIdType numNewPts;\n float *x;\n vtkIdType ptId, id;\n vtkPolyData *output = this->GetOutput();\n vtkPointData *outputPD = output->GetPointData();\n vtkDataSet *input= this->GetInput();\n vtkIdType numPts=input->GetNumberOfPoints();\n \n \/\/ Check input\n \/\/\n vtkDebugMacro(<<\"Masking points\");\n\n if ( numPts < 1 )\n {\n return;\n }\n\n pd = input->GetPointData();\n id = 0;\n \n \/\/ Allocate space\n \/\/\n numNewPts = numPts \/ this->OnRatio;\n if (numNewPts > this->MaximumNumberOfPoints)\n {\n numNewPts = this->MaximumNumberOfPoints;\n }\n newPts = vtkPoints::New();\n newPts->Allocate(numNewPts);\n outputPD->CopyAllocate(pd);\n\n \/\/ Traverse points and copy\n \/\/\n int abort=0;\n vtkIdType progressInterval=numPts\/20 +1;\n if ( this->RandomMode ) \/\/ retro mode\n {\n float cap;\n \n if (((float)numPts\/this->OnRatio) > this->MaximumNumberOfPoints)\n {\n cap = 2.0*numPts\/this->MaximumNumberOfPoints - 1;\n }\n else \n {\n cap = 2.0*this->OnRatio - 1;\n }\n\n for (ptId = this->Offset; \n (ptId < numPts) && (id < this->MaximumNumberOfPoints) && !abort; \n ptId += (1 + (int)((float)vtkMath::Random()*cap)) )\n {\n x = input->GetPoint(ptId);\n id = newPts->InsertNextPoint(x);\n outputPD->CopyData(pd,ptId,id);\n if ( ! (id % progressInterval) ) \/\/abort\/progress\n {\n this->UpdateProgress (0.5*id\/numPts);\n abort = this->GetAbortExecute();\n }\n }\n }\n else \/\/ a.r. mode\n {\n for ( ptId = this->Offset; \n (ptId < numPts) && (id < (this->MaximumNumberOfPoints-1)) && !abort;\n ptId += this->OnRatio )\n {\n x = input->GetPoint(ptId);\n id = newPts->InsertNextPoint(x);\n outputPD->CopyData(pd,ptId,id);\n if ( ! (id % progressInterval) ) \/\/abort\/progress\n {\n this->UpdateProgress (0.5*id\/numPts);\n abort = this->GetAbortExecute();\n }\n }\n }\n\n \/\/ Generate vertices if requested\n \/\/\n if ( this->GenerateVertices )\n {\n vtkCellArray *verts = vtkCellArray::New();\n verts->Allocate(verts->EstimateSize(1,id+1));\n verts->InsertNextCell(id+1);\n for ( ptId=0; ptId<(id+1) && !abort; ptId++)\n {\n if ( ! (ptId % progressInterval) ) \/\/abort\/progress\n {\n this->UpdateProgress (0.5+0.5*ptId\/(id+1));\n abort = this->GetAbortExecute();\n }\n verts->InsertCellPoint(ptId);\n }\n output->SetVerts(verts);\n verts->Delete();\n }\n\n \/\/ Update ourselves\n \/\/\n output->SetPoints(newPts);\n newPts->Delete();\n \n output->Squeeze();\n\n vtkDebugMacro(<<\"Masked \" << numPts << \" original points to \" \n << id+1 << \" points\");\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMaskPoints::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"Generate Vertices: \" \n << (this->GenerateVertices ? \"On\\n\" : \"Off\\n\");\n os << indent << \"MaximumNumberOfPoints: \" \n << this->MaximumNumberOfPoints << \"\\n\";\n os << indent << \"On Ratio: \" << this->OnRatio << \"\\n\";\n os << indent << \"Offset: \" << this->Offset << \"\\n\";\n os << indent << \"Random Mode: \" << (this->RandomMode ? \"On\\n\" : \"Off\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <iostream>\n\n#include <SFML\/Graphics.hpp>\n\n#include \"Universe.hpp\"\n#include \"Body.hpp\"\n\n#define MASS 10\n#define BASE_LINE 2\n\nusing namespace sf;\nusing namespace std;\n\nint main()\n{\n\tunsigned int width(800), height(600);\n\tRenderWindow window(VideoMode(width, height), \"Gravity Simulation by Johan\");\n\tView view(FloatRect(0, 0, width, height));\n\n\t\/\/ Drawable elements\n\tUniverse universe;\n\tVertexArray line(Lines, 2);\n\tCircleShape base_line(BASE_LINE);\n\n\t\/\/ Logic vars\n\tClock timer;\n\tfloat delta_t(0);\n\tint mass(MASS);\n\tVector2f mousePosition;\n\tVector2f start, end;\n\tbool running = true;\n\tbool is_placing = false;\n\tbool is_moving = false;\n\tbool trace = false;\n\tbool control = false;\n\tbool shift = false;\n\n\t\/\/ Some inits\n\tline[0].color = Color::Blue;\n\tline[1].color = Color::Green;\n\tbase_line.setFillColor(Color::Blue);\n\twindow.setView(view);\n\n\twhile (running)\n\t{\n\t\tEvent evt;\n\t\twhile (window.pollEvent(evt))\n\t\t{\n\t\t\tif (evt.type == Event::Closed)\n\t\t\t{\n\t\t\t\trunning = false;\n\t\t\t}\n\n\t\t\tif (evt.type == Event::Resized)\n\t\t\t{\n\t\t\t\tview.setSize(evt.size.width, evt.size.height);\n\t\t\t\twindow.setView(view);\n\t\t\t}\n\n\t\t\tif (evt.type == Event::KeyPressed)\n\t\t\t{\n\t\t\t\tif (evt.key.code == Keyboard::Escape)\n\t\t\t\t{\n\t\t\t\t\trunning = false;\n\t\t\t\t}\n\n\t\t\t\tswitch (evt.key.code)\n\t\t\t\t{\n case Keyboard::PageUp:\n\t\t\t\tcase Keyboard::Add:\n\t\t\t\t\tmass *= 10;\n\t\t\t\t\tif (mass < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmass = MASS;\n\t\t\t\t\t}\n\t\t\t\t\tcout << \"Mass is now \" << mass << endl;\n\t\t\t\t\tbreak;\n\n case Keyboard::PageDown:\n\t\t\t\tcase Keyboard::Subtract:\n\t\t\t\t\tif (mass > 10)\n\t\t\t\t\t{\n\t\t\t\t\t\tmass \/= 10;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmass = MASS;\n\t\t\t\t\t}\n\t\t\t\t\tcout << \"Mass is now \" << mass << endl;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Keyboard::T:\n\t\t\t\t\ttrace = !trace;\n\t\t\t\t\tcout << \"Trace mode \" << (trace ? \"enabled\" : \"disabled\") << endl;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Keyboard::Space:\n if (is_placing)\n {\n cout << \"Planet placement cancelled\" << endl;\n }\n \n is_placing = false;\n break;\n\n case Keyboard::LControl:\n \tcontrol = true;\n \tbreak;\n\n case Keyboard::LShift:\n \tshift = true;\n \tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (evt.type == Event::KeyReleased)\n\t\t\t{\n\t\t\t\tswitch (evt.key.code)\n\t\t\t\t{\n\t\t\t\tcase Keyboard::LControl:\n\t\t\t\t\tcontrol = false;\n\n\t\t\t\tcase Keyboard::LShift:\n\t\t\t\t\tshift = false;\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (evt.type == Event::MouseButtonPressed)\n\t\t\t{\n if (shift)\n {\n universe.eraseAt(Vector2f(evt.mouseButton.x, evt.mouseButton.y));\n }\n else if (control)\n {\n \tis_moving = true;\n }\n else\n {\n is_placing = true;\n\n line[0].position = window.mapPixelToCoords(Vector2i(evt.mouseButton.x, evt.mouseButton.y));\n line[1].position = line[0].position;\n start = Vector2f(evt.mouseButton.x, evt.mouseButton.y);\n end = start;\n\n Vector2f base = \n \twindow.mapPixelToCoords(Vector2i(evt.mouseButton.x - BASE_LINE, evt.mouseButton.y - BASE_LINE));\n base_line.setPosition(base);\n }\n }\n\n\t\t\tif (evt.type == Event::MouseMoved)\n\t\t\t{\n\t\t\t\tif (is_placing)\n\t\t\t\t{\n\t\t\t\t\tline[1].position = window.mapPixelToCoords(Vector2i(evt.mouseMove.x, evt.mouseMove.y));\n\t\t\t\t\tend = Vector2f(evt.mouseMove.x, evt.mouseMove.y);\n\t\t\t\t}\n\n\t\t\t\tif (is_moving)\n\t\t\t\t{\n\t\t\t\t\tview.move(mousePosition - Vector2f(evt.mouseMove.x, evt.mouseMove.y));\n\t\t\t\t\twindow.setView(view);\n\t\t\t\t}\n\n\t\t\t\tmousePosition = Vector2f(evt.mouseMove.x, evt.mouseMove.y);\n\t\t\t}\n\n\t\t\tif (evt.type == Event::MouseButtonReleased)\n\t\t\t{\n\t\t\t\tif (is_placing)\n\t\t\t\t{\n\t\t\t\t\tis_placing = false;\n\n\t\t\t\t\tVector2f direction = end - start;\n\n\t\t\t\t\tBody p(Vector2f(0, 0), mass, direction);\n\n\t\t\t\t\tp.position = Vector2f(line[0].position.x,\n\t\t\t\t\t\t\tline[0].position.y);;\n\n\t\t\t\t\tuniverse.addPlanet(p);\n\t\t\t\t}\n\n\t\t\t\tif (is_moving)\n\t\t\t\t{\n\t\t\t\t\tis_moving = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (evt.type == Event::MouseWheelMoved)\n\t\t\t{\n\t\t\t\tfloat factor = (evt.mouseWheel.delta < 1 ? 1.10 : 0.90);\n\t\t\t\tview.zoom(factor);\n\t\t\t\twindow.setView(view);\n\t\t\t}\n\t\t}\n\n\t\tif (!trace)\n\t\t{\n\t\t\twindow.clear();\n\t\t}\n\n\t\t\/\/ Delta T\n\t\tdelta_t = timer.restart().asSeconds();\n\n\t\t\/\/ Vector Preview - wow - need an arrow - hard\n\t\tif (is_placing)\n\t\t{\n\t\t\twindow.draw(line);\n\t\t\twindow.draw(base_line);\n\t\t}\n\n\t\t\/\/ Planets\n\t\tuniverse.move(delta_t);\n\t\tuniverse.draw(window);\n\t\t\n\t\twindow.display();\n\n\t\tsleep(milliseconds(3));\n\t}\n\n\treturn 0;\n}\n<commit_msg>added protodisk generation (press C)<commit_after>#include <vector>\n#include <iostream>\n#include <random>\n\n#include <SFML\/Graphics.hpp>\n\n#include \"Universe.hpp\"\n#include \"Body.hpp\"\n\n#define MASS 10\n#define BASE_LINE 2\n#define CLUSTER_RADIUS 150\n#define CLUSTER_NUMBER 1000\n\n#ifdef _WIN32\n\t#define M_PI 3.14\n#endif\n\nusing namespace sf;\nusing namespace std;\n\nfloat gen_random_float();\n\nint main()\n{\n\tunsigned int width(800), height(600);\n\tRenderWindow window(VideoMode(width, height), \"Gravity Simulation by Johan\");\n\tView view(FloatRect(0, 0, width, height));\n\n\t\/\/ Drawable elements\n\tUniverse universe;\n\tVertexArray line(Lines, 2);\n\tCircleShape base_line(BASE_LINE);\n\n\t\/\/ Logic vars\n\tClock timer;\n\tfloat delta_t(0);\n\tint mass(MASS);\n\tVector2f mousePosition;\n\tVector2f start, end;\n\tbool running = true;\n\tbool is_placing = false;\n\tbool is_moving = false;\n\tbool trace = false;\n\tbool control = false;\n\tbool shift = false;\n\n\t\/\/ Some inits\n\tsrand(time(0));\n\tline[0].color = Color::Blue;\n\tline[1].color = Color::Green;\n\tbase_line.setFillColor(Color::Blue);\n\twindow.setView(view);\n\n\twhile (running)\n\t{\n\t\tEvent evt;\n\t\twhile (window.pollEvent(evt))\n\t\t{\n\t\t\tif (evt.type == Event::Closed)\n\t\t\t{\n\t\t\t\trunning = false;\n\t\t\t}\n\n\t\t\tif (evt.type == Event::Resized)\n\t\t\t{\n\t\t\t\tview.setSize(evt.size.width, evt.size.height);\n\t\t\t\twindow.setView(view);\n\t\t\t}\n\n\t\t\tif (evt.type == Event::KeyPressed)\n\t\t\t{\n\t\t\t\tif (evt.key.code == Keyboard::Escape)\n\t\t\t\t{\n\t\t\t\t\trunning = false;\n\t\t\t\t}\n\n\t\t\t\tswitch (evt.key.code)\n\t\t\t\t{\n\t\t\t\tcase Keyboard::PageUp:\n\t\t\t\tcase Keyboard::Add:\n\t\t\t\t\tmass *= 10;\n\t\t\t\t\tif (mass < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmass = MASS;\n\t\t\t\t\t}\n\t\t\t\t\tcout << \"Mass is now \" << mass << endl;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Keyboard::PageDown:\n\t\t\t\tcase Keyboard::Subtract:\n\t\t\t\t\tif (mass > 10)\n\t\t\t\t\t{\n\t\t\t\t\t\tmass \/= 10;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmass = MASS;\n\t\t\t\t\t}\n\t\t\t\t\tcout << \"Mass is now \" << mass << endl;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Keyboard::T:\n\t\t\t\t\ttrace = !trace;\n\t\t\t\t\tcout << \"Trace mode \" << (trace ? \"enabled\" : \"disabled\") << endl;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Keyboard::Space:\n\t\t\t\t\tif (is_placing)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"Planet placement cancelled\" << endl;\n\t\t\t\t\t}\n\t \n\t\t\t\t\tis_placing = false;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Keyboard::LControl:\n\t\t\t\t\tcontrol = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Keyboard::LShift:\n\t\t\t\t\tshift = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Keyboard::C:\n\t\t\t\t\t{\n\t\t\t\t\t\tVector2f pos_circle(view.getCenter());\n\n\t\t\t\t\t\tfor (int i = 0; i < CLUSTER_NUMBER; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat a(gen_random_float());\n\t\t\t\t\t\t\tfloat b(gen_random_float());\n\n\t\t\t\t\t\t\tif (b > a)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfloat t(a);\n\t\t\t\t\t\t\t\ta = b;\n\t\t\t\t\t\t\t\tb = t;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tVector2f pos_p(b*CLUSTER_RADIUS*cos(2*M_PI*a\/b), b*CLUSTER_RADIUS*sin(2*M_PI*a\/b));\n\t\t\t\t\t\t\tpos_p += pos_circle;\n\n\t\t\t\t\t\t\tuniverse.addPlanet(pos_p, 1, Vector2f());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (evt.type == Event::KeyReleased)\n\t\t\t{\n\t\t\t\tswitch (evt.key.code)\n\t\t\t\t{\n\t\t\t\tcase Keyboard::LControl:\n\t\t\t\t\tcontrol = false;\n\n\t\t\t\tcase Keyboard::LShift:\n\t\t\t\t\tshift = false;\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (evt.type == Event::MouseButtonPressed)\n\t\t\t{\n\t\t\t\tif (shift)\n\t\t\t\t{\n\t\t\t\t\tuniverse.eraseAt(Vector2f(evt.mouseButton.x, evt.mouseButton.y));\n\t\t\t\t}\n\t\t\t\telse if (control)\n\t\t\t\t{\n\t\t\t\t\tis_moving = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tis_placing = true;\n\n\t\t\t\t\tline[0].position = window.mapPixelToCoords(Vector2i(evt.mouseButton.x, evt.mouseButton.y));\n\t\t\t\t\tline[1].position = line[0].position;\n\t\t\t\t\tstart = Vector2f(evt.mouseButton.x, evt.mouseButton.y);\n\t\t\t\t\tend = start;\n\n\t\t\t\t\tVector2f base = \n\t\t\t\t\t\twindow.mapPixelToCoords(Vector2i(evt.mouseButton.x - BASE_LINE, evt.mouseButton.y - BASE_LINE));\n\t\t\t\t\tbase_line.setPosition(base);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (evt.type == Event::MouseMoved)\n\t\t\t{\n\t\t\t\tif (is_placing)\n\t\t\t\t{\n\t\t\t\t\tline[1].position = window.mapPixelToCoords(Vector2i(evt.mouseMove.x, evt.mouseMove.y));\n\t\t\t\t\tend = Vector2f(evt.mouseMove.x, evt.mouseMove.y);\n\t\t\t\t}\n\n\t\t\t\tif (is_moving)\n\t\t\t\t{\n\t\t\t\t\tview.move(mousePosition - Vector2f(evt.mouseMove.x, evt.mouseMove.y));\n\t\t\t\t\twindow.setView(view);\n\t\t\t\t}\n\n\t\t\t\tmousePosition = Vector2f(evt.mouseMove.x, evt.mouseMove.y);\n\t\t\t}\n\n\t\t\tif (evt.type == Event::MouseButtonReleased)\n\t\t\t{\n\t\t\t\tif (is_placing)\n\t\t\t\t{\n\t\t\t\t\tis_placing = false;\n\n\t\t\t\t\tVector2f direction = end - start;\n\n\t\t\t\t\tBody p(Vector2f(0, 0), mass, direction);\n\n\t\t\t\t\tp.position = Vector2f(line[0].position.x,\n\t\t\t\t\t\t\tline[0].position.y);;\n\n\t\t\t\t\tuniverse.addPlanet(p);\n\t\t\t\t}\n\n\t\t\t\tif (is_moving)\n\t\t\t\t{\n\t\t\t\t\tis_moving = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (evt.type == Event::MouseWheelMoved)\n\t\t\t{\n\t\t\t\tfloat factor = (evt.mouseWheel.delta < 1 ? 1.10 : 0.90);\n\t\t\t\tview.zoom(factor);\n\t\t\t\twindow.setView(view);\n\t\t\t}\n\t\t}\n\n\t\tif (!trace)\n\t\t{\n\t\t\twindow.clear();\n\t\t}\n\n\t\t\/\/ Delta T\n\t\tdelta_t = timer.restart().asSeconds();\n\n\t\t\/\/ Vector Preview - wow - need an arrow - hard\n\t\tif (is_placing)\n\t\t{\n\t\t\twindow.draw(line);\n\t\t\twindow.draw(base_line);\n\t\t}\n\n\t\t\/\/ Planets\n\t\tuniverse.move(delta_t);\n\t\tuniverse.draw(window);\n\t\t\n\t\twindow.display();\n\n\t\tsleep(milliseconds(3));\n\t}\n\n\treturn 0;\n}\n\nfloat gen_random_float()\n{\n\tstatic mt19937 engine(time(nullptr));\n\tstatic uniform_real_distribution<float> distribution(0.0f, 1.0f);\n\n\tstatic auto gen = std::bind(distribution, engine);\n\n\treturn gen();\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\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#include \"otbTrainImagesClassifier.h\"\n\n#include <iostream>\n#include \"otbCommandLineArgumentParser.h\"\n\n\/\/Image \n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbVectorData.h\"\n#include \"otbVectorDataFileReader.h\"\n#include \"otbListSampleGenerator.h\"\n\/\/#include \"otbTypeManager.h\"\n\n\/\/ ListSample\n#include \"itkListSample.h\"\n#include \"itkVariableLengthVector.h\"\n#include \"itkFixedArray.h\"\n\n\/\/ SVM estimator\n#include \"otbSVMSampleListModelEstimator.h\"\n\n\/\/ Statistic XML Reader\n#include \"otbStatisticsXMLFileReader.h\"\n\n\/\/ Validation\n#include \"otbSVMClassifier.h\"\n#include \"otbConfusionMatrixCalculator.h\"\n\n#include \"itkTimeProbe.h\"\n#include \"otbStandardFilterWatcher.h\"\n\n\/\/ Normalize the samples\n#include \"otbShiftScaleSampleListFilter.h\"\n\n\/\/ List sample concatenation\n#include \"otbConcatenateSampleListFilter.h\"\n\n\/\/ Balancing ListSample\n#include \"otbListSampleToBalancedListSampleFilter.h\"\n\nnamespace otb\n{\n\nint TrainImagesClassifier::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"TrainImagesClassifier\");\n descriptor->SetDescription(\"Perform SVM training from multiple input images and multiple vector data.\");\n descriptor->AddOptionNParams(\"InputImages\", \"A list of images\", \n \"in\", true, ApplicationDescriptor::InputImage);\n descriptor->AddOptionNParams(\"VectorDataSamples\", \"Vector Data of sample used to train the estimator\", \n \"vd\", true, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"ImagesStatistics\", \"XML file containing mean and variance of input images.\",\n \"is\", 1, false, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"Output\", \"Output SVM model\",\n \"out\", 1, true, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"Margin\", \"Margin for SVM learning.\",\n \"m\", 1, false, ApplicationDescriptor::Real);\n descriptor->AddOption(\"Balancing\", \"Balance and grow the training set.\",\n \"b\", 1, false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"SVM_Kernel\", \"Type of kernel use to estimate SVM model : 0 = LINEAR (default), 1 = RBF, 2 = POLY, 3 = SIGMOID\",\n \"k\", 1, false, ApplicationDescriptor::Integer);\n return EXIT_SUCCESS;\n}\n\nint TrainImagesClassifier::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n \/\/ Input Image\n \/\/typedef double ValueType;\n \/\/typedef unsigned short PixelType; \/\/ def by manuel\n typedef float PixelType;\n typedef otb::VectorImage<PixelType,2> VectorImageType;\n typedef otb::Image<PixelType,2> ImageType;\n typedef otb::ImageFileReader<VectorImageType> ReaderType;\n\n \/\/ Training vectordata\n typedef otb::VectorData<> VectorDataType;\n typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;\n typedef itk::VariableLengthVector<PixelType> MeasurementType;\n\n \/\/ SampleList manipulation\n typedef otb::ListSampleGenerator<VectorImageType, VectorDataType> ListSampleGeneratorType;\n\n typedef ListSampleGeneratorType::ListSampleType ListSampleType;\n typedef ListSampleGeneratorType::LabelType LabelType;\n typedef ListSampleGeneratorType::ListLabelType LabelListSampleType;\n typedef otb::Statistics::ConcatenateSampleListFilter\n <ListSampleType> ConcatenateListSampleFilterType;\n typedef otb::Statistics::ConcatenateSampleListFilter\n <LabelListSampleType> ConcatenateLabelListSampleFilterType;\n\n \/\/ Statistic XML file Reader \n typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader;\n\n typedef otb::Statistics::ListSampleToBalancedListSampleFilter<\n ListSampleType, LabelListSampleType> BalancingListSampleFilterType;\n\n typedef otb::Statistics::ShiftScaleSampleListFilter<\n ListSampleType, ListSampleType> ShiftScaleFilterType;\n\n \/\/ SVM Estimator\n typedef otb::Functor::VariableLengthVectorToMeasurementVectorFunctor<\n MeasurementType> MeasurementVectorFunctorType;\n typedef otb::SVMSampleListModelEstimator<\n ListSampleType,\n LabelListSampleType,\n MeasurementVectorFunctorType> SVMEstimatorType;\n typedef otb::SVMClassifier<ListSampleType, LabelType::ValueType> ClassifierType;\n\n typedef otb::ConfusionMatrixCalculator<LabelListSampleType,\n LabelListSampleType> ConfusionMatrixCalculatorType;\n typedef ClassifierType::OutputType ClassifierOutputType;\n\n \/\/Create training and validation for list samples and label list samples\n ConcatenateLabelListSampleFilterType::Pointer concatenateTrainingLabels =\n ConcatenateLabelListSampleFilterType::New();\n ConcatenateListSampleFilterType::Pointer concatenateTrainingSamples =\n ConcatenateListSampleFilterType::New();\n ConcatenateLabelListSampleFilterType::Pointer concatenateValidationLabels =\n ConcatenateLabelListSampleFilterType::New();\n ConcatenateListSampleFilterType::Pointer concatenateValidationSamples =\n ConcatenateListSampleFilterType::New();\n\n \/\/Set the size of training and validation set\n \/\/TODO use default parameters of the filter?\n const long int maxTrainingSize = 100;\n const long int maxValidationSize = 100;\n const double validationTrainingProportion = 0.5;\n\n unsigned int nbBands = 0;\n \/\/Iterate over all input images\n for(int imgIndex = 0; imgIndex<parseResult->GetNumberOfParameters(\"InputImages\");++imgIndex)\n {\n \/\/ Read the image\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(parseResult->GetParameterString(\"InputImages\",imgIndex));\n reader->UpdateOutputInformation();\n\n std::cout<<\"Processing image (\"<<imgIndex<<\"): \"<<reader->GetFileName()<<std::endl;\n\n if (imgIndex == 0)\n {\n nbBands = reader->GetOutput()->GetNumberOfComponentsPerPixel();\n }\n\n \/\/ read the Vectordata\n VectorDataReaderType::Pointer vdreader = VectorDataReaderType::New();\n vdreader->SetFileName(parseResult->GetParameterString(\"VectorDataSamples\",imgIndex));\n vdreader->Update();\n std::cout<<\"Set VectorData filename: \"<< parseResult->GetParameterString(\"VectorDataSamples\",imgIndex) <<std::endl;\n\n \/\/Sample list generator\n ListSampleGeneratorType::Pointer sampleGenerator = ListSampleGeneratorType::New();\n\n \/\/Set inputs of the sample generator\n \/\/TODO the ListSampleGenerator perform UpdateOutputData over the input image (need a persistent implementation)\n sampleGenerator->SetInput(reader->GetOutput());\n sampleGenerator->SetInputVectorData(vdreader->GetOutput());\n sampleGenerator->SetMaxTrainingSize(maxTrainingSize);\n sampleGenerator->SetMaxValidationSize(maxValidationSize);\n sampleGenerator->SetValidationTrainingProportion(validationTrainingProportion);\n\n sampleGenerator->SetClassKey(\"Class\");\n\n sampleGenerator->Update();\n\n std::cout << \"output size: \" << sampleGenerator->GetTrainingListLabel()->GetMeasurementVectorSize() <<std::endl;\n\n \/\/Concatenate training and validation samples from the image\n concatenateTrainingLabels->AddInput(sampleGenerator->GetTrainingListLabel());\n concatenateTrainingSamples->AddInput(sampleGenerator->GetTrainingListSample());\n concatenateValidationLabels->AddInput(sampleGenerator->GetValidationListLabel());\n concatenateValidationSamples->AddInput(sampleGenerator->GetValidationListSample());\n }\n\n \/\/ Update\n concatenateTrainingSamples->Update();\n concatenateTrainingLabels->Update();\n concatenateValidationSamples->Update();\n concatenateValidationLabels->Update();\n\n \/\/ Normalize the samples\n \/\/ Read the mean and variance form the XML file (estimate with the otbEstimateImagesStatistics application)\n MeasurementType meanMeasurentVector;\n MeasurementType varianceMeasurentVector;\n if(parseResult->IsOptionPresent(\"ImagesStatistics\"))\n {\n StatisticsReader::Pointer statisticsReader = StatisticsReader::New();\n statisticsReader->SetFileName(parseResult->GetParameterString(\"ImagesStatistics\").c_str());\n meanMeasurentVector = statisticsReader->GetStatisticVectorByName(\"mean\");\n varianceMeasurentVector = statisticsReader->GetStatisticVectorByName(\"variance\");\n }\n else\n {\n meanMeasurentVector.SetSize(nbBands);\n meanMeasurentVector.Fill(0.);\n varianceMeasurentVector.SetSize(nbBands);\n varianceMeasurentVector.Fill(1.);\n }\n\n std::cout << \"MeanVector: \" << meanMeasurentVector << std::endl;\n std::cout << \"Variance Vector: \" << varianceMeasurentVector << std::endl;\n\n \/\/ Shift scale the samples\n ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New();\n trainingShiftScaleFilter->SetInput(concatenateTrainingSamples->GetOutput());\n trainingShiftScaleFilter->SetShifts(meanMeasurentVector);\n trainingShiftScaleFilter->SetScales(varianceMeasurentVector);\n trainingShiftScaleFilter->Update();\n\n ShiftScaleFilterType::Pointer validationShiftScaleFilter = ShiftScaleFilterType::New();\n validationShiftScaleFilter->SetInput(concatenateValidationSamples->GetOutput());\n validationShiftScaleFilter->SetShifts(meanMeasurentVector);\n validationShiftScaleFilter->SetScales(varianceMeasurentVector);\n validationShiftScaleFilter->Update();\n\n ListSampleType::Pointer listSample;\n LabelListSampleType::Pointer labelListSample;\n\n if(parseResult->IsOptionPresent(\"Balancing\"))\n {\n \/\/ Balance the list sample.\n std::cout<<\"Number of training samples before balancing: \"<<concatenateTrainingSamples->GetOutputSampleList()->Size()<<std::endl;\n BalancingListSampleFilterType::Pointer balancingFilter = BalancingListSampleFilterType::New();\n balancingFilter->SetInput(trainingShiftScaleFilter->GetOutput()\/*GetOutputSampleList()*\/);\n balancingFilter->SetInputLabel(concatenateTrainingLabels->GetOutput()\/*GetOutputSampleList()*\/);\n balancingFilter->SetBalancingFactor(parseResult->GetParameterUInt(\"Balancing\"));\n balancingFilter->Update();\n listSample = balancingFilter->GetOutputSampleList();\n labelListSample = balancingFilter->GetOutputLabelSampleList();\n std::cout<<\"Number of samples after balancing: \"<<balancingFilter->GetOutputSampleList()->Size()<<std::endl;\n }\n else\n {\n listSample = trainingShiftScaleFilter->GetOutputSampleList();\n labelListSample = concatenateTrainingLabels->GetOutputSampleList();\n std::cout<<\"Number of training samples: \"<<concatenateTrainingSamples->GetOutputSampleList()->Size()<<std::endl;\n }\n\n \/\/ split the data set into training\/validation set\n ListSampleType::Pointer trainingListSample = listSample;\n ListSampleType::Pointer validationListSample = validationShiftScaleFilter->GetOutputSampleList();\n LabelListSampleType::Pointer trainingLabeledListSample = labelListSample;\n LabelListSampleType::Pointer validationLabeledListSample = concatenateValidationLabels->GetOutputSampleList();\n\n std::cout<<\"Size of training set: \"<<trainingListSample->Size()<<std::endl;\n std::cout<<\"Size of validation set: \"<<validationListSample->Size()<<std::endl;\n std::cout<<\"Size of labeled training set: \"<<trainingLabeledListSample->Size()<<std::endl;\n std::cout<<\"Size of labeled validation set: \"<<validationLabeledListSample->Size()<<std::endl;\n\n \/\/ Estimate SVM model\n SVMEstimatorType::Pointer svmestimator = SVMEstimatorType::New();\n svmestimator->SetInputSampleList(trainingListSample);\n svmestimator->SetTrainingSampleList(trainingLabeledListSample);\n svmestimator->SetParametersOptimization(true);\n\n \/\/TODO : Add some other options\n\n if(parseResult->IsOptionPresent(\"Margin\"))\n {\n svmestimator->SetC(parseResult->GetParameterDouble(\"Margin\"));\n }\n\n if(parseResult->IsOptionPresent(\"Margin\"))\n {\n switch (parseResult->GetParameterInt(\"SVM_Kernel\"))\n {\n case 0: \/\/ LINEAR\n svmestimator->SetKernelType(LINEAR);\n break;\n case 1: \/\/ RBF\n svmestimator->SetKernelType(RBF);\n break;\n case 2: \/\/ POLY\n svmestimator->SetKernelType(POLY);\n break;\n case 3: \/\/ SIGMOID\n svmestimator->SetKernelType(SIGMOID);\n break;\n default: \/\/ DEFAULT = LINEAR\n svmestimator->SetKernelType(LINEAR);\n break;\n }\n }\n else\n {\n svmestimator->SetKernelType(LINEAR);\n }\n svmestimator->Update();\n svmestimator->GetModel()->SaveModel(parseResult->GetParameterString(\"Output\"));\n\n std::cout<<\"Learning done -> Final SVM accuracy: \" << svmestimator->GetFinalCrossValidationAccuracy() <<std::endl;\n\n \/\/--------------------------\n \/\/ Performances estimation\n ClassifierType::Pointer validationClassifier = ClassifierType::New();\n validationClassifier->SetSample(validationListSample);\n validationClassifier->SetNumberOfClasses(svmestimator->GetModel()->GetNumberOfClasses());\n validationClassifier->SetModel(svmestimator->GetModel());\n validationClassifier->Update();\n\n \/\/ Estimate performances\n ClassifierOutputType::ConstIterator it = validationClassifier->GetOutput()->Begin();\n ClassifierOutputType::ConstIterator itEnd = validationClassifier->GetOutput()->End();\n\n LabelListSampleType::Pointer classifierListLabel = LabelListSampleType::New();\n\n while (it != itEnd)\n {\n \/\/ Due to a bug in SVMClassifier, outlier in one-class SVM are labeled with unsigned int max\n classifierListLabel->PushBack(\n it.GetClassLabel() == itk::NumericTraits<unsigned int>::max() ? 2 : it.GetClassLabel()\n );\n ++it;\n }\n\n ConfusionMatrixCalculatorType::Pointer confMatCalc = ConfusionMatrixCalculatorType::New();\n\n confMatCalc->SetReferenceLabels(validationLabeledListSample);\n confMatCalc->SetProducedLabels(classifierListLabel);\n\n confMatCalc->Update();\n\n std::cout<< \"confusion matrix: \\n\" << confMatCalc->GetConfusionMatrix() << std::endl;\n\n std::cout << \"Precision of the different class: \" << confMatCalc->GetPrecisions() << std::endl;\n std::cout << \"Recall of the different class: \" << confMatCalc->GetRecalls() << std::endl;\n std::cout << \"F-score of the different class: \" << confMatCalc->GetFScores() << std::endl;\n std::cout << \"Kappa index: \" << confMatCalc->GetKappaIndex() << std::endl;\n\n \/\/ TODO: implement hyperplan distance classifier and performance validation (cf. object detection) ?\n\n\n\n return EXIT_SUCCESS;\n}\n\n}\n<commit_msg>STYLE: clean code and enhance comments<commit_after>\/*=========================================================================\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#include \"otbTrainImagesClassifier.h\"\n\n#include <iostream>\n#include \"otbCommandLineArgumentParser.h\"\n\n\/\/Image \n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbVectorData.h\"\n#include \"otbVectorDataFileReader.h\"\n#include \"otbListSampleGenerator.h\"\n\/\/#include \"otbTypeManager.h\"\n\n\/\/ ListSample\n#include \"itkListSample.h\"\n#include \"itkVariableLengthVector.h\"\n#include \"itkFixedArray.h\"\n\n\/\/ SVM estimator\n#include \"otbSVMSampleListModelEstimator.h\"\n\n\/\/ Statistic XML Reader\n#include \"otbStatisticsXMLFileReader.h\"\n\n\/\/ Validation\n#include \"otbSVMClassifier.h\"\n#include \"otbConfusionMatrixCalculator.h\"\n\n#include \"itkTimeProbe.h\"\n#include \"otbStandardFilterWatcher.h\"\n\n\/\/ Normalize the samples\n#include \"otbShiftScaleSampleListFilter.h\"\n\n\/\/ List sample concatenation\n#include \"otbConcatenateSampleListFilter.h\"\n\n\/\/ Balancing ListSample\n#include \"otbListSampleToBalancedListSampleFilter.h\"\n\nnamespace otb\n{\n\nint TrainImagesClassifier::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"TrainImagesClassifier\");\n descriptor->SetDescription(\"Perform SVM training from multiple input images and multiple vector data.\");\n descriptor->AddOptionNParams(\"InputImages\", \"A list of images\", \n \"in\", true, ApplicationDescriptor::InputImage);\n descriptor->AddOptionNParams(\"VectorDataSamples\", \"Vector Data of sample used to train the estimator\", \n \"vd\", true, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"ImagesStatistics\", \"XML file containing mean and variance of input images.\",\n \"is\", 1, false, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"Output\", \"Output SVM model\",\n \"out\", 1, true, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"Margin\", \"Margin for SVM learning.\",\n \"m\", 1, false, ApplicationDescriptor::Real);\n descriptor->AddOption(\"Balancing\", \"Balance and grow the training set.\",\n \"b\", 1, false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"SVM_Kernel\", \"Type of kernel use to estimate SVM model : 0 = LINEAR (default), 1 = RBF, 2 = POLY, 3 = SIGMOID\",\n \"k\", 1, false, ApplicationDescriptor::Integer);\n return EXIT_SUCCESS;\n}\n\nint TrainImagesClassifier::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n \/\/ Input Image\n \/\/typedef double ValueType;\n typedef float PixelType;\n typedef otb::VectorImage<PixelType,2> VectorImageType;\n typedef otb::Image<PixelType,2> ImageType;\n typedef otb::ImageFileReader<VectorImageType> ReaderType;\n\n \/\/ Training vectordata\n typedef otb::VectorData<> VectorDataType;\n typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;\n typedef itk::VariableLengthVector<PixelType> MeasurementType;\n\n \/\/ SampleList manipulation\n typedef otb::ListSampleGenerator<VectorImageType, VectorDataType> ListSampleGeneratorType;\n\n typedef ListSampleGeneratorType::ListSampleType ListSampleType;\n typedef ListSampleGeneratorType::LabelType LabelType;\n typedef ListSampleGeneratorType::ListLabelType LabelListSampleType;\n typedef otb::Statistics::ConcatenateSampleListFilter\n <ListSampleType> ConcatenateListSampleFilterType;\n typedef otb::Statistics::ConcatenateSampleListFilter\n <LabelListSampleType> ConcatenateLabelListSampleFilterType;\n\n \/\/ Statistic XML file Reader \n typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader;\n\n \/\/ Enhance List Sample\n typedef otb::Statistics::ListSampleToBalancedListSampleFilter<\n ListSampleType, LabelListSampleType> BalancingListSampleFilterType;\n typedef otb::Statistics::ShiftScaleSampleListFilter<\n ListSampleType, ListSampleType> ShiftScaleFilterType;\n\n \/\/ SVM Estimator\n typedef otb::Functor::VariableLengthVectorToMeasurementVectorFunctor<\n MeasurementType> MeasurementVectorFunctorType;\n typedef otb::SVMSampleListModelEstimator<\n ListSampleType,\n LabelListSampleType,\n MeasurementVectorFunctorType> SVMEstimatorType;\n typedef otb::SVMClassifier<ListSampleType, LabelType::ValueType> ClassifierType;\n\n \/\/ Estimate performance on validation sample\n typedef otb::ConfusionMatrixCalculator<LabelListSampleType,\n LabelListSampleType> ConfusionMatrixCalculatorType;\n typedef ClassifierType::OutputType ClassifierOutputType;\n\n\n \/\/Create training and validation for list samples and label list samples\n ConcatenateLabelListSampleFilterType::Pointer concatenateTrainingLabels =\n ConcatenateLabelListSampleFilterType::New();\n ConcatenateListSampleFilterType::Pointer concatenateTrainingSamples =\n ConcatenateListSampleFilterType::New();\n ConcatenateLabelListSampleFilterType::Pointer concatenateValidationLabels =\n ConcatenateLabelListSampleFilterType::New();\n ConcatenateListSampleFilterType::Pointer concatenateValidationSamples =\n ConcatenateListSampleFilterType::New();\n\n \/\/Set the size of training and validation set\n \/\/TODO use default parameters of the filter?\n const long int maxTrainingSize = 100;\n const long int maxValidationSize = 100;\n const double validationTrainingProportion = 0.5;\n\n \/\/--------------------------\n \/\/ Load measurements from images\n unsigned int nbBands = 0;\n \/\/Iterate over all input images\n for(int imgIndex = 0; imgIndex<parseResult->GetNumberOfParameters(\"InputImages\");++imgIndex)\n {\n \/\/ Read the image\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(parseResult->GetParameterString(\"InputImages\",imgIndex));\n reader->UpdateOutputInformation();\n\n std::cout<<\"Processing image (\"<<imgIndex<<\"): \"<<reader->GetFileName()<<std::endl;\n\n if (imgIndex == 0)\n {\n nbBands = reader->GetOutput()->GetNumberOfComponentsPerPixel();\n }\n\n \/\/ read the Vectordata\n VectorDataReaderType::Pointer vdreader = VectorDataReaderType::New();\n vdreader->SetFileName(parseResult->GetParameterString(\"VectorDataSamples\",imgIndex));\n vdreader->Update();\n std::cout<<\"Set VectorData filename: \"<< parseResult->GetParameterString(\"VectorDataSamples\",imgIndex) <<std::endl;\n\n \/\/Sample list generator\n ListSampleGeneratorType::Pointer sampleGenerator = ListSampleGeneratorType::New();\n\n \/\/Set inputs of the sample generator\n \/\/TODO the ListSampleGenerator perform UpdateOutputData over the input image (need a persistent implementation)\n sampleGenerator->SetInput(reader->GetOutput());\n sampleGenerator->SetInputVectorData(vdreader->GetOutput());\n sampleGenerator->SetMaxTrainingSize(maxTrainingSize);\n sampleGenerator->SetMaxValidationSize(maxValidationSize);\n sampleGenerator->SetValidationTrainingProportion(validationTrainingProportion);\n\n sampleGenerator->SetClassKey(\"Class\");\n\n sampleGenerator->Update();\n\n std::cout << \"output size: \" << sampleGenerator->GetTrainingListLabel()->GetMeasurementVectorSize() <<std::endl;\n\n \/\/Concatenate training and validation samples from the image\n concatenateTrainingLabels->AddInput(sampleGenerator->GetTrainingListLabel());\n concatenateTrainingSamples->AddInput(sampleGenerator->GetTrainingListSample());\n concatenateValidationLabels->AddInput(sampleGenerator->GetValidationListLabel());\n concatenateValidationSamples->AddInput(sampleGenerator->GetValidationListSample());\n }\n\n \/\/ Update\n concatenateTrainingSamples->Update();\n concatenateTrainingLabels->Update();\n concatenateValidationSamples->Update();\n concatenateValidationLabels->Update();\n\n \/\/--------------------------\n \/\/ Normalize the samples\n \/\/ Read the mean and variance form the XML file (estimate with the otbEstimateImagesStatistics application)\n MeasurementType meanMeasurentVector;\n MeasurementType varianceMeasurentVector;\n if(parseResult->IsOptionPresent(\"ImagesStatistics\"))\n {\n StatisticsReader::Pointer statisticsReader = StatisticsReader::New();\n statisticsReader->SetFileName(parseResult->GetParameterString(\"ImagesStatistics\").c_str());\n meanMeasurentVector = statisticsReader->GetStatisticVectorByName(\"mean\");\n varianceMeasurentVector = statisticsReader->GetStatisticVectorByName(\"variance\");\n }\n else\n {\n meanMeasurentVector.SetSize(nbBands);\n meanMeasurentVector.Fill(0.);\n varianceMeasurentVector.SetSize(nbBands);\n varianceMeasurentVector.Fill(1.);\n }\n\n std::cout << \"MeanVector: \" << meanMeasurentVector << std::endl;\n std::cout << \"Variance Vector: \" << varianceMeasurentVector << std::endl;\n\n \/\/ Shift scale the samples\n ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New();\n trainingShiftScaleFilter->SetInput(concatenateTrainingSamples->GetOutput());\n trainingShiftScaleFilter->SetShifts(meanMeasurentVector);\n trainingShiftScaleFilter->SetScales(varianceMeasurentVector);\n trainingShiftScaleFilter->Update();\n\n ShiftScaleFilterType::Pointer validationShiftScaleFilter = ShiftScaleFilterType::New();\n validationShiftScaleFilter->SetInput(concatenateValidationSamples->GetOutput());\n validationShiftScaleFilter->SetShifts(meanMeasurentVector);\n validationShiftScaleFilter->SetScales(varianceMeasurentVector);\n validationShiftScaleFilter->Update();\n\n ListSampleType::Pointer listSample;\n LabelListSampleType::Pointer labelListSample;\n\n \/\/--------------------------\n \/\/ Balancing training sample (if needed)\n if(parseResult->IsOptionPresent(\"Balancing\"))\n {\n \/\/ Balance the list sample.\n std::cout<<\"Number of training samples before balancing: \"<<concatenateTrainingSamples->GetOutputSampleList()->Size()<<std::endl;\n BalancingListSampleFilterType::Pointer balancingFilter = BalancingListSampleFilterType::New();\n balancingFilter->SetInput(trainingShiftScaleFilter->GetOutput()\/*GetOutputSampleList()*\/);\n balancingFilter->SetInputLabel(concatenateTrainingLabels->GetOutput()\/*GetOutputSampleList()*\/);\n balancingFilter->SetBalancingFactor(parseResult->GetParameterUInt(\"Balancing\"));\n balancingFilter->Update();\n listSample = balancingFilter->GetOutputSampleList();\n labelListSample = balancingFilter->GetOutputLabelSampleList();\n std::cout<<\"Number of samples after balancing: \"<<balancingFilter->GetOutputSampleList()->Size()<<std::endl;\n }\n else\n {\n listSample = trainingShiftScaleFilter->GetOutputSampleList();\n labelListSample = concatenateTrainingLabels->GetOutputSampleList();\n std::cout<<\"Number of training samples: \"<<concatenateTrainingSamples->GetOutputSampleList()->Size()<<std::endl;\n }\n\n \/\/--------------------------\n \/\/ Split the data set into training\/validation set\n ListSampleType::Pointer trainingListSample = listSample;\n ListSampleType::Pointer validationListSample = validationShiftScaleFilter->GetOutputSampleList();\n LabelListSampleType::Pointer trainingLabeledListSample = labelListSample;\n LabelListSampleType::Pointer validationLabeledListSample = concatenateValidationLabels->GetOutputSampleList();\n\n std::cout<<\"Size of training set: \"<<trainingListSample->Size()<<std::endl;\n std::cout<<\"Size of validation set: \"<<validationListSample->Size()<<std::endl;\n std::cout<<\"Size of labeled training set: \"<<trainingLabeledListSample->Size()<<std::endl;\n std::cout<<\"Size of labeled validation set: \"<<validationLabeledListSample->Size()<<std::endl;\n\n \/\/--------------------------\n \/\/ Estimate SVM model\n SVMEstimatorType::Pointer svmestimator = SVMEstimatorType::New();\n svmestimator->SetInputSampleList(trainingListSample);\n svmestimator->SetTrainingSampleList(trainingLabeledListSample);\n svmestimator->SetParametersOptimization(true);\n\n \/\/TODO : Add some other options\n\n if(parseResult->IsOptionPresent(\"Margin\"))\n {\n svmestimator->SetC(parseResult->GetParameterDouble(\"Margin\"));\n }\n\n if(parseResult->IsOptionPresent(\"Margin\"))\n {\n switch (parseResult->GetParameterInt(\"SVM_Kernel\"))\n {\n case 0: \/\/ LINEAR\n svmestimator->SetKernelType(LINEAR);\n break;\n case 1: \/\/ RBF\n svmestimator->SetKernelType(RBF);\n break;\n case 2: \/\/ POLY\n svmestimator->SetKernelType(POLY);\n break;\n case 3: \/\/ SIGMOID\n svmestimator->SetKernelType(SIGMOID);\n break;\n default: \/\/ DEFAULT = LINEAR\n svmestimator->SetKernelType(LINEAR);\n break;\n }\n }\n else\n {\n svmestimator->SetKernelType(LINEAR);\n }\n svmestimator->Update();\n svmestimator->GetModel()->SaveModel(parseResult->GetParameterString(\"Output\"));\n\n std::cout<<\"Learning done -> Final SVM accuracy: \" << svmestimator->GetFinalCrossValidationAccuracy() <<std::endl;\n\n \/\/--------------------------\n \/\/ Performances estimation\n ClassifierType::Pointer validationClassifier = ClassifierType::New();\n validationClassifier->SetSample(validationListSample);\n validationClassifier->SetNumberOfClasses(svmestimator->GetModel()->GetNumberOfClasses());\n validationClassifier->SetModel(svmestimator->GetModel());\n validationClassifier->Update();\n\n \/\/ Estimate performances\n ClassifierOutputType::ConstIterator it = validationClassifier->GetOutput()->Begin();\n ClassifierOutputType::ConstIterator itEnd = validationClassifier->GetOutput()->End();\n\n LabelListSampleType::Pointer classifierListLabel = LabelListSampleType::New();\n\n while (it != itEnd)\n {\n \/\/ Due to a bug in SVMClassifier, outlier in one-class SVM are labeled with unsigned int max\n classifierListLabel->PushBack(\n it.GetClassLabel() == itk::NumericTraits<unsigned int>::max() ? 2 : it.GetClassLabel()\n );\n ++it;\n }\n\n ConfusionMatrixCalculatorType::Pointer confMatCalc = ConfusionMatrixCalculatorType::New();\n\n confMatCalc->SetReferenceLabels(validationLabeledListSample);\n confMatCalc->SetProducedLabels(classifierListLabel);\n\n confMatCalc->Update();\n\n std::cout<< \"confusion matrix: \\n\" << confMatCalc->GetConfusionMatrix() << std::endl;\n\n std::cout << \"Precision of the different class: \" << confMatCalc->GetPrecisions() << std::endl;\n std::cout << \"Recall of the different class: \" << confMatCalc->GetRecalls() << std::endl;\n std::cout << \"F-score of the different class: \" << confMatCalc->GetFScores() << std::endl;\n std::cout << \"Kappa index: \" << confMatCalc->GetKappaIndex() << std::endl;\n\n \/\/ TODO: implement hyperplan distance classifier and performance validation (cf. object detection) ?\n\n return EXIT_SUCCESS;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: IsoSurfaceExtraction.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Isosurface extraction has attracted continuous interest since the early\n\/\/ days of image analysis. Although it is commonly associated with image\n\/\/ segmentation, isosurface extraction is not in itself a segmentation\n\/\/ technique, instead it is a transformation that changes the way a\n\/\/ segmentation is represented. In its most common form, isosurface extraction\n\/\/ is the equivalent of image thresholding followed by surface extraction.\n\/\/\n\/\/ Probably the most widely known method of surface extraction is the\n\/\/ \\emph{Marching Cubes} algorithm~\\cite{MarchingCubes}. Although it has been\n\/\/ followed by a number of variants~\\cite{VTKBook}, Marching Cubes has become\n\/\/ an icon on medical image processing. The following example illustrates how\n\/\/ to perform isosurface extraction in ITK using an algorithm similar to\n\/\/ Marching Cubes~\\footnote{Note that the Marching Cubes algorithm is covered\n\/\/ by a patent that expired on June 5th 2005}.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageRegionIterator.h\"\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The representation of unstructured data in ITK is done with the\n\/\/ \\doxygen{Mesh}, that allows to represent N-Dimensional grids of varied\n\/\/ topology. It is natural then that the filter that extracts isosurfaces from\n\/\/ an Image will produce a Mesh as output.\n\/\/\n\/\/ We initiate our example by including the header files of the isosurface\n\/\/ extraction filter and the Mesh.\n\/\/\n\/\/ \\index{Marching Cubes}\n\/\/ \\index{Isosurface extraction!Mesh}\n\/\/ \\index{BinaryMask3DMeshSource!Header}\n\/\/ \\index{Mesh!Isosurface extraction}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkBinaryMask3DMeshSource.h\"\n#include \"itkMesh.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\nint main(int argc, char * argv[] ) \n{\n\n if( argc < 3 )\n {\n std::cerr << \"Usage: IsoSurfaceExtraction inputImageFile isoValue \" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We define then the pixel type and dimension of the image from which we are\n\/\/ going to extract the isosurface.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n const unsigned int Dimension = 3;\n typedef unsigned short PixelType;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ With the same image type we instantiate the type of an ImageFileReader and\n\/\/ construct one with the purpose of reading in the input image.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n typedef itk::ImageFileReader< ImageType > ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n\/\/ Software Guide : EndCodeSnippet\n\n try\n {\n reader->Update();\n }\n catch( itk::ExceptionObject & exp )\n {\n std::cerr << \"Exception thrown while reading the input file \" << std::endl;\n std::cerr << exp << std::endl;\n return EXIT_FAILURE;\n }\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The type of the \\doxygen{Mesh} is instantiated by specifying the type to be\n\/\/ associated with the pixel value of the Mesh nodes. Having declared the Image\n\/\/ type and the Mesh type we can also instantiate the isosurface extraction\n\/\/ filter, and construct one by invoking its \\code{New()} method.\n\/\/\n\/\/ \\index{BinaryMask3DMeshSource!Instantiation}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n typedef itk::Mesh<double> MeshType;\n\n typedef itk::BinaryMask3DMeshSource< ImageType, MeshType > MeshSourceType;\n\n MeshSourceType::Pointer meshSource = MeshSourceType::New();\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ In this particular example, the value to be used for selecting the\n\/\/ isosurface is read from the command line arguments and passed to the filter\n\/\/ by using the \\code{SetObjectValue()} method. Note that at this point this is\n\/\/ equivalent to performing thresholding on the input image.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n const PixelType isovalue = static_cast<PixelType>( atof( argv[2] ) );\n\n meshSource->SetObjectValue( isovalue );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The input to the isosurface extraction filter is taken from the output of\n\/\/ the image reader.\n\/\/\n\/\/ \\index{BinaryMask3DMeshSource!SetInput}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\/\/ Software Guide : BeginCodeSnippet\n meshSource->SetInput( reader->GetOutput() );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Finally we trigger the execution of the pipeline by invoking the\n\/\/ \\code{Update()} method. Note that given that the pipeline may throw\n\/\/ exception, this call must be place inside a \\code{try\/catch} block.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n try\n {\n meshSource->Update();\n }\n catch( itk::ExceptionObject & exp )\n {\n std::cerr << \"Exception thrown during Update() \" << std::endl;\n std::cerr << exp << std::endl;\n return EXIT_FAILURE;\n }\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ As a way of taking a look at the output Mesh we print out here its number of\n\/\/ Nodes and Cells.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n std::cout << \"Nodes = \" << meshSource->GetNumberOfNodes() << std::endl;\n std::cout << \"Cells = \" << meshSource->GetNumberOfCells() << std::endl;\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This resulting Mesh could be used as input for a deformable model\n\/\/ segmentation algorithm, or it could be converted to a format suitable for\n\/\/ visualization in an interactive application.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\n return EXIT_SUCCESS;\n}\n\n\n\n\n<commit_msg>STYLE: Clarifying that this filter does not expect an isovalue but an object value.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: IsoSurfaceExtraction.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Surface extraction has attracted continuous interest since the early days\n\/\/ of image analysis, in particular on the context of medical applications.\n\/\/ Although it is commonly associated with image segmentation, surface\n\/\/ extraction is not in itself a segmentation technique, instead it is a\n\/\/ transformation that changes the way a segmentation is represented. In its\n\/\/ most common form, isosurface extraction is the equivalent of image\n\/\/ thresholding followed by surface extraction.\n\/\/\n\/\/ Probably the most widely known method of surface extraction is the\n\/\/ \\emph{Marching Cubes} algorithm~\\cite{MarchingCubes}. Although it has been\n\/\/ followed by a number of variants~\\cite{VTKBook}, Marching Cubes has become\n\/\/ an icon on medical image processing. The following example illustrates how\n\/\/ to perform surface extraction in ITK using an algorithm similar to Marching\n\/\/ Cubes~\\footnote{Note that the Marching Cubes algorithm is covered by a\n\/\/ patent that expired on June 5th 2005.}.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\n#include \"itkImageFileReader.h\"\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The representation of unstructured data in ITK is done with the\n\/\/ \\doxygen{Mesh}, that allows to represent N-Dimensional grids of varied\n\/\/ topology. It is natural then that the filter that extracts surfaces from\n\/\/ an Image will produce a Mesh as output.\n\/\/\n\/\/ We initiate our example by including the header files of the surface\n\/\/ extraction filter, the image and the Mesh.\n\/\/\n\/\/ \\index{Marching Cubes}\n\/\/ \\index{Isosurface extraction!Mesh}\n\/\/ \\index{BinaryMask3DMeshSource!Header}\n\/\/ \\index{Mesh!Isosurface extraction}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkBinaryMask3DMeshSource.h\"\n#include \"itkImage.h\"\n#include \"itkMesh.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\nint main(int argc, char * argv[] ) \n{\n\n if( argc < 3 )\n {\n std::cerr << \"Usage: IsoSurfaceExtraction inputImageFile objectValue \" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We define then the pixel type and dimension of the image from which we are\n\/\/ going to extract the surface.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n const unsigned int Dimension = 3;\n typedef unsigned char PixelType;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ With the same image type we instantiate the type of an ImageFileReader and\n\/\/ construct one with the purpose of reading in the input image.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n typedef itk::ImageFileReader< ImageType > ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n\/\/ Software Guide : EndCodeSnippet\n\n try\n {\n reader->Update();\n }\n catch( itk::ExceptionObject & exp )\n {\n std::cerr << \"Exception thrown while reading the input file \" << std::endl;\n std::cerr << exp << std::endl;\n return EXIT_FAILURE;\n }\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The type of the \\doxygen{Mesh} is instantiated by specifying the type to be\n\/\/ associated with the pixel value of the Mesh nodes. This particular pixel\n\/\/ type happens to be irrelevant for the purpose of extracting the surface. \n\/\/ \n\/\/ \\index{BinaryMask3DMeshSource!Instantiation}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n typedef itk::Mesh<double> MeshType;\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Having declared the Image and Mesh types we can now instantiate the\n\/\/ surface extraction filter, and construct one by invoking its \\code{New()}\n\/\/ method.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\n\/\/ Software Guide : BeginCodeSnippet\n typedef itk::BinaryMask3DMeshSource< ImageType, MeshType > MeshSourceType;\n\n MeshSourceType::Pointer meshSource = MeshSourceType::New();\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ In this particular example, the pixel value to be associated to the object\n\/\/ to be extracted is read from the command line arguments and it is passed to\n\/\/ the filter by using the \\code{SetObjectValue()} method. Note that this is\n\/\/ different from the traditional isovalue used in the Marching Cubes\n\/\/ algorithm. In the case of the \\code{BinaryMask3DMeshSource} filter, the\n\/\/ object values defines the membership of pixels to the object from which the\n\/\/ surface will be extracted. In other words, the surface will be surrounding\n\/\/ all pixels with value equal to the ObjectValue parameter.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n const PixelType objectValue = static_cast<PixelType>( atof( argv[2] ) );\n\n meshSource->SetObjectValue( objectValue );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The input to the surface extraction filter is taken from the output of\n\/\/ the image reader.\n\/\/\n\/\/ \\index{BinaryMask3DMeshSource!SetInput}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\/\/ Software Guide : BeginCodeSnippet\n meshSource->SetInput( reader->GetOutput() );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Finally we trigger the execution of the pipeline by invoking the\n\/\/ \\code{Update()} method. Note that given that the pipeline may throw\n\/\/ exception, this call must be place inside a \\code{try\/catch} block.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n try\n {\n meshSource->Update();\n }\n catch( itk::ExceptionObject & exp )\n {\n std::cerr << \"Exception thrown during Update() \" << std::endl;\n std::cerr << exp << std::endl;\n return EXIT_FAILURE;\n }\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ As a way of taking a look at the output Mesh we print out here its number of\n\/\/ Nodes and Cells.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n std::cout << \"Nodes = \" << meshSource->GetNumberOfNodes() << std::endl;\n std::cout << \"Cells = \" << meshSource->GetNumberOfCells() << std::endl;\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This resulting Mesh could be used as input for a deformable model\n\/\/ segmentation algorithm, or it could be converted to a format suitable for\n\/\/ visualization in an interactive application.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\n return EXIT_SUCCESS;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: ResampleImageFilter9.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#ifdef __BORLANDC__\n#define ITK_LEAN_AND_MEAN\n#endif\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Resampling can also be performed in multi-component images. \n\/\/ This example compares nearest neighbor resampling using the Nearest \n\/\/ neighbor and the linear interpolators for vector images.\n\/\/ \n\/\/ Try \n\/\/ ResampleImageFilter9 Examples\/Data\/VisibleWomanEyeSlice.png \n\/\/ SliceNearestNeighbor.png SliceLinear.png\n\/\/\n\/\/ \\index{itk::VectorResampleImageFilter!Image internal transform}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkVectorResampleImageFilter.h\"\n#include \"itkIdentityTransform.h\"\n#include \"itkVectorNearestNeighborInterpolateImageFunction.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkRGBPixel.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] << \n \" inputImageFile outputImageFile_NearestNeighbor\" << \n \" outputImageFile_Linear \" << std::endl;\n return EXIT_FAILURE;\n }\n\n const unsigned int Dimension = 2;\n typedef unsigned char PixelComponentType;\n typedef itk::RGBPixel< PixelComponentType > PixelType;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n typedef itk::ImageFileReader< ImageType > ReaderType;\n typedef itk::ImageFileWriter< ImageType > WriterType;\n\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writerNearest = WriterType::New(); \/\/ writer for nearest neighbor\n WriterType::Pointer writerLinear = WriterType::New(); \/\/ writer for linear\n\n reader->SetFileName( argv[1] );\n writerNearest->SetFileName( argv[2] );\n writerLinear->SetFileName( argv[3] );\n\n typedef itk::VectorResampleImageFilter<\n ImageType, ImageType > FilterType;\n\n FilterType::Pointer nearestFilter = FilterType::New();\n FilterType::Pointer linearFilter = FilterType::New();\n\n \/\/Interpolators\n typedef itk::VectorNearestNeighborInterpolateImageFunction< \n ImageType, double > NearestInterpolatorType;\n NearestInterpolatorType::Pointer interpolatorNearest = NearestInterpolatorType::New();\n \n typedef itk::VectorLinearInterpolateImageFunction< \n ImageType, double > LinearInterpolatorType;\n LinearInterpolatorType::Pointer interpolatorLinear = LinearInterpolatorType::New();\n\n nearestFilter->SetInterpolator( interpolatorNearest );\n linearFilter->SetInterpolator( interpolatorLinear );\n\n typedef itk::IdentityTransform< double, Dimension > TransformType;\n TransformType::Pointer transform = TransformType::New();\n\n nearestFilter->SetTransform( transform );\n linearFilter->SetTransform( transform );\n\n \/\/ Software Guide : BeginCodeSnippet\n nearestFilter->SetDefaultPixelValue( 50 );\n linearFilter->SetDefaultPixelValue( 50 );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginCodeSnippet\n ImageType::SpacingType spacing;\n spacing[0] = .35; \/\/ pixel spacing in millimeters along X\n spacing[1] = .35; \/\/ pixel spacing in millimeters along Y\n\n nearestFilter->SetOutputSpacing( spacing );\n linearFilter->SetOutputSpacing( spacing );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginCodeSnippet\n ImageType::PointType origin;\n origin[0] = 0.4; \/\/ X space coordinate of origin\n origin[1] = 0.4; \/\/ Y space coordinate of origin\n nearestFilter->SetOutputOrigin( origin );\n linearFilter->SetOutputOrigin( origin );\n \/\/ Software Guide : EndCodeSnippet\n\n\n ImageType::SizeType size;\n\n size[0] = 300; \/\/ number of pixels along X\n size[1] = 300; \/\/ number of pixels along Y\n\n nearestFilter->SetSize( size );\n linearFilter->SetSize( size );\n\n nearestFilter->SetInput( reader->GetOutput() );\n linearFilter->SetInput( reader->GetOutput() );\n writerNearest->SetInput( nearestFilter->GetOutput() );\n writerLinear->SetInput( linearFilter->GetOutput() );\n\n\n \n try\n {\n writerNearest->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception thrown \" << std::endl;\n std::cerr << excp << std::endl;\n }\n\n try\n {\n writerLinear->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception thrown \" << std::endl;\n std::cerr << excp << std::endl;\n }\n\n return EXIT_SUCCESS;\n\n}\n\n<commit_msg>COMP: set threads to 1 to see if test passes on Borland.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: ResampleImageFilter9.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#ifdef __BORLANDC__\n#define ITK_LEAN_AND_MEAN\n#endif\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Resampling can also be performed in multi-component images. \n\/\/ This example compares nearest neighbor resampling using the Nearest \n\/\/ neighbor and the linear interpolators for vector images.\n\/\/ \n\/\/ Try \n\/\/ ResampleImageFilter9 Examples\/Data\/VisibleWomanEyeSlice.png \n\/\/ SliceNearestNeighbor.png SliceLinear.png\n\/\/\n\/\/ \\index{itk::VectorResampleImageFilter!Image internal transform}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkVectorResampleImageFilter.h\"\n#include \"itkIdentityTransform.h\"\n#include \"itkVectorNearestNeighborInterpolateImageFunction.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkRGBPixel.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] << \n \" inputImageFile outputImageFile_NearestNeighbor\" << \n \" outputImageFile_Linear \" << std::endl;\n return EXIT_FAILURE;\n }\n\n const unsigned int Dimension = 2;\n typedef unsigned char PixelComponentType;\n typedef itk::RGBPixel< PixelComponentType > PixelType;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n typedef itk::ImageFileReader< ImageType > ReaderType;\n typedef itk::ImageFileWriter< ImageType > WriterType;\n\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writerNearest = WriterType::New(); \/\/ writer for nearest neighbor\n WriterType::Pointer writerLinear = WriterType::New(); \/\/ writer for linear\n\n reader->SetFileName( argv[1] );\n writerNearest->SetFileName( argv[2] );\n writerLinear->SetFileName( argv[3] );\n\n typedef itk::VectorResampleImageFilter<\n ImageType, ImageType > FilterType;\n\n FilterType::Pointer nearestFilter = FilterType::New();\n FilterType::Pointer linearFilter = FilterType::New();\n\n \/\/Interpolators\n typedef itk::VectorNearestNeighborInterpolateImageFunction< \n ImageType, double > NearestInterpolatorType;\n NearestInterpolatorType::Pointer interpolatorNearest = NearestInterpolatorType::New();\n \n typedef itk::VectorLinearInterpolateImageFunction< \n ImageType, double > LinearInterpolatorType;\n LinearInterpolatorType::Pointer interpolatorLinear = LinearInterpolatorType::New();\n\n nearestFilter->SetInterpolator( interpolatorNearest );\n linearFilter->SetInterpolator( interpolatorLinear );\n\n typedef itk::IdentityTransform< double, Dimension > TransformType;\n TransformType::Pointer transform = TransformType::New();\n\n nearestFilter->SetTransform( transform );\n linearFilter->SetTransform( transform );\n\n \/\/ Software Guide : BeginCodeSnippet\n nearestFilter->SetDefaultPixelValue( 50 );\n nearestFilter->SetNumberOfThreads(1);\n linearFilter->SetDefaultPixelValue( 50 );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginCodeSnippet\n ImageType::SpacingType spacing;\n spacing[0] = .35; \/\/ pixel spacing in millimeters along X\n spacing[1] = .35; \/\/ pixel spacing in millimeters along Y\n\n nearestFilter->SetOutputSpacing( spacing );\n linearFilter->SetOutputSpacing( spacing );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginCodeSnippet\n ImageType::PointType origin;\n origin[0] = 0.4; \/\/ X space coordinate of origin\n origin[1] = 0.4; \/\/ Y space coordinate of origin\n nearestFilter->SetOutputOrigin( origin );\n linearFilter->SetOutputOrigin( origin );\n \/\/ Software Guide : EndCodeSnippet\n\n\n ImageType::SizeType size;\n\n size[0] = 300; \/\/ number of pixels along X\n size[1] = 300; \/\/ number of pixels along Y\n\n nearestFilter->SetSize( size );\n linearFilter->SetSize( size );\n\n nearestFilter->SetInput( reader->GetOutput() );\n linearFilter->SetInput( reader->GetOutput() );\n writerNearest->SetInput( nearestFilter->GetOutput() );\n writerLinear->SetInput( linearFilter->GetOutput() );\n\n\n \n try\n {\n writerNearest->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception thrown \" << std::endl;\n std::cerr << excp << std::endl;\n }\n\n try\n {\n writerLinear->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception thrown \" << std::endl;\n std::cerr << excp << std::endl;\n }\n\n return EXIT_SUCCESS;\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"HPRecType.h\"\r\n#include \"Util.h\"\r\n#include <set>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\natomic<HazardPointer::Node*> HazardPointer::s_head;\r\n\r\nthread_local std::vector<void*> _retiredList;\r\n\r\nvoid HazardPointer::Retire(void* pOld) {\r\n _retiredList.push_back(pOld);\r\n if (_retiredList.size() >= 100) { \/\/ Maximum retired list size\r\n Scan();\r\n }\r\n}\r\n\r\nvoid HazardPointer::Scan() {\r\n \/\/ Stage 1: Scan the hazard pointers list, collecting all nonnull ptrs\r\n std::set<void*> hazardPointers;\r\n for (auto* node = s_head.load(); node != nullptr; node = node->next) {\r\n if (node->ptr) hazardPointers.insert(node->ptr);\r\n }\r\n\r\n \/\/ Stage 2 (sort the list) isn't required when using std::set.\r\n\r\n \/\/ Stage 3: Search for them!\r\n for (auto it = _retiredList.begin(); it != _retiredList.end(); ) {\r\n if (hazardPointers.find(*it) != hazardPointers.end()) {\r\n delete *it;\r\n it = _retiredList.erase(it);\r\n } else {\r\n ++it;\r\n }\r\n }\r\n}\r\n\r\nHazardPointer::HazardPointer() {\r\n \/\/ Try to reuse a retired node\r\n for (_node = s_head.load(); _node != nullptr; _node = _node->next) {\r\n if (!CAS(_node->active, false, true)) continue;\r\n return;\r\n }\r\n\r\n \/\/ Else, there are no free nodes, create a new one\r\n _node = new HazardPointer::Node();\r\n HazardPointer::Node* old;\r\n do {\r\n old = s_head.load();\r\n _node->next = old;\r\n } while (!CAS(s_head, old, _node));\r\n return;\r\n}\r\n\r\nHazardPointer::HazardPointer(HazardPointer&& other) noexcept {\r\n std::swap(_node, other._node);\r\n}\r\n\r\nHazardPointer::~HazardPointer() {\r\n if (_node) {\r\n _node->ptr = nullptr;\r\n _node->active = false;\r\n }\r\n}\r\n\r\nHazardPointer& HazardPointer::operator=(HazardPointer&& other) noexcept {\r\n std::swap(_node, other._node);\r\n return other;\r\n}\r\n<commit_msg>Need to always scan to avoid leaking.<commit_after>#include \"HPRecType.h\"\r\n#include \"Util.h\"\r\n#include <set>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\natomic<HazardPointer::Node*> HazardPointer::s_head;\r\n\r\nthread_local std::vector<void*> _retiredList;\r\n\r\nvoid HazardPointer::Retire(void* pOld) {\r\n _retiredList.push_back(pOld);\r\n Scan();\r\n}\r\n\r\nvoid HazardPointer::Scan() {\r\n \/\/ Stage 1: Scan the hazard pointers list, collecting all nonnull ptrs\r\n std::set<void*> hazardPointers;\r\n for (auto* node = s_head.load(); node != nullptr; node = node->next) {\r\n if (node->ptr) hazardPointers.insert(node->ptr);\r\n }\r\n\r\n \/\/ Stage 2 (sort the list) isn't required when using std::set.\r\n\r\n \/\/ Stage 3: Search for them!\r\n for (auto it = _retiredList.begin(); it != _retiredList.end(); ) {\r\n if (hazardPointers.find(*it) != hazardPointers.end()) {\r\n delete *it;\r\n it = _retiredList.erase(it);\r\n } else {\r\n ++it;\r\n }\r\n }\r\n}\r\n\r\nHazardPointer::HazardPointer() {\r\n \/\/ Try to reuse a retired node\r\n for (_node = s_head.load(); _node != nullptr; _node = _node->next) {\r\n if (!CAS(_node->active, false, true)) continue;\r\n return;\r\n }\r\n\r\n \/\/ Else, there are no free nodes, create a new one\r\n _node = new HazardPointer::Node();\r\n HazardPointer::Node* old;\r\n do {\r\n old = s_head.load();\r\n _node->next = old;\r\n } while (!CAS(s_head, old, _node));\r\n return;\r\n}\r\n\r\nHazardPointer::HazardPointer(HazardPointer&& other) noexcept {\r\n std::swap(_node, other._node);\r\n}\r\n\r\nHazardPointer::~HazardPointer() {\r\n if (_node) {\r\n _node->ptr = nullptr;\r\n _node->active = false;\r\n }\r\n}\r\n\r\nHazardPointer& HazardPointer::operator=(HazardPointer&& other) noexcept {\r\n std::swap(_node, other._node);\r\n return other;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"zmq.h\"\n#include <iostream>\n#include \"AliHLTDataTypes.h\"\n#include \"AliHLTComponent.h\"\n#include \"AliHLTMessage.h\"\n#include \"TClass.h\"\n#include \"TMap.h\"\n#include \"TPRegexp.h\"\n#include \"TObjString.h\"\n#include \"TList.h\"\n#include \"TMessage.h\"\n#include \"TRint.h\"\n#include \"TApplication.h\"\n#include <time.h>\n#include <string>\n#include <map>\n#include \"AliZMQhelpers.h\"\n\n\/\/this is meant to become a class, hence the structure with global vars etc.\n\/\/Also the code is rather flat - it is a bit of a playground to test ideas.\n\/\/TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling\n\/\/zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide\n\/\/easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...)\n\n\/\/methods\nint ProcessOptionString(TString arguments);\nint InitZMQ();\nvoid* work(void* param);\nint Run();\n\n\/\/configuration vars\nTString fZMQconfigIN = \"\";\nTString fZMQconfigOUT = \"\";\nTString fZMQconfigMON = \"\";\n\nBool_t fSendOnMerge = kTRUE;\nBool_t fResetOnSend = kFALSE;\n\n\/\/ZMQ stuff\nvoid* fZMQcontext = NULL; \/\/ze zmq context\n\nvoid* fZMQmon = NULL; \/\/the request-reply socket, here we request the merged data\nvoid* fZMQout = NULL; \/\/the monitoring socket, here we publish a copy of the data\nvoid* fZMQin = NULL; \/\/the in socket - entry point for the data to be merged.\nint inType = -1;\nint outType = -1;\nint monType = -1;\n\nint fZMQtimeout = -1;\nint fZMQmaxQueueSize = 100;\nint fSleep = 0;\nbool fVerbose = false;\n\nconst char* fUSAGE =\n \"ZMQproxy: a simple monitored ZMQ proxy\\n\"\n \"options:\\n\"\n \" -in : socket in\\n\"\n \" -out : socket out\\n\"\n \" -mon : monitor socket\\n\"\n \" -sleep : sleep between polls (ms) (if in is a REQ socket)\\n\"\n \" -timeout : timeout for a poll (ms)\\n\"\n ;\n\nint capture(void* capture, zmq_msg_t* msg, int more = 0)\n{\n int rc = 0;\n if (!capture) return 0;\n zmq_msg_t ctrl;\n rc = zmq_msg_init(&ctrl);\n if (rc<0) return -1;\n rc = zmq_msg_copy(&ctrl, msg);\n if (rc<0) return -1;\n return zmq_msg_send(&ctrl, capture, more?ZMQ_SNDMORE:0);\n}\n\nint forward(void* from, void* to, void* mon, zmq_msg_t* msg)\n{\n int rc = 0;\n int more = 0;\n size_t moresize = sizeof(more);\n while (true)\n {\n rc = zmq_msg_recv(msg,from,0);\n if (rc<0) return -1;\n rc = zmq_getsockopt(from, ZMQ_RCVMORE, &more, &moresize);\n if (from!=mon) {\n rc = capture(mon,msg,more);\n }\n if (rc<0) return -1;\n rc = zmq_msg_send(msg,to,more?ZMQ_SNDMORE:0);\n if (rc<0) return -1;\n if (more==0) break;\n }\n if (fVerbose) printf(\"forwarded...\\n\");\n return 0;\n}\n\n\/\/_______________________________________________________________________________________\nint Run()\n{\n int rc = 0;\n\n bool interrunpted = false;\n while (!interrunpted)\n {\n \/\/send the requests first\n \/\/it is OK to block if there is no remote end\n \/\/the use case is to go from REQ->PUB for the event display\n \/\/otherwise the reconnect can take a while\n if (inType==ZMQ_REQ) {\n if (fVerbose) printf(\"requesting on %p %s\\n\",fZMQin, fZMQconfigIN.Data());\n rc = alizmq_msg_send(\"\",\"\",fZMQin,0);\n }\n if (outType==ZMQ_REQ) {\n if (fVerbose) printf(\"requesting on %s\\n\",fZMQconfigOUT.Data());\n alizmq_msg_send(\"\",\"\",fZMQout,0);\n }\n\n \/\/poll socket readiness for sending\n Int_t noutSockets=2;\n zmq_pollitem_t outSockets[] = { \n { fZMQin, 0, ZMQ_POLLOUT, 0 },\n { fZMQout, 0, ZMQ_POLLOUT, 0 },\n { fZMQmon, 0, ZMQ_POLLOUT, 0 },\n };\n rc = zmq_poll(outSockets, noutSockets, fZMQtimeout); \/\/poll outSockets\n if (rc==-1 && errno==ETERM)\n {\n \/\/this can only happen if the context was terminated, one of the inSockets are\n \/\/not valid or operation was interrupted\n Printf(\"zmq_poll (out) was interrupted! rc = %i, %s\", rc, zmq_strerror(errno));\n break;\n }\n \/\/in\n if (outSockets[0].revents & ZMQ_POLLOUT)\n {\n if (fVerbose) printf(\"socket (%p) %s signals ZMQ_POLLOUT\\n\",fZMQin, fZMQconfigIN.Data());\n }\n \/\/out\n if (outSockets[1].revents & ZMQ_POLLOUT)\n {\n if (fVerbose) printf(\"socket %p (%s) signals ZMQ_POLLOUT\\n\", fZMQout, fZMQconfigOUT.Data());\n }\n \/\/mon\n if (outSockets[2].revents & ZMQ_POLLOUT)\n {\n if (fVerbose) printf(\"socket %p (%s) signals ZMQ_POLLOUT\\n\", fZMQmon, fZMQconfigMON.Data());\n }\n \n \/\/poll incoming data\n Int_t ninSockets=3;\n zmq_pollitem_t inSockets[] = { \n { fZMQin, 0, ZMQ_POLLIN, 0 },\n { fZMQout, 0, ZMQ_POLLIN, 0 },\n { fZMQmon, 0, ZMQ_POLLIN, 0 },\n };\n\n if (fVerbose) printf(\"starting poll in\\n\");\n int pollrc = zmq_poll(inSockets, ninSockets, fZMQtimeout); \/\/poll inSockets\n if (pollrc==-1 && errno==ETERM)\n {\n \/\/this can only happen if the context was terminated, one of the inSockets are\n \/\/not valid or operation was interrupted\n Printf(\"zmq_poll (in) was interrupted! rc = %i, %s\", rc, zmq_strerror(errno));\n break;\n }\n\n zmq_msg_t msg;\n zmq_msg_init(&msg);\n \/\/in\n if (inSockets[0].revents & ZMQ_POLLIN)\n {\n if (fVerbose) printf(\"data in on %s\\n\",fZMQconfigIN.Data());\n if (outSockets[1].events & ZMQ_POLLOUT)\n {\n rc = forward(fZMQin,fZMQout,fZMQmon,&msg);\n }\n }\n \/\/out\n if (inSockets[1].revents & ZMQ_POLLIN)\n {\n if (fVerbose) printf(\"data in on %s\\n\",fZMQconfigOUT.Data());\n if (outSockets[0].events & ZMQ_POLLOUT)\n {\n rc = forward(fZMQout,fZMQin,fZMQmon,&msg);\n }\n }\n \/\/mon\n if (inSockets[2].revents & ZMQ_POLLIN)\n {\n if (fVerbose) printf(\"data in on %s\\n\",fZMQconfigMON.Data());\n if (outSockets[2].events & ZMQ_POLLOUT)\n {\n rc = forward(fZMQmon,fZMQmon,NULL,&msg);\n }\n }\n zmq_msg_close(&msg);\n \n \/\/if we time out (waiting for a response) reinit the REQ socket(s)\n if (pollrc==0)\n {\n if (inType==ZMQ_REQ) {\n if (fVerbose) printf(\"no reply from %s in %i ms, server died?\\n\",\n fZMQconfigIN.Data(), fZMQtimeout);\n rc = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), \n -1, fZMQmaxQueueSize);\n if (fVerbose) printf(\"rc of reinit %i\\n\",rc);\n }\n if (outType==ZMQ_REQ) {\n if (fVerbose) printf(\"no reply from %s in %i ms, server died?\\n\",\n fZMQconfigOUT.Data(), fZMQtimeout);\n rc = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(), \n -1, fZMQmaxQueueSize);\n if (fVerbose) printf(\"rc of reinit %i\\n\",rc);\n }\n if (monType==ZMQ_REQ) {\n if (fVerbose) printf(\"no reply from %s in %i ms, server died?\\n\",\n fZMQconfigMON.Data(), fZMQtimeout);\n rc = alizmq_socket_init(fZMQmon, fZMQcontext, fZMQconfigMON.Data(), \n -1, fZMQmaxQueueSize);\n if (fVerbose) printf(\"rc of reinit %i\\n\",rc);\n }\n }\n\n if (fSleep>0) usleep(fSleep);\n }\n\n return rc;\n}\n\n\/\/_______________________________________________________________________________________\nint InitZMQ()\n{\n \/\/init or reinit stuff\n int rc = 0;\n inType = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, fZMQmaxQueueSize);\n outType = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(), -1, fZMQmaxQueueSize);\n monType = alizmq_socket_init(fZMQmon, fZMQcontext, fZMQconfigMON.Data(), -1, fZMQmaxQueueSize);\n printf(\"socket init (in,out,mon): %i, %i, %i, %s, %s, %s\\n\",inType,outType,monType,alizmq_socket_name(inType),alizmq_socket_name(outType),alizmq_socket_name(monType));\n return rc;\n}\n\n\/\/______________________________________________________________________________\nint ProcessOptionString(TString arguments)\n{\n \/\/process passed options\n aliStringVec* options = AliOptionParser::TokenizeOptionString(arguments);\n int nOptions = 0;\n for (aliStringVec::iterator i=options->begin(); i!=options->end(); ++i)\n {\n const TString& option = i->first;\n const TString& value = i->second;\n if (option.EqualTo(\"ZMQconfigIN\") || option.EqualTo(\"in\"))\n {\n fZMQconfigIN = value;\n }\n else if (option.EqualTo(\"ZMQconfigOUT\") || option.EqualTo(\"out\"))\n {\n fZMQconfigOUT = value;\n }\n else if (option.EqualTo(\"ZMQconfigMON\") || option.EqualTo(\"mon\"))\n {\n fZMQconfigMON = value;\n }\n else if (option.EqualTo(\"Verbose\"))\n {\n fVerbose = true;\n }\n else if (option.EqualTo(\"sleep\"))\n {\n fSleep = value.Atoi() * 1000;\n }\n else if (option.EqualTo(\"timeout\"))\n {\n fZMQtimeout = value.Atoi();\n }\n else\n {\n nOptions=-1;\n break;\n }\n nOptions++;\n }\n delete options; \/\/tidy up\n\n return nOptions; \n}\n\n\/\/_______________________________________________________________________________________\nint main(int argc, char** argv)\n{\n int mainReturnCode=0;\n\n \/\/process args\n TString argString = AliOptionParser::GetFullArgString(argc,argv);\n if (ProcessOptionString(argString)<=0)\n {\n printf(\"%s\",fUSAGE);\n return 1;\n }\n\n \/\/the context\n fZMQcontext = alizmq_context();\n\n \/\/init stuff\n if (InitZMQ()<0) {\n Printf(\"failed init\");\n return 1;\n }\n\n Run();\n\n \/\/destroy ZMQ sockets\n zmq_close(fZMQmon);\n zmq_close(fZMQin);\n \/\/zmq_close(fZMQout);\n zmq_ctx_destroy(fZMQcontext);\n return mainReturnCode;\n}\n\n<commit_msg>ZMQproxy: update self doc<commit_after>#include \"zmq.h\"\n#include <iostream>\n#include \"AliHLTDataTypes.h\"\n#include \"AliHLTComponent.h\"\n#include \"AliHLTMessage.h\"\n#include \"TClass.h\"\n#include \"TMap.h\"\n#include \"TPRegexp.h\"\n#include \"TObjString.h\"\n#include \"TList.h\"\n#include \"TMessage.h\"\n#include \"TRint.h\"\n#include \"TApplication.h\"\n#include <time.h>\n#include <string>\n#include <map>\n#include \"AliZMQhelpers.h\"\n\n\/\/this is meant to become a class, hence the structure with global vars etc.\n\/\/Also the code is rather flat - it is a bit of a playground to test ideas.\n\/\/TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling\n\/\/zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide\n\/\/easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...)\n\n\/\/methods\nint ProcessOptionString(TString arguments);\nint InitZMQ();\nvoid* work(void* param);\nint Run();\n\n\/\/configuration vars\nTString fZMQconfigIN = \"\";\nTString fZMQconfigOUT = \"\";\nTString fZMQconfigMON = \"\";\n\nBool_t fSendOnMerge = kTRUE;\nBool_t fResetOnSend = kFALSE;\n\n\/\/ZMQ stuff\nvoid* fZMQcontext = NULL; \/\/ze zmq context\n\nvoid* fZMQmon = NULL; \/\/the request-reply socket, here we request the merged data\nvoid* fZMQout = NULL; \/\/the monitoring socket, here we publish a copy of the data\nvoid* fZMQin = NULL; \/\/the in socket - entry point for the data to be merged.\nint inType = -1;\nint outType = -1;\nint monType = -1;\n\nint fZMQtimeout = -1;\nint fZMQmaxQueueSize = 100;\nint fSleep = 0;\nbool fVerbose = false;\n\nconst char* fUSAGE =\n \"ZMQproxy: a simple monitored ZMQ proxy\\n\"\n \"caveat: using a REQ socket causes a custom request to be sent;\\n\"\n \" only the reply is forwardedto the backend.\\n\"\n \" For request forwarding use DEALER-ROUTER.\\n\"\n \"options:\\n\"\n \" -in : socket in\\n\"\n \" -out : socket out\\n\"\n \" -mon : monitor socket\\n\"\n \" -sleep : sleep between polls (ms) (if in is a REQ socket)\\n\"\n \" -timeout : timeout for a poll (ms)\\n\"\n ;\n\nint capture(void* capture, zmq_msg_t* msg, int more = 0)\n{\n int rc = 0;\n if (!capture) return 0;\n zmq_msg_t ctrl;\n rc = zmq_msg_init(&ctrl);\n if (rc<0) return -1;\n rc = zmq_msg_copy(&ctrl, msg);\n if (rc<0) return -1;\n return zmq_msg_send(&ctrl, capture, more?ZMQ_SNDMORE:0);\n}\n\nint forward(void* from, void* to, void* mon, zmq_msg_t* msg)\n{\n int rc = 0;\n int more = 0;\n size_t moresize = sizeof(more);\n while (true)\n {\n rc = zmq_msg_recv(msg,from,0);\n if (rc<0) return -1;\n rc = zmq_getsockopt(from, ZMQ_RCVMORE, &more, &moresize);\n if (from!=mon) {\n rc = capture(mon,msg,more);\n }\n if (rc<0) return -1;\n rc = zmq_msg_send(msg,to,more?ZMQ_SNDMORE:0);\n if (rc<0) return -1;\n if (more==0) break;\n }\n if (fVerbose) printf(\"forwarded...\\n\");\n return 0;\n}\n\n\/\/_______________________________________________________________________________________\nint Run()\n{\n int rc = 0;\n\n bool interrunpted = false;\n while (!interrunpted)\n {\n \/\/send the requests first\n \/\/it is OK to block if there is no remote end\n \/\/the use case is to go from REQ->PUB for the event display\n \/\/otherwise the reconnect can take a while\n if (inType==ZMQ_REQ) {\n if (fVerbose) printf(\"requesting on %p %s\\n\",fZMQin, fZMQconfigIN.Data());\n rc = alizmq_msg_send(\"\",\"\",fZMQin,0);\n }\n if (outType==ZMQ_REQ) {\n if (fVerbose) printf(\"requesting on %s\\n\",fZMQconfigOUT.Data());\n alizmq_msg_send(\"\",\"\",fZMQout,0);\n }\n\n \/\/poll socket readiness for sending\n Int_t noutSockets=2;\n zmq_pollitem_t outSockets[] = { \n { fZMQin, 0, ZMQ_POLLOUT, 0 },\n { fZMQout, 0, ZMQ_POLLOUT, 0 },\n { fZMQmon, 0, ZMQ_POLLOUT, 0 },\n };\n rc = zmq_poll(outSockets, noutSockets, fZMQtimeout); \/\/poll outSockets\n if (rc==-1 && errno==ETERM)\n {\n \/\/this can only happen if the context was terminated, one of the inSockets are\n \/\/not valid or operation was interrupted\n Printf(\"zmq_poll (out) was interrupted! rc = %i, %s\", rc, zmq_strerror(errno));\n break;\n }\n \/\/in\n if (outSockets[0].revents & ZMQ_POLLOUT)\n {\n if (fVerbose) printf(\"socket (%p) %s signals ZMQ_POLLOUT\\n\",fZMQin, fZMQconfigIN.Data());\n }\n \/\/out\n if (outSockets[1].revents & ZMQ_POLLOUT)\n {\n if (fVerbose) printf(\"socket %p (%s) signals ZMQ_POLLOUT\\n\", fZMQout, fZMQconfigOUT.Data());\n }\n \/\/mon\n if (outSockets[2].revents & ZMQ_POLLOUT)\n {\n if (fVerbose) printf(\"socket %p (%s) signals ZMQ_POLLOUT\\n\", fZMQmon, fZMQconfigMON.Data());\n }\n \n \/\/poll incoming data\n Int_t ninSockets=3;\n zmq_pollitem_t inSockets[] = { \n { fZMQin, 0, ZMQ_POLLIN, 0 },\n { fZMQout, 0, ZMQ_POLLIN, 0 },\n { fZMQmon, 0, ZMQ_POLLIN, 0 },\n };\n\n if (fVerbose) printf(\"starting poll in\\n\");\n int pollrc = zmq_poll(inSockets, ninSockets, fZMQtimeout); \/\/poll inSockets\n if (pollrc==-1 && errno==ETERM)\n {\n \/\/this can only happen if the context was terminated, one of the inSockets are\n \/\/not valid or operation was interrupted\n Printf(\"zmq_poll (in) was interrupted! rc = %i, %s\", rc, zmq_strerror(errno));\n break;\n }\n\n zmq_msg_t msg;\n zmq_msg_init(&msg);\n \/\/in\n if (inSockets[0].revents & ZMQ_POLLIN)\n {\n if (fVerbose) printf(\"data in on %s\\n\",fZMQconfigIN.Data());\n if (outSockets[1].events & ZMQ_POLLOUT)\n {\n rc = forward(fZMQin,fZMQout,fZMQmon,&msg);\n }\n }\n \/\/out\n if (inSockets[1].revents & ZMQ_POLLIN)\n {\n if (fVerbose) printf(\"data in on %s\\n\",fZMQconfigOUT.Data());\n if (outSockets[0].events & ZMQ_POLLOUT)\n {\n rc = forward(fZMQout,fZMQin,fZMQmon,&msg);\n }\n }\n \/\/mon\n if (inSockets[2].revents & ZMQ_POLLIN)\n {\n if (fVerbose) printf(\"data in on %s\\n\",fZMQconfigMON.Data());\n if (outSockets[2].events & ZMQ_POLLOUT)\n {\n rc = forward(fZMQmon,fZMQmon,NULL,&msg);\n }\n }\n zmq_msg_close(&msg);\n \n \/\/if we time out (waiting for a response) reinit the REQ socket(s)\n if (pollrc==0)\n {\n if (inType==ZMQ_REQ) {\n if (fVerbose) printf(\"no reply from %s in %i ms, server died?\\n\",\n fZMQconfigIN.Data(), fZMQtimeout);\n rc = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), \n -1, fZMQmaxQueueSize);\n if (fVerbose) printf(\"rc of reinit %i\\n\",rc);\n }\n if (outType==ZMQ_REQ) {\n if (fVerbose) printf(\"no reply from %s in %i ms, server died?\\n\",\n fZMQconfigOUT.Data(), fZMQtimeout);\n rc = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(), \n -1, fZMQmaxQueueSize);\n if (fVerbose) printf(\"rc of reinit %i\\n\",rc);\n }\n if (monType==ZMQ_REQ) {\n if (fVerbose) printf(\"no reply from %s in %i ms, server died?\\n\",\n fZMQconfigMON.Data(), fZMQtimeout);\n rc = alizmq_socket_init(fZMQmon, fZMQcontext, fZMQconfigMON.Data(), \n -1, fZMQmaxQueueSize);\n if (fVerbose) printf(\"rc of reinit %i\\n\",rc);\n }\n }\n\n if (fSleep>0) usleep(fSleep);\n }\n\n return rc;\n}\n\n\/\/_______________________________________________________________________________________\nint InitZMQ()\n{\n \/\/init or reinit stuff\n int rc = 0;\n inType = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, fZMQmaxQueueSize);\n outType = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(), -1, fZMQmaxQueueSize);\n monType = alizmq_socket_init(fZMQmon, fZMQcontext, fZMQconfigMON.Data(), -1, fZMQmaxQueueSize);\n printf(\"socket init (in,out,mon): %i, %i, %i, %s, %s, %s\\n\",inType,outType,monType,alizmq_socket_name(inType),alizmq_socket_name(outType),alizmq_socket_name(monType));\n return rc;\n}\n\n\/\/______________________________________________________________________________\nint ProcessOptionString(TString arguments)\n{\n \/\/process passed options\n aliStringVec* options = AliOptionParser::TokenizeOptionString(arguments);\n int nOptions = 0;\n for (aliStringVec::iterator i=options->begin(); i!=options->end(); ++i)\n {\n const TString& option = i->first;\n const TString& value = i->second;\n if (option.EqualTo(\"ZMQconfigIN\") || option.EqualTo(\"in\"))\n {\n fZMQconfigIN = value;\n }\n else if (option.EqualTo(\"ZMQconfigOUT\") || option.EqualTo(\"out\"))\n {\n fZMQconfigOUT = value;\n }\n else if (option.EqualTo(\"ZMQconfigMON\") || option.EqualTo(\"mon\"))\n {\n fZMQconfigMON = value;\n }\n else if (option.EqualTo(\"Verbose\"))\n {\n fVerbose = true;\n }\n else if (option.EqualTo(\"sleep\"))\n {\n fSleep = value.Atoi() * 1000;\n }\n else if (option.EqualTo(\"timeout\"))\n {\n fZMQtimeout = value.Atoi();\n }\n else\n {\n nOptions=-1;\n break;\n }\n nOptions++;\n }\n delete options; \/\/tidy up\n\n return nOptions; \n}\n\n\/\/_______________________________________________________________________________________\nint main(int argc, char** argv)\n{\n int mainReturnCode=0;\n\n \/\/process args\n TString argString = AliOptionParser::GetFullArgString(argc,argv);\n if (ProcessOptionString(argString)<=0)\n {\n printf(\"%s\",fUSAGE);\n return 1;\n }\n\n \/\/the context\n fZMQcontext = alizmq_context();\n\n \/\/init stuff\n if (InitZMQ()<0) {\n Printf(\"failed init\");\n return 1;\n }\n\n Run();\n\n \/\/destroy ZMQ sockets\n zmq_close(fZMQmon);\n zmq_close(fZMQin);\n \/\/zmq_close(fZMQout);\n zmq_ctx_destroy(fZMQcontext);\n return mainReturnCode;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ _____ _ _\n\/\/ |_ _|_ _ __| |_ __ ___ | | ___\n\/\/ | |\/ _` |\/ _` | '_ \\ \/ _ \\| |\/ _ \\\n\/\/ | | (_| | (_| | |_) | (_) | | __\/\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 ofconditions and the following disclaimer.\n\/\/\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 materialsprovided with the\n\/\/ distribution.\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 HOLDER 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#include \"..\/common\/harness.hh\"\n#include \"lexer.hh\"\n\nTADPOLE_TEST(TadpoleLexer) {\n using TK = tadpole::TokenKind;\n#define TESTEQ(k) TADPOLE_CHECK_EQ(lex.next_token().kind(), k)\n#define DUMPLEX() do {\\\n for (;;) {\\\n auto t = lex.next_token();\\\n std::fprintf(stdout, \"%-24s | %-32s | %d\\n\",\\\n tadpole::get_kind_name(t.kind()),\\\n t.as_cstring(),\\\n t.lineno());\\\n if (t.kind() == TK::TK_EOF)\\\n break;\\\n }\\\n } while (false)\n\n {\n std::string s =\n \"print(\\\"Welcome to Tadpole !!!\\\");\\nvar v = 34 * 56 \/ 22.45 + (88.76 - 27.4);\";\n tadpole::Lexer lex(s);\n DUMPLEX();\n }\n\n {\n std::string s = \"var a = 56;\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::KW_VAR);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_EQ);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_EOF);\n }\n\n {\n std::string s = \"print(\\\"23 + 45 =\\\", 23 + 45);\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_STRING);\n TESTEQ(TK::TK_COMMA);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_PLUS);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_EOF);\n }\n\n#undef DUMPLEX\n#undef TESTEQ\n}\n<commit_msg>:white_check_mark: test(lexer): updated the test for lexer<commit_after>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ _____ _ _\n\/\/ |_ _|_ _ __| |_ __ ___ | | ___\n\/\/ | |\/ _` |\/ _` | '_ \\ \/ _ \\| |\/ _ \\\n\/\/ | | (_| | (_| | |_) | (_) | | __\/\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 ofconditions and the following disclaimer.\n\/\/\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 materialsprovided with the\n\/\/ distribution.\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 HOLDER 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#include \"..\/common\/harness.hh\"\n#include \"lexer.hh\"\n\nTADPOLE_TEST(TadpoleLexer) {\n using TK = tadpole::TokenKind;\n#define TESTEQ(k) TADPOLE_CHECK_EQ(lex.next_token().kind(), k)\n#define DUMPLEX() do {\\\n for (;;) {\\\n auto t = lex.next_token();\\\n std::fprintf(stdout, \"%-24s | %-32s | %d\\n\",\\\n tadpole::get_kind_name(t.kind()),\\\n t.as_cstring(),\\\n t.lineno());\\\n if (t.kind() == TK::TK_EOF)\\\n break;\\\n }\\\n } while (false)\n\n {\n std::string s =\n \"print(\\\"Welcome to Tadpole !!!\\\");\\nvar v = 34 * 56 \/ 22.45 + (88.76 - 27.4);\";\n tadpole::Lexer lex(s);\n DUMPLEX();\n }\n\n {\n std::string s = \"var a = 56;\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::KW_VAR);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_EQ);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_EOF);\n }\n\n {\n std::string s = \"print(\\\"23 + 45 =\\\", 23 + 45);\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_STRING);\n TESTEQ(TK::TK_COMMA);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_PLUS);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_EOF);\n }\n\n {\n std::string s = \"fn show_msg(msg) { print(msg); }\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::KW_FN);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_LBRACE);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_RBRACE);\n TESTEQ(TK::TK_EOF);\n }\n\n#undef DUMPLEX\n#undef TESTEQ\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ This class provides access to ITS SDD digits in raw data.\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliITSRawStreamSDD.h\"\n#include \"AliRawReader.h\"\n#include \"AliLog.h\"\n\nClassImp(AliITSRawStreamSDD)\n \nconst UInt_t AliITSRawStreamSDD::fgkCodeLength[8] = {8, 18, 2, 3, 4, 5, 6, 7};\n\n\/\/______________________________________________________________________\nAliITSRawStreamSDD::AliITSRawStreamSDD(AliRawReader* rawReader) :\n AliITSRawStream(rawReader),\nfDDLModuleMap(0),\nfData(0),\nfEventId(0),\nfCarlosId(-1),\nfChannel(0),\nfJitter(0),\nfDDL(0),\nfEndWords(0),\nfResetSkip(0)\n{\n\/\/ create an object to read ITS SDD raw digits\n fDDLModuleMap=new AliITSDDLModuleMapSDD();\n fDDLModuleMap->SetDefaultMap();\n Reset();\n for(Int_t im=0;im<kSDDModules;im++){\n fLowThresholdArray[im][0]=0;\n fLowThresholdArray[im][1]=0;\n }\n for(Int_t i=0;i<kFifoWords;i++) fNfifo[i]=0;\n for(Int_t i=0;i<kDDLsNumber;i++) fSkip[i]=0;\n fRawReader->Reset();\n fRawReader->Select(\"ITSSDD\");\n\n for(Short_t i=0; i<kCarlosWords; i++) fICarlosWord[i]=0x30000000 + i; \/\/ 805306368+i;\n for(Short_t i=0; i<kFifoWords; i++) fIFifoWord[i]=0x30000010 + i; \/\/ 805306384+i;\n}\n\n\/\/______________________________________________________________________\nAliITSRawStreamSDD::AliITSRawStreamSDD(const AliITSRawStreamSDD& rs) :\nAliITSRawStream(rs.fRawReader),\nfDDLModuleMap(rs.fDDLModuleMap),\nfData(0),\nfEventId(0),\nfCarlosId(-1),\nfChannel(0),\nfJitter(0),\nfDDL(0),\nfEndWords(0),\nfResetSkip(0)\n{\n \/\/ copy constructor\n AliError(\"Copy constructor should not be used.\");\n}\n\/\/__________________________________________________________________________\nAliITSRawStreamSDD& AliITSRawStreamSDD::operator=(const AliITSRawStreamSDD& rs) {\n \/\/ assignment operator\n if (this!=&rs) {}\n AliError(\"Assignment opertator should not be used.\");\n return *this;\n}\n\n\/\/______________________________________________________________________\nAliITSRawStreamSDD::~AliITSRawStreamSDD(){\n if(fDDLModuleMap) delete fDDLModuleMap;\n}\n\/\/______________________________________________________________________\nUInt_t AliITSRawStreamSDD::ReadBits()\n{\n\/\/ read bits from the given channel\n UInt_t result = (fChannelData[fCarlosId][fChannel] & ((1<<fReadBits[fCarlosId][fChannel]) - 1));\n fChannelData[fCarlosId][fChannel] >>= fReadBits[fCarlosId][fChannel]; \n fLastBit[fCarlosId][fChannel] -= fReadBits[fCarlosId][fChannel];\n return result;\n}\n\n\/\/______________________________________________________________________\nInt_t AliITSRawStreamSDD::DecompAmbra(Int_t value) const\n{\n \/\/ AMBRA decompression (from 8 to 10 bit)\n \n if ((value & 0x80) == 0) {\n return value & 0x7f;\n } else if ((value & 0x40) == 0) {\n return 0x081 + ((value & 0x3f) << 1);\n } else if ((value & 0x20) == 0) {\n return 0x104 + ((value & 0x1f) << 3);\n } else {\n return 0x208 + ((value & 0x1f) << 4);\n }\n \n}\n\n\/\/______________________________________________________________________\nBool_t AliITSRawStreamSDD::Next()\n{\n\/\/ read the next raw digit\n\/\/ returns kFALSE if there is no digit left\n\/\/ returns kTRUE and fCompletedModule=kFALSE when a digit is found\n\/\/ returns kTRUE and fCompletedModule=kTRUE when a module is completed (=3x3FFFFFFF footer words)\n\n fPrevModuleID = fModuleID;\n fDDL=fRawReader->GetDDLID();\n fCompletedModule=kFALSE;\n\n while (kTRUE) {\n if(fResetSkip==0){\n Bool_t kSkip = SkipHeaderWord();\n fResetSkip=1;\n if(!kSkip) return kSkip;\n }\n \n if ((fChannel < 0) || (fCarlosId < 0) || (fChannel >= 2) || (fCarlosId >= kModulesPerDDL) || (fLastBit[fCarlosId][fChannel] < fReadBits[fCarlosId][fChannel]) ) {\n if (!fRawReader->ReadNextInt(fData)) return kFALSE; \/\/ read next word\n Int_t ddln = fRawReader->GetDDLID();\n if(ddln!=fDDL) { \n\tReset();\n\tfDDL=fRawReader->GetDDLID();\n }\n if(ddln < 0 || ddln > (kDDLsNumber-1)) ddln = 0;\n\n fChannel = -1;\n if((fData >> 16) == 0x7F00){ \/\/ jitter word\n\tfResetSkip=0;\n\tfEndWords=0;\n\tcontinue;\n }\n\n UInt_t nData28= fData >> 28;\n UInt_t nData30= fData >> 30;\n\n\n if (nData28== 0x02) { \/\/ header\n\tfEventId = (fData >> 3) & 0x07FF; \n } else if (nData28== 0x04) {\n\t\/\/ JTAG word -- do nothing\n } else if (nData28== 0x03) { \/\/ Carlos and FIFO words or Footers\n\tif(fData>=fICarlosWord[0]&&fData<=fICarlosWord[11]) { \/\/ Carlos Word\n\t if(fEndWords==12) continue; \/\/ out of event\n\t fCarlosId = fData-fICarlosWord[0];\n\t Int_t iFifoIdx = fCarlosId\/3;\n\t fNfifo[iFifoIdx] = fCarlosId;\n\t} else if (fData>=fIFifoWord[0]&&fData<=fIFifoWord[3]){ \/\/ FIFO word\n\t if(fEndWords==12) continue; \/\/ out of event\n\t fCarlosId = fNfifo[fData-fIFifoWord[0]];\t \n\t} else if(fData==0x3FFFFFFF){ \/\/ Carlos footer\n\t if(fCarlosId>=0 && fCarlosId<kModulesPerDDL){\n\t fICountFoot[fCarlosId]++; \/\/ stop before the last word (last word=jitter)\n\t if(fICountFoot[fCarlosId]==3){\n\t fCompletedModule=kTRUE;\n\t \/\/\t printf(\"Completed module %d DDL %d\\n\",fCarlosId,ddln);\n\t return kTRUE;\n\t }\n\t }\n\t} else if(fData==0x3F1F1F1F){ \/\/ CarlosRX footer\n\t fEndWords++;\n\t if(fEndWords<=12) continue;\n\t}else{\n\t fRawReader->AddMajorErrorLog(kDataError,\"Too many footers\");\n\t AliWarning(Form(\"invalid data: too many footers\\n\", fData));\n\t return kFALSE;\t \n\t}\n } else if (nData30 == 0x02 || nData30 == 0x03) {\n\tfChannel = nData30-2;\n\tif(fCarlosId>=0 && fChannel>=0 && fCarlosId <kModulesPerDDL && fChannel<2){\n\t fChannelData[fCarlosId][fChannel] += \n\t (ULong64_t(fData & 0x3FFFFFFF) << fLastBit[fCarlosId][fChannel]);\n\t fLastBit[fCarlosId][fChannel] += 30;\n\t}\n } else { \/\/ unknown data format\n\tfRawReader->AddMajorErrorLog(kDataFormatErr,Form(\"Invalid data %8.8x\",fData));\n\tAliWarning(Form(\"invalid data: %8.8x\\n\", fData));\n\treturn kFALSE;\n }\n \n if(fCarlosId>=0 && fCarlosId <kModulesPerDDL){\n\t fModuleID = GetModuleNumber(ddln,fCarlosId);\n }\n } else { \/\/ decode data\n if (fReadCode[fCarlosId][fChannel]) {\/\/ read the next code word\n\tfChannelCode[fCarlosId][fChannel] = ReadBits();\n\tfReadCode[fCarlosId][fChannel] = kFALSE;\n\tfReadBits[fCarlosId][fChannel] = fgkCodeLength[fChannelCode[fCarlosId][fChannel]];\n } else { \/\/ read the next data word\n\tUInt_t data = ReadBits();\n\tfReadCode[fCarlosId][fChannel] = kTRUE;\n\tfReadBits[fCarlosId][fChannel] = 3;\n\tif (fChannelCode[fCarlosId][fChannel] == 0) { \/\/ set the time bin\t \n\t fTimeBin[fCarlosId][fChannel] = data;\n\t} else if (fChannelCode[fCarlosId][fChannel] == 1) { \/\/ next anode\n\t fTimeBin[fCarlosId][fChannel] = 0;\n\t fAnode[fCarlosId][fChannel]++;\n\t} else { \/\/ ADC signal data\n\t fSignal = DecompAmbra(data + (1 << fChannelCode[fCarlosId][fChannel]) + fLowThresholdArray[fModuleID-kSPDModules][fChannel]);\n\t fCoord1 = fAnode[fCarlosId][fChannel];\n\t fCoord2 = fTimeBin[fCarlosId][fChannel];\n\t fTimeBin[fCarlosId][fChannel]++;\n\t \/\/printf(\"Data read, Module=%d , Anode=%d , Time=%d , Charge=%d\\n\",fModuleID,fCoord1,fCoord2,fSignal);\n\t return kTRUE;\n\t}\n }\n }\n }\n return kFALSE;\n}\n\n\/\/______________________________________________________________________\nvoid AliITSRawStreamSDD::Reset(){\n\n \/\/reset data member for a new ddl\n for(Int_t i=0;i<2;i++){\n for(Int_t ic=0;ic<kModulesPerDDL;ic++){\n fChannelData[ic][i]=0;\n fLastBit[ic][i]=0;\n fChannelCode[ic][i]=0;\n fReadCode[ic][i]=kTRUE;\n fReadBits[ic][i]=3;\n fTimeBin[ic][i]=0;\n fAnode[ic][i]=0; \n }\n fLowThreshold[i]=0;\n }\n for(Int_t i=0;i<kModulesPerDDL;i++) fICountFoot[i]=0;\n}\n\n\/\/______________________________________________________________________\nBool_t AliITSRawStreamSDD::SkipHeaderWord(){\n \/\/ skip the 1 DDL header word = 0xffffffff\n while (kTRUE) {\n if (!fRawReader->ReadNextInt(fData)) return kFALSE; \n if ((fData >> 30) == 0x01) continue; \/\/ JTAG word\n if(fData==0xFFFFFFFF) return kTRUE;\n }\n}\n\n<commit_msg>Modifs to increase the speed of the SDD raw streamer (F.Prino)<commit_after>\/**************************************************************************\n * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ This class provides access to ITS SDD digits in raw data.\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliITSRawStreamSDD.h\"\n#include \"AliRawReader.h\"\n#include \"AliLog.h\"\n\nClassImp(AliITSRawStreamSDD)\n \nconst UInt_t AliITSRawStreamSDD::fgkCodeLength[8] = {8, 18, 2, 3, 4, 5, 6, 7};\n\n\/\/______________________________________________________________________\nAliITSRawStreamSDD::AliITSRawStreamSDD(AliRawReader* rawReader) :\n AliITSRawStream(rawReader),\nfDDLModuleMap(0),\nfData(0),\nfEventId(0),\nfCarlosId(-1),\nfChannel(0),\nfJitter(0),\nfDDL(0),\nfEndWords(0),\nfResetSkip(0)\n{\n\/\/ create an object to read ITS SDD raw digits\n fDDLModuleMap=new AliITSDDLModuleMapSDD();\n fDDLModuleMap->SetDefaultMap();\n Reset();\n for(Int_t im=0;im<kSDDModules;im++){\n fLowThresholdArray[im][0]=0;\n fLowThresholdArray[im][1]=0;\n }\n for(Int_t i=0;i<kFifoWords;i++) fNfifo[i]=0;\n for(Int_t i=0;i<kDDLsNumber;i++) fSkip[i]=0;\n fRawReader->Reset();\n fRawReader->Select(\"ITSSDD\");\n\n for(Short_t i=0; i<kCarlosWords; i++) fICarlosWord[i]=0x30000000 + i; \/\/ 805306368+i;\n for(Short_t i=0; i<kFifoWords; i++) fIFifoWord[i]=0x30000010 + i; \/\/ 805306384+i;\n}\n\n\/\/______________________________________________________________________\nAliITSRawStreamSDD::AliITSRawStreamSDD(const AliITSRawStreamSDD& rs) :\nAliITSRawStream(rs.fRawReader),\nfDDLModuleMap(rs.fDDLModuleMap),\nfData(0),\nfEventId(0),\nfCarlosId(-1),\nfChannel(0),\nfJitter(0),\nfDDL(0),\nfEndWords(0),\nfResetSkip(0)\n{\n \/\/ copy constructor\n AliError(\"Copy constructor should not be used.\");\n}\n\/\/__________________________________________________________________________\nAliITSRawStreamSDD& AliITSRawStreamSDD::operator=(const AliITSRawStreamSDD& rs) {\n \/\/ assignment operator\n if (this!=&rs) {}\n AliError(\"Assignment opertator should not be used.\");\n return *this;\n}\n\n\/\/______________________________________________________________________\nAliITSRawStreamSDD::~AliITSRawStreamSDD(){\n if(fDDLModuleMap) delete fDDLModuleMap;\n}\n\/\/______________________________________________________________________\nUInt_t AliITSRawStreamSDD::ReadBits()\n{\n\/\/ read bits from the given channel\n UInt_t result = (fChannelData[fCarlosId][fChannel] & ((1<<fReadBits[fCarlosId][fChannel]) - 1));\n fChannelData[fCarlosId][fChannel] >>= fReadBits[fCarlosId][fChannel]; \n fLastBit[fCarlosId][fChannel] -= fReadBits[fCarlosId][fChannel];\n return result;\n}\n\n\/\/______________________________________________________________________\nInt_t AliITSRawStreamSDD::DecompAmbra(Int_t value) const\n{\n \/\/ AMBRA decompression (from 8 to 10 bit)\n \n if ((value & 0x80) == 0) {\n return value & 0x7f;\n } else if ((value & 0x40) == 0) {\n return 0x081 + ((value & 0x3f) << 1);\n } else if ((value & 0x20) == 0) {\n return 0x104 + ((value & 0x1f) << 3);\n } else {\n return 0x208 + ((value & 0x1f) << 4);\n }\n \n}\n\n\/\/______________________________________________________________________\nBool_t AliITSRawStreamSDD::Next()\n{\n\/\/ read the next raw digit\n\/\/ returns kFALSE if there is no digit left\n\/\/ returns kTRUE and fCompletedModule=kFALSE when a digit is found\n\/\/ returns kTRUE and fCompletedModule=kTRUE when a module is completed (=3x3FFFFFFF footer words)\n\n fPrevModuleID = fModuleID;\n fDDL=fRawReader->GetDDLID();\n fCompletedModule=kFALSE;\n\n while (kTRUE) {\n if(fResetSkip==0){\n Bool_t kSkip = SkipHeaderWord();\n fResetSkip=1;\n if(!kSkip) return kSkip;\n }\n \n if ((fChannel < 0) || (fCarlosId < 0) || (fChannel >= 2) || (fCarlosId >= kModulesPerDDL) || (fLastBit[fCarlosId][fChannel] < fReadBits[fCarlosId][fChannel]) ) {\n if (!fRawReader->ReadNextInt(fData)) return kFALSE; \/\/ read next word\n Int_t ddln = fRawReader->GetDDLID();\n if(ddln!=fDDL) { \n\tReset();\n\tfDDL=fRawReader->GetDDLID();\n }\n\n fChannel = -1;\n if((fData >> 16) == 0x7F00){ \/\/ jitter word\n\tfResetSkip=0;\n\tfEndWords=0;\n\tcontinue;\n }\n\n UInt_t nData28= fData >> 28;\n UInt_t nData30= fData >> 30;\n\n\n if (nData28== 0x02) { \/\/ header\n\tfEventId = (fData >> 3) & 0x07FF; \n } else if (nData28== 0x04) {\n\t\/\/ JTAG word -- do nothing\n } else if (nData28== 0x03) { \/\/ Carlos and FIFO words or Footers\n\tif(fData>=fICarlosWord[0]&&fData<=fICarlosWord[11]) { \/\/ Carlos Word\n\t if(fEndWords==12) continue; \/\/ out of event\n\t fCarlosId = fData-fICarlosWord[0];\n\t Int_t iFifoIdx = fCarlosId\/3;\n\t fNfifo[iFifoIdx] = fCarlosId;\n\t} else if (fData>=fIFifoWord[0]&&fData<=fIFifoWord[3]){ \/\/ FIFO word\n\t if(fEndWords==12) continue; \/\/ out of event\n\t fCarlosId = fNfifo[fData-fIFifoWord[0]];\t \n\t} else if(fData==0x3FFFFFFF){ \/\/ Carlos footer\n\t fICountFoot[fCarlosId]++; \/\/ stop before the last word (last word=jitter)\n\t if(fICountFoot[fCarlosId]==3){\n\t fCompletedModule=kTRUE;\n\t \/\/\t printf(\"Completed module %d DDL %d\\n\",fCarlosId,ddln);\n\t return kTRUE;\n\t }\n\t} else if(fData==0x3F1F1F1F){ \/\/ CarlosRX footer\n\t fEndWords++;\n\t if(fEndWords<=12) continue;\n\t}else{\n\t fRawReader->AddMajorErrorLog(kDataError,\"Too many footers\");\n\t AliWarning(Form(\"invalid data: too many footers\\n\", fData));\n\t return kFALSE;\t \n\t}\n } else if (nData30 == 0x02 || nData30 == 0x03) {\n\tfChannel = nData30-2;\n\tfChannelData[fCarlosId][fChannel] += \n\t (ULong64_t(fData & 0x3FFFFFFF) << fLastBit[fCarlosId][fChannel]);\n\tfLastBit[fCarlosId][fChannel] += 30;\n } else { \/\/ unknown data format\n\tfRawReader->AddMajorErrorLog(kDataFormatErr,Form(\"Invalid data %8.8x\",fData));\n\tAliWarning(Form(\"invalid data: %8.8x\\n\", fData));\n\treturn kFALSE;\n }\n \n if(fCarlosId>=0 && fCarlosId <kModulesPerDDL){\n\t fModuleID = GetModuleNumber(ddln,fCarlosId);\n }\n } else { \/\/ decode data\n if (fReadCode[fCarlosId][fChannel]) {\/\/ read the next code word\n\tfChannelCode[fCarlosId][fChannel] = ReadBits();\n\tfReadCode[fCarlosId][fChannel] = kFALSE;\n\tfReadBits[fCarlosId][fChannel] = fgkCodeLength[fChannelCode[fCarlosId][fChannel]];\n } else { \/\/ read the next data word\n\tUInt_t data = ReadBits();\n\tfReadCode[fCarlosId][fChannel] = kTRUE;\n\tfReadBits[fCarlosId][fChannel] = 3;\n\tif (fChannelCode[fCarlosId][fChannel] == 0) { \/\/ set the time bin\t \n\t fTimeBin[fCarlosId][fChannel] = data;\n\t} else if (fChannelCode[fCarlosId][fChannel] == 1) { \/\/ next anode\n\t fTimeBin[fCarlosId][fChannel] = 0;\n\t fAnode[fCarlosId][fChannel]++;\n\t} else { \/\/ ADC signal data\n\t fSignal = DecompAmbra(data + (1 << fChannelCode[fCarlosId][fChannel]) + fLowThresholdArray[fModuleID-kSPDModules][fChannel]);\n\t fCoord1 = fAnode[fCarlosId][fChannel];\n\t fCoord2 = fTimeBin[fCarlosId][fChannel];\n\t fTimeBin[fCarlosId][fChannel]++;\n\t \/\/printf(\"Data read, Module=%d , Anode=%d , Time=%d , Charge=%d\\n\",fModuleID,fCoord1,fCoord2,fSignal);\n\t return kTRUE;\n\t}\n }\n }\n }\n return kFALSE;\n}\n\n\/\/______________________________________________________________________\nvoid AliITSRawStreamSDD::Reset(){\n\n \/\/reset data member for a new ddl\n for(Int_t i=0;i<2;i++){\n for(Int_t ic=0;ic<kModulesPerDDL;ic++){\n fChannelData[ic][i]=0;\n fLastBit[ic][i]=0;\n fChannelCode[ic][i]=0;\n fReadCode[ic][i]=kTRUE;\n fReadBits[ic][i]=3;\n fTimeBin[ic][i]=0;\n fAnode[ic][i]=0; \n }\n fLowThreshold[i]=0;\n }\n for(Int_t i=0;i<kModulesPerDDL;i++) fICountFoot[i]=0;\n}\n\n\/\/______________________________________________________________________\nBool_t AliITSRawStreamSDD::SkipHeaderWord(){\n \/\/ skip the 1 DDL header word = 0xffffffff\n while (kTRUE) {\n if (!fRawReader->ReadNextInt(fData)) return kFALSE; \n if ((fData >> 30) == 0x01) continue; \/\/ JTAG word\n if(fData==0xFFFFFFFF) return kTRUE;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"rcppbridge.h\"\n\n#include <boost\/foreach.hpp>\n#include \"..\/JASP-Common\/base64.h\"\n#include <iomanip>\n\nusing namespace std;\n\n\nRcppBridge* RcppBridge::_staticRef;\n\nRcppBridge::RcppBridge()\n{\n\t_staticRef = this;\n\n\t_rInside[\".read.dataset.native\"] = Rcpp::InternalFunction(&RcppBridge::readDataSetStatic);\n\t_rInside[\".read.dataset.header.native\"] = Rcpp::InternalFunction(&RcppBridge::readDataSetHeaderStatic);\n\t_rInside[\".callback.native\"] = Rcpp::InternalFunction(&RcppBridge::callbackStatic);\n\n\t_rInside[\"jasp.analyses\"] = Rcpp::List();\n\t_rInside.parseEvalQNT(\"suppressPackageStartupMessages(library(\\\"RJSONIO\\\"))\");\n\t_rInside.parseEvalQNT(\"suppressPackageStartupMessages(library(\\\"JASP\\\"))\");\n}\n\nvoid RcppBridge::setDataSet(DataSet* dataSet)\n{\n\t_dataSet = dataSet;\n}\n\nJson::Value RcppBridge::init(const string &name, const Json::Value &options)\n{\n\tSEXP results;\n\n\t_rInside[\"name\"] = name;\n\t_rInside[\"options.as.json.string\"] = options.toStyledString();\n\t_rInside.parseEval(\"init(name=name, options.as.json.string=options.as.json.string)\", results);\n\n\tstring resultsAsString = Rcpp::as<string>(results);\n\n\tJson::Reader r;\n\tJson::Value json;\n\tr.parse(resultsAsString, json);\n\n\treturn json;\n}\n\nJson::Value RcppBridge::run(const string &name, const Json::Value &options, boost::function<int (Json::Value)> callback)\n{\n\tSEXP results;\n\n\t_callback = callback;\n\n\t_rInside[\"name\"] = name;\n\t_rInside[\"options.as.json.string\"] = options.toStyledString();\n\t_rInside.parseEval(\"run(name=name, options.as.json.string=options.as.json.string)\", results);\n\n\t_callback = NULL;\n\n\tstring resultsAsString = Rcpp::as<string>(results);\n\n\tJson::Reader r;\n\tJson::Value json;\n\tr.parse(resultsAsString, json);\n\n\treturn json;\n}\n\nRcpp::DataFrame RcppBridge::readDataSet(const std::map<std::string, Column::ColumnType> &columns)\n{\n\tRcpp::List list(columns.size());\n\tRcpp::CharacterVector columnNames;\n\n\tint colNo = 0;\n\n\ttypedef pair<const string, Column::ColumnType> ColumnInfo;\n\n\tBOOST_FOREACH(const ColumnInfo &columnInfo, columns)\n\t{\n\t\t(void)columns;\n\t\tstring dot = \".\";\n\n\t\tstring columnName = columnInfo.first;\n\n\t\tstring base64 = Base64::encode(dot, columnName);\n\t\tcolumnNames.push_back(base64);\n\n\t\tColumn &column = _dataSet->columns().get(columnName);\n\t\tColumn::ColumnType columnType = column.columnType();\n\n\t\tColumn::ColumnType requestedType = columnInfo.second;\n\t\tif (requestedType == Column::ColumnTypeUnknown)\n\t\t\trequestedType = columnType;\n\n\t\tint rowCount = column.rowCount();\n\t\tint rowNo = 0;\n\n\t\tif (requestedType == Column::ColumnTypeScale)\n\t\t{\n\t\t\tif (columnType == Column::ColumnTypeScale)\n\t\t\t{\n\t\t\t\tRcpp::NumericVector v(rowCount);\n\n\t\t\t\tBOOST_FOREACH(double value, column.AsDoubles)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tv[rowNo++] = value;\n\t\t\t\t}\n\n\t\t\t\tlist[colNo++] = v;\n\t\t\t}\n\t\t\telse if (columnType == Column::ColumnTypeOrdinal || columnType == Column::ColumnTypeNominal)\n\t\t\t{\n\t\t\t\tRcpp::IntegerVector v(rowCount);\n\n\t\t\t\tBOOST_FOREACH(int value, column.AsInts)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tv[rowNo++] = column.actualFromRaw(value);\n\t\t\t\t}\n\n\t\t\t\tlist[colNo++] = v;\n\t\t\t}\n\t\t\telse \/\/ columnType == Column::ColumnTypeNominalText\n\t\t\t{\n\t\t\t\tRcpp::IntegerVector v(rowCount);\n\n\t\t\t\tBOOST_FOREACH(int value, column.AsInts)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tv[rowNo++] = column.actualFromRaw(value);\n\t\t\t\t}\n\n\t\t\t\tmakeFactor(v, column.labels());\n\n\t\t\t\tlist[colNo++] = v;\n\t\t\t}\n\t\t}\n\t\telse \/\/ if (requestedType != Column::ColumnTypeScale)\n\t\t{\n\t\t\tbool ordinal = (requestedType == Column::ColumnTypeOrdinal);\n\n\t\t\tRcpp::IntegerVector v(rowCount);\n\n\t\t\tif (columnType != Column::ColumnTypeScale)\n\t\t\t{\n\t\t\t\tBOOST_FOREACH(int value, column.AsInts)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tv[rowNo++] = value + 1;\n\t\t\t\t}\n\n\t\t\t\tmakeFactor(v, column.labels(), ordinal);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ scale to nominal or ordinal (doesn't really make sense, but we have to do something)\n\n\t\t\t\tset<int> uniqueValues;\n\n\t\t\t\tBOOST_FOREACH(double value, column.AsDoubles)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tint intValue = (int)(value * 1000);\n\t\t\t\t\tuniqueValues.insert(intValue);\n\t\t\t\t}\n\n\t\t\t\tint index = 0;\n\t\t\t\tmap<int, int> valueToIndex;\n\t\t\t\tvector<string> labels;\n\n\t\t\t\tBOOST_FOREACH(int value, uniqueValues)\n\t\t\t\t{\n\t\t\t\t\t(void)uniqueValues;\n\t\t\t\t\tvalueToIndex[value] = index;\n\n\t\t\t\t\tstringstream ss;\n\t\t\t\t\tss << ((double)value \/ 1000);\n\t\t\t\t\tlabels.push_back(ss.str());\n\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\n\t\t\t\tBOOST_FOREACH(double value, column.AsDoubles)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\n\t\t\t\t\tif (isnan(value))\n\t\t\t\t\t\tv[rowNo++] = INT_MIN;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tv[rowNo++] = valueToIndex[(int)(value * 1000)] + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmakeFactor(v, labels, ordinal);\n\t\t\t}\n\n\t\t\tlist[colNo++] = v;\n\t\t}\n\t}\n\n\tlist.attr(\"names\") = columnNames;\n\n\tRcpp::DataFrame dataFrame = Rcpp::DataFrame(list);\n\n\treturn dataFrame;\n}\n\nRcpp::DataFrame RcppBridge::readDataSetHeader(const std::map<string, Column::ColumnType> &columns)\n{\n\tRcpp::List list(columns.size());\n\tRcpp::CharacterVector columnNames;\n\n\tint colNo = 0;\n\n\ttypedef pair<const string, Column::ColumnType> ColumnInfo;\n\n\tBOOST_FOREACH(const ColumnInfo &columnInfo, columns)\n\t{\n\t\t(void)columns;\n\t\tstring dot = \".\";\n\n\t\tstring columnName = columnInfo.first;\n\n\t\tstring base64 = Base64::encode(dot, columnName);\n\t\tcolumnNames.push_back(base64);\n\n\t\tColumn &column = _dataSet->columns().get(columnName);\n\t\tColumn::ColumnType columnType = column.columnType();\n\n\t\tColumn::ColumnType requestedType = columnInfo.second;\n\t\tif (requestedType == Column::ColumnTypeUnknown)\n\t\t\trequestedType = columnType;\n\n\t\tif (requestedType == Column::ColumnTypeScale)\n\t\t{\n\t\t\tif (columnType == Column::ColumnTypeScale)\n\t\t\t{\n\t\t\t\tlist[colNo++] = Rcpp::NumericVector(0);\n\t\t\t}\n\t\t\telse if (columnType == Column::ColumnTypeOrdinal || columnType == Column::ColumnTypeNominal)\n\t\t\t{\n\t\t\t\tlist[colNo++] = Rcpp::IntegerVector(0);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tRcpp::IntegerVector v(0);\n\t\t\t\tmakeFactor(v, column.labels());\n\t\t\t\tlist[colNo++] = v;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbool ordinal = (requestedType == Column::ColumnTypeOrdinal);\n\n\t\t\tRcpp::IntegerVector v(0);\n\t\t\tmakeFactor(v, column.labels(), ordinal);\n\n\t\t\tlist[colNo++] = v;\n\t\t}\n\t}\n\n\tlist.attr(\"names\") = columnNames;\n\n\tRcpp::DataFrame dataFrame = Rcpp::DataFrame(list);\n\n\treturn dataFrame;\n}\n\nvoid RcppBridge::makeFactor(Rcpp::IntegerVector &v, const Labels &levels, bool ordinal)\n{\n\tRcpp::CharacterVector labels;\n\n\tfor (int i = 0; i < levels.size(); i++)\n\t\tlabels.push_back(levels.at(i).text());\n\n\tv.attr(\"levels\") = labels;\n\n\tvector<string> cla55;\n\tif (ordinal)\n\t\tcla55.push_back(\"ordered\");\n\tcla55.push_back(\"factor\");\n\n\tv.attr(\"class\") = cla55;\n}\n\nvoid RcppBridge::makeFactor(Rcpp::IntegerVector &v, const std::vector<string> &levels, bool ordinal)\n{\n\tv.attr(\"levels\") = levels;\n\n\tvector<string> cla55;\n\tif (ordinal)\n\t\tcla55.push_back(\"ordered\");\n\tcla55.push_back(\"factor\");\n\n\tv.attr(\"class\") = cla55;\n}\n\n\nint RcppBridge::callback(SEXP results)\n{\n\tstring jsonString = Rcpp::as<string>(results);\n\n\tJson::Reader r;\n\tJson::Value json;\n\tr.parse(jsonString, json);\n\n\treturn _callback(json);\n}\n\nRcpp::DataFrame RcppBridge::readDataSetStatic(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns)\n{\t\n\tmap<string, Column::ColumnType> columnsRequested = marshallSEXPs(columns, columnsAsNumeric, columnsAsOrdinal, columnsAsNominal, allColumns);\n\treturn _staticRef->readDataSet(columnsRequested);\n}\n\nRcpp::DataFrame RcppBridge::readDataSetHeaderStatic(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns)\n{\n\tmap<string, Column::ColumnType> columnsRequested = marshallSEXPs(columns, columnsAsNumeric, columnsAsOrdinal, columnsAsNominal, allColumns);\n\treturn _staticRef->readDataSetHeader(columnsRequested);\n}\n\nstd::map<string, Column::ColumnType> RcppBridge::marshallSEXPs(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns)\n{\n\tmap<string, Column::ColumnType> columnsRequested;\n\n\tif (Rf_isLogical(allColumns) && Rcpp::as<bool>(allColumns))\n\t{\n\t\t(void)_staticRef;\n\t\tBOOST_FOREACH(const Column &column, _staticRef->_dataSet->columns())\n\t\t\tcolumnsRequested[column.name()] = Column::ColumnTypeUnknown;\n\t}\n\n\tif (Rf_isString(columns))\n\t{\n\t\tvector<string> temp = Rcpp::as<vector<string> >(columns);\n\t\tfor (int i = 0; i < temp.size(); i++)\n\t\t\tcolumnsRequested[temp.at(i)] = Column::ColumnTypeUnknown;\n\t}\n\n\tif (Rf_isString(columnsAsNumeric))\n\t{\n\t\tvector<string> temp = Rcpp::as<vector<string> >(columnsAsNumeric);\n\t\tfor (int i = 0; i < temp.size(); i++)\n\t\t\tcolumnsRequested[temp.at(i)] = Column::ColumnTypeScale;\n\t}\n\n\tif (Rf_isString(columnsAsOrdinal))\n\t{\n\t\tvector<string> temp = Rcpp::as<vector<string> >(columnsAsOrdinal);\n\t\tfor (int i = 0; i < temp.size(); i++)\n\t\t\tcolumnsRequested[temp.at(i)] = Column::ColumnTypeOrdinal;\n\t}\n\n\tif (Rf_isString(columnsAsNominal))\n\t{\n\t\tvector<string> temp = Rcpp::as<vector<string> >(columnsAsNominal);\n\t\tfor (int i = 0; i < temp.size(); i++)\n\t\t\tcolumnsRequested[temp.at(i)] = Column::ColumnTypeNominal;\n\t}\n\n\treturn columnsRequested;\n}\n\nSEXP RcppBridge::callbackStatic(SEXP results)\n{\n\tRcpp::NumericVector control(1);\n\tcontrol[0] = _staticRef->callback(results);\n\treturn control;\n}\n\n\n<commit_msg>Fix to dataframe loading of ordinals with NAs<commit_after>#include \"rcppbridge.h\"\n\n#include <boost\/foreach.hpp>\n#include \"..\/JASP-Common\/base64.h\"\n#include <iomanip>\n\nusing namespace std;\n\n\nRcppBridge* RcppBridge::_staticRef;\n\nRcppBridge::RcppBridge()\n{\n\t_staticRef = this;\n\n\t_rInside[\".read.dataset.native\"] = Rcpp::InternalFunction(&RcppBridge::readDataSetStatic);\n\t_rInside[\".read.dataset.header.native\"] = Rcpp::InternalFunction(&RcppBridge::readDataSetHeaderStatic);\n\t_rInside[\".callback.native\"] = Rcpp::InternalFunction(&RcppBridge::callbackStatic);\n\n\t_rInside[\"jasp.analyses\"] = Rcpp::List();\n\t_rInside.parseEvalQNT(\"suppressPackageStartupMessages(library(\\\"RJSONIO\\\"))\");\n\t_rInside.parseEvalQNT(\"suppressPackageStartupMessages(library(\\\"JASP\\\"))\");\n}\n\nvoid RcppBridge::setDataSet(DataSet* dataSet)\n{\n\t_dataSet = dataSet;\n}\n\nJson::Value RcppBridge::init(const string &name, const Json::Value &options)\n{\n\tSEXP results;\n\n\t_rInside[\"name\"] = name;\n\t_rInside[\"options.as.json.string\"] = options.toStyledString();\n\t_rInside.parseEval(\"init(name=name, options.as.json.string=options.as.json.string)\", results);\n\n\tstring resultsAsString = Rcpp::as<string>(results);\n\n\tJson::Reader r;\n\tJson::Value json;\n\tr.parse(resultsAsString, json);\n\n\treturn json;\n}\n\nJson::Value RcppBridge::run(const string &name, const Json::Value &options, boost::function<int (Json::Value)> callback)\n{\n\tSEXP results;\n\n\t_callback = callback;\n\n\t_rInside[\"name\"] = name;\n\t_rInside[\"options.as.json.string\"] = options.toStyledString();\n\t_rInside.parseEval(\"run(name=name, options.as.json.string=options.as.json.string)\", results);\n\n\t_callback = NULL;\n\n\tstring resultsAsString = Rcpp::as<string>(results);\n\n\tJson::Reader r;\n\tJson::Value json;\n\tr.parse(resultsAsString, json);\n\n\treturn json;\n}\n\nRcpp::DataFrame RcppBridge::readDataSet(const std::map<std::string, Column::ColumnType> &columns)\n{\n\tRcpp::List list(columns.size());\n\tRcpp::CharacterVector columnNames;\n\n\tint colNo = 0;\n\n\ttypedef pair<const string, Column::ColumnType> ColumnInfo;\n\n\tBOOST_FOREACH(const ColumnInfo &columnInfo, columns)\n\t{\n\t\t(void)columns;\n\t\tstring dot = \".\";\n\n\t\tstring columnName = columnInfo.first;\n\n\t\tstring base64 = Base64::encode(dot, columnName);\n\t\tcolumnNames.push_back(base64);\n\n\t\tColumn &column = _dataSet->columns().get(columnName);\n\t\tColumn::ColumnType columnType = column.columnType();\n\n\t\tColumn::ColumnType requestedType = columnInfo.second;\n\t\tif (requestedType == Column::ColumnTypeUnknown)\n\t\t\trequestedType = columnType;\n\n\t\tint rowCount = column.rowCount();\n\t\tint rowNo = 0;\n\n\t\tif (requestedType == Column::ColumnTypeScale)\n\t\t{\n\t\t\tif (columnType == Column::ColumnTypeScale)\n\t\t\t{\n\t\t\t\tRcpp::NumericVector v(rowCount);\n\n\t\t\t\tBOOST_FOREACH(double value, column.AsDoubles)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tv[rowNo++] = value;\n\t\t\t\t}\n\n\t\t\t\tlist[colNo++] = v;\n\t\t\t}\n\t\t\telse if (columnType == Column::ColumnTypeOrdinal || columnType == Column::ColumnTypeNominal)\n\t\t\t{\n\t\t\t\tRcpp::IntegerVector v(rowCount);\n\n\t\t\t\tBOOST_FOREACH(int value, column.AsInts)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tv[rowNo++] = column.actualFromRaw(value);\n\t\t\t\t}\n\n\t\t\t\tlist[colNo++] = v;\n\t\t\t}\n\t\t\telse \/\/ columnType == Column::ColumnTypeNominalText\n\t\t\t{\n\t\t\t\tRcpp::IntegerVector v(rowCount);\n\n\t\t\t\tBOOST_FOREACH(int value, column.AsInts)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tv[rowNo++] = column.actualFromRaw(value);\n\t\t\t\t}\n\n\t\t\t\tmakeFactor(v, column.labels());\n\n\t\t\t\tlist[colNo++] = v;\n\t\t\t}\n\t\t}\n\t\telse \/\/ if (requestedType != Column::ColumnTypeScale)\n\t\t{\n\t\t\tbool ordinal = (requestedType == Column::ColumnTypeOrdinal);\n\n\t\t\tRcpp::IntegerVector v(rowCount);\n\n\t\t\tif (columnType != Column::ColumnTypeScale)\n\t\t\t{\n\t\t\t\tBOOST_FOREACH(int value, column.AsInts)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tif (value == INT_MIN)\n\t\t\t\t\t\tv[rowNo++] = INT_MIN;\n\t\t\t\t\telse\n\t\t\t\t\t\tv[rowNo++] = value + 1;\n\t\t\t\t}\n\n\t\t\t\tmakeFactor(v, column.labels(), ordinal);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ scale to nominal or ordinal (doesn't really make sense, but we have to do something)\n\n\t\t\t\tset<int> uniqueValues;\n\n\t\t\t\tBOOST_FOREACH(double value, column.AsDoubles)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\t\t\t\t\tint intValue = (int)(value * 1000);\n\t\t\t\t\tuniqueValues.insert(intValue);\n\t\t\t\t}\n\n\t\t\t\tint index = 0;\n\t\t\t\tmap<int, int> valueToIndex;\n\t\t\t\tvector<string> labels;\n\n\t\t\t\tBOOST_FOREACH(int value, uniqueValues)\n\t\t\t\t{\n\t\t\t\t\t(void)uniqueValues;\n\t\t\t\t\tvalueToIndex[value] = index;\n\n\t\t\t\t\tstringstream ss;\n\t\t\t\t\tss << ((double)value \/ 1000);\n\t\t\t\t\tlabels.push_back(ss.str());\n\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\n\t\t\t\tBOOST_FOREACH(double value, column.AsDoubles)\n\t\t\t\t{\n\t\t\t\t\t(void)column;\n\n\t\t\t\t\tif (isnan(value))\n\t\t\t\t\t\tv[rowNo++] = INT_MIN;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tv[rowNo++] = valueToIndex[(int)(value * 1000)] + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmakeFactor(v, labels, ordinal);\n\t\t\t}\n\n\t\t\tlist[colNo++] = v;\n\t\t}\n\t}\n\n\tlist.attr(\"names\") = columnNames;\n\n\tRcpp::DataFrame dataFrame = Rcpp::DataFrame(list);\n\n\treturn dataFrame;\n}\n\nRcpp::DataFrame RcppBridge::readDataSetHeader(const std::map<string, Column::ColumnType> &columns)\n{\n\tRcpp::List list(columns.size());\n\tRcpp::CharacterVector columnNames;\n\n\tint colNo = 0;\n\n\ttypedef pair<const string, Column::ColumnType> ColumnInfo;\n\n\tBOOST_FOREACH(const ColumnInfo &columnInfo, columns)\n\t{\n\t\t(void)columns;\n\t\tstring dot = \".\";\n\n\t\tstring columnName = columnInfo.first;\n\n\t\tstring base64 = Base64::encode(dot, columnName);\n\t\tcolumnNames.push_back(base64);\n\n\t\tColumn &column = _dataSet->columns().get(columnName);\n\t\tColumn::ColumnType columnType = column.columnType();\n\n\t\tColumn::ColumnType requestedType = columnInfo.second;\n\t\tif (requestedType == Column::ColumnTypeUnknown)\n\t\t\trequestedType = columnType;\n\n\t\tif (requestedType == Column::ColumnTypeScale)\n\t\t{\n\t\t\tif (columnType == Column::ColumnTypeScale)\n\t\t\t{\n\t\t\t\tlist[colNo++] = Rcpp::NumericVector(0);\n\t\t\t}\n\t\t\telse if (columnType == Column::ColumnTypeOrdinal || columnType == Column::ColumnTypeNominal)\n\t\t\t{\n\t\t\t\tlist[colNo++] = Rcpp::IntegerVector(0);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tRcpp::IntegerVector v(0);\n\t\t\t\tmakeFactor(v, column.labels());\n\t\t\t\tlist[colNo++] = v;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbool ordinal = (requestedType == Column::ColumnTypeOrdinal);\n\n\t\t\tRcpp::IntegerVector v(0);\n\t\t\tmakeFactor(v, column.labels(), ordinal);\n\n\t\t\tlist[colNo++] = v;\n\t\t}\n\t}\n\n\tlist.attr(\"names\") = columnNames;\n\n\tRcpp::DataFrame dataFrame = Rcpp::DataFrame(list);\n\n\treturn dataFrame;\n}\n\nvoid RcppBridge::makeFactor(Rcpp::IntegerVector &v, const Labels &levels, bool ordinal)\n{\n\tRcpp::CharacterVector labels;\n\n\tfor (int i = 0; i < levels.size(); i++)\n\t\tlabels.push_back(levels.at(i).text());\n\n\tv.attr(\"levels\") = labels;\n\n\tvector<string> cla55;\n\tif (ordinal)\n\t\tcla55.push_back(\"ordered\");\n\tcla55.push_back(\"factor\");\n\n\tv.attr(\"class\") = cla55;\n}\n\nvoid RcppBridge::makeFactor(Rcpp::IntegerVector &v, const std::vector<string> &levels, bool ordinal)\n{\n\tv.attr(\"levels\") = levels;\n\n\tvector<string> cla55;\n\tif (ordinal)\n\t\tcla55.push_back(\"ordered\");\n\tcla55.push_back(\"factor\");\n\n\tv.attr(\"class\") = cla55;\n}\n\n\nint RcppBridge::callback(SEXP results)\n{\n\tstring jsonString = Rcpp::as<string>(results);\n\n\tJson::Reader r;\n\tJson::Value json;\n\tr.parse(jsonString, json);\n\n\treturn _callback(json);\n}\n\nRcpp::DataFrame RcppBridge::readDataSetStatic(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns)\n{\t\n\tmap<string, Column::ColumnType> columnsRequested = marshallSEXPs(columns, columnsAsNumeric, columnsAsOrdinal, columnsAsNominal, allColumns);\n\treturn _staticRef->readDataSet(columnsRequested);\n}\n\nRcpp::DataFrame RcppBridge::readDataSetHeaderStatic(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns)\n{\n\tmap<string, Column::ColumnType> columnsRequested = marshallSEXPs(columns, columnsAsNumeric, columnsAsOrdinal, columnsAsNominal, allColumns);\n\treturn _staticRef->readDataSetHeader(columnsRequested);\n}\n\nstd::map<string, Column::ColumnType> RcppBridge::marshallSEXPs(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns)\n{\n\tmap<string, Column::ColumnType> columnsRequested;\n\n\tif (Rf_isLogical(allColumns) && Rcpp::as<bool>(allColumns))\n\t{\n\t\t(void)_staticRef;\n\t\tBOOST_FOREACH(const Column &column, _staticRef->_dataSet->columns())\n\t\t\tcolumnsRequested[column.name()] = Column::ColumnTypeUnknown;\n\t}\n\n\tif (Rf_isString(columns))\n\t{\n\t\tvector<string> temp = Rcpp::as<vector<string> >(columns);\n\t\tfor (int i = 0; i < temp.size(); i++)\n\t\t\tcolumnsRequested[temp.at(i)] = Column::ColumnTypeUnknown;\n\t}\n\n\tif (Rf_isString(columnsAsNumeric))\n\t{\n\t\tvector<string> temp = Rcpp::as<vector<string> >(columnsAsNumeric);\n\t\tfor (int i = 0; i < temp.size(); i++)\n\t\t\tcolumnsRequested[temp.at(i)] = Column::ColumnTypeScale;\n\t}\n\n\tif (Rf_isString(columnsAsOrdinal))\n\t{\n\t\tvector<string> temp = Rcpp::as<vector<string> >(columnsAsOrdinal);\n\t\tfor (int i = 0; i < temp.size(); i++)\n\t\t\tcolumnsRequested[temp.at(i)] = Column::ColumnTypeOrdinal;\n\t}\n\n\tif (Rf_isString(columnsAsNominal))\n\t{\n\t\tvector<string> temp = Rcpp::as<vector<string> >(columnsAsNominal);\n\t\tfor (int i = 0; i < temp.size(); i++)\n\t\t\tcolumnsRequested[temp.at(i)] = Column::ColumnTypeNominal;\n\t}\n\n\treturn columnsRequested;\n}\n\nSEXP RcppBridge::callbackStatic(SEXP results)\n{\n\tRcpp::NumericVector control(1);\n\tcontrol[0] = _staticRef->callback(results);\n\treturn control;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n irkick.cpp - Implementation of the main window\n -------------------\n copyright : (C) 2002 by Gav Wood\n email : gav@kde.org\n***************************************************************************\/\n\n\/\/ This program is free software.\n\n#include <qwidget.h>\n#include <qdialog.h>\n#include <qtooltip.h>\n#include <qregexp.h>\n#include <qtimer.h>\n#include <qevent.h>\n\/\/Added by qt3to4:\n#include <QMouseEvent>\n#include <Q3ValueList>\n#include <Q3CString>\n\n#include <kdeversion.h>\n#include <kapplication.h>\n#include <kaction.h>\n#if !(KDE_VERSION_MINOR<=1 && KDE_VERSION_RELEASE<=5)\n#include <kactioncollection.h>\n#endif\n#include <ksimpleconfig.h>\n#include <ksystemtray.h>\n#include <kiconloader.h>\n#include <kpassivepopup.h>\n#include <kmessagebox.h>\n#include <kpopupmenu.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kaboutdialog.h>\n#include <kaboutkde.h>\n#include <kwinmodule.h>\n#include <kwin.h>\n#include <khelpmenu.h>\n#include <kglobal.h>\n#include <kstdguiitem.h>\n\n#include <dcopclient.h>\n#include <dcopref.h>\n\n#include \"profileserver.h\"\n#include \"irkick.h\"\n\nvoid IRKTrayIcon::mousePressEvent(QMouseEvent *e)\n{\n\tKSystemTray::mousePressEvent(new QMouseEvent(QEvent::MouseButtonPress, e->pos(), e->globalPos(), e->button() == Qt::LeftButton ? Qt::RightButton : e->button(), e->state()));\n}\n\nIRKick::IRKick(const Q3CString &obj) : QObject(), DCOPObject(obj), npApp(QString::null)\n{\n kapp->dcopClient()->setDefaultObject(obj);\n\ttheClient = new KLircClient();\n\n\ttheTrayIcon = new IRKTrayIcon();\n\tif(theClient->isConnected())\n\t{\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n\t\tQToolTip::add(theTrayIcon, i18n(\"KDE Lirc Server: Ready.\"));\n\t}\n\telse\n\t{\ttheTrayIcon->setPixmap(SmallIcon(\"irkickoff\"));\n\t\tQToolTip::add(theTrayIcon, i18n(\"KDE Lirc Server: No infra-red remote controls found.\"));\n\t\tQTimer::singleShot(10000, this, SLOT(checkLirc()));\n\t}\n\ttheFlashOff = new QTimer(theTrayIcon);\n\tconnect(theFlashOff, SIGNAL(timeout()), SLOT(flashOff()));\n\n\ttheResetCount = 0;\n\tslotReloadConfiguration();\n\tconnect(theClient, SIGNAL(connectionClosed()), this, SLOT(slotClosed()));\n\tconnect(theClient, SIGNAL(remotesRead()), this, SLOT(resetModes()));\n\tconnect(theClient, SIGNAL(commandReceived(const QString &, const QString &, int)), this, SLOT(gotMessage(const QString &, const QString &, int)));\n\n\ttheTrayIcon->contextMenu()->changeTitle(0, \"IRKick\");\n\ttheTrayIcon->contextMenu()->insertItem(SmallIcon( \"configure\" ), i18n(\"&Configure...\"), this, SLOT(slotConfigure()));\n\ttheTrayIcon->contextMenu()->insertSeparator();\n\ttheTrayIcon->contextMenu()->insertItem(SmallIcon( \"help\" ), KStdGuiItem::help().text(), (new KHelpMenu(theTrayIcon, KGlobal::instance()->aboutData()))->menu());\n\ttheTrayIcon->actionCollection()->action(\"file_quit\")->disconnect(SIGNAL(activated()));\n\tconnect(theTrayIcon->actionCollection()->action(\"file_quit\"), SIGNAL(activated()), SLOT(doQuit()));\n\n\ttheTrayIcon->show();\n}\n\nIRKick::~IRKick()\n{\n\tdelete theTrayIcon;\n\tfor(QMap<QString,IRKTrayIcon *>::iterator i = currentModeIcons.begin(); i != currentModeIcons.end(); ++i)\n\t\tif(*i) delete *i;\n}\n\nvoid IRKick::slotClosed()\n{\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkickoff\"));\n\tKPassivePopup::message(\"IRKick\", i18n(\"The infrared system has severed its connection. Remote controls are no longer available.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\tQTimer::singleShot(1000, this, SLOT(checkLirc()));\n}\n\nvoid IRKick::checkLirc()\n{\n\tif(!theClient->isConnected())\n\t\tif(theClient->connectToLirc())\n\t\t{\tKPassivePopup::message(\"IRKick\", i18n(\"A connection to the infrared system has been made. Remote controls may now be available.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\t\t\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n\t\t}\n\t\telse\n\t\t\tQTimer::singleShot(10000, this, SLOT(checkLirc()));\n}\n\nvoid IRKick::flashOff()\n{\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n}\n\nvoid IRKick::doQuit()\n{\n\tKSimpleConfig theConfig(\"irkickrc\");\n\ttheConfig.setGroup(\"General\");\n\tswitch(KMessageBox::questionYesNoCancel(0, i18n(\"Should the Infrared Remote Control server start automatically when you begin KDE?\"), i18n(\"Automatically Start?\"), i18n(\"Start Automatically\"), i18n(\"Do Not Start\")))\n\t{\tcase KMessageBox::No: theConfig.writeEntry(\"AutoStart\", false); break;\n\t\tcase KMessageBox::Yes: theConfig.writeEntry(\"AutoStart\", true); break;\n\t\tcase KMessageBox::Cancel: return;\n\t}\n\tKApplication::kApplication()->quit();\n}\n\nvoid IRKick::resetModes()\n{\n\tif(theResetCount > 1)\n\t\tKPassivePopup::message(\"IRKick\", i18n(\"Resetting all modes.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\tif(!theResetCount)\n\t\tallModes.generateNulls(theClient->remotes());\n\n\tQStringList remotes = theClient->remotes();\n\tfor(QStringList::iterator i = remotes.begin(); i != remotes.end(); ++i)\n\t{\tcurrentModes[*i] = allModes.getDefault(*i).name();\n\t\tif(theResetCount && currentModeIcons[*i]) delete currentModeIcons[*i];\n\t\tcurrentModeIcons[*i] = 0;\n\t}\n\tupdateModeIcons();\n\ttheResetCount++;\n}\n\nvoid IRKick::slotReloadConfiguration()\n{\n\t\/\/ load configuration from config file\n\tKSimpleConfig theConfig(\"irkickrc\");\n\tallActions.loadFromConfig(theConfig);\n\tallModes.loadFromConfig(theConfig);\n\tif(currentModes.count() && theResetCount)\n\t\tresetModes();\n}\n\nvoid IRKick::slotConfigure()\n{\n\tKApplication::startServiceByDesktopName(\"kcmlirc\");\n}\n\nvoid IRKick::updateModeIcons()\n{\n\tfor(QMap<QString,QString>::iterator i = currentModes.begin(); i != currentModes.end(); ++i)\n\t{\tMode mode = allModes.getMode(i.key(), i.data());\n\t\tif(mode.iconFile().isNull() || mode.iconFile().isEmpty())\n\t\t{\tif(currentModeIcons[i.key()])\n\t\t\t{\tdelete currentModeIcons[i.key()];\n\t\t\t\tcurrentModeIcons[i.key()] = 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\tif(!currentModeIcons[i.key()])\n\t\t\t{\tcurrentModeIcons[i.key()] = new IRKTrayIcon();\n\t\t\t\tcurrentModeIcons[i.key()]->show();\n\t\t\t\tcurrentModeIcons[i.key()]->contextMenu()->changeTitle(0, mode.remoteName());\n\t\t\t\tcurrentModeIcons[i.key()]->actionCollection()->action(\"file_quit\")->setEnabled(false);\n\t\t\t}\n\t\t\tcurrentModeIcons[i.key()]->setPixmap(KIconLoader().loadIcon(mode.iconFile(), KIcon::Panel));\n\t\t\tQToolTip::add(currentModeIcons[i.key()], mode.remoteName() + \": <b>\" + mode.name() + \"<\/b>\");\n\t\t}\n\t}\n}\n\nbool IRKick::getPrograms(const IRAction &action, QStringList &programs)\n{\n\tDCOPClient *theDC = KApplication::dcopClient();\n\tprograms.clear();\n\n\tif(action.unique())\n\t{\tif(theDC->isApplicationRegistered(action.program().utf8()))\n\t\t\tprograms += action.program();\n\t}\n\telse\n\t{\n\t\tQRegExp r = QRegExp(\"^\" + action.program() + \"-(\\\\d+)$\");\n\t\t\/\/ find all instances...\n\t\tQCStringList buf = theDC->registeredApplications();\n\t\tfor(QCStringList::iterator i = buf.begin(); i != buf.end(); ++i)\n\t\t{\n\t\t\tQString program = QString::fromUtf8(*i);\n\t\t\tif(program.contains(r))\n\t\t\t\tprograms += program;\n\t\t}\n\t\tif(programs.size() > 1 && action.ifMulti() == IM_DONTSEND)\n\t\t\treturn false;\n\t\telse if(programs.size() > 1 && action.ifMulti() == IM_SENDTOTOP)\n\t\t{\tQ3ValueList<WId> s = KWinModule().stackingOrder();\n\t\t\t\/\/ go through all the (ordered) window pids\n\t\t\tfor(Q3ValueList<WId>::iterator i = s.fromLast(); i != s.end(); i--)\n\t\t\t{\tint p = KWin::info(*i).pid;\n\t\t\t\tQString id = action.program() + \"-\" + QString().setNum(p);\n\t\t\t\tif(programs.contains(id))\n\t\t\t\t{\tprograms.clear();\n\t\t\t\t\tprograms += id;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile(programs.size() > 1) programs.remove(programs.begin());\n\t\t}\n\t\telse if(programs.size() > 1 && action.ifMulti() == IM_SENDTOBOTTOM)\n\t\t{\tQ3ValueList<WId> s = KWinModule().stackingOrder();\n\t\t\t\/\/ go through all the (ordered) window pids\n\t\t\tfor(Q3ValueList<WId>::iterator i = s.begin(); i != s.end(); ++i)\n\t\t\t{\tint p = KWin::info(*i).pid;\n\t\t\t\tQString id = action.program() + \"-\" + QString().setNum(p);\n\t\t\t\tif(programs.contains(id))\n\t\t\t\t{\tprograms.clear();\n\t\t\t\t\tprograms += id;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile(programs.size() > 1) programs.remove(programs.begin());\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid IRKick::executeAction(const IRAction &action)\n{\n\tDCOPClient *theDC = KApplication::dcopClient();\n\tQStringList programs;\n\n\tif(!getPrograms(action, programs)) return;\n\n\t\/\/ if programs.size()==0 here, then the app is definately not running.\n\tif(action.autoStart() && !programs.size())\n\t{\tQString sname = ProfileServer::profileServer()->getServiceName(action.program());\n\t\tif(!sname.isNull())\n\t\t{\n\t\t\tKPassivePopup::message(\"IRKick\", i18n(\"Starting <b>%1<\/b>...\").arg(action.application()), SmallIcon(\"irkick\"), theTrayIcon);\n\t\t\tKApplication::startServiceByDesktopName(sname);\n\t\t}\n\t}\n\tif(action.isJustStart()) return;\n\n\tif(!getPrograms(action, programs)) return;\n\n\tfor(QStringList::iterator i = programs.begin(); i != programs.end(); ++i)\n\t{\tconst QString &program = *i;\n\t\tif(theDC->isApplicationRegistered(program.utf8()))\n\t\t{\tQByteArray data; QDataStream arg(&data, QIODevice::WriteOnly);\n arg.setVersion(QDataStream::Qt_3_1);\n\t\t\tkdDebug() << \"Sending data (\" << program << \", \" << action.object() << \", \" << action.method().prototypeNR() << endl;\n\t\t\tfor(Arguments::const_iterator j = action.arguments().begin(); j != action.arguments().end(); ++j)\n\t\t\t{\tkdDebug() << \"Got argument...\" << endl;\n\t\t\t\tswitch((*j).type())\n\t\t\t\t{\tcase QVariant::Int: arg << (*j).toInt(); break;\n\t\t\t\t\tcase QVariant::CString: arg << (*j).toCString(); break;\n\t\t\t\t\tcase QVariant::StringList: arg << (*j).toStringList(); break;\n\t\t\t\t\tcase QVariant::UInt: arg << (*j).toUInt(); break;\n\t\t\t\t\tcase QVariant::Bool: arg << (*j).toBool(); break;\n\t\t\t\t\tcase QVariant::Double: arg << (*j).toDouble(); break;\n\t\t\t\t\tdefault: arg << (*j).toString(); break;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttheDC->send(program.utf8(), action.object().utf8(), action.method().prototypeNR().utf8(), data);\n\t\t}\n\t}\n}\n\nvoid IRKick::gotMessage(const QString &theRemote, const QString &theButton, int theRepeatCounter)\n{\n\tkdDebug() << \"Got message: \" << theRemote << \": \" << theButton << \" (\" << theRepeatCounter << \")\" << endl;\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkickflash\"));\n\ttheFlashOff->start(200, true);\n\tif(!npApp.isNull())\n\t{\n\t\tQString theApp = npApp;\n\t\tnpApp = QString::null;\n\t\t\/\/ send notifier by DCOP to npApp\/npModule\/npMethod(theRemote, theButton);\n\t\tQByteArray data; QDataStream arg(&data, QIODevice::WriteOnly);\n arg.setVersion(QDataStream::Qt_3_1);\n\t\targ << theRemote << theButton;\n\t\tKApplication::dcopClient()->send(theApp.utf8(), npModule.utf8(), npMethod.utf8(), data);\n\t}\n\telse\n\t{\n\t\tif(currentModes[theRemote].isNull()) currentModes[theRemote] = \"\";\n\t\tIRAItList l = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton);\n\t\tif(!currentModes[theRemote].isEmpty())\n\t\t\tl += allActions.findByModeButton(Mode(theRemote, \"\"), theButton);\n\t\tbool doBefore = true, doAfter = false;\n\t\tfor(IRAItList::const_iterator i = l.begin(); i != l.end(); ++i)\n\t\t\tif((**i).isModeChange() && !theRepeatCounter)\n\t\t\t{\t\/\/ mode switch\n\t\t\t\tcurrentModes[theRemote] = (**i).modeChange();\n\t\t\t\tMode mode = allModes.getMode(theRemote, (**i).modeChange());\n\t\t\t\tupdateModeIcons();\n\t\t\t\tdoBefore = (**i).doBefore();\n\t\t\t\tdoAfter = (**i).doAfter();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tfor(int after = 0; after < 2; after++)\n\t\t{\tif(doBefore && !after || doAfter && after)\n\t\t\t\tfor(IRAItList::const_iterator i = l.begin(); i != l.end(); ++i)\n\t\t\t\t\tif(!(**i).isModeChange() && ((**i).repeat() || !theRepeatCounter))\n\t\t\t\t\t{\texecuteAction(**i);\n\t\t\t\t\t}\n\t\t\tif(!after && doAfter)\n\t\t\t{\tl = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton);\n\t\t\t\tif(!currentModes[theRemote].isEmpty())\n\t\t\t\t\tl += allActions.findByModeButton(Mode(theRemote, \"\"), theButton);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid IRKick::stealNextPress(QString app, QString module, QString method)\n{\n\tnpApp = app;\n\tnpModule = module;\n\tnpMethod = method;\n}\n\nvoid IRKick::dontStealNextPress()\n{\n\tnpApp = QString::null;\n}\n\n#include \"irkick.moc\"\n<commit_msg>Start to fix it<commit_after>\/***************************************************************************\n irkick.cpp - Implementation of the main window\n -------------------\n copyright : (C) 2002 by Gav Wood\n email : gav@kde.org\n***************************************************************************\/\n\n\/\/ This program is free software.\n\n#include <qwidget.h>\n#include <qdialog.h>\n#include <qtooltip.h>\n#include <qregexp.h>\n#include <qtimer.h>\n#include <qevent.h>\n\/\/Added by qt3to4:\n#include <QMouseEvent>\n#include <Q3ValueList>\n#include <Q3CString>\n#include <kdeversion.h>\n#include <kapplication.h>\n#include <kaction.h>\n#if !(KDE_VERSION_MINOR<=1 && KDE_VERSION_RELEASE<=5)\n#include <kactioncollection.h>\n#endif\n#include <ksimpleconfig.h>\n#include <ksystemtray.h>\n#include <kiconloader.h>\n#include <kpassivepopup.h>\n#include <kmessagebox.h>\n#include <kpopupmenu.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kaboutdialog.h>\n#include <kaboutkde.h>\n#include <kwinmodule.h>\n#include <kwin.h>\n#include <khelpmenu.h>\n#include <kglobal.h>\n#include <kstdguiitem.h>\n\n#include <dcopclient.h>\n#include <dcopref.h>\n\n#include \"profileserver.h\"\n#include \"irkick.h\"\n\nvoid IRKTrayIcon::mousePressEvent(QMouseEvent *e)\n{\n\tKSystemTray::mousePressEvent(new QMouseEvent(QEvent::MouseButtonPress, e->pos(), e->globalPos(), e->button() == Qt::LeftButton ? Qt::RightButton : e->button(), e->state()));\n}\n\nIRKick::IRKick(const Q3CString &obj) : QObject(), DCOPObject(obj), npApp(QString::null)\n{\n kapp->dcopClient()->setDefaultObject(obj);\n\ttheClient = new KLircClient();\n\n\ttheTrayIcon = new IRKTrayIcon();\n\tif(theClient->isConnected())\n\t{\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n\t\tQToolTip::add(theTrayIcon, i18n(\"KDE Lirc Server: Ready.\"));\n\t}\n\telse\n\t{\ttheTrayIcon->setPixmap(SmallIcon(\"irkickoff\"));\n\t\tQToolTip::add(theTrayIcon, i18n(\"KDE Lirc Server: No infra-red remote controls found.\"));\n\t\tQTimer::singleShot(10000, this, SLOT(checkLirc()));\n\t}\n\ttheFlashOff = new QTimer(theTrayIcon);\n\tconnect(theFlashOff, SIGNAL(timeout()), SLOT(flashOff()));\n\n\ttheResetCount = 0;\n\tslotReloadConfiguration();\n\tconnect(theClient, SIGNAL(connectionClosed()), this, SLOT(slotClosed()));\n\tconnect(theClient, SIGNAL(remotesRead()), this, SLOT(resetModes()));\n\tconnect(theClient, SIGNAL(commandReceived(const QString &, const QString &, int)), this, SLOT(gotMessage(const QString &, const QString &, int)));\n\n\ttheTrayIcon->contextMenu()->changeTitle(0, \"IRKick\");\n\ttheTrayIcon->contextMenu()->insertItem(SmallIcon( \"configure\" ), i18n(\"&Configure...\"), this, SLOT(slotConfigure()));\n\ttheTrayIcon->contextMenu()->insertSeparator();\n\ttheTrayIcon->contextMenu()->insertItem(SmallIcon( \"help\" ), KStdGuiItem::help().text(), (new KHelpMenu(theTrayIcon, KGlobal::instance()->aboutData()))->menu());\n\ttheTrayIcon->actionCollection()->action(\"file_quit\")->disconnect(SIGNAL(activated()));\n\tconnect(theTrayIcon->actionCollection()->action(\"file_quit\"), SIGNAL(activated()), SLOT(doQuit()));\n\n\ttheTrayIcon->show();\n}\n\nIRKick::~IRKick()\n{\n\tdelete theTrayIcon;\n\tfor(QMap<QString,IRKTrayIcon *>::iterator i = currentModeIcons.begin(); i != currentModeIcons.end(); ++i)\n\t\tif(*i) delete *i;\n}\n\nvoid IRKick::slotClosed()\n{\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkickoff\"));\n\tKPassivePopup::message(\"IRKick\", i18n(\"The infrared system has severed its connection. Remote controls are no longer available.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\tQTimer::singleShot(1000, this, SLOT(checkLirc()));\n}\n\nvoid IRKick::checkLirc()\n{\n\tif(!theClient->isConnected())\n\t\tif(theClient->connectToLirc())\n\t\t{\tKPassivePopup::message(\"IRKick\", i18n(\"A connection to the infrared system has been made. Remote controls may now be available.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\t\t\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n\t\t}\n\t\telse\n\t\t\tQTimer::singleShot(10000, this, SLOT(checkLirc()));\n}\n\nvoid IRKick::flashOff()\n{\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n}\n\nvoid IRKick::doQuit()\n{\n\tKSimpleConfig theConfig(\"irkickrc\");\n\ttheConfig.setGroup(\"General\");\n\tswitch(KMessageBox::questionYesNoCancel(0, i18n(\"Should the Infrared Remote Control server start automatically when you begin KDE?\"), i18n(\"Automatically Start?\"), i18n(\"Start Automatically\"), i18n(\"Do Not Start\")))\n\t{\tcase KMessageBox::No: theConfig.writeEntry(\"AutoStart\", false); break;\n\t\tcase KMessageBox::Yes: theConfig.writeEntry(\"AutoStart\", true); break;\n\t\tcase KMessageBox::Cancel: return;\n\t}\n\tKApplication::kApplication()->quit();\n}\n\nvoid IRKick::resetModes()\n{\n\tif(theResetCount > 1)\n\t\tKPassivePopup::message(\"IRKick\", i18n(\"Resetting all modes.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\tif(!theResetCount)\n\t\tallModes.generateNulls(theClient->remotes());\n\n\tQStringList remotes = theClient->remotes();\n\tfor(QStringList::iterator i = remotes.begin(); i != remotes.end(); ++i)\n\t{\tcurrentModes[*i] = allModes.getDefault(*i).name();\n\t\tif(theResetCount && currentModeIcons[*i]) delete currentModeIcons[*i];\n\t\tcurrentModeIcons[*i] = 0;\n\t}\n\tupdateModeIcons();\n\ttheResetCount++;\n}\n\nvoid IRKick::slotReloadConfiguration()\n{\n\t\/\/ load configuration from config file\n\tKSimpleConfig theConfig(\"irkickrc\");\n\tallActions.loadFromConfig(theConfig);\n\tallModes.loadFromConfig(theConfig);\n\tif(currentModes.count() && theResetCount)\n\t\tresetModes();\n}\n\nvoid IRKick::slotConfigure()\n{\n\tKApplication::startServiceByDesktopName(\"kcmlirc\");\n}\n\nvoid IRKick::updateModeIcons()\n{\n\tfor(QMap<QString,QString>::iterator i = currentModes.begin(); i != currentModes.end(); ++i)\n\t{\tMode mode = allModes.getMode(i.key(), i.data());\n\t\tif(mode.iconFile().isNull() || mode.iconFile().isEmpty())\n\t\t{\tif(currentModeIcons[i.key()])\n\t\t\t{\tdelete currentModeIcons[i.key()];\n\t\t\t\tcurrentModeIcons[i.key()] = 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\tif(!currentModeIcons[i.key()])\n\t\t\t{\tcurrentModeIcons[i.key()] = new IRKTrayIcon();\n\t\t\t\tcurrentModeIcons[i.key()]->show();\n\t\t\t\tcurrentModeIcons[i.key()]->contextMenu()->changeTitle(0, mode.remoteName());\n\t\t\t\tcurrentModeIcons[i.key()]->actionCollection()->action(\"file_quit\")->setEnabled(false);\n\t\t\t}\n\t\t\tcurrentModeIcons[i.key()]->setPixmap(KIconLoader().loadIcon(mode.iconFile(), KIcon::Panel));\n\t\t\tQToolTip::add(currentModeIcons[i.key()], mode.remoteName() + \": <b>\" + mode.name() + \"<\/b>\");\n\t\t}\n\t}\n}\n\nbool IRKick::getPrograms(const IRAction &action, QStringList &programs)\n{\n\tDCOPClient *theDC = KApplication::dcopClient();\n\tprograms.clear();\n\n\tif(action.unique())\n\t{\tif(theDC->isApplicationRegistered(action.program().utf8()))\n\t\t\tprograms += action.program();\n\t}\n\telse\n\t{\n\t\tQRegExp r = QRegExp(\"^\" + action.program() + \"-(\\\\d+)$\");\n\t\t\/\/ find all instances...\n\t\tDCOPCStringList buf = theDC->registeredApplications();\n\t\tfor(DCOPCStringList::iterator i = buf.begin(); i != buf.end(); ++i)\n\t\t{\n\t\t\tQString program = QString::fromUtf8(*i);\n\t\t\tif(program.contains(r))\n\t\t\t\tprograms += program;\n\t\t}\n\t\tif(programs.size() > 1 && action.ifMulti() == IM_DONTSEND)\n\t\t\treturn false;\n\t\telse if(programs.size() > 1 && action.ifMulti() == IM_SENDTOTOP)\n\t\t{\tQ3ValueList<WId> s = KWinModule().stackingOrder();\n\t\t\t\/\/ go through all the (ordered) window pids\n\t\t\tfor(Q3ValueList<WId>::iterator i = s.fromLast(); i != s.end(); i--)\n\t\t\t{\tint p = KWin::windowInfo(*i,NET::WMPid).win();\n\t\t\t\tQString id = action.program() + \"-\" + QString().setNum(p);\n\t\t\t\tif(programs.contains(id))\n\t\t\t\t{\tprograms.clear();\n\t\t\t\t\tprograms += id;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile(programs.size() > 1) programs.remove(programs.begin());\n\t\t}\n\t\telse if(programs.size() > 1 && action.ifMulti() == IM_SENDTOBOTTOM)\n\t\t{\tQ3ValueList<WId> s = KWinModule().stackingOrder();\n\t\t\t\/\/ go through all the (ordered) window pids\n\t\t\tfor(Q3ValueList<WId>::iterator i = s.begin(); i != s.end(); ++i)\n\t\t\t{\tint p = KWin::windowInfo(*i,NET::WMPid).win();\n\t\t\t\tQString id = action.program() + \"-\" + QString().setNum(p);\n\t\t\t\tif(programs.contains(id))\n\t\t\t\t{\tprograms.clear();\n\t\t\t\t\tprograms += id;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile(programs.size() > 1) programs.remove(programs.begin());\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid IRKick::executeAction(const IRAction &action)\n{\n\tDCOPClient *theDC = KApplication::dcopClient();\n\tQStringList programs;\n\n\tif(!getPrograms(action, programs)) return;\n\n\t\/\/ if programs.size()==0 here, then the app is definately not running.\n\tif(action.autoStart() && !programs.size())\n\t{\tQString sname = ProfileServer::profileServer()->getServiceName(action.program());\n\t\tif(!sname.isNull())\n\t\t{\n\t\t\tKPassivePopup::message(\"IRKick\", i18n(\"Starting <b>%1<\/b>...\").arg(action.application()), SmallIcon(\"irkick\"), theTrayIcon);\n\t\t\tKApplication::startServiceByDesktopName(sname);\n\t\t}\n\t}\n\tif(action.isJustStart()) return;\n\n\tif(!getPrograms(action, programs)) return;\n\n\tfor(QStringList::iterator i = programs.begin(); i != programs.end(); ++i)\n\t{\tconst QString &program = *i;\n\t\tif(theDC->isApplicationRegistered(program.utf8()))\n\t\t{\tQByteArray data; QDataStream arg(&data, QIODevice::WriteOnly);\n arg.setVersion(QDataStream::Qt_3_1);\n\t\t\tkdDebug() << \"Sending data (\" << program << \", \" << action.object() << \", \" << action.method().prototypeNR() << endl;\n\t\t\tfor(Arguments::const_iterator j = action.arguments().begin(); j != action.arguments().end(); ++j)\n\t\t\t{\tkdDebug() << \"Got argument...\" << endl;\n\t\t\t\tswitch((*j).type())\n\t\t\t\t{\tcase QVariant::Int: arg << (*j).toInt(); break;\n\t\t\t\t\tcase QVariant::CString: arg << (*j).toCString(); break;\n\t\t\t\t\tcase QVariant::StringList: arg << (*j).toStringList(); break;\n\t\t\t\t\tcase QVariant::UInt: arg << (*j).toUInt(); break;\n\t\t\t\t\tcase QVariant::Bool: arg << (*j).toBool(); break;\n\t\t\t\t\tcase QVariant::Double: arg << (*j).toDouble(); break;\n\t\t\t\t\tdefault: arg << (*j).toString(); break;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttheDC->send(program.utf8(), action.object().utf8(), action.method().prototypeNR().utf8(), data);\n\t\t}\n\t}\n}\n\nvoid IRKick::gotMessage(const QString &theRemote, const QString &theButton, int theRepeatCounter)\n{\n\tkdDebug() << \"Got message: \" << theRemote << \": \" << theButton << \" (\" << theRepeatCounter << \")\" << endl;\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkickflash\"));\n\ttheFlashOff->start(200, true);\n\tif(!npApp.isNull())\n\t{\n\t\tQString theApp = npApp;\n\t\tnpApp = QString::null;\n\t\t\/\/ send notifier by DCOP to npApp\/npModule\/npMethod(theRemote, theButton);\n\t\tQByteArray data; QDataStream arg(&data, QIODevice::WriteOnly);\n arg.setVersion(QDataStream::Qt_3_1);\n\t\targ << theRemote << theButton;\n\t\tKApplication::dcopClient()->send(theApp.utf8(), npModule.utf8(), npMethod.utf8(), data);\n\t}\n\telse\n\t{\n\t\tif(currentModes[theRemote].isNull()) currentModes[theRemote] = \"\";\n\t\tIRAItList l = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton);\n\t\tif(!currentModes[theRemote].isEmpty())\n\t\t\tl += allActions.findByModeButton(Mode(theRemote, \"\"), theButton);\n\t\tbool doBefore = true, doAfter = false;\n\t\tfor(IRAItList::const_iterator i = l.begin(); i != l.end(); ++i)\n\t\t\tif((**i).isModeChange() && !theRepeatCounter)\n\t\t\t{\t\/\/ mode switch\n\t\t\t\tcurrentModes[theRemote] = (**i).modeChange();\n\t\t\t\tMode mode = allModes.getMode(theRemote, (**i).modeChange());\n\t\t\t\tupdateModeIcons();\n\t\t\t\tdoBefore = (**i).doBefore();\n\t\t\t\tdoAfter = (**i).doAfter();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tfor(int after = 0; after < 2; after++)\n\t\t{\tif(doBefore && !after || doAfter && after)\n\t\t\t\tfor(IRAItList::const_iterator i = l.begin(); i != l.end(); ++i)\n\t\t\t\t\tif(!(**i).isModeChange() && ((**i).repeat() || !theRepeatCounter))\n\t\t\t\t\t{\texecuteAction(**i);\n\t\t\t\t\t}\n\t\t\tif(!after && doAfter)\n\t\t\t{\tl = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton);\n\t\t\t\tif(!currentModes[theRemote].isEmpty())\n\t\t\t\t\tl += allActions.findByModeButton(Mode(theRemote, \"\"), theButton);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid IRKick::stealNextPress(QString app, QString module, QString method)\n{\n\tnpApp = app;\n\tnpModule = module;\n\tnpMethod = method;\n}\n\nvoid IRKick::dontStealNextPress()\n{\n\tnpApp = QString::null;\n}\n\n#include \"irkick.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestLabeledGeoView2D.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------*\/\n\/\/ .SECTION Description\n\n#include \"vtkCamera.h\"\n#include \"vtkGeoAlignedImageSource.h\"\n#include \"vtkGeoAlignedImageRepresentation.h\"\n#include \"vtkGeoFileImageSource.h\"\n#include \"vtkGeoFileTerrainSource.h\"\n#include \"vtkGeoGraphRepresentation2D.h\"\n#include \"vtkGeoProjectionSource.h\"\n#include \"vtkGeoRandomGraphSource.h\"\n#include \"vtkGeoTerrain2D.h\"\n#include \"vtkGeoTerrainNode.h\"\n#include \"vtkGeoView2D.h\"\n#include \"vtkJPEGReader.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStdString.h\"\n#include \"vtkTestUtilities.h\"\n\n#include <vtksys\/ios\/sstream>\n\nint TestLabeledGeoView2D(int argc, char* argv[])\n{\n int proj = 40;\n char* fname = vtkTestUtilities::ExpandDataFileName(\n argc, argv, \"Data\/NE2_ps_bath_small.jpg\");\n vtkStdString imageFile = fname;\n\n \/\/ Create the view\n vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New();\n vtkSmartPointer<vtkGeoView2D> view = vtkSmartPointer<vtkGeoView2D>::New();\n view->SetupRenderWindow(win);\n\n \/\/ Create the terrain\n vtkSmartPointer<vtkGeoTerrain2D> terrain =\n vtkSmartPointer<vtkGeoTerrain2D>::New();\n vtkSmartPointer<vtkGeoSource> terrainSource;\n vtkGeoProjectionSource* projSource = vtkGeoProjectionSource::New();\n projSource->SetProjection(proj);\n terrainSource.TakeReference(projSource);\n terrain->SetSource(terrainSource);\n view->SetSurface(terrain);\n\n \/\/ Create background image\n vtkSmartPointer<vtkGeoAlignedImageRepresentation> imageRep =\n vtkSmartPointer<vtkGeoAlignedImageRepresentation>::New();\n vtkSmartPointer<vtkGeoSource> imageSource;\n vtkGeoAlignedImageSource* alignedSource = vtkGeoAlignedImageSource::New();\n vtkSmartPointer<vtkJPEGReader> reader =\n vtkSmartPointer<vtkJPEGReader>::New();\n reader->SetFileName(imageFile.c_str());\n reader->Update();\n alignedSource->SetImage(reader->GetOutput());\n imageSource.TakeReference(alignedSource);\n imageRep->SetSource(imageSource);\n view->AddRepresentation(imageRep);\n\n vtkSmartPointer<vtkGeoRandomGraphSource> graphSource = \n vtkSmartPointer<vtkGeoRandomGraphSource>::New();\n graphSource->SetNumberOfVertices(500);\n vtkSmartPointer<vtkGeoGraphRepresentation2D> graphRep = \n vtkSmartPointer<vtkGeoGraphRepresentation2D>::New();\n\n graphRep->SetInputConnection(graphSource->GetOutputPort());\n graphRep->SetVertexLabelArrayName(\"latitude\");\n graphRep->SetUseLabelHierarchy(true);\n graphRep->SetVertexLabelVisibility(true);\n \n view->AddRepresentation(graphRep);\n\n \/\/ Set up the viewport\n win->SetSize(600, 600);\n vtkSmartPointer<vtkGeoTerrainNode> root =\n vtkSmartPointer<vtkGeoTerrainNode>::New();\n terrainSource->FetchRoot(root);\n double bounds[6];\n root->GetModel()->GetBounds(bounds);\n bounds[0] = bounds[0] - (bounds[1] - bounds[0])*0.01;\n bounds[1] = bounds[1] + (bounds[1] - bounds[0])*0.01;\n bounds[2] = bounds[2] - (bounds[3] - bounds[2])*0.01;\n bounds[3] = bounds[3] + (bounds[3] - bounds[2])*0.01;\n double scalex = (bounds[1] - bounds[0])\/2.0;\n double scaley = (bounds[3] - bounds[2])\/2.0;\n double scale = (scalex > scaley) ? scalex : scaley;\n \n view->GetRenderer()->ResetCamera();\n view->GetRenderer()->GetActiveCamera()->SetParallelScale(scale);\n\n view->Update();\n int retVal = vtkRegressionTestImage(win);\n if (retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n win->GetInteractor()->Initialize();\n win->GetInteractor()->Start();\n }\n\n terrainSource->ShutDown();\n imageSource->ShutDown();\n\n delete [] fname;\n return !retVal;\n}\n\n<commit_msg>BUG: change projection type to see if malloc bug in libproj4 on stops.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestLabeledGeoView2D.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------*\/\n\/\/ .SECTION Description\n\n#include \"vtkCamera.h\"\n#include \"vtkGeoAlignedImageSource.h\"\n#include \"vtkGeoAlignedImageRepresentation.h\"\n#include \"vtkGeoFileImageSource.h\"\n#include \"vtkGeoFileTerrainSource.h\"\n#include \"vtkGeoGraphRepresentation2D.h\"\n#include \"vtkGeoProjectionSource.h\"\n#include \"vtkGeoRandomGraphSource.h\"\n#include \"vtkGeoTerrain2D.h\"\n#include \"vtkGeoTerrainNode.h\"\n#include \"vtkGeoView2D.h\"\n#include \"vtkJPEGReader.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStdString.h\"\n#include \"vtkTestUtilities.h\"\n\n#include <vtksys\/ios\/sstream>\n\nint TestLabeledGeoView2D(int argc, char* argv[])\n{\n int proj = 35;\n char* fname = vtkTestUtilities::ExpandDataFileName(\n argc, argv, \"Data\/NE2_ps_bath_small.jpg\");\n vtkStdString imageFile = fname;\n\n \/\/ Create the view\n vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New();\n vtkSmartPointer<vtkGeoView2D> view = vtkSmartPointer<vtkGeoView2D>::New();\n view->SetupRenderWindow(win);\n\n \/\/ Create the terrain\n vtkSmartPointer<vtkGeoTerrain2D> terrain =\n vtkSmartPointer<vtkGeoTerrain2D>::New();\n vtkSmartPointer<vtkGeoSource> terrainSource;\n vtkGeoProjectionSource* projSource = vtkGeoProjectionSource::New();\n projSource->SetProjection(proj);\n terrainSource.TakeReference(projSource);\n terrain->SetSource(terrainSource);\n view->SetSurface(terrain);\n\n \/\/ Create background image\n vtkSmartPointer<vtkGeoAlignedImageRepresentation> imageRep =\n vtkSmartPointer<vtkGeoAlignedImageRepresentation>::New();\n vtkSmartPointer<vtkGeoSource> imageSource;\n vtkGeoAlignedImageSource* alignedSource = vtkGeoAlignedImageSource::New();\n vtkSmartPointer<vtkJPEGReader> reader =\n vtkSmartPointer<vtkJPEGReader>::New();\n reader->SetFileName(imageFile.c_str());\n reader->Update();\n alignedSource->SetImage(reader->GetOutput());\n imageSource.TakeReference(alignedSource);\n imageRep->SetSource(imageSource);\n view->AddRepresentation(imageRep);\n\n vtkSmartPointer<vtkGeoRandomGraphSource> graphSource = \n vtkSmartPointer<vtkGeoRandomGraphSource>::New();\n graphSource->SetNumberOfVertices(500);\n vtkSmartPointer<vtkGeoGraphRepresentation2D> graphRep = \n vtkSmartPointer<vtkGeoGraphRepresentation2D>::New();\n\n graphRep->SetInputConnection(graphSource->GetOutputPort());\n graphRep->SetVertexLabelArrayName(\"latitude\");\n graphRep->SetUseLabelHierarchy(true);\n graphRep->SetVertexLabelVisibility(true);\n \n view->AddRepresentation(graphRep);\n\n \/\/ Set up the viewport\n win->SetSize(600, 600);\n vtkSmartPointer<vtkGeoTerrainNode> root =\n vtkSmartPointer<vtkGeoTerrainNode>::New();\n terrainSource->FetchRoot(root);\n double bounds[6];\n root->GetModel()->GetBounds(bounds);\n bounds[0] = bounds[0] - (bounds[1] - bounds[0])*0.01;\n bounds[1] = bounds[1] + (bounds[1] - bounds[0])*0.01;\n bounds[2] = bounds[2] - (bounds[3] - bounds[2])*0.01;\n bounds[3] = bounds[3] + (bounds[3] - bounds[2])*0.01;\n double scalex = (bounds[1] - bounds[0])\/2.0;\n double scaley = (bounds[3] - bounds[2])\/2.0;\n double scale = (scalex > scaley) ? scalex : scaley;\n \n view->GetRenderer()->ResetCamera();\n view->GetRenderer()->GetActiveCamera()->SetParallelScale(scale);\n\n view->Update();\n int retVal = vtkRegressionTestImage(win);\n if (retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n win->GetInteractor()->Initialize();\n win->GetInteractor()->Start();\n }\n\n terrainSource->ShutDown();\n imageSource->ShutDown();\n\n delete [] fname;\n return !retVal;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"world.hh\"\n#include \"actor.hh\"\n#include \"common.hh\"\n\nvoid World::generate(int seed) {\n\tsrand(seed);\n\tcreateCity(10, 10);\n}\n\nActor& World::addActor(Actor* actor) {\n\tactors.push_back(actor);\n\tactors.back().setWorld(this);\n\treturn actors.back();\n}\n\n\/\/\/ Function: updateView\n\/\/\/ Updates the Actor's view.\nvoid World::updateView(Actor& actor) {\n\ttilearray& view = actor.getView();\n\tfor (int j = actor.y - viewYDist; j <= actor.y + viewYDist; j++) {\n\t\tfor (int i = actor.x - viewXDist; i <= actor.x + viewXDist; i++) {\n\t\t\tif (i < 0 || j < 0 || i >= width || j >= height) continue;\n\t\t\tbool visible = hasLOS(actor, i, j);\n\t\t\tbool explored = visible ? true : actor.hasExplored(i,j);\n\t\t\tTile& tile = view[j][i];\n\t\t\tif (visible || explored) tile = getTile(i, j);\n\t\t\tif (!visible) tile.actor = NULL;\n\t\t\ttile.visible = visible;\n\t\t\ttile.explored = explored;\n\t\t}\n\t}\n}\n\n\/\/\/ Function updateVisibleActors\n\/\/\/ Updates all visibile actors lists of all actors\nvoid World::updateVisibleActors() {\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); it++) {\n\t\tit->visible_actors.clear();\n\t}\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); it++) {\n\t\tfor (Actors::iterator it2 = actors.begin(); it2 != actors.end(); it2++) {\n\t\t\tif (it == it2) continue;\n\t\t\tif (it->getConstView()[it2->y][it2->x].visible) {\n\t\t\t\tit->visible_actors.push_back(&(*it2));\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/\/ Function: hasLOS\n\/\/\/ Tests if given coordinates are visible for a player.\nbool World::hasLOS(const Actor& actor, int x, int y) const {\n\tfloat dist = distance2d(float(x), float(y), float(actor.x), float(actor.y));\n\n\tif (dist > actor.viewDist) return false; \/\/ Out of reach\n\tif (x < 0 || y < 0 || x >= width || y >= height) return false; \/\/ Out of world\n\tif (dist <= 1.5) return true; \/\/ Very close\n\n\tfloat dx = float(x - actor.x) \/ (dist * 2.0);\n\tfloat dy = float(y - actor.y) \/ (dist * 2.0);\n\tfloat xx = actor.x + dx;\n\tfloat yy = actor.y + dy;\n\tfloat dd = distance2d(0.0f,0.0f,dx,dy);\n\tfloat d = 0.5 + dd;\n\tdo {\n\t\tif (d > getTile(round(xx), round(yy)).blocks_vision_dist) return false;\n\t\txx += dx; yy += dy; d += dd;\n\t} while (distance2d(float(x), float(y), xx, yy) > 0.5);\n\treturn true;\n}\n\n\/\/\/ Function: update\n\/\/\/ Updates the world - views, visibilities and AI\nvoid World::update(bool skipAI) {\n\t\/\/ Reset tiles' actor pointers\n\tint w = getWidth(), h = getHeight();\n\tfor (int j = 0; j < h; j++)\n\t\tfor (int i = 0; i < w; i++) tiles[j][i].actor = NULL;\n\t\/\/ Update tiles' actor pointers\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); ++it)\n\t\ttiles[it->y][it->x].actor = &(*it);\n\t\/\/ Update views\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); ++it)\n\t\tupdateView(*it);\n\t\/\/ Update visible actors\n\tupdateVisibleActors();\n\t\/\/ Do AI\n\tif (skipAI) return;\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); ++it)\n\t\tif (it->useAI) it->AI();\n}\n\n\/\/\/ Function: draw\n\/\/\/ Draws the world with actors.\nvoid World::draw(Actor& actor) {\n\t\/\/ Cls\n\twerase(worldwin);\n\t\/\/ Border\n\twattroff(worldwin, A_BOLD);\n\twcolor_set(worldwin, COLOR_GREEN, 0);\n\tbox(worldwin, 0 , 0);\n\t\/\/ Tiles\n\tconst tilearray& view = actor.getConstView();\n\tfor (int j = actor.y - viewYDist; j <= actor.y + viewYDist; j++) {\n\t\tfor (int i = actor.x - viewXDist; i <= actor.x + viewXDist; i++) {\n\t\t\tTile tile;\n\t\t\tif (i >= 0 && j >= 0 && i < width && j < height) tile = view[j][i];\n\t\t\tif (tile.visible) wattron(worldwin, A_BOLD);\n\t\t\telse wattroff(worldwin, A_BOLD);\n\t\t\twcolor_set(worldwin, tile.color, 0);\n\t\t\tmvwaddch(worldwin, y2scr(j, actor.y), x2scr(i, actor.x), tile.ch);\n\t\t}\n\t}\n\t\/\/ ActorPtrs\n\tfor (ActorPtrs::const_iterator it = actor.visible_actors.begin(); it != actor.visible_actors.end(); ++it) {\n\t\tsetColor(worldwin, (*it)->getColor());\n\t\tmvwaddch(worldwin, y2scr((*it)->y, actor.y),\n\t\t\t\t\t\t x2scr((*it)->x, actor.x), (*it)->getChar());\n\t}\n\t\/\/ Player\n\tsetColor(worldwin, actor.getColor());\n\tmvwaddch(worldwin, y2scr(actor.y, actor.y),\n\t\t\t\t\t x2scr(actor.x, actor.x), actor.getChar());\n\t\/\/ Flush\n\twrefresh(worldwin);\n}\n<commit_msg>Much better FOV algorithm.<commit_after>#include \"world.hh\"\n#include \"actor.hh\"\n#include \"common.hh\"\n\nnamespace {\n\t\/\/ FOV algorithm from reflexivelos roguelike engine under MIT License.\n\t\/\/ Based on generalization of Bresenham, runs in O(N^3).\n\tvoid fov_dir(int dir, int dis, int px, int py, tilearray& view, World& world) {\n\t\tint cx, cy;\n\t\tfor (int q = 1; q <= dis; ++q) for (int p = 0; p < q+1; p++) {\n\t\t\tfor (int ad1 = 1, ad2[2] = {0, 0}, s[2] = {0, q-1}, eps[2] = {0, q-1}; ad1 <= dis && s[0] <= s[1]; ++ad1)\n\t\t\t for (int i = 0; i < 2; i++) {\n\t\t\t\teps[i] += p;\n\t\t\t\tif (eps[i] >= q) { \/\/ This should look familiar\n\t\t\t\t\teps[i] -= q;\n\t\t\t\t\t++ad2[i];\n\t\t\t\t}\n\t\t\t\tcx = ad1, cy = ad2[i];\n\t\t\t\tif (dir&1) cx = -cx;\n\t\t\t\tif (dir&2) cy = -cy;\n\t\t\t\tif (dir&4) cx ^= cy ^= cx ^= cy;\n\t\t\t\tcx += px, cy += py;\n\t\t\t\tint d = (cx-px)*(cx-px) + (cy-py)*(cy-py); \/\/ Squared distance from origin\n\t\t\t\t\/\/ Visible\n\t\t\t\tif (!(cx < 0 || cy < 0 || cx >= world.getWidth() || cy >= world.getHeight())) {\n\t\t\t\t\tif (d <= dis*dis + 1) {\n\t\t\t\t\t\tview[cy][cx] = world.getTile(cx, cy);\n\t\t\t\t\t\tview[cy][cx].explored = true;\n\t\t\t\t\t\tview[cy][cx].visible = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Update range of possibilities for s\n\t\t\t\tint dd = world.getTile(cx, cy).blocks_vision_dist;\n\t\t\t\tif (d > dd*dd) { \/\/ if blocks_vision\n\t\t\t\t\tif (i == 0) s[i] += q-eps[i], eps[i] = 0, ++ad2[0];\n\t\t\t\t\tif (i == 1) s[i] -= eps[i]+1, eps[i] = q-1, --ad2[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid World::generate(int seed) {\n\tsrand(seed);\n\tcreateCity(10, 10);\n}\n\nActor& World::addActor(Actor* actor) {\n\tactors.push_back(actor);\n\tactors.back().setWorld(this);\n\treturn actors.back();\n}\n\n\/\/\/ Function: updateView\n\/\/\/ Updates the Actor's view.\nvoid World::updateView(Actor& actor) {\n\ttilearray& view = actor.getView();\n\t\/\/ Reset light\n\tfor (int j = actor.y - viewYDist; j <= actor.y + viewYDist; j++) {\n\t\tfor (int i = actor.x - viewXDist; i <= actor.x + viewXDist; i++) {\n\t\t\tif (i < 0 || j < 0 || i >= width || j >= height) continue;\n\t\t\tview[j][i].visible = false;\n\t\t}\n\t}\n\t\/\/ Calculate FOV\n\tfor (int i = 0; i < 8; ++i) fov_dir(i, actor.viewDist, actor.x, actor.y, view, *this);\n}\n\n\/\/\/ Function updateVisibleActors\n\/\/\/ Updates all visibile actors lists of all actors\nvoid World::updateVisibleActors() {\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); it++) {\n\t\tit->visible_actors.clear();\n\t}\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); it++) {\n\t\tfor (Actors::iterator it2 = actors.begin(); it2 != actors.end(); it2++) {\n\t\t\tif (it == it2) continue;\n\t\t\tif (it->getConstView()[it2->y][it2->x].visible) {\n\t\t\t\tit->visible_actors.push_back(&(*it2));\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/\/ Function: hasLOS\n\/\/\/ Tests if given coordinates are visible for a player.\nbool World::hasLOS(const Actor& actor, int x, int y) const {\n\tfloat dist = distance2d(float(x), float(y), float(actor.x), float(actor.y));\n\n\tif (dist > actor.viewDist) return false; \/\/ Out of reach\n\tif (x < 0 || y < 0 || x >= width || y >= height) return false; \/\/ Out of world\n\tif (dist <= 1.5) return true; \/\/ Very close\n\n\tfloat dx = float(x - actor.x) \/ (dist * 2.0);\n\tfloat dy = float(y - actor.y) \/ (dist * 2.0);\n\tfloat xx = actor.x + dx;\n\tfloat yy = actor.y + dy;\n\tfloat dd = distance2d(0.0f,0.0f,dx,dy);\n\tfloat d = 0.5 + dd;\n\tdo {\n\t\tif (d > getTile(round(xx), round(yy)).blocks_vision_dist) return false;\n\t\txx += dx; yy += dy; d += dd;\n\t} while (distance2d(float(x), float(y), xx, yy) > 0.5);\n\treturn true;\n}\n\n\/\/\/ Function: update\n\/\/\/ Updates the world - views, visibilities and AI\nvoid World::update(bool skipAI) {\n\t\/\/ Reset tiles' actor pointers\n\tint w = getWidth(), h = getHeight();\n\tfor (int j = 0; j < h; j++)\n\t\tfor (int i = 0; i < w; i++) tiles[j][i].actor = NULL;\n\t\/\/ Update tiles' actor pointers\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); ++it)\n\t\ttiles[it->y][it->x].actor = &(*it);\n\t\/\/ Update views\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); ++it)\n\t\tupdateView(*it);\n\t\/\/ Update visible actors\n\tupdateVisibleActors();\n\t\/\/ Do AI\n\tif (skipAI) return;\n\tfor (Actors::iterator it = actors.begin(); it != actors.end(); ++it)\n\t\tif (it->useAI) it->AI();\n}\n\n\/\/\/ Function: draw\n\/\/\/ Draws the world with actors.\nvoid World::draw(Actor& actor) {\n\t\/\/ Cls\n\twerase(worldwin);\n\t\/\/ Border\n\twattroff(worldwin, A_BOLD);\n\twcolor_set(worldwin, COLOR_GREEN, 0);\n\tbox(worldwin, 0 , 0);\n\t\/\/ Tiles\n\tconst tilearray& view = actor.getConstView();\n\tfor (int j = actor.y - viewYDist; j <= actor.y + viewYDist; j++) {\n\t\tfor (int i = actor.x - viewXDist; i <= actor.x + viewXDist; i++) {\n\t\t\tTile tile;\n\t\t\tif (i >= 0 && j >= 0 && i < width && j < height) tile = view[j][i];\n\t\t\tif (tile.visible) wattron(worldwin, A_BOLD);\n\t\t\telse wattroff(worldwin, A_BOLD);\n\t\t\twcolor_set(worldwin, tile.color, 0);\n\t\t\tmvwaddch(worldwin, y2scr(j, actor.y), x2scr(i, actor.x), tile.ch);\n\t\t}\n\t}\n\t\/\/ ActorPtrs\n\tfor (ActorPtrs::const_iterator it = actor.visible_actors.begin(); it != actor.visible_actors.end(); ++it) {\n\t\tsetColor(worldwin, (*it)->getColor());\n\t\tmvwaddch(worldwin, y2scr((*it)->y, actor.y),\n\t\t\t\t\t\t x2scr((*it)->x, actor.x), (*it)->getChar());\n\t}\n\t\/\/ Player\n\tsetColor(worldwin, actor.getColor());\n\tmvwaddch(worldwin, y2scr(actor.y, actor.y),\n\t\t\t\t\t x2scr(actor.x, actor.x), actor.getChar());\n\t\/\/ Flush\n\twrefresh(worldwin);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"TerrainChunkRenderer.h\"\n#include \"GL3DProgram.h\"\n#include \"TerrainChunk.h\"\n\nTerrainChunkRenderer::TerrainChunkRenderer() {\n\t\n}\nTerrainChunkRenderer::~TerrainChunkRenderer() {\n\t\/\/Destroy all the render slots\n\tfor (auto slot : renderSlots) \n\t\tdelete slot.second;\n\tfor (auto slot : openSlots)\n\t\tdelete slot;\n}\n\t\nTerrainChunkRenderer::HotChunk::HotChunk() {\n\tglGenBuffers(1,&vertexData);\n\tglGenVertexArrays(1,&vertexArrayBuffer);\n}\nTerrainChunkRenderer::HotChunk::~HotChunk() {\n\tglDeleteBuffers(1,&vertexData);\n\tglDeleteVertexArrays(1,&vertexArrayBuffer);\n}\n\/\/Render the set chunk\nvoid TerrainChunkRenderer::HotChunk::Render(GL3DProgram * shader) {\n\tglBindVertexArray ( vertexArrayBuffer );\n\tglBindBuffer ( GL_ARRAY_BUFFER, vertexData );\n\tglVertexAttribPointer ( shader->AttributeVertex(), 3, GL_FLOAT, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,Vertex) );\n\tglVertexAttribPointer ( shader->AttributeTexture(), 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,TextureCoordinateX) );\n\tglDrawArrays( GL_TRIANGLES, 0, vertexCount);\n}\nvoid TerrainChunkRenderer::HotChunk::Set(TerrainChunk * chunk, GL3DProgram * shader) {\n\tvertexCount = chunk->VertexDataSize;\n\n\tglBindVertexArray ( vertexArrayBuffer );\n\t\/\/vertex positions\n\tglBindBuffer ( GL_ARRAY_BUFFER, vertexData );\n\tglBufferData ( GL_ARRAY_BUFFER, vertexCount*sizeof(TerrainChunk::ChunkVertexData), chunk->VertexData, GL_STATIC_DRAW );\n\tglEnableVertexAttribArray ( shader->AttributeVertex() );\n\tglVertexAttribPointer ( shader->AttributeVertex(), 3, GL_FLOAT, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,Vertex) );\n\tglEnableVertexAttribArray ( shader->AttributeTexture() );\n\tglVertexAttribPointer ( shader->AttributeTexture(), 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,TextureCoordinateX) );\n\n\t\/\/glVertexAttribPointer ( shader->AttributeTexture(), 1, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,TextureCoordinate) );\n\t\n}\n\nvoid TerrainChunkRenderer::StartRendering(GL3DProgram * shader) {\n\n}\n\nvoid TerrainChunkRenderer::RenderTerrainChunk(vec2 tilePos, TerrainChunk * chunk, GL3DProgram * shader) {\n\t\/\/Draw the chunk relative to itself\n\tshader->Model.PushMatrix();\n\tshader->Model.Translate(chunk->X,chunk->Y,0);\n\tshader->Model.Apply();\n\n\t\/\/Check if this chunk is already buffered\n\tvec2 chunkPosition = tilePos+vec2(chunk->X,chunk->Y);\n\tauto slotIterator = renderSlots.find(chunkPosition);\n\tHotChunk * renderer;\n\tif (slotIterator == renderSlots.end()) {\n\t\t\/\/Doesn't exist, buffer it\n\t\t\/\/find an open slot\n\t\tHotChunk * openSlot;\n\t\tif (openSlots.size() > 0) {\n\t\t\topenSlot = openSlots.back();\n\t\t\topenSlots.pop_back();\n\t\t}\n\t\telse\n\t\t\topenSlot = new HotChunk();\n\n\t\t\/\/Set the slot to hold the given chunk\n\t\topenSlot->Set(chunk,shader);\n\n\t\t\/\/Save the slot as in use\n\t\trenderSlots[chunkPosition] = openSlot;\n\t\trenderer = openSlot;\n\t}\n\telse\n\t\trenderer = slotIterator->second;\n\n\t\/\/Run the renderer\n\trenderer->Render(shader);\n\t\/\/Mark it as used\n\trenderer->Rendered = true;\n\n\tshader->Model.PopMatrix();\n}\n\n\nvoid TerrainChunkRenderer::FinishRendering(GL3DProgram * shader) {\n\t\/\/Find renderers which were not used and mark them as free\n\tfor (auto it = renderSlots.begin(); it != renderSlots.end();) {\n\t\tif (it->second->Rendered) {\n\t\t\tit->second->Rendered = false;\n\t\t\tit++;\n\t\t}\n\t\telse {\n\t\t\topenSlots.push_back(it->second);\n\t\t\tit = renderSlots.erase(it);\n\t\t}\n\t}\n}<commit_msg>Added a check to make sure vertex data is packing correctly<commit_after>#include \"stdafx.h\"\n#include \"TerrainChunkRenderer.h\"\n#include \"GL3DProgram.h\"\n#include \"TerrainChunk.h\"\n\nTerrainChunkRenderer::TerrainChunkRenderer() {\n\tcout << \"Chunk vertex data size: \" << sizeof(TerrainChunk::ChunkVertexData) << \"\\n\";\n}\nTerrainChunkRenderer::~TerrainChunkRenderer() {\n\t\/\/Destroy all the render slots\n\tfor (auto slot : renderSlots) \n\t\tdelete slot.second;\n\tfor (auto slot : openSlots)\n\t\tdelete slot;\n}\n\t\nTerrainChunkRenderer::HotChunk::HotChunk() {\n\tglGenBuffers(1,&vertexData);\n\tglGenVertexArrays(1,&vertexArrayBuffer);\n}\nTerrainChunkRenderer::HotChunk::~HotChunk() {\n\tglDeleteBuffers(1,&vertexData);\n\tglDeleteVertexArrays(1,&vertexArrayBuffer);\n}\n\/\/Render the set chunk\nvoid TerrainChunkRenderer::HotChunk::Render(GL3DProgram * shader) {\n\tglBindVertexArray ( vertexArrayBuffer );\n\tglBindBuffer ( GL_ARRAY_BUFFER, vertexData );\n\tglVertexAttribPointer ( shader->AttributeVertex(), 3, GL_FLOAT, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,Vertex) );\n\tglVertexAttribPointer ( shader->AttributeTexture(), 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,TextureCoordinateX) );\n\tglDrawArrays( GL_TRIANGLES, 0, vertexCount);\n}\nvoid TerrainChunkRenderer::HotChunk::Set(TerrainChunk * chunk, GL3DProgram * shader) {\n\tvertexCount = chunk->VertexDataSize;\n\n\tglBindVertexArray ( vertexArrayBuffer );\n\t\/\/vertex positions\n\tglBindBuffer ( GL_ARRAY_BUFFER, vertexData );\n\tglBufferData ( GL_ARRAY_BUFFER, vertexCount*sizeof(TerrainChunk::ChunkVertexData), chunk->VertexData, GL_STATIC_DRAW );\n\tglEnableVertexAttribArray ( shader->AttributeVertex() );\n\tglVertexAttribPointer ( shader->AttributeVertex(), 3, GL_FLOAT, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,Vertex) );\n\tglEnableVertexAttribArray ( shader->AttributeTexture() );\n\tglVertexAttribPointer ( shader->AttributeTexture(), 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,TextureCoordinateX) );\n\n\t\/\/glVertexAttribPointer ( shader->AttributeTexture(), 1, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,TextureCoordinate) );\n\t\n}\n\nvoid TerrainChunkRenderer::StartRendering(GL3DProgram * shader) {\n\n}\n\nvoid TerrainChunkRenderer::RenderTerrainChunk(vec2 tilePos, TerrainChunk * chunk, GL3DProgram * shader) {\n\t\/\/Draw the chunk relative to itself\n\tshader->Model.PushMatrix();\n\tshader->Model.Translate(chunk->X,chunk->Y,0);\n\tshader->Model.Apply();\n\n\t\/\/Check if this chunk is already buffered\n\tvec2 chunkPosition = tilePos+vec2(chunk->X,chunk->Y);\n\tauto slotIterator = renderSlots.find(chunkPosition);\n\tHotChunk * renderer;\n\tif (slotIterator == renderSlots.end()) {\n\t\t\/\/Doesn't exist, buffer it\n\t\t\/\/find an open slot\n\t\tHotChunk * openSlot;\n\t\tif (openSlots.size() > 0) {\n\t\t\topenSlot = openSlots.back();\n\t\t\topenSlots.pop_back();\n\t\t}\n\t\telse\n\t\t\topenSlot = new HotChunk();\n\n\t\t\/\/Set the slot to hold the given chunk\n\t\topenSlot->Set(chunk,shader);\n\n\t\t\/\/Save the slot as in use\n\t\trenderSlots[chunkPosition] = openSlot;\n\t\trenderer = openSlot;\n\t}\n\telse\n\t\trenderer = slotIterator->second;\n\n\t\/\/Run the renderer\n\trenderer->Render(shader);\n\t\/\/Mark it as used\n\trenderer->Rendered = true;\n\n\tshader->Model.PopMatrix();\n}\n\n\nvoid TerrainChunkRenderer::FinishRendering(GL3DProgram * shader) {\n\t\/\/Find renderers which were not used and mark them as free\n\tfor (auto it = renderSlots.begin(); it != renderSlots.end();) {\n\t\tif (it->second->Rendered) {\n\t\t\tit->second->Rendered = false;\n\t\t\tit++;\n\t\t}\n\t\telse {\n\t\t\topenSlots.push_back(it->second);\n\t\t\tit = renderSlots.erase(it);\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ Copyright (c) 2008-2013 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Engine.h\"\r\n#include \"Camera.h\"\r\n#include \"CoreEvents.h\"\r\n#include \"Font.h\"\r\n#include \"Graphics.h\"\r\n#include \"Input.h\"\r\n#include \"Material.h\"\r\n#include \"Model.h\"\r\n#include \"Octree.h\"\r\n#include \"Renderer.h\"\r\n#include \"ResourceCache.h\"\r\n#include \"StaticModel.h\"\r\n#include \"Text.h\"\r\n#include \"UI.h\"\r\n\r\n#include \"StaticScene.h\"\r\n\r\n#include \"DebugNew.h\"\r\n\r\n\/\/ Expands to this example's entry-point\r\nDEFINE_APPLICATION_MAIN(StaticScene)\r\n\r\nStaticScene::StaticScene(Context* context) :\r\n Sample(context),\r\n yaw_(0.0f),\r\n pitch_(0.0f)\r\n{\r\n}\r\n\r\nvoid StaticScene::Start()\r\n{\r\n \/\/ Execute base class startup\r\n Sample::Start();\r\n\r\n \/\/ Create the scene content\r\n CreateScene();\r\n \r\n \/\/ Create the UI content\r\n CreateInstructions();\r\n \r\n \/\/ Setup the viewport for displaying the scene\r\n SetupViewport();\r\n\r\n \/\/ Hook up to the frame update events\r\n SubscribeToEvents();\r\n}\r\n\r\nvoid StaticScene::CreateScene()\r\n{\r\n ResourceCache* cache = GetSubsystem<ResourceCache>();\r\n \r\n scene_ = new Scene(context_);\r\n \r\n \/\/ Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will\r\n \/\/ show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it\r\n \/\/ is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically\r\n \/\/ optimizing manner\r\n scene_->CreateComponent<Octree>();\r\n \r\n \/\/ Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple \r\n \/\/ plane mesh with a \"stone\" material. Note that naming the scene nodes is optional. Scale the scene node larger\r\n \/\/ (100 x 100 world units)\r\n Node* planeNode = scene_->CreateChild(\"Plane\");\r\n StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();\r\n planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));\r\n planeObject->SetModel(cache->GetResource<Model>(\"Models\/Plane.mdl\"));\r\n planeObject->SetMaterial(cache->GetResource<Material>(\"Materials\/Stone.xml\"));\r\n \r\n \/\/ Create a directional light to the world so that we can see something. The light scene node's orientation controls the\r\n \/\/ light direction; we will use the SetDirection() function which calculates the orientation from a forward direction vector.\r\n \/\/ The light will use default settings (white light, no shadows)\r\n Node* lightNode = scene_->CreateChild(\"Directional light\");\r\n lightNode->SetDirection(Vector3(-1.0f, -1.0f, -1.0f)); \/\/ The direction vector does not need to be normalized\r\n Light* light = lightNode->CreateComponent<Light>();\r\n light->SetLightType(LIGHT_DIRECTIONAL);\r\n \r\n \/\/ Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a\r\n \/\/ quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains\r\n \/\/ LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll\r\n \/\/ see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the\r\n \/\/ same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the\r\n \/\/ scene.\r\n const unsigned NUM_OBJECTS = 200;\r\n for (unsigned i = 0; i < NUM_OBJECTS; ++i)\r\n {\r\n Node* mushroomNode = scene_->CreateChild(\"Mushroom\");\r\n StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();\r\n mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));\r\n mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));\r\n mushroomNode->SetScale(1.0f + Random(1.0f));\r\n mushroomObject->SetModel(cache->GetResource<Model>(\"Models\/Mushroom.mdl\"));\r\n mushroomObject->SetMaterial(cache->GetResource<Material>(\"Materials\/Mushroom.xml\"));\r\n }\r\n \r\n \/\/ Create a scene node for the camera, which we will move around\r\n \/\/ The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)\r\n cameraNode_ = scene_->CreateChild(\"Camera\");\r\n cameraNode_->CreateComponent<Camera>();\r\n \r\n \/\/ Set an initial position for the camera scene node above the plane\r\n cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));\r\n}\r\n\r\nvoid StaticScene::CreateInstructions()\n{\n ResourceCache* cache = GetSubsystem<ResourceCache>();\n UI* ui = GetSubsystem<UI>();\n \n \/\/ Construct new Text object, set string to display and font to use\n Text* instructionText = ui->GetRoot()->CreateChild<Text>();\n instructionText->SetText(\"Use WASD keys and mouse to move\");\n instructionText->SetFont(cache->GetResource<Font>(\"Fonts\/Anonymous Pro.ttf\"), 15);\n \n \/\/ Position the text relative to the screen center\n instructionText->SetHorizontalAlignment(HA_CENTER);\n instructionText->SetVerticalAlignment(VA_CENTER);\n instructionText->SetPosition(0, ui->GetRoot()->GetHeight() \/ 4);\n}\r\n\r\nvoid StaticScene::SetupViewport()\r\n{\r\n Renderer* renderer = GetSubsystem<Renderer>();\r\n \r\n \/\/ Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera\r\n \/\/ at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward \/ deferred) to\r\n \/\/ use, but now we just use full screen and default render path configured in the engine command line options\r\n SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));\r\n renderer->SetViewport(0, viewport);\r\n}\r\n\r\nvoid StaticScene::MoveCamera(float timeStep)\r\n{\r\n Input* input = GetSubsystem<Input>();\r\n \r\n \/\/ Movement speed as world units per second\r\n const float MOVE_SPEED = 20.0f;\r\n \/\/ Mouse sensitivity as degrees per pixel\r\n const float MOUSE_SENSITIVITY = 0.1f;\r\n \r\n \/\/ Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees\r\n IntVector2 mouseMove = input->GetMouseMove();\r\n yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;\r\n pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;\r\n pitch_ = Clamp(pitch_, -90.0f, 90.0f);\r\n \r\n \/\/ Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero.\r\n cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));\r\n \r\n \/\/ Read WASD keys and move the camera scene node to the corresponding direction if they are pressed\r\n \/\/ Use the TranslateRelative() function to move relative to the node's orientation. Alternatively we could\r\n \/\/ multiply the desired direction with the node's orientation quaternion, and use just Translate()\r\n if (input->GetKeyDown('W'))\r\n cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('S'))\r\n cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('A'))\r\n cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('D'))\r\n cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);\r\n}\r\n\r\nvoid StaticScene::SubscribeToEvents()\r\n{\r\n \/\/ Subscribes HandleUpdate() method for processing update events\r\n SubscribeToEvent(E_UPDATE, HANDLER(StaticScene, HandleUpdate));\r\n}\r\n\r\nvoid StaticScene::HandleUpdate(StringHash eventType, VariantMap& eventData)\r\n{\r\n \/\/ Event parameters are always defined inside a namespace corresponding to the event's name\r\n using namespace Update;\r\n\r\n \/\/ Take the frame time step, which is stored as a float\r\n float timeStep = eventData[P_TIMESTEP].GetFloat();\r\n \r\n \/\/ Move the camera, scale movement with time step\r\n MoveCamera(timeStep);\r\n}\r\n<commit_msg>Disable camera controls when the UI has a focused element.<commit_after>\/\/\r\n\/\/ Copyright (c) 2008-2013 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Engine.h\"\r\n#include \"Camera.h\"\r\n#include \"CoreEvents.h\"\r\n#include \"Font.h\"\r\n#include \"Graphics.h\"\r\n#include \"Input.h\"\r\n#include \"Material.h\"\r\n#include \"Model.h\"\r\n#include \"Octree.h\"\r\n#include \"Renderer.h\"\r\n#include \"ResourceCache.h\"\r\n#include \"StaticModel.h\"\r\n#include \"Text.h\"\r\n#include \"UI.h\"\r\n\r\n#include \"StaticScene.h\"\r\n\r\n#include \"DebugNew.h\"\r\n\r\n\/\/ Expands to this example's entry-point\r\nDEFINE_APPLICATION_MAIN(StaticScene)\r\n\r\nStaticScene::StaticScene(Context* context) :\r\n Sample(context),\r\n yaw_(0.0f),\r\n pitch_(0.0f)\r\n{\r\n}\r\n\r\nvoid StaticScene::Start()\r\n{\r\n \/\/ Execute base class startup\r\n Sample::Start();\r\n\r\n \/\/ Create the scene content\r\n CreateScene();\r\n \r\n \/\/ Create the UI content\r\n CreateInstructions();\r\n \r\n \/\/ Setup the viewport for displaying the scene\r\n SetupViewport();\r\n\r\n \/\/ Hook up to the frame update events\r\n SubscribeToEvents();\r\n}\r\n\r\nvoid StaticScene::CreateScene()\r\n{\r\n ResourceCache* cache = GetSubsystem<ResourceCache>();\r\n \r\n scene_ = new Scene(context_);\r\n \r\n \/\/ Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will\r\n \/\/ show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it\r\n \/\/ is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically\r\n \/\/ optimizing manner\r\n scene_->CreateComponent<Octree>();\r\n \r\n \/\/ Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple \r\n \/\/ plane mesh with a \"stone\" material. Note that naming the scene nodes is optional. Scale the scene node larger\r\n \/\/ (100 x 100 world units)\r\n Node* planeNode = scene_->CreateChild(\"Plane\");\r\n StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();\r\n planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));\r\n planeObject->SetModel(cache->GetResource<Model>(\"Models\/Plane.mdl\"));\r\n planeObject->SetMaterial(cache->GetResource<Material>(\"Materials\/Stone.xml\"));\r\n \r\n \/\/ Create a directional light to the world so that we can see something. The light scene node's orientation controls the\r\n \/\/ light direction; we will use the SetDirection() function which calculates the orientation from a forward direction vector.\r\n \/\/ The light will use default settings (white light, no shadows)\r\n Node* lightNode = scene_->CreateChild(\"Directional light\");\r\n lightNode->SetDirection(Vector3(-1.0f, -1.0f, -1.0f)); \/\/ The direction vector does not need to be normalized\r\n Light* light = lightNode->CreateComponent<Light>();\r\n light->SetLightType(LIGHT_DIRECTIONAL);\r\n \r\n \/\/ Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a\r\n \/\/ quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains\r\n \/\/ LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll\r\n \/\/ see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the\r\n \/\/ same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the\r\n \/\/ scene.\r\n const unsigned NUM_OBJECTS = 200;\r\n for (unsigned i = 0; i < NUM_OBJECTS; ++i)\r\n {\r\n Node* mushroomNode = scene_->CreateChild(\"Mushroom\");\r\n StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();\r\n mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));\r\n mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));\r\n mushroomNode->SetScale(1.0f + Random(1.0f));\r\n mushroomObject->SetModel(cache->GetResource<Model>(\"Models\/Mushroom.mdl\"));\r\n mushroomObject->SetMaterial(cache->GetResource<Material>(\"Materials\/Mushroom.xml\"));\r\n }\r\n \r\n \/\/ Create a scene node for the camera, which we will move around\r\n \/\/ The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)\r\n cameraNode_ = scene_->CreateChild(\"Camera\");\r\n cameraNode_->CreateComponent<Camera>();\r\n \r\n \/\/ Set an initial position for the camera scene node above the plane\r\n cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));\r\n}\r\n\r\nvoid StaticScene::CreateInstructions()\r\n{\r\n ResourceCache* cache = GetSubsystem<ResourceCache>();\r\n UI* ui = GetSubsystem<UI>();\r\n \r\n \/\/ Construct new Text object, set string to display and font to use\r\n Text* instructionText = ui->GetRoot()->CreateChild<Text>();\r\n instructionText->SetText(\"Use WASD keys and mouse to move\");\r\n instructionText->SetFont(cache->GetResource<Font>(\"Fonts\/Anonymous Pro.ttf\"), 15);\r\n \r\n \/\/ Position the text relative to the screen center\r\n instructionText->SetHorizontalAlignment(HA_CENTER);\r\n instructionText->SetVerticalAlignment(VA_CENTER);\r\n instructionText->SetPosition(0, ui->GetRoot()->GetHeight() \/ 4);\r\n}\r\n\r\nvoid StaticScene::SetupViewport()\r\n{\r\n Renderer* renderer = GetSubsystem<Renderer>();\r\n \r\n \/\/ Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera\r\n \/\/ at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward \/ deferred) to\r\n \/\/ use, but now we just use full screen and default render path configured in the engine command line options\r\n SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));\r\n renderer->SetViewport(0, viewport);\r\n}\r\n\r\nvoid StaticScene::MoveCamera(float timeStep)\r\n{\r\n \/\/ Do not move if the UI has a focused element (the console)\r\n UI* ui = GetSubsystem<UI>();\r\n if (ui->GetFocusElement())\r\n return;\r\n \r\n Input* input = GetSubsystem<Input>();\r\n \r\n \/\/ Movement speed as world units per second\r\n const float MOVE_SPEED = 20.0f;\r\n \/\/ Mouse sensitivity as degrees per pixel\r\n const float MOUSE_SENSITIVITY = 0.1f;\r\n \r\n \/\/ Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees\r\n IntVector2 mouseMove = input->GetMouseMove();\r\n yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;\r\n pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;\r\n pitch_ = Clamp(pitch_, -90.0f, 90.0f);\r\n \r\n \/\/ Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero.\r\n cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));\r\n \r\n \/\/ Read WASD keys and move the camera scene node to the corresponding direction if they are pressed\r\n \/\/ Use the TranslateRelative() function to move relative to the node's orientation. Alternatively we could\r\n \/\/ multiply the desired direction with the node's orientation quaternion, and use just Translate()\r\n if (input->GetKeyDown('W'))\r\n cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('S'))\r\n cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('A'))\r\n cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('D'))\r\n cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);\r\n}\r\n\r\nvoid StaticScene::SubscribeToEvents()\r\n{\r\n \/\/ Subscribes HandleUpdate() method for processing update events\r\n SubscribeToEvent(E_UPDATE, HANDLER(StaticScene, HandleUpdate));\r\n}\r\n\r\nvoid StaticScene::HandleUpdate(StringHash eventType, VariantMap& eventData)\r\n{\r\n \/\/ Event parameters are always defined inside a namespace corresponding to the event's name\r\n using namespace Update;\r\n\r\n \/\/ Take the frame time step, which is stored as a float\r\n float timeStep = eventData[P_TIMESTEP].GetFloat();\r\n \r\n \/\/ Move the camera, scale movement with time step\r\n MoveCamera(timeStep);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * input_manager.cpp : Manage an input and interact with its GUI elements\n ****************************************************************************\n * Copyright (C) 2000-2005 the VideoLAN team\n * $Id: wxwidgets.cpp 15731 2006-05-25 14:43:53Z zorglub $\n *\n * Authors: Clément Stenac <zorglub@videolan.org>\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; 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"input_manager.hpp\"\n#include \"dialogs_provider.hpp\"\n#include \"qt4.hpp\"\n\n\/**********************************************************************\n * InputManager implementation\n **********************************************************************\/\n\nInputManager::InputManager( QObject *parent, intf_thread_t *_p_intf) :\n QObject( parent ), p_intf( _p_intf )\n{\n p_input = NULL;\n \/* Subscribe to updates *\/\n connect( DialogsProvider::getInstance( p_intf )->fixed_timer,\n SIGNAL( timeout() ), this, SLOT( update() ) );\n}\n\nInputManager::~InputManager()\n{\n}\n\nvoid InputManager::setInput( input_thread_t *_p_input )\n{\n p_input = _p_input;\n emit positionUpdated( 0.0,0,0 );\n}\n\nvoid InputManager::update()\n{\n \/\/\/ \\todo Emit the signals only if it changed\n if( !p_input || p_input->b_die ) return;\n\n if( p_input->b_dead )\n {\n emit positionUpdated( 0.0, 0, 0 );\n emit navigationChanged( 0 );\n emit statusChanged( 0 ); \/\/ 0 = STOPPED, 1 = PAUSE, 2 = PLAY\n }\n\n \/* Update position *\/\n mtime_t i_length, i_time;\n float f_pos;\n i_length = var_GetTime( p_input, \"length\" ) \/ 1000000;\n i_time = var_GetTime( p_input, \"time\") \/ 1000000;\n f_pos = var_GetFloat( p_input, \"position\" );\n emit positionUpdated( f_pos, i_time, i_length );\n\n \/* Update disc status *\/\n vlc_value_t val;\n var_Change( p_input, \"title\", VLC_VAR_CHOICESCOUNT, &val, NULL );\n if( val.i_int > 0 )\n {\n vlc_value_t val;\n var_Change( p_input, \"chapter\", VLC_VAR_CHOICESCOUNT, &val, NULL );\n if( val.i_int > 0 )\n emit navigationChanged( 1 ); \/\/ 1 = chapter, 2 = title, 3 = NO\n else\n emit navigationChanged( 2 );\n }\n else\n {\n emit navigationChanged( 0 );\n }\n\n \/* Update text *\/\n QString text;\n if( p_input->input.p_item->p_meta &&\n p_input->input.p_item->p_meta->psz_nowplaying &&\n *p_input->input.p_item->p_meta->psz_nowplaying )\n {\n text.sprintf( \"%s - %s\",\n p_input->input.p_item->p_meta->psz_nowplaying,\n p_input->input.p_item->psz_name );\n }\n else\n {\n text.sprintf( \"%s\", p_input->input.p_item->psz_name );\n }\n emit nameChanged( text );\n\n}\n\nvoid InputManager::sliderUpdate( float new_pos )\n{\n if( p_input && !p_input->b_die && !p_input->b_dead )\n var_SetFloat( p_input, \"position\", new_pos );\n}\n\n\/**********************************************************************\n * MainInputManager implementation. Wrap an input manager and\n * take care of updating the main playlist input\n **********************************************************************\/\nMainInputManager * MainInputManager::instance = NULL;\n\nMainInputManager::MainInputManager( intf_thread_t *_p_intf ) : QObject(NULL),\n p_intf( _p_intf )\n{\n p_input = NULL;\n im = new InputManager( this, p_intf );\n \/* Get timer updates *\/\n connect( DialogsProvider::getInstance(p_intf)->fixed_timer,\n SIGNAL(timeout() ), this, SLOT( updateInput() ) );\n \/* Warn our embedded IM about input changes *\/\n connect( this, SIGNAL( inputChanged( input_thread_t * ) ),\n im, SLOT( setInput( input_thread_t * ) ) );\n}\n\nvoid MainInputManager::updateInput()\n{\n vlc_mutex_lock( &p_intf->change_lock );\n if( p_input && p_input->b_dead )\n {\n vlc_object_release( p_input );\n p_input = NULL;\n emit inputChanged( NULL );\n }\n\n if( !p_input )\n {\n playlist_t *p_playlist = (playlist_t *) vlc_object_find( p_intf,\n VLC_OBJECT_PLAYLIST, FIND_ANYWHERE );\n assert( p_playlist );\n PL_LOCK;\n p_input = p_playlist->p_input;\n if( p_input )\n {\n vlc_object_yield( p_input );\n emit inputChanged( p_input );\n }\n PL_UNLOCK;\n vlc_object_release( p_playlist );\n }\n vlc_mutex_unlock( &p_intf->change_lock );\n}\n<commit_msg>qt4\/input_manager.cpp: compile fix<commit_after>\/*****************************************************************************\n * input_manager.cpp : Manage an input and interact with its GUI elements\n ****************************************************************************\n * Copyright (C) 2000-2005 the VideoLAN team\n * $Id: wxwidgets.cpp 15731 2006-05-25 14:43:53Z zorglub $\n *\n * Authors: Clément Stenac <zorglub@videolan.org>\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; 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include <assert.h>\n\n#include \"input_manager.hpp\"\n#include \"dialogs_provider.hpp\"\n#include \"qt4.hpp\"\n\n\/**********************************************************************\n * InputManager implementation\n **********************************************************************\/\n\nInputManager::InputManager( QObject *parent, intf_thread_t *_p_intf) :\n QObject( parent ), p_intf( _p_intf )\n{\n p_input = NULL;\n \/* Subscribe to updates *\/\n connect( DialogsProvider::getInstance( p_intf )->fixed_timer,\n SIGNAL( timeout() ), this, SLOT( update() ) );\n}\n\nInputManager::~InputManager()\n{\n}\n\nvoid InputManager::setInput( input_thread_t *_p_input )\n{\n p_input = _p_input;\n emit positionUpdated( 0.0,0,0 );\n}\n\nvoid InputManager::update()\n{\n \/\/\/ \\todo Emit the signals only if it changed\n if( !p_input || p_input->b_die ) return;\n\n if( p_input->b_dead )\n {\n emit positionUpdated( 0.0, 0, 0 );\n emit navigationChanged( 0 );\n emit statusChanged( 0 ); \/\/ 0 = STOPPED, 1 = PAUSE, 2 = PLAY\n }\n\n \/* Update position *\/\n mtime_t i_length, i_time;\n float f_pos;\n i_length = var_GetTime( p_input, \"length\" ) \/ 1000000;\n i_time = var_GetTime( p_input, \"time\") \/ 1000000;\n f_pos = var_GetFloat( p_input, \"position\" );\n emit positionUpdated( f_pos, i_time, i_length );\n\n \/* Update disc status *\/\n vlc_value_t val;\n var_Change( p_input, \"title\", VLC_VAR_CHOICESCOUNT, &val, NULL );\n if( val.i_int > 0 )\n {\n vlc_value_t val;\n var_Change( p_input, \"chapter\", VLC_VAR_CHOICESCOUNT, &val, NULL );\n if( val.i_int > 0 )\n emit navigationChanged( 1 ); \/\/ 1 = chapter, 2 = title, 3 = NO\n else\n emit navigationChanged( 2 );\n }\n else\n {\n emit navigationChanged( 0 );\n }\n\n \/* Update text *\/\n QString text;\n if( p_input->input.p_item->p_meta &&\n p_input->input.p_item->p_meta->psz_nowplaying &&\n *p_input->input.p_item->p_meta->psz_nowplaying )\n {\n text.sprintf( \"%s - %s\",\n p_input->input.p_item->p_meta->psz_nowplaying,\n p_input->input.p_item->psz_name );\n }\n else\n {\n text.sprintf( \"%s\", p_input->input.p_item->psz_name );\n }\n emit nameChanged( text );\n\n}\n\nvoid InputManager::sliderUpdate( float new_pos )\n{\n if( p_input && !p_input->b_die && !p_input->b_dead )\n var_SetFloat( p_input, \"position\", new_pos );\n}\n\n\/**********************************************************************\n * MainInputManager implementation. Wrap an input manager and\n * take care of updating the main playlist input\n **********************************************************************\/\nMainInputManager * MainInputManager::instance = NULL;\n\nMainInputManager::MainInputManager( intf_thread_t *_p_intf ) : QObject(NULL),\n p_intf( _p_intf )\n{\n p_input = NULL;\n im = new InputManager( this, p_intf );\n \/* Get timer updates *\/\n connect( DialogsProvider::getInstance(p_intf)->fixed_timer,\n SIGNAL(timeout() ), this, SLOT( updateInput() ) );\n \/* Warn our embedded IM about input changes *\/\n connect( this, SIGNAL( inputChanged( input_thread_t * ) ),\n im, SLOT( setInput( input_thread_t * ) ) );\n}\n\nvoid MainInputManager::updateInput()\n{\n vlc_mutex_lock( &p_intf->change_lock );\n if( p_input && p_input->b_dead )\n {\n vlc_object_release( p_input );\n p_input = NULL;\n emit inputChanged( NULL );\n }\n\n if( !p_input )\n {\n playlist_t *p_playlist = (playlist_t *) vlc_object_find( p_intf,\n VLC_OBJECT_PLAYLIST, FIND_ANYWHERE );\n assert( p_playlist );\n PL_LOCK;\n p_input = p_playlist->p_input;\n if( p_input )\n {\n vlc_object_yield( p_input );\n emit inputChanged( p_input );\n }\n PL_UNLOCK;\n vlc_object_release( p_playlist );\n }\n vlc_mutex_unlock( &p_intf->change_lock );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Reference: http:\/\/www.indiana.edu\/~iulg\/trm\/\n *\n * Instruction set\n * ===============\n * Add 1 to Rn : 1^n#\n * Rn.push(1)\n *\n * Add # to Rn : 1^n##\n * Rn.push(#)\n *\n * Go forward n : 1^n###\n * pc += n\n * Go backward n : 1^n####\n * pc -= n\n *\n * Cases on Rn : 1^n#####\n * if Rn.empty(), pc += 1\n * if Rn.pop() == 1, pc += 2\n * if Rn.pop() == #, pc += 3\n *\/\n\n#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nenum Code {\n O,\n H\n};\n\nenum Op {\n Add1 = 1,\n Add0 = 2,\n Inc = 3,\n Dec = 4,\n Case = 5\n};\n\nstruct Instr {\n Op o;\n int n;\n};\n\nvector< Instr > program;\nmap< int, queue<Code> > mem;\n\nvoid push(int i, Code c) {\n mem[i].push(c);\n}\n\nint cases(int i) {\n queue<Code>& Rn = mem[i];\n if (Rn.empty()) {\n return 1;\n } else if (Rn.front() == O) {\n Rn.pop();\n return 2;\n } else if (Rn.front() == H) {\n Rn.pop();\n return 3;\n }\n}\n\nvoid print_registers() {\n for (map< int, queue<Code> >::iterator it=mem.begin(); it != mem.end(); it++) {\n cout << \"R\" << it->first << \":\";\n queue<Code> content = it->second;\n while (content.empty() == false) {\n Code c = content.front();\n content.pop();\n if (c == O) {\n cout << \"1\";\n } else {\n cout << \"#\";\n }\n }\n cout << endl;\n }\n}\n\nstring op2string(Op o) {\n switch (o) {\n case Add1: return \"Add1\";\n case Add0: return \"Add#\";\n case Inc: return \"Inc\";\n case Dec: return \"Dec\";\n case Case: return \"Case\";\n }\n}\n\nstring instr2string(Instr in) {\n return op2string(in.o) + \" \" + to_string(in.n);\n}\n \nvoid print_program() {\n for ( auto &p : program) {\n cout << instr2string(p) << endl;\n }\n}\n\nvoid eval(int pc) {\n while (pc < program.size()) {\n Instr in = program[pc];\n \/\/cout << \"pc:\" + to_string(pc) + \" \" + \"instr: \" + instr2string(in) << endl;\n switch (in.o) {\n case Add1:\n push(in.n, O);\n pc++;\n break;\n\n case Add0:\n push(in.n, H);\n pc++;\n break;\n\n case Inc:\n pc += in.n;\n break;\n\n case Dec:\n pc -= in.n;\n break;\n\n case Case:\n pc += cases(in.n);\n break;\n }\n }\n}\n \nvoid load_program() {\n cin.sync_with_stdio(false);\n \n char curr;\n\n int n = 0;\n int c = 0;\n \n while (cin >> curr) {\n if (curr == '1') {\n if (c > 0) {\n n = 0;\n c = 0;\n }\n n++;\n } else if (curr == '#') {\n c++;\n if (c == 1) {\n program.push_back({Add1, n});\n } else {\n program.back().o = (Op)c;\n }\n }\n }\n}\n\nint main() {\n load_program();\n \/\/print_program();\n eval(0);\n print_registers();\n return 0;\n}\n<commit_msg>rename member o to op<commit_after>\/*\n * Reference: http:\/\/www.indiana.edu\/~iulg\/trm\/\n *\n * Instruction set\n * ===============\n * Add 1 to Rn : 1^n#\n * Rn.push(1)\n *\n * Add # to Rn : 1^n##\n * Rn.push(#)\n *\n * Go forward n : 1^n###\n * pc += n\n * Go backward n : 1^n####\n * pc -= n\n *\n * Cases on Rn : 1^n#####\n * if Rn.empty(), pc += 1\n * if Rn.pop() == 1, pc += 2\n * if Rn.pop() == #, pc += 3\n *\/\n\n#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nenum Code {\n O,\n H\n};\n\nenum Op {\n Add1 = 1,\n Add0 = 2,\n Inc = 3,\n Dec = 4,\n Case = 5\n};\n\nstruct Instr {\n Op op;\n int n;\n};\n\nvector< Instr > program;\nmap< int, queue<Code> > mem;\n\nvoid push(int i, Code c) {\n mem[i].push(c);\n}\n\nint cases(int i) {\n queue<Code>& Rn = mem[i];\n if (Rn.empty()) {\n return 1;\n } else if (Rn.front() == O) {\n Rn.pop();\n return 2;\n } else if (Rn.front() == H) {\n Rn.pop();\n return 3;\n }\n}\n\nvoid print_registers() {\n for (map< int, queue<Code> >::iterator it=mem.begin(); it != mem.end(); it++) {\n cout << \"R\" << it->first << \":\";\n queue<Code> content = it->second;\n while (content.empty() == false) {\n Code c = content.front();\n content.pop();\n if (c == O) {\n cout << \"1\";\n } else {\n cout << \"#\";\n }\n }\n cout << endl;\n }\n}\n\nstring op2string(Op o) {\n switch (o) {\n case Add1: return \"Add1\";\n case Add0: return \"Add#\";\n case Inc: return \"Inc\";\n case Dec: return \"Dec\";\n case Case: return \"Case\";\n }\n}\n\nstring instr2string(Instr in) {\n return op2string(in.op) + \" \" + to_string(in.n);\n}\n \nvoid print_program() {\n for ( auto &p : program) {\n cout << instr2string(p) << endl;\n }\n}\n\nvoid eval(int pc) {\n while (pc < program.size()) {\n Instr in = program[pc];\n \/\/cout << \"pc:\" + to_string(pc) + \" \" + \"instr: \" + instr2string(in) << endl;\n switch (in.op) {\n case Add1:\n push(in.n, O);\n pc++;\n break;\n\n case Add0:\n push(in.n, H);\n pc++;\n break;\n\n case Inc:\n pc += in.n;\n break;\n\n case Dec:\n pc -= in.n;\n break;\n\n case Case:\n pc += cases(in.n);\n break;\n }\n }\n}\n \nvoid load_program() {\n cin.sync_with_stdio(false);\n \n char curr;\n\n int n = 0;\n int c = 0;\n \n while (cin >> curr) {\n if (curr == '1') {\n if (c > 0) {\n n = 0;\n c = 0;\n }\n n++;\n } else if (curr == '#') {\n c++;\n if (c == 1) {\n program.push_back({Add1, n});\n } else {\n program.back().op = (Op)c;\n }\n }\n }\n}\n\nint main() {\n load_program();\n \/\/print_program();\n eval(0);\n print_registers();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n kabcexport.cpp - Export Contacts to Address Book Wizard for Kopete\n\n Copyright (c) 2005 by Will Stephenson <will@stevello.free-online.co.uk>\n Resource selector taken from KRES::SelectDialog\n Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>\n Copyright (c) 2002 Jan-Pascal van Best <janpascal@vanbest.org>\n Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>\n\n Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <qpushbutton.h>\n#include <q3listbox.h>\n#include <q3listview.h>\n#include <q3ptrlist.h>\n#include <qmap.h>\n\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kabc\/addressee.h>\n#include <kabc\/addressbook.h>\n#include <kabc\/phonenumber.h>\n#include <kabc\/picture.h>\n#include <kabc\/resource.h>\n#include <kabc\/stdaddressbook.h>\n\n#include <kabcpersistence.h>\n#include <kopetecontact.h>\n#include <kopetecontactlist.h>\n#include <kopetecontactproperty.h>\n#include <kopeteglobal.h>\n#include <kopetemetacontact.h>\n\n#include \"kabcpersistence.h\"\n\n#include \"kabcexport.h\"\n\nclass ContactLVI : public Q3CheckListItem\n{\n\tpublic:\n\t\tContactLVI ( Kopete::MetaContact * mc, Q3ListView * parent, const QString & text, Type tt = RadioButtonController ) : Q3CheckListItem( parent, text, tt ), mc( mc )\n\t\t{\t}\n\t\tKopete::MetaContact * mc;\n\t\tQString uid;\n};\n\n\/\/ ctor populates the resource list and contact list, and enables the next button on the first page \nKabcExportWizard::KabcExportWizard( QWidget *parent, const char *name )\n\t: KabcExportWizard_Base( parent, name )\n{\n\tconnect( m_addrBooks, SIGNAL( selectionChanged( Q3ListBoxItem * ) ), SLOT( slotResourceSelectionChanged( Q3ListBoxItem * ) ) );\n\n\tconnect( m_btnSelectAll, SIGNAL( clicked() ), SLOT( slotSelectAll() ) );\n\tconnect( m_btnDeselectAll, SIGNAL( clicked() ), SLOT( slotDeselectAll() ) );\n\t\n\t\/\/ fill resource selector\n\tm_addressBook = Kopete::KABCPersistence::self()->addressBook();\n\n\tQ3PtrList<KABC::Resource> kabcResources = m_addressBook->resources();\n\n\tQ3PtrListIterator<KABC::Resource> resIt( kabcResources );\n\tKABC::Resource *resource;\n\t\n\tuint counter = 0;\n\twhile ( ( resource = resIt.current() ) != 0 ) \n\t{\n\t\t++resIt;\n\t\tif ( !resource->readOnly() ) \n\t\t{\n\t\t\tm_resourceMap.insert( counter, resource );\n\t\t\tm_addrBooks->insertItem( resource->resourceName() );\n\t\t\tcounter++;\n\t\t}\n\t}\n\tsetNextEnabled( Q3Wizard::page( 0 ), false );\n\tsetFinishEnabled( Q3Wizard::page( 1 ), true );\n\t\/\/ if there were no writable address books, tell the user\n\tif ( counter == 0 )\n\t{\n\t\tm_addrBooks->insertItem( i18n( \"No writeable addressbook resource found.\" ) );\n\t\tm_addrBooks->insertItem( i18n( \"Add or enable one using the KDE Control Center.\" ) );\n\t\tm_addrBooks->setEnabled( false );\n\t}\n\n\tif ( m_addrBooks->count() == 1 )\n\t\tm_addrBooks->setSelected( 0, true );\n\t\n\t\/\/ fill contact list\n\tQList<Kopete::MetaContact*> contacts = Kopete::ContactList::self()->metaContacts();\n\tQList<Kopete::MetaContact*>::iterator it, itEnd = contacts.end();\n\tcounter = 0;\n\tQString alreadyIn = i18n( \" (already in address book)\" );\n\tfor ( it = contacts.begin(); it != itEnd; ++it)\n\t{\n\t\tKopete::MetaContact* mc = (*it);\n\t\tm_contactMap.insert( counter, mc );\n\t\tQ3CheckListItem * lvi = new ContactLVI( mc, m_contactList,\n\t\t\t\tmc->displayName(), Q3CheckListItem::CheckBox );\n\t\tlvi->setOn( false );\n\t\tif ( mc->metaContactId().contains(':') )\n\t\t{\n\t\t\tlvi->setOn( true );\n\t\t\tlvi->setEnabled( true );\n\t\t}\n\t\telse\n\t\t\tlvi->setText( 0, lvi->text( 0 ) + alreadyIn );\n\t}\n}\n\nKabcExportWizard::~KabcExportWizard()\n{\n\t\n}\n\nvoid KabcExportWizard::slotDeselectAll()\n{\n\tQ3ListViewItemIterator it( m_contactList );\n\twhile ( it.current() )\n\t{\n\t\tContactLVI *item = static_cast<ContactLVI *>( it.current() );\n\t\titem->setOn( false );\n\t\t++it;\n\t}\n}\n\nvoid KabcExportWizard::slotSelectAll()\n{\n\tQ3ListViewItemIterator it( m_contactList );\n\twhile ( it.current() )\n\t{\n\t\tContactLVI *item = static_cast<ContactLVI *>( it.current() );\n\t\t++it;\n\t\tif ( !item->isEnabled() )\n\t\t\tcontinue;\n\t\titem->setOn( true );\n\t}\n}\n\nvoid KabcExportWizard::slotResourceSelectionChanged( Q3ListBoxItem * lbi )\n{\n\tsetNextEnabled( Q3Wizard::page( 0 ), lbi->isSelected() );\n}\n\n\/\/ accept runs the export algorithm\nvoid KabcExportWizard::accept()\n{\n\t\/\/ first add an addressee to the selected resource \n\t\/\/ then set the metacontactId of each MC to that of the new addressee\n\tKABC::Resource * selectedResource = \n\t\t\tm_resourceMap[ ( m_addrBooks->index( m_addrBooks->selectedItem() ) ) ];\n\t\/\/ for each item checked\n\t{\n\t\tQ3ListViewItemIterator it( m_contactList );\n\t\twhile ( it.current() )\n\t\t{\n\t\t\tContactLVI *item = static_cast<ContactLVI *>( it.current() );\n\t\t\t\/\/ if it is checked and enabled\n\t\t\tif ( item->isEnabled() && item->isOn() )\n\t\t\t{\n\t\t\t\tKABC::Addressee addr;\n\t\t\t\taddr = m_addressBook->findByUid( item->mc->metaContactId() );\n\t\t\t\tif ( addr.isEmpty() ) \/\/ unassociated contact\n\t\t\t\t{\n\t\t\t\t\tkdDebug( 14000 ) << \"creating addressee \" << item->mc->displayName() << \" in address book \" << selectedResource->resourceName() << endl;\n\t\t\t\t\t\/\/ create a new addressee in the selected resource\n\t\t\t\t\taddr.setResource( selectedResource );\n\n\t\t\t\t\t\/\/ set name\n\t\t\t\t\tQList<Kopete::Contact*> contacts = item->mc->contacts();\n\t\t\t\t\tif ( contacts.count() == 1 )\n\t\t\t\t\t{\n\t\t\t\t\t\tKopete::ContactProperty prop;\n\t\t\t\t\t\tprop = contacts.first()->property(\n\t\t\t\t\t\t\t\tKopete::Global::Properties::self()->fullName() );\n\t\t\t\t\t\tif ( prop.isNull() )\n\t\t\t\t\t\t\taddr.setNameFromString( item->mc->displayName() );\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\taddr.setNameFromString( prop.value().toString() );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\taddr.setNameFromString( item->mc->displayName() );\n\n\t\t\t\t\t\/\/ set details\n\t\t\t\t\texportDetails( item->mc, addr );\n\t\t\t\t\tm_addressBook->insertAddressee( addr );\n\t\t\t\t\t\/\/ set the metacontact's id to that of the new addressee \n\t\t\t\t\t\/\/ - this causes the addressbook to be written by libkopete\n\t\t\t\t\titem->mc->setMetaContactId( addr.uid() );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\texportDetails( item->mc, addr );\n\t\t\t\t\tm_addressBook->insertAddressee( addr );\n\t\t\t\t}\n\t\t\t}\n\t\t\t++it;\n\t\t}\n\t}\n\t\/\/ request a write in case we only changed details on existing linked addressee\n\tKopete::KABCPersistence::self()->writeAddressBook( selectedResource );\n\tQDialog::accept();\n}\n\nvoid KabcExportWizard::exportDetails( Kopete::MetaContact * mc, KABC::Addressee & addr )\n{\n\tQList<Kopete::Contact*> contacts = mc->contacts();\n\tQList<Kopete::Contact*>::iterator cit, citEnd = contacts.begin();\n\tfor( cit = contacts.begin(); cit != citEnd; ++cit )\n\t{\n\t\tKopete::ContactProperty prop;\n\t\tprop = (*cit)->property( Kopete::Global::Properties::self()->emailAddress() );\n\t\tif ( !prop.isNull() )\n\t\t{\n\t\t\taddr.insertEmail( prop.value().toString() );\n\t\t}\n\t\tprop = (*cit)->property( Kopete::Global::Properties::self()->privatePhone() );\n\t\tif ( !prop.isNull() )\n\t\t{\n\t\t\taddr.insertPhoneNumber( KABC::PhoneNumber( prop.value().toString(), KABC::PhoneNumber::Home ) );\n\t\t}\n\t\tprop = (*cit)->property( Kopete::Global::Properties::self()->workPhone() );\n\t\tif ( !prop.isNull() )\n\t\t{\n\t\t\taddr.insertPhoneNumber( KABC::PhoneNumber( prop.value().toString(), KABC::PhoneNumber::Work ) );\n\t\t}\n\t\tprop = (*cit)->property( Kopete::Global::Properties::self()->privateMobilePhone() );\n\t\tif ( !prop.isNull() )\n\t\t{\n\t\t\taddr.insertPhoneNumber( KABC::PhoneNumber( prop.value().toString(), KABC::PhoneNumber::Cell ) );\n\t\t}\n\t\n\t}\n\t\n\tQImage photo = mc->photo();\n\tif ( !photo.isNull() )\n\t\taddr.setPhoto( KABC::Picture( photo ) );\n}\n\n#include \"kabcexport.moc\"\n<commit_msg>compile (port to kabc changes)<commit_after>\/*\n kabcexport.cpp - Export Contacts to Address Book Wizard for Kopete\n\n Copyright (c) 2005 by Will Stephenson <will@stevello.free-online.co.uk>\n Resource selector taken from KRES::SelectDialog\n Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>\n Copyright (c) 2002 Jan-Pascal van Best <janpascal@vanbest.org>\n Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>\n\n Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <qpushbutton.h>\n#include <q3listbox.h>\n#include <q3listview.h>\n#include <qmap.h>\n\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kabc\/addressee.h>\n#include <kabc\/addressbook.h>\n#include <kabc\/phonenumber.h>\n#include <kabc\/picture.h>\n#include <kabc\/resource.h>\n#include <kabc\/stdaddressbook.h>\n\n#include <kabcpersistence.h>\n#include <kopetecontact.h>\n#include <kopetecontactlist.h>\n#include <kopetecontactproperty.h>\n#include <kopeteglobal.h>\n#include <kopetemetacontact.h>\n\n#include \"kabcpersistence.h\"\n\n#include \"kabcexport.h\"\n\nclass ContactLVI : public Q3CheckListItem\n{\n\tpublic:\n\t\tContactLVI ( Kopete::MetaContact * mc, Q3ListView * parent, const QString & text, Type tt = RadioButtonController ) : Q3CheckListItem( parent, text, tt ), mc( mc )\n\t\t{\t}\n\t\tKopete::MetaContact * mc;\n\t\tQString uid;\n};\n\n\/\/ ctor populates the resource list and contact list, and enables the next button on the first page \nKabcExportWizard::KabcExportWizard( QWidget *parent, const char *name )\n\t: KabcExportWizard_Base( parent, name )\n{\n\tconnect( m_addrBooks, SIGNAL( selectionChanged( Q3ListBoxItem * ) ), SLOT( slotResourceSelectionChanged( Q3ListBoxItem * ) ) );\n\n\tconnect( m_btnSelectAll, SIGNAL( clicked() ), SLOT( slotSelectAll() ) );\n\tconnect( m_btnDeselectAll, SIGNAL( clicked() ), SLOT( slotDeselectAll() ) );\n\t\n\t\/\/ fill resource selector\n\tm_addressBook = Kopete::KABCPersistence::self()->addressBook();\n\n\tQList<KABC::Resource*> kabcResources = m_addressBook->resources();\n\n\tQListIterator<KABC::Resource*> resIt( kabcResources );\n\tKABC::Resource *resource;\n\t\n\tuint counter = 0;\n\twhile ( resIt.hasNext() ) \n\t{\n\t\tresource = resIt.next();\n\t\tif ( !resource->readOnly() ) \n\t\t{\n\t\t\tm_resourceMap.insert( counter, resource );\n\t\t\tm_addrBooks->insertItem( resource->resourceName() );\n\t\t\tcounter++;\n\t\t}\n\t}\n\tsetNextEnabled( Q3Wizard::page( 0 ), false );\n\tsetFinishEnabled( Q3Wizard::page( 1 ), true );\n\t\/\/ if there were no writable address books, tell the user\n\tif ( counter == 0 )\n\t{\n\t\tm_addrBooks->insertItem( i18n( \"No writeable addressbook resource found.\" ) );\n\t\tm_addrBooks->insertItem( i18n( \"Add or enable one using the KDE Control Center.\" ) );\n\t\tm_addrBooks->setEnabled( false );\n\t}\n\n\tif ( m_addrBooks->count() == 1 )\n\t\tm_addrBooks->setSelected( 0, true );\n\t\n\t\/\/ fill contact list\n\tQList<Kopete::MetaContact*> contacts = Kopete::ContactList::self()->metaContacts();\n\tQList<Kopete::MetaContact*>::iterator it, itEnd = contacts.end();\n\tcounter = 0;\n\tQString alreadyIn = i18n( \" (already in address book)\" );\n\tfor ( it = contacts.begin(); it != itEnd; ++it)\n\t{\n\t\tKopete::MetaContact* mc = (*it);\n\t\tm_contactMap.insert( counter, mc );\n\t\tQ3CheckListItem * lvi = new ContactLVI( mc, m_contactList,\n\t\t\t\tmc->displayName(), Q3CheckListItem::CheckBox );\n\t\tlvi->setOn( false );\n\t\tif ( mc->metaContactId().contains(':') )\n\t\t{\n\t\t\tlvi->setOn( true );\n\t\t\tlvi->setEnabled( true );\n\t\t}\n\t\telse\n\t\t\tlvi->setText( 0, lvi->text( 0 ) + alreadyIn );\n\t}\n}\n\nKabcExportWizard::~KabcExportWizard()\n{\n\t\n}\n\nvoid KabcExportWizard::slotDeselectAll()\n{\n\tQ3ListViewItemIterator it( m_contactList );\n\twhile ( it.current() )\n\t{\n\t\tContactLVI *item = static_cast<ContactLVI *>( it.current() );\n\t\titem->setOn( false );\n\t\t++it;\n\t}\n}\n\nvoid KabcExportWizard::slotSelectAll()\n{\n\tQ3ListViewItemIterator it( m_contactList );\n\twhile ( it.current() )\n\t{\n\t\tContactLVI *item = static_cast<ContactLVI *>( it.current() );\n\t\t++it;\n\t\tif ( !item->isEnabled() )\n\t\t\tcontinue;\n\t\titem->setOn( true );\n\t}\n}\n\nvoid KabcExportWizard::slotResourceSelectionChanged( Q3ListBoxItem * lbi )\n{\n\tsetNextEnabled( Q3Wizard::page( 0 ), lbi->isSelected() );\n}\n\n\/\/ accept runs the export algorithm\nvoid KabcExportWizard::accept()\n{\n\t\/\/ first add an addressee to the selected resource \n\t\/\/ then set the metacontactId of each MC to that of the new addressee\n\tKABC::Resource * selectedResource = \n\t\t\tm_resourceMap[ ( m_addrBooks->index( m_addrBooks->selectedItem() ) ) ];\n\t\/\/ for each item checked\n\t{\n\t\tQ3ListViewItemIterator it( m_contactList );\n\t\twhile ( it.current() )\n\t\t{\n\t\t\tContactLVI *item = static_cast<ContactLVI *>( it.current() );\n\t\t\t\/\/ if it is checked and enabled\n\t\t\tif ( item->isEnabled() && item->isOn() )\n\t\t\t{\n\t\t\t\tKABC::Addressee addr;\n\t\t\t\taddr = m_addressBook->findByUid( item->mc->metaContactId() );\n\t\t\t\tif ( addr.isEmpty() ) \/\/ unassociated contact\n\t\t\t\t{\n\t\t\t\t\tkdDebug( 14000 ) << \"creating addressee \" << item->mc->displayName() << \" in address book \" << selectedResource->resourceName() << endl;\n\t\t\t\t\t\/\/ create a new addressee in the selected resource\n\t\t\t\t\taddr.setResource( selectedResource );\n\n\t\t\t\t\t\/\/ set name\n\t\t\t\t\tQList<Kopete::Contact*> contacts = item->mc->contacts();\n\t\t\t\t\tif ( contacts.count() == 1 )\n\t\t\t\t\t{\n\t\t\t\t\t\tKopete::ContactProperty prop;\n\t\t\t\t\t\tprop = contacts.first()->property(\n\t\t\t\t\t\t\t\tKopete::Global::Properties::self()->fullName() );\n\t\t\t\t\t\tif ( prop.isNull() )\n\t\t\t\t\t\t\taddr.setNameFromString( item->mc->displayName() );\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\taddr.setNameFromString( prop.value().toString() );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\taddr.setNameFromString( item->mc->displayName() );\n\n\t\t\t\t\t\/\/ set details\n\t\t\t\t\texportDetails( item->mc, addr );\n\t\t\t\t\tm_addressBook->insertAddressee( addr );\n\t\t\t\t\t\/\/ set the metacontact's id to that of the new addressee \n\t\t\t\t\t\/\/ - this causes the addressbook to be written by libkopete\n\t\t\t\t\titem->mc->setMetaContactId( addr.uid() );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\texportDetails( item->mc, addr );\n\t\t\t\t\tm_addressBook->insertAddressee( addr );\n\t\t\t\t}\n\t\t\t}\n\t\t\t++it;\n\t\t}\n\t}\n\t\/\/ request a write in case we only changed details on existing linked addressee\n\tKopete::KABCPersistence::self()->writeAddressBook( selectedResource );\n\tQDialog::accept();\n}\n\nvoid KabcExportWizard::exportDetails( Kopete::MetaContact * mc, KABC::Addressee & addr )\n{\n\tQList<Kopete::Contact*> contacts = mc->contacts();\n\tQList<Kopete::Contact*>::iterator cit, citEnd = contacts.begin();\n\tfor( cit = contacts.begin(); cit != citEnd; ++cit )\n\t{\n\t\tKopete::ContactProperty prop;\n\t\tprop = (*cit)->property( Kopete::Global::Properties::self()->emailAddress() );\n\t\tif ( !prop.isNull() )\n\t\t{\n\t\t\taddr.insertEmail( prop.value().toString() );\n\t\t}\n\t\tprop = (*cit)->property( Kopete::Global::Properties::self()->privatePhone() );\n\t\tif ( !prop.isNull() )\n\t\t{\n\t\t\taddr.insertPhoneNumber( KABC::PhoneNumber( prop.value().toString(), KABC::PhoneNumber::Home ) );\n\t\t}\n\t\tprop = (*cit)->property( Kopete::Global::Properties::self()->workPhone() );\n\t\tif ( !prop.isNull() )\n\t\t{\n\t\t\taddr.insertPhoneNumber( KABC::PhoneNumber( prop.value().toString(), KABC::PhoneNumber::Work ) );\n\t\t}\n\t\tprop = (*cit)->property( Kopete::Global::Properties::self()->privateMobilePhone() );\n\t\tif ( !prop.isNull() )\n\t\t{\n\t\t\taddr.insertPhoneNumber( KABC::PhoneNumber( prop.value().toString(), KABC::PhoneNumber::Cell ) );\n\t\t}\n\t\n\t}\n\t\n\tQImage photo = mc->photo();\n\tif ( !photo.isNull() )\n\t\taddr.setPhoto( KABC::Picture( photo ) );\n}\n\n#include \"kabcexport.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright © 2016 by Donald King <chronos@chronos-tachyon.net>\n\/\/ Available under the MIT License. See LICENSE for details.\n\n#include \"gtest\/gtest.h\"\n\n#include <fcntl.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <time.h>\n#include <unistd.h>\n\n#include <array>\n#include <condition_variable>\n#include <cstdlib>\n#include <cstring>\n#include <mutex>\n#include <thread>\n#include <vector>\n\n#include \"base\/cleanup.h\"\n#include \"base\/fd.h\"\n#include \"base\/logging.h\"\n#include \"base\/result_testing.h\"\n#include \"io\/util.h\"\n\nstatic std::unique_lock<std::mutex> acquire_lock(std::mutex& mu) {\n return std::unique_lock<std::mutex>(mu);\n}\n\nstatic void sleep_ms(unsigned int ms) {\n struct timespec tv;\n ::bzero(&tv, sizeof(tv));\n tv.tv_sec = (ms \/ 1000);\n tv.tv_nsec = (ms % 1000) * 1000000;\n ::nanosleep(&tv, nullptr);\n}\n\nstatic event::Manager make_manager() {\n event::Manager m;\n event::ManagerOptions mo;\n mo.set_num_pollers(0, 1);\n mo.dispatcher().set_type(event::DispatcherType::async_dispatcher);\n event::new_manager(&m, mo).assert_ok();\n return m;\n}\n\nTEST(Copy, StringReaderStringWriter) {\n std::string in = \"0123456789ab\";\n std::string out;\n io::Reader r = io::stringreader(in);\n io::Writer w = io::stringwriter(&out);\n\n event::Task task;\n std::size_t n;\n io::copy(&task, &n, w, r);\n event::wait_all({w.manager(), r.manager()}, {&task});\n EXPECT_OK(task.result());\n EXPECT_EQ(12U, n);\n EXPECT_EQ(out, in);\n}\n\nstatic void TestFileFileCopy(io::Options o) {\n std::string srcpath, dstpath;\n base::FD srcfd, dstfd;\n\n ASSERT_OK(base::make_tempfile(&srcpath, &srcfd, \"mojo-io-util-test.XXXXXX\"));\n auto cleanup0 = base::cleanup([srcpath] { ::unlink(srcpath.c_str()); });\n\n ASSERT_OK(base::make_tempfile(&dstpath, &dstfd, \"mojo-io-util-test.XXXXXX\"));\n auto cleanup1 = base::cleanup([dstpath] { ::unlink(dstpath.c_str()); });\n\n constexpr std::size_t N = 4096;\n\n std::vector<char> in;\n in.assign(N, 'A');\n in.resize(N, 'B');\n\n io::Reader r;\n io::Writer w;\n event::Task task;\n std::size_t n = 42;\n\n w = io::fdwriter(srcfd, o);\n w.write(&task, &n, in.data(), N);\n while (!task.is_finished()) {\n EXPECT_OK(o.manager().donate(false));\n }\n EXPECT_OK(task.result());\n EXPECT_EQ(N, n);\n\n {\n auto pair = srcfd->acquire_fd();\n EXPECT_EQ(0, ::lseek(pair.first, 0, SEEK_SET));\n }\n\n r = io::fdreader(srcfd, o);\n w = io::fdwriter(dstfd, o);\n task.reset();\n io::copy_n(&task, &n, N, w, r);\n while (!task.is_finished()) {\n EXPECT_OK(o.manager().donate(false));\n }\n EXPECT_OK(task.result());\n EXPECT_EQ(N, n);\n\n {\n auto pair = dstfd->acquire_fd();\n EXPECT_EQ(0, ::lseek(pair.first, 0, SEEK_SET));\n }\n\n std::vector<char> out;\n out.resize(2 * N);\n r = io::fdreader(dstfd, o);\n task.reset();\n r.read(&task, out.data(), &n, 1, out.size());\n while (!task.is_finished()) {\n EXPECT_OK(o.manager().donate(false));\n }\n EXPECT_OK(task.result());\n EXPECT_EQ(N, n);\n out.resize(n);\n\n EXPECT_EQ(std::string(in.begin(), in.end()),\n std::string(out.begin(), out.end()));\n}\n\nTEST(Copy, FileFileLoop512) {\n io::Options o;\n o.set_manager(make_manager());\n o.set_block_size(512);\n o.set_transfer_mode(io::TransferMode::read_write);\n TestFileFileCopy(o);\n}\n\nTEST(Copy, FileFileLoop4K) {\n io::Options o;\n o.set_manager(make_manager());\n o.set_block_size(4096);\n o.set_transfer_mode(io::TransferMode::read_write);\n TestFileFileCopy(o);\n}\n\nTEST(Copy, FileFileSendfile) {\n io::Options o;\n o.set_manager(make_manager());\n o.set_transfer_mode(io::TransferMode::sendfile);\n TestFileFileCopy(o);\n}\n\nTEST(Copy, FileFileSplice) {\n io::Options o;\n o.set_manager(make_manager());\n o.set_transfer_mode(io::TransferMode::splice);\n TestFileFileCopy(o);\n}\n\nTEST(Copy, HeterogenousManagers) {\n event::Manager rm = make_manager();\n event::Manager wm = make_manager();\n io::Options ro, wo;\n ro.set_manager(rm);\n ro.set_block_size(4096);\n ro.set_transfer_mode(io::TransferMode::read_write);\n wo.set_manager(wm);\n wo.set_block_size(4096);\n wo.set_transfer_mode(io::TransferMode::read_write);\n\n base::SocketPair rdpair, wrpair;\n ASSERT_OK(base::make_socketpair(&rdpair, AF_UNIX, SOCK_STREAM, 0));\n ASSERT_OK(base::make_socketpair(&wrpair, AF_UNIX, SOCK_STREAM, 0));\n ASSERT_OK(base::set_blocking(rdpair.left, true));\n ASSERT_OK(base::set_blocking(wrpair.right, true));\n ASSERT_OK(base::shutdown(rdpair.right, SHUT_WR));\n ASSERT_OK(base::shutdown(wrpair.right, SHUT_WR));\n\n LOG(INFO) << \"sockets are ready\";\n\n std::mutex mu;\n std::size_t blocks_transferred = 0;\n\n std::thread t1([&rdpair] {\n std::vector<char> buf;\n buf.assign(4096, 'A');\n for (std::size_t i = 0; i < 16; ++i) {\n sleep_ms(1);\n LOG(INFO) << \"writing block #\" << i;\n auto r =\n base::write_exactly(rdpair.left, buf.data(), buf.size(), \"rdpair\");\n EXPECT_OK(r);\n if (!r) break;\n }\n sleep_ms(1);\n LOG(INFO) << \"sending EOF on rdpair\";\n EXPECT_OK(rdpair.left->close());\n });\n\n std::thread t2([&wrpair, &mu, &blocks_transferred] {\n std::vector<char> buf;\n buf.resize(1024);\n std::size_t i = 0;\n base::Result r;\n while (true) {\n sleep_ms(1);\n LOG(INFO) << \"reading block #\" << (i \/ 4) << \".\" << ((i % 4) * 25);\n r = base::read_exactly(wrpair.right, buf.data(), buf.size(), \"wrpair\");\n if (!r) break;\n auto lock = acquire_lock(mu);\n ++blocks_transferred;\n ++i;\n }\n EXPECT_EOF(r);\n LOG(INFO) << \"got EOF on wrpair\";\n });\n\n io::Reader r = io::fdreader(rdpair.right, ro);\n io::Writer w = io::fdwriter(wrpair.left, wo);\n\n event::Task task;\n std::size_t n;\n LOG(INFO) << \"starting copy\";\n io::copy(&task, &n, w, r);\n LOG(INFO) << \"waiting on copy\";\n event::wait_all({rm, wm}, {&task});\n LOG(INFO) << \"copy complete\";\n EXPECT_OK(task.result());\n LOG(INFO) << \"sending EOF on wrpair\";\n EXPECT_OK(wrpair.left->close());\n\n LOG(INFO) << \"joining threads\";\n t1.join();\n t2.join();\n EXPECT_EQ(4U * 16U, blocks_transferred);\n}\n\nstatic void init() __attribute__((constructor));\nstatic void init() { base::log_stderr_set_level(VLOG_LEVEL(6)); }\n<commit_msg>Flush logs at the end of each test, to make the output a little more predictable at V=6.<commit_after>\/\/ Copyright © 2016 by Donald King <chronos@chronos-tachyon.net>\n\/\/ Available under the MIT License. See LICENSE for details.\n\n#include \"gtest\/gtest.h\"\n\n#include <fcntl.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <time.h>\n#include <unistd.h>\n\n#include <array>\n#include <condition_variable>\n#include <cstdlib>\n#include <cstring>\n#include <mutex>\n#include <thread>\n#include <vector>\n\n#include \"base\/cleanup.h\"\n#include \"base\/fd.h\"\n#include \"base\/logging.h\"\n#include \"base\/result_testing.h\"\n#include \"io\/util.h\"\n\nstatic std::unique_lock<std::mutex> acquire_lock(std::mutex& mu) {\n return std::unique_lock<std::mutex>(mu);\n}\n\nstatic void sleep_ms(unsigned int ms) {\n struct timespec tv;\n ::bzero(&tv, sizeof(tv));\n tv.tv_sec = (ms \/ 1000);\n tv.tv_nsec = (ms % 1000) * 1000000;\n ::nanosleep(&tv, nullptr);\n}\n\nstatic event::Manager make_manager() {\n event::Manager m;\n event::ManagerOptions mo;\n mo.set_num_pollers(0, 1);\n mo.dispatcher().set_type(event::DispatcherType::async_dispatcher);\n event::new_manager(&m, mo).assert_ok();\n return m;\n}\n\nTEST(Copy, StringReaderStringWriter) {\n std::string in = \"0123456789ab\";\n std::string out;\n io::Reader r = io::stringreader(in);\n io::Writer w = io::stringwriter(&out);\n\n event::Task task;\n std::size_t n;\n io::copy(&task, &n, w, r);\n event::wait_all({w.manager(), r.manager()}, {&task});\n EXPECT_OK(task.result());\n EXPECT_EQ(12U, n);\n EXPECT_EQ(out, in);\n\n base::log_flush();\n}\n\nstatic void TestFileFileCopy(io::Options o) {\n std::string srcpath, dstpath;\n base::FD srcfd, dstfd;\n\n ASSERT_OK(base::make_tempfile(&srcpath, &srcfd, \"mojo-io-util-test.XXXXXX\"));\n auto cleanup0 = base::cleanup([srcpath] { ::unlink(srcpath.c_str()); });\n\n ASSERT_OK(base::make_tempfile(&dstpath, &dstfd, \"mojo-io-util-test.XXXXXX\"));\n auto cleanup1 = base::cleanup([dstpath] { ::unlink(dstpath.c_str()); });\n\n constexpr std::size_t N = 4096;\n\n std::vector<char> in;\n in.assign(N, 'A');\n in.resize(N, 'B');\n\n io::Reader r;\n io::Writer w;\n event::Task task;\n std::size_t n = 42;\n\n w = io::fdwriter(srcfd, o);\n w.write(&task, &n, in.data(), N);\n while (!task.is_finished()) {\n EXPECT_OK(o.manager().donate(false));\n }\n EXPECT_OK(task.result());\n EXPECT_EQ(N, n);\n\n {\n auto pair = srcfd->acquire_fd();\n EXPECT_EQ(0, ::lseek(pair.first, 0, SEEK_SET));\n }\n\n r = io::fdreader(srcfd, o);\n w = io::fdwriter(dstfd, o);\n task.reset();\n io::copy_n(&task, &n, N, w, r);\n while (!task.is_finished()) {\n EXPECT_OK(o.manager().donate(false));\n }\n EXPECT_OK(task.result());\n EXPECT_EQ(N, n);\n\n {\n auto pair = dstfd->acquire_fd();\n EXPECT_EQ(0, ::lseek(pair.first, 0, SEEK_SET));\n }\n\n std::vector<char> out;\n out.resize(2 * N);\n r = io::fdreader(dstfd, o);\n task.reset();\n r.read(&task, out.data(), &n, 1, out.size());\n while (!task.is_finished()) {\n EXPECT_OK(o.manager().donate(false));\n }\n EXPECT_OK(task.result());\n EXPECT_EQ(N, n);\n out.resize(n);\n\n EXPECT_EQ(std::string(in.begin(), in.end()),\n std::string(out.begin(), out.end()));\n\n base::log_flush();\n}\n\nTEST(Copy, FileFileLoop512) {\n io::Options o;\n o.set_manager(make_manager());\n o.set_block_size(512);\n o.set_transfer_mode(io::TransferMode::read_write);\n TestFileFileCopy(o);\n}\n\nTEST(Copy, FileFileLoop4K) {\n io::Options o;\n o.set_manager(make_manager());\n o.set_block_size(4096);\n o.set_transfer_mode(io::TransferMode::read_write);\n TestFileFileCopy(o);\n}\n\nTEST(Copy, FileFileSendfile) {\n io::Options o;\n o.set_manager(make_manager());\n o.set_transfer_mode(io::TransferMode::sendfile);\n TestFileFileCopy(o);\n}\n\nTEST(Copy, FileFileSplice) {\n io::Options o;\n o.set_manager(make_manager());\n o.set_transfer_mode(io::TransferMode::splice);\n TestFileFileCopy(o);\n}\n\nTEST(Copy, HeterogenousManagers) {\n event::Manager rm = make_manager();\n event::Manager wm = make_manager();\n io::Options ro, wo;\n ro.set_manager(rm);\n ro.set_block_size(4096);\n ro.set_transfer_mode(io::TransferMode::read_write);\n wo.set_manager(wm);\n wo.set_block_size(4096);\n wo.set_transfer_mode(io::TransferMode::read_write);\n\n base::SocketPair rdpair, wrpair;\n ASSERT_OK(base::make_socketpair(&rdpair, AF_UNIX, SOCK_STREAM, 0));\n ASSERT_OK(base::make_socketpair(&wrpair, AF_UNIX, SOCK_STREAM, 0));\n ASSERT_OK(base::set_blocking(rdpair.left, true));\n ASSERT_OK(base::set_blocking(wrpair.right, true));\n ASSERT_OK(base::shutdown(rdpair.right, SHUT_WR));\n ASSERT_OK(base::shutdown(wrpair.right, SHUT_WR));\n\n LOG(INFO) << \"sockets are ready\";\n\n std::mutex mu;\n std::size_t blocks_transferred = 0;\n\n std::thread t1([&rdpair] {\n std::vector<char> buf;\n buf.assign(4096, 'A');\n for (std::size_t i = 0; i < 16; ++i) {\n sleep_ms(1);\n LOG(INFO) << \"writing block #\" << i;\n auto r =\n base::write_exactly(rdpair.left, buf.data(), buf.size(), \"rdpair\");\n EXPECT_OK(r);\n if (!r) break;\n }\n sleep_ms(1);\n LOG(INFO) << \"sending EOF on rdpair\";\n EXPECT_OK(rdpair.left->close());\n });\n\n std::thread t2([&wrpair, &mu, &blocks_transferred] {\n std::vector<char> buf;\n buf.resize(1024);\n std::size_t i = 0;\n base::Result r;\n while (true) {\n sleep_ms(1);\n LOG(INFO) << \"reading block #\" << (i \/ 4) << \".\" << ((i % 4) * 25);\n r = base::read_exactly(wrpair.right, buf.data(), buf.size(), \"wrpair\");\n if (!r) break;\n auto lock = acquire_lock(mu);\n ++blocks_transferred;\n ++i;\n }\n EXPECT_EOF(r);\n LOG(INFO) << \"got EOF on wrpair\";\n });\n\n io::Reader r = io::fdreader(rdpair.right, ro);\n io::Writer w = io::fdwriter(wrpair.left, wo);\n\n event::Task task;\n std::size_t n;\n LOG(INFO) << \"starting copy\";\n io::copy(&task, &n, w, r);\n LOG(INFO) << \"waiting on copy\";\n event::wait_all({rm, wm}, {&task});\n LOG(INFO) << \"copy complete\";\n EXPECT_OK(task.result());\n LOG(INFO) << \"sending EOF on wrpair\";\n EXPECT_OK(wrpair.left->close());\n\n LOG(INFO) << \"joining threads\";\n t1.join();\n t2.join();\n EXPECT_EQ(4U * 16U, blocks_transferred);\n\n base::log_flush();\n}\n\nstatic void init() __attribute__((constructor));\nstatic void init() { base::log_stderr_set_level(VLOG_LEVEL(6)); }\n<|endoftext|>"} {"text":"<commit_before>#include \"plugin.h\"\n\n#include <algorithm>\n#include <cstring>\n\n#include \"npapi-headers\/npfunctions.h\"\n\nNPNetscapeFuncs g_browser_functions = { 0 };\n\nnamespace {\n\nNPError initializeBrowserFuncs(NPNetscapeFuncs* bFuncs)\n{\n if (!bFuncs)\n return NPERR_INVALID_FUNCTABLE_ERROR;\n\n int major_version = bFuncs->version >> 8;\n int minor_version = bFuncs->version & 0xff;\n\n if (major_version != NP_VERSION_MAJOR)\n return NPERR_INCOMPATIBLE_VERSION_ERROR;\n\n \/\/ TODO: Assert support in minor_version for features we care\n \/\/ about.\n\n memcpy(&g_browser_functions, bFuncs,\n std::min(sizeof(g_browser_functions), (size_t)bFuncs->size));\n\n return NPERR_NO_ERROR;\n}\n\n} \/\/ namespace\n\nNP_EXPORT(NPError) OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)\n{\n pFuncs->size = sizeof(*pFuncs);\n pFuncs->version = 0; \/\/ My version?\n \/\/ TODO: implement the functions I need.\n return NPERR_NO_ERROR;\n}\n\nNP_EXPORT(NPError) OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs,\n\t\t\t\t\tNPPluginFuncs* pFuncs)\n{\n NPError err = initializeBrowserFuncs(bFuncs);\n if (err != NPERR_NO_ERROR)\n return err;\n\n \/\/ On Unix, it looks like NP_GetEntryPoints isn't called directly?\n \/\/ The prototype for NP_Initialize is different from everyone\n \/\/ else. Meh.\n return NP_GetEntryPoints(pFuncs);\n}\n\nNP_EXPORT(NPError) OSCALL NP_GetValue(void *instance,\n NPPVariable variable,\n void *value)\n{\n NPError err = NPERR_NO_ERROR;\n switch (variable) {\n case NPPVpluginNameString:\n *reinterpret_cast<const char **>(value) = \"Embedded Emacs\";\n break;\n case NPPVpluginDescriptionString:\n *reinterpret_cast<const char **>(value) =\n \"Embeds emacs into your browser window with XEmbed.\";\n break;\n default:\n err = NPERR_GENERIC_ERROR;\n }\n return err;\n}\n\n\/\/ This probably should be const char *, but NPAPI messed up.\nNP_EXPORT(char*) OSCALL NP_GetMIMEDescription(void)\n{\n return const_cast<char*>(\"application\/x-emacs-npapi::Embed emacs with NPAPI\");\n}\n<commit_msg>Add some stubs for NPP_New and NPP_Destroy<commit_after>#include \"plugin.h\"\n\n#include <algorithm>\n#include <cstring>\n\n#include \"emacsinstance.h\"\n#include \"npapi-headers\/npfunctions.h\"\n\nNPNetscapeFuncs g_browser_functions = { 0 };\n\nnamespace {\n\nNPError initializeBrowserFuncs(NPNetscapeFuncs* bFuncs)\n{\n if (!bFuncs)\n return NPERR_INVALID_FUNCTABLE_ERROR;\n\n int major_version = bFuncs->version >> 8;\n int minor_version = bFuncs->version & 0xff;\n\n if (major_version != NP_VERSION_MAJOR)\n return NPERR_INCOMPATIBLE_VERSION_ERROR;\n\n \/\/ TODO: Assert support in minor_version for features we care\n \/\/ about.\n\n memcpy(&g_browser_functions, bFuncs,\n std::min(sizeof(g_browser_functions), (size_t)bFuncs->size));\n\n return NPERR_NO_ERROR;\n}\n\n} \/\/ namespace\n\nNP_EXPORT(NPError) OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)\n{\n pFuncs->size = sizeof(*pFuncs);\n pFuncs->version = 0; \/\/ My version?\n pFuncs->newp = NPP_New;\n pFuncs->destroy = NPP_Destroy;\n \/\/ TODO: implement the functions I need.\n return NPERR_NO_ERROR;\n}\n\nNP_EXPORT(NPError) OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs,\n\t\t\t\t\tNPPluginFuncs* pFuncs)\n{\n NPError err = initializeBrowserFuncs(bFuncs);\n if (err != NPERR_NO_ERROR)\n return err;\n\n \/\/ On Unix, it looks like NP_GetEntryPoints isn't called directly?\n \/\/ The prototype for NP_Initialize is different from everyone\n \/\/ else. Meh.\n return NP_GetEntryPoints(pFuncs);\n}\n\nNP_EXPORT(NPError) OSCALL NP_GetValue(void *instance,\n NPPVariable variable,\n void *value)\n{\n NPError err = NPERR_NO_ERROR;\n switch (variable) {\n case NPPVpluginNameString:\n *reinterpret_cast<const char **>(value) = \"Embedded Emacs\";\n break;\n case NPPVpluginDescriptionString:\n *reinterpret_cast<const char **>(value) =\n \"Embeds emacs into your browser window with XEmbed.\";\n break;\n default:\n err = NPERR_GENERIC_ERROR;\n }\n return err;\n}\n\n\/\/ This probably should be const char *, but NPAPI messed up.\nNP_EXPORT(char*) OSCALL NP_GetMIMEDescription(void)\n{\n return const_cast<char*>(\"application\/x-emacs-npapi::Embed emacs with NPAPI\");\n}\n\n\/*****************************\/\n\/* NPP Functions *\/\n\/*****************************\/\n\nNPError NPP_New(NPMIMEType pluginType, NPP instance,\n uint16_t mode, int16_t argc, char* argn[],\n char* argv[], NPSavedData* saved)\n{\n return NPERR_GENERIC_ERROR;\n}\n\nNPError NPP_Destroy(NPP instance, NPSavedData** save)\n{\n return NPERR_GENERIC_ERROR;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the KOrganizer alarm daemon.\n\n Copyright (c) 2000,2003 Cornelius Schumacher <schumacher@kde.org>\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; 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. 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\n\n#include <QLabel>\n#include <QFile>\n#include <QSpinBox>\n#include <QLayout>\n#include <QPushButton>\n#include <QDataStream>\n\/\/Added by qt3to4:\n#include <QVBoxLayout>\n#include <QBoxLayout>\n#include <QtDBus>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kprocess.h>\n#include <kdebug.h>\n#include <kmessagebox.h>\n#include <knotification.h>\n#include <kcombobox.h>\n#include <kwin.h>\n#include <klockfile.h>\n#include <kpushbutton.h>\n#include <phonon\/audioplayer.h>\n\n#include <kcal\/event.h>\n#include <ktoolinvocation.h>\n#include <kglobal.h>\n#include <kvbox.h>\n\n#include \"koeventviewer.h\"\n\n#include \"alarmdialog.h\"\n#include \"alarmdialog.moc\"\n#include <korganizer_interface.h>\n\nAlarmDialog::AlarmDialog( QWidget *parent )\n : KDialog( parent\/*, Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_StaysOnTop |\n Qt::WStyle_DialogBorder,*\/ ),\n mSuspendTimer(this)\n{\n KIconLoader::global()->addAppDir( \"kdepim\" );\n\n QWidget *topBox = new QWidget( this);\n setMainWidget( topBox );\n setCaption( i18n(\"Reminder\") );\n setButtons( Ok | User1 | User2 );\n setDefaultButton( User1 );\n setButtonText( User1, i18n(\"Suspend\") );\n setButtonText( User2, i18n(\"Edit...\") );\n QBoxLayout *topLayout = new QVBoxLayout( topBox );\n topLayout->setSpacing( spacingHint() );\n\n QLabel *label = new QLabel( i18n(\"The following events triggered reminders:\"),\n topBox );\n topLayout->addWidget( label );\n\n mEventViewer = new KOEventViewer( topBox );\n topLayout->addWidget( mEventViewer );\n\n KHBox *suspendBox = new KHBox( topBox );\n suspendBox->setSpacing( spacingHint() );\n topLayout->addWidget( suspendBox );\n\n QLabel *l = new QLabel( i18n(\"Suspend &duration:\"), suspendBox );\n mSuspendSpin = new QSpinBox( suspendBox );\n mSuspendSpin->setRange( 1, 9999 );\n mSuspendSpin->setValue( 5 ); \/\/ default suspend duration\n l->setBuddy( mSuspendSpin );\n\n mSuspendUnit = new KComboBox( suspendBox );\n mSuspendUnit->addItem( i18n(\"minute(s)\") );\n mSuspendUnit->addItem( i18n(\"hour(s)\") );\n mSuspendUnit->addItem( i18n(\"day(s)\") );\n mSuspendUnit->addItem( i18n(\"week(s)\") );\n\n \/\/ showButton( User2\/*3*\/, false );\n\n setMinimumSize( 300, 200 );\n connect(this,SIGNAL(okClicked()),this, SLOT(slotOk()));\n connect(this,SIGNAL(user1Clicked()),this,SLOT(slotUser1()));\n connect(this,SIGNAL(user2Clicked()),this,SLOT(slotUser2()));\n}\n\nAlarmDialog::~AlarmDialog()\n{\n delete mIncidence;\n}\n\nvoid AlarmDialog::setIncidence( Incidence *incidence )\n{\n mIncidence = incidence->clone();\n mEventViewer->appendIncidence( mIncidence );\n}\n\nvoid AlarmDialog::setRemindAt( const QDateTime &dt )\n{\n mRemindAt = dt;\n}\n\nvoid AlarmDialog::slotOk()\n{\n accept();\n emit finishedSignal( this );\n}\n\nvoid AlarmDialog::slotUser1()\n{\n if ( !isVisible() )\n return;\n\n int unit=1;\n switch ( mSuspendUnit->currentIndex() ) {\n case 3: \/\/ weeks\n unit *= 7;\n case 2: \/\/ days\n unit *= 24;\n case 1: \/\/ hours\n unit *= 60;\n case 0: \/\/ minutes\n unit *= 60;\n default:\n break;\n }\n\n setTimer( unit * mSuspendSpin->value() );\n accept();\n}\n\nvoid AlarmDialog::setTimer( int seconds )\n{\n connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( show() ) );\n mSuspendTimer.setSingleShot( true );\n mSuspendTimer.start( 1000 * seconds );\n mRemindAt = QDateTime::currentDateTime();\n mRemindAt = mRemindAt.addSecs( seconds );\n}\n\nvoid AlarmDialog::slotUser2()\n{\n if ( !QDBusConnection::sessionBus().interface()->isServiceRegistered( \"org.kde.korganizer\" ) ) {\n if ( KToolInvocation::startServiceByDesktopName( \"korganizer\", QString() ) )\n KMessageBox::error( 0, i18n(\"Could not start KOrganizer.\") );\n }\n org::kde::korganizer::Korganizer korganizer(\"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.editIncidence(mIncidence->uid());\n\n#ifdef Q_OS_UNIX\n#ifdef __GNUC__\n#warning \"kde4: verify it when kontact will not crash\"\n#endif\n \/\/ get desktop # where korganizer (or kontact) runs\n QString object = QDBusConnection::sessionBus().interface()->isServiceRegistered( \"org.kde.kontact\" ) ?\n \"kontact-mainwindow_1\" : \"korganizer\/MainWindow_1\";\n QDBusInterface korganizerObj(\"org.kde.korganizer\", '\/'+object);\n QDBusReply<int> reply = korganizerObj.call( \"winId\" );\n if ( reply.isValid() ) {\n int window = reply;\n int desktop = KWin::windowInfo( window, NET::WMDesktop ).desktop();\n\n if ( KWin::currentDesktop() == desktop ) {\n KWin::iconifyWindow( winId(), false );\n }\n else\n KWin::setCurrentDesktop( desktop );\n\n KWin::activateWindow( KWin::transientFor( window ) );\n }\n#endif\n}\n\nvoid AlarmDialog::show()\n{\n KDialog::show();\n#ifdef Q_OS_UNIX\n KWin::setState( winId(), NET::KeepAbove );\n KWin::setOnAllDesktops( winId(), true );\n#endif\n eventNotification();\n}\n\nvoid AlarmDialog::suspendValueChanged()\n{\n setButtonFocus( User1 );\n}\n\nvoid AlarmDialog::suspendUnitChanged()\n{\n setButtonFocus( User1 );\n setButtonFocus( User2 );\n}\n\nvoid AlarmDialog::eventNotification()\n{\n bool beeped = false;\n Alarm::List alarms = mIncidence->alarms();\n Alarm::List::ConstIterator it;\n for ( it = alarms.begin(); it != alarms.end(); ++it ) {\n Alarm *alarm = *it;\n\/\/ FIXME: Check whether this should be done for all multiple alarms\n if (alarm->type() == Alarm::Procedure) {\n\/\/ FIXME: Add a message box asking whether the procedure should really be executed\n kDebug(5890) << \"Starting program: '\" << alarm->programFile() << \"'\" << endl;\n KProcess proc;\n proc << QFile::encodeName(alarm->programFile());\n proc.start(KProcess::DontCare);\n }\n else if (alarm->type() == Alarm::Audio) {\n beeped = true;\n Phonon::AudioPlayer* player = new Phonon::AudioPlayer( Phonon::NotificationCategory, this );\n player->play( KUrl( QFile::encodeName(alarm->audioFile() ) ) );\n }\n }\n\n if ( !beeped ) {\n KNotification::beep();\n }\n}\n\nvoid AlarmDialog::wakeUp()\n{\n if ( mRemindAt <= QDateTime::currentDateTime() )\n show();\n else\n setTimer( QDateTime::currentDateTime().secsTo( mRemindAt ) );\n}\n\nvoid AlarmDialog::slotSave()\n{\n KConfig *config = KGlobal::config();\n KLockFile::Ptr lock = config->lockFile();\n if ( lock.data()->lock() != KLockFile::LockOK )\n return;\n\n config->setGroup( \"General\" );\n int numReminders = config->readEntry(\"Reminders\", 0);\n config->writeEntry( \"Reminders\", ++numReminders );\n\n config->setGroup( QString(\"Incidence-%1\").arg(numReminders) );\n config->writeEntry( \"UID\", mIncidence->uid() );\n config->writeEntry( \"RemindAt\", mRemindAt );\n config->sync();\n lock.data()->unlock();\n}\n\n<commit_msg>Don't use \"-\"<commit_after>\/*\n This file is part of the KOrganizer alarm daemon.\n\n Copyright (c) 2000,2003 Cornelius Schumacher <schumacher@kde.org>\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; 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. 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\n\n#include <QLabel>\n#include <QFile>\n#include <QSpinBox>\n#include <QLayout>\n#include <QPushButton>\n#include <QDataStream>\n\/\/Added by qt3to4:\n#include <QVBoxLayout>\n#include <QBoxLayout>\n#include <QtDBus>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kprocess.h>\n#include <kdebug.h>\n#include <kmessagebox.h>\n#include <knotification.h>\n#include <kcombobox.h>\n#include <kwin.h>\n#include <klockfile.h>\n#include <kpushbutton.h>\n#include <phonon\/audioplayer.h>\n\n#include <kcal\/event.h>\n#include <ktoolinvocation.h>\n#include <kglobal.h>\n#include <kvbox.h>\n\n#include \"koeventviewer.h\"\n\n#include \"alarmdialog.h\"\n#include \"alarmdialog.moc\"\n#include <korganizer_interface.h>\n\nAlarmDialog::AlarmDialog( QWidget *parent )\n : KDialog( parent\/*, Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_StaysOnTop |\n Qt::WStyle_DialogBorder,*\/ ),\n mSuspendTimer(this)\n{\n KIconLoader::global()->addAppDir( \"kdepim\" );\n\n QWidget *topBox = new QWidget( this);\n setMainWidget( topBox );\n setCaption( i18n(\"Reminder\") );\n setButtons( Ok | User1 | User2 );\n setDefaultButton( User1 );\n setButtonText( User1, i18n(\"Suspend\") );\n setButtonText( User2, i18n(\"Edit...\") );\n QBoxLayout *topLayout = new QVBoxLayout( topBox );\n topLayout->setSpacing( spacingHint() );\n\n QLabel *label = new QLabel( i18n(\"The following events triggered reminders:\"),\n topBox );\n topLayout->addWidget( label );\n\n mEventViewer = new KOEventViewer( topBox );\n topLayout->addWidget( mEventViewer );\n\n KHBox *suspendBox = new KHBox( topBox );\n suspendBox->setSpacing( spacingHint() );\n topLayout->addWidget( suspendBox );\n\n QLabel *l = new QLabel( i18n(\"Suspend &duration:\"), suspendBox );\n mSuspendSpin = new QSpinBox( suspendBox );\n mSuspendSpin->setRange( 1, 9999 );\n mSuspendSpin->setValue( 5 ); \/\/ default suspend duration\n l->setBuddy( mSuspendSpin );\n\n mSuspendUnit = new KComboBox( suspendBox );\n mSuspendUnit->addItem( i18n(\"minute(s)\") );\n mSuspendUnit->addItem( i18n(\"hour(s)\") );\n mSuspendUnit->addItem( i18n(\"day(s)\") );\n mSuspendUnit->addItem( i18n(\"week(s)\") );\n\n \/\/ showButton( User2\/*3*\/, false );\n\n setMinimumSize( 300, 200 );\n connect(this,SIGNAL(okClicked()),this, SLOT(slotOk()));\n connect(this,SIGNAL(user1Clicked()),this,SLOT(slotUser1()));\n connect(this,SIGNAL(user2Clicked()),this,SLOT(slotUser2()));\n}\n\nAlarmDialog::~AlarmDialog()\n{\n delete mIncidence;\n}\n\nvoid AlarmDialog::setIncidence( Incidence *incidence )\n{\n mIncidence = incidence->clone();\n mEventViewer->appendIncidence( mIncidence );\n}\n\nvoid AlarmDialog::setRemindAt( const QDateTime &dt )\n{\n mRemindAt = dt;\n}\n\nvoid AlarmDialog::slotOk()\n{\n accept();\n emit finishedSignal( this );\n}\n\nvoid AlarmDialog::slotUser1()\n{\n if ( !isVisible() )\n return;\n\n int unit=1;\n switch ( mSuspendUnit->currentIndex() ) {\n case 3: \/\/ weeks\n unit *= 7;\n case 2: \/\/ days\n unit *= 24;\n case 1: \/\/ hours\n unit *= 60;\n case 0: \/\/ minutes\n unit *= 60;\n default:\n break;\n }\n\n setTimer( unit * mSuspendSpin->value() );\n accept();\n}\n\nvoid AlarmDialog::setTimer( int seconds )\n{\n connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( show() ) );\n mSuspendTimer.setSingleShot( true );\n mSuspendTimer.start( 1000 * seconds );\n mRemindAt = QDateTime::currentDateTime();\n mRemindAt = mRemindAt.addSecs( seconds );\n}\n\nvoid AlarmDialog::slotUser2()\n{\n if ( !QDBusConnection::sessionBus().interface()->isServiceRegistered( \"org.kde.korganizer\" ) ) {\n if ( KToolInvocation::startServiceByDesktopName( \"korganizer\", QString() ) )\n KMessageBox::error( 0, i18n(\"Could not start KOrganizer.\") );\n }\n org::kde::korganizer::Korganizer korganizer(\"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.editIncidence(mIncidence->uid());\n\n#ifdef Q_OS_UNIX\n#ifdef __GNUC__\n#warning \"kde4: verify it when kontact will not crash\"\n#endif\n \/\/ get desktop # where korganizer (or kontact) runs\n QString object = QDBusConnection::sessionBus().interface()->isServiceRegistered( \"org.kde.kontact\" ) ?\n \"kontact\/mainwindow_1\" : \"korganizer\/MainWindow_1\";\n QDBusInterface korganizerObj(\"org.kde.korganizer\", '\/'+object);\n QDBusReply<int> reply = korganizerObj.call( \"winId\" );\n if ( reply.isValid() ) {\n int window = reply;\n int desktop = KWin::windowInfo( window, NET::WMDesktop ).desktop();\n\n if ( KWin::currentDesktop() == desktop ) {\n KWin::iconifyWindow( winId(), false );\n }\n else\n KWin::setCurrentDesktop( desktop );\n\n KWin::activateWindow( KWin::transientFor( window ) );\n }\n#endif\n}\n\nvoid AlarmDialog::show()\n{\n KDialog::show();\n#ifdef Q_OS_UNIX\n KWin::setState( winId(), NET::KeepAbove );\n KWin::setOnAllDesktops( winId(), true );\n#endif\n eventNotification();\n}\n\nvoid AlarmDialog::suspendValueChanged()\n{\n setButtonFocus( User1 );\n}\n\nvoid AlarmDialog::suspendUnitChanged()\n{\n setButtonFocus( User1 );\n setButtonFocus( User2 );\n}\n\nvoid AlarmDialog::eventNotification()\n{\n bool beeped = false;\n Alarm::List alarms = mIncidence->alarms();\n Alarm::List::ConstIterator it;\n for ( it = alarms.begin(); it != alarms.end(); ++it ) {\n Alarm *alarm = *it;\n\/\/ FIXME: Check whether this should be done for all multiple alarms\n if (alarm->type() == Alarm::Procedure) {\n\/\/ FIXME: Add a message box asking whether the procedure should really be executed\n kDebug(5890) << \"Starting program: '\" << alarm->programFile() << \"'\" << endl;\n KProcess proc;\n proc << QFile::encodeName(alarm->programFile());\n proc.start(KProcess::DontCare);\n }\n else if (alarm->type() == Alarm::Audio) {\n beeped = true;\n Phonon::AudioPlayer* player = new Phonon::AudioPlayer( Phonon::NotificationCategory, this );\n player->play( KUrl( QFile::encodeName(alarm->audioFile() ) ) );\n }\n }\n\n if ( !beeped ) {\n KNotification::beep();\n }\n}\n\nvoid AlarmDialog::wakeUp()\n{\n if ( mRemindAt <= QDateTime::currentDateTime() )\n show();\n else\n setTimer( QDateTime::currentDateTime().secsTo( mRemindAt ) );\n}\n\nvoid AlarmDialog::slotSave()\n{\n KConfig *config = KGlobal::config();\n KLockFile::Ptr lock = config->lockFile();\n if ( lock.data()->lock() != KLockFile::LockOK )\n return;\n\n config->setGroup( \"General\" );\n int numReminders = config->readEntry(\"Reminders\", 0);\n config->writeEntry( \"Reminders\", ++numReminders );\n\n config->setGroup( QString(\"Incidence-%1\").arg(numReminders) );\n config->writeEntry( \"UID\", mIncidence->uid() );\n config->writeEntry( \"RemindAt\", mRemindAt );\n config->sync();\n lock.data()->unlock();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: pcivga.cc,v 1.21 2009\/01\/10 11:30:20 vruppert Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2002,2003 Mike Nordell\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 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 St, Fifth Floor, Boston, MA  02110-1301 USA\n\n\/\/\n\/\/ Experimental PCI VGA adapter\n\/\/\n\n\/\/ Note: This \"driver\" was created for the SOLE PURPOSE of getting BeOS\n\/\/ to boot. It currently does NOTHING more than presenting a generic VGA\n\/\/ device on the PCI bus. ALL gfx in\/out-put is still handled by the VGA code.\n\/\/ Furthermore, almost all of the PCI registers are currently acting like RAM.\n\n\n\/\/ Define BX_PLUGGABLE in files that can be compiled into plugins. For\n\/\/ platforms that require a special tag on exported symbols, BX_PLUGGABLE\n\/\/ is used to know when we are exporting symbols and when we are importing.\n#define BX_PLUGGABLE\n\n#include \"iodev.h\"\n\n#if BX_SUPPORT_PCI && BX_SUPPORT_PCIVGA\n\n#include \"pci.h\"\n#include \"pcivga.h\"\n\n#define LOG_THIS thePciVgaAdapter->\n\nbx_pcivga_c* thePciVgaAdapter = 0;\n\nint libpcivga_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[])\n{\n thePciVgaAdapter = new bx_pcivga_c();\n BX_REGISTER_DEVICE_DEVMODEL(plugin, type, thePciVgaAdapter, BX_PLUGIN_PCIVGA);\n return 0; \/\/ Success\n}\n\nvoid libpcivga_LTX_plugin_fini(void)\n{\n delete thePciVgaAdapter;\n}\n\nbx_pcivga_c::bx_pcivga_c()\n{\n put(\"PCIVGA\");\n}\n\nbx_pcivga_c::~bx_pcivga_c()\n{\n BX_DEBUG((\"Exit\"));\n}\n\nvoid bx_pcivga_c::init(void)\n{\n \/\/ called once when bochs initializes\n\n Bit8u devfunc = 0x00;\n unsigned i;\n\n DEV_register_pci_handlers(this, &devfunc, BX_PLUGIN_PCIVGA,\n \"Experimental PCI VGA\");\n\n for (i=0; i<256; i++) {\n BX_PCIVGA_THIS s.pci_conf[i] = 0x0;\n }\n\n \/\/ readonly registers\n static const struct init_vals_t {\n unsigned addr;\n unsigned char val;\n } init_vals[] = {\n \/\/ Note that the values for vendor and device id are selected at random!\n \/\/ There might actually be \"real\" values for \"experimental\" vendor and\n \/\/ device that should be used!\n { 0x00, 0x34 }, { 0x01, 0x12 }, \/\/ 0x1234 - experimental vendor\n { 0x02, 0x11 }, { 0x03, 0x11 }, \/\/ 0x1111 - experimental device\n { 0x0a, 0x00 }, \/\/ class_sub VGA controller\n { 0x0b, 0x03 }, \/\/ class_base display\n { 0x0e, 0x00 } \/\/ header_type_generic\n };\n for (i = 0; i < sizeof(init_vals) \/ sizeof(*init_vals); ++i) {\n BX_PCIVGA_THIS s.pci_conf[init_vals[i].addr] = init_vals[i].val;\n }\n}\n\nvoid bx_pcivga_c::reset(unsigned type)\n{\n static const struct reset_vals_t {\n unsigned addr;\n unsigned char val;\n } reset_vals[] = {\n { 0x04, 0x03 }, { 0x05, 0x00 },\t\/\/ command_io + command_mem\n { 0x06, 0x00 }, { 0x07, 0x02 }\t\/\/ status_devsel_medium\n };\n for (unsigned i = 0; i < sizeof(reset_vals) \/ sizeof(*reset_vals); ++i) {\n BX_PCIVGA_THIS s.pci_conf[reset_vals[i].addr] = reset_vals[i].val;\n }\n}\n\nvoid bx_pcivga_c::register_state(void)\n{\n bx_list_c *list = new bx_list_c(SIM->get_bochs_root(), \"pcivga\", \"PCI VGA Adapter State\", 1);\n register_pci_state(list, BX_PCIVGA_THIS s.pci_conf);\n}\n\n\/\/ pci configuration space read callback handler\nBit32u bx_pcivga_c::pci_read_handler(Bit8u address, unsigned io_len)\n{\n Bit32u value = 0;\n\n if (io_len > 4 || io_len == 0) {\n BX_DEBUG((\"Experimental PCIVGA read register 0x%02x, len=%u !\",\n (unsigned) address, (unsigned) io_len));\n return 0xffffffff;\n }\n\n const char* pszName = \" \";\n switch (address) {\n case 0x00: if (io_len == 2) {\n pszName = \"(vendor id) \";\n } else if (io_len == 4) {\n pszName = \"(vendor + device) \";\n }\n break;\n case 0x04: if (io_len == 2) {\n pszName = \"(command) \";\n } else if (io_len == 4) {\n pszName = \"(command+status) \";\n }\n break;\n case 0x08: if (io_len == 1) {\n pszName = \"(revision id) \";\n } else if (io_len == 4) {\n pszName = \"(rev.+class code) \";\n }\n break;\n case 0x0c: pszName = \"(cache line size) \"; break;\n case 0x28: pszName = \"(cardbus cis) \"; break;\n case 0x2c: pszName = \"(subsys. vendor+) \"; break;\n case 0x30: pszName = \"(rom base) \"; break;\n case 0x3c: pszName = \"(interrupt line+) \"; break;\n case 0x3d: pszName = \"(interrupt pin) \"; break;\n }\n\n \/\/ This odd code is to display only what bytes actually were read.\n char szTmp[9];\n char szTmp2[3];\n szTmp[0] = '\\0';\n szTmp2[0] = '\\0';\n for (unsigned i=0; i<io_len; i++) {\n value |= (BX_PCIVGA_THIS s.pci_conf[address+i] << (i*8));\n\n sprintf(szTmp2, \"%02x\", (BX_PCIVGA_THIS s.pci_conf[address+i]));\n strrev(szTmp2);\n strcat(szTmp, szTmp2);\n }\n strrev(szTmp);\n BX_DEBUG((\"Experimental PCIVGA read register 0x%02x %svalue 0x%s\",\n address, pszName, szTmp));\n return value;\n}\n\n\n\/\/ static pci configuration space write callback handler\nvoid bx_pcivga_c::pci_write_handler(Bit8u address, Bit32u value, unsigned io_len)\n{\n if ((address >= 0x10) && (address < 0x34))\n return;\n \/\/ This odd code is to display only what bytes actually were written.\n char szTmp[9];\n char szTmp2[3];\n szTmp[0] = '\\0';\n szTmp2[0] = '\\0';\n for (unsigned i=0; i<io_len; i++) {\n const Bit8u value8 = (value >> (i*8)) & 0xFF;\n switch (address+i) {\n case 0x04: \/\/ disallowing write to command\n case 0x06: \/\/ disallowing write to status lo-byte (is that expected?)\n strcpy(szTmp2, \"..\");\n break;\n default:\n BX_PCIVGA_THIS s.pci_conf[address+i] = value8;\n sprintf(szTmp2, \"%02x\", value8);\n }\n strrev(szTmp2);\n strcat(szTmp, szTmp2);\n }\n strrev(szTmp);\n BX_DEBUG((\"Experimental PCIVGA write register 0x%02x value 0x%s\", address, szTmp));\n}\n\n#endif \/\/ BX_SUPPORT_PCI && BX_SUPPORT_PCIVGA\n<commit_msg>- stored LFB address in base address #0 (TODO: implement changeable LFB address; VGABIOS should read LFB base from PCI)<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: pcivga.cc,v 1.22 2009\/01\/22 22:29:23 vruppert Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2002,2003 Mike Nordell\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 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 St, Fifth Floor, Boston, MA  02110-1301 USA\n\n\/\/\n\/\/ Experimental PCI VGA adapter\n\/\/\n\n\/\/ Note: This \"driver\" was created for the SOLE PURPOSE of getting BeOS\n\/\/ to boot. It currently does NOTHING more than presenting a generic VGA\n\/\/ device on the PCI bus. ALL gfx in\/out-put is still handled by the VGA code.\n\/\/ Furthermore, almost all of the PCI registers are currently acting like RAM.\n\n\n\/\/ Define BX_PLUGGABLE in files that can be compiled into plugins. For\n\/\/ platforms that require a special tag on exported symbols, BX_PLUGGABLE\n\/\/ is used to know when we are exporting symbols and when we are importing.\n#define BX_PLUGGABLE\n\n#include \"iodev.h\"\n\n#if BX_SUPPORT_PCI && BX_SUPPORT_PCIVGA\n\n#include \"pci.h\"\n#include \"vga.h\"\n#include \"pcivga.h\"\n\n#define LOG_THIS thePciVgaAdapter->\n\nbx_pcivga_c* thePciVgaAdapter = 0;\n\nint libpcivga_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[])\n{\n thePciVgaAdapter = new bx_pcivga_c();\n BX_REGISTER_DEVICE_DEVMODEL(plugin, type, thePciVgaAdapter, BX_PLUGIN_PCIVGA);\n return 0; \/\/ Success\n}\n\nvoid libpcivga_LTX_plugin_fini(void)\n{\n delete thePciVgaAdapter;\n}\n\nbx_pcivga_c::bx_pcivga_c()\n{\n put(\"PCIVGA\");\n}\n\nbx_pcivga_c::~bx_pcivga_c()\n{\n BX_DEBUG((\"Exit\"));\n}\n\nvoid bx_pcivga_c::init(void)\n{\n \/\/ called once when bochs initializes\n\n Bit8u devfunc = 0x00;\n unsigned i;\n\n DEV_register_pci_handlers(this, &devfunc, BX_PLUGIN_PCIVGA,\n \"Experimental PCI VGA\");\n\n for (i=0; i<256; i++) {\n BX_PCIVGA_THIS s.pci_conf[i] = 0x0;\n }\n\n \/\/ readonly registers\n static const struct init_vals_t {\n unsigned addr;\n unsigned char val;\n } init_vals[] = {\n \/\/ Note that the values for vendor and device id are selected at random!\n \/\/ There might actually be \"real\" values for \"experimental\" vendor and\n \/\/ device that should be used!\n { 0x00, 0x34 }, { 0x01, 0x12 }, \/\/ 0x1234 - experimental vendor\n { 0x02, 0x11 }, { 0x03, 0x11 }, \/\/ 0x1111 - experimental device\n { 0x0a, 0x00 }, \/\/ class_sub VGA controller\n { 0x0b, 0x03 }, \/\/ class_base display\n { 0x0e, 0x00 } \/\/ header_type_generic\n };\n for (i = 0; i < sizeof(init_vals) \/ sizeof(*init_vals); ++i) {\n BX_PCIVGA_THIS s.pci_conf[init_vals[i].addr] = init_vals[i].val;\n }\n}\n\nvoid bx_pcivga_c::reset(unsigned type)\n{\n static const struct reset_vals_t {\n unsigned addr;\n unsigned char val;\n } reset_vals[] = {\n { 0x04, 0x03 }, { 0x05, 0x00 }, \/\/ command_io + command_mem\n { 0x06, 0x00 }, { 0x07, 0x02 } \/\/ status_devsel_medium\n };\n for (unsigned i = 0; i < sizeof(reset_vals) \/ sizeof(*reset_vals); ++i) {\n BX_PCIVGA_THIS s.pci_conf[reset_vals[i].addr] = reset_vals[i].val;\n }\n \/\/ FIXME: LFB address should be changeable\n WriteHostDWordToLittleEndian(&BX_PCIVGA_THIS s.pci_conf[0x10],\n VBE_DISPI_LFB_PHYSICAL_ADDRESS | 0x08);\n}\n\nvoid bx_pcivga_c::register_state(void)\n{\n bx_list_c *list = new bx_list_c(SIM->get_bochs_root(), \"pcivga\", \"PCI VGA Adapter State\", 1);\n register_pci_state(list, BX_PCIVGA_THIS s.pci_conf);\n}\n\n\/\/ pci configuration space read callback handler\nBit32u bx_pcivga_c::pci_read_handler(Bit8u address, unsigned io_len)\n{\n Bit32u value = 0;\n\n if (io_len > 4 || io_len == 0) {\n BX_DEBUG((\"Experimental PCIVGA read register 0x%02x, len=%u !\",\n (unsigned) address, (unsigned) io_len));\n return 0xffffffff;\n }\n\n const char* pszName = \" \";\n switch (address) {\n case 0x00: if (io_len == 2) {\n pszName = \"(vendor id) \";\n } else if (io_len == 4) {\n pszName = \"(vendor + device) \";\n }\n break;\n case 0x04: if (io_len == 2) {\n pszName = \"(command) \";\n } else if (io_len == 4) {\n pszName = \"(command+status) \";\n }\n break;\n case 0x08: if (io_len == 1) {\n pszName = \"(revision id) \";\n } else if (io_len == 4) {\n pszName = \"(rev.+class code) \";\n }\n break;\n case 0x0c: pszName = \"(cache line size) \"; break;\n case 0x10: pszName = \"(base address #0) \"; break;\n case 0x28: pszName = \"(cardbus cis) \"; break;\n case 0x2c: pszName = \"(subsys. vendor+) \"; break;\n case 0x30: pszName = \"(rom base) \"; break;\n case 0x3c: pszName = \"(interrupt line+) \"; break;\n case 0x3d: pszName = \"(interrupt pin) \"; break;\n }\n\n \/\/ This odd code is to display only what bytes actually were read.\n char szTmp[9];\n char szTmp2[3];\n szTmp[0] = '\\0';\n szTmp2[0] = '\\0';\n for (unsigned i=0; i<io_len; i++) {\n value |= (BX_PCIVGA_THIS s.pci_conf[address+i] << (i*8));\n\n sprintf(szTmp2, \"%02x\", (BX_PCIVGA_THIS s.pci_conf[address+i]));\n strrev(szTmp2);\n strcat(szTmp, szTmp2);\n }\n strrev(szTmp);\n BX_DEBUG((\"Experimental PCIVGA read register 0x%02x %svalue 0x%s\",\n address, pszName, szTmp));\n return value;\n}\n\n\n\/\/ static pci configuration space write callback handler\nvoid bx_pcivga_c::pci_write_handler(Bit8u address, Bit32u value, unsigned io_len)\n{\n unsigned i;\n unsigned write_addr;\n Bit8u new_value, old_value;\n Bit32u mask, value32;\n bx_bool baseaddr_change = 0;\n\n if ((address >= 0x14) && (address < 0x34))\n return;\n if (io_len <= 4) {\n \/\/ This odd code is to display only what bytes actually were written.\n char szTmp[9];\n char szTmp2[3];\n szTmp[0] = '\\0';\n szTmp2[0] = '\\0';\n for (i = 0; i < io_len; i++) {\n write_addr = address + i;\n old_value = BX_PCIVGA_THIS s.pci_conf[write_addr];\n new_value = (Bit8u)(value & 0xff);\n switch (write_addr) {\n case 0x04: \/\/ disallowing write to command\n case 0x06: \/\/ disallowing write to status lo-byte (is that expected?)\n new_value = old_value;\n strcpy(szTmp2, \"..\");\n break;\n case 0x10: \/\/ base address #0\n new_value = (new_value & 0xf0) | (old_value & 0x0f);\n case 0x11: case 0x12: case 0x13:\n baseaddr_change |= (old_value != new_value);\n default:\n sprintf(szTmp2, \"%02x\", new_value);\n }\n BX_PCIVGA_THIS s.pci_conf[write_addr] = new_value;\n value >>= 8;\n strrev(szTmp2);\n strcat(szTmp, szTmp2);\n }\n if (baseaddr_change) {\n \/\/ FIXME: implement changeable LFB address\n ReadHostDWordFromLittleEndian(&BX_PCIVGA_THIS s.pci_conf[0x10], value32);\n mask = ~((VBE_DISPI_TOTAL_VIDEO_MEMORY_MB << 20) - 1);\n value32 &= mask;\n WriteHostDWordToLittleEndian(&BX_PCIVGA_THIS s.pci_conf[0x10], value32);\n }\n strrev(szTmp);\n BX_DEBUG((\"Experimental PCIVGA write register 0x%02x value 0x%s\", address, szTmp));\n }\n}\n\n#endif \/\/ BX_SUPPORT_PCI && BX_SUPPORT_PCIVGA\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 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. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#ifndef HAVE_LIBVLC\n# error This file requires libvlc\n#endif\n\n#include \"NetworkFileSystemFactory.h\"\n#include \"filesystem\/network\/Directory.h\"\n#include \"utils\/VLCInstance.h\"\n#include \"MediaLibrary.h\"\n\n#include <algorithm>\n\nnamespace medialibrary\n{\nnamespace factory\n{\n\nNetworkFileSystemFactory::NetworkFileSystemFactory( const std::string& protocol, const std::string& name )\n : m_protocol( protocol )\n , m_discoverer( VLCInstance::get(), name )\n , m_mediaList( m_discoverer.mediaList() )\n{\n auto& em = m_mediaList->eventManager();\n em.onItemAdded( [this]( VLC::MediaPtr m, int ) { onDeviceAdded( m ); } );\n em.onItemDeleted( [this]( VLC::MediaPtr m, int ) { onDeviceRemoved( m ); } );\n m_discoverer.start();\n}\n\nstd::shared_ptr<fs::IDirectory> NetworkFileSystemFactory::createDirectory( const std::string& path )\n{\n return std::make_shared<fs::NetworkDirectory>( path, *this );\n}\n\nstd::shared_ptr<fs::IDevice> NetworkFileSystemFactory::createDevice( const std::string& mrl )\n{\n std::shared_ptr<fs::IDevice> res;\n std::unique_lock<compat::Mutex> lock( m_devicesLock );\n\n m_deviceCond.wait_for( lock, std::chrono::seconds{ 5 }, [this, &res, &mrl]() {\n auto it = std::find_if( begin( m_devices ), end( m_devices ), [&mrl]( const Device& d ) {\n return d.mrl == mrl;\n });\n if ( it == end( m_devices ) )\n return false;\n res = it->device;\n return true;\n });\n return res;\n}\n\nstd::shared_ptr<fs::IDevice> NetworkFileSystemFactory::createDeviceFromMrl( const std::string& path )\n{\n std::lock_guard<compat::Mutex> lock( m_devicesLock );\n auto it = std::find_if( begin( m_devices ), end( m_devices ), [&path]( const Device& d ) {\n return path.compare( 0, d.mrl.length(), d.mrl );\n });\n if ( it == end( m_devices ) )\n return nullptr;\n return it->device;\n}\n\nvoid NetworkFileSystemFactory::refreshDevices()\n{\n}\n\nbool NetworkFileSystemFactory::isMrlSupported( const std::string& path ) const\n{\n const auto idx = m_protocol.length();\n if ( path.compare( 0, idx, m_protocol ) != 0 )\n return false;\n return path[idx] == ':' && path[idx + 1] == '\/' && path[idx + 2] == '\/';\n\n}\n\nbool NetworkFileSystemFactory::isNetworkFileSystem() const\n{\n return true;\n}\n\nvoid NetworkFileSystemFactory::onDeviceAdded( VLC::MediaPtr media )\n{\n const auto& mrl = media->mrl();\n if ( mrl.compare( 0, m_protocol.length(), m_protocol ) != 0 )\n return;\n\n std::lock_guard<compat::Mutex> lock( m_devicesLock );\n auto it = std::find_if( begin( m_devices ), end( m_devices ), [&mrl]( const Device& d ) {\n return d.mrl== mrl;\n });\n if ( it != end( m_devices ) )\n return;\n const auto idx = m_protocol.length();\n if ( mrl[idx] != ':' || mrl[idx + 1] != '\/' || mrl[idx + 2] != '\/' )\n return;\n\n auto name = mrl.substr( idx + 3 );\n\n m_devices.emplace_back( name, mrl, *media );\n m_deviceCond.notify_one();\n}\n\nvoid NetworkFileSystemFactory::onDeviceRemoved( VLC::MediaPtr media )\n{\n std::lock_guard<compat::Mutex> lock( m_devicesLock );\n const auto& mrl = media->mrl();\n m_devices.erase( std::remove_if( begin( m_devices ), end( m_devices ), [&mrl]( const Device& d ) {\n return d.mrl == mrl;\n }), end( m_devices ) );\n}\n\n}\n}\n<commit_msg>fs: network: Factory: Remove supefluous copy<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 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. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#ifndef HAVE_LIBVLC\n# error This file requires libvlc\n#endif\n\n#include \"NetworkFileSystemFactory.h\"\n#include \"filesystem\/network\/Directory.h\"\n#include \"utils\/VLCInstance.h\"\n#include \"MediaLibrary.h\"\n\n#include <algorithm>\n\nnamespace medialibrary\n{\nnamespace factory\n{\n\nNetworkFileSystemFactory::NetworkFileSystemFactory( const std::string& protocol, const std::string& name )\n : m_protocol( protocol )\n , m_discoverer( VLCInstance::get(), name )\n , m_mediaList( m_discoverer.mediaList() )\n{\n auto& em = m_mediaList->eventManager();\n em.onItemAdded( [this]( VLC::MediaPtr m, int ) { onDeviceAdded( std::move( m ) ); } );\n em.onItemDeleted( [this]( VLC::MediaPtr m, int ) { onDeviceRemoved( std::move( m ) ); } );\n m_discoverer.start();\n}\n\nstd::shared_ptr<fs::IDirectory> NetworkFileSystemFactory::createDirectory( const std::string& path )\n{\n return std::make_shared<fs::NetworkDirectory>( path, *this );\n}\n\nstd::shared_ptr<fs::IDevice> NetworkFileSystemFactory::createDevice( const std::string& mrl )\n{\n std::shared_ptr<fs::IDevice> res;\n std::unique_lock<compat::Mutex> lock( m_devicesLock );\n\n m_deviceCond.wait_for( lock, std::chrono::seconds{ 5 }, [this, &res, &mrl]() {\n auto it = std::find_if( begin( m_devices ), end( m_devices ), [&mrl]( const Device& d ) {\n return d.mrl == mrl;\n });\n if ( it == end( m_devices ) )\n return false;\n res = it->device;\n return true;\n });\n return res;\n}\n\nstd::shared_ptr<fs::IDevice> NetworkFileSystemFactory::createDeviceFromMrl( const std::string& path )\n{\n std::lock_guard<compat::Mutex> lock( m_devicesLock );\n auto it = std::find_if( begin( m_devices ), end( m_devices ), [&path]( const Device& d ) {\n return path.compare( 0, d.mrl.length(), d.mrl );\n });\n if ( it == end( m_devices ) )\n return nullptr;\n return it->device;\n}\n\nvoid NetworkFileSystemFactory::refreshDevices()\n{\n}\n\nbool NetworkFileSystemFactory::isMrlSupported( const std::string& path ) const\n{\n const auto idx = m_protocol.length();\n if ( path.compare( 0, idx, m_protocol ) != 0 )\n return false;\n return path[idx] == ':' && path[idx + 1] == '\/' && path[idx + 2] == '\/';\n\n}\n\nbool NetworkFileSystemFactory::isNetworkFileSystem() const\n{\n return true;\n}\n\nvoid NetworkFileSystemFactory::onDeviceAdded( VLC::MediaPtr media )\n{\n const auto& mrl = media->mrl();\n if ( mrl.compare( 0, m_protocol.length(), m_protocol ) != 0 )\n return;\n\n std::lock_guard<compat::Mutex> lock( m_devicesLock );\n auto it = std::find_if( begin( m_devices ), end( m_devices ), [&mrl]( const Device& d ) {\n return d.mrl== mrl;\n });\n if ( it != end( m_devices ) )\n return;\n const auto idx = m_protocol.length();\n if ( mrl[idx] != ':' || mrl[idx + 1] != '\/' || mrl[idx + 2] != '\/' )\n return;\n\n auto name = mrl.substr( idx + 3 );\n\n m_devices.emplace_back( name, mrl, *media );\n m_deviceCond.notify_one();\n}\n\nvoid NetworkFileSystemFactory::onDeviceRemoved( VLC::MediaPtr media )\n{\n std::lock_guard<compat::Mutex> lock( m_devicesLock );\n const auto& mrl = media->mrl();\n m_devices.erase( std::remove_if( begin( m_devices ), end( m_devices ), [&mrl]( const Device& d ) {\n return d.mrl == mrl;\n }), end( m_devices ) );\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <boost\/thread\/thread.hpp>\n#include <pcl\/common\/common_headers.h>\n#include <pcl\/common\/common_headers.h>\n#include <pcl\/range_image\/range_image.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/visualization\/range_image_visualizer.h>\n#include <pcl\/visualization\/pcl_visualizer.h>\n#include <pcl\/console\/parse.h>\n\ntypedef pcl::PointXYZ PointType;\n\n\/\/ --------------------\n\/\/ -----Parameters-----\n\/\/ --------------------\nfloat angular_resolution_x = 0.5f,\n angular_resolution_y = angular_resolution_x;\npcl::RangeImage::CoordinateFrame coordinate_frame = pcl::RangeImage::CAMERA_FRAME;\nbool live_update = false;\n\n\/\/ --------------\n\/\/ -----Help-----\n\/\/ --------------\nvoid \nprintUsage (const char* progName)\n{\n std::cout << \"\\n\\nUsage: \"<<progName<<\" [options] <scene.pcd>\\n\\n\"\n << \"Options:\\n\"\n << \"-------------------------------------------\\n\"\n << \"-rx <float> angular resolution in degrees (default \"<<angular_resolution_x<<\")\\n\"\n << \"-ry <float> angular resolution in degrees (default \"<<angular_resolution_y<<\")\\n\"\n << \"-c <int> coordinate frame (default \"<< (int)coordinate_frame<<\")\\n\"\n << \"-l live update - update the range image according to the selected view in the 3D viewer.\\n\"\n << \"-h this help\\n\"\n << \"\\n\\n\";\n}\n\nvoid \nsetViewerPose (pcl::visualization::PCLVisualizer& viewer, const Eigen::Affine3f& viewer_pose)\n{\n Eigen::Vector3f pos_vector = viewer_pose * Eigen::Vector3f(0, 0, 0);\n Eigen::Vector3f look_at_vector = viewer_pose.rotation () * Eigen::Vector3f(0, 0, 1) + pos_vector;\n Eigen::Vector3f up_vector = viewer_pose.rotation () * Eigen::Vector3f(0, -1, 0);\n viewer.setCameraPosition (pos_vector[0], pos_vector[1], pos_vector[2],\n look_at_vector[0], look_at_vector[1], look_at_vector[2],\n up_vector[0], up_vector[1], up_vector[2]);\n}\n\n\/\/ --------------\n\/\/ -----Main-----\n\/\/ --------------\nint \nmain (int argc, char** argv)\n{\n \/\/ --------------------------------------\n \/\/ -----Parse Command Line Arguments-----\n \/\/ --------------------------------------\n if (pcl::console::find_argument (argc, argv, \"-h\") >= 0)\n {\n printUsage (argv[0]);\n return 0;\n }\n if (pcl::console::find_argument (argc, argv, \"-l\") >= 0)\n {\n live_update = true;\n std::cout << \"Live update is on.\\n\";\n }\n if (pcl::console::parse (argc, argv, \"-rx\", angular_resolution_x) >= 0)\n std::cout << \"Setting angular resolution in x-direction to \"<<angular_resolution_x<<\"deg.\\n\";\n if (pcl::console::parse (argc, argv, \"-ry\", angular_resolution_y) >= 0)\n std::cout << \"Setting angular resolution in y-direction to \"<<angular_resolution_y<<\"deg.\\n\";\n int tmp_coordinate_frame;\n if (pcl::console::parse (argc, argv, \"-c\", tmp_coordinate_frame) >= 0)\n {\n coordinate_frame = pcl::RangeImage::CoordinateFrame (tmp_coordinate_frame);\n std::cout << \"Using coordinate frame \"<< (int)coordinate_frame<<\".\\n\";\n }\n angular_resolution_x = pcl::deg2rad (angular_resolution_x);\n angular_resolution_y = pcl::deg2rad (angular_resolution_y);\n \n \/\/ ------------------------------------------------------------------\n \/\/ -----Read pcd file or create example point cloud if not given-----\n \/\/ ------------------------------------------------------------------\n pcl::PointCloud<PointType>::Ptr point_cloud_ptr (new pcl::PointCloud<PointType>);\n pcl::PointCloud<PointType>& point_cloud = *point_cloud_ptr;\n Eigen::Affine3f scene_sensor_pose (Eigen::Affine3f::Identity ());\n std::vector<int> pcd_filename_indices = pcl::console::parse_file_extension_argument (argc, argv, \"pcd\");\n if (!pcd_filename_indices.empty ())\n {\n std::string filename = argv[pcd_filename_indices[0]];\n if (pcl::io::loadPCDFile (filename, point_cloud) == -1)\n {\n std::cout << \"Was not able to open file \\\"\"<<filename<<\"\\\".\\n\";\n printUsage (argv[0]);\n return 0;\n }\n scene_sensor_pose = Eigen::Affine3f (Eigen::Translation3f (point_cloud.sensor_origin_[0],\n point_cloud.sensor_origin_[1],\n point_cloud.sensor_origin_[2])) *\n Eigen::Affine3f (point_cloud.sensor_orientation_);\n }\n else\n {\n std::cout << \"\\nNo *.pcd file given => Genarating example point cloud.\\n\\n\";\n for (float x=-0.5f; x<=0.5f; x+=0.01f)\n {\n for (float y=-0.5f; y<=0.5f; y+=0.01f)\n {\n PointType point; point.x = x; point.y = y; point.z = 2.0f - y;\n point_cloud.points.push_back (point);\n }\n }\n point_cloud.width = (int) point_cloud.points.size (); point_cloud.height = 1;\n }\n \n \/\/ -----------------------------------------------\n \/\/ -----Create RangeImage from the PointCloud-----\n \/\/ -----------------------------------------------\n float noise_level = 0.0;\n float min_range = 0.0f;\n int border_size = 1;\n boost::shared_ptr<pcl::RangeImage> range_image_ptr(new pcl::RangeImage);\n pcl::RangeImage& range_image = *range_image_ptr; \n range_image.createFromPointCloud (point_cloud, angular_resolution_x, angular_resolution_y,\n pcl::deg2rad (360.0f), pcl::deg2rad (180.0f),\n scene_sensor_pose, coordinate_frame, noise_level, min_range, border_size);\n \n \/\/ --------------------------------------------\n \/\/ -----Open 3D viewer and add point cloud-----\n \/\/ --------------------------------------------\n pcl::visualization::PCLVisualizer viewer (\"3D Viewer\");\n viewer.setBackgroundColor (1, 1, 1);\n pcl::visualization::PointCloudColorHandlerCustom<pcl::PointWithRange> range_image_color_handler (range_image_ptr, 0, 0, 0);\n viewer.addPointCloud (range_image_ptr, range_image_color_handler, \"range image\");\n viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, \"range image\");\n \/\/viewer.addCoordinateSystem (1.0f);\n \/\/PointCloudColorHandlerCustom<PointType> point_cloud_color_handler (point_cloud_ptr, 150, 150, 150);\n \/\/viewer.addPointCloud (point_cloud_ptr, point_cloud_color_handler, \"original point cloud\");\n viewer.initCameraParameters ();\n setViewerPose(viewer, range_image.getTransformationToWorldSystem ());\n \n \/\/ --------------------------\n \/\/ -----Show range image-----\n \/\/ --------------------------\n pcl::visualization::RangeImageVisualizer range_image_widget (\"Range image\");\n range_image_widget.showRangeImage (range_image);\n \n \/\/--------------------\n \/\/ -----Main loop-----\n \/\/--------------------\n while (!viewer.wasStopped ())\n {\n range_image_widget.spinOnce ();\n viewer.spinOnce ();\n pcl_sleep (0.01);\n \n if (live_update)\n {\n scene_sensor_pose = viewer.getViewerPose();\n range_image.createFromPointCloud (point_cloud, angular_resolution_x, angular_resolution_y,\n pcl::deg2rad (360.0f), pcl::deg2rad (180.0f),\n scene_sensor_pose, pcl::RangeImage::LASER_FRAME, noise_level, min_range, border_size);\n range_image_widget.showRangeImage (range_image);\n }\n }\n}\n<commit_msg>fixed double include<commit_after>#include <iostream>\n\n#include <boost\/thread\/thread.hpp>\n\n#include <pcl\/common\/common_headers.h>\n#include <pcl\/range_image\/range_image.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/visualization\/range_image_visualizer.h>\n#include <pcl\/visualization\/pcl_visualizer.h>\n#include <pcl\/console\/parse.h>\n\ntypedef pcl::PointXYZ PointType;\n\n\/\/ --------------------\n\/\/ -----Parameters-----\n\/\/ --------------------\nfloat angular_resolution_x = 0.5f,\n angular_resolution_y = angular_resolution_x;\npcl::RangeImage::CoordinateFrame coordinate_frame = pcl::RangeImage::CAMERA_FRAME;\nbool live_update = false;\n\n\/\/ --------------\n\/\/ -----Help-----\n\/\/ --------------\nvoid \nprintUsage (const char* progName)\n{\n std::cout << \"\\n\\nUsage: \"<<progName<<\" [options] <scene.pcd>\\n\\n\"\n << \"Options:\\n\"\n << \"-------------------------------------------\\n\"\n << \"-rx <float> angular resolution in degrees (default \"<<angular_resolution_x<<\")\\n\"\n << \"-ry <float> angular resolution in degrees (default \"<<angular_resolution_y<<\")\\n\"\n << \"-c <int> coordinate frame (default \"<< (int)coordinate_frame<<\")\\n\"\n << \"-l live update - update the range image according to the selected view in the 3D viewer.\\n\"\n << \"-h this help\\n\"\n << \"\\n\\n\";\n}\n\nvoid \nsetViewerPose (pcl::visualization::PCLVisualizer& viewer, const Eigen::Affine3f& viewer_pose)\n{\n Eigen::Vector3f pos_vector = viewer_pose * Eigen::Vector3f(0, 0, 0);\n Eigen::Vector3f look_at_vector = viewer_pose.rotation () * Eigen::Vector3f(0, 0, 1) + pos_vector;\n Eigen::Vector3f up_vector = viewer_pose.rotation () * Eigen::Vector3f(0, -1, 0);\n viewer.setCameraPosition (pos_vector[0], pos_vector[1], pos_vector[2],\n look_at_vector[0], look_at_vector[1], look_at_vector[2],\n up_vector[0], up_vector[1], up_vector[2]);\n}\n\n\/\/ --------------\n\/\/ -----Main-----\n\/\/ --------------\nint \nmain (int argc, char** argv)\n{\n \/\/ --------------------------------------\n \/\/ -----Parse Command Line Arguments-----\n \/\/ --------------------------------------\n if (pcl::console::find_argument (argc, argv, \"-h\") >= 0)\n {\n printUsage (argv[0]);\n return 0;\n }\n if (pcl::console::find_argument (argc, argv, \"-l\") >= 0)\n {\n live_update = true;\n std::cout << \"Live update is on.\\n\";\n }\n if (pcl::console::parse (argc, argv, \"-rx\", angular_resolution_x) >= 0)\n std::cout << \"Setting angular resolution in x-direction to \"<<angular_resolution_x<<\"deg.\\n\";\n if (pcl::console::parse (argc, argv, \"-ry\", angular_resolution_y) >= 0)\n std::cout << \"Setting angular resolution in y-direction to \"<<angular_resolution_y<<\"deg.\\n\";\n int tmp_coordinate_frame;\n if (pcl::console::parse (argc, argv, \"-c\", tmp_coordinate_frame) >= 0)\n {\n coordinate_frame = pcl::RangeImage::CoordinateFrame (tmp_coordinate_frame);\n std::cout << \"Using coordinate frame \"<< (int)coordinate_frame<<\".\\n\";\n }\n angular_resolution_x = pcl::deg2rad (angular_resolution_x);\n angular_resolution_y = pcl::deg2rad (angular_resolution_y);\n \n \/\/ ------------------------------------------------------------------\n \/\/ -----Read pcd file or create example point cloud if not given-----\n \/\/ ------------------------------------------------------------------\n pcl::PointCloud<PointType>::Ptr point_cloud_ptr (new pcl::PointCloud<PointType>);\n pcl::PointCloud<PointType>& point_cloud = *point_cloud_ptr;\n Eigen::Affine3f scene_sensor_pose (Eigen::Affine3f::Identity ());\n std::vector<int> pcd_filename_indices = pcl::console::parse_file_extension_argument (argc, argv, \"pcd\");\n if (!pcd_filename_indices.empty ())\n {\n std::string filename = argv[pcd_filename_indices[0]];\n if (pcl::io::loadPCDFile (filename, point_cloud) == -1)\n {\n std::cout << \"Was not able to open file \\\"\"<<filename<<\"\\\".\\n\";\n printUsage (argv[0]);\n return 0;\n }\n scene_sensor_pose = Eigen::Affine3f (Eigen::Translation3f (point_cloud.sensor_origin_[0],\n point_cloud.sensor_origin_[1],\n point_cloud.sensor_origin_[2])) *\n Eigen::Affine3f (point_cloud.sensor_orientation_);\n }\n else\n {\n std::cout << \"\\nNo *.pcd file given => Genarating example point cloud.\\n\\n\";\n for (float x=-0.5f; x<=0.5f; x+=0.01f)\n {\n for (float y=-0.5f; y<=0.5f; y+=0.01f)\n {\n PointType point; point.x = x; point.y = y; point.z = 2.0f - y;\n point_cloud.points.push_back (point);\n }\n }\n point_cloud.width = (int) point_cloud.points.size (); point_cloud.height = 1;\n }\n \n \/\/ -----------------------------------------------\n \/\/ -----Create RangeImage from the PointCloud-----\n \/\/ -----------------------------------------------\n float noise_level = 0.0;\n float min_range = 0.0f;\n int border_size = 1;\n boost::shared_ptr<pcl::RangeImage> range_image_ptr(new pcl::RangeImage);\n pcl::RangeImage& range_image = *range_image_ptr; \n range_image.createFromPointCloud (point_cloud, angular_resolution_x, angular_resolution_y,\n pcl::deg2rad (360.0f), pcl::deg2rad (180.0f),\n scene_sensor_pose, coordinate_frame, noise_level, min_range, border_size);\n \n \/\/ --------------------------------------------\n \/\/ -----Open 3D viewer and add point cloud-----\n \/\/ --------------------------------------------\n pcl::visualization::PCLVisualizer viewer (\"3D Viewer\");\n viewer.setBackgroundColor (1, 1, 1);\n pcl::visualization::PointCloudColorHandlerCustom<pcl::PointWithRange> range_image_color_handler (range_image_ptr, 0, 0, 0);\n viewer.addPointCloud (range_image_ptr, range_image_color_handler, \"range image\");\n viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, \"range image\");\n \/\/viewer.addCoordinateSystem (1.0f);\n \/\/PointCloudColorHandlerCustom<PointType> point_cloud_color_handler (point_cloud_ptr, 150, 150, 150);\n \/\/viewer.addPointCloud (point_cloud_ptr, point_cloud_color_handler, \"original point cloud\");\n viewer.initCameraParameters ();\n setViewerPose(viewer, range_image.getTransformationToWorldSystem ());\n \n \/\/ --------------------------\n \/\/ -----Show range image-----\n \/\/ --------------------------\n pcl::visualization::RangeImageVisualizer range_image_widget (\"Range image\");\n range_image_widget.showRangeImage (range_image);\n \n \/\/--------------------\n \/\/ -----Main loop-----\n \/\/--------------------\n while (!viewer.wasStopped ())\n {\n range_image_widget.spinOnce ();\n viewer.spinOnce ();\n pcl_sleep (0.01);\n \n if (live_update)\n {\n scene_sensor_pose = viewer.getViewerPose();\n range_image.createFromPointCloud (point_cloud, angular_resolution_x, angular_resolution_y,\n pcl::deg2rad (360.0f), pcl::deg2rad (180.0f),\n scene_sensor_pose, pcl::RangeImage::LASER_FRAME, noise_level, min_range, border_size);\n range_image_widget.showRangeImage (range_image);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Linker.cpp -------------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ The SIL linker walks the call graph beginning at a starting function,\n\/\/\/ deserializing functions, vtables and witness tables.\n\/\/\/\n\/\/\/ The behavior of the linker is controlled by a LinkMode value. The LinkMode\n\/\/\/ has three possible values:\n\/\/\/\n\/\/\/ - LinkNone: The linker does not deserialize anything. This is only used for\n\/\/\/ debugging and testing purposes, and never during normal operation.\n\/\/\/\n\/\/\/ - LinkNormal: The linker deserializes bodies for declarations that must be\n\/\/\/ emitted into the client because they do not have definitions available\n\/\/\/ externally. This includes:\n\/\/\/\n\/\/\/ - witness tables for imported conformances\n\/\/\/\n\/\/\/ - functions with shared linkage\n\/\/\/\n\/\/\/ - LinkAll: All reachable functions (including public functions) are\n\/\/\/ deserialized, including public functions.\n\/\/\/\n\/\/\/ The primary entry point into the linker is the SILModule::linkFunction()\n\/\/\/ function, which recursively walks the call graph starting from the given\n\/\/\/ function.\n\/\/\/\n\/\/\/ In the mandatory pipeline (-Onone), the linker is invoked from the mandatory\n\/\/\/ SIL linker pass, which pulls in just enough to allow us to emit code, using\n\/\/\/ LinkNormal mode.\n\/\/\/\n\/\/\/ In the performance pipeline, after guaranteed optimizations but before\n\/\/\/ performance optimizations, the 'performance SILLinker' pass links\n\/\/\/ transitively all reachable functions, to uncover optimization opportunities\n\/\/\/ that might be missed from deserializing late. The performance pipeline uses\n\/\/\/ LinkAll mode.\n\/\/\/\n\/\/\/ *NOTE*: In LinkAll mode, we deserialize all vtables and witness tables,\n\/\/\/ even those with public linkage. This is not strictly necessary, since the\n\/\/\/ devirtualizer deserializes vtables and witness tables as needed. However,\n\/\/\/ doing so early creates more opportunities for optimization.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-linker\"\n#include \"Linker.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/FoldingSet.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"swift\/AST\/ProtocolConformance.h\"\n#include \"swift\/AST\/SubstitutionMap.h\"\n#include \"swift\/ClangImporter\/ClangModule.h\"\n#include \"swift\/SIL\/FormalLinkage.h\"\n#include <functional>\n\nusing namespace swift;\nusing namespace Lowering;\n\nSTATISTIC(NumFuncLinked, \"Number of SIL functions linked\");\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Linker Helpers\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid SILLinkerVisitor::addFunctionToWorklist(SILFunction *F) {\n assert(F->isExternalDeclaration());\n\n LLVM_DEBUG(llvm::dbgs() << \"Imported function: \"\n << F->getName() << \"\\n\");\n if (Mod.loadFunction(F)) {\n if (F->isExternalDeclaration())\n return;\n\n F->setBare(IsBare);\n F->verify();\n Worklist.push_back(F);\n Changed = true;\n ++NumFuncLinked;\n }\n}\n\n\/\/\/ Deserialize a function and add it to the worklist for processing.\nvoid SILLinkerVisitor::maybeAddFunctionToWorklist(SILFunction *F) {\n \/\/ Don't need to do anything if the function already has a body.\n if (!F->isExternalDeclaration())\n return;\n\n \/\/ In the performance pipeline, we deserialize all reachable functions.\n if (isLinkAll())\n return addFunctionToWorklist(F);\n\n \/\/ Otherwise, make sure to deserialize shared functions; we need to\n \/\/ emit them into the client binary since they're not available\n \/\/ externally.\n if (hasSharedVisibility(F->getLinkage()))\n return addFunctionToWorklist(F);\n\n \/\/ Functions with PublicNonABI linkage are deserialized as having\n \/\/ HiddenExternal linkage when they are declarations, then they\n \/\/ become SharedExternal after the body has been deserialized.\n \/\/ So try deserializing HiddenExternal functions too.\n if (F->getLinkage() == SILLinkage::HiddenExternal)\n return addFunctionToWorklist(F);\n}\n\n\/\/\/ Process F, recursively deserializing any thing F may reference.\nbool SILLinkerVisitor::processFunction(SILFunction *F) {\n \/\/ If F is a declaration, first deserialize it.\n if (F->isExternalDeclaration()) {\n maybeAddFunctionToWorklist(F);\n } else {\n Worklist.push_back(F);\n }\n\n process();\n return Changed;\n}\n\n\/\/\/ Deserialize the given VTable all SIL the VTable transitively references.\nvoid SILLinkerVisitor::linkInVTable(ClassDecl *D) {\n \/\/ Devirtualization already deserializes vtables as needed in both the\n \/\/ mandatory and performance pipelines, and we don't support specialized\n \/\/ vtables that might have shared linkage yet, so this is only needed in\n \/\/ the performance pipeline to deserialize more functions early, and expose\n \/\/ optimization opportunities.\n assert(isLinkAll());\n\n \/\/ Attempt to lookup the Vtbl from the SILModule.\n SILVTable *Vtbl = Mod.lookUpVTable(D);\n if (!Vtbl)\n return;\n\n \/\/ Ok we found our VTable. Visit each function referenced by the VTable. If\n \/\/ any of the functions are external declarations, add them to the worklist\n \/\/ for processing.\n for (auto P : Vtbl->getEntries()) {\n \/\/ Deserialize and recursively walk any vtable entries that do not have\n \/\/ bodies yet.\n maybeAddFunctionToWorklist(P.Implementation);\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Visitors\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {\n if (auto sig = AI->getCallee()->getType().castTo<SILFunctionType>()\n ->getGenericSignature()) {\n visitApplySubstitutions(AI->getSubstitutionMap());\n }\n}\n\nvoid SILLinkerVisitor::visitTryApplyInst(TryApplyInst *TAI) {\n if (auto sig = TAI->getCallee()->getType().castTo<SILFunctionType>()\n ->getGenericSignature()) {\n visitApplySubstitutions(TAI->getSubstitutionMap());\n }\n}\n\nvoid SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {\n if (auto sig = PAI->getCallee()->getType().castTo<SILFunctionType>()\n ->getGenericSignature()) {\n visitApplySubstitutions(PAI->getSubstitutionMap());\n }\n}\n\nvoid SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {\n maybeAddFunctionToWorklist(FRI->getReferencedFunction());\n}\n\n\/\/ Eagerly visiting all used conformances leads to a large blowup\n\/\/ in the amount of SIL we read in. For optimization purposes we can defer\n\/\/ reading in most conformances until we need them for devirtualization.\n\/\/ However, we *must* pull in shared clang-importer-derived conformances\n\/\/ we potentially use, since we may not otherwise have a local definition.\nstatic bool mustDeserializeProtocolConformance(SILModule &M,\n ProtocolConformanceRef c) {\n if (!c.isConcrete())\n return false;\n auto conformance = c.getConcrete()->getRootNormalConformance();\n return M.Types.protocolRequiresWitnessTable(conformance->getProtocol())\n && isa<ClangModuleUnit>(conformance->getDeclContext()\n ->getModuleScopeContext());\n}\n\nvoid SILLinkerVisitor::visitProtocolConformance(\n ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {\n \/\/ If an abstract protocol conformance was passed in, just return false.\n if (ref.isAbstract())\n return;\n \n bool mustDeserialize = mustDeserializeProtocolConformance(Mod, ref);\n\n \/\/ Otherwise try and lookup a witness table for C.\n auto C = ref.getConcrete();\n \n if (!VisitedConformances.insert(C).second)\n return;\n \n SILWitnessTable *WT = Mod.lookUpWitnessTable(C, true);\n\n \/\/ If we don't find any witness table for the conformance, bail and return\n \/\/ false.\n if (!WT) {\n Mod.createWitnessTableDeclaration(\n C, getLinkageForProtocolConformance(\n C->getRootNormalConformance(), NotForDefinition));\n\n \/\/ Adding the declaration may allow us to now deserialize the body.\n \/\/ Force the body if we must deserialize this witness table.\n if (mustDeserialize) {\n WT = Mod.lookUpWitnessTable(C, true);\n assert(WT && WT->isDefinition()\n && \"unable to deserialize witness table when we must?!\");\n } else {\n return;\n }\n }\n\n \/\/ If the looked up witness table is a declaration, there is nothing we can\n \/\/ do here. Just bail and return false.\n if (WT->isDeclaration())\n return;\n\n auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {\n \/\/ Formally all conformances referenced by a used conformance are used.\n \/\/ However, eagerly visiting them all at this point leads to a large blowup\n \/\/ in the amount of SIL we read in. For optimization purposes we can defer\n \/\/ reading in most conformances until we need them for devirtualization.\n \/\/ However, we *must* pull in shared clang-importer-derived conformances\n \/\/ we potentially use, since we may not otherwise have a local definition.\n if (mustDeserializeProtocolConformance(Mod, c))\n visitProtocolConformance(c, None);\n };\n \n \/\/ For each entry in the witness table...\n for (auto &E : WT->getEntries()) {\n switch (E.getKind()) {\n \/\/ If the entry is a witness method...\n case SILWitnessTable::WitnessKind::Method: {\n \/\/ And we are only interested in deserializing a specific requirement\n \/\/ and don't have that requirement, don't deserialize this method.\n if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)\n continue;\n\n \/\/ The witness could be removed by dead function elimination.\n if (!E.getMethodWitness().Witness)\n continue;\n\n \/\/ Otherwise, deserialize the witness if it has shared linkage, or if\n \/\/ we were asked to deserialize everything.\n maybeAddFunctionToWorklist(E.getMethodWitness().Witness);\n break;\n }\n \n \/\/ If the entry is a related witness table, see whether we need to\n \/\/ eagerly deserialize it.\n case SILWitnessTable::WitnessKind::BaseProtocol: {\n auto baseConformance = E.getBaseProtocolWitness().Witness;\n maybeVisitRelatedConformance(ProtocolConformanceRef(baseConformance));\n break;\n }\n case SILWitnessTable::WitnessKind::AssociatedTypeProtocol: {\n auto assocConformance = E.getAssociatedTypeProtocolWitness().Witness;\n maybeVisitRelatedConformance(assocConformance);\n break;\n }\n \n case SILWitnessTable::WitnessKind::AssociatedType:\n case SILWitnessTable::WitnessKind::Invalid:\n break;\n }\n }\n}\n\nvoid SILLinkerVisitor::visitApplySubstitutions(SubstitutionMap subs) {\n for (auto &reqt : subs.getGenericSignature()->getRequirements()) {\n switch (reqt.getKind()) {\n case RequirementKind::Conformance: {\n auto conformance = subs.lookupConformance(\n reqt.getFirstType()->getCanonicalType(),\n cast<ProtocolDecl>(reqt.getSecondType()->getAnyNominal()))\n .getValue();\n \n \/\/ Formally all conformances referenced in a function application are\n \/\/ used. However, eagerly visiting them all at this point leads to a\n \/\/ large blowup in the amount of SIL we read in, and we aren't very\n \/\/ systematic about laziness. For optimization purposes we can defer\n \/\/ reading in most conformances until we need them for devirtualization.\n \/\/ However, we *must* pull in shared clang-importer-derived conformances\n \/\/ we potentially use, since we may not otherwise have a local definition.\n if (mustDeserializeProtocolConformance(Mod, conformance)) {\n visitProtocolConformance(conformance, None);\n }\n break;\n }\n case RequirementKind::Layout:\n case RequirementKind::SameType:\n case RequirementKind::Superclass:\n break;\n }\n }\n}\n\nvoid SILLinkerVisitor::visitInitExistentialAddrInst(\n InitExistentialAddrInst *IEI) {\n \/\/ Link in all protocol conformances that this touches.\n \/\/\n \/\/ TODO: There might be a two step solution where the init_existential_inst\n \/\/ causes the witness table to be brought in as a declaration and then the\n \/\/ protocol method inst causes the actual deserialization. For now we are\n \/\/ not going to be smart about this to enable avoiding any issues with\n \/\/ visiting the open_existential_addr\/witness_method before the\n \/\/ init_existential_inst.\n for (ProtocolConformanceRef C : IEI->getConformances()) {\n visitProtocolConformance(C, Optional<SILDeclRef>());\n }\n}\n\nvoid SILLinkerVisitor::visitInitExistentialRefInst(\n InitExistentialRefInst *IERI) {\n \/\/ Link in all protocol conformances that this touches.\n \/\/\n \/\/ TODO: There might be a two step solution where the init_existential_inst\n \/\/ causes the witness table to be brought in as a declaration and then the\n \/\/ protocol method inst causes the actual deserialization. For now we are\n \/\/ not going to be smart about this to enable avoiding any issues with\n \/\/ visiting the protocol_method before the init_existential_inst.\n for (ProtocolConformanceRef C : IERI->getConformances()) {\n visitProtocolConformance(C, Optional<SILDeclRef>());\n }\n}\n\nvoid SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {\n if (!isLinkAll())\n return;\n\n \/\/ Grab the class decl from the alloc ref inst.\n ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();\n if (!D)\n return;\n\n linkInVTable(D);\n}\n\nvoid SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {\n if (!isLinkAll())\n return;\n\n CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();\n ClassDecl *C = instTy.getClassOrBoundGenericClass();\n if (!C)\n return;\n\n linkInVTable(C);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Top Level Routine\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Main loop of the visitor. Called by one of the other *visit* methods.\nvoid SILLinkerVisitor::process() {\n \/\/ Process everything transitively referenced by one of the functions in the\n \/\/ worklist.\n while (!Worklist.empty()) {\n auto *Fn = Worklist.pop_back_val();\n\n if (Fn->getModule().isSerialized()) {\n \/\/ If the containing module has been serialized,\n \/\/ Remove The Serialized state (if any)\n \/\/ This allows for more optimizations\n Fn->setSerialized(IsSerialized_t::IsNotSerialized);\n }\n\n LLVM_DEBUG(llvm::dbgs() << \"Process imports in function: \"\n << Fn->getName() << \"\\n\");\n\n for (auto &BB : *Fn) {\n for (auto &I : BB) {\n visit(&I);\n }\n }\n }\n}\n<commit_msg>SIL: Simplify SILLinkerVisitor::visitApplySubstitutions()<commit_after>\/\/===--- Linker.cpp -------------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ The SIL linker walks the call graph beginning at a starting function,\n\/\/\/ deserializing functions, vtables and witness tables.\n\/\/\/\n\/\/\/ The behavior of the linker is controlled by a LinkMode value. The LinkMode\n\/\/\/ has three possible values:\n\/\/\/\n\/\/\/ - LinkNone: The linker does not deserialize anything. This is only used for\n\/\/\/ debugging and testing purposes, and never during normal operation.\n\/\/\/\n\/\/\/ - LinkNormal: The linker deserializes bodies for declarations that must be\n\/\/\/ emitted into the client because they do not have definitions available\n\/\/\/ externally. This includes:\n\/\/\/\n\/\/\/ - witness tables for imported conformances\n\/\/\/\n\/\/\/ - functions with shared linkage\n\/\/\/\n\/\/\/ - LinkAll: All reachable functions (including public functions) are\n\/\/\/ deserialized, including public functions.\n\/\/\/\n\/\/\/ The primary entry point into the linker is the SILModule::linkFunction()\n\/\/\/ function, which recursively walks the call graph starting from the given\n\/\/\/ function.\n\/\/\/\n\/\/\/ In the mandatory pipeline (-Onone), the linker is invoked from the mandatory\n\/\/\/ SIL linker pass, which pulls in just enough to allow us to emit code, using\n\/\/\/ LinkNormal mode.\n\/\/\/\n\/\/\/ In the performance pipeline, after guaranteed optimizations but before\n\/\/\/ performance optimizations, the 'performance SILLinker' pass links\n\/\/\/ transitively all reachable functions, to uncover optimization opportunities\n\/\/\/ that might be missed from deserializing late. The performance pipeline uses\n\/\/\/ LinkAll mode.\n\/\/\/\n\/\/\/ *NOTE*: In LinkAll mode, we deserialize all vtables and witness tables,\n\/\/\/ even those with public linkage. This is not strictly necessary, since the\n\/\/\/ devirtualizer deserializes vtables and witness tables as needed. However,\n\/\/\/ doing so early creates more opportunities for optimization.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-linker\"\n#include \"Linker.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/FoldingSet.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"swift\/AST\/ProtocolConformance.h\"\n#include \"swift\/AST\/SubstitutionMap.h\"\n#include \"swift\/ClangImporter\/ClangModule.h\"\n#include \"swift\/SIL\/FormalLinkage.h\"\n#include <functional>\n\nusing namespace swift;\nusing namespace Lowering;\n\nSTATISTIC(NumFuncLinked, \"Number of SIL functions linked\");\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Linker Helpers\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid SILLinkerVisitor::addFunctionToWorklist(SILFunction *F) {\n assert(F->isExternalDeclaration());\n\n LLVM_DEBUG(llvm::dbgs() << \"Imported function: \"\n << F->getName() << \"\\n\");\n if (Mod.loadFunction(F)) {\n if (F->isExternalDeclaration())\n return;\n\n F->setBare(IsBare);\n F->verify();\n Worklist.push_back(F);\n Changed = true;\n ++NumFuncLinked;\n }\n}\n\n\/\/\/ Deserialize a function and add it to the worklist for processing.\nvoid SILLinkerVisitor::maybeAddFunctionToWorklist(SILFunction *F) {\n \/\/ Don't need to do anything if the function already has a body.\n if (!F->isExternalDeclaration())\n return;\n\n \/\/ In the performance pipeline, we deserialize all reachable functions.\n if (isLinkAll())\n return addFunctionToWorklist(F);\n\n \/\/ Otherwise, make sure to deserialize shared functions; we need to\n \/\/ emit them into the client binary since they're not available\n \/\/ externally.\n if (hasSharedVisibility(F->getLinkage()))\n return addFunctionToWorklist(F);\n\n \/\/ Functions with PublicNonABI linkage are deserialized as having\n \/\/ HiddenExternal linkage when they are declarations, then they\n \/\/ become SharedExternal after the body has been deserialized.\n \/\/ So try deserializing HiddenExternal functions too.\n if (F->getLinkage() == SILLinkage::HiddenExternal)\n return addFunctionToWorklist(F);\n}\n\n\/\/\/ Process F, recursively deserializing any thing F may reference.\nbool SILLinkerVisitor::processFunction(SILFunction *F) {\n \/\/ If F is a declaration, first deserialize it.\n if (F->isExternalDeclaration()) {\n maybeAddFunctionToWorklist(F);\n } else {\n Worklist.push_back(F);\n }\n\n process();\n return Changed;\n}\n\n\/\/\/ Deserialize the given VTable all SIL the VTable transitively references.\nvoid SILLinkerVisitor::linkInVTable(ClassDecl *D) {\n \/\/ Devirtualization already deserializes vtables as needed in both the\n \/\/ mandatory and performance pipelines, and we don't support specialized\n \/\/ vtables that might have shared linkage yet, so this is only needed in\n \/\/ the performance pipeline to deserialize more functions early, and expose\n \/\/ optimization opportunities.\n assert(isLinkAll());\n\n \/\/ Attempt to lookup the Vtbl from the SILModule.\n SILVTable *Vtbl = Mod.lookUpVTable(D);\n if (!Vtbl)\n return;\n\n \/\/ Ok we found our VTable. Visit each function referenced by the VTable. If\n \/\/ any of the functions are external declarations, add them to the worklist\n \/\/ for processing.\n for (auto P : Vtbl->getEntries()) {\n \/\/ Deserialize and recursively walk any vtable entries that do not have\n \/\/ bodies yet.\n maybeAddFunctionToWorklist(P.Implementation);\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Visitors\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {\n if (auto sig = AI->getCallee()->getType().castTo<SILFunctionType>()\n ->getGenericSignature()) {\n visitApplySubstitutions(AI->getSubstitutionMap());\n }\n}\n\nvoid SILLinkerVisitor::visitTryApplyInst(TryApplyInst *TAI) {\n if (auto sig = TAI->getCallee()->getType().castTo<SILFunctionType>()\n ->getGenericSignature()) {\n visitApplySubstitutions(TAI->getSubstitutionMap());\n }\n}\n\nvoid SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {\n if (auto sig = PAI->getCallee()->getType().castTo<SILFunctionType>()\n ->getGenericSignature()) {\n visitApplySubstitutions(PAI->getSubstitutionMap());\n }\n}\n\nvoid SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {\n maybeAddFunctionToWorklist(FRI->getReferencedFunction());\n}\n\n\/\/ Eagerly visiting all used conformances leads to a large blowup\n\/\/ in the amount of SIL we read in. For optimization purposes we can defer\n\/\/ reading in most conformances until we need them for devirtualization.\n\/\/ However, we *must* pull in shared clang-importer-derived conformances\n\/\/ we potentially use, since we may not otherwise have a local definition.\nstatic bool mustDeserializeProtocolConformance(SILModule &M,\n ProtocolConformanceRef c) {\n if (!c.isConcrete())\n return false;\n auto conformance = c.getConcrete()->getRootNormalConformance();\n return M.Types.protocolRequiresWitnessTable(conformance->getProtocol())\n && isa<ClangModuleUnit>(conformance->getDeclContext()\n ->getModuleScopeContext());\n}\n\nvoid SILLinkerVisitor::visitProtocolConformance(\n ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {\n \/\/ If an abstract protocol conformance was passed in, just return false.\n if (ref.isAbstract())\n return;\n \n bool mustDeserialize = mustDeserializeProtocolConformance(Mod, ref);\n\n \/\/ Otherwise try and lookup a witness table for C.\n auto C = ref.getConcrete();\n \n if (!VisitedConformances.insert(C).second)\n return;\n \n SILWitnessTable *WT = Mod.lookUpWitnessTable(C, true);\n\n \/\/ If we don't find any witness table for the conformance, bail and return\n \/\/ false.\n if (!WT) {\n Mod.createWitnessTableDeclaration(\n C, getLinkageForProtocolConformance(\n C->getRootNormalConformance(), NotForDefinition));\n\n \/\/ Adding the declaration may allow us to now deserialize the body.\n \/\/ Force the body if we must deserialize this witness table.\n if (mustDeserialize) {\n WT = Mod.lookUpWitnessTable(C, true);\n assert(WT && WT->isDefinition()\n && \"unable to deserialize witness table when we must?!\");\n } else {\n return;\n }\n }\n\n \/\/ If the looked up witness table is a declaration, there is nothing we can\n \/\/ do here. Just bail and return false.\n if (WT->isDeclaration())\n return;\n\n auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {\n \/\/ Formally all conformances referenced by a used conformance are used.\n \/\/ However, eagerly visiting them all at this point leads to a large blowup\n \/\/ in the amount of SIL we read in. For optimization purposes we can defer\n \/\/ reading in most conformances until we need them for devirtualization.\n \/\/ However, we *must* pull in shared clang-importer-derived conformances\n \/\/ we potentially use, since we may not otherwise have a local definition.\n if (mustDeserializeProtocolConformance(Mod, c))\n visitProtocolConformance(c, None);\n };\n \n \/\/ For each entry in the witness table...\n for (auto &E : WT->getEntries()) {\n switch (E.getKind()) {\n \/\/ If the entry is a witness method...\n case SILWitnessTable::WitnessKind::Method: {\n \/\/ And we are only interested in deserializing a specific requirement\n \/\/ and don't have that requirement, don't deserialize this method.\n if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)\n continue;\n\n \/\/ The witness could be removed by dead function elimination.\n if (!E.getMethodWitness().Witness)\n continue;\n\n \/\/ Otherwise, deserialize the witness if it has shared linkage, or if\n \/\/ we were asked to deserialize everything.\n maybeAddFunctionToWorklist(E.getMethodWitness().Witness);\n break;\n }\n \n \/\/ If the entry is a related witness table, see whether we need to\n \/\/ eagerly deserialize it.\n case SILWitnessTable::WitnessKind::BaseProtocol: {\n auto baseConformance = E.getBaseProtocolWitness().Witness;\n maybeVisitRelatedConformance(ProtocolConformanceRef(baseConformance));\n break;\n }\n case SILWitnessTable::WitnessKind::AssociatedTypeProtocol: {\n auto assocConformance = E.getAssociatedTypeProtocolWitness().Witness;\n maybeVisitRelatedConformance(assocConformance);\n break;\n }\n \n case SILWitnessTable::WitnessKind::AssociatedType:\n case SILWitnessTable::WitnessKind::Invalid:\n break;\n }\n }\n}\n\nvoid SILLinkerVisitor::visitApplySubstitutions(SubstitutionMap subs) {\n for (auto conformance : subs.getConformances()) {\n \/\/ Formally all conformances referenced in a function application are\n \/\/ used. However, eagerly visiting them all at this point leads to a\n \/\/ large blowup in the amount of SIL we read in, and we aren't very\n \/\/ systematic about laziness. For optimization purposes we can defer\n \/\/ reading in most conformances until we need them for devirtualization.\n \/\/ However, we *must* pull in shared clang-importer-derived conformances\n \/\/ we potentially use, since we may not otherwise have a local definition.\n if (mustDeserializeProtocolConformance(Mod, conformance)) {\n visitProtocolConformance(conformance, None);\n }\n }\n}\n\nvoid SILLinkerVisitor::visitInitExistentialAddrInst(\n InitExistentialAddrInst *IEI) {\n \/\/ Link in all protocol conformances that this touches.\n \/\/\n \/\/ TODO: There might be a two step solution where the init_existential_inst\n \/\/ causes the witness table to be brought in as a declaration and then the\n \/\/ protocol method inst causes the actual deserialization. For now we are\n \/\/ not going to be smart about this to enable avoiding any issues with\n \/\/ visiting the open_existential_addr\/witness_method before the\n \/\/ init_existential_inst.\n for (ProtocolConformanceRef C : IEI->getConformances()) {\n visitProtocolConformance(C, Optional<SILDeclRef>());\n }\n}\n\nvoid SILLinkerVisitor::visitInitExistentialRefInst(\n InitExistentialRefInst *IERI) {\n \/\/ Link in all protocol conformances that this touches.\n \/\/\n \/\/ TODO: There might be a two step solution where the init_existential_inst\n \/\/ causes the witness table to be brought in as a declaration and then the\n \/\/ protocol method inst causes the actual deserialization. For now we are\n \/\/ not going to be smart about this to enable avoiding any issues with\n \/\/ visiting the protocol_method before the init_existential_inst.\n for (ProtocolConformanceRef C : IERI->getConformances()) {\n visitProtocolConformance(C, Optional<SILDeclRef>());\n }\n}\n\nvoid SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {\n if (!isLinkAll())\n return;\n\n \/\/ Grab the class decl from the alloc ref inst.\n ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();\n if (!D)\n return;\n\n linkInVTable(D);\n}\n\nvoid SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {\n if (!isLinkAll())\n return;\n\n CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();\n ClassDecl *C = instTy.getClassOrBoundGenericClass();\n if (!C)\n return;\n\n linkInVTable(C);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Top Level Routine\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Main loop of the visitor. Called by one of the other *visit* methods.\nvoid SILLinkerVisitor::process() {\n \/\/ Process everything transitively referenced by one of the functions in the\n \/\/ worklist.\n while (!Worklist.empty()) {\n auto *Fn = Worklist.pop_back_val();\n\n if (Fn->getModule().isSerialized()) {\n \/\/ If the containing module has been serialized,\n \/\/ Remove The Serialized state (if any)\n \/\/ This allows for more optimizations\n Fn->setSerialized(IsSerialized_t::IsNotSerialized);\n }\n\n LLVM_DEBUG(llvm::dbgs() << \"Process imports in function: \"\n << Fn->getName() << \"\\n\");\n\n for (auto &BB : *Fn) {\n for (auto &I : BB) {\n visit(&I);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>AliGenerator* AddMCGenPythia8(Float_t e_cms = 2760., Bool_t kCR = kTRUE, Int_t kF = 1,Int_t kProcess=0,Double_t ptHardMin=0,Double_t ptHardMax=1.) \n{\n \/\/ Add Pythia 8 generator: \n \/\/ -kProcess=0 MB generation\n \/\/ -kProcess=1 Jet production, pthard generation\n \/\/ - Color reconnection = ON\/OFF\n \/\/ - Set k factor, default = 1; range of possible values in xmldoc\/CouplingsAndScales.xml\n\n gSystem->Load(\"liblhapdf\");\n \n AliGenerator *genP = NULL;\n genP = CreatePythia8Gen(e_cms, kCR, kF,kProcess,ptHardMin,ptHardMax);\n \n return genP;\n}\n\nAliGenerator* CreatePythia8Gen(Float_t e_cms, Bool_t kCR, Int_t kF,Int_t kProcess,Double_t ptHardMin,Double_t ptHardMax) {\n \n gSystem->Load(\"libpythia6\");\n gSystem->Load(\"libEGPythia6\");\n gSystem->Load(\"libAliPythia6\");\n gSystem->Load(\"libpythia8\");\n gSystem->Load(\"libAliPythia8\");\n gSystem->Setenv(\"PYTHIA8DATA\", gSystem->ExpandPathName(\"$ALICE_ROOT\/PYTHIA8\/pythia8\/xmldoc\"));\n gSystem->Setenv(\"LHAPDF\", gSystem->ExpandPathName(\"$ALICE_ROOT\/LHAPDF\"));\n gSystem->Setenv(\"LHAPATH\", gSystem->ExpandPathName(\"$ALICE_ROOT\/LHAPDF\/PDFsets\"));\n\n\n AliGenPythiaPlus* gener = new AliGenPythiaPlus(AliPythia8::Instance());\n\n \/\/ set process (MB)\n if(kProcess==0) gener->SetProcess(kPyMbDefault);\n \n \n if(kProcess==1) {gener->SetProcess(kPyJets);\n if(ptHardMin>0.)\n AliPythia8::Instance()->SetPtHardRange(ptHardMin,ptHardMax);\n } \n\n \/\/Centre of mass energy \n gener->SetEnergyCMS(e_cms); \/\/ in GeV\n\n \/\/ Event list\n gener->SetEventListRange(-1, 2);\n\n \/\/ color reconnection\n (AliPythia8::Instance())->ReadString(\"Tune:pp = 5\");\/\/CR\n\n \/\/random seed based on time\n AliPythia8::Instance()->ReadString(\"Random:setSeed = on\");\n AliPythia8::Instance()->ReadString(\"Random:seed = 0\");\n\n if(kCR) \n (AliPythia8::Instance())->ReadString(\"BeamRemnants:reconnectColours = on\");\n else\n (AliPythia8::Instance())->ReadString(\"BeamRemnants:reconnectColours = off\");\n \n \n AliPythia8::Instance()->ReadString(Form(\"MultipartonInteractions:kFactor = %i\", kF));\n \n return gener;\n}\n<commit_msg>adjusting to new names of CR parameters<commit_after>AliGenerator* AddMCGenPythia8(Float_t e_cms = 2760., Bool_t kCR = kTRUE, Int_t kF = 1,Int_t kProcess=0,Double_t ptHardMin=0,Double_t ptHardMax=1.) \n{\n \/\/ Add Pythia 8 generator: \n \/\/ -kProcess=0 MB generation\n \/\/ -kProcess=1 Jet production, pthard generation\n \/\/ - Color reconnection = ON\/OFF\n \/\/ - Set k factor, default = 1; range of possible values in xmldoc\/CouplingsAndScales.xml\n\n gSystem->Load(\"liblhapdf\");\n \n AliGenerator *genP = NULL;\n genP = CreatePythia8Gen(e_cms, kCR, kF,kProcess,ptHardMin,ptHardMax);\n \n return genP;\n}\n\nAliGenerator* CreatePythia8Gen(Float_t e_cms, Bool_t kCR, Int_t kF,Int_t kProcess,Double_t ptHardMin,Double_t ptHardMax) {\n \n gSystem->Load(\"libpythia6\");\n gSystem->Load(\"libEGPythia6\");\n gSystem->Load(\"libAliPythia6\");\n gSystem->Load(\"libpythia8\");\n gSystem->Load(\"libAliPythia8\");\n gSystem->Setenv(\"PYTHIA8DATA\", gSystem->ExpandPathName(\"$ALICE_ROOT\/PYTHIA8\/pythia8\/xmldoc\"));\n gSystem->Setenv(\"LHAPDF\", gSystem->ExpandPathName(\"$ALICE_ROOT\/LHAPDF\"));\n gSystem->Setenv(\"LHAPATH\", gSystem->ExpandPathName(\"$ALICE_ROOT\/LHAPDF\/PDFsets\"));\n\n\n AliGenPythiaPlus* gener = new AliGenPythiaPlus(AliPythia8::Instance());\n\n \/\/ set process (MB)\n if(kProcess==0) gener->SetProcess(kPyMbDefault);\n \n \n if(kProcess==1) {gener->SetProcess(kPyJets);\n if(ptHardMin>0.)\n AliPythia8::Instance()->SetPtHardRange(ptHardMin,ptHardMax);\n } \n\n \/\/Centre of mass energy \n gener->SetEnergyCMS(e_cms); \/\/ in GeV\n\n \/\/ Event list\n gener->SetEventListRange(-1, 2);\n\n \/\/ color reconnection\n (AliPythia8::Instance())->ReadString(\"Tune:pp = 5\");\/\/CR\n\n \/\/random seed based on time\n AliPythia8::Instance()->ReadString(\"Random:setSeed = on\");\n AliPythia8::Instance()->ReadString(\"Random:seed = 0\");\n\n if(kCR) \n (AliPythia8::Instance())->ReadString(\"ColourReconnection:reconnect = on\");\n else\n (AliPythia8::Instance())->ReadString(\"ColourReconnection:reconnect = off\");\n \n \n AliPythia8::Instance()->ReadString(Form(\"MultipartonInteractions:kFactor = %i\", kF));\n \n return gener;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>\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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT 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 OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <QtCrypto>\n#include <QtTest\/QtTest>\n\n#ifdef QT_STATICPLUGIN\n#include \"import_plugins.h\"\n#endif\n\nclass TLSUnitTest : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void initTestCase();\n void cleanupTestCase();\n void testCipherList();\nprivate:\n QCA::Initializer* m_init;\n};\n\nvoid TLSUnitTest::initTestCase()\n{\n m_init = new QCA::Initializer;\n#include \"..\/fixpaths.include\"\n}\n\nvoid TLSUnitTest::cleanupTestCase()\n{\n delete m_init;\n}\n\nvoid TLSUnitTest::testCipherList()\n{\n if(!QCA::isSupported(\"tls\", \"qca-ossl\"))\n\tQWARN(\"TLS not supported for qca-ossl\");\n else {\n\tQCA::TLS *tls = new QCA::TLS(QCA::TLS::Stream, 0, \"qca-ossl\");\n\tQStringList cipherList = tls->supportedCipherSuites(QCA::TLS::TLS_v1);\n\tQVERIFY( cipherList.contains(\"TLS_DHE_RSA_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_DSS_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_RSA_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_DSS_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_RC4_128_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_RC4_128_MD5\") );\n\n\t\/\/ Fedora 20 openssl has no this cipher suites.\n\t\/\/ I just believe that F20 has the most strict patent rules\n\t\/\/ and Fedora list is the minimal default list.\n\t\/\/ It should fit for every openssl distribuition.\n\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_DHE_RSA_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_DHE_DSS_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_RSA_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_RSA_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_RSA_EXPORT_WITH_RC4_40_MD5\") );\n\n\tcipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v3);\n\tQVERIFY( cipherList.contains(\"SSL_DHE_RSA_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_DSS_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_RSA_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_DSS_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_RC4_128_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_RC4_128_MD5\") );\n\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_DHE_RSA_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_DHE_DSS_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_RSA_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_RSA_EXPORT_WITH_RC4_40_MD5\") );\n\n\tcipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v2);\n\tQVERIFY( cipherList.contains(\"SSL_CK_DES_192_EDE3_CBC_WITH_MD5\") );\n\tQVERIFY( cipherList.contains(\"SSL_CK_RC4_128_EXPORT40_WITH_MD5\") );\n\tQVERIFY( cipherList.contains(\"SSL_CK_RC2_128_CBC_WITH_MD5\") );\n\tQVERIFY( cipherList.contains(\"SSL_CK_RC4_128_WITH_MD5\") );\n\tQVERIFY( cipherList.contains(\"SSL_CK_DES_64_CBC_WITH_MD5\") );\n\tQVERIFY( cipherList.contains(\"SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5\") );\n\tQVERIFY( cipherList.contains(\"SSL_CK_RC4_128_EXPORT40_WITH_MD5\") );\n }\n}\n\nQTEST_MAIN(TLSUnitTest)\n\n#include \"tlsunittest.moc\"\n<commit_msg>tlsunittest: disable more ciphers<commit_after>\/**\n * Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>\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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT 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 OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <QtCrypto>\n#include <QtTest\/QtTest>\n\n#ifdef QT_STATICPLUGIN\n#include \"import_plugins.h\"\n#endif\n\nclass TLSUnitTest : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void initTestCase();\n void cleanupTestCase();\n void testCipherList();\nprivate:\n QCA::Initializer* m_init;\n};\n\nvoid TLSUnitTest::initTestCase()\n{\n m_init = new QCA::Initializer;\n#include \"..\/fixpaths.include\"\n}\n\nvoid TLSUnitTest::cleanupTestCase()\n{\n delete m_init;\n}\n\nvoid TLSUnitTest::testCipherList()\n{\n if(!QCA::isSupported(\"tls\", \"qca-ossl\"))\n\tQWARN(\"TLS not supported for qca-ossl\");\n else {\n\tQCA::TLS *tls = new QCA::TLS(QCA::TLS::Stream, 0, \"qca-ossl\");\n\tQStringList cipherList = tls->supportedCipherSuites(QCA::TLS::TLS_v1);\n\tQVERIFY( cipherList.contains(\"TLS_DHE_RSA_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_DSS_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_RSA_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_DHE_DSS_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_RC4_128_SHA\") );\n\tQVERIFY( cipherList.contains(\"TLS_RSA_WITH_RC4_128_MD5\") );\n\n\t\/\/ Fedora 20 openssl has no this cipher suites.\n\t\/\/ I just believe that F20 has the most strict patent rules\n\t\/\/ and Fedora list is the minimal default list.\n\t\/\/ It should fit for every openssl distribuition.\n\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_DHE_RSA_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_DHE_DSS_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_RSA_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_RSA_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"TLS_RSA_EXPORT_WITH_RC4_40_MD5\") );\n\n\tcipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v3);\n\tQVERIFY( cipherList.contains(\"SSL_DHE_RSA_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_DSS_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_AES_256_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_3DES_EDE_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_RSA_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_DHE_DSS_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_AES_128_CBC_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_RC4_128_SHA\") );\n\tQVERIFY( cipherList.contains(\"SSL_RSA_WITH_RC4_128_MD5\") );\n\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_DHE_RSA_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_DHE_DSS_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_RSA_WITH_DES_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_RSA_EXPORT_WITH_RC4_40_MD5\") );\n\n\t\/\/ Debian testing (jessie) has no these ciphers. So disable them.\n\n\t\/\/ cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v2);\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_CK_DES_192_EDE3_CBC_WITH_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_CK_RC4_128_EXPORT40_WITH_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_CK_RC2_128_CBC_WITH_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_CK_RC4_128_WITH_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_CK_DES_64_CBC_WITH_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5\") );\n\t\/\/ QVERIFY( cipherList.contains(\"SSL_CK_RC4_128_EXPORT40_WITH_MD5\") );\n }\n}\n\nQTEST_MAIN(TLSUnitTest)\n\n#include \"tlsunittest.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode: C++; c-file-style: \"gnu\" -*-\n\/\/ kmfilter.cpp\n\/\/ Author: Stefan Taferner <taferner@kde.org>\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"kmfilter.h\"\n#include \"kmfilteraction.h\"\n#include \"kmglobal.h\"\n\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <kconfig.h>\n\n#include <assert.h>\n\n\nKMFilter::KMFilter( KConfig* aConfig, bool popFilter )\n : bPopFilter(popFilter)\n{\n if (!bPopFilter)\n mActions.setAutoDelete( true );\n\n if ( aConfig )\n readConfig( aConfig );\n else if ( bPopFilter )\n mAction = Down;\n else {\n bApplyOnInbound = true;\n bApplyOnOutbound = false;\n bApplyOnExplicit = true;\n bStopProcessingHere = true;\n bConfigureShortcut = false;\n }\n}\n\n\nKMFilter::KMFilter( const KMFilter & aFilter )\n{\n bPopFilter = aFilter.isPopFilter();\n\n if ( !bPopFilter )\n mActions.setAutoDelete( true );\n\n mPattern = aFilter.mPattern;\n\n if ( bPopFilter ){\n mAction = aFilter.mAction;\n } else {\n bApplyOnInbound = aFilter.applyOnInbound();\n bApplyOnOutbound = aFilter.applyOnOutbound();\n bApplyOnExplicit = aFilter.applyOnExplicit();\n bStopProcessingHere = aFilter.stopProcessingHere();\n bConfigureShortcut = aFilter.configureShortcut();\n mIcon = aFilter.icon();\n\n QPtrListIterator<KMFilterAction> it( aFilter.mActions );\n for ( it.toFirst() ; it.current() ; ++it ) {\n KMFilterActionDesc *desc = (*kmkernel->filterActionDict())[ (*it)->name() ];\n if ( desc ) {\n\tKMFilterAction *f = desc->create();\n\tif ( f ) {\n\t f->argsFromString( (*it)->argsAsString() );\n\t mActions.append( f );\n\t}\n }\n }\n }\n}\n\n\/\/ only for !bPopFilter\nKMFilter::ReturnCode KMFilter::execActions( KMMessage* msg, bool& stopIt ) const\n{\n ReturnCode status = NoResult;\n\n QPtrListIterator<KMFilterAction> it( mActions );\n for ( it.toFirst() ; it.current() ; ++it ) {\n\n kdDebug(5006) << \"####### KMFilter::process: going to apply action \"\n\t << (*it)->label() << \" \\\"\" << (*it)->argsAsString()\n\t << \"\\\"\" << endl;\n\n KMFilterAction::ReturnCode result = (*it)->process( msg );\n\n switch ( result ) {\n case KMFilterAction::CriticalError:\n \/\/ in case it's a critical error: return immediately!\n return CriticalError;\n case KMFilterAction::ErrorButGoOn:\n default:\n break;\n }\n }\n\n if ( status == NoResult ) \/\/ No filters matched, keep copy of message\n status = GoOn;\n\n stopIt = stopProcessingHere();\n\n return status;\n}\n\nbool KMFilter::requiresBody( KMMsgBase* msg )\n{\n if (pattern() && pattern()->requiresBody())\n return true; \/\/ no pattern means always matches?\n QPtrListIterator<KMFilterAction> it( *actions() );\n for ( it.toFirst() ; it.current() ; ++it )\n if ((*it)->requiresBody( msg ))\n return true;\n return false;\n}\n\n\/** No descriptions *\/\n\/\/ only for bPopFilter\nvoid KMFilter::setAction(const KMPopFilterAction aAction)\n{\n mAction = aAction;\n}\n\n\/\/ only for bPopFilter\nKMPopFilterAction KMFilter::action()\n{\n return mAction;\n}\n\n\/\/ only for !bPopFilter\nbool KMFilter::folderRemoved( KMFolder* aFolder, KMFolder* aNewFolder )\n{\n bool rem = false;\n\n QPtrListIterator<KMFilterAction> it( mActions );\n for ( it.toFirst() ; it.current() ; ++it )\n if ( (*it)->folderRemoved( aFolder, aNewFolder ) )\n rem = true;\n\n return rem;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMFilter::readConfig(KConfig* config)\n{\n \/\/ MKSearchPattern::readConfig ensures\n \/\/ that the pattern is purified.\n mPattern.readConfig(config);\n\n if (bPopFilter)\n \/\/ get the action description...\n mAction = (KMPopFilterAction) config->readNumEntry( \"action\" );\n else {\n QStringList sets = config->readListEntry(\"apply-on\");\n if ( sets.isEmpty() && !config->hasKey(\"apply-on\") ) {\n bApplyOnOutbound = false;\n bApplyOnInbound = true;\n bApplyOnExplicit = true;\n } else {\n bApplyOnInbound = bool(sets.contains(\"check-mail\"));\n bApplyOnOutbound = bool(sets.contains(\"send-mail\"));\n bApplyOnExplicit = bool(sets.contains(\"manual-filtering\"));\n }\n\n bStopProcessingHere = config->readBoolEntry(\"StopProcessingHere\", true);\n bConfigureShortcut = config->readBoolEntry(\"ConfigureShortcut\", false);\n mIcon = config->readEntry( \"Icon\", \"gear\" );\n\n int i, numActions;\n QString actName, argsName;\n\n mActions.clear();\n\n numActions = config->readNumEntry(\"actions\",0);\n if (numActions > FILTER_MAX_ACTIONS) {\n numActions = FILTER_MAX_ACTIONS ;\n KMessageBox::information( 0, i18n(\"<qt>Too many filter actions in filter rule <b>%1<\/b>.<\/qt>\").arg( mPattern.name() ) );\n }\n\n for ( i=0 ; i < numActions ; i++ ) {\n actName.sprintf(\"action-name-%d\", i);\n argsName.sprintf(\"action-args-%d\", i);\n \/\/ get the action description...\n KMFilterActionDesc *desc = (*kmkernel->filterActionDict())[ config->readEntry( actName ) ];\n if ( desc ) {\n \/\/...create an instance...\n KMFilterAction *fa = desc->create();\n if ( fa ) {\n \t \/\/...load it with it's parameter...\n fa->argsFromString( config->readEntry( argsName ) );\n\t \/\/...check if it's emoty and...\n\t if ( !fa->isEmpty() )\n\t \/\/...append it if it's not and...\n\t mActions.append( fa );\n\t else\n\t \/\/...delete is else.\n\t delete fa;\n }\n } else\n KMessageBox::information( 0 \/* app-global modal dialog box *\/,\n\t\t\t\t i18n(\"<qt>Unknown filter action <b>%1<\/b><br>in filter rule <b>%2<\/b>.<br>Ignoring it.<\/qt>\")\n\t\t\t\t .arg( config->readEntry( actName ) ).arg( mPattern.name() ) );\n }\n }\n}\n\n\nvoid KMFilter::writeConfig(KConfig* config) const\n{\n mPattern.writeConfig(config);\n\n if (bPopFilter) {\n config->writeEntry( \"action\", mAction );\n } else {\n QStringList sets;\n if ( bApplyOnInbound )\n sets.append( \"check-mail\" );\n if ( bApplyOnOutbound )\n sets.append( \"send-mail\" );\n if ( bApplyOnExplicit )\n sets.append( \"manual-filtering\" );\n config->writeEntry( \"apply-on\", sets );\n\n config->writeEntry( \"StopProcessingHere\", bStopProcessingHere );\n config->writeEntry( \"ConfigureShortcut\", bConfigureShortcut );\n config->writeEntry( \"Icon\", mIcon );\n\n QString key;\n int i;\n\n QPtrListIterator<KMFilterAction> it( mActions );\n for ( i=0, it.toFirst() ; it.current() ; ++it, ++i ) {\n config->writeEntry( key.sprintf(\"action-name-%d\", i),\n \t\t\t (*it)->name() );\n config->writeEntry( key.sprintf(\"action-args-%d\", i),\n\t\t\t (*it)->argsAsString() );\n }\n config->writeEntry(\"actions\", i );\n }\n}\n\nvoid KMFilter::purify()\n{\n mPattern.purify();\n\n if (!bPopFilter) {\n QPtrListIterator<KMFilterAction> it( mActions );\n it.toLast();\n while ( it.current() )\n if ( (*it)->isEmpty() )\n mActions.remove ( (*it) );\n else\n --it;\n }\n}\n\nbool KMFilter::isEmpty() const\n{\n if (bPopFilter)\n return mPattern.isEmpty();\n else\n return mPattern.isEmpty() && mActions.isEmpty();\n}\n\n#ifndef NDEBUG\nconst QString KMFilter::asString() const\n{\n QString result;\n\n result += mPattern.asString();\n\n if (bPopFilter){\n result += \" action: \";\n result += mAction;\n result += \"\\n\";\n }\n else {\n QPtrListIterator<KMFilterAction> it( mActions );\n for ( it.toFirst() ; it.current() ; ++it ) {\n result += \" action: \";\n result += (*it)->label();\n result += \" \";\n result += (*it)->argsAsString();\n result += \"\\n\";\n }\n result += \"This filter belongs to the following sets:\";\n if ( bApplyOnInbound )\n result += \" Inbound\";\n if ( bApplyOnOutbound )\n result += \" Outbound\";\n if ( bApplyOnExplicit )\n result += \" Explicit\";\n result += \"\\n\";\n if ( bStopProcessingHere )\n result += \"If it matches, processing stops at this filter.\\n\";\n }\n return result;\n}\n#endif\n<commit_msg>Commiting a patch by Ingo Klöcker: The attached patch fixes the critical bug #71866.<commit_after>\/\/ -*- mode: C++; c-file-style: \"gnu\" -*-\n\/\/ kmfilter.cpp\n\/\/ Author: Stefan Taferner <taferner@kde.org>\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"kmfilter.h\"\n#include \"kmfilteraction.h\"\n#include \"kmglobal.h\"\n\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <kconfig.h>\n\n#include <assert.h>\n\n\nKMFilter::KMFilter( KConfig* aConfig, bool popFilter )\n : bPopFilter(popFilter)\n{\n if (!bPopFilter)\n mActions.setAutoDelete( true );\n\n if ( aConfig )\n readConfig( aConfig );\n else if ( bPopFilter )\n mAction = Down;\n else {\n bApplyOnInbound = true;\n bApplyOnOutbound = false;\n bApplyOnExplicit = true;\n bStopProcessingHere = true;\n bConfigureShortcut = false;\n }\n}\n\n\nKMFilter::KMFilter( const KMFilter & aFilter )\n{\n bPopFilter = aFilter.isPopFilter();\n\n if ( !bPopFilter )\n mActions.setAutoDelete( true );\n\n mPattern = aFilter.mPattern;\n\n if ( bPopFilter ){\n mAction = aFilter.mAction;\n } else {\n bApplyOnInbound = aFilter.applyOnInbound();\n bApplyOnOutbound = aFilter.applyOnOutbound();\n bApplyOnExplicit = aFilter.applyOnExplicit();\n bStopProcessingHere = aFilter.stopProcessingHere();\n bConfigureShortcut = aFilter.configureShortcut();\n mIcon = aFilter.icon();\n\n QPtrListIterator<KMFilterAction> it( aFilter.mActions );\n for ( it.toFirst() ; it.current() ; ++it ) {\n KMFilterActionDesc *desc = (*kmkernel->filterActionDict())[ (*it)->name() ];\n if ( desc ) {\n\tKMFilterAction *f = desc->create();\n\tif ( f ) {\n\t f->argsFromString( (*it)->argsAsString() );\n\t mActions.append( f );\n\t}\n }\n }\n }\n}\n\n\/\/ only for !bPopFilter\nKMFilter::ReturnCode KMFilter::execActions( KMMessage* msg, bool& stopIt ) const\n{\n ReturnCode status = NoResult;\n\n QPtrListIterator<KMFilterAction> it( mActions );\n for ( it.toFirst() ; it.current() ; ++it ) {\n\n kdDebug(5006) << \"####### KMFilter::process: going to apply action \"\n\t << (*it)->label() << \" \\\"\" << (*it)->argsAsString()\n\t << \"\\\"\" << endl;\n\n KMFilterAction::ReturnCode result = (*it)->process( msg );\n\n switch ( result ) {\n case KMFilterAction::CriticalError:\n \/\/ in case it's a critical error: return immediately!\n return CriticalError;\n case KMFilterAction::ErrorButGoOn:\n default:\n break;\n }\n }\n\n if ( status == NoResult ) \/\/ No filters matched, keep copy of message\n status = GoOn;\n\n stopIt = stopProcessingHere();\n\n return status;\n}\n\nbool KMFilter::requiresBody( KMMsgBase* msg )\n{\n if (pattern() && pattern()->requiresBody())\n return true; \/\/ no pattern means always matches?\n QPtrListIterator<KMFilterAction> it( *actions() );\n for ( it.toFirst() ; it.current() ; ++it )\n if ((*it)->requiresBody( msg ))\n return true;\n return false;\n}\n\n\/** No descriptions *\/\n\/\/ only for bPopFilter\nvoid KMFilter::setAction(const KMPopFilterAction aAction)\n{\n mAction = aAction;\n}\n\n\/\/ only for bPopFilter\nKMPopFilterAction KMFilter::action()\n{\n return mAction;\n}\n\n\/\/ only for !bPopFilter\nbool KMFilter::folderRemoved( KMFolder* aFolder, KMFolder* aNewFolder )\n{\n bool rem = false;\n\n QPtrListIterator<KMFilterAction> it( mActions );\n for ( it.toFirst() ; it.current() ; ++it )\n if ( (*it)->folderRemoved( aFolder, aNewFolder ) )\n rem = true;\n\n return rem;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMFilter::readConfig(KConfig* config)\n{\n \/\/ MKSearchPattern::readConfig ensures\n \/\/ that the pattern is purified.\n mPattern.readConfig(config);\n\n if (bPopFilter) {\n \/\/ get the action description...\n QString action = config->readEntry( \"action\" );\n if ( action == \"down\" )\n mAction = Down;\n else if ( action == \"later\" )\n mAction = Later;\n else if ( action == \"delete\" )\n mAction = Delete;\n else\n mAction = NoAction;\n }\n else {\n QStringList sets = config->readListEntry(\"apply-on\");\n if ( sets.isEmpty() && !config->hasKey(\"apply-on\") ) {\n bApplyOnOutbound = false;\n bApplyOnInbound = true;\n bApplyOnExplicit = true;\n } else {\n bApplyOnInbound = bool(sets.contains(\"check-mail\"));\n bApplyOnOutbound = bool(sets.contains(\"send-mail\"));\n bApplyOnExplicit = bool(sets.contains(\"manual-filtering\"));\n }\n\n bStopProcessingHere = config->readBoolEntry(\"StopProcessingHere\", true);\n bConfigureShortcut = config->readBoolEntry(\"ConfigureShortcut\", false);\n mIcon = config->readEntry( \"Icon\", \"gear\" );\n\n int i, numActions;\n QString actName, argsName;\n\n mActions.clear();\n\n numActions = config->readNumEntry(\"actions\",0);\n if (numActions > FILTER_MAX_ACTIONS) {\n numActions = FILTER_MAX_ACTIONS ;\n KMessageBox::information( 0, i18n(\"<qt>Too many filter actions in filter rule <b>%1<\/b>.<\/qt>\").arg( mPattern.name() ) );\n }\n\n for ( i=0 ; i < numActions ; i++ ) {\n actName.sprintf(\"action-name-%d\", i);\n argsName.sprintf(\"action-args-%d\", i);\n \/\/ get the action description...\n KMFilterActionDesc *desc = (*kmkernel->filterActionDict())[ config->readEntry( actName ) ];\n if ( desc ) {\n \/\/...create an instance...\n KMFilterAction *fa = desc->create();\n if ( fa ) {\n \t \/\/...load it with it's parameter...\n fa->argsFromString( config->readEntry( argsName ) );\n\t \/\/...check if it's emoty and...\n\t if ( !fa->isEmpty() )\n\t \/\/...append it if it's not and...\n\t mActions.append( fa );\n\t else\n\t \/\/...delete is else.\n\t delete fa;\n }\n } else\n KMessageBox::information( 0 \/* app-global modal dialog box *\/,\n\t\t\t\t i18n(\"<qt>Unknown filter action <b>%1<\/b><br>in filter rule <b>%2<\/b>.<br>Ignoring it.<\/qt>\")\n\t\t\t\t .arg( config->readEntry( actName ) ).arg( mPattern.name() ) );\n }\n }\n}\n\n\nvoid KMFilter::writeConfig(KConfig* config) const\n{\n mPattern.writeConfig(config);\n\n if (bPopFilter) {\n switch ( mAction ) {\n case Down:\n config->writeEntry( \"action\", \"down\" );\n break;\n case Later:\n config->writeEntry( \"action\", \"later\" );\n break;\n case Delete:\n config->writeEntry( \"action\", \"delete\" );\n break;\n default:\n config->writeEntry( \"action\", \"\" );\n }\n } else {\n QStringList sets;\n if ( bApplyOnInbound )\n sets.append( \"check-mail\" );\n if ( bApplyOnOutbound )\n sets.append( \"send-mail\" );\n if ( bApplyOnExplicit )\n sets.append( \"manual-filtering\" );\n config->writeEntry( \"apply-on\", sets );\n\n config->writeEntry( \"StopProcessingHere\", bStopProcessingHere );\n config->writeEntry( \"ConfigureShortcut\", bConfigureShortcut );\n config->writeEntry( \"Icon\", mIcon );\n\n QString key;\n int i;\n\n QPtrListIterator<KMFilterAction> it( mActions );\n for ( i=0, it.toFirst() ; it.current() ; ++it, ++i ) {\n config->writeEntry( key.sprintf(\"action-name-%d\", i),\n \t\t\t (*it)->name() );\n config->writeEntry( key.sprintf(\"action-args-%d\", i),\n\t\t\t (*it)->argsAsString() );\n }\n config->writeEntry(\"actions\", i );\n }\n}\n\nvoid KMFilter::purify()\n{\n mPattern.purify();\n\n if (!bPopFilter) {\n QPtrListIterator<KMFilterAction> it( mActions );\n it.toLast();\n while ( it.current() )\n if ( (*it)->isEmpty() )\n mActions.remove ( (*it) );\n else\n --it;\n }\n}\n\nbool KMFilter::isEmpty() const\n{\n if (bPopFilter)\n return mPattern.isEmpty();\n else\n return mPattern.isEmpty() && mActions.isEmpty();\n}\n\n#ifndef NDEBUG\nconst QString KMFilter::asString() const\n{\n QString result;\n\n result += mPattern.asString();\n\n if (bPopFilter){\n result += \" action: \";\n result += mAction;\n result += \"\\n\";\n }\n else {\n QPtrListIterator<KMFilterAction> it( mActions );\n for ( it.toFirst() ; it.current() ; ++it ) {\n result += \" action: \";\n result += (*it)->label();\n result += \" \";\n result += (*it)->argsAsString();\n result += \"\\n\";\n }\n result += \"This filter belongs to the following sets:\";\n if ( bApplyOnInbound )\n result += \" Inbound\";\n if ( bApplyOnOutbound )\n result += \" Outbound\";\n if ( bApplyOnExplicit )\n result += \" Explicit\";\n result += \"\\n\";\n if ( bStopProcessingHere )\n result += \"If it matches, processing stops at this filter.\\n\";\n }\n return result;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * KNotes\n *\n * $Id$\n *\n * Copyright (C) 1997 Bernd Johannes Wuebben\n * wuebben@math.cornell.edu\n * \n * This program 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 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 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 program; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include \"knotes.h\"\n\n#include <qtooltip.h>\n#include <kwm.h>\n#include <kapp.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n\n#include \"knotes.h\"\n#include \"docking.h\"\n\n\/\/extern QStrList KPostit::PostitFilesList; \/\/ names of all postit files\n\/\/extern QList<KPostit> \t KPostit::PostitList; \n\nDockWidget::DockWidget(const char *name): QWidget(0, name, 0) {\n\n docked = false;\n\n pos_x = pos_y = 0;\n\n picsmall_pixmap = KGlobal::iconLoader()->loadApplicationMiniIcon( \"knotes.xpm\" );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ popup menu for left mouse button\n\n popup_m = new QPopupMenu();\n\n createLeftPopUp();\n\n connect( popup_m, SIGNAL(activated( int )),SLOT(findKPostit(int)) );\n popup_m->adjustSize();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ right_popup menu for left mouse button\n\n right_popup_m = new QPopupMenu();\n right_popup_m->insertItem (i18n(\"Help\"),this,SLOT(help()));\n\n right_popup_m->insertItem(i18n(\"Change Defaults\"),\n\t\t\t this, SLOT(configureKNotes()));\n\n right_popup_m->insertSeparator();\n\n right_popup_m->insertItem (i18n(\"Exit Knotes\"),\n\t\t\t this, SLOT(exitKNotes()));\n\n \/\/ connect( right_popup_m, SIGNAL(activated( int )),SLOT(rightAction(int)) );\n right_popup_m->adjustSize();\n\n\n}\n\nDockWidget::~DockWidget(){\n\n\n}\n\nvoid DockWidget::createLeftPopUp(){\n\n \/\/ printf(\"In creatLeftPopUp\\n\");\n popup_m->clear();\n\n newID = popup_m->insertItem(i18n(\"New Knote\"),\n\t\t\t\t this, SLOT(newKNote()));\n\n popup_m->insertSeparator();\n\n for ( uint i = 0; i < KPostit::PostitFilesList.count(); i++){\n \n popup_m->insertItem (KPostit::PostitFilesList[i]);\n\n }\n}\n\nvoid DockWidget::newKNote(){\n\n KPostit* postit;\n\n if(KPostit::PostitFilesList.count() == 0 ){\n\n KPostit::PostitFilesList.append(\"knote 1\");\n postit = new KPostit(NULL,NULL,0,KPostit::PostitFilesList.last());\n\n KPostit::PostitList.append(postit); \n postit->show();\n createLeftPopUp();\n\n }\n else{\n\n KPostit::PostitList.first()->newKPostit(); \n }\n\n\n}\nvoid DockWidget::exitKNotes(){\n\n \/\/ printf(\"in exitKNotes\\n\");\n\n if(KPostit::PostitList.count() > 0){\n\n \/\/ printf(\"about to exit via PostitList\\n\");\n KPostit::PostitList.at(0)->quit();\n\n }\n else{\n QApplication::exit();\n }\n\n}\n\nvoid DockWidget::configureKNotes(){\n\n\n KPostit* postit;\n\n if(KPostit::PostitFilesList.count() == 0 ){\n\n KPostit::PostitFilesList.append(\"knote 1\");\n postit = new KPostit(NULL,NULL,0,KPostit::PostitFilesList.last());\n\n KPostit::PostitList.append(postit); \n\n\n }\n\n KPostit::PostitList.at(0)->defaults();\n createLeftPopUp();\n\n}\n\n\nvoid DockWidget::help(){\n\n kapp->invokeHTMLHelp(\"\",\"\");\n\n}\n\n\nvoid DockWidget::dock() {\n\n if (!docked) {\n \/\/ prepare panel to accept this widget\n KWM::setDockWindow (this->winId());\n\n \/\/ that's all the space there is\n this->setFixedSize(24, 24);\n\n \/\/ finally dock the widget\n this->show();\n docked = true;\n }\n\n}\n\nvoid DockWidget::findKPostit(int i){\n\n \/\/ convert absolute id to relative index\n i = popup_m->indexOf(i);\n\n if(KPostit::PostitList.count() > 0 && i > 1){\n KPostit::PostitList.at(0)->findKPostit( i - 2 );\n }\n\n}\n\n\nvoid DockWidget::undock() {\n\n if (docked) {\n \/\/ new docking method, taken from ksirc (servercontroller.cpp)\n this->hide();\n this->recreate(0x0, 0, QPoint(0,0), FALSE); \n docked = false;\n }\n}\n\nconst bool DockWidget::isDocked() {\n\n return docked;\n\n}\n\nvoid DockWidget::paintEvent (QPaintEvent *e) {\n\n (void) e;\n\n paintIcon();\n\n}\n\nvoid DockWidget::paintIcon () {\n\n bitBlt(this, 0, 0, &picsmall_pixmap);\n\n\n}\n\n\nvoid DockWidget::mousePressEvent(QMouseEvent *e) {\n\n if ( e->button() == (LeftButton || MidButton) ) {\n\n QPoint point = this->mapToGlobal (QPoint(0,0));\n\n point = point - QPoint(30,60);\n popup_m->popup(point);\n popup_m->exec();\n return;\n }\n\n if ( e->button() == RightButton ) {\n\n QPoint point = this->mapToGlobal (QPoint(0,0));\n\n point = point - QPoint(30,60);\n right_popup_m->popup(point);\n right_popup_m->exec();\n }\n\n}\n\nvoid DockWidget::toggle_window_state() {\n\n \/*\n \/\/ restore\/hide connect-window\n if(k != 0L) {\n if (k->isVisible()){\n\n\n QPoint point = k->mapToGlobal (QPoint (0,0));\n pos_x = point.x();\n pos_y = point.y();\n k->hide();\n }\n else {\n k->setGeometry(\n\t\t pos_x, \n\t\t pos_y,\n\t\t k->width(),\n\t\t k->height());\n\n k->show();\n }\n }\n *\/\n}\n\n\n\n\n\n#include \"docking.moc\"\n\n\n\n\n\n\n<commit_msg>adopt latest KIconLoader changes<commit_after>\/*\n * KNotes\n *\n * $Id$\n *\n * Copyright (C) 1997 Bernd Johannes Wuebben\n * wuebben@math.cornell.edu\n * \n * This program 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 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 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 program; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include \"knotes.h\"\n\n#include <qtooltip.h>\n#include <kwm.h>\n#include <kapp.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n\n#include \"knotes.h\"\n#include \"docking.h\"\n\n\/\/extern QStrList KPostit::PostitFilesList; \/\/ names of all postit files\n\/\/extern QList<KPostit> \t KPostit::PostitList; \n\nDockWidget::DockWidget(const char *name): QWidget(0, name, 0) {\n\n docked = false;\n\n pos_x = pos_y = 0;\n\n picsmall_pixmap = KGlobal::iconLoader()->loadApplicationIcon( \"knotes\", KIconLoader::Small );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ popup menu for left mouse button\n\n popup_m = new QPopupMenu();\n\n createLeftPopUp();\n\n connect( popup_m, SIGNAL(activated( int )),SLOT(findKPostit(int)) );\n popup_m->adjustSize();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ right_popup menu for left mouse button\n\n right_popup_m = new QPopupMenu();\n right_popup_m->insertItem (i18n(\"Help\"),this,SLOT(help()));\n\n right_popup_m->insertItem(i18n(\"Change Defaults\"),\n\t\t\t this, SLOT(configureKNotes()));\n\n right_popup_m->insertSeparator();\n\n right_popup_m->insertItem (i18n(\"Exit Knotes\"),\n\t\t\t this, SLOT(exitKNotes()));\n\n \/\/ connect( right_popup_m, SIGNAL(activated( int )),SLOT(rightAction(int)) );\n right_popup_m->adjustSize();\n\n\n}\n\nDockWidget::~DockWidget(){\n\n\n}\n\nvoid DockWidget::createLeftPopUp(){\n\n \/\/ printf(\"In creatLeftPopUp\\n\");\n popup_m->clear();\n\n newID = popup_m->insertItem(i18n(\"New Knote\"),\n\t\t\t\t this, SLOT(newKNote()));\n\n popup_m->insertSeparator();\n\n for ( uint i = 0; i < KPostit::PostitFilesList.count(); i++){\n \n popup_m->insertItem (KPostit::PostitFilesList[i]);\n\n }\n}\n\nvoid DockWidget::newKNote(){\n\n KPostit* postit;\n\n if(KPostit::PostitFilesList.count() == 0 ){\n\n KPostit::PostitFilesList.append(\"knote 1\");\n postit = new KPostit(NULL,NULL,0,KPostit::PostitFilesList.last());\n\n KPostit::PostitList.append(postit); \n postit->show();\n createLeftPopUp();\n\n }\n else{\n\n KPostit::PostitList.first()->newKPostit(); \n }\n\n\n}\nvoid DockWidget::exitKNotes(){\n\n \/\/ printf(\"in exitKNotes\\n\");\n\n if(KPostit::PostitList.count() > 0){\n\n \/\/ printf(\"about to exit via PostitList\\n\");\n KPostit::PostitList.at(0)->quit();\n\n }\n else{\n QApplication::exit();\n }\n\n}\n\nvoid DockWidget::configureKNotes(){\n\n\n KPostit* postit;\n\n if(KPostit::PostitFilesList.count() == 0 ){\n\n KPostit::PostitFilesList.append(\"knote 1\");\n postit = new KPostit(NULL,NULL,0,KPostit::PostitFilesList.last());\n\n KPostit::PostitList.append(postit); \n\n\n }\n\n KPostit::PostitList.at(0)->defaults();\n createLeftPopUp();\n\n}\n\n\nvoid DockWidget::help(){\n\n kapp->invokeHTMLHelp(\"\",\"\");\n\n}\n\n\nvoid DockWidget::dock() {\n\n if (!docked) {\n \/\/ prepare panel to accept this widget\n KWM::setDockWindow (this->winId());\n\n \/\/ that's all the space there is\n this->setFixedSize(24, 24);\n\n \/\/ finally dock the widget\n this->show();\n docked = true;\n }\n\n}\n\nvoid DockWidget::findKPostit(int i){\n\n \/\/ convert absolute id to relative index\n i = popup_m->indexOf(i);\n\n if(KPostit::PostitList.count() > 0 && i > 1){\n KPostit::PostitList.at(0)->findKPostit( i - 2 );\n }\n\n}\n\n\nvoid DockWidget::undock() {\n\n if (docked) {\n \/\/ new docking method, taken from ksirc (servercontroller.cpp)\n this->hide();\n this->recreate(0x0, 0, QPoint(0,0), FALSE); \n docked = false;\n }\n}\n\nconst bool DockWidget::isDocked() {\n\n return docked;\n\n}\n\nvoid DockWidget::paintEvent (QPaintEvent *e) {\n\n (void) e;\n\n paintIcon();\n\n}\n\nvoid DockWidget::paintIcon () {\n\n bitBlt(this, 0, 0, &picsmall_pixmap);\n\n\n}\n\n\nvoid DockWidget::mousePressEvent(QMouseEvent *e) {\n\n if ( e->button() == (LeftButton || MidButton) ) {\n\n QPoint point = this->mapToGlobal (QPoint(0,0));\n\n point = point - QPoint(30,60);\n popup_m->popup(point);\n popup_m->exec();\n return;\n }\n\n if ( e->button() == RightButton ) {\n\n QPoint point = this->mapToGlobal (QPoint(0,0));\n\n point = point - QPoint(30,60);\n right_popup_m->popup(point);\n right_popup_m->exec();\n }\n\n}\n\nvoid DockWidget::toggle_window_state() {\n\n \/*\n \/\/ restore\/hide connect-window\n if(k != 0L) {\n if (k->isVisible()){\n\n\n QPoint point = k->mapToGlobal (QPoint (0,0));\n pos_x = point.x();\n pos_y = point.y();\n k->hide();\n }\n else {\n k->setGeometry(\n\t\t pos_x, \n\t\t pos_y,\n\t\t k->width(),\n\t\t k->height());\n\n k->show();\n }\n }\n *\/\n}\n\n\n\n\n\n#include \"docking.moc\"\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Clear LexTableBuilder's state after detecting conflicts<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Attempting to serialize sprites<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ZXSpectrum.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 17\/03\/2021.\n\/\/ Copyright © 2021 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"ZXSpectrum.hpp\"\n\n#include \"..\/..\/MachineTypes.hpp\"\n\n#include \"..\/..\/..\/Analyser\/Static\/ZXSpectrum\/Target.hpp\"\n\n#include <array>\n\nnamespace {\n\tconst unsigned int ClockRate = 3'500'000;\n}\n\n\nnamespace Sinclair {\nnamespace ZXSpectrum {\n\nusing Model = Analyser::Static::ZXSpectrum::Target::Model;\ntemplate<Model model> class ConcreteMachine:\n\tpublic MachineTypes::ScanProducer,\n\tpublic MachineTypes::TimedMachine,\n\tpublic Machine {\n\tpublic:\n\t\tConcreteMachine(const Analyser::Static::ZXSpectrum::Target &target, const ROMMachine::ROMFetcher &rom_fetcher)\n\t\t{\n\t\t\tset_clock_rate(ClockRate);\n\n\t\t\t\/\/ With only the +2a and +3 currently supported, the +3 ROM is always\n\t\t\t\/\/ the one required.\n\t\t\tconst auto roms =\n\t\t\t\trom_fetcher({ {\"ZXSpectrum\", \"the +2a\/+3 ROM\", \"plus3.rom\", 64 * 1024, 0x96e3c17a} });\n\t\t\tif(!roms[0]) throw ROMMachine::Error::MissingROMs;\n\t\t\tmemcpy(rom_.data(), roms[0]->data(), std::min(rom_.size(), roms[0]->size()));\n\n\t\t\t\/\/ TODO: insert media, set up memory map.\n\t\t\t(void)target;\n\t\t}\n\n\t\t\/\/ MARK: - TimedMachine\n\n\t\tvoid run_for(const Cycles cycles) override {\n\t\t\t\/\/ TODO.\n\t\t\t(void)cycles;\n\t\t}\n\n\t\t\/\/ MARK: - ScanProducer\n\n\t\tvoid set_scan_target(Outputs::Display::ScanTarget *scan_target) final {\n\t\t\t(void)scan_target;\n\t\t}\n\n\t\tOutputs::Display::ScanStatus get_scaled_scan_status() const final {\n\t\t\t\/\/ TODO.\n\t\t\treturn Outputs::Display::ScanStatus();\n\t\t}\n\n\tprivate:\n\t\tstd::array<uint8_t, 64*1024> rom_;\n\t\tstd::array<uint8_t, 128*1024> ram_;\n};\n\n\n}\n}\n\nusing namespace Sinclair::ZXSpectrum;\n\nMachine *Machine::ZXSpectrum(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) {\n\tconst auto zx_target = dynamic_cast<const Analyser::Static::ZXSpectrum::Target *>(target);\n\n\tswitch(zx_target->model) {\n\t\tcase Model::Plus2a:\treturn new ConcreteMachine<Model::Plus2a>(*zx_target, rom_fetcher);\n\t\tcase Model::Plus3:\treturn new ConcreteMachine<Model::Plus3>(*zx_target, rom_fetcher);\n\t}\n\n\treturn nullptr;\n}\n\nMachine::~Machine() {}\n<commit_msg>Stumbles towards a memory map.<commit_after>\/\/\n\/\/ ZXSpectrum.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 17\/03\/2021.\n\/\/ Copyright © 2021 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"ZXSpectrum.hpp\"\n\n#include \"..\/..\/MachineTypes.hpp\"\n\n#include \"..\/..\/..\/Processors\/Z80\/Z80.hpp\"\n\n#include \"..\/..\/..\/Analyser\/Static\/ZXSpectrum\/Target.hpp\"\n\n#include <array>\n\nnamespace {\n\tconst unsigned int ClockRate = 3'500'000;\n}\n\n\nnamespace Sinclair {\nnamespace ZXSpectrum {\n\nusing Model = Analyser::Static::ZXSpectrum::Target::Model;\ntemplate<Model model> class ConcreteMachine:\n\tpublic Machine,\n\tpublic MachineTypes::ScanProducer,\n\tpublic MachineTypes::TimedMachine,\n\tpublic CPU::Z80::BusHandler {\n\tpublic:\n\t\tConcreteMachine(const Analyser::Static::ZXSpectrum::Target &target, const ROMMachine::ROMFetcher &rom_fetcher) :\n\t\t\tz80_(*this)\n\t\t{\n\t\t\tset_clock_rate(ClockRate);\n\n\t\t\t\/\/ With only the +2a and +3 currently supported, the +3 ROM is always\n\t\t\t\/\/ the one required.\n\t\t\tconst auto roms =\n\t\t\t\trom_fetcher({ {\"ZXSpectrum\", \"the +2a\/+3 ROM\", \"plus3.rom\", 64 * 1024, 0x96e3c17a} });\n\t\t\tif(!roms[0]) throw ROMMachine::Error::MissingROMs;\n\t\t\tmemcpy(rom_.data(), roms[0]->data(), std::min(rom_.size(), roms[0]->size()));\n\n\t\t\t\/\/ Set up initial memory map.\n\t\t\tupdate_memory_map();\n\n\t\t\t\/\/ TODO: insert media.\n\t\t\t(void)target;\n\t\t}\n\n\t\t\/\/ MARK: - TimedMachine\n\n\t\tvoid run_for(const Cycles cycles) override {\n\t\t\tz80_.run_for(cycles);\n\t\t}\n\n\t\t\/\/ MARK: - ScanProducer\n\n\t\tvoid set_scan_target(Outputs::Display::ScanTarget *scan_target) final {\n\t\t\t(void)scan_target;\n\t\t}\n\n\t\tOutputs::Display::ScanStatus get_scaled_scan_status() const final {\n\t\t\t\/\/ TODO.\n\t\t\treturn Outputs::Display::ScanStatus();\n\t\t}\n\n\t\t\/\/ MARK: - BusHandler\n\n\t\tforceinline HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) {\n\t\t\t(void)cycle;\n\n\t\t\treturn HalfCycles(0);\n\t\t}\n\n\tprivate:\n\t\tCPU::Z80::Processor<ConcreteMachine, false, false> z80_;\n\n\t\t\/\/ MARK: - Memory.\n\t\tstd::array<uint8_t, 64*1024> rom_;\n\t\tstd::array<uint8_t, 128*1024> ram_;\n\n\t\tstd::array<uint8_t, 16*1024> scratch_;\n\t\tconst uint8_t *read_pointers_[4];\n\t\tuint8_t *write_pointers_[4];\n\n\t\tuint8_t port1ffd_ = 0;\n\t\tuint8_t port7ffd_ = 0;\n\t\tbool disable_paging_ = false;\n\n\t\tvoid update_memory_map() {\n\t\t\tif(disable_paging_) {\n\t\t\t\t\/\/ Set 48kb-esque memory map.\n\t\t\t\tset_memory(0, rom_.data(), nullptr);\n\t\t\t\tset_memory(1, &ram_[5 * 16384], &ram_[5 * 16384]);\n\t\t\t\tset_memory(2, &ram_[2 * 16384], &ram_[2 * 16384]);\n\t\t\t\tset_memory(3, &ram_[0 * 16384], &ram_[0 * 16384]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif(port1ffd_ & 1) {\n\t\t\t\t\/\/ \"Special paging mode\", i.e. one of four fixed\n\t\t\t\t\/\/ RAM configurations, port 7ffd doesn't matter.\n\n\t\t\t\tswitch(port1ffd_ & 0x6) {\n\t\t\t\t\tdefault:\n\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\tset_memory(0, &ram_[0 * 16384], &ram_[0 * 16384]);\n\t\t\t\t\t\tset_memory(1, &ram_[1 * 16384], &ram_[1 * 16384]);\n\t\t\t\t\t\tset_memory(2, &ram_[2 * 16384], &ram_[2 * 16384]);\n\t\t\t\t\t\tset_memory(3, &ram_[3 * 16384], &ram_[3 * 16384]);\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 0x02:\n\t\t\t\t\t\tset_memory(0, &ram_[4 * 16384], &ram_[4 * 16384]);\n\t\t\t\t\t\tset_memory(1, &ram_[5 * 16384], &ram_[5 * 16384]);\n\t\t\t\t\t\tset_memory(2, &ram_[6 * 16384], &ram_[6 * 16384]);\n\t\t\t\t\t\tset_memory(3, &ram_[7 * 16384], &ram_[7 * 16384]);\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 0x04:\n\t\t\t\t\t\tset_memory(0, &ram_[4 * 16384], &ram_[4 * 16384]);\n\t\t\t\t\t\tset_memory(1, &ram_[5 * 16384], &ram_[5 * 16384]);\n\t\t\t\t\t\tset_memory(2, &ram_[6 * 16384], &ram_[6 * 16384]);\n\t\t\t\t\t\tset_memory(3, &ram_[3 * 16384], &ram_[3 * 16384]);\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 0x06:\n\t\t\t\t\t\tset_memory(0, &ram_[4 * 16384], &ram_[4 * 16384]);\n\t\t\t\t\t\tset_memory(1, &ram_[7 * 16384], &ram_[7 * 16384]);\n\t\t\t\t\t\tset_memory(2, &ram_[6 * 16384], &ram_[6 * 16384]);\n\t\t\t\t\t\tset_memory(3, &ram_[3 * 16384], &ram_[3 * 16384]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Apply standard 128kb-esque mapping (albeit with extra ROM to pick from).\n\t\t\tconst auto rom = &rom_[ (((port1ffd_ >> 1) & 2) | ((port7ffd_ >> 4) & 1)) * 16384];\n\t\t\tset_memory(0, rom, nullptr);\n\n\t\t\tset_memory(1, &ram_[5 * 16384], &ram_[5 * 16384]);\n\t\t\tset_memory(2, &ram_[2 * 16384], &ram_[2 * 16384]);\n\n\t\t\tconst auto high_ram = &ram_[(port7ffd_ & 7) * 16384];\n\t\t\tset_memory(3, high_ram, high_ram);\n\t\t}\n\n\t\tvoid set_memory(int bank, const uint8_t *read, uint8_t *write) {\n\t\t\tread_pointers_[bank] = read - bank*16384;\n\t\t\twrite_pointers_[bank] = (write ? write : scratch_.data()) - bank*16384;\n\t\t}\n};\n\n\n}\n}\n\nusing namespace Sinclair::ZXSpectrum;\n\nMachine *Machine::ZXSpectrum(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) {\n\tconst auto zx_target = dynamic_cast<const Analyser::Static::ZXSpectrum::Target *>(target);\n\n\tswitch(zx_target->model) {\n\t\tcase Model::Plus2a:\treturn new ConcreteMachine<Model::Plus2a>(*zx_target, rom_fetcher);\n\t\tcase Model::Plus3:\treturn new ConcreteMachine<Model::Plus3>(*zx_target, rom_fetcher);\n\t}\n\n\treturn nullptr;\n}\n\nMachine::~Machine() {}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Natron\n\/\/\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012.\n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Curve.h\"\n\n#include <algorithm>\n\n#include \"Engine\/CurvePrivate.h\"\n#include \"Engine\/Interpolation.h\"\n\nnamespace {\n struct KeyFrameCloner {\n boost::shared_ptr<KeyFrame> operator()(const boost::shared_ptr<KeyFrame>& kf) const { return boost::shared_ptr<KeyFrame>(new KeyFrame(kf->getTime(),kf->getValue())); }\n };\n\n class KeyFrameTimePredicate\n {\n public:\n KeyFrameTimePredicate(double t) : _t(t) {};\n\n bool operator()(const boost::shared_ptr<KeyFrame>& f) { return (f->getTime() == _t); }\n private:\n double _t;\n };\n}\n\n\/************************************KEYFRAME************************************\/\n\nKeyFrame::KeyFrame()\n : _imp(new KeyFramePrivate)\n{}\n\n\nKeyFrame::KeyFrame(double time, const Variant& initialValue)\n : _imp(new KeyFramePrivate(time,initialValue))\n{\n}\n\nKeyFrame::KeyFrame(const KeyFrame& other)\n : _imp(new KeyFramePrivate(*(other._imp)))\n{\n}\n\nvoid KeyFrame::operator=(const KeyFrame& o)\n{\n _imp->time = o._imp->time;\n _imp->value = o._imp->value;\n _imp->leftTangent = o._imp->leftTangent;\n _imp->rightTangent = o._imp->rightTangent;\n _imp->interpolation = o._imp->interpolation;\n}\n\nKeyFrame::~KeyFrame(){}\n\nbool KeyFrame::operator==(const KeyFrame& o) const {\n return _imp->value == o._imp->value &&\n _imp->time == o._imp->time;\n}\n\n\nvoid KeyFrame::setLeftTangent(const Variant& v){\n _imp->leftTangent = v;\n}\n\n\nvoid KeyFrame::setRightTangent(const Variant& v){\n _imp->rightTangent = v;\n}\n\n\nvoid KeyFrame::setValue(const Variant& v){\n _imp->value = v;\n}\n\nvoid KeyFrame::setTime(double time){\n _imp->time = time;\n}\n\n\nvoid KeyFrame::setInterpolation(Natron::KeyframeType interp) { _imp->interpolation = interp; }\n\nNatron::KeyframeType KeyFrame::getInterpolation() const { return _imp->interpolation; }\n\n\nconst Variant& KeyFrame::getValue() const { return _imp->value; }\n\ndouble KeyFrame::getTime() const { return _imp->time; }\n\nconst Variant& KeyFrame::getLeftTangent() const { return _imp->leftTangent; }\n\nconst Variant& KeyFrame::getRightTangent() const { return _imp->rightTangent; }\n\n\/************************************CURVEPATH************************************\/\n\nCurve::Curve()\n : _imp(new CurvePrivate)\n{\n\n}\n\nCurve::Curve(Knob *owner)\n : _imp(new CurvePrivate)\n{\n _imp->owner = owner;\n}\n\nCurve::~Curve(){ clearKeyFrames(); }\n\nvoid Curve::clearKeyFrames(){\n _imp->keyFrames.clear();\n}\n\n\n\nvoid Curve::clone(const Curve& other){\n clearKeyFrames();\n const KeyFrameSet& otherKeys = other.getKeyFrames();\n std::transform(otherKeys.begin(), otherKeys.end(), std::inserter(_imp->keyFrames, _imp->keyFrames.begin()), KeyFrameCloner());\n}\n\n\ndouble Curve::getMinimumTimeCovered() const{\n assert(!_imp->keyFrames.empty());\n return (*_imp->keyFrames.begin())->getTime();\n}\n\ndouble Curve::getMaximumTimeCovered() const{\n assert(!_imp->keyFrames.empty());\n return (*_imp->keyFrames.rbegin())->getTime();\n}\n\nvoid Curve::addKeyFrame(boost::shared_ptr<KeyFrame> cp)\n{\n std::pair<KeyFrameSet::iterator,bool> newKey = _imp->keyFrames.insert(cp);\n if (newKey.second) {\n refreshTangents(KEYFRAME_CHANGED, newKey.first);\n }else{\n (*newKey.first)->setValue(cp->getValue());\n }\n}\n\nvoid Curve::removeKeyFrame(boost::shared_ptr<KeyFrame> cp) {\n KeyFrameSet::iterator it = std::find(_imp->keyFrames.begin(),_imp->keyFrames.end(),cp);\n KeyFrameSet::iterator prev = it;\n boost::shared_ptr<KeyFrame> prevCp;\n boost::shared_ptr<KeyFrame> nextCp;\n if(it != _imp->keyFrames.begin()){\n --prev;\n prevCp = (*prev);\n }\n KeyFrameSet::iterator next = it;\n ++next;\n if(next != _imp->keyFrames.end()){\n nextCp = (*next);\n }\n _imp->keyFrames.erase(it);\n if(prevCp){\n refreshTangents(TANGENT_CHANGED,prevCp);\n }\n if(nextCp){\n refreshTangents(TANGENT_CHANGED,nextCp);\n }\n\n}\n\nvoid Curve::removeKeyFrame(double time) {\n KeyFrameSet::iterator it = std::find_if(_imp->keyFrames.begin(), _imp->keyFrames.end(), KeyFrameTimePredicate(time));\n if (it != _imp->keyFrames.end()) {\n removeKeyFrame(*it);\n }\n}\n\n\n\n\nVariant Curve::getValueAt(double t) const {\n assert(!_imp->keyFrames.empty());\n if (_imp->keyFrames.size() == 1) {\n \/\/if there's only 1 keyframe, don't bother interpolating\n return (*_imp->keyFrames.begin())->getValue();\n }\n double tcur,tnext;\n double vcurDerivRight ,vnextDerivLeft ,vcur ,vnext ;\n Natron::KeyframeType interp ,interpNext;\n KeyFrameSet::const_iterator upper = _imp->keyFrames.end();\n for(KeyFrameSet::const_iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){\n if((*it)->getTime() > t){\n upper = it;\n break;\n }else if((*it)->getTime() == t){\n \/\/if the time is exactly the time of a keyframe, return its value\n return (*it)->getValue();\n }\n }\n\n\n \/\/if all keys have a greater time (i.e: we search after the last keyframe)\n KeyFrameSet::const_iterator prev = upper;\n --prev;\n\n\n \/\/if we found no key that has a greater time (i.e: we search before the 1st keyframe)\n if (upper == _imp->keyFrames.begin()) {\n tnext = (*upper)->getTime();\n vnext = (*upper)->getValue().value<double>();\n vnextDerivLeft = (*upper)->getLeftTangent().value<double>();\n interpNext = (*upper)->getInterpolation();\n tcur = tnext - 1.;\n vcur = vnext;\n vcurDerivRight = 0.;\n interp = Natron::KEYFRAME_NONE;\n\n } else if (upper == _imp->keyFrames.end()) {\n tcur = (*prev)->getTime();\n vcur = (*prev)->getValue().value<double>();\n vcurDerivRight = (*prev)->getRightTangent().value<double>();\n interp = (*prev)->getInterpolation();\n tnext = tcur + 1.;\n vnext = vcur;\n vnextDerivLeft = 0.;\n interpNext = Natron::KEYFRAME_NONE;\n } else {\n tcur = (*prev)->getTime();\n vcur = (*prev)->getValue().value<double>();\n vcurDerivRight = (*prev)->getRightTangent().value<double>();\n interp = (*prev)->getInterpolation();\n tnext = (*upper)->getTime();\n vnext = (*upper)->getValue().value<double>();\n vnextDerivLeft = (*upper)->getLeftTangent().value<double>();\n interpNext = (*upper)->getInterpolation();\n }\n\n double v = Natron::interpolate<double>(tcur,vcur,\n vcurDerivRight,\n vnextDerivLeft,\n tnext,vnext,\n t,\n interp,\n interpNext);\n\n \n const Variant& firstKeyValue = (*_imp->keyFrames.begin())->getValue();\n switch(firstKeyValue.type()){\n case QVariant::Int :\n return Variant((int)std::floor(v+0.5));\n case QVariant::Double :\n return Variant(v);\n case QVariant::Bool:\n return Variant((bool)std::floor(v+0.5));\n default:\n std::string exc(\"The type requested ( \");\n exc.append(firstKeyValue.typeName());\n exc.append(\") is not interpolable, it cannot animate!\");\n throw std::invalid_argument(exc);\n }\n\n\n\n}\n\n\nbool Curve::isAnimated() const { return _imp->keyFrames.size() > 1; }\n\nint Curve::keyFramesCount() const { return (int)_imp->keyFrames.size(); }\n\nconst KeyFrameSet& Curve::getKeyFrames() const { return _imp->keyFrames; }\n\nvoid Curve::setKeyFrameValue(const Variant& value,boost::shared_ptr<KeyFrame> k){\n if(value.toDouble() != k->getValue().toDouble()){\n k->setValue(value);\n evaluateCurveChanged(KEYFRAME_CHANGED,k);\n }\n\n}\n\nvoid Curve::setKeyFrameTime(double time,boost::shared_ptr<KeyFrame> k){\n if(time != k->getTime()){\n k->setTime(time);\n evaluateCurveChanged(KEYFRAME_CHANGED,k);\n }\n}\n\n\nvoid Curve::setKeyFrameValueAndTime(double time,const Variant& value,boost::shared_ptr<KeyFrame> k){\n if(time != k->getTime() || value.toDouble() != k->getValue().toDouble()){\n k->setTime(time);\n k->setValue(value);\n evaluateCurveChanged(KEYFRAME_CHANGED,k);\n }\n\n}\n\nvoid Curve::setKeyFrameLeftTangent(const Variant& value,boost::shared_ptr<KeyFrame> k){\n if(value.toDouble() != k->getRightTangent().toDouble()){\n k->setLeftTangent(value);\n evaluateCurveChanged(TANGENT_CHANGED,k);\n }\n \n}\n\nvoid Curve::setKeyFrameRightTangent(const Variant& value,boost::shared_ptr<KeyFrame> k){\n if(k->getLeftTangent().toDouble() != value.toDouble()){\n k->setRightTangent(value);\n evaluateCurveChanged(TANGENT_CHANGED,k);\n }\n}\n\nvoid Curve::setKeyFrameTangents(const Variant& left,const Variant& right,boost::shared_ptr<KeyFrame> k){\n if(k->getLeftTangent().toDouble() != left.toDouble() || right.toDouble() != k->getRightTangent().toDouble()){\n k->setLeftTangent(left);\n k->setRightTangent(right);\n evaluateCurveChanged(TANGENT_CHANGED,k);\n }\n \n}\n\n\nvoid Curve::setKeyFrameInterpolation(Natron::KeyframeType interp,boost::shared_ptr<KeyFrame> k){\n if(k->getInterpolation() != interp){\n k->setInterpolation(interp);\n evaluateCurveChanged(KEYFRAME_CHANGED,k);\n }\n}\n\n\n\nvoid Curve::refreshTangents(Curve::CurveChangedReason reason, KeyFrameSet::iterator key){\n double tcur = (*key)->getTime();\n double vcur = (*key)->getValue().value<double>();\n \n double tprev, vprev, tnext, vnext, vprevDerivRight, vnextDerivLeft;\n Natron::KeyframeType prevType, nextType;\n if (key == _imp->keyFrames.begin()) {\n tprev = tcur;\n vprev = vcur;\n vprevDerivRight = 0.;\n prevType = Natron::KEYFRAME_NONE;\n } else {\n KeyFrameSet::const_iterator prev = key;\n --prev;\n tprev = (*prev)->getTime();\n vprev = (*prev)->getValue().value<double>();\n vprevDerivRight = (*prev)->getRightTangent().value<double>();\n prevType = (*prev)->getInterpolation();\n \n \/\/if prev is the first keyframe, and not edited by the user then interpolate linearly\n if(prev == _imp->keyFrames.begin() && prevType != Natron::KEYFRAME_FREE &&\n prevType != Natron::KEYFRAME_BROKEN){\n prevType = Natron::KEYFRAME_LINEAR;\n }\n }\n \n KeyFrameSet::const_iterator next = key;\n ++next;\n if (next == _imp->keyFrames.end()) {\n tnext = tcur;\n vnext = vcur;\n vnextDerivLeft = 0.;\n nextType = Natron::KEYFRAME_NONE;\n } else {\n tnext = (*next)->getTime();\n vnext = (*next)->getValue().value<double>();\n vnextDerivLeft = (*next)->getLeftTangent().value<double>();\n nextType = (*next)->getInterpolation();\n \n KeyFrameSet::const_iterator nextnext = next;\n ++nextnext;\n \/\/if next is thelast keyframe, and not edited by the user then interpolate linearly\n if(nextnext == _imp->keyFrames.end() && nextType != Natron::KEYFRAME_FREE &&\n nextType != Natron::KEYFRAME_BROKEN){\n nextType = Natron::KEYFRAME_LINEAR;\n }\n }\n \n double vcurDerivLeft,vcurDerivRight;\n try{\n Natron::autoComputeTangents<double>(prevType,\n (*key)->getInterpolation(),\n nextType,\n tprev, vprev,\n tcur, vcur,\n tnext, vnext,\n vprevDerivRight,\n vnextDerivLeft,\n &vcurDerivLeft, &vcurDerivRight);\n }catch(const std::exception& e){\n std::cout << e.what() << std::endl;\n assert(false);\n }\n (*key)->setLeftTangent(Variant(vcurDerivLeft));\n (*key)->setRightTangent(Variant(vcurDerivRight));\n if(reason != TANGENT_CHANGED){\n evaluateCurveChanged(TANGENT_CHANGED,*key);\n }\n\n}\n\nvoid Curve::refreshTangents(CurveChangedReason reason, boost::shared_ptr<KeyFrame> k){\n KeyFrameSet::iterator it = std::find(_imp->keyFrames.begin(),_imp->keyFrames.end(),k);\n assert(it!=_imp->keyFrames.end());\n refreshTangents(reason,it);\n}\n\nvoid Curve::evaluateCurveChanged(CurveChangedReason reason,boost::shared_ptr<KeyFrame> k){\n KeyFrameSet::iterator found = _imp->keyFrames.end();\n for(KeyFrameSet::iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){\n if((*it) == k){\n found = it;\n break;\n }\n }\n assert(found!=_imp->keyFrames.end());\n \n if(k->getInterpolation()!= Natron::KEYFRAME_BROKEN && k->getInterpolation() != Natron::KEYFRAME_FREE\n && reason != TANGENT_CHANGED ){\n refreshTangents(TANGENT_CHANGED,found);\n }\n KeyFrameSet::iterator prev = found;\n if(found != _imp->keyFrames.begin()){\n --prev;\n if((*prev)->getInterpolation()!= Natron::KEYFRAME_BROKEN &&\n (*prev)->getInterpolation()!= Natron::KEYFRAME_FREE){\n refreshTangents(TANGENT_CHANGED,prev);\n }\n }\n KeyFrameSet::iterator next = found;\n ++next;\n if(next != _imp->keyFrames.end()){\n if((*next)->getInterpolation()!= Natron::KEYFRAME_BROKEN &&\n (*next)->getInterpolation()!= Natron::KEYFRAME_FREE){\n refreshTangents(TANGENT_CHANGED,next);\n }\n }\n \n _imp->owner->evaluateAnimationChange();\n}\n<commit_msg>clone(): copy all values from keyframe<commit_after>\/\/ Natron\n\/\/\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012.\n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Curve.h\"\n\n#include <algorithm>\n\n#include \"Engine\/CurvePrivate.h\"\n#include \"Engine\/Interpolation.h\"\n\nnamespace {\n struct KeyFrameCloner {\n boost::shared_ptr<KeyFrame> operator()(const boost::shared_ptr<KeyFrame>& kf) const { return boost::shared_ptr<KeyFrame>(new KeyFrame(*kf)); }\n };\n\n class KeyFrameTimePredicate\n {\n public:\n KeyFrameTimePredicate(double t) : _t(t) {};\n\n bool operator()(const boost::shared_ptr<KeyFrame>& f) { return (f->getTime() == _t); }\n private:\n double _t;\n };\n}\n\n\/************************************KEYFRAME************************************\/\n\nKeyFrame::KeyFrame()\n : _imp(new KeyFramePrivate)\n{}\n\n\nKeyFrame::KeyFrame(double time, const Variant& initialValue)\n : _imp(new KeyFramePrivate(time,initialValue))\n{\n}\n\nKeyFrame::KeyFrame(const KeyFrame& other)\n : _imp(new KeyFramePrivate(*(other._imp)))\n{\n}\n\nvoid KeyFrame::operator=(const KeyFrame& o)\n{\n _imp->time = o._imp->time;\n _imp->value = o._imp->value;\n _imp->leftTangent = o._imp->leftTangent;\n _imp->rightTangent = o._imp->rightTangent;\n _imp->interpolation = o._imp->interpolation;\n}\n\nKeyFrame::~KeyFrame(){}\n\nbool KeyFrame::operator==(const KeyFrame& o) const {\n return _imp->value == o._imp->value &&\n _imp->time == o._imp->time;\n}\n\n\nvoid KeyFrame::setLeftTangent(const Variant& v){\n _imp->leftTangent = v;\n}\n\n\nvoid KeyFrame::setRightTangent(const Variant& v){\n _imp->rightTangent = v;\n}\n\n\nvoid KeyFrame::setValue(const Variant& v){\n _imp->value = v;\n}\n\nvoid KeyFrame::setTime(double time){\n _imp->time = time;\n}\n\n\nvoid KeyFrame::setInterpolation(Natron::KeyframeType interp) { _imp->interpolation = interp; }\n\nNatron::KeyframeType KeyFrame::getInterpolation() const { return _imp->interpolation; }\n\n\nconst Variant& KeyFrame::getValue() const { return _imp->value; }\n\ndouble KeyFrame::getTime() const { return _imp->time; }\n\nconst Variant& KeyFrame::getLeftTangent() const { return _imp->leftTangent; }\n\nconst Variant& KeyFrame::getRightTangent() const { return _imp->rightTangent; }\n\n\/************************************CURVEPATH************************************\/\n\nCurve::Curve()\n : _imp(new CurvePrivate)\n{\n\n}\n\nCurve::Curve(Knob *owner)\n : _imp(new CurvePrivate)\n{\n _imp->owner = owner;\n}\n\nCurve::~Curve(){ clearKeyFrames(); }\n\nvoid Curve::clearKeyFrames(){\n _imp->keyFrames.clear();\n}\n\n\n\nvoid Curve::clone(const Curve& other){\n clearKeyFrames();\n const KeyFrameSet& otherKeys = other.getKeyFrames();\n std::transform(otherKeys.begin(), otherKeys.end(), std::inserter(_imp->keyFrames, _imp->keyFrames.begin()), KeyFrameCloner());\n}\n\n\ndouble Curve::getMinimumTimeCovered() const{\n assert(!_imp->keyFrames.empty());\n return (*_imp->keyFrames.begin())->getTime();\n}\n\ndouble Curve::getMaximumTimeCovered() const{\n assert(!_imp->keyFrames.empty());\n return (*_imp->keyFrames.rbegin())->getTime();\n}\n\nvoid Curve::addKeyFrame(boost::shared_ptr<KeyFrame> cp)\n{\n std::pair<KeyFrameSet::iterator,bool> newKey = _imp->keyFrames.insert(cp);\n if (newKey.second) {\n refreshTangents(KEYFRAME_CHANGED, newKey.first);\n }else{\n (*newKey.first)->setValue(cp->getValue());\n }\n}\n\nvoid Curve::removeKeyFrame(boost::shared_ptr<KeyFrame> cp) {\n KeyFrameSet::iterator it = std::find(_imp->keyFrames.begin(),_imp->keyFrames.end(),cp);\n KeyFrameSet::iterator prev = it;\n boost::shared_ptr<KeyFrame> prevCp;\n boost::shared_ptr<KeyFrame> nextCp;\n if(it != _imp->keyFrames.begin()){\n --prev;\n prevCp = (*prev);\n }\n KeyFrameSet::iterator next = it;\n ++next;\n if(next != _imp->keyFrames.end()){\n nextCp = (*next);\n }\n _imp->keyFrames.erase(it);\n if(prevCp){\n refreshTangents(TANGENT_CHANGED,prevCp);\n }\n if(nextCp){\n refreshTangents(TANGENT_CHANGED,nextCp);\n }\n\n}\n\nvoid Curve::removeKeyFrame(double time) {\n KeyFrameSet::iterator it = std::find_if(_imp->keyFrames.begin(), _imp->keyFrames.end(), KeyFrameTimePredicate(time));\n if (it != _imp->keyFrames.end()) {\n removeKeyFrame(*it);\n }\n}\n\n\n\n\nVariant Curve::getValueAt(double t) const {\n assert(!_imp->keyFrames.empty());\n if (_imp->keyFrames.size() == 1) {\n \/\/if there's only 1 keyframe, don't bother interpolating\n return (*_imp->keyFrames.begin())->getValue();\n }\n double tcur,tnext;\n double vcurDerivRight ,vnextDerivLeft ,vcur ,vnext ;\n Natron::KeyframeType interp ,interpNext;\n KeyFrameSet::const_iterator upper = _imp->keyFrames.end();\n for(KeyFrameSet::const_iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){\n if((*it)->getTime() > t){\n upper = it;\n break;\n }else if((*it)->getTime() == t){\n \/\/if the time is exactly the time of a keyframe, return its value\n return (*it)->getValue();\n }\n }\n\n\n \/\/if all keys have a greater time (i.e: we search after the last keyframe)\n KeyFrameSet::const_iterator prev = upper;\n --prev;\n\n\n \/\/if we found no key that has a greater time (i.e: we search before the 1st keyframe)\n if (upper == _imp->keyFrames.begin()) {\n tnext = (*upper)->getTime();\n vnext = (*upper)->getValue().value<double>();\n vnextDerivLeft = (*upper)->getLeftTangent().value<double>();\n interpNext = (*upper)->getInterpolation();\n tcur = tnext - 1.;\n vcur = vnext;\n vcurDerivRight = 0.;\n interp = Natron::KEYFRAME_NONE;\n\n } else if (upper == _imp->keyFrames.end()) {\n tcur = (*prev)->getTime();\n vcur = (*prev)->getValue().value<double>();\n vcurDerivRight = (*prev)->getRightTangent().value<double>();\n interp = (*prev)->getInterpolation();\n tnext = tcur + 1.;\n vnext = vcur;\n vnextDerivLeft = 0.;\n interpNext = Natron::KEYFRAME_NONE;\n } else {\n tcur = (*prev)->getTime();\n vcur = (*prev)->getValue().value<double>();\n vcurDerivRight = (*prev)->getRightTangent().value<double>();\n interp = (*prev)->getInterpolation();\n tnext = (*upper)->getTime();\n vnext = (*upper)->getValue().value<double>();\n vnextDerivLeft = (*upper)->getLeftTangent().value<double>();\n interpNext = (*upper)->getInterpolation();\n }\n\n double v = Natron::interpolate<double>(tcur,vcur,\n vcurDerivRight,\n vnextDerivLeft,\n tnext,vnext,\n t,\n interp,\n interpNext);\n\n \n const Variant& firstKeyValue = (*_imp->keyFrames.begin())->getValue();\n switch(firstKeyValue.type()){\n case QVariant::Int :\n return Variant((int)std::floor(v+0.5));\n case QVariant::Double :\n return Variant(v);\n case QVariant::Bool:\n return Variant((bool)std::floor(v+0.5));\n default:\n std::string exc(\"The type requested ( \");\n exc.append(firstKeyValue.typeName());\n exc.append(\") is not interpolable, it cannot animate!\");\n throw std::invalid_argument(exc);\n }\n\n\n\n}\n\n\nbool Curve::isAnimated() const { return _imp->keyFrames.size() > 1; }\n\nint Curve::keyFramesCount() const { return (int)_imp->keyFrames.size(); }\n\nconst KeyFrameSet& Curve::getKeyFrames() const { return _imp->keyFrames; }\n\nvoid Curve::setKeyFrameValue(const Variant& value,boost::shared_ptr<KeyFrame> k){\n if(value.toDouble() != k->getValue().toDouble()){\n k->setValue(value);\n evaluateCurveChanged(KEYFRAME_CHANGED,k);\n }\n\n}\n\nvoid Curve::setKeyFrameTime(double time,boost::shared_ptr<KeyFrame> k){\n if(time != k->getTime()){\n k->setTime(time);\n evaluateCurveChanged(KEYFRAME_CHANGED,k);\n }\n}\n\n\nvoid Curve::setKeyFrameValueAndTime(double time,const Variant& value,boost::shared_ptr<KeyFrame> k){\n if(time != k->getTime() || value.toDouble() != k->getValue().toDouble()){\n k->setTime(time);\n k->setValue(value);\n evaluateCurveChanged(KEYFRAME_CHANGED,k);\n }\n\n}\n\nvoid Curve::setKeyFrameLeftTangent(const Variant& value,boost::shared_ptr<KeyFrame> k){\n if(value.toDouble() != k->getRightTangent().toDouble()){\n k->setLeftTangent(value);\n evaluateCurveChanged(TANGENT_CHANGED,k);\n }\n \n}\n\nvoid Curve::setKeyFrameRightTangent(const Variant& value,boost::shared_ptr<KeyFrame> k){\n if(k->getLeftTangent().toDouble() != value.toDouble()){\n k->setRightTangent(value);\n evaluateCurveChanged(TANGENT_CHANGED,k);\n }\n}\n\nvoid Curve::setKeyFrameTangents(const Variant& left,const Variant& right,boost::shared_ptr<KeyFrame> k){\n if(k->getLeftTangent().toDouble() != left.toDouble() || right.toDouble() != k->getRightTangent().toDouble()){\n k->setLeftTangent(left);\n k->setRightTangent(right);\n evaluateCurveChanged(TANGENT_CHANGED,k);\n }\n \n}\n\n\nvoid Curve::setKeyFrameInterpolation(Natron::KeyframeType interp,boost::shared_ptr<KeyFrame> k){\n if(k->getInterpolation() != interp){\n k->setInterpolation(interp);\n evaluateCurveChanged(KEYFRAME_CHANGED,k);\n }\n}\n\n\n\nvoid Curve::refreshTangents(Curve::CurveChangedReason reason, KeyFrameSet::iterator key){\n double tcur = (*key)->getTime();\n double vcur = (*key)->getValue().value<double>();\n \n double tprev, vprev, tnext, vnext, vprevDerivRight, vnextDerivLeft;\n Natron::KeyframeType prevType, nextType;\n if (key == _imp->keyFrames.begin()) {\n tprev = tcur;\n vprev = vcur;\n vprevDerivRight = 0.;\n prevType = Natron::KEYFRAME_NONE;\n } else {\n KeyFrameSet::const_iterator prev = key;\n --prev;\n tprev = (*prev)->getTime();\n vprev = (*prev)->getValue().value<double>();\n vprevDerivRight = (*prev)->getRightTangent().value<double>();\n prevType = (*prev)->getInterpolation();\n \n \/\/if prev is the first keyframe, and not edited by the user then interpolate linearly\n if(prev == _imp->keyFrames.begin() && prevType != Natron::KEYFRAME_FREE &&\n prevType != Natron::KEYFRAME_BROKEN){\n prevType = Natron::KEYFRAME_LINEAR;\n }\n }\n \n KeyFrameSet::const_iterator next = key;\n ++next;\n if (next == _imp->keyFrames.end()) {\n tnext = tcur;\n vnext = vcur;\n vnextDerivLeft = 0.;\n nextType = Natron::KEYFRAME_NONE;\n } else {\n tnext = (*next)->getTime();\n vnext = (*next)->getValue().value<double>();\n vnextDerivLeft = (*next)->getLeftTangent().value<double>();\n nextType = (*next)->getInterpolation();\n \n KeyFrameSet::const_iterator nextnext = next;\n ++nextnext;\n \/\/if next is thelast keyframe, and not edited by the user then interpolate linearly\n if(nextnext == _imp->keyFrames.end() && nextType != Natron::KEYFRAME_FREE &&\n nextType != Natron::KEYFRAME_BROKEN){\n nextType = Natron::KEYFRAME_LINEAR;\n }\n }\n \n double vcurDerivLeft,vcurDerivRight;\n try{\n Natron::autoComputeTangents<double>(prevType,\n (*key)->getInterpolation(),\n nextType,\n tprev, vprev,\n tcur, vcur,\n tnext, vnext,\n vprevDerivRight,\n vnextDerivLeft,\n &vcurDerivLeft, &vcurDerivRight);\n }catch(const std::exception& e){\n std::cout << e.what() << std::endl;\n assert(false);\n }\n (*key)->setLeftTangent(Variant(vcurDerivLeft));\n (*key)->setRightTangent(Variant(vcurDerivRight));\n if(reason != TANGENT_CHANGED){\n evaluateCurveChanged(TANGENT_CHANGED,*key);\n }\n\n}\n\nvoid Curve::refreshTangents(CurveChangedReason reason, boost::shared_ptr<KeyFrame> k){\n KeyFrameSet::iterator it = std::find(_imp->keyFrames.begin(),_imp->keyFrames.end(),k);\n assert(it!=_imp->keyFrames.end());\n refreshTangents(reason,it);\n}\n\nvoid Curve::evaluateCurveChanged(CurveChangedReason reason,boost::shared_ptr<KeyFrame> k){\n KeyFrameSet::iterator found = _imp->keyFrames.end();\n for(KeyFrameSet::iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){\n if((*it) == k){\n found = it;\n break;\n }\n }\n assert(found!=_imp->keyFrames.end());\n \n if(k->getInterpolation()!= Natron::KEYFRAME_BROKEN && k->getInterpolation() != Natron::KEYFRAME_FREE\n && reason != TANGENT_CHANGED ){\n refreshTangents(TANGENT_CHANGED,found);\n }\n KeyFrameSet::iterator prev = found;\n if(found != _imp->keyFrames.begin()){\n --prev;\n if((*prev)->getInterpolation()!= Natron::KEYFRAME_BROKEN &&\n (*prev)->getInterpolation()!= Natron::KEYFRAME_FREE){\n refreshTangents(TANGENT_CHANGED,prev);\n }\n }\n KeyFrameSet::iterator next = found;\n ++next;\n if(next != _imp->keyFrames.end()){\n if((*next)->getInterpolation()!= Natron::KEYFRAME_BROKEN &&\n (*next)->getInterpolation()!= Natron::KEYFRAME_FREE){\n refreshTangents(TANGENT_CHANGED,next);\n }\n }\n \n _imp->owner->evaluateAnimationChange();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==\/\/\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\/\/ This file defines a DeadStores, a flow-sensitive checker that looks for\n\/\/ stores to variables that are no longer live.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/LocalCheckers.h\"\n#include \"clang\/Analysis\/PathDiagnostic.h\"\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"clang\/AST\/ExprObjC.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/DeclObjC.h\"\n#include \"clang\/Basic\/LangOptions.h\"\n#include <sstream>\n\nusing namespace clang;\n\nstatic bool scan_dealloc(Stmt* S, Selector Dealloc) { \n \n if (ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(S))\n if (ME->getSelector() == Dealloc)\n if (Expr* Receiver = ME->getReceiver()->IgnoreParenCasts())\n if (PreDefinedExpr* E = dyn_cast<PreDefinedExpr>(Receiver))\n if (E->getIdentType() == PreDefinedExpr::ObjCSuper)\n return true;\n\n \/\/ Recurse to children.\n\n for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I)\n if (*I && scan_dealloc(*I, Dealloc))\n return true;\n \n return false;\n}\n\nvoid clang::CheckObjCDealloc(ObjCImplementationDecl* D,\n const LangOptions& LOpts, BugReporter& BR) {\n\n assert (LOpts.getGCMode() != LangOptions::GCOnly);\n \n ASTContext& Ctx = BR.getContext();\n ObjCInterfaceDecl* ID = D->getClassInterface();\n \n \/\/ Does the class contain any ivars that are pointers (or id<...>)?\n \/\/ If not, skip the check entirely.\n \/\/ NOTE: This is motivated by PR 2517:\n \/\/ http:\/\/llvm.org\/bugs\/show_bug.cgi?id=2517\n \n bool containsPointerIvar = false;\n \n for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end();\n I!=E; ++I) {\n \n QualType T = (*I)->getType();\n \n if (T->isPointerType() || T->isObjCQualifiedIdType()) {\n containsPointerIvar = true;\n break;\n }\n }\n \n if (!containsPointerIvar)\n return;\n \n \/\/ Determine if the class subclasses NSObject.\n IdentifierInfo* NSObjectII = &Ctx.Idents.get(\"NSObject\");\n \n for ( ; ID ; ID = ID->getSuperClass())\n if (ID->getIdentifier() == NSObjectII)\n break;\n \n if (!ID)\n return;\n \n \/\/ Get the \"dealloc\" selector.\n IdentifierInfo* II = &Ctx.Idents.get(\"dealloc\");\n Selector S = Ctx.Selectors.getSelector(0, &II);\n \n ObjCMethodDecl* MD = 0;\n \n \/\/ Scan the instance methods for \"dealloc\".\n for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),\n E = D->instmeth_end(); I!=E; ++I) {\n \n if ((*I)->getSelector() == S) {\n MD = *I;\n break;\n } \n }\n \n if (!MD) { \/\/ No dealloc found.\n \n \/\/ FIXME: This code should be reduced to three lines if possible (Refactor).\n SimpleBugType BT(LOpts.getGCMode() == LangOptions::NonGC \n ? \"missing -dealloc\" \n : \"missing -dealloc (Hybrid MM, non-GC)\");\n \n DiagCollector C(BT);\n \n std::ostringstream os;\n os << \"Objective-C class '\" << D->getName()\n << \"' lacks a 'dealloc' instance method\";\n \n Diagnostic& Diag = BR.getDiagnostic(); \n Diag.Report(&C,\n Ctx.getFullLoc(D->getLocStart()),\n Diag.getCustomDiagID(Diagnostic::Warning, os.str().c_str()),\n NULL, 0, NULL, 0);\n \n for (DiagCollector::iterator I = C.begin(), E = C.end(); I != E; ++I)\n BR.EmitWarning(*I);\n \n return;\n }\n \n \/\/ dealloc found. Scan for missing [super dealloc].\n if (MD->getBody() && !scan_dealloc(MD->getBody(), S)) {\n \n \/\/ FIXME: This code should be reduced to three lines if possible (Refactor).\n SimpleBugType BT(LOpts.getGCMode() == LangOptions::NonGC\n ? \"missing [super dealloc]\"\n : \"missing [super dealloc] (Hybrid MM, non-GC)\");\n \n DiagCollector C(BT);\n \n std::ostringstream os;\n os << \"The 'dealloc' instance method in Objective-C class '\" << D->getName()\n << \"' does not send a 'dealloc' message to its super class\"\n \" (missing [super dealloc])\";\n \n Diagnostic& Diag = BR.getDiagnostic(); \n Diag.Report(&C,\n Ctx.getFullLoc(MD->getLocStart()),\n Diag.getCustomDiagID(Diagnostic::Warning, os.str().c_str()),\n NULL, 0, NULL, 0);\n \n for (DiagCollector::iterator I = C.begin(), E = C.end(); I != E; ++I)\n BR.EmitWarning(*I);\n } \n}\n\n<commit_msg>Fix comment.<commit_after>\/\/==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==\/\/\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\/\/ This file defines a CheckObjCDealloc, a checker that\n\/\/ analyzes an Objective-C class's implementation to determine if it\n\/\/ correctly implements -dealloc.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/LocalCheckers.h\"\n#include \"clang\/Analysis\/PathDiagnostic.h\"\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"clang\/AST\/ExprObjC.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/DeclObjC.h\"\n#include \"clang\/Basic\/LangOptions.h\"\n#include <sstream>\n\nusing namespace clang;\n\nstatic bool scan_dealloc(Stmt* S, Selector Dealloc) { \n \n if (ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(S))\n if (ME->getSelector() == Dealloc)\n if (Expr* Receiver = ME->getReceiver()->IgnoreParenCasts())\n if (PreDefinedExpr* E = dyn_cast<PreDefinedExpr>(Receiver))\n if (E->getIdentType() == PreDefinedExpr::ObjCSuper)\n return true;\n\n \/\/ Recurse to children.\n\n for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I)\n if (*I && scan_dealloc(*I, Dealloc))\n return true;\n \n return false;\n}\n\nvoid clang::CheckObjCDealloc(ObjCImplementationDecl* D,\n const LangOptions& LOpts, BugReporter& BR) {\n\n assert (LOpts.getGCMode() != LangOptions::GCOnly);\n \n ASTContext& Ctx = BR.getContext();\n ObjCInterfaceDecl* ID = D->getClassInterface();\n \n \/\/ Does the class contain any ivars that are pointers (or id<...>)?\n \/\/ If not, skip the check entirely.\n \/\/ NOTE: This is motivated by PR 2517:\n \/\/ http:\/\/llvm.org\/bugs\/show_bug.cgi?id=2517\n \n bool containsPointerIvar = false;\n \n for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end();\n I!=E; ++I) {\n \n QualType T = (*I)->getType();\n \n if (T->isPointerType() || T->isObjCQualifiedIdType()) {\n containsPointerIvar = true;\n break;\n }\n }\n \n if (!containsPointerIvar)\n return;\n \n \/\/ Determine if the class subclasses NSObject.\n IdentifierInfo* NSObjectII = &Ctx.Idents.get(\"NSObject\");\n \n for ( ; ID ; ID = ID->getSuperClass())\n if (ID->getIdentifier() == NSObjectII)\n break;\n \n if (!ID)\n return;\n \n \/\/ Get the \"dealloc\" selector.\n IdentifierInfo* II = &Ctx.Idents.get(\"dealloc\");\n Selector S = Ctx.Selectors.getSelector(0, &II);\n \n ObjCMethodDecl* MD = 0;\n \n \/\/ Scan the instance methods for \"dealloc\".\n for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),\n E = D->instmeth_end(); I!=E; ++I) {\n \n if ((*I)->getSelector() == S) {\n MD = *I;\n break;\n } \n }\n \n if (!MD) { \/\/ No dealloc found.\n \n \/\/ FIXME: This code should be reduced to three lines if possible (Refactor).\n SimpleBugType BT(LOpts.getGCMode() == LangOptions::NonGC \n ? \"missing -dealloc\" \n : \"missing -dealloc (Hybrid MM, non-GC)\");\n \n DiagCollector C(BT);\n \n std::ostringstream os;\n os << \"Objective-C class '\" << D->getName()\n << \"' lacks a 'dealloc' instance method\";\n \n Diagnostic& Diag = BR.getDiagnostic(); \n Diag.Report(&C,\n Ctx.getFullLoc(D->getLocStart()),\n Diag.getCustomDiagID(Diagnostic::Warning, os.str().c_str()),\n NULL, 0, NULL, 0);\n \n for (DiagCollector::iterator I = C.begin(), E = C.end(); I != E; ++I)\n BR.EmitWarning(*I);\n \n return;\n }\n \n \/\/ dealloc found. Scan for missing [super dealloc].\n if (MD->getBody() && !scan_dealloc(MD->getBody(), S)) {\n \n \/\/ FIXME: This code should be reduced to three lines if possible (Refactor).\n SimpleBugType BT(LOpts.getGCMode() == LangOptions::NonGC\n ? \"missing [super dealloc]\"\n : \"missing [super dealloc] (Hybrid MM, non-GC)\");\n \n DiagCollector C(BT);\n \n std::ostringstream os;\n os << \"The 'dealloc' instance method in Objective-C class '\" << D->getName()\n << \"' does not send a 'dealloc' message to its super class\"\n \" (missing [super dealloc])\";\n \n Diagnostic& Diag = BR.getDiagnostic(); \n Diag.Report(&C,\n Ctx.getFullLoc(MD->getLocStart()),\n Diag.getCustomDiagID(Diagnostic::Warning, os.str().c_str()),\n NULL, 0, NULL, 0);\n \n for (DiagCollector::iterator I = C.begin(), E = C.end(); I != E; ++I)\n BR.EmitWarning(*I);\n } \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==\/\/\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\/\/ This file defines a CheckObjCDealloc, a checker that\n\/\/ analyzes an Objective-C class's implementation to determine if it\n\/\/ correctly implements -dealloc.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/LocalCheckers.h\"\n#include \"clang\/Analysis\/PathDiagnostic.h\"\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"clang\/AST\/ExprObjC.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/DeclObjC.h\"\n#include \"clang\/Basic\/LangOptions.h\"\n#include <sstream>\n\nusing namespace clang;\n\nstatic bool scan_dealloc(Stmt* S, Selector Dealloc) { \n \n if (ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(S))\n if (ME->getSelector() == Dealloc)\n if (Expr* Receiver = ME->getReceiver()->IgnoreParenCasts())\n if (PreDefinedExpr* E = dyn_cast<PreDefinedExpr>(Receiver))\n if (E->getIdentType() == PreDefinedExpr::ObjCSuper)\n return true;\n\n \/\/ Recurse to children.\n\n for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I)\n if (*I && scan_dealloc(*I, Dealloc))\n return true;\n \n return false;\n}\n\nstatic bool isSEL(QualType T, IdentifierInfo* SelII) {\n if (const TypedefType* Ty = T->getAsTypedefType())\n return Ty->getDecl()->getIdentifier() == SelII;\n \n return false;\n}\n\nvoid clang::CheckObjCDealloc(ObjCImplementationDecl* D,\n const LangOptions& LOpts, BugReporter& BR) {\n\n assert (LOpts.getGCMode() != LangOptions::GCOnly);\n \n ASTContext& Ctx = BR.getContext();\n ObjCInterfaceDecl* ID = D->getClassInterface();\n \n \/\/ Does the class contain any ivars that are pointers (or id<...>)?\n \/\/ If not, skip the check entirely.\n \/\/ NOTE: This is motivated by PR 2517:\n \/\/ http:\/\/llvm.org\/bugs\/show_bug.cgi?id=2517\n \n bool containsPointerIvar = false;\n IdentifierInfo* SelII = &Ctx.Idents.get(\"SEL\");\n \n for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end();\n I!=E; ++I) {\n \n ObjCIvarDecl* ID = *I;\n QualType T = ID->getType();\n \n if ((T->isPointerType() || Ctx.isObjCObjectPointerType(T)) &&\n (ID->getAttr<IBOutletAttr>() == 0 && \/\/ Skip IBOutlets.\n !isSEL(T, SelII))) { \/\/ Skip SEL ivars.\n containsPointerIvar = true;\n break;\n }\n }\n \n if (!containsPointerIvar)\n return;\n \n \/\/ Determine if the class subclasses NSObject.\n IdentifierInfo* NSObjectII = &Ctx.Idents.get(\"NSObject\");\n \n for ( ; ID ; ID = ID->getSuperClass())\n if (ID->getIdentifier() == NSObjectII)\n break;\n \n if (!ID)\n return;\n \n \/\/ Get the \"dealloc\" selector.\n IdentifierInfo* II = &Ctx.Idents.get(\"dealloc\");\n Selector S = Ctx.Selectors.getSelector(0, &II); \n ObjCMethodDecl* MD = 0;\n \n \/\/ Scan the instance methods for \"dealloc\".\n for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),\n E = D->instmeth_end(); I!=E; ++I) {\n \n if ((*I)->getSelector() == S) {\n MD = *I;\n break;\n } \n }\n \n if (!MD) { \/\/ No dealloc found.\n \n const char* name = LOpts.getGCMode() == LangOptions::NonGC \n ? \"missing -dealloc\" \n : \"missing -dealloc (Hybrid MM, non-GC)\";\n \n std::ostringstream os;\n os << \"Objective-C class '\" << D->getName()\n << \"' lacks a 'dealloc' instance method\";\n \n BR.EmitBasicReport(name, os.str().c_str(), D->getLocStart());\n return;\n }\n \n \/\/ dealloc found. Scan for missing [super dealloc].\n if (MD->getBody() && !scan_dealloc(MD->getBody(), S)) {\n \n const char* name = LOpts.getGCMode() == LangOptions::NonGC\n ? \"missing [super dealloc]\"\n : \"missing [super dealloc] (Hybrid MM, non-GC)\";\n \n std::ostringstream os;\n os << \"The 'dealloc' instance method in Objective-C class '\" << D->getName()\n << \"' does not send a 'dealloc' message to its super class\"\n \" (missing [super dealloc])\";\n \n BR.EmitBasicReport(name, os.str().c_str(), D->getLocStart());\n return;\n } \n}\n\n<commit_msg>Only warn about missing\/incomplete -dealloc implementations when a class contains a non-SEL, non-IBOutlet ivar that references an ObjC object.<commit_after>\/\/==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==\/\/\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\/\/ This file defines a CheckObjCDealloc, a checker that\n\/\/ analyzes an Objective-C class's implementation to determine if it\n\/\/ correctly implements -dealloc.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/LocalCheckers.h\"\n#include \"clang\/Analysis\/PathDiagnostic.h\"\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"clang\/AST\/ExprObjC.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/DeclObjC.h\"\n#include \"clang\/Basic\/LangOptions.h\"\n#include <sstream>\n\nusing namespace clang;\n\nstatic bool scan_dealloc(Stmt* S, Selector Dealloc) { \n \n if (ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(S))\n if (ME->getSelector() == Dealloc)\n if (Expr* Receiver = ME->getReceiver()->IgnoreParenCasts())\n if (PreDefinedExpr* E = dyn_cast<PreDefinedExpr>(Receiver))\n if (E->getIdentType() == PreDefinedExpr::ObjCSuper)\n return true;\n\n \/\/ Recurse to children.\n\n for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I)\n if (*I && scan_dealloc(*I, Dealloc))\n return true;\n \n return false;\n}\n\nstatic bool isSEL(QualType T, IdentifierInfo* SelII) {\n if (const TypedefType* Ty = T->getAsTypedefType())\n return Ty->getDecl()->getIdentifier() == SelII;\n \n return false;\n}\n\nvoid clang::CheckObjCDealloc(ObjCImplementationDecl* D,\n const LangOptions& LOpts, BugReporter& BR) {\n\n assert (LOpts.getGCMode() != LangOptions::GCOnly);\n \n ASTContext& Ctx = BR.getContext();\n ObjCInterfaceDecl* ID = D->getClassInterface();\n \n \/\/ Does the class contain any ivars that are pointers (or id<...>)?\n \/\/ If not, skip the check entirely.\n \/\/ NOTE: This is motivated by PR 2517:\n \/\/ http:\/\/llvm.org\/bugs\/show_bug.cgi?id=2517\n \n bool containsPointerIvar = false;\n IdentifierInfo* SelII = &Ctx.Idents.get(\"SEL\");\n \n for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end();\n I!=E; ++I) {\n \n ObjCIvarDecl* ID = *I;\n QualType T = ID->getType();\n \n if (!Ctx.isObjCObjectPointerType(T) ||\n ID->getAttr<IBOutletAttr>() || \/\/ Skip IBOutlets.\n isSEL(T, SelII)) \/\/ Skip SEL ivars.\n continue;\n \n containsPointerIvar = true;\n break;\n }\n \n if (!containsPointerIvar)\n return;\n \n \/\/ Determine if the class subclasses NSObject.\n IdentifierInfo* NSObjectII = &Ctx.Idents.get(\"NSObject\");\n \n for ( ; ID ; ID = ID->getSuperClass())\n if (ID->getIdentifier() == NSObjectII)\n break;\n \n if (!ID)\n return;\n \n \/\/ Get the \"dealloc\" selector.\n IdentifierInfo* II = &Ctx.Idents.get(\"dealloc\");\n Selector S = Ctx.Selectors.getSelector(0, &II); \n ObjCMethodDecl* MD = 0;\n \n \/\/ Scan the instance methods for \"dealloc\".\n for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),\n E = D->instmeth_end(); I!=E; ++I) {\n \n if ((*I)->getSelector() == S) {\n MD = *I;\n break;\n } \n }\n \n if (!MD) { \/\/ No dealloc found.\n \n const char* name = LOpts.getGCMode() == LangOptions::NonGC \n ? \"missing -dealloc\" \n : \"missing -dealloc (Hybrid MM, non-GC)\";\n \n std::ostringstream os;\n os << \"Objective-C class '\" << D->getName()\n << \"' lacks a 'dealloc' instance method\";\n \n BR.EmitBasicReport(name, os.str().c_str(), D->getLocStart());\n return;\n }\n \n \/\/ dealloc found. Scan for missing [super dealloc].\n if (MD->getBody() && !scan_dealloc(MD->getBody(), S)) {\n \n const char* name = LOpts.getGCMode() == LangOptions::NonGC\n ? \"missing [super dealloc]\"\n : \"missing [super dealloc] (Hybrid MM, non-GC)\";\n \n std::ostringstream os;\n os << \"The 'dealloc' instance method in Objective-C class '\" << D->getName()\n << \"' does not send a 'dealloc' message to its super class\"\n \" (missing [super dealloc])\";\n \n BR.EmitBasicReport(name, os.str().c_str(), D->getLocStart());\n return;\n } \n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"amuse\/AudioGroupSampleDirectory.hpp\"\n#include \"amuse\/Common.hpp\"\n#include <string.h>\n\nnamespace amuse\n{\n\nvoid AudioGroupSampleDirectory::Entry::swapBig()\n{\n m_sfxId = SBig(m_sfxId);\n m_sampleOff = SBig(m_sampleOff);\n m_unk = SBig(m_unk);\n m_sampleRate = SBig(m_sampleRate);\n m_numSamples = SBig(m_numSamples);\n m_loopStartSample = SBig(m_loopStartSample);\n m_loopLengthSamples = SBig(m_loopLengthSamples);\n m_adpcmParmOffset = SBig(m_adpcmParmOffset);\n}\n\nvoid AudioGroupSampleDirectory::ADPCMParms::swapBigDSP()\n{\n dsp.m_bytesPerFrame = SBig(dsp.m_bytesPerFrame);\n dsp.m_hist2 = SBig(dsp.m_hist2);\n dsp.m_hist1 = SBig(dsp.m_hist1);\n for (int i=0 ; i<8 ; ++i)\n {\n dsp.m_coefs[i][0] = SBig(dsp.m_coefs[i][0]);\n dsp.m_coefs[i][1] = SBig(dsp.m_coefs[i][1]);\n }\n}\n\nvoid AudioGroupSampleDirectory::ADPCMParms::swapBigVADPCM()\n{\n int16_t* allCoefs = reinterpret_cast<int16_t*>(vadpcm.m_coefs[0][0]);\n for (int i=0 ; i<128 ; ++i)\n allCoefs[i] = SBig(allCoefs[i]);\n}\n\nAudioGroupSampleDirectory::AudioGroupSampleDirectory(const unsigned char* data, GCNDataTag)\n{\n const unsigned char* cur = data;\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n const AudioGroupSampleDirectory::Entry* ent =\n reinterpret_cast<const AudioGroupSampleDirectory::Entry*>(cur);\n\n std::pair<Entry, ADPCMParms>& store = m_entries[SBig(ent->m_sfxId)];\n store.first = *ent;\n store.first.swapBig();\n\n if (store.first.m_adpcmParmOffset)\n {\n const AudioGroupSampleDirectory::ADPCMParms* adpcm =\n reinterpret_cast<const AudioGroupSampleDirectory::ADPCMParms*>(data +\n store.first.m_adpcmParmOffset);\n store.second = *adpcm;\n store.second.swapBigDSP();\n }\n\n cur += 32;\n }\n}\n\nstruct MusyX1SdirEntry\n{\n uint16_t m_sfxId;\n uint32_t m_sampleOff;\n uint32_t m_pitchSampleRate;\n uint32_t m_numSamples;\n uint32_t m_loopStartSample;\n uint32_t m_loopLengthSamples;\n\n void swapBig()\n {\n m_sfxId = SBig(m_sfxId);\n m_sampleOff = SBig(m_sampleOff);\n m_pitchSampleRate = SBig(m_pitchSampleRate);\n m_numSamples = SBig(m_numSamples);\n m_loopStartSample = SBig(m_loopStartSample);\n m_loopLengthSamples = SBig(m_loopLengthSamples);\n }\n\n void setIntoMusyX2(AudioGroupSampleDirectory::Entry& ent) const\n {\n ent.m_sfxId = m_sfxId;\n ent.m_sampleOff = m_sampleOff;\n ent.m_unk = 0;\n ent.m_pitch = m_pitchSampleRate >> 24;\n ent.m_sampleRate = m_pitchSampleRate & 0xffff;\n ent.m_numSamples = m_numSamples;\n ent.m_loopStartSample = m_loopStartSample;\n ent.m_loopLengthSamples = m_loopLengthSamples;\n ent.m_adpcmParmOffset = 0;\n }\n};\n\nstruct MusyX1AbsSdirEntry\n{\n uint16_t m_sfxId;\n uint32_t m_sampleOff;\n uint32_t m_unk;\n uint32_t m_pitchSampleRate;\n uint32_t m_numSamples;\n uint32_t m_loopStartSample;\n uint32_t m_loopLengthSamples;\n\n void swapBig()\n {\n m_sfxId = SBig(m_sfxId);\n m_sampleOff = SBig(m_sampleOff);\n m_unk = SBig(m_unk);\n m_pitchSampleRate = SBig(m_pitchSampleRate);\n m_numSamples = SBig(m_numSamples);\n m_loopStartSample = SBig(m_loopStartSample);\n m_loopLengthSamples = SBig(m_loopLengthSamples);\n }\n\n void setIntoMusyX2(AudioGroupSampleDirectory::Entry& ent) const\n {\n ent.m_sfxId = m_sfxId;\n ent.m_sampleOff = m_sampleOff;\n ent.m_unk = m_unk;\n ent.m_pitch = m_pitchSampleRate >> 24;\n ent.m_sampleRate = m_pitchSampleRate & 0xffff;\n ent.m_numSamples = m_numSamples;\n ent.m_loopStartSample = m_loopStartSample;\n ent.m_loopLengthSamples = m_loopLengthSamples;\n ent.m_adpcmParmOffset = 0;\n }\n};\n\nAudioGroupSampleDirectory::AudioGroupSampleDirectory(const unsigned char* data,\n const unsigned char* sampData,\n bool absOffs, N64DataTag)\n{\n const unsigned char* cur = data;\n\n if (absOffs)\n {\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n MusyX1AbsSdirEntry ent = *reinterpret_cast<const MusyX1AbsSdirEntry*>(cur);\n ent.swapBig();\n\n std::pair<Entry, ADPCMParms>& store = m_entries[ent.m_sfxId];\n ent.setIntoMusyX2(store.first);\n\n memcpy(&store.second.vadpcm.m_coefs, sampData + ent.m_sampleOff, 256);\n store.second.swapBigVADPCM();\n\n cur += 28;\n }\n }\n else\n {\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n MusyX1SdirEntry ent = *reinterpret_cast<const MusyX1SdirEntry*>(cur);\n ent.swapBig();\n\n std::pair<Entry, ADPCMParms>& store = m_entries[ent.m_sfxId];\n ent.setIntoMusyX2(store.first);\n\n memcpy(&store.second.vadpcm.m_coefs, sampData + ent.m_sampleOff, 256);\n store.second.swapBigVADPCM();\n\n cur += 24;\n }\n }\n}\n\nAudioGroupSampleDirectory::AudioGroupSampleDirectory(const unsigned char* data,\n bool absOffs, PCDataTag)\n{\n const unsigned char* cur = data;\n\n if (absOffs)\n {\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n const MusyX1AbsSdirEntry* ent = reinterpret_cast<const MusyX1AbsSdirEntry*>(cur);\n\n std::pair<Entry, ADPCMParms>& store = m_entries[ent->m_sfxId];\n ent->setIntoMusyX2(store.first);\n\n cur += 28;\n }\n }\n else\n {\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n const MusyX1SdirEntry* ent = reinterpret_cast<const MusyX1SdirEntry*>(cur);\n\n std::pair<Entry, ADPCMParms>& store = m_entries[ent->m_sfxId];\n ent->setIntoMusyX2(store.first);\n\n cur += 24;\n }\n }\n}\n\n}\n<commit_msg>ADPCM parameter copy fix<commit_after>#include \"amuse\/AudioGroupSampleDirectory.hpp\"\n#include \"amuse\/Common.hpp\"\n#include <string.h>\n\nnamespace amuse\n{\n\nvoid AudioGroupSampleDirectory::Entry::swapBig()\n{\n m_sfxId = SBig(m_sfxId);\n m_sampleOff = SBig(m_sampleOff);\n m_unk = SBig(m_unk);\n m_sampleRate = SBig(m_sampleRate);\n m_numSamples = SBig(m_numSamples);\n m_loopStartSample = SBig(m_loopStartSample);\n m_loopLengthSamples = SBig(m_loopLengthSamples);\n m_adpcmParmOffset = SBig(m_adpcmParmOffset);\n}\n\nvoid AudioGroupSampleDirectory::ADPCMParms::swapBigDSP()\n{\n dsp.m_bytesPerFrame = SBig(dsp.m_bytesPerFrame);\n dsp.m_hist2 = SBig(dsp.m_hist2);\n dsp.m_hist1 = SBig(dsp.m_hist1);\n for (int i=0 ; i<8 ; ++i)\n {\n dsp.m_coefs[i][0] = SBig(dsp.m_coefs[i][0]);\n dsp.m_coefs[i][1] = SBig(dsp.m_coefs[i][1]);\n }\n}\n\nvoid AudioGroupSampleDirectory::ADPCMParms::swapBigVADPCM()\n{\n int16_t* allCoefs = reinterpret_cast<int16_t*>(vadpcm.m_coefs[0][0]);\n for (int i=0 ; i<128 ; ++i)\n allCoefs[i] = SBig(allCoefs[i]);\n}\n\nAudioGroupSampleDirectory::AudioGroupSampleDirectory(const unsigned char* data, GCNDataTag)\n{\n const unsigned char* cur = data;\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n const AudioGroupSampleDirectory::Entry* ent =\n reinterpret_cast<const AudioGroupSampleDirectory::Entry*>(cur);\n\n std::pair<Entry, ADPCMParms>& store = m_entries[SBig(ent->m_sfxId)];\n store.first = *ent;\n store.first.swapBig();\n\n if (store.first.m_adpcmParmOffset)\n {\n const AudioGroupSampleDirectory::ADPCMParms* adpcm =\n reinterpret_cast<const AudioGroupSampleDirectory::ADPCMParms*>(data +\n store.first.m_adpcmParmOffset);\n store.second.dsp = adpcm->dsp;\n store.second.swapBigDSP();\n }\n\n cur += 32;\n }\n}\n\nstruct MusyX1SdirEntry\n{\n uint16_t m_sfxId;\n uint32_t m_sampleOff;\n uint32_t m_pitchSampleRate;\n uint32_t m_numSamples;\n uint32_t m_loopStartSample;\n uint32_t m_loopLengthSamples;\n\n void swapBig()\n {\n m_sfxId = SBig(m_sfxId);\n m_sampleOff = SBig(m_sampleOff);\n m_pitchSampleRate = SBig(m_pitchSampleRate);\n m_numSamples = SBig(m_numSamples);\n m_loopStartSample = SBig(m_loopStartSample);\n m_loopLengthSamples = SBig(m_loopLengthSamples);\n }\n\n void setIntoMusyX2(AudioGroupSampleDirectory::Entry& ent) const\n {\n ent.m_sfxId = m_sfxId;\n ent.m_sampleOff = m_sampleOff;\n ent.m_unk = 0;\n ent.m_pitch = m_pitchSampleRate >> 24;\n ent.m_sampleRate = m_pitchSampleRate & 0xffff;\n ent.m_numSamples = m_numSamples;\n ent.m_loopStartSample = m_loopStartSample;\n ent.m_loopLengthSamples = m_loopLengthSamples;\n ent.m_adpcmParmOffset = 0;\n }\n};\n\nstruct MusyX1AbsSdirEntry\n{\n uint16_t m_sfxId;\n uint32_t m_sampleOff;\n uint32_t m_unk;\n uint32_t m_pitchSampleRate;\n uint32_t m_numSamples;\n uint32_t m_loopStartSample;\n uint32_t m_loopLengthSamples;\n\n void swapBig()\n {\n m_sfxId = SBig(m_sfxId);\n m_sampleOff = SBig(m_sampleOff);\n m_unk = SBig(m_unk);\n m_pitchSampleRate = SBig(m_pitchSampleRate);\n m_numSamples = SBig(m_numSamples);\n m_loopStartSample = SBig(m_loopStartSample);\n m_loopLengthSamples = SBig(m_loopLengthSamples);\n }\n\n void setIntoMusyX2(AudioGroupSampleDirectory::Entry& ent) const\n {\n ent.m_sfxId = m_sfxId;\n ent.m_sampleOff = m_sampleOff;\n ent.m_unk = m_unk;\n ent.m_pitch = m_pitchSampleRate >> 24;\n ent.m_sampleRate = m_pitchSampleRate & 0xffff;\n ent.m_numSamples = m_numSamples;\n ent.m_loopStartSample = m_loopStartSample;\n ent.m_loopLengthSamples = m_loopLengthSamples;\n ent.m_adpcmParmOffset = 0;\n }\n};\n\nAudioGroupSampleDirectory::AudioGroupSampleDirectory(const unsigned char* data,\n const unsigned char* sampData,\n bool absOffs, N64DataTag)\n{\n const unsigned char* cur = data;\n\n if (absOffs)\n {\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n MusyX1AbsSdirEntry ent = *reinterpret_cast<const MusyX1AbsSdirEntry*>(cur);\n ent.swapBig();\n\n std::pair<Entry, ADPCMParms>& store = m_entries[ent.m_sfxId];\n ent.setIntoMusyX2(store.first);\n\n memcpy(&store.second.vadpcm.m_coefs, sampData + ent.m_sampleOff, 256);\n store.second.swapBigVADPCM();\n\n cur += 28;\n }\n }\n else\n {\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n MusyX1SdirEntry ent = *reinterpret_cast<const MusyX1SdirEntry*>(cur);\n ent.swapBig();\n\n std::pair<Entry, ADPCMParms>& store = m_entries[ent.m_sfxId];\n ent.setIntoMusyX2(store.first);\n\n memcpy(&store.second.vadpcm.m_coefs, sampData + ent.m_sampleOff, 256);\n store.second.swapBigVADPCM();\n\n cur += 24;\n }\n }\n}\n\nAudioGroupSampleDirectory::AudioGroupSampleDirectory(const unsigned char* data,\n bool absOffs, PCDataTag)\n{\n const unsigned char* cur = data;\n\n if (absOffs)\n {\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n const MusyX1AbsSdirEntry* ent = reinterpret_cast<const MusyX1AbsSdirEntry*>(cur);\n\n std::pair<Entry, ADPCMParms>& store = m_entries[ent->m_sfxId];\n ent->setIntoMusyX2(store.first);\n\n cur += 28;\n }\n }\n else\n {\n while (*reinterpret_cast<const uint32_t*>(cur) != 0xffffffff)\n {\n const MusyX1SdirEntry* ent = reinterpret_cast<const MusyX1SdirEntry*>(cur);\n\n std::pair<Entry, ADPCMParms>& store = m_entries[ent->m_sfxId];\n ent->setIntoMusyX2(store.first);\n\n cur += 24;\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===\/\/\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\/\/ This file implements the LLVMTargetMachine class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/GCStrategy.h\"\n#include \"llvm\/CodeGen\/MachineFunctionAnalysis.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/Target\/TargetRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\nusing namespace llvm;\n\nnamespace llvm {\n bool EnableFastISel;\n}\n\nstatic cl::opt<bool> DisablePostRA(\"disable-post-ra\", cl::Hidden,\n cl::desc(\"Disable Post Regalloc\"));\nstatic cl::opt<bool> DisableBranchFold(\"disable-branch-fold\", cl::Hidden,\n cl::desc(\"Disable branch folding\"));\nstatic cl::opt<bool> DisableTailDuplicate(\"disable-tail-duplicate\", cl::Hidden,\n cl::desc(\"Disable tail duplication\"));\nstatic cl::opt<bool> DisableCodePlace(\"disable-code-place\", cl::Hidden,\n cl::desc(\"Disable code placement\"));\nstatic cl::opt<bool> DisableSSC(\"disable-ssc\", cl::Hidden,\n cl::desc(\"Disable Stack Slot Coloring\"));\nstatic cl::opt<bool> DisableMachineLICM(\"disable-machine-licm\", cl::Hidden,\n cl::desc(\"Disable Machine LICM\"));\nstatic cl::opt<bool> DisableMachineSink(\"disable-machine-sink\", cl::Hidden,\n cl::desc(\"Disable Machine Sinking\"));\nstatic cl::opt<bool> DisableLSR(\"disable-lsr\", cl::Hidden,\n cl::desc(\"Disable Loop Strength Reduction Pass\"));\nstatic cl::opt<bool> DisableCGP(\"disable-cgp\", cl::Hidden,\n cl::desc(\"Disable Codegen Prepare\"));\nstatic cl::opt<bool> PrintLSR(\"print-lsr-output\", cl::Hidden,\n cl::desc(\"Print LLVM IR produced by the loop-reduce pass\"));\nstatic cl::opt<bool> PrintISelInput(\"print-isel-input\", cl::Hidden,\n cl::desc(\"Print LLVM IR input to isel pass\"));\nstatic cl::opt<bool> PrintEmittedAsm(\"print-emitted-asm\", cl::Hidden,\n cl::desc(\"Dump emitter generated instructions as assembly\"));\nstatic cl::opt<bool> PrintGCInfo(\"print-gc\", cl::Hidden,\n cl::desc(\"Dump garbage collector data\"));\nstatic cl::opt<bool> VerifyMachineCode(\"verify-machineinstrs\", cl::Hidden,\n cl::desc(\"Verify generated machine code\"),\n cl::init(getenv(\"LLVM_VERIFY_MACHINEINSTRS\")!=NULL));\n\n\/\/ Enable or disable FastISel. Both options are needed, because\n\/\/ FastISel is enabled by default with -fast, and we wish to be\n\/\/ able to enable or disable fast-isel independently from -O0.\nstatic cl::opt<cl::boolOrDefault>\nEnableFastISelOption(\"fast-isel\", cl::Hidden,\n cl::desc(\"Enable the \\\"fast\\\" instruction selector\"));\n\n\/\/ Enable or disable an experimental optimization to split GEPs\n\/\/ and run a special GVN pass which does not examine loads, in\n\/\/ an effort to factor out redundancy implicit in complex GEPs.\nstatic cl::opt<bool> EnableSplitGEPGVN(\"split-gep-gvn\", cl::Hidden,\n cl::desc(\"Split GEPs and run no-load GVN\"));\n\nstatic cl::opt<bool> PreAllocTailDup(\"pre-regalloc-taildup\", cl::Hidden,\n cl::desc(\"Pre-register allocation tail duplication\"));\n\nLLVMTargetMachine::LLVMTargetMachine(const Target &T,\n const std::string &TargetTriple)\n : TargetMachine(T) {\n AsmInfo = T.createAsmInfo(TargetTriple);\n}\n\n\/\/ Set the default code model for the JIT for a generic target.\n\/\/ FIXME: Is small right here? or .is64Bit() ? Large : Small?\nvoid\nLLVMTargetMachine::setCodeModelForJIT() {\n setCodeModel(CodeModel::Small);\n}\n\n\/\/ Set the default code model for static compilation for a generic target.\nvoid\nLLVMTargetMachine::setCodeModelForStatic() {\n setCodeModel(CodeModel::Small);\n}\n\nFileModel::Model\nLLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,\n formatted_raw_ostream &Out,\n CodeGenFileType FileType,\n CodeGenOpt::Level OptLevel) {\n \/\/ Add common CodeGen passes.\n if (addCommonCodeGenPasses(PM, OptLevel))\n return FileModel::Error;\n\n switch (FileType) {\n default:\n break;\n case TargetMachine::AssemblyFile:\n if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))\n return FileModel::Error;\n return FileModel::AsmFile;\n case TargetMachine::ObjectFile:\n if (getMachOWriterInfo())\n return FileModel::MachOFile;\n else if (getELFWriterInfo())\n return FileModel::ElfFile;\n }\n\n return FileModel::Error;\n}\n\nbool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,\n CodeGenOpt::Level OptLevel,\n bool Verbose,\n formatted_raw_ostream &Out) {\n FunctionPass *Printer =\n getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);\n if (!Printer)\n return true;\n\n PM.add(Printer);\n return false;\n}\n\n\/\/\/ addPassesToEmitFileFinish - If the passes to emit the specified file had to\n\/\/\/ be split up (e.g., to add an object writer pass), this method can be used to\n\/\/\/ finish up adding passes to emit the file, if necessary.\nbool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,\n MachineCodeEmitter *MCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForStatic();\n \n if (MCE)\n addSimpleCodeEmitter(PM, OptLevel, *MCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitFileFinish - If the passes to emit the specified file had to\n\/\/\/ be split up (e.g., to add an object writer pass), this method can be used to\n\/\/\/ finish up adding passes to emit the file, if necessary.\nbool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,\n JITCodeEmitter *JCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForJIT();\n \n if (JCE)\n addSimpleCodeEmitter(PM, OptLevel, *JCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitFileFinish - If the passes to emit the specified file had to\n\/\/\/ be split up (e.g., to add an object writer pass), this method can be used to\n\/\/\/ finish up adding passes to emit the file, if necessary.\nbool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,\n ObjectCodeEmitter *OCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForStatic();\n \n if (OCE)\n addSimpleCodeEmitter(PM, OptLevel, *OCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitMachineCode - Add passes to the specified pass manager to\n\/\/\/ get machine code emitted. This uses a MachineCodeEmitter object to handle\n\/\/\/ actually outputting the machine code and resolving things like the address\n\/\/\/ of functions. This method should returns true if machine code emission is\n\/\/\/ not supported.\n\/\/\/\nbool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,\n MachineCodeEmitter &MCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForJIT();\n \n \/\/ Add common CodeGen passes.\n if (addCommonCodeGenPasses(PM, OptLevel))\n return true;\n\n addCodeEmitter(PM, OptLevel, MCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitMachineCode - Add passes to the specified pass manager to\n\/\/\/ get machine code emitted. This uses a MachineCodeEmitter object to handle\n\/\/\/ actually outputting the machine code and resolving things like the address\n\/\/\/ of functions. This method should returns true if machine code emission is\n\/\/\/ not supported.\n\/\/\/\nbool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,\n JITCodeEmitter &JCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForJIT();\n \n \/\/ Add common CodeGen passes.\n if (addCommonCodeGenPasses(PM, OptLevel))\n return true;\n\n addCodeEmitter(PM, OptLevel, JCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\nstatic void printAndVerify(PassManagerBase &PM,\n const char *Banner,\n bool allowDoubleDefs = false) {\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(errs(), Banner));\n\n if (VerifyMachineCode)\n PM.add(createMachineVerifierPass(allowDoubleDefs));\n}\n\n\/\/\/ addCommonCodeGenPasses - Add standard LLVM codegen passes used for both\n\/\/\/ emitting to assembly files or machine code output.\n\/\/\/\nbool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,\n CodeGenOpt::Level OptLevel) {\n \/\/ Standard LLVM-Level Passes.\n\n \/\/ Optionally, tun split-GEPs and no-load GVN.\n if (EnableSplitGEPGVN) {\n PM.add(createGEPSplitterPass());\n PM.add(createGVNPass(\/*NoPRE=*\/false, \/*NoLoads=*\/true));\n }\n\n \/\/ Run loop strength reduction before anything else.\n if (OptLevel != CodeGenOpt::None && !DisableLSR) {\n PM.add(createLoopStrengthReducePass(getTargetLowering()));\n if (PrintLSR)\n PM.add(createPrintFunctionPass(\"\\n\\n*** Code after LSR ***\\n\", &errs()));\n }\n\n \/\/ Turn exception handling constructs into something the code generators can\n \/\/ handle.\n switch (getMCAsmInfo()->getExceptionHandlingType())\n {\n case ExceptionHandling::SjLj:\n \/\/ SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both\n PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));\n PM.add(createSjLjEHPass(getTargetLowering()));\n break;\n case ExceptionHandling::Dwarf:\n PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));\n break;\n case ExceptionHandling::None:\n PM.add(createLowerInvokePass(getTargetLowering()));\n break;\n }\n\n PM.add(createGCLoweringPass());\n\n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n if (OptLevel != CodeGenOpt::None && !DisableCGP)\n PM.add(createCodeGenPreparePass(getTargetLowering()));\n\n PM.add(createStackProtectorPass(getTargetLowering()));\n\n if (PrintISelInput)\n PM.add(createPrintFunctionPass(\"\\n\\n\"\n \"*** Final LLVM Code input to ISel ***\\n\",\n &errs()));\n\n \/\/ Standard Lower-Level Passes.\n\n \/\/ Set up a MachineFunction for the rest of CodeGen to work on.\n PM.add(new MachineFunctionAnalysis(*this, OptLevel));\n\n \/\/ Enable FastISel with -fast, but allow that to be overridden.\n if (EnableFastISelOption == cl::BOU_TRUE ||\n (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))\n EnableFastISel = true;\n\n \/\/ Ask the target for an isel.\n if (addInstSelector(PM, OptLevel))\n return true;\n\n \/\/ Print the instruction selected machine code...\n printAndVerify(PM, \"After Instruction Selection\",\n \/* allowDoubleDefs= *\/ true);\n\n if (OptLevel != CodeGenOpt::None) {\n if (!DisableMachineLICM)\n PM.add(createMachineLICMPass());\n if (!DisableMachineSink)\n PM.add(createMachineSinkingPass());\n printAndVerify(PM, \"After MachineLICM and MachineSinking\",\n \/* allowDoubleDefs= *\/ true);\n }\n\n \/\/ Pre-ra tail duplication.\n if (OptLevel != CodeGenOpt::None &&\n !DisableTailDuplicate && PreAllocTailDup) {\n PM.add(createTailDuplicatePass(true));\n printAndVerify(PM, \"After Pre-RegAlloc TailDuplicate\");\n }\n\n \/\/ Run pre-ra passes.\n if (addPreRegAlloc(PM, OptLevel))\n printAndVerify(PM, \"After PreRegAlloc passes\",\n \/* allowDoubleDefs= *\/ true);\n\n \/\/ Perform register allocation.\n PM.add(createRegisterAllocator());\n printAndVerify(PM, \"After Register Allocation\");\n\n \/\/ Perform stack slot coloring.\n if (OptLevel != CodeGenOpt::None && !DisableSSC) {\n \/\/ FIXME: Re-enable coloring with register when it's capable of adding\n \/\/ kill markers.\n PM.add(createStackSlotColoringPass(false));\n printAndVerify(PM, \"After StackSlotColoring\");\n }\n\n \/\/ Run post-ra passes.\n if (addPostRegAlloc(PM, OptLevel))\n printAndVerify(PM, \"After PostRegAlloc passes\");\n\n PM.add(createLowerSubregsPass());\n printAndVerify(PM, \"After LowerSubregs\");\n\n \/\/ Insert prolog\/epilog code. Eliminate abstract frame index references...\n PM.add(createPrologEpilogCodeInserter());\n printAndVerify(PM, \"After PrologEpilogCodeInserter\");\n\n \/\/ Run pre-sched2 passes.\n if (addPreSched2(PM, OptLevel))\n printAndVerify(PM, \"After PreSched2 passes\");\n\n \/\/ Second pass scheduler.\n if (OptLevel != CodeGenOpt::None && !DisablePostRA) {\n PM.add(createPostRAScheduler(OptLevel));\n printAndVerify(PM, \"After PostRAScheduler\");\n }\n\n \/\/ Branch folding must be run after regalloc and prolog\/epilog insertion.\n if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {\n PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));\n printAndVerify(PM, \"After BranchFolding\");\n }\n\n \/\/ Tail duplication.\n if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {\n PM.add(createTailDuplicatePass(false));\n printAndVerify(PM, \"After TailDuplicate\");\n }\n\n PM.add(createGCMachineCodeAnalysisPass());\n\n if (PrintGCInfo)\n PM.add(createGCInfoPrinter(errs()));\n\n if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {\n PM.add(createCodePlacementOptPass());\n printAndVerify(PM, \"After CodePlacementOpt\");\n }\n\n if (addPreEmitPass(PM, OptLevel))\n printAndVerify(PM, \"After PreEmit passes\");\n\n return false;\n}\n<commit_msg><commit_after>\/\/===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===\/\/\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\/\/ This file implements the LLVMTargetMachine class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/GCStrategy.h\"\n#include \"llvm\/CodeGen\/MachineFunctionAnalysis.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/Target\/TargetRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\nusing namespace llvm;\n\nnamespace llvm {\n bool EnableFastISel;\n}\n\nstatic cl::opt<bool> DisablePostRA(\"disable-post-ra\", cl::Hidden,\n cl::desc(\"Disable Post Regalloc\"));\nstatic cl::opt<bool> DisableBranchFold(\"disable-branch-fold\", cl::Hidden,\n cl::desc(\"Disable branch folding\"));\nstatic cl::opt<bool> DisableTailDuplicate(\"disable-tail-duplicate\", cl::Hidden,\n cl::desc(\"Disable tail duplication\"));\nstatic cl::opt<bool> DisableCodePlace(\"disable-code-place\", cl::Hidden,\n cl::desc(\"Disable code placement\"));\nstatic cl::opt<bool> DisableSSC(\"disable-ssc\", cl::Hidden,\n cl::desc(\"Disable Stack Slot Coloring\"));\nstatic cl::opt<bool> DisableMachineLICM(\"disable-machine-licm\", cl::Hidden,\n cl::desc(\"Disable Machine LICM\"));\nstatic cl::opt<bool> DisableMachineSink(\"disable-machine-sink\", cl::Hidden,\n cl::desc(\"Disable Machine Sinking\"));\nstatic cl::opt<bool> DisableLSR(\"disable-lsr\", cl::Hidden,\n cl::desc(\"Disable Loop Strength Reduction Pass\"));\nstatic cl::opt<bool> DisableCGP(\"disable-cgp\", cl::Hidden,\n cl::desc(\"Disable Codegen Prepare\"));\nstatic cl::opt<bool> PrintLSR(\"print-lsr-output\", cl::Hidden,\n cl::desc(\"Print LLVM IR produced by the loop-reduce pass\"));\nstatic cl::opt<bool> PrintISelInput(\"print-isel-input\", cl::Hidden,\n cl::desc(\"Print LLVM IR input to isel pass\"));\nstatic cl::opt<bool> PrintEmittedAsm(\"print-emitted-asm\", cl::Hidden,\n cl::desc(\"Dump emitter generated instructions as assembly\"));\nstatic cl::opt<bool> PrintGCInfo(\"print-gc\", cl::Hidden,\n cl::desc(\"Dump garbage collector data\"));\nstatic cl::opt<bool> VerifyMachineCode(\"verify-machineinstrs\", cl::Hidden,\n cl::desc(\"Verify generated machine code\"),\n cl::init(getenv(\"LLVM_VERIFY_MACHINEINSTRS\")!=NULL));\n\n\/\/ Enable or disable FastISel. Both options are needed, because\n\/\/ FastISel is enabled by default with -fast, and we wish to be\n\/\/ able to enable or disable fast-isel independently from -O0.\nstatic cl::opt<cl::boolOrDefault>\nEnableFastISelOption(\"fast-isel\", cl::Hidden,\n cl::desc(\"Enable the \\\"fast\\\" instruction selector\"));\n\n\/\/ Enable or disable an experimental optimization to split GEPs\n\/\/ and run a special GVN pass which does not examine loads, in\n\/\/ an effort to factor out redundancy implicit in complex GEPs.\nstatic cl::opt<bool> EnableSplitGEPGVN(\"split-gep-gvn\", cl::Hidden,\n cl::desc(\"Split GEPs and run no-load GVN\"));\n\nstatic cl::opt<bool> PreAllocTailDup(\"pre-regalloc-taildup\", cl::Hidden,\n cl::desc(\"Pre-register allocation tail duplication\"));\n\nLLVMTargetMachine::LLVMTargetMachine(const Target &T,\n const std::string &TargetTriple)\n : TargetMachine(T) {\n AsmInfo = T.createAsmInfo(TargetTriple);\n}\n\n\/\/ Set the default code model for the JIT for a generic target.\n\/\/ FIXME: Is small right here? or .is64Bit() ? Large : Small?\nvoid\nLLVMTargetMachine::setCodeModelForJIT() {\n setCodeModel(CodeModel::Small);\n}\n\n\/\/ Set the default code model for static compilation for a generic target.\nvoid\nLLVMTargetMachine::setCodeModelForStatic() {\n setCodeModel(CodeModel::Small);\n}\n\nFileModel::Model\nLLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,\n formatted_raw_ostream &Out,\n CodeGenFileType FileType,\n CodeGenOpt::Level OptLevel) {\n \/\/ Add common CodeGen passes.\n if (addCommonCodeGenPasses(PM, OptLevel))\n return FileModel::Error;\n\n switch (FileType) {\n default:\n break;\n case TargetMachine::AssemblyFile:\n if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))\n return FileModel::Error;\n return FileModel::AsmFile;\n case TargetMachine::ObjectFile:\n if (getMachOWriterInfo())\n return FileModel::MachOFile;\n else if (getELFWriterInfo())\n return FileModel::ElfFile;\n }\n\n return FileModel::Error;\n}\n\nbool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,\n CodeGenOpt::Level OptLevel,\n bool Verbose,\n formatted_raw_ostream &Out) {\n FunctionPass *Printer =\n getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);\n if (!Printer)\n return true;\n\n PM.add(Printer);\n return false;\n}\n\n\/\/\/ addPassesToEmitFileFinish - If the passes to emit the specified file had to\n\/\/\/ be split up (e.g., to add an object writer pass), this method can be used to\n\/\/\/ finish up adding passes to emit the file, if necessary.\nbool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,\n MachineCodeEmitter *MCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForStatic();\n \n if (MCE)\n addSimpleCodeEmitter(PM, OptLevel, *MCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitFileFinish - If the passes to emit the specified file had to\n\/\/\/ be split up (e.g., to add an object writer pass), this method can be used to\n\/\/\/ finish up adding passes to emit the file, if necessary.\nbool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,\n JITCodeEmitter *JCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForJIT();\n \n if (JCE)\n addSimpleCodeEmitter(PM, OptLevel, *JCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitFileFinish - If the passes to emit the specified file had to\n\/\/\/ be split up (e.g., to add an object writer pass), this method can be used to\n\/\/\/ finish up adding passes to emit the file, if necessary.\nbool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,\n ObjectCodeEmitter *OCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForStatic();\n \n if (OCE)\n addSimpleCodeEmitter(PM, OptLevel, *OCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitMachineCode - Add passes to the specified pass manager to\n\/\/\/ get machine code emitted. This uses a MachineCodeEmitter object to handle\n\/\/\/ actually outputting the machine code and resolving things like the address\n\/\/\/ of functions. This method should returns true if machine code emission is\n\/\/\/ not supported.\n\/\/\/\nbool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,\n MachineCodeEmitter &MCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForJIT();\n \n \/\/ Add common CodeGen passes.\n if (addCommonCodeGenPasses(PM, OptLevel))\n return true;\n\n addCodeEmitter(PM, OptLevel, MCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitMachineCode - Add passes to the specified pass manager to\n\/\/\/ get machine code emitted. This uses a MachineCodeEmitter object to handle\n\/\/\/ actually outputting the machine code and resolving things like the address\n\/\/\/ of functions. This method should returns true if machine code emission is\n\/\/\/ not supported.\n\/\/\/\nbool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,\n JITCodeEmitter &JCE,\n CodeGenOpt::Level OptLevel) {\n \/\/ Make sure the code model is set.\n setCodeModelForJIT();\n \n \/\/ Add common CodeGen passes.\n if (addCommonCodeGenPasses(PM, OptLevel))\n return true;\n\n addCodeEmitter(PM, OptLevel, JCE);\n if (PrintEmittedAsm)\n addAssemblyEmitter(PM, OptLevel, true, ferrs());\n\n PM.add(createGCInfoDeleter());\n\n return false; \/\/ success!\n}\n\nstatic void printAndVerify(PassManagerBase &PM,\n const char *Banner,\n bool allowDoubleDefs = false) {\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));\n\n if (VerifyMachineCode)\n PM.add(createMachineVerifierPass(allowDoubleDefs));\n}\n\n\/\/\/ addCommonCodeGenPasses - Add standard LLVM codegen passes used for both\n\/\/\/ emitting to assembly files or machine code output.\n\/\/\/\nbool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,\n CodeGenOpt::Level OptLevel) {\n \/\/ Standard LLVM-Level Passes.\n\n \/\/ Optionally, tun split-GEPs and no-load GVN.\n if (EnableSplitGEPGVN) {\n PM.add(createGEPSplitterPass());\n PM.add(createGVNPass(\/*NoPRE=*\/false, \/*NoLoads=*\/true));\n }\n\n \/\/ Run loop strength reduction before anything else.\n if (OptLevel != CodeGenOpt::None && !DisableLSR) {\n PM.add(createLoopStrengthReducePass(getTargetLowering()));\n if (PrintLSR)\n PM.add(createPrintFunctionPass(\"\\n\\n*** Code after LSR ***\\n\", &dbgs()));\n }\n\n \/\/ Turn exception handling constructs into something the code generators can\n \/\/ handle.\n switch (getMCAsmInfo()->getExceptionHandlingType())\n {\n case ExceptionHandling::SjLj:\n \/\/ SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both\n PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));\n PM.add(createSjLjEHPass(getTargetLowering()));\n break;\n case ExceptionHandling::Dwarf:\n PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));\n break;\n case ExceptionHandling::None:\n PM.add(createLowerInvokePass(getTargetLowering()));\n break;\n }\n\n PM.add(createGCLoweringPass());\n\n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n if (OptLevel != CodeGenOpt::None && !DisableCGP)\n PM.add(createCodeGenPreparePass(getTargetLowering()));\n\n PM.add(createStackProtectorPass(getTargetLowering()));\n\n if (PrintISelInput)\n PM.add(createPrintFunctionPass(\"\\n\\n\"\n \"*** Final LLVM Code input to ISel ***\\n\",\n &dbgs()));\n\n \/\/ Standard Lower-Level Passes.\n\n \/\/ Set up a MachineFunction for the rest of CodeGen to work on.\n PM.add(new MachineFunctionAnalysis(*this, OptLevel));\n\n \/\/ Enable FastISel with -fast, but allow that to be overridden.\n if (EnableFastISelOption == cl::BOU_TRUE ||\n (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))\n EnableFastISel = true;\n\n \/\/ Ask the target for an isel.\n if (addInstSelector(PM, OptLevel))\n return true;\n\n \/\/ Print the instruction selected machine code...\n printAndVerify(PM, \"After Instruction Selection\",\n \/* allowDoubleDefs= *\/ true);\n\n if (OptLevel != CodeGenOpt::None) {\n if (!DisableMachineLICM)\n PM.add(createMachineLICMPass());\n if (!DisableMachineSink)\n PM.add(createMachineSinkingPass());\n printAndVerify(PM, \"After MachineLICM and MachineSinking\",\n \/* allowDoubleDefs= *\/ true);\n }\n\n \/\/ Pre-ra tail duplication.\n if (OptLevel != CodeGenOpt::None &&\n !DisableTailDuplicate && PreAllocTailDup) {\n PM.add(createTailDuplicatePass(true));\n printAndVerify(PM, \"After Pre-RegAlloc TailDuplicate\");\n }\n\n \/\/ Run pre-ra passes.\n if (addPreRegAlloc(PM, OptLevel))\n printAndVerify(PM, \"After PreRegAlloc passes\",\n \/* allowDoubleDefs= *\/ true);\n\n \/\/ Perform register allocation.\n PM.add(createRegisterAllocator());\n printAndVerify(PM, \"After Register Allocation\");\n\n \/\/ Perform stack slot coloring.\n if (OptLevel != CodeGenOpt::None && !DisableSSC) {\n \/\/ FIXME: Re-enable coloring with register when it's capable of adding\n \/\/ kill markers.\n PM.add(createStackSlotColoringPass(false));\n printAndVerify(PM, \"After StackSlotColoring\");\n }\n\n \/\/ Run post-ra passes.\n if (addPostRegAlloc(PM, OptLevel))\n printAndVerify(PM, \"After PostRegAlloc passes\");\n\n PM.add(createLowerSubregsPass());\n printAndVerify(PM, \"After LowerSubregs\");\n\n \/\/ Insert prolog\/epilog code. Eliminate abstract frame index references...\n PM.add(createPrologEpilogCodeInserter());\n printAndVerify(PM, \"After PrologEpilogCodeInserter\");\n\n \/\/ Run pre-sched2 passes.\n if (addPreSched2(PM, OptLevel))\n printAndVerify(PM, \"After PreSched2 passes\");\n\n \/\/ Second pass scheduler.\n if (OptLevel != CodeGenOpt::None && !DisablePostRA) {\n PM.add(createPostRAScheduler(OptLevel));\n printAndVerify(PM, \"After PostRAScheduler\");\n }\n\n \/\/ Branch folding must be run after regalloc and prolog\/epilog insertion.\n if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {\n PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));\n printAndVerify(PM, \"After BranchFolding\");\n }\n\n \/\/ Tail duplication.\n if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {\n PM.add(createTailDuplicatePass(false));\n printAndVerify(PM, \"After TailDuplicate\");\n }\n\n PM.add(createGCMachineCodeAnalysisPass());\n\n if (PrintGCInfo)\n PM.add(createGCInfoPrinter(dbgs()));\n\n if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {\n PM.add(createCodePlacementOptPass());\n printAndVerify(PM, \"After CodePlacementOpt\");\n }\n\n if (addPreEmitPass(PM, OptLevel))\n printAndVerify(PM, \"After PreEmit passes\");\n\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"stdafx.h\"\n#include \"tpsemaphore.h\"\n\nusing namespace common;\n\n\ncTPSemaphore::cTPSemaphore()\n\t: m_isThreadLoop(false)\n{\n}\n\ncTPSemaphore::~cTPSemaphore()\n{\n\tClear();\n}\n\n\n\/\/ if threadCount -1, threadCount = processor count\nbool cTPSemaphore::Init(const int threadCount \/\/=-1\n)\n{\n\tClear();\n\n\tint generateThreadCount = threadCount;\n\tif (threadCount < 0)\n\t{\n\t\tSYSTEM_INFO si;\n\t\tGetSystemInfo(&si);\n\t\tgenerateThreadCount = (int)si.dwNumberOfProcessors;\n\t}\n\n\tm_isThreadLoop = true;\n\tfor (int i = 0; i < generateThreadCount; ++i)\n\t\tm_threads.push_back(new std::thread(cTPSemaphore::ThreadFunction, this));\n\n\treturn true;\n}\n\n\nbool cTPSemaphore::PushTask(cTask *task)\n{\n\tm_cs.Lock();\n\tm_tasks.push_front(task);\n\tm_cs.Unlock();\n\tm_sema.Signal();\n\treturn true;\n}\n\n\ncTask* cTPSemaphore::PopTask()\n{\n\tcTask *task = NULL;\n\n\tm_sema.Wait();\n\tm_cs.Lock();\n\tif (m_tasks.empty())\n\t{\n\t\tm_cs.Unlock();\n\t\treturn PopTask();\n\t}\n\telse\n\t{\n\t\ttask = m_tasks.back();\n\t\tm_tasks.pop_back();\n\t}\n\tm_cs.Unlock();\n\treturn task;\n}\n\n\nbool cTPSemaphore::RemoveTask(const StrId &taskName)\n{\n\tm_cs.Lock();\n\tauto it = std::find_if(m_tasks.begin(), m_tasks.end()\n\t\t, [&](auto &t) { return t->m_name == taskName; });\n\tconst bool isExist = (m_tasks.end() != it);\n\tif (isExist)\n\t{\n\t\tdelete *it;\n\t\tm_tasks.erase(it);\n\t\tm_sema.Wait();\n\t}\n\tm_cs.Unlock();\n\treturn true;\n}\n\n\nbool cTPSemaphore::RemoveTask(const int taskId)\n{\n\tm_cs.Lock();\n\tauto it = std::find_if(m_tasks.begin(), m_tasks.end()\n\t\t, [&](auto &t) { return t->m_id == taskId; });\n\tconst bool isExist = (m_tasks.end() != it);\n\tif (isExist)\n\t{\n\t\tdelete *it;\n\t\tm_tasks.erase(it);\n\t\tm_sema.Wait();\n\t}\n\tm_cs.Unlock();\n\treturn true;\n}\n\n\n\/\/ wait all task finish\n\/\/ no optimize\nvoid cTPSemaphore::Wait()\n{\n\twhile (!m_tasks.empty())\n\t\tSleep(10);\n}\n\n\n\/\/ is initialize?\nbool cTPSemaphore::IsInit()\n{\n\treturn !m_threads.empty();\n}\n\n\n\/\/ thread terminate\nvoid cTPSemaphore::Terminate()\n{\n\tm_isThreadLoop = false;\n\n\tfor (auto th : m_threads)\n\t\tif (th->joinable())\n\t\t\tPushTask(nullptr); \/\/ finish thread\n\n\tfor (auto th : m_threads)\n\t{\n\t\tif (th->joinable())\n\t\t\tth->join();\n\t\tdelete th;\n\t}\n\tm_threads.clear();\n}\n\n\nvoid cTPSemaphore::Clear()\n{\n\t\/\/ wait all task finish\n\tfor (auto th : m_threads)\n\t\tif (th->joinable())\n\t\t\tPushTask(nullptr); \/\/ finish thread\n\n\tm_isThreadLoop = false;\n\n\tfor (auto th : m_threads)\n\t{\n\t\tif (th->joinable())\n\t\t\tth->join();\n\t\tdelete th;\n\t}\n\tm_threads.clear();\n\n\tm_sema.Clear();\n\n\tAutoCSLock cs(m_cs);\n\twhile (!m_tasks.empty())\n\t{\n\t\tdelete m_tasks.back();\n\t\tm_tasks.pop_back();\n\t}\n}\n\n\nint cTPSemaphore::ThreadFunction(cTPSemaphore *tpSemaphore)\n{\n\twhile (tpSemaphore->m_isThreadLoop)\n\t{\n\t\tcTask *task = tpSemaphore->PopTask();\n\t\tif (!task) \/\/ end thread command?\n\t\t\tbreak;\n\t\ttry \n\t\t{\n\t\t\ttask->Run(0.f);\n\t\t}\n\t\tcatch (std::exception &e) \n\t\t{\n\t\t\tdbg::Logc(2, \"error cTPSemaphore Task exception, %s\\n\", e.what());\n\t\t}\n\t\tdelete task;\n\t}\n\treturn 1;\n}\n<commit_msg>update common, thread etc<commit_after>\n#include \"stdafx.h\"\n#include \"tpsemaphore.h\"\n\nusing namespace common;\n\n\ncTPSemaphore::cTPSemaphore()\n\t: m_isThreadLoop(false)\n{\n}\n\ncTPSemaphore::~cTPSemaphore()\n{\n\tClear();\n}\n\n\n\/\/ if threadCount -1, threadCount = processor count\nbool cTPSemaphore::Init(const int threadCount \/\/=-1\n)\n{\n\tClear();\n\n\tint generateThreadCount = threadCount;\n\tif (threadCount < 0)\n\t{\n\t\tSYSTEM_INFO si;\n\t\tGetSystemInfo(&si);\n\t\tgenerateThreadCount = (int)si.dwNumberOfProcessors;\n\t}\n\n\tm_isThreadLoop = true;\n\tfor (int i = 0; i < generateThreadCount; ++i)\n\t\tm_threads.push_back(new std::thread(cTPSemaphore::ThreadFunction, this));\n\n\treturn true;\n}\n\n\nbool cTPSemaphore::PushTask(cTask *task)\n{\n\tm_cs.Lock();\n\tm_tasks.push_front(task);\n\tm_cs.Unlock();\n\tm_sema.Signal();\n\treturn true;\n}\n\n\ncTask* cTPSemaphore::PopTask()\n{\n\tcTask *task = NULL;\n\n\tm_sema.Wait();\n\tm_cs.Lock();\n\tif (m_tasks.empty())\n\t{\n\t\tm_cs.Unlock();\n\t\treturn PopTask();\n\t}\n\telse\n\t{\n\t\ttask = m_tasks.back();\n\t\tm_tasks.pop_back();\n\t}\n\tm_cs.Unlock();\n\treturn task;\n}\n\n\nbool cTPSemaphore::RemoveTask(const StrId &taskName)\n{\n\tm_cs.Lock();\n\tauto it = std::find_if(m_tasks.begin(), m_tasks.end()\n\t\t, [&](auto &t) { return t->m_name == taskName; });\n\tconst bool isExist = (m_tasks.end() != it);\n\tif (isExist)\n\t{\n\t\tdelete *it;\n\t\tm_tasks.erase(it);\n\t\tm_sema.Wait();\n\t}\n\tm_cs.Unlock();\n\treturn true;\n}\n\n\nbool cTPSemaphore::RemoveTask(const int taskId)\n{\n\tm_cs.Lock();\n\tauto it = std::find_if(m_tasks.begin(), m_tasks.end()\n\t\t, [&](auto &t) { return t->m_id == taskId; });\n\tconst bool isExist = (m_tasks.end() != it);\n\tif (isExist)\n\t{\n\t\tdelete *it;\n\t\tm_tasks.erase(it);\n\t\tm_sema.Wait();\n\t}\n\tm_cs.Unlock();\n\treturn true;\n}\n\n\n\/\/ wait all task finish\n\/\/ no optimize\nvoid cTPSemaphore::Wait()\n{\n\twhile (!m_tasks.empty())\n\t\tSleep(10);\n}\n\n\n\/\/ is initialize?\nbool cTPSemaphore::IsInit()\n{\n\treturn !m_threads.empty();\n}\n\n\n\/\/ thread terminate\nvoid cTPSemaphore::Terminate()\n{\n\tm_isThreadLoop = false;\n\n\tfor (auto th : m_threads)\n\t\tif (th->joinable())\n\t\t\tPushTask(nullptr); \/\/ finish thread\n\n\tfor (auto th : m_threads)\n\t{\n\t\tif (th->joinable())\n\t\t\tth->join();\n\t\tdelete th;\n\t}\n\tm_threads.clear();\n}\n\n\nvoid cTPSemaphore::Clear()\n{\n\t\/\/ wait all task finish\n\tfor (auto th : m_threads)\n\t\tif (th->joinable())\n\t\t\tPushTask(nullptr); \/\/ finish thread\n\n\tm_isThreadLoop = false;\n\n\tfor (auto th : m_threads)\n\t{\n\t\tif (th->joinable())\n\t\t\tth->join();\n\t\tdelete th;\n\t}\n\tm_threads.clear();\n\n\tm_sema.Clear();\n\n\tAutoCSLock cs(m_cs);\n\twhile (!m_tasks.empty())\n\t{\n\t\tdelete m_tasks.back();\n\t\tm_tasks.pop_back();\n\t}\n}\n\n\nint cTPSemaphore::ThreadFunction(cTPSemaphore *tpSemaphore)\n{\n\twhile (tpSemaphore->m_isThreadLoop)\n\t{\n\t\tcTask *task = tpSemaphore->PopTask();\n\t\tif (!task) \/\/ end thread command?\n\t\t\tbreak;\n\t\ttry \n\t\t{\n\t\t\ttask->Run(0.f);\n\t\t}\n\t\tcatch (std::exception &e) \n\t\t{\n\t\t\tdbg::Logc(2, \"error cTPSemaphore Task exception, %s, %s\\n\"\n\t\t\t\t, e.what(), task->m_name.c_str());\n\t\t}\n\t\tdelete task;\n\t}\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip>\n#include <string>\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/contrib\/contrib.hpp\"\n#include \"opencv2\/superres\/superres.hpp\"\n#include \"opencv2\/superres\/optical_flow.hpp\"\n#include \"opencv2\/opencv_modules.hpp\"\n\n#if defined(HAVE_OPENCV_OCL)\n#include \"opencv2\/ocl\/ocl.hpp\"\n#endif\n\nusing namespace std;\nusing namespace cv;\nusing namespace cv::superres;\nbool useOclChanged;\n#define MEASURE_TIME(op) \\\n { \\\n TickMeter tm; \\\n tm.start(); \\\n op; \\\n tm.stop(); \\\n cout << tm.getTimeSec() << \" sec\" << endl; \\\n }\n\nstatic Ptr<DenseOpticalFlowExt> createOptFlow(const string& name, bool useGpu)\n{\n if (name == \"farneback\")\n {\n if (useGpu)\n return createOptFlow_Farneback_GPU();\n else\n return createOptFlow_Farneback();\n }\n else if (name == \"simple\")\n return createOptFlow_Simple();\n else if (name == \"tvl1\")\n {\n if (useGpu)\n return createOptFlow_DualTVL1_GPU();\n else\n return createOptFlow_DualTVL1();\n }\n else if (name == \"brox\")\n return createOptFlow_Brox_GPU();\n else if (name == \"pyrlk\")\n return createOptFlow_PyrLK_GPU();\n else\n {\n cerr << \"Incorrect Optical Flow algorithm - \" << name << endl;\n exit(-1);\n }\n}\n#if defined(HAVE_OPENCV_OCL)\nstatic Ptr<DenseOpticalFlowExt> createOptFlow(const string& name)\n{\n if (name == \"farneback\")\n {\n return createOptFlow_Farneback_OCL();\n }\n else if (name == \"simple\")\n {\n useOclChanged = true;\n std::cout<<\"simple on OpenCL has not been implemented. Use CPU instead!\\n\";\n return createOptFlow_Simple();\n }\n else if (name == \"tvl1\")\n return createOptFlow_DualTVL1_OCL();\n else if (name == \"brox\")\n {\n std::cout<<\"brox has not been implemented!\\n\";\n return NULL;\n }\n else if (name == \"pyrlk\")\n return createOptFlow_PyrLK_OCL();\n else\n {\n cerr << \"Incorrect Optical Flow algorithm - \" << name << endl;\n }\n return 0;\n}\n#endif\nint main(int argc, const char* argv[])\n{\n useOclChanged = false;\n CommandLineParser cmd(argc, argv,\n \"{ v | video | | Input video }\"\n \"{ o | output | | Output video }\"\n \"{ s | scale | 4 | Scale factor }\"\n \"{ i | iterations | 180 | Iteration count }\"\n \"{ t | temporal | 4 | Radius of the temporal search area }\"\n \"{ f | flow | farneback | Optical flow algorithm (farneback, simple, tvl1, brox, pyrlk) }\"\n \"{ g | gpu | | CPU as default device, cuda for CUDA and ocl for OpenCL }\"\n \"{ h | help | false | Print help message }\"\n );\n\n if (cmd.get<bool>(\"help\"))\n {\n cout << \"This sample demonstrates Super Resolution algorithms for video sequence\" << endl;\n cmd.printParams();\n return 0;\n }\n\n const string inputVideoName = cmd.get<string>(\"video\");\n const string outputVideoName = cmd.get<string>(\"output\");\n const int scale = cmd.get<int>(\"scale\");\n const int iterations = cmd.get<int>(\"iterations\");\n const int temporalAreaRadius = cmd.get<int>(\"temporal\");\n const string optFlow = cmd.get<string>(\"flow\");\n string gpuOption = cmd.get<string>(\"gpu\");\n\n std::transform(gpuOption.begin(), gpuOption.end(), gpuOption.begin(), ::tolower);\n\n bool useCuda = false;\n bool useOcl = false;\n\n if(gpuOption.compare(\"ocl\") == 0)\n useOcl = true;\n else if(gpuOption.compare(\"cuda\") == 0)\n useCuda = true;\n\n#ifndef HAVE_OPENCV_OCL\n if(useOcl)\n {\n {\n cout<<\"OPENCL is not compiled\\n\";\n return 0;\n }\n }\n#endif\n#if defined(HAVE_OPENCV_OCL)\n std::vector<cv::ocl::Info>info;\n if(useCuda)\n {\n CV_Assert(!useOcl);\n info.clear();\n }\n\n if(useOcl)\n {\n CV_Assert(!useCuda);\n cv::ocl::getDevice(info);\n }\n#endif\n Ptr<SuperResolution> superRes;\n\n\n#if defined(HAVE_OPENCV_OCL)\n if(useOcl)\n {\n Ptr<DenseOpticalFlowExt> of = createOptFlow(optFlow);\n if (of.empty())\n exit(-1);\n if(useOclChanged)\n {\n superRes = createSuperResolution_BTVL1();\n useOcl = !useOcl;\n }else\n superRes = createSuperResolution_BTVL1_OCL();\n superRes->set(\"opticalFlow\", of);\n }\n else\n#endif\n {\n if (useCuda)\n superRes = createSuperResolution_BTVL1_GPU();\n else\n superRes = createSuperResolution_BTVL1();\n\n Ptr<DenseOpticalFlowExt> of = createOptFlow(optFlow, useCuda);\n\n if (of.empty())\n exit(-1);\n superRes->set(\"opticalFlow\", of);\n }\n\n superRes->set(\"scale\", scale);\n superRes->set(\"iterations\", iterations);\n superRes->set(\"temporalAreaRadius\", temporalAreaRadius);\n\n Ptr<FrameSource> frameSource;\n if (useCuda)\n {\n \/\/ Try to use gpu Video Decoding\n try\n {\n frameSource = createFrameSource_Video_GPU(inputVideoName);\n Mat frame;\n frameSource->nextFrame(frame);\n }\n catch (const cv::Exception&)\n {\n frameSource.release();\n }\n }\n if (frameSource.empty())\n frameSource = createFrameSource_Video(inputVideoName);\n\n \/\/ skip first frame, it is usually corrupted\n {\n Mat frame;\n frameSource->nextFrame(frame);\n cout << \"Input : \" << inputVideoName << \" \" << frame.size() << endl;\n cout << \"Scale factor : \" << scale << endl;\n cout << \"Iterations : \" << iterations << endl;\n cout << \"Temporal radius : \" << temporalAreaRadius << endl;\n cout << \"Optical Flow : \" << optFlow << endl;\n#if defined(HAVE_OPENCV_OCL)\n cout << \"Mode : \" << (useCuda ? \"CUDA\" : useOcl? \"OpenCL\" : \"CPU\") << endl;\n#else\n cout << \"Mode : \" << (useGpu ? \"CUDA\" : \"CPU\") << endl;\n#endif\n }\n\n superRes->setInput(frameSource);\n\n VideoWriter writer;\n\n for (int i = 0;; ++i)\n {\n cout << '[' << setw(3) << i << \"] : \";\n Mat result;\n\n#if defined(HAVE_OPENCV_OCL)\n cv::ocl::oclMat result_;\n\n if(useOcl)\n {\n MEASURE_TIME(superRes->nextFrame(result_));\n }\n else\n#endif\n {\n MEASURE_TIME(superRes->nextFrame(result));\n }\n\n#ifdef HAVE_OPENCV_OCL\n if(useOcl)\n {\n if(!result_.empty())\n {\n result_.download(result);\n }\n }\n#endif\n if (result.empty())\n break;\n\n imshow(\"Super Resolution\", result);\n\n if (waitKey(1000) > 0)\n break;\n\n if (!outputVideoName.empty())\n {\n if (!writer.isOpened())\n writer.open(outputVideoName, CV_FOURCC('X', 'V', 'I', 'D'), 25.0, result.size());\n writer << result;\n }\n }\n\n return 0;\n}\n<commit_msg>bugfix-for-3231<commit_after>#include <iostream>\n#include <iomanip>\n#include <string>\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/contrib\/contrib.hpp\"\n#include \"opencv2\/superres\/superres.hpp\"\n#include \"opencv2\/superres\/optical_flow.hpp\"\n#include \"opencv2\/opencv_modules.hpp\"\n\n#if defined(HAVE_OPENCV_OCL)\n#include \"opencv2\/ocl\/ocl.hpp\"\n#endif\n\nusing namespace std;\nusing namespace cv;\nusing namespace cv::superres;\nbool useOclChanged;\n#define MEASURE_TIME(op) \\\n { \\\n TickMeter tm; \\\n tm.start(); \\\n op; \\\n tm.stop(); \\\n cout << tm.getTimeSec() << \" sec\" << endl; \\\n }\n\nstatic Ptr<DenseOpticalFlowExt> createOptFlow(const string& name, bool useGpu)\n{\n if (name == \"farneback\")\n {\n if (useGpu)\n return createOptFlow_Farneback_GPU();\n else\n return createOptFlow_Farneback();\n }\n else if (name == \"simple\")\n return createOptFlow_Simple();\n else if (name == \"tvl1\")\n {\n if (useGpu)\n return createOptFlow_DualTVL1_GPU();\n else\n return createOptFlow_DualTVL1();\n }\n else if (name == \"brox\")\n return createOptFlow_Brox_GPU();\n else if (name == \"pyrlk\")\n return createOptFlow_PyrLK_GPU();\n else\n {\n cerr << \"Incorrect Optical Flow algorithm - \" << name << endl;\n exit(-1);\n }\n}\n#if defined(HAVE_OPENCV_OCL)\nstatic Ptr<DenseOpticalFlowExt> createOptFlow(const string& name)\n{\n if (name == \"farneback\")\n {\n return createOptFlow_Farneback_OCL();\n }\n else if (name == \"simple\")\n {\n useOclChanged = true;\n std::cout<<\"simple on OpenCL has not been implemented. Use CPU instead!\\n\";\n return createOptFlow_Simple();\n }\n else if (name == \"tvl1\")\n return createOptFlow_DualTVL1_OCL();\n else if (name == \"brox\")\n {\n std::cout<<\"brox has not been implemented!\\n\";\n return NULL;\n }\n else if (name == \"pyrlk\")\n return createOptFlow_PyrLK_OCL();\n else\n {\n cerr << \"Incorrect Optical Flow algorithm - \" << name << endl;\n }\n return 0;\n}\n#endif\nint main(int argc, const char* argv[])\n{\n useOclChanged = false;\n CommandLineParser cmd(argc, argv,\n \"{ v | video | | Input video }\"\n \"{ o | output | | Output video }\"\n \"{ s | scale | 4 | Scale factor }\"\n \"{ i | iterations | 180 | Iteration count }\"\n \"{ t | temporal | 4 | Radius of the temporal search area }\"\n \"{ f | flow | farneback | Optical flow algorithm (farneback, simple, tvl1, brox, pyrlk) }\"\n \"{ g | gpu | | CPU as default device, cuda for CUDA and ocl for OpenCL }\"\n \"{ h | help | false | Print help message }\"\n );\n\n if (cmd.get<bool>(\"help\"))\n {\n cout << \"This sample demonstrates Super Resolution algorithms for video sequence\" << endl;\n cmd.printParams();\n return 0;\n }\n\n const string inputVideoName = cmd.get<string>(\"video\");\n const string outputVideoName = cmd.get<string>(\"output\");\n const int scale = cmd.get<int>(\"scale\");\n const int iterations = cmd.get<int>(\"iterations\");\n const int temporalAreaRadius = cmd.get<int>(\"temporal\");\n const string optFlow = cmd.get<string>(\"flow\");\n string gpuOption = cmd.get<string>(\"gpu\");\n\n std::transform(gpuOption.begin(), gpuOption.end(), gpuOption.begin(), ::tolower);\n\n bool useCuda = false;\n bool useOcl = false;\n\n if(gpuOption.compare(\"ocl\") == 0)\n useOcl = true;\n else if(gpuOption.compare(\"cuda\") == 0)\n useCuda = true;\n\n#ifndef HAVE_OPENCV_OCL\n if(useOcl)\n {\n {\n cout<<\"OPENCL is not compiled\\n\";\n return 0;\n }\n }\n#endif\n#if defined(HAVE_OPENCV_OCL)\n std::vector<cv::ocl::Info>info;\n if(useCuda)\n {\n CV_Assert(!useOcl);\n info.clear();\n }\n\n if(useOcl)\n {\n CV_Assert(!useCuda);\n cv::ocl::getDevice(info);\n }\n#endif\n Ptr<SuperResolution> superRes;\n\n\n#if defined(HAVE_OPENCV_OCL)\n if(useOcl)\n {\n Ptr<DenseOpticalFlowExt> of = createOptFlow(optFlow);\n if (of.empty())\n exit(-1);\n if(useOclChanged)\n {\n superRes = createSuperResolution_BTVL1();\n useOcl = !useOcl;\n }else\n superRes = createSuperResolution_BTVL1_OCL();\n superRes->set(\"opticalFlow\", of);\n }\n else\n#endif\n {\n if (useCuda)\n superRes = createSuperResolution_BTVL1_GPU();\n else\n superRes = createSuperResolution_BTVL1();\n\n Ptr<DenseOpticalFlowExt> of = createOptFlow(optFlow, useCuda);\n\n if (of.empty())\n exit(-1);\n superRes->set(\"opticalFlow\", of);\n }\n\n superRes->set(\"scale\", scale);\n superRes->set(\"iterations\", iterations);\n superRes->set(\"temporalAreaRadius\", temporalAreaRadius);\n\n Ptr<FrameSource> frameSource;\n if (useCuda)\n {\n \/\/ Try to use gpu Video Decoding\n try\n {\n frameSource = createFrameSource_Video_GPU(inputVideoName);\n Mat frame;\n frameSource->nextFrame(frame);\n }\n catch (const cv::Exception&)\n {\n frameSource.release();\n }\n }\n if (frameSource.empty())\n frameSource = createFrameSource_Video(inputVideoName);\n\n \/\/ skip first frame, it is usually corrupted\n {\n Mat frame;\n frameSource->nextFrame(frame);\n cout << \"Input : \" << inputVideoName << \" \" << frame.size() << endl;\n cout << \"Scale factor : \" << scale << endl;\n cout << \"Iterations : \" << iterations << endl;\n cout << \"Temporal radius : \" << temporalAreaRadius << endl;\n cout << \"Optical Flow : \" << optFlow << endl;\n#if defined(HAVE_OPENCV_OCL)\n cout << \"Mode : \" << (useCuda ? \"CUDA\" : useOcl? \"OpenCL\" : \"CPU\") << endl;\n#else\n cout << \"Mode : \" << (useCuda ? \"CUDA\" : \"CPU\") << endl;\n#endif\n }\n\n superRes->setInput(frameSource);\n\n VideoWriter writer;\n\n for (int i = 0;; ++i)\n {\n cout << '[' << setw(3) << i << \"] : \";\n Mat result;\n\n#if defined(HAVE_OPENCV_OCL)\n cv::ocl::oclMat result_;\n\n if(useOcl)\n {\n MEASURE_TIME(superRes->nextFrame(result_));\n }\n else\n#endif\n {\n MEASURE_TIME(superRes->nextFrame(result));\n }\n\n#ifdef HAVE_OPENCV_OCL\n if(useOcl)\n {\n if(!result_.empty())\n {\n result_.download(result);\n }\n }\n#endif\n if (result.empty())\n break;\n\n imshow(\"Super Resolution\", result);\n\n if (waitKey(1000) > 0)\n break;\n\n if (!outputVideoName.empty())\n {\n if (!writer.isOpened())\n writer.open(outputVideoName, CV_FOURCC('X', 'V', 'I', 'D'), 25.0, result.size());\n writer << result;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName\t\t\t\t: NFCMapModule.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date : 2013-07-05\r\n\/\/ @Module : NFCMapModule\r\n\/\/ @Desc :\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#include \"NFCMapModule.h\"\r\n\r\nbool NFCMapModule::Init()\r\n{\r\n m_pNoSqlModule = pPluginManager->GetModule<NFINoSqlModule>(\"NFCNoSqlModule\");\r\n m_pGameServerNet_ServerModule = pPluginManager->GetModule<NFIGameServerNet_ServerModule>(\"NFCGameServerNet_ServerModule\");\r\n return true;\r\n}\r\n\r\nbool NFCMapModule::Shut()\r\n{\r\n return true;\r\n}\r\n\r\nbool NFCMapModule::Execute()\r\n{\r\n return true;\r\n}\r\n\r\nbool NFCMapModule::AfterInit()\r\n{\r\n\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_BIG_MAP_GRID, this, &NFCMapModule::ReqBigMapsInfo)) { return false; }\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_MAP_GRID_INFO, this, &NFCMapModule::ReqMapTitleInfo)) { return false; }\r\n\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_HOLD_MAP_GRID, this, &NFCMapModule::ReqStation)) { return false; }\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_GET_MAP_GRID_AWARD, this, &NFCMapModule::ReqGetMapAward)) { return false; }\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_LEAVE_MSG_MAP_GRID, this, &NFCMapModule::ReqLeaveMsgToMap)) { return false; }\r\n\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_MAP_GRID_HUNTING, this, &NFCMapModule::ReqMapHunting)) { return false; }\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_MAP_GRID_KING_WAR, this, &NFCMapModule::ReqMapKingWar)) { return false; }\r\n\r\n return true;\r\n}\r\n\r\nvoid NFCMapModule::ReqMapTitleInfo(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqBigMapGridInfo);\r\n\r\n\r\n\r\n\r\n}\r\n\r\nvoid NFCMapModule::ReqBigMapsInfo(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqBigMapInfo);\r\n}\r\n\r\nvoid NFCMapModule::ReqStation(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqHoldMapGrid);\r\n}\r\n\r\nvoid NFCMapModule::ReqGetMapAward(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqGetMapAward);\r\n}\r\n\r\nvoid NFCMapModule::ReqLeaveMsgToMap(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqLeaveMapMsg);\r\n}\r\n\r\nvoid NFCMapModule::ReqMapHunting(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqMapHunting);\r\n}\r\n\r\nvoid NFCMapModule::ReqMapKingWar(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqMapKingWar);\r\n}\r\n\r\nstd::string NFCMapModule::GetGridBaseKey(const std::string&strGridID)\r\n{\r\n return \"GridBaseKey_\" + strGridID;\r\n}\r\n\r\nstd::string NFCMapModule::GetGridLeaveMsgKey(const std::string&strGridID)\r\n{\r\n return \"GridLeaveMsgKey_\" + strGridID;\r\n}\r\n\r\nstd::string NFCMapModule::GetGridWarHistoryKey(const std::string&strGridID)\r\n{\r\n return \"GridWarHistoryKey_\" + strGridID;\r\n}\r\n\r\nbool NFCMapModule::GetGridBaseInfo(const std::string&strGridID, NFMsg::BigMapGridBaseInfo& xBaseInfo)\r\n{\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strKey = GetGridBaseKey(strGridID);\r\n std::vector<std::pair<std::string, std::string>> xValue;\r\n int nRet = pNoSqlDriver->HGetAll(strKey, xValue);\r\n if(nRet > 0)\r\n {\r\n \/\/xBaseInfo.set_id(\"\");\r\n \/\/xBaseInfo.set_owner();\r\n \/\/xBaseInfo.set_level(1);\r\n \/\/xBaseInfo.set_member_count(100);\r\n \/\/xBaseInfo.set_resource(100);\r\n \/\/xBaseInfo.set_icon(\"\");\r\n\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::GetGridLeaveMsgInfo(const std::string&strGridID, std::vector<NFMsg::BigMapLeaveMsg>& xLeaveMsgList)\r\n{\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strKey = GetGridLeaveMsgKey(strGridID);\r\n std::vector<std::pair<std::string, std::string>> xValue;\r\n int nRet = pNoSqlDriver->HGetAll(strKey, xValue);\r\n if(nRet > 0)\r\n {\r\n for(int i = 0; i< xValue.size(); ++i)\r\n {\r\n \/\/first is a guid\r\n\t\t\t\tNFMsg::BigMapLeaveMsg xLeaveMsg;\r\n if (!xLeaveMsg.ParseFromString(xValue[i].second))\r\n {\r\n \/\/log error\r\n continue;\r\n }\r\n\r\n xLeaveMsgList.push_back(xLeaveMsg);\r\n }\r\n\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::GetGridWarHistoryInfo(const std::string&strGridID, std::vector<NFMsg::BigMapWarHistory>& xWarHistoryList)\r\n{\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strKey = GetGridWarHistoryKey(strGridID);\r\n std::vector<std::pair<std::string, std::string>> xValue;\r\n int nRet = pNoSqlDriver->HGetAll(strKey, xValue);\r\n if(nRet > 0)\r\n {\r\n for(int i = 0; i< xValue.size(); ++i)\r\n {\r\n \/\/first is a guid\r\n NFMsg::BigMapWarHistory xWarData;\r\n if (!xWarData.ParseFromString(xValue[i].second))\r\n {\r\n \/\/log error\r\n continue;\r\n }\r\n\r\n xWarHistoryList.push_back(xWarData);\r\n }\r\n\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::SetGridBaseInfo(const std::string&strGridID, const NFMsg::BigMapGridBaseInfo& xBaseInfo)\r\n{\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strKey = GetGridBaseKey(strGridID);\r\n\r\n std::vector<std::string> keys;\r\n std::vector<std::string> values;\r\n\r\n \/\/xBaseInfo.set_id(\"\");\r\n \/\/xBaseInfo.set_owner();\r\n \/\/xBaseInfo.set_level(1);\r\n \/\/xBaseInfo.set_member_count(100);\r\n \/\/xBaseInfo.set_resource(100);\r\n \/\/xBaseInfo.set_icon(\"\");\r\n\r\n pNoSqlDriver->HMSet(strKey, keys, values);\r\n\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::AddGridLeaveMsgInfo(const std::string&strGridID, const NFMsg::BigMapLeaveMsg& xLeaveMsg)\r\n{\r\n \/\/\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strValue;\r\n std::string strKey = GetGridLeaveMsgKey(strGridID);\r\n pNoSqlDriver->ListPush(strKey, strValue);\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::AddGridWarHistoryInfo(const std::string&strGridID, const NFMsg::BigMapWarHistory& xWarHistory)\r\n{\r\n \/\/\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strValue;\r\n std::string strKey = GetGridWarHistoryKey(strGridID);\r\n\r\n pNoSqlDriver->ListPush(strKey, strValue);\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n<commit_msg>map logic<commit_after>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName\t\t\t\t: NFCMapModule.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date : 2013-07-05\r\n\/\/ @Module : NFCMapModule\r\n\/\/ @Desc :\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#include \"NFCMapModule.h\"\r\n\r\nbool NFCMapModule::Init()\r\n{\r\n m_pNoSqlModule = pPluginManager->GetModule<NFINoSqlModule>(\"NFCNoSqlModule\");\r\n m_pGameServerNet_ServerModule = pPluginManager->GetModule<NFIGameServerNet_ServerModule>(\"NFCGameServerNet_ServerModule\");\r\n return true;\r\n}\r\n\r\nbool NFCMapModule::Shut()\r\n{\r\n return true;\r\n}\r\n\r\nbool NFCMapModule::Execute()\r\n{\r\n return true;\r\n}\r\n\r\nbool NFCMapModule::AfterInit()\r\n{\r\n\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_BIG_MAP_GRID, this, &NFCMapModule::ReqBigMapsInfo)) { return false; }\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_MAP_GRID_INFO, this, &NFCMapModule::ReqMapTitleInfo)) { return false; }\r\n\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_HOLD_MAP_GRID, this, &NFCMapModule::ReqStation)) { return false; }\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_GET_MAP_GRID_AWARD, this, &NFCMapModule::ReqGetMapAward)) { return false; }\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_LEAVE_MSG_MAP_GRID, this, &NFCMapModule::ReqLeaveMsgToMap)) { return false; }\r\n\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_MAP_GRID_HUNTING, this, &NFCMapModule::ReqMapHunting)) { return false; }\r\n\tif (!m_pGameServerNet_ServerModule->AddReciveCallBack(NFMsg::EGameMsgID::EGMI_REQ_MAP_GRID_KING_WAR, this, &NFCMapModule::ReqMapKingWar)) { return false; }\r\n\r\n return true;\r\n}\r\n\r\nvoid NFCMapModule::ReqMapTitleInfo(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqBigMapGridInfo);\r\n\r\n\r\n\r\n\r\n}\r\n\r\nvoid NFCMapModule::ReqBigMapsInfo(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqBigMapInfo);\r\n}\r\n\r\nvoid NFCMapModule::ReqStation(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqHoldMapGrid);\r\n}\r\n\r\nvoid NFCMapModule::ReqGetMapAward(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqGetMapAward);\r\n}\r\n\r\nvoid NFCMapModule::ReqLeaveMsgToMap(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqLeaveMapMsg);\r\n}\r\n\r\nvoid NFCMapModule::ReqMapHunting(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqMapHunting);\r\n}\r\n\r\nvoid NFCMapModule::ReqMapKingWar(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\r\n{\r\n\t\/\/CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqMapKingWar);\r\n}\r\n\r\nstd::string NFCMapModule::GetGridBaseKey(const std::string&strGridID)\r\n{\r\n return \"GridBaseKey_\" + strGridID;\r\n}\r\n\r\nstd::string NFCMapModule::GetGridLeaveMsgKey(const std::string&strGridID)\r\n{\r\n return \"GridLeaveMsgKey_\" + strGridID;\r\n}\r\n\r\nstd::string NFCMapModule::GetGridWarHistoryKey(const std::string&strGridID)\r\n{\r\n return \"GridWarHistoryKey_\" + strGridID;\r\n}\r\n\r\nbool NFCMapModule::GetGridBaseInfo(const std::string&strGridID, NFMsg::BigMapGridBaseInfo& xBaseInfo)\r\n{\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n\tif (pNoSqlDriver)\r\n\t{\r\n\t\tstd::string strKey = GetGridBaseKey(strGridID);\r\n\t\tstd::string strData;\r\n\t\tif (pNoSqlDriver->Get(strKey, strData))\r\n\t\t{\r\n\t\t\tif (xBaseInfo.ParseFromString(strData))\r\n\t\t\t{\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::GetGridLeaveMsgInfo(const std::string&strGridID, std::vector<NFMsg::BigMapLeaveMsg>& xLeaveMsgList)\r\n{\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n\tif (pNoSqlDriver)\r\n\t{\r\n\t\tstd::string strKey = GetGridLeaveMsgKey(strGridID);\r\n\t\tstd::vector<std::string> xValues;\r\n\t\tif (pNoSqlDriver->ListRange(strKey, 0, 10, xValues))\r\n\t\t{\r\n\t\t\tfor (int i = 0; i< xValues.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tNFMsg::BigMapLeaveMsg xLeaveMsgData;\r\n\t\t\t\tif (xLeaveMsgData.ParseFromString(xValues[i]))\r\n\t\t\t\t{\r\n\t\t\t\t\txLeaveMsgList.push_back(xLeaveMsgData);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::GetGridWarHistoryInfo(const std::string&strGridID, std::vector<NFMsg::BigMapWarHistory>& xWarHistoryList)\r\n{\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strKey = GetGridWarHistoryKey(strGridID);\r\n std::vector<std::string> xValues;\r\n if(pNoSqlDriver->ListRange(strKey, 0, 10, xValues))\r\n {\r\n for(int i = 0; i< xValues.size(); ++i)\r\n {\r\n NFMsg::BigMapWarHistory xWarData;\r\n if (xWarData.ParseFromString(xValues[i]))\r\n {\r\n\t\t\t\t\txWarHistoryList.push_back(xWarData);\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::SetGridBaseInfo(const std::string&strGridID, const NFMsg::BigMapGridBaseInfo& xBaseInfo)\r\n{\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strKey = GetGridBaseKey(strGridID);\r\n\t\tstd::string strData;\r\n\t\tif (xBaseInfo.SerializeToString(&strData))\r\n\t\t{\r\n\t\t\treturn pNoSqlDriver->Set(strKey, strData);\r\n\t\t}\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::AddGridLeaveMsgInfo(const std::string&strGridID, const NFMsg::BigMapLeaveMsg& xLeaveMsg)\r\n{\r\n \/\/\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strKey = GetGridLeaveMsgKey(strGridID);\r\n\t\tstd::string strData;\r\n\t\tif (xLeaveMsg.SerializeToString(&strData))\r\n\t\t{\r\n\t\t\treturn pNoSqlDriver->ListPush(strKey, strData);\r\n\t\t}\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCMapModule::AddGridWarHistoryInfo(const std::string&strGridID, const NFMsg::BigMapWarHistory& xWarHistory)\r\n{\r\n \/\/\r\n NFINoSqlDriver* pNoSqlDriver = m_pNoSqlModule->GetDriver();\r\n if (pNoSqlDriver)\r\n {\r\n std::string strKey = GetGridWarHistoryKey(strGridID);\r\n\t\tstd::string strData;\r\n\t\tif (xWarHistory.SerializeToString(&strData))\r\n\t\t{\r\n\t\t\t\/\/\r\n\t\t\treturn pNoSqlDriver->ListPush(strKey, strData);\r\n\t\t}\r\n }\r\n\r\n return false;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"net\/base\/cert_database.h\"\n\n#include <openssl\/x509.h>\n\n#include \"base\/logging.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/openssl_private_key_store.h\"\n#include \"net\/base\/x509_certificate.h\"\n\nnamespace net {\n\nCertDatabase::CertDatabase() {\n}\n\nint CertDatabase::CheckUserCert(X509Certificate* cert) {\n if (!cert)\n return ERR_CERT_INVALID;\n if (cert->HasExpired())\n return ERR_CERT_DATE_INVALID;\n\n if (!OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(\n X509_PUBKEY_get(X509_get_X509_PUBKEY(cert->os_cert_handle()))))\n return ERR_NO_PRIVATE_KEY_FOR_CERT;\n\n return OK;\n}\n\nint CertDatabase::AddUserCert(X509Certificate* cert) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return ERR_NOT_IMPLEMENTED;\n}\n\nvoid CertDatabase::ListCerts(CertificateList* certs) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n}\n\nint CertDatabase::ImportFromPKCS12(const std::string& data,\n const string16& password) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return ERR_NOT_IMPLEMENTED;\n}\n\nint CertDatabase::ExportToPKCS12(const CertificateList& certs,\n const string16& password,\n std::string* output) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return 0;\n}\n\nbool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return false;\n}\n\nunsigned int CertDatabase::GetCertTrust(const X509Certificate* cert,\n CertType type) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return 0;\n}\n\nbool CertDatabase::SetCertTrust(const X509Certificate* cert,\n CertType type,\n unsigned int trust_bits) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return false;\n}\n\n} \/\/ namespace net\n<commit_msg>Fixes OpenSSL build following http:\/\/codereview.chromium.org\/5686002\/<commit_after>\/\/ Copyright (c) 2010 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 \"net\/base\/cert_database.h\"\n\n#include <openssl\/x509.h>\n\n#include \"base\/logging.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/openssl_private_key_store.h\"\n#include \"net\/base\/x509_certificate.h\"\n\nnamespace net {\n\nCertDatabase::CertDatabase() {\n}\n\nint CertDatabase::CheckUserCert(X509Certificate* cert) {\n if (!cert)\n return ERR_CERT_INVALID;\n if (cert->HasExpired())\n return ERR_CERT_DATE_INVALID;\n\n if (!OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(\n X509_PUBKEY_get(X509_get_X509_PUBKEY(cert->os_cert_handle()))))\n return ERR_NO_PRIVATE_KEY_FOR_CERT;\n\n return OK;\n}\n\nint CertDatabase::AddUserCert(X509Certificate* cert) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return ERR_NOT_IMPLEMENTED;\n}\n\nvoid CertDatabase::ListCerts(CertificateList* certs) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n}\n\nCryptoModule* CertDatabase::GetDefaultModule() const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return NULL;\n}\n\nint CertDatabase::ImportFromPKCS12(net::CryptoModule* module,\n const std::string& data,\n const string16& password) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return ERR_NOT_IMPLEMENTED;\n}\n\nint CertDatabase::ExportToPKCS12(const CertificateList& certs,\n const string16& password,\n std::string* output) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return 0;\n}\n\nbool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return false;\n}\n\nunsigned int CertDatabase::GetCertTrust(const X509Certificate* cert,\n CertType type) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return 0;\n}\n\nbool CertDatabase::SetCertTrust(const X509Certificate* cert,\n CertType type,\n unsigned int trust_bits) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return false;\n}\n\n} \/\/ namespace net\n<|endoftext|>"} {"text":"<commit_before>\/* \n * Jamoma Shared Library\n * Functions and resources used by Jamoma objects.\n * By Tim Place, Copyright © 2007\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"Jamoma.h\"\n\n\/\/ constants\nconst double k_pi = 3.1415926535897932;\t\t\/\/ pi\nconst double k_twopi = 6.2831853071795864;\t\/\/ 2 * pi\nconst double k_anti_denormal_value = 1e-18;\t\n\n\/\/ statics and globals\nstatic long\t\t\tinitialized = false;\nstatic t_hashtab\t*hash_modules = NULL;\t\t\t\/\/ a hashtab of all modules (jcom.hubs) currently instantiated\n\/\/t_object\t\t\t*obj_jamoma_clock = NULL;\t\t\/\/ there is only one master clock for the whole system\n\/\/t_object\t\t\t*obj_jamoma_scheduler = NULL;\t\/\/ a shared global instance of the scheduler class (there may be others too)\nbool\t\t\t\tmax5 = false;\n\n\n\/************************************************************************************\/\n\/\/ Init the framework\n\nvoid jamoma_init(void)\n{\n\tif(!initialized){\n\t\tt_object*\tmax = gensym(\"max\")->s_thing;\n\t\tt_symbol*\tmeth = gensym(\"objectfile\");\n\t\tt_atom\t\ta[4];\n\t\n\t\tif(maxversion() >= 0x0500)\n\t\t\tmax5 = true;\n\t\t\n\t\tTTBlueInit();\n\t\tcommon_symbols_init();\n\t\tjamomaSymbolsInit();\n\n\t\treceivemaster_initclass();\n\t\treceive_initclass();\n\t\tobject_method(max, meth, gensym(\"jcom.receive\"), gensym(\"jcom.loader\"), gensym(\"jcom.receive\"));\n\t\tobject_method_sym(max, gensym(\"db.object_addinternal\"), gensym(\"jcom.receive\"), NULL);\n\t\t\n\t\tsend_initclass();\n\t\tobject_method(max, meth, gensym(\"jcom.send\"), gensym(\"jcom.loader\"), gensym(\"jcom.send\"));\n\t\tobject_method_sym(max, gensym(\"db.object_addinternal\"), gensym(\"jcom.send\"), NULL);\n\n\t\treceive_tilde_initclass();\n\t\tobject_method(max, meth, gensym(\"jcom.receive~\"), gensym(\"jcom.loader\"), gensym(\"jcom.receive~\"));\n\t\tobject_method_sym(max, gensym(\"db.object_addinternal\"), gensym(\"jcom.receive~\"), NULL);\n\n\t\tsend_tilde_initclass();\n\t\tobject_method(max, meth, gensym(\"jcom.send~\"), gensym(\"jcom.loader\"), gensym(\"jcom.send~\"));\n\t\tobject_method_sym(max, gensym(\"db.object_addinternal\"), gensym(\"jcom.send~\"), NULL);\n\t\t\n\t\t\/\/ Setup Class Aliases for TTBlue\n\t\tobject_method(max, meth, gensym(\"jcom.limiter~\"), gensym(\"tt.limiter~\"), gensym(\"jcom.limiter~\"));\n\t\tobject_method(max, meth, gensym(\"jcom.saturation~\"), gensym(\"tt.overdrive~\"), gensym(\"jcom.saturation~\"));\n\t\t\n\t\t\/\/ Create Required Global Instances\n\t\t\/\/ obj_jamoma_clock = (t_object*)object_new_typed(CLASS_NOBOX, gensym(\"jamoma.clock\"), 0, NULL);\n\t\t\/\/ obj_jamoma_scheduler = (t_object*)object_new_typed(CLASS_NOBOX, gensym(\"jamoma.scheduler\"), 0, NULL);\n\t\thash_modules = (t_hashtab*)hashtab_new(0);\n\t\t\/\/ TODO: Use quittask_install() to set up a destructor for this to free it before Max exits\n\n\t\t\/\/ Add Jamoma Key Commands:\n\t\t\n\t\t\/\/ J -- a new object box with \"jcom.\" in it\n\t\tatom_setsym(a+0, gensym(\"J\"));\n\t\tatom_setsym(a+1, gensym(\"patcher\"));\n\t\tatom_setsym(a+2, gensym(\"inserttextobj\"));\n\t\tatom_setsym(a+3, gensym(\"jcom.\"));\n\t\tobject_method_typed(max, gensym(\"definecommand\"), 4, a, NULL);\n\t\t\n\t\t\/\/ M -- a new object box with \"jmod.\" in it\n\t\tatom_setsym(a+0, gensym(\"M\"));\n\t\tatom_setsym(a+1, gensym(\"patcher\"));\n\t\tatom_setsym(a+2, gensym(\"inserttextobj\"));\n\t\tatom_setsym(a+3, gensym(\"jmod.\"));\n\t\tobject_method_typed(max, gensym(\"definecommand\"), 4, a, NULL);\n\n\t\t\/\/ I -- a new audio input module, O -- a new audio output module\t\n\t\tobject_method_parse(max, gensym(\"definecommand\"), \"I patcher insertobj bpatcher @name jmod.input~.maxpat @args \/input~\", NULL);\n\t\tobject_method_parse(max, gensym(\"definecommand\"), \"O patcher insertobj bpatcher @name jmod.output~.maxpat @args \/output~\", NULL);\n\t\n\t\t\/\/ B -- a new module in a bpatcher\n\t\tobject_method_parse(max, gensym(\"definecommand\"), \"B patcher inserttextobj \\\"bpatcher @args myModule @name jmod.\\\"\", NULL);\t\t\n\t\t\n\t\t\n\t\t\/\/ Here bind the TTBlue environment object to the symbol \"TTBlue\"\n\t\t{\n\t\t\tt_symbol* TTBlueMaxSymbol = gensym(\"TTBlue\");\n\t\t\t\n\t\t\t\/\/TTBlueMaxSymbol->s_thing = ;\n\t\t\t\/\/ Before we can do this we have to have a ttblue max class to receive the messages, duh...\n\t\t}\n\t\t\n\t\t\n\t\tpost(\"Jamoma %s - www.jamoma.org\", JAMOMA_VERSION);\n\t\tinitialized = true;\n\t}\n}\n\n\nt_max_err jamoma_hub_register(t_symbol *name, t_object *hub)\n{\n\tt_object *test = NULL;\n\t\n\thashtab_lookup(hash_modules, name, &test);\n\tif(test)\n\t\treturn MAX_ERR_GENERIC;\n\telse{\n\t\thashtab_store(hash_modules, name, hub);\n\t\treturn MAX_ERR_NONE;\n\t}\n}\n\n\nvoid jamoma_hub_remove(t_symbol *name)\n{\n\thashtab_chuckkey(hash_modules, name);\n}\n\n\nt_object* jamoma_get_hub_for_module_named(t_symbol *name)\n{\n\tt_object *hub = NULL;\n\t\n\thashtab_lookup(hash_modules, name, &hub);\n\treturn hub;\n}\n\n\nvoid jamoma_get_all_module_names(long *numModules, t_symbol ***moduleNames)\n{\n\thashtab_getkeys(hash_modules, numModules, moduleNames);\n}\n\n\nt_object* jamoma_object_getpatcher(t_object *obj)\n{\n\tt_object *patcher = NULL;\n\t\n\tif(max5)\n\t\tobject_obex_lookup(obj, gensym(\"#P\"), &patcher);\n\telse\n\t\tpatcher = (t_object*)gensym(\"#P\")->s_thing;\n\treturn patcher;\n}\n\n\nt_symbol *jamoma_patcher_getcontext(t_object *patcher)\n{\n\tif(max5){\n\t\tt_object\t*box = object_attr_getobj(patcher, jps_box);\n\t\tt_symbol\t*objclass = NULL;\n\t\t\n\t\tif(box)\n\t\t\tobjclass = object_classname(box);\n\t\t\n\t\tif(objclass == gensym(\"bpatcher\"))\n\t\t\treturn objclass;\n\t\telse if(objclass == gensym(\"newobj\"))\n\t\t\treturn gensym(\"subpatcher\");\n\t\telse\n\t\t\treturn gensym(\"toplevel\");\n\n\t\treturn _sym_nothing;\n\t}\n\telse{\n\t\terror(\"This version of Jamoma requires Max 5\");\n\t\treturn _sym_nothing;\n\t}\n}\n\n\n\/\/ Don't pass memory in for this function! It will allocate what it needs\n\/\/ -- then the caller is responsible for freeing\nvoid jamoma_patcher_getargs(t_object *patcher, long *argc, t_atom **argv)\n{\n\tif(max5){\n\t\tt_symbol\t\t*context = jamoma_patcher_getcontext(patcher);\n\t\tt_object\t\t*box = object_attr_getobj(patcher, jps_box);\n\t\tt_object\t\t*textfield = NULL;\n\t\tchar\t\t\t*text = NULL;\n\t\tunsigned long\ttextlen = 0;\n\n\t\tif(context == gensym(\"bpatcher\"))\n\t\t\tobject_attr_getvalueof(box, gensym(\"args\"), argc, argv);\n\t\telse if(context == gensym(\"subpatcher\")){\n\t\t\ttextfield = object_attr_getobj(box, gensym(\"textfield\"));\n\t\t\tobject_method(textfield, gensym(\"gettextptr\"), &text, &textlen);\n\t\t\tatom_setparse(argc, argv, text);\n\t\t}\n\t\telse{\n\t\t\t*argc = 0;\n\t\t\t*argv = NULL;\n\t\t}\n\t}\n\telse{\n\t\terror(\"This version of Jamoma requires Max 5\");\n\t}\n}\n\n\nt_symbol* jamoma_patcher_getvarname(t_object *patcher)\n{\n\tif(max5){\n\t\treturn _sym_nothing;\n\t}\n\telse{\n\t\terror(\"This version of Jamoma requires Max 5\");\n\t\treturn _sym_nothing;\n\t}\n}\n\n\n\/\/ When the DSP is started, we make sure the Jamoma Clock and Scheduler \n\/\/ are updated if needed\nvoid jamoma_dsp(t_object *, t_signal **sp, short *count)\n{\n\t\/\/jamoma_clock_dsp(NULL, sp, count);\n}\n\n\n\/\/ This is the default attribute getter for Jamoma's core\n\/\/ It sends the data out not only the parameter dumpout, but also\n\/\/ out the feedback outlet from the module\n\/\/ for example:\n\/\/ \tjamoma_class_attr_new(c, \"ramp\/drive\", _sym_symbol, (method)param_setramp, \n\/\/\t\tcalcoffset(t_param, attr_ramp));\nvoid jamoma_class_attr_new(t_class *c, char *attrName, t_symbol *attrType, method setter, method getter)\n{\n\tt_object\t*attr = NULL;\n\tchar\t\tgetterName[256];\n\t\n\tstrcpy(getterName, attrName);\n\tstrcat(getterName, \"\/get\");\n\n\tattr = attr_offset_new(attrName, attrType, 0, getter, setter, NULL);\n\tclass_addattr(c, attr);\n\n\tclass_addmethod(c, (method)jamoma_class_attr_get, getterName, A_GIMME, 0);\n}\n\n\nvoid jamoma_class_attr_array_new(t_class *c, char *attrName, t_symbol *attrType, long list_size, method setter, method getter)\n{\n\tt_object\t*attr = NULL;\n\tchar\t\tgetterName[256];\n\t\n\tstrcpy(getterName, attrName);\n\tstrcat(getterName, \"\/get\");\n\n\tattr = attr_offset_array_new(attrName, _sym_atom, list_size, 0, getter, setter, NULL, NULL);\n\tclass_addattr(c, attr);\n\n\tclass_addmethod(c, (method)jamoma_class_attr_get, getterName, A_GIMME, 0);\n}\n\n\nvoid jamoma_class_attr_get(t_object *o, t_symbol *attrName, long, t_atom *)\n{\n\tchar\t\tcAttrName[256];\n\tt_symbol\t*sAttrName;\n\tchar\t\t*temp;\n\tlong\t\tac = 0;\n\tt_atom\t\t*av = NULL;\n\tt_jcom_core_subscriber_common *x = (t_jcom_core_subscriber_common*)o;\n\t\n\tstrcpy(cAttrName, attrName->s_name);\n\ttemp = strrchr(cAttrName, '\/');\n\tif(temp)\n\t\t*temp = 0;\n\tsAttrName = gensym(cAttrName);\n\n\tobject_attr_getvalueof(o, sAttrName, &ac, &av);\n\tobject_obex_dumpout(o, sAttrName, ac, av);\n\tif(x->hub != NULL){\n\t\tchar\t\ts[256];\n\t\tt_atom\t\ta[4];\n\t\n\t\tsnprintf(s, 256, \"%s:\/%s\", x->attr_name->s_name, attrName->s_name);\n\t\tatom_setsym(a+0, gensym(s));\n\t\tsysmem_copyptr(av, a+1, sizeof(t_atom) * ac);\n\t\tobject_method_typed(x->hub, jps_feedback, ac + 1, a, NULL);\n\t}\n\n\tif(ac)\n\t\tsysmem_freeptr(av);\n}\n\n<commit_msg>Sort patcher dictionaries when they are saved. This won't benefit us until everyone is using the next build of Max, but then it will be a big benefit, as we will be able to diff patchers meaningfully using SVN.<commit_after>\/* \n * Jamoma Shared Library\n * Functions and resources used by Jamoma objects.\n * By Tim Place, Copyright © 2007\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"Jamoma.h\"\n\n\/\/ constants\nconst double k_pi = 3.1415926535897932;\t\t\/\/ pi\nconst double k_twopi = 6.2831853071795864;\t\/\/ 2 * pi\nconst double k_anti_denormal_value = 1e-18;\t\n\n\/\/ statics and globals\nstatic long\t\t\tinitialized = false;\nstatic t_hashtab\t*hash_modules = NULL;\t\t\t\/\/ a hashtab of all modules (jcom.hubs) currently instantiated\n\/\/t_object\t\t\t*obj_jamoma_clock = NULL;\t\t\/\/ there is only one master clock for the whole system\n\/\/t_object\t\t\t*obj_jamoma_scheduler = NULL;\t\/\/ a shared global instance of the scheduler class (there may be others too)\nbool\t\t\t\tmax5 = false;\n\n\n\/************************************************************************************\/\n\/\/ Init the framework\n\nvoid jamoma_init(void)\n{\n\tif(!initialized){\n\t\tt_object*\tmax = gensym(\"max\")->s_thing;\n\t\tt_symbol*\tmeth = gensym(\"objectfile\");\n\t\tt_atom\t\ta[4];\n\t\n\t\tif(maxversion() >= 0x0500)\n\t\t\tmax5 = true;\n\t\t\n\t\tTTBlueInit();\n\t\tcommon_symbols_init();\n\t\tjamomaSymbolsInit();\n\n\t\treceivemaster_initclass();\n\t\treceive_initclass();\n\t\tobject_method(max, meth, gensym(\"jcom.receive\"), gensym(\"jcom.loader\"), gensym(\"jcom.receive\"));\n\t\tobject_method_sym(max, gensym(\"db.object_addinternal\"), gensym(\"jcom.receive\"), NULL);\n\t\t\n\t\tsend_initclass();\n\t\tobject_method(max, meth, gensym(\"jcom.send\"), gensym(\"jcom.loader\"), gensym(\"jcom.send\"));\n\t\tobject_method_sym(max, gensym(\"db.object_addinternal\"), gensym(\"jcom.send\"), NULL);\n\n\t\treceive_tilde_initclass();\n\t\tobject_method(max, meth, gensym(\"jcom.receive~\"), gensym(\"jcom.loader\"), gensym(\"jcom.receive~\"));\n\t\tobject_method_sym(max, gensym(\"db.object_addinternal\"), gensym(\"jcom.receive~\"), NULL);\n\n\t\tsend_tilde_initclass();\n\t\tobject_method(max, meth, gensym(\"jcom.send~\"), gensym(\"jcom.loader\"), gensym(\"jcom.send~\"));\n\t\tobject_method_sym(max, gensym(\"db.object_addinternal\"), gensym(\"jcom.send~\"), NULL);\n\t\t\n\t\t\/\/ Setup Class Aliases for TTBlue\n\t\tobject_method(max, meth, gensym(\"jcom.limiter~\"), gensym(\"tt.limiter~\"), gensym(\"jcom.limiter~\"));\n\t\tobject_method(max, meth, gensym(\"jcom.saturation~\"), gensym(\"tt.overdrive~\"), gensym(\"jcom.saturation~\"));\n\t\t\n\t\t\/\/ Create Required Global Instances\n\t\t\/\/ obj_jamoma_clock = (t_object*)object_new_typed(CLASS_NOBOX, gensym(\"jamoma.clock\"), 0, NULL);\n\t\t\/\/ obj_jamoma_scheduler = (t_object*)object_new_typed(CLASS_NOBOX, gensym(\"jamoma.scheduler\"), 0, NULL);\n\t\thash_modules = (t_hashtab*)hashtab_new(0);\n\t\t\/\/ TODO: Use quittask_install() to set up a destructor for this to free it before Max exits\n\n\t\t\n\t\t\/\/ This tells Max 5.0.6 and higher that we want the patcher files to be saved such that they are sorted.\n\t\t\/\/ Having the saved this way makes our SVN diffs much more meaningful.\n\t\tobject_method_long(max, gensym(\"sortpatcherdictonsave\"), 1, NULL);\n\t\n\t\t\n\t\t\/\/ Add Jamoma Key Commands:\n\t\t\n\t\t\/\/ J -- a new object box with \"jcom.\" in it\n\t\tatom_setsym(a+0, gensym(\"J\"));\n\t\tatom_setsym(a+1, gensym(\"patcher\"));\n\t\tatom_setsym(a+2, gensym(\"inserttextobj\"));\n\t\tatom_setsym(a+3, gensym(\"jcom.\"));\n\t\tobject_method_typed(max, gensym(\"definecommand\"), 4, a, NULL);\n\t\t\n\t\t\/\/ M -- a new object box with \"jmod.\" in it\n\t\tatom_setsym(a+0, gensym(\"M\"));\n\t\tatom_setsym(a+1, gensym(\"patcher\"));\n\t\tatom_setsym(a+2, gensym(\"inserttextobj\"));\n\t\tatom_setsym(a+3, gensym(\"jmod.\"));\n\t\tobject_method_typed(max, gensym(\"definecommand\"), 4, a, NULL);\n\n\t\t\/\/ I -- a new audio input module, O -- a new audio output module\t\n\t\tobject_method_parse(max, gensym(\"definecommand\"), \"I patcher insertobj bpatcher @name jmod.input~.maxpat @args \/input~\", NULL);\n\t\tobject_method_parse(max, gensym(\"definecommand\"), \"O patcher insertobj bpatcher @name jmod.output~.maxpat @args \/output~\", NULL);\n\t\n\t\t\/\/ B -- a new module in a bpatcher\n\t\tobject_method_parse(max, gensym(\"definecommand\"), \"B patcher inserttextobj \\\"bpatcher @args myModule @name jmod.\\\"\", NULL);\t\t\n\t\t\n\t\t\n\t\t\/\/ Here bind the TTBlue environment object to the symbol \"TTBlue\"\n\t\t{\n\t\t\tt_symbol* TTBlueMaxSymbol = gensym(\"TTBlue\");\n\t\t\t\n\t\t\t\/\/TTBlueMaxSymbol->s_thing = ;\n\t\t\t\/\/ Before we can do this we have to have a ttblue max class to receive the messages, duh...\n\t\t}\n\t\t\n\t\t\n\t\tpost(\"Jamoma %s - www.jamoma.org\", JAMOMA_VERSION);\n\t\tinitialized = true;\n\t}\n}\n\n\nt_max_err jamoma_hub_register(t_symbol *name, t_object *hub)\n{\n\tt_object *test = NULL;\n\t\n\thashtab_lookup(hash_modules, name, &test);\n\tif(test)\n\t\treturn MAX_ERR_GENERIC;\n\telse{\n\t\thashtab_store(hash_modules, name, hub);\n\t\treturn MAX_ERR_NONE;\n\t}\n}\n\n\nvoid jamoma_hub_remove(t_symbol *name)\n{\n\thashtab_chuckkey(hash_modules, name);\n}\n\n\nt_object* jamoma_get_hub_for_module_named(t_symbol *name)\n{\n\tt_object *hub = NULL;\n\t\n\thashtab_lookup(hash_modules, name, &hub);\n\treturn hub;\n}\n\n\nvoid jamoma_get_all_module_names(long *numModules, t_symbol ***moduleNames)\n{\n\thashtab_getkeys(hash_modules, numModules, moduleNames);\n}\n\n\nt_object* jamoma_object_getpatcher(t_object *obj)\n{\n\tt_object *patcher = NULL;\n\t\n\tif(max5)\n\t\tobject_obex_lookup(obj, gensym(\"#P\"), &patcher);\n\telse\n\t\tpatcher = (t_object*)gensym(\"#P\")->s_thing;\n\treturn patcher;\n}\n\n\nt_symbol *jamoma_patcher_getcontext(t_object *patcher)\n{\n\tif(max5){\n\t\tt_object\t*box = object_attr_getobj(patcher, jps_box);\n\t\tt_symbol\t*objclass = NULL;\n\t\t\n\t\tif(box)\n\t\t\tobjclass = object_classname(box);\n\t\t\n\t\tif(objclass == gensym(\"bpatcher\"))\n\t\t\treturn objclass;\n\t\telse if(objclass == gensym(\"newobj\"))\n\t\t\treturn gensym(\"subpatcher\");\n\t\telse\n\t\t\treturn gensym(\"toplevel\");\n\n\t\treturn _sym_nothing;\n\t}\n\telse{\n\t\terror(\"This version of Jamoma requires Max 5\");\n\t\treturn _sym_nothing;\n\t}\n}\n\n\n\/\/ Don't pass memory in for this function! It will allocate what it needs\n\/\/ -- then the caller is responsible for freeing\nvoid jamoma_patcher_getargs(t_object *patcher, long *argc, t_atom **argv)\n{\n\tif(max5){\n\t\tt_symbol\t\t*context = jamoma_patcher_getcontext(patcher);\n\t\tt_object\t\t*box = object_attr_getobj(patcher, jps_box);\n\t\tt_object\t\t*textfield = NULL;\n\t\tchar\t\t\t*text = NULL;\n\t\tunsigned long\ttextlen = 0;\n\n\t\tif(context == gensym(\"bpatcher\"))\n\t\t\tobject_attr_getvalueof(box, gensym(\"args\"), argc, argv);\n\t\telse if(context == gensym(\"subpatcher\")){\n\t\t\ttextfield = object_attr_getobj(box, gensym(\"textfield\"));\n\t\t\tobject_method(textfield, gensym(\"gettextptr\"), &text, &textlen);\n\t\t\tatom_setparse(argc, argv, text);\n\t\t}\n\t\telse{\n\t\t\t*argc = 0;\n\t\t\t*argv = NULL;\n\t\t}\n\t}\n\telse{\n\t\terror(\"This version of Jamoma requires Max 5\");\n\t}\n}\n\n\nt_symbol* jamoma_patcher_getvarname(t_object *patcher)\n{\n\tif(max5){\n\t\treturn _sym_nothing;\n\t}\n\telse{\n\t\terror(\"This version of Jamoma requires Max 5\");\n\t\treturn _sym_nothing;\n\t}\n}\n\n\n\/\/ When the DSP is started, we make sure the Jamoma Clock and Scheduler \n\/\/ are updated if needed\nvoid jamoma_dsp(t_object *, t_signal **sp, short *count)\n{\n\t\/\/jamoma_clock_dsp(NULL, sp, count);\n}\n\n\n\/\/ This is the default attribute getter for Jamoma's core\n\/\/ It sends the data out not only the parameter dumpout, but also\n\/\/ out the feedback outlet from the module\n\/\/ for example:\n\/\/ \tjamoma_class_attr_new(c, \"ramp\/drive\", _sym_symbol, (method)param_setramp, \n\/\/\t\tcalcoffset(t_param, attr_ramp));\nvoid jamoma_class_attr_new(t_class *c, char *attrName, t_symbol *attrType, method setter, method getter)\n{\n\tt_object\t*attr = NULL;\n\tchar\t\tgetterName[256];\n\t\n\tstrcpy(getterName, attrName);\n\tstrcat(getterName, \"\/get\");\n\n\tattr = attr_offset_new(attrName, attrType, 0, getter, setter, NULL);\n\tclass_addattr(c, attr);\n\n\tclass_addmethod(c, (method)jamoma_class_attr_get, getterName, A_GIMME, 0);\n}\n\n\nvoid jamoma_class_attr_array_new(t_class *c, char *attrName, t_symbol *attrType, long list_size, method setter, method getter)\n{\n\tt_object\t*attr = NULL;\n\tchar\t\tgetterName[256];\n\t\n\tstrcpy(getterName, attrName);\n\tstrcat(getterName, \"\/get\");\n\n\tattr = attr_offset_array_new(attrName, _sym_atom, list_size, 0, getter, setter, NULL, NULL);\n\tclass_addattr(c, attr);\n\n\tclass_addmethod(c, (method)jamoma_class_attr_get, getterName, A_GIMME, 0);\n}\n\n\nvoid jamoma_class_attr_get(t_object *o, t_symbol *attrName, long, t_atom *)\n{\n\tchar\t\tcAttrName[256];\n\tt_symbol\t*sAttrName;\n\tchar\t\t*temp;\n\tlong\t\tac = 0;\n\tt_atom\t\t*av = NULL;\n\tt_jcom_core_subscriber_common *x = (t_jcom_core_subscriber_common*)o;\n\t\n\tstrcpy(cAttrName, attrName->s_name);\n\ttemp = strrchr(cAttrName, '\/');\n\tif(temp)\n\t\t*temp = 0;\n\tsAttrName = gensym(cAttrName);\n\n\tobject_attr_getvalueof(o, sAttrName, &ac, &av);\n\tobject_obex_dumpout(o, sAttrName, ac, av);\n\tif(x->hub != NULL){\n\t\tchar\t\ts[256];\n\t\tt_atom\t\ta[4];\n\t\n\t\tsnprintf(s, 256, \"%s:\/%s\", x->attr_name->s_name, attrName->s_name);\n\t\tatom_setsym(a+0, gensym(s));\n\t\tsysmem_copyptr(av, a+1, sizeof(t_atom) * ac);\n\t\tobject_method_typed(x->hub, jps_feedback, ac + 1, a, NULL);\n\t}\n\n\tif(ac)\n\t\tsysmem_freeptr(av);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <CoreFoundation\/CoreFoundation.h>\n\n#include \"SFBAudioEngine\/AudioDecoder.h\"\n#include \"SFBAudioEngine\/AudioMetadata.h\"\n#include \"SFBAudioEngine\/AudioPlayer.h\"\n#include \"SFBAudioEngine\/DSPAudioPlayer.h\"\n\n#include \"CAStreamBasicDescription.h\"\n\n#include <unistd.h>\n\n\nstatic CFArrayRef\nCreateOutputDeviceArray()\n{\n\tUInt32 specifierSize = 0;\n\tOSStatus status = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &specifierSize, NULL);\n\tif(kAudioHardwareNoError != status) {\n\t\tprintf(\"AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices) failed: %i\\n\", status);\n\t\treturn NULL;\n\t}\n\t\t\n\tUInt32 deviceCount = static_cast<UInt32>(specifierSize \/ sizeof(AudioDeviceID));\n\t\t\n\tAudioDeviceID *audioDevices = static_cast<AudioDeviceID *>(calloc(1, specifierSize));\n\tif(NULL == audioDevices) {\n\t\tputs(\"Unable to allocate memory\");\n\t\treturn NULL;\n\t}\n\t\n\tstatus = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &specifierSize, audioDevices);\n\tif(kAudioHardwareNoError != status) {\n\t\tprintf(\"AudioHardwareGetProperty (kAudioHardwarePropertyDevices) failed: %i\\n\", status);\n\t\tfree(audioDevices), audioDevices = NULL;\n\t\treturn NULL;\n\t}\n\t\n\tCFMutableArrayRef outputDeviceArray = CFArrayCreateMutable(kCFAllocatorDefault, deviceCount, &kCFTypeArrayCallBacks);\n\tif(NULL == outputDeviceArray) {\n\t\tputs(\"CFArrayCreateMutable failed\");\n\t\tfree(audioDevices), audioDevices = NULL;\n\t\treturn NULL;\n\t}\n\t\n\t\/\/ Iterate through all the devices and determine which are output-capable\n\tfor(UInt32 i = 0; i < deviceCount; ++i) {\n\t\t\/\/ Query device UID\n\t\tCFStringRef deviceUID = NULL;\n\t\tspecifierSize = sizeof(deviceUID);\n\t\tstatus = AudioDeviceGetProperty(audioDevices[i], 0, FALSE, kAudioDevicePropertyDeviceUID, &specifierSize, &deviceUID);\n\t\tif(kAudioHardwareNoError != status) {\n\t\t\tprintf(\"AudioDeviceGetProperty (kAudioDevicePropertyDeviceUID) failed: %i\\n\", status);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\/\/ Query device name\n\t\tCFStringRef deviceName = NULL;\n\t\tspecifierSize = sizeof(deviceName);\n\t\tstatus = AudioDeviceGetProperty(audioDevices[i], 0, FALSE, kAudioDevicePropertyDeviceNameCFString, &specifierSize, &deviceName);\n\t\tif(kAudioHardwareNoError != status) {\n\t\t\tprintf(\"AudioDeviceGetProperty (kAudioDevicePropertyDeviceNameCFString) failed: %i\\n\", status);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Query device manufacturer\n\t\tCFStringRef deviceManufacturer = NULL;\n\t\tspecifierSize = sizeof(deviceManufacturer);\n\t\tstatus = AudioDeviceGetProperty(audioDevices[i], 0, FALSE, kAudioDevicePropertyDeviceManufacturerCFString, &specifierSize, &deviceManufacturer);\n\t\tif(kAudioHardwareNoError != status) {\n\t\t\tprintf(\"AudioDeviceGetProperty (kAudioDevicePropertyDeviceManufacturerCFString) failed: %i\\n\", status);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\/\/ Determine if the device is an output device (it is an output device if it has output channels)\n\t\tspecifierSize = 0;\n\t\tstatus = AudioDeviceGetPropertyInfo(audioDevices[i], 0, FALSE, kAudioDevicePropertyStreamConfiguration, &specifierSize, NULL);\n\t\tif(kAudioHardwareNoError != status) {\n\t\t\tprintf(\"AudioDeviceGetPropertyInfo (kAudioDevicePropertyStreamConfiguration) failed: %i\\n\", status);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tAudioBufferList *bufferList = static_cast<AudioBufferList *>(calloc(1, specifierSize));\n\t\tif(NULL == bufferList) {\n\t\t\tputs(\"Unable to allocate memory\");\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tstatus = AudioDeviceGetProperty(audioDevices[i], 0, FALSE, kAudioDevicePropertyStreamConfiguration, &specifierSize, bufferList);\n\t\tif(kAudioHardwareNoError != status || 0 == bufferList->mNumberBuffers) {\n\t\t\tprintf(\"AudioDeviceGetProperty (kAudioDevicePropertyStreamConfiguration) failed: %i\\n\", status);\n\t\t\tfree(bufferList), bufferList = NULL;\n\t\t\tcontinue;\t\t\t\n\t\t}\n\t\t\n\t\tfree(bufferList), bufferList = NULL;\n\t\t\n\t\t\/\/ Add a dictionary for this device to the array of output devices\n\t\tCFStringRef keys\t[]\t= { CFSTR(\"deviceUID\"),\t\tCFSTR(\"deviceName\"),\tCFSTR(\"deviceManufacturer\") };\n\t\tCFStringRef values\t[]\t= { deviceUID,\t\t\t\tdeviceName,\t\t\t\tdeviceManufacturer };\n\t\t\n\t\tCFDictionaryRef deviceDictionary = CFDictionaryCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t reinterpret_cast<const void **>(keys), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t reinterpret_cast<const void **>(values), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 3,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\n\n\t\tCFArrayAppendValue(outputDeviceArray, deviceDictionary);\n\t}\n\t\n\tfree(audioDevices), audioDevices = NULL;\n\t\n\t\/\/ Return a non-mutable copy of the array\n\tCFArrayRef copy = CFArrayCreateCopy(kCFAllocatorDefault, outputDeviceArray);\n\tCFRelease(outputDeviceArray), outputDeviceArray = NULL;\n\t\n\treturn copy;\n}\n\nstatic void\nPrintStreamsForDeviceID(AudioDeviceID deviceID)\n{\n\tAudioObjectShow(deviceID);\n\t\n\tUInt32 mixable = 0xFFFF;\n\tUInt32 specifierSize = sizeof(mixable);\n\tOSStatus result = AudioDeviceGetProperty(deviceID, \n\t\t\t\t\t\t\t\t\t\t\t 0, \n\t\t\t\t\t\t\t\t\t\t\t FALSE, \n\t\t\t\t\t\t\t\t\t\t\t kAudioDevicePropertySupportsMixing, \n\t\t\t\t\t\t\t\t\t\t\t &specifierSize, \n\t\t\t\t\t\t\t\t\t\t\t &mixable);\n\t\n\tif(noErr != result)\n\t\tfprintf(stderr, \"AudioDeviceGetProperty (kAudioDevicePropertySupportsMixing) failed: %i\\n\", result);\n\t\n\tprintf(\"Device supports mixing: %s\\n\", mixable ? \"Yes\" : \"No\");\n\n\tresult = AudioDeviceGetPropertyInfo(deviceID, \n\t\t\t\t\t\t\t\t\t\t0, \n\t\t\t\t\t\t\t\t\t\tFALSE, \n\t\t\t\t\t\t\t\t\t\tkAudioDevicePropertyStreams, \n\t\t\t\t\t\t\t\t\t\t&specifierSize, \n\t\t\t\t\t\t\t\t\t\tNULL);\n\n\tif(noErr != result) {\n\t\tfprintf(stderr, \"AudioDeviceGetPropertyInfo (kAudioDevicePropertyStreams) failed: %i\\n\", result);\n\t\treturn;\n\t}\n\t\n\tUInt32 streamCount = static_cast<UInt32>(specifierSize \/ sizeof(AudioStreamID));\n\n\tAudioStreamID audioStreams [streamCount];\n\t\n\tresult = AudioDeviceGetProperty(deviceID, \n\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\tFALSE, \n\t\t\t\t\t\t\t\t\tkAudioDevicePropertyStreams,\n\t\t\t\t\t\t\t\t\t&specifierSize,\n\t\t\t\t\t\t\t\t\taudioStreams);\n\t\n\tif(noErr != result) {\n\t\tfprintf(stderr, \"AudioDeviceGetProperty (kAudioDevicePropertyStreams) failed: %i\\n\", result);\n\t\treturn;\n\t}\n\t\n\tprintf(\"\\nDevice has %d streams\\n\", streamCount);\n\t\n\tfor(UInt32 i = 0; i < streamCount; ++i) {\n\t\tAudioStreamID streamID = audioStreams[i];\n\t\t\n\t\tAudioObjectShow(streamID);\n\n\t\tresult = AudioStreamGetPropertyInfo(streamID, \n\t\t\t\t\t\t\t\t\t\t\t0, \n\t\t\t\t\t\t\t\t\t\t\tkAudioStreamPropertyAvailableVirtualFormats, \n\t\t\t\t\t\t\t\t\t\t\t&specifierSize, \n\t\t\t\t\t\t\t\t\t\t\tNULL);\n\n\t\tif(noErr != result) {\n\t\t\tfprintf(stderr, \"AudioStreamGetPropertyInfo (kAudioStreamPropertyAvailableVirtualFormats) failed: %i\\n\", result);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tUInt32 virtualFormatCount = static_cast<UInt32>(specifierSize \/ sizeof(AudioStreamRangedDescription));\n\n\t\tAudioStreamRangedDescription virtualFormats [virtualFormatCount];\n\t\t\n\t\tresult = AudioStreamGetProperty(streamID, \n\t\t\t\t\t\t\t\t\t\t0, \n\t\t\t\t\t\t\t\t\t\tkAudioStreamPropertyAvailableVirtualFormats,\n\t\t\t\t\t\t\t\t\t\t&specifierSize, \n\t\t\t\t\t\t\t\t\t\tvirtualFormats);\n\n\t\tif(noErr != result) {\n\t\t\tfprintf(stderr, \"AudioStreamGetProperty (kAudioStreamPropertyAvailableVirtualFormats) failed: %i\\n\", result);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tprintf(\"\\nAudioStream %x Virtual Formats:\\n\",streamID);\n\t\tfor(UInt32 j = 0; j < virtualFormatCount; ++j) {\n\t\t\tCAStreamBasicDescription sd = virtualFormats[j].mFormat;\n\t\t\tsd.Print(stdout);\n\t\t\tprintf(\"reserved: %i\\n\", sd.mReserved);\n\t\t}\n\n\t\tresult = AudioStreamGetPropertyInfo(streamID, \n\t\t\t\t\t\t\t\t\t\t\t0, \n\t\t\t\t\t\t\t\t\t\t\tkAudioStreamPropertyAvailablePhysicalFormats, \n\t\t\t\t\t\t\t\t\t\t\t&specifierSize, \n\t\t\t\t\t\t\t\t\t\t\tNULL);\n\t\t\n\t\tif(noErr != result) {\n\t\t\tfprintf(stderr, \"AudioStreamGetPropertyInfo (kAudioStreamPropertyAvailablePhysicalFormats) failed: %i\\n\", result);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tUInt32 physicalFormatCount = static_cast<UInt32>(specifierSize \/ sizeof(AudioStreamRangedDescription));\n\t\t\n\t\tAudioStreamRangedDescription physicalFormats [physicalFormatCount];\n\t\t\n\t\tresult = AudioStreamGetProperty(streamID, \n\t\t\t\t\t\t\t\t\t\t0, \n\t\t\t\t\t\t\t\t\t\tkAudioStreamPropertyAvailablePhysicalFormats, \n\t\t\t\t\t\t\t\t\t\t&specifierSize, \n\t\t\t\t\t\t\t\t\t\tphysicalFormats);\n\t\t\n\t\tif(noErr != result) {\n\t\t\tfprintf(stderr, \"AudioStreamGetProperty (kAudioStreamPropertyAvailablePhysicalFormats) failed: %i\\n\", result);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tprintf(\"\\nAudioStream %x Physical Formats:\\n\",streamID);\n\t\tfor(UInt32 j = 0; j < physicalFormatCount; ++j) {\n\t\t\tCAStreamBasicDescription sd = physicalFormats[j].mFormat;\n\t\t\tsd.Print(stdout);\n\t\t}\n\t}\n}\n\nstatic void\nPrintStreamsForDeviceUID(CFStringRef deviceUID)\n{\n\tassert(NULL != deviceUID);\n\t\n\tAudioDeviceID deviceID = kAudioDeviceUnknown;\n\tAudioValueTranslation translation;\n\t\n\ttranslation.mInputData\t\t\t= &deviceUID;\n\ttranslation.mInputDataSize\t\t= sizeof(deviceUID);\n\ttranslation.mOutputData\t\t\t= &deviceID;\n\ttranslation.mOutputDataSize\t\t= sizeof(deviceID);\n\t\n\tUInt32 specifierSize\t\t\t= sizeof(translation);\n\t\n\tOSStatus result = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, \n\t\t\t\t\t\t\t\t\t\t\t &specifierSize, \n\t\t\t\t\t\t\t\t\t\t\t &translation);\n\t\n\tif(noErr != result) {\n\t\tfprintf(stderr, \"AudioHardwareGetProperty (kAudioHardwarePropertyDeviceForUID) failed: %i\", result);\n\t\treturn;\n\t}\n\t\n\tPrintStreamsForDeviceID(deviceID);\n}\n\nstatic void\nPrintStreamFormatsForDeviceID(AudioDeviceID deviceID)\n{\n\tOSStatus result;\n\tUInt32 specifierSize;\n\t\n\tresult = AudioDeviceGetPropertyInfo(deviceID, \n\t\t\t\t\t\t\t\t\t\t0, \n\t\t\t\t\t\t\t\t\t\tFALSE, \n\t\t\t\t\t\t\t\t\t\tkAudioDevicePropertyStreams, \n\t\t\t\t\t\t\t\t\t\t&specifierSize, \n\t\t\t\t\t\t\t\t\t\tNULL);\n\t\n\tif(noErr != result) {\n\t\tfprintf(stderr, \"AudioDeviceGetPropertyInfo (kAudioDevicePropertyStreams) failed: %i\\n\", result);\n\t\treturn;\n\t}\n\t\n\tUInt32 streamCount = static_cast<UInt32>(specifierSize \/ sizeof(AudioStreamID));\n\t\n\tAudioStreamID audioStreams [streamCount];\n\t\n\tresult = AudioDeviceGetProperty(deviceID, \n\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\tFALSE, \n\t\t\t\t\t\t\t\t\tkAudioDevicePropertyStreams,\n\t\t\t\t\t\t\t\t\t&specifierSize,\n\t\t\t\t\t\t\t\t\taudioStreams);\n\t\n\tif(noErr != result) {\n\t\tfprintf(stderr, \"AudioDeviceGetProperty (kAudioDevicePropertyStreams) failed: %i\\n\", result);\n\t\treturn;\n\t}\n\t\t\n\tfor(UInt32 i = 0; i < streamCount; ++i) {\n\t\tAudioStreamID streamID = audioStreams[i];\n\t\t\n\t\tCAStreamBasicDescription virtualFormat;\n\t\tspecifierSize = sizeof(virtualFormat);\n\t\t\n\t\tresult = AudioStreamGetProperty(streamID, \n\t\t\t\t\t\t\t\t\t\t0, \n\t\t\t\t\t\t\t\t\t\tkAudioStreamPropertyVirtualFormat,\n\t\t\t\t\t\t\t\t\t\t&specifierSize, \n\t\t\t\t\t\t\t\t\t\t&virtualFormat);\n\t\t\n\t\tif(noErr != result) {\n\t\t\tfprintf(stderr, \"AudioStreamGetProperty (kAudioStreamPropertyVirtualFormat) failed: %i\\n\", result);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tprintf(\"Current virtual format: \");\n\t\tvirtualFormat.Print(stdout);\n\t\t\n\t\tCAStreamBasicDescription physicalFormat;\n\t\tspecifierSize = sizeof(physicalFormat);\n\t\t\n\t\tresult = AudioStreamGetProperty(streamID, \n\t\t\t\t\t\t\t\t\t\t0, \n\t\t\t\t\t\t\t\t\t\tkAudioStreamPropertyPhysicalFormat,\n\t\t\t\t\t\t\t\t\t\t&specifierSize, \n\t\t\t\t\t\t\t\t\t\t&physicalFormat);\n\t\t\n\t\tif(noErr != result) {\n\t\t\tfprintf(stderr, \"AudioStreamGetProperty (kAudioStreamPropertyPhysicalFormat) failed: %i\\n\", result);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tprintf(\"Current physical format: \");\n\t\tphysicalFormat.Print(stdout);\t\t\n\t}\n}\n\nstatic void\nPrintStreamFormatsForDeviceUID(CFStringRef deviceUID)\n{\n\tassert(NULL != deviceUID);\n\t\n\tAudioDeviceID deviceID = kAudioDeviceUnknown;\n\tAudioValueTranslation translation;\n\t\n\ttranslation.mInputData\t\t\t= &deviceUID;\n\ttranslation.mInputDataSize\t\t= sizeof(deviceUID);\n\ttranslation.mOutputData\t\t\t= &deviceID;\n\ttranslation.mOutputDataSize\t\t= sizeof(deviceID);\n\t\n\tUInt32 specifierSize\t\t\t= sizeof(translation);\n\t\n\tOSStatus result = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, \n\t\t\t\t\t\t\t\t\t\t\t &specifierSize, \n\t\t\t\t\t\t\t\t\t\t\t &translation);\n\t\n\tif(noErr != result) {\n\t\tfprintf(stderr, \"AudioHardwareGetProperty (kAudioHardwarePropertyDeviceForUID) failed: %i\", result);\n\t\treturn;\n\t}\n\t\n\tPrintStreamFormatsForDeviceID(deviceID);\n}\n\nstatic void\ndecodingStarted(void\t\t\t\t\t*context,\n\t\t\t\tconst AudioDecoder\t\t*decoder)\n{\n#pragma unused(context)\n\tprintf(\"Decoding started: \");\n\tCFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));\n}\n\nstatic void\ndecodingFinished(void\t\t\t\t\t*context,\n\t\t\t\t const AudioDecoder\t\t*decoder)\n{\n#pragma unused(context)\n\tprintf(\"Decoding finished: \");\n\tCFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));\n}\n\nstatic void\nrenderingStarted(void\t\t\t\t\t*context,\n\t\t\t\t const AudioDecoder\t\t*decoder)\n{\n#pragma unused(context)\n\tprintf(\"Rendering started: \");\n\tCFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));\n}\n\nstatic void\nrenderingFinished(void\t\t\t\t\t*context,\n\t\t\t\t const AudioDecoder\t\t*decoder)\n{\n#pragma unused(context)\n\tprintf(\"Rendering finished: \");\n\tCFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));\n}\n\nstatic void usage(const char *argv0)\n{\n\tassert(NULL != argv0);\n\t\n\tfprintf(stderr, \"Usage: %s file [file ...]\", argv0);\n}\n\n\/\/#include <getopt.h>\n\/\/\n\/\/\/* Flag set by ‘--verbose’. *\/\n\/\/static int verbose_flag;\n\/\/\n\/\/static struct option long_options [] = {\n\/\/\t\/* These options set a flag. *\/\n\/\/\t{\"verbose\", no_argument, &verbose_flag, 1},\n\/\/\t{\"brief\", no_argument, &verbose_flag, 0},\n\/\/\t\/* These options don't set a flag.\n\/\/\t We distinguish them by their indices. *\/\n\/\/\t{\"add\", no_argument, 0, 'a'},\n\/\/\t{\"append\", no_argument, 0, 'b'},\n\/\/\t{\"delete\", required_argument, 0, 'd'},\n\/\/\t{\"create\", required_argument, 0, 'c'},\n\/\/\t{\"file\", required_argument, 0, 'f'},\n\/\/\t{0, 0, 0, 0}\n\/\/};\n\nint main(int argc, char *argv [])\n{\n\/\/\tfor(;;) {\n\/\/\t\t\/* getopt_long stores the option index here. *\/\n\/\/\t\tint option_index = 0;\n\/\/\t\t\n\/\/\t\tint c = getopt_long(argc, \n\/\/\t\t\t\t\t\t\targv, \n\/\/\t\t\t\t\t\t\t\"abc:d:f:\",\n\/\/\t\t\t\t\t\t\tlong_options, \n\/\/\t\t\t\t\t\t\t&option_index);\n\/\/\t\t\n\/\/\t\t\/* Detect the end of the options. *\/\n\/\/\t\tif (c == -1)\n\/\/\t\t\tbreak;\n\/\/\t\t\n\/\/\t\tswitch(c) {\n\/\/\t\t\tcase 0:\n\/\/\t\t\t\t\/* If this option set a flag, do nothing else now. *\/\n\/\/\t\t\t\tif(long_options[option_index].flag != 0)\n\/\/\t\t\t\t\tbreak;\n\/\/\t\t\t\tprintf(\"option %s\", long_options[option_index].name);\n\/\/\t\t\t\tif(optarg)\n\/\/\t\t\t\t\tprintf (\" with arg %s\", optarg);\n\/\/\t\t\t\tprintf (\"\\n\");\n\/\/\t\t\t\tbreak;\n\/\/\t\t\t\t\n\/\/\t\t\tcase 'a':\n\/\/\t\t\t\tputs(\"option -a\\n\");\n\/\/\t\t\t\tbreak;\n\/\/\t\t\t\t\n\/\/\t\t\tcase 'b':\n\/\/\t\t\t\tputs(\"option -b\\n\");\n\/\/\t\t\t\tbreak;\n\/\/\t\t\t\t\n\/\/\t\t\tcase 'c':\n\/\/\t\t\t\tprintf(\"option -c with value `%s'\\n\", optarg);\n\/\/\t\t\t\tbreak;\n\/\/\t\t\t\t\n\/\/\t\t\tcase 'd':\n\/\/\t\t\t\tprintf(\"option -d with value `%s'\\n\", optarg);\n\/\/\t\t\t\tbreak;\n\/\/\t\t\t\t\n\/\/\t\t\tcase 'f':\n\/\/\t\t\t\tprintf(\"option -f with value `%s'\\n\", optarg);\n\/\/\t\t\t\tbreak;\n\/\/\t\t\t\t\n\/\/\t\t\tcase '?':\n\/\/\t\t\t\t\/* getopt_long already printed an error message. *\/\n\/\/\t\t\t\tbreak;\n\/\/\t\t\t\t\n\/\/\t\t\tdefault:\n\/\/\t\t\t\tabort();\n\/\/\t\t}\n\/\/\t}\n\/\/\t\n\/\/\t\/* Instead of reporting ‘--verbose’\n\/\/\t and ‘--brief’ as they are encountered,\n\/\/\t we report the final status resulting from them. *\/\n\/\/\tif(verbose_flag)\n\/\/\t\tputs(\"verbose flag is set\");\n\/\/\t\n\/\/\t\/* Print any remaining command line arguments (not options). *\/\n\/\/\tif(optind < argc) {\n\/\/\t\tprintf(\"non-option ARGV-elements: \");\n\/\/\t\twhile(optind < argc)\n\/\/\t\t\tprintf (\"%s \", argv[optind++]);\n\/\/\t\tputchar('\\n');\n\/\/\t}\n\/\/ \n\/\/\treturn EXIT_SUCCESS;\n\/\/\t\n\/\/\t\n\t\n\tif(1 == argc) {\n\t\tprintf(\"Usage: %s file [file ...]\", argv[0]);\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\/\/\tCFArrayRef outputDevices = CreateOutputDeviceArray();\n\/\/\tCFShow(outputDevices);\n\/\/\tCFRelease(outputDevices), outputDevices = NULL;\n\/\/\treturn 1;\n\tAudioPlayer player;\n\t\n\tFloat32 volume;\n\tif(player.GetMasterVolume(volume))\n\t\tprintf(\"Master Volume: %f\\n\", volume);\n\n\tif(player.GetVolumeForChannel(1, volume))\n\t\tprintf(\"Channel 1 Volume: %f\\n\", volume);\n\t\n\/\/\tif(false == player.SetOutputDeviceUID(CFSTR(\"SoundflowerEngine:0\")))\n\tif(false == player.SetOutputDeviceUID(CFSTR(\"AppleUSBAudioEngine:Wavelength Audio,ltd:Proton USBDAC:(C) 2009 Wavelength Audio, ltd.:1\")))\n\/\/\tif(false == player.SetOutputDeviceUID(CFSTR(\"AppleUSBAudioEngine:Texas Instruments:Benchmark 1.0:fd111000:1\")))\n\t\tputs(\"Couldn't set output device UID\");\n\n\tif(false == player.StartHoggingOutputDevice())\n\t\tputs(\"Couldn't hog output device\");\n\n\tCAStreamBasicDescription asbd, oldFormat, vFormat;\n\n\tputs(\"====================\");\n\t\n\tif(player.GetOutputStreamPhysicalFormat(oldFormat)) {\n\t\tprintf(\"Original physical format: \");\n\t\toldFormat.Print(stdout);\n\t}\n\t\n\tif(player.GetOutputStreamVirtualFormat(vFormat)) {\n\t\tprintf(\"Original virtual format: \");\n\t\tvFormat.Print(stdout);\n\t}\n\t\n\tputs(\"====================\");\n\n\tasbd.mFormatID\t\t\t= kAudioFormatLinearPCM;\n\tasbd.mFormatFlags\t\t= kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonMixable;\n\tasbd.mBitsPerChannel\t= 24;\n\tasbd.mChannelsPerFrame\t= 2;\n\tasbd.mSampleRate\t\t= 44100;\n\tasbd.mFramesPerPacket\t= 1;\n\tasbd.mBytesPerFrame\t\t= 6;\n\tasbd.mBytesPerPacket\t= 6;\n\tasbd.mReserved\t\t\t= 0;\n\t\n\tif(false == player.SetOutputStreamPhysicalFormat(asbd))\n\t\tputs(\"Couldn't set physical format\");\n\/\/\telse\n\/\/\t\tasbd.Print(stderr);\n\n\twhile(0 < --argc) {\n\t\t\n\t\tconst char *path = *++argv;\n\n\t\tCFURLRef fileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(path), strlen(path), FALSE);\n\n\t\tAudioMetadata *metadata = AudioMetadata::CreateMetadataForURL(fileURL);\n\t\tif(NULL == metadata)\n\t\t\tputs(\"Couldn't create metadata\");\n\t\t\n\/\/\t\t13:33:52 - 17:21:06\n\/\/\t\tAudioDecoder *decoder = AudioDecoder::CreateDecoderForURLRegion(fileURL,\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstatic_cast<SInt64>(44100*((13*60) + 33 + (52.\/75))), \n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstatic_cast<UInt32>(44100*(3*60 + 47 + (14.\/75))),\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\n\t\tAudioDecoder *decoder = AudioDecoder::CreateDecoderForURL(fileURL);\n\t\tif(NULL == decoder) {\n\t\t\tputs(\"Couldn't create decoder\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tdecoder->SetDecodingStartedCallback(decodingStarted, NULL);\n\t\tdecoder->SetDecodingFinishedCallback(decodingFinished, NULL);\n\t\tdecoder->SetRenderingStartedCallback(renderingStarted, NULL);\n\t\tdecoder->SetRenderingFinishedCallback(renderingFinished, NULL);\n\t\t\n\t\tif(false == player.Enqueue(decoder))\n\t\t\tputs(\"Couldn't enqueue\");\n\t}\n\n\tplayer.Play();\n\n\twhile(player.IsPlaying() && 30 > player.GetCurrentTime()) {\n\t\tCFRunLoopRunInMode(kCFRunLoopDefaultMode, 2, true);\n\n\t\tprintf(\"%.2f \/ %.2f [%.2f]\\n\", player.GetCurrentTime(), player.GetTotalTime(), player.GetRemainingTime());\n\t}\n\t\n\tplayer.Stop();\n\n\t\/\/ Restore the old format\n\tif(false == player.SetOutputStreamPhysicalFormat(oldFormat))\n\t\tputs(\"Couldn't restore physical format\");\n\t\n\tif(false == player.StopHoggingOutputDevice())\n\t\tputs(\"Couldn't stop hogging output device\");\n\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>Turned Example into a bare-bones command line player<commit_after>\/*\n * Copyright (C) 2009, 2010 Stephen F. Booth <me@sbooth.org>\n * All Rights Reserved\n *\/\n\n#include <CoreFoundation\/CoreFoundation.h>\n\n#include \"SFBAudioEngine\/AudioDecoder.h\"\n#include \"SFBAudioEngine\/AudioPlayer.h\"\n#include \"SFBAudioEngine\/DSPAudioPlayer.h\"\n\n#include <unistd.h>\n\n\nstatic void\ndecodingStarted(void\t\t\t\t\t*context,\n\t\t\t\tconst AudioDecoder\t\t*decoder)\n{\n#pragma unused(context)\n\tprintf(\"Decoding started: \");\n\tCFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));\n}\n\nstatic void\ndecodingFinished(void\t\t\t\t\t*context,\n\t\t\t\t const AudioDecoder\t\t*decoder)\n{\n#pragma unused(context)\n\tprintf(\"Decoding finished: \");\n\tCFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));\n}\n\nstatic void\nrenderingStarted(void\t\t\t\t\t*context,\n\t\t\t\t const AudioDecoder\t\t*decoder)\n{\n#pragma unused(context)\n\tprintf(\"Rendering started: \");\n\tCFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));\n}\n\nstatic void\nrenderingFinished(void\t\t\t\t\t*context,\n\t\t\t\t const AudioDecoder\t\t*decoder)\n{\n#pragma unused(context)\n\tprintf(\"Rendering finished: \");\n\tCFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));\n}\n\n\nint main(int argc, char *argv [])\n{\n\tif(1 == argc) {\n\t\tprintf(\"Usage: %s file [file ...]\", argv[0]);\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\tAudioPlayer player;\n\t\n\twhile(0 < --argc) {\n\t\tconst char *path = *++argv;\n\t\tCFURLRef fileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t reinterpret_cast<const UInt8 *>(path), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t strlen(path), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t FALSE);\n\n\t\tAudioDecoder *decoder = AudioDecoder::CreateDecoderForURL(fileURL);\n\n\t\tCFRelease(fileURL), fileURL = NULL;\n\t\t\n\t\tif(NULL == decoder) {\n\t\t\tputs(\"Couldn't create decoder\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tdecoder->SetDecodingStartedCallback(decodingStarted, NULL);\n\t\tdecoder->SetDecodingFinishedCallback(decodingFinished, NULL);\n\t\tdecoder->SetRenderingStartedCallback(renderingStarted, NULL);\n\t\tdecoder->SetRenderingFinishedCallback(renderingFinished, NULL);\n\t\t\n\t\tif(false == player.Enqueue(decoder)) {\n\t\t\tputs(\"Couldn't enqueue decoder\");\n\t\t\tdelete decoder, decoder = NULL;\n\t\t}\n\t}\n\n\tplayer.Play();\n\n\t\/\/ Display progress every 2 seconds\n\twhile(player.IsPlaying()) {\n\t\tCFRunLoopRunInMode(kCFRunLoopDefaultMode, 2, true);\n\n\t\tprintf(\"%.2f \/ %.2f [%.2f]\\n\", player.GetCurrentTime(), player.GetTotalTime(), player.GetRemainingTime());\n\t}\n\t\n\tplayer.Stop();\n\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>cid#983376 Dereference before null check<commit_after><|endoftext|>"} {"text":"<commit_before>#include <stdexcept>\n#include <string>\n\n#include <ros\/ros.h>\n#include <actionlib\/client\/simple_action_client.h>\n#include <geometry_msgs\/Point.h>\n#include <geometry_msgs\/TransformStamped.h>\n#include <goal_sender_msgs\/ApplyGoals.h>\n#include <goal_sender_msgs\/GoalSequence.h>\n#include <move_base_msgs\/MoveBaseAction.h>\n#include <move_base_msgs\/MoveBaseGoal.h>\n#include <tf2_geometry_msgs\/tf2_geometry_msgs.h>\n#include <tf2_ros\/transform_listener.h>\n\ninline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {\n const auto x {a.x - b.x};\n const auto y {a.y - b.y};\n return x*x + y*y;\n}\n\n\/**\n * Waypoint update service manager\n *\/\nclass WaypointManager\n{\npublic:\n bool operator()(goal_sender_msgs::ApplyGoals::Request& req,\n goal_sender_msgs::ApplyGoals::Response& res){\n sequence_ = req.goal_sequence;\n res.success = true;\n res.message = \"update waypoints\";\n return true;\n }\n\n const geometry_msgs::Point& point() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before point()\"};\n return now_goal->position;\n }\n\n const geometry_msgs::Quaternion& quaternion() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before radius()\"};\n return now_goal->oriantation;\n }\n\n double radius() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before radius()\"};\n return now_goal->radius;\n }\n\n bool next()\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before next()\"}; \/\/ wrong way.\n if (++now_goal == sequence_.waypoints.end())\n return false; \/\/ correct way: this is last one.\n return true;\n }\n\n bool is_end() const noexcept\n {\n return sequence_.waypoints.end() == now_goal;\n }\n\n explicit operator bool() noexcept\n {\n return !is_end();\n }\n\n [[deprecated]]\n const goal_sender_msgs::Waypoint& get() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before get()\"};\n return *now_goal;\n }\n\nprivate:\n goal_sender_msgs::GoalSequence sequence_;\n decltype(sequence_.waypoints)::iterator now_goal;\n};\n\n\/**\n * Tf lookup API\n *\/\nclass TfPositionManager\n{\npublic:\n explicit TfPositionManager(tf2_ros::Buffer& tfBuffer) \/\/ buffer is lvalue\n : buffer_ {tfBuffer}\n {\n }\n\n geometry_msgs::Point operator()(std::string parent, std::string child) const\n {\n const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};\n geometry_msgs::Point point;\n point.x = ts.transform.translation.x;\n point.y = ts.transform.translation.y;\n return point;\n }\n\nprivate:\n const tf2_ros::Buffer& buffer_;\n};\n\nclass GoalSender\n{\npublic:\n using MoveBaseActionClient = actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>;\n\n GoalSender(WaypointManager& point_manager,\n MoveBaseActionClient& move_base_client,\n TfPositionManager lookupper)\n : point_manager_ {point_manager},\n move_base_client_ {move_base_client},\n lookupper_ {lookupper}\n {\n }\n\n void once()\n {\n if (!point_manager_)\n return; \/\/ no work\n if (is_reach()) {\n point_manager_.next();\n send_goal();\n }\n }\n\nprivate:\n bool is_reach() const\n {\n const auto robot_point {lookupper_(\"\/map\", \"\/base_link\")};\n const auto waypoint_point {point_manager_.point()};\n const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};\n\n const auto radius {point_manager_.radius()};\n const auto sqr_radius {radius * radius};\n\n if (sqr_distance < sqr_radius) \/\/ into valid range\n return true;\n return false;\n }\n\n void send_goal() const\n {\n if (!point_manager_) { \/\/ finish waypoint\n move_base_client_.cancelGoal(); \/\/ cancel moveing\n ROS_INFO(\"Finish waypoints\");\n return;\n }\n\n move_base_msgs::MoveBaseGoal goal;\n goal.target_pose.pose.position = point_manager_.point();\n goal.target_pose.pose.orientation = point_manager_.quaternion();\n goal.target_pose.header.frame_id = \"\/map\";\n goal.target_pose.header.stamp = ros::Time::now();\n move_base_client_.sendGoal(goal); \/\/ send waypoint\n }\n\n WaypointManager& point_manager_;\n MoveBaseActionClient& move_base_client_;\n TfPositionManager lookupper_;\n};\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"goal_sender\");\n ros::NodeHandle nh {};\n\n WaypointManager point_manager {};\n ros::ServiceServer srv {\n nh.advertiseService<goal_sender_msgs::ApplyGoals::Request,\n goal_sender_msgs::ApplyGoals::Response>(\n \"apply_goals\", point_manager)};\n\n tf2_ros::Buffer tfBuffer;\n tf2_ros::TransformListener tfListener {tfBuffer};\n TfPositionManager lookupper {tfBuffer};\n\n GoalSender::MoveBaseActionClient move_base_client {\"move_base\", true};\n move_base_client.waitForServer();\n\n GoalSender goal_sender {point_manager, move_base_client, lookupper};\n\n ros::Rate rate {10};\n while (ros::ok()) {\n ros::spinOnce();\n goal_sender.once();\n }\n}\n<commit_msg>Fix typo on error message<commit_after>#include <stdexcept>\n#include <string>\n\n#include <ros\/ros.h>\n#include <actionlib\/client\/simple_action_client.h>\n#include <geometry_msgs\/Point.h>\n#include <geometry_msgs\/TransformStamped.h>\n#include <goal_sender_msgs\/ApplyGoals.h>\n#include <goal_sender_msgs\/GoalSequence.h>\n#include <move_base_msgs\/MoveBaseAction.h>\n#include <move_base_msgs\/MoveBaseGoal.h>\n#include <tf2_geometry_msgs\/tf2_geometry_msgs.h>\n#include <tf2_ros\/transform_listener.h>\n\ninline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {\n const auto x {a.x - b.x};\n const auto y {a.y - b.y};\n return x*x + y*y;\n}\n\n\/**\n * Waypoint update service manager\n *\/\nclass WaypointManager\n{\npublic:\n bool operator()(goal_sender_msgs::ApplyGoals::Request& req,\n goal_sender_msgs::ApplyGoals::Response& res){\n sequence_ = req.goal_sequence;\n res.success = true;\n res.message = \"update waypoints\";\n return true;\n }\n\n const geometry_msgs::Point& point() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before point()\"};\n return now_goal->position;\n }\n\n const geometry_msgs::Quaternion& quaternion() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before quaternion()\"};\n return now_goal->oriantation;\n }\n\n double radius() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before radius()\"};\n return now_goal->radius;\n }\n\n bool next()\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before next()\"}; \/\/ wrong way.\n if (++now_goal == sequence_.waypoints.end())\n return false; \/\/ correct way: this is last one.\n return true;\n }\n\n bool is_end() const noexcept\n {\n return sequence_.waypoints.end() == now_goal;\n }\n\n explicit operator bool() noexcept\n {\n return !is_end();\n }\n\n [[deprecated]]\n const goal_sender_msgs::Waypoint& get() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before get()\"};\n return *now_goal;\n }\n\nprivate:\n goal_sender_msgs::GoalSequence sequence_;\n decltype(sequence_.waypoints)::iterator now_goal;\n};\n\n\/**\n * Tf lookup API\n *\/\nclass TfPositionManager\n{\npublic:\n explicit TfPositionManager(tf2_ros::Buffer& tfBuffer) \/\/ buffer is lvalue\n : buffer_ {tfBuffer}\n {\n }\n\n geometry_msgs::Point operator()(std::string parent, std::string child) const\n {\n const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};\n geometry_msgs::Point point;\n point.x = ts.transform.translation.x;\n point.y = ts.transform.translation.y;\n return point;\n }\n\nprivate:\n const tf2_ros::Buffer& buffer_;\n};\n\nclass GoalSender\n{\npublic:\n using MoveBaseActionClient = actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>;\n\n GoalSender(WaypointManager& point_manager,\n MoveBaseActionClient& move_base_client,\n TfPositionManager lookupper)\n : point_manager_ {point_manager},\n move_base_client_ {move_base_client},\n lookupper_ {lookupper}\n {\n }\n\n void once()\n {\n if (!point_manager_)\n return; \/\/ no work\n if (is_reach()) {\n point_manager_.next();\n send_goal();\n }\n }\n\nprivate:\n bool is_reach() const\n {\n const auto robot_point {lookupper_(\"\/map\", \"\/base_link\")};\n const auto waypoint_point {point_manager_.point()};\n const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};\n\n const auto radius {point_manager_.radius()};\n const auto sqr_radius {radius * radius};\n\n if (sqr_distance < sqr_radius) \/\/ into valid range\n return true;\n return false;\n }\n\n void send_goal() const\n {\n if (!point_manager_) { \/\/ finish waypoint\n move_base_client_.cancelGoal(); \/\/ cancel moveing\n ROS_INFO(\"Finish waypoints\");\n return;\n }\n\n move_base_msgs::MoveBaseGoal goal;\n goal.target_pose.pose.position = point_manager_.point();\n goal.target_pose.pose.orientation = point_manager_.quaternion();\n goal.target_pose.header.frame_id = \"\/map\";\n goal.target_pose.header.stamp = ros::Time::now();\n move_base_client_.sendGoal(goal); \/\/ send waypoint\n }\n\n WaypointManager& point_manager_;\n MoveBaseActionClient& move_base_client_;\n TfPositionManager lookupper_;\n};\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"goal_sender\");\n ros::NodeHandle nh {};\n\n WaypointManager point_manager {};\n ros::ServiceServer srv {\n nh.advertiseService<goal_sender_msgs::ApplyGoals::Request,\n goal_sender_msgs::ApplyGoals::Response>(\n \"apply_goals\", point_manager)};\n\n tf2_ros::Buffer tfBuffer;\n tf2_ros::TransformListener tfListener {tfBuffer};\n TfPositionManager lookupper {tfBuffer};\n\n GoalSender::MoveBaseActionClient move_base_client {\"move_base\", true};\n move_base_client.waitForServer();\n\n GoalSender goal_sender {point_manager, move_base_client, lookupper};\n\n ros::Rate rate {10};\n while (ros::ok()) {\n ros::spinOnce();\n goal_sender.once();\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix my wrong logic in row info iteration.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>also ifCOUNT2 return type is always number<commit_after><|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkImageIOBaseTest.cxx\n Language: C++\n Date: $Date$xgoto-l\n\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n#include \"itkImageIOBase.h\"\n#include \"itkMetaImageIO.h\"\n\nint itkImageIOBaseTest(int ac, char* av[])\n{\n typedef itk::ImageIOBase BaseReaderType;\n typedef BaseReaderType BaseReaderPointerType;\n\n typedef itk::MetaImageIO ReaderType;\n typedef ReaderType::Pointer ReaderPointerType;\n\n itk::MetaImageIO::Pointer reader = itk::MetaImageIO::New();\n reader->SetNumberOfDimensions(3);\n\n bool gotException = false;\n try \n {\n reader->SetDimensions(3,1.0);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetDimensions\"\n << std::endl;\n return EXIT_FAILURE;\n }\n \n gotException = false;\n try \n {\n reader->SetOrigin(3,1.0);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetOrigin\"\n << std::endl;\n return EXIT_FAILURE;\n }\n\n gotException = false;\n try \n {\n reader->SetSpacing(3,1.0);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetSpacing\"\n << std::endl;\n return EXIT_FAILURE;\n }\n\n gotException = false;\n try \n {\n std::vector<double> direction(3);\n direction[0] = 1.0;\n direction[1] = 1.0;\n direction[2] = 1.0;\n reader->SetDirection(3,direction);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetDirection\"\n << std::endl;\n return EXIT_FAILURE;\n }\n\n gotException = false;\n try \n {\n vnl_vector<double> direction(3);\n direction[0] = 1.0;\n direction[1] = 1.0;\n direction[2] = 1.0;\n reader->SetDirection(3,direction);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetDirection\"\n << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n<commit_msg>COMP: Removing unused parameters from the arguments of the main() function.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkImageIOBaseTest.cxx\n Language: C++\n Date: $Date$xgoto-l\n\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n#include \"itkImageIOBase.h\"\n#include \"itkMetaImageIO.h\"\n\nint itkImageIOBaseTest( int , char * [] )\n{\n typedef itk::ImageIOBase BaseReaderType;\n typedef BaseReaderType BaseReaderPointerType;\n\n typedef itk::MetaImageIO ReaderType;\n typedef ReaderType::Pointer ReaderPointerType;\n\n itk::MetaImageIO::Pointer reader = itk::MetaImageIO::New();\n reader->SetNumberOfDimensions(3);\n\n bool gotException = false;\n try \n {\n reader->SetDimensions(3,1.0);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetDimensions\"\n << std::endl;\n return EXIT_FAILURE;\n }\n \n gotException = false;\n try \n {\n reader->SetOrigin(3,1.0);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetOrigin\"\n << std::endl;\n return EXIT_FAILURE;\n }\n\n gotException = false;\n try \n {\n reader->SetSpacing(3,1.0);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetSpacing\"\n << std::endl;\n return EXIT_FAILURE;\n }\n\n gotException = false;\n try \n {\n std::vector<double> direction(3);\n direction[0] = 1.0;\n direction[1] = 1.0;\n direction[2] = 1.0;\n reader->SetDirection(3,direction);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetDirection\"\n << std::endl;\n return EXIT_FAILURE;\n }\n\n gotException = false;\n try \n {\n vnl_vector<double> direction(3);\n direction[0] = 1.0;\n direction[1] = 1.0;\n direction[2] = 1.0;\n reader->SetDirection(3,direction);\n }\n catch ( itk::ExceptionObject& e )\n {\n std::cerr << \"Caught expected exception \" << e << std::endl;\n gotException = true;\n }\n if (!gotException)\n {\n std::cerr << \"Failed to catch expected exception in method SetDirection\"\n << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"FPSRoleLocal.h\"\n#include \"Creature.h\"\n\nCFPSRoleLocal::CFPSRoleLocal(void)\n{\n\tm_nCharMode = 0;\n\tm_nMuzzleBone = -1;\n\tm_nUpdateMove = 0;\n}\n\nCFPSRoleLocal::~CFPSRoleLocal(void)\n{\n\tdelete m_pActorBase;\n}\n\nCFPSRoleLocal::CFPSRoleLocal(void)\n{\n\tm_nCharMode = 0;\n\tm_nMuzzleBone = -1;\n\tm_nUpdateMove = 0;\n}\n\n\nint CFPSRoleLocal::Init(int nRoleID,const char* strCharFile)\n{\n\tCFPSRole::Init(nRoleID, strCharFile);\n\n\tm_pCreature->SetupBody(1, 1);\n\n\n\treturn 1;\n}\n<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include \"FPSRoleLocal.h\"\n#include \"Creature.h\"\n\nCFPSRoleLocal::CFPSRoleLocal(void)\n{\n\tm_nCharMode = 0;\n\tm_nMuzzleBone = -1;\n\tm_nUpdateMove = 0;\n}\n\nCFPSRoleLocal::~CFPSRoleLocal(void)\n{\n\tdelete m_pActorBase;\n}\n\nCFPSRoleLocal::CFPSRoleLocal(void)\n{\n\tm_nCharMode = 0;\n\tm_nMuzzleBone = -1;\n\tm_nUpdateMove = 0;\n}\n\n\nint CFPSRoleLocal::Init(int nRoleID,const char* strCharFile)\n{\n\tCFPSRole::Init(nRoleID, strCharFile);\n\n\tm_pCreature->SetupBody(1, 1);\n\n\tm_pCreature->SetHighShadow(1);\n\tSetupArms(2, 0);\n\n\tm_pActorBase = new CActorBase();\n\tm_pActorBase->SetEnabled(1);\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ NAME\n\/\/ FeatureAlign.cpp -- image registration using feature matching\n\/\/\n\/\/ SEE ALSO\n\/\/ FeatureAlign.h longer description\n\/\/\n\/\/ Based on code by Richard Szeliski, 2001.\n\/\/ (modified for CSE576 Spring 2005, and for CS4670, Fall 2012-2013)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ImageLib\/ImageLib.h\"\n#include \"FeatureAlign.h\"\n#include \"SVD.h\"\n\n#include <math.h>\n#include <iostream>\n\nCTransform3x3 ComputeHomography(const FeatureSet &f1, const FeatureSet &f2,\n const vector<FeatureMatch> &matches)\n{\n int numMatches = (int) matches.size();\n\n \/\/ first, we will compute the A matrix in the homogeneous linear equations Ah = 0\n int numRows = 2 * numMatches; \/\/ number of rows of A\n const int numCols = 9; \/\/ number of columns of A\n\n \/\/ this allocates space for the A matrix\n AMatrixType A = AMatrixType::Zero(numRows, numCols);\n\n for (int i = 0; i < numMatches; i++) {\n const FeatureMatch &m = matches[i];\n const Feature &a = f1[m.id1];\n const Feature &b = f2[m.id2];\n\n \/\/ BEGIN TODO\n \/\/ fill in the matrix A in this loop.\n \/\/ To access an element of A, use parentheses, e.g. A(0,0)\n\n\t\t\/\/ Note that A is a (2n x 9) matrix\n\t\t\/\/ We can easily fill in A according to the lecture\n\t\t\/\/ Row 2i\n\t\tA(2*i, 0) = a.x;\n\t\tA(2*i, 1) = a.y;\n\t\tA(2*i, 2) = 1;\n\t\tA(2*i, 3) = 0;\n\t\tA(2*i, 4) = 0;\n\t\tA(2*i, 5) = 0;\n\t\tA(2*i, 6) = -b.x * a.x;\n\t\tA(2*i, 7) = -b.x * a.y;\n\t\tA(2*i, 8) = -b.x;\n\n\t\t\/\/ Row 2i+1\n\t\tA(2*i+1, 0) = 0;\n\t\tA(2*i+1, 1) = 0;\n\t\tA(2*i+1, 2) = 0;\n\t\tA(2*i+1, 3) = a.x;\n\t\tA(2*i+1, 4) = a.y;\n\t\tA(2*i+1, 5) = 1;\n\t\tA(2*i+1, 6) = -b.y * a.x;\n\t\tA(2*i+1, 7) = -b.y * a.y;\n\t\tA(2*i+1, 8) = -b.y;\n\n \/\/ END TODO\n }\n\n \/\/ Compute the SVD of the A matrix and get out the matrix V^T and the vector of singular values\n AMatrixType Vt;\n VectorXd sv;\n SVD(A, Vt, sv);\n\n CTransform3x3 H;\n \/\/ BEGIN TODO\n \/\/ fill the homography H with the appropriate elements of the SVD\n \/\/ To extract, for instance, the V matrix, use svd.matrixV()\n\n\t\/\/ Find the smallest sv first\n\t\/\/ minSv: smallest sv value\n\t\/\/ minSvIdx: smallest sv index\n\tdouble minSv = sv[0];\n\tint minSvIdx = 0;\n\tfor (int i = 1; i < 9; i++) {\n\t\tif (sv[i] < minSv) {\n\t\t\tminSv = sv[i];\n\t\t\tminSvIdx = i;\n\t\t}\n\t}\n\t\/\/ Rank(A) = 8 => H = a v_n (a is a constant)\n\t\/\/ v_n corresponds to the smallest sv\n\tH[0][0] = Vt(minSvIdx,0) \/ Vt(minSvIdx,8);\n\tH[0][1] = Vt(minSvIdx,1) \/ Vt(minSvIdx,8);\n\tH[0][2] = Vt(minSvIdx,2) \/ Vt(minSvIdx,8);\n\tH[1][0] = Vt(minSvIdx,3) \/ Vt(minSvIdx,8);\n\tH[1][1] = Vt(minSvIdx,4) \/ Vt(minSvIdx,8);\n\tH[1][2] = Vt(minSvIdx,5) \/ Vt(minSvIdx,8);\n\tH[2][0] = Vt(minSvIdx,6) \/ Vt(minSvIdx,8);\n\tH[2][1] = Vt(minSvIdx,7) \/ Vt(minSvIdx,8);\n\tH[2][2] = Vt(minSvIdx,8) \/ Vt(minSvIdx,8);\n\n \/\/ END TODO\n\n return H;\n}\n\n\n\/******************* TO DO *********************\n * alignPair:\n *\tINPUT:\n *\t\tf1, f2: source feature sets\n *\t\tmatches: correspondences between f1 and f2\n * Each match in 'matches' contains two feature ids of \n * matching features, id1 (in f1) and id2 (in f2).\n *\t\tm: motion model\n *\t\tnRANSAC: number of RANSAC iterations\n *\t\tRANSACthresh: RANSAC distance threshold\n *\t\tM: transformation matrix (output)\n *\n *\tOUTPUT:\n *\t\trepeat for nRANSAC iterations:\n *\t\t\tchoose a minimal set of feature matches\n *\t\t\testimate the transformation implied by these matches\n *\t\t\tcount the number of inliers\n *\t\tfor the transformation with the maximum number of inliers,\n *\t\tcompute the least squares motion estimate using the inliers,\n *\t\tand store it in M\n *\/\nint alignPair(const FeatureSet &f1, const FeatureSet &f2,\n const vector<FeatureMatch> &matches, MotionModel m, \n int nRANSAC, double RANSACthresh, CTransform3x3& M)\n{\n \/\/ BEGIN TODO\n \/\/ Write this entire method. You need to handle two types of \n \/\/ motion models, pure translations (m == eTranslation) and \n \/\/ full homographies (m == eHomography). However, you should\n \/\/ only have one outer loop to perform the RANSAC code, as \n \/\/ the use of RANSAC is almost identical for both cases.\n \/\/\n \/\/ Your homography handling code should call ComputeHomography.\n \/\/ This function should also call countInliers and, at the end,\n \/\/ leastSquaresFit.\nprintf(\"TODO: %s:%d\\n\", __FILE__, __LINE__); \n\n \/\/ END TODO\n\n return 0;\n}\n\n\/******************* TO DO *********************\n * countInliers:\n *\tINPUT:\n *\t\tf1, f2: source feature sets\n *\t\tmatches: correspondences between f1 and f2\n *\t\tm: motion model\n * Each match in 'matches' contains two feature ids of \n * matching features, id1 (in f1) and id2 (in f2).\n *\t\tM: transformation matrix\n *\t\tRANSACthresh: RANSAC distance threshold\n *\t\tinliers: inlier feature IDs\n *\tOUTPUT:\n *\t\ttransform the features in f1 by M\n *\n *\t\tcount the number of features in f1 for which the transformed\n *\t\tfeature is within Euclidean distance RANSACthresh of its match\n *\t\tin f2\n *\n *\t\tstore these features IDs in inliers\n *\n *\/\nint countInliers(const FeatureSet &f1, const FeatureSet &f2,\n const vector<FeatureMatch> &matches, MotionModel m, \n CTransform3x3 M, double RANSACthresh, vector<int> &inliers)\n{\n inliers.clear();\n\n for (unsigned int i = 0; i < matches.size(); i++) {\n \/\/ BEGIN TODO\n \/\/ determine if the ith matched feature f1[id1-1], when transformed by M,\n \/\/ is within RANSACthresh of its match in f2\n \/\/\n \/\/ if so, append i to inliers\nprintf(\"TODO: %s:%d\\n\", __FILE__, __LINE__); \n\n \/\/ END TODO\n }\n\n return (int) inliers.size();\n}\n\n\/******************* TO DO *********************\n * leastSquaresFit:\n *\tINPUT:\n *\t\tf1, f2: source feature sets\n *\t\tmatches: correspondences between f1 and f2\n *\t\tm: motion model\n * inliers: inlier match indices (indexes into 'matches' array)\n *\t\tM: transformation matrix (output)\n *\tOUTPUT:\n *\t\tcompute the transformation from f1 to f2 using only the inliers\n *\t\tand return it in M\n *\/\nint leastSquaresFit(const FeatureSet &f1, const FeatureSet &f2,\n const vector<FeatureMatch> &matches, MotionModel m, \n const vector<int> &inliers, CTransform3x3& M)\n{\n \/\/ This function needs to handle two possible motion models, \n \/\/ pure translations and full homographies.\n\n switch (m) {\n case eTranslate: {\n \/\/ for spherically warped images, the transformation is a \n \/\/ translation and only has two degrees of freedom\n \/\/\n \/\/ therefore, we simply compute the average translation vector\n \/\/ between the feature in f1 and its match in f2 for all inliers\n double u = 0;\n double v = 0;\n\n for (int i=0; i < (int) inliers.size(); i++) {\n\t\t\t \/\/ BEGIN TODO\n\t\t\t \/\/ use this loop to compute the average translation vector\n\t\t\t \/\/ over all inliers\nprintf(\"TODO: %s:%d\\n\", __FILE__, __LINE__); \n\n \/\/ END TODO\n }\n\n u \/= inliers.size();\n v \/= inliers.size();\n\n M = CTransform3x3::Translation((float) u, (float) v);\n\n break;\n } \n\n case eHomography: {\n\t\t\tM = CTransform3x3();\n\n \/\/ BEGIN TODO\n\t\t \/\/ Compute a homography M using all inliers.\n\t\t \/\/ This should call ComputeHomography.\nprintf(\"TODO: %s:%d\\n\", __FILE__, __LINE__); \n\n \/\/ END TODO\n \n break;\n }\n } \n\n return 0;\n}\n\n<commit_msg>alignPair done<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ NAME\n\/\/ FeatureAlign.cpp -- image registration using feature matching\n\/\/\n\/\/ SEE ALSO\n\/\/ FeatureAlign.h longer description\n\/\/\n\/\/ Based on code by Richard Szeliski, 2001.\n\/\/ (modified for CSE576 Spring 2005, and for CS4670, Fall 2012-2013)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ImageLib\/ImageLib.h\"\n#include \"FeatureAlign.h\"\n#include \"SVD.h\"\n\n#include <math.h>\n#include <iostream>\n\nCTransform3x3 ComputeHomography(const FeatureSet &f1, const FeatureSet &f2,\n const vector<FeatureMatch> &matches)\n{\n int numMatches = (int) matches.size();\n\n \/\/ first, we will compute the A matrix in the homogeneous linear equations Ah = 0\n int numRows = 2 * numMatches; \/\/ number of rows of A\n const int numCols = 9; \/\/ number of columns of A\n\n \/\/ this allocates space for the A matrix\n AMatrixType A = AMatrixType::Zero(numRows, numCols);\n\n for (int i = 0; i < numMatches; i++) {\n const FeatureMatch &m = matches[i];\n const Feature &a = f1[m.id1];\n const Feature &b = f2[m.id2];\n\n \/\/ BEGIN TODO\n \/\/ fill in the matrix A in this loop.\n \/\/ To access an element of A, use parentheses, e.g. A(0,0)\n\n\t\t\/\/ Note that A is a (2n x 9) matrix\n\t\t\/\/ We can easily fill in A according to the lecture\n\t\t\/\/ Row 2i\n\t\tA(2*i, 0) = a.x;\n\t\tA(2*i, 1) = a.y;\n\t\tA(2*i, 2) = 1;\n\t\tA(2*i, 3) = 0;\n\t\tA(2*i, 4) = 0;\n\t\tA(2*i, 5) = 0;\n\t\tA(2*i, 6) = -b.x * a.x;\n\t\tA(2*i, 7) = -b.x * a.y;\n\t\tA(2*i, 8) = -b.x;\n\n\t\t\/\/ Row 2i+1\n\t\tA(2*i+1, 0) = 0;\n\t\tA(2*i+1, 1) = 0;\n\t\tA(2*i+1, 2) = 0;\n\t\tA(2*i+1, 3) = a.x;\n\t\tA(2*i+1, 4) = a.y;\n\t\tA(2*i+1, 5) = 1;\n\t\tA(2*i+1, 6) = -b.y * a.x;\n\t\tA(2*i+1, 7) = -b.y * a.y;\n\t\tA(2*i+1, 8) = -b.y;\n\n \/\/ END TODO\n }\n\n \/\/ Compute the SVD of the A matrix and get out the matrix V^T and the vector of singular values\n AMatrixType Vt;\n VectorXd sv;\n SVD(A, Vt, sv);\n\n CTransform3x3 H;\n \/\/ BEGIN TODO\n \/\/ fill the homography H with the appropriate elements of the SVD\n \/\/ To extract, for instance, the V matrix, use svd.matrixV()\n\n\t\/\/ Find the smallest sv first\n\t\/\/ minSv: smallest sv value\n\t\/\/ minSvIdx: smallest sv index\n\tdouble minSv = sv[0];\n\tint minSvIdx = 0;\n\tfor (int i = 0; i < (int)sv.size(); i++) {\n\t\tif (sv[i] < minSv && sv[i] > 0) {\n\t\t\tminSv = sv[i];\n\t\t\tminSvIdx = i;\n\t\t}\n\t}\n\t\/\/ Rank(A) = 8 => H = a v_n (a is a constant)\n\t\/\/ v_n corresponds to the smallest sv\n\tH[0][0] = Vt(minSvIdx,0) \/ Vt(minSvIdx,8);\n\tH[0][1] = Vt(minSvIdx,1) \/ Vt(minSvIdx,8);\n\tH[0][2] = Vt(minSvIdx,2) \/ Vt(minSvIdx,8);\n\tH[1][0] = Vt(minSvIdx,3) \/ Vt(minSvIdx,8);\n\tH[1][1] = Vt(minSvIdx,4) \/ Vt(minSvIdx,8);\n\tH[1][2] = Vt(minSvIdx,5) \/ Vt(minSvIdx,8);\n\tH[2][0] = Vt(minSvIdx,6) \/ Vt(minSvIdx,8);\n\tH[2][1] = Vt(minSvIdx,7) \/ Vt(minSvIdx,8);\n\tH[2][2] = Vt(minSvIdx,8) \/ Vt(minSvIdx,8);\n\n \/\/ END TODO\n\n return H;\n}\n\n\n\/******************* TO DO *********************\n * alignPair:\n *\tINPUT:\n *\t\tf1, f2: source feature sets\n *\t\tmatches: correspondences between f1 and f2\n * Each match in 'matches' contains two feature ids of \n * matching features, id1 (in f1) and id2 (in f2).\n *\t\tm: motion model\n *\t\tnRANSAC: number of RANSAC iterations\n *\t\tRANSACthresh: RANSAC distance threshold\n *\t\tM: transformation matrix (output)\n *\n *\tOUTPUT:\n *\t\trepeat for nRANSAC iterations:\n *\t\t\tchoose a minimal set of feature matches\n *\t\t\testimate the transformation implied by these matches\n *\t\t\tcount the number of inliers\n *\t\tfor the transformation with the maximum number of inliers,\n *\t\tcompute the least squares motion estimate using the inliers,\n *\t\tand store it in M\n *\/\nint alignPair(const FeatureSet &f1, const FeatureSet &f2,\n const vector<FeatureMatch> &matches, MotionModel m, \n int nRANSAC, double RANSACthresh, CTransform3x3& M)\n{\n \/\/ BEGIN TODO\n \/\/ Write this entire method. You need to handle two types of \n \/\/ motion models, pure translations (m == eTranslation) and \n \/\/ full homographies (m == eHomography). However, you should\n \/\/ only have one outer loop to perform the RANSAC code, as \n \/\/ the use of RANSAC is almost identical for both cases.\n \/\/\n \/\/ Your homography handling code should call ComputeHomography.\n \/\/ This function should also call countInliers and, at the end,\n \/\/ leastSquaresFit.\n\t\n\t\/\/ Generate a random seed\n\t\/\/ srand(unsigned int(time(NULL)));\n\n\t\/\/ Save maximum inliers\n\t\/\/ maxInlierCnt: maximum number of inliers\n\t\/\/ maxInliers: inlier feature ids of f1\n\tint maxInlierCnt = 0;\n\tvector<int> maxInliers;\n\n\tfor (int i = 0; i < nRANSAC; i++) {\n\t\t\n\t\t\/\/ Number of features\n\t\tint numF = matches.size();\n\n\t\t\/\/ Number of samples\n\t\tint numS;\n\t\tswitch (m) {\n\t\t\tcase eTranslate:\n\t\t\t\tnumS = 1;\n\t\t\t\tbreak;\n\t\t\tcase eHomography:\n\t\t\t\tnumS = 4;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tvector<FeatureMatch> randMatches;\n\t\tint cnt = 0;\n\t\twhile (cnt < numS) {\n\t\t\t\/\/ Randomly pick a pair from the feature list that isn't in the list\n\t\t\tint rdn = rand() % numF;\n\t\t\tFeatureMatch curFeature = matches[rdn];\n\t\t\t\/\/ Check if this match is already selected\n\t\t\tbool selected = false;\n\t\t\tfor (int j = 0; j < (int)randMatches.size(); j++) {\n\t\t\t\tif (randMatches[j].id1 == curFeature.id1 && randMatches[j].id2 == curFeature.id2) {\n\t\t\t\t\tselected = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ If not, push it to the sample space\n\t\t\tif (!selected) {\n\t\t\t\trandMatches.push_back(curFeature);\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\t\/\/ Get the transform\n\t\tCTransform3x3 M;\n\t\t\/\/ Translation\n\t\tif (numS ==1) {\n\t\t\tFeatureMatch match = randMatches[0];\n\t\t\tM[0][0] = 1;\n\t\t\tM[0][1] = 0;\n\t\t\tM[0][2] = f2[match.id2].x - f1[match.id1].x;\n\t\t\tM[1][0] = 0;\n\t\t\tM[1][1] = 1;\n\t\t\tM[1][2] = f2[match.id2].y - f1[match.id2].y;\n\t\t\tM[2][0] = 0;\n\t\t\tM[2][1] = 0;\n\t\t\tM[2][2] = 1;\n\t\t}\n\t\t\/\/ Homography\n\t\telse {\n\t\t\tM = ComputeHomography(f1, f2, randMatches);\n\t\t}\n\t\t\/\/ Count inliers matching this homography\n\t\tvector<int> curInliers;\n\t\tint numInliers = countInliers(f1, f2, matches, m, M, RANSACthresh, curInliers);\n\t\t\/\/ Update maximum inliers\n\t\tif (numInliers > maxInlierCnt) {\n\t\t\tmaxInlierCnt = numInliers;\n\t\t\tmaxInliers.clear();\n\t\t\tfor (int k = 0; k < numInliers; k++) {\n\t\t\t\tmaxInliers.push_back(curInliers[k]);\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Call leastSquaresFit\n\tif (leastSquaresFit(f1, f2, matches, m, maxInliers, M) != 0) {\n\t\tcout << \"ERROR: leastSquaresFit exits abnormally!\" << endl;\n\t\treturn -1;\n\t}\n \/\/ END TODO\n\n return 0;\n}\n\n\/******************* TO DO *********************\n * countInliers:\n *\tINPUT:\n *\t\tf1, f2: source feature sets\n *\t\tmatches: correspondences between f1 and f2\n *\t\tm: motion model\n * Each match in 'matches' contains two feature ids of \n * matching features, id1 (in f1) and id2 (in f2).\n *\t\tM: transformation matrix\n *\t\tRANSACthresh: RANSAC distance threshold\n *\t\tinliers: inlier feature IDs\n *\tOUTPUT:\n *\t\ttransform the features in f1 by M\n *\n *\t\tcount the number of features in f1 for which the transformed\n *\t\tfeature is within Euclidean distance RANSACthresh of its match\n *\t\tin f2\n *\n *\t\tstore these features IDs in inliers\n *\n *\/\nint countInliers(const FeatureSet &f1, const FeatureSet &f2,\n const vector<FeatureMatch> &matches, MotionModel m, \n CTransform3x3 M, double RANSACthresh, vector<int> &inliers)\n{\n inliers.clear();\n\n for (unsigned int i = 0; i < matches.size(); i++) {\n \/\/ BEGIN TODO\n \/\/ determine if the ith matched feature f1[id1-1], when transformed by M,\n \/\/ is within RANSACthresh of its match in f2\n \/\/\n \/\/ if so, append i to inliers\nprintf(\"TODO: %s:%d\\n\", __FILE__, __LINE__); \n\n \/\/ END TODO\n }\n\n return (int) inliers.size();\n}\n\n\/******************* TO DO *********************\n * leastSquaresFit:\n *\tINPUT:\n *\t\tf1, f2: source feature sets\n *\t\tmatches: correspondences between f1 and f2\n *\t\tm: motion model\n * inliers: inlier match indices (indexes into 'matches' array)\n *\t\tM: transformation matrix (output)\n *\tOUTPUT:\n *\t\tcompute the transformation from f1 to f2 using only the inliers\n *\t\tand return it in M\n *\/\nint leastSquaresFit(const FeatureSet &f1, const FeatureSet &f2,\n const vector<FeatureMatch> &matches, MotionModel m, \n const vector<int> &inliers, CTransform3x3& M)\n{\n \/\/ This function needs to handle two possible motion models, \n \/\/ pure translations and full homographies.\n\n switch (m) {\n case eTranslate: {\n \/\/ for spherically warped images, the transformation is a \n \/\/ translation and only has two degrees of freedom\n \/\/\n \/\/ therefore, we simply compute the average translation vector\n \/\/ between the feature in f1 and its match in f2 for all inliers\n double u = 0;\n double v = 0;\n\n for (int i=0; i < (int) inliers.size(); i++) {\n\t\t\t \/\/ BEGIN TODO\n\t\t\t \/\/ use this loop to compute the average translation vector\n\t\t\t \/\/ over all inliers\nprintf(\"TODO: %s:%d\\n\", __FILE__, __LINE__); \n\n \/\/ END TODO\n }\n\n u \/= inliers.size();\n v \/= inliers.size();\n\n M = CTransform3x3::Translation((float) u, (float) v);\n\n break;\n } \n\n case eHomography: {\n\t\t\tM = CTransform3x3();\n\n \/\/ BEGIN TODO\n\t\t \/\/ Compute a homography M using all inliers.\n\t\t \/\/ This should call ComputeHomography.\nprintf(\"TODO: %s:%d\\n\", __FILE__, __LINE__); \n\n \/\/ END TODO\n \n break;\n }\n } \n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight\n Project home: https:\/\/github.com\/puuu\/MQTT433gateway\/\n\n The MIT License (MIT)\n\n Copyright (c) 2017 Jan Losinski\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and\/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include <ESP8266WebServer.h>\n#include <WString.h>\n\n#include <ArduinoJson.h>\n#include <ArduinoSimpleLogging.h>\n\n#include \"..\/..\/dist\/index.html.gz.h\"\n#include \"ConfigWebServer.h\"\n\nconst char PROGMEM PLAIN[] = \"plain\";\nconst char PROGMEM TEXT_PLAIN[] = \"text\/plain\";\nconst char PROGMEM TEXT_HTML[] = \"text\/html\";\nconst char PROGMEM APPLICATION_JSON[] = \"application\/json\";\n\nconst char PROGMEM URL_ROOT[] = \"\/\";\nconst char PROGMEM URL_SYSTEM[] = \"\/system\";\nconst char PROGMEM URL_CONFIG[] = \"\/config\";\nconst char PROGMEM URL_PROTOCOLS[] = \"\/protocols\";\nconst char PROGMEM URL_DEBUG[] = \"\/debug\";\nconst char PROGMEM URL_FIRMWARE[] = \"\/firmware\";\n\nvoid ConfigWebServer::begin() {\n server.on(FPSTR(URL_ROOT), authenticated([this]() {\n Logger.debug.println(F(\"Webserver: frontend request\"));\n server.sendHeader(F(\"Content-Encoding\"), F(\"gzip\"));\n server.setContentLength(index_html_gz_len);\n server.send(200, FPSTR(TEXT_HTML), \"\");\n server.sendContent_P(index_html_gz, index_html_gz_len);\n }));\n\n server.on(FPSTR(URL_SYSTEM), HTTP_GET, authenticated([this]() {\n Logger.debug.println(F(\"Webserver: system GET\"));\n server.send_P(200, TEXT_PLAIN, PSTR(\"POST your commands here\"));\n }));\n\n server.on(\n FPSTR(URL_SYSTEM), HTTP_POST,\n authenticated(std::bind(&::ConfigWebServer::onSystemCommand, this)));\n\n server.on(FPSTR(URL_CONFIG), HTTP_GET, authenticated([&]() {\n Logger.debug.println(F(\"Webserver: config GET\"));\n onConfigGet();\n }));\n\n server.on(FPSTR(URL_CONFIG), HTTP_PUT, authenticated([&]() {\n Logger.debug.println(F(\"Webserver: config PUT\"));\n settings.deserialize(server.arg(FPSTR(PLAIN)));\n settings.save();\n onConfigGet();\n }));\n\n server.on(FPSTR(URL_PROTOCOLS), HTTP_GET, authenticated([this]() {\n Logger.debug.println(F(\"Webserver: protocols GET\"));\n if (protocolProvider) {\n server.send(200, FPSTR(APPLICATION_JSON), protocolProvider());\n } else {\n Logger.warning.println(F(\"No protocolProvider avaiable.\"));\n server.send_P(200, APPLICATION_JSON, PSTR(\"[]\"));\n }\n }));\n\n server.on(FPSTR(URL_DEBUG), HTTP_GET, authenticated([&]() {\n Logger.debug.println(F(\"Webserver: debug GET\"));\n onDebugFlagGet();\n }));\n\n server.on(FPSTR(URL_DEBUG), HTTP_PUT,\n authenticated(std::bind(&::ConfigWebServer::onDebugFlagSet, this)));\n\n server.on(FPSTR(URL_FIRMWARE), HTTP_GET, authenticated([this]() {\n Logger.debug.println(F(\"Webserver: firmware GET\"));\n server.send(\n 200, FPSTR(APPLICATION_JSON),\n String(F(\"{\\\"version\\\":\\\"\" QUOTE(FIRMWARE_VERSION) \"\\\",\")) +\n F(\"\\\"chipId\\\":\\\"\") + String(ESP.getChipId(), HEX) +\n F(\"\\\"}\"));\n }));\n\n server.on(\n FPSTR(URL_FIRMWARE), HTTP_POST,\n authenticated(std::bind(&::ConfigWebServer::onFirmwareFinish, this)),\n std::bind(&::ConfigWebServer::onFirmwareUpload, this));\n\n Logger.debug.println(F(\"Starting webserver and websocket server.\"));\n wsLogTarget.begin();\n server.begin();\n}\n\nvoid ConfigWebServer::registerSystemCommandHandler(\n const String& command, const ConfigWebServer::SystemCommandCb& cb) {\n systemCommandHandlers.emplace_front(command, cb);\n}\n\nvoid ConfigWebServer::registerDebugFlagHandler(\n const String& state, const ConfigWebServer::DebugFlagGetCb& getState,\n const ConfigWebServer::DebugFlagSetCb& setState) {\n debugFlagHandlers.emplace_front(state, getState, setState);\n}\n\nvoid ConfigWebServer::onConfigGet() {\n String buff;\n settings.serialize(buff, true, false);\n server.send(200, FPSTR(APPLICATION_JSON), buff);\n}\n\nvoid ConfigWebServer::onSystemCommand() {\n Logger.debug.println(F(\"Webserver: system POST\"));\n DynamicJsonBuffer buffer;\n JsonObject& request = buffer.parse(server.arg(FPSTR(PLAIN)));\n\n if (!request.success()) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"Cannot parse command!\"));\n return;\n }\n\n if (!request.containsKey(F(\"command\"))) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"No command found!\"));\n return;\n }\n\n for (const auto& systemCommandHandler : systemCommandHandlers) {\n if (systemCommandHandler.command == request[F(\"command\")]) {\n server.send_P(200, TEXT_PLAIN, PSTR(\"Run command!\"));\n systemCommandHandler.cb();\n return;\n }\n }\n\n server.send_P(400, TEXT_PLAIN, PSTR(\"Unknown command\"));\n}\n\nvoid ConfigWebServer::onDebugFlagSet() {\n Logger.debug.println(F(\"Webserver: debug PUT\"));\n DynamicJsonBuffer buffer;\n JsonObject& request = buffer.parse(server.arg(FPSTR(PLAIN)));\n\n if (request.success()) {\n for (const auto& debugFlagHandler : debugFlagHandlers) {\n if (request.containsKey(debugFlagHandler.name)) {\n debugFlagHandler.setState(request[debugFlagHandler.name].as<bool>());\n Logger.debug.print(F(\"Set debug flag \"));\n Logger.debug.print(debugFlagHandler.name);\n Logger.debug.print(F(\": \"));\n Logger.debug.println(request[debugFlagHandler.name].as<bool>());\n }\n }\n } else {\n Logger.error.println(F(\"Cannot parse debug flag as json object!\"));\n }\n onDebugFlagGet();\n}\n\nvoid ConfigWebServer::onDebugFlagGet() {\n DynamicJsonBuffer buffer;\n JsonObject& root = buffer.createObject();\n\n for (const auto& debugFlagHandler : debugFlagHandlers) {\n root[debugFlagHandler.name] = debugFlagHandler.getState();\n }\n String result;\n root.printTo(result);\n server.send(200, FPSTR(APPLICATION_JSON), result);\n}\n\nvoid ConfigWebServer::onFirmwareFinish() {\n server.sendHeader(F(\"Connection\"), F(\"close\"));\n\n Logger.info.println(F(\"Got an update. Rebooting...\"));\n if (Update.hasError()) {\n server.send_P(\n 200, TEXT_PLAIN,\n PSTR(\"Update failed. More information can be found on the serial \"\n \"console. \\n\\nDevice will reboot with old firmware. Please \"\n \"reconnect and try to flash again.\"));\n } else {\n server.sendHeader(F(\"Refresh\"), F(\"20; URL=\/\"));\n server.send_P(200, TEXT_PLAIN,\n PSTR(\"Update successful.\\n\\nDevice will reboot and try \"\n \"to reconnect in 20 seconds.\"));\n }\n delay(500);\n ESP.restart();\n}\n\nvoid ConfigWebServer::onFirmwareUpload() {\n static bool authenticate = false;\n HTTPUpload& upload = server.upload();\n wsLogTarget.loop();\n\n if (upload.status == UPLOAD_FILE_START) {\n authenticate = server.authenticate(ADMIN_USERNAME,\n this->settings.configPassword.c_str());\n if (!authenticate) {\n return;\n }\n Logger.info.println(F(\"Webserver: firmware upload started\"));\n Serial.setDebugOutput(true);\n\n if (otaHook) {\n otaHook();\n }\n\n Logger.debug.print(F(\"Update: \"));\n Logger.debug.println(upload.filename.c_str());\n Logger.debug.print(F(\"Free heap: \"));\n Logger.debug.println(ESP.getFreeHeap());\n uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;\n if (!Update.begin(maxSketchSpace)) { \/\/ start with max available size\n Update.printError(Serial);\n }\n } else if (upload.status == UPLOAD_FILE_WRITE && authenticate) {\n if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {\n Update.printError(Serial);\n }\n } else if (upload.status == UPLOAD_FILE_END && authenticate) {\n if (Update.end(true)) { \/\/ true to set the size to the current progress\n Logger.debug.print(F(\"Update Success: \"));\n Logger.debug.println(upload.totalSize);\n } else {\n Update.printError(Serial);\n }\n Serial.setDebugOutput(false);\n }\n yield();\n}\n\nvoid ConfigWebServer::loop() {\n wsLogTarget.loop();\n server.handleClient();\n}\n\nPrint& ConfigWebServer::logTarget() { return wsLogTarget; }\n\nESP8266WebServer::THandlerFunction ConfigWebServer::authenticated(\n const ESP8266WebServer::THandlerFunction& handler) {\n return [=]() {\n if (!server.authenticate(ADMIN_USERNAME,\n this->settings.configPassword.c_str())) {\n server.requestAuthentication(DIGEST_AUTH, nullptr,\n F(\"Authentication required!\"));\n Logger.warning.println(F(\"Webserver: Authentication failed.\"));\n } else {\n handler();\n }\n };\n}\n<commit_msg>WebServer: do not proceed on errors during update<commit_after>\/**\n MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight\n Project home: https:\/\/github.com\/puuu\/MQTT433gateway\/\n\n The MIT License (MIT)\n\n Copyright (c) 2017 Jan Losinski\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and\/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include <ESP8266WebServer.h>\n#include <WString.h>\n\n#include <ArduinoJson.h>\n#include <ArduinoSimpleLogging.h>\n\n#include \"..\/..\/dist\/index.html.gz.h\"\n#include \"ConfigWebServer.h\"\n\nconst char PROGMEM PLAIN[] = \"plain\";\nconst char PROGMEM TEXT_PLAIN[] = \"text\/plain\";\nconst char PROGMEM TEXT_HTML[] = \"text\/html\";\nconst char PROGMEM APPLICATION_JSON[] = \"application\/json\";\n\nconst char PROGMEM URL_ROOT[] = \"\/\";\nconst char PROGMEM URL_SYSTEM[] = \"\/system\";\nconst char PROGMEM URL_CONFIG[] = \"\/config\";\nconst char PROGMEM URL_PROTOCOLS[] = \"\/protocols\";\nconst char PROGMEM URL_DEBUG[] = \"\/debug\";\nconst char PROGMEM URL_FIRMWARE[] = \"\/firmware\";\n\nvoid ConfigWebServer::begin() {\n server.on(FPSTR(URL_ROOT), authenticated([this]() {\n Logger.debug.println(F(\"Webserver: frontend request\"));\n server.sendHeader(F(\"Content-Encoding\"), F(\"gzip\"));\n server.setContentLength(index_html_gz_len);\n server.send(200, FPSTR(TEXT_HTML), \"\");\n server.sendContent_P(index_html_gz, index_html_gz_len);\n }));\n\n server.on(FPSTR(URL_SYSTEM), HTTP_GET, authenticated([this]() {\n Logger.debug.println(F(\"Webserver: system GET\"));\n server.send_P(200, TEXT_PLAIN, PSTR(\"POST your commands here\"));\n }));\n\n server.on(\n FPSTR(URL_SYSTEM), HTTP_POST,\n authenticated(std::bind(&::ConfigWebServer::onSystemCommand, this)));\n\n server.on(FPSTR(URL_CONFIG), HTTP_GET, authenticated([&]() {\n Logger.debug.println(F(\"Webserver: config GET\"));\n onConfigGet();\n }));\n\n server.on(FPSTR(URL_CONFIG), HTTP_PUT, authenticated([&]() {\n Logger.debug.println(F(\"Webserver: config PUT\"));\n settings.deserialize(server.arg(FPSTR(PLAIN)));\n settings.save();\n onConfigGet();\n }));\n\n server.on(FPSTR(URL_PROTOCOLS), HTTP_GET, authenticated([this]() {\n Logger.debug.println(F(\"Webserver: protocols GET\"));\n if (protocolProvider) {\n server.send(200, FPSTR(APPLICATION_JSON), protocolProvider());\n } else {\n Logger.warning.println(F(\"No protocolProvider avaiable.\"));\n server.send_P(200, APPLICATION_JSON, PSTR(\"[]\"));\n }\n }));\n\n server.on(FPSTR(URL_DEBUG), HTTP_GET, authenticated([&]() {\n Logger.debug.println(F(\"Webserver: debug GET\"));\n onDebugFlagGet();\n }));\n\n server.on(FPSTR(URL_DEBUG), HTTP_PUT,\n authenticated(std::bind(&::ConfigWebServer::onDebugFlagSet, this)));\n\n server.on(FPSTR(URL_FIRMWARE), HTTP_GET, authenticated([this]() {\n Logger.debug.println(F(\"Webserver: firmware GET\"));\n server.send(\n 200, FPSTR(APPLICATION_JSON),\n String(F(\"{\\\"version\\\":\\\"\" QUOTE(FIRMWARE_VERSION) \"\\\",\")) +\n F(\"\\\"chipId\\\":\\\"\") + String(ESP.getChipId(), HEX) +\n F(\"\\\"}\"));\n }));\n\n server.on(\n FPSTR(URL_FIRMWARE), HTTP_POST,\n authenticated(std::bind(&::ConfigWebServer::onFirmwareFinish, this)),\n std::bind(&::ConfigWebServer::onFirmwareUpload, this));\n\n Logger.debug.println(F(\"Starting webserver and websocket server.\"));\n wsLogTarget.begin();\n server.begin();\n}\n\nvoid ConfigWebServer::registerSystemCommandHandler(\n const String& command, const ConfigWebServer::SystemCommandCb& cb) {\n systemCommandHandlers.emplace_front(command, cb);\n}\n\nvoid ConfigWebServer::registerDebugFlagHandler(\n const String& state, const ConfigWebServer::DebugFlagGetCb& getState,\n const ConfigWebServer::DebugFlagSetCb& setState) {\n debugFlagHandlers.emplace_front(state, getState, setState);\n}\n\nvoid ConfigWebServer::onConfigGet() {\n String buff;\n settings.serialize(buff, true, false);\n server.send(200, FPSTR(APPLICATION_JSON), buff);\n}\n\nvoid ConfigWebServer::onSystemCommand() {\n Logger.debug.println(F(\"Webserver: system POST\"));\n DynamicJsonBuffer buffer;\n JsonObject& request = buffer.parse(server.arg(FPSTR(PLAIN)));\n\n if (!request.success()) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"Cannot parse command!\"));\n return;\n }\n\n if (!request.containsKey(F(\"command\"))) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"No command found!\"));\n return;\n }\n\n for (const auto& systemCommandHandler : systemCommandHandlers) {\n if (systemCommandHandler.command == request[F(\"command\")]) {\n server.send_P(200, TEXT_PLAIN, PSTR(\"Run command!\"));\n systemCommandHandler.cb();\n return;\n }\n }\n\n server.send_P(400, TEXT_PLAIN, PSTR(\"Unknown command\"));\n}\n\nvoid ConfigWebServer::onDebugFlagSet() {\n Logger.debug.println(F(\"Webserver: debug PUT\"));\n DynamicJsonBuffer buffer;\n JsonObject& request = buffer.parse(server.arg(FPSTR(PLAIN)));\n\n if (request.success()) {\n for (const auto& debugFlagHandler : debugFlagHandlers) {\n if (request.containsKey(debugFlagHandler.name)) {\n debugFlagHandler.setState(request[debugFlagHandler.name].as<bool>());\n Logger.debug.print(F(\"Set debug flag \"));\n Logger.debug.print(debugFlagHandler.name);\n Logger.debug.print(F(\": \"));\n Logger.debug.println(request[debugFlagHandler.name].as<bool>());\n }\n }\n } else {\n Logger.error.println(F(\"Cannot parse debug flag as json object!\"));\n }\n onDebugFlagGet();\n}\n\nvoid ConfigWebServer::onDebugFlagGet() {\n DynamicJsonBuffer buffer;\n JsonObject& root = buffer.createObject();\n\n for (const auto& debugFlagHandler : debugFlagHandlers) {\n root[debugFlagHandler.name] = debugFlagHandler.getState();\n }\n String result;\n root.printTo(result);\n server.send(200, FPSTR(APPLICATION_JSON), result);\n}\n\nvoid ConfigWebServer::onFirmwareFinish() {\n server.sendHeader(F(\"Connection\"), F(\"close\"));\n\n Logger.info.println(F(\"Got an update. Rebooting...\"));\n if (Update.hasError()) {\n server.send_P(\n 200, TEXT_PLAIN,\n PSTR(\"Update failed. More information can be found on the serial \"\n \"console. \\n\\nDevice will reboot with old firmware. Please \"\n \"reconnect and try to flash again.\"));\n } else {\n server.sendHeader(F(\"Refresh\"), F(\"20; URL=\/\"));\n server.send_P(200, TEXT_PLAIN,\n PSTR(\"Update successful.\\n\\nDevice will reboot and try \"\n \"to reconnect in 20 seconds.\"));\n }\n delay(500);\n ESP.restart();\n}\n\nvoid ConfigWebServer::onFirmwareUpload() {\n static bool authenticate = false;\n static bool error = false;\n HTTPUpload& upload = server.upload();\n wsLogTarget.loop();\n\n if (upload.status == UPLOAD_FILE_START) {\n authenticate = server.authenticate(ADMIN_USERNAME,\n this->settings.configPassword.c_str());\n error = false;\n if (!authenticate) {\n return;\n }\n Logger.info.println(F(\"Webserver: firmware upload started\"));\n Serial.setDebugOutput(true);\n\n if (otaHook) {\n otaHook();\n }\n\n Logger.debug.print(F(\"Update: \"));\n Logger.debug.println(upload.filename.c_str());\n Logger.debug.print(F(\"Free heap: \"));\n Logger.debug.println(ESP.getFreeHeap());\n uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;\n if (!Update.begin(maxSketchSpace)) { \/\/ start with max available size\n Update.printError(Serial);\n }\n } else if (upload.status == UPLOAD_FILE_WRITE && authenticate && !error) {\n if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {\n error = true;\n Update.printError(Serial);\n }\n } else if (upload.status == UPLOAD_FILE_END && authenticate && !error) {\n if (Update.end(true)) { \/\/ true to set the size to the current progress\n Logger.debug.print(F(\"Update Success: \"));\n Logger.debug.println(upload.totalSize);\n } else {\n Update.printError(Serial);\n }\n Serial.setDebugOutput(false);\n }\n yield();\n}\n\nvoid ConfigWebServer::loop() {\n wsLogTarget.loop();\n server.handleClient();\n}\n\nPrint& ConfigWebServer::logTarget() { return wsLogTarget; }\n\nESP8266WebServer::THandlerFunction ConfigWebServer::authenticated(\n const ESP8266WebServer::THandlerFunction& handler) {\n return [=]() {\n if (!server.authenticate(ADMIN_USERNAME,\n this->settings.configPassword.c_str())) {\n server.requestAuthentication(DIGEST_AUTH, nullptr,\n F(\"Authentication required!\"));\n Logger.warning.println(F(\"Webserver: Authentication failed.\"));\n } else {\n handler();\n }\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight\n Project home: https:\/\/github.com\/puuu\/MQTT433gateway\/\n\n The MIT License (MIT)\n\n Copyright (c) 2017 Jan Losinski\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and\/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include <ArduinoJson.h>\n\n#include \"ConfigWebServer.h\"\n\nconst char TEXT_PLAIN[] PROGMEM = \"text\/plain\";\nconst char APPLICATION_JSON[] = \"application\/json\";\n\nvoid ConfigWebServer::begin(const Settings& settings) {\n server.on(\"\/\",\n [this]() { server.send(200, TEXT_PLAIN, F(\"Hello from rfESP\")); });\n\n server.on(\"\/\", [this]() {\n server.send(200, TEXT_PLAIN, F(\"POST your commands here\"));\n });\n\n server.on(\"\/system\", HTTP_POST,\n std::bind(&::ConfigWebServer::onSystemCommand, this));\n\n server.begin();\n}\n\nvoid ConfigWebServer::registerSystemCommandHandler(\n const String& command, const ConfigWebServer::SystemCommandCb& cb) {\n systemCommandHandlers.emplace_front(command, cb);\n}\n\nvoid ConfigWebServer::onSystemCommand() {\n DynamicJsonBuffer buffer;\n JsonObject& request = buffer.parse(server.arg(\"plain\"));\n\n if (!request.success()) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"Cannot parse command!\"));\n return;\n }\n\n if (!request.containsKey(\"command\")) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"No command found!\"));\n return;\n }\n\n for (const auto &systemCommandHandler : systemCommandHandlers) {\n if (systemCommandHandler.command == request[\"command\"]) {\n server.send_P(200, TEXT_PLAIN, PSTR(\"Run command!\"));\n systemCommandHandler.cb();\n return;\n }\n }\n\n server.send_P(400, TEXT_PLAIN, PSTR(\"Unknown command\"));\n}\n\nvoid ConfigWebServer::handleClient() { server.handleClient(); }\n\nvoid ConfigWebServer::updateSettings(const Settings& settings) {}\n<commit_msg>Webserver: fix missing url route<commit_after>\/**\n MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight\n Project home: https:\/\/github.com\/puuu\/MQTT433gateway\/\n\n The MIT License (MIT)\n\n Copyright (c) 2017 Jan Losinski\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and\/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include <ArduinoJson.h>\n\n#include \"ConfigWebServer.h\"\n\nconst char TEXT_PLAIN[] PROGMEM = \"text\/plain\";\nconst char APPLICATION_JSON[] = \"application\/json\";\n\nvoid ConfigWebServer::begin(const Settings& settings) {\n server.on(\"\/\",\n [this]() { server.send(200, TEXT_PLAIN, F(\"Hello from rfESP\")); });\n\n server.on(\"\/system\", [this]() {\n server.send(200, TEXT_PLAIN, F(\"POST your commands here\"));\n });\n\n server.on(\"\/system\", HTTP_POST,\n std::bind(&::ConfigWebServer::onSystemCommand, this));\n\n server.begin();\n}\n\nvoid ConfigWebServer::registerSystemCommandHandler(\n const String& command, const ConfigWebServer::SystemCommandCb& cb) {\n systemCommandHandlers.emplace_front(command, cb);\n}\n\nvoid ConfigWebServer::onSystemCommand() {\n DynamicJsonBuffer buffer;\n JsonObject& request = buffer.parse(server.arg(\"plain\"));\n\n if (!request.success()) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"Cannot parse command!\"));\n return;\n }\n\n if (!request.containsKey(\"command\")) {\n server.send_P(400, TEXT_PLAIN, PSTR(\"No command found!\"));\n return;\n }\n\n for (const auto &systemCommandHandler : systemCommandHandlers) {\n if (systemCommandHandler.command == request[\"command\"]) {\n server.send_P(200, TEXT_PLAIN, PSTR(\"Run command!\"));\n systemCommandHandler.cb();\n return;\n }\n }\n\n server.send_P(400, TEXT_PLAIN, PSTR(\"Unknown command\"));\n}\n\nvoid ConfigWebServer::handleClient() { server.handleClient(); }\n\nvoid ConfigWebServer::updateSettings(const Settings& settings) {}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * Copyright : (C) 2002 by Gav Wood <gav@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License as *\n * published by the Free Software Foundation; either version 2 of *\n * the License or (at your option) version 3 or any later version *\n * accepted by the membership of KDE e.V. (or its successor approved *\n * by the membership of KDE e.V.), which shall act as a proxy *\n * defined in Section 14 of 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 <http:\/\/www.gnu.org\/licenses\/>. *\n *************************************************************************\/\n\n\n\/**\n * @author Gav Wood\n *\/\n\n\/\/ main.cpp - Implementation of the main window\n\n#include \"irkick.h\"\n\n#include <kcmdlineargs.h>\n#include <kuniqueapplication.h>\n\nextern \"C\" KDE_EXPORT int kdemain(int argc, char *argv[])\n{\n\n KAboutData *aboutData = new KAboutData(\"irkick\", 0, ki18n(\"IRKick\"), KDE::versionString(), ki18n(\"The KDE Infrared Remote Control Server\"), KAboutData::License_GPL, ki18n(\"(c) 2003, Gav Wood\"), ki18n(\"Control your desktop with your remote.\"), \"http:\/\/utils.kde.org\/projects\/kdelirc\");\n aboutData->addAuthor(ki18n(\"Gav Wood\"), ki18n(\"Author\"), \"gav@kde.org\");\n aboutData->addCredit(ki18n(\"Malte Starostik\"), ki18n(\"Original LIRC interface code\"), \"malte.starostik@t-online.de\");\n aboutData->addCredit(ki18n(\"Dirk Ziegelmeier\"), ki18n(\"Ideas, concept code\"), \"dirk@ziegelmeier.net\");\n aboutData->addCredit(ki18n(\"Zsolt Rizsanyi\"), ki18n(\"Random patches\"), \"rizsanyi@myrealbox.com\");\n aboutData->addCredit(ki18n(\"Antonio Larrosa Jiménez\"), ki18n(\"Ideas\"), \"larrosa@kde.org\");\n aboutData->addCredit(ki18n(\"Michael Zanetti\"), ki18n(\"KDE4-Port and refactoring\"), \"michael_zanetti@gmx.net\");\n aboutData->addCredit(ki18n(\"Frank Scheffold\"), ki18n(\"KDE4-Port and refactoring\"), \"fscheffold@googlemail.com\");\n\n\n KCmdLineArgs::init(argc, argv, aboutData);\n KUniqueApplication::addCmdLineOptions();\n KUniqueApplication app;\n app.setQuitOnLastWindowClosed(false);\n KGlobal::locale()->insertCatalog(\"kdelirc\");\n app.disableSessionManagement();\n IRKick *theIRKick = new IRKick();\n int ret = app.exec();\n delete theIRKick;\n return ret;\n}\n<commit_msg>bumping the version numbers in \/trunk, now that 4.3 has been branched<commit_after>\/*************************************************************************\n * Copyright : (C) 2002 by Gav Wood <gav@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License as *\n * published by the Free Software Foundation; either version 2 of *\n * the License or (at your option) version 3 or any later version *\n * accepted by the membership of KDE e.V. (or its successor approved *\n * by the membership of KDE e.V.), which shall act as a proxy *\n * defined in Section 14 of 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 <http:\/\/www.gnu.org\/licenses\/>. *\n *************************************************************************\/\n\n\n\/**\n * @author Gav Wood\n *\/\n\n\/\/ main.cpp - Implementation of the main window\n\n#include \"irkick.h\"\n\n#include <kcmdlineargs.h>\n#include <kuniqueapplication.h>\n\nextern \"C\" KDE_EXPORT int kdemain(int argc, char *argv[])\n{\n\n KAboutData *aboutData = new KAboutData(\"irkick\", 0, ki18n(\"IRKick\"), KDE_VERSION_STRING, ki18n(\"The KDE Infrared Remote Control Server\"), KAboutData::License_GPL, ki18n(\"(c) 2003, Gav Wood\"), ki18n(\"Control your desktop with your remote.\"), \"http:\/\/utils.kde.org\/projects\/kdelirc\");\n aboutData->addAuthor(ki18n(\"Gav Wood\"), ki18n(\"Author\"), \"gav@kde.org\");\n aboutData->addCredit(ki18n(\"Malte Starostik\"), ki18n(\"Original LIRC interface code\"), \"malte.starostik@t-online.de\");\n aboutData->addCredit(ki18n(\"Dirk Ziegelmeier\"), ki18n(\"Ideas, concept code\"), \"dirk@ziegelmeier.net\");\n aboutData->addCredit(ki18n(\"Zsolt Rizsanyi\"), ki18n(\"Random patches\"), \"rizsanyi@myrealbox.com\");\n aboutData->addCredit(ki18n(\"Antonio Larrosa Jiménez\"), ki18n(\"Ideas\"), \"larrosa@kde.org\");\n aboutData->addCredit(ki18n(\"Michael Zanetti\"), ki18n(\"KDE4-Port and refactoring\"), \"michael_zanetti@gmx.net\");\n aboutData->addCredit(ki18n(\"Frank Scheffold\"), ki18n(\"KDE4-Port and refactoring\"), \"fscheffold@googlemail.com\");\n\n\n KCmdLineArgs::init(argc, argv, aboutData);\n KUniqueApplication::addCmdLineOptions();\n KUniqueApplication app;\n app.setQuitOnLastWindowClosed(false);\n KGlobal::locale()->insertCatalog(\"kdelirc\");\n app.disableSessionManagement();\n IRKick *theIRKick = new IRKick();\n int ret = app.exec();\n delete theIRKick;\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"StartMenu.h\"\n#include <stdlib.h>\n#include <time.h>\n#include <fstream>\n#include <iterator>\n\nStartMenu::StartMenu(Input* input) : Superscene(input)\n{\n hud = new Entity();\n hud->make2D();\n hud->scale = glm::vec3(0.5,0.5,1);\n hud->setColor(glm::vec3(0,1,0));\n hud->position = glm::vec3(1024.0\/3.0f,720\/2.0f,0);\n this->addChild(hud);\n\n hud2 = new Entity();\n hud2->make2D();\n hud2->scale = glm::vec3(0.5,0.5,1);\n hud2->setColor(glm::vec3(1,0,0));\n hud2->position = glm::vec3(1024 - 1024.0\/3.0f,720\/2.0f,0);\n this->addChild(hud2);\n}\n\nStartMenu::~StartMenu()\n{\n\n}\n\nvoid StartMenu::Update(float deltaTime)\n{\n if (Collision::intersectMouse2D(hud, glm::vec2(input->getMousePosition())) && input->getMouseKeyDown(0)) {\n sceneState = Superscene::NEXT;\n }\n if (Collision::intersectMouse2D(hud2, glm::vec2(input->getMousePosition())) && input->getMouseKeyDown(0)) {\n sceneState = Superscene::DESTROY;\n }\n}\n<commit_msg>Update documentation<commit_after>#include \"StartMenu.h\"\n#include <stdlib.h>\n#include <time.h>\n#include <fstream>\n#include <iterator>\n\nStartMenu::StartMenu(Input* input) : Superscene(input)\n{\n \/\/ Make a entity\n hud = new Entity();\n \/\/ Make it 2D (GUI element)\n hud->make2D();\n \/\/ Set the scale of this entity\n hud->scale = glm::vec3(0.5,0.5,1);\n \/\/ Set the color of this entity\n hud->setColor(glm::vec3(0,1,0));\n \/\/ Set the position of this entity according to the screen size\n hud->position = glm::vec3(1024.0\/3.0f,720\/2.0f,0);\n \/\/ Add this entity to the list of children (rendertargets)\n this->addChild(hud);\n\n \/\/ See above\n hud2 = new Entity();\n hud2->make2D();\n hud2->scale = glm::vec3(0.5,0.5,1);\n hud2->setColor(glm::vec3(1,0,0));\n hud2->position = glm::vec3(1024 - 1024.0\/3.0f,720\/2.0f,0);\n this->addChild(hud2);\n}\n\nStartMenu::~StartMenu()\n{\n \n}\n\nvoid StartMenu::Update(float deltaTime)\n{\n \/\/ If we click on this element\n if (Collision::intersectMouse2D(hud, glm::vec2(input->getMousePosition())) && input->getMouseKeyDown(0)) {\n \/\/ Switch to the next scene\n sceneState = Superscene::NEXT;\n }\n \/\/ If we click on this element\n if (Collision::intersectMouse2D(hud2, glm::vec2(input->getMousePosition())) && input->getMouseKeyDown(0)) {\n \/\/ Switch to the next scene\n sceneState = Superscene::DESTROY;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"myarea.h\"\n#include <cairomm\/context.h>\n#include <giomm\/resource.h>\n#include <gdkmm\/general.h> \/\/ set_source_pixbuf()\n#include <glibmm\/fileutils.h>\n#include <iostream>\n#include <sys\/mman.h>\n#include <fcntl.h>\n\n#define SHARED_FB \"shared_fb\"\n\nMyArea::MyArea()\n{\n shm_fd = -1;\n shm_buf = NULL;\n try\n {\n \/\/ The fractal image has been created by the XaoS program.\n \/\/ http:\/\/xaos.sourceforge.net\n \/\/m_image = Gdk::Pixbuf::create_from_resource(\"\/image\/fractal_image.png\");\n \/\/m_image = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, false, 8, 320, 200);\n\n \/\/guint8* data = m_image->get_pixels();\n \/\/ guint8* data = (guint8*)malloc(3*320*200);\n int shm_fd = shm_open(SHARED_FB, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);\n if(shm_fd > 0) {\n ftruncate(shm_fd, 320*200*3);\n shm_buf = mmap(NULL, 320*200*3, PROT_READ|PROT_WRITE, MAP_SHARED, shm_fd, (off_t)0);\n if(shm_buf == MAP_FAILED) {\n fprintf(stderr, \"mmap failed: %s\\n\", strerror(errno));\n shm_buf = NULL;\n }\n }\n else {\n fprintf(stderr, \"shm_open failed: %s\\n\", strerror(errno));\n }\n \n if(shm_buf != NULL) {\n guint8* data = (guint8*)shm_buf;\n m_image = Gdk::Pixbuf::create_from_data(data, Gdk::COLORSPACE_RGB, false, 8, 320, 200, 320 * 3);\n\n for(int row = 0; row < 200; row++) {\n for(int col = 0; col < 320; col++) {\n \/\/*data++ = row;\n *data++ = 0;\n *data++ = row;\n *data++ = row;\n }\n }\n }\n \/\/memset(data, 128, 3 * sizeof(guint8) * 320 * 200);\n\n }\n catch(const Gio::ResourceError& ex)\n {\n \/\/std::cerr << \"ResourceError: \" << ex.what() << std::endl;\n }\n catch(const Gdk::PixbufError& ex)\n {\n \/\/std::cerr << \"PixbufError: \" << ex.what() << std::endl;\n }\n\n \/\/ Show at least a quarter of the image.\n if (m_image)\n set_size_request(m_image->get_width()\/2, m_image->get_height()\/2);\n}\n\nMyArea::~MyArea()\n{\n fprintf(stdout, \"exiting\\n\");\n if(shm_buf != NULL) {\n munmap(shm_buf, 320*200*3);\n }\n if(shm_fd > 0) {\n shm_unlink(SHARED_FB);\n }\n}\n\nbool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)\n{\n if (!m_image)\n return false;\n\n Gtk::Allocation allocation = get_allocation();\n const int width = allocation.get_width();\n const int height = allocation.get_height();\n\n \/\/ Draw the image in the middle of the drawing area, or (if the image is\n \/\/ larger than the drawing area) draw the middle part of the image.\n Gdk::Cairo::set_source_pixbuf(cr, m_image,\n (width - m_image->get_width())\/2, (height - m_image->get_height())\/2);\n cr->paint();\n\n return true;\n}\n<commit_msg>close<commit_after>#include \"myarea.h\"\n#include <cairomm\/context.h>\n#include <giomm\/resource.h>\n#include <gdkmm\/general.h> \/\/ set_source_pixbuf()\n#include <glibmm\/fileutils.h>\n#include <iostream>\n#include <sys\/mman.h>\n#include <fcntl.h>\n\n#define SHARED_FB \"shared_fb\"\n\nMyArea::MyArea()\n{\n shm_fd = -1;\n shm_buf = NULL;\n try\n {\n int shm_fd = shm_open(SHARED_FB, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);\n if(shm_fd > 0) {\n ftruncate(shm_fd, 320*200*3);\n shm_buf = mmap(NULL, 320*200*3, PROT_READ|PROT_WRITE, MAP_SHARED, shm_fd, (off_t)0);\n if(shm_buf == MAP_FAILED) {\n fprintf(stderr, \"mmap failed: %s\\n\", strerror(errno));\n shm_buf = NULL;\n }\n }\n else {\n fprintf(stderr, \"shm_open failed: %s\\n\", strerror(errno));\n }\n \n if(shm_buf != NULL) {\n guint8* data = (guint8*)shm_buf;\n m_image = Gdk::Pixbuf::create_from_data(data, Gdk::COLORSPACE_RGB, false, 8, 320, 200, 320 * 3);\n\n for(int row = 0; row < 200; row++) {\n for(int col = 0; col < 320; col++) {\n \/\/*data++ = row;\n *data++ = 0;\n *data++ = row;\n *data++ = row;\n }\n }\n }\n \/\/memset(data, 128, 3 * sizeof(guint8) * 320 * 200);\n\n }\n catch(const Gio::ResourceError& ex)\n {\n \/\/std::cerr << \"ResourceError: \" << ex.what() << std::endl;\n }\n catch(const Gdk::PixbufError& ex)\n {\n \/\/std::cerr << \"PixbufError: \" << ex.what() << std::endl;\n }\n\n if (m_image) {\n set_size_request(m_image->get_width(), m_image->get_height());\n }\n}\n\nMyArea::~MyArea()\n{\n if(shm_buf != NULL) {\n munmap(shm_buf, 320*200*3);\n }\n if(shm_fd > 0) {\n close(shm_fd);\n shm_unlink(SHARED_FB);\n }\n}\n\nbool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)\n{\n if (!m_image)\n return false;\n\n Gtk::Allocation allocation = get_allocation();\n const int width = allocation.get_width();\n const int height = allocation.get_height();\n\n \/\/ Draw the image in the middle of the drawing area, or (if the image is\n \/\/ larger than the drawing area) draw the middle part of the image.\n Gdk::Cairo::set_source_pixbuf(cr, m_image,\n (width - m_image->get_width())\/2, (height - m_image->get_height())\/2);\n cr->paint();\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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\/\/ A binary wrapper for QuicClient. Connects to --hostname on\n\/\/ --port and requests URLs specified on the command line.\n\/\/\n\/\/ For example:\n\/\/ quic_client --port 6122 \/index.html \/favicon.ico\n\n#include \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"net\/base\/ip_endpoint.h\"\n#include \"net\/tools\/quic\/quic_client.h\"\n\nint32 FLAGS_port = 6121;\nstd::string FLAGS_address = \"127.0.0.1\";\nstd::string FLAGS_hostname = \"localhost\";\n\nint main(int argc, char *argv[]) {\n CommandLine::Init(argc, argv);\n\n\n base::AtExitManager exit_manager;\n\n net::IPAddressNumber addr;\n CHECK(net::ParseIPLiteralToNumber(FLAGS_address, &addr));\n net::tools::QuicClient client(\n net::IPEndPoint(addr, FLAGS_port), FLAGS_hostname);\n\n client.Initialize();\n\n if (!client.Connect()) return 1;\n\n client.SendRequestsAndWaitForResponse(argc, argv);\n return 0;\n}\n<commit_msg>Fix the commandline handling in quic_client.<commit_after>\/\/ 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\/\/ A binary wrapper for QuicClient. Connects to --hostname or --address on\n\/\/ --port and requests URLs specified on the command line.\n\/\/\n\/\/ For example:\n\/\/ quic_client --port 6122 \/index.html \/favicon.ico\n\n#include \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"net\/base\/ip_endpoint.h\"\n#include \"net\/tools\/quic\/quic_client.h\"\n\nint32 FLAGS_port = 6121;\nstd::string FLAGS_address = \"127.0.0.1\";\nstd::string FLAGS_hostname = \"localhost\";\n\nint main(int argc, char *argv[]) {\n CommandLine::Init(argc, argv);\n CommandLine* line = CommandLine::ForCurrentProcess();\n if (line->HasSwitch(\"port\")) {\n int port;\n if (base::StringToInt(line->GetSwitchValueASCII(\"port\"), &port)) {\n FLAGS_port = port;\n }\n }\n if (line->HasSwitch(\"address\")) {\n FLAGS_address = line->GetSwitchValueASCII(\"address\");\n }\n if (line->HasSwitch(\"hostname\")) {\n FLAGS_hostname = line->GetSwitchValueASCII(\"hostname\");\n }\n LOG(INFO) << \"server port: \" << FLAGS_port\n << \" address: \" << FLAGS_address\n << \" hostname: \" << FLAGS_hostname;\n\n base::AtExitManager exit_manager;\n\n net::IPAddressNumber addr;\n CHECK(net::ParseIPLiteralToNumber(FLAGS_address, &addr));\n net::tools::QuicClient client(\n net::IPEndPoint(addr, FLAGS_port), FLAGS_hostname);\n\n client.Initialize();\n\n if (!client.Connect()) return 1;\n\n client.SendRequestsAndWaitForResponse(argc, argv);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QFileDialog>\n#include <memory>\n#include \"lib\/CRC\/CRC32.h\"\n#include \"lib\/File\/File.h\"\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\nnamespace\n{\n QString filters(\"All files (*.*)\");\n}\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n}\n\nMainWindow::~MainWindow()\n{\n}\n\nvoid MainWindow::on_inputPathPushButton_clicked()\n{\n QString inputPath = QFileDialog::getOpenFileName(\n 0, \"Load file\", QDir::currentPath(), filters);\n\n if (inputPath == nullptr)\n return;\n\n ui->inputPathLineEdit->setText(inputPath);\n\n if (ui->outputPathLineEdit->text() == \"\")\n {\n auto inputFileInfo = QFileInfo(inputPath);\n auto outputPath = inputFileInfo.baseName() + \"-patched\";\n if (inputFileInfo.completeSuffix() != \"\")\n outputPath += \".\" + inputFileInfo.completeSuffix();\n ui->outputPathLineEdit->setText(outputPath);\n }\n}\n\nvoid MainWindow::on_outputPathPushButton_clicked()\n{\n QString outputPath = QFileDialog::getSaveFileName(\n 0, \"Save file\", QDir::currentPath(), filters);\n\n if (outputPath == nullptr)\n return;\n\n ui->outputPathLineEdit->setText(outputPath);\n}\n\nvoid MainWindow::on_patchPushButton_clicked()\n{\n try\n {\n uint32_t desiredChecksum = ui->crcLineEdit->text().toULong(nullptr, 16);\n std::string inputPath = ui->inputPathLineEdit->text().toStdString();\n std::string outputPath = ui->outputPathLineEdit->text().toStdString();\n\n std::unique_ptr<CRC> crc(new CRC32);\n\n std::unique_ptr<File> inputFile(File::fromFileName(\n inputPath.c_str(), File::FOPEN_READ | File::FOPEN_BINARY));\n\n std::unique_ptr<File> outputFile(File::fromFileName(\n outputPath.c_str(), File::FOPEN_WRITE | File::FOPEN_BINARY));\n\n File::OffsetType desiredPosition = inputFile->getFileSize();\n\n crc->applyPatch(\n desiredChecksum,\n desiredPosition,\n *inputFile,\n *outputFile,\n false);\n\n puts(\"Done!\"); \/\/TODO\n }\n catch (...)\n {\n puts(\"Error...\"); \/\/TODO\n }\n}\n\n#ifdef WAF\n #include \"gui\/mainwindow.moc\"\n #include \"gui\/mainwindow.cc.moc\"\n#endif\n<commit_msg>Added parent widgets to save and open dialogs<commit_after>#include <QFileDialog>\n#include <memory>\n#include \"lib\/CRC\/CRC32.h\"\n#include \"lib\/File\/File.h\"\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\nnamespace\n{\n QString filters(\"All files (*.*)\");\n}\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n}\n\nMainWindow::~MainWindow()\n{\n}\n\nvoid MainWindow::on_inputPathPushButton_clicked()\n{\n QString inputPath = QFileDialog::getOpenFileName(\n ui->centralWidget, \"Load file\", QDir::currentPath(), filters);\n\n if (inputPath == nullptr)\n return;\n\n ui->inputPathLineEdit->setText(inputPath);\n\n if (ui->outputPathLineEdit->text() == \"\")\n {\n auto inputFileInfo = QFileInfo(inputPath);\n auto outputPath = inputFileInfo.baseName() + \"-patched\";\n if (inputFileInfo.completeSuffix() != \"\")\n outputPath += \".\" + inputFileInfo.completeSuffix();\n ui->outputPathLineEdit->setText(outputPath);\n }\n}\n\nvoid MainWindow::on_outputPathPushButton_clicked()\n{\n QString outputPath = QFileDialog::getSaveFileName(\n ui->centralWidget, \"Save file\", QDir::currentPath(), filters);\n\n if (outputPath == nullptr)\n return;\n\n ui->outputPathLineEdit->setText(outputPath);\n}\n\nvoid MainWindow::on_patchPushButton_clicked()\n{\n try\n {\n uint32_t desiredChecksum = ui->crcLineEdit->text().toULong(nullptr, 16);\n std::string inputPath = ui->inputPathLineEdit->text().toStdString();\n std::string outputPath = ui->outputPathLineEdit->text().toStdString();\n\n std::unique_ptr<CRC> crc(new CRC32);\n\n std::unique_ptr<File> inputFile(File::fromFileName(\n inputPath.c_str(), File::FOPEN_READ | File::FOPEN_BINARY));\n\n std::unique_ptr<File> outputFile(File::fromFileName(\n outputPath.c_str(), File::FOPEN_WRITE | File::FOPEN_BINARY));\n\n File::OffsetType desiredPosition = inputFile->getFileSize();\n\n crc->applyPatch(\n desiredChecksum,\n desiredPosition,\n *inputFile,\n *outputFile,\n false);\n\n puts(\"Done!\"); \/\/TODO\n }\n catch (...)\n {\n puts(\"Error...\"); \/\/TODO\n }\n}\n\n#ifdef WAF\n #include \"gui\/mainwindow.moc\"\n #include \"gui\/mainwindow.cc.moc\"\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ =============================================================================\n\/\/ Type Interfaces -- Title Page\n\/\/ =============================================================================\n\n\/** \\page pageTypeInterfaces Type Interfaces\n *\n * These pages document <em>type interfaces<\/em>: i.e. types which may appear as template\n * parameters, and which must conform to some standard in order to complete their tasks.\n *\n * Documented Type Interfaces in the %Tomographer framwork are:\n *\n * - \\subpage pageInterfaceMatrQ\n * - \\subpage pageInterfaceTomoProblem\n * - \\subpage pageInterfaceRandomWalk\n * - \\subpage pageInterfaceMHWalker\n * - \\subpage pageInterfaceMHRWStatsCollector\n * - \\subpage pageInterfaceTomoValueCalculator\n * - \\subpage pageTaskManagerDispatcher\n *\n *\/\n\n\n\/\/ =============================================================================\n\/\/ MatrQ\n\/\/ =============================================================================\n\n\/** \\page pageInterfaceMatrQ Interface\n *\n * Declares types for dealing with quantum states and POVMs of a fixed dimension which\n * we'll call here \\a dim. See also \\ref Tomographer::MatrQ.\n *\n * \\par typedef ... RealScalar\n * The real scalar type we're working with.\n *\n * \\par typedef ... ComplexScalar\n * The complex scalar type we're working with.\n *\n * \\par typedef ... IntFreqType\n * The integral type to use for measurement counts. Usually \\c int is enough, except if in\n * your experiment you take >1e9 measurements\n *\n * \\par typedef ... MatrixType\n * The type needed to represent a density matrix. This is usually expected to be a Eigen\n * type.\n *\n * \\par MatrixType initMatrixType() const\n * Returns an expression which can be assigned to a \\a MatrixType such that the matrix is\n * initialized to a square \\a dim x \\a dim zero matrix.\n *\n * \\par typedef ... VectorParamType\n * The type needed to represent a X-parameterization of a density matrix. This is usually\n * expected to be a Eigen type.\n *\n * \\par MatrixType initVectorParamType() const\n * Returns an expression which can be assigned to a \\a VectorParamType such that the\n * vector is initialized to a zero column vector with <em>dim*dim<\/em> entries.\n *\n * \\par typedef ... VectorParamNdofType\n * The type needed to represent some parameterization of a density matrix with\n * <em>dim*dim-1<\/em> parameters. This is usually expected to be a Eigen type.\n *\n * \\par MatrixType initVectorParamNdofType() const\n * Returns an expression which can be assigned to a \\a VectorParamNdofType such that the\n * vector is initialized to a zero column vector with <em>dim*dim-1<\/em> entries.\n *\n * \\par typedef ... VectorParamListType\n * The type needed to represent a list of X-parameterizations of e.g. POVM effects, each\n * with <em>dim*dim<\/em> parameters. This is usually expected to be a Eigen type.\n *\n * \\par MatrixType initVectorParamListType(std::size_t length) const\n * Returns an expression which can be assigned to a \\a VectorParamListType such that the\n * list is initialized to a list with \\a length copies of a zero column vector with\n * <em>dim*dim<\/em> entries.\n *\n * \\par typedef ... FreqListType\n * The type needed to represent frequency counts of measurements. This is typically an\n * \\ref Eigen::Array integral type. \n *\n * \\par MatrixType initFreqListType(std::size_t len) const\n * Returns an expression which can be assigned to a \\a FreqListType such that the vector\n * is initialized to \\a len items with zero counts each.\n *\n *\n *\/\n\n\n\/\/ =============================================================================\n\/\/ TomoProblem\n\/\/ =============================================================================\n\n\/** \\page pageInterfaceTomoProblem Interface\n *\n * Stores the data relevant for a tomography problem. Includes:\n *\n * - a \\ref pageInterfaceMatrQ object, which stores the dimension and is able to construct\n * requested types;\n *\n * - cached values of \\a dim, <em>dim2=dim*dim<\/em>, and <em>Ndof=dim*dim-1<\/em>\n *\n * - a factor by which to artificially amplify\/reduce the number of frequency counts\n *\n * - the list of POVM effects and their frequency counts (measurement data)\n *\n * - the maximum likelihood estimate, along with cached values of various of its\n * parameterizations\n *\n * - a method which can calculate the loglikelihood function.\n *\n * See also: \\ref Tomographer::IndepMeasTomoProblem<MatrQ_,LLHValueType_,UseCLoopInstead>\n *\n *\n * \\par const MatrQ matrq;\n * A \\ref pageInterfaceMatrQ object which we may use to create matrices etc.\n *\n * \\par const IntegralType dim;\n * Cached dimension.\n *\n * \\par const IntegralType dim2;\n * Cached value of <em>dim*dim<\/em>\n *\n * \\par const IntegralType Ndof;\n * Cached value of <em>dim*dim-1<\/em>\n *\n * \\par typedef .. LLHValueType;\n * The type to use to store the value of the loglikelihood function calculated by \\a\n * calc_llh().\n *\n * \\par LLHValueType NMeasAmplifyFactor;\n * Factor by which to multiply all measurement frequencies when calculating the\n * loglikelihood function\n * \n * \\par typename MatrQ::VectorParamListType Exn;\n * The POVM Entries, parameterized with \\ref pageParamsX\n *\n * \\par typename MatrQ::FreqListType Nx;\n * The frequency list, i.e. number of times each POVM effect was observed\n *\n * \\par typename MatrQ::MatrixType rho_MLE;\n * Maximum likelihood estimate as density matrix\n *\n * \\par typename MatrQ::MatrixType T_MLE;\n * Maximum likelihood estimate as \\ref pageParamsT of the density matrix\n *\n * \\par typename MatrQ::VectorParamType x_MLE;\n * Maximum likelihood estimate as \\ref pageParamsX\n *\n * \\par LLHValueType calc_llh(const typename MatrQ::VectorParamType & x) const;\n * Calculate the loglikelihood function, defined as\n * \\f[\n * \\lambda\\left(\\rho\\right) = -2\\,\\ln\\,\\tr\\left[B^n\\,\\rho^{\\otimes n}\\right]\\ .\n * \\f]\n * The argument \\a x is the \\ref pageParamsX of the density matrix at which the\n * loglikelihood function should be evaluated.\n *\n *\/\n\n\n\/\/ =============================================================================\n\/\/ MHRWStatsCollector\n\/\/ =============================================================================\n\n\/** \\page pageInterfaceMHRWStatsCollector MHRWStatsCollector Interface\n *\n * A type implementing a \\a MHRWStatsCollector interface is responsible for collecting\n * statistics from samples during a Metropolis-Hastings random walk (see \\ref\n * Tomographer::MHRandomWalk).\n *\n * This type must provide the following members. The members, or the class itself, must be\n * templates with type parameters \\c CountIntType, \\c PointType, \\c FnValueType, and \\c\n * MHRandomWalk. (It is usually most convenient to template the methods themselves, so\n * that you don't have to specify the parameters when instantiating the object.)\n *\n * \\par void init()\n * is called before starting the random walk\n *\n * \\par void thermalizing_done()\n * is called after the thermalizing runs, before starting the \"live\" runs.\n * \n * \\par void done()\n * is called after the random walk is finished.\n *\n * \\par void process_sample(CountIntType, const PointType & pt, FnValueType fnval, MHRandomWalk & rw)\n * is called at the end of each sweep, after the thermalization sweeps have finished. \n * This function is meant to actually take live samples.\n *\n * \\par void raw_move(CountIntType k, bool is_thermalizing, bool is_live_iter, bool accepted, double a, const PointType & newpt, FnValueType newptval, const PointType & curpt, FnValueType curptval, MHRandomWalk & rw)\n * is called after each move during the random walk. Note that if you want to take\n * real samples, use \\c process_sample() instead.\n *\n * \\par\n * \\c k is the iteration number, \\c is_thermalizing is \\c true during the first part\n * of the random walk during the thermalizing runs, \\c is_live_iter is set to \\c true\n * only if a sample is taken at this point, i.e. if not thermalizing and after a full\n * sweep. \\c accepted indicates whether this Metropolis-Hastings move was accepted or\n * not and \\c a gives the ratio of the function which was tested for the move. (Note\n * that \\c a might not be calculated and left to 1 if known to be greater than 1.) \\c\n * newpt and \\c newptval are the new proposal jump point and the function value at\n * that new point. The function value is either the actual value of the function, or\n * its logarithm, or a dummy value, depending on \\c MHWalker::UseFnSyntaxType. \n * Similarly \\c curpt and \\c curptval are the current point and function value. The\n * object \\c rw is a reference to the random walk object instance.\n * \n *\n *\/\n\n\n\n\n\/\/ =============================================================================\n\/\/ MHWalker\n\/\/ =============================================================================\n\n\/** \\page pageInterfaceMHWalker MHWalker Interface\n *\n * A \\a MHWalker compliant type describes a particular Metropolis-Hastings walk on some\n * state space. It takes care for example of providing candidate new points (jump\n * function), and calculating the probability ratio for the jump.\n *\n * \\a MHWalker types are used in particular by:\n * - \\refitem Tomographer::MHRandomWalk.\n *\n * A type implementing the \\a MHWalker interface must provide the following types:\n *\n * \\par typedef ... PointType\n * The type needed to represent a point in state space in which we are performing a\n * random walk. An object of such type is never default-constructed, but always\n * copy-constructed from another \\a PointType. One should also be able to assign a \\a\n * PointType to another \\c PointType (e.g. <code>curpt = other_point<\/code>).\n *\n * \\par typedef ... RealScalar\n * The type needed to represent a step size. This will most likely be a \\c double\n * or some floating-point type.\n *\n * \\par typedef ... FnValueType — required only if UseFnSyntaxType != MHUseFnRelativeValue\n * The return value type of the function evaluated at each point during the\n * Metropolis-Hastings random walk. Usually this is \\c double or some floating-point\n * type. You do not need to provide this typedef if \\c UseFnSyntaxType is set to \\c\n * MHUseFnRelativeValue.\n *\n * A \\a MHWalker must provide the following constant enumeration values:\n *\n * \\par enum { UseFnSyntaxType = ... }\n * Specifies how we calculate the function probability ratio of two points in the\n * random walk. \\c UseFnSyntaxType should be set to one of either \\ref\n * Tomographer::MHUseFnValue, \\ref Tomographer::MHUseFnLogValue, or \\ref\n * Tomographer::MHUseFnRelativeValue. See \\ref\n * labelMHWalkerUseFnSyntaxType \"Role of UseFnSyntaxType\".\n *\n *\n * And must provide the following members:\n *\n * \\par void init()\n *\n * \\par void thermalizing_done()\n *\n * \\par void done()\n *\n * \\par PointType jump_fn(const PointType & curpt, RealScalar step_size)\n *\n * \\par FnValueType fnval(const PointType & curpt) — required only if UseFnSyntaxType == MHUseFnValue\n *\n * \\par FnValueType fnlogval(const PointType & curpt) — required only if UseFnSyntaxType == MHUseFnLogValue\n *\n * \\par double fnrelval(const PointType & newpt, const PointType & curpt) — required only if UseFnSyntaxType == MHUseFnRelativeValue\n *\n * <br><br>\n * \n * \\anchor labelMHWalkerUseFnSyntaxType\n * \\par Role of \\c UseFnSyntaxType:\n *\n * - MHUseFnValue --> use MHWalker::fnval(newpt)\n * - MHUseFnLogValue --> use MHWalker::fnlogval(newpt)\n * - MHUseFnRelativeValue --> use MHWalker::fnrelval(newpt, curpt)\n *\n *\n * .........................\n *\n *\/\n\n\n\n\n\/\/ =============================================================================\n\/\/ RandomWalk\n\/\/ =============================================================================\n\n\n\n\/** \\page pageInterfaceRandomWalk RandomWalk Interface\n *\n * The \\a RandomWalk type is responsible for actually implementing the random walk. It\n * should keep the current state of the random walk in memory and update it when the \\c\n * move() function is called.\n *\n * \\a RandomWalk types are used in particular by:\n * - \\refitem Tomographer::RandomWalkBase.\n *\n * The \\a RandomWalk type should provide the following typedef member:\n *\n * \\par typedef ... CountIntType\n * This (usually an <code>unsigned int<\/code> or <code>unsigned long<\/code>)\n * should specify which type to use to count the iterations. This is also the\n * return type of \\c n_sweep() etc.\n *\n * \\a RandomWalk needs to provide the following members, which are called at the\n * appropriate times:\n *\n * \\par CountIntType RandomWalk::n_sweep()\n * Number of iterations that compose a \"sweep\".\n *\n * \\par CountIntType RandomWalk::n_therm()\n * Number of thermalizing sweeps to perform.\n *\n * \\par CountIntType RandomWalk::n_run()\n * Number of live sweeps to perform.\n *\n * \\par void RandomWalk::move(CountIntType k, bool is_thermalizing, bool is_live_iter)\n * Is called to perform a new random walk iteration. The random walk object is\n * responsible for keeping the current state of the random walk in memory,\n * and for processing a jump function. This method should update the internal\n * state of the random walk. This function does not return anything. \\c k is the\n * raw iteration count, starting at zero (and which is reset to zero after the\n * thermalizing sweeps). \\c is_thermalizing is \\c true during the thermalizing\n * runs, \\c false otherwise. \\c is_live_iter is \\c true when a live sample is\n * taken, only once every sweep after the thermalization runs.\n *\n * \\par void RandomWalk::process_sample(CountIntType k)\n * Is called for each \"live\" point for which a sample should be taken. The point\n * in question is the current state of the random walk. This only happens after\n * thermalization, and at the last iteration of a sweep.\n *\n * \\par void RandomWalk::init()\n * Is called before starting the random walk. The RandomWalk may perform custom\n * last-minute initializations if required.\n *\n * \\par void RandomWalk::thermalizing_done()\n * Is called after the thermalizing runs and before starting the live runs.\n *\n * \\par void RandomWalk::done()\n * Is called after the random walk is finished. This happens after the given\n * number of iterations were reached.\n *\n *\/\n\n\n\/** \\page pageInterfaceTomoValueCalculator TomoValueCalculator Interface\n *\n * \\todo ............ doc. ..................\n *\n * NOTE: must be copy-constructible, and different threads must be able to operate safely\n * on different copies.\n *\/\n<commit_msg>fixed minor stuff<commit_after>\n\/\/ =============================================================================\n\/\/ Type Interfaces -- Title Page\n\/\/ =============================================================================\n\n\/** \\page pageTypeInterfaces Type Interfaces\n *\n * These pages document <em>type interfaces<\/em>: i.e. types which may appear as template\n * parameters, and which must conform to some standard in order to complete their tasks.\n *\n * Documented Type Interfaces in the %Tomographer framwork are:\n *\n * - \\subpage pageInterfaceMatrQ\n * - \\subpage pageInterfaceTomoProblem\n * - \\subpage pageInterfaceRandomWalk\n * - \\subpage pageInterfaceMHWalker\n * - \\subpage pageInterfaceMHRWStatsCollector\n * - \\subpage pageInterfaceTomoValueCalculator\n * - \\subpage pageTaskManagerDispatcher\n *\n *\/\n\n\n\/\/ =============================================================================\n\/\/ MatrQ\n\/\/ =============================================================================\n\n\/** \\page pageInterfaceMatrQ MatrQ Interface\n *\n * Declares types for dealing with quantum states and POVMs of a fixed dimension which\n * we'll call here \\a dim. See also \\ref Tomographer::MatrQ.\n *\n * \\par typedef ... RealScalar\n * The real scalar type we're working with.\n *\n * \\par typedef ... ComplexScalar\n * The complex scalar type we're working with.\n *\n * \\par typedef ... IntFreqType\n * The integral type to use for measurement counts. Usually \\c int is enough, except if in\n * your experiment you take >1e9 measurements\n *\n * \\par typedef ... MatrixType\n * The type needed to represent a density matrix. This is usually expected to be a Eigen\n * type.\n *\n * \\par MatrixType initMatrixType() const\n * Returns an expression which can be assigned to a \\a MatrixType such that the matrix is\n * initialized to a square \\a dim x \\a dim zero matrix.\n *\n * \\par typedef ... VectorParamType\n * The type needed to represent a X-parameterization of a density matrix. This is usually\n * expected to be a Eigen type.\n *\n * \\par MatrixType initVectorParamType() const\n * Returns an expression which can be assigned to a \\a VectorParamType such that the\n * vector is initialized to a zero column vector with <em>dim*dim<\/em> entries.\n *\n * \\par typedef ... VectorParamNdofType\n * The type needed to represent some parameterization of a density matrix with\n * <em>dim*dim-1<\/em> parameters. This is usually expected to be a Eigen type.\n *\n * \\par MatrixType initVectorParamNdofType() const\n * Returns an expression which can be assigned to a \\a VectorParamNdofType such that the\n * vector is initialized to a zero column vector with <em>dim*dim-1<\/em> entries.\n *\n * \\par typedef ... VectorParamListType\n * The type needed to represent a list of X-parameterizations of e.g. POVM effects, each\n * with <em>dim*dim<\/em> parameters. This is usually expected to be a Eigen type.\n *\n * \\par MatrixType initVectorParamListType(std::size_t length) const\n * Returns an expression which can be assigned to a \\a VectorParamListType such that the\n * list is initialized to a list with \\a length copies of a zero column vector with\n * <em>dim*dim<\/em> entries.\n *\n * \\par typedef ... FreqListType\n * The type needed to represent frequency counts of measurements. This is typically an\n * \\ref Eigen::Array integral type. \n *\n * \\par MatrixType initFreqListType(std::size_t len) const\n * Returns an expression which can be assigned to a \\a FreqListType such that the vector\n * is initialized to \\a len items with zero counts each.\n *\n *\n *\/\n\n\n\/\/ =============================================================================\n\/\/ TomoProblem\n\/\/ =============================================================================\n\n\/** \\page pageInterfaceTomoProblem TomoProblem Interface\n *\n * Stores the data relevant for a tomography problem. Includes:\n *\n * - a \\ref pageInterfaceMatrQ object, which stores the dimension and is able to construct\n * requested types;\n *\n * - cached values of \\a dim, <em>dim2=dim*dim<\/em>, and <em>Ndof=dim*dim-1<\/em>\n *\n * - a factor by which to artificially amplify\/reduce the number of frequency counts\n *\n * - the list of POVM effects and their frequency counts (measurement data)\n *\n * - the maximum likelihood estimate, along with cached values of various of its\n * parameterizations\n *\n * - a method which can calculate the loglikelihood function.\n *\n * See also: \\ref Tomographer::IndepMeasTomoProblem<MatrQ_,LLHValueType_,UseCLoopInstead>\n *\n *\n * \\par const MatrQ matrq;\n * A \\ref pageInterfaceMatrQ object which we may use to create matrices etc.\n *\n * \\par const IntegralType dim;\n * Cached dimension.\n *\n * \\par const IntegralType dim2;\n * Cached value of <em>dim*dim<\/em>\n *\n * \\par const IntegralType Ndof;\n * Cached value of <em>dim*dim-1<\/em>\n *\n * \\par typedef .. LLHValueType;\n * The type to use to store the value of the loglikelihood function calculated by \\a\n * calc_llh().\n *\n * \\par LLHValueType NMeasAmplifyFactor;\n * Factor by which to multiply all measurement frequencies when calculating the\n * loglikelihood function\n * \n * \\par typename MatrQ::VectorParamListType Exn;\n * The POVM Entries, parameterized with \\ref pageParamsX\n *\n * \\par typename MatrQ::FreqListType Nx;\n * The frequency list, i.e. number of times each POVM effect was observed\n *\n * \\par typename MatrQ::MatrixType rho_MLE;\n * Maximum likelihood estimate as density matrix\n *\n * \\par typename MatrQ::MatrixType T_MLE;\n * Maximum likelihood estimate as \\ref pageParamsT of the density matrix\n *\n * \\par typename MatrQ::VectorParamType x_MLE;\n * Maximum likelihood estimate as \\ref pageParamsX\n *\n * \\par LLHValueType calc_llh(const typename MatrQ::VectorParamType & x) const;\n * Calculate the loglikelihood function, defined as\n * \\f[\n * \\lambda\\left(\\rho\\right) = -2\\,\\ln\\,\\mathrm{tr}\\left[B^n\\,\\rho^{\\otimes n}\\right]\\ .\n * \\f]\n * The argument \\a x is the \\ref pageParamsX of the density matrix at which the\n * loglikelihood function should be evaluated.\n *\n *\/\n\n\n\/\/ =============================================================================\n\/\/ MHRWStatsCollector\n\/\/ =============================================================================\n\n\/** \\page pageInterfaceMHRWStatsCollector MHRWStatsCollector Interface\n *\n * A type implementing a \\a MHRWStatsCollector interface is responsible for collecting\n * statistics from samples during a Metropolis-Hastings random walk (see \\ref\n * Tomographer::MHRandomWalk).\n *\n * This type must provide the following members. The members, or the class itself, must be\n * templates with type parameters \\c CountIntType, \\c PointType, \\c FnValueType, and \\c\n * MHRandomWalk. (It is usually most convenient to template the methods themselves, so\n * that you don't have to specify the parameters when instantiating the object.)\n *\n * \\par void init()\n * is called before starting the random walk\n *\n * \\par void thermalizing_done()\n * is called after the thermalizing runs, before starting the \"live\" runs.\n * \n * \\par void done()\n * is called after the random walk is finished.\n *\n * \\par void process_sample(CountIntType, const PointType & pt, FnValueType fnval, MHRandomWalk & rw)\n * is called at the end of each sweep, after the thermalization sweeps have finished. \n * This function is meant to actually take live samples.\n *\n * \\par void raw_move(CountIntType k, bool is_thermalizing, bool is_live_iter, bool accepted, double a, const PointType & newpt, FnValueType newptval, const PointType & curpt, FnValueType curptval, MHRandomWalk & rw)\n * is called after each move during the random walk. Note that if you want to take\n * real samples, use \\c process_sample() instead.\n *\n * \\par\n * \\c k is the iteration number, \\c is_thermalizing is \\c true during the first part\n * of the random walk during the thermalizing runs, \\c is_live_iter is set to \\c true\n * only if a sample is taken at this point, i.e. if not thermalizing and after a full\n * sweep. \\c accepted indicates whether this Metropolis-Hastings move was accepted or\n * not and \\c a gives the ratio of the function which was tested for the move. (Note\n * that \\c a might not be calculated and left to 1 if known to be greater than 1.) \\c\n * newpt and \\c newptval are the new proposal jump point and the function value at\n * that new point. The function value is either the actual value of the function, or\n * its logarithm, or a dummy value, depending on \\c MHWalker::UseFnSyntaxType. \n * Similarly \\c curpt and \\c curptval are the current point and function value. The\n * object \\c rw is a reference to the random walk object instance.\n * \n *\n *\/\n\n\n\n\n\/\/ =============================================================================\n\/\/ MHWalker\n\/\/ =============================================================================\n\n\/** \\page pageInterfaceMHWalker MHWalker Interface\n *\n * A \\a MHWalker compliant type describes a particular Metropolis-Hastings walk on some\n * state space. It takes care for example of providing candidate new points (jump\n * function), and calculating the probability ratio for the jump.\n *\n * \\a MHWalker types are used in particular by:\n * - \\refitem Tomographer::MHRandomWalk.\n *\n * A type implementing the \\a MHWalker interface must provide the following types:\n *\n * \\par typedef ... PointType\n * The type needed to represent a point in state space in which we are performing a\n * random walk. An object of such type is never default-constructed, but always\n * copy-constructed from another \\a PointType. One should also be able to assign a \\a\n * PointType to another \\c PointType (e.g. <code>curpt = other_point<\/code>).\n *\n * \\par typedef ... RealScalar\n * The type needed to represent a step size. This will most likely be a \\c double\n * or some floating-point type.\n *\n * \\par typedef ... FnValueType — required only if UseFnSyntaxType != MHUseFnRelativeValue\n * The return value type of the function evaluated at each point during the\n * Metropolis-Hastings random walk. Usually this is \\c double or some floating-point\n * type. You do not need to provide this typedef if \\c UseFnSyntaxType is set to \\c\n * MHUseFnRelativeValue.\n *\n * A \\a MHWalker must provide the following constant enumeration values:\n *\n * \\par enum { UseFnSyntaxType = ... }\n * Specifies how we calculate the function probability ratio of two points in the\n * random walk. \\c UseFnSyntaxType should be set to one of either \\ref\n * Tomographer::MHUseFnValue, \\ref Tomographer::MHUseFnLogValue, or \\ref\n * Tomographer::MHUseFnRelativeValue. See \\ref\n * labelMHWalkerUseFnSyntaxType \"Role of UseFnSyntaxType\".\n *\n *\n * And must provide the following members:\n *\n * \\par void init()\n *\n * \\par void thermalizing_done()\n *\n * \\par void done()\n *\n * \\par PointType jump_fn(const PointType & curpt, RealScalar step_size)\n *\n * \\par FnValueType fnval(const PointType & curpt) — required only if UseFnSyntaxType == MHUseFnValue\n *\n * \\par FnValueType fnlogval(const PointType & curpt) — required only if UseFnSyntaxType == MHUseFnLogValue\n *\n * \\par double fnrelval(const PointType & newpt, const PointType & curpt) — required only if UseFnSyntaxType == MHUseFnRelativeValue\n *\n * <br><br>\n * \n * \\anchor labelMHWalkerUseFnSyntaxType\n * \\par Role of \\c UseFnSyntaxType:\n *\n * - MHUseFnValue --> use MHWalker::fnval(newpt)\n * - MHUseFnLogValue --> use MHWalker::fnlogval(newpt)\n * - MHUseFnRelativeValue --> use MHWalker::fnrelval(newpt, curpt)\n *\n *\n * .........................\n *\n *\/\n\n\n\n\n\/\/ =============================================================================\n\/\/ RandomWalk\n\/\/ =============================================================================\n\n\n\n\/** \\page pageInterfaceRandomWalk RandomWalk Interface\n *\n * The \\a RandomWalk type is responsible for actually implementing the random walk. It\n * should keep the current state of the random walk in memory and update it when the \\c\n * move() function is called.\n *\n * \\a RandomWalk types are used in particular by:\n * - \\refitem Tomographer::RandomWalkBase.\n *\n * The \\a RandomWalk type should provide the following typedef member:\n *\n * \\par typedef ... CountIntType\n * This (usually an <code>unsigned int<\/code> or <code>unsigned long<\/code>)\n * should specify which type to use to count the iterations. This is also the\n * return type of \\c n_sweep() etc.\n *\n * \\a RandomWalk needs to provide the following members, which are called at the\n * appropriate times:\n *\n * \\par CountIntType RandomWalk::n_sweep()\n * Number of iterations that compose a \"sweep\".\n *\n * \\par CountIntType RandomWalk::n_therm()\n * Number of thermalizing sweeps to perform.\n *\n * \\par CountIntType RandomWalk::n_run()\n * Number of live sweeps to perform.\n *\n * \\par void RandomWalk::move(CountIntType k, bool is_thermalizing, bool is_live_iter)\n * Is called to perform a new random walk iteration. The random walk object is\n * responsible for keeping the current state of the random walk in memory,\n * and for processing a jump function. This method should update the internal\n * state of the random walk. This function does not return anything. \\c k is the\n * raw iteration count, starting at zero (and which is reset to zero after the\n * thermalizing sweeps). \\c is_thermalizing is \\c true during the thermalizing\n * runs, \\c false otherwise. \\c is_live_iter is \\c true when a live sample is\n * taken, only once every sweep after the thermalization runs.\n *\n * \\par void RandomWalk::process_sample(CountIntType k)\n * Is called for each \"live\" point for which a sample should be taken. The point\n * in question is the current state of the random walk. This only happens after\n * thermalization, and at the last iteration of a sweep.\n *\n * \\par void RandomWalk::init()\n * Is called before starting the random walk. The RandomWalk may perform custom\n * last-minute initializations if required.\n *\n * \\par void RandomWalk::thermalizing_done()\n * Is called after the thermalizing runs and before starting the live runs.\n *\n * \\par void RandomWalk::done()\n * Is called after the random walk is finished. This happens after the given\n * number of iterations were reached.\n *\n *\/\n\n\n\/** \\page pageInterfaceTomoValueCalculator TomoValueCalculator Interface\n *\n * \\todo ............ doc. ..................\n *\n * NOTE: must be copy-constructible, and different threads must be able to operate safely\n * on different copies.\n *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Tape.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 03\/12\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Tape.hpp\"\n\nusing namespace Electron;\n\nTape::Tape() :\n\t\tTapePlayer(2000000),\n\t\tis_running_(false),\n\t\tdata_register_(0),\n\t\tdelegate_(nullptr),\n\t\toutput_({.bits_remaining_until_empty = 0, .cycles_into_pulse = 0}),\n\t\tlast_posted_interrupt_status_(0),\n\t\tinterrupt_status_(0) {}\n\nvoid Tape::push_tape_bit(uint16_t bit) {\n\tdata_register_ = (uint16_t)((data_register_ >> 1) | (bit << 10));\n\n\tif(input_.minimum_bits_until_full) input_.minimum_bits_until_full--;\n\tif(input_.minimum_bits_until_full == 8) interrupt_status_ &= ~Interrupt::ReceiveDataFull;\n\tif(!input_.minimum_bits_until_full) {\n\t\tif((data_register_&0x3) == 0x1) {\n\t\t\tinterrupt_status_ |= Interrupt::ReceiveDataFull;\n\t\t\tif(is_in_input_mode_) input_.minimum_bits_until_full = 9;\n\t\t}\n\t}\n\n\tif(output_.bits_remaining_until_empty)\toutput_.bits_remaining_until_empty--;\n\tif(!output_.bits_remaining_until_empty)\tinterrupt_status_ |= Interrupt::TransmitDataEmpty;\n\n\tif(data_register_ == 0x3ff)\tinterrupt_status_ |= Interrupt::HighToneDetect;\n\telse\t\t\t\t\t\tinterrupt_status_ &= ~Interrupt::HighToneDetect;\n\n\tevaluate_interrupts();\n}\n\nvoid Tape::evaluate_interrupts() {\n\tif(last_posted_interrupt_status_ != interrupt_status_) {\n\t\tlast_posted_interrupt_status_ = interrupt_status_;\n\t\tif(delegate_) delegate_->tape_did_change_interrupt_status(this);\n\t}\n}\n\nvoid Tape::clear_interrupts(uint8_t interrupts) {\n\tinterrupt_status_ &= ~interrupts;\n\tevaluate_interrupts();\n}\n\nvoid Tape::set_is_in_input_mode(bool is_in_input_mode) {\n\tis_in_input_mode_ = is_in_input_mode;\n}\n\nvoid Tape::set_counter(uint8_t value) {\n\toutput_.cycles_into_pulse = 0;\n\toutput_.bits_remaining_until_empty = 0;\n}\n\nvoid Tape::set_data_register(uint8_t value) {\n\tdata_register_ = (uint16_t)((value << 2) | 1);\n\toutput_.bits_remaining_until_empty = 9;\n}\n\nuint8_t Tape::get_data_register() {\n\treturn (uint8_t)(data_register_ >> 2);\n}\n\nvoid Tape::process_input_pulse(Storage::Tape::Tape::Pulse pulse) {\n\tcrossings_[0] = crossings_[1];\n\tcrossings_[1] = crossings_[2];\n\tcrossings_[2] = crossings_[3];\n\n\tcrossings_[3] = Tape::Unrecognised;\n\tif(pulse.type != Storage::Tape::Tape::Pulse::Zero) {\n\t\tfloat pulse_length = (float)pulse.length.length \/ (float)pulse.length.clock_rate;\n\t\tif(pulse_length >= 0.35 \/ 2400.0 && pulse_length < 0.7 \/ 2400.0) crossings_[3] = Tape::Short;\n\t\tif(pulse_length >= 0.35 \/ 1200.0 && pulse_length < 0.7 \/ 1200.0) crossings_[3] = Tape::Long;\n\t}\n\n\tif(crossings_[0] == Tape::Long && crossings_[1] == Tape::Long) {\n\t\tpush_tape_bit(0);\n\t\tcrossings_[0] = crossings_[1] = Tape::Recognised;\n\t} else {\n\t\tif(crossings_[0] == Tape::Short && crossings_[1] == Tape::Short && crossings_[2] == Tape::Short && crossings_[3] == Tape::Short) {\n\t\t\tpush_tape_bit(1);\n\t\t\tcrossings_[0] = crossings_[1] =\n\t\t\tcrossings_[2] = crossings_[3] = Tape::Recognised;\n\t\t}\n\t}\n}\n\nvoid Tape::run_for_cycles(unsigned int number_of_cycles) {\n\tif(is_enabled_) {\n\t\tif(is_in_input_mode_) {\n\t\t\tif(is_running_) {\n\t\t\t\tTapePlayer::run_for_cycles((int)number_of_cycles);\n\t\t\t}\n\t\t} else {\n\t\t\toutput_.cycles_into_pulse += number_of_cycles;\n\t\t\twhile(output_.cycles_into_pulse > 1664) {\t\/\/ 1664 = the closest you can get to 1200 baud if you're looking for something\n\t\t\t\toutput_.cycles_into_pulse -= 1664;\t\t\/\/ that divides the 125,000Hz clock that the sound divider runs off.\n\t\t\t\tpush_tape_bit(1);\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Oh yuck, it looks like I've repeated this same test in two different places. Must figure out where to factor it out to. But in the meantime, the emulated Electron has just loaded its first CSW.<commit_after>\/\/\n\/\/ Tape.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 03\/12\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Tape.hpp\"\n\nusing namespace Electron;\n\nTape::Tape() :\n\t\tTapePlayer(2000000),\n\t\tis_running_(false),\n\t\tdata_register_(0),\n\t\tdelegate_(nullptr),\n\t\toutput_({.bits_remaining_until_empty = 0, .cycles_into_pulse = 0}),\n\t\tlast_posted_interrupt_status_(0),\n\t\tinterrupt_status_(0) {}\n\nvoid Tape::push_tape_bit(uint16_t bit) {\n\tdata_register_ = (uint16_t)((data_register_ >> 1) | (bit << 10));\n\n\tif(input_.minimum_bits_until_full) input_.minimum_bits_until_full--;\n\tif(input_.minimum_bits_until_full == 8) interrupt_status_ &= ~Interrupt::ReceiveDataFull;\n\tif(!input_.minimum_bits_until_full) {\n\t\tif((data_register_&0x3) == 0x1) {\n\t\t\tinterrupt_status_ |= Interrupt::ReceiveDataFull;\n\t\t\tif(is_in_input_mode_) input_.minimum_bits_until_full = 9;\n\t\t}\n\t}\n\n\tif(output_.bits_remaining_until_empty)\toutput_.bits_remaining_until_empty--;\n\tif(!output_.bits_remaining_until_empty)\tinterrupt_status_ |= Interrupt::TransmitDataEmpty;\n\n\tif(data_register_ == 0x3ff)\tinterrupt_status_ |= Interrupt::HighToneDetect;\n\telse\t\t\t\t\t\tinterrupt_status_ &= ~Interrupt::HighToneDetect;\n\n\tevaluate_interrupts();\n}\n\nvoid Tape::evaluate_interrupts() {\n\tif(last_posted_interrupt_status_ != interrupt_status_) {\n\t\tlast_posted_interrupt_status_ = interrupt_status_;\n\t\tif(delegate_) delegate_->tape_did_change_interrupt_status(this);\n\t}\n}\n\nvoid Tape::clear_interrupts(uint8_t interrupts) {\n\tinterrupt_status_ &= ~interrupts;\n\tevaluate_interrupts();\n}\n\nvoid Tape::set_is_in_input_mode(bool is_in_input_mode) {\n\tis_in_input_mode_ = is_in_input_mode;\n}\n\nvoid Tape::set_counter(uint8_t value) {\n\toutput_.cycles_into_pulse = 0;\n\toutput_.bits_remaining_until_empty = 0;\n}\n\nvoid Tape::set_data_register(uint8_t value) {\n\tdata_register_ = (uint16_t)((value << 2) | 1);\n\toutput_.bits_remaining_until_empty = 9;\n}\n\nuint8_t Tape::get_data_register() {\n\treturn (uint8_t)(data_register_ >> 2);\n}\n\nvoid Tape::process_input_pulse(Storage::Tape::Tape::Pulse pulse) {\n\tcrossings_[0] = crossings_[1];\n\tcrossings_[1] = crossings_[2];\n\tcrossings_[2] = crossings_[3];\n\n\tcrossings_[3] = Tape::Unrecognised;\n\tif(pulse.type != Storage::Tape::Tape::Pulse::Zero) {\n\t\tfloat pulse_length = (float)pulse.length.length \/ (float)pulse.length.clock_rate;\n\t\tif(pulse_length >= 0.35 \/ 2400.0 && pulse_length < 0.7 \/ 1200.0) {\n\t\t\tcrossings_[3] = pulse_length > 1.0 \/ 3000.0 ? Tape::Long : Tape::Short;\n\t\t}\n\/\/\t\tif(pulse_length >= 0.35 \/ 2400.0 && pulse_length < 0.7 \/ 2400.0) crossings_[3] = Tape::Short;\n\/\/\t\tif(pulse_length >= 0.35 \/ 1200.0 && pulse_length < 0.7 \/ 1200.0) crossings_[3] = Tape::Long;\n\t}\n\n\tif(crossings_[0] == Tape::Long && crossings_[1] == Tape::Long) {\n\t\tpush_tape_bit(0);\n\t\tcrossings_[0] = crossings_[1] = Tape::Recognised;\n\t} else {\n\t\tif(crossings_[0] == Tape::Short && crossings_[1] == Tape::Short && crossings_[2] == Tape::Short && crossings_[3] == Tape::Short) {\n\t\t\tpush_tape_bit(1);\n\t\t\tcrossings_[0] = crossings_[1] =\n\t\t\tcrossings_[2] = crossings_[3] = Tape::Recognised;\n\t\t}\n\t}\n}\n\nvoid Tape::run_for_cycles(unsigned int number_of_cycles) {\n\tif(is_enabled_) {\n\t\tif(is_in_input_mode_) {\n\t\t\tif(is_running_) {\n\t\t\t\tTapePlayer::run_for_cycles((int)number_of_cycles);\n\t\t\t}\n\t\t} else {\n\t\t\toutput_.cycles_into_pulse += number_of_cycles;\n\t\t\twhile(output_.cycles_into_pulse > 1664) {\t\/\/ 1664 = the closest you can get to 1200 baud if you're looking for something\n\t\t\t\toutput_.cycles_into_pulse -= 1664;\t\t\/\/ that divides the 125,000Hz clock that the sound divider runs off.\n\t\t\t\tpush_tape_bit(1);\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkFileWriterSelector.h\"\n\n#include <mitkFileWriterRegistry.h>\n#include <mitkCoreServices.h>\n#include <mitkIMimeTypeProvider.h>\n#include <mitkBaseData.h>\n\n#include <usServiceReference.h>\n#include <usServiceProperties.h>\n#include <usAny.h>\n\n#include <itksys\/SystemTools.hxx>\n\n#include <set>\n#include <limits>\n#include <iterator>\n\nnamespace mitk {\n\nstruct FileWriterSelector::Item::Impl : us::SharedData\n{\n Impl()\n : m_FileWriter(NULL)\n , m_ConfidenceLevel(IFileWriter::Unsupported)\n , m_BaseDataIndex(0)\n , m_Id(-1)\n {}\n\n us::ServiceReference<IFileWriter> m_FileWriterRef;\n IFileWriter* m_FileWriter;\n IFileWriter::ConfidenceLevel m_ConfidenceLevel;\n std::size_t m_BaseDataIndex;\n MimeType m_MimeType;\n long m_Id;\n};\n\nstruct FileWriterSelector::Impl : us::SharedData\n{\n Impl()\n : m_BestId(-1)\n , m_SelectedId(m_BestId)\n {}\n\n Impl(const Impl& other)\n : us::SharedData(other)\n , m_BestId(-1)\n , m_SelectedId(m_BestId)\n {}\n\n FileWriterRegistry m_WriterRegistry;\n std::map<long, FileWriterSelector::Item> m_Items;\n std::set<MimeType> m_MimeTypes;\n long m_BestId;\n long m_SelectedId;\n};\n\nFileWriterSelector::FileWriterSelector(const FileWriterSelector& other)\n : m_Data(other.m_Data)\n{\n}\n\nFileWriterSelector::FileWriterSelector(const BaseData* baseData, const std::string& mimeType,\n const std::string& path)\n : m_Data(new Impl)\n{\n mitk::CoreServicePointer<mitk::IMimeTypeProvider> mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider());\n\n std::vector<FileWriterRegistry::WriterReference> refs;\n\n std::string destMimeType = mimeType;\n if (destMimeType.empty() && !path.empty())\n {\n \/\/ try to derive a mime-type from the file\n std::vector<MimeType> mimeTypes = mimeTypeProvider->GetMimeTypesForFile(path);\n if (!mimeTypes.empty())\n {\n for( unsigned int index = 0; index < mimeTypes.size(); index++)\n {\n std::vector<FileWriterRegistry::WriterReference> tempRefs = m_Data->m_WriterRegistry.GetReferences(baseData, mimeTypes.at(index).GetName());\n for( unsigned int innerIndex = 0; innerIndex < tempRefs.size(); innerIndex++)\n {\n refs.push_back( tempRefs.at(innerIndex) );\n }\n }\n }\n else if (!itksys::SystemTools::GetFilenameExtension(path).empty())\n {\n \/\/ If there are no suitable mime-type for the file AND an extension\n \/\/ was supplied, we stop here.\n return;\n }\n }\n else\n {\n refs = m_Data->m_WriterRegistry.GetReferences(baseData, destMimeType);\n }\n\n std::vector<std::string> classHierarchy = baseData->GetClassHierarchy();\n\n \/\/ Get all writers and their mime types for the given base data type\n Item bestItem;\n for (std::vector<FileWriterRegistry::WriterReference>::const_iterator iter = refs.begin(),\n iterEnd = refs.end(); iter != iterEnd; ++iter)\n {\n std::string mimeTypeName = iter->GetProperty(IFileWriter::PROP_MIMETYPE()).ToString();\n if (!mimeTypeName.empty())\n {\n MimeType mimeType = mimeTypeProvider->GetMimeTypeForName(mimeTypeName);\n if (mimeType.IsValid())\n {\n \/\/ There is a registered mime-type for this writer. Now get the confidence level\n \/\/ of this writer for writing the given base data object.\n\n IFileWriter* writer = m_Data->m_WriterRegistry.GetWriter(*iter);\n if (writer == NULL) continue;\n try\n {\n writer->SetInput(baseData);\n IFileWriter::ConfidenceLevel confidenceLevel = writer->GetConfidenceLevel();\n if (confidenceLevel == IFileWriter::Unsupported)\n {\n continue;\n }\n\n std::string baseDataType = iter->GetProperty(IFileWriter::PROP_BASEDATA_TYPE()).ToString();\n std::vector<std::string>::iterator idxIter =\n std::find(classHierarchy.begin(), classHierarchy.end(), baseDataType);\n std::size_t baseDataIndex = std::numeric_limits<std::size_t>::max();\n if (idxIter != classHierarchy.end())\n {\n baseDataIndex = std::distance(classHierarchy.begin(), idxIter);\n }\n\n Item item;\n item.d->m_FileWriterRef = *iter;\n item.d->m_FileWriter = writer;\n item.d->m_ConfidenceLevel = confidenceLevel;\n item.d->m_BaseDataIndex = baseDataIndex;\n item.d->m_MimeType = mimeType;\n item.d->m_Id = us::any_cast<long>(iter->GetProperty(us::ServiceConstants::SERVICE_ID()));\n m_Data->m_Items.insert(std::make_pair(item.d->m_Id, item));\n m_Data->m_MimeTypes.insert(mimeType);\n if (!bestItem.GetReference() || bestItem < item)\n {\n bestItem = item;\n }\n }\n catch (const us::BadAnyCastException& e)\n {\n MITK_WARN << \"Unexpected: \" << e.what();\n }\n catch (const std::exception& e)\n {\n \/\/ Log the error but continue\n MITK_WARN << \"IFileWriter::GetConfidenceLevel exception: \" << e.what();\n }\n }\n }\n }\n\n if (bestItem.GetReference())\n {\n m_Data->m_BestId = bestItem.GetServiceId();\n m_Data->m_SelectedId = m_Data->m_BestId;\n }\n}\n\nFileWriterSelector::~FileWriterSelector()\n{\n}\n\nFileWriterSelector& FileWriterSelector::operator=(const FileWriterSelector& other)\n{\n m_Data = other.m_Data;\n return *this;\n}\n\nbool FileWriterSelector::IsEmpty() const\n{\n return m_Data->m_Items.empty();\n}\n\nstd::vector<FileWriterSelector::Item> FileWriterSelector::Get(const std::string& mimeType) const\n{\n std::vector<Item> result;\n for (std::map<long, Item>::const_iterator iter = m_Data->m_Items.begin(),\n iterEnd = m_Data->m_Items.end(); iter != iterEnd; ++iter)\n {\n if (mimeType.empty() || iter->second.GetMimeType().GetName() == mimeType)\n {\n result.push_back(iter->second);\n }\n }\n std::sort(result.begin(), result.end());\n return result;\n}\n\nstd::vector<FileWriterSelector::Item> FileWriterSelector::Get() const\n{\n return Get(this->GetSelected().d->m_MimeType.GetName());\n}\n\nFileWriterSelector::Item FileWriterSelector::Get(long id) const\n{\n std::map<long, Item>::const_iterator iter = m_Data->m_Items.find(id);\n if (iter != m_Data->m_Items.end())\n {\n return iter->second;\n }\n return Item();\n}\n\nFileWriterSelector::Item FileWriterSelector::GetDefault() const\n{\n return Get(m_Data->m_BestId);\n}\n\nlong FileWriterSelector::GetDefaultId() const\n{\n return m_Data->m_BestId;\n}\n\nFileWriterSelector::Item FileWriterSelector::GetSelected() const\n{\n return Get(m_Data->m_SelectedId);\n}\n\nlong FileWriterSelector::GetSelectedId() const\n{\n return m_Data->m_SelectedId;\n}\n\nbool FileWriterSelector::Select(const std::string& mimeType)\n{\n std::vector<Item> items = Get(mimeType);\n if (items.empty()) return false;\n return Select(items.back());\n}\n\nbool FileWriterSelector::Select(const FileWriterSelector::Item& item)\n{\n return Select(item.d->m_Id);\n}\n\nbool FileWriterSelector::Select(long id)\n{\n if (id > -1)\n {\n if (m_Data->m_Items.find(id) == m_Data->m_Items.end())\n {\n return false;\n }\n m_Data->m_SelectedId = id;\n return true;\n }\n return false;\n}\n\nstd::vector<MimeType> FileWriterSelector::GetMimeTypes() const\n{\n std::vector<MimeType> result;\n result.reserve(m_Data->m_MimeTypes.size());\n result.assign(m_Data->m_MimeTypes.begin(), m_Data->m_MimeTypes.end());\n return result;\n}\n\nvoid FileWriterSelector::Swap(FileWriterSelector& fws)\n{\n m_Data.Swap(fws.m_Data);\n}\n\nFileWriterSelector::Item::Item(const FileWriterSelector::Item& other)\n : d(other.d)\n{\n}\n\nFileWriterSelector::Item::~Item()\n{\n}\n\nFileWriterSelector::Item& FileWriterSelector::Item::operator=(const FileWriterSelector::Item& other)\n{\n d = other.d;\n return *this;\n}\n\nIFileWriter* FileWriterSelector::Item::GetWriter() const\n{\n return d->m_FileWriter;\n}\n\nstd::string FileWriterSelector::Item::GetDescription() const\n{\n us::Any descr = d->m_FileWriterRef.GetProperty(IFileWriter::PROP_DESCRIPTION());\n if (descr.Empty()) return std::string();\n return descr.ToString();\n}\n\nIFileWriter::ConfidenceLevel FileWriterSelector::Item::GetConfidenceLevel() const\n{\n return d->m_ConfidenceLevel;\n}\n\nMimeType FileWriterSelector::Item::GetMimeType() const\n{\n return d->m_MimeType;\n}\n\nstd::string FileWriterSelector::Item::GetBaseDataType() const\n{\n us::Any any = d->m_FileWriterRef.GetProperty(IFileWriter::PROP_BASEDATA_TYPE());\n if (any.Empty()) return std::string();\n return any.ToString();\n}\n\nus::ServiceReference<IFileWriter> FileWriterSelector::Item::GetReference() const\n{\n return d->m_FileWriterRef;\n}\n\nlong FileWriterSelector::Item::GetServiceId() const\n{\n return d->m_Id;\n}\n\nbool FileWriterSelector::Item::operator<(const FileWriterSelector::Item& other) const\n{\n \/\/ sort by confidence level first (ascending)\n if (d->m_ConfidenceLevel == other.d->m_ConfidenceLevel)\n {\n \/\/ sort by class hierarchy index (writers for more derived\n \/\/ based data types are considered a better match)\n if (d->m_BaseDataIndex == other.d->m_BaseDataIndex)\n {\n \/\/ sort by file writer service ranking\n return d->m_FileWriterRef < other.d->m_FileWriterRef;\n }\n return other.d->m_BaseDataIndex < d->m_BaseDataIndex;\n }\n return d->m_ConfidenceLevel < other.d->m_ConfidenceLevel;\n}\n\nFileWriterSelector::Item::Item()\n : d(new Impl())\n{}\n\nvoid swap(FileWriterSelector& fws1, FileWriterSelector& fws2)\n{\n fws1.Swap(fws2);\n}\n\n}\n<commit_msg>COMP: Also get references for empy destMimeType<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkFileWriterSelector.h\"\n\n#include <mitkFileWriterRegistry.h>\n#include <mitkCoreServices.h>\n#include <mitkIMimeTypeProvider.h>\n#include <mitkBaseData.h>\n\n#include <usServiceReference.h>\n#include <usServiceProperties.h>\n#include <usAny.h>\n\n#include <itksys\/SystemTools.hxx>\n\n#include <set>\n#include <limits>\n#include <iterator>\n\nnamespace mitk {\n\nstruct FileWriterSelector::Item::Impl : us::SharedData\n{\n Impl()\n : m_FileWriter(NULL)\n , m_ConfidenceLevel(IFileWriter::Unsupported)\n , m_BaseDataIndex(0)\n , m_Id(-1)\n {}\n\n us::ServiceReference<IFileWriter> m_FileWriterRef;\n IFileWriter* m_FileWriter;\n IFileWriter::ConfidenceLevel m_ConfidenceLevel;\n std::size_t m_BaseDataIndex;\n MimeType m_MimeType;\n long m_Id;\n};\n\nstruct FileWriterSelector::Impl : us::SharedData\n{\n Impl()\n : m_BestId(-1)\n , m_SelectedId(m_BestId)\n {}\n\n Impl(const Impl& other)\n : us::SharedData(other)\n , m_BestId(-1)\n , m_SelectedId(m_BestId)\n {}\n\n FileWriterRegistry m_WriterRegistry;\n std::map<long, FileWriterSelector::Item> m_Items;\n std::set<MimeType> m_MimeTypes;\n long m_BestId;\n long m_SelectedId;\n};\n\nFileWriterSelector::FileWriterSelector(const FileWriterSelector& other)\n : m_Data(other.m_Data)\n{\n}\n\nFileWriterSelector::FileWriterSelector(const BaseData* baseData, const std::string& mimeType,\n const std::string& path)\n : m_Data(new Impl)\n{\n mitk::CoreServicePointer<mitk::IMimeTypeProvider> mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider());\n\n std::vector<FileWriterRegistry::WriterReference> refs;\n\n std::string destMimeType = mimeType;\n if (destMimeType.empty() && !path.empty())\n {\n \/\/ try to derive a mime-type from the file\n std::vector<MimeType> mimeTypes = mimeTypeProvider->GetMimeTypesForFile(path);\n if (!mimeTypes.empty())\n {\n for( unsigned int index = 0; index < mimeTypes.size(); index++)\n {\n std::vector<FileWriterRegistry::WriterReference> tempRefs = m_Data->m_WriterRegistry.GetReferences(baseData, mimeTypes.at(index).GetName());\n for( unsigned int innerIndex = 0; innerIndex < tempRefs.size(); innerIndex++)\n {\n refs.push_back( tempRefs.at(innerIndex) );\n }\n }\n }\n else if (!itksys::SystemTools::GetFilenameExtension(path).empty())\n {\n \/\/ If there are no suitable mime-type for the file AND an extension\n \/\/ was supplied, we stop here.\n return;\n }\n else\n {\n refs = m_Data->m_WriterRegistry.GetReferences(baseData, destMimeType);\n }\n }\n else\n {\n refs = m_Data->m_WriterRegistry.GetReferences(baseData, destMimeType);\n }\n\n std::vector<std::string> classHierarchy = baseData->GetClassHierarchy();\n\n \/\/ Get all writers and their mime types for the given base data type\n Item bestItem;\n for (std::vector<FileWriterRegistry::WriterReference>::const_iterator iter = refs.begin(),\n iterEnd = refs.end(); iter != iterEnd; ++iter)\n {\n std::string mimeTypeName = iter->GetProperty(IFileWriter::PROP_MIMETYPE()).ToString();\n if (!mimeTypeName.empty())\n {\n MimeType mimeType = mimeTypeProvider->GetMimeTypeForName(mimeTypeName);\n if (mimeType.IsValid())\n {\n \/\/ There is a registered mime-type for this writer. Now get the confidence level\n \/\/ of this writer for writing the given base data object.\n\n IFileWriter* writer = m_Data->m_WriterRegistry.GetWriter(*iter);\n if (writer == NULL) continue;\n try\n {\n writer->SetInput(baseData);\n IFileWriter::ConfidenceLevel confidenceLevel = writer->GetConfidenceLevel();\n if (confidenceLevel == IFileWriter::Unsupported)\n {\n continue;\n }\n\n std::string baseDataType = iter->GetProperty(IFileWriter::PROP_BASEDATA_TYPE()).ToString();\n std::vector<std::string>::iterator idxIter =\n std::find(classHierarchy.begin(), classHierarchy.end(), baseDataType);\n std::size_t baseDataIndex = std::numeric_limits<std::size_t>::max();\n if (idxIter != classHierarchy.end())\n {\n baseDataIndex = std::distance(classHierarchy.begin(), idxIter);\n }\n\n Item item;\n item.d->m_FileWriterRef = *iter;\n item.d->m_FileWriter = writer;\n item.d->m_ConfidenceLevel = confidenceLevel;\n item.d->m_BaseDataIndex = baseDataIndex;\n item.d->m_MimeType = mimeType;\n item.d->m_Id = us::any_cast<long>(iter->GetProperty(us::ServiceConstants::SERVICE_ID()));\n m_Data->m_Items.insert(std::make_pair(item.d->m_Id, item));\n m_Data->m_MimeTypes.insert(mimeType);\n if (!bestItem.GetReference() || bestItem < item)\n {\n bestItem = item;\n }\n }\n catch (const us::BadAnyCastException& e)\n {\n MITK_WARN << \"Unexpected: \" << e.what();\n }\n catch (const std::exception& e)\n {\n \/\/ Log the error but continue\n MITK_WARN << \"IFileWriter::GetConfidenceLevel exception: \" << e.what();\n }\n }\n }\n }\n\n if (bestItem.GetReference())\n {\n m_Data->m_BestId = bestItem.GetServiceId();\n m_Data->m_SelectedId = m_Data->m_BestId;\n }\n}\n\nFileWriterSelector::~FileWriterSelector()\n{\n}\n\nFileWriterSelector& FileWriterSelector::operator=(const FileWriterSelector& other)\n{\n m_Data = other.m_Data;\n return *this;\n}\n\nbool FileWriterSelector::IsEmpty() const\n{\n return m_Data->m_Items.empty();\n}\n\nstd::vector<FileWriterSelector::Item> FileWriterSelector::Get(const std::string& mimeType) const\n{\n std::vector<Item> result;\n for (std::map<long, Item>::const_iterator iter = m_Data->m_Items.begin(),\n iterEnd = m_Data->m_Items.end(); iter != iterEnd; ++iter)\n {\n if (mimeType.empty() || iter->second.GetMimeType().GetName() == mimeType)\n {\n result.push_back(iter->second);\n }\n }\n std::sort(result.begin(), result.end());\n return result;\n}\n\nstd::vector<FileWriterSelector::Item> FileWriterSelector::Get() const\n{\n return Get(this->GetSelected().d->m_MimeType.GetName());\n}\n\nFileWriterSelector::Item FileWriterSelector::Get(long id) const\n{\n std::map<long, Item>::const_iterator iter = m_Data->m_Items.find(id);\n if (iter != m_Data->m_Items.end())\n {\n return iter->second;\n }\n return Item();\n}\n\nFileWriterSelector::Item FileWriterSelector::GetDefault() const\n{\n return Get(m_Data->m_BestId);\n}\n\nlong FileWriterSelector::GetDefaultId() const\n{\n return m_Data->m_BestId;\n}\n\nFileWriterSelector::Item FileWriterSelector::GetSelected() const\n{\n return Get(m_Data->m_SelectedId);\n}\n\nlong FileWriterSelector::GetSelectedId() const\n{\n return m_Data->m_SelectedId;\n}\n\nbool FileWriterSelector::Select(const std::string& mimeType)\n{\n std::vector<Item> items = Get(mimeType);\n if (items.empty()) return false;\n return Select(items.back());\n}\n\nbool FileWriterSelector::Select(const FileWriterSelector::Item& item)\n{\n return Select(item.d->m_Id);\n}\n\nbool FileWriterSelector::Select(long id)\n{\n if (id > -1)\n {\n if (m_Data->m_Items.find(id) == m_Data->m_Items.end())\n {\n return false;\n }\n m_Data->m_SelectedId = id;\n return true;\n }\n return false;\n}\n\nstd::vector<MimeType> FileWriterSelector::GetMimeTypes() const\n{\n std::vector<MimeType> result;\n result.reserve(m_Data->m_MimeTypes.size());\n result.assign(m_Data->m_MimeTypes.begin(), m_Data->m_MimeTypes.end());\n return result;\n}\n\nvoid FileWriterSelector::Swap(FileWriterSelector& fws)\n{\n m_Data.Swap(fws.m_Data);\n}\n\nFileWriterSelector::Item::Item(const FileWriterSelector::Item& other)\n : d(other.d)\n{\n}\n\nFileWriterSelector::Item::~Item()\n{\n}\n\nFileWriterSelector::Item& FileWriterSelector::Item::operator=(const FileWriterSelector::Item& other)\n{\n d = other.d;\n return *this;\n}\n\nIFileWriter* FileWriterSelector::Item::GetWriter() const\n{\n return d->m_FileWriter;\n}\n\nstd::string FileWriterSelector::Item::GetDescription() const\n{\n us::Any descr = d->m_FileWriterRef.GetProperty(IFileWriter::PROP_DESCRIPTION());\n if (descr.Empty()) return std::string();\n return descr.ToString();\n}\n\nIFileWriter::ConfidenceLevel FileWriterSelector::Item::GetConfidenceLevel() const\n{\n return d->m_ConfidenceLevel;\n}\n\nMimeType FileWriterSelector::Item::GetMimeType() const\n{\n return d->m_MimeType;\n}\n\nstd::string FileWriterSelector::Item::GetBaseDataType() const\n{\n us::Any any = d->m_FileWriterRef.GetProperty(IFileWriter::PROP_BASEDATA_TYPE());\n if (any.Empty()) return std::string();\n return any.ToString();\n}\n\nus::ServiceReference<IFileWriter> FileWriterSelector::Item::GetReference() const\n{\n return d->m_FileWriterRef;\n}\n\nlong FileWriterSelector::Item::GetServiceId() const\n{\n return d->m_Id;\n}\n\nbool FileWriterSelector::Item::operator<(const FileWriterSelector::Item& other) const\n{\n \/\/ sort by confidence level first (ascending)\n if (d->m_ConfidenceLevel == other.d->m_ConfidenceLevel)\n {\n \/\/ sort by class hierarchy index (writers for more derived\n \/\/ based data types are considered a better match)\n if (d->m_BaseDataIndex == other.d->m_BaseDataIndex)\n {\n \/\/ sort by file writer service ranking\n return d->m_FileWriterRef < other.d->m_FileWriterRef;\n }\n return other.d->m_BaseDataIndex < d->m_BaseDataIndex;\n }\n return d->m_ConfidenceLevel < other.d->m_ConfidenceLevel;\n}\n\nFileWriterSelector::Item::Item()\n : d(new Impl())\n{}\n\nvoid swap(FileWriterSelector& fws1, FileWriterSelector& fws2)\n{\n fws1.Swap(fws2);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SkyManager.h\"\n#include <iostream>\n\n#define degreesToRadians(x) x*(3.141592f\/180.0f)\nfloat g_light;\nfloat g_ticks;\n\n\/\/blend\nfloat blend(float x, float y, float factor){\n return x + ((y-x) * factor);\n}\n\nSkyManager::SkyManager()\n: sun(\"Sun\"), moon(\"Moon\")\n{\n dayTime = 0; \/\/Dawn\n m_prevTime = 0; \/\/Time now\n\n std::vector<GLfloat> svertexCoords\n { \n -70, 70, 400,\n 70, 70, 400,\n 70, -70, 400,\n -70, -70, 400\n };\n\n std::vector<GLfloat> stextureCoords\n {\n 0, 1,\n 1, 1,\n 1, 0,\n 0, 0,\n };\n\n std::vector<GLuint> sindexCoords\n {\n 0, 1, 2,\n 2, 3, 0\n };\n\n m_SunModel.addData({svertexCoords, stextureCoords, sindexCoords});\n\n std::vector<GLfloat> mvertexCoords\n { \n -70, 70, -400,\n 70, 70, -400,\n 70, -70, -400,\n -70, -70, -400\n };\n\n std::vector<GLfloat> mtextureCoords\n {\n 0, 1,\n 1, 1,\n 1, 0,\n 0, 0,\n };\n\n std::vector<GLuint> mindexCoords\n {\n 0, 1, 2,\n 2, 3, 0\n };\n\n m_MoonModel.addData({mvertexCoords, mtextureCoords, mindexCoords});\n\n}\n\nvoid SkyManager::TickUpdate(unsigned int tickTime){\n \/\/Day Time Management\n dayTime += tickTime - m_prevTime;\n m_prevTime = tickTime;\n\n if(dayTime > 23999){\n dayTime = 0;\n }\n\n\n \/\/Ambient light\n \/\/0 = 6am\n \/\/12000 = 6pm\n if(dayTime < 1500){ \/\/6am - 9am sun gets brighter\n g_light = blend(0.6f, 1.0f, (float)dayTime \/ 1500); \n }\n if(dayTime > 1500 && dayTime < 10500){ \/\/9am - 3pm sun is brightest\n g_light = 1.0f;\n }\n if(dayTime > 10500 && dayTime < 12000){ \/\/3pm - 6pm sun gets dimmer\n g_light = blend(1.0f, 0.6f,(float)((float)dayTime - 10500) \/ 1500);\n }\n if(dayTime > 12000 && dayTime < 13500){ \/\/6pm - 9pm sun light fades\n g_light = blend(0.6f, 0.2f, (float)((float)dayTime - 12000)\/ 1500);\n }\n if(dayTime > 13500 && dayTime < 22500){\/\/9pm - 3am is night\n g_light = 0.2f;\n }\n if(dayTime > 22500 && dayTime < 24000){\n g_light = blend(0.2f, 0.6f, (float)((float)dayTime-22500) \/ 1500);\n }\n \n \/\/Update Sun\/Moon matrix\n transformMatrix = glm::translate(glm::mat4(1.0f), playerPos);\n\n g_ticks = dayTime;\n}\n\nvoid SkyManager::setTime(unsigned int tickTime){\n dayTime = tickTime;\n}\n\nunsigned int SkyManager::getTime(){\n return dayTime;\n}\n\nvoid SkyManager::Update(glm::vec3 position){\n playerPos = position;\n}\n\nvoid SkyManager::render(const Camera& camera){\n \n skyBox.Render(camera);\n glEnable(GL_BLEND); \n m_shader.useProgram();\n m_SunModel.bindVAO();\n sun.bindTexture();\n\n m_shader.loadModelMatrix(transformMatrix);\n m_shader.loadProjectionViewMatrix (camera.getProjectionViewMatrix());\n m_shader.loadTime(degreesToRadians(((float)dayTime\/24000) * 360));\n\n GL::drawElements(m_SunModel.getIndicesCount());\n\n m_shader.useProgram();\n m_MoonModel.bindVAO();\n moon.bindTexture();\n\n m_shader.loadModelMatrix(transformMatrix);\n m_shader.loadProjectionViewMatrix (camera.getProjectionViewMatrix());\n m_shader.loadTime(degreesToRadians(((float)dayTime\/24000) * 360));\n\n clouds.Render(camera, playerPos);\n\n GL::drawElements(m_MoonModel.getIndicesCount());\n glDisable(GL_BLEND);\n\n}<commit_msg>Fixed drawing of the moon.<commit_after>#include \"SkyManager.h\"\n#include <iostream>\n\n#define degreesToRadians(x) x*(3.141592f\/180.0f)\nfloat g_light;\nfloat g_ticks;\n\n\/\/blend\nfloat blend(float x, float y, float factor){\n return x + ((y-x) * factor);\n}\n\nSkyManager::SkyManager()\n: sun(\"Sun\"), moon(\"Moon\")\n{\n dayTime = 0; \/\/Dawn\n m_prevTime = 0; \/\/Time now\n\n std::vector<GLfloat> svertexCoords\n { \n -70, 70, 400,\n 70, 70, 400,\n 70, -70, 400,\n -70, -70, 400\n };\n\n std::vector<GLfloat> stextureCoords\n {\n 0, 1,\n 1, 1,\n 1, 0,\n 0, 0,\n };\n\n std::vector<GLuint> sindexCoords\n {\n 0, 1, 2,\n 2, 3, 0\n };\n\n m_SunModel.addData({svertexCoords, stextureCoords, sindexCoords});\n\n std::vector<GLfloat> mvertexCoords\n { \n -70, 70, -400,\n 70, 70, -400,\n 70, -70, -400,\n -70, -70, -400\n };\n\n std::vector<GLfloat> mtextureCoords\n {\n 0, 1,\n 1, 1,\n 1, 0,\n 0, 0,\n };\n\n std::vector<GLuint> mindexCoords\n {\n 0, 1, 2,\n 2, 3, 0\n };\n\n m_MoonModel.addData({mvertexCoords, mtextureCoords, mindexCoords});\n\n}\n\nvoid SkyManager::TickUpdate(unsigned int tickTime){\n \/\/Day Time Management\n dayTime += tickTime - m_prevTime;\n m_prevTime = tickTime;\n\n if(dayTime > 23999){\n dayTime = 0;\n }\n\n\n \/\/Ambient light\n \/\/0 = 6am\n \/\/12000 = 6pm\n if(dayTime < 1500){ \/\/6am - 9am sun gets brighter\n g_light = blend(0.6f, 1.0f, (float)dayTime \/ 1500); \n }\n if(dayTime > 1500 && dayTime < 10500){ \/\/9am - 3pm sun is brightest\n g_light = 1.0f;\n }\n if(dayTime > 10500 && dayTime < 12000){ \/\/3pm - 6pm sun gets dimmer\n g_light = blend(1.0f, 0.6f,(float)((float)dayTime - 10500) \/ 1500);\n }\n if(dayTime > 12000 && dayTime < 13500){ \/\/6pm - 9pm sun light fades\n g_light = blend(0.6f, 0.2f, (float)((float)dayTime - 12000)\/ 1500);\n }\n if(dayTime > 13500 && dayTime < 22500){\/\/9pm - 3am is night\n g_light = 0.2f;\n }\n if(dayTime > 22500 && dayTime < 24000){\n g_light = blend(0.2f, 0.6f, (float)((float)dayTime-22500) \/ 1500);\n }\n \n \/\/Update Sun\/Moon matrix\n transformMatrix = glm::translate(glm::mat4(1.0f), playerPos);\n\n g_ticks = dayTime;\n}\n\nvoid SkyManager::setTime(unsigned int tickTime){\n dayTime = tickTime;\n}\n\nunsigned int SkyManager::getTime(){\n return dayTime;\n}\n\nvoid SkyManager::Update(glm::vec3 position){\n playerPos = position;\n}\n\nvoid SkyManager::render(const Camera& camera){\n \n skyBox.Render(camera);\n glEnable(GL_BLEND); \n m_shader.useProgram();\n m_SunModel.bindVAO();\n sun.bindTexture();\n\n m_shader.loadModelMatrix(transformMatrix);\n m_shader.loadProjectionViewMatrix (camera.getProjectionViewMatrix());\n m_shader.loadTime(degreesToRadians(((float)dayTime\/24000) * 360));\n\n GL::drawElements(m_SunModel.getIndicesCount());\n\n m_shader.useProgram();\n m_MoonModel.bindVAO();\n moon.bindTexture();\n\n m_shader.loadModelMatrix(transformMatrix);\n m_shader.loadProjectionViewMatrix (camera.getProjectionViewMatrix());\n m_shader.loadTime(degreesToRadians(((float)dayTime\/24000) * 360));\n GL::drawElements(m_MoonModel.getIndicesCount());\n\n clouds.Render(camera, playerPos);\n glDisable(GL_BLEND);\n\n}<|endoftext|>"} {"text":"<commit_before>\/** \\brief Utility for converting between MARC formats.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (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. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <set>\n#include <stdexcept>\n#include <climits>\n#include <cstdio>\n#include <cstdlib>\n#include \"MARC.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname << \" [--quiet] [--limit max_no_of_records] marc_input marc_output [CTLN_1 CTLN_2 .. CTLN_N]\\n\"\n << \" Autoconverts the MARC format of \\\"marc_input\\\" to \\\"marc_output\\\".\\n\"\n << \" Supported extensions are \\\"xml\\\", \\\"mrc\\\", \\\"marc\\\" and \\\"raw\\\".\\n\"\n << \" All extensions except for \\\"xml\\\" are assumed to imply MARC-21.\\n\"\n << \" If a control number list has been specified only those records will\\n\"\n << \" be extracted or converted.\\n\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid ProcessRecords(const bool quiet, const unsigned max_no_of_records, MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,\n const std::set<std::string> &control_numbers)\n{\n unsigned record_count(0), extracted_count(0);\n\n while (MARC::Record record = marc_reader->read()) {\n ++record_count;\n\n if (not control_numbers.empty() and control_numbers.find(record.getControlNumber()) == control_numbers.end())\n continue;\n\n ++extracted_count;\n marc_writer->write(record);\n\n if (record_count == max_no_of_records)\n break;\n }\n\n if (not quiet) {\n logger->info(\"Processed \" + std::to_string(record_count) + \" MARC record(s).\");\n logger->info(\"Extracted or converted \" + std::to_string(extracted_count) + \" record(s).\");\n }\n}\n\n\n} \/\/ unnamed namespace\n\n\nint main(int argc, char *argv[]) {\n ::progname = argv[0];\n\n if (argc < 3)\n Usage();\n\n bool quiet(false);\n if (std::strcmp(argv[1], \"--quiet\") == 0) {\n quiet = true;\n --argc, ++argv;\n }\n\n if (argc < 3)\n Usage();\n\n unsigned max_no_of_records(UINT_MAX);\n if (std::strcmp(argv[1], \"--limit\") == 0) {\n if (not StringUtil::ToUnsigned(argv[2], &max_no_of_records) or max_no_of_records == 0)\n Usage();\n argc += 2;\n argv += 2;\n }\n \n if (argc != 3)\n Usage();\n\n const std::string input_filename(argv[1]);\n const std::string output_filename(argv[2]);\n\n try {\n std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(input_filename));\n std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(output_filename));\n\n std::set<std::string> control_numbers;\n for (int arg_no(3); arg_no < argc; ++arg_no)\n control_numbers.emplace(argv[arg_no]);\n\n ProcessRecords(quiet, max_no_of_records, marc_reader.get(), marc_writer.get(), control_numbers);\n } catch (const std::exception &e) {\n LOG_ERROR(\"Caught exception: \" + std::string(e.what()));\n }\n}\n<commit_msg>Another argument-handling fix. a.k., three's the chram!<commit_after>\/** \\brief Utility for converting between MARC formats.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (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. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <set>\n#include <stdexcept>\n#include <climits>\n#include <cstdio>\n#include <cstdlib>\n#include \"MARC.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname << \" [--quiet] [--limit max_no_of_records] marc_input marc_output [CTLN_1 CTLN_2 .. CTLN_N]\\n\"\n << \" Autoconverts the MARC format of \\\"marc_input\\\" to \\\"marc_output\\\".\\n\"\n << \" Supported extensions are \\\"xml\\\", \\\"mrc\\\", \\\"marc\\\" and \\\"raw\\\".\\n\"\n << \" All extensions except for \\\"xml\\\" are assumed to imply MARC-21.\\n\"\n << \" If a control number list has been specified only those records will\\n\"\n << \" be extracted or converted.\\n\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid ProcessRecords(const bool quiet, const unsigned max_no_of_records, MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,\n const std::set<std::string> &control_numbers)\n{\n unsigned record_count(0), extracted_count(0);\n\n while (MARC::Record record = marc_reader->read()) {\n ++record_count;\n\n if (not control_numbers.empty() and control_numbers.find(record.getControlNumber()) == control_numbers.end())\n continue;\n\n ++extracted_count;\n marc_writer->write(record);\n\n if (record_count == max_no_of_records)\n break;\n }\n\n if (not quiet) {\n logger->info(\"Processed \" + std::to_string(record_count) + \" MARC record(s).\");\n logger->info(\"Extracted or converted \" + std::to_string(extracted_count) + \" record(s).\");\n }\n}\n\n\n} \/\/ unnamed namespace\n\n\nint main(int argc, char *argv[]) {\n ::progname = argv[0];\n\n if (argc < 3)\n Usage();\n\n bool quiet(false);\n if (std::strcmp(argv[1], \"--quiet\") == 0) {\n quiet = true;\n --argc, ++argv;\n }\n\n if (argc < 3)\n Usage();\n\n unsigned max_no_of_records(UINT_MAX);\n if (std::strcmp(argv[1], \"--limit\") == 0) {\n if (not StringUtil::ToUnsigned(argv[2], &max_no_of_records) or max_no_of_records == 0)\n Usage();\n argc -= 2;\n argv += 2;\n }\n \n if (argc < 3)\n Usage();\n\n const std::string input_filename(argv[1]);\n const std::string output_filename(argv[2]);\n\n try {\n std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(input_filename));\n std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(output_filename));\n\n std::set<std::string> control_numbers;\n for (int arg_no(3); arg_no < argc; ++arg_no)\n control_numbers.emplace(argv[arg_no]);\n\n ProcessRecords(quiet, max_no_of_records, marc_reader.get(), marc_writer.get(), control_numbers);\n } catch (const std::exception &e) {\n LOG_ERROR(\"Caught exception: \" + std::string(e.what()));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n open source routing machine\n Copyright (C) Dennis Luxen, 2010\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU AFFERO General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\nor see http:\/\/www.gnu.org\/licenses\/agpl.txt.\n *\/\n\n#define VERBOSE(x) x\n#define VERBOSE2(x)\n\n#ifdef NDEBUG\n#undef VERBOSE\n#undef VERBOSE2\n#endif\n\nextern \"C\" {\n#include <lua.h>\n#include <lauxlib.h>\n#include <lualib.h>\n}\n#include <luabind\/luabind.hpp>\n\n#include <boost\/foreach.hpp>\n\n#include <fstream>\n#include <istream>\n#include <iostream>\n#include <cstring>\n#include <string>\n#include <vector>\n\n#include \"Algorithms\/IteratorBasedCRC32.h\"\n#include \"Util\/OpenMPWrapper.h\"\n#include \"typedefs.h\"\n#include \"Contractor\/Contractor.h\"\n#include \"Contractor\/EdgeBasedGraphFactory.h\"\n#include \"DataStructures\/BinaryHeap.h\"\n#include \"DataStructures\/DeallocatingVector.h\"\n#include \"DataStructures\/NNGrid.h\"\n#include \"DataStructures\/QueryEdge.h\"\n#include \"Util\/BaseConfiguration.h\"\n#include \"Util\/InputFileUtil.h\"\n#include \"Util\/GraphLoader.h\"\n\nusing namespace std;\n\ntypedef QueryEdge::EdgeData EdgeData;\ntypedef DynamicGraph<EdgeData>::InputEdge InputEdge;\ntypedef StaticGraph<EdgeData>::InputEdge StaticEdge;\ntypedef BaseConfiguration ContractorConfiguration;\n\nstd::vector<NodeInfo> internalToExternalNodeMapping;\nstd::vector<_Restriction> inputRestrictions;\nstd::vector<NodeID> bollardNodes;\nstd::vector<NodeID> trafficLightNodes;\n\nint main (int argc, char *argv[]) {\n if(argc < 3) {\n ERR(\"usage: \" << std::endl << argv[0] << \" <osrm-data> <osrm-restrictions>\");\n }\n\n double startupTime = get_timestamp();\n unsigned numberOfThreads = omp_get_num_procs();\n std::string SRTM_ROOT;\n if(testDataFile(\"contractor.ini\")) {\n ContractorConfiguration contractorConfig(\"contractor.ini\");\n if(atoi(contractorConfig.GetParameter(\"Threads\").c_str()) != 0 && (unsigned)atoi(contractorConfig.GetParameter(\"Threads\").c_str()) <= numberOfThreads)\n numberOfThreads = (unsigned)atoi( contractorConfig.GetParameter(\"Threads\").c_str() );\n if(0 < contractorConfig.GetParameter(\"SRTM\").size() )\n SRTM_ROOT = contractorConfig.GetParameter(\"SRTM\");\n }\n if(0 != SRTM_ROOT.size())\n INFO(\"Loading SRTM from\/to \" << SRTM_ROOT);\n omp_set_num_threads(numberOfThreads);\n\n INFO(\"Using restrictions from file: \" << argv[2]);\n std::ifstream restrictionsInstream(argv[2], ios::binary);\n if(!restrictionsInstream.good()) {\n ERR(\"Could not access <osrm-restrictions> files\");\n }\n _Restriction restriction;\n unsigned usableRestrictionsCounter(0);\n restrictionsInstream.read((char*)&usableRestrictionsCounter, sizeof(unsigned));\n inputRestrictions.resize(usableRestrictionsCounter);\n restrictionsInstream.read((char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(_Restriction));\n restrictionsInstream.close();\n\n std::ifstream in;\n in.open (argv[1], std::ifstream::in | std::ifstream::binary);\n if (!in.is_open()) {\n ERR(\"Cannot open \" << argv[1]);\n }\n\n char nodeOut[1024]; strcpy(nodeOut, argv[1]); strcat(nodeOut, \".nodes\");\n char edgeOut[1024]; strcpy(edgeOut, argv[1]); strcat(edgeOut, \".edges\");\n char graphOut[1024]; \tstrcpy(graphOut, argv[1]); \tstrcat(graphOut, \".hsgr\");\n char ramIndexOut[1024]; \tstrcpy(ramIndexOut, argv[1]); \tstrcat(ramIndexOut, \".ramIndex\");\n char fileIndexOut[1024]; strcpy(fileIndexOut, argv[1]); \tstrcat(fileIndexOut, \".fileIndex\");\n char levelInfoOut[1024]; strcpy(levelInfoOut, argv[1]); \tstrcat(levelInfoOut, \".levels\");\n\n std::vector<ImportEdge> edgeList;\n NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions);\n in.close();\n INFO(inputRestrictions.size() << \" restrictions, \" << bollardNodes.size() << \" bollard nodes, \" << trafficLightNodes.size() << \" traffic lights\");\n\n if(!testDataFile(\"profile.lua\")) {\n ERR(\"Need profile.lua to apply traffic signal penalty\");\n }\n \/*** Setup Scripting Environment ***\/\n\n \/\/ Create a new lua state\n lua_State *myLuaState = luaL_newstate();\n\n \/\/ Connect LuaBind to this lua state\n luabind::open(myLuaState);\n\n\n \/\/ Now call our function in a lua script\n if(0 != luaL_dofile(myLuaState, \"profile.lua\")) {\n ERR(lua_tostring(myLuaState,-1)<< \" occured in scripting block\");\n }\n\n EdgeBasedGraphFactory::SpeedProfileProperties speedProfile;\n\n if(0 != luaL_dostring( myLuaState, \"return traffic_signal_penalty\\n\")) {\n ERR(lua_tostring(myLuaState,-1)<< \" occured in scripting block\");\n }\n speedProfile.trafficSignalPenalty = lua_tointeger(myLuaState, -1);\n\n if(0 != luaL_dostring( myLuaState, \"return u_turn_penalty\\n\")) {\n ERR(lua_tostring(myLuaState,-1)<< \" occured in scripting block\");\n }\n speedProfile.uTurnPenalty = lua_tointeger(myLuaState, -1);\n\n\n \/***\n * Building an edge-expanded graph from node-based input an turn restrictions\n *\/\n\n INFO(\"Generating edge-expanded graph representation\");\n EdgeBasedGraphFactory * edgeBasedGraphFactory = new EdgeBasedGraphFactory (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping, speedProfile);\n std::vector<ImportEdge>().swap(edgeList);\n edgeBasedGraphFactory->Run(edgeOut);\n std::vector<_Restriction>().swap(inputRestrictions);\n std::vector<NodeID>().swap(bollardNodes);\n std::vector<NodeID>().swap(trafficLightNodes);\n NodeID edgeBasedNodeNumber = edgeBasedGraphFactory->GetNumberOfNodes();\n DeallocatingVector<EdgeBasedEdge> edgeBasedEdgeList;\n edgeBasedGraphFactory->GetEdgeBasedEdges(edgeBasedEdgeList);\n if(0 == edgeBasedEdgeList.size())\n ERR(\"The input data is broken. It is impossible to do any turns in this graph\");\n\n\n \/***\n * Writing info on original (node-based) nodes\n *\/\n\n INFO(\"writing node map ...\");\n std::ofstream mapOutFile(nodeOut, std::ios::binary);\n mapOutFile.write((char *)&(internalToExternalNodeMapping[0]), internalToExternalNodeMapping.size()*sizeof(NodeInfo));\n mapOutFile.close();\n std::vector<NodeInfo>().swap(internalToExternalNodeMapping);\n\n \/***\n * Writing info on original (node-based) edges\n *\/\n INFO(\"writing info on original edges\");\n std::vector<OriginalEdgeData> originalEdgeData;\n edgeBasedGraphFactory->GetOriginalEdgeData(originalEdgeData);\n\n\/\/ std::ofstream oedOutFile(edgeOut, std::ios::binary);\n\/\/ unsigned numberOfOrigEdges = originalEdgeData.size();\n\/\/ oedOutFile.write((char*)&numberOfOrigEdges, sizeof(unsigned));\n\/\/ oedOutFile.write((char*)&(originalEdgeData[0]), originalEdgeData.size()*sizeof(OriginalEdgeData));\n\/\/ oedOutFile.close();\n\/\/ std::vector<OriginalEdgeData>().swap(originalEdgeData);\n\n DeallocatingVector<EdgeBasedGraphFactory::EdgeBasedNode> nodeBasedEdgeList;\n edgeBasedGraphFactory->GetEdgeBasedNodes(nodeBasedEdgeList);\n delete edgeBasedGraphFactory;\n double expansionHasFinishedTime = get_timestamp() - startupTime;\n\n \/***\n * Building grid-like nearest-neighbor data structure\n *\/\n\n INFO(\"building grid ...\");\n WritableGrid * writeableGrid = new WritableGrid();\n writeableGrid->ConstructGrid(nodeBasedEdgeList, ramIndexOut, fileIndexOut);\n delete writeableGrid;\n IteratorbasedCRC32<DeallocatingVector<EdgeBasedGraphFactory::EdgeBasedNode> > crc32;\n unsigned crc32OfNodeBasedEdgeList = crc32(nodeBasedEdgeList.begin(), nodeBasedEdgeList.end() );\n nodeBasedEdgeList.clear();\n INFO(\"CRC32 based checksum is \" << crc32OfNodeBasedEdgeList);\n\n \/***\n * Contracting the edge-expanded graph\n *\/\n\n INFO(\"initializing contractor\");\n Contractor* contractor = new Contractor( edgeBasedNodeNumber, edgeBasedEdgeList );\n double contractionStartedTimestamp(get_timestamp());\n contractor->Run();\n INFO(\"Contraction took \" << get_timestamp() - contractionStartedTimestamp << \" sec\");\n\n DeallocatingVector< QueryEdge > contractedEdgeList;\n contractor->GetEdges( contractedEdgeList );\n delete contractor;\n\n \/***\n * Sorting contracted edges in a way that the static query graph can read some in in-place.\n *\/\n\n INFO(\"Building Node Array\");\n sort(contractedEdgeList.begin(), contractedEdgeList.end());\n unsigned numberOfNodes = 0;\n unsigned numberOfEdges = contractedEdgeList.size();\n INFO(\"Serializing compacted graph\");\n ofstream edgeOutFile(graphOut, ios::binary);\n\n BOOST_FOREACH(QueryEdge & edge, contractedEdgeList) {\n if(edge.source > numberOfNodes) {\n numberOfNodes = edge.source;\n }\n if(edge.target > numberOfNodes) {\n numberOfNodes = edge.target;\n }\n }\n numberOfNodes+=1;\n\n std::vector< StaticGraph<EdgeData>::_StrNode > _nodes;\n _nodes.resize( numberOfNodes + 1 );\n\n StaticGraph<EdgeData>::EdgeIterator edge = 0;\n StaticGraph<EdgeData>::EdgeIterator position = 0;\n for ( StaticGraph<EdgeData>::NodeIterator node = 0; node <= numberOfNodes; ++node ) {\n StaticGraph<EdgeData>::EdgeIterator lastEdge = edge;\n while ( edge < numberOfEdges && contractedEdgeList[edge].source == node )\n ++edge;\n _nodes[node].firstEdge = position; \/\/=edge\n position += edge - lastEdge; \/\/remove\n }\n ++numberOfNodes;\n \/\/Serialize numberOfNodes, nodes\n edgeOutFile.write((char*) &crc32OfNodeBasedEdgeList, sizeof(unsigned));\n edgeOutFile.write((char*) &numberOfNodes, sizeof(unsigned));\n edgeOutFile.write((char*) &_nodes[0], sizeof(StaticGraph<EdgeData>::_StrNode)*(numberOfNodes));\n \/\/Serialize number of Edges\n edgeOutFile.write((char*) &position, sizeof(unsigned));\n --numberOfNodes;\n edge = 0;\n int usedEdgeCounter = 0;\n StaticGraph<EdgeData>::_StrEdge currentEdge;\n for ( StaticGraph<EdgeData>::NodeIterator node = 0; node < numberOfNodes; ++node ) {\n for ( StaticGraph<EdgeData>::EdgeIterator i = _nodes[node].firstEdge, e = _nodes[node+1].firstEdge; i != e; ++i ) {\n assert(node != contractedEdgeList[edge].target);\n currentEdge.target = contractedEdgeList[edge].target;\n currentEdge.data = contractedEdgeList[edge].data;\n if(currentEdge.data.distance <= 0) {\n INFO(\"Edge: \" << i << \",source: \" << contractedEdgeList[edge].source << \", target: \" << contractedEdgeList[edge].target << \", dist: \" << currentEdge.data.distance);\n ERR(\"Failed at edges of node \" << node << \" of \" << numberOfNodes);\n }\n \/\/Serialize edges\n edgeOutFile.write((char*) ¤tEdge, sizeof(StaticGraph<EdgeData>::_StrEdge));\n ++edge;\n ++usedEdgeCounter;\n }\n }\n double endTime = (get_timestamp() - startupTime);\n INFO(\"Expansion : \" << (nodeBasedNodeNumber\/expansionHasFinishedTime) << \" nodes\/sec and \"<< (edgeBasedNodeNumber\/expansionHasFinishedTime) << \" edges\/sec\");\n INFO(\"Contraction: \" << (edgeBasedNodeNumber\/expansionHasFinishedTime) << \" nodes\/sec and \"<< usedEdgeCounter\/endTime << \" edges\/sec\");\n\n edgeOutFile.close();\n \/\/cleanedEdgeList.clear();\n _nodes.clear();\n INFO(\"finished preprocessing\");\n return 0;\n}\n<commit_msg>Use seconds for penalties<commit_after>\/*\n open source routing machine\n Copyright (C) Dennis Luxen, 2010\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU AFFERO General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\nor see http:\/\/www.gnu.org\/licenses\/agpl.txt.\n *\/\n\n#define VERBOSE(x) x\n#define VERBOSE2(x)\n\n#ifdef NDEBUG\n#undef VERBOSE\n#undef VERBOSE2\n#endif\n\nextern \"C\" {\n#include <lua.h>\n#include <lauxlib.h>\n#include <lualib.h>\n}\n#include <luabind\/luabind.hpp>\n\n#include <boost\/foreach.hpp>\n\n#include <fstream>\n#include <istream>\n#include <iostream>\n#include <cstring>\n#include <string>\n#include <vector>\n\n#include \"Algorithms\/IteratorBasedCRC32.h\"\n#include \"Util\/OpenMPWrapper.h\"\n#include \"typedefs.h\"\n#include \"Contractor\/Contractor.h\"\n#include \"Contractor\/EdgeBasedGraphFactory.h\"\n#include \"DataStructures\/BinaryHeap.h\"\n#include \"DataStructures\/DeallocatingVector.h\"\n#include \"DataStructures\/NNGrid.h\"\n#include \"DataStructures\/QueryEdge.h\"\n#include \"Util\/BaseConfiguration.h\"\n#include \"Util\/InputFileUtil.h\"\n#include \"Util\/GraphLoader.h\"\n\nusing namespace std;\n\ntypedef QueryEdge::EdgeData EdgeData;\ntypedef DynamicGraph<EdgeData>::InputEdge InputEdge;\ntypedef StaticGraph<EdgeData>::InputEdge StaticEdge;\ntypedef BaseConfiguration ContractorConfiguration;\n\nstd::vector<NodeInfo> internalToExternalNodeMapping;\nstd::vector<_Restriction> inputRestrictions;\nstd::vector<NodeID> bollardNodes;\nstd::vector<NodeID> trafficLightNodes;\n\nint main (int argc, char *argv[]) {\n if(argc < 3) {\n ERR(\"usage: \" << std::endl << argv[0] << \" <osrm-data> <osrm-restrictions>\");\n }\n\n double startupTime = get_timestamp();\n unsigned numberOfThreads = omp_get_num_procs();\n std::string SRTM_ROOT;\n if(testDataFile(\"contractor.ini\")) {\n ContractorConfiguration contractorConfig(\"contractor.ini\");\n if(atoi(contractorConfig.GetParameter(\"Threads\").c_str()) != 0 && (unsigned)atoi(contractorConfig.GetParameter(\"Threads\").c_str()) <= numberOfThreads)\n numberOfThreads = (unsigned)atoi( contractorConfig.GetParameter(\"Threads\").c_str() );\n if(0 < contractorConfig.GetParameter(\"SRTM\").size() )\n SRTM_ROOT = contractorConfig.GetParameter(\"SRTM\");\n }\n if(0 != SRTM_ROOT.size())\n INFO(\"Loading SRTM from\/to \" << SRTM_ROOT);\n omp_set_num_threads(numberOfThreads);\n\n INFO(\"Using restrictions from file: \" << argv[2]);\n std::ifstream restrictionsInstream(argv[2], ios::binary);\n if(!restrictionsInstream.good()) {\n ERR(\"Could not access <osrm-restrictions> files\");\n }\n _Restriction restriction;\n unsigned usableRestrictionsCounter(0);\n restrictionsInstream.read((char*)&usableRestrictionsCounter, sizeof(unsigned));\n inputRestrictions.resize(usableRestrictionsCounter);\n restrictionsInstream.read((char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(_Restriction));\n restrictionsInstream.close();\n\n std::ifstream in;\n in.open (argv[1], std::ifstream::in | std::ifstream::binary);\n if (!in.is_open()) {\n ERR(\"Cannot open \" << argv[1]);\n }\n\n char nodeOut[1024]; strcpy(nodeOut, argv[1]); strcat(nodeOut, \".nodes\");\n char edgeOut[1024]; strcpy(edgeOut, argv[1]); strcat(edgeOut, \".edges\");\n char graphOut[1024]; \tstrcpy(graphOut, argv[1]); \tstrcat(graphOut, \".hsgr\");\n char ramIndexOut[1024]; \tstrcpy(ramIndexOut, argv[1]); \tstrcat(ramIndexOut, \".ramIndex\");\n char fileIndexOut[1024]; strcpy(fileIndexOut, argv[1]); \tstrcat(fileIndexOut, \".fileIndex\");\n char levelInfoOut[1024]; strcpy(levelInfoOut, argv[1]); \tstrcat(levelInfoOut, \".levels\");\n\n std::vector<ImportEdge> edgeList;\n NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions);\n in.close();\n INFO(inputRestrictions.size() << \" restrictions, \" << bollardNodes.size() << \" bollard nodes, \" << trafficLightNodes.size() << \" traffic lights\");\n\n if(!testDataFile(\"profile.lua\")) {\n ERR(\"Need profile.lua to apply traffic signal penalty\");\n }\n \/*** Setup Scripting Environment ***\/\n\n \/\/ Create a new lua state\n lua_State *myLuaState = luaL_newstate();\n\n \/\/ Connect LuaBind to this lua state\n luabind::open(myLuaState);\n\n\n \/\/ Now call our function in a lua script\n if(0 != luaL_dofile(myLuaState, \"profile.lua\")) {\n ERR(lua_tostring(myLuaState,-1)<< \" occured in scripting block\");\n }\n\n EdgeBasedGraphFactory::SpeedProfileProperties speedProfile;\n\n if(0 != luaL_dostring( myLuaState, \"return traffic_signal_penalty\\n\")) {\n ERR(lua_tostring(myLuaState,-1)<< \" occured in scripting block\");\n }\n speedProfile.trafficSignalPenalty = 10*lua_tointeger(myLuaState, -1);\n\n if(0 != luaL_dostring( myLuaState, \"return u_turn_penalty\\n\")) {\n ERR(lua_tostring(myLuaState,-1)<< \" occured in scripting block\");\n }\n speedProfile.uTurnPenalty = 10*lua_tointeger(myLuaState, -1);\n\n\n \/***\n * Building an edge-expanded graph from node-based input an turn restrictions\n *\/\n\n INFO(\"Generating edge-expanded graph representation\");\n EdgeBasedGraphFactory * edgeBasedGraphFactory = new EdgeBasedGraphFactory (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping, speedProfile);\n std::vector<ImportEdge>().swap(edgeList);\n edgeBasedGraphFactory->Run(edgeOut);\n std::vector<_Restriction>().swap(inputRestrictions);\n std::vector<NodeID>().swap(bollardNodes);\n std::vector<NodeID>().swap(trafficLightNodes);\n NodeID edgeBasedNodeNumber = edgeBasedGraphFactory->GetNumberOfNodes();\n DeallocatingVector<EdgeBasedEdge> edgeBasedEdgeList;\n edgeBasedGraphFactory->GetEdgeBasedEdges(edgeBasedEdgeList);\n if(0 == edgeBasedEdgeList.size())\n ERR(\"The input data is broken. It is impossible to do any turns in this graph\");\n\n\n \/***\n * Writing info on original (node-based) nodes\n *\/\n\n INFO(\"writing node map ...\");\n std::ofstream mapOutFile(nodeOut, std::ios::binary);\n mapOutFile.write((char *)&(internalToExternalNodeMapping[0]), internalToExternalNodeMapping.size()*sizeof(NodeInfo));\n mapOutFile.close();\n std::vector<NodeInfo>().swap(internalToExternalNodeMapping);\n\n \/***\n * Writing info on original (node-based) edges\n *\/\n INFO(\"writing info on original edges\");\n std::vector<OriginalEdgeData> originalEdgeData;\n edgeBasedGraphFactory->GetOriginalEdgeData(originalEdgeData);\n\n\/\/ std::ofstream oedOutFile(edgeOut, std::ios::binary);\n\/\/ unsigned numberOfOrigEdges = originalEdgeData.size();\n\/\/ oedOutFile.write((char*)&numberOfOrigEdges, sizeof(unsigned));\n\/\/ oedOutFile.write((char*)&(originalEdgeData[0]), originalEdgeData.size()*sizeof(OriginalEdgeData));\n\/\/ oedOutFile.close();\n\/\/ std::vector<OriginalEdgeData>().swap(originalEdgeData);\n\n DeallocatingVector<EdgeBasedGraphFactory::EdgeBasedNode> nodeBasedEdgeList;\n edgeBasedGraphFactory->GetEdgeBasedNodes(nodeBasedEdgeList);\n delete edgeBasedGraphFactory;\n double expansionHasFinishedTime = get_timestamp() - startupTime;\n\n \/***\n * Building grid-like nearest-neighbor data structure\n *\/\n\n INFO(\"building grid ...\");\n WritableGrid * writeableGrid = new WritableGrid();\n writeableGrid->ConstructGrid(nodeBasedEdgeList, ramIndexOut, fileIndexOut);\n delete writeableGrid;\n IteratorbasedCRC32<DeallocatingVector<EdgeBasedGraphFactory::EdgeBasedNode> > crc32;\n unsigned crc32OfNodeBasedEdgeList = crc32(nodeBasedEdgeList.begin(), nodeBasedEdgeList.end() );\n nodeBasedEdgeList.clear();\n INFO(\"CRC32 based checksum is \" << crc32OfNodeBasedEdgeList);\n\n \/***\n * Contracting the edge-expanded graph\n *\/\n\n INFO(\"initializing contractor\");\n Contractor* contractor = new Contractor( edgeBasedNodeNumber, edgeBasedEdgeList );\n double contractionStartedTimestamp(get_timestamp());\n contractor->Run();\n INFO(\"Contraction took \" << get_timestamp() - contractionStartedTimestamp << \" sec\");\n\n DeallocatingVector< QueryEdge > contractedEdgeList;\n contractor->GetEdges( contractedEdgeList );\n delete contractor;\n\n \/***\n * Sorting contracted edges in a way that the static query graph can read some in in-place.\n *\/\n\n INFO(\"Building Node Array\");\n sort(contractedEdgeList.begin(), contractedEdgeList.end());\n unsigned numberOfNodes = 0;\n unsigned numberOfEdges = contractedEdgeList.size();\n INFO(\"Serializing compacted graph\");\n ofstream edgeOutFile(graphOut, ios::binary);\n\n BOOST_FOREACH(QueryEdge & edge, contractedEdgeList) {\n if(edge.source > numberOfNodes) {\n numberOfNodes = edge.source;\n }\n if(edge.target > numberOfNodes) {\n numberOfNodes = edge.target;\n }\n }\n numberOfNodes+=1;\n\n std::vector< StaticGraph<EdgeData>::_StrNode > _nodes;\n _nodes.resize( numberOfNodes + 1 );\n\n StaticGraph<EdgeData>::EdgeIterator edge = 0;\n StaticGraph<EdgeData>::EdgeIterator position = 0;\n for ( StaticGraph<EdgeData>::NodeIterator node = 0; node <= numberOfNodes; ++node ) {\n StaticGraph<EdgeData>::EdgeIterator lastEdge = edge;\n while ( edge < numberOfEdges && contractedEdgeList[edge].source == node )\n ++edge;\n _nodes[node].firstEdge = position; \/\/=edge\n position += edge - lastEdge; \/\/remove\n }\n ++numberOfNodes;\n \/\/Serialize numberOfNodes, nodes\n edgeOutFile.write((char*) &crc32OfNodeBasedEdgeList, sizeof(unsigned));\n edgeOutFile.write((char*) &numberOfNodes, sizeof(unsigned));\n edgeOutFile.write((char*) &_nodes[0], sizeof(StaticGraph<EdgeData>::_StrNode)*(numberOfNodes));\n \/\/Serialize number of Edges\n edgeOutFile.write((char*) &position, sizeof(unsigned));\n --numberOfNodes;\n edge = 0;\n int usedEdgeCounter = 0;\n StaticGraph<EdgeData>::_StrEdge currentEdge;\n for ( StaticGraph<EdgeData>::NodeIterator node = 0; node < numberOfNodes; ++node ) {\n for ( StaticGraph<EdgeData>::EdgeIterator i = _nodes[node].firstEdge, e = _nodes[node+1].firstEdge; i != e; ++i ) {\n assert(node != contractedEdgeList[edge].target);\n currentEdge.target = contractedEdgeList[edge].target;\n currentEdge.data = contractedEdgeList[edge].data;\n if(currentEdge.data.distance <= 0) {\n INFO(\"Edge: \" << i << \",source: \" << contractedEdgeList[edge].source << \", target: \" << contractedEdgeList[edge].target << \", dist: \" << currentEdge.data.distance);\n ERR(\"Failed at edges of node \" << node << \" of \" << numberOfNodes);\n }\n \/\/Serialize edges\n edgeOutFile.write((char*) ¤tEdge, sizeof(StaticGraph<EdgeData>::_StrEdge));\n ++edge;\n ++usedEdgeCounter;\n }\n }\n double endTime = (get_timestamp() - startupTime);\n INFO(\"Expansion : \" << (nodeBasedNodeNumber\/expansionHasFinishedTime) << \" nodes\/sec and \"<< (edgeBasedNodeNumber\/expansionHasFinishedTime) << \" edges\/sec\");\n INFO(\"Contraction: \" << (edgeBasedNodeNumber\/expansionHasFinishedTime) << \" nodes\/sec and \"<< usedEdgeCounter\/endTime << \" edges\/sec\");\n\n edgeOutFile.close();\n \/\/cleanedEdgeList.clear();\n _nodes.clear();\n INFO(\"finished preprocessing\");\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SphericalInterpolator.h\"\n\nSphericalInterpolator::SphericalInterpolator()\n{\n\n}\n\n\nSphericalInterpolator::~SphericalInterpolator()\n{\n\n}\n\n\/\/the vectors must be in the order of xyz 000,100,010,001,101,011,110,111\nfloat* SphericalInterpolator::Build(float vectorInput[8][3], float relativePos[3])\n{\n\tfloat vectorFinal[3];\n\tint i;\n\tfor (i = 0; i < 3; i++) {\n\t\tvectorFinal[i] =\tvectorInput[0][i] * (1 - relativePos[0]) * (1 - relativePos[1]) * (1 - relativePos[2]) +\n\t\t\t\t\t\t\tvectorInput[1][i] * (relativePos[0]) * (1 - relativePos[1]) * (1 - relativePos[2]) +\n\t\t\t\t\t\t\tvectorInput[2][i] * (1 - relativePos[0]) * relativePos[1] * (1 - relativePos[2]) +\n\t\t\t\t\t\t\tvectorInput[3][i] * (1 - relativePos[0]) * (1 - relativePos[1]) * relativePos[2] +\n\t\t\t\t\t\t\tvectorInput[4][i] * relativePos[0] * (1 - relativePos[1]) * relativePos[2] +\n\t\t\t\t\t\t\tvectorInput[5][i] * (1 - relativePos[0]) * relativePos[1] * relativePos[2] +\n\t\t\t\t\t\t\tvectorInput[6][i] * relativePos[0] * relativePos[1] * (1 - relativePos[2]) +\n\t\t\t\t\t\t\tvectorInput[7][i] * relativePos[0] * relativePos[1] * relativePos[2];\n\t}\n\treturn vectorFinal;\n}<commit_msg>Fixed returning a local, temporary variable.<commit_after>#include \"SphericalInterpolator.h\"\n\nSphericalInterpolator::SphericalInterpolator()\n{\n\n}\n\n\nSphericalInterpolator::~SphericalInterpolator()\n{\n\n}\n\n\/\/the vectors must be in the order of xyz 000,100,010,001,101,011,110,111\nfloat* SphericalInterpolator::Build(float vectorInput[8][3], float relativePos[3])\n{\n\tfloat* vectorFinal = new float[3];\n\tint i;\n\tfor (i = 0; i < 3; i++) {\n\t\tvectorFinal[i] =\tvectorInput[0][i] * (1 - relativePos[0]) * (1 - relativePos[1]) * (1 - relativePos[2]) +\n\t\t\t\t\t\t\tvectorInput[1][i] * (relativePos[0]) * (1 - relativePos[1]) * (1 - relativePos[2]) +\n\t\t\t\t\t\t\tvectorInput[2][i] * (1 - relativePos[0]) * relativePos[1] * (1 - relativePos[2]) +\n\t\t\t\t\t\t\tvectorInput[3][i] * (1 - relativePos[0]) * (1 - relativePos[1]) * relativePos[2] +\n\t\t\t\t\t\t\tvectorInput[4][i] * relativePos[0] * (1 - relativePos[1]) * relativePos[2] +\n\t\t\t\t\t\t\tvectorInput[5][i] * (1 - relativePos[0]) * relativePos[1] * relativePos[2] +\n\t\t\t\t\t\t\tvectorInput[6][i] * relativePos[0] * relativePos[1] * (1 - relativePos[2]) +\n\t\t\t\t\t\t\tvectorInput[7][i] * relativePos[0] * relativePos[1] * relativePos[2];\n\t}\n\treturn vectorFinal;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2016 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : hugh\/support\/signal_handler.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ include i\/f header\n\n#include \"hugh\/support\/signal_handler.hpp\"\n\n\/\/ includes, system\n\n#include <array> \/\/ std::array<>\n#include <csignal> \/\/ ::sigfillset, ::pthread_sigmask\n#include <cstdlib> \/\/ std::abort, std::exit\n#include <cstring> \/\/ ::strsignal\n#include <iomanip> \/\/ std::boolalpha\n#include <iostream> \/\/ std::cerr\n#include <thread> \/\/ std::thread\n#include <unordered_map> \/\/ std::unordered_map<>\n\n\/\/ includes, project\n\n\/\/#include <>\n\n#define HUGH_USE_TRACE\n#undef HUGH_USE_TRACE\n#include <hugh\/support\/trace.hpp>\n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n\n using handler_map_type = std::unordered_map<signed,\n hugh::support::signal_handler::handler_function_type>;\n \n \/\/ variables, internal\n\n bool initialized(false);\n handler_map_type handler_map;\n std::unique_ptr<std::thread> handler_thread(nullptr);\n \n \/\/ functions, internal\n\n void\n default_handler_indirect(int \/* signo *\/, ::siginfo_t* value, void* \/* user_data *\/)\n {\n TRACE(\"hugh::support::signal_handler::<unnamed>::default_handler_indirect\");\n \n handler_map[value->si_signo](value->si_signo);\n }\n\n void\n default_handler(signed signo)\n {\n TRACE(\"hugh::support::signal_handler::<unnamed>::default_handler\");\n \n volatile bool ignore_signal(false);\n volatile bool create_core(false);\n volatile bool fatal_exit(false);\n\n switch (signo) {\n case SIGUSR1:\n case SIGUSR2:\n case SIGCHLD:\n case SIGTSTP:\n case SIGCONT:\n case SIGTTIN:\n case SIGTTOU:\n case SIGPROF:\n case SIGURG:\n case SIGVTALRM:\n \/\/ case SIGCLD:\n case SIGWINCH:\n ignore_signal = true;\n break;\n }\n\n switch (signo) {\n case SIGQUIT:\n case SIGILL:\n case SIGABRT:\n case SIGFPE:\n case SIGSEGV:\n case SIGBUS:\n case SIGSYS:\n case SIGTRAP:\n case SIGXCPU:\n case SIGXFSZ:\n \/\/ case SIGIOT:\n \/\/ case SIGLOST:\n create_core = true;\n break;\n\n case SIGALRM:\n case SIGPIPE:\n fatal_exit = true;\n break;\n\n case SIGHUP:\n case SIGINT:\n case SIGTERM:\n case SIGPOLL:\n \/\/ case SIGEMT:\n case SIGSTKFLT:\n \/\/ case SIGIO:\n case SIGPWR:\n break;\n\n default:\n break;\n }\n\n#if 0\n {\n std::cerr << '\\n'\n << \"support::signal_handler::<unnamed>::default_handler: \"\n << \"caught signal '\" << ::strsignal(signo) << \"'; \"\n << \"ignore:\" << std::boolalpha << ignore_signal << \", \"\n << \"core:\" << std::boolalpha << create_core << \", \"\n << \"fatal:\" << std::boolalpha << fatal_exit << \", \"\n << '\\n';\n }\n#endif\n\n if (ignore_signal) {\n return;\n }\n\n if (create_core) {\n std::abort();\n }\n\n if (fatal_exit) {\n std::exit(EXIT_FAILURE);\n }\n\n std::exit(EXIT_SUCCESS);\n }\n\n void\n signal_thread_function()\n {\n TRACE(\"hugh::support::signal_handler::<unnamed>::signal_thread_function\");\n \n bool done(false);\n\n while (!done) {\n TRACE_NEVER(\"hugh::support::signal_handler::<unnamed>::signal_thread_function[loop]\");\n \n ::sigset_t signal_mask;\n\n \/\/ unblock all signals and refill the mask for signals to be handled\n\n ::sigfillset (&signal_mask);\n ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0);\n\n ::siginfo_t value;\n\n \/\/ wait for signal\n\n bool evaluate(true);\n\n if (-1 == ::sigwaitinfo(&signal_mask, &value)) {\n if (EINTR != errno)\n std::abort();\n else\n evaluate = false;\n }\n\n \/\/ block all signal and handle current one\n\n ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0);\n\n#if 0\n {\n std::cerr << '\\n'\n << \"support::signal_handler::<unnamed>::signal_thread_function: \"\n << ((evaluate) ? \"\" : \"!\") << \"evaluating signal \"\n << ::strsignal(value.si_signo)\n << '\\n';\n }\n#endif\n \n if (evaluate) {\n handler_map[value.si_signo](value.si_signo);\n }\n }\n }\n \n void\n initialize()\n {\n TRACE(\"hugh::support::signal_handler::<unnamed>::initialize\");\n \n if (!initialized) {\n static std::array<signed const, 3> const sync_signals = {\n {\n SIGSEGV, SIGFPE, SIGILL,\n }\n };\n \n ::sigset_t signal_mask;\n\n ::sigfillset(&signal_mask);\n\n for (unsigned i(0); i < sync_signals.size(); ++i) {\n ::sigdelset(&signal_mask, sync_signals[i]);\n }\n \n for (unsigned i(1); i < _NSIG; ++i) {\n handler_map[i] = default_handler;\n }\n \n struct sigaction sa;\n\n sa.sa_sigaction = default_handler_indirect;\n sa.sa_flags = SA_SIGINFO;\n\n ::sigemptyset(&sa.sa_mask);\n\n for (unsigned i(0); i < sync_signals.size(); ++i) {\n ::sigaction(sync_signals[i], &sa, 0);\n }\n \n ::sigfillset (&signal_mask);\n ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0);\n {\n handler_thread.reset(new std::thread(signal_thread_function));\n }\n ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0);\n \n \/\/ avoid exception when 'handler_thread' is destructed\n handler_thread->detach();\n\n initialized = true;\n }\n }\n\n} \/\/ namespace {\n\nnamespace hugh {\n \n namespace support {\n \n \/\/ variables, exported\n \n \/\/ functions, exported\n\n signal_handler::~signal_handler()\n {\n TRACE(\"hugh::support::signal_handler::signal_handler\");\n }\n\n signal_handler::handler_function_type\n signal_handler::handler(signed signo)\n {\n TRACE(\"hugh::support::signal_handler::handler(get)\");\n \n return handler_map[signo];\n }\n\n signal_handler::handler_function_type\n signal_handler::handler(signed signo, handler_function_type new_handler)\n {\n TRACE(\"hugh::support::signal_handler::handler(set)\");\n \n handler_function_type old_handler(handler_map[signo]);\n\n if (new_handler) {\n handler_map[signo] = new_handler;\n }\n \n return old_handler;\n }\n\n \/* explicit *\/\n signal_handler::signal_handler(boost::restricted)\n {\n TRACE(\"hugh::support::signal_handler::signal_handler\");\n \n initialize();\n }\n\n std::string\n signal_name(signed signo)\n {\n TRACE(\"hugh::support::signal_name\");\n\n std::string result(\"UNKNOWN SIGNAL\");\n\n if ((0 < signo) && (_NSIG > signo)) {\n result = sys_siglist[signo];\n }\n \n return result;\n }\n \n } \/\/ namespace support {\n\n} \/\/ namespace hugh {\n<commit_msg>added: some tracing decoration<commit_after>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2016 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : hugh\/support\/signal_handler.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ include i\/f header\n\n#include \"hugh\/support\/signal_handler.hpp\"\n\n\/\/ includes, system\n\n#include <array> \/\/ std::array<>\n#include <csignal> \/\/ ::sigfillset, ::pthread_sigmask\n#include <cstdlib> \/\/ std::abort, std::exit\n#include <cstring> \/\/ ::strsignal\n#include <iomanip> \/\/ std::boolalpha\n#include <iostream> \/\/ std::cerr\n#include <thread> \/\/ std::thread\n#include <unordered_map> \/\/ std::unordered_map<>\n\n\/\/ includes, project\n\n\/\/#include <>\n\n#define HUGH_USE_TRACE\n#undef HUGH_USE_TRACE\n#include <hugh\/support\/trace.hpp>\n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n\n using handler_map_type = std::unordered_map<signed,\n hugh::support::signal_handler::handler_function_type>;\n \n \/\/ variables, internal\n\n bool initialized(false);\n handler_map_type handler_map;\n std::unique_ptr<std::thread> handler_thread(nullptr);\n \n \/\/ functions, internal\n\n void\n default_handler_indirect(int \/* signo *\/, ::siginfo_t* value, void* \/* user_data *\/)\n {\n TRACE(\"hugh::support::signal_handler::<unnamed>::default_handler_indirect\");\n \n handler_map[value->si_signo](value->si_signo);\n }\n\n void\n default_handler(signed signo)\n {\n TRACE(\"hugh::support::signal_handler::<unnamed>::default_handler(\" + std::to_string(signo) +\n \") [\" + hugh::support::signal_name(signo) + \"]\");\n \n volatile bool ignore_signal(false);\n volatile bool create_core(false);\n volatile bool fatal_exit(false);\n\n switch (signo) {\n case SIGUSR1:\n case SIGUSR2:\n case SIGCHLD:\n case SIGTSTP:\n case SIGCONT:\n case SIGTTIN:\n case SIGTTOU:\n case SIGPROF:\n case SIGURG:\n case SIGVTALRM:\n \/\/ case SIGCLD:\n case SIGWINCH:\n ignore_signal = true;\n break;\n }\n\n switch (signo) {\n case SIGQUIT:\n case SIGILL:\n case SIGABRT:\n case SIGFPE:\n case SIGSEGV:\n case SIGBUS:\n case SIGSYS:\n case SIGTRAP:\n case SIGXCPU:\n case SIGXFSZ:\n \/\/ case SIGIOT:\n \/\/ case SIGLOST:\n create_core = true;\n break;\n\n case SIGALRM:\n case SIGPIPE:\n fatal_exit = true;\n break;\n\n case SIGHUP:\n case SIGINT:\n case SIGTERM:\n case SIGPOLL:\n \/\/ case SIGEMT:\n case SIGSTKFLT:\n \/\/ case SIGIO:\n case SIGPWR:\n break;\n\n default:\n break;\n }\n\n#if 0\n {\n std::cerr << '\\n'\n << \"support::signal_handler::<unnamed>::default_handler: \"\n << \"caught signal '\" << ::strsignal(signo) << \"'; \"\n << \"ignore:\" << std::boolalpha << ignore_signal << \", \"\n << \"core:\" << std::boolalpha << create_core << \", \"\n << \"fatal:\" << std::boolalpha << fatal_exit << \", \"\n << '\\n';\n }\n#endif\n\n if (ignore_signal) {\n return;\n }\n\n if (create_core) {\n std::abort();\n }\n\n if (fatal_exit) {\n std::exit(EXIT_FAILURE);\n }\n\n std::exit(EXIT_SUCCESS);\n }\n\n void\n signal_thread_function()\n {\n TRACE(\"hugh::support::signal_handler::<unnamed>::signal_thread_function\");\n \n bool done(false);\n\n while (!done) {\n TRACE_NEVER(\"hugh::support::signal_handler::<unnamed>::signal_thread_function[loop]\");\n \n ::sigset_t signal_mask;\n\n \/\/ unblock all signals and refill the mask for signals to be handled\n\n ::sigfillset (&signal_mask);\n ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0);\n\n ::siginfo_t value;\n\n \/\/ wait for signal\n\n bool evaluate(true);\n\n if (-1 == ::sigwaitinfo(&signal_mask, &value)) {\n if (EINTR != errno)\n std::abort();\n else\n evaluate = false;\n }\n\n \/\/ block all signal and handle current one\n\n ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0);\n\n#if 0\n {\n std::cerr << '\\n'\n << \"support::signal_handler::<unnamed>::signal_thread_function: \"\n << ((evaluate) ? \"\" : \"!\") << \"evaluating signal \"\n << ::strsignal(value.si_signo)\n << '\\n';\n }\n#endif\n \n if (evaluate) {\n handler_map[value.si_signo](value.si_signo);\n }\n }\n }\n \n void\n initialize()\n {\n TRACE(\"hugh::support::signal_handler::<unnamed>::initialize\");\n \n if (!initialized) {\n static std::array<signed const, 3> const sync_signals = {\n {\n SIGSEGV, SIGFPE, SIGILL,\n }\n };\n \n ::sigset_t signal_mask;\n\n ::sigfillset(&signal_mask);\n\n for (unsigned i(0); i < sync_signals.size(); ++i) {\n ::sigdelset(&signal_mask, sync_signals[i]);\n }\n \n for (unsigned i(1); i < _NSIG; ++i) {\n handler_map[i] = default_handler;\n }\n \n struct sigaction sa;\n\n sa.sa_sigaction = default_handler_indirect;\n sa.sa_flags = SA_SIGINFO;\n\n ::sigemptyset(&sa.sa_mask);\n\n for (unsigned i(0); i < sync_signals.size(); ++i) {\n ::sigaction(sync_signals[i], &sa, 0);\n }\n \n ::sigfillset (&signal_mask);\n ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0);\n {\n handler_thread.reset(new std::thread(signal_thread_function));\n }\n ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0);\n \n \/\/ avoid exception when 'handler_thread' is destructed\n handler_thread->detach();\n\n initialized = true;\n }\n }\n\n} \/\/ namespace {\n\nnamespace hugh {\n \n namespace support {\n \n \/\/ variables, exported\n \n \/\/ functions, exported\n\n signal_handler::~signal_handler()\n {\n TRACE(\"hugh::support::signal_handler::signal_handler\");\n }\n\n signal_handler::handler_function_type\n signal_handler::handler(signed signo)\n {\n TRACE(\"hugh::support::signal_handler::handler(get)\");\n \n return handler_map[signo];\n }\n\n signal_handler::handler_function_type\n signal_handler::handler(signed signo, handler_function_type new_handler)\n {\n TRACE(\"hugh::support::signal_handler::handler(set)\");\n \n handler_function_type old_handler(handler_map[signo]);\n\n if (new_handler) {\n handler_map[signo] = new_handler;\n }\n \n return old_handler;\n }\n\n \/* explicit *\/\n signal_handler::signal_handler(boost::restricted)\n {\n TRACE(\"hugh::support::signal_handler::signal_handler\");\n \n initialize();\n }\n\n std::string\n signal_name(signed signo)\n {\n TRACE(\"hugh::support::signal_name\");\n\n std::string result(\"UNKNOWN SIGNAL\");\n\n if ((0 < signo) && (_NSIG > signo)) {\n result = sys_siglist[signo];\n }\n \n return result;\n }\n \n } \/\/ namespace support {\n\n} \/\/ namespace hugh {\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: RGrid.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\/\/ This example shows how to create a rectilinear grid.\n\/\/\n\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkRectilinearGrid.h\"\n#include \"vtkRectilinearGridGeometryFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkActor.h\"\n#include \"vtkProperty.h\"\n#include \"vtkCamera.h\"\n\nint main()\n{\n int i;\n static float x[47]={\n -1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542, \n -0.911458, -0.859375, -0.807292, -0.755208, -0.703125, -0.651042, \n -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542, \n -0.286458, -0.234375, -0.182292, -0.130209, -0.078125, -0.026042, \n 0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458, \n 0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958, \n 0.651042, 0.703125, 0.755208, 0.807292, 0.859375, 0.911458, \n 0.963542, 1.01562, 1.06771, 1.11979, 1.17188};\n static float y[33]={-1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375, \n -0.78125, -0.703125, -0.625, -0.546875, -0.46875, -0.390625, \n -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125, \n 0.15625, 0.234375, 0.3125, 0.390625, 0.46875, 0.546875, \n 0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562, \n 1.09375, 1.17188, 1.25};\n static float z[44]={0, 0.1, 0.2, 0.3, 0.4, 0.5, \n 0.6, 0.7, 0.75, 0.8, 0.9, 1, \n 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, \n 1.7, 1.75, 1.8, 1.9, 2, 2.1, \n 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, \n 2.75, 2.8, 2.9, 3, 3.1, 3.2, \n 3.3, 3.4, 3.5, 3.6, 3.7, 3.75, \n 3.8, 3.9};\n\n \/\/ Create a rectilinear grid by defining three arrays specifying the\n \/\/ coordinates in the x-y-z directions.\n vtkFloatArray *xCoords = vtkFloatArray::New();\n for (i=0; i<47; i++) xCoords->InsertNextValue(x[i]);\n \n vtkFloatArray *yCoords = vtkFloatArray::New();\n for (i=0; i<33; i++) yCoords->InsertNextValue(y[i]);\n \n vtkFloatArray *zCoords = vtkFloatArray::New();\n for (i=0; i<44; i++) zCoords->InsertNextValue(z[i]);\n \n \/\/ The coordinates are assigned to the rectilinear grid. Make sure that\n \/\/ the number of values in each of the XCoordinates, YCoordinates, \n \/\/ and ZCoordinates is equal to what is defined in SetDimensions().\n \/\/\n vtkRectilinearGrid *rgrid = vtkRectilinearGrid::New();\n rgrid->SetDimensions(47,33,44);\n rgrid->SetXCoordinates(xCoords);\n rgrid->SetYCoordinates(yCoords);\n rgrid->SetZCoordinates(zCoords);\n\n \/\/ Extract a plane from the grid to see what we've got.\n vtkRectilinearGridGeometryFilter *plane = vtkRectilinearGridGeometryFilter::New();\n plane->SetInput(rgrid);\n plane->SetExtent(0,46, 16,16, 0,43);\n\n vtkPolyDataMapper *rgridMapper = vtkPolyDataMapper::New();\n rgridMapper->SetInput(plane->GetOutput());\n\n vtkActor *wireActor = vtkActor::New();\n wireActor->SetMapper(rgridMapper);\n wireActor->GetProperty()->SetRepresentationToWireframe();\n wireActor->GetProperty()->SetColor(0,0,0);\n\n \/\/ Create the usual rendering stuff.\n vtkRenderer *renderer = vtkRenderer::New();\n vtkRenderWindow *renWin = vtkRenderWindow::New();\n renWin->AddRenderer(renderer);\n vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n\n renderer->AddActor(wireActor);\n renderer->SetBackground(1,1,1);\n renderer->ResetCamera();\n renderer->GetActiveCamera()->Elevation(60.0);\n renderer->GetActiveCamera()->Azimuth(30.0);\n renderer->GetActiveCamera()->Zoom(1.0);\n \n renWin->SetSize(300,300);\n\n \/\/ interact with data\n renWin->Render();\n iren->Start();\n\n \/\/ Clean up\n renderer->Delete();\n renWin->Delete();\n iren->Delete();\n xCoords->Delete();\n yCoords->Delete();\n zCoords->Delete();\n rgrid->Delete();\n rgridMapper->Delete();\n wireActor->Delete();\n\n return 0;\n}\n<commit_msg>COMP: add missing Delete<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: RGrid.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\/\/ This example shows how to create a rectilinear grid.\n\/\/\n\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkRectilinearGrid.h\"\n#include \"vtkRectilinearGridGeometryFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkActor.h\"\n#include \"vtkProperty.h\"\n#include \"vtkCamera.h\"\n\nint main()\n{\n int i;\n static float x[47]={\n -1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542, \n -0.911458, -0.859375, -0.807292, -0.755208, -0.703125, -0.651042, \n -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542, \n -0.286458, -0.234375, -0.182292, -0.130209, -0.078125, -0.026042, \n 0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458, \n 0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958, \n 0.651042, 0.703125, 0.755208, 0.807292, 0.859375, 0.911458, \n 0.963542, 1.01562, 1.06771, 1.11979, 1.17188};\n static float y[33]={-1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375, \n -0.78125, -0.703125, -0.625, -0.546875, -0.46875, -0.390625, \n -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125, \n 0.15625, 0.234375, 0.3125, 0.390625, 0.46875, 0.546875, \n 0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562, \n 1.09375, 1.17188, 1.25};\n static float z[44]={0, 0.1, 0.2, 0.3, 0.4, 0.5, \n 0.6, 0.7, 0.75, 0.8, 0.9, 1, \n 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, \n 1.7, 1.75, 1.8, 1.9, 2, 2.1, \n 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, \n 2.75, 2.8, 2.9, 3, 3.1, 3.2, \n 3.3, 3.4, 3.5, 3.6, 3.7, 3.75, \n 3.8, 3.9};\n\n \/\/ Create a rectilinear grid by defining three arrays specifying the\n \/\/ coordinates in the x-y-z directions.\n vtkFloatArray *xCoords = vtkFloatArray::New();\n for (i=0; i<47; i++) xCoords->InsertNextValue(x[i]);\n \n vtkFloatArray *yCoords = vtkFloatArray::New();\n for (i=0; i<33; i++) yCoords->InsertNextValue(y[i]);\n \n vtkFloatArray *zCoords = vtkFloatArray::New();\n for (i=0; i<44; i++) zCoords->InsertNextValue(z[i]);\n \n \/\/ The coordinates are assigned to the rectilinear grid. Make sure that\n \/\/ the number of values in each of the XCoordinates, YCoordinates, \n \/\/ and ZCoordinates is equal to what is defined in SetDimensions().\n \/\/\n vtkRectilinearGrid *rgrid = vtkRectilinearGrid::New();\n rgrid->SetDimensions(47,33,44);\n rgrid->SetXCoordinates(xCoords);\n rgrid->SetYCoordinates(yCoords);\n rgrid->SetZCoordinates(zCoords);\n\n \/\/ Extract a plane from the grid to see what we've got.\n vtkRectilinearGridGeometryFilter *plane = vtkRectilinearGridGeometryFilter::New();\n plane->SetInput(rgrid);\n plane->SetExtent(0,46, 16,16, 0,43);\n\n vtkPolyDataMapper *rgridMapper = vtkPolyDataMapper::New();\n rgridMapper->SetInput(plane->GetOutput());\n\n vtkActor *wireActor = vtkActor::New();\n wireActor->SetMapper(rgridMapper);\n wireActor->GetProperty()->SetRepresentationToWireframe();\n wireActor->GetProperty()->SetColor(0,0,0);\n\n \/\/ Create the usual rendering stuff.\n vtkRenderer *renderer = vtkRenderer::New();\n vtkRenderWindow *renWin = vtkRenderWindow::New();\n renWin->AddRenderer(renderer);\n vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n\n renderer->AddActor(wireActor);\n renderer->SetBackground(1,1,1);\n renderer->ResetCamera();\n renderer->GetActiveCamera()->Elevation(60.0);\n renderer->GetActiveCamera()->Azimuth(30.0);\n renderer->GetActiveCamera()->Zoom(1.0);\n \n renWin->SetSize(300,300);\n\n \/\/ interact with data\n renWin->Render();\n iren->Start();\n\n \/\/ Clean up\n plane->Delete();\n renderer->Delete();\n renWin->Delete();\n iren->Delete();\n xCoords->Delete();\n yCoords->Delete();\n zCoords->Delete();\n rgrid->Delete();\n rgridMapper->Delete();\n wireActor->Delete();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2014 Petar Perisin <petar.perisin@gmail.com>\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"ansiescapecodehandler.h\"\n#include <utils\/qtcassert.h>\n\nnamespace Utils {\n\n\/*!\n \\class Utils::AnsiEscapeCodeHandler\n\n \\brief The AnsiEscapeCodeHandler class parses text and extracts ANSI escape codes from it.\n\n In order to preserve color information across text segments, an instance of this class\n must be stored for the lifetime of a stream.\n Also, one instance of this class should not handle multiple streams (at least not\n at the same time).\n\n Its main function is parseText(), which accepts text and default QTextCharFormat.\n This function is designed to parse text and split colored text to smaller strings,\n with their appropriate formatting information set inside QTextCharFormat.\n\n Usage:\n \\list\n \\li Create new instance of AnsiEscapeCodeHandler for a stream.\n \\li To add new text, call parseText() with the text and a default QTextCharFormat.\n The result of this function is a list of strings with formats set in appropriate\n QTextCharFormat.\n \\endlist\n*\/\n\nAnsiEscapeCodeHandler::AnsiEscapeCodeHandler() :\n m_previousFormatClosed(true)\n{\n}\n\nstatic QColor ansiColor(uint code)\n{\n QTC_ASSERT(code < 8, return QColor());\n\n const int red = code & 1 ? 170 : 0;\n const int green = code & 2 ? 170 : 0;\n const int blue = code & 4 ? 170 : 0;\n return QColor(red, green, blue);\n}\n\nQList<FormattedText> AnsiEscapeCodeHandler::parseText(const FormattedText &input)\n{\n enum AnsiEscapeCodes {\n ResetFormat = 0,\n BoldText = 1,\n TextColorStart = 30,\n TextColorEnd = 37,\n RgbTextColor = 38,\n DefaultTextColor = 39,\n BackgroundColorStart = 40,\n BackgroundColorEnd = 47,\n RgbBackgroundColor = 48,\n DefaultBackgroundColor = 49\n };\n\n QList<FormattedText> outputData;\n\n QTextCharFormat charFormat = m_previousFormatClosed ? input.format : m_previousFormat;\n\n const QString escape = QLatin1String(\"\\x1b[\");\n if (!input.text.contains(escape)) {\n outputData << FormattedText(input.text, charFormat);\n return outputData;\n } else if (!input.text.startsWith(escape)) {\n outputData << FormattedText(input.text.left(input.text.indexOf(escape)), charFormat);\n }\n\n const QChar semicolon = QLatin1Char(';');\n const QChar colorTerminator = QLatin1Char('m');\n \/\/ strippedText always starts with \"\\e[\"\n QString strippedText = input.text.mid(input.text.indexOf(escape));\n while (!strippedText.isEmpty()) {\n while (strippedText.startsWith(escape)) {\n strippedText.remove(0, 2);\n\n \/\/ get the number\n QString strNumber;\n QStringList numbers;\n while (strippedText.at(0).isDigit() || strippedText.at(0) == semicolon) {\n if (strippedText.at(0).isDigit()) {\n strNumber += strippedText.at(0);\n } else {\n numbers << strNumber;\n strNumber.clear();\n }\n strippedText.remove(0, 1);\n }\n if (!strNumber.isEmpty())\n numbers << strNumber;\n\n \/\/ remove terminating char\n if (!strippedText.startsWith(colorTerminator)) {\n strippedText.remove(0, 1);\n continue;\n }\n strippedText.remove(0, 1);\n\n if (numbers.isEmpty()) {\n charFormat = input.format;\n endFormatScope();\n }\n\n for (int i = 0; i < numbers.size(); ++i) {\n const int code = numbers.at(i).toInt();\n\n if (code >= TextColorStart && code <= TextColorEnd) {\n charFormat.setForeground(ansiColor(code - TextColorStart));\n setFormatScope(charFormat);\n } else if (code >= BackgroundColorStart && code <= BackgroundColorEnd) {\n charFormat.setBackground(ansiColor(code - BackgroundColorStart));\n setFormatScope(charFormat);\n } else {\n switch (code) {\n case ResetFormat:\n charFormat = input.format;\n endFormatScope();\n break;\n case BoldText:\n charFormat.setFontWeight(QFont::Bold);\n setFormatScope(charFormat);\n break;\n case DefaultTextColor:\n charFormat.setForeground(input.format.foreground());\n setFormatScope(charFormat);\n break;\n case DefaultBackgroundColor:\n charFormat.setBackground(input.format.background());\n setFormatScope(charFormat);\n break;\n case RgbTextColor:\n case RgbBackgroundColor:\n if (++i >= numbers.size())\n break;\n if (numbers.at(i).toInt() == 2) {\n \/\/ RGB set with format: 38;2;<r>;<g>;<b>\n if ((i + 3) < numbers.size()) {\n (code == RgbTextColor) ?\n charFormat.setForeground(QColor(numbers.at(i + 1).toInt(),\n numbers.at(i + 2).toInt(),\n numbers.at(i + 3).toInt())) :\n charFormat.setBackground(QColor(numbers.at(i + 1).toInt(),\n numbers.at(i + 2).toInt(),\n numbers.at(i + 3).toInt()));\n setFormatScope(charFormat);\n }\n i += 3;\n } else if (numbers.at(i).toInt() == 5) {\n \/\/ rgb set with format: 38;5;<i>\n \/\/ unsupported because of unclear documentation, so we just skip <i>\n ++i;\n }\n break;\n default:\n break;\n }\n }\n }\n }\n\n if (strippedText.isEmpty())\n break;\n int index = strippedText.indexOf(escape);\n if (index > 0) {\n outputData << FormattedText(strippedText.left(index), charFormat);\n strippedText.remove(0, index);\n } else if (index == -1) {\n outputData << FormattedText(strippedText, charFormat);\n break;\n }\n }\n return outputData;\n}\n\nvoid AnsiEscapeCodeHandler::endFormatScope()\n{\n m_previousFormatClosed = true;\n}\n\nvoid AnsiEscapeCodeHandler::setFormatScope(const QTextCharFormat &charFormat)\n{\n m_previousFormat = charFormat;\n m_previousFormatClosed = false;\n}\n\n} \/\/ namespace Utils\n<commit_msg>AnsiEscapeHandler: Avoid some iterations over the string<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2014 Petar Perisin <petar.perisin@gmail.com>\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"ansiescapecodehandler.h\"\n#include <utils\/qtcassert.h>\n\nnamespace Utils {\n\n\/*!\n \\class Utils::AnsiEscapeCodeHandler\n\n \\brief The AnsiEscapeCodeHandler class parses text and extracts ANSI escape codes from it.\n\n In order to preserve color information across text segments, an instance of this class\n must be stored for the lifetime of a stream.\n Also, one instance of this class should not handle multiple streams (at least not\n at the same time).\n\n Its main function is parseText(), which accepts text and default QTextCharFormat.\n This function is designed to parse text and split colored text to smaller strings,\n with their appropriate formatting information set inside QTextCharFormat.\n\n Usage:\n \\list\n \\li Create new instance of AnsiEscapeCodeHandler for a stream.\n \\li To add new text, call parseText() with the text and a default QTextCharFormat.\n The result of this function is a list of strings with formats set in appropriate\n QTextCharFormat.\n \\endlist\n*\/\n\nAnsiEscapeCodeHandler::AnsiEscapeCodeHandler() :\n m_previousFormatClosed(true)\n{\n}\n\nstatic QColor ansiColor(uint code)\n{\n QTC_ASSERT(code < 8, return QColor());\n\n const int red = code & 1 ? 170 : 0;\n const int green = code & 2 ? 170 : 0;\n const int blue = code & 4 ? 170 : 0;\n return QColor(red, green, blue);\n}\n\nQList<FormattedText> AnsiEscapeCodeHandler::parseText(const FormattedText &input)\n{\n enum AnsiEscapeCodes {\n ResetFormat = 0,\n BoldText = 1,\n TextColorStart = 30,\n TextColorEnd = 37,\n RgbTextColor = 38,\n DefaultTextColor = 39,\n BackgroundColorStart = 40,\n BackgroundColorEnd = 47,\n RgbBackgroundColor = 48,\n DefaultBackgroundColor = 49\n };\n\n QList<FormattedText> outputData;\n\n QTextCharFormat charFormat = m_previousFormatClosed ? input.format : m_previousFormat;\n\n const QString escape = QLatin1String(\"\\x1b[\");\n const int escapePos = input.text.indexOf(escape);\n if (escapePos < 0) {\n outputData << FormattedText(input.text, charFormat);\n return outputData;\n } else if (escapePos != 0) {\n outputData << FormattedText(input.text.left(escapePos), charFormat);\n }\n\n const QChar semicolon = QLatin1Char(';');\n const QChar colorTerminator = QLatin1Char('m');\n \/\/ strippedText always starts with \"\\e[\"\n QString strippedText = input.text.mid(escapePos);\n while (!strippedText.isEmpty()) {\n while (strippedText.startsWith(escape)) {\n strippedText.remove(0, 2);\n\n \/\/ get the number\n QString strNumber;\n QStringList numbers;\n while (strippedText.at(0).isDigit() || strippedText.at(0) == semicolon) {\n if (strippedText.at(0).isDigit()) {\n strNumber += strippedText.at(0);\n } else {\n numbers << strNumber;\n strNumber.clear();\n }\n strippedText.remove(0, 1);\n }\n if (!strNumber.isEmpty())\n numbers << strNumber;\n\n \/\/ remove terminating char\n if (!strippedText.startsWith(colorTerminator)) {\n strippedText.remove(0, 1);\n continue;\n }\n strippedText.remove(0, 1);\n\n if (numbers.isEmpty()) {\n charFormat = input.format;\n endFormatScope();\n }\n\n for (int i = 0; i < numbers.size(); ++i) {\n const int code = numbers.at(i).toInt();\n\n if (code >= TextColorStart && code <= TextColorEnd) {\n charFormat.setForeground(ansiColor(code - TextColorStart));\n setFormatScope(charFormat);\n } else if (code >= BackgroundColorStart && code <= BackgroundColorEnd) {\n charFormat.setBackground(ansiColor(code - BackgroundColorStart));\n setFormatScope(charFormat);\n } else {\n switch (code) {\n case ResetFormat:\n charFormat = input.format;\n endFormatScope();\n break;\n case BoldText:\n charFormat.setFontWeight(QFont::Bold);\n setFormatScope(charFormat);\n break;\n case DefaultTextColor:\n charFormat.setForeground(input.format.foreground());\n setFormatScope(charFormat);\n break;\n case DefaultBackgroundColor:\n charFormat.setBackground(input.format.background());\n setFormatScope(charFormat);\n break;\n case RgbTextColor:\n case RgbBackgroundColor:\n if (++i >= numbers.size())\n break;\n if (numbers.at(i).toInt() == 2) {\n \/\/ RGB set with format: 38;2;<r>;<g>;<b>\n if ((i + 3) < numbers.size()) {\n (code == RgbTextColor) ?\n charFormat.setForeground(QColor(numbers.at(i + 1).toInt(),\n numbers.at(i + 2).toInt(),\n numbers.at(i + 3).toInt())) :\n charFormat.setBackground(QColor(numbers.at(i + 1).toInt(),\n numbers.at(i + 2).toInt(),\n numbers.at(i + 3).toInt()));\n setFormatScope(charFormat);\n }\n i += 3;\n } else if (numbers.at(i).toInt() == 5) {\n \/\/ rgb set with format: 38;5;<i>\n \/\/ unsupported because of unclear documentation, so we just skip <i>\n ++i;\n }\n break;\n default:\n break;\n }\n }\n }\n }\n\n if (strippedText.isEmpty())\n break;\n int index = strippedText.indexOf(escape);\n if (index > 0) {\n outputData << FormattedText(strippedText.left(index), charFormat);\n strippedText.remove(0, index);\n } else if (index == -1) {\n outputData << FormattedText(strippedText, charFormat);\n break;\n }\n }\n return outputData;\n}\n\nvoid AnsiEscapeCodeHandler::endFormatScope()\n{\n m_previousFormatClosed = true;\n}\n\nvoid AnsiEscapeCodeHandler::setFormatScope(const QTextCharFormat &charFormat)\n{\n m_previousFormat = charFormat;\n m_previousFormatClosed = false;\n}\n\n} \/\/ namespace Utils\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\/\/ splitted from AliHLTConfiguration.cxx,v 1.25 2007\/10\/12 13:24:47\n\/**************************************************************************\n * This file is property of and copyright by the ALICE HLT Project * \n * ALICE Experiment at CERN, All rights reserved. *\n * *\n * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\n * for The ALICE HLT Project. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/** @file AliHLTConfigurationHandler.cxx\n @author Matthias Richter\n @date \n @brief Implementation of HLT tasks.\n*\/\n\n\/\/ see header file for class documentation\n\/\/ or\n\/\/ refer to README to build package\n\/\/ or\n\/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n\n#if __GNUC__>= 3\nusing namespace std;\n#endif\n\n#include <cerrno>\n#include <iostream>\n#include <string>\n#include \"AliHLTConfigurationHandler.h\"\n#include \"AliHLTConfiguration.h\"\n\n\/** ROOT macro for the implementation of ROOT specific class methods *\/\nClassImp(AliHLTConfigurationHandler)\n\nAliHLTConfigurationHandler::AliHLTConfigurationHandler()\n :\n fgListConfigurations()\n{\n \/\/ see header file for class documentation\n \/\/ or\n \/\/ refer to README to build package\n \/\/ or\n \/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n SetLocalLoggingLevel(kHLTLogInfo);\n}\n\nAliHLTConfigurationHandler::~AliHLTConfigurationHandler()\n{\n \/\/ see header file for function documentation\n TObjLink* lnk=NULL;\n while ((lnk=fgListConfigurations.FirstLink())!=NULL) {\n AliHLTConfiguration* pConf=(AliHLTConfiguration*)lnk->GetObject();\n HLTDebug(\"delete configuration \\\"%s\\\"\", pConf->GetName());\n fgListConfigurations.Remove(lnk);\n delete pConf;\n }\n}\n\nAliHLTConfigurationHandler* AliHLTConfigurationHandler::fgpInstance=NULL;\nint AliHLTConfigurationHandler::fgNofInstances=0;\n\nAliHLTConfigurationHandler* AliHLTConfigurationHandler::CreateHandler()\n{\n \/\/ see header file for class documentation\n if (!fgpInstance) fgpInstance=new AliHLTConfigurationHandler;\n fgNofInstances++;\n return fgpInstance;\n}\n\nint AliHLTConfigurationHandler::Destroy()\n{\n \/\/ see header file for class documentation\n int nofInstances=0;\n if (fgpInstance==this) {\n nofInstances=fgNofInstances--;\n }\n if (nofInstances==0) delete this;\n return nofInstances;\n}\n\n\nint AliHLTConfigurationHandler::RegisterConfiguration(AliHLTConfiguration* pConf)\n{\n \/\/ see header file for function documentation\n int iResult=0;\n if (pConf) {\n AliHLTConfiguration* pExisting=NULL;\n if ((pExisting=FindConfiguration(pConf->GetName())) == NULL) {\n AliHLTConfiguration* pClone=new AliHLTConfiguration(*pConf);\n fgListConfigurations.Add(pClone);\n HLTDebug(\"configuration \\\"%s\\\" (%p) registered from %p\", pClone->GetName(), pClone, pConf);\n\n \/\/ mark all configurations with unresolved dependencies for re-evaluation\n TObjLink* lnk=fgListConfigurations.FirstLink();\n while (lnk) {\n\tAliHLTConfiguration* pSrc=(AliHLTConfiguration*)lnk->GetObject();\n\tif (pSrc && pSrc!=pClone && pSrc->SourcesResolved()!=1) {\n\t pSrc->InvalidateSources();\n\t}\n\tlnk=lnk->Next();\n }\n } else {\n if ((*pExisting)!=(*pConf)) {\n iResult=-EEXIST;\n HLTWarning(\"configuration \\\"%s\\\" already registered with different properties\", pConf->GetName());\n }\n }\n } else {\n iResult=-EINVAL;\n }\n return iResult;\n}\n\nint AliHLTConfigurationHandler::CreateConfiguration(const char* id, const char* component, const char* sources, const char* arguments)\n{\n \/\/ see header file for function documentation\n int iResult=0;\n AliHLTConfiguration* pConf= new AliHLTConfiguration(id, component, sources, arguments);\n if (pConf) {\n \/\/ the configuration will be registered automatically, if this failes the configuration\n \/\/ is missing -> delete it\n if (FindConfiguration(id)==NULL) {\n delete pConf;\n pConf=NULL;\n iResult=-EEXIST;\n }\n } else {\n HLTError(\"system error: object allocation failed\");\n iResult=-ENOMEM;\n }\n return iResult;\n}\n\nvoid AliHLTConfigurationHandler::PrintConfigurations()\n{\n \/\/ see header file for function documentation\n HLTLogKeyword(\"configuration listing\");\n HLTMessage(\"registered configurations:\");\n TObjLink *lnk = fgListConfigurations.FirstLink();\n while (lnk) {\n TObject *obj = lnk->GetObject();\n HLTMessage(\" %s\", obj->GetName());\n lnk = lnk->Next();\n }\n}\n\nint AliHLTConfigurationHandler::RemoveConfiguration(const char* id)\n{\n \/\/ see header file for function documentation\n int iResult=0;\n if (id) {\n AliHLTConfiguration* pConf=NULL;\n if ((pConf=FindConfiguration(id))!=NULL) {\n iResult=RemoveConfiguration(pConf);\n delete pConf;\n pConf=NULL;\n } else {\n HLTWarning(\"can not find configuration \\\"%s\\\"\", id);\n iResult=-ENOENT;\n }\n } else {\n iResult=-EINVAL;\n }\n return iResult;\n}\n\nint AliHLTConfigurationHandler::RemoveConfiguration(AliHLTConfiguration* pConf)\n{\n \/\/ see header file for function documentation\n int iResult=0;\n if (pConf) {\n \/\/ remove the configuration from the list\n HLTDebug(\"remove configuration \\\"%s\\\"\", pConf->GetName());\n fgListConfigurations.Remove(pConf);\n \/\/ remove cross links in the remaining configurations\n TObjLink* lnk=fgListConfigurations.FirstLink();\n while (lnk && iResult>=0) {\n AliHLTConfiguration* pRem=(AliHLTConfiguration*)lnk->GetObject();\n if (pRem) {\n\tpRem->InvalidateSource(pConf);\n } else {\n\tiResult=-EFAULT;\n }\n lnk=lnk->Next();\n }\n }\n return iResult;\n}\n\nAliHLTConfiguration* AliHLTConfigurationHandler::FindConfiguration(const char* id)\n{\n \/\/ see header file for function documentation\n AliHLTConfiguration* pConf=NULL;\n if (id) {\n pConf=(AliHLTConfiguration*)fgListConfigurations.FindObject(id); \n }\n return pConf;\n}\n\n<commit_msg>Fixing bug in destruction of global instance.<commit_after>\/\/ $Id$\n\/\/ splitted from AliHLTConfiguration.cxx,v 1.25 2007\/10\/12 13:24:47\n\/**************************************************************************\n * This file is property of and copyright by the ALICE HLT Project * \n * ALICE Experiment at CERN, All rights reserved. *\n * *\n * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\n * for The ALICE HLT Project. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/** @file AliHLTConfigurationHandler.cxx\n @author Matthias Richter\n @date \n @brief Implementation of HLT tasks.\n*\/\n\n\/\/ see header file for class documentation\n\/\/ or\n\/\/ refer to README to build package\n\/\/ or\n\/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n\n#if __GNUC__>= 3\nusing namespace std;\n#endif\n\n#include <cerrno>\n#include <iostream>\n#include <string>\n#include \"AliHLTConfigurationHandler.h\"\n#include \"AliHLTConfiguration.h\"\n\n\/** ROOT macro for the implementation of ROOT specific class methods *\/\nClassImp(AliHLTConfigurationHandler)\n\nAliHLTConfigurationHandler::AliHLTConfigurationHandler()\n :\n fgListConfigurations()\n{\n \/\/ see header file for class documentation\n \/\/ or\n \/\/ refer to README to build package\n \/\/ or\n \/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n SetLocalLoggingLevel(kHLTLogInfo);\n}\n\nAliHLTConfigurationHandler::~AliHLTConfigurationHandler()\n{\n \/\/ see header file for function documentation\n TObjLink* lnk=NULL;\n while ((lnk=fgListConfigurations.FirstLink())!=NULL) {\n AliHLTConfiguration* pConf=(AliHLTConfiguration*)lnk->GetObject();\n HLTDebug(\"delete configuration \\\"%s\\\"\", pConf->GetName());\n fgListConfigurations.Remove(lnk);\n delete pConf;\n }\n}\n\nAliHLTConfigurationHandler* AliHLTConfigurationHandler::fgpInstance=NULL;\nint AliHLTConfigurationHandler::fgNofInstances=0;\n\nAliHLTConfigurationHandler* AliHLTConfigurationHandler::CreateHandler()\n{\n \/\/ see header file for class documentation\n if (!fgpInstance) fgpInstance=new AliHLTConfigurationHandler;\n fgNofInstances++;\n return fgpInstance;\n}\n\nint AliHLTConfigurationHandler::Destroy()\n{\n \/\/ see header file for class documentation\n int nofInstances=0;\n if (fgpInstance==this) {\n nofInstances=fgNofInstances--;\n }\n if (fgNofInstances==0) {\n delete fgpInstance;\n fgpInstance = NULL;\n }\n return nofInstances;\n}\n\n\nint AliHLTConfigurationHandler::RegisterConfiguration(AliHLTConfiguration* pConf)\n{\n \/\/ see header file for function documentation\n int iResult=0;\n if (pConf) {\n AliHLTConfiguration* pExisting=NULL;\n if ((pExisting=FindConfiguration(pConf->GetName())) == NULL) {\n AliHLTConfiguration* pClone=new AliHLTConfiguration(*pConf);\n fgListConfigurations.Add(pClone);\n HLTDebug(\"configuration \\\"%s\\\" (%p) registered from %p\", pClone->GetName(), pClone, pConf);\n\n \/\/ mark all configurations with unresolved dependencies for re-evaluation\n TObjLink* lnk=fgListConfigurations.FirstLink();\n while (lnk) {\n\tAliHLTConfiguration* pSrc=(AliHLTConfiguration*)lnk->GetObject();\n\tif (pSrc && pSrc!=pClone && pSrc->SourcesResolved()!=1) {\n\t pSrc->InvalidateSources();\n\t}\n\tlnk=lnk->Next();\n }\n } else {\n if ((*pExisting)!=(*pConf)) {\n iResult=-EEXIST;\n HLTWarning(\"configuration \\\"%s\\\" already registered with different properties\", pConf->GetName());\n }\n }\n } else {\n iResult=-EINVAL;\n }\n return iResult;\n}\n\nint AliHLTConfigurationHandler::CreateConfiguration(const char* id, const char* component, const char* sources, const char* arguments)\n{\n \/\/ see header file for function documentation\n int iResult=0;\n AliHLTConfiguration* pConf= new AliHLTConfiguration(id, component, sources, arguments);\n if (pConf) {\n \/\/ the configuration will be registered automatically, if this failes the configuration\n \/\/ is missing -> delete it\n if (FindConfiguration(id)==NULL) {\n delete pConf;\n pConf=NULL;\n iResult=-EEXIST;\n }\n } else {\n HLTError(\"system error: object allocation failed\");\n iResult=-ENOMEM;\n }\n return iResult;\n}\n\nvoid AliHLTConfigurationHandler::PrintConfigurations()\n{\n \/\/ see header file for function documentation\n HLTLogKeyword(\"configuration listing\");\n HLTMessage(\"registered configurations:\");\n TObjLink *lnk = fgListConfigurations.FirstLink();\n while (lnk) {\n TObject *obj = lnk->GetObject();\n HLTMessage(\" %s\", obj->GetName());\n lnk = lnk->Next();\n }\n}\n\nint AliHLTConfigurationHandler::RemoveConfiguration(const char* id)\n{\n \/\/ see header file for function documentation\n int iResult=0;\n if (id) {\n AliHLTConfiguration* pConf=NULL;\n if ((pConf=FindConfiguration(id))!=NULL) {\n iResult=RemoveConfiguration(pConf);\n delete pConf;\n pConf=NULL;\n } else {\n HLTWarning(\"can not find configuration \\\"%s\\\"\", id);\n iResult=-ENOENT;\n }\n } else {\n iResult=-EINVAL;\n }\n return iResult;\n}\n\nint AliHLTConfigurationHandler::RemoveConfiguration(AliHLTConfiguration* pConf)\n{\n \/\/ see header file for function documentation\n int iResult=0;\n if (pConf) {\n \/\/ remove the configuration from the list\n HLTDebug(\"remove configuration \\\"%s\\\"\", pConf->GetName());\n fgListConfigurations.Remove(pConf);\n \/\/ remove cross links in the remaining configurations\n TObjLink* lnk=fgListConfigurations.FirstLink();\n while (lnk && iResult>=0) {\n AliHLTConfiguration* pRem=(AliHLTConfiguration*)lnk->GetObject();\n if (pRem) {\n\tpRem->InvalidateSource(pConf);\n } else {\n\tiResult=-EFAULT;\n }\n lnk=lnk->Next();\n }\n }\n return iResult;\n}\n\nAliHLTConfiguration* AliHLTConfigurationHandler::FindConfiguration(const char* id)\n{\n \/\/ see header file for function documentation\n AliHLTConfiguration* pConf=NULL;\n if (id) {\n pConf=(AliHLTConfiguration*)fgListConfigurations.FindObject(id); \n }\n return pConf;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: ImagePlaneWidget.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkActor.h\"\n#include \"vtkActor2D.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCellPicker.h\"\n#include \"vtkCommand.h\"\n#include \"vtkImageActor.h\"\n#include \"vtkImageMapToColors.h\"\n#include \"vtkImagePlaneWidget.h\"\n#include \"vtkImageReader.h\"\n#include \"vtkLookupTable.h\"\n#include \"vtkOutlineFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkTextMapper.h\"\n#include \"vtkVolume16Reader.h\"\n\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkDebugLeaks.h\"\n\n\/\/ Callback for the interaction\nclass vtkMyCallback : public vtkCommand\n{\npublic:\n static vtkMyCallback *New()\n { return new vtkMyCallback; }\n void Delete()\n { delete this; }\n virtual void Execute(vtkObject *caller, unsigned long, void*)\n {\n vtkImagePlaneWidget *planeWidget = reinterpret_cast<vtkImagePlaneWidget*>(caller);\n\n sprintf(this->buffer,\"%.2f, %d\",planeWidget->GetSlicePosition(),planeWidget->GetSliceIndex());\n this->Mapper->SetInput(buffer);\n this->Mapper->Modified();\n }\n vtkMyCallback():Mapper(0){};\n vtkTextMapper* Mapper;\n char buffer[128];\n};\n\nint main( int argc, char *argv[] )\n{\n vtkDebugLeaks::PromptUserOff();\n\n char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/headsq\/quarter\");\n\n vtkVolume16Reader* v16 = vtkVolume16Reader::New();\n v16->SetDataDimensions( 64, 64);\n v16->SetDataByteOrderToLittleEndian(); \n v16->SetImageRange( 1, 93);\n v16->SetDataSpacing( 3.2, 3.2, 1.5);\n v16->SetFilePrefix( fname );\n v16->SetDataMask( 0x7fff);\n v16->Update();\n\n delete[] fname;\n\n vtkOutlineFilter* outline = vtkOutlineFilter::New();\n outline->SetInput(v16->GetOutput());\n\n vtkPolyDataMapper* outlineMapper = vtkPolyDataMapper::New();\n outlineMapper->SetInput(outline->GetOutput());\n\n vtkActor* outlineActor = vtkActor::New();\n outlineActor->SetMapper( outlineMapper);\n\n vtkRenderer* ren1 = vtkRenderer::New();\n vtkRenderer* ren2 = vtkRenderer::New();\n\n vtkRenderWindow* renWin = vtkRenderWindow::New();\n renWin->AddRenderer(ren2);\n renWin->AddRenderer(ren1);\n\n vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n\n vtkCellPicker* picker = vtkCellPicker::New();\n picker->SetTolerance(0.005);\n\n vtkImagePlaneWidget* planeWidgetX = vtkImagePlaneWidget::New();\n planeWidgetX->SetInteractor( iren);\n planeWidgetX->SetKeyPressActivationValue('x');\n planeWidgetX->SetPicker(picker);\n planeWidgetX->GetPlaneProperty()->SetColor(1,0,0);\n planeWidgetX->TextureInterpolateOff();\n planeWidgetX->SetResliceInterpolateToNearestNeighbour();\n planeWidgetX->SetInput(v16->GetOutput());\n planeWidgetX->SetPlaneOrientationToXAxes();\n planeWidgetX->SetSliceIndex(32);\n planeWidgetX->On();\n\n vtkImagePlaneWidget* planeWidgetY = vtkImagePlaneWidget::New();\n planeWidgetY->SetInteractor( iren);\n planeWidgetY->SetKeyPressActivationValue('y');\n planeWidgetY->SetPicker(picker);\n planeWidgetY->GetPlaneProperty()->SetColor(1,1,0);\n planeWidgetY->TextureInterpolateOn();\n planeWidgetY->SetResliceInterpolateToLinear();\n planeWidgetY->SetInput(v16->GetOutput());\n planeWidgetY->SetPlaneOrientationToYAxes();\n planeWidgetY->SetSlicePosition(102.4);\n planeWidgetY->SetLookupTable( planeWidgetX->GetLookupTable());\n planeWidgetY->On();\n\n vtkImagePlaneWidget* planeWidgetZ = vtkImagePlaneWidget::New();\n planeWidgetZ->SetInteractor( iren);\n planeWidgetZ->SetKeyPressActivationValue('z');\n planeWidgetZ->SetPicker(picker);\n planeWidgetZ->GetPlaneProperty()->SetColor(0,0,1);\n planeWidgetZ->TextureInterpolateOn();\n planeWidgetZ->SetResliceInterpolateToCubic();\n planeWidgetZ->SetInput(v16->GetOutput());\n planeWidgetZ->SetPlaneOrientationToZAxes();\n planeWidgetZ->SetSliceIndex(25);\n planeWidgetZ->SetLookupTable( planeWidgetX->GetLookupTable());\n planeWidgetZ->On();\n\n \/\/ add text display of planeWidgetZ's slice position and slice index to ren2\n vtkTextMapper* textMapper = vtkTextMapper::New();\n textMapper->SetInput(\"NA\");\n textMapper->SetFontSize(18);\n textMapper->SetFontFamilyToArial();\n textMapper->SetJustificationToLeft();\n textMapper->BoldOn();\n textMapper->ItalicOff();\n textMapper->ShadowOff();\n\n vtkActor2D* textActor = vtkActor2D::New();\n textActor->SetMapper(textMapper);\n textActor->GetProperty()->SetColor(0,1,1);\n\n \/\/ link the widget to the text by callback\n vtkMyCallback *myCallback = vtkMyCallback::New();\n myCallback->Mapper = textMapper;\n\n planeWidgetZ->AddObserver(vtkCommand::InteractionEvent,myCallback);\n\n \/\/ add a 2D image to test the GetReslice method\n vtkImageMapToColors* colorMap = vtkImageMapToColors::New();\n colorMap->PassAlphaToOutputOff();\n colorMap->SetActiveComponent(0);\n colorMap->SetOutputFormatToLuminance();\n colorMap->SetInput(planeWidgetZ->GetResliceOutput());\n colorMap->SetLookupTable(planeWidgetX->GetLookupTable());\n\n vtkImageActor* imageActor = vtkImageActor::New();\n imageActor->PickableOff();\n imageActor->SetInput(colorMap->GetOutput());\n\n \/\/ add the actors\n ren1->AddActor( outlineActor);\n ren2->AddActor( imageActor);\n ren2->AddActor( textActor);\n\n ren1->SetBackground( 0.1, 0.1, 0.2);\n ren2->SetBackground( 0.2, 0.1, 0.2);\n\n renWin->SetSize( 600, 350);\n\n ren1->SetViewport(0,0,0.58333,1);\n ren2->SetViewport(0.58333,0,1,1);\n\n \/\/ set the actors' postions\n renWin->Render();\n iren->SetEventPosition( 175,175);\n iren->SetKeyCode('r');\n iren->InvokeEvent(vtkCommand::CharEvent,NULL);\n iren->SetEventPosition( 475,175);\n iren->SetKeyCode('r');\n iren->InvokeEvent(vtkCommand::CharEvent,NULL);\n int *o = ren2->GetOrigin();\n textActor->SetDisplayPosition(o[0] + 5, o[1] + 5);\n renWin->Render();\n\n \/\/ test SetKeyPressActivationValue for one of the widgets\n iren->SetKeyCode('z');\n iren->InvokeEvent(vtkCommand::CharEvent,NULL);\n iren->SetKeyCode('z');\n iren->InvokeEvent(vtkCommand::CharEvent,NULL);\n\n ren1->GetActiveCamera()->Elevation(110);\n ren1->GetActiveCamera()->SetViewUp(0, 0, -1);\n ren1->GetActiveCamera()->Azimuth(45);\n ren1->GetActiveCamera()->Dolly(1.15);\n ren1->ResetCameraClippingRange();\n\n \/\/ make the window level work\n int pos1[2] = { 193,187};\n iren->SetEventPosition(pos1);\n iren->InvokeEvent(vtkCommand::RightButtonPressEvent, NULL);\n int pos2[2] = { 105,197};\n iren->SetEventPosition(pos2);\n iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n iren->InvokeEvent(vtkCommand::RightButtonReleaseEvent, NULL);\n\n int retVal = vtkRegressionTestImage( renWin );\n\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n planeWidgetX->Delete();\n planeWidgetY->Delete();\n planeWidgetZ->Delete();\n colorMap->Delete();\n imageActor->Delete();\n picker->Delete();\n outlineActor->Delete();\n outlineMapper->Delete();\n outline->Delete();\n iren->Delete();\n renWin->Delete();\n ren1->Delete();\n ren2->Delete();\n v16->Delete();\n textMapper->Delete();\n textActor->Delete();\n myCallback->Delete();\n\n return !retVal;\n}\n<commit_msg>FIX: remove vtkTextMapper from test's pipeline<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: ImagePlaneWidget.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkActor.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCellPicker.h\"\n#include \"vtkCommand.h\"\n#include \"vtkImageActor.h\"\n#include \"vtkImageMapToColors.h\"\n#include \"vtkImagePlaneWidget.h\"\n#include \"vtkImageReader.h\"\n#include \"vtkLookupTable.h\"\n#include \"vtkOutlineFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkVolume16Reader.h\"\n\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkDebugLeaks.h\"\n\nint main( int argc, char *argv[] )\n{\n vtkDebugLeaks::PromptUserOff();\n\n char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/headsq\/quarter\");\n\n vtkVolume16Reader* v16 = vtkVolume16Reader::New();\n v16->SetDataDimensions( 64, 64);\n v16->SetDataByteOrderToLittleEndian(); \n v16->SetImageRange( 1, 93);\n v16->SetDataSpacing( 3.2, 3.2, 1.5);\n v16->SetFilePrefix( fname );\n v16->SetDataMask( 0x7fff);\n v16->Update();\n\n delete[] fname;\n\n vtkOutlineFilter* outline = vtkOutlineFilter::New();\n outline->SetInput(v16->GetOutput());\n\n vtkPolyDataMapper* outlineMapper = vtkPolyDataMapper::New();\n outlineMapper->SetInput(outline->GetOutput());\n\n vtkActor* outlineActor = vtkActor::New();\n outlineActor->SetMapper( outlineMapper);\n\n vtkRenderer* ren1 = vtkRenderer::New();\n vtkRenderer* ren2 = vtkRenderer::New();\n\n vtkRenderWindow* renWin = vtkRenderWindow::New();\n renWin->AddRenderer(ren2);\n renWin->AddRenderer(ren1);\n\n vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n\n vtkCellPicker* picker = vtkCellPicker::New();\n picker->SetTolerance(0.005);\n\n vtkImagePlaneWidget* planeWidgetX = vtkImagePlaneWidget::New();\n planeWidgetX->SetInteractor( iren);\n planeWidgetX->SetKeyPressActivationValue('x');\n planeWidgetX->SetPicker(picker);\n planeWidgetX->GetPlaneProperty()->SetColor(1,0,0);\n planeWidgetX->TextureInterpolateOff();\n planeWidgetX->SetResliceInterpolateToNearestNeighbour();\n planeWidgetX->SetInput(v16->GetOutput());\n planeWidgetX->SetPlaneOrientationToXAxes();\n planeWidgetX->SetSliceIndex(32);\n planeWidgetX->On();\n\n vtkImagePlaneWidget* planeWidgetY = vtkImagePlaneWidget::New();\n planeWidgetY->SetInteractor( iren);\n planeWidgetY->SetKeyPressActivationValue('y');\n planeWidgetY->SetPicker(picker);\n planeWidgetY->GetPlaneProperty()->SetColor(1,1,0);\n planeWidgetY->TextureInterpolateOn();\n planeWidgetY->SetResliceInterpolateToLinear();\n planeWidgetY->SetInput(v16->GetOutput());\n planeWidgetY->SetPlaneOrientationToYAxes();\n planeWidgetY->SetSlicePosition(102.4);\n planeWidgetY->SetLookupTable( planeWidgetX->GetLookupTable());\n planeWidgetY->On();\n\n vtkImagePlaneWidget* planeWidgetZ = vtkImagePlaneWidget::New();\n planeWidgetZ->SetInteractor( iren);\n planeWidgetZ->SetKeyPressActivationValue('z');\n planeWidgetZ->SetPicker(picker);\n planeWidgetZ->GetPlaneProperty()->SetColor(0,0,1);\n planeWidgetZ->TextureInterpolateOn();\n planeWidgetZ->SetResliceInterpolateToCubic();\n planeWidgetZ->SetInput(v16->GetOutput());\n planeWidgetZ->SetPlaneOrientationToZAxes();\n planeWidgetZ->SetSliceIndex(25);\n planeWidgetZ->SetLookupTable( planeWidgetX->GetLookupTable());\n planeWidgetZ->On();\n\n \/\/ add a 2D image to test the GetReslice method\n vtkImageMapToColors* colorMap = vtkImageMapToColors::New();\n colorMap->PassAlphaToOutputOff();\n colorMap->SetActiveComponent(0);\n colorMap->SetOutputFormatToLuminance();\n colorMap->SetInput(planeWidgetZ->GetResliceOutput());\n colorMap->SetLookupTable(planeWidgetX->GetLookupTable());\n\n vtkImageActor* imageActor = vtkImageActor::New();\n imageActor->PickableOff();\n imageActor->SetInput(colorMap->GetOutput());\n\n \/\/ add the actors\n ren1->AddActor( outlineActor);\n ren2->AddActor( imageActor);\n\n ren1->SetBackground( 0.1, 0.1, 0.2);\n ren2->SetBackground( 0.2, 0.1, 0.2);\n\n renWin->SetSize( 600, 350);\n\n ren1->SetViewport(0,0,0.58333,1);\n ren2->SetViewport(0.58333,0,1,1);\n\n \/\/ set the actors' postions\n renWin->Render();\n iren->SetEventPosition( 175,175);\n iren->SetKeyCode('r');\n iren->InvokeEvent(vtkCommand::CharEvent,NULL);\n iren->SetEventPosition( 475,175);\n iren->SetKeyCode('r');\n iren->InvokeEvent(vtkCommand::CharEvent,NULL);\n renWin->Render();\n\n \/\/ test SetKeyPressActivationValue for one of the widgets\n iren->SetKeyCode('z');\n iren->InvokeEvent(vtkCommand::CharEvent,NULL);\n iren->SetKeyCode('z');\n iren->InvokeEvent(vtkCommand::CharEvent,NULL);\n\n ren1->GetActiveCamera()->Elevation(110);\n ren1->GetActiveCamera()->SetViewUp(0, 0, -1);\n ren1->GetActiveCamera()->Azimuth(45);\n ren1->GetActiveCamera()->Dolly(1.15);\n ren1->ResetCameraClippingRange();\n\n \/\/ make the window level work\n int pos1[2] = { 193,187};\n iren->SetEventPosition(pos1);\n iren->InvokeEvent(vtkCommand::RightButtonPressEvent, NULL);\n int pos2[2] = { 105,197};\n iren->SetEventPosition(pos2);\n iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n iren->InvokeEvent(vtkCommand::RightButtonReleaseEvent, NULL);\n \n \/\/ make the plane pushing work by left button\n int pos3[2] = { 244,225};\n iren->SetEventPosition(pos3);\n iren->InvokeEvent(vtkCommand::LeftButtonPressEvent, NULL);\n int pos4[2] = { 196,200};\n iren->SetEventPosition(pos4);\n iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n iren->SetEventPosition(pos3);\n iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n iren->InvokeEvent(vtkCommand::LeftButtonReleaseEvent, NULL);\n \n \/\/ make the plane pushing work by middle button\n int pos5[2] = { 140,219};\n iren->SetEventPosition(pos5);\n iren->InvokeEvent(vtkCommand::MiddleButtonPressEvent, NULL);\n int pos6[2] = { 202,196};\n iren->SetEventPosition(pos6);\n iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n iren->SetEventPosition(pos5);\n iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n iren->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent, NULL);\n\n int retVal = vtkRegressionTestImage( renWin );\n\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n planeWidgetX->Delete();\n planeWidgetY->Delete();\n planeWidgetZ->Delete();\n colorMap->Delete();\n imageActor->Delete();\n picker->Delete();\n outlineActor->Delete();\n outlineMapper->Delete();\n outline->Delete();\n iren->Delete();\n renWin->Delete();\n ren1->Delete();\n ren2->Delete();\n v16->Delete();\n\n return !retVal;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: ImageAccumulate.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkImageData.h\"\n#include \"vtkImageSinusoidSource.h\"\n#include \"vtkImageAccumulate.h\"\n#include \"vtkImageViewer.h\"\n#include \"vtkRenderWindowInteractor.h\"\n\n#include \"vtkTestUtilities.h\"\n#include \"vtkRegressionTestImage.h\"\n\n#include <math.h>\n\nint ImageAccumulate(int , char *[])\n{\n int rval = 0;\n\n \/\/ Create a blank image\n vtkImageSinusoidSource *sinus = vtkImageSinusoidSource::New();\n sinus->SetWholeExtent(0,512-1,0,512-1,0,64-1);\n sinus->SetAmplitude( 0 );\n sinus->Update();\n\n \/\/ Set some value\n sinus->GetOutput()->SetScalarComponentFromDouble ( 0, 0, 0, 0, 1);\n sinus->GetOutput()->SetScalarComponentFromDouble ( 10, 10, 10, 0, 2);\n sinus->GetOutput()->SetScalarComponentFromDouble ( 10, 100, 20, 0, 3);\n sinus->GetOutput()->SetScalarComponentFromDouble (100, 10, 30, 0, 4);\n sinus->GetOutput()->SetScalarComponentFromDouble (100, 100, 40, 0, 5);\n\n vtkImageAccumulate *acc = vtkImageAccumulate::New();\n acc->SetInputConnection( sinus->GetOutputPort() );\n \/\/acc->IgnoreZeroOn();\n \/\/acc->Update();\n\n acc->Print(cout);\n double min[3], max[3];\n acc->GetMin(min);\n acc->GetMax(max);\n if( min[0] != 0 )\n {\n cerr << \"Min: \" << min[0] << endl;\n rval++;\n }\n if( max[0] != 5 )\n {\n cerr << \"Max: \" << max[0] << endl;\n rval++;\n }\n double mean[3];\n long int voxcount = acc->GetVoxelCount();\n acc->GetMean(mean);\n double m = double(1+2+3+4+5)\/voxcount;\n if( fabs(mean[0] - m) > 1e-10 )\n {\n cerr << \"Mean: \" << mean[0] << endl;\n rval++;\n }\n\n\n acc->IgnoreZeroOn();\n acc->Update();\n acc->Print( cout );\n\n sinus->Delete();\n acc->Delete();\n\n return rval;\n}\n\n<commit_msg>ENH: more testing<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: ImageAccumulate.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkImageData.h\"\n#include \"vtkImageSinusoidSource.h\"\n#include \"vtkImageAccumulate.h\"\n#include \"vtkImageViewer.h\"\n#include \"vtkRenderWindowInteractor.h\"\n\n#include \"vtkTestUtilities.h\"\n#include \"vtkRegressionTestImage.h\"\n\n#include <math.h>\n\nint ImageAccumulate(int , char *[])\n{\n int rval = 0;\n\n \/\/ Create a blank image\n vtkImageSinusoidSource *sinus = vtkImageSinusoidSource::New();\n sinus->SetWholeExtent(0,512-1,0,512-1,0,64-1);\n sinus->SetAmplitude( 0 );\n sinus->Update();\n\n \/\/ Set some value\n sinus->GetOutput()->SetScalarComponentFromDouble ( 0, 0, 0, 0, 1);\n sinus->GetOutput()->SetScalarComponentFromDouble ( 10, 10, 10, 0, 2);\n sinus->GetOutput()->SetScalarComponentFromDouble ( 10, 100, 20, 0, 3);\n sinus->GetOutput()->SetScalarComponentFromDouble (100, 10, 30, 0, 4);\n sinus->GetOutput()->SetScalarComponentFromDouble (100, 100, 40, 0, 5);\n\n vtkImageAccumulate *acc = vtkImageAccumulate::New();\n acc->SetInputConnection( sinus->GetOutputPort() );\n \/\/acc->IgnoreZeroOn();\n acc->Update();\n\n acc->Print(cout);\n double min[3], max[3];\n acc->GetMin(min);\n acc->GetMax(max);\n if( min[0] != 0 )\n {\n cerr << \"Min: \" << min[0] << endl;\n rval++;\n }\n if( max[0] != 5 )\n {\n cerr << \"Max: \" << max[0] << endl;\n rval++;\n }\n double mean[3];\n long int voxcount;\n voxcount = acc->GetVoxelCount();\n acc->GetMean(mean);\n double m = double(1+2+3+4+5)\/voxcount;\n if( fabs(mean[0] - m) > 1e-10 )\n {\n cerr << \"Mean: \" << mean[0] << endl;\n rval++;\n }\n\n\n \/\/ Test IgnoreZero option\n acc->IgnoreZeroOn();\n acc->Update();\n acc->Print( cout );\n\n \/\/ Simple test\n acc->GetMin(min);\n acc->GetMax(max);\n if( min[0] != 1 )\n {\n cerr << \"Min: \" << min[0] << endl;\n rval++;\n }\n if( max[0] != 5 )\n {\n cerr << \"Max: \" << max[0] << endl;\n rval++;\n }\n acc->GetMean(mean);\n if( mean[0] != double(1+2+3+4+5)\/5 )\n {\n cerr << \"Mean: \" << mean[0] << endl;\n rval++;\n }\n\n sinus->Delete();\n acc->Delete();\n\n return rval;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * $Id$\n *\n * Copyright (c) 2011 Surfnet \n * Copyright (c) 2011 .SE (The Internet Infrastructure Foundation).\n * Copyright (c) 2011 OpenDNSSEC AB (svb)\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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \"config.h\"\n\n\/* On MacOSX arc4random is only available when we \n undef _ANSI_SOURCE and define _DARWIN_C_SOURCE. *\/\n#ifdef __APPLE__\n#undef _ANSI_SOURCE\n#define _DARWIN_C_SOURCE 1\n#include <stdlib.h>\n#endif\n\n#include \"resalt.h\"\n\n#include \"shared\/duration.h\"\n\nint PolicyUpdateSalt(::ods::kasp::Policy &policy)\n{\n \/* This will be the salt that we create \n * salt never longer than 255 so 512 can\n * hold a hex encoded version of the salt.\n *\/\n char salt[512];\n \/* for mapping random numbers in range 0..15 to hex characters *\/\n const char *hex_chars = \"0123456789abcdef\";\n \/* Number of hex characters *\/\n unsigned int nhex_chars = strlen(hex_chars);\n \n if (!policy.denial().has_nsec3()) {\n \/\/ no nsec3 present so no need to resalt either.\n return 0;\n } \n\n const ::ods::kasp::NSEC3 &nsec3 = policy.denial().nsec3();\n if ( nsec3.has_salt() && nsec3.has_salt_last_change() ) {\n if (time_now() < nsec3.salt_last_change()+nsec3.resalt() ) {\n \/\/ Current time is within resalt period since last change.\n return 0;\n }\n }\n \n \/\/ Seems we have a nsec3 section that needs a salt generated\n \n \/\/ required uint32 resalt = 3 [(xml).path=\"Resalt\", (xml).type=duration]; \/\/ re-salting interval\n \/\/ required uint32 saltlength = 6 [(xml).path=\"Hash\/Salt\/@length\"];\/\/ nsec3 salt length 0..255\n \/\/ optional string salt = 7 [(xml).path=\"Hash\/Salt\"];\/\/ the actual salt is generated by the enforcer e.g. 0438eb9a93a6d6c5\n \/\/ optional uint32 salt_last_change = 8 [(xml).path=\"Hash\/Salt\/@lastchanged\"]; \/\/ timestamp for when the last resalt took place\n\n unsigned int saltlength = nsec3.saltlength();\n if (saltlength <= 0 || saltlength > 255) {\n \/\/ error, saltlength out of range..\n return -3;\n }\n \n#ifdef HAVE_ARC4RANDOM\n for (int i = 0; i < 2*saltlength; ++i) {\n salt[i] = hex_chars[ arc4random() % nhex_chars ];\n }\n#else\n srand( time(NULL) );\n for (int i = 0; i < 2*saltlength; ++i) {\n salt[i] = hex_chars[rand()%nhex_chars];\n\n }\n#endif\n\n policy.mutable_denial()->mutable_nsec3()->set_salt(&salt[0],2*saltlength);\n policy.mutable_denial()->mutable_nsec3()->set_salt_last_change(time_now());\n return 1;\n}\n<commit_msg>Always include stdlib.h<commit_after>\/*\n * $Id$\n *\n * Copyright (c) 2011 Surfnet \n * Copyright (c) 2011 .SE (The Internet Infrastructure Foundation).\n * Copyright (c) 2011 OpenDNSSEC AB (svb)\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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \"config.h\"\n\n\/* On MacOSX arc4random is only available when we \n undef _ANSI_SOURCE and define _DARWIN_C_SOURCE. *\/\n#ifdef __APPLE__\n#undef _ANSI_SOURCE\n#define _DARWIN_C_SOURCE 1\n#endif\n#include <stdlib.h>\n\n#include \"resalt.h\"\n\n#include \"shared\/duration.h\"\n\nint PolicyUpdateSalt(::ods::kasp::Policy &policy)\n{\n \/* This will be the salt that we create \n * salt never longer than 255 so 512 can\n * hold a hex encoded version of the salt.\n *\/\n char salt[512];\n \/* for mapping random numbers in range 0..15 to hex characters *\/\n const char *hex_chars = \"0123456789abcdef\";\n \/* Number of hex characters *\/\n unsigned int nhex_chars = strlen(hex_chars);\n \n if (!policy.denial().has_nsec3()) {\n \/\/ no nsec3 present so no need to resalt either.\n return 0;\n } \n\n const ::ods::kasp::NSEC3 &nsec3 = policy.denial().nsec3();\n if ( nsec3.has_salt() && nsec3.has_salt_last_change() ) {\n if (time_now() < nsec3.salt_last_change()+nsec3.resalt() ) {\n \/\/ Current time is within resalt period since last change.\n return 0;\n }\n }\n \n \/\/ Seems we have a nsec3 section that needs a salt generated\n \n \/\/ required uint32 resalt = 3 [(xml).path=\"Resalt\", (xml).type=duration]; \/\/ re-salting interval\n \/\/ required uint32 saltlength = 6 [(xml).path=\"Hash\/Salt\/@length\"];\/\/ nsec3 salt length 0..255\n \/\/ optional string salt = 7 [(xml).path=\"Hash\/Salt\"];\/\/ the actual salt is generated by the enforcer e.g. 0438eb9a93a6d6c5\n \/\/ optional uint32 salt_last_change = 8 [(xml).path=\"Hash\/Salt\/@lastchanged\"]; \/\/ timestamp for when the last resalt took place\n\n unsigned int saltlength = nsec3.saltlength();\n if (saltlength <= 0 || saltlength > 255) {\n \/\/ error, saltlength out of range..\n return -3;\n }\n \n#ifdef HAVE_ARC4RANDOM\n for (int i = 0; i < 2*saltlength; ++i) {\n salt[i] = hex_chars[ arc4random() % nhex_chars ];\n }\n#else\n srand( time(NULL) );\n for (int i = 0; i < 2*saltlength; ++i) {\n salt[i] = hex_chars[rand()%nhex_chars];\n\n }\n#endif\n\n policy.mutable_denial()->mutable_nsec3()->set_salt(&salt[0],2*saltlength);\n policy.mutable_denial()->mutable_nsec3()->set_salt_last_change(time_now());\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef OPCODE_BASE_H\n#define OPCODE_BASE_H\n#ifndef MSVC\n#include \"csdl.h\"\n#include <cstdarg>\n#else\n#include <cmath>\n#include \"csdl.h\"\n#endif\n\n\/**\n * Template base class, or pseudo-virtual base class,\n * for writing Csound opcodes in C++.\n * Derive opcode implementation classes like this:\n *\n * DerivedClass : public OpcodeBase<DerivedClass>\n * {\n * public:\n * \/\/ All output fields must be declared first as MYFLT *:\n * MYFLT *aret1;\n * \/\/ All input fields must be declared next as MYFLT *:\n * MYFLT *iarg1;\n * MYFLT *karg2;\n * MYFLT *aarg3;\n * \/\/ All internal state variables must be declared after that:\n * size_t state1;\n * double state2;\n * MYFLT state3;\n * \/\/ Declare and implement only whichever of these are required:\n * void init();\n * void kontrol();\n * void audio;\n * void noteoff();\n * void deinit();\n * };\n *\/\ntemplate<typename T>\nclass OpcodeBase\n{\npublic:\n int init(CSOUND *csound)\n {\n return NOTOK;\n }\n static int init_(CSOUND *csound, void *opcode_)\n {\n T *opcode = reinterpret_cast<T *>(opcode_);\n if (!csound->reinitflag && !csound->tieflag)\n csound->RegisterDeinitCallback(csound,\n &opcode->h, OpcodeBase<T>::noteoff_);\n return opcode->init(csound);\n }\n int kontrol(CSOUND *csound)\n {\n return NOTOK;\n }\n static int kontrol_(CSOUND *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->kontrol(csound);\n }\n int audio(CSOUND *csound)\n {\n return NOTOK;\n }\n static int audio_(CSOUND *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->audio(csound);\n }\n int noteoff(CSOUND *csound)\n {\n return OK;\n }\n static int noteoff_(CSOUND *csound, void *opcode)\n {\n return reinterpret_cast< OpcodeBase<T> *>(opcode)->noteoff(csound);\n }\n void log(CSOUND *csound, const char *format,...)\n {\n va_list args;\n va_start(args, format);\n if(csound) {\n csound->MessageV(csound, 0, format, args);\n }\n else {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n }\n void warn(CSOUND *csound, const char *format,...)\n {\n va_list args;\n va_start(args, format);\n if(csound) {\n if(csound->GetMessageLevel(csound) & WARNMSG ||\n csound->GetDebug(csound)) {\n csound->MessageV(csound, CSOUNDMSG_WARNING, format, args);\n }\n }\n else {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n }\n OPDS h;\n};\n\n#endif\n\n<commit_msg>Updated to reflect more conformant compilers.<commit_after>#ifndef OPCODE_BASE_H\n#define OPCODE_BASE_H\n#ifndef MSVC\n#include \"csdl.h\"\n#include <cstdarg>\n#else\n#include <cmath>\n#include \"csdl.h\"\n#endif\n\n\/**\n * Template base class, or pseudo-virtual base class,\n * for writing Csound opcodes in C++.\n * Derive opcode implementation classes like this:\n *\n * DerivedClass : public OpcodeBase<DerivedClass>\n * {\n * public:\n * \/\/ All output fields must be declared first as MYFLT *:\n * MYFLT *aret1;\n * \/\/ All input fields must be declared next as MYFLT *:\n * MYFLT *iarg1;\n * MYFLT *karg2;\n * MYFLT *aarg3;\n * \/\/ All internal state variables must be declared after that:\n * size_t state1;\n * double state2;\n * MYFLT state3;\n * \/\/ Declare and implement only whichever of these are required:\n * void init();\n * void kontrol();\n * void audio;\n * void noteoff();\n * void deinit();\n * };\n *\/\ntemplate<typename T>\nclass OpcodeBase\n{\npublic:\n int init(CSOUND *csound)\n {\n return NOTOK;\n }\n static int init_(CSOUND *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->init(csound);\n }\n int kontrol(CSOUND *csound)\n {\n return NOTOK;\n }\n static int kontrol_(CSOUND *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->kontrol(csound);\n }\n int audio(CSOUND *csound)\n {\n return NOTOK;\n }\n static int audio_(CSOUND *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->audio(csound);\n }\n void log(CSOUND *csound, const char *format,...)\n {\n va_list args;\n va_start(args, format);\n if(csound) {\n csound->MessageV(csound, 0, format, args);\n }\n else {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n }\n void warn(CSOUND *csound, const char *format,...)\n {\n va_list args;\n va_start(args, format);\n if(csound) {\n if(csound->GetMessageLevel(csound) & WARNMSG ||\n csound->GetDebug(csound)) {\n csound->MessageV(csound, CSOUNDMSG_WARNING, format, args);\n }\n }\n else {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n }\n OPDS h;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\n#include <togo\/image\/config.hpp>\n#include <togo\/core\/error\/assert.hpp>\n#include <togo\/core\/utility\/utility.hpp>\n#include <togo\/image\/pixmap\/pixmap.hpp>\n\n#include <togo\/support\/test.hpp>\n\n#include <cstring>\n\nusing namespace togo;\n\nsigned main() {\n\tmemory_init();\n\n\tColor c_init{0x01, 0x02, 0x03, 0x04};\n\tColor c_fill1{0xAA, 0xBB, 0xCC, 0xDD};\n\tColor c_fill2{0xDD, 0xCC, 0xBB, 0xAA};\n\tauto cp_init = c_init.packed();\n\tauto cp_fill1 = c_fill1.packed();\n\t\/\/ auto cp_fill2 = c_fill2.packed();\n\n\tPixmap p{PixelFormatID::rgba8};\n\tpixmap::resize(p, UVec2{1, 1}, c_init);\n\tTOGO_ASSERTE(p.data && p.data_size == p.data_capacity && p.data_size == 1*1 * 4);\n\tauto data = reinterpret_cast<u32*>(p.data);\n\tTOGO_ASSERTE(data[0] == cp_init);\n\n\tpixmap::resize(p, UVec2{4, 4}, c_fill1);\n\tTOGO_ASSERTE(p.data && p.data_size == p.data_capacity && p.data_size == 4*4 * 4);\n\tdata = reinterpret_cast<u32*>(p.data);\n\tTOGO_ASSERTE(data[0] == cp_init);\n\t{auto end = pointer_add(data, p.data_size);\n\tfor (auto check = data + 1; check != end; ++check) {\n\t\tTOGO_ASSERTE(*check == cp_fill1);\n\t}}\n\n\t{Pixmap copy{p.format};\n\tpixmap::copy(copy, p);\n\tTOGO_ASSERTE(\n\t\tcopy.data_size == p.data_size &&\n\t\tstd::memcmp(copy.data, p.data, p.data_size) == 0\n\t);}\n\n\t{Pixmap blit{p.format};\n\tpixmap::resize(blit, UVec2{4, 4}, c_fill2);\n\tpixmap::blit(blit, p, UVec2{0, 0});\n\tTOGO_ASSERTE(\n\t\tblit.data_size == p.data_size &&\n\t\tstd::memcmp(blit.data, p.data, p.data_size) == 0\n\t);}\n\n\treturn 0;\n}\n<commit_msg>lib\/image\/test\/pixmap\/general: URC.<commit_after>\n#include <togo\/image\/config.hpp>\n#include <togo\/core\/error\/assert.hpp>\n#include <togo\/core\/utility\/utility.hpp>\n#include <togo\/image\/pixmap\/pixmap.hpp>\n\n#include <togo\/support\/test.hpp>\n\n#include <cstring>\n\nusing namespace togo;\n\nsigned main() {\n\tmemory_init();\n\n\tPixelFormat format{PixelFormatID::rgba};\n\tauto ps = pixel_format::pixel_size(format);\n\tColor c_init{0x01, 0x02, 0x03, 0x04};\n\tColor c_fill1{0xAA, 0xBB, 0xCC, 0xDD};\n\tColor c_fill2{0xDD, 0xCC, 0xBB, 0xAA};\n\tauto cp_init = pixel_format::pack(format, c_init);\n\tauto cp_fill1 = pixel_format::pack(format, c_fill1);\n\t\/\/ auto cp_fill2 = pixel_format::pack(format, c_fill2);\n\n\tPixmap p{format};\n\tpixmap::resize(p, UVec2{1, 1}, c_init);\n\tTOGO_ASSERTE(p.data && p.data_size == p.data_capacity && p.data_size == 1*1 * ps);\n\tauto data = reinterpret_cast<u32*>(p.data);\n\tTOGO_ASSERTE(data[0] == cp_init);\n\n\tpixmap::resize(p, UVec2{4, 4}, c_fill1);\n\tTOGO_ASSERTE(p.data && p.data_size == p.data_capacity && p.data_size == 4*4 * ps);\n\tdata = reinterpret_cast<u32*>(p.data);\n\tTOGO_ASSERTE(data[0] == cp_init);\n\t{auto end = pointer_add(data, p.data_size);\n\tfor (auto check = data + 1; check != end; ++check) {\n\t\tTOGO_ASSERTE(*check == cp_fill1);\n\t}}\n\n\t{Pixmap copy{PixelFormatID::xrgb};\n\tpixmap::copy(copy, p);\n\tTOGO_ASSERTE(\n\t\tcopy.data_size == p.data_size &&\n\t\tstd::memcmp(copy.data, p.data, p.data_size) == 0\n\t);}\n\n\t{Pixmap blit{format};\n\tpixmap::resize(blit, UVec2{4, 4}, c_fill2);\n\tpixmap::blit(blit, p, UVec2{0, 0});\n\tTOGO_ASSERTE(\n\t\tblit.data_size == p.data_size &&\n\t\tstd::memcmp(blit.data, p.data, p.data_size) == 0\n\t);}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright 2013-2014 The MilkCat Project Developers\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\/\/ hmm_part_of_speech_tagger.cc --- Created at 2013-11-10\n\/\/\n\n#include \"milkcat\/hmm_part_of_speech_tagger.h\"\n#include <stdio.h>\n#include <stdint.h>\n#include <string>\n#include \"milkcat\/beam.h\"\n#include \"milkcat\/hmm_model.h\"\n#include \"milkcat\/libmilkcat.h\"\n#include \"milkcat\/part_of_speech_tag_instance.h\"\n#include \"milkcat\/term_instance.h\"\n#include \"utils\/utils.h\"\n\nnamespace milkcat {\n\nstruct HMMPartOfSpeechTagger::Node {\n int tag;\n double cost;\n const HMMPartOfSpeechTagger::Node *prevoius_node;\n};\n\nHMMPartOfSpeechTagger::HMMPartOfSpeechTagger(): model_(nullptr),\n node_pool_(nullptr),\n index_(nullptr),\n PU_emit_(nullptr),\n DT_emit_(nullptr),\n term_instance_(nullptr) {\n for (int i = 0; i < kMaxBeams; ++i) {\n beams_[i] = nullptr;\n }\n}\n\nHMMPartOfSpeechTagger::~HMMPartOfSpeechTagger() {\n delete node_pool_;\n node_pool_ = nullptr;\n\n delete PU_emit_;\n PU_emit_ = nullptr;\n\n delete DT_emit_;\n DT_emit_ = nullptr;\n\n for (int i = 0; i < kMaxBeams; ++i) {\n if (beams_[i] != nullptr)\n delete beams_[i];\n beams_[i] = nullptr;\n }\n}\n\nnamespace {\n\n\/\/ Compare two node potiners by its cost value\nbool HmmNodePtrCmp(HMMPartOfSpeechTagger::Node *n1, \n HMMPartOfSpeechTagger::Node *n2) {\n return n1->cost < n2->cost;\n}\n\n\/\/ New an emit node for tag specified by tag_str. If tag_str not exist in model\n\/\/ return a nullptr and status indicates an corruption error.\nHMMModel::Emit *NewEmitFromTag(const char *tag_str,\n const HMMModel *model,\n Status *status) {\n int tagid = model->tag_id(tag_str);\n if (tagid < 0) *status = Status::Corruption(\"Invalid HMM model.\");\n\n HMMModel::Emit *emit = nullptr;\n if (status->ok()) {\n emit = new HMMModel::Emit(tagid, 0.0, nullptr);\n }\n\n return emit;\n}\n\n} \/\/ namespace\n\nHMMPartOfSpeechTagger *HMMPartOfSpeechTagger::New(\n ModelFactory *model_factory,\n Status *status) {\n HMMPartOfSpeechTagger *self = new HMMPartOfSpeechTagger();\n self->node_pool_ = new NodePool<Node>(); \n\n for (int i = 0; i < kMaxBeams; ++i) {\n self->beams_[i] = new Beam<Node>(kBeamSize, \n self->node_pool_, \n i,\n HmmNodePtrCmp);\n }\n\n self->model_ = model_factory->HMMPosModel(status);\n\n if (status->ok()) self->PU_emit_ = NewEmitFromTag(\"PU\", self->model_, status);\n if (status->ok()) self->DT_emit_ = NewEmitFromTag(\"DT\", self->model_, status);\n\n if (status->ok()) {\n self->BOS_tagid_ = self->model_->tag_id(\"BOS\");\n if (self->BOS_tagid_ < 0) \n *status = Status::Corruption(\"Invalid HMM model.\");\n }\n\n if (status->ok()) {\n self->NN_tagid_ = self->model_->tag_id(\"NN\");\n if (self->NN_tagid_ < 0) \n *status = Status::Corruption(\"Invalid HMM model.\");\n }\n\n\n if (status->ok()) self->index_ = model_factory->Index(status);\n\n if (status->ok()) {\n return self;\n } else {\n delete self;\n return NULL;\n }\n}\n\nHMMModel::Emit *HMMPartOfSpeechTagger::GetEmitAtPosition(int position) {\n int term_id;\n HMMModel::Emit *emit;\n\n term_id = term_instance_->term_id_at(position);\n if (term_id == TermInstance::kTermIdNone) {\n term_id = index_->Search(term_instance_->term_text_at(position));\n }\n\n emit = model_->emit(term_id);\n if (emit == nullptr) {\n int term_type = term_instance_->term_type_at(position);\n switch (term_type) {\n case TermInstance::kPunction:\n case TermInstance::kSymbol:\n case TermInstance::kOther:\n emit = PU_emit_;\n break;\n case TermInstance::kNumber:\n emit = DT_emit_;\n break;\n }\n } \n\n return emit;\n}\n\ninline void HMMPartOfSpeechTagger::AddBOSNodeToBeam() {\n Node *bos_node = node_pool_->Alloc();\n bos_node->tag = BOS_tagid_;\n bos_node->cost = 0;\n bos_node->prevoius_node = nullptr;\n beams_[0]->Clear();\n beams_[0]->Add(bos_node);\n\n Node *bos_node_2 = node_pool_->Alloc();\n bos_node_2->tag = BOS_tagid_;\n bos_node_2->cost = 0;\n bos_node_2->prevoius_node = bos_node;\n beams_[1]->Clear();\n beams_[1]->Add(bos_node_2);\n}\n\ninline void HMMPartOfSpeechTagger::GetBestPOSTagFromBeam(\n PartOfSpeechTagInstance *part_of_speech_tag_instance) {\n int position = term_instance_->size() - 1;\n const Node *node = beams_[position + 2]->MinimalNode();\n\n while (node->tag != BOS_tagid_) {\n part_of_speech_tag_instance->set_value_at(position,\n model_->tag_str(node->tag));\n position--;\n node = node->prevoius_node;\n }\n\n part_of_speech_tag_instance->set_size(term_instance_->size());\n}\n\nvoid HMMPartOfSpeechTagger::Tag(\n PartOfSpeechTagInstance *part_of_speech_tag_instance,\n TermInstance *term_instance) {\n term_instance_ = term_instance;\n\n AddBOSNodeToBeam();\n\n \/\/ Viterbi algorithm\n for (int i = 0; i < term_instance->size(); ++i)\n BuildBeam(i);\n\n \/\/ Find the best result\n GetBestPOSTagFromBeam(part_of_speech_tag_instance);\n\n node_pool_->ReleaseAll();\n}\n\nvoid HMMPartOfSpeechTagger::GuessTag(const Node *leftleft_node, \n const Node *left_node,\n Beam<Node> *beam) {\n int leftleft_tag = leftleft_node->tag, \n left_tag = left_node->tag;\n Node *node = nullptr;\n\n node = node_pool_->Alloc();\n node->tag = NN_tagid_;\n node->cost = left_node->cost;\n node->prevoius_node = left_node;\n beam->Add(node);\n\n}\n\nvoid HMMPartOfSpeechTagger::BuildBeam(int position) {\n \/\/ Beam has two BOS node at 0 and 1\n int beam_position = position + 2;\n\n HMMModel::Emit *emit = GetEmitAtPosition(position), *emit_node;\n const Node *leftleft_node, *left_node, *node;\n int leftleft_tag, left_tag, tag;\n\n Beam<Node> *previous_beam = beams_[beam_position - 1];\n Beam<Node> *beam = beams_[beam_position];\n\n previous_beam->Shrink();\n beam->Clear();\n\n for (int i = 0; i < previous_beam->size(); ++i) {\n left_node = previous_beam->node_at(i);\n leftleft_node = left_node->prevoius_node;\n\n leftleft_tag = leftleft_node->tag;\n left_tag = left_node->tag;\n\n \/\/ If current word has emit information or current word is punction or \n \/\/ symbol\n emit_node = emit;\n if (emit_node) {\n while (emit_node) {\n tag = emit_node->tag;\n double trans_cost = model_->trans_cost(leftleft_tag, left_tag, tag);\n double emit_cost = emit_node->cost;\n Node *node = node_pool_->Alloc();\n node->tag = tag;\n node->cost = left_node->cost + trans_cost + emit_cost;\n node->prevoius_node = left_node;\n beam->Add(node);\n\n#ifdef LOG\n printf(\"node added %s %s cost = %lf trans_cost = %lf emit_cost = %lf\\n\",\n term_instance_->term_text_at(position),\n model_->tag_str(tag), \n trans_cost + emit_cost,\n trans_cost,\n emit_cost);\n#endif\n\n emit_node = emit_node->next;\n }\n } else {\n GuessTag(leftleft_node, left_node, beam);\n }\n }\n}\n\n} \/\/ namespace milkcat\n<commit_msg>change decoder method in hmm_part_of_speech_tagger<commit_after>\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright 2013-2014 The MilkCat Project Developers\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\/\/ hmm_part_of_speech_tagger.cc --- Created at 2013-11-10\n\/\/\n\n#include \"milkcat\/hmm_part_of_speech_tagger.h\"\n#include <stdio.h>\n#include <stdint.h>\n#include <string>\n#include \"milkcat\/beam.h\"\n#include \"milkcat\/hmm_model.h\"\n#include \"milkcat\/libmilkcat.h\"\n#include \"milkcat\/part_of_speech_tag_instance.h\"\n#include \"milkcat\/term_instance.h\"\n#include \"utils\/utils.h\"\n\n#define LOG\n\nnamespace milkcat {\n\nstruct HMMPartOfSpeechTagger::Node {\n int tag;\n double cost;\n const HMMPartOfSpeechTagger::Node *prevoius_node;\n\n inline void set_value(int tag, int cost, const Node *prevoius_node) {\n this->tag = tag;\n this->cost = cost;\n this->prevoius_node = prevoius_node;\n } \n};\n\nHMMPartOfSpeechTagger::HMMPartOfSpeechTagger(): model_(nullptr),\n node_pool_(nullptr),\n index_(nullptr),\n PU_emit_(nullptr),\n DT_emit_(nullptr),\n term_instance_(nullptr) {\n for (int i = 0; i < kMaxBeams; ++i) {\n beams_[i] = nullptr;\n }\n}\n\nHMMPartOfSpeechTagger::~HMMPartOfSpeechTagger() {\n delete node_pool_;\n node_pool_ = nullptr;\n\n delete PU_emit_;\n PU_emit_ = nullptr;\n\n delete DT_emit_;\n DT_emit_ = nullptr;\n\n for (int i = 0; i < kMaxBeams; ++i) {\n if (beams_[i] != nullptr)\n delete beams_[i];\n beams_[i] = nullptr;\n }\n}\n\nnamespace {\n\n\/\/ Compare two node potiners by its cost value\nbool HmmNodePtrCmp(HMMPartOfSpeechTagger::Node *n1, \n HMMPartOfSpeechTagger::Node *n2) {\n return n1->cost < n2->cost;\n}\n\n\/\/ New an emit node for tag specified by tag_str. If tag_str not exist in model\n\/\/ return a nullptr and status indicates an corruption error.\nHMMModel::Emit *NewEmitFromTag(const char *tag_str,\n const HMMModel *model,\n Status *status) {\n int tagid = model->tag_id(tag_str);\n if (tagid < 0) *status = Status::Corruption(\"Invalid HMM model.\");\n\n HMMModel::Emit *emit = nullptr;\n if (status->ok()) {\n emit = new HMMModel::Emit(tagid, 0.0, nullptr);\n }\n\n return emit;\n}\n\n} \/\/ namespace\n\nHMMPartOfSpeechTagger *HMMPartOfSpeechTagger::New(\n ModelFactory *model_factory,\n Status *status) {\n HMMPartOfSpeechTagger *self = new HMMPartOfSpeechTagger();\n self->node_pool_ = new NodePool<Node>(); \n\n for (int i = 0; i < kMaxBeams; ++i) {\n self->beams_[i] = new Beam<Node>(kBeamSize, \n self->node_pool_, \n i,\n HmmNodePtrCmp);\n }\n\n self->model_ = model_factory->HMMPosModel(status);\n\n if (status->ok()) self->PU_emit_ = NewEmitFromTag(\"PU\", self->model_, status);\n if (status->ok()) self->DT_emit_ = NewEmitFromTag(\"DT\", self->model_, status);\n\n if (status->ok()) {\n self->BOS_tagid_ = self->model_->tag_id(\"BOS\");\n if (self->BOS_tagid_ < 0) \n *status = Status::Corruption(\"Invalid HMM model.\");\n }\n\n if (status->ok()) {\n self->NN_tagid_ = self->model_->tag_id(\"NN\");\n if (self->NN_tagid_ < 0) \n *status = Status::Corruption(\"Invalid HMM model.\");\n }\n\n\n if (status->ok()) self->index_ = model_factory->Index(status);\n\n if (status->ok()) {\n return self;\n } else {\n delete self;\n return NULL;\n }\n}\n\nHMMModel::Emit *HMMPartOfSpeechTagger::GetEmitAtPosition(int position) {\n int term_id;\n HMMModel::Emit *emit;\n\n term_id = term_instance_->term_id_at(position);\n if (term_id == TermInstance::kTermIdNone) {\n term_id = index_->Search(term_instance_->term_text_at(position));\n }\n\n emit = model_->emit(term_id);\n if (emit == nullptr) {\n int term_type = term_instance_->term_type_at(position);\n switch (term_type) {\n case TermInstance::kPunction:\n case TermInstance::kSymbol:\n case TermInstance::kOther:\n emit = PU_emit_;\n break;\n case TermInstance::kNumber:\n emit = DT_emit_;\n break;\n }\n } \n\n if (emit == nullptr) emit = PU_emit_;\n\n return emit;\n}\n\ninline void HMMPartOfSpeechTagger::AddBOSNodeToBeam() {\n Node *bos_node = node_pool_->Alloc();\n bos_node->tag = BOS_tagid_;\n bos_node->cost = 0;\n bos_node->prevoius_node = nullptr;\n beams_[0]->Clear();\n beams_[0]->Add(bos_node);\n\n Node *bos_node_2 = node_pool_->Alloc();\n bos_node_2->tag = BOS_tagid_;\n bos_node_2->cost = 0;\n bos_node_2->prevoius_node = bos_node;\n beams_[1]->Clear();\n beams_[1]->Add(bos_node_2);\n}\n\ninline void HMMPartOfSpeechTagger::GetBestPOSTagFromBeam(\n PartOfSpeechTagInstance *part_of_speech_tag_instance) {\n int position = term_instance_->size() - 1;\n const Node *node = beams_[position + 2]->MinimalNode();\n\n while (node->tag != BOS_tagid_) {\n part_of_speech_tag_instance->set_value_at(position,\n model_->tag_str(node->tag));\n position--;\n node = node->prevoius_node;\n }\n\n part_of_speech_tag_instance->set_size(term_instance_->size());\n}\n\nvoid HMMPartOfSpeechTagger::Tag(\n PartOfSpeechTagInstance *part_of_speech_tag_instance,\n TermInstance *term_instance) {\n term_instance_ = term_instance;\n\n AddBOSNodeToBeam();\n\n \/\/ Viterbi algorithm\n for (int i = 0; i < term_instance->size(); ++i)\n BuildBeam(i);\n\n \/\/ Find the best result\n GetBestPOSTagFromBeam(part_of_speech_tag_instance);\n\n node_pool_->ReleaseAll();\n}\n\nvoid HMMPartOfSpeechTagger::GuessTag(const Node *leftleft_node, \n const Node *left_node,\n Beam<Node> *beam) {\n int leftleft_tag = leftleft_node->tag, \n left_tag = left_node->tag;\n Node *node = nullptr;\n\n node = node_pool_->Alloc();\n node->tag = NN_tagid_;\n node->cost = left_node->cost;\n node->prevoius_node = left_node;\n beam->Add(node);\n\n}\n\nvoid HMMPartOfSpeechTagger::BuildBeam(int position) {\n \/\/ Beam has two BOS node at 0 and 1\n int beam_position = position + 2;\n\n HMMModel::Emit *emit = GetEmitAtPosition(position);\n const Node *leftleft_node, *left_node;\n int leftleft_tag, left_tag, tag;\n\n Beam<Node> *previous_beam = beams_[beam_position - 1];\n Beam<Node> *beam = beams_[beam_position];\n\n previous_beam->Shrink();\n beam->Clear();\n\n\n while (emit) {\n double min_cost = 1e38;\n const Node *min_left_node;\n for (int i = 0; i < previous_beam->size(); ++i) {\n left_node = previous_beam->node_at(i);\n leftleft_node = left_node->prevoius_node;\n\n leftleft_tag = leftleft_node->tag;\n left_tag = left_node->tag;\n\n \/\/ If current word has emit information or current word is punction or \n \/\/ symbol\n\n double trans_cost = model_->trans_cost(leftleft_tag, \n left_tag, \n emit->tag);\n double emit_cost = emit->cost;\n double cost = left_node->cost + trans_cost + emit_cost;\n if (cost < min_cost) {\n printf(\"find min cost %lf\\n\", cost);\n min_cost = cost;\n min_left_node = left_node;\n }\n\n#ifdef LOG\n printf(\"%s %s %s %s\"\n \"total_cost = %lf cost = %lf trans_cost = %lf emit_cost = %lf\\n\",\n term_instance_->term_text_at(position),\n model_->tag_str(leftleft_tag), \n model_->tag_str(left_tag), \n model_->tag_str(emit->tag),\n cost,\n trans_cost + emit_cost,\n trans_cost,\n emit_cost);\n#endif\n }\n\n Node *node = node_pool_->Alloc();\n node->set_value(emit->tag, min_cost, min_left_node);\n beam->Add(node); \n\n emit = emit->next;\n }\n\n}\n\n} \/\/ namespace milkcat\n<|endoftext|>"} {"text":"<commit_before>\/* NOTE: In this document, for a type to \"act like a data type\" means that it\nis default-constructible, copy-constructible, copy-assignable, and destructible.\nIf it allocates heap memory, it must manage it on its own. *\/\n\nnamespace clustering {\n\n\/* `namespace_interface_t` is the main entry point that protocol parsers use to\nperform reads and writes on a namespace. `protocol_t` is a config struct that\nholds all the types specific to that protocol. *\/\ntemplate<class protocol_t>\nclass namespace_interface_t {\n\n \/* This document doesn't deal with the details of how to find namespaces.\n Tim's plan is that each protocol will keep its own directory of namespaces\n organized in a protocol-specific way. Riak could have a map from strings\n to namespaces, along with a way to synchronize the creation of namespaces.\n Memcached could have a set of (namespace, port) pairs. Redis could...\n do whatever makes sense for Redis. *\/\n namespace_interface_t(\n mailbox_cluster_t *cluster,\n metadata_view_t<namespace_metadata_t<protocol_t> > *namespace_metadata\n );\n ~namespace_interface_t();\n\n \/* Performs the given read query on the namespace. [May block] *\/\n protocol_t::read_response_t read(protocol_t::read_t query);\n\n \/* Performs the given write query on the namespace. [May block] *\/\n protocol_t::write_response_t write(protocol_t::write_t query);\n\n \/* Reads and writes configuration information for the namespace, such as the\n replication factor. *\/\n ... configure(...);\n\nprivate:\n ...\n};\n\n} \/* namespace clustering *\/\n\n\/* `?` indicates that something is protocol-specific. Each protocol will define\na `?_protocol_t` for itself and all the members therein. That `?_protocol_t`\nwill be passed as a template parameter to the clustering code so it knows how\nto work with that protocol. *\/\n\nnamespace ? {\n\nstruct ?_protocol_t {\n\n \/* `region_t` is like a set (in the mathematical sense) of keys, although\n not all sets can be expressed as `region_t`s. Protocols will probably be\n implemented as a range of keys, although it could be something weirder, like\n the set of all keys whose hashes fall into a certain range.\n\n In this document, we talk about regions using set notation. \n `union(regions)` refers to the union of multiple regions. And so on. *\/\n\n struct region_t {\n \/* Returns true if this `region_t` is a superset of `x`. *\/\n bool contains(region_t x);\n\n \/* Returns true if this `region_t` overlaps `x`. *\/\n bool overlaps(region_t x);\n\n \/* Returns the `region_t` containing all keys both in this `region_t`\n and `x`. *\/\n region_t intersection(region_t x);\n\n \/* Other requirements: `region_t` must be serializable. The \"==\" and\n \"!=\" operators must work on `region_t`. `region_t` must act like a data\n type. *\/\n\n private:\n ?\n };\n\n \/* `read_t`, `read_response_t`, `write_t`, `write_response_t`, and\n `backfill_chunk_t` must all be serializable. *\/\n\n struct read_t {\n\n \/* Indicates which keys the read depends on. *\/\n region_t get_region();\n\n \/* Breaks the read into several sub-reads for individual regions.\n [Precondition] union(regions) == read.get_region()\n [Precondition] forall x,y in regions, x does not overlap y\n [Postcondition] read.shard(regions).size() == regions.size()\n [Postcondition] read.shard(regions)[i].get_region() IsSubsetOf regions[i]\n *\/\n std::vector<read_t> shard(std::vector<region_t> regions);\n\n \/* Breaks the read into several sub-reads that will be run in parallel\n on different machines. `read_t` may choose how many sub-reads to create,\n but creating more than `optimal_factor` sub-reads won't help performance\n and may hurt it.\n [Postcondition] read.parallelize()[i].get_region() IsSubsetOf read.get_region()\n *\/\n std::vector<read_t> parallelize(int optimal_factor);\n\n \/* Other requirements: `read_t` must be serializable. `read_t` must act\n like a data type. *\/\n\n private:\n ?\n };\n\n struct read_response_t {\n\n \/* Recombines the responses to a group of reads created by\n `read_t::shard()`. *\/\n static read_response_t unshard(std::vector<read_response_t> responses);\n\n \/* Recombines the responses to a group of reads created by\n `read_t::parallelize()`. *\/\n static read_response_t unparallelize(std::vector<read_response_t> responses);\n\n \/* Other requirements: `read_response_t` must be serializable.\n `read_response_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n struct write_t {\n\n \/* Indicates which keys the write depends on or will modify. *\/\n region_t get_region();\n\n \/* Breaks the write into several sub-writes for individual regions.\n Preconditions and postconditions are the same as for `read_t::shard()`.\n *\/\n std::vector<write_t> shard(std::vector<region_t> regions);\n\n \/* Other requirements: `write_t` must be serializable. `write_t` must\n act like a data type. *\/\n\n private:\n ?\n };\n\n struct write_response_t {\n\n \/* Recombines the responses to a group of writes created by\n `write_t::shard()`. *\/\n static write_response_t unshard(std::vector<write_response_t> responses);\n\n \/* Other requirements: `write_response_t` must be serializable.\n `write_response_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n \/* `store_t` is the object that performs actual operations on stored data.\n It is responsible for constructing its own cache and btree.\n\n Although operations may be run on the `store_t` concurrently, it should\n behave as though every operation's effect was instantaneous. For example, if\n the store receives a write and then immediately receives a read before the\n write is done, the read should see the effects of the write. *\/\n\n struct store_t {\n\n \/* Returns the same region that was passed to the constructor. *\/\n region_t get_region();\n\n \/* A store can be either coherent or incoherent. Roughly, \"incoherent\"\n means you're in the middle of a backfill. The coherence of a store must\n be persisted to disk.\n [Precondition] !store.is_backfilling() *\/\n bool is_coherent();\n\n \/* Returns the store's current timestamp.\n [Precondition] !store.is_backfilling() *\/\n repli_timestamp_t get_timestamp();\n\n \/* Performs a read operation on the store. May not modify the store's\n state in any way.\n [Precondition] read.get_region() IsSubsetOf store.get_region()\n [Precondition] store.is_coherent()\n [Precondition] !store.is_backfilling()\n [May block]\n *\/\n read_response_t read(read_t read, order_token_t otok);\n\n \/* Performs a write operation on the store. The effect on the stored\n state must be deterministic; if I have two `store_t`s in the same state\n and I call `write()` on both with the same parameters, then they must\n both transition to the same state.\n [Precondition] write.get_region() IsSubsetOf store.get_region()\n [Precondition] store.is_coherent()\n [Precondition] !store.is_backfilling()\n [Precondition] timestamp >= store.get_timestamp()\n [Postcondition] store.get_timestamp() == timestamp\n [May block]\n *\/\n write_response_t write(write_t write, repli_timestamp_t timestamp, order_token_t otok);\n\n \/* Returns `true` if the store is in the middle of a backfill. *\/\n bool is_backfilling();\n\n struct backfill_request_t {\n\n \/* You don't have to actually implement `get_region()` and\n `get_timestamp()`; they're only here to make it easier to describe\n preconditions and postconditions. *\/\n\n \/* Returns the same value as the backfillee's `get_region()` method.\n *\/\n region_t get_region();\n\n \/* Returns the same value as the backfillee's `get_timestamp()`\n method. *\/\n repli_timestamp_t get_timestamp();\n\n \/* Other requirements: `backfill_request_t` must be serializable.\n `backfill_request_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n struct backfill_chunk_t {\n\n \/* Other requirements: `backfill_chunk_t` must be serializable.\n `backfill_chunk_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n struct backfill_end_t {\n\n \/* Other requirements: `backfill_end_t` must be serializable.\n `backfill_end_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n \/* Prepares the store for a backfill. Returns a `backfill_request_t`\n which expresses what information the store needs backfilled.\n [Precondition] !store.is_backfilling()\n [Postcondition] store.is_backfilling()\n [Postcondition] store.backfillee_begin().get_region() == store.get_region()\n [Postcondition] store.get_timestamp() == store.backfillee_begin().get_timestamp()\n [May block] *\/\n backfill_request_t backfillee_begin();\n\n \/* Delivers a chunk of a running backfill.\n [Precondition] store.is_backfilling()\n [May block] *\/\n void backfillee_chunk(backfill_chunk_t);\n\n \/* Notifies that the backfill is over.\n [Precondition] store.is_backfilling()\n [Postcondition] !store.is_backfilling()\n [Postcondition] store.is_coherent()\n [May block] *\/\n void backfillee_end(backfill_end_t);\n\n \/* Notifies that the backfill won't be finished because something went\n wrong.\n [Precondition] store.is_backfilling()\n [Postcondition] !store.is_backfilling()\n [Postcondition] !store.is_coherent()\n [May block] *\/\n void backfillee_cancel();\n\n \/* Sends a backfill to another store. `request` should be the return\n value of the backfillee's `backfillee_begin()` method. `backfiller()`\n should call `chunk_fun` with `backfill_chunk_t`s to be passed to the\n backfillee's `backfillee_chunk()` method. `backfiller()` should block\n until the backfill is done, and then return a `backfill_end_t` to be\n passed to the backfillee's `backfillee_end()` method. If `interruptor`\n is pulsed before the backfill is over, then `backfiller()` should stop\n the backfill and throw an `interrupted_exc_t` as soon as possible.\n [Precondition] request.get_region() == store.get_region()\n [Precondition] request.get_timestamp() <= store.get_timestamp()\n [Precondition] !store.is_backfilling()\n [Precondition] store.is_coherent()\n [May block] *\/\n backfill_end_t backfiller(\n backfill_request_t request,\n boost::function<void(backfill_chunk_t)> chunk_fun,\n signal_t *interruptor);\n\n \/* Here's an example of how to use the backfill API. `backfill()` will\n copy data from `backfiller` to `backfillee` unless `interruptor` is\n pulsed, in which case it will throw `interrupted_exc_t`.\n\n void backfill(store_t *backfillee, store_t *backfiller, signal_t *interruptor) {\n backfill_request_t req = backfillee->backfillee_begin();\n backfill_end_t end;\n try {\n end = backfiller->backfiller(\n req,\n boost::bind(&store_t::backfillee_chunk, backfillee),\n interruptor);\n } catch (interrupted_exc_t) {\n backfillee->backfillee_cancel();\n throw;\n }\n backfillee->backfillee_end(end);\n }\n *\/\n\n private:\n ?\n };\n\n \/* Stores will be created and destroyed via some yet-unspecified mechanism.\n I don't know exactly what it will be yet. *\/\n\n \/* NOTE: I don't know what form the `rebalance()` function will take in the\n finished product. I'm including it here because I know something like it\n will eventually be necessary. But it probably won't be a stand-alone\n function, and its type signature might be different.\n \n Creates a set of stores which contain the same data as `recyclees`, but\n whose regions are `goals`. Each store in `recyclees` must either be\n destroyed or re-used as part of the return value.\n [Precondition] The regions of the stores in `recyclees` must not overlap.\n [Precondition] The regions in `goals` must not overlap.\n [Precondition] The union of the regions in `recyclees` must be the same\n as the union of the regions in `goals`.\n [Postcondition] store_manager.rebalance(recyclees, goals)[i].get_region() == goals[i]\n [Postcondition] store_manager.rebalance(recyclees, goals).size() == goals.size()\n [May block] *\/\n static std::vector<store_t *> rebalance(\n std::vector<store_t *> recyclees,\n std::vector<region_t> goals);\n};\n\n} \/* namespace ? *\/\n\n\/* Notes on ordering guarantees:\n\n1. All the replicas of each individual key will see writes in the same order.\n\n Example: Suppose K = \"x\". You send (append \"a\" to K) and (append \"b\" to K)\n concurrently from different nodes. Either every copy of K will become \"xab\",\n or every copy of K will become \"xba\", but the different copies of K will\n never disagree.\n\n2. Queries from the same origin will be performed in same order they are sent.\n\n Example: Suppose K = \"a\". You send (set K to \"b\") and (read K) from the same\n thread on the same node, in that order. The read will return \"b\".\n\n3. Arbitrary atomic single-key operations can be performed, as long as the\n `protocol_t::store_t` supports them.\n\n4. There are no other atomicity or ordering guarantees.\n\n Example: Suppose K1 = \"x\" and K2 = \"x\". You send (append \"a\" to every key)\n and (append \"b\" to every key) concurrently. Every copy of K1 will agree with\n every other copy of K1, and every copy of K2 will agree with every other\n copy of K2, but K1 and K2 may disagree.\n\n Example: Suppose K = \"a\". You send (set K to \"b\"). As soon as it's sent, you\n send (set K to \"c\") from a different node. K may end up being either \"b\" or\n \"c\".\n\n Example: Suppose K1 = \"a\" and K2 = \"a\". You send (set K1 to \"b\") and (set K2\n to \"b\") from the same node, in that order. Then you send (read K1 and K2)\n from a different node. The read may return (K1 = \"a\", K2 = \"b\").\n\n5. There is no simple way to perform an atomic multikey transaction. You might\n be able to fake it by using a key as a \"lock\".\n*\/\n<commit_msg>Add another insight to clustering doc. (Joe is annoying tim even more)<commit_after>\/* NOTE: In this document, for a type to \"act like a data type\" means that it\nis default-constructible, copy-constructible, copy-assignable, and destructible.\nIf it allocates heap memory, it must manage it on its own. *\/\n\nnamespace clustering {\n\n\/* `namespace_interface_t` is the main entry point that protocol parsers use to\nperform reads and writes on a namespace. `protocol_t` is a config struct that\nholds all the types specific to that protocol. *\/\ntemplate<class protocol_t>\nclass namespace_interface_t {\n\n \/* This document doesn't deal with the details of how to find namespaces.\n Tim's plan is that each protocol will keep its own directory of namespaces\n organized in a protocol-specific way. Riak could have a map from strings\n to namespaces, along with a way to synchronize the creation of namespaces.\n Memcached could have a set of (namespace, port) pairs. Redis could...\n do whatever makes sense for Redis. *\/\n namespace_interface_t(\n mailbox_cluster_t *cluster,\n metadata_view_t<namespace_metadata_t<protocol_t> > *namespace_metadata\n );\n ~namespace_interface_t();\n\n \/* Performs the given read query on the namespace. [May block] *\/\n protocol_t::read_response_t read(protocol_t::read_t query);\n\n \/* Performs the given write query on the namespace. [May block] *\/\n protocol_t::write_response_t write(protocol_t::write_t query);\n\n \/* Reads and writes configuration information for the namespace, such as the\n replication factor. *\/\n ... configure(...);\n\nprivate:\n ...\n};\n\n} \/* namespace clustering *\/\n\n\/* `?` indicates that something is protocol-specific. Each protocol will define\na `?_protocol_t` for itself and all the members therein. That `?_protocol_t`\nwill be passed as a template parameter to the clustering code so it knows how\nto work with that protocol. *\/\n\nnamespace ? {\n\nstruct ?_protocol_t {\n\n \/* `region_t` is like a set (in the mathematical sense) of keys, although\n not all sets can be expressed as `region_t`s. Protocols will probably be\n implemented as a range of keys, although it could be something weirder, like\n the set of all keys whose hashes fall into a certain range.\n\n In this document, we talk about regions using set notation. \n `union(regions)` refers to the union of multiple regions. And so on. *\/\n\n struct region_t {\n \/* Returns true if this `region_t` is a superset of `x`. *\/\n bool contains(region_t x);\n\n \/* Returns true if this `region_t` overlaps `x`. *\/\n bool overlaps(region_t x);\n\n \/* Returns the `region_t` containing all keys both in this `region_t`\n and `x`. *\/\n region_t intersection(region_t x);\n\n \/* Other requirements: `region_t` must be serializable. The \"==\" and\n \"!=\" operators must work on `region_t`. `region_t` must act like a data\n type. *\/\n\n private:\n ?\n };\n\n \/* `read_t`, `read_response_t`, `write_t`, `write_response_t`, and\n `backfill_chunk_t` must all be serializable. *\/\n\n struct read_t {\n\n \/* Indicates which keys the read depends on. *\/\n region_t get_region();\n\n \/* Breaks the read into several sub-reads for individual regions.\n [Precondition] union(regions) == read.get_region()\n [Precondition] forall x,y in regions, x does not overlap y\n [Postcondition] read.shard(regions).size() == regions.size()\n [Postcondition] read.shard(regions)[i].get_region() IsSubsetOf regions[i]\n *\/\n std::vector<read_t> shard(std::vector<region_t> regions);\n\n \/* Breaks the read into several sub-reads that will be run in parallel\n on different machines. `read_t` may choose how many sub-reads to create,\n but creating more than `optimal_factor` sub-reads won't help performance\n and may hurt it.\n [Postcondition] read.parallelize()[i].get_region() IsSubsetOf read.get_region()\n \n Notice that parallelize need not return reads with disjoint regions, in fact in\n many reasonable cases the regions will not be disjoint. Such as in the case of\n a riak bucket dump.\n *\/\n std::vector<read_t> parallelize(int optimal_factor);\n\n \/* Other requirements: `read_t` must be serializable. `read_t` must act\n like a data type. *\/\n\n private:\n ?\n };\n\n struct read_response_t {\n\n \/* Recombines the responses to a group of reads created by\n `read_t::shard()`. *\/\n static read_response_t unshard(std::vector<read_response_t> responses);\n\n \/* Recombines the responses to a group of reads created by\n `read_t::parallelize()`. *\/\n static read_response_t unparallelize(std::vector<read_response_t> responses);\n\n \/* Other requirements: `read_response_t` must be serializable.\n `read_response_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n struct write_t {\n\n \/* Indicates which keys the write depends on or will modify. *\/\n region_t get_region();\n\n \/* Breaks the write into several sub-writes for individual regions.\n Preconditions and postconditions are the same as for `read_t::shard()`.\n *\/\n std::vector<write_t> shard(std::vector<region_t> regions);\n\n \/* Other requirements: `write_t` must be serializable. `write_t` must\n act like a data type. *\/\n\n private:\n ?\n };\n\n struct write_response_t {\n\n \/* Recombines the responses to a group of writes created by\n `write_t::shard()`. *\/\n static write_response_t unshard(std::vector<write_response_t> responses);\n\n \/* Other requirements: `write_response_t` must be serializable.\n `write_response_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n \/* `store_t` is the object that performs actual operations on stored data.\n It is responsible for constructing its own cache and btree.\n\n Although operations may be run on the `store_t` concurrently, it should\n behave as though every operation's effect was instantaneous. For example, if\n the store receives a write and then immediately receives a read before the\n write is done, the read should see the effects of the write. *\/\n\n struct store_t {\n\n \/* Returns the same region that was passed to the constructor. *\/\n region_t get_region();\n\n \/* A store can be either coherent or incoherent. Roughly, \"incoherent\"\n means you're in the middle of a backfill. The coherence of a store must\n be persisted to disk.\n [Precondition] !store.is_backfilling() *\/\n bool is_coherent();\n\n \/* Returns the store's current timestamp.\n [Precondition] !store.is_backfilling() *\/\n repli_timestamp_t get_timestamp();\n\n \/* Performs a read operation on the store. May not modify the store's\n state in any way.\n [Precondition] read.get_region() IsSubsetOf store.get_region()\n [Precondition] store.is_coherent()\n [Precondition] !store.is_backfilling()\n [May block]\n *\/\n read_response_t read(read_t read, order_token_t otok);\n\n \/* Performs a write operation on the store. The effect on the stored\n state must be deterministic; if I have two `store_t`s in the same state\n and I call `write()` on both with the same parameters, then they must\n both transition to the same state.\n [Precondition] write.get_region() IsSubsetOf store.get_region()\n [Precondition] store.is_coherent()\n [Precondition] !store.is_backfilling()\n [Precondition] timestamp >= store.get_timestamp()\n [Postcondition] store.get_timestamp() == timestamp\n [May block]\n *\/\n write_response_t write(write_t write, repli_timestamp_t timestamp, order_token_t otok);\n\n \/* Returns `true` if the store is in the middle of a backfill. *\/\n bool is_backfilling();\n\n struct backfill_request_t {\n\n \/* You don't have to actually implement `get_region()` and\n `get_timestamp()`; they're only here to make it easier to describe\n preconditions and postconditions. *\/\n\n \/* Returns the same value as the backfillee's `get_region()` method.\n *\/\n region_t get_region();\n\n \/* Returns the same value as the backfillee's `get_timestamp()`\n method. *\/\n repli_timestamp_t get_timestamp();\n\n \/* Other requirements: `backfill_request_t` must be serializable.\n `backfill_request_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n struct backfill_chunk_t {\n\n \/* Other requirements: `backfill_chunk_t` must be serializable.\n `backfill_chunk_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n struct backfill_end_t {\n\n \/* Other requirements: `backfill_end_t` must be serializable.\n `backfill_end_t` must act like a data type. *\/\n\n private:\n ?\n };\n\n \/* Prepares the store for a backfill. Returns a `backfill_request_t`\n which expresses what information the store needs backfilled.\n [Precondition] !store.is_backfilling()\n [Postcondition] store.is_backfilling()\n [Postcondition] store.backfillee_begin().get_region() == store.get_region()\n [Postcondition] store.get_timestamp() == store.backfillee_begin().get_timestamp()\n [May block] *\/\n backfill_request_t backfillee_begin();\n\n \/* Delivers a chunk of a running backfill.\n [Precondition] store.is_backfilling()\n [May block] *\/\n void backfillee_chunk(backfill_chunk_t);\n\n \/* Notifies that the backfill is over.\n [Precondition] store.is_backfilling()\n [Postcondition] !store.is_backfilling()\n [Postcondition] store.is_coherent()\n [May block] *\/\n void backfillee_end(backfill_end_t);\n\n \/* Notifies that the backfill won't be finished because something went\n wrong.\n [Precondition] store.is_backfilling()\n [Postcondition] !store.is_backfilling()\n [Postcondition] !store.is_coherent()\n [May block] *\/\n void backfillee_cancel();\n\n \/* Sends a backfill to another store. `request` should be the return\n value of the backfillee's `backfillee_begin()` method. `backfiller()`\n should call `chunk_fun` with `backfill_chunk_t`s to be passed to the\n backfillee's `backfillee_chunk()` method. `backfiller()` should block\n until the backfill is done, and then return a `backfill_end_t` to be\n passed to the backfillee's `backfillee_end()` method. If `interruptor`\n is pulsed before the backfill is over, then `backfiller()` should stop\n the backfill and throw an `interrupted_exc_t` as soon as possible.\n [Precondition] request.get_region() == store.get_region()\n [Precondition] request.get_timestamp() <= store.get_timestamp()\n [Precondition] !store.is_backfilling()\n [Precondition] store.is_coherent()\n [May block] *\/\n backfill_end_t backfiller(\n backfill_request_t request,\n boost::function<void(backfill_chunk_t)> chunk_fun,\n signal_t *interruptor);\n\n \/* Here's an example of how to use the backfill API. `backfill()` will\n copy data from `backfiller` to `backfillee` unless `interruptor` is\n pulsed, in which case it will throw `interrupted_exc_t`.\n\n void backfill(store_t *backfillee, store_t *backfiller, signal_t *interruptor) {\n backfill_request_t req = backfillee->backfillee_begin();\n backfill_end_t end;\n try {\n end = backfiller->backfiller(\n req,\n boost::bind(&store_t::backfillee_chunk, backfillee),\n interruptor);\n } catch (interrupted_exc_t) {\n backfillee->backfillee_cancel();\n throw;\n }\n backfillee->backfillee_end(end);\n }\n *\/\n\n private:\n ?\n };\n\n \/* Stores will be created and destroyed via some yet-unspecified mechanism.\n I don't know exactly what it will be yet. *\/\n\n \/* NOTE: I don't know what form the `rebalance()` function will take in the\n finished product. I'm including it here because I know something like it\n will eventually be necessary. But it probably won't be a stand-alone\n function, and its type signature might be different.\n \n Creates a set of stores which contain the same data as `recyclees`, but\n whose regions are `goals`. Each store in `recyclees` must either be\n destroyed or re-used as part of the return value.\n [Precondition] The regions of the stores in `recyclees` must not overlap.\n [Precondition] The regions in `goals` must not overlap.\n [Precondition] The union of the regions in `recyclees` must be the same\n as the union of the regions in `goals`.\n [Postcondition] store_manager.rebalance(recyclees, goals)[i].get_region() == goals[i]\n [Postcondition] store_manager.rebalance(recyclees, goals).size() == goals.size()\n [May block] *\/\n static std::vector<store_t *> rebalance(\n std::vector<store_t *> recyclees,\n std::vector<region_t> goals);\n};\n\n} \/* namespace ? *\/\n\n\/* Notes on ordering guarantees:\n\n1. All the replicas of each individual key will see writes in the same order.\n\n Example: Suppose K = \"x\". You send (append \"a\" to K) and (append \"b\" to K)\n concurrently from different nodes. Either every copy of K will become \"xab\",\n or every copy of K will become \"xba\", but the different copies of K will\n never disagree.\n\n2. Queries from the same origin will be performed in same order they are sent.\n\n Example: Suppose K = \"a\". You send (set K to \"b\") and (read K) from the same\n thread on the same node, in that order. The read will return \"b\".\n\n3. Arbitrary atomic single-key operations can be performed, as long as the\n `protocol_t::store_t` supports them.\n\n4. There are no other atomicity or ordering guarantees.\n\n Example: Suppose K1 = \"x\" and K2 = \"x\". You send (append \"a\" to every key)\n and (append \"b\" to every key) concurrently. Every copy of K1 will agree with\n every other copy of K1, and every copy of K2 will agree with every other\n copy of K2, but K1 and K2 may disagree.\n\n Example: Suppose K = \"a\". You send (set K to \"b\"). As soon as it's sent, you\n send (set K to \"c\") from a different node. K may end up being either \"b\" or\n \"c\".\n\n Example: Suppose K1 = \"a\" and K2 = \"a\". You send (set K1 to \"b\") and (set K2\n to \"b\") from the same node, in that order. Then you send (read K1 and K2)\n from a different node. The read may return (K1 = \"a\", K2 = \"b\").\n\n5. There is no simple way to perform an atomic multikey transaction. You might\n be able to fake it by using a key as a \"lock\".\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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#ifndef ALTITUDE_HPP\n#define ALTITUDE_HPP\n\n#include <uORB\/topics\/vehicle_local_position.h>\n#include <uORB\/topics\/wind_estimate.h>\n\nclass MavlinkStreamAltitude : public MavlinkStream\n{\npublic:\n\tstatic MavlinkStream *new_instance(Mavlink *mavlink) { return new MavlinkStreamAltitude(mavlink); }\n\n\tstatic constexpr const char *get_name_static() { return \"ALTITUDE\"; }\n\tstatic constexpr uint16_t get_id_static() { return MAVLINK_MSG_ID_ALTITUDE; }\n\n\tconst char *get_name() const override { return get_name_static(); }\n\tuint16_t get_id() override { return get_id_static(); }\n\n\tunsigned get_size() override\n\t{\n\t\treturn _local_pos_sub.advertised() ? MAVLINK_MSG_ID_ALTITUDE_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES : 0;\n\t}\n\nprivate:\n\texplicit MavlinkStreamAltitude(Mavlink *mavlink) : MavlinkStream(mavlink) {}\n\n\tuORB::Subscription _local_pos_sub{ORB_ID(vehicle_local_position)};\n\tuORB::Subscription _home_sub{ORB_ID(home_position)};\n\tuORB::Subscription _air_data_sub{ORB_ID(vehicle_air_data)};\n\n\tbool send() override\n\t{\n\t\tmavlink_altitude_t msg{};\n\n\t\tmsg.altitude_monotonic = NAN;\n\t\tmsg.altitude_amsl = NAN;\n\t\tmsg.altitude_local = NAN;\n\t\tmsg.altitude_relative = NAN;\n\t\tmsg.altitude_terrain = NAN;\n\t\tmsg.bottom_clearance = NAN;\n\n\t\t\/\/ always update monotonic altitude\n\t\tbool air_data_updated = false;\n\t\tvehicle_air_data_s air_data{};\n\t\t_air_data_sub.copy(&air_data);\n\n\t\tif (air_data.timestamp > 0) {\n\t\t\tmsg.altitude_monotonic = air_data.baro_alt_meter;\n\n\t\t\tair_data_updated = true;\n\t\t}\n\n\t\tbool lpos_updated = false;\n\n\t\tvehicle_local_position_s local_pos;\n\n\t\tif (_local_pos_sub.copy(&local_pos)) {\n\n\t\t\tif (local_pos.z_valid) {\n\t\t\t\tif (local_pos.z_global) {\n\t\t\t\t\tmsg.altitude_amsl = -local_pos.z + local_pos.ref_alt;\n\n\t\t\t\t} else {\n\t\t\t\t\tmsg.altitude_amsl = msg.altitude_monotonic;\n\t\t\t\t}\n\n\t\t\t\tmsg.altitude_local = -local_pos.z;\n\n\t\t\t\thome_position_s home{};\n\t\t\t\t_home_sub.copy(&home);\n\n\t\t\t\tif (home.valid_alt) {\n\t\t\t\t\tmsg.altitude_relative = -(local_pos.z - home.z);\n\n\t\t\t\t} else {\n\t\t\t\t\tmsg.altitude_relative = -local_pos.z;\n\t\t\t\t}\n\n\t\t\t\tif (local_pos.dist_bottom_valid) {\n\t\t\t\t\tmsg.altitude_terrain = -local_pos.z - local_pos.dist_bottom;\n\t\t\t\t\tmsg.bottom_clearance = local_pos.dist_bottom;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlpos_updated = true;\n\t\t}\n\n\t\t\/\/ local position timeout after 10 ms\n\t\t\/\/ avoid publishing only baro altitude_monotonic if possible\n\t\tbool lpos_timeout = (hrt_elapsed_time(&local_pos.timestamp) > 10_ms);\n\n\t\tif (lpos_updated || (air_data_updated && lpos_timeout)) {\n\t\t\tmsg.time_usec = hrt_absolute_time();\n\t\t\tmavlink_msg_altitude_send_struct(_mavlink->get_channel(), &msg);\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n};\n\n#endif \/\/ ALTITUDE_HPP\n<commit_msg>mavlink: ALTITUDE stream initialize local_pos<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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#ifndef ALTITUDE_HPP\n#define ALTITUDE_HPP\n\n#include <uORB\/topics\/vehicle_local_position.h>\n#include <uORB\/topics\/wind_estimate.h>\n\nclass MavlinkStreamAltitude : public MavlinkStream\n{\npublic:\n\tstatic MavlinkStream *new_instance(Mavlink *mavlink) { return new MavlinkStreamAltitude(mavlink); }\n\n\tstatic constexpr const char *get_name_static() { return \"ALTITUDE\"; }\n\tstatic constexpr uint16_t get_id_static() { return MAVLINK_MSG_ID_ALTITUDE; }\n\n\tconst char *get_name() const override { return get_name_static(); }\n\tuint16_t get_id() override { return get_id_static(); }\n\n\tunsigned get_size() override\n\t{\n\t\treturn _local_pos_sub.advertised() ? MAVLINK_MSG_ID_ALTITUDE_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES : 0;\n\t}\n\nprivate:\n\texplicit MavlinkStreamAltitude(Mavlink *mavlink) : MavlinkStream(mavlink) {}\n\n\tuORB::Subscription _local_pos_sub{ORB_ID(vehicle_local_position)};\n\tuORB::Subscription _home_sub{ORB_ID(home_position)};\n\tuORB::Subscription _air_data_sub{ORB_ID(vehicle_air_data)};\n\n\tbool send() override\n\t{\n\t\tmavlink_altitude_t msg{};\n\n\t\tmsg.altitude_monotonic = NAN;\n\t\tmsg.altitude_amsl = NAN;\n\t\tmsg.altitude_local = NAN;\n\t\tmsg.altitude_relative = NAN;\n\t\tmsg.altitude_terrain = NAN;\n\t\tmsg.bottom_clearance = NAN;\n\n\t\t\/\/ always update monotonic altitude\n\t\tbool air_data_updated = false;\n\t\tvehicle_air_data_s air_data{};\n\t\t_air_data_sub.copy(&air_data);\n\n\t\tif (air_data.timestamp > 0) {\n\t\t\tmsg.altitude_monotonic = air_data.baro_alt_meter;\n\n\t\t\tair_data_updated = true;\n\t\t}\n\n\t\tbool lpos_updated = false;\n\n\t\tvehicle_local_position_s local_pos{};\n\n\t\tif (_local_pos_sub.copy(&local_pos)) {\n\n\t\t\tif (local_pos.z_valid) {\n\t\t\t\tif (local_pos.z_global) {\n\t\t\t\t\tmsg.altitude_amsl = -local_pos.z + local_pos.ref_alt;\n\n\t\t\t\t} else {\n\t\t\t\t\tmsg.altitude_amsl = msg.altitude_monotonic;\n\t\t\t\t}\n\n\t\t\t\tmsg.altitude_local = -local_pos.z;\n\n\t\t\t\thome_position_s home{};\n\t\t\t\t_home_sub.copy(&home);\n\n\t\t\t\tif (home.valid_alt) {\n\t\t\t\t\tmsg.altitude_relative = -(local_pos.z - home.z);\n\n\t\t\t\t} else {\n\t\t\t\t\tmsg.altitude_relative = -local_pos.z;\n\t\t\t\t}\n\n\t\t\t\tif (local_pos.dist_bottom_valid) {\n\t\t\t\t\tmsg.altitude_terrain = -local_pos.z - local_pos.dist_bottom;\n\t\t\t\t\tmsg.bottom_clearance = local_pos.dist_bottom;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlpos_updated = true;\n\t\t}\n\n\t\t\/\/ local position timeout after 10 ms\n\t\t\/\/ avoid publishing only baro altitude_monotonic if possible\n\t\tbool lpos_timeout = (hrt_elapsed_time(&local_pos.timestamp) > 10_ms);\n\n\t\tif (lpos_updated || (air_data_updated && lpos_timeout)) {\n\t\t\tmsg.time_usec = hrt_absolute_time();\n\t\t\tmavlink_msg_altitude_send_struct(_mavlink->get_channel(), &msg);\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n};\n\n#endif \/\/ ALTITUDE_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"platform\/i_platform.h\"\n#include \"network\/ctf_client_datas_message.h\"\n#include \"core\/ctf_program_state.h\"\n\nnamespace network {\nnamespace ctf {\n\nClientDatasMessageSenderSystem::ClientDatasMessageSenderSystem()\n : MessageSenderSystem()\n{\n \/\/This one is not used yet you should wire it before use\n}\n\n\nvoid ClientDatasMessageSenderSystem::Init()\n{\n MessageSenderSystem::Init();\n \/\/This one is not used yet you should wire it before use\n mOnCtfClientDatasChangedEvent = EventServer<CtfClientDatasChangedEvent>::Get().Subscribe( boost::bind( &ClientDatasMessageSenderSystem::OnCtfClientDatasChangedEvent, this, _1) );\n}\n\n\nvoid ClientDatasMessageSenderSystem::Update(double DeltaTime)\n{\n MessageSenderSystem::Update(DeltaTime);\n \/\/This one is not used yet you should wire it before use\n}\n\nvoid ClientDatasMessageSenderSystem::OnCtfClientDatasChangedEvent( CtfClientDatasChangedEvent const & event )\n{\n std::auto_ptr<ctf::ClientDatasMessage> message(new ctf::ClientDatasMessage);\n message->mClientDatas = event.mCtfClientDatas;\n mMessageHolder.AddOutgoingMessage(message);\n}\n\nClientDatasMessageHandlerSubSystem::ClientDatasMessageHandlerSubSystem()\n : MessageHandlerSubSystem()\n{\n}\n\n\nvoid ClientDatasMessageHandlerSubSystem::Init()\n{\n}\n\nvoid ClientDatasMessageHandlerSubSystem::Execute(Message const& message)\n{\n if ( mProgramState.mMode )\n {\n }\n ClientDatasMessage const& msg=static_cast<ClientDatasMessage const&>(message);\n L1(\"executing ctf::ClientDatasMessageHandlerSubSystem from id: %d \\n\",msg.mSenderId );\n ::ctf::ProgramState& ctfProgramState=::ctf::ProgramState::Get();\n ctfProgramState.mClientDatas=msg.mClientDatas;\n for (::ctf::ProgramState::ClientDatas_t::iterator i=ctfProgramState.mClientDatas.begin(), e=ctfProgramState.mClientDatas.end();i!=e;++i)\n {\n L1(\"**** ctf arrived. **** from id: %d \\n\", i->mClientId );\n L1(\" team:%d\\n\", i->mTeam );\n }\n}\n\n} \/\/ namespace ctf\n} \/\/ namespace network\n\n<commit_msg>M: remove unused condition<commit_after>#include \"platform\/i_platform.h\"\n#include \"network\/ctf_client_datas_message.h\"\n#include \"core\/ctf_program_state.h\"\n\nnamespace network {\nnamespace ctf {\n\nClientDatasMessageSenderSystem::ClientDatasMessageSenderSystem()\n : MessageSenderSystem()\n{\n \/\/This one is not used yet you should wire it before use\n}\n\n\nvoid ClientDatasMessageSenderSystem::Init()\n{\n MessageSenderSystem::Init();\n \/\/This one is not used yet you should wire it before use\n mOnCtfClientDatasChangedEvent = EventServer<CtfClientDatasChangedEvent>::Get().Subscribe( boost::bind( &ClientDatasMessageSenderSystem::OnCtfClientDatasChangedEvent, this, _1) );\n}\n\n\nvoid ClientDatasMessageSenderSystem::Update(double DeltaTime)\n{\n MessageSenderSystem::Update(DeltaTime);\n \/\/This one is not used yet you should wire it before use\n}\n\nvoid ClientDatasMessageSenderSystem::OnCtfClientDatasChangedEvent( CtfClientDatasChangedEvent const & event )\n{\n std::auto_ptr<ctf::ClientDatasMessage> message(new ctf::ClientDatasMessage);\n message->mClientDatas = event.mCtfClientDatas;\n mMessageHolder.AddOutgoingMessage(message);\n}\n\nClientDatasMessageHandlerSubSystem::ClientDatasMessageHandlerSubSystem()\n : MessageHandlerSubSystem()\n{\n}\n\n\nvoid ClientDatasMessageHandlerSubSystem::Init()\n{\n}\n\nvoid ClientDatasMessageHandlerSubSystem::Execute(Message const& message)\n{\n ClientDatasMessage const& msg=static_cast<ClientDatasMessage const&>(message);\n L1(\"executing ctf::ClientDatasMessageHandlerSubSystem from id: %d \\n\",msg.mSenderId );\n ::ctf::ProgramState& ctfProgramState=::ctf::ProgramState::Get();\n ctfProgramState.mClientDatas=msg.mClientDatas;\n for (::ctf::ProgramState::ClientDatas_t::iterator i=ctfProgramState.mClientDatas.begin(), e=ctfProgramState.mClientDatas.end();i!=e;++i)\n {\n L1(\"**** ctf arrived. **** from id: %d \\n\", i->mClientId );\n L1(\" team:%d\\n\", i->mTeam );\n }\n}\n\n} \/\/ namespace ctf\n} \/\/ namespace network\n\n<|endoftext|>"} {"text":"<commit_before>\/\/*****************************************************************************\n\/\/ Copyright 2017-2020 Intel Corporation\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#include \"ngraph\/op\/embedding_segments_sum.hpp\"\n#include \"ngraph\/op\/constant.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\nconstexpr NodeTypeInfo op::v3::EmbeddingSegmentsSum::type_info;\n\nop::v3::EmbeddingSegmentsSum::EmbeddingSegmentsSum(const Output<Node>& emb_table,\n const Output<Node>& indices,\n const Output<Node>& segment_ids,\n const Output<Node>& num_segments,\n const Output<Node>& per_sample_weights,\n const Output<Node>& default_index)\n : Op({emb_table, indices, segment_ids, num_segments, per_sample_weights, default_index})\n{\n constructor_validate_and_infer_types();\n}\n\nop::v3::EmbeddingSegmentsSum::EmbeddingSegmentsSum(const Output<Node>& emb_table,\n const Output<Node>& indices,\n const Output<Node>& segment_ids,\n const Output<Node>& num_segments,\n const Output<Node>& per_sample_weights)\n : Op({emb_table, indices, segment_ids, num_segments, per_sample_weights})\n{\n constructor_validate_and_infer_types();\n}\n\nop::v3::EmbeddingSegmentsSum::EmbeddingSegmentsSum(const Output<Node>& emb_table,\n const Output<Node>& indices,\n const Output<Node>& segment_ids,\n const Output<Node>& num_segments)\n : Op({emb_table, indices, segment_ids, num_segments})\n{\n constructor_validate_and_infer_types();\n}\n\nvoid op::v3::EmbeddingSegmentsSum::validate_and_infer_types()\n{\n enum\n {\n EMB_TABLE,\n INDICES,\n SEGMENT_IDS,\n NUM_SEGMENTS,\n PER_SAMPLE_WEIGHTS,\n DEFAULT_INDEX\n };\n\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(SEGMENT_IDS) == element::i64 ||\n get_input_element_type(SEGMENT_IDS) == element::i32,\n \"SEGMENT_IDS type must be i32 or i64\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(INDICES) == element::i64 ||\n get_input_element_type(INDICES) == element::i32,\n \"INDICES type must be i32 or i64\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(NUM_SEGMENTS) == element::i64 ||\n get_input_element_type(NUM_SEGMENTS) == element::i32,\n \"NUM_SEGMENTS type must be i32 or i64\");\n\n NODE_VALIDATION_CHECK(\n this,\n get_input_element_type(INDICES).compatible(get_input_element_type(SEGMENT_IDS)),\n \"Segment_ids element type (\",\n get_input_element_type(SEGMENT_IDS),\n \") must match indices element type (\",\n get_input_element_type(INDICES),\n \")\");\n\n NODE_VALIDATION_CHECK(\n this,\n get_input_element_type(SEGMENT_IDS).compatible(get_input_element_type(NUM_SEGMENTS)),\n \"Num_segments element type (\",\n get_input_element_type(NUM_SEGMENTS),\n \") must match Segment_ids element type (\",\n get_input_element_type(SEGMENT_IDS),\n \")\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(INDICES).is_dynamic() ||\n get_input_partial_shape(INDICES).to_shape().size() == 1,\n \"INDICES must be 1D\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(SEGMENT_IDS).is_dynamic() ||\n get_input_partial_shape(SEGMENT_IDS).to_shape().size() == 1,\n \"SEGMENT_IDS must be 1D\");\n\n NODE_VALIDATION_CHECK(\n this,\n get_input_partial_shape(INDICES).compatible(get_input_partial_shape(SEGMENT_IDS)),\n \"INDICES and SEGMENT_IDS shape must be same\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(NUM_SEGMENTS).compatible(PartialShape{}),\n \"NUM_SEGMENTS must be a scalar\");\n\n if (get_input_size() >= 5)\n {\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(EMB_TABLE).compatible(\n get_input_element_type(PER_SAMPLE_WEIGHTS)),\n \"Per sample weight element type (\",\n get_input_element_type(PER_SAMPLE_WEIGHTS),\n \") must match embedding table element type (\",\n get_input_element_type(EMB_TABLE),\n \")\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(PER_SAMPLE_WEIGHTS).is_dynamic() ||\n get_input_partial_shape(PER_SAMPLE_WEIGHTS).to_shape().size() ==\n 1,\n \"PER_SAMPLE_WEIGHTS must be 1D\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(INDICES).compatible(\n get_input_partial_shape(PER_SAMPLE_WEIGHTS)),\n \"INDICES and PER_SAMPLE_WEIGHTS shape must be same\");\n }\n\n if (get_input_size() == 6)\n {\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(DEFAULT_INDEX) == element::i64 ||\n get_input_element_type(DEFAULT_INDEX) == element::i32,\n \"DEFAULT_INDEX type must be i32 or i64\");\n\n NODE_VALIDATION_CHECK(\n this,\n get_input_element_type(INDICES).compatible(get_input_element_type(DEFAULT_INDEX)),\n \"Default_index element type (\",\n get_input_element_type(DEFAULT_INDEX),\n \") must match indices element type (\",\n get_input_element_type(INDICES),\n \")\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(DEFAULT_INDEX).compatible(PartialShape{}),\n \"DEFAULT_INDEX must be a scalar\");\n }\n\n element::Type result_et = get_input_element_type(EMB_TABLE);\n\n const PartialShape& emb_table_shape = get_input_partial_shape(EMB_TABLE);\n\n PartialShape result_shape;\n if (emb_table_shape.rank().is_static())\n {\n std::vector<Dimension> result_dims(emb_table_shape.rank().get_length());\n result_dims[0] = Dimension::dynamic();\n for (size_t i = 1; i < emb_table_shape.rank().get_length(); i++)\n {\n result_dims[i] = emb_table_shape[i];\n }\n\n result_shape = PartialShape(result_dims);\n }\n else\n {\n result_shape = PartialShape::dynamic();\n }\n\n set_input_is_relevant_to_shape(NUM_SEGMENTS);\n set_output_type(0, result_et, result_shape);\n}\n\nshared_ptr<Node>\n op::v3::EmbeddingSegmentsSum::clone_with_new_inputs(const OutputVector& new_args) const\n{\n check_new_args_count(this, new_args);\n if (new_args.size() == 4)\n {\n return make_shared<EmbeddingSegmentsSum>(\n new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3));\n }\n else if (new_args.size() == 5)\n {\n return make_shared<EmbeddingSegmentsSum>(\n new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3), new_args.at(4));\n }\n else\n {\n return make_shared<EmbeddingSegmentsSum>(new_args.at(0),\n new_args.at(1),\n new_args.at(2),\n new_args.at(3),\n new_args.at(4),\n new_args.at(5));\n }\n}\n<commit_msg>Add more checks<commit_after>\/\/*****************************************************************************\n\/\/ Copyright 2017-2020 Intel Corporation\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#include \"ngraph\/op\/embedding_segments_sum.hpp\"\n#include \"ngraph\/op\/constant.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\nconstexpr NodeTypeInfo op::v3::EmbeddingSegmentsSum::type_info;\n\nop::v3::EmbeddingSegmentsSum::EmbeddingSegmentsSum(const Output<Node>& emb_table,\n const Output<Node>& indices,\n const Output<Node>& segment_ids,\n const Output<Node>& num_segments,\n const Output<Node>& per_sample_weights,\n const Output<Node>& default_index)\n : Op({emb_table, indices, segment_ids, num_segments, per_sample_weights, default_index})\n{\n constructor_validate_and_infer_types();\n}\n\nop::v3::EmbeddingSegmentsSum::EmbeddingSegmentsSum(const Output<Node>& emb_table,\n const Output<Node>& indices,\n const Output<Node>& segment_ids,\n const Output<Node>& num_segments,\n const Output<Node>& per_sample_weights)\n : Op({emb_table, indices, segment_ids, num_segments, per_sample_weights})\n{\n constructor_validate_and_infer_types();\n}\n\nop::v3::EmbeddingSegmentsSum::EmbeddingSegmentsSum(const Output<Node>& emb_table,\n const Output<Node>& indices,\n const Output<Node>& segment_ids,\n const Output<Node>& num_segments)\n : Op({emb_table, indices, segment_ids, num_segments})\n{\n constructor_validate_and_infer_types();\n}\n\nvoid op::v3::EmbeddingSegmentsSum::validate_and_infer_types()\n{\n enum\n {\n EMB_TABLE,\n INDICES,\n SEGMENT_IDS,\n NUM_SEGMENTS,\n PER_SAMPLE_WEIGHTS,\n DEFAULT_INDEX\n };\n\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(SEGMENT_IDS) == element::i64 ||\n get_input_element_type(SEGMENT_IDS) == element::i32,\n \"SEGMENT_IDS type must be i32 or i64\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(INDICES) == element::i64 ||\n get_input_element_type(INDICES) == element::i32,\n \"INDICES type must be i32 or i64\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(NUM_SEGMENTS) == element::i64 ||\n get_input_element_type(NUM_SEGMENTS) == element::i32,\n \"NUM_SEGMENTS type must be i32 or i64\");\n\n NODE_VALIDATION_CHECK(\n this,\n get_input_element_type(INDICES).compatible(get_input_element_type(SEGMENT_IDS)),\n \"Segment_ids element type (\",\n get_input_element_type(SEGMENT_IDS),\n \") must match indices element type (\",\n get_input_element_type(INDICES),\n \")\");\n\n NODE_VALIDATION_CHECK(\n this,\n get_input_element_type(SEGMENT_IDS).compatible(get_input_element_type(NUM_SEGMENTS)),\n \"Num_segments element type (\",\n get_input_element_type(NUM_SEGMENTS),\n \") must match Segment_ids element type (\",\n get_input_element_type(SEGMENT_IDS),\n \")\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(INDICES).is_dynamic() ||\n get_input_partial_shape(INDICES).to_shape().size() == 1,\n \"INDICES must be 1D\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(SEGMENT_IDS).is_dynamic() ||\n get_input_partial_shape(SEGMENT_IDS).to_shape().size() == 1,\n \"SEGMENT_IDS must be 1D\");\n\n NODE_VALIDATION_CHECK(\n this,\n get_input_partial_shape(INDICES).compatible(get_input_partial_shape(SEGMENT_IDS)),\n \"INDICES and SEGMENT_IDS shape must be same\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(NUM_SEGMENTS).compatible(PartialShape{}),\n \"NUM_SEGMENTS must be a scalar\");\n\n if (get_input_size() >= 5)\n {\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(EMB_TABLE).compatible(\n get_input_element_type(PER_SAMPLE_WEIGHTS)),\n \"Per sample weight element type (\",\n get_input_element_type(PER_SAMPLE_WEIGHTS),\n \") must match embedding table element type (\",\n get_input_element_type(EMB_TABLE),\n \")\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(PER_SAMPLE_WEIGHTS).is_dynamic() ||\n get_input_partial_shape(PER_SAMPLE_WEIGHTS).to_shape().size() ==\n 1,\n \"PER_SAMPLE_WEIGHTS must be 1D\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(INDICES).compatible(\n get_input_partial_shape(PER_SAMPLE_WEIGHTS)),\n \"INDICES and PER_SAMPLE_WEIGHTS shape must be same\");\n }\n\n if (get_input_size() == 6)\n {\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(DEFAULT_INDEX) == element::i64 ||\n get_input_element_type(DEFAULT_INDEX) == element::i32,\n \"DEFAULT_INDEX type must be i32 or i64\");\n\n NODE_VALIDATION_CHECK(\n this,\n get_input_element_type(INDICES).compatible(get_input_element_type(DEFAULT_INDEX)),\n \"Default_index element type (\",\n get_input_element_type(DEFAULT_INDEX),\n \") must match indices element type (\",\n get_input_element_type(INDICES),\n \")\");\n\n NODE_VALIDATION_CHECK(this,\n get_input_partial_shape(DEFAULT_INDEX).compatible(PartialShape{}),\n \"DEFAULT_INDEX must be a scalar\");\n }\n\n element::Type result_et = get_input_element_type(EMB_TABLE);\n\n const PartialShape& emb_table_shape = get_input_partial_shape(EMB_TABLE);\n\n PartialShape result_shape;\n if (emb_table_shape.rank().is_static())\n {\n std::vector<Dimension> result_dims(emb_table_shape.rank().get_length());\n result_dims[0] = Dimension::dynamic();\n for (size_t i = 1; i < emb_table_shape.rank().get_length(); i++)\n {\n result_dims[i] = emb_table_shape[i];\n }\n\n result_shape = PartialShape(result_dims);\n }\n else\n {\n result_shape = PartialShape::dynamic();\n }\n\n set_input_is_relevant_to_shape(NUM_SEGMENTS);\n set_output_type(0, result_et, result_shape);\n}\n\nshared_ptr<Node>\n op::v3::EmbeddingSegmentsSum::clone_with_new_inputs(const OutputVector& new_args) const\n{\n check_new_args_count(this, new_args);\n if (new_args.size() == 4)\n {\n return make_shared<EmbeddingSegmentsSum>(\n new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3));\n }\n else if (new_args.size() == 5)\n {\n return make_shared<EmbeddingSegmentsSum>(\n new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3), new_args.at(4));\n }\n else if (new_args.size() == 6)\n {\n return make_shared<EmbeddingSegmentsSum>(new_args.at(0),\n new_args.at(1),\n new_args.at(2),\n new_args.at(3),\n new_args.at(4),\n new_args.at(5));\n }\n else\n {\n throw ngraph_error(\"Incorrect number of arguments\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- tsan_string.cc ----------------------------------------------------===\/\/\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\/\/ This file is a part of ThreadSanitizer (TSan), a race detector.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"tsan_test_util.h\"\n#include \"gtest\/gtest.h\"\n#include <string.h>\n\nnamespace __tsan {\n\nTEST(ThreadSanitizer, Memcpy) {\n char data0[7] = {1, 2, 3, 4, 5, 6, 7};\n char data[7] = {42, 42, 42, 42, 42, 42, 42};\n MainThread().Memcpy(data+1, data0+1, 5);\n EXPECT_EQ(data[0], 42);\n EXPECT_EQ(data[1], 2);\n EXPECT_EQ(data[2], 3);\n EXPECT_EQ(data[3], 4);\n EXPECT_EQ(data[4], 5);\n EXPECT_EQ(data[5], 6);\n EXPECT_EQ(data[6], 42);\n MainThread().Memset(data+1, 13, 5);\n EXPECT_EQ(data[0], 42);\n EXPECT_EQ(data[1], 13);\n EXPECT_EQ(data[2], 13);\n EXPECT_EQ(data[3], 13);\n EXPECT_EQ(data[4], 13);\n EXPECT_EQ(data[5], 13);\n EXPECT_EQ(data[6], 42);\n}\n\nTEST(ThreadSanitizer, MemcpyRace1) {\n char *data = new char[10];\n char *data1 = new char[10];\n char *data2 = new char[10];\n ScopedThread t1, t2;\n t1.Memcpy(data, data1, 10);\n t2.Memcpy(data, data2, 10, true);\n}\n\nTEST(ThreadSanitizer, MemcpyRace2) {\n char *data = new char[10];\n char *data1 = new char[10];\n char *data2 = new char[10];\n ScopedThread t1, t2;\n t1.Memcpy(data+5, data1, 1);\n t2.Memcpy(data+3, data2, 4, true);\n}\n\nTEST(ThreadSanitizer, MemcpyRace3) {\n char *data = new char[10];\n char *data1 = new char[10];\n char *data2 = new char[10];\n ScopedThread t1, t2;\n t1.Memcpy(data, data1, 10);\n t2.Memcpy(data1, data2, 10, true);\n}\n\nTEST(ThreadSanitizer, MemcpyStack) {\n char *data = new char[10];\n char *data1 = new char[10];\n ScopedThread t1, t2;\n t1.Memcpy(data, data1, 10);\n t2.Memcpy(data, data1, 10, true);\n}\n\nTEST(ThreadSanitizer, MemsetRace1) {\n char *data = new char[10];\n ScopedThread t1, t2;\n t1.Memset(data, 1, 10);\n t2.Memset(data, 2, 10, true);\n}\n\n} \/\/ namespace __tsan\n<commit_msg>tsan: exclude flaky test<commit_after>\/\/===-- tsan_string.cc ----------------------------------------------------===\/\/\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\/\/ This file is a part of ThreadSanitizer (TSan), a race detector.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"tsan_test_util.h\"\n#include \"gtest\/gtest.h\"\n#include <string.h>\n\nnamespace __tsan {\n\nTEST(ThreadSanitizer, Memcpy) {\n char data0[7] = {1, 2, 3, 4, 5, 6, 7};\n char data[7] = {42, 42, 42, 42, 42, 42, 42};\n MainThread().Memcpy(data+1, data0+1, 5);\n EXPECT_EQ(data[0], 42);\n EXPECT_EQ(data[1], 2);\n EXPECT_EQ(data[2], 3);\n EXPECT_EQ(data[3], 4);\n EXPECT_EQ(data[4], 5);\n EXPECT_EQ(data[5], 6);\n EXPECT_EQ(data[6], 42);\n MainThread().Memset(data+1, 13, 5);\n EXPECT_EQ(data[0], 42);\n EXPECT_EQ(data[1], 13);\n EXPECT_EQ(data[2], 13);\n EXPECT_EQ(data[3], 13);\n EXPECT_EQ(data[4], 13);\n EXPECT_EQ(data[5], 13);\n EXPECT_EQ(data[6], 42);\n}\n\nTEST(ThreadSanitizer, MemcpyRace1) {\n char *data = new char[10];\n char *data1 = new char[10];\n char *data2 = new char[10];\n ScopedThread t1, t2;\n t1.Memcpy(data, data1, 10);\n t2.Memcpy(data, data2, 10, true);\n}\n\n\/\/ The test fails with TSAN_SHADOW_COUNT=2,\n\/\/ because the old racy access is evicted.\n#if defined(TSAN_SHADOW_COUNT) && TSAN_SHADOW_COUNT >= 4\nTEST(ThreadSanitizer, MemcpyRace2) {\n char *data = new char[10];\n char *data1 = new char[10];\n char *data2 = new char[10];\n ScopedThread t1, t2;\n t1.Memcpy(data+5, data1, 1);\n t2.Memcpy(data+3, data2, 4, true);\n}\n#endif\n\nTEST(ThreadSanitizer, MemcpyRace3) {\n char *data = new char[10];\n char *data1 = new char[10];\n char *data2 = new char[10];\n ScopedThread t1, t2;\n t1.Memcpy(data, data1, 10);\n t2.Memcpy(data1, data2, 10, true);\n}\n\nTEST(ThreadSanitizer, MemcpyStack) {\n char *data = new char[10];\n char *data1 = new char[10];\n ScopedThread t1, t2;\n t1.Memcpy(data, data1, 10);\n t2.Memcpy(data, data1, 10, true);\n}\n\nTEST(ThreadSanitizer, MemsetRace1) {\n char *data = new char[10];\n ScopedThread t1, t2;\n t1.Memset(data, 1, 10);\n t2.Memset(data, 2, 10, true);\n}\n\n} \/\/ namespace __tsan\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2017 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_CONFIG_OPTION_HPP\n#define CAF_CONFIG_OPTION_HPP\n\n#include <memory>\n#include <string>\n#include <vector>\n#include <cstdint>\n#include <cstring>\n#include <functional>\n\n#include \"caf\/atom.hpp\"\n#include \"caf\/error.hpp\"\n#include \"caf\/message.hpp\"\n#include \"caf\/variant.hpp\"\n#include \"caf\/config_value.hpp\"\n#include \"caf\/deep_to_string.hpp\"\n#include \"caf\/static_visitor.hpp\"\n\n#include \"caf\/detail\/type_traits.hpp\"\n\nnamespace caf {\n\nextern const char* type_name_visitor_tbl[];\n\n\/\/\/ Helper class to generate config readers for different input types.\nclass config_option {\npublic:\n using config_reader_sink = std::function<void (size_t, config_value&,\n optional<std::ostream&>)>;\n\n using legal_types = detail::type_list<bool, float, double, std::string, \n atom_value, int8_t, uint8_t, int16_t, \n uint16_t, int32_t, uint32_t, int64_t, \n uint64_t>;\n\n config_option(const char* cat, const char* nm, const char* expl);\n\n virtual ~config_option();\n\n inline const char* name() const {\n return name_.c_str();\n }\n\n inline char short_name() const {\n return short_name_;\n }\n\n inline const char* category() const {\n return category_;\n }\n\n inline const char* explanation() const {\n return explanation_;\n }\n\n \/\/\/ Returns the full name for this config option as \"<category>.<long name>\".\n std::string full_name() const;\n\n \/\/\/ Returns the held value as string.\n virtual std::string to_string() const = 0;\n\n \/\/\/ Returns a sink function for config readers.\n virtual config_reader_sink to_sink() = 0;\n\n \/\/\/ Returns a CLI argument parser.\n virtual message::cli_arg to_cli_arg(bool use_caf_prefix = false) = 0;\n\n \/\/\/ Returns a human-readable type name for the visited type.\n class type_name_visitor : public static_visitor<const char*> {\n public:\n template <class T>\n const char* operator()(const T&) const {\n static constexpr bool is_int = std::is_integral<T>::value \n && !std::is_same<bool, T>::value;\n static constexpr std::integral_constant<bool, is_int> tk{};\n static constexpr int index = idx<T>(tk);\n static_assert(index >= 0, \"illegal type in name visitor\");\n return type_name_visitor_tbl[static_cast<size_t>(index)];\n }\n\n private:\n template <class T>\n static constexpr int idx(std::false_type \/* is_integer *\/) {\n return detail::tl_index_of<legal_types, T>::value;\n }\n\n template <class T>\n static constexpr int idx(std::true_type \/* is_integer *\/) {\n using squashed = detail::squashed_int_t<T>;\n return detail::tl_index_of<legal_types, squashed>::value;\n }\n };\n\nprotected:\n template <class T, class U>\n static bool assign_config_value(T& x, U& y) {\n x = std::move(y);\n return true;\n }\n\n template <class T>\n static bool assign_config_value(T& x, int64_t& y) {\n if (y < static_cast<int64_t>(std::numeric_limits<T>::lowest()) \n || y > static_cast<int64_t>(std::numeric_limits<T>::max())) \n return false;\n x = static_cast<T>(y);\n return true;\n }\n\n static bool assign_config_value(uint64_t& x, int64_t& y) {\n if (y < 0)\n return false;\n x = static_cast<uint64_t>(y);\n return true;\n }\n\n static bool assign_config_value(float& x, double& y) {\n if (y < static_cast<double>(std::numeric_limits<float>::lowest()) \n || y > static_cast<double>(std::numeric_limits<float>::max()))\n return false;\n x = static_cast<float>(y);\n return true;\n }\n\n void report_type_error(size_t ln, config_value& x, const char* expected,\n optional<std::ostream&> out);\n\nprivate:\n const char* category_;\n std::string name_;\n const char* explanation_;\n char short_name_;\n};\n\ntemplate <class T, bool IsInsertable = detail::can_insert_elements<T>()\n && !std::is_same<T, std::string>::value>\nclass config_option_impl : public config_option {\npublic:\n config_option_impl(T& ref, const char* ctg, const char* nm, const char* xp)\n : config_option(ctg, nm, xp),\n ref_(ref) {\n \/\/ nop\n }\n\n std::string to_string() const override {\n return deep_to_string(ref_);\n }\n\n message::cli_arg to_cli_arg(bool use_caf_prefix) override {\n std::string argname;\n if (use_caf_prefix)\n argname = \"caf#\";\n if (strcmp(category(), \"global\") != 0) {\n argname += category();\n argname += \".\";\n }\n argname += name();\n if (short_name() != '\\0') {\n argname += ',';\n argname += short_name();\n }\n return {std::move(argname), explanation(), ref_};\n }\n\n config_reader_sink to_sink() override {\n return [=](size_t ln, config_value& x, optional<std::ostream&> errors) {\n \/\/ the INI parser accepts all integers as int64_t\n \/\/ and all floating point numbers as doubles\n using cfg_type =\n typename std::conditional<\n std::is_integral<T>::value && !std::is_same<bool, T>::value,\n int64_t,\n typename std::conditional<\n std::is_floating_point<T>::value,\n double,\n T \n >::type\n >::type;\n if (get<cfg_type>(&x) && assign_config_value(ref_, get<cfg_type>(x)))\n return;\n type_name_visitor tnv;\n report_type_error(ln, x, tnv(ref_), errors);\n };\n }\n\nprivate:\n T& ref_;\n};\n\ntemplate <class T>\nclass config_option_impl<T, true> : public config_option {\npublic:\n using value_type = typename T::value_type;\n\n config_option_impl(T& ref, const char* ctg, const char* nm, const char* xp)\n : config_option(ctg, nm, xp),\n ref_(ref) {\n \/\/ nop\n }\n\n std::string to_string() const override {\n return deep_to_string(ref_);\n }\n\n message::cli_arg to_cli_arg(bool use_caf_prefix) override {\n std::string argname;\n if (use_caf_prefix)\n argname = \"caf#\";\n if (strcmp(category(), \"global\") != 0) {\n argname += category();\n argname += \".\";\n }\n argname += name();\n if (short_name() != '\\0') {\n argname += ',';\n argname += short_name();\n }\n return {std::move(argname), explanation(), ref_};\n }\n\n config_reader_sink to_sink() override {\n return [=](size_t ln, config_value& x, optional<std::ostream&> errors) {\n \/\/ the INI parser accepts all integers as int64_t\n \/\/ and all floating point numbers as doubles\n using cfg_type =\n typename std::conditional<\n std::is_integral<value_type>::value && \n !std::is_same<bool, value_type>::value,\n int64_t,\n typename std::conditional<\n std::is_floating_point<value_type>::value,\n double,\n value_type \n >::type\n >::type;\n value_type tmp;\n if (get<cfg_type>(&x) && assign_config_value(tmp, get<cfg_type>(x))) {\n ref_.insert(ref_.end(), std::move(tmp));\n return;\n }\n type_name_visitor tnv;\n report_type_error(ln, x, tnv(tmp), errors);\n };\n }\n\nprivate:\n T& ref_;\n};\n\n\ntemplate <class T>\nstd::unique_ptr<config_option>\nmake_config_option(T& storage, const char* category,\n const char* name, const char* explanation) {\n auto ptr = new config_option_impl<T>(storage, category, name, explanation);\n return std::unique_ptr<config_option>{ptr};\n}\n\n} \/\/ namespace caf\n\n#endif \/\/ CAF_CONFIG_OPTION_HPP\n<commit_msg>Fix parsing of size_t config options<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2017 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_CONFIG_OPTION_HPP\n#define CAF_CONFIG_OPTION_HPP\n\n#include <memory>\n#include <string>\n#include <vector>\n#include <cstdint>\n#include <cstring>\n#include <functional>\n\n#include \"caf\/atom.hpp\"\n#include \"caf\/error.hpp\"\n#include \"caf\/message.hpp\"\n#include \"caf\/variant.hpp\"\n#include \"caf\/config_value.hpp\"\n#include \"caf\/deep_to_string.hpp\"\n#include \"caf\/static_visitor.hpp\"\n\n#include \"caf\/detail\/type_traits.hpp\"\n\nnamespace caf {\n\nextern const char* type_name_visitor_tbl[];\n\n\/\/\/ Helper class to generate config readers for different input types.\nclass config_option {\npublic:\n using config_reader_sink = std::function<void (size_t, config_value&,\n optional<std::ostream&>)>;\n\n using legal_types = detail::type_list<bool, float, double, std::string,\n atom_value, int8_t, uint8_t, int16_t,\n uint16_t, int32_t, uint32_t, int64_t,\n uint64_t>;\n\n config_option(const char* cat, const char* nm, const char* expl);\n\n virtual ~config_option();\n\n inline const char* name() const {\n return name_.c_str();\n }\n\n inline char short_name() const {\n return short_name_;\n }\n\n inline const char* category() const {\n return category_;\n }\n\n inline const char* explanation() const {\n return explanation_;\n }\n\n \/\/\/ Returns the full name for this config option as \"<category>.<long name>\".\n std::string full_name() const;\n\n \/\/\/ Returns the held value as string.\n virtual std::string to_string() const = 0;\n\n \/\/\/ Returns a sink function for config readers.\n virtual config_reader_sink to_sink() = 0;\n\n \/\/\/ Returns a CLI argument parser.\n virtual message::cli_arg to_cli_arg(bool use_caf_prefix = false) = 0;\n\n \/\/\/ Returns a human-readable type name for the visited type.\n class type_name_visitor : public static_visitor<const char*> {\n public:\n template <class T>\n const char* operator()(const T&) const {\n static constexpr bool is_int = std::is_integral<T>::value\n && !std::is_same<bool, T>::value;\n static constexpr std::integral_constant<bool, is_int> tk{};\n static constexpr int index = idx<T>(tk);\n static_assert(index >= 0, \"illegal type in name visitor\");\n return type_name_visitor_tbl[static_cast<size_t>(index)];\n }\n\n private:\n \/\/ Catches non-integer types.\n template <class T>\n static constexpr int idx(std::false_type) {\n return detail::tl_index_of<legal_types, T>::value;\n }\n\n \/\/ Catches integer types.\n template <class T>\n static constexpr int idx(std::true_type) {\n using squashed = detail::squashed_int_t<T>;\n return detail::tl_index_of<legal_types, squashed>::value;\n }\n };\n\nprotected:\n template <class T, class U>\n static bool assign_config_value(T& x, U& y) {\n x = std::move(y);\n return true;\n }\n\n \/\/ Catches any integer type that is smaller than int64_t.\n template <class T>\n static typename std::enable_if<sizeof(T) < sizeof(int64_t), bool>::type\n assign_config_value(T& x, int64_t& y) {\n if (y < static_cast<int64_t>(std::numeric_limits<T>::lowest())\n || y > static_cast<int64_t>(std::numeric_limits<T>::max()))\n return false;\n x = static_cast<T>(y);\n return true;\n }\n\n \/\/ Catches size_t and uint64_t (yes, they differ on some compilers).\n template <class T>\n static typename std::enable_if<std::is_unsigned<T>::value\n && sizeof(T) == sizeof(int64_t), bool>::type\n assign_config_value(T& x, int64_t& y) {\n if (y < 0)\n return false;\n x = static_cast<uint64_t>(y);\n return true;\n }\n\n static bool assign_config_value(float& x, double& y) {\n if (y < static_cast<double>(std::numeric_limits<float>::lowest())\n || y > static_cast<double>(std::numeric_limits<float>::max()))\n return false;\n x = static_cast<float>(y);\n return true;\n }\n\n void report_type_error(size_t ln, config_value& x, const char* expected,\n optional<std::ostream&> out);\n\nprivate:\n const char* category_;\n std::string name_;\n const char* explanation_;\n char short_name_;\n};\n\ntemplate <class T,\n bool IsInsertable = detail::can_insert_elements<T>()\n && !std::is_same<T, std::string>::value>\nclass config_option_impl : public config_option {\npublic:\n config_option_impl(T& ref, const char* ctg, const char* nm, const char* xp)\n : config_option(ctg, nm, xp),\n ref_(ref) {\n \/\/ nop\n }\n\n std::string to_string() const override {\n return deep_to_string(ref_);\n }\n\n message::cli_arg to_cli_arg(bool use_caf_prefix) override {\n std::string argname;\n if (use_caf_prefix)\n argname = \"caf#\";\n if (strcmp(category(), \"global\") != 0) {\n argname += category();\n argname += \".\";\n }\n argname += name();\n if (short_name() != '\\0') {\n argname += ',';\n argname += short_name();\n }\n return {std::move(argname), explanation(), ref_};\n }\n\n config_reader_sink to_sink() override {\n return [=](size_t ln, config_value& x, optional<std::ostream&> errors) {\n \/\/ the INI parser accepts all integers as int64_t\n \/\/ and all floating point numbers as doubles\n using cfg_type =\n typename std::conditional<\n std::is_integral<T>::value && !std::is_same<bool, T>::value,\n int64_t,\n typename std::conditional<\n std::is_floating_point<T>::value,\n double,\n T\n >::type\n >::type;\n if (get<cfg_type>(&x) && assign_config_value(ref_, get<cfg_type>(x)))\n return;\n type_name_visitor tnv;\n report_type_error(ln, x, tnv(ref_), errors);\n };\n }\n\nprivate:\n T& ref_;\n};\n\ntemplate <class T>\nclass config_option_impl<T, true> : public config_option {\npublic:\n using value_type = typename T::value_type;\n\n config_option_impl(T& ref, const char* ctg, const char* nm, const char* xp)\n : config_option(ctg, nm, xp),\n ref_(ref) {\n \/\/ nop\n }\n\n std::string to_string() const override {\n return deep_to_string(ref_);\n }\n\n message::cli_arg to_cli_arg(bool use_caf_prefix) override {\n std::string argname;\n if (use_caf_prefix)\n argname = \"caf#\";\n if (strcmp(category(), \"global\") != 0) {\n argname += category();\n argname += \".\";\n }\n argname += name();\n if (short_name() != '\\0') {\n argname += ',';\n argname += short_name();\n }\n return {std::move(argname), explanation(), ref_};\n }\n\n config_reader_sink to_sink() override {\n return [=](size_t ln, config_value& x, optional<std::ostream&> errors) {\n \/\/ the INI parser accepts all integers as int64_t\n \/\/ and all floating point numbers as doubles\n using cfg_type =\n typename std::conditional<\n std::is_integral<value_type>::value && \n !std::is_same<bool, value_type>::value,\n int64_t,\n typename std::conditional<\n std::is_floating_point<value_type>::value,\n double,\n value_type \n >::type\n >::type;\n value_type tmp;\n if (get<cfg_type>(&x) && assign_config_value(tmp, get<cfg_type>(x))) {\n ref_.insert(ref_.end(), std::move(tmp));\n return;\n }\n type_name_visitor tnv;\n report_type_error(ln, x, tnv(tmp), errors);\n };\n }\n\nprivate:\n T& ref_;\n};\n\n\ntemplate <class T>\nstd::unique_ptr<config_option>\nmake_config_option(T& storage, const char* category,\n const char* name, const char* explanation) {\n auto ptr = new config_option_impl<T>(storage, category, name, explanation);\n return std::unique_ptr<config_option>{ptr};\n}\n\n} \/\/ namespace caf\n\n#endif \/\/ CAF_CONFIG_OPTION_HPP\n<|endoftext|>"} {"text":"<commit_before>\/* \n MPL3115A2 Barometric Pressure Sensor Library\n By: Nathan Seidle\n SparkFun Electronics\n Date: September 24th, 2013\n License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).\n \n Get pressure, altitude and temperature from the MPL3115A2 sensor.\n \n September 6, 2016: Modified for use in OpenROV's Software \n\n*\/\n\n#include <Arduino.h>\n#include <CI2C.h>\n\n#include \"MPL3115A2.h\"\n\nusing namespace mpl3115a2;\n\n\nMPL3115A2::MPL3115A2( CI2C *i2cInterfaceIn )\n : m_i2cAddress( mpl3115a2::MPL3115A2_ADDRESS )\n , m_pI2C( i2cInterfaceIn )\n{\n\n}\n\nERetCode MPL3115A2::Initialize() \n{\n m_isInitialized = false;\n\n delay( 500 );\n\n \/\/Verify that the sensor is up and running\n if( VerifyChipId() != ERetCode::SUCCESS )\n {\n \/\/We were unable to verify this sensor\n return ERetCode::FAILED;\n }\n\n m_isInitialized = true;\n return ERetCode::SUCCESS; \n}\n\nERetCode MPL3115A2::SetMode( EMode modeIn )\n{\n switch (modeIn)\n {\n case EMode::BAROMETER:\n {\n return SetModeBarometer();\n }\n case EMode::ALTIMETER:\n {\n return SetModeAltimeter();\n }\n case EMode::STANDBY:\n {\n return SetModeStandby();\n }\n case EMode::ACTIVE:\n {\n return SetModeActive();\n }\n default:\n {\n return ERetCode::FAILED;\n }\n }\n}\n\n\/\/Call with a rate from 0 to 7. See page 33 for table of ratios.\n\/\/Sets the over sample rate. Datasheet calls for 128 but you can set it \n\/\/from 1 to 128 samples. The higher the oversample rate the greater\n\/\/the time between data samples.\nERetCode MPL3115A2::SetOversampleRatio( EOversampleRatio osrIn )\n{\n int32_t returnCode;\n auto sampleRate = static_cast<int>( osrIn );\n\n \/\/Align it for the control register\n sampleRate <<= 3;\n\n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Clear out old Oversample bits\n tempSetting &= B11000111;\n\n \/\/Mask new sample rate\n tempSetting |= sampleRate;\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n \n return ERetCode::SUCCESS;\n}\n\n\/\/Enables the pressure and temp measurement event flags so that we can\n\/\/test against them. This is recommended in datasheet during setup.\nERetCode MPL3115A2::EnableEventFlags()\n{\n \/\/ Enable all three pressure and temp event flags \n auto ret = WriteByte( MPL3115A2_REGISTER::PT_DATA_CFG, 0x07);\n if( ret != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n \n return ERetCode::SUCCESS;\n}\n\n\/\/Reads the current pressure in Pa\n\/\/Unit must be set in barometric pressure mode\nERetCode MPL3115A2::ReadPressure( float& pressureOut )\n{\n int32_t retCode;\n \/\/Serial.println(\"In pressure loop\");\n\n \/\/Check the PDR bit to see if we need to toggle oneshot\n uint8_t status;\n\n retCode = ReadByte( MPL3115A2_REGISTER::STATUS, status );\n if( retCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n \n if( ( status & (1<<2) ) == 0 )\n {\n \/\/Serial.println( \"HAVE TO TOGGLE ONESHOT\" );\n ToggleOneShot();\n }\n\n \/\/Wait for PDR bit \n int counter = 0;\n retCode = ReadByte( MPL3115A2_REGISTER::STATUS, status );\n if( retCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n while( ( status & (1<<2) ) == 0 )\n {\n \/\/Check that bit again, duh\n retCode = ReadByte( MPL3115A2_REGISTER::STATUS, status );\n if( retCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n if( ++counter > 600 )\n {\n return ERetCode::TIMED_OUT;\n }\n }\n\n return ERetCode::SUCCESS;\n}\n\n\n\n\/***************************************************************************\n PRIVATE FUNCTIONS\n ***************************************************************************\/\n\nERetCode MPL3115A2::VerifyChipId()\n{\n \/\/Read the chip id\n uint8_t id;\n\n auto ret = ReadByte( MPL3115A2_REGISTER::WHO_AM_I, id );\n\n if( ret != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Check to see if it matches the proper ID (0xC4)\n if( id != 0xC4 )\n {\n return ERetCode::FAILED;\n }\n\n return ERetCode::SUCCESS;\n}\n\nERetCode MPL3115A2::SetModeBarometer()\n{\n int32_t returnCode;\n \n \/\/Read the current settings\n uint8_t setting;\n\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, setting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Clear the altimeter bit\n setting &= ~(1<<7);\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, setting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n return ERetCode::SUCCESS;\n}\n\nERetCode MPL3115A2::SetModeAltimeter()\n{\n int32_t returnCode;\n \n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Set the altimeter bit\n tempSetting |= (1<<7);\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n return ERetCode::SUCCESS;\n}\n\n\/\/Puts the sensor in standby mode\n\/\/This is needed so that we can modify the major control registers\nERetCode MPL3115A2::SetModeStandby()\n{\n int32_t returnCode;\n \n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Clear SBYB bit for Standby mode\n tempSetting &= ~(1<<0);\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n return ERetCode::SUCCESS; \n}\n\n\/\/Puts the sensor in active mode\n\/\/This is needed so that we can modify the major control registers\nERetCode MPL3115A2::SetModeActive()\n{\n int32_t returnCode;\n \n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Set SBYB bit for Active mode\n tempSetting |= (1<<0);\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n return ERetCode::SUCCESS;\n}\n\n\/\/Clears and then sets the OST bit which causes the sensor to take another readings\n\/\/Needed to sample faster than 1Hz\nERetCode MPL3115A2::ToggleOneShot()\n{\n Serial.println( \"Toggling one shot.\" );\n int32_t returnCode;\n\n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED_ONESHOT;\n }\n \n \/\/Clear the one shot bit\n tempSetting &= ~(1<<1);\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED_ONESHOT;\n }\n\n \/\/Reat the current settings, just to be safe :)\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED_ONESHOT;\n }\n\n \/\/Set the overshot bit\n tempSetting |= (1<<1);\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED_ONESHOT;\n }\n\n return ERetCode::SUCCESS; \n}\n\nint32_t MPL3115A2::WriteByte( MPL3115A2_REGISTER addressIn, uint8_t dataIn )\n{\n\treturn (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn );\n}\n\nint32_t MPL3115A2::ReadByte( MPL3115A2_REGISTER addressIn, uint8_t &dataOut )\n{\n\treturn (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut );\n}\nint32_t MPL3115A2::ReadNBytes( MPL3115A2_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn )\n{\n return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn );\n}<commit_msg>Need to make sure it sets the correct bit<commit_after>\/* \n MPL3115A2 Barometric Pressure Sensor Library\n By: Nathan Seidle\n SparkFun Electronics\n Date: September 24th, 2013\n License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).\n \n Get pressure, altitude and temperature from the MPL3115A2 sensor.\n \n September 6, 2016: Modified for use in OpenROV's Software \n\n*\/\n\n#include <Arduino.h>\n#include <CI2C.h>\n\n#include \"MPL3115A2.h\"\n\nusing namespace mpl3115a2;\n\n\nMPL3115A2::MPL3115A2( CI2C *i2cInterfaceIn )\n : m_i2cAddress( mpl3115a2::MPL3115A2_ADDRESS )\n , m_pI2C( i2cInterfaceIn )\n{\n\n}\n\nERetCode MPL3115A2::Initialize() \n{\n m_isInitialized = false;\n\n delay( 500 );\n\n \/\/Verify that the sensor is up and running\n if( VerifyChipId() != ERetCode::SUCCESS )\n {\n \/\/We were unable to verify this sensor\n return ERetCode::FAILED;\n }\n\n m_isInitialized = true;\n return ERetCode::SUCCESS; \n}\n\nERetCode MPL3115A2::SetMode( EMode modeIn )\n{\n switch (modeIn)\n {\n case EMode::BAROMETER:\n {\n return SetModeBarometer();\n }\n case EMode::ALTIMETER:\n {\n return SetModeAltimeter();\n }\n case EMode::STANDBY:\n {\n return SetModeStandby();\n }\n case EMode::ACTIVE:\n {\n return SetModeActive();\n }\n default:\n {\n return ERetCode::FAILED;\n }\n }\n}\n\n\/\/Call with a rate from 0 to 7. See page 33 for table of ratios.\n\/\/Sets the over sample rate. Datasheet calls for 128 but you can set it \n\/\/from 1 to 128 samples. The higher the oversample rate the greater\n\/\/the time between data samples.\nERetCode MPL3115A2::SetOversampleRatio( EOversampleRatio osrIn )\n{\n int32_t returnCode;\n auto sampleRate = static_cast<int>( osrIn );\n\n \/\/Align it for the control register\n sampleRate <<= 3;\n\n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Clear out old Oversample bits\n tempSetting &= B11000111;\n\n \/\/Mask new sample rate\n tempSetting |= sampleRate;\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n \n return ERetCode::SUCCESS;\n}\n\n\/\/Enables the pressure and temp measurement event flags so that we can\n\/\/test against them. This is recommended in datasheet during setup.\nERetCode MPL3115A2::EnableEventFlags()\n{\n \/\/ Enable all three pressure and temp event flags \n auto ret = WriteByte( MPL3115A2_REGISTER::PT_DATA_CFG, 0x07);\n if( ret != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n \n return ERetCode::SUCCESS;\n}\n\n\/\/Reads the current pressure in Pa\n\/\/Unit must be set in barometric pressure mode\nERetCode MPL3115A2::ReadPressure( float& pressureOut )\n{\n int32_t retCode;\n \/\/Serial.println(\"In pressure loop\");\n\n \/\/Check the PDR bit to see if we need to toggle oneshot\n uint8_t status;\n\n retCode = ReadByte( MPL3115A2_REGISTER::STATUS, status );\n if( retCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n Serial.println(status, HEX);\n\n\n return ERetCode::SUCCESS;\n}\n\nERetCode MPL3115A2::SetModeAltimeter()\n{\n int32_t returnCode;\n \n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Set the altimeter bit\n tempSetting |= (1<<7);\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n return ERetCode::SUCCESS;\n}\n\n\/\/Puts the sensor in standby mode\n\/\/This is needed so that we can modify the major control registers\nERetCode MPL3115A2::SetModeStandby()\n{\n int32_t returnCode;\n \n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Clear SBYB bit for Standby mode\n tempSetting &= ~(1<<0);\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n return ERetCode::SUCCESS; \n}\n\n\/\/Puts the sensor in active mode\n\/\/This is needed so that we can modify the major control registers\nERetCode MPL3115A2::SetModeActive()\n{\n int32_t returnCode;\n \n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n \/\/Set SBYB bit for Active mode\n tempSetting |= (1<<0);\n\n \/\/And write it to the register\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED;\n }\n\n return ERetCode::SUCCESS;\n}\n\n\/\/Clears and then sets the OST bit which causes the sensor to take another readings\n\/\/Needed to sample faster than 1Hz\nERetCode MPL3115A2::ToggleOneShot()\n{\n Serial.println( \"Toggling one shot.\" );\n int32_t returnCode;\n\n \/\/Read the current settings\n uint8_t tempSetting;\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED_ONESHOT;\n }\n \n \/\/Clear the one shot bit\n tempSetting &= ~(1<<1);\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED_ONESHOT;\n }\n\n \/\/Reat the current settings, just to be safe :)\n returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED_ONESHOT;\n }\n\n \/\/Set the overshot bit\n tempSetting |= (1<<1);\n returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );\n if( returnCode != I2C::ERetCode::SUCCESS )\n {\n return ERetCode::FAILED_ONESHOT;\n }\n\n return ERetCode::SUCCESS; \n}\n\nint32_t MPL3115A2::WriteByte( MPL3115A2_REGISTER addressIn, uint8_t dataIn )\n{\n\treturn (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn );\n}\n\nint32_t MPL3115A2::ReadByte( MPL3115A2_REGISTER addressIn, uint8_t &dataOut )\n{\n\treturn (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut );\n}\nint32_t MPL3115A2::ReadNBytes( MPL3115A2_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn )\n{\n return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn );\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Any modified source or binaries are used only with the BitShares network.\n *\n * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *\n * 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <graphene\/chain\/database.hpp>\n\n#include <graphene\/chain\/operation_history_object.hpp>\n#include <graphene\/chain\/protocol\/fee_schedule.hpp>\n\n#include <fc\/io\/fstream.hpp>\n\n#include <fstream>\n#include <functional>\n#include <iostream>\n\nnamespace graphene { namespace chain {\n\ndatabase::database()\n{\n initialize_indexes();\n initialize_evaluators();\n}\n\ndatabase::~database()\n{\n clear_pending();\n}\n\nvoid database::reindex(fc::path data_dir, const genesis_state_type& initial_allocation)\n{ try {\n ilog( \"reindexing blockchain\" );\n wipe(data_dir, false);\n open(data_dir, [&initial_allocation]{return initial_allocation;});\n\n auto start = fc::time_point::now();\n auto last_block = _block_id_to_block.last();\n if( !last_block ) {\n elog( \"!no last block\" );\n edump((last_block));\n return;\n }\n\n const auto last_block_num = last_block->block_num();\n\n ilog( \"Replaying blocks...\" );\n _undo_db.disable();\n for( uint32_t i = 1; i <= last_block_num; ++i )\n {\n if( i % 2000 == 0 ) std::cerr << \" \" << double(i*100)\/last_block_num << \"% \"<<i << \" of \" <<last_block_num<<\" \\n\";\n fc::optional< signed_block > block = _block_id_to_block.fetch_by_number(i);\n if( !block.valid() )\n {\n wlog( \"Reindexing terminated due to gap: Block ${i} does not exist!\", (\"i\", i) );\n uint32_t dropped_count = 0;\n while( true )\n {\n fc::optional< block_id_type > last_id = _block_id_to_block.last_id();\n \/\/ this can trigger if we attempt to e.g. read a file that has block #2 but no block #1\n if( !last_id.valid() )\n break;\n \/\/ we've caught up to the gap\n if( block_header::num_from_id( *last_id ) <= i )\n break;\n _block_id_to_block.remove( *last_id );\n dropped_count++;\n }\n wlog( \"Dropped ${n} blocks from after the gap\", (\"n\", dropped_count) );\n break;\n }\n apply_block(*block, skip_witness_signature |\n skip_transaction_signatures |\n skip_transaction_dupe_check |\n skip_tapos_check |\n skip_witness_schedule_check |\n skip_authority_check);\n }\n _undo_db.enable();\n auto end = fc::time_point::now();\n ilog( \"Done reindexing, elapsed time: ${t} sec\", (\"t\",double((end-start).count())\/1000000.0 ) );\n} FC_CAPTURE_AND_RETHROW( (data_dir) ) }\n\nvoid database::wipe(const fc::path& data_dir, bool include_blocks)\n{\n ilog(\"Wiping database\", (\"include_blocks\", include_blocks));\n close();\n object_database::wipe(data_dir);\n if( include_blocks )\n fc::remove_all( data_dir \/ \"database\" );\n}\n\nvoid database::open(\n const fc::path& data_dir,\n std::function<genesis_state_type()> genesis_loader)\n{\n try\n {\n object_database::open(data_dir);\n\n _block_id_to_block.open(data_dir \/ \"database\" \/ \"block_num_to_block\");\n\n if( !find(global_property_id_type()) )\n init_genesis(genesis_loader());\n\n fc::optional<signed_block> last_block = _block_id_to_block.last();\n if( last_block.valid() )\n {\n _fork_db.start_block( *last_block );\n idump((last_block->id())(last_block->block_num()));\n if( last_block->id() != head_block_id() )\n {\n FC_ASSERT( head_block_num() == 0, \"last block ID does not match current chain state\" );\n }\n }\n \/\/idump((head_block_id())(head_block_num()));\n }\n FC_CAPTURE_LOG_AND_RETHROW( (data_dir) )\n}\n\nvoid database::close(bool rewind)\n{\n \/\/ TODO: Save pending tx's on close()\n clear_pending();\n\n \/\/ pop all of the blocks that we can given our undo history, this should\n \/\/ throw when there is no more undo history to pop\n if( rewind )\n {\n try\n {\n while( true )\n {\n \/\/ elog(\"pop\");\n block_id_type popped_block_id = head_block_id();\n pop_block();\n _fork_db.remove(popped_block_id); \/\/ doesn't throw on missing\n try\n {\n _block_id_to_block.remove(popped_block_id);\n }\n catch (const fc::key_not_found_exception&)\n {\n }\n }\n }\n catch (...)\n {\n }\n }\n\n \/\/ Since pop_block() will move tx's in the popped blocks into pending,\n \/\/ we have to clear_pending() after we're done popping to get a clean\n \/\/ DB state (issue #336).\n clear_pending();\n\n object_database::flush();\n object_database::close();\n\n if( _block_id_to_block.is_open() )\n _block_id_to_block.close();\n\n _fork_db.reset();\n}\n\n} }\n<commit_msg>db_management.cpp: Only pop to last irreversible block, fix #407<commit_after>\/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Any modified source or binaries are used only with the BitShares network.\n *\n * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *\n * 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <graphene\/chain\/database.hpp>\n\n#include <graphene\/chain\/operation_history_object.hpp>\n#include <graphene\/chain\/protocol\/fee_schedule.hpp>\n\n#include <fc\/io\/fstream.hpp>\n\n#include <fstream>\n#include <functional>\n#include <iostream>\n\nnamespace graphene { namespace chain {\n\ndatabase::database()\n{\n initialize_indexes();\n initialize_evaluators();\n}\n\ndatabase::~database()\n{\n clear_pending();\n}\n\nvoid database::reindex(fc::path data_dir, const genesis_state_type& initial_allocation)\n{ try {\n ilog( \"reindexing blockchain\" );\n wipe(data_dir, false);\n open(data_dir, [&initial_allocation]{return initial_allocation;});\n\n auto start = fc::time_point::now();\n auto last_block = _block_id_to_block.last();\n if( !last_block ) {\n elog( \"!no last block\" );\n edump((last_block));\n return;\n }\n\n const auto last_block_num = last_block->block_num();\n\n ilog( \"Replaying blocks...\" );\n _undo_db.disable();\n for( uint32_t i = 1; i <= last_block_num; ++i )\n {\n if( i % 2000 == 0 ) std::cerr << \" \" << double(i*100)\/last_block_num << \"% \"<<i << \" of \" <<last_block_num<<\" \\n\";\n fc::optional< signed_block > block = _block_id_to_block.fetch_by_number(i);\n if( !block.valid() )\n {\n wlog( \"Reindexing terminated due to gap: Block ${i} does not exist!\", (\"i\", i) );\n uint32_t dropped_count = 0;\n while( true )\n {\n fc::optional< block_id_type > last_id = _block_id_to_block.last_id();\n \/\/ this can trigger if we attempt to e.g. read a file that has block #2 but no block #1\n if( !last_id.valid() )\n break;\n \/\/ we've caught up to the gap\n if( block_header::num_from_id( *last_id ) <= i )\n break;\n _block_id_to_block.remove( *last_id );\n dropped_count++;\n }\n wlog( \"Dropped ${n} blocks from after the gap\", (\"n\", dropped_count) );\n break;\n }\n apply_block(*block, skip_witness_signature |\n skip_transaction_signatures |\n skip_transaction_dupe_check |\n skip_tapos_check |\n skip_witness_schedule_check |\n skip_authority_check);\n }\n _undo_db.enable();\n auto end = fc::time_point::now();\n ilog( \"Done reindexing, elapsed time: ${t} sec\", (\"t\",double((end-start).count())\/1000000.0 ) );\n} FC_CAPTURE_AND_RETHROW( (data_dir) ) }\n\nvoid database::wipe(const fc::path& data_dir, bool include_blocks)\n{\n ilog(\"Wiping database\", (\"include_blocks\", include_blocks));\n close();\n object_database::wipe(data_dir);\n if( include_blocks )\n fc::remove_all( data_dir \/ \"database\" );\n}\n\nvoid database::open(\n const fc::path& data_dir,\n std::function<genesis_state_type()> genesis_loader)\n{\n try\n {\n object_database::open(data_dir);\n\n _block_id_to_block.open(data_dir \/ \"database\" \/ \"block_num_to_block\");\n\n if( !find(global_property_id_type()) )\n init_genesis(genesis_loader());\n\n fc::optional<signed_block> last_block = _block_id_to_block.last();\n if( last_block.valid() )\n {\n _fork_db.start_block( *last_block );\n idump((last_block->id())(last_block->block_num()));\n if( last_block->id() != head_block_id() )\n {\n FC_ASSERT( head_block_num() == 0, \"last block ID does not match current chain state\" );\n }\n }\n \/\/idump((head_block_id())(head_block_num()));\n }\n FC_CAPTURE_LOG_AND_RETHROW( (data_dir) )\n}\n\nvoid database::close(bool rewind)\n{\n \/\/ TODO: Save pending tx's on close()\n clear_pending();\n\n \/\/ pop all of the blocks that we can given our undo history, this should\n \/\/ throw when there is no more undo history to pop\n if( rewind )\n {\n try\n {\n uint32_t cutoff = get_dynamic_global_properties().last_irreversible_block_num;\n\n while( head_block_num() > cutoff )\n {\n \/\/ elog(\"pop\");\n block_id_type popped_block_id = head_block_id();\n pop_block();\n _fork_db.remove(popped_block_id); \/\/ doesn't throw on missing\n try\n {\n _block_id_to_block.remove(popped_block_id);\n }\n catch (const fc::key_not_found_exception&)\n {\n }\n }\n }\n catch (...)\n {\n }\n }\n\n \/\/ Since pop_block() will move tx's in the popped blocks into pending,\n \/\/ we have to clear_pending() after we're done popping to get a clean\n \/\/ DB state (issue #336).\n clear_pending();\n\n object_database::flush();\n object_database::close();\n\n if( _block_id_to_block.is_open() )\n _block_id_to_block.close();\n\n _fork_db.reset();\n}\n\n} }\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/\n\/\/ Contributors: Kirsten Weber\n\n#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH\n#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n#include \"cmake_config.h\"\n#elif defined(HAVE_CONFIG_H)\n#include \"config.h\"\n#endif\n\n#include <memory>\n\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/fvector.hh>\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/la\/container\/interface.hh>\n\n#include <dune\/gdt\/space\/interface.hh>\n\n#include \"local.hh\"\n\nnamespace Dune {\nnamespace GDT {\n\n\n\/\/ template< class DiscreteFunctionSpaceImp, class VectorImp >\n\/\/ class DefaultConst;\n\n\n\/\/ template< class DiscreteFunctionSpaceImp, class VectorImp >\n\/\/ class Default\n\/\/ : public Dune::VTKFunction< typename DiscreteFunctionSpaceImp::GridViewType >\n\/\/{\n\/\/ private:\n\/\/ typedef Dune::VTKFunction< typename DiscreteFunctionSpaceImp::GridViewType > BaseType;\n\n\/\/ public:\n\/\/ typedef DiscreteFunctionSpaceImp DiscreteFunctionSpaceType;\n\n\/\/ typedef VectorImp VectorType;\n\n\/\/ typedef Default< DiscreteFunctionSpaceType, VectorType > ThisType;\n\n\/\/ typedef DefaultConst< DiscreteFunctionSpaceType, VectorType > ConstType;\n\n\/\/ typedef typename DiscreteFunctionSpaceType::GridViewType::template Codim< 0 >::Iterator::Entity EntityType;\n\n\/\/ static const int polOrder = DiscreteFunctionSpaceType::polynomialOrder;\n\n\/\/ typedef Dune::Detailed::Discretizations::DiscreteFunction::LocalConst< ThisType > ConstLocalFunctionType;\n\n\/\/ typedef Dune::Detailed::Discretizations::DiscreteFunction::Local< ThisType > LocalFunctionType;\n\n\/\/ typedef typename DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;\n\n\/\/ typedef typename FunctionSpaceType::DomainType DomainType;\n\n\/\/ typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;\n\n\/\/ typedef typename FunctionSpaceType::RangeType RangeType;\n\n\/\/ static const int dimDomain = DiscreteFunctionSpaceType::dimDomain;\n\n\/\/ static const int dimRange = DiscreteFunctionSpaceType::dimRange;\n\n\/\/ typedef typename VectorType::size_type size_type;\n\n\/\/ Default(const DiscreteFunctionSpaceType& _space,\n\/\/ std::shared_ptr< VectorType > _vector,\n\/\/ const std::string _name = \"discrete_function\")\n\/\/ : BaseType(),\n\/\/ space_(_space)\n\/\/ , vector_(_vector)\n\/\/ , name_(_name)\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ }\n\n\/\/ Default(const DiscreteFunctionSpaceType& _space,\n\/\/ const std::string _name = \"discrete_function\")\n\/\/ : BaseType(),\n\/\/ space_(_space)\n\/\/ , vector_(new VectorType(space_.map().size()))\n\/\/ , name_(_name)\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ }\n\n\/\/ std::shared_ptr< const ConstType > createConst() const\n\/\/ {\n\/\/ std::shared_ptr< const ConstType > ret(new ConstType(*this));\n\/\/ return ret;\n\/\/ }\n\n\/\/ private:\n\/\/ Default(const ThisType&);\n\/\/ ThisType& operator=(const ThisType&);\n\n\/\/ public:\n\/\/ const DiscreteFunctionSpaceType& space() const\n\/\/ {\n\/\/ return space_;\n\/\/ }\n\n\/\/ virtual std::string name() const\n\/\/ {\n\/\/ return name_;\n\/\/ }\n\n\/\/ ConstLocalFunctionType localFunction(const EntityType& entity) const\n\/\/ {\n\/\/ return ConstLocalFunctionType(*this, entity);\n\/\/ }\n\n\/\/ LocalFunctionType localFunction(const EntityType& entity)\n\/\/ {\n\/\/ return LocalFunctionType(*this, entity);\n\/\/ }\n\n\/\/ std::shared_ptr< VectorType > vector()\n\/\/ {\n\/\/ return vector_;\n\/\/ }\n\n\/\/ const std::shared_ptr< const VectorType > vector() const\n\/\/ {\n\/\/ return vector_;\n\/\/ }\n\n\/\/ \/**\n\/\/ @name Convenience methods\n\/\/ @{\n\/\/ **\/\n\/\/ size_type size() const\n\/\/ {\n\/\/ return vector_->size();\n\/\/ }\n\/\/ \/**\n\/\/ @}\n\/\/ **\/\n\n\/\/ void clear()\n\/\/ {\n\/\/ const RangeFieldType zero(0);\n\/\/ for (size_type ii = 0; ii < vector_->size(); ++ii)\n\/\/ vector_->set(ii, zero);\n\/\/ }\n\n\/\/ \/**\n\/\/ @name Methods to comply with the Dune::VTKFunction interface\n\/\/ @{\n\/\/ **\/\n\/\/ virtual int ncomps() const\n\/\/ {\n\/\/ return dimRange;\n\/\/ }\n\n\/\/ virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ RangeType ret(0.0);\n\/\/ localFunction(entity).evaluate(x, ret);\n\/\/ return ret[component];\n\/\/ }\n\/\/ \/**\n\/\/ @}\n\/\/ **\/\n\n\/\/ private:\n\/\/ const DiscreteFunctionSpaceType& space_;\n\/\/ std::shared_ptr< VectorType > vector_;\n\/\/ const std::string name_;\n\/\/}; \/\/ class Default\n\n\ntemplate <class SpaceImp, class VectorImp>\nclass DiscreteFunctionDefaultConst : public Dune::VTKFunction<typename SpaceImp::GridPartType::GridViewType>,\n public Dune::Stuff::LocalizableFunction\n{\npublic:\n typedef typename SpaceInterface<typename SpaceImp::Traits>::derived_type SpaceType;\n typedef typename Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>::derived_type VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef DiscreteFunctionLocalConst<SpaceType, VectorType> ConstLocalFunctionType;\n typedef typename ConstLocalFunctionType::DomainType DomainType;\n typedef typename ConstLocalFunctionType::RangeType RangeType;\n\n DiscreteFunctionDefaultConst(const SpaceType& sp, const std::shared_ptr<const VectorType> vec,\n const std::string nm = \"discrete_function\")\n : \/*BaseType()\n , *\/ space_(sp)\n , name_(nm)\n , vector_(vec)\n {\n assert(vector_->size() == space_.mapper().size() && \"Given vector has wrong size!\");\n }\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n ConstLocalFunctionType localFunction(const EntityType& entity) const\n {\n return ConstLocalFunctionType(*this, entity);\n }\n\n std::shared_ptr<const VectorType> vector() const\n {\n return vector_;\n }\n\n \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/* @{ *\/\n virtual int ncomps() const\n {\n return SpaceType::dimRange;\n }\n\n virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n {\n RangeType ret(0);\n localFunction(entity).evaluate(x, ret);\n return ret[component];\n }\n \/* @} *\/\n\nprivate:\n const SpaceType& space_;\n const std::string name_;\n const std::shared_ptr<const VectorType> vector_;\n}; \/\/ class DiscreteFunctionDefaultConst\n\n\ntemplate <class SpaceImp, class VectorImp>\nclass DiscreteFunctionDefault : public DiscreteFunctionDefaultConst<SpaceImp, VectorImp>\n{\n typedef DiscreteFunctionDefaultConst<SpaceImp, VectorImp> BaseType;\n\npublic:\n typedef typename SpaceInterface<typename SpaceImp::Traits>::derived_type SpaceType;\n typedef typename Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>::derived_type VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef DiscreteFunctionLocal<SpaceType, VectorType> LocalFunctionType;\n typedef typename LocalFunctionType::DomainType DomainType;\n\n DiscreteFunctionDefault(const SpaceType& sp, std::shared_ptr<VectorType> vec,\n const std::string nm = \"discrete_function\")\n : BaseType(sp, vec, nm)\n , nonConstVector_(vec)\n {\n }\n\n DiscreteFunctionDefault(const SpaceType& sp, const std::string nm = \"discrete_function\")\n : BaseType(sp, std::make_shared<VectorType>(sp.mapper().size()), nm)\n , nonConstVector_(std::make_shared<VectorType>(const_cast<VectorType&>(\n *(BaseType::vector())))) \/\/ <- I am not sure if this is safe to do. I would expect the BaseType to live long\n \/\/ enough, but maybe someone else has a better Idea!\n {\n }\n\n LocalFunctionType localFunction(const EntityType& entity)\n {\n return LocalFunctionType(*this, entity);\n }\n\n std::shared_ptr<VectorType> vector()\n {\n return nonConstVector_;\n }\n\n \/\/ virtual std::string name() const\n \/\/ {\n \/\/ return BaseType::name();\n \/\/ }\n\n \/\/ \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/\/ \/* @{ *\/\n \/\/ virtual int ncomps() const\n \/\/ {\n \/\/ return BaseType::ncomps();\n \/\/ }\n\n \/\/ virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n \/\/ {\n \/\/ BaseType::evaluate(component, entity, x);\n \/\/ }\n \/\/ \/* @} *\/\n\nprivate:\n std::shared_ptr<VectorType> nonConstVector_;\n}; \/\/ class DiscreteFunctionDefault\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH\n<commit_msg>[discretefunction.default] some cleanup<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/\n\/\/ Contributors: Kirsten Weber\n\n#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH\n#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n#include \"cmake_config.h\"\n#elif defined(HAVE_CONFIG_H)\n#include \"config.h\"\n#endif\n\n#include <memory>\n\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/fvector.hh>\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/la\/container\/interface.hh>\n#include <dune\/gdt\/space\/interface.hh>\n\n#include \"local.hh\"\n\nnamespace Dune {\nnamespace GDT {\n\n\ntemplate <class SpaceImp, class VectorImp>\nclass DiscreteFunctionDefaultConst : public Dune::VTKFunction<typename SpaceImp::GridPartType::GridViewType>,\n public Dune::Stuff::LocalizableFunction\n{\npublic:\n typedef typename SpaceInterface<typename SpaceImp::Traits>::derived_type SpaceType;\n typedef typename Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>::derived_type VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef DiscreteFunctionLocalConst<SpaceType, VectorType> ConstLocalFunctionType;\n typedef typename ConstLocalFunctionType::DomainType DomainType;\n typedef typename ConstLocalFunctionType::RangeType RangeType;\n\n DiscreteFunctionDefaultConst(const SpaceType& sp, const std::shared_ptr<const VectorType> vec,\n const std::string nm = \"discrete_function\")\n : space_(sp)\n , name_(nm)\n , vector_(vec)\n {\n assert(vector_->size() == space_.mapper().size() && \"Given vector has wrong size!\");\n }\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n ConstLocalFunctionType localFunction(const EntityType& entity) const\n {\n return ConstLocalFunctionType(*this, entity);\n }\n\n std::shared_ptr<const VectorType> vector() const\n {\n return vector_;\n }\n\n \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/* @{ *\/\n virtual int ncomps() const\n {\n return SpaceType::dimRange;\n }\n\n virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n {\n RangeType ret(0);\n localFunction(entity).evaluate(x, ret);\n return ret[component];\n }\n \/* @} *\/\n\nprivate:\n const SpaceType& space_;\n const std::string name_;\n const std::shared_ptr<const VectorType> vector_;\n}; \/\/ class DiscreteFunctionDefaultConst\n\n\ntemplate <class SpaceImp, class VectorImp>\nclass DiscreteFunctionDefault : public DiscreteFunctionDefaultConst<SpaceImp, VectorImp>\n{\n typedef DiscreteFunctionDefaultConst<SpaceImp, VectorImp> BaseType;\n\npublic:\n typedef typename SpaceInterface<typename SpaceImp::Traits>::derived_type SpaceType;\n typedef typename Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>::derived_type VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef DiscreteFunctionLocal<SpaceType, VectorType> LocalFunctionType;\n typedef typename LocalFunctionType::DomainType DomainType;\n\n DiscreteFunctionDefault(const SpaceType& sp, std::shared_ptr<VectorType> vec,\n const std::string nm = \"discrete_function\")\n : BaseType(sp, vec, nm)\n , nonConstVector_(vec)\n {\n }\n\n DiscreteFunctionDefault(const SpaceType& sp, const std::string nm = \"discrete_function\")\n : BaseType(sp, std::make_shared<VectorType>(sp.mapper().size()), nm)\n , nonConstVector_(std::make_shared<VectorType>(const_cast<VectorType&>(\n *(BaseType::vector())))) \/\/ <- I am not sure if this is safe to do. I would expect the BaseType to live long\n \/\/ enough, but maybe someone else has a better Idea!\n {\n }\n\n LocalFunctionType localFunction(const EntityType& entity)\n {\n return LocalFunctionType(*this, entity);\n }\n\n std::shared_ptr<VectorType> vector()\n {\n return nonConstVector_;\n }\n\n \/\/ virtual std::string name() const\n \/\/ {\n \/\/ return BaseType::name();\n \/\/ }\n\n \/\/ \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/\/ \/* @{ *\/\n \/\/ virtual int ncomps() const\n \/\/ {\n \/\/ return BaseType::ncomps();\n \/\/ }\n\n \/\/ virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n \/\/ {\n \/\/ BaseType::evaluate(component, entity, x);\n \/\/ }\n \/\/ \/* @} *\/\n\nprivate:\n std::shared_ptr<VectorType> nonConstVector_;\n}; \/\/ class DiscreteFunctionDefault\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\r\n#include <iostream>\r\n#include <tuple>\r\n\r\n#include <opcodes.hpp>\r\n\r\nusing namespace std;\r\nusing dcpu::emulator::opcode;\r\n\r\nclass OpcodesParserTest: public ::testing::TestWithParam<tuple<uint16_t, string>> {\r\npublic:\r\n\tvoid SetUp() {\r\n\t\tauto data = GetParam();\r\n\t\tinstruction = get<0>(data);\r\n\t\texpected_string = get<1>(data);\r\n\t}\r\nprotected:\r\n\tuint16_t instruction;\r\n\tstring expected_string;\r\n};\r\n\r\nTEST_P(OpcodesParserTest, Parse) {\r\n\tdcpu::emulator::dcpu cpu;\r\n\r\n\tunique_ptr<opcode> op = opcode::parse(cpu, instruction);\r\n\tEXPECT_EQ(expected_string, op->to_str());\r\n}\r\n\r\nINSTANTIATE_TEST_CASE_P(All, OpcodesParserTest, ::testing::Values(\r\n\tmake_tuple((uint16_t)0x0001, string(\"set A, A\")),\r\n\tmake_tuple((uint16_t)0x0002, string(\"add A, A\")),\r\n\tmake_tuple((uint16_t)0x0003, string(\"sub A, A\")),\r\n\tmake_tuple((uint16_t)0x0004, string(\"mul A, A\")),\r\n\tmake_tuple((uint16_t)0x0005, string(\"mli A, A\")),\r\n\tmake_tuple((uint16_t)0x0006, string(\"div A, A\")),\r\n\tmake_tuple((uint16_t)0x0007, string(\"dvi A, A\")),\r\n\tmake_tuple((uint16_t)0x0008, string(\"mod A, A\")),\r\n\tmake_tuple((uint16_t)0x0009, string(\"mdi A, A\")),\r\n\tmake_tuple((uint16_t)0x000a, string(\"and A, A\")),\r\n\tmake_tuple((uint16_t)0x000b, string(\"bor A, A\")),\r\n\tmake_tuple((uint16_t)0x000c, string(\"xor A, A\")),\r\n\tmake_tuple((uint16_t)0x000d, string(\"shr A, A\")),\r\n\tmake_tuple((uint16_t)0x000e, string(\"asr A, A\")),\r\n\tmake_tuple((uint16_t)0x000f, string(\"shl A, A\")),\r\n\tmake_tuple((uint16_t)0xfd50, string(\"ifb [C], 30\")),\r\n\tmake_tuple((uint16_t)0xf971, string(\"ifc [X], 29\")),\r\n\tmake_tuple((uint16_t)0x0012, string(\"ife A, A\")),\r\n\tmake_tuple((uint16_t)0x0013, string(\"ifn A, A\")),\r\n\tmake_tuple((uint16_t)0x0014, string(\"ifg A, A\")),\r\n\tmake_tuple((uint16_t)0x0015, string(\"ifa A, A\")),\r\n\tmake_tuple((uint16_t)0x0016, string(\"ifl A, A\")),\r\n\tmake_tuple((uint16_t)0x0017, string(\"ifu A, A\")),\r\n\tmake_tuple((uint16_t)0x001a, string(\"adx A, A\")),\r\n\tmake_tuple((uint16_t)0x001b, string(\"sbx A, A\")),\r\n\tmake_tuple((uint16_t)0x001e, string(\"sti A, A\")),\r\n\tmake_tuple((uint16_t)0x001f, string(\"std A, A\")),\r\n\tmake_tuple((uint16_t)0x0020, string(\"jsr A\")),\r\n\tmake_tuple((uint16_t)0x00e0, string(\"hcf A\")),\r\n\tmake_tuple((uint16_t)0x0100, string(\"int A\")),\r\n\tmake_tuple((uint16_t)0x0120, string(\"iag A\")),\r\n\tmake_tuple((uint16_t)0x0140, string(\"ias A\")),\r\n\tmake_tuple((uint16_t)0x0160, string(\"rfi A\")),\r\n\tmake_tuple((uint16_t)0x0180, string(\"iaq A\")),\r\n\tmake_tuple((uint16_t)0x0200, string(\"hwn A\")),\r\n\tmake_tuple((uint16_t)0x0220, string(\"hwq A\")),\r\n\tmake_tuple((uint16_t)0x0240, string(\"hwi A\"))\r\n\r\n));\r\n<commit_msg>Added negative tests for opcodes parser<commit_after>#include <gtest\/gtest.h>\r\n#include <iostream>\r\n#include <tuple>\r\n\r\n#include <opcodes.hpp>\r\n\r\nusing namespace std;\r\nusing dcpu::emulator::opcode;\r\n\r\nclass OpcodesParserTest: public ::testing::TestWithParam<tuple<uint16_t, string>> {\r\npublic:\r\n\tvoid SetUp() {\r\n\t\tauto data = GetParam();\r\n\t\tinstruction = get<0>(data);\r\n\t\texpected_string = get<1>(data);\r\n\t}\r\nprotected:\r\n\tuint16_t instruction;\r\n\tstring expected_string;\r\n};\r\n\r\nTEST_P(OpcodesParserTest, ValidInstruction) {\r\n\tdcpu::emulator::dcpu cpu;\r\n\r\n\tunique_ptr<opcode> op = opcode::parse(cpu, instruction);\r\n\tEXPECT_EQ(expected_string, op->to_str());\r\n}\r\n\r\nINSTANTIATE_TEST_CASE_P(All, OpcodesParserTest, ::testing::Values(\r\n\tmake_tuple((uint16_t)0x0001, string(\"set A, A\")),\r\n\tmake_tuple((uint16_t)0x0002, string(\"add A, A\")),\r\n\tmake_tuple((uint16_t)0x0003, string(\"sub A, A\")),\r\n\tmake_tuple((uint16_t)0x0004, string(\"mul A, A\")),\r\n\tmake_tuple((uint16_t)0x0005, string(\"mli A, A\")),\r\n\tmake_tuple((uint16_t)0x0006, string(\"div A, A\")),\r\n\tmake_tuple((uint16_t)0x0007, string(\"dvi A, A\")),\r\n\tmake_tuple((uint16_t)0x0008, string(\"mod A, A\")),\r\n\tmake_tuple((uint16_t)0x0009, string(\"mdi A, A\")),\r\n\tmake_tuple((uint16_t)0x000a, string(\"and A, A\")),\r\n\tmake_tuple((uint16_t)0x000b, string(\"bor A, A\")),\r\n\tmake_tuple((uint16_t)0x000c, string(\"xor A, A\")),\r\n\tmake_tuple((uint16_t)0x000d, string(\"shr A, A\")),\r\n\tmake_tuple((uint16_t)0x000e, string(\"asr A, A\")),\r\n\tmake_tuple((uint16_t)0x000f, string(\"shl A, A\")),\r\n\tmake_tuple((uint16_t)0xfd50, string(\"ifb [C], 30\")),\r\n\tmake_tuple((uint16_t)0xf971, string(\"ifc [X], 29\")),\r\n\tmake_tuple((uint16_t)0x0012, string(\"ife A, A\")),\r\n\tmake_tuple((uint16_t)0x0013, string(\"ifn A, A\")),\r\n\tmake_tuple((uint16_t)0x0014, string(\"ifg A, A\")),\r\n\tmake_tuple((uint16_t)0x0015, string(\"ifa A, A\")),\r\n\tmake_tuple((uint16_t)0x0016, string(\"ifl A, A\")),\r\n\tmake_tuple((uint16_t)0x0017, string(\"ifu A, A\")),\r\n\tmake_tuple((uint16_t)0x001a, string(\"adx A, A\")),\r\n\tmake_tuple((uint16_t)0x001b, string(\"sbx A, A\")),\r\n\tmake_tuple((uint16_t)0x001e, string(\"sti A, A\")),\r\n\tmake_tuple((uint16_t)0x001f, string(\"std A, A\")),\r\n\tmake_tuple((uint16_t)0x0020, string(\"jsr A\")),\r\n\tmake_tuple((uint16_t)0x00e0, string(\"hcf A\")),\r\n\tmake_tuple((uint16_t)0x0100, string(\"int A\")),\r\n\tmake_tuple((uint16_t)0x0120, string(\"iag A\")),\r\n\tmake_tuple((uint16_t)0x0140, string(\"ias A\")),\r\n\tmake_tuple((uint16_t)0x0160, string(\"rfi A\")),\r\n\tmake_tuple((uint16_t)0x0180, string(\"iaq A\")),\r\n\tmake_tuple((uint16_t)0x0200, string(\"hwn A\")),\r\n\tmake_tuple((uint16_t)0x0220, string(\"hwq A\")),\r\n\tmake_tuple((uint16_t)0x0240, string(\"hwi A\"))\r\n));\r\n\r\nclass OpcodesParserNegativeTest: public ::testing::TestWithParam<uint16_t> {\r\npublic:\r\n\tvoid SetUp() {\r\n\t\tinstruction = GetParam();\r\n\t}\r\nprotected:\r\n\tuint16_t instruction;\r\n};\r\n\r\nTEST_P(OpcodesParserNegativeTest, InvalidInstruction) {\r\n\tdcpu::emulator::dcpu cpu;\r\n\tEXPECT_THROW({\r\n\t\topcode::parse(cpu, instruction);\r\n\t}, invalid_argument);\r\n}\r\n\r\nINSTANTIATE_TEST_CASE_P(All, OpcodesParserNegativeTest, ::testing::Values(\r\n\t0x0000, 0x0018, 0x0019, 0x001c, 0x001d, 0x0040, 0x0060, 0x0080, 0x00a0, 0x00c0, 0x01a0, 0x01c0, 0x01e0,\r\n\t0x0260, 0x0280, 0x02a0, 0x02c0, 0x02e0, 0x0300, 0x0320, 0x0340, 0x0360, 0x0380, 0x03a0, 0x03c0, 0x03e0));\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright(c) 2016 Jounayd Id Salah\n\/\/ Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http:\/\/opensource.org\/licenses\/MIT).\n#include \"parser_clang\/pch.h\"\n#include \"parser_clang\/coClangSourceParser.h\"\n#include \"pattern\/scope\/coDefer.h\"\n#include \"lang\/result\/coResult_f.h\"\n#include \"lang\/reflect\/coType.h\"\n#include \"lang\/reflect\/coField.h\"\n#include \"parser\/source\/coParsedType.h\"\n#include \"parser\/source\/coParsedField.h\"\n#include \"container\/string\/coDynamicString_f.h\"\n#include \"container\/array\/coDynamicArray_f.h\"\n#include \"container\/array\/coConstArray_f.h\"\n#include \"memory\/allocator\/coLocalAllocator.h\"\n#include \"io\/path\/coPath_f.h\"\n#include \"io\/path\/coPathStatus.h\"\n\ncoSourceParser* coSourceParser::Create()\n{\n\treturn new coClangSourceParser();\n}\n\ncoClangSourceParser::coClangSourceParser()\n\t: clangIndex(nullptr)\n{\n\n}\n\ncoClangSourceParser::~coClangSourceParser()\n{\n\tif (clangIndex)\n\t{\n\t\tclang_disposeIndex(clangIndex);\n\t}\n}\n\ncoResult coClangSourceParser::OnInit(const coObject::InitConfig& _config)\n{\n\tcoTRY(Super::OnInit(_config), nullptr);\n\t\/\/const InitConfig& config = static_cast<const InitConfig&>(_config);\n\tcoASSERT(!clangIndex);\n\tclangIndex = clang_createIndex(1, 1);\n\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParsePrecompiledHeader(const ParseConfig& _config)\n{\n\tcoTRY(Super::ParsePrecompiledHeader(_config), nullptr);\n\tcoLocalAllocator localAllocator(2048);\n\n\t\/\/ Check out dir\n\t\/*{\n\t\tcoPathStatus status;\n\t\tcoTRY(coGetPathStatus(status, _config.outPath), nullptr);\n\t\tcoTRY(status.Exists(), \"The output directory does not exist: \"<<_config.outPath);\n\t}*\/\n\n\t\/\/ Build file path\n\tcoDynamicString filePath(localAllocator);\n\t{\n\t\tfilePath = _config.filePath;\n\t\tcoNullTerminate(filePath);\n\t}\n\n\t\/\/ Build out path\n\tcoDynamicString outPath(localAllocator);\n\t{\n\t\tcoConstString baseName;\n\t\tcoGetBaseName(baseName, _config.filePath);\n\t\tcoJoinPaths(outPath, _config.outPath, baseName);\n\t\toutPath << \".pch\";\n\t\tcoNullTerminate(outPath);\n\t}\n\n\t\/\/ Parse\n\t{\n\t\tCXTranslationUnit translationUnit = nullptr;\n\t\tconst coArray<const coChar*> args = { \"-x\", \"c++\", \"-std=c++11\", \"-fms-compatibility-version=19\", \"-D\", \"coREFLECTION_PARSING\", \"-IJ:\/CODE\/core\/src\" };\n\t\t\/\/translationUnit = clang_createTranslationUnitFromSourceFile(clangIndex, filePath.data, args.count, args.data, 0, nullptr);\n\t\tconst CXErrorCode parseError = clang_parseTranslationUnit2(clangIndex, filePath.data, args.data, args.count, nullptr, 0, CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete, &translationUnit);\n\t\tcoTRY(parseError == CXError_Success, \"Clang failed to parse the file: \" << filePath);\n\t\tcoTRY(translationUnit, \"Can't create translation unit from source file: \" << filePath);\n\t\tcoDEFER() { clang_disposeTranslationUnit(translationUnit); };\n\t\tconst CXSaveError saveError = static_cast<CXSaveError>(clang_saveTranslationUnit(translationUnit, outPath.data, 0));\n\t\tcoTRY(parseError == CXSaveError_None, \"Clang failed to save the file: \" << outPath.data);\n\t}\n\t\n\treturn true;\n}\n\ncoResult coClangSourceParser::Parse(ParseResult& _result, const ParseConfig& _config)\n{\n\tcoTRY(Super::Parse(_result, _config), nullptr);\n\tcoLocalAllocator localAllocator(2048);\n\n\tcoDynamicString filePath(localAllocator);\n\tfilePath = _config.filePath;\n\tcoNullTerminate(filePath);\n\tCXTranslationUnit translationUnit = nullptr;\n\tconst coArray<const coChar*> args = {\"-x\", \"c++\", \"-std=c++11\", \"-fms-compatibility-version=19\", \"-D\", \"coREFLECTION_PARSING\", \"-IJ:\/CODE\/core\/src\", \"-include-pch\", \"J:\/CODE\/core\/build\/vs2015\/reflect\/pattern\/pch.pch\"};\n\t\/\/translationUnit = clang_createTranslationUnitFromSourceFile(clangIndex, filePath.data, args.count, args.data, 0, nullptr);\n\tconst CXErrorCode error = clang_parseTranslationUnit2(clangIndex, filePath.data, args.data, args.count, nullptr, 0, CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete, &translationUnit);\n\tcoTRY(error == CXError_Success, \"Clang failed to parse the file: \" << filePath);\n\tcoTRY(translationUnit, \"Can't create translation unit from source file: \" << filePath);\n\tcoDEFER() { clang_disposeTranslationUnit(translationUnit); };\n\tCXCursor cursor = clang_getTranslationUnitCursor(translationUnit);\n\n\tif (_result.parsedTypes)\n\t{\n\t\tcoTRY(ParseTypes(_result, cursor), \"Failed to parse types\");\n\t}\n\treturn true;\n}\n\nCXChildVisitResult coClangSourceParser::ParseTypesVisitor(CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n{\n\tconst ScopeInfo* scope = static_cast<const ScopeInfo*>(_clientData);\n\tcoClangSourceParser* _this = scope->parser;\n\tconst coBool definition = clang_isCursorDefinition(_child) != 0;\n\tif (!definition)\n\t\treturn CXChildVisitResult::CXChildVisit_Continue;\n\n\tswitch (_child.kind)\n\t{\n\tcase CXCursor_ClassDecl:\n\tcase CXCursor_StructDecl:\n\t{\n\t\tconst CXCursor reflectedAttr = FindAttribute(_child, \"Reflected\");\n\t\tif (!clang_Cursor_isNull(reflectedAttr))\n\t\t{\n\t\t\tcoASSERT(scope->result);\n\t\t\tif (!_this->ParseType(*scope->result, _child))\n\t\t\t{\n\t\t\t\tcoERROR(\"Failed\");\n\t\t\t\treturn CXChildVisitResult::CXChildVisit_Break;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\t}\n\treturn CXChildVisitResult::CXChildVisit_Continue;\n}\n\nCXChildVisitResult coClangSourceParser::ParseTypeChildrenVisitor(CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n{\n\tconst ScopeInfo* scope = static_cast<const ScopeInfo*>(_clientData);\n\tcoASSERT(scope);\n\tcoClangSourceParser* _this = scope->parser;\n\tif (!_this->ParseTypeChild(*scope, _child))\n\t{\n\t\tcoERROR(\"Failed to parse type child\");\n\t\tCXChildVisitResult::CXChildVisit_Break;\n\t}\n\t\n\treturn CXChildVisitResult::CXChildVisit_Continue;\n}\n\ncoResult coClangSourceParser::ParseTypeChild(const ScopeInfo& scope, const CXCursor& _cursor)\n{\n\tcoTRY(scope.curType, nullptr);\n\tswitch (_cursor.kind)\n\t{\n\tcase CXCursor_StructDecl:\n\t{\n\t\tint x = 0;\n\t\t++x;\n\t\tbreak;\n\t}\n\tcase CXCursor_FieldDecl:\n\t{\n\t\tcoParsedField* parsedField = new coParsedField();\n\t\tparsedField->field = new coField();\n\t\tcoDEFER() { delete parsedField; };\n\t\tcoTRY(ParseField(*parsedField, _cursor), \"Failed to parse field: \" << parsedField->field->name);\n\t\tcoPushBack(scope.curType->parsedFields, parsedField);\n\t\tparsedField = nullptr;\n\t\tbreak;\n\t}\n\tcase CXCursor_VarDecl: \/\/ Static field\n\t{\n\t\tbreak;\n\t}\n\tcase CXCursor_CXXMethod: \/\/ Both static and non-static\n\t{\n\t\tconst coBool staticMethod = clang_CXXMethod_isStatic(_cursor) != 0;\n\t\tif (staticMethod)\n\t\t{\n\n\t\t}\n\t\telse\n\t\t{\n\n\t\t}\n\t\tbreak;\n\t}\n\t}\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseTypes(ParseResult& _result, const CXCursor& _cursor)\n{\n\tcoASSERT(_result.parsedTypes);\n\tScopeInfo scope;\n\tscope.parser = this;\n\tscope.result = &_result;\n\tclang_visitChildren(_cursor, &ParseTypesVisitor, &scope);\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseType(ParseResult& _result, const CXCursor& _cursor)\n{\n\tcoParsedType* parsedType = new coParsedType();\n\tcoDEFER() { delete parsedType; };\n\tparsedType->type = new coType();\n\tcoTRY(ParseSymbol(*parsedType->type, _cursor), nullptr);\n\tScopeInfo scope;\n\tscope.parser = this;\n\tscope.curType = parsedType;\n\tclang_visitChildren(_cursor, &ParseTypeChildrenVisitor, &scope);\n\tcoPushBack(*_result.parsedTypes, parsedType);\n\tparsedType = nullptr; \/\/ Release from defer\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseField(coParsedField& _parsedField, const CXCursor& _cursor)\n{\n\tcoTRY(ParseSymbol(*_parsedField.field, _cursor), nullptr);\n\tconst CXType type = clang_getCursorType(_cursor);\n\tconst CXType canonicalType = clang_getCanonicalType(type);\n\tconst CXCursor typeCursor = clang_getTypeDeclaration(canonicalType);\n\tconst CXString typeSpelling = clang_getCursorSpelling(typeCursor);\n\tcoDEFER() { clang_disposeString(typeSpelling); };\n\t_parsedField.typeName = clang_getCString(typeSpelling);\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseSymbol(coSymbol& _symbol, const CXCursor& _cursor)\n{\n\tconst CXString name = clang_getCursorSpelling(_cursor);\n\tcoDEFER() { clang_disposeString(name); };\n\t_symbol.name = clang_getCString(name);\n\n\tconst CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(_cursor);\n\tif (access == CX_CXXPublic)\n\t\t_symbol.symbolFlags |= coType::PUBLIC;\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseMethod(coParsedFunction& \/*_function*\/, const CXCursor& _cursor)\n{\n\tconst coBool staticMethod = clang_CXXMethod_isStatic(_cursor) != 0;\n\tif (staticMethod)\n\t{\n\n\t}\n\telse\n\t{\n\n\t}\n\treturn true;\n}\n\nCXCursor coClangSourceParser::FindAttribute(const CXCursor& _cursor, const coConstString& _attr)\n{\n\tswitch (_cursor.kind)\n\t{\n\tcase CXCursor_ClassDecl:\n\tcase CXCursor_StructDecl:\n\t{\n\t\tstruct Result\n\t\t{\n\t\t\tResult(const coConstString& _structName) : cursor(clang_getNullCursor()), structName(_structName) {}\n\t\t\tCXCursor cursor;\n\t\t\tconst coConstString& structName;\n\t\t};\n\t\tstatic const coConstString attributePrefix(\"_attribute_\");\n\t\tcoDynamicString structName;\n\t\tstructName << attributePrefix;\n\t\tstructName << _attr;\n\t\tResult result(structName);\n\t\tauto AttributeVisitor = [](CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n\t\t{\n\t\t\tif (_child.kind == CXCursor_StructDecl)\n\t\t\t{\n\t\t\t\tCXString cursorStr = clang_getCursorDisplayName(_child);\n\t\t\t\tcoDEFER() { clang_disposeString(cursorStr); };\n\t\t\t\tconst coConstString name = clang_getCString(cursorStr);\n\t\t\t\tResult* result = static_cast<Result*>(_clientData);\n\t\t\t\tif (name == result->structName)\n\t\t\t\t{\n\t\t\t\t\tresult->cursor = _child;\n\t\t\t\t\treturn CXChildVisit_Break;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn CXChildVisit_Continue;\n\t\t};\n\t\tclang_visitChildren(_cursor, AttributeVisitor, &result);\n\t\treturn result.cursor;\n\t\tbreak;\n\t}\n\t}\n\n\treturn clang_getNullCursor();\n}\n<commit_msg>Fixed hard-coded pch directory.<commit_after>\/\/ Copyright(c) 2016 Jounayd Id Salah\n\/\/ Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http:\/\/opensource.org\/licenses\/MIT).\n#include \"parser_clang\/pch.h\"\n#include \"parser_clang\/coClangSourceParser.h\"\n#include \"pattern\/scope\/coDefer.h\"\n#include \"lang\/result\/coResult_f.h\"\n#include \"lang\/reflect\/coType.h\"\n#include \"lang\/reflect\/coField.h\"\n#include \"parser\/source\/coParsedType.h\"\n#include \"parser\/source\/coParsedField.h\"\n#include \"container\/string\/coDynamicString_f.h\"\n#include \"container\/array\/coDynamicArray_f.h\"\n#include \"container\/array\/coConstArray_f.h\"\n#include \"memory\/allocator\/coLocalAllocator.h\"\n#include \"io\/path\/coPath_f.h\"\n#include \"io\/path\/coPathStatus.h\"\n\ncoSourceParser* coSourceParser::Create()\n{\n\treturn new coClangSourceParser();\n}\n\ncoClangSourceParser::coClangSourceParser()\n\t: clangIndex(nullptr)\n{\n\n}\n\ncoClangSourceParser::~coClangSourceParser()\n{\n\tif (clangIndex)\n\t{\n\t\tclang_disposeIndex(clangIndex);\n\t}\n}\n\ncoResult coClangSourceParser::OnInit(const coObject::InitConfig& _config)\n{\n\tcoTRY(Super::OnInit(_config), nullptr);\n\t\/\/const InitConfig& config = static_cast<const InitConfig&>(_config);\n\tcoASSERT(!clangIndex);\n\tclangIndex = clang_createIndex(1, 1);\n\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParsePrecompiledHeader(const ParseConfig& _config)\n{\n\tcoTRY(Super::ParsePrecompiledHeader(_config), nullptr);\n\tcoLocalAllocator localAllocator(2048);\n\n\t\/\/ Check out dir\n\t\/*{\n\t\tcoPathStatus status;\n\t\tcoTRY(coGetPathStatus(status, _config.outPath), nullptr);\n\t\tcoTRY(status.Exists(), \"The output directory does not exist: \"<<_config.outPath);\n\t}*\/\n\n\t\/\/ Build file path\n\tcoDynamicString filePath(localAllocator);\n\t{\n\t\tfilePath = _config.filePath;\n\t\tcoNullTerminate(filePath);\n\t}\n\n\t\/\/ Build out path\n\tcoDynamicString outPath(localAllocator);\n\t{\n\t\tcoConstString baseName;\n\t\tcoGetBaseName(baseName, _config.filePath);\n\t\tcoJoinPaths(outPath, _config.outPath, baseName);\n\t\toutPath << \".pch\";\n\t\tcoNullTerminate(outPath);\n\t}\n\n\t\/\/ Parse\n\t{\n\t\tCXTranslationUnit translationUnit = nullptr;\n\t\tconst coArray<const coChar*> args = { \"-x\", \"c++\", \"-std=c++11\", \"-fms-compatibility-version=19\", \"-D\", \"coREFLECTION_PARSING\", \"-IJ:\/CODE\/core\/src\" };\n\t\t\/\/translationUnit = clang_createTranslationUnitFromSourceFile(clangIndex, filePath.data, args.count, args.data, 0, nullptr);\n\t\tconst CXErrorCode parseError = clang_parseTranslationUnit2(clangIndex, filePath.data, args.data, args.count, nullptr, 0, CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete, &translationUnit);\n\t\tcoTRY(parseError == CXError_Success, \"Clang failed to parse the file: \" << filePath);\n\t\tcoTRY(translationUnit, \"Can't create translation unit from source file: \" << filePath);\n\t\tcoDEFER() { clang_disposeTranslationUnit(translationUnit); };\n\t\tconst CXSaveError saveError = static_cast<CXSaveError>(clang_saveTranslationUnit(translationUnit, outPath.data, 0));\n\t\tcoTRY(parseError == CXSaveError_None, \"Clang failed to save the file: \" << outPath.data);\n\t}\n\t\n\treturn true;\n}\n\ncoResult coClangSourceParser::Parse(ParseResult& _result, const ParseConfig& _config)\n{\n\tcoTRY(Super::Parse(_result, _config), nullptr);\n\tcoLocalAllocator localAllocator(2048);\n\n\tcoDynamicString filePath(localAllocator);\n\tfilePath = _config.filePath;\n\tcoNullTerminate(filePath);\n\tCXTranslationUnit translationUnit = nullptr;\n\tconst coArray<const coChar*> args = {\"-x\", \"c++\", \"-std=c++11\", \"-fms-compatibility-version=19\", \"-D\", \"coREFLECTION_PARSING\", \"-IJ:\/CODE\/core\/src\", \"-include-pch\", \"J:\/CODE\/core\/build\/clang\/reflect\/pattern\/pch.pch\"};\n\t\/\/translationUnit = clang_createTranslationUnitFromSourceFile(clangIndex, filePath.data, args.count, args.data, 0, nullptr);\n\tconst CXErrorCode error = clang_parseTranslationUnit2(clangIndex, filePath.data, args.data, args.count, nullptr, 0, CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete, &translationUnit);\n\tcoTRY(error == CXError_Success, \"Clang failed to parse the file: \" << filePath);\n\tcoTRY(translationUnit, \"Can't create translation unit from source file: \" << filePath);\n\tcoDEFER() { clang_disposeTranslationUnit(translationUnit); };\n\tCXCursor cursor = clang_getTranslationUnitCursor(translationUnit);\n\n\tif (_result.parsedTypes)\n\t{\n\t\tcoTRY(ParseTypes(_result, cursor), \"Failed to parse types\");\n\t}\n\treturn true;\n}\n\nCXChildVisitResult coClangSourceParser::ParseTypesVisitor(CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n{\n\tconst ScopeInfo* scope = static_cast<const ScopeInfo*>(_clientData);\n\tcoClangSourceParser* _this = scope->parser;\n\tconst coBool definition = clang_isCursorDefinition(_child) != 0;\n\tif (!definition)\n\t\treturn CXChildVisitResult::CXChildVisit_Continue;\n\n\tswitch (_child.kind)\n\t{\n\tcase CXCursor_ClassDecl:\n\tcase CXCursor_StructDecl:\n\t{\n\t\tconst CXCursor reflectedAttr = FindAttribute(_child, \"Reflected\");\n\t\tif (!clang_Cursor_isNull(reflectedAttr))\n\t\t{\n\t\t\tcoASSERT(scope->result);\n\t\t\tif (!_this->ParseType(*scope->result, _child))\n\t\t\t{\n\t\t\t\tcoERROR(\"Failed\");\n\t\t\t\treturn CXChildVisitResult::CXChildVisit_Break;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\t}\n\treturn CXChildVisitResult::CXChildVisit_Continue;\n}\n\nCXChildVisitResult coClangSourceParser::ParseTypeChildrenVisitor(CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n{\n\tconst ScopeInfo* scope = static_cast<const ScopeInfo*>(_clientData);\n\tcoASSERT(scope);\n\tcoClangSourceParser* _this = scope->parser;\n\tif (!_this->ParseTypeChild(*scope, _child))\n\t{\n\t\tcoERROR(\"Failed to parse type child\");\n\t\tCXChildVisitResult::CXChildVisit_Break;\n\t}\n\t\n\treturn CXChildVisitResult::CXChildVisit_Continue;\n}\n\ncoResult coClangSourceParser::ParseTypeChild(const ScopeInfo& scope, const CXCursor& _cursor)\n{\n\tcoTRY(scope.curType, nullptr);\n\tswitch (_cursor.kind)\n\t{\n\tcase CXCursor_StructDecl:\n\t{\n\t\tint x = 0;\n\t\t++x;\n\t\tbreak;\n\t}\n\tcase CXCursor_FieldDecl:\n\t{\n\t\tcoParsedField* parsedField = new coParsedField();\n\t\tparsedField->field = new coField();\n\t\tcoDEFER() { delete parsedField; };\n\t\tcoTRY(ParseField(*parsedField, _cursor), \"Failed to parse field: \" << parsedField->field->name);\n\t\tcoPushBack(scope.curType->parsedFields, parsedField);\n\t\tparsedField = nullptr;\n\t\tbreak;\n\t}\n\tcase CXCursor_VarDecl: \/\/ Static field\n\t{\n\t\tbreak;\n\t}\n\tcase CXCursor_CXXMethod: \/\/ Both static and non-static\n\t{\n\t\tconst coBool staticMethod = clang_CXXMethod_isStatic(_cursor) != 0;\n\t\tif (staticMethod)\n\t\t{\n\n\t\t}\n\t\telse\n\t\t{\n\n\t\t}\n\t\tbreak;\n\t}\n\t}\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseTypes(ParseResult& _result, const CXCursor& _cursor)\n{\n\tcoASSERT(_result.parsedTypes);\n\tScopeInfo scope;\n\tscope.parser = this;\n\tscope.result = &_result;\n\tclang_visitChildren(_cursor, &ParseTypesVisitor, &scope);\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseType(ParseResult& _result, const CXCursor& _cursor)\n{\n\tcoParsedType* parsedType = new coParsedType();\n\tcoDEFER() { delete parsedType; };\n\tparsedType->type = new coType();\n\tcoTRY(ParseSymbol(*parsedType->type, _cursor), nullptr);\n\tScopeInfo scope;\n\tscope.parser = this;\n\tscope.curType = parsedType;\n\tclang_visitChildren(_cursor, &ParseTypeChildrenVisitor, &scope);\n\tcoPushBack(*_result.parsedTypes, parsedType);\n\tparsedType = nullptr; \/\/ Release from defer\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseField(coParsedField& _parsedField, const CXCursor& _cursor)\n{\n\tcoTRY(ParseSymbol(*_parsedField.field, _cursor), nullptr);\n\tconst CXType type = clang_getCursorType(_cursor);\n\tconst CXType canonicalType = clang_getCanonicalType(type);\n\tconst CXCursor typeCursor = clang_getTypeDeclaration(canonicalType);\n\tconst CXString typeSpelling = clang_getCursorSpelling(typeCursor);\n\tcoDEFER() { clang_disposeString(typeSpelling); };\n\t_parsedField.typeName = clang_getCString(typeSpelling);\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseSymbol(coSymbol& _symbol, const CXCursor& _cursor)\n{\n\tconst CXString name = clang_getCursorSpelling(_cursor);\n\tcoDEFER() { clang_disposeString(name); };\n\t_symbol.name = clang_getCString(name);\n\n\tconst CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(_cursor);\n\tif (access == CX_CXXPublic)\n\t\t_symbol.symbolFlags |= coType::PUBLIC;\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseMethod(coParsedFunction& \/*_function*\/, const CXCursor& _cursor)\n{\n\tconst coBool staticMethod = clang_CXXMethod_isStatic(_cursor) != 0;\n\tif (staticMethod)\n\t{\n\n\t}\n\telse\n\t{\n\n\t}\n\treturn true;\n}\n\nCXCursor coClangSourceParser::FindAttribute(const CXCursor& _cursor, const coConstString& _attr)\n{\n\tswitch (_cursor.kind)\n\t{\n\tcase CXCursor_ClassDecl:\n\tcase CXCursor_StructDecl:\n\t{\n\t\tstruct Result\n\t\t{\n\t\t\tResult(const coConstString& _structName) : cursor(clang_getNullCursor()), structName(_structName) {}\n\t\t\tCXCursor cursor;\n\t\t\tconst coConstString& structName;\n\t\t};\n\t\tstatic const coConstString attributePrefix(\"_attribute_\");\n\t\tcoDynamicString structName;\n\t\tstructName << attributePrefix;\n\t\tstructName << _attr;\n\t\tResult result(structName);\n\t\tauto AttributeVisitor = [](CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n\t\t{\n\t\t\tif (_child.kind == CXCursor_StructDecl)\n\t\t\t{\n\t\t\t\tCXString cursorStr = clang_getCursorDisplayName(_child);\n\t\t\t\tcoDEFER() { clang_disposeString(cursorStr); };\n\t\t\t\tconst coConstString name = clang_getCString(cursorStr);\n\t\t\t\tResult* result = static_cast<Result*>(_clientData);\n\t\t\t\tif (name == result->structName)\n\t\t\t\t{\n\t\t\t\t\tresult->cursor = _child;\n\t\t\t\t\treturn CXChildVisit_Break;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn CXChildVisit_Continue;\n\t\t};\n\t\tclang_visitChildren(_cursor, AttributeVisitor, &result);\n\t\treturn result.cursor;\n\t\tbreak;\n\t}\n\t}\n\n\treturn clang_getNullCursor();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"registerhandler.h\"\n\n#include \"debuggeractions.h\"\n#include \"debuggeragents.h\"\n#include \"debuggerconstants.h\"\n#include \"debuggerengine.h\"\n\n#include <utils\/qtcassert.h>\n\n#include <QtCore\/QAbstractTableModel>\n#include <QtCore\/QDebug>\n\n#include <QtGui\/QColor>\n\nusing namespace Debugger;\nusing namespace Debugger::Internal;\nusing namespace Debugger::Constants;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ RegisterHandler\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRegisterHandler::RegisterHandler(DebuggerEngine *engine)\n : m_engine(engine)\n{\n setNumberBase(16);\n}\n\nint RegisterHandler::rowCount(const QModelIndex &parent) const\n{\n return parent.isValid() ? 0 : m_registers.size();\n}\n\nint RegisterHandler::columnCount(const QModelIndex &parent) const\n{\n return parent.isValid() ? 0 : 2;\n}\n\ninline QString RegisterHandler::value(const Register ®, bool padded) const\n{\n bool ok = true;\n \/\/ Try to convert to number?\n const qulonglong value = reg.value.toULongLong(&ok, 0); \/\/ Autodetect format\n if (ok)\n return QString::fromAscii(\"%1\").arg(value, (padded ? m_strlen : 0), m_base);\n \/\/ Cannot convert, return raw string.\n if (padded && reg.value.size() < m_strlen)\n return QString(m_strlen - reg.value.size(), QLatin1Char(' ')) + reg.value;\n return reg.value;\n}\n\nQVariant RegisterHandler::data(const QModelIndex &index, int role) const\n{\n switch (role) {\n case EngineStateRole:\n return m_engine->state();\n\n case EngineCapabilitiesRole:\n return m_engine->debuggerCapabilities();\n\n case EngineActionsEnabledRole:\n return m_engine->debuggerActionsEnabled();\n\n case RegisterNumberBaseRole:\n return m_base;\n }\n\n if (!index.isValid() || index.row() >= m_registers.size())\n return QVariant();\n\n const Register ® = m_registers.at(index.row());\n\n switch (role) {\n case RegisterAddressRole: {\n \/\/ Return some address associated with the register. Autodetect format\n bool ok = true;\n qulonglong value = reg.value.toULongLong(&ok, 0);\n return ok ? QVariant(QString::fromLatin1(\"0x\") + QString::number(value, 16)) : QVariant();\n }\n break;\n\n case Qt::DisplayRole:\n switch (index.column()) {\n case 0: {\n const QString padding = QLatin1String(\" \");\n return QVariant(padding + reg.name + padding);\n }\n case 1: \/\/ Display: Pad value for alignment\n return value(reg, true);\n } \/\/ switch column\n case Qt::EditRole: \/\/ Edit: Unpadded for editing\n return value(reg, false);\n case Qt::TextAlignmentRole:\n return index.column() == 1 ? QVariant(Qt::AlignRight) : QVariant();\n case RegisterChangedRole:\n return QVariant(reg.changed);\n default:\n break;\n }\n return QVariant();\n}\n\nQVariant RegisterHandler::headerData(int section, Qt::Orientation orientation,\n int role) const\n{\n if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {\n switch (section) {\n case 0: return tr(\"Name\");\n case 1: return tr(\"Value (base %1)\").arg(m_base);\n };\n }\n return QVariant();\n}\n\nQt::ItemFlags RegisterHandler::flags(const QModelIndex &idx) const\n{\n using namespace Qt;\n\n if (!idx.isValid())\n return ItemFlags();\n\n static const ItemFlags notEditable =\n ItemIsSelectable\n \/\/ | ItemIsDragEnabled\n \/\/ | ItemIsDropEnabled\n | ItemIsEnabled;\n\n static const ItemFlags editable = notEditable | ItemIsEditable;\n\n if (idx.column() == 1)\n return editable; \/\/ locals and watcher values are editable\n return notEditable;\n}\n\nbool RegisterHandler::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n switch (role) {\n case RequestSetRegisterRole:\n m_engine->setRegisterValue(index.row(), value.toString());\n return true;\n\n case RequestReloadRegistersRole:\n m_engine->reloadRegisters();\n return true;\n\n case RequestShowMemoryRole:\n (void) new MemoryViewAgent(m_engine, value.toString());\n return true;\n\n default:\n return QAbstractTableModel::setData(index, value, role);\n }\n}\n\nvoid RegisterHandler::removeAll()\n{\n m_registers.clear();\n reset();\n}\n\nbool RegisterHandler::isEmpty() const\n{\n return m_registers.isEmpty();\n}\n\nvoid RegisterHandler::setRegisters(const Registers ®isters)\n{\n m_registers = registers;\n calculateWidth();\n reset();\n}\n\nvoid RegisterHandler::setAndMarkRegisters(const Registers ®isters)\n{\n const Registers old = m_registers;\n m_registers = registers;\n for (int i = qMin(m_registers.size(), old.size()); --i >= 0; )\n m_registers[i].changed = m_registers[i].value != old[i].value;\n calculateWidth();\n reset();\n}\n\nRegisters RegisterHandler::registers() const\n{\n return m_registers;\n}\n\nvoid RegisterHandler::calculateWidth()\n{\n m_strlen = (m_base == 2 ? 64 : m_base == 8 ? 32 : m_base == 10 ? 26 : 16);\n foreach(const Register ®, m_registers)\n if (reg.value.size() > m_strlen)\n m_strlen = reg.value.size();\n if (m_strlen > 40) \/\/ Allow for 128bit, but restrict overly ling CDB register arrays.\n m_strlen = 40;\n}\n\nvoid RegisterHandler::setNumberBase(int base)\n{\n if (m_base != base) {\n m_base = base;\n calculateWidth();\n emit reset();\n }\n}\n<commit_msg>Debugger: Make register window smaller (do not pad all values).<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"registerhandler.h\"\n\n#include \"debuggeractions.h\"\n#include \"debuggeragents.h\"\n#include \"debuggerconstants.h\"\n#include \"debuggerengine.h\"\n\n#include <utils\/qtcassert.h>\n\n#include <QtCore\/QAbstractTableModel>\n#include <QtCore\/QDebug>\n\n#include <QtGui\/QColor>\n\nusing namespace Debugger;\nusing namespace Debugger::Internal;\nusing namespace Debugger::Constants;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ RegisterHandler\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRegisterHandler::RegisterHandler(DebuggerEngine *engine)\n : m_engine(engine)\n{\n setNumberBase(16);\n}\n\nint RegisterHandler::rowCount(const QModelIndex &parent) const\n{\n return parent.isValid() ? 0 : m_registers.size();\n}\n\nint RegisterHandler::columnCount(const QModelIndex &parent) const\n{\n return parent.isValid() ? 0 : 2;\n}\n\ninline QString RegisterHandler::value(const Register ®, bool padded) const\n{\n bool ok = true;\n \/\/ Try to convert to number?\n const qulonglong value = reg.value.toULongLong(&ok, 0); \/\/ Autodetect format\n if (ok)\n return QString::fromAscii(\"%1\").arg(value, (padded ? m_strlen : 0), m_base);\n \/\/ Cannot convert, return raw string.\n if (padded && reg.value.size() < m_strlen)\n return QString(m_strlen - reg.value.size(), QLatin1Char(' ')) + reg.value;\n return reg.value;\n}\n\nQVariant RegisterHandler::data(const QModelIndex &index, int role) const\n{\n switch (role) {\n case EngineStateRole:\n return m_engine->state();\n\n case EngineCapabilitiesRole:\n return m_engine->debuggerCapabilities();\n\n case EngineActionsEnabledRole:\n return m_engine->debuggerActionsEnabled();\n\n case RegisterNumberBaseRole:\n return m_base;\n }\n\n if (!index.isValid() || index.row() >= m_registers.size())\n return QVariant();\n\n const Register ® = m_registers.at(index.row());\n\n switch (role) {\n case RegisterAddressRole: {\n \/\/ Return some address associated with the register. Autodetect format\n bool ok = true;\n qulonglong value = reg.value.toULongLong(&ok, 0);\n return ok ? QVariant(QString::fromLatin1(\"0x\") + QString::number(value, 16)) : QVariant();\n }\n break;\n\n case Qt::DisplayRole:\n switch (index.column()) {\n case 0: {\n const QString padding = QLatin1String(\" \");\n return QVariant(padding + reg.name + padding);\n }\n case 1: \/\/ Display: Pad value for alignment\n return value(reg, true);\n } \/\/ switch column\n case Qt::EditRole: \/\/ Edit: Unpadded for editing\n return value(reg, false);\n case Qt::TextAlignmentRole:\n return index.column() == 1 ? QVariant(Qt::AlignRight) : QVariant();\n case RegisterChangedRole:\n return QVariant(reg.changed);\n default:\n break;\n }\n return QVariant();\n}\n\nQVariant RegisterHandler::headerData(int section, Qt::Orientation orientation,\n int role) const\n{\n if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {\n switch (section) {\n case 0: return tr(\"Name\");\n case 1: return tr(\"Value (base %1)\").arg(m_base);\n };\n }\n return QVariant();\n}\n\nQt::ItemFlags RegisterHandler::flags(const QModelIndex &idx) const\n{\n using namespace Qt;\n\n if (!idx.isValid())\n return ItemFlags();\n\n static const ItemFlags notEditable =\n ItemIsSelectable\n \/\/ | ItemIsDragEnabled\n \/\/ | ItemIsDropEnabled\n | ItemIsEnabled;\n\n static const ItemFlags editable = notEditable | ItemIsEditable;\n\n if (idx.column() == 1)\n return editable; \/\/ locals and watcher values are editable\n return notEditable;\n}\n\nbool RegisterHandler::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n switch (role) {\n case RequestSetRegisterRole:\n m_engine->setRegisterValue(index.row(), value.toString());\n return true;\n\n case RequestReloadRegistersRole:\n m_engine->reloadRegisters();\n return true;\n\n case RequestShowMemoryRole:\n (void) new MemoryViewAgent(m_engine, value.toString());\n return true;\n\n default:\n return QAbstractTableModel::setData(index, value, role);\n }\n}\n\nvoid RegisterHandler::removeAll()\n{\n m_registers.clear();\n reset();\n}\n\nbool RegisterHandler::isEmpty() const\n{\n return m_registers.isEmpty();\n}\n\nvoid RegisterHandler::setRegisters(const Registers ®isters)\n{\n m_registers = registers;\n calculateWidth();\n reset();\n}\n\nvoid RegisterHandler::setAndMarkRegisters(const Registers ®isters)\n{\n const Registers old = m_registers;\n m_registers = registers;\n for (int i = qMin(m_registers.size(), old.size()); --i >= 0; )\n m_registers[i].changed = m_registers[i].value != old[i].value;\n calculateWidth();\n reset();\n}\n\nRegisters RegisterHandler::registers() const\n{\n return m_registers;\n}\n\nvoid RegisterHandler::calculateWidth()\n{\n m_strlen = (m_base == 2 ? 64 : m_base == 8 ? 32 : m_base == 10 ? 26 : 16);\n}\n\nvoid RegisterHandler::setNumberBase(int base)\n{\n if (m_base != base) {\n m_base = base;\n calculateWidth();\n emit reset();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"osparser.h\"\n#include \"projectexplorerconstants.h\"\n#include \"task.h\"\n\n#include <utils\/hostosinfo.h>\n\nusing namespace ProjectExplorer;\n\nOsParser::OsParser() :\n m_hasFatalError(false)\n{\n setObjectName(QLatin1String(\"OsParser\"));\n}\n\nvoid OsParser::stdError(const QString &line)\n{\n IOutputParser::stdError(line);\n}\n\nvoid OsParser::stdOutput(const QString &line)\n{\n if (Utils::HostOsInfo::isWindowsHost()) {\n const QString trimmed = line.trimmed();\n if (trimmed == QLatin1String(\"The process cannot access the file because it is being used by another process.\")) {\n addTask(Task(Task::Error, tr(\"The process can not access the file because it is being used by another process.\\n\"\n \"Please close all running instances of your application before starting a build.\"),\n Utils::FileName(), -1, Constants::TASK_CATEGORY_COMPILE));\n m_hasFatalError = true;\n }\n }\n IOutputParser::stdOutput(line);\n}\n\nbool OsParser::hasFatalErrors() const\n{\n return m_hasFatalError || IOutputParser::hasFatalErrors();\n}\n<commit_msg>Linux: Warn on build applications failing due to missing libraries<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"osparser.h\"\n#include \"projectexplorerconstants.h\"\n#include \"task.h\"\n\n#include <utils\/hostosinfo.h>\n\nusing namespace ProjectExplorer;\n\nOsParser::OsParser() :\n m_hasFatalError(false)\n{\n setObjectName(QLatin1String(\"OsParser\"));\n}\n\nvoid OsParser::stdError(const QString &line)\n{\n if (Utils::HostOsInfo::isLinuxHost()) {\n const QString trimmed = line.trimmed();\n if (trimmed.contains(QLatin1String(\": error while loading shared libraries:\"))) {\n addTask(Task(Task::Error, trimmed, Utils::FileName(), -1, Constants::TASK_CATEGORY_COMPILE));\n }\n }\n IOutputParser::stdError(line);\n}\n\nvoid OsParser::stdOutput(const QString &line)\n{\n if (Utils::HostOsInfo::isWindowsHost()) {\n const QString trimmed = line.trimmed();\n if (trimmed == QLatin1String(\"The process cannot access the file because it is being used by another process.\")) {\n addTask(Task(Task::Error, tr(\"The process can not access the file because it is being used by another process.\\n\"\n \"Please close all running instances of your application before starting a build.\"),\n Utils::FileName(), -1, Constants::TASK_CATEGORY_COMPILE));\n m_hasFatalError = true;\n }\n }\n IOutputParser::stdOutput(line);\n}\n\nbool OsParser::hasFatalErrors() const\n{\n return m_hasFatalError || IOutputParser::hasFatalErrors();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include \"lcontrol\/control.h\"\n#include <thread>\n\nusing namespace std::literals;\nusing namespace lcomm;\n\n#define NUM_ITER 20\n#define SLEEP_DELAY 20ms\n\n\/\/ Define to 1 if you want the frames sent to the drone to be printed on stdout.\n#define PRINT_FRAMES 0\n\nnamespace lcontrol {\n\n namespace {\n void printFrame(std::string const& f) {\n#if PRINT_FRAMES\n std::cout << f << '\\n';\n#endif\n }\n }\n\n std::atomic<std::uint32_t> Control::m_seqNum;\n std::unique_ptr<lcomm::ClientSocket> Control::m_sock;\n\n std::string Control::float_to_string(float i) {\n return std::to_string(*reinterpret_cast<std::uint32_t const*>(&i));\n }\n\n void Control::init() {\n m_seqNum = 0;\n m_sock = std::make_unique<ClientSocket>(\"127.0.0.1\", 5556, false);\n }\n\n void Control::enableStabilization() {\n for(int i = 0; i < NUM_ITER; ++i) {\n Control::horizontalPlan(m_seqNum.fetch_add(1), *m_sock);\n std::this_thread::sleep_for(SLEEP_DELAY);\n }\n }\n\n void Control::takeoff() {\n for(int i = 0; i < NUM_ITER; ++i) {\n Control::takeoff(m_seqNum.fetch_add(1), *m_sock);\n std::this_thread::sleep_for(SLEEP_DELAY);\n }\n }\n\n void Control::land() {\n for(int i = 0; i < NUM_ITER; ++i) {\n Control::land(m_seqNum.fetch_add(1), *m_sock);\n std::this_thread::sleep_for(SLEEP_DELAY);\n }\n }\n\n \/\/ Ask the drone to send the navdata :\n \/\/ AT*CONFIG=\"seqNum\",\\\"general:navdata_demo\\\",\\\"TRUE\\\"\\r\n void Control::sendNavData(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*CONFIG=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",\\\"general:navdata_demo\\\",\\\"TRUE\\\"\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Reset the communication watchdog :\n \/\/ AT*COMWDG=\"seqNum\"\\r\n void Control::watchdog(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*COMWD=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \"\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Emergency mode on the drone :\n \/\/ AT*REF=\"seqNum\",290717952\\r\n void Control::emergencyMode(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*REF=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",290717952\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Calibrate the horizontal plan :\n \/\/ AT*FTRIM=\"seqNum\"\\r\n void Control::horizontalPlan(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*FTRIM=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \"\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Calibrate the magnetometer :\n \/\/ AT*CALIB=\"seqNum\",0\\r\n void Control::magnetometer(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*CALIB=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",0\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Take off :\n \/\/ AT*REF=\"seqNum\",290718208\\r\n void Control::takeoff(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*REF=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",290718208\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Land :\n \/\/ AT*REF=\"seqNum\",290717696\\r\n void Control::land(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*REF=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",290717696\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Send a movement to the drone :\n \/\/ AT*PCMD=\"seqNum\",\"flag\",\"leftRightTilt\",\"frontBackTilt\",\"verticalSpeed\",\"angularSpeed\",\\r\n void Control::movement(std::uint32_t seqNum, int flag, float frontBackTilt, float leftRightTilt, float verticalSpeed, float angularSpeed, ClientSocket& s) {\n std::string data(\"AT*PCMD=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",\" + std::to_string(flag) + \",\" + Control::float_to_string(leftRightTilt) + \",\" +\n Control::float_to_string(frontBackTilt) + \",\" + Control::float_to_string(verticalSpeed) + \",\" +\n Control::float_to_string(angularSpeed) + \",\\r\";\n printFrame(data);\n s.write(data);\n }\n}\n<commit_msg>libcontrol has now a blocking connection initialization<commit_after>#include <iostream>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include \"lcontrol\/control.h\"\n#include <thread>\n\nusing namespace std::literals;\nusing namespace lcomm;\n\n#define NUM_ITER 20\n#define SLEEP_DELAY 20ms\n\n\/\/ Define to 1 if you want the frames sent to the drone to be printed on stdout.\n#define PRINT_FRAMES 0\n\nnamespace lcontrol {\n\n namespace {\n void printFrame(std::string const& f) {\n#if PRINT_FRAMES\n std::cout << f << '\\n';\n#endif\n }\n }\n\n std::atomic<std::uint32_t> Control::m_seqNum;\n std::unique_ptr<lcomm::ClientSocket> Control::m_sock;\n\n std::string Control::float_to_string(float i) {\n return std::to_string(*reinterpret_cast<std::uint32_t const*>(&i));\n }\n\n void Control::init() {\n m_seqNum = 0;\n m_sock = std::make_unique<ClientSocket>(\"127.0.0.1\", 5556, false);\n int numAttempt = 0;\n while(!m_sock->opened()) {\n std::cout << \"Waiting for lcontrol's connection \" << numAttempt++ << \"...\" << std::endl;\n std::this_thread::sleep_for(100ms);\n }\n std::cout << \"lcontrol connected!\" << std::endl;\n }\n\n void Control::enableStabilization() {\n for(int i = 0; i < NUM_ITER; ++i) {\n Control::horizontalPlan(m_seqNum.fetch_add(1), *m_sock);\n std::this_thread::sleep_for(SLEEP_DELAY);\n }\n }\n\n void Control::takeoff() {\n for(int i = 0; i < NUM_ITER; ++i) {\n Control::takeoff(m_seqNum.fetch_add(1), *m_sock);\n std::this_thread::sleep_for(SLEEP_DELAY);\n }\n }\n\n void Control::land() {\n for(int i = 0; i < NUM_ITER; ++i) {\n Control::land(m_seqNum.fetch_add(1), *m_sock);\n std::this_thread::sleep_for(SLEEP_DELAY);\n }\n }\n\n \/\/ Ask the drone to send the navdata :\n \/\/ AT*CONFIG=\"seqNum\",\\\"general:navdata_demo\\\",\\\"TRUE\\\"\\r\n void Control::sendNavData(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*CONFIG=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",\\\"general:navdata_demo\\\",\\\"TRUE\\\"\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Reset the communication watchdog :\n \/\/ AT*COMWDG=\"seqNum\"\\r\n void Control::watchdog(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*COMWD=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \"\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Emergency mode on the drone :\n \/\/ AT*REF=\"seqNum\",290717952\\r\n void Control::emergencyMode(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*REF=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",290717952\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Calibrate the horizontal plan :\n \/\/ AT*FTRIM=\"seqNum\"\\r\n void Control::horizontalPlan(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*FTRIM=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \"\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Calibrate the magnetometer :\n \/\/ AT*CALIB=\"seqNum\",0\\r\n void Control::magnetometer(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*CALIB=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",0\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Take off :\n \/\/ AT*REF=\"seqNum\",290718208\\r\n void Control::takeoff(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*REF=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",290718208\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Land :\n \/\/ AT*REF=\"seqNum\",290717696\\r\n void Control::land(std::uint32_t seqNum, ClientSocket& s) {\n std::string data(\"AT*REF=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",290717696\\r\";\n printFrame(data);\n s.write(data);\n }\n\n \/\/ Send a movement to the drone :\n \/\/ AT*PCMD=\"seqNum\",\"flag\",\"leftRightTilt\",\"frontBackTilt\",\"verticalSpeed\",\"angularSpeed\",\\r\n void Control::movement(std::uint32_t seqNum, int flag, float frontBackTilt, float leftRightTilt, float verticalSpeed, float angularSpeed, ClientSocket& s) {\n std::string data(\"AT*PCMD=\");\n std::string seqStr = std::to_string(seqNum);\n data += seqStr + \",\" + std::to_string(flag) + \",\" + Control::float_to_string(leftRightTilt) + \",\" +\n Control::float_to_string(frontBackTilt) + \",\" + Control::float_to_string(verticalSpeed) + \",\" +\n Control::float_to_string(angularSpeed) + \",\\r\";\n printFrame(data);\n s.write(data);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2000 by Norman Kramer\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 \"csengine\/crysball.h\"\n#include \"csgeom\/frustum.h\"\n\nint csCrystalBall::csTriNode::Add (const csCrystalBallVec *normal,\n\tint tri1, int tri2, int tri3, csVector *vP, csVector *vTP)\n{\n int nPos = 0;\n if (IsLeaf ())\n {\n \/\/ we reached the last level\n \/\/ if this leaf is empty just add the polyidx\n \/\/ if the new normal to be added equals the one in this leaf we are done\n \/\/ otherwise we have to split this leaf\n if (len == 0)\n {\n nPos = vP->Insert (from, (void*)normal);\n }\n else\n {\n csCrystalBallVec *n = (csCrystalBallVec*)vP->Get (from);\n\n if (*n == *normal)\n {\n\t\/\/ just append this index\n\tnPos = vP->Insert (from, (void*)normal);\n }\n else\n {\n\t\/\/ split\n\t\/\/ as the splitpoint we just take the middle of old-new (this will\n\t\/\/ ensure, that the old and new point are separated in distinct\n\t\/\/ triangles)\n\tcsVector3 *mc = new csVector3 (*n + (*normal - *n)\/2.0f);\n\tmc->Normalize (); \/\/ now the point lies on the unit sphere\n\tdivider = vTP->Push ((void*)mc);\n\n\tbool bNew=false, bOld=false;\n\n\t\/\/ now decide which triangle the old and the new point(s) will go into\n\tif ((bOld=(Classify (*n, tri1, tri2, divider, vTP) == INSIDE)))\n\t \/\/ contains the original points\n\t AddChild (new csTriNode (this, from, len));\n\telse\n\tif ((bNew=(Classify (*normal, tri1, tri2, divider, vTP) == INSIDE)))\n\t{\n\t csTriNode *tnode = new csTriNode (this, from+len, 0);\n\t AddChild (tnode); \/\/ contains the new point\n\t nPos = tnode->Add (normal, tri1, tri2, divider, vP, vTP);\n\t}\n\telse\n\t AddChild (new csTriNode (this, from+len+1, 0)); \/\/ remains empty\n\n\tif (!bOld && (bOld=(Classify (*n, tri2, tri3, divider, vTP) == INSIDE)))\n\t \/\/ contains the original points\n\t AddChild (new csTriNode (this, from, len));\n\telse\n\tif (!bNew && (bNew=(Classify (*normal, tri2, tri3, divider, vTP)\n\t\t== INSIDE)))\n\t{\n\t csTriNode *tnode = new csTriNode (this, from+len, 0);\n\t \/\/ contains the new point\n\t AddChild (new csTriNode (this, from+len, 1));\n\t nPos = tnode->Add (normal, tri2, tri3, divider, vP, vTP);\n\t}\n\telse\n\t AddChild (new csTriNode (this, from+len+1, 0)); \/\/ remains empty\n\n\tif (!bOld && (bOld=(Classify (*n, tri3, tri1, divider, vTP) == INSIDE)))\n\t \/\/ contains the original points\n\t AddChild (new csTriNode (this, from, len));\n\telse\n\tif (!bNew && (bNew=(Classify (*normal, tri3, tri1, divider, vTP)\n\t\t== INSIDE)))\n\t{\n\t csTriNode *tnode = new csTriNode (this, from+len, 0);\n\t \/\/ contains the new point\n\t AddChild (new csTriNode (this, from+len, 1));\n\t nPos = tnode->Add (normal, tri3, tri1, divider, vP, vTP);\n\t}\n\telse\n\t AddChild (new csTriNode (this, from+len+1, 0)); \/\/ remains empty\n\n }\n }\n } \/\/ IsLeaf ()\n else\n {\n \/\/ ok, this is not a leaf, lets check which subtriangle we have to dive into\n if (Classify (*normal, tri1, tri2, divider, vTP) == INSIDE)\n nPos = ((csTriNode*)children.Get (0))->\n \tAdd (normal, tri1, tri2, divider, vP, vTP);\n else\n if (Classify (*normal, tri2, tri3, divider, vTP) == INSIDE)\n nPos = ((csTriNode*)children.Get (1))->\n \tAdd (normal, tri2, tri3, divider, vP, vTP);\n else\n nPos = ((csTriNode*)children.Get (2))->\n \tAdd (normal, tri3, tri1, divider, vP, vTP);\n }\n return nPos;\n}\n\nvoid csCrystalBall::csTriNode::Adjust (int nPos)\n{\n bool bDive = true;\n if (from > nPos)\n from++;\n else\n if ((from <= nPos && from+len > nPos) || (from == nPos && len == 0))\n len++;\n else\n bDive = false;\n\n if (bDive && !IsLeaf())\n {\n ((csTriNode*)children.Get (0))->Adjust (nPos);\n ((csTriNode*)children.Get (1))->Adjust (nPos);\n ((csTriNode*)children.Get (2))->Adjust (nPos);\n }\n}\n\nint csCrystalBall::csTriNode::Classify (const csVector3 &n, int i1, int i2,\n\t\t\t\t int i3, const csVector *vTP) const\n{\n csVector3 origo (0,0,0);\n\n csFrustum frust (origo);\n frust.AddVertex (*(csVector3*)vTP->Get (i1));\n frust.AddVertex (*(csVector3*)vTP->Get (i2));\n frust.AddVertex (*(csVector3*)vTP->Get (i3));\n\n return (frust.Contains (n)\n \t? csCrystalBall::csTriNode::INSIDE\n\t: csCrystalBall::csTriNode::OUTSIDE);\n}\n\nvoid csCrystalBall::csTriNode::Transform (\n\tconst csMatrix3 &m, csVector &indexVector,\n\tint useSign, long cookie,\n\tconst csVector *vP, const csVector *vTP,\n\tconst csVector3 &v1, const csVector3 &v2,\n\tconst csVector3 &v3)\n{\n \/\/ If the node has no children, we can decide based on the normal\n \/\/ assigned to this triangle.\n if (IsLeaf ())\n {\n if (len>0)\n {\n \/\/ check the normal directly\n csCrystalBallVec *n = (csCrystalBallVec*)vP->Get (from);\n csVector3 tn = m* (*n);\n if (SignMatches (&tn, useSign))\n {\n\t\/\/ add all polygon indices\n\tint to = from+len;\n\tint i;\n\tfor (i=from; i < to; i++)\n\t indexVector.Push ((csSome)((csCrystalBallVec*)vP->Get (i))->\n\t \tGetIndex ());\n }\n }\n }\n else\n {\n const csVector3 *p[4] = {&v1, &v2, &v3, &v1};\n csVector3 td = m* (*(csCrystalBallVec*)vTP->Get (divider));\n\tint i;\n for (i=0; i < 3; i++)\n {\n const csVector3 &n1 = *p[i];\n const csVector3 &n2 = *p[i+1];\n int match = SignMatches (&n1, &n2, &td, useSign);\n\n if (match == 0)\n {\n\t\/\/ all in same half of sphere, sp add them all\n\tcsTriNode *tri = (csTriNode*)children.Get (i);\n\tint to = tri->from+tri->len;\n\tint j;\n\tfor (j=tri->from; j < to; j++)\n\t indexVector.Push ((csSome)((csCrystalBallVec*)vP->Get (j))->\n\t \tGetIndex ());\n }\n else\n if (match == 1)\n {\n\t\/\/ triangle is on both sides of sphere, so dive into subtriangles\n\tTransform (m, indexVector, useSign, cookie, vP, vTP, n1, n2, td);\n }\n }\n }\n}\n\nbool csCrystalBall::csTriNode::SignMatches (const csVector3 *tn, int useSign)\n{\n bool match = false;\n if (useSign < 0)\n {\n if (tn->z <= 0.0)\n match = true;\n else\n if (tn->z >= 0.0)\n match = false;\n }\n else\n {\n if (tn->z >= 0.0)\n match = true;\n else\n if (tn->z <= 0.0)\n match = false;\n }\n return match;\n}\n\nint csCrystalBall::csTriNode::SignMatches (\n\tconst csVector3 *n1, const csVector3 *n2,\n\tconst csVector3 *td, int useSign)\n{\n int match;\n if (useSign < 0)\n {\n if (n1->z <= 0.0 && n2->z <= 0.0 && td->z <= 0.0)\n match = 0;\n else\n if (n1->z >= 0.0 && n2->z >= 0.0 && td->z >= 0.0)\n match = 2;\n else\n match = 1;\n }\n else\n {\n if (n1->z >= 0.0 && n2->z >= 0.0 && td->z >= 0.0)\n match = 0;\n else\n if (n1->z <= 0.0 && n2->z <= 0.0 && td->z <= 0.0)\n match = 2;\n else\n match = 1;\n }\n return match;\n}\n\ncsCrystalBall::csCrystalBall ()\n{\n \/\/ standard axis points from which we'll create the initial 8 triangles\n vTrianglePoints.Push (new csVector3 (1,0,0));\n vTrianglePoints.Push (new csVector3 (0,1,0));\n vTrianglePoints.Push (new csVector3 (0,0,1));\n vTrianglePoints.Push (new csVector3 (-1,0,0));\n vTrianglePoints.Push (new csVector3 (0,-1,0));\n vTrianglePoints.Push (new csVector3 (0,0,-1));\n}\n\ncsCrystalBall::~csCrystalBall ()\n{\n int i;\n for (i=0; i < vTrianglePoints.Length (); i++)\n delete (csVector3*)vTrianglePoints.Get (i);\n for (i=0; i < vPoints.Length (); i++)\n delete (csCrystalBallVec*)vPoints.Get (i);\n}\n\nvoid csCrystalBall::InsertPolygon (iPolygonMesh *polyset, int idx)\n{\n csMeshedPolygon &mp = polyset->GetPolygons ()[idx];\n \/\/ calc the normal first\n csCrystalBallVec *n = new csCrystalBallVec (idx);\n csMath3::CalcNormal (*n, polyset->GetVertices ()[mp.vertices[0]],\n\t\t polyset->GetVertices ()[mp.vertices[1]],\n\t\t polyset->GetVertices ()[mp.vertices[2]]\n\t\t );\n \/\/ which of the 8 starting triangles we add this to ?\n int i1 = 0, i2 = 0, i3 = 0, i = 0;\n if (n->y < 0)\n i += 4;\n if (n->z < 0)\n i += 2;\n if (n->x >= 0)\n i += 1;\n\n switch (i)\n {\n case 0: i1=3; i2=1; i2=2; break;\n case 1: i1=0; i2=1; i2=2; break;\n case 2: i1=3; i2=1; i2=5; break;\n case 3: i1=0; i2=1; i2=5; break;\n case 4: i1=3; i2=4; i2=2; break;\n case 5: i1=0; i2=4; i2=2; break;\n case 6: i1=3; i2=4; i2=5; break;\n case 7: i1=0; i2=4; i2=5; break;\n }\n\n int nPos = tri[i].Add (n, i1, i2, i3, &vPoints, &vTrianglePoints);\n for (i=0; i < 7; i++)\n tri[i].Adjust (nPos);\n}\n\nvoid csCrystalBall::Build (iPolygonMesh *polyset)\n{\n \/\/ just cycle through all polygons and add them\n int i;\n for (i=0; i<polyset->GetPolygonCount (); i++)\n InsertPolygon (polyset, i);\n}\n\nvoid csCrystalBall::Transform (const csTransform &o2c, csVector &indexVector,\n\t\t\t int useSign, long cookie)\n{\n \/\/ fill indexVector with the indices to those polygons that have a\n \/\/ normal vector with sign(z-coordinate) == <useSign>\n\n \/\/ first check the base triangles\n \/\/ for this we simply check the base vectors - luckily the form a unit matrix\n \/\/ so we can simply check o2c.\n\n const csMatrix3 &m = o2c.GetO2T ();\n csVector3 e1 = m.Col1 ();\n csVector3 e2 = m.Col2 ();\n csVector3 e3 = m.Col3 ();\n csVector3 ne1 = -1 * e1;\n csVector3 ne2 = -1 * e2;\n csVector3 ne3 = -1 * e3;\n\n tri[0].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, ne1, e2, e3);\n tri[1].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, e1, e2, e3);\n tri[2].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, ne1, e2, ne3);\n tri[3].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, e1, e2, ne3);\n tri[4].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, ne1, ne2, e3);\n tri[5].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, e1, ne2, e3);\n tri[6].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, ne1, ne2, ne3);\n tri[7].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, e1, ne2, ne3);\n}\n<commit_msg>Elimated the assignments within conditional expression wanings under MSVC and also cleaned up the code.<commit_after>\/*\n Copyright (C) 2000 by Norman Kramer\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 \"csengine\/crysball.h\"\n#include \"csgeom\/frustum.h\"\n\nint csCrystalBall::csTriNode::Add (const csCrystalBallVec *normal,\n\tint tri1, int tri2, int tri3, csVector *vP, csVector *vTP)\n{\n int nPos = 0;\n if (IsLeaf ())\n {\n \/\/ we reached the last level\n \/\/ if this leaf is empty just add the polyidx\n \/\/ if the new normal to be added equals the one in this leaf we are done\n \/\/ otherwise we have to split this leaf\n if (len == 0)\n {\n nPos = vP->Insert (from, (void*)normal);\n }\n else\n {\n csCrystalBallVec *n = (csCrystalBallVec*)vP->Get (from);\n\n if (*n == *normal)\n {\n\t\/\/ just append this index\n\tnPos = vP->Insert (from, (void*)normal);\n }\n else\n {\n\t\/\/ split\n\t\/\/ as the splitpoint we just take the middle of old-new (this will\n\t\/\/ ensure, that the old and new point are separated in distinct\n\t\/\/ triangles)\n\tcsVector3 *mc = new csVector3 (*n + (*normal - *n)\/2.0f);\n\tmc->Normalize (); \/\/ now the point lies on the unit sphere\n\tdivider = vTP->Push ((void*)mc);\n\n\tbool bNew = false, bOld = false;\n\n\t\/\/ now decide which triangle the old and the new point(s) will go into\n bOld = Classify (*n, tri1, tri2, divider, vTP);\n\tif (bOld == INSIDE)\n {\n\t \/\/ contains the original points\n\t AddChild (new csTriNode (this, from, len));\n }\n\telse\n {\n bNew = Classify (*normal, tri1, tri2, divider, vTP);\n if (bNew == INSIDE)\n {\n csTriNode *tnode = new csTriNode (this, from+len, 0);\n AddChild (tnode); \/\/ contains the new point\n nPos = tnode->Add (normal, tri1, tri2, divider, vP, vTP);\n }\n else\n AddChild (new csTriNode (this, from+len+1, 0)); \/\/ remains empty\n }\n\n bOld = Classify (*n, tri2, tri3, divider, vTP);\n\tif (!bOld && bOld == INSIDE)\n {\n\t \/\/ contains the original points\n\t AddChild (new csTriNode (this, from, len));\n }\n\telse\n {\n bNew = Classify (*normal, tri2, tri3, divider, vTP);\n if (!bNew && bNew == INSIDE)\n {\n csTriNode *tnode = new csTriNode (this, from+len, 0);\n \/\/ contains the new point\n AddChild (new csTriNode (this, from+len, 1));\n nPos = tnode->Add (normal, tri2, tri3, divider, vP, vTP);\n }\n else\n AddChild (new csTriNode (this, from+len+1, 0)); \/\/ remains empty\n }\n\n bOld = Classify (*n, tri3, tri1, divider, vTP);\n\tif (!bOld && bOld == INSIDE)\n {\n\t \/\/ contains the original points\n\t AddChild (new csTriNode (this, from, len));\n }\n\telse\n {\n bNew = Classify (*normal, tri3, tri1, divider, vTP);\n if (!bNew && bNew== INSIDE)\n {\n csTriNode *tnode = new csTriNode (this, from+len, 0);\n \/\/ contains the new point\n AddChild (new csTriNode (this, from+len, 1));\n nPos = tnode->Add (normal, tri3, tri1, divider, vP, vTP);\n }\n else\n AddChild (new csTriNode (this, from+len+1, 0)); \/\/ remains empty\n }\n\n }\n }\n } \/\/ IsLeaf ()\n else\n {\n \/\/ ok, this is not a leaf, lets check which subtriangle we have to dive into\n if (Classify (*normal, tri1, tri2, divider, vTP) == INSIDE)\n nPos = ((csTriNode*)children.Get (0))->\n \tAdd (normal, tri1, tri2, divider, vP, vTP);\n else\n if (Classify (*normal, tri2, tri3, divider, vTP) == INSIDE)\n nPos = ((csTriNode*)children.Get (1))->\n \tAdd (normal, tri2, tri3, divider, vP, vTP);\n else\n nPos = ((csTriNode*)children.Get (2))->\n \tAdd (normal, tri3, tri1, divider, vP, vTP);\n }\n return nPos;\n}\n\nvoid csCrystalBall::csTriNode::Adjust (int nPos)\n{\n bool bDive = true;\n if (from > nPos)\n from++;\n else\n if ((from <= nPos && from+len > nPos) || (from == nPos && len == 0))\n len++;\n else\n bDive = false;\n\n if (bDive && !IsLeaf())\n {\n ((csTriNode*)children.Get (0))->Adjust (nPos);\n ((csTriNode*)children.Get (1))->Adjust (nPos);\n ((csTriNode*)children.Get (2))->Adjust (nPos);\n }\n}\n\nint csCrystalBall::csTriNode::Classify (const csVector3 &n, int i1, int i2,\n\t\t\t\t int i3, const csVector *vTP) const\n{\n csVector3 origo (0,0,0);\n\n csFrustum frust (origo);\n frust.AddVertex (*(csVector3*)vTP->Get (i1));\n frust.AddVertex (*(csVector3*)vTP->Get (i2));\n frust.AddVertex (*(csVector3*)vTP->Get (i3));\n\n return (frust.Contains (n)\n \t? csCrystalBall::csTriNode::INSIDE\n\t: csCrystalBall::csTriNode::OUTSIDE);\n}\n\nvoid csCrystalBall::csTriNode::Transform (\n\tconst csMatrix3 &m, csVector &indexVector,\n\tint useSign, long cookie,\n\tconst csVector *vP, const csVector *vTP,\n\tconst csVector3 &v1, const csVector3 &v2,\n\tconst csVector3 &v3)\n{\n \/\/ If the node has no children, we can decide based on the normal\n \/\/ assigned to this triangle.\n if (IsLeaf ())\n {\n if (len>0)\n {\n \/\/ check the normal directly\n csCrystalBallVec *n = (csCrystalBallVec*)vP->Get (from);\n csVector3 tn = m* (*n);\n if (SignMatches (&tn, useSign))\n {\n\t\/\/ add all polygon indices\n\tint to = from+len;\n\tint i;\n\tfor (i=from; i < to; i++)\n\t indexVector.Push ((csSome)((csCrystalBallVec*)vP->Get (i))->\n\t \tGetIndex ());\n }\n }\n }\n else\n {\n const csVector3 *p[4] = {&v1, &v2, &v3, &v1};\n csVector3 td = m* (*(csCrystalBallVec*)vTP->Get (divider));\n\tint i;\n for (i=0; i < 3; i++)\n {\n const csVector3 &n1 = *p[i];\n const csVector3 &n2 = *p[i+1];\n int match = SignMatches (&n1, &n2, &td, useSign);\n\n if (match == 0)\n {\n\t\/\/ all in same half of sphere, sp add them all\n\tcsTriNode *tri = (csTriNode*)children.Get (i);\n\tint to = tri->from+tri->len;\n\tint j;\n\tfor (j=tri->from; j < to; j++)\n\t indexVector.Push ((csSome)((csCrystalBallVec*)vP->Get (j))->\n\t \tGetIndex ());\n }\n else\n if (match == 1)\n {\n\t\/\/ triangle is on both sides of sphere, so dive into subtriangles\n\tTransform (m, indexVector, useSign, cookie, vP, vTP, n1, n2, td);\n }\n }\n }\n}\n\nbool csCrystalBall::csTriNode::SignMatches (const csVector3 *tn, int useSign)\n{\n bool match = false;\n if (useSign < 0)\n {\n if (tn->z <= 0.0)\n match = true;\n else\n if (tn->z >= 0.0)\n match = false;\n }\n else\n {\n if (tn->z >= 0.0)\n match = true;\n else\n if (tn->z <= 0.0)\n match = false;\n }\n return match;\n}\n\nint csCrystalBall::csTriNode::SignMatches (\n\tconst csVector3 *n1, const csVector3 *n2,\n\tconst csVector3 *td, int useSign)\n{\n int match;\n if (useSign < 0)\n {\n if (n1->z <= 0.0 && n2->z <= 0.0 && td->z <= 0.0)\n match = 0;\n else\n if (n1->z >= 0.0 && n2->z >= 0.0 && td->z >= 0.0)\n match = 2;\n else\n match = 1;\n }\n else\n {\n if (n1->z >= 0.0 && n2->z >= 0.0 && td->z >= 0.0)\n match = 0;\n else\n if (n1->z <= 0.0 && n2->z <= 0.0 && td->z <= 0.0)\n match = 2;\n else\n match = 1;\n }\n return match;\n}\n\ncsCrystalBall::csCrystalBall ()\n{\n \/\/ standard axis points from which we'll create the initial 8 triangles\n vTrianglePoints.Push (new csVector3 (1,0,0));\n vTrianglePoints.Push (new csVector3 (0,1,0));\n vTrianglePoints.Push (new csVector3 (0,0,1));\n vTrianglePoints.Push (new csVector3 (-1,0,0));\n vTrianglePoints.Push (new csVector3 (0,-1,0));\n vTrianglePoints.Push (new csVector3 (0,0,-1));\n}\n\ncsCrystalBall::~csCrystalBall ()\n{\n int i;\n for (i=0; i < vTrianglePoints.Length (); i++)\n delete (csVector3*)vTrianglePoints.Get (i);\n for (i=0; i < vPoints.Length (); i++)\n delete (csCrystalBallVec*)vPoints.Get (i);\n}\n\nvoid csCrystalBall::InsertPolygon (iPolygonMesh *polyset, int idx)\n{\n csMeshedPolygon &mp = polyset->GetPolygons ()[idx];\n \/\/ calc the normal first\n csCrystalBallVec *n = new csCrystalBallVec (idx);\n csMath3::CalcNormal (*n, polyset->GetVertices ()[mp.vertices[0]],\n\t\t polyset->GetVertices ()[mp.vertices[1]],\n\t\t polyset->GetVertices ()[mp.vertices[2]]\n\t\t );\n \/\/ which of the 8 starting triangles we add this to ?\n int i1 = 0, i2 = 0, i3 = 0, i = 0;\n if (n->y < 0)\n i += 4;\n if (n->z < 0)\n i += 2;\n if (n->x >= 0)\n i += 1;\n\n switch (i)\n {\n case 0: i1=3; i2=1; i2=2; break;\n case 1: i1=0; i2=1; i2=2; break;\n case 2: i1=3; i2=1; i2=5; break;\n case 3: i1=0; i2=1; i2=5; break;\n case 4: i1=3; i2=4; i2=2; break;\n case 5: i1=0; i2=4; i2=2; break;\n case 6: i1=3; i2=4; i2=5; break;\n case 7: i1=0; i2=4; i2=5; break;\n }\n\n int nPos = tri[i].Add (n, i1, i2, i3, &vPoints, &vTrianglePoints);\n for (i=0; i < 7; i++)\n tri[i].Adjust (nPos);\n}\n\nvoid csCrystalBall::Build (iPolygonMesh *polyset)\n{\n \/\/ just cycle through all polygons and add them\n int i;\n for (i=0; i<polyset->GetPolygonCount (); i++)\n InsertPolygon (polyset, i);\n}\n\nvoid csCrystalBall::Transform (const csTransform &o2c, csVector &indexVector,\n\t\t\t int useSign, long cookie)\n{\n \/\/ fill indexVector with the indices to those polygons that have a\n \/\/ normal vector with sign(z-coordinate) == <useSign>\n\n \/\/ first check the base triangles\n \/\/ for this we simply check the base vectors - luckily the form a unit matrix\n \/\/ so we can simply check o2c.\n\n const csMatrix3 &m = o2c.GetO2T ();\n csVector3 e1 = m.Col1 ();\n csVector3 e2 = m.Col2 ();\n csVector3 e3 = m.Col3 ();\n csVector3 ne1 = -1 * e1;\n csVector3 ne2 = -1 * e2;\n csVector3 ne3 = -1 * e3;\n\n tri[0].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, ne1, e2, e3);\n tri[1].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, e1, e2, e3);\n tri[2].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, ne1, e2, ne3);\n tri[3].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, e1, e2, ne3);\n tri[4].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, ne1, ne2, e3);\n tri[5].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, e1, ne2, e3);\n tri[6].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, ne1, ne2, ne3);\n tri[7].Transform (m, indexVector, useSign, cookie, &vPoints,\n \t&vTrianglePoints, e1, ne2, ne3);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\r\n\r\nvoid*\tNULLC::defaultAlloc(int size)\r\n{\r\n\treturn ::new(std::nothrow) char[size];\r\n}\r\nvoid\tNULLC::defaultDealloc(void* ptr)\r\n{\r\n\t::delete[] (char*)ptr;\r\n}\r\n\r\nvoid*\t(*NULLC::alloc)(int) = NULLC::defaultAlloc;\r\nvoid\t(*NULLC::dealloc)(void*) = NULLC::defaultDealloc;\r\n\r\nvoid* NULLC::alignedAlloc(int size)\r\n{\r\n\tvoid *unaligned = alloc((size + 16 - 1) + sizeof(void*));\r\n\tif(!unaligned)\r\n\t\treturn NULL;\r\n\tvoid *ptr = (void*)(((intptr_t)unaligned + sizeof(void*) + 16 - 1) & ~(16 - 1));\r\n\tmemcpy((void**)ptr - 1, &unaligned, sizeof(unaligned));\r\n\treturn ptr;\r\n}\r\n\r\nvoid* NULLC::alignedAlloc(int size, int extraSize)\r\n{\r\n\tvoid *unaligned = alloc((size + 16 - 1) + sizeof(void*) + extraSize);\r\n\tif(!unaligned)\r\n\t\treturn NULL;\r\n\tvoid *ptr = (void*)((((intptr_t)unaligned + sizeof(void*) + extraSize + 16 - 1) & ~(16 - 1)) - extraSize);\r\n\tmemcpy((void**)ptr - 1, &unaligned, sizeof(unaligned));\r\n\treturn ptr;\r\n}\r\n\r\nvoid NULLC::alignedDealloc(void* ptr)\r\n{\r\n\tvoid* unaligned = NULL;\r\n\tmemcpy(&unaligned, (void**)ptr - 1, sizeof(unaligned));\r\n\tdealloc(unaligned);\r\n}\r\n\r\nconst char* NULLC::defaultFileLoad(const char* name, unsigned* size)\r\n{\r\n\tassert(name);\r\n\tassert(size);\r\n\r\n\tFILE *file = fopen(name, \"rb\");\r\n\tif(file)\r\n\t{\r\n\t\tfseek(file, 0, SEEK_END);\r\n\t\t*size = ftell(file);\r\n\t\tfseek(file, 0, SEEK_SET);\r\n\t\tchar *fileContent = (char*)NULLC::alloc(*size + 1);\r\n\t\tunsigned read = (unsigned)fread(fileContent, 1, *size, file);\r\n\r\n\t\tif(read != *size)\r\n\t\t{\r\n\t\t\tNULLC::dealloc(fileContent);\r\n\t\t\t*size = 0;\r\n\t\t\treturn NULL;\r\n\t\t}\r\n\r\n\t\tfileContent[*size] = 0;\r\n\t\tfclose(file);\r\n\t\treturn fileContent;\r\n\t}\r\n\t*size = 0;\r\n\treturn NULL;\r\n}\r\n\r\nvoid NULLC::defaultFileFree(const char* data)\r\n{\r\n\tif(data)\r\n\t\tNULLC::dealloc((char*)data);\r\n}\r\n\r\nconst char* (*NULLC::fileLoad)(const char*, unsigned*) = NULLC::defaultFileLoad;\r\nvoid (*NULLC::fileFree)(const char*) = NULLC::defaultFileFree;\r\n<commit_msg>Fixed file handle leak after file read failure<commit_after>#include \"stdafx.h\"\r\n\r\nvoid*\tNULLC::defaultAlloc(int size)\r\n{\r\n\treturn ::new(std::nothrow) char[size];\r\n}\r\nvoid\tNULLC::defaultDealloc(void* ptr)\r\n{\r\n\t::delete[] (char*)ptr;\r\n}\r\n\r\nvoid*\t(*NULLC::alloc)(int) = NULLC::defaultAlloc;\r\nvoid\t(*NULLC::dealloc)(void*) = NULLC::defaultDealloc;\r\n\r\nvoid* NULLC::alignedAlloc(int size)\r\n{\r\n\tvoid *unaligned = alloc((size + 16 - 1) + sizeof(void*));\r\n\tif(!unaligned)\r\n\t\treturn NULL;\r\n\tvoid *ptr = (void*)(((intptr_t)unaligned + sizeof(void*) + 16 - 1) & ~(16 - 1));\r\n\tmemcpy((void**)ptr - 1, &unaligned, sizeof(unaligned));\r\n\treturn ptr;\r\n}\r\n\r\nvoid* NULLC::alignedAlloc(int size, int extraSize)\r\n{\r\n\tvoid *unaligned = alloc((size + 16 - 1) + sizeof(void*) + extraSize);\r\n\tif(!unaligned)\r\n\t\treturn NULL;\r\n\tvoid *ptr = (void*)((((intptr_t)unaligned + sizeof(void*) + extraSize + 16 - 1) & ~(16 - 1)) - extraSize);\r\n\tmemcpy((void**)ptr - 1, &unaligned, sizeof(unaligned));\r\n\treturn ptr;\r\n}\r\n\r\nvoid NULLC::alignedDealloc(void* ptr)\r\n{\r\n\tvoid* unaligned = NULL;\r\n\tmemcpy(&unaligned, (void**)ptr - 1, sizeof(unaligned));\r\n\tdealloc(unaligned);\r\n}\r\n\r\nconst char* NULLC::defaultFileLoad(const char* name, unsigned* size)\r\n{\r\n\tassert(name);\r\n\tassert(size);\r\n\r\n\tFILE *file = fopen(name, \"rb\");\r\n\tif(file)\r\n\t{\r\n\t\tfseek(file, 0, SEEK_END);\r\n\t\t*size = ftell(file);\r\n\t\tfseek(file, 0, SEEK_SET);\r\n\t\tchar *fileContent = (char*)NULLC::alloc(*size + 1);\r\n\t\tunsigned read = (unsigned)fread(fileContent, 1, *size, file);\r\n\r\n\t\tif(read != *size)\r\n\t\t{\r\n\t\t\tNULLC::dealloc(fileContent);\r\n\t\t\t*size = 0;\r\n\r\n\t\t\tfclose(file);\r\n\t\t\treturn NULL;\r\n\t\t}\r\n\r\n\t\tfileContent[*size] = 0;\r\n\t\tfclose(file);\r\n\t\treturn fileContent;\r\n\t}\r\n\t*size = 0;\r\n\treturn NULL;\r\n}\r\n\r\nvoid NULLC::defaultFileFree(const char* data)\r\n{\r\n\tif(data)\r\n\t\tNULLC::dealloc((char*)data);\r\n}\r\n\r\nconst char* (*NULLC::fileLoad)(const char*, unsigned*) = NULLC::defaultFileLoad;\r\nvoid (*NULLC::fileFree)(const char*) = NULLC::defaultFileFree;\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * PointerAgent.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Tue Aug 30 2005.\n * Copyright (c) 2005 Alyssa Milburn. 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 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 *\/\n\n#include \"PointerAgent.h\"\n#include \"openc2e.h\"\n#include \"World.h\"\n#include \"Engine.h\"\n#include \"caosVM.h\"\n#include \"Room.h\"\n\n\/\/ TODO: change imagecount?\nPointerAgent::PointerAgent(std::string spritefile) : SimpleAgent(2, 1, 1, INT_MAX, spritefile, 0, 0) {\n\tname = \"hand\";\n\thandle_events = true;\n\tholdingWire = 0;\n\twireOriginID = 0;\n\t\/\/ TODO: verify attributes on the pointer in c2e\n\tattr.setInt(256); \/\/ camera shy\n}\n\nvoid PointerAgent::finishInit() {\n\tAgent::finishInit();\n\n\t\/\/ float relative to main camera\n\tattr.setInt(attr.getInt() & 32);\n\tfloatSetup();\n}\n\n\/\/ TODO: this should have a queueScript equiv too\nvoid PointerAgent::firePointerScript(unsigned short event, Agent *src) {\n\tassert(src); \/\/ TODO: I \/think\/ this should only be called by the engine..\n\tshared_ptr<script> s = src->findScript(event);\n\tif (!s && engine.version < 3) { \/\/ TODO: are we sure this doesn't apply to c2e?\n\t\ts = findScript(event); \/\/ TODO: we should make sure this actually belongs to the pointer agent and isn't a fallback, maybe\n\t}\n\tif (!s) return;\n\tif (!vm) vm = world.getVM(this);\n\tif (vm->fireScript(s, false, src)) { \/\/ TODO: should FROM be src?\n\t\tvm->setTarg(this);\n\t\tzotstack();\n\t}\n}\n\nvoid PointerAgent::physicsTick() {\n\t\/\/ TODO: this is a hack, which does nothing, because we set a velocity in main() but also move the cursor manually\n}\n\nvoid PointerAgent::kill() {\n\t\/\/ pointer agent isn't killable\n}\n\nvoid PointerAgent::handleEvent(SomeEvent &event) {\n\tif (event.type == eventmousemove) {\n\t\tmoveTo(event.x + world.camera.getX(), event.y + world.camera.getY());\n\t\tvelx.setInt(event.xrel * 4);\n\t\tvely.setInt(event.yrel * 4);\n\n\t\t\/\/ middle mouse button scrolling\n\t\tif (event.button & buttonmiddle)\n\t\t\tworld.camera.moveTo(world.camera.getX() - event.xrel, world.camera.getY() - event.yrel, jump);\n\t} else if (!handle_events) {\n\t\t\/* mouse move events are (apparently - see eg C3 agent help) still handled with handle_events disabled, but nothing else *\/\n\t\treturn;\n\t} else if (event.type == eventmousebuttondown) {\n\t\t\/\/ do our custom handling\n\t\tif (event.button == buttonleft) {\n\t\t\tCompoundPart *a = world.partAt(x, y);\n\t\t\tif (a \/* && a->canActivate() *\/) { \/\/ TODO\n\t\t\t\tAgent* parent = a->getParent();\n\n\t\t\t\tint eve = -1;\n\t\t\t\n\t\t\t\tbool foundport = false;\n\t\t\t\tif (engine.version > 2) {\n\t\t\t\t\tfor (std::map<unsigned int, boost::shared_ptr<OutputPort> >::iterator i = parent->outports.begin();\n\t\t\t\t\t\t\t i != parent->outports.end(); i++) {\n\t\t\t\t\t\t\/\/ TODO: 4 is a magic number i pulled out of nooooowhere\n\t\t\t\t\t\tif (abs(i->second->x + parent->x - x) < 4 && abs(i->second->y + parent->y - y) < 4) {\n\t\t\t\t\t\t\tfoundport = true;\n\t\t\t\t\t\t\tif (holdingWire == 2) {\n\t\t\t\t\t\t\t\tparent->join(i->first, wireOriginAgent, wireOriginID);\n\t\t\t\t\t\t\t\tholdingWire = 0;\n\t\t\t\t\t\t\t\teve = 111;\n\t\t\t\t\t\t\t} else if (holdingWire == 0) {\n\t\t\t\t\t\t\t\teve = 110;\n\t\t\t\t\t\t\t\tholdingWire = 1;\n\t\t\t\t\t\t\t\twireOriginAgent = parent;\n\t\t\t\t\t\t\t\twireOriginID = i->first;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!foundport) {\n\t\t\t\t\t\tfor (std::map<unsigned int, boost::shared_ptr<InputPort> >::iterator i = parent->inports.begin();\n\t\t\t\t\t\t\t\t i != parent->inports.end(); i++) {\n\t\t\t\t\t\t\t\/\/ TODO: 4 is a magic number i pulled out of nooooowhere\n\t\t\t\t\t\t\tif (abs(i->second->x + parent->x - x) < 4 && abs(i->second->y + parent->y - y) < 4) {\n\t\t\t\t\t\t\t\tfoundport = true;\n\t\t\t\t\t\t\t\tif (holdingWire == 1) {\n\t\t\t\t\t\t\t\t\twireOriginAgent->join(wireOriginID, parent, i->first);\n\t\t\t\t\t\t\t\t\tholdingWire = 0;\n\t\t\t\t\t\t\t\t\teve = 111;\n\t\t\t\t\t\t\t\t} else if (holdingWire == 0) {\n\t\t\t\t\t\t\t\t\teve = 110;\n\t\t\t\t\t\t\t\t\tholdingWire = 2;\n\t\t\t\t\t\t\t\t\twireOriginAgent = parent;\n\t\t\t\t\t\t\t\t\twireOriginID = i->first;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\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}\n\n\t\t\t\tif (!foundport) {\n\t\t\t\t\tif (holdingWire) {\n\t\t\t\t\t\tholdingWire = 0;\n\t\t\t\t\t\teve = 113;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ if the agent isn't paused, tell it to handle a click\n\t\t\t\t\t\tint scriptid = a->handleClick(x - a->x - parent->x, y - a->y - parent->y);\n\t\t\t\t\t\tif (scriptid != -1) {\n\t\t\t\t\t\t\t\/\/ fire the script\n\t\t\t\t\t\t\t\/\/ _p1_ is id of part for button clicks, according to Edynn code\n\t\t\t\t\t\t\t\/\/ TODO: should _p1_ always be set? :)\n\t\t\t\t\t\t\tif (!parent->paused) parent->queueScript(scriptid, world.hand(), (int)a->id);\n\n\t\t\t\t\t\t\t\/\/ annoyingly queueScript doesn't reliably tell us if it did anything useful.\n\t\t\t\t\t\t\t\/\/ TODO: work out the mess which is queueScript's return values etc\n\t\t\t\t\t\t\tif (!parent->findScript(scriptid)) return;\n\n\t\t\t\t\t\t\t\/\/ fire the associated pointer script too, if necessary\n\t\t\t\t\t\t\t\/\/ TODO: fuzzie has no idea if this code is remotely correct\n\t\t\t\t\t\t\tif (engine.version < 3) {\n\t\t\t\t\t\t\t\teve = 50;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\teve = 101; \/\/ Pointer Activate 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tswitch (scriptid) {\n\t\t\t\t\t\t\t\tcase 0: eve += 2; break; \/\/ deactivate\n\t\t\t\t\t\t\t\tcase 1: break; \/\/ activate 1\n\t\t\t\t\t\t\t\tcase 2: eve += 1; break; \/\/ activate 2\n\t\t\t\t\t\t\t\tdefault: return;\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}\n\n\t\t\t\tif (eve != -1) firePointerScript(eve, a->getParent());\n\t\t\t} else if (engine.version > 2) {\n\t\t\t\tif (holdingWire) {\n\t\t\t\t\tholdingWire = 0;\n\t\t\t\t\tqueueScript(113, 0);\n\t\t\t\t} else {\n\t\t\t\t\tqueueScript(116, 0); \/\/ Pointer Clicked Background\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.button == buttonright) {\n\t\t\tif (world.paused) return; \/\/ TODO: wrong?\n\t\t\t\t\t\t\t\n\t\t\t\/\/ picking up and dropping are implictly handled by the scripts (well,\n\t\t\t\/\/ messages) 4 and 5\tTODO: check if this is correct behaviour, one issue\n\t\t\t\/\/ is that this isn't instant, another is the messages might only be\n\t\t\t\/\/ fired in c2e when you use MESG WRIT, in which case we'll need to\n\t\t\t\/\/ manually set carrying to NULL and a here, respectively - fuzzie\n\t\t\tif (carrying) {\n\t\t\t\t\/\/ TODO: c1 support - these attributes are invalid for c1\n\t\t\t\tif (!carrying->suffercollisions() || (carrying->validInRoomSystem() || engine.version == 1)) {\n\t\t\t\t\tcarrying->queueScript(5, this); \/\/ drop\n\n\t\t\t\t\tint eve; if (engine.version < 3) eve = 54; else eve = 105;\n\t\t\t\t\tfirePointerScript(eve, carrying); \/\/ Pointer Drop\n\n\t\t\t\t\t\/\/ TODO: is this the correct check?\n\t\t\t\t\tif (carrying->sufferphysics() && carrying->suffercollisions()) {\n\t\t\t\t\t\t\/\/ TODO: do this in the pointer agent?\n\t\t\t\t\t\tcarrying->velx.setFloat(velx.getFloat());\n\t\t\t\t\t\tcarrying->vely.setFloat(vely.getFloat());\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ TODO: some kind of \"fail to drop\" animation\/sound?\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tAgent *a = world.agentAt(x, y, false, true);\n\t\t\t\tif (a) {\n\t\t\t\t\ta->queueScript(4, this); \/\/ pickup\n\n\t\t\t\t\tint eve; if (engine.version < 3) eve = 53; else eve = 104;\n\t\t\t\t\tfirePointerScript(eve, a); \/\/ Pointer Pickup\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.button == buttonmiddle) {\n\t\t\tstd::vector<shared_ptr<Room> > rooms = world.map.roomsAt(event.x + world.camera.getX(), event.y + world.camera.getY());\n\t\t\tif (rooms.size() > 0) std::cout << \"Room at cursor is \" << rooms[0]->id << std::endl;\n\t\t\tAgent *a = world.agentAt(event.x + world.camera.getX(), event.y + world.camera.getY(), true);\n\t\t\tif (a)\n\t\t\t\tstd::cout << \"Agent under mouse is \" << a->identify();\n\t\t\telse\n\t\t\t\tstd::cout << \"No agent under cursor\";\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n}\n\n\/* vim: set noet: *\/\n<commit_msg>Ports are disconnectable now (click inputport-side connection to remove)<commit_after>\/*\n * PointerAgent.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Tue Aug 30 2005.\n * Copyright (c) 2005 Alyssa Milburn. 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 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 *\/\n\n#include \"PointerAgent.h\"\n#include \"openc2e.h\"\n#include \"World.h\"\n#include \"Engine.h\"\n#include \"caosVM.h\"\n#include \"Room.h\"\n\n\/\/ TODO: change imagecount?\nPointerAgent::PointerAgent(std::string spritefile) : SimpleAgent(2, 1, 1, INT_MAX, spritefile, 0, 0) {\n\tname = \"hand\";\n\thandle_events = true;\n\tholdingWire = 0;\n\twireOriginID = 0;\n\t\/\/ TODO: verify attributes on the pointer in c2e\n\tattr.setInt(256); \/\/ camera shy\n}\n\nvoid PointerAgent::finishInit() {\n\tAgent::finishInit();\n\n\t\/\/ float relative to main camera\n\tattr.setInt(attr.getInt() & 32);\n\tfloatSetup();\n}\n\n\/\/ TODO: this should have a queueScript equiv too\nvoid PointerAgent::firePointerScript(unsigned short event, Agent *src) {\n\tassert(src); \/\/ TODO: I \/think\/ this should only be called by the engine..\n\tshared_ptr<script> s = src->findScript(event);\n\tif (!s && engine.version < 3) { \/\/ TODO: are we sure this doesn't apply to c2e?\n\t\ts = findScript(event); \/\/ TODO: we should make sure this actually belongs to the pointer agent and isn't a fallback, maybe\n\t}\n\tif (!s) return;\n\tif (!vm) vm = world.getVM(this);\n\tif (vm->fireScript(s, false, src)) { \/\/ TODO: should FROM be src?\n\t\tvm->setTarg(this);\n\t\tzotstack();\n\t}\n}\n\nvoid PointerAgent::physicsTick() {\n\t\/\/ TODO: this is a hack, which does nothing, because we set a velocity in main() but also move the cursor manually\n}\n\nvoid PointerAgent::kill() {\n\t\/\/ pointer agent isn't killable\n}\n\nvoid PointerAgent::handleEvent(SomeEvent &event) {\n\tif (event.type == eventmousemove) {\n\t\tmoveTo(event.x + world.camera.getX(), event.y + world.camera.getY());\n\t\tvelx.setInt(event.xrel * 4);\n\t\tvely.setInt(event.yrel * 4);\n\n\t\t\/\/ middle mouse button scrolling\n\t\tif (event.button & buttonmiddle)\n\t\t\tworld.camera.moveTo(world.camera.getX() - event.xrel, world.camera.getY() - event.yrel, jump);\n\t} else if (!handle_events) {\n\t\t\/* mouse move events are (apparently - see eg C3 agent help) still handled with handle_events disabled, but nothing else *\/\n\t\treturn;\n\t} else if (event.type == eventmousebuttondown) {\n\t\t\/\/ do our custom handling\n\t\tif (event.button == buttonleft) {\n\t\t\tCompoundPart *a = world.partAt(x, y);\n\t\t\tif (a \/* && a->canActivate() *\/) { \/\/ TODO\n\t\t\t\tAgent* parent = a->getParent();\n\n\t\t\t\tint eve = -1;\n\t\t\t\n\t\t\t\tbool foundport = false;\n\t\t\t\tif (engine.version > 2) {\n\t\t\t\t\tfor (std::map<unsigned int, boost::shared_ptr<OutputPort> >::iterator i = parent->outports.begin();\n\t\t\t\t\t\t\t i != parent->outports.end(); i++) {\n\t\t\t\t\t\t\/\/ TODO: 4 is a magic number i pulled out of nooooowhere\n\t\t\t\t\t\tif (abs(i->second->x + parent->x - x) < 4 && abs(i->second->y + parent->y - y) < 4) {\n\t\t\t\t\t\t\tfoundport = true;\n\t\t\t\t\t\t\tif (holdingWire == 2) {\n\t\t\t\t\t\t\t\tparent->join(i->first, wireOriginAgent, wireOriginID);\n\t\t\t\t\t\t\t\tholdingWire = 0;\n\t\t\t\t\t\t\t\teve = 111;\n\t\t\t\t\t\t\t} else if (holdingWire == 0) {\n\t\t\t\t\t\t\t\teve = 110;\n\t\t\t\t\t\t\t\tholdingWire = 1;\n\t\t\t\t\t\t\t\twireOriginAgent = parent;\n\t\t\t\t\t\t\t\twireOriginID = i->first;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!foundport) {\n\t\t\t\t\t\tfor (std::map<unsigned int, boost::shared_ptr<InputPort> >::iterator i = parent->inports.begin();\n\t\t\t\t\t\t\t\t i != parent->inports.end(); i++) {\n\t\t\t\t\t\t\t\/\/ TODO: 4 is a magic number i pulled out of nooooowhere\n\t\t\t\t\t\t\tif (abs(i->second->x + parent->x - x) < 4 && abs(i->second->y + parent->y - y) < 4) {\n\t\t\t\t\t\t\t\tfoundport = true;\n\t\t\t\t\t\t\t\tif (holdingWire == 1) {\n\t\t\t\t\t\t\t\t\twireOriginAgent->join(wireOriginID, parent, i->first);\n\t\t\t\t\t\t\t\t\tholdingWire = 0;\n\t\t\t\t\t\t\t\t\teve = 111;\n\t\t\t\t\t\t\t\t} else if (holdingWire == 0) {\n\t\t\t\t\t\t\t\t\tif (i->second->source) {\n\t\t\t\t\t\t\t\t\t\teve = 112;\n\t\t\t\t\t\t\t\t\t\tholdingWire = 1;\n\t\t\t\t\t\t\t\t\t\twireOriginAgent = i->second->source;\n\t\t\t\t\t\t\t\t\t\twireOriginID = i->second->sourceid;\n\t\t\t\t\t\t\t\t\t\ti->second->source->outports[i->second->sourceid]->dests.remove(std::pair<AgentRef, unsigned int>(parent, i->first));\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\teve = 110;\n\t\t\t\t\t\t\t\t\t\tholdingWire = 2;\n\t\t\t\t\t\t\t\t\t\twireOriginAgent = parent;\n\t\t\t\t\t\t\t\t\t\twireOriginID = i->first;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\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}\n\n\t\t\t\tif (!foundport) {\n\t\t\t\t\tif (holdingWire) {\n\t\t\t\t\t\tholdingWire = 0;\n\t\t\t\t\t\teve = 113;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ if the agent isn't paused, tell it to handle a click\n\t\t\t\t\t\tint scriptid = a->handleClick(x - a->x - parent->x, y - a->y - parent->y);\n\t\t\t\t\t\tif (scriptid != -1) {\n\t\t\t\t\t\t\t\/\/ fire the script\n\t\t\t\t\t\t\t\/\/ _p1_ is id of part for button clicks, according to Edynn code\n\t\t\t\t\t\t\t\/\/ TODO: should _p1_ always be set? :)\n\t\t\t\t\t\t\tif (!parent->paused) parent->queueScript(scriptid, world.hand(), (int)a->id);\n\n\t\t\t\t\t\t\t\/\/ annoyingly queueScript doesn't reliably tell us if it did anything useful.\n\t\t\t\t\t\t\t\/\/ TODO: work out the mess which is queueScript's return values etc\n\t\t\t\t\t\t\tif (!parent->findScript(scriptid)) return;\n\n\t\t\t\t\t\t\t\/\/ fire the associated pointer script too, if necessary\n\t\t\t\t\t\t\t\/\/ TODO: fuzzie has no idea if this code is remotely correct\n\t\t\t\t\t\t\tif (engine.version < 3) {\n\t\t\t\t\t\t\t\teve = 50;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\teve = 101; \/\/ Pointer Activate 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tswitch (scriptid) {\n\t\t\t\t\t\t\t\tcase 0: eve += 2; break; \/\/ deactivate\n\t\t\t\t\t\t\t\tcase 1: break; \/\/ activate 1\n\t\t\t\t\t\t\t\tcase 2: eve += 1; break; \/\/ activate 2\n\t\t\t\t\t\t\t\tdefault: return;\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}\n\n\t\t\t\tif (eve != -1) firePointerScript(eve, a->getParent());\n\t\t\t} else if (engine.version > 2) {\n\t\t\t\tif (holdingWire) {\n\t\t\t\t\tholdingWire = 0;\n\t\t\t\t\tqueueScript(113, 0);\n\t\t\t\t} else {\n\t\t\t\t\tqueueScript(116, 0); \/\/ Pointer Clicked Background\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.button == buttonright) {\n\t\t\tif (world.paused) return; \/\/ TODO: wrong?\n\t\t\t\t\t\t\t\n\t\t\t\/\/ picking up and dropping are implictly handled by the scripts (well,\n\t\t\t\/\/ messages) 4 and 5\tTODO: check if this is correct behaviour, one issue\n\t\t\t\/\/ is that this isn't instant, another is the messages might only be\n\t\t\t\/\/ fired in c2e when you use MESG WRIT, in which case we'll need to\n\t\t\t\/\/ manually set carrying to NULL and a here, respectively - fuzzie\n\t\t\tif (carrying) {\n\t\t\t\t\/\/ TODO: c1 support - these attributes are invalid for c1\n\t\t\t\tif (!carrying->suffercollisions() || (carrying->validInRoomSystem() || engine.version == 1)) {\n\t\t\t\t\tcarrying->queueScript(5, this); \/\/ drop\n\n\t\t\t\t\tint eve; if (engine.version < 3) eve = 54; else eve = 105;\n\t\t\t\t\tfirePointerScript(eve, carrying); \/\/ Pointer Drop\n\n\t\t\t\t\t\/\/ TODO: is this the correct check?\n\t\t\t\t\tif (carrying->sufferphysics() && carrying->suffercollisions()) {\n\t\t\t\t\t\t\/\/ TODO: do this in the pointer agent?\n\t\t\t\t\t\tcarrying->velx.setFloat(velx.getFloat());\n\t\t\t\t\t\tcarrying->vely.setFloat(vely.getFloat());\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ TODO: some kind of \"fail to drop\" animation\/sound?\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tAgent *a = world.agentAt(x, y, false, true);\n\t\t\t\tif (a) {\n\t\t\t\t\ta->queueScript(4, this); \/\/ pickup\n\n\t\t\t\t\tint eve; if (engine.version < 3) eve = 53; else eve = 104;\n\t\t\t\t\tfirePointerScript(eve, a); \/\/ Pointer Pickup\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.button == buttonmiddle) {\n\t\t\tstd::vector<shared_ptr<Room> > rooms = world.map.roomsAt(event.x + world.camera.getX(), event.y + world.camera.getY());\n\t\t\tif (rooms.size() > 0) std::cout << \"Room at cursor is \" << rooms[0]->id << std::endl;\n\t\t\tAgent *a = world.agentAt(event.x + world.camera.getX(), event.y + world.camera.getY(), true);\n\t\t\tif (a)\n\t\t\t\tstd::cout << \"Agent under mouse is \" << a->identify();\n\t\t\telse\n\t\t\t\tstd::cout << \"No agent under cursor\";\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n}\n\n\/* vim: set noet: *\/\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <conio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n\ntypedef struct\n{\n\tint codigo;\n\tchar raca[30], nome[100];\n} registro;\n\ntypedef struct\n{\n\tint codigo, offset;\n} indice1;\n\ntypedef struct\n{\n\tchar vacina[30];\n\tint offset;\n} indice2;\n\nint Menu();\nvoid AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2);\nvoid CadastraVacina(FILE **AP1, FILE **AP2);\nvoid CadastraCachorro(FILE **AP2);\nvoid AtualizaInfoIndice(char status, FILE **arq);\nint ExisteCachorro(int codigo, FILE **AP2);\n\nint main() \n{\n int opcao;\n\tFILE *AP1, *AP2, *IndPrim, *IndSec1, *IndSec2;\n\t\n\tAbreArquivos(&AP1, &AP2, &IndPrim, &IndSec1, &IndSec2);\n\topcao = Menu();\n\twhile (opcao != 0)\n\t{\n\t switch(opcao)\n\t {\n\t case 1: CadastraCachorro(&AP2);\n }\n opcao = Menu();\n }\n\t\n\tfclose(AP1);\n\tfclose(AP2);\n\tfclose(IndPrim);\n\tfclose(IndSec1);\n\tfclose(IndSec2);\n\treturn 0;\n}\n\nint Menu()\n{\n\tint opcao = -1;\n\t\n\twhile ((opcao != 1) && (opcao != 0))\n\t{\n\t\tsystem(\"CLS\");\n printf(\"\\n1 - Cadastra Cachorro\");\n\t\tprintf(\"\\n0 - Sair\");\n\t\tprintf(\"\\n\\nEscolha a opcao: \");\n scanf(\"%d\", &opcao);\n }\n\treturn opcao;\n}\n\n\/*\nDESCRIO: Verifica se os arquivos j foram criados.\n Se no, cria-os.\nPARMETROS: AP1 - Arquivo Principal 1\n AP2 - Arquivo Principal 2\n\t IndPrim - Arquivo de ndice (busca por chave primria)\n\t\t\tIndSec1 - Arquivo de ndice 1 (busca por chave secundria)\n\t\t\tIndSec2 - Arquivo de ndice 2 (busca por chave secundria)\n*\/\nvoid AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2)\n{\n if ((*AP1 = fopen(\"AP1.bin\", \"r+b\")) == NULL)\n {\n \t*AP1 = fopen(\"AP1.bin\", \"w+b\");\n \tfprintf(*AP1, \"%d\", -1);\n \t*IndPrim = fopen(\"IndPrim.bin\", \"w+b\");\n \tAtualizaInfoIndice('!', IndPrim);\n \t*IndSec1 = fopen(\"IndSec1.bin\", \"w+b\");\n \tAtualizaInfoIndice('!', IndSec1);\n \t*IndSec2 = fopen(\"IndSec2.bin\", \"w+b\");\n \tAtualizaInfoIndice('!', IndSec2);\n\t}\n\t\/*else if (ExigeRecriaIndice(IndPrim))\n\t{\n\t\tRecriaIndicePrim(AP1);\n\t\tQuickSortInd1(INDEX1, 0, tam1);\n\t}\n\telse\n\t{\n\t\tIndPrim = fopen(\"IndPrim.bin\", \"r+b\");\n\t\tCarregaIndice(IndPrim, 1);\n \tIndSec1 = fopen(\"IndSec1.bin\", \"r+b\");\n \tCarregaIndice(IndSec1, 2);\n \tIndSec2 = fopen(\"IndSec2.bin\", \"r+b\");\n \tCarregaIndice(IndSec2, 1);\n\t}*\/\n \t\n if ((*AP2 = fopen(\"AP2.bin\", \"r+b\")) == NULL)\n *AP2 = fopen(\"AP2.bin\", \"w+b\");\n \n}\n\n\/*\nDESCRIO: Cadastra informaes de um cachorro no Arquivo Principal 2\nPARMETROS: AP2 - Arquivo Principal 2\n*\/\nvoid CadastraCachorro(FILE **AP2)\n{\n\tregistro reg;\n\t\n\tsystem(\"CLS\");\n\tprintf(\"\\nCodigo: \");\n\tscanf(\"%d\", ®.codigo);\n\twhile (ExisteCachorro(reg.codigo, AP2))\n\t{\n\t\tsystem(\"CLS\");\n\t\tprintf(\"\\nCodigo ja cadastrado. Digite novamente!\");\n\t\tgetch();\n\t\tsystem(\"CLS\");\n\t\tprintf(\"\\nCodigo: \");\n\t\tscanf(\"%d\", ®.codigo);\n\t}\n\tfflush(stdin);\n\tprintf(\"Raca: \");\n\tgets(reg.raca);\n\tprintf(\"Nome do Cachorro: \");\n\tgets(reg.nome);\n\n\t\n\tfseek(*AP2, 0, SEEK_END); \/\/seta a posio para o fim do arquivo.\n\tfwrite(®, sizeof(reg), 1, *AP2); \/\/escreve no fim do arquivo.\n}\n\n\/*\nDESCRIO: Atualiza o header do ndice com o status de atualizao\nPARMETROS: status - '*' - ndice atualizado\n '!' - ndice desatualizado\n arq - ndice a ser atualizado\n*\/\nvoid AtualizaInfoIndice(char status, FILE **arq)\n{\n\tfseek(*arq, 0, SEEK_SET);\n\tfputc(status, *arq);\t\n}\n\n\/*\nDESCRIO: Verifica se o cdigo j existe no arquivo.\nPARMETROS: codigo - Cdigo a ser verificado\n AP2 - Arquivo Principal 2\nRETORNOS: 0 - No existe um cachorro com o cdigo passado por parmetro\n 1 - Existe um cachorro com o cdigo passado por parmetro\n*\/\nint ExisteCachorro(int codigo, FILE **AP2)\n{\n\tint i = 0;\n\tregistro reg;\n\t\n\trewind(*AP2);\n\twhile (fread(®, sizeof(registro)*i, 1, *AP2) >= 1)\n\t{\n\t\tif (reg.codigo == codigo)\n\t\t{\n\t\t\treturn 1;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\t\t\n\t}\n return 0;\t\n}\n\nvoid CadastraVacina(FILE **AP1, FILE **AP2)\n{\n int cod_controle, cod_cachorro, tam_reg;\n char verificador = '*', vacina[30], data[6], respo[100], registro[255];\n \n system(\"CLS\");\n printf(\"\\n\\nDigite o cdigo do cachorro <-1 para cadastrar um cachorro>: \");\n scanf(\"%d\", &cod_cachorro);\n if (cod_cachorro == -1)\n CadastraCachorro(AP2);\n else\n {\n while (!ExisteCachorro(cod_cachorro, AP2))\n { \n printf(\"\\n\\nCachorro inexistente. Digite novamente!\");\n system(\"CLS\"); \n printf(\"\\n\\nDigite o cdigo do cachorro <-1 para cadastrar um cachorro>: \");\n scanf(\"%d\", &cod_cachorro);\n if (cod_cachorro == -1)\n CadastraCachorro(AP2); \n }\n system(\"CLS\");\n \/\/cod_controle = pegar do INDEX1 ordenado;\n printf(\"Codigo do cachorro: %d\", cod_cachorro);\n printf(\"\\nNome da vacina: \");\n gets(vacina);\n printf(\"\\nData de vacinacao <MM\/AA>: \");\n gets(data);\n printf(\"\\nResponsavel pela aplicacao: \");\n gets(respo);\n sprintf(registro, \"%d|%d|%s|%s|%s|\", cod_controle, cod_cachorro, vacina, data, respo);\n tam_reg = strlen(registro);\n \/\/verificar espaos em branco no arquivo para insero;\n fwrite(&tam_reg, sizeof(int), 1, *AP1);\n fwrite(&verificador, sizeof(char), 1, *AP1);\n fwrite(registro, sizeof(char), tam_reg, *AP1);\n }\n}\n\n<commit_msg>Novas Funções<commit_after>#include <stdio.h>\n#include <conio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n\ntypedef struct\n{\n\tint codigo;\n\tchar raca[30], nome[100];\n} registro;\n\ntypedef struct\n{\n\tint codigo, offset;\n} indice1;\n\ntypedef struct\n{\n\tchar vacina[30];\n\tint offset;\n} indice2;\n\nint Menu();\nvoid AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2);\nvoid CadastraVacina(FILE **AP1, FILE **AP2);\nvoid CadastraCachorro(FILE **AP2);\nvoid AtualizaInfoIndice(char status, FILE **arq);\nint ExisteCachorro(int codigo, FILE **AP2);\nint ProcuraEspacoVazio(FILE **AP1, int tam_reg);\n\nint main() \n{\n int opcao;\n\tFILE *AP1, *AP2, *IndPrim, *IndSec1, *IndSec2;\n\t\n\tAbreArquivos(&AP1, &AP2, &IndPrim, &IndSec1, &IndSec2);\n\topcao = Menu();\n\twhile (opcao != 0)\n\t{\n\t switch(opcao)\n\t {\n\t case 1: CadastraVacina(&AP1, &AP2);\n }\n opcao = Menu();\n }\n\t\n\tfclose(AP1);\n\tfclose(AP2);\n\tfclose(IndPrim);\n\tfclose(IndSec1);\n\tfclose(IndSec2);\n\treturn 0;\n}\n\nint Menu()\n{\n\tint opcao = -1;\n\t\n\twhile ((opcao != 1) && (opcao != 0))\n\t{\n\t\tsystem(\"CLS\");\n printf(\"\\n1 - Cadastra Vacina\");\n\t\tprintf(\"\\n0 - Sair\");\n\t\tprintf(\"\\n\\nEscolha a opcao: \");\n scanf(\"%d\", &opcao);\n }\n\treturn opcao;\n}\n\n\/*\nDESCRIO: Verifica se os arquivos j foram criados.\n Se no, cria-os.\nPARMETROS: AP1 - Arquivo Principal 1\n AP2 - Arquivo Principal 2\n\t IndPrim - Arquivo de ndice (busca por chave primria)\n\t\t\tIndSec1 - Arquivo de ndice 1 (busca por chave secundria)\n\t\t\tIndSec2 - Arquivo de ndice 2 (busca por chave secundria)\n*\/\nvoid AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2)\n{\n if ((*AP1 = fopen(\"AP1.bin\", \"r+b\")) == NULL)\n {\n \t*AP1 = fopen(\"AP1.bin\", \"w+b\");\n \tfprintf(*AP1, \"%d\", -1);\n \t*IndPrim = fopen(\"IndPrim.bin\", \"w+b\");\n \tAtualizaInfoIndice('!', IndPrim);\n \t*IndSec1 = fopen(\"IndSec1.bin\", \"w+b\");\n \tAtualizaInfoIndice('!', IndSec1);\n \t*IndSec2 = fopen(\"IndSec2.bin\", \"w+b\");\n \tAtualizaInfoIndice('!', IndSec2);\n\t}\n\t\/*else if (ExigeRecriaIndice(IndPrim))\n\t{\n\t\tRecriaIndicePrim(AP1);\n\t\tQuickSortInd1(INDEX1, 0, tam1);\n\t}\n\telse\n\t{\n\t\tIndPrim = fopen(\"IndPrim.bin\", \"r+b\");\n\t\tCarregaIndice(IndPrim, 1);\n \tIndSec1 = fopen(\"IndSec1.bin\", \"r+b\");\n \tCarregaIndice(IndSec1, 2);\n \tIndSec2 = fopen(\"IndSec2.bin\", \"r+b\");\n \tCarregaIndice(IndSec2, 1);\n\t}*\/\n \t\n if ((*AP2 = fopen(\"AP2.bin\", \"r+b\")) == NULL)\n *AP2 = fopen(\"AP2.bin\", \"w+b\");\n \n}\n\n\/*\nDESCRIO: Cadastra informaes de um cachorro no Arquivo Principal 2\nPARMETROS: AP2 - Arquivo Principal 2\n*\/\nvoid CadastraCachorro(FILE **AP2)\n{\n\tregistro reg;\n\t\n\tsystem(\"CLS\");\n\tprintf(\"\\nCodigo: \");\n\tscanf(\"%d\", ®.codigo);\n\twhile (ExisteCachorro(reg.codigo, AP2))\n\t{\n\t\tsystem(\"CLS\");\n\t\tprintf(\"\\nCodigo ja cadastrado. Digite novamente!\");\n\t\tgetch();\n\t\tsystem(\"CLS\");\n\t\tprintf(\"\\nCodigo: \");\n\t\tscanf(\"%d\", ®.codigo);\n\t}\n\tfflush(stdin);\n\tprintf(\"Raca: \");\n\tgets(reg.raca);\n\tprintf(\"Nome do Cachorro: \");\n\tgets(reg.nome);\n\n\t\n\tfseek(*AP2, 0, SEEK_END); \/\/seta a posio para o fim do arquivo.\n\tfwrite(®, sizeof(reg), 1, *AP2); \/\/escreve no fim do arquivo.\n}\n\n\/*\nDESCRIO: Atualiza o header do ndice com o status de atualizao\nPARMETROS: status - '*' - ndice atualizado\n '!' - ndice desatualizado\n arq - ndice a ser atualizado\n*\/\nvoid AtualizaInfoIndice(char status, FILE **arq)\n{\n\tfseek(*arq, 0, SEEK_SET);\n\tfputc(status, *arq);\t\n}\n\n\/*\nDESCRIO: Verifica se o cdigo j existe no arquivo.\nPARMETROS: codigo - Cdigo a ser verificado\n AP2 - Arquivo Principal 2\nRETORNOS: 0 - No existe um cachorro com o cdigo passado por parmetro\n 1 - Existe um cachorro com o cdigo passado por parmetro\n*\/\nint ExisteCachorro(int codigo, FILE **AP2)\n{\n\tint i = 1;\n\tregistro reg;\n\t\n\trewind(*AP2);\n\twhile (fread(®, sizeof(registro)*i, 1, *AP2) >= 1)\n\t{\n\t\tif (reg.codigo == codigo)\n\t\t{\n\t\t\treturn 1;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\t\t\n\t}\n return 0;\t\n}\n\n\/*\nDESCRIO: Realiza o cadastro de vacinas\nPARMETROS: AP1 - Arquivo principal 1\n AP2 - Arquivo principal 2\n*\/\nvoid CadastraVacina(FILE **AP1, FILE **AP2)\n{\n int cod_controle, cod_cachorro, tam_reg, posicao;\n char verificador = '*', vacina[30], data[6], respo[100], registro[255];\n \n system(\"CLS\");\n printf(\"\\n\\nDigite o cdigo do cachorro <-1 para cadastrar um cachorro>: \");\n scanf(\"%d\", &cod_cachorro);\n if (cod_cachorro == -1)\n CadastraCachorro(AP2);\n else\n {\n while (!ExisteCachorro(cod_cachorro, AP2))\n { \n printf(\"\\n\\nCachorro inexistente. Digite novamente!\");\n system(\"CLS\"); \n printf(\"\\n\\nDigite o cdigo do cachorro <-1 para cadastrar um cachorro>: \");\n scanf(\"%d\", &cod_cachorro);\n if (cod_cachorro == -1)\n CadastraCachorro(AP2); \n }\n system(\"CLS\");\n cod_controle = 1;\/\/cod_controle = pegar do INDEX1 ordenado;\n printf(\"Codigo do cachorro: %d\", cod_cachorro);\n fflush(stdin);\n printf(\"\\nNome da vacina: \");\n gets(vacina);\n printf(\"\\nData de vacinacao <MM\/AA>: \");\n gets(data);\n printf(\"\\nResponsavel pela aplicacao: \");\n gets(respo);\n sprintf(registro, \"%d|%d|%s|%s|%s|\", cod_controle, cod_cachorro, vacina, data, respo);\n tam_reg = strlen(registro);\n posicao = ProcuraEspacoVazio(AP1, tam_reg);\n if (posicao != -1)\n fseek(*AP1, posicao, SEEK_SET);\n else\n fseek(*AP1, 0, SEEK_END);\n fwrite(&tam_reg, sizeof(int), 1, *AP1);\n fwrite(&verificador, sizeof(char), 1, *AP1);\n fwrite(registro, sizeof(char), tam_reg, *AP1);\n }\n}\n\n\/*\nDESCRIO: Retorna o espao vazio encontrado no arquivo\nPARMETROS: AP1 - Arquivo principal 1\n tam_reg - tamanho do registro a ser inserido\nRETORNO: posio livre para ser escrita\n*\/\nint ProcuraEspacoVazio(FILE **AP1, int tam_reg)\n{\n int offset, tam, pos;\n char ch;\n \n rewind(*AP1);\n fread(&offset, sizeof(int), 1, *AP1);\n if (offset == -1)\n return -1;\n else\n {\n fseek(*AP1, offset, SEEK_SET);\n pos = ftell(*AP1);\n while (fread(&tam, sizeof(int), 1, *AP1))\n {\n if (tam == -1)\n {\n return -1;\n break;\n }\n else\n {\n ch = fgetc(*AP1);\n if ((tam > tam_reg) && (ch == '!'))\n {\n return pos;\n break; \n }\n else\n {\n fread(&offset, sizeof(int), 1, *AP1);\n fseek(*AP1, offset, SEEK_SET);\n } \n } \n } \n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"fileHelpers\/DICOMLoaderVTK.h\"\n#include \"ContourFromMask.h\"\n#include \"ActiveContour.h\"\n#include \"ContourToMask.h\"\n#include \"Helpers\/Validator.h\"\n#include \"Helpers\/Converter.h\"\n\n#include <vtkExtractVOI.h>\n\n#include <opencv2\/highgui.hpp>\n#include <vtkRenderer.h>\n\nint main( int argc, char** argv )\n{\n if( argc < 4 )\n {\n std::cerr << \"usage: \" << argv[0] << \" [pathToDatasetImage] [pathToMaskImage] [pathToGroundTruth]\" << std::endl;\n return -1;\n }\n\n int nPoints = 500;\n double simplficationEps = 1;\n double elasticity = 10;\n double stiffness = 500;\n double speed = 0.2;\n double smoothingSigma = 2;\n double iterations = 130;\n\n std::cerr << \"load data\" << std::endl;\n vtkSmartPointer<vtkImageData> image =\n DICOMLoaderVTK::loadDICOMSeries( std::string( argv[1] ) );\n\n vtkSmartPointer<vtkImageData> mask =\n DICOMLoaderVTK::loadDICOMSeries( std::string( argv[2] ) );\n\n vtkSmartPointer<vtkImageData> groundTruth =\n DICOMLoaderVTK::loadDICOMSeries( std::string( argv[3] ) );\n\n int* dim = mask->GetDimensions();\n\n std::cerr << \"find initial contours\" << std::endl;\n std::vector< std::vector<Contour> > contoursPerSclice;\n for( int i = 0; i < mask->GetDimensions()[2]; ++i )\n {\n vtkSmartPointer<vtkExtractVOI> voiExtractor =\n vtkSmartPointer<vtkExtractVOI>::New();\n voiExtractor->SetInputData( mask );\n voiExtractor->SetVOI( 0, dim[0]-1, 0, dim[1]-1, i, i );\n voiExtractor->Update();\n voiExtractor->GetOutput()->SetExtent( 0, dim[0]-1, 0, dim[1]-1, 0, 0 );\n\n std::vector<Contour> contoursInSlice = ContourFromMask::computeWithEdgeFilter( voiExtractor->GetOutput(), 0 );\n std::cout << \"found contours \" << contoursInSlice.size() << \" in slice \" << mask->GetDimensions()[2]-i << std::endl;\n for( size_t j = 0; j < contoursInSlice.size(); ++j )\n {\n \/\/ if number of points is small enough, don't simplify\n if( contoursInSlice[j].size() < nPoints )\n continue;\n\n contoursInSlice[j] = ContourFromMask::simplify( contoursInSlice[j], simplficationEps );\n contoursInSlice[j] = ContourFromMask::resample( contoursInSlice[j], nPoints );\n }\n if( contoursInSlice.size() > 3 )\n std::cerr << \"contours found in slice bigger than 3: \" << contoursInSlice.size() << \" in slice \" << i << std::endl;\n contoursPerSclice.push_back( contoursInSlice );\n }\n\n std::cerr << \"initalizing contour algorithm\" << std::endl;\n std::cerr << \"mask dimension: \" << dim[0] << \" \" << dim[1] << \" \" << dim[2] << std::endl;\n \/\/ initialize all algorithms\n std::vector<std::vector<ActiveContour> > activeContourAlgorithms( contoursPerSclice.size() );\n for( size_t i = 0; i < contoursPerSclice.size(); ++i )\n {\n vtkSmartPointer<vtkExtractVOI> voiExtractor =\n vtkSmartPointer<vtkExtractVOI>::New();\n voiExtractor->SetInputData( image );\n voiExtractor->SetVOI( 0, dim[0]-1, 0, dim[1]-1, i, i );\n voiExtractor->Update();\n voiExtractor->GetOutput()->SetExtent( 0, dim[0]-1, 0, dim[1]-1, 0, 0 );\n\n activeContourAlgorithms[i].resize( contoursPerSclice[i].size() );\n for( size_t j = 0; j < contoursPerSclice[i].size(); ++j )\n {\n ActiveContour& activeContour = activeContourAlgorithms[i][j];\n activeContour.setMaxIterations( iterations );\n activeContour.setElasticity( elasticity );\n activeContour.setStiffness( stiffness );\n activeContour.setIterationSpeed( speed );\n activeContour.setEdgeSoothingSigma( smoothingSigma );\n activeContour.setStartPoints( contoursPerSclice[i][j] );\n\n activeContour.setImage( voiExtractor->GetOutput() );\n }\n }\n\n std::cerr << \"optimizing contours\" << std::endl;\n \/\/ fit curves:\n std::vector< std::vector<Contour> > finalContoursPerSclice( contoursPerSclice.size() );\n for( size_t i = 0; i < activeContourAlgorithms.size(); ++i )\n {\n finalContoursPerSclice[i].resize( activeContourAlgorithms[i].size() );\n for( size_t j = 0; j < activeContourAlgorithms[i].size(); ++j )\n {\n finalContoursPerSclice[i][j] = activeContourAlgorithms[i][j].compute();\n }\n }\n\n std::cerr << \"converting contours to masks and saving\" << std::endl;\n std::vector<cv::Mat3b> masksSlicewise;\n \/\/ covert curves to masks\n for( size_t i = 0; i < finalContoursPerSclice.size(); ++i )\n {\n cv::Mat3b sliceMask( dim[1], dim[0], cv::Vec3b( 0, 0, 0 ) );\n for( size_t j = 0; j < finalContoursPerSclice[i].size(); ++j )\n {\n cv::Mat3b mask = ContourToMask::compute( finalContoursPerSclice[i][j], dim );\n cv::add( sliceMask, mask, sliceMask );\n }\n std::stringstream ss;\n ss << \"mask\" << std::setfill('0') << std::setw(2) << finalContoursPerSclice.size()- i << \".jpg\";\n cv::imwrite( ss.str(), sliceMask );\n masksSlicewise.push_back( sliceMask );\n }\n\n std::cerr << \"computing validation\" << std::endl;\n double diceCoeffOptimized =\n Validator::diceCoeff3DVolume( ContourToMask::computeITK( finalContoursPerSclice, mask->GetDimensions() ),\n Converter::ConvertVTKToITK<MaskType>( groundTruth ) );\n double diceCoeffBefore =\n Validator::diceCoeff3DVolume( Converter::ConvertVTKToITK<MaskType>( mask ),\n Converter::ConvertVTKToITK<MaskType>( groundTruth ) );\n\n std::cerr << \"diceCoeff before optimization: \" << diceCoeffBefore << std::endl;\n std::cerr << \"diceCoeff after optimization: \" << diceCoeffOptimized << std::endl;\n\n}\n<commit_msg>added filters to fit3D executable<commit_after>#include \"fileHelpers\/DICOMLoaderVTK.h\"\n#include \"ContourFromMask.h\"\n#include \"ActiveContour.h\"\n#include \"ContourToMask.h\"\n#include \"Helpers\/Validator.h\"\n#include \"Helpers\/Converter.h\"\n#include \"BiasCorrection.h\"\n#include \"Denoising.h\"\n\n#include <vtkExtractVOI.h>\n\n#include <opencv2\/highgui.hpp>\n#include <vtkRenderer.h>\n\nint main( int argc, char** argv )\n{\n if( argc < 4 )\n {\n std::cerr << \"usage: \" << argv[0] << \" [pathToDatasetImage] [pathToMaskImage] [pathToGroundTruth]\" << std::endl;\n return -1;\n }\n\n int nPoints = 500;\n double simplficationEps = 1;\n double elasticity = 10;\n double stiffness = 500;\n double speed = 0.2;\n double smoothingSigma = 2;\n double iterations = 130;\n\n std::cerr << \"load data\" << argv[1] << std::endl;\n vtkSmartPointer<vtkImageData> image =\n DICOMLoaderVTK::loadDICOMSeries( std::string( argv[1] ) );\n\n vtkSmartPointer<vtkImageData> mask =\n DICOMLoaderVTK::loadDICOMSeries( std::string( argv[2] ) );\n\n vtkSmartPointer<vtkImageData> groundTruth =\n DICOMLoaderVTK::loadDICOMSeries( std::string( argv[3] ) );\n\n int* dim = mask->GetDimensions();\n\n \/\/image = BiasCorrection::shadingFilter( image, mask, 2, true, 500, 500 );\n ImageType::Pointer itkImg = Converter::ConvertVTKToITK<ImageType>( image );\n itkImg =Denoising::bilateralFilterTemplate<ImageType>( itkImg, 2, 100 );\n image = Converter::ConvertITKToVTK<ImageType>( itkImg );\n\n std::cerr << \"find initial contours\" << std::endl;\n std::vector< std::vector<Contour> > contoursPerSclice;\n for( int i = 0; i < mask->GetDimensions()[2]; ++i )\n {\n vtkSmartPointer<vtkExtractVOI> voiExtractor =\n vtkSmartPointer<vtkExtractVOI>::New();\n voiExtractor->SetInputData( mask );\n voiExtractor->SetVOI( 0, dim[0]-1, 0, dim[1]-1, i, i );\n voiExtractor->Update();\n voiExtractor->GetOutput()->SetExtent( 0, dim[0]-1, 0, dim[1]-1, 0, 0 );\n\n std::vector<Contour> contoursInSlice = ContourFromMask::computeWithEdgeFilter( voiExtractor->GetOutput(), 0 );\n std::cout << \"found contours \" << contoursInSlice.size() << \" in slice \" << mask->GetDimensions()[2]-i << std::endl;\n for( size_t j = 0; j < contoursInSlice.size(); ++j )\n {\n \/\/ if number of points is small enough, don't simplify\n if( contoursInSlice[j].size() < nPoints )\n continue;\n\n contoursInSlice[j] = ContourFromMask::simplify( contoursInSlice[j], simplficationEps );\n contoursInSlice[j] = ContourFromMask::resample( contoursInSlice[j], nPoints );\n }\n if( contoursInSlice.size() > 3 )\n std::cerr << \"contours found in slice bigger than 3: \" << contoursInSlice.size() << \" in slice \" << i << std::endl;\n contoursPerSclice.push_back( contoursInSlice );\n }\n\n std::cerr << \"initalizing contour algorithm\" << std::endl;\n std::cerr << \"mask dimension: \" << dim[0] << \" \" << dim[1] << \" \" << dim[2] << std::endl;\n \/\/ initialize all algorithms\n std::vector<std::vector<ActiveContour> > activeContourAlgorithms( contoursPerSclice.size() );\n for( size_t i = 0; i < contoursPerSclice.size(); ++i )\n {\n vtkSmartPointer<vtkExtractVOI> voiExtractor =\n vtkSmartPointer<vtkExtractVOI>::New();\n voiExtractor->SetInputData( image );\n voiExtractor->SetVOI( 0, dim[0]-1, 0, dim[1]-1, i, i );\n voiExtractor->Update();\n voiExtractor->GetOutput()->SetExtent( 0, dim[0]-1, 0, dim[1]-1, 0, 0 );\n\n activeContourAlgorithms[i].resize( contoursPerSclice[i].size() );\n for( size_t j = 0; j < contoursPerSclice[i].size(); ++j )\n {\n ActiveContour& activeContour = activeContourAlgorithms[i][j];\n activeContour.setMaxIterations( iterations );\n activeContour.setElasticity( elasticity );\n activeContour.setStiffness( stiffness );\n activeContour.setIterationSpeed( speed );\n activeContour.setEdgeSoothingSigma( smoothingSigma );\n activeContour.setStartPoints( contoursPerSclice[i][j] );\n\n activeContour.setImage( voiExtractor->GetOutput() );\n }\n }\n\n std::cerr << \"optimizing contours\" << std::endl;\n \/\/ fit curves:\n std::vector< std::vector<Contour> > finalContoursPerSclice( contoursPerSclice.size() );\n for( size_t i = 0; i < activeContourAlgorithms.size(); ++i )\n {\n finalContoursPerSclice[i].resize( activeContourAlgorithms[i].size() );\n for( size_t j = 0; j < activeContourAlgorithms[i].size(); ++j )\n {\n finalContoursPerSclice[i][j] = activeContourAlgorithms[i][j].compute();\n }\n }\n\n std::cerr << \"converting contours to masks and saving\" << std::endl;\n std::vector<cv::Mat3b> masksSlicewise;\n \/\/ covert curves to masks\n for( size_t i = 0; i < finalContoursPerSclice.size(); ++i )\n {\n cv::Mat3b sliceMask( dim[1], dim[0], cv::Vec3b( 0, 0, 0 ) );\n for( size_t j = 0; j < finalContoursPerSclice[i].size(); ++j )\n {\n cv::Mat3b mask = ContourToMask::compute( finalContoursPerSclice[i][j], dim );\n cv::add( sliceMask, mask, sliceMask );\n }\n std::stringstream ss;\n ss << \"mask\" << std::setfill('0') << std::setw(2) << finalContoursPerSclice.size()- i << \".jpg\";\n cv::imwrite( ss.str(), sliceMask );\n masksSlicewise.push_back( sliceMask );\n }\n\n std::cerr << \"computing validation\" << std::endl;\n double diceCoeffOptimized =\n Validator::diceCoeff3DVolume( ContourToMask::computeITK( finalContoursPerSclice, mask->GetDimensions() ),\n Converter::ConvertVTKToITK<MaskType>( groundTruth ) );\n double diceCoeffBefore =\n Validator::diceCoeff3DVolume( Converter::ConvertVTKToITK<MaskType>( mask ),\n Converter::ConvertVTKToITK<MaskType>( groundTruth ) );\n\n std::cerr << \"diceCoeff before optimization: \" << diceCoeffBefore << std::endl;\n std::cerr << \"diceCoeff after optimization: \" << diceCoeffOptimized << std::endl;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"astclass.h\"\n\n#include \"core\/defines.h\"\n\n#include \"yasc\/compiler\/scope\/scope.h\"\n#include \"yasc\/compiler\/scope\/scopevariable.h\"\n#include \"libraries\/libcil\/cil\/class.h\"\n\n#include \"astfunction.h\"\n#include \"asttype.h\"\n#include \"asttypevariables.h\"\n#include \"astvariable.h\"\n#include \"astfield.h\"\n#include \"astvisitor.h\"\n\nASTClass::ASTClass():\n ASTNode(),\n mKind(eClass),\n mModifiers(),\n mpBaseType(nullptr),\n mInterfaces(),\n mpTypeVariables(nullptr),\n mFunctions(),\n mFunctionTable(),\n mName(),\n mFullName(),\n mStatics(),\n mFields(),\n mpCompiledClass(nullptr)\n{\n}\n\nASTClass::~ASTClass()\n{\n setBaseType(nullptr);\n setTypeVariables(nullptr);\n setCompiledClass(nullptr);\n}\n\n\/\/ - Get\/set\n\nASTClass::Kind ASTClass::getKind() const\n{\n return mKind;\n}\n\nvoid ASTClass::setKind(Kind kind)\n{\n mKind = kind;\n}\n\nbool ASTClass::hasBaseType() const\n{\n return mpBaseType != nullptr;\n}\n \nconst ASTType& ASTClass::getBaseType() const\n{\n return *mpBaseType;\n}\n\nASTType& ASTClass::getBaseType()\n{\n return *mpBaseType;\n}\n\nvoid ASTClass::setBaseType(ASTType* pbasetype)\n{\n delete mpBaseType;\n mpBaseType = pbasetype;\n}\n\nbool ASTClass::hasBaseClass() const\n{\n return hasBaseType() && !getBaseType().isUnknown();\n}\n \nconst ASTClass& ASTClass::getBaseClass() const\n{\n ASSERT_PTR(mpBaseType);\n ASSERT(mpBaseType->hasObjectClass());\n return mpBaseType->getObjectClass();\n}\n\nASTClass& ASTClass::getBaseClass()\n{\n ASSERT_PTR(mpBaseType);\n return mpBaseType->getObjectClass();\n}\n\nvoid ASTClass::setBaseClass(ASTClass& baseclass)\n{\n ASSERT_PTR(mpBaseType);\n mpBaseType->setObjectClass(baseclass);\n}\n\nconst String& ASTClass::getName() const\n{\n return mName;\n}\n \nvoid ASTClass::setName(const String& name)\n{\n mName = name;\n}\n\nconst String& ASTClass::getFullName() const\n{\n return mFullName;\n}\n\nvoid ASTClass::setFullName(const String& name)\n{\n mFullName = name;\n}\n\nconst ASTModifiers& ASTClass::getModifiers() const\n{\n return mModifiers;\n}\n\nASTModifiers& ASTClass::getModifiers()\n{\n return mModifiers;\n}\n\nconst ASTTypeVariables& ASTClass::getTypeVariables() const\n{\n ASSERT_PTR(mpTypeVariables);\n return *mpTypeVariables;\n}\n\nASTTypeVariables& ASTClass::getTypeVariables()\n{\n ASSERT_PTR(mpTypeVariables);\n return *mpTypeVariables;\n}\n\nvoid ASTClass::setTypeVariables(ASTTypeVariables* pinfo)\n{\n delete mpTypeVariables;\n mpTypeVariables = pinfo;\n}\n\nconst ASTFunctionMap& ASTClass::getFunctions() const\n{\n return mFunctions;\n}\n\nASTFunctionMap& ASTClass::getFunctions()\n{\n return mFunctions;\n}\n\nconst ASTFunctionTable& ASTClass::getFunctionTable() const\n{\n return mFunctionTable;\n}\n\nASTFunctionTable& ASTClass::getFunctionTable()\n{\n return mFunctionTable;\n}\n\nconst ASTTypeList& ASTClass::getInterfaces() const\n{\n return mInterfaces;\n}\n \nASTTypeList& ASTClass::getInterfaces()\n{\n return mInterfaces;\n}\n\nconst ASTClass::Fields& ASTClass::getStatics() const\n{\n return mStatics;\n}\n\nconst ASTClass::Fields& ASTClass::getFields() const\n{\n return mFields;\n}\n\nCIL::Class& ASTClass::getCompiledClass()\n{\n ASSERT_PTR(mpCompiledClass);\n return *mpCompiledClass;\n}\n\nCIL::Class* ASTClass::useCompiledClass()\n{\n CIL::Class* presult = mpCompiledClass;\n mpCompiledClass = nullptr;\n return presult;\n}\n\nvoid ASTClass::setCompiledClass(CIL::Class* pclass)\n{\n delete mpCompiledClass;\n mpCompiledClass = pclass;\n}\n\n\/\/ - Query\n\nbool ASTClass::isClass() const\n{\n return mKind == eClass;\n}\n \nbool ASTClass::isInterface() const\n{\n return mKind == eInterface;\n}\n \nbool ASTClass::isBase(const ASTClass& base) const\n{\n if ( this == &base )\n {\n return true;\n }\n else if ( hasBaseClass() )\n {\n const ASTClass& baseclass = getBaseClass();\n\n if ( &baseclass == &base )\n {\n return true;\n }\n else\n {\n return baseclass.isBase(base);\n }\n }\n return false;\n}\n\nbool ASTClass::isImplementing(const ASTClass& intrface) const\n{\n if ( mInterfaces.contains(intrface) )\n {\n return true;\n }\n else if ( hasBaseClass() )\n {\n return getBaseClass().isImplementing(intrface);\n }\n\n return false;\n}\n\nbool ASTClass::isLocal(const ASTFunction& function) const\n{\n return &function.getClass() == this;\n}\n\nbool ASTClass::isNative() const\n{\n return mModifiers.isNative() || hasNativeFunction();\n}\n\nbool ASTClass::isGeneric() const\n{\n return mpTypeVariables != nullptr;\n}\n\nbool ASTClass::isTypeName(const String& name) const\n{\n return isGeneric() && mpTypeVariables->contains(name);\n}\n\nbool ASTClass::hasConstructor() const\n{\n return mFunctions.hasConstructor();\n}\n\nbool ASTClass::hasAbstractFunction() const\n{\n return mFunctions.hasAbstractFunction();\n}\n\nbool ASTClass::hasNativeFunction() const\n{\n return mFunctions.hasNativeFunction();\n}\n\nbool ASTClass::hasNativeConstructor() const\n{\n return mFunctions.hasNativeConstructor();\n}\n\nint ASTClass::getTotalStatics() const\n{\n return mStatics.size();\n}\n\nint ASTClass::getTotalVariables() const\n{\n return mFields.size() + (hasBaseClass() ? getBaseClass().getTotalVariables() : 0);\n}\n\nconst ASTField& ASTClass::getField(int var) const\n{\n if ( mFields.empty() || mFields[0]->getVariable().getResourceIndex() > var )\n {\n return getBaseClass().getField(var);\n }\n\n std::size_t index = var - mFields[0]->getVariable().getResourceIndex();\n ASSERT(index < mFields.size());\n return *mFields[index];\n}\n\n\/\/ - Operations\n \nvoid ASTClass::addInterface(ASTType* ptype)\n{\n mInterfaces.append(ptype);\n}\n\nbool ASTClass::isMember(const String& name) const\n{\n const ASTMember* pmember = findField(name);\n if ( pmember == nullptr )\n {\n pmember = findStatic(name);\n if ( pmember == nullptr )\n {\n return mFunctions.hasFunction(name);\n }\n }\n\n return true;\n}\n\nvoid ASTClass::addMember(ASTMember* pmember)\n{\n if ( pmember->getKind() == ASTMember::eField )\n {\n ASTField* pfield = dynamic_cast<ASTField*>(pmember);\n\n if ( pfield->getVariable().getModifiers().isStatic() )\n {\n mStatics.push_back(pfield);\n }\n else\n {\n mFields.push_back(pfield);\n }\n }\n else\n {\n ASTFunction* pfunction = dynamic_cast<ASTFunction*>(pmember);\n pfunction->setClass(*this);\n\n mFunctions.insert(pfunction);\n }\n\n pmember->setClass(*this);\n addChild(pmember);\n}\n\nvoid ASTClass::insertFunction(int index, ASTFunction* pfunction)\n{\n mFunctions.insert(pfunction);\n mFunctionTable.set(index, *pfunction);\n\n insertChild(index, pfunction);\n}\n\nvoid ASTClass::ensureDefaultConstructor()\n{\n if ( isClass() && !hasConstructor() )\n {\n ASTFunction* pconstructor = new ASTFunction(ASTMember::eConstructor);\n pconstructor->setName(mName);\n pconstructor->setType(new ASTType(ASTType::eVoid));\n pconstructor->getModifiers().setVisibility(ASTModifiers::ePublic);\n\n addMember(pconstructor);\n }\n}\n\nASTType* ASTClass::createThisType() const\n{\n ASTType* presult = new ASTType(ASTType::eObject);\n presult->setObjectName(getFullName());\n presult->setObjectClass(const_cast<ASTClass&>(*this));\n return presult;\n}\n\nvoid ASTClass::collectInterfaces(ASTTypeList& interfaces) const\n{\n interfaces.append(mInterfaces);\n\n if ( hasBaseClass() )\n {\n getBaseClass().collectInterfaces(interfaces);\n }\n}\n\nvoid ASTClass::registerVariables(Scope& scope) const\n{\n if ( hasBaseClass() )\n {\n getBaseClass().registerVariables(scope);\n }\n\n for ( std::size_t index = 0; index < mStatics.size(); index++ )\n {\n ASTField* pstatic = mStatics[index];\n scope.add(ScopeVariable::fromVariable(pstatic->getVariable()));\n }\n\n for ( std::size_t index = 0; index < mFields.size(); index++ )\n {\n ASTField* pvariable = mFields[index];\n scope.add(ScopeVariable::fromVariable(pvariable->getVariable()));\n }\n}\n\nvoid ASTClass::calculateResources()\n{\n indexStatics();\n indexVariables();\n indexFunctions();\n}\n\nvoid ASTClass::indexStatics()\n{\n for ( std::size_t index = 0; index < mStatics.size(); index++ )\n {\n ASTField* pstatic = mStatics[index];\n pstatic->getVariable().setResourceIndex(index);\n }\n}\n\nvoid ASTClass::indexVariables()\n{\n int base = hasBaseClass() ? getBaseClass().getTotalVariables() : 0;\n\n for ( std::size_t index = 0; index < mFields.size(); index++ )\n {\n ASTField* pvariable = mFields[index];\n pvariable->getVariable().setResourceIndex(base + index);\n }\n}\n\nvoid ASTClass::indexFunctions()\n{\n if ( isClass() )\n {\n if ( hasBaseClass() )\n {\n mFunctionTable = getBaseClass().getFunctionTable();\n }\n }\n\n mFunctionTable.build(mFunctions);\n}\n\n\/\/ - Search\n\nconst ASTField* ASTClass::findStatic(const String& name, SearchScope scope) const\n{\n return const_cast<ASTClass&>(*this).findStatic(name, scope);\n}\n\nASTField* ASTClass::findStatic(const String& name, SearchScope scope)\n{\n for ( std::size_t index = 0; index < mStatics.size(); index++ )\n {\n ASTField* pstatic = mStatics[index];\n if ( pstatic->getVariable().getName() == name )\n {\n return pstatic;\n }\n }\n return scope == eAll && hasBaseClass() ? getBaseClass().findStatic(name, eAll) : nullptr;\n}\n\nconst ASTField* ASTClass::findField(const String& name, SearchScope scope) const\n{\n return const_cast<ASTClass&>(*this).findField(name, scope);\n}\n\nASTField* ASTClass::findField(const String& name, SearchScope scope)\n{\n for ( std::size_t index = 0; index < mFields.size(); index++ )\n {\n ASTField* pvariable = mFields[index];\n if ( pvariable->getVariable().getName() == name )\n {\n return pvariable;\n }\n }\n return scope == eAll && hasBaseClass() ? getBaseClass().findField(name) : nullptr;\n}\n\nconst ASTFunction* ASTClass::findBestMatch(const String& name, const ASTSignature& signature, const ASTTypeList& types) const\n{\n return const_cast<ASTClass&>(*this).findBestMatch(name, signature, types);\n}\n\nASTFunction* ASTClass::findBestMatch(const String& name, const ASTSignature& signature, const ASTTypeList& types)\n{\n ASTFunction* pfunction = mFunctions.findBestMatch(name, signature, types);\n if ( pfunction == nullptr && hasBaseClass() )\n {\n pfunction = getBaseClass().findBestMatch(name, signature, types);\n }\n return pfunction;\n}\n\nconst ASTFunction* ASTClass::findExactMatch(const String& name, const ASTSignature& signature) const\n{\n return const_cast<ASTClass&>(*this).findExactMatch(name, signature);\n}\n\nASTFunction* ASTClass::findExactMatch(const String& name, const ASTSignature& signature)\n{\n ASTFunction* pfunction = mFunctions.findExactMatch(name, signature);\n if ( pfunction == nullptr && hasBaseClass() )\n {\n pfunction = getBaseClass().findExactMatch(name, signature);\n }\n return pfunction;\n}\n\n\/\/ - Visitor\n \nACCEPT_IMPL(ASTClass)<commit_msg>Fix coverity issues 33966 & 33967<commit_after>\n#include \"astclass.h\"\n\n#include \"core\/defines.h\"\n\n#include \"yasc\/compiler\/scope\/scope.h\"\n#include \"yasc\/compiler\/scope\/scopevariable.h\"\n#include \"libraries\/libcil\/cil\/class.h\"\n\n#include \"astfunction.h\"\n#include \"asttype.h\"\n#include \"asttypevariables.h\"\n#include \"astvariable.h\"\n#include \"astfield.h\"\n#include \"astvisitor.h\"\n\nASTClass::ASTClass():\n ASTNode(),\n mKind(eClass),\n mModifiers(),\n mpBaseType(nullptr),\n mInterfaces(),\n mpTypeVariables(nullptr),\n mFunctions(),\n mFunctionTable(),\n mName(),\n mFullName(),\n mStatics(),\n mFields(),\n mpCompiledClass(nullptr)\n{\n}\n\nASTClass::~ASTClass()\n{\n setBaseType(nullptr);\n setTypeVariables(nullptr);\n setCompiledClass(nullptr);\n}\n\n\/\/ - Get\/set\n\nASTClass::Kind ASTClass::getKind() const\n{\n return mKind;\n}\n\nvoid ASTClass::setKind(Kind kind)\n{\n mKind = kind;\n}\n\nbool ASTClass::hasBaseType() const\n{\n return mpBaseType != nullptr;\n}\n \nconst ASTType& ASTClass::getBaseType() const\n{\n return *mpBaseType;\n}\n\nASTType& ASTClass::getBaseType()\n{\n return *mpBaseType;\n}\n\nvoid ASTClass::setBaseType(ASTType* pbasetype)\n{\n delete mpBaseType;\n mpBaseType = pbasetype;\n}\n\nbool ASTClass::hasBaseClass() const\n{\n return hasBaseType() && !getBaseType().isUnknown();\n}\n \nconst ASTClass& ASTClass::getBaseClass() const\n{\n ASSERT_PTR(mpBaseType);\n ASSERT(mpBaseType->hasObjectClass());\n return mpBaseType->getObjectClass();\n}\n\nASTClass& ASTClass::getBaseClass()\n{\n ASSERT_PTR(mpBaseType);\n return mpBaseType->getObjectClass();\n}\n\nvoid ASTClass::setBaseClass(ASTClass& baseclass)\n{\n ASSERT_PTR(mpBaseType);\n mpBaseType->setObjectClass(baseclass);\n}\n\nconst String& ASTClass::getName() const\n{\n return mName;\n}\n \nvoid ASTClass::setName(const String& name)\n{\n mName = name;\n}\n\nconst String& ASTClass::getFullName() const\n{\n return mFullName;\n}\n\nvoid ASTClass::setFullName(const String& name)\n{\n mFullName = name;\n}\n\nconst ASTModifiers& ASTClass::getModifiers() const\n{\n return mModifiers;\n}\n\nASTModifiers& ASTClass::getModifiers()\n{\n return mModifiers;\n}\n\nconst ASTTypeVariables& ASTClass::getTypeVariables() const\n{\n ASSERT_PTR(mpTypeVariables);\n return *mpTypeVariables;\n}\n\nASTTypeVariables& ASTClass::getTypeVariables()\n{\n ASSERT_PTR(mpTypeVariables);\n return *mpTypeVariables;\n}\n\nvoid ASTClass::setTypeVariables(ASTTypeVariables* pinfo)\n{\n delete mpTypeVariables;\n mpTypeVariables = pinfo;\n}\n\nconst ASTFunctionMap& ASTClass::getFunctions() const\n{\n return mFunctions;\n}\n\nASTFunctionMap& ASTClass::getFunctions()\n{\n return mFunctions;\n}\n\nconst ASTFunctionTable& ASTClass::getFunctionTable() const\n{\n return mFunctionTable;\n}\n\nASTFunctionTable& ASTClass::getFunctionTable()\n{\n return mFunctionTable;\n}\n\nconst ASTTypeList& ASTClass::getInterfaces() const\n{\n return mInterfaces;\n}\n \nASTTypeList& ASTClass::getInterfaces()\n{\n return mInterfaces;\n}\n\nconst ASTClass::Fields& ASTClass::getStatics() const\n{\n return mStatics;\n}\n\nconst ASTClass::Fields& ASTClass::getFields() const\n{\n return mFields;\n}\n\nCIL::Class& ASTClass::getCompiledClass()\n{\n ASSERT_PTR(mpCompiledClass);\n return *mpCompiledClass;\n}\n\nCIL::Class* ASTClass::useCompiledClass()\n{\n CIL::Class* presult = mpCompiledClass;\n mpCompiledClass = nullptr;\n return presult;\n}\n\nvoid ASTClass::setCompiledClass(CIL::Class* pclass)\n{\n delete mpCompiledClass;\n mpCompiledClass = pclass;\n}\n\n\/\/ - Query\n\nbool ASTClass::isClass() const\n{\n return mKind == eClass;\n}\n \nbool ASTClass::isInterface() const\n{\n return mKind == eInterface;\n}\n \nbool ASTClass::isBase(const ASTClass& base) const\n{\n if ( this == &base )\n {\n return true;\n }\n else if ( hasBaseClass() )\n {\n const ASTClass& baseclass = getBaseClass();\n\n if ( &baseclass == &base )\n {\n return true;\n }\n else\n {\n return baseclass.isBase(base);\n }\n }\n return false;\n}\n\nbool ASTClass::isImplementing(const ASTClass& intrface) const\n{\n if ( mInterfaces.contains(intrface) )\n {\n return true;\n }\n else if ( hasBaseClass() )\n {\n return getBaseClass().isImplementing(intrface);\n }\n\n return false;\n}\n\nbool ASTClass::isLocal(const ASTFunction& function) const\n{\n return &function.getClass() == this;\n}\n\nbool ASTClass::isNative() const\n{\n return mModifiers.isNative() || hasNativeFunction();\n}\n\nbool ASTClass::isGeneric() const\n{\n return mpTypeVariables != nullptr;\n}\n\nbool ASTClass::isTypeName(const String& name) const\n{\n return isGeneric() && mpTypeVariables->contains(name);\n}\n\nbool ASTClass::hasConstructor() const\n{\n return mFunctions.hasConstructor();\n}\n\nbool ASTClass::hasAbstractFunction() const\n{\n return mFunctions.hasAbstractFunction();\n}\n\nbool ASTClass::hasNativeFunction() const\n{\n return mFunctions.hasNativeFunction();\n}\n\nbool ASTClass::hasNativeConstructor() const\n{\n return mFunctions.hasNativeConstructor();\n}\n\nint ASTClass::getTotalStatics() const\n{\n return mStatics.size();\n}\n\nint ASTClass::getTotalVariables() const\n{\n return mFields.size() + (hasBaseClass() ? getBaseClass().getTotalVariables() : 0);\n}\n\nconst ASTField& ASTClass::getField(int var) const\n{\n if ( mFields.empty() || mFields[0]->getVariable().getResourceIndex() > var )\n {\n return getBaseClass().getField(var);\n }\n\n std::size_t index = var - mFields[0]->getVariable().getResourceIndex();\n ASSERT(index < mFields.size());\n return *mFields[index];\n}\n\n\/\/ - Operations\n \nvoid ASTClass::addInterface(ASTType* ptype)\n{\n mInterfaces.append(ptype);\n}\n\nbool ASTClass::isMember(const String& name) const\n{\n const ASTMember* pmember = findField(name);\n if ( pmember == nullptr )\n {\n pmember = findStatic(name);\n if ( pmember == nullptr )\n {\n return mFunctions.hasFunction(name);\n }\n }\n\n return true;\n}\n\nvoid ASTClass::addMember(ASTMember* pmember)\n{\n switch ( pmember->getKind() )\n {\n case ASTMember::eField:\n {\n ASTField* pfield = static_cast<ASTField*>(pmember);\n\n if ( pfield->getVariable().getModifiers().isStatic() )\n {\n mStatics.push_back(pfield);\n }\n else\n {\n mFields.push_back(pfield);\n }\n }\n break;\n case ASTMember::eConstructor:\n case ASTMember::eFunction:\n {\n ASTFunction* pfunction = static_cast<ASTFunction*>(pmember);\n pfunction->setClass(*this);\n\n mFunctions.insert(pfunction);\n }\n break;\n case ASTMember::eProperty:\n {\n \/\/ not implemented yet\n }\n break;\n }\n\n pmember->setClass(*this);\n addChild(pmember);\n}\n\nvoid ASTClass::insertFunction(int index, ASTFunction* pfunction)\n{\n mFunctions.insert(pfunction);\n mFunctionTable.set(index, *pfunction);\n\n insertChild(index, pfunction);\n}\n\nvoid ASTClass::ensureDefaultConstructor()\n{\n if ( isClass() && !hasConstructor() )\n {\n ASTFunction* pconstructor = new ASTFunction(ASTMember::eConstructor);\n pconstructor->setName(mName);\n pconstructor->setType(new ASTType(ASTType::eVoid));\n pconstructor->getModifiers().setVisibility(ASTModifiers::ePublic);\n\n addMember(pconstructor);\n }\n}\n\nASTType* ASTClass::createThisType() const\n{\n ASTType* presult = new ASTType(ASTType::eObject);\n presult->setObjectName(getFullName());\n presult->setObjectClass(const_cast<ASTClass&>(*this));\n return presult;\n}\n\nvoid ASTClass::collectInterfaces(ASTTypeList& interfaces) const\n{\n interfaces.append(mInterfaces);\n\n if ( hasBaseClass() )\n {\n getBaseClass().collectInterfaces(interfaces);\n }\n}\n\nvoid ASTClass::registerVariables(Scope& scope) const\n{\n if ( hasBaseClass() )\n {\n getBaseClass().registerVariables(scope);\n }\n\n for ( std::size_t index = 0; index < mStatics.size(); index++ )\n {\n ASTField* pstatic = mStatics[index];\n scope.add(ScopeVariable::fromVariable(pstatic->getVariable()));\n }\n\n for ( std::size_t index = 0; index < mFields.size(); index++ )\n {\n ASTField* pvariable = mFields[index];\n scope.add(ScopeVariable::fromVariable(pvariable->getVariable()));\n }\n}\n\nvoid ASTClass::calculateResources()\n{\n indexStatics();\n indexVariables();\n indexFunctions();\n}\n\nvoid ASTClass::indexStatics()\n{\n for ( std::size_t index = 0; index < mStatics.size(); index++ )\n {\n ASTField* pstatic = mStatics[index];\n pstatic->getVariable().setResourceIndex(index);\n }\n}\n\nvoid ASTClass::indexVariables()\n{\n int base = hasBaseClass() ? getBaseClass().getTotalVariables() : 0;\n\n for ( std::size_t index = 0; index < mFields.size(); index++ )\n {\n ASTField* pvariable = mFields[index];\n pvariable->getVariable().setResourceIndex(base + index);\n }\n}\n\nvoid ASTClass::indexFunctions()\n{\n if ( isClass() )\n {\n if ( hasBaseClass() )\n {\n mFunctionTable = getBaseClass().getFunctionTable();\n }\n }\n\n mFunctionTable.build(mFunctions);\n}\n\n\/\/ - Search\n\nconst ASTField* ASTClass::findStatic(const String& name, SearchScope scope) const\n{\n return const_cast<ASTClass&>(*this).findStatic(name, scope);\n}\n\nASTField* ASTClass::findStatic(const String& name, SearchScope scope)\n{\n for ( std::size_t index = 0; index < mStatics.size(); index++ )\n {\n ASTField* pstatic = mStatics[index];\n if ( pstatic->getVariable().getName() == name )\n {\n return pstatic;\n }\n }\n return scope == eAll && hasBaseClass() ? getBaseClass().findStatic(name, eAll) : nullptr;\n}\n\nconst ASTField* ASTClass::findField(const String& name, SearchScope scope) const\n{\n return const_cast<ASTClass&>(*this).findField(name, scope);\n}\n\nASTField* ASTClass::findField(const String& name, SearchScope scope)\n{\n for ( std::size_t index = 0; index < mFields.size(); index++ )\n {\n ASTField* pvariable = mFields[index];\n if ( pvariable->getVariable().getName() == name )\n {\n return pvariable;\n }\n }\n return scope == eAll && hasBaseClass() ? getBaseClass().findField(name) : nullptr;\n}\n\nconst ASTFunction* ASTClass::findBestMatch(const String& name, const ASTSignature& signature, const ASTTypeList& types) const\n{\n return const_cast<ASTClass&>(*this).findBestMatch(name, signature, types);\n}\n\nASTFunction* ASTClass::findBestMatch(const String& name, const ASTSignature& signature, const ASTTypeList& types)\n{\n ASTFunction* pfunction = mFunctions.findBestMatch(name, signature, types);\n if ( pfunction == nullptr && hasBaseClass() )\n {\n pfunction = getBaseClass().findBestMatch(name, signature, types);\n }\n return pfunction;\n}\n\nconst ASTFunction* ASTClass::findExactMatch(const String& name, const ASTSignature& signature) const\n{\n return const_cast<ASTClass&>(*this).findExactMatch(name, signature);\n}\n\nASTFunction* ASTClass::findExactMatch(const String& name, const ASTSignature& signature)\n{\n ASTFunction* pfunction = mFunctions.findExactMatch(name, signature);\n if ( pfunction == nullptr && hasBaseClass() )\n {\n pfunction = getBaseClass().findExactMatch(name, signature);\n }\n return pfunction;\n}\n\n\/\/ - Visitor\n \nACCEPT_IMPL(ASTClass)\n<|endoftext|>"} {"text":"<commit_before>\/* $Id$\n *\n * OpenMAMA: The open middleware agnostic messaging API\n * Copyright (C) 2011 NYSE Technologies, Inc.\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\n * 02110-1301 USA\n *\/\n\n#include <pthread.h>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <assert.h>\n#include <errno.h>\n#include <stdio.h>\n\n#include <mama\/mamacpp.h>\n#include <mamda\/MamdaLock.h>\n \nusing std::string;\nusing std::ostringstream;\nusing std::runtime_error;\n\nnamespace Wombat\n{\n\n class MamdaLock::MamdaLockImpl\n {\n public:\n MamdaLockImpl (MamdaLock::Scheme scheme, \n const char* context,\n int threads);\n ~MamdaLockImpl ();\n\n bool acquire (MamdaLock::Type type);\n bool release (MamdaLock::Type type);\n\n private:\n MamdaLockImpl (const MamdaLockImpl& impl); \/\/ No copying!\n\n void handlePthreadError (int status, \n const string& context);\n\n bool lockMutex (bool throwEx, \n const char* context);\n\n bool unlockMutex (bool throwEx, \n const char* context);\n\n MamdaLock::Scheme mScheme;\n\n pthread_mutex_t mMutex; \n pthread_cond_t mCond;\n pthread_mutexattr_t mMutexAttr;\n\n \/\/ For rwlocking\n pthread_rwlock_t mRwLock;\n pthread_rwlockattr_t mRwLockAttr;\n\n int mCount;\n int mThreads;\n\n char mName [129];\n char mContext [129];\n };\n\n MamdaLock::MamdaLock(\n Scheme scheme, \n const char* context, \n int threads)\n : mImpl (*new MamdaLockImpl(scheme, context, threads)) \n {\n }\n\n MamdaLock::MamdaLockImpl::MamdaLockImpl (\n MamdaLock::Scheme scheme, \n const char* context, \n int threads)\n : mScheme (scheme)\n , mCount (0)\n , mThreads (threads)\n {\n int status = 0;\n\n snprintf (mName, 128, \"%s\", context);\n snprintf (mContext, 128, \"[%s]\", context);\n\n if (MamdaLock::SHARED == scheme)\n {\n status = pthread_rwlockattr_init (&mRwLockAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n\t\t\t \"MamdaLock::MamdaLock(): Failed to init rwlock attr\");\n }\n status = pthread_rwlock_init (&mRwLock, &mRwLockAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n\t\t\t \"MamdaLock::MamdaLock(): Failed to init rwlock attr\");\n }\n return;\n }\n status = pthread_mutexattr_init (&mMutexAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n\t\t \"MamdaLock::MamdaLock(): Failed to init mutex attr\");\n }\n if (MamdaLock::EXCLUSIVE == scheme)\n {\n\n status = pthread_mutexattr_settype(&mMutexAttr, \n\t\t\t\t\t\t PTHREAD_MUTEX_RECURSIVE_NP);\n\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::MamdaLock(): Failed to set mutex \"\n \"attr: PTHREAD_MUTEX_RECURSIVE_NP\");\n }\n }\n\n status = pthread_mutex_init (&mMutex, &mMutexAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::MamdaLock(): \"\n\t\t\t \"Failed to init mutex\");\n }\n\n status = pthread_cond_init (&mCond, NULL);\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::Lock(): Failed to init cond\");\n }\n } \n\n MamdaLock::~MamdaLock()\n {\n delete &mImpl;\n }\n\n MamdaLock::MamdaLockImpl::~MamdaLockImpl()\n {\n if (mScheme == MamdaLock::SHARED)\n {\n int status = pthread_rwlock_destroy (&mRwLock);\n if (0 == status)\n {\n handlePthreadError (status,\n \"MamdaLock::~MamdaLock(): Failed to destroy rwlock\");\n }\n status = pthread_rwlockattr_destroy (&mRwLockAttr);\n if (0 == status)\n {\n handlePthreadError (status,\n \"MamdaLock::~MamdaLock(): Failed to destroy rwlockattr\");\n }\n\n return;\n }\n int status = pthread_mutex_destroy (&mMutex);\n if (0 == status)\n {\n handlePthreadError (status,\n \"MamdaLock::~MamdaLock(): Failed to destroy mutex\");\n }\n status = pthread_cond_destroy (&mCond);\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::MamdaLock(): Failed to destroy cond\");\n }\n\n status = pthread_mutexattr_destroy (&mMutexAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::MamdaLock(): Failed to destroy mutex attr\");\n }\n }\n\n bool MamdaLock::acquire (Type type)\n {\n return mImpl.acquire (type);\n }\n\n bool MamdaLock::MamdaLockImpl::acquire (MamdaLock::Type type)\n {\n bool isLogFinest = (MAMA_LOG_LEVEL_FINEST == mama_getLogLevel());\n\n if (mThreads == -1) \n {\n mCount++;\n if (mCount % 10000 == 0)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquired %d locks so far\\n\",\n mContext, \n mCount);\n }\n return true;\n }\n\n \/\/ For the EXCLUSIVE locking scheme, it just uses\n \/\/ simple mutexes\n if (mScheme == MamdaLock::SHARED) \n {\n if (isLogFinest)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquiring %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n\n if (type == MamdaLock::READ)\n {\n int status = pthread_rwlock_rdlock (&mRwLock);\n\n if (isLogFinest)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquired %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n\n if (status)\n {\n handlePthreadError (false, \"MamdaLock::acquire() rdlock\");\n return false;\n }\n return true;\n }\n else\n { \n int status = pthread_rwlock_wrlock (&mRwLock);\n\n if (isLogFinest)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquired %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n if (status)\n {\n handlePthreadError (false, \"MamdaLock::acquire() wrlock\");\n return false;\n }\n return true;\n }\n }\n else\n { \n if (!lockMutex (false, \"MamdaLock::acquire(): (1)\"))\n return false;\n\n if (isLogFinest)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquired %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n\n return true;\n }\n return true;\n }\n\n bool MamdaLock::release (MamdaLock::Type type)\n {\n return mImpl.release (type);\n }\n\n bool MamdaLock::MamdaLockImpl::release (MamdaLock::Type type)\n {\n if (mThreads == -1) \n return true;\n\n if (MAMA_LOG_LEVEL_FINEST == mama_getLogLevel())\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Releasing %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n\n if (mScheme == MamdaLock::SHARED)\n {\n int status = pthread_rwlock_unlock (&mRwLock);\n\n if (status)\n {\n handlePthreadError (false, \"MamdaLock::acquire() rdlock\");\n return false;\n }\n return true;\n }\n else\n {\n \/\/Release any waiting threads\n if (!unlockMutex (true, \"MamdaLock::release(): (1)\"))\n {\n return false;\n }\n return true;\n }\n }\n\n void MamdaLock::MamdaLockImpl::handlePthreadError (\n int status, \n const string& context)\n {\n if (0 != status)\n {\n string errorStr;\n switch (status)\n {\n case (EINVAL):\n errorStr = \"Mutex not properly initialized!\";\n break;\n case (EDEADLK):\n errorStr = \"Already locked by calling thread!\";\n break;\n case (EPERM):\n errorStr = \"Calling thread does not own the mutex!\";\n break;\n case (EBUSY):\n errorStr = \"thread is currently locked!\";\n break;\n default:\n errorStr = \"unrecognized failure type\";\n break;\n }\n mama_log (MAMA_LOG_LEVEL_NORMAL,\n \"%s: %s (%d)!\\n\", \n mContext, \n errorStr.c_str(),\n status);\n }\n }\n\n bool MamdaLock::MamdaLockImpl::lockMutex (\n bool throwEx,\n const char* context)\n {\n int status = pthread_mutex_lock (&mMutex);\n\n if (0 != status)\n {\n string errMsg = context;\n errMsg += \" lock failed\";\n\n handlePthreadError (status, errMsg);\n\n if (throwEx)\n throw runtime_error (errMsg.c_str());\n return false;\n }\n return true;\n }\n\n bool MamdaLock::MamdaLockImpl::unlockMutex (\n bool throwEx,\n const char* context)\n {\n int status = pthread_mutex_unlock (&mMutex);\n if (0 != status)\n {\n string errMsg = context;\n errMsg += \" unlock failed\";\n\n handlePthreadError (status, errMsg);\n\n if (throwEx)\n throw runtime_error (errMsg.c_str());\n return false;\n }\n return true;\n }\n\n const char* MamdaLock::scheme (Scheme scheme)\n {\n switch(scheme)\n {\n case(SHARED): return \"SHARED\";\n case(EXCLUSIVE): return \"EXCLUSIVE\";\n default: return \"UNKNOWN SCHEME\";\n }\n }\n\n const char* MamdaLock::type (Type type)\n {\n switch(type)\n {\n case(READ): return \"READ\";\n case(WRITE): return \"WRITE\";\n default: return \"UNKNOWN TYPE\";\n }\n }\n\n} \/\/ namespace Wombat\n<commit_msg>MAMDA: Implement WTHREAD_MUTEX_RECURSIVE in MAMDA.<commit_after>\/* $Id$\n *\n * OpenMAMA: The open middleware agnostic messaging API\n * Copyright (C) 2011 NYSE Technologies, Inc.\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\n * 02110-1301 USA\n *\/\n\n#include <pthread.h>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <assert.h>\n#include <errno.h>\n#include <stdio.h>\n\n#include <mama\/mamacpp.h>\n#include <mamda\/MamdaLock.h>\n \nusing std::string;\nusing std::ostringstream;\nusing std::runtime_error;\n\nnamespace Wombat\n{\n\n class MamdaLock::MamdaLockImpl\n {\n public:\n MamdaLockImpl (MamdaLock::Scheme scheme, \n const char* context,\n int threads);\n ~MamdaLockImpl ();\n\n bool acquire (MamdaLock::Type type);\n bool release (MamdaLock::Type type);\n\n private:\n MamdaLockImpl (const MamdaLockImpl& impl); \/\/ No copying!\n\n void handlePthreadError (int status, \n const string& context);\n\n bool lockMutex (bool throwEx, \n const char* context);\n\n bool unlockMutex (bool throwEx, \n const char* context);\n\n MamdaLock::Scheme mScheme;\n\n pthread_mutex_t mMutex; \n pthread_cond_t mCond;\n pthread_mutexattr_t mMutexAttr;\n\n \/\/ For rwlocking\n pthread_rwlock_t mRwLock;\n pthread_rwlockattr_t mRwLockAttr;\n\n int mCount;\n int mThreads;\n\n char mName [129];\n char mContext [129];\n };\n\n MamdaLock::MamdaLock(\n Scheme scheme, \n const char* context, \n int threads)\n : mImpl (*new MamdaLockImpl(scheme, context, threads)) \n {\n }\n\n MamdaLock::MamdaLockImpl::MamdaLockImpl (\n MamdaLock::Scheme scheme, \n const char* context, \n int threads)\n : mScheme (scheme)\n , mCount (0)\n , mThreads (threads)\n {\n int status = 0;\n\n snprintf (mName, 128, \"%s\", context);\n snprintf (mContext, 128, \"[%s]\", context);\n\n if (MamdaLock::SHARED == scheme)\n {\n status = pthread_rwlockattr_init (&mRwLockAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n\t\t\t \"MamdaLock::MamdaLock(): Failed to init rwlock attr\");\n }\n status = pthread_rwlock_init (&mRwLock, &mRwLockAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n\t\t\t \"MamdaLock::MamdaLock(): Failed to init rwlock attr\");\n }\n return;\n }\n status = pthread_mutexattr_init (&mMutexAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n\t\t \"MamdaLock::MamdaLock(): Failed to init mutex attr\");\n }\n if (MamdaLock::EXCLUSIVE == scheme)\n {\n\n status = pthread_mutexattr_settype(&mMutexAttr, \n\t\t\t\t\t\t WTHREAD_MUTEX_RECURSIVE);\n\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::MamdaLock(): Failed to set mutex \"\n \"attr: PTHREAD_MUTEX_RECURSIVE_NP\");\n }\n }\n\n status = pthread_mutex_init (&mMutex, &mMutexAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::MamdaLock(): \"\n\t\t\t \"Failed to init mutex\");\n }\n\n status = pthread_cond_init (&mCond, NULL);\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::Lock(): Failed to init cond\");\n }\n } \n\n MamdaLock::~MamdaLock()\n {\n delete &mImpl;\n }\n\n MamdaLock::MamdaLockImpl::~MamdaLockImpl()\n {\n if (mScheme == MamdaLock::SHARED)\n {\n int status = pthread_rwlock_destroy (&mRwLock);\n if (0 == status)\n {\n handlePthreadError (status,\n \"MamdaLock::~MamdaLock(): Failed to destroy rwlock\");\n }\n status = pthread_rwlockattr_destroy (&mRwLockAttr);\n if (0 == status)\n {\n handlePthreadError (status,\n \"MamdaLock::~MamdaLock(): Failed to destroy rwlockattr\");\n }\n\n return;\n }\n int status = pthread_mutex_destroy (&mMutex);\n if (0 == status)\n {\n handlePthreadError (status,\n \"MamdaLock::~MamdaLock(): Failed to destroy mutex\");\n }\n status = pthread_cond_destroy (&mCond);\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::MamdaLock(): Failed to destroy cond\");\n }\n\n status = pthread_mutexattr_destroy (&mMutexAttr);\n if (0 != status)\n {\n handlePthreadError (status,\n \"MamdaLock::MamdaLock(): Failed to destroy mutex attr\");\n }\n }\n\n bool MamdaLock::acquire (Type type)\n {\n return mImpl.acquire (type);\n }\n\n bool MamdaLock::MamdaLockImpl::acquire (MamdaLock::Type type)\n {\n bool isLogFinest = (MAMA_LOG_LEVEL_FINEST == mama_getLogLevel());\n\n if (mThreads == -1) \n {\n mCount++;\n if (mCount % 10000 == 0)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquired %d locks so far\\n\",\n mContext, \n mCount);\n }\n return true;\n }\n\n \/\/ For the EXCLUSIVE locking scheme, it just uses\n \/\/ simple mutexes\n if (mScheme == MamdaLock::SHARED) \n {\n if (isLogFinest)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquiring %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n\n if (type == MamdaLock::READ)\n {\n int status = pthread_rwlock_rdlock (&mRwLock);\n\n if (isLogFinest)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquired %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n\n if (status)\n {\n handlePthreadError (false, \"MamdaLock::acquire() rdlock\");\n return false;\n }\n return true;\n }\n else\n { \n int status = pthread_rwlock_wrlock (&mRwLock);\n\n if (isLogFinest)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquired %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n if (status)\n {\n handlePthreadError (false, \"MamdaLock::acquire() wrlock\");\n return false;\n }\n return true;\n }\n }\n else\n { \n if (!lockMutex (false, \"MamdaLock::acquire(): (1)\"))\n return false;\n\n if (isLogFinest)\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Acquired %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n\n return true;\n }\n return true;\n }\n\n bool MamdaLock::release (MamdaLock::Type type)\n {\n return mImpl.release (type);\n }\n\n bool MamdaLock::MamdaLockImpl::release (MamdaLock::Type type)\n {\n if (mThreads == -1) \n return true;\n\n if (MAMA_LOG_LEVEL_FINEST == mama_getLogLevel())\n {\n mama_log (MAMA_LOG_LEVEL_FINEST,\n \"%s: Releasing %s lock using scheme %s PID(%d)\\n\",\n mContext, \n MamdaLock::type (type), \n MamdaLock::scheme (mScheme), \n (void*)pthread_self());\n }\n\n if (mScheme == MamdaLock::SHARED)\n {\n int status = pthread_rwlock_unlock (&mRwLock);\n\n if (status)\n {\n handlePthreadError (false, \"MamdaLock::acquire() rdlock\");\n return false;\n }\n return true;\n }\n else\n {\n \/\/Release any waiting threads\n if (!unlockMutex (true, \"MamdaLock::release(): (1)\"))\n {\n return false;\n }\n return true;\n }\n }\n\n void MamdaLock::MamdaLockImpl::handlePthreadError (\n int status, \n const string& context)\n {\n if (0 != status)\n {\n string errorStr;\n switch (status)\n {\n case (EINVAL):\n errorStr = \"Mutex not properly initialized!\";\n break;\n case (EDEADLK):\n errorStr = \"Already locked by calling thread!\";\n break;\n case (EPERM):\n errorStr = \"Calling thread does not own the mutex!\";\n break;\n case (EBUSY):\n errorStr = \"thread is currently locked!\";\n break;\n default:\n errorStr = \"unrecognized failure type\";\n break;\n }\n mama_log (MAMA_LOG_LEVEL_NORMAL,\n \"%s: %s (%d)!\\n\", \n mContext, \n errorStr.c_str(),\n status);\n }\n }\n\n bool MamdaLock::MamdaLockImpl::lockMutex (\n bool throwEx,\n const char* context)\n {\n int status = pthread_mutex_lock (&mMutex);\n\n if (0 != status)\n {\n string errMsg = context;\n errMsg += \" lock failed\";\n\n handlePthreadError (status, errMsg);\n\n if (throwEx)\n throw runtime_error (errMsg.c_str());\n return false;\n }\n return true;\n }\n\n bool MamdaLock::MamdaLockImpl::unlockMutex (\n bool throwEx,\n const char* context)\n {\n int status = pthread_mutex_unlock (&mMutex);\n if (0 != status)\n {\n string errMsg = context;\n errMsg += \" unlock failed\";\n\n handlePthreadError (status, errMsg);\n\n if (throwEx)\n throw runtime_error (errMsg.c_str());\n return false;\n }\n return true;\n }\n\n const char* MamdaLock::scheme (Scheme scheme)\n {\n switch(scheme)\n {\n case(SHARED): return \"SHARED\";\n case(EXCLUSIVE): return \"EXCLUSIVE\";\n default: return \"UNKNOWN SCHEME\";\n }\n }\n\n const char* MamdaLock::type (Type type)\n {\n switch(type)\n {\n case(READ): return \"READ\";\n case(WRITE): return \"WRITE\";\n default: return \"UNKNOWN TYPE\";\n }\n }\n\n} \/\/ namespace Wombat\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The zScale Authors <legal@zscale.io>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"stx\/stdtypes.h\"\n#include \"stx\/test\/unittest.h\"\n#include \"zbase\/core\/ReplicationScheme.h\"\n\nusing namespace stx;\nusing namespace zbase;\n\nUNIT_TEST(ReplicationSchemeTest);\n\nTEST_CASE(ReplicationSchemeTest, TestHostAssignmentWithTwoNodes, [] () {\n ClusterConfig cc;\n cc.set_dht_num_copies(3);\n\n {\n auto node = cc.add_dht_nodes();\n node->set_status(DHTNODE_LIVE);\n node->set_name(\"nodeA\");\n node->set_addr(\"1.1.1.1:1234\");\n *node->add_sha1_tokens() = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\n *node->add_sha1_tokens() = \"6666666666666666666666666666666666666666\";\n }\n\n {\n auto node = cc.add_dht_nodes();\n node->set_status(DHTNODE_LIVE);\n node->set_name(\"nodeB\");\n node->set_addr(\"2.2.2.2:1234\");\n *node->add_sha1_tokens() = \"3333333333333333333333333333333333333333\";\n }\n\n\n DHTReplicationScheme rscheme(cc);\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"1111111111111111111111111111111111111111\"));\n\n EXPECT_EQ(replicas.size(), 2);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"2.2.2.2:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"6666666666666666666666666666666666666666\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"1.1.1.1:1234\");\n }\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"8888888888888888888888888888888888888888\"));\n\n EXPECT_EQ(replicas.size(), 2);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"1.1.1.1:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"2.2.2.2:1234\");\n }\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"dddddddddddddddddddddddddddddddddddddddd\"));\n\n EXPECT_EQ(replicas.size(), 2);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"2.2.2.2:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"6666666666666666666666666666666666666666\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"1.1.1.1:1234\");\n }\n});\n\n\n<commit_msg>ReplicationSchemeTest...<commit_after>\/**\n * Copyright (c) 2015 - The zScale Authors <legal@zscale.io>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"stx\/stdtypes.h\"\n#include \"stx\/test\/unittest.h\"\n#include \"zbase\/core\/ReplicationScheme.h\"\n\nusing namespace stx;\nusing namespace zbase;\n\nUNIT_TEST(ReplicationSchemeTest);\n\nTEST_CASE(ReplicationSchemeTest, TestHostAssignmentWithTwoNodes, [] () {\n ClusterConfig cc;\n cc.set_dht_num_copies(3);\n\n {\n auto node = cc.add_dht_nodes();\n node->set_status(DHTNODE_LIVE);\n node->set_name(\"nodeA\");\n node->set_addr(\"1.1.1.1:1234\");\n *node->add_sha1_tokens() = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\n *node->add_sha1_tokens() = \"6666666666666666666666666666666666666666\";\n }\n\n {\n auto node = cc.add_dht_nodes();\n node->set_status(DHTNODE_LIVE);\n node->set_name(\"nodeB\");\n node->set_addr(\"2.2.2.2:1234\");\n *node->add_sha1_tokens() = \"3333333333333333333333333333333333333333\";\n }\n\n\n DHTReplicationScheme rscheme(cc);\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"1111111111111111111111111111111111111111\"));\n\n EXPECT_EQ(replicas.size(), 2);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"2.2.2.2:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"6666666666666666666666666666666666666666\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"1.1.1.1:1234\");\n }\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"8888888888888888888888888888888888888888\"));\n\n EXPECT_EQ(replicas.size(), 2);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"1.1.1.1:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"2.2.2.2:1234\");\n }\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"dddddddddddddddddddddddddddddddddddddddd\"));\n\n EXPECT_EQ(replicas.size(), 2);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"2.2.2.2:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"6666666666666666666666666666666666666666\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"1.1.1.1:1234\");\n }\n});\n\nTEST_CASE(ReplicationSchemeTest, TestHostAssignmentWithThreeNodes, [] () {\n ClusterConfig cc;\n cc.set_dht_num_copies(3);\n\n {\n auto node = cc.add_dht_nodes();\n node->set_status(DHTNODE_LIVE);\n node->set_name(\"nodeA\");\n node->set_addr(\"1.1.1.1:1234\");\n *node->add_sha1_tokens() = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\n *node->add_sha1_tokens() = \"6666666666666666666666666666666666666666\";\n }\n\n {\n auto node = cc.add_dht_nodes();\n node->set_status(DHTNODE_LIVE);\n node->set_name(\"nodeB\");\n node->set_addr(\"2.2.2.2:1234\");\n *node->add_sha1_tokens() = \"3333333333333333333333333333333333333333\";\n }\n\n {\n auto node = cc.add_dht_nodes();\n node->set_status(DHTNODE_LIVE);\n node->set_name(\"nodeC\");\n node->set_addr(\"3.3.3.3:1234\");\n *node->add_sha1_tokens() = \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\";\n *node->add_sha1_tokens() = \"fcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfc\";\n }\n\n\n DHTReplicationScheme rscheme(cc);\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"1111111111111111111111111111111111111111\"));\n\n EXPECT_EQ(replicas.size(), 3);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"2.2.2.2:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"6666666666666666666666666666666666666666\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"1.1.1.1:1234\");\n EXPECT_EQ(\n replicas[2].unique_id.toString(),\n \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\");\n EXPECT_EQ(replicas[2].addr.ipAndPort(), \"3.3.3.3:1234\");\n }\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"8888888888888888888888888888888888888888\"));\n\n EXPECT_EQ(replicas.size(), 3);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"1.1.1.1:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"3.3.3.3:1234\");\n EXPECT_EQ(\n replicas[2].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[2].addr.ipAndPort(), \"2.2.2.2:1234\");\n }\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"dddddddddddddddddddddddddddddddddddddddd\"));\n\n EXPECT_EQ(replicas.size(), 3);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"fcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfc\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"3.3.3.3:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"2.2.2.2:1234\");\n EXPECT_EQ(\n replicas[2].unique_id.toString(),\n \"6666666666666666666666666666666666666666\");\n EXPECT_EQ(replicas[2].addr.ipAndPort(), \"1.1.1.1:1234\");\n }\n\n {\n auto replicas = rscheme.replicasFor(\n SHA1Hash::fromHexString(\"fdfdfdfdfdfdfdfdfdfdfdfdfdfdfdfdfdfdfdfd\"));\n\n EXPECT_EQ(replicas.size(), 3);\n EXPECT_EQ(\n replicas[0].unique_id.toString(),\n \"3333333333333333333333333333333333333333\");\n EXPECT_EQ(replicas[0].addr.ipAndPort(), \"2.2.2.2:1234\");\n EXPECT_EQ(\n replicas[1].unique_id.toString(),\n \"6666666666666666666666666666666666666666\");\n EXPECT_EQ(replicas[1].addr.ipAndPort(), \"1.1.1.1:1234\");\n EXPECT_EQ(\n replicas[2].unique_id.toString(),\n \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\");\n EXPECT_EQ(replicas[2].addr.ipAndPort(), \"3.3.3.3:1234\");\n }\n});\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2011 Google Inc.\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 \"syzygy\/relink\/order_relinker.h\"\n#include \"syzygy\/reorder\/random_order_generator.h\"\n#include \"base\/file_util.h\"\n#include \"gtest\/gtest.h\"\n#include \"syzygy\/pe\/decomposer.h\"\n#include \"syzygy\/pe\/pe_file.h\"\n#include \"syzygy\/pe\/unittest_util.h\"\n\nclass OrderRelinkerTest : public testing::PELibUnitTest {\n protected:\n static const FilePath kInstrDllName;\n static const FilePath kOrderFileName;\n static const FilePath kTestDataDir;\n};\n\nconst FilePath OrderRelinkerTest::kOrderFileName(L\"order_file.json\");\nconst FilePath OrderRelinkerTest::kInstrDllName(L\"instrumented_test_dll.dll\");\nconst FilePath OrderRelinkerTest::kTestDataDir(L\"test_data\");\n\nusing reorder::RandomOrderGenerator;\nusing reorder::Reorderer;\n\nTEST_F(OrderRelinkerTest, Relink) {\n FilePath temp_dir;\n ASSERT_NO_FATAL_FAILURE(CreateTemporaryDir(&temp_dir));\n FilePath output_dll_path = temp_dir.Append(kDllName);\n FilePath output_pdb_path = temp_dir.Append(kDllPdbName);\n FilePath order_file_path = temp_dir.Append(kOrderFileName);\n\n FilePath test_data_dir = GetExeRelativePath(kTestDataDir.value().c_str());\n FilePath input_dll_path = test_data_dir.Append(kDllName);\n FilePath input_pdb_path = test_data_dir.Append(kDllPdbName);\n FilePath instr_dll_path = test_data_dir.Append(kInstrDllName);\n\n pe::PEFile pe_file;\n pe::Decomposer::DecomposedImage decomposed;\n reorder::Reorderer::Order order(pe_file, decomposed);\n reorder::RandomOrderGenerator order_generator(12345);\n std::vector<FilePath> trace_paths;\n reorder::Reorderer::Flags flags = 0;\n Reorderer reorderer(input_dll_path,\n instr_dll_path,\n trace_paths,\n flags);\n ASSERT_TRUE(reorderer.Reorder(&order_generator, &order));\n ASSERT_TRUE(order.SerializeToJSON(order_file_path, true));\n\n relink::OrderRelinker relinker(order_file_path);\n ASSERT_TRUE(relinker.Relink(input_dll_path,\n input_pdb_path,\n output_dll_path,\n output_pdb_path));\n ASSERT_NO_FATAL_FAILURE(CheckTestDll(output_dll_path));\n}\n\nTEST_F(OrderRelinkerTest, RelinkWithPadding) {\n FilePath temp_dir;\n ASSERT_NO_FATAL_FAILURE(CreateTemporaryDir(&temp_dir));\n FilePath output_dll_path = temp_dir.Append(kDllName);\n FilePath output_pdb_path = temp_dir.Append(kDllPdbName);\n FilePath order_file_path = temp_dir.Append(kOrderFileName);\n\n FilePath test_data_dir = GetExeRelativePath(kTestDataDir.value().c_str());\n FilePath input_dll_path = test_data_dir.Append(kDllName);\n FilePath input_pdb_path = test_data_dir.Append(kDllPdbName);\n FilePath instr_dll_path = test_data_dir.Append(kInstrDllName);\n\n pe::PEFile pe_file;\n pe::Decomposer::DecomposedImage decomposed;\n reorder::Reorderer::Order order(pe_file, decomposed);\n reorder::RandomOrderGenerator order_generator(12345);\n std::vector<FilePath> trace_paths;\n reorder::Reorderer::Flags flags = 0;\n Reorderer reorderer(input_dll_path,\n instr_dll_path,\n trace_paths,\n flags);\n ASSERT_TRUE(reorderer.Reorder(&order_generator, &order));\n ASSERT_TRUE(order.SerializeToJSON(order_file_path, true));\n\n relink::OrderRelinker relinker(order_file_path);\n relinker.set_padding_length(32);\n ASSERT_TRUE(relinker.Relink(input_dll_path,\n input_pdb_path,\n output_dll_path,\n output_pdb_path));\n ASSERT_NO_FATAL_FAILURE(CheckTestDll(output_dll_path));\n}\n<commit_msg>Fix a noop unittest<commit_after>\/\/ Copyright 2011 Google Inc.\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 \"syzygy\/relink\/order_relinker.h\"\n#include \"syzygy\/reorder\/random_order_generator.h\"\n#include \"base\/file_util.h\"\n#include \"gtest\/gtest.h\"\n#include \"syzygy\/pe\/decomposer.h\"\n#include \"syzygy\/pe\/pe_file.h\"\n#include \"syzygy\/pe\/unittest_util.h\"\n\nclass OrderRelinkerTest : public testing::PELibUnitTest {\n protected:\n static const FilePath kInstrDllName;\n static const FilePath kOrderFileName;\n static const FilePath kTestDataDir;\n};\n\nconst FilePath OrderRelinkerTest::kOrderFileName(L\"order_file.json\");\nconst FilePath OrderRelinkerTest::kInstrDllName(L\"instrumented_test_dll.dll\");\nconst FilePath OrderRelinkerTest::kTestDataDir(L\"test_data\");\n\nusing reorder::RandomOrderGenerator;\nusing reorder::Reorderer;\n\nTEST_F(OrderRelinkerTest, Relink) {\n FilePath temp_dir;\n ASSERT_NO_FATAL_FAILURE(CreateTemporaryDir(&temp_dir));\n FilePath output_dll_path = temp_dir.Append(kDllName);\n FilePath output_pdb_path = temp_dir.Append(kDllPdbName);\n FilePath order_file_path = temp_dir.Append(kOrderFileName);\n\n FilePath test_data_dir = GetExeRelativePath(kTestDataDir.value().c_str());\n FilePath input_dll_path = test_data_dir.Append(kDllName);\n FilePath input_pdb_path = test_data_dir.Append(kDllPdbName);\n FilePath instr_dll_path = test_data_dir.Append(kInstrDllName);\n\n pe::PEFile pe_file;\n pe::Decomposer::DecomposedImage decomposed;\n reorder::Reorderer::Order order(pe_file, decomposed);\n reorder::RandomOrderGenerator order_generator(12345);\n std::vector<FilePath> trace_paths;\n reorder::Reorderer::Flags flags = reorder::Reorderer::kFlagReorderCode |\n reorder::Reorderer::kFlagReorderData;\n Reorderer reorderer(input_dll_path,\n instr_dll_path,\n trace_paths,\n flags);\n ASSERT_TRUE(reorderer.Reorder(&order_generator, &order));\n ASSERT_TRUE(order.SerializeToJSON(order_file_path, true));\n\n relink::OrderRelinker relinker(order_file_path);\n ASSERT_TRUE(relinker.Relink(input_dll_path,\n input_pdb_path,\n output_dll_path,\n output_pdb_path));\n ASSERT_NO_FATAL_FAILURE(CheckTestDll(output_dll_path));\n}\n\nTEST_F(OrderRelinkerTest, RelinkWithPadding) {\n FilePath temp_dir;\n ASSERT_NO_FATAL_FAILURE(CreateTemporaryDir(&temp_dir));\n FilePath output_dll_path = temp_dir.Append(kDllName);\n FilePath output_pdb_path = temp_dir.Append(kDllPdbName);\n FilePath order_file_path = temp_dir.Append(kOrderFileName);\n\n FilePath test_data_dir = GetExeRelativePath(kTestDataDir.value().c_str());\n FilePath input_dll_path = test_data_dir.Append(kDllName);\n FilePath input_pdb_path = test_data_dir.Append(kDllPdbName);\n FilePath instr_dll_path = test_data_dir.Append(kInstrDllName);\n\n pe::PEFile pe_file;\n pe::Decomposer::DecomposedImage decomposed;\n reorder::Reorderer::Order order(pe_file, decomposed);\n reorder::RandomOrderGenerator order_generator(12345);\n std::vector<FilePath> trace_paths;\n reorder::Reorderer::Flags flags = reorder::Reorderer::kFlagReorderCode |\n reorder::Reorderer::kFlagReorderData;\n Reorderer reorderer(input_dll_path,\n instr_dll_path,\n trace_paths,\n flags);\n ASSERT_TRUE(reorderer.Reorder(&order_generator, &order));\n ASSERT_TRUE(order.SerializeToJSON(order_file_path, true));\n\n relink::OrderRelinker relinker(order_file_path);\n relinker.set_padding_length(32);\n ASSERT_TRUE(relinker.Relink(input_dll_path,\n input_pdb_path,\n output_dll_path,\n output_pdb_path));\n ASSERT_NO_FATAL_FAILURE(CheckTestDll(output_dll_path));\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>hacker rank<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Fixed some bugs.<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.\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 find a copy of the License in the LICENCE file.\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 * @file SinogramCreator.cpp\n *\/\n\n#include \"SinogramCreator.h\"\n\nSinogramCreator::SinogramCreator(const char* name) : JPetUserTask(name) {}\n\nSinogramCreator::~SinogramCreator() {}\n\nbool SinogramCreator::init()\n{\n auto opts = getOptions();\n fOutputEvents = new JPetTimeWindow(\"JPetEvent\");\n\n return true;\n}\n\nbool SinogramCreator::exec()\n{\n assert(kNumberOfScintillatorsInReconstructionLayer % 2 == 0); \/\/ number of scintillators always should be parzysta\n\n int numberOfScintillatorsInHalf = kNumberOfScintillatorsInReconstructionLayer \/ 2;\n float reconstructionAngleDiff = kReconstructionEndAngle - kReconstructionStartAngle;\n float reconstructionAngleStep = (reconstructionAngleDiff) \/ static_cast<float>(numberOfScintillatorsInHalf);\n\n int maxThetaNumber = (reconstructionAngleDiff \/ reconstructionAngleStep) + 1;\n int maxDistanceNumber = std::floor(kReconstructionLayerRadius * 2 * (1.f \/ kReconstructionDistanceAccuracy)) + 1;\n if (fSinogram == nullptr) {\n fSinogram = new SinogramResultType(maxDistanceNumber, (std::vector<int>(maxThetaNumber)));\n }\n if (const auto& timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {\n unsigned int numberOfEventsInTimeWindow = timeWindow->getNumberOfEvents();\n for (unsigned int i = 0; i < numberOfEventsInTimeWindow; i++) {\n auto event = dynamic_cast<const JPetEvent&>(timeWindow->operator[](static_cast<int>(i)));\n auto hits = event.getHits();\n if (hits.size() == 2) {\n const auto& firstHit = hits[0];\n const auto& secondHit = hits[1];\n if (checkLayer(firstHit) && checkLayer(secondHit)) {\n for (float theta = kReconstructionStartAngle; theta < kReconstructionEndAngle; theta += reconstructionAngleStep) {\n float x = kReconstructionLayerRadius * std::cos(theta * (M_PI \/ 180));\n float y = kReconstructionLayerRadius * std::sin(theta * (M_PI \/ 180));\n std::pair<float, float> intersectionPoint = SinogramCreatorTools::lineIntersection(std::make_pair(-x, -y), std::make_pair(x, y),\n std::make_pair(firstHit.getPosX(), firstHit.getPosY()), std::make_pair(secondHit.getPosX(), secondHit.getPosY()));\n if (intersectionPoint.first != std::numeric_limits<float>::max() && intersectionPoint.second != std::numeric_limits<float>::max()) {\n float distance = SinogramCreatorTools::length2D(intersectionPoint.first, intersectionPoint.second);\n if (intersectionPoint.first < 0.f)\n distance = -distance;\n int distanceRound = std::floor((kReconstructionLayerRadius \/ kReconstructionDistanceAccuracy)\n + kReconstructionDistanceAccuracy)\n + std::floor((distance \/ kReconstructionDistanceAccuracy) + kReconstructionDistanceAccuracy);\n int thetaNumber = theta \/ reconstructionAngleStep;\n \/\/if (thetaNumber >= maxThetaNumber || distanceRound >= maxDistanceNumber) {\n std::cout << \"Theta: \" << thetaNumber << \" maxTheta: \" << maxThetaNumber << \" distanceRound: \" << distanceRound << \" maxDistanceRound: \" << maxDistanceNumber << \" distance: \" << distance << \" ix: \" << intersectionPoint.first << \" iy: \" << intersectionPoint.second << \" x1: \" << firstHit.getPosX() << \" y1: \" << firstHit.getPosY() << \" x2: \" << secondHit.getPosX() << \" y2: \" << secondHit.getPosY() << std::endl;\n \/\/}\n fSinogram->at(distanceRound).at(thetaNumber)++;\n }\n }\n }\n }\n }\n } else {\n ERROR(\"Returned event is not TimeWindow\");\n return false;\n }\n return true;\n}\n\nbool SinogramCreator::checkLayer(const JPetHit& hit)\n{\n return hit.getBarrelSlot().getLayer().getID() == 1;\n}\n\nbool SinogramCreator::terminate()\n{\n const auto outFile = \"sinogram.ppm\";\n std::ofstream res(outFile);\n res << \"P2\" << std::endl;\n res << (*fSinogram)[0].size() << \" \" << fSinogram->size() << std::endl;\n res << \"255\" << std::endl;\n for (unsigned int i = 0; i < fSinogram->size(); i++) {\n for (unsigned int j = 0; j < (*fSinogram)[0].size(); j++) {\n res << static_cast<int>((*fSinogram)[i][j]) << \" \";\n }\n res << std::endl;\n }\n res.close();\n return true;\n}\n<commit_msg>Add condition to filter events with radius greather then reconstruction layer<commit_after>\/**\n * @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.\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 find a copy of the License in the LICENCE file.\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 * @file SinogramCreator.cpp\n *\/\n\n#include \"SinogramCreator.h\"\n\nSinogramCreator::SinogramCreator(const char* name) : JPetUserTask(name) {}\n\nSinogramCreator::~SinogramCreator() {}\n\nbool SinogramCreator::init()\n{\n auto opts = getOptions();\n fOutputEvents = new JPetTimeWindow(\"JPetEvent\");\n\n return true;\n}\n\nbool SinogramCreator::exec()\n{\n assert(kNumberOfScintillatorsInReconstructionLayer % 2 == 0); \/\/ number of scintillators always should be parzysta\n\n int numberOfScintillatorsInHalf = kNumberOfScintillatorsInReconstructionLayer \/ 2;\n float reconstructionAngleDiff = kReconstructionEndAngle - kReconstructionStartAngle;\n float reconstructionAngleStep = (reconstructionAngleDiff) \/ static_cast<float>(numberOfScintillatorsInHalf);\n\n int maxThetaNumber = (reconstructionAngleDiff \/ reconstructionAngleStep) + 1;\n int maxDistanceNumber = std::floor(kReconstructionLayerRadius * 2 * (1.f \/ kReconstructionDistanceAccuracy)) + 1;\n if (fSinogram == nullptr) {\n fSinogram = new SinogramResultType(maxDistanceNumber, (std::vector<int>(maxThetaNumber)));\n }\n if (const auto& timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {\n unsigned int numberOfEventsInTimeWindow = timeWindow->getNumberOfEvents();\n for (unsigned int i = 0; i < numberOfEventsInTimeWindow; i++) {\n auto event = dynamic_cast<const JPetEvent&>(timeWindow->operator[](static_cast<int>(i)));\n auto hits = event.getHits();\n if (hits.size() == 2) {\n const auto& firstHit = hits[0];\n const auto& secondHit = hits[1];\n if (checkLayer(firstHit) && checkLayer(secondHit)) {\n for (float theta = kReconstructionStartAngle; theta < kReconstructionEndAngle; theta += reconstructionAngleStep) {\n float x = kReconstructionLayerRadius * std::cos(theta * (M_PI \/ 180));\n float y = kReconstructionLayerRadius * std::sin(theta * (M_PI \/ 180));\n std::pair<float, float> intersectionPoint = SinogramCreatorTools::lineIntersection(std::make_pair(-x, -y), std::make_pair(x, y),\n std::make_pair(firstHit.getPosX(), firstHit.getPosY()), std::make_pair(secondHit.getPosX(), secondHit.getPosY()));\n if (intersectionPoint.first != std::numeric_limits<float>::max() && intersectionPoint.second != std::numeric_limits<float>::max()) {\n float distance = SinogramCreatorTools::length2D(intersectionPoint.first, intersectionPoint.second);\n if (distance >= kReconstructionLayerRadius) \/\/ if distance is greather then our max reconstuction layer radius, it cant be placed in sinogram\n continue;\n if (intersectionPoint.first < 0.f)\n distance = -distance;\n int distanceRound = std::floor((kReconstructionLayerRadius \/ kReconstructionDistanceAccuracy)\n + kReconstructionDistanceAccuracy)\n + std::floor((distance \/ kReconstructionDistanceAccuracy) + kReconstructionDistanceAccuracy);\n int thetaNumber = theta \/ reconstructionAngleStep;\n \/\/if (thetaNumber >= maxThetaNumber || distanceRound >= maxDistanceNumber) {\n std::cout << \"Theta: \" << thetaNumber << \" maxTheta: \" << maxThetaNumber << \" distanceRound: \" << distanceRound << \" maxDistanceRound: \" << maxDistanceNumber << \" distance: \" << distance << \" ix: \" << intersectionPoint.first << \" iy: \" << intersectionPoint.second << \" x1: \" << firstHit.getPosX() << \" y1: \" << firstHit.getPosY() << \" x2: \" << secondHit.getPosX() << \" y2: \" << secondHit.getPosY() << std::endl;\n \/\/}\n fSinogram->at(distanceRound).at(thetaNumber)++;\n }\n }\n }\n }\n }\n } else {\n ERROR(\"Returned event is not TimeWindow\");\n return false;\n }\n return true;\n}\n\nbool SinogramCreator::checkLayer(const JPetHit& hit)\n{\n return hit.getBarrelSlot().getLayer().getID() == 1;\n}\n\nbool SinogramCreator::terminate()\n{\n const auto outFile = \"sinogram.ppm\";\n std::ofstream res(outFile);\n res << \"P2\" << std::endl;\n res << (*fSinogram)[0].size() << \" \" << fSinogram->size() << std::endl;\n res << \"255\" << std::endl;\n for (unsigned int i = 0; i < fSinogram->size(); i++) {\n for (unsigned int j = 0; j < (*fSinogram)[0].size(); j++) {\n res << static_cast<int>((*fSinogram)[i][j]) << \" \";\n }\n res << std::endl;\n }\n res.close();\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Poco\/Exception.h>\n\n#include \"ui\/PlaceHandler.h\"\n#include \"ui\/Serializing.h\"\n\nusing namespace std;\nusing namespace Poco;\nusing namespace BeeeOn;\nusing namespace BeeeOn::UI;\n\nPlaceHandler::PlaceHandler()\n{\n\tinjector<PlaceHandler, PlaceService>(\"placeService\",\n\t\t\t&PlaceHandler::setPlaceService);\n\tinjector<PlaceHandler, IdentityService>(\"identityService\",\n\t\t\t&PlaceHandler::setIdentityService);\n\tinjector<PlaceHandler, PlaceAccessPolicy>(\"accessPolicy\",\n\t\t\t&PlaceHandler::setAccessPolicy);\n}\n\nconst string PlaceHandler::handleCreate(istream &in,\n\t\tconst VerifiedIdentityID &identityID)\n{\n\tVerifiedIdentity identity(identityID);\n\tif (!m_identityService->fetch(identity))\n\t\tthrow InvalidAccessException(\"no such identity\");\n\n\tPlace place;\n\tdeserialize(in, place);\n\n\tm_placeService->create(place, identity.identity());\n\treturn serialize(place);\n}\n\nconst string PlaceHandler::handleUpdate(istream &in,\n\t\tconst UserID &userId,\n\t\tconst string &placeId)\n{\n\tPlace place(PlaceID::parse(placeId));\n\tUser user(userId);\n\n\tm_accessPolicy->assureUpdate(user, place);\n\n\tif (!m_placeService->fetch(place))\n\t\treturn \"\";\n\n\tdeserialize(in, place);\n\n\tif (!m_placeService->update(place)) {\n\t\tthrow Exception(\"failed to update place: \"\n\t\t\t\t+ place.id().toString());\n\t}\n\n\treturn serialize(place);\n}\n\nconst string PlaceHandler::handleGet(const UserID &userId,\n\t\tconst string &placeId)\n{\n\tPlace place(PlaceID::parse(placeId));\n\tUser user(userId);\n\n\tm_accessPolicy->assureGet(user, place);\n\n\tif (!m_placeService->fetch(place)) {\n\t\treturn \"\";\n\t}\n\n\treturn serialize(place);\n}\n\nconst string PlaceHandler::handleDelete(const UserID &userId,\n\t\tconst string &placeId)\n{\n\tPlace place(PlaceID::parse(placeId));\n\tUser user(userId);\n\n\tm_accessPolicy->assureRemove(user, place);\n\n\tif (!m_placeService->fetch(place))\n\t\treturn \"\";\n\n\tif (!m_placeService->remove(place, user))\n\t\treturn \"\";\n\n\treturn serialize(place);\n}\n\nconst string PlaceHandler::handleGetAll(const UserID &userId)\n{\n\tUser user(userId);\n\tstd::vector<Place> places;\n\n\tm_placeService->fetchAccessible(places, user);\n\treturn serialize(places);\n}\n\nBEEEON_OBJECT(PlaceHandler, BeeeOn::UI::PlaceHandler)\n<commit_msg>PlaceHandler: avoid redundant fetch<commit_after>#include <Poco\/Exception.h>\n\n#include \"ui\/PlaceHandler.h\"\n#include \"ui\/Serializing.h\"\n\nusing namespace std;\nusing namespace Poco;\nusing namespace BeeeOn;\nusing namespace BeeeOn::UI;\n\nPlaceHandler::PlaceHandler()\n{\n\tinjector<PlaceHandler, PlaceService>(\"placeService\",\n\t\t\t&PlaceHandler::setPlaceService);\n\tinjector<PlaceHandler, IdentityService>(\"identityService\",\n\t\t\t&PlaceHandler::setIdentityService);\n\tinjector<PlaceHandler, PlaceAccessPolicy>(\"accessPolicy\",\n\t\t\t&PlaceHandler::setAccessPolicy);\n}\n\nconst string PlaceHandler::handleCreate(istream &in,\n\t\tconst VerifiedIdentityID &identityID)\n{\n\tVerifiedIdentity identity(identityID);\n\tif (!m_identityService->fetch(identity))\n\t\tthrow InvalidAccessException(\"no such identity\");\n\n\tPlace place;\n\tdeserialize(in, place);\n\n\tm_placeService->create(place, identity.identity());\n\treturn serialize(place);\n}\n\nconst string PlaceHandler::handleUpdate(istream &in,\n\t\tconst UserID &userId,\n\t\tconst string &placeId)\n{\n\tPlace place(PlaceID::parse(placeId));\n\tUser user(userId);\n\n\tm_accessPolicy->assureUpdate(user, place);\n\n\tif (!m_placeService->fetch(place))\n\t\treturn \"\";\n\n\tdeserialize(in, place);\n\n\tif (!m_placeService->update(place)) {\n\t\tthrow Exception(\"failed to update place: \"\n\t\t\t\t+ place.id().toString());\n\t}\n\n\treturn serialize(place);\n}\n\nconst string PlaceHandler::handleGet(const UserID &userId,\n\t\tconst string &placeId)\n{\n\tPlace place(PlaceID::parse(placeId));\n\tUser user(userId);\n\n\tm_accessPolicy->assureGet(user, place);\n\n\tif (!m_placeService->fetch(place)) {\n\t\treturn \"\";\n\t}\n\n\treturn serialize(place);\n}\n\nconst string PlaceHandler::handleDelete(const UserID &userId,\n\t\tconst string &placeId)\n{\n\tPlace place(PlaceID::parse(placeId));\n\tUser user(userId);\n\n\tm_accessPolicy->assureRemove(user, place);\n\n\tif (!m_placeService->remove(place, user))\n\t\treturn \"\";\n\n\treturn serialize(place);\n}\n\nconst string PlaceHandler::handleGetAll(const UserID &userId)\n{\n\tUser user(userId);\n\tstd::vector<Place> places;\n\n\tm_placeService->fetchAccessible(places, user);\n\treturn serialize(places);\n}\n\nBEEEON_OBJECT(PlaceHandler, BeeeOn::UI::PlaceHandler)\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Replace random feature id generation with deterministic<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ See docs in ..\/ops\/math_ops.cc.\n\n#define EIGEN_USE_THREADS\n\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/type_traits.h\"\n#include \"tensorflow\/core\/framework\/types.h\"\n#include \"tensorflow\/core\/kernels\/meta_support.h\"\n#include \"tensorflow\/core\/kernels\/quantization_utils.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/platform\/bfloat16.h\"\n\nnamespace {\nenum {\n QUANTIZE_MODE_MIN_COMBINED,\n QUANTIZE_MODE_MIN_FIRST,\n QUANTIZE_MODE_SCALED,\n};\n} \/\/ namespace\n\nnamespace tensorflow {\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n\ntemplate <typename T>\nT Cast(float v) {\n return v;\n}\n\ntemplate <>\nbfloat16 Cast<bfloat16>(float v) {\n return bfloat16(v);\n}\n\ntemplate <typename Device, typename T, typename S>\nclass DequantizeOp : public OpKernel {\n public:\n explicit DequantizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n string mode_string;\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"mode\", &mode_string));\n OP_REQUIRES(\n ctx,\n (ctx->output_type(0) == DT_FLOAT || ctx->output_type(0) == DT_BFLOAT16),\n errors::InvalidArgument(\"Output type must be bfloat16 or float,\"\n \" is '\" +\n DataTypeString(ctx->output_type(0)) + \"'\"));\n\n need_cast_ = true;\n if (ctx->output_type(0) == DT_FLOAT) {\n need_cast_ = false;\n OP_REQUIRES(ctx,\n (mode_string == \"MIN_COMBINED\" ||\n mode_string == \"MIN_FIRST\" || mode_string == \"SCALED\"),\n errors::InvalidArgument(\"Mode string must be 'MIN_COMBINED',\"\n \" 'MIN_FIRST', or 'SCALED', is '\" +\n mode_string + \"'\"));\n } else {\n OP_REQUIRES(\n ctx, (mode_string == \"MIN_COMBINED\"),\n errors::InvalidArgument(\"When output type is bfloat16, Mode\"\n \" string must be 'MIN_COMBINED', is '\" +\n mode_string + \"'\"));\n }\n\n if (mode_string == \"MIN_COMBINED\") {\n mode_ = QUANTIZE_MODE_MIN_COMBINED;\n } else if (mode_string == \"MIN_FIRST\") {\n mode_ = QUANTIZE_MODE_MIN_FIRST;\n } else if (mode_string == \"SCALED\") {\n mode_ = QUANTIZE_MODE_SCALED;\n }\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"narrow_range\", &narrow_range_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"axis\", &axis_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const Tensor& input_min_tensor = ctx->input(1);\n const Tensor& input_max_tensor = ctx->input(2);\n\n int num_slices = 1;\n if (axis_ > -1) {\n num_slices = input.dim_size(axis_);\n }\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n Tensor float_output =\n need_cast_ ? tensorflow::Tensor(DT_FLOAT, input.shape()) : *output;\n if (num_slices == 1) {\n const float min_range = input_min_tensor.flat<float>()(0);\n const float max_range = input_max_tensor.flat<float>()(0);\n DequantizeTensor(ctx, input, min_range, max_range, &float_output);\n } else {\n OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n \"Dequantize with axis != -1.\"));\n\n int64 pre_dim = 1, post_dim = 1;\n for (int i = 0; i < axis_; ++i) {\n pre_dim *= float_output.dim_size(i);\n }\n for (int i = axis_ + 1; i < float_output.dims(); ++i) {\n post_dim *= float_output.dim_size(i);\n }\n auto input_tensor = input.template bit_casted_shaped<T, 3>(\n {pre_dim, num_slices, post_dim});\n auto output_tensor =\n float_output.flat_inner_outer_dims<float, 3>(axis_ - 1);\n auto min_ranges = input_min_tensor.vec<float>();\n auto max_ranges = input_max_tensor.vec<float>();\n for (int i = 0; i < num_slices; ++i) {\n DequantizeSlice(ctx->eigen_device<Device>(), ctx,\n input_tensor.template chip<1>(i), min_ranges(i),\n max_ranges(i), output_tensor.template chip<1>(i));\n }\n }\n if (need_cast_) {\n S* out_ptr = output->flat<S>().data();\n float* in_ptr = float_output.flat<float>().data();\n for (int64 i = 0; i < float_output.NumElements(); ++i) {\n out_ptr[i] = static_cast<S>(in_ptr[i]);\n }\n }\n }\n\n void DequantizeTensor(OpKernelContext* ctx, const Tensor& input,\n const float min_range, const float max_range,\n Tensor* output) {\n const float half_range =\n !std::is_signed<T>::value\n ? 0.0f\n : (static_cast<float>(std::numeric_limits<T>::max()) -\n std::numeric_limits<T>::min() + 1) \/\n 2.0f;\n\n if (mode_ == QUANTIZE_MODE_MIN_COMBINED) {\n const float scale_factor =\n (max_range - min_range) \/\n (static_cast<float>(std::numeric_limits<T>::max()) -\n std::numeric_limits<T>::min());\n\n const auto& input_tensor = input.flat<T>();\n output->flat<float>() =\n ((input_tensor.template cast<float>() + half_range) * scale_factor) +\n min_range;\n\n } else if (mode_ == QUANTIZE_MODE_MIN_FIRST) {\n if (meta::IsSupportedAndEnabled() && std::is_same<T, quint8>()) {\n auto input_ui8_array = input.flat<quint8>();\n meta::Dequantize(ctx, input_ui8_array.data(), input_ui8_array.size(),\n min_range, max_range, output->flat<float>().data());\n } else {\n QuantizedTensorToFloatInPlaceUsingEigen<T>(\n ctx->template eigen_device<Device>(), input, min_range, max_range,\n output);\n }\n } else if (mode_ == QUANTIZE_MODE_SCALED) {\n const int min_output_value =\n std::numeric_limits<T>::min() + (narrow_range_ ? 1 : 0);\n const float scale_factor =\n std::numeric_limits<T>::min() == 0\n ? (max_range \/ std::numeric_limits<T>::max())\n : std::max(min_range \/ min_output_value,\n max_range \/ std::numeric_limits<T>::max());\n const auto& input_tensor = input.flat<T>();\n output->flat<float>() =\n input_tensor.template cast<int>().template cast<float>() *\n scale_factor;\n }\n }\n\n template <typename ConstVec, typename Vec>\n void DequantizeSlice(const Device& d, OpKernelContext* ctx,\n const ConstVec& input, float min_range, float max_range,\n Vec output) {\n \/\/ TODO(pauldonnelly): Factor out the similar calculations in quantize,\n \/\/ dequantize and quantize_and_dequantize ops.\n const float half_range =\n !std::is_signed<T>::value\n ? 0.0f\n : (static_cast<float>(std::numeric_limits<T>::max()) -\n std::numeric_limits<T>::min() + 1) \/\n 2.0f;\n\n if (mode_ == QUANTIZE_MODE_MIN_COMBINED) {\n const float scale_factor =\n (max_range - min_range) \/\n (static_cast<float>(std::numeric_limits<T>::max()) -\n std::numeric_limits<T>::min());\n\n output.device(d) =\n ((input.template cast<float>() + half_range) * scale_factor) +\n min_range;\n } else if (mode_ == QUANTIZE_MODE_SCALED) {\n const int min_output_value =\n std::numeric_limits<T>::min() + (narrow_range_ ? 1 : 0);\n const float scale_factor =\n std::numeric_limits<T>::min() == 0\n ? (max_range \/ std::numeric_limits<T>::max())\n : std::max(min_range \/ min_output_value,\n max_range \/ std::numeric_limits<T>::max());\n output.device(d) = input.template cast<float>() * scale_factor;\n }\n }\n\n private:\n int mode_;\n int axis_;\n bool narrow_range_;\n bool need_cast_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<quint8>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, quint8, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint8>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, qint8, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<quint16>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, quint16, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint16>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, qint16, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint32>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, qint32, float>);\n\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<quint8>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, quint8, bfloat16>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint8>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, qint8, bfloat16>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<quint16>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, quint16, bfloat16>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint16>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, qint16, bfloat16>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint32>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, qint32, bfloat16>);\n} \/\/ namespace tensorflow\n<commit_msg>Fix heap OOB read in dequantize op.<commit_after>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ See docs in ..\/ops\/math_ops.cc.\n\n#define EIGEN_USE_THREADS\n\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/type_traits.h\"\n#include \"tensorflow\/core\/framework\/types.h\"\n#include \"tensorflow\/core\/kernels\/meta_support.h\"\n#include \"tensorflow\/core\/kernels\/quantization_utils.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/platform\/bfloat16.h\"\n\nnamespace {\nenum {\n QUANTIZE_MODE_MIN_COMBINED,\n QUANTIZE_MODE_MIN_FIRST,\n QUANTIZE_MODE_SCALED,\n};\n} \/\/ namespace\n\nnamespace tensorflow {\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n\ntemplate <typename T>\nT Cast(float v) {\n return v;\n}\n\ntemplate <>\nbfloat16 Cast<bfloat16>(float v) {\n return bfloat16(v);\n}\n\ntemplate <typename Device, typename T, typename S>\nclass DequantizeOp : public OpKernel {\n public:\n explicit DequantizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n string mode_string;\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"mode\", &mode_string));\n OP_REQUIRES(\n ctx,\n (ctx->output_type(0) == DT_FLOAT || ctx->output_type(0) == DT_BFLOAT16),\n errors::InvalidArgument(\"Output type must be bfloat16 or float,\"\n \" is '\" +\n DataTypeString(ctx->output_type(0)) + \"'\"));\n\n need_cast_ = true;\n if (ctx->output_type(0) == DT_FLOAT) {\n need_cast_ = false;\n OP_REQUIRES(ctx,\n (mode_string == \"MIN_COMBINED\" ||\n mode_string == \"MIN_FIRST\" || mode_string == \"SCALED\"),\n errors::InvalidArgument(\"Mode string must be 'MIN_COMBINED',\"\n \" 'MIN_FIRST', or 'SCALED', is '\" +\n mode_string + \"'\"));\n } else {\n OP_REQUIRES(\n ctx, (mode_string == \"MIN_COMBINED\"),\n errors::InvalidArgument(\"When output type is bfloat16, Mode\"\n \" string must be 'MIN_COMBINED', is '\" +\n mode_string + \"'\"));\n }\n\n if (mode_string == \"MIN_COMBINED\") {\n mode_ = QUANTIZE_MODE_MIN_COMBINED;\n } else if (mode_string == \"MIN_FIRST\") {\n mode_ = QUANTIZE_MODE_MIN_FIRST;\n } else if (mode_string == \"SCALED\") {\n mode_ = QUANTIZE_MODE_SCALED;\n }\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"narrow_range\", &narrow_range_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"axis\", &axis_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const Tensor& input_min_tensor = ctx->input(1);\n const Tensor& input_max_tensor = ctx->input(2);\n\n int num_slices = 1;\n if (axis_ > -1) {\n num_slices = input.dim_size(axis_);\n }\n OP_REQUIRES(ctx, input_min_tensor.NumElements() == num_slices,\n errors::InvalidArgument(\n \"input_min_tensor must have as many elements as input on \"\n \"the dequantization axis (\",\n axis_, \"), got \", input_min_tensor.NumElements(),\n \", expected \", num_slices));\n OP_REQUIRES(ctx, input_max_tensor.NumElements() == num_slices,\n errors::InvalidArgument(\n \"input_max_tensor must have as many elements as input on \"\n \"the dequantization axis (\",\n axis_, \"), got \", input_max_tensor.NumElements(),\n \", expected \", num_slices));\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n Tensor float_output =\n need_cast_ ? tensorflow::Tensor(DT_FLOAT, input.shape()) : *output;\n if (num_slices == 1) {\n const float min_range = input_min_tensor.flat<float>()(0);\n const float max_range = input_max_tensor.flat<float>()(0);\n DequantizeTensor(ctx, input, min_range, max_range, &float_output);\n } else {\n OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n \"Dequantize with axis != -1.\"));\n\n int64 pre_dim = 1, post_dim = 1;\n for (int i = 0; i < axis_; ++i) {\n pre_dim *= float_output.dim_size(i);\n }\n for (int i = axis_ + 1; i < float_output.dims(); ++i) {\n post_dim *= float_output.dim_size(i);\n }\n auto input_tensor = input.template bit_casted_shaped<T, 3>(\n {pre_dim, num_slices, post_dim});\n auto output_tensor =\n float_output.flat_inner_outer_dims<float, 3>(axis_ - 1);\n auto min_ranges = input_min_tensor.vec<float>();\n auto max_ranges = input_max_tensor.vec<float>();\n for (int i = 0; i < num_slices; ++i) {\n DequantizeSlice(ctx->eigen_device<Device>(), ctx,\n input_tensor.template chip<1>(i), min_ranges(i),\n max_ranges(i), output_tensor.template chip<1>(i));\n }\n }\n if (need_cast_) {\n S* out_ptr = output->flat<S>().data();\n float* in_ptr = float_output.flat<float>().data();\n for (int64 i = 0; i < float_output.NumElements(); ++i) {\n out_ptr[i] = static_cast<S>(in_ptr[i]);\n }\n }\n }\n\n void DequantizeTensor(OpKernelContext* ctx, const Tensor& input,\n const float min_range, const float max_range,\n Tensor* output) {\n const float half_range =\n !std::is_signed<T>::value\n ? 0.0f\n : (static_cast<float>(std::numeric_limits<T>::max()) -\n std::numeric_limits<T>::min() + 1) \/\n 2.0f;\n\n if (mode_ == QUANTIZE_MODE_MIN_COMBINED) {\n const float scale_factor =\n (max_range - min_range) \/\n (static_cast<float>(std::numeric_limits<T>::max()) -\n std::numeric_limits<T>::min());\n\n const auto& input_tensor = input.flat<T>();\n output->flat<float>() =\n ((input_tensor.template cast<float>() + half_range) * scale_factor) +\n min_range;\n\n } else if (mode_ == QUANTIZE_MODE_MIN_FIRST) {\n if (meta::IsSupportedAndEnabled() && std::is_same<T, quint8>()) {\n auto input_ui8_array = input.flat<quint8>();\n meta::Dequantize(ctx, input_ui8_array.data(), input_ui8_array.size(),\n min_range, max_range, output->flat<float>().data());\n } else {\n QuantizedTensorToFloatInPlaceUsingEigen<T>(\n ctx->template eigen_device<Device>(), input, min_range, max_range,\n output);\n }\n } else if (mode_ == QUANTIZE_MODE_SCALED) {\n const int min_output_value =\n std::numeric_limits<T>::min() + (narrow_range_ ? 1 : 0);\n const float scale_factor =\n std::numeric_limits<T>::min() == 0\n ? (max_range \/ std::numeric_limits<T>::max())\n : std::max(min_range \/ min_output_value,\n max_range \/ std::numeric_limits<T>::max());\n const auto& input_tensor = input.flat<T>();\n output->flat<float>() =\n input_tensor.template cast<int>().template cast<float>() *\n scale_factor;\n }\n }\n\n template <typename ConstVec, typename Vec>\n void DequantizeSlice(const Device& d, OpKernelContext* ctx,\n const ConstVec& input, float min_range, float max_range,\n Vec output) {\n \/\/ TODO(pauldonnelly): Factor out the similar calculations in quantize,\n \/\/ dequantize and quantize_and_dequantize ops.\n const float half_range =\n !std::is_signed<T>::value\n ? 0.0f\n : (static_cast<float>(std::numeric_limits<T>::max()) -\n std::numeric_limits<T>::min() + 1) \/\n 2.0f;\n\n if (mode_ == QUANTIZE_MODE_MIN_COMBINED) {\n const float scale_factor =\n (max_range - min_range) \/\n (static_cast<float>(std::numeric_limits<T>::max()) -\n std::numeric_limits<T>::min());\n\n output.device(d) =\n ((input.template cast<float>() + half_range) * scale_factor) +\n min_range;\n } else if (mode_ == QUANTIZE_MODE_SCALED) {\n const int min_output_value =\n std::numeric_limits<T>::min() + (narrow_range_ ? 1 : 0);\n const float scale_factor =\n std::numeric_limits<T>::min() == 0\n ? (max_range \/ std::numeric_limits<T>::max())\n : std::max(min_range \/ min_output_value,\n max_range \/ std::numeric_limits<T>::max());\n output.device(d) = input.template cast<float>() * scale_factor;\n }\n }\n\n private:\n int mode_;\n int axis_;\n bool narrow_range_;\n bool need_cast_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<quint8>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, quint8, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint8>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, qint8, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<quint16>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, quint16, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint16>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, qint16, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint32>(\"T\")\n .TypeConstraint<float>(\"dtype\"),\n DequantizeOp<CPUDevice, qint32, float>);\n\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<quint8>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, quint8, bfloat16>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint8>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, qint8, bfloat16>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<quint16>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, quint16, bfloat16>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint16>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, qint16, bfloat16>);\nREGISTER_KERNEL_BUILDER(Name(\"Dequantize\")\n .Device(DEVICE_CPU)\n .TypeConstraint<qint32>(\"T\")\n .TypeConstraint<bfloat16>(\"dtype\"),\n DequantizeOp<CPUDevice, qint32, bfloat16>);\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/framework\/op_registry.h\"\n#include \"paddle\/platform\/place.h\"\n#ifdef PADDLE_WITH_CUDA\n#include \"paddle\/platform\/gpu_info.h\"\n#endif\n\nnamespace paddle {\nnamespace operators {\n\nclass GetPlacesOp : public framework::OperatorBase {\n public:\n GetPlacesOp(const std::string &type, const framework::VariableNameMap &inputs,\n const framework::VariableNameMap &outputs,\n const framework::AttributeMap &attrs)\n : OperatorBase(type, inputs, outputs, attrs) {}\n void Run(const framework::Scope &scope,\n const platform::DeviceContext &dev_ctx) const override {\n std::string device_type = Attr<std::string>(\"device_type\");\n auto trainer_count = Attr<int>(\"trainer_count\");\n\n auto out_var_name = Output(\"Out\");\n auto *out_var = scope.FindVar(out_var_name);\n PADDLE_ENFORCE(out_var != nullptr, \"Output variable %s cannot be found\",\n out_var_name);\n\n auto &places = *(out_var->GetMutable<std::vector<platform::Place>>());\n places.resize(trainer_count);\n if (device_type == \"CUDA\") {\n#ifdef PADDLE_WITH_CUDA\n PADDLE_ENFORCE_LT(trainer_count, GetCUDADeviceCount());\n for (int i = 0; i < trainer_count; i++) {\n places.emplace_back(platform::GPUPlace(i));\n }\n#else\n PADDLE_THROW(\"'GPUPlace' is not supported in CPU only device.\");\n#endif\n } else if (device_type == \"CPU\") {\n for (int i = 0; i < trainer_count; i++) {\n places.emplace_back(platform::CPUPlace());\n }\n }\n }\n};\n\nclass GetPlacesOpProtoMaker : public framework::OpProtoAndCheckerMaker {\n public:\n GetPlacesOpProtoMaker(framework::OpProto *proto,\n framework::OpAttrChecker *op_checker)\n : OpProtoAndCheckerMaker(proto, op_checker) {\n AddOutput(\"Out\", \"vector of Place\");\n AddAttr<int>(\"trainer_count\", \"(int)trainer count\").SetDefault(1);\n AddAttr<std::string>(\"device_type\",\n \"(string), deivce type can be \\\"CPU\\\" and \\\"CUDA\\\"\")\n .InEnum({\"CPU\", \"CUDA\"});\n AddComment(R\"DOC(\nReturns a list of places based on flags. The list will be used for parallel execution.\n\n)DOC\");\n }\n};\n} \/\/ namespace operators\n} \/\/ namespace paddle\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(get_places, ops::GetPlacesOp, ops::GetPlacesOpProtoMaker);\n<commit_msg>fix ci<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/framework\/op_registry.h\"\n#include \"paddle\/platform\/place.h\"\n#ifdef PADDLE_WITH_CUDA\n#include \"paddle\/platform\/gpu_info.h\"\n#endif\n\nnamespace paddle {\nnamespace operators {\n\nclass GetPlacesOp : public framework::OperatorBase {\n public:\n GetPlacesOp(const std::string &type, const framework::VariableNameMap &inputs,\n const framework::VariableNameMap &outputs,\n const framework::AttributeMap &attrs)\n : OperatorBase(type, inputs, outputs, attrs) {}\n void Run(const framework::Scope &scope,\n const platform::DeviceContext &dev_ctx) const override {\n std::string device_type = Attr<std::string>(\"device_type\");\n auto trainer_count = Attr<int>(\"trainer_count\");\n\n auto out_var_name = Output(\"Out\");\n auto *out_var = scope.FindVar(out_var_name);\n PADDLE_ENFORCE(out_var != nullptr, \"Output variable %s cannot be found\",\n out_var_name);\n\n auto &places = *(out_var->GetMutable<std::vector<platform::Place>>());\n places.resize(trainer_count);\n if (device_type == \"CUDA\") {\n#ifdef PADDLE_WITH_CUDA\n PADDLE_ENFORCE_LT(trainer_count, platform::GetCUDADeviceCount());\n for (int i = 0; i < trainer_count; i++) {\n places.emplace_back(platform::GPUPlace(i));\n }\n#else\n PADDLE_THROW(\"'GPUPlace' is not supported in CPU only device.\");\n#endif\n } else if (device_type == \"CPU\") {\n for (int i = 0; i < trainer_count; i++) {\n places.emplace_back(platform::CPUPlace());\n }\n }\n }\n};\n\nclass GetPlacesOpProtoMaker : public framework::OpProtoAndCheckerMaker {\n public:\n GetPlacesOpProtoMaker(framework::OpProto *proto,\n framework::OpAttrChecker *op_checker)\n : OpProtoAndCheckerMaker(proto, op_checker) {\n AddOutput(\"Out\", \"vector of Place\");\n AddAttr<int>(\"trainer_count\", \"(int)trainer count\").SetDefault(1);\n AddAttr<std::string>(\"device_type\",\n \"(string), deivce type can be \\\"CPU\\\" and \\\"CUDA\\\"\")\n .InEnum({\"CPU\", \"CUDA\"});\n AddComment(R\"DOC(\nReturns a list of places based on flags. The list will be used for parallel execution.\n\n)DOC\");\n }\n};\n} \/\/ namespace operators\n} \/\/ namespace paddle\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(get_places, ops::GetPlacesOp, ops::GetPlacesOpProtoMaker);\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n\n#include <QX11Info>\n#include <stdlib.h>\n#include <QtCore>\n#include <QtGui>\n\nnamespace {\n const char * const TextPrompt = \"Double-click this text area to invoke virtual keyboard ...\";\n const char * const ImModuleEnv = \"QT_IM_MODULE\";\n const char * const ExpectedImModule = \"MInputContext\";\n\n\n QString checkForErrors()\n {\n const char * const imModule = getenv(ImModuleEnv);\n QString errorMsg;\n\n if (not imModule\n || (0 != strcmp(getenv(ImModuleEnv), ExpectedImModule))) {\n errorMsg.append(QString(\"You will not be able to use the virtual keyboard. The \" \\\n \"environment variable %1 must be set to %2.\")\n .arg(ImModuleEnv)\n .arg(ExpectedImModule));\n }\n\n if (not QX11Info::isCompositingManagerRunning()) {\n if (not errorMsg.isEmpty()) {\n errorMsg.append(\"\\n\");\n }\n\n errorMsg.append(\"No compositing window manager found. You might be able to run the \" \\\n \"MeeGo Input Method server in self-compositing mode:\\n\" \\\n \"$ meego-im-uiserver -use-self-composition -manual-redirection\");\n }\n\n return errorMsg;\n }\n}\n\nclass MyTextEdit\n : public QTextEdit\n{\nprivate:\n bool wasFocused;\n\npublic:\n MyTextEdit()\n : QTextEdit(TextPrompt)\n , wasFocused(false)\n {}\n\nprotected:\n void focusInEvent(QFocusEvent *e)\n {\n toPlainText();\n \/\/ On first text edit, clear pre-set TextPrompt:\n if (not wasFocused && toPlainText() == QString(TextPrompt)) {\n wasFocused = true;\n setText(\"\");\n }\n\n QTextEdit::focusInEvent(e);\n }\n};\n\nMainWindow::MainWindow()\n : QMainWindow()\n , serverProcess(new QProcess(this))\n , orientationIndex(0)\n , startServerButton(new QPushButton)\n , rotateKeyboardButton(new QPushButton)\n , textEdit(new QTextEdit)\n{\n serverProcess->setProcessChannelMode(QProcess::ForwardedChannels);\n connect(serverProcess, SIGNAL(error(QProcess::ProcessError)),\n this, SLOT(onServerError()));\n connect(serverProcess, SIGNAL(stateChanged(QProcess::ProcessState)),\n this, SLOT(onServerStateChanged()));\n\n connect(startServerButton, SIGNAL(clicked()),\n this, SLOT(onStartServerClicked()));\n connect(rotateKeyboardButton, SIGNAL(clicked()),\n this, SLOT(onRotateKeyboardClicked()));\n\n initUI();\n onServerStateChanged();\n\n const QString &errorMsg(checkForErrors());\n if (not errorMsg.isEmpty()) {\n textEdit->setText(errorMsg);\n qCritical() << \"CRITICAL:\" << errorMsg;\n }\n}\n\nvoid MainWindow::initUI()\n{\n setWindowTitle(\"Maliit test application\");\n\n QVBoxLayout *vbox = new QVBoxLayout();\n\n rotateKeyboardButton->setText(\"Rotate keyboard\");\n vbox->addWidget(startServerButton);\n vbox->addWidget(rotateKeyboardButton);\n\n \/\/ Clicking the button will steal focus from the text edit, thus hiding\n \/\/ the virtual keyboard:\n QPushButton *hideVkb = new QPushButton(\"Hide virtual keyboard\");\n vbox->addWidget(hideVkb);\n\n vbox->addWidget(textEdit);\n\n QPushButton *closeApp = new QPushButton(\"Close application\");\n vbox->addWidget(closeApp);\n connect(closeApp, SIGNAL(clicked()),\n this, SLOT(close()));\n\n setCentralWidget(new QWidget);\n centralWidget()->setLayout(vbox);\n show();\n}\n\nMainWindow::~MainWindow()\n{\n serverProcess->terminate();\n}\n\nvoid MainWindow::onStartServerClicked()\n{\n const QString programName(\"meego-im-uiserver\");\n QStringList arguments;\n arguments << \"-use-self-composition\" << \"-bypass-wm-hint\";\n\n if (serverProcess->state() != QProcess::NotRunning) {\n serverProcess->terminate();\n } else {\n serverProcess->start(programName, arguments);\n }\n}\n\nvoid MainWindow::onServerError()\n{\n textEdit->setText(serverProcess->errorString());\n}\n\nvoid MainWindow::onServerStateChanged()\n{\n switch (serverProcess->state()) {\n case QProcess::Running:\n startServerButton->setText(\"(running) Stop input method server\");\n break;\n case QProcess::Starting:\n startServerButton->setText(\"(starting) Stop input method server\");\n break;\n case QProcess::NotRunning:\n startServerButton->setText(\"(stopped) Start input method server\");\n default:\n break;\n }\n}\n\n\/\/ Copied from minputmethodnamespace.h\nnamespace MInputMethod {\n enum OrientationAngle { Angle0=0, Angle90=90, Angle180=180, Angle270=270 };\n}\n\nvoid MainWindow::onRotateKeyboardClicked()\n{\n const MInputMethod::OrientationAngle orientations[] = {MInputMethod::Angle0,\n MInputMethod::Angle90,\n MInputMethod::Angle180,\n MInputMethod::Angle270};\n orientationIndex++;\n if (orientationIndex >= 4) {\n orientationIndex = 0;\n }\n const MInputMethod::OrientationAngle angle = orientations[orientationIndex];\n\n QMetaObject::invokeMethod(qApp->inputContext(), \"notifyOrientationChanged\",\n Q_ARG(MInputMethod::OrientationAngle, angle));\n}\n<commit_msg>Changes: Let extra buttons in example app be focus proxies for text area<commit_after>#include \"mainwindow.h\"\n\n#include <QX11Info>\n#include <stdlib.h>\n#include <QtCore>\n#include <QtGui>\n\nnamespace {\n const char * const TextPrompt = \"Double-click this text area to invoke virtual keyboard ...\";\n const char * const ImModuleEnv = \"QT_IM_MODULE\";\n const char * const ExpectedImModule = \"MInputContext\";\n\n\n QString checkForErrors()\n {\n const char * const imModule = getenv(ImModuleEnv);\n QString errorMsg;\n\n if (not imModule\n || (0 != strcmp(getenv(ImModuleEnv), ExpectedImModule))) {\n errorMsg.append(QString(\"You will not be able to use the virtual keyboard. The \" \\\n \"environment variable %1 must be set to %2.\")\n .arg(ImModuleEnv)\n .arg(ExpectedImModule));\n }\n\n if (not QX11Info::isCompositingManagerRunning()) {\n if (not errorMsg.isEmpty()) {\n errorMsg.append(\"\\n\");\n }\n\n errorMsg.append(\"No compositing window manager found. You might be able to run the \" \\\n \"MeeGo Input Method server in self-compositing mode:\\n\" \\\n \"$ meego-im-uiserver -use-self-composition -manual-redirection\");\n }\n\n return errorMsg;\n }\n}\n\nclass MyTextEdit\n : public QTextEdit\n{\nprivate:\n bool wasFocused;\n\npublic:\n MyTextEdit()\n : QTextEdit(TextPrompt)\n , wasFocused(false)\n {}\n\nprotected:\n void focusInEvent(QFocusEvent *e)\n {\n toPlainText();\n \/\/ On first text edit, clear pre-set TextPrompt:\n if (not wasFocused && toPlainText() == QString(TextPrompt)) {\n wasFocused = true;\n setText(\"\");\n }\n\n QTextEdit::focusInEvent(e);\n }\n};\n\nMainWindow::MainWindow()\n : QMainWindow()\n , serverProcess(new QProcess(this))\n , orientationIndex(0)\n , startServerButton(new QPushButton)\n , rotateKeyboardButton(new QPushButton)\n , textEdit(new QTextEdit)\n{\n serverProcess->setProcessChannelMode(QProcess::ForwardedChannels);\n connect(serverProcess, SIGNAL(error(QProcess::ProcessError)),\n this, SLOT(onServerError()));\n connect(serverProcess, SIGNAL(stateChanged(QProcess::ProcessState)),\n this, SLOT(onServerStateChanged()));\n\n connect(startServerButton, SIGNAL(clicked()),\n this, SLOT(onStartServerClicked()));\n connect(rotateKeyboardButton, SIGNAL(clicked()),\n this, SLOT(onRotateKeyboardClicked()));\n\n initUI();\n onServerStateChanged();\n\n const QString &errorMsg(checkForErrors());\n if (not errorMsg.isEmpty()) {\n textEdit->setText(errorMsg);\n qCritical() << \"CRITICAL:\" << errorMsg;\n }\n}\n\nvoid MainWindow::initUI()\n{\n setWindowTitle(\"Maliit test application\");\n\n QVBoxLayout *vbox = new QVBoxLayout();\n\n rotateKeyboardButton->setText(\"Rotate keyboard\");\n vbox->addWidget(startServerButton);\n vbox->addWidget(rotateKeyboardButton);\n\n \/\/ Clicking the button will steal focus from the text edit, thus hiding\n \/\/ the virtual keyboard:\n QPushButton *hideVkb = new QPushButton(\"Hide virtual keyboard\");\n vbox->addWidget(hideVkb);\n vbox->addWidget(textEdit);\n\n \/\/ But don't want other buttons to steal focus:\n startServerButton->setFocusProxy(textEdit);\n rotateKeyboardButton->setFocusProxy(textEdit);\n\n QPushButton *closeApp = new QPushButton(\"Close application\");\n vbox->addWidget(closeApp);\n connect(closeApp, SIGNAL(clicked()),\n this, SLOT(close()));\n\n setCentralWidget(new QWidget);\n centralWidget()->setLayout(vbox);\n show();\n}\n\nMainWindow::~MainWindow()\n{\n serverProcess->terminate();\n}\n\nvoid MainWindow::onStartServerClicked()\n{\n const QString programName(\"meego-im-uiserver\");\n QStringList arguments;\n arguments << \"-use-self-composition\" << \"-bypass-wm-hint\";\n\n if (serverProcess->state() != QProcess::NotRunning) {\n serverProcess->terminate();\n } else {\n serverProcess->start(programName, arguments);\n }\n}\n\nvoid MainWindow::onServerError()\n{\n textEdit->setText(serverProcess->errorString());\n}\n\nvoid MainWindow::onServerStateChanged()\n{\n switch (serverProcess->state()) {\n case QProcess::Running:\n startServerButton->setText(\"(running) Stop input method server\");\n break;\n case QProcess::Starting:\n startServerButton->setText(\"(starting) Stop input method server\");\n break;\n case QProcess::NotRunning:\n startServerButton->setText(\"(stopped) Start input method server\");\n default:\n break;\n }\n}\n\n\/\/ Copied from minputmethodnamespace.h\nnamespace MInputMethod {\n enum OrientationAngle { Angle0=0, Angle90=90, Angle180=180, Angle270=270 };\n}\n\nvoid MainWindow::onRotateKeyboardClicked()\n{\n const MInputMethod::OrientationAngle orientations[] = {MInputMethod::Angle0,\n MInputMethod::Angle90,\n MInputMethod::Angle180,\n MInputMethod::Angle270};\n orientationIndex++;\n if (orientationIndex >= 4) {\n orientationIndex = 0;\n }\n const MInputMethod::OrientationAngle angle = orientations[orientationIndex];\n\n QMetaObject::invokeMethod(qApp->inputContext(), \"notifyOrientationChanged\",\n Q_ARG(MInputMethod::OrientationAngle, angle));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Google Inc.\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\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. 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\/\/ 3. The name of the author may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\/\/ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\/\/ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\/\/ NOT 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 OF\n\/\/ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"third_party\/pcsc-lite\/naclport\/server\/src\/public\/pcsc_lite_server_web_port_service.h\"\n\n#include <stdint.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <string>\n#include <thread>\n#include <utility>\n\n#include <google_smart_card_common\/ipc_emulation.h>\n#include <google_smart_card_common\/logging\/logging.h>\n#include <google_smart_card_common\/messaging\/typed_message.h>\n#include <google_smart_card_common\/optional.h>\n#include <google_smart_card_common\/value.h>\n#include <google_smart_card_common\/value_conversion.h>\n\n#include \"server_sockets_manager.h\"\n\n\/\/ Include the C headers after all other includes, because the preprocessor\n\/\/ definitions from them interfere with the symbols from the standard C++\n\/\/ library.\nextern \"C\" {\n#include \"winscard.h\"\n#include \"debuglog.h\"\n#include \"eventhandler.h\"\n#include \"hotplug.h\"\n#include \"readerfactory.h\"\n#include \"sys_generic.h\"\n#include \"winscard_svc.h\"\n}\n\n\/\/ Old versions of Emscripten have buggy multi-threading - so bail out if the\n\/\/ developer still hasn't updated their local Emscripten version.\n#ifdef __EMSCRIPTEN__\n#if __EMSCRIPTEN_major__ < 2 || \\\n (__EMSCRIPTEN_major__ == 2 && __EMSCRIPTEN_minor__ == 0 && \\\n __EMSCRIPTEN_tiny__ < 31)\n#error \"Emscripten >=2.0.31 must be used\"\n#endif\n#endif \/\/ __EMSCRIPTEN__\n\nnamespace google_smart_card {\n\nnamespace {\n\nPcscLiteServerWebPortService* g_pcsc_lite_server = nullptr;\n\nconstexpr char kLoggingPrefix[] = \"[PC\/SC-Lite NaCl port] \";\n\n\/\/ Constants for message types that are sent to the JavaScript side. These\n\/\/ strings must match the ones in reader-tracker.js.\nconstexpr char kReaderInitAddMessageType[] = \"reader_init_add\";\nconstexpr char kReaderFinishAddMessageType[] = \"reader_finish_add\";\nconstexpr char kReaderRemoveMessageType[] = \"reader_remove\";\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is being added by the PC\/SC-Lite daemon.\nstruct ReaderInitAddMessageData {\n std::string reader_name;\n int port;\n std::string device;\n};\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is completely added by the PC\/SC-Lite daemon.\nstruct ReaderFinishAddMessageData {\n std::string reader_name;\n int port;\n std::string device;\n long return_code;\n};\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is removed by the PC\/SC-Lite daemon.\nstruct ReaderRemoveMessageData {\n std::string reader_name;\n int port;\n};\n\nvoid PcscLiteServerDaemonThreadMain() {\n while (true) {\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"[daemon thread] \"\n << \"Waiting for the new connected clients...\";\n optional<int> server_socket_file_descriptor =\n PcscLiteServerSocketsManager::GetInstance()->WaitAndPop();\n if (!server_socket_file_descriptor) {\n \/\/ A shutdown signal received.\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix\n << \"[daemon thread] Shutting down...\";\n break;\n }\n\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"[daemon thread] A new \"\n << \"client was connected, starting a handler thread...\";\n \/\/ Note: even though the CreateContextThread function accepts its\n \/\/ server_socket_file_descriptor argument by pointer, it doesn't store the\n \/\/ pointer itself anywhere - so it's safe to use a local variable here.\n uint32_t server_socket_file_descriptor_unsigned =\n static_cast<uint32_t>(server_socket_file_descriptor.value());\n \/\/ FIXME(emaxx): Deal with cases when CreateContextThread returns errors.\n \/\/ Looks like it may happen legitimately when the abusive client(s) request\n \/\/ to establish too many requests. Probably, some limitation should be\n \/\/ applied to all clients.\n GOOGLE_SMART_CARD_CHECK(\n ::CreateContextThread(&server_socket_file_descriptor_unsigned) ==\n SCARD_S_SUCCESS);\n }\n\n \/\/ Clean up the structures and threads owned by the third-party PC\/SC-Lite\n \/\/ code. This follows the code in the \"if (AraKiri)\" block in the\n \/\/ `SVCServiceRunLoop()` function in pcsc-lite\/src\/src\/pcscdaemon.c.\n HPStopHotPluggables();\n \/\/ TODO: Upstream's approach with a magic sleep is flaky: the background\n \/\/ thread might be still running after this point, causing crashes. Replace\n \/\/ this with a proper waiting mechanism.\n SYS_Sleep(5);\n RFCleanupReaders();\n EHDeinitializeEventStructures();\n ContextsDeinitialize();\n}\n\n} \/\/ namespace\n\ntemplate <>\nStructValueDescriptor<ReaderInitAddMessageData>::Description\nStructValueDescriptor<ReaderInitAddMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderInitAddMessageData\")\n .WithField(&ReaderInitAddMessageData::reader_name, \"readerName\")\n .WithField(&ReaderInitAddMessageData::port, \"port\")\n .WithField(&ReaderInitAddMessageData::device, \"device\");\n}\n\ntemplate <>\nStructValueDescriptor<ReaderFinishAddMessageData>::Description\nStructValueDescriptor<ReaderFinishAddMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderFinishAddMessageData\")\n .WithField(&ReaderFinishAddMessageData::reader_name, \"readerName\")\n .WithField(&ReaderFinishAddMessageData::port, \"port\")\n .WithField(&ReaderFinishAddMessageData::device, \"device\")\n .WithField(&ReaderFinishAddMessageData::return_code, \"returnCode\");\n}\n\ntemplate <>\nStructValueDescriptor<ReaderRemoveMessageData>::Description\nStructValueDescriptor<ReaderRemoveMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderRemoveMessageData\")\n .WithField(&ReaderRemoveMessageData::reader_name, \"readerName\")\n .WithField(&ReaderRemoveMessageData::port, \"port\");\n}\n\nPcscLiteServerWebPortService::PcscLiteServerWebPortService(\n GlobalContext* global_context)\n : global_context_(global_context) {\n GOOGLE_SMART_CARD_CHECK(!g_pcsc_lite_server);\n g_pcsc_lite_server = this;\n}\n\nPcscLiteServerWebPortService::~PcscLiteServerWebPortService() {\n \/\/ If the daemon thread is joinable, it means `ShutDownAndWait()` wasn't\n \/\/ called, which is a violation of the contract.\n GOOGLE_SMART_CARD_CHECK(!daemon_thread_.joinable());\n\n GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server == this);\n g_pcsc_lite_server = nullptr;\n}\n\n\/\/ static\nconst PcscLiteServerWebPortService*\nPcscLiteServerWebPortService::GetInstance() {\n GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server);\n return g_pcsc_lite_server;\n}\n\nvoid PcscLiteServerWebPortService::InitializeAndRunDaemonThread() {\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Initialization...\";\n\n IpcEmulation::CreateGlobalInstance();\n PcscLiteServerSocketsManager::CreateGlobalInstance();\n\n ::SYS_InitRandom();\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Setting up PC\/SC-Lite \"\n << \"logging...\";\n ::DebugLogSetLogType(DEBUGLOG_SYSLOG_DEBUG);\n#ifdef NDEBUG\n ::DebugLogSetLevel(PCSC_LOG_ERROR);\n#else\n ::DebugLogSetLevel(PCSC_LOG_DEBUG);\n ::DebugLogSetCategory(DEBUG_CATEGORY_APDU | DEBUG_CATEGORY_SW);\n#endif\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"PC\/SC-Lite logging was \"\n << \"set up.\";\n\n LONG return_code;\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Allocating reader \"\n << \"structures...\";\n return_code = ::RFAllocateReaderSpace(0);\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Reader structures \"\n << \"allocation finished with the following result: \\\"\"\n << ::pcsc_stringify_error(return_code) << \"\\\".\";\n GOOGLE_SMART_CARD_CHECK(return_code == SCARD_S_SUCCESS);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Performing initial hot \"\n << \"plug drivers search...\";\n return_code = ::HPSearchHotPluggables();\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Initial hot plug \"\n << \"drivers search finished with the following result code: \"\n << return_code << \".\";\n GOOGLE_SMART_CARD_CHECK(return_code == 0);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Registering for hot \"\n << \"plug events...\";\n \/\/ FIXME(emaxx): Currently this ends up on polling the libusb each second, as\n \/\/ it doesn't provide any way to subscribe for the device list change. But\n \/\/ it's possible to optimize this onto publisher-pattern-style implementation,\n \/\/ by handling the chrome.usb API events (see\n \/\/ <https:\/\/developer.chrome.com\/apps\/usb#Events>) and using them in a\n \/\/ replacement implementation of the currently used original hotplug_libusb.c\n \/\/ source file.\n return_code = ::HPRegisterForHotplugEvents();\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Registering for hot \"\n << \"plug events finished with the following result code: \" << return_code\n << \".\";\n GOOGLE_SMART_CARD_CHECK(return_code == 0);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Allocating client \"\n << \"structures...\";\n return_code = ::ContextsInitialize(0, 0);\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Client structures \"\n << \"allocation finished with the following result code: \" << return_code\n << \"...\";\n GOOGLE_SMART_CARD_CHECK(return_code == 1);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Waiting for the readers \"\n << \"initialization...\";\n ::RFWaitForReaderInit();\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Waiting for the readers \"\n << \"initialization finished.\";\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Starting PC\/SC-Lite \"\n << \"daemon thread...\";\n daemon_thread_ = std::thread(PcscLiteServerDaemonThreadMain);\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"PC\/SC-Lite daemon \"\n << \"thread has started.\";\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Initialization \"\n << \"successfully finished.\";\n}\n\nvoid PcscLiteServerWebPortService::ShutDownAndWait() {\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Shutting down the PC\/SC-Lite daemon thread...\";\n \/\/ This notifies the daemon thread to shut down.\n PcscLiteServerSocketsManager::GetInstance()->ShutDown();\n daemon_thread_.join();\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix\n << \"The PC\/SC-Lite daemon thread shut down.\";\n\n \/\/ Shut down the global state created in `InitializeAndRunDaemonThread()`.\n PcscLiteServerSocketsManager::DestroyGlobalInstance();\n IpcEmulation::DestroyGlobalInstance();\n}\n\nvoid PcscLiteServerWebPortService::PostReaderInitAddMessage(\n const char* reader_name,\n int port,\n const char* device) const {\n ReaderInitAddMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n message_data.device = device;\n PostMessage(kReaderInitAddMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostReaderFinishAddMessage(\n const char* reader_name,\n int port,\n const char* device,\n long return_code) const {\n ReaderFinishAddMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n message_data.device = device;\n message_data.return_code = return_code;\n PostMessage(kReaderFinishAddMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostReaderRemoveMessage(\n const char* reader_name,\n int port) const {\n ReaderRemoveMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n PostMessage(kReaderRemoveMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostMessage(const char* type,\n Value message_data) const {\n TypedMessage typed_message;\n typed_message.type = type;\n typed_message.data = std::move(message_data);\n global_context_->PostMessageToJs(\n ConvertToValueOrDie(std::move(typed_message)));\n}\n\n} \/\/ namespace google_smart_card\n<commit_msg>Add missing emscripten\/version.h include (#740)<commit_after>\/\/ Copyright 2016 Google Inc.\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\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. 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\/\/ 3. The name of the author may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\/\/ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\/\/ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\/\/ NOT 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 OF\n\/\/ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"third_party\/pcsc-lite\/naclport\/server\/src\/public\/pcsc_lite_server_web_port_service.h\"\n\n#include <stdint.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <string>\n#include <thread>\n#include <utility>\n\n#include <google_smart_card_common\/ipc_emulation.h>\n#include <google_smart_card_common\/logging\/logging.h>\n#include <google_smart_card_common\/messaging\/typed_message.h>\n#include <google_smart_card_common\/optional.h>\n#include <google_smart_card_common\/value.h>\n#include <google_smart_card_common\/value_conversion.h>\n\n#include \"server_sockets_manager.h\"\n\n#ifdef __EMSCRIPTEN__\n#include <emscripten\/version.h>\n#endif\n\n\/\/ Include the C headers after all other includes, because the preprocessor\n\/\/ definitions from them interfere with the symbols from the standard C++\n\/\/ library.\nextern \"C\" {\n#include \"winscard.h\"\n#include \"debuglog.h\"\n#include \"eventhandler.h\"\n#include \"hotplug.h\"\n#include \"readerfactory.h\"\n#include \"sys_generic.h\"\n#include \"winscard_svc.h\"\n}\n\n\/\/ Old versions of Emscripten have buggy multi-threading - so bail out if the\n\/\/ developer still hasn't updated their local Emscripten version.\n#ifdef __EMSCRIPTEN__\n#if __EMSCRIPTEN_major__ < 2 || \\\n (__EMSCRIPTEN_major__ == 2 && __EMSCRIPTEN_minor__ == 0 && \\\n __EMSCRIPTEN_tiny__ < 31)\n#error \"Emscripten >=2.0.31 must be used\"\n#endif\n#endif \/\/ __EMSCRIPTEN__\n\nnamespace google_smart_card {\n\nnamespace {\n\nPcscLiteServerWebPortService* g_pcsc_lite_server = nullptr;\n\nconstexpr char kLoggingPrefix[] = \"[PC\/SC-Lite NaCl port] \";\n\n\/\/ Constants for message types that are sent to the JavaScript side. These\n\/\/ strings must match the ones in reader-tracker.js.\nconstexpr char kReaderInitAddMessageType[] = \"reader_init_add\";\nconstexpr char kReaderFinishAddMessageType[] = \"reader_finish_add\";\nconstexpr char kReaderRemoveMessageType[] = \"reader_remove\";\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is being added by the PC\/SC-Lite daemon.\nstruct ReaderInitAddMessageData {\n std::string reader_name;\n int port;\n std::string device;\n};\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is completely added by the PC\/SC-Lite daemon.\nstruct ReaderFinishAddMessageData {\n std::string reader_name;\n int port;\n std::string device;\n long return_code;\n};\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is removed by the PC\/SC-Lite daemon.\nstruct ReaderRemoveMessageData {\n std::string reader_name;\n int port;\n};\n\nvoid PcscLiteServerDaemonThreadMain() {\n while (true) {\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"[daemon thread] \"\n << \"Waiting for the new connected clients...\";\n optional<int> server_socket_file_descriptor =\n PcscLiteServerSocketsManager::GetInstance()->WaitAndPop();\n if (!server_socket_file_descriptor) {\n \/\/ A shutdown signal received.\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix\n << \"[daemon thread] Shutting down...\";\n break;\n }\n\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"[daemon thread] A new \"\n << \"client was connected, starting a handler thread...\";\n \/\/ Note: even though the CreateContextThread function accepts its\n \/\/ server_socket_file_descriptor argument by pointer, it doesn't store the\n \/\/ pointer itself anywhere - so it's safe to use a local variable here.\n uint32_t server_socket_file_descriptor_unsigned =\n static_cast<uint32_t>(server_socket_file_descriptor.value());\n \/\/ FIXME(emaxx): Deal with cases when CreateContextThread returns errors.\n \/\/ Looks like it may happen legitimately when the abusive client(s) request\n \/\/ to establish too many requests. Probably, some limitation should be\n \/\/ applied to all clients.\n GOOGLE_SMART_CARD_CHECK(\n ::CreateContextThread(&server_socket_file_descriptor_unsigned) ==\n SCARD_S_SUCCESS);\n }\n\n \/\/ Clean up the structures and threads owned by the third-party PC\/SC-Lite\n \/\/ code. This follows the code in the \"if (AraKiri)\" block in the\n \/\/ `SVCServiceRunLoop()` function in pcsc-lite\/src\/src\/pcscdaemon.c.\n HPStopHotPluggables();\n \/\/ TODO: Upstream's approach with a magic sleep is flaky: the background\n \/\/ thread might be still running after this point, causing crashes. Replace\n \/\/ this with a proper waiting mechanism.\n SYS_Sleep(5);\n RFCleanupReaders();\n EHDeinitializeEventStructures();\n ContextsDeinitialize();\n}\n\n} \/\/ namespace\n\ntemplate <>\nStructValueDescriptor<ReaderInitAddMessageData>::Description\nStructValueDescriptor<ReaderInitAddMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderInitAddMessageData\")\n .WithField(&ReaderInitAddMessageData::reader_name, \"readerName\")\n .WithField(&ReaderInitAddMessageData::port, \"port\")\n .WithField(&ReaderInitAddMessageData::device, \"device\");\n}\n\ntemplate <>\nStructValueDescriptor<ReaderFinishAddMessageData>::Description\nStructValueDescriptor<ReaderFinishAddMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderFinishAddMessageData\")\n .WithField(&ReaderFinishAddMessageData::reader_name, \"readerName\")\n .WithField(&ReaderFinishAddMessageData::port, \"port\")\n .WithField(&ReaderFinishAddMessageData::device, \"device\")\n .WithField(&ReaderFinishAddMessageData::return_code, \"returnCode\");\n}\n\ntemplate <>\nStructValueDescriptor<ReaderRemoveMessageData>::Description\nStructValueDescriptor<ReaderRemoveMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderRemoveMessageData\")\n .WithField(&ReaderRemoveMessageData::reader_name, \"readerName\")\n .WithField(&ReaderRemoveMessageData::port, \"port\");\n}\n\nPcscLiteServerWebPortService::PcscLiteServerWebPortService(\n GlobalContext* global_context)\n : global_context_(global_context) {\n GOOGLE_SMART_CARD_CHECK(!g_pcsc_lite_server);\n g_pcsc_lite_server = this;\n}\n\nPcscLiteServerWebPortService::~PcscLiteServerWebPortService() {\n \/\/ If the daemon thread is joinable, it means `ShutDownAndWait()` wasn't\n \/\/ called, which is a violation of the contract.\n GOOGLE_SMART_CARD_CHECK(!daemon_thread_.joinable());\n\n GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server == this);\n g_pcsc_lite_server = nullptr;\n}\n\n\/\/ static\nconst PcscLiteServerWebPortService*\nPcscLiteServerWebPortService::GetInstance() {\n GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server);\n return g_pcsc_lite_server;\n}\n\nvoid PcscLiteServerWebPortService::InitializeAndRunDaemonThread() {\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Initialization...\";\n\n IpcEmulation::CreateGlobalInstance();\n PcscLiteServerSocketsManager::CreateGlobalInstance();\n\n ::SYS_InitRandom();\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Setting up PC\/SC-Lite \"\n << \"logging...\";\n ::DebugLogSetLogType(DEBUGLOG_SYSLOG_DEBUG);\n#ifdef NDEBUG\n ::DebugLogSetLevel(PCSC_LOG_ERROR);\n#else\n ::DebugLogSetLevel(PCSC_LOG_DEBUG);\n ::DebugLogSetCategory(DEBUG_CATEGORY_APDU | DEBUG_CATEGORY_SW);\n#endif\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"PC\/SC-Lite logging was \"\n << \"set up.\";\n\n LONG return_code;\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Allocating reader \"\n << \"structures...\";\n return_code = ::RFAllocateReaderSpace(0);\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Reader structures \"\n << \"allocation finished with the following result: \\\"\"\n << ::pcsc_stringify_error(return_code) << \"\\\".\";\n GOOGLE_SMART_CARD_CHECK(return_code == SCARD_S_SUCCESS);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Performing initial hot \"\n << \"plug drivers search...\";\n return_code = ::HPSearchHotPluggables();\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Initial hot plug \"\n << \"drivers search finished with the following result code: \"\n << return_code << \".\";\n GOOGLE_SMART_CARD_CHECK(return_code == 0);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Registering for hot \"\n << \"plug events...\";\n \/\/ FIXME(emaxx): Currently this ends up on polling the libusb each second, as\n \/\/ it doesn't provide any way to subscribe for the device list change. But\n \/\/ it's possible to optimize this onto publisher-pattern-style implementation,\n \/\/ by handling the chrome.usb API events (see\n \/\/ <https:\/\/developer.chrome.com\/apps\/usb#Events>) and using them in a\n \/\/ replacement implementation of the currently used original hotplug_libusb.c\n \/\/ source file.\n return_code = ::HPRegisterForHotplugEvents();\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Registering for hot \"\n << \"plug events finished with the following result code: \" << return_code\n << \".\";\n GOOGLE_SMART_CARD_CHECK(return_code == 0);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Allocating client \"\n << \"structures...\";\n return_code = ::ContextsInitialize(0, 0);\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Client structures \"\n << \"allocation finished with the following result code: \" << return_code\n << \"...\";\n GOOGLE_SMART_CARD_CHECK(return_code == 1);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Waiting for the readers \"\n << \"initialization...\";\n ::RFWaitForReaderInit();\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Waiting for the readers \"\n << \"initialization finished.\";\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Starting PC\/SC-Lite \"\n << \"daemon thread...\";\n daemon_thread_ = std::thread(PcscLiteServerDaemonThreadMain);\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"PC\/SC-Lite daemon \"\n << \"thread has started.\";\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Initialization \"\n << \"successfully finished.\";\n}\n\nvoid PcscLiteServerWebPortService::ShutDownAndWait() {\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Shutting down the PC\/SC-Lite daemon thread...\";\n \/\/ This notifies the daemon thread to shut down.\n PcscLiteServerSocketsManager::GetInstance()->ShutDown();\n daemon_thread_.join();\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix\n << \"The PC\/SC-Lite daemon thread shut down.\";\n\n \/\/ Shut down the global state created in `InitializeAndRunDaemonThread()`.\n PcscLiteServerSocketsManager::DestroyGlobalInstance();\n IpcEmulation::DestroyGlobalInstance();\n}\n\nvoid PcscLiteServerWebPortService::PostReaderInitAddMessage(\n const char* reader_name,\n int port,\n const char* device) const {\n ReaderInitAddMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n message_data.device = device;\n PostMessage(kReaderInitAddMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostReaderFinishAddMessage(\n const char* reader_name,\n int port,\n const char* device,\n long return_code) const {\n ReaderFinishAddMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n message_data.device = device;\n message_data.return_code = return_code;\n PostMessage(kReaderFinishAddMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostReaderRemoveMessage(\n const char* reader_name,\n int port) const {\n ReaderRemoveMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n PostMessage(kReaderRemoveMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostMessage(const char* type,\n Value message_data) const {\n TypedMessage typed_message;\n typed_message.type = type;\n typed_message.data = std::move(message_data);\n global_context_->PostMessageToJs(\n ConvertToValueOrDie(std::move(typed_message)));\n}\n\n} \/\/ namespace google_smart_card\n<|endoftext|>"} {"text":"<commit_before>#include \"WPILib.h\"\n#include \"RobotStrap.h\"\n#include \"constants.h\"\n\n\/**\n * Constructor \n *\/\nRobotStrap::RobotStrap() :\n\t\/\/ Initialize all the member objects in the same order\n\t\/\/ declared within the body.\n\tmyRobot(LEFT_MOTOR_PORT, RIGHT_MOTOR_PORT),\n\tstick(JOYSTICK_PORT)\n{\n\tmyRobot.SetExpiration(0.1);\n}\n\n\/**\n * Prints robot status to the console \n *\/\nvoid RobotStrap::printStatus( void )\n{\n\t\/\/ Get an instance of the driver station to use its API\n\tDriverStation* ds = DriverStation::GetInstance();\n\t\n\t\/\/ Get important variable data\n\tfloat voltage = ds -> GetBatteryVoltage();\n\n\t\/\/ Print the data\n\tprintf(\"=======STATUS=======\\n\");\n\tprintf(\"Battery Voltage: %f\\n\", voltage);\n}\n\n\/**\n * Runs during test mode\n *\/\nvoid RobotStrap::Test( void )\n{\n\n}\n\n\/**\n * Drive left & right motors for 2 seconds then stop\n *\/\nvoid RobotStrap::Autonomous( void )\n{\n\tmyRobot.SetSafetyEnabled(false);\n\tmyRobot.Drive(-0.5, 0.0); \t\/\/ drive forwards half speed\n\tWait(2.0); \t\t\t\t\/\/ for 2 seconds\n\tmyRobot.Drive(0.0, 0.0); \t\/\/ stop robot\n}\n\n\/**\n * Runs the motors with arcade steering. \n *\/\nvoid RobotStrap::OperatorControl( void )\n{\t\n\t\/\/ Set the safety\n\tmyRobot.SetSafetyEnabled(true);\n\n\t\/\/ Establish arm\n\tJaguar* arm = new Jaguar(ARM_MOTOR_PORT);\n\t\n\t\/\/ Infinite loop\n\twhile (IsOperatorControl())\n\t{\t\n\t\t\/\/ Print status if the button is pressed\n\t\tif(stick.GetRawButton(11))\n\t\t\tthis -> printStatus();\n\t\t\n\t\t\/\/ Move the arm based on buttons\n\t\tbool launchValue = stick.GetRawButton(1);\n\t\tbool rewindValue = stick.GetRawButton(2);\n\t\t\n\t\tif(launchValue)\n\t\t\t\/\/ make arm launch forwards\n\t\t\tarm -> Set(0.25);\n\t\telse if(rewindValue)\n\t\t\t\/\/ make the arm launch backwards\n\t\t\tarm -> Set(-0.25);\n\t\telse\n\t\t\tarm -> Set(0);\n\t\t\n\t\tmyRobot.ArcadeDrive(stick); \/\/ drive with arcade style (use right stick)\n\t\tWait(0.005); \/\/ wait for a motor update time\n\t}\n}\n\nSTART_ROBOT_CLASS(RobotStrap);\n\n<commit_msg>Update RobotStrap.cpp<commit_after>#include \"WPILib.h\"\n#include \"RobotStrap.h\"\n#include \"constants.h\"\n\n\/**\n * Constructor \n *\/\nRobotStrap::RobotStrap() :\n\t\/\/ Initialize all the member objects in the same order\n\t\/\/ declared within the body.\n\tmyRobot(LEFT_MOTOR_PORT, RIGHT_MOTOR_PORT),\n\tstick(JOYSTICK_PORT)\n{\n\tmyRobot.SetExpiration(0.1);\n}\n\n\/**\n * Prints robot status to the console \n *\/\nvoid RobotStrap::printStatus( void )\n{\n\t\/\/ Get an instance of the driver station to use its API\n\tDriverStation* ds = DriverStation::GetInstance();\n\t\n\t\/\/ Get important variable data\n\tfloat voltage = ds -> GetBatteryVoltage();\n\n\t\/\/ Print the data\n\tprintf(\"=======STATUS=======\\n\");\n\tprintf(\"Battery Voltage: %f\\n\", voltage);\n}\n\n\/**\n * Runs during test mode\n *\/\nvoid RobotStrap::Test( void )\n{\n\n}\n\n\/**\n * Drive left & right motors for 2 seconds then stop\n *\/\nvoid RobotStrap::Autonomous( void )\n{\n\tmyRobot.SetSafetyEnabled(false);\n\tmyRobot.Drive(-0.5, 0.0); \t\/\/ drive forwards half speed\n\tWait(2.0); \t\t\t\t\/\/ for 2 seconds\n\tmyRobot.Drive(0.0, 0.0); \t\/\/ stop robot\n}\n\n\/**\n * Runs the motors with arcade steering. \n *\/\nvoid RobotStrap::OperatorControl( void )\n{\t\n\t\/\/ Set the safety\n\tmyRobot.SetSafetyEnabled(true);\n\n\t\/\/ Establish arm\n\tJaguar* arm = new Jaguar(ARM_MOTOR_PORT);\n\t\n\t\/\/ Infinite loop\n\twhile (IsOperatorControl())\n\t{\t\n\t\t\/\/ Print status if the button is pressed\n\t\tif(stick.GetRawButton(11))\n\t\t\tthis -> printStatus();\n\t\t\n\t\t\/\/ Move the arm based on buttons\n\t\tbool launchValue = stick.GetRawButton(1);\n\t\tbool rewindValue = stick.GetRawButton(2);\n\t\t\n\t\t\/\/ Determine the speed to throw the arm at\n\t\tfloat speed = (stick.getThrottle() - (-1)) \/ 2;\n\t\t\n\t\tif(launchValue)\n\t\t\t\/\/ make arm launch forwards\n\t\t\tarm -> Set(1 * speed);\n\t\telse if(rewindValue)\n\t\t\t\/\/ make the arm launch backwards\n\t\t\tarm -> Set(-1 * speed);\n\t\telse\n\t\t\tarm -> Set(0);\n\t\t\n\t\tmyRobot.ArcadeDrive(stick); \/\/ drive with arcade style (use right stick)\n\t\tWait(0.005); \/\/ wait for a motor update time\n\t}\n}\n\nSTART_ROBOT_CLASS(RobotStrap);\n\n<|endoftext|>"} {"text":"<commit_before>#include \"dbus\/baulicht.h\"\n#include \"baulichtexecutor.h\"\n\n#include <QCoreApplication>\n#include <QDBusConnection>\n#include <QDBusError>\n#include <QDebug>\n\nint main(int argc, char* argv[])\n{\n QCoreApplication app(argc, argv);\n\n const QString& serviceName = \"de.naptower.Baulicht\";\n\n QDBusConnection connection = QDBusConnection::sessionBus();\n if (!connection.registerService(serviceName)) {\n qDebug() << \"Failed to register service\" << serviceName << \":\" << connection.lastError().message();\n return 1;\n }\n\n Baulicht service;\n if (!connection.registerObject(\"\/\", &service, QDBusConnection::ExportAllSlots)) {\n qDebug() << \"Failed to register object at \/:\" << connection.lastError().message();\n return 1;\n }\n\n BaulichtExecutor executor;\n QString code = executor.convertToMorse(\"Morse Code\");\n qDebug() << \"Morse code:\" << code;\n qDebug() << \"Morse code:\" << QString(\"===_===___===_===_===___=_===_=___=_=_=___=_______===_=_===_=___===_===_===___===_=_=___=\");\n\n return app.exec();\n}\n\n<commit_msg>Removed debug code.<commit_after>#include \"dbus\/baulicht.h\"\n#include \"baulichtexecutor.h\"\n\n#include <QCoreApplication>\n#include <QDBusConnection>\n#include <QDBusError>\n#include <QDebug>\n\nint main(int argc, char* argv[])\n{\n QCoreApplication app(argc, argv);\n\n const QString& serviceName = \"de.naptower.Baulicht\";\n\n QDBusConnection connection = QDBusConnection::sessionBus();\n if (!connection.registerService(serviceName)) {\n qDebug() << \"Failed to register service\" << serviceName << \":\" << connection.lastError().message();\n return 1;\n }\n\n Baulicht service;\n if (!connection.registerObject(\"\/\", &service, QDBusConnection::ExportAllSlots)) {\n qDebug() << \"Failed to register object at \/:\" << connection.lastError().message();\n return 1;\n }\n\n BaulichtExecutor executor;\n QString code = executor.convertToMorse(\"Morse Code\");\n\n return app.exec();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Script Generator project on Qt Labs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"shellheadergenerator.h\"\n#include \"fileout.h\"\n\n#include <QtCore\/QDir>\n\n#include <qdebug.h>\n\nQString ShellHeaderGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const\n{\n return QString(\"PythonQtWrapper_%1.h\").arg(meta_class->name());\n}\n\n\nvoid ShellHeaderGenerator::writeFieldAccessors(QTextStream &s, const AbstractMetaField *field)\n{\n const AbstractMetaFunction *setter = field->setter();\n const AbstractMetaFunction *getter = field->getter();\n\n \/\/ static fields are not supported (yet?)\n if (setter->isStatic()) return;\n\n \/\/ Uuid data4 did not work (TODO: move to typesystem...(\n if (field->enclosingClass()->name()==\"QUuid\" && setter->name()==\"data4\") return;\n if (field->enclosingClass()->name()==\"QIPv6Address\") return;\n\n if (!field->type()->isConstant()) {\n writeFunctionSignature(s, setter, 0, QString(),\n Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | ShowStatic | UnderscoreSpaces));\n s << \"{ theWrappedObject->\" << field->name() << \" = \" << setter->arguments()[0]->argumentName() << \"; }\\n\";\n }\n \n writeFunctionSignature(s, getter, 0, QString(),\n Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));\n s << \"{ return theWrappedObject->\" << field->name() << \"; }\\n\";\n}\n\nstatic bool enum_lessThan(const AbstractMetaEnum *a, const AbstractMetaEnum *b)\n{\n return a->name() < b->name();\n}\n\nstatic bool field_lessThan(const AbstractMetaField *a, const AbstractMetaField *b)\n{\n return a->name() < b->name();\n}\n\nvoid ShellHeaderGenerator::write(QTextStream &s, const AbstractMetaClass *meta_class)\n{\n QString builtIn = ShellGenerator::isBuiltIn(meta_class->name())?\"_builtin\":\"\";\n QString pro_file_name = meta_class->package().replace(\".\", \"_\") + builtIn + \"\/\" + meta_class->package().replace(\".\", \"_\") + builtIn + \".pri\";\n priGenerator->addHeader(pro_file_name, fileNameForClass(meta_class));\n setupGenerator->addClass(meta_class->package().replace(\".\", \"_\") + builtIn, meta_class);\n\n QString include_block = \"PYTHONQTWRAPPER_\" + meta_class->name().toUpper() + \"_H\";\n\n s << \"#ifndef \" << include_block << endl\n << \"#define \" << include_block << endl << endl;\n\n Include inc = meta_class->typeEntry()->include();\n ShellGenerator::writeInclude(s, inc);\n\n s << \"#include <QObject>\" << endl << endl;\n s << \"#include <PythonQt.h>\" << endl << endl;\n\n IncludeList list = meta_class->typeEntry()->extraIncludes();\n qSort(list.begin(), list.end());\n foreach (const Include &inc, list) {\n ShellGenerator::writeInclude(s, inc);\n } \n s << endl;\n\n AbstractMetaFunctionList ctors = meta_class->queryFunctions(AbstractMetaClass::Constructors\n | AbstractMetaClass::WasVisible\n | AbstractMetaClass::NotRemovedFromTargetLang);\n\n if (meta_class->qualifiedCppName().contains(\"Ssl\")) {\n s << \"#ifndef QT_NO_OPENSSL\" << endl;\n }\n\n \/\/ Shell-------------------------------------------------------------------\n if (meta_class->generateShellClass() && !ctors.isEmpty()) {\n\n AbstractMetaFunctionList virtualsForShell = getVirtualFunctionsForShell(meta_class);\n\n s << \"class \" << shellClassName(meta_class)\n << \" : public \" << meta_class->qualifiedCppName() << endl << \"{\" << endl;\n s << \"public:\" << endl;\n foreach(AbstractMetaFunction* fun, ctors) {\n s << \" \";\n writeFunctionSignature(s, fun, 0,\"PythonQtShell_\",\n Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));\n s << \":\" << meta_class->qualifiedCppName() << \"(\";\n QString scriptFunctionName = fun->originalName();\n AbstractMetaArgumentList args = fun->arguments();\n for (int i = 0; i < args.size(); ++i) {\n if (i > 0)\n s << \", \";\n s << args.at(i)->argumentName();\n }\n s << \"),_wrapper(NULL) { \";\n writeInjectedCode(s, meta_class, TypeSystem::PyInheritShellConstructorCode, true);\n s << \" };\" << endl;\n }\n s << endl;\n s << \" ~\" << shellClassName(meta_class) << \"();\" << endl;\n s << endl;\n\n foreach(AbstractMetaFunction* fun, virtualsForShell) {\n s << \"virtual \";\n writeFunctionSignature(s, fun, 0, QString(),\n Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));\n s << \";\" << endl;\n }\n s << endl;\n writeInjectedCode(s, meta_class, TypeSystem::PyShellDeclaration);\n writeInjectedCode(s, meta_class, TypeSystem::PyInheritShellDeclaration, true);\n s << \" PythonQtInstanceWrapper* _wrapper; \" << endl;\n\n s << \"};\" << endl << endl;\n }\n\n \/\/ Promoter-------------------------------------------------------------------\n AbstractMetaFunctionList promoteFunctions;\n if (meta_class->typeEntry()->shouldCreatePromoter()) {\n promoteFunctions = getProtectedFunctionsThatNeedPromotion(meta_class);\n }\n if (!promoteFunctions.isEmpty()) {\n s << \"class \" << promoterClassName(meta_class)\n << \" : public \" << meta_class->qualifiedCppName() << endl << \"{ public:\" << endl;\n\n AbstractMetaEnumList enums1 = meta_class->enums();\n qSort(enums1.begin(), enums1.end(), enum_lessThan);\n foreach(AbstractMetaEnum* enum1, enums1) {\n if (enum1->wasProtected()) {\n s << \"enum \" << enum1->name() << \"{\" << endl;\n bool first = true;\n QString scope = meta_class->qualifiedCppName();\n foreach(AbstractMetaEnumValue* value, enum1->values()) {\n if (first) { first = false; }\n else { s << \", \"; }\n s << \" \" << value->name() << \" = \" << scope << \"::\" << value->name();\n }\n s << \"};\" << endl;\n }\n }\n \n foreach(AbstractMetaFunction* fun, promoteFunctions) {\n if (fun->isStatic()) {\n s << \"static \";\n }\n s << \"inline \";\n writeFunctionSignature(s, fun, 0, \"promoted_\",\n Option(IncludeDefaultExpression | OriginalName | UnderscoreSpaces | ProtectedEnumAsInts));\n s << \" { \";\n QString scriptFunctionName = fun->originalName();\n AbstractMetaArgumentList args = fun->arguments();\n if (fun->type()) {\n s << \"return \";\n }\n if (!fun->isAbstract()) {\n s << meta_class->qualifiedCppName() << \"::\";\n }\n s << fun->originalName() << \"(\";\n for (int i = 0; i < args.size(); ++i) {\n if (i > 0) {\n s << \", \";\n }\n if (args.at(i)->type()->isEnum()) {\n AbstractMetaEnum* enumType = m_classes.findEnum((EnumTypeEntry *)args.at(i)->type()->typeEntry());\n if (enumType && enumType->wasProtected()) {\n s << \"(\" << enumType->typeEntry()->qualifiedCppName() << \")\";\n }\n }\n s << args.at(i)->argumentName();\n }\n s << \"); }\" << endl;\n }\n\n s << \"};\" << endl << endl;\n }\n\n \/\/ Wrapper-------------------------------------------------------------------\n\n s << \"class \" << wrapperClassName(meta_class)\n << \" : public QObject\" << endl\n << \"{ Q_OBJECT\" << endl;\n\n s << \"public:\" << endl;\n\n AbstractMetaEnumList enums1 = meta_class->enums();\n qSort(enums1.begin(), enums1.end(), enum_lessThan);\n AbstractMetaEnumList enums;\n QList<FlagsTypeEntry*> flags;\n foreach(AbstractMetaEnum* enum1, enums1) {\n \/\/ catch gadgets and enums that are not exported on QObjects...\n if ((enum1->wasProtected() || enum1->wasPublic()) && (!meta_class->isQObject() || !enum1->hasQEnumsDeclaration())) {\n enums << enum1;\n if (enum1->typeEntry()->flags()) {\n flags << enum1->typeEntry()->flags();\n }\n }\n }\n if (enums.count()) {\n s << \"Q_ENUMS(\";\n foreach(AbstractMetaEnum* enum1, enums) {\n s << enum1->name() << \" \";\n }\n s << \")\" << endl;\n \n if (flags.count()) {\n s << \"Q_FLAGS(\";\n foreach(FlagsTypeEntry* flag1, flags) {\n QString origName = flag1->originalName();\n int idx = origName.lastIndexOf(\"::\");\n if (idx!= -1) {\n origName = origName.mid(idx+2);\n }\n s << origName << \" \";\n }\n s << \")\" << endl;\n }\n \n foreach(AbstractMetaEnum* enum1, enums) {\n s << \"enum \" << enum1->name() << \"{\" << endl;\n bool first = true;\n QString scope = enum1->wasProtected() ? promoterClassName(meta_class) : meta_class->qualifiedCppName();\n\n foreach(AbstractMetaEnumValue* value, enum1->values()) {\n if (first) { first = false; }\n else { s << \", \"; }\n s << \" \" << value->name() << \" = \" << scope << \"::\" << value->name();\n }\n s << \"};\" << endl;\n }\n if (flags.count()) {\n foreach(AbstractMetaEnum* enum1, enums) {\n if (enum1->typeEntry()->flags()) {\n QString origName = enum1->typeEntry()->flags()->originalName();\n int idx = origName.lastIndexOf(\"::\");\n if (idx!= -1) {\n origName = origName.mid(idx+2);\n }\n s << \"Q_DECLARE_FLAGS(\"<< origName << \", \" << enum1->name() <<\")\"<<endl;\n }\n }\n }\n }\n s << \"public slots:\" << endl;\n if (meta_class->generateShellClass() || !meta_class->isAbstract()) {\n\n bool copyConstructorSeen = false;\n bool defaultConstructorSeen = false;\n foreach (const AbstractMetaFunction *fun, ctors) {\n if (fun->isAbstract() || (!meta_class->generateShellClass() && !fun->isPublic())) { continue; }\n\n s << meta_class->qualifiedCppName() << \"* \";\n writeFunctionSignature(s, fun, 0, \"new_\",\n Option(IncludeDefaultExpression | OriginalName | ShowStatic));\n s << \";\" << endl;\n if (fun->arguments().size()==1 && meta_class->qualifiedCppName() == fun->arguments().at(0)->type()->typeEntry()->qualifiedCppName()) {\n copyConstructorSeen = true;\n }\n if (fun->arguments().size()==0) {\n defaultConstructorSeen = true;\n }\n }\n\n if (meta_class->typeEntry()->isValue()\n && !copyConstructorSeen && defaultConstructorSeen) {\n QString className = meta_class->generateShellClass()?shellClassName(meta_class):meta_class->qualifiedCppName();\n s << meta_class->qualifiedCppName() << \"* new_\" << meta_class->name() << \"(const \" << meta_class->qualifiedCppName() << \"& other) {\" << endl;\n s << className << \"* a = new \" << className << \"();\" << endl;\n s << \"*((\" << meta_class->qualifiedCppName() << \"*)a) = other;\" << endl;\n s << \"return a; }\" << endl;\n }\n }\n if (meta_class->hasPublicDestructor() && !meta_class->isNamespace()) {\n s << \"void delete_\" << meta_class->name() << \"(\" << meta_class->qualifiedCppName() << \"* obj) { delete obj; } \";\n s << endl;\n }\n\n AbstractMetaFunctionList functions = getFunctionsToWrap(meta_class);\n\n foreach (const AbstractMetaFunction *function, functions) {\n if (!function->isSlot() || function->isVirtual()) {\n \n \/\/ for debugging:\n functionHasNonConstReferences(function);\n \n s << \" \";\n writeFunctionSignature(s, function, 0, QString(),\n Option(ConvertReferenceToPtr | FirstArgIsWrappedObject | IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces | ProtectedEnumAsInts));\n s << \";\" << endl;\n }\n }\n if (meta_class->hasDefaultToStringFunction() || meta_class->hasToStringCapability()) {\n s << \" QString py_toString(\" << meta_class->qualifiedCppName() << \"*);\" << endl; \n }\n if (meta_class->hasDefaultIsNull()) {\n s << \" bool __nonzero__(\" << meta_class->qualifiedCppName() << \"* obj) { return !obj->isNull(); }\" << endl; \n }\n\n AbstractMetaFieldList fields = meta_class->fields();\n qSort(fields.begin(), fields.end(), field_lessThan);\n\n \/\/ TODO: move \"So\" check to typesystem, e.g. allow star in rejection...\n \/\/ Field accessors\n foreach (const AbstractMetaField *field, fields ) {\n if (field->isPublic() && !field->type()->name().startsWith(\"So\")) {\n writeFieldAccessors(s, field);\n }\n }\n\n writeInjectedCode(s, meta_class, TypeSystem::PyWrapperDeclaration);\n\n \n s << \"};\" << endl << endl;\n if (meta_class->qualifiedCppName().contains(\"Ssl\")) {\n s << \"#endif\" << endl << endl;\n }\n\n s << \"#endif \/\/ \" << include_block << endl;\n\n\n}\n\nvoid ShellHeaderGenerator::writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class, int type, bool recursive)\n{\n const AbstractMetaClass *cls = meta_class;\n do {\n CodeSnipList code_snips = cls->typeEntry()->codeSnips();\n foreach(const CodeSnip &cs, code_snips) {\n if (cs.language == type) {\n s << cs.code() << endl;\n }\n }\n cls = cls->baseClass();\n } while (recursive && cls);\n}\n<commit_msg>added special field accessors for Inventor<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Script Generator project on Qt Labs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"shellheadergenerator.h\"\n#include \"fileout.h\"\n\n#include <QtCore\/QDir>\n\n#include <qdebug.h>\n\nQString ShellHeaderGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const\n{\n return QString(\"PythonQtWrapper_%1.h\").arg(meta_class->name());\n}\n\n\nvoid ShellHeaderGenerator::writeFieldAccessors(QTextStream &s, const AbstractMetaField *field)\n{\n const AbstractMetaFunction *setter = field->setter();\n const AbstractMetaFunction *getter = field->getter();\n\n \/\/ static fields are not supported (yet?)\n if (setter->isStatic()) return;\n\n \/\/ Uuid data4 did not work (TODO: move to typesystem...(\n if (field->enclosingClass()->name()==\"QUuid\" && setter->name()==\"data4\") return;\n if (field->enclosingClass()->name()==\"QIPv6Address\") return;\n\n bool isInventorField = field->type()->name().startsWith(\"So\");\n\n if (!isInventorField && !field->type()->isConstant()) {\n writeFunctionSignature(s, setter, 0, QString(),\n Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | ShowStatic | UnderscoreSpaces));\n s << \"{ theWrappedObject->\" << field->name() << \" = \" << setter->arguments()[0]->argumentName() << \"; }\\n\";\n }\n \n bool addIndirection = false;\n if (isInventorField && getter->type()->indirections() == 0) {\n \/\/ make it a field ptr:\n getter->type()->setIndirections(1);\n addIndirection = true;\n }\n writeFunctionSignature(s, getter, 0, QString(),\n Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));\n s << \"{ return \";\n if (addIndirection) {\n s << \"&\";\n }\n s << \"theWrappedObject->\" << field->name() << \"; }\\n\";\n}\n\nstatic bool enum_lessThan(const AbstractMetaEnum *a, const AbstractMetaEnum *b)\n{\n return a->name() < b->name();\n}\n\nstatic bool field_lessThan(const AbstractMetaField *a, const AbstractMetaField *b)\n{\n return a->name() < b->name();\n}\n\nvoid ShellHeaderGenerator::write(QTextStream &s, const AbstractMetaClass *meta_class)\n{\n QString builtIn = ShellGenerator::isBuiltIn(meta_class->name())?\"_builtin\":\"\";\n QString pro_file_name = meta_class->package().replace(\".\", \"_\") + builtIn + \"\/\" + meta_class->package().replace(\".\", \"_\") + builtIn + \".pri\";\n priGenerator->addHeader(pro_file_name, fileNameForClass(meta_class));\n setupGenerator->addClass(meta_class->package().replace(\".\", \"_\") + builtIn, meta_class);\n\n QString include_block = \"PYTHONQTWRAPPER_\" + meta_class->name().toUpper() + \"_H\";\n\n s << \"#ifndef \" << include_block << endl\n << \"#define \" << include_block << endl << endl;\n\n Include inc = meta_class->typeEntry()->include();\n ShellGenerator::writeInclude(s, inc);\n\n s << \"#include <QObject>\" << endl << endl;\n s << \"#include <PythonQt.h>\" << endl << endl;\n\n IncludeList list = meta_class->typeEntry()->extraIncludes();\n qSort(list.begin(), list.end());\n foreach (const Include &inc, list) {\n ShellGenerator::writeInclude(s, inc);\n } \n s << endl;\n\n AbstractMetaFunctionList ctors = meta_class->queryFunctions(AbstractMetaClass::Constructors\n | AbstractMetaClass::WasVisible\n | AbstractMetaClass::NotRemovedFromTargetLang);\n\n if (meta_class->qualifiedCppName().contains(\"Ssl\")) {\n s << \"#ifndef QT_NO_OPENSSL\" << endl;\n }\n\n \/\/ Shell-------------------------------------------------------------------\n if (meta_class->generateShellClass() && !ctors.isEmpty()) {\n\n AbstractMetaFunctionList virtualsForShell = getVirtualFunctionsForShell(meta_class);\n\n s << \"class \" << shellClassName(meta_class)\n << \" : public \" << meta_class->qualifiedCppName() << endl << \"{\" << endl;\n s << \"public:\" << endl;\n foreach(AbstractMetaFunction* fun, ctors) {\n s << \" \";\n writeFunctionSignature(s, fun, 0,\"PythonQtShell_\",\n Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));\n s << \":\" << meta_class->qualifiedCppName() << \"(\";\n QString scriptFunctionName = fun->originalName();\n AbstractMetaArgumentList args = fun->arguments();\n for (int i = 0; i < args.size(); ++i) {\n if (i > 0)\n s << \", \";\n s << args.at(i)->argumentName();\n }\n s << \"),_wrapper(NULL) { \";\n writeInjectedCode(s, meta_class, TypeSystem::PyInheritShellConstructorCode, true);\n s << \" };\" << endl;\n }\n s << endl;\n s << \" ~\" << shellClassName(meta_class) << \"();\" << endl;\n s << endl;\n\n foreach(AbstractMetaFunction* fun, virtualsForShell) {\n s << \"virtual \";\n writeFunctionSignature(s, fun, 0, QString(),\n Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));\n s << \";\" << endl;\n }\n s << endl;\n writeInjectedCode(s, meta_class, TypeSystem::PyShellDeclaration);\n writeInjectedCode(s, meta_class, TypeSystem::PyInheritShellDeclaration, true);\n s << \" PythonQtInstanceWrapper* _wrapper; \" << endl;\n\n s << \"};\" << endl << endl;\n }\n\n \/\/ Promoter-------------------------------------------------------------------\n AbstractMetaFunctionList promoteFunctions;\n if (meta_class->typeEntry()->shouldCreatePromoter()) {\n promoteFunctions = getProtectedFunctionsThatNeedPromotion(meta_class);\n }\n if (!promoteFunctions.isEmpty()) {\n s << \"class \" << promoterClassName(meta_class)\n << \" : public \" << meta_class->qualifiedCppName() << endl << \"{ public:\" << endl;\n\n AbstractMetaEnumList enums1 = meta_class->enums();\n qSort(enums1.begin(), enums1.end(), enum_lessThan);\n foreach(AbstractMetaEnum* enum1, enums1) {\n if (enum1->wasProtected()) {\n s << \"enum \" << enum1->name() << \"{\" << endl;\n bool first = true;\n QString scope = meta_class->qualifiedCppName();\n foreach(AbstractMetaEnumValue* value, enum1->values()) {\n if (first) { first = false; }\n else { s << \", \"; }\n s << \" \" << value->name() << \" = \" << scope << \"::\" << value->name();\n }\n s << \"};\" << endl;\n }\n }\n \n foreach(AbstractMetaFunction* fun, promoteFunctions) {\n if (fun->isStatic()) {\n s << \"static \";\n }\n s << \"inline \";\n writeFunctionSignature(s, fun, 0, \"promoted_\",\n Option(IncludeDefaultExpression | OriginalName | UnderscoreSpaces | ProtectedEnumAsInts));\n s << \" { \";\n QString scriptFunctionName = fun->originalName();\n AbstractMetaArgumentList args = fun->arguments();\n if (fun->type()) {\n s << \"return \";\n }\n if (!fun->isAbstract()) {\n s << meta_class->qualifiedCppName() << \"::\";\n }\n s << fun->originalName() << \"(\";\n for (int i = 0; i < args.size(); ++i) {\n if (i > 0) {\n s << \", \";\n }\n if (args.at(i)->type()->isEnum()) {\n AbstractMetaEnum* enumType = m_classes.findEnum((EnumTypeEntry *)args.at(i)->type()->typeEntry());\n if (enumType && enumType->wasProtected()) {\n s << \"(\" << enumType->typeEntry()->qualifiedCppName() << \")\";\n }\n }\n s << args.at(i)->argumentName();\n }\n s << \"); }\" << endl;\n }\n\n s << \"};\" << endl << endl;\n }\n\n \/\/ Wrapper-------------------------------------------------------------------\n\n s << \"class \" << wrapperClassName(meta_class)\n << \" : public QObject\" << endl\n << \"{ Q_OBJECT\" << endl;\n\n s << \"public:\" << endl;\n\n AbstractMetaEnumList enums1 = meta_class->enums();\n qSort(enums1.begin(), enums1.end(), enum_lessThan);\n AbstractMetaEnumList enums;\n QList<FlagsTypeEntry*> flags;\n foreach(AbstractMetaEnum* enum1, enums1) {\n \/\/ catch gadgets and enums that are not exported on QObjects...\n if ((enum1->wasProtected() || enum1->wasPublic()) && (!meta_class->isQObject() || !enum1->hasQEnumsDeclaration())) {\n enums << enum1;\n if (enum1->typeEntry()->flags()) {\n flags << enum1->typeEntry()->flags();\n }\n }\n }\n if (enums.count()) {\n s << \"Q_ENUMS(\";\n foreach(AbstractMetaEnum* enum1, enums) {\n s << enum1->name() << \" \";\n }\n s << \")\" << endl;\n \n if (flags.count()) {\n s << \"Q_FLAGS(\";\n foreach(FlagsTypeEntry* flag1, flags) {\n QString origName = flag1->originalName();\n int idx = origName.lastIndexOf(\"::\");\n if (idx!= -1) {\n origName = origName.mid(idx+2);\n }\n s << origName << \" \";\n }\n s << \")\" << endl;\n }\n \n foreach(AbstractMetaEnum* enum1, enums) {\n s << \"enum \" << enum1->name() << \"{\" << endl;\n bool first = true;\n QString scope = enum1->wasProtected() ? promoterClassName(meta_class) : meta_class->qualifiedCppName();\n\n foreach(AbstractMetaEnumValue* value, enum1->values()) {\n if (first) { first = false; }\n else { s << \", \"; }\n s << \" \" << value->name() << \" = \" << scope << \"::\" << value->name();\n }\n s << \"};\" << endl;\n }\n if (flags.count()) {\n foreach(AbstractMetaEnum* enum1, enums) {\n if (enum1->typeEntry()->flags()) {\n QString origName = enum1->typeEntry()->flags()->originalName();\n int idx = origName.lastIndexOf(\"::\");\n if (idx!= -1) {\n origName = origName.mid(idx+2);\n }\n s << \"Q_DECLARE_FLAGS(\"<< origName << \", \" << enum1->name() <<\")\"<<endl;\n }\n }\n }\n }\n s << \"public slots:\" << endl;\n if (meta_class->generateShellClass() || !meta_class->isAbstract()) {\n\n bool copyConstructorSeen = false;\n bool defaultConstructorSeen = false;\n foreach (const AbstractMetaFunction *fun, ctors) {\n if (fun->isAbstract() || (!meta_class->generateShellClass() && !fun->isPublic())) { continue; }\n\n s << meta_class->qualifiedCppName() << \"* \";\n writeFunctionSignature(s, fun, 0, \"new_\",\n Option(IncludeDefaultExpression | OriginalName | ShowStatic));\n s << \";\" << endl;\n if (fun->arguments().size()==1 && meta_class->qualifiedCppName() == fun->arguments().at(0)->type()->typeEntry()->qualifiedCppName()) {\n copyConstructorSeen = true;\n }\n if (fun->arguments().size()==0) {\n defaultConstructorSeen = true;\n }\n }\n\n if (meta_class->typeEntry()->isValue()\n && !copyConstructorSeen && defaultConstructorSeen) {\n QString className = meta_class->generateShellClass()?shellClassName(meta_class):meta_class->qualifiedCppName();\n s << meta_class->qualifiedCppName() << \"* new_\" << meta_class->name() << \"(const \" << meta_class->qualifiedCppName() << \"& other) {\" << endl;\n s << className << \"* a = new \" << className << \"();\" << endl;\n s << \"*((\" << meta_class->qualifiedCppName() << \"*)a) = other;\" << endl;\n s << \"return a; }\" << endl;\n }\n }\n if (meta_class->hasPublicDestructor() && !meta_class->isNamespace()) {\n s << \"void delete_\" << meta_class->name() << \"(\" << meta_class->qualifiedCppName() << \"* obj) { delete obj; } \";\n s << endl;\n }\n\n AbstractMetaFunctionList functions = getFunctionsToWrap(meta_class);\n\n foreach (const AbstractMetaFunction *function, functions) {\n if (!function->isSlot() || function->isVirtual()) {\n \n \/\/ for debugging:\n functionHasNonConstReferences(function);\n \n s << \" \";\n writeFunctionSignature(s, function, 0, QString(),\n Option(ConvertReferenceToPtr | FirstArgIsWrappedObject | IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces | ProtectedEnumAsInts));\n s << \";\" << endl;\n }\n }\n if (meta_class->hasDefaultToStringFunction() || meta_class->hasToStringCapability()) {\n s << \" QString py_toString(\" << meta_class->qualifiedCppName() << \"*);\" << endl; \n }\n if (meta_class->hasDefaultIsNull()) {\n s << \" bool __nonzero__(\" << meta_class->qualifiedCppName() << \"* obj) { return !obj->isNull(); }\" << endl; \n }\n\n AbstractMetaFieldList fields = meta_class->fields();\n qSort(fields.begin(), fields.end(), field_lessThan);\n\n \/\/ TODO: move \"So\" check to typesystem, e.g. allow star in rejection...\n \/\/ Field accessors\n foreach (const AbstractMetaField *field, fields ) {\n if (field->isPublic()) {\n writeFieldAccessors(s, field);\n }\n }\n\n writeInjectedCode(s, meta_class, TypeSystem::PyWrapperDeclaration);\n\n \n s << \"};\" << endl << endl;\n if (meta_class->qualifiedCppName().contains(\"Ssl\")) {\n s << \"#endif\" << endl << endl;\n }\n\n s << \"#endif \/\/ \" << include_block << endl;\n\n\n}\n\nvoid ShellHeaderGenerator::writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class, int type, bool recursive)\n{\n const AbstractMetaClass *cls = meta_class;\n do {\n CodeSnipList code_snips = cls->typeEntry()->codeSnips();\n foreach(const CodeSnip &cs, code_snips) {\n if (cs.language == type) {\n s << cs.code() << endl;\n }\n }\n cls = cls->baseClass();\n } while (recursive && cls);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Vadim N. on 16\/03\/2016.\n\/\/\n\n#include \"benchutils.h\"\n\nint main(int argc, char* argv[]) {\n\n if (argc < 2) {\n std::cout << \"Please re-run the script with the data folder path supplied.\" << std::endl;\n return 1;\n }\n\n std::chrono::system_clock::time_point tp1, tp2;\n\n std::vector< std::pair<std::string, size_t> > timepoints;\n\n std::vector<prob_t> logLvec;\n\n \/\/ std::string temp_str;\n\n \/\/ time_t vj_single_parse, vdj_single_parse,\n \/\/ vj_single_prob, vj_single_meta,\n \/\/ vj_single_infer, vdj_single_prob,\n \/\/ vdj_single_meta, vdj_single_infer;\n\n \/\/ time_t vj_good_parse, vdj_good_parse,\n \/\/ vj_good_prob, vj_good_meta,\n \/\/ vj_good_infer, vdj_good_prob,\n \/\/ vdj_good_meta, vdj_good_infer;\n\n std::string BENCH_DATA_FOLDER = argv[1];\n\n std::cout << \"Data folder:\\t[\" << BENCH_DATA_FOLDER << \"]\" << endl;\n\n\n \/\/\n \/\/ TCR alpha chain repertoire - VJ recombination\n \/\/\n VDJRecombinationGenes vj_single_genes(\"Vgene\",\n BENCH_DATA_FOLDER + \"trav.txt\",\n \"Jgene\",\n BENCH_DATA_FOLDER + \"traj.txt\");\n\n\n VDJRecombinationGenes vj_single_genes2;\n vj_single_genes2 = vj_single_genes;\n\n\n string input_alpha_file = \"alpha.250k.txt\";\n string input_beta_file = \"beta.250k.txt\";\n\n CDR3NucParser parser;\n Cloneset cloneset_vj;\n\n YMIR_BENCHMARK(\"Parsing VJ\",\n parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,\n &cloneset_vj,\n vj_single_genes,\n NUCLEOTIDE,\n VJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE),\n VDJAlignerParameters(2)))\n\n \/\/\n \/\/ TCR beta chain repertoire - VDJ recombination\n \/\/\n\/\/ VDJRecombinationGenes vdj_single_genes(\"Vgene\",\n\/\/ BENCH_DATA_FOLDER + \"trbv.txt\",\n\/\/ \"Jgene\",\n\/\/ BENCH_DATA_FOLDER + \"trbj.txt\",\n\/\/ \"Dgene\",\n\/\/ BENCH_DATA_FOLDER + \"trbd.txt\");\n\/\/\n\/\/ Cloneset cloneset_vdj;\n\/\/ YMIR_BENCHMARK(\"Parsing VDJ\",\n\/\/ parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,\n\/\/ &cloneset_vdj,\n\/\/ vdj_single_genes,\n\/\/ NUCLEOTIDE,\n\/\/ VDJ_RECOMB,\n\/\/ AlignmentColumnOptions()\n\/\/ .setV(AlignmentColumnOptions::USE_PROVIDED)\n\/\/ .setD(AlignmentColumnOptions::OVERWRITE)\n\/\/ .setJ(AlignmentColumnOptions::USE_PROVIDED),\n\/\/ VDJAlignerParameters(3)))\n\n \/\/\n \/\/ VJ MAAG\n \/\/\n ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRA\", EMPTY);\n\n \/\/\n \/\/ VDJ MAAG\n \/\/\n\/\/ ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRB\", EMPTY);\n\n\n \/\/\n \/\/ Inference\n \/\/\n vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000};\n vec_sample = { 100000 };\n vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; \/\/, 2000, 5000, 10000};\n\/\/ vec_block = {2000, 5000, 10000};\n vec_block = { std::stoi(argv[2]) };\n vector<double> vec_alpha = {.5, .6, .7, .8, .9};\n vec_alpha = { std::stof(argv[3]) };\n vector<double> vec_beta = {.1, .5, 1, 3};\n vec_beta = { std::stof(argv[4]) };\n vector<double> vec_K = {1, 2, 3};\n vec_K = { std::stod(argv[5]) };\n ErrorMode error_mode = COMPUTE_ERRORS;\n\n\/\/ int niter, sample, block;\n\/\/ double alpha;\n\/\/ niter = 10;\n\/\/ int sample = 10000;\n\n\/\/ RUN_EM_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, niter, sample, error_mode)\n\/\/ RUN_EM_INFERENCE(string(\"vdj\"), cloneset_vdj, vdj_single_model, niter, sample, error_mode)\n\/\/ for(auto val_sample: vec_sample) {\n\/\/ RUN_EM_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, 40, val_sample, error_mode)\n\/\/ }\n\n\/\/ ModelParameterVector new_param_vec = vj_single_model.event_probabilities();\n\/\/ new_param_vec.fill(1);\n\/\/ new_param_vec.normaliseEventFamilies();\n\/\/ vj_single_model.updateModelParameterVector(new_param_vec);\n\/\/\n\/\/ auto rep_nonc = cloneset_vj.noncoding().sample(2500);\n\/\/ auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true);\n\/\/ vector<prob_t> prob_vec(maag_rep.size(), 0);\n\/\/\n\/\/ vector<bool> good_clonotypes(maag_rep.size(), true);\n\/\/ for (size_t i = 0; i < maag_rep.size(); ++i) {\n\/\/ if (rep_nonc[i].is_good()) {\n\/\/ prob_vec[i] = maag_rep[i].fullProbability();\n\/\/ if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) {\n\/\/ good_clonotypes[i] = false;\n\/\/ }\n\/\/ } else {\n\/\/ good_clonotypes[i] = false;\n\/\/ }\n\/\/ }\n\n for(auto val_sample: vec_sample) {\n for(auto val_block: vec_block) {\n for (auto val_alpha: vec_alpha) {\n for (auto val_beta: vec_beta) {\n for (auto val_K: vec_K) {\n RUN_SG_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)\n }\n }\n }\n }\n }\n\n}\n<commit_msg>debug<commit_after>\/\/\n\/\/ Created by Vadim N. on 16\/03\/2016.\n\/\/\n\n#include \"benchutils.h\"\n\nint main(int argc, char* argv[]) {\n\n if (argc < 2) {\n std::cout << \"Please re-run the script with the data folder path supplied.\" << std::endl;\n return 1;\n }\n\n std::chrono::system_clock::time_point tp1, tp2;\n\n std::vector< std::pair<std::string, size_t> > timepoints;\n\n std::vector<prob_t> logLvec;\n\n std::string temp_str;\n\n \/\/ time_t vj_single_parse, vdj_single_parse,\n \/\/ vj_single_prob, vj_single_meta,\n \/\/ vj_single_infer, vdj_single_prob,\n \/\/ vdj_single_meta, vdj_single_infer;\n\n \/\/ time_t vj_good_parse, vdj_good_parse,\n \/\/ vj_good_prob, vj_good_meta,\n \/\/ vj_good_infer, vdj_good_prob,\n \/\/ vdj_good_meta, vdj_good_infer;\n\n std::string BENCH_DATA_FOLDER = argv[1];\n\n std::cout << \"Data folder:\\t[\" << BENCH_DATA_FOLDER << \"]\" << endl;\n\n\n \/\/\n \/\/ TCR alpha chain repertoire - VJ recombination\n \/\/\n VDJRecombinationGenes vj_single_genes(\"Vgene\",\n BENCH_DATA_FOLDER + \"trav.txt\",\n \"Jgene\",\n BENCH_DATA_FOLDER + \"traj.txt\");\n\n\n VDJRecombinationGenes vj_single_genes2;\n vj_single_genes2 = vj_single_genes;\n\n\n string input_alpha_file = \"alpha.250k.txt\";\n string input_beta_file = \"beta.250k.txt\";\n\n CDR3NucParser parser;\n Cloneset cloneset_vj;\n\n YMIR_BENCHMARK(\"Parsing VJ\",\n parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,\n &cloneset_vj,\n vj_single_genes,\n NUCLEOTIDE,\n VJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE),\n VDJAlignerParameters(2)))\n\n \/\/\n \/\/ TCR beta chain repertoire - VDJ recombination\n \/\/\n\/\/ VDJRecombinationGenes vdj_single_genes(\"Vgene\",\n\/\/ BENCH_DATA_FOLDER + \"trbv.txt\",\n\/\/ \"Jgene\",\n\/\/ BENCH_DATA_FOLDER + \"trbj.txt\",\n\/\/ \"Dgene\",\n\/\/ BENCH_DATA_FOLDER + \"trbd.txt\");\n\/\/\n\/\/ Cloneset cloneset_vdj;\n\/\/ YMIR_BENCHMARK(\"Parsing VDJ\",\n\/\/ parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,\n\/\/ &cloneset_vdj,\n\/\/ vdj_single_genes,\n\/\/ NUCLEOTIDE,\n\/\/ VDJ_RECOMB,\n\/\/ AlignmentColumnOptions()\n\/\/ .setV(AlignmentColumnOptions::USE_PROVIDED)\n\/\/ .setD(AlignmentColumnOptions::OVERWRITE)\n\/\/ .setJ(AlignmentColumnOptions::USE_PROVIDED),\n\/\/ VDJAlignerParameters(3)))\n\n \/\/\n \/\/ VJ MAAG\n \/\/\n ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRA\", EMPTY);\n\n \/\/\n \/\/ VDJ MAAG\n \/\/\n\/\/ ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRB\", EMPTY);\n\n\n \/\/\n \/\/ Inference\n \/\/\n vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000};\n vec_sample = { 100000 };\n vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; \/\/, 2000, 5000, 10000};\n\/\/ vec_block = {2000, 5000, 10000};\n vec_block = { std::stoi(argv[2]) };\n vector<double> vec_alpha = {.5, .6, .7, .8, .9};\n vec_alpha = { std::stof(argv[3]) };\n vector<double> vec_beta = {.1, .5, 1, 3};\n vec_beta = { std::stof(argv[4]) };\n vector<double> vec_K = {1, 2, 3};\n vec_K = { std::stod(argv[5]) };\n ErrorMode error_mode = COMPUTE_ERRORS;\n\n\/\/ int niter, sample, block;\n\/\/ double alpha;\n\/\/ niter = 10;\n\/\/ int sample = 10000;\n\n\/\/ RUN_EM_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, niter, sample, error_mode)\n\/\/ RUN_EM_INFERENCE(string(\"vdj\"), cloneset_vdj, vdj_single_model, niter, sample, error_mode)\n\/\/ for(auto val_sample: vec_sample) {\n\/\/ RUN_EM_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, 40, val_sample, error_mode)\n\/\/ }\n\n\/\/ ModelParameterVector new_param_vec = vj_single_model.event_probabilities();\n\/\/ new_param_vec.fill(1);\n\/\/ new_param_vec.normaliseEventFamilies();\n\/\/ vj_single_model.updateModelParameterVector(new_param_vec);\n\/\/\n\/\/ auto rep_nonc = cloneset_vj.noncoding().sample(2500);\n\/\/ auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true);\n\/\/ vector<prob_t> prob_vec(maag_rep.size(), 0);\n\/\/\n\/\/ vector<bool> good_clonotypes(maag_rep.size(), true);\n\/\/ for (size_t i = 0; i < maag_rep.size(); ++i) {\n\/\/ if (rep_nonc[i].is_good()) {\n\/\/ prob_vec[i] = maag_rep[i].fullProbability();\n\/\/ if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) {\n\/\/ good_clonotypes[i] = false;\n\/\/ }\n\/\/ } else {\n\/\/ good_clonotypes[i] = false;\n\/\/ }\n\/\/ }\n\n for(auto val_sample: vec_sample) {\n for(auto val_block: vec_block) {\n for (auto val_alpha: vec_alpha) {\n for (auto val_beta: vec_beta) {\n for (auto val_K: vec_K) {\n RUN_SG_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)\n }\n }\n }\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <jios\/istream_ij.hpp>\n\n#include <boost\/throw_exception.hpp>\n#include <boost\/core\/null_deleter.hpp>\n\nusing namespace std;\n\nnamespace jios {\n\n\n\/\/ istream_facade\n\nistream_facade::istream_facade(shared_ptr<istream> const& p_is)\n : p_is_(p_is)\n , buf_(4096)\n , bytes_avail_(0)\n{\n if (!p_is_) {\n BOOST_THROW_EXCEPTION(bad_alloc());\n }\n}\n\nistream_facade::istream_facade(istream & is)\n : p_is_(&is, boost::null_deleter())\n , buf_(4096)\n , bytes_avail_(0)\n{\n}\n\nstreamsize istream_facade::avail()\n{\n if (!bytes_avail_ && p_is_->good()) {\n bytes_avail_ = p_is_->readsome(buf_.data(), buf_.size());\n }\n return bytes_avail_;\n}\n\nvoid istream_facade::eat_whitespace()\n{\n istream & is = *p_is_;\n if (!bytes_avail_ && is.good()) {\n bytes_avail_ = is.readsome(buf_.data(), buf_.size());\n }\n char const* it = buf_.data();\n while (bytes_avail_ > 0 && ::isspace(*it)) {\n ++it;\n --bytes_avail_;\n if (!bytes_avail_ && is.good()) {\n bytes_avail_ = is.readsome(buf_.data(), buf_.size());\n it = buf_.data();\n }\n }\n if (bytes_avail_ > 0 && it != buf_.data()) {\n copy(it, it + bytes_avail_, buf_.data());\n }\n}\n\nvoid istream_facade::remove(streamsize n)\n{\n BOOST_ASSERT( n <= bytes_avail_ );\n if (n > bytes_avail_) { n = bytes_avail_; }\n bytes_avail_ -= n;\n if (bytes_avail_ > 0) {\n char const* rest = buf_.data() + n;\n copy(rest, rest + bytes_avail_, buf_.data());\n }\n}\n\nvoid istream_facade::remove_until(const char * it)\n{\n remove(it - buf_.data());\n}\n\n\/\/ istream_ijsource\n\nclass istream_ijsource : public ijsource\n{\npublic:\n istream_ijsource(shared_ptr<istream_facade> const& p_is,\n shared_ptr<istream_parser> const& p_p)\n : p_is_(p_is)\n , p_parser_(p_p)\n {\n if (!p_is_ || !p_parser_) {\n BOOST_THROW_EXCEPTION(bad_alloc());\n }\n }\n\nprivate:\n void induce();\n\n ijstate & do_state() override { return *p_is_; }\n ijstate const& do_state() const override { return *p_is_; }\n\n ijpair & do_ref() override { induce(); return p_parser_->result(); }\n\n bool do_is_terminator() override { induce(); return !p_parser_->is_parsed(); }\n\n void do_advance() override { induce(); p_parser_->clear(); }\n\n bool do_expecting() override;\n\n shared_ptr<istream_facade> p_is_;\n shared_ptr<istream_parser> p_parser_;\n};\n\nvoid istream_ijsource::induce()\n{\n while (this->expecting()) {\n p_is_->peek();\n }\n}\n\nbool istream_ijsource::do_expecting()\n{\n p_parser_->parse(p_is_);\n return !p_parser_->is_parsed() && p_is_->good();\n}\n\nshared_ptr<ijsource>\n make_stream_ijsource(shared_ptr<istream_facade> const& p_is,\n shared_ptr<istream_parser> const& p_p)\n{\n return make_shared<istream_ijsource>(p_is, p_p);\n}\n\n\/\/ streaming_node \n\nclass streaming_node : public ijpair\n{\npublic:\n streaming_node(shared_ptr<istream_facade> const& p_is,\n shared_ptr<istream_parser> const& p_p)\n : p_is_(p_is)\n , p_parser_(p_p)\n {\n if (!p_is_ || !p_parser_) {\n BOOST_THROW_EXCEPTION(bad_alloc());\n }\n }\n\nprivate:\n ijstate & do_state() override { return *p_is_; }\n ijstate const& do_state() const override { return *p_is_; }\n\n json_type do_type() const override { return json_type::jarray; }\n\n void do_parse(int64_t &) override { failout(); }\n void do_parse(double &) override { failout(); }\n void do_parse(bool &) override { failout(); }\n void do_parse(std::string &) override { failout(); }\n void do_parse(buffer_iterator) override { failout(); }\n\n ijarray do_begin_array() override;\n ijobject do_begin_object() { failout(); return ijobject(); }\n\n std::string do_key() const { BOOST_ASSERT(false); return \"\"; }\n\n void failout() { this->set_failbit(); }\n\n shared_ptr<istream_facade> p_is_;\npublic:\n shared_ptr<istream_parser> p_parser_;\n};\n\nijarray streaming_node::do_begin_array()\n{\n return p_parser_->result().array();\n}\n\n\/\/ streaming_parser\n\nclass streaming_parser : public istream_parser\n{\npublic:\n streaming_parser(shared_ptr<istream_facade> const& p_is,\n istream_parser_factory const& fallback)\n : node_(p_is, factory(p_is))\n {}\n\nprivate:\n void do_clear() override;\n void do_parse(std::shared_ptr<istream_facade> const& p_is) override;\n bool do_is_parsed() const override;\n ijpair & do_result() override;\n\n streaming_node node_;\n};\n\nvoid streaming_parser::do_clear()\n{\n node_.p_parser_->clear();\n}\n\nvoid streaming_parser::do_parse(std::shared_ptr<istream_facade> const& p_is)\n{\n node_.p_parser_->parse(p_is);\n}\n\nbool streaming_parser::do_is_parsed() const\n{\n return node_.p_parser_->is_parsed();\n}\n\nijpair & streaming_parser::do_result()\n{\n return node_;\n}\n\nshared_ptr<istream_parser>\n make_streaming_parser(shared_ptr<istream_facade> const& p_is,\n istream_parser_factory const& fallback)\n{\n return make_shared<streaming_parser>(p_is, fallback);\n}\n\n\n} \/\/ namespace\n\n<commit_msg>missing modifications<commit_after>#include <jios\/istream_ij.hpp>\n\n#include <boost\/throw_exception.hpp>\n#include <boost\/core\/null_deleter.hpp>\n\nusing namespace std;\n\nnamespace jios {\n\n\n\/\/ istream_facade\n\nistream_facade::istream_facade(shared_ptr<istream> const& p_is)\n : p_is_(p_is)\n , buf_(4096)\n , bytes_avail_(0)\n{\n if (!p_is_) {\n BOOST_THROW_EXCEPTION(bad_alloc());\n }\n}\n\nistream_facade::istream_facade(istream & is)\n : p_is_(&is, boost::null_deleter())\n , buf_(4096)\n , bytes_avail_(0)\n{\n}\n\nstreamsize istream_facade::avail()\n{\n if (!bytes_avail_ && p_is_->good()) {\n bytes_avail_ = p_is_->readsome(buf_.data(), buf_.size());\n }\n return bytes_avail_;\n}\n\nvoid istream_facade::eat_whitespace()\n{\n istream & is = *p_is_;\n if (!bytes_avail_ && is.good()) {\n bytes_avail_ = is.readsome(buf_.data(), buf_.size());\n }\n char const* it = buf_.data();\n while (bytes_avail_ > 0 && ::isspace(*it)) {\n ++it;\n --bytes_avail_;\n if (!bytes_avail_ && is.good()) {\n bytes_avail_ = is.readsome(buf_.data(), buf_.size());\n it = buf_.data();\n }\n }\n if (bytes_avail_ > 0 && it != buf_.data()) {\n copy(it, it + bytes_avail_, buf_.data());\n }\n}\n\nvoid istream_facade::remove(streamsize n)\n{\n BOOST_ASSERT( n <= bytes_avail_ );\n if (n > bytes_avail_) { n = bytes_avail_; }\n bytes_avail_ -= n;\n if (bytes_avail_ > 0) {\n char const* rest = buf_.data() + n;\n copy(rest, rest + bytes_avail_, buf_.data());\n }\n}\n\nvoid istream_facade::remove_until(const char * it)\n{\n remove(it - buf_.data());\n}\n\n\/\/ istream_ijsource\n\nclass istream_ijsource : public ijsource\n{\npublic:\n istream_ijsource(shared_ptr<istream_facade> const& p_is,\n shared_ptr<istream_parser> const& p_p)\n : p_is_(p_is)\n , p_parser_(p_p)\n {\n if (!p_is_ || !p_parser_) {\n BOOST_THROW_EXCEPTION(bad_alloc());\n }\n }\n\nprivate:\n void induce();\n\n ijstate & do_state() override { return *p_is_; }\n ijstate const& do_state() const override { return *p_is_; }\n\n ijpair & do_ref() override { induce(); return p_parser_->result(); }\n\n bool do_is_terminator() override { induce(); return !p_parser_->is_parsed(); }\n\n void do_advance() override { induce(); p_parser_->clear(); }\n\n bool do_expecting() override;\n\n shared_ptr<istream_facade> p_is_;\n shared_ptr<istream_parser> p_parser_;\n};\n\nvoid istream_ijsource::induce()\n{\n while (this->expecting()) {\n p_is_->peek();\n }\n}\n\nbool istream_ijsource::do_expecting()\n{\n p_parser_->parse(p_is_);\n return !p_parser_->is_parsed() && p_is_->good();\n}\n\nshared_ptr<ijsource>\n make_stream_ijsource(shared_ptr<istream_facade> const& p_is,\n shared_ptr<istream_parser> const& p_p)\n{\n return make_shared<istream_ijsource>(p_is, p_p);\n}\n\n\/\/ streaming_node \n\nclass streaming_node : public ijpair\n{\npublic:\n streaming_node(shared_ptr<istream_facade> const& p_is,\n shared_ptr<istream_parser> const& p_p)\n : p_is_(p_is)\n , p_parser_(p_p)\n {\n if (!p_is_ || !p_parser_) {\n BOOST_THROW_EXCEPTION(bad_alloc());\n }\n }\n\nprivate:\n ijstate & do_state() override { return *p_is_; }\n ijstate const& do_state() const override { return *p_is_; }\n\n json_type do_type() const override { return json_type::jarray; }\n\n void do_parse(int64_t &) override { failout(); }\n void do_parse(double &) override { failout(); }\n void do_parse(bool &) override { failout(); }\n void do_parse(std::string &) override { failout(); }\n void do_parse(buffer_iterator) override { failout(); }\n\n ijarray do_begin_array() override;\n ijobject do_begin_object() { failout(); return ijobject(); }\n\n std::string do_key() const { BOOST_ASSERT(false); return \"\"; }\n\n void failout() { this->set_failbit(); }\n\n shared_ptr<istream_facade> p_is_;\npublic:\n shared_ptr<istream_parser> p_parser_;\n};\n\nijarray streaming_node::do_begin_array()\n{\n return p_parser_->result().array();\n}\n\n\/\/ streaming_parser\n\nclass streaming_parser : public istream_parser\n{\npublic:\n streaming_parser(shared_ptr<istream_facade> const& p_is,\n istream_parser_factory const& fallback)\n : node_(p_is, fallback(p_is))\n {}\n\nprivate:\n void do_clear() override;\n void do_parse(std::shared_ptr<istream_facade> const& p_is) override;\n bool do_is_parsed() const override;\n ijpair & do_result() override;\n\n streaming_node node_;\n};\n\nvoid streaming_parser::do_clear()\n{\n node_.p_parser_->clear();\n}\n\nvoid streaming_parser::do_parse(std::shared_ptr<istream_facade> const& p_is)\n{\n node_.p_parser_->parse(p_is);\n}\n\nbool streaming_parser::do_is_parsed() const\n{\n return node_.p_parser_->is_parsed();\n}\n\nijpair & streaming_parser::do_result()\n{\n return node_;\n}\n\nshared_ptr<istream_parser>\n make_streaming_parser(shared_ptr<istream_facade> const& p_is,\n istream_parser_factory const& fallback)\n{\n return make_shared<streaming_parser>(p_is, fallback);\n}\n\n\n} \/\/ namespace\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 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 \"base\/message_pump_libevent.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n\n#include \"base\/logging.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/time.h\"\n#include \"third_party\/libevent\/event.h\"\n\nnamespace base {\n\n\/\/ Return 0 on success\n\/\/ Too small a function to bother putting in a library?\nstatic int SetNonBlocking(int fd) {\n int flags = fcntl(fd, F_GETFL, 0);\n if (flags == -1)\n flags = 0;\n return fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n}\n\nMessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()\n : is_persistent_(false),\n event_(NULL) {\n}\n\nMessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {\n if (event_.get()) {\n StopWatchingFileDescriptor();\n }\n}\n\nvoid MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,\n bool is_persistent) {\n DCHECK(e);\n DCHECK(event_.get() == NULL);\n\n is_persistent_ = is_persistent;\n event_.reset(e);\n}\n\nevent *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {\n return event_.release();\n}\n\nbool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {\n if (event_.get() == NULL) {\n return true;\n }\n\n \/\/ event_del() is a no-op of the event isn't active.\n return (event_del(event_.get()) == 0);\n}\n\n\/\/ Called if a byte is received on the wakeup pipe.\nvoid MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {\n base::MessagePumpLibevent* that =\n static_cast<base::MessagePumpLibevent*>(context);\n DCHECK(that->wakeup_pipe_out_ == socket);\n\n \/\/ Remove and discard the wakeup byte.\n char buf;\n int nread = read(socket, &buf, 1);\n DCHECK(nread == 1);\n \/\/ Tell libevent to break out of inner loop.\n event_base_loopbreak(that->event_base_);\n}\n\nMessagePumpLibevent::MessagePumpLibevent()\n : keep_running_(true),\n in_run_(false),\n event_base_(event_base_new()),\n wakeup_pipe_in_(-1),\n wakeup_pipe_out_(-1) {\n if (!Init())\n NOTREACHED();\n}\n\nbool MessagePumpLibevent::Init() {\n int fds[2];\n if (pipe(fds)) {\n DLOG(ERROR) << \"pipe() failed, errno: \" << errno;\n return false;\n }\n if (SetNonBlocking(fds[0])) {\n DLOG(ERROR) << \"SetNonBlocking for pipe fd[0] failed, errno: \" << errno;\n return false;\n }\n if (SetNonBlocking(fds[1])) {\n DLOG(ERROR) << \"SetNonBlocking for pipe fd[1] failed, errno: \" << errno;\n return false;\n }\n wakeup_pipe_out_ = fds[0];\n wakeup_pipe_in_ = fds[1];\n\n wakeup_event_ = new event;\n event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,\n OnWakeup, this);\n event_base_set(event_base_, wakeup_event_);\n\n if (event_add(wakeup_event_, 0))\n return false;\n return true;\n}\n\nMessagePumpLibevent::~MessagePumpLibevent() {\n DCHECK(wakeup_event_);\n DCHECK(event_base_);\n event_del(wakeup_event_);\n delete wakeup_event_;\n if (wakeup_pipe_in_ >= 0)\n close(wakeup_pipe_in_);\n if (wakeup_pipe_out_ >= 0)\n close(wakeup_pipe_out_);\n event_base_free(event_base_);\n}\n\nbool MessagePumpLibevent::WatchFileDescriptor(int fd,\n bool persistent,\n Mode mode,\n FileDescriptorWatcher *controller,\n Watcher *delegate) {\n DCHECK(fd > 0);\n DCHECK(controller);\n DCHECK(delegate);\n DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);\n\n int event_mask = persistent ? EV_PERSIST : 0;\n if ((mode & WATCH_READ) != 0) {\n event_mask |= EV_READ;\n }\n if ((mode & WATCH_WRITE) != 0) {\n event_mask |= EV_WRITE;\n }\n\n \/\/ |should_delete_event| is true if we're modifying an event that's currently\n \/\/ active in |controller|.\n \/\/ If we're modifying an existing event and there's an error then we need to\n \/\/ tell libevent to clean it up via event_delete() before returning.\n bool should_delete_event = true;\n scoped_ptr<event> evt(controller->ReleaseEvent());\n if (evt.get() == NULL) {\n should_delete_event = false;\n \/\/ Ownership is transferred to the controller.\n evt.reset(new event);\n }\n\n \/\/ Set current interest mask and message pump for this event.\n event_set(evt.get(), fd, event_mask, OnLibeventNotification,\n delegate);\n\n \/\/ Tell libevent which message pump this socket will belong to when we add it.\n if (event_base_set(event_base_, evt.get()) != 0) {\n if (should_delete_event) {\n event_del(evt.get());\n }\n return false;\n }\n\n \/\/ Add this socket to the list of monitored sockets.\n if (event_add(evt.get(), NULL) != 0) {\n if (should_delete_event) {\n event_del(evt.get());\n }\n return false;\n }\n\n \/\/ Transfer ownership of e to controller.\n controller->Init(evt.release(), persistent);\n return true;\n}\n\n\nvoid MessagePumpLibevent::OnLibeventNotification(int fd, short flags,\n void* context) {\n Watcher* watcher = static_cast<Watcher*>(context);\n\n if (flags & EV_WRITE) {\n watcher->OnFileCanWriteWithoutBlocking(fd);\n }\n if (flags & EV_READ) {\n watcher->OnFileCanReadWithoutBlocking(fd);\n }\n}\n\n\/\/ Reentrant!\nvoid MessagePumpLibevent::Run(Delegate* delegate) {\n DCHECK(keep_running_) << \"Quit must have been called outside of Run!\";\n\n bool old_in_run = in_run_;\n in_run_ = true;\n\n for (;;) {\n ScopedNSAutoreleasePool autorelease_pool;\n\n bool did_work = delegate->DoWork();\n if (!keep_running_)\n break;\n\n did_work |= delegate->DoDelayedWork(&delayed_work_time_);\n if (!keep_running_)\n break;\n\n if (did_work)\n continue;\n\n did_work = delegate->DoIdleWork();\n if (!keep_running_)\n break;\n\n if (did_work)\n continue;\n\n \/\/ EVLOOP_ONCE tells libevent to only block once,\n \/\/ but to service all pending events when it wakes up.\n if (delayed_work_time_.is_null()) {\n event_base_loop(event_base_, EVLOOP_ONCE);\n } else {\n TimeDelta delay = delayed_work_time_ - Time::Now();\n if (delay > TimeDelta()) {\n struct timeval poll_tv;\n poll_tv.tv_sec = delay.InSeconds();\n poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;\n event_base_loopexit(event_base_, &poll_tv);\n event_base_loop(event_base_, EVLOOP_ONCE);\n } else {\n \/\/ It looks like delayed_work_time_ indicates a time in the past, so we\n \/\/ need to call DoDelayedWork now.\n delayed_work_time_ = Time();\n }\n }\n }\n\n keep_running_ = true;\n in_run_ = old_in_run;\n}\n\nvoid MessagePumpLibevent::Quit() {\n DCHECK(in_run_);\n \/\/ Tell both libevent and Run that they should break out of their loops.\n keep_running_ = false;\n ScheduleWork();\n}\n\nvoid MessagePumpLibevent::ScheduleWork() {\n \/\/ Tell libevent (in a threadsafe way) that it should break out of its loop.\n char buf = 0;\n int nwrite = write(wakeup_pipe_in_, &buf, 1);\n DCHECK(nwrite == 1);\n}\n\nvoid MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {\n \/\/ We know that we can't be blocked on Wait right now since this method can\n \/\/ only be called on the same thread as Run, so we only need to update our\n \/\/ record of how long to sleep when we do sleep.\n delayed_work_time_ = delayed_work_time;\n}\n\n} \/\/ namespace base\n<commit_msg>Minor DCHECK cleanups in libevent. DCHECK=>DCHECK_EQ where possible. Change a DCHECK not to fire on write() returning -1 && errno==EAGAIN, since this happens normally under heavy load. Review URL: http:\/\/codereview.chromium.org\/42295<commit_after>\/\/ Copyright (c) 2008 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 \"base\/message_pump_libevent.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n\n#include \"base\/logging.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/time.h\"\n#include \"third_party\/libevent\/event.h\"\n\nnamespace base {\n\n\/\/ Return 0 on success\n\/\/ Too small a function to bother putting in a library?\nstatic int SetNonBlocking(int fd) {\n int flags = fcntl(fd, F_GETFL, 0);\n if (flags == -1)\n flags = 0;\n return fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n}\n\nMessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()\n : is_persistent_(false),\n event_(NULL) {\n}\n\nMessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {\n if (event_.get()) {\n StopWatchingFileDescriptor();\n }\n}\n\nvoid MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,\n bool is_persistent) {\n DCHECK(e);\n DCHECK(event_.get() == NULL);\n\n is_persistent_ = is_persistent;\n event_.reset(e);\n}\n\nevent *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {\n return event_.release();\n}\n\nbool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {\n if (event_.get() == NULL) {\n return true;\n }\n\n \/\/ event_del() is a no-op of the event isn't active.\n return (event_del(event_.get()) == 0);\n}\n\n\/\/ Called if a byte is received on the wakeup pipe.\nvoid MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {\n base::MessagePumpLibevent* that =\n static_cast<base::MessagePumpLibevent*>(context);\n DCHECK(that->wakeup_pipe_out_ == socket);\n\n \/\/ Remove and discard the wakeup byte.\n char buf;\n int nread = read(socket, &buf, 1);\n DCHECK_EQ(nread, 1);\n \/\/ Tell libevent to break out of inner loop.\n event_base_loopbreak(that->event_base_);\n}\n\nMessagePumpLibevent::MessagePumpLibevent()\n : keep_running_(true),\n in_run_(false),\n event_base_(event_base_new()),\n wakeup_pipe_in_(-1),\n wakeup_pipe_out_(-1) {\n if (!Init())\n NOTREACHED();\n}\n\nbool MessagePumpLibevent::Init() {\n int fds[2];\n if (pipe(fds)) {\n DLOG(ERROR) << \"pipe() failed, errno: \" << errno;\n return false;\n }\n if (SetNonBlocking(fds[0])) {\n DLOG(ERROR) << \"SetNonBlocking for pipe fd[0] failed, errno: \" << errno;\n return false;\n }\n if (SetNonBlocking(fds[1])) {\n DLOG(ERROR) << \"SetNonBlocking for pipe fd[1] failed, errno: \" << errno;\n return false;\n }\n wakeup_pipe_out_ = fds[0];\n wakeup_pipe_in_ = fds[1];\n\n wakeup_event_ = new event;\n event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,\n OnWakeup, this);\n event_base_set(event_base_, wakeup_event_);\n\n if (event_add(wakeup_event_, 0))\n return false;\n return true;\n}\n\nMessagePumpLibevent::~MessagePumpLibevent() {\n DCHECK(wakeup_event_);\n DCHECK(event_base_);\n event_del(wakeup_event_);\n delete wakeup_event_;\n if (wakeup_pipe_in_ >= 0)\n close(wakeup_pipe_in_);\n if (wakeup_pipe_out_ >= 0)\n close(wakeup_pipe_out_);\n event_base_free(event_base_);\n}\n\nbool MessagePumpLibevent::WatchFileDescriptor(int fd,\n bool persistent,\n Mode mode,\n FileDescriptorWatcher *controller,\n Watcher *delegate) {\n DCHECK(fd > 0);\n DCHECK(controller);\n DCHECK(delegate);\n DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);\n\n int event_mask = persistent ? EV_PERSIST : 0;\n if ((mode & WATCH_READ) != 0) {\n event_mask |= EV_READ;\n }\n if ((mode & WATCH_WRITE) != 0) {\n event_mask |= EV_WRITE;\n }\n\n \/\/ |should_delete_event| is true if we're modifying an event that's currently\n \/\/ active in |controller|.\n \/\/ If we're modifying an existing event and there's an error then we need to\n \/\/ tell libevent to clean it up via event_delete() before returning.\n bool should_delete_event = true;\n scoped_ptr<event> evt(controller->ReleaseEvent());\n if (evt.get() == NULL) {\n should_delete_event = false;\n \/\/ Ownership is transferred to the controller.\n evt.reset(new event);\n }\n\n \/\/ Set current interest mask and message pump for this event.\n event_set(evt.get(), fd, event_mask, OnLibeventNotification,\n delegate);\n\n \/\/ Tell libevent which message pump this socket will belong to when we add it.\n if (event_base_set(event_base_, evt.get()) != 0) {\n if (should_delete_event) {\n event_del(evt.get());\n }\n return false;\n }\n\n \/\/ Add this socket to the list of monitored sockets.\n if (event_add(evt.get(), NULL) != 0) {\n if (should_delete_event) {\n event_del(evt.get());\n }\n return false;\n }\n\n \/\/ Transfer ownership of e to controller.\n controller->Init(evt.release(), persistent);\n return true;\n}\n\n\nvoid MessagePumpLibevent::OnLibeventNotification(int fd, short flags,\n void* context) {\n Watcher* watcher = static_cast<Watcher*>(context);\n\n if (flags & EV_WRITE) {\n watcher->OnFileCanWriteWithoutBlocking(fd);\n }\n if (flags & EV_READ) {\n watcher->OnFileCanReadWithoutBlocking(fd);\n }\n}\n\n\/\/ Reentrant!\nvoid MessagePumpLibevent::Run(Delegate* delegate) {\n DCHECK(keep_running_) << \"Quit must have been called outside of Run!\";\n\n bool old_in_run = in_run_;\n in_run_ = true;\n\n for (;;) {\n ScopedNSAutoreleasePool autorelease_pool;\n\n bool did_work = delegate->DoWork();\n if (!keep_running_)\n break;\n\n did_work |= delegate->DoDelayedWork(&delayed_work_time_);\n if (!keep_running_)\n break;\n\n if (did_work)\n continue;\n\n did_work = delegate->DoIdleWork();\n if (!keep_running_)\n break;\n\n if (did_work)\n continue;\n\n \/\/ EVLOOP_ONCE tells libevent to only block once,\n \/\/ but to service all pending events when it wakes up.\n if (delayed_work_time_.is_null()) {\n event_base_loop(event_base_, EVLOOP_ONCE);\n } else {\n TimeDelta delay = delayed_work_time_ - Time::Now();\n if (delay > TimeDelta()) {\n struct timeval poll_tv;\n poll_tv.tv_sec = delay.InSeconds();\n poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;\n event_base_loopexit(event_base_, &poll_tv);\n event_base_loop(event_base_, EVLOOP_ONCE);\n } else {\n \/\/ It looks like delayed_work_time_ indicates a time in the past, so we\n \/\/ need to call DoDelayedWork now.\n delayed_work_time_ = Time();\n }\n }\n }\n\n keep_running_ = true;\n in_run_ = old_in_run;\n}\n\nvoid MessagePumpLibevent::Quit() {\n DCHECK(in_run_);\n \/\/ Tell both libevent and Run that they should break out of their loops.\n keep_running_ = false;\n ScheduleWork();\n}\n\nvoid MessagePumpLibevent::ScheduleWork() {\n \/\/ Tell libevent (in a threadsafe way) that it should break out of its loop.\n char buf = 0;\n int nwrite = write(wakeup_pipe_in_, &buf, 1);\n DCHECK(nwrite == 1 || errno == EAGAIN)\n << \"[nwrite:\" << nwrite << \"] [errno:\" << errno << \"]\";\n}\n\nvoid MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {\n \/\/ We know that we can't be blocked on Wait right now since this method can\n \/\/ only be called on the same thread as Run, so we only need to update our\n \/\/ record of how long to sleep when we do sleep.\n delayed_work_time_ = delayed_work_time;\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2014 Rapptz\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\n\/\/ subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ 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, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef JSONPP_PARSER_HPP\n#define JSONPP_PARSER_HPP\n\n#include \"error.hpp\"\n#include \"value.hpp\"\n#include <cstring>\n#include <iosfwd>\n\nnamespace json {\ninline namespace v1 {\nstruct parser {\nprivate:\n unsigned line = 1;\n unsigned column = 1;\n\n const char* skip_white_space(const char* str) {\n while(*str && isspace(*str)) {\n ++str;\n ++column;\n if(*str == '\\n') {\n ++line;\n column = 0;\n }\n }\n return str;\n }\n\n const char* parse_value(const char* str, value& v) {\n const char* s = skip_white_space(str);\n if(!s) {\n throw parser_error(\"unexpected EOF found\", line, column);\n }\n\n if(isdigit(*s) || *s == '+' || *s == '-') {\n s = parse_number(s, v);\n }\n else {\n switch(*s) {\n case 'n':\n s = parse_null(s, v);\n break;\n case '\"':\n s = parse_string(s, v);\n break;\n case 't':\n case 'f':\n s = parse_bool(s, v);\n break;\n case '[':\n s = parse_array(s, v);\n break;\n case '{':\n s = parse_object(s, v);\n break;\n }\n }\n\n return skip_white_space(s);\n }\n\n const char* parse_null(const char* str, value& v) {\n static const char null_str[] = \"null\";\n if(!str) {\n throw parser_error(\"expected null, received EOF instead\", line, column);\n }\n\n if(std::strncmp(str, null_str, sizeof(null_str) - 1) != 0) {\n throw parser_error(\"expected null not found\", line, column);\n }\n\n v = nullptr;\n str = str + sizeof(null_str) - 1;\n column += sizeof(null_str);\n return str;\n }\n\n const char* parse_number(const char* str, value& v) {\n static const std::string lookup = \"0123456789eE+-.\";\n const char* begin = str;\n if(!begin) {\n throw parser_error(\"expected number, received EOF instead\", line, column);\n }\n\n while(lookup.find(*str) != std::string::npos) {\n ++str;\n }\n\n double val = 0.0;\n try {\n std::string temp(begin, str);\n val = std::stod(temp);\n column += temp.size() + 1;\n }\n catch(const std::exception& e) {\n throw parser_error(\"number could not be parsed properly\", line, column);\n }\n\n v = val;\n return str;\n }\n\n template<typename Value>\n const char* parse_string(const char* str, Value& v) {\n const char* end = str + 1;\n if(!end) {\n throw parser_error(\"expected string, received EOF instead\", line, column);\n }\n\n while(*end && *end != '\"') {\n ++end;\n }\n\n if(!end) {\n throw parser_error(\"unescaped string sequence found\", line, column);\n }\n\n auto&& temp = std::string(str + 1, end);\n column += temp.size() + 1;\n v = temp;\n ++end;\n return end;\n }\n\n const char* parse_bool(const char* str, value& v) {\n if(!str) {\n throw parser_error(\"expected boolean, received EOF instead\", line, column);\n }\n\n bool expected_true = *str == 't';\n const char* boolean = expected_true ? \"true\" : \"false\";\n const size_t len = expected_true ? 4 : 5;\n\n if(std::strncmp(str, boolean, len) != 0) {\n throw parser_error(\"expected boolean not found\", line, column);\n }\n\n v = expected_true;\n str = str + len;\n column += len;\n return str;\n }\n\n const char* parse_array(const char* str, value& v) {\n const char *s = str + 1;\n array arr;\n value elem;\n\n while (*s && *s != ']') {\n s = parse_value(s, elem);\n if(*s != ',') {\n if(*s != ']') {\n throw parser_error(\"missing comma\", line, column);\n }\n }\n else if(*s == ',') {\n ++s;\n }\n\n arr.push_back(elem);\n }\n v = arr;\n return *s == ']' ? s + 1 : s;\n }\n\n const char* parse_object(const char* str, value& v) {\n const char* s = str + 1;\n object obj;\n std::string key;\n value elem;\n\n while(*s && *s != '}') {\n s = skip_white_space(s);\n if(*s != '\"') {\n throw parser_error(\"expected string as key not found\", line, column);\n }\n s = parse_string(s, key);\n s = skip_white_space(s);\n\n if(*s != ':') {\n throw parser_error(\"missing semicolon\", line, column);\n }\n ++s;\n s = parse_value(s, elem);\n\n if(*s != ',') {\n if(*s != '}') {\n throw parser_error(\"missing comma\", line, column);\n }\n }\n ++s;\n obj.emplace(key, elem);\n }\n\n v = obj;\n return *s == '}' ? s + 1 : s;\n }\npublic:\n parser() = default;\n parser(const std::string& str, value& v) {\n parse(str, v);\n }\n\n template<typename IStream, DisableIf<is_string<IStream>> = 0>\n parser(IStream& in, value& v) {\n parse(in, v);\n }\n\n void parse(const std::string& str, value& v) {\n line = 1;\n column = 1;\n parse_value(str.c_str(), v);\n }\n\n template<typename IStream, DisableIf<is_string<IStream>> = 0>\n void parse(IStream& in, value& v) {\n static_assert(std::is_base_of<std::istream, IStream>::value, \"Input stream passed must inherit from std::istream\");\n if(in) {\n in.seekg(0, in.end);\n auto size = in.tellg();\n in.seekg(0, in.beg);\n std::string str;\n str.resize(size);\n in.read(&str[0], size);\n parse(str, v);\n }\n }\n};\n} \/\/ v1\n} \/\/ json\n\n#endif \/\/ JSONPP_PARSER_HPP\n<commit_msg>Fix parsing error with objects. Add unexpected token diagnostics.<commit_after>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2014 Rapptz\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\n\/\/ subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ 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, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef JSONPP_PARSER_HPP\n#define JSONPP_PARSER_HPP\n\n#include \"error.hpp\"\n#include \"value.hpp\"\n#include <cstring>\n#include <iosfwd>\n\nnamespace json {\ninline namespace v1 {\nstruct parser {\nprivate:\n unsigned line = 1;\n unsigned column = 1;\n\n const char* skip_white_space(const char* str) {\n while(*str && isspace(*str)) {\n ++str;\n ++column;\n if(*str == '\\n') {\n ++line;\n column = 0;\n }\n }\n return str;\n }\n\n const char* parse_value(const char* str, value& v) {\n const char* s = skip_white_space(str);\n if(!s) {\n throw parser_error(\"unexpected EOF found\", line, column);\n }\n\n if(isdigit(*s) || *s == '+' || *s == '-') {\n s = parse_number(s, v);\n }\n else {\n switch(*s) {\n case 'n':\n s = parse_null(s, v);\n break;\n case '\"':\n s = parse_string(s, v);\n break;\n case 't':\n case 'f':\n s = parse_bool(s, v);\n break;\n case '[':\n s = parse_array(s, v);\n break;\n case '{':\n s = parse_object(s, v);\n break;\n default:\n throw parser_error(\"unexpected token found\", line, column);\n break;\n }\n }\n\n static const std::string accepted_characters = \",[]{}:\";\n s = skip_white_space(s);\n if(*s && accepted_characters.find(*s) == std::string::npos) {\n throw parser_error(\"unexpected token found\", line, column);\n }\n\n return s;\n }\n\n const char* parse_null(const char* str, value& v) {\n static const char null_str[] = \"null\";\n if(!str) {\n throw parser_error(\"expected null, received EOF instead\", line, column);\n }\n\n if(std::strncmp(str, null_str, sizeof(null_str) - 1) != 0) {\n throw parser_error(\"expected null not found\", line, column);\n }\n\n v = nullptr;\n str = str + sizeof(null_str) - 1;\n column += sizeof(null_str);\n return str;\n }\n\n const char* parse_number(const char* str, value& v) {\n static const std::string lookup = \"0123456789eE+-.\";\n const char* begin = str;\n if(!begin) {\n throw parser_error(\"expected number, received EOF instead\", line, column);\n }\n\n while(lookup.find(*str) != std::string::npos) {\n ++str;\n }\n\n double val = 0.0;\n try {\n std::string temp(begin, str);\n val = std::stod(temp);\n column += temp.size() + 1;\n }\n catch(const std::exception& e) {\n throw parser_error(\"number could not be parsed properly\", line, column);\n }\n\n v = val;\n return str;\n }\n\n template<typename Value>\n const char* parse_string(const char* str, Value& v) {\n const char* end = str + 1;\n if(!end) {\n throw parser_error(\"expected string, received EOF instead\", line, column);\n }\n\n while(*end && *end != '\"') {\n ++end;\n }\n\n if(!end) {\n throw parser_error(\"unescaped string sequence found\", line, column);\n }\n\n auto&& temp = std::string(str + 1, end);\n column += temp.size() + 1;\n v = temp;\n ++end;\n return end;\n }\n\n const char* parse_bool(const char* str, value& v) {\n if(!str) {\n throw parser_error(\"expected boolean, received EOF instead\", line, column);\n }\n\n bool expected_true = *str == 't';\n const char* boolean = expected_true ? \"true\" : \"false\";\n const size_t len = expected_true ? 4 : 5;\n\n if(std::strncmp(str, boolean, len) != 0) {\n throw parser_error(\"expected boolean not found\", line, column);\n }\n\n v = expected_true;\n str = str + len;\n column += len;\n return str;\n }\n\n const char* parse_array(const char* str, value& v) {\n const char *s = str + 1;\n array arr;\n value elem;\n\n while (*s && *s != ']') {\n s = parse_value(s, elem);\n if(*s != ',') {\n if(*s != ']') {\n throw parser_error(\"missing comma\", line, column);\n }\n }\n else if(*s == ',') {\n ++s;\n }\n\n arr.push_back(elem);\n }\n v = arr;\n return *s == ']' ? s + 1 : s;\n }\n\n const char* parse_object(const char* str, value& v) {\n const char* s = str + 1;\n object obj;\n std::string key;\n value elem;\n\n while(*s) {\n s = skip_white_space(s);\n\n \/\/ empty object\n if(*s == '}') {\n break;\n }\n\n if(*s != '\"') {\n throw parser_error(\"expected string as key not found\", line, column);\n }\n s = parse_string(s, key);\n s = skip_white_space(s);\n\n if(*s != ':') {\n throw parser_error(\"missing semicolon\", line, column);\n }\n ++s;\n s = parse_value(s, elem);\n\n if(*s != ',') {\n if(*s != '}') {\n throw parser_error(\"missing comma\", line, column);\n }\n }\n else if(*s == ',') {\n ++s;\n }\n obj.emplace(key, elem);\n }\n\n v = obj;\n return *s == '}' ? s + 1 : s;\n }\npublic:\n parser() = default;\n parser(const std::string& str, value& v) {\n parse(str, v);\n }\n\n template<typename IStream, DisableIf<is_string<IStream>> = 0>\n parser(IStream& in, value& v) {\n parse(in, v);\n }\n\n void parse(const std::string& str, value& v) {\n line = 1;\n column = 1;\n parse_value(str.c_str(), v);\n }\n\n template<typename IStream, DisableIf<is_string<IStream>> = 0>\n void parse(IStream& in, value& v) {\n static_assert(std::is_base_of<std::istream, IStream>::value, \"Input stream passed must inherit from std::istream\");\n if(in) {\n in.seekg(0, in.end);\n auto size = in.tellg();\n in.seekg(0, in.beg);\n std::string str;\n str.resize(size);\n in.read(&str[0], size);\n parse(str, v);\n }\n }\n};\n} \/\/ v1\n} \/\/ json\n\n#endif \/\/ JSONPP_PARSER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/base:$Name: $:$Id: TVirtualViewer3D.cxx,v 1.9 2007\/01\/29 15:10:48 brun Exp $\n\/\/ Author: Olivier Couet 05\/10\/2004\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TVirtualViewer3D \/\/\n\/\/ \/\/\n\/\/ Abstract 3D shapes viewer. The concrete implementations are: \/\/\n\/\/ \/\/\n\/\/ TViewerX3D : X3d viewer \/\/\n\/\/ TGLViewer : OpenGL viewer \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/BEGIN_HTML <!--\n\/* -->\n<h4>3D Viewer Infrastructure Overview<\/h4>\n<p>The 3D Viewer infrastructure consists of:<\/p>\n<ul>\n <li> TVirtualViewer3D interface: An abstract handle to the viewer, allowing\n client to test preferences, add objects, control the viewer via scripting\n (to be added) etc.<\/li>\n <li>TBuffer3D class hierarchy: Used to describe 3D objects\n ("shapes")\n - filled \/added by negotiation with viewer via TVirtualViewer3D.<\/li>\n<\/ul>\n<p>Together these allow clients to publish objects to any one of the 3D viewers\n (currently OpenGL\/x3d,TPad), free of viewer specific drawing code. They allow\n our simple x3d viewer, and considerably more sophisticated OpenGL one to both\n work with both geometry libraries (g3d and geom) efficiently.<\/p>\n<p>Publishing to a viewer consists of the following steps:<\/p>\n<ol>\n <li> Create \/ obtain viewer handle<\/li>\n <li>Begin scene on viewer<\/li>\n <li>Fill mandatory parts of TBuffer3D describing object<\/li>\n <li>Add to viewer<\/li>\n <li>Fill optional parts of TBuffer3D if requested by viewer, and add again<br>\n ... repeat 3\/4\/5\n as required<\/li>\n <li>End scene on viewer<\/li>\n<\/ol>\n<h4>Creating \/ Obtaining Viewer<\/h4>\n<p>Create\/obtain the viewer handle via local\/global pad - the viewer is always\n bound to a TPad object at present [This may be removed as a restriction in\n the future] . You should perform the publishing to the viewer described below\n in the Paint() method of the object you attach to the pad (via Draw())<\/p>\n<pre>TVirtualViewer3D * v = gPad->GetViewer3D("xxxx");<\/pre>\n<p>" xxxx" is viewer type: OpenGL "ogl", X3D "x3d" or\n Pad "pad" (default). The viewer is created via the plugin manager,\n attached to pad, and the interface returned.<\/p>\n<h4> Begin \/ End Scene<\/h4>\n<p>Objects must be added to viewer between BeginScene\/EndScene calls e.g.<\/p>\n<pre>v->BeginScene();\n.....\nv->AddObject(....);\nv->AddObject(....);\n.....\nv->EndScene();<\/pre>\n<p>The BeginScene call will cause the viewer to suspend redraws etc, and after\n the EndScene the viewer will reset the camera to frame the new scene and redraw.<\/p>\n[x3d viewer does not support changing of scenes - objects added after the\n first Open\/CloseScene pair will be ignored.]<br>\n<h4>Filling TBuffer3D and Adding to Viewer<\/h4>\n<p>The viewers behind the TVirtualViewer3D interface differ greatly in their\n capabilities e.g.<\/p>\n<ul>\n <li> Some know how to draw certain shapes natively (e.g. spheres\/tubes in\n OpenGL) - others always require a raw tessellation description of points\/lines\/segments.<\/li>\n <li>Some\n need the 3D object positions in the global frame, others can cope with\n local frames + a translation matrix - which can give considerable performance\n benefits.<\/li>\n<\/ul>\n<p>To cope with these situations the object buffer is filled out in negotiation\n with the viewer. TBuffer3D classes are conceptually divided into enumerated\n sections Core, BoundingBox, Raw etc (see TBuffer3D.h for more details). <\/p>\n<p align=\"center\"><img src=\"gif\/TBuffer3D.gif\" width=\"501\" height=\"501\"><\/p>\n<p>The<em> SectionsValid() \/ SetSectionsValid \/ ClearSectionsValid() <\/em>methods of TBuffer3D\n are used to test\/set\/clear these section valid flags.<\/p>\n<p>The sections found in TBuffer3D (<em>Core\/BoundingBox\/Raw Sizes\/Raw<\/em>)\n are sufficient to describe any tessellated shape in a generic fashion. An additional <em>ShapeSpecific<\/em> section\n in derived shape specific classes allows a more abstract shape description\n ("a sphere of inner radius x, outer radius y"). This enables a viewer\n which knows how to draw (tessellate) the shape itself to do so, which can bring\n considerable performance and quality benefits, while providing a generic fallback\n suitable for all viewers.<\/p>\n<p>The rules for client negotiation with the viewer are:<\/p>\n<ul>\n <li> If suitable specialized TBuffer3D class exists, use it, otherwise use\n TBuffer3D.<\/li>\n <li>Complete the mandatory Core section.<\/li>\n <li>Complete the ShapeSpecific section\n if applicable.<\/li>\n <li>Complete the BoundingBox if you can.<\/li>\n <li>Pass this buffer to the viewer using\n one of the AddObject() methods - see below.<\/li>\n<\/ul>\n<p>If the viewer requires more sections to be completed (Raw\/RawSizes) AddObject()\n will return flags indicating which ones, otherwise it returns kNone. You must\n fill the buffer and mark these sections valid, and pass the buffer again. A\n typical code snippet would be:<\/p>\n<pre>TBuffer3DSphere sphereBuffer;\n\/\/ Fill out kCore...\n\/\/ Fill out kBoundingBox...\n\/\/ Fill out kShapeSpecific for TBuffer3DSphere\n\/\/ Try first add to viewer\nInt_t reqSections = viewer->AddObject(buffer);\nif (reqSections != TBuffer3D::kNone) {\n if (reqSections & TBuffer3D::kRawSizes) {\n \/\/ Fill out kRawSizes...\n }\n if (reqSections & TBuffer3D::kRaw) {\n \/\/ Fill out kRaw...\n }\n \/\/ Add second time to viewer - ignore return cannot do more\n viewer->AddObject(buffer);\n }\n}<\/pre>\n<p><em>ShapeSpecific<\/em>: If the viewer can directly display the buffer without\n filling of the kRaw\/kRawSizes section it will not need to request client side\n tessellation.\n Currently we provide the following various shape specific classes, which the\n OpenGL viewer can take advantage of (see TBuffer3D.h and TBuffer3DTypes.h)<\/p>\n<ul>\n <li>TBuffer3DSphere - solid, hollow and cut spheres*<\/li>\n <li>TBuffer3DTubeSeg - angle tube segment<\/li>\n <li>TBuffer3DCutTube - angle tube segment with plane cut ends.<\/li>\n<\/ul>\n<p>*OpenGL only supports solid spheres at present - cut\/hollow ones will be\n requested tessellated.<\/p>\n<p>Anyone is free to add new TBuffer3D classes, but it should be clear that the\n viewers require updating to be able to take advantage of them. The number of\n native shapes in OpenGL will be expanded over time.<\/p>\n<p><em>BoundingBox: <\/em>You are not obliged to complete this, as any viewer\n requiring one internally (OpenGL) will build one for you if you do not provide.\n However\n to do this the viewer will force you to provide the raw tessellation, and the\n resulting box will be axis aligned with the overall scene, which is non-ideal\n for rotated shapes.<\/p>\n<p>As we need to support orientated (rotated) bounding boxes, TBuffer3D requires\n the 6 vertices of the box. We also provide a convenience function, SetAABoundingBox(),\n for simpler case of setting an axis aligned bounding box.<\/p>\n<h4>\n Master\/Local Reference Frames<\/h4>\nThe <em>Core<\/em> section of TBuffer3D contains two members relating to reference\n frames:\n<em>fLocalFrame<\/em> & <em>fLocalMaster<\/em>. <em>fLocalFrame<\/em> indicates\n if any positions in the buffer (bounding box and tessellation vertexes) are\n in local or master (world\n frame). <em>fLocalMaster<\/em> is a standard 4x4 translation matrix (OpenGL\n colum major ordering) for placing the object into the 3D master frame.\n <p>If <em>fLocalFrame<\/em> is kFALSE, <em>fLocalMaster<\/em> should contain an\n identity matrix. This is set by default, and can be reset using <em>SetLocalMasterIdentity()<\/em> function.<br>\nLogical & Physical Objects<\/p>\n<p>There are two cases of object addition:<\/p>\n<ul>\n <li> Add this object as a single independent entity in the world reference\n frame.<\/li>\n <li>Add\n a physical placement (copy) of this logical object (described in local\n reference frame).<\/li>\n<\/ul>\n<p>The second case is very typical in geometry packages, GEANT4, where we have\n very large number repeated placements of relatively few logical (unique) shapes.\n Some viewers (OpenGL only at present) are able to take advantage of this by\n identifying unique logical shapes from the <em>fID<\/em> logical ID member of\n TBuffer3D. If repeated addition of the same <em>fID<\/em> is found, the shape\n is cached already - and the costly tessellation does not need to be sent again.\n The viewer can\n also perform internal GL specific caching with considerable performance gains\n in these cases.<\/p>\n<p>For this to work correctly the logical object in must be described in TBuffer3D\n in the local reference frame, complete with the local\/master translation. The\n viewer indicates this through the interface method<\/p>\n<pre>PreferLocalFrame()<\/pre>\n<p>If this returns kTRUE you can make repeated calls to AddObject(), with TBuffer3D\n containing the same fID, and different <em>fLocalMaster<\/em> placements.<\/p>\n<p>For viewers supporting logical\/physical objects, the TBuffer3D content refers\n to the properties of logical object, with the <em>fLocalMaster<\/em> transform and the\n <em>fColor<\/em> and <em>fTransparency<\/em> attributes, which can be varied for each physical\n object.<\/p>\n<p>As a minimum requirement all clients must be capable of filling the raw tessellation\n of the object buffer, in the master reference frame. Conversely viewers must\n always be capable of displaying the object described by this buffer.<\/p>\n<h4>\n Scene Rebuilds<\/h4>\n<p>It should be understood that AddObject is not an explicit command to the viewer\n - it may for various reasons decide to ignore it:<\/p>\n<ul>\n <li> It already has the object internally cached .<\/li>\n <li>The object falls outside\n some 'interest' limits of the viewer camera.<\/li>\n <li>The object is too small to\n be worth drawing.<\/li>\n<\/ul>\n<p>In all these cases AddObject() returns kNone, as it does for successful addition,\n simply indicating it does not require you to provide further information about\n this object. You should\n not try to make any assumptions about what the viewer did with it.<\/p>\n<p>This enables the viewer to be connected to a client which sends potentially\n millions of objects, and only accept those that are of interest at a certain\n time, caching the relatively small number of CPU\/memory costly logical shapes,\n and retaining\/discarding the physical placements as required. The viewer may\n decide to force the client to rebuild (republish) the scene (via\n a TPad\n repaint\n at\n present),\n and\n thus\n collect\n these\n objects if\n the\n internal viewer state changes. It does this presently by forcing a repaint\n on the attached TPad object - hence the reason for putting all publishing to\n the viewer in the attached pad objects Paint() method. We will likely remove\n this requirement in the future, indicating the rebuild request via a normal\nROOT signal, which the client can detect.<\/p>\n<h4>\n Physical IDs<\/h4>\nTVirtualViewer3D provides for two methods of object addition:virtual Int_t AddObject(const\nTBuffer3D & buffer, Bool_t * addChildren = 0)<br>\n<pre>virtual Int_t AddObject(UInt_t physicalID, const TBuffer3D & buffer, Bool_t * addChildren = 0)<\/pre>\n<p>If you use the first (simple) case a viewer using logical\/physical pairs\n will generate IDs for each physical object internally. In the second you\n can specify\n a unique identifier from the client, which allows the viewer to be more\n efficient. It can now cache both logical and physical objects, and only discard\n physical\n objects no longer of interest as part of scene rebuilds.<\/p>\n<h4>\n Child Objects<\/h4>\n<p>In many geometries there is a rigid containment hierarchy, and so if the viewer\n is not interested in a certain object due to limits\/size then it will also\n not be interest in any of the contained branch of descendents. Both AddObject()\n methods have an addChildren parameter. The viewer will complete this (if passed)\nindicating if children (contained within the one just sent) are worth adding.<\/p>\n<h4>\n Recyling TBuffer3D <\/h4>\n<p>Once add AddObject() has been called, the contents are copied to the viewer\n internally. You are free to destroy this object, or recycle it for the next\n object if suitable.<\/p>\n<!--*\/\n\/\/ -->END_HTML\n\n\n#include \"TVirtualViewer3D.h\"\n#include \"TVirtualPad.h\"\n#include \"TPluginManager.h\"\n#include \"TError.h\"\n#include \"TROOT.h\"\n#include \"TClass.h\"\n\nClassImp(TVirtualViewer3D)\n\n\/\/______________________________________________________________________________\nTVirtualViewer3D* TVirtualViewer3D::Viewer3D(TVirtualPad *pad, Option_t *type)\n{\n \/\/ Create a Viewer 3D of specified type\n TVirtualViewer3D *viewer = 0;\n TPluginHandler *h;\n if ((h = gROOT->GetPluginManager()->FindHandler(\"TVirtualViewer3D\", type))) {\n if (h->LoadPlugin() == -1) return 0;\n\n if (!pad) {\n viewer = (TVirtualViewer3D *) h->ExecPlugin(1, gPad);\n } else {\n viewer = (TVirtualViewer3D *) h->ExecPlugin(1, pad);\n }\n }\n return viewer;\n}\n<commit_msg>remove now unused TROOT.h include.<commit_after>\/\/ @(#)root\/base:$Name: $:$Id: TVirtualViewer3D.cxx,v 1.10 2007\/06\/11 19:56:33 brun Exp $\n\/\/ Author: Olivier Couet 05\/10\/2004\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TVirtualViewer3D \/\/\n\/\/ \/\/\n\/\/ Abstract 3D shapes viewer. The concrete implementations are: \/\/\n\/\/ \/\/\n\/\/ TViewerX3D : X3d viewer \/\/\n\/\/ TGLViewer : OpenGL viewer \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/BEGIN_HTML <!--\n\/* -->\n<h4>3D Viewer Infrastructure Overview<\/h4>\n<p>The 3D Viewer infrastructure consists of:<\/p>\n<ul>\n <li> TVirtualViewer3D interface: An abstract handle to the viewer, allowing\n client to test preferences, add objects, control the viewer via scripting\n (to be added) etc.<\/li>\n <li>TBuffer3D class hierarchy: Used to describe 3D objects\n ("shapes")\n - filled \/added by negotiation with viewer via TVirtualViewer3D.<\/li>\n<\/ul>\n<p>Together these allow clients to publish objects to any one of the 3D viewers\n (currently OpenGL\/x3d,TPad), free of viewer specific drawing code. They allow\n our simple x3d viewer, and considerably more sophisticated OpenGL one to both\n work with both geometry libraries (g3d and geom) efficiently.<\/p>\n<p>Publishing to a viewer consists of the following steps:<\/p>\n<ol>\n <li> Create \/ obtain viewer handle<\/li>\n <li>Begin scene on viewer<\/li>\n <li>Fill mandatory parts of TBuffer3D describing object<\/li>\n <li>Add to viewer<\/li>\n <li>Fill optional parts of TBuffer3D if requested by viewer, and add again<br>\n ... repeat 3\/4\/5\n as required<\/li>\n <li>End scene on viewer<\/li>\n<\/ol>\n<h4>Creating \/ Obtaining Viewer<\/h4>\n<p>Create\/obtain the viewer handle via local\/global pad - the viewer is always\n bound to a TPad object at present [This may be removed as a restriction in\n the future] . You should perform the publishing to the viewer described below\n in the Paint() method of the object you attach to the pad (via Draw())<\/p>\n<pre>TVirtualViewer3D * v = gPad->GetViewer3D("xxxx");<\/pre>\n<p>" xxxx" is viewer type: OpenGL "ogl", X3D "x3d" or\n Pad "pad" (default). The viewer is created via the plugin manager,\n attached to pad, and the interface returned.<\/p>\n<h4> Begin \/ End Scene<\/h4>\n<p>Objects must be added to viewer between BeginScene\/EndScene calls e.g.<\/p>\n<pre>v->BeginScene();\n.....\nv->AddObject(....);\nv->AddObject(....);\n.....\nv->EndScene();<\/pre>\n<p>The BeginScene call will cause the viewer to suspend redraws etc, and after\n the EndScene the viewer will reset the camera to frame the new scene and redraw.<\/p>\n[x3d viewer does not support changing of scenes - objects added after the\n first Open\/CloseScene pair will be ignored.]<br>\n<h4>Filling TBuffer3D and Adding to Viewer<\/h4>\n<p>The viewers behind the TVirtualViewer3D interface differ greatly in their\n capabilities e.g.<\/p>\n<ul>\n <li> Some know how to draw certain shapes natively (e.g. spheres\/tubes in\n OpenGL) - others always require a raw tessellation description of points\/lines\/segments.<\/li>\n <li>Some\n need the 3D object positions in the global frame, others can cope with\n local frames + a translation matrix - which can give considerable performance\n benefits.<\/li>\n<\/ul>\n<p>To cope with these situations the object buffer is filled out in negotiation\n with the viewer. TBuffer3D classes are conceptually divided into enumerated\n sections Core, BoundingBox, Raw etc (see TBuffer3D.h for more details). <\/p>\n<p align=\"center\"><img src=\"gif\/TBuffer3D.gif\" width=\"501\" height=\"501\"><\/p>\n<p>The<em> SectionsValid() \/ SetSectionsValid \/ ClearSectionsValid() <\/em>methods of TBuffer3D\n are used to test\/set\/clear these section valid flags.<\/p>\n<p>The sections found in TBuffer3D (<em>Core\/BoundingBox\/Raw Sizes\/Raw<\/em>)\n are sufficient to describe any tessellated shape in a generic fashion. An additional <em>ShapeSpecific<\/em> section\n in derived shape specific classes allows a more abstract shape description\n ("a sphere of inner radius x, outer radius y"). This enables a viewer\n which knows how to draw (tessellate) the shape itself to do so, which can bring\n considerable performance and quality benefits, while providing a generic fallback\n suitable for all viewers.<\/p>\n<p>The rules for client negotiation with the viewer are:<\/p>\n<ul>\n <li> If suitable specialized TBuffer3D class exists, use it, otherwise use\n TBuffer3D.<\/li>\n <li>Complete the mandatory Core section.<\/li>\n <li>Complete the ShapeSpecific section\n if applicable.<\/li>\n <li>Complete the BoundingBox if you can.<\/li>\n <li>Pass this buffer to the viewer using\n one of the AddObject() methods - see below.<\/li>\n<\/ul>\n<p>If the viewer requires more sections to be completed (Raw\/RawSizes) AddObject()\n will return flags indicating which ones, otherwise it returns kNone. You must\n fill the buffer and mark these sections valid, and pass the buffer again. A\n typical code snippet would be:<\/p>\n<pre>TBuffer3DSphere sphereBuffer;\n\/\/ Fill out kCore...\n\/\/ Fill out kBoundingBox...\n\/\/ Fill out kShapeSpecific for TBuffer3DSphere\n\/\/ Try first add to viewer\nInt_t reqSections = viewer->AddObject(buffer);\nif (reqSections != TBuffer3D::kNone) {\n if (reqSections & TBuffer3D::kRawSizes) {\n \/\/ Fill out kRawSizes...\n }\n if (reqSections & TBuffer3D::kRaw) {\n \/\/ Fill out kRaw...\n }\n \/\/ Add second time to viewer - ignore return cannot do more\n viewer->AddObject(buffer);\n }\n}<\/pre>\n<p><em>ShapeSpecific<\/em>: If the viewer can directly display the buffer without\n filling of the kRaw\/kRawSizes section it will not need to request client side\n tessellation.\n Currently we provide the following various shape specific classes, which the\n OpenGL viewer can take advantage of (see TBuffer3D.h and TBuffer3DTypes.h)<\/p>\n<ul>\n <li>TBuffer3DSphere - solid, hollow and cut spheres*<\/li>\n <li>TBuffer3DTubeSeg - angle tube segment<\/li>\n <li>TBuffer3DCutTube - angle tube segment with plane cut ends.<\/li>\n<\/ul>\n<p>*OpenGL only supports solid spheres at present - cut\/hollow ones will be\n requested tessellated.<\/p>\n<p>Anyone is free to add new TBuffer3D classes, but it should be clear that the\n viewers require updating to be able to take advantage of them. The number of\n native shapes in OpenGL will be expanded over time.<\/p>\n<p><em>BoundingBox: <\/em>You are not obliged to complete this, as any viewer\n requiring one internally (OpenGL) will build one for you if you do not provide.\n However\n to do this the viewer will force you to provide the raw tessellation, and the\n resulting box will be axis aligned with the overall scene, which is non-ideal\n for rotated shapes.<\/p>\n<p>As we need to support orientated (rotated) bounding boxes, TBuffer3D requires\n the 6 vertices of the box. We also provide a convenience function, SetAABoundingBox(),\n for simpler case of setting an axis aligned bounding box.<\/p>\n<h4>\n Master\/Local Reference Frames<\/h4>\nThe <em>Core<\/em> section of TBuffer3D contains two members relating to reference\n frames:\n<em>fLocalFrame<\/em> & <em>fLocalMaster<\/em>. <em>fLocalFrame<\/em> indicates\n if any positions in the buffer (bounding box and tessellation vertexes) are\n in local or master (world\n frame). <em>fLocalMaster<\/em> is a standard 4x4 translation matrix (OpenGL\n colum major ordering) for placing the object into the 3D master frame.\n <p>If <em>fLocalFrame<\/em> is kFALSE, <em>fLocalMaster<\/em> should contain an\n identity matrix. This is set by default, and can be reset using <em>SetLocalMasterIdentity()<\/em> function.<br>\nLogical & Physical Objects<\/p>\n<p>There are two cases of object addition:<\/p>\n<ul>\n <li> Add this object as a single independent entity in the world reference\n frame.<\/li>\n <li>Add\n a physical placement (copy) of this logical object (described in local\n reference frame).<\/li>\n<\/ul>\n<p>The second case is very typical in geometry packages, GEANT4, where we have\n very large number repeated placements of relatively few logical (unique) shapes.\n Some viewers (OpenGL only at present) are able to take advantage of this by\n identifying unique logical shapes from the <em>fID<\/em> logical ID member of\n TBuffer3D. If repeated addition of the same <em>fID<\/em> is found, the shape\n is cached already - and the costly tessellation does not need to be sent again.\n The viewer can\n also perform internal GL specific caching with considerable performance gains\n in these cases.<\/p>\n<p>For this to work correctly the logical object in must be described in TBuffer3D\n in the local reference frame, complete with the local\/master translation. The\n viewer indicates this through the interface method<\/p>\n<pre>PreferLocalFrame()<\/pre>\n<p>If this returns kTRUE you can make repeated calls to AddObject(), with TBuffer3D\n containing the same fID, and different <em>fLocalMaster<\/em> placements.<\/p>\n<p>For viewers supporting logical\/physical objects, the TBuffer3D content refers\n to the properties of logical object, with the <em>fLocalMaster<\/em> transform and the\n <em>fColor<\/em> and <em>fTransparency<\/em> attributes, which can be varied for each physical\n object.<\/p>\n<p>As a minimum requirement all clients must be capable of filling the raw tessellation\n of the object buffer, in the master reference frame. Conversely viewers must\n always be capable of displaying the object described by this buffer.<\/p>\n<h4>\n Scene Rebuilds<\/h4>\n<p>It should be understood that AddObject is not an explicit command to the viewer\n - it may for various reasons decide to ignore it:<\/p>\n<ul>\n <li> It already has the object internally cached .<\/li>\n <li>The object falls outside\n some 'interest' limits of the viewer camera.<\/li>\n <li>The object is too small to\n be worth drawing.<\/li>\n<\/ul>\n<p>In all these cases AddObject() returns kNone, as it does for successful addition,\n simply indicating it does not require you to provide further information about\n this object. You should\n not try to make any assumptions about what the viewer did with it.<\/p>\n<p>This enables the viewer to be connected to a client which sends potentially\n millions of objects, and only accept those that are of interest at a certain\n time, caching the relatively small number of CPU\/memory costly logical shapes,\n and retaining\/discarding the physical placements as required. The viewer may\n decide to force the client to rebuild (republish) the scene (via\n a TPad\n repaint\n at\n present),\n and\n thus\n collect\n these\n objects if\n the\n internal viewer state changes. It does this presently by forcing a repaint\n on the attached TPad object - hence the reason for putting all publishing to\n the viewer in the attached pad objects Paint() method. We will likely remove\n this requirement in the future, indicating the rebuild request via a normal\nROOT signal, which the client can detect.<\/p>\n<h4>\n Physical IDs<\/h4>\nTVirtualViewer3D provides for two methods of object addition:virtual Int_t AddObject(const\nTBuffer3D & buffer, Bool_t * addChildren = 0)<br>\n<pre>virtual Int_t AddObject(UInt_t physicalID, const TBuffer3D & buffer, Bool_t * addChildren = 0)<\/pre>\n<p>If you use the first (simple) case a viewer using logical\/physical pairs\n will generate IDs for each physical object internally. In the second you\n can specify\n a unique identifier from the client, which allows the viewer to be more\n efficient. It can now cache both logical and physical objects, and only discard\n physical\n objects no longer of interest as part of scene rebuilds.<\/p>\n<h4>\n Child Objects<\/h4>\n<p>In many geometries there is a rigid containment hierarchy, and so if the viewer\n is not interested in a certain object due to limits\/size then it will also\n not be interest in any of the contained branch of descendents. Both AddObject()\n methods have an addChildren parameter. The viewer will complete this (if passed)\nindicating if children (contained within the one just sent) are worth adding.<\/p>\n<h4>\n Recyling TBuffer3D <\/h4>\n<p>Once add AddObject() has been called, the contents are copied to the viewer\n internally. You are free to destroy this object, or recycle it for the next\n object if suitable.<\/p>\n<!--*\/\n\/\/ -->END_HTML\n\n\n#include \"TVirtualViewer3D.h\"\n#include \"TVirtualPad.h\"\n#include \"TPluginManager.h\"\n#include \"TError.h\"\n#include \"TClass.h\"\n\nClassImp(TVirtualViewer3D)\n\n\/\/______________________________________________________________________________\nTVirtualViewer3D* TVirtualViewer3D::Viewer3D(TVirtualPad *pad, Option_t *type)\n{\n \/\/ Create a Viewer 3D of specified type.\n\n TVirtualViewer3D *viewer = 0;\n TPluginHandler *h;\n if ((h = gPluginMgr->FindHandler(\"TVirtualViewer3D\", type))) {\n if (h->LoadPlugin() == -1)\n return 0;\n\n if (!pad) {\n viewer = (TVirtualViewer3D *) h->ExecPlugin(1, gPad);\n } else {\n viewer = (TVirtualViewer3D *) h->ExecPlugin(1, pad);\n }\n }\n return viewer;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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\/\/ This file contains unit tests for PEImage.\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"base\/win\/pe_image.h\"\n#include \"base\/win\/windows_version.h\"\n\nnamespace base {\nnamespace win {\n\n\/\/ Just counts the number of invocations.\nbool ExportsCallback(const PEImage &image,\n DWORD ordinal,\n DWORD hint,\n LPCSTR name,\n PVOID function,\n LPCSTR forward,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool ImportsCallback(const PEImage &image,\n LPCSTR module,\n DWORD ordinal,\n LPCSTR name,\n DWORD hint,\n PIMAGE_THUNK_DATA iat,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool SectionsCallback(const PEImage &image,\n PIMAGE_SECTION_HEADER header,\n PVOID section_start,\n DWORD section_size,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool RelocsCallback(const PEImage &image,\n WORD type,\n PVOID address,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool ImportChunksCallback(const PEImage &image,\n LPCSTR module,\n PIMAGE_THUNK_DATA name_table,\n PIMAGE_THUNK_DATA iat,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool DelayImportChunksCallback(const PEImage &image,\n PImgDelayDescr delay_descriptor,\n LPCSTR module,\n PIMAGE_THUNK_DATA name_table,\n PIMAGE_THUNK_DATA iat,\n PIMAGE_THUNK_DATA bound_iat,\n PIMAGE_THUNK_DATA unload_iat,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ We'll be using some known values for the tests.\nenum Value {\n sections = 0,\n imports_dlls,\n delay_dlls,\n exports,\n imports,\n delay_imports,\n relocs\n};\n\n\/\/ Retrieves the expected value from advapi32.dll based on the OS.\nint GetExpectedValue(Value value, DWORD os) {\n const int xp_delay_dlls = 2;\n const int xp_exports = 675;\n const int xp_imports = 422;\n const int xp_delay_imports = 8;\n const int xp_relocs = 9180;\n const int vista_delay_dlls = 4;\n const int vista_exports = 799;\n const int vista_imports = 476;\n const int vista_delay_imports = 24;\n const int vista_relocs = 10188;\n const int w2k_delay_dlls = 0;\n const int w2k_exports = 566;\n const int w2k_imports = 357;\n const int w2k_delay_imports = 0;\n const int w2k_relocs = 7388;\n const int win7_delay_dlls = 7;\n const int win7_exports = 806;\n const int win7_imports = 568;\n const int win7_delay_imports = 71;\n const int win7_relocs = 7812;\n const int win8_delay_dlls = 9;\n const int win8_exports = 806;\n const int win8_imports = 568;\n const int win8_delay_imports = 113;\n const int win8_relocs = 9478;\n\n \/\/ Contains the expected value, for each enumerated property (Value), and the\n \/\/ OS version: [Value][os_version]\n const int expected[][5] = {\n {4, 4, 4, 4, 5},\n {3, 3, 3, 13, 19},\n {w2k_delay_dlls, xp_delay_dlls, vista_delay_dlls, win7_delay_dlls,\n win8_delay_dlls},\n {w2k_exports, xp_exports, vista_exports, win7_exports, win8_exports},\n {w2k_imports, xp_imports, vista_imports, win7_imports, win8_imports},\n {w2k_delay_imports, xp_delay_imports,\n vista_delay_imports, win7_delay_imports, win8_delay_imports},\n {w2k_relocs, xp_relocs, vista_relocs, win7_relocs, win8_relocs}\n };\n\n if (value > relocs)\n return 0;\n if (50 == os)\n os = 0; \/\/ 5.0\n else if (51 == os || 52 == os)\n os = 1;\n else if (os == 60)\n os = 2; \/\/ 6.x\n else if (os == 61)\n os = 3;\n else if (os >= 62)\n os = 4;\n else\n return 0;\n\n return expected[value][os];\n}\n\n\/\/ Tests that we are able to enumerate stuff from a PE file, and that\n\/\/ the actual number of items found is within the expected range.\nTEST(PEImageTest, EnumeratesPE) {\n \/\/ Windows Server 2003 is not supported as a test environment for this test.\n if (base::win::GetVersion() == base::win::VERSION_SERVER_2003)\n return;\n HMODULE module = LoadLibrary(L\"advapi32.dll\");\n ASSERT_TRUE(NULL != module);\n\n PEImage pe(module);\n int count = 0;\n EXPECT_TRUE(pe.VerifyMagic());\n\n DWORD os = pe.GetNTHeaders()->OptionalHeader.MajorOperatingSystemVersion;\n os = os * 10 + pe.GetNTHeaders()->OptionalHeader.MinorOperatingSystemVersion;\n\n pe.EnumSections(SectionsCallback, &count);\n EXPECT_EQ(GetExpectedValue(sections, os), count);\n\n count = 0;\n pe.EnumImportChunks(ImportChunksCallback, &count);\n EXPECT_EQ(GetExpectedValue(imports_dlls, os), count);\n\n count = 0;\n pe.EnumDelayImportChunks(DelayImportChunksCallback, &count);\n EXPECT_EQ(GetExpectedValue(delay_dlls, os), count);\n\n count = 0;\n pe.EnumExports(ExportsCallback, &count);\n EXPECT_GT(count, GetExpectedValue(exports, os) - 20);\n EXPECT_LT(count, GetExpectedValue(exports, os) + 100);\n\n count = 0;\n pe.EnumAllImports(ImportsCallback, &count);\n EXPECT_GT(count, GetExpectedValue(imports, os) - 20);\n EXPECT_LT(count, GetExpectedValue(imports, os) + 100);\n\n count = 0;\n pe.EnumAllDelayImports(ImportsCallback, &count);\n EXPECT_GT(count, GetExpectedValue(delay_imports, os) - 2);\n EXPECT_LT(count, GetExpectedValue(delay_imports, os) + 8);\n\n count = 0;\n pe.EnumRelocs(RelocsCallback, &count);\n EXPECT_GT(count, GetExpectedValue(relocs, os) - 150);\n EXPECT_LT(count, GetExpectedValue(relocs, os) + 1500);\n\n FreeLibrary(module);\n}\n\n\/\/ Tests that we can locate an specific exported symbol, by name and by ordinal.\nTEST(PEImageTest, RetrievesExports) {\n HMODULE module = LoadLibrary(L\"advapi32.dll\");\n ASSERT_TRUE(NULL != module);\n\n PEImage pe(module);\n WORD ordinal;\n\n EXPECT_TRUE(pe.GetProcOrdinal(\"RegEnumKeyExW\", &ordinal));\n\n FARPROC address1 = pe.GetProcAddress(\"RegEnumKeyExW\");\n FARPROC address2 = pe.GetProcAddress(reinterpret_cast<char*>(ordinal));\n EXPECT_TRUE(address1 != NULL);\n EXPECT_TRUE(address2 != NULL);\n EXPECT_TRUE(address1 == address2);\n\n FreeLibrary(module);\n}\n\n} \/\/ namespace win\n} \/\/ namespace base\n<commit_msg>Fixes for the EnumeratesPE base_unittest failures seen on Windows 8 X64. The values used by this test for sections and import dlls, needed to be changed. These values are different for X86 and X64.<commit_after>\/\/ 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\/\/ This file contains unit tests for PEImage.\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"base\/win\/pe_image.h\"\n#include \"base\/win\/windows_version.h\"\n\nnamespace base {\nnamespace win {\n\n\/\/ Just counts the number of invocations.\nbool ExportsCallback(const PEImage &image,\n DWORD ordinal,\n DWORD hint,\n LPCSTR name,\n PVOID function,\n LPCSTR forward,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool ImportsCallback(const PEImage &image,\n LPCSTR module,\n DWORD ordinal,\n LPCSTR name,\n DWORD hint,\n PIMAGE_THUNK_DATA iat,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool SectionsCallback(const PEImage &image,\n PIMAGE_SECTION_HEADER header,\n PVOID section_start,\n DWORD section_size,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool RelocsCallback(const PEImage &image,\n WORD type,\n PVOID address,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool ImportChunksCallback(const PEImage &image,\n LPCSTR module,\n PIMAGE_THUNK_DATA name_table,\n PIMAGE_THUNK_DATA iat,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ Just counts the number of invocations.\nbool DelayImportChunksCallback(const PEImage &image,\n PImgDelayDescr delay_descriptor,\n LPCSTR module,\n PIMAGE_THUNK_DATA name_table,\n PIMAGE_THUNK_DATA iat,\n PIMAGE_THUNK_DATA bound_iat,\n PIMAGE_THUNK_DATA unload_iat,\n PVOID cookie) {\n int* count = reinterpret_cast<int*>(cookie);\n (*count)++;\n return true;\n}\n\n\/\/ We'll be using some known values for the tests.\nenum Value {\n sections = 0,\n imports_dlls,\n delay_dlls,\n exports,\n imports,\n delay_imports,\n relocs\n};\n\n\/\/ Retrieves the expected value from advapi32.dll based on the OS.\nint GetExpectedValue(Value value, DWORD os) {\n const int xp_delay_dlls = 2;\n const int xp_exports = 675;\n const int xp_imports = 422;\n const int xp_delay_imports = 8;\n const int xp_relocs = 9180;\n const int vista_delay_dlls = 4;\n const int vista_exports = 799;\n const int vista_imports = 476;\n const int vista_delay_imports = 24;\n const int vista_relocs = 10188;\n const int w2k_delay_dlls = 0;\n const int w2k_exports = 566;\n const int w2k_imports = 357;\n const int w2k_delay_imports = 0;\n const int w2k_relocs = 7388;\n const int win7_delay_dlls = 7;\n const int win7_exports = 806;\n const int win7_imports = 568;\n const int win7_delay_imports = 71;\n const int win7_relocs = 7812;\n const int win8_delay_dlls = 9;\n const int win8_exports = 806;\n const int win8_imports = 568;\n const int win8_delay_imports = 113;\n const int win8_relocs = 9478;\n int win8_sections = 4;\n int win8_import_dlls = 17;\n\n base::win::OSInfo* os_info = base::win::OSInfo::GetInstance();\n if (os_info->architecture() == base::win::OSInfo::X86_ARCHITECTURE) {\n win8_sections = 5;\n win8_import_dlls = 19;\n }\n\n \/\/ Contains the expected value, for each enumerated property (Value), and the\n \/\/ OS version: [Value][os_version]\n const int expected[][5] = {\n {4, 4, 4, 4, win8_sections},\n {3, 3, 3, 13, win8_import_dlls},\n {w2k_delay_dlls, xp_delay_dlls, vista_delay_dlls, win7_delay_dlls,\n win8_delay_dlls},\n {w2k_exports, xp_exports, vista_exports, win7_exports, win8_exports},\n {w2k_imports, xp_imports, vista_imports, win7_imports, win8_imports},\n {w2k_delay_imports, xp_delay_imports,\n vista_delay_imports, win7_delay_imports, win8_delay_imports},\n {w2k_relocs, xp_relocs, vista_relocs, win7_relocs, win8_relocs}\n };\n\n if (value > relocs)\n return 0;\n if (50 == os)\n os = 0; \/\/ 5.0\n else if (51 == os || 52 == os)\n os = 1;\n else if (os == 60)\n os = 2; \/\/ 6.x\n else if (os == 61)\n os = 3;\n else if (os >= 62)\n os = 4;\n else\n return 0;\n\n return expected[value][os];\n}\n\n\/\/ Tests that we are able to enumerate stuff from a PE file, and that\n\/\/ the actual number of items found is within the expected range.\nTEST(PEImageTest, EnumeratesPE) {\n \/\/ Windows Server 2003 is not supported as a test environment for this test.\n if (base::win::GetVersion() == base::win::VERSION_SERVER_2003)\n return;\n HMODULE module = LoadLibrary(L\"advapi32.dll\");\n ASSERT_TRUE(NULL != module);\n\n PEImage pe(module);\n int count = 0;\n EXPECT_TRUE(pe.VerifyMagic());\n\n DWORD os = pe.GetNTHeaders()->OptionalHeader.MajorOperatingSystemVersion;\n os = os * 10 + pe.GetNTHeaders()->OptionalHeader.MinorOperatingSystemVersion;\n\n pe.EnumSections(SectionsCallback, &count);\n EXPECT_EQ(GetExpectedValue(sections, os), count);\n\n count = 0;\n pe.EnumImportChunks(ImportChunksCallback, &count);\n EXPECT_EQ(GetExpectedValue(imports_dlls, os), count);\n\n count = 0;\n pe.EnumDelayImportChunks(DelayImportChunksCallback, &count);\n EXPECT_EQ(GetExpectedValue(delay_dlls, os), count);\n\n count = 0;\n pe.EnumExports(ExportsCallback, &count);\n EXPECT_GT(count, GetExpectedValue(exports, os) - 20);\n EXPECT_LT(count, GetExpectedValue(exports, os) + 100);\n\n count = 0;\n pe.EnumAllImports(ImportsCallback, &count);\n EXPECT_GT(count, GetExpectedValue(imports, os) - 20);\n EXPECT_LT(count, GetExpectedValue(imports, os) + 100);\n\n count = 0;\n pe.EnumAllDelayImports(ImportsCallback, &count);\n EXPECT_GT(count, GetExpectedValue(delay_imports, os) - 2);\n EXPECT_LT(count, GetExpectedValue(delay_imports, os) + 8);\n\n count = 0;\n pe.EnumRelocs(RelocsCallback, &count);\n EXPECT_GT(count, GetExpectedValue(relocs, os) - 150);\n EXPECT_LT(count, GetExpectedValue(relocs, os) + 1500);\n\n FreeLibrary(module);\n}\n\n\/\/ Tests that we can locate an specific exported symbol, by name and by ordinal.\nTEST(PEImageTest, RetrievesExports) {\n HMODULE module = LoadLibrary(L\"advapi32.dll\");\n ASSERT_TRUE(NULL != module);\n\n PEImage pe(module);\n WORD ordinal;\n\n EXPECT_TRUE(pe.GetProcOrdinal(\"RegEnumKeyExW\", &ordinal));\n\n FARPROC address1 = pe.GetProcAddress(\"RegEnumKeyExW\");\n FARPROC address2 = pe.GetProcAddress(reinterpret_cast<char*>(ordinal));\n EXPECT_TRUE(address1 != NULL);\n EXPECT_TRUE(address2 != NULL);\n EXPECT_TRUE(address1 == address2);\n\n FreeLibrary(module);\n}\n\n} \/\/ namespace win\n} \/\/ namespace base\n<|endoftext|>"} {"text":"<commit_before>#include <db_cxx.h>\n\n\n#include <iostream>\nusing namespace std;\nint main()\n{\n Dbt dbt;\n dbt.set_size(3);\n cout << \"Hello World!\" << endl; cout << \"Welcome to C++ Programming\" << endl;\n return 0;\n}\n<commit_msg>Added Dbt.get_ulen and Dbt.set_ulen Modified test1 to test new functions and some of the older ones. Addresses #197<commit_after>#include <db_cxx.h>\n\n\n#include <iostream>\nusing namespace std;\nint main()\n{\n u_int32_t size = 3;\n u_int32_t flags = 5;\n u_int32_t ulen = 7;\n void* data = &size;\n Dbt dbt;\n\n dbt.set_size(size);\n dbt.set_flags(flags);\n dbt.set_data(data);\n dbt.set_ulen(ulen);\n assert(dbt.get_size() == size);\n assert(dbt.get_flags() == flags);\n assert(dbt.get_data() == data);\n assert(dbt.get_ulen() == ulen);\n cout << \"Hello World!\" << endl; cout << \"Welcome to C++ Programming\" << endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015-2016 André Netzeband\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 all\n * 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 THE\n * SOFTWARE.\n *\n *\/\n\n\/**\n * @file main.cpp\n * @brief This example creates a simple Irrlicht scene with background and a simple IMGUI window.\n *\/\n\n\/\/ standard library includes\n#include <exception>\n#include <iostream>\n\n\/\/ library includes\n#include <IrrIMGUI\/IncludeIrrlicht.h>\n#include <IrrIMGUI\/IncludeIMGUI.h>\n#include <IrrIMGUI\/IrrIMGUI.h>\n#include <IrrIMGUI\/IrrIMGUIDebug.h>\n\n\/\/ helper macros for reacting on unexpected states\n#define _TOSTR(x) #x\n#define TOSTR(x) _TOSTR(x)\n#define FASSERT(expr) if (!(expr)) { throw IrrIMGUI::Debug::ExAssert(__FILE__ \"[\" TOSTR(__LINE__) \"] Assertion failed: \\'\" TOSTR(expr) \"'\\n\"); }\n\n\/\/ builds up the Irrlicht scene\nvoid runScene(void)\n{\n using namespace IrrIMGUI;\n using namespace irr;\n\n \/\/ Create standard event receiver for the IrrIMGUI\n CIMGUIEventReceiver EventReceiver;\n\n \/\/ Irrlicht Settings\n SIrrlichtCreationParameters IrrlichtParams;\n IrrlichtParams.DriverType = video::EDT_OPENGL;\n IrrlichtParams.WindowSize = core::dimension2d<u32>(1024, 800);\n IrrlichtParams.Bits = 32;\n IrrlichtParams.Fullscreen = false;\n IrrlichtParams.Stencilbuffer = true;\n IrrlichtParams.AntiAlias = 16;\n IrrlichtParams.Vsync = false;\n IrrlichtParams.EventReceiver = &EventReceiver;\n\n IrrlichtDevice * const pDevice = createDeviceEx(IrrlichtParams);\n FASSERT(pDevice);\n\n \/\/ Create GUI object\n CIMGUIHandle GUI(pDevice, &EventReceiver);\n\n video::IVideoDriver * const pDriver = pDevice->getVideoDriver();\n scene::ISceneManager * const pSceneManager = pDevice->getSceneManager();\n\n scene::ISceneNode * const pMainScreen = pSceneManager->addEmptySceneNode();\n scene::ISceneNode * const pMoonScreen = pSceneManager->addEmptySceneNode();\n\n pDriver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, false);\n irr::scene::ISceneNode * const pSkybox = pSceneManager->addSkyBoxSceneNode(\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pMainScreen);\n pDriver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, true);\n\n \/\/ Create Planet object\n scene::IMeshSceneNode * const pMoon = pSceneManager->addSphereSceneNode(5.0f, 128, pMoonScreen);\n FASSERT(pMoon);\n pMoon->setPosition(irr::core::vector3df(0,0,25));\n pMoon->setMaterialTexture(0, pDriver->getTexture(\"..\/..\/media\/Phobos.jpg\"));\n pMoon->setMaterialFlag(irr::video::EMF_LIGHTING, false);\n\n \/\/ Add camera object\n irr::scene::ICameraSceneNode * const pMainCam = pSceneManager->addCameraSceneNode(pMainScreen, core::vector3df(0, 0, 0), core::vector3df(0,0,5));\n irr::scene::ICameraSceneNode * const pMoonCam = pSceneManager->addCameraSceneNode(pMoonScreen, core::vector3df(0, 0,15), core::vector3df(0,0,25));\n\n u32 LastTime = pDevice->getTimer()->getRealTime();\n f32 Rotation = 0.0;\n f32 RotPerSec = 0.01f;\n bool IsFirstLoop = true;\n int RotationDirection = 1;\n f32 Color[3] = {0.0f\/256.0f, 43.0f\/256.0f, 56.0f\/256.0f};\n\n \/\/ Prepare double rendering\n video::ITexture * const pRenderTarget = pDriver->addRenderTargetTexture(core::dimension2d<u32>(384, 300), \"Moon\");\n IGUITexture * const pRenderTextureID = GUI.createTexture(pRenderTarget);\n\n \/\/ Start main loop\n while(pDevice->run())\n {\n pDriver->beginScene(true, true, irr::video::SColor(255,100,101,140));\n\n \/\/ ****************************\n \/\/ Render Moon Scene\n \/\/ ****************************\n pDriver->setRenderTarget(pRenderTarget, true, true, video::SColor(255,(u32)(Color[0]*255.0f),(u32)(Color[1]*255.0f),(u32)(Color[2]*255.0f)));\n pMoonScreen->setVisible(true);\n pMainScreen->setVisible(false);\n pSceneManager->setActiveCamera(pMoonCam);\n\n pSceneManager->drawAll();\n\n pDriver->setRenderTarget(0, true, true, video::SColor(255,100,101,140));\n\n \/\/ ****************************\n \/\/ Render Main Scene\n \/\/ ****************************\n pMoonScreen->setVisible(false);\n pMainScreen->setVisible(true);\n pSceneManager->setActiveCamera(pMainCam);\n\n GUI.startGUI();\n\n \/\/ create first window with picture sources\n if (IsFirstLoop)\n {\n ImGui::SetNextWindowPos(ImVec2(20.0f, 20.0f));\n ImGui::SetNextWindowSize(ImVec2(500.0f, 100.0f));\n }\n ImGui::Begin(\"Picture sources\");\n ImGui::Text(\"Background picture from Manuel Tellur \/ pixelio.de (Image-ID: 642831)\");\n ImGui::Text(\"Moon (Phobos) texture from http:\/\/nasa3d.arc.nasa.gov\");\n if (ImGui::Button(\"Exit\", ImVec2(40, 20)))\n {\n pDevice->closeDevice();\n }\n ImGui::End();\n\n GUI.updateTexture(pRenderTextureID, pRenderTarget);\n\n if (IsFirstLoop)\n {\n ImGui::SetNextWindowPos(ImVec2(300.0f, 200.0f));\n ImGui::SetNextWindowSize(ImVec2(400.0f, 450.0f));\n }\n ImGui::Begin(\"Moon Window\", NULL, ImGuiWindowFlags_ShowBorders);\n ImGui::Text(\"%.1f FPS\", ImGui::GetIO().Framerate);\n ImGui::Image(*pRenderTextureID, ImVec2(384, 300));\n ImGui::BeginGroup();\n ImGui::RadioButton(\"Left\", &RotationDirection, 1);\n ImGui::RadioButton(\"Stop\", &RotationDirection, 0);\n ImGui::RadioButton(\"Right\", &RotationDirection, -1);\n ImGui::EndGroup();\n ImGui::SameLine(0.0f, 10.0f);\n ImGui::BeginGroup();\n ImGui::SliderFloat(\"Speed\", &RotPerSec, 0.001f, 0.5f);\n ImGui::SliderFloat(\"Angle\", &Rotation, 0.0f, 360.0f);\n ImGui::ColorEdit3(\"Color\", Color);\n ImGui::EndGroup();\n ImGui::End();\n\n pSceneManager->drawAll();\n GUI.drawAll();\n\n pDriver->endScene();\n\n u32 const Time = pDevice->getTimer()->getRealTime();\n u32 const DeltaTime = Time - LastTime;\n if (DeltaTime > 0)\n {\n Rotation += (360.0f * RotPerSec * ((float)RotationDirection)) * (DeltaTime \/ 1000.0f);\n if (Rotation > 360.0f)\n {\n Rotation -= 360.0f;\n }\n else if (Rotation < 0.0f)\n {\n Rotation += 360.0f;\n }\n LastTime = Time;\n }\n pMoon->setRotation(irr::core::vector3df(0,Rotation,0));\n IsFirstLoop = false;\n }\n\n GUI.deleteTexture(pRenderTextureID);\n pDevice->drop();\n\n}\n\nint main(void)\n{\n try\n {\n runScene();\n }\n catch(std::exception &rEx)\n {\n std::cout << rEx.what() << std::flush;\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\\n');\n }\n\n return 0;\n}\n<commit_msg>Add FPS print out at window caption.<commit_after>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015-2016 André Netzeband\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 all\n * 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 THE\n * SOFTWARE.\n *\n *\/\n\n\/**\n * @file main.cpp\n * @brief This example creates a simple Irrlicht scene with background and a simple IMGUI window.\n *\/\n\n\/\/ standard library includes\n#include <exception>\n#include <iostream>\n\n\/\/ library includes\n#include <IrrIMGUI\/IncludeIrrlicht.h>\n#include <IrrIMGUI\/IncludeIMGUI.h>\n#include <IrrIMGUI\/IrrIMGUI.h>\n#include <IrrIMGUI\/IrrIMGUIDebug.h>\n\n\/\/ helper macros for reacting on unexpected states\n#define _TOSTR(x) #x\n#define TOSTR(x) _TOSTR(x)\n#define FASSERT(expr) if (!(expr)) { throw IrrIMGUI::Debug::ExAssert(__FILE__ \"[\" TOSTR(__LINE__) \"] Assertion failed: \\'\" TOSTR(expr) \"'\\n\"); }\n\n\/\/ builds up the Irrlicht scene\nvoid runScene(void)\n{\n using namespace IrrIMGUI;\n using namespace irr;\n\n \/\/ Create standard event receiver for the IrrIMGUI\n CIMGUIEventReceiver EventReceiver;\n\n \/\/ Irrlicht Settings\n SIrrlichtCreationParameters IrrlichtParams;\n IrrlichtParams.DriverType = video::EDT_OPENGL;\n IrrlichtParams.WindowSize = core::dimension2d<u32>(1024, 800);\n IrrlichtParams.Bits = 32;\n IrrlichtParams.Fullscreen = false;\n IrrlichtParams.Stencilbuffer = true;\n IrrlichtParams.AntiAlias = 16;\n IrrlichtParams.Vsync = false;\n IrrlichtParams.EventReceiver = &EventReceiver;\n\n IrrlichtDevice * const pDevice = createDeviceEx(IrrlichtParams);\n FASSERT(pDevice);\n\n \/\/ Create GUI object\n CIMGUIHandle GUI(pDevice, &EventReceiver);\n\n video::IVideoDriver * const pDriver = pDevice->getVideoDriver();\n scene::ISceneManager * const pSceneManager = pDevice->getSceneManager();\n\n scene::ISceneNode * const pMainScreen = pSceneManager->addEmptySceneNode();\n scene::ISceneNode * const pMoonScreen = pSceneManager->addEmptySceneNode();\n\n pDriver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, false);\n irr::scene::ISceneNode * const pSkybox = pSceneManager->addSkyBoxSceneNode(\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pDriver->getTexture(\"..\/..\/media\/Background.jpg\"),\n pMainScreen);\n pDriver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, true);\n\n \/\/ Create Planet object\n scene::IMeshSceneNode * const pMoon = pSceneManager->addSphereSceneNode(5.0f, 128, pMoonScreen);\n FASSERT(pMoon);\n pMoon->setPosition(irr::core::vector3df(0,0,25));\n pMoon->setMaterialTexture(0, pDriver->getTexture(\"..\/..\/media\/Phobos.jpg\"));\n pMoon->setMaterialFlag(irr::video::EMF_LIGHTING, false);\n\n \/\/ Add camera object\n irr::scene::ICameraSceneNode * const pMainCam = pSceneManager->addCameraSceneNode(pMainScreen, core::vector3df(0, 0, 0), core::vector3df(0,0,5));\n irr::scene::ICameraSceneNode * const pMoonCam = pSceneManager->addCameraSceneNode(pMoonScreen, core::vector3df(0, 0,15), core::vector3df(0,0,25));\n\n u32 LastTime = pDevice->getTimer()->getRealTime();\n s32 LastFPS = 0;\n f32 Rotation = 0.0;\n f32 RotPerSec = 0.01f;\n bool IsFirstLoop = true;\n int RotationDirection = 1;\n f32 Color[3] = {0.0f\/256.0f, 43.0f\/256.0f, 56.0f\/256.0f};\n\n \/\/ Prepare double rendering\n video::ITexture * const pRenderTarget = pDriver->addRenderTargetTexture(core::dimension2d<u32>(384, 300), \"Moon\");\n IGUITexture * const pRenderTextureID = GUI.createTexture(pRenderTarget);\n\n \/\/ Start main loop\n while(pDevice->run())\n {\n pDriver->beginScene(true, true, irr::video::SColor(255,100,101,140));\n\n \/\/ ****************************\n \/\/ Render Moon Scene\n \/\/ ****************************\n pDriver->setRenderTarget(pRenderTarget, true, true, video::SColor(255,(u32)(Color[0]*255.0f),(u32)(Color[1]*255.0f),(u32)(Color[2]*255.0f)));\n pMoonScreen->setVisible(true);\n pMainScreen->setVisible(false);\n pSceneManager->setActiveCamera(pMoonCam);\n\n pSceneManager->drawAll();\n\n pDriver->setRenderTarget(0, true, true, video::SColor(255,100,101,140));\n\n \/\/ ****************************\n \/\/ Render Main Scene\n \/\/ ****************************\n pMoonScreen->setVisible(false);\n pMainScreen->setVisible(true);\n pSceneManager->setActiveCamera(pMainCam);\n\n GUI.startGUI();\n\n \/\/ create first window with picture sources\n if (IsFirstLoop)\n {\n ImGui::SetNextWindowPos(ImVec2(20.0f, 20.0f));\n ImGui::SetNextWindowSize(ImVec2(500.0f, 100.0f));\n }\n ImGui::Begin(\"Picture sources\");\n ImGui::Text(\"Background picture from Manuel Tellur \/ pixelio.de (Image-ID: 642831)\");\n ImGui::Text(\"Moon (Phobos) texture from http:\/\/nasa3d.arc.nasa.gov\");\n if (ImGui::Button(\"Exit\", ImVec2(40, 20)))\n {\n pDevice->closeDevice();\n }\n ImGui::End();\n\n GUI.updateTexture(pRenderTextureID, pRenderTarget);\n\n if (IsFirstLoop)\n {\n ImGui::SetNextWindowPos(ImVec2(300.0f, 200.0f));\n ImGui::SetNextWindowSize(ImVec2(400.0f, 450.0f));\n }\n ImGui::Begin(\"Moon Window\", NULL, ImGuiWindowFlags_ShowBorders);\n ImGui::Text(\"%.1f FPS\", ImGui::GetIO().Framerate);\n ImGui::Image(*pRenderTextureID, ImVec2(384, 300));\n ImGui::BeginGroup();\n ImGui::RadioButton(\"Left\", &RotationDirection, 1);\n ImGui::RadioButton(\"Stop\", &RotationDirection, 0);\n ImGui::RadioButton(\"Right\", &RotationDirection, -1);\n ImGui::EndGroup();\n ImGui::SameLine(0.0f, 10.0f);\n ImGui::BeginGroup();\n ImGui::SliderFloat(\"Speed\", &RotPerSec, 0.001f, 0.5f);\n ImGui::SliderFloat(\"Angle\", &Rotation, 0.0f, 360.0f);\n ImGui::ColorEdit3(\"Color\", Color);\n ImGui::EndGroup();\n ImGui::End();\n\n pSceneManager->drawAll();\n GUI.drawAll();\n\n pDriver->endScene();\n\n u32 const Time = pDevice->getTimer()->getRealTime();\n u32 const DeltaTime = Time - LastTime;\n if (DeltaTime > 0)\n {\n Rotation += (360.0f * RotPerSec * ((float)RotationDirection)) * (DeltaTime \/ 1000.0f);\n if (Rotation > 360.0f)\n {\n Rotation -= 360.0f;\n }\n else if (Rotation < 0.0f)\n {\n Rotation += 360.0f;\n }\n LastTime = Time;\n }\n pMoon->setRotation(irr::core::vector3df(0,Rotation,0));\n IsFirstLoop = false;\n\n s32 const FPS = pDriver->getFPS();\n if (FPS != LastFPS)\n {\n LastFPS = FPS;\n core::stringw TempString = L\"Using a render target texture with IMGUI - FPS: \";\n TempString += LastFPS;\n pDevice->setWindowCaption(TempString.c_str());\n }\n }\n\n GUI.deleteTexture(pRenderTextureID);\n pDevice->drop();\n\n}\n\nint main(void)\n{\n try\n {\n runScene();\n }\n catch(std::exception &rEx)\n {\n std::cout << rEx.what() << std::flush;\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\\n');\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: macropg_impl.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:05:39 $\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 _MACROPG_IMPL_HXX\n#define _MACROPG_IMPL_HXX\n\nclass _SfxMacroTabPage_Impl\n{\npublic:\n _SfxMacroTabPage_Impl( void );\n ~_SfxMacroTabPage_Impl();\n\n String maStaticMacroLBLabel;\n PushButton* pAssignPB;\n PushButton* pDeletePB;\n String* pStrEvent;\n String* pAssignedMacro;\n ListBox* pScriptTypeLB;\n _HeaderTabListBox* pEventLB;\n SfxConfigGroupListBox_Impl* pGroupLB;\n FixedText* pFT_MacroLBLabel;\n SfxConfigFunctionListBox_Impl* pMacroLB;\n\n FixedText* pMacroFT;\n String* pMacroStr;\n FNGetRangeHdl fnGetRange;\n FNGetMacrosOfRangeHdl fnGetMacroOfRange;\n\n BOOL bReadOnly;\n};\n\n\n#endif\n<commit_msg>INTEGRATION: CWS fwk48 (1.2.326); FILE MERGED 2006\/09\/13 10:42:42 pb 1.2.326.1: fix: #125845# new member: maFillGroupTimer<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: macropg_impl.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-10-13 09:47:09 $\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 _MACROPG_IMPL_HXX\n#define _MACROPG_IMPL_HXX\n\nclass _SfxMacroTabPage_Impl\n{\npublic:\n _SfxMacroTabPage_Impl( void );\n ~_SfxMacroTabPage_Impl();\n\n String maStaticMacroLBLabel;\n PushButton* pAssignPB;\n PushButton* pDeletePB;\n String* pStrEvent;\n String* pAssignedMacro;\n ListBox* pScriptTypeLB;\n _HeaderTabListBox* pEventLB;\n SfxConfigGroupListBox_Impl* pGroupLB;\n FixedText* pFT_MacroLBLabel;\n SfxConfigFunctionListBox_Impl* pMacroLB;\n\n FixedText* pMacroFT;\n String* pMacroStr;\n FNGetRangeHdl fnGetRange;\n FNGetMacrosOfRangeHdl fnGetMacroOfRange;\n\n BOOL bReadOnly;\n Timer maFillGroupTimer;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -g -triple %itanium_abi_triple -emit-llvm -o - %s | FileCheck %s\n\n\/\/ Make sure that clang outputs distinct debug info for a function\n\/\/ that is inlined twice on the same line. Otherwise it would appear\n\/\/ as if the function was only inlined once.\n\n#define INLINE inline __attribute__((always_inline))\n\nint i;\n\nINLINE void sum(int a, int b) {\n i = a + b;\n}\n\nvoid noinline(int x, int y) {\n i = x + y;\n}\n\n#define CALLS sum(9, 10), sum(11, 12)\n\ninline void inlsum(int t, int u) {\n i = t + u;\n}\n\nint main() {\n sum(1, 2), sum(3, 4);\n noinline(5, 6), noinline(7, 8);\n CALLS;\n inlsum(13, 14), inlsum(15, 16);\n}\n\n\/\/ CHECK-LABEL: @main\n\/\/ CHECK: = add {{.*}} !dbg [[FIRST_INLINE:![0-9]*]]\n\/\/ CHECK: = add {{.*}} !dbg [[SECOND_INLINE:![0-9]*]]\n\n\/\/ Check that we don't give column information (and thus end up with distinct\n\/\/ line entries) for two non-inlined calls on the same line.\n\/\/ CHECK: call {{.*}}noinline{{.*}}({{i32[ ]?[a-z]*}} 5, {{i32[ ]?[a-z]*}} 6), !dbg [[NOINLINE:![0-9]*]]\n\/\/ CHECK: call {{.*}}noinline{{.*}}({{i32[ ]?[a-z]*}} 7, {{i32[ ]?[a-z]*}} 8), !dbg [[NOINLINE]]\n\n\/\/ FIXME: These should be separate locations but because the two calls have the\n\/\/ same line \/and\/ column, they get coalesced into a single inlined call by\n\/\/ accident. We need discriminators or some other changes to LLVM to cope with\n\/\/ this. (this is, unfortunately, an LLVM test disguised as a Clang test - since\n\/\/ inlining is forced to happen here). It's possible this could be fixed in\n\/\/ Clang, but I doubt it'll be the right place for the fix.\n\/\/ CHECK: = add {{.*}} !dbg [[FIRST_MACRO_INLINE:![0-9]*]]\n\/\/ CHECK: = add {{.*}} !dbg [[FIRST_MACRO_INLINE]]\n\n\/\/ Even if the functions are marked inline but do not get inlined, they\n\/\/ shouldn't use column information, and thus should be at the same debug\n\/\/ location.\n\/\/ CHECK: call {{.*}}inlsum{{.*}}({{i32[ ]?[a-z]*}} 13, {{i32[ ]?[a-z]*}} 14), !dbg [[INL_FIRST:![0-9]*]]\n\/\/ CHECK: call {{.*}}inlsum{{.*}}({{i32[ ]?[a-z]*}} 15, {{i32[ ]?[a-z]*}} 16), !dbg [[INL_SECOND:![0-9]*]]\n\n\/\/ [[FIRST_INLINE]] =\n\/\/ [[SECOND_INLINE]] =\n\n\/\/ FIXME: These should be the same location since the functions appear on the\n\/\/ same line and were not inlined - they needlessly have column information\n\/\/ intended to disambiguate inlined calls, which is going to confuse GDB as it\n\/\/ doesn't cope well with column information.\n\/\/ [[INL_FIRST]] =\n\/\/ [[INL_SECOND]] =\n<commit_msg>DebugInfo: Remove distinct-call-inlining test case as this is being fixed in LLVM.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * *\n * I|*j^3Cl|a \"+!*% qt Nd gW *\n * l]{y+l?MM* !#Wla\\NNP NW MM I| *\n * PW ?E| tWg Wg sC! AW ~@v~ *\n * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim *\n * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ *\n * #M aQ? MW M3 Mg Q( HQ YR IM| *\n * Dq {Ql MH iMX Mg MM QP QM Eg *\n * !EWNaPRag2$ +M\" $WNaHaN% MQE$%EXW QQ CM %M%a$D *\n * *\n * Website: https:\/\/github.com\/zpublic\/zpublic *\n * *\n ************************************************************************\/\n\n\/**\n * @file\n * @brief ļͼ\n *\/\n\n\n#pragma once\n#include \"win_utils_header.h\"\n#include <ShlObj.h>\n\nnamespace zl\n{\nnamespace WinUtils\n{\n\n class ZLFileIcon\n {\n public:\n ZLFileIcon(HICON hIcon = NULL) : m_icon(hIcon) {}\n virtual ~ZLFileIcon() { reset(); }\n void reset()\n {\n if (m_icon != NULL)\n {\n ::DestroyIcon(m_icon);\n m_icon = NULL;\n }\n }\n BOOL Load(LPCTSTR szFilePath, BOOL bLargeIcon = TRUE)\n {\n reset();\n BOOL bRet = FALSE;\n SHFILEINFO fileInfo = {0};\n DWORD dwStyle = SHGFI_ICON | SHGFI_USEFILEATTRIBUTES;\n if (bLargeIcon)\n dwStyle |= SHGFI_LARGEICON;\n else\n dwStyle |= SHGFI_SMALLICON;\n\n if (::SHGetFileInfo(szFilePath, 0, &fileInfo, sizeof(fileInfo), dwStyle))\n {\n m_icon = fileInfo.hIcon;\n bRet = TRUE;\n }\n return bRet;\n }\n BOOL LoadEx(LPCTSTR szFilePath, UINT uSize = 48, UINT uIndex = 0)\n {\n reset();\n if (::SHDefExtractIcon(szFilePath, uIndex, 0, &m_icon, NULL, uSize) == S_OK)\n {\n return TRUE;\n }\n else\n {\n return FALSE;\n }\n }\n HICON GetHandle()\n {\n return m_icon;\n }\n\n protected:\n HICON m_icon;\n };\n\n}\n}\n<commit_msg>*file_icon文件注释<commit_after>\/*************************************************************************\n * *\n * I|*j^3Cl|a \"+!*% qt Nd gW *\n * l]{y+l?MM* !#Wla\\NNP NW MM I| *\n * PW ?E| tWg Wg sC! AW ~@v~ *\n * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim *\n * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ *\n * #M aQ? MW M3 Mg Q( HQ YR IM| *\n * Dq {Ql MH iMX Mg MM QP QM Eg *\n * !EWNaPRag2$ +M\" $WNaHaN% MQE$%EXW QQ CM %M%a$D *\n * *\n * Website: https:\/\/github.com\/zpublic\/zpublic *\n * *\n ************************************************************************\/\n\n\/**\n * @file\n * @brief ļͼ\n *\/\n\n\n#pragma once\n#include \"win_utils_header.h\"\n#include <ShlObj.h>\n\nnamespace zl\n{\nnamespace WinUtils\n{\n\t\/**\n\t* @brief ȡļͼ\n\t*\/\n class ZLFileIcon\n {\n public:\n ZLFileIcon(HICON hIcon = NULL) : m_icon(hIcon) {}\n virtual ~ZLFileIcon() { reset(); }\n void reset()\n {\n if (m_icon != NULL)\n {\n ::DestroyIcon(m_icon);\n m_icon = NULL;\n }\n }\n\t\t\/**\n\t\t * @brief ȡļͼ\n\t\t * @param[in] szFilePath ļ·\n\t\t * @param[in] bLargeIcon ǷΪͼ꣬ĬTRUE\n\t\t * @return ɹTRUEʧܷFALSE\n\t\t * @see SHGetFileInfo\n\t\t *\/\n BOOL Load(LPCTSTR szFilePath, BOOL bLargeIcon = TRUE)\n {\n reset();\n BOOL bRet = FALSE;\n SHFILEINFO fileInfo = {0};\n DWORD dwStyle = SHGFI_ICON | SHGFI_USEFILEATTRIBUTES;\n if (bLargeIcon)\n dwStyle |= SHGFI_LARGEICON;\n else\n dwStyle |= SHGFI_SMALLICON;\n\n if (::SHGetFileInfo(szFilePath, 0, &fileInfo, sizeof(fileInfo), dwStyle))\n {\n m_icon = fileInfo.hIcon;\n bRet = TRUE;\n }\n return bRet;\n }\n\t\t\/**\n\t\t * @brief ļȡͼ\n\t\t * @param[in] szFilePath ļ·\n\t\t * @param[in] uSize ͼĴС\n\t\t * @param[in] uIndex szFilePathļͼ\n\t\t * @return ɹTRUEʧܷFALSE\n\t\t * @see SHDefExtractIcon\n\t\t *\/\n BOOL LoadEx(LPCTSTR szFilePath, UINT uSize = 48, UINT uIndex = 0)\n {\n reset();\n if (::SHDefExtractIcon(szFilePath, uIndex, 0, &m_icon, NULL, uSize) == S_OK)\n {\n return TRUE;\n }\n else\n {\n return FALSE;\n }\n }\n HICON GetHandle()\n {\n return m_icon;\n }\n\n protected:\n HICON m_icon;\n };\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef __linux__\n# include <sys\/sendfile.h>\n#endif\n\n#include <cerrno>\n#include <algorithm>\n#include <limits>\n\n#include \"direct-fd-stream.hh\"\n#include \"copy.hh\"\n\nnamespace mimosa\n{\n namespace stream\n {\n DirectFdStream::DirectFdStream(int fd, bool own_fd)\n : fd_(fd),\n own_fd_(own_fd),\n mode_(0)\n {\n }\n\n DirectFdStream::~DirectFdStream()\n {\n if (own_fd_ && fd_ >= 0)\n {\n ::close(fd_);\n fd_ = -1;\n }\n }\n\n int64_t\n DirectFdStream::write(const char * data, uint64_t nbytes)\n {\n return ::write(fd_, data, nbytes);\n }\n\n int64_t\n DirectFdStream::writev(const struct iovec *iov, int iovcnt)\n {\n return ::writev(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX);\n }\n\n int64_t\n DirectFdStream::read(char * data, uint64_t nbytes)\n {\n return ::read(fd_, data, nbytes);\n }\n\n int64_t\n DirectFdStream::readv(const struct iovec *iov, int iovcnt)\n {\n return ::readv(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX);\n }\n\n void\n DirectFdStream::close()\n {\n assert(own_fd_);\n if (own_fd_ && fd_ >= 0)\n {\n int fd = fd_;\n fd_ = -1;\n ::close(fd);\n }\n }\n\n bool\n DirectFdStream::stat() const\n {\n struct ::stat st;\n if (::fstat(fd_, &st))\n return false;\n mode_ = st.st_mode;\n return true;\n }\n\n#ifdef __linux__\n static int64_t copySendfile(DirectFdStream & input,\n DirectFdStream & output,\n int64_t max_bytes)\n {\n int64_t total = 0;\n\n while (total < max_bytes || max_bytes == 0) {\n int64_t limit;\n\n if (max_bytes == 0)\n limit = std::numeric_limits<int64_t>::max();\n else\n limit = max_bytes - total;\n\n ssize_t bytes = ::sendfile(output.fd(), input.fd(), nullptr, limit);\n if (bytes <= 0) {\n if (errno == EAGAIN)\n continue;\n return total;\n }\n total += bytes;\n }\n return total;\n }\n\n static int64_t copySplice(DirectFdStream & input,\n DirectFdStream & output,\n int64_t max_bytes)\n {\n int64_t total = 0;\n\n while (total < max_bytes || max_bytes == 0) {\n int64_t limit;\n\n if (max_bytes == 0)\n limit = std::numeric_limits<int64_t>::max();\n else\n limit = max_bytes - total;\n\n ssize_t bytes = ::splice(input.fd(), nullptr, output.fd(), nullptr, limit, 0);\n if (bytes <= 0) {\n if (errno == EAGAIN)\n continue;\n return total;\n }\n total += bytes;\n }\n return total;\n }\n\n static int64_t copySpliceAny(DirectFdStream & input,\n DirectFdStream & output,\n int64_t max_bytes)\n {\n int pfd[2];\n int64_t total = 0;\n\n if (::pipe2(pfd, O_CLOEXEC | O_NONBLOCK))\n return -1;\n\n while (total < max_bytes || max_bytes == 0) {\n int64_t limit;\n\n if (max_bytes == 0)\n limit = std::numeric_limits<int64_t>::max();\n else\n limit = max_bytes - total;\n\n ssize_t rbytes = ::splice(input.fd(), nullptr, pfd[1], nullptr, limit, 0);\n if (bytes <= 0) {\n if (errno == EAGAIN)\n continue;\n goto end;\n }\n\n while (rbytes > 0) {\n ssize_t wbytes = ::splice(pfd[0], nullptr, output.fd(), nullptr, rbytes, 0);\n if (wbytes < 0) {\n if (errno == EAGAIN)\n continue;\n total = -1;\n goto end;\n }\n\n total += wbytes;\n rbytes -= wbytes;\n }\n }\n\n end:\n ::close(pfd[0]);\n ::close(pfd[1]);\n return total;\n }\n#endif \/\/ __linux__\n\n int64_t copy(DirectFdStream & input,\n DirectFdStream & output,\n int64_t max_bytes)\n {\n\n#ifdef __linux__\n \/\/ disk to fd\n if (S_ISREG(input.fdMode()))\n return copySendfile(input, output, max_bytes);\n\n \/\/ from a pipe or to a pipe\n if (S_ISFIFO(input.fdMode()) || S_ISFIFO(output.fdMode()))\n return copySplice(input, output, max_bytes);\n\n \/\/ splice: input -> pipe -> output\n if (max_bytes == 0 || max_bytes > 4096)\n return copySpliceAny(input, output, max_bytes);\n#endif \/\/ __linux__\n\n \/\/ user copy\n return copy(static_cast<Stream &> (input),\n static_cast<Stream &> (output),\n max_bytes);\n }\n }\n}\n<commit_msg>Fix splice copy<commit_after>#ifdef __linux__\n# include <sys\/sendfile.h>\n#endif\n\n#include <cerrno>\n#include <algorithm>\n#include <limits>\n\n#include \"direct-fd-stream.hh\"\n#include \"copy.hh\"\n\nnamespace mimosa\n{\n namespace stream\n {\n DirectFdStream::DirectFdStream(int fd, bool own_fd)\n : fd_(fd),\n own_fd_(own_fd),\n mode_(0)\n {\n }\n\n DirectFdStream::~DirectFdStream()\n {\n if (own_fd_ && fd_ >= 0)\n {\n ::close(fd_);\n fd_ = -1;\n }\n }\n\n int64_t\n DirectFdStream::write(const char * data, uint64_t nbytes)\n {\n return ::write(fd_, data, nbytes);\n }\n\n int64_t\n DirectFdStream::writev(const struct iovec *iov, int iovcnt)\n {\n return ::writev(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX);\n }\n\n int64_t\n DirectFdStream::read(char * data, uint64_t nbytes)\n {\n return ::read(fd_, data, nbytes);\n }\n\n int64_t\n DirectFdStream::readv(const struct iovec *iov, int iovcnt)\n {\n return ::readv(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX);\n }\n\n void\n DirectFdStream::close()\n {\n assert(own_fd_);\n if (own_fd_ && fd_ >= 0)\n {\n int fd = fd_;\n fd_ = -1;\n ::close(fd);\n }\n }\n\n bool\n DirectFdStream::stat() const\n {\n struct ::stat st;\n if (::fstat(fd_, &st))\n return false;\n mode_ = st.st_mode;\n return true;\n }\n\n#ifdef __linux__\n static int64_t copySendfile(DirectFdStream & input,\n DirectFdStream & output,\n int64_t max_bytes)\n {\n int64_t total = 0;\n\n while (total < max_bytes || max_bytes == 0) {\n int64_t limit;\n\n if (max_bytes == 0)\n limit = std::numeric_limits<int64_t>::max();\n else\n limit = max_bytes - total;\n\n ssize_t bytes = ::sendfile(output.fd(), input.fd(), nullptr, limit);\n if (bytes <= 0) {\n if (errno == EAGAIN)\n continue;\n return total;\n }\n total += bytes;\n }\n return total;\n }\n\n static int64_t copySplice(DirectFdStream & input,\n DirectFdStream & output,\n int64_t max_bytes)\n {\n int64_t total = 0;\n\n while (total < max_bytes || max_bytes == 0) {\n int64_t limit;\n\n if (max_bytes == 0)\n limit = std::numeric_limits<int64_t>::max();\n else\n limit = max_bytes - total;\n\n ssize_t bytes = ::splice(input.fd(), nullptr, output.fd(), nullptr, limit, 0);\n if (bytes <= 0) {\n if (errno == EAGAIN)\n continue;\n return total;\n }\n total += bytes;\n }\n return total;\n }\n\n static int64_t copySpliceAny(DirectFdStream & input,\n DirectFdStream & output,\n int64_t max_bytes)\n {\n int pfd[2];\n int64_t total = 0;\n\n if (::pipe2(pfd, O_CLOEXEC | O_NONBLOCK))\n return -1;\n\n while (total < max_bytes || max_bytes == 0) {\n int64_t limit;\n\n if (max_bytes == 0)\n limit = std::numeric_limits<int64_t>::max();\n else\n limit = max_bytes - total;\n\n ssize_t rbytes = ::splice(input.fd(), nullptr, pfd[1], nullptr, limit, 0);\n if (rbytes <= 0) {\n if (errno == EAGAIN)\n continue;\n goto end;\n }\n\n while (rbytes > 0) {\n ssize_t wbytes = ::splice(pfd[0], nullptr, output.fd(), nullptr, rbytes, 0);\n if (wbytes < 0) {\n if (errno == EAGAIN)\n continue;\n total = -1;\n goto end;\n }\n\n total += wbytes;\n rbytes -= wbytes;\n }\n }\n\n end:\n ::close(pfd[0]);\n ::close(pfd[1]);\n return total;\n }\n#endif \/\/ __linux__\n\n int64_t copy(DirectFdStream & input,\n DirectFdStream & output,\n int64_t max_bytes)\n {\n\n#ifdef __linux__\n \/\/ disk to fd\n if (S_ISREG(input.fdMode()))\n return copySendfile(input, output, max_bytes);\n\n \/\/ from a pipe or to a pipe\n if (S_ISFIFO(input.fdMode()) || S_ISFIFO(output.fdMode()))\n return copySplice(input, output, max_bytes);\n\n \/\/ splice: input -> pipe -> output\n if (max_bytes == 0 || max_bytes > 4096)\n return copySpliceAny(input, output, max_bytes);\n#endif \/\/ __linux__\n\n \/\/ user copy\n return copy(static_cast<Stream &> (input),\n static_cast<Stream &> (output),\n max_bytes);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Flutter 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 \"flutter\/shell\/common\/shell_io_manager.h\"\n\n#include \"flutter\/fml\/message_loop.h\"\n#include \"flutter\/shell\/common\/context_options.h\"\n#include \"third_party\/skia\/include\/gpu\/gl\/GrGLInterface.h\"\n\nnamespace flutter {\n\nsk_sp<GrDirectContext> ShellIOManager::CreateCompatibleResourceLoadingContext(\n GrBackend backend,\n sk_sp<const GrGLInterface> gl_interface) {\n#if !OS_FUCHSIA && SK_GL\n if (backend != GrBackend::kOpenGL_GrBackend) {\n return nullptr;\n }\n\n const auto options = MakeDefaultContextOptions(ContextType::kResource);\n\n if (auto context = GrDirectContext::MakeGL(gl_interface, options)) {\n \/\/ Do not cache textures created by the image decoder. These textures\n \/\/ should be deleted when they are no longer referenced by an SkImage.\n context->setResourceCacheLimit(0);\n return context;\n }\n#endif \/\/ !OS_FUCHSIA && SK_GL\n\n return nullptr;\n}\n\nShellIOManager::ShellIOManager(\n sk_sp<GrDirectContext> resource_context,\n std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch,\n fml::RefPtr<fml::TaskRunner> unref_queue_task_runner,\n std::shared_ptr<impeller::Context> impeller_context,\n fml::TimeDelta unref_queue_drain_delay)\n : resource_context_(std::move(resource_context)),\n resource_context_weak_factory_(\n resource_context_\n ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>(\n resource_context_.get())\n : nullptr),\n unref_queue_(fml::MakeRefCounted<flutter::SkiaUnrefQueue>(\n std::move(unref_queue_task_runner),\n unref_queue_drain_delay,\n resource_context_)),\n is_gpu_disabled_sync_switch_(is_gpu_disabled_sync_switch),\n impeller_context_(std::move(impeller_context)),\n weak_factory_(this) {\n if (!resource_context_) {\n#ifndef OS_FUCHSIA\n FML_DLOG(WARNING) << \"The IO manager was initialized without a resource \"\n \"context. Async texture uploads will be disabled. \"\n \"Expect performance degradation.\";\n#endif \/\/ OS_FUCHSIA\n }\n}\n\nShellIOManager::~ShellIOManager() {\n \/\/ Last chance to drain the IO queue as the platform side reference to the\n \/\/ underlying OpenGL context may be going away.\n is_gpu_disabled_sync_switch_->Execute(\n fml::SyncSwitch::Handlers().SetIfFalse([&] { unref_queue_->Drain(); }));\n}\n\nvoid ShellIOManager::NotifyResourceContextAvailable(\n sk_sp<GrDirectContext> resource_context) {\n \/\/ The resource context needs to survive as long as we have Dart objects\n \/\/ referencing. We shouldn't ever need to replace it if we have one - unless\n \/\/ we've somehow shut down the Dart VM and started a new one fresh.\n if (!resource_context_) {\n UpdateResourceContext(std::move(resource_context));\n }\n}\n\nvoid ShellIOManager::UpdateResourceContext(\n sk_sp<GrDirectContext> resource_context) {\n resource_context_ = std::move(resource_context);\n resource_context_weak_factory_ =\n resource_context_\n ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>(\n resource_context_.get())\n : nullptr;\n unref_queue_->UpdateResourceContext(resource_context_);\n}\n\nfml::WeakPtr<ShellIOManager> ShellIOManager::GetWeakPtr() {\n return weak_factory_.GetWeakPtr();\n}\n\n\/\/ |IOManager|\nfml::WeakPtr<GrDirectContext> ShellIOManager::GetResourceContext() const {\n return resource_context_weak_factory_\n ? resource_context_weak_factory_->GetWeakPtr()\n : fml::WeakPtr<GrDirectContext>();\n}\n\n\/\/ |IOManager|\nfml::RefPtr<flutter::SkiaUnrefQueue> ShellIOManager::GetSkiaUnrefQueue() const {\n return unref_queue_;\n}\n\n\/\/ |IOManager|\nfml::WeakPtr<IOManager> ShellIOManager::GetWeakIOManager() const {\n return weak_factory_.GetWeakPtr();\n}\n\n\/\/ |IOManager|\nstd::shared_ptr<const fml::SyncSwitch>\nShellIOManager::GetIsGpuDisabledSyncSwitch() {\n return is_gpu_disabled_sync_switch_;\n}\n\n\/\/ |IOManager|\nstd::shared_ptr<impeller::Context> ShellIOManager::GetImpellerContext() const {\n return impeller_context_;\n}\n\n} \/\/ namespace flutter\n<commit_msg>Remove IO manager Fuchsia workaround. (#34959)<commit_after>\/\/ Copyright 2013 The Flutter 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 \"flutter\/shell\/common\/shell_io_manager.h\"\n\n#include \"flutter\/fml\/message_loop.h\"\n#include \"flutter\/shell\/common\/context_options.h\"\n#include \"third_party\/skia\/include\/gpu\/gl\/GrGLInterface.h\"\n\nnamespace flutter {\n\nsk_sp<GrDirectContext> ShellIOManager::CreateCompatibleResourceLoadingContext(\n GrBackend backend,\n sk_sp<const GrGLInterface> gl_interface) {\n#if SK_GL\n if (backend != GrBackend::kOpenGL_GrBackend) {\n return nullptr;\n }\n\n const auto options = MakeDefaultContextOptions(ContextType::kResource);\n\n if (auto context = GrDirectContext::MakeGL(gl_interface, options)) {\n \/\/ Do not cache textures created by the image decoder. These textures\n \/\/ should be deleted when they are no longer referenced by an SkImage.\n context->setResourceCacheLimit(0);\n return context;\n }\n#endif \/\/ SK_GL\n\n return nullptr;\n}\n\nShellIOManager::ShellIOManager(\n sk_sp<GrDirectContext> resource_context,\n std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch,\n fml::RefPtr<fml::TaskRunner> unref_queue_task_runner,\n std::shared_ptr<impeller::Context> impeller_context,\n fml::TimeDelta unref_queue_drain_delay)\n : resource_context_(std::move(resource_context)),\n resource_context_weak_factory_(\n resource_context_\n ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>(\n resource_context_.get())\n : nullptr),\n unref_queue_(fml::MakeRefCounted<flutter::SkiaUnrefQueue>(\n std::move(unref_queue_task_runner),\n unref_queue_drain_delay,\n resource_context_)),\n is_gpu_disabled_sync_switch_(is_gpu_disabled_sync_switch),\n impeller_context_(std::move(impeller_context)),\n weak_factory_(this) {\n if (!resource_context_) {\n#ifndef OS_FUCHSIA\n FML_DLOG(WARNING) << \"The IO manager was initialized without a resource \"\n \"context. Async texture uploads will be disabled. \"\n \"Expect performance degradation.\";\n#endif \/\/ OS_FUCHSIA\n }\n}\n\nShellIOManager::~ShellIOManager() {\n \/\/ Last chance to drain the IO queue as the platform side reference to the\n \/\/ underlying OpenGL context may be going away.\n is_gpu_disabled_sync_switch_->Execute(\n fml::SyncSwitch::Handlers().SetIfFalse([&] { unref_queue_->Drain(); }));\n}\n\nvoid ShellIOManager::NotifyResourceContextAvailable(\n sk_sp<GrDirectContext> resource_context) {\n \/\/ The resource context needs to survive as long as we have Dart objects\n \/\/ referencing. We shouldn't ever need to replace it if we have one - unless\n \/\/ we've somehow shut down the Dart VM and started a new one fresh.\n if (!resource_context_) {\n UpdateResourceContext(std::move(resource_context));\n }\n}\n\nvoid ShellIOManager::UpdateResourceContext(\n sk_sp<GrDirectContext> resource_context) {\n resource_context_ = std::move(resource_context);\n resource_context_weak_factory_ =\n resource_context_\n ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>(\n resource_context_.get())\n : nullptr;\n unref_queue_->UpdateResourceContext(resource_context_);\n}\n\nfml::WeakPtr<ShellIOManager> ShellIOManager::GetWeakPtr() {\n return weak_factory_.GetWeakPtr();\n}\n\n\/\/ |IOManager|\nfml::WeakPtr<GrDirectContext> ShellIOManager::GetResourceContext() const {\n return resource_context_weak_factory_\n ? resource_context_weak_factory_->GetWeakPtr()\n : fml::WeakPtr<GrDirectContext>();\n}\n\n\/\/ |IOManager|\nfml::RefPtr<flutter::SkiaUnrefQueue> ShellIOManager::GetSkiaUnrefQueue() const {\n return unref_queue_;\n}\n\n\/\/ |IOManager|\nfml::WeakPtr<IOManager> ShellIOManager::GetWeakIOManager() const {\n return weak_factory_.GetWeakPtr();\n}\n\n\/\/ |IOManager|\nstd::shared_ptr<const fml::SyncSwitch>\nShellIOManager::GetIsGpuDisabledSyncSwitch() {\n return is_gpu_disabled_sync_switch_;\n}\n\n\/\/ |IOManager|\nstd::shared_ptr<impeller::Context> ShellIOManager::GetImpellerContext() const {\n return impeller_context_;\n}\n\n} \/\/ namespace flutter\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %check_clang_tidy %s misc-misplaced-const %t\n\ntypedef int plain_i;\ntypedef int *ip;\ntypedef const int *cip;\n\nvoid func() {\n if (const int *i = 0)\n ;\n if (const plain_i *i = 0)\n ;\n if (const cip i = 0)\n ;\n\n \/\/ CHECK-MESSAGES: :[[@LINE+1]]:16: warning: 'i' declared with a const-qualified typedef type; results in the type being 'int *const' instead of 'const int *'\n if (const ip i = 0)\n ;\n}\n\ntemplate <typename Ty>\nstruct S {\n const Ty *i;\n const Ty &i2;\n};\n\ntemplate struct S<int>;\ntemplate struct S<ip>; \/\/ ok\ntemplate struct S<cip>;\ntemplate struct S<int *>; \/\/ ok\n\nstruct T {\n typedef void (T::*PMF)();\n\n void f() {\n const PMF val = &T::f; \/\/ ok\n }\n};\n<commit_msg>Fixing a build bot issue with duplicate explicit instantiations.<commit_after>\/\/ RUN: %check_clang_tidy %s misc-misplaced-const %t\n\ntypedef int plain_i;\ntypedef int *ip;\ntypedef const int *cip;\n\nvoid func() {\n if (const int *i = 0)\n ;\n if (const plain_i *i = 0)\n ;\n if (const cip i = 0)\n ;\n\n \/\/ CHECK-MESSAGES: :[[@LINE+1]]:16: warning: 'i' declared with a const-qualified typedef type; results in the type being 'int *const' instead of 'const int *'\n if (const ip i = 0)\n ;\n}\n\ntemplate <typename Ty>\nstruct S {\n const Ty *i;\n const Ty &i2;\n};\n\ntemplate struct S<int>;\ntemplate struct S<ip>; \/\/ ok\ntemplate struct S<cip>;\n\ntemplate <typename Ty>\nstruct U {\n const Ty *i;\n const Ty &i2;\n};\n\ntemplate struct U<int *>; \/\/ ok\n\nstruct T {\n typedef void (T::*PMF)();\n\n void f() {\n const PMF val = &T::f; \/\/ ok\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012 Cloudera Inc.\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 \"runtime\/mem-tracker.h\"\n\n#include <boost\/algorithm\/string\/join.hpp>\n#include <google\/malloc_extension.h>\n#include <gutil\/strings\/substitute.h>\n\n#include \"runtime\/exec-env.h\"\n#include \"resourcebroker\/resource-broker.h\"\n#include \"statestore\/query-resource-mgr.h\"\n#include \"util\/debug-util.h\"\n#include \"util\/mem-info.h\"\n#include \"util\/pretty-printer.h\"\n#include \"util\/uid-util.h\"\n\nusing namespace boost;\nusing namespace std;\nusing namespace strings;\n\nnamespace impala {\n\nconst string MemTracker::COUNTER_NAME = \"PeakMemoryUsage\";\nMemTracker::RequestTrackersMap MemTracker::request_to_mem_trackers_;\nMemTracker::PoolTrackersMap MemTracker::pool_to_mem_trackers_;\nmutex MemTracker::static_mem_trackers_lock_;\n\nAtomicInt<int64_t> MemTracker::released_memory_since_gc_;\n\n\/\/ Name for request pool MemTrackers. '$0' is replaced with the pool name.\nconst string REQUEST_POOL_MEM_TRACKER_LABEL_FORMAT = \"RequestPool=$0\";\n\nMemTracker::MemTracker(int64_t byte_limit, int64_t rm_reserved_limit, const string& label,\n MemTracker* parent, bool log_usage_if_zero)\n : limit_(byte_limit),\n rm_reserved_limit_(rm_reserved_limit),\n label_(label),\n parent_(parent),\n consumption_(&local_counter_),\n local_counter_(TUnit::BYTES),\n consumption_metric_(NULL),\n auto_unregister_(false),\n enable_logging_(false),\n log_stack_(false),\n log_usage_if_zero_(log_usage_if_zero),\n query_resource_mgr_(NULL),\n num_gcs_metric_(NULL),\n bytes_freed_by_last_gc_metric_(NULL),\n bytes_over_limit_metric_(NULL) {\n if (parent != NULL) parent_->AddChildTracker(this);\n Init();\n}\n\nMemTracker::MemTracker(\n RuntimeProfile* profile, int64_t byte_limit, int64_t rm_reserved_limit,\n const std::string& label, MemTracker* parent)\n : limit_(byte_limit),\n rm_reserved_limit_(rm_reserved_limit),\n label_(label),\n parent_(parent),\n consumption_(profile->AddHighWaterMarkCounter(COUNTER_NAME, TUnit::BYTES)),\n local_counter_(TUnit::BYTES),\n consumption_metric_(NULL),\n auto_unregister_(false),\n enable_logging_(false),\n log_stack_(false),\n log_usage_if_zero_(true),\n query_resource_mgr_(NULL),\n num_gcs_metric_(NULL),\n bytes_freed_by_last_gc_metric_(NULL),\n bytes_over_limit_metric_(NULL) {\n if (parent != NULL) parent_->AddChildTracker(this);\n Init();\n}\n\nMemTracker::MemTracker(UIntGauge* consumption_metric,\n int64_t byte_limit, int64_t rm_reserved_limit, const string& label)\n : limit_(byte_limit),\n rm_reserved_limit_(rm_reserved_limit),\n label_(label),\n parent_(NULL),\n consumption_(&local_counter_),\n local_counter_(TUnit::BYTES),\n consumption_metric_(consumption_metric),\n auto_unregister_(false),\n enable_logging_(false),\n log_stack_(false),\n log_usage_if_zero_(true),\n query_resource_mgr_(NULL),\n num_gcs_metric_(NULL),\n bytes_freed_by_last_gc_metric_(NULL),\n bytes_over_limit_metric_(NULL) {\n Init();\n}\n\nvoid MemTracker::Init() {\n DCHECK(rm_reserved_limit_ == -1 || limit_ == -1 || rm_reserved_limit_ <= limit_);\n \/\/ populate all_trackers_ and limit_trackers_\n MemTracker* tracker = this;\n while (tracker != NULL) {\n all_trackers_.push_back(tracker);\n if (tracker->has_limit()) limit_trackers_.push_back(tracker);\n tracker = tracker->parent_;\n }\n DCHECK_GT(all_trackers_.size(), 0);\n DCHECK_EQ(all_trackers_[0], this);\n}\n\nvoid MemTracker::AddChildTracker(MemTracker* tracker) {\n lock_guard<mutex> l(child_trackers_lock_);\n tracker->child_tracker_it_ = child_trackers_.insert(child_trackers_.end(), tracker);\n}\n\nvoid MemTracker::UnregisterFromParent() {\n DCHECK(parent_ != NULL);\n lock_guard<mutex> l(parent_->child_trackers_lock_);\n parent_->child_trackers_.erase(child_tracker_it_);\n child_tracker_it_ = parent_->child_trackers_.end();\n}\n\nMemTracker* MemTracker::GetRequestPoolMemTracker(const string& pool_name,\n MemTracker* parent) {\n DCHECK(!pool_name.empty());\n lock_guard<mutex> l(static_mem_trackers_lock_);\n PoolTrackersMap::iterator it = pool_to_mem_trackers_.find(pool_name);\n if (it != pool_to_mem_trackers_.end()) {\n MemTracker* tracker = it->second;\n DCHECK(pool_name == tracker->pool_name_);\n return tracker;\n } else {\n if (parent == NULL) return NULL;\n \/\/ First time this pool_name registered, make a new object.\n MemTracker* tracker = new MemTracker(-1, -1,\n Substitute(REQUEST_POOL_MEM_TRACKER_LABEL_FORMAT, pool_name),\n parent);\n tracker->auto_unregister_ = true;\n tracker->pool_name_ = pool_name;\n pool_to_mem_trackers_[pool_name] = tracker;\n return tracker;\n }\n}\n\nshared_ptr<MemTracker> MemTracker::GetQueryMemTracker(\n const TUniqueId& id, int64_t byte_limit, int64_t rm_reserved_limit, MemTracker* parent,\n QueryResourceMgr* res_mgr) {\n if (byte_limit != -1) {\n if (byte_limit > MemInfo::physical_mem()) {\n LOG(WARNING) << \"Memory limit \"\n << PrettyPrinter::Print(byte_limit, TUnit::BYTES)\n << \" exceeds physical memory of \"\n << PrettyPrinter::Print(MemInfo::physical_mem(), TUnit::BYTES);\n }\n VLOG_QUERY << \"Using query memory limit: \"\n << PrettyPrinter::Print(byte_limit, TUnit::BYTES);\n }\n\n lock_guard<mutex> l(static_mem_trackers_lock_);\n RequestTrackersMap::iterator it = request_to_mem_trackers_.find(id);\n if (it != request_to_mem_trackers_.end()) {\n \/\/ Return the existing MemTracker object for this id, converting the weak ptr\n \/\/ to a shared ptr.\n shared_ptr<MemTracker> tracker = it->second.lock();\n DCHECK_EQ(tracker->limit_, byte_limit);\n DCHECK(id == tracker->query_id_);\n DCHECK(parent == tracker->parent_);\n return tracker;\n } else {\n \/\/ First time this id registered, make a new object. Give a shared ptr to\n \/\/ the caller and put a weak ptr in the map.\n shared_ptr<MemTracker> tracker(new MemTracker(byte_limit, rm_reserved_limit,\n Substitute(\"Query($0) Limit\", lexical_cast<string>(id)), parent));\n tracker->auto_unregister_ = true;\n tracker->query_id_ = id;\n request_to_mem_trackers_[id] = tracker;\n if (res_mgr != NULL) tracker->SetQueryResourceMgr(res_mgr);\n return tracker;\n }\n}\n\nMemTracker::~MemTracker() {\n DCHECK_EQ(consumption(), 0) << \"Leaked memory in \" << this << endl << LogUsage();\n lock_guard<mutex> l(static_mem_trackers_lock_);\n if (auto_unregister_) UnregisterFromParent();\n \/\/ Erase the weak ptr reference from the map.\n request_to_mem_trackers_.erase(query_id_);\n \/\/ Per-pool trackers should live the entire lifetime of the impalad process, but\n \/\/ remove the element from the map in case this changes in the future.\n pool_to_mem_trackers_.erase(pool_name_);\n}\n\nvoid MemTracker::RegisterMetrics(MetricGroup* metrics, const string& prefix) {\n num_gcs_metric_ = metrics->AddCounter(\n Substitute(\"$0.num-gcs\", prefix), 0L, TUnit::UNIT);\n\n \/\/ TODO: Consider a total amount of bytes freed counter\n bytes_freed_by_last_gc_metric_ = metrics->AddGauge<int64_t>(\n Substitute(\"$0.bytes-freed-by-last-gc\", prefix), -1, TUnit::BYTES);\n\n bytes_over_limit_metric_ = metrics->AddGauge<int64_t>(\n Substitute(\"$0.bytes-over-limit\", prefix), -1, TUnit::BYTES);\n}\n\n\/\/ Calling this on the query tracker results in output like:\n\/\/ Query Limit: memory limit exceeded. Limit=100.00 MB Consumption=106.19 MB\n\/\/ Fragment 5b45e83bbc2d92bd:d3ff8a7df7a2f491: Consumption=52.00 KB\n\/\/ AGGREGATION_NODE (id=6): Consumption=44.00 KB\n\/\/ EXCHANGE_NODE (id=5): Consumption=0.00\n\/\/ DataStreamMgr: Consumption=0.00\n\/\/ Fragment 5b45e83bbc2d92bd:d3ff8a7df7a2f492: Consumption=100.00 KB\n\/\/ AGGREGATION_NODE (id=2): Consumption=36.00 KB\n\/\/ AGGREGATION_NODE (id=4): Consumption=40.00 KB\n\/\/ EXCHANGE_NODE (id=3): Consumption=0.00\n\/\/ DataStreamMgr: Consumption=0.00\n\/\/ DataStreamSender: Consumption=16.00 KB\nstring MemTracker::LogUsage(const string& prefix) const {\n if (!log_usage_if_zero_ && consumption() == 0) return \"\";\n\n stringstream ss;\n ss << prefix << label_ << \":\";\n if (CheckLimitExceeded()) ss << \" memory limit exceeded.\";\n if (limit_ > 0) ss << \" Limit=\" << PrettyPrinter::Print(limit_, TUnit::BYTES);\n ss << \" Consumption=\" << PrettyPrinter::Print(consumption(), TUnit::BYTES);\n\n stringstream prefix_ss;\n prefix_ss << prefix << \" \";\n string new_prefix = prefix_ss.str();\n lock_guard<mutex> l(child_trackers_lock_);\n string child_trackers_usage = LogUsage(new_prefix, child_trackers_);\n if (!child_trackers_usage.empty()) ss << \"\\n\" << child_trackers_usage;\n return ss.str();\n}\n\nstring MemTracker::LogUsage(const string& prefix, const list<MemTracker*>& trackers) {\n vector<string> usage_strings;\n for (list<MemTracker*>::const_iterator it = trackers.begin();\n it != trackers.end(); ++it) {\n string usage_string = (*it)->LogUsage(prefix);\n if (!usage_string.empty()) usage_strings.push_back(usage_string);\n }\n return join(usage_strings, \"\\n\");\n}\n\nvoid MemTracker::LogUpdate(bool is_consume, int64_t bytes) const {\n stringstream ss;\n ss << this << \" \" << (is_consume ? \"Consume: \" : \"Release: \") << bytes\n << \" Consumption: \" << consumption() << \" Limit: \" << limit_;\n if (log_stack_) ss << endl << GetStackTrace();\n LOG(ERROR) << ss.str();\n}\n\nbool MemTracker::GcMemory(int64_t max_consumption) {\n if (max_consumption < 0) return true;\n ScopedSpinLock l(&gc_lock_);\n if (consumption_metric_ != NULL) consumption_->Set(consumption_metric_->value());\n uint64_t pre_gc_consumption = consumption();\n \/\/ Check if someone gc'd before us\n if (pre_gc_consumption < max_consumption) return false;\n if (num_gcs_metric_ != NULL) num_gcs_metric_->Increment(1);\n\n \/\/ Try to free up some memory\n for (int i = 0; i < gc_functions_.size(); ++i) {\n gc_functions_[i]();\n if (consumption_metric_ != NULL) consumption_->Set(consumption_metric_->value());\n if (consumption() <= max_consumption) break;\n }\n\n if (bytes_freed_by_last_gc_metric_ != NULL) {\n bytes_freed_by_last_gc_metric_->set_value(pre_gc_consumption - consumption());\n }\n return consumption() > max_consumption;\n}\n\nvoid MemTracker::GcTcmalloc() {\n#ifndef ADDRESS_SANITIZER\n released_memory_since_gc_ = 0;\n MallocExtension::instance()->ReleaseFreeMemory();\n#else\n \/\/ Nothing to do if not using tcmalloc.\n#endif\n}\n\nbool MemTracker::ExpandRmReservation(int64_t bytes) {\n if (query_resource_mgr_ == NULL || rm_reserved_limit_ == -1) return false;\n \/\/ TODO: Make this asynchronous after IO mgr changes to use TryConsume() are done.\n lock_guard<mutex> l(resource_acquisition_lock_);\n int64_t requested = consumption_->current_value() + bytes;\n \/\/ Can't exceed the hard limit under any circumstance\n if (requested >= limit_ && limit_ != -1) return false;\n \/\/ Test to see if we can satisfy the limit anyhow; maybe a different request was already\n \/\/ in flight.\n if (requested < rm_reserved_limit_) return true;\n\n TResourceBrokerExpansionRequest exp;\n query_resource_mgr_->CreateExpansionRequest(max(1L, bytes \/ (1024 * 1024)), 0L, &exp);\n\n TResourceBrokerExpansionResponse response;\n Status status = ExecEnv::GetInstance()->resource_broker()->Expand(exp, &response);\n if (!status.ok()) {\n LOG(INFO) << \"Failed to expand memory limit by \"\n << PrettyPrinter::Print(bytes, TUnit::BYTES) << \": \"\n << status.GetDetail();\n return false;\n }\n\n DCHECK(response.allocated_resources.size() == 1) << \"Got more resources than expected\";\n const llama::TAllocatedResource& resource =\n response.allocated_resources.begin()->second;\n DCHECK(resource.v_cpu_cores == 0L) << \"Unexpected VCPUs returned by Llama\";\n\n \/\/ Finally, check whether the allocation that we got took us over the limits for any of\n \/\/ our ancestors.\n int64_t bytes_allocated = resource.memory_mb * 1024L * 1024L;\n BOOST_FOREACH(const MemTracker* tracker, all_trackers_) {\n if (tracker == this) continue;\n if (tracker->consumption_->current_value() + bytes_allocated > tracker->limit_) {\n \/\/ Don't adjust our limit; rely on query tear-down to release the resource.\n return false;\n }\n }\n\n rm_reserved_limit_ += bytes_allocated;\n \/\/ Resource broker might give us more than we ask for\n if (limit_ != -1) rm_reserved_limit_ = min(rm_reserved_limit_, limit_);\n return true;\n}\n\n}\n<commit_msg>Temporarily removing the DCHECK_EQ(consumption(),0) even from mem-tracker destructor<commit_after>\/\/ Copyright 2012 Cloudera Inc.\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 \"runtime\/mem-tracker.h\"\n\n#include <boost\/algorithm\/string\/join.hpp>\n#include <google\/malloc_extension.h>\n#include <gutil\/strings\/substitute.h>\n\n#include \"runtime\/exec-env.h\"\n#include \"resourcebroker\/resource-broker.h\"\n#include \"statestore\/query-resource-mgr.h\"\n#include \"util\/debug-util.h\"\n#include \"util\/mem-info.h\"\n#include \"util\/pretty-printer.h\"\n#include \"util\/uid-util.h\"\n\nusing namespace boost;\nusing namespace std;\nusing namespace strings;\n\nnamespace impala {\n\nconst string MemTracker::COUNTER_NAME = \"PeakMemoryUsage\";\nMemTracker::RequestTrackersMap MemTracker::request_to_mem_trackers_;\nMemTracker::PoolTrackersMap MemTracker::pool_to_mem_trackers_;\nmutex MemTracker::static_mem_trackers_lock_;\n\nAtomicInt<int64_t> MemTracker::released_memory_since_gc_;\n\n\/\/ Name for request pool MemTrackers. '$0' is replaced with the pool name.\nconst string REQUEST_POOL_MEM_TRACKER_LABEL_FORMAT = \"RequestPool=$0\";\n\nMemTracker::MemTracker(int64_t byte_limit, int64_t rm_reserved_limit, const string& label,\n MemTracker* parent, bool log_usage_if_zero)\n : limit_(byte_limit),\n rm_reserved_limit_(rm_reserved_limit),\n label_(label),\n parent_(parent),\n consumption_(&local_counter_),\n local_counter_(TUnit::BYTES),\n consumption_metric_(NULL),\n auto_unregister_(false),\n enable_logging_(false),\n log_stack_(false),\n log_usage_if_zero_(log_usage_if_zero),\n query_resource_mgr_(NULL),\n num_gcs_metric_(NULL),\n bytes_freed_by_last_gc_metric_(NULL),\n bytes_over_limit_metric_(NULL) {\n if (parent != NULL) parent_->AddChildTracker(this);\n Init();\n}\n\nMemTracker::MemTracker(\n RuntimeProfile* profile, int64_t byte_limit, int64_t rm_reserved_limit,\n const std::string& label, MemTracker* parent)\n : limit_(byte_limit),\n rm_reserved_limit_(rm_reserved_limit),\n label_(label),\n parent_(parent),\n consumption_(profile->AddHighWaterMarkCounter(COUNTER_NAME, TUnit::BYTES)),\n local_counter_(TUnit::BYTES),\n consumption_metric_(NULL),\n auto_unregister_(false),\n enable_logging_(false),\n log_stack_(false),\n log_usage_if_zero_(true),\n query_resource_mgr_(NULL),\n num_gcs_metric_(NULL),\n bytes_freed_by_last_gc_metric_(NULL),\n bytes_over_limit_metric_(NULL) {\n if (parent != NULL) parent_->AddChildTracker(this);\n Init();\n}\n\nMemTracker::MemTracker(UIntGauge* consumption_metric,\n int64_t byte_limit, int64_t rm_reserved_limit, const string& label)\n : limit_(byte_limit),\n rm_reserved_limit_(rm_reserved_limit),\n label_(label),\n parent_(NULL),\n consumption_(&local_counter_),\n local_counter_(TUnit::BYTES),\n consumption_metric_(consumption_metric),\n auto_unregister_(false),\n enable_logging_(false),\n log_stack_(false),\n log_usage_if_zero_(true),\n query_resource_mgr_(NULL),\n num_gcs_metric_(NULL),\n bytes_freed_by_last_gc_metric_(NULL),\n bytes_over_limit_metric_(NULL) {\n Init();\n}\n\nvoid MemTracker::Init() {\n DCHECK(rm_reserved_limit_ == -1 || limit_ == -1 || rm_reserved_limit_ <= limit_);\n \/\/ populate all_trackers_ and limit_trackers_\n MemTracker* tracker = this;\n while (tracker != NULL) {\n all_trackers_.push_back(tracker);\n if (tracker->has_limit()) limit_trackers_.push_back(tracker);\n tracker = tracker->parent_;\n }\n DCHECK_GT(all_trackers_.size(), 0);\n DCHECK_EQ(all_trackers_[0], this);\n}\n\nvoid MemTracker::AddChildTracker(MemTracker* tracker) {\n lock_guard<mutex> l(child_trackers_lock_);\n tracker->child_tracker_it_ = child_trackers_.insert(child_trackers_.end(), tracker);\n}\n\nvoid MemTracker::UnregisterFromParent() {\n DCHECK(parent_ != NULL);\n lock_guard<mutex> l(parent_->child_trackers_lock_);\n parent_->child_trackers_.erase(child_tracker_it_);\n child_tracker_it_ = parent_->child_trackers_.end();\n}\n\nMemTracker* MemTracker::GetRequestPoolMemTracker(const string& pool_name,\n MemTracker* parent) {\n DCHECK(!pool_name.empty());\n lock_guard<mutex> l(static_mem_trackers_lock_);\n PoolTrackersMap::iterator it = pool_to_mem_trackers_.find(pool_name);\n if (it != pool_to_mem_trackers_.end()) {\n MemTracker* tracker = it->second;\n DCHECK(pool_name == tracker->pool_name_);\n return tracker;\n } else {\n if (parent == NULL) return NULL;\n \/\/ First time this pool_name registered, make a new object.\n MemTracker* tracker = new MemTracker(-1, -1,\n Substitute(REQUEST_POOL_MEM_TRACKER_LABEL_FORMAT, pool_name),\n parent);\n tracker->auto_unregister_ = true;\n tracker->pool_name_ = pool_name;\n pool_to_mem_trackers_[pool_name] = tracker;\n return tracker;\n }\n}\n\nshared_ptr<MemTracker> MemTracker::GetQueryMemTracker(\n const TUniqueId& id, int64_t byte_limit, int64_t rm_reserved_limit, MemTracker* parent,\n QueryResourceMgr* res_mgr) {\n if (byte_limit != -1) {\n if (byte_limit > MemInfo::physical_mem()) {\n LOG(WARNING) << \"Memory limit \"\n << PrettyPrinter::Print(byte_limit, TUnit::BYTES)\n << \" exceeds physical memory of \"\n << PrettyPrinter::Print(MemInfo::physical_mem(), TUnit::BYTES);\n }\n VLOG_QUERY << \"Using query memory limit: \"\n << PrettyPrinter::Print(byte_limit, TUnit::BYTES);\n }\n\n lock_guard<mutex> l(static_mem_trackers_lock_);\n RequestTrackersMap::iterator it = request_to_mem_trackers_.find(id);\n if (it != request_to_mem_trackers_.end()) {\n \/\/ Return the existing MemTracker object for this id, converting the weak ptr\n \/\/ to a shared ptr.\n shared_ptr<MemTracker> tracker = it->second.lock();\n DCHECK_EQ(tracker->limit_, byte_limit);\n DCHECK(id == tracker->query_id_);\n DCHECK(parent == tracker->parent_);\n return tracker;\n } else {\n \/\/ First time this id registered, make a new object. Give a shared ptr to\n \/\/ the caller and put a weak ptr in the map.\n shared_ptr<MemTracker> tracker(new MemTracker(byte_limit, rm_reserved_limit,\n Substitute(\"Query($0) Limit\", lexical_cast<string>(id)), parent));\n tracker->auto_unregister_ = true;\n tracker->query_id_ = id;\n request_to_mem_trackers_[id] = tracker;\n if (res_mgr != NULL) tracker->SetQueryResourceMgr(res_mgr);\n return tracker;\n }\n}\n\nMemTracker::~MemTracker() {\n lock_guard<mutex> l(static_mem_trackers_lock_);\n if (auto_unregister_) UnregisterFromParent();\n \/\/ Erase the weak ptr reference from the map.\n request_to_mem_trackers_.erase(query_id_);\n \/\/ Per-pool trackers should live the entire lifetime of the impalad process, but\n \/\/ remove the element from the map in case this changes in the future.\n pool_to_mem_trackers_.erase(pool_name_);\n}\n\nvoid MemTracker::RegisterMetrics(MetricGroup* metrics, const string& prefix) {\n num_gcs_metric_ = metrics->AddCounter(\n Substitute(\"$0.num-gcs\", prefix), 0L, TUnit::UNIT);\n\n \/\/ TODO: Consider a total amount of bytes freed counter\n bytes_freed_by_last_gc_metric_ = metrics->AddGauge<int64_t>(\n Substitute(\"$0.bytes-freed-by-last-gc\", prefix), -1, TUnit::BYTES);\n\n bytes_over_limit_metric_ = metrics->AddGauge<int64_t>(\n Substitute(\"$0.bytes-over-limit\", prefix), -1, TUnit::BYTES);\n}\n\n\/\/ Calling this on the query tracker results in output like:\n\/\/ Query Limit: memory limit exceeded. Limit=100.00 MB Consumption=106.19 MB\n\/\/ Fragment 5b45e83bbc2d92bd:d3ff8a7df7a2f491: Consumption=52.00 KB\n\/\/ AGGREGATION_NODE (id=6): Consumption=44.00 KB\n\/\/ EXCHANGE_NODE (id=5): Consumption=0.00\n\/\/ DataStreamMgr: Consumption=0.00\n\/\/ Fragment 5b45e83bbc2d92bd:d3ff8a7df7a2f492: Consumption=100.00 KB\n\/\/ AGGREGATION_NODE (id=2): Consumption=36.00 KB\n\/\/ AGGREGATION_NODE (id=4): Consumption=40.00 KB\n\/\/ EXCHANGE_NODE (id=3): Consumption=0.00\n\/\/ DataStreamMgr: Consumption=0.00\n\/\/ DataStreamSender: Consumption=16.00 KB\nstring MemTracker::LogUsage(const string& prefix) const {\n if (!log_usage_if_zero_ && consumption() == 0) return \"\";\n\n stringstream ss;\n ss << prefix << label_ << \":\";\n if (CheckLimitExceeded()) ss << \" memory limit exceeded.\";\n if (limit_ > 0) ss << \" Limit=\" << PrettyPrinter::Print(limit_, TUnit::BYTES);\n ss << \" Consumption=\" << PrettyPrinter::Print(consumption(), TUnit::BYTES);\n\n stringstream prefix_ss;\n prefix_ss << prefix << \" \";\n string new_prefix = prefix_ss.str();\n lock_guard<mutex> l(child_trackers_lock_);\n string child_trackers_usage = LogUsage(new_prefix, child_trackers_);\n if (!child_trackers_usage.empty()) ss << \"\\n\" << child_trackers_usage;\n return ss.str();\n}\n\nstring MemTracker::LogUsage(const string& prefix, const list<MemTracker*>& trackers) {\n vector<string> usage_strings;\n for (list<MemTracker*>::const_iterator it = trackers.begin();\n it != trackers.end(); ++it) {\n string usage_string = (*it)->LogUsage(prefix);\n if (!usage_string.empty()) usage_strings.push_back(usage_string);\n }\n return join(usage_strings, \"\\n\");\n}\n\nvoid MemTracker::LogUpdate(bool is_consume, int64_t bytes) const {\n stringstream ss;\n ss << this << \" \" << (is_consume ? \"Consume: \" : \"Release: \") << bytes\n << \" Consumption: \" << consumption() << \" Limit: \" << limit_;\n if (log_stack_) ss << endl << GetStackTrace();\n LOG(ERROR) << ss.str();\n}\n\nbool MemTracker::GcMemory(int64_t max_consumption) {\n if (max_consumption < 0) return true;\n ScopedSpinLock l(&gc_lock_);\n if (consumption_metric_ != NULL) consumption_->Set(consumption_metric_->value());\n uint64_t pre_gc_consumption = consumption();\n \/\/ Check if someone gc'd before us\n if (pre_gc_consumption < max_consumption) return false;\n if (num_gcs_metric_ != NULL) num_gcs_metric_->Increment(1);\n\n \/\/ Try to free up some memory\n for (int i = 0; i < gc_functions_.size(); ++i) {\n gc_functions_[i]();\n if (consumption_metric_ != NULL) consumption_->Set(consumption_metric_->value());\n if (consumption() <= max_consumption) break;\n }\n\n if (bytes_freed_by_last_gc_metric_ != NULL) {\n bytes_freed_by_last_gc_metric_->set_value(pre_gc_consumption - consumption());\n }\n return consumption() > max_consumption;\n}\n\nvoid MemTracker::GcTcmalloc() {\n#ifndef ADDRESS_SANITIZER\n released_memory_since_gc_ = 0;\n MallocExtension::instance()->ReleaseFreeMemory();\n#else\n \/\/ Nothing to do if not using tcmalloc.\n#endif\n}\n\nbool MemTracker::ExpandRmReservation(int64_t bytes) {\n if (query_resource_mgr_ == NULL || rm_reserved_limit_ == -1) return false;\n \/\/ TODO: Make this asynchronous after IO mgr changes to use TryConsume() are done.\n lock_guard<mutex> l(resource_acquisition_lock_);\n int64_t requested = consumption_->current_value() + bytes;\n \/\/ Can't exceed the hard limit under any circumstance\n if (requested >= limit_ && limit_ != -1) return false;\n \/\/ Test to see if we can satisfy the limit anyhow; maybe a different request was already\n \/\/ in flight.\n if (requested < rm_reserved_limit_) return true;\n\n TResourceBrokerExpansionRequest exp;\n query_resource_mgr_->CreateExpansionRequest(max(1L, bytes \/ (1024 * 1024)), 0L, &exp);\n\n TResourceBrokerExpansionResponse response;\n Status status = ExecEnv::GetInstance()->resource_broker()->Expand(exp, &response);\n if (!status.ok()) {\n LOG(INFO) << \"Failed to expand memory limit by \"\n << PrettyPrinter::Print(bytes, TUnit::BYTES) << \": \"\n << status.GetDetail();\n return false;\n }\n\n DCHECK(response.allocated_resources.size() == 1) << \"Got more resources than expected\";\n const llama::TAllocatedResource& resource =\n response.allocated_resources.begin()->second;\n DCHECK(resource.v_cpu_cores == 0L) << \"Unexpected VCPUs returned by Llama\";\n\n \/\/ Finally, check whether the allocation that we got took us over the limits for any of\n \/\/ our ancestors.\n int64_t bytes_allocated = resource.memory_mb * 1024L * 1024L;\n BOOST_FOREACH(const MemTracker* tracker, all_trackers_) {\n if (tracker == this) continue;\n if (tracker->consumption_->current_value() + bytes_allocated > tracker->limit_) {\n \/\/ Don't adjust our limit; rely on query tear-down to release the resource.\n return false;\n }\n }\n\n rm_reserved_limit_ += bytes_allocated;\n \/\/ Resource broker might give us more than we ask for\n if (limit_ != -1) rm_reserved_limit_ = min(rm_reserved_limit_, limit_);\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n This is a library for the BNO055 orientation sensor\n\n Designed specifically to work with the Adafruit BNO055 Breakout.\n\n Pick one up today in the adafruit shop!\n ------> http:\/\/www.adafruit.com\/products\n\n These sensors use I2C to communicate, 2 pins are required to interface.\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit andopen-source hardware by purchasing products\n from Adafruit!\n\n Written by KTOWN for Adafruit Industries.\n\n MIT license, all text above must be included in any redistribution\n ***************************************************************************\/\n\n#if ARDUINO >= 100\n #include \"Arduino.h\"\n#else\n #include \"WProgram.h\"\n#endif\n\n#include <math.h>\n#include <limits.h>\n\n#include \"Adafruit_BNO055.h\"\n\n\/***************************************************************************\n CONSTRUCTOR\n ***************************************************************************\/\n \n\/**************************************************************************\/\n\/*!\n @brief Instantiates a new Adafruit_BNO055 class\n*\/\n\/**************************************************************************\/\nAdafruit_BNO055::Adafruit_BNO055(int32_t sensorID, uint8_t address)\n{\n _sensorID = sensorID;\n _address = address;\n}\n\n\/***************************************************************************\n PUBLIC FUNCTIONS\n ***************************************************************************\/\n\n\/**************************************************************************\/\n\/*!\n @brief Sets up the HW\n*\/\n\/**************************************************************************\/\nbool Adafruit_BNO055::begin(adafruit_bno055_opmode_t mode)\n{\n \/* Enable I2C *\/\n Wire.begin();\n\n \/* Make sure we have the right device *\/\n uint8_t id = read8(BNO055_CHIP_ID_ADDR);\n if(id != BNO055_ID)\n {\n delay(1000); \/\/ hold on for boot\n if(id != BNO055_ID) {\n return false; \/\/ still not? ok bail\n }\n }\n\n \/* Switch to config mode (just in case since this is the default) *\/\n setMode(OPERATION_MODE_CONFIG);\n\n \/* Reset *\/\n write8(BNO055_SYS_TRIGGER_ADDR, 0x20);\n while (read8(BNO055_CHIP_ID_ADDR) != BNO055_ID)\n {\n delay(10);\n }\n delay(50);\n \n \/* Set to normal power mode *\/\n write8(BNO055_PWR_MODE_ADDR, POWER_MODE_NORMAL);\n delay(10);\n\n write8(BNO055_PAGE_ID_ADDR, 0);\n \n \/* Set the output units *\/\n \/*\n uint8_t unitsel = (0 << 7) | \/\/ Orientation = Android\n (0 << 4) | \/\/ Temperature = Celsius\n (0 << 2) | \/\/ Euler = Degrees\n (1 << 1) | \/\/ Gyro = Rads\n (0 << 0); \/\/ Accelerometer = m\/s^2\n write8(BNO055_UNIT_SEL_ADDR, unitsel);\n *\/\n\n write8(BNO055_SYS_TRIGGER_ADDR, 0x0);\n delay(10);\n \/* Set the requested operating mode (see section 3.3) *\/\n setMode(mode);\n delay(20);\n\n return true;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Puts the chip in the specified operating mode\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::setMode(adafruit_bno055_opmode_t mode)\n{\n _mode = mode;\n write8(BNO055_OPR_MODE_ADDR, _mode);\n delay(30);\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Use the external 32.768KHz crystal\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::setExtCrystalUse(boolean usextal)\n{\n adafruit_bno055_opmode_t modeback = _mode;\n\n \/* Switch to config mode (just in case since this is the default) *\/\n setMode(OPERATION_MODE_CONFIG);\n delay(25);\n write8(BNO055_PAGE_ID_ADDR, 0);\n if (usextal) {\n write8(BNO055_SYS_TRIGGER_ADDR, 0x80);\n } else {\n write8(BNO055_SYS_TRIGGER_ADDR, 0x00);\n }\n delay(10);\n \/* Set the requested operating mode (see section 3.3) *\/\n setMode(modeback);\n delay(20);\n}\n\n\n\/**************************************************************************\/\n\/*!\n @brief Gets the latest system status info\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::getSystemStatus(uint8_t *system_status, uint8_t *self_test_result, uint8_t *system_error)\n{\n adafruit_bno055_opmode_t backupmode = _mode;\n\n setMode(OPERATION_MODE_CONFIG);\n delay(20);\n write8(BNO055_PAGE_ID_ADDR, 0);\n\n write8(BNO055_SYS_TRIGGER_ADDR, read8(BNO055_SYS_TRIGGER_ADDR) | 0x1);\n delay(1000);\n \n \/* System Status (see section 4.3.58)\n ---------------------------------\n 0 = Idle\n 1 = System Error\n 2 = Initializing Peripherals\n 3 = System Iniitalization\n 4 = Executing Self-Test\n 5 = Sensor fusio algorithm running\n 6 = System running without fusion algorithms *\/\n \n if (system_status != 0)\n *system_status = read8(BNO055_SYS_STAT_ADDR);\n \n \/* Self Test Results (see section )\n --------------------------------\n 1 = test passed, 0 = test failed\n \n Bit 0 = Accelerometer self test\n Bit 1 = Magnetometer self test\n Bit 2 = Gyroscope self test\n Bit 3 = MCU self test\n\n 0x0F = all good! *\/\n \n if (self_test_result != 0)\n *self_test_result = read8(BNO055_SELFTEST_RESULT_ADDR);\n\n \/* System Error (see section 4.3.59)\n ---------------------------------\n 0 = No error\n 1 = Peripheral initialization error\n 2 = System initialization error\n 3 = Self test result failed\n 4 = Register map value out of range\n 5 = Register map address out of range\n 6 = Register map write error\n 7 = BNO low power mode not available for selected operat ion mode\n 8 = Accelerometer power mode not available\n 9 = Fusion algorithm configuration error\n A = Sensor configuration error *\/\n \n if (system_error != 0)\n *system_error = read8(BNO055_SYS_ERR_ADDR);\n\n setMode(backupmode);\n delay(20);\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Gets the chip revision numbers\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::getRevInfo(adafruit_bno055_rev_info_t* info)\n{\n uint8_t a, b;\n\n memset(info, 0, sizeof(adafruit_bno055_rev_info_t));\n\n \/* Check the accelerometer revision *\/\n info->accel_rev = read8(BNO055_ACCEL_REV_ID_ADDR);\n\n \/* Check the magnetometer revision *\/\n info->mag_rev = read8(BNO055_MAG_REV_ID_ADDR);\n\n \/* Check the gyroscope revision *\/\n info->gyro_rev = read8(BNO055_GYRO_REV_ID_ADDR);\n\n \/* Check the SW revision *\/\n info->bl_rev = read8(BNO055_BL_REV_ID_ADDR);\n \n a = read8(BNO055_SW_REV_ID_LSB_ADDR);\n b = read8(BNO055_SW_REV_ID_MSB_ADDR);\n info->sw_rev = (((uint16_t)b) << 8) | ((uint16_t)a);\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Gets teh temperature in degrees celsius\n*\/\n\/**************************************************************************\/\nint8_t Adafruit_BNO055::getTemp(void)\n{\n int8_t temp = (int8_t)(read8(BNO055_TEMP_ADDR));\n return temp;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Gets a vector reading from the specified source\n*\/\n\/**************************************************************************\/\nimu::Vector<3> Adafruit_BNO055::getVector(adafruit_vector_type_t vector_type)\n{\n imu::Vector<3> xyz;\n uint8_t buffer[6];\n memset (buffer, 0, 6);\n \n int16_t x, y, z;\n x = y = z = 0;\n \n \/* Read vector data (6 bytes) *\/\n readLen((adafruit_bno055_reg_t)vector_type, buffer, 6);\n \n x = ((int16_t)buffer[0]) | (((int16_t)buffer[1]) << 8);\n y = ((int16_t)buffer[2]) | (((int16_t)buffer[3]) << 8);\n z = ((int16_t)buffer[4]) | (((int16_t)buffer[5]) << 8);\n\n \/* Convert the value to an appropriate range (section 3.6.4) *\/\n \/* and assign the value to the Vector type *\/\n switch(vector_type)\n {\n case VECTOR_MAGNETOMETER:\n \/* 1uT = 16 LSB *\/\n xyz[0] = ((double)x)\/16.0;\n xyz[1] = ((double)y)\/16.0;\n xyz[2] = ((double)z)\/16.0;\n break;\n case VECTOR_GYROSCOPE:\n \/* 1rps = 900 LSB *\/\n xyz[0] = ((double)x)\/900.0;\n xyz[1] = ((double)y)\/900.0;\n xyz[2] = ((double)z)\/900.0;\n break;\n case VECTOR_EULER:\n \/* 1 degree = 16 LSB *\/\n xyz[0] = ((double)x)\/16.0;\n xyz[1] = ((double)y)\/16.0;\n xyz[2] = ((double)z)\/16.0;\n break;\n case VECTOR_ACCELEROMETER:\n case VECTOR_LINEARACCEL:\n case VECTOR_GRAVITY:\n \/* 1m\/s^2 = 100 LSB *\/\n xyz[0] = ((double)x)\/100.0;\n xyz[1] = ((double)y)\/100.0;\n xyz[2] = ((double)z)\/100.0;\n break;\n }\n \n return xyz;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Gets a quaternion reading from the specified source\n*\/\n\/**************************************************************************\/\nimu::Quaternion Adafruit_BNO055::getQuat(void)\n{\n uint8_t buffer[8];\n memset (buffer, 0, 8);\n \n int16_t x, y, z, w;\n x = y = z = w = 0;\n \n \/* Read quat data (8 bytes) *\/\n readLen(BNO055_QUATERNION_DATA_W_LSB_ADDR, buffer, 8);\n w = (((uint16_t)buffer[1]) << 8) | ((uint16_t)buffer[0]);\n x = (((uint16_t)buffer[3]) << 8) | ((uint16_t)buffer[2]);\n y = (((uint16_t)buffer[5]) << 8) | ((uint16_t)buffer[4]);\n z = (((uint16_t)buffer[7]) << 8) | ((uint16_t)buffer[6]);\n\n \/* Assign to Quaternion *\/\n imu::Quaternion quat((double)w, (double)x, (double)y, (double)z);\n return quat;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Provides the sensor_t data for this sensor\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::getSensor(sensor_t *sensor)\n{\n \/* Clear the sensor_t object *\/\n memset(sensor, 0, sizeof(sensor_t));\n\n \/* Insert the sensor name in the fixed length char array *\/\n strncpy (sensor->name, \"BNO055\", sizeof(sensor->name) - 1);\n sensor->name[sizeof(sensor->name)- 1] = 0;\n sensor->version = 1;\n sensor->sensor_id = _sensorID;\n sensor->type = SENSOR_TYPE_ORIENTATION;\n sensor->min_delay = 0;\n sensor->max_value = 0.0F;\n sensor->min_value = 0.0F;\n sensor->resolution = 0.01F;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Reads the sensor and returns the data as a sensors_event_t\n*\/\n\/**************************************************************************\/\nbool Adafruit_BNO055::getEvent(sensors_event_t *event)\n{\n \/* Clear the event *\/\n memset(event, 0, sizeof(sensors_event_t));\n\n event->version = sizeof(sensors_event_t);\n event->sensor_id = _sensorID;\n event->type = SENSOR_TYPE_ORIENTATION;\n event->timestamp = millis();\n\n \/* Get a Euler angle sample for orientation *\/\n imu::Vector<3> euler = getVector(Adafruit_BNO055::VECTOR_EULER);\n event->orientation.x = euler.x();\n event->orientation.y = euler.y();\n event->orientation.z = euler.z();\n\n return true;\n}\n\n\/***************************************************************************\n PRIVATE FUNCTIONS\n ***************************************************************************\/\n\n\/**************************************************************************\/\n\/*!\n @brief Writes an 8 bit value over I2C\n*\/\n\/**************************************************************************\/\nbool Adafruit_BNO055::write8(adafruit_bno055_reg_t reg, byte value)\n{\n Wire.beginTransmission(_address);\n #if ARDUINO >= 100\n Wire.write((uint8_t)reg);\n Wire.write((uint8_t)value);\n #else\n Wire.send(reg);\n Wire.send(value);\n #endif\n Wire.endTransmission();\n\n \/* ToDo: Check for error! *\/\n return true;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Reads an 8 bit value over I2C\n*\/\n\/**************************************************************************\/\nbyte Adafruit_BNO055::read8(adafruit_bno055_reg_t reg )\n{\n byte value = 0;\n \n Wire.beginTransmission(_address);\n #if ARDUINO >= 100\n Wire.write((uint8_t)reg);\n #else\n Wire.send(reg);\n #endif\n Wire.endTransmission();\n Wire.requestFrom(_address, (byte)1);\n #if ARDUINO >= 100\n value = Wire.read();\n #else\n value = Wire.receive();\n #endif\n \n return value;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Reads the specified number of bytes over I2C\n*\/\n\/**************************************************************************\/\nbool Adafruit_BNO055::readLen(adafruit_bno055_reg_t reg, byte * buffer, uint8_t len)\n{\n Wire.beginTransmission(_address);\n #if ARDUINO >= 100\n Wire.write((uint8_t)reg);\n #else\n Wire.send(reg);\n #endif\n Wire.endTransmission();\n Wire.requestFrom(_address, (byte)len);\n\n \/* Wait until data is available *\/\n while (Wire.available() < len);\n \n for (uint8_t i = 0; i < len; i++)\n {\n #if ARDUINO >= 100\n buffer[i] = Wire.read();\n #else\n buffer[i] = Wire.receive();\n #endif\n }\n \n \/* ToDo: Check for errors! *\/\n return true;\n}\n<commit_msg>Bug fixes for getQuat() and begin()<commit_after>\/***************************************************************************\n This is a library for the BNO055 orientation sensor\n\n Designed specifically to work with the Adafruit BNO055 Breakout.\n\n Pick one up today in the adafruit shop!\n ------> http:\/\/www.adafruit.com\/products\n\n These sensors use I2C to communicate, 2 pins are required to interface.\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit andopen-source hardware by purchasing products\n from Adafruit!\n\n Written by KTOWN for Adafruit Industries.\n\n MIT license, all text above must be included in any redistribution\n ***************************************************************************\/\n\n#if ARDUINO >= 100\n #include \"Arduino.h\"\n#else\n #include \"WProgram.h\"\n#endif\n\n#include <math.h>\n#include <limits.h>\n\n#include \"Adafruit_BNO055.h\"\n\n\/***************************************************************************\n CONSTRUCTOR\n ***************************************************************************\/\n \n\/**************************************************************************\/\n\/*!\n @brief Instantiates a new Adafruit_BNO055 class\n*\/\n\/**************************************************************************\/\nAdafruit_BNO055::Adafruit_BNO055(int32_t sensorID, uint8_t address)\n{\n _sensorID = sensorID;\n _address = address;\n}\n\n\/***************************************************************************\n PUBLIC FUNCTIONS\n ***************************************************************************\/\n\n\/**************************************************************************\/\n\/*!\n @brief Sets up the HW\n*\/\n\/**************************************************************************\/\nbool Adafruit_BNO055::begin(adafruit_bno055_opmode_t mode)\n{\n \/* Enable I2C *\/\n Wire.begin();\n\n \/* Make sure we have the right device *\/\n uint8_t id = read8(BNO055_CHIP_ID_ADDR);\n if(id != BNO055_ID)\n {\n delay(1000); \/\/ hold on for boot\n id = read8(BNO055_CHIP_ID_ADDR);\n if(id != BNO055_ID) {\n return false; \/\/ still not? ok bail\n }\n }\n\n \/* Switch to config mode (just in case since this is the default) *\/\n setMode(OPERATION_MODE_CONFIG);\n\n \/* Reset *\/\n write8(BNO055_SYS_TRIGGER_ADDR, 0x20);\n while (read8(BNO055_CHIP_ID_ADDR) != BNO055_ID)\n {\n delay(10);\n }\n delay(50);\n \n \/* Set to normal power mode *\/\n write8(BNO055_PWR_MODE_ADDR, POWER_MODE_NORMAL);\n delay(10);\n\n write8(BNO055_PAGE_ID_ADDR, 0);\n \n \/* Set the output units *\/\n \/*\n uint8_t unitsel = (0 << 7) | \/\/ Orientation = Android\n (0 << 4) | \/\/ Temperature = Celsius\n (0 << 2) | \/\/ Euler = Degrees\n (1 << 1) | \/\/ Gyro = Rads\n (0 << 0); \/\/ Accelerometer = m\/s^2\n write8(BNO055_UNIT_SEL_ADDR, unitsel);\n *\/\n\n write8(BNO055_SYS_TRIGGER_ADDR, 0x0);\n delay(10);\n \/* Set the requested operating mode (see section 3.3) *\/\n setMode(mode);\n delay(20);\n\n return true;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Puts the chip in the specified operating mode\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::setMode(adafruit_bno055_opmode_t mode)\n{\n _mode = mode;\n write8(BNO055_OPR_MODE_ADDR, _mode);\n delay(30);\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Use the external 32.768KHz crystal\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::setExtCrystalUse(boolean usextal)\n{\n adafruit_bno055_opmode_t modeback = _mode;\n\n \/* Switch to config mode (just in case since this is the default) *\/\n setMode(OPERATION_MODE_CONFIG);\n delay(25);\n write8(BNO055_PAGE_ID_ADDR, 0);\n if (usextal) {\n write8(BNO055_SYS_TRIGGER_ADDR, 0x80);\n } else {\n write8(BNO055_SYS_TRIGGER_ADDR, 0x00);\n }\n delay(10);\n \/* Set the requested operating mode (see section 3.3) *\/\n setMode(modeback);\n delay(20);\n}\n\n\n\/**************************************************************************\/\n\/*!\n @brief Gets the latest system status info\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::getSystemStatus(uint8_t *system_status, uint8_t *self_test_result, uint8_t *system_error)\n{\n adafruit_bno055_opmode_t backupmode = _mode;\n\n setMode(OPERATION_MODE_CONFIG);\n delay(20);\n write8(BNO055_PAGE_ID_ADDR, 0);\n\n write8(BNO055_SYS_TRIGGER_ADDR, read8(BNO055_SYS_TRIGGER_ADDR) | 0x1);\n delay(1000);\n \n \/* System Status (see section 4.3.58)\n ---------------------------------\n 0 = Idle\n 1 = System Error\n 2 = Initializing Peripherals\n 3 = System Iniitalization\n 4 = Executing Self-Test\n 5 = Sensor fusio algorithm running\n 6 = System running without fusion algorithms *\/\n \n if (system_status != 0)\n *system_status = read8(BNO055_SYS_STAT_ADDR);\n \n \/* Self Test Results (see section )\n --------------------------------\n 1 = test passed, 0 = test failed\n \n Bit 0 = Accelerometer self test\n Bit 1 = Magnetometer self test\n Bit 2 = Gyroscope self test\n Bit 3 = MCU self test\n\n 0x0F = all good! *\/\n \n if (self_test_result != 0)\n *self_test_result = read8(BNO055_SELFTEST_RESULT_ADDR);\n\n \/* System Error (see section 4.3.59)\n ---------------------------------\n 0 = No error\n 1 = Peripheral initialization error\n 2 = System initialization error\n 3 = Self test result failed\n 4 = Register map value out of range\n 5 = Register map address out of range\n 6 = Register map write error\n 7 = BNO low power mode not available for selected operat ion mode\n 8 = Accelerometer power mode not available\n 9 = Fusion algorithm configuration error\n A = Sensor configuration error *\/\n \n if (system_error != 0)\n *system_error = read8(BNO055_SYS_ERR_ADDR);\n\n setMode(backupmode);\n delay(20);\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Gets the chip revision numbers\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::getRevInfo(adafruit_bno055_rev_info_t* info)\n{\n uint8_t a, b;\n\n memset(info, 0, sizeof(adafruit_bno055_rev_info_t));\n\n \/* Check the accelerometer revision *\/\n info->accel_rev = read8(BNO055_ACCEL_REV_ID_ADDR);\n\n \/* Check the magnetometer revision *\/\n info->mag_rev = read8(BNO055_MAG_REV_ID_ADDR);\n\n \/* Check the gyroscope revision *\/\n info->gyro_rev = read8(BNO055_GYRO_REV_ID_ADDR);\n\n \/* Check the SW revision *\/\n info->bl_rev = read8(BNO055_BL_REV_ID_ADDR);\n \n a = read8(BNO055_SW_REV_ID_LSB_ADDR);\n b = read8(BNO055_SW_REV_ID_MSB_ADDR);\n info->sw_rev = (((uint16_t)b) << 8) | ((uint16_t)a);\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Gets teh temperature in degrees celsius\n*\/\n\/**************************************************************************\/\nint8_t Adafruit_BNO055::getTemp(void)\n{\n int8_t temp = (int8_t)(read8(BNO055_TEMP_ADDR));\n return temp;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Gets a vector reading from the specified source\n*\/\n\/**************************************************************************\/\nimu::Vector<3> Adafruit_BNO055::getVector(adafruit_vector_type_t vector_type)\n{\n imu::Vector<3> xyz;\n uint8_t buffer[6];\n memset (buffer, 0, 6);\n \n int16_t x, y, z;\n x = y = z = 0;\n \n \/* Read vector data (6 bytes) *\/\n readLen((adafruit_bno055_reg_t)vector_type, buffer, 6);\n \n x = ((int16_t)buffer[0]) | (((int16_t)buffer[1]) << 8);\n y = ((int16_t)buffer[2]) | (((int16_t)buffer[3]) << 8);\n z = ((int16_t)buffer[4]) | (((int16_t)buffer[5]) << 8);\n\n \/* Convert the value to an appropriate range (section 3.6.4) *\/\n \/* and assign the value to the Vector type *\/\n switch(vector_type)\n {\n case VECTOR_MAGNETOMETER:\n \/* 1uT = 16 LSB *\/\n xyz[0] = ((double)x)\/16.0;\n xyz[1] = ((double)y)\/16.0;\n xyz[2] = ((double)z)\/16.0;\n break;\n case VECTOR_GYROSCOPE:\n \/* 1rps = 900 LSB *\/\n xyz[0] = ((double)x)\/900.0;\n xyz[1] = ((double)y)\/900.0;\n xyz[2] = ((double)z)\/900.0;\n break;\n case VECTOR_EULER:\n \/* 1 degree = 16 LSB *\/\n xyz[0] = ((double)x)\/16.0;\n xyz[1] = ((double)y)\/16.0;\n xyz[2] = ((double)z)\/16.0;\n break;\n case VECTOR_ACCELEROMETER:\n case VECTOR_LINEARACCEL:\n case VECTOR_GRAVITY:\n \/* 1m\/s^2 = 100 LSB *\/\n xyz[0] = ((double)x)\/100.0;\n xyz[1] = ((double)y)\/100.0;\n xyz[2] = ((double)z)\/100.0;\n break;\n }\n \n return xyz;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Gets a quaternion reading from the specified source\n*\/\n\/**************************************************************************\/\nimu::Quaternion Adafruit_BNO055::getQuat(void)\n{\n uint8_t buffer[8];\n memset (buffer, 0, 8);\n \n int16_t x, y, z, w;\n x = y = z = w = 0;\n \n \/* Read quat data (8 bytes) *\/\n readLen(BNO055_QUATERNION_DATA_W_LSB_ADDR, buffer, 8);\n w = (((uint16_t)buffer[1]) << 8) | ((uint16_t)buffer[0]);\n x = (((uint16_t)buffer[3]) << 8) | ((uint16_t)buffer[2]);\n y = (((uint16_t)buffer[5]) << 8) | ((uint16_t)buffer[4]);\n z = (((uint16_t)buffer[7]) << 8) | ((uint16_t)buffer[6]);\n\n \/* Assign to Quaternion *\/\n \/* See http:\/\/ae-bst.resource.bosch.com\/media\/products\/dokumente\/bno055\/BST_BNO055_DS000_12~1.pdf\n 3.6.5.5 Orientation (Quaternion) *\/\n const double scale = (1.0 \/ (1<<14));\n imu::Quaternion quat(scale * w, scale * x, scale * y, scale * z);\n return quat;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Provides the sensor_t data for this sensor\n*\/\n\/**************************************************************************\/\nvoid Adafruit_BNO055::getSensor(sensor_t *sensor)\n{\n \/* Clear the sensor_t object *\/\n memset(sensor, 0, sizeof(sensor_t));\n\n \/* Insert the sensor name in the fixed length char array *\/\n strncpy (sensor->name, \"BNO055\", sizeof(sensor->name) - 1);\n sensor->name[sizeof(sensor->name)- 1] = 0;\n sensor->version = 1;\n sensor->sensor_id = _sensorID;\n sensor->type = SENSOR_TYPE_ORIENTATION;\n sensor->min_delay = 0;\n sensor->max_value = 0.0F;\n sensor->min_value = 0.0F;\n sensor->resolution = 0.01F;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Reads the sensor and returns the data as a sensors_event_t\n*\/\n\/**************************************************************************\/\nbool Adafruit_BNO055::getEvent(sensors_event_t *event)\n{\n \/* Clear the event *\/\n memset(event, 0, sizeof(sensors_event_t));\n\n event->version = sizeof(sensors_event_t);\n event->sensor_id = _sensorID;\n event->type = SENSOR_TYPE_ORIENTATION;\n event->timestamp = millis();\n\n \/* Get a Euler angle sample for orientation *\/\n imu::Vector<3> euler = getVector(Adafruit_BNO055::VECTOR_EULER);\n event->orientation.x = euler.x();\n event->orientation.y = euler.y();\n event->orientation.z = euler.z();\n\n return true;\n}\n\n\/***************************************************************************\n PRIVATE FUNCTIONS\n ***************************************************************************\/\n\n\/**************************************************************************\/\n\/*!\n @brief Writes an 8 bit value over I2C\n*\/\n\/**************************************************************************\/\nbool Adafruit_BNO055::write8(adafruit_bno055_reg_t reg, byte value)\n{\n Wire.beginTransmission(_address);\n #if ARDUINO >= 100\n Wire.write((uint8_t)reg);\n Wire.write((uint8_t)value);\n #else\n Wire.send(reg);\n Wire.send(value);\n #endif\n Wire.endTransmission();\n\n \/* ToDo: Check for error! *\/\n return true;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Reads an 8 bit value over I2C\n*\/\n\/**************************************************************************\/\nbyte Adafruit_BNO055::read8(adafruit_bno055_reg_t reg )\n{\n byte value = 0;\n \n Wire.beginTransmission(_address);\n #if ARDUINO >= 100\n Wire.write((uint8_t)reg);\n #else\n Wire.send(reg);\n #endif\n Wire.endTransmission();\n Wire.requestFrom(_address, (byte)1);\n #if ARDUINO >= 100\n value = Wire.read();\n #else\n value = Wire.receive();\n #endif\n \n return value;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Reads the specified number of bytes over I2C\n*\/\n\/**************************************************************************\/\nbool Adafruit_BNO055::readLen(adafruit_bno055_reg_t reg, byte * buffer, uint8_t len)\n{\n Wire.beginTransmission(_address);\n #if ARDUINO >= 100\n Wire.write((uint8_t)reg);\n #else\n Wire.send(reg);\n #endif\n Wire.endTransmission();\n Wire.requestFrom(_address, (byte)len);\n\n \/* Wait until data is available *\/\n while (Wire.available() < len);\n \n for (uint8_t i = 0; i < len; i++)\n {\n #if ARDUINO >= 100\n buffer[i] = Wire.read();\n #else\n buffer[i] = Wire.receive();\n #endif\n }\n \n \/* ToDo: Check for errors! *\/\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Vadim N. on 16\/03\/2016.\n\/\/\n\n#include \"benchutils.h\"\n\nusing namespace ymir;\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n\n if (argc < 2) {\n std::cout << \"Please re-run the script with the data folder path supplied.\" << std::endl;\n return 1;\n }\n\n std::chrono::system_clock::time_point tp1, tp2;\n\n std::vector< std::pair<std::string, size_t> > timepoints;\n\n std::vector<prob_t> logLvec;\n\n std::string temp_str;\n\n time_t vj_single_parse, vdj_single_parse,\n vj_single_prob, vj_single_meta,\n vj_single_infer, vdj_single_prob,\n vdj_single_meta, vdj_single_infer;\n\n time_t vj_good_parse, vdj_good_parse,\n vj_good_prob, vj_good_meta,\n vj_good_infer, vdj_good_prob,\n vdj_good_meta, vdj_good_infer;\n\n std::string BENCH_DATA_FOLDER = argv[1];\n\n std::cout << \"Data folder:\\t[\" << BENCH_DATA_FOLDER << \"]\" << endl;\n\n\n \/\/\n \/\/ TCR alpha chain repertoire - VJ recombination\n \/\/\n \/\/ VDJRecombinationGenes vj_single_genes(\"Vgene\",\n \/\/ \"\/home\/vadim\/ymir\/benchmark\/data\/trav.txt\",\n \/\/ \"Jgene\",\n \/\/ \"\/home\/vadim\/ymir\/benchmark\/data\/traj.txt\");\n\n\n string input_alpha_file = \"alpha.250k.txt\";\n string input_beta_file = \"beta.250k.txt\";\n\n CDR3NucParser parser;\n\n \/\/ Cloneset cloneset_vj;\n \/\/ YMIR_BENCHMARK(\"Parsing VJ\",\n \/\/ parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,\n \/\/ &cloneset_vj,\n \/\/ vj_single_genes,\n \/\/ NUCLEOTIDE,\n \/\/ VJ_RECOMB,\n \/\/ AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE),\n \/\/ VDJAlignerParameters(2)))\n\n \/\/\n \/\/ TCR beta chain repertoire - VDJ recombination\n \/\/\n VDJRecombinationGenes vdj_single_genes(\"Vgene\",\n BENCH_DATA_FOLDER + \"trbv.txt\",\n \"Jgene\",\n BENCH_DATA_FOLDER + \"trbj.txt\",\n \"Dgene\",\n BENCH_DATA_FOLDER + \"trbd.txt\");\n\n Cloneset cloneset_vdj;\n YMIR_BENCHMARK(\"Parsing VDJ\",\n parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,\n &cloneset_vdj,\n vdj_single_genes,\n NUCLEOTIDE,\n VDJ_RECOMB,\n AlignmentColumnOptions()\n .setV(AlignmentColumnOptions::OVERWRITE)\n .setD(AlignmentColumnOptions::OVERWRITE)\n .setJ(AlignmentColumnOptions::OVERWRITE),\n VDJAlignerParameters(3)))\n\n \/\/\n \/\/ VJ MAAG\n \/\/\n \/\/ ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRA\", EMPTY);\n\n \/\/\n \/\/ VDJ MAAG\n \/\/\n ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRB\", EMPTY);\n\n\n \/\/\n \/\/ Inference\n \/\/\n vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000};\n vec_sample = { std::stoi(argv[2]) };\n \/\/ int val_sample = cloneset_vdj.noncoding().size();\n\/\/ int val_sample = 100;\n vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; \/\/, 2000, 5000, 10000};\n\/\/ vec_block = {2000, 5000, 10000};\n vec_block = { std::stoi(argv[3]) };\n vector<double> vec_alpha = {.5, .6, .7, .8, .9};\n \/\/ vec_alpha = { std::stof(argv[3]) };\n vector<double> vec_beta = {.1, .5, 1, 3};\n \/\/ vec_beta = { std::stof(argv[4]) };\n vector<double> vec_K = {1, 2, 3};\n \/\/ vec_K = { std::stod(argv[5]) };\n ErrorMode error_mode = COMPUTE_ERRORS;\n\n\/\/ int niter, sample, block;\n\/\/ double alpha;\n\/\/ niter = 10;\n\/\/ int sample = 10000;\n\n\/\/ RUN_EM_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, niter, sample, error_mode)\n\/\/ RUN_EM_INFERENCE(string(\"vdj\"), cloneset_vdj, vdj_single_model, niter, sample, error_mode)\n\/\/ for(auto val_sample: vec_sample) {\n\/\/ RUN_EM_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, 40, val_sample, error_mode)\n\/\/ }\n\n\/\/ ModelParameterVector new_param_vec = vj_single_model.event_probabilities();\n\/\/ new_param_vec.fill(1);\n\/\/ new_param_vec.normaliseEventFamilies();\n\/\/ vj_single_model.updateModelParameterVector(new_param_vec);\n\/\/\n\/\/ auto rep_nonc = cloneset_vj.noncoding().sample(2500);\n\/\/ auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true);\n\/\/ vector<prob_t> prob_vec(maag_rep.size(), 0);\n\/\/\n\/\/ vector<bool> good_clonotypes(maag_rep.size(), true);\n\/\/ for (size_t i = 0; i < maag_rep.size(); ++i) {\n\/\/ if (rep_nonc[i].is_good()) {\n\/\/ prob_vec[i] = maag_rep[i].fullProbability();\n\/\/ if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) {\n\/\/ good_clonotypes[i] = false;\n\/\/ }\n\/\/ } else {\n\/\/ good_clonotypes[i] = false;\n\/\/ }\n\/\/ }\n\n for(auto val_sample: vec_sample) {\n for(auto val_block: vec_block) {\n for (auto val_alpha: vec_alpha) {\n for (auto val_beta: vec_beta) {\n for (auto val_K: vec_K) {\n \/\/ RUN_SG_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)\n RUN_SG_INFERENCE(string(\"vdj\"), cloneset_vdj, vdj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)\n }\n }\n }\n }\n }\n\n}\n<commit_msg>debug<commit_after>\/\/\n\/\/ Created by Vadim N. on 16\/03\/2016.\n\/\/\n\n#include \"benchutils.h\"\n\nusing namespace ymir;\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n\n if (argc < 2) {\n std::cout << \"Please re-run the script with the data folder path supplied.\" << std::endl;\n return 1;\n }\n\n std::chrono::system_clock::time_point tp1, tp2;\n\n std::vector< std::pair<std::string, size_t> > timepoints;\n\n std::vector<prob_t> logLvec;\n\n std::string temp_str;\n\n time_t vj_single_parse, vdj_single_parse,\n vj_single_prob, vj_single_meta,\n vj_single_infer, vdj_single_prob,\n vdj_single_meta, vdj_single_infer;\n\n time_t vj_good_parse, vdj_good_parse,\n vj_good_prob, vj_good_meta,\n vj_good_infer, vdj_good_prob,\n vdj_good_meta, vdj_good_infer;\n\n std::string BENCH_DATA_FOLDER = argv[1];\n\n std::cout << \"Data folder:\\t[\" << BENCH_DATA_FOLDER << \"]\" << endl;\n\n\n \/\/\n \/\/ TCR alpha chain repertoire - VJ recombination\n \/\/\n \/\/ VDJRecombinationGenes vj_single_genes(\"Vgene\",\n \/\/ \"\/home\/vadim\/ymir\/benchmark\/data\/trav.txt\",\n \/\/ \"Jgene\",\n \/\/ \"\/home\/vadim\/ymir\/benchmark\/data\/traj.txt\");\n\n\n string input_alpha_file = \"alpha.250k.txt\";\n string input_beta_file = \"beta.250k.txt\";\n\n CDR3NucParser parser;\n\n \/\/ Cloneset cloneset_vj;\n \/\/ YMIR_BENCHMARK(\"Parsing VJ\",\n \/\/ parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,\n \/\/ &cloneset_vj,\n \/\/ vj_single_genes,\n \/\/ NUCLEOTIDE,\n \/\/ VJ_RECOMB,\n \/\/ AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE),\n \/\/ VDJAlignerParameters(2)))\n\n \/\/\n \/\/ TCR beta chain repertoire - VDJ recombination\n \/\/\n VDJRecombinationGenes vdj_single_genes(\"Vgene\",\n BENCH_DATA_FOLDER + \"trbv.txt\",\n \"Jgene\",\n BENCH_DATA_FOLDER + \"trbj.txt\",\n \"Dgene\",\n BENCH_DATA_FOLDER + \"trbd.txt\");\n\n Cloneset cloneset_vdj;\n YMIR_BENCHMARK(\"Parsing VDJ\",\n parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,\n &cloneset_vdj,\n vdj_single_genes,\n NUCLEOTIDE,\n VDJ_RECOMB,\n AlignmentColumnOptions()\n .setV(AlignmentColumnOptions::OVERWRITE)\n .setD(AlignmentColumnOptions::OVERWRITE)\n .setJ(AlignmentColumnOptions::OVERWRITE),\n VDJAlignerParameters(3)))\n\n \/\/\n \/\/ VJ MAAG\n \/\/\n \/\/ ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRA\", EMPTY);\n\n \/\/\n \/\/ VDJ MAAG\n \/\/\n ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRB\", EMPTY);\n\n\n \/\/\n \/\/ Inference\n \/\/\n vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000};\n vec_sample = { std::stoi(argv[2]) };\n \/\/ int val_sample = cloneset_vdj.noncoding().size();\n\/\/ int val_sample = 100;\n vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; \/\/, 2000, 5000, 10000};\n\/\/ vec_block = {2000, 5000, 10000};\n vec_block = { std::stoi(argv[3]) };\n vector<double> vec_alpha = {.5, .6, .7, .8, .9};\n \/\/ vec_alpha = { std::stof(argv[3]) };\n vector<double> vec_beta = {.1, .5, 1, 3};\n \/\/ vec_beta = { std::stof(argv[4]) };\n vector<double> vec_K = {1, 2, 3};\n \/\/ vec_K = { std::stod(argv[5]) };\n ErrorMode error_mode = COMPUTE_ERRORS;\n\n\/\/ int niter, sample, block;\n\/\/ double alpha;\n\/\/ niter = 10;\n\/\/ int sample = 10000;\n\n\/\/ RUN_EM_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, niter, sample, error_mode)\n\/\/ RUN_EM_INFERENCE(string(\"vdj\"), cloneset_vdj, vdj_single_model, niter, sample, error_mode)\n for(auto val_sample: vec_sample) {\n RUN_EM_INFERENCE(string(\"vdj\"), cloneset_vdj, vdj_single_model, 40, val_sample, error_mode)\n }\n\n\/\/ ModelParameterVector new_param_vec = vj_single_model.event_probabilities();\n\/\/ new_param_vec.fill(1);\n\/\/ new_param_vec.normaliseEventFamilies();\n\/\/ vj_single_model.updateModelParameterVector(new_param_vec);\n\/\/\n\/\/ auto rep_nonc = cloneset_vj.noncoding().sample(2500);\n\/\/ auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true);\n\/\/ vector<prob_t> prob_vec(maag_rep.size(), 0);\n\/\/\n\/\/ vector<bool> good_clonotypes(maag_rep.size(), true);\n\/\/ for (size_t i = 0; i < maag_rep.size(); ++i) {\n\/\/ if (rep_nonc[i].is_good()) {\n\/\/ prob_vec[i] = maag_rep[i].fullProbability();\n\/\/ if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) {\n\/\/ good_clonotypes[i] = false;\n\/\/ }\n\/\/ } else {\n\/\/ good_clonotypes[i] = false;\n\/\/ }\n\/\/ }\n\n for(auto val_sample: vec_sample) {\n for(auto val_block: vec_block) {\n for (auto val_alpha: vec_alpha) {\n for (auto val_beta: vec_beta) {\n for (auto val_K: vec_K) {\n \/\/ RUN_SG_INFERENCE(string(\"vj\"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)\n RUN_SG_INFERENCE(string(\"vdj\"), cloneset_vdj, vdj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)\n }\n }\n }\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ A simple binary to grep URLs out of text.\n\/\/\n\/\/ Based on the URI class contrib'd to the excellent PEGTL library.\n\/\/\n\/\/ Licenced under the MIT licence as per the original code.\n\/\/\n\/\/ Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/ColinH\/PEGTL\/\n\n#include <iostream>\n#include <string>\n#include <iomanip>\n#include <ios>\n\n#include <pegtl.hh>\n#include <pegtl\/trace.hh>\n#include <pegtl\/contrib\/uri.hh>\n\nusing grammar = pegtl::uri::URI;\n\nnamespace pegtl {\n namespace uri {\n struct URIState {\n std::string uri;\n };\n\n \/\/ The default base action class.\n template<typename Rule>\n struct URIActions : pegtl::nothing<Rule> {};\n\n \/\/ Action for the URI class.\n template<>\n struct URIActions<URI> {\n static void apply(const pegtl::input& input,\n URIState& parsed_uri) {\n parsed_uri.uri.assign(input.string());\n }\n };\n }\n}\n\nusing pegtl::uri::URIActions;\nusing pegtl::uri::URIState;\n\n\/\/ Should be compiled down quite nicely. :)\nchar brackets[] = {'{', '}', '[', ']', '(', ')', '<', '>', '\"', '\\''};\nbool IsBracket(char c) {\n for (int i = 0; i < sizeof(brackets) \/ sizeof(char); ++i) {\n if (c == brackets[i]) return true;\n }\n return false;\n}\n\nint main(int argc, char* argv[]) {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n std::string thunk;\n while (std::cin >> thunk) {\n \/\/ Trim.\n int start = 0, end = thunk.size();\n for (; start < thunk.size() && IsBracket(thunk[start]); ++start) {}\n for (; end > 0 && IsBracket(thunk[end - 1]); --end) {}\n\n URIState state;\n bool parse_result = pegtl::parse<grammar, URIActions>(\n thunk.data() + start, thunk.data() + end, \"stdin\", state);\n if (parse_result) {\n std::cout << state.uri << '\\n';\n }\n }\n return 0;\n}\n<commit_msg>Fix compile bugs. Serves me right for not testing before committing.<commit_after>\/\/ A simple binary to grep URLs out of text.\n\/\/\n\/\/ Based on the URI class contrib'd to the excellent PEGTL library.\n\/\/\n\/\/ Licenced under the MIT licence as per the original code.\n\/\/\n\/\/ Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/ColinH\/PEGTL\/\n\n#include <iostream>\n#include <string>\n#include <iomanip>\n#include <ios>\n\n#include <pegtl.hh>\n#include <pegtl\/trace.hh>\n#include <pegtl\/contrib\/uri.hh>\n\nusing grammar = pegtl::uri::URI;\n\nnamespace pegtl {\n namespace uri {\n struct URIState {\n std::string uri;\n };\n\n \/\/ The default base action class.\n template<typename Rule>\n struct URIActions : pegtl::nothing<Rule> {};\n\n \/\/ Action for the URI class.\n template<>\n struct URIActions<URI> {\n static void apply(const pegtl::input& input,\n URIState& parsed_uri) {\n parsed_uri.uri.assign(input.string());\n }\n };\n }\n}\n\nusing pegtl::uri::URIActions;\nusing pegtl::uri::URIState;\n\n\/\/ Should be compiled down quite nicely. :)\nchar brackets[] = {'{', '}', '[', ']', '(', ')', '<', '>', '\"', '\\''};\nbool IsBracket(char c) {\n for (int i = 0; i < sizeof(brackets) \/ sizeof(char); ++i) {\n if (c == brackets[i]) return true;\n }\n return false;\n}\n\nint main(int argc, char* argv[]) {\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(nullptr);\n std::string thunk;\n while (std::cin >> thunk) {\n \/\/ Trim.\n int start = 0, end = thunk.size();\n for (; start < thunk.size() && IsBracket(thunk[start]); ++start) {}\n for (; end > 0 && IsBracket(thunk[end - 1]); --end) {}\n\n URIState state;\n bool parse_result = pegtl::parse<grammar, URIActions>(\n thunk.data() + start, thunk.data() + end, \"stdin\", state);\n if (parse_result) {\n std::cout << state.uri << '\\n';\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"bench_common.h\"\n#include <dariadb.h>\n#include <storage\/capacitor.h>\n#include <utils\/fs.h>\n#include <utils\/metrics.h>\n#include <utils\/thread_manager.h>\n\n#include <boost\/program_options.hpp>\n\nnamespace po = boost::program_options;\n\nstd::atomic_llong append_count{0};\nstd::atomic_size_t reads_count{0};\nbool stop_info = false;\nbool stop_readers = false;\n\nclass BenchCallback : public dariadb::storage::IReaderClb {\npublic:\n BenchCallback() { count = 0; }\n void call(const dariadb::Meas &v) { count++; }\n std::atomic<size_t> count;\n};\n\nvoid show_info(dariadb::storage::Engine *storage) {\n clock_t t0 = clock();\n while (true) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n clock_t t1 = clock();\n auto writes_per_sec = append_count.load() \/ double((t1 - t0) \/ CLOCKS_PER_SEC);\n auto reads_per_sec = reads_count.load() \/ double((t1 - t0) \/ CLOCKS_PER_SEC);\n auto queue_sizes = storage->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \" T:\" << queue_sizes.active_works << \") reads: \" << reads_count\n << \" speed:\" << reads_per_sec << \"\/sec\"\n << \" writes: \" << append_count << \" speed: \" << writes_per_sec\n << \"\/sec progress:\"\n << (int64_t(100) * append_count) \/ dariadb_bench::all_writes\n << \"% \";\n std::cout.flush();\n if (stop_info) {\n std::cout.flush();\n break;\n }\n }\n std::cout << \"\\n\";\n}\n\nvoid show_drop_info(dariadb::storage::Engine *storage) {\n while (true) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n auto queue_sizes = storage->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \" T:\" << queue_sizes.active_works << \") \";\n std::cout.flush();\n if (stop_info) {\n std::cout.flush();\n break;\n }\n }\n std::cout << \"\\n\";\n}\n\nvoid reader(dariadb::storage::IMeasStorage_ptr ms, dariadb::IdSet all_id_set,\n dariadb::Time from, dariadb::Time to) {\n std::random_device r;\n std::default_random_engine e1(r());\n std::uniform_int_distribution<dariadb::Id> uniform_dist(from, to);\n std::shared_ptr<BenchCallback> clbk{new BenchCallback};\n\n while (true) {\n clbk->count = 0;\n \/\/ auto time_point1 = uniform_dist(e1);\n auto f = from;\n auto t = dariadb::timeutil::current_time();\n\n auto qi = dariadb::storage::QueryInterval(\n dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, f, t);\n ms->foreach (qi, clbk.get());\n\n reads_count += clbk->count;\n if (stop_readers) {\n break;\n }\n }\n}\n\nint main(int argc, char *argv[]) {\n (void)argc;\n (void)argv;\n std::cout << \"Performance benchmark\" << std::endl;\n std::cout << \"Writers count:\" << dariadb_bench::total_threads_count << std::endl;\n\n const std::string storage_path = \"perf_benchmark_storage\";\n bool readers_enable = false;\n bool metrics_enable = false;\n bool readonly = false;\n bool readall_enabled = false;\n bool dont_clean = false;\n \/\/ bool full_flush = false;\n po::options_description desc(\"Allowed options\");\n desc.add_options()(\"help\", \"produce help message\")(\"readonly\", \"readonly mode\")(\n \"readall\", \"read all benchmark enable.\")\n \/\/(\"full-flush\", \"wait end of all async tasks.\")\n (\"dont-clean\", \"dont clean storage path before start.\")(\n \"enable-readers\",\n po::value<bool>(&readers_enable)->default_value(readers_enable),\n \"enable readers threads\")(\n \"enable-metrics\",\n po::value<bool>(&metrics_enable)->default_value(metrics_enable));\n\n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm);\n } catch (std::exception &ex) {\n logger(\"Error: \" << ex.what());\n exit(1);\n }\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 1;\n }\n\n if (metrics_enable) {\n std::cout << \"Enable metrics.\" << std::endl;\n }\n\n if (vm.count(\"readonly\")) {\n std::cout << \"Readonly mode.\" << std::endl;\n readonly = true;\n }\n\n if (vm.count(\"readall\")) {\n std::cout << \"Read all benchmark enabled.\" << std::endl;\n readall_enabled = true;\n }\n\n if (vm.count(\"dont-clean\")) {\n std::cout << \"Dont clean storage.\" << std::endl;\n dont_clean = true;\n }\n\n \/*if (vm.count(\"full-flush\")) {\n std::cout << \"full-flush.\" << std::endl;\n full_flush = true;\n }*\/\n\n if (readers_enable) {\n std::cout << \"Readers enable. count: \" << dariadb_bench::total_readers_count\n << std::endl;\n }\n\n {\n std::cout << \"Write...\" << std::endl;\n\n const size_t chunk_size = 512;\n const size_t cap_B = 50;\n\n \/\/ dont_clean = true;\n if (!dont_clean && dariadb::utils::fs::path_exists(storage_path)) {\n if (!readonly) {\n std::cout << \" remove \" << storage_path << std::endl;\n dariadb::utils::fs::rm(storage_path);\n }\n }\n\n dariadb::Time start_time = dariadb::timeutil::current_time();\n std::cout << \" start time: \" << dariadb::timeutil::to_string(start_time) << std::endl;\n\n dariadb::storage::PageManager::Params page_param(storage_path, chunk_size);\n dariadb::storage::CapacitorManager::Params cap_param(storage_path, cap_B);\n\tcap_param.store_period = 0; \/\/ 1000 * 2;\n\tcap_param.max_levels = 11;\n\tcap_param.max_closed_caps = 0; \/\/ 5;\n\tdariadb::storage::AOFManager::Params aof_param(storage_path, 0);\n\taof_param.buffer_size = 1000;\n\taof_param.max_size = cap_param.measurements_count();\n\n cap_param.max_levels = 11;\n auto raw_ptr = new dariadb::storage::Engine(aof_param, page_param, cap_param);\n\n dariadb::storage::IMeasStorage_ptr ms{raw_ptr};\n\n dariadb::IdSet all_id_set;\n append_count = 0;\n stop_info = false;\n\n std::thread info_thread(show_info, raw_ptr);\n\n std::vector<std::thread> writers(dariadb_bench::total_threads_count);\n std::vector<std::thread> readers(dariadb_bench::total_readers_count);\n\n size_t pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {\n auto id_from = dariadb_bench::get_id_from(pos);\n auto id_to = dariadb_bench::get_id_to(pos);\n for (size_t j = id_from; j < id_to; j++) {\n all_id_set.insert(j);\n }\n if (!readonly) {\n std::thread t{dariadb_bench::thread_writer_rnd_stor, dariadb::Id(pos),\n dariadb::Time(i), &append_count, raw_ptr};\n writers[pos] = std::move(t);\n }\n pos++;\n }\n if (readers_enable) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {\n std::thread t{reader, ms, all_id_set, start_time,\n dariadb::timeutil::current_time()};\n readers[pos++] = std::move(t);\n }\n }\n\n if (!readonly) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {\n std::thread t = std::move(writers[pos++]);\n t.join();\n }\n }\n stop_readers = true;\n if (readers_enable) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {\n std::thread t = std::move(readers[pos++]);\n t.join();\n }\n }\n\n stop_info = true;\n info_thread.join();\n std::cout << \" total id:\" << all_id_set.size() << std::endl;\n\n {\n std::cout << \"==> full flush...\" << std::endl;\n stop_info = false;\n std::thread flush_info_thread(show_drop_info, raw_ptr);\n\n auto start = clock();\n raw_ptr->flush();\n \/\/ if (full_flush)\n { raw_ptr->wait_all_asyncs(); }\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n stop_info = true;\n flush_info_thread.join();\n std::cout << \"flush time: \" << elapsed << std::endl;\n }\n\n if (!readonly) {\n size_t ccount = size_t(raw_ptr->queue_size().cola_count*0.5);\n std::cout << \"==> drop part caps to \" << ccount << \"...\" << std::endl;\n stop_info = false;\n std::thread flush_info_thread(show_drop_info, raw_ptr);\n\n auto start = clock();\n raw_ptr->drop_part_caps(ccount);\n raw_ptr->flush();\n raw_ptr->wait_all_asyncs();\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n stop_info = true;\n flush_info_thread.join();\n std::cout << \"drop time: \" << elapsed << std::endl;\n }\n\n auto queue_sizes = raw_ptr->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \")\" << append_count << std::endl;\n\n std::cout << \"Active threads: \"\n << dariadb::utils::async::ThreadManager::instance()->active_works()\n << std::endl;\n\n dariadb_bench::readBenchark(all_id_set, ms.get(), 100, start_time,\n dariadb::timeutil::current_time());\n\n\tauto max_time = ms->maxTime();\n\tstd::cout << \"==> interval end time: \" << dariadb::timeutil::to_string(max_time)\n\t\t<< std::endl;\n\n if (readall_enabled) {\n if (readonly) {\n start_time = dariadb::Time(0);\n }\n\n std::shared_ptr<BenchCallback> clbk{new BenchCallback()};\n \n\n dariadb::storage::QueryInterval qi{\n dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, start_time,\n max_time};\n\n std::cout << \"==> foreach all...\" << std::endl;\n\n auto start = clock();\n\n ms->foreach (qi, clbk.get());\n\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n std::cout << \"readed: \" << clbk->count << std::endl;\n std::cout << \"time: \" << elapsed << std::endl;\n\n std::cout << \"==> read all...\" << std::endl;\n\n start = clock();\n\n auto readed = ms->readInterval(qi);\n\n elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n std::cout << \"readed: \" << readed.size() << std::endl;\n std::cout << \"time: \" << elapsed << std::endl;\n\n auto expected = (dariadb_bench::write_per_id_count *\n dariadb_bench::total_threads_count * dariadb_bench::id_per_thread);\n\n std::map<dariadb::Id, dariadb::Meas::MeasList> _dict;\n for (auto &v : readed) {\n _dict[v.id].push_back(v);\n }\n\n if (readed.size() != expected) {\n std::cout << \"expected: \" << expected << \" get:\" << clbk->count << std::endl;\n\t\tstd::cout << \" all_writesL \" << dariadb_bench::all_writes;\n for (auto &kv : _dict) {\n std::cout << \" \" << kv.first << \" -> \" << kv.second.size() << std::endl;\n }\n throw MAKE_EXCEPTION(\"(clbk->count!=(iteration_count*total_threads_count))\");\n }\n }\n std::cout << \"stoping storage...\\n\";\n ms = nullptr;\n }\n\n if (!(dont_clean || readonly) && (dariadb::utils::fs::path_exists(storage_path))) {\n std::cout << \"cleaning...\\n\";\n dariadb::utils::fs::rm(storage_path);\n }\n\n if (metrics_enable) {\n std::cout << \"metrics:\\n\"\n << dariadb::utils::metrics::MetricsManager::instance()->to_string()\n << std::endl;\n }\n}\n<commit_msg>more verbose benchmark.<commit_after>#include \"bench_common.h\"\n#include <dariadb.h>\n#include <storage\/capacitor.h>\n#include <utils\/fs.h>\n#include <utils\/metrics.h>\n#include <utils\/thread_manager.h>\n\n#include <boost\/program_options.hpp>\n\nnamespace po = boost::program_options;\n\nstd::atomic_llong append_count{0};\nstd::atomic_size_t reads_count{0};\nbool stop_info = false;\nbool stop_readers = false;\n\nclass BenchCallback : public dariadb::storage::IReaderClb {\npublic:\n BenchCallback() { count = 0; }\n void call(const dariadb::Meas &v) { count++; }\n std::atomic<size_t> count;\n};\n\nvoid show_info(dariadb::storage::Engine *storage) {\n clock_t t0 = clock();\n while (true) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n clock_t t1 = clock();\n auto writes_per_sec = append_count.load() \/ double((t1 - t0) \/ CLOCKS_PER_SEC);\n auto reads_per_sec = reads_count.load() \/ double((t1 - t0) \/ CLOCKS_PER_SEC);\n auto queue_sizes = storage->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \" T:\" << queue_sizes.active_works << \") reads: \" << reads_count\n << \" speed:\" << reads_per_sec << \"\/sec\"\n << \" writes: \" << append_count << \" speed: \" << writes_per_sec\n << \"\/sec progress:\"\n << (int64_t(100) * append_count) \/ dariadb_bench::all_writes\n << \"% \";\n std::cout.flush();\n if (stop_info) {\n std::cout.flush();\n break;\n }\n }\n std::cout << \"\\n\";\n}\n\nvoid show_drop_info(dariadb::storage::Engine *storage) {\n while (true) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n auto queue_sizes = storage->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \" T:\" << queue_sizes.active_works << \") \";\n std::cout.flush();\n if (stop_info) {\n std::cout.flush();\n break;\n }\n }\n std::cout << \"\\n\";\n}\n\nvoid reader(dariadb::storage::IMeasStorage_ptr ms, dariadb::IdSet all_id_set,\n dariadb::Time from, dariadb::Time to) {\n std::random_device r;\n std::default_random_engine e1(r());\n std::uniform_int_distribution<dariadb::Id> uniform_dist(from, to);\n std::shared_ptr<BenchCallback> clbk{new BenchCallback};\n\n while (true) {\n clbk->count = 0;\n \/\/ auto time_point1 = uniform_dist(e1);\n auto f = from;\n auto t = dariadb::timeutil::current_time();\n\n auto qi = dariadb::storage::QueryInterval(\n dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, f, t);\n ms->foreach (qi, clbk.get());\n\n reads_count += clbk->count;\n if (stop_readers) {\n break;\n }\n }\n}\n\nint main(int argc, char *argv[]) {\n (void)argc;\n (void)argv;\n std::cout << \"Performance benchmark\" << std::endl;\n std::cout << \"Writers count:\" << dariadb_bench::total_threads_count << std::endl;\n\n const std::string storage_path = \"perf_benchmark_storage\";\n bool readers_enable = false;\n bool metrics_enable = false;\n bool readonly = false;\n bool readall_enabled = false;\n bool dont_clean = false;\n \/\/ bool full_flush = false;\n po::options_description desc(\"Allowed options\");\n desc.add_options()(\"help\", \"produce help message\")(\"readonly\", \"readonly mode\")(\n \"readall\", \"read all benchmark enable.\")\n \/\/(\"full-flush\", \"wait end of all async tasks.\")\n (\"dont-clean\", \"dont clean storage path before start.\")(\n \"enable-readers\",\n po::value<bool>(&readers_enable)->default_value(readers_enable),\n \"enable readers threads\")(\n \"enable-metrics\",\n po::value<bool>(&metrics_enable)->default_value(metrics_enable));\n\n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm);\n } catch (std::exception &ex) {\n logger(\"Error: \" << ex.what());\n exit(1);\n }\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 1;\n }\n\n if (metrics_enable) {\n std::cout << \"Enable metrics.\" << std::endl;\n }\n\n if (vm.count(\"readonly\")) {\n std::cout << \"Readonly mode.\" << std::endl;\n readonly = true;\n }\n\n if (vm.count(\"readall\")) {\n std::cout << \"Read all benchmark enabled.\" << std::endl;\n readall_enabled = true;\n }\n\n if (vm.count(\"dont-clean\")) {\n std::cout << \"Dont clean storage.\" << std::endl;\n dont_clean = true;\n }\n\n \/*if (vm.count(\"full-flush\")) {\n std::cout << \"full-flush.\" << std::endl;\n full_flush = true;\n }*\/\n\n if (readers_enable) {\n std::cout << \"Readers enable. count: \" << dariadb_bench::total_readers_count\n << std::endl;\n }\n\n {\n std::cout << \"Write...\" << std::endl;\n\n const size_t chunk_size = 512;\n const size_t cap_B = 50;\n\n \/\/ dont_clean = true;\n if (!dont_clean && dariadb::utils::fs::path_exists(storage_path)) {\n if (!readonly) {\n std::cout << \" remove \" << storage_path << std::endl;\n dariadb::utils::fs::rm(storage_path);\n }\n }\n\n dariadb::Time start_time = dariadb::timeutil::current_time();\n std::cout << \" start time: \" << dariadb::timeutil::to_string(start_time) << std::endl;\n\n dariadb::storage::PageManager::Params page_param(storage_path, chunk_size);\n \n\tdariadb::storage::CapacitorManager::Params cap_param(storage_path, cap_B);\n\tcap_param.store_period = 1000 * 60*60;\n\tcap_param.max_levels = 11;\n\tcap_param.max_closed_caps = 0; \/\/ 5;\n\t\n\tdariadb::storage::AOFManager::Params aof_param(storage_path, 0);\n\taof_param.buffer_size = 1000;\n\taof_param.max_size = cap_param.measurements_count();\n auto raw_ptr = new dariadb::storage::Engine(aof_param, page_param, cap_param);\n\n dariadb::storage::IMeasStorage_ptr ms{raw_ptr};\n\n dariadb::IdSet all_id_set;\n append_count = 0;\n stop_info = false;\n\n std::thread info_thread(show_info, raw_ptr);\n\n std::vector<std::thread> writers(dariadb_bench::total_threads_count);\n std::vector<std::thread> readers(dariadb_bench::total_readers_count);\n\n size_t pos = 0;\n\tauto writers_start = clock();\n for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {\n auto id_from = dariadb_bench::get_id_from(pos);\n auto id_to = dariadb_bench::get_id_to(pos);\n for (size_t j = id_from; j < id_to; j++) {\n all_id_set.insert(j);\n }\n if (!readonly) {\n std::thread t{dariadb_bench::thread_writer_rnd_stor, dariadb::Id(pos),\n dariadb::Time(i), &append_count, raw_ptr};\n writers[pos] = std::move(t);\n }\n pos++;\n }\n if (readers_enable) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {\n std::thread t{reader, ms, all_id_set, start_time,\n dariadb::timeutil::current_time()};\n readers[pos++] = std::move(t);\n }\n }\n\t\n\t\n\n if (!readonly) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {\n std::thread t = std::move(writers[pos++]);\n t.join();\n }\n }\n\tauto writers_elapsed = (((float)clock() - writers_start) \/ CLOCKS_PER_SEC);\n stop_readers = true;\n if (readers_enable) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {\n std::thread t = std::move(readers[pos++]);\n t.join();\n }\n }\n\n stop_info = true;\n info_thread.join();\n std::cout << \" total id:\" << all_id_set.size() << std::endl;\n\tstd::cout << \"write time: \" << writers_elapsed << std::endl;\n {\n std::cout << \"==> full flush...\" << std::endl;\n stop_info = false;\n std::thread flush_info_thread(show_drop_info, raw_ptr);\n\n auto start = clock();\n raw_ptr->flush();\n \/\/ if (full_flush)\n { raw_ptr->wait_all_asyncs(); }\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n stop_info = true;\n flush_info_thread.join();\n std::cout << \"flush time: \" << elapsed << std::endl;\n }\n\n if (!readonly) {\n size_t ccount = size_t(raw_ptr->queue_size().cola_count*0.5);\n std::cout << \"==> drop part caps to \" << ccount << \"...\" << std::endl;\n stop_info = false;\n std::thread flush_info_thread(show_drop_info, raw_ptr);\n\n auto start = clock();\n raw_ptr->drop_part_caps(ccount);\n raw_ptr->flush();\n raw_ptr->wait_all_asyncs();\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n stop_info = true;\n flush_info_thread.join();\n std::cout << \"drop time: \" << elapsed << std::endl;\n }\n\n auto queue_sizes = raw_ptr->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \")\" << std::endl;\n\n std::cout << \"Active threads: \"\n << dariadb::utils::async::ThreadManager::instance()->active_works()\n << std::endl;\n\n dariadb_bench::readBenchark(all_id_set, ms.get(), 100, start_time,\n dariadb::timeutil::current_time());\n\n\tauto max_time = ms->maxTime();\n\tstd::cout << \"==> interval end time: \" << dariadb::timeutil::to_string(max_time)\n\t\t<< std::endl;\n\n if (readall_enabled) {\n if (readonly) {\n start_time = dariadb::Time(0);\n }\n\n std::shared_ptr<BenchCallback> clbk{new BenchCallback()};\n \n\n dariadb::storage::QueryInterval qi{\n dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, start_time,\n max_time};\n\n std::cout << \"==> foreach all...\" << std::endl;\n\n auto start = clock();\n\n ms->foreach (qi, clbk.get());\n\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n std::cout << \"readed: \" << clbk->count << std::endl;\n std::cout << \"time: \" << elapsed << std::endl;\n\n std::cout << \"==> read all...\" << std::endl;\n\n start = clock();\n\n auto readed = ms->readInterval(qi);\n\n elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n std::cout << \"readed: \" << readed.size() << std::endl;\n std::cout << \"time: \" << elapsed << std::endl;\n\n auto expected = (dariadb_bench::write_per_id_count *\n dariadb_bench::total_threads_count * dariadb_bench::id_per_thread);\n\n std::map<dariadb::Id, dariadb::Meas::MeasList> _dict;\n for (auto &v : readed) {\n _dict[v.id].push_back(v);\n }\n\n if (readed.size() != expected) {\n std::cout << \"expected: \" << expected << \" get:\" << clbk->count << std::endl;\n\t\tstd::cout << \" all_writesL \" << dariadb_bench::all_writes;\n for (auto &kv : _dict) {\n std::cout << \" \" << kv.first << \" -> \" << kv.second.size() << std::endl;\n }\n throw MAKE_EXCEPTION(\"(clbk->count!=(iteration_count*total_threads_count))\");\n }\n }\n std::cout << \"stoping storage...\\n\";\n ms = nullptr;\n }\n\n if (!(dont_clean || readonly) && (dariadb::utils::fs::path_exists(storage_path))) {\n std::cout << \"cleaning...\\n\";\n dariadb::utils::fs::rm(storage_path);\n }\n\n if (metrics_enable) {\n std::cout << \"metrics:\\n\"\n << dariadb::utils::metrics::MetricsManager::instance()->to_string()\n << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <QUrl>\n\n#include \"abstractmediaplayer.h\"\n#include \"defs.h\"\n#include \"mediaobject.h\"\n#include \"utils.h\"\n\nQT_BEGIN_NAMESPACE\n\nusing namespace Phonon;\nusing namespace Phonon::MMF;\n\n\/*! \\class MMF::AbstractMediaPlayer\n \\internal\n*\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constants\n\/\/-----------------------------------------------------------------------------\n\nconst int NullMaxVolume = -1;\nconst int BufferStatusTimerInterval = 100; \/\/ ms\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constructor \/ destructor\n\/\/-----------------------------------------------------------------------------\n\nMMF::AbstractMediaPlayer::AbstractMediaPlayer\n (MediaObject *parent, const AbstractPlayer *player)\n : AbstractPlayer(player)\n , m_parent(parent)\n , m_playPending(false)\n , m_positionTimer(new QTimer(this))\n , m_bufferStatusTimer(new QTimer(this))\n , m_mmfMaxVolume(NullMaxVolume)\n , m_prefinishMarkSent(false)\n , m_aboutToFinishSent(false)\n{\n connect(m_positionTimer.data(), SIGNAL(timeout()), this, SLOT(positionTick()));\n connect(m_bufferStatusTimer.data(), SIGNAL(timeout()), this, SLOT(bufferStatusTick()));\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ MediaObjectInterface\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::AbstractMediaPlayer::play()\n{\n TRACE_CONTEXT(AbstractMediaPlayer::play, EAudioApi);\n TRACE_ENTRY(\"state %d\", privateState());\n\n switch (privateState()) {\n case GroundState:\n setError(tr(\"Not ready to play\"));\n break;\n\n case LoadingState:\n m_playPending = true;\n break;\n\n case StoppedState:\n case PausedState:\n doPlay();\n startPositionTimer();\n changeState(PlayingState);\n break;\n\n case PlayingState:\n case BufferingState:\n case ErrorState:\n \/\/ Do nothing\n break;\n\n \/\/ Protection against adding new states and forgetting to update this switch\n default:\n TRACE_PANIC(InvalidStatePanic);\n }\n\n TRACE_EXIT(\"state %d\", privateState());\n}\n\nvoid MMF::AbstractMediaPlayer::pause()\n{\n TRACE_CONTEXT(AbstractMediaPlayer::pause, EAudioApi);\n TRACE_ENTRY(\"state %d\", privateState());\n\n m_playPending = false;\n stopTimers();\n\n switch (privateState()) {\n case GroundState:\n case LoadingState:\n case PausedState:\n case StoppedState:\n \/\/ Do nothing\n break;\n\n case PlayingState:\n case BufferingState:\n changeState(PausedState);\n \/\/ Fall through\n case ErrorState:\n doPause();\n break;\n\n \/\/ Protection against adding new states and forgetting to update this switch\n default:\n TRACE_PANIC(InvalidStatePanic);\n }\n\n TRACE_EXIT(\"state %d\", privateState());\n}\n\nvoid MMF::AbstractMediaPlayer::stop()\n{\n TRACE_CONTEXT(AbstractMediaPlayer::stop, EAudioApi);\n TRACE_ENTRY(\"state %d\", privateState());\n\n m_playPending = false;\n stopTimers();\n\n switch (privateState()) {\n case GroundState:\n case LoadingState:\n case StoppedState:\n case ErrorState:\n \/\/ Do nothing\n break;\n\n case PlayingState:\n case BufferingState:\n case PausedState:\n doStop();\n changeState(StoppedState);\n break;\n\n \/\/ Protection against adding new states and forgetting to update this switch\n default:\n TRACE_PANIC(InvalidStatePanic);\n }\n\n TRACE_EXIT(\"state %d\", privateState());\n}\n\nvoid MMF::AbstractMediaPlayer::seek(qint64 ms)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::seek, EAudioApi);\n TRACE_ENTRY(\"state %d pos %Ld\", state(), ms);\n\n switch (privateState()) {\n \/\/ Fallthrough all these\n case GroundState:\n case StoppedState:\n case PausedState:\n case PlayingState:\n case LoadingState:\n {\n bool wasPlaying = false;\n if (state() == PlayingState) {\n stopPositionTimer();\n doPause();\n wasPlaying = true;\n }\n\n doSeek(ms);\n resetMarksIfRewound();\n\n if(wasPlaying && state() != ErrorState) {\n doPlay();\n startPositionTimer();\n }\n\n break;\n }\n case BufferingState:\n \/\/ Fallthrough\n case ErrorState:\n \/\/ Do nothing\n break;\n }\n\n TRACE_EXIT_0();\n}\n\nbool MMF::AbstractMediaPlayer::isSeekable() const\n{\n return true;\n}\n\nvoid MMF::AbstractMediaPlayer::doSetTickInterval(qint32 interval)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::doSetTickInterval, EAudioApi);\n TRACE_ENTRY(\"state %d m_interval %d interval %d\", privateState(), tickInterval(), interval);\n\n m_positionTimer->setInterval(interval);\n\n TRACE_EXIT_0();\n}\n\nvoid MMF::AbstractMediaPlayer::open(const MediaSource &source, RFile& file)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::setFileSource, EAudioApi);\n TRACE_ENTRY(\"state %d source.type %d\", privateState(), source.type());\n\n close();\n changeState(GroundState);\n\n TInt symbianErr = KErrNone;\n QString errorMessage;\n\n switch (source.type()) {\n case MediaSource::LocalFile: {\n symbianErr = openFile(file);\n if (KErrNone != symbianErr)\n errorMessage = tr(\"Error opening file\");\n break;\n }\n\n case MediaSource::Url: {\n const QUrl url(source.url());\n\n if (url.scheme() == QLatin1String(\"file\")) {\n symbianErr = openFile(file);\n if (KErrNone != symbianErr)\n errorMessage = tr(\"Error opening file\");\n } else {\n symbianErr = openUrl(url.toString());\n if (KErrNone != symbianErr)\n errorMessage = tr(\"Error opening URL\");\n }\n\n break;\n }\n\n case MediaSource::Invalid:\n case MediaSource::Disc:\n case MediaSource::Stream:\n TRACE_0(\"Error opening source: type not supported\");\n errorMessage = tr(\"Error opening source: type not supported\");\n break;\n\n case MediaSource::Empty:\n TRACE_0(\"Empty source - doing nothing\");\n TRACE_EXIT_0();\n return;\n\n \/\/ Protection against adding new media types and forgetting to update this switch\n default:\n TRACE_PANIC(InvalidMediaTypePanic);\n }\n\n if (errorMessage.isEmpty()) {\n changeState(LoadingState);\n } else {\n if (symbianErr)\n setError(errorMessage, symbianErr);\n else\n setError(errorMessage);\n }\n\n TRACE_EXIT_0();\n}\n\nvoid MMF::AbstractMediaPlayer::volumeChanged(qreal volume)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::volumeChanged, EAudioInternal);\n TRACE_ENTRY(\"state %d\", privateState());\n\n AbstractPlayer::volumeChanged(volume);\n doVolumeChanged();\n\n TRACE_EXIT_0();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Private functions\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::AbstractMediaPlayer::startPositionTimer()\n{\n m_positionTimer->start(tickInterval());\n}\n\nvoid MMF::AbstractMediaPlayer::stopPositionTimer()\n{\n m_positionTimer->stop();\n}\n\nvoid MMF::AbstractMediaPlayer::startBufferStatusTimer()\n{\n m_bufferStatusTimer->start(BufferStatusTimerInterval);\n}\n\nvoid MMF::AbstractMediaPlayer::stopBufferStatusTimer()\n{\n m_bufferStatusTimer->stop();\n}\n\nvoid MMF::AbstractMediaPlayer::stopTimers()\n{\n stopPositionTimer();\n stopBufferStatusTimer();\n}\n\nvoid MMF::AbstractMediaPlayer::doVolumeChanged()\n{\n switch (privateState()) {\n case GroundState:\n case LoadingState:\n case ErrorState:\n \/\/ Do nothing\n break;\n\n case StoppedState:\n case PausedState:\n case PlayingState:\n case BufferingState: {\n const qreal volume = (m_volume * m_mmfMaxVolume) + 0.5;\n const int err = setDeviceVolume(volume);\n\n if (KErrNone != err) {\n setError(tr(\"Setting volume failed\"), err);\n }\n break;\n }\n\n \/\/ Protection against adding new states and forgetting to update this\n \/\/ switch\n default:\n Utils::panic(InvalidStatePanic);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Protected functions\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::AbstractMediaPlayer::bufferingStarted()\n{\n m_stateBeforeBuffering = privateState();\n changeState(BufferingState);\n bufferStatusTick();\n startBufferStatusTimer();\n}\n\nvoid MMF::AbstractMediaPlayer::bufferingComplete()\n{\n stopBufferStatusTimer();\n emit MMF::AbstractPlayer::bufferStatus(100);\n changeState(m_stateBeforeBuffering);\n}\n\nvoid MMF::AbstractMediaPlayer::maxVolumeChanged(int mmfMaxVolume)\n{\n m_mmfMaxVolume = mmfMaxVolume;\n doVolumeChanged();\n}\n\nvoid MMF::AbstractMediaPlayer::playbackComplete(int error)\n{\n stopTimers();\n\n if (KErrNone == error) {\n changeState(StoppedState);\n\n \/\/ MediaObject::switchToNextSource deletes the current player, so we\n \/\/ call it via delayed slot invokation to ensure that this object does\n \/\/ not get deleted during execution of a member function.\n QMetaObject::invokeMethod(m_parent, \"switchToNextSource\", Qt::QueuedConnection);\n }\n else {\n setError(tr(\"Playback complete\"), error);\n }\n}\n\nqint64 MMF::AbstractMediaPlayer::toMilliSeconds(const TTimeIntervalMicroSeconds &in)\n{\n return in.Int64() \/ 1000;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Slots\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::AbstractMediaPlayer::positionTick()\n{\n emitMarksIfReached();\n\n const qint64 current = currentTime();\n emit MMF::AbstractPlayer::tick(current);\n}\n\nvoid MMF::AbstractMediaPlayer::emitMarksIfReached()\n{\n const qint64 current = currentTime();\n const qint64 total = totalTime();\n const qint64 remaining = total - current;\n\n if (prefinishMark() && !m_prefinishMarkSent) {\n if (remaining < (prefinishMark() + tickInterval()\/2)) {\n m_prefinishMarkSent = true;\n emit prefinishMarkReached(remaining);\n }\n }\n\n if (!m_aboutToFinishSent) {\n if (remaining < tickInterval()) {\n m_aboutToFinishSent = true;\n emit aboutToFinish();\n }\n }\n}\n\nvoid MMF::AbstractMediaPlayer::resetMarksIfRewound()\n{\n const qint64 current = currentTime();\n const qint64 total = totalTime();\n const qint64 remaining = total - current;\n\n if (prefinishMark() && m_prefinishMarkSent)\n if (remaining >= (prefinishMark() + tickInterval()\/2))\n m_prefinishMarkSent = false;\n\n if (m_aboutToFinishSent)\n if (remaining >= tickInterval())\n m_aboutToFinishSent = false;\n}\n\nvoid MMF::AbstractMediaPlayer::bufferStatusTick()\n{\n emit MMF::AbstractPlayer::bufferStatus(bufferStatus());\n}\n\nvoid MMF::AbstractMediaPlayer::changeState(PrivateState newState)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::changeState, EAudioInternal);\n\n const Phonon::State oldPhononState = phononState(privateState());\n const Phonon::State newPhononState = phononState(newState);\n\n \/\/ TODO: add some invariants to check that the transition is valid\n AbstractPlayer::changeState(newState);\n\n if (LoadingState == oldPhononState && StoppedState == newPhononState) {\n \/\/ Ensure initial volume is set on MMF API before starting playback\n doVolumeChanged();\n\n \/\/ Check whether play() was called while clip was being loaded. If so,\n \/\/ playback should be started now\n if (m_playPending) {\n TRACE_0(\"play was called while loading; starting playback now\");\n m_playPending = false;\n play();\n }\n }\n}\n\nvoid MMF::AbstractMediaPlayer::updateMetaData()\n{\n TRACE_CONTEXT(AbstractMediaPlayer::updateMetaData, EAudioInternal);\n TRACE_ENTRY_0();\n\n m_metaData.clear();\n\n const int numberOfEntries = numberOfMetaDataEntries();\n for(int i=0; i<numberOfEntries; ++i) {\n const QPair<QString, QString> entry = metaDataEntry(i);\n\n \/\/ Note that we capitalize the key, as required by the Ogg Vorbis\n \/\/ metadata standard to which Phonon adheres:\n \/\/ http:\/\/xiph.org\/vorbis\/doc\/v-comment.html\n m_metaData.insert(entry.first.toUpper(), entry.second);\n }\n\n emit metaDataChanged(m_metaData);\n\n TRACE_EXIT_0();\n}\n\nQT_END_NAMESPACE\n\n<commit_msg>Removed dead code from Phonon MMF backend<commit_after>\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <QUrl>\n\n#include \"abstractmediaplayer.h\"\n#include \"defs.h\"\n#include \"mediaobject.h\"\n#include \"utils.h\"\n\nQT_BEGIN_NAMESPACE\n\nusing namespace Phonon;\nusing namespace Phonon::MMF;\n\n\/*! \\class MMF::AbstractMediaPlayer\n \\internal\n*\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constants\n\/\/-----------------------------------------------------------------------------\n\nconst int NullMaxVolume = -1;\nconst int BufferStatusTimerInterval = 100; \/\/ ms\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constructor \/ destructor\n\/\/-----------------------------------------------------------------------------\n\nMMF::AbstractMediaPlayer::AbstractMediaPlayer\n (MediaObject *parent, const AbstractPlayer *player)\n : AbstractPlayer(player)\n , m_parent(parent)\n , m_playPending(false)\n , m_positionTimer(new QTimer(this))\n , m_bufferStatusTimer(new QTimer(this))\n , m_mmfMaxVolume(NullMaxVolume)\n , m_prefinishMarkSent(false)\n , m_aboutToFinishSent(false)\n{\n connect(m_positionTimer.data(), SIGNAL(timeout()), this, SLOT(positionTick()));\n connect(m_bufferStatusTimer.data(), SIGNAL(timeout()), this, SLOT(bufferStatusTick()));\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ MediaObjectInterface\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::AbstractMediaPlayer::play()\n{\n TRACE_CONTEXT(AbstractMediaPlayer::play, EAudioApi);\n TRACE_ENTRY(\"state %d\", privateState());\n\n switch (privateState()) {\n case GroundState:\n setError(tr(\"Not ready to play\"));\n break;\n\n case LoadingState:\n m_playPending = true;\n break;\n\n case StoppedState:\n case PausedState:\n doPlay();\n startPositionTimer();\n changeState(PlayingState);\n break;\n\n case PlayingState:\n case BufferingState:\n case ErrorState:\n \/\/ Do nothing\n break;\n\n \/\/ Protection against adding new states and forgetting to update this switch\n default:\n TRACE_PANIC(InvalidStatePanic);\n }\n\n TRACE_EXIT(\"state %d\", privateState());\n}\n\nvoid MMF::AbstractMediaPlayer::pause()\n{\n TRACE_CONTEXT(AbstractMediaPlayer::pause, EAudioApi);\n TRACE_ENTRY(\"state %d\", privateState());\n\n m_playPending = false;\n stopTimers();\n\n switch (privateState()) {\n case GroundState:\n case LoadingState:\n case PausedState:\n case StoppedState:\n \/\/ Do nothing\n break;\n\n case PlayingState:\n case BufferingState:\n changeState(PausedState);\n \/\/ Fall through\n case ErrorState:\n doPause();\n break;\n\n \/\/ Protection against adding new states and forgetting to update this switch\n default:\n TRACE_PANIC(InvalidStatePanic);\n }\n\n TRACE_EXIT(\"state %d\", privateState());\n}\n\nvoid MMF::AbstractMediaPlayer::stop()\n{\n TRACE_CONTEXT(AbstractMediaPlayer::stop, EAudioApi);\n TRACE_ENTRY(\"state %d\", privateState());\n\n m_playPending = false;\n stopTimers();\n\n switch (privateState()) {\n case GroundState:\n case LoadingState:\n case StoppedState:\n case ErrorState:\n \/\/ Do nothing\n break;\n\n case PlayingState:\n case BufferingState:\n case PausedState:\n doStop();\n changeState(StoppedState);\n break;\n\n \/\/ Protection against adding new states and forgetting to update this switch\n default:\n TRACE_PANIC(InvalidStatePanic);\n }\n\n TRACE_EXIT(\"state %d\", privateState());\n}\n\nvoid MMF::AbstractMediaPlayer::seek(qint64 ms)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::seek, EAudioApi);\n TRACE_ENTRY(\"state %d pos %Ld\", state(), ms);\n\n switch (privateState()) {\n \/\/ Fallthrough all these\n case GroundState:\n case StoppedState:\n case PausedState:\n case PlayingState:\n case LoadingState:\n {\n bool wasPlaying = false;\n if (state() == PlayingState) {\n stopPositionTimer();\n doPause();\n wasPlaying = true;\n }\n\n doSeek(ms);\n resetMarksIfRewound();\n\n if(wasPlaying && state() != ErrorState) {\n doPlay();\n startPositionTimer();\n }\n\n break;\n }\n case BufferingState:\n \/\/ Fallthrough\n case ErrorState:\n \/\/ Do nothing\n break;\n }\n\n TRACE_EXIT_0();\n}\n\nbool MMF::AbstractMediaPlayer::isSeekable() const\n{\n return true;\n}\n\nvoid MMF::AbstractMediaPlayer::doSetTickInterval(qint32 interval)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::doSetTickInterval, EAudioApi);\n TRACE_ENTRY(\"state %d m_interval %d interval %d\", privateState(), tickInterval(), interval);\n\n m_positionTimer->setInterval(interval);\n\n TRACE_EXIT_0();\n}\n\nvoid MMF::AbstractMediaPlayer::open(const MediaSource &source, RFile& file)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::setFileSource, EAudioApi);\n TRACE_ENTRY(\"state %d source.type %d\", privateState(), source.type());\n\n close();\n changeState(GroundState);\n\n TInt symbianErr = KErrNone;\n QString errorMessage;\n\n switch (source.type()) {\n case MediaSource::LocalFile: {\n symbianErr = openFile(file);\n if (KErrNone != symbianErr)\n errorMessage = tr(\"Error opening file\");\n break;\n }\n\n case MediaSource::Url: {\n const QUrl url(source.url());\n\n if (url.scheme() == QLatin1String(\"file\")) {\n symbianErr = openFile(file);\n if (KErrNone != symbianErr)\n errorMessage = tr(\"Error opening file\");\n } else {\n symbianErr = openUrl(url.toString());\n if (KErrNone != symbianErr)\n errorMessage = tr(\"Error opening URL\");\n }\n\n break;\n }\n\n \/\/ Other source types are handled in MediaObject::createPlayer\n\n \/\/ Protection against adding new media types and forgetting to update this switch\n default:\n TRACE_PANIC(InvalidMediaTypePanic);\n }\n\n if (errorMessage.isEmpty()) {\n changeState(LoadingState);\n } else {\n if (symbianErr)\n setError(errorMessage, symbianErr);\n else\n setError(errorMessage);\n }\n\n TRACE_EXIT_0();\n}\n\nvoid MMF::AbstractMediaPlayer::volumeChanged(qreal volume)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::volumeChanged, EAudioInternal);\n TRACE_ENTRY(\"state %d\", privateState());\n\n AbstractPlayer::volumeChanged(volume);\n doVolumeChanged();\n\n TRACE_EXIT_0();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Private functions\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::AbstractMediaPlayer::startPositionTimer()\n{\n m_positionTimer->start(tickInterval());\n}\n\nvoid MMF::AbstractMediaPlayer::stopPositionTimer()\n{\n m_positionTimer->stop();\n}\n\nvoid MMF::AbstractMediaPlayer::startBufferStatusTimer()\n{\n m_bufferStatusTimer->start(BufferStatusTimerInterval);\n}\n\nvoid MMF::AbstractMediaPlayer::stopBufferStatusTimer()\n{\n m_bufferStatusTimer->stop();\n}\n\nvoid MMF::AbstractMediaPlayer::stopTimers()\n{\n stopPositionTimer();\n stopBufferStatusTimer();\n}\n\nvoid MMF::AbstractMediaPlayer::doVolumeChanged()\n{\n switch (privateState()) {\n case GroundState:\n case LoadingState:\n case ErrorState:\n \/\/ Do nothing\n break;\n\n case StoppedState:\n case PausedState:\n case PlayingState:\n case BufferingState: {\n const qreal volume = (m_volume * m_mmfMaxVolume) + 0.5;\n const int err = setDeviceVolume(volume);\n\n if (KErrNone != err) {\n setError(tr(\"Setting volume failed\"), err);\n }\n break;\n }\n\n \/\/ Protection against adding new states and forgetting to update this\n \/\/ switch\n default:\n Utils::panic(InvalidStatePanic);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Protected functions\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::AbstractMediaPlayer::bufferingStarted()\n{\n m_stateBeforeBuffering = privateState();\n changeState(BufferingState);\n bufferStatusTick();\n startBufferStatusTimer();\n}\n\nvoid MMF::AbstractMediaPlayer::bufferingComplete()\n{\n stopBufferStatusTimer();\n emit MMF::AbstractPlayer::bufferStatus(100);\n changeState(m_stateBeforeBuffering);\n}\n\nvoid MMF::AbstractMediaPlayer::maxVolumeChanged(int mmfMaxVolume)\n{\n m_mmfMaxVolume = mmfMaxVolume;\n doVolumeChanged();\n}\n\nvoid MMF::AbstractMediaPlayer::playbackComplete(int error)\n{\n stopTimers();\n\n if (KErrNone == error) {\n changeState(StoppedState);\n\n \/\/ MediaObject::switchToNextSource deletes the current player, so we\n \/\/ call it via delayed slot invokation to ensure that this object does\n \/\/ not get deleted during execution of a member function.\n QMetaObject::invokeMethod(m_parent, \"switchToNextSource\", Qt::QueuedConnection);\n }\n else {\n setError(tr(\"Playback complete\"), error);\n }\n}\n\nqint64 MMF::AbstractMediaPlayer::toMilliSeconds(const TTimeIntervalMicroSeconds &in)\n{\n return in.Int64() \/ 1000;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Slots\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::AbstractMediaPlayer::positionTick()\n{\n emitMarksIfReached();\n\n const qint64 current = currentTime();\n emit MMF::AbstractPlayer::tick(current);\n}\n\nvoid MMF::AbstractMediaPlayer::emitMarksIfReached()\n{\n const qint64 current = currentTime();\n const qint64 total = totalTime();\n const qint64 remaining = total - current;\n\n if (prefinishMark() && !m_prefinishMarkSent) {\n if (remaining < (prefinishMark() + tickInterval()\/2)) {\n m_prefinishMarkSent = true;\n emit prefinishMarkReached(remaining);\n }\n }\n\n if (!m_aboutToFinishSent) {\n if (remaining < tickInterval()) {\n m_aboutToFinishSent = true;\n emit aboutToFinish();\n }\n }\n}\n\nvoid MMF::AbstractMediaPlayer::resetMarksIfRewound()\n{\n const qint64 current = currentTime();\n const qint64 total = totalTime();\n const qint64 remaining = total - current;\n\n if (prefinishMark() && m_prefinishMarkSent)\n if (remaining >= (prefinishMark() + tickInterval()\/2))\n m_prefinishMarkSent = false;\n\n if (m_aboutToFinishSent)\n if (remaining >= tickInterval())\n m_aboutToFinishSent = false;\n}\n\nvoid MMF::AbstractMediaPlayer::bufferStatusTick()\n{\n emit MMF::AbstractPlayer::bufferStatus(bufferStatus());\n}\n\nvoid MMF::AbstractMediaPlayer::changeState(PrivateState newState)\n{\n TRACE_CONTEXT(AbstractMediaPlayer::changeState, EAudioInternal);\n\n const Phonon::State oldPhononState = phononState(privateState());\n const Phonon::State newPhononState = phononState(newState);\n\n \/\/ TODO: add some invariants to check that the transition is valid\n AbstractPlayer::changeState(newState);\n\n if (LoadingState == oldPhononState && StoppedState == newPhononState) {\n \/\/ Ensure initial volume is set on MMF API before starting playback\n doVolumeChanged();\n\n \/\/ Check whether play() was called while clip was being loaded. If so,\n \/\/ playback should be started now\n if (m_playPending) {\n TRACE_0(\"play was called while loading; starting playback now\");\n m_playPending = false;\n play();\n }\n }\n}\n\nvoid MMF::AbstractMediaPlayer::updateMetaData()\n{\n TRACE_CONTEXT(AbstractMediaPlayer::updateMetaData, EAudioInternal);\n TRACE_ENTRY_0();\n\n m_metaData.clear();\n\n const int numberOfEntries = numberOfMetaDataEntries();\n for(int i=0; i<numberOfEntries; ++i) {\n const QPair<QString, QString> entry = metaDataEntry(i);\n\n \/\/ Note that we capitalize the key, as required by the Ogg Vorbis\n \/\/ metadata standard to which Phonon adheres:\n \/\/ http:\/\/xiph.org\/vorbis\/doc\/v-comment.html\n m_metaData.insert(entry.first.toUpper(), entry.second);\n }\n\n emit metaDataChanged(m_metaData);\n\n TRACE_EXIT_0();\n}\n\nQT_END_NAMESPACE\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPainterPolyDataMapper.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkPainterPolyDataMapper.h\"\n\n#include \"vtkChooserPainter.h\"\n#include \"vtkClipPlanesPainter.h\"\n#include \"vtkCoincidentTopologyResolutionPainter.h\"\n#include \"vtkCommand.h\"\n#include \"vtkDefaultPainter.h\"\n#include \"vtkDisplayListPainter.h\"\n#include \"vtkGarbageCollector.h\"\n#include \"vtkGenericVertexAttributeMapping.h\"\n#include \"vtkHardwareSelectionPolyDataPainter.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationObjectBaseKey.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPlaneCollection.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkPrimitivePainter.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkScalarsToColorsPainter.h\"\n#include \"vtkStandardPolyDataPainter.h\"\n\nvtkStandardNewMacro(vtkPainterPolyDataMapper);\n\/\/-----------------------------------------------------------------------------\nclass vtkPainterPolyDataMapperObserver : public vtkCommand\n{\npublic:\n static vtkPainterPolyDataMapperObserver* New()\n { return new vtkPainterPolyDataMapperObserver; }\n\n virtual void Execute(vtkObject* caller, unsigned long event, void*)\n {\n vtkPainter* p = vtkPainter::SafeDownCast(caller);\n if (this->Target && p && event == vtkCommand::ProgressEvent)\n {\n this->Target->UpdateProgress(p->GetProgress());\n }\n }\n vtkPainterPolyDataMapperObserver()\n {\n this->Target = 0;\n }\n vtkPainterPolyDataMapper* Target;\n};\n\n\n\/\/-----------------------------------------------------------------------------\nvtkPainterPolyDataMapper::vtkPainterPolyDataMapper()\n{\n this->Painter = 0;\n\n this->PainterInformation = vtkInformation::New();\n\n this->Observer = vtkPainterPolyDataMapperObserver::New();\n this->Observer->Target = this;\n\n vtkDefaultPainter* dp = vtkDefaultPainter::New();\n this->SetPainter(dp);\n dp->Delete();\n\n vtkChooserPainter* cp = vtkChooserPainter::New();\n this->Painter->SetDelegatePainter(cp);\n cp->Delete();\n\n this->SelectionPainter = 0;\n vtkPainter* selPainter = vtkHardwareSelectionPolyDataPainter::New();\n this->SetSelectionPainter(selPainter);\n selPainter->Delete();\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkPainterPolyDataMapper::~vtkPainterPolyDataMapper()\n{\n this->SetPainter(NULL);\n this->SetSelectionPainter(0);\n this->Observer->Target = NULL;\n this->Observer->Delete();\n this->PainterInformation->Delete();\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::MapDataArrayToVertexAttribute(\n const char* vertexAttributeName,\n const char* dataArrayName,\n int field,\n int componentno)\n{\n vtkGenericVertexAttributeMapping* mappings = 0;\n if( this->PainterInformation->Has(\n vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) )\n {\n mappings = vtkGenericVertexAttributeMapping::SafeDownCast(\n this->PainterInformation->Get(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()));\n }\n\n if (mappings==NULL)\n {\n mappings = vtkGenericVertexAttributeMapping::New();\n this->PainterInformation->Set(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE(), mappings);\n mappings->Delete();\n }\n\n mappings->AddMapping(\n vertexAttributeName, dataArrayName, field, componentno);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::MapDataArrayToMultiTextureAttribute(\n int unit,\n const char* dataArrayName,\n int field,\n int componentno)\n{\n vtkGenericVertexAttributeMapping* mappings = 0;\n if( this->PainterInformation->Has(\n vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) )\n {\n mappings = vtkGenericVertexAttributeMapping::SafeDownCast(\n this->PainterInformation->Get(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()));\n }\n\n if (mappings==NULL)\n {\n mappings = vtkGenericVertexAttributeMapping::New();\n this->PainterInformation->Set(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE(), mappings);\n mappings->Delete();\n }\n\n mappings->AddMapping(\n unit, dataArrayName, field, componentno);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::RemoveAllVertexAttributeMappings()\n{\n vtkGenericVertexAttributeMapping* mappings = 0;\n if( this->PainterInformation->Has(\n vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) )\n {\n mappings = vtkGenericVertexAttributeMapping::SafeDownCast(\n this->PainterInformation->Get(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()));\n mappings->RemoveAllMappings();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::RemoveVertexAttributeMapping(\n const char* vertexAttributeName)\n{\n vtkGenericVertexAttributeMapping* mappings = 0;\n if( this->PainterInformation->Has(\n vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) )\n {\n mappings = vtkGenericVertexAttributeMapping::SafeDownCast(\n this->PainterInformation->Get(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()));\n mappings->RemoveMapping(vertexAttributeName);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::SetPainter(vtkPainter* p)\n{\n if (this->Painter)\n {\n this->Painter->RemoveObservers(vtkCommand::ProgressEvent, this->Observer);\n this->Painter->SetInformation(0);\n }\n vtkSetObjectBodyMacro(Painter, vtkPainter, p);\n\n if (this->Painter)\n {\n this->Painter->AddObserver(vtkCommand::ProgressEvent, this->Observer);\n this->Painter->SetInformation(this->PainterInformation);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::SetSelectionPainter(vtkPainter* p)\n{\n if (this->SelectionPainter)\n {\n this->SelectionPainter->SetInformation(0);\n this->SelectionPainter->RemoveObservers(vtkCommand::ProgressEvent, this->Observer);\n }\n vtkSetObjectBodyMacro(SelectionPainter, vtkPainter, p);\n if (this->SelectionPainter)\n {\n this->SelectionPainter->AddObserver(vtkCommand::ProgressEvent, this->Observer);\n this->SelectionPainter->SetInformation(this->PainterInformation);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::ReportReferences(vtkGarbageCollector *collector)\n{\n this->Superclass::ReportReferences(collector);\n vtkGarbageCollectorReport(collector, this->Painter, \"Painter\");\n vtkGarbageCollectorReport(collector, this->SelectionPainter, \"SelectionPainter\");\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::ReleaseGraphicsResources(vtkWindow *w)\n{\n if (this->Painter)\n {\n this->Painter->ReleaseGraphicsResources(w);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::UpdatePainterInformation()\n{\n vtkInformation* info = this->PainterInformation;\n\n info->Set(vtkPainter::STATIC_DATA(), this->Static);\n\n info->Set(vtkScalarsToColorsPainter::USE_LOOKUP_TABLE_SCALAR_RANGE(),\n this->GetUseLookupTableScalarRange());\n info->Set(vtkScalarsToColorsPainter::SCALAR_RANGE(),\n this->GetScalarRange(), 2);\n info->Set(vtkScalarsToColorsPainter::SCALAR_MODE(), this->GetScalarMode());\n info->Set(vtkScalarsToColorsPainter::COLOR_MODE(), this->GetColorMode());\n info->Set(vtkScalarsToColorsPainter::INTERPOLATE_SCALARS_BEFORE_MAPPING(),\n this->GetInterpolateScalarsBeforeMapping());\n info->Set(vtkScalarsToColorsPainter::LOOKUP_TABLE(), this->LookupTable);\n info->Set(vtkScalarsToColorsPainter::SCALAR_VISIBILITY(),\n this->GetScalarVisibility());\n info->Set(vtkScalarsToColorsPainter::ARRAY_ACCESS_MODE(),\n this->ArrayAccessMode);\n info->Set(vtkScalarsToColorsPainter::ARRAY_ID(), this->ArrayId);\n info->Set(vtkScalarsToColorsPainter::ARRAY_NAME(), this->ArrayName);\n info->Set(vtkScalarsToColorsPainter::ARRAY_COMPONENT(), this->ArrayComponent);\n info->Set(vtkScalarsToColorsPainter::SCALAR_MATERIAL_MODE(),\n this->GetScalarMaterialMode());\n\n info->Set(vtkClipPlanesPainter::CLIPPING_PLANES(), this->ClippingPlanes);\n\n info->Set(vtkCoincidentTopologyResolutionPainter::RESOLVE_COINCIDENT_TOPOLOGY(),\n this->GetResolveCoincidentTopology());\n info->Set(vtkCoincidentTopologyResolutionPainter::Z_SHIFT(),\n this->GetResolveCoincidentTopologyZShift());\n double p[2];\n this->GetResolveCoincidentTopologyPolygonOffsetParameters(p[0], p[1]);\n info->Set(vtkCoincidentTopologyResolutionPainter::POLYGON_OFFSET_PARAMETERS(),\n p, 2);\n info->Set(vtkCoincidentTopologyResolutionPainter::POLYGON_OFFSET_FACES(),\n this->GetResolveCoincidentTopologyPolygonOffsetFaces());\n\n int immr = (this->ImmediateModeRendering ||\n vtkMapper::GetGlobalImmediateModeRendering());\n info->Set(vtkDisplayListPainter::IMMEDIATE_MODE_RENDERING(), immr);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::RenderPiece(vtkRenderer* ren, vtkActor* act)\n{\n vtkDataObject *input= this->GetInputDataObject(0, 0);\n\n vtkStandardPolyDataPainter * painter =\n vtkStandardPolyDataPainter::SafeDownCast(this->Painter);\n if (painter != NULL && vtkPolyData::SafeDownCast(input))\n {\n \/\/ FIXME: This is not supported currently for composite datasets.\n vtkInformationVector *inArrayVec =\n this->Information->Get(INPUT_ARRAYS_TO_PROCESS());\n int numArrays = inArrayVec->GetNumberOfInformationObjects();\n\n for(int i = 0; i < numArrays; i++)\n {\n painter->AddMultiTextureCoordsArray(this->GetInputArrayToProcess(i,input));\n }\n }\n\n \/\/\n \/\/ make sure that we've been properly initialized\n \/\/\n if (ren->GetRenderWindow()->CheckAbortStatus())\n {\n return;\n }\n\n if ( input == NULL )\n {\n vtkErrorMacro(<< \"No input!\");\n return;\n }\n else\n {\n this->InvokeEvent(vtkCommand::StartEvent,NULL);\n if (!this->Static)\n {\n this->GetInputAlgorithm()->Update();\n }\n this->InvokeEvent(vtkCommand::EndEvent,NULL);\n\n \/\/ This check is unnecessary since the mapper will be cropped out by culling\n \/\/ if it returns invalid bounds which is what will happen when input has no\n \/\/ points.\n \/\/ vtkIdType numPts = input->GetNumberOfPoints();\n \/\/ if (numPts == 0)\n \/\/ {\n \/\/ vtkDebugMacro(<< \"No points!\");\n \/\/ return;\n \/\/ }\n }\n\n \/\/ Update Painter information if obsolete.\n if (this->PainterUpdateTime < this->GetMTime())\n {\n this->UpdatePainterInformation();\n this->PainterUpdateTime.Modified();\n }\n\n \/\/ make sure our window is current\n ren->GetRenderWindow()->MakeCurrent();\n this->TimeToDraw = 0.0;\n\n \/\/ If we are rendering in selection mode, then we use the selection painter\n \/\/ instead of the standard painter.\n if (this->SelectionPainter && ren->GetSelector())\n {\n this->SelectionPainter->SetInput(input);\n this->SelectionPainter->Render(ren, act, 0xff,\n (this->ForceCompileOnly==1));\n this->TimeToDraw = this->SelectionPainter->GetTimeToDraw();\n }\n else if (this->SelectionPainter && this->SelectionPainter != this->Painter)\n {\n this->SelectionPainter->ReleaseGraphicsResources(ren->GetRenderWindow());\n }\n\n if (this->Painter && ren->GetSelector() == 0)\n {\n \/\/ Pass polydata.\n this->Painter->SetInput(input);\n this->Painter->Render(ren, act, 0xff,this->ForceCompileOnly==1);\n this->TimeToDraw = this->Painter->GetTimeToDraw();\n }\n\n \/\/ If the timer is not accurate enough, set it to a small\n \/\/ time so that it is not zero\n if ( this->TimeToDraw == 0.0 )\n {\n this->TimeToDraw = 0.0001;\n }\n\n this->UpdateProgress(1.0);\n}\n\n\/\/-------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::ComputeBounds()\n{\n this->GetInput()->GetBounds(this->Bounds);\n\n \/\/ if the mapper has a painter, update the bounds in the painter\n vtkPainter *painter = this->GetPainter();\n if (painter)\n {\n \/\/ Update Painter information if obsolete.\n if (this->PainterUpdateTime < this->GetMTime())\n {\n this->UpdatePainterInformation();\n this->PainterUpdateTime.Modified();\n }\n painter->UpdateBounds(this->Bounds);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkPainterPolyDataMapper::GetIsOpaque()\n{\n if (this->ScalarVisibility &&\n this->ColorMode == VTK_COLOR_MODE_DEFAULT)\n {\n vtkPolyData* input =\n vtkPolyData::SafeDownCast(this->GetInputDataObject(0, 0));\n if (input)\n {\n int cellFlag;\n vtkDataArray* scalars = this->GetScalars(input,\n this->ScalarMode, this->ArrayAccessMode, this->ArrayId,\n this->ArrayName, cellFlag);\n if (scalars && scalars->IsA(\"vtkUnsignedCharArray\") &&\n (scalars->GetNumberOfComponents() == 4 \/*(RGBA)*\/ ||\n scalars->GetNumberOfComponents() == 2 \/*(LuminanceAlpha)*\/))\n {\n vtkUnsignedCharArray* colors =\n static_cast<vtkUnsignedCharArray*>(scalars);\n if ((colors->GetNumberOfComponents() == 4 && colors->GetValueRange(3)[0] < 255) ||\n (colors->GetNumberOfComponents() == 2 && colors->GetValueRange(1)[0] < 255))\n {\n \/\/ If the opacity is 255, despite the fact that the user specified\n \/\/ RGBA, we know that the Alpha is 100% opaque. So treat as opaque.\n return false;\n }\n }\n }\n }\n return this->Superclass::GetIsOpaque();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Painter: \" ;\n if (this->Painter)\n {\n os << endl;\n this->Painter->PrintSelf(os, indent.GetNextIndent());\n }\n else\n {\n os << indent << \"(none)\" << endl;\n }\n os << indent << \"SelectionPainter: \" << this->SelectionPainter << endl;\n}\n<commit_msg>BUG #14273: Don't segfault when mapper has empty input.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPainterPolyDataMapper.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n#include \"vtkPainterPolyDataMapper.h\"\n\n#include \"vtkChooserPainter.h\"\n#include \"vtkClipPlanesPainter.h\"\n#include \"vtkCoincidentTopologyResolutionPainter.h\"\n#include \"vtkCommand.h\"\n#include \"vtkDefaultPainter.h\"\n#include \"vtkDisplayListPainter.h\"\n#include \"vtkGarbageCollector.h\"\n#include \"vtkGenericVertexAttributeMapping.h\"\n#include \"vtkHardwareSelectionPolyDataPainter.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationObjectBaseKey.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPlaneCollection.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkPrimitivePainter.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkScalarsToColorsPainter.h\"\n#include \"vtkStandardPolyDataPainter.h\"\n\nvtkStandardNewMacro(vtkPainterPolyDataMapper);\n\/\/-----------------------------------------------------------------------------\nclass vtkPainterPolyDataMapperObserver : public vtkCommand\n{\npublic:\n static vtkPainterPolyDataMapperObserver* New()\n { return new vtkPainterPolyDataMapperObserver; }\n\n virtual void Execute(vtkObject* caller, unsigned long event, void*)\n {\n vtkPainter* p = vtkPainter::SafeDownCast(caller);\n if (this->Target && p && event == vtkCommand::ProgressEvent)\n {\n this->Target->UpdateProgress(p->GetProgress());\n }\n }\n vtkPainterPolyDataMapperObserver()\n {\n this->Target = 0;\n }\n vtkPainterPolyDataMapper* Target;\n};\n\n\n\/\/-----------------------------------------------------------------------------\nvtkPainterPolyDataMapper::vtkPainterPolyDataMapper()\n{\n this->Painter = 0;\n\n this->PainterInformation = vtkInformation::New();\n\n this->Observer = vtkPainterPolyDataMapperObserver::New();\n this->Observer->Target = this;\n\n vtkDefaultPainter* dp = vtkDefaultPainter::New();\n this->SetPainter(dp);\n dp->Delete();\n\n vtkChooserPainter* cp = vtkChooserPainter::New();\n this->Painter->SetDelegatePainter(cp);\n cp->Delete();\n\n this->SelectionPainter = 0;\n vtkPainter* selPainter = vtkHardwareSelectionPolyDataPainter::New();\n this->SetSelectionPainter(selPainter);\n selPainter->Delete();\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkPainterPolyDataMapper::~vtkPainterPolyDataMapper()\n{\n this->SetPainter(NULL);\n this->SetSelectionPainter(0);\n this->Observer->Target = NULL;\n this->Observer->Delete();\n this->PainterInformation->Delete();\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::MapDataArrayToVertexAttribute(\n const char* vertexAttributeName,\n const char* dataArrayName,\n int field,\n int componentno)\n{\n vtkGenericVertexAttributeMapping* mappings = 0;\n if( this->PainterInformation->Has(\n vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) )\n {\n mappings = vtkGenericVertexAttributeMapping::SafeDownCast(\n this->PainterInformation->Get(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()));\n }\n\n if (mappings==NULL)\n {\n mappings = vtkGenericVertexAttributeMapping::New();\n this->PainterInformation->Set(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE(), mappings);\n mappings->Delete();\n }\n\n mappings->AddMapping(\n vertexAttributeName, dataArrayName, field, componentno);\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::MapDataArrayToMultiTextureAttribute(\n int unit,\n const char* dataArrayName,\n int field,\n int componentno)\n{\n vtkGenericVertexAttributeMapping* mappings = 0;\n if( this->PainterInformation->Has(\n vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) )\n {\n mappings = vtkGenericVertexAttributeMapping::SafeDownCast(\n this->PainterInformation->Get(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()));\n }\n\n if (mappings==NULL)\n {\n mappings = vtkGenericVertexAttributeMapping::New();\n this->PainterInformation->Set(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE(), mappings);\n mappings->Delete();\n }\n\n mappings->AddMapping(\n unit, dataArrayName, field, componentno);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::RemoveAllVertexAttributeMappings()\n{\n vtkGenericVertexAttributeMapping* mappings = 0;\n if( this->PainterInformation->Has(\n vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) )\n {\n mappings = vtkGenericVertexAttributeMapping::SafeDownCast(\n this->PainterInformation->Get(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()));\n mappings->RemoveAllMappings();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::RemoveVertexAttributeMapping(\n const char* vertexAttributeName)\n{\n vtkGenericVertexAttributeMapping* mappings = 0;\n if( this->PainterInformation->Has(\n vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) )\n {\n mappings = vtkGenericVertexAttributeMapping::SafeDownCast(\n this->PainterInformation->Get(\n vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()));\n mappings->RemoveMapping(vertexAttributeName);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::SetPainter(vtkPainter* p)\n{\n if (this->Painter)\n {\n this->Painter->RemoveObservers(vtkCommand::ProgressEvent, this->Observer);\n this->Painter->SetInformation(0);\n }\n vtkSetObjectBodyMacro(Painter, vtkPainter, p);\n\n if (this->Painter)\n {\n this->Painter->AddObserver(vtkCommand::ProgressEvent, this->Observer);\n this->Painter->SetInformation(this->PainterInformation);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::SetSelectionPainter(vtkPainter* p)\n{\n if (this->SelectionPainter)\n {\n this->SelectionPainter->SetInformation(0);\n this->SelectionPainter->RemoveObservers(vtkCommand::ProgressEvent, this->Observer);\n }\n vtkSetObjectBodyMacro(SelectionPainter, vtkPainter, p);\n if (this->SelectionPainter)\n {\n this->SelectionPainter->AddObserver(vtkCommand::ProgressEvent, this->Observer);\n this->SelectionPainter->SetInformation(this->PainterInformation);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::ReportReferences(vtkGarbageCollector *collector)\n{\n this->Superclass::ReportReferences(collector);\n vtkGarbageCollectorReport(collector, this->Painter, \"Painter\");\n vtkGarbageCollectorReport(collector, this->SelectionPainter, \"SelectionPainter\");\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::ReleaseGraphicsResources(vtkWindow *w)\n{\n if (this->Painter)\n {\n this->Painter->ReleaseGraphicsResources(w);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::UpdatePainterInformation()\n{\n vtkInformation* info = this->PainterInformation;\n\n info->Set(vtkPainter::STATIC_DATA(), this->Static);\n\n info->Set(vtkScalarsToColorsPainter::USE_LOOKUP_TABLE_SCALAR_RANGE(),\n this->GetUseLookupTableScalarRange());\n info->Set(vtkScalarsToColorsPainter::SCALAR_RANGE(),\n this->GetScalarRange(), 2);\n info->Set(vtkScalarsToColorsPainter::SCALAR_MODE(), this->GetScalarMode());\n info->Set(vtkScalarsToColorsPainter::COLOR_MODE(), this->GetColorMode());\n info->Set(vtkScalarsToColorsPainter::INTERPOLATE_SCALARS_BEFORE_MAPPING(),\n this->GetInterpolateScalarsBeforeMapping());\n info->Set(vtkScalarsToColorsPainter::LOOKUP_TABLE(), this->LookupTable);\n info->Set(vtkScalarsToColorsPainter::SCALAR_VISIBILITY(),\n this->GetScalarVisibility());\n info->Set(vtkScalarsToColorsPainter::ARRAY_ACCESS_MODE(),\n this->ArrayAccessMode);\n info->Set(vtkScalarsToColorsPainter::ARRAY_ID(), this->ArrayId);\n info->Set(vtkScalarsToColorsPainter::ARRAY_NAME(), this->ArrayName);\n info->Set(vtkScalarsToColorsPainter::ARRAY_COMPONENT(), this->ArrayComponent);\n info->Set(vtkScalarsToColorsPainter::SCALAR_MATERIAL_MODE(),\n this->GetScalarMaterialMode());\n\n info->Set(vtkClipPlanesPainter::CLIPPING_PLANES(), this->ClippingPlanes);\n\n info->Set(vtkCoincidentTopologyResolutionPainter::RESOLVE_COINCIDENT_TOPOLOGY(),\n this->GetResolveCoincidentTopology());\n info->Set(vtkCoincidentTopologyResolutionPainter::Z_SHIFT(),\n this->GetResolveCoincidentTopologyZShift());\n double p[2];\n this->GetResolveCoincidentTopologyPolygonOffsetParameters(p[0], p[1]);\n info->Set(vtkCoincidentTopologyResolutionPainter::POLYGON_OFFSET_PARAMETERS(),\n p, 2);\n info->Set(vtkCoincidentTopologyResolutionPainter::POLYGON_OFFSET_FACES(),\n this->GetResolveCoincidentTopologyPolygonOffsetFaces());\n\n int immr = (this->ImmediateModeRendering ||\n vtkMapper::GetGlobalImmediateModeRendering());\n info->Set(vtkDisplayListPainter::IMMEDIATE_MODE_RENDERING(), immr);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::RenderPiece(vtkRenderer* ren, vtkActor* act)\n{\n vtkDataObject *input= this->GetInputDataObject(0, 0);\n\n vtkStandardPolyDataPainter * painter =\n vtkStandardPolyDataPainter::SafeDownCast(this->Painter);\n if (painter != NULL && vtkPolyData::SafeDownCast(input))\n {\n \/\/ FIXME: This is not supported currently for composite datasets.\n vtkInformationVector *inArrayVec =\n this->Information->Get(INPUT_ARRAYS_TO_PROCESS());\n int numArrays = inArrayVec->GetNumberOfInformationObjects();\n\n for(int i = 0; i < numArrays; i++)\n {\n painter->AddMultiTextureCoordsArray(this->GetInputArrayToProcess(i,input));\n }\n }\n\n \/\/\n \/\/ make sure that we've been properly initialized\n \/\/\n if (ren->GetRenderWindow()->CheckAbortStatus())\n {\n return;\n }\n\n if ( input == NULL )\n {\n vtkErrorMacro(<< \"No input!\");\n return;\n }\n else\n {\n this->InvokeEvent(vtkCommand::StartEvent,NULL);\n if (!this->Static)\n {\n this->GetInputAlgorithm()->Update();\n }\n this->InvokeEvent(vtkCommand::EndEvent,NULL);\n\n \/\/ This check is unnecessary since the mapper will be cropped out by culling\n \/\/ if it returns invalid bounds which is what will happen when input has no\n \/\/ points.\n \/\/ vtkIdType numPts = input->GetNumberOfPoints();\n \/\/ if (numPts == 0)\n \/\/ {\n \/\/ vtkDebugMacro(<< \"No points!\");\n \/\/ return;\n \/\/ }\n }\n\n \/\/ Update Painter information if obsolete.\n if (this->PainterUpdateTime < this->GetMTime())\n {\n this->UpdatePainterInformation();\n this->PainterUpdateTime.Modified();\n }\n\n \/\/ make sure our window is current\n ren->GetRenderWindow()->MakeCurrent();\n this->TimeToDraw = 0.0;\n\n \/\/ If we are rendering in selection mode, then we use the selection painter\n \/\/ instead of the standard painter.\n if (this->SelectionPainter && ren->GetSelector())\n {\n this->SelectionPainter->SetInput(input);\n this->SelectionPainter->Render(ren, act, 0xff,\n (this->ForceCompileOnly==1));\n this->TimeToDraw = this->SelectionPainter->GetTimeToDraw();\n }\n else if (this->SelectionPainter && this->SelectionPainter != this->Painter)\n {\n this->SelectionPainter->ReleaseGraphicsResources(ren->GetRenderWindow());\n }\n\n if (this->Painter && ren->GetSelector() == 0)\n {\n \/\/ Pass polydata.\n this->Painter->SetInput(input);\n this->Painter->Render(ren, act, 0xff,this->ForceCompileOnly==1);\n this->TimeToDraw = this->Painter->GetTimeToDraw();\n }\n\n \/\/ If the timer is not accurate enough, set it to a small\n \/\/ time so that it is not zero\n if ( this->TimeToDraw == 0.0 )\n {\n this->TimeToDraw = 0.0001;\n }\n\n this->UpdateProgress(1.0);\n}\n\n\/\/-------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::ComputeBounds()\n{\n if (!this->GetInput())\n {\n vtkMath::UninitializeBounds(this->Bounds);\n return;\n }\n\n this->GetInput()->GetBounds(this->Bounds);\n\n \/\/ if the mapper has a painter, update the bounds in the painter\n vtkPainter *painter = this->GetPainter();\n if (painter)\n {\n \/\/ Update Painter information if obsolete.\n if (this->PainterUpdateTime < this->GetMTime())\n {\n this->UpdatePainterInformation();\n this->PainterUpdateTime.Modified();\n }\n painter->UpdateBounds(this->Bounds);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkPainterPolyDataMapper::GetIsOpaque()\n{\n if (this->ScalarVisibility &&\n this->ColorMode == VTK_COLOR_MODE_DEFAULT)\n {\n vtkPolyData* input =\n vtkPolyData::SafeDownCast(this->GetInputDataObject(0, 0));\n if (input)\n {\n int cellFlag;\n vtkDataArray* scalars = this->GetScalars(input,\n this->ScalarMode, this->ArrayAccessMode, this->ArrayId,\n this->ArrayName, cellFlag);\n if (scalars && scalars->IsA(\"vtkUnsignedCharArray\") &&\n (scalars->GetNumberOfComponents() == 4 \/*(RGBA)*\/ ||\n scalars->GetNumberOfComponents() == 2 \/*(LuminanceAlpha)*\/))\n {\n vtkUnsignedCharArray* colors =\n static_cast<vtkUnsignedCharArray*>(scalars);\n if ((colors->GetNumberOfComponents() == 4 && colors->GetValueRange(3)[0] < 255) ||\n (colors->GetNumberOfComponents() == 2 && colors->GetValueRange(1)[0] < 255))\n {\n \/\/ If the opacity is 255, despite the fact that the user specified\n \/\/ RGBA, we know that the Alpha is 100% opaque. So treat as opaque.\n return false;\n }\n }\n }\n }\n return this->Superclass::GetIsOpaque();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkPainterPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Painter: \" ;\n if (this->Painter)\n {\n os << endl;\n this->Painter->PrintSelf(os, indent.GetNextIndent());\n }\n else\n {\n os << indent << \"(none)\" << endl;\n }\n os << indent << \"SelectionPainter: \" << this->SelectionPainter << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2021 Google LLC\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\/\/ This file wraps the swig_helper.h classes in python using pybind11.\n\/\/ Because pybind11_protobuf does not support building with CMake for OR-Tools,\n\/\/ the API has been transformed to use serialized protos from Python to C++ and\n\/\/ from C++ to python:\n\/\/ from Python to C++: use proto.SerializeToString(). This creates a python\n\/\/ string that is passed to C++ and parsed back to proto.\n\/\/ from C++ to Python, we cast the result of proto.SerializeAsString() to\n\/\/ pybind11::bytes. This is passed back to python, which will reconstruct\n\/\/ the proto using PythonProto.FromString(byte[]).\n\n#include \"ortools\/sat\/swig_helper.h\"\n\n#include <string>\n\n#include \"ortools\/sat\/cp_model.pb.h\"\n#include \"ortools\/util\/sorted_interval_list.h\"\n#include \"pybind11\/functional.h\"\n#include \"pybind11\/pybind11.h\"\n#include \"pybind11\/stl.h\"\n\nusing ::operations_research::Domain;\nusing ::operations_research::sat::CpModelProto;\nusing ::operations_research::sat::CpSatHelper;\nusing ::operations_research::sat::CpSolverResponse;\nusing ::operations_research::sat::IntegerVariableProto;\nusing ::operations_research::sat::SatParameters;\nusing ::operations_research::sat::SolutionCallback;\nusing ::operations_research::sat::SolveWrapper;\nusing ::pybind11::arg;\n\nclass PySolutionCallback : public SolutionCallback {\n public:\n using SolutionCallback::SolutionCallback; \/* Inherit constructors *\/\n\n void OnSolutionCallback() const override {\n ::pybind11::gil_scoped_acquire acquire;\n PYBIND11_OVERRIDE_PURE(\n void, \/* Return type *\/\n SolutionCallback, \/* Parent class *\/\n OnSolutionCallback, \/* Name of function *\/\n \/* This function has no arguments. The trailing comma\n in the previous line is needed for some compilers *\/\n );\n }\n};\n\nvoid SetSerializedParameters(const std::string& serialized_parameters,\n SolveWrapper* solve_wrapper) {\n SatParameters parameters;\n if (parameters.ParseFromString(serialized_parameters)) {\n solve_wrapper->SetParameters(parameters);\n }\n}\n\npybind11::bytes SerializedSolve(const std::string& serialized_model,\n SolveWrapper* solve_wrapper) {\n ::pybind11::gil_scoped_release release;\n CpModelProto model_proto;\n model_proto.ParseFromString(serialized_model);\n return solve_wrapper->Solve(model_proto).SerializeAsString();\n}\n\nstd::string SerializedModelStats(const std::string& serialized_model) {\n CpModelProto model_proto;\n model_proto.ParseFromString(serialized_model);\n return CpSatHelper::ModelStats(model_proto);\n}\n\nstd::string SerializedSolverResponseStats(\n const std::string& serialized_response) {\n CpSolverResponse response_proto;\n response_proto.ParseFromString(serialized_response);\n return CpSatHelper::SolverResponseStats(response_proto);\n}\n\nstd::string SerializedValidateModel(const std::string& serialized_model) {\n CpModelProto model_proto;\n model_proto.ParseFromString(serialized_model);\n return CpSatHelper::ValidateModel(model_proto);\n}\n\nDomain SerializedVariableDomain(const std::string& serialized_variable) {\n IntegerVariableProto variable_proto;\n variable_proto.ParseFromString(serialized_variable);\n return CpSatHelper::VariableDomain(variable_proto);\n}\n\nbool SerializedWriteModelToFile(const std::string& serialized_model,\n const std::string& filename) {\n CpModelProto model_proto;\n model_proto.ParseFromString(serialized_model);\n return CpSatHelper::WriteModelToFile(model_proto, filename);\n}\n\npybind11::bytes SerializedResponse(const SolutionCallback& solution_callback) {\n return solution_callback.Response().SerializeAsString();\n}\n\nPYBIND11_MODULE(swig_helper, m) {\n pybind11::module::import(\"ortools.util.python.sorted_interval_list\");\n\n pybind11::class_<SolutionCallback, PySolutionCallback>(m, \"SolutionCallback\")\n .def(pybind11::init<>())\n .def(\"OnSolutionCallback\", &SolutionCallback::OnSolutionCallback)\n .def(\"BestObjectiveBound\", &SolutionCallback::BestObjectiveBound)\n .def(\"DeterministicTime\", &SolutionCallback::DeterministicTime)\n .def(\"HasResponse\", &SolutionCallback::HasResponse)\n .def(\"NumBinaryPropagations\", &SolutionCallback::NumBinaryPropagations)\n .def(\"NumBooleans\", &SolutionCallback::NumBooleans)\n .def(\"NumBranches\", &SolutionCallback::NumBranches)\n .def(\"NumConflicts\", &SolutionCallback::NumConflicts)\n .def(\"NumIntegerPropagations\", &SolutionCallback::NumIntegerPropagations)\n .def(\"ObjectiveValue\", &SolutionCallback::ObjectiveValue)\n .def_static(\"SerializedResponse\", &SerializedResponse,\n arg(\"solution_callback\"))\n .def(\"SolutionBooleanValue\", &SolutionCallback::SolutionBooleanValue,\n arg(\"index\"))\n .def(\"SolutionIntegerValue\", &SolutionCallback::SolutionIntegerValue,\n arg(\"index\"))\n .def(\"StopSearch\", &SolutionCallback::StopSearch)\n .def(\"UserTime\", &SolutionCallback::UserTime)\n .def(\"WallTime\", &SolutionCallback::WallTime);\n\n pybind11::class_<SolveWrapper>(m, \"SolveWrapper\")\n .def(pybind11::init<>())\n .def(\"AddLogCallback\", &SolveWrapper::AddLogCallback, arg(\"log_callback\"))\n .def(\"AddSolutionCallback\", &SolveWrapper::AddSolutionCallback,\n arg(\"callback\"))\n .def(\"ClearSolutionCallback\", &SolveWrapper::ClearSolutionCallback)\n .def_static(\"SetSerializedParameters\", &SetSerializedParameters,\n arg(\"serialized_parameters\"), arg(\"solve_wrapper\"))\n .def_static(\"SerializedSolve\", &SerializedSolve, arg(\"model_proto\"),\n arg(\"solve_wrapper\"))\n .def(\"StopSearch\", &SolveWrapper::StopSearch);\n\n pybind11::class_<CpSatHelper>(m, \"CpSatHelper\")\n .def_static(\"SerializedModelStats\", &SerializedModelStats,\n arg(\"serialized_model\"))\n .def_static(\"SerializedSolverResponseStats\",\n &SerializedSolverResponseStats, arg(\"serialized_response\"))\n .def_static(\"SerializedValidateModel\", &SerializedValidateModel,\n arg(\"serialized_model\"))\n .def_static(\"SerializedVariableDomain\", &SerializedVariableDomain,\n arg(\"serialized_variable\"))\n .def_static(\"SerializedWriteModelToFile\", &SerializedWriteModelToFile,\n arg(\"serialized_model\"), arg(\"filename\"));\n}\n<commit_msg>python: Fix pymalloc after releasing gil (#3329)<commit_after>\/\/ Copyright 2010-2021 Google LLC\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\/\/ This file wraps the swig_helper.h classes in python using pybind11.\n\/\/ Because pybind11_protobuf does not support building with CMake for OR-Tools,\n\/\/ the API has been transformed to use serialized protos from Python to C++ and\n\/\/ from C++ to python:\n\/\/ from Python to C++: use proto.SerializeToString(). This creates a python\n\/\/ string that is passed to C++ and parsed back to proto.\n\/\/ from C++ to Python, we cast the result of proto.SerializeAsString() to\n\/\/ pybind11::bytes. This is passed back to python, which will reconstruct\n\/\/ the proto using PythonProto.FromString(byte[]).\n\n#include \"ortools\/sat\/swig_helper.h\"\n\n#include <string>\n\n#include \"ortools\/sat\/cp_model.pb.h\"\n#include \"ortools\/util\/sorted_interval_list.h\"\n#include \"pybind11\/functional.h\"\n#include \"pybind11\/pybind11.h\"\n#include \"pybind11\/stl.h\"\n\nusing ::operations_research::Domain;\nusing ::operations_research::sat::CpModelProto;\nusing ::operations_research::sat::CpSatHelper;\nusing ::operations_research::sat::CpSolverResponse;\nusing ::operations_research::sat::IntegerVariableProto;\nusing ::operations_research::sat::SatParameters;\nusing ::operations_research::sat::SolutionCallback;\nusing ::operations_research::sat::SolveWrapper;\nusing ::pybind11::arg;\n\nclass PySolutionCallback : public SolutionCallback {\n public:\n using SolutionCallback::SolutionCallback; \/* Inherit constructors *\/\n\n void OnSolutionCallback() const override {\n ::pybind11::gil_scoped_acquire acquire;\n PYBIND11_OVERRIDE_PURE(\n void, \/* Return type *\/\n SolutionCallback, \/* Parent class *\/\n OnSolutionCallback, \/* Name of function *\/\n \/* This function has no arguments. The trailing comma\n in the previous line is needed for some compilers *\/\n );\n }\n};\n\nvoid SetSerializedParameters(const std::string& serialized_parameters,\n SolveWrapper* solve_wrapper) {\n SatParameters parameters;\n if (parameters.ParseFromString(serialized_parameters)) {\n solve_wrapper->SetParameters(parameters);\n }\n}\n\npybind11::bytes SerializedSolve(const std::string& serialized_model,\n SolveWrapper* solve_wrapper) {\n std::string result;\n {\n ::pybind11::gil_scoped_release release;\n CpModelProto model_proto;\n model_proto.ParseFromString(serialized_model);\n result = solve_wrapper->Solve(model_proto).SerializeAsString();\n }\n return result;\n}\n\nstd::string SerializedModelStats(const std::string& serialized_model) {\n CpModelProto model_proto;\n model_proto.ParseFromString(serialized_model);\n return CpSatHelper::ModelStats(model_proto);\n}\n\nstd::string SerializedSolverResponseStats(\n const std::string& serialized_response) {\n CpSolverResponse response_proto;\n response_proto.ParseFromString(serialized_response);\n return CpSatHelper::SolverResponseStats(response_proto);\n}\n\nstd::string SerializedValidateModel(const std::string& serialized_model) {\n CpModelProto model_proto;\n model_proto.ParseFromString(serialized_model);\n return CpSatHelper::ValidateModel(model_proto);\n}\n\nDomain SerializedVariableDomain(const std::string& serialized_variable) {\n IntegerVariableProto variable_proto;\n variable_proto.ParseFromString(serialized_variable);\n return CpSatHelper::VariableDomain(variable_proto);\n}\n\nbool SerializedWriteModelToFile(const std::string& serialized_model,\n const std::string& filename) {\n CpModelProto model_proto;\n model_proto.ParseFromString(serialized_model);\n return CpSatHelper::WriteModelToFile(model_proto, filename);\n}\n\npybind11::bytes SerializedResponse(const SolutionCallback& solution_callback) {\n return solution_callback.Response().SerializeAsString();\n}\n\nPYBIND11_MODULE(swig_helper, m) {\n pybind11::module::import(\"ortools.util.python.sorted_interval_list\");\n\n pybind11::class_<SolutionCallback, PySolutionCallback>(m, \"SolutionCallback\")\n .def(pybind11::init<>())\n .def(\"OnSolutionCallback\", &SolutionCallback::OnSolutionCallback)\n .def(\"BestObjectiveBound\", &SolutionCallback::BestObjectiveBound)\n .def(\"DeterministicTime\", &SolutionCallback::DeterministicTime)\n .def(\"HasResponse\", &SolutionCallback::HasResponse)\n .def(\"NumBinaryPropagations\", &SolutionCallback::NumBinaryPropagations)\n .def(\"NumBooleans\", &SolutionCallback::NumBooleans)\n .def(\"NumBranches\", &SolutionCallback::NumBranches)\n .def(\"NumConflicts\", &SolutionCallback::NumConflicts)\n .def(\"NumIntegerPropagations\", &SolutionCallback::NumIntegerPropagations)\n .def(\"ObjectiveValue\", &SolutionCallback::ObjectiveValue)\n .def_static(\"SerializedResponse\", &SerializedResponse,\n arg(\"solution_callback\"))\n .def(\"SolutionBooleanValue\", &SolutionCallback::SolutionBooleanValue,\n arg(\"index\"))\n .def(\"SolutionIntegerValue\", &SolutionCallback::SolutionIntegerValue,\n arg(\"index\"))\n .def(\"StopSearch\", &SolutionCallback::StopSearch)\n .def(\"UserTime\", &SolutionCallback::UserTime)\n .def(\"WallTime\", &SolutionCallback::WallTime);\n\n pybind11::class_<SolveWrapper>(m, \"SolveWrapper\")\n .def(pybind11::init<>())\n .def(\"AddLogCallback\", &SolveWrapper::AddLogCallback, arg(\"log_callback\"))\n .def(\"AddSolutionCallback\", &SolveWrapper::AddSolutionCallback,\n arg(\"callback\"))\n .def(\"ClearSolutionCallback\", &SolveWrapper::ClearSolutionCallback)\n .def_static(\"SetSerializedParameters\", &SetSerializedParameters,\n arg(\"serialized_parameters\"), arg(\"solve_wrapper\"))\n .def_static(\"SerializedSolve\", &SerializedSolve, arg(\"model_proto\"),\n arg(\"solve_wrapper\"))\n .def(\"StopSearch\", &SolveWrapper::StopSearch);\n\n pybind11::class_<CpSatHelper>(m, \"CpSatHelper\")\n .def_static(\"SerializedModelStats\", &SerializedModelStats,\n arg(\"serialized_model\"))\n .def_static(\"SerializedSolverResponseStats\",\n &SerializedSolverResponseStats, arg(\"serialized_response\"))\n .def_static(\"SerializedValidateModel\", &SerializedValidateModel,\n arg(\"serialized_model\"))\n .def_static(\"SerializedVariableDomain\", &SerializedVariableDomain,\n arg(\"serialized_variable\"))\n .def_static(\"SerializedWriteModelToFile\", &SerializedWriteModelToFile,\n arg(\"serialized_model\"), arg(\"filename\"));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ location.cxx -- class for determining model location in the flightgear world.\n\/\/\n\/\/ Written by Jim Wilson, David Megginson, started April 2002.\n\/\/ Based largely on code by Curtis Olson and Norman Vine.\n\/\/\n\/\/ Copyright (C) 2002 Curtis L. Olson - curt@flightgear.org\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ 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, write to the Free Software\n\/\/ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\/\/\n\/\/ $Id$\n\n\n#include <simgear\/compiler.h>\n\n#ifdef HAVE_CONFIG_H\n# include <simgear_config.h>\n#endif\n\n#include <simgear\/debug\/logstream.hxx>\n#include <simgear\/constants.h>\n#include <simgear\/math\/point3d.hxx>\n#include <simgear\/math\/polar3d.hxx>\n#include <simgear\/math\/sg_geodesy.hxx>\n#include <simgear\/math\/vector.hxx>\n\n#include \"location.hxx\"\n\n\n\/**\n * make model transformation Matrix - based on optimizations by NHV\n *\/\nstatic void MakeTRANS( sgMat4 dst, const double Theta,\n\t\t\tconst double Phi, const double Psi, \n const sgMat4 UP)\n{\n SGfloat cosTheta = (SGfloat) cos(Theta);\n SGfloat sinTheta = (SGfloat) sin(Theta);\n SGfloat cosPhi = (SGfloat) cos(Phi);\n SGfloat sinPhi = (SGfloat) sin(Phi);\n SGfloat sinPsi = (SGfloat) sin(Psi) ;\n SGfloat cosPsi = (SGfloat) cos(Psi) ;\n\n sgMat4 tmp;\n\t\n tmp[0][0] = cosPhi * cosTheta;\n tmp[0][1] =\tsinPhi * cosPsi + cosPhi * -sinTheta * -sinPsi;\n tmp[0][2] =\tsinPhi * sinPsi + cosPhi * -sinTheta * cosPsi;\n\n tmp[1][0] = -sinPhi * cosTheta;\n tmp[1][1] =\tcosPhi * cosPsi + -sinPhi * -sinTheta * -sinPsi;\n tmp[1][2] =\tcosPhi * sinPsi + -sinPhi * -sinTheta * cosPsi;\n\t\n tmp[2][0] = sinTheta;\n tmp[2][1] =\tcosTheta * -sinPsi;\n tmp[2][2] =\tcosTheta * cosPsi;\n\t\n float a = UP[0][0];\n float b = UP[1][0];\n float c = UP[2][0];\n dst[2][0] = a*tmp[0][0] + b*tmp[0][1] + c*tmp[0][2] ;\n dst[1][0] = a*tmp[1][0] + b*tmp[1][1] + c*tmp[1][2] ;\n dst[0][0] = -(a*tmp[2][0] + b*tmp[2][1] + c*tmp[2][2]) ;\n dst[3][0] = SG_ZERO ;\n\n a = UP[0][1];\n b = UP[1][1];\n c = UP[2][1];\n dst[2][1] = a*tmp[0][0] + b*tmp[0][1] + c*tmp[0][2] ;\n dst[1][1] = a*tmp[1][0] + b*tmp[1][1] + c*tmp[1][2] ;\n dst[0][1] = -(a*tmp[2][0] + b*tmp[2][1] + c*tmp[2][2]) ;\n dst[3][1] = SG_ZERO ;\n\n a = UP[0][2];\n c = UP[2][2];\n dst[2][2] = a*tmp[0][0] + c*tmp[0][2] ;\n dst[1][2] = a*tmp[1][0] + c*tmp[1][2] ;\n dst[0][2] = -(a*tmp[2][0] + c*tmp[2][2]) ;\n dst[3][2] = SG_ZERO ;\n\n dst[2][3] = SG_ZERO ;\n dst[1][3] = SG_ZERO ;\n dst[0][3] = SG_ZERO ;\n dst[3][3] = SG_ONE ;\n\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGLocation.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Constructor\nSGLocation::SGLocation( void ):\n _dirty(true),\n _lon_deg(0),\n _lat_deg(0),\n _alt_ft(0),\n _roll_deg(0),\n _pitch_deg(0),\n _heading_deg(0),\n _cur_elev_m(0),\n _tile_center(0)\n{\n sgdZeroVec3(_absolute_view_pos);\n sgZeroVec3(_relative_view_pos);\n sgZeroVec3(_zero_elev_view_pos);\n sgMakeRotMat4( UP, 0.0, 0.0, 0.0 );\n sgMakeRotMat4( TRANS, 0.0, 0.0, 0.0 );\n}\n\n\n\/\/ Destructor\nSGLocation::~SGLocation( void ) {\n}\n\nvoid\nSGLocation::init ()\n{\n}\n\nvoid\nSGLocation::bind ()\n{\n}\n\nvoid\nSGLocation::unbind ()\n{\n}\n\nvoid\nSGLocation::setPosition (double lon_deg, double lat_deg, double alt_ft)\n{\n _dirty = true;\n _lon_deg = lon_deg;\n _lat_deg = lat_deg;\n _alt_ft = alt_ft;\n}\n\nvoid\nSGLocation::setOrientation (double roll_deg, double pitch_deg, double heading_deg)\n{\n _dirty = true;\n _roll_deg = roll_deg;\n _pitch_deg = pitch_deg;\n _heading_deg = heading_deg;\n}\n\ndouble *\nSGLocation::get_absolute_view_pos( const Point3D scenery_center ) \n{\n if ( _dirty ) {\n recalc( scenery_center );\n }\n return _absolute_view_pos;\n}\n\nfloat *\nSGLocation::getRelativeViewPos( const Point3D scenery_center ) \n{\n if ( _dirty ) {\n recalc( scenery_center );\n }\n return _relative_view_pos;\n}\n\nfloat *\nSGLocation::getZeroElevViewPos( const Point3D scenery_center ) \n{\n if ( _dirty ) {\n recalc( scenery_center );\n }\n return _zero_elev_view_pos;\n}\n\n\n\/\/ recalc() is done every time one of the setters is called (making the \n\/\/ cached data \"dirty\") on the next \"get\". It calculates all the outputs \n\/\/ for viewer.\nvoid\nSGLocation::recalc( const Point3D scenery_center )\n{\n\n recalcPosition( _lon_deg, _lat_deg, _alt_ft, scenery_center );\n\n \/\/ Make the world up rotation matrix for eye positioin...\n sgMakeRotMat4( UP, _lon_deg, 0.0, -_lat_deg );\n\n\n \/\/ get the world up radial vector from planet center for output\n sgSetVec3( _world_up, UP[0][0], UP[0][1], UP[0][2] );\n\n \/\/ Creat local matrix with current geodetic position. Converting\n \/\/ the orientation (pitch\/roll\/heading) to vectors.\n MakeTRANS( TRANS, _pitch_deg * SG_DEGREES_TO_RADIANS,\n _roll_deg * SG_DEGREES_TO_RADIANS,\n -_heading_deg * SG_DEGREES_TO_RADIANS,\n UP);\n\n \/\/ Given a vector pointing straight down (-Z), map into onto the\n \/\/ local plane representing \"horizontal\". This should give us the\n \/\/ local direction for moving \"south\".\n sgVec3 minus_z;\n sgSetVec3( minus_z, 0.0, 0.0, -1.0 );\n\n sgmap_vec_onto_cur_surface_plane(_world_up, _relative_view_pos, minus_z,\n\t\t\t\t _surface_south);\n sgNormalizeVec3(_surface_south);\n\n \/\/ now calculate the surface east vector\n sgVec3 world_down;\n sgNegateVec3(world_down, _world_up);\n sgVectorProductVec3(_surface_east, _surface_south, world_down);\n\n set_clean();\n}\n\nvoid\nSGLocation::recalcPosition( double lon_deg, double lat_deg, double alt_ft,\n const Point3D scenery_center ) const\n{\n double lat = lat_deg * SGD_DEGREES_TO_RADIANS;\n double lon = lon_deg * SGD_DEGREES_TO_RADIANS;\n double alt = alt_ft * SG_FEET_TO_METER;\n\n sgGeodToCart(lat, lon, alt, _absolute_view_pos);\n\n int i;\n double ground[3];\n sgGeodToCart(lat, lon, 0, ground);\n for(i=0; i<3; i++)\n _zero_elev_view_pos[i] = ground[i] - _tile_center[i];\n\n \/\/ FIXME: view position should ONLY be calculated in the viewer...\n \/\/ Anything else should calculate their own positions relative to the \n \/\/ viewer's tile_center.\n for(i=0; i<3; i++)\n _relative_view_pos[i] = _absolute_view_pos[i] - scenery_center[i];\n}\n\nvoid\nSGLocation::update (int dt)\n{\n}\n<commit_msg>Frederic Bouvier:<commit_after>\/\/ location.cxx -- class for determining model location in the flightgear world.\n\/\/\n\/\/ Written by Jim Wilson, David Megginson, started April 2002.\n\/\/ Based largely on code by Curtis Olson and Norman Vine.\n\/\/\n\/\/ Copyright (C) 2002 Curtis L. Olson - curt@flightgear.org\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ 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, write to the Free Software\n\/\/ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\/\/\n\/\/ $Id$\n\n\n#include <simgear\/compiler.h>\n\n#ifdef HAVE_CONFIG_H\n# include <simgear_config.h>\n#endif\n\n#include <simgear\/debug\/logstream.hxx>\n#include <simgear\/constants.h>\n#include <simgear\/math\/point3d.hxx>\n#include <simgear\/math\/polar3d.hxx>\n#include <simgear\/math\/sg_geodesy.hxx>\n#include <simgear\/math\/vector.hxx>\n\n#include \"location.hxx\"\n\n\n\/**\n * make model transformation Matrix - based on optimizations by NHV\n *\/\nstatic void MakeTRANS( sgMat4 dst, const double Theta,\n\t\t\tconst double Phi, const double Psi, \n const sgMat4 UP)\n{\n SGfloat cosTheta = (SGfloat) cos(Theta);\n SGfloat sinTheta = (SGfloat) sin(Theta);\n SGfloat cosPhi = (SGfloat) cos(Phi);\n SGfloat sinPhi = (SGfloat) sin(Phi);\n SGfloat sinPsi = (SGfloat) sin(Psi) ;\n SGfloat cosPsi = (SGfloat) cos(Psi) ;\n\n sgMat4 tmp;\n\t\n tmp[0][0] = cosPhi * cosTheta;\n tmp[0][1] =\tsinPhi * cosPsi + cosPhi * -sinTheta * -sinPsi;\n tmp[0][2] =\tsinPhi * sinPsi + cosPhi * -sinTheta * cosPsi;\n\n tmp[1][0] = -sinPhi * cosTheta;\n tmp[1][1] =\tcosPhi * cosPsi + -sinPhi * -sinTheta * -sinPsi;\n tmp[1][2] =\tcosPhi * sinPsi + -sinPhi * -sinTheta * cosPsi;\n\t\n tmp[2][0] = sinTheta;\n tmp[2][1] =\tcosTheta * -sinPsi;\n tmp[2][2] =\tcosTheta * cosPsi;\n\t\n float a = UP[0][0];\n float b = UP[1][0];\n float c = UP[2][0];\n dst[2][0] = a*tmp[0][0] + b*tmp[0][1] + c*tmp[0][2] ;\n dst[1][0] = a*tmp[1][0] + b*tmp[1][1] + c*tmp[1][2] ;\n dst[0][0] = -(a*tmp[2][0] + b*tmp[2][1] + c*tmp[2][2]) ;\n dst[3][0] = SG_ZERO ;\n\n a = UP[0][1];\n b = UP[1][1];\n c = UP[2][1];\n dst[2][1] = a*tmp[0][0] + b*tmp[0][1] + c*tmp[0][2] ;\n dst[1][1] = a*tmp[1][0] + b*tmp[1][1] + c*tmp[1][2] ;\n dst[0][1] = -(a*tmp[2][0] + b*tmp[2][1] + c*tmp[2][2]) ;\n dst[3][1] = SG_ZERO ;\n\n a = UP[0][2];\n c = UP[2][2];\n dst[2][2] = a*tmp[0][0] + c*tmp[0][2] ;\n dst[1][2] = a*tmp[1][0] + c*tmp[1][2] ;\n dst[0][2] = -(a*tmp[2][0] + c*tmp[2][2]) ;\n dst[3][2] = SG_ZERO ;\n\n dst[2][3] = SG_ZERO ;\n dst[1][3] = SG_ZERO ;\n dst[0][3] = SG_ZERO ;\n dst[3][3] = SG_ONE ;\n\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGLocation.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Constructor\nSGLocation::SGLocation( void ):\n _dirty(true),\n _lon_deg(-1000),\n _lat_deg(0),\n _alt_ft(0),\n _roll_deg(0),\n _pitch_deg(0),\n _heading_deg(0),\n _cur_elev_m(0),\n _tile_center(0)\n{\n sgdZeroVec3(_absolute_view_pos);\n sgZeroVec3(_relative_view_pos);\n sgZeroVec3(_zero_elev_view_pos);\n sgMakeRotMat4( UP, 0.0, 0.0, 0.0 );\n sgMakeRotMat4( TRANS, 0.0, 0.0, 0.0 );\n}\n\n\n\/\/ Destructor\nSGLocation::~SGLocation( void ) {\n}\n\nvoid\nSGLocation::init ()\n{\n}\n\nvoid\nSGLocation::bind ()\n{\n}\n\nvoid\nSGLocation::unbind ()\n{\n}\n\nvoid\nSGLocation::setPosition (double lon_deg, double lat_deg, double alt_ft)\n{\n _dirty = true;\n _lon_deg = lon_deg;\n _lat_deg = lat_deg;\n _alt_ft = alt_ft;\n}\n\nvoid\nSGLocation::setOrientation (double roll_deg, double pitch_deg, double heading_deg)\n{\n _dirty = true;\n _roll_deg = roll_deg;\n _pitch_deg = pitch_deg;\n _heading_deg = heading_deg;\n}\n\ndouble *\nSGLocation::get_absolute_view_pos( const Point3D scenery_center ) \n{\n if ( _dirty ) {\n recalc( scenery_center );\n }\n return _absolute_view_pos;\n}\n\nfloat *\nSGLocation::getRelativeViewPos( const Point3D scenery_center ) \n{\n if ( _dirty ) {\n recalc( scenery_center );\n }\n return _relative_view_pos;\n}\n\nfloat *\nSGLocation::getZeroElevViewPos( const Point3D scenery_center ) \n{\n if ( _dirty ) {\n recalc( scenery_center );\n }\n return _zero_elev_view_pos;\n}\n\n\n\/\/ recalc() is done every time one of the setters is called (making the \n\/\/ cached data \"dirty\") on the next \"get\". It calculates all the outputs \n\/\/ for viewer.\nvoid\nSGLocation::recalc( const Point3D scenery_center )\n{\n\n recalcPosition( _lon_deg, _lat_deg, _alt_ft, scenery_center );\n\n \/\/ Make the world up rotation matrix for eye positioin...\n sgMakeRotMat4( UP, _lon_deg, 0.0, -_lat_deg );\n\n\n \/\/ get the world up radial vector from planet center for output\n sgSetVec3( _world_up, UP[0][0], UP[0][1], UP[0][2] );\n\n \/\/ Creat local matrix with current geodetic position. Converting\n \/\/ the orientation (pitch\/roll\/heading) to vectors.\n MakeTRANS( TRANS, _pitch_deg * SG_DEGREES_TO_RADIANS,\n _roll_deg * SG_DEGREES_TO_RADIANS,\n -_heading_deg * SG_DEGREES_TO_RADIANS,\n UP);\n\n \/\/ Given a vector pointing straight down (-Z), map into onto the\n \/\/ local plane representing \"horizontal\". This should give us the\n \/\/ local direction for moving \"south\".\n sgVec3 minus_z;\n sgSetVec3( minus_z, 0.0, 0.0, -1.0 );\n\n sgmap_vec_onto_cur_surface_plane(_world_up, _relative_view_pos, minus_z,\n\t\t\t\t _surface_south);\n sgNormalizeVec3(_surface_south);\n\n \/\/ now calculate the surface east vector\n sgVec3 world_down;\n sgNegateVec3(world_down, _world_up);\n sgVectorProductVec3(_surface_east, _surface_south, world_down);\n\n set_clean();\n}\n\nvoid\nSGLocation::recalcPosition( double lon_deg, double lat_deg, double alt_ft,\n const Point3D scenery_center ) const\n{\n double lat = lat_deg * SGD_DEGREES_TO_RADIANS;\n double lon = lon_deg * SGD_DEGREES_TO_RADIANS;\n double alt = alt_ft * SG_FEET_TO_METER;\n\n sgGeodToCart(lat, lon, alt, _absolute_view_pos);\n\n int i;\n double ground[3];\n sgGeodToCart(lat, lon, 0, ground);\n for(i=0; i<3; i++)\n _zero_elev_view_pos[i] = ground[i] - _tile_center[i];\n\n \/\/ FIXME: view position should ONLY be calculated in the viewer...\n \/\/ Anything else should calculate their own positions relative to the \n \/\/ viewer's tile_center.\n for(i=0; i<3; i++)\n _relative_view_pos[i] = _absolute_view_pos[i] - scenery_center[i];\n}\n\nvoid\nSGLocation::update (int dt)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2017, Vlad Meșco\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\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 ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n#include \"model.h\"\n#include \"window.h\"\n#include \"logger.h\"\n\n#include <FL\/Fl.H>\n\n#include <algorithm>\n#include <vector>\n#include <cassert>\n\nstd::vector<Schema> drumSchemas {\n \/* Basic Drum *\/\n {\n \"Mono\",\n {\n { \"path\", Schema::STRING },\n { \"volume\", Schema::NUMBER },\n },\n },\n \/* Stereo Drum *\/\n {\n \"Stereo\",\n {\n { \"path\", Schema::STRING },\n { \"volume\", Schema::NUMBER },\n { \"stereo\", Schema::STUB, {\n { \"pan\", Schema::READ_ONLY_STRING },\n }},\n { \"params\", Schema::SUBSCHEMA, {\n { \"pan\", Schema::NUMBER },\n }},\n },\n },\n \/* Chorus Drum *\/\n {\n \"Chorus\",\n {\n { \"path\", Schema::STRING },\n { \"volume\", Schema::NUMBER },\n { \"stereo\", Schema::STUB, {\n { \"chorus\", Schema::READ_ONLY_STRING },\n }},\n { \"params\", Schema::SUBSCHEMA, {\n { \"pan\", Schema::NUMBER },\n { \"delay\", Schema::NUMBER },\n { \"amount\", Schema::NUMBER },\n { \"speed\", Schema::NUMBER },\n { \"depth\", Schema::NUMBER },\n }},\n },\n },\n};\n\nstd::vector<Schema> whatSchemas {\n {\n \"Standard\",\n {\n { \"bpm\", Schema::NUMBER },\n },\n },\n};\n\nstd::list<Vindow*> windows;\n\nstd::shared_ptr<Model> load_model(std::string path)\n{\n return {};\n}\n\nvoid save_model(std::shared_ptr<Model> m)\n{\n}\n\nbool is_any_model_dirty()\n{\n return std::any_of(windows.begin(), windows.end(), [](Vindow* w) -> bool {\n return w->GetModel()->dirty;\n });\n}\n\nvoid create_window(std::shared_ptr<Model> m)\n{\n windows.emplace_back(new Vindow(m, drumSchemas, whatSchemas));\n assert(m);\n assert(windows.back()->GetModel());\n windows.back()->show();\n}\n\nvoid destroy_window(Vindow* whom)\n{\n auto found = std::find_if(windows.begin(), windows.end(), [whom](Vindow * w) -> bool {\n return w == whom;\n });\n if(found == windows.end())\n {\n fprintf(stderr, \"window not found... not abort()-ing to not lose data, but it should be fixed\");\n return;\n }\n windows.erase(found);\n Fl::delete_widget(whom);\n}\n\nint main(int argc, char* argv[])\n{\n Fl::scheme(\"gtk+\");\n#if 1\n \/* test code *\/\n std::shared_ptr<Model> m(new Model());\n m->whos.push_back({\n \"kick\",\n &drumSchemas[0],\n {\n { \"path\", \"kick.wav\" },\n { \"volume\", \"100\" },\n }\n });\n m->whos.push_back({\n \"snare\",\n &drumSchemas[1],\n {\n { \"path\", \"snare.wav\" },\n { \"volume\", \"100\" },\n { \"stereo\", \"chorus\" },\n { \"pan\", \"-10\" },\n }\n });\n m->whos.push_back({\n \"hat\",\n &drumSchemas[2],\n {\n { \"path\", \"snare.wav\" },\n { \"volume\", \"100\" },\n { \"stereo\", \"chorus\" },\n { \"pan\", \"-10\" },\n { \"delay\", \"3\" },\n { \"amount\", \"60\" },\n { \"speed\", \"30\" },\n { \"depth\", \"30\" },\n }\n });\n m->whats.push_back({\n \"A1\",\n \"120\",\n &whatSchemas[0],\n {\n { '!', '.', '\/', },\n { '.', '!', ':', },\n { '.', '.', '\/', },\n }});\n m->output.push_back({{ '1' }});\n m->output.push_back({{ '1' }});\n for(size_t i = 0; i < 80; ++i) {\n m->output.push_back({{ '.' }});\n }\n m->output.push_back({{ '1' }});\n create_window(m);\n\n return Fl::run();\n#endif\n}\n<commit_msg>fix indent<commit_after>\/*\nCopyright (c) 2017, Vlad Meșco\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\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 ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n#include \"model.h\"\n#include \"window.h\"\n#include \"logger.h\"\n\n#include <FL\/Fl.H>\n\n#include <algorithm>\n#include <vector>\n#include <cassert>\n\nstd::vector<Schema> drumSchemas {\n \/* Basic Drum *\/\n {\n \"Mono\",\n {\n { \"path\", Schema::STRING },\n { \"volume\", Schema::NUMBER },\n },\n },\n \/* Stereo Drum *\/\n {\n \"Stereo\",\n {\n { \"path\", Schema::STRING },\n { \"volume\", Schema::NUMBER },\n { \"stereo\", Schema::STUB, {\n { \"pan\", Schema::READ_ONLY_STRING },\n }},\n { \"params\", Schema::SUBSCHEMA, {\n { \"pan\", Schema::NUMBER },\n }},\n },\n },\n \/* Chorus Drum *\/\n {\n \"Chorus\",\n {\n { \"path\", Schema::STRING },\n { \"volume\", Schema::NUMBER },\n { \"stereo\", Schema::STUB, {\n { \"chorus\", Schema::READ_ONLY_STRING },\n }},\n { \"params\", Schema::SUBSCHEMA, {\n { \"pan\", Schema::NUMBER },\n { \"delay\", Schema::NUMBER },\n { \"amount\", Schema::NUMBER },\n { \"speed\", Schema::NUMBER },\n { \"depth\", Schema::NUMBER },\n }},\n },\n },\n};\n\nstd::vector<Schema> whatSchemas {\n {\n \"Standard\",\n {\n { \"bpm\", Schema::NUMBER },\n },\n },\n};\n\nstd::list<Vindow*> windows;\n\nstd::shared_ptr<Model> load_model(std::string path)\n{\n return {};\n}\n\nvoid save_model(std::shared_ptr<Model> m)\n{\n}\n\nbool is_any_model_dirty()\n{\n return std::any_of(windows.begin(), windows.end(), [](Vindow* w) -> bool {\n return w->GetModel()->dirty;\n });\n}\n\nvoid create_window(std::shared_ptr<Model> m)\n{\n windows.emplace_back(new Vindow(m, drumSchemas, whatSchemas));\n assert(m);\n assert(windows.back()->GetModel());\n windows.back()->show();\n}\n\nvoid destroy_window(Vindow* whom)\n{\n auto found = std::find_if(windows.begin(), windows.end(), [whom](Vindow * w) -> bool {\n return w == whom;\n });\n if(found == windows.end())\n {\n fprintf(stderr, \"window not found... not abort()-ing to not lose data, but it should be fixed\");\n return;\n }\n windows.erase(found);\n Fl::delete_widget(whom);\n}\n\nint main(int argc, char* argv[])\n{\n Fl::scheme(\"gtk+\");\n#if 1\n \/* test code *\/\n std::shared_ptr<Model> m(new Model());\n m->whos.push_back({\n \"kick\",\n &drumSchemas[0],\n {\n { \"path\", \"kick.wav\" },\n { \"volume\", \"100\" },\n }\n });\n m->whos.push_back({\n \"snare\",\n &drumSchemas[1],\n {\n { \"path\", \"snare.wav\" },\n { \"volume\", \"100\" },\n { \"stereo\", \"chorus\" },\n { \"pan\", \"-10\" },\n }\n });\n m->whos.push_back({\n \"hat\",\n &drumSchemas[2],\n {\n { \"path\", \"snare.wav\" },\n { \"volume\", \"100\" },\n { \"stereo\", \"chorus\" },\n { \"pan\", \"-10\" },\n { \"delay\", \"3\" },\n { \"amount\", \"60\" },\n { \"speed\", \"30\" },\n { \"depth\", \"30\" },\n }\n });\n m->whats.push_back({\n \"A1\",\n \"120\",\n &whatSchemas[0],\n {\n { '!', '.', '\/', },\n { '.', '!', ':', },\n { '.', '.', '\/', },\n }});\n m->output.push_back({{ '1' }});\n m->output.push_back({{ '1' }});\n for(size_t i = 0; i < 80; ++i) {\n m->output.push_back({{ '.' }});\n }\n m->output.push_back({{ '1' }});\n create_window(m);\n\n return Fl::run();\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"kglpainter.h\"\n#include <math.h>\n#include <QtCore\/QDebug>\nclass KGLPainterPrivate\n{\npublic :\n QColor color;\nfloat lineWidth;\nfloat pointSize;\nGLenum polygonMode;\nKGLPointList pointList;\n\n\n\n};\nKGLPainter::KGLPainter(QObject * parent)\n :QObject(parent)\n{\n d = new KGLPainterPrivate;\n d->color = Qt::white;\n d->lineWidth = 1;\n d->pointSize = 1;\n}\n\nKGLPainter::~KGLPainter()\n{\n delete d;\n}\n\n\/\/============Parameter Function\nvoid KGLPainter::setColor(const QColor &col){\n d->color = col;\n}\nvoid KGLPainter::setLineWidth(float width){\n d->lineWidth = width;\n\n}\nvoid KGLPainter::setPointSize(float size){\n d->pointSize=size;\n glPointSize(d->pointSize);\n}\nvoid KGLPainter::setPolygonMode(GLenum mode){\n d->polygonMode = mode;\n glPolygonMode(GL_FRONT_AND_BACK,mode);\n}\nvoid KGLPainter::createRect(const QRectF &rect)\n{\n d->pointList.clear();\n d->pointList.append(KGLPoint(rect.x(), rect.y(),d->color,QPointF(0 , 0)));\n d->pointList.append(KGLPoint(rect.x() + rect.width(), rect.y(),d->color, QPointF(1 , 0)));\n d->pointList.append(KGLPoint(rect.x() + rect.width(), rect.y() + rect.height(),d->color, QPointF(1 , 1)));\n d->pointList.append(KGLPoint(rect.x(), rect.y() + rect.height(),d->color, QPointF(0 , 1)));\n \n}\nvoid KGLPainter::createRect(float x, float y, float w, float h){\n createRect(QRectF(x,y,w,h));}\n\nvoid KGLPainter::createLine(const QLineF &line )\n{\n\n d->pointList.clear();\n d->pointList.append(KGLPoint(line.x1(), line.y1(),Qt::white));\n d->pointList.append(KGLPoint(line.x2(), line.y2(),Qt::white));\n\n\n}\nvoid KGLPainter::createLine(float x1, float y1, float x2, float y2){\n createLine(QLineF(x1,y1,x2,y2));\n}\n\nvoid KGLPainter::createCircle(const QPointF ¢er, float radius, float step)\n{\n if ( step <3)\n {\n qDebug()<<\"cannot create it. Use createline...\";\n return;\n }\n d->pointList.clear();\n d->pointList.append(\n KGLPoint(center.x(),center.y(),d->color,QPointF(center.x() ,center.y())));\n\n float radStep = 2*M_PI\/step;\n\n for(float i=0; i<=2*M_PI+1; i+=radStep)\n {\n float cosr = (float)cos(i);\n float sinr = (float)sin(i);\n\n float x = cosr*radius + center.x();\n float y = sinr*radius + center.y();\n d->pointList.append(KGLPoint(x,y,d->color,QPointF(cosr ,sinr)));\n }\n\n}\nvoid KGLPainter::createCircle(float cx, float cy, float radius, float step){\n createCircle(QPointF(cx,cy),radius,step);\n}\nvoid KGLPainter::createPolygon(const QPolygonF & polygon)\n{\n d->pointList.clear();\n foreach(QPointF p, polygon)\n d->pointList.append(KGLPoint(p.x(),p.y(),d->color,QPointF(p.x() ,p.y())));\n}\nvoid KGLPainter::draw(GLenum mode)\n{\n glLineWidth(d->lineWidth);\n glPointSize(d->pointSize);\n glPolygonMode(GL_FRONT_AND_BACK,d->polygonMode);\n\n\n \/*enable client state *\/\n glEnableClientState(GL_VERTEX_ARRAY);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n glEnableClientState(GL_COLOR_ARRAY);\n\n \/* send data *\/\n glVertexPointer(2, GL_FLOAT,sizeof(KGLPoint),d->pointList.vertexStart());\n glTexCoordPointer(2,GL_FLOAT,sizeof(KGLPoint),d->pointList.texCoordStart());\n glColorPointer(4, GL_FLOAT,sizeof(KGLPoint),d->pointList.colorStart());\n\n \/\/ \/* create vertex *\/\n glDrawArrays(mode, 0, d->pointList.size());\n\n \/* disable client state *\/\n glDisableClientState(GL_COLOR_ARRAY);\n glDisableClientState(GL_TEXTURE_COORD_ARRAY);\n glDisableClientState(GL_VERTEX_ARRAY);\n\n glLineWidth(1);\n glPointSize(1);\n glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);\n}\n\nvoid KGLPainter::drawRect(const QRectF &rect){\n createRect(rect);\n draw(GL_POLYGON);\n}\nvoid KGLPainter::drawRect(float x, float y, float w, float h){\n createRect(x,y,w,h);\n draw(GL_POLYGON);\n}\nvoid KGLPainter::drawLine(const QLineF &line){\n createLine(line);\n draw(GL_LINE);\n\n}\nvoid KGLPainter::drawLine(float x1, float y1, float x2, float y2){\n createLine(x1,y1,x2,y2);\n draw(GL_LINE);\n}\nvoid KGLPainter::drawPoint(const QPointF &point){\n glBegin(GL_POINT);\n glVertex2d(point.x(),point.y());\n glEnd();\n}\nvoid KGLPainter::drawPoint(float x, float y){\n glBegin(GL_POINT);\n glVertex2d(x,y);\n glEnd();\n\n}\nvoid KGLPainter::drawCircle(const QPointF ¢er, float radius, float step){\n createCircle(center,radius,step);\n draw(GL_TRIANGLE_FAN);\n}\nvoid KGLPainter::drawCircle(float cx,float cy, float radius, float step ){\n createCircle(cx,cy,radius,step);\n draw(GL_TRIANGLE_FAN);\n}\nvoid KGLPainter::drawPolygon(const QPolygonF & polygon){\n createPolygon(polygon);\n draw(GL_POLYGON);\n\n}\n\n#include \"kglpainter.cpp\"\n<commit_msg>KGL: includes kglpainter.moc instead of kglpainter.cpp at the end of the file, prevent it from infinitely including itself<commit_after>#include \"kglpainter.h\"\n#include <math.h>\n#include <QtCore\/QDebug>\nclass KGLPainterPrivate\n{\npublic :\n QColor color;\nfloat lineWidth;\nfloat pointSize;\nGLenum polygonMode;\nKGLPointList pointList;\n\n\n\n};\nKGLPainter::KGLPainter(QObject * parent)\n :QObject(parent)\n{\n d = new KGLPainterPrivate;\n d->color = Qt::white;\n d->lineWidth = 1;\n d->pointSize = 1;\n}\n\nKGLPainter::~KGLPainter()\n{\n delete d;\n}\n\n\/\/============Parameter Function\nvoid KGLPainter::setColor(const QColor &col){\n d->color = col;\n}\nvoid KGLPainter::setLineWidth(float width){\n d->lineWidth = width;\n\n}\nvoid KGLPainter::setPointSize(float size){\n d->pointSize=size;\n glPointSize(d->pointSize);\n}\nvoid KGLPainter::setPolygonMode(GLenum mode){\n d->polygonMode = mode;\n glPolygonMode(GL_FRONT_AND_BACK,mode);\n}\nvoid KGLPainter::createRect(const QRectF &rect)\n{\n d->pointList.clear();\n d->pointList.append(KGLPoint(rect.x(), rect.y(),d->color,QPointF(0 , 0)));\n d->pointList.append(KGLPoint(rect.x() + rect.width(), rect.y(),d->color, QPointF(1 , 0)));\n d->pointList.append(KGLPoint(rect.x() + rect.width(), rect.y() + rect.height(),d->color, QPointF(1 , 1)));\n d->pointList.append(KGLPoint(rect.x(), rect.y() + rect.height(),d->color, QPointF(0 , 1)));\n \n}\nvoid KGLPainter::createRect(float x, float y, float w, float h){\n createRect(QRectF(x,y,w,h));}\n\nvoid KGLPainter::createLine(const QLineF &line )\n{\n\n d->pointList.clear();\n d->pointList.append(KGLPoint(line.x1(), line.y1(),Qt::white));\n d->pointList.append(KGLPoint(line.x2(), line.y2(),Qt::white));\n\n\n}\nvoid KGLPainter::createLine(float x1, float y1, float x2, float y2){\n createLine(QLineF(x1,y1,x2,y2));\n}\n\nvoid KGLPainter::createCircle(const QPointF ¢er, float radius, float step)\n{\n if ( step <3)\n {\n qDebug()<<\"cannot create it. Use createline...\";\n return;\n }\n d->pointList.clear();\n d->pointList.append(\n KGLPoint(center.x(),center.y(),d->color,QPointF(center.x() ,center.y())));\n\n float radStep = 2*M_PI\/step;\n\n for(float i=0; i<=2*M_PI+1; i+=radStep)\n {\n float cosr = (float)cos(i);\n float sinr = (float)sin(i);\n\n float x = cosr*radius + center.x();\n float y = sinr*radius + center.y();\n d->pointList.append(KGLPoint(x,y,d->color,QPointF(cosr ,sinr)));\n }\n\n}\nvoid KGLPainter::createCircle(float cx, float cy, float radius, float step){\n createCircle(QPointF(cx,cy),radius,step);\n}\nvoid KGLPainter::createPolygon(const QPolygonF & polygon)\n{\n d->pointList.clear();\n foreach(QPointF p, polygon)\n d->pointList.append(KGLPoint(p.x(),p.y(),d->color,QPointF(p.x() ,p.y())));\n}\nvoid KGLPainter::draw(GLenum mode)\n{\n glLineWidth(d->lineWidth);\n glPointSize(d->pointSize);\n glPolygonMode(GL_FRONT_AND_BACK,d->polygonMode);\n\n\n \/*enable client state *\/\n glEnableClientState(GL_VERTEX_ARRAY);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n glEnableClientState(GL_COLOR_ARRAY);\n\n \/* send data *\/\n glVertexPointer(2, GL_FLOAT,sizeof(KGLPoint),d->pointList.vertexStart());\n glTexCoordPointer(2,GL_FLOAT,sizeof(KGLPoint),d->pointList.texCoordStart());\n glColorPointer(4, GL_FLOAT,sizeof(KGLPoint),d->pointList.colorStart());\n\n \/\/ \/* create vertex *\/\n glDrawArrays(mode, 0, d->pointList.size());\n\n \/* disable client state *\/\n glDisableClientState(GL_COLOR_ARRAY);\n glDisableClientState(GL_TEXTURE_COORD_ARRAY);\n glDisableClientState(GL_VERTEX_ARRAY);\n\n glLineWidth(1);\n glPointSize(1);\n glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);\n}\n\nvoid KGLPainter::drawRect(const QRectF &rect){\n createRect(rect);\n draw(GL_POLYGON);\n}\nvoid KGLPainter::drawRect(float x, float y, float w, float h){\n createRect(x,y,w,h);\n draw(GL_POLYGON);\n}\nvoid KGLPainter::drawLine(const QLineF &line){\n createLine(line);\n draw(GL_LINE);\n\n}\nvoid KGLPainter::drawLine(float x1, float y1, float x2, float y2){\n createLine(x1,y1,x2,y2);\n draw(GL_LINE);\n}\nvoid KGLPainter::drawPoint(const QPointF &point){\n glBegin(GL_POINT);\n glVertex2d(point.x(),point.y());\n glEnd();\n}\nvoid KGLPainter::drawPoint(float x, float y){\n glBegin(GL_POINT);\n glVertex2d(x,y);\n glEnd();\n\n}\nvoid KGLPainter::drawCircle(const QPointF ¢er, float radius, float step){\n createCircle(center,radius,step);\n draw(GL_TRIANGLE_FAN);\n}\nvoid KGLPainter::drawCircle(float cx,float cy, float radius, float step ){\n createCircle(cx,cy,radius,step);\n draw(GL_TRIANGLE_FAN);\n}\nvoid KGLPainter::drawPolygon(const QPolygonF & polygon){\n createPolygon(polygon);\n draw(GL_POLYGON);\n\n}\n\n#include \"kglpainter.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>#include \"core.h\"\n#include \"chip.h\"\n\n#include \"network.h\"\n#include \"ocache.h\"\n#include \"syscall_model.h\"\n#include \"sync_client.h\"\n#include \"network_types.h\"\n#include \"memory_manager.h\"\n\n#include \"log.h\"\n#define LOG_DEFAULT_RANK core_tid\n#define LOG_DEFAULT_MODULE CORE\n\n\/\/ externally defined vars\n\nextern LEVEL_BASE::KNOB<Boolean> g_knob_enable_performance_modeling;\nextern LEVEL_BASE::KNOB<Boolean> g_knob_enable_dcache_modeling;\nextern LEVEL_BASE::KNOB<Boolean> g_knob_enable_icache_modeling;\n\nextern LEVEL_BASE::KNOB<UInt32> g_knob_cache_size;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_line_size;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_associativity;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_mutation_interval;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_threshold_hit;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_threshold_miss;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_size;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_associativity;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_max_search_depth;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_threshold_hit;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_threshold_miss;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_size;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_associativity;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_max_search_depth; \n\n\nusing namespace std;\n\nint Core::coreInit(int tid, int num_mod)\n{\n core_tid = tid;\n core_num_mod = num_mod;\n\n network = new Network(this);\n\n if ( g_knob_enable_performance_modeling ) \n {\n perf_model = new PerfModel(\"performance modeler\");\n LOG_PRINT(\"Instantiated performance model.\");\n } else \n {\n perf_model = (PerfModel *) NULL; \n } \n\n if ( g_knob_enable_dcache_modeling || g_knob_enable_icache_modeling ) \n {\n\t\tocache = new OCache(\"organic cache\", \n g_knob_cache_size.Value() * k_KILO,\n g_knob_line_size.Value(),\n g_knob_associativity.Value(),\n g_knob_mutation_interval.Value(),\n g_knob_dcache_threshold_hit.Value(),\n g_knob_dcache_threshold_miss.Value(),\n g_knob_dcache_size.Value() * k_KILO,\n g_knob_dcache_associativity.Value(),\n g_knob_dcache_max_search_depth.Value(),\n g_knob_icache_threshold_hit.Value(),\n g_knob_icache_threshold_miss.Value(),\n g_knob_icache_size.Value() * k_KILO,\n g_knob_icache_associativity.Value(),\n g_knob_icache_max_search_depth.Value()); \n\n \tLOG_PRINT(\"instantiated organic cache model\");\n \n\t} else \n {\n ocache = (OCache *) NULL;\n } \n\n if ( g_config->isSimulatingSharedMemory() ) {\n \n assert( g_knob_enable_dcache_modeling ); \n\n LOG_PRINT(\"instantiated memory manager model\");\n memory_manager = new MemoryManager(this, ocache);\n\n } else {\n\n memory_manager = (MemoryManager *) NULL;\n LOG_PRINT(\"No Memory Manager being used\");\n \n }\n\n syscall_model = new SyscallMdl(network);\n\/\/ InitLock(&dcache_lock);\n sync_client = new SyncClient(this);\n\n return 0;\n}\n\nint Core::coreSendW(int sender, int receiver, char *buffer, int size)\n{\n \/\/ Create a net packet\n NetPacket packet;\n packet.sender= sender;\n packet.receiver= receiver;\n packet.type = USER;\n packet.length = size;\n packet.data = buffer;\n\n \/*\n packet.data = new char[size];\n for(int i = 0; i < size; i++)\n packet.data[i] = buffer[i];\n *\/\n\n SInt32 sent = network->netSend(packet);\n\n assert(sent == size);\n\n return sent == size ? 0 : -1;\n}\n\nint Core::coreRecvW(int sender, int receiver, char *buffer, int size)\n{\n NetPacket packet;\n NetMatch match;\n\n match.senders.push_back(sender);\n match.types.push_back(USER);\n\n packet = network->netRecv(match);\n\n LOG_PRINT(\"Got packet: from %i, to %i, type %i, len %i\", packet.sender, packet.receiver, (SInt32)packet.type, packet.length);\n\n assert((unsigned)size == packet.length);\n\n memcpy(buffer, packet.data, size);\n\n \/\/ De-allocate dynamic memory\n \/\/ Is this the best place to de-allocate packet.data ?? \n delete [] (Byte*)packet.data;\n\n return (unsigned)size == packet.length ? 0 : -1;\n}\n\nvoid Core::fini(int code, void *v, ostream& out)\n{\n if ( g_knob_enable_performance_modeling )\n {\n out << \"General:\\n\";\n perf_model->fini(code, v, out);\n network->outputSummary(out);\n }\n\n if ( g_knob_enable_dcache_modeling || g_knob_enable_icache_modeling )\n ocache->fini(code,v,out);\n\n delete sync_client;\n delete syscall_model;\n delete ocache;\n delete perf_model;\n delete network;\n}\n\n\n\/\/ organic cache wrappers\n\nbool Core::icacheRunLoadModel(IntPtr i_addr, UInt32 size)\n{ return ocache->runICacheLoadModel(i_addr, size).first; }\n\n\/*\n * dcacheRunModel (mem_operation_t operation, IntPtr d_addr, char* data_buffer, UInt32 data_size)\n *\n * Arguments:\n * d_addr :: address of location we want to access (read or write)\n * shmem_req_t :: READ or WRITE\n * data_buffer :: buffer holding data for WRITE or buffer which must be written on a READ\n * data_size :: size of data we must read\/write\n *\n * Return Value:\n * hit :: Say whether there has been at least one cache hit or not\n *\/\nbool Core::dcacheRunModel(mem_operation_t operation, IntPtr d_addr, char* data_buffer, UInt32 data_size)\n{\n\tshmem_req_t shmem_operation;\n\t\n\tif (operation == LOAD) {\n\t\tshmem_operation = READ;\n\t}\n\telse {\n\t\tshmem_operation = WRITE;\n\t}\n\n\tif (g_config->isSimulatingSharedMemory()) {\n LOG_PRINT(\"%s - ADDR: %x, data_size: %u, END!!\", ((operation==LOAD) ? \" READ \" : \" WRITE \"), d_addr, data_size);\n\n\t\tbool all_hits = true;\n\n\t\tif (data_size <= 0) {\n\t\t\treturn (true);\n\t\t\t\/\/ TODO: this is going to affect the statistics even though no shared_mem action is taking place\n\t\t}\n\n\t\tIntPtr begin_addr = d_addr;\n\t\tIntPtr end_addr = d_addr + data_size;\n\t \tIntPtr begin_addr_aligned = begin_addr - (begin_addr % ocache->dCacheLineSize());\n\t\tIntPtr end_addr_aligned = end_addr - (end_addr % ocache->dCacheLineSize());\n\t\tchar *curr_data_buffer_head = data_buffer;\n\n\t\t\/\/TODO set the size parameter correctly, based on the size of the data buffer\n\t\t\/\/TODO does this spill over to another line? should shared_mem test look at other DRAM entries?\n\t\tfor (IntPtr curr_addr_aligned = begin_addr_aligned ; curr_addr_aligned <= end_addr_aligned \/* Note <= *\/; curr_addr_aligned += ocache->dCacheLineSize())\n\t\t{\n\t\t\t\/\/ Access the cache one line at a time\n\t\t\tUInt32 curr_offset;\n\t\t\tUInt32 curr_size;\n\n\t\t\t\/\/ Determine the offset\n\t\t\t\/\/ TODO fix curr_size calculations\n\t\t\t\/\/ FIXME: Check if all this is correct\n\t\t\tif (curr_addr_aligned == begin_addr_aligned) {\n\t\t\t\tcurr_offset = begin_addr % ocache->dCacheLineSize();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcurr_offset = 0;\n\t\t\t}\n\n\t\t\t\/\/ Determine the size\n\t\t\tif (curr_addr_aligned == end_addr_aligned) {\n\t\t\t\tcurr_size = (end_addr % ocache->dCacheLineSize()) - (curr_offset);\n\t\t\t\tif (curr_size == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcurr_size = ocache->dCacheLineSize() - (curr_offset);\n\t\t\t}\n \n LOG_PRINT(\"Start InitiateSharedMemReq: ADDR: %x, offset: %u, curr_size: %u\", curr_addr_aligned, curr_offset, curr_size);\n\n\t\t\tif (!memory_manager->initiateSharedMemReq(shmem_operation, curr_addr_aligned, curr_offset, curr_data_buffer_head, curr_size)) {\n\t\t\t\t\/\/ If it is a LOAD operation, 'initiateSharedMemReq' causes curr_data_buffer_head to be automatically filled in\n\t\t\t\t\/\/ If it is a STORE operation, 'initiateSharedMemReq' reads the data from curr_data_buffer_head\n\t\t\t\tall_hits = false;\n\t\t\t}\n\t\t\t\n LOG_PRINT(\"End InitiateSharedMemReq: ADDR: %u, offset: %u, curr_size: %u\", curr_addr_aligned, curr_offset, curr_size);\n\n\t\t\t\/\/ Increment the buffer head\n\t\t\tcurr_data_buffer_head += curr_size;\n\t\t}\n\n LOG_PRINT(\"%s - ADDR: %x, data_size: %u, END!!\", ((operation==LOAD) ? \" READ \" : \" WRITE \"), d_addr, data_size);\n\t\t\n\t\treturn all_hits;\t\t \n \n\t} \n\telse \n\t{\n\t \/\/ run this if we aren't using shared_memory\n\t\t\/\/ FIXME: I am not sure this is right\n\t\t\/\/ What if the initial data for this address is in some other core's DRAM (which is on some other host machine)\n\t\tif(operation == LOAD)\n\t\t\treturn ocache->runDCacheLoadModel(d_addr, data_size).first;\n\t\telse\n\t\t\treturn ocache->runDCacheStoreModel(d_addr, data_size).first;\n }\n}\n\nvoid Core::debugSetCacheState(IntPtr address, CacheState::cstate_t cstate, char *c_data)\n{\n\tmemory_manager->debugSetCacheState(address, cstate, c_data);\n}\n\nbool Core::debugAssertCacheState(IntPtr address, CacheState::cstate_t expected_cstate, char *expected_data)\n{\n\treturn memory_manager->debugAssertCacheState(address, expected_cstate, expected_data);\n}\n\nvoid Core::debugSetDramState(IntPtr address, DramDirectoryEntry::dstate_t dstate, vector<UInt32> sharers_list, char *d_data)\n{\n\tmemory_manager->debugSetDramState(address, dstate, sharers_list, d_data);\t\t \n}\n\nbool Core::debugAssertDramState(IntPtr address, DramDirectoryEntry::dstate_t dstate, vector<UInt32> sharers_list, char *d_data)\n{\n\treturn memory_manager->debugAssertDramState(address, dstate, sharers_list, d_data);\n}\n\n<commit_msg>[core] Fix a log message format.<commit_after>#include \"core.h\"\n#include \"chip.h\"\n\n#include \"network.h\"\n#include \"ocache.h\"\n#include \"syscall_model.h\"\n#include \"sync_client.h\"\n#include \"network_types.h\"\n#include \"memory_manager.h\"\n\n#include \"log.h\"\n#define LOG_DEFAULT_RANK core_tid\n#define LOG_DEFAULT_MODULE CORE\n\n\/\/ externally defined vars\n\nextern LEVEL_BASE::KNOB<Boolean> g_knob_enable_performance_modeling;\nextern LEVEL_BASE::KNOB<Boolean> g_knob_enable_dcache_modeling;\nextern LEVEL_BASE::KNOB<Boolean> g_knob_enable_icache_modeling;\n\nextern LEVEL_BASE::KNOB<UInt32> g_knob_cache_size;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_line_size;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_associativity;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_mutation_interval;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_threshold_hit;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_threshold_miss;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_size;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_associativity;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_dcache_max_search_depth;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_threshold_hit;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_threshold_miss;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_size;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_associativity;\nextern LEVEL_BASE::KNOB<UInt32> g_knob_icache_max_search_depth; \n\n\nusing namespace std;\n\nint Core::coreInit(int tid, int num_mod)\n{\n core_tid = tid;\n core_num_mod = num_mod;\n\n network = new Network(this);\n\n if ( g_knob_enable_performance_modeling ) \n {\n perf_model = new PerfModel(\"performance modeler\");\n LOG_PRINT(\"Instantiated performance model.\");\n } else \n {\n perf_model = (PerfModel *) NULL; \n } \n\n if ( g_knob_enable_dcache_modeling || g_knob_enable_icache_modeling ) \n {\n\t\tocache = new OCache(\"organic cache\", \n g_knob_cache_size.Value() * k_KILO,\n g_knob_line_size.Value(),\n g_knob_associativity.Value(),\n g_knob_mutation_interval.Value(),\n g_knob_dcache_threshold_hit.Value(),\n g_knob_dcache_threshold_miss.Value(),\n g_knob_dcache_size.Value() * k_KILO,\n g_knob_dcache_associativity.Value(),\n g_knob_dcache_max_search_depth.Value(),\n g_knob_icache_threshold_hit.Value(),\n g_knob_icache_threshold_miss.Value(),\n g_knob_icache_size.Value() * k_KILO,\n g_knob_icache_associativity.Value(),\n g_knob_icache_max_search_depth.Value()); \n\n \tLOG_PRINT(\"instantiated organic cache model\");\n \n\t} else \n {\n ocache = (OCache *) NULL;\n } \n\n if ( g_config->isSimulatingSharedMemory() ) {\n \n assert( g_knob_enable_dcache_modeling ); \n\n LOG_PRINT(\"instantiated memory manager model\");\n memory_manager = new MemoryManager(this, ocache);\n\n } else {\n\n memory_manager = (MemoryManager *) NULL;\n LOG_PRINT(\"No Memory Manager being used\");\n \n }\n\n syscall_model = new SyscallMdl(network);\n\/\/ InitLock(&dcache_lock);\n sync_client = new SyncClient(this);\n\n return 0;\n}\n\nint Core::coreSendW(int sender, int receiver, char *buffer, int size)\n{\n \/\/ Create a net packet\n NetPacket packet;\n packet.sender= sender;\n packet.receiver= receiver;\n packet.type = USER;\n packet.length = size;\n packet.data = buffer;\n\n \/*\n packet.data = new char[size];\n for(int i = 0; i < size; i++)\n packet.data[i] = buffer[i];\n *\/\n\n SInt32 sent = network->netSend(packet);\n\n assert(sent == size);\n\n return sent == size ? 0 : -1;\n}\n\nint Core::coreRecvW(int sender, int receiver, char *buffer, int size)\n{\n NetPacket packet;\n NetMatch match;\n\n match.senders.push_back(sender);\n match.types.push_back(USER);\n\n packet = network->netRecv(match);\n\n LOG_PRINT(\"Got packet: from %i, to %i, type %i, len %i\", packet.sender, packet.receiver, (SInt32)packet.type, packet.length);\n\n assert((unsigned)size == packet.length);\n\n memcpy(buffer, packet.data, size);\n\n \/\/ De-allocate dynamic memory\n \/\/ Is this the best place to de-allocate packet.data ?? \n delete [] (Byte*)packet.data;\n\n return (unsigned)size == packet.length ? 0 : -1;\n}\n\nvoid Core::fini(int code, void *v, ostream& out)\n{\n if ( g_knob_enable_performance_modeling )\n {\n out << \"General:\\n\";\n perf_model->fini(code, v, out);\n network->outputSummary(out);\n }\n\n if ( g_knob_enable_dcache_modeling || g_knob_enable_icache_modeling )\n ocache->fini(code,v,out);\n\n delete sync_client;\n delete syscall_model;\n delete ocache;\n delete perf_model;\n delete network;\n}\n\n\n\/\/ organic cache wrappers\n\nbool Core::icacheRunLoadModel(IntPtr i_addr, UInt32 size)\n{ return ocache->runICacheLoadModel(i_addr, size).first; }\n\n\/*\n * dcacheRunModel (mem_operation_t operation, IntPtr d_addr, char* data_buffer, UInt32 data_size)\n *\n * Arguments:\n * d_addr :: address of location we want to access (read or write)\n * shmem_req_t :: READ or WRITE\n * data_buffer :: buffer holding data for WRITE or buffer which must be written on a READ\n * data_size :: size of data we must read\/write\n *\n * Return Value:\n * hit :: Say whether there has been at least one cache hit or not\n *\/\nbool Core::dcacheRunModel(mem_operation_t operation, IntPtr d_addr, char* data_buffer, UInt32 data_size)\n{\n\tshmem_req_t shmem_operation;\n\t\n\tif (operation == LOAD) {\n\t\tshmem_operation = READ;\n\t}\n\telse {\n\t\tshmem_operation = WRITE;\n\t}\n\n\tif (g_config->isSimulatingSharedMemory()) {\n LOG_PRINT(\"%s - ADDR: %x, data_size: %u, END!!\", ((operation==LOAD) ? \" READ \" : \" WRITE \"), d_addr, data_size);\n\n\t\tbool all_hits = true;\n\n\t\tif (data_size <= 0) {\n\t\t\treturn (true);\n\t\t\t\/\/ TODO: this is going to affect the statistics even though no shared_mem action is taking place\n\t\t}\n\n\t\tIntPtr begin_addr = d_addr;\n\t\tIntPtr end_addr = d_addr + data_size;\n\t \tIntPtr begin_addr_aligned = begin_addr - (begin_addr % ocache->dCacheLineSize());\n\t\tIntPtr end_addr_aligned = end_addr - (end_addr % ocache->dCacheLineSize());\n\t\tchar *curr_data_buffer_head = data_buffer;\n\n\t\t\/\/TODO set the size parameter correctly, based on the size of the data buffer\n\t\t\/\/TODO does this spill over to another line? should shared_mem test look at other DRAM entries?\n\t\tfor (IntPtr curr_addr_aligned = begin_addr_aligned ; curr_addr_aligned <= end_addr_aligned \/* Note <= *\/; curr_addr_aligned += ocache->dCacheLineSize())\n\t\t{\n\t\t\t\/\/ Access the cache one line at a time\n\t\t\tUInt32 curr_offset;\n\t\t\tUInt32 curr_size;\n\n\t\t\t\/\/ Determine the offset\n\t\t\t\/\/ TODO fix curr_size calculations\n\t\t\t\/\/ FIXME: Check if all this is correct\n\t\t\tif (curr_addr_aligned == begin_addr_aligned) {\n\t\t\t\tcurr_offset = begin_addr % ocache->dCacheLineSize();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcurr_offset = 0;\n\t\t\t}\n\n\t\t\t\/\/ Determine the size\n\t\t\tif (curr_addr_aligned == end_addr_aligned) {\n\t\t\t\tcurr_size = (end_addr % ocache->dCacheLineSize()) - (curr_offset);\n\t\t\t\tif (curr_size == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcurr_size = ocache->dCacheLineSize() - (curr_offset);\n\t\t\t}\n \n LOG_PRINT(\"Start InitiateSharedMemReq: ADDR: %x, offset: %u, curr_size: %u\", curr_addr_aligned, curr_offset, curr_size);\n\n\t\t\tif (!memory_manager->initiateSharedMemReq(shmem_operation, curr_addr_aligned, curr_offset, curr_data_buffer_head, curr_size)) {\n\t\t\t\t\/\/ If it is a LOAD operation, 'initiateSharedMemReq' causes curr_data_buffer_head to be automatically filled in\n\t\t\t\t\/\/ If it is a STORE operation, 'initiateSharedMemReq' reads the data from curr_data_buffer_head\n\t\t\t\tall_hits = false;\n\t\t\t}\n\t\t\t\n LOG_PRINT(\"End InitiateSharedMemReq: ADDR: %x, offset: %u, curr_size: %u\", curr_addr_aligned, curr_offset, curr_size);\n\n\t\t\t\/\/ Increment the buffer head\n\t\t\tcurr_data_buffer_head += curr_size;\n\t\t}\n\n LOG_PRINT(\"%s - ADDR: %x, data_size: %u, END!!\", ((operation==LOAD) ? \" READ \" : \" WRITE \"), d_addr, data_size);\n\t\t\n\t\treturn all_hits;\t\t \n \n\t} \n\telse \n\t{\n\t \/\/ run this if we aren't using shared_memory\n\t\t\/\/ FIXME: I am not sure this is right\n\t\t\/\/ What if the initial data for this address is in some other core's DRAM (which is on some other host machine)\n\t\tif(operation == LOAD)\n\t\t\treturn ocache->runDCacheLoadModel(d_addr, data_size).first;\n\t\telse\n\t\t\treturn ocache->runDCacheStoreModel(d_addr, data_size).first;\n }\n}\n\nvoid Core::debugSetCacheState(IntPtr address, CacheState::cstate_t cstate, char *c_data)\n{\n\tmemory_manager->debugSetCacheState(address, cstate, c_data);\n}\n\nbool Core::debugAssertCacheState(IntPtr address, CacheState::cstate_t expected_cstate, char *expected_data)\n{\n\treturn memory_manager->debugAssertCacheState(address, expected_cstate, expected_data);\n}\n\nvoid Core::debugSetDramState(IntPtr address, DramDirectoryEntry::dstate_t dstate, vector<UInt32> sharers_list, char *d_data)\n{\n\tmemory_manager->debugSetDramState(address, dstate, sharers_list, d_data);\t\t \n}\n\nbool Core::debugAssertDramState(IntPtr address, DramDirectoryEntry::dstate_t dstate, vector<UInt32> sharers_list, char *d_data)\n{\n\treturn memory_manager->debugAssertDramState(address, dstate, sharers_list, d_data);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"includes.h\"\n\nuint64_t toint(const std::string & s, const int & base){\n \/\/ Changees strings to uint64_t\n uint64_t value = 0;\n switch (base){\n case 2:\n for(const unsigned char & c : s){\n value = (value << 1) + (static_cast <uint8_t> (c) - '\\x30');\n }\n break;\n case 8:\n std::stringstream(s) >> std::oct >> value;\n break;\n case 10:\n std::stringstream(s) >> std::dec >> value;\n break;\n case 16:\n std::stringstream(s) >> std::hex >> value; \/\/ Thanks to Oli Charlesworth @ stackoverflow\n break;\n case 256:\n for(const unsigned char & c : s){\n value = (value << 8) + static_cast <uint8_t> (c);\n }\n break;\n default:\n std::stringstream s; s << std::dec << base;\n throw std::runtime_error(\"Error: toint() undefined for base: \" + s.str());\n break;\n };\n return value;\n}\n\nstd::string little_end(const std::string & str, const unsigned int & base){\n \/\/ Changes a string to its little endian form\n int s = 8 * (base == 2) + 2 * (base == 16) + (base == 256);\n std::string t = \"\";\n for (uint32_t x = 0; x < str.size() \/ s; x++){\n t = str.substr(s * x, s)+ t;\n }\n return t;\n}\n\n\/\/ Changes a binary string to its hexadecimal equivalent\nstd::string bintohex(const std::string & in, bool caps){\n if (in.size() & 3){\n throw std::runtime_error(\"Error: input string length not a multiple of 4.\");\n }\n std::string out(in.size() >> 2, '0');\n for(unsigned int i = 0, j = 0; i < in.size(); i += 4, j++){\n unsigned char c = 0;\n for(uint8_t k = 0; k < 4; k++){\n c = (c << 1) | (in[i + k] == '1');\n }\n\n if (caps){\n out[j] = \"0123456789ABCDEF\"[c];\n }\n else{\n out[j] = \"0123456789abcdef\"[c];\n }\n }\n return out;\n}\n\nstd::string binify(const std::string & in, unsigned int size){\n std::string out(in.size() << 3, 0);\n unsigned int i = 0;\n for(unsigned char const & c : in){\n std::string bin = binify(c);\n for(unsigned char const & b : bin){\n out[i++] = b;\n }\n }\n if (out.size() < size){\n out = std::string(size - out.size(), '0') + out;\n }\n return out;\n}\n\nstd::string binify(unsigned char c){\n std::string out(8, '0');\n uint8_t i = 7;\n while (c){\n out[i--] = \"01\"[c & 1];\n c >>= 1;\n }\n return out;\n}\n\n\/\/ convert a string from binary to ASCII\nstd::string unbinify(const std::string & in){\n if (in.size() & 7){\n throw std::runtime_error(\"Error: input string length not a multiple of 8.\");\n }\n\n std::string out(in.size() >> 3, 0);\n for(unsigned int i = 0, j = 0; i < in.size(); i += 8, j++){\n unsigned char c = 0;\n for(uint8_t k = 0; k < 8; k++){\n c = (c << 1) + (in[i + k] == '1');\n }\n out[j] = c;\n }\n\n return out;\n}\n\n\/\/ Changes an ASCII string to an ASCII string containing the\n\/\/ hexadecimal representation of the original chars\nstd::string hexlify(const std::string & in, bool caps){\n std::string out(in.size() << 1, '0');\n unsigned int i = 0;\n for(unsigned char const & c : in){\n std::string h = hexlify(c, caps);\n out[i++] = h[0];\n out[i++] = h[1];\n }\n\n return out;\n}\n\nstd::string hexlify(const char in, bool caps){\n return makehex(static_cast <uint8_t> (in), 2, caps);\n}\n\nstd::string unhexlify(const std::string & in){\n \/\/ Reverse hexlify\n if (in.size() & 1){\n throw std::runtime_error(\"Error: input string of odd length.\");\n }\n std::string out(in.size() >> 1, 0);\n for(unsigned int x = 0; x < in.size(); x += 2){\n if (('0' <= in[x]) && (in[x] <= '9')){\n out[x >> 1] = static_cast <uint8_t> ((in[x] - '0') << 4);\n }\n else if(('a' <= in[x]) && (in[x] <= 'f')){\n out[x >> 1] = static_cast <uint8_t> ((in[x] - 'a' + 10) << 4);\n }\n else if(('A' <= in[x]) && (in[x] <= 'F')){\n out[x >> 1] = static_cast <uint8_t> ((in[x] - 'A' + 10) << 4);\n }\n else{\n throw std::runtime_error(\"Error: Invalid character found: \" + std::string(1, in[x]));\n }\n if (('0' <= in[x + 1]) && (in[x + 1] <= '9')){\n out[x >> 1] |= static_cast <uint8_t> (in[x + 1] - '0');\n }\n else if(('a' <= in[x + 1]) && (in[x + 1] <= 'f')){\n out[x >> 1] |= static_cast <uint8_t> (in[x + 1] - 'a' + 10);\n }\n else if(('A' <= in[x + 1]) && (in[x + 1] <= 'F')){\n out[x >> 1] |= static_cast <uint8_t> (in[x + 1] - 'A' + 10);\n }\n else{\n throw std::runtime_error(\"Error: Invalid character found: \" + std::string(1, in[x + 1]));\n }\n }\n return out;\n}\n\nstd::string pkcs5(const std::string & data, const unsigned int & blocksize){\n \/\/ Adds PKCS5 Padding\n int pad = ((blocksize - data.size()) % blocksize) % blocksize;\n std::string padding(pad, static_cast <char> (pad));\n return data + padding;\n}\n\nstd::string remove_pkcs5(std::string data){\n \/\/ Removes PKCS Padding\n uint8_t pad = static_cast <uint8_t> (data[data.size() - 1]);\n std::string padding(pad, static_cast <char> (pad));\n if ((pad < data.size()) && (padding == data.substr(data.size() - pad, pad)))\n data = data.substr(0, data.size() - pad);\n return data;\n}\n\n\/\/ adds characters to the front of the string\nstd::string zfill(const std::string & str, const unsigned int & n, const char fill){\n if (n > str.size()){\n return std::string(n - str.size(), fill) + str;\n }\n return str;\n}\n\n\/\/ Left rotate a string\nstd::string ROL(const std::string & str, const std::size_t bits){\n std::string out;\n if (str.size()){\n out = (str + str).substr(bits >> 3, str.size());\n const std::size_t push = bits & 7;\n if (push){\n const std::size_t pull = 8 - push;\n const char mask = (1 << push) - 1;\n const char top = (out[0] >> pull) & mask;\n\n for(std::string::size_type i = 1; i < out.size(); i++){\n out[i - 1] = (out[i - 1] << push) | ((out[i] >> pull) & mask);\n }\n out.back() = (out.back() << push) | top;\n }\n }\n\n return out;\n}\n\n\/\/ and two strings, up to the last character of the shorter string\nstd::string and_strings(const std::string & str1, const std::string & str2){\n std::string::size_type end = std::min(str1.size(), str2.size());\n std::string out = str1.substr(0, end);\n for(std::string::size_type i = 0; i < end; i++){\n out[i] &= str2[i];\n }\n return out;\n}\n\n\/\/ or two strings, up to the last character of the shorter string\nstd::string or_strings(const std::string & str1, const std::string & str2){\n std::string::size_type end = std::min(str1.size(), str2.size());\n std::string out = str1.substr(0, end);\n for(std::string::size_type i = 0; i < end; i++){\n out[i] |= str2[i];\n }\n return out;\n}\n\n\/\/ xor the contents of 2 strings, up to the last character of the shorter string\nstd::string xor_strings(const std::string & str1, const std::string & str2){\n std::string::size_type end = std::min(str1.size(), str2.size());\n std::string out = str1.substr(0, end);\n for(std::string::size_type i = 0; i < end; i++){\n out[i] ^= str2[i];\n }\n return out;\n}\n<commit_msg>Fix #5<commit_after>#include \"includes.h\"\n\nuint64_t toint(const std::string & s, const int & base){\n \/\/ Changees strings to uint64_t\n uint64_t value = 0;\n switch (base){\n case 2:\n for(const unsigned char & c : s){\n value = (value << 1) + (static_cast <uint8_t> (c) - '\\x30');\n }\n break;\n case 8:\n std::stringstream(s) >> std::oct >> value;\n break;\n case 10:\n std::stringstream(s) >> std::dec >> value;\n break;\n case 16:\n std::stringstream(s) >> std::hex >> value; \/\/ Thanks to Oli Charlesworth @ stackoverflow\n break;\n case 256:\n for(const unsigned char & c : s){\n value = (value << 8) + static_cast <uint8_t> (c);\n }\n break;\n default:\n std::stringstream s; s << std::dec << base;\n throw std::runtime_error(\"Error: toint() undefined for base: \" + s.str());\n break;\n };\n return value;\n}\n\nstd::string little_end(const std::string & str, const unsigned int & base){\n \/\/ Changes a string to its little endian form\n int s = 8 * (base == 2) + 2 * (base == 16) + (base == 256);\n std::string t = \"\";\n for (uint32_t x = 0; x < str.size() \/ s; x++){\n t = str.substr(s * x, s)+ t;\n }\n return t;\n}\n\n\/\/ Changes a binary string to its hexadecimal equivalent\nstd::string bintohex(const std::string & in, bool caps){\n if (in.size() & 3){\n throw std::runtime_error(\"Error: input string length not a multiple of 4.\");\n }\n std::string out(in.size() >> 2, '0');\n for(unsigned int i = 0, j = 0; i < in.size(); i += 4, j++){\n unsigned char c = 0;\n for(uint8_t k = 0; k < 4; k++){\n c = (c << 1) | (in[i + k] == '1');\n }\n\n if (caps){\n out[j] = \"0123456789ABCDEF\"[c];\n }\n else{\n out[j] = \"0123456789abcdef\"[c];\n }\n }\n return out;\n}\n\nstd::string binify(const std::string & in, unsigned int size){\n std::string out(in.size() << 3, 0);\n unsigned int i = 0;\n for(unsigned char const & c : in){\n std::string bin = binify(c);\n for(unsigned char const & b : bin){\n out[i++] = b;\n }\n }\n if (out.size() < size){\n out = std::string(size - out.size(), '0') + out;\n }\n return out;\n}\n\nstd::string binify(unsigned char c){\n std::string out(8, '0');\n uint8_t i = 7;\n while (c){\n out[i--] = \"01\"[c & 1];\n c >>= 1;\n }\n return out;\n}\n\n\/\/ convert a string from binary to ASCII\nstd::string unbinify(const std::string & in){\n if (in.size() & 7){\n throw std::runtime_error(\"Error: input string length not a multiple of 8.\");\n }\n\n std::string out(in.size() >> 3, 0);\n for(unsigned int i = 0, j = 0; i < in.size(); i += 8, j++){\n unsigned char c = 0;\n for(uint8_t k = 0; k < 8; k++){\n c = (c << 1) + (in[i + k] == '1');\n }\n out[j] = c;\n }\n\n return out;\n}\n\n\/\/ Changes an ASCII string to an ASCII string containing the\n\/\/ hexadecimal representation of the original chars\nstd::string hexlify(const std::string & in, bool caps){\n std::string out(in.size() << 1, '0');\n unsigned int i = 0;\n for(unsigned char const & c : in){\n std::string h = hexlify(c, caps);\n out[i++] = h[0];\n out[i++] = h[1];\n }\n\n return out;\n}\n\nstd::string hexlify(const char in, bool caps){\n return makehex(static_cast <uint8_t> (in), 2, caps);\n}\n\nstd::string unhexlify(const std::string & in){\n \/\/ Reverse hexlify\n if (in.size() & 1){\n throw std::runtime_error(\"Error: input string of odd length.\");\n }\n std::string out(in.size() >> 1, 0);\n for(unsigned int x = 0; x < in.size(); x += 2){\n if (('0' <= in[x]) && (in[x] <= '9')){\n out[x >> 1] = static_cast <uint8_t> ((in[x] - '0') << 4);\n }\n else if(('a' <= in[x]) && (in[x] <= 'f')){\n out[x >> 1] = static_cast <uint8_t> ((in[x] - 'a' + 10) << 4);\n }\n else if(('A' <= in[x]) && (in[x] <= 'F')){\n out[x >> 1] = static_cast <uint8_t> ((in[x] - 'A' + 10) << 4);\n }\n else{\n throw std::runtime_error(\"Error: Invalid character found: \" + std::string(1, in[x]));\n }\n if (('0' <= in[x + 1]) && (in[x + 1] <= '9')){\n out[x >> 1] |= static_cast <uint8_t> (in[x + 1] - '0');\n }\n else if(('a' <= in[x + 1]) && (in[x + 1] <= 'f')){\n out[x >> 1] |= static_cast <uint8_t> (in[x + 1] - 'a' + 10);\n }\n else if(('A' <= in[x + 1]) && (in[x + 1] <= 'F')){\n out[x >> 1] |= static_cast <uint8_t> (in[x + 1] - 'A' + 10);\n }\n else{\n throw std::runtime_error(\"Error: Invalid character found: \" + std::string(1, in[x + 1]));\n }\n }\n return out;\n}\n\nstd::string pkcs5(const std::string & data, const unsigned int & blocksize){\n \/\/ Adds PKCS5 Padding\n int pad = blocksize - (data.size() % blocksize);\n std::string padding(pad, static_cast <char> (pad));\n return data + padding;\n}\n\nstd::string remove_pkcs5(std::string data){\n \/\/ Removes PKCS Padding\n uint8_t pad = static_cast <uint8_t> (data[data.size() - 1]);\n if ((pad > data.size()) ||\n (std::string(pad, static_cast <char> (pad)) != data.substr(data.size() - pad, pad))) {\n throw std::runtime_error(\"Error: Could not remove pkcs5 padding.\");\n }\n data.resize(data.size() - pad);\n return data;\n}\n\n\/\/ adds characters to the front of the string\nstd::string zfill(const std::string & str, const unsigned int & n, const char fill){\n if (n > str.size()){\n return std::string(n - str.size(), fill) + str;\n }\n return str;\n}\n\n\/\/ Left rotate a string\nstd::string ROL(const std::string & str, const std::size_t bits){\n std::string out;\n if (str.size()){\n out = (str + str).substr(bits >> 3, str.size());\n const std::size_t push = bits & 7;\n if (push){\n const std::size_t pull = 8 - push;\n const char mask = (1 << push) - 1;\n const char top = (out[0] >> pull) & mask;\n\n for(std::string::size_type i = 1; i < out.size(); i++){\n out[i - 1] = (out[i - 1] << push) | ((out[i] >> pull) & mask);\n }\n out.back() = (out.back() << push) | top;\n }\n }\n\n return out;\n}\n\n\/\/ and two strings, up to the last character of the shorter string\nstd::string and_strings(const std::string & str1, const std::string & str2){\n std::string::size_type end = std::min(str1.size(), str2.size());\n std::string out = str1.substr(0, end);\n for(std::string::size_type i = 0; i < end; i++){\n out[i] &= str2[i];\n }\n return out;\n}\n\n\/\/ or two strings, up to the last character of the shorter string\nstd::string or_strings(const std::string & str1, const std::string & str2){\n std::string::size_type end = std::min(str1.size(), str2.size());\n std::string out = str1.substr(0, end);\n for(std::string::size_type i = 0; i < end; i++){\n out[i] |= str2[i];\n }\n return out;\n}\n\n\/\/ xor the contents of 2 strings, up to the last character of the shorter string\nstd::string xor_strings(const std::string & str1, const std::string & str2){\n std::string::size_type end = std::min(str1.size(), str2.size());\n std::string out = str1.substr(0, end);\n for(std::string::size_type i = 0; i < end; i++){\n out[i] ^= str2[i];\n }\n return out;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include \"exp.h\"\n\nint main( int argc , char **argv )\n{\n testing :: InitGoogleTest( &argc , argv ) ;\n return RUN_ALL_TESTS( ) ;\n}\n<commit_msg>Delete mainExp.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <qi\/messaging\/publisher.hpp>\n\nint main(int argc, char *argv[])\n{\n \/\/ Create the publisher, giving it a name that helps to track it\n qi::Publisher publisher(\"time\");\n\n \/\/ Connect the publisher to the master\n const std::string masterAddress = \"127.0.0.1:5555\";\n publisher.connect(masterAddress);\n\n \/\/ Advertise the Topic, giving it a name and an int type\n publisher.advertiseTopic<int>(\"time\/hour\");\n\n \/\/ Publish the hour to the Topic, sending an int\n publisher.publish(\"time\/hour\", 10)\n}\n<commit_msg>Fix publisher example<commit_after>#include <qi\/messaging\/publisher.hpp>\n\nint main(int argc, char *argv[])\n{\n \/\/ Create the publisher, giving it a name that helps to track it\n qi::Publisher publisher(\"time\");\n\n \/\/ Connect the publisher to the master\n const std::string masterAddress = \"127.0.0.1:5555\";\n publisher.connect(masterAddress);\n\n \/\/ Advertise the Topic, giving it a name and an int type\n publisher.advertiseTopic<int>(\"time\/hour\");\n\n \/\/ Publish the hour to the Topic, sending an int\n publisher.publish(\"time\/hour\", 10);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b3dcolor.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 02:24: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#ifndef GCC\n#pragma hdrstop\n#endif\n\n#ifndef _B3D_B3DCOLOR_HXX\n#include \"b3dcolor.hxx\"\n#endif\n\n\/*************************************************************************\n|*\n|* Farbwert interpolieren\n|*\n\\************************************************************************\/\n\nvoid B3dColor::CalcInBetween(Color& rOld1, Color& rOld2, double t)\n{\n if(rOld1 != rOld2)\n {\n UINT16 nFac = (UINT16)(t * 256.0);\n UINT16 nNegFac = 256 - nFac;\n SetRed((UINT8)(((nFac * (UINT16)rOld2.GetRed())\n + (nNegFac * (UINT16)rOld1.GetRed())) >> 8));\n SetGreen((UINT8)(((nFac * (UINT16)rOld2.GetGreen())\n + (nNegFac * (UINT16)rOld1.GetGreen())) >> 8));\n SetBlue((UINT8)(((nFac * (UINT16)rOld2.GetBlue())\n + (nNegFac * (UINT16)rOld1.GetBlue())) >> 8));\n SetTransparency((UINT8)(((nFac * (UINT16)rOld2.GetTransparency())\n + (nNegFac * (UINT16)rOld1.GetTransparency())) >> 8));\n }\n else\n {\n SetColor(rOld1.GetColor());\n }\n}\n\n\/*************************************************************************\n|*\n|* Farbwert Mittelwert finden mit 2 Farben\n|*\n\\************************************************************************\/\n\nvoid B3dColor::CalcMiddle(Color& rOld1, Color& rOld2)\n{\n if(rOld1 != rOld2)\n {\n SetRed((UINT8)(((UINT16)rOld1.GetRed()\n + (UINT16)rOld2.GetRed())>>1));\n SetGreen((UINT8)(((UINT16)rOld1.GetGreen()\n + (UINT16)rOld2.GetGreen())>>1));\n SetBlue((UINT8)(((UINT16)rOld1.GetBlue()\n + (UINT16)rOld2.GetBlue())>>1));\n SetTransparency((UINT8)(((UINT16)rOld1.GetTransparency()\n + (UINT16)rOld2.GetTransparency())>>1));\n }\n else\n {\n SetColor(rOld1.GetColor());\n }\n}\n\n\/*************************************************************************\n|*\n|* Farbwert Mittelwert finden mit 3 Farben\n|*\n\\************************************************************************\/\n\nvoid B3dColor::CalcMiddle(Color& rOld1, Color& rOld2, Color& rOld3)\n{\n if(rOld1 != rOld2)\n {\n if(rOld1 != rOld3)\n {\n \/\/ alle 3 unterschiedlich\n SetRed((UINT8)(((UINT16)rOld1.GetRed()\n + (UINT16)rOld2.GetRed()\n + (UINT16)rOld3.GetRed()) \/ 3L));\n SetGreen((UINT8)(((UINT16)rOld1.GetGreen()\n + (UINT16)rOld2.GetGreen()\n + (UINT16)rOld3.GetGreen()) \/ 3L));\n SetBlue((UINT8)(((UINT16)rOld1.GetBlue()\n + (UINT16)rOld2.GetBlue()\n + (UINT16)rOld3.GetBlue()) \/ 3L));\n SetTransparency((UINT8)(((UINT16)rOld1.GetTransparency()\n + (UINT16)rOld2.GetTransparency()\n + (UINT16)rOld3.GetTransparency()) \/ 3L));\n }\n else\n {\n \/\/ 1 != 2, 1 == 3\n CalcMiddle(rOld1, rOld2);\n }\n }\n else\n {\n \/\/ 1 == 2\n if(rOld1 != rOld3)\n {\n CalcMiddle(rOld1, rOld3);\n }\n else\n {\n \/\/ 1==2, 1==3 -> alle gleich\n SetColor(rOld1.GetColor());\n }\n }\n}\n\n\/*************************************************************************\n|*\n|* Ermittle den Abstand der beiden Farben im Farbraum\n|* Dies geschieht OHNE Wurzelziehen, d.h. es wird als Metrik im RGB\n|* Farbraum hier das Quadrat der 'echten' (gewohnten) Entfernung benutzt\n|*\n\\************************************************************************\/\n\nULONG B3dColor::GetDistance(Color& rOld)\n{\n \/\/ Bei Gleichheit kein Abstand\n if(*this == rOld)\n return 0L;\n\n \/\/ Abstand ermitteln\n long nDistRed = rOld.GetRed() > GetRed() ?\n rOld.GetRed() - GetRed() :\n GetRed() - rOld.GetRed();\n long nDistGreen = rOld.GetGreen() > GetGreen() ?\n rOld.GetGreen() - GetGreen() :\n GetGreen() - rOld.GetGreen();\n long nDistBlue = rOld.GetBlue() > GetBlue() ?\n rOld.GetBlue() - GetBlue() :\n GetBlue() - rOld.GetBlue();\n return (ULONG)(nDistRed * nDistRed\n + nDistGreen * nDistGreen\n + nDistBlue * nDistBlue);\n}\n\n\/*************************************************************************\n|*\n|* Farbaddition mit clamping\n|*\n\\************************************************************************\/\n\nB3dColor& B3dColor::operator+= (const B3dColor& rCol)\n{\n UINT16 nZwi;\n if(rCol.GetRed())\n {\n nZwi = (UINT16)GetRed() + (UINT16)rCol.GetRed();\n if(nZwi > 255)\n nZwi = 255;\n SetRed((UINT8)nZwi);\n }\n if(rCol.GetGreen())\n {\n nZwi = (UINT16)GetGreen() + (UINT16)rCol.GetGreen();\n if(nZwi > 255)\n nZwi = 255;\n SetGreen((UINT8)nZwi);\n }\n if(rCol.GetBlue())\n {\n nZwi = (UINT16)GetBlue() + (UINT16)rCol.GetBlue();\n if(nZwi > 255)\n nZwi = 255;\n SetBlue((UINT8)nZwi);\n }\n if(rCol.GetTransparency())\n {\n nZwi = (UINT16)GetTransparency() + (UINT16)rCol.GetTransparency();\n if(nZwi > 255)\n nZwi = 255;\n SetTransparency((UINT8)nZwi);\n }\n return *this;\n}\n\n\/*************************************************************************\n|*\n|* Farbsubtraktion mit clamping\n|*\n\\************************************************************************\/\n\nB3dColor& B3dColor::operator-= (const B3dColor& rCol)\n{\n INT16 nZwi;\n if(rCol.GetRed())\n {\n nZwi = (INT16)GetRed() - (INT16)rCol.GetRed();\n if(nZwi < 0)\n nZwi = 0;\n SetRed((UINT8)nZwi);\n }\n if(rCol.GetGreen())\n {\n nZwi = (INT16)GetGreen() - (INT16)rCol.GetGreen();\n if(nZwi < 0)\n nZwi = 0;\n SetGreen((UINT8)nZwi);\n }\n if(rCol.GetBlue())\n {\n nZwi = (INT16)GetBlue() - (INT16)rCol.GetBlue();\n if(nZwi < 0)\n nZwi = 0;\n SetBlue((UINT8)nZwi);\n }\n if(rCol.GetTransparency())\n {\n nZwi = (INT16)GetTransparency() - (INT16)rCol.GetTransparency();\n if(nZwi < 0)\n nZwi = 0;\n SetTransparency((UINT8)nZwi);\n }\n return *this;\n}\n\n\/*************************************************************************\n|*\n|* Farbaddition mit clamping, neue Farbe erzeugen\n|*\n\\************************************************************************\/\n\nB3dColor B3dColor::operator+ (const B3dColor& rCol) const\n{\n B3dColor aSum = *this;\n aSum += rCol;\n return aSum;\n}\n\n\/*************************************************************************\n|*\n|* Farbsubtraktion mit clamping, neue Farbe erzeugen\n|*\n\\************************************************************************\/\n\nB3dColor B3dColor::operator- (const B3dColor& rCol) const\n{\n B3dColor aSub = *this;\n aSub -= rCol;\n return aSub;\n}\n\n\/*************************************************************************\n|*\n|* Farbmultiplikation, d.h. Gewichtung der Farben aneinander\n|*\n\\************************************************************************\/\n\nB3dColor& B3dColor::operator*= (const B3dColor& rCol)\n{\n \/\/ urspruengliches Objekt ist die Farbe, rCol die zu berechnende\n \/\/ Gewichtung\n SetRed((UINT8)(((((UINT16)GetRed())+1)\n * (UINT16)rCol.GetRed()) >> 8));\n SetGreen((UINT8)(((((UINT16)GetGreen())+1)\n * (UINT16)rCol.GetGreen()) >> 8));\n SetBlue((UINT8)(((((UINT16)GetBlue())+1)\n * (UINT16)rCol.GetBlue()) >> 8));\n SetTransparency((UINT8)(((((UINT16)GetTransparency())+1)\n * (UINT16)rCol.GetTransparency()) >> 8));\n return *this;\n}\n\n\/*************************************************************************\n|*\n|* Farbmultiplikation, neue Farbe erzeugen\n|*\n\\************************************************************************\/\n\nB3dColor B3dColor::operator* (const B3dColor& rCol) const\n{\n B3dColor aMul = *this;\n aMul *= rCol;\n return aMul;\n}\n\n\/*************************************************************************\n|*\n|* Farbmultiplikation mit Faktor im Bereich [0.0 .. 1.0]\n|*\n\\************************************************************************\/\n\nB3dColor& B3dColor::operator*= (const double fVal)\n{\n ULONG nVal = (ULONG)(fVal * 65536.0);\n SetRed((UINT8)(((ULONG)GetRed() * nVal) >> 16));\n SetGreen((UINT8)(((ULONG)GetGreen() * nVal) >> 16));\n SetBlue((UINT8)(((ULONG)GetBlue() * nVal) >> 16));\n SetTransparency((UINT8)(((ULONG)GetTransparency() * nVal) >> 16));\n return *this;\n}\n\n\/*************************************************************************\n|*\n|* Farbmultiplikation mit Faktor, neue Farbe erzeugen\n|*\n\\************************************************************************\/\n\nB3dColor B3dColor::operator* (const double fVal) const\n{\n B3dColor aMul = *this;\n aMul *= fVal;\n return aMul;\n}\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.3.118); FILE MERGED 2006\/09\/01 17:29:59 kaib 1.3.118.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b3dcolor.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 15:36:39 $\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_goodies.hxx\"\n#ifndef GCC\n#endif\n\n#ifndef _B3D_B3DCOLOR_HXX\n#include \"b3dcolor.hxx\"\n#endif\n\n\/*************************************************************************\n|*\n|* Farbwert interpolieren\n|*\n\\************************************************************************\/\n\nvoid B3dColor::CalcInBetween(Color& rOld1, Color& rOld2, double t)\n{\n if(rOld1 != rOld2)\n {\n UINT16 nFac = (UINT16)(t * 256.0);\n UINT16 nNegFac = 256 - nFac;\n SetRed((UINT8)(((nFac * (UINT16)rOld2.GetRed())\n + (nNegFac * (UINT16)rOld1.GetRed())) >> 8));\n SetGreen((UINT8)(((nFac * (UINT16)rOld2.GetGreen())\n + (nNegFac * (UINT16)rOld1.GetGreen())) >> 8));\n SetBlue((UINT8)(((nFac * (UINT16)rOld2.GetBlue())\n + (nNegFac * (UINT16)rOld1.GetBlue())) >> 8));\n SetTransparency((UINT8)(((nFac * (UINT16)rOld2.GetTransparency())\n + (nNegFac * (UINT16)rOld1.GetTransparency())) >> 8));\n }\n else\n {\n SetColor(rOld1.GetColor());\n }\n}\n\n\/*************************************************************************\n|*\n|* Farbwert Mittelwert finden mit 2 Farben\n|*\n\\************************************************************************\/\n\nvoid B3dColor::CalcMiddle(Color& rOld1, Color& rOld2)\n{\n if(rOld1 != rOld2)\n {\n SetRed((UINT8)(((UINT16)rOld1.GetRed()\n + (UINT16)rOld2.GetRed())>>1));\n SetGreen((UINT8)(((UINT16)rOld1.GetGreen()\n + (UINT16)rOld2.GetGreen())>>1));\n SetBlue((UINT8)(((UINT16)rOld1.GetBlue()\n + (UINT16)rOld2.GetBlue())>>1));\n SetTransparency((UINT8)(((UINT16)rOld1.GetTransparency()\n + (UINT16)rOld2.GetTransparency())>>1));\n }\n else\n {\n SetColor(rOld1.GetColor());\n }\n}\n\n\/*************************************************************************\n|*\n|* Farbwert Mittelwert finden mit 3 Farben\n|*\n\\************************************************************************\/\n\nvoid B3dColor::CalcMiddle(Color& rOld1, Color& rOld2, Color& rOld3)\n{\n if(rOld1 != rOld2)\n {\n if(rOld1 != rOld3)\n {\n \/\/ alle 3 unterschiedlich\n SetRed((UINT8)(((UINT16)rOld1.GetRed()\n + (UINT16)rOld2.GetRed()\n + (UINT16)rOld3.GetRed()) \/ 3L));\n SetGreen((UINT8)(((UINT16)rOld1.GetGreen()\n + (UINT16)rOld2.GetGreen()\n + (UINT16)rOld3.GetGreen()) \/ 3L));\n SetBlue((UINT8)(((UINT16)rOld1.GetBlue()\n + (UINT16)rOld2.GetBlue()\n + (UINT16)rOld3.GetBlue()) \/ 3L));\n SetTransparency((UINT8)(((UINT16)rOld1.GetTransparency()\n + (UINT16)rOld2.GetTransparency()\n + (UINT16)rOld3.GetTransparency()) \/ 3L));\n }\n else\n {\n \/\/ 1 != 2, 1 == 3\n CalcMiddle(rOld1, rOld2);\n }\n }\n else\n {\n \/\/ 1 == 2\n if(rOld1 != rOld3)\n {\n CalcMiddle(rOld1, rOld3);\n }\n else\n {\n \/\/ 1==2, 1==3 -> alle gleich\n SetColor(rOld1.GetColor());\n }\n }\n}\n\n\/*************************************************************************\n|*\n|* Ermittle den Abstand der beiden Farben im Farbraum\n|* Dies geschieht OHNE Wurzelziehen, d.h. es wird als Metrik im RGB\n|* Farbraum hier das Quadrat der 'echten' (gewohnten) Entfernung benutzt\n|*\n\\************************************************************************\/\n\nULONG B3dColor::GetDistance(Color& rOld)\n{\n \/\/ Bei Gleichheit kein Abstand\n if(*this == rOld)\n return 0L;\n\n \/\/ Abstand ermitteln\n long nDistRed = rOld.GetRed() > GetRed() ?\n rOld.GetRed() - GetRed() :\n GetRed() - rOld.GetRed();\n long nDistGreen = rOld.GetGreen() > GetGreen() ?\n rOld.GetGreen() - GetGreen() :\n GetGreen() - rOld.GetGreen();\n long nDistBlue = rOld.GetBlue() > GetBlue() ?\n rOld.GetBlue() - GetBlue() :\n GetBlue() - rOld.GetBlue();\n return (ULONG)(nDistRed * nDistRed\n + nDistGreen * nDistGreen\n + nDistBlue * nDistBlue);\n}\n\n\/*************************************************************************\n|*\n|* Farbaddition mit clamping\n|*\n\\************************************************************************\/\n\nB3dColor& B3dColor::operator+= (const B3dColor& rCol)\n{\n UINT16 nZwi;\n if(rCol.GetRed())\n {\n nZwi = (UINT16)GetRed() + (UINT16)rCol.GetRed();\n if(nZwi > 255)\n nZwi = 255;\n SetRed((UINT8)nZwi);\n }\n if(rCol.GetGreen())\n {\n nZwi = (UINT16)GetGreen() + (UINT16)rCol.GetGreen();\n if(nZwi > 255)\n nZwi = 255;\n SetGreen((UINT8)nZwi);\n }\n if(rCol.GetBlue())\n {\n nZwi = (UINT16)GetBlue() + (UINT16)rCol.GetBlue();\n if(nZwi > 255)\n nZwi = 255;\n SetBlue((UINT8)nZwi);\n }\n if(rCol.GetTransparency())\n {\n nZwi = (UINT16)GetTransparency() + (UINT16)rCol.GetTransparency();\n if(nZwi > 255)\n nZwi = 255;\n SetTransparency((UINT8)nZwi);\n }\n return *this;\n}\n\n\/*************************************************************************\n|*\n|* Farbsubtraktion mit clamping\n|*\n\\************************************************************************\/\n\nB3dColor& B3dColor::operator-= (const B3dColor& rCol)\n{\n INT16 nZwi;\n if(rCol.GetRed())\n {\n nZwi = (INT16)GetRed() - (INT16)rCol.GetRed();\n if(nZwi < 0)\n nZwi = 0;\n SetRed((UINT8)nZwi);\n }\n if(rCol.GetGreen())\n {\n nZwi = (INT16)GetGreen() - (INT16)rCol.GetGreen();\n if(nZwi < 0)\n nZwi = 0;\n SetGreen((UINT8)nZwi);\n }\n if(rCol.GetBlue())\n {\n nZwi = (INT16)GetBlue() - (INT16)rCol.GetBlue();\n if(nZwi < 0)\n nZwi = 0;\n SetBlue((UINT8)nZwi);\n }\n if(rCol.GetTransparency())\n {\n nZwi = (INT16)GetTransparency() - (INT16)rCol.GetTransparency();\n if(nZwi < 0)\n nZwi = 0;\n SetTransparency((UINT8)nZwi);\n }\n return *this;\n}\n\n\/*************************************************************************\n|*\n|* Farbaddition mit clamping, neue Farbe erzeugen\n|*\n\\************************************************************************\/\n\nB3dColor B3dColor::operator+ (const B3dColor& rCol) const\n{\n B3dColor aSum = *this;\n aSum += rCol;\n return aSum;\n}\n\n\/*************************************************************************\n|*\n|* Farbsubtraktion mit clamping, neue Farbe erzeugen\n|*\n\\************************************************************************\/\n\nB3dColor B3dColor::operator- (const B3dColor& rCol) const\n{\n B3dColor aSub = *this;\n aSub -= rCol;\n return aSub;\n}\n\n\/*************************************************************************\n|*\n|* Farbmultiplikation, d.h. Gewichtung der Farben aneinander\n|*\n\\************************************************************************\/\n\nB3dColor& B3dColor::operator*= (const B3dColor& rCol)\n{\n \/\/ urspruengliches Objekt ist die Farbe, rCol die zu berechnende\n \/\/ Gewichtung\n SetRed((UINT8)(((((UINT16)GetRed())+1)\n * (UINT16)rCol.GetRed()) >> 8));\n SetGreen((UINT8)(((((UINT16)GetGreen())+1)\n * (UINT16)rCol.GetGreen()) >> 8));\n SetBlue((UINT8)(((((UINT16)GetBlue())+1)\n * (UINT16)rCol.GetBlue()) >> 8));\n SetTransparency((UINT8)(((((UINT16)GetTransparency())+1)\n * (UINT16)rCol.GetTransparency()) >> 8));\n return *this;\n}\n\n\/*************************************************************************\n|*\n|* Farbmultiplikation, neue Farbe erzeugen\n|*\n\\************************************************************************\/\n\nB3dColor B3dColor::operator* (const B3dColor& rCol) const\n{\n B3dColor aMul = *this;\n aMul *= rCol;\n return aMul;\n}\n\n\/*************************************************************************\n|*\n|* Farbmultiplikation mit Faktor im Bereich [0.0 .. 1.0]\n|*\n\\************************************************************************\/\n\nB3dColor& B3dColor::operator*= (const double fVal)\n{\n ULONG nVal = (ULONG)(fVal * 65536.0);\n SetRed((UINT8)(((ULONG)GetRed() * nVal) >> 16));\n SetGreen((UINT8)(((ULONG)GetGreen() * nVal) >> 16));\n SetBlue((UINT8)(((ULONG)GetBlue() * nVal) >> 16));\n SetTransparency((UINT8)(((ULONG)GetTransparency() * nVal) >> 16));\n return *this;\n}\n\n\/*************************************************************************\n|*\n|* Farbmultiplikation mit Faktor, neue Farbe erzeugen\n|*\n\\************************************************************************\/\n\nB3dColor B3dColor::operator* (const double fVal) const\n{\n B3dColor aMul = *this;\n aMul *= fVal;\n return aMul;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <boost\/python.hpp>\n#include <libtorrent\/alert.hpp>\n#include <libtorrent\/alert_types.hpp>\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nstd::string get_buffer(read_piece_alert const& rpa)\n{\n return rpa.buffer ? std::string(rpa.buffer.get(), rpa.size)\n : std::string();\n}\n\nvoid bind_alert()\n{\n using boost::noncopyable;\n\n {\n scope alert_scope = class_<alert, noncopyable>(\"alert\", no_init)\n .def(\"message\", &alert::message)\n .def(\"what\", &alert::what)\n .def(\"category\", &alert::category)\n#ifndef TORRENT_NO_DEPRECATE\n .def(\"severity\", &alert::severity)\n#endif\n .def(\"__str__\", &alert::message)\n ;\n\n#ifndef TORRENT_NO_DEPRECATE\n enum_<alert::severity_t>(\"severity_levels\")\n .value(\"debug\", alert::debug)\n .value(\"info\", alert::info)\n .value(\"warning\", alert::warning)\n .value(\"critical\", alert::critical)\n .value(\"fatal\", alert::fatal)\n .value(\"none\", alert::none)\n ;\n#endif\n\n enum_<alert::category_t>(\"category_t\")\n .value(\"error_notification\", alert::error_notification)\n .value(\"peer_notification\", alert::peer_notification)\n .value(\"port_mapping_notification\", alert::port_mapping_notification)\n .value(\"storage_notification\", alert::storage_notification)\n .value(\"tracker_notification\", alert::tracker_notification)\n .value(\"debug_notification\", alert::debug_notification)\n .value(\"status_notification\", alert::status_notification)\n .value(\"progress_notification\", alert::progress_notification)\n .value(\"ip_block_notification\", alert::ip_block_notification)\n .value(\"performance_warning\", alert::performance_warning)\n .value(\"all_categories\", alert::all_categories)\n ;\n\n }\n\n class_<torrent_alert, bases<alert>, noncopyable>(\n \"torrent_alert\", no_init\n )\n .def_readonly(\"handle\", &torrent_alert::handle)\n ;\n\n class_<tracker_alert, bases<torrent_alert>, noncopyable>(\n \"tracker_alert\", no_init\n )\n .def_readonly(\"url\", &tracker_alert::url)\n ;\n\n class_<read_piece_alert, bases<torrent_alert>, noncopyable>(\n \"read_piece_alert\", 0, no_init\n )\n .add_property(\"buffer\", get_buffer)\n .def_readonly(\"piece\", &read_piece_alert::piece)\n .def_readonly(\"size\", &read_piece_alert::size)\n ;\n\n class_<peer_alert, bases<torrent_alert>, noncopyable>(\n \"peer_alert\", no_init\n )\n .def_readonly(\"ip\", &peer_alert::ip)\n .def_readonly(\"pid\", &peer_alert::pid)\n ;\n class_<tracker_error_alert, bases<tracker_alert>, noncopyable>(\n \"tracker_error_alert\", no_init\n )\n .def_readonly(\"msg\", &tracker_error_alert::msg)\n .def_readonly(\"times_in_row\", &tracker_error_alert::times_in_row)\n .def_readonly(\"status_code\", &tracker_error_alert::status_code)\n ;\n\n class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>(\n \"tracker_warning_alert\", no_init\n );\n\n class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>(\n \"tracker_reply_alert\", no_init\n )\n .def_readonly(\"num_peers\", &tracker_reply_alert::num_peers)\n ;\n\n class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>(\n \"tracker_announce_alert\", no_init\n )\n .def_readonly(\"event\", &tracker_reply_alert::event)\n ;\n\n class_<hash_failed_alert, bases<torrent_alert>, noncopyable>(\n \"hash_failed_alert\", no_init\n )\n .def_readonly(\"piece_index\", &hash_failed_alert::piece_index)\n ;\n\n class_<peer_ban_alert, bases<peer_alert>, noncopyable>(\n \"peer_ban_alert\", no_init\n );\n\n class_<peer_error_alert, bases<peer_alert>, noncopyable>(\n \"peer_error_alert\", no_init\n );\n\n class_<invalid_request_alert, bases<peer_alert>, noncopyable>(\n \"invalid_request_alert\", no_init\n )\n .def_readonly(\"request\", &invalid_request_alert::request)\n ;\n\n class_<peer_request>(\"peer_request\")\n .def_readonly(\"piece\", &peer_request::piece)\n .def_readonly(\"start\", &peer_request::start)\n .def_readonly(\"length\", &peer_request::length)\n .def(self == self)\n ;\n\n class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_finished_alert\", no_init\n );\n\n class_<piece_finished_alert, bases<torrent_alert>, noncopyable>(\n \"piece_finished_alert\", no_init\n )\n .def_readonly(\"piece_index\", &piece_finished_alert::piece_index)\n ;\n\n class_<block_finished_alert, bases<peer_alert>, noncopyable>(\n \"block_finished_alert\", no_init\n )\n .def_readonly(\"block_index\", &block_finished_alert::block_index)\n .def_readonly(\"piece_index\", &block_finished_alert::piece_index)\n ;\n\n class_<block_downloading_alert, bases<peer_alert>, noncopyable>(\n \"block_downloading_alert\", no_init\n )\n .def_readonly(\"peer_speedmsg\", &block_downloading_alert::peer_speedmsg)\n .def_readonly(\"block_index\", &block_downloading_alert::block_index)\n .def_readonly(\"piece_index\", &block_downloading_alert::piece_index)\n ;\n\n class_<storage_moved_alert, bases<torrent_alert>, noncopyable>(\n \"storage_moved_alert\", no_init\n )\n .def_readonly(\"path\", &storaged_moved_alert::path)\n ;\n\n class_<storage_moved_failed_alert, bases<torrent_alert>, noncopyable>(\n \"storage_moved_failed_alert\", no_init\n )\n .def_readonly(\"error\", &storage_moved_failed_alert::error)\n ;\n\n class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_deleted_alert\", no_init\n );\n\n class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_paused_alert\", no_init\n );\n\n class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_checked_alert\", no_init\n );\n\n class_<url_seed_alert, bases<torrent_alert>, noncopyable>(\n \"url_seed_alert\", no_init\n )\n .def_readonly(\"url\", &url_seed_alert::url)\n .def_readonly(\"msg\", &url_seed_alert::msg)\n ;\n\n class_<file_error_alert, bases<torrent_alert>, noncopyable>(\n \"file_error_alert\", no_init\n )\n .def_readonly(\"file\", &file_error_alert::file)\n .def_readonly(\"msg\", &file_error_alert::msg)\n ;\n\n class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>(\n \"metadata_failed_alert\", no_init\n );\n\n class_<metadata_received_alert, bases<torrent_alert>, noncopyable>(\n \"metadata_received_alert\", no_init\n );\n\n class_<listen_failed_alert, bases<alert>, noncopyable>(\n \"listen_failed_alert\", no_init\n )\n .def_readonly(\"endpoint\", &listen_failed_alert::endpoint)\n .def_readonly(\"error\", &listen_failed_alert::error)\n ;\n\n class_<listen_succeeded_alert, bases<alert>, noncopyable>(\n \"listen_succeeded_alert\", no_init\n )\n .def_readonly(\"endpoint\", &listen_succeeded_alert::endpoint)\n ;\n\n class_<portmap_error_alert, bases<alert>, noncopyable>(\n \"portmap_error_alert\", no_init\n )\n .def_readonly(\"mapping\", &portmap_error_alert::mapping)\n .def_readonly(\"type\", &portmap_error_alert::type)\n .def_readonly(\"msg\", &portmap_error_alert::msg)\n ;\n\n class_<portmap_alert, bases<alert>, noncopyable>(\n \"portmap_alert\", no_init\n )\n .def_readonly(\"mapping\", &portmap_alert::mapping)\n .def_readonly(\"external_port\", &portmap_alert::external_port)\n .def_readonly(\"type\", &portmap_alert::type)\n ;\n\n class_<portmap_log_alert, bases<alert>, noncopyable>(\n \"portmap_log_alert\", no_init\n )\n .def_readonly(\"type\", &portmap_log_alert::type)\n .def_readonly(\"msg\", &portmap_log_alert::msg)\n ;\n\n class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>(\n \"fastresume_rejected_alert\", no_init\n )\n .def_readonly(\"msg\", &fastresume_rejected_alert::msg)\n ;\n\n class_<peer_blocked_alert, bases<alert>, noncopyable>(\n \"peer_blocked_alert\", no_init\n )\n .def_readonly(\"ip\", &peer_blocked_alert::ip)\n ;\n\n class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>(\n \"scrape_reply_alert\", no_init\n )\n .def_readonly(\"incomplete\", &scrape_reply_alert::incomplete)\n .def_readonly(\"complete\", &scrape_reply_alert::complete)\n ;\n\n class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>(\n \"scrape_failed_alert\", no_init\n );\n\n class_<udp_error_alert, bases<alert>, noncopyable>(\n \"udp_error_alert\", no_init\n )\n .def_readonly(\"endpoint\", &udp_error_alert::endpoint)\n .def_readonly(\"error\", &udp_error_alert::error)\n ;\n\n class_<external_ip_alert, bases<alert>, noncopyable>(\n \"external_ip_alert\", no_init\n )\n .def_readonly(\"external_address\", &external_ip_alert::external_address)\n ;\n\n class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>(\n \"save_resume_data_alert\", no_init\n )\n .def_readonly(\"resume_data\", &save_resume_data_alert::resume_data)\n ;\n\n class_<file_renamed_alert, bases<torrent_alert>, noncopyable>(\n \"file_renamed_alert\", no_init\n )\n .def_readonly(\"index\", &file_renamed_alert::index)\n .def_readonly(\"name\", &file_renamed_alert::name)\n ;\n\n class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>(\n \"file_rename_failed_alert\", no_init\n )\n .def_readonly(\"index\", &file_rename_failed_alert::index)\n .def_readonly(\"error\", &file_rename_failed_alert::error)\n ;\n\n class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_resumed_alert\", no_init\n\t);\n\n\tclass_<state_changed_alert, bases<torrent_alert>, noncopyable>(\n\t \"state_changed_alert\", no_init\n\t)\n\t .def_readonly(\"state\", &state_changed_alert::state)\n\t .def_readonly(\"prev_state\", &state_changed_alert::prev_state)\n\t ;\n\n\tclass_<dht_reply_alert, bases<tracker_alert>, noncopyable>(\n\t \"dht_reply_alert\", no_init\n\t)\n\t .def_readonly(\"num_peers\", &dht_reply_alert::num_peers)\n\t ;\n\n class_<dht_announce_alert, bases<alert>, noncopyable>(\n \"dht_announce_alert\", no_init\n )\n .def_readonly(\"ip\" &dht_announce_alert::ip)\n .def_readonly(\"port\", &dht_announce_alert::port)\n .def_readonly(\"info_hash\", &dht_announce_alert::info_hash)\n ;\n\n class_<dht_get_peers_alert, bases<alert>, noncopyable>(\n \"dht_get_peers_alert\", no_init\n )\n .def_readonly(\"info_hash\", &dht_get_peers_alert::info_hash)\n ;\n\n\tclass_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>(\n\t \"peer_unsnubbed_alert\", no_init\n\t);\n\n\tclass_<peer_snubbed_alert, bases<peer_alert>, noncopyable>(\n\t \"peer_snubbed_alert\", no_init\n\t);\n\n class_<peer_connect_alert, bases<peer_alert>, noncopyable>(\n \"peer_connect_alert\", no_init\n );\n\n class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>(\n \"peer_disconnected_alert\", no_init\n )\n .def_readonly(\"msg\", &peer_disconnected_alert::msg)\n ;\n\n class_<request_dropped_alert, bases<peer_alert>, noncopyable>(\n \"request_dropped_alert\", no_init\n )\n .def_readonly(\"block_index\", &request_dropped_alert::block_index)\n .def_readonly(\"piece_index\", &request_dropped_alert::piece_index)\n ;\n\n class_<block_timeout_alert, bases<peer_alert>, noncopyable>(\n \"block_timeout_alert\", no_init\n )\n .def_readonly(\"block_index\", &block_timeout_alert::block_index)\n .def_readonly(\"piece_index\", &block_timeout_alert::piece_index)\n ;\n\n class_<unwanted_block_alert, bases<peer_alert>, noncopyable>(\n \"unwanted_block_alert\", no_init\n )\n .def_readonly(\"block_index\", &unwanted_block_alert::block_index)\n .def_readonly(\"piece_index\", &unwanted_block_alert::piece_index)\n ;\n\n class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_delete_failed_alert\", no_init\n )\n .def_readonly(\"msg\", &torrent_delete_failed_alert::msg)\n ;\n\n class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>(\n \"save_resume_data_failed_alert\", no_init\n )\n .def_readonly(\"msg\", &save_resume_data_failed_alert::msg)\n ;\n\n class_<performance_alert, bases<torrent_alert>, noncopyable>(\n \"performance_alert\", no_init\n )\n .def_readonly(\"warning_code\", &performance_alert::warning_code)\n ;\n enum_<performance_alert::performance_warning_t>(\"performance_warning_t\")\n .value(\"outstanding_disk_buffer_limit_reached\", performance_alert::outstanding_disk_buffer_limit_reached)\n .value(\"outstanding_request_limit_reached\", performance_alert::outstanding_request_limit_reached)\n .value(\"upload_limit_too_low\", performance_alert::upload_limit_too_low)\n .value(\"download_limit_too_low\", performance_alert::download_limit_too_low)\n ;\n\n\n\n}\n<commit_msg>Fix some typos<commit_after>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <boost\/python.hpp>\n#include <libtorrent\/alert.hpp>\n#include <libtorrent\/alert_types.hpp>\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nstd::string get_buffer(read_piece_alert const& rpa)\n{\n return rpa.buffer ? std::string(rpa.buffer.get(), rpa.size)\n : std::string();\n}\n\nvoid bind_alert()\n{\n using boost::noncopyable;\n\n {\n scope alert_scope = class_<alert, noncopyable>(\"alert\", no_init)\n .def(\"message\", &alert::message)\n .def(\"what\", &alert::what)\n .def(\"category\", &alert::category)\n#ifndef TORRENT_NO_DEPRECATE\n .def(\"severity\", &alert::severity)\n#endif\n .def(\"__str__\", &alert::message)\n ;\n\n#ifndef TORRENT_NO_DEPRECATE\n enum_<alert::severity_t>(\"severity_levels\")\n .value(\"debug\", alert::debug)\n .value(\"info\", alert::info)\n .value(\"warning\", alert::warning)\n .value(\"critical\", alert::critical)\n .value(\"fatal\", alert::fatal)\n .value(\"none\", alert::none)\n ;\n#endif\n\n enum_<alert::category_t>(\"category_t\")\n .value(\"error_notification\", alert::error_notification)\n .value(\"peer_notification\", alert::peer_notification)\n .value(\"port_mapping_notification\", alert::port_mapping_notification)\n .value(\"storage_notification\", alert::storage_notification)\n .value(\"tracker_notification\", alert::tracker_notification)\n .value(\"debug_notification\", alert::debug_notification)\n .value(\"status_notification\", alert::status_notification)\n .value(\"progress_notification\", alert::progress_notification)\n .value(\"ip_block_notification\", alert::ip_block_notification)\n .value(\"performance_warning\", alert::performance_warning)\n .value(\"all_categories\", alert::all_categories)\n ;\n\n }\n\n class_<torrent_alert, bases<alert>, noncopyable>(\n \"torrent_alert\", no_init\n )\n .def_readonly(\"handle\", &torrent_alert::handle)\n ;\n\n class_<tracker_alert, bases<torrent_alert>, noncopyable>(\n \"tracker_alert\", no_init\n )\n .def_readonly(\"url\", &tracker_alert::url)\n ;\n\n class_<read_piece_alert, bases<torrent_alert>, noncopyable>(\n \"read_piece_alert\", 0, no_init\n )\n .add_property(\"buffer\", get_buffer)\n .def_readonly(\"piece\", &read_piece_alert::piece)\n .def_readonly(\"size\", &read_piece_alert::size)\n ;\n\n class_<peer_alert, bases<torrent_alert>, noncopyable>(\n \"peer_alert\", no_init\n )\n .def_readonly(\"ip\", &peer_alert::ip)\n .def_readonly(\"pid\", &peer_alert::pid)\n ;\n class_<tracker_error_alert, bases<tracker_alert>, noncopyable>(\n \"tracker_error_alert\", no_init\n )\n .def_readonly(\"msg\", &tracker_error_alert::msg)\n .def_readonly(\"times_in_row\", &tracker_error_alert::times_in_row)\n .def_readonly(\"status_code\", &tracker_error_alert::status_code)\n ;\n\n class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>(\n \"tracker_warning_alert\", no_init\n );\n\n class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>(\n \"tracker_reply_alert\", no_init\n )\n .def_readonly(\"num_peers\", &tracker_reply_alert::num_peers)\n ;\n\n class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>(\n \"tracker_announce_alert\", no_init\n )\n .def_readonly(\"event\", &tracker_announce_alert::event)\n ;\n\n class_<hash_failed_alert, bases<torrent_alert>, noncopyable>(\n \"hash_failed_alert\", no_init\n )\n .def_readonly(\"piece_index\", &hash_failed_alert::piece_index)\n ;\n\n class_<peer_ban_alert, bases<peer_alert>, noncopyable>(\n \"peer_ban_alert\", no_init\n );\n\n class_<peer_error_alert, bases<peer_alert>, noncopyable>(\n \"peer_error_alert\", no_init\n );\n\n class_<invalid_request_alert, bases<peer_alert>, noncopyable>(\n \"invalid_request_alert\", no_init\n )\n .def_readonly(\"request\", &invalid_request_alert::request)\n ;\n\n class_<peer_request>(\"peer_request\")\n .def_readonly(\"piece\", &peer_request::piece)\n .def_readonly(\"start\", &peer_request::start)\n .def_readonly(\"length\", &peer_request::length)\n .def(self == self)\n ;\n\n class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_finished_alert\", no_init\n );\n\n class_<piece_finished_alert, bases<torrent_alert>, noncopyable>(\n \"piece_finished_alert\", no_init\n )\n .def_readonly(\"piece_index\", &piece_finished_alert::piece_index)\n ;\n\n class_<block_finished_alert, bases<peer_alert>, noncopyable>(\n \"block_finished_alert\", no_init\n )\n .def_readonly(\"block_index\", &block_finished_alert::block_index)\n .def_readonly(\"piece_index\", &block_finished_alert::piece_index)\n ;\n\n class_<block_downloading_alert, bases<peer_alert>, noncopyable>(\n \"block_downloading_alert\", no_init\n )\n .def_readonly(\"peer_speedmsg\", &block_downloading_alert::peer_speedmsg)\n .def_readonly(\"block_index\", &block_downloading_alert::block_index)\n .def_readonly(\"piece_index\", &block_downloading_alert::piece_index)\n ;\n\n class_<storage_moved_alert, bases<torrent_alert>, noncopyable>(\n \"storage_moved_alert\", no_init\n )\n .def_readonly(\"path\", &storage_moved_alert::path)\n ;\n\n class_<storage_moved_failed_alert, bases<torrent_alert>, noncopyable>(\n \"storage_moved_failed_alert\", no_init\n )\n .def_readonly(\"error\", &storage_moved_failed_alert::error)\n ;\n\n class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_deleted_alert\", no_init\n );\n\n class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_paused_alert\", no_init\n );\n\n class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_checked_alert\", no_init\n );\n\n class_<url_seed_alert, bases<torrent_alert>, noncopyable>(\n \"url_seed_alert\", no_init\n )\n .def_readonly(\"url\", &url_seed_alert::url)\n .def_readonly(\"msg\", &url_seed_alert::msg)\n ;\n\n class_<file_error_alert, bases<torrent_alert>, noncopyable>(\n \"file_error_alert\", no_init\n )\n .def_readonly(\"file\", &file_error_alert::file)\n .def_readonly(\"msg\", &file_error_alert::msg)\n ;\n\n class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>(\n \"metadata_failed_alert\", no_init\n );\n\n class_<metadata_received_alert, bases<torrent_alert>, noncopyable>(\n \"metadata_received_alert\", no_init\n );\n\n class_<listen_failed_alert, bases<alert>, noncopyable>(\n \"listen_failed_alert\", no_init\n )\n .def_readonly(\"endpoint\", &listen_failed_alert::endpoint)\n .def_readonly(\"error\", &listen_failed_alert::error)\n ;\n\n class_<listen_succeeded_alert, bases<alert>, noncopyable>(\n \"listen_succeeded_alert\", no_init\n )\n .def_readonly(\"endpoint\", &listen_succeeded_alert::endpoint)\n ;\n\n class_<portmap_error_alert, bases<alert>, noncopyable>(\n \"portmap_error_alert\", no_init\n )\n .def_readonly(\"mapping\", &portmap_error_alert::mapping)\n .def_readonly(\"type\", &portmap_error_alert::type)\n .def_readonly(\"msg\", &portmap_error_alert::msg)\n ;\n\n class_<portmap_alert, bases<alert>, noncopyable>(\n \"portmap_alert\", no_init\n )\n .def_readonly(\"mapping\", &portmap_alert::mapping)\n .def_readonly(\"external_port\", &portmap_alert::external_port)\n .def_readonly(\"type\", &portmap_alert::type)\n ;\n\n class_<portmap_log_alert, bases<alert>, noncopyable>(\n \"portmap_log_alert\", no_init\n )\n .def_readonly(\"type\", &portmap_log_alert::type)\n .def_readonly(\"msg\", &portmap_log_alert::msg)\n ;\n\n class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>(\n \"fastresume_rejected_alert\", no_init\n )\n .def_readonly(\"msg\", &fastresume_rejected_alert::msg)\n ;\n\n class_<peer_blocked_alert, bases<alert>, noncopyable>(\n \"peer_blocked_alert\", no_init\n )\n .def_readonly(\"ip\", &peer_blocked_alert::ip)\n ;\n\n class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>(\n \"scrape_reply_alert\", no_init\n )\n .def_readonly(\"incomplete\", &scrape_reply_alert::incomplete)\n .def_readonly(\"complete\", &scrape_reply_alert::complete)\n ;\n\n class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>(\n \"scrape_failed_alert\", no_init\n );\n\n class_<udp_error_alert, bases<alert>, noncopyable>(\n \"udp_error_alert\", no_init\n )\n .def_readonly(\"endpoint\", &udp_error_alert::endpoint)\n .def_readonly(\"error\", &udp_error_alert::error)\n ;\n\n class_<external_ip_alert, bases<alert>, noncopyable>(\n \"external_ip_alert\", no_init\n )\n .def_readonly(\"external_address\", &external_ip_alert::external_address)\n ;\n\n class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>(\n \"save_resume_data_alert\", no_init\n )\n .def_readonly(\"resume_data\", &save_resume_data_alert::resume_data)\n ;\n\n class_<file_renamed_alert, bases<torrent_alert>, noncopyable>(\n \"file_renamed_alert\", no_init\n )\n .def_readonly(\"index\", &file_renamed_alert::index)\n .def_readonly(\"name\", &file_renamed_alert::name)\n ;\n\n class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>(\n \"file_rename_failed_alert\", no_init\n )\n .def_readonly(\"index\", &file_rename_failed_alert::index)\n .def_readonly(\"error\", &file_rename_failed_alert::error)\n ;\n\n class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_resumed_alert\", no_init\n\t);\n\n\tclass_<state_changed_alert, bases<torrent_alert>, noncopyable>(\n\t \"state_changed_alert\", no_init\n\t)\n\t .def_readonly(\"state\", &state_changed_alert::state)\n\t .def_readonly(\"prev_state\", &state_changed_alert::prev_state)\n\t ;\n\n\tclass_<dht_reply_alert, bases<tracker_alert>, noncopyable>(\n\t \"dht_reply_alert\", no_init\n\t)\n\t .def_readonly(\"num_peers\", &dht_reply_alert::num_peers)\n\t ;\n\n class_<dht_announce_alert, bases<alert>, noncopyable>(\n \"dht_announce_alert\", no_init\n )\n .def_readonly(\"ip\", &dht_announce_alert::ip)\n .def_readonly(\"port\", &dht_announce_alert::port)\n .def_readonly(\"info_hash\", &dht_announce_alert::info_hash)\n ;\n\n class_<dht_get_peers_alert, bases<alert>, noncopyable>(\n \"dht_get_peers_alert\", no_init\n )\n .def_readonly(\"info_hash\", &dht_get_peers_alert::info_hash)\n ;\n\n\tclass_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>(\n\t \"peer_unsnubbed_alert\", no_init\n\t);\n\n\tclass_<peer_snubbed_alert, bases<peer_alert>, noncopyable>(\n\t \"peer_snubbed_alert\", no_init\n\t);\n\n class_<peer_connect_alert, bases<peer_alert>, noncopyable>(\n \"peer_connect_alert\", no_init\n );\n\n class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>(\n \"peer_disconnected_alert\", no_init\n )\n .def_readonly(\"msg\", &peer_disconnected_alert::msg)\n ;\n\n class_<request_dropped_alert, bases<peer_alert>, noncopyable>(\n \"request_dropped_alert\", no_init\n )\n .def_readonly(\"block_index\", &request_dropped_alert::block_index)\n .def_readonly(\"piece_index\", &request_dropped_alert::piece_index)\n ;\n\n class_<block_timeout_alert, bases<peer_alert>, noncopyable>(\n \"block_timeout_alert\", no_init\n )\n .def_readonly(\"block_index\", &block_timeout_alert::block_index)\n .def_readonly(\"piece_index\", &block_timeout_alert::piece_index)\n ;\n\n class_<unwanted_block_alert, bases<peer_alert>, noncopyable>(\n \"unwanted_block_alert\", no_init\n )\n .def_readonly(\"block_index\", &unwanted_block_alert::block_index)\n .def_readonly(\"piece_index\", &unwanted_block_alert::piece_index)\n ;\n\n class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>(\n \"torrent_delete_failed_alert\", no_init\n )\n .def_readonly(\"msg\", &torrent_delete_failed_alert::msg)\n ;\n\n class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>(\n \"save_resume_data_failed_alert\", no_init\n )\n .def_readonly(\"msg\", &save_resume_data_failed_alert::msg)\n ;\n\n class_<performance_alert, bases<torrent_alert>, noncopyable>(\n \"performance_alert\", no_init\n )\n .def_readonly(\"warning_code\", &performance_alert::warning_code)\n ;\n enum_<performance_alert::performance_warning_t>(\"performance_warning_t\")\n .value(\"outstanding_disk_buffer_limit_reached\", performance_alert::outstanding_disk_buffer_limit_reached)\n .value(\"outstanding_request_limit_reached\", performance_alert::outstanding_request_limit_reached)\n .value(\"upload_limit_too_low\", performance_alert::upload_limit_too_low)\n .value(\"download_limit_too_low\", performance_alert::download_limit_too_low)\n ;\n\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <pthread.h>\n#include \"simulator.h\"\n#include \"thread_manager.h\"\n#include \"core_manager.h\"\n#include \"core.h\"\n#include \"config_file.hpp\"\n\n#include \"carbon_user.h\"\n#include \"thread_support_private.h\"\n\nCAPI_return_t CAPI_rank(int *core_id)\n{\n *core_id = CarbonGetCoreId();\n return 0;\n}\n\nCAPI_return_t CAPI_Initialize(int rank)\n{\n Sim()->getCoreManager()->initializeCommId(rank);\n return 0;\n}\n\nCAPI_return_t CAPI_message_send_w(CAPI_endpoint_t sender, CAPI_endpoint_t receiver,\n char *buffer, int size)\n{\n Core *core = Sim()->getCoreManager()->getCurrentCore();\n\n LOG_PRINT(\"SimSendW - sender: %d, recv: %d\", sender, receiver);\n\n core_id_t sending_core = Config::getSingleton()->getCoreFromCommId(sender);\n core_id_t receiving_core = Config::getSingleton()->getCoreFromCommId(receiver);\n\n if(sending_core == INVALID_CORE_ID)\n return CAPI_SenderNotInitialized;\n if(receiving_core == INVALID_CORE_ID)\n return CAPI_ReceiverNotInitialized;\n\n return core ? core->coreSendW(sending_core, receiving_core, buffer, size) : CAPI_SenderNotInitialized;\n}\n\nCAPI_return_t CAPI_message_receive_w(CAPI_endpoint_t sender, CAPI_endpoint_t receiver,\n char *buffer, int size)\n{\n Core *core = Sim()->getCoreManager()->getCurrentCore();\n\n LOG_PRINT(\"SimRecvW - sender: %d, recv: %d\", sender, receiver);\n\n core_id_t sending_core = Config::getSingleton()->getCoreFromCommId(sender);\n core_id_t receiving_core = Config::getSingleton()->getCoreFromCommId(receiver);\n\n if(sending_core == INVALID_CORE_ID)\n return CAPI_SenderNotInitialized;\n if(receiving_core == INVALID_CORE_ID)\n return CAPI_ReceiverNotInitialized;\n\n return core ? core->coreRecvW(sending_core, receiving_core, buffer, size) : CAPI_ReceiverNotInitialized;\n}\n<commit_msg>[capi] Print message size on send.<commit_after>#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <pthread.h>\n#include \"simulator.h\"\n#include \"thread_manager.h\"\n#include \"core_manager.h\"\n#include \"core.h\"\n#include \"config_file.hpp\"\n\n#include \"carbon_user.h\"\n#include \"thread_support_private.h\"\n\nCAPI_return_t CAPI_rank(int *core_id)\n{\n *core_id = CarbonGetCoreId();\n return 0;\n}\n\nCAPI_return_t CAPI_Initialize(int rank)\n{\n Sim()->getCoreManager()->initializeCommId(rank);\n return 0;\n}\n\nCAPI_return_t CAPI_message_send_w(CAPI_endpoint_t sender, CAPI_endpoint_t receiver,\n char *buffer, int size)\n{\n Core *core = Sim()->getCoreManager()->getCurrentCore();\n\n LOG_PRINT(\"SimSendW - sender: %d, recv: %d, size: %d\", sender, receiver, size);\n\n core_id_t sending_core = Config::getSingleton()->getCoreFromCommId(sender);\n core_id_t receiving_core = Config::getSingleton()->getCoreFromCommId(receiver);\n\n if(sending_core == INVALID_CORE_ID)\n return CAPI_SenderNotInitialized;\n if(receiving_core == INVALID_CORE_ID)\n return CAPI_ReceiverNotInitialized;\n\n return core ? core->coreSendW(sending_core, receiving_core, buffer, size) : CAPI_SenderNotInitialized;\n}\n\nCAPI_return_t CAPI_message_receive_w(CAPI_endpoint_t sender, CAPI_endpoint_t receiver,\n char *buffer, int size)\n{\n Core *core = Sim()->getCoreManager()->getCurrentCore();\n\n LOG_PRINT(\"SimRecvW - sender: %d, recv: %d\", sender, receiver);\n\n core_id_t sending_core = Config::getSingleton()->getCoreFromCommId(sender);\n core_id_t receiving_core = Config::getSingleton()->getCoreFromCommId(receiver);\n\n if(sending_core == INVALID_CORE_ID)\n return CAPI_SenderNotInitialized;\n if(receiving_core == INVALID_CORE_ID)\n return CAPI_ReceiverNotInitialized;\n\n return core ? core->coreRecvW(sending_core, receiving_core, buffer, size) : CAPI_ReceiverNotInitialized;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ POPBufferWriter.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <iostream>\n\n#define TINYOBJLOADER_IMPLEMENTATION \/\/ define this in only *one* .cc\n#include \"tiny_obj_loader.h\"\n\n#include <fstream>\nusing namespace std;\n\n\/*\n\tStructure to hold a record that should be written to file\n*\/\nstruct rec\n{\n\tshort x, y, z;\n\tchar u, v;\n};\n\n\/*\n\tStructure to hold min and max values for transformation\n*\/\nstruct minmax\n{\n\tfloat minx, miny, minz;\n\tfloat maxx, maxy, maxz;\n};\n\n\/*\n\tStructure to hold a vertex entry that is not transformed yet\n*\/\nstruct entry\n{\n\tfloat vx, vy, vz;\n\tfloat nx, ny, nz;\n};\n\nstruct float2 { float u, v; };\nstruct float3 { float x, y, z; };\n\n\/*\n\tOctahedron normal coding\n*\/\n\n\/\/TODO Add conversion code here\n\n\nint main()\n{\n\tconst string inputfile = \"models\/bunny.obj\";\n\tconst string modelName = \"bunny\";\n\tconst char* dataFileName = \"out.pop\";\n\n\n\t\/*\n\t\tPrepare output file\n\t*\/\n\tint i;\n\tFILE *f;\n\tstruct rec r;\n\tfopen_s(&f, dataFileName, \"wb\");\n\tif (!f)\n\t\treturn 1;\n\n\n\t\/*\n\t\tParse obj file\n\t*\/\n\ttinyobj::attrib_t attrib;\n\tstd::vector<tinyobj::shape_t> shapes;\n\tstd::vector<tinyobj::material_t> materials;\n\tstd::string err;\n\n\tbool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, inputfile.c_str());\n\tif (!err.empty()) { \/\/ `err` may contain warning message.\n\t\tstd::cerr << err << std::endl;\n\t}\n\tif (!ret || shapes.size() < 1) {\n\t\texit(1);\n\t}\n\n\n\t\/\/ Create a vector to hold the entries\n\tstd::vector<entry> entries;\n\tint vertexCount = shapes[0].mesh.num_face_vertices.size() * 3;\n\tstd::cout << \"Found \" << vertexCount << \" vertices in file \" << inputfile << std::endl;\n\tentries.reserve(vertexCount);\n\tint counter = 0;\n\n\n\t\/\/ Init min and max values\n\tminmax minMaxValues;\n\tminMaxValues.minx = HUGE_VALF;\n\tminMaxValues.maxx = -HUGE_VALF;\n\tminMaxValues.miny = HUGE_VALF;\n\tminMaxValues.maxy = -HUGE_VALF;\n\tminMaxValues.minz = HUGE_VALF;\n\tminMaxValues.maxz = -HUGE_VALF;\n\n\n\t\/*\n\t\tLoop over file content and create output\n\t*\/\n\tsize_t index_offset = 0;\n\tfor (size_t f = 0; f < shapes[0].mesh.num_face_vertices.size(); f++) {\n\t\tsize_t fv = shapes[0].mesh.num_face_vertices[f];\n\n\t\t\/\/ Loop over vertices in the face.\n\t\tfor (size_t v = 0; v < fv; v++) {\n\t\t\t\/\/ access to vertex\n\t\t\ttinyobj::index_t idx = shapes[0].mesh.indices[index_offset + v];\n\n\t\t\t\/\/ create an entry per vertex and update the min and max values if necessary\n\t\t\tentry e;\n\t\t\te.vx = attrib.vertices[3 * idx.vertex_index + 0];\n\t\t\tif (e.vx < minMaxValues.minx) minMaxValues.minx = e.vx;\n\t\t\tif (e.vx > minMaxValues.maxx) minMaxValues.maxx = e.vx;\n\n\t\t\te.vy = attrib.vertices[3 * idx.vertex_index + 1];\n\t\t\tif (e.vy < minMaxValues.miny) minMaxValues.miny = e.vy;\n\t\t\tif (e.vy > minMaxValues.maxy) minMaxValues.maxy = e.vy;\n\n\t\t\te.vz = attrib.vertices[3 * idx.vertex_index + 2];\n\t\t\tif (e.vz < minMaxValues.minz) minMaxValues.minz = e.vz;\n\t\t\tif (e.vz > minMaxValues.maxz) minMaxValues.maxz = e.vz;\n\n\t\t\te.nx = attrib.normals[3 * idx.normal_index + 0];\n\t\t\te.ny = attrib.normals[3 * idx.normal_index + 1];\n\t\t\te.nz = attrib.normals[3 * idx.normal_index + 2];\n\n\t\t\tentries.push_back(e);\n\t\t\tcounter++;\n\t\t}\n\t\tindex_offset += fv;\n\t}\n\n\n\t\/\/ Output some debugging values\n\tstd::cout << \"MaxX: \" << minMaxValues.maxx << \" MaxY:\" << minMaxValues.maxy << \" MaxZ: \" << minMaxValues.maxz << std::endl;\n\tstd::cout << \"MinX: \" << minMaxValues.minx << \" MinY:\" << minMaxValues.miny << \" MinZ: \" << minMaxValues.minz << std::endl;\n\n\n\t\/\/ Write meta values to meta data file\n\tofstream metaFile;\n\tmetaFile.open(\"out.json\");\n\tmetaFile << \"{\\n\";\n\tmetaFile << \"\\\"name\\\": \\\"\" << modelName << \"\\\",\\n\";\n\tmetaFile << \"\\\"data\\\": \\\"\" << dataFileName << \"\\\",\\n\";\n\tmetaFile << \"\\\"numVertices\\\": \\\"\" << counter << \"\\\",\\n\";\n\tmetaFile << \"\\\"xmin\\\": \" << minMaxValues.minx << \",\\n\";\n\tmetaFile << \"\\\"ymin\\\": \" << minMaxValues.miny << \",\\n\";\n\tmetaFile << \"\\\"zmin\\\": \" << minMaxValues.minz << \",\\n\";\n\tmetaFile << \"\\\"xmax\\\": \" << minMaxValues.maxx << \",\\n\";\n\tmetaFile << \"\\\"ymax\\\": \" << minMaxValues.maxy << \",\\n\";\n\tmetaFile << \"\\\"zmax\\\": \" << minMaxValues.maxz << \",\\n\";\n\tmetaFile << \"\\\"factor\\\": \" << USHRT_MAX << \"\\n\";\n\tmetaFile << \"}\\n\";\n\tmetaFile.close();\n\n\n\t\/*\n\t\tWrite new values (normalized to range of unsigned short)\n\t*\/\n\tfor (i = 0;i < counter; i++)\n\t{\n\t\tentry e = entries[i];\n\t\tr.x = floor((e.vx - minMaxValues.minx) \/ (minMaxValues.maxx - minMaxValues.minx) * USHRT_MAX);\n\t\tr.y = floor((e.vy - minMaxValues.miny) \/ (minMaxValues.maxy - minMaxValues.miny) * USHRT_MAX);\n\t\tr.z = floor((e.vz - minMaxValues.minz) \/ (minMaxValues.maxz - minMaxValues.minz) * USHRT_MAX);\n\t\tr.u = 0;\n\t\tr.v = 0;\n\t\tfwrite(&r, sizeof(struct rec), 1, f);\n\t}\n\n\n\tstd::cout << \"Exported \" << counter << \" vertices\" << std::endl;\n\tfclose(f);\n\tcin.get();\n}\n<commit_msg>Added octahedron normal export to writer<commit_after>\/\/ POPBufferWriter.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <iostream>\n\n#define TINYOBJLOADER_IMPLEMENTATION \/\/ define this in only *one* .cc\n#include \"tiny_obj_loader.h\"\n\n#include <fstream>\nusing namespace std;\n\n\/*\n\tStructure to hold a record that should be written to file\n*\/\nstruct rec\n{\n\tshort x, y, z;\n\tchar u, v;\n};\n\n\/*\n\tStructure to hold min and max values for transformation\n*\/\nstruct minmax\n{\n\tfloat minx, miny, minz, minu, minv;\n\tfloat maxx, maxy, maxz, maxu, maxv;\n};\n\n\/*\n\tStructure to hold a vertex entry that is not transformed yet\n*\/\nstruct entry\n{\n\tfloat vx, vy, vz;\n\tfloat nx, ny, nz;\n\tfloat nu, nv;\n};\n\nstruct float2 { float u, v; };\nstruct float3 { float x, y, z; };\n\n\/*\n\tOctahedron normal coding\n*\/\n\n\/\/TODO Add conversion code here\nfloat wrapOctahedronNormalValue(float v1, float v2)\n{\n\treturn (1.0f - fabs(v2)) * (v1 >= 0.0f ? 1.0 : -1.0);\n}\n\n\nvoid encodeOctahedronNormal(float nx, float ny, float nz, float & octNorU, float & octNorV)\n{\n\tfloat absSum = fabs(nx) + fabs(ny) + fabs(nz);\n\n\tnx \/= absSum;\n\tny \/= absSum;\n\n\tif (nz < 0.0f)\n\t{\n\t\tfloat tmp = nx;\n\t\tnx = wrapOctahedronNormalValue(nx, ny);\n\t\tny = wrapOctahedronNormalValue(ny, tmp);\n\t}\n\n\toctNorU = nx * 0.5f + 0.5f;\n\toctNorV = ny * 0.5f + 0.5f;\n}\n\n\nint main()\n{\n\tconst string inputfile = \"models\/bunny.obj\";\n\tconst string modelName = \"bunny\";\n\tconst char* dataFileName = \"bunny.pop\";\n\tconst char* metaFileName = \"bunny.json\";\n\n\n\t\/*\n\t\tPrepare output file\n\t*\/\n\tint i;\n\tFILE *f;\n\tstruct rec r;\n\tfopen_s(&f, dataFileName, \"wb\");\n\tif (!f)\n\t\treturn 1;\n\n\n\t\/*\n\t\tParse obj file\n\t*\/\n\tcout << \"Reading file \" << inputfile << endl;\n\n\ttinyobj::attrib_t attrib;\n\tstd::vector<tinyobj::shape_t> shapes;\n\tstd::vector<tinyobj::material_t> materials;\n\tstd::string err;\n\n\tbool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, inputfile.c_str());\n\tif (!err.empty()) { \/\/ `err` may contain warning message.\n\t\tstd::cerr << err << std::endl;\n\t}\n\tif (!ret || shapes.size() < 1) {\n\t\texit(1);\n\t}\n\n\n\t\/\/ Create a vector to hold the entries\n\tstd::vector<entry> entries;\n\tint vertexCount = shapes[0].mesh.num_face_vertices.size() * 3;\n\tstd::cout << \"Found \" << vertexCount << \" vertices in file \" << inputfile << std::endl;\n\tentries.reserve(vertexCount);\n\tint counter = 0;\n\n\n\t\/\/ Init min and max values\n\tminmax minMaxValues;\n\tminMaxValues.minx = HUGE_VALF;\n\tminMaxValues.maxx = -HUGE_VALF;\n\tminMaxValues.miny = HUGE_VALF;\n\tminMaxValues.maxy = -HUGE_VALF;\n\tminMaxValues.minz = HUGE_VALF;\n\tminMaxValues.maxz = -HUGE_VALF;\n\n\n\t\/*\n\t\tLoop over file content and create output\n\t*\/\n\tsize_t index_offset = 0;\n\tfor (size_t f = 0; f < shapes[0].mesh.num_face_vertices.size(); f++) {\n\t\tsize_t fv = shapes[0].mesh.num_face_vertices[f];\n\n\t\t\/\/ Loop over vertices in the face.\n\t\tfor (size_t v = 0; v < fv; v++) {\n\t\t\t\/\/ access to vertex\n\t\t\ttinyobj::index_t idx = shapes[0].mesh.indices[index_offset + v];\n\n\t\t\t\/\/ create an entry per vertex and update the min and max values if necessary\n\t\t\tentry e;\n\t\t\te.vx = attrib.vertices[3 * idx.vertex_index + 0];\n\t\t\tif (e.vx < minMaxValues.minx) minMaxValues.minx = e.vx;\n\t\t\tif (e.vx > minMaxValues.maxx) minMaxValues.maxx = e.vx;\n\n\t\t\te.vy = attrib.vertices[3 * idx.vertex_index + 1];\n\t\t\tif (e.vy < minMaxValues.miny) minMaxValues.miny = e.vy;\n\t\t\tif (e.vy > minMaxValues.maxy) minMaxValues.maxy = e.vy;\n\n\t\t\te.vz = attrib.vertices[3 * idx.vertex_index + 2];\n\t\t\tif (e.vz < minMaxValues.minz) minMaxValues.minz = e.vz;\n\t\t\tif (e.vz > minMaxValues.maxz) minMaxValues.maxz = e.vz;\n\n\t\t\t\/\/ convert normals to octahedron normals\n\t\t\te.nx = attrib.normals[3 * idx.normal_index + 0];\n\t\t\te.ny = attrib.normals[3 * idx.normal_index + 1];\n\t\t\te.nz = attrib.normals[3 * idx.normal_index + 2];\n\t\t\tencodeOctahedronNormal(e.nx, e.ny, e.nz, e.nu, e.nv);\n\n\t\t\tentries.push_back(e);\n\t\t\tcounter++;\n\t\t}\n\t\tindex_offset += fv;\n\t}\n\n\n\t\/\/ Output some debugging values\n\tstd::cout << \"MaxX: \" << minMaxValues.maxx << \" MaxY:\" << minMaxValues.maxy << \" MaxZ: \" << minMaxValues.maxz << std::endl;\n\tstd::cout << \"MinX: \" << minMaxValues.minx << \" MinY:\" << minMaxValues.miny << \" MinZ: \" << minMaxValues.minz << std::endl;\n\n\n\t\/\/ Write meta values to meta data file\n\tofstream metaFile;\n\tmetaFile.open(metaFileName);\n\tmetaFile << \"{\\n\";\n\tmetaFile << \"\\\"name\\\": \\\"\" << modelName << \"\\\",\\n\";\n\tmetaFile << \"\\\"data\\\": \\\"\" << dataFileName << \"\\\",\\n\";\n\tmetaFile << \"\\\"numVertices\\\": \\\"\" << counter << \"\\\",\\n\";\n\tmetaFile << \"\\\"xmin\\\": \" << minMaxValues.minx << \",\\n\";\n\tmetaFile << \"\\\"ymin\\\": \" << minMaxValues.miny << \",\\n\";\n\tmetaFile << \"\\\"zmin\\\": \" << minMaxValues.minz << \",\\n\";\n\tmetaFile << \"\\\"xmax\\\": \" << minMaxValues.maxx << \",\\n\";\n\tmetaFile << \"\\\"ymax\\\": \" << minMaxValues.maxy << \",\\n\";\n\tmetaFile << \"\\\"zmax\\\": \" << minMaxValues.maxz << \",\\n\";\n\tmetaFile << \"\\\"factor\\\": \" << USHRT_MAX << \"\\n\";\n\tmetaFile << \"}\\n\";\n\tmetaFile.close();\n\n\n\t\/*\n\t\tWrite new values (normalized to range of unsigned short)\n\t*\/\n\tfor (i = 0;i < counter; i++)\n\t{\n\t\tentry e = entries[i];\n\n\t\tr.x = floor((e.vx - minMaxValues.minx) \/ (minMaxValues.maxx - minMaxValues.minx) * USHRT_MAX);\n\t\tr.y = floor((e.vy - minMaxValues.miny) \/ (minMaxValues.maxy - minMaxValues.miny) * USHRT_MAX);\n\t\tr.z = floor((e.vz - minMaxValues.minz) \/ (minMaxValues.maxz - minMaxValues.minz) * USHRT_MAX);\n\t\tr.u = floor(e.nu * UCHAR_MAX);\n\t\tr.v = floor(e.nv * UCHAR_MAX);\n\n\t\tfwrite(&r, sizeof(struct rec), 1, f);\n\t}\n\n\n\tstd::cout << \"Exported \" << counter << \" vertices\" << std::endl;\n\tfclose(f);\n\tcin.get();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef SILICIUM_REACTIVE_SOCKET_OBSERVABLE_HPP\n#define SILICIUM_REACTIVE_SOCKET_OBSERVABLE_HPP\n\n#include <silicium\/fast_variant.hpp>\n#include <silicium\/override.hpp>\n#include <silicium\/observable.hpp>\n#include <silicium\/exchange.hpp>\n#include <boost\/config.hpp>\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/range\/iterator_range.hpp>\n\nnamespace Si\n{\n\tstruct incoming_bytes\n\t{\n\t\tchar const *begin = nullptr, *end = nullptr;\n\n\t\tincoming_bytes() BOOST_NOEXCEPT\n\t\t{\n\t\t}\n\n\t\tincoming_bytes(char const *begin, char const *end) BOOST_NOEXCEPT\n\t\t\t: begin(begin)\n\t\t\t, end(end)\n\t\t{\n\t\t}\n\t};\n\n\ttypedef Si::fast_variant<incoming_bytes, boost::system::error_code> received_from_socket;\n\n\tstruct socket_observable : observable<received_from_socket>\n\t{\n\t\ttypedef received_from_socket element_type;\n\t\ttypedef boost::iterator_range<char *> buffer_type;\n\n\t\tsocket_observable(boost::asio::ip::tcp::socket &socket, buffer_type buffer)\n\t\t\t: socket(&socket)\n\t\t\t, buffer(buffer)\n\t\t{\n\t\t\tassert(!buffer.empty());\n\t\t}\n\n\t\tvirtual void async_get_one(observer<element_type> &receiver) SILICIUM_OVERRIDE\n\t\t{\n\t\t\tassert(!receiver_);\n\t\t\treceiver_ = &receiver;\n\t\t\tsocket->async_receive(boost::asio::buffer(buffer.begin(), buffer.size()), [this](boost::system::error_code error, std::size_t bytes_received)\n\t\t\t{\n\t\t\t\tassert(receiver_);\n\t\t\t\tif (error)\n\t\t\t\t{\n\t\t\t\t\tif (error == boost::asio::error::operation_aborted)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\texchange(this->receiver_, nullptr)->got_element(error);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto * const receiver = exchange(this->receiver_, nullptr);\n\t\t\t\t\treceiver->got_element(incoming_bytes{buffer.begin(), buffer.begin() + bytes_received});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tvirtual void cancel() SILICIUM_OVERRIDE\n\t\t{\n\t\t\tassert(receiver_);\n\t\t\tsocket->cancel();\n\t\t\treceiver_ = nullptr;\n\t\t}\n\n\tprivate:\n\n\t\tboost::asio::ip::tcp::socket *socket;\n\t\tbuffer_type buffer;\n\t\tobserver<element_type> *receiver_ = nullptr;\n\t};\n}\n\n#endif\n<commit_msg>devirtualize socket_observable<commit_after>#ifndef SILICIUM_REACTIVE_SOCKET_OBSERVABLE_HPP\n#define SILICIUM_REACTIVE_SOCKET_OBSERVABLE_HPP\n\n#include <silicium\/fast_variant.hpp>\n#include <silicium\/override.hpp>\n#include <silicium\/observer.hpp>\n#include <silicium\/exchange.hpp>\n#include <boost\/config.hpp>\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/range\/iterator_range.hpp>\n\nnamespace Si\n{\n\tstruct incoming_bytes\n\t{\n\t\tchar const *begin = nullptr, *end = nullptr;\n\n\t\tincoming_bytes() BOOST_NOEXCEPT\n\t\t{\n\t\t}\n\n\t\tincoming_bytes(char const *begin, char const *end) BOOST_NOEXCEPT\n\t\t\t: begin(begin)\n\t\t\t, end(end)\n\t\t{\n\t\t}\n\t};\n\n\ttypedef Si::fast_variant<incoming_bytes, boost::system::error_code> received_from_socket;\n\n\tstruct socket_observable\n\t{\n\t\ttypedef received_from_socket element_type;\n\t\ttypedef boost::iterator_range<char *> buffer_type;\n\n\t\tsocket_observable(boost::asio::ip::tcp::socket &socket, buffer_type buffer)\n\t\t\t: socket(&socket)\n\t\t\t, buffer(buffer)\n\t\t{\n\t\t\tassert(!buffer.empty());\n\t\t}\n\n\t\tvoid async_get_one(observer<element_type> &receiver)\n\t\t{\n\t\t\tassert(!receiver_);\n\t\t\treceiver_ = &receiver;\n\t\t\tsocket->async_receive(boost::asio::buffer(buffer.begin(), buffer.size()), [this](boost::system::error_code error, std::size_t bytes_received)\n\t\t\t{\n\t\t\t\tassert(receiver_);\n\t\t\t\tif (error)\n\t\t\t\t{\n\t\t\t\t\tif (error == boost::asio::error::operation_aborted)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\texchange(this->receiver_, nullptr)->got_element(error);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto * const receiver = exchange(this->receiver_, nullptr);\n\t\t\t\t\treceiver->got_element(incoming_bytes{buffer.begin(), buffer.begin() + bytes_received});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tvoid cancel()\n\t\t{\n\t\t\tassert(receiver_);\n\t\t\tsocket->cancel();\n\t\t\treceiver_ = nullptr;\n\t\t}\n\n\tprivate:\n\n\t\tboost::asio::ip::tcp::socket *socket;\n\t\tbuffer_type buffer;\n\t\tobserver<element_type> *receiver_ = nullptr;\n\t};\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ ================ INCLUDES ===================\n#include <Arduino.h>\n\n#include <Debug.h>\n#include <MouseMove.h>\n#include <IndicatorLEDs.h>\n\n\/\/ ================= DEBUG =====================\n#define PRINT_FREE_RAM \/\/print free RAM and headers\n\nDebug debug;\n\n\/\/ ======= INSTANTIATION THE KEYBOARD ==========\n#include \"config.h\"\n#include <instantiations_ports.h>\n#include <instantiations_codes.h>\n#include <instantiations_matrix.h> \/\/layout table is with instantiations_matrix.h\n\n\/\/ ================== MAIN =====================\nvoid setup()\n{\n rowPort1_R.begin();\n colPort0_R.begin();\n indicatorLEDs.begin(&layerState_DH);\n Keyboard.begin();\n Mouse.begin();\n\n#ifdef PRINT_FREE_RAM\n delay(1000); \/\/time for OS to detect USB before printing\n Keyboard.print(F(\"keybrd_DH.ino \"));\n debug.print_free_RAM();\n#endif \/\/end PRINT_FREE_RAM\n}\n\nvoid loop()\n{\n matrix_L.scan();\n matrix_R.scan();\n indicatorLEDs.blink();\n mouseMove.send();\n\n \/\/debug.print_scans_per_second();\n \/\/debug.print_microseconds_per_scan();\n}\n<commit_msg>move Wire.begin() to sketch<commit_after>\/\/ ================ INCLUDES ===================\n#include <Arduino.h>\n\n#include <Debug.h>\n#include <MouseMove.h>\n#include <IndicatorLEDs.h>\n\n\/\/ ================= DEBUG =====================\n#define PRINT_FREE_RAM \/\/print free RAM and headers\n\nDebug debug;\n\n\/\/ ======= INSTANTIATION THE KEYBOARD ==========\n#include \"config.h\"\n#include <instantiations_ports.h>\n#include <instantiations_codes.h>\n#include <instantiations_matrix.h> \/\/layout table is with instantiations_matrix.h\n\n\/\/ ================== MAIN =====================\nvoid setup()\n{\n Wire.begin(); \/\/todo has not been tested yet,\n \/\/Wire.begin() must be called before rowPort.begin() colPort.begin()\n rowPort1_R.begin();\n colPort0_R.begin();\n indicatorLEDs.begin(&layerState_DH);\n Keyboard.begin();\n Mouse.begin();\n\n#ifdef PRINT_FREE_RAM\n delay(1000); \/\/time for OS to detect USB before printing\n Keyboard.print(F(\"keybrd_DH.ino \"));\n debug.print_free_RAM();\n#endif \/\/end PRINT_FREE_RAM\n}\n\nvoid loop()\n{\n matrix_L.scan();\n matrix_R.scan();\n indicatorLEDs.blink();\n mouseMove.send();\n\n \/\/debug.print_scans_per_second();\n \/\/debug.print_microseconds_per_scan();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include \"astutil.h\"\n#include \"bb.h\"\n#include \"bitVec.h\"\n#include \"expr.h\"\n#include \"stmt.h\"\n#include \"view.h\"\n\nBasicBlock::BasicBlock()\n : id(nextid++) {}\n\n#define BB_START() \\\n basicBlock = new BasicBlock()\n\n\/\/ The assert tests that the expression we are adding to this basic block\n\/\/ has not already been deleted.\n#define BB_ADD(expr) \\\n INT_ASSERT(expr); \\\n basicBlock->exprs.add(expr)\n\n#define BB_ADD_LS(exprls) \\\n for_alist(expr, exprls) { \\\n BB_ADD(expr); \\\n }\n\n#define BB_STOP() \\\n fn->basicBlocks->add(Steal())\n\n#define BB_RESTART() \\\n BB_STOP(); \\\n BB_START()\n\n#define BBB(stmt) \\\n buildBasicBlocks(fn, stmt)\n\n#define BB_THREAD(src, dst) \\\n dst->ins.add(src); \\\n src->outs.add(dst)\n\n\/\/# Statics\nBasicBlock* BasicBlock::basicBlock;\nMap<LabelSymbol*,Vec<BasicBlock*>*> BasicBlock::gotoMaps;\nMap<LabelSymbol*,BasicBlock*> BasicBlock::labelMaps;\nint BasicBlock::nextid;\n\n\n\/\/ Returns true if the class invariants have been preserved.\nbool BasicBlock::isOK()\n{\n \/\/ Right now we just test that all entries are valid.\n forv_Vec(Expr, expr, exprs)\n if (expr == 0) return false;\n return true;\n}\n\n\/\/ Reset the shared statics.\nvoid BasicBlock::reset(FnSymbol* fn)\n{\n if (fn->basicBlocks)\n {\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n delete bb;\n delete fn->basicBlocks;\n }\n fn->basicBlocks = new Vec<BasicBlock*>();\n gotoMaps.clear();\n labelMaps.clear();\n nextid = 0;\n}\n\nBasicBlock* BasicBlock::Steal()\n{\n BasicBlock* temp = basicBlock;\n basicBlock = 0;\n return temp;\n}\n\n\/\/ This is the top-level (public) builder function.\nvoid buildBasicBlocks(FnSymbol* fn)\n{\n BasicBlock::reset(fn);\n BasicBlock::basicBlock = new BasicBlock();\n BasicBlock::buildBasicBlocks(fn, fn->body);\n fn->basicBlocks->add(BasicBlock::Steal());\n}\n\nvoid BasicBlock::buildBasicBlocks(FnSymbol* fn, Expr* stmt)\n{\n if (!stmt) return;\n\n if (BlockStmt* s = toBlockStmt(stmt))\n {\n \/\/ If a loop statement.\n if (s->blockInfo)\n {\n BasicBlock* top = basicBlock;\n BB_RESTART();\n \/\/ Assumes that blockInfo is never null.\n BB_ADD(s->blockInfo);\n BasicBlock* loopTop = basicBlock;\n for_alist(stmt, s->body) {\n BBB(stmt);\n }\n BasicBlock* loopBottom = basicBlock;\n BB_RESTART();\n BasicBlock* bottom = basicBlock;\n BB_THREAD(top, loopTop);\n BB_THREAD(loopBottom, bottom);\n BB_THREAD(loopBottom, loopTop);\n BB_THREAD(top, bottom);\n }\n else\n {\n for_alist(stmt, s->body)\n BBB(stmt);\n }\n }\n else if (CondStmt* s = toCondStmt(stmt))\n {\n INT_ASSERT(s->condExpr);\n BB_ADD(s->condExpr);\n BasicBlock* top = basicBlock;\n BB_RESTART();\n BB_THREAD(top, basicBlock);\n BBB(s->thenStmt);\n BasicBlock* thenBottom = basicBlock;\n BB_RESTART();\n if (s->elseStmt)\n {\n BB_THREAD(top, basicBlock);\n BBB(s->elseStmt);\n BasicBlock* elseBottom = basicBlock;\n BB_RESTART();\n BB_THREAD(elseBottom, basicBlock);\n }\n else\n {\n BB_THREAD(top, basicBlock);\n }\n BB_THREAD(thenBottom, basicBlock);\n } else if (GotoStmt* s = toGotoStmt(stmt)) {\n LabelSymbol* label = toLabelSymbol(toSymExpr(s->label)->var);\n if (BasicBlock* bb = labelMaps.get(label)) {\n BB_THREAD(basicBlock, bb);\n } else {\n Vec<BasicBlock*>* vbb = gotoMaps.get(label);\n if (!vbb)\n vbb = new Vec<BasicBlock*>();\n vbb->add(basicBlock);\n gotoMaps.put(label, vbb);\n }\n BB_ADD(s); \/\/ Put the goto at the end of its block.\n BB_RESTART();\n } else {\n DefExpr* def = toDefExpr(stmt);\n if (def && toLabelSymbol(def->sym)) {\n \/\/ If a label appears in the middle of a block,\n \/\/ we start a new block.\n if (basicBlock->exprs.count() > 0)\n {\n BasicBlock* top = basicBlock;\n BB_RESTART();\n BB_THREAD(top, basicBlock);\n }\n BB_ADD(def); \/\/ Put the label def at the start of its block.\n\n \/\/ OK, this statement is a label def, so get the label.\n LabelSymbol* label = toLabelSymbol(def->sym);\n\n \/\/ See if we have any unresolved references to this label,\n \/\/ and resolve them.\n if (Vec<BasicBlock*>* vbb = gotoMaps.get(label)) {\n forv_Vec(BasicBlock, bb, *vbb) {\n BB_THREAD(bb, basicBlock);\n }\n }\n labelMaps.put(label, basicBlock);\n } else {\n BB_ADD(stmt);\n }\n }\n}\n\n\/\/ Returns true if the basic block structure is OK, false otherwise.\nbool verifyBasicBlocks(FnSymbol* fn)\n{\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n {\n if (! bb->isOK())\n return false;\n }\n return true;\n}\n\nvoid buildLocalsVectorMap(FnSymbol* fn,\n Vec<Symbol*>& locals,\n Map<Symbol*,int>& localMap) {\n int i = 0;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n forv_Vec(Expr, expr, bb->exprs) {\n if (DefExpr* def = toDefExpr(expr)) {\n if (toVarSymbol(def->sym)) {\n locals.add(def->sym);\n localMap.put(def->sym, i++);\n }\n }\n }\n }\n}\n\n\n\/\/#define DEBUG_FLOW\nvoid backwardFlowAnalysis(FnSymbol* fn,\n Vec<BitVec*>& GEN,\n Vec<BitVec*>& KILL,\n Vec<BitVec*>& IN,\n Vec<BitVec*>& OUT) {\n bool iterate = true;\n while (iterate) {\n iterate = false;\n int i = 0;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n for (int j = 0; j < IN.v[i]->ndata; j++) {\n unsigned new_in = (OUT.v[i]->data[j] & ~KILL.v[i]->data[j]) | GEN.v[i]->data[j];\n if (new_in != IN.v[i]->data[j]) {\n IN.v[i]->data[j] = new_in;\n iterate = true;\n }\n unsigned new_out = 0;\n forv_Vec(BasicBlock, bbout, bb->outs) {\n new_out = new_out | IN.v[bbout->id]->data[j];\n }\n if (new_out != OUT.v[i]->data[j]) {\n OUT.v[i]->data[j] = new_out;\n iterate = true;\n }\n }\n i++;\n }\n#ifdef DEBUG_FLOW\n printf(\"IN\\n\"); printBitVectorSets(IN);\n printf(\"OUT\\n\"); printBitVectorSets(OUT);\n#endif\n }\n}\n\n\nvoid forwardFlowAnalysis(FnSymbol* fn,\n Vec<BitVec*>& GEN,\n Vec<BitVec*>& KILL,\n Vec<BitVec*>& IN,\n Vec<BitVec*>& OUT,\n bool intersect) {\n int nbbq = fn->basicBlocks->n; \/\/ size of bb queue\n Vec<int> bbq;\n BitVec bbs(nbbq);\n int iq = -1, nq = nbbq-1; \/\/ index to first and last bb in bbq\n for (int i = 0; i < fn->basicBlocks->n; i++) {\n bbq.add(i);\n bbs.set(i);\n }\n while (iq != nq) {\n iq = (iq + 1) % nbbq;\n int i = bbq.v[iq];\n bbs.unset(i);\n#ifdef DEBUG_FLOW\n if (iq == 0) {\n printf(\"IN\\n\"); printBitVectorSets(IN);\n printf(\"OUT\\n\"); printBitVectorSets(OUT);\n }\n#endif\n BasicBlock* bb = fn->basicBlocks->v[i];\n bool change = false;\n for (int j = 0; j < IN.v[i]->ndata; j++) {\n if (bb->ins.n > 0) {\n unsigned new_in = (intersect) ? (unsigned)(-1) : 0;\n forv_Vec(BasicBlock, bbin, bb->ins) {\n if (intersect)\n new_in &= OUT.v[bbin->id]->data[j];\n else\n new_in |= OUT.v[bbin->id]->data[j];\n }\n if (new_in != IN.v[i]->data[j]) {\n IN.v[i]->data[j] = new_in;\n change = true;\n }\n }\n unsigned new_out = (IN.v[i]->data[j] & ~KILL.v[i]->data[j]) | GEN.v[i]->data[j];\n if (new_out != OUT.v[i]->data[j]) {\n OUT.v[i]->data[j] = new_out;\n change = true;\n }\n }\n if (change) {\n forv_Vec(BasicBlock, bbout, bb->outs) {\n if (!bbs.get(bbout->id)) {\n nq = (nq + 1) % nbbq;\n bbs.set(bbout->id);\n bbq.v[nq] = bbout->id;\n }\n }\n }\n }\n}\n\n\nvoid printBasicBlocks(FnSymbol* fn) {\n forv_Vec(BasicBlock, b, *fn->basicBlocks) {\n printf(\"%2d: \", b->id);\n forv_Vec(BasicBlock, bb, b->ins) {\n printf(\"%d \", bb->id);\n }\n printf(\" > \");\n forv_Vec(BasicBlock, bb, b->outs) {\n printf(\"%d \", bb->id);\n }\n printf(\"\\n\");\n forv_Vec(Expr, expr, b->exprs) {\n if (expr)\n list_view_noline(expr);\n else\n printf(\"0 (null)\\n\");\n }\n printf(\"\\n\");\n }\n}\n\nvoid printLocalsVector(Vec<Symbol*> locals, Map<Symbol*,int>& localMap) {\n printf(\"Local Variables\\n\");\n forv_Vec(Symbol, local, locals) {\n printf(\"%2d: %s[%d]\\n\", localMap.get(local), local->name, local->id);\n }\n printf(\"\\n\");\n}\n\nvoid printDefsVector(Vec<SymExpr*> defs, Map<SymExpr*,int>& defMap) {\n printf(\"Variable Definitions\\n\");\n forv_Vec(SymExpr, def, defs) {\n printf(\"%2d: %s[%d] in %d\\n\", defMap.get(def), def->var->name,\n def->var->id, def->getStmtExpr()->id);\n }\n printf(\"\\n\");\n}\n\nvoid printLocalsVectorSets(Vec<BitVec*>& sets, Vec<Symbol*> locals) {\n int i = 0;\n forv_Vec(BitVec, set, sets) {\n printf(\"%2d: \", i);\n for (int j = 0; j < set->size; j++) {\n if (set->get(j))\n printf(\"%s[%d] \", locals.v[j]->name, locals.v[j]->id);\n }\n printf(\"\\n\");\n i++;\n }\n printf(\"\\n\");\n}\n\nvoid printBitVectorSets(Vec<BitVec*>& sets) {\n int i = 0;\n forv_Vec(BitVec, set, sets) {\n printf(\"%2d: \", i);\n for (int j = 0; j < set->size; j++) {\n printf(\"%d\", (set->get(j)) ? 1 : 0);\n if ((j+1) % 10 == 0) printf(\" \");\n }\n printf(\"\\n\");\n i++;\n }\n printf(\"\\n\");\n}\n<commit_msg>Use do { ... } while (0) idiom in multiline macros.<commit_after>#include <cstdlib>\n#include \"astutil.h\"\n#include \"bb.h\"\n#include \"bitVec.h\"\n#include \"expr.h\"\n#include \"stmt.h\"\n#include \"view.h\"\n\nBasicBlock::BasicBlock()\n : id(nextid++) {}\n\n#define BB_START() \\\n basicBlock = new BasicBlock()\n\n\/\/ The assert tests that the expression we are adding to this basic block\n\/\/ has not already been deleted.\n#define BB_ADD(expr) \\\n do { \\\n INT_ASSERT(expr); \\\n basicBlock->exprs.add(expr); \\\n } while (0)\n\n#define BB_STOP() \\\n fn->basicBlocks->add(Steal())\n\n#define BB_RESTART() \\\n do { \\\n BB_STOP(); \\\n BB_START(); \\\n } while (0)\n\n#define BBB(stmt) \\\n buildBasicBlocks(fn, stmt)\n\n#define BB_THREAD(src, dst) \\\n do { \\\n dst->ins.add(src); \\\n src->outs.add(dst); \\\n } while (0)\n\n\n\/\/# Statics\nBasicBlock* BasicBlock::basicBlock;\nMap<LabelSymbol*,Vec<BasicBlock*>*> BasicBlock::gotoMaps;\nMap<LabelSymbol*,BasicBlock*> BasicBlock::labelMaps;\nint BasicBlock::nextid;\n\n\n\/\/ Returns true if the class invariants have been preserved.\nbool BasicBlock::isOK()\n{\n \/\/ Right now we just test that all entries are valid.\n forv_Vec(Expr, expr, exprs)\n if (expr == 0) return false;\n return true;\n}\n\n\/\/ Reset the shared statics.\nvoid BasicBlock::reset(FnSymbol* fn)\n{\n if (fn->basicBlocks)\n {\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n delete bb;\n delete fn->basicBlocks;\n }\n fn->basicBlocks = new Vec<BasicBlock*>();\n gotoMaps.clear();\n labelMaps.clear();\n nextid = 0;\n}\n\nBasicBlock* BasicBlock::Steal()\n{\n BasicBlock* temp = basicBlock;\n basicBlock = 0;\n return temp;\n}\n\n\/\/ This is the top-level (public) builder function.\nvoid buildBasicBlocks(FnSymbol* fn)\n{\n BasicBlock::reset(fn);\n BasicBlock::basicBlock = new BasicBlock();\n BasicBlock::buildBasicBlocks(fn, fn->body);\n fn->basicBlocks->add(BasicBlock::Steal());\n}\n\nvoid BasicBlock::buildBasicBlocks(FnSymbol* fn, Expr* stmt)\n{\n if (!stmt) return;\n\n if (BlockStmt* s = toBlockStmt(stmt))\n {\n \/\/ If a loop statement.\n if (s->blockInfo)\n {\n BasicBlock* top = basicBlock;\n BB_RESTART();\n \/\/ Assumes that blockInfo is never null.\n BB_ADD(s->blockInfo);\n BasicBlock* loopTop = basicBlock;\n for_alist(stmt, s->body) {\n BBB(stmt);\n }\n BasicBlock* loopBottom = basicBlock;\n BB_RESTART();\n BasicBlock* bottom = basicBlock;\n BB_THREAD(top, loopTop);\n BB_THREAD(loopBottom, bottom);\n BB_THREAD(loopBottom, loopTop);\n BB_THREAD(top, bottom);\n }\n else\n {\n for_alist(stmt, s->body)\n BBB(stmt);\n }\n }\n else if (CondStmt* s = toCondStmt(stmt))\n {\n INT_ASSERT(s->condExpr);\n BB_ADD(s->condExpr);\n BasicBlock* top = basicBlock;\n BB_RESTART();\n BB_THREAD(top, basicBlock);\n BBB(s->thenStmt);\n BasicBlock* thenBottom = basicBlock;\n BB_RESTART();\n if (s->elseStmt)\n {\n BB_THREAD(top, basicBlock);\n BBB(s->elseStmt);\n BasicBlock* elseBottom = basicBlock;\n BB_RESTART();\n BB_THREAD(elseBottom, basicBlock);\n }\n else\n {\n BB_THREAD(top, basicBlock);\n }\n BB_THREAD(thenBottom, basicBlock);\n } else if (GotoStmt* s = toGotoStmt(stmt)) {\n LabelSymbol* label = toLabelSymbol(toSymExpr(s->label)->var);\n if (BasicBlock* bb = labelMaps.get(label)) {\n BB_THREAD(basicBlock, bb);\n } else {\n Vec<BasicBlock*>* vbb = gotoMaps.get(label);\n if (!vbb)\n vbb = new Vec<BasicBlock*>();\n vbb->add(basicBlock);\n gotoMaps.put(label, vbb);\n }\n BB_ADD(s); \/\/ Put the goto at the end of its block.\n BB_RESTART();\n } else {\n DefExpr* def = toDefExpr(stmt);\n if (def && toLabelSymbol(def->sym)) {\n \/\/ If a label appears in the middle of a block,\n \/\/ we start a new block.\n if (basicBlock->exprs.count() > 0)\n {\n BasicBlock* top = basicBlock;\n BB_RESTART();\n BB_THREAD(top, basicBlock);\n }\n BB_ADD(def); \/\/ Put the label def at the start of its block.\n\n \/\/ OK, this statement is a label def, so get the label.\n LabelSymbol* label = toLabelSymbol(def->sym);\n\n \/\/ See if we have any unresolved references to this label,\n \/\/ and resolve them.\n if (Vec<BasicBlock*>* vbb = gotoMaps.get(label)) {\n forv_Vec(BasicBlock, bb, *vbb) {\n BB_THREAD(bb, basicBlock);\n }\n }\n labelMaps.put(label, basicBlock);\n } else {\n BB_ADD(stmt);\n }\n }\n}\n\n\/\/ Returns true if the basic block structure is OK, false otherwise.\nbool verifyBasicBlocks(FnSymbol* fn)\n{\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n {\n if (! bb->isOK())\n return false;\n }\n return true;\n}\n\nvoid buildLocalsVectorMap(FnSymbol* fn,\n Vec<Symbol*>& locals,\n Map<Symbol*,int>& localMap) {\n int i = 0;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n forv_Vec(Expr, expr, bb->exprs) {\n if (DefExpr* def = toDefExpr(expr)) {\n if (toVarSymbol(def->sym)) {\n locals.add(def->sym);\n localMap.put(def->sym, i++);\n }\n }\n }\n }\n}\n\n\n\/\/#define DEBUG_FLOW\nvoid backwardFlowAnalysis(FnSymbol* fn,\n Vec<BitVec*>& GEN,\n Vec<BitVec*>& KILL,\n Vec<BitVec*>& IN,\n Vec<BitVec*>& OUT) {\n bool iterate = true;\n while (iterate) {\n iterate = false;\n int i = 0;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n for (int j = 0; j < IN.v[i]->ndata; j++) {\n unsigned new_in = (OUT.v[i]->data[j] & ~KILL.v[i]->data[j]) | GEN.v[i]->data[j];\n if (new_in != IN.v[i]->data[j]) {\n IN.v[i]->data[j] = new_in;\n iterate = true;\n }\n unsigned new_out = 0;\n forv_Vec(BasicBlock, bbout, bb->outs) {\n new_out = new_out | IN.v[bbout->id]->data[j];\n }\n if (new_out != OUT.v[i]->data[j]) {\n OUT.v[i]->data[j] = new_out;\n iterate = true;\n }\n }\n i++;\n }\n#ifdef DEBUG_FLOW\n printf(\"IN\\n\"); printBitVectorSets(IN);\n printf(\"OUT\\n\"); printBitVectorSets(OUT);\n#endif\n }\n}\n\n\nvoid forwardFlowAnalysis(FnSymbol* fn,\n Vec<BitVec*>& GEN,\n Vec<BitVec*>& KILL,\n Vec<BitVec*>& IN,\n Vec<BitVec*>& OUT,\n bool intersect) {\n int nbbq = fn->basicBlocks->n; \/\/ size of bb queue\n Vec<int> bbq;\n BitVec bbs(nbbq);\n int iq = -1, nq = nbbq-1; \/\/ index to first and last bb in bbq\n for (int i = 0; i < fn->basicBlocks->n; i++) {\n bbq.add(i);\n bbs.set(i);\n }\n while (iq != nq) {\n iq = (iq + 1) % nbbq;\n int i = bbq.v[iq];\n bbs.unset(i);\n#ifdef DEBUG_FLOW\n if (iq == 0) {\n printf(\"IN\\n\"); printBitVectorSets(IN);\n printf(\"OUT\\n\"); printBitVectorSets(OUT);\n }\n#endif\n BasicBlock* bb = fn->basicBlocks->v[i];\n bool change = false;\n for (int j = 0; j < IN.v[i]->ndata; j++) {\n if (bb->ins.n > 0) {\n unsigned new_in = (intersect) ? (unsigned)(-1) : 0;\n forv_Vec(BasicBlock, bbin, bb->ins) {\n if (intersect)\n new_in &= OUT.v[bbin->id]->data[j];\n else\n new_in |= OUT.v[bbin->id]->data[j];\n }\n if (new_in != IN.v[i]->data[j]) {\n IN.v[i]->data[j] = new_in;\n change = true;\n }\n }\n unsigned new_out = (IN.v[i]->data[j] & ~KILL.v[i]->data[j]) | GEN.v[i]->data[j];\n if (new_out != OUT.v[i]->data[j]) {\n OUT.v[i]->data[j] = new_out;\n change = true;\n }\n }\n if (change) {\n forv_Vec(BasicBlock, bbout, bb->outs) {\n if (!bbs.get(bbout->id)) {\n nq = (nq + 1) % nbbq;\n bbs.set(bbout->id);\n bbq.v[nq] = bbout->id;\n }\n }\n }\n }\n}\n\n\nvoid printBasicBlocks(FnSymbol* fn) {\n forv_Vec(BasicBlock, b, *fn->basicBlocks) {\n printf(\"%2d: \", b->id);\n forv_Vec(BasicBlock, bb, b->ins) {\n printf(\"%d \", bb->id);\n }\n printf(\" > \");\n forv_Vec(BasicBlock, bb, b->outs) {\n printf(\"%d \", bb->id);\n }\n printf(\"\\n\");\n forv_Vec(Expr, expr, b->exprs) {\n if (expr)\n list_view_noline(expr);\n else\n printf(\"0 (null)\\n\");\n }\n printf(\"\\n\");\n }\n}\n\nvoid printLocalsVector(Vec<Symbol*> locals, Map<Symbol*,int>& localMap) {\n printf(\"Local Variables\\n\");\n forv_Vec(Symbol, local, locals) {\n printf(\"%2d: %s[%d]\\n\", localMap.get(local), local->name, local->id);\n }\n printf(\"\\n\");\n}\n\nvoid printDefsVector(Vec<SymExpr*> defs, Map<SymExpr*,int>& defMap) {\n printf(\"Variable Definitions\\n\");\n forv_Vec(SymExpr, def, defs) {\n printf(\"%2d: %s[%d] in %d\\n\", defMap.get(def), def->var->name,\n def->var->id, def->getStmtExpr()->id);\n }\n printf(\"\\n\");\n}\n\nvoid printLocalsVectorSets(Vec<BitVec*>& sets, Vec<Symbol*> locals) {\n int i = 0;\n forv_Vec(BitVec, set, sets) {\n printf(\"%2d: \", i);\n for (int j = 0; j < set->size; j++) {\n if (set->get(j))\n printf(\"%s[%d] \", locals.v[j]->name, locals.v[j]->id);\n }\n printf(\"\\n\");\n i++;\n }\n printf(\"\\n\");\n}\n\nvoid printBitVectorSets(Vec<BitVec*>& sets) {\n int i = 0;\n forv_Vec(BitVec, set, sets) {\n printf(\"%2d: \", i);\n for (int j = 0; j < set->size; j++) {\n printf(\"%d\", (set->get(j)) ? 1 : 0);\n if ((j+1) % 10 == 0) printf(\" \");\n }\n printf(\"\\n\");\n i++;\n }\n printf(\"\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*-\n *\n * Copyright (C) 2008 Stuart Buchanan\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\n *\/\n\n#ifdef HAVE_CONFIG_H\n# include <simgear_config.h>\n#endif\n\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <map>\n\n#include <boost\/tuple\/tuple_comparison.hpp>\n\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osg\/Math>\n#include <osg\/MatrixTransform>\n#include <osg\/Matrix>\n#include <osg\/NodeVisitor>\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/FileUtils>\n\n#include <simgear\/debug\/logstream.hxx>\n#include <simgear\/math\/sg_random.h>\n#include <simgear\/misc\/sg_path.hxx>\n#include <simgear\/scene\/material\/Effect.hxx>\n#include <simgear\/scene\/material\/EffectGeode.hxx>\n#include <simgear\/props\/props.hxx>\n#include <simgear\/scene\/util\/QuadTreeBuilder.hxx>\n#include <simgear\/scene\/util\/RenderConstants.hxx>\n#include <simgear\/scene\/util\/StateAttributeFactory.hxx>\n#include <simgear\/structure\/OSGUtils.hxx>\n\n#include \"ShaderGeometry.hxx\"\n#include \"TreeBin.hxx\"\n\n#define SG_TREE_QUAD_TREE_DEPTH 3\n#define SG_TREE_FADE_OUT_LEVELS 10\n\nusing namespace osg;\n\nnamespace simgear\n{\n\n\/\/ Tree instance scheme:\n\/\/ vertex - local position of quad vertex.\n\/\/ normal - x y scaling, z number of varieties\n\/\/ fog coord - rotation\n\/\/ color - xyz of tree quad origin, replicated 4 times.\n\/\/\n\/\/ The tree quad is rendered twice, with different rotations, to\n\/\/ create the crossed tree geometry.\n\nstruct TreesBoundingBoxCallback : public Drawable::ComputeBoundingBoxCallback\n{\n TreesBoundingBoxCallback() {}\n TreesBoundingBoxCallback(const TreesBoundingBoxCallback&, const CopyOp&) {}\n META_Object(simgear, TreesBoundingBoxCallback);\n virtual BoundingBox computeBound(const Drawable&) const;\n};\n\nBoundingBox\nTreesBoundingBoxCallback::computeBound(const Drawable& drawable) const\n{\n BoundingBox bb;\n const Geometry* geom = static_cast<const Geometry*>(&drawable);\n const Vec3Array* v = static_cast<const Vec3Array*>(geom->getVertexArray());\n const Vec3Array* pos = static_cast<const Vec3Array*>(geom->getColorArray());\n const Vec3Array* params\n = static_cast<const Vec3Array*>(geom->getNormalArray());\n const FloatArray* rot\n = static_cast<const FloatArray*>(geom->getFogCoordArray());\n float w = (*params)[0].x();\n float h = (*params)[0].y();\n Geometry::PrimitiveSetList primSets = geom->getPrimitiveSetList();\n FloatArray::const_iterator rotitr = rot->begin();\n for (Geometry::PrimitiveSetList::const_iterator psitr = primSets.begin(),\n psend = primSets.end();\n psitr != psend;\n ++psitr, ++rotitr) {\n Matrixd trnsfrm = (Matrixd::scale(w, w, h)\n * Matrixd::rotate(*rotitr, Vec3(0.0f, 0.0f, 1.0f)));\n DrawArrays* da = static_cast<DrawArrays*>(psitr->get());\n GLint psFirst = da->getFirst();\n GLint psEndVert = psFirst + da->getCount();\n for (GLint i = psFirst;i < psEndVert; ++i) {\n Vec3 pt = (*v)[i];\n pt = pt * trnsfrm;\n pt += (*pos)[i];\n bb.expandBy(pt);\n }\n }\n return bb;\n}\n\nGeometry* makeSharedTreeGeometry(int numQuads)\n{\n \/\/ generate a repeatable random seed\n mt seed;\n mt_init(&seed, unsigned(123));\n \/\/ set up the coords\n osg::Vec3Array* v = new osg::Vec3Array;\n osg::Vec2Array* t = new osg::Vec2Array;\n v->reserve(numQuads * 4);\n t->reserve(numQuads * 4);\n for (int i = 0; i < numQuads; ++i) {\n \/\/ Apply a random scaling factor and texture index.\n float h = (mt_rand(&seed) + mt_rand(&seed)) \/ 2.0f + 0.5f;\n float cw = h * .5;\n v->push_back(Vec3(0.0f, -cw, 0.0f));\n v->push_back(Vec3(0.0f, cw, 0.0f));\n v->push_back(Vec3(0.0f, cw, h));\n v->push_back(Vec3(0.0f,-cw, h));\n \/\/ The texture coordinate range is not the entire coordinate\n \/\/ space, as the texture has a number of different trees on\n \/\/ it. Here we assign random coordinates and let the shader\n \/\/ choose the variety.\n float variety = mt_rand(&seed);\n t->push_back(Vec2(variety, 0.0f));\n t->push_back(Vec2(variety + 1.0f, 0.0f));\n t->push_back(Vec2(variety + 1.0f, 0.25f));\n t->push_back(Vec2(variety, 0.25f));\n }\n Geometry* result = new Geometry;\n result->setVertexArray(v);\n result->setTexCoordArray(0, t);\n result->setComputeBoundingBoxCallback(new TreesBoundingBoxCallback);\n result->setUseDisplayList(false);\n return result;\n}\n\nref_ptr<Geometry> sharedTreeGeometry;\n\nGeometry* createTreeGeometry(float width, float height, int varieties)\n{\n if (!sharedTreeGeometry)\n sharedTreeGeometry = makeSharedTreeGeometry(1600);\n Geometry* quadGeom = simgear::clone(sharedTreeGeometry.get(),\n CopyOp::SHALLOW_COPY);\n Vec3Array* params = new Vec3Array;\n params->push_back(Vec3(width, height, (float)varieties));\n quadGeom->setNormalArray(params);\n quadGeom->setNormalBinding(Geometry::BIND_OVERALL);\n \/\/ Positions\n quadGeom->setColorArray(new Vec3Array);\n quadGeom->setColorBinding(Geometry::BIND_PER_VERTEX);\n FloatArray* rotation = new FloatArray(2);\n (*rotation)[0] = 0.0;\n (*rotation)[1] = PI_2;\n quadGeom->setFogCoordArray(rotation);\n quadGeom->setFogCoordBinding(Geometry::BIND_PER_PRIMITIVE_SET);\n \/\/ The primitive sets render the same geometry, but the second\n \/\/ will rotated 90 degrees by the vertex shader, which uses the\n \/\/ fog coordinate as a rotation.\n for (int i = 0; i < 2; ++i)\n quadGeom->addPrimitiveSet(new DrawArrays(PrimitiveSet::QUADS));\n return quadGeom;\n}\n\nEffectGeode* createTreeGeode(float width, float height, int varieties)\n{\n EffectGeode* result = new EffectGeode;\n result->addDrawable(createTreeGeometry(width, height, varieties));\n return result;\n}\n\nvoid addTreeToLeafGeode(Geode* geode, const SGVec3f& p)\n{\n Vec3 pos = toOsg(p);\n unsigned int numDrawables = geode->getNumDrawables();\n Geometry* geom\n = static_cast<Geometry*>(geode->getDrawable(numDrawables - 1));\n Vec3Array* posArray = static_cast<Vec3Array*>(geom->getColorArray());\n if (posArray->size()\n >= static_cast<Vec3Array*>(geom->getVertexArray())->size()) {\n Vec3Array* paramsArray\n = static_cast<Vec3Array*>(geom->getNormalArray());\n Vec3 params = (*paramsArray)[0];\n geom = createTreeGeometry(params.x(), params.y(), params.z());\n posArray = static_cast<Vec3Array*>(geom->getColorArray());\n geode->addDrawable(geom);\n }\n posArray->insert(posArray->end(), 4, pos);\n size_t numVerts = posArray->size();\n for (int i = 0; i < 2; ++i) {\n DrawArrays* primSet\n = static_cast<DrawArrays*>(geom->getPrimitiveSet(i));\n primSet->setCount(numVerts);\n }\n}\n\ntypedef std::map<std::string, osg::observer_ptr<Effect> > EffectMap;\n\nstatic EffectMap treeEffectMap;\n\n\/\/ Helper classes for creating the quad tree\nnamespace\n{\nstruct MakeTreesLeaf\n{\n MakeTreesLeaf(float range, int varieties, float width, float height,\n Effect* effect) :\n _range(range), _varieties(varieties),\n _width(width), _height(height), _effect(effect) {}\n\n MakeTreesLeaf(const MakeTreesLeaf& rhs) :\n _range(rhs._range),\n _varieties(rhs._varieties), _width(rhs._width), _height(rhs._height),\n _effect(rhs._effect)\n {}\n\n LOD* operator() () const\n {\n LOD* result = new LOD;\n \n \/\/ Create a series of LOD nodes so trees cover decreases slightly\n \/\/ gradually with distance from _range to 2*_range\n for (float i = 0.0; i < SG_TREE_FADE_OUT_LEVELS; i++)\n { \n EffectGeode* geode = createTreeGeode(_width, _height, _varieties);\n geode->setEffect(_effect.get());\n result->addChild(geode, 0, _range * (1.0 + i \/ (SG_TREE_FADE_OUT_LEVELS - 1.0)));\n }\n return result;\n }\n float _range;\n int _varieties;\n float _width;\n float _height;\n ref_ptr<Effect> _effect;\n};\n\nstruct AddTreesLeafObject\n{\n void operator() (LOD* lod, const TreeBin::Tree& tree) const\n {\n Geode* geode = static_cast<Geode*>(lod->getChild(int(tree.position.x() * 10.0f) % lod->getNumChildren()));\n addTreeToLeafGeode(geode, tree.position);\n }\n};\n\nstruct GetTreeCoord\n{\n Vec3 operator() (const TreeBin::Tree& tree) const\n {\n return toOsg(tree.position);\n }\n};\n\ntypedef QuadTreeBuilder<LOD*, TreeBin::Tree, MakeTreesLeaf, AddTreesLeafObject,\n GetTreeCoord> ShaderGeometryQuadtree;\n}\n\nstruct TreeTransformer\n{\n TreeTransformer(Matrix& mat_) : mat(mat_) {}\n TreeBin::Tree operator()(const TreeBin::Tree& tree) const\n {\n Vec3 pos = toOsg(tree.position);\n return TreeBin::Tree(toSG(pos * mat));\n }\n Matrix mat;\n};\n\n\/\/ We may end up with a quadtree with many empty leaves. One might say\n\/\/ that we should avoid constructing the leaves in the first place,\n\/\/ but this node visitor tries to clean up after the fact.\n\nstruct QuadTreeCleaner : public osg::NodeVisitor\n{\n QuadTreeCleaner() : NodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN)\n {\n }\n void apply(LOD& lod)\n {\n for (int i = lod.getNumChildren() - 1; i >= 0; --i) {\n EffectGeode* geode = dynamic_cast<EffectGeode*>(lod.getChild(i));\n if (!geode)\n continue;\n bool geodeEmpty = true;\n for (unsigned j = 0; j < geode->getNumDrawables(); ++j) {\n const Geometry* geom = dynamic_cast<Geometry*>(geode->getDrawable(j));\n if (!geom) {\n geodeEmpty = false;\n break;\n }\n for (unsigned k = 0; k < geom->getNumPrimitiveSets(); k++) {\n const PrimitiveSet* ps = geom->getPrimitiveSet(k);\n if (ps->getNumIndices() > 0) {\n geodeEmpty = false;\n break;\n }\n }\n }\n if (geodeEmpty)\n lod.removeChildren(i, 1);\n }\n }\n};\n\n\/\/ This actually returns a MatrixTransform node. If we rotate the whole\n\/\/ forest into the local Z-up coordinate system we can reuse the\n\/\/ primitive tree geometry for all the forests of the same type.\n\nosg::Group* createForest(SGTreeBinList& forestList, const osg::Matrix& transform,\n const SGReaderWriterOptions* options)\n{\n Matrix transInv = Matrix::inverse(transform);\n static Matrix ident;\n \/\/ Set up some shared structures.\n ref_ptr<Group> group;\n MatrixTransform* mt = new MatrixTransform(transform);\n\n SGTreeBinList::iterator i;\n\n for (i = forestList.begin(); i != forestList.end(); ++i) {\n TreeBin* forest = *i;\n \n ref_ptr<Effect> effect;\n EffectMap::iterator iter = treeEffectMap.find(forest->texture);\n\n if ((iter == treeEffectMap.end())||\n (!iter->second.lock(effect)))\n {\n SGPropertyNode_ptr effectProp = new SGPropertyNode;\n makeChild(effectProp, \"inherits-from\")->setStringValue(\"Effects\/tree\");\n SGPropertyNode* params = makeChild(effectProp, \"parameters\");\n \/\/ emphasize n = 0\n params->getChild(\"texture\", 0, true)->getChild(\"image\", 0, true)\n ->setStringValue(forest->texture);\n effect = makeEffect(effectProp, true, options);\n if (iter == treeEffectMap.end())\n treeEffectMap.insert(EffectMap::value_type(forest->texture, effect));\n else\n iter->second = effect; \/\/ update existing, but empty observer\n }\n\n \/\/ Now, create a quadtree for the forest.\n ShaderGeometryQuadtree\n quadtree(GetTreeCoord(), AddTreesLeafObject(),\n SG_TREE_QUAD_TREE_DEPTH,\n MakeTreesLeaf(forest->range, forest->texture_varieties,\n forest->width, forest->height, effect));\n \/\/ Transform tree positions from the \"geocentric\" positions we\n \/\/ get from the scenery polys into the local Z-up coordinate\n \/\/ system.\n std::vector<TreeBin::Tree> rotatedTrees;\n rotatedTrees.reserve(forest->_trees.size());\n std::transform(forest->_trees.begin(), forest->_trees.end(),\n std::back_inserter(rotatedTrees),\n TreeTransformer(transInv));\n quadtree.buildQuadTree(rotatedTrees.begin(), rotatedTrees.end());\n group = quadtree.getRoot();\n\n for (size_t i = 0; i < group->getNumChildren(); ++i)\n mt->addChild(group->getChild(i));\n \n delete forest;\n }\n \n forestList.clear();\n QuadTreeCleaner cleaner;\n mt->accept(cleaner);\n return mt;\n}\n\n\n}\n<commit_msg>Reduce the height of tree UV coordinates to work around mipmap issues.<commit_after>\/* -*-c++-*-\n *\n * Copyright (C) 2008 Stuart Buchanan\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\n *\/\n\n#ifdef HAVE_CONFIG_H\n# include <simgear_config.h>\n#endif\n\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <map>\n\n#include <boost\/tuple\/tuple_comparison.hpp>\n\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osg\/Math>\n#include <osg\/MatrixTransform>\n#include <osg\/Matrix>\n#include <osg\/NodeVisitor>\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/FileUtils>\n\n#include <simgear\/debug\/logstream.hxx>\n#include <simgear\/math\/sg_random.h>\n#include <simgear\/misc\/sg_path.hxx>\n#include <simgear\/scene\/material\/Effect.hxx>\n#include <simgear\/scene\/material\/EffectGeode.hxx>\n#include <simgear\/props\/props.hxx>\n#include <simgear\/scene\/util\/QuadTreeBuilder.hxx>\n#include <simgear\/scene\/util\/RenderConstants.hxx>\n#include <simgear\/scene\/util\/StateAttributeFactory.hxx>\n#include <simgear\/structure\/OSGUtils.hxx>\n\n#include \"ShaderGeometry.hxx\"\n#include \"TreeBin.hxx\"\n\n#define SG_TREE_QUAD_TREE_DEPTH 3\n#define SG_TREE_FADE_OUT_LEVELS 10\n\nusing namespace osg;\n\nnamespace simgear\n{\n\n\/\/ Tree instance scheme:\n\/\/ vertex - local position of quad vertex.\n\/\/ normal - x y scaling, z number of varieties\n\/\/ fog coord - rotation\n\/\/ color - xyz of tree quad origin, replicated 4 times.\n\/\/\n\/\/ The tree quad is rendered twice, with different rotations, to\n\/\/ create the crossed tree geometry.\n\nstruct TreesBoundingBoxCallback : public Drawable::ComputeBoundingBoxCallback\n{\n TreesBoundingBoxCallback() {}\n TreesBoundingBoxCallback(const TreesBoundingBoxCallback&, const CopyOp&) {}\n META_Object(simgear, TreesBoundingBoxCallback);\n virtual BoundingBox computeBound(const Drawable&) const;\n};\n\nBoundingBox\nTreesBoundingBoxCallback::computeBound(const Drawable& drawable) const\n{\n BoundingBox bb;\n const Geometry* geom = static_cast<const Geometry*>(&drawable);\n const Vec3Array* v = static_cast<const Vec3Array*>(geom->getVertexArray());\n const Vec3Array* pos = static_cast<const Vec3Array*>(geom->getColorArray());\n const Vec3Array* params\n = static_cast<const Vec3Array*>(geom->getNormalArray());\n const FloatArray* rot\n = static_cast<const FloatArray*>(geom->getFogCoordArray());\n float w = (*params)[0].x();\n float h = (*params)[0].y();\n Geometry::PrimitiveSetList primSets = geom->getPrimitiveSetList();\n FloatArray::const_iterator rotitr = rot->begin();\n for (Geometry::PrimitiveSetList::const_iterator psitr = primSets.begin(),\n psend = primSets.end();\n psitr != psend;\n ++psitr, ++rotitr) {\n Matrixd trnsfrm = (Matrixd::scale(w, w, h)\n * Matrixd::rotate(*rotitr, Vec3(0.0f, 0.0f, 1.0f)));\n DrawArrays* da = static_cast<DrawArrays*>(psitr->get());\n GLint psFirst = da->getFirst();\n GLint psEndVert = psFirst + da->getCount();\n for (GLint i = psFirst;i < psEndVert; ++i) {\n Vec3 pt = (*v)[i];\n pt = pt * trnsfrm;\n pt += (*pos)[i];\n bb.expandBy(pt);\n }\n }\n return bb;\n}\n\nGeometry* makeSharedTreeGeometry(int numQuads)\n{\n \/\/ generate a repeatable random seed\n mt seed;\n mt_init(&seed, unsigned(123));\n \/\/ set up the coords\n osg::Vec3Array* v = new osg::Vec3Array;\n osg::Vec2Array* t = new osg::Vec2Array;\n v->reserve(numQuads * 4);\n t->reserve(numQuads * 4);\n for (int i = 0; i < numQuads; ++i) {\n \/\/ Apply a random scaling factor and texture index.\n float h = (mt_rand(&seed) + mt_rand(&seed)) \/ 2.0f + 0.5f;\n float cw = h * .5;\n v->push_back(Vec3(0.0f, -cw, 0.0f));\n v->push_back(Vec3(0.0f, cw, 0.0f));\n v->push_back(Vec3(0.0f, cw, h));\n v->push_back(Vec3(0.0f,-cw, h));\n \/\/ The texture coordinate range is not the entire coordinate\n \/\/ space, as the texture has a number of different trees on\n \/\/ it. Here we assign random coordinates and let the shader\n \/\/ choose the variety.\n \/\/ Height isn't quite 0.25 to allow for UV map bleeding when\n \/\/ mipmaps are generated.\n float variety = mt_rand(&seed);\n t->push_back(Vec2(variety, 0.0f));\n t->push_back(Vec2(variety + 1.0f, 0.0f));\n t->push_back(Vec2(variety + 1.0f, 0.246f));\n t->push_back(Vec2(variety, 0.246f));\n }\n Geometry* result = new Geometry;\n result->setVertexArray(v);\n result->setTexCoordArray(0, t);\n result->setComputeBoundingBoxCallback(new TreesBoundingBoxCallback);\n result->setUseDisplayList(false);\n return result;\n}\n\nref_ptr<Geometry> sharedTreeGeometry;\n\nGeometry* createTreeGeometry(float width, float height, int varieties)\n{\n if (!sharedTreeGeometry)\n sharedTreeGeometry = makeSharedTreeGeometry(1600);\n Geometry* quadGeom = simgear::clone(sharedTreeGeometry.get(),\n CopyOp::SHALLOW_COPY);\n Vec3Array* params = new Vec3Array;\n params->push_back(Vec3(width, height, (float)varieties));\n quadGeom->setNormalArray(params);\n quadGeom->setNormalBinding(Geometry::BIND_OVERALL);\n \/\/ Positions\n quadGeom->setColorArray(new Vec3Array);\n quadGeom->setColorBinding(Geometry::BIND_PER_VERTEX);\n FloatArray* rotation = new FloatArray(2);\n (*rotation)[0] = 0.0;\n (*rotation)[1] = PI_2;\n quadGeom->setFogCoordArray(rotation);\n quadGeom->setFogCoordBinding(Geometry::BIND_PER_PRIMITIVE_SET);\n \/\/ The primitive sets render the same geometry, but the second\n \/\/ will rotated 90 degrees by the vertex shader, which uses the\n \/\/ fog coordinate as a rotation.\n for (int i = 0; i < 2; ++i)\n quadGeom->addPrimitiveSet(new DrawArrays(PrimitiveSet::QUADS));\n return quadGeom;\n}\n\nEffectGeode* createTreeGeode(float width, float height, int varieties)\n{\n EffectGeode* result = new EffectGeode;\n result->addDrawable(createTreeGeometry(width, height, varieties));\n return result;\n}\n\nvoid addTreeToLeafGeode(Geode* geode, const SGVec3f& p)\n{\n Vec3 pos = toOsg(p);\n unsigned int numDrawables = geode->getNumDrawables();\n Geometry* geom\n = static_cast<Geometry*>(geode->getDrawable(numDrawables - 1));\n Vec3Array* posArray = static_cast<Vec3Array*>(geom->getColorArray());\n if (posArray->size()\n >= static_cast<Vec3Array*>(geom->getVertexArray())->size()) {\n Vec3Array* paramsArray\n = static_cast<Vec3Array*>(geom->getNormalArray());\n Vec3 params = (*paramsArray)[0];\n geom = createTreeGeometry(params.x(), params.y(), params.z());\n posArray = static_cast<Vec3Array*>(geom->getColorArray());\n geode->addDrawable(geom);\n }\n posArray->insert(posArray->end(), 4, pos);\n size_t numVerts = posArray->size();\n for (int i = 0; i < 2; ++i) {\n DrawArrays* primSet\n = static_cast<DrawArrays*>(geom->getPrimitiveSet(i));\n primSet->setCount(numVerts);\n }\n}\n\ntypedef std::map<std::string, osg::observer_ptr<Effect> > EffectMap;\n\nstatic EffectMap treeEffectMap;\n\n\/\/ Helper classes for creating the quad tree\nnamespace\n{\nstruct MakeTreesLeaf\n{\n MakeTreesLeaf(float range, int varieties, float width, float height,\n Effect* effect) :\n _range(range), _varieties(varieties),\n _width(width), _height(height), _effect(effect) {}\n\n MakeTreesLeaf(const MakeTreesLeaf& rhs) :\n _range(rhs._range),\n _varieties(rhs._varieties), _width(rhs._width), _height(rhs._height),\n _effect(rhs._effect)\n {}\n\n LOD* operator() () const\n {\n LOD* result = new LOD;\n \n \/\/ Create a series of LOD nodes so trees cover decreases slightly\n \/\/ gradually with distance from _range to 2*_range\n for (float i = 0.0; i < SG_TREE_FADE_OUT_LEVELS; i++)\n { \n EffectGeode* geode = createTreeGeode(_width, _height, _varieties);\n geode->setEffect(_effect.get());\n result->addChild(geode, 0, _range * (1.0 + i \/ (SG_TREE_FADE_OUT_LEVELS - 1.0)));\n }\n return result;\n }\n float _range;\n int _varieties;\n float _width;\n float _height;\n ref_ptr<Effect> _effect;\n};\n\nstruct AddTreesLeafObject\n{\n void operator() (LOD* lod, const TreeBin::Tree& tree) const\n {\n Geode* geode = static_cast<Geode*>(lod->getChild(int(tree.position.x() * 10.0f) % lod->getNumChildren()));\n addTreeToLeafGeode(geode, tree.position);\n }\n};\n\nstruct GetTreeCoord\n{\n Vec3 operator() (const TreeBin::Tree& tree) const\n {\n return toOsg(tree.position);\n }\n};\n\ntypedef QuadTreeBuilder<LOD*, TreeBin::Tree, MakeTreesLeaf, AddTreesLeafObject,\n GetTreeCoord> ShaderGeometryQuadtree;\n}\n\nstruct TreeTransformer\n{\n TreeTransformer(Matrix& mat_) : mat(mat_) {}\n TreeBin::Tree operator()(const TreeBin::Tree& tree) const\n {\n Vec3 pos = toOsg(tree.position);\n return TreeBin::Tree(toSG(pos * mat));\n }\n Matrix mat;\n};\n\n\/\/ We may end up with a quadtree with many empty leaves. One might say\n\/\/ that we should avoid constructing the leaves in the first place,\n\/\/ but this node visitor tries to clean up after the fact.\n\nstruct QuadTreeCleaner : public osg::NodeVisitor\n{\n QuadTreeCleaner() : NodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN)\n {\n }\n void apply(LOD& lod)\n {\n for (int i = lod.getNumChildren() - 1; i >= 0; --i) {\n EffectGeode* geode = dynamic_cast<EffectGeode*>(lod.getChild(i));\n if (!geode)\n continue;\n bool geodeEmpty = true;\n for (unsigned j = 0; j < geode->getNumDrawables(); ++j) {\n const Geometry* geom = dynamic_cast<Geometry*>(geode->getDrawable(j));\n if (!geom) {\n geodeEmpty = false;\n break;\n }\n for (unsigned k = 0; k < geom->getNumPrimitiveSets(); k++) {\n const PrimitiveSet* ps = geom->getPrimitiveSet(k);\n if (ps->getNumIndices() > 0) {\n geodeEmpty = false;\n break;\n }\n }\n }\n if (geodeEmpty)\n lod.removeChildren(i, 1);\n }\n }\n};\n\n\/\/ This actually returns a MatrixTransform node. If we rotate the whole\n\/\/ forest into the local Z-up coordinate system we can reuse the\n\/\/ primitive tree geometry for all the forests of the same type.\n\nosg::Group* createForest(SGTreeBinList& forestList, const osg::Matrix& transform,\n const SGReaderWriterOptions* options)\n{\n Matrix transInv = Matrix::inverse(transform);\n static Matrix ident;\n \/\/ Set up some shared structures.\n ref_ptr<Group> group;\n MatrixTransform* mt = new MatrixTransform(transform);\n\n SGTreeBinList::iterator i;\n\n for (i = forestList.begin(); i != forestList.end(); ++i) {\n TreeBin* forest = *i;\n \n ref_ptr<Effect> effect;\n EffectMap::iterator iter = treeEffectMap.find(forest->texture);\n\n if ((iter == treeEffectMap.end())||\n (!iter->second.lock(effect)))\n {\n SGPropertyNode_ptr effectProp = new SGPropertyNode;\n makeChild(effectProp, \"inherits-from\")->setStringValue(\"Effects\/tree\");\n SGPropertyNode* params = makeChild(effectProp, \"parameters\");\n \/\/ emphasize n = 0\n params->getChild(\"texture\", 0, true)->getChild(\"image\", 0, true)\n ->setStringValue(forest->texture);\n effect = makeEffect(effectProp, true, options);\n if (iter == treeEffectMap.end())\n treeEffectMap.insert(EffectMap::value_type(forest->texture, effect));\n else\n iter->second = effect; \/\/ update existing, but empty observer\n }\n\n \/\/ Now, create a quadtree for the forest.\n ShaderGeometryQuadtree\n quadtree(GetTreeCoord(), AddTreesLeafObject(),\n SG_TREE_QUAD_TREE_DEPTH,\n MakeTreesLeaf(forest->range, forest->texture_varieties,\n forest->width, forest->height, effect));\n \/\/ Transform tree positions from the \"geocentric\" positions we\n \/\/ get from the scenery polys into the local Z-up coordinate\n \/\/ system.\n std::vector<TreeBin::Tree> rotatedTrees;\n rotatedTrees.reserve(forest->_trees.size());\n std::transform(forest->_trees.begin(), forest->_trees.end(),\n std::back_inserter(rotatedTrees),\n TreeTransformer(transInv));\n quadtree.buildQuadTree(rotatedTrees.begin(), rotatedTrees.end());\n group = quadtree.getRoot();\n\n for (size_t i = 0; i < group->getNumChildren(); ++i)\n mt->addChild(group->getChild(i));\n \n delete forest;\n }\n \n forestList.clear();\n QuadTreeCleaner cleaner;\n mt->accept(cleaner);\n return mt;\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ screen-dump.cxx -- dump a copy of the opengl screen buffer to a file\n\/\/\n\/\/ Contributed by Richard Kaszeta <bofh@me.umn.edu>, started October 1999.\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 General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\/\/\n\/\/ $Id$\n\n\n#ifdef HAVE_CONFIG_H\n# include <simgear_config.h>\n#endif\n\n#if defined(__CYGWIN__) \/* && !defined(USING_X) *\/\n#define WIN32\n#endif\n\n#if defined(WIN32) \/* MINGW and MSC predefine WIN32 *\/\n# include <windows.h>\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n\n#include <simgear\/compiler.h>\n\n#include SG_GL_H\n\n#include \"screen-dump.hxx\"\n\n\n#define RGB3 3\t\t\t\/\/ 3 bytes of color info per pixel\n#define RGBA 4\t\t\t\/\/ 4 bytes of color+alpha info\n\nbool sg_glWritePPMFile(const char *filename, GLubyte *buffer, int win_width, int win_height, int mode)\n{\n int i, j, k, q;\n unsigned char *ibuffer;\n FILE *fp;\n int pixelSize = mode==GL_RGBA?4:3;\n\n ibuffer = (unsigned char *) malloc(win_width*win_height*RGB3);\n\n if ( (fp = fopen(filename, \"wb\")) == NULL ) {\n\tprintf(\"Warning: cannot open %s\\n\", filename);\n\treturn false;\n }\n\n fprintf(fp, \"P6\\n# CREATOR: glReadPixel()\\n%d %d\\n%d\\n\",\n\t win_width, win_height, UCHAR_MAX);\n q = 0;\n for (i = 0; i < win_height; i++)\n\tfor (j = 0; j < win_width; j++)\n\t for (k = 0; k < RGB3; k++)\n\t\tibuffer[q++] = (unsigned char)\n\t\t *(buffer + (pixelSize*((win_height-1-i)*win_width+j)+k));\n fwrite(ibuffer, sizeof(unsigned char), RGB3*win_width*win_height, fp);\n fclose(fp);\n free(ibuffer);\n\n printf(\"wrote file (%d x %d pixels, %d bytes)\\n\",\n\t win_width, win_height, RGB3*win_width*win_height);\n return true;\n}\n\n\n\/\/ dump the screen buffer to a ppm file\nbool sg_glDumpWindow(const char *filename, int win_width, int win_height) {\n GLubyte *buffer;\n bool result;\n\n buffer = (GLubyte *) malloc(win_width*win_height*RGBA);\n\n \/\/ read window contents from color buffer with glReadPixels\n glFinish();\n glReadPixels(0, 0, win_width, win_height, \n\t\t GL_RGBA, GL_UNSIGNED_BYTE, buffer);\n result = sg_glWritePPMFile( filename, buffer, win_width, win_height,\n\t\t\t\tGL_RGBA );\n free(buffer);\n\n return result;\n}\n\n<commit_msg>Nick WARNE: add file name to screenshot info line<commit_after>\/\/ screen-dump.cxx -- dump a copy of the opengl screen buffer to a file\n\/\/\n\/\/ Contributed by Richard Kaszeta <bofh@me.umn.edu>, started October 1999.\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 General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\/\/\n\/\/ $Id$\n\n\n#ifdef HAVE_CONFIG_H\n# include <simgear_config.h>\n#endif\n\n#if defined(__CYGWIN__) \/* && !defined(USING_X) *\/\n#define WIN32\n#endif\n\n#if defined(WIN32) \/* MINGW and MSC predefine WIN32 *\/\n# include <windows.h>\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n\n#include <simgear\/compiler.h>\n\n#include SG_GL_H\n\n#include \"screen-dump.hxx\"\n\n\n#define RGB3 3\t\t\t\/\/ 3 bytes of color info per pixel\n#define RGBA 4\t\t\t\/\/ 4 bytes of color+alpha info\n\nbool sg_glWritePPMFile(const char *filename, GLubyte *buffer, int win_width, int win_height, int mode)\n{\n int i, j, k, q;\n unsigned char *ibuffer;\n FILE *fp;\n int pixelSize = mode==GL_RGBA?4:3;\n\n ibuffer = (unsigned char *) malloc(win_width*win_height*RGB3);\n\n if ( (fp = fopen(filename, \"wb\")) == NULL ) {\n\tprintf(\"Warning: cannot open %s\\n\", filename);\n\treturn false;\n }\n\n fprintf(fp, \"P6\\n# CREATOR: glReadPixel()\\n%d %d\\n%d\\n\",\n\t win_width, win_height, UCHAR_MAX);\n q = 0;\n for (i = 0; i < win_height; i++)\n\tfor (j = 0; j < win_width; j++)\n\t for (k = 0; k < RGB3; k++)\n\t\tibuffer[q++] = (unsigned char)\n\t\t *(buffer + (pixelSize*((win_height-1-i)*win_width+j)+k));\n fwrite(ibuffer, sizeof(unsigned char), RGB3*win_width*win_height, fp);\n fclose(fp);\n free(ibuffer);\n\n printf(\"wrote file '%s' (%d x %d pixels, %d bytes)\\n\",\n\t filename, win_width, win_height, RGB3*win_width*win_height);\n return true;\n}\n\n\n\/\/ dump the screen buffer to a ppm file\nbool sg_glDumpWindow(const char *filename, int win_width, int win_height) {\n GLubyte *buffer;\n bool result;\n\n buffer = (GLubyte *) malloc(win_width*win_height*RGBA);\n\n \/\/ read window contents from color buffer with glReadPixels\n glFinish();\n glReadPixels(0, 0, win_width, win_height, \n\t\t GL_RGBA, GL_UNSIGNED_BYTE, buffer);\n result = sg_glWritePPMFile( filename, buffer, win_width, win_height,\n\t\t\t\tGL_RGBA );\n free(buffer);\n\n return result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"TaskIcon.h\"\r\n#include <cmath>\r\n\r\nconst UINT icon_id = 100;\r\nconst UINT id_exit = 101;\r\n\r\nstatic const wchar_t *const icon_label = L\"Xbox Controller Battery Level\";\r\nstatic const wchar_t *const task_class = L\"xinput-batlev_task-icon\";\r\nstatic const wchar_t icon_emoji[] = L\"🎮\";\r\nstatic std::atomic<size_t> task_refcount = 0;\r\n\r\nTaskIcon::TaskIcon()\r\n : icon_(128, 128, 2)\r\n{\r\n RegClass();\r\n hwnd_ = CreateWindowExW(\r\n 0, task_class, icon_label,\r\n 0, 0, 0, 0, 0, nullptr,\r\n nullptr, hinstance, this\r\n );\r\n\r\n menu_ = CreatePopupMenu();\r\n if (!menu_) CheckLastError();\r\n\r\n MENUINFO menuinfo = { sizeof(menuinfo) };\r\n menuinfo.fMask = MIM_STYLE;\r\n menuinfo.dwStyle = MNS_AUTODISMISS;\r\n SetMenuInfo(menu_, &menuinfo);\r\n\r\n InsertMenuW(menu_, 0, MF_BYPOSITION, id_exit, L\"Exit\");\r\n\r\n CheckHR(DWriteCreateFactory(\r\n DWRITE_FACTORY_TYPE_SHARED,\r\n __uuidof(*dwrite_),\r\n (IUnknown **)&dwrite_)\r\n );\r\n\r\n CheckHR(dwrite_->CreateTextFormat(\r\n L\"Segoe UI Emoji\",\r\n nullptr,\r\n DWRITE_FONT_WEIGHT_NORMAL,\r\n DWRITE_FONT_STYLE_NORMAL,\r\n DWRITE_FONT_STRETCH_NORMAL,\r\n 42,\r\n L\"en-US\",\r\n &font_\r\n ));\r\n\r\n NOTIFYICONDATAW idata = { sizeof(idata) };\r\n idata.hWnd = hwnd_;\r\n idata.uID = icon_id;\r\n idata.uVersion = NOTIFYICON_VERSION_4;\r\n idata.uCallbackMessage = WM_TASKICON;\r\n idata.hIcon = MakeIcon(false);\r\n idata.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;\r\n wcscpy_s(idata.szTip, icon_label);\r\n Shell_NotifyIconW(NIM_ADD, &idata);\r\n}\r\n\r\nTaskIcon::~TaskIcon()\r\n{\r\n NOTIFYICONDATAW idata = { sizeof(idata) };\r\n idata.hWnd = hwnd_;\r\n idata.uID = icon_id;\r\n Shell_NotifyIconW(NIM_DELETE, &idata);\r\n\r\n if (menu_)\r\n DestroyMenu(menu_);\r\n if (hwnd_)\r\n DestroyWindow(hwnd_);\r\n UnregClass();\r\n}\r\n\r\nvoid TaskIcon::MessageLoop()\r\n{\r\n \/\/ Recheck once every 5 seconds\r\n SetTimer(hwnd_, icon_id, 5 * 1000, nullptr);\r\n\r\n \/\/ Initial update\r\n UpdateIcon();\r\n\r\n MSG msg;\r\n while (GetMessageW(&msg, hwnd_, 0, 0))\r\n {\r\n TranslateMessage(&msg);\r\n DispatchMessageW(&msg);\r\n\r\n if (stop_)\r\n {\r\n break;\r\n }\r\n }\r\n}\r\n\r\nvoid TaskIcon::Stop()\r\n{\r\n stop_ = true;\r\n}\r\n\r\nLRESULT TaskIcon::StaticWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)\r\n{\r\n if (msg == WM_CREATE)\r\n {\r\n auto cdata = (CREATESTRUCTW *)lparam;\r\n SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR)cdata->lpCreateParams);\r\n return 0;\r\n }\r\n\r\n auto task_ptr = (TaskIcon *)GetWindowLongPtrW(hwnd, GWLP_USERDATA);\r\n if (task_ptr)\r\n {\r\n return task_ptr->WndProc(msg, wparam, lparam);\r\n }\r\n return DefWindowProcW(hwnd, msg, wparam, lparam);\r\n}\r\n\r\nLRESULT TaskIcon::WndProc(UINT msg, WPARAM wparam, LPARAM lparam)\r\n{\r\n switch (msg)\r\n {\r\n case WM_TIMER:\r\n {\r\n UpdateIcon();\r\n return 0;\r\n }\r\n case WM_TASKICON:\r\n {\r\n if (LOWORD(lparam) == WM_RBUTTONUP)\r\n {\r\n POINT cpos;\r\n GetCursorPos(&cpos);\r\n\r\n SetForegroundWindow(hwnd_);\r\n TrackPopupMenuEx(\r\n menu_,\r\n TPM_BOTTOMALIGN | TPM_LEFTALIGN,\r\n cpos.x, cpos.y,\r\n hwnd_,\r\n nullptr\r\n );\r\n }\r\n return 0;\r\n }\r\n case WM_COMMAND:\r\n {\r\n if (wparam == id_exit)\r\n {\r\n stop_ = true;\r\n }\r\n return 0;\r\n }\r\n }\r\n\r\n return DefWindowProcW(hwnd_, msg, wparam, lparam);\r\n}\r\n\r\nvoid TaskIcon::UpdateIcon()\r\n{\r\n XINPUT_BATTERY_INFORMATION info;\r\n if (XInputGetBatteryInformation(0, BATTERY_DEVTYPE_GAMEPAD, &info) != ERROR_SUCCESS)\r\n {\r\n info.BatteryType = BATTERY_TYPE_DISCONNECTED;\r\n }\r\n\r\n switch (info.BatteryType)\r\n {\r\n case BATTERY_TYPE_WIRED:\r\n batlevel_ = 1;\r\n nocontroller_ = false;\r\n unknown_ = false;\r\n break;\r\n\r\n case BATTERY_TYPE_ALKALINE:\r\n case BATTERY_TYPE_NIMH:\r\n switch (info.BatteryLevel)\r\n {\r\n case BATTERY_LEVEL_EMPTY:\r\n batlevel_ = 0;\r\n break;\r\n case BATTERY_LEVEL_LOW:\r\n batlevel_ = 0.3f;\r\n break;\r\n case BATTERY_LEVEL_MEDIUM:\r\n batlevel_ = 0.6f;\r\n break;\r\n case BATTERY_LEVEL_FULL:\r\n batlevel_ = 1;\r\n break;\r\n }\r\n nocontroller_ = false;\r\n unknown_ = false;\r\n break;\r\n\r\n case BATTERY_TYPE_UNKNOWN:\r\n batlevel_ = 0;\r\n nocontroller_ = false;\r\n unknown_ = true;\r\n\r\n case BATTERY_TYPE_DISCONNECTED:\r\n default:\r\n batlevel_ = 0;\r\n nocontroller_ = true;\r\n unknown_ = false;\r\n break;\r\n }\r\n\r\n NOTIFYICONDATAW idata = { sizeof(idata) };\r\n idata.hWnd = hwnd_;\r\n idata.uID = icon_id;\r\n idata.hIcon = MakeIcon(true);\r\n idata.uFlags = NIF_ICON;\r\n Shell_NotifyIconW(NIM_MODIFY, &idata);\r\n}\r\n\r\nHICON TaskIcon::MakeIcon(bool redraw)\r\n{\r\n auto icon = icon_.GetIcon();\r\n if (!icon || redraw)\r\n {\r\n ComPtr<ID2D1RenderTarget> target;\r\n icon_.Lock(&target);\r\n\r\n target->BeginDraw();\r\n target->Clear();\r\n\r\n auto size = target->GetSize();\r\n auto batrect = D2D1::RectF(5, size.height \/ 2 - 16, size.width - 8, size.height \/ 2 + 16);\r\n auto posend = D2D1::RectF(size.width - 8, size.height \/ 2 - 8, size.width, size.height \/ 2 + 8);\r\n auto fillrect = D2D1::RectF(batrect.left + 5, batrect.top + 5, batrect.right - 5, batrect.bottom - 5);\r\n fillrect.right = (1 - batlevel_) * fillrect.left + batlevel_ * fillrect.right;\r\n\r\n ComPtr<ID2D1SolidColorBrush> brush;\r\n CheckHR(target->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &brush));\r\n\r\n target->DrawRectangle(batrect, brush, 5);\r\n target->FillRectangle(posend, brush);\r\n target->FillRectangle(fillrect, brush);\r\n\r\n target->DrawText(\r\n icon_emoji,\r\n ARRAYSIZE(icon_emoji) - 1,\r\n font_,\r\n D2D1::RectF(\r\n size.width \/ 3,\r\n size.height \/ 4.f,\r\n size.width,\r\n size.height\r\n ),\r\n brush,\r\n D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT\r\n );\r\n\r\n if (nocontroller_)\r\n {\r\n ComPtr<ID2D1SolidColorBrush> errbrush;\r\n CheckHR(target->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &errbrush));\r\n auto center = D2D1::Point2F(16, size.height \/ 2 + 16);\r\n auto radiusx = std::sqrtf(2) * 7;\r\n auto tl = D2D1::Point2F(center.x - radiusx, center.y - radiusx);\r\n auto tr = D2D1::Point2F(center.x + radiusx, center.y - radiusx);\r\n auto bl = D2D1::Point2F(center.x - radiusx, center.y + radiusx);\r\n auto br = D2D1::Point2F(center.x + radiusx, center.y + radiusx);\r\n\r\n target->FillEllipse(\r\n D2D1::Ellipse(\r\n center,\r\n 16, 16\r\n ),\r\n errbrush\r\n );\r\n target->DrawLine(tl, br, brush, 5);\r\n target->DrawLine(tr, bl, brush, 5);\r\n }\r\n\r\n CheckHR(target->EndDraw());\r\n\r\n icon_.Unlock();\r\n icon = icon_.GetIcon();\r\n }\r\n return icon;\r\n}\r\n\r\nvoid TaskIcon::RegClass()\r\n{\r\n if (task_refcount++)\r\n return;\r\n\r\n WNDCLASSEXW wndc = { sizeof(wndc) };\r\n wndc.cbWndExtra = sizeof(TaskIcon *);\r\n wndc.hInstance = hinstance;\r\n wndc.lpfnWndProc = TaskIcon::StaticWndProc;\r\n wndc.lpszClassName = task_class;\r\n RegisterClassExW(&wndc);\r\n}\r\n\r\nvoid TaskIcon::UnregClass()\r\n{\r\n if (--task_refcount)\r\n return;\r\n\r\n UnregisterClassW(task_class, hinstance);\r\n}\r\n<commit_msg>Adds tooltip<commit_after>#include \"TaskIcon.h\"\r\n#include <cmath>\r\n\r\nconst UINT icon_id = 100;\r\nconst UINT id_exit = 101;\r\n\r\nstatic const wchar_t *const icon_label = L\"Xbox Controller Battery Level\";\r\nstatic const wchar_t *const task_class = L\"xinput-batlev_task-icon\";\r\nstatic const wchar_t icon_emoji[] = L\"🎮\";\r\nstatic std::atomic<size_t> task_refcount = 0;\r\n\r\nTaskIcon::TaskIcon()\r\n : icon_(128, 128, 2)\r\n{\r\n RegClass();\r\n hwnd_ = CreateWindowExW(\r\n 0, task_class, icon_label,\r\n 0, 0, 0, 0, 0, nullptr,\r\n nullptr, hinstance, this\r\n );\r\n\r\n menu_ = CreatePopupMenu();\r\n if (!menu_) CheckLastError();\r\n\r\n MENUINFO menuinfo = { sizeof(menuinfo) };\r\n menuinfo.fMask = MIM_STYLE;\r\n menuinfo.dwStyle = MNS_AUTODISMISS;\r\n SetMenuInfo(menu_, &menuinfo);\r\n\r\n InsertMenuW(menu_, 0, MF_BYPOSITION, id_exit, L\"Exit\");\r\n\r\n CheckHR(DWriteCreateFactory(\r\n DWRITE_FACTORY_TYPE_SHARED,\r\n __uuidof(*dwrite_),\r\n (IUnknown **)&dwrite_)\r\n );\r\n\r\n CheckHR(dwrite_->CreateTextFormat(\r\n L\"Segoe UI Emoji\",\r\n nullptr,\r\n DWRITE_FONT_WEIGHT_NORMAL,\r\n DWRITE_FONT_STYLE_NORMAL,\r\n DWRITE_FONT_STRETCH_NORMAL,\r\n 42,\r\n L\"en-US\",\r\n &font_\r\n ));\r\n\r\n NOTIFYICONDATAW idata = { sizeof(idata) };\r\n idata.hWnd = hwnd_;\r\n idata.uID = icon_id;\r\n idata.uVersion = NOTIFYICON_VERSION_4;\r\n idata.uCallbackMessage = WM_TASKICON;\r\n idata.hIcon = MakeIcon(false);\r\n idata.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;\r\n wcscpy_s(idata.szTip, icon_label);\r\n Shell_NotifyIconW(NIM_ADD, &idata);\r\n}\r\n\r\nTaskIcon::~TaskIcon()\r\n{\r\n NOTIFYICONDATAW idata = { sizeof(idata) };\r\n idata.hWnd = hwnd_;\r\n idata.uID = icon_id;\r\n Shell_NotifyIconW(NIM_DELETE, &idata);\r\n\r\n if (menu_)\r\n DestroyMenu(menu_);\r\n if (hwnd_)\r\n DestroyWindow(hwnd_);\r\n UnregClass();\r\n}\r\n\r\nvoid TaskIcon::MessageLoop()\r\n{\r\n \/\/ Recheck once every 5 seconds\r\n SetTimer(hwnd_, icon_id, 5 * 1000, nullptr);\r\n\r\n \/\/ Initial update\r\n UpdateIcon();\r\n\r\n MSG msg;\r\n while (GetMessageW(&msg, hwnd_, 0, 0))\r\n {\r\n TranslateMessage(&msg);\r\n DispatchMessageW(&msg);\r\n\r\n if (stop_)\r\n {\r\n break;\r\n }\r\n }\r\n}\r\n\r\nvoid TaskIcon::Stop()\r\n{\r\n stop_ = true;\r\n}\r\n\r\nLRESULT TaskIcon::StaticWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)\r\n{\r\n if (msg == WM_CREATE)\r\n {\r\n auto cdata = (CREATESTRUCTW *)lparam;\r\n SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR)cdata->lpCreateParams);\r\n return 0;\r\n }\r\n\r\n auto task_ptr = (TaskIcon *)GetWindowLongPtrW(hwnd, GWLP_USERDATA);\r\n if (task_ptr)\r\n {\r\n return task_ptr->WndProc(msg, wparam, lparam);\r\n }\r\n return DefWindowProcW(hwnd, msg, wparam, lparam);\r\n}\r\n\r\nLRESULT TaskIcon::WndProc(UINT msg, WPARAM wparam, LPARAM lparam)\r\n{\r\n switch (msg)\r\n {\r\n case WM_TIMER:\r\n {\r\n UpdateIcon();\r\n return 0;\r\n }\r\n case WM_TASKICON:\r\n {\r\n if (LOWORD(lparam) == WM_RBUTTONUP)\r\n {\r\n POINT cpos;\r\n GetCursorPos(&cpos);\r\n\r\n SetForegroundWindow(hwnd_);\r\n TrackPopupMenuEx(\r\n menu_,\r\n TPM_BOTTOMALIGN | TPM_LEFTALIGN,\r\n cpos.x, cpos.y,\r\n hwnd_,\r\n nullptr\r\n );\r\n }\r\n return 0;\r\n }\r\n case WM_COMMAND:\r\n {\r\n if (wparam == id_exit)\r\n {\r\n stop_ = true;\r\n }\r\n return 0;\r\n }\r\n }\r\n\r\n return DefWindowProcW(hwnd_, msg, wparam, lparam);\r\n}\r\n\r\nvoid TaskIcon::UpdateIcon()\r\n{\r\n XINPUT_BATTERY_INFORMATION info;\r\n if (XInputGetBatteryInformation(0, BATTERY_DEVTYPE_GAMEPAD, &info) != ERROR_SUCCESS)\r\n {\r\n info.BatteryType = BATTERY_TYPE_DISCONNECTED;\r\n }\r\n\r\n wchar_t *tip = L\"\";\r\n switch (info.BatteryType)\r\n {\r\n case BATTERY_TYPE_WIRED:\r\n batlevel_ = 1;\r\n nocontroller_ = false;\r\n unknown_ = false;\r\n break;\r\n\r\n case BATTERY_TYPE_ALKALINE:\r\n case BATTERY_TYPE_NIMH:\r\n switch (info.BatteryLevel)\r\n {\r\n case BATTERY_LEVEL_EMPTY:\r\n batlevel_ = 0;\r\n tip = L\"Controller battery is empty\";\r\n break;\r\n case BATTERY_LEVEL_LOW:\r\n batlevel_ = 0.3f;\r\n tip = L\"Controller battery is getting low\";\r\n break;\r\n case BATTERY_LEVEL_MEDIUM:\r\n batlevel_ = 0.6f;\r\n tip = L\"Controller battery is OK\";\r\n break;\r\n case BATTERY_LEVEL_FULL:\r\n batlevel_ = 1;\r\n tip = L\"Controller battery is full\";\r\n break;\r\n }\r\n nocontroller_ = false;\r\n unknown_ = false;\r\n break;\r\n\r\n case BATTERY_TYPE_UNKNOWN:\r\n batlevel_ = 0;\r\n nocontroller_ = false;\r\n unknown_ = true;\r\n tip = L\"Battery level couldn't be read\";\r\n\r\n case BATTERY_TYPE_DISCONNECTED:\r\n default:\r\n batlevel_ = 0;\r\n nocontroller_ = true;\r\n unknown_ = false;\r\n tip = L\"No controller connected\";\r\n break;\r\n }\r\n\r\n\r\n NOTIFYICONDATAW idata = { sizeof(idata) };\r\n idata.hWnd = hwnd_;\r\n idata.uID = icon_id;\r\n idata.hIcon = MakeIcon(true);\r\n idata.uFlags = NIF_ICON | NIF_TIP;\r\n swprintf_s(idata.szTip, tip);\r\n \r\n Shell_NotifyIconW(NIM_MODIFY, &idata);\r\n}\r\n\r\nHICON TaskIcon::MakeIcon(bool redraw)\r\n{\r\n auto icon = icon_.GetIcon();\r\n if (!icon || redraw)\r\n {\r\n ComPtr<ID2D1RenderTarget> target;\r\n icon_.Lock(&target);\r\n\r\n target->BeginDraw();\r\n target->Clear();\r\n\r\n auto size = target->GetSize();\r\n auto batrect = D2D1::RectF(5, size.height \/ 2 - 16, size.width - 8, size.height \/ 2 + 16);\r\n auto posend = D2D1::RectF(size.width - 8, size.height \/ 2 - 8, size.width, size.height \/ 2 + 8);\r\n auto fillrect = D2D1::RectF(batrect.left + 5, batrect.top + 5, batrect.right - 5, batrect.bottom - 5);\r\n fillrect.right = (1 - batlevel_) * fillrect.left + batlevel_ * fillrect.right;\r\n\r\n ComPtr<ID2D1SolidColorBrush> brush;\r\n CheckHR(target->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &brush));\r\n\r\n target->DrawRectangle(batrect, brush, 5);\r\n target->FillRectangle(posend, brush);\r\n target->FillRectangle(fillrect, brush);\r\n\r\n target->DrawText(\r\n icon_emoji,\r\n ARRAYSIZE(icon_emoji) - 1,\r\n font_,\r\n D2D1::RectF(\r\n size.width \/ 3,\r\n size.height \/ 4.f,\r\n size.width,\r\n size.height\r\n ),\r\n brush,\r\n D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT\r\n );\r\n\r\n if (nocontroller_)\r\n {\r\n ComPtr<ID2D1SolidColorBrush> errbrush;\r\n CheckHR(target->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &errbrush));\r\n auto center = D2D1::Point2F(16, size.height \/ 2 + 16);\r\n auto radiusx = std::sqrtf(2) * 7;\r\n auto tl = D2D1::Point2F(center.x - radiusx, center.y - radiusx);\r\n auto tr = D2D1::Point2F(center.x + radiusx, center.y - radiusx);\r\n auto bl = D2D1::Point2F(center.x - radiusx, center.y + radiusx);\r\n auto br = D2D1::Point2F(center.x + radiusx, center.y + radiusx);\r\n\r\n target->FillEllipse(\r\n D2D1::Ellipse(\r\n center,\r\n 16, 16\r\n ),\r\n errbrush\r\n );\r\n target->DrawLine(tl, br, brush, 5);\r\n target->DrawLine(tr, bl, brush, 5);\r\n }\r\n\r\n CheckHR(target->EndDraw());\r\n\r\n icon_.Unlock();\r\n icon = icon_.GetIcon();\r\n }\r\n return icon;\r\n}\r\n\r\nvoid TaskIcon::RegClass()\r\n{\r\n if (task_refcount++)\r\n return;\r\n\r\n WNDCLASSEXW wndc = { sizeof(wndc) };\r\n wndc.cbWndExtra = sizeof(TaskIcon *);\r\n wndc.hInstance = hinstance;\r\n wndc.lpfnWndProc = TaskIcon::StaticWndProc;\r\n wndc.lpszClassName = task_class;\r\n RegisterClassExW(&wndc);\r\n}\r\n\r\nvoid TaskIcon::UnregClass()\r\n{\r\n if (--task_refcount)\r\n return;\r\n\r\n UnregisterClassW(task_class, hinstance);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"Corners.h\"\n#include \"TilesetGenerator.h\"\n#include \"TileGenerator.h\"\n#include <functional>\n#include <stdexcept>\n#include <sstream>\n#include <boost\/filesystem.hpp>\n#include \"common.h\"\n\nnamespace tilegen\n{\n\nTilesetGenerator::TilesetGenerator(const Options& options,\n std::unique_ptr<partition::TilePartitionerBase> tile_partitioner) :\n options(options),\n mTilePartitioner(std::move(tile_partitioner))\n{\n for (auto& terrain : options.terrains)\n {\n images.addTerrain(terrain.first, terrain.second.fileName, options.filename,\n terrain.second.offsetX, terrain.second.offsetY, options.tileFormat.resolution);\n }\n}\n\nvoid TilesetGenerator::generate(std::function<void(const sf::Texture&, std::string)> callback)\n{\n mo.setResolution(options.tileFormat.resolution);\n boost::filesystem::path p(options.relativeOutputDirectory);\n for (const auto& clique : options.cliques)\n {\n CornersGenerator cp(clique, static_cast<size_t>(CORNERS));\n std::pair<size_t, size_t> tileset_resolution = cp.size_2d(options.tileFormat.resolution);\n size_t res_x = tileset_resolution.first;\n size_t res_y = tileset_resolution.second;\n std::unique_ptr<sf::RenderTexture> output{getBlankImage(res_x, res_y)};\n\n auto filename = getOutputImageFilename(clique);\n\n \/\/ MetaOutput.addTileset, addTile should use this version of filename;\n \/\/ relative to output dir, not options dir!\n mo.addTileset(clique, filename, res_x, res_y);\n generateClique(clique, *output, filename);\n output->display();\n\n p.append(filename);\n callback(output->getTexture(), p.string());\n p.remove_filename();\n }\n}\n\nvoid TilesetGenerator::generateClique(const Options::Clique& clique, sf::RenderTexture& image, std::string filename)\n{\n CornersGenerator cp(clique, static_cast<size_t>(CORNERS));\n for (auto it = cp.cbegin(); it != cp.cend(); ++it)\n {\n const auto& corner_terrains = *it;\n std::pair<size_t, size_t> tp = it.coordinates_2d();\n TileGenerator::generate(image, tp.first, tp.second, corner_terrains,\n images, options, *mTilePartitioner.get());\n mo.addTile(corner_terrains, filename,\n tp.first*options.tileFormat.resolution,\n tp.second*options.tileFormat.resolution);\n }\n}\n\nstd::string TilesetGenerator::getOutputImageFilename(const Options::Clique& clique) const\n{\n std::stringstream ss;\n for (auto terrain : clique)\n {\n ss << terrain << \".\";\n }\n ss << options.tileFormat.fileType;\n return ss.str();\n}\n\nstd::unique_ptr<sf::RenderTexture> TilesetGenerator::getBlankImage(size_t res_x, size_t res_y) const\n{\n std::unique_ptr<sf::RenderTexture> output{std::make_unique<sf::RenderTexture>()};\n output->create(res_x, res_y);\n output->clear(sf::Color(0,0,0,255));\n return output;\n}\n\n} \/\/ namespace tilegen\n<commit_msg>Use clearer names in TilesetGenerator<commit_after>#include \"Corners.h\"\n#include \"TilesetGenerator.h\"\n#include \"TileGenerator.h\"\n#include <functional>\n#include <stdexcept>\n#include <sstream>\n#include <boost\/filesystem.hpp>\n#include \"common.h\"\n\nnamespace tilegen\n{\n\nTilesetGenerator::TilesetGenerator(const Options& options,\n std::unique_ptr<partition::TilePartitionerBase> tile_partitioner) :\n options(options),\n mTilePartitioner(std::move(tile_partitioner))\n{\n for (auto& terrain : options.terrains)\n {\n images.addTerrain(terrain.first, terrain.second.fileName, options.filename,\n terrain.second.offsetX, terrain.second.offsetY, options.tileFormat.resolution);\n }\n}\n\nvoid TilesetGenerator::generate(std::function<void(const sf::Texture&, std::string)> callback)\n{\n mo.setResolution(options.tileFormat.resolution);\n boost::filesystem::path p(options.relativeOutputDirectory);\n for (const auto& clique : options.cliques)\n {\n CornersGenerator corners_generator(clique, static_cast<size_t>(CORNERS));\n std::pair<size_t, size_t> tileset_resolution = corners_generator.size_2d(options.tileFormat.resolution);\n size_t res_x = tileset_resolution.first;\n size_t res_y = tileset_resolution.second;\n std::unique_ptr<sf::RenderTexture> output{getBlankImage(res_x, res_y)};\n\n auto filename = getOutputImageFilename(clique);\n\n \/\/ MetaOutput.addTileset, addTile should use this version of filename;\n \/\/ relative to output dir, not options dir!\n mo.addTileset(clique, filename, res_x, res_y);\n generateClique(clique, *output, filename);\n output->display();\n\n p.append(filename);\n callback(output->getTexture(), p.string());\n p.remove_filename();\n }\n}\n\nvoid TilesetGenerator::generateClique(const Options::Clique& clique, sf::RenderTexture& image, std::string filename)\n{\n CornersGenerator cp(clique, static_cast<size_t>(CORNERS));\n for (auto it = cp.cbegin(); it != cp.cend(); ++it)\n {\n const auto& corner_terrains = *it;\n std::pair<size_t, size_t> tile_position = it.coordinates_2d();\n TileGenerator::generate(image, tile_position.first, tile_position.second, corner_terrains,\n images, options, *mTilePartitioner.get());\n mo.addTile(corner_terrains, filename,\n tile_position.first*options.tileFormat.resolution,\n tile_position.second*options.tileFormat.resolution);\n }\n}\n\nstd::string TilesetGenerator::getOutputImageFilename(const Options::Clique& clique) const\n{\n std::stringstream ss;\n for (auto terrain : clique)\n {\n ss << terrain << \".\";\n }\n ss << options.tileFormat.fileType;\n return ss.str();\n}\n\nstd::unique_ptr<sf::RenderTexture> TilesetGenerator::getBlankImage(size_t res_x, size_t res_y) const\n{\n std::unique_ptr<sf::RenderTexture> output{std::make_unique<sf::RenderTexture>()};\n output->create(res_x, res_y);\n output->clear(sf::Color(0,0,0,255));\n return output;\n}\n\n} \/\/ namespace tilegen\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Arg.cpp - Argument Implementations -----------------------------*-===\/\/\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#include \"clang\/Driver\/Arg.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/Option.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang::driver;\n\nArg::Arg(ArgClass _Kind, const Option *_Opt, unsigned _Index) \n : Kind(_Kind),\n Opt(_Opt),\n Index(_Index),\n Claimed(false)\n{\n}\n\nArg::~Arg() { }\n\nvoid Arg::dump() const {\n llvm::errs() << \"<\";\n switch (Kind) {\n default:\n assert(0 && \"Invalid kind\");\n#define P(N) case N: llvm::errs() << #N; break\n P(FlagClass);\n P(PositionalClass);\n P(JoinedClass);\n P(SeparateClass);\n P(CommaJoinedClass);\n P(JoinedAndSeparateClass);\n#undef P\n }\n\n llvm::errs() << \" Opt:\";\n Opt->dump();\n\n llvm::errs() << \" Index:\" << Index;\n\n if (isa<CommaJoinedArg>(this) || isa<SeparateArg>(this))\n llvm::errs() << \" NumValues:\" << getNumValues();\n\n llvm::errs() << \">\\n\";\n}\n\nFlagArg::FlagArg(const Option *Opt, unsigned Index)\n : Arg(FlagClass, Opt, Index) {\n}\n\nvoid FlagArg::render(const ArgList &Args, ArgStringList &Output) const {\n assert(0 && \"FIXME: Implement\");\n}\n\nconst char *FlagArg::getValue(const ArgList &Args, unsigned N) const {\n assert(0 && \"Invalid index.\");\n return 0;\n}\n\nPositionalArg::PositionalArg(const Option *Opt, unsigned Index)\n : Arg(PositionalClass, Opt, Index) {\n}\n\nvoid PositionalArg::render(const ArgList &Args, ArgStringList &Output) const {\n assert(0 && \"FIXME: Implement\");\n}\n\nconst char *PositionalArg::getValue(const ArgList &Args, unsigned N) const {\n assert(N < getNumValues() && \"Invalid index.\");\n return Args.getArgString(getIndex());\n}\n\nJoinedArg::JoinedArg(const Option *Opt, unsigned Index)\n : Arg(JoinedClass, Opt, Index) {\n}\n\nvoid JoinedArg::render(const ArgList &Args, ArgStringList &Output) const {\n assert(0 && \"FIXME: Implement\");\n}\n\nconst char *JoinedArg::getValue(const ArgList &Args, unsigned N) const {\n assert(N < getNumValues() && \"Invalid index.\");\n \/\/ FIXME: Avoid strlen.\n return Args.getArgString(getIndex()) + strlen(getOption().getName());\n}\n\nCommaJoinedArg::CommaJoinedArg(const Option *Opt, unsigned Index, \n const char *Str)\n : Arg(CommaJoinedClass, Opt, Index) {\n const char *Prev = Str; \n for (;; ++Str) {\n char c = *Str;\n\n if (!c) {\n if (Prev != Str)\n Values.push_back(std::string(Prev, Str));\n break;\n } else if (c == ',') {\n if (Prev != Str)\n Values.push_back(std::string(Prev, Str));\n Prev = Str + 1;\n }\n }\n}\n\nvoid CommaJoinedArg::render(const ArgList &Args, ArgStringList &Output) const {\n assert(0 && \"FIXME: Implement\");\n}\n\nconst char *CommaJoinedArg::getValue(const ArgList &Args, unsigned N) const {\n assert(N < getNumValues() && \"Invalid index.\");\n return Values[N].c_str();\n}\n\nSeparateArg::SeparateArg(const Option *Opt, unsigned Index, unsigned _NumValues)\n : Arg(SeparateClass, Opt, Index), NumValues(_NumValues) {\n}\n\nvoid SeparateArg::render(const ArgList &Args, ArgStringList &Output) const {\n assert(0 && \"FIXME: Implement\");\n}\n\nconst char *SeparateArg::getValue(const ArgList &Args, unsigned N) const { \n assert(N < getNumValues() && \"Invalid index.\");\n return Args.getArgString(getIndex() + 1 + N);\n}\n\nJoinedAndSeparateArg::JoinedAndSeparateArg(const Option *Opt, unsigned Index)\n : Arg(JoinedAndSeparateClass, Opt, Index) {\n}\n\nvoid JoinedAndSeparateArg::render(const ArgList &Args, \n ArgStringList &Output) const {\n assert(0 && \"FIXME: Implement\");\n}\n\nconst char *JoinedAndSeparateArg::getValue(const ArgList &Args, \n unsigned N) const {\n assert(N < getNumValues() && \"Invalid index.\");\n if (N == 0)\n return Args.getArgString(getIndex()) + strlen(getOption().getName());\n return Args.getArgString(getIndex() + 1);\n}\n<commit_msg>Driver: Provide Arg::render implementations.<commit_after>\/\/===--- Arg.cpp - Argument Implementations -----------------------------*-===\/\/\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#include \"clang\/Driver\/Arg.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/Option.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang::driver;\n\nArg::Arg(ArgClass _Kind, const Option *_Opt, unsigned _Index) \n : Kind(_Kind),\n Opt(_Opt),\n Index(_Index),\n Claimed(false)\n{\n}\n\nArg::~Arg() { }\n\nvoid Arg::dump() const {\n llvm::errs() << \"<\";\n switch (Kind) {\n default:\n assert(0 && \"Invalid kind\");\n#define P(N) case N: llvm::errs() << #N; break\n P(FlagClass);\n P(PositionalClass);\n P(JoinedClass);\n P(SeparateClass);\n P(CommaJoinedClass);\n P(JoinedAndSeparateClass);\n#undef P\n }\n\n llvm::errs() << \" Opt:\";\n Opt->dump();\n\n llvm::errs() << \" Index:\" << Index;\n\n if (isa<CommaJoinedArg>(this) || isa<SeparateArg>(this))\n llvm::errs() << \" NumValues:\" << getNumValues();\n\n llvm::errs() << \">\\n\";\n}\n\nFlagArg::FlagArg(const Option *Opt, unsigned Index)\n : Arg(FlagClass, Opt, Index) {\n}\n\nvoid FlagArg::render(const ArgList &Args, ArgStringList &Output) const {\n Output.push_back(Args.getArgString(getIndex()));\n}\n\nconst char *FlagArg::getValue(const ArgList &Args, unsigned N) const {\n assert(0 && \"Invalid index.\");\n return 0;\n}\n\nPositionalArg::PositionalArg(const Option *Opt, unsigned Index)\n : Arg(PositionalClass, Opt, Index) {\n}\n\nvoid PositionalArg::render(const ArgList &Args, ArgStringList &Output) const {\n Output.push_back(Args.getArgString(getIndex()));\n}\n\nconst char *PositionalArg::getValue(const ArgList &Args, unsigned N) const {\n assert(N < getNumValues() && \"Invalid index.\");\n return Args.getArgString(getIndex());\n}\n\nJoinedArg::JoinedArg(const Option *Opt, unsigned Index)\n : Arg(JoinedClass, Opt, Index) {\n}\n\nvoid JoinedArg::render(const ArgList &Args, ArgStringList &Output) const {\n if (getOption().hasForceSeparateRender()) {\n Output.push_back(getOption().getName());\n Output.push_back(getValue(Args, 0));\n } else {\n Output.push_back(Args.getArgString(getIndex()));\n }\n}\n\nconst char *JoinedArg::getValue(const ArgList &Args, unsigned N) const {\n assert(N < getNumValues() && \"Invalid index.\");\n \/\/ FIXME: Avoid strlen.\n return Args.getArgString(getIndex()) + strlen(getOption().getName());\n}\n\nCommaJoinedArg::CommaJoinedArg(const Option *Opt, unsigned Index, \n const char *Str)\n : Arg(CommaJoinedClass, Opt, Index) {\n const char *Prev = Str; \n for (;; ++Str) {\n char c = *Str;\n\n if (!c) {\n if (Prev != Str)\n Values.push_back(std::string(Prev, Str));\n break;\n } else if (c == ',') {\n if (Prev != Str)\n Values.push_back(std::string(Prev, Str));\n Prev = Str + 1;\n }\n }\n}\n\nvoid CommaJoinedArg::render(const ArgList &Args, ArgStringList &Output) const {\n Output.push_back(Args.getArgString(getIndex()));\n}\n\nconst char *CommaJoinedArg::getValue(const ArgList &Args, unsigned N) const {\n assert(N < getNumValues() && \"Invalid index.\");\n return Values[N].c_str();\n}\n\nSeparateArg::SeparateArg(const Option *Opt, unsigned Index, unsigned _NumValues)\n : Arg(SeparateClass, Opt, Index), NumValues(_NumValues) {\n}\n\nvoid SeparateArg::render(const ArgList &Args, ArgStringList &Output) const {\n if (getOption().hasForceJoinedRender()) {\n assert(getNumValues() == 1 && \"Cannot force joined render with > 1 args.\");\n \/\/ FIXME: Avoid std::string.\n std::string Joined(getOption().getName());\n Joined += Args.getArgString(getIndex());\n Output.push_back(Args.MakeArgString(Joined.c_str()));\n } else {\n Output.push_back(Args.getArgString(getIndex()));\n for (unsigned i = 0; i < NumValues; ++i)\n Output.push_back(Args.getArgString(getIndex() + 1 + i));\n }\n}\n\nconst char *SeparateArg::getValue(const ArgList &Args, unsigned N) const { \n assert(N < getNumValues() && \"Invalid index.\");\n return Args.getArgString(getIndex() + 1 + N);\n}\n\nJoinedAndSeparateArg::JoinedAndSeparateArg(const Option *Opt, unsigned Index)\n : Arg(JoinedAndSeparateClass, Opt, Index) {\n}\n\nvoid JoinedAndSeparateArg::render(const ArgList &Args, \n ArgStringList &Output) const {\n Output.push_back(Args.getArgString(getIndex()));\n Output.push_back(Args.getArgString(getIndex()) + 1);\n}\n\nconst char *JoinedAndSeparateArg::getValue(const ArgList &Args, \n unsigned N) const {\n assert(N < getNumValues() && \"Invalid index.\");\n if (N == 0)\n return Args.getArgString(getIndex()) + strlen(getOption().getName());\n return Args.getArgString(getIndex() + 1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: PyVTKSpecialObject.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"PyVTKSpecialObject.h\"\n#include \"vtkPythonUtil.h\"\n\n#include <vtksys\/ios\/sstream>\n\n\/\/--------------------------------------------------------------------\nPyVTKSpecialType::PyVTKSpecialType(\n char *cname, char *cdocs[], PyMethodDef *cmethods, PyMethodDef *ccons,\n PyVTKSpecialMethods *smethods)\n{\n this->classname = PyString_FromString(cname);\n this->docstring = vtkPythonUtil::BuildDocString(cdocs);\n this->methods = cmethods;\n this->constructors = ccons;\n this->copy_func = smethods->copy_func;\n this->delete_func = smethods->delete_func;\n this->print_func = smethods->print_func;\n this->compare_func = smethods->compare_func;\n this->hash_func = smethods->hash_func;\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyObject *PyVTKSpecialObject_PyString(PyVTKSpecialObject *self)\n{\n vtksys_ios::ostringstream os;\n self->vtk_info->print_func(os, self->vtk_ptr);\n const vtksys_stl::string &s = os.str();\n return PyString_FromStringAndSize(s.data(), s.size());\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyObject *PyVTKSpecialObject_PyRepr(PyVTKSpecialObject *self)\n{\n char buf[255];\n sprintf(buf,\"<%s %s at %p>\", self->ob_type->tp_name,\n PyString_AsString(self->vtk_info->classname), self);\n return PyString_FromString(buf);\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyObject *PyVTKSpecialObject_PyGetAttr(PyVTKSpecialObject *self,\n PyObject *attr)\n{\n char *name = PyString_AsString(attr);\n PyMethodDef *meth;\n\n if (name[0] == '_')\n {\n if (strcmp(name,\"__name__\") == 0)\n {\n Py_INCREF(self->vtk_info->classname);\n return self->vtk_info->classname;\n }\n if (strcmp(name,\"__doc__\") == 0)\n {\n Py_INCREF(self->vtk_info->docstring);\n return self->vtk_info->docstring;\n }\n if (strcmp(name,\"__methods__\") == 0)\n {\n meth = self->vtk_info->methods;\n PyObject *lst;\n int i, n;\n\n for (n = 0; meth && meth[n].ml_name; n++)\n {\n ;\n }\n\n if ((lst = PyList_New(n)) != NULL)\n {\n meth = self->vtk_info->methods;\n for (i = 0; i < n; i++)\n {\n PyList_SetItem(lst, i, PyString_FromString(meth[i].ml_name));\n }\n PyList_Sort(lst);\n }\n return lst;\n }\n\n if (strcmp(name,\"__members__\") == 0)\n {\n PyObject *lst;\n if ((lst = PyList_New(4)) != NULL)\n {\n PyList_SetItem(lst,0,PyString_FromString(\"__doc__\"));\n PyList_SetItem(lst,1,PyString_FromString(\"__members__\"));\n PyList_SetItem(lst,2,PyString_FromString(\"__methods__\"));\n PyList_SetItem(lst,3,PyString_FromString(\"__name__\"));\n }\n return lst;\n }\n }\n\n for (meth = self->vtk_info->methods; meth && meth->ml_name; meth++)\n {\n if (name[0] == meth->ml_name[0] && strcmp(name+1, meth->ml_name+1) == 0)\n {\n return PyCFunction_New(meth, (PyObject *)self);\n }\n }\n\n PyErr_SetString(PyExc_AttributeError, name);\n return NULL;\n}\n\n\/\/--------------------------------------------------------------------\nstatic void PyVTKSpecialObject_PyDelete(PyVTKSpecialObject *self)\n{\n if (self->vtk_ptr)\n {\n self->vtk_info->delete_func(self->vtk_ptr);\n }\n self->vtk_ptr = NULL;\n#if (PY_MAJOR_VERSION >= 2)\n PyObject_Del(self);\n#else\n PyMem_DEL(self);\n#endif\n}\n\n\/\/--------------------------------------------------------------------\nstatic long PyVTKSpecialObject_PyHash(PyVTKSpecialObject *self)\n{\n \/\/ self->vtk_hash must never be set to anything but -1 for mutable objects\n if (self->vtk_hash != -1)\n {\n return self->vtk_hash;\n }\n\n if (self->vtk_ptr && self->vtk_info->hash_func)\n {\n int imm = 0;\n long val = self->vtk_info->hash_func(self->vtk_ptr, &imm);\n if (val != -1)\n {\n if (imm)\n {\n \/\/ cache the hash for immutable objects\n self->vtk_hash = val;\n }\n return val;\n }\n }\n\/\/ python 2.6\n#if PY_VERSION_HEX >= 0x02060000\n return PyObject_HashNotImplemented((PyObject *)self);\n#else\n PyErr_SetString(PyExc_TypeError, (char *)\"object is not hashable\");\n return -1;\n#endif\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyObject *PyVTKSpecialObject_PyRichCompare(\n PyVTKSpecialObject *self, PyVTKSpecialObject *o, int opid)\n{\n if (self->vtk_ptr && self->vtk_info->compare_func)\n {\n int val = self->vtk_info->compare_func(self->vtk_ptr, o->vtk_ptr, opid);\n if (val == 0)\n {\n Py_INCREF(Py_False);\n return Py_False;\n }\n else if (val != -1)\n {\n Py_INCREF(Py_True);\n return Py_True;\n }\n }\n\n PyErr_SetString(PyExc_TypeError, (char *)\"operation not available\");\n return NULL;\n\/\/ Returning \"None\" is also valid, but not as informative\n#if PY_VERSION_HEX >= 0x02010000\n\/\/ Py_INCREF(Py_NotImplemented);\n\/\/ return Py_NotImplemented;\n#else\n\/\/ Py_INCREF(Py_None);\n\/\/ return Py_None;\n#endif\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyTypeObject PyVTKSpecialObjectType = {\n PyObject_HEAD_INIT(&PyType_Type)\n 0,\n (char*)\"vtkspecialobject\", \/\/ tp_name\n sizeof(PyVTKSpecialObject), \/\/ tp_basicsize\n 0, \/\/ tp_itemsize\n (destructor)PyVTKSpecialObject_PyDelete, \/\/ tp_dealloc\n (printfunc)0, \/\/ tp_print\n (getattrfunc)0, \/\/ tp_getattr\n (setattrfunc)0, \/\/ tp_setattr\n (cmpfunc)0, \/\/ tp_compare\n (reprfunc)PyVTKSpecialObject_PyRepr, \/\/ tp_repr\n 0, \/\/ tp_as_number\n 0, \/\/ tp_as_sequence\n 0, \/\/ tp_as_mapping\n (hashfunc)PyVTKSpecialObject_PyHash, \/\/ tp_hash\n (ternaryfunc)0, \/\/ tp_call\n (reprfunc)PyVTKSpecialObject_PyString, \/\/ tp_string\n (getattrofunc)PyVTKSpecialObject_PyGetAttr, \/\/ tp_getattro\n (setattrofunc)0, \/\/ tp_setattro\n 0, \/\/ tp_as_buffer\n Py_TPFLAGS_HAVE_RICHCOMPARE, \/\/ tp_flags\n (char*)\"vtkspecialobject - a vtk object not derived from vtkObjectBase.\", \/\/ tp_doc\n 0, \/\/ tp_traverse\n 0, \/\/ tp_clear\n (richcmpfunc)PyVTKSpecialObject_PyRichCompare, \/\/ tp_richcompare\n 0, \/\/ tp_weaklistoffset\n VTK_PYTHON_UTIL_SUPRESS_UNINITIALIZED\n};\n\n\/\/--------------------------------------------------------------------\nint PyVTKSpecialObject_Check(PyObject *obj)\n{\n return (obj->ob_type == &PyVTKSpecialObjectType);\n}\n\n\/\/--------------------------------------------------------------------\nPyObject *PyVTKSpecialObject_New(char *classname, void *ptr, int copy)\n{\n#if (PY_MAJOR_VERSION >= 2)\n PyVTKSpecialObject *self = PyObject_New(PyVTKSpecialObject,\n &PyVTKSpecialObjectType);\n#else\n PyVTKSpecialObject *self = PyObject_NEW(PyVTKSpecialObject,\n &PyVTKSpecialObjectType);\n#endif\n\n PyVTKSpecialType *info = vtkPythonUtil::FindSpecialType(classname);\n\n if (info == 0)\n {\n char buf[256];\n sprintf(buf,\"cannot create object of unknown type \\\"%s\\\"\",classname);\n PyErr_SetString(PyExc_ValueError,buf);\n return NULL;\n }\n\n if (copy)\n {\n ptr = info->copy_func(ptr);\n }\n\n self->vtk_ptr = ptr;\n self->vtk_hash = -1;\n self->vtk_info = info;\n\n return (PyObject *)self;\n}\n\n\/\/--------------------------------------------------------------------\nPyObject *PyVTKSpecialType_New(\n PyMethodDef *newmethod, PyMethodDef *methods, PyMethodDef *constructors,\n char *classname, char *docstring[], PyVTKSpecialMethods *smethods)\n{\n \/\/ Add this type to the special type map\n PyVTKSpecialType *info =\n vtkPythonUtil::AddSpecialTypeToMap(\n classname, docstring, methods, constructors, smethods);\n\n \/\/ Add the built docstring to the method\n newmethod->ml_doc = PyString_AsString(info->docstring);\n\n return PyCFunction_New(newmethod, Py_None);\n}\n<commit_msg>ENH: cleaner repr() for PyVTKSpecialObject<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: PyVTKSpecialObject.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"PyVTKSpecialObject.h\"\n#include \"vtkPythonUtil.h\"\n\n#include <vtksys\/ios\/sstream>\n\n\/\/--------------------------------------------------------------------\nPyVTKSpecialType::PyVTKSpecialType(\n char *cname, char *cdocs[], PyMethodDef *cmethods, PyMethodDef *ccons,\n PyVTKSpecialMethods *smethods)\n{\n this->classname = PyString_FromString(cname);\n this->docstring = vtkPythonUtil::BuildDocString(cdocs);\n this->methods = cmethods;\n this->constructors = ccons;\n this->copy_func = smethods->copy_func;\n this->delete_func = smethods->delete_func;\n this->print_func = smethods->print_func;\n this->compare_func = smethods->compare_func;\n this->hash_func = smethods->hash_func;\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyObject *PyVTKSpecialObject_PyString(PyVTKSpecialObject *self)\n{\n vtksys_ios::ostringstream os;\n self->vtk_info->print_func(os, self->vtk_ptr);\n const vtksys_stl::string &s = os.str();\n return PyString_FromStringAndSize(s.data(), s.size());\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyObject *PyVTKSpecialObject_PyRepr(PyVTKSpecialObject *self)\n{\n vtksys_ios::ostringstream os;\n os << \"(\" << PyString_AS_STRING(self->vtk_info->classname) << \")\";\n self->vtk_info->print_func(os, self->vtk_ptr);\n const vtksys_stl::string &s = os.str();\n return PyString_FromStringAndSize(s.data(), s.size());\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyObject *PyVTKSpecialObject_PyGetAttr(PyVTKSpecialObject *self,\n PyObject *attr)\n{\n char *name = PyString_AsString(attr);\n PyMethodDef *meth;\n\n if (name[0] == '_')\n {\n if (strcmp(name,\"__name__\") == 0)\n {\n Py_INCREF(self->vtk_info->classname);\n return self->vtk_info->classname;\n }\n if (strcmp(name,\"__doc__\") == 0)\n {\n Py_INCREF(self->vtk_info->docstring);\n return self->vtk_info->docstring;\n }\n if (strcmp(name,\"__methods__\") == 0)\n {\n meth = self->vtk_info->methods;\n PyObject *lst;\n int i, n;\n\n for (n = 0; meth && meth[n].ml_name; n++)\n {\n ;\n }\n\n if ((lst = PyList_New(n)) != NULL)\n {\n meth = self->vtk_info->methods;\n for (i = 0; i < n; i++)\n {\n PyList_SetItem(lst, i, PyString_FromString(meth[i].ml_name));\n }\n PyList_Sort(lst);\n }\n return lst;\n }\n\n if (strcmp(name,\"__members__\") == 0)\n {\n PyObject *lst;\n if ((lst = PyList_New(4)) != NULL)\n {\n PyList_SetItem(lst,0,PyString_FromString(\"__doc__\"));\n PyList_SetItem(lst,1,PyString_FromString(\"__members__\"));\n PyList_SetItem(lst,2,PyString_FromString(\"__methods__\"));\n PyList_SetItem(lst,3,PyString_FromString(\"__name__\"));\n }\n return lst;\n }\n }\n\n for (meth = self->vtk_info->methods; meth && meth->ml_name; meth++)\n {\n if (name[0] == meth->ml_name[0] && strcmp(name+1, meth->ml_name+1) == 0)\n {\n return PyCFunction_New(meth, (PyObject *)self);\n }\n }\n\n PyErr_SetString(PyExc_AttributeError, name);\n return NULL;\n}\n\n\/\/--------------------------------------------------------------------\nstatic void PyVTKSpecialObject_PyDelete(PyVTKSpecialObject *self)\n{\n if (self->vtk_ptr)\n {\n self->vtk_info->delete_func(self->vtk_ptr);\n }\n self->vtk_ptr = NULL;\n#if (PY_MAJOR_VERSION >= 2)\n PyObject_Del(self);\n#else\n PyMem_DEL(self);\n#endif\n}\n\n\/\/--------------------------------------------------------------------\nstatic long PyVTKSpecialObject_PyHash(PyVTKSpecialObject *self)\n{\n \/\/ self->vtk_hash must never be set to anything but -1 for mutable objects\n if (self->vtk_hash != -1)\n {\n return self->vtk_hash;\n }\n\n if (self->vtk_ptr && self->vtk_info->hash_func)\n {\n int imm = 0;\n long val = self->vtk_info->hash_func(self->vtk_ptr, &imm);\n if (val != -1)\n {\n if (imm)\n {\n \/\/ cache the hash for immutable objects\n self->vtk_hash = val;\n }\n return val;\n }\n }\n\/\/ python 2.6\n#if PY_VERSION_HEX >= 0x02060000\n return PyObject_HashNotImplemented((PyObject *)self);\n#else\n PyErr_SetString(PyExc_TypeError, (char *)\"object is not hashable\");\n return -1;\n#endif\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyObject *PyVTKSpecialObject_PyRichCompare(\n PyVTKSpecialObject *self, PyVTKSpecialObject *o, int opid)\n{\n if (self->vtk_ptr && self->vtk_info->compare_func)\n {\n int val = self->vtk_info->compare_func(self->vtk_ptr, o->vtk_ptr, opid);\n if (val == 0)\n {\n Py_INCREF(Py_False);\n return Py_False;\n }\n else if (val != -1)\n {\n Py_INCREF(Py_True);\n return Py_True;\n }\n }\n\n PyErr_SetString(PyExc_TypeError, (char *)\"operation not available\");\n return NULL;\n\/\/ Returning \"None\" is also valid, but not as informative\n#if PY_VERSION_HEX >= 0x02010000\n\/\/ Py_INCREF(Py_NotImplemented);\n\/\/ return Py_NotImplemented;\n#else\n\/\/ Py_INCREF(Py_None);\n\/\/ return Py_None;\n#endif\n}\n\n\/\/--------------------------------------------------------------------\nstatic PyTypeObject PyVTKSpecialObjectType = {\n PyObject_HEAD_INIT(&PyType_Type)\n 0,\n (char*)\"vtkspecialobject\", \/\/ tp_name\n sizeof(PyVTKSpecialObject), \/\/ tp_basicsize\n 0, \/\/ tp_itemsize\n (destructor)PyVTKSpecialObject_PyDelete, \/\/ tp_dealloc\n (printfunc)0, \/\/ tp_print\n (getattrfunc)0, \/\/ tp_getattr\n (setattrfunc)0, \/\/ tp_setattr\n (cmpfunc)0, \/\/ tp_compare\n (reprfunc)PyVTKSpecialObject_PyRepr, \/\/ tp_repr\n 0, \/\/ tp_as_number\n 0, \/\/ tp_as_sequence\n 0, \/\/ tp_as_mapping\n (hashfunc)PyVTKSpecialObject_PyHash, \/\/ tp_hash\n (ternaryfunc)0, \/\/ tp_call\n (reprfunc)PyVTKSpecialObject_PyString, \/\/ tp_string\n (getattrofunc)PyVTKSpecialObject_PyGetAttr, \/\/ tp_getattro\n (setattrofunc)0, \/\/ tp_setattro\n 0, \/\/ tp_as_buffer\n Py_TPFLAGS_HAVE_RICHCOMPARE, \/\/ tp_flags\n (char*)\"vtkspecialobject - a vtk object not derived from vtkObjectBase.\", \/\/ tp_doc\n 0, \/\/ tp_traverse\n 0, \/\/ tp_clear\n (richcmpfunc)PyVTKSpecialObject_PyRichCompare, \/\/ tp_richcompare\n 0, \/\/ tp_weaklistoffset\n VTK_PYTHON_UTIL_SUPRESS_UNINITIALIZED\n};\n\n\/\/--------------------------------------------------------------------\nint PyVTKSpecialObject_Check(PyObject *obj)\n{\n return (obj->ob_type == &PyVTKSpecialObjectType);\n}\n\n\/\/--------------------------------------------------------------------\nPyObject *PyVTKSpecialObject_New(char *classname, void *ptr, int copy)\n{\n#if (PY_MAJOR_VERSION >= 2)\n PyVTKSpecialObject *self = PyObject_New(PyVTKSpecialObject,\n &PyVTKSpecialObjectType);\n#else\n PyVTKSpecialObject *self = PyObject_NEW(PyVTKSpecialObject,\n &PyVTKSpecialObjectType);\n#endif\n\n PyVTKSpecialType *info = vtkPythonUtil::FindSpecialType(classname);\n\n if (info == 0)\n {\n char buf[256];\n sprintf(buf,\"cannot create object of unknown type \\\"%s\\\"\",classname);\n PyErr_SetString(PyExc_ValueError,buf);\n return NULL;\n }\n\n if (copy)\n {\n ptr = info->copy_func(ptr);\n }\n\n self->vtk_ptr = ptr;\n self->vtk_hash = -1;\n self->vtk_info = info;\n\n return (PyObject *)self;\n}\n\n\/\/--------------------------------------------------------------------\nPyObject *PyVTKSpecialType_New(\n PyMethodDef *newmethod, PyMethodDef *methods, PyMethodDef *constructors,\n char *classname, char *docstring[], PyVTKSpecialMethods *smethods)\n{\n \/\/ Add this type to the special type map\n PyVTKSpecialType *info =\n vtkPythonUtil::AddSpecialTypeToMap(\n classname, docstring, methods, constructors, smethods);\n\n \/\/ Add the built docstring to the method\n newmethod->ml_doc = PyString_AsString(info->docstring);\n\n return PyCFunction_New(newmethod, Py_None);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: FixedText.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2007-03-09 13:25:24 $\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 _FORMS_FIXEDTEXT_HXX_\n#define _FORMS_FIXEDTEXT_HXX_\n\n#ifndef _FORMS_FORMCOMPONENT_HXX_\n#include \"FormComponent.hxx\"\n#endif\n\n\/\/.........................................................................\nnamespace frm\n{\n\n\/\/==================================================================\n\/\/ OFixedTextModel\n\/\/==================================================================\nclass OFixedTextModel\n :public OControlModel\n{\npublic:\n DECLARE_DEFAULT_LEAF_XTOR( OFixedTextModel );\n\n\/\/ XServiceInfo\n IMPLEMENTATION_NAME(OFixedTextModel);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n\/\/ XPersistObject\n virtual ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ OControlModel's property handling\n virtual void describeAggregateProperties(\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& \/* [out] *\/ _rProps\n ) const;\n\nprotected:\n DECLARE_XCLONEABLE();\n};\n\n\/\/.........................................................................\n}\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_FIXEDTEXT_HXX_\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.82); FILE MERGED 2008\/04\/01 12:30:21 thb 1.6.82.2: #i85898# Stripping all external header guards 2008\/03\/31 13:11:33 rt 1.6.82.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: FixedText.hxx,v $\n * $Revision: 1.7 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _FORMS_FIXEDTEXT_HXX_\n#define _FORMS_FIXEDTEXT_HXX_\n\n#include \"FormComponent.hxx\"\n\n\/\/.........................................................................\nnamespace frm\n{\n\n\/\/==================================================================\n\/\/ OFixedTextModel\n\/\/==================================================================\nclass OFixedTextModel\n :public OControlModel\n{\npublic:\n DECLARE_DEFAULT_LEAF_XTOR( OFixedTextModel );\n\n\/\/ XServiceInfo\n IMPLEMENTATION_NAME(OFixedTextModel);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n\/\/ XPersistObject\n virtual ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ OControlModel's property handling\n virtual void describeAggregateProperties(\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& \/* [out] *\/ _rProps\n ) const;\n\nprotected:\n DECLARE_XCLONEABLE();\n};\n\n\/\/.........................................................................\n}\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_FIXEDTEXT_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n* Author : James Chapman\n* License : MIT\/X11 (http:\/\/directory.fsf.org\/wiki\/License:X11)\n* Description : Simple UDP ping example\n********************************************************************************\/\n\n#include <atomic>\n#include <iostream>\n#include <string>\n#include <thread>\n\n#ifdef _WIN32\n#include <WS2tcpip.h>\n#else\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#endif \/\/ _WIN32\n\n#include \"zmq.hpp\"\n\n#ifdef _WIN32\n#pragma comment(lib, \"Ws2_32.lib\")\n#endif \/\/ _WIN32\n\n#define PING_PORT_NUMBER 9999\n#define PING_MSG_SIZE 2\n#define PING_INTERVAL 500\n#define SOCKET_POLL_TIMEOUT 3000\n\n#define INFO_OUT(MSG) std::cout << \"[INFO] \" << \" \" << (MSG) << std::endl\n#define ERROR_OUT(MSG) std::cerr << \"[ERROR] \" << \" \" << (MSG) << std::endl\n\n#ifndef _WIN32\n#define SOCKET int\n#define INVALID_SOCKET (SOCKET)(~0)\n#define SOCKET_ERROR (SOCKET)(~1)\n#define NO_ERROR 0\n#endif \/\/ _WIN32\n\nstd::atomic<bool> g_threadInterupted(false);\n\n\/**\n* Create a socket and use ZeroMQ to poll.\n*\/\nvoid listener()\n{\n #ifdef _WIN32\n WSADATA wsaData;\n #endif \/\/ _WIN32\n int nResult = 0;\n int nOptOffVal = 0;\n int nOptOnVal = 1;\n int nOptLen = sizeof(int);\n\n #ifdef _WIN32\n \/\/ Initialize Winsock\n nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);\n if (nResult != NO_ERROR)\n {\n ERROR_OUT(\"zmqListen : WSAStartup failed\");\n }\n #endif \/\/ _WIN32\n\n \/\/ Create UDP socket\n SOCKET fdSocket;\n fdSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);\n if (fdSocket == INVALID_SOCKET)\n {\n ERROR_OUT(\"zmqListen : Socket creation failed\");\n }\n\n \/\/ Set up the sockaddr structure\n struct sockaddr_in saListen = {0};\n saListen.sin_family = AF_INET;\n saListen.sin_port = htons(PING_PORT_NUMBER);\n saListen.sin_addr.s_addr = htonl(INADDR_ANY);\n\n \/\/ Bind the socket\n nResult = bind(fdSocket, (sockaddr*)&saListen, sizeof(saListen));\n if (nResult != NO_ERROR)\n {\n ERROR_OUT(\"zmqListen : socket bind failed\");\n }\n\n while (!g_threadInterupted)\n {\n \/\/ Poll socket for a message\n zmq::pollitem_t items[] = {{NULL, fdSocket, ZMQ_POLLIN, 0}};\n zmq::poll(&items[0], 1, SOCKET_POLL_TIMEOUT);\n\n \/\/ If we get a message, print the contents\n if (items[0].revents & ZMQ_POLLIN)\n {\n char recvBuf[PING_MSG_SIZE] = {0};\n #ifdef _WIN32\n int saSize = sizeof(struct sockaddr_in);\n #else\n socklen_t saSize = sizeof(struct sockaddr_in);\n #endif \/\/ _WIN32\n size_t size = recvfrom(fdSocket, recvBuf, PING_MSG_SIZE + 1, 0, (sockaddr*)&saListen, &saSize);\n {\n std::string ip(inet_ntoa(saListen.sin_addr));\n INFO_OUT(\"received: \" + std::string(recvBuf) + \" from \" + ip);\n }\n }\n }\n\n #ifdef _WIN32\n closesocket(fdSocket);\n WSACleanup();\n #endif \/\/ _WIN32\n}\n\n\/**\n* Run broadcast and listen in seperate threads\n*\/\nint main()\n{\n g_threadInterupted = false;\n\n \/\/ Start listener in a seperate thread\n std::thread listenerThread(listener);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n\n {\n #ifdef _WIN32\n WSADATA wsaData;\n #endif \/\/ _WIN32\n int nResult = 0;\n int nOptOffVal = 0;\n int nOptOnVal = 1;\n int nOptLen = sizeof(int);\n\n #ifdef _WIN32\n \/\/ Initialize Winsock\n nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);\n if (nResult != NO_ERROR)\n {\n ERROR_OUT(\"broadcast : WSAStartup failed\");\n }\n #endif \/\/ _WIN32\n\n \/\/ Create UDP socket\n SOCKET fdSocket;\n fdSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);\n if (fdSocket == INVALID_SOCKET)\n {\n ERROR_OUT(\"broadcast : socket creation failed\");\n }\n\n \/\/ Ask operating system to let us do broadcasts from socket\n nResult = setsockopt(fdSocket, SOL_SOCKET, SO_BROADCAST, (char *)&nOptOnVal, nOptLen);\n if (nResult != NO_ERROR)\n {\n ERROR_OUT(\"broadcast : setsockopt SO_BROADCAST failed\");\n }\n\n \/\/ Set up the sockaddr structure\n struct sockaddr_in saBroadcast = {0};\n saBroadcast.sin_family = AF_INET;\n saBroadcast.sin_port = htons(PING_PORT_NUMBER);\n saBroadcast.sin_addr.s_addr = htonl(INADDR_BROADCAST);\n\n \/\/ Broadcast 5 beacon messages\n for (int i = 0; i < 5; i++)\n {\n char buffer[PING_MSG_SIZE] = {0};\n strcpy(&buffer[0], \"!\");\n int bytes = sendto(fdSocket, buffer, PING_MSG_SIZE + 1, 0, (sockaddr*)&saBroadcast, sizeof(struct sockaddr_in));\n if (bytes == SOCKET_ERROR)\n {\n ERROR_OUT(\"broadcast : sendto failed\");\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(PING_INTERVAL));\n }\n\n #ifdef _WIN32\n closesocket(fdSocket);\n WSACleanup();\n #endif \/\/ _WIN32\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n\n g_threadInterupted = true;\n\n listenerThread.join();\n\n return 0;\n}\n<commit_msg>Removed unused variables<commit_after>\/*******************************************************************************\n* Author : James Chapman\n* License : MIT\/X11 (http:\/\/directory.fsf.org\/wiki\/License:X11)\n* Description : Simple UDP ping example for Windows VS\n********************************************************************************\/\n\n#include <atomic>\n#include <iostream>\n#include <string>\n#include <thread>\n\n#ifdef _WIN32\n#include <WS2tcpip.h>\n#else\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#endif \/\/ _WIN32\n\n#include \"zmq.hpp\"\n\n#ifdef _WIN32\n#pragma comment(lib, \"Ws2_32.lib\")\n#endif \/\/ _WIN32\n\n#define PING_PORT_NUMBER 9999\n#define PING_MSG_SIZE 2\n#define PING_INTERVAL 500\n#define SOCKET_POLL_TIMEOUT 3000\n\n#define INFO_OUT(MSG) std::cout << \"[INFO] \" << \" \" << (MSG) << std::endl\n#define ERROR_OUT(MSG) std::cerr << \"[ERROR] \" << \" \" << (MSG) << std::endl\n\n#ifndef _WIN32\n#define SOCKET int\n#define INVALID_SOCKET (SOCKET)(~0)\n#define SOCKET_ERROR (SOCKET)(~1)\n#define NO_ERROR 0\n#endif \/\/ _WIN32\n\nstd::atomic<bool> g_threadInterupted(false);\n\n\/**\n* Create a socket and use ZeroMQ to poll.\n*\/\nvoid listener()\n{\n #ifdef _WIN32\n WSADATA wsaData;\n #endif \/\/ _WIN32\n int nResult = 0;\n\n #ifdef _WIN32\n \/\/ Initialize Winsock\n nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);\n if (nResult != NO_ERROR)\n {\n ERROR_OUT(\"zmqListen : WSAStartup failed\");\n }\n #endif \/\/ _WIN32\n\n \/\/ Create UDP socket\n SOCKET fdSocket;\n fdSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);\n if (fdSocket == INVALID_SOCKET)\n {\n ERROR_OUT(\"zmqListen : Socket creation failed\");\n }\n\n \/\/ Set up the sockaddr structure\n struct sockaddr_in saListen = {0};\n saListen.sin_family = AF_INET;\n saListen.sin_port = htons(PING_PORT_NUMBER);\n saListen.sin_addr.s_addr = htonl(INADDR_ANY);\n\n \/\/ Bind the socket\n nResult = bind(fdSocket, (sockaddr*)&saListen, sizeof(saListen));\n if (nResult != NO_ERROR)\n {\n ERROR_OUT(\"zmqListen : socket bind failed\");\n }\n\n while (!g_threadInterupted)\n {\n \/\/ Poll socket for a message\n zmq::pollitem_t items[] = {{NULL, fdSocket, ZMQ_POLLIN, 0}};\n zmq::poll(&items[0], 1, SOCKET_POLL_TIMEOUT);\n\n \/\/ If we get a message, print the contents\n if (items[0].revents & ZMQ_POLLIN)\n {\n char recvBuf[PING_MSG_SIZE] = {0};\n #ifdef _WIN32\n int saSize = sizeof(struct sockaddr_in);\n #else\n socklen_t saSize = sizeof(struct sockaddr_in);\n #endif \/\/ _WIN32\n size_t size = recvfrom(fdSocket, recvBuf, PING_MSG_SIZE + 1, 0, (sockaddr*)&saListen, &saSize);\n {\n std::string ip(inet_ntoa(saListen.sin_addr));\n INFO_OUT(\"received: \" + std::string(recvBuf) + \" from \" + ip);\n }\n }\n }\n\n #ifdef _WIN32\n closesocket(fdSocket);\n WSACleanup();\n #endif \/\/ _WIN32\n}\n\n\/**\n* Run broadcast and listen in seperate threads\n*\/\nint main()\n{\n g_threadInterupted = false;\n\n \/\/ Start listener in a seperate thread\n std::thread listenerThread(listener);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n\n {\n #ifdef _WIN32\n WSADATA wsaData;\n #endif \/\/ _WIN32\n int nResult = 0;\n int nOptOffVal = 0;\n int nOptOnVal = 1;\n int nOptLen = sizeof(int);\n\n #ifdef _WIN32\n \/\/ Initialize Winsock\n nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);\n if (nResult != NO_ERROR)\n {\n ERROR_OUT(\"broadcast : WSAStartup failed\");\n }\n #endif \/\/ _WIN32\n\n \/\/ Create UDP socket\n SOCKET fdSocket;\n fdSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);\n if (fdSocket == INVALID_SOCKET)\n {\n ERROR_OUT(\"broadcast : socket creation failed\");\n }\n\n \/\/ Ask operating system to let us do broadcasts from socket\n nResult = setsockopt(fdSocket, SOL_SOCKET, SO_BROADCAST, (char *)&nOptOnVal, nOptLen);\n if (nResult != NO_ERROR)\n {\n ERROR_OUT(\"broadcast : setsockopt SO_BROADCAST failed\");\n }\n\n \/\/ Set up the sockaddr structure\n struct sockaddr_in saBroadcast = {0};\n saBroadcast.sin_family = AF_INET;\n saBroadcast.sin_port = htons(PING_PORT_NUMBER);\n saBroadcast.sin_addr.s_addr = htonl(INADDR_BROADCAST);\n\n \/\/ Broadcast 5 beacon messages\n for (int i = 0; i < 5; i++)\n {\n char buffer[PING_MSG_SIZE] = {0};\n strcpy(&buffer[0], \"!\");\n int bytes = sendto(fdSocket, buffer, PING_MSG_SIZE + 1, 0, (sockaddr*)&saBroadcast, sizeof(struct sockaddr_in));\n if (bytes == SOCKET_ERROR)\n {\n ERROR_OUT(\"broadcast : sendto failed\");\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(PING_INTERVAL));\n }\n\n #ifdef _WIN32\n closesocket(fdSocket);\n WSACleanup();\n #endif \/\/ _WIN32\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n\n g_threadInterupted = true;\n\n listenerThread.join();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.\n\n\/\/ Permission is hereby granted, free of charge, to any person\n\/\/ obtaining a copy of this software and associated documentation\n\/\/ files (the \"Software\"), to deal in the Software without\n\/\/ restriction, including without limitation the rights to use, copy,\n\/\/ modify, merge, publish, distribute, sublicense, and\/or sell copies\n\/\/ 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\n\/\/ included in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n#include <assert.h>\n#include \"dmaManager.h\"\n#include \"MMURequest.h\"\n#include \"MMUIndication.h\"\n#include \"MemServerRequest.h\"\n#include \"MemServerIndication.h\"\n\n#define PLATFORM_TILE 0\n\nclass PortalPoller;\n#ifndef NO_CPP_PORTAL_CODE\nstatic int mmu_error_limit = 20;\nstatic int mem_error_limit = 20;\nclass MMUIndication : public MMUIndicationWrapper\n{\n DmaManager *portalMemory;\n public:\n MMUIndication(DmaManager *pm, unsigned int id, int tile=PLATFORM_TILE) : MMUIndicationWrapper(id,tile), portalMemory(pm) {}\n MMUIndication(DmaManager *pm, unsigned int id, PortalTransportFunctions *item, void *param) : MMUIndicationWrapper(id, item, param), portalMemory(pm) {}\n virtual void configResp(uint32_t pointer){\n fprintf(stderr, \"MMUIndication::configResp: %x\\n\", pointer);\n portalMemory->confResp(pointer);\n }\n virtual void error (uint32_t code, uint32_t pointer, uint64_t offset, uint64_t extra) {\n fprintf(stderr, \"MMUIndication::error(code=0x%x, pointer=0x%x, offset=0x%\"PRIx64\" extra=-0x%\"PRIx64\"\\n\", code, pointer, offset, extra);\n if (--mmu_error_limit < 0)\n exit(-1);\n }\n virtual void idResponse(uint32_t sglId){\n portalMemory->sglIdResp(sglId);\n }\n};\n\nclass MemServerIndication : public MemServerIndicationWrapper\n{\n MemServerRequestProxy *memServerRequestProxy;\n sem_t mtSem;\n uint64_t mtCnt;\n void init(){\n if (sem_init(&mtSem, 0, 0))\n PORTAL_PRINTF(\"MemServerIndication::init failed to init mtSem\\n\");\n }\n public:\n MemServerIndication(unsigned int id, int tile=PLATFORM_TILE) : MemServerIndicationWrapper(id,tile), memServerRequestProxy(NULL) {init();}\n MemServerIndication(MemServerRequestProxy *p, unsigned int id, int tile=PLATFORM_TILE) : MemServerIndicationWrapper(id,tile), memServerRequestProxy(p) {init();}\n virtual void addrResponse(uint64_t physAddr){\n fprintf(stderr, \"DmaIndication::addrResponse(physAddr=%\"PRIx64\")\\n\", physAddr);\n }\n virtual void reportStateDbg(const DmaDbgRec rec){\n fprintf(stderr, \"MemServerIndication::reportStateDbg: {x:%08x y:%08x z:%08x w:%08x}\\n\", rec.x,rec.y,rec.z,rec.w);\n }\n virtual void reportMemoryTraffic(uint64_t words){\n \/\/fprintf(stderr, \"reportMemoryTraffic: words=%\"PRIx64\"\\n\", words);\n mtCnt = words;\n sem_post(&mtSem);\n }\n virtual void error (uint32_t code, uint32_t pointer, uint64_t offset, uint64_t extra) {\n fprintf(stderr, \"MemServerIndication::error(code=%x, pointer=%x, offset=%\"PRIx64\" extra=%\"PRIx64\"\\n\", code, pointer, offset, extra);\n if (--mem_error_limit < 0)\n exit(-1);\n }\n uint64_t receiveMemoryTraffic(){\n sem_wait(&mtSem);\n return mtCnt; \n }\n uint64_t getMemoryTraffic(const ChannelType rc){\n assert(memServerRequestProxy);\n memServerRequestProxy->memoryTraffic(rc);\n return receiveMemoryTraffic();\n }\n};\n\nstatic MemServerRequestProxy *hostMemServerRequest;\nstatic MemServerIndication *hostMemServerIndication;\nstatic MMUIndication *mmuIndication;\nDmaManager *platformInit(void)\n{\n hostMemServerRequest = new MemServerRequestProxy(IfcNames_MemServerRequestS2H, PLATFORM_TILE);\n MMURequestProxy *dmap = new MMURequestProxy(IfcNames_MMURequestS2H, PLATFORM_TILE);\n DmaManager *dma = new DmaManager(dmap);\n hostMemServerIndication = new MemServerIndication(hostMemServerRequest, IfcNames_MemServerIndicationH2S, PLATFORM_TILE);\n mmuIndication = new MMUIndication(dma, IfcNames_MMUIndicationH2S, PLATFORM_TILE);\n\n#ifdef FPGA0_CLOCK_FREQ\n long req_freq = FPGA0_CLOCK_FREQ;\n long freq = 0;\n setClockFrequency(0, req_freq, &freq);\n fprintf(stderr, \"Requested FCLK[0]=%ld actually %ld\\n\", req_freq, freq);\n#endif\n return dma;\n}\n\nvoid platformStatistics(void)\n{\n uint64_t cycles = portalTimerLap(0);\n hostMemServerRequest->memoryTraffic(ChannelType_Read);\n uint64_t read_beats = hostMemServerIndication->receiveMemoryTraffic();\n float read_util = (float)read_beats\/(float)cycles;\n hostMemServerRequest->memoryTraffic(ChannelType_Write);\n uint64_t write_beats = hostMemServerIndication->receiveMemoryTraffic();\n float write_util = (float)write_beats\/(float)cycles;\n fprintf(stderr, \" read_beats: %llx\\n\", (long long)read_beats);\n fprintf(stderr, \" write_beats: %llx\\n\", (long long)write_beats);\n fprintf(stderr, \"memory utilization (beats\/cycle): read %f write %f\\n\", read_util, write_util);\n}\n#endif\n<commit_msg>print cycles as well as read and write beats<commit_after>\n\/\/ Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.\n\n\/\/ Permission is hereby granted, free of charge, to any person\n\/\/ obtaining a copy of this software and associated documentation\n\/\/ files (the \"Software\"), to deal in the Software without\n\/\/ restriction, including without limitation the rights to use, copy,\n\/\/ modify, merge, publish, distribute, sublicense, and\/or sell copies\n\/\/ 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\n\/\/ included in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n#include <assert.h>\n#include \"dmaManager.h\"\n#include \"MMURequest.h\"\n#include \"MMUIndication.h\"\n#include \"MemServerRequest.h\"\n#include \"MemServerIndication.h\"\n\n#define PLATFORM_TILE 0\n\nclass PortalPoller;\n#ifndef NO_CPP_PORTAL_CODE\nstatic int mmu_error_limit = 20;\nstatic int mem_error_limit = 20;\nclass MMUIndication : public MMUIndicationWrapper\n{\n DmaManager *portalMemory;\n public:\n MMUIndication(DmaManager *pm, unsigned int id, int tile=PLATFORM_TILE) : MMUIndicationWrapper(id,tile), portalMemory(pm) {}\n MMUIndication(DmaManager *pm, unsigned int id, PortalTransportFunctions *item, void *param) : MMUIndicationWrapper(id, item, param), portalMemory(pm) {}\n virtual void configResp(uint32_t pointer){\n fprintf(stderr, \"MMUIndication::configResp: %x\\n\", pointer);\n portalMemory->confResp(pointer);\n }\n virtual void error (uint32_t code, uint32_t pointer, uint64_t offset, uint64_t extra) {\n fprintf(stderr, \"MMUIndication::error(code=0x%x, pointer=0x%x, offset=0x%\"PRIx64\" extra=-0x%\"PRIx64\"\\n\", code, pointer, offset, extra);\n if (--mmu_error_limit < 0)\n exit(-1);\n }\n virtual void idResponse(uint32_t sglId){\n portalMemory->sglIdResp(sglId);\n }\n};\n\nclass MemServerIndication : public MemServerIndicationWrapper\n{\n MemServerRequestProxy *memServerRequestProxy;\n sem_t mtSem;\n uint64_t mtCnt;\n void init(){\n if (sem_init(&mtSem, 0, 0))\n PORTAL_PRINTF(\"MemServerIndication::init failed to init mtSem\\n\");\n }\n public:\n MemServerIndication(unsigned int id, int tile=PLATFORM_TILE) : MemServerIndicationWrapper(id,tile), memServerRequestProxy(NULL) {init();}\n MemServerIndication(MemServerRequestProxy *p, unsigned int id, int tile=PLATFORM_TILE) : MemServerIndicationWrapper(id,tile), memServerRequestProxy(p) {init();}\n virtual void addrResponse(uint64_t physAddr){\n fprintf(stderr, \"DmaIndication::addrResponse(physAddr=%\"PRIx64\")\\n\", physAddr);\n }\n virtual void reportStateDbg(const DmaDbgRec rec){\n fprintf(stderr, \"MemServerIndication::reportStateDbg: {x:%08x y:%08x z:%08x w:%08x}\\n\", rec.x,rec.y,rec.z,rec.w);\n }\n virtual void reportMemoryTraffic(uint64_t words){\n \/\/fprintf(stderr, \"reportMemoryTraffic: words=%\"PRIx64\"\\n\", words);\n mtCnt = words;\n sem_post(&mtSem);\n }\n virtual void error (uint32_t code, uint32_t pointer, uint64_t offset, uint64_t extra) {\n fprintf(stderr, \"MemServerIndication::error(code=%x, pointer=%x, offset=%\"PRIx64\" extra=%\"PRIx64\"\\n\", code, pointer, offset, extra);\n if (--mem_error_limit < 0)\n exit(-1);\n }\n uint64_t receiveMemoryTraffic(){\n sem_wait(&mtSem);\n return mtCnt; \n }\n uint64_t getMemoryTraffic(const ChannelType rc){\n assert(memServerRequestProxy);\n memServerRequestProxy->memoryTraffic(rc);\n return receiveMemoryTraffic();\n }\n};\n\nstatic MemServerRequestProxy *hostMemServerRequest;\nstatic MemServerIndication *hostMemServerIndication;\nstatic MMUIndication *mmuIndication;\nDmaManager *platformInit(void)\n{\n hostMemServerRequest = new MemServerRequestProxy(IfcNames_MemServerRequestS2H, PLATFORM_TILE);\n MMURequestProxy *dmap = new MMURequestProxy(IfcNames_MMURequestS2H, PLATFORM_TILE);\n DmaManager *dma = new DmaManager(dmap);\n hostMemServerIndication = new MemServerIndication(hostMemServerRequest, IfcNames_MemServerIndicationH2S, PLATFORM_TILE);\n mmuIndication = new MMUIndication(dma, IfcNames_MMUIndicationH2S, PLATFORM_TILE);\n\n#ifdef FPGA0_CLOCK_FREQ\n long req_freq = FPGA0_CLOCK_FREQ;\n long freq = 0;\n setClockFrequency(0, req_freq, &freq);\n fprintf(stderr, \"Requested FCLK[0]=%ld actually %ld\\n\", req_freq, freq);\n#endif\n return dma;\n}\n\nvoid platformStatistics(void)\n{\n uint64_t cycles = portalTimerLap(0);\n hostMemServerRequest->memoryTraffic(ChannelType_Read);\n uint64_t read_beats = hostMemServerIndication->receiveMemoryTraffic();\n float read_util = (float)read_beats\/(float)cycles;\n hostMemServerRequest->memoryTraffic(ChannelType_Write);\n uint64_t write_beats = hostMemServerIndication->receiveMemoryTraffic();\n float write_util = (float)write_beats\/(float)cycles;\n fprintf(stderr, \" read_beats: %lld\\n\", (long long)read_beats);\n fprintf(stderr, \" write_beats: %lld\\n\", (long long)write_beats);\n fprintf(stderr, \" cycles: %lld\\n\", (long long)cycles);\n fprintf(stderr, \"memory utilization (beats\/cycle): read %f write %f\\n\", read_util, write_util);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: test_sec.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: dbo $ $Date: 2000-12-21 14:41:57 $\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#include <stdio.h>\n\n#include <vos\/conditn.hxx>\n#include <vos\/thread.hxx>\n\n#include <uno\/current_context.hxx>\n\n#include <cppuhelper\/implbase1.hxx>\n\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <com\/sun\/star\/loader\/XImplementationLoader.hpp>\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n\nusing namespace rtl;\nusing namespace vos;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::security;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::loader;\nusing namespace com::sun::star::registry;\nusing namespace com::sun::star::container;\n\n\nstatic inline void out( const sal_Char * p )\n{\n ::fprintf( stderr, p );\n}\nstatic inline void out( const OUString & r )\n{\n OString aStr( OUStringToOString( r, RTL_TEXTENCODING_ASCII_US ) );\n out( aStr.getStr() );\n}\n\n\nstatic Reference< XInterface > load(\n const Reference< XMultiServiceFactory > & xMgr,\n const char * service,\n const char * implName, const char * activator, const char * loc ) throw ()\n{\n Reference< XInterface > xRet(\n xMgr->createInstance( OUString::createFromAscii( service ) ) );\n if (xRet.is())\n return xRet;\n\n try\n {\n Reference< XImplementationLoader > xLoader(\n xMgr->createInstance( OUString::createFromAscii( activator ) ), UNO_QUERY );\n if (xLoader.is())\n {\n Reference< XSingleServiceFactory > xFac( xLoader->activate(\n OUString::createFromAscii( implName ), OUString(),\n OUString::createFromAscii( loc ),\n Reference< XRegistryKey >() ), UNO_QUERY );\n if (xFac.is())\n return xFac->createInstance();\n }\n else\n {\n out( \"### cannot activate loader \\\"\" );\n out( activator );\n out( \"\\\"!\\n\" );\n }\n }\n catch (Exception &)\n {\n out( \"### cannot activate service \\\"\" );\n out( service );\n out( \"\\\"!\\n\" );\n }\n return Reference< XInterface >();\n}\n\nstatic void setEnv( const Reference< XMultiServiceFactory > & xMgr ) throw ()\n{\n OSL_ASSERT( xMgr.is() );\n Reference< XNameContainer > xContext( getCurrentContext(), UNO_QUERY );\n OSL_ASSERT( xContext.is() );\n\n try\n {\n xContext->insertByName(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.lang.ServiceManager\") ),\n makeAny( xMgr ) );\n xContext->insertByName(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.security.AccessController\") ),\n makeAny( load( xMgr,\n \"com.sun.star.security.AccessController\",\n \"com.sun.star.comp.security.AccessController\",\n \"com.sun.star.loader.Java2\",\n \"com.sun.star.comp.security.AccessController\" ) ) );\n xContext->insertByName(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.security.auth.login.LoginContext\") ),\n makeAny( load( xMgr,\n \"com.sun.star.security.auth.login.LoginContext\",\n \"com.sun.star.comp.security.auth.login.LoginContext\",\n \"com.sun.star.loader.Java2\",\n \"com.sun.star.comp.security.auth.login.LoginContext\" ) ) );\n }\n catch (Exception & rExc)\n {\n out( \"### exception occured: \" );\n out( rExc.Message );\n out( \"\\n\" );\n }\n}\n\n\/\/##################################################################################################\n\/\/##################################################################################################\n\/\/##################################################################################################\n\nstruct PrivAction : WeakImplHelper1< XPrivilegedAction >\n{\n virtual Any SAL_CALL run()\n throw (Exception)\n {\n throw IllegalArgumentException(\n OUString::createFromAscii(\"testtest\"), (OWeakObject *)this, (sal_Int16)5 );\n }\n};\n\nstruct Thread1 : public OThread\n{\n Reference< XMultiServiceFactory > _xMgr;\n\n Thread1( const Reference< XMultiServiceFactory > & xMgr )\n : _xMgr( xMgr )\n {}\n\n void f()\n {\n Reference< XNameAccess > xAccess( getCurrentContext(), UNO_QUERY );\n OSL_ASSERT( xAccess->getByName( OUString::createFromAscii(\"a\") ) == (sal_Int16)5 );\n Reference< XNameContainer > xCont( getCurrentContext(), UNO_QUERY );\n xCont->insertByName( OUString::createFromAscii(\"b\"), makeAny( (sal_Int32)6 ) );\n }\n virtual void SAL_CALL run()\n {\n try\n {\n setEnv( _xMgr );\n Reference< XNameContainer > xCont( getCurrentContext(), UNO_QUERY );\n xCont->insertByName( OUString::createFromAscii(\"a\"), makeAny( (sal_Int32)5 ) );\n f();\n Reference< XNameAccess > xAccess( getCurrentContext(), UNO_QUERY );\n OSL_ASSERT( xAccess->getByName( OUString::createFromAscii(\"b\") ) == (sal_Int16)6 );\n\n\/\/ checkPermission(\n\/\/ Permission( OUString::createFromAscii(\"java.io.FilePermission\"),\n\/\/ OUString::createFromAscii(\"f:\\\\userprofiles.dat\"),\n\/\/ OUString::createFromAscii(\"read\") ) );\n\n\/\/ try\n\/\/ {\n\/\/ Reference< XCurrentContext > xContext( getCurrentContext() );\n\/\/ Reference< XAccessController > xACC( xContext->getAccessController() );\n\/\/ xACC->doPrivileged( new PrivAction(), Reference< XAccessControlContext >() );\n\/\/ }\n\/\/ catch (IllegalArgumentException & r)\n\/\/ {\n\/\/ OSL_ASSERT( r.ArgumentPosition == 5 &&\n\/\/ r.Message.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(\"testtest\") ));\n\/\/ }\n }\n catch (RuntimeException & rExc)\n {\n out( rExc.Message );\n }\n }\n};\n\n\nvoid test_security( const Reference< XMultiServiceFactory > & xMgr ) throw ()\n{\n setEnv( xMgr );\n OSL_ASSERT( getCurrentContext()->getServiceManager().is() );\n\n Thread1 thread1( xMgr );\n thread1.create();\n thread1.join();\n out( \"> exiting...\\n\" );\n}\n<commit_msg>removed include <vos\/conditn.hxx> and <vos\/thread.hxx> and using namespace vos<commit_after>\/*************************************************************************\n *\n * $RCSfile: test_sec.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: jl $ $Date: 2001-03-19 10:10:07 $\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#include <stdio.h>\n\n\n#include <uno\/current_context.hxx>\n\n#include <cppuhelper\/implbase1.hxx>\n\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <com\/sun\/star\/loader\/XImplementationLoader.hpp>\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n\nusing namespace rtl;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::security;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::loader;\nusing namespace com::sun::star::registry;\nusing namespace com::sun::star::container;\n\n\nstatic inline void out( const sal_Char * p )\n{\n ::fprintf( stderr, p );\n}\nstatic inline void out( const OUString & r )\n{\n OString aStr( OUStringToOString( r, RTL_TEXTENCODING_ASCII_US ) );\n out( aStr.getStr() );\n}\n\n\nstatic Reference< XInterface > load(\n const Reference< XMultiServiceFactory > & xMgr,\n const char * service,\n const char * implName, const char * activator, const char * loc ) throw ()\n{\n Reference< XInterface > xRet(\n xMgr->createInstance( OUString::createFromAscii( service ) ) );\n if (xRet.is())\n return xRet;\n\n try\n {\n Reference< XImplementationLoader > xLoader(\n xMgr->createInstance( OUString::createFromAscii( activator ) ), UNO_QUERY );\n if (xLoader.is())\n {\n Reference< XSingleServiceFactory > xFac( xLoader->activate(\n OUString::createFromAscii( implName ), OUString(),\n OUString::createFromAscii( loc ),\n Reference< XRegistryKey >() ), UNO_QUERY );\n if (xFac.is())\n return xFac->createInstance();\n }\n else\n {\n out( \"### cannot activate loader \\\"\" );\n out( activator );\n out( \"\\\"!\\n\" );\n }\n }\n catch (Exception &)\n {\n out( \"### cannot activate service \\\"\" );\n out( service );\n out( \"\\\"!\\n\" );\n }\n return Reference< XInterface >();\n}\n\nstatic void setEnv( const Reference< XMultiServiceFactory > & xMgr ) throw ()\n{\n OSL_ASSERT( xMgr.is() );\n Reference< XNameContainer > xContext( getCurrentContext(), UNO_QUERY );\n OSL_ASSERT( xContext.is() );\n\n try\n {\n xContext->insertByName(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.lang.ServiceManager\") ),\n makeAny( xMgr ) );\n xContext->insertByName(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.security.AccessController\") ),\n makeAny( load( xMgr,\n \"com.sun.star.security.AccessController\",\n \"com.sun.star.comp.security.AccessController\",\n \"com.sun.star.loader.Java2\",\n \"com.sun.star.comp.security.AccessController\" ) ) );\n xContext->insertByName(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.security.auth.login.LoginContext\") ),\n makeAny( load( xMgr,\n \"com.sun.star.security.auth.login.LoginContext\",\n \"com.sun.star.comp.security.auth.login.LoginContext\",\n \"com.sun.star.loader.Java2\",\n \"com.sun.star.comp.security.auth.login.LoginContext\" ) ) );\n }\n catch (Exception & rExc)\n {\n out( \"### exception occured: \" );\n out( rExc.Message );\n out( \"\\n\" );\n }\n}\n\n\/\/##################################################################################################\n\/\/##################################################################################################\n\/\/##################################################################################################\n\nstruct PrivAction : WeakImplHelper1< XPrivilegedAction >\n{\n virtual Any SAL_CALL run()\n throw (Exception)\n {\n throw IllegalArgumentException(\n OUString::createFromAscii(\"testtest\"), (OWeakObject *)this, (sal_Int16)5 );\n }\n};\n\nstruct Thread1 : public OThread\n{\n Reference< XMultiServiceFactory > _xMgr;\n\n Thread1( const Reference< XMultiServiceFactory > & xMgr )\n : _xMgr( xMgr )\n {}\n\n void f()\n {\n Reference< XNameAccess > xAccess( getCurrentContext(), UNO_QUERY );\n OSL_ASSERT( xAccess->getByName( OUString::createFromAscii(\"a\") ) == (sal_Int16)5 );\n Reference< XNameContainer > xCont( getCurrentContext(), UNO_QUERY );\n xCont->insertByName( OUString::createFromAscii(\"b\"), makeAny( (sal_Int32)6 ) );\n }\n virtual void SAL_CALL run()\n {\n try\n {\n setEnv( _xMgr );\n Reference< XNameContainer > xCont( getCurrentContext(), UNO_QUERY );\n xCont->insertByName( OUString::createFromAscii(\"a\"), makeAny( (sal_Int32)5 ) );\n f();\n Reference< XNameAccess > xAccess( getCurrentContext(), UNO_QUERY );\n OSL_ASSERT( xAccess->getByName( OUString::createFromAscii(\"b\") ) == (sal_Int16)6 );\n\n\/\/ checkPermission(\n\/\/ Permission( OUString::createFromAscii(\"java.io.FilePermission\"),\n\/\/ OUString::createFromAscii(\"f:\\\\userprofiles.dat\"),\n\/\/ OUString::createFromAscii(\"read\") ) );\n\n\/\/ try\n\/\/ {\n\/\/ Reference< XCurrentContext > xContext( getCurrentContext() );\n\/\/ Reference< XAccessController > xACC( xContext->getAccessController() );\n\/\/ xACC->doPrivileged( new PrivAction(), Reference< XAccessControlContext >() );\n\/\/ }\n\/\/ catch (IllegalArgumentException & r)\n\/\/ {\n\/\/ OSL_ASSERT( r.ArgumentPosition == 5 &&\n\/\/ r.Message.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(\"testtest\") ));\n\/\/ }\n }\n catch (RuntimeException & rExc)\n {\n out( rExc.Message );\n }\n }\n};\n\n\nvoid test_security( const Reference< XMultiServiceFactory > & xMgr ) throw ()\n{\n setEnv( xMgr );\n OSL_ASSERT( getCurrentContext()->getServiceManager().is() );\n\n Thread1 thread1( xMgr );\n thread1.create();\n thread1.join();\n out( \"> exiting...\\n\" );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: slide.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2005-10-11 08:54:29 $\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 _SLIDESHOW_SLIDE_HXX\n#define _SLIDESHOW_SLIDE_HXX\n\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HXX_\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_\n#include <com\/sun\/star\/drawing\/XDrawPage.hpp>\n#endif\n\n#ifndef BOOST_SHARED_PTR_HPP_INCLUDED\n#include <boost\/shared_ptr.hpp>\n#endif\n\n#ifndef _CPPCANVAS_SPRITECANVAS_HXX\n#include <cppcanvas\/spritecanvas.hxx>\n#endif\n\n#ifndef _BGFX_VECTOR_B2ISIZE_HXX\n#include <basegfx\/vector\/b2isize.hxx>\n#endif\n\n#include <vector>\n#include <utility>\n\n#include <unoview.hxx>\n#include <event.hxx>\n#include <layermanager.hxx>\n#include <userpaintoverlay.hxx>\n#include <slideanimations.hxx>\n#include <slidebitmap.hxx>\n#include <shapeeventbroadcaster.hxx>\n#include \"boost\/optional.hpp\"\n\n\/* Definition of Slide class *\/\n\nnamespace presentation\n{\n namespace internal\n {\n class EventQueue;\n class ActivitiesQueue;\n class UserEventQueue;\n\n class Slide\n {\n public:\n \/** Construct from XDrawPage\n\n Prefetches shapes from draw page, thus might take some\n time. The Slide object generally works in XDrawPage\n model coordinates, that is, the page will have the\n width and height as specified in the XDrawPage's\n property set. The top, left corner of the page will be\n rendered at (0,0) in the given canvas' view coordinate\n system.\n *\/\n Slide( const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage >& xDrawPage,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XAnimationNode >& xRootNode,\n EventQueue& rEventQueue,\n ActivitiesQueue& rActivitiesQueue,\n EventMultiplexer& rEventMultiplexer,\n UserEventQueue& rUserEventQueue,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XComponentContext >& xContext );\n\n ~Slide();\n\n \/** Add a view to this slide\n *\/\n void addView( const UnoViewSharedPtr& rView );\n\n \/** Remove a previously added a view from this slide\n\n @return true, if this view was successfully removed, false\n otherwise (e.g. if this view wasn't added in the first place)\n *\/\n bool removeView( const UnoViewSharedPtr& rView );\n\n \/** Add the given listener for the given shape.\n\n This method implements the addShapeEventListener\n method of the XSlideShow interface. The given listener\n is called, whenever a user clicks on the shape. If the\n shape is not contained in this slide, this method does\n nothing.\n *\/\n void addShapeEventListener( const ::com::sun::star::uno::Reference<\n ::com::sun::star::presentation::XShapeEventListener >& xListener,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XShape >& xShape );\n\n \/** Revoke the given listener for the given shape.\n\n This method implements the removeShapeEventListener\n method of the XSlideShow interface.\n *\/\n void removeShapeEventListener( const ::com::sun::star::uno::Reference<\n ::com::sun::star::presentation::XShapeEventListener >& xListener,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XShape >& xShape );\n\n \/** Control intrinsic animation behaviour\n\n @param bImageAnimationsAllowed\n When true, GIF and drawing layer animations will be\n shown. When false, those shapes have no intrinsic\n animation.\n *\/\n void setImageAnimationsAllowed( bool bImageAnimationsAllowed );\n\n \/** Set the mouse cursor for a given shape.\n\n This method implements the setShapeCursor method of\n the XSlideShow interface. Whenever the mouse hovers\n over the given shape, the specified mouse cursor will\n be shown. To reset the mouse cursor to the default,\n specify awt::SystemPointer::ARROW.\n *\/\n void setShapeCursor( const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XShape >& xShape,\n sal_Int16 nPointerShape );\n\n \/** Prepares to show slide.\n\n Call this method to reduce the timeout show(), and\n getInitialSlideBitmap() need to complete. If\n prefetchShow() is not called explicitely, the named\n methods will call it implicitely.\n *\/\n bool prefetchShow();\n\n \/** Paint the slide on all registered views, without any effects\n *\/\n bool paint();\n\n \/** Shows the slide on all registered views\n *\/\n bool show();\n\n \/** Force-end the slide show.\n *\/\n void end();\n\n \/** Query whether this slide is currently showing.\n\n @return true, if this slide is currently showing\n (i.e. show() was called more often than end()).\n *\/\n bool isShowing() const;\n\n \/** Query whether the slide has animations at all\n\n If the slide doesn't have animations, show() is\n equivalent to paint(). If an event is registered with\n registerSlideEndEvent(), this event will be\n immediately activated at the end of the show() method.\n\n @return true, if this slide has animations, false\n otherwise\n *\/\n bool isAnimated();\n\n \/** Request bitmap for current slide appearance.\n\n The bitmap returned by this method is dependent on the\n current state of the slide and the contained\n animations. A newly generated slide will return the\n initial slide content here (e.g. with all 'appear'\n effect shapes invisible), a slide whose effects are\n currently running will return a bitmap corresponding\n to the current position on the animation timeline, and\n a slide whose effects have all been run will generate\n a bitmap with the final slide appearance (e.g. with\n all 'hide' effect shapes invisible).\n\n @param rView\n View to retrieve bitmap for (note that the bitmap will\n have device-pixel equivalence to the content that\n would have been rendered onto the given view). Note\n that the view must have been added to this slide via\n addView() before, otherwise, this method will throw an\n exception.\n *\/\n \/\/ TODO(F2): Rework SlideBitmap to no longer be based on XBitmap,\n \/\/ but on canvas-independent basegfx bitmaps\n SlideBitmapSharedPtr getCurrentSlideBitmap( const UnoViewSharedPtr& rView );\n\n \/** Query the slide, whether next slide should appear\n automatically.\n\n @return true, if next slide should be displayed\n automatically. When false is returned, the user is\n required to click to have the next slide shown.\n *\/\n bool hasAutomaticNextSlide() const;\n\n \/** Query the slide for the timeout, until the next slide\n is automatically shown.\n\n This value is undefined, should\n hasAutomaticNextSlide() return false.\n\n @return a timeout in seconds, for which to delay the\n display of the next slide.\n *\/\n double getAutomaticNextSlideTimeout() const;\n\n \/** Control the user paint mode.\n\n The user paint mode lets the user paint on this slide\n with the given color, when pressing down the\n mousebutton.\n *\/\n void setUserPaintColor( boost::optional<RGBColor> const& rColor );\n\n \/\/\/ Query the XDrawPage's size\n basegfx::B2ISize getSlideSize() const;\n\n \/\/\/ Get size of the slide in device coordinates for given view\n ::basegfx::B2ISize getSlideSizePixel(\n UnoViewSharedPtr const & pView ) const;\n\n \/\/\/ Gets the underlying API page\n ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage > const&\n getXDrawPage() const { return mxDrawPage; }\n\n \/\/\/ Gets the animation node.\n ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XAnimationNode > const&\n getXAnimationNode() const { return mxRootNode; }\n\n private:\n \/\/ default: disabled copy\/assignment\n Slide(const Slide&);\n Slide& operator=( const Slide& );\n\n void enablePaintOverlay();\n void disablePaintOverlay();\n\n \/\/\/ Set all Shapes to their initial attributes for slideshow\n bool applyInitialShapeAttributes( const ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XAnimationNode >& xRootAnimationNode );\n\n \/\/\/ Renders current slide content to bitmap\n SlideBitmapSharedPtr createCurrentSlideBitmap(\n const UnoViewSharedPtr& rView,\n ::basegfx::B2ISize const & rSlideSize );\n\n \/\/\/ Prefetch all shapes (not the animations)\n bool prefetchShapes();\n\n \/\/\/ Prefetch show, but don't call applyInitialShapeAttributes()\n bool implPrefetchShow();\n\n \/\/\/ Query the rectangle covered by the slide\n ::basegfx::B2DRectangle getSlideRect() const;\n\n \/\/\/ Start GIF and other intrinsic shape animations\n void endIntrinsicAnimations();\n\n \/\/\/ End GIF and other intrinsic shape animations\n void startIntrinsicAnimations();\n\n\n \/\/ Types\n \/\/ =====\n\n enum SlideAnimationState\n {\n CONSTRUCTING_STATE=0,\n INITIAL_STATE=1,\n SHOWING_STATE=2,\n FINAL_STATE=3,\n SlideAnimationState_NUM_ENTRIES=4\n };\n\n \/** Vector of slide bitmaps.\n\n Since the bitmap content is sensitive to animation\n effects, we have an inner vector containing a distinct\n bitmap for each of the SlideAnimationStates.\n *\/\n typedef ::std::vector< ::std::vector< SlideBitmapSharedPtr > > VectorOfSlideBitmaps;\n\n\n \/\/ Member variables\n \/\/ ================\n\n \/\/\/ The page model object\n ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage > const mxDrawPage;\n ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XAnimationNode > const mxRootNode;\n\n \/\/\/ Contains common objects needed throughout the slideshow\n SlideShowContext maContext;\n\n ::boost::shared_ptr<ShapeEventBroadcaster> mpEventBroadcaster;\n\n \/\/\/ Handles the animation and event generation for us\n SlideAnimations maAnimations;\n\n \/\/\/ All added views\n UnoViewVector maViews;\n\n ::boost::optional<RGBColor> maUserPaintColor;\n UserPaintOverlaySharedPtr mpPaintOverlay;\n\n \/\/\/ Bitmap with initial slide content\n VectorOfSlideBitmaps maSlideBitmaps;\n\n \/\/\/ Timeout for automatic next slide display\n double mnNextSlideTimeout;\n\n SlideAnimationState meAnimationState;\n\n \/\/\/ True, when intrinsic shape animations are allowed\n bool mbImageAnimationsAllowed;\n\n \/\/\/ True, if initial load of all page shapes succeeded\n bool mbShapesLoaded;\n\n \/\/\/ True, if initial load of all animation info succeeded\n bool mbShowLoaded;\n\n \/** True, if this slide is not static.\n\n If this slide has animated content, this variable wiil\n be true, and false otherwise.\n *\/\n bool mbHaveAnimations;\n\n \/** True, if this slide has a main animation sequence.\n\n If this slide has animation content, which in turn has\n a main animation sequence (which must be fully run\n before EventMultiplexer::notifySlideAnimationsEnd() is\n called), this member is true.\n *\/\n bool mbMainSequenceFound;\n\n \/** When true, next slide should display without further\n user interaction.\n *\/\n bool mbHasAutomaticNextSlide;\n\n struct ShapesIterationFunc; friend struct ShapesIterationFunc;\n };\n\n typedef ::boost::shared_ptr< ::presentation::internal::Slide > SlideSharedPtr;\n\n }\n}\n\n#endif \/* _SLIDESHOW_SLIDE_HXX *\/\n<commit_msg>INTEGRATION: CWS presfixes09 (1.7.16); FILE MERGED 2006\/04\/03 16:19:04 thb 1.7.16.5: #i37778# Now passing down ComponentContext to all interested parties; building a second, all-exports version of the slideshow component (to facilitate unit testing also for internal classes) - this made necessary renaming ImportFailedException to ShapeLoadFailedException (because of silly i63703); applied relevant parts of #i63770# (const-correctness); reworked view handling in such a way that views are now kept in one central repository (and are not duplicated across all interested objects); moved code from namespace presentation to namespace slideshow 2006\/03\/24 18:23:37 thb 1.7.16.4: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006\/03\/23 17:22:45 thb 1.7.16.3: #i49357# Changed manual noncopyable boiler plate to boost::noncopyable 2006\/03\/15 15:22:24 thb 1.7.16.2: #i49357# Removed external include guards from all non-export headers (and from the cxx files, anyway) 2006\/03\/06 22:14:36 thb 1.7.16.1: #i53194# #i55294# #i59324# Overhauled IntrinsicAnimationActivity; fixes GIF animation import; corrected rehearse timings sprite size; several cosmetic changes (removed external header guards); prepared scene for sprite prio<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: slide.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2006-12-13 16:02: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 _SLIDESHOW_SLIDE_HXX\n#define _SLIDESHOW_SLIDE_HXX\n\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#include <com\/sun\/star\/drawing\/XDrawPage.hpp>\n\n#include <cppcanvas\/spritecanvas.hxx>\n\n#include <basegfx\/vector\/b2isize.hxx>\n\n#include \"unoview.hxx\"\n#include \"event.hxx\"\n#include \"layermanager.hxx\"\n#include \"userpaintoverlay.hxx\"\n#include \"slideanimations.hxx\"\n#include \"slidebitmap.hxx\"\n#include \"shapeeventbroadcaster.hxx\"\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/utility.hpp>\n#include <boost\/optional.hpp>\n\n#include <vector>\n#include <utility>\n\n\/* Definition of Slide class *\/\n\nnamespace slideshow\n{\n namespace internal\n {\n class EventQueue;\n class ActivitiesQueue;\n class UserEventQueue;\n\n typedef ::boost::shared_ptr< class Slide > SlideSharedPtr;\n\n class Slide : private boost::noncopyable,\n public ViewEventHandler\n {\n public:\n \/** Construct from XDrawPage\n\n Prefetches shapes from draw page, thus might take some\n time. The Slide object generally works in XDrawPage\n model coordinates, that is, the page will have the\n width and height as specified in the XDrawPage's\n property set. The top, left corner of the page will be\n rendered at (0,0) in the given canvas' view coordinate\n system.\n *\/\n static SlideSharedPtr create( const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage >& xDrawPage,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XAnimationNode >& xRootNode,\n EventQueue& rEventQueue,\n ActivitiesQueue& rActivitiesQueue,\n EventMultiplexer& rEventMultiplexer,\n UserEventQueue& rUserEventQueue,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XComponentContext >& xContext,\n const UnoViewContainer& rViewContainer );\n ~Slide();\n\n \/\/ ViewEventHandler\n virtual void viewAdded( const UnoViewSharedPtr& rView );\n virtual void viewRemoved( const UnoViewSharedPtr& rView );\n virtual void viewChanged( const UnoViewSharedPtr& rView );\n\n \/** Add the given listener for the given shape.\n\n This method implements the addShapeEventListener\n method of the XSlideShow interface. The given listener\n is called, whenever a user clicks on the shape. If the\n shape is not contained in this slide, this method does\n nothing.\n *\/\n void addShapeEventListener( const ::com::sun::star::uno::Reference<\n ::com::sun::star::presentation::XShapeEventListener >& xListener,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XShape >& xShape );\n\n \/** Revoke the given listener for the given shape.\n\n This method implements the removeShapeEventListener\n method of the XSlideShow interface.\n *\/\n void removeShapeEventListener( const ::com::sun::star::uno::Reference<\n ::com::sun::star::presentation::XShapeEventListener >& xListener,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XShape >& xShape );\n\n \/** Control intrinsic animation behaviour\n\n @param bImageAnimationsAllowed\n When true, GIF and drawing layer animations will be\n shown. When false, those shapes have no intrinsic\n animation.\n *\/\n void setImageAnimationsAllowed( bool bImageAnimationsAllowed );\n\n \/** Set the mouse cursor for a given shape.\n\n This method implements the setShapeCursor method of\n the XSlideShow interface. Whenever the mouse hovers\n over the given shape, the specified mouse cursor will\n be shown. To reset the mouse cursor to the default,\n specify awt::SystemPointer::ARROW.\n *\/\n void setShapeCursor( const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XShape >& xShape,\n sal_Int16 nPointerShape );\n\n \/** Prepares to show slide.\n\n Call this method to reduce the timeout show(), and\n getInitialSlideBitmap() need to complete. If\n prefetchShow() is not called explicitely, the named\n methods will call it implicitely.\n *\/\n bool prefetchShow();\n\n \/** Paint the slide on given view, without any animation effects\n *\/\n bool paint( const UnoViewSharedPtr& rView );\n\n \/** Shows the slide on all registered views\n *\/\n bool show();\n\n \/** Force-end the slide show.\n *\/\n void end();\n\n \/** Query whether this slide is currently showing.\n\n @return true, if this slide is currently showing\n (i.e. show() was called more often than end()).\n *\/\n bool isShowing() const;\n\n \/** Query whether the slide has animations at all\n\n If the slide doesn't have animations, show() is\n equivalent to paint(). If an event is registered with\n registerSlideEndEvent(), this event will be\n immediately activated at the end of the show() method.\n\n @return true, if this slide has animations, false\n otherwise\n *\/\n bool isAnimated();\n\n \/** Request bitmap for current slide appearance.\n\n The bitmap returned by this method is dependent on the\n current state of the slide and the contained\n animations. A newly generated slide will return the\n initial slide content here (e.g. with all 'appear'\n effect shapes invisible), a slide whose effects are\n currently running will return a bitmap corresponding\n to the current position on the animation timeline, and\n a slide whose effects have all been run will generate\n a bitmap with the final slide appearance (e.g. with\n all 'hide' effect shapes invisible).\n\n @param rView\n View to retrieve bitmap for (note that the bitmap will\n have device-pixel equivalence to the content that\n would have been rendered onto the given view). Note\n that the view must have been added to this slide\n before via viewAdded().\n *\/\n \/\/ TODO(F2): Rework SlideBitmap to no longer be based on XBitmap,\n \/\/ but on canvas-independent basegfx bitmaps\n SlideBitmapSharedPtr getCurrentSlideBitmap( const UnoViewSharedPtr& rView );\n\n \/** Query the slide, whether next slide should appear\n automatically.\n\n @return true, if next slide should be displayed\n automatically. When false is returned, the user is\n required to click to have the next slide shown.\n *\/\n bool hasAutomaticNextSlide() const;\n\n \/** Query the slide for the timeout, until the next slide\n is automatically shown.\n\n This value is undefined, should\n hasAutomaticNextSlide() return false.\n\n @return a timeout in seconds, for which to delay the\n display of the next slide.\n *\/\n double getAutomaticNextSlideTimeout() const;\n\n \/** Control the user paint mode.\n\n The user paint mode lets the user paint on this slide\n with the given color, when pressing down the\n mousebutton.\n *\/\n void setUserPaintColor( boost::optional<RGBColor> const& rColor );\n\n \/\/\/ Query the XDrawPage's size\n basegfx::B2ISize getSlideSize() const;\n\n \/\/\/ Get size of the slide in device coordinates for given view\n ::basegfx::B2ISize getSlideSizePixel(\n UnoViewSharedPtr const & pView ) const;\n\n \/\/\/ Gets the underlying API page\n ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage > const&\n getXDrawPage() const { return mxDrawPage; }\n\n \/\/\/ Gets the animation node.\n ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XAnimationNode > const&\n getXAnimationNode() const { return mxRootNode; }\n\n private:\n Slide( const ::com::sun::star::uno::Reference<\n ::com::sun::star::drawing::XDrawPage >& xDrawPage,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XAnimationNode >& xRootNode,\n EventQueue& rEventQueue,\n ActivitiesQueue& rActivitiesQueue,\n EventMultiplexer& rEventMultiplexer,\n UserEventQueue& rUserEventQueue,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XComponentContext >& xContext,\n const UnoViewContainer& rViewContainer );\n\n void enablePaintOverlay();\n void disablePaintOverlay();\n\n \/\/\/ Set all Shapes to their initial attributes for slideshow\n bool applyInitialShapeAttributes( const ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XAnimationNode >& xRootAnimationNode );\n\n \/\/\/ Renders current slide content to bitmap\n SlideBitmapSharedPtr createCurrentSlideBitmap(\n const UnoViewSharedPtr& rView,\n ::basegfx::B2ISize const & rSlideSize );\n\n \/\/\/ Prefetch all shapes (not the animations)\n bool prefetchShapes();\n\n \/\/\/ Prefetch show, but don't call applyInitialShapeAttributes()\n bool implPrefetchShow();\n\n \/\/\/ Query the rectangle covered by the slide\n ::basegfx::B2DRectangle getSlideRect() const;\n\n \/\/\/ Start GIF and other intrinsic shape animations\n void endIntrinsicAnimations();\n\n \/\/\/ End GIF and other intrinsic shape animations\n void startIntrinsicAnimations();\n\n\n \/\/ Types\n \/\/ =====\n\n enum SlideAnimationState\n {\n CONSTRUCTING_STATE=0,\n INITIAL_STATE=1,\n SHOWING_STATE=2,\n FINAL_STATE=3,\n SlideAnimationState_NUM_ENTRIES=4\n };\n\n typedef std::vector< SlideBitmapSharedPtr > VectorOfSlideBitmaps;\n \/** Vector of slide bitmaps.\n\n Since the bitmap content is sensitive to animation\n effects, we have an inner vector containing a distinct\n bitmap for each of the SlideAnimationStates.\n *\/\n typedef ::std::vector< std::pair< UnoViewSharedPtr,\n VectorOfSlideBitmaps > > VectorOfVectorOfSlideBitmaps;\n\n\n \/\/ Member variables\n \/\/ ================\n\n \/\/\/ The page model object\n const com::sun::star::uno::Reference<\n com::sun::star::drawing::XDrawPage > mxDrawPage;\n const com::sun::star::uno::Reference<\n com::sun::star::animations::XAnimationNode > mxRootNode;\n\n \/\/\/ Contains common objects needed throughout the slideshow\n SlideShowContext maContext;\n\n ::boost::shared_ptr<ShapeEventBroadcaster> mpEventBroadcaster;\n\n \/\/\/ Handles the animation and event generation for us\n SlideAnimations maAnimations;\n\n ::boost::optional<RGBColor> maUserPaintColor;\n UserPaintOverlaySharedPtr mpPaintOverlay;\n\n \/\/\/ Bitmaps with slide content at various states\n VectorOfVectorOfSlideBitmaps maSlideBitmaps;\n\n \/\/\/ Timeout for automatic next slide display\n double mnNextSlideTimeout;\n\n SlideAnimationState meAnimationState;\n\n \/\/\/ True, when intrinsic shape animations are allowed\n bool mbImageAnimationsAllowed;\n\n \/\/\/ True, if initial load of all page shapes succeeded\n bool mbShapesLoaded;\n\n \/\/\/ True, if initial load of all animation info succeeded\n bool mbShowLoaded;\n\n \/** True, if this slide is not static.\n\n If this slide has animated content, this variable wiil\n be true, and false otherwise.\n *\/\n bool mbHaveAnimations;\n\n \/** True, if this slide has a main animation sequence.\n\n If this slide has animation content, which in turn has\n a main animation sequence (which must be fully run\n before EventMultiplexer::notifySlideAnimationsEnd() is\n called), this member is true.\n *\/\n bool mbMainSequenceFound;\n\n \/** When true, next slide should display without further\n user interaction.\n *\/\n bool mbHasAutomaticNextSlide;\n\n struct ShapesIterationFunc; friend struct ShapesIterationFunc;\n };\n }\n}\n\n#endif \/* _SLIDESHOW_SLIDE_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"BrowserManager.h\"\r\n#include <windows.h>\r\n#include <objbase.h>\r\n\r\nint APIENTRY _tWinMain(HINSTANCE hInstance,\r\n\tHINSTANCE hPrevInstance,\r\n\tLPTSTR lpCmdLine,\r\n\tint nCmdShow)\r\n{\r\n\tint result = 0;\r\n\tHRESULT Hr = ::CoInitialize(NULL);\r\n\tif(FAILED(Hr)) return 0;\r\n\r\n\tDuiLib::CPaintManagerUI::SetInstance(hInstance);\r\n\tDuiLib::CPaintManagerUI::SetResourceType(DuiLib::UILIB_ZIPRESOURCE);\r\n\tDuiLib::CPaintManagerUI::SetResourcePath(DuiLib::CPaintManagerUI::GetInstancePath());\r\n\tDuiLib::CPaintManagerUI::SetResourceZip(MAKEINTRESOURCE(IDR_ZIPRES), _T(\"ZIPRES\"));\r\n\t\r\n\tCefMainArgs main_args(hInstance);\n\tCefRefPtr<CefApp> app;\r\n\tCefSettings settings;\/\/ Specify CEF global settings here.\r\n\tvoid* sandbox_info = NULL;\r\n#ifdef CEF_USE_SANDBOX\r\n CefScopedSandboxInfo scoped_sandbox;\r\n sandbox_info = scoped_sandbox.sandbox_info();\r\n#else\r\n\tsettings.no_sandbox = true;\r\n#endif\r\n\t\/\/CefRefPtr<Browser::ClientAppBrowser> app(new Browser::ClientAppBrowser);\r\n\tCefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();\n app = new Browser::ClientAppBrowser();\r\n\tcommand_line->InitFromString(::GetCommandLineW());\r\n\tconst std::string& process_type = command_line->GetSwitchValue(\"type\");\r\n\n\n\n\t\/\/ Execute the secondary process, if any.\r\n\tint exit_code = CefExecuteProcess(main_args, app, sandbox_info);\r\n\tif (exit_code >= 0)\r\n\t\treturn exit_code;\r\n\r\n\tWCHAR szBuffer[MAX_PATH];\r\n\t::ZeroMemory(&szBuffer, sizeof(szBuffer));\r\n\tGetTempPathW(MAX_PATH,szBuffer);\r\n\tstd::wstring sBuffer = szBuffer;\r\n\tsBuffer += L\"Browser\";\r\n\tCefString(&settings.cache_path).FromWString(sBuffer);\r\n\r\n\tsettings.ignore_certificate_errors = true;\r\n\r\n\t\/\/settings.command_line_args_disabled = true;\r\n\r\n\tCefString(&settings.locale).FromASCII(\"zh-CN\");\r\n\r\n\t\/\/ Initialize CEF.\r\n\tCefInitialize(main_args, settings, app, sandbox_info);\r\n\n\tscoped_ptr<Browser::BrowserManager> pBrowserManager(new Browser::BrowserManager(true));\r\n\tscoped_ptr<Browser::MessageLoop> message_loop;\n\tmessage_loop.reset(new Browser::MessageLoop);\r\n\r\n\tpBrowserManager->CreateRootWindow(true,false,CefRect(),_T(\"https:\/\/www.hao123.com\/\"));\r\n\r\n\t\/\/DuiLib::CPaintManagerUI::MessageLoop();\n\tresult = message_loop->Run();\r\n\r\n\tDuiLib::CPaintManagerUI::Term();\r\n\r\n\t\/\/ Shut down CEF.\r\n\tCefShutdown();\r\n\t\n\tmessage_loop.reset();\r\n\r\n\t::CoUninitialize();\r\n\treturn result;\r\n}\r\n<commit_msg>Release版不输出日志<commit_after>#include \"stdafx.h\"\n#include \"BrowserManager.h\"\r\n#include <windows.h>\r\n#include <objbase.h>\r\n\r\nint APIENTRY _tWinMain(HINSTANCE hInstance,\r\n\tHINSTANCE hPrevInstance,\r\n\tLPTSTR lpCmdLine,\r\n\tint nCmdShow)\r\n{\r\n\tint result = 0;\r\n\tHRESULT Hr = ::CoInitialize(NULL);\r\n\tif(FAILED(Hr)) return 0;\r\n\r\n\tDuiLib::CPaintManagerUI::SetInstance(hInstance);\r\n\tDuiLib::CPaintManagerUI::SetResourceType(DuiLib::UILIB_ZIPRESOURCE);\r\n\tDuiLib::CPaintManagerUI::SetResourcePath(DuiLib::CPaintManagerUI::GetInstancePath());\r\n\tDuiLib::CPaintManagerUI::SetResourceZip(MAKEINTRESOURCE(IDR_ZIPRES), _T(\"ZIPRES\"));\r\n\t\r\n\tCefMainArgs main_args(hInstance);\n\tCefRefPtr<CefApp> app;\r\n\tCefSettings settings;\/\/ Specify CEF global settings here.\r\n\tvoid* sandbox_info = NULL;\r\n#ifdef CEF_USE_SANDBOX\r\n CefScopedSandboxInfo scoped_sandbox;\r\n sandbox_info = scoped_sandbox.sandbox_info();\r\n#else\r\n\tsettings.no_sandbox = true;\r\n#endif\r\n\t\/\/CefRefPtr<Browser::ClientAppBrowser> app(new Browser::ClientAppBrowser);\r\n\tCefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();\n app = new Browser::ClientAppBrowser();\r\n\tcommand_line->InitFromString(::GetCommandLineW());\r\n\tconst std::string& process_type = command_line->GetSwitchValue(\"type\");\r\n\n\t\/\/ Execute the secondary process, if any.\r\n\tint exit_code = CefExecuteProcess(main_args, app, sandbox_info);\r\n\tif (exit_code >= 0)\r\n\t\treturn exit_code;\r\n\r\n\tWCHAR szBuffer[MAX_PATH];\r\n\t::ZeroMemory(&szBuffer, sizeof(szBuffer));\r\n\tGetTempPathW(MAX_PATH,szBuffer);\r\n\tstd::wstring sBuffer = szBuffer;\r\n\tsBuffer += L\"Browser\";\r\n\tCefString(&settings.cache_path).FromWString(sBuffer);\r\n\r\n\tsettings.ignore_certificate_errors = true;\r\n\r\n\t\/\/settings.command_line_args_disabled = true;\r\n\r\n\tCefString(&settings.locale).FromASCII(\"zh-CN\");\r\n\r\n#ifndef _DEBUG\r\n\tsettings.log_severity = LOGSEVERITY_DISABLE;\r\n#endif\r\n\r\n\t\/\/ Initialize CEF.\r\n\tCefInitialize(main_args, settings, app, sandbox_info);\r\n\n\tscoped_ptr<Browser::BrowserManager> pBrowserManager(new Browser::BrowserManager(true));\r\n\tscoped_ptr<Browser::MessageLoop> message_loop;\n\tmessage_loop.reset(new Browser::MessageLoop);\r\n\r\n\tpBrowserManager->CreateRootWindow(true,false,CefRect(),_T(\"https:\/\/www.hao123.com\/\"));\r\n\r\n\t\/\/DuiLib::CPaintManagerUI::MessageLoop();\n\tresult = message_loop->Run();\r\n\r\n\tDuiLib::CPaintManagerUI::Term();\r\n\r\n\t\/\/ Shut down CEF.\r\n\tCefShutdown();\r\n\t\n\tmessage_loop.reset();\r\n\r\n\t::CoUninitialize();\r\n\treturn result;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"ScriptLoader.h\"\n\n#include <Server_Common\/Logging\/Logger.h>\n#include <Server_Common\/Config\/XMLConfig.h>\n#include \"ServerZone.h\"\n\n#include <boost\/format.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\nextern Core::Logger g_log;\nextern Core::ServerZone g_serverZone;\n\nnamespace fs = boost::filesystem;\n\nCore::Scripting::ScriptLoader::ScriptLoader()\n{}\n\nconst std::string Core::Scripting::ScriptLoader::getModuleExtension()\n{\n#ifdef _WIN32\n return \".dll\";\n#elif __APPLE__\n return \".dylib\";\n#else\n return \".so\";\n#endif\n}\n\nbool Core::Scripting::ScriptLoader::unloadModule( ModuleHandle handle )\n{\n#ifdef _WIN32\n bool success = FreeLibrary( handle ) != 0;\n#else\n bool success = dlclose( handle ) == 0;\n#endif\n\n if( !success )\n {\n g_log.error( \"Failed to unload module @ 0x\" + boost::str( boost::format( \"%|08X|\" ) % handle ) );\n\n return false;\n }\n\n g_log.debug( \"Unloaded module @ 0x\" + boost::str( boost::format( \"%|08X|\" ) % handle ) );\n\n return true;\n}\n\nCore::Scripting::ScriptInfo* Core::Scripting::ScriptLoader::loadModule( const std::string& path )\n{\n boost::filesystem::path f( path );\n\n if ( isModuleLoaded( f.stem().string() ) )\n {\n g_log.error( \"Unable to load module '\" + f.stem().string() + \"' as it is already loaded\" );\n return nullptr;\n }\n\n \/\/ copy to temp dir\n fs::path cacheDir( f.parent_path() \/= g_serverZone.getConfig()->getValue< std::string >( \"Settings.General.Scripts.CachePath\", \".\/cache\/\" ) );\n fs::create_directories( cacheDir );\n fs::path dest( cacheDir \/= f.filename().string() );\n\n if ( fs::exists( dest ) )\n {\n fs::remove( dest );\n }\n\n fs::copy_file( f, dest );\n\n#ifdef _WIN32\n ModuleHandle handle = LoadLibrary( dest.string().c_str() );\n#else\n ModuleHandle handle = dlopen( dest.string().c_str(), RTLD_LAZY );\n#endif\n\n if( !handle )\n {\n g_log.error( \"Failed to load module from: \" + path );\n\n return nullptr;\n }\n\n g_log.info( \"Loaded module '\" + f.filename().string() + \"' @ 0x\" + boost::str( boost::format( \"%|08X|\" ) % handle ) );\n\n auto info = new ScriptInfo;\n info->handle = handle;\n info->library_name = f.stem().string();\n info->cache_path = dest.string();\n info->library_path = f.string();\n\n m_scriptMap.insert( std::make_pair( f.stem().string(), info ) );\n\n return info;\n}\n\nScriptObject* Core::Scripting::ScriptLoader::getScriptObject( ModuleHandle handle )\n{\n using getScript = ScriptObject*(*)();\n\n#ifdef _WIN32\n getScript func = reinterpret_cast< getScript >( GetProcAddress( handle, \"getScript\" ) );\n#else\n getScript func = reinterpret_cast< getScript >( dlsym( handle, \"getScript\" ) );\n#endif\n\n if( func )\n {\n auto ptr = func();\n\n g_log.debug( \"got ScriptObject @ 0x\" + boost::str( boost::format( \"%|08X|\" ) % ptr ) );\n g_log.debug( \"script info -> name: \" + std::string( ptr->getName() ) + \", id: \" + std::to_string( ptr->getId() ) );\n\n return ptr;\n }\n else\n return nullptr;\n}\n\nbool Core::Scripting::ScriptLoader::unloadScript( Core::Scripting::ScriptInfo* info )\n{\n return unloadScript( info->handle );\n}\n\nbool Core::Scripting::ScriptLoader::unloadScript( ModuleHandle handle )\n{\n for( auto it = m_scriptMap.begin(); it != m_scriptMap.end(); ++it )\n {\n if( it->second->handle == handle )\n {\n auto info = it->second;\n m_scriptMap.erase( it );\n\n if( unloadModule( handle ) )\n {\n \/\/ remove cached file\n fs::remove( info->cache_path );\n\n delete info;\n\n return true;\n }\n\n g_log.error( \"failed to unload module: \" + info->library_name );\n\n return false;\n }\n }\n\n return false;\n}\n\nbool Core::Scripting::ScriptLoader::isModuleLoaded( std::string name )\n{\n for( auto it = m_scriptMap.begin(); it != m_scriptMap.end(); ++it )\n {\n if( boost::iequals( it->second->library_name, name ) )\n return true;\n }\n\n return false;\n}\n\nCore::Scripting::ScriptInfo* Core::Scripting::ScriptLoader::getScriptInfo( std::string name )\n{\n for( auto it = m_scriptMap.begin(); it != m_scriptMap.end(); ++it )\n {\n if( it->second->script_name == name )\n {\n return it->second;\n }\n }\n\n return nullptr;\n}\n\nvoid Core::Scripting::ScriptLoader::findScripts( std::set< Core::Scripting::ScriptInfo* >& scripts, const std::string& search )\n{\n for( auto it = m_scriptMap.begin(); it != m_scriptMap.end(); ++it )\n {\n if( it->second->script_name.find( search ) != std::string::npos )\n {\n scripts.insert( it->second );\n }\n }\n}<commit_msg>maybe, just maybe, it builds on travis now<commit_after>#include \"ScriptLoader.h\"\n\n#include <Server_Common\/Logging\/Logger.h>\n#include <Server_Common\/Config\/XMLConfig.h>\n#include \"ServerZone.h\"\n\n#include <boost\/format.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <experimental\/filesystem>\n\nextern Core::Logger g_log;\nextern Core::ServerZone g_serverZone;\n\nnamespace fs = std::experimental::filesystem;\n\nCore::Scripting::ScriptLoader::ScriptLoader()\n{}\n\nconst std::string Core::Scripting::ScriptLoader::getModuleExtension()\n{\n#ifdef _WIN32\n return \".dll\";\n#elif __APPLE__\n return \".dylib\";\n#else\n return \".so\";\n#endif\n}\n\nbool Core::Scripting::ScriptLoader::unloadModule( ModuleHandle handle )\n{\n#ifdef _WIN32\n bool success = FreeLibrary( handle ) != 0;\n#else\n bool success = dlclose( handle ) == 0;\n#endif\n\n if( !success )\n {\n g_log.error( \"Failed to unload module @ 0x\" + boost::str( boost::format( \"%|08X|\" ) % handle ) );\n\n return false;\n }\n\n g_log.debug( \"Unloaded module @ 0x\" + boost::str( boost::format( \"%|08X|\" ) % handle ) );\n\n return true;\n}\n\nCore::Scripting::ScriptInfo* Core::Scripting::ScriptLoader::loadModule( const std::string& path )\n{\n fs::path f( path );\n\n if ( isModuleLoaded( f.stem().string() ) )\n {\n g_log.error( \"Unable to load module '\" + f.stem().string() + \"' as it is already loaded\" );\n return nullptr;\n }\n\n \/\/ copy to temp dir\n fs::path cacheDir( f.parent_path() \/= g_serverZone.getConfig()->getValue< std::string >( \"Settings.General.Scripts.CachePath\", \".\/cache\/\" ) );\n fs::create_directories( cacheDir );\n fs::path dest( cacheDir \/= f.filename().string() );\n\n if ( fs::exists( dest ) )\n {\n fs::remove( dest );\n }\n\n fs::copy_file( f, dest );\n\n#ifdef _WIN32\n ModuleHandle handle = LoadLibrary( dest.string().c_str() );\n#else\n ModuleHandle handle = dlopen( dest.string().c_str(), RTLD_LAZY );\n#endif\n\n if( !handle )\n {\n g_log.error( \"Failed to load module from: \" + path );\n\n return nullptr;\n }\n\n g_log.info( \"Loaded module '\" + f.filename().string() + \"' @ 0x\" + boost::str( boost::format( \"%|08X|\" ) % handle ) );\n\n auto info = new ScriptInfo;\n info->handle = handle;\n info->library_name = f.stem().string();\n info->cache_path = dest.string();\n info->library_path = f.string();\n\n m_scriptMap.insert( std::make_pair( f.stem().string(), info ) );\n\n return info;\n}\n\nScriptObject* Core::Scripting::ScriptLoader::getScriptObject( ModuleHandle handle )\n{\n using getScript = ScriptObject*(*)();\n\n#ifdef _WIN32\n getScript func = reinterpret_cast< getScript >( GetProcAddress( handle, \"getScript\" ) );\n#else\n getScript func = reinterpret_cast< getScript >( dlsym( handle, \"getScript\" ) );\n#endif\n\n if( func )\n {\n auto ptr = func();\n\n g_log.debug( \"got ScriptObject @ 0x\" + boost::str( boost::format( \"%|08X|\" ) % ptr ) );\n g_log.debug( \"script info -> name: \" + std::string( ptr->getName() ) + \", id: \" + std::to_string( ptr->getId() ) );\n\n return ptr;\n }\n else\n return nullptr;\n}\n\nbool Core::Scripting::ScriptLoader::unloadScript( Core::Scripting::ScriptInfo* info )\n{\n return unloadScript( info->handle );\n}\n\nbool Core::Scripting::ScriptLoader::unloadScript( ModuleHandle handle )\n{\n for( auto it = m_scriptMap.begin(); it != m_scriptMap.end(); ++it )\n {\n if( it->second->handle == handle )\n {\n auto info = it->second;\n m_scriptMap.erase( it );\n\n if( unloadModule( handle ) )\n {\n \/\/ remove cached file\n fs::remove( info->cache_path );\n\n delete info;\n\n return true;\n }\n\n g_log.error( \"failed to unload module: \" + info->library_name );\n\n return false;\n }\n }\n\n return false;\n}\n\nbool Core::Scripting::ScriptLoader::isModuleLoaded( std::string name )\n{\n for( auto it = m_scriptMap.begin(); it != m_scriptMap.end(); ++it )\n {\n if( boost::iequals( it->second->library_name, name ) )\n return true;\n }\n\n return false;\n}\n\nCore::Scripting::ScriptInfo* Core::Scripting::ScriptLoader::getScriptInfo( std::string name )\n{\n for( auto it = m_scriptMap.begin(); it != m_scriptMap.end(); ++it )\n {\n if( it->second->script_name == name )\n {\n return it->second;\n }\n }\n\n return nullptr;\n}\n\nvoid Core::Scripting::ScriptLoader::findScripts( std::set< Core::Scripting::ScriptInfo* >& scripts, const std::string& search )\n{\n for( auto it = m_scriptMap.begin(); it != m_scriptMap.end(); ++it )\n {\n if( it->second->script_name.find( search ) != std::string::npos )\n {\n scripts.insert( it->second );\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n kopete.cpp - description\n -------------------\n begin : Wed Dec 26 03:12:10 CLST 2001\n copyright : (C) 2001 by Duncan Mac-Vicar Prett\n email : duncan@puc.cl\n ***************************************************************************\/\n\n\/***************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include <qvaluelist.h>\n#include <qlist.h>\n#include <qlayout.h>\n\n#include <kconfig.h>\n#include <kdebug.h>\n#include <kcrash.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n\n#include <kopete.h>\n#include <preferencesdialog.h>\n#include <kopetewindow.h>\n#include \"plugin.h\"\n#include \"pluginloader.h\"\n#include \"pluginmodule.h\"\n#include <addwizardimpl.h>\n#include \"systemtray.h\"\n\nclass Plugins;\n\nKopete::Kopete(): KUniqueApplication(true, true, true)\n{\n\t\/\/plugins = new PluginManager;\n\tallConnected = false;\n\n\tmLibraryLoader = new LibraryLoader;\n\tmIconLoader = KGlobal::iconLoader();\n\tmPref=new PreferencesDialog;\n\tPlugins *blah = new Plugins(this);\n\n\tmainwindow = new KopeteWindow;\n\tsetMainWidget(mainwindow);\n\tmainwindow->statusBar()->show();\n\n \tmPref->hide();\n\n\tKConfig *config=KGlobal::config();\n\tconfig->setGroup(\"\");\n\t\/* Ups! the user dont have plugins selected. *\/\n\tif (!config->hasKey(\"Modules\"))\n\t{\n\t\tQStringList modules;\n\t\tmodules.append(\"icq.plugin\");\n\t\tmodules.append(\"msn.plugin\");\n\t\tconfig->writeEntry(\"Modules\", modules);\n\t}\n\t\/* Ok, load saved plugins *\/\n\tloadPlugins();\n\ttray = new KopeteSystemTray();\n\n}\n\nKopete::~Kopete()\n{\n\tdelete mPref;\n\tdelete mLibraryLoader;\n\tdelete mainwindow;\n\n\t\/\/ Only use this if cant find crash cause :-)\n\t\/\/KCrash::setCrashHandler(Kopete::cleverKCrashHack);\n}\nvoid Kopete::slotPreferences()\n{\n mPref->show();\n mPref->raise();\n}\n\/** No descriptions *\/\nvoid Kopete::slotExit()\n{\n\tquit();\n}\n\nKopeteSystemTray *Kopete::systemTray()\n{\n\treturn tray;\n}\n\n\/** No descriptions *\/\nvoid Kopete::readOptions()\n{\n\t\/*\n KConfig *config = KGlobal::config();\n config->setGroup(\"General\");\n\tvisible = config->readBoolEntry(\"Visible\",true);\n\tQSize size = config->readSizeEntry(\"Geometry\");\n config->readBoolEntry(\"Idle Detection\",false);\n config->readNumEntry(\"MaxIdle\",15);\n\n if(!size.isEmpty())\n {\n resize(size);\n }\n QPoint pos=config->readPointEntry(\"Position\");\n if(!pos.isNull())\n {\n move(pos);\n }\t\n config->setGroup(\"ICQ\");\n QString icqNick = config->readEntry( \"icqNick\" );\n QString icqUIN = config->readEntry( \"icqUIN\" );\n\tQString icqPass = config->readEntry( \"icqPass\" );\n\tconfig->setGroup(\"MSN\");\n QString msnNick = config->readEntry( \"msnNick\" );\n QString msnID = config->readEntry( \"msnID\" );\n\tQString msnPass = config->readEntry( \"msnPass\" );\n\n\tautoConnect=-1;\n if ( profiles.count() == 0 )\n slotSettings();\n else\n {\n \/\/Construct menu...\n for ( int i = 0 ; i < profiles.count() ; i++ )\n {\n KAction *tmpaction = new KMsnAction( profiles[i] , \/\/Name\n 0 , \/\/Accel\n this , \/\/Receiver\n SLOT(slotConnector( int ) ),\n actionCollection(),\/\/Parent (not sure...)\n profiles[i] , \/\/Internal name\n i ); \/\/ID, needed for connecting\n \/\/Add actions to the submenu\n fileConnector->insert( tmpaction );\n \/\/And add them to our list...\n actions.append( tmpaction );\n \/\/.. and make sure that they're deleted when we delete them\n actions.setAutoDelete( true );\n\n if (autoStr == profiles[i])\n\tautoConnect=i;\n }\n }\n\n\n*\/\n}\n\/** No descriptions *\/\nvoid Kopete::saveOptions(){\n}\n\n\/** Connect to all loaded protocol plugins *\/\nvoid Kopete::slotConnectAll()\n{\n\tQValueList<KopeteLibraryInfo> l = kopeteapp->libraryLoader()->loaded();\n for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)\n\t{\n\t\tkdDebug() << \"Kopete: [Connect All]: \"<<(*i).name <<\"\\n\";\n\t\tPlugin *tmpprot = (kopeteapp->libraryLoader())->mLibHash[(*i).specfile]->plugin;\t\t\t\t\n\t\tIMProtocol *prot = static_cast<IMProtocol*>(tmpprot);\n\t\tif ( !(prot->isConnected()))\n\t\t{\n\t\t\tprot->Connect();\n\t\t}\n\t}\n\tallConnected = true;\n\tmainWindow()->actionConnect->setEnabled(false);\n mainWindow()->actionDisconnect->setEnabled(true);\n}\n\n\/** Connect to all loaded protocol plugins *\/\nvoid Kopete::slotDisconnectAll()\n{\n\tQValueList<KopeteLibraryInfo> l = kopeteapp->libraryLoader()->loaded();\n for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)\n\t{\n\t\tkdDebug() << \"Kopete: [Disconnect All]: \"<<(*i).name <<\"\\n\";\n\t\tPlugin *tmpprot = (kopeteapp->libraryLoader())->mLibHash[(*i).specfile]->plugin;\t\t\t\t\n\t\tIMProtocol *prot = static_cast<IMProtocol*>(tmpprot);\n\t\tif (prot->isConnected())\n\t\t{\n\t\t\tprot->Disconnect();\n\t\t}\n\t}\n\tallConnected = false;\n\tmainWindow()->actionConnect->setEnabled(true);\n mainWindow()->actionDisconnect->setEnabled(false);\n}\n\n\/** No descriptions *\/\nvoid Kopete::slotAboutPlugins()\n{\n\tAboutPlugins *aboutPl;\n\taboutPl = new AboutPlugins(mainwindow);\n\taboutPl->show();\n\n}\n\/** Add a contact through Wizard *\/\nvoid Kopete::slotAddContact()\n{\n\tAddWizardImpl *tmpdialog = new AddWizardImpl(this->mainWindow());\n\ttmpdialog->show();\n}\n\n\/** No descriptions *\/\nvoid Kopete::slotSetAway()\n{\n}\/** No descriptions *\/\nvoid Kopete::initPlugins()\n{\n\t\n}\n\/** No descriptions *\/\nvoid Kopete::loadPlugins()\n{\n\tmLibraryLoader->loadAll();\n}\n\nvoid Kopete::cleverKCrashHack(int)\n{\n\t\/\/ do nothing\n\n\t\/\/ Understand that the KDE libraries have a memory leak, and\n\t\/\/ the playlist cannot be unloaded without causing a crash\n\t\/\/ in QApplication::windowMapper() or something similar.\n\t\/\/ this is just to prevent the KCrash window from appearing\n\t\/\/ and bugging the user regularly\n\n\t\/\/ someone fix the libraries.\n\tkdDebug() << \"Crashed.\\n\" << endl;\n\t_exit(255);\n}\n\/** No descriptions *\/\nKStatusBar *Kopete::statusBar()\n{\n\treturn mainwindow->statusBar();\n}\n\/** No descriptions *\/\nContactList *Kopete::contactList()\n{\n\treturn mainwindow->contactlist;\n\n}\n<commit_msg>- Systray should be created before plugins get loaded if not, plugins are not able to add menus to it<commit_after>\/***************************************************************************\n kopete.cpp - description\n -------------------\n begin : Wed Dec 26 03:12:10 CLST 2001\n copyright : (C) 2001 by Duncan Mac-Vicar Prett\n email : duncan@puc.cl\n ***************************************************************************\/\n\n\/***************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include <qvaluelist.h>\n#include <qlist.h>\n#include <qlayout.h>\n\n#include <kconfig.h>\n#include <kdebug.h>\n#include <kcrash.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n\n#include <kopete.h>\n#include <preferencesdialog.h>\n#include <kopetewindow.h>\n#include \"plugin.h\"\n#include \"pluginloader.h\"\n#include \"pluginmodule.h\"\n#include <addwizardimpl.h>\n#include \"systemtray.h\"\n\nclass Plugins;\n\nKopete::Kopete(): KUniqueApplication(true, true, true)\n{\n\t\/\/plugins = new PluginManager;\n\tallConnected = false;\n\n\tmLibraryLoader = new LibraryLoader;\n\tmIconLoader = KGlobal::iconLoader();\n\tmPref=new PreferencesDialog;\n\tPlugins *blah = new Plugins(this);\n\n\tmainwindow = new KopeteWindow;\n\tsetMainWidget(mainwindow);\n\tmainwindow->statusBar()->show();\n\n \tmPref->hide();\n\n\tKConfig *config=KGlobal::config();\n\tconfig->setGroup(\"\");\n\t\/* Ups! the user dont have plugins selected. *\/\n\tif (!config->hasKey(\"Modules\"))\n\t{\n\t\tQStringList modules;\n\t\tmodules.append(\"icq.plugin\");\n\t\tmodules.append(\"msn.plugin\");\n\t\tconfig->writeEntry(\"Modules\", modules);\n\t}\n\ttray = new KopeteSystemTray();\n\t\/* Ok, load saved plugins *\/\n\tloadPlugins();\n}\n\nKopete::~Kopete()\n{\n\tdelete mPref;\n\tdelete mLibraryLoader;\n\tdelete mainwindow;\n\n\t\/\/ Only use this if cant find crash cause :-)\n\t\/\/KCrash::setCrashHandler(Kopete::cleverKCrashHack);\n}\nvoid Kopete::slotPreferences()\n{\n mPref->show();\n mPref->raise();\n}\n\/** No descriptions *\/\nvoid Kopete::slotExit()\n{\n\tquit();\n}\n\nKopeteSystemTray *Kopete::systemTray()\n{\n\treturn tray;\n}\n\n\/** No descriptions *\/\nvoid Kopete::readOptions()\n{\n\t\/*\n KConfig *config = KGlobal::config();\n config->setGroup(\"General\");\n\tvisible = config->readBoolEntry(\"Visible\",true);\n\tQSize size = config->readSizeEntry(\"Geometry\");\n config->readBoolEntry(\"Idle Detection\",false);\n config->readNumEntry(\"MaxIdle\",15);\n\n if(!size.isEmpty())\n {\n resize(size);\n }\n QPoint pos=config->readPointEntry(\"Position\");\n if(!pos.isNull())\n {\n move(pos);\n }\t\n config->setGroup(\"ICQ\");\n QString icqNick = config->readEntry( \"icqNick\" );\n QString icqUIN = config->readEntry( \"icqUIN\" );\n\tQString icqPass = config->readEntry( \"icqPass\" );\n\tconfig->setGroup(\"MSN\");\n QString msnNick = config->readEntry( \"msnNick\" );\n QString msnID = config->readEntry( \"msnID\" );\n\tQString msnPass = config->readEntry( \"msnPass\" );\n\n\tautoConnect=-1;\n if ( profiles.count() == 0 )\n slotSettings();\n else\n {\n \/\/Construct menu...\n for ( int i = 0 ; i < profiles.count() ; i++ )\n {\n KAction *tmpaction = new KMsnAction( profiles[i] , \/\/Name\n 0 , \/\/Accel\n this , \/\/Receiver\n SLOT(slotConnector( int ) ),\n actionCollection(),\/\/Parent (not sure...)\n profiles[i] , \/\/Internal name\n i ); \/\/ID, needed for connecting\n \/\/Add actions to the submenu\n fileConnector->insert( tmpaction );\n \/\/And add them to our list...\n actions.append( tmpaction );\n \/\/.. and make sure that they're deleted when we delete them\n actions.setAutoDelete( true );\n\n if (autoStr == profiles[i])\n\tautoConnect=i;\n }\n }\n\n\n*\/\n}\n\/** No descriptions *\/\nvoid Kopete::saveOptions(){\n}\n\n\/** Connect to all loaded protocol plugins *\/\nvoid Kopete::slotConnectAll()\n{\n\tQValueList<KopeteLibraryInfo> l = kopeteapp->libraryLoader()->loaded();\n for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)\n\t{\n\t\tkdDebug() << \"Kopete: [Connect All]: \"<<(*i).name <<\"\\n\";\n\t\tPlugin *tmpprot = (kopeteapp->libraryLoader())->mLibHash[(*i).specfile]->plugin;\t\t\t\t\n\t\tIMProtocol *prot = static_cast<IMProtocol*>(tmpprot);\n\t\tif ( !(prot->isConnected()))\n\t\t{\n\t\t\tprot->Connect();\n\t\t}\n\t}\n\tallConnected = true;\n\tmainWindow()->actionConnect->setEnabled(false);\n mainWindow()->actionDisconnect->setEnabled(true);\n}\n\n\/** Connect to all loaded protocol plugins *\/\nvoid Kopete::slotDisconnectAll()\n{\n\tQValueList<KopeteLibraryInfo> l = kopeteapp->libraryLoader()->loaded();\n for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)\n\t{\n\t\tkdDebug() << \"Kopete: [Disconnect All]: \"<<(*i).name <<\"\\n\";\n\t\tPlugin *tmpprot = (kopeteapp->libraryLoader())->mLibHash[(*i).specfile]->plugin;\t\t\t\t\n\t\tIMProtocol *prot = static_cast<IMProtocol*>(tmpprot);\n\t\tif (prot->isConnected())\n\t\t{\n\t\t\tprot->Disconnect();\n\t\t}\n\t}\n\tallConnected = false;\n\tmainWindow()->actionConnect->setEnabled(true);\n mainWindow()->actionDisconnect->setEnabled(false);\n}\n\n\/** No descriptions *\/\nvoid Kopete::slotAboutPlugins()\n{\n\tAboutPlugins *aboutPl;\n\taboutPl = new AboutPlugins(mainwindow);\n\taboutPl->show();\n\n}\n\/** Add a contact through Wizard *\/\nvoid Kopete::slotAddContact()\n{\n\tAddWizardImpl *tmpdialog = new AddWizardImpl(this->mainWindow());\n\ttmpdialog->show();\n}\n\n\/** No descriptions *\/\nvoid Kopete::slotSetAway()\n{\n}\/** No descriptions *\/\nvoid Kopete::initPlugins()\n{\n\t\n}\n\/** No descriptions *\/\nvoid Kopete::loadPlugins()\n{\n\tmLibraryLoader->loadAll();\n}\n\nvoid Kopete::cleverKCrashHack(int)\n{\n\t\/\/ do nothing\n\n\t\/\/ Understand that the KDE libraries have a memory leak, and\n\t\/\/ the playlist cannot be unloaded without causing a crash\n\t\/\/ in QApplication::windowMapper() or something similar.\n\t\/\/ this is just to prevent the KCrash window from appearing\n\t\/\/ and bugging the user regularly\n\n\t\/\/ someone fix the libraries.\n\tkdDebug() << \"Crashed.\\n\" << endl;\n\t_exit(255);\n}\n\/** No descriptions *\/\nKStatusBar *Kopete::statusBar()\n{\n\treturn mainwindow->statusBar();\n}\n\/** No descriptions *\/\nContactList *Kopete::contactList()\n{\n\treturn mainwindow->contactlist;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: RegularData1D_test.C,v 1.6 2001\/07\/10 10:38:42 oliver Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/DATATYPE\/regularData1D.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(class_name, \"$Id: RegularData1D_test.C,v 1.6 2001\/07\/10 10:38:42 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\nRegularData1D* rd_ptr;\nCHECK(TRegularData1D::TRegularData1D())\n\trd_ptr = new RegularData1D;\n\tTEST_NOT_EQUAL(rd_ptr, 0)\nRESULT\n\n\nCHECK(TRegularData1D::~TRegularData1D())\n delete rd_ptr;\nRESULT\n\n\nCHECK(TRegularData1D::BALL_CREATE(RegularData1D<T>))\n\t\nRESULT\n\n\nRegularData1D rd;\nCHECK(TRegularData1D::TRegularData1D(const TRegularData1D& data))\n\trd.setBoundaries(1.1, 2.1);\n\trd.resize(1);\n\trd[0] = 1.2;\n\tRegularData1D rd2(rd);\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 1.1)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 2.1)\n\tTEST_REAL_EQUAL(rd2[0], 1.2) \n\tTEST_EQUAL(rd2.getSize(), 1)\nRESULT\n\n\nCHECK(TRegularData1D::clear())\n\trd.clear();\n\tTEST_REAL_EQUAL(rd.getLowerBound(), 1.1)\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 2.1)\n\tTEST_EQUAL(rd.getSize(), 1)\n\tTEST_REAL_EQUAL(rd[0], 0.0)\nRESULT\n\n\nCHECK(TRegularData1D::destroy())\n\trd[0] = 2.3;\n\trd.destroy();\n\tTEST_REAL_EQUAL(rd.getLowerBound(), 0.0)\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 0.0)\n\tTEST_EQUAL(rd.getSize(), 0)\nRESULT\n\n\nCHECK(TRegularData1D::TRegularData1D& operator = (const TRegularData1D& data))\n\trd.setBoundaries(1.1, 2.1);\n\trd.resize(1);\n\trd[0] = 1.2;\n\tRegularData1D rd2 = rd;\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 1.1)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 2.1)\n\tTEST_REAL_EQUAL(rd2[0], 1.2) \n\tTEST_EQUAL(rd2.getSize(), 1)\nRESULT\n\n\nCHECK(TRegularData1D::TRegularData1D& operator = (const VectorType& data))\n\tRegularData1D::VectorType v;\n\tv.push_back(1.1);\n\tv.push_back(1.2);\n\tv.push_back(1.3);\n\tv.push_back(1.4);\n\tRegularData1D rd2;\n\trd2.setBoundaries(0.0, 1.0);\n\trd2 = v;\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 0.0)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 1.0)\n\tTEST_EQUAL(rd2.getSize(), 4)\n\tTEST_REAL_EQUAL(rd2[0], 1.1)\n\tTEST_REAL_EQUAL(rd2[1], 1.2)\n\tTEST_REAL_EQUAL(rd2[2], 1.3)\n\tTEST_REAL_EQUAL(rd2[3], 1.4)\nRESULT\n\n\nCHECK(TRegularData1D::bool operator == (const TRegularData1D& data) const )\n\trd.destroy();\n\trd.resize(4);\n\trd[0] = 1.1;\n\trd[1] = 1.2;\n\trd[2] = 1.3;\n\trd[3] = 1.4;\n\tRegularData1D rd2 = rd;\n\tTEST_EQUAL(rd == rd2, true)\n\trd2[3] = 1.41;\n\tTEST_EQUAL(rd == rd2, false)\n\trd2[3] = 1.4;\n\tTEST_EQUAL(rd == rd2, true)\n\trd.setBoundaries(1.1, 1.4);\n\tTEST_EQUAL(rd == rd2, false)\n\trd2.setBoundaries(1.1, 1.4);\n\tTEST_EQUAL(rd == rd2, true)\nRESULT\n\n\nCHECK(TRegularData1D::T& operator [] (Position index) const )\n TEST_REAL_EQUAL(rd[3], 1.4)\n\tTEST_EXCEPTION(Exception::IndexOverflow, rd[4])\nRESULT\n\n\nCHECK(TRegularData1D::T& operator [] (Position index))\n rd[3] = 1.5;\n\tTEST_REAL_EQUAL(rd[3], 1.5)\n\tTEST_EXCEPTION(Exception::IndexOverflow, rd[4] = 44.4)\nRESULT\n\n\nRegularData1D rd2;\nCHECK(TRegularData1D::getSize() const )\n TEST_EQUAL(rd.getSize(), 4)\n\tTEST_EQUAL(rd2.getSize(), 0)\nRESULT\n\n\nCHECK(TRegularData1D::getLowerBound() const )\n\trd.setBoundaries(1.1, 1.5);\n\tTEST_REAL_EQUAL(rd.getLowerBound(), 1.1)\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 0.0)\nRESULT\n\n\nCHECK(TRegularData1D::getUpperBound() const )\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 1.5)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 0.0)\nRESULT\n\n\nCHECK(TRegularData1D::setLowerBound())\n\trd.setBoundaries(-99.9, 99.9);\n\tTEST_REAL_EQUAL(rd.getLowerBound(), -99.9)\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 99.9)\n\trd.setBoundaries(99.9, -99.9);\n\tTEST_REAL_EQUAL(rd.getLowerBound(), -99.9)\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 99.9)\nRESULT\n\n\nCHECK(TRegularData1D::resize(Size new_size))\n\tTEST_EQUAL(rd.getSize(), 4)\n\trd.resize(99);\n\tTEST_EQUAL(rd.getSize(), 99)\n\tTEST_REAL_EQUAL(rd[98], 0.0)\n\trd.resize(3);\n\tTEST_EQUAL(rd.getSize(), 3)\n\tTEST_REAL_EQUAL(rd[2], 1.3)\n\tTEST_EXCEPTION(Exception::IndexOverflow, rd[3])\nRESULT\n\nCHECK(TRegularData1D::rescale(Size new_size))\n\tTRegularData1D<float>\tdata;\n\tTEST_EQUAL(data.getSize(), 0)\n\tdata.rescale(1);\n\tTEST_EQUAL(data.getSize(), 1)\n\tTEST_EQUAL(data[0], 0.0)\n\tdata[0] = 2.0;\n\tdata.rescale(2);\n\tTEST_EQUAL(data.getSize(), 2)\n\tTEST_EQUAL(data[0], 2.0)\n\tTEST_EQUAL(data[0], 2.0)\n\tdata[0] = 1.0;\n\tdata.rescale(3);\n\tTEST_EQUAL(data.getSize(), 3)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.5)\n\tTEST_REAL_EQUAL(data[2], 2.0)\n\tdata.rescale(4);\n\tTEST_EQUAL(data.getSize(), 4)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.3333333)\n\tTEST_REAL_EQUAL(data[2], 1.6666667)\n\tTEST_REAL_EQUAL(data[3], 2.0)\nRESULT\n\nCHECK(TRegularData1D::rescale(double lower, double upper, Size new_size))\n\tTRegularData1D<float>\tdata;\n\tdata.resize(2);\n\tdata.setBoundaries(0.0, 1.0);\n\tdata[0] = 1.0;\n\tdata[1] = 2.0;\n\tdata.rescale(0.0, 1.0, 3);\n\tTEST_EQUAL(data.getSize(), 3)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.5)\n\tTEST_REAL_EQUAL(data[2], 2.0)\n\tdata.rescale(0.0, 1.0, 4);\n\tTEST_EQUAL(data.getSize(), 4)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.3333333)\n\tTEST_REAL_EQUAL(data[2], 1.6666667)\n\tTEST_REAL_EQUAL(data[3], 2.0)\n\tdata.rescale(0.0, 1.0, 4);\n\tTEST_EQUAL(data.getSize(), 4)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.3333333)\n\tTEST_REAL_EQUAL(data[2], 1.6666667)\n\tTEST_REAL_EQUAL(data[3], 2.0)\n\tdata.rescale(-1.0, 2.0, 10);\n\tTEST_EQUAL(data.getSize(), 10)\n\tTEST_REAL_EQUAL(data[0], 0.0)\n\tTEST_REAL_EQUAL(data[1], 0.0)\n\tTEST_REAL_EQUAL(data[2], 0.0)\n\tTEST_REAL_EQUAL(data[3], 1.0)\n\tTEST_REAL_EQUAL(data[4], 1.3333333)\n\tTEST_REAL_EQUAL(data[5], 1.6666667)\n\tTEST_REAL_EQUAL(data[6], 2.0)\n\tTEST_REAL_EQUAL(data[7], 0.0)\n\tTEST_REAL_EQUAL(data[8], 0.0)\n\tTEST_REAL_EQUAL(data[9], 0.0)\n\tdata.rescale(0.0, 1.0, 3);\n\tTEST_EQUAL(data.getSize(), 3)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.5)\n\tTEST_REAL_EQUAL(data[2], 2.0)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<commit_msg>added test for detailled cstr<commit_after>\/\/ $Id: RegularData1D_test.C,v 1.7 2001\/07\/10 17:50:11 amoll Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/DATATYPE\/regularData1D.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(class_name, \"$Id: RegularData1D_test.C,v 1.7 2001\/07\/10 17:50:11 amoll Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\nRegularData1D* rd_ptr;\nCHECK(TRegularData1D::TRegularData1D())\n\trd_ptr = new RegularData1D;\n\tTEST_NOT_EQUAL(rd_ptr, 0)\nRESULT\n\n\nCHECK(TRegularData1D::~TRegularData1D())\n delete rd_ptr;\nRESULT\n\n\nCHECK(TRegularData1D::BALL_CREATE(RegularData1D<T>))\n\t\nRESULT\n\n\nRegularData1D rd;\nCHECK(TRegularData1D::TRegularData1D(const TRegularData1D& data))\n\trd.setBoundaries(1.1, 2.1);\n\trd.resize(1);\n\trd[0] = 1.2;\n\tRegularData1D rd2(rd);\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 1.1)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 2.1)\n\tTEST_REAL_EQUAL(rd2[0], 1.2) \n\tTEST_EQUAL(rd2.getSize(), 1)\nRESULT\n\n\nRegularData1D::VectorType v;\nv.push_back(1.1);\nv.push_back(1.2);\nv.push_back(1.3);\nv.push_back(1.4);\n\nCHECK(TRegularData1D(const VectorType& data, double lower, double upper))\n\tRegularData1D rd2(v, 1.0, 1.5);\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 1.0)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 1.5)\n\tTEST_EQUAL(rd2.getSize(), 4)\n\tTEST_REAL_EQUAL(rd2[0], 1.1)\n\tTEST_REAL_EQUAL(rd2[3], 1.4)\n\n\tRegularData1D rd3(v);\n\tTEST_REAL_EQUAL(rd3.getLowerBound(), 0.0)\n\tTEST_REAL_EQUAL(rd3.getUpperBound(), 0.0)\n\tTEST_EQUAL(rd3.getSize(), 4)\nRESULT\n\n\nCHECK(TRegularData1D::clear())\n\trd.clear();\n\tTEST_REAL_EQUAL(rd.getLowerBound(), 1.1)\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 2.1)\n\tTEST_EQUAL(rd.getSize(), 1)\n\tTEST_REAL_EQUAL(rd[0], 0.0)\nRESULT\n\n\nCHECK(TRegularData1D::destroy())\n\trd[0] = 2.3;\n\trd.destroy();\n\tTEST_REAL_EQUAL(rd.getLowerBound(), 0.0)\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 0.0)\n\tTEST_EQUAL(rd.getSize(), 0)\nRESULT\n\n\nCHECK(TRegularData1D::TRegularData1D& operator = (const TRegularData1D& data))\n\trd.setBoundaries(1.1, 2.1);\n\trd.resize(1);\n\trd[0] = 1.2;\n\tRegularData1D rd2 = rd;\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 1.1)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 2.1)\n\tTEST_REAL_EQUAL(rd2[0], 1.2) \n\tTEST_EQUAL(rd2.getSize(), 1)\nRESULT\n\n\nCHECK(TRegularData1D::TRegularData1D& operator = (const VectorType& data))\n\tRegularData1D::VectorType v;\n\tv.push_back(1.1);\n\tv.push_back(1.2);\n\tv.push_back(1.3);\n\tv.push_back(1.4);\n\tRegularData1D rd2;\n\trd2.setBoundaries(0.0, 1.0);\n\trd2 = v;\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 0.0)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 1.0)\n\tTEST_EQUAL(rd2.getSize(), 4)\n\tTEST_REAL_EQUAL(rd2[0], 1.1)\n\tTEST_REAL_EQUAL(rd2[1], 1.2)\n\tTEST_REAL_EQUAL(rd2[2], 1.3)\n\tTEST_REAL_EQUAL(rd2[3], 1.4)\nRESULT\n\n\nCHECK(TRegularData1D::bool operator == (const TRegularData1D& data) const )\n\trd.destroy();\n\trd.resize(4);\n\trd[0] = 1.1;\n\trd[1] = 1.2;\n\trd[2] = 1.3;\n\trd[3] = 1.4;\n\tRegularData1D rd2 = rd;\n\tTEST_EQUAL(rd == rd2, true)\n\trd2[3] = 1.41;\n\tTEST_EQUAL(rd == rd2, false)\n\trd2[3] = 1.4;\n\tTEST_EQUAL(rd == rd2, true)\n\trd.setBoundaries(1.1, 1.4);\n\tTEST_EQUAL(rd == rd2, false)\n\trd2.setBoundaries(1.1, 1.4);\n\tTEST_EQUAL(rd == rd2, true)\nRESULT\n\n\nCHECK(TRegularData1D::T& operator [] (Position index) const )\n TEST_REAL_EQUAL(rd[3], 1.4)\n\tTEST_EXCEPTION(Exception::IndexOverflow, rd[4])\nRESULT\n\n\nCHECK(TRegularData1D::T& operator [] (Position index))\n rd[3] = 1.5;\n\tTEST_REAL_EQUAL(rd[3], 1.5)\n\tTEST_EXCEPTION(Exception::IndexOverflow, rd[4] = 44.4)\nRESULT\n\n\nRegularData1D rd2;\nCHECK(TRegularData1D::getSize() const )\n TEST_EQUAL(rd.getSize(), 4)\n\tTEST_EQUAL(rd2.getSize(), 0)\nRESULT\n\n\nCHECK(TRegularData1D::getLowerBound() const )\n\trd.setBoundaries(1.1, 1.5);\n\tTEST_REAL_EQUAL(rd.getLowerBound(), 1.1)\n\tTEST_REAL_EQUAL(rd2.getLowerBound(), 0.0)\nRESULT\n\n\nCHECK(TRegularData1D::getUpperBound() const )\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 1.5)\n\tTEST_REAL_EQUAL(rd2.getUpperBound(), 0.0)\nRESULT\n\n\nCHECK(TRegularData1D::setLowerBound())\n\trd.setBoundaries(-99.9, 99.9);\n\tTEST_REAL_EQUAL(rd.getLowerBound(), -99.9)\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 99.9)\n\trd.setBoundaries(99.9, -99.9);\n\tTEST_REAL_EQUAL(rd.getLowerBound(), -99.9)\n\tTEST_REAL_EQUAL(rd.getUpperBound(), 99.9)\nRESULT\n\n\nCHECK(TRegularData1D::resize(Size new_size))\n\tTEST_EQUAL(rd.getSize(), 4)\n\trd.resize(99);\n\tTEST_EQUAL(rd.getSize(), 99)\n\tTEST_REAL_EQUAL(rd[98], 0.0)\n\trd.resize(3);\n\tTEST_EQUAL(rd.getSize(), 3)\n\tTEST_REAL_EQUAL(rd[2], 1.3)\n\tTEST_EXCEPTION(Exception::IndexOverflow, rd[3])\nRESULT\n\nCHECK(TRegularData1D::rescale(Size new_size))\n\tTRegularData1D<float>\tdata;\n\tTEST_EQUAL(data.getSize(), 0)\n\tdata.rescale(1);\n\tTEST_EQUAL(data.getSize(), 1)\n\tTEST_EQUAL(data[0], 0.0)\n\tdata[0] = 2.0;\n\tdata.rescale(2);\n\tTEST_EQUAL(data.getSize(), 2)\n\tTEST_EQUAL(data[0], 2.0)\n\tTEST_EQUAL(data[0], 2.0)\n\tdata[0] = 1.0;\n\tdata.rescale(3);\n\tTEST_EQUAL(data.getSize(), 3)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.5)\n\tTEST_REAL_EQUAL(data[2], 2.0)\n\tdata.rescale(4);\n\tTEST_EQUAL(data.getSize(), 4)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.3333333)\n\tTEST_REAL_EQUAL(data[2], 1.6666667)\n\tTEST_REAL_EQUAL(data[3], 2.0)\nRESULT\n\nCHECK(TRegularData1D::rescale(double lower, double upper, Size new_size))\n\tTRegularData1D<float>\tdata;\n\tdata.resize(2);\n\tdata.setBoundaries(0.0, 1.0);\n\tdata[0] = 1.0;\n\tdata[1] = 2.0;\n\tdata.rescale(0.0, 1.0, 3);\n\tTEST_EQUAL(data.getSize(), 3)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.5)\n\tTEST_REAL_EQUAL(data[2], 2.0)\n\tdata.rescale(0.0, 1.0, 4);\n\tTEST_EQUAL(data.getSize(), 4)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.3333333)\n\tTEST_REAL_EQUAL(data[2], 1.6666667)\n\tTEST_REAL_EQUAL(data[3], 2.0)\n\tdata.rescale(0.0, 1.0, 4);\n\tTEST_EQUAL(data.getSize(), 4)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.3333333)\n\tTEST_REAL_EQUAL(data[2], 1.6666667)\n\tTEST_REAL_EQUAL(data[3], 2.0)\n\tdata.rescale(-1.0, 2.0, 10);\n\tTEST_EQUAL(data.getSize(), 10)\n\tTEST_REAL_EQUAL(data[0], 0.0)\n\tTEST_REAL_EQUAL(data[1], 0.0)\n\tTEST_REAL_EQUAL(data[2], 0.0)\n\tTEST_REAL_EQUAL(data[3], 1.0)\n\tTEST_REAL_EQUAL(data[4], 1.3333333)\n\tTEST_REAL_EQUAL(data[5], 1.6666667)\n\tTEST_REAL_EQUAL(data[6], 2.0)\n\tTEST_REAL_EQUAL(data[7], 0.0)\n\tTEST_REAL_EQUAL(data[8], 0.0)\n\tTEST_REAL_EQUAL(data[9], 0.0)\n\tdata.rescale(0.0, 1.0, 3);\n\tTEST_EQUAL(data.getSize(), 3)\n\tTEST_REAL_EQUAL(data[0], 1.0)\n\tTEST_REAL_EQUAL(data[1], 1.5)\n\tTEST_REAL_EQUAL(data[2], 2.0)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: RegularData2D_test.C,v 1.3 2001\/06\/22 11:07:50 oliver Exp $\n\n#include <BALL\/CONCEPT\/classTest.h>\n#include <BALL\/DATATYPE\/regularData2D.h>\n\nSTART_TEST(RegularData2D, \"$Id: RegularData2D_test.C,v 1.3 2001\/06\/22 11:07:50 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\nString filename;\nusing BALL::RegularData2D;\nRegularData2D*\tgrid;\n\nCHECK(RegularData2D())\n\tgrid = new RegularData2D();\n\tTEST_NOT_EQUAL(grid, 0)\nRESULT\n\nCHECK(~RegularData2D())\n\tdelete grid;\nRESULT\n\nRegularData2D g;\n\nCHECK(RegularData2D(\/2))\n\tg = RegularData2D(0.0, 0.0, 4.0, 9.0, 2.0, 3.0);\n\tTEST_EQUAL(g.getSize(), 6)\n\n\tTEST_REAL_EQUAL(g.getMinX(), 0.0)\n\tTEST_REAL_EQUAL(g.getMinY(), 0.0)\n\n\tTEST_REAL_EQUAL(g.getMaxX(), 4.0)\n\tTEST_REAL_EQUAL(g.getMaxY(), 9.0)\n\n\tTEST_EQUAL(g.getMaxXIndex(), 1)\n\tTEST_EQUAL(g.getMaxYIndex(), 2)\n\n\tTEST_REAL_EQUAL(g.getXSpacing(), 4.0)\n\tTEST_REAL_EQUAL(g.getYSpacing(), 4.5)\n\n\tVector2 p(0, 0);\n\tTEST_EQUAL(g.getOrigin()== p, true)\nRESULT\n\nCHECK(RegularData2D(const TRegularData2D<GridDataType>& grid, bool deep = true))\n\tRegularData2D g2(g);\n\tTEST_EQUAL(g.getSize(), 6)\nRESULT\n\nCHECK(clear())\n\tRegularData2D g2(g);\n\tg2[1] = 1.234;\n\tg2.clear();\n\tTEST_EQUAL(g2.isValid(), false)\n\tTEST_EQUAL(g2.getSize(), 0)\nRESULT\n\nCHECK(getSize())\n\tTEST_EQUAL(g.getSize(), 6)\n\tRegularData2D g2;\n\tTEST_EQUAL(g2.getSize(), 0)\nRESULT\n\nCHECK(set(const RegularData2D& grid))\n\tg[1] = 1.2345;\n\tRegularData2D g1;\n\tg1.set(g);\n\tTEST_EQUAL(g1.getSize(), 6)\n\tTEST_REAL_EQUAL(g1[1], 1.2345)\nRESULT\n\nCHECK(operator = (const RegularData2D& grid))\n\tg[1] = 1.2345;\n\tRegularData2D g1;\n\tg1 = g;\n\tTEST_EQUAL(g1.getSize(), 6)\n\tTEST_REAL_EQUAL(g1[1], 1.2345)\nRESULT\n\nCHECK(dump())\n String filename;\n\tNEW_TMP_FILE(filename)\n\tstd::ofstream outfile(filename.c_str(), File::OUT);\n\tfor (Position k = 0; k < g.getSize(); k++)\n\t{\n\t\tg[k] = k;\n\t}\n\tg.dump(outfile);\n\toutfile.close();\n\tTEST_FILE(filename.c_str(), \"data\/RegularData2D_test.txt\", true)\nRESULT\n\n\nCHECK(isValid())\n\tTEST_EQUAL(g.isValid(), true)\nRESULT\n\nCHECK(getMaxX())\n\tTEST_REAL_EQUAL(g.getMaxX(), 4.0)\nRESULT\n\nCHECK(getMaxY())\n\tTEST_REAL_EQUAL(g.getMaxY(), 9.0)\nRESULT\n\nCHECK(getMinX())\n\tTEST_REAL_EQUAL(g.getMinX(), 0.0)\nRESULT\n\nCHECK(getMinY())\n\tTEST_REAL_EQUAL(g.getMinY(), 0.0)\nRESULT\n\nCHECK(getMaxXIndex())\n\tTEST_EQUAL(g.getMaxXIndex(), 1)\nRESULT\n\nCHECK(getMaxYIndex())\n\tTEST_EQUAL(g.getMaxYIndex(), 2)\nRESULT\n\nCHECK(getXSpacing())\n\tTEST_REAL_EQUAL(g.getXSpacing(), 4.0)\nRESULT\n\nCHECK(getYSpacing())\n\tTEST_REAL_EQUAL(g.getYSpacing(), 4.5)\nRESULT\n\nBALL::RegularData2D::GridIndex\tpp;\nVector2 v;\n\nCHECK(getIndex(const Vector2& vector))\n\tv = Vector2(2.11, 4.51);\n\tpp = g.getIndex(v);\n\tTEST_EQUAL(pp.x, 1)\n\tTEST_EQUAL(pp.y, 1)\nRESULT\n\nCHECK(getIndex(\/2))\n\tpp = g.getIndex(2.11, 4.51);\n\tTEST_EQUAL(pp.x, 1)\n\tTEST_EQUAL(pp.y, 1)\nRESULT\n\nCHECK(getData(Position))\n\t*(g.getData(0, 0)) = 5.4321;\t\t\n\tv = g.getOrigin();\n\tTEST_REAL_EQUAL(*(g.getData(0)), 5.4321);\nRESULT\n\nCHECK(operator[]\/1\/2)\n\tg[5] = 1.2345;\n\tv = Vector2(3.0, 8.2);\n\tTEST_EQUAL(g[5], g[v]);\nRESULT\n\nCHECK(getGridCoordinates\/1)\n\tv = g.getGridCoordinates(1, 1);\n\tTEST_REAL_EQUAL(v.x, 4.0)\n\tTEST_REAL_EQUAL(v.y, 4.5)\nRESULT\n\nCHECK(getGridCoordinates\/2)\n\tv = g.getGridCoordinates(5);\n\tTEST_REAL_EQUAL(v.x, 4.0)\n\tTEST_REAL_EQUAL(v.y, 9.0)\n\n\tTEST_EXCEPTION(Exception::OutOfGrid, v = g.getGridCoordinates(6))\n\tTEST_EXCEPTION(Exception::OutOfGrid, g.getGridCoordinates(7))\nRESULT\n\nCHECK(getRectangleIndices)\n\tv = Vector2(3.9, 3.9);\n\tPosition p1, p2, p3, p4;\n\tg.getRectangleIndices(v, p1, p2, p3, p4);\n\tTEST_EQUAL(p1, 0);\n\tTEST_EQUAL(p2, 1);\n\tTEST_EQUAL(p3, 2);\n\tTEST_EQUAL(p4, 3);\n\n\tv = Vector2(3.1, 4.6);\n\tg.getRectangleIndices(v, p1, p2, p3, p4);\n\tTEST_EQUAL(p1, 2);\n\tTEST_EQUAL(p2, 3);\n\tTEST_EQUAL(p3, 4);\n\tTEST_EQUAL(p4, 5);\n\n\tv = Vector2(10.1, 2.1);\n\tTEST_EXCEPTION(Exception::OutOfGrid, g.getRectangleIndices(v, p1, p2, p3, p4))\nRESULT\n\nCHECK(getRectangleData)\n\tv = Vector2(0, 4.2);\n\tfloat p1, p2, p3, p4;\n\tg[0] = 1;\n\tg[1] = 2;\n\tg[2] = 3;\n\tg[3] = 4;\n\tg.getRectangleData(v, p1, p2, p3, p4);\n\tTEST_EQUAL(p1, 1);\n\tTEST_EQUAL(p2, 2);\n\tTEST_EQUAL(p3, 3);\n\tTEST_EQUAL(p4, 4);\n\n\tv = Vector2(4.1, 2.1);\n\tTEST_EXCEPTION(Exception::OutOfGrid, g.getRectangleData(v, p1, p2, p3, p4))\nRESULT\n\nCHECK(getOrigin)\n\tv = g.getOrigin();\n\tTEST_REAL_EQUAL(v.x, 0.0)\n\tTEST_REAL_EQUAL(v.y, 0.0)\nRESULT\n\nCHECK(setOrigin\/1)\n\tg.setOrigin(1.0, 1.0);\n\tv = g.getOrigin();\n\tTEST_REAL_EQUAL(v.x, 1.0)\n\tTEST_REAL_EQUAL(v.y, 1.0)\n\tpp = g.getIndex(2.49, 5.1);\n\tTEST_EQUAL(pp.x, 0)\n\tTEST_EQUAL(pp.y, 1)\nRESULT\n\nCHECK(setOrigin\/2)\n\tv = Vector2(2.0, 2.0);\n\tg.setOrigin(v);\n\tv = g.getOrigin();\n\tTEST_REAL_EQUAL(v.x, 2.0)\n\tTEST_REAL_EQUAL(v.y, 2.0)\n\tpp = g.getIndex(3.94, 6.41);\n\tTEST_EQUAL(pp.x, 0)\n\tTEST_EQUAL(pp.y, 1)\nRESULT\n\nCHECK(getDimension)\n\tTEST_REAL_EQUAL(g.getDimension().x, 4.0)\n\tTEST_REAL_EQUAL(g.getDimension().y, 9.0)\nRESULT\n\ng = RegularData2D(0.0, 0.0, 4.0, 9.0, 2.0, 3.0);\n\nCHECK(getInterpolatedValue)\n\tfor (Position i = 0; i < g.getSize() ; i++)\n\t{\n\t\tg[i] = i;\n\t}\n\tv = Vector2(0.0, 0.0);\n\tTEST_EQUAL(g.getInterpolatedValue(v), 0.0)\n\n\tv = Vector2(4.0, 9.0);\n\tTEST_EQUAL(g.getInterpolatedValue(v), 0.0)\n\n\tv = Vector2(2.0, 4.5);\n\tTEST_EQUAL(g.getInterpolatedValue(v), 2.5)\n\n\tv = Vector2(4.0, 2.25);\n\tTEST_EQUAL(g.getInterpolatedValue(v), 2.0)\n\n\tv = Vector2(10.1, 0);\n\tTEST_EXCEPTION(Exception::OutOfGrid, g.getInterpolatedValue(v))\nRESULT\n\nRegularData2D grid2 = g;\n\nCHECK(operator ==)\n\tgrid2 = g;\n\tTEST_EQUAL(g.isValid(), true)\n\tTEST_EQUAL(g == g, true)\n\tgrid2[5] = -99.9;\n\tTEST_EQUAL(g == grid2, false)\nRESULT\n\nCHECK(operator !=)\n\tTEST_EQUAL(g != grid2, true)\n\tgrid2[5] = (g)[5];\n\tTEST_EQUAL(g != grid2, false)\nRESULT\n\nCHECK(has()1\/1)\n\tRegularData2D g(0.0, 0.0, 10.0, 10.0, 10, 10);\n\tTEST_EQUAL(g.has(0.0, 0.0), true)\n\tTEST_EQUAL(g.has(10.0, 10.0), true)\n\tTEST_EQUAL(g.has(10.1, 10.0), false)\n\n\tRegularData2D h;\n\tTEST_EQUAL(h.isValid(), false)\n\tTEST_EQUAL(h.has(0.0, 0.0), false)\nRESULT\n\nCHECK(getMinValue())\n\tRegularData2D g(0.0, 0.0, 10.0, 10.0, 11, 11);\n\tg.data[0] = -123.23;\n\tg.data[1] = +123.23;\n\tg.data[13] = -123.231;\n\tg.data[3] = -123.230;\n\tVector2 vector2;\n\tconst float* float_ptr = g.getMinValue(vector2);\n\tTEST_NOT_EQUAL(float_ptr, 0)\n\tif (float_ptr != 0)\n\t{\n\t\tTEST_REAL_EQUAL(*float_ptr, (float) -123.231)\n\t\tTEST_EQUAL(vector2.x, 2)\n\t\tTEST_EQUAL(vector2.y, 1)\n\t\t\n\t\tg.data[120] = -124.11;\n\t\tTEST_REAL_EQUAL(*g.getMinValue(vector2), (float) -124.11)\n\t\tTEST_EQUAL(vector2.x, 10)\n\t\tTEST_EQUAL(vector2.y, 10)\n\t\tg.data[120] = 0.11;\n\t\t\n\t\tg.data[13] = -123.11;\n\t\tTEST_REAL_EQUAL(*g.getMinValue(vector2), (float) -123.23)\n\t\tTEST_EQUAL(vector2.x, 0)\n\t\tTEST_EQUAL(vector2.y, 0)\n\t}\nRESULT\n\nCHECK(getMaxValue())\n\tRegularData2D g(0.0, 0.0, 10.0, 10.0, 11, 11);\n\tg.data[0] = +123.23;\n\tg.data[1] = +123.23;\n\tg.data[13] = +123.231;\n\tg.data[3] = -123.230;\n\tVector2 vector2;\n\tconst float* float_ptr = g.getMaxValue(vector2);\n\tTEST_NOT_EQUAL(float_ptr, 0)\n\tif (float_ptr != 0)\n\t{\n\t\tTEST_REAL_EQUAL(*float_ptr, (float) +123.231)\n\t\tTEST_EQUAL(vector2.x, 2)\n\t\tTEST_EQUAL(vector2.y, 1)\n\t\t\n\t\tg.data[120] = +124.11;\n\t\tTEST_REAL_EQUAL(*g.getMaxValue(vector2), (float) +124.11)\n\t\tTEST_EQUAL(vector2.x, 10)\n\t\tTEST_EQUAL(vector2.y, 10)\n\t\tg.data[120] = 0.11;\n\t\t\n\t\tg.data[13] = +123.11;\n\t\tTEST_REAL_EQUAL(*g.getMaxValue(vector2), (float) +123.23)\n\t\tTEST_EQUAL(vector2.x, 0)\n\t\tTEST_EQUAL(vector2.y, 0)\n\t}\nRESULT\n\nCHECK(rescale)\n\tRegularData2D g(0.0, 0.0, 9.0, 9.0, 10, 10);\n\tg.data[0] = -4.5;\n\tg.data[1] = -2.25;\n\tg.data[2] = 4.5;\n\tg.rescale(0, 1);\n\tTEST_EQUAL(g.data[0], 0)\n\tTEST_EQUAL(g.data[1], 0.25)\n\tTEST_EQUAL(g.data[2], 1)\n\tTEST_EQUAL(g.data[3], 0.5)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<commit_msg>fixed: incorrect oracle value for test<commit_after>\/\/ $Id: RegularData2D_test.C,v 1.4 2001\/06\/23 02:24:07 oliver Exp $\n\n#include <BALL\/CONCEPT\/classTest.h>\n#include <BALL\/DATATYPE\/regularData2D.h>\n\nSTART_TEST(RegularData2D, \"$Id: RegularData2D_test.C,v 1.4 2001\/06\/23 02:24:07 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\nString filename;\nusing BALL::RegularData2D;\nRegularData2D*\tgrid;\n\nCHECK(RegularData2D())\n\tgrid = new RegularData2D();\n\tTEST_NOT_EQUAL(grid, 0)\nRESULT\n\nCHECK(~RegularData2D())\n\tdelete grid;\nRESULT\n\nRegularData2D g;\n\nCHECK(RegularData2D(\/2))\n\tg = RegularData2D(0.0, 0.0, 4.0, 9.0, 2.0, 3.0);\n\tTEST_EQUAL(g.getSize(), 6)\n\n\tTEST_REAL_EQUAL(g.getMinX(), 0.0)\n\tTEST_REAL_EQUAL(g.getMinY(), 0.0)\n\n\tTEST_REAL_EQUAL(g.getMaxX(), 4.0)\n\tTEST_REAL_EQUAL(g.getMaxY(), 9.0)\n\n\tTEST_EQUAL(g.getMaxXIndex(), 1)\n\tTEST_EQUAL(g.getMaxYIndex(), 2)\n\n\tTEST_REAL_EQUAL(g.getXSpacing(), 4.0)\n\tTEST_REAL_EQUAL(g.getYSpacing(), 4.5)\n\n\tVector2 p(0, 0);\n\tTEST_EQUAL(g.getOrigin()== p, true)\nRESULT\n\nCHECK(RegularData2D(const TRegularData2D<GridDataType>& grid, bool deep = true))\n\tRegularData2D g2(g);\n\tTEST_EQUAL(g.getSize(), 6)\nRESULT\n\nCHECK(clear())\n\tRegularData2D g2(g);\n\tg2[1] = 1.234;\n\tg2.clear();\n\tTEST_EQUAL(g2.isValid(), false)\n\tTEST_EQUAL(g2.getSize(), 0)\nRESULT\n\nCHECK(getSize())\n\tTEST_EQUAL(g.getSize(), 6)\n\tRegularData2D g2;\n\tTEST_EQUAL(g2.getSize(), 0)\nRESULT\n\nCHECK(set(const RegularData2D& grid))\n\tg[1] = 1.2345;\n\tRegularData2D g1;\n\tg1.set(g);\n\tTEST_EQUAL(g1.getSize(), 6)\n\tTEST_REAL_EQUAL(g1[1], 1.2345)\nRESULT\n\nCHECK(operator = (const RegularData2D& grid))\n\tg[1] = 1.2345;\n\tRegularData2D g1;\n\tg1 = g;\n\tTEST_EQUAL(g1.getSize(), 6)\n\tTEST_REAL_EQUAL(g1[1], 1.2345)\nRESULT\n\nCHECK(dump())\n String filename;\n\tNEW_TMP_FILE(filename)\n\tstd::ofstream outfile(filename.c_str(), File::OUT);\n\tfor (Position k = 0; k < g.getSize(); k++)\n\t{\n\t\tg[k] = k;\n\t}\n\tg.dump(outfile);\n\toutfile.close();\n\tTEST_FILE(filename.c_str(), \"data\/RegularData2D_test.txt\", true)\nRESULT\n\n\nCHECK(isValid())\n\tTEST_EQUAL(g.isValid(), true)\nRESULT\n\nCHECK(getMaxX())\n\tTEST_REAL_EQUAL(g.getMaxX(), 4.0)\nRESULT\n\nCHECK(getMaxY())\n\tTEST_REAL_EQUAL(g.getMaxY(), 9.0)\nRESULT\n\nCHECK(getMinX())\n\tTEST_REAL_EQUAL(g.getMinX(), 0.0)\nRESULT\n\nCHECK(getMinY())\n\tTEST_REAL_EQUAL(g.getMinY(), 0.0)\nRESULT\n\nCHECK(getMaxXIndex())\n\tTEST_EQUAL(g.getMaxXIndex(), 1)\nRESULT\n\nCHECK(getMaxYIndex())\n\tTEST_EQUAL(g.getMaxYIndex(), 2)\nRESULT\n\nCHECK(getXSpacing())\n\tTEST_REAL_EQUAL(g.getXSpacing(), 4.0)\nRESULT\n\nCHECK(getYSpacing())\n\tTEST_REAL_EQUAL(g.getYSpacing(), 4.5)\nRESULT\n\nBALL::RegularData2D::GridIndex\tpp;\nVector2 v;\n\nCHECK(getIndex(const Vector2& vector))\n\tv = Vector2(2.11, 4.51);\n\tpp = g.getIndex(v);\n\tTEST_EQUAL(pp.x, 1)\n\tTEST_EQUAL(pp.y, 1)\nRESULT\n\nCHECK(getIndex(\/2))\n\tpp = g.getIndex(2.11, 4.51);\n\tTEST_EQUAL(pp.x, 1)\n\tTEST_EQUAL(pp.y, 1)\nRESULT\n\nCHECK(getData(Position))\n\t*(g.getData(0, 0)) = 5.4321;\t\t\n\tv = g.getOrigin();\n\tTEST_REAL_EQUAL(*(g.getData(0)), 5.4321);\nRESULT\n\nCHECK(operator[]\/1\/2)\n\tg[5] = 1.2345;\n\tv = Vector2(3.0, 8.2);\n\tTEST_EQUAL(g[5], g[v]);\nRESULT\n\nCHECK(getGridCoordinates\/1)\n\tv = g.getGridCoordinates(1, 1);\n\tTEST_REAL_EQUAL(v.x, 4.0)\n\tTEST_REAL_EQUAL(v.y, 4.5)\nRESULT\n\nCHECK(getGridCoordinates\/2)\n\tv = g.getGridCoordinates(5);\n\tTEST_REAL_EQUAL(v.x, 4.0)\n\tTEST_REAL_EQUAL(v.y, 9.0)\n\n\tTEST_EXCEPTION(Exception::OutOfGrid, v = g.getGridCoordinates(6))\n\tTEST_EXCEPTION(Exception::OutOfGrid, g.getGridCoordinates(7))\nRESULT\n\nCHECK(getRectangleIndices)\n\tv = Vector2(3.9, 3.9);\n\tPosition p1, p2, p3, p4;\n\tg.getRectangleIndices(v, p1, p2, p3, p4);\n\tTEST_EQUAL(p1, 0);\n\tTEST_EQUAL(p2, 1);\n\tTEST_EQUAL(p3, 2);\n\tTEST_EQUAL(p4, 3);\n\n\tv = Vector2(3.1, 4.6);\n\tg.getRectangleIndices(v, p1, p2, p3, p4);\n\tTEST_EQUAL(p1, 2);\n\tTEST_EQUAL(p2, 3);\n\tTEST_EQUAL(p3, 4);\n\tTEST_EQUAL(p4, 5);\n\n\tv = Vector2(10.1, 2.1);\n\tTEST_EXCEPTION(Exception::OutOfGrid, g.getRectangleIndices(v, p1, p2, p3, p4))\nRESULT\n\nCHECK(getRectangleData)\n\tv = Vector2(0, 4.2);\n\tfloat p1, p2, p3, p4;\n\tg[0] = 1;\n\tg[1] = 2;\n\tg[2] = 3;\n\tg[3] = 4;\n\tg.getRectangleData(v, p1, p2, p3, p4);\n\tTEST_EQUAL(p1, 1);\n\tTEST_EQUAL(p2, 2);\n\tTEST_EQUAL(p3, 3);\n\tTEST_EQUAL(p4, 4);\n\n\tv = Vector2(4.1, 2.1);\n\tTEST_EXCEPTION(Exception::OutOfGrid, g.getRectangleData(v, p1, p2, p3, p4))\nRESULT\n\nCHECK(getOrigin)\n\tv = g.getOrigin();\n\tTEST_REAL_EQUAL(v.x, 0.0)\n\tTEST_REAL_EQUAL(v.y, 0.0)\nRESULT\n\nCHECK(setOrigin\/1)\n\tg.setOrigin(1.0, 1.0);\n\tv = g.getOrigin();\n\tTEST_REAL_EQUAL(v.x, 1.0)\n\tTEST_REAL_EQUAL(v.y, 1.0)\n\tpp = g.getIndex(2.49, 5.1);\n\tTEST_EQUAL(pp.x, 0)\n\tTEST_EQUAL(pp.y, 1)\nRESULT\n\nCHECK(setOrigin\/2)\n\tv = Vector2(2.0, 2.0);\n\tg.setOrigin(v);\n\tv = g.getOrigin();\n\tTEST_REAL_EQUAL(v.x, 2.0)\n\tTEST_REAL_EQUAL(v.y, 2.0)\n\tpp = g.getIndex(3.94, 6.41);\n\tTEST_EQUAL(pp.x, 0)\n\tTEST_EQUAL(pp.y, 1)\nRESULT\n\nCHECK(getDimension)\n\tTEST_REAL_EQUAL(g.getDimension().x, 4.0)\n\tTEST_REAL_EQUAL(g.getDimension().y, 9.0)\nRESULT\n\ng = RegularData2D(0.0, 0.0, 4.0, 9.0, 2.0, 3.0);\n\nCHECK(getInterpolatedValue)\n\tfor (Position i = 0; i < g.getSize() ; i++)\n\t{\n\t\tg[i] = i;\n\t}\n\tv = Vector2(0.0, 0.0);\n\tTEST_EQUAL(g.getInterpolatedValue(v), 0.0)\n\n\tv = Vector2(4.0, 9.0);\n\tTEST_EQUAL(g.getInterpolatedValue(v), 5.0)\n\n\tv = Vector2(2.0, 4.5);\n\tTEST_EQUAL(g.getInterpolatedValue(v), 2.5)\n\n\tv = Vector2(4.0, 2.25);\n\tTEST_EQUAL(g.getInterpolatedValue(v), 2.0)\n\n\tv = Vector2(10.1, 0);\n\tTEST_EXCEPTION(Exception::OutOfGrid, g.getInterpolatedValue(v))\nRESULT\n\nRegularData2D grid2 = g;\n\nCHECK(operator ==)\n\tgrid2 = g;\n\tTEST_EQUAL(g.isValid(), true)\n\tTEST_EQUAL(g == g, true)\n\tgrid2[5] = -99.9;\n\tTEST_EQUAL(g == grid2, false)\nRESULT\n\nCHECK(operator !=)\n\tTEST_EQUAL(g != grid2, true)\n\tgrid2[5] = (g)[5];\n\tTEST_EQUAL(g != grid2, false)\nRESULT\n\nCHECK(has()1\/1)\n\tRegularData2D g(0.0, 0.0, 10.0, 10.0, 10, 10);\n\tTEST_EQUAL(g.has(0.0, 0.0), true)\n\tTEST_EQUAL(g.has(10.0, 10.0), true)\n\tTEST_EQUAL(g.has(10.1, 10.0), false)\n\n\tRegularData2D h;\n\tTEST_EQUAL(h.isValid(), false)\n\tTEST_EQUAL(h.has(0.0, 0.0), false)\nRESULT\n\nCHECK(getMinValue())\n\tRegularData2D g(0.0, 0.0, 10.0, 10.0, 11, 11);\n\tg.data[0] = -123.23;\n\tg.data[1] = +123.23;\n\tg.data[13] = -123.231;\n\tg.data[3] = -123.230;\n\tVector2 vector2;\n\tconst float* float_ptr = g.getMinValue(vector2);\n\tTEST_NOT_EQUAL(float_ptr, 0)\n\tif (float_ptr != 0)\n\t{\n\t\tTEST_REAL_EQUAL(*float_ptr, (float) -123.231)\n\t\tTEST_EQUAL(vector2.x, 2)\n\t\tTEST_EQUAL(vector2.y, 1)\n\t\t\n\t\tg.data[120] = -124.11;\n\t\tTEST_REAL_EQUAL(*g.getMinValue(vector2), (float) -124.11)\n\t\tTEST_EQUAL(vector2.x, 10)\n\t\tTEST_EQUAL(vector2.y, 10)\n\t\tg.data[120] = 0.11;\n\t\t\n\t\tg.data[13] = -123.11;\n\t\tTEST_REAL_EQUAL(*g.getMinValue(vector2), (float) -123.23)\n\t\tTEST_EQUAL(vector2.x, 0)\n\t\tTEST_EQUAL(vector2.y, 0)\n\t}\nRESULT\n\nCHECK(getMaxValue())\n\tRegularData2D g(0.0, 0.0, 10.0, 10.0, 11, 11);\n\tg.data[0] = +123.23;\n\tg.data[1] = +123.23;\n\tg.data[13] = +123.231;\n\tg.data[3] = -123.230;\n\tVector2 vector2;\n\tconst float* float_ptr = g.getMaxValue(vector2);\n\tTEST_NOT_EQUAL(float_ptr, 0)\n\tif (float_ptr != 0)\n\t{\n\t\tTEST_REAL_EQUAL(*float_ptr, (float) +123.231)\n\t\tTEST_EQUAL(vector2.x, 2)\n\t\tTEST_EQUAL(vector2.y, 1)\n\t\t\n\t\tg.data[120] = +124.11;\n\t\tTEST_REAL_EQUAL(*g.getMaxValue(vector2), (float) +124.11)\n\t\tTEST_EQUAL(vector2.x, 10)\n\t\tTEST_EQUAL(vector2.y, 10)\n\t\tg.data[120] = 0.11;\n\t\t\n\t\tg.data[13] = +123.11;\n\t\tTEST_REAL_EQUAL(*g.getMaxValue(vector2), (float) +123.23)\n\t\tTEST_EQUAL(vector2.x, 0)\n\t\tTEST_EQUAL(vector2.y, 0)\n\t}\nRESULT\n\nCHECK(rescale)\n\tRegularData2D g(0.0, 0.0, 9.0, 9.0, 10, 10);\n\tg.data[0] = -4.5;\n\tg.data[1] = -2.25;\n\tg.data[2] = 4.5;\n\tg.rescale(0, 1);\n\tTEST_EQUAL(g.data[0], 0)\n\tTEST_EQUAL(g.data[1], 0.25)\n\tTEST_EQUAL(g.data[2], 1)\n\tTEST_EQUAL(g.data[3], 0.5)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\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\n#include \"mainwindow.h\"\n\n#include <QtCore\/QVariantList>\n\n#include <KFileDialog>\n#include <KStandardAction>\n#include <KActionCollection>\n#include <KAction>\n#include <KStatusBar>\n#include <KMessageBox>\n#include <KConfigDialog>\n#include <KLocalizedString>\n#include <KPluginSelector>\n#include <KRun>\n#include <KRecentFilesAction>\n#include <KDE\/KTabWidget>\n#include <KDE\/KToolBar>\n#include <KDE\/KRichTextEdit>\n\n#include <core\/debughelper.h>\n#include <engine\/game.h>\n#include <engine\/gameproject.h>\n#include <engine\/scene.h>\n\n#include \"lib\/plugin.h\"\n#include \"lib\/pluginmanager.h\"\n#include \"lib\/objectmanager.h\"\n#include \"lib\/historymanager.h\"\n#include \"lib\/selectionmanager.h\"\n#include \"lib\/dockmanager.h\"\n#include \"lib\/filemanager.h\"\n#include \"lib\/widgets\/filearea.h\"\n\n#include \"gluoncreatorsettings.h\"\n#include \"dialogs\/configdialog.h\"\n#include <QVBoxLayout>\n#include <KParts\/PartManager>\n\nusing namespace GluonCreator;\n\nclass MainWindow::MainWindowPrivate\n{\n public:\n MainWindowPrivate()\n {\n }\n\n bool modified;\n QString fileName;\n KRecentFilesAction* recentFiles;\n ProjectSelectionDialog* projectDialog;\n\n FileArea* mainArea;\n};\n\nMainWindow::MainWindow( const QString& fileName )\n : KParts::MainWindow(),\n d( new MainWindowPrivate )\n{\n d->modified = false;\n\n GluonCore::GluonObjectFactory::instance()->loadPlugins();\n\n PluginManager::instance()->setParent( this );\n ObjectManager::instance()->setParent( this );\n HistoryManager::instance()->setParent( this );\n SelectionManager::instance()->setParent( this );\n\n DockManager::instance()->setParent( this );\n DockManager::instance()->setMainWindow( this );\n\n FileManager::instance()->initialize( this );\n connect( FileManager::instance()->partManager(), SIGNAL( activePartChanged( KParts::Part* ) ), this, SLOT( createGUI( KParts::Part* ) ) );\n\n PluginManager::instance()->setMainWindow( this );\n PluginManager::instance()->loadPlugins();\n\n setDockNestingEnabled( true );\n setCorner( Qt::TopLeftCorner, Qt::LeftDockWidgetArea );\n setCorner( Qt::BottomLeftCorner, Qt::LeftDockWidgetArea );\n setCorner( Qt::TopRightCorner, Qt::RightDockWidgetArea );\n setCorner( Qt::BottomRightCorner, Qt::RightDockWidgetArea );\n\n d->mainArea = new FileArea( this );\n setCentralWidget( d->mainArea );\n\n setupActions();\n setupGUI();\n stateChanged( \"initial\" );\n\n d->projectDialog = new ProjectSelectionDialog( this );\n d->projectDialog->setModal( true );\n connect( d->projectDialog, SIGNAL( accepted() ), SLOT( projectDialogClosed() ) );\n\n DockManager::instance()->setDocksEnabled( false );\n DockManager::instance()->setDocksLocked( GluonCreator::Settings::lockLayout() );\n\n if( fileName.isEmpty() )\n {\n showNewProjectDialog();\n }\n else\n {\n openProject( fileName );\n }\n}\n\nMainWindow::~MainWindow()\n{\n d->recentFiles->saveEntries( KGlobal::config()->group( \"Recent Files\" ) );\n GluonCreator::Settings::setLockLayout( actionCollection()->action( \"lockLayout\" )->isChecked() );\n GluonCreator::Settings::self()->writeConfig();\n GluonEngine::Game::instance()->stopGame();\n}\n\nvoid MainWindow::openProject( KUrl url )\n{\n openProject( url.path() );\n}\n\nvoid MainWindow::openProject( const QString& fileName )\n{\n if( !fileName.isEmpty() && QFile::exists( fileName ) )\n {\n statusBar()->showMessage( i18n( \"Opening project...\" ) );\n\n FileManager::instance()->openFile( fileName, i18nc( \"View Game Tab\", \"View\" ), \"gluon_viewer_part\", QVariantList() << QString( \"autoplay=false\" ) );\n\n GluonEngine::Game::instance()->initializeAll();\n GluonEngine::Game::instance()->drawAll();\n\n d->fileName = fileName;\n d->recentFiles->addUrl( KUrl( fileName ) );\n\n stateChanged( \"fileOpened\" );\n DockManager::instance()->setDocksEnabled( true );\n\n if( centralWidget() )\n centralWidget()->setEnabled( true );\n\n statusBar()->showMessage( i18n( \"Project successfully opened\" ) );\n setCaption( i18n( \"%1 - Gluon Creator\", fileName.section( '\/', -1 ) ) );\n HistoryManager::instance()->clear();\n connect( HistoryManager::instance(), SIGNAL( historyChanged( const QUndoCommand* ) ), SLOT( historyChanged() ) );\n }\n else\n {\n statusBar()->showMessage( i18n( \"Unable to open project file...\" ) );\n }\n}\n\nvoid MainWindow::saveProject()\n{\n saveProject( d->fileName );\n}\n\nvoid MainWindow::saveProject( const QString& fileName )\n{\n if( !fileName.isEmpty() )\n {\n statusBar()->showMessage( i18n( \"Saving project...\" ) );\n GluonEngine::Game::instance()->gameProject()->setFilename( QUrl( fileName ) );\n QDir::setCurrent( KUrl( fileName ).directory() );\n if( !GluonEngine::Game::instance()->gameProject()->saveToFile() )\n {\n KMessageBox::error( this, i18n( \"Could not save file.\" ) );\n return;\n }\n statusBar()->showMessage( i18n( \"Project successfully saved.\" ) );\n setCaption( i18n( \"%1 - Gluon Creator\", fileName.section( '\/', -1 ) ) );\n HistoryManager::instance()->setClean();\n\n d->recentFiles->addUrl( KUrl( fileName ) );\n }\n else\n {\n saveProjectAs();\n }\n}\n\nvoid MainWindow::saveProjectAs()\n{\n d->fileName = KFileDialog::getSaveFileName( KUrl(), i18n( \"*.gluon|Gluon Project Files\" ) );\n if( !d->fileName.isEmpty() ) saveProject();\n}\n\nvoid MainWindow::setupActions()\n{\n KStandardAction::openNew( this, SLOT( showNewProjectDialog() ), actionCollection() );\n KStandardAction::open( this, SLOT( showOpenProjectDialog() ), actionCollection() );\n KStandardAction::save( this, SLOT( saveProject() ), actionCollection() );\n KStandardAction::saveAs( this, SLOT( saveProjectAs() ), actionCollection() );\n KStandardAction::quit( this, SLOT( close() ), actionCollection() );\n KStandardAction::preferences( this, SLOT( showPreferences() ), actionCollection() );\n\n KAction* undo = KStandardAction::undo( HistoryManager::instance(), SLOT( undo() ), actionCollection() );\n connect( HistoryManager::instance(), SIGNAL( canUndoChanged( bool ) ), undo, SLOT( setEnabled( bool ) ) );\n\n KAction* redo = KStandardAction::redo( HistoryManager::instance(), SLOT( redo() ), actionCollection() );\n connect( HistoryManager::instance(), SIGNAL( canRedoChanged( bool ) ), redo, SLOT( setEnabled( bool ) ) );\n\n connect( HistoryManager::instance(), SIGNAL( cleanChanged( bool ) ), SLOT( cleanChanged( bool ) ) );\n\n d->recentFiles = KStandardAction::openRecent( this, SLOT( openProject( KUrl ) ), actionCollection() );\n d->recentFiles->loadEntries( KGlobal::config()->group( \"Recent Files\" ) );\n\n KAction* newObject = new KAction( KIcon( \"document-new\" ), i18n( \"New Object\" ), actionCollection() );\n actionCollection()->addAction( \"newObject\", newObject );\n connect( newObject, SIGNAL( triggered( bool ) ), ObjectManager::instance(), SLOT( createNewGameObject() ) );\n\n KAction* newScene = new KAction( KIcon( \"document-new\" ), i18n( \"New Scene\" ), actionCollection() );\n actionCollection()->addAction( \"newScene\", newScene );\n connect( newScene, SIGNAL( triggered( bool ) ), ObjectManager::instance(), SLOT( createNewScene() ) );\n\n KAction* play = new KAction( KIcon( \"media-playback-start\" ), i18n( \"Play Game\" ), actionCollection() );\n actionCollection()->addAction( \"playGame\", play );\n connect( play, SIGNAL( triggered( bool ) ), SLOT( playGame() ) );\n\n KAction* pause = new KAction( KIcon( \"media-playback-pause\" ), i18n( \"Pause Game\" ), actionCollection() );\n actionCollection()->addAction( \"pauseGame\", pause );\n connect( pause, SIGNAL( triggered( bool ) ), SLOT( pauseGame() ) );\n\n KAction* stop = new KAction( KIcon( \"media-playback-stop\" ), i18n( \"Stop Game\" ), actionCollection() );\n actionCollection()->addAction( \"stopGame\", stop );\n connect( stop, SIGNAL( triggered( bool ) ), SLOT( stopGame() ) );\n\n KAction* addAsset = new KAction( KIcon( \"document-new\" ), i18n( \"Add Assets...\" ), actionCollection() );\n actionCollection()->addAction( \"addAsset\", addAsset );\n connect( addAsset, SIGNAL( triggered( bool ) ), SLOT( addAsset() ) );\n\n KAction* chooseEntryPoint = new KAction( KIcon( \"media-playback-start\" ), i18n( \"Set current scene as entry point\" ), actionCollection() );\n actionCollection()->addAction( \"chooseEntryPoint\", chooseEntryPoint );\n connect( chooseEntryPoint, SIGNAL( triggered( bool ) ), SLOT( chooseEntryPoint() ) );\n\n KAction* lockLayout = new KAction( KIcon( \"object-locked\" ), i18n( \"Lock layout\" ), actionCollection() );\n actionCollection()->addAction( \"lockLayout\", lockLayout );\n lockLayout->setCheckable( true );\n lockLayout->setChecked( GluonCreator::Settings::lockLayout() );\n connect( lockLayout, SIGNAL( triggered( bool ) ), DockManager::instance(), SLOT( setDocksLocked( bool ) ) );\n}\n\nvoid MainWindow::showPreferences()\n{\n if( KConfigDialog::showDialog( \"settings\" ) )\n {\n return;\n }\n ConfigDialog* dialog = new ConfigDialog( this, \"settings\", GluonCreator::Settings::self() );\n dialog->setAttribute( Qt::WA_DeleteOnClose );\n dialog->show();\n}\n\nvoid MainWindow::playGame( )\n{\n if( GluonEngine::Game::instance()->isRunning() )\n {\n GluonEngine::Game::instance()->setPause( false );\n stateChanged( \"paused\", StateReverse );\n }\n else\n {\n stateChanged( \"playing\" );\n\n d->mainArea->setActiveTab( 0 );\n\n QString currentSceneName = GluonEngine::Game::instance()->currentScene()->fullyQualifiedName();\n saveProject();\n\n \/\/Set the focus to the entire window, so that we do not accidentally trigger actions\n setFocus();\n\n \/\/Start the game loop\n \/\/Note that this starts an infinite loop in Game\n GluonEngine::Game::instance()->runGame();\n\n \/\/This happens after we exit the game loop\n stateChanged( \"playing\", StateReverse );\n\n openProject( d->fileName );\n GluonEngine::Game::instance()->setCurrentScene( currentSceneName );\n }\n}\n\nvoid MainWindow::pauseGame()\n{\n GluonEngine::Game::instance()->setPause( true );\n stateChanged( \"paused\" );\n}\n\nvoid MainWindow::stopGame()\n{\n GluonEngine::Game::instance()->stopGame();\n}\n\nvoid MainWindow::historyChanged()\n{\n GluonEngine::Game::instance()->drawAll();\n GluonEngine::Game::instance()->currentScene()->savableDirty = true;\n d->modified = true;\n\n setCaption( i18n( \"%1 [modified]\", d->fileName.isEmpty() ? i18n( \"New Project\" ) : d->fileName.section( '\/', -1 ) ) );\n}\n\nvoid MainWindow::cleanChanged( bool clean )\n{\n if( clean )\n {\n d->modified = false;\n setCaption( i18n( \"%1\", d->fileName.isEmpty() ? i18n( \"New Project\" ) : d->fileName.section( '\/', -1 ) ) );\n }\n}\n\nbool MainWindow::queryClose()\n{\n if( d->modified )\n {\n int code = KMessageBox::questionYesNoCancel( this, i18n( \"The project has been changed. Do you want to save before closing?\" ), i18n( \"Save Before Closing?\" ),\n KStandardGuiItem::save(), KStandardGuiItem::dontSave() );\n\n if( code == KMessageBox::Cancel )\n return false;\n\n if( code == KMessageBox::No )\n return true;\n\n saveProject();\n return true;\n }\n\n return true;\n}\n\nvoid MainWindow::addAsset()\n{\n QStringList assets = KFileDialog::getOpenFileNames();\n\n foreach( const QString & asset, assets )\n {\n ObjectManager::instance()->createNewAsset( asset );\n }\n}\n\nvoid MainWindow::chooseEntryPoint()\n{\n if( GluonEngine::Game::instance()->gameProject() )\n {\n if( GluonEngine::Game::instance()->currentScene() )\n {\n GluonEngine::Game::instance()->gameProject()->setEntryPoint( GluonEngine::Game::instance()->currentScene() );\n }\n }\n}\n\nvoid GluonCreator::MainWindow::showNewProjectDialog()\n{\n d->projectDialog->setPage( ProjectSelectionDialog::NewProjectPage );\n d->projectDialog->show();\n}\n\nvoid GluonCreator::MainWindow::showOpenProjectDialog()\n{\n d->projectDialog->setPage( ProjectSelectionDialog::OpenProjectPage );\n d->projectDialog->show();\n}\n\nvoid GluonCreator::MainWindow::projectDialogClosed()\n{\n openProject( d->projectDialog->fileName() );\n}\n\nvoid MainWindow::initializeGame()\n{\n\n\n}\n<commit_msg>Call initializeAll() after setCurrentScene, which calls stopAll() and cleanupAll().<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\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\n#include \"mainwindow.h\"\n\n#include <QtCore\/QVariantList>\n\n#include <KFileDialog>\n#include <KStandardAction>\n#include <KActionCollection>\n#include <KAction>\n#include <KStatusBar>\n#include <KMessageBox>\n#include <KConfigDialog>\n#include <KLocalizedString>\n#include <KPluginSelector>\n#include <KRun>\n#include <KRecentFilesAction>\n#include <KDE\/KTabWidget>\n#include <KDE\/KToolBar>\n#include <KDE\/KRichTextEdit>\n\n#include <core\/debughelper.h>\n#include <engine\/game.h>\n#include <engine\/gameproject.h>\n#include <engine\/scene.h>\n\n#include \"lib\/plugin.h\"\n#include \"lib\/pluginmanager.h\"\n#include \"lib\/objectmanager.h\"\n#include \"lib\/historymanager.h\"\n#include \"lib\/selectionmanager.h\"\n#include \"lib\/dockmanager.h\"\n#include \"lib\/filemanager.h\"\n#include \"lib\/widgets\/filearea.h\"\n\n#include \"gluoncreatorsettings.h\"\n#include \"dialogs\/configdialog.h\"\n#include <QVBoxLayout>\n#include <KParts\/PartManager>\n\nusing namespace GluonCreator;\n\nclass MainWindow::MainWindowPrivate\n{\n public:\n MainWindowPrivate()\n {\n }\n\n bool modified;\n QString fileName;\n KRecentFilesAction* recentFiles;\n ProjectSelectionDialog* projectDialog;\n\n FileArea* mainArea;\n};\n\nMainWindow::MainWindow( const QString& fileName )\n : KParts::MainWindow(),\n d( new MainWindowPrivate )\n{\n d->modified = false;\n\n GluonCore::GluonObjectFactory::instance()->loadPlugins();\n\n PluginManager::instance()->setParent( this );\n ObjectManager::instance()->setParent( this );\n HistoryManager::instance()->setParent( this );\n SelectionManager::instance()->setParent( this );\n\n DockManager::instance()->setParent( this );\n DockManager::instance()->setMainWindow( this );\n\n FileManager::instance()->initialize( this );\n connect( FileManager::instance()->partManager(), SIGNAL( activePartChanged( KParts::Part* ) ), this, SLOT( createGUI( KParts::Part* ) ) );\n\n PluginManager::instance()->setMainWindow( this );\n PluginManager::instance()->loadPlugins();\n\n setDockNestingEnabled( true );\n setCorner( Qt::TopLeftCorner, Qt::LeftDockWidgetArea );\n setCorner( Qt::BottomLeftCorner, Qt::LeftDockWidgetArea );\n setCorner( Qt::TopRightCorner, Qt::RightDockWidgetArea );\n setCorner( Qt::BottomRightCorner, Qt::RightDockWidgetArea );\n\n d->mainArea = new FileArea( this );\n setCentralWidget( d->mainArea );\n\n setupActions();\n setupGUI();\n stateChanged( \"initial\" );\n\n d->projectDialog = new ProjectSelectionDialog( this );\n d->projectDialog->setModal( true );\n connect( d->projectDialog, SIGNAL( accepted() ), SLOT( projectDialogClosed() ) );\n\n DockManager::instance()->setDocksEnabled( false );\n DockManager::instance()->setDocksLocked( GluonCreator::Settings::lockLayout() );\n\n if( fileName.isEmpty() )\n {\n showNewProjectDialog();\n }\n else\n {\n openProject( fileName );\n }\n}\n\nMainWindow::~MainWindow()\n{\n d->recentFiles->saveEntries( KGlobal::config()->group( \"Recent Files\" ) );\n GluonCreator::Settings::setLockLayout( actionCollection()->action( \"lockLayout\" )->isChecked() );\n GluonCreator::Settings::self()->writeConfig();\n GluonEngine::Game::instance()->stopGame();\n}\n\nvoid MainWindow::openProject( KUrl url )\n{\n openProject( url.path() );\n}\n\nvoid MainWindow::openProject( const QString& fileName )\n{\n if( !fileName.isEmpty() && QFile::exists( fileName ) )\n {\n statusBar()->showMessage( i18n( \"Opening project...\" ) );\n\n FileManager::instance()->openFile( fileName, i18nc( \"View Game Tab\", \"View\" ), \"gluon_viewer_part\", QVariantList() << QString( \"autoplay=false\" ) );\n\n GluonEngine::Game::instance()->initializeAll();\n GluonEngine::Game::instance()->drawAll();\n\n d->fileName = fileName;\n d->recentFiles->addUrl( KUrl( fileName ) );\n\n stateChanged( \"fileOpened\" );\n DockManager::instance()->setDocksEnabled( true );\n\n if( centralWidget() )\n centralWidget()->setEnabled( true );\n\n statusBar()->showMessage( i18n( \"Project successfully opened\" ) );\n setCaption( i18n( \"%1 - Gluon Creator\", fileName.section( '\/', -1 ) ) );\n HistoryManager::instance()->clear();\n connect( HistoryManager::instance(), SIGNAL( historyChanged( const QUndoCommand* ) ), SLOT( historyChanged() ) );\n }\n else\n {\n statusBar()->showMessage( i18n( \"Unable to open project file...\" ) );\n }\n}\n\nvoid MainWindow::saveProject()\n{\n saveProject( d->fileName );\n}\n\nvoid MainWindow::saveProject( const QString& fileName )\n{\n if( !fileName.isEmpty() )\n {\n statusBar()->showMessage( i18n( \"Saving project...\" ) );\n GluonEngine::Game::instance()->gameProject()->setFilename( QUrl( fileName ) );\n QDir::setCurrent( KUrl( fileName ).directory() );\n if( !GluonEngine::Game::instance()->gameProject()->saveToFile() )\n {\n KMessageBox::error( this, i18n( \"Could not save file.\" ) );\n return;\n }\n statusBar()->showMessage( i18n( \"Project successfully saved.\" ) );\n setCaption( i18n( \"%1 - Gluon Creator\", fileName.section( '\/', -1 ) ) );\n HistoryManager::instance()->setClean();\n\n d->recentFiles->addUrl( KUrl( fileName ) );\n }\n else\n {\n saveProjectAs();\n }\n}\n\nvoid MainWindow::saveProjectAs()\n{\n d->fileName = KFileDialog::getSaveFileName( KUrl(), i18n( \"*.gluon|Gluon Project Files\" ) );\n if( !d->fileName.isEmpty() ) saveProject();\n}\n\nvoid MainWindow::setupActions()\n{\n KStandardAction::openNew( this, SLOT( showNewProjectDialog() ), actionCollection() );\n KStandardAction::open( this, SLOT( showOpenProjectDialog() ), actionCollection() );\n KStandardAction::save( this, SLOT( saveProject() ), actionCollection() );\n KStandardAction::saveAs( this, SLOT( saveProjectAs() ), actionCollection() );\n KStandardAction::quit( this, SLOT( close() ), actionCollection() );\n KStandardAction::preferences( this, SLOT( showPreferences() ), actionCollection() );\n\n KAction* undo = KStandardAction::undo( HistoryManager::instance(), SLOT( undo() ), actionCollection() );\n connect( HistoryManager::instance(), SIGNAL( canUndoChanged( bool ) ), undo, SLOT( setEnabled( bool ) ) );\n\n KAction* redo = KStandardAction::redo( HistoryManager::instance(), SLOT( redo() ), actionCollection() );\n connect( HistoryManager::instance(), SIGNAL( canRedoChanged( bool ) ), redo, SLOT( setEnabled( bool ) ) );\n\n connect( HistoryManager::instance(), SIGNAL( cleanChanged( bool ) ), SLOT( cleanChanged( bool ) ) );\n\n d->recentFiles = KStandardAction::openRecent( this, SLOT( openProject( KUrl ) ), actionCollection() );\n d->recentFiles->loadEntries( KGlobal::config()->group( \"Recent Files\" ) );\n\n KAction* newObject = new KAction( KIcon( \"document-new\" ), i18n( \"New Object\" ), actionCollection() );\n actionCollection()->addAction( \"newObject\", newObject );\n connect( newObject, SIGNAL( triggered( bool ) ), ObjectManager::instance(), SLOT( createNewGameObject() ) );\n\n KAction* newScene = new KAction( KIcon( \"document-new\" ), i18n( \"New Scene\" ), actionCollection() );\n actionCollection()->addAction( \"newScene\", newScene );\n connect( newScene, SIGNAL( triggered( bool ) ), ObjectManager::instance(), SLOT( createNewScene() ) );\n\n KAction* play = new KAction( KIcon( \"media-playback-start\" ), i18n( \"Play Game\" ), actionCollection() );\n actionCollection()->addAction( \"playGame\", play );\n connect( play, SIGNAL( triggered( bool ) ), SLOT( playGame() ) );\n\n KAction* pause = new KAction( KIcon( \"media-playback-pause\" ), i18n( \"Pause Game\" ), actionCollection() );\n actionCollection()->addAction( \"pauseGame\", pause );\n connect( pause, SIGNAL( triggered( bool ) ), SLOT( pauseGame() ) );\n\n KAction* stop = new KAction( KIcon( \"media-playback-stop\" ), i18n( \"Stop Game\" ), actionCollection() );\n actionCollection()->addAction( \"stopGame\", stop );\n connect( stop, SIGNAL( triggered( bool ) ), SLOT( stopGame() ) );\n\n KAction* addAsset = new KAction( KIcon( \"document-new\" ), i18n( \"Add Assets...\" ), actionCollection() );\n actionCollection()->addAction( \"addAsset\", addAsset );\n connect( addAsset, SIGNAL( triggered( bool ) ), SLOT( addAsset() ) );\n\n KAction* chooseEntryPoint = new KAction( KIcon( \"media-playback-start\" ), i18n( \"Set current scene as entry point\" ), actionCollection() );\n actionCollection()->addAction( \"chooseEntryPoint\", chooseEntryPoint );\n connect( chooseEntryPoint, SIGNAL( triggered( bool ) ), SLOT( chooseEntryPoint() ) );\n\n KAction* lockLayout = new KAction( KIcon( \"object-locked\" ), i18n( \"Lock layout\" ), actionCollection() );\n actionCollection()->addAction( \"lockLayout\", lockLayout );\n lockLayout->setCheckable( true );\n lockLayout->setChecked( GluonCreator::Settings::lockLayout() );\n connect( lockLayout, SIGNAL( triggered( bool ) ), DockManager::instance(), SLOT( setDocksLocked( bool ) ) );\n}\n\nvoid MainWindow::showPreferences()\n{\n if( KConfigDialog::showDialog( \"settings\" ) )\n {\n return;\n }\n ConfigDialog* dialog = new ConfigDialog( this, \"settings\", GluonCreator::Settings::self() );\n dialog->setAttribute( Qt::WA_DeleteOnClose );\n dialog->show();\n}\n\nvoid MainWindow::playGame( )\n{\n if( GluonEngine::Game::instance()->isRunning() )\n {\n GluonEngine::Game::instance()->setPause( false );\n stateChanged( \"paused\", StateReverse );\n }\n else\n {\n stateChanged( \"playing\" );\n\n d->mainArea->setActiveTab( 0 );\n\n QString currentSceneName = GluonEngine::Game::instance()->currentScene()->fullyQualifiedName();\n saveProject();\n\n \/\/Set the focus to the entire window, so that we do not accidentally trigger actions\n setFocus();\n\n \/\/Start the game loop\n \/\/Note that this starts an infinite loop in Game\n GluonEngine::Game::instance()->runGame();\n\n \/\/This happens after we exit the game loop\n stateChanged( \"playing\", StateReverse );\n\n openProject( d->fileName );\n GluonEngine::Game::instance()->setCurrentScene( currentSceneName );\n GluonEngine::Game::instance()->initializeAll();\n }\n}\n\nvoid MainWindow::pauseGame()\n{\n GluonEngine::Game::instance()->setPause( true );\n stateChanged( \"paused\" );\n}\n\nvoid MainWindow::stopGame()\n{\n GluonEngine::Game::instance()->stopGame();\n}\n\nvoid MainWindow::historyChanged()\n{\n GluonEngine::Game::instance()->drawAll();\n GluonEngine::Game::instance()->currentScene()->savableDirty = true;\n d->modified = true;\n\n setCaption( i18n( \"%1 [modified]\", d->fileName.isEmpty() ? i18n( \"New Project\" ) : d->fileName.section( '\/', -1 ) ) );\n}\n\nvoid MainWindow::cleanChanged( bool clean )\n{\n if( clean )\n {\n d->modified = false;\n setCaption( i18n( \"%1\", d->fileName.isEmpty() ? i18n( \"New Project\" ) : d->fileName.section( '\/', -1 ) ) );\n }\n}\n\nbool MainWindow::queryClose()\n{\n if( d->modified )\n {\n int code = KMessageBox::questionYesNoCancel( this, i18n( \"The project has been changed. Do you want to save before closing?\" ), i18n( \"Save Before Closing?\" ),\n KStandardGuiItem::save(), KStandardGuiItem::dontSave() );\n\n if( code == KMessageBox::Cancel )\n return false;\n\n if( code == KMessageBox::No )\n return true;\n\n saveProject();\n return true;\n }\n\n return true;\n}\n\nvoid MainWindow::addAsset()\n{\n QStringList assets = KFileDialog::getOpenFileNames();\n\n foreach( const QString & asset, assets )\n {\n ObjectManager::instance()->createNewAsset( asset );\n }\n}\n\nvoid MainWindow::chooseEntryPoint()\n{\n if( GluonEngine::Game::instance()->gameProject() )\n {\n if( GluonEngine::Game::instance()->currentScene() )\n {\n GluonEngine::Game::instance()->gameProject()->setEntryPoint( GluonEngine::Game::instance()->currentScene() );\n }\n }\n}\n\nvoid GluonCreator::MainWindow::showNewProjectDialog()\n{\n d->projectDialog->setPage( ProjectSelectionDialog::NewProjectPage );\n d->projectDialog->show();\n}\n\nvoid GluonCreator::MainWindow::showOpenProjectDialog()\n{\n d->projectDialog->setPage( ProjectSelectionDialog::OpenProjectPage );\n d->projectDialog->show();\n}\n\nvoid GluonCreator::MainWindow::projectDialogClosed()\n{\n openProject( d->projectDialog->fileName() );\n}\n\nvoid MainWindow::initializeGame()\n{\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: dockWidget.C,v 1.4 2003\/09\/09 23:23:22 amoll Exp $\n\n#include <BALL\/VIEW\/WIDGETS\/dockWidget.h>\n#include <BALL\/VIEW\/KERNEL\/mainControl.h>\n#include <qmenubar.h>\n#include <qlabel.h>\n\nusing std::endl;\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\t\t\nDockWidget::DockWidget(QWidget* parent, const char* name)\n: QDockWindow(QDockWindow::InDock, parent),\n\tModularWidget(name)\n{\n\tlayout_ = new QVBoxLayout(this);\n caption_label_ = new QLabel(this, \"caption_label\");\n\tcaption_label_->resize(120, 12);\n caption_label_->setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed, 0, 0, false));\n caption_label_->setPaletteBackgroundColor( QColor( 255, 255, 127 ) );\n QFont caption_label_font(caption_label_->font());\n caption_label_font.setFamily( \"Helvetica\" );\n caption_label_font.setPointSize( 11 );\n caption_label_->setFont( caption_label_font ); \n caption_label_->setFrameShape(QLabel::NoFrame);\n caption_label_->setAlignment(QLabel::AlignCenter);\n\tlayout_->addWidget(caption_label_);\n\tboxLayout()->addItem(layout_);\n\n\tsetOrientation(Qt::Vertical);\n resize( QSize(132, 293));\n\n\tif (name != 0) \n\t{ \n\t\tsetCaption(name);\n\t\tsetName(name);\n\t\tcaption_label_->setText(name);\n\t}\n\telse \n\t{\n\t\tsetName(\"DockWidget\");\n\t}\n\n\tregisterWidget(this);\n}\n\nvoid DockWidget::setGuest(QWidget& guest)\n{\n\tQPoint p;\n\tguest.reparent(this, p, true);\n\tguest.resize(120,1000);\n guest.setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, 0, 0, false));\n\tlayout_->addWidget(&guest);\n\tsetMinimumSize(20, 20);\n\tsetCloseMode(QDockWindow::Always);\n\tsetResizeEnabled(true);\n}\n\nvoid DockWidget::initializeWidget(MainControl& main_control)\n\tthrow()\n{\n\twindow_menu_entry_id_ = \n\t\tmain_control.insertMenuEntry(MainControl::WINDOWS, getIdentifier(), this, SLOT(switchShowWidget()));\n\tgetMainControl()->menuBar()->setItemChecked(window_menu_entry_id_, true);\n}\n\n\nvoid DockWidget::finalizeWidget(MainControl& main_control)\n\tthrow()\n{\n\tmain_control.removeMenuEntry(MainControl::WINDOWS, getIdentifier(), this, SLOT(switchShowWidget()));\n}\n\n\nvoid DockWidget::switchShowWidget()\n\tthrow()\n{\n\tQMenuBar* menu = getMainControl()->menuBar();\n\tif (menu->isItemChecked(window_menu_entry_id_))\n\t{\n\t\thide();\n\t\tmenu->setItemChecked(window_menu_entry_id_, false);\n\t}\n\telse\n\t{\n\t\tshow();\n\t\tmenu->setItemChecked(window_menu_entry_id_, true);\n\t}\n}\n\nvoid DockWidget::writePreferences(INIFile& inifile)\n\tthrow()\n{\n\tinifile.insertValue(\"WINDOWS\", getIdentifier() + \"::on\", \n\t\tString(getMainControl()->menuBar()->isItemChecked(window_menu_entry_id_)));\n}\n\nvoid DockWidget::fetchPreferences(INIFile & inifile)\n\tthrow()\n{\n\tif (!inifile.hasEntry(\"WINDOWS\", getIdentifier() + \"::on\")) return;\n\tif (inifile.getValue( \"WINDOWS\", getIdentifier() + \"::on\").toUnsignedInt() == 0) \n\t{\n\t\tswitchShowWidget();\n\t}\n}\n\n\nvoid DockWidget::close()\n{\nLog.error() << \"#~~# 1\" << std::endl;\n\tQDockWindow::close();\n}\n\n} } \/\/ namespaces\n<commit_msg>no message<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: dockWidget.C,v 1.5 2003\/09\/10 01:27:49 amoll Exp $\n\n#include <BALL\/VIEW\/WIDGETS\/dockWidget.h>\n#include <BALL\/VIEW\/KERNEL\/mainControl.h>\n#include <qmenubar.h>\n#include <qlabel.h>\n\nusing std::endl;\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\t\t\nDockWidget::DockWidget(QWidget* parent, const char* name)\n: QDockWindow(QDockWindow::InDock, parent),\n\tModularWidget(name),\n\tdefault_visible_(true)\n{\n\tlayout_ = new QVBoxLayout(this);\n caption_label_ = new QLabel(this, \"caption_label\");\n\tcaption_label_->resize(120, 12);\n caption_label_->setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed, 0, 0, false));\n caption_label_->setPaletteBackgroundColor( QColor( 255, 255, 127 ) );\n QFont caption_label_font(caption_label_->font());\n caption_label_font.setFamily( \"Helvetica\" );\n caption_label_font.setPointSize( 11 );\n caption_label_->setFont( caption_label_font ); \n caption_label_->setFrameShape(QLabel::NoFrame);\n caption_label_->setAlignment(QLabel::AlignCenter);\n\tlayout_->addWidget(caption_label_);\n\tboxLayout()->addItem(layout_);\n\n\tsetOrientation(Qt::Vertical);\n resize( QSize(132, 293));\n\n\tif (name != 0) \n\t{ \n\t\tsetCaption(name);\n\t\tsetName(name);\n\t\tcaption_label_->setText(name);\n\t}\n\telse \n\t{\n\t\tsetName(\"DockWidget\");\n\t}\n\n\tregisterWidget(this);\n}\n\nvoid DockWidget::setGuest(QWidget& guest)\n{\n\tQPoint p;\n\tguest.reparent(this, p, true);\n\tguest.resize(120,1000);\n guest.setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, 0, 0, false));\n\tlayout_->addWidget(&guest);\n\tsetMinimumSize(20, 20);\n\tsetCloseMode(QDockWindow::Always);\n\tsetResizeEnabled(true);\n}\n\nvoid DockWidget::initializeWidget(MainControl& main_control)\n\tthrow()\n{\n\twindow_menu_entry_id_ = \n\t\tmain_control.insertMenuEntry(MainControl::WINDOWS, getIdentifier(), this, SLOT(switchShowWidget()));\n\tgetMainControl()->menuBar()->setItemChecked(window_menu_entry_id_, true);\n}\n\n\nvoid DockWidget::finalizeWidget(MainControl& main_control)\n\tthrow()\n{\n\tmain_control.removeMenuEntry(MainControl::WINDOWS, getIdentifier(), this, SLOT(switchShowWidget()));\n}\n\n\nvoid DockWidget::switchShowWidget()\n\tthrow()\n{\n\tQMenuBar* menu = getMainControl()->menuBar();\n\tif (menu->isItemChecked(window_menu_entry_id_))\n\t{\n\t\thide();\n\t\tmenu->setItemChecked(window_menu_entry_id_, false);\n\t}\n\telse\n\t{\n\t\tshow();\n\t\tmenu->setItemChecked(window_menu_entry_id_, true);\n\t}\n}\n\nvoid DockWidget::writePreferences(INIFile& inifile)\n\tthrow()\n{\n\tinifile.insertValue(\"WINDOWS\", getIdentifier() + \"::on\", \n\t\tString(getMainControl()->menuBar()->isItemChecked(window_menu_entry_id_)));\n\n\tinifile.insertValue(\"WINDOWS\", getIdentifier() + \"::x\", String(x()));\n\tinifile.insertValue(\"WINDOWS\", getIdentifier() + \"::y\", String(y()));\n\tinifile.insertValue(\"WINDOWS\", getIdentifier() + \"::width\", String(width()));\n\tinifile.insertValue(\"WINDOWS\", getIdentifier() + \"::height\", String(height()));\n\n\tinifile.insertValue(\"WINDOWS\", getIdentifier() + \"::docked\", String(place()));\n}\n\nvoid DockWidget::fetchPreferences(INIFile & inifile)\n\tthrow()\n{\n\tif (\t (inifile.hasEntry(\"WINDOWS\", getIdentifier() + \"::on\") &&\n\t\t\t\t inifile.getValue(\"WINDOWS\", getIdentifier() + \"::on\").toUnsignedInt() == 0)\n\t\t || (!default_visible_))\n\t{\n\t\tswitchShowWidget();\n\t}\n\n\tif (inifile.hasEntry(\"WINDOWS\", getIdentifier() + \"::x\"))\n\t{\n\t\tsetGeometry(inifile.getValue(\"WINDOWS\", getIdentifier() + \"::x\").toUnsignedInt(),\n\t\t inifile.getValue(\"WINDOWS\", getIdentifier() + \"::y\").toUnsignedInt(),\n\t\t inifile.getValue(\"WINDOWS\", getIdentifier() + \"::width\").toUnsignedInt(),\n\t\t inifile.getValue(\"WINDOWS\", getIdentifier() + \"::height\").toUnsignedInt());\n\t}\n\n\tif (inifile.hasEntry(\"WINDOWS\", getIdentifier() + \"::docked\") &&\n\t\t\tinifile.getValue(\"WINDOWS\", getIdentifier() + \"::docked\").toUnsignedInt() != 0)\n\t{\n\t\tundock();\n\t}\n}\n\n} } \/\/ namespaces\n<|endoftext|>"} {"text":"<commit_before>\/*\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. See the\n * GNU Library 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, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * OpenDmxThread.h\n * Thread for the open dmx device\n * Copyright (C) 2005-2007 Simon Newton\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/time.h>\n#include <time.h>\n\n#include <llad\/logger.h>\n#include \"OpenDmxThread.h\"\n\nnamespace lla {\nnamespace plugin {\n\nusing std::string;\n\ntypedef struct {\n OpenDmxThread *th;\n string path;\n} t_args;\n\n\nvoid *thread_run(void *d) {\n t_args *args = (t_args*) d;\n\n args->th->Run(args->path);\n free(args);\n}\n\n\/*\n * Create a new OpenDmxThread object\n *\n *\/\nOpenDmxThread::OpenDmxThread() {\n m_fd = -1;\n memset(m_dmx, 0x00, DMX_UNIVERSE_SIZE);\n pthread_mutex_init(&m_mutex, NULL);\n m_term = false;\n pthread_mutex_init(&m_term_mutex, NULL);\n pthread_cond_init(&m_term_cond, NULL);\n\n m_tid = 0;\n}\n\n\n\/*\n *\n *\/\nOpenDmxThread::~OpenDmxThread() {\n pthread_cond_destroy(&m_term_cond);\n pthread_mutex_destroy(&m_term_mutex);\n pthread_mutex_destroy(&m_mutex);\n}\n\n\n\/*\n * run this thread\n *\n *\/\nvoid *OpenDmxThread::Run(const string &path) {\n uint8_t buf[DMX_UNIVERSE_SIZE+1];\n struct timeval tv;\n struct timespec ts;\n\n \/\/ should close other fd here\n\n \/\/ start code\n buf[0] = 0x00;\n m_fd = open(path.c_str(), O_WRONLY);\n\n while (1) {\n pthread_mutex_lock(&m_term_mutex);\n if (m_term) {\n pthread_mutex_unlock(&m_term_mutex);\n break;\n }\n pthread_mutex_unlock(&m_term_mutex);\n\n if (m_fd == -1) {\n if (gettimeofday(&tv, NULL) < 0) {\n printf(\"gettimeofday error\\n\");\n break;\n }\n ts.tv_sec = tv.tv_sec + 1;\n ts.tv_nsec = tv.tv_usec * 1000;\n\n pthread_cond_timedwait(&m_term_cond, &m_term_mutex, &ts);\n pthread_mutex_unlock(&m_term_mutex);\n\n m_fd = open(path.c_str(), O_WRONLY);\n\n if (m_fd == -1)\n printf(\"open %d: %s\\n\", m_fd, strerror(errno));\n\n } else {\n pthread_mutex_lock(&m_mutex);\n memcpy(&buf[1], m_dmx, DMX_UNIVERSE_SIZE);\n pthread_mutex_unlock(&m_mutex);\n\n do_write(buf, DMX_UNIVERSE_SIZE + 1);\n }\n }\n return NULL;\n}\n\n\n\/*\n * Start this thread\n *\n *\/\nint OpenDmxThread::Start(const string &path) {\n \/\/ this is passed to the thread and free'ed there\n t_args *args = (t_args*) malloc(sizeof(t_args));\n\n args->th = this;\n args->path = path;\n\n if (pthread_create(&m_tid, NULL, lla::plugin::thread_run, (void*) args)) {\n Logger::instance()->log(Logger::WARN, \"pthread create failed\");\n return -1;\n }\n return 0;\n}\n\n\n\/*\n * Stop the thread\n *\n *\/\nint OpenDmxThread::Stop() {\n pthread_mutex_lock(&m_term_mutex);\n m_term = true;\n pthread_mutex_unlock(&m_term_mutex);\n\n pthread_cond_signal(&m_term_cond);\n pthread_join(m_tid, NULL);\n}\n\n\n\n\/*\n * Store the data in the shared buffer\n *\n *\/\nint OpenDmxThread::WriteDmx(uint8_t *data, int length) {\n pthread_mutex_lock(&m_mutex);\n memcpy(m_dmx, data, length);\n pthread_mutex_unlock(&m_mutex);\n}\n\n\n\nint OpenDmxThread::do_write(uint8_t *buf, int length) {\n int res = write(m_fd, buf, length);\n\n if (res < 0) {\n \/\/ if you unplug devices from the dongle\n perror(\"Error writing to device\");\n\n res = close(m_fd);\n if (res < 0)\n perror(\"close\");\n else\n m_fd = -1;\n\n return -1;\n }\n return 0;\n}\n\n} \/\/ plugin\n} \/\/ lla\n<commit_msg> * fix a bug in the OpenDmx plugin - thanks Christopher Staite<commit_after>\/*\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. See the\n * GNU Library 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, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * OpenDmxThread.h\n * Thread for the open dmx device\n * Copyright (C) 2005-2007 Simon Newton\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/time.h>\n#include <time.h>\n\n#include <llad\/logger.h>\n#include \"OpenDmxThread.h\"\n\nnamespace lla {\nnamespace plugin {\n\nusing std::string;\n\ntypedef struct {\n OpenDmxThread *th;\n string path;\n} t_args;\n\n\nvoid *thread_run(void *d) {\n t_args *args = (t_args*) d;\n\n args->th->Run(args->path);\n delete args;\n}\n\n\/*\n * Create a new OpenDmxThread object\n *\n *\/\nOpenDmxThread::OpenDmxThread() {\n m_fd = -1;\n memset(m_dmx, 0x00, DMX_UNIVERSE_SIZE);\n pthread_mutex_init(&m_mutex, NULL);\n m_term = false;\n pthread_mutex_init(&m_term_mutex, NULL);\n pthread_cond_init(&m_term_cond, NULL);\n\n m_tid = 0;\n}\n\n\n\/*\n *\n *\/\nOpenDmxThread::~OpenDmxThread() {\n pthread_cond_destroy(&m_term_cond);\n pthread_mutex_destroy(&m_term_mutex);\n pthread_mutex_destroy(&m_mutex);\n}\n\n\n\/*\n * run this thread\n *\n *\/\nvoid *OpenDmxThread::Run(const string &path) {\n uint8_t buf[DMX_UNIVERSE_SIZE+1];\n struct timeval tv;\n struct timespec ts;\n\n \/\/ should close other fd here\n\n \/\/ start code\n buf[0] = 0x00;\n m_fd = open(path.c_str(), O_WRONLY);\n\n while (1) {\n pthread_mutex_lock(&m_term_mutex);\n if (m_term) {\n pthread_mutex_unlock(&m_term_mutex);\n break;\n }\n pthread_mutex_unlock(&m_term_mutex);\n\n if (m_fd == -1) {\n if (gettimeofday(&tv, NULL) < 0) {\n printf(\"gettimeofday error\\n\");\n break;\n }\n ts.tv_sec = tv.tv_sec + 1;\n ts.tv_nsec = tv.tv_usec * 1000;\n\n pthread_cond_timedwait(&m_term_cond, &m_term_mutex, &ts);\n pthread_mutex_unlock(&m_term_mutex);\n\n m_fd = open(path.c_str(), O_WRONLY);\n\n if (m_fd == -1)\n printf(\"open %d: %s\\n\", m_fd, strerror(errno));\n\n } else {\n pthread_mutex_lock(&m_mutex);\n memcpy(&buf[1], m_dmx, DMX_UNIVERSE_SIZE);\n pthread_mutex_unlock(&m_mutex);\n\n do_write(buf, DMX_UNIVERSE_SIZE + 1);\n }\n }\n return NULL;\n}\n\n\n\/*\n * Start this thread\n *\n *\/\nint OpenDmxThread::Start(const string &path) {\n \/\/ this is passed to the thread and free'ed there\n t_args *args = new t_args;\n\n args->th = this;\n args->path = path;\n\n if (pthread_create(&m_tid, NULL, lla::plugin::thread_run, (void*) args)) {\n Logger::instance()->log(Logger::WARN, \"pthread create failed\");\n return -1;\n }\n return 0;\n}\n\n\n\/*\n * Stop the thread\n *\n *\/\nint OpenDmxThread::Stop() {\n pthread_mutex_lock(&m_term_mutex);\n m_term = true;\n pthread_mutex_unlock(&m_term_mutex);\n\n pthread_cond_signal(&m_term_cond);\n pthread_join(m_tid, NULL);\n}\n\n\n\n\/*\n * Store the data in the shared buffer\n *\n *\/\nint OpenDmxThread::WriteDmx(uint8_t *data, int length) {\n pthread_mutex_lock(&m_mutex);\n memcpy(m_dmx, data, length);\n pthread_mutex_unlock(&m_mutex);\n}\n\n\n\nint OpenDmxThread::do_write(uint8_t *buf, int length) {\n int res = write(m_fd, buf, length);\n\n if (res < 0) {\n \/\/ if you unplug devices from the dongle\n perror(\"Error writing to device\");\n\n res = close(m_fd);\n if (res < 0)\n perror(\"close\");\n else\n m_fd = -1;\n\n return -1;\n }\n return 0;\n}\n\n} \/\/ plugin\n} \/\/ lla\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Small fix for krystal scene (removed DebugFrameRender).<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ PROJECT: Aspia Remote Desktop\r\n\/\/ FILE: desktop_capture\/differ.cc\r\n\/\/ LICENSE: Mozilla Public License Version 2.0\r\n\/\/ PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)\r\n\/\/\r\n\r\n#include \"desktop_capture\/differ.h\"\r\n\r\n#include \"desktop_capture\/diff_block_sse2.h\"\r\n\r\nnamespace aspia {\r\n\r\nstatic const int kBytesPerPixel = 4;\r\nstatic const int kBlockSize = 16;\r\nstatic const int kBytesPerBlock = kBytesPerPixel * kBlockSize;\r\n\r\nstatic INLINE uint8_t DiffFullBlock_C(const uint8_t* image1,\r\n const uint8_t* image2,\r\n int bytes_per_row)\r\n{\r\n for (int y = 0; y < kBlockSize; ++y)\r\n {\r\n if (memcmp(image1, image2, kBytesPerBlock) != 0)\r\n {\r\n return 1U;\r\n }\r\n\r\n image1 += bytes_per_row;\r\n image2 += bytes_per_row;\r\n }\r\n\r\n return 0U;\r\n}\r\n\r\n\/\/\r\n\/\/ Check for diffs in upper-left portion of the block. The size of the portion\r\n\/\/ to check is specified by the |width| and |height| values.\r\n\/\/ Note that if we force the capturer to always return images whose width and\r\n\/\/ height are multiples of kBlockSize, then this will never be called.\r\n\/\/\r\nstatic INLINE uint8_t DiffPartialBlock(const uint8_t* prev_image,\r\n const uint8_t* curr_image,\r\n int bytes_per_row,\r\n int bytes_per_block,\r\n int height)\r\n{\r\n for (int y = 0; y < height; ++y)\r\n {\r\n if (memcmp(prev_image, curr_image, bytes_per_block) != 0)\r\n {\r\n return 1U;\r\n }\r\n\r\n prev_image += bytes_per_row;\r\n curr_image += bytes_per_row;\r\n }\r\n\r\n return 0U;\r\n}\r\n\r\nDiffer::Differ(const DesktopSize& size)\r\n : size_(size),\r\n bytes_per_row_(size.Width() * kBytesPerPixel),\r\n diff_width_(((size.Width() + kBlockSize - 1) \/ kBlockSize) + 1),\r\n diff_height_(((size.Height() + kBlockSize - 1) \/ kBlockSize) + 1),\r\n full_blocks_x_(size.Width() \/ kBlockSize),\r\n full_blocks_y_(size.Height() \/ kBlockSize)\r\n{\r\n const int diff_info_size = diff_width_ * diff_height_;\r\n\r\n diff_info_ = std::make_unique<uint8_t[]>(diff_info_size);\r\n memset(diff_info_.get(), 0, diff_info_size);\r\n\r\n \/\/ Calc size of partial blocks which may be present on right and bottom\r\n \/\/ edge.\r\n partial_column_width_ = size.Width() - (full_blocks_x_ * kBlockSize);\r\n partial_row_height_ = size.Height() - (full_blocks_y_ * kBlockSize);\r\n\r\n \/\/ Offset from the start of one block-row to the next.\r\n block_stride_y_ = bytes_per_row_ * kBlockSize;\r\n}\r\n\r\n\/\/\r\n\/\/ Identify all of the blocks that contain changed pixels.\r\n\/\/\r\nvoid Differ::MarkDirtyBlocks(const uint8_t* prev_image, const uint8_t* curr_image)\r\n{\r\n const uint8_t* prev_block_row_start = prev_image;\r\n const uint8_t* curr_block_row_start = curr_image;\r\n\r\n \/\/ Offset from the start of one diff_info row to the next.\r\n const int diff_stride = diff_width_;\r\n\r\n uint8_t* is_diff_row_start = diff_info_.get();\r\n\r\n for (int y = 0; y < full_blocks_y_; ++y)\r\n {\r\n const uint8_t* prev_block = prev_block_row_start;\r\n const uint8_t* curr_block = curr_block_row_start;\r\n\r\n uint8_t* is_different = is_diff_row_start;\r\n\r\n for (int x = 0; x < full_blocks_x_; ++x)\r\n {\r\n \/\/ For x86 and x86_64, we do not support processors that do not\r\n \/\/ have SSE2 instructions support.\r\n if (kBlockSize == 16)\r\n {\r\n \/\/ Mark this block as being modified so that it gets\r\n \/\/ incorporated into a dirty rect.\r\n *is_different = DiffFullBlock_16x16_SSE2(prev_block,\r\n curr_block,\r\n bytes_per_row_);\r\n }\r\n else if (kBlockSize == 32)\r\n {\r\n \/\/ Mark this block as being modified so that it gets\r\n \/\/ incorporated into a dirty rect.\r\n *is_different = DiffFullBlock_32x32_SSE2(prev_block,\r\n curr_block,\r\n bytes_per_row_);\r\n }\r\n\r\n prev_block += kBytesPerBlock;\r\n curr_block += kBytesPerBlock;\r\n\r\n ++is_different;\r\n }\r\n\r\n \/\/\r\n \/\/ If there is a partial column at the end, handle it.\r\n \/\/ This condition should rarely, if ever, occur.\r\n \/\/\r\n if (partial_column_width_ != 0)\r\n {\r\n *is_different = DiffPartialBlock(prev_block,\r\n curr_block,\r\n bytes_per_row_,\r\n kBytesPerBlock,\r\n kBlockSize);\r\n\r\n ++is_different;\r\n }\r\n\r\n \/\/ Update pointers for next row.\r\n prev_block_row_start += block_stride_y_;\r\n curr_block_row_start += block_stride_y_;\r\n\r\n is_diff_row_start += diff_stride;\r\n }\r\n\r\n \/\/ If the screen height is not a multiple of the block size, then this\r\n \/\/ handles the last partial row. This situation is far more common than\r\n \/\/ the 'partial column' case.\r\n if (partial_row_height_ != 0)\r\n {\r\n const uint8_t* prev_block = prev_block_row_start;\r\n const uint8_t* curr_block = curr_block_row_start;\r\n\r\n uint8_t* is_different = is_diff_row_start;\r\n\r\n for (int x = 0; x < full_blocks_x_; ++x)\r\n {\r\n *is_different = DiffPartialBlock(prev_block,\r\n curr_block,\r\n bytes_per_row_,\r\n kBytesPerBlock,\r\n partial_row_height_);\r\n\r\n prev_block += kBytesPerBlock;\r\n curr_block += kBytesPerBlock;\r\n ++is_different;\r\n }\r\n\r\n if (partial_column_width_ != 0)\r\n {\r\n *is_different =\r\n DiffPartialBlock(prev_block,\r\n curr_block,\r\n bytes_per_row_,\r\n partial_column_width_ * kBytesPerPixel,\r\n partial_row_height_);\r\n }\r\n }\r\n}\r\n\r\n\/\/\r\n\/\/ After the dirty blocks have been identified, this routine merges adjacent\r\n\/\/ blocks into a region.\r\n\/\/ The goal is to minimize the region that covers the dirty blocks.\r\n\/\/\r\nvoid Differ::MergeBlocks(DesktopRegion* dirty_region)\r\n{\r\n uint8_t* is_diff_row_start = diff_info_.get();\r\n const int diff_stride = diff_width_;\r\n\r\n for (int y = 0; y < diff_height_; ++y)\r\n {\r\n uint8_t* is_different = is_diff_row_start;\r\n\r\n for (int x = 0; x < diff_width_; ++x)\r\n {\r\n \/\/ We've found a modified block. Look at blocks to the right and\r\n \/\/ below to group this block with as many others as we can.\r\n if (*is_different != 0)\r\n {\r\n \/\/ Width and height of the rectangle in blocks.\r\n int width = 1;\r\n int height = 1;\r\n\r\n *is_different = 0;\r\n\r\n \/\/ Group with blocks to the right.\r\n \/\/ We can keep looking until we find an unchanged block because\r\n \/\/ we have a boundary block which is never marked as having\r\n \/\/ diffs.\r\n uint8_t* right = is_different + 1;\r\n\r\n while (*right != 0)\r\n {\r\n *right++ = 0;\r\n ++width;\r\n }\r\n\r\n \/\/ Group with blocks below.\r\n \/\/ The entire width of blocks that we matched above much match\r\n \/\/ for each row that we add.\r\n uint8_t* bottom = is_different;\r\n bool found_new_row;\r\n\r\n do\r\n {\r\n found_new_row = true;\r\n bottom += diff_stride;\r\n right = bottom;\r\n\r\n for (int x2 = 0; x2 < width; ++x2)\r\n {\r\n if (*right++ == 0)\r\n found_new_row = false;\r\n }\r\n\r\n if (found_new_row)\r\n {\r\n ++height;\r\n\r\n \/\/ We need to go back and erase the diff markers so\r\n \/\/ that we don't try to add these blocks a second time.\r\n right = bottom;\r\n\r\n for (int x2 = 0; x2 < width; ++x2)\r\n {\r\n *right++ = 0;\r\n }\r\n }\r\n } while (found_new_row);\r\n\r\n int32_t l = x * kBlockSize;\r\n int32_t t = y * kBlockSize;\r\n int32_t r = l + (width * kBlockSize);\r\n int32_t b = t + (height * kBlockSize);\r\n\r\n if (r > size_.Width())\r\n r = size_.Width();\r\n\r\n if (b > size_.Height())\r\n b = size_.Height();\r\n\r\n \/\/ Add rect to region.\r\n dirty_region->AddRect(DesktopRect::MakeLTRB(l, t, r, b));\r\n }\r\n\r\n \/\/ Increment to next block in this row.\r\n ++is_different;\r\n }\r\n\r\n \/\/ Go to start of next row.\r\n is_diff_row_start += diff_stride;\r\n }\r\n}\r\n\r\nvoid Differ::CalcDirtyRegion(const uint8_t* prev_image,\r\n const uint8_t* curr_image,\r\n DesktopRegion* dirty_region)\r\n{\r\n dirty_region->Clear();\r\n\r\n \/\/ Identify all the blocks that contain changed pixels.\r\n MarkDirtyBlocks(prev_image, curr_image);\r\n\r\n \/\/\r\n \/\/ Now that we've identified the blocks that have changed, merge adjacent\r\n \/\/ blocks to minimize the number of rects that we return.\r\n \/\/\r\n MergeBlocks(dirty_region);\r\n}\r\n\r\n} \/\/ namespace aspia\r\n<commit_msg>- Remove unneeded increment<commit_after>\/\/\r\n\/\/ PROJECT: Aspia Remote Desktop\r\n\/\/ FILE: desktop_capture\/differ.cc\r\n\/\/ LICENSE: Mozilla Public License Version 2.0\r\n\/\/ PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)\r\n\/\/\r\n\r\n#include \"desktop_capture\/differ.h\"\r\n\r\n#include \"desktop_capture\/diff_block_sse2.h\"\r\n\r\nnamespace aspia {\r\n\r\nstatic const int kBytesPerPixel = 4;\r\nstatic const int kBlockSize = 16;\r\nstatic const int kBytesPerBlock = kBytesPerPixel * kBlockSize;\r\n\r\nstatic INLINE uint8_t DiffFullBlock_C(const uint8_t* image1,\r\n const uint8_t* image2,\r\n int bytes_per_row)\r\n{\r\n for (int y = 0; y < kBlockSize; ++y)\r\n {\r\n if (memcmp(image1, image2, kBytesPerBlock) != 0)\r\n {\r\n return 1U;\r\n }\r\n\r\n image1 += bytes_per_row;\r\n image2 += bytes_per_row;\r\n }\r\n\r\n return 0U;\r\n}\r\n\r\n\/\/\r\n\/\/ Check for diffs in upper-left portion of the block. The size of the portion\r\n\/\/ to check is specified by the |width| and |height| values.\r\n\/\/ Note that if we force the capturer to always return images whose width and\r\n\/\/ height are multiples of kBlockSize, then this will never be called.\r\n\/\/\r\nstatic INLINE uint8_t DiffPartialBlock(const uint8_t* prev_image,\r\n const uint8_t* curr_image,\r\n int bytes_per_row,\r\n int bytes_per_block,\r\n int height)\r\n{\r\n for (int y = 0; y < height; ++y)\r\n {\r\n if (memcmp(prev_image, curr_image, bytes_per_block) != 0)\r\n {\r\n return 1U;\r\n }\r\n\r\n prev_image += bytes_per_row;\r\n curr_image += bytes_per_row;\r\n }\r\n\r\n return 0U;\r\n}\r\n\r\nDiffer::Differ(const DesktopSize& size)\r\n : size_(size),\r\n bytes_per_row_(size.Width() * kBytesPerPixel),\r\n diff_width_(((size.Width() + kBlockSize - 1) \/ kBlockSize) + 1),\r\n diff_height_(((size.Height() + kBlockSize - 1) \/ kBlockSize) + 1),\r\n full_blocks_x_(size.Width() \/ kBlockSize),\r\n full_blocks_y_(size.Height() \/ kBlockSize)\r\n{\r\n const int diff_info_size = diff_width_ * diff_height_;\r\n\r\n diff_info_ = std::make_unique<uint8_t[]>(diff_info_size);\r\n memset(diff_info_.get(), 0, diff_info_size);\r\n\r\n \/\/ Calc size of partial blocks which may be present on right and bottom\r\n \/\/ edge.\r\n partial_column_width_ = size.Width() - (full_blocks_x_ * kBlockSize);\r\n partial_row_height_ = size.Height() - (full_blocks_y_ * kBlockSize);\r\n\r\n \/\/ Offset from the start of one block-row to the next.\r\n block_stride_y_ = bytes_per_row_ * kBlockSize;\r\n}\r\n\r\n\/\/\r\n\/\/ Identify all of the blocks that contain changed pixels.\r\n\/\/\r\nvoid Differ::MarkDirtyBlocks(const uint8_t* prev_image, const uint8_t* curr_image)\r\n{\r\n const uint8_t* prev_block_row_start = prev_image;\r\n const uint8_t* curr_block_row_start = curr_image;\r\n\r\n \/\/ Offset from the start of one diff_info row to the next.\r\n const int diff_stride = diff_width_;\r\n\r\n uint8_t* is_diff_row_start = diff_info_.get();\r\n\r\n for (int y = 0; y < full_blocks_y_; ++y)\r\n {\r\n const uint8_t* prev_block = prev_block_row_start;\r\n const uint8_t* curr_block = curr_block_row_start;\r\n\r\n uint8_t* is_different = is_diff_row_start;\r\n\r\n for (int x = 0; x < full_blocks_x_; ++x)\r\n {\r\n \/\/ For x86 and x86_64, we do not support processors that do not\r\n \/\/ have SSE2 instructions support.\r\n if (kBlockSize == 16)\r\n {\r\n \/\/ Mark this block as being modified so that it gets\r\n \/\/ incorporated into a dirty rect.\r\n *is_different = DiffFullBlock_16x16_SSE2(prev_block,\r\n curr_block,\r\n bytes_per_row_);\r\n }\r\n else if (kBlockSize == 32)\r\n {\r\n \/\/ Mark this block as being modified so that it gets\r\n \/\/ incorporated into a dirty rect.\r\n *is_different = DiffFullBlock_32x32_SSE2(prev_block,\r\n curr_block,\r\n bytes_per_row_);\r\n }\r\n\r\n prev_block += kBytesPerBlock;\r\n curr_block += kBytesPerBlock;\r\n\r\n ++is_different;\r\n }\r\n\r\n \/\/ If there is a partial column at the end, handle it.\r\n \/\/ This condition should rarely, if ever, occur.\r\n if (partial_column_width_ != 0)\r\n {\r\n *is_different = DiffPartialBlock(prev_block,\r\n curr_block,\r\n bytes_per_row_,\r\n kBytesPerBlock,\r\n kBlockSize);\r\n }\r\n\r\n \/\/ Update pointers for next row.\r\n prev_block_row_start += block_stride_y_;\r\n curr_block_row_start += block_stride_y_;\r\n\r\n is_diff_row_start += diff_stride;\r\n }\r\n\r\n \/\/ If the screen height is not a multiple of the block size, then this\r\n \/\/ handles the last partial row. This situation is far more common than\r\n \/\/ the 'partial column' case.\r\n if (partial_row_height_ != 0)\r\n {\r\n const uint8_t* prev_block = prev_block_row_start;\r\n const uint8_t* curr_block = curr_block_row_start;\r\n\r\n uint8_t* is_different = is_diff_row_start;\r\n\r\n for (int x = 0; x < full_blocks_x_; ++x)\r\n {\r\n *is_different = DiffPartialBlock(prev_block,\r\n curr_block,\r\n bytes_per_row_,\r\n kBytesPerBlock,\r\n partial_row_height_);\r\n\r\n prev_block += kBytesPerBlock;\r\n curr_block += kBytesPerBlock;\r\n ++is_different;\r\n }\r\n\r\n if (partial_column_width_ != 0)\r\n {\r\n *is_different =\r\n DiffPartialBlock(prev_block,\r\n curr_block,\r\n bytes_per_row_,\r\n partial_column_width_ * kBytesPerPixel,\r\n partial_row_height_);\r\n }\r\n }\r\n}\r\n\r\n\/\/\r\n\/\/ After the dirty blocks have been identified, this routine merges adjacent\r\n\/\/ blocks into a region.\r\n\/\/ The goal is to minimize the region that covers the dirty blocks.\r\n\/\/\r\nvoid Differ::MergeBlocks(DesktopRegion* dirty_region)\r\n{\r\n uint8_t* is_diff_row_start = diff_info_.get();\r\n const int diff_stride = diff_width_;\r\n\r\n for (int y = 0; y < diff_height_; ++y)\r\n {\r\n uint8_t* is_different = is_diff_row_start;\r\n\r\n for (int x = 0; x < diff_width_; ++x)\r\n {\r\n \/\/ We've found a modified block. Look at blocks to the right and\r\n \/\/ below to group this block with as many others as we can.\r\n if (*is_different != 0)\r\n {\r\n \/\/ Width and height of the rectangle in blocks.\r\n int width = 1;\r\n int height = 1;\r\n\r\n *is_different = 0;\r\n\r\n \/\/ Group with blocks to the right.\r\n \/\/ We can keep looking until we find an unchanged block because\r\n \/\/ we have a boundary block which is never marked as having\r\n \/\/ diffs.\r\n uint8_t* right = is_different + 1;\r\n\r\n while (*right != 0)\r\n {\r\n *right++ = 0;\r\n ++width;\r\n }\r\n\r\n \/\/ Group with blocks below.\r\n \/\/ The entire width of blocks that we matched above much match\r\n \/\/ for each row that we add.\r\n uint8_t* bottom = is_different;\r\n bool found_new_row;\r\n\r\n do\r\n {\r\n found_new_row = true;\r\n bottom += diff_stride;\r\n right = bottom;\r\n\r\n for (int x2 = 0; x2 < width; ++x2)\r\n {\r\n if (*right++ == 0)\r\n found_new_row = false;\r\n }\r\n\r\n if (found_new_row)\r\n {\r\n ++height;\r\n\r\n \/\/ We need to go back and erase the diff markers so\r\n \/\/ that we don't try to add these blocks a second time.\r\n right = bottom;\r\n\r\n for (int x2 = 0; x2 < width; ++x2)\r\n {\r\n *right++ = 0;\r\n }\r\n }\r\n } while (found_new_row);\r\n\r\n int32_t l = x * kBlockSize;\r\n int32_t t = y * kBlockSize;\r\n int32_t r = l + (width * kBlockSize);\r\n int32_t b = t + (height * kBlockSize);\r\n\r\n if (r > size_.Width())\r\n r = size_.Width();\r\n\r\n if (b > size_.Height())\r\n b = size_.Height();\r\n\r\n \/\/ Add rect to region.\r\n dirty_region->AddRect(DesktopRect::MakeLTRB(l, t, r, b));\r\n }\r\n\r\n \/\/ Increment to next block in this row.\r\n ++is_different;\r\n }\r\n\r\n \/\/ Go to start of next row.\r\n is_diff_row_start += diff_stride;\r\n }\r\n}\r\n\r\nvoid Differ::CalcDirtyRegion(const uint8_t* prev_image,\r\n const uint8_t* curr_image,\r\n DesktopRegion* dirty_region)\r\n{\r\n dirty_region->Clear();\r\n\r\n \/\/ Identify all the blocks that contain changed pixels.\r\n MarkDirtyBlocks(prev_image, curr_image);\r\n\r\n \/\/\r\n \/\/ Now that we've identified the blocks that have changed, merge adjacent\r\n \/\/ blocks to minimize the number of rects that we return.\r\n \/\/\r\n MergeBlocks(dirty_region);\r\n}\r\n\r\n} \/\/ namespace aspia\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ CalcCoordinator.cpp\n\n#include \"CalcCoordinator.h\"\n\nCalcCoordinator::CalcCoordinator(OutputResult::OutputType out_t, std::string resultFileName) : outFileName(resultFileName), outputMutex(new boost::mutex()), calcValuesMutex(new boost::mutex()), calcInfo(new vector<CalcInfo>()), outResults(new OutputResult(out_t, resultFileName)) {\n\t\n}\n\nCalcCoordinator::~CalcCoordinator() {\n\t\n}\n\n\nvoid CalcCoordinator::RunCalculations() {\n\tint numberOfThreads = thread::hardware_concurrency();\n\t\n\tfor (int i = 0; i < numberOfThreads; i++) {\n\t\tCalcThread calcThread(i, calcInfo, calcValuesMutex, outputMutex, outResults);\n\t\tcalcThreads.push_back(thread(calcThread));\n\t}\n\t\n\twhile (calcThreads.size() > 0) {\n\t\tcalcThreads[calcThreads.size() - 1].join();\n\t\tcalcThreads.pop_back();\n\t}\n}\n\nvoid CalcCoordinator::AddCalculation(const Detector &det, Detector::CalcType cType, double fpPerHour, double beta, int uncertLoops) {\n\tcalcInfo->push_back(CalcInfo(det, cType, fpPerHour, beta, uncertLoops));\n}\n\nvoid CalcCoordinator::AddFixedCalculation(const Detector &det, Detector::CalcType cType, double fpPerHour, double beta, double intTime, int uncertLoops) {\n\tCalcInfo tmp(det, cType, fpPerHour, beta, uncertLoops);\n\ttmp.FixIntegrationTime(intTime);\n\tcalcInfo->push_back(tmp);\n}\n\nvoid CalcCoordinator::AddPlotCalculation(const Detector &det, Detector::CalcType cType, double fpPerHour, double beta, double start_time, double stop_time, unsigned int steps) {\n\tCalcInfo tmp(det, cType, fpPerHour, beta, 0);\n\ttmp.SetPlotDetails(start_time, stop_time, steps);\n\tcalcInfo->push_back(tmp);\n}\n\n\nCalcThread::CalcThread(int threadId, boost::shared_ptr<vector<CalcInfo>> calcValues, boost::shared_ptr<boost::mutex> calcValuesMutex, boost::shared_ptr<boost::mutex> outputMutex, boost::shared_ptr<OutputResult> outResults) : calcValues(calcValues), calcValuesMutex(calcValuesMutex), threadId(threadId), outputMutex(outputMutex), outResults(outResults) {\n\t\n}\n\nvoid CalcThread::operator()() {\n\tCalcInfo tmpInfo;\n\twhile (true) {\n\t\t{\n\t\t\tboost::mutex::scoped_lock lock(*calcValuesMutex.get());\n\t\t\tif (calcValues->size() == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttmpInfo = calcValues->at(calcValues->size() - 1);\n\t\t\tcalcValues->pop_back();\n\t\t\tPRINT_T(std::string(\"CalcThread(): Thread starts work on new job. \") + lexical_cast<std::string>(calcValues->size()) + std::string(\" jobs are still queued up.\"));\n\t\t}\n\t\tif (tmpInfo.plotCalc) {\n\t\t\tCalcTimeVsActData(tmpInfo);\n\t\t} else {\n\t\t\tCalcTimeAndAct(tmpInfo);\n\t\t}\n\t}\n}\n\nint CalcThread::CalcTimeVsActData(CalcInfo &info) {\n\tstd::vector<std::pair<double, double>> timeActVec;\n\tstd::vector<double> clTime;\n\tstd::vector<unsigned int> clValue;\n\t\n\tPRINT_T(std::string(\"CalcThread::CalcTimeVsActData(): Locating minimas between \") + lexical_cast<std::string>(info.start_time) + std::string(\" and \") + lexical_cast<std::string>(info.stop_time) + std::string(\" seconds.\"));\n\tdouble currentTime = info.start_time;\n\tdouble currentM;\n\tint current_C_L = int(info.start_time * info.det.GetSimBkg() + 0.5);\n\tif (current_C_L < 2) {\n\t\tcurrent_C_L = 2;\n\t}\n\twhile (currentTime < info.stop_time) {\n\t\tFindLocalMinima(info, current_C_L, currentTime, currentM);\n\t\tif (currentTime > info.start_time and currentTime < info.stop_time) {\n\t\t\tclTime.push_back(currentTime);\n\t\t\tclValue.push_back(current_C_L);\n\t\t\t\n\t\t\ttimeActVec.push_back(std::pair<double, double>(currentTime, currentM));\n\t\t\tPRINT_T(std::string(\"CalcThread::CalcTimeVsActData(): Storing results for C_L = \") + lexical_cast<std::string>(current_C_L) + std::string(\".\"));\n\t\t} else {\n\t\t\tPRINT_T(std::string(\"CalcThread::CalcTimeVsActData(): Throwing away results for C_L = \") + lexical_cast<std::string>(current_C_L) + std::string(\".\"));\n\t\t}\n\t\tcurrent_C_L++;\n\t}\n\t\n\tPRINT_T(std::string(\"CalcThread::CalcTimeVsActData(): Calculating remaining sensitivity values between \") + lexical_cast<std::string>(info.start_time) + std::string(\" and \") + lexical_cast<std::string>(info.stop_time) + std::string(\" seconds.\"));\n\tArrayXd testTimes = ArrayXd::LinSpaced(info.steps, info.start_time, info.stop_time);\n\tfor (int u = 0; u < testTimes.size(); u++) {\n\t\tinfo.det.SetIntegrationTime(testTimes[u]);\n\t\tdouble act = info.det.CalcActivityFPH(info.fpPerHour, info.beta, info.cType);\n\t\ttimeActVec.push_back(std::pair<double, double>(testTimes[u], act));\n\t}\n\tstruct c_sorter\n\t{\n\t\tinline bool operator() (const std::pair<double, double>& p1, const std::pair<double, double>& p2)\n\t\t{\n\t\t\treturn (p1.first < p2.first);\n\t\t}\n\t};\n\t\n\tstd::sort(timeActVec.begin(), timeActVec.end(), c_sorter());\n\t\n\tstd::string calcTypeStr;\n\tif (info.cType == Detector::CalcType::BEST) {\n\t\tcalcTypeStr = string(\"BEST\");\n\t} else if (info.cType == Detector::CalcType::MEAN) {\n\t\tcalcTypeStr = string(\"MEAN\");\n\t} else if (info.cType == Detector::CalcType::WORST) {\n\t\tcalcTypeStr = string(\"WORST\");\n\t} else if (info.cType == Detector::CalcType::LIST_MODE) {\n\t\tcalcTypeStr = string(\"LIST_MODE\");\n\t} else {\n\t\tcalcTypeStr = string(\"UNKNOWN\");\n\t}\n\t\n\t{\n\t\tboost::mutex::scoped_lock lock(*outputMutex.get());\n\t\toutResults->StartResult();\n\t\toutResults->Write(\"calc_type\", calcTypeStr);\n\t\toutResults->Write(\"distance\", info.det.GetDistance());\n\t\toutResults->Write(\"velocity\", info.det.GetVelocity());\n\t\toutResults->Write(\"background\", info.det.GetSimBkg());\n\t\toutResults->Write(\"cl_values\", clValue);\n\t\toutResults->Write(\"cl_times\", clTime);\n\t\toutResults->Write(\"times_and_acts\", timeActVec);\n\t\toutResults->EndResult();\n\t}\n\t\n\treturn 0;\n}\n\nint CalcThread::CalcTimeAndAct(CalcInfo &info) {\n\tvector<pair<string,string>> result;\n\t\n\t\n\tdouble time, actValue;\n\tvector<double> timeVec;\n\tvector<double> actVec;\n\tif (info.fixedInt) {\n\t\ttime = info.intTime;\n\t\tinfo.det.SetIntegrationTime(time);\n\t\tactValue = info.det.CalcActivityFPH(info.fpPerHour, info.beta, info.cType);\n\t} else {\n\t\tFindGlobalMinima(info, time, actValue);\n\t}\n\t\n\tstd::string calcTypeStr;\n\tif (info.cType == Detector::CalcType::BEST) {\n\t\tcalcTypeStr = string(\"BEST\");\n\t} else if (info.cType == Detector::CalcType::MEAN) {\n\t\tcalcTypeStr = string(\"MEAN\");\n\t} else if (info.cType == Detector::CalcType::WORST) {\n\t\tcalcTypeStr = string(\"WORST\");\n\t} else if (info.cType == Detector::CalcType::LIST_MODE) {\n\t\tcalcTypeStr = string(\"LIST_MODE\");\n\t} else {\n\t\tcalcTypeStr = string(\"UNKNOWN\");\n\t}\n\tinfo.det.SetIntegrationTime(time);\n\tdouble srcDetectProb = info.det.CalcTruePositiveProbFPH(info.fpPerHour, actValue, info.cType);\n\tint crit_limit = info.det.CriticalLimitFPH(info.fpPerHour, info.cType);\n\t\n\tArrayXd signalArray = info.det.CalcSignal(actValue, info.cType);\n\t\n\tstd::vector<std::pair<double, double>> periodsVector = info.det.GetIntTimes(info.cType);\n\t\n\tdouble timeStdDev = -1;\n\tdouble actStdDev = -1;\n\tdouble actMean = -1;\n\tdouble timeMean = -1;\n\t\n\tif (info.uncertLoops > 1) {\n\t\tdouble tempTime, tempAct, timeSum = 0, actSum = 0;\n\t\tdouble timeDiffSum = 0;\n\t\tdouble actDiffSum = 0;\n\t\t\n\t\tif (info.fixedInt) {\n\t\t\tfor (int y = 0; y < info.uncertLoops; y++) {\n\t\t\t\tinfo.det.RandomizeParameters();\n\t\t\t\ttempAct = info.det.CalcActivityFPH(info.fpPerHour, info.beta, info.cType);\n\t\t\t\tactSum += tempAct;\n\t\t\t\ttimeVec.push_back(tempTime);\n\t\t\t\tactVec.push_back(tempAct);\n\t\t\t\t\n\t\t\t}\n\t\t\tactMean = actSum \/ info.uncertLoops;\n\t\t\ttimeMean = info.intTime;\n\t\t\t\n\t\t\tfor (int i = 0; i < info.uncertLoops; i++) {\n\t\t\t\tactDiffSum += (actVec[i] - actMean) * (actVec[i] - actMean);\n\t\t\t}\n\t\t\t\n\t\t\ttimeStdDev = 0.0;\n\t\t\tactStdDev = sqrt(actDiffSum \/ info.uncertLoops);\n\t\t\t\n\t\t} else {\n\t\t\tfor (int y = 0; y < info.uncertLoops; y++) {\n\t\t\t\tinfo.det.RandomizeParameters();\n\t\t\t\tFindGlobalMinima(info, tempTime, tempAct);\n\t\t\t\tactSum += tempAct;\n\t\t\t\ttimeSum += tempTime;\n\t\t\t\ttimeVec.push_back(tempTime);\n\t\t\t\tactVec.push_back(tempAct);\n\t\t\t}\n\t\t\tactMean = actSum \/ info.uncertLoops;\n\t\t\ttimeMean = timeSum \/ info.uncertLoops;\n\t\t\t\n\t\t\tfor (int i = 0; i < info.uncertLoops; i++) {\n\t\t\t\ttimeDiffSum += (timeVec[i] - timeMean) * (timeVec[i] - timeMean);\n\t\t\t\tactDiffSum += (actVec[i] - actMean) * (actVec[i] - actMean);\n\t\t\t}\n\t\t\t\n\t\t\ttimeStdDev = sqrt(timeDiffSum \/ info.uncertLoops);\n\t\t\tactStdDev = sqrt(actDiffSum \/ info.uncertLoops);\n\t\t}\n\t}\n\t\n\t{\n\t\tboost::mutex::scoped_lock lock(*outputMutex.get());\n\t\toutResults->StartResult();\n\t\toutResults->Write(\"calc_type\", calcTypeStr);\n\t\toutResults->Write(\"distance\", info.det.GetDistance());\n\t\toutResults->Write(\"velocity\", info.det.GetVelocity());\n\t\toutResults->Write(\"background\", info.det.GetSimBkg());\n\t\toutResults->Write(\"fix_int_time\", info.fixedInt);\n\t\toutResults->Write(\"int_time\", time);\n\t\toutResults->Write(\"min_act\", actValue);\n\t\toutResults->Write(\"true_pos_prob\", srcDetectProb);\n\t\toutResults->Write(\"critical_limit\", crit_limit);\n\t\toutResults->Write(\"int_periods\", periodsVector);\n\t\toutResults->Write(\"mean_signal\", signalArray);\n\t\tif (info.uncertLoops > 1) {\n\t\t\toutResults->Write(\"int_time_std_dev\", timeStdDev);\n\t\t\toutResults->Write(\"int_time_mean\", timeMean);\n\t\t\toutResults->Write(\"min_act_std_dev\", actStdDev);\n\t\t\toutResults->Write(\"min_act_mean\", actMean);\n\t\t}\n\t\toutResults->EndResult();\n\t}\n\treturn 0;\n}\n\nvoid FindGlobalMinima(CalcInfo &info, double &time, double &bestM) {\n\tdouble currentTime = 0.0, lastTime = 5.0;\n\tdouble lastM = 1.0, currentM = 1.0;\n\tint current_C_L = 3; \/\/Fix me: starting C_L value influences speed quite a bit. Find better starting value!\n\tFindLocalMinima(info, current_C_L, lastTime, lastM);\n\tcurrentTime = lastTime;\n\tcurrent_C_L++;\n\twhile (true) {\n\t\tPRINT_T(std::string(\"FindGlobalMinima(): Locating global minima for C_L = \") + lexical_cast<std::string>(current_C_L));\n\t\tFindLocalMinima(info, current_C_L, currentTime, currentM);\n\t\tif (currentM < lastM) {\n\t\t\tlastM = currentM;\n\t\t\tlastTime = currentTime;\n\t\t\tcurrent_C_L++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\ttime = lastTime;\n\tbestM = lastM;\n}\n\nvoid FindLocalMinima(CalcInfo &info, int target_C_L, double &iTime, double &minM) {\n\tconst double maxTimeDiff = 0.00001; \/\/The maximum time step allowed when finding minimas, might need to be changed\n\tdouble upper_time = iTime + maxTimeDiff * 2; \/\/To assist the algorithm slightly, we add the maximum time diff\n\tdouble lower_time = 0.0;\n\t\n\t\/\/Find where we have C_L = target_C_L\n\t\/\/This is done by stepping up and down in integration time until C_L = target_C_L\n\tint current_C_L;\n\tdo {\n\t\tinfo.det.SetIntegrationTime(upper_time);\n\t\tcurrent_C_L = info.det.CriticalLimitFPH(info.fpPerHour, info.cType);\n\t\t\n\t\tif (current_C_L > target_C_L) {\n\t\t\tupper_time = lower_time + (upper_time - lower_time) \/ 2.0;\n\t\t} else if (current_C_L < target_C_L) {\n\t\t\tlower_time = upper_time;\n\t\t\tupper_time *= 2;\n\t\t}\n\t } while (current_C_L != target_C_L);\n\t\n\tlower_time = upper_time; \/\/This is now our minimum time\n\t\n\t\/\/Find some integration time where C_L > target_C_L\n\t\/\/This is needed in order for the algorithm to do a binary search in the later stages of the algorithm\n\tdo {\n\t\tupper_time *= 1.3; \/\/Potentially fix me, probably a bit to radical to double the upper time\n\t\tinfo.det.SetIntegrationTime(upper_time);\n\t} while (info.det.CriticalLimitFPH(info.fpPerHour, info.cType) == target_C_L);\n\t\n\t\/\/Now do the actual minima-finding part\n\t\/\/This is done by moving the upper and lower time limits closer to each other which results in the algorithm closing in on when target_C_L becomes target_C_L + 1\n\tdouble c_time;\n\twhile (upper_time - lower_time > maxTimeDiff) {\n\t\tc_time = (upper_time - lower_time) \/ 2.0 + lower_time;\n\t\tinfo.det.SetIntegrationTime(c_time);\n\t\tcurrent_C_L = info.det.CriticalLimitFPH(info.fpPerHour, info.cType);\n\t\tif (current_C_L == target_C_L) {\n\t\t\tlower_time = c_time;\n\t\t} else {\n\t\t\tupper_time = c_time;\n\t\t}\n\t}\n\t\/\/The actual integration time is the lower one as we really want C_L = target_C_L\n\tiTime = lower_time;\n\tinfo.det.SetIntegrationTime(iTime);\n\tminM = info.det.CalcActivityFPH(info.fpPerHour, info.beta, info.cType);\n}\n<commit_msg>Added information in verbose message.<commit_after>\/\/\n\/\/ CalcCoordinator.cpp\n\n#include \"CalcCoordinator.h\"\n\nCalcCoordinator::CalcCoordinator(OutputResult::OutputType out_t, std::string resultFileName) : outFileName(resultFileName), outputMutex(new boost::mutex()), calcValuesMutex(new boost::mutex()), calcInfo(new vector<CalcInfo>()), outResults(new OutputResult(out_t, resultFileName)) {\n\t\n}\n\nCalcCoordinator::~CalcCoordinator() {\n\t\n}\n\n\nvoid CalcCoordinator::RunCalculations() {\n\tint numberOfThreads = thread::hardware_concurrency();\n\t\n\tfor (int i = 0; i < numberOfThreads; i++) {\n\t\tCalcThread calcThread(i, calcInfo, calcValuesMutex, outputMutex, outResults);\n\t\tcalcThreads.push_back(thread(calcThread));\n\t}\n\t\n\twhile (calcThreads.size() > 0) {\n\t\tcalcThreads[calcThreads.size() - 1].join();\n\t\tcalcThreads.pop_back();\n\t}\n}\n\nvoid CalcCoordinator::AddCalculation(const Detector &det, Detector::CalcType cType, double fpPerHour, double beta, int uncertLoops) {\n\tcalcInfo->push_back(CalcInfo(det, cType, fpPerHour, beta, uncertLoops));\n}\n\nvoid CalcCoordinator::AddFixedCalculation(const Detector &det, Detector::CalcType cType, double fpPerHour, double beta, double intTime, int uncertLoops) {\n\tCalcInfo tmp(det, cType, fpPerHour, beta, uncertLoops);\n\ttmp.FixIntegrationTime(intTime);\n\tcalcInfo->push_back(tmp);\n}\n\nvoid CalcCoordinator::AddPlotCalculation(const Detector &det, Detector::CalcType cType, double fpPerHour, double beta, double start_time, double stop_time, unsigned int steps) {\n\tCalcInfo tmp(det, cType, fpPerHour, beta, 0);\n\ttmp.SetPlotDetails(start_time, stop_time, steps);\n\tcalcInfo->push_back(tmp);\n}\n\n\nCalcThread::CalcThread(int threadId, boost::shared_ptr<vector<CalcInfo>> calcValues, boost::shared_ptr<boost::mutex> calcValuesMutex, boost::shared_ptr<boost::mutex> outputMutex, boost::shared_ptr<OutputResult> outResults) : calcValues(calcValues), calcValuesMutex(calcValuesMutex), threadId(threadId), outputMutex(outputMutex), outResults(outResults) {\n\t\n}\n\nvoid CalcThread::operator()() {\n\tCalcInfo tmpInfo;\n\twhile (true) {\n\t\t{\n\t\t\tboost::mutex::scoped_lock lock(*calcValuesMutex.get());\n\t\t\tif (calcValues->size() == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttmpInfo = calcValues->at(calcValues->size() - 1);\n\t\t\tcalcValues->pop_back();\n\t\t\tPRINT_T(std::string(\"CalcThread(): Thread starts work on new job. \") + lexical_cast<std::string>(calcValues->size()) + std::string(\" jobs are still queued up.\"));\n\t\t}\n\t\tif (tmpInfo.plotCalc) {\n\t\t\tCalcTimeVsActData(tmpInfo);\n\t\t} else {\n\t\t\tCalcTimeAndAct(tmpInfo);\n\t\t}\n\t}\n}\n\nint CalcThread::CalcTimeVsActData(CalcInfo &info) {\n\tstd::vector<std::pair<double, double>> timeActVec;\n\tstd::vector<double> clTime;\n\tstd::vector<unsigned int> clValue;\n\t\n\tPRINT_T(std::string(\"CalcThread::CalcTimeVsActData(): Locating minimas between \") + lexical_cast<std::string>(info.start_time) + std::string(\" and \") + lexical_cast<std::string>(info.stop_time) + std::string(\" seconds.\"));\n\tdouble currentTime = info.start_time;\n\tdouble currentM;\n\tint current_C_L = int(info.start_time * info.det.GetSimBkg() + 0.5);\n\tif (current_C_L < 2) {\n\t\tcurrent_C_L = 2;\n\t}\n\twhile (currentTime < info.stop_time) {\n\t\tFindLocalMinima(info, current_C_L, currentTime, currentM);\n\t\tif (currentTime > info.start_time and currentTime < info.stop_time) {\n\t\t\tclTime.push_back(currentTime);\n\t\t\tclValue.push_back(current_C_L);\n\t\t\t\n\t\t\ttimeActVec.push_back(std::pair<double, double>(currentTime, currentM));\n\t\t\tPRINT_T(std::string(\"CalcThread::CalcTimeVsActData(): Storing results for C_L = \") + lexical_cast<std::string>(current_C_L) + std::string(\" (t=\") + lexical_cast<std::string>(currentTime) + std::string(\", m=\") + lexical_cast<std::string>(currentM) + std::string(\").\"));\n\t\t} else {\n\t\t\tPRINT_T(std::string(\"CalcThread::CalcTimeVsActData(): Throwing away results for C_L = \") + lexical_cast<std::string>(current_C_L) + std::string(\" (t=\") + lexical_cast<std::string>(currentTime) + std::string(\", m=\") + lexical_cast<std::string>(currentM) + std::string(\").\"));\n\t\t}\n\t\tcurrent_C_L++;\n\t}\n\t\n\tPRINT_T(std::string(\"CalcThread::CalcTimeVsActData(): Calculating remaining sensitivity values between \") + lexical_cast<std::string>(info.start_time) + std::string(\" and \") + lexical_cast<std::string>(info.stop_time) + std::string(\" seconds.\"));\n\tArrayXd testTimes = ArrayXd::LinSpaced(info.steps, info.start_time, info.stop_time);\n\tfor (int u = 0; u < testTimes.size(); u++) {\n\t\tinfo.det.SetIntegrationTime(testTimes[u]);\n\t\tdouble act = info.det.CalcActivityFPH(info.fpPerHour, info.beta, info.cType);\n\t\ttimeActVec.push_back(std::pair<double, double>(testTimes[u], act));\n\t}\n\tstruct c_sorter\n\t{\n\t\tinline bool operator() (const std::pair<double, double>& p1, const std::pair<double, double>& p2)\n\t\t{\n\t\t\treturn (p1.first < p2.first);\n\t\t}\n\t};\n\t\n\tstd::sort(timeActVec.begin(), timeActVec.end(), c_sorter());\n\t\n\tstd::string calcTypeStr;\n\tif (info.cType == Detector::CalcType::BEST) {\n\t\tcalcTypeStr = string(\"BEST\");\n\t} else if (info.cType == Detector::CalcType::MEAN) {\n\t\tcalcTypeStr = string(\"MEAN\");\n\t} else if (info.cType == Detector::CalcType::WORST) {\n\t\tcalcTypeStr = string(\"WORST\");\n\t} else if (info.cType == Detector::CalcType::LIST_MODE) {\n\t\tcalcTypeStr = string(\"LIST_MODE\");\n\t} else {\n\t\tcalcTypeStr = string(\"UNKNOWN\");\n\t}\n\t\n\t{\n\t\tboost::mutex::scoped_lock lock(*outputMutex.get());\n\t\toutResults->StartResult();\n\t\toutResults->Write(\"calc_type\", calcTypeStr);\n\t\toutResults->Write(\"distance\", info.det.GetDistance());\n\t\toutResults->Write(\"velocity\", info.det.GetVelocity());\n\t\toutResults->Write(\"background\", info.det.GetSimBkg());\n\t\toutResults->Write(\"cl_values\", clValue);\n\t\toutResults->Write(\"cl_times\", clTime);\n\t\toutResults->Write(\"times_and_acts\", timeActVec);\n\t\toutResults->EndResult();\n\t}\n\t\n\treturn 0;\n}\n\nint CalcThread::CalcTimeAndAct(CalcInfo &info) {\n\tvector<pair<string,string>> result;\n\t\n\t\n\tdouble time, actValue;\n\tvector<double> timeVec;\n\tvector<double> actVec;\n\tif (info.fixedInt) {\n\t\ttime = info.intTime;\n\t\tinfo.det.SetIntegrationTime(time);\n\t\tactValue = info.det.CalcActivityFPH(info.fpPerHour, info.beta, info.cType);\n\t} else {\n\t\tFindGlobalMinima(info, time, actValue);\n\t}\n\t\n\tstd::string calcTypeStr;\n\tif (info.cType == Detector::CalcType::BEST) {\n\t\tcalcTypeStr = string(\"BEST\");\n\t} else if (info.cType == Detector::CalcType::MEAN) {\n\t\tcalcTypeStr = string(\"MEAN\");\n\t} else if (info.cType == Detector::CalcType::WORST) {\n\t\tcalcTypeStr = string(\"WORST\");\n\t} else if (info.cType == Detector::CalcType::LIST_MODE) {\n\t\tcalcTypeStr = string(\"LIST_MODE\");\n\t} else {\n\t\tcalcTypeStr = string(\"UNKNOWN\");\n\t}\n\tinfo.det.SetIntegrationTime(time);\n\tdouble srcDetectProb = info.det.CalcTruePositiveProbFPH(info.fpPerHour, actValue, info.cType);\n\tint crit_limit = info.det.CriticalLimitFPH(info.fpPerHour, info.cType);\n\t\n\tArrayXd signalArray = info.det.CalcSignal(actValue, info.cType);\n\t\n\tstd::vector<std::pair<double, double>> periodsVector = info.det.GetIntTimes(info.cType);\n\t\n\tdouble timeStdDev = -1;\n\tdouble actStdDev = -1;\n\tdouble actMean = -1;\n\tdouble timeMean = -1;\n\t\n\tif (info.uncertLoops > 1) {\n\t\tdouble tempTime, tempAct, timeSum = 0, actSum = 0;\n\t\tdouble timeDiffSum = 0;\n\t\tdouble actDiffSum = 0;\n\t\t\n\t\tif (info.fixedInt) {\n\t\t\tfor (int y = 0; y < info.uncertLoops; y++) {\n\t\t\t\tinfo.det.RandomizeParameters();\n\t\t\t\ttempAct = info.det.CalcActivityFPH(info.fpPerHour, info.beta, info.cType);\n\t\t\t\tactSum += tempAct;\n\t\t\t\ttimeVec.push_back(tempTime);\n\t\t\t\tactVec.push_back(tempAct);\n\t\t\t\t\n\t\t\t}\n\t\t\tactMean = actSum \/ info.uncertLoops;\n\t\t\ttimeMean = info.intTime;\n\t\t\t\n\t\t\tfor (int i = 0; i < info.uncertLoops; i++) {\n\t\t\t\tactDiffSum += (actVec[i] - actMean) * (actVec[i] - actMean);\n\t\t\t}\n\t\t\t\n\t\t\ttimeStdDev = 0.0;\n\t\t\tactStdDev = sqrt(actDiffSum \/ info.uncertLoops);\n\t\t\t\n\t\t} else {\n\t\t\tfor (int y = 0; y < info.uncertLoops; y++) {\n\t\t\t\tinfo.det.RandomizeParameters();\n\t\t\t\tFindGlobalMinima(info, tempTime, tempAct);\n\t\t\t\tactSum += tempAct;\n\t\t\t\ttimeSum += tempTime;\n\t\t\t\ttimeVec.push_back(tempTime);\n\t\t\t\tactVec.push_back(tempAct);\n\t\t\t}\n\t\t\tactMean = actSum \/ info.uncertLoops;\n\t\t\ttimeMean = timeSum \/ info.uncertLoops;\n\t\t\t\n\t\t\tfor (int i = 0; i < info.uncertLoops; i++) {\n\t\t\t\ttimeDiffSum += (timeVec[i] - timeMean) * (timeVec[i] - timeMean);\n\t\t\t\tactDiffSum += (actVec[i] - actMean) * (actVec[i] - actMean);\n\t\t\t}\n\t\t\t\n\t\t\ttimeStdDev = sqrt(timeDiffSum \/ info.uncertLoops);\n\t\t\tactStdDev = sqrt(actDiffSum \/ info.uncertLoops);\n\t\t}\n\t}\n\t\n\t{\n\t\tboost::mutex::scoped_lock lock(*outputMutex.get());\n\t\toutResults->StartResult();\n\t\toutResults->Write(\"calc_type\", calcTypeStr);\n\t\toutResults->Write(\"distance\", info.det.GetDistance());\n\t\toutResults->Write(\"velocity\", info.det.GetVelocity());\n\t\toutResults->Write(\"background\", info.det.GetSimBkg());\n\t\toutResults->Write(\"fix_int_time\", info.fixedInt);\n\t\toutResults->Write(\"int_time\", time);\n\t\toutResults->Write(\"min_act\", actValue);\n\t\toutResults->Write(\"true_pos_prob\", srcDetectProb);\n\t\toutResults->Write(\"critical_limit\", crit_limit);\n\t\toutResults->Write(\"int_periods\", periodsVector);\n\t\toutResults->Write(\"mean_signal\", signalArray);\n\t\tif (info.uncertLoops > 1) {\n\t\t\toutResults->Write(\"int_time_std_dev\", timeStdDev);\n\t\t\toutResults->Write(\"int_time_mean\", timeMean);\n\t\t\toutResults->Write(\"min_act_std_dev\", actStdDev);\n\t\t\toutResults->Write(\"min_act_mean\", actMean);\n\t\t}\n\t\toutResults->EndResult();\n\t}\n\treturn 0;\n}\n\nvoid FindGlobalMinima(CalcInfo &info, double &time, double &bestM) {\n\tdouble currentTime = 0.0, lastTime = 5.0;\n\tdouble lastM = 1.0, currentM = 1.0;\n\tint current_C_L = 3; \/\/Fix me: starting C_L value influences speed quite a bit. Find better starting value!\n\tFindLocalMinima(info, current_C_L, lastTime, lastM);\n\tcurrentTime = lastTime;\n\tcurrent_C_L++;\n\twhile (true) {\n\t\tPRINT_T(std::string(\"FindGlobalMinima(): Locating global minima for C_L = \") + lexical_cast<std::string>(current_C_L));\n\t\tFindLocalMinima(info, current_C_L, currentTime, currentM);\n\t\tif (currentM < lastM) {\n\t\t\tlastM = currentM;\n\t\t\tlastTime = currentTime;\n\t\t\tcurrent_C_L++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\ttime = lastTime;\n\tbestM = lastM;\n}\n\nvoid FindLocalMinima(CalcInfo &info, int target_C_L, double &iTime, double &minM) {\n\tconst double maxTimeDiff = 0.00001; \/\/The maximum time step allowed when finding minimas, might need to be changed\n\tdouble upper_time = iTime + maxTimeDiff * 2; \/\/To assist the algorithm slightly, we add the maximum time diff\n\tdouble lower_time = 0.0;\n\t\n\t\/\/Find where we have C_L = target_C_L\n\t\/\/This is done by stepping up and down in integration time until C_L = target_C_L\n\tint current_C_L;\n\tdo {\n\t\tinfo.det.SetIntegrationTime(upper_time);\n\t\tcurrent_C_L = info.det.CriticalLimitFPH(info.fpPerHour, info.cType);\n\t\t\n\t\tif (current_C_L > target_C_L) {\n\t\t\tupper_time = lower_time + (upper_time - lower_time) \/ 2.0;\n\t\t} else if (current_C_L < target_C_L) {\n\t\t\tlower_time = upper_time;\n\t\t\tupper_time *= 2;\n\t\t}\n\t } while (current_C_L != target_C_L);\n\t\n\tlower_time = upper_time; \/\/This is now our minimum time\n\t\n\t\/\/Find some integration time where C_L > target_C_L\n\t\/\/This is needed in order for the algorithm to do a binary search in the later stages of the algorithm\n\tdo {\n\t\tupper_time *= 1.3; \/\/Potentially fix me, probably a bit to radical to double the upper time\n\t\tinfo.det.SetIntegrationTime(upper_time);\n\t} while (info.det.CriticalLimitFPH(info.fpPerHour, info.cType) == target_C_L);\n\t\n\t\/\/Now do the actual minima-finding part\n\t\/\/This is done by moving the upper and lower time limits closer to each other which results in the algorithm closing in on when target_C_L becomes target_C_L + 1\n\tdouble c_time;\n\twhile (upper_time - lower_time > maxTimeDiff) {\n\t\tc_time = (upper_time - lower_time) \/ 2.0 + lower_time;\n\t\tinfo.det.SetIntegrationTime(c_time);\n\t\tcurrent_C_L = info.det.CriticalLimitFPH(info.fpPerHour, info.cType);\n\t\tif (current_C_L == target_C_L) {\n\t\t\tlower_time = c_time;\n\t\t} else {\n\t\t\tupper_time = c_time;\n\t\t}\n\t}\n\t\/\/The actual integration time is the lower one as we really want C_L = target_C_L\n\tiTime = lower_time;\n\tinfo.det.SetIntegrationTime(iTime);\n\tminM = info.det.CalcActivityFPH(info.fpPerHour, info.beta, info.cType);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\n * This is a simple test program to test the facilities of the libcvmfs C\n * (not C++) library, which is used by Parrot and some other tools.\n *\n * The goal here is not so much to build the ultimate testing tool, but to\n * provide a simple build target which can verify that libcvmfs is exporting the\n * proper set of symbols to be used by a C program.\n *\/\n\n#define __STDC_FORMAT_MACROS\n\n#include \"cvmfs_config.h\"\n\n#include <errno.h>\n#include <inttypes.h>\n\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <map>\n#include <string>\n\n#include \"libcvmfs.h\"\n\n#define TEST_LINE_MAX 1024\n\ntypedef std::map<std::string, cvmfs_context*> RepoMap;\nstatic RepoMap attached_repos;\n\nvoid cvmfs_test_help()\n{\n printf(\"commands are:\\n\");\n printf(\" attach <repo name (without .cern.ch)>\\n\");\n printf(\" detach <repo name (without .cern.ch)>\\n\");\n printf(\" list <path>\\n\");\n printf(\" cat <path>\\n\");\n printf(\" quit\\n\");\n}\n\nint cvmfs_test_list(cvmfs_context *ctx, const char *path)\n{\n if (ctx == NULL) {\n fprintf(stderr, \"%s\\n\", \"please attach a repo first!\");\n return -1;\n }\n\n char filepath[TEST_LINE_MAX];\n struct stat info;\n\n char **buffer = 0;\n size_t length = 0;\n int i;\n\n int result = cvmfs_listdir(ctx, path, &buffer, &length);\n if (result < 0) {\n fprintf(stderr, \"%s: %s\\n\", path, strerror(errno));\n return -1;\n }\n\n\n for (i = 0; buffer[i]; i++) {\n snprintf(filepath, TEST_LINE_MAX, \"%s\/%s\", path, buffer[i]);\n cvmfs_stat(ctx, filepath, &info);\n printf(\"%10\"PRIu64\" %s\\n\", static_cast<uint64_t>(info.st_size), buffer[i]);\n }\n\n free(buffer);\n\n return 0;\n}\n\nint cvmfs_test_cat(cvmfs_context *ctx, const char *path)\n{\n if (ctx == NULL) {\n fprintf(stderr, \"%s\\n\", \"please attach a repo first!\");\n return -1;\n }\n\n char buffer[TEST_LINE_MAX];\n\n int fd = cvmfs_open(ctx, path);\n if (fd < 0) {\n fprintf(stderr, \"%s: %s\\n\", path, strerror(errno));\n return fd;\n }\n\n while (1) {\n int length = read(fd, buffer, sizeof(buffer));\n if (length <= 0) break;\n int retval = write(1, buffer, length);\n assert(retval == length);\n }\n\n cvmfs_close(ctx, fd);\n\n return 0;\n}\n\ncvmfs_context* cvmfs_test_attach(const char *repo_name)\n{\n cvmfs_context *ctx = NULL;\n\n RepoMap::const_iterator i = attached_repos.find(repo_name);\n if (i == attached_repos.end()) {\n const char *repo_options =\n \"repo_name=%s.cern.ch,url=http:\/\/cvmfs-stratum-one.cern.ch\/opt\/%s;\"\n \"http:\/\/cernvmfs.gridpp.rl.ac.uk\/opt\/%s;http:\/\/cvmfs.racf.bnl.gov\/opt\/%s,\"\n \"pubkey=\/etc\/cvmfs\/keys\/cern.ch\/cern.ch.pub,\"\n \"proxies=http:\/\/ca-proxy.cern.ch:3128\";\n char options[TEST_LINE_MAX];\n snprintf(options, TEST_LINE_MAX, repo_options, repo_name, repo_name,\n repo_name, repo_name);\n\n printf(\"attaching repo with options: %s\\n\", options);\n ctx = cvmfs_attach_repo(options);\n if (ctx == NULL) {\n fprintf(stderr, \"couldn't initialize cvmfs!\\n\");\n } else {\n attached_repos[repo_name] = ctx;\n }\n } else {\n printf(\"switching to previously attached repo: %s\\n\", repo_name);\n ctx = i->second;\n }\n\n return ctx;\n}\n\nvoid cvmfs_test_detach(const char *repo_name, const cvmfs_context *active_ctx) {\n RepoMap::iterator i = attached_repos.find(repo_name);\n if (i == attached_repos.end()) {\n printf(\"Did not find '%s' to detach\\n\", repo_name);\n return;\n }\n\n cvmfs_context *ctx = i->second;\n if (ctx == active_ctx) {\n printf(\"'%s' is currently active and cannot be detached.\\n\", repo_name);\n return;\n }\n\n attached_repos.erase(i);\n cvmfs_detach_repo(ctx);\n}\n\n\nint main(int argc, char *argv[])\n{\n char line[TEST_LINE_MAX];\n char path[TEST_LINE_MAX];\n char repo_name[TEST_LINE_MAX];\n\n const char *global_options = \"cache_directory=\/tmp\/test-libcvmfs-cache\";\n\n printf(\"%s: initializing with options: %s\\n\", argv[0], global_options);\n int retval = cvmfs_init(global_options);\n if (retval != 0) {\n fprintf(stderr, \"couldn't initialize libcvmfs!\\n\");\n return -1;\n }\n\n cvmfs_context *ctx = NULL;\n\n while (1) {\n printf(\"cvmfs> \");\n fflush(stdout);\n\n if (!fgets(line, sizeof(line), stdin)) break;\n\n line[strlen(line)-1] = 0;\n\n if (sscanf(line, \"list %s\", path) == 1) {\n cvmfs_test_list(ctx, path);\n } else if (sscanf(line, \"cat %s\", path) == 1) {\n cvmfs_test_cat(ctx, path);\n } else if (sscanf(line, \"attach %s\", repo_name) == 1) {\n ctx = cvmfs_test_attach(repo_name);\n } else if (sscanf(line, \"detach %s\", repo_name) == 1) {\n cvmfs_test_detach(repo_name, ctx);\n } else if (!strcmp(line, \"quit\")) {\n break;\n } else {\n cvmfs_test_help();\n }\n }\n\n cvmfs_fini();\n\n return 0;\n}\n\n<commit_msg>FIX: test_libcvmfs initialization options<commit_after>\/**\n * This file is part of the CernVM File System.\n *\n * This is a simple test program to test the facilities of the libcvmfs C\n * (not C++) library, which is used by Parrot and some other tools.\n *\n * The goal here is not so much to build the ultimate testing tool, but to\n * provide a simple build target which can verify that libcvmfs is exporting the\n * proper set of symbols to be used by a C program.\n *\/\n\n#define __STDC_FORMAT_MACROS\n\n#include \"cvmfs_config.h\"\n\n#include <errno.h>\n#include <inttypes.h>\n\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <map>\n#include <string>\n\n#include \"libcvmfs.h\"\n\n#define TEST_LINE_MAX 1024\n\ntypedef std::map<std::string, cvmfs_context*> RepoMap;\nstatic RepoMap attached_repos;\n\nvoid cvmfs_test_help()\n{\n printf(\"commands are:\\n\");\n printf(\" attach <repo name (without .cern.ch)>\\n\");\n printf(\" detach <repo name (without .cern.ch)>\\n\");\n printf(\" list <path>\\n\");\n printf(\" cat <path>\\n\");\n printf(\" quit\\n\");\n}\n\nint cvmfs_test_list(cvmfs_context *ctx, const char *path)\n{\n if (ctx == NULL) {\n fprintf(stderr, \"%s\\n\", \"please attach a repo first!\");\n return -1;\n }\n\n char filepath[TEST_LINE_MAX];\n struct stat info;\n\n char **buffer = 0;\n size_t length = 0;\n int i;\n\n int result = cvmfs_listdir(ctx, path, &buffer, &length);\n if (result < 0) {\n fprintf(stderr, \"%s: %s\\n\", path, strerror(errno));\n return -1;\n }\n\n\n for (i = 0; buffer[i]; i++) {\n snprintf(filepath, TEST_LINE_MAX, \"%s\/%s\", path, buffer[i]);\n cvmfs_stat(ctx, filepath, &info);\n printf(\"%10\"PRIu64\" %s\\n\", static_cast<uint64_t>(info.st_size), buffer[i]);\n }\n\n free(buffer);\n\n return 0;\n}\n\nint cvmfs_test_cat(cvmfs_context *ctx, const char *path)\n{\n if (ctx == NULL) {\n fprintf(stderr, \"%s\\n\", \"please attach a repo first!\");\n return -1;\n }\n\n char buffer[TEST_LINE_MAX];\n\n int fd = cvmfs_open(ctx, path);\n if (fd < 0) {\n fprintf(stderr, \"%s: %s\\n\", path, strerror(errno));\n return fd;\n }\n\n while (1) {\n int length = read(fd, buffer, sizeof(buffer));\n if (length <= 0) break;\n int retval = write(1, buffer, length);\n assert(retval == length);\n }\n\n cvmfs_close(ctx, fd);\n\n return 0;\n}\n\ncvmfs_context* cvmfs_test_attach(const char *repo_name)\n{\n cvmfs_context *ctx = NULL;\n\n RepoMap::const_iterator i = attached_repos.find(repo_name);\n if (i == attached_repos.end()) {\n const char *repo_options =\n \"repo_name=%s.cern.ch,url=http:\/\/cvmfs-stratum-one.cern.ch\/opt\/%s;\"\n \"http:\/\/cernvmfs.gridpp.rl.ac.uk\/opt\/%s;http:\/\/cvmfs.racf.bnl.gov\/opt\/%s,\"\n \"pubkey=\/etc\/cvmfs\/keys\/cern.ch\/cern.ch.pub\";\n char options[TEST_LINE_MAX];\n snprintf(options, TEST_LINE_MAX, repo_options, repo_name, repo_name,\n repo_name, repo_name);\n\n printf(\"attaching repo with options: %s\\n\", options);\n ctx = cvmfs_attach_repo(options);\n if (ctx == NULL) {\n fprintf(stderr, \"couldn't initialize cvmfs!\\n\");\n } else {\n attached_repos[repo_name] = ctx;\n }\n } else {\n printf(\"switching to previously attached repo: %s\\n\", repo_name);\n ctx = i->second;\n }\n\n return ctx;\n}\n\nvoid cvmfs_test_detach(const char *repo_name, const cvmfs_context *active_ctx) {\n RepoMap::iterator i = attached_repos.find(repo_name);\n if (i == attached_repos.end()) {\n printf(\"Did not find '%s' to detach\\n\", repo_name);\n return;\n }\n\n cvmfs_context *ctx = i->second;\n if (ctx == active_ctx) {\n printf(\"'%s' is currently active and cannot be detached.\\n\", repo_name);\n return;\n }\n\n attached_repos.erase(i);\n cvmfs_detach_repo(ctx);\n}\n\n\nint main(int argc, char *argv[])\n{\n char line[TEST_LINE_MAX];\n char path[TEST_LINE_MAX];\n char repo_name[TEST_LINE_MAX];\n\n const char *global_options = \"cache_directory=\/tmp\/test-libcvmfs-cache\";\n\n printf(\"%s: initializing with options: %s\\n\", argv[0], global_options);\n int retval = cvmfs_init(global_options);\n if (retval != 0) {\n fprintf(stderr, \"couldn't initialize libcvmfs!\\n\");\n return -1;\n }\n\n cvmfs_context *ctx = NULL;\n\n while (1) {\n printf(\"cvmfs> \");\n fflush(stdout);\n\n if (!fgets(line, sizeof(line), stdin)) break;\n\n line[strlen(line)-1] = 0;\n\n if (sscanf(line, \"list %s\", path) == 1) {\n cvmfs_test_list(ctx, path);\n } else if (sscanf(line, \"cat %s\", path) == 1) {\n cvmfs_test_cat(ctx, path);\n } else if (sscanf(line, \"attach %s\", repo_name) == 1) {\n ctx = cvmfs_test_attach(repo_name);\n } else if (sscanf(line, \"detach %s\", repo_name) == 1) {\n cvmfs_test_detach(repo_name, ctx);\n } else if (!strcmp(line, \"quit\")) {\n break;\n } else {\n cvmfs_test_help();\n }\n }\n\n cvmfs_fini();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Coding Standard: Unpublishable\n\/\/ This crap is going to work if it is the last thing I do tonight\n\/\/ I really miss having a desk that fits me, I dont even know what is going on 'osajgnnd[onea\n\/\/ Lets go\n\n\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <iostream>\nusing namespace std;\n\n\n\nint main() {\n\tcout << \"Loading the JSON file\" << endl;\n\tusing boost::property_tree::ptree;\n\tptree pt;\n\n\t\/\/ Load the JSON into the property tree ometrherfke\n\tstring testfile = \"db_schema.json\";\n\tread_json(testfile, pt);\n\n\tcout << \"JSON file loaded\" << endl;\n\n\n\n\tcout << \"Parsing File\" << endl;\n\tfor ( ptree::value_type const& v : pt.get_child(\"\")) {\n\n\t\tstring columnName = v.first;\n\n\t\tptree subtree = v.second;\n\t\tstring type = subtree.get<std::string>(\"Type\"); \n\t\tstring size = subtree.get(\"Size\", \"\");\n\t\tstring description = subtree.get(\"Description\", \"\");\n\t\tbool isIndex = subtree.get(\"Index\", false);\n\t\tstring defaultValue = subtree.get(\"Default\", \"\");\n\t\tbool isNullable = subtree.get(\"Nullable\", true);\n\t\tstring extraData = subtree.get(\"Extra\", \"\");\n\t\tbool isDepricated = subtree.get(\"Depricated\", false);\n\n\n\t\tcout << \" `\" << boost::to_lower_copy(columnName) << \"`\";\n\t\tcout << \" \" << boost::to_lower_copy(type); if (size.length() > 0) cout << \"(\" << size << \")\"; cout << \" \";\n\t\tif (!isNullable) cout << \"NOT NULL\";\n\t\tif (extraData.length() > 0) cout << \" \" << extraData;\n\t\tcout << \",\" << endl;\n\n\n\n\t\t\/\/ CREATE TABLE `virtual_aliases` (\n\t\t\/\/ `id` int(11) NOT NULL auto_increment,\n\t\t\/\/ `domain_id` int(11) NOT NULL,\n\t\t\/\/ `source` varchar(100) NOT NULL,\n\t\t\/\/ `destination` varchar(100) NOT NULL,\n\t\t\/\/ PRIMARY KEY (`id`),\n\t\t\/\/ FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE\n\t\t\/\/ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n\t}\n\n}<commit_msg>modified the schema compiler to handle indexes beter and generate c++ code<commit_after>\/\/ Coding Standard: Unpublishable\n\/\/ This crap is going to work if it is the last thing I do tonight\n\/\/ I really miss having a desk that fits me, I dont even know what is going on 'osajgnnd[onea\n\/\/ Lets go\n\n\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <iostream>\n#include <vector>\n#include <sstream>\n#include <map>\nusing namespace std;\n\n\n\nmap <string, string> SQLtoC {\n\t{\"varchar\", \"string\"},\n\t{\"int\", \"int\"},\n\t{\"timestamp\", \"sql_timestamp\"}\n};\n\n\nint main() {\n\tcout << \"Loading the JSON file\" << endl;\n\tusing boost::property_tree::ptree;\n\tptree pt;\n\n\t\/\/ Load the JSON into the property tree ometrherfke\n\tstring testfile = \"db_schema.json\";\n\tread_json(testfile, pt);\n\n\tcout << \"JSON file loaded\" << endl;\n\n\n\n\tcout << \"Parsing File\" << endl;\n\n\tstringstream cfile; \/\/ Really these should all be files\n\tstringstream sqlrows; \/\/ to be joined and encapsulated\n\tvector<string> slqindexes; \/\/ to be joined as is\n\n\tsqlrows << \"CREATE TABLE rules (\"; \n\n\n\tstring concatinator = \"\";\n\tfor ( ptree::value_type const& v : pt.get_child(\"columns\")) {\n\n\t\tstring columnName = v.first;\n\n\t\tptree subtree = v.second;\n\t\tstring type = subtree.get<std::string>(\"Type\");\n\t\tstring size = subtree.get(\"Size\", \"\");\n\t\tstring description = subtree.get(\"Description\", \"\");\n\t\tstring indexName = subtree.get(\"Index\", \"\");\n\t\tstring defaultValue = subtree.get(\"Default\", \"\");\n\t\tbool isNullable = subtree.get(\"Nullable\", true);\n\t\tstring extraData = subtree.get(\"Extra\", \"\");\n\t\tbool isDepricated = subtree.get(\"Depricated\", false);\n\n\n\n\n\t\tsqlrows << concatinator << endl << \" `\" << boost::to_lower_copy(columnName) << \"`\";\n\t\tsqlrows << \" \" << boost::to_lower_copy(type); if (size.length() > 0) sqlrows << \"(\" << size << \")\"; sqlrows << \" \";\n\t\tif (!isNullable) sqlrows << \"NOT NULL\";\n\t\tif (defaultValue.length() > 0) sqlrows << \" DEFAULT \" << defaultValue;\n\t\tif (extraData.length() > 0) sqlrows << \" \" << extraData;\n\t\tconcatinator = \",\";\n\n\n\t\tcfile << SQLtoC[type] << \" \" << columnName << \";\" << endl;\n\n\t\t\/\/ CREATE TABLE `virtual_aliases` (\n\t\t\/\/ `id` int(11) NOT NULL auto_increment,\n\t\t\/\/ `domain_id` int(11) NOT NULL,\n\t\t\/\/ `source` varchar(100) NOT NULL,\n\t\t\/\/ `destination` varchar(100) NOT NULL,\n\t\t\/\/ PRIMARY KEY (`id`),\n\t\t\/\/ FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE\n\t\t\/\/ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n\t}\n\n\tsqlrows << endl << \") ENGINE=InnoDB DEFAULT CHARSET=utf8;\" << endl; \/\/ the engine data might not be nessasary but IDK\n\t\/\/ cout << \"CREATE INDEX \" << indexName << \"ON rules (\" << columnName << \");\" << endl;\n\tcout << sqlrows.rdbuf() << endl;\n\tcout << cfile.rdbuf() << endl;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: trajectoryFile.C,v 1.3 2000\/12\/19 15:22:58 anker Exp $\n\n#include <BALL\/FORMAT\/trajectoryFile.h>\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\tTrajectoryFile::TrajectoryFile\n\t\t()\n\t\tthrow()\n\t\t:\tFile()\n\t{\n\t}\n\n\n\tTrajectoryFile::TrajectoryFile\n\t\t(const TrajectoryFile& file)\n\t\tthrow()\n\t\t:\tFile(file)\n\t{\n\t}\n\n\n\tTrajectoryFile::TrajectoryFile\n\t\t(const String& filename, File::OpenMode open_mode)\n\t\tthrow()\n\t\t: File(filename, open_mode)\n\t{\n\t}\n\n\n\tTrajectoryFile::~TrajectoryFile\n\t\t()\n\t\tthrow()\n\t{\n\t\tclear();\n\t}\n\n\n\tconst TrajectoryFile& TrajectoryFile::operator =\n\t\t(const TrajectoryFile& file)\n\t\tthrow()\n\t{\n\t\tFile::operator = (file);\n\n\t\treturn *this;\n\t}\n\n\n\tvoid TrajectoryFile::clear()\n\t\tthrow()\n\t{\n\t\tFile::clear();\n\t}\n\n\n\tbool TrajectoryFile::operator ==\n\t\t(const TrajectoryFile& file) const\n\t\tthrow()\n\t{\n\t\treturn File::operator == (file);\n\t}\n\n\n\tbool TrajectoryFile::readHeader()\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::readHeader(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tbool TrajectoryFile::updateHeader(const SnapShotManager& \/* manager *\/)\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::updateHeader(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tbool TrajectoryFile::writeHeader()\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::writeHeader(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tbool TrajectoryFile::read(SnapShotManager& \/* manager *\/)\n\t\tthrow(Exception::NotImplemented)\n\t{\n\t\tLog.error() << \"TrajectoryFile::read(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\t\n\n\tbool TrajectoryFile::write(const SnapShotManager& \/* manager *\/)\n\t\tthrow(Exception::NotImplemented)\n\t{\n\t\tLog.error() << \"TrajectoryFile::write(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tbool TrajectoryFile::append(const SnapShot& \/* snapshot *\/)\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::append(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n} \/\/ namespace BALL\n<commit_msg>removed: updateHeader() added: read(SnapShot&), flushToDisk(const vector<SnapShot>&), getNumberOfSnapShots()<commit_after>\/\/ $Id: trajectoryFile.C,v 1.4 2001\/03\/11 19:41:03 anker Exp $\n\n#include <BALL\/FORMAT\/trajectoryFile.h>\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\tTrajectoryFile::TrajectoryFile\n\t\t()\n\t\tthrow()\n\t\t:\tFile()\n\t{\n\t}\n\n\n\tTrajectoryFile::TrajectoryFile\n\t\t(const TrajectoryFile& file)\n\t\tthrow()\n\t\t:\tFile(file)\n\t{\n\t}\n\n\n\tTrajectoryFile::TrajectoryFile\n\t\t(const String& filename, File::OpenMode open_mode)\n\t\tthrow()\n\t\t: File(filename, open_mode)\n\t{\n\t}\n\n\n\tTrajectoryFile::~TrajectoryFile\n\t\t()\n\t\tthrow()\n\t{\n\t\tclear();\n\t}\n\n\n\tconst TrajectoryFile& TrajectoryFile::operator =\n\t\t(const TrajectoryFile& file)\n\t\tthrow()\n\t{\n\t\tFile::operator = (file);\n\n\t\treturn *this;\n\t}\n\n\n\tvoid TrajectoryFile::clear()\n\t\tthrow()\n\t{\n\t\tFile::clear();\n\t}\n\n\n\tbool TrajectoryFile::operator ==\n\t\t(const TrajectoryFile& file) const\n\t\tthrow()\n\t{\n\t\treturn File::operator == (file);\n\t}\n\n\n\tbool TrajectoryFile::readHeader()\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::readHeader(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tbool TrajectoryFile::writeHeader()\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::writeHeader(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tbool TrajectoryFile::read(SnapShotManager& \/* manager *\/)\n\t\tthrow(Exception::NotImplemented)\n\t{\n\t\tLog.error() << \"TrajectoryFile::read(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\t\n\n\tbool TrajectoryFile::write(const SnapShotManager& \/* manager *\/)\n\t\tthrow(Exception::NotImplemented)\n\t{\n\t\tLog.error() << \"TrajectoryFile::write(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tbool TrajectoryFile::append(const SnapShot& \/* snapshot *\/)\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::append(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tbool TrajectoryFile::read(SnapShot& \/* snapshot *\/)\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::read(): \" \n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\n\n\tSize TrajectoryFile::getNumberOfSnapShots() const\n\t\tthrow()\n\t{\n\t\treturn number_of_snapshots_;\n\t}\n\n\n\tbool TrajectoryFile::flushToDisk(const ::std::vector<SnapShot> \/* buffer *\/)\n\t\tthrow()\n\t{\n\t\tLog.error() << \"TrajectoryFile::flushToDisk(): \"\n\t\t\t<< \"This method should not be called\" << endl;\n\t\treturn false;\n\t}\n\t\n} \/\/ namespace BALL\n<|endoftext|>"} {"text":"<commit_before>\n\nAliAnalysisTaskESDfilter *AddTaskESDFilter(Bool_t useKineFilter=kTRUE, \n Bool_t writeMuonAOD=kFALSE,\n Bool_t writeDimuonAOD=kFALSE,\n\t\t\t\t\t Bool_t usePhysicsSelection=kFALSE,\n\t\t\t\t\t Bool_t useCentralityTask=kFALSE)\n{\n\/\/ Creates a filter task and adds it to the analysis manager.\n\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskESDFilter\", \"No analysis manager to connect to.\");\n return NULL;\n } \n \n \/\/ This task requires an ESD input handler and an AOD output handler.\n \/\/ Check this using the analysis manager.\n \/\/===============================================================================\n TString type = mgr->GetInputEventHandler()->GetDataType();\n if (!type.Contains(\"ESD\")) {\n ::Error(\"AddTaskESDFilter\", \"ESD filtering task needs the manager to have an ESD input handler.\");\n return NULL;\n } \n \/\/ Check if AOD output handler exist.\n AliAODHandler *aod_h = (AliAODHandler*)mgr->GetOutputEventHandler();\n if (!aod_h) {\n ::Error(\"AddTaskESDFilter\", \"ESD filtering task needs the manager to have an AOD output handler.\");\n return NULL;\n }\n \/\/ Check if MC handler is connected in case kine filter requested\n AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();\n if (!mcH && useKineFilter) {\n ::Error(\"AddTaskESDFilter\", \"No MC handler connected while kine filtering requested\");\n return NULL;\n } \n \n \/\/ Create the task, add it to the manager and configure it.\n \/\/=========================================================================== \n \/\/ Barrel tracks filter\n AliAnalysisTaskESDfilter *esdfilter = new AliAnalysisTaskESDfilter(\"ESD Filter\");\n\n \/\/ Make the AOD a little bit lighter and filtering faster\n \n esdfilter->DisableCascades();\n \/\/ esdfilter->DisableV0s();\n esdfilter->DisableKinks();\n \/\/ esdfilter->DisableTracks();\n esdfilter->DisablePmdClusters();\n \/\/ esdfilter->DisableCaloClusters();\n \/\/ esdfilter->DisableCells(); \n esdfilter->DisableTracklets();\n esdfilter->SetWriteHybridGlobalConstrainedOnly(kTRUE);\n\n AliAnalysisTaskAODCentralityMaker* ctask = 0;\n if (useCentralityTask) {\n ctask = new AliAnalysisTaskAODCentralityMaker(\"AODCentralityMaker\");\n ctask->SetDeltaAODFileName(\"AliAODCentrality.root\");\n mgr->AddTask(ctask);\n }\n\n\n mgr->AddTask(esdfilter);\n \/\/ Muons\n \/\/ AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter(\"ESD Muon Filter\");\n \/\/ mgr->AddTask(esdmuonfilter);\n if(usePhysicsSelection){\n esdfilter->SelectCollisionCandidates(AliVEvent::kAny);\n \/\/ esdmuonfilter->SelectCollisionCandidates(AliVEvent::kAny);\n } \n\n \/\/ Filtering of MC particles (decays conversions etc)\n \/\/ this task has to go AFTER all other filter tasks\n \/\/ since it fills the AODMC array with all\n \/\/ selected MC Particles, only this way we have the \n \/\/ AODMCparticle information available for following tasks\n AliAnalysisTaskMCParticleFilter *kinefilter = 0;\n if (useKineFilter) {\n kinefilter = new AliAnalysisTaskMCParticleFilter(\"Particle Kine Filter\");\n if(usePhysicsSelection)kinefilter->SelectCollisionCandidates(AliVEvent::kAny);\n mgr->AddTask(kinefilter);\n } \n\n \/\/ Cuts on primary tracks\n AliESDtrackCuts* esdTrackCutsL = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();\n\n \/\/ ITS stand-alone tracks\n AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts(\"ITS stand-alone Track Cuts\", \"ESD Track Cuts\");\n esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE);\n\n \/\/ Pixel OR necessary for the electrons\n AliESDtrackCuts *itsStrong = new AliESDtrackCuts(\"ITSorSPD\", \"pixel requirement for ITS\");\n itsStrong->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny);\n\n\n \/\/ PID for the electrons\n AliESDpidCuts *electronID = new AliESDpidCuts(\"Electrons\", \"Electron PID cuts\");\n electronID->SetTPCnSigmaCut(AliPID::kElectron, 3.);\n\n \/\/ tighter cuts on primary particles for high pT tracks\n \/\/ take the standard cuts, which include already \n \/\/ ITSrefit and use only primaries...\n\n \/\/ ITS cuts for new jet analysis \n gROOT->LoadMacro(\"$ALICE_ROOT\/PWG4\/macros\/CreateTrackCutsPWG4.C\");\n AliESDtrackCuts* esdTrackCutsHG0 = CreateTrackCutsPWG4(10001001);\n\n \/\/ throw out tracks with too low number of clusters in\n \/\/ the first pass (be consistent with TPC only tracks)\n \/\/ N.B. the number off crossed rows still acts on the tracks after\n \/\/ all iterations if we require tpc standalone, number of clusters\n \/\/ and chi2 TPC cuts act on track after the first iteration\n \/\/ esdTrackCutsH0->SetRequireTPCStandAlone(kTRUE);\n \/\/ esdTrackCutsH0->SetMinNClustersTPC(80); \/\/ <--- first pass\n\n\n \/\/ the complement to the one with SPD requirement\n AliESDtrackCuts* esdTrackCutsHG1 = CreateTrackCutsPWG4(10011001);\n\n \/\/ the tracks that must not be taken pass this cut and\n \/\/ non HGC1 and HG\n AliESDtrackCuts* esdTrackCutsHG2 = CreateTrackCutsPWG4(10021001);\n\n \n\n\n \/\/ standard cuts also used in R_AA analysis\n gROOT->LoadMacro(\"$ALICE_ROOT\/PWG0\/dNdPt\/macros\/CreatedNdPtTrackCuts.C\");\n AliESDtrackCuts* esdTrackCutsH2 = CreatedNdPtTrackCuts(200);\n esdTrackCutsH2->SetMaxChi2PerClusterITS(36.);\n esdTrackCutsH2->SetPtRange(0.15,1E10);\n\n \/\/ TPC only tracks\n AliESDtrackCuts* esdTrackCutsGCOnly = CreateTrackCutsPWG4(10041001);\n\n \/\/ Compose the filter\n AliAnalysisFilter* trackFilter = new AliAnalysisFilter(\"trackFilter\");\n \/\/ 1, 1<<0\n trackFilter->AddCuts(esdTrackCutsL);\n \/\/ 2 1<<1\n trackFilter->AddCuts(esdTrackCutsITSsa);\n \/\/ 4 1<<2\n trackFilter->AddCuts(itsStrong);\n itsStrong->SetFilterMask(1); \/\/ AND with Standard track cuts \n \/\/ 8 1<<3\n trackFilter->AddCuts(electronID);\n electronID->SetFilterMask(4); \/\/ AND with Pixel Cuts\n \/\/ 16 1<<4\n trackFilter->AddCuts(esdTrackCutsHG0);\n \/\/ 32 1<<5\n trackFilter->AddCuts(esdTrackCutsHG1);\n \/\/ 64 1<<6\n trackFilter->AddCuts(esdTrackCutsHG2);\n \/\/ 128 1<<7\n trackFilter->AddCuts(esdTrackCutsHG0); \/\/ add once more for tpc only tracks\n \/\/ 256 1<<8\n trackFilter->AddCuts(esdTrackCutsGCOnly);\n \/\/ 512 1<<9 \n trackFilter->AddCuts(esdTrackCutsHG1); \/\/ add once more for tpc only tracks\n \/\/ 512 1<<10 \n trackFilter->AddCuts(esdTrackCutsH2); \/\/ add r_aa cuts\n\n esdfilter->SetGlobalConstrainedFilterMask(1<<8|1<<9); \/\/ these tracks are written out as global constrained tracks\n esdfilter->SetHybridFilterMaskGlobalConstrainedGlobal((1<<4)); \/\/ these normal global tracks will be marked as hybrid\n\n\n \/\/ Filter with cuts on V0s\n AliESDv0Cuts* esdV0Cuts = new AliESDv0Cuts(\"Standard V0 Cuts pp\", \"ESD V0 Cuts\");\n esdV0Cuts->SetMinRadius(0.2);\n esdV0Cuts->SetMaxRadius(200);\n esdV0Cuts->SetMinDcaPosToVertex(0.05);\n esdV0Cuts->SetMinDcaNegToVertex(0.05);\n esdV0Cuts->SetMaxDcaV0Daughters(1.5);\n esdV0Cuts->SetMinCosinePointingAngle(0.99);\n AliAnalysisFilter* v0Filter = new AliAnalysisFilter(\"v0Filter\");\n v0Filter->AddCuts(esdV0Cuts);\n\n esdfilter->SetTrackFilter(trackFilter);\n esdfilter->SetV0Filter(v0Filter);\n\n \/\/ Enable writing of Muon AODs\n \/\/ esdmuonfilter->SetWriteMuonAOD(writeMuonAOD);\n \n \/\/ Enable writing of Dimuon AODs\n \/\/ esdmuonfilter->SetWriteDimuonAOD(writeDimuonAOD);\n \n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n\n mgr->ConnectInput (esdfilter, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput (esdfilter, 0, mgr->GetCommonOutputContainer());\n \n\n \/\/ mgr->ConnectInput (esdmuonfilter, 0, mgr->GetCommonInputContainer());\n if (useKineFilter) {\n mgr->ConnectInput (kinefilter, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput (kinefilter, 0, mgr->GetCommonOutputContainer());\n AliAnalysisDataContainer *coutputEx = mgr->CreateContainer(\"cFilterList\", TList::Class(),\n\t\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\"pyxsec_hists.root\");\n mgr->ConnectOutput (kinefilter, 1,coutputEx);\n } \n if (useCentralityTask) {\n mgr->ConnectInput (ctask, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(ctask, 0, mgr->GetCommonOutputContainer());\n }\n\n return esdfilter;\n }\n \n<commit_msg>adding TPC cosntrained tracks back in for comparison<commit_after>\n\nAliAnalysisTaskESDfilter *AddTaskESDFilter(Bool_t useKineFilter=kTRUE, \n Bool_t writeMuonAOD=kFALSE,\n Bool_t writeDimuonAOD=kFALSE,\n\t\t\t\t\t Bool_t usePhysicsSelection=kFALSE,\n\t\t\t\t\t Bool_t useCentralityTask=kFALSE)\n{\n\/\/ Creates a filter task and adds it to the analysis manager.\n\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskESDFilter\", \"No analysis manager to connect to.\");\n return NULL;\n } \n \n \/\/ This task requires an ESD input handler and an AOD output handler.\n \/\/ Check this using the analysis manager.\n \/\/===============================================================================\n TString type = mgr->GetInputEventHandler()->GetDataType();\n if (!type.Contains(\"ESD\")) {\n ::Error(\"AddTaskESDFilter\", \"ESD filtering task needs the manager to have an ESD input handler.\");\n return NULL;\n } \n \/\/ Check if AOD output handler exist.\n AliAODHandler *aod_h = (AliAODHandler*)mgr->GetOutputEventHandler();\n if (!aod_h) {\n ::Error(\"AddTaskESDFilter\", \"ESD filtering task needs the manager to have an AOD output handler.\");\n return NULL;\n }\n \/\/ Check if MC handler is connected in case kine filter requested\n AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();\n if (!mcH && useKineFilter) {\n ::Error(\"AddTaskESDFilter\", \"No MC handler connected while kine filtering requested\");\n return NULL;\n } \n \n \/\/ Create the task, add it to the manager and configure it.\n \/\/=========================================================================== \n \/\/ Barrel tracks filter\n AliAnalysisTaskESDfilter *esdfilter = new AliAnalysisTaskESDfilter(\"ESD Filter\");\n\n \/\/ Make the AOD a little bit lighter and filtering faster\n \n esdfilter->DisableCascades();\n \/\/ esdfilter->DisableV0s();\n esdfilter->DisableKinks();\n \/\/ esdfilter->DisableTracks();\n esdfilter->DisablePmdClusters();\n \/\/ esdfilter->DisableCaloClusters();\n \/\/ esdfilter->DisableCells(); \n esdfilter->DisableTracklets();\n esdfilter->SetWriteHybridGlobalConstrainedOnly(kTRUE);\n\n AliAnalysisTaskAODCentralityMaker* ctask = 0;\n if (useCentralityTask) {\n ctask = new AliAnalysisTaskAODCentralityMaker(\"AODCentralityMaker\");\n ctask->SetDeltaAODFileName(\"AliAODCentrality.root\");\n mgr->AddTask(ctask);\n }\n\n\n mgr->AddTask(esdfilter);\n \/\/ Muons\n \/\/ AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter(\"ESD Muon Filter\");\n \/\/ mgr->AddTask(esdmuonfilter);\n if(usePhysicsSelection){\n esdfilter->SelectCollisionCandidates(AliVEvent::kAny);\n \/\/ esdmuonfilter->SelectCollisionCandidates(AliVEvent::kAny);\n } \n\n \/\/ Filtering of MC particles (decays conversions etc)\n \/\/ this task has to go AFTER all other filter tasks\n \/\/ since it fills the AODMC array with all\n \/\/ selected MC Particles, only this way we have the \n \/\/ AODMCparticle information available for following tasks\n AliAnalysisTaskMCParticleFilter *kinefilter = 0;\n if (useKineFilter) {\n kinefilter = new AliAnalysisTaskMCParticleFilter(\"Particle Kine Filter\");\n if(usePhysicsSelection)kinefilter->SelectCollisionCandidates(AliVEvent::kAny);\n mgr->AddTask(kinefilter);\n } \n\n \/\/ Cuts on primary tracks\n AliESDtrackCuts* esdTrackCutsL = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();\n\n \/\/ ITS stand-alone tracks\n AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts(\"ITS stand-alone Track Cuts\", \"ESD Track Cuts\");\n esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE);\n\n \/\/ Pixel OR necessary for the electrons\n AliESDtrackCuts *itsStrong = new AliESDtrackCuts(\"ITSorSPD\", \"pixel requirement for ITS\");\n itsStrong->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny);\n\n\n \/\/ PID for the electrons\n AliESDpidCuts *electronID = new AliESDpidCuts(\"Electrons\", \"Electron PID cuts\");\n electronID->SetTPCnSigmaCut(AliPID::kElectron, 3.);\n\n \/\/ tighter cuts on primary particles for high pT tracks\n \/\/ take the standard cuts, which include already \n \/\/ ITSrefit and use only primaries...\n\n \/\/ ITS cuts for new jet analysis \n gROOT->LoadMacro(\"$ALICE_ROOT\/PWG4\/macros\/CreateTrackCutsPWG4.C\");\n AliESDtrackCuts* esdTrackCutsHG0 = CreateTrackCutsPWG4(10001004);\n\n \/\/ throw out tracks with too low number of clusters in\n \/\/ the first pass (be consistent with TPC only tracks)\n \/\/ N.B. the number off crossed rows still acts on the tracks after\n \/\/ all iterations if we require tpc standalone, number of clusters\n \/\/ and chi2 TPC cuts act on track after the first iteration\n \/\/ esdTrackCutsH0->SetRequireTPCStandAlone(kTRUE);\n \/\/ esdTrackCutsH0->SetMinNClustersTPC(80); \/\/ <--- first pass\n\n\n \/\/ the complement to the one with SPD requirement\n AliESDtrackCuts* esdTrackCutsHG1 = CreateTrackCutsPWG4(10011004);\n\n \/\/ the tracks that must not be taken pass this cut and\n \/\/ non HGC1 and HG\n AliESDtrackCuts* esdTrackCutsHG2 = CreateTrackCutsPWG4(10021004);\n\n \n\n\n \/\/ standard cuts also used in R_AA analysis\n gROOT->LoadMacro(\"$ALICE_ROOT\/PWG0\/dNdPt\/macros\/CreatedNdPtTrackCuts.C\");\n AliESDtrackCuts* esdTrackCutsH2 = CreatedNdPtTrackCuts(200);\n esdTrackCutsH2->SetMaxChi2PerClusterITS(36.);\n esdTrackCutsH2->SetPtRange(0.15,1E10);\n\n AliESDtrackCuts* esdTrackCutsGCOnly = CreateTrackCutsPWG4(10041004);\n\n \/\/ TPC only tracks\n AliESDtrackCuts* esdTrackCutsTPCCOnly = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();\n esdTrackCutsTPCCOnly->SetMinNClustersTPC(70);\n\n\n\n \/\/ Compose the filter\n AliAnalysisFilter* trackFilter = new AliAnalysisFilter(\"trackFilter\");\n \/\/ 1, 1<<0\n trackFilter->AddCuts(esdTrackCutsL);\n \/\/ 2 1<<1\n trackFilter->AddCuts(esdTrackCutsITSsa);\n \/\/ 4 1<<2\n trackFilter->AddCuts(itsStrong);\n itsStrong->SetFilterMask(1); \/\/ AND with Standard track cuts \n \/\/ 8 1<<3\n trackFilter->AddCuts(electronID);\n electronID->SetFilterMask(4); \/\/ AND with Pixel Cuts\n \/\/ 16 1<<4\n trackFilter->AddCuts(esdTrackCutsHG0);\n \/\/ 32 1<<5\n trackFilter->AddCuts(esdTrackCutsHG1);\n \/\/ 64 1<<6\n trackFilter->AddCuts(esdTrackCutsHG2);\n \/\/ 128 1<<7\n trackFilter->AddCuts(esdTrackCutsHG0); \/\/ add once more for tpc only tracks\n \/\/ 256 1<<8\n trackFilter->AddCuts(esdTrackCutsGCOnly);\n \/\/ 512 1<<9 \n trackFilter->AddCuts(esdTrackCutsHG1); \/\/ add once more for tpc only tracks\n \/\/ 1024 1<<10 \n trackFilter->AddCuts(esdTrackCutsH2); \/\/ add r_aa cuts\n \/\/ 2048 1<<11 \n trackFilter->AddCuts(esdTrackCutsTPCCOnly); \/\/ add QM TPC only track cuts\n \n\n esdfilter->SetGlobalConstrainedFilterMask(1<<8|1<<9); \/\/ these tracks are written out as global constrained tracks\n esdfilter->SetHybridFilterMaskGlobalConstrainedGlobal((1<<4)); \/\/ these normal global tracks will be marked as hybrid\n\n esdfilter->SetTPCConstrainedFilterMask(1<<11); \/\/ these tracks are written out as global constrained tracks\n\n \/\/ Filter with cuts on V0s\n AliESDv0Cuts* esdV0Cuts = new AliESDv0Cuts(\"Standard V0 Cuts pp\", \"ESD V0 Cuts\");\n esdV0Cuts->SetMinRadius(0.2);\n esdV0Cuts->SetMaxRadius(200);\n esdV0Cuts->SetMinDcaPosToVertex(0.05);\n esdV0Cuts->SetMinDcaNegToVertex(0.05);\n esdV0Cuts->SetMaxDcaV0Daughters(1.5);\n esdV0Cuts->SetMinCosinePointingAngle(0.99);\n AliAnalysisFilter* v0Filter = new AliAnalysisFilter(\"v0Filter\");\n v0Filter->AddCuts(esdV0Cuts);\n\n esdfilter->SetTrackFilter(trackFilter);\n esdfilter->SetV0Filter(v0Filter);\n\n \/\/ Enable writing of Muon AODs\n \/\/ esdmuonfilter->SetWriteMuonAOD(writeMuonAOD);\n \n \/\/ Enable writing of Dimuon AODs\n \/\/ esdmuonfilter->SetWriteDimuonAOD(writeDimuonAOD);\n \n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n\n mgr->ConnectInput (esdfilter, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput (esdfilter, 0, mgr->GetCommonOutputContainer());\n \n\n \/\/ mgr->ConnectInput (esdmuonfilter, 0, mgr->GetCommonInputContainer());\n if (useKineFilter) {\n mgr->ConnectInput (kinefilter, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput (kinefilter, 0, mgr->GetCommonOutputContainer());\n AliAnalysisDataContainer *coutputEx = mgr->CreateContainer(\"cFilterList\", TList::Class(),\n\t\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\"pyxsec_hists.root\");\n mgr->ConnectOutput (kinefilter, 1,coutputEx);\n } \n if (useCentralityTask) {\n mgr->ConnectInput (ctask, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(ctask, 0, mgr->GetCommonOutputContainer());\n }\n\n return esdfilter;\n }\n \n<|endoftext|>"} {"text":"<commit_before>#include \"manual_recorder.h\"\n\nnamespace lightstep {\n\/\/------------------------------------------------------------------------------\n\/\/ Constructor\n\/\/------------------------------------------------------------------------------\nManualRecorder::ManualRecorder(Logger& logger, LightStepTracerOptions options,\n std::unique_ptr<AsyncTransporter>&& transporter)\n : logger_{logger},\n options_{std::move(options)},\n builder_{options_.access_token, options_.tags},\n transporter_{std::move(transporter)} {\n \/\/ If no MetricsObserver was provided, use a default one that does nothing.\n if (options_.metrics_observer == nullptr) {\n options_.metrics_observer.reset(new MetricsObserver{});\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ RecordSpan\n\/\/------------------------------------------------------------------------------\nvoid ManualRecorder::RecordSpan(collector::Span&& span) noexcept try {\n if (builder_.num_pending_spans() >= options_.max_buffered_spans.value()) {\n \/\/ If there's no report in flight, flush the recoder. We can only get\n \/\/ here if max_buffered_spans was dynamically decreased.\n \/\/\n \/\/ Otherwise, drop the span.\n if (!IsReportInProgress()) {\n FlushOne();\n } else {\n dropped_spans_++;\n options_.metrics_observer->OnSpansDropped(1);\n return;\n }\n }\n builder_.AddSpan(std::move(span));\n if (builder_.num_pending_spans() >= options_.max_buffered_spans.value()) {\n FlushOne();\n }\n} catch (const std::exception& e) {\n logger_.Error(\"Failed to record span: \", e.what());\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ IsReportInProgress\n\/\/------------------------------------------------------------------------------\nbool ManualRecorder::IsReportInProgress() const noexcept {\n return encoding_seqno_ > 1 + flushed_seqno_;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ FlushOne\n\/\/------------------------------------------------------------------------------\nbool ManualRecorder::FlushOne() noexcept try {\n options_.metrics_observer->OnFlush();\n\n \/\/ If a report is currently in flight, do nothing; and if there are any\n \/\/ pending spans, then the flush is considered to have failed.\n if (IsReportInProgress()) {\n return builder_.num_pending_spans() == 0;\n }\n\n saved_pending_spans_ = builder_.num_pending_spans();\n if (saved_pending_spans_ == 0) {\n return true;\n }\n saved_dropped_spans_ = dropped_spans_;\n builder_.set_pending_client_dropped_spans(dropped_spans_);\n dropped_spans_ = 0;\n std::swap(builder_.pending(), active_request_);\n ++encoding_seqno_;\n transporter_->Send(active_request_, active_response_, *this);\n return true;\n} catch (const std::exception& e) {\n logger_.Error(\"Failed to Flush: \", e.what());\n options_.metrics_observer->OnSpansDropped(saved_pending_spans_);\n dropped_spans_ += saved_pending_spans_;\n active_request_.Clear();\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ FlushWithTimeout\n\/\/------------------------------------------------------------------------------\nbool ManualRecorder::FlushWithTimeout(\n std::chrono::system_clock::duration \/*timeout*\/) noexcept {\n return FlushOne();\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ OnSuccess\n\/\/------------------------------------------------------------------------------\nvoid ManualRecorder::OnSuccess() noexcept {\n ++flushed_seqno_;\n active_request_.Clear();\n options_.metrics_observer->OnSpansSent(saved_pending_spans_);\n if (options_.verbose) {\n logger_.Info(R\"(Report: resp=\")\", active_response_.ShortDebugString(),\n R\"(\")\");\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ OnFailure\n\/\/------------------------------------------------------------------------------\nvoid ManualRecorder::OnFailure(std::error_code error) noexcept {\n ++flushed_seqno_;\n active_request_.Clear();\n options_.metrics_observer->OnSpansDropped(saved_pending_spans_);\n dropped_spans_ += saved_dropped_spans_ + saved_pending_spans_;\n logger_.Error(\"Failed to send report: \", error.message());\n}\n} \/\/ namespace lightstep\n<commit_msg>Cache max_buffered_spans value.<commit_after>#include \"manual_recorder.h\"\n\nnamespace lightstep {\n\/\/------------------------------------------------------------------------------\n\/\/ Constructor\n\/\/------------------------------------------------------------------------------\nManualRecorder::ManualRecorder(Logger& logger, LightStepTracerOptions options,\n std::unique_ptr<AsyncTransporter>&& transporter)\n : logger_{logger},\n options_{std::move(options)},\n builder_{options_.access_token, options_.tags},\n transporter_{std::move(transporter)} {\n \/\/ If no MetricsObserver was provided, use a default one that does nothing.\n if (options_.metrics_observer == nullptr) {\n options_.metrics_observer.reset(new MetricsObserver{});\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ RecordSpan\n\/\/------------------------------------------------------------------------------\nvoid ManualRecorder::RecordSpan(collector::Span&& span) noexcept try {\n auto max_buffered_spans = options_.max_buffered_spans.value();\n if (builder_.num_pending_spans() >= max_buffered_spans) {\n \/\/ If there's no report in flight, flush the recoder. We can only get\n \/\/ here if max_buffered_spans was dynamically decreased.\n \/\/\n \/\/ Otherwise, drop the span.\n if (!IsReportInProgress()) {\n FlushOne();\n } else {\n dropped_spans_++;\n options_.metrics_observer->OnSpansDropped(1);\n return;\n }\n }\n builder_.AddSpan(std::move(span));\n if (builder_.num_pending_spans() >= max_buffered_spans) {\n FlushOne();\n }\n} catch (const std::exception& e) {\n logger_.Error(\"Failed to record span: \", e.what());\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ IsReportInProgress\n\/\/------------------------------------------------------------------------------\nbool ManualRecorder::IsReportInProgress() const noexcept {\n return encoding_seqno_ > 1 + flushed_seqno_;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ FlushOne\n\/\/------------------------------------------------------------------------------\nbool ManualRecorder::FlushOne() noexcept try {\n options_.metrics_observer->OnFlush();\n\n \/\/ If a report is currently in flight, do nothing; and if there are any\n \/\/ pending spans, then the flush is considered to have failed.\n if (IsReportInProgress()) {\n return builder_.num_pending_spans() == 0;\n }\n\n saved_pending_spans_ = builder_.num_pending_spans();\n if (saved_pending_spans_ == 0) {\n return true;\n }\n saved_dropped_spans_ = dropped_spans_;\n builder_.set_pending_client_dropped_spans(dropped_spans_);\n dropped_spans_ = 0;\n std::swap(builder_.pending(), active_request_);\n ++encoding_seqno_;\n transporter_->Send(active_request_, active_response_, *this);\n return true;\n} catch (const std::exception& e) {\n logger_.Error(\"Failed to Flush: \", e.what());\n options_.metrics_observer->OnSpansDropped(saved_pending_spans_);\n dropped_spans_ += saved_pending_spans_;\n active_request_.Clear();\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ FlushWithTimeout\n\/\/------------------------------------------------------------------------------\nbool ManualRecorder::FlushWithTimeout(\n std::chrono::system_clock::duration \/*timeout*\/) noexcept {\n return FlushOne();\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ OnSuccess\n\/\/------------------------------------------------------------------------------\nvoid ManualRecorder::OnSuccess() noexcept {\n ++flushed_seqno_;\n active_request_.Clear();\n options_.metrics_observer->OnSpansSent(saved_pending_spans_);\n if (options_.verbose) {\n logger_.Info(R\"(Report: resp=\")\", active_response_.ShortDebugString(),\n R\"(\")\");\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ OnFailure\n\/\/------------------------------------------------------------------------------\nvoid ManualRecorder::OnFailure(std::error_code error) noexcept {\n ++flushed_seqno_;\n active_request_.Clear();\n options_.metrics_observer->OnSpansDropped(saved_pending_spans_);\n dropped_spans_ += saved_dropped_spans_ + saved_pending_spans_;\n logger_.Error(\"Failed to send report: \", error.message());\n}\n} \/\/ namespace lightstep\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/core\/reduce_pre_table.hpp\n *\n * Hash table with support for reduce and partitions.\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_CORE_REDUCE_PRE_TABLE_HEADER\n#define C7A_CORE_REDUCE_PRE_TABLE_HEADER\n\n#include <c7a\/api\/function_traits.hpp>\n#include <c7a\/data\/data_manager.hpp>\n\n#include <map>\n#include <iostream>\n#include <c7a\/common\/logger.hpp>\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include <array>\n#include <deque>\n#include <utility>\n\nnamespace c7a {\nnamespace core {\ntemplate <typename KeyExtractor, typename ReduceFunction, typename EmitterFunction>\nclass ReducePreTable\n{\n static const bool debug = true;\n\n using key_t = typename FunctionTraits<KeyExtractor>::result_type;\n\n using value_t = typename FunctionTraits<ReduceFunction>::result_type;\n\nprotected:\n struct hash_result\n {\n \/\/! which partition number the item belongs to.\n size_t partition_id;\n \/\/! index within the partition's sub-hashtable of this item\n size_t partition_offset;\n \/\/! index within the whole hashtable\n size_t global_index;\n\n hash_result(key_t v, const ReducePreTable& ht) {\n size_t hashed = std::hash<key_t>() (v);\n\n \/\/ partition idx\n partition_offset = hashed % ht.num_buckets_per_partition_;\n\n \/\/ partition id\n partition_id = hashed % ht.num_partitions_;\n\n \/\/ global idx\n global_index = partition_id * ht.num_buckets_per_partition_ + partition_offset;\n }\n };\n\n struct bucket_block {\n \/\/ TODO(ms): use a new\/delete here instead of a vector, it is faster.\n std::vector<std::pair<key_t, value_t> > items;\n\n bucket_block * next = NULL;\n\n bucket_block(const ReducePreTable& ht) {\n items.reserve(ht.bucket_block_size_);\n }\n };\n\npublic:\n ReducePreTable(size_t num_partitions, size_t num_buckets_init_scale, size_t num_buckets_resize_scale,\n size_t max_num_items_per_bucket, size_t max_num_items_table,\n KeyExtractor key_extractor, ReduceFunction reduce_function,\n std::vector<EmitterFunction> emit)\n : num_partitions_(num_partitions),\n num_buckets_init_scale_(num_buckets_init_scale),\n num_buckets_resize_scale_(num_buckets_resize_scale),\n max_num_items_per_bucket_(max_num_items_per_bucket),\n max_num_items_table_(max_num_items_table),\n key_extractor_(key_extractor),\n reduce_function_(reduce_function),\n emit_(emit) {\n init();\n }\n\n ReducePreTable(size_t partition_size, KeyExtractor key_extractor,\n ReduceFunction reduce_function, std::vector<EmitterFunction> emit)\n : num_partitions_(partition_size),\n key_extractor_(key_extractor),\n reduce_function_(reduce_function),\n emit_(emit) {\n init();\n }\n\n ~ReducePreTable() { }\n\n void init() {\n sLOG << \"creating reducePreTable with\" << emit_.size() << \"output emiters\";\n for (auto& e : emit_)\n emit_stats_.push_back(0);\n\n num_buckets_ = num_partitions_ * num_buckets_init_scale_;\n if (num_partitions_ > num_buckets_ &&\n num_buckets_ % num_partitions_ != 0) {\n throw std::invalid_argument(\"partition_size must be less than or equal to num_buckets \"\n \"AND partition_size a divider of num_buckets\");\n }\n num_buckets_per_partition_ = num_buckets_ \/ num_partitions_;\n\n vector_.resize(num_buckets_, NULL);\n items_per_partition_.resize(num_partitions_, 0);\n }\n\n \/*!\n * Inserts a key\/value pair.\n *\n * Optionally, this may be reduce using the reduce function\n * in case the key already exists.\n *\/\n void Insert(const value_t& p) {\n key_t key = key_extractor_(p);\n\n hash_result h(key, *this);\n\n LOG << \"key: \" << key << \" to bucket id: \" << h.global_index;\n\n size_t num_items_bucket = 0;\n bucket_block* current_bucket_block = vector_[h.global_index];\n while (current_bucket_block != NULL)\n {\n for (auto& bucket_item : current_bucket_block->items)\n {\n \/\/ if item and key equals\n \/\/ then reduce\n if (key == bucket_item.first)\n {\n LOG << \"match of key: \" << key << \" and \" << bucket_item.first << \" ... reducing...\";\n bucket_item.second = reduce_function_(bucket_item.second, p);\n LOG << \"...finished reduce!\";\n return;\n }\n\n \/\/ increase num items in bucket for visited item\n num_items_bucket++;\n }\n\n if (current_bucket_block->next == NULL)\n {\n break;\n }\n\n current_bucket_block = current_bucket_block->next;\n }\n\n if (current_bucket_block == NULL)\n {\n current_bucket_block = vector_[h.global_index] = new bucket_block(*this);\n }\n else if (current_bucket_block->items.size() == bucket_block_size_)\n {\n current_bucket_block = current_bucket_block->next = new bucket_block(*this);\n }\n\n \/\/ insert new item in current bucket block\n current_bucket_block->items.push_back(std::pair<key_t, value_t>(key, p));\n \/\/ increase counter for partition\n items_per_partition_[h.partition_id]++;\n \/\/ increase total counter\n table_size_++;\n\n \/\/ increase num items in bucket for inserted item\n num_items_bucket++;\n\n if (table_size_ > max_num_items_table_)\n {\n LOG << \"spilling in progress\";\n FlushLargestPartition();\n }\n\n if (num_items_bucket > max_num_items_per_bucket_)\n {\n ResizeUp();\n }\n }\n\n \/*!\n * Flushes all items.\n *\/\n void Flush() {\n LOG << \"Flushing all items\";\n\n \/\/ retrieve items\n for (size_t i = 0; i < num_partitions_; i++)\n {\n FlushPartition(i);\n }\n\n LOG << \"Flushed all items\";\n }\n\n \/*!\n * Retrieves all items belonging to the partition\n * having the most items. Retrieved items are then forward\n * to the provided emitter.\n *\/\n void FlushLargestPartition() {\n LOG << \"Flushing items of largest partition\";\n\n \/\/ get partition with max size\n size_t p_size_max = 0;\n size_t p_idx = 0;\n for (size_t i = 0; i < num_partitions_; i++)\n {\n if (items_per_partition_[i] > p_size_max)\n {\n p_size_max = items_per_partition_[i];\n p_idx = i;\n }\n }\n\n LOG << \"currMax: \"\n << p_size_max\n << \" currentIdx: \"\n << p_idx\n << \" currentIdx*p_size: \"\n << p_idx * num_buckets_per_partition_\n << \" CurrentIdx*p_size+p_size-1 \"\n << p_idx * num_buckets_per_partition_ + num_buckets_per_partition_ - 1;\n\n LOG << \"Largest patition id: \"\n << p_idx;\n\n FlushPartition(p_idx);\n\n LOG << \"Flushed items of largest partition\";\n }\n\n \/*!\n * Flushes all items of a partition.\n *\/\n void FlushPartition(size_t partition_id) {\n LOG << \"Flushing items of partition with id: \"\n << partition_id;\n\n for (size_t i = partition_id * num_buckets_per_partition_;\n i <= partition_id * num_buckets_per_partition_ + num_buckets_per_partition_ - 1; i++)\n {\n bucket_block* current_bucket_block = vector_[i];\n while (current_bucket_block != NULL)\n {\n for (std::pair<key_t, value_t>& bucket_item : current_bucket_block->items)\n {\n emit_[partition_id](bucket_item.second);\n emit_stats_[partition_id]++;\n }\n \/\/TODO(ms) call emit_[partition_id].Flush here to ensure elements are acutally pushed via network\n \/\/I could not make the change because there are some instances of this class with std::functions\n \/\/and they don't offer the Flush() mehtod of course.\n bucket_block* tmp_current_bucket_block = current_bucket_block->next;\n delete current_bucket_block;\n current_bucket_block = tmp_current_bucket_block;\n }\n\n vector_[i] = NULL;\n }\n\n \/\/ reset total counter\n table_size_ -= items_per_partition_[partition_id];\n \/\/ reset partition specific counter\n items_per_partition_[partition_id] = 0;\n\n LOG << \"Flushed items of partition with id: \"\n << partition_id;\n }\n\n \/*!\n * Returns the total num of items.\n *\/\n size_t Size() {\n return table_size_;\n }\n\n \/*!\n * Returns the total num of items.\n *\/\n size_t NumBuckets() {\n return num_buckets_;\n }\n\n \/*!\n * Sets the maximum size of the hash table. We don't want to push 2vt elements before flush happens.\n *\/\n void SetMaxSize(size_t size) {\n max_num_items_table_ = size;\n }\n\n \/*!\n * Closes all emitter\n *\/\n void CloseEmitter() {\n sLOG << \"emit stats:\";\n unsigned int i = 0;\n for (auto& e : emit_) {\n e.Close();\n sLOG << \"emiter\" << i << \"pushed\" << emit_stats_[i++];\n }\n }\n\n \/*!\n * Resizes the table by increasing the number of buckets using some\n * resize scale factor. All items are rehashed as part of the operation.\n *\/\n void ResizeUp() {\n LOG << \"Resizing\";\n num_buckets_ *= num_buckets_resize_scale_;\n num_buckets_per_partition_ = num_buckets_ \/ num_partitions_;\n \/\/ init new array\n std::vector<bucket_block*> vector_old = vector_;\n std::vector<bucket_block*> vector_new; \/\/ TODO(ms): 3 vectors? come on! -> make it happen with one vector only!\n vector_new.resize(num_buckets_, NULL);\n vector_ = vector_new;\n \/\/ rehash all items in old array\n for (bucket_block* b_block : vector_old)\n {\n bucket_block* current_bucket_block = b_block;\n while (current_bucket_block != NULL)\n {\n for (std::pair<key_t, value_t>& bucket_item : current_bucket_block->items)\n {\n Insert(bucket_item.second);\n }\n bucket_block* tmp_current_bucket_block = current_bucket_block->next;\n delete current_bucket_block;\n current_bucket_block = tmp_current_bucket_block;\n }\n }\n LOG << \"Resized\";\n }\n\n \/*!\n * Removes all items in the table, but NOT flushing them.\n *\/\n void Clear() {\n LOG << \"Clearing\";\n std::fill(vector_.begin(), vector_.end(), NULL);\n std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0);\n table_size_ = 0;\n LOG << \"Cleared\";\n }\n\n \/*!\n * Removes all items in the table, but NOT flushing them.\n *\/\n void Reset() {\n LOG << \"Resetting\";\n num_buckets_ = num_partitions_ * num_buckets_init_scale_;\n num_buckets_per_partition_ = num_buckets_ \/ num_partitions_;\n vector_.resize(num_buckets_, NULL);\n std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0);\n table_size_ = 0;\n LOG << \"Resetted\";\n }\n\n \/*!\n * Prints content of hash table.\n *\/\n void Print() {\n LOG << \"Printing\";\n\n for (int i = 0; i < num_buckets_; i++)\n {\n if (vector_[i] == NULL)\n {\n LOG << \"bucket id: \"\n << i\n << \" empty\";\n }\n else\n {\n std::string log = \"\";\n\n bucket_block* current_bucket_block = vector_[i];\n while (current_bucket_block != NULL)\n {\n log += \"block: \";\n\n for (std::pair<key_t, value_t> bucket_item : current_bucket_block->items)\n {\n if (&bucket_item != NULL)\n {\n log += \"(\";\n log += bucket_item.first;\n log += \", \";\n \/\/log += bucket_item.second; \/\/ TODO(ms): How to convert value_t to a string?\n log += \") \";\n }\n }\n current_bucket_block = current_bucket_block->next;\n }\n\n LOG << \"bucket id: \"\n << i\n << \" \"\n << log;\n }\n }\n\n return;\n }\n\nprivate:\n size_t num_partitions_; \/\/ partition size\n\n size_t num_buckets_; \/\/ num buckets\n\n size_t num_buckets_per_partition_; \/\/ num buckets per partition\n\n size_t num_buckets_init_scale_ = 10; \/\/ set number of buckets per partition based on num_partitions\n \/\/ multiplied with some scaling factor, must be equal to or greater than 1\n\n size_t num_buckets_resize_scale_ = 2; \/\/ resize scale on max_num_items_per_bucket_\n\n size_t bucket_block_size_ = 32; \/\/ size of bucket blocks\n\n size_t max_num_items_per_bucket_ = 256; \/\/ max num of items per bucket before resize\n\n std::vector<size_t> items_per_partition_; \/\/ num items per partition\n\n size_t table_size_ = 0; \/\/ total number of items\n\n size_t max_num_items_table_ = 1048576; \/\/ max num of items before spilling of largest partition\n\n KeyExtractor key_extractor_;\n\n ReduceFunction reduce_function_;\n\n std::vector<EmitterFunction> emit_;\n std::vector<int> emit_stats_;\n\n std::vector<bucket_block*> vector_;\n};\n\n} \/\/ namespace core\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_CORE_REDUCE_PRE_TABLE_HEADER\n\n\/******************************************************************************\/\n<commit_msg>fix compiler warning in reduce_pre_table.hpp that I introduced<commit_after>\/*******************************************************************************\n * c7a\/core\/reduce_pre_table.hpp\n *\n * Hash table with support for reduce and partitions.\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_CORE_REDUCE_PRE_TABLE_HEADER\n#define C7A_CORE_REDUCE_PRE_TABLE_HEADER\n\n#include <c7a\/api\/function_traits.hpp>\n#include <c7a\/data\/data_manager.hpp>\n\n#include <map>\n#include <iostream>\n#include <c7a\/common\/logger.hpp>\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include <array>\n#include <deque>\n#include <utility>\n\nnamespace c7a {\nnamespace core {\ntemplate <typename KeyExtractor, typename ReduceFunction, typename EmitterFunction>\nclass ReducePreTable\n{\n static const bool debug = true;\n\n using key_t = typename FunctionTraits<KeyExtractor>::result_type;\n\n using value_t = typename FunctionTraits<ReduceFunction>::result_type;\n\nprotected:\n struct hash_result\n {\n \/\/! which partition number the item belongs to.\n size_t partition_id;\n \/\/! index within the partition's sub-hashtable of this item\n size_t partition_offset;\n \/\/! index within the whole hashtable\n size_t global_index;\n\n hash_result(key_t v, const ReducePreTable& ht) {\n size_t hashed = std::hash<key_t>() (v);\n\n \/\/ partition idx\n partition_offset = hashed % ht.num_buckets_per_partition_;\n\n \/\/ partition id\n partition_id = hashed % ht.num_partitions_;\n\n \/\/ global idx\n global_index = partition_id * ht.num_buckets_per_partition_ + partition_offset;\n }\n };\n\n struct bucket_block {\n \/\/ TODO(ms): use a new\/delete here instead of a vector, it is faster.\n std::vector<std::pair<key_t, value_t> > items;\n\n bucket_block * next = NULL;\n\n bucket_block(const ReducePreTable& ht) {\n items.reserve(ht.bucket_block_size_);\n }\n };\n\npublic:\n ReducePreTable(size_t num_partitions, size_t num_buckets_init_scale, size_t num_buckets_resize_scale,\n size_t max_num_items_per_bucket, size_t max_num_items_table,\n KeyExtractor key_extractor, ReduceFunction reduce_function,\n std::vector<EmitterFunction> emit)\n : num_partitions_(num_partitions),\n num_buckets_init_scale_(num_buckets_init_scale),\n num_buckets_resize_scale_(num_buckets_resize_scale),\n max_num_items_per_bucket_(max_num_items_per_bucket),\n max_num_items_table_(max_num_items_table),\n key_extractor_(key_extractor),\n reduce_function_(reduce_function),\n emit_(emit) {\n init();\n }\n\n ReducePreTable(size_t partition_size, KeyExtractor key_extractor,\n ReduceFunction reduce_function, std::vector<EmitterFunction> emit)\n : num_partitions_(partition_size),\n key_extractor_(key_extractor),\n reduce_function_(reduce_function),\n emit_(emit) {\n init();\n }\n\n ~ReducePreTable() { }\n\n void init() {\n sLOG << \"creating reducePreTable with\" << emit_.size() << \"output emiters\";\n for (size_t i = 0; i < emit_.size(); i++)\n emit_stats_.push_back(0);\n\n num_buckets_ = num_partitions_ * num_buckets_init_scale_;\n if (num_partitions_ > num_buckets_ &&\n num_buckets_ % num_partitions_ != 0) {\n throw std::invalid_argument(\"partition_size must be less than or equal to num_buckets \"\n \"AND partition_size a divider of num_buckets\");\n }\n num_buckets_per_partition_ = num_buckets_ \/ num_partitions_;\n\n vector_.resize(num_buckets_, NULL);\n items_per_partition_.resize(num_partitions_, 0);\n }\n\n \/*!\n * Inserts a key\/value pair.\n *\n * Optionally, this may be reduce using the reduce function\n * in case the key already exists.\n *\/\n void Insert(const value_t& p) {\n key_t key = key_extractor_(p);\n\n hash_result h(key, *this);\n\n LOG << \"key: \" << key << \" to bucket id: \" << h.global_index;\n\n size_t num_items_bucket = 0;\n bucket_block* current_bucket_block = vector_[h.global_index];\n while (current_bucket_block != NULL)\n {\n for (auto& bucket_item : current_bucket_block->items)\n {\n \/\/ if item and key equals\n \/\/ then reduce\n if (key == bucket_item.first)\n {\n LOG << \"match of key: \" << key << \" and \" << bucket_item.first << \" ... reducing...\";\n bucket_item.second = reduce_function_(bucket_item.second, p);\n LOG << \"...finished reduce!\";\n return;\n }\n\n \/\/ increase num items in bucket for visited item\n num_items_bucket++;\n }\n\n if (current_bucket_block->next == NULL)\n {\n break;\n }\n\n current_bucket_block = current_bucket_block->next;\n }\n\n if (current_bucket_block == NULL)\n {\n current_bucket_block = vector_[h.global_index] = new bucket_block(*this);\n }\n else if (current_bucket_block->items.size() == bucket_block_size_)\n {\n current_bucket_block = current_bucket_block->next = new bucket_block(*this);\n }\n\n \/\/ insert new item in current bucket block\n current_bucket_block->items.push_back(std::pair<key_t, value_t>(key, p));\n \/\/ increase counter for partition\n items_per_partition_[h.partition_id]++;\n \/\/ increase total counter\n table_size_++;\n\n \/\/ increase num items in bucket for inserted item\n num_items_bucket++;\n\n if (table_size_ > max_num_items_table_)\n {\n LOG << \"spilling in progress\";\n FlushLargestPartition();\n }\n\n if (num_items_bucket > max_num_items_per_bucket_)\n {\n ResizeUp();\n }\n }\n\n \/*!\n * Flushes all items.\n *\/\n void Flush() {\n LOG << \"Flushing all items\";\n\n \/\/ retrieve items\n for (size_t i = 0; i < num_partitions_; i++)\n {\n FlushPartition(i);\n }\n\n LOG << \"Flushed all items\";\n }\n\n \/*!\n * Retrieves all items belonging to the partition\n * having the most items. Retrieved items are then forward\n * to the provided emitter.\n *\/\n void FlushLargestPartition() {\n LOG << \"Flushing items of largest partition\";\n\n \/\/ get partition with max size\n size_t p_size_max = 0;\n size_t p_idx = 0;\n for (size_t i = 0; i < num_partitions_; i++)\n {\n if (items_per_partition_[i] > p_size_max)\n {\n p_size_max = items_per_partition_[i];\n p_idx = i;\n }\n }\n\n LOG << \"currMax: \"\n << p_size_max\n << \" currentIdx: \"\n << p_idx\n << \" currentIdx*p_size: \"\n << p_idx * num_buckets_per_partition_\n << \" CurrentIdx*p_size+p_size-1 \"\n << p_idx * num_buckets_per_partition_ + num_buckets_per_partition_ - 1;\n\n LOG << \"Largest patition id: \"\n << p_idx;\n\n FlushPartition(p_idx);\n\n LOG << \"Flushed items of largest partition\";\n }\n\n \/*!\n * Flushes all items of a partition.\n *\/\n void FlushPartition(size_t partition_id) {\n LOG << \"Flushing items of partition with id: \"\n << partition_id;\n\n for (size_t i = partition_id * num_buckets_per_partition_;\n i <= partition_id * num_buckets_per_partition_ + num_buckets_per_partition_ - 1; i++)\n {\n bucket_block* current_bucket_block = vector_[i];\n while (current_bucket_block != NULL)\n {\n for (std::pair<key_t, value_t>& bucket_item : current_bucket_block->items)\n {\n emit_[partition_id](bucket_item.second);\n emit_stats_[partition_id]++;\n }\n \/\/TODO(ms) call emit_[partition_id].Flush here to ensure elements are acutally pushed via network\n \/\/I could not make the change because there are some instances of this class with std::functions\n \/\/and they don't offer the Flush() mehtod of course.\n bucket_block* tmp_current_bucket_block = current_bucket_block->next;\n delete current_bucket_block;\n current_bucket_block = tmp_current_bucket_block;\n }\n\n vector_[i] = NULL;\n }\n\n \/\/ reset total counter\n table_size_ -= items_per_partition_[partition_id];\n \/\/ reset partition specific counter\n items_per_partition_[partition_id] = 0;\n\n LOG << \"Flushed items of partition with id: \"\n << partition_id;\n }\n\n \/*!\n * Returns the total num of items.\n *\/\n size_t Size() {\n return table_size_;\n }\n\n \/*!\n * Returns the total num of items.\n *\/\n size_t NumBuckets() {\n return num_buckets_;\n }\n\n \/*!\n * Sets the maximum size of the hash table. We don't want to push 2vt elements before flush happens.\n *\/\n void SetMaxSize(size_t size) {\n max_num_items_table_ = size;\n }\n\n \/*!\n * Closes all emitter\n *\/\n void CloseEmitter() {\n sLOG << \"emit stats:\";\n unsigned int i = 0;\n for (auto& e : emit_) {\n e.Close();\n sLOG << \"emiter\" << i << \"pushed\" << emit_stats_[i++];\n }\n }\n\n \/*!\n * Resizes the table by increasing the number of buckets using some\n * resize scale factor. All items are rehashed as part of the operation.\n *\/\n void ResizeUp() {\n LOG << \"Resizing\";\n num_buckets_ *= num_buckets_resize_scale_;\n num_buckets_per_partition_ = num_buckets_ \/ num_partitions_;\n \/\/ init new array\n std::vector<bucket_block*> vector_old = vector_;\n std::vector<bucket_block*> vector_new; \/\/ TODO(ms): 3 vectors? come on! -> make it happen with one vector only!\n vector_new.resize(num_buckets_, NULL);\n vector_ = vector_new;\n \/\/ rehash all items in old array\n for (bucket_block* b_block : vector_old)\n {\n bucket_block* current_bucket_block = b_block;\n while (current_bucket_block != NULL)\n {\n for (std::pair<key_t, value_t>& bucket_item : current_bucket_block->items)\n {\n Insert(bucket_item.second);\n }\n bucket_block* tmp_current_bucket_block = current_bucket_block->next;\n delete current_bucket_block;\n current_bucket_block = tmp_current_bucket_block;\n }\n }\n LOG << \"Resized\";\n }\n\n \/*!\n * Removes all items in the table, but NOT flushing them.\n *\/\n void Clear() {\n LOG << \"Clearing\";\n std::fill(vector_.begin(), vector_.end(), NULL);\n std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0);\n table_size_ = 0;\n LOG << \"Cleared\";\n }\n\n \/*!\n * Removes all items in the table, but NOT flushing them.\n *\/\n void Reset() {\n LOG << \"Resetting\";\n num_buckets_ = num_partitions_ * num_buckets_init_scale_;\n num_buckets_per_partition_ = num_buckets_ \/ num_partitions_;\n vector_.resize(num_buckets_, NULL);\n std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0);\n table_size_ = 0;\n LOG << \"Resetted\";\n }\n\n \/*!\n * Prints content of hash table.\n *\/\n void Print() {\n LOG << \"Printing\";\n\n for (int i = 0; i < num_buckets_; i++)\n {\n if (vector_[i] == NULL)\n {\n LOG << \"bucket id: \"\n << i\n << \" empty\";\n }\n else\n {\n std::string log = \"\";\n\n bucket_block* current_bucket_block = vector_[i];\n while (current_bucket_block != NULL)\n {\n log += \"block: \";\n\n for (std::pair<key_t, value_t> bucket_item : current_bucket_block->items)\n {\n if (&bucket_item != NULL)\n {\n log += \"(\";\n log += bucket_item.first;\n log += \", \";\n \/\/log += bucket_item.second; \/\/ TODO(ms): How to convert value_t to a string?\n log += \") \";\n }\n }\n current_bucket_block = current_bucket_block->next;\n }\n\n LOG << \"bucket id: \"\n << i\n << \" \"\n << log;\n }\n }\n\n return;\n }\n\nprivate:\n size_t num_partitions_; \/\/ partition size\n\n size_t num_buckets_; \/\/ num buckets\n\n size_t num_buckets_per_partition_; \/\/ num buckets per partition\n\n size_t num_buckets_init_scale_ = 10; \/\/ set number of buckets per partition based on num_partitions\n \/\/ multiplied with some scaling factor, must be equal to or greater than 1\n\n size_t num_buckets_resize_scale_ = 2; \/\/ resize scale on max_num_items_per_bucket_\n\n size_t bucket_block_size_ = 32; \/\/ size of bucket blocks\n\n size_t max_num_items_per_bucket_ = 256; \/\/ max num of items per bucket before resize\n\n std::vector<size_t> items_per_partition_; \/\/ num items per partition\n\n size_t table_size_ = 0; \/\/ total number of items\n\n size_t max_num_items_table_ = 1048576; \/\/ max num of items before spilling of largest partition\n\n KeyExtractor key_extractor_;\n\n ReduceFunction reduce_function_;\n\n std::vector<EmitterFunction> emit_;\n std::vector<int> emit_stats_;\n\n std::vector<bucket_block*> vector_;\n};\n\n} \/\/ namespace core\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_CORE_REDUCE_PRE_TABLE_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>#include \"logger.h\"\n#include \"functions.h\"\n\n#ifdef QT_DEBUG\n\t#include <QDebug>\n#endif\n\n\nvoid Logger::setLogFile(const QString &path)\n{\n\tm_logFile.setFileName(path);\n\tm_logFile.open(QFile::Append | QFile::Text | QFile::Truncate);\n}\n\nvoid Logger::setLogLevel(LogLevel level)\n{\n\tm_level = level;\n}\n\n\nvoid Logger::messageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message)\n{\n\tstatic QMap<QtMsgType, LogLevel> messageTypes\n\t{\n\t\t{ QtMsgType::QtDebugMsg, Logger::Debug },\n\t\t{ QtMsgType::QtInfoMsg, Logger::Info },\n\t\t{ QtMsgType::QtWarningMsg, Logger::Warning },\n\t\t{ QtMsgType::QtCriticalMsg, Logger::Error },\n\t\t{ QtMsgType::QtFatalMsg, Logger::Error },\n\t\t{ QtMsgType::QtSystemMsg, Logger::Error },\n\t};\n\n\tQString label = \"[Qt]\";\n\tQString category(context.category);\n\tif (!category.isEmpty())\n\t\tlabel += \"[\" + category + \"]\";\n\t#if defined QT_MESSAGELOGCONTEXT && defined QT_DEBUG && 0\n\t\tlabel += QString(\"[%1(%2)::%3]\").arg(context.file).arg(context.line).arg(context.function);\n\t#endif\n\n\tLogger::getInstance().log(QString(\"%1 %2\").arg(label, message), messageTypes[type]);\n}\n\nvoid Logger::noMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message)\n{\n\tQ_UNUSED(type);\n\tQ_UNUSED(context);\n\tQ_UNUSED(message);\n}\n\nvoid Logger::setupMessageOutput(bool log)\n{\n\tqInstallMessageHandler(log ? Logger::messageOutput : Logger::noMessageOutput);\n}\n\n\/**\n * Append text in the log in a new line.\n * @param\tl\tThe message to append.\n *\/\nvoid Logger::log(const QString &l, LogLevel level)\n{\n\tif (level < m_level)\n\t\treturn;\n\n\tif (!m_logFile.isOpen())\n\t\tsetLogFile(savePath(\"main.log\", false, true));\n\n\tstatic const QStringList levels = QStringList() << \"Debug\" << \"Info\" << \"Warning\" << \"Error\";\n\tstatic const QStringList colors = QStringList() << \"#999\" << \"\" << \"orange\" << \"red\";\n\tQString levelStr = levels[level];\n\tQDateTime time = QDateTime::currentDateTime();\n\n\t\/\/ Write ASCII log to file\n\tm_logFile.write(QString(\"[\"+time.toString(\"hh:mm:ss.zzz\")+\"][\"+levelStr+\"] \"+stripTags(l)+\"\\n\").toUtf8());\n\tm_logFile.flush();\n\n\t\/\/ Emit colored HTML log\n\tQString levelColor = colors[level];\n\tQString msg = \"[\" + time.toString(\"hh:mm:ss.zzz\") + \"][\" + levelStr + \"] \" + l;\n\tif (!levelColor.isEmpty())\n\t\tmsg = QString(\"<span style='color:%1'>%2<\/span>\").arg(levelColor, msg);\n\temit newLog(msg);\n\n\t#ifdef QT_DEBUG\n\t\tqDebug() << time.toString(\"hh:mm:ss.zzz\") << levelStr << l;\n\t#endif\n}\n\nvoid Logger::logCommand(const QString &l)\n{\n\tif (!m_fCommandsLog.isOpen())\n\t{\n\t\tm_fCommandsLog.setFileName(savePath(\"commands.log\", false, true));\n\t\tm_fCommandsLog.open(QFile::Append | QFile::Text | QFile::Truncate);\n\t}\n\n\tm_fCommandsLog.write(QString(l+\"\\r\\n\").toUtf8());\n\tm_fCommandsLog.flush();\n}\n\nvoid Logger::logCommandSql(const QString &l)\n{\n\tif (!m_fCommandsSqlLog.isOpen())\n\t{\n\t\tm_fCommandsSqlLog.setFileName(savePath(\"commands.sql\", false, true));\n\t\tm_fCommandsSqlLog.open(QFile::Append | QFile::Text | QFile::Truncate);\n\t}\n\n\tm_fCommandsSqlLog.write(QString(l+\"\\r\\n\").toUtf8());\n\tm_fCommandsSqlLog.flush();\n}\n\n\/**\n * Append text in the log at the end of the current line.\n * @param\tl\tThe message to append.\n *\/\nvoid Logger::logUpdate(const QString &l)\n{\n\tQ_UNUSED(l);\n\n\t\/*QDateTime date = _log.keys().at(_log.count()-1);\n\tQString message = _log.value(date)+l;\n\t_log.insert(date, message);\n\t_mainwindow->logShow();\n\n\tqDebug() << l;*\/\n}\n\n\nvoid log(const QString &l, Logger::LogLevel level)\n{\n\tLOG(l, level);\n}\n<commit_msg>Fix build on Qt 5.5.0-<commit_after>#include \"logger.h\"\n#include \"functions.h\"\n\n#ifdef QT_DEBUG\n\t#include <QDebug>\n#endif\n\n\nvoid Logger::setLogFile(const QString &path)\n{\n\tm_logFile.setFileName(path);\n\tm_logFile.open(QFile::Append | QFile::Text | QFile::Truncate);\n}\n\nvoid Logger::setLogLevel(LogLevel level)\n{\n\tm_level = level;\n}\n\n\nvoid Logger::messageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message)\n{\n\tstatic QMap<QtMsgType, LogLevel> messageTypes\n\t{\n\t\t{ QtMsgType::QtDebugMsg, Logger::Debug },\n\t\t#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))\n\t\t\t{ QtMsgType::QtInfoMsg, Logger::Info },\n\t\t#endif\n\t\t{ QtMsgType::QtWarningMsg, Logger::Warning },\n\t\t{ QtMsgType::QtCriticalMsg, Logger::Error },\n\t\t{ QtMsgType::QtFatalMsg, Logger::Error },\n\t\t{ QtMsgType::QtSystemMsg, Logger::Error },\n\t};\n\n\tQString label = \"[Qt]\";\n\tQString category(context.category);\n\tif (!category.isEmpty())\n\t\tlabel += \"[\" + category + \"]\";\n\t#if defined QT_MESSAGELOGCONTEXT && defined QT_DEBUG && 0\n\t\tlabel += QString(\"[%1(%2)::%3]\").arg(context.file).arg(context.line).arg(context.function);\n\t#endif\n\n\tLogger::getInstance().log(QString(\"%1 %2\").arg(label, message), messageTypes[type]);\n}\n\nvoid Logger::noMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message)\n{\n\tQ_UNUSED(type);\n\tQ_UNUSED(context);\n\tQ_UNUSED(message);\n}\n\nvoid Logger::setupMessageOutput(bool log)\n{\n\tqInstallMessageHandler(log ? Logger::messageOutput : Logger::noMessageOutput);\n}\n\n\/**\n * Append text in the log in a new line.\n * @param\tl\tThe message to append.\n *\/\nvoid Logger::log(const QString &l, LogLevel level)\n{\n\tif (level < m_level)\n\t\treturn;\n\n\tif (!m_logFile.isOpen())\n\t\tsetLogFile(savePath(\"main.log\", false, true));\n\n\tstatic const QStringList levels = QStringList() << \"Debug\" << \"Info\" << \"Warning\" << \"Error\";\n\tstatic const QStringList colors = QStringList() << \"#999\" << \"\" << \"orange\" << \"red\";\n\tQString levelStr = levels[level];\n\tQDateTime time = QDateTime::currentDateTime();\n\n\t\/\/ Write ASCII log to file\n\tm_logFile.write(QString(\"[\"+time.toString(\"hh:mm:ss.zzz\")+\"][\"+levelStr+\"] \"+stripTags(l)+\"\\n\").toUtf8());\n\tm_logFile.flush();\n\n\t\/\/ Emit colored HTML log\n\tQString levelColor = colors[level];\n\tQString msg = \"[\" + time.toString(\"hh:mm:ss.zzz\") + \"][\" + levelStr + \"] \" + l;\n\tif (!levelColor.isEmpty())\n\t\tmsg = QString(\"<span style='color:%1'>%2<\/span>\").arg(levelColor, msg);\n\temit newLog(msg);\n\n\t#ifdef QT_DEBUG\n\t\tqDebug() << time.toString(\"hh:mm:ss.zzz\") << levelStr << l;\n\t#endif\n}\n\nvoid Logger::logCommand(const QString &l)\n{\n\tif (!m_fCommandsLog.isOpen())\n\t{\n\t\tm_fCommandsLog.setFileName(savePath(\"commands.log\", false, true));\n\t\tm_fCommandsLog.open(QFile::Append | QFile::Text | QFile::Truncate);\n\t}\n\n\tm_fCommandsLog.write(QString(l+\"\\r\\n\").toUtf8());\n\tm_fCommandsLog.flush();\n}\n\nvoid Logger::logCommandSql(const QString &l)\n{\n\tif (!m_fCommandsSqlLog.isOpen())\n\t{\n\t\tm_fCommandsSqlLog.setFileName(savePath(\"commands.sql\", false, true));\n\t\tm_fCommandsSqlLog.open(QFile::Append | QFile::Text | QFile::Truncate);\n\t}\n\n\tm_fCommandsSqlLog.write(QString(l+\"\\r\\n\").toUtf8());\n\tm_fCommandsSqlLog.flush();\n}\n\n\/**\n * Append text in the log at the end of the current line.\n * @param\tl\tThe message to append.\n *\/\nvoid Logger::logUpdate(const QString &l)\n{\n\tQ_UNUSED(l);\n\n\t\/*QDateTime date = _log.keys().at(_log.count()-1);\n\tQString message = _log.value(date)+l;\n\t_log.insert(date, message);\n\t_mainwindow->logShow();\n\n\tqDebug() << l;*\/\n}\n\n\nvoid log(const QString &l, Logger::LogLevel level)\n{\n\tLOG(l, level);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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#include \"modules\/canbus\/common\/canbus_gflags.h\"\n\n\/\/ System gflags\nDEFINE_string(canbus_node_name, \"chassis\", \"The chassis module name in proto\");\nDEFINE_string(canbus_module_name, \"canbus\", \"Module name\");\n\nDEFINE_string(canbus_adapter_config_filename,\n \"modules\/canbus\/conf\/adapter.conf\", \"The adapter config file\");\n\n\/\/ data file\nDEFINE_string(canbus_conf_file, \"modules\/canbus\/conf\/canbus_conf.pb.txt\",\n \"Default canbus conf file\");\n\n\/\/ Canbus gflags\nDEFINE_double(chassis_freq, 100, \"Chassis feedback timer frequency.\");\nDEFINE_int64(min_cmd_interval, 5, \"Minimum control command interval in us.\");\n\n\/\/ chassis_detail message publish\nDEFINE_bool(enable_chassis_detail_pub, false, \"Chassis Detail message publish\");\n\n\/\/ canbus test files\nDEFINE_string(canbus_test_file, \"modules\/canbus\/testdata\/canbus_test.pb.txt\",\n \"canbus tester input test file, in ControlCommand pb format.\");\n<commit_msg>Update canbus_gflags.cc<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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#include \"modules\/canbus\/common\/canbus_gflags.h\"\n\n\/\/ System gflags\nDEFINE_string(canbus_node_name, \"chassis\", \"The chassis module name in proto\");\nDEFINE_string(canbus_module_name, \"canbus\", \"Module name\");\n\nDEFINE_string(canbus_adapter_config_filename,\n \"modules\/canbus\/conf\/adapter.conf\", \"The adapter config file\");\n\n\/\/ data file\nDEFINE_string(canbus_conf_file, \"modules\/canbus\/conf\/canbus_conf.pb.txt\",\n \"Default canbus conf file\");\n\n\/\/ Canbus gflags\nDEFINE_double(chassis_freq, 100, \"Chassis feedback timer frequency.\");\nDEFINE_int64(min_cmd_interval, 5, \"Minimum control command interval in ms.\");\n\n\/\/ chassis_detail message publish\nDEFINE_bool(enable_chassis_detail_pub, false, \"Chassis Detail message publish\");\n\n\/\/ canbus test files\nDEFINE_string(canbus_test_file, \"modules\/canbus\/testdata\/canbus_test.pb.txt\",\n \"canbus tester input test file, in ControlCommand pb format.\");\n<|endoftext|>"} {"text":"<commit_before><commit_msg>build<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ ------------------------------------------------------------------------------------------------\n#include \"Library\/Chrono\/Date.hpp\"\n#include \"Library\/Chrono\/Date.hpp\"\n#include \"Library\/Chrono\/Datetime.hpp\"\n#include \"Base\/Shared.hpp\"\n\n\/\/ ------------------------------------------------------------------------------------------------\nnamespace SqMod {\n\n\/\/ ------------------------------------------------------------------------------------------------\nSQChar Date::Delimiter = '-';\n\n\/\/ ------------------------------------------------------------------------------------------------\nconst Uint8 Date::MonthLengths[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n\n\/\/ ------------------------------------------------------------------------------------------------\nSQInteger Date::Typename(HSQUIRRELVM vm)\n{\n static SQChar name[] = _SC(\"SqChronoDate\");\n sq_pushstring(vm, name, sizeof(name));\n return 1;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::operator + (const Date & o) const\n{\n return Date(o);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::operator - (const Date & o) const\n{\n return Date(o);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::operator * (const Date & o) const\n{\n return Date(o);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::operator \/ (const Date & o) const\n{\n return Date(o);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::Set(Uint16 year, Uint8 month, Uint8 day)\n{\n if (!ValidDate(year, month, day))\n {\n STHROWF(\"Invalid date: %04u%c%02u%c%02u%c%u\"\n , m_Delimiter, m_Year\n , m_Delimiter, m_Month\n , m_Delimiter, m_Day\n );\n }\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nCSStr Date::GetStr() const\n{\n return ToString();\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::SetStr(CSStr str)\n{\n \/\/ The format specifications that will be used to scan the string\n static SQChar fs[] = _SC(\" %u , %u , %u,\");\n \/\/ Is the specified string empty?\n if (!str || *str == '\\0')\n {\n \/\/ Clear the values\n m_Year = 0;\n m_Month = 0;\n m_Day = 0;\n \/\/ We're done here\n return;\n }\n \/\/ Assign the specified delimiter\n fs[4] = m_Delimiter;\n fs[9] = m_Delimiter;\n \/\/ The sscanf function requires at least 32 bit integers\n Uint32 year = 0, month = 0, day = 0;\n \/\/ Attempt to extract the component values from the specified string\n sscanf(str, fs, &year, &month, &day);\n \/\/ Clamp the extracted values to the boundaries of associated type and assign them\n Set(ClampL< Uint32, Uint8 >(year),\n ClampL< Uint32, Uint8 >(month),\n ClampL< Uint32, Uint8 >(day)\n );\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nInt32 Date::Compare(const Date & o) const\n{\n if (m_Year < o.m_Year)\n {\n return -1;\n }\n else if (m_Year > o.m_Year)\n {\n return 1;\n }\n else if (m_Month < o.m_Month)\n {\n return -1;\n }\n else if (m_Month > o.m_Month)\n {\n return 1;\n }\n else if (m_Day < o.m_Day)\n {\n return -1;\n }\n else if (m_Day > o.m_Day)\n {\n return 1;\n }\n \/\/ They're equal\n return 0;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nCSStr Date::ToString() const\n{\n return ToStrF(\"%04u%c%02u%c%02u%c%u\"\n , m_Delimiter, m_Year\n , m_Delimiter, m_Month\n , m_Delimiter, m_Day\n );\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::SetYear(Uint16 year)\n{\n\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::SetMonth(Uint8 month)\n{\n\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::SetDay(Uint8 day)\n{\n\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::AddYears(Int32 years)\n{\n return Date(*this);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::AddMonths(Int32 months)\n{\n return Date(*this);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::AddDays(Int32 days)\n{\n return Date(*this);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nbool Date::ValidDate(Uint16 year, Uint8 month, Uint8 day)\n{\n \/\/ Is this a valid date?\n if (year == 0 || month == 0 || day == 0)\n {\n return false;\n }\n \/\/ Is the month within range?\n else if (month > 12)\n {\n return false;\n }\n \/\/ Return whether the day inside the month\n return day <= DaysInMonth(year, month);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nUint8 Date::DaysInMonth(Uint16 year, Uint8 month)\n{\n \/\/ Is the specified month within range?\n if (month > 12)\n {\n STHROWF(\"Month value is out of range: %u > 12\", month);\n }\n \/\/ Obtain the days in this month\n Uint8 days = MonthLengths[month - 1];\n \/\/ Should we account for January?\n if (month == 2 && IsLeapYear(year))\n {\n ++days;\n }\n \/\/ Return the resulted days\n return days;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nUint16 Date::DayOfYear(Uint16 year, Uint8 month, Uint8 day)\n{\n \/\/ Start with 0 days\n Uint16 doy = 0;\n \/\/ Cumulate the days in months\n for (Uint8 m = 1; m < month; ++month)\n {\n doy += DaysInMonth(year, m);\n }\n \/\/ Add the specified days\n doy += day;\n \/\/ Return the result\n return doy;\n}\n\n\/\/ ================================================================================================\nvoid Register_ChronoDate(HSQUIRRELVM vm, Table & \/*cns*\/)\n{\n RootTable(vm).Bind(_SC(\"SqDate\"), Class< Date >(vm, _SC(\"SqChronoDate\"))\n \/\/ Constructors\n .Ctor()\n .Ctor< Uint16 >()\n .Ctor< Uint16, Uint8 >()\n .Ctor< Uint16, Uint8, Uint8 >()\n \/\/ Static Properties\n .SetStaticValue(_SC(\"GlobalDelimiter\"), &Date::Delimiter)\n \/\/ Core Metamethods\n .Func(_SC(\"_tostring\"), &Date::ToString)\n .SquirrelFunc(_SC(\"_typename\"), &Date::Typename)\n .Func(_SC(\"_cmp\"), &Date::Cmp)\n \/\/ Metamethods\n .Func< Date (Date::*)(const Date &) const >(_SC(\"_add\"), &Date::operator +)\n .Func< Date (Date::*)(const Date &) const >(_SC(\"_sub\"), &Date::operator -)\n .Func< Date (Date::*)(const Date &) const >(_SC(\"_mul\"), &Date::operator *)\n .Func< Date (Date::*)(const Date &) const >(_SC(\"_div\"), &Date::operator \/)\n \/\/ Properties\n .Prop(_SC(\"Year\"), &Date::GetYear, &Date::SetYear)\n .Prop(_SC(\"Month\"), &Date::GetMonth, &Date::SetMonth)\n .Prop(_SC(\"Day\"), &Date::GetDay, &Date::SetDay)\n .Prop(_SC(\"Str\"), &Date::GetStr, &Date::SetStr)\n .Prop(_SC(\"Delimiter\"), &Date::GetDelimiter, &Date::SetDelimiter)\n .Prop(_SC(\"LeapYear\"), &Date::IsThisLeapYear)\n .Prop(_SC(\"YearDays\"), &Date::GetYearDays)\n .Prop(_SC(\"MonthDays\"), &Date::GetMonthDays)\n \/\/ Member Methods\n .Func(_SC(\"AddYears\"), &Date::AddYears)\n .Func(_SC(\"AddMonths\"), &Date::AddMonths)\n .Func(_SC(\"AddDays\"), &Date::AddDays)\n \/\/ Overloaded Methods\n .Overload< void (Date::*)(Uint16) >(_SC(\"Set\"), &Date::Set)\n .Overload< void (Date::*)(Uint16, Uint8) >(_SC(\"Set\"), &Date::Set)\n .Overload< void (Date::*)(Uint16, Uint8, Uint8) >(_SC(\"Set\"), &Date::Set)\n );\n}\n\n} \/\/ Namespace:: SqMod\n<commit_msg>Avoid GCC error \"array subscript is above array bounds\" which probably considers that the unsigned char could underflow and access an element out of the months range.<commit_after>\/\/ ------------------------------------------------------------------------------------------------\n#include \"Library\/Chrono\/Date.hpp\"\n#include \"Library\/Chrono\/Date.hpp\"\n#include \"Library\/Chrono\/Datetime.hpp\"\n#include \"Base\/Shared.hpp\"\n\n\/\/ ------------------------------------------------------------------------------------------------\nnamespace SqMod {\n\n\/\/ ------------------------------------------------------------------------------------------------\nSQChar Date::Delimiter = '-';\n\n\/\/ ------------------------------------------------------------------------------------------------\nconst Uint8 Date::MonthLengths[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n\n\/\/ ------------------------------------------------------------------------------------------------\nSQInteger Date::Typename(HSQUIRRELVM vm)\n{\n static SQChar name[] = _SC(\"SqChronoDate\");\n sq_pushstring(vm, name, sizeof(name));\n return 1;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::operator + (const Date & o) const\n{\n return Date(o);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::operator - (const Date & o) const\n{\n return Date(o);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::operator * (const Date & o) const\n{\n return Date(o);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::operator \/ (const Date & o) const\n{\n return Date(o);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::Set(Uint16 year, Uint8 month, Uint8 day)\n{\n if (!ValidDate(year, month, day))\n {\n STHROWF(\"Invalid date: %04u%c%02u%c%02u%c%u\"\n , m_Delimiter, m_Year\n , m_Delimiter, m_Month\n , m_Delimiter, m_Day\n );\n }\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nCSStr Date::GetStr() const\n{\n return ToString();\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::SetStr(CSStr str)\n{\n \/\/ The format specifications that will be used to scan the string\n static SQChar fs[] = _SC(\" %u , %u , %u,\");\n \/\/ Is the specified string empty?\n if (!str || *str == '\\0')\n {\n \/\/ Clear the values\n m_Year = 0;\n m_Month = 0;\n m_Day = 0;\n \/\/ We're done here\n return;\n }\n \/\/ Assign the specified delimiter\n fs[4] = m_Delimiter;\n fs[9] = m_Delimiter;\n \/\/ The sscanf function requires at least 32 bit integers\n Uint32 year = 0, month = 0, day = 0;\n \/\/ Attempt to extract the component values from the specified string\n sscanf(str, fs, &year, &month, &day);\n \/\/ Clamp the extracted values to the boundaries of associated type and assign them\n Set(ClampL< Uint32, Uint8 >(year),\n ClampL< Uint32, Uint8 >(month),\n ClampL< Uint32, Uint8 >(day)\n );\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nInt32 Date::Compare(const Date & o) const\n{\n if (m_Year < o.m_Year)\n {\n return -1;\n }\n else if (m_Year > o.m_Year)\n {\n return 1;\n }\n else if (m_Month < o.m_Month)\n {\n return -1;\n }\n else if (m_Month > o.m_Month)\n {\n return 1;\n }\n else if (m_Day < o.m_Day)\n {\n return -1;\n }\n else if (m_Day > o.m_Day)\n {\n return 1;\n }\n \/\/ They're equal\n return 0;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nCSStr Date::ToString() const\n{\n return ToStrF(\"%04u%c%02u%c%02u%c%u\"\n , m_Delimiter, m_Year\n , m_Delimiter, m_Month\n , m_Delimiter, m_Day\n );\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::SetYear(Uint16 year)\n{\n\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::SetMonth(Uint8 month)\n{\n\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nvoid Date::SetDay(Uint8 day)\n{\n\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::AddYears(Int32 years)\n{\n return Date(*this);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::AddMonths(Int32 months)\n{\n return Date(*this);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nDate Date::AddDays(Int32 days)\n{\n return Date(*this);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nbool Date::ValidDate(Uint16 year, Uint8 month, Uint8 day)\n{\n \/\/ Is this a valid date?\n if (year == 0 || month == 0 || day == 0)\n {\n return false;\n }\n \/\/ Is the month within range?\n else if (month > 12)\n {\n return false;\n }\n \/\/ Return whether the day inside the month\n return day <= DaysInMonth(year, month);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nUint8 Date::DaysInMonth(Uint16 year, Uint8 month)\n{\n \/\/ Is the specified month within range?\n if (month > 12)\n {\n STHROWF(\"Month value is out of range: %u > 12\", month);\n }\n \/\/ Obtain the days in this month\n Uint8 days = *(MonthLengths + month);\n \/\/ Should we account for January?\n if (month == 2 && IsLeapYear(year))\n {\n ++days;\n }\n \/\/ Return the resulted days\n return days;\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\nUint16 Date::DayOfYear(Uint16 year, Uint8 month, Uint8 day)\n{\n \/\/ Start with 0 days\n Uint16 doy = 0;\n \/\/ Cumulate the days in months\n for (Uint8 m = 1; m < month; ++month)\n {\n doy += DaysInMonth(year, m);\n }\n \/\/ Add the specified days\n doy += day;\n \/\/ Return the result\n return doy;\n}\n\n\/\/ ================================================================================================\nvoid Register_ChronoDate(HSQUIRRELVM vm, Table & \/*cns*\/)\n{\n RootTable(vm).Bind(_SC(\"SqDate\"), Class< Date >(vm, _SC(\"SqChronoDate\"))\n \/\/ Constructors\n .Ctor()\n .Ctor< Uint16 >()\n .Ctor< Uint16, Uint8 >()\n .Ctor< Uint16, Uint8, Uint8 >()\n \/\/ Static Properties\n .SetStaticValue(_SC(\"GlobalDelimiter\"), &Date::Delimiter)\n \/\/ Core Metamethods\n .Func(_SC(\"_tostring\"), &Date::ToString)\n .SquirrelFunc(_SC(\"_typename\"), &Date::Typename)\n .Func(_SC(\"_cmp\"), &Date::Cmp)\n \/\/ Metamethods\n .Func< Date (Date::*)(const Date &) const >(_SC(\"_add\"), &Date::operator +)\n .Func< Date (Date::*)(const Date &) const >(_SC(\"_sub\"), &Date::operator -)\n .Func< Date (Date::*)(const Date &) const >(_SC(\"_mul\"), &Date::operator *)\n .Func< Date (Date::*)(const Date &) const >(_SC(\"_div\"), &Date::operator \/)\n \/\/ Properties\n .Prop(_SC(\"Year\"), &Date::GetYear, &Date::SetYear)\n .Prop(_SC(\"Month\"), &Date::GetMonth, &Date::SetMonth)\n .Prop(_SC(\"Day\"), &Date::GetDay, &Date::SetDay)\n .Prop(_SC(\"Str\"), &Date::GetStr, &Date::SetStr)\n .Prop(_SC(\"Delimiter\"), &Date::GetDelimiter, &Date::SetDelimiter)\n .Prop(_SC(\"LeapYear\"), &Date::IsThisLeapYear)\n .Prop(_SC(\"YearDays\"), &Date::GetYearDays)\n .Prop(_SC(\"MonthDays\"), &Date::GetMonthDays)\n \/\/ Member Methods\n .Func(_SC(\"AddYears\"), &Date::AddYears)\n .Func(_SC(\"AddMonths\"), &Date::AddMonths)\n .Func(_SC(\"AddDays\"), &Date::AddDays)\n \/\/ Overloaded Methods\n .Overload< void (Date::*)(Uint16) >(_SC(\"Set\"), &Date::Set)\n .Overload< void (Date::*)(Uint16, Uint8) >(_SC(\"Set\"), &Date::Set)\n .Overload< void (Date::*)(Uint16, Uint8, Uint8) >(_SC(\"Set\"), &Date::Set)\n );\n}\n\n} \/\/ Namespace:: SqMod\n<|endoftext|>"} {"text":"<commit_before>\/*\n +----------------------------------------------------------------------+\n | PHP-OpenCV |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.apache.org\/licenses\/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | hihozhou@gmail.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: HaiHao Zhou <hihozhou@gmail.com> |\n +----------------------------------------------------------------------+\n *\/\n\n\n#include \"..\/..\/php_opencv.h\"\n#include \"opencv_highgui.h\"\n#include \"core\/opencv_mat.h\"\n#include \"..\/..\/opencv_exception.h\"\n\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n\/**\n * \/\/todo only cli can call this function\n * CV\\imshow\n * @param execute_data\n * @param return_value\n *\/\nPHP_FUNCTION(opencv_imshow){\n char *window_name;\n long window_name_len;\n zval *object;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"sO\", &window_name, &window_name_len, &object,opencv_mat_ce) == FAILURE) {\n RETURN_NULL();\n }\n opencv_mat_object *obj = Z_PHP_MAT_OBJ_P(object);\n\/\/ namedWindow(window_name);\n imshow(window_name,*(obj->mat));\n RETURN_NULL();\n}\n\n\n\/**\n * CV\\waitKey\n * @param execute_data\n * @param return_value\n *\/\nPHP_FUNCTION(opencv_wait_key){\n long delay = 0;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"|l\", &delay) == FAILURE) {\n RETURN_NULL();\n }\n int key = waitKey((int)delay);\/\/millisecond\n RETURN_LONG(key);\n}\n\n\/**\n * php namedWindow flags to c++ namedWindow flags\n * @param flags\n * @return\n *\/\nint php_window_flags_to_c_flags(int flags){\n if(flags == 1){\n return WINDOW_NORMAL;\n }else if(flags==2){\n return WINDOW_AUTOSIZE;\n }else if(flags==3){\n return WINDOW_OPENGL;\n }else if(flags==4){\n return WINDOW_FULLSCREEN;\n }else if(flags==5){\n return WINDOW_FREERATIO;\n }else if(flags==6){\n return WINDOW_GUI_EXPANDED;\n }else if(flags==7){\n return WINDOW_GUI_NORMAL;\n }\n return WINDOW_AUTOSIZE;\n}\n\n\/**\n * CV\\namedWindow\n * @param window_name\n * @param flags\n *\/\nPHP_FUNCTION(opencv_named_window){\n char *window_name;\n long window_name_len;\n long flags = 2;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s|l\", &window_name, &window_name_len, &flags) == FAILURE) {\n RETURN_NULL();\n }\n namedWindow(window_name,php_window_flags_to_c_flags((int)flags));\n RETURN_NULL();\n}\n\nstruct opencv_fcall_info_struct{\n zend_fcall_info *fci;\n zend_fcall_info_cache *fci_cache;\n};\n\nvoid opencv_create_trackbar_callback(int pos, void* userdata){\n opencv_fcall_info_struct *fci_s=(opencv_fcall_info_struct*)userdata;\n\n zval retval;\n zval args[1];\n ZVAL_LONG(&args[0], (long)pos);\n fci_s->fci->param_count = 1;\n fci_s->fci->params = args;\n fci_s->fci->retval = &retval;\n\n \/\/todo zend_call_function: Assertion `((zend_object*)func->op_array.prototype)->gc.u.v.type == 8' failed.\n zend_call_function(fci_s->fci, fci_s->fci_cache);\n zval_ptr_dtor(&args[0]);\n}\n\n\n\/**\n * \/\/todo c++ createTrackbar 跳转事件调用php传入的闭包:1php全局变量,2c++闭包\n * CV\\createTrackbar\n * @param execute_data\n * @param return_value\n *\/\nPHP_FUNCTION(opencv_create_trackbar){\n char *trackbarname, *winname;\n long value, count, trackbarname_len,winname_len;\n zval retval;\n\n zend_fcall_info *fci = new zend_fcall_info;\n zend_fcall_info_cache *fci_cache = new zend_fcall_info_cache;\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"ssll|f\",\n &trackbarname, &trackbarname_len,\n &winname,&winname_len,\n &value,&count,\n fci, fci_cache) == FAILURE) {\n return;\n }\n\n int *trackbar_value_ptr = new int(value);\n\n opencv_fcall_info_struct *fci_s = new opencv_fcall_info_struct;\n fci_s->fci=fci;\n fci_s->fci_cache = fci_cache;\n createTrackbar(trackbarname, winname, trackbar_value_ptr, (int)count,opencv_create_trackbar_callback,fci_s);\n opencv_create_trackbar_callback(*trackbar_value_ptr,fci_s);\n\/\/ createTrackbar(trackbarname, winname, trackbar_value_ptr, (int)count);\n\/\/ zend_call_function(fci_s->fci, fci_s->fci_cache);\n RETURN_NULL();\n\n\/\/ if (zend_call_function(fci, fci_cache) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {\n\/\/ zval_ptr_dtor(&args[0]);\n\/\/ RETURN_ZVAL(&retval,1,1);\n\/\/ ZVAL_COPY_VALUE(return_value, &retval);\n\/\/ } else {\n\/\/ RETURN_FALSE;\n\/\/ }\n\n}\n\nPHP_FUNCTION(opencv_destroy_window){\n char *winname;\n long winname_len;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &winname,&winname_len) == FAILURE) {\n return;\n }\n\n try{\n destroyWindow(winname);\n }catch (Exception e){\n opencv_throw_exception(e.what());\n }\n\n RETURN_NULL();\n\n\n}\n\n\n\nvoid opencv_highgui_init(int module_number)\n{\n \/**\n * ! ! Flags for CV\\namedWindow\n *\/\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_NORMAL\", 1, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_AUTOSIZE\", 2, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_OPENGL\", 3, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_FULLSCREEN\", 4, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_FREERATIO\", 5, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_GUI_EXPANDED\", 6, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_GUI_NORMAL\", 7, CONST_CS | CONST_PERSISTENT);\n}<commit_msg>CV\\createTrackbar callback<commit_after>\/*\n +----------------------------------------------------------------------+\n | PHP-OpenCV |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.apache.org\/licenses\/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | hihozhou@gmail.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: HaiHao Zhou <hihozhou@gmail.com> |\n +----------------------------------------------------------------------+\n *\/\n\n\n#include \"..\/..\/php_opencv.h\"\n#include \"opencv_highgui.h\"\n#include \"core\/opencv_mat.h\"\n#include \"..\/..\/opencv_exception.h\"\n\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n\/**\n * \/\/todo only cli can call this function\n * CV\\imshow\n * @param execute_data\n * @param return_value\n *\/\nPHP_FUNCTION(opencv_imshow){\n char *window_name;\n long window_name_len;\n zval *object;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"sO\", &window_name, &window_name_len, &object,opencv_mat_ce) == FAILURE) {\n RETURN_NULL();\n }\n opencv_mat_object *obj = Z_PHP_MAT_OBJ_P(object);\n\/\/ namedWindow(window_name);\n imshow(window_name,*(obj->mat));\n RETURN_NULL();\n}\n\n\n\/**\n * CV\\waitKey\n * @param execute_data\n * @param return_value\n *\/\nPHP_FUNCTION(opencv_wait_key){\n long delay = 0;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"|l\", &delay) == FAILURE) {\n RETURN_NULL();\n }\n int key = waitKey((int)delay);\/\/millisecond\n RETURN_LONG(key);\n}\n\n\/**\n * php namedWindow flags to c++ namedWindow flags\n * @param flags\n * @return\n *\/\nint php_window_flags_to_c_flags(int flags){\n if(flags == 1){\n return WINDOW_NORMAL;\n }else if(flags==2){\n return WINDOW_AUTOSIZE;\n }else if(flags==3){\n return WINDOW_OPENGL;\n }else if(flags==4){\n return WINDOW_FULLSCREEN;\n }else if(flags==5){\n return WINDOW_FREERATIO;\n }else if(flags==6){\n return WINDOW_GUI_EXPANDED;\n }else if(flags==7){\n return WINDOW_GUI_NORMAL;\n }\n return WINDOW_AUTOSIZE;\n}\n\n\/**\n * CV\\namedWindow\n * @param window_name\n * @param flags\n *\/\nPHP_FUNCTION(opencv_named_window){\n char *window_name;\n long window_name_len;\n long flags = 2;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s|l\", &window_name, &window_name_len, &flags) == FAILURE) {\n RETURN_NULL();\n }\n namedWindow(window_name,php_window_flags_to_c_flags((int)flags));\n RETURN_NULL();\n}\n\nstruct opencv_fcall_info_cb{\n zend_fcall_info *fci;\n zend_fcall_info_cache *fci_cache;\n};\n\n\nopencv_fcall_info_cb * opencv_fcall_info_cb_create(zend_fcall_info *fci_ptr, zend_fcall_info_cache *fci_cache_ptr) {\n opencv_fcall_info_cb *cb = new opencv_fcall_info_cb;\n cb->fci = new zend_fcall_info;\n cb->fci_cache = new zend_fcall_info_cache;\n\n memcpy(cb->fci, fci_ptr, sizeof(zend_fcall_info));\n memcpy(cb->fci_cache, fci_cache_ptr, sizeof(zend_fcall_info_cache));\n Z_TRY_ADDREF(cb->fci->function_name);\n cb->fci->param_count = 0;\n cb->fci->no_separation = 1;\n cb->fci->retval = NULL;\n\n return cb;\n}\n\nvoid opencv_create_trackbar_callback(int pos, void* userdata){\n opencv_fcall_info_cb *fci_s=(opencv_fcall_info_cb*)userdata;\n\n zval retval;\n zval args[1];\n ZVAL_LONG(&args[0], (long)pos);\/\/将滑动条滑动的值传入到闭包参数中\n fci_s->fci->param_count = 1;\n fci_s->fci->params = args;\n fci_s->fci->retval = &retval;\n\n zend_call_function(fci_s->fci, fci_s->fci_cache);\n zval_ptr_dtor(&args[0]);\n}\n\n\n\n\/**\n * todo Total 1 memory leaks detected\n * CV\\createTrackbar\n * @param execute_data\n * @param return_value\n *\/\nPHP_FUNCTION(opencv_create_trackbar){\n char *trackbarname, *winname;\n long value, count, trackbarname_len,winname_len;\n zval retval;\n\n zend_fcall_info fci;\n zend_fcall_info_cache fci_cache;\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"ssll|f\",\n &trackbarname, &trackbarname_len,\n &winname,&winname_len,\n &value,&count,\n &fci, &fci_cache) == FAILURE) {\n return;\n }\n\n int *trackbar_value_ptr = new int(value);\n\n opencv_fcall_info_cb *cb = opencv_fcall_info_cb_create(&fci, &fci_cache);\n createTrackbar(trackbarname, winname, trackbar_value_ptr, (int)count,opencv_create_trackbar_callback,cb);\n RETURN_NULL();\n}\n\nPHP_FUNCTION(opencv_destroy_window){\n char *winname;\n long winname_len;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &winname,&winname_len) == FAILURE) {\n return;\n }\n\n try{\n destroyWindow(winname);\n }catch (Exception e){\n opencv_throw_exception(e.what());\n }\n\n RETURN_NULL();\n\n\n}\n\n\n\nvoid opencv_highgui_init(int module_number)\n{\n \/**\n * ! ! Flags for CV\\namedWindow\n *\/\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_NORMAL\", 1, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_AUTOSIZE\", 2, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_OPENGL\", 3, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_FULLSCREEN\", 4, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_FREERATIO\", 5, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_GUI_EXPANDED\", 6, CONST_CS | CONST_PERSISTENT);\n REGISTER_NS_LONG_CONSTANT(OPENCV_NS, \"WINDOW_GUI_NORMAL\", 7, CONST_CS | CONST_PERSISTENT);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n* SixTrack Wrapper for Pythia8\n* V.K. Berglyd Olsen, BE-ABP-HSS\n* Created: 2018-07-30\n* Updated: 2019-07-17\n*\/\n\n#include \"pythia_wrapper.h\"\n\nusing namespace Pythia8;\n\nextern \"C\" {\n\nbool pythiaWrapper_init() {\n if(!pythia.init()) return false;\n pythia.settings.writeFile(\"pythia_settings.dat\", true);\n std::cout << \"PYTHIA> Done\" << std::endl;\n return true;\n}\n\nbool pythiaWrapper_defaults() {\n std::cout << \"PYTHIA> Setting defaults\" << std::endl;\n pythia.settings.flag(\"Init:showChangedSettings\", true);\n pythia.settings.flag(\"Init:showChangedParticleData\", false);\n pythia.settings.flag(\"SigmaTotal:mode\", 3);\n pythia.settings.flag(\"SigmaDiffractive:mode\", 3);\n return true;\n}\n\nvoid pythiaWrapper_setProcess(bool sEL, bool sSD, bool sDD, bool sCD, bool sND) {\n std::cout << \"PYTHIA> Setting processes\" << std::endl;\n pythia.settings.flag(\"SoftQCD:elastic\", sEL);\n pythia.settings.flag(\"SoftQCD:singleDiffractive\", sSD);\n pythia.settings.flag(\"SoftQCD:doubleDiffractive\", sDD);\n pythia.settings.flag(\"SoftQCD:centralDiffractive\", sCD);\n pythia.settings.flag(\"SoftQCD:nonDiffractive\", sND);\n}\n\nvoid pythiaWrapper_setCoulomb(bool sCMB, double tAbsMin) {\n pythia.settings.flag(\"SigmaElastic:Coulomb\", sCMB);\n pythia.settings.parm(\"SigmaElastic:tAbsMin\", tAbsMin);\n}\n\nvoid pythiaWrapper_setSeed(int rndSeed) {\n std::cout << \"PYTHIA> Setting random seed\" << std::endl;\n pythia.settings.mode(\"Random:seed\", rndSeed);\n}\n\nvoid pythiaWrapper_setBeam(int frameType, int idA, int idB, double eA, double eB) {\n std::cout << \"PYTHIA> Setting beam parameters\" << std::endl;\n pythia.settings.mode(\"Beams:frameType\", frameType);\n pythia.settings.mode(\"Beams:idA\", idA);\n pythia.settings.mode(\"Beams:idB\", idB);\n pythia.settings.parm(\"Beams:eA\", eA);\n pythia.settings.parm(\"Beams:eB\", eB);\n if(frameType == 3) {\n pythia.settings.flag(\"Beams:allowVariableEnergy\", true);\n }\n}\n\nvoid pythiaWrapper_readFile(char* fileName) {\n std::cout << \"PYTHIA> Loading settings from external file\" << std::endl;\n pythia.readFile(std::string(fileName));\n}\n\nvoid pythiaWrapper_getInitial(double& sigTot, double& sigEl, double& m0) {\n \/\/ sigTot = pythia.info.sigmaGen(0);\n sigTot = pythia.parm(\"SigmaTotal:sigmaTot\");\n sigEl = pythia.parm(\"SigmaTotal:sigmaEl\");\n\n \/\/ Generate one test event, and extract the particle mass\n pythia.next();\n m0 = sqrt(pythia.event[1].p().m2Calc());\n}\n\n\/**\n * SoftQCD Events\n * ================\n * 101 : Non-Diffrcative\n * 102 : Elastic AB -> AB\n * 103 : Single Diffractive AB -> XB\n * 104 : Single Diffractive AB -> AX\n * 105 : Double Diffractive AB -> XX\n * 106 : Central Diffractive AB -> AXB\n *\/\n\nvoid pythiaWrapper_getEvent(bool& status, int& code, double& t, double& theta, double& dEE, double& dPP) {\n status = pythia.next();\n code = pythia.info.code();\n if(!status) {\n code = 0;\n t = 0.0;\n theta = 0.0;\n dEE = 0.0;\n dPP = 0.0;\n return;\n }\n if(code == 101) {\n t = 0.0;\n theta = 0.0;\n dEE = 0.0;\n dPP = 0.0;\n }\n else if(code == 102) { \/\/ Elastic\n t = pythia.info.tHat();\n theta = pythia.event[3].theta();\n dEE = (pythia.event[3].e() - pythia.event[1].e()) \/ pythia.event[1].e();\n dPP = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) \/ pythia.event[1].pAbs();\n }\n else if(code == 104) { \/\/ Single Diffractive AB->AX\n t = pythia.info.tHat();\n theta = pythia.event[3].theta();\n dEE = (pythia.event[3].e() - pythia.event[1].e()) \/ pythia.event[1].e();\n dPP = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) \/ pythia.event[1].pAbs();\n }\n else if(code == 106) { \/\/ Central Diffractive AB->AXB\n t = (pythia.event[3].p() - pythia.event[1].p()).m2Calc();\n theta = pythia.event[3].theta();\n dEE = (pythia.event[3].e() - pythia.event[1].e()) \/ pythia.event[1].e();\n dPP = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) \/ pythia.event[1].pAbs();\n }\n else {\n t = 0.0;\n theta = 0.0;\n dEE = 0.0;\n dPP = 0.0;\n }\n}\n\nvoid pythiaWrapper_getEventPVector(bool& status, int& code, double& t, double& theta, double& dEE, double& dPP, double* vecPin, double* vecPout) {\n\n status = pythia.next(vecPin[0],vecPin[1],vecPin[2],vecPin[3],vecPin[4],vecPin[5]);\n code = pythia.info.code();\n\n t = 0.0;\n theta = 0.0;\n dEE = 0.0;\n dPP = 0.0;\n\n if(code == 102 || code == 104 || code == 106) {\n theta = pythia.event[3].theta();\n dEE = (pythia.event[3].e() - pythia.event[1].e()) \/ pythia.event[1].e();\n dPP = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) \/ pythia.event[1].pAbs();\n }\n if(code == 102 || code == 104) {\n t = pythia.info.tHat();\n }\n if(code == 106) {\n t = (pythia.event[3].p() - pythia.event[1].p()).m2Calc();\n }\n\n vecPin[0] = pythia.event[1].px();\n vecPin[1] = pythia.event[1].py();\n vecPin[2] = pythia.event[1].pz();\n vecPin[3] = pythia.event[2].px();\n vecPin[4] = pythia.event[2].py();\n vecPin[5] = pythia.event[2].pz();\n vecPout[0] = pythia.event[3].px();\n vecPout[1] = pythia.event[3].py();\n vecPout[2] = pythia.event[3].pz();\n vecPout[3] = pythia.event[4].px();\n vecPout[4] = pythia.event[4].py();\n vecPout[5] = pythia.event[4].pz();\n\n}\n\n}\n<commit_msg>No need to sqrt a square variable if we can get the un-squared one<commit_after>\/*\n* SixTrack Wrapper for Pythia8\n* V.K. Berglyd Olsen, BE-ABP-HSS\n* Created: 2018-07-30\n* Updated: 2019-07-17\n*\/\n\n#include \"pythia_wrapper.h\"\n\nusing namespace Pythia8;\n\nextern \"C\" {\n\nbool pythiaWrapper_init() {\n if(!pythia.init()) return false;\n pythia.settings.writeFile(\"pythia_settings.dat\", true);\n std::cout << \"PYTHIA> Done\" << std::endl;\n return true;\n}\n\nbool pythiaWrapper_defaults() {\n std::cout << \"PYTHIA> Setting defaults\" << std::endl;\n pythia.settings.flag(\"Init:showChangedSettings\", true);\n pythia.settings.flag(\"Init:showChangedParticleData\", false);\n pythia.settings.flag(\"SigmaTotal:mode\", 3);\n pythia.settings.flag(\"SigmaDiffractive:mode\", 3);\n return true;\n}\n\nvoid pythiaWrapper_setProcess(bool sEL, bool sSD, bool sDD, bool sCD, bool sND) {\n std::cout << \"PYTHIA> Setting processes\" << std::endl;\n pythia.settings.flag(\"SoftQCD:elastic\", sEL);\n pythia.settings.flag(\"SoftQCD:singleDiffractive\", sSD);\n pythia.settings.flag(\"SoftQCD:doubleDiffractive\", sDD);\n pythia.settings.flag(\"SoftQCD:centralDiffractive\", sCD);\n pythia.settings.flag(\"SoftQCD:nonDiffractive\", sND);\n}\n\nvoid pythiaWrapper_setCoulomb(bool sCMB, double tAbsMin) {\n pythia.settings.flag(\"SigmaElastic:Coulomb\", sCMB);\n pythia.settings.parm(\"SigmaElastic:tAbsMin\", tAbsMin);\n}\n\nvoid pythiaWrapper_setSeed(int rndSeed) {\n std::cout << \"PYTHIA> Setting random seed\" << std::endl;\n pythia.settings.mode(\"Random:seed\", rndSeed);\n}\n\nvoid pythiaWrapper_setBeam(int frameType, int idA, int idB, double eA, double eB) {\n std::cout << \"PYTHIA> Setting beam parameters\" << std::endl;\n pythia.settings.mode(\"Beams:frameType\", frameType);\n pythia.settings.mode(\"Beams:idA\", idA);\n pythia.settings.mode(\"Beams:idB\", idB);\n pythia.settings.parm(\"Beams:eA\", eA);\n pythia.settings.parm(\"Beams:eB\", eB);\n if(frameType == 3) {\n pythia.settings.flag(\"Beams:allowVariableEnergy\", true);\n }\n}\n\nvoid pythiaWrapper_readFile(char* fileName) {\n std::cout << \"PYTHIA> Loading settings from external file\" << std::endl;\n pythia.readFile(std::string(fileName));\n}\n\nvoid pythiaWrapper_getInitial(double& sigTot, double& sigEl, double& m0) {\n \/\/ sigTot = pythia.info.sigmaGen(0);\n sigTot = pythia.parm(\"SigmaTotal:sigmaTot\");\n sigEl = pythia.parm(\"SigmaTotal:sigmaEl\");\n\n \/\/ Generate one test event, and extract the particle mass\n pythia.next();\n m0 = pythia.event[1].p().mCalc();\n}\n\n\/**\n * SoftQCD Events\n * ================\n * 101 : Non-Diffrcative\n * 102 : Elastic AB -> AB\n * 103 : Single Diffractive AB -> XB\n * 104 : Single Diffractive AB -> AX\n * 105 : Double Diffractive AB -> XX\n * 106 : Central Diffractive AB -> AXB\n *\/\n\nvoid pythiaWrapper_getEvent(bool& status, int& code, double& t, double& theta, double& dEE, double& dPP) {\n status = pythia.next();\n code = pythia.info.code();\n if(!status) {\n code = 0;\n t = 0.0;\n theta = 0.0;\n dEE = 0.0;\n dPP = 0.0;\n return;\n }\n if(code == 101) {\n t = 0.0;\n theta = 0.0;\n dEE = 0.0;\n dPP = 0.0;\n }\n else if(code == 102) { \/\/ Elastic\n t = pythia.info.tHat();\n theta = pythia.event[3].theta();\n dEE = (pythia.event[3].e() - pythia.event[1].e()) \/ pythia.event[1].e();\n dPP = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) \/ pythia.event[1].pAbs();\n }\n else if(code == 104) { \/\/ Single Diffractive AB->AX\n t = pythia.info.tHat();\n theta = pythia.event[3].theta();\n dEE = (pythia.event[3].e() - pythia.event[1].e()) \/ pythia.event[1].e();\n dPP = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) \/ pythia.event[1].pAbs();\n }\n else if(code == 106) { \/\/ Central Diffractive AB->AXB\n t = (pythia.event[3].p() - pythia.event[1].p()).m2Calc();\n theta = pythia.event[3].theta();\n dEE = (pythia.event[3].e() - pythia.event[1].e()) \/ pythia.event[1].e();\n dPP = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) \/ pythia.event[1].pAbs();\n }\n else {\n t = 0.0;\n theta = 0.0;\n dEE = 0.0;\n dPP = 0.0;\n }\n}\n\nvoid pythiaWrapper_getEventPVector(bool& status, int& code, double& t, double& theta, double& dEE, double& dPP, double* vecPin, double* vecPout) {\n\n status = pythia.next(vecPin[0],vecPin[1],vecPin[2],vecPin[3],vecPin[4],vecPin[5]);\n code = pythia.info.code();\n\n t = 0.0;\n theta = 0.0;\n dEE = 0.0;\n dPP = 0.0;\n\n if(code == 102 || code == 104 || code == 106) {\n theta = pythia.event[3].theta();\n dEE = (pythia.event[3].e() - pythia.event[1].e()) \/ pythia.event[1].e();\n dPP = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) \/ pythia.event[1].pAbs();\n }\n if(code == 102 || code == 104) {\n t = pythia.info.tHat();\n }\n if(code == 106) {\n t = (pythia.event[3].p() - pythia.event[1].p()).m2Calc();\n }\n\n vecPin[0] = pythia.event[1].px();\n vecPin[1] = pythia.event[1].py();\n vecPin[2] = pythia.event[1].pz();\n vecPin[3] = pythia.event[2].px();\n vecPin[4] = pythia.event[2].py();\n vecPin[5] = pythia.event[2].pz();\n vecPout[0] = pythia.event[3].px();\n vecPout[1] = pythia.event[3].py();\n vecPout[2] = pythia.event[3].pz();\n vecPout[3] = pythia.event[4].px();\n vecPout[4] = pythia.event[4].py();\n vecPout[5] = pythia.event[4].pz();\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fixed for compile<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * DataManBase.cpp\n *\n * Created on: Apr 12, 2017\n * Author: Jason Wang\n *\/\n\n#include \"DataManBase.h\"\n\n#include <sstream>\n\n#include <adios2sys\/DynamicLoader.hxx>\n\nstruct DataManBase::ManagerLibrary\n{\n adios2sys::DynamicLoader::LibraryHandle m_LibraryHandle;\n DataManBase *(*m_getManFunc)();\n\n ManagerLibrary(std::string method)\n {\n std::vector<std::string> searchedLibs;\n std::string libName;\n\n std::vector<std::string> libPrefixes;\n libPrefixes.emplace_back(\"\");\n libPrefixes.emplace_back(\"lib\");\n#ifdef __CYGWIN__\n libPrefixes.emplace_back(\"cyg\");\n#endif\n\n std::vector<std::string> libSuffixes;\n#ifdef __APPLE__\n libSuffixes.emplace_back(\"man.dylib\");\n libSuffixes.emplace_back(\"man.so\");\n#endif\n#ifdef __hpux\n libSuffixes.emplace_back(\"man.sl\");\n#endif\n#ifdef __unix__\n libSuffixes.emplace_back(\"man.so\");\n#endif\n#ifdef _WIN32\n libSuffixes.emplace_back(\"man.dll\");\n#endif\n\n \/\/ Test the various combinations of library names\n for (const std::string &prefix : libPrefixes)\n {\n for (const std::string &suffix : libSuffixes)\n {\n libName = prefix + method + suffix;\n m_LibraryHandle =\n adios2sys::DynamicLoader::OpenLibrary(libName);\n searchedLibs.push_back(libName);\n if (m_LibraryHandle)\n {\n break;\n }\n }\n if (m_LibraryHandle)\n {\n break;\n }\n }\n if (!m_LibraryHandle)\n {\n std::stringstream errString;\n errString << \"Unable to locate the \" << method << \" manager \"\n << \"library; searched for \";\n std::copy(searchedLibs.begin(), searchedLibs.end(),\n std::ostream_iterator<std::string>(errString, \" \"));\n\n throw std::runtime_error(errString.str());\n }\n\n \/\/ Bind to the getMan symbol\n adios2sys::DynamicLoader::SymbolPointer symbolHandle =\n adios2sys::DynamicLoader::GetSymbolAddress(m_LibraryHandle,\n \"getMan\");\n if (!symbolHandle)\n {\n throw std::runtime_error(\"Unable to locate the getMan symbol in \" +\n libName);\n }\n m_getManFunc = reinterpret_cast<DataManBase *(*)()>(symbolHandle);\n }\n\n ~ManagerLibrary()\n {\n if (m_LibraryHandle)\n {\n adios2sys::DynamicLoader::CloseLibrary(m_LibraryHandle);\n }\n }\n};\n\nDataManBase::DataManBase()\n{\n m_profiling[\"total_manager_time\"] = 0.0f;\n m_profiling[\"total_mb\"] = 0.0f;\n m_start_time = std::chrono::system_clock::now();\n}\n\nint DataManBase::put(const void *p_data, std::string p_doid, std::string p_var,\n std::string p_dtype, std::vector<size_t> p_putshape,\n std::vector<size_t> p_varshape,\n std::vector<size_t> p_offset, size_t p_timestep,\n int p_tolerance, int p_priority)\n{\n json msg;\n msg[\"doid\"] = p_doid;\n msg[\"var\"] = p_var;\n msg[\"dtype\"] = p_dtype;\n msg[\"putshape\"] = p_putshape;\n msg[\"putbytes\"] = product(p_putshape, dsize(p_dtype));\n msg[\"varshape\"] = p_varshape;\n msg[\"varbytes\"] = product(p_varshape, dsize(p_dtype));\n msg[\"offset\"] = p_offset;\n msg[\"timestep\"] = p_timestep;\n msg[\"tolerance\"] = p_tolerance;\n msg[\"priority\"] = p_priority;\n return put(p_data, msg);\n}\n\nint DataManBase::put_begin(const void *p_data, json &p_jmsg)\n{\n check_shape(p_jmsg);\n p_jmsg[\"profiling\"] = m_profiling;\n m_step_time = std::chrono::system_clock::now();\n return 0;\n}\n\nint DataManBase::put_end(const void *p_data, json &p_jmsg)\n{\n auto end = std::chrono::system_clock::now();\n std::chrono::duration<double> duration = end - m_step_time;\n m_profiling[\"total_manager_time\"] =\n m_profiling[\"total_manager_time\"].get<double>() + duration.count();\n m_profiling[\"total_mb\"] =\n m_profiling[\"total_mb\"].get<size_t>() +\n product(p_jmsg[\"varshape\"], dsize(p_jmsg[\"dtype\"])) \/ 1000000.0f;\n duration = end - m_start_time;\n m_profiling[\"total_workflow_time\"] = duration.count();\n m_profiling[\"workflow_mbs\"] =\n m_profiling[\"total_mb\"].get<double>() \/\n m_profiling[\"total_workflow_time\"].get<double>();\n m_profiling[\"manager_mbs\"] =\n m_profiling[\"total_mb\"].get<double>() \/\n m_profiling[\"total_manager_time\"].get<double>();\n if (p_jmsg[\"compressed_size\"] != nullptr)\n p_jmsg[\"putbytes\"] = p_jmsg[\"compressed_size\"].get<size_t>();\n put_next(p_data, p_jmsg);\n return 0;\n}\n\nint DataManBase::get(void *p_data, std::string p_doid, std::string p_var,\n std::string p_dtype, std::vector<size_t> p_getshape,\n std::vector<size_t> p_varshape,\n std::vector<size_t> p_offset, size_t p_timestep)\n{\n json msg;\n msg[\"doid\"] = p_doid;\n msg[\"var\"] = p_var;\n msg[\"dtype\"] = p_dtype;\n msg[\"getshape\"] = p_getshape;\n msg[\"varshape\"] = p_varshape;\n msg[\"offset\"] = p_offset;\n msg[\"timestep\"] = p_timestep;\n return get(p_data, msg);\n}\n\nint DataManBase::get(void *p_data, std::string p_doid, std::string p_var,\n std::string &p_dtype, std::vector<size_t> &p_varshape,\n size_t &p_timestep)\n{\n json msg;\n msg[\"doid\"] = p_doid;\n msg[\"var\"] = p_var;\n return get(p_data, msg);\n}\n\nvoid DataManBase::reg_callback(\n std::function<void(const void *, std::string, std::string, std::string,\n std::vector<size_t>)>\n cb)\n{\n if (m_next.size() == 0)\n {\n m_callback = cb;\n }\n else\n {\n for (auto i : m_next)\n {\n i.second->reg_callback(cb);\n }\n }\n}\n\nvoid DataManBase::dump(const void *p_data, json p_jmsg, std::ostream &out)\n{\n std::vector<size_t> p_varshape =\n p_jmsg[\"varshape\"].get<std::vector<size_t>>();\n std::string dtype = p_jmsg[\"dtype\"];\n size_t length = p_jmsg[\"dumplength\"].get<size_t>();\n size_t s = 0;\n for (size_t i = 0; i < product(p_varshape, 1); i++)\n {\n s++;\n out << ((float *)p_data)[i] << \" \";\n if (s == length)\n {\n out << std::endl;\n s = 0;\n }\n }\n out << std::endl;\n}\n\nvoid DataManBase::add_next(std::string p_name,\n std::shared_ptr<DataManBase> p_next)\n{\n m_next[p_name] = p_next;\n}\n\nvoid DataManBase::remove_next(std::string p_name) { m_next.erase(p_name); }\n\nbool DataManBase::have_next()\n{\n if (m_next.size() == 0)\n {\n return false;\n }\n else\n {\n return true;\n }\n}\n\nvoid DataManBase::print_next(std::ostream &out)\n{\n for (auto i : m_next)\n {\n out << i.second->name() << \" -> \";\n i.second->print_next();\n out << std::endl;\n }\n}\n\nbool DataManBase::auto_transform(const void *p_in, void *p_out, json &p_jmsg)\n{\n if (p_jmsg[\"compression_method\"] != nullptr)\n {\n auto method = p_jmsg[\"compression_method\"];\n auto man = get_man(method);\n if (man == nullptr)\n {\n logging(\"Library file for compression method \" +\n p_jmsg[\"compression_method\"].dump() + \" not found!\");\n return false;\n }\n man->transform(p_in, p_out, p_jmsg);\n p_jmsg.erase(\"compression_method\");\n p_jmsg.erase(\"compression_rate\");\n p_jmsg.erase(\"compressed_size\");\n return true;\n }\n else\n {\n return false;\n }\n}\n\nvoid DataManBase::add_man_to_path(std::string p_new, std::string p_path)\n{\n if (m_next.count(p_path) > 0)\n {\n auto man = get_man(p_new);\n if (man)\n {\n man->add_next(p_path, m_next[p_path]);\n this->add_next(p_new, man);\n this->remove_next(p_path);\n }\n }\n}\n\nint DataManBase::flush_next()\n{\n for (auto i : m_next)\n {\n i.second->flush();\n }\n return 0;\n}\n\nint DataManBase::put_next(const void *p_data, json p_jmsg)\n{\n for (auto i : m_next)\n {\n i.second->put(p_data, p_jmsg);\n }\n return 0;\n}\n\nstd::shared_ptr<DataManBase> DataManBase::get_man(std::string method)\n{\n try\n {\n \/\/ Reuse already loaded libraries if possible\n auto libIt = m_LoadedManagers.find(method);\n if (libIt == m_LoadedManagers.end())\n {\n \/\/ This insertion will only fail if an entry for method already\n \/\/ exists, which this if block ensures that it doesn't.\n libIt =\n m_LoadedManagers.insert({method, new ManagerLibrary(method)})\n .first;\n }\n return std::shared_ptr<DataManBase>(libIt->second->m_getManFunc());\n }\n catch (const std::runtime_error &ex)\n {\n logging(ex.what());\n return nullptr;\n }\n}\n<commit_msg>Add more verbose logging to dataman when loading manager libraries<commit_after>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * DataManBase.cpp\n *\n * Created on: Apr 12, 2017\n * Author: Jason Wang\n *\/\n\n#include \"DataManBase.h\"\n\n#include <sstream>\n\n#include <adios2sys\/DynamicLoader.hxx>\n\nstruct DataManBase::ManagerLibrary\n{\n std::string m_LibraryName;\n adios2sys::DynamicLoader::LibraryHandle m_LibraryHandle;\n DataManBase *(*m_getManFunc)();\n\n ManagerLibrary(std::string method)\n {\n std::vector<std::string> searchedLibs;\n std::string libName;\n\n std::vector<std::string> libPrefixes;\n libPrefixes.emplace_back(\"\");\n libPrefixes.emplace_back(\"lib\");\n#ifdef __CYGWIN__\n libPrefixes.emplace_back(\"cyg\");\n#endif\n\n std::vector<std::string> libSuffixes;\n#ifdef __APPLE__\n libSuffixes.emplace_back(\"man.dylib\");\n libSuffixes.emplace_back(\"man.so\");\n#endif\n#ifdef __hpux\n libSuffixes.emplace_back(\"man.sl\");\n#endif\n#ifdef __unix__\n libSuffixes.emplace_back(\"man.so\");\n#endif\n#ifdef _WIN32\n libSuffixes.emplace_back(\"man.dll\");\n#endif\n\n \/\/ Test the various combinations of library names\n for (const std::string &prefix : libPrefixes)\n {\n for (const std::string &suffix : libSuffixes)\n {\n libName = prefix + method + suffix;\n m_LibraryHandle =\n adios2sys::DynamicLoader::OpenLibrary(libName);\n searchedLibs.push_back(libName);\n if (m_LibraryHandle)\n {\n break;\n }\n }\n if (m_LibraryHandle)\n {\n break;\n }\n }\n if (!m_LibraryHandle)\n {\n std::stringstream errString;\n errString << \"Unable to locate the \" << method << \" manager \"\n << \"library; searched for \";\n std::copy(searchedLibs.begin(), searchedLibs.end(),\n std::ostream_iterator<std::string>(errString, \" \"));\n\n throw std::runtime_error(errString.str());\n }\n\n \/\/ Bind to the getMan symbol\n adios2sys::DynamicLoader::SymbolPointer symbolHandle =\n adios2sys::DynamicLoader::GetSymbolAddress(m_LibraryHandle,\n \"getMan\");\n if (!symbolHandle)\n {\n throw std::runtime_error(\"Unable to locate the getMan symbol in \" +\n libName);\n }\n m_getManFunc = reinterpret_cast<DataManBase *(*)()>(symbolHandle);\n m_LibraryName = libName;\n }\n\n ~ManagerLibrary()\n {\n if (m_LibraryHandle)\n {\n adios2sys::DynamicLoader::CloseLibrary(m_LibraryHandle);\n }\n }\n};\n\nDataManBase::DataManBase()\n{\n m_profiling[\"total_manager_time\"] = 0.0f;\n m_profiling[\"total_mb\"] = 0.0f;\n m_start_time = std::chrono::system_clock::now();\n}\n\nint DataManBase::put(const void *p_data, std::string p_doid, std::string p_var,\n std::string p_dtype, std::vector<size_t> p_putshape,\n std::vector<size_t> p_varshape,\n std::vector<size_t> p_offset, size_t p_timestep,\n int p_tolerance, int p_priority)\n{\n json msg;\n msg[\"doid\"] = p_doid;\n msg[\"var\"] = p_var;\n msg[\"dtype\"] = p_dtype;\n msg[\"putshape\"] = p_putshape;\n msg[\"putbytes\"] = product(p_putshape, dsize(p_dtype));\n msg[\"varshape\"] = p_varshape;\n msg[\"varbytes\"] = product(p_varshape, dsize(p_dtype));\n msg[\"offset\"] = p_offset;\n msg[\"timestep\"] = p_timestep;\n msg[\"tolerance\"] = p_tolerance;\n msg[\"priority\"] = p_priority;\n return put(p_data, msg);\n}\n\nint DataManBase::put_begin(const void *p_data, json &p_jmsg)\n{\n check_shape(p_jmsg);\n p_jmsg[\"profiling\"] = m_profiling;\n m_step_time = std::chrono::system_clock::now();\n return 0;\n}\n\nint DataManBase::put_end(const void *p_data, json &p_jmsg)\n{\n auto end = std::chrono::system_clock::now();\n std::chrono::duration<double> duration = end - m_step_time;\n m_profiling[\"total_manager_time\"] =\n m_profiling[\"total_manager_time\"].get<double>() + duration.count();\n m_profiling[\"total_mb\"] =\n m_profiling[\"total_mb\"].get<size_t>() +\n product(p_jmsg[\"varshape\"], dsize(p_jmsg[\"dtype\"])) \/ 1000000.0f;\n duration = end - m_start_time;\n m_profiling[\"total_workflow_time\"] = duration.count();\n m_profiling[\"workflow_mbs\"] =\n m_profiling[\"total_mb\"].get<double>() \/\n m_profiling[\"total_workflow_time\"].get<double>();\n m_profiling[\"manager_mbs\"] =\n m_profiling[\"total_mb\"].get<double>() \/\n m_profiling[\"total_manager_time\"].get<double>();\n if (p_jmsg[\"compressed_size\"] != nullptr)\n p_jmsg[\"putbytes\"] = p_jmsg[\"compressed_size\"].get<size_t>();\n put_next(p_data, p_jmsg);\n return 0;\n}\n\nint DataManBase::get(void *p_data, std::string p_doid, std::string p_var,\n std::string p_dtype, std::vector<size_t> p_getshape,\n std::vector<size_t> p_varshape,\n std::vector<size_t> p_offset, size_t p_timestep)\n{\n json msg;\n msg[\"doid\"] = p_doid;\n msg[\"var\"] = p_var;\n msg[\"dtype\"] = p_dtype;\n msg[\"getshape\"] = p_getshape;\n msg[\"varshape\"] = p_varshape;\n msg[\"offset\"] = p_offset;\n msg[\"timestep\"] = p_timestep;\n return get(p_data, msg);\n}\n\nint DataManBase::get(void *p_data, std::string p_doid, std::string p_var,\n std::string &p_dtype, std::vector<size_t> &p_varshape,\n size_t &p_timestep)\n{\n json msg;\n msg[\"doid\"] = p_doid;\n msg[\"var\"] = p_var;\n return get(p_data, msg);\n}\n\nvoid DataManBase::reg_callback(\n std::function<void(const void *, std::string, std::string, std::string,\n std::vector<size_t>)>\n cb)\n{\n if (m_next.size() == 0)\n {\n m_callback = cb;\n }\n else\n {\n for (auto i : m_next)\n {\n i.second->reg_callback(cb);\n }\n }\n}\n\nvoid DataManBase::dump(const void *p_data, json p_jmsg, std::ostream &out)\n{\n std::vector<size_t> p_varshape =\n p_jmsg[\"varshape\"].get<std::vector<size_t>>();\n std::string dtype = p_jmsg[\"dtype\"];\n size_t length = p_jmsg[\"dumplength\"].get<size_t>();\n size_t s = 0;\n for (size_t i = 0; i < product(p_varshape, 1); i++)\n {\n s++;\n out << ((float *)p_data)[i] << \" \";\n if (s == length)\n {\n out << std::endl;\n s = 0;\n }\n }\n out << std::endl;\n}\n\nvoid DataManBase::add_next(std::string p_name,\n std::shared_ptr<DataManBase> p_next)\n{\n m_next[p_name] = p_next;\n}\n\nvoid DataManBase::remove_next(std::string p_name) { m_next.erase(p_name); }\n\nbool DataManBase::have_next()\n{\n if (m_next.size() == 0)\n {\n return false;\n }\n else\n {\n return true;\n }\n}\n\nvoid DataManBase::print_next(std::ostream &out)\n{\n for (auto i : m_next)\n {\n out << i.second->name() << \" -> \";\n i.second->print_next();\n out << std::endl;\n }\n}\n\nbool DataManBase::auto_transform(const void *p_in, void *p_out, json &p_jmsg)\n{\n if (p_jmsg[\"compression_method\"] != nullptr)\n {\n auto method = p_jmsg[\"compression_method\"];\n auto man = get_man(method);\n if (man == nullptr)\n {\n logging(\"Library file for compression method \" +\n p_jmsg[\"compression_method\"].dump() + \" not found!\");\n return false;\n }\n man->transform(p_in, p_out, p_jmsg);\n p_jmsg.erase(\"compression_method\");\n p_jmsg.erase(\"compression_rate\");\n p_jmsg.erase(\"compressed_size\");\n return true;\n }\n else\n {\n return false;\n }\n}\n\nvoid DataManBase::add_man_to_path(std::string p_new, std::string p_path)\n{\n if (m_next.count(p_path) > 0)\n {\n auto man = get_man(p_new);\n if (man)\n {\n man->add_next(p_path, m_next[p_path]);\n this->add_next(p_new, man);\n this->remove_next(p_path);\n }\n }\n}\n\nint DataManBase::flush_next()\n{\n for (auto i : m_next)\n {\n i.second->flush();\n }\n return 0;\n}\n\nint DataManBase::put_next(const void *p_data, json p_jmsg)\n{\n for (auto i : m_next)\n {\n i.second->put(p_data, p_jmsg);\n }\n return 0;\n}\n\nstd::shared_ptr<DataManBase> DataManBase::get_man(std::string method)\n{\n try\n {\n \/\/ Reuse already loaded libraries if possible\n auto libIt = m_LoadedManagers.find(method);\n if (libIt == m_LoadedManagers.end())\n {\n \/\/ This insertion will only fail if an entry for method already\n \/\/ exists, which this if block ensures that it doesn't.\n libIt =\n m_LoadedManagers.insert({method, new ManagerLibrary(method)})\n .first;\n logging(\"Loaded \" + libIt->second->m_LibraryName);\n }\n else\n {\n logging(\"Using existing \" + libIt->second->m_LibraryName + \".\");\n }\n return std::shared_ptr<DataManBase>(libIt->second->m_getManFunc());\n }\n catch (const std::runtime_error &ex)\n {\n logging(ex.what());\n return nullptr;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"choiceview.h\"\n\n#include <QKeyEvent>\n#include <QPaintEvent>\n#include <QPainter>\n\nChoice::Choice(const QString &title, const QString &id, const QStringList ¶ms)\n : _id(id), _title(title), _params(params) {\n}\n\nconst QString &Choice::id() const {\n return _id;\n}\n\nconst QString &Choice::title() const {\n return _title;\n}\n\nconst QStringList &Choice::params() const {\n return _params;\n}\n\nChoiceView::ChoiceView(QWidget *parent)\n : QWidget(parent),\n _offset(0) {\n\n setFocusPolicy(Qt::StrongFocus);\n\n QFont myFont;\n myFont.setPointSize(20);\n setFont(myFont);\n}\n\nChoiceView::~ChoiceView() { }\n\nstatic const int arrowHeight = 8;\n\nstatic char _hotkeys[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };\nvoid ChoiceView::paintEvent(QPaintEvent *event) {\n QFontMetrics metrics(font());\n QPainter painter(this);\n\n int y = arrowHeight + 2;\n const int baseline = metrics.leading() + metrics.ascent() + 1;\n const int w = width(), h = height() - (y * 2);\n const int yInc = h \/ 10;\n const int labelWidth = w - yInc - 10;\n const int hotkeyCenter = w - (yInc \/ 2);\n\n \/\/ Top arrow\n const int center = w \/ 2;\n painter.eraseRect(0, 0, w, y);\n if (_offset > 0) {\n painter.drawLine(center, 0, center - arrowHeight, arrowHeight);\n painter.drawLine(center, 0, center + arrowHeight, arrowHeight);\n painter.drawLine(center - arrowHeight, arrowHeight, center + arrowHeight, arrowHeight);\n }\n \n \/\/ Bottom arrow\n painter.eraseRect(0, height() - y, w, y);\n if (_offset + 10 < _choices.size()) {\n painter.drawLine(center, height() - 1, center - arrowHeight, height() - arrowHeight - 1);\n painter.drawLine(center, height() - 1, center + arrowHeight, height() - arrowHeight - 1);\n painter.drawLine(center - arrowHeight, height() - arrowHeight - 1,\n center + arrowHeight, height() - arrowHeight - 1);\n }\n\n QLinearGradient fade(QPointF(0,0), QPointF(labelWidth, 0));\n fade.setColorAt(0, Qt::black);\n fade.setColorAt(0.95, Qt::black);\n fade.setColorAt(1.0, QColor(0xAA, 0xAA, 0xAA));\n \n QTextOption noWrap;\n noWrap.setWrapMode(QTextOption::NoWrap);\n\n \/\/ Choice area\n for (int row = 0; row < NUM_CHOICES; row++) {\n const int item = row + _offset;\n painter.eraseRect(0, y, w, yInc);\n if (item < _choices.size()) {\n const Choice &c = _choices[item];\n if (metrics.width(c.title()) > labelWidth) {\n painter.setPen(QPen(QBrush(fade), 1));\n } else {\n painter.setPen(QPen(Qt::black));\n }\n\n painter.drawText(QRectF(0, y, labelWidth, yInc), c.title(), noWrap);\n\n painter.save();\n if (row > 0) {\n painter.setPen(QColor(0xAA, 0xAA, 0xAA));\n painter.drawLine(50, y - 10, w - 50, y - 10);\n }\n\n painter.setPen(QColor(0x55, 0x55, 0x55));\n painter.drawRect(labelWidth + 10, y + metrics.leading(), yInc - 1, metrics.height());\n painter.drawText(hotkeyCenter - (metrics.width(_hotkeys[row]) \/ 2), y + baseline,\n QString(1, _hotkeys[row]));\n\n painter.restore();\n }\n y += yInc;\n }\n}\n\nvoid ChoiceView::keyPressEvent(QKeyEvent *event) {\n if (event->key() >= Qt::Key_0 && event->key() <= Qt::Key_9) {\n int chosen = event->key() - Qt::Key_0 + _offset - 1;\n if (chosen < _offset) chosen += 10;\n if (chosen < _choices.size()) {\n choose(chosen);\n return;\n }\n } else if (event->key() == Qt::Key_Escape) {\n goBack();\n return;\n } else if (event->key() == Qt::Key_Down) {\n pageDown();\n return;\n } else if (event->key() == Qt::Key_Up) {\n pageUp();\n return;\n }\n QWidget::keyPressEvent(event);\n}\n\nvoid ChoiceView::choose(int chosen) {\n emit choiceMade(_choices[chosen]);\n}\n\nvoid ChoiceView::goBack() {\n emit back();\n}\n\nvoid ChoiceView::setChoices(const QList<Choice> choices) {\n _choices = choices;\n if (_offset >= _choices.size()) {\n \/\/ Integer division floors here.\n _offset = (_choices.size() \/ 10) * 10;\n }\n emit morePages(_choices.size() \/ 10);\n refreshLabels();\n}\n\nvoid ChoiceView::pageDown() {\n if (_offset < _choices.size() - 10) {\n _offset += 10;\n refreshLabels();\n }\n}\n\nvoid ChoiceView::pageUp() {\n if (_offset >= 10) {\n _offset -= 10;\n refreshLabels();\n }\n}\n\nvoid ChoiceView::refreshLabels() {\n update();\n emit switchedToPage(_offset \/ 10);\n}\n\nbool operator<(Choice a, Choice b) {\n return a.title().compare(b.title(), Qt::CaseInsensitive) < 0;\n}\n<commit_msg>Rounded edges of hotkey mnemonics.<commit_after>#include \"choiceview.h\"\n\n#include <QKeyEvent>\n#include <QPaintEvent>\n#include <QPainter>\n\nChoice::Choice(const QString &title, const QString &id, const QStringList ¶ms)\n : _id(id), _title(title), _params(params) {\n}\n\nconst QString &Choice::id() const {\n return _id;\n}\n\nconst QString &Choice::title() const {\n return _title;\n}\n\nconst QStringList &Choice::params() const {\n return _params;\n}\n\nChoiceView::ChoiceView(QWidget *parent)\n : QWidget(parent),\n _offset(0) {\n\n setFocusPolicy(Qt::StrongFocus);\n\n QFont myFont;\n myFont.setPointSize(20);\n setFont(myFont);\n}\n\nChoiceView::~ChoiceView() { }\n\nstatic const int arrowHeight = 8;\n\nstatic char _hotkeys[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };\nvoid ChoiceView::paintEvent(QPaintEvent *event) {\n QFontMetrics metrics(font());\n QPainter painter(this);\n\n int y = arrowHeight + 2;\n const int baseline = metrics.leading() + metrics.ascent() + 1;\n const int w = width(), h = height() - (y * 2);\n const int yInc = h \/ 10;\n const int labelWidth = w - yInc - 10;\n const int hotkeyCenter = w - (yInc \/ 2);\n\n \/\/ Top arrow\n const int center = w \/ 2;\n painter.eraseRect(0, 0, w, y);\n if (_offset > 0) {\n painter.drawLine(center, 0, center - arrowHeight, arrowHeight);\n painter.drawLine(center, 0, center + arrowHeight, arrowHeight);\n painter.drawLine(center - arrowHeight, arrowHeight, center + arrowHeight, arrowHeight);\n }\n \n \/\/ Bottom arrow\n painter.eraseRect(0, height() - y, w, y);\n if (_offset + 10 < _choices.size()) {\n painter.drawLine(center, height() - 1, center - arrowHeight, height() - arrowHeight - 1);\n painter.drawLine(center, height() - 1, center + arrowHeight, height() - arrowHeight - 1);\n painter.drawLine(center - arrowHeight, height() - arrowHeight - 1,\n center + arrowHeight, height() - arrowHeight - 1);\n }\n\n QLinearGradient fade(QPointF(0,0), QPointF(labelWidth, 0));\n fade.setColorAt(0, Qt::black);\n fade.setColorAt(0.95, Qt::black);\n fade.setColorAt(1.0, QColor(0xAA, 0xAA, 0xAA));\n \n QTextOption noWrap;\n noWrap.setWrapMode(QTextOption::NoWrap);\n\n \/\/ Choice area\n for (int row = 0; row < NUM_CHOICES; row++) {\n const int item = row + _offset;\n painter.eraseRect(0, y, w, yInc);\n if (item < _choices.size()) {\n const Choice &c = _choices[item];\n if (metrics.width(c.title()) > labelWidth) {\n painter.setPen(QPen(QBrush(fade), 1));\n } else {\n painter.setPen(QPen(Qt::black));\n }\n\n painter.drawText(QRectF(0, y, labelWidth, yInc), c.title(), noWrap);\n\n painter.save();\n if (row > 0) {\n painter.setPen(QColor(0xAA, 0xAA, 0xAA));\n painter.drawLine(50, y - 10, w - 50, y - 10);\n }\n\n painter.setPen(QColor(0x55, 0x55, 0x55));\n painter.drawRoundedRect(labelWidth + 10, y + metrics.leading(), yInc - 1, metrics.height(), 4, 4);\n painter.drawText(hotkeyCenter - (metrics.width(_hotkeys[row]) \/ 2), y + baseline,\n QString(1, _hotkeys[row]));\n\n painter.restore();\n }\n y += yInc;\n }\n}\n\nvoid ChoiceView::keyPressEvent(QKeyEvent *event) {\n if (event->key() >= Qt::Key_0 && event->key() <= Qt::Key_9) {\n int chosen = event->key() - Qt::Key_0 + _offset - 1;\n if (chosen < _offset) chosen += 10;\n if (chosen < _choices.size()) {\n choose(chosen);\n return;\n }\n } else if (event->key() == Qt::Key_Escape) {\n goBack();\n return;\n } else if (event->key() == Qt::Key_Down) {\n pageDown();\n return;\n } else if (event->key() == Qt::Key_Up) {\n pageUp();\n return;\n }\n QWidget::keyPressEvent(event);\n}\n\nvoid ChoiceView::choose(int chosen) {\n emit choiceMade(_choices[chosen]);\n}\n\nvoid ChoiceView::goBack() {\n emit back();\n}\n\nvoid ChoiceView::setChoices(const QList<Choice> choices) {\n _choices = choices;\n if (_offset >= _choices.size()) {\n \/\/ Integer division floors here.\n _offset = (_choices.size() \/ 10) * 10;\n }\n emit morePages(_choices.size() \/ 10);\n refreshLabels();\n}\n\nvoid ChoiceView::pageDown() {\n if (_offset < _choices.size() - 10) {\n _offset += 10;\n refreshLabels();\n }\n}\n\nvoid ChoiceView::pageUp() {\n if (_offset >= 10) {\n _offset -= 10;\n refreshLabels();\n }\n}\n\nvoid ChoiceView::refreshLabels() {\n update();\n emit switchedToPage(_offset \/ 10);\n}\n\nbool operator<(Choice a, Choice b) {\n return a.title().compare(b.title(), Qt::CaseInsensitive) < 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <precomp.h>\n#include <cosv\/string.hxx>\n\n\/\/ NOT FULLY DECLARED SERVICES\n#include <string.h>\n#include <cosv\/comfunc.hxx>\n\n\n\n\nnamespace csv\n{\n\n\ninline const char *\nstr_from_StringOffset( const String & i_rStr,\n str::size i_nOffset )\n{\n return i_nOffset < i_rStr.size()\n ? i_rStr.c_str() + i_nOffset\n : \"\";\n}\n\ninline const char *\nstr_from_ptr( const char * i_str )\n{\n\n return valid_str(i_str);\n}\n\n\n\/\/********************* String::S_Data **********************\/\/\n\ninline String::\nS_Data::S_Data()\n : nCount(1)\n{\n}\n\nString::\nS_Data::S_Data( const char * i_sData,\n size_type i_nValidLength )\n : aStr( str_from_ptr(i_sData),\n (i_nValidLength != str::maxsize\n ? i_nValidLength\n : strlen(i_sData)) ),\n nCount(1)\n{\n}\n\nString::\nS_Data::~S_Data()\n{\n csv_assert( nCount == 0 );\n}\n\nconst String::S_Data *\nString::\nS_Data::Acquire() const\n{\n#ifdef CSV_NO_MUTABLE\n ++ (const_cast< uintt& >(nCount));\n#else\n ++nCount;\n#endif\n return this;\n}\n\nvoid\nString::\nS_Data::Release() const\n{\n#ifdef CSV_NO_MUTABLE\n -- (const_cast< uintt& >(nCount));\n#else\n --nCount;\n#endif\n if (nCount == 0)\n delete (const_cast< S_Data* >(this));\n}\n\n\n\/\/************************** String **************************\/\/\n\n\nString::String()\n : pd( String::Null_().pd->Acquire() )\n{\n}\n\nString::String( const char * i_str )\n : pd( new S_Data(i_str) )\n{\n}\n\nString::String( const char * i_str,\n size_type i_nLength )\n : pd( new S_Data(i_str, i_nLength) )\n{\n}\n\nString::String( const_iterator i_itBegin,\n const_iterator i_itEnd )\n : pd( new S_Data(i_itBegin, size_type(i_itEnd - i_itBegin)) )\n{\n}\n\nString::String( const self & i_rStr )\n : pd( i_rStr.pd->Acquire() )\n{\n}\n\nString::~String()\n{\n pd->Release();\n}\n\n\nString &\nString::operator=( const self & i_rStr )\n{\n i_rStr.pd->Acquire();\n pd->Release();\n pd = i_rStr.pd;\n\n return *this;\n}\n\nString &\nString::operator=( const char * i_str )\n{\n const S_Data *\n pTemp = new S_Data(i_str);\n pd->Release();\n pd = pTemp;\n\n return *this;\n}\n\nvoid\nString::assign( const char * i_str,\n size_type i_nLength )\n{\n const S_Data *\n pTemp = new S_Data( i_str, i_nLength );\n pd->Release();\n pd = pTemp;\n}\n\nint\nString::compare( const self & i_rStr ) const\n{\n return strcmp( c_str(), i_rStr.c_str() );\n}\n\nint\nString::compare( const CharOrder_Table & i_rOrder,\n const self & i_rStr ) const\n{\n return csv::compare( i_rOrder, c_str(), i_rStr.c_str() );\n}\n\nconst String &\nString::Null_()\n{\n \/\/ Must not use the default constructor! Because that one calls\n \/\/ this function, which would create a circular dependency.\n static const String aNull_(\"\");\n return aNull_;\n}\n\nconst char &\nString::Nulch_()\n{\n static const char cNull_ = '\\0';\n return cNull_;\n}\n\n\nint\ncompare( const String & i_s1,\n csv::str::position i_nStartPosition1,\n const char * i_s2,\n csv::str::size i_nLength )\n{\n const char * pS1 = str_from_StringOffset( i_s1, i_nStartPosition1 );\n\n if ( i_nLength != csv::str::maxsize )\n return strncmp( pS1,\n i_s2,\n i_nLength );\n else\n return strcmp( pS1,\n i_s2 );\n}\n\nint\ncompare( const CharOrder_Table & i_rOrder,\n const char * i_s1,\n const char * i_s2 )\n{\n const char * it1 = i_s1;\n const char * it2 = i_s2;\n for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\\0'; ++it1, ++it2 )\n {}\n return int( i_rOrder(*it1) - i_rOrder(*it2) );\n}\n\nint\ncompare( const CharOrder_Table & i_rOrder,\n const char * i_s1,\n const char * i_s2,\n csv::str::size i_nLength )\n{\n const char * sEnd = i_s1 + i_nLength;\n\n const char * it1 = i_s1;\n const char * it2 = i_s2;\n for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\\0' AND it1 != sEnd; ++it1, ++it2 )\n {}\n\n if ( it1 != sEnd )\n return int( i_rOrder(*it1) - i_rOrder(*it2) );\n else\n return 0;\n}\n\n} \/\/ namespace csv\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>ditch unused compare<commit_after>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <precomp.h>\n#include <cosv\/string.hxx>\n\n\/\/ NOT FULLY DECLARED SERVICES\n#include <string.h>\n#include <cosv\/comfunc.hxx>\n\n\n\n\nnamespace csv\n{\n\n\ninline const char *\nstr_from_StringOffset( const String & i_rStr,\n str::size i_nOffset )\n{\n return i_nOffset < i_rStr.size()\n ? i_rStr.c_str() + i_nOffset\n : \"\";\n}\n\ninline const char *\nstr_from_ptr( const char * i_str )\n{\n\n return valid_str(i_str);\n}\n\n\n\/\/********************* String::S_Data **********************\/\/\n\ninline String::\nS_Data::S_Data()\n : nCount(1)\n{\n}\n\nString::\nS_Data::S_Data( const char * i_sData,\n size_type i_nValidLength )\n : aStr( str_from_ptr(i_sData),\n (i_nValidLength != str::maxsize\n ? i_nValidLength\n : strlen(i_sData)) ),\n nCount(1)\n{\n}\n\nString::\nS_Data::~S_Data()\n{\n csv_assert( nCount == 0 );\n}\n\nconst String::S_Data *\nString::\nS_Data::Acquire() const\n{\n#ifdef CSV_NO_MUTABLE\n ++ (const_cast< uintt& >(nCount));\n#else\n ++nCount;\n#endif\n return this;\n}\n\nvoid\nString::\nS_Data::Release() const\n{\n#ifdef CSV_NO_MUTABLE\n -- (const_cast< uintt& >(nCount));\n#else\n --nCount;\n#endif\n if (nCount == 0)\n delete (const_cast< S_Data* >(this));\n}\n\n\n\/\/************************** String **************************\/\/\n\n\nString::String()\n : pd( String::Null_().pd->Acquire() )\n{\n}\n\nString::String( const char * i_str )\n : pd( new S_Data(i_str) )\n{\n}\n\nString::String( const char * i_str,\n size_type i_nLength )\n : pd( new S_Data(i_str, i_nLength) )\n{\n}\n\nString::String( const_iterator i_itBegin,\n const_iterator i_itEnd )\n : pd( new S_Data(i_itBegin, size_type(i_itEnd - i_itBegin)) )\n{\n}\n\nString::String( const self & i_rStr )\n : pd( i_rStr.pd->Acquire() )\n{\n}\n\nString::~String()\n{\n pd->Release();\n}\n\n\nString &\nString::operator=( const self & i_rStr )\n{\n i_rStr.pd->Acquire();\n pd->Release();\n pd = i_rStr.pd;\n\n return *this;\n}\n\nString &\nString::operator=( const char * i_str )\n{\n const S_Data *\n pTemp = new S_Data(i_str);\n pd->Release();\n pd = pTemp;\n\n return *this;\n}\n\nvoid\nString::assign( const char * i_str,\n size_type i_nLength )\n{\n const S_Data *\n pTemp = new S_Data( i_str, i_nLength );\n pd->Release();\n pd = pTemp;\n}\n\nint\nString::compare( const self & i_rStr ) const\n{\n return strcmp( c_str(), i_rStr.c_str() );\n}\n\nint\nString::compare( const CharOrder_Table & i_rOrder,\n const self & i_rStr ) const\n{\n return csv::compare( i_rOrder, c_str(), i_rStr.c_str() );\n}\n\nconst String &\nString::Null_()\n{\n \/\/ Must not use the default constructor! Because that one calls\n \/\/ this function, which would create a circular dependency.\n static const String aNull_(\"\");\n return aNull_;\n}\n\nconst char &\nString::Nulch_()\n{\n static const char cNull_ = '\\0';\n return cNull_;\n}\n\n\nint\ncompare( const String & i_s1,\n csv::str::position i_nStartPosition1,\n const char * i_s2,\n csv::str::size i_nLength )\n{\n const char * pS1 = str_from_StringOffset( i_s1, i_nStartPosition1 );\n\n if ( i_nLength != csv::str::maxsize )\n return strncmp( pS1,\n i_s2,\n i_nLength );\n else\n return strcmp( pS1,\n i_s2 );\n}\n\nint\ncompare( const CharOrder_Table & i_rOrder,\n const char * i_s1,\n const char * i_s2 )\n{\n const char * it1 = i_s1;\n const char * it2 = i_s2;\n for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\\0'; ++it1, ++it2 )\n {}\n return int( i_rOrder(*it1) - i_rOrder(*it2) );\n}\n\n} \/\/ namespace csv\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\n\/\/!\n\/\/! This file implements the entire test catalog, by implementing all functions\n\/\/! required for a disir plugin that may serve configs generated from mold, and molds\n\/\/! defined programmatically. This is part of the extended disir library so that\n\/\/! it is easy to iterate and test new plugins.\n\/\/!\n\n#include <map>\n#include <utility>\n#include <string.h>\n#include <limits.h>\n\n#include <disir\/disir.h>\n#include <disir\/util.h>\n#include <disir\/plugin.h>\n#include <disir\/test.h>\n#include <disir\/fslib\/util.h>\n\n#include \"mqueue.h\"\n\n\/\/ Include programmatic implementation of several molds\n#include \"basic_keyval.cc\"\n#include \"basic_section.cc\"\n#include \"json_test_mold.cc\"\n#include \"restriction_keyval_numeric_types.cc\"\n#include \"restriction_entries.cc\"\n#include \"restriction_config_parent_keyval_min_entry.cc\"\n#include \"restriction_config_parent_keyval_max_entry.cc\"\n#include \"restriction_config_parent_section_max_entry.cc\"\n#include \"restriction_section_parent_keyval_max_entry.cc\"\n#include \"basic_version_difference.cc\"\n#include \"complex_section.cc\"\n#include \"config_query_permutations.cc\"\n\ntypedef enum disir_status (*output_mold)(struct disir_mold **);\n\n\/\/! Internal static map to store test molds by id\nstatic std::map<std::string, output_mold> molds = {\n std::make_pair (\"basic_keyval\", basic_keyval),\n std::make_pair (\"basic_section\", basic_section),\n std::make_pair (\"json_test_mold\", json_test_mold),\n std::make_pair (\"restriction_keyval_numeric_types\", restriction_keyval_numeric_types),\n std::make_pair (\"restriction_entries\", restriction_entries),\n std::make_pair (\"restriction_config_parent_keyval_min_entry\",\n restriction_config_parent_keyval_min_entry),\n std::make_pair (\"restriction_config_parent_keyval_max_entry\",\n restriction_config_parent_keyval_max_entry),\n std::make_pair (\"restriction_config_parent_section_max_entry\",\n restriction_config_parent_section_max_entry),\n std::make_pair (\"restriction_section_parent_keyval_max_entry\",\n restriction_section_parent_keyval_max_entry),\n std::make_pair (\"basic_version_difference\", basic_version_difference),\n std::make_pair (\"complex_section\", complex_section),\n std::make_pair (\"config_query_permutations\", config_query_permutations),\n std::make_pair (\"nested\/basic_keyval\", basic_keyval),\n std::make_pair (\"nested\/\", basic_keyval),\n std::make_pair (\"super\/\", basic_keyval),\n std::make_pair (\"super\/nested\/\", basic_keyval),\n std::make_pair (\"super\/nested\/basic_keyval\", basic_keyval),\n};\n\n\nenum disir_status\ndio_test_config_read (struct disir_instance *instance,\n struct disir_register_plugin *plugin, const char *entry_id,\n struct disir_mold *mold, struct disir_config **config)\n{\n enum disir_status status;\n output_mold func_mold;\n char namespace_entry[PATH_MAX];\n\n (void) &instance;\n (void) &plugin;\n\n func_mold = molds[std::string(entry_id)];\n if (func_mold == NULL)\n {\n if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n func_mold = molds[namespace_entry];\n if (func_mold == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n }\n\n status = func_mold (&mold);\n if (status != DISIR_STATUS_OK)\n return status;\n\n status = disir_generate_config_from_mold (mold, NULL, config);\n \/\/ We are finished with our allocated mold\n disir_mold_finished (&mold);\n return status;\n}\n\nenum disir_status\ndio_test_config_entries (struct disir_instance *instance,\n struct disir_register_plugin *plugin, struct disir_entry **entries)\n{\n return dio_test_mold_entries (instance, plugin, entries);\n}\n\nenum disir_status\ndio_test_config_query (struct disir_instance *instance, struct disir_register_plugin *plugin,\n const char *entry_id, struct disir_entry **entry)\n{\n (void) &instance;\n (void) &plugin;\n (void) &entry;\n\n if (molds[entry_id] == NULL)\n return DISIR_STATUS_NOT_EXIST;\n else\n return DISIR_STATUS_EXISTS;\n}\n\nenum disir_status\ndio_test_mold_read (struct disir_instance *instance, struct disir_register_plugin *plugin,\n const char *entry_id, struct disir_mold **mold)\n{\n enum disir_status status;\n output_mold func_mold;\n char namespace_entry[PATH_MAX];\n\n (void) &instance;\n (void) &plugin;\n (void) &entry_id;\n\n func_mold = molds[entry_id];\n if (func_mold == NULL)\n {\n\n if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n func_mold = molds[namespace_entry];\n if (func_mold == NULL)\n {\n return DISIR_STATUS_INVALID_ARGUMENT;\n }\n }\n\n status = func_mold (mold);\n if (status != DISIR_STATUS_OK)\n return status;\n\n return DISIR_STATUS_OK;;\n}\n\nenum disir_status\ndio_test_mold_entries (struct disir_instance *instance,\n struct disir_register_plugin *plugin, struct disir_entry **entries)\n{\n struct disir_entry *queue;\n struct disir_entry *entry;\n\n (void) &instance;\n (void) &plugin;\n\n\n queue = NULL;\n\n for (auto i = molds.begin(); i != molds.end(); ++i)\n {\n entry = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));\n if (entry == NULL)\n continue;\n\n entry->de_entry_name = strdup (i->first.c_str());\n entry->flag.DE_READABLE = 1;\n entry->flag.DE_WRITABLE = 1;\n if (i->first.back() == '\/')\n {\n entry->flag.DE_NAMESPACE_ENTRY = 1;\n }\n MQ_ENQUEUE (queue, entry);\n }\n\n *entries = queue;\n\n return DISIR_STATUS_OK;\n}\n\nenum disir_status\ndio_test_mold_query (struct disir_instance *instance, struct disir_register_plugin *plugin,\n const char *entry_id, struct disir_entry **entry)\n{\n char namespace_entry[PATH_MAX];\n\n (void) &instance;\n (void) &plugin;\n\n if (entry_id == NULL)\n return DISIR_STATUS_INTERNAL_ERROR;;\n\n std::string name(entry_id);\n if (molds.count (name) == 0)\n {\n if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n name = std::string (namespace_entry);\n \/\/ The namespace entry does not exist\n if (molds.count (name) == 0)\n {\n return DISIR_STATUS_NOT_EXIST;\n }\n }\n\n if (entry != NULL)\n {\n *entry = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));\n if (*entry == NULL)\n return DISIR_STATUS_NO_MEMORY;\n\n (*entry)->de_entry_name = strdup (name.c_str());\n (*entry)->flag.DE_READABLE = 1;\n (*entry)->flag.DE_WRITABLE = 1;\n if (name.back() == '\/')\n {\n (*entry)->flag.DE_NAMESPACE_ENTRY = 1;\n }\n }\n\n return DISIR_STATUS_EXISTS;\n}\n\n<commit_msg>fix: correct error code in test plugin corner-case<commit_after>\n\/\/!\n\/\/! This file implements the entire test catalog, by implementing all functions\n\/\/! required for a disir plugin that may serve configs generated from mold, and molds\n\/\/! defined programmatically. This is part of the extended disir library so that\n\/\/! it is easy to iterate and test new plugins.\n\/\/!\n\n#include <map>\n#include <utility>\n#include <string.h>\n#include <limits.h>\n\n#include <disir\/disir.h>\n#include <disir\/util.h>\n#include <disir\/plugin.h>\n#include <disir\/test.h>\n#include <disir\/fslib\/util.h>\n\n#include \"mqueue.h\"\n\n\/\/ Include programmatic implementation of several molds\n#include \"basic_keyval.cc\"\n#include \"basic_section.cc\"\n#include \"json_test_mold.cc\"\n#include \"restriction_keyval_numeric_types.cc\"\n#include \"restriction_entries.cc\"\n#include \"restriction_config_parent_keyval_min_entry.cc\"\n#include \"restriction_config_parent_keyval_max_entry.cc\"\n#include \"restriction_config_parent_section_max_entry.cc\"\n#include \"restriction_section_parent_keyval_max_entry.cc\"\n#include \"basic_version_difference.cc\"\n#include \"complex_section.cc\"\n#include \"config_query_permutations.cc\"\n\ntypedef enum disir_status (*output_mold)(struct disir_mold **);\n\n\/\/! Internal static map to store test molds by id\nstatic std::map<std::string, output_mold> molds = {\n std::make_pair (\"basic_keyval\", basic_keyval),\n std::make_pair (\"basic_section\", basic_section),\n std::make_pair (\"json_test_mold\", json_test_mold),\n std::make_pair (\"restriction_keyval_numeric_types\", restriction_keyval_numeric_types),\n std::make_pair (\"restriction_entries\", restriction_entries),\n std::make_pair (\"restriction_config_parent_keyval_min_entry\",\n restriction_config_parent_keyval_min_entry),\n std::make_pair (\"restriction_config_parent_keyval_max_entry\",\n restriction_config_parent_keyval_max_entry),\n std::make_pair (\"restriction_config_parent_section_max_entry\",\n restriction_config_parent_section_max_entry),\n std::make_pair (\"restriction_section_parent_keyval_max_entry\",\n restriction_section_parent_keyval_max_entry),\n std::make_pair (\"basic_version_difference\", basic_version_difference),\n std::make_pair (\"complex_section\", complex_section),\n std::make_pair (\"config_query_permutations\", config_query_permutations),\n std::make_pair (\"nested\/basic_keyval\", basic_keyval),\n std::make_pair (\"nested\/\", basic_keyval),\n std::make_pair (\"super\/\", basic_keyval),\n std::make_pair (\"super\/nested\/\", basic_keyval),\n std::make_pair (\"super\/nested\/basic_keyval\", basic_keyval),\n};\n\n\nenum disir_status\ndio_test_config_read (struct disir_instance *instance,\n struct disir_register_plugin *plugin, const char *entry_id,\n struct disir_mold *mold, struct disir_config **config)\n{\n enum disir_status status;\n output_mold func_mold;\n char namespace_entry[PATH_MAX];\n\n (void) &instance;\n (void) &plugin;\n\n func_mold = molds[std::string(entry_id)];\n if (func_mold == NULL)\n {\n if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n func_mold = molds[namespace_entry];\n if (func_mold == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n }\n\n status = func_mold (&mold);\n if (status != DISIR_STATUS_OK)\n return status;\n\n status = disir_generate_config_from_mold (mold, NULL, config);\n \/\/ We are finished with our allocated mold\n disir_mold_finished (&mold);\n return status;\n}\n\nenum disir_status\ndio_test_config_entries (struct disir_instance *instance,\n struct disir_register_plugin *plugin, struct disir_entry **entries)\n{\n return dio_test_mold_entries (instance, plugin, entries);\n}\n\nenum disir_status\ndio_test_config_query (struct disir_instance *instance, struct disir_register_plugin *plugin,\n const char *entry_id, struct disir_entry **entry)\n{\n (void) &instance;\n (void) &plugin;\n (void) &entry;\n\n if (molds[entry_id] == NULL)\n return DISIR_STATUS_NOT_EXIST;\n else\n return DISIR_STATUS_EXISTS;\n}\n\nenum disir_status\ndio_test_mold_read (struct disir_instance *instance, struct disir_register_plugin *plugin,\n const char *entry_id, struct disir_mold **mold)\n{\n enum disir_status status;\n output_mold func_mold;\n char namespace_entry[PATH_MAX];\n\n (void) &instance;\n (void) &plugin;\n (void) &entry_id;\n\n func_mold = molds[entry_id];\n if (func_mold == NULL)\n {\n\n if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n func_mold = molds[namespace_entry];\n if (func_mold == NULL)\n {\n return DISIR_STATUS_INVALID_ARGUMENT;\n }\n }\n\n status = func_mold (mold);\n if (status != DISIR_STATUS_OK)\n return status;\n\n return DISIR_STATUS_OK;;\n}\n\nenum disir_status\ndio_test_mold_entries (struct disir_instance *instance,\n struct disir_register_plugin *plugin, struct disir_entry **entries)\n{\n struct disir_entry *queue;\n struct disir_entry *entry;\n\n (void) &instance;\n (void) &plugin;\n\n\n queue = NULL;\n\n for (auto i = molds.begin(); i != molds.end(); ++i)\n {\n entry = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));\n if (entry == NULL)\n continue;\n\n entry->de_entry_name = strdup (i->first.c_str());\n entry->flag.DE_READABLE = 1;\n entry->flag.DE_WRITABLE = 1;\n if (i->first.back() == '\/')\n {\n entry->flag.DE_NAMESPACE_ENTRY = 1;\n }\n MQ_ENQUEUE (queue, entry);\n }\n\n *entries = queue;\n\n return DISIR_STATUS_OK;\n}\n\nenum disir_status\ndio_test_mold_query (struct disir_instance *instance, struct disir_register_plugin *plugin,\n const char *entry_id, struct disir_entry **entry)\n{\n char namespace_entry[PATH_MAX];\n\n (void) &instance;\n (void) &plugin;\n\n if (entry_id == NULL)\n return DISIR_STATUS_INTERNAL_ERROR;;\n\n std::string name(entry_id);\n if (molds.count (name) == 0)\n {\n if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)\n return DISIR_STATUS_NOT_EXIST;\n\n name = std::string (namespace_entry);\n \/\/ The namespace entry does not exist\n if (molds.count (name) == 0)\n {\n return DISIR_STATUS_NOT_EXIST;\n }\n }\n\n if (entry != NULL)\n {\n *entry = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));\n if (*entry == NULL)\n return DISIR_STATUS_NO_MEMORY;\n\n (*entry)->de_entry_name = strdup (name.c_str());\n (*entry)->flag.DE_READABLE = 1;\n (*entry)->flag.DE_WRITABLE = 1;\n if (name.back() == '\/')\n {\n (*entry)->flag.DE_NAMESPACE_ENTRY = 1;\n }\n }\n\n return DISIR_STATUS_EXISTS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"linenoise\/linenoise.h\"\n#include \"raptor.h\"\n#include \"routing\/raptor_api.h\"\n#include \"type\/data.h\"\n#include \"utils\/timer.h\"\n#include \"type\/response.pb.h\"\n#include \"routing_cli_utils.h\"\n#include \"ptreferential\/ptreferential_api.h\"\n#include <boost\/program_options.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include \"type\/pb_converter.h\"\n\nnamespace nr = navitia::routing;\nnamespace nt = navitia::type;\nnamespace bt = boost::posix_time;\nnamespace po = boost::program_options ;\nnamespace pb = pbnavitia;\n\nvoid completion(const char *buf, linenoiseCompletions *lc) {\n if (buf[0] == 'j' || buf[0] == '\\0') {\n linenoiseAddCompletion(lc,\"journey\");\n }\n if (buf[0] == 'p' || buf[0] == '\\0') {\n linenoiseAddCompletion(lc,\"ptref\");\n } \n}\n\/* This program takes a path to a nav.lz4 navitia's file\n * It will be loaded at the begginning of the program\n *\/\nint main(int argc, char **argv) {\n if (argc < 2) {\n std::cerr << \"A filename is needed\" << std::endl;\n return 1;\n }\n\n navitia::cli::compute_options compute_opt;\n compute_opt.load(argv[1]);\n po::variables_map vm;\n char *line;\n \/* Parse options, with --multiline we enable multi line editing. *\/\n linenoiseSetCompletionCallback(completion);\n linenoiseHistoryLoad(\"history.txt\"); \/* Load the history at startup *\/\n while((line = linenoise(\"hello> \")) != nullptr) {\n linenoiseHistoryAdd(line);\n linenoiseHistorySave(\"history.txt\");\n std::string str_line(line);\n auto splitted_line = po::split_unix(str_line);\n if (splitted_line.empty()) {\n continue;\n }\n if (splitted_line[0] == \"journey\") {\n po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), compute_opt.vm);\n po::notify(compute_opt.vm);\n compute_opt.compute();\n } else if (splitted_line[0] == \"ptref\") {\n if (splitted_line.size() < 2) {\n std::cerr << \"an ID is needed\" << std::endl;\n continue;\n }\n const std::string id = splitted_line[1];\n #define SHOW_ID_CLI(type_name, collection_name) \\\n auto collection_name##_map = compute_opt.data.pt_data->collection_name##_map;\\\n if ( collection_name##_map.find(id) != collection_name##_map.end()) {\\\n pbnavitia::type_name p;\\\n navitia::fill_pb_object(collection_name##_map.at(id), compute_opt.data, &p);\\\n std::cout << p.DebugString() << std::endl;}\n ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI)\n }\n }\n return 0;\n}\n<commit_msg>Cli: clear the vm map<commit_after>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"linenoise\/linenoise.h\"\n#include \"raptor.h\"\n#include \"routing\/raptor_api.h\"\n#include \"type\/data.h\"\n#include \"utils\/timer.h\"\n#include \"type\/response.pb.h\"\n#include \"routing_cli_utils.h\"\n#include \"ptreferential\/ptreferential_api.h\"\n#include <boost\/program_options.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include \"type\/pb_converter.h\"\n\nnamespace nr = navitia::routing;\nnamespace nt = navitia::type;\nnamespace bt = boost::posix_time;\nnamespace po = boost::program_options ;\nnamespace pb = pbnavitia;\n\nvoid completion(const char *buf, linenoiseCompletions *lc) {\n if (buf[0] == 'j' || buf[0] == '\\0') {\n linenoiseAddCompletion(lc,\"journey\");\n }\n if (buf[0] == 'p' || buf[0] == '\\0') {\n linenoiseAddCompletion(lc,\"ptref\");\n } \n}\n\/* This program takes a path to a nav.lz4 navitia's file\n * It will be loaded at the begginning of the program\n *\/\nint main(int argc, char **argv) {\n if (argc < 2) {\n std::cerr << \"A filename is needed\" << std::endl;\n return 1;\n }\n\n navitia::cli::compute_options compute_opt;\n compute_opt.load(argv[1]);\n po::variables_map vm;\n char *line;\n \/* Parse options, with --multiline we enable multi line editing. *\/\n linenoiseSetCompletionCallback(completion);\n linenoiseHistoryLoad(\"history.txt\"); \/* Load the history at startup *\/\n while((line = linenoise(\"hello> \")) != nullptr) {\n linenoiseHistoryAdd(line);\n linenoiseHistorySave(\"history.txt\");\n std::string str_line(line);\n auto splitted_line = po::split_unix(str_line);\n if (splitted_line.empty()) {\n continue;\n }\n if (splitted_line[0] == \"journey\") {\n compute_opt.vm.clear();\n po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), compute_opt.vm);\n po::notify(compute_opt.vm);\n compute_opt.compute();\n } else if (splitted_line[0] == \"ptref\") {\n if (splitted_line.size() < 2) {\n std::cerr << \"an ID is needed\" << std::endl;\n continue;\n }\n const std::string id = splitted_line[1];\n #define SHOW_ID_CLI(type_name, collection_name) \\\n auto collection_name##_map = compute_opt.data.pt_data->collection_name##_map;\\\n if ( collection_name##_map.find(id) != collection_name##_map.end()) {\\\n pbnavitia::type_name p;\\\n navitia::fill_pb_object(collection_name##_map.at(id), compute_opt.data, &p);\\\n std::cout << p.DebugString() << std::endl;}\n ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI)\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QSqlQuery>\n#include <QSqlRecord>\n#include <QSqlError>\n\n#include \"raster.h\"\n#include \"symboltable.h\"\n#include \"astnode.h\"\n#include \"idnode.h\"\n#include \"operationnode.h\"\n#include \"expressionnode.h\"\n#include \"symboltable.h\"\n#include \"formatter.h\"\n#include \"formatters.h\"\n#include \"scriptnode.h\"\n#include \"table.h\"\n#include \"featurecoverage.h\"\n#include \"feature.h\"\n#include \"numericrange.h\"\n#include \"numericdomain.h\"\n#include \"connectorinterface.h\"\n#include \"factory.h\"\n#include \"abstractfactory.h\"\n#include \"connectorfactory.h\"\n#include \"catalog.h\"\n#include \"mastercatalog.h\"\n#include \"ilwiscontext.h\"\n#include \"juliantime.h\"\n#include \"selectnode.h\"\n#include \"selectornode.h\"\n#include \"outparametersnode.h\"\n#include \"assignmentnode.h\"\n\nusing namespace Ilwis;\n\nAssignmentNode::AssignmentNode() : _defintion(false)\n{\n}\n\nbool AssignmentNode::isDefinition() const\n{\n return _defintion;\n}\n\nvoid AssignmentNode::setDefintion(bool yesno)\n{\n _defintion= yesno;\n}\n\nvoid AssignmentNode::setExpression(ASTNode *node)\n{\n _expression =QSharedPointer<ASTNode>(node);\n}\n\nQString AssignmentNode::nodeType() const\n{\n return \"assignment\";\n}\n\nIIlwisObject AssignmentNode::getObject(const Symbol& sym) const {\n IlwisTypes tp = sym._type;\n if ( tp & itRASTER)\n return sym._var.value<Ilwis::IRasterCoverage>().as<IlwisObject>();\n if ( tp & itFEATURE)\n return sym._var.value<Ilwis::IFeatureCoverage>().as<IlwisObject>();\n return IIlwisObject();\n\n}\n\nvoid AssignmentNode::getFormat(QSharedPointer<ASTNode>& node, QString& format, QString& fnamespace) const {\n Formatter *fnode = static_cast<Formatter *>(node->child(0).data());\n format = fnode->format();\n fnamespace = fnode->fnamespace();\n\n if ( format == \"\" || format == sUNDEF) {\n Formatter *fnode = ScriptNode::activeFormat(itRASTER);\n if ( fnode) {\n format = fnode->format();\n fnamespace = fnode->fnamespace();\n }\n }\n}\n\nvoid AssignmentNode::store2Format(QSharedPointer<ASTNode>& node, const Symbol& sym, const QString& result) {\n QString format, fnamespace;\n getFormat(node, format, fnamespace);\n if ( format != \"\" && format != sUNDEF) {\n Ilwis::IIlwisObject object = getObject(sym);\n bool wasAnonymous = object->isAnonymous();\n QUrl url = context()->workingCatalog()->source().url().toString() + \"\/\" + result;\n object->name(result);\n object->connectTo(url, format, fnamespace, Ilwis::IlwisObject::cmOUTPUT);\n object->createTime(Ilwis::Time::now());\n if ( wasAnonymous)\n mastercatalog()->addItems({object->source(IlwisObject::cmOUTPUT | IlwisObject::cmEXTENDED)});\n\n object->store({\"storemode\",Ilwis::IlwisObject::smMETADATA | Ilwis::IlwisObject::smBINARYDATA});\n\n }\n}\n\nbool AssignmentNode::evaluate(SymbolTable& symbols, int scope, ExecutionContext *ctx)\n{\n if ( _expression.isNull())\n return false;\n\n\n bool res = _expression->evaluate(symbols, scope, ctx);\n if ( res) {\n NodeValue val = _expression->value();\n for(int i = 0; i < val.size(); ++i) {\n Symbol sym = symbols.getSymbol(val.id(i),SymbolTable::gaREMOVEIFANON);\n IlwisTypes tp = sym.isValid() ? sym._type : itUNKNOWN;\n QString result = _outParms->id(i);\n QSharedPointer<ASTNode> specifier = _outParms->specifier(result);\n if ( !specifier.isNull()) {\n if ( specifier->noOfChilderen()!= 1)\n return ERROR2(ERR_NO_OBJECT_TYPE_FOR_2, \"Output object\", \"expression\");\n store2Format(specifier, sym, result);\n\n }\n if ( hasType(tp, itILWISOBJECT)) {\n bool ok;\n if ( hasType(tp, itRASTER)) {\n ok = copyObject<RasterCoverage>(sym, result,symbols);\n }\n else if hasType(tp, itFEATURE)\n ok = copyObject<FeatureCoverage>(sym, result,symbols);\n else if hasType(tp, itTABLE){\n ok = copyObject<Table>(sym, result,symbols,true);\n QSharedPointer<Selector> selector = _outParms->selector(result);\n if (!selector.isNull()){\n QString varName = selector->variable();\n ITable source = sym._var.value<ITable>();\n QString oldColName = ctx->_additionalInfo[source->name()].toString();\n QVariant newT= symbols.getValue(result);\n ITable newTable = newT.value<ITable>();\n ColumnDefinition coldef = newTable->columndefinition(oldColName);\n if ( coldef.isValid()){\n coldef.name(varName);\n newTable->columndefinition(coldef);\n }\n }\n }\n\n if(!ok) {\n throw ErrorObject(QString(TR(ERR_OPERATION_FAILID1).arg(\"assignment\")));\n }\n ctx->clear(true);\n ctx->_results.push_back(result);\n return ok;\n\n } else {\n sym = symbols.getSymbol(result,SymbolTable::gaREMOVEIFANON);\n tp = sym.isValid() ? sym._type : itUNKNOWN;\n if ( tp == itUNKNOWN) {\n tp = Domain::ilwType(val);\n }\n }\n ctx->clear();\n \/\/ symbols.addSymbol(result, scope, tp, _expression->value());\n ctx->addOutput(symbols,_expression->value(),result, tp, Resource());\n\n return true;\n }\n }\n return false;\n}\n\nvoid AssignmentNode::addOutputs(OutParametersNode *p)\n{\n _outParms.reset(p);\n}\n\nvoid AssignmentNode::setOutId(IDNode *idnode)\n{\n _outParms.reset(new OutParametersNode());\n _outParms->addResult(idnode);\n\n}\n\n\n<commit_msg>wierd syntax error that wasnt detected by the compiler<commit_after>#include <QSqlQuery>\n#include <QSqlRecord>\n#include <QSqlError>\n\n#include \"raster.h\"\n#include \"symboltable.h\"\n#include \"astnode.h\"\n#include \"idnode.h\"\n#include \"operationnode.h\"\n#include \"expressionnode.h\"\n#include \"symboltable.h\"\n#include \"formatter.h\"\n#include \"formatters.h\"\n#include \"scriptnode.h\"\n#include \"table.h\"\n#include \"featurecoverage.h\"\n#include \"feature.h\"\n#include \"numericrange.h\"\n#include \"numericdomain.h\"\n#include \"connectorinterface.h\"\n#include \"factory.h\"\n#include \"abstractfactory.h\"\n#include \"connectorfactory.h\"\n#include \"catalog.h\"\n#include \"mastercatalog.h\"\n#include \"ilwiscontext.h\"\n#include \"juliantime.h\"\n#include \"selectnode.h\"\n#include \"selectornode.h\"\n#include \"outparametersnode.h\"\n#include \"assignmentnode.h\"\n\nusing namespace Ilwis;\n\nAssignmentNode::AssignmentNode() : _defintion(false)\n{\n}\n\nbool AssignmentNode::isDefinition() const\n{\n return _defintion;\n}\n\nvoid AssignmentNode::setDefintion(bool yesno)\n{\n _defintion= yesno;\n}\n\nvoid AssignmentNode::setExpression(ASTNode *node)\n{\n _expression =QSharedPointer<ASTNode>(node);\n}\n\nQString AssignmentNode::nodeType() const\n{\n return \"assignment\";\n}\n\nIIlwisObject AssignmentNode::getObject(const Symbol& sym) const {\n IlwisTypes tp = sym._type;\n if ( tp & itRASTER)\n return sym._var.value<Ilwis::IRasterCoverage>().as<IlwisObject>();\n if ( tp & itFEATURE)\n return sym._var.value<Ilwis::IFeatureCoverage>().as<IlwisObject>();\n return IIlwisObject();\n\n}\n\nvoid AssignmentNode::getFormat(QSharedPointer<ASTNode>& node, QString& format, QString& fnamespace) const {\n Formatter *fnode = static_cast<Formatter *>(node->child(0).data());\n format = fnode->format();\n fnamespace = fnode->fnamespace();\n\n if ( format == \"\" || format == sUNDEF) {\n Formatter *fnode = ScriptNode::activeFormat(itRASTER);\n if ( fnode) {\n format = fnode->format();\n fnamespace = fnode->fnamespace();\n }\n }\n}\n\nvoid AssignmentNode::store2Format(QSharedPointer<ASTNode>& node, const Symbol& sym, const QString& result) {\n QString format, fnamespace;\n getFormat(node, format, fnamespace);\n if ( format != \"\" && format != sUNDEF) {\n Ilwis::IIlwisObject object = getObject(sym);\n bool wasAnonymous = object->isAnonymous();\n QUrl url = context()->workingCatalog()->source().url().toString() + \"\/\" + result;\n object->name(result);\n object->connectTo(url, format, fnamespace, Ilwis::IlwisObject::cmOUTPUT);\n object->createTime(Ilwis::Time::now());\n if ( wasAnonymous)\n mastercatalog()->addItems({object->source(IlwisObject::cmOUTPUT | IlwisObject::cmEXTENDED)});\n\n object->store({\"storemode\",Ilwis::IlwisObject::smMETADATA | Ilwis::IlwisObject::smBINARYDATA});\n\n }\n}\n\nbool AssignmentNode::evaluate(SymbolTable& symbols, int scope, ExecutionContext *ctx)\n{\n if ( _expression.isNull())\n return false;\n\n\n bool res = _expression->evaluate(symbols, scope, ctx);\n if ( res) {\n NodeValue val = _expression->value();\n for(int i = 0; i < val.size(); ++i) {\n Symbol sym = symbols.getSymbol(val.id(i),SymbolTable::gaREMOVEIFANON);\n IlwisTypes tp = sym.isValid() ? sym._type : itUNKNOWN;\n QString result = _outParms->id(i);\n QSharedPointer<ASTNode> specifier = _outParms->specifier(result);\n if ( !specifier.isNull()) {\n if ( specifier->noOfChilderen()!= 1)\n return ERROR2(ERR_NO_OBJECT_TYPE_FOR_2, \"Output object\", \"expression\");\n store2Format(specifier, sym, result);\n\n }\n if ( hasType(tp, itILWISOBJECT)) {\n bool ok;\n if ( hasType(tp, itRASTER)) {\n ok = copyObject<RasterCoverage>(sym, result,symbols);\n }\n else if (hasType(tp, itFEATURE))\n ok = copyObject<FeatureCoverage>(sym, result,symbols);\n else if (hasType(tp, itTABLE)){\n ok = copyObject<Table>(sym, result,symbols,true);\n QSharedPointer<Selector> selector = _outParms->selector(result);\n if (!selector.isNull()){\n QString varName = selector->variable();\n ITable source = sym._var.value<ITable>();\n QString oldColName = ctx->_additionalInfo[source->name()].toString();\n QVariant newT= symbols.getValue(result);\n ITable newTable = newT.value<ITable>();\n ColumnDefinition coldef = newTable->columndefinition(oldColName);\n if ( coldef.isValid()){\n coldef.name(varName);\n newTable->columndefinition(coldef);\n }\n }\n }\n\n if(!ok) {\n throw ErrorObject(QString(TR(ERR_OPERATION_FAILID1).arg(\"assignment\")));\n }\n ctx->clear(true);\n ctx->_results.push_back(result);\n return ok;\n\n } else {\n sym = symbols.getSymbol(result,SymbolTable::gaREMOVEIFANON);\n tp = sym.isValid() ? sym._type : itUNKNOWN;\n if ( tp == itUNKNOWN) {\n tp = Domain::ilwType(val);\n }\n }\n ctx->clear();\n \/\/ symbols.addSymbol(result, scope, tp, _expression->value());\n ctx->addOutput(symbols,_expression->value(),result, tp, Resource());\n\n return true;\n }\n }\n return false;\n}\n\nvoid AssignmentNode::addOutputs(OutParametersNode *p)\n{\n _outParms.reset(p);\n}\n\nvoid AssignmentNode::setOutId(IDNode *idnode)\n{\n _outParms.reset(new OutParametersNode());\n _outParms->addResult(idnode);\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- c++ -*-\n\n\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkOpenGLExtensionManager.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n Copyright 2003 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive\n license for use of this work by or on behalf of the\n U.S. Government. Redistribution and use in source and binary forms, with\n or without modification, are permitted provided that this Notice and any\n statement of authorship are reproduced on all copies.\n\n=========================================================================*\/\n\n#include \"vtkOpenGLExtensionManager.h\"\n#include \"vtkOpenGLExtensionManagerConfigure.h\"\n#include \"vtkgl.h\"\n\n#include \"vtkRenderWindow.h\"\n#include \"vtkObjectFactory.h\"\n\n#include <string.h>\n\n#include <vtkstd\/string>\n\n#ifdef VTK_DEFINE_GLX_GET_PROC_ADDRESS_PROTOTYPE\nextern \"C\" vtkglX::__GLXextFuncPtr glXGetProcAddressARB(const GLubyte *);\n#endif \/\/VTK_DEFINE_GLX_GET_PROC_ADDRESS_PROTOTYPE\n\n#ifdef VTK_USE_VTK_DYNAMIC_LOADER\n#include \"vtkDynamicLoader.h\"\n#include <vtkstd\/string>\n#include <vtkstd\/list>\n#endif\n\n#ifdef VTK_USE_APPLE_LOADER\n#include <mach-o\/dyld.h>\n#endif \/\/VTK_USE_APPLE_LOADER\n\n\/\/ GLU is currently not linked in VTK. We do not support it here.\n#define GLU_SUPPORTED 0\n\nvtkCxxRevisionMacro(vtkOpenGLExtensionManager, \"1.17\");\nvtkStandardNewMacro(vtkOpenGLExtensionManager);\n\nvtkOpenGLExtensionManager::vtkOpenGLExtensionManager()\n{\n this->RenderWindow = NULL;\n this->ExtensionsString = NULL;\n\n this->Modified();\n}\n\nvtkOpenGLExtensionManager::~vtkOpenGLExtensionManager()\n{\n this->SetRenderWindow(NULL);\n if (this->ExtensionsString)\n {\n delete[] this->ExtensionsString;\n }\n}\n\nvoid vtkOpenGLExtensionManager::PrintSelf(ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n\n os << indent << \"RenderWindow: (\" << this->RenderWindow << \")\" << endl;\n os << indent << \"BuildTime: \" << this->BuildTime << endl;\n os << indent << \"ExtensionsString: \"\n << (this->ExtensionsString ? this->ExtensionsString : \"(NULL)\") << endl;\n}\n\nvoid vtkOpenGLExtensionManager::SetRenderWindow(vtkRenderWindow *renwin)\n{\n if (renwin == this->RenderWindow)\n {\n return;\n }\n\n vtkDebugMacro(\"Setting RenderWindow to \" << renwin);\n\n if (this->RenderWindow)\n {\n this->RenderWindow->UnRegister(this);\n }\n\n this->RenderWindow = renwin;\n if (this->RenderWindow)\n {\n this->RenderWindow->Register(this);\n }\n\n this->Modified();\n}\n\nvoid vtkOpenGLExtensionManager::Update()\n{\n if (this->BuildTime > this->MTime)\n {\n return;\n }\n\n vtkDebugMacro(\"Update\");\n\n if (this->ExtensionsString)\n {\n delete[] this->ExtensionsString;\n this->ExtensionsString = NULL;\n }\n\n this->ReadOpenGLExtensions();\n\n this->BuildTime.Modified();\n}\n\nint vtkOpenGLExtensionManager::ExtensionSupported(const char *name)\n{\n this->Update();\n\n const char *p = this->ExtensionsString;\n int NameLen = strlen(name);\n int result = 0;\n\n for(;;)\n {\n int n;\n while (*p == ' ') p++;\n if (*p == '\\0')\n {\n result = 0;\n break;\n }\n n = strcspn(p, \" \");\n if ((NameLen == n) && (strncmp(name, p, n) == 0))\n {\n result = 1;\n break;\n }\n p += n;\n }\n return result;\n}\n\nvtkOpenGLExtensionManagerFunctionPointer\nvtkOpenGLExtensionManager::GetProcAddress(const char *fname)\n{\n vtkDebugMacro(<< \"Trying to load OpenGL function \" << fname);\n\n#ifdef VTK_USE_WGL_GET_PROC_ADDRESS\n return reinterpret_cast<vtkOpenGLExtensionManagerFunctionPointer>(wglGetProcAddress(fname));\n#endif \/\/VTK_USE_WGL_GET_PROC_ADDRESS\n\n\n#ifdef VTK_USE_APPLE_LOADER\n NSSymbol symbol = NULL;\n char *mangled_fname = new char[strlen(fname)+2];\n \/\/ Prepend a '_' to the function name.\n strcpy(mangled_fname+1, fname);\n mangled_fname[0] = '_';\n if (NSIsSymbolNameDefined(mangled_fname))\n {\n symbol = NSLookupAndBindSymbol(mangled_fname);\n }\n else\n {\n vtkDebugMacro(\"Could not load \" << mangled_fname);\n }\n delete[] mangled_fname;\n if (symbol)\n {\n return (vtkOpenGLExtensionManagerFunctionPointer)NSAddressOfSymbol(symbol);\n }\n else\n {\n vtkDebugMacro(\"Could not load \" << mangled_fname);\n return NULL;\n }\n#endif \/\/VTK_USE_APPLE_LOADER\n\n\n#ifdef VTK_USE_GLX_GET_PROC_ADDRESS\n return (vtkOpenGLExtensionManagerFunctionPointer)glXGetProcAddress((const GLubyte *)fname);\n#endif \/\/VTK_USE_GLX_GET_PROC_ADDRESS\n#ifdef VTK_USE_GLX_GET_PROC_ADDRESS_ARB\n return (vtkOpenGLExtensionManagerFunctionPointer)glXGetProcAddressARB((const GLubyte *)fname);\n#endif \/\/VTK_USE_GLX_GET_PROC_ADDRESS_ARB\n\n\n#ifdef VTK_USE_VTK_DYNAMIC_LOADER\n \/\/ If the GLX implementation cannot load procedures for us, load them\n \/\/ directly from the dynamic libraries.\n static vtkstd::list<vtkstd::string> ogl_libraries;\n\n if (ogl_libraries.empty())\n {\n const char *ext = vtkDynamicLoader::LibExtension();\n vtkstd::string::size_type ext_size = strlen(ext);\n \/\/ Must be the first function we tried to load. Fill this list with\n \/\/ the OpenGL libraries we linked against.\n vtkstd::string l(OPENGL_LIBRARIES);\n vtkstd::string::size_type filename_start = 0;\n while (1)\n {\n vtkstd::string::size_type filename_end = l.find(';', filename_start);\n if (filename_end == vtkstd::string::npos)\n {\n break;\n }\n vtkstd::string possible_file = l.substr(filename_start,\n filename_end-filename_start);\n \/\/ Make sure this is actually a library. Do this by making sure it\n \/\/ has an appropriate extension. This is by no means definitive, but\n \/\/ it1 should do.\n if ( (possible_file.length() > ext_size)\n && (possible_file.substr(possible_file.length()-ext_size) == ext) )\n {\n ogl_libraries.push_back(possible_file);\n }\n\n filename_start = filename_end + 1;\n }\n }\n\n \/\/ Look for the function in each library.\n for (vtkstd::list<vtkstd::string>::iterator i = ogl_libraries.begin();\n i != ogl_libraries.end(); i++)\n {\n vtkLibHandle lh = vtkDynamicLoader::OpenLibrary((*i).c_str());\n void *f = vtkDynamicLoader::GetSymbolAddress(lh, fname);\n vtkDynamicLoader::CloseLibrary(lh);\n if (f) return (vtkOpenGLExtensionManagerFunctionPointer)f;\n }\n\n \/\/ Could not find the function.\n return NULL;\n#endif \/\/VTK_USE_VTK_DYNAMIC_LOADER\n\n#ifdef VTK_NO_EXTENSION_LOADING\n return NULL;\n#endif \/\/VTK_NO_EXTENSION_LOADING\n}\n\nvoid vtkOpenGLExtensionManager::LoadExtension(const char *name)\n{\n if (!this->ExtensionSupported(name))\n {\n vtkWarningMacro(\"Attempting to load \" << name\n << \", which is not supported.\");\n }\n\n int success = vtkgl::LoadExtension(name, this);\n\n if (!success)\n {\n vtkErrorMacro(\"Extension \" << name << \" could not be loaded.\");\n }\n}\n\nvoid vtkOpenGLExtensionManager::ReadOpenGLExtensions()\n{\n vtkDebugMacro(\"ReadOpenGLExtensions\");\n\n#ifdef VTK_NO_EXTENSION_LOADING\n\n this->ExtensionsString = new char[1];\n this->ExtensionsString[0] = '\\0';\n return;\n\n#else \/\/!VTK_NO_EXTENSION_LOADING\n\n if (this->RenderWindow)\n {\n if (!this->RenderWindow->IsA(\"vtkOpenGLRenderWindow\"))\n {\n \/\/ If the render window is not OpenGL, then it obviously has no\n \/\/ extensions.\n this->ExtensionsString = new char[1];\n this->ExtensionsString[0] = '\\0';\n return;\n }\n if (this->RenderWindow->GetNeverRendered())\n {\n this->RenderWindow->Render();\n }\n this->RenderWindow->MakeCurrent();\n }\n\n vtkstd::string extensions_string;\n\n const char *gl_extensions;\n const char *glu_extensions = \"\";\n const char *win_extensions;\n\n gl_extensions = (const char *)glGetString(GL_EXTENSIONS);\n\n if (gl_extensions == NULL)\n {\n gl_extensions = \"\";\n }\n\n if (!this->RenderWindow && (gl_extensions[0] == '\\0'))\n {\n vtkDebugMacro(\"No window active? Attaching default render window.\");\n vtkRenderWindow *renwin = vtkRenderWindow::New();\n renwin->SetSize(1, 1);\n this->SetRenderWindow(renwin);\n renwin->Delete();\n this->ReadOpenGLExtensions();\n return;\n }\n\n extensions_string = gl_extensions;\n\n#if GLU_SUPPORTED\n glu_extensions = (const char *)gluGetString(GLU_EXTENSIONS);\n#endif\n if (glu_extensions != NULL)\n {\n extensions_string += \" \";\n extensions_string += glu_extensions;\n }\n\n#if defined(WIN32)\n \/\/ Don't use this->LoadExtension or we will go into an infinite loop.\n vtkgl::LoadExtension(\"WGL_ARB_extensions_string\", this);\n if (vtkwgl::GetExtensionsStringARB)\n {\n win_extensions = vtkwgl::GetExtensionsStringARB(wglGetCurrentDC());\n }\n else\n {\n \/\/vtkWarningMacro(\"Could not query WGL extensions.\");\n win_extensions = \"\";\n }\n#elif defined(__APPLE__)\n\/\/ vtkWarningMacro(\"Does APPLE have a windows extension string?\");\n win_extensions = \"\";\n#else\n win_extensions = glXGetClientString(glXGetCurrentDisplay(),\n GLX_EXTENSIONS);\n#endif\n\n if (win_extensions != NULL)\n {\n extensions_string += \" \";\n extensions_string += win_extensions;\n }\n\n \/\/ We build special extension identifiers for OpenGL versions. Check to\n \/\/ see which are supported.\n vtkstd::string version_extensions;\n vtkstd::string::size_type beginpos, endpos;\n\n version_extensions = vtkgl::GLVersionExtensionsString();\n endpos = 0;\n while (endpos != vtkstd::string::npos)\n {\n beginpos = version_extensions.find_first_not_of(' ', endpos);\n if (beginpos == vtkstd::string::npos) break;\n endpos = version_extensions.find_first_of(' ', beginpos);\n\n vtkstd::string ve = version_extensions.substr(beginpos, endpos-beginpos);\n if (vtkgl::LoadExtension(ve.c_str(), this))\n {\n extensions_string += \" \";\n extensions_string += ve;\n }\n }\n\n#ifdef VTK_USE_X\n version_extensions = vtkgl::GLXVersionExtensionsString();\n endpos = 0;\n while (endpos != vtkstd::string::npos)\n {\n beginpos = version_extensions.find_first_not_of(' ', endpos);\n if (beginpos == vtkstd::string::npos) break;\n endpos = version_extensions.find_first_of(' ', beginpos);\n\n vtkstd::string ve = version_extensions.substr(beginpos, endpos-beginpos);\n if (vtkgl::LoadExtension(ve.c_str(), this))\n {\n extensions_string += \" \";\n extensions_string += ve;\n }\n }\n#endif \/\/VTK_USE_X\n\n \/\/ Store extensions string.\n this->ExtensionsString = new char[extensions_string.length()+1];\n strcpy(this->ExtensionsString, extensions_string.c_str());\n\n#endif \/\/!VTK_NO_EXTENSION_LOADING\n}\n<commit_msg><commit_after>\/\/ -*- c++ -*-\n\n\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkOpenGLExtensionManager.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n Copyright 2003 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive\n license for use of this work by or on behalf of the\n U.S. Government. Redistribution and use in source and binary forms, with\n or without modification, are permitted provided that this Notice and any\n statement of authorship are reproduced on all copies.\n\n=========================================================================*\/\n\n#include \"vtkOpenGLExtensionManager.h\"\n#include \"vtkOpenGLExtensionManagerConfigure.h\"\n#include \"vtkgl.h\"\n\n#include \"vtkRenderWindow.h\"\n#include \"vtkObjectFactory.h\"\n\n#include <string.h>\n\n#include <vtkstd\/string>\n\n#ifdef VTK_DEFINE_GLX_GET_PROC_ADDRESS_PROTOTYPE\nextern \"C\" vtkglX::__GLXextFuncPtr glXGetProcAddressARB(const GLubyte *);\n#endif \/\/VTK_DEFINE_GLX_GET_PROC_ADDRESS_PROTOTYPE\n\n#ifdef VTK_USE_VTK_DYNAMIC_LOADER\n#include \"vtkDynamicLoader.h\"\n#include <vtkstd\/string>\n#include <vtkstd\/list>\n#endif\n\n#ifdef VTK_USE_APPLE_LOADER\n#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3\n#include <dlfcn.h>\n#else\n#include <mach-o\/dyld.h>\n#endif\n#endif \/\/VTK_USE_APPLE_LOADER\n\n\/\/ GLU is currently not linked in VTK. We do not support it here.\n#define GLU_SUPPORTED 0\n\nvtkCxxRevisionMacro(vtkOpenGLExtensionManager, \"1.18\");\nvtkStandardNewMacro(vtkOpenGLExtensionManager);\n\nvtkOpenGLExtensionManager::vtkOpenGLExtensionManager()\n{\n this->RenderWindow = NULL;\n this->ExtensionsString = NULL;\n\n this->Modified();\n}\n\nvtkOpenGLExtensionManager::~vtkOpenGLExtensionManager()\n{\n this->SetRenderWindow(NULL);\n if (this->ExtensionsString)\n {\n delete[] this->ExtensionsString;\n }\n}\n\nvoid vtkOpenGLExtensionManager::PrintSelf(ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n\n os << indent << \"RenderWindow: (\" << this->RenderWindow << \")\" << endl;\n os << indent << \"BuildTime: \" << this->BuildTime << endl;\n os << indent << \"ExtensionsString: \"\n << (this->ExtensionsString ? this->ExtensionsString : \"(NULL)\") << endl;\n}\n\nvoid vtkOpenGLExtensionManager::SetRenderWindow(vtkRenderWindow *renwin)\n{\n if (renwin == this->RenderWindow)\n {\n return;\n }\n\n vtkDebugMacro(\"Setting RenderWindow to \" << renwin);\n\n if (this->RenderWindow)\n {\n this->RenderWindow->UnRegister(this);\n }\n\n this->RenderWindow = renwin;\n if (this->RenderWindow)\n {\n this->RenderWindow->Register(this);\n }\n\n this->Modified();\n}\n\nvoid vtkOpenGLExtensionManager::Update()\n{\n if (this->BuildTime > this->MTime)\n {\n return;\n }\n\n vtkDebugMacro(\"Update\");\n\n if (this->ExtensionsString)\n {\n delete[] this->ExtensionsString;\n this->ExtensionsString = NULL;\n }\n\n this->ReadOpenGLExtensions();\n\n this->BuildTime.Modified();\n}\n\nint vtkOpenGLExtensionManager::ExtensionSupported(const char *name)\n{\n this->Update();\n\n const char *p = this->ExtensionsString;\n int NameLen = strlen(name);\n int result = 0;\n\n for(;;)\n {\n int n;\n while (*p == ' ') p++;\n if (*p == '\\0')\n {\n result = 0;\n break;\n }\n n = strcspn(p, \" \");\n if ((NameLen == n) && (strncmp(name, p, n) == 0))\n {\n result = 1;\n break;\n }\n p += n;\n }\n return result;\n}\n\nvtkOpenGLExtensionManagerFunctionPointer\nvtkOpenGLExtensionManager::GetProcAddress(const char *fname)\n{\n vtkDebugMacro(<< \"Trying to load OpenGL function \" << fname);\n\n#ifdef VTK_USE_WGL_GET_PROC_ADDRESS\n return reinterpret_cast<vtkOpenGLExtensionManagerFunctionPointer>(wglGetProcAddress(fname));\n#endif \/\/VTK_USE_WGL_GET_PROC_ADDRESS\n\n\n#ifdef VTK_USE_APPLE_LOADER\n\n#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3\n \n void* globalsymbolobject = dlopen(NULL, RTLD_GLOBAL);\n if(globalsymbolobject)\n {\n void* dlsymbol = dlsym(globalsymbolobject, fname);\n dlclose(globalsymbolobject);\n if(!dlsymbol)\n {\n vtkDebugMacro(\"Could not load \" << fname);\n }\n return (vtkOpenGLExtensionManagerFunctionPointer)(dlsymbol);\n }\n else\n {\n vtkDebugMacro(\"Could not load \" << fname);\n return NULL;\n }\n\n#else\n \n NSSymbol symbol = NULL;\n char *mangled_fname = new char[strlen(fname)+2];\n \/\/ Prepend a '_' to the function name.\n strcpy(mangled_fname+1, fname);\n mangled_fname[0] = '_';\n if (NSIsSymbolNameDefined(mangled_fname))\n {\n symbol = NSLookupAndBindSymbol(mangled_fname);\n }\n else\n {\n vtkDebugMacro(\"Could not load \" << mangled_fname);\n }\n delete[] mangled_fname;\n if (symbol)\n {\n return (vtkOpenGLExtensionManagerFunctionPointer)NSAddressOfSymbol(symbol);\n }\n else\n {\n vtkDebugMacro(\"Could not load \" << mangled_fname);\n return NULL;\n }\n\n#endif \/\/MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3\n#endif \/\/VTK_USE_APPLE_LOADER\n\n\n#ifdef VTK_USE_GLX_GET_PROC_ADDRESS\n return (vtkOpenGLExtensionManagerFunctionPointer)glXGetProcAddress((const GLubyte *)fname);\n#endif \/\/VTK_USE_GLX_GET_PROC_ADDRESS\n#ifdef VTK_USE_GLX_GET_PROC_ADDRESS_ARB\n return (vtkOpenGLExtensionManagerFunctionPointer)glXGetProcAddressARB((const GLubyte *)fname);\n#endif \/\/VTK_USE_GLX_GET_PROC_ADDRESS_ARB\n\n\n#ifdef VTK_USE_VTK_DYNAMIC_LOADER\n \/\/ If the GLX implementation cannot load procedures for us, load them\n \/\/ directly from the dynamic libraries.\n static vtkstd::list<vtkstd::string> ogl_libraries;\n\n if (ogl_libraries.empty())\n {\n const char *ext = vtkDynamicLoader::LibExtension();\n vtkstd::string::size_type ext_size = strlen(ext);\n \/\/ Must be the first function we tried to load. Fill this list with\n \/\/ the OpenGL libraries we linked against.\n vtkstd::string l(OPENGL_LIBRARIES);\n vtkstd::string::size_type filename_start = 0;\n while (1)\n {\n vtkstd::string::size_type filename_end = l.find(';', filename_start);\n if (filename_end == vtkstd::string::npos)\n {\n break;\n }\n vtkstd::string possible_file = l.substr(filename_start,\n filename_end-filename_start);\n \/\/ Make sure this is actually a library. Do this by making sure it\n \/\/ has an appropriate extension. This is by no means definitive, but\n \/\/ it1 should do.\n if ( (possible_file.length() > ext_size)\n && (possible_file.substr(possible_file.length()-ext_size) == ext) )\n {\n ogl_libraries.push_back(possible_file);\n }\n\n filename_start = filename_end + 1;\n }\n }\n\n \/\/ Look for the function in each library.\n for (vtkstd::list<vtkstd::string>::iterator i = ogl_libraries.begin();\n i != ogl_libraries.end(); i++)\n {\n vtkLibHandle lh = vtkDynamicLoader::OpenLibrary((*i).c_str());\n void *f = vtkDynamicLoader::GetSymbolAddress(lh, fname);\n vtkDynamicLoader::CloseLibrary(lh);\n if (f) return (vtkOpenGLExtensionManagerFunctionPointer)f;\n }\n\n \/\/ Could not find the function.\n return NULL;\n#endif \/\/VTK_USE_VTK_DYNAMIC_LOADER\n\n#ifdef VTK_NO_EXTENSION_LOADING\n return NULL;\n#endif \/\/VTK_NO_EXTENSION_LOADING\n}\n\nvoid vtkOpenGLExtensionManager::LoadExtension(const char *name)\n{\n if (!this->ExtensionSupported(name))\n {\n vtkWarningMacro(\"Attempting to load \" << name\n << \", which is not supported.\");\n }\n\n int success = vtkgl::LoadExtension(name, this);\n\n if (!success)\n {\n vtkErrorMacro(\"Extension \" << name << \" could not be loaded.\");\n }\n}\n\nvoid vtkOpenGLExtensionManager::ReadOpenGLExtensions()\n{\n vtkDebugMacro(\"ReadOpenGLExtensions\");\n\n#ifdef VTK_NO_EXTENSION_LOADING\n\n this->ExtensionsString = new char[1];\n this->ExtensionsString[0] = '\\0';\n return;\n\n#else \/\/!VTK_NO_EXTENSION_LOADING\n\n if (this->RenderWindow)\n {\n if (!this->RenderWindow->IsA(\"vtkOpenGLRenderWindow\"))\n {\n \/\/ If the render window is not OpenGL, then it obviously has no\n \/\/ extensions.\n this->ExtensionsString = new char[1];\n this->ExtensionsString[0] = '\\0';\n return;\n }\n if (this->RenderWindow->GetNeverRendered())\n {\n this->RenderWindow->Render();\n }\n this->RenderWindow->MakeCurrent();\n }\n\n vtkstd::string extensions_string;\n\n const char *gl_extensions;\n const char *glu_extensions = \"\";\n const char *win_extensions;\n\n gl_extensions = (const char *)glGetString(GL_EXTENSIONS);\n\n if (gl_extensions == NULL)\n {\n gl_extensions = \"\";\n }\n\n if (!this->RenderWindow && (gl_extensions[0] == '\\0'))\n {\n vtkDebugMacro(\"No window active? Attaching default render window.\");\n vtkRenderWindow *renwin = vtkRenderWindow::New();\n renwin->SetSize(1, 1);\n this->SetRenderWindow(renwin);\n renwin->Delete();\n this->ReadOpenGLExtensions();\n return;\n }\n\n extensions_string = gl_extensions;\n\n#if GLU_SUPPORTED\n glu_extensions = (const char *)gluGetString(GLU_EXTENSIONS);\n#endif\n if (glu_extensions != NULL)\n {\n extensions_string += \" \";\n extensions_string += glu_extensions;\n }\n\n#if defined(WIN32)\n \/\/ Don't use this->LoadExtension or we will go into an infinite loop.\n vtkgl::LoadExtension(\"WGL_ARB_extensions_string\", this);\n if (vtkwgl::GetExtensionsStringARB)\n {\n win_extensions = vtkwgl::GetExtensionsStringARB(wglGetCurrentDC());\n }\n else\n {\n \/\/vtkWarningMacro(\"Could not query WGL extensions.\");\n win_extensions = \"\";\n }\n#elif defined(__APPLE__)\n\/\/ vtkWarningMacro(\"Does APPLE have a windows extension string?\");\n win_extensions = \"\";\n#else\n win_extensions = glXGetClientString(glXGetCurrentDisplay(),\n GLX_EXTENSIONS);\n#endif\n\n if (win_extensions != NULL)\n {\n extensions_string += \" \";\n extensions_string += win_extensions;\n }\n\n \/\/ We build special extension identifiers for OpenGL versions. Check to\n \/\/ see which are supported.\n vtkstd::string version_extensions;\n vtkstd::string::size_type beginpos, endpos;\n\n version_extensions = vtkgl::GLVersionExtensionsString();\n endpos = 0;\n while (endpos != vtkstd::string::npos)\n {\n beginpos = version_extensions.find_first_not_of(' ', endpos);\n if (beginpos == vtkstd::string::npos) break;\n endpos = version_extensions.find_first_of(' ', beginpos);\n\n vtkstd::string ve = version_extensions.substr(beginpos, endpos-beginpos);\n if (vtkgl::LoadExtension(ve.c_str(), this))\n {\n extensions_string += \" \";\n extensions_string += ve;\n }\n }\n\n#ifdef VTK_USE_X\n version_extensions = vtkgl::GLXVersionExtensionsString();\n endpos = 0;\n while (endpos != vtkstd::string::npos)\n {\n beginpos = version_extensions.find_first_not_of(' ', endpos);\n if (beginpos == vtkstd::string::npos) break;\n endpos = version_extensions.find_first_of(' ', beginpos);\n\n vtkstd::string ve = version_extensions.substr(beginpos, endpos-beginpos);\n if (vtkgl::LoadExtension(ve.c_str(), this))\n {\n extensions_string += \" \";\n extensions_string += ve;\n }\n }\n#endif \/\/VTK_USE_X\n\n \/\/ Store extensions string.\n this->ExtensionsString = new char[extensions_string.length()+1];\n strcpy(this->ExtensionsString, extensions_string.c_str());\n\n#endif \/\/!VTK_NO_EXTENSION_LOADING\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashGraph.\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#include <signal.h>\n#ifdef PROFILER\n#include <gperftools\/profiler.h>\n#endif\n\n#include \"stat.h\"\n#include \"FGlib.h\"\n#include \"graph.h\"\n\nvoid int_handler(int sig_num)\n{\n#ifdef PROFILER\n\tif (!graph_conf.get_prof_file().empty())\n\t\tProfilerStop();\n#endif\n\texit(0);\n}\n\nvoid print_usage()\n{\n\tfprintf(stderr,\n\t\t\t\"cc [options] conf_file graph_file index_file\\n\");\n\tfprintf(stderr, \"-c confs: add more configurations to the system\\n\");\n\tfprintf(stderr, \"-s size: the output min component size\\n\");\n\tfprintf(stderr, \"-o file: output the component size to the file\\n\");\n\tfprintf(stderr, \"-t: the type of connected components\\n\");\n\tgraph_conf.print_help();\n\tparams.print_help();\n}\n\nint main(int argc, char *argv[])\n{\n\tint opt;\n\tstd::string confs;\n\tstd::string output_file;\n\tsize_t min_comp_size = 0;\n\tint num_opts = 0;\n\tstd::string type = \"wcc\";\n\twhile ((opt = getopt(argc, argv, \"c:s:o:t:\")) != -1) {\n\t\tnum_opts++;\n\t\tswitch (opt) {\n\t\t\tcase 'c':\n\t\t\t\tconfs = optarg;\n\t\t\t\tnum_opts++;\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tmin_comp_size = atoi(optarg);\n\t\t\t\tnum_opts++;\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\toutput_file = optarg;\n\t\t\t\tnum_opts++;\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\ttype = optarg;\n\t\t\t\tnum_opts++;\n\t\t\tdefault:\n\t\t\t\tprint_usage();\n\t\t}\n\t}\n\targv += 1 + num_opts;\n\targc -= 1 + num_opts;\n\n\tif (argc < 3) {\n\t\tprint_usage();\n\t\texit(-1);\n\t}\n\n\tstd::string conf_file = argv[0];\n\tstd::string graph_file = argv[1];\n\tstd::string index_file = argv[2];\n\n\tconfig_map::ptr configs = config_map::create(conf_file);\n\tassert(configs);\n\tconfigs->add_options(confs);\n\n\tsignal(SIGINT, int_handler);\n\n\tFG_graph::ptr graph = FG_graph::create(graph_file, index_file, configs);\n\tFG_vector<vertex_id_t>::ptr comp_ids;\n\tif (type == \"wcc\")\n\t\tcomp_ids = compute_wcc(graph);\n\telse if (type == \"scc\")\n\t\tcomp_ids = compute_scc(graph);\n\telse\n\t\tassert(0);\n\n\tcount_map<vertex_id_t> map;\n\tcomp_ids->count_unique(map);\n\tstd::pair<vertex_id_t, size_t> max_comp = map.get_max_count();\n\tprintf(\"There are %ld components, and largest comp has %ld vertices\\n\",\n\t\t\tmap.get_size(), max_comp.second);\n\n\tstruct large_comp_apply\n\t{\n\t\tstd::set<vertex_id_t> &large_comps;\n\t\tvsize_t threshold;\n\t\tlarge_comp_apply(std::set<vertex_id_t> &_comps,\n\t\t\t\tvsize_t threshold): large_comps(_comps) {\n\t\t\tthis->threshold = threshold;\n\t\t}\n\n\t\tvoid operator()(const std::pair<vertex_id_t, size_t> &v) {\n\t\t\tif (v.second >= threshold)\n\t\t\t\tlarge_comps.insert(v.first);\n\t\t}\n\t};\n\n\tstd::set<vertex_id_t> wanted_comps;\n\tmap.apply(large_comp_apply(wanted_comps, min_comp_size));\n\t\/\/ We ignore the largest component.\n\twanted_comps.erase(max_comp.first);\n\tprintf(\"There are %ld components of the size larger than %ld\\n\",\n\t\t\twanted_comps.size() + 1, min_comp_size);\n\n\tif (!output_file.empty()) {\n\t\tFILE *f = fopen(output_file.c_str(), \"w\");\n\t\tif (f == NULL) {\n\t\t\tperror(\"fopen\");\n\t\t\tassert(0);\n\t\t}\n\n\t\tstd::map<vertex_id_t, graph::ptr> clusters;\n\t\tfetch_subgraphs(graph, comp_ids, wanted_comps, clusters);\n\n\t\ttypedef std::map<vertex_id_t, std::pair<size_t, size_t> > size_map_t;\n\t\tsize_map_t cluster_sizes;\n\t\tcompute_subgraph_sizes(graph, comp_ids, wanted_comps, cluster_sizes);\n\n\t\tBOOST_FOREACH(size_map_t::value_type v, cluster_sizes) {\n\t\t\tstd::map<vertex_id_t, graph::ptr>::const_iterator it\n\t\t\t\t= clusters.find(v.first);\n\t\t\tBOOST_VERIFY(it != clusters.end());\n\t\t\tBOOST_VERIFY(v.second.first == it->second->get_num_vertices());\n\t\t\tBOOST_VERIFY(v.second.second == it->second->get_num_edges());\n\t\t\tfprintf(f, \"comp %u: %ld, %ld\\n\", v.first, v.second.first,\n\t\t\t\t\tv.second.second);\n\t\t}\n\n\t\tfclose(f);\n\n\t\ttypedef std::pair<vertex_id_t, directed_graph<>::ptr> id_graph_t;\n\t\tBOOST_FOREACH(id_graph_t v, clusters) {\n\t\t\tv.second->dump_as_edge_list(output_file\n\t\t\t\t\t+ \"-\" + ltoa(v.first));\n\t\t}\n\t}\n}\n<commit_msg>[Graph]: delete test_cc.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n========================= Cpp Console Table\n| Cpp | Console | Table | version 1.0.0\n========================= https:\/\/github.com\/Oradle\/CppConsoleTable\n\nLicensed under the MIT License <http:\/\/opensource.org\/licenses\/MIT>.\nCopyright (c) 2017 Oradle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#pragma once\n#ifndef _CPP_CONSOLE_TABLE_\n#define _CPP_CONSOLE_TABLE_\n\n#include <iostream>\n#include <map>\n#include <string>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nnamespace samilton {\n\t\/\/ force declaration\n\tclass ConsoleTable;\n\n\tclass ConsoleString {\n\tpublic:\n\t\tConsoleString &operator=(const std::string &val) {\n\t\t\t_str = val;\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const char *val) {\n\t\t\t_str = val;\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const long &val) {\n\t\t\t_str = std::to_string(val);\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const int &val) {\n\t\t\t_str = std::to_string(val);\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const double &val) {\n\t\t\t_str = std::to_string(val);\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const float &val) {\n\t\t\t_str = std::to_string(val);\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const bool &val) {\n\t\t\tif (val)\n\t\t\t\t_str = \"true\";\n\t\t\telse\n\t\t\t\t_str = \"false\";\n\n\t\t\treturn *this;\n\t\t}\n\tprivate:\n\t\tfriend std::ostream &operator<<(std::ostream &stream, ConsoleTable &table);\n\n\t\tstd::string _str;\n\t};\n\n\tclass ConsoleRow {\n\tpublic:\n\t\t~ConsoleRow() {\n\t\t\tfor (auto &element : _rowData) {\n\t\t\t\tdelete element.second;\n\t\t\t}\n\t\t}\n\n\t\tConsoleString &operator[](const size_t &column) {\n\t\t\ttry {\n\t\t\t\treturn *_rowData.at(column);\n\t\t\t}\n\t\t\tcatch (...) {\n\t\t\t\t_rowData[column] = new ConsoleString;\n\t\t\t\treturn *_rowData[column];\n\t\t\t}\n\t\t}\n\tprivate:\n\t\tfriend std::ostream &operator<<(std::ostream &stream, ConsoleTable &table);\n\n\t\tstd::map<size_t, ConsoleString*> _rowData;\n\t};\n\n\tclass ConsoleTable {\n\tpublic:\n\t\tenum class Alignment {\n\t\t\tleft = 0,\n\t\t\tcentre,\n\t\t\tright\n\t\t};\n\n\t\tstruct TableChars {\n\t\t\tchar topRight = 187, topLeft = 201, downRight = 188, downLeft = 200;\n\t\t\tchar topDownSimple = 205, topSeparation = 203, downSeparation = 202;\n\t\t\tchar leftRightSimple = 186, leftSeparation = 204, rightSeparation = 185;\n\t\t\tchar centreSeparation = 206;\n\t\t};\n\n\t\tConsoleTable() {\n\t\t\t_alignment = Alignment::left;\n\t\t\t_leftIndent = 0;\n\t\t\t_rightIndent = 0;\n\t\t}\n\n\t\tConsoleTable(const Alignment &alignment) {\n\t\t\t_alignment = alignment;\n\t\t\t_leftIndent = 0;\n\t\t\t_rightIndent = 0;\n\t\t}\n\n\t\tConsoleTable(const size_t &leftIndent, const size_t &rightIndent, const Alignment &alignment = Alignment::left) {\n\t\t\t_leftIndent = leftIndent;\n\t\t\t_rightIndent = rightIndent;\n\t\t\t_alignment = alignment;\n\t\t}\n\n\t\t~ConsoleTable() {\n\t\t\tfor (auto &element : _tableData) {\n\t\t\t\tdelete element.second;\n\t\t\t}\n\t\t}\n\n\t\tvoid setAlignment(const Alignment &alignment) {\n\t\t\t_alignment = alignment;\n\t\t}\n\n\t\tvoid setIndent(const size_t &leftIndent, const size_t &rightIndent)\n\t\t{\n\t\t\t_leftIndent = leftIndent;\n\t\t\t_rightIndent = rightIndent;\n\t\t}\n\n\t\tvoid setTableChars(const TableChars &chars) {\n\t\t\t_chars = chars;\n\t\t}\n\n\t\tConsoleRow &operator[](const size_t &row) {\n\t\t\ttry {\n\t\t\t\treturn *_tableData.at(row);\n\t\t\t}\n\t\t\tcatch (...) {\n\t\t\t\t_tableData[row] = new ConsoleRow;\n\t\t\t\treturn *_tableData[row];\n\t\t\t}\n\t\t}\n\n\t\tfriend std::ostream &operator<<(std::ostream &stream, ConsoleTable &table);\n\tprivate:\n\t\tvoid _fillStreamByChar(std::ostream &stream, const char &fillChar, const size_t &lenght) {\n\t\t\tif (lenght > 0)\n\t\t\t\tstream << std::setfill(fillChar) << std::setw(lenght);\n\t\t}\n\n\t\tvoid _fillStreamByChar(std::ostream &stream, const char &fillChar, const char &endChar, const size_t &lenght) {\n\t\t\tif (lenght > 0)\n\t\t\t\tstream << std::setfill(fillChar) << std::setw(lenght) << endChar;\n\t\t}\n\n\t\tTableChars _chars;\n\t\tstd::map<size_t, ConsoleRow*> _tableData;\n\t\tAlignment _alignment;\n\t\tsize_t _leftIndent, _rightIndent;\n\t};\n\n\tinline std::ostream &operator<<(std::ostream &stream, ConsoleTable &table) {\n\t\t\/\/ Return if table is empty\n\t\tif (table._tableData.size() == 0)\n\t\t\treturn stream;\n\t\t\n\t\t\/\/ Calculation row and column\n\t\tsize_t row = 0;\n\t\tsize_t column = 0;\n\t\tfor (auto &i : table._tableData) {\n\t\t\trow = std::max(row, i.first);\n\t\t\tfor (auto &j : i.second->_rowData)\n\t\t\t\tcolumn = std::max(column, j.first);\n\t\t}\n\t\trow++;\n\t\tcolumn++;\n\t\n\t\t\/\/ Calculation width of every column\n\t\tstd::vector<size_t> columnWidth;\n\t\tfor (size_t i = 0; i < column; i++) {\n\t\t\tsize_t tmp = 1;\n\t\t\tfor (size_t j = 0; j < row; j++) {\n\t\t\t\tif (table._tableData[j] != nullptr && table._tableData[j]->_rowData[i] != nullptr) {\n\t\t\t\t\ttmp = std::max(tmp, table._tableData[j]->_rowData[i]->_str.size());\n\t\t\t\t}\n\t\t\t}\n\t\t\tcolumnWidth.push_back(tmp);\n\t\t}\n\n\t\tif (table._alignment != ConsoleTable::Alignment::centre) {\n\t\t\tstream << std::right << table._chars.topLeft;\n\t\t\ttable._fillStreamByChar(stream, table._chars.topDownSimple, columnWidth[0] + 1 + table._leftIndent + table._rightIndent);\n\n\t\t\tif (column != 1) {\n\t\t\t\tfor (size_t i = 1; i < column; i++) {\n\t\t\t\t\tstream << table._chars.topSeparation << std::setw(columnWidth[i] + 1 + table._leftIndent + table._rightIndent);\n\t\t\t\t}\n\t\t\t}\n\t\t\tstream << table._chars.topRight << std::endl;\n\n\t\t\tfor (size_t i = 0; i < row; i++) {\n\t\t\t\tif (table._alignment == ConsoleTable::Alignment::left)\n\t\t\t\t\tstream << std::left;\n\t\t\t\telse if (table._alignment == ConsoleTable::Alignment::right)\n\t\t\t\t\tstream << std::right;\n\n\t\t\t\tfor (size_t j = 0; j < column; j++) {\n\t\t\t\t\tif (table._tableData[i] != nullptr && table._tableData[i]->_rowData[j] != nullptr) {\n\t\t\t\t\t\tstream << table._chars.leftRightSimple;\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._leftIndent);\n\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', columnWidth[j]);\n\t\t\t\t\t\tstream << table._tableData[i]->_rowData[j]->_str;\n\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._rightIndent);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tstream << table._chars.leftRightSimple;\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._leftIndent);\n\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', columnWidth[j]);\n\t\t\t\t\t\tstream << ' ';\n\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._rightIndent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstream << std::right << table._chars.leftRightSimple << std::endl;\n\n\t\t\t\tif (i == row - 1) {\n\t\t\t\t\tstream << table._chars.downLeft;\n\t\t\t\t\ttable._fillStreamByChar(stream, table._chars.topDownSimple, columnWidth[0] + 1 + table._leftIndent + table._rightIndent);\n\n\t\t\t\t\tif (column != 1) {\n\t\t\t\t\t\tfor (size_t j = 1; j < column; j++) {\n\t\t\t\t\t\t\tstream << table._chars.downSeparation << std::setw(columnWidth[j] + 1 + table._leftIndent + table._rightIndent);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tstream << table._chars.downRight << std::endl;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstream << table._chars.leftSeparation;\n\t\t\t\t\ttable._fillStreamByChar(stream, table._chars.topDownSimple, columnWidth[0] + 1 + table._leftIndent + table._rightIndent);\n\n\t\t\t\t\tif (column != 1) {\n\t\t\t\t\t\tfor (size_t j = 1; j < column; j++) {\n\t\t\t\t\t\t\tstream << table._chars.centreSeparation << std::setw(columnWidth[j] + 1 + table._leftIndent + table._rightIndent);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tstream << table._chars.rightSeparation << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (auto &i : table._tableData) {\n\t\t\t\tfor (auto &j : i.second->_rowData) {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn stream;\n\t}\n}\n\n#endif \/\/ _CPP_CONSOLE_TABLE_<commit_msg>Added working centre alignment<commit_after>\/*\n========================= Cpp Console Table\n| Cpp | Console | Table | version 1.0.0\n========================= https:\/\/github.com\/Oradle\/CppConsoleTable\n\nLicensed under the MIT License <http:\/\/opensource.org\/licenses\/MIT>.\nCopyright (c) 2017 Oradle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#pragma once\n#ifndef _CPP_CONSOLE_TABLE_\n#define _CPP_CONSOLE_TABLE_\n\n#include <iostream>\n#include <map>\n#include <string>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nnamespace samilton {\n\t\/\/ force declaration\n\tclass ConsoleTable;\n\n\tclass ConsoleString {\n\tpublic:\n\t\tConsoleString &operator=(const std::string &val) {\n\t\t\t_str = val;\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const char *val) {\n\t\t\t_str = val;\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const long &val) {\n\t\t\t_str = std::to_string(val);\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const int &val) {\n\t\t\t_str = std::to_string(val);\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const double &val) {\n\t\t\t_str = std::to_string(val);\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const float &val) {\n\t\t\t_str = std::to_string(val);\n\t\t\treturn *this;\n\t\t}\n\n\t\tConsoleString &operator=(const bool &val) {\n\t\t\tif (val)\n\t\t\t\t_str = \"true\";\n\t\t\telse\n\t\t\t\t_str = \"false\";\n\n\t\t\treturn *this;\n\t\t}\n\tprivate:\n\t\tfriend std::ostream &operator<<(std::ostream &stream, ConsoleTable &table);\n\n\t\tstd::string _str;\n\t};\n\n\tclass ConsoleRow {\n\tpublic:\n\t\t~ConsoleRow() {\n\t\t\tfor (auto &element : _rowData) {\n\t\t\t\tdelete element.second;\n\t\t\t}\n\t\t}\n\n\t\tConsoleString &operator[](const size_t &column) {\n\t\t\ttry {\n\t\t\t\treturn *_rowData.at(column);\n\t\t\t}\n\t\t\tcatch (...) {\n\t\t\t\t_rowData[column] = new ConsoleString;\n\t\t\t\treturn *_rowData[column];\n\t\t\t}\n\t\t}\n\tprivate:\n\t\tfriend std::ostream &operator<<(std::ostream &stream, ConsoleTable &table);\n\n\t\tstd::map<size_t, ConsoleString*> _rowData;\n\t};\n\n\tclass ConsoleTable {\n\tpublic:\n\t\tenum class Alignment {\n\t\t\tleft = 0,\n\t\t\tcentre,\n\t\t\tright\n\t\t};\n\n\t\tstruct TableChars {\n\t\t\tchar topRight = 187, topLeft = 201, downRight = 188, downLeft = 200;\n\t\t\tchar topDownSimple = 205, topSeparation = 203, downSeparation = 202;\n\t\t\tchar leftRightSimple = 186, leftSeparation = 204, rightSeparation = 185;\n\t\t\tchar centreSeparation = 206;\n\t\t};\n\n\t\tConsoleTable() {\n\t\t\t_alignment = Alignment::left;\n\t\t\t_leftIndent = 0;\n\t\t\t_rightIndent = 0;\n\t\t}\n\n\t\tConsoleTable(const Alignment &alignment) {\n\t\t\t_alignment = alignment;\n\t\t\t_leftIndent = 0;\n\t\t\t_rightIndent = 0;\n\t\t}\n\n\t\tConsoleTable(const size_t &leftIndent, const size_t &rightIndent, const Alignment &alignment = Alignment::left) {\n\t\t\t_leftIndent = leftIndent;\n\t\t\t_rightIndent = rightIndent;\n\t\t\t_alignment = alignment;\n\t\t}\n\n\t\t~ConsoleTable() {\n\t\t\tfor (auto &element : _tableData) {\n\t\t\t\tdelete element.second;\n\t\t\t}\n\t\t}\n\n\t\tvoid setAlignment(const Alignment &alignment) {\n\t\t\t_alignment = alignment;\n\t\t}\n\n\t\tvoid setIndent(const size_t &leftIndent, const size_t &rightIndent)\n\t\t{\n\t\t\t_leftIndent = leftIndent;\n\t\t\t_rightIndent = rightIndent;\n\t\t}\n\n\t\tvoid setTableChars(const TableChars &chars) {\n\t\t\t_chars = chars;\n\t\t}\n\n\t\tConsoleRow &operator[](const size_t &row) {\n\t\t\ttry {\n\t\t\t\treturn *_tableData.at(row);\n\t\t\t}\n\t\t\tcatch (...) {\n\t\t\t\t_tableData[row] = new ConsoleRow;\n\t\t\t\treturn *_tableData[row];\n\t\t\t}\n\t\t}\n\n\t\tfriend std::ostream &operator<<(std::ostream &stream, ConsoleTable &table);\n\tprivate:\n\t\tvoid _fillStreamByChar(std::ostream &stream, const char &fillChar, const size_t &lenght) {\n\t\t\tif (lenght > 0)\n\t\t\t\tstream << std::setfill(fillChar) << std::setw(lenght);\n\t\t}\n\n\t\tvoid _fillStreamByChar(std::ostream &stream, const char &fillChar, const char &endChar, const size_t &lenght) {\n\t\t\tif (lenght > 0)\n\t\t\t\tstream << std::setfill(fillChar) << std::setw(lenght) << endChar;\n\t\t}\n\n\t\tTableChars _chars;\n\t\tstd::map<size_t, ConsoleRow*> _tableData;\n\t\tAlignment _alignment;\n\t\tsize_t _leftIndent, _rightIndent;\n\t};\n\n\tinline std::ostream &operator<<(std::ostream &stream, ConsoleTable &table) {\n\t\t\/\/ Return if table is empty\n\t\tif (table._tableData.size() == 0)\n\t\t\treturn stream;\n\n\t\t\/\/ Calculation row and column\n\t\tsize_t row = 0;\n\t\tsize_t column = 0;\n\t\tfor (auto &i : table._tableData) {\n\t\t\trow = std::max(row, i.first);\n\t\t\tfor (auto &j : i.second->_rowData)\n\t\t\t\tcolumn = std::max(column, j.first);\n\t\t}\n\t\trow++;\n\t\tcolumn++;\n\n\t\t\/\/ Calculation width of every column\n\t\tstd::vector<size_t> columnWidth;\n\t\tfor (size_t i = 0; i < column; i++) {\n\t\t\tsize_t tmp = 1;\n\t\t\tfor (size_t j = 0; j < row; j++) {\n\t\t\t\tif (table._tableData[j] != nullptr && table._tableData[j]->_rowData[i] != nullptr) {\n\t\t\t\t\ttmp = std::max(tmp, table._tableData[j]->_rowData[i]->_str.size());\n\t\t\t\t}\n\t\t\t}\n\t\t\tcolumnWidth.push_back(tmp);\n\t\t}\n\n\t\t\/\/ Top border\n\t\tstream << std::right << table._chars.topLeft;\n\t\ttable._fillStreamByChar(stream, table._chars.topDownSimple, columnWidth[0] + 1 + table._leftIndent + table._rightIndent);\n\n\t\tif (column != 1) {\n\t\t\tfor (size_t i = 1; i < column; i++) {\n\t\t\t\tstream << table._chars.topSeparation << std::setw(columnWidth[i] + 1 + table._leftIndent + table._rightIndent);\n\t\t\t}\n\t\t}\n\t\tstream << table._chars.topRight << std::endl;\n\n\t\t\/\/ Elements and middle borders\n\t\tfor (size_t i = 0; i < row; i++) {\n\t\t\tfor (size_t j = 0; j < column; j++) {\n\t\t\t\tif (table._tableData[i] != nullptr && table._tableData[i]->_rowData[j] != nullptr) {\n\t\t\t\t\tif (table._alignment == ConsoleTable::Alignment::centre) {\n\t\t\t\t\t\tconst size_t tmp = columnWidth[j] - table._tableData[i]->_rowData[j]->_str.size();\n\t\t\t\t\t\tsize_t leftAlignmentIndent, rightAlignmentIndent;\n\t\t\t\t\t\tif (tmp % 2) {\n\t\t\t\t\t\t\tleftAlignmentIndent = tmp \/ 2;\n\t\t\t\t\t\t\trightAlignmentIndent = tmp \/ 2 + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tleftAlignmentIndent = rightAlignmentIndent = tmp \/ 2;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstream << table._chars.leftRightSimple;\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._leftIndent + leftAlignmentIndent);\n\n\t\t\t\t\t\tstream << table._tableData[i]->_rowData[j]->_str;\n\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._rightIndent + rightAlignmentIndent);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (table._alignment == ConsoleTable::Alignment::left)\n\t\t\t\t\t\t\tstream << std::left;\n\t\t\t\t\t\telse if (table._alignment == ConsoleTable::Alignment::right)\n\t\t\t\t\t\t\tstream << std::right;\n\n\t\t\t\t\t\tstream << table._chars.leftRightSimple;\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._leftIndent);\n\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', columnWidth[j]);\n\t\t\t\t\t\tstream << table._tableData[i]->_rowData[j]->_str;\n\n\t\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._rightIndent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstream << table._chars.leftRightSimple;\n\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._leftIndent);\n\n\t\t\t\t\ttable._fillStreamByChar(stream, ' ', columnWidth[j]);\n\t\t\t\t\tstream << ' ';\n\n\t\t\t\t\ttable._fillStreamByChar(stream, ' ', ' ', table._rightIndent);\n\t\t\t\t}\n\t\t\t}\n\t\t\tstream << std::right << table._chars.leftRightSimple << std::endl;\n\n\t\t\t\/\/ Down border\n\t\t\tif (i == row - 1) {\n\t\t\t\tstream << table._chars.downLeft;\n\t\t\t\ttable._fillStreamByChar(stream, table._chars.topDownSimple, columnWidth[0] + 1 + table._leftIndent + table._rightIndent);\n\n\t\t\t\tif (column != 1) {\n\t\t\t\t\tfor (size_t j = 1; j < column; j++) {\n\t\t\t\t\t\tstream << table._chars.downSeparation << std::setw(columnWidth[j] + 1 + table._leftIndent + table._rightIndent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstream << table._chars.downRight << std::endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstream << table._chars.leftSeparation;\n\t\t\t\ttable._fillStreamByChar(stream, table._chars.topDownSimple, columnWidth[0] + 1 + table._leftIndent + table._rightIndent);\n\n\t\t\t\tif (column != 1) {\n\t\t\t\t\tfor (size_t j = 1; j < column; j++) {\n\t\t\t\t\t\tstream << table._chars.centreSeparation << std::setw(columnWidth[j] + 1 + table._leftIndent + table._rightIndent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstream << table._chars.rightSeparation << std::endl;\n\t\t\t}\n\t\t}\n\n\t\treturn stream;\n\t}\n}\n\n#endif \/\/ _CPP_CONSOLE_TABLE_<|endoftext|>"} {"text":"<commit_before>#include \"pyToCppModelInterface.h\"\n#include <boost\/python\/stl_iterator.hpp>\n#include <iostream>\n#include <stdexcept>\n\nnamespace threeML {\n\n template< typename T > inline\n std::vector< T > to_std_vector( const boost::python::object& iterable )\n {\n return std::vector< T >( boost::python::stl_input_iterator< T >( iterable ),\n boost::python::stl_input_iterator< T >( ) );\n }\n\n pyToCppModelInterface::pyToCppModelInterface(PyObject *pyModelUninterpreted) :\n m_nPtSources(0), m_nExtSources(0), n_calls(0)\n { \n \n try \n {\n boost::python::object \n o(boost::python::handle<>(boost::python::borrowed(pyModelUninterpreted)));\n \n m_pyModel = o;\n \n } \n catch (...)\n {\n throw std::runtime_error(\"ModelInterface: Could not interpret the LikelihoodModel class\");\n } \n \n \/\/TODO: add a verification of the interface for the pyObject\n \n try {\n \n \n m_nPtSources = boost::python::extract<int>(m_pyModel.attr(\"getNumberOfPointSources\")());\n \n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not use getNumberOfPointSources from python Object\");\n \n }\n }\n \n bool pyToCppModelInterface::isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const\n { \n return false;\n }\n \n int pyToCppModelInterface::getNumberOfPointSources() const\n {\n\n return m_nPtSources;\n\n }\n \n void pyToCppModelInterface::getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const\n {\n \n boost::python::object coords;\n \n try {\n \n coords = m_pyModel.attr(\"getPointSourcePosition\")(srcid);\n \n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not call getPointSourcePosition on the python side\");\n \n }\n \n try {\n \n (*j2000_ra) = boost::python::extract<double>(coords[0]);\n (*j2000_dec) = boost::python::extract<double>(coords[1]);\n \n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not convert the coordinates I got from the python side\");\n }\n }\n \n void pyToCppModelInterface::update()\n { \n \n \/\/std::cerr << \"Emptying cache\" << std::endl;\n \n \/\/Empty the cache\n m_cache.clear();\n \n }\n \n std::vector<double> \n pyToCppModelInterface::getPointSourceFluxes(int srcid, std::vector<double> energies) const\n { \n \n if ( m_cache.count( srcid )==1 ) \n {\n \n \/\/std::cerr << \"Cached\" << std::endl;\n \n \/\/Return cached version\n \n return m_cache[srcid];\n \n } else {\n \n n_calls += 1;\n \n \/\/std::cerr << \"Filling cache for \" << srcid << \" (\" << n_calls << \")\" << std::endl;\n \n }\n \n \n \/\/Construct a generic object (instead of for example a list) so that\n \/\/the pyModel can return any iterable (list, numpy.array, etc)\n \n boost::python::object fluxes;\n \n \/\/try {\n \n fluxes = m_pyModel.attr(\"getPointSourceFluxes\")(srcid,energies);\n \n \/\/} catch (...) {\n \n \/\/ throw std::runtime_error(\n \/\/ \"ModelInterface: Could not get the fluxes from the python side\");\n \n \/\/}\n \n std::vector<double> fluxes_v;\n \n try {\n \n fluxes_v = to_std_vector<double>(fluxes);\n\t \n\t \/*\n\t for(int i=0; i < fluxes_v.size(); ++i) \n\t {\n\t \n\t std::cerr << \"e[\" << i << \"] = \" << fluxes_v[i] << std::endl;\n\t \n\t }*\/\n\t \n \n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not convert the fluxes I got from the python side\");\n \n }\n \n \/\/Cache result\n \n m_cache[srcid] = fluxes_v;\n \n return fluxes_v;\n }\n \n int pyToCppModelInterface::getNumberOfExtendedSources() const\n {\n return 0;\n }\n \n std::vector<double> \n pyToCppModelInterface::getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, \n std::vector<double> energies) const\n {\n std::vector<double> fluxes;\n return fluxes;\n }\n \n \n std::string pyToCppModelInterface::getPointSourceName(int srcid) const\n {\n \n std::string name;\n \n try {\n \n name = boost::python::extract<std::string>(\n m_pyModel.attr(\"getPointSourceName\")(srcid)\n );\n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not get the point source name from the python side\");\n \n }\n \n return name;\n }\n \n std::string pyToCppModelInterface::getExtendedSourceName(int srcid) const\n {\n std::string name(\"test\");\n return name;\n }\n\n}\n<commit_msg>Correcting a problem with units. Now fluxes are per MeV, instead of per keV<commit_after>#include \"pyToCppModelInterface.h\"\n#include <boost\/python\/stl_iterator.hpp>\n#include <iostream>\n#include <stdexcept>\n\nnamespace threeML {\n\n template< typename T > inline\n std::vector< T > to_std_vector( const boost::python::object& iterable )\n {\n return std::vector< T >( boost::python::stl_input_iterator< T >( iterable ),\n boost::python::stl_input_iterator< T >( ) );\n }\n\n pyToCppModelInterface::pyToCppModelInterface(PyObject *pyModelUninterpreted) :\n m_nPtSources(0), m_nExtSources(0), n_calls(0)\n { \n \n try \n {\n boost::python::object \n o(boost::python::handle<>(boost::python::borrowed(pyModelUninterpreted)));\n \n m_pyModel = o;\n \n } \n catch (...)\n {\n throw std::runtime_error(\"ModelInterface: Could not interpret the LikelihoodModel class\");\n } \n \n \/\/TODO: add a verification of the interface for the pyObject\n \n try {\n \n \n m_nPtSources = boost::python::extract<int>(m_pyModel.attr(\"getNumberOfPointSources\")());\n \n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not use getNumberOfPointSources from python Object\");\n \n }\n }\n \n bool pyToCppModelInterface::isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const\n { \n return false;\n }\n \n int pyToCppModelInterface::getNumberOfPointSources() const\n {\n\n return m_nPtSources;\n\n }\n \n void pyToCppModelInterface::getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const\n {\n \n boost::python::object coords;\n \n try {\n \n coords = m_pyModel.attr(\"getPointSourcePosition\")(srcid);\n \n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not call getPointSourcePosition on the python side\");\n \n }\n \n try {\n \n (*j2000_ra) = boost::python::extract<double>(coords[0]);\n (*j2000_dec) = boost::python::extract<double>(coords[1]);\n \n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not convert the coordinates I got from the python side\");\n }\n }\n \n void pyToCppModelInterface::update()\n { \n \n \/\/std::cerr << \"Emptying cache\" << std::endl;\n \n \/\/Empty the cache\n m_cache.clear();\n \n }\n \n std::vector<double> \n pyToCppModelInterface::getPointSourceFluxes(int srcid, std::vector<double> energies) const\n { \n \n if ( m_cache.count( srcid )==1 ) \n {\n \n \/\/std::cerr << \"Cached\" << std::endl;\n \n \/\/Return cached version\n \n return m_cache[srcid];\n \n } else {\n \n n_calls += 1;\n \n \/\/std::cerr << \"Filling cache for \" << srcid << \" (\" << n_calls << \")\" << std::endl;\n \n }\n \n \n \/\/Construct a generic object (instead of for example a list) so that\n \/\/the pyModel can return any iterable (list, numpy.array, etc)\n \n boost::python::object fluxes;\n \n \/\/try {\n \n fluxes = m_pyModel.attr(\"getPointSourceFluxes\")(srcid,energies);\n \n \/\/} catch (...) {\n \n \/\/ throw std::runtime_error(\n \/\/ \"ModelInterface: Could not get the fluxes from the python side\");\n \n \/\/}\n \n std::vector<double> fluxes_v;\n \n try {\n \n fluxes_v = to_std_vector<double>(fluxes);\n\t \n\t \n \/\/Transform in ph\/cm2\/s\/MeV from ph\/cm2\/s\/keV\n \n\t for(int i=0; i < fluxes_v.size(); ++i) \n\t {\n\t \n\t fluxes_v[i] = fluxes_v[i] \/ 1000.0;\n\t \n\t }\n\t \n \n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not convert the fluxes I got from the python side\");\n \n }\n \n \/\/Cache result\n \n m_cache[srcid] = fluxes_v;\n \n return fluxes_v;\n }\n \n int pyToCppModelInterface::getNumberOfExtendedSources() const\n {\n return 0;\n }\n \n std::vector<double> \n pyToCppModelInterface::getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, \n std::vector<double> energies) const\n {\n std::vector<double> fluxes;\n return fluxes;\n }\n \n \n std::string pyToCppModelInterface::getPointSourceName(int srcid) const\n {\n \n std::string name;\n \n try {\n \n name = boost::python::extract<std::string>(\n m_pyModel.attr(\"getPointSourceName\")(srcid)\n );\n } catch (...) {\n \n throw std::runtime_error(\n \"ModelInterface: Could not get the point source name from the python side\");\n \n }\n \n return name;\n }\n \n std::string pyToCppModelInterface::getExtendedSourceName(int srcid) const\n {\n std::string name(\"test\");\n return name;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n@file IO\/PropStateStore.hpp\n@brief Prop state store.\n\n@author Timothy Howard\n@copyright 2013-2014 Timothy Howard under the MIT license;\nsee @ref index or the accompanying LICENSE file for full text.\n*\/\n\n#ifndef HORD_IO_PROPSTATESTORE_HPP_\n#define HORD_IO_PROPSTATESTORE_HPP_\n\n#include <Hord\/config.hpp>\n#include <Hord\/utility.hpp>\n#include <Hord\/IO\/Defs.hpp>\n\nnamespace Hord {\nnamespace IO {\n\n\/\/ Forward declarations\nclass PropStateStore;\n\n\/**\n\t@addtogroup io\n\t@{\n*\/\n\/**\n\t@addtogroup prop\n\t@{\n*\/\n\nnamespace {\n\n\/\/ FIXME: For some terrific reason Clang sees this function as\n\/\/ only being *declared* if it is placed in-class before the\n\/\/ anonymous enum.\nstatic constexpr unsigned\nstate_fill(\n\tIO::PropState const state\n) noexcept {\n\treturn 0u\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::identity ) << 2))\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::metadata ) << 2))\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::scratch ) << 2))\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::primary ) << 2))\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::auxiliary) << 2))\n\t;\n}\n\n} \/\/ anonymous namespace\n\n\/**\n\tProp state store.\n\n\t@note Within the state store, all unsupplied props imply\n\tIO::PropState::original.\n\n\t@sa IO::PropState\n*\/\nclass PropStateStore final {\nprivate:\n\tstatic_assert(\n\t\t5u == enum_cast(PropType::LAST),\n\t\t\"masks and all_have() need to be updated\"\n\t);\n\tstatic_assert(\n\t\t4u <= sizeof(unsigned),\n\t\t\"implementation requires at least 4 bytes in unsigned int\"\n\t);\n\n\t\/*\n\t\tBits (1-6 are props, S is whether they are supplied):\n\t\tXXSS SSSS 6666 5555 4444 3333 2222 1111\n\n\t\t6666 is currently unoccupied (there are only 5 props).\n\t*\/\n\tenum : unsigned {\n\t\t\/\/ 4 bits per prop\n\t\tstate_mask = 0x0F,\n\t\t\/\/ 5 states\n\t\tfull_mask = 0x000FFFFF,\n\t\t\/\/ 3 always-supplied props (identity, metadata, and scratch)\n\t\tbase_value = 0x07000FFF,\n\n\t\t\/\/ (PropType << type_shift) gives the number of bits\n\t\t\/\/ to move left for the prop's state\n\t\ttype_shift = 2u,\n\t\t\/\/ (PropTypeBit << flag_shift) gives the\n\t\t\/\/ is_supplied bit for the prop\n\t\tflag_shift = 24u,\n\n\t\tbit_primary\n\t\t\t= enum_cast(IO::PropTypeBit::primary)\n\t\t\t<< flag_shift\n\t\t,\n\t\tbit_auxiliary\n\t\t\t= enum_cast(IO::PropTypeBit::auxiliary)\n\t\t\t<< flag_shift\n\t\t,\n\n\t\tprop_unsupplied_implied\n\t\t\t= enum_cast(IO::PropState::unsupplied)\n\t\t\t| enum_cast(IO::PropState::original)\n\t\t,\n\t\tprop_unsupplied_single = enum_cast(IO::PropState::unsupplied),\n\n\t\tmask_unsupplied_implied\n\t\t\t= state_fill(static_cast<IO::PropState>(prop_unsupplied_implied))\n\t\t,\n\n\t\tall_mask_unsupplied = state_fill(IO::PropState::unsupplied),\n\t\tall_mask_original = state_fill(IO::PropState::original),\n\t\tall_mask_modified = state_fill(IO::PropState::modified),\n\t};\n\n\tstatic constexpr unsigned\n\tshift_up(\n\t\tunsigned const value,\n\t\tIO::PropType const prop_type,\n\t\tunsigned const mask = state_mask\n\t) noexcept {\n\t\treturn (value & mask) << (enum_cast(prop_type) << type_shift);\n\t}\n\n\tstatic constexpr unsigned\n\tshift_down(\n\t\tunsigned const value,\n\t\tIO::PropType const prop_type,\n\t\tunsigned const mask = state_mask\n\t) noexcept {\n\t\treturn (value >> (enum_cast(prop_type) << type_shift)) & mask;\n\t}\n\n\tstatic constexpr unsigned\n\tmask_off(\n\t\tunsigned const value,\n\t\tIO::PropType const prop_type\n\t) noexcept {\n\t\treturn ~(state_mask << (enum_cast(prop_type) << type_shift)) & value;\n\t}\n\n\tunsigned m_states_supplied;\n\tunsigned m_states;\n\n\tPropStateStore() = delete;\n\tPropStateStore& operator=(PropStateStore const&) = delete;\n\npublic:\n\/** @name Special member functions *\/ \/\/\/ @{\n\t\/** Destructor. *\/\n\t~PropStateStore() = default;\n\n\t\/** Copy constructor. *\/\n\tPropStateStore(PropStateStore const&) = default;\n\t\/** Move constructor. *\/\n\tPropStateStore(PropStateStore&&) = default;\n\t\/** Move assignment operator. *\/\n\tPropStateStore& operator=(PropStateStore&&) = default;\n\n\t\/**\n\t\tConstructor with object data prop availability.\n\n\t\t@post All <strong>supplied<\/strong> props are uninitialized.\n\n\t\t@param supplies_primary Whether IO::PropType::primary is\n\t\tsupplied.\n\t\t@param supplies_auxiliary Whether IO::PropType::auxiliary is\n\t\tsupplied.\n\t*\/\n\tconstexpr\n\tPropStateStore(\n\t\tbool const supplies_primary,\n\t\tbool const supplies_auxiliary\n\t) noexcept\n\t\t: m_states_supplied(\n\t\t\tbase_value\n\t\t\t| (!supplies_primary ? 0u : (\n\t\t\t\tbit_primary |\n\t\t\t\tshift_up(state_mask, IO::PropType::primary)\n\t\t\t))\n\t\t\t| (!supplies_auxiliary ? 0u : (\n\t\t\t\tbit_auxiliary |\n\t\t\t\tshift_up(state_mask, IO::PropType::auxiliary)\n\t\t\t))\n\t\t)\n\t\t, m_states(\n\t\t\t~m_states_supplied & mask_unsupplied_implied\n\t\t)\n\t{}\n\/\/\/ @}\n\n\/** @name Properties *\/ \/\/\/ @{\n\t\/**\n\t\tCheck if prop has a state.\n\n\t\t@note If @a state is a state combination, the return\n\t\tvalue will be @c true if <em>any<\/em> of the combined\n\t\tstates are set.\n\n\t\t@param prop_type Prop type.\n\t\t@param state Prop state.\n\t*\/\n\tbool\n\thas(\n\t\tIO::PropType const prop_type,\n\t\tIO::PropState const state\n\t) const noexcept {\n\t\treturn shift_down(m_states, prop_type, enum_cast(state));\n\t}\n\n\t\/**\n\t\tCheck if any prop is modified.\n\t*\/\n\tbool\n\tany_modified() const noexcept {\n\t\treturn 0u != (m_states & all_mask_modified);\n\t}\n\n\t\/**\n\t\tCheck if all props match external storage.\n\t*\/\n\tbool\n\tall_original() const noexcept {\n\t\treturn all_mask_original == (m_states & all_mask_original);\n\t}\n\n\t\/**\n\t\tCheck if all supplied props are uninitialized.\n\t*\/\n\tbool\n\tall_uninitialized() const noexcept {\n\t\treturn 0u == (m_states & m_states_supplied);\n\t}\n\n\t\/**\n\t\tCheck if all supplied data props are initialized.\n\t*\/\n\tbool\n\tall_data_initialized() const noexcept {\n\t\t\/\/ NB: Non-supplied props \"are\" original within the store\n\t\t\/\/ and all other states imply the prop is initialized\n\t\treturn shift_down(m_states, IO::PropType::primary)\n\t\t\t&& shift_down(m_states, IO::PropType::auxiliary);\n\t}\n\n\t\/**\n\t\tCheck if prop is initialized.\n\n\t\t@param prop_type Prop type.\n\t*\/\n\tbool\n\tis_initialized(\n\t\tIO::PropType const prop_type\n\t) const noexcept {\n\t\treturn 0u != shift_down(m_states, prop_type);\n\t}\n\n\t\/**\n\t\tCheck if prop is supplied.\n\n\t\t@param prop_type Prop type.\n\t*\/\n\tbool\n\tsupplies(\n\t\tIO::PropType const prop_type\n\t) const noexcept {\n\t\treturn supplies_all(IO::prop_flag(prop_type));\n\t}\n\n\t\/**\n\t\tCheck if all given props are supplied.\n\t*\/\n\tbool\n\tsupplies_all(\n\t\tIO::PropTypeBit const props\n\t) const noexcept {\n\t\treturn\n\t\t\tenum_cast(props)\n\t\t\t== (enum_cast(get_supplied()) & enum_cast(props))\n\t\t;\n\t}\n\n\t\/**\n\t\tCheck if any given props are supplied.\n\t*\/\n\tbool\n\tsupplies_any(\n\t\tIO::PropTypeBit const props\n\t) const noexcept {\n\t\treturn enum_cast(get_supplied()) & enum_cast(props);\n\t}\n\n\t\/**\n\t\tGet store value.\n\t*\/\n\tunsigned\n\tget_value() const noexcept {\n\t\treturn m_states;\n\t}\n\n\t\/**\n\t\tGet full state for prop.\n\n\t\t@param prop_type Prop type.\n\t*\/\n\tIO::PropState\n\tget_state(\n\t\tIO::PropType const prop_type\n\t) const noexcept {\n\t\treturn static_cast<IO::PropState>(\n\t\t\tshift_down(m_states, prop_type)\n\t\t);\n\t}\n\n\t\/**\n\t\tGet supplied props.\n\t*\/\n\tIO::PropTypeBit\n\tget_supplied() const noexcept {\n\t\treturn static_cast<IO::PropTypeBit>(\n\t\t\tm_states_supplied >> flag_shift\n\t\t);\n\t}\n\/\/\/ @}\n\n\/** @name Operations *\/ \/\/\/ @{\n\t\/**\n\t\tReset all states to uninitialized.\n\n\t\t@note Non-supplied states are not modified.\n\n\t\t@returns @c *this.\n\t*\/\n\tPropStateStore&\n\treset_all() noexcept {\n\t\tm_states = ~m_states_supplied & mask_unsupplied_implied;\n\t\treturn *this;\n\t}\n\n\t\/**\n\t\tReset a prop state to uninitialized.\n\n\t\t@note If the prop is not supplied, this has no effect.\n\n\t\t@returns @c *this.\n\t\t@param prop_type Prop type.\n\t*\/\n\tPropStateStore&\n\treset(\n\t\tPropType const prop_type\n\t) noexcept {\n\t\tif (supplies(prop_type)) {\n\t\t\tm_states = mask_off(m_states, prop_type);\n\t\t}\n\t\treturn *this;\n\t}\n\n\t\/**\n\t\tAssign prop state.\n\n\t\t@note If the prop is not supplied, this has no effect.\n\n\t\t@par\n\t\t@note IO::PropState::unsupplied is masked out\n\t\tof @a state before assignment. Only the constructor can\n\t\tassign this state.\n\n\t\t@returns @c *this.\n\t\t@param prop_type Prop type.\n\t\t@param state Prop state.\n\t*\/\n\tPropStateStore&\n\tassign(\n\t\tIO::PropType const prop_type,\n\t\tIO::PropState const state\n\t) noexcept {\n\t\tif (supplies(prop_type)) {\n\t\t\tm_states\n\t\t\t\t= mask_off(m_states, prop_type)\n\t\t\t\t| shift_up(\n\t\t\t\t\t~prop_unsupplied_single & enum_cast(state),\n\t\t\t\t\tprop_type\n\t\t\t\t)\n\t\t\t;\n\t\t}\n\t\treturn *this;\n\t}\n\n\tPropStateStore&\n\tassign_all(\n\t\tIO::PropState const state\n\t) noexcept {\n\t\tswitch (state) {\n\t\tcase IO::PropState::unsupplied:\n\t\t\treset_all();\n\t\t\tbreak;\n\t\tcase IO::PropState::original:\n\t\t\tm_states\n\t\t\t\t= (~m_states_supplied & mask_unsupplied_implied)\n\t\t\t\t| (m_states_supplied & all_mask_original)\n\t\t\t;\n\t\t\tbreak;\n\t\tcase IO::PropState::modified:\n\t\t\tm_states\n\t\t\t\t= (~m_states_supplied & mask_unsupplied_implied)\n\t\t\t\t| (m_states_supplied & all_mask_modified)\n\t\t\t;\n\t\t\tbreak;\n\t\t}\n\t\treturn *this;\n\t}\n\/\/\/ @}\n};\n\n\/** @} *\/ \/\/ end of doc-group prop\n\/** @} *\/ \/\/ end of doc-group io\n\n} \/\/ namespace IO\n} \/\/ namespace Hord\n\n#endif \/\/ HORD_IO_PROPSTATESTORE_HPP_\n<commit_msg>IO::PropStateStore: made accessors constexpr.<commit_after>\/**\n@file IO\/PropStateStore.hpp\n@brief Prop state store.\n\n@author Timothy Howard\n@copyright 2013-2014 Timothy Howard under the MIT license;\nsee @ref index or the accompanying LICENSE file for full text.\n*\/\n\n#ifndef HORD_IO_PROPSTATESTORE_HPP_\n#define HORD_IO_PROPSTATESTORE_HPP_\n\n#include <Hord\/config.hpp>\n#include <Hord\/utility.hpp>\n#include <Hord\/IO\/Defs.hpp>\n\nnamespace Hord {\nnamespace IO {\n\n\/\/ Forward declarations\nclass PropStateStore;\n\n\/**\n\t@addtogroup io\n\t@{\n*\/\n\/**\n\t@addtogroup prop\n\t@{\n*\/\n\nnamespace {\n\n\/\/ FIXME: For some terrific reason Clang sees this function as\n\/\/ only being *declared* if it is placed in-class before the\n\/\/ anonymous enum.\nstatic constexpr unsigned\nstate_fill(\n\tIO::PropState const state\n) noexcept {\n\treturn 0u\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::identity ) << 2))\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::metadata ) << 2))\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::scratch ) << 2))\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::primary ) << 2))\n\t\t| (enum_cast(state) << (enum_cast(IO::PropType::auxiliary) << 2))\n\t;\n}\n\n} \/\/ anonymous namespace\n\n\/**\n\tProp state store.\n\n\t@note Within the state store, all unsupplied props imply\n\tIO::PropState::original.\n\n\t@sa IO::PropState\n*\/\nclass PropStateStore final {\nprivate:\n\tstatic_assert(\n\t\t5u == enum_cast(PropType::LAST),\n\t\t\"masks and all_have() need to be updated\"\n\t);\n\tstatic_assert(\n\t\t4u <= sizeof(unsigned),\n\t\t\"implementation requires at least 4 bytes in unsigned int\"\n\t);\n\n\t\/*\n\t\tBits (1-6 are props, s is whether they are supplied):\n\t\tXXss ssss 6666 5555 4444 3333 2222 1111\n\n\t\t6666 is currently unoccupied (there are only 5 props).\n\t*\/\n\tenum : unsigned {\n\t\t\/\/ 4 bits per prop\n\t\tstate_mask = 0x0F,\n\t\t\/\/ 5 states\n\t\tfull_mask = 0x000FFFFF,\n\t\t\/\/ 3 always-supplied props (identity, metadata, and scratch)\n\t\tbase_value = 0x07000FFF,\n\n\t\t\/\/ (PropType << type_shift) gives the number of bits\n\t\t\/\/ to move left for the prop's state\n\t\ttype_shift = 2u,\n\t\t\/\/ (PropTypeBit << flag_shift) gives the\n\t\t\/\/ is_supplied bit for the prop\n\t\tflag_shift = 24u,\n\n\t\tbit_primary\n\t\t\t= enum_cast(IO::PropTypeBit::primary)\n\t\t\t<< flag_shift\n\t\t,\n\t\tbit_auxiliary\n\t\t\t= enum_cast(IO::PropTypeBit::auxiliary)\n\t\t\t<< flag_shift\n\t\t,\n\n\t\tprop_unsupplied_implied\n\t\t\t= enum_cast(IO::PropState::unsupplied)\n\t\t\t| enum_cast(IO::PropState::original)\n\t\t,\n\t\tprop_unsupplied_single = enum_cast(IO::PropState::unsupplied),\n\n\t\tmask_unsupplied_implied\n\t\t\t= state_fill(static_cast<IO::PropState>(prop_unsupplied_implied))\n\t\t,\n\n\t\tall_mask_unsupplied = state_fill(IO::PropState::unsupplied),\n\t\tall_mask_original = state_fill(IO::PropState::original),\n\t\tall_mask_modified = state_fill(IO::PropState::modified),\n\t};\n\n\tstatic constexpr unsigned\n\tshift_up(\n\t\tunsigned const value,\n\t\tIO::PropType const prop_type,\n\t\tunsigned const mask = state_mask\n\t) noexcept {\n\t\treturn (value & mask) << (enum_cast(prop_type) << type_shift);\n\t}\n\n\tstatic constexpr unsigned\n\tshift_down(\n\t\tunsigned const value,\n\t\tIO::PropType const prop_type,\n\t\tunsigned const mask = state_mask\n\t) noexcept {\n\t\treturn (value >> (enum_cast(prop_type) << type_shift)) & mask;\n\t}\n\n\tstatic constexpr unsigned\n\tmask_off(\n\t\tunsigned const value,\n\t\tIO::PropType const prop_type\n\t) noexcept {\n\t\treturn ~(state_mask << (enum_cast(prop_type) << type_shift)) & value;\n\t}\n\n\tunsigned m_states_supplied;\n\tunsigned m_states;\n\n\tPropStateStore() = delete;\n\tPropStateStore& operator=(PropStateStore const&) = delete;\n\npublic:\n\/** @name Special member functions *\/ \/\/\/ @{\n\t\/** Destructor. *\/\n\t~PropStateStore() = default;\n\n\t\/** Copy constructor. *\/\n\tPropStateStore(PropStateStore const&) = default;\n\t\/** Move constructor. *\/\n\tPropStateStore(PropStateStore&&) = default;\n\t\/** Move assignment operator. *\/\n\tPropStateStore& operator=(PropStateStore&&) = default;\n\n\t\/**\n\t\tConstructor with object data prop availability.\n\n\t\t@post All <strong>supplied<\/strong> props are uninitialized.\n\n\t\t@param supplies_primary Whether IO::PropType::primary is\n\t\tsupplied.\n\t\t@param supplies_auxiliary Whether IO::PropType::auxiliary is\n\t\tsupplied.\n\t*\/\n\tconstexpr\n\tPropStateStore(\n\t\tbool const supplies_primary,\n\t\tbool const supplies_auxiliary\n\t) noexcept\n\t\t: m_states_supplied(\n\t\t\tbase_value\n\t\t\t| (!supplies_primary ? 0u : (\n\t\t\t\tbit_primary |\n\t\t\t\tshift_up(state_mask, IO::PropType::primary)\n\t\t\t))\n\t\t\t| (!supplies_auxiliary ? 0u : (\n\t\t\t\tbit_auxiliary |\n\t\t\t\tshift_up(state_mask, IO::PropType::auxiliary)\n\t\t\t))\n\t\t)\n\t\t, m_states(\n\t\t\t~m_states_supplied & mask_unsupplied_implied\n\t\t)\n\t{}\n\/\/\/ @}\n\n\/** @name Properties *\/ \/\/\/ @{\n\t\/**\n\t\tCheck if prop has a state.\n\n\t\t@note If @a state is a state combination, the return\n\t\tvalue will be @c true if <em>any<\/em> of the combined\n\t\tstates are set.\n\n\t\t@param prop_type Prop type.\n\t\t@param state Prop state.\n\t*\/\n\tconstexpr bool\n\thas(\n\t\tIO::PropType const prop_type,\n\t\tIO::PropState const state\n\t) const noexcept {\n\t\treturn shift_down(m_states, prop_type, enum_cast(state));\n\t}\n\n\t\/**\n\t\tCheck if any prop is modified.\n\t*\/\n\tconstexpr bool\n\tany_modified() const noexcept {\n\t\treturn 0u != (m_states & all_mask_modified);\n\t}\n\n\t\/**\n\t\tCheck if all props match external storage.\n\t*\/\n\tconstexpr bool\n\tall_original() const noexcept {\n\t\treturn all_mask_original == (m_states & all_mask_original);\n\t}\n\n\t\/**\n\t\tCheck if all supplied props are uninitialized.\n\t*\/\n\tconstexpr bool\n\tall_uninitialized() const noexcept {\n\t\treturn 0u == (m_states & m_states_supplied);\n\t}\n\n\t\/**\n\t\tCheck if all supplied data props are initialized.\n\t*\/\n\tconstexpr bool\n\tall_data_initialized() const noexcept {\n\t\t\/\/ NB: Non-supplied props \"are\" original within the store\n\t\t\/\/ and all other states imply the prop is initialized\n\t\treturn shift_down(m_states, IO::PropType::primary)\n\t\t\t&& shift_down(m_states, IO::PropType::auxiliary);\n\t}\n\n\t\/**\n\t\tCheck if prop is initialized.\n\n\t\t@param prop_type Prop type.\n\t*\/\n\tconstexpr bool\n\tis_initialized(\n\t\tIO::PropType const prop_type\n\t) const noexcept {\n\t\treturn 0u != shift_down(m_states, prop_type);\n\t}\n\n\t\/**\n\t\tCheck if prop is supplied.\n\n\t\t@param prop_type Prop type.\n\t*\/\n\tconstexpr bool\n\tsupplies(\n\t\tIO::PropType const prop_type\n\t) const noexcept {\n\t\treturn supplies_all(IO::prop_flag(prop_type));\n\t}\n\n\t\/**\n\t\tCheck if all given props are supplied.\n\t*\/\n\tconstexpr bool\n\tsupplies_all(\n\t\tIO::PropTypeBit const props\n\t) const noexcept {\n\t\treturn\n\t\t\tenum_cast(props)\n\t\t\t== (enum_cast(get_supplied()) & enum_cast(props))\n\t\t;\n\t}\n\n\t\/**\n\t\tCheck if any given props are supplied.\n\t*\/\n\tconstexpr bool\n\tsupplies_any(\n\t\tIO::PropTypeBit const props\n\t) const noexcept {\n\t\treturn enum_cast(get_supplied()) & enum_cast(props);\n\t}\n\n\t\/**\n\t\tGet store value.\n\t*\/\n\tconstexpr unsigned\n\tget_value() const noexcept {\n\t\treturn m_states;\n\t}\n\n\t\/**\n\t\tGet full state for prop.\n\n\t\t@param prop_type Prop type.\n\t*\/\n\tconstexpr IO::PropState\n\tget_state(\n\t\tIO::PropType const prop_type\n\t) const noexcept {\n\t\treturn static_cast<IO::PropState>(\n\t\t\tshift_down(m_states, prop_type)\n\t\t);\n\t}\n\n\t\/**\n\t\tGet supplied props.\n\t*\/\n\tconstexpr IO::PropTypeBit\n\tget_supplied() const noexcept {\n\t\treturn static_cast<IO::PropTypeBit>(\n\t\t\tm_states_supplied >> flag_shift\n\t\t);\n\t}\n\/\/\/ @}\n\n\/** @name Operations *\/ \/\/\/ @{\n\t\/**\n\t\tReset all states to uninitialized.\n\n\t\t@note Non-supplied states are not modified.\n\n\t\t@returns @c *this.\n\t*\/\n\tPropStateStore&\n\treset_all() noexcept {\n\t\tm_states = ~m_states_supplied & mask_unsupplied_implied;\n\t\treturn *this;\n\t}\n\n\t\/**\n\t\tReset a prop state to uninitialized.\n\n\t\t@note If the prop is not supplied, this has no effect.\n\n\t\t@returns @c *this.\n\t\t@param prop_type Prop type.\n\t*\/\n\tPropStateStore&\n\treset(\n\t\tPropType const prop_type\n\t) noexcept {\n\t\tif (supplies(prop_type)) {\n\t\t\tm_states = mask_off(m_states, prop_type);\n\t\t}\n\t\treturn *this;\n\t}\n\n\t\/**\n\t\tAssign prop state.\n\n\t\t@note If the prop is not supplied, this has no effect.\n\n\t\t@par\n\t\t@note IO::PropState::unsupplied is masked out\n\t\tof @a state before assignment. Only the constructor can\n\t\tassign this state.\n\n\t\t@returns @c *this.\n\t\t@param prop_type Prop type.\n\t\t@param state Prop state.\n\t*\/\n\tPropStateStore&\n\tassign(\n\t\tIO::PropType const prop_type,\n\t\tIO::PropState const state\n\t) noexcept {\n\t\tif (supplies(prop_type)) {\n\t\t\tm_states\n\t\t\t\t= mask_off(m_states, prop_type)\n\t\t\t\t| shift_up(\n\t\t\t\t\t~prop_unsupplied_single & enum_cast(state),\n\t\t\t\t\tprop_type\n\t\t\t\t)\n\t\t\t;\n\t\t}\n\t\treturn *this;\n\t}\n\n\tPropStateStore&\n\tassign_all(\n\t\tIO::PropState const state\n\t) noexcept {\n\t\tswitch (state) {\n\t\tcase IO::PropState::unsupplied:\n\t\t\treset_all();\n\t\t\tbreak;\n\t\tcase IO::PropState::original:\n\t\t\tm_states\n\t\t\t\t= (~m_states_supplied & mask_unsupplied_implied)\n\t\t\t\t| (m_states_supplied & all_mask_original)\n\t\t\t;\n\t\t\tbreak;\n\t\tcase IO::PropState::modified:\n\t\t\tm_states\n\t\t\t\t= (~m_states_supplied & mask_unsupplied_implied)\n\t\t\t\t| (m_states_supplied & all_mask_modified)\n\t\t\t;\n\t\t\tbreak;\n\t\t}\n\t\treturn *this;\n\t}\n\/\/\/ @}\n};\n\n\/** @} *\/ \/\/ end of doc-group prop\n\/** @} *\/ \/\/ end of doc-group io\n\n} \/\/ namespace IO\n} \/\/ namespace Hord\n\n#endif \/\/ HORD_IO_PROPSTATESTORE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2013-2014 mogemimi.\n\/\/\n\/\/ Distributed under the MIT License.\n\/\/ See accompanying file LICENSE.md or copy at\n\/\/ http:\/\/enginetrouble.net\/pomdog\/LICENSE.md for details.\n\/\/\n\n#ifndef POMDOG_MATHHELPER_F07877B3_827B_4997_8895_51BD6934A0B7_HPP\n#define POMDOG_MATHHELPER_F07877B3_827B_4997_8895_51BD6934A0B7_HPP\n\n#if (_MSC_VER > 1000)\n#\tpragma once\n#endif\n\n#include \"Degree.hpp\"\n#include \"Radian.hpp\"\n#include <cstdint>\n#include <cfloat>\n#include <type_traits>\n\nnamespace Pomdog {\n\ntemplate <typename T>\nstruct MathConstants;\n\ntemplate <>\nstruct MathConstants<float>\n{\n\tstatic constexpr float Pi() { return 3.1415926535f; }\n\tstatic constexpr float TwoPi() { return 6.2831853071f; }\n\tstatic constexpr float OneOverPi() { return 0.3183098861f; }\n\tstatic constexpr float OneOver2Pi() { return 0.1591549430f; }\n\tstatic constexpr float PiOver2() { return 1.5707963267f; }\n\tstatic constexpr float PiOver4() { return 0.7853981633f; }\n};\n\ntemplate <>\nstruct MathConstants<double>\n{\n\tstatic constexpr float Pi() { return 3.14159265358979323846; }\n\tstatic constexpr float TwoPi() { return 6.28318530717958647692; }\n\tstatic constexpr float OneOverPi() { return 0.31830988618379067154; }\n\tstatic constexpr float OneOver2Pi() { return 0.15915494309189533576; }\n\tstatic constexpr float PiOver2() { return 1.57079632679489661923; }\n\tstatic constexpr float PiOver4() { return 0.78539816339744830962; }\n};\n\nnamespace MathHelper {\n\/\/-------------------------------------------------------------------\ntemplate <typename T>\nT Clamp(T const& x, T const& min, T const& max)\n{\n\tstatic_assert(std::is_arithmetic<T>::value, \"\");\n\tPOMDOG_ASSERT_MESSAGE(min < max, \"In Clamp, maxval is out of range\");\n\tif (x < min) {\n\t\treturn min;\n\t}\n\tif (x > max) {\n\t\treturn max;\n\t}\n\treturn x;\n}\n\/\/-------------------------------------------------------------------\ntemplate <typename T>\nT Saturate(T const& x)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"T is floaing point number\");\n\treturn Clamp(x, T(0), T(1));\n}\n\/\/-------------------------------------------------------------------\n\/\/\/@~Japanese\n\/\/\/ @brief 線形補間を行います。\ntemplate <typename T>\nT Lerp(T const& source1, T const& source2, T const& amount)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"T is floaing point number\");\n\treturn source1 + amount * (source2 - source1);\n}\n\/\/-------------------------------------------------------------------\n\/\/\/@~Japanese\n\/\/\/ @brief スムーズなエルミート補間を行います。\ntemplate <typename T>\nT SmoothStep(T const& min, T const& max, T const& amount)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"T is floaing point number\");\n\t\/\/POMDOG_ASSERT(amount >= 0);\n\t\/\/POMDOG_ASSERT(amount <= 1);\n\tauto x = Saturate(amount);\n\tauto scale = x * x * (T(3) - T(2) * x);\n\treturn min + scale * (max - min);\n}\n\/\/-------------------------------------------------------------------\ntemplate <typename T>\nRadian<T> ToRadians(Degree<T> const& degrees)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"\");\n\tconstexpr auto scaleFactor = MathConstants<T>::Pi() * (static_cast<T>(1) \/ static_cast<T>(180));\n\treturn Radian<T>(degrees.value * scaleFactor);\n}\n\/\/-------------------------------------------------------------------\ntemplate <typename T>\nDegree<T> ToDegrees(Radian<T> const& radians)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"\");\n\tconstexpr auto scaleFactor = static_cast<T>(180) * (static_cast<T>(1) \/ MathConstants<T>::Pi());\n\treturn Degree<T>(radians.value * scaleFactor);\n}\n\n}\/\/ namespace MathHelper\n}\/\/ namespace Pomdog\n\n#endif \/\/ !defined(POMDOG_MATHHELPER_F07877B3_827B_4997_8895_51BD6934A0B7_HPP)\n<commit_msg>Fix result type<commit_after>\/\/\n\/\/ Copyright (C) 2013-2014 mogemimi.\n\/\/\n\/\/ Distributed under the MIT License.\n\/\/ See accompanying file LICENSE.md or copy at\n\/\/ http:\/\/enginetrouble.net\/pomdog\/LICENSE.md for details.\n\/\/\n\n#ifndef POMDOG_MATHHELPER_F07877B3_827B_4997_8895_51BD6934A0B7_HPP\n#define POMDOG_MATHHELPER_F07877B3_827B_4997_8895_51BD6934A0B7_HPP\n\n#if (_MSC_VER > 1000)\n#\tpragma once\n#endif\n\n#include \"Degree.hpp\"\n#include \"Radian.hpp\"\n#include <cstdint>\n#include <cfloat>\n#include <type_traits>\n\nnamespace Pomdog {\n\ntemplate <typename T>\nstruct MathConstants;\n\ntemplate <>\nstruct MathConstants<float>\n{\n\tstatic constexpr float Pi() { return 3.1415926535f; }\n\tstatic constexpr float TwoPi() { return 6.2831853071f; }\n\tstatic constexpr float OneOverPi() { return 0.3183098861f; }\n\tstatic constexpr float OneOver2Pi() { return 0.1591549430f; }\n\tstatic constexpr float PiOver2() { return 1.5707963267f; }\n\tstatic constexpr float PiOver4() { return 0.7853981633f; }\n};\n\ntemplate <>\nstruct MathConstants<double>\n{\n\tstatic constexpr double Pi() { return 3.14159265358979323846; }\n\tstatic constexpr double TwoPi() { return 6.28318530717958647692; }\n\tstatic constexpr double OneOverPi() { return 0.31830988618379067154; }\n\tstatic constexpr double OneOver2Pi() { return 0.15915494309189533576; }\n\tstatic constexpr double PiOver2() { return 1.57079632679489661923; }\n\tstatic constexpr double PiOver4() { return 0.78539816339744830962; }\n};\n\nnamespace MathHelper {\n\/\/-------------------------------------------------------------------\ntemplate <typename T>\nT Clamp(T const& x, T const& min, T const& max)\n{\n\tstatic_assert(std::is_arithmetic<T>::value, \"\");\n\tPOMDOG_ASSERT_MESSAGE(min < max, \"In Clamp, maxval is out of range\");\n\tif (x < min) {\n\t\treturn min;\n\t}\n\tif (x > max) {\n\t\treturn max;\n\t}\n\treturn x;\n}\n\/\/-------------------------------------------------------------------\ntemplate <typename T>\nT Saturate(T const& x)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"T is floaing point number\");\n\treturn Clamp(x, T(0), T(1));\n}\n\/\/-------------------------------------------------------------------\n\/\/\/@~Japanese\n\/\/\/ @brief 線形補間を行います。\ntemplate <typename T>\nT Lerp(T const& source1, T const& source2, T const& amount)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"T is floaing point number\");\n\treturn source1 + amount * (source2 - source1);\n}\n\/\/-------------------------------------------------------------------\n\/\/\/@~Japanese\n\/\/\/ @brief スムーズなエルミート補間を行います。\ntemplate <typename T>\nT SmoothStep(T const& min, T const& max, T const& amount)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"T is floaing point number\");\n\t\/\/POMDOG_ASSERT(amount >= 0);\n\t\/\/POMDOG_ASSERT(amount <= 1);\n\tauto x = Saturate(amount);\n\tauto scale = x * x * (T(3) - T(2) * x);\n\treturn min + scale * (max - min);\n}\n\/\/-------------------------------------------------------------------\ntemplate <typename T>\nRadian<T> ToRadians(Degree<T> const& degrees)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"\");\n\tconstexpr auto scaleFactor = MathConstants<T>::Pi() * (static_cast<T>(1) \/ static_cast<T>(180));\n\treturn Radian<T>(degrees.value * scaleFactor);\n}\n\/\/-------------------------------------------------------------------\ntemplate <typename T>\nDegree<T> ToDegrees(Radian<T> const& radians)\n{\n\tstatic_assert(std::is_floating_point<T>::value, \"\");\n\tconstexpr auto scaleFactor = static_cast<T>(180) * (static_cast<T>(1) \/ MathConstants<T>::Pi());\n\treturn Degree<T>(radians.value * scaleFactor);\n}\n\n}\/\/ namespace MathHelper\n}\/\/ namespace Pomdog\n\n#endif \/\/ !defined(POMDOG_MATHHELPER_F07877B3_827B_4997_8895_51BD6934A0B7_HPP)\n<|endoftext|>"} {"text":"<commit_before>\/*\n** File Name: circular_shift.hpp\n** Author: Aditya Ramesh\n** Date: 03\/20\/2015\n** Contact: _@adityaramesh.com\n**\n** XXX: Clang seems to be buggy in compiling the inline assembly below in\n** certain situations.\n*\/\n\n#ifndef ZC5D2A64A_2B75_4209_B5EE_48410B26BFAE\n#define ZC5D2A64A_2B75_4209_B5EE_48410B26BFAE\n\n#include <type_traits>\n#include <ccbase\/platform\/attributes.hpp>\n#include <ccbase\/platform\/identification.hpp>\n\n#if !(PLATFORM_ARCH == PLATFORM_ARCH_X86 && \\\n (PLATFORM_COMPILER == PLATFORM_COMPILER_CLANG || \\\n PLATFORM_COMPILER == PLATFORM_COMPILER_GCC || \\\n PLATFORM_COMPILER == PLATFORM_COMPILER_ICC))\n\t#warning \"Unsupported platform for cc::rotl and cc::rotr.\"\n\t#warning \"The operation will not use intrinsics.\"\n#endif\n\nnamespace cc {\n\n#if (PLATFORM_ARCH == PLATFORM_ARCH_X86 && \\\n (PLATFORM_COMPILER == PLATFORM_COMPILER_CLANG || \\\n PLATFORM_COMPILER == PLATFORM_COMPILER_GCC || \\\n PLATFORM_COMPILER == PLATFORM_COMPILER_ICC))\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint8_t rotl(uint8_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint8_t{};\n\tasm(\"rolb %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint16_t rotl(uint16_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint16_t{};\n\tasm(\"rolw %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint32_t rotl(uint32_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint32_t{};\n\tasm(\"roll %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint64_t rotl(uint64_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint64_t{};\n\tasm(\"rolq %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint8_t rotr(uint8_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint8_t{};\n\tasm(\"rorb %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint16_t rotr(uint16_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint16_t{};\n\tasm(\"rorw %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint32_t rotr(uint32_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint32_t{};\n\tasm(\"rorl %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint64_t rotr(uint64_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint64_t{};\n\tasm(\"rorq %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\n#else\n\ntemplate <\n\tclass Integer1,\n\tclass Integer2,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer1>::value &&\n\t\tstd::is_unsigned<Integer2>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE constexpr\nInteger1 unsafe_rotl(Integer1 x, Integer2 shift)\nnoexcept\n{\n\treturn (x << shift) | (x >> (8 * sizeof(Integer1) - shift));\n}\n\ntemplate <\n\tclass Integer1,\n\tclass Integer2,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer1>::value &&\n\t\tstd::is_unsigned<Integer2>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE constexpr\nInteger1 unsafe_rotr(Integer1 x, Integer2 shift)\nnoexcept\n{\n\treturn (x >> shift) | (x << (8 * sizeof(Integer1) - shift));\n}\n\ntemplate <\n\tclass Integer1,\n\tclass Integer2,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer1>::value &&\n\t\tstd::is_unsigned<Integer2>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE constexpr\nInteger1 rotl(Integer1 x, Integer2 shift)\nnoexcept\n{\n\treturn unsafe_rotl(x, shift % (sizeof(Integer1) - 1));\n}\n\ntemplate <\n\tclass Integer1,\n\tclass Integer2,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer1>::value &&\n\t\tstd::is_unsigned<Integer2>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE constexpr\nInteger1 rotr(Integer1 x, Integer2 shift)\nnoexcept\n{\n\treturn unsafe_rotr(x, shift % (sizeof(Integer1) - 1));\n}\n\n#endif\n\n}\n\n#endif\n<commit_msg>Updated name in header.<commit_after>\/*\n** File Name: rotate.hpp\n** Author: Aditya Ramesh\n** Date: 03\/20\/2015\n** Contact: _@adityaramesh.com\n**\n** XXX: Clang seems to be buggy in compiling the inline assembly below in\n** certain situations.\n*\/\n\n#ifndef ZC5D2A64A_2B75_4209_B5EE_48410B26BFAE\n#define ZC5D2A64A_2B75_4209_B5EE_48410B26BFAE\n\n#include <type_traits>\n#include <ccbase\/platform\/attributes.hpp>\n#include <ccbase\/platform\/identification.hpp>\n\n#if !(PLATFORM_ARCH == PLATFORM_ARCH_X86 && \\\n (PLATFORM_COMPILER == PLATFORM_COMPILER_CLANG || \\\n PLATFORM_COMPILER == PLATFORM_COMPILER_GCC || \\\n PLATFORM_COMPILER == PLATFORM_COMPILER_ICC))\n\t#warning \"Unsupported platform for cc::rotl and cc::rotr.\"\n\t#warning \"The operation will not use intrinsics.\"\n#endif\n\nnamespace cc {\n\n#if (PLATFORM_ARCH == PLATFORM_ARCH_X86 && \\\n (PLATFORM_COMPILER == PLATFORM_COMPILER_CLANG || \\\n PLATFORM_COMPILER == PLATFORM_COMPILER_GCC || \\\n PLATFORM_COMPILER == PLATFORM_COMPILER_ICC))\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint8_t rotl(uint8_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint8_t{};\n\tasm(\"rolb %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint16_t rotl(uint16_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint16_t{};\n\tasm(\"rolw %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint32_t rotl(uint32_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint32_t{};\n\tasm(\"roll %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint64_t rotl(uint64_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint64_t{};\n\tasm(\"rolq %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint8_t rotr(uint8_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint8_t{};\n\tasm(\"rorb %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint16_t rotr(uint16_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint16_t{};\n\tasm(\"rorw %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint32_t rotr(uint32_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint32_t{};\n\tasm(\"rorl %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\ntemplate <\n\tclass Integer,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE\nuint64_t rotr(uint64_t x, Integer shift)\nnoexcept\n{\n\tauto res = uint64_t{};\n\tasm(\"rorq %%cl, %0\"\n\t\t: \"=r\" (res)\n\t\t: \"c\" (shift), \"0\" (x)\n\t);\n\treturn res;\n}\n\n#else\n\ntemplate <\n\tclass Integer1,\n\tclass Integer2,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer1>::value &&\n\t\tstd::is_unsigned<Integer2>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE constexpr\nInteger1 unsafe_rotl(Integer1 x, Integer2 shift)\nnoexcept\n{\n\treturn (x << shift) | (x >> (8 * sizeof(Integer1) - shift));\n}\n\ntemplate <\n\tclass Integer1,\n\tclass Integer2,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer1>::value &&\n\t\tstd::is_unsigned<Integer2>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE constexpr\nInteger1 unsafe_rotr(Integer1 x, Integer2 shift)\nnoexcept\n{\n\treturn (x >> shift) | (x << (8 * sizeof(Integer1) - shift));\n}\n\ntemplate <\n\tclass Integer1,\n\tclass Integer2,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer1>::value &&\n\t\tstd::is_unsigned<Integer2>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE constexpr\nInteger1 rotl(Integer1 x, Integer2 shift)\nnoexcept\n{\n\treturn unsafe_rotl(x, shift % (sizeof(Integer1) - 1));\n}\n\ntemplate <\n\tclass Integer1,\n\tclass Integer2,\n\ttypename std::enable_if<\n\t\tstd::is_unsigned<Integer1>::value &&\n\t\tstd::is_unsigned<Integer2>::value, int\n\t>::type = 0\n>\nCC_ALWAYS_INLINE constexpr\nInteger1 rotr(Integer1 x, Integer2 shift)\nnoexcept\n{\n\treturn unsafe_rotr(x, shift % (sizeof(Integer1) - 1));\n}\n\n#endif\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ SendDlg.cpp : ʵļ\n\/\/\n\n#include \"stdafx.h\"\n#include \"DacrsUI.h\"\n#include \"SendDlg.h\"\n#include \"afxdialogex.h\"\n\n\n\/\/ CSendDlg Ի\n\nIMPLEMENT_DYNAMIC(CSendDlg, CDialogBar)\n\nCSendDlg::CSendDlg()\n{\n\tm_pBmp = NULL ;\n}\n\nCSendDlg::~CSendDlg()\n{\n\tif( NULL != m_pBmp ) {\n\t\tDeleteObject(m_pBmp) ;\n\t\tm_pBmp = NULL ;\n\t}\n}\n\nvoid CSendDlg::DoDataExchange(CDataExchange* pDX)\n{\n\tCDialogBar::DoDataExchange(pDX);\n\tDDX_Control(pDX, IDC_BUTTON_ADDBOOK , m_rBtnAddbook);\n\tDDX_Control(pDX, IDC_SENDTRNSFER , m_rBtnSend);\n\tDDX_Control(pDX, IDC_STATIC_XM , m_strTx1);\n\tDDX_Control(pDX, IDC_COMBO_ADDR_OUT , m_addrbook);\n}\n\n\nBEGIN_MESSAGE_MAP(CSendDlg, CDialogBar)\n\tON_BN_CLICKED(IDC_SENDTRNSFER, &CSendDlg::OnBnClickedSendtrnsfer)\n\tON_CBN_SELCHANGE(IDC_COMBO_ADDR_OUT, &CSendDlg::OnCbnSelchangeCombo1)\n\tON_MESSAGE(MSG_USER_SEND_UI , &CSendDlg::OnShowListaddrData )\n\tON_WM_CREATE()\n\tON_WM_ERASEBKGND()\n\tON_BN_CLICKED(IDC_BUTTON_ADDBOOK, &CSendDlg::OnBnClickedButtonAddbook)\nEND_MESSAGE_MAP()\n\n\n\/\/ CTransfer Ϣ\n\nvoid CSendDlg::SetBkBmpNid( UINT nBitmapIn ) \n{\n\tif( NULL != m_pBmp ) {\n\t\t::DeleteObject( m_pBmp ) ;\n\t\tm_pBmp = NULL ;\n\t}\n\tm_pBmp\t= NULL ;\n\tHINSTANCE\thInstResource = NULL;\t\n\thInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP);\n\tif( NULL != hInstResource ) {\n\t\tm_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0);\n\t}\n}\n\nvoid CSendDlg::OnBnClickedSendtrnsfer()\n{\n\t\/\/ TODO: ڴӿؼ֪ͨ\n\tif (m_mapAddrInfo.size() == 0)\n\t{\n\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"͵ַ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\treturn;\n\t}\n\tCString text;\n\tm_addrbook.GetWindowText(text) ;\n\tuistruct::LISTADDR_t data;\n\tif(text!=_T(\"\"))\n\t{\n\t\tif(m_mapAddrInfo.count(text)<=0)\n\t\t{\n\t\t\t\/\/::MessageBox( this->GetSafeHwnd() ,_T(\"͵ַ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\t\t\/\/uistruct::LISTADDR_t te = m_pListaddrInfo[text];\n\t\tdata = m_mapAddrInfo[text];\n\t\n\t}\n\n\t\tCString strCommand , strMaddress , strMoney;\n\t\tif(!data.bSign) \n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"͵ַδ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\n\t\tGetDlgItem(IDC_EDIT_DESADDRESS)->GetWindowTextA(strMaddress);\n\t\tif (strMaddress == _T(\"\"))\n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"ַܵδ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\t\tif(!strcmp(strMaddress.GetString(), data.address))\n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"͵ַĿĵַͬ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tGetDlgItem(IDC_EDIT_MONEY)->GetWindowTextA(strMoney);\n\t\tdouble dSendMoney = atof(strMoney);\n\t\tif(dSendMoney > data.fMoney || ( data.fMoney>-0.0000001 && data.fMoney< 0.000001 )) \n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"˻\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\n\t\tif(_T(\"\") == strMoney.GetString() || (dSendMoney >-0.0000001 && dSendMoney< 0.000001))\n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"ͽΪ0\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\t\tstrCommand.Format(_T(\"%s %s %s %lld\"),_T(\"sendtoaddress\") ,data.address ,strMaddress ,REAL_MONEY(dSendMoney));\n\t\tCStringA strShowData ;\n\n\t\tCSoyPayHelp::getInstance()->SendRpc(strCommand,strShowData);\n\n\t\tJson::Reader reader; \n\t\tJson::Value root; \n\n\t\tif (!reader.parse(strShowData.GetString(), root)) \n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,strShowData , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn ;\n\t\t}\n\t\tBOOL bRes = FALSE ;\n\t\tCString strGettxdetail;\n\t\tint pos = strShowData.Find(\"hash\");\n\t\tif ( pos >=0 ) {\n\t\t\t\/\/뵽ݿ\n\t\t\tCString strHash,strHash1 ;\n\t\t\tstrHash.Format(_T(\"'%s'\") , root[\"hash\"].asCString() );\n\t\t\tstrHash1.Format(_T(\"%s\") , root[\"hash\"].asCString() );\n\t\t\ttheApp.cs_SqlData.Lock();\n\t\t\tint nItem = theApp.m_SqliteDeal.FindDB(_T(\"revtransaction\") , strHash1 ,_T(\"hash\") ) ;\n\t\t\ttheApp.cs_SqlData.Unlock();\n\n\t\t\tif ( 0 == nItem ) {\n\n\t\t\t\tCPostMsg postmsg(MSG_USER_GET_UPDATABASE,WM_REVTRANSACTION);\n\t\t\t\tpostmsg.SetData(strHash);\n\t\t\t\ttheApp.m_MsgQueue.push(postmsg);\n\t\t\t}\n\t\t}\n\n\t\tCString strData;\n\t\tif ( pos >=0 ) {\n\t\t\tstrData.Format( _T(\"ת˳ɹ\\n%s\") , root[\"hash\"].asCString() ) ;\n\t\t}else{\n\t\t\tstrData.Format( _T(\"תʧ!\") ) ;\n\t\t}\n\t\t::MessageBox( this->GetSafeHwnd() ,strData , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\n}\n\n\nvoid CSendDlg::OnCbnSelchangeCombo1()\n{\n\t\/\/ TODO: ڴӿؼ֪ͨ\n\tif (m_mapAddrInfo.size() == 0)\n\t{\n\t\treturn;\n\t}\n\tCString text;\n\tm_addrbook.GetWindowText(text) ;\n\tif(text!=_T(\"\"))\n\t{\n\t if(m_mapAddrInfo.count(text)<=0)\n\t {\n\t\t TRACE(\"map OnCbnSelchangeCombo1 error\");\n\t\t return;\n\t }\n\t\/\/uistruct::LISTADDR_t te = m_pListaddrInfo[text];\n\tCString strshow;\n\tstrshow.Format(_T(\"%.8f\"),m_mapAddrInfo[text].fMoney);\n\t((CStatic*)GetDlgItem(IDC_STATIC_XM))->SetWindowText(strshow);\n\tInvalidate();\n\t}\n\n}\nBOOL CSendDlg::AddListaddrDataBox(){\n\n\ttheApp.cs_SqlData.Lock();\n\ttheApp.m_SqliteDeal.GetListaddrData(&m_mapAddrInfo);\n\ttheApp.cs_SqlData.Unlock();\n\n\tif ( 0 == m_mapAddrInfo.size() ) return FALSE ;\n\n\t\/\/ComBoxؼ\n\t((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->ResetContent();\n\t\/\/صComBoxؼ\n\tint nItem = 0;\n\tstd::map<CString,uistruct::LISTADDR_t>::const_iterator const_it;\n\tfor ( const_it = m_mapAddrInfo.begin() ; const_it != m_mapAddrInfo.end() ; const_it++ ) {\n\n\t\t((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->InsertString(nItem , const_it->first );\n\t\t\/\/((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->SetItemData(nItem, (DWORD_PTR)&(*const_it));\n\t\tnItem++;\n\t}\n\t((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->SetCurSel(0);\n\n\tCString address;\n\tm_addrbook.GetWindowText(address);\n\tstd::map<CString,uistruct::LISTADDR_t>::const_iterator item = m_mapAddrInfo.find(address);\n\t\/\/uistruct::LISTADDR_t pListAddr = m_pListaddrInfo.find(address);\n\n\tuistruct::LISTADDR_t *pListAddr = (uistruct::LISTADDR_t*)(((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->GetItemData(((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->GetCurSel())) ;\n\n\tif ( m_mapAddrInfo.end()!= item ) {\n\t\tuistruct::LISTADDR_t addrstruc = item->second;\n\t\/\/\tdouble money = CSoyPayHelp::getInstance()->GetAccountBalance(pListAddr->address);\n\t\tCString strshow;\n\t\tstrshow.Format(_T(\"%.8f\"),addrstruc.fMoney);\n\t\tm_strTx1.SetWindowText(strshow);\n\t\t\/\/((CStatic*)GetDlgItem(IDC_STATIC_XM))->SetWindowText(strshow);\n\t\tInvalidate();\n\t}\n\treturn TRUE ;\n}\n\nLRESULT CSendDlg::OnShowListaddrData( WPARAM wParam, LPARAM lParam ) \n{\n\t\/\/\n\tint type = (int)wParam;\n\tswitch(type)\n\t{\n\tcase WM_UP_ADDRESS:\n\t\t{\n\t\t\tModifyComboxItem();\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase WM_UP_NEWADDRESS:\n\t\t{\n\t\t\tInsertComboxIitem();\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\n\t}\n\treturn 0 ;\n}\n\/\/ CSendDlg Ϣ\n\n\nBOOL CSendDlg::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID)\n{\n\t\/\/ TODO: ڴרô\/û\n\n\tBOOL bRes = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID);\n\tif (bRes) \n\t{\n\t\t\/\/m_rBtnSend.LoadBitmaps(IDB_BITMAP_BOTTON_SEND1,IDB_BITMAP_BOTTON_SEND2,IDB_BITMAP_BOTTON_SEND3,IDB_BITMAP_BOTTON_SEND3);\n\t\tm_rBtnAddbook.LoadBitmaps(IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK);\n\t\tUpdateData(0);\n\t\tm_strTx1.SetFont(120, _T(\"\"));\t\t\t\t\/\/ʾʹС\n\t\tm_strTx1.SetWindowText(_T(\"\"));\n\t\tAddListaddrDataBox();\n\n\t\tm_rBtnSend.SetBitmaps( IDB_BITMAP_BUTTON , RGB(255, 255, 0) , IDB_BITMAP_BUTTON , RGB(255, 255, 255) );\n\t\tm_rBtnSend.SetAlign(CButtonST::ST_ALIGN_OVERLAP);\n\t\tm_rBtnSend.SetWindowText(\"\") ;\n\t\tm_rBtnSend.SetFontEx(24 , _T(\"΢ź\"));\n\t\tm_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_OUT , RGB(0, 0, 0));\n\t\tm_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_IN , RGB(200, 75, 60));\n\t\tm_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_FOCUS, RGB(0, 0, 0));\n\t\tm_rBtnSend.SetColor(CButtonST::BTNST_COLOR_BK_IN, RGB(0, 0, 0));\n\t\tm_rBtnSend.SizeToContent();\n\n\t\ttheApp.SubscribeMsg( theApp.GetMtHthrdId() , GetSafeHwnd() , MSG_USER_SEND_UI ) ;\n\t\t((CComboBox*)GetDlgItem(IDC_COMBO2))->SetCurSel(0);\n\t\t\n\t}\n\treturn bRes;\n}\n\n\nint CSendDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)\n{\n\tif (CDialogBar::OnCreate(lpCreateStruct) == -1)\n\t\treturn -1;\n\n\t\/\/ TODO: ڴרõĴ\n\tSetBkBmpNid(IDB_BITMAP_SENDUI_BJ);\n\n\treturn 0;\n}\n\n\nBOOL CSendDlg::OnEraseBkgnd(CDC* pDC)\n{\n\t\/\/ TODO: ڴϢ\/Ĭֵ\n\tCRect rect; \n\tGetClientRect(&rect); \n\n\tif(m_pBmp != NULL) { \n\t\tBITMAP bm; \n\t\tCDC dcMem; \n\t\t::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm); \n\t\tdcMem.CreateCompatibleDC(NULL); \n\t\tHBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp); \n\t\tpDC-> StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY); \n\n\t\tdcMem.SelectObject(pOldBitmap);\n\t\tdcMem.DeleteDC();\n\t} else \n\t\tCWnd::OnEraseBkgnd(pDC); \n\n\treturn 1;\n}\n\nvoid CSendDlg::OnBnClickedButtonAddbook()\n{\n\t\/\/ TODO: ڴӿؼ֪ͨ\n}\nvoid CSendDlg::ModifyComboxItem(){\n\tCPostMsg postmsg;\n\tif (!theApp.m_UiSendDlgQueue.pop(postmsg))\n\t{\n\t\treturn ;\n\t}\n\n\tuistruct::LISTADDR_t addr; \n\tstring strTemp = postmsg.GetData();\n\taddr.JsonToStruct(strTemp.c_str());\n\n\tCString addressd;\n\taddressd.Format(_T(\"%s\"),addr.address);\n\n\tif(m_mapAddrInfo.count(addressd)<=0)\n\t{\n\t\tTRACE(\"map ModifyComboxItem error\");\n\t\treturn;\n\t}\n\tm_mapAddrInfo[addressd]=addr;\n\t\n\t\t\n}\nvoid CSendDlg::InsertComboxIitem()\n{\n\tCPostMsg postmsg;\n\tif (!theApp.m_UiSendDlgQueue.pop(postmsg))\n\t{\n\t\treturn ;\n\t}\n\n\tuistruct::LISTADDR_t addr; \n\tstring strTemp = postmsg.GetData();\n\taddr.JsonToStruct(strTemp.c_str());\n\t\n\tCString addressd;\n\taddressd.Format(_T(\"%s\"),addr.address);\n\n\tif(m_mapAddrInfo.count(addressd)>0)\n\t{\n\t\tTRACE(\"map InsertComboxIitem error\");\n\t\treturn;\n\t}\n\tm_mapAddrInfo[addressd]=addr;\n\n\tint item = m_addrbook.GetCount();\n\tm_addrbook.InsertString(item,addressd);\n}\n<commit_msg>modify OnCbnSelchangeCombo1 funciton<commit_after>\/\/ SendDlg.cpp : ʵļ\n\/\/\n\n#include \"stdafx.h\"\n#include \"DacrsUI.h\"\n#include \"SendDlg.h\"\n#include \"afxdialogex.h\"\n\n\n\/\/ CSendDlg Ի\n\nIMPLEMENT_DYNAMIC(CSendDlg, CDialogBar)\n\nCSendDlg::CSendDlg()\n{\n\tm_pBmp = NULL ;\n}\n\nCSendDlg::~CSendDlg()\n{\n\tif( NULL != m_pBmp ) {\n\t\tDeleteObject(m_pBmp) ;\n\t\tm_pBmp = NULL ;\n\t}\n}\n\nvoid CSendDlg::DoDataExchange(CDataExchange* pDX)\n{\n\tCDialogBar::DoDataExchange(pDX);\n\tDDX_Control(pDX, IDC_BUTTON_ADDBOOK , m_rBtnAddbook);\n\tDDX_Control(pDX, IDC_SENDTRNSFER , m_rBtnSend);\n\tDDX_Control(pDX, IDC_STATIC_XM , m_strTx1);\n\tDDX_Control(pDX, IDC_COMBO_ADDR_OUT , m_addrbook);\n}\n\n\nBEGIN_MESSAGE_MAP(CSendDlg, CDialogBar)\n\tON_BN_CLICKED(IDC_SENDTRNSFER, &CSendDlg::OnBnClickedSendtrnsfer)\n\tON_CBN_SELCHANGE(IDC_COMBO_ADDR_OUT, &CSendDlg::OnCbnSelchangeCombo1)\n\tON_MESSAGE(MSG_USER_SEND_UI , &CSendDlg::OnShowListaddrData )\n\tON_WM_CREATE()\n\tON_WM_ERASEBKGND()\n\tON_BN_CLICKED(IDC_BUTTON_ADDBOOK, &CSendDlg::OnBnClickedButtonAddbook)\nEND_MESSAGE_MAP()\n\n\n\/\/ CTransfer Ϣ\n\nvoid CSendDlg::SetBkBmpNid( UINT nBitmapIn ) \n{\n\tif( NULL != m_pBmp ) {\n\t\t::DeleteObject( m_pBmp ) ;\n\t\tm_pBmp = NULL ;\n\t}\n\tm_pBmp\t= NULL ;\n\tHINSTANCE\thInstResource = NULL;\t\n\thInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP);\n\tif( NULL != hInstResource ) {\n\t\tm_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0);\n\t}\n}\n\nvoid CSendDlg::OnBnClickedSendtrnsfer()\n{\n\t\/\/ TODO: ڴӿؼ֪ͨ\n\tif (m_mapAddrInfo.size() == 0)\n\t{\n\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"͵ַ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\treturn;\n\t}\n\tCString text;\n\tm_addrbook.GetWindowText(text) ;\n\tuistruct::LISTADDR_t data;\n\tif(text!=_T(\"\"))\n\t{\n\t\tif(m_mapAddrInfo.count(text)<=0)\n\t\t{\n\t\t\t\/\/::MessageBox( this->GetSafeHwnd() ,_T(\"͵ַ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\t\t\/\/uistruct::LISTADDR_t te = m_pListaddrInfo[text];\n\t\tdata = m_mapAddrInfo[text];\n\t\n\t}\n\n\t\tCString strCommand , strMaddress , strMoney;\n\t\tif(!data.bSign) \n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"͵ַδ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\n\t\tGetDlgItem(IDC_EDIT_DESADDRESS)->GetWindowTextA(strMaddress);\n\t\tif (strMaddress == _T(\"\"))\n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"ַܵδ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\t\tif(!strcmp(strMaddress.GetString(), data.address))\n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"͵ַĿĵַͬ\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tGetDlgItem(IDC_EDIT_MONEY)->GetWindowTextA(strMoney);\n\t\tdouble dSendMoney = atof(strMoney);\n\t\tif(dSendMoney > data.fMoney || ( data.fMoney>-0.0000001 && data.fMoney< 0.000001 )) \n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"˻\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\n\t\tif(_T(\"\") == strMoney.GetString() || (dSendMoney >-0.0000001 && dSendMoney< 0.000001))\n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,_T(\"ͽΪ0\") , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn;\n\t\t}\n\t\tstrCommand.Format(_T(\"%s %s %s %lld\"),_T(\"sendtoaddress\") ,data.address ,strMaddress ,REAL_MONEY(dSendMoney));\n\t\tCStringA strShowData ;\n\n\t\tCSoyPayHelp::getInstance()->SendRpc(strCommand,strShowData);\n\n\t\tJson::Reader reader; \n\t\tJson::Value root; \n\n\t\tif (!reader.parse(strShowData.GetString(), root)) \n\t\t{\n\t\t\t::MessageBox( this->GetSafeHwnd() ,strShowData , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\t\t\treturn ;\n\t\t}\n\t\tBOOL bRes = FALSE ;\n\t\tCString strGettxdetail;\n\t\tint pos = strShowData.Find(\"hash\");\n\t\tif ( pos >=0 ) {\n\t\t\t\/\/뵽ݿ\n\t\t\tCString strHash,strHash1 ;\n\t\t\tstrHash.Format(_T(\"'%s'\") , root[\"hash\"].asCString() );\n\t\t\tstrHash1.Format(_T(\"%s\") , root[\"hash\"].asCString() );\n\t\t\ttheApp.cs_SqlData.Lock();\n\t\t\tint nItem = theApp.m_SqliteDeal.FindDB(_T(\"revtransaction\") , strHash1 ,_T(\"hash\") ) ;\n\t\t\ttheApp.cs_SqlData.Unlock();\n\n\t\t\tif ( 0 == nItem ) {\n\n\t\t\t\tCPostMsg postmsg(MSG_USER_GET_UPDATABASE,WM_REVTRANSACTION);\n\t\t\t\tpostmsg.SetData(strHash);\n\t\t\t\ttheApp.m_MsgQueue.push(postmsg);\n\t\t\t}\n\t\t}\n\n\t\tCString strData;\n\t\tif ( pos >=0 ) {\n\t\t\tstrData.Format( _T(\"ת˳ɹ\\n%s\") , root[\"hash\"].asCString() ) ;\n\t\t}else{\n\t\t\tstrData.Format( _T(\"תʧ!\") ) ;\n\t\t}\n\t\t::MessageBox( this->GetSafeHwnd() ,strData , _T(\"ʾ\") , MB_ICONINFORMATION ) ;\n\n}\n\n\nvoid CSendDlg::OnCbnSelchangeCombo1()\n{\n\t\/\/ TODO: ڴӿؼ֪ͨ\n\tif (m_mapAddrInfo.size() == 0)\n\t{\n\t\treturn;\n\t}\n\tCString text;\n\tint sel = m_addrbook.GetCurSel();\n\tm_addrbook.GetLBText(sel,text);\n\t\n\t\/\/m_addrbook.GetWindowText(text) ;\n\tif(text!=_T(\"\"))\n\t{\n\t if(m_mapAddrInfo.count(text)<=0)\n\t {\n\t\t TRACE(\"map OnCbnSelchangeCombo1 error\");\n\t\t return;\n\t }\n\t\/\/uistruct::LISTADDR_t te = m_pListaddrInfo[text];\n\tCString strshow;\n\tstrshow.Format(_T(\"%.8f\"),m_mapAddrInfo[text].fMoney);\n\t((CStatic*)GetDlgItem(IDC_STATIC_XM))->SetWindowText(strshow);\n\tInvalidate();\n\t}\n\n}\nBOOL CSendDlg::AddListaddrDataBox(){\n\n\ttheApp.cs_SqlData.Lock();\n\ttheApp.m_SqliteDeal.GetListaddrData(&m_mapAddrInfo);\n\ttheApp.cs_SqlData.Unlock();\n\n\tif ( 0 == m_mapAddrInfo.size() ) return FALSE ;\n\n\t\/\/ComBoxؼ\n\t((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->ResetContent();\n\t\/\/صComBoxؼ\n\tint nItem = 0;\n\tstd::map<CString,uistruct::LISTADDR_t>::const_iterator const_it;\n\tfor ( const_it = m_mapAddrInfo.begin() ; const_it != m_mapAddrInfo.end() ; const_it++ ) {\n\n\t\t((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->InsertString(nItem , const_it->first );\n\t\t\/\/((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->SetItemData(nItem, (DWORD_PTR)&(*const_it));\n\t\tnItem++;\n\t}\n\t((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->SetCurSel(0);\n\n\tCString address;\n\tm_addrbook.GetWindowText(address);\n\tstd::map<CString,uistruct::LISTADDR_t>::const_iterator item = m_mapAddrInfo.find(address);\n\t\/\/uistruct::LISTADDR_t pListAddr = m_pListaddrInfo.find(address);\n\n\tuistruct::LISTADDR_t *pListAddr = (uistruct::LISTADDR_t*)(((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->GetItemData(((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->GetCurSel())) ;\n\n\tif ( m_mapAddrInfo.end()!= item ) {\n\t\tuistruct::LISTADDR_t addrstruc = item->second;\n\t\/\/\tdouble money = CSoyPayHelp::getInstance()->GetAccountBalance(pListAddr->address);\n\t\tCString strshow;\n\t\tstrshow.Format(_T(\"%.8f\"),addrstruc.fMoney);\n\t\tm_strTx1.SetWindowText(strshow);\n\t\t\/\/((CStatic*)GetDlgItem(IDC_STATIC_XM))->SetWindowText(strshow);\n\t\tInvalidate();\n\t}\n\treturn TRUE ;\n}\n\nLRESULT CSendDlg::OnShowListaddrData( WPARAM wParam, LPARAM lParam ) \n{\n\t\/\/\n\tint type = (int)wParam;\n\tswitch(type)\n\t{\n\tcase WM_UP_ADDRESS:\n\t\t{\n\t\t\tModifyComboxItem();\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase WM_UP_NEWADDRESS:\n\t\t{\n\t\t\tInsertComboxIitem();\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\n\t}\n\treturn 0 ;\n}\n\/\/ CSendDlg Ϣ\n\n\nBOOL CSendDlg::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID)\n{\n\t\/\/ TODO: ڴרô\/û\n\n\tBOOL bRes = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID);\n\tif (bRes) \n\t{\n\t\t\/\/m_rBtnSend.LoadBitmaps(IDB_BITMAP_BOTTON_SEND1,IDB_BITMAP_BOTTON_SEND2,IDB_BITMAP_BOTTON_SEND3,IDB_BITMAP_BOTTON_SEND3);\n\t\tm_rBtnAddbook.LoadBitmaps(IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK);\n\t\tUpdateData(0);\n\t\tm_strTx1.SetFont(120, _T(\"\"));\t\t\t\t\/\/ʾʹС\n\t\tm_strTx1.SetWindowText(_T(\"\"));\n\t\tAddListaddrDataBox();\n\n\t\tm_rBtnSend.SetBitmaps( IDB_BITMAP_BUTTON , RGB(255, 255, 0) , IDB_BITMAP_BUTTON , RGB(255, 255, 255) );\n\t\tm_rBtnSend.SetAlign(CButtonST::ST_ALIGN_OVERLAP);\n\t\tm_rBtnSend.SetWindowText(\"\") ;\n\t\tm_rBtnSend.SetFontEx(24 , _T(\"΢ź\"));\n\t\tm_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_OUT , RGB(0, 0, 0));\n\t\tm_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_IN , RGB(200, 75, 60));\n\t\tm_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_FOCUS, RGB(0, 0, 0));\n\t\tm_rBtnSend.SetColor(CButtonST::BTNST_COLOR_BK_IN, RGB(0, 0, 0));\n\t\tm_rBtnSend.SizeToContent();\n\n\t\ttheApp.SubscribeMsg( theApp.GetMtHthrdId() , GetSafeHwnd() , MSG_USER_SEND_UI ) ;\n\t\t((CComboBox*)GetDlgItem(IDC_COMBO2))->SetCurSel(0);\n\t\t\n\t}\n\treturn bRes;\n}\n\n\nint CSendDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)\n{\n\tif (CDialogBar::OnCreate(lpCreateStruct) == -1)\n\t\treturn -1;\n\n\t\/\/ TODO: ڴרõĴ\n\tSetBkBmpNid(IDB_BITMAP_SENDUI_BJ);\n\n\treturn 0;\n}\n\n\nBOOL CSendDlg::OnEraseBkgnd(CDC* pDC)\n{\n\t\/\/ TODO: ڴϢ\/Ĭֵ\n\tCRect rect; \n\tGetClientRect(&rect); \n\n\tif(m_pBmp != NULL) { \n\t\tBITMAP bm; \n\t\tCDC dcMem; \n\t\t::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm); \n\t\tdcMem.CreateCompatibleDC(NULL); \n\t\tHBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp); \n\t\tpDC-> StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY); \n\n\t\tdcMem.SelectObject(pOldBitmap);\n\t\tdcMem.DeleteDC();\n\t} else \n\t\tCWnd::OnEraseBkgnd(pDC); \n\n\treturn 1;\n}\n\nvoid CSendDlg::OnBnClickedButtonAddbook()\n{\n\t\/\/ TODO: ڴӿؼ֪ͨ\n}\nvoid CSendDlg::ModifyComboxItem(){\n\tCPostMsg postmsg;\n\tif (!theApp.m_UiSendDlgQueue.pop(postmsg))\n\t{\n\t\treturn ;\n\t}\n\n\tuistruct::LISTADDR_t addr; \n\tstring strTemp = postmsg.GetData();\n\taddr.JsonToStruct(strTemp.c_str());\n\n\tCString addressd;\n\taddressd.Format(_T(\"%s\"),addr.address);\n\n\tif(m_mapAddrInfo.count(addressd)<=0)\n\t{\n\t\tTRACE(\"map ModifyComboxItem error\");\n\t\treturn;\n\t}\n\tm_mapAddrInfo[addressd]=addr;\n\t\n\t\t\n}\nvoid CSendDlg::InsertComboxIitem()\n{\n\tCPostMsg postmsg;\n\tif (!theApp.m_UiSendDlgQueue.pop(postmsg))\n\t{\n\t\treturn ;\n\t}\n\n\tuistruct::LISTADDR_t addr; \n\tstring strTemp = postmsg.GetData();\n\taddr.JsonToStruct(strTemp.c_str());\n\t\n\tCString addressd;\n\taddressd.Format(_T(\"%s\"),addr.address);\n\n\tif(m_mapAddrInfo.count(addressd)>0)\n\t{\n\t\tTRACE(\"map InsertComboxIitem error\");\n\t\treturn;\n\t}\n\tm_mapAddrInfo[addressd]=addr;\n\n\tint item = m_addrbook.GetCount();\n\tm_addrbook.InsertString(item,addressd);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief ThreadCommon class header\n *\n * \\author Copyright (C) 2015 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2015-11-13\n *\/\n\n#ifndef INCLUDE_DISTORTOS_THREADCOMMON_HPP_\n#define INCLUDE_DISTORTOS_THREADCOMMON_HPP_\n\n#include \"distortos\/Semaphore.hpp\"\n#include \"distortos\/Thread.hpp\"\n\nnamespace distortos\n{\n\n\/\/\/ ThreadCommon class implements common functionality of threads\nclass ThreadCommon : public Thread\n{\npublic:\n\n\t\/\/\/ unique_ptr (with deleter) to storage for stack\n\tusing StackStorageUniquePointer = architecture::Stack::StorageUniquePointer;\n\n\t\/**\n\t * \\brief ThreadCommon's constructor\n\t *\n\t * \\param [in] stackStorageUniquePointer is a rvalue reference to StackStorageUniquePointer with storage for stack\n\t * (\\a size bytes long) and appropriate deleter\n\t * \\param [in] size is the size of stack's storage, bytes\n\t * \\param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest\n\t * \\param [in] schedulingPolicy is the scheduling policy of the thread\n\t * \\param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will\n\t * be added, nullptr to inherit thread group from currently running thread\n\t * \\param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception\n\t * of signals for this thread\n\t *\/\n\n\tThreadCommon(StackStorageUniquePointer&& stackStorageUniquePointer, size_t size, uint8_t priority,\n\t\t\tSchedulingPolicy schedulingPolicy, scheduler::ThreadGroupControlBlock* threadGroupControlBlock,\n\t\t\tSignalsReceiver* signalsReceiver);\n\n\t\/**\n\t * \\brief ThreadCommon's constructor\n\t *\n\t * \\param [in] stack is an rvalue reference to architecture::Stack object which will be adopted for this thread\n\t * \\param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest\n\t * \\param [in] schedulingPolicy is the scheduling policy of the thread\n\t * \\param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will\n\t * be added, nullptr to inherit thread group from currently running thread\n\t * \\param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception\n\t * of signals for this thread\n\t *\/\n\n\tThreadCommon(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy,\n\t\t\tscheduler::ThreadGroupControlBlock* threadGroupControlBlock, SignalsReceiver* signalsReceiver);\n\n\t\/**\n\t * \\brief Generates signal for thread.\n\t *\n\t * Similar to pthread_kill() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/pthread_kill.html\n\t *\n\t * Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be\n\t * unblocked.\n\t *\n\t * \\param [in] signalNumber is the signal that will be generated, [0; 31]\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EINVAL - \\a signalNumber value is invalid;\n\t * - ENOTSUP - reception of signals is disabled for this thread;\n\t *\/\n\n\tvirtual int generateSignal(uint8_t signalNumber) override;\n\n\t\/**\n\t * \\return effective priority of thread\n\t *\/\n\n\tvirtual uint8_t getEffectivePriority() const override;\n\n\t\/**\n\t * \\brief Gets set of currently pending signals.\n\t *\n\t * Similar to sigpending() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/sigpending.html\n\t *\n\t * This function shall return the set of signals that are blocked from delivery and are pending on the thread.\n\t *\n\t * \\return set of currently pending signals\n\t *\/\n\n\tvirtual SignalSet getPendingSignalSet() const override;\n\n\t\/**\n\t * \\return priority of thread\n\t *\/\n\n\tvirtual uint8_t getPriority() const override;\n\n\t\/**\n\t * \\return scheduling policy of the thread\n\t *\/\n\n\tvirtual SchedulingPolicy getSchedulingPolicy() const override;\n\n\t\/**\n\t * \\return current state of thread\n\t *\/\n\n\tvirtual scheduler::ThreadControlBlock::State getState() const override;\n\n\t\/**\n\t * \\brief Waits for thread termination.\n\t *\n\t * Similar to std::thread::join() - http:\/\/en.cppreference.com\/w\/cpp\/thread\/thread\/join\n\t * Similar to POSIX pthread_join() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/pthread_join.html\n\t *\n\t * Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to\n\t * join() on the same target thread are undefined.\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EDEADLK - deadlock condition was detected,\n\t * - EINVAL - this thread is not joinable,\n\t * - ...\n\t *\/\n\n\tvirtual int join() override;\n\n\t\/**\n\t * \\brief Queues signal for thread.\n\t *\n\t * Similar to sigqueue() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/sigqueue.html\n\t *\n\t * Adds the signalNumber and signal value (sigval union) to queue of SignalInformation objects. If this thread is\n\t * currently waiting for this signal, it will be unblocked.\n\t *\n\t * \\param [in] signalNumber is the signal that will be queued, [0; 31]\n\t * \\param [in] value is the signal value\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in\n\t * associated queue of SignalInformation objects;\n\t * - EINVAL - \\a signalNumber value is invalid;\n\t * - ENOTSUP - reception or queuing of signals are disabled for this thread;\n\t *\/\n\n\tvirtual int queueSignal(uint8_t signalNumber, sigval value) override;\n\n\t\/**\n\t * \\brief Changes priority of thread.\n\t *\n\t * If the priority really changes, the position in the thread list is adjusted and context switch may be requested.\n\t *\n\t * \\param [in] priority is the new priority of thread\n\t * \\param [in] alwaysBehind selects the method of ordering when lowering the priority\n\t * - false - the thread is moved to the head of the group of threads with the new priority (default),\n\t * - true - the thread is moved to the tail of the group of threads with the new priority.\n\t *\/\n\n\tvirtual void setPriority(uint8_t priority, bool alwaysBehind = {}) override;\n\n\t\/**\n\t * param [in] schedulingPolicy is the new scheduling policy of the thread\n\t *\/\n\n\tvirtual void setSchedulingPolicy(SchedulingPolicy schedulingPolicy) override;\n\n\t\/**\n\t * \\brief Starts the thread.\n\t *\n\t * This operation can be performed on threads in \"New\" state only.\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EINVAL - thread is already started;\n\t * - error codes returned by scheduler::Scheduler::add();\n\t *\/\n\n\tvirtual int start() override;\n\nprotected:\n\n\t\/**\n\t * \\return reference to internal ThreadControlBlock object\n\t *\/\n\n\tscheduler::ThreadControlBlock& getThreadControlBlock();\n\n\t\/**\n\t * \\return const reference to internal ThreadControlBlock object\n\t *\/\n\n\tconst scheduler::ThreadControlBlock& getThreadControlBlock() const;\n\nprivate:\n\n\t\/**\n\t * \\brief Termination hook function of thread\n\t *\n\t * This function is called after run() completes, from Scheduler::remove().\n\t *\/\n\n\tvirtual void terminationHook() override;\n\n\t\/\/\/ internal ThreadControlBlock object\n\tscheduler::ThreadControlBlock threadControlBlock_;\n\n\t\/\/\/ semaphore used by join()\n\tSemaphore joinSemaphore_;\n};\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_THREADCOMMON_HPP_\n<commit_msg>ThreadCommon: explicitly make the class move-constructible<commit_after>\/**\n * \\file\n * \\brief ThreadCommon class header\n *\n * \\author Copyright (C) 2015 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2015-11-13\n *\/\n\n#ifndef INCLUDE_DISTORTOS_THREADCOMMON_HPP_\n#define INCLUDE_DISTORTOS_THREADCOMMON_HPP_\n\n#include \"distortos\/Semaphore.hpp\"\n#include \"distortos\/Thread.hpp\"\n\nnamespace distortos\n{\n\n\/\/\/ ThreadCommon class implements common functionality of threads\nclass ThreadCommon : public Thread\n{\npublic:\n\n\t\/\/\/ unique_ptr (with deleter) to storage for stack\n\tusing StackStorageUniquePointer = architecture::Stack::StorageUniquePointer;\n\n\t\/**\n\t * \\brief ThreadCommon's constructor\n\t *\n\t * \\param [in] stackStorageUniquePointer is a rvalue reference to StackStorageUniquePointer with storage for stack\n\t * (\\a size bytes long) and appropriate deleter\n\t * \\param [in] size is the size of stack's storage, bytes\n\t * \\param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest\n\t * \\param [in] schedulingPolicy is the scheduling policy of the thread\n\t * \\param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will\n\t * be added, nullptr to inherit thread group from currently running thread\n\t * \\param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception\n\t * of signals for this thread\n\t *\/\n\n\tThreadCommon(StackStorageUniquePointer&& stackStorageUniquePointer, size_t size, uint8_t priority,\n\t\t\tSchedulingPolicy schedulingPolicy, scheduler::ThreadGroupControlBlock* threadGroupControlBlock,\n\t\t\tSignalsReceiver* signalsReceiver);\n\n\t\/**\n\t * \\brief ThreadCommon's constructor\n\t *\n\t * \\param [in] stack is an rvalue reference to architecture::Stack object which will be adopted for this thread\n\t * \\param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest\n\t * \\param [in] schedulingPolicy is the scheduling policy of the thread\n\t * \\param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will\n\t * be added, nullptr to inherit thread group from currently running thread\n\t * \\param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception\n\t * of signals for this thread\n\t *\/\n\n\tThreadCommon(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy,\n\t\t\tscheduler::ThreadGroupControlBlock* threadGroupControlBlock, SignalsReceiver* signalsReceiver);\n\n\t\/**\n\t * \\brief Generates signal for thread.\n\t *\n\t * Similar to pthread_kill() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/pthread_kill.html\n\t *\n\t * Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be\n\t * unblocked.\n\t *\n\t * \\param [in] signalNumber is the signal that will be generated, [0; 31]\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EINVAL - \\a signalNumber value is invalid;\n\t * - ENOTSUP - reception of signals is disabled for this thread;\n\t *\/\n\n\tvirtual int generateSignal(uint8_t signalNumber) override;\n\n\t\/**\n\t * \\return effective priority of thread\n\t *\/\n\n\tvirtual uint8_t getEffectivePriority() const override;\n\n\t\/**\n\t * \\brief Gets set of currently pending signals.\n\t *\n\t * Similar to sigpending() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/sigpending.html\n\t *\n\t * This function shall return the set of signals that are blocked from delivery and are pending on the thread.\n\t *\n\t * \\return set of currently pending signals\n\t *\/\n\n\tvirtual SignalSet getPendingSignalSet() const override;\n\n\t\/**\n\t * \\return priority of thread\n\t *\/\n\n\tvirtual uint8_t getPriority() const override;\n\n\t\/**\n\t * \\return scheduling policy of the thread\n\t *\/\n\n\tvirtual SchedulingPolicy getSchedulingPolicy() const override;\n\n\t\/**\n\t * \\return current state of thread\n\t *\/\n\n\tvirtual scheduler::ThreadControlBlock::State getState() const override;\n\n\t\/**\n\t * \\brief Waits for thread termination.\n\t *\n\t * Similar to std::thread::join() - http:\/\/en.cppreference.com\/w\/cpp\/thread\/thread\/join\n\t * Similar to POSIX pthread_join() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/pthread_join.html\n\t *\n\t * Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to\n\t * join() on the same target thread are undefined.\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EDEADLK - deadlock condition was detected,\n\t * - EINVAL - this thread is not joinable,\n\t * - ...\n\t *\/\n\n\tvirtual int join() override;\n\n\t\/**\n\t * \\brief Queues signal for thread.\n\t *\n\t * Similar to sigqueue() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/sigqueue.html\n\t *\n\t * Adds the signalNumber and signal value (sigval union) to queue of SignalInformation objects. If this thread is\n\t * currently waiting for this signal, it will be unblocked.\n\t *\n\t * \\param [in] signalNumber is the signal that will be queued, [0; 31]\n\t * \\param [in] value is the signal value\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in\n\t * associated queue of SignalInformation objects;\n\t * - EINVAL - \\a signalNumber value is invalid;\n\t * - ENOTSUP - reception or queuing of signals are disabled for this thread;\n\t *\/\n\n\tvirtual int queueSignal(uint8_t signalNumber, sigval value) override;\n\n\t\/**\n\t * \\brief Changes priority of thread.\n\t *\n\t * If the priority really changes, the position in the thread list is adjusted and context switch may be requested.\n\t *\n\t * \\param [in] priority is the new priority of thread\n\t * \\param [in] alwaysBehind selects the method of ordering when lowering the priority\n\t * - false - the thread is moved to the head of the group of threads with the new priority (default),\n\t * - true - the thread is moved to the tail of the group of threads with the new priority.\n\t *\/\n\n\tvirtual void setPriority(uint8_t priority, bool alwaysBehind = {}) override;\n\n\t\/**\n\t * param [in] schedulingPolicy is the new scheduling policy of the thread\n\t *\/\n\n\tvirtual void setSchedulingPolicy(SchedulingPolicy schedulingPolicy) override;\n\n\t\/**\n\t * \\brief Starts the thread.\n\t *\n\t * This operation can be performed on threads in \"New\" state only.\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EINVAL - thread is already started;\n\t * - error codes returned by scheduler::Scheduler::add();\n\t *\/\n\n\tvirtual int start() override;\n\n\tThreadCommon(const ThreadCommon&) = delete;\n\tThreadCommon(ThreadCommon&&) = default;\n\tconst ThreadCommon& operator=(const ThreadCommon&) = delete;\n\tThreadCommon& operator=(ThreadCommon&&) = delete;\n\nprotected:\n\n\t\/**\n\t * \\return reference to internal ThreadControlBlock object\n\t *\/\n\n\tscheduler::ThreadControlBlock& getThreadControlBlock();\n\n\t\/**\n\t * \\return const reference to internal ThreadControlBlock object\n\t *\/\n\n\tconst scheduler::ThreadControlBlock& getThreadControlBlock() const;\n\nprivate:\n\n\t\/**\n\t * \\brief Termination hook function of thread\n\t *\n\t * This function is called after run() completes, from Scheduler::remove().\n\t *\/\n\n\tvirtual void terminationHook() override;\n\n\t\/\/\/ internal ThreadControlBlock object\n\tscheduler::ThreadControlBlock threadControlBlock_;\n\n\t\/\/\/ semaphore used by join()\n\tSemaphore joinSemaphore_;\n};\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_THREADCOMMON_HPP_\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITKGLCMIMAGECALCULATOR_HXX\n#define ITKGLCMCIMAGEALCULATOR_HXX\n\n#include \"itkGLCMImageCalculator.h\"\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n#include \"itkNumericTraits.h\"\n\nnamespace itk\n{\nnamespace Statistics\n{\n\ntemplate< typename TInputImage, typename TGLCMType >\nGLCMImageCalculator< TInputImage, TGLCMType >\n::GLCMImageCalculator():\n m_Image(TInputImage::New()),\n m_RegionSetByUser(false),\n m_CooccurrenceMatrix(GLCMType::New())\n{}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::Compute(void)\n{\n if(m_MatrixSize != m_CooccurrenceMatrix->GetSize())\n {\n this->m_CooccurrenceMatrix->SetSize(m_MatrixSize);\n }\n\n if ( !m_RegionSetByUser )\n {\n m_Region = m_Image->GetRequestedRegion();\n }\n\n if(!m_Image->GetBufferedRegion().IsInside(m_Region))\n {\n itkExceptionMacro( << \"The requested region is outside of the buffered region\" );\n }\n\n itkDebugMacro( << \"Processing region: \" << m_Region );\n\n itk::ImageRegionConstIteratorWithIndex< ImageType > iterator(m_Image, m_Region);\n PixelType centerPixelIntensity, offsetPixelIntensity;\n typename ImageType::IndexType centerPixelIndex, offsetPixelIndex;\n typename OffsetVectorType::ConstIterator off_it, off_it_begin = m_Offsets->Begin(), off_it_end = m_Offsets->End();\n\n iterator.GoToBegin();\n while(!iterator.IsAtEnd())\n {\n centerPixelIndex = iterator.GetIndex();\n\n itkDebugMacro( << \"Processing pixel at \" << centerPixelIndex );\n\n centerPixelIntensity = m_Image->GetPixel(centerPixelIndex);\n \/\/ don't put a pixel in the histogram if the value is out of bound\n if ( centerPixelIntensity >= 0 && centerPixelIntensity < m_MatrixSize )\n {\n for ( off_it = off_it_begin; off_it != off_it_end; ++off_it )\n {\n offsetPixelIndex = centerPixelIndex + off_it.Value();\n\n itkDebugMacro( << \"\\tProcessing pixel at \" << offsetPixelIndex );\n\n if(m_Region.IsInside(offsetPixelIndex))\n {\n offsetPixelIntensity = m_Image->GetPixel(offsetPixelIndex);\n\n \/\/ don't put a pixel in the histogram if the value is out-of-bounds.\n if ( offsetPixelIntensity >= 0 && offsetPixelIntensity < m_MatrixSize )\n {\n m_CooccurrenceMatrix->IncrementCounter(centerPixelIntensity, offsetPixelIntensity);\n m_CooccurrenceMatrix->IncrementCounter(offsetPixelIntensity, centerPixelIntensity);\n }\n else \n {\n itkExceptionMacro( << \"Value (\" << offsetPixelIntensity << \") out of bound [0; \" << m_MatrixSize << \"[\" );\n }\n }\n }\n }\n else \n {\n itkExceptionMacro( << \"Value (\" << centerPixelIntensity << \") out of bound [0; \" << m_MatrixSize << \"[\" );\n }\n\n ++iterator;\n }\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::SetRegion(const RegionType & region)\n{\n m_Region = region;\n m_RegionSetByUser = true;\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::ResetMatrix()\n{\n m_CooccurrenceMatrix->SetToZero();\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::SetOffsets(const OffsetVectorType * os)\n{\n itkDebugMacro(\"setting offsets to \" << os);\n this->m_Offsets = os;\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::SetOffset(const OffsetType offset)\n{\n OffsetVectorPointer offsetVector = OffsetVectorType::New();\n\n offsetVector->push_back(offset);\n this->SetOffsets(offsetVector);\n\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n\n os << indent << \"Image: \" << std::endl;\n m_Image->Print( os, indent.GetNextIndent() );\n os << indent << \"Region: \" << std::endl;\n m_Region.Print( os, indent.GetNextIndent() );\n os << indent << \"Region set by User: \" << m_RegionSetByUser << std::endl;\n}\n\n} \/\/ end namespace Statistics\n} \/\/ end namespace itk\n\n#endif \/* ITKGLCMIMAGECALCULATOR_HXX *\/\n<commit_msg>Ajoute un appel manquant à modified() dans le calculateur de matrice de cooccurrence.<commit_after>#ifndef ITKGLCMIMAGECALCULATOR_HXX\n#define ITKGLCMCIMAGEALCULATOR_HXX\n\n#include \"itkGLCMImageCalculator.h\"\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n#include \"itkNumericTraits.h\"\n\nnamespace itk\n{\nnamespace Statistics\n{\n\ntemplate< typename TInputImage, typename TGLCMType >\nGLCMImageCalculator< TInputImage, TGLCMType >\n::GLCMImageCalculator():\n m_Image(TInputImage::New()),\n m_RegionSetByUser(false),\n m_CooccurrenceMatrix(GLCMType::New())\n{}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::Compute(void)\n{\n if(m_MatrixSize != m_CooccurrenceMatrix->GetSize())\n {\n this->m_CooccurrenceMatrix->SetSize(m_MatrixSize);\n }\n\n if ( !m_RegionSetByUser )\n {\n m_Region = m_Image->GetRequestedRegion();\n }\n\n if(!m_Image->GetBufferedRegion().IsInside(m_Region))\n {\n itkExceptionMacro( << \"The requested region is outside of the buffered region\" );\n }\n\n itkDebugMacro( << \"Processing region: \" << m_Region );\n\n itk::ImageRegionConstIteratorWithIndex< ImageType > iterator(m_Image, m_Region);\n PixelType centerPixelIntensity, offsetPixelIntensity;\n typename ImageType::IndexType centerPixelIndex, offsetPixelIndex;\n typename OffsetVectorType::ConstIterator off_it, off_it_begin = m_Offsets->Begin(), off_it_end = m_Offsets->End();\n\n iterator.GoToBegin();\n while(!iterator.IsAtEnd())\n {\n centerPixelIndex = iterator.GetIndex();\n\n itkDebugMacro( << \"Processing pixel at \" << centerPixelIndex );\n\n centerPixelIntensity = m_Image->GetPixel(centerPixelIndex);\n \/\/ don't put a pixel in the histogram if the value is out of bound\n if ( centerPixelIntensity >= 0 && centerPixelIntensity < m_MatrixSize )\n {\n for ( off_it = off_it_begin; off_it != off_it_end; ++off_it )\n {\n offsetPixelIndex = centerPixelIndex + off_it.Value();\n\n itkDebugMacro( << \"\\tProcessing pixel at \" << offsetPixelIndex );\n\n if(m_Region.IsInside(offsetPixelIndex))\n {\n offsetPixelIntensity = m_Image->GetPixel(offsetPixelIndex);\n\n \/\/ don't put a pixel in the histogram if the value is out-of-bounds.\n if ( offsetPixelIntensity >= 0 && offsetPixelIntensity < m_MatrixSize )\n {\n m_CooccurrenceMatrix->IncrementCounter(centerPixelIntensity, offsetPixelIntensity);\n m_CooccurrenceMatrix->IncrementCounter(offsetPixelIntensity, centerPixelIntensity);\n }\n else \n {\n itkExceptionMacro( << \"Value (\" << offsetPixelIntensity << \") out of bound [0; \" << m_MatrixSize << \"[\" );\n }\n }\n }\n }\n else \n {\n itkExceptionMacro( << \"Value (\" << centerPixelIntensity << \") out of bound [0; \" << m_MatrixSize << \"[\" );\n }\n\n ++iterator;\n }\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::SetRegion(const RegionType & region)\n{\n m_Region = region;\n m_RegionSetByUser = true;\n\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::ResetMatrix()\n{\n m_CooccurrenceMatrix->SetToZero();\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::SetOffsets(const OffsetVectorType * os)\n{\n itkDebugMacro(\"setting offsets to \" << os);\n this->m_Offsets = os;\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::SetOffset(const OffsetType offset)\n{\n OffsetVectorPointer offsetVector = OffsetVectorType::New();\n\n offsetVector->push_back(offset);\n this->SetOffsets(offsetVector);\n\n this->Modified();\n}\n\ntemplate< typename TInputImage, typename TGLCMType >\nvoid\nGLCMImageCalculator< TInputImage, TGLCMType >\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n\n os << indent << \"Image: \" << std::endl;\n m_Image->Print( os, indent.GetNextIndent() );\n os << indent << \"Region: \" << std::endl;\n m_Region.Print( os, indent.GetNextIndent() );\n os << indent << \"Region set by User: \" << m_RegionSetByUser << std::endl;\n}\n\n} \/\/ end namespace Statistics\n} \/\/ end namespace itk\n\n#endif \/* ITKGLCMIMAGECALCULATOR_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2021 The Cross-Media Measurement Authors\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 \"wfa\/virtual_people\/core\/model\/utils\/distributed_consistent_hashing.h\"\n\n#include \"absl\/container\/flat_hash_map.h\"\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/status\/statusor.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"src\/test\/cc\/testutil\/matchers.h\"\n#include \"src\/test\/cc\/testutil\/status_macros.h\"\n\nnamespace wfa_virtual_people {\nnamespace {\n\nusing ::testing::DoubleNear;\nusing ::testing::Pair;\nusing ::testing::UnorderedElementsAre;\nusing ::wfa::StatusIs;\n\nconstexpr int kSeedNumber = 10000;\n\nTEST(DistributedConsistentHashingTest, TestEmptyDistribution) {\n std::vector<DistributionChoice> distribution;\n EXPECT_THAT(\n DistributedConsistentHashing::Build(std::move(distribution)).status(),\n StatusIs(absl::StatusCode::kInvalidArgument, \"\"));\n}\n\nTEST(DistributedConsistentHashingTest, TestZeroProbabilitiesSum) {\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0}),\n DistributionChoice({1, 0})\n });\n EXPECT_THAT(\n DistributedConsistentHashing::Build(std::move(distribution)).status(),\n StatusIs(absl::StatusCode::kInvalidArgument, \"\"));\n}\n\nTEST(DistributedConsistentHashingTest, TestNegativeProbability) {\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, -1})\n });\n EXPECT_THAT(\n DistributedConsistentHashing::Build(std::move(distribution)).status(),\n StatusIs(absl::StatusCode::kInvalidArgument, \"\"));\n}\n\nTEST(DistributedConsistentHashingTest, TestOutputDistribution) {\n \/\/ Distribution:\n \/\/ choice_id probability\n \/\/ 0 0.4\n \/\/ 1 0.2\n \/\/ 2 0.2\n \/\/ 3 0.2\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0.4}),\n DistributionChoice({1, 0.2}),\n DistributionChoice({2, 0.2}),\n DistributionChoice({3, 0.2})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n absl::flat_hash_map<int32_t, double> output_counts;\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n int32_t output = hashing->Hash(std::to_string(seed));\n if (output_counts.find(output) == output_counts.end()) {\n output_counts[output] = 0;\n }\n ++output_counts[output];\n }\n for (auto& [key, value] : output_counts) {\n value \/= static_cast<double>(kSeedNumber);\n }\n \/\/ Absolute error more than 2% is very unlikely.\n EXPECT_THAT(output_counts, UnorderedElementsAre(\n Pair(0, DoubleNear(0.4, 0.02)),\n Pair(1, DoubleNear(0.2, 0.02)),\n Pair(2, DoubleNear(0.2, 0.02)),\n Pair(3, DoubleNear(0.2, 0.02))));\n}\n\nTEST(DistributedConsistentHashingTest, TestNormalize) {\n \/\/ Distribution:\n \/\/ choice_id probability_before_normalized normalized_probability\n \/\/ 0 0.8 0.4\n \/\/ 1 0.4 0.2\n \/\/ 2 0.4 0.2\n \/\/ 3 0.4 0.2\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0.8}),\n DistributionChoice({1, 0.4}),\n DistributionChoice({2, 0.4}),\n DistributionChoice({3, 0.4})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n absl::flat_hash_map<int32_t, double> output_counts;\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n int32_t output = hashing->Hash(std::to_string(seed));\n if (output_counts.find(output) == output_counts.end()) {\n output_counts[output] = 0;\n }\n ++output_counts[output];\n }\n for (auto& [key, value] : output_counts) {\n value \/= static_cast<double>(kSeedNumber);\n }\n \/\/ Absolute error more than 2% is very unlikely.\n EXPECT_THAT(output_counts, UnorderedElementsAre(\n Pair(0, DoubleNear(0.4, 0.02)),\n Pair(1, DoubleNear(0.2, 0.02)),\n Pair(2, DoubleNear(0.2, 0.02)),\n Pair(3, DoubleNear(0.2, 0.02))));\n}\n\nTEST(DistributedConsistentHashingTest, TestZeroProbability) {\n \/\/ Distribution:\n \/\/ choice_id probability\n \/\/ 0 0\n \/\/ 1 1\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0}),\n DistributionChoice({1, 1})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n EXPECT_EQ(hashing->Hash(std::to_string(seed)), 1);\n }\n}\n\nTEST(DistributedConsistentHashingTest, TestZeroAfterNormalization) {\n \/\/ Distribution:\n \/\/ choice_id probability_before_normalized normalized_probability\n \/\/ 0 std::numeric_limits<double>::min() 0\n \/\/ 1 std::numeric_limits<double>::max() 1\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, std::numeric_limits<double>::min()}),\n DistributionChoice({1, std::numeric_limits<double>::max()})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n EXPECT_EQ(hashing->Hash(std::to_string(seed)), 1);\n }\n}\n\nTEST(DistributedConsistentHashingTest,\n TestOutputDistribution_NonConsecutiveChoiceId) {\n \/\/ Distribution:\n \/\/ choice_id probability\n \/\/ 0 0.4\n \/\/ 2 0.2\n \/\/ 4 0.2\n \/\/ 6 0.2\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0.4}),\n DistributionChoice({2, 0.2}),\n DistributionChoice({4, 0.2}),\n DistributionChoice({6, 0.2})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n absl::flat_hash_map<int32_t, double> output_counts;\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n int32_t output = hashing->Hash(std::to_string(seed));\n if (output_counts.find(output) == output_counts.end()) {\n output_counts[output] = 0;\n }\n ++output_counts[output];\n }\n for (auto& [key, value] : output_counts) {\n value \/= static_cast<double>(kSeedNumber);\n }\n \/\/ Absolute error more than 2% is very unlikely.\n EXPECT_THAT(output_counts, UnorderedElementsAre(\n Pair(0, DoubleNear(0.4, 0.02)),\n Pair(2, DoubleNear(0.2, 0.02)),\n Pair(4, DoubleNear(0.2, 0.02)),\n Pair(6, DoubleNear(0.2, 0.02))));\n}\n\nTEST(DistributedConsistentHashingTest, TestOutputChangeCount) {\n \/\/ Distributions:\n \/\/ choice_id probability_1 probability_2\n \/\/ 0 0.4 0.2\n \/\/ 1 0.2 0.2\n \/\/ 2 0.2 0.2\n \/\/ 3 0.2 0.4\n std::vector<DistributionChoice> distribution_1({\n DistributionChoice({0, 0.4}),\n DistributionChoice({1, 0.2}),\n DistributionChoice({2, 0.2}),\n DistributionChoice({3, 0.2})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing_1,\n DistributedConsistentHashing::Build(std::move(distribution_1)));\n std::vector<DistributionChoice> distribution_2({\n DistributionChoice({0, 0.2}),\n DistributionChoice({1, 0.2}),\n DistributionChoice({2, 0.2}),\n DistributionChoice({3, 0.4})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing_2,\n DistributedConsistentHashing::Build(std::move(distribution_2)));\n\n int diff_output_count = 0;\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n int32_t output_1 = hashing_1->Hash(std::to_string(seed));\n int32_t output_2 = hashing_2->Hash(std::to_string(seed));\n if (output_1 != output_2) {\n ++diff_output_count;\n }\n }\n \/\/ The number of outputs different between 2 hashings is guaranteed to be less\n \/\/ than L1 distance of the 2 distributions, which is 40% of total counts here.\n EXPECT_LE(diff_output_count, kSeedNumber * 0.4);\n}\n\n} \/\/ namespace\n} \/\/ namespace wfa_virtual_people\n<commit_msg>Remove underscore in tests name.<commit_after>\/\/ Copyright 2021 The Cross-Media Measurement Authors\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 \"wfa\/virtual_people\/core\/model\/utils\/distributed_consistent_hashing.h\"\n\n#include \"absl\/container\/flat_hash_map.h\"\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/status\/statusor.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"src\/test\/cc\/testutil\/matchers.h\"\n#include \"src\/test\/cc\/testutil\/status_macros.h\"\n\nnamespace wfa_virtual_people {\nnamespace {\n\nusing ::testing::DoubleNear;\nusing ::testing::Pair;\nusing ::testing::UnorderedElementsAre;\nusing ::wfa::StatusIs;\n\nconstexpr int kSeedNumber = 10000;\n\nTEST(DistributedConsistentHashingTest, TestEmptyDistribution) {\n std::vector<DistributionChoice> distribution;\n EXPECT_THAT(\n DistributedConsistentHashing::Build(std::move(distribution)).status(),\n StatusIs(absl::StatusCode::kInvalidArgument, \"\"));\n}\n\nTEST(DistributedConsistentHashingTest, TestZeroProbabilitiesSum) {\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0}),\n DistributionChoice({1, 0})\n });\n EXPECT_THAT(\n DistributedConsistentHashing::Build(std::move(distribution)).status(),\n StatusIs(absl::StatusCode::kInvalidArgument, \"\"));\n}\n\nTEST(DistributedConsistentHashingTest, TestNegativeProbability) {\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, -1})\n });\n EXPECT_THAT(\n DistributedConsistentHashing::Build(std::move(distribution)).status(),\n StatusIs(absl::StatusCode::kInvalidArgument, \"\"));\n}\n\nTEST(DistributedConsistentHashingTest, TestOutputDistribution) {\n \/\/ Distribution:\n \/\/ choice_id probability\n \/\/ 0 0.4\n \/\/ 1 0.2\n \/\/ 2 0.2\n \/\/ 3 0.2\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0.4}),\n DistributionChoice({1, 0.2}),\n DistributionChoice({2, 0.2}),\n DistributionChoice({3, 0.2})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n absl::flat_hash_map<int32_t, double> output_counts;\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n int32_t output = hashing->Hash(std::to_string(seed));\n if (output_counts.find(output) == output_counts.end()) {\n output_counts[output] = 0;\n }\n ++output_counts[output];\n }\n for (auto& [key, value] : output_counts) {\n value \/= static_cast<double>(kSeedNumber);\n }\n \/\/ Absolute error more than 2% is very unlikely.\n EXPECT_THAT(output_counts, UnorderedElementsAre(\n Pair(0, DoubleNear(0.4, 0.02)),\n Pair(1, DoubleNear(0.2, 0.02)),\n Pair(2, DoubleNear(0.2, 0.02)),\n Pair(3, DoubleNear(0.2, 0.02))));\n}\n\nTEST(DistributedConsistentHashingTest, TestNormalize) {\n \/\/ Distribution:\n \/\/ choice_id probability_before_normalized normalized_probability\n \/\/ 0 0.8 0.4\n \/\/ 1 0.4 0.2\n \/\/ 2 0.4 0.2\n \/\/ 3 0.4 0.2\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0.8}),\n DistributionChoice({1, 0.4}),\n DistributionChoice({2, 0.4}),\n DistributionChoice({3, 0.4})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n absl::flat_hash_map<int32_t, double> output_counts;\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n int32_t output = hashing->Hash(std::to_string(seed));\n if (output_counts.find(output) == output_counts.end()) {\n output_counts[output] = 0;\n }\n ++output_counts[output];\n }\n for (auto& [key, value] : output_counts) {\n value \/= static_cast<double>(kSeedNumber);\n }\n \/\/ Absolute error more than 2% is very unlikely.\n EXPECT_THAT(output_counts, UnorderedElementsAre(\n Pair(0, DoubleNear(0.4, 0.02)),\n Pair(1, DoubleNear(0.2, 0.02)),\n Pair(2, DoubleNear(0.2, 0.02)),\n Pair(3, DoubleNear(0.2, 0.02))));\n}\n\nTEST(DistributedConsistentHashingTest, TestZeroProbability) {\n \/\/ Distribution:\n \/\/ choice_id probability\n \/\/ 0 0\n \/\/ 1 1\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0}),\n DistributionChoice({1, 1})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n EXPECT_EQ(hashing->Hash(std::to_string(seed)), 1);\n }\n}\n\nTEST(DistributedConsistentHashingTest, TestZeroAfterNormalization) {\n \/\/ Distribution:\n \/\/ choice_id probability_before_normalized normalized_probability\n \/\/ 0 std::numeric_limits<double>::min() 0\n \/\/ 1 std::numeric_limits<double>::max() 1\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, std::numeric_limits<double>::min()}),\n DistributionChoice({1, std::numeric_limits<double>::max()})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n EXPECT_EQ(hashing->Hash(std::to_string(seed)), 1);\n }\n}\n\nTEST(DistributedConsistentHashingTest,\n TestOutputDistributionNonConsecutiveChoiceId) {\n \/\/ Distribution:\n \/\/ choice_id probability\n \/\/ 0 0.4\n \/\/ 2 0.2\n \/\/ 4 0.2\n \/\/ 6 0.2\n std::vector<DistributionChoice> distribution({\n DistributionChoice({0, 0.4}),\n DistributionChoice({2, 0.2}),\n DistributionChoice({4, 0.2}),\n DistributionChoice({6, 0.2})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing,\n DistributedConsistentHashing::Build(std::move(distribution)));\n absl::flat_hash_map<int32_t, double> output_counts;\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n int32_t output = hashing->Hash(std::to_string(seed));\n if (output_counts.find(output) == output_counts.end()) {\n output_counts[output] = 0;\n }\n ++output_counts[output];\n }\n for (auto& [key, value] : output_counts) {\n value \/= static_cast<double>(kSeedNumber);\n }\n \/\/ Absolute error more than 2% is very unlikely.\n EXPECT_THAT(output_counts, UnorderedElementsAre(\n Pair(0, DoubleNear(0.4, 0.02)),\n Pair(2, DoubleNear(0.2, 0.02)),\n Pair(4, DoubleNear(0.2, 0.02)),\n Pair(6, DoubleNear(0.2, 0.02))));\n}\n\nTEST(DistributedConsistentHashingTest, TestOutputChangeCount) {\n \/\/ Distributions:\n \/\/ choice_id probability_1 probability_2\n \/\/ 0 0.4 0.2\n \/\/ 1 0.2 0.2\n \/\/ 2 0.2 0.2\n \/\/ 3 0.2 0.4\n std::vector<DistributionChoice> distribution_1({\n DistributionChoice({0, 0.4}),\n DistributionChoice({1, 0.2}),\n DistributionChoice({2, 0.2}),\n DistributionChoice({3, 0.2})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing_1,\n DistributedConsistentHashing::Build(std::move(distribution_1)));\n std::vector<DistributionChoice> distribution_2({\n DistributionChoice({0, 0.2}),\n DistributionChoice({1, 0.2}),\n DistributionChoice({2, 0.2}),\n DistributionChoice({3, 0.4})\n });\n ASSERT_OK_AND_ASSIGN(\n std::unique_ptr<DistributedConsistentHashing> hashing_2,\n DistributedConsistentHashing::Build(std::move(distribution_2)));\n\n int diff_output_count = 0;\n for (int seed = 0; seed < kSeedNumber; ++seed) {\n int32_t output_1 = hashing_1->Hash(std::to_string(seed));\n int32_t output_2 = hashing_2->Hash(std::to_string(seed));\n if (output_1 != output_2) {\n ++diff_output_count;\n }\n }\n \/\/ The number of outputs different between 2 hashings is guaranteed to be less\n \/\/ than L1 distance of the 2 distributions, which is 40% of total counts here.\n EXPECT_LE(diff_output_count, kSeedNumber * 0.4);\n}\n\n} \/\/ namespace\n} \/\/ namespace wfa_virtual_people\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <agency\/detail\/tuple.hpp>\n#include <utility>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class T, class... Args>\nclass factory\n{\n public:\n __AGENCY_ANNOTATION\n factory() : args_() {}\n\n __AGENCY_ANNOTATION\n factory(const tuple<Args...>& args)\n : args_(args)\n {}\n\n \/\/ XXX eliminate me!\n __AGENCY_ANNOTATION\n T make() const &\n {\n return __tu::make_from_tuple<T>(args_);\n }\n\n \/\/ XXX eliminate me!\n __AGENCY_ANNOTATION\n T make() &&\n {\n return __tu::make_from_tuple<T>(std::move(args_));\n }\n\n __AGENCY_ANNOTATION\n T operator()() const &\n {\n return make();\n }\n\n __AGENCY_ANNOTATION\n T operator()() &&\n {\n return std::move(*this).make();\n }\n\n private:\n tuple<Args...> args_;\n};\n\n\ntemplate<class T>\n__AGENCY_ANNOTATION\nfactory<T,T> make_factory(const T& arg)\n{\n return factory<T,T>{detail::make_tuple(arg)};\n}\n\n\nstruct unit {};\n\n\nstruct unit_factory : factory<unit> {};\n\n\ntemplate<class... Factories>\nstruct zip_factory\n{\n tuple<Factories...> factory_tuple_;\n\n zip_factory(const tuple<Factories...>& factories) : factory_tuple_(factories) {}\n\n\n template<size_t... Indices>\n __AGENCY_ANNOTATION\n agency::detail::tuple<\n typename std::result_of<Factories()>::type...\n >\n impl(agency::detail::index_sequence<Indices...>)\n {\n return agency::detail::make_tuple(detail::get<Indices>(factory_tuple_)()...);\n }\n\n __AGENCY_ANNOTATION\n agency::detail::tuple<\n typename std::result_of<Factories()>::type...\n >\n operator()()\n {\n return impl(index_sequence_for<Factories...>());\n }\n};\n\n\ntemplate<class... Factories>\n__AGENCY_ANNOTATION\nzip_factory<Factories...> make_zip_factory(const tuple<Factories...>& factory_tuple)\n{\n return zip_factory<Factories...>(factory_tuple);\n}\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<commit_msg>Add result_of_factory & result_of_factory_t<commit_after>#pragma once\n\n#include <agency\/detail\/tuple.hpp>\n#include <utility>\n#include <type_traits>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class Factory>\nstruct result_of_factory : std::result_of<Factory()> {};\n\n\ntemplate<class Factory>\nusing result_of_factory_t = typename result_of_factory<Factory>::type;\n\n\ntemplate<class T, class... Args>\nclass factory\n{\n public:\n __AGENCY_ANNOTATION\n factory() : args_() {}\n\n __AGENCY_ANNOTATION\n factory(const tuple<Args...>& args)\n : args_(args)\n {}\n\n \/\/ XXX eliminate me!\n __AGENCY_ANNOTATION\n T make() const &\n {\n return __tu::make_from_tuple<T>(args_);\n }\n\n \/\/ XXX eliminate me!\n __AGENCY_ANNOTATION\n T make() &&\n {\n return __tu::make_from_tuple<T>(std::move(args_));\n }\n\n __AGENCY_ANNOTATION\n T operator()() const &\n {\n return make();\n }\n\n __AGENCY_ANNOTATION\n T operator()() &&\n {\n return std::move(*this).make();\n }\n\n private:\n tuple<Args...> args_;\n};\n\n\ntemplate<class T>\n__AGENCY_ANNOTATION\nfactory<T,T> make_factory(const T& arg)\n{\n return factory<T,T>{detail::make_tuple(arg)};\n}\n\n\nstruct unit {};\n\n\nstruct unit_factory : factory<unit> {};\n\n\ntemplate<class... Factories>\nstruct zip_factory\n{\n tuple<Factories...> factory_tuple_;\n\n zip_factory(const tuple<Factories...>& factories) : factory_tuple_(factories) {}\n\n\n template<size_t... Indices>\n __AGENCY_ANNOTATION\n agency::detail::tuple<\n typename std::result_of<Factories()>::type...\n >\n impl(agency::detail::index_sequence<Indices...>)\n {\n return agency::detail::make_tuple(detail::get<Indices>(factory_tuple_)()...);\n }\n\n __AGENCY_ANNOTATION\n agency::detail::tuple<\n typename std::result_of<Factories()>::type...\n >\n operator()()\n {\n return impl(index_sequence_for<Factories...>());\n }\n};\n\n\ntemplate<class... Factories>\n__AGENCY_ANNOTATION\nzip_factory<Factories...> make_zip_factory(const tuple<Factories...>& factory_tuple)\n{\n return zip_factory<Factories...>(factory_tuple);\n}\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_TEXT_SYMBOLIZER_HPP\n#define MAPNIK_TEXT_SYMBOLIZER_HPP\n\n\/\/ mapnik\n#include <mapnik\/color.hpp>\n#include <mapnik\/font_set.hpp>\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/filter_factory.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/text_placements.hpp>\n\n\/\/ boost\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n\n\/\/ stl\n#include <string>\n\nnamespace mapnik\n{\n\nstruct MAPNIK_DECL text_symbolizer : public symbolizer_base\n{\n \/\/ Note - we do not use boost::make_shared below as VC2010 is \n\t\/\/ not able to compile make_shared used within a constructor\n\ttext_symbolizer(expression_ptr name, std::string const& face_name,\n float size, color const& fill,\n text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)\n );\n text_symbolizer(expression_ptr name, float size, color const& fill,\n text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)\n );\n text_symbolizer(text_symbolizer const& rhs);\n text_symbolizer& operator=(text_symbolizer const& rhs);\n expression_ptr get_name() const;\n void set_name(expression_ptr expr);\n\n expression_ptr get_orientation() const; \/\/ orienation (rotation angle atm)\n void set_orientation(expression_ptr expr);\n \n unsigned get_text_ratio() const; \/\/ target ratio for text bounding box in pixels\n void set_text_ratio(unsigned ratio);\n unsigned get_wrap_width() const; \/\/ width to wrap text at, or trigger ratio\n void set_wrap_width(unsigned ratio);\n unsigned char get_wrap_char() const; \/\/ character used to wrap lines\n std::string get_wrap_char_string() const; \/\/ character used to wrap lines as std::string\n void set_wrap_char(unsigned char character);\n void set_wrap_char_from_string(std::string const& character);\n text_transform_e get_text_transform() const; \/\/ text conversion on strings before display\n void set_text_transform(text_transform_e convert);\n unsigned get_line_spacing() const; \/\/ spacing between lines of text\n void set_line_spacing(unsigned spacing);\n unsigned get_character_spacing() const; \/\/ spacing between characters in text\n void set_character_spacing(unsigned spacing);\n unsigned get_label_spacing() const; \/\/ spacing between repeated labels on lines\n void set_label_spacing(unsigned spacing);\n unsigned get_label_position_tolerance() const; \/\/distance the label can be moved on the line to fit, if 0 the default is used\n void set_label_position_tolerance(unsigned tolerance);\n bool get_force_odd_labels() const; \/\/ try render an odd amount of labels\n void set_force_odd_labels(bool force);\n double get_max_char_angle_delta() const; \/\/ maximum change in angle between adjacent characters\n void set_max_char_angle_delta(double angle);\n float get_text_size() const;\n void set_text_size(float size);\n std::string const& get_face_name() const;\n void set_face_name(std::string face_name);\n font_set const& get_fontset() const;\n void set_fontset(font_set const& fset);\n color const& get_fill() const;\n void set_fill(color const& fill);\n void set_halo_fill(color const& fill);\n color const& get_halo_fill() const;\n void set_halo_radius(double radius);\n double get_halo_radius() const;\n void set_label_placement(label_placement_e label_p);\n label_placement_e get_label_placement() const;\n void set_vertical_alignment(vertical_alignment_e valign);\n vertical_alignment_e get_vertical_alignment() const;\n void set_anchor(double x, double y);\n position const& get_anchor() const;\n void set_displacement(double x, double y);\n void set_displacement(position const& p);\n position const& get_displacement() const;\n void set_avoid_edges(bool avoid);\n bool get_avoid_edges() const;\n void set_minimum_distance(double distance);\n double get_minimum_distance() const;\n void set_minimum_padding(double distance);\n double get_minimum_padding() const;\n void set_minimum_path_length(double size);\n double get_minimum_path_length() const;\n void set_allow_overlap(bool overlap);\n bool get_allow_overlap() const;\n void set_text_opacity(double opacity);\n double get_text_opacity() const;\n bool get_wrap_before() const; \/\/ wrap text at wrap_char immediately before current work\n void set_wrap_before(bool wrap_before);\n void set_horizontal_alignment(horizontal_alignment_e valign);\n horizontal_alignment_e get_horizontal_alignment() const;\n void set_justify_alignment(justify_alignment_e valign);\n justify_alignment_e get_justify_alignment() const;\n text_placements_ptr get_placement_options() const;\n void set_placement_options(text_placements_ptr placement_options);\n\nprivate:\n expression_ptr name_;\n expression_ptr orientation_;\n std::string face_name_;\n font_set fontset_;\n unsigned text_ratio_;\n unsigned wrap_width_;\n unsigned char wrap_char_;\n text_transform_e text_transform_;\n unsigned line_spacing_;\n unsigned character_spacing_;\n unsigned label_spacing_;\n unsigned label_position_tolerance_;\n bool force_odd_labels_;\n double max_char_angle_delta_;\n color fill_;\n color halo_fill_;\n double halo_radius_;\n label_placement_e label_p_;\n position anchor_;\n bool avoid_edges_;\n double minimum_distance_;\n double minimum_padding_;\n double minimum_path_length_;\n bool overlap_;\n double text_opacity_;\n bool wrap_before_;\n text_placements_ptr placement_options_;\n};\n}\n\n#endif \/\/ MAPNIK_TEXT_SYMBOLIZER_HPP\n<commit_msg>add vc++ 2008 to the list.<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_TEXT_SYMBOLIZER_HPP\n#define MAPNIK_TEXT_SYMBOLIZER_HPP\n\n\/\/ mapnik\n#include <mapnik\/color.hpp>\n#include <mapnik\/font_set.hpp>\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/filter_factory.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/text_placements.hpp>\n\n\/\/ boost\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n\n\/\/ stl\n#include <string>\n\nnamespace mapnik\n{\n\nstruct MAPNIK_DECL text_symbolizer : public symbolizer_base\n{\n \/\/ Note - we do not use boost::make_shared below as VC2008 and VC2010 are\n \/\/ not able to compile make_shared used within a constructor\n text_symbolizer(expression_ptr name, std::string const& face_name,\n float size, color const& fill,\n text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)\n );\n text_symbolizer(expression_ptr name, float size, color const& fill,\n text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)\n );\n text_symbolizer(text_symbolizer const& rhs);\n text_symbolizer& operator=(text_symbolizer const& rhs);\n expression_ptr get_name() const;\n void set_name(expression_ptr expr);\n\n expression_ptr get_orientation() const; \/\/ orienation (rotation angle atm)\n void set_orientation(expression_ptr expr);\n \n unsigned get_text_ratio() const; \/\/ target ratio for text bounding box in pixels\n void set_text_ratio(unsigned ratio);\n unsigned get_wrap_width() const; \/\/ width to wrap text at, or trigger ratio\n void set_wrap_width(unsigned ratio);\n unsigned char get_wrap_char() const; \/\/ character used to wrap lines\n std::string get_wrap_char_string() const; \/\/ character used to wrap lines as std::string\n void set_wrap_char(unsigned char character);\n void set_wrap_char_from_string(std::string const& character);\n text_transform_e get_text_transform() const; \/\/ text conversion on strings before display\n void set_text_transform(text_transform_e convert);\n unsigned get_line_spacing() const; \/\/ spacing between lines of text\n void set_line_spacing(unsigned spacing);\n unsigned get_character_spacing() const; \/\/ spacing between characters in text\n void set_character_spacing(unsigned spacing);\n unsigned get_label_spacing() const; \/\/ spacing between repeated labels on lines\n void set_label_spacing(unsigned spacing);\n unsigned get_label_position_tolerance() const; \/\/distance the label can be moved on the line to fit, if 0 the default is used\n void set_label_position_tolerance(unsigned tolerance);\n bool get_force_odd_labels() const; \/\/ try render an odd amount of labels\n void set_force_odd_labels(bool force);\n double get_max_char_angle_delta() const; \/\/ maximum change in angle between adjacent characters\n void set_max_char_angle_delta(double angle);\n float get_text_size() const;\n void set_text_size(float size);\n std::string const& get_face_name() const;\n void set_face_name(std::string face_name);\n font_set const& get_fontset() const;\n void set_fontset(font_set const& fset);\n color const& get_fill() const;\n void set_fill(color const& fill);\n void set_halo_fill(color const& fill);\n color const& get_halo_fill() const;\n void set_halo_radius(double radius);\n double get_halo_radius() const;\n void set_label_placement(label_placement_e label_p);\n label_placement_e get_label_placement() const;\n void set_vertical_alignment(vertical_alignment_e valign);\n vertical_alignment_e get_vertical_alignment() const;\n void set_anchor(double x, double y);\n position const& get_anchor() const;\n void set_displacement(double x, double y);\n void set_displacement(position const& p);\n position const& get_displacement() const;\n void set_avoid_edges(bool avoid);\n bool get_avoid_edges() const;\n void set_minimum_distance(double distance);\n double get_minimum_distance() const;\n void set_minimum_padding(double distance);\n double get_minimum_padding() const;\n void set_minimum_path_length(double size);\n double get_minimum_path_length() const;\n void set_allow_overlap(bool overlap);\n bool get_allow_overlap() const;\n void set_text_opacity(double opacity);\n double get_text_opacity() const;\n bool get_wrap_before() const; \/\/ wrap text at wrap_char immediately before current work\n void set_wrap_before(bool wrap_before);\n void set_horizontal_alignment(horizontal_alignment_e valign);\n horizontal_alignment_e get_horizontal_alignment() const;\n void set_justify_alignment(justify_alignment_e valign);\n justify_alignment_e get_justify_alignment() const;\n text_placements_ptr get_placement_options() const;\n void set_placement_options(text_placements_ptr placement_options);\n\nprivate:\n expression_ptr name_;\n expression_ptr orientation_;\n std::string face_name_;\n font_set fontset_;\n unsigned text_ratio_;\n unsigned wrap_width_;\n unsigned char wrap_char_;\n text_transform_e text_transform_;\n unsigned line_spacing_;\n unsigned character_spacing_;\n unsigned label_spacing_;\n unsigned label_position_tolerance_;\n bool force_odd_labels_;\n double max_char_angle_delta_;\n color fill_;\n color halo_fill_;\n double halo_radius_;\n label_placement_e label_p_;\n position anchor_;\n bool avoid_edges_;\n double minimum_distance_;\n double minimum_padding_;\n double minimum_path_length_;\n bool overlap_;\n double text_opacity_;\n bool wrap_before_;\n text_placements_ptr placement_options_;\n};\n}\n\n#endif \/\/ MAPNIK_TEXT_SYMBOLIZER_HPP\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#1311653 Uninitialized scalar field<commit_after><|endoftext|>"} {"text":"<commit_before>\/** \n * @file lldrawpoolsimple.cpp\n * @brief LLDrawPoolSimple class implementation\n *\n * $LicenseInfo:firstyear=2002&license=viewergpl$\n * \n * Copyright (c) 2002-2009, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"lldrawpoolsimple.h\"\n\n#include \"llviewercamera.h\"\n#include \"lldrawable.h\"\n#include \"llface.h\"\n#include \"llsky.h\"\n#include \"pipeline.h\"\n#include \"llspatialpartition.h\"\n#include \"llviewershadermgr.h\"\n#include \"llrender.h\"\n\n\nstatic LLGLSLShader* simple_shader = NULL;\nstatic LLGLSLShader* fullbright_shader = NULL;\n\nstatic LLFastTimer::DeclareTimer FTM_RENDER_SIMPLE_DEFERRED(\"Deferred Simple\");\nstatic LLFastTimer::DeclareTimer FTM_RENDER_GRASS_DEFERRED(\"Deferred Grass\");\n\nvoid LLDrawPoolGlow::render(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_GLOW);\n\tLLGLEnable blend(GL_BLEND);\n\tLLGLDisable test(GL_ALPHA_TEST);\n\tgGL.setSceneBlendType(LLRender::BT_ADD);\n\t\n\tU32 shader_level = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT);\n\n\tif (shader_level > 0 && fullbright_shader)\n\t{\n\t\tfullbright_shader->bind();\n\t}\n\telse\n\t{\n\t\tgPipeline.enableLightsFullbright(LLColor4(1,1,1,1));\n\t}\n\n\tLLGLDepthTest depth(GL_TRUE, GL_FALSE);\n\tgGL.setColorMask(false, true);\n\trenderTexture(LLRenderPass::PASS_GLOW, getVertexDataMask());\n\t\n\tgGL.setColorMask(true, false);\n\tgGL.setSceneBlendType(LLRender::BT_ALPHA);\n\t\n\tif (shader_level > 0 && fullbright_shader)\n\t{\n\t\tfullbright_shader->unbind();\n\t}\n}\n\nvoid LLDrawPoolGlow::pushBatch(LLDrawInfo& params, U32 mask, BOOL texture)\n{\n\tglColor4ubv(params.mGlowColor.mV);\n\tLLRenderPass::pushBatch(params, mask, texture);\n}\n\n\nLLDrawPoolSimple::LLDrawPoolSimple() :\n\tLLRenderPass(POOL_SIMPLE)\n{\n}\n\nvoid LLDrawPoolSimple::prerender()\n{\n\tmVertexShaderLevel = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT);\n}\n\nvoid LLDrawPoolSimple::beginRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_SIMPLE);\n\n\tif (LLPipeline::sUnderWaterRender)\n\t{\n\t\tsimple_shader = &gObjectSimpleWaterProgram;\n\t}\n\telse\n\t{\n\t\tsimple_shader = &gObjectSimpleProgram;\n\t}\n\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tsimple_shader->bind();\n\t}\n\telse \n\t{\n\t\t\/\/ don't use shaders!\n\t\tif (gGLManager.mHasShaderObjects)\n\t\t{\n\t\t\tLLGLSLShader::bindNoShader();\n\t\t}\t\t\n\t}\n}\n\nvoid LLDrawPoolSimple::endRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_SIMPLE);\n\tLLRenderPass::endRenderPass(pass);\n\n\tif (mVertexShaderLevel > 0){\n\n\t\tsimple_shader->unbind();\n\t}\n}\n\nvoid LLDrawPoolSimple::render(S32 pass)\n{\n\tLLGLDisable blend(GL_BLEND);\n\tLLGLDisable alpha_test(GL_ALPHA_TEST);\n\t\n\t{ \/\/render simple\n\t\tLLFastTimer t(FTM_RENDER_SIMPLE);\n\t\tgPipeline.enableLightsDynamic();\n\t\trenderTexture(LLRenderPass::PASS_SIMPLE, getVertexDataMask());\n\n\t\tif (LLPipeline::sRenderDeferred)\n\t\t{\n\t\t\trenderTexture(LLRenderPass::PASS_BUMP, getVertexDataMask());\n\t\t}\n\t}\n}\n\n\/\/===============================\n\/\/DEFERRED IMPLEMENTATION\n\/\/===============================\n\nvoid LLDrawPoolSimple::beginDeferredPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_SIMPLE_DEFERRED);\n\tgDeferredDiffuseProgram.bind();\n}\n\nvoid LLDrawPoolSimple::endDeferredPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_SIMPLE_DEFERRED);\n\tLLRenderPass::endRenderPass(pass);\n\n\tgDeferredDiffuseProgram.unbind();\n}\n\nvoid LLDrawPoolSimple::renderDeferred(S32 pass)\n{\n\tLLGLDisable blend(GL_BLEND);\n\tLLGLDisable alpha_test(GL_ALPHA_TEST);\n\n\t{ \/\/render simple\n\t\tLLFastTimer t(FTM_RENDER_SIMPLE_DEFERRED);\n\t\trenderTexture(LLRenderPass::PASS_SIMPLE, getVertexDataMask());\n\t}\n}\n\n\/\/ grass drawpool\nLLDrawPoolGrass::LLDrawPoolGrass() :\n LLRenderPass(POOL_GRASS)\n{\n\n}\n\nvoid LLDrawPoolGrass::prerender()\n{\n\tmVertexShaderLevel = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT);\n}\n\n\nvoid LLDrawPoolGrass::beginRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_GRASS);\n\n\tif (LLPipeline::sUnderWaterRender)\n\t{\n\t\tsimple_shader = &gObjectSimpleWaterProgram;\n\t}\n\telse\n\t{\n\t\tsimple_shader = &gObjectSimpleProgram;\n\t}\n\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tsimple_shader->bind();\n\t}\n\telse \n\t{\n\t\t\/\/ don't use shaders!\n\t\tif (gGLManager.mHasShaderObjects)\n\t\t{\n\t\t\tLLGLSLShader::bindNoShader();\n\t\t}\t\t\n\t}\n}\n\nvoid LLDrawPoolGrass::endRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_GRASS);\n\tLLRenderPass::endRenderPass(pass);\n\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tsimple_shader->unbind();\n\t}\n}\n\nvoid LLDrawPoolGrass::render(S32 pass)\n{\n\tLLGLDisable blend(GL_BLEND);\n\tgGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);\n\n\t{\n\t\tLLFastTimer t(FTM_RENDER_GRASS);\n\t\tLLGLEnable test(GL_ALPHA_TEST);\n\t\tgGL.setSceneBlendType(LLRender::BT_ALPHA);\n\t\t\/\/render grass\n\t\tLLRenderPass::renderTexture(LLRenderPass::PASS_GRASS, getVertexDataMask());\n\t}\t\t\t\n\n\tgGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);\n}\n\nvoid LLDrawPoolGrass::beginDeferredPass(S32 pass)\n{\n\n}\n\nvoid LLDrawPoolGrass::endDeferredPass(S32 pass)\n{\n\n}\n\nvoid LLDrawPoolGrass::renderDeferred(S32 pass)\n{\n\tgGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.f);\n\n\t{\n\t\tLLFastTimer t(FTM_RENDER_GRASS_DEFERRED);\n\t\tgDeferredTreeProgram.bind();\n\t\tLLGLEnable test(GL_ALPHA_TEST);\n\t\t\/\/render grass\n\t\tLLRenderPass::renderTexture(LLRenderPass::PASS_GRASS, getVertexDataMask());\n\t}\t\t\t\n\n\tgGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);\n}\n\n\n\/\/ Fullbright drawpool\nLLDrawPoolFullbright::LLDrawPoolFullbright() :\n\tLLRenderPass(POOL_FULLBRIGHT)\n{\n}\n\nvoid LLDrawPoolFullbright::prerender()\n{\n\tmVertexShaderLevel = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT);\n}\n\nvoid LLDrawPoolFullbright::beginRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_FULLBRIGHT);\n\t\n\tif (LLPipeline::sUnderWaterRender)\n\t{\n\t\tfullbright_shader = &gObjectFullbrightWaterProgram;\n\t}\n\telse\n\t{\n\t\tfullbright_shader = &gObjectFullbrightProgram;\n\t}\n}\n\nvoid LLDrawPoolFullbright::endRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_FULLBRIGHT);\n\tLLRenderPass::endRenderPass(pass);\n\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tfullbright_shader->unbind();\n\t}\n}\n\nvoid LLDrawPoolFullbright::render(S32 pass)\n{ \/\/render fullbright\n\tLLFastTimer t(FTM_RENDER_FULLBRIGHT);\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tfullbright_shader->bind();\n\t\tfullbright_shader->uniform1f(LLViewerShaderMgr::FULLBRIGHT, 1.f);\n\t}\n\telse\n\t{\n\t\tgPipeline.enableLightsFullbright(LLColor4(1,1,1,1));\n\t}\n\t\n\t\/\/gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.25f);\n\t\n\t\/\/LLGLEnable test(GL_ALPHA_TEST);\n\t\/\/LLGLEnable blend(GL_BLEND);\n\tgGL.setSceneBlendType(LLRender::BT_ALPHA);\n\tU32 fullbright_mask = LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_TEXCOORD0 | LLVertexBuffer::MAP_COLOR;\n\trenderTexture(LLRenderPass::PASS_FULLBRIGHT, fullbright_mask);\n\n\t\/\/gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);\n}\n\nS32 LLDrawPoolFullbright::getNumPasses()\n{ \n\treturn 1;\n}\n\n<commit_msg>Stop z-fighting in glow pass.<commit_after>\/** \n * @file lldrawpoolsimple.cpp\n * @brief LLDrawPoolSimple class implementation\n *\n * $LicenseInfo:firstyear=2002&license=viewergpl$\n * \n * Copyright (c) 2002-2009, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"lldrawpoolsimple.h\"\n\n#include \"llviewercamera.h\"\n#include \"lldrawable.h\"\n#include \"llface.h\"\n#include \"llsky.h\"\n#include \"pipeline.h\"\n#include \"llspatialpartition.h\"\n#include \"llviewershadermgr.h\"\n#include \"llrender.h\"\n\n\nstatic LLGLSLShader* simple_shader = NULL;\nstatic LLGLSLShader* fullbright_shader = NULL;\n\nstatic LLFastTimer::DeclareTimer FTM_RENDER_SIMPLE_DEFERRED(\"Deferred Simple\");\nstatic LLFastTimer::DeclareTimer FTM_RENDER_GRASS_DEFERRED(\"Deferred Grass\");\n\nvoid LLDrawPoolGlow::render(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_GLOW);\n\tLLGLEnable blend(GL_BLEND);\n\tLLGLDisable test(GL_ALPHA_TEST);\n\tgGL.flush();\n\t\/\/\/ Get rid of z-fighting with non-glow pass.\n\tLLGLEnable polyOffset(GL_POLYGON_OFFSET_FILL);\n\tglPolygonOffset(-1.0f, -1.0f);\n\tgGL.setSceneBlendType(LLRender::BT_ADD);\n\t\n\tU32 shader_level = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT);\n\n\tif (shader_level > 0 && fullbright_shader)\n\t{\n\t\tfullbright_shader->bind();\n\t}\n\telse\n\t{\n\t\tgPipeline.enableLightsFullbright(LLColor4(1,1,1,1));\n\t}\n\n\tLLGLDepthTest depth(GL_TRUE, GL_FALSE);\n\tgGL.setColorMask(false, true);\n\trenderTexture(LLRenderPass::PASS_GLOW, getVertexDataMask());\n\t\n\tgGL.setColorMask(true, false);\n\tgGL.setSceneBlendType(LLRender::BT_ALPHA);\n\t\n\tif (shader_level > 0 && fullbright_shader)\n\t{\n\t\tfullbright_shader->unbind();\n\t}\n}\n\nvoid LLDrawPoolGlow::pushBatch(LLDrawInfo& params, U32 mask, BOOL texture)\n{\n\tglColor4ubv(params.mGlowColor.mV);\n\tLLRenderPass::pushBatch(params, mask, texture);\n}\n\n\nLLDrawPoolSimple::LLDrawPoolSimple() :\n\tLLRenderPass(POOL_SIMPLE)\n{\n}\n\nvoid LLDrawPoolSimple::prerender()\n{\n\tmVertexShaderLevel = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT);\n}\n\nvoid LLDrawPoolSimple::beginRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_SIMPLE);\n\n\tif (LLPipeline::sUnderWaterRender)\n\t{\n\t\tsimple_shader = &gObjectSimpleWaterProgram;\n\t}\n\telse\n\t{\n\t\tsimple_shader = &gObjectSimpleProgram;\n\t}\n\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tsimple_shader->bind();\n\t}\n\telse \n\t{\n\t\t\/\/ don't use shaders!\n\t\tif (gGLManager.mHasShaderObjects)\n\t\t{\n\t\t\tLLGLSLShader::bindNoShader();\n\t\t}\t\t\n\t}\n}\n\nvoid LLDrawPoolSimple::endRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_SIMPLE);\n\tLLRenderPass::endRenderPass(pass);\n\n\tif (mVertexShaderLevel > 0){\n\n\t\tsimple_shader->unbind();\n\t}\n}\n\nvoid LLDrawPoolSimple::render(S32 pass)\n{\n\tLLGLDisable blend(GL_BLEND);\n\tLLGLDisable alpha_test(GL_ALPHA_TEST);\n\t\n\t{ \/\/render simple\n\t\tLLFastTimer t(FTM_RENDER_SIMPLE);\n\t\tgPipeline.enableLightsDynamic();\n\t\trenderTexture(LLRenderPass::PASS_SIMPLE, getVertexDataMask());\n\n\t\tif (LLPipeline::sRenderDeferred)\n\t\t{\n\t\t\trenderTexture(LLRenderPass::PASS_BUMP, getVertexDataMask());\n\t\t}\n\t}\n}\n\n\/\/===============================\n\/\/DEFERRED IMPLEMENTATION\n\/\/===============================\n\nvoid LLDrawPoolSimple::beginDeferredPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_SIMPLE_DEFERRED);\n\tgDeferredDiffuseProgram.bind();\n}\n\nvoid LLDrawPoolSimple::endDeferredPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_SIMPLE_DEFERRED);\n\tLLRenderPass::endRenderPass(pass);\n\n\tgDeferredDiffuseProgram.unbind();\n}\n\nvoid LLDrawPoolSimple::renderDeferred(S32 pass)\n{\n\tLLGLDisable blend(GL_BLEND);\n\tLLGLDisable alpha_test(GL_ALPHA_TEST);\n\n\t{ \/\/render simple\n\t\tLLFastTimer t(FTM_RENDER_SIMPLE_DEFERRED);\n\t\trenderTexture(LLRenderPass::PASS_SIMPLE, getVertexDataMask());\n\t}\n}\n\n\/\/ grass drawpool\nLLDrawPoolGrass::LLDrawPoolGrass() :\n LLRenderPass(POOL_GRASS)\n{\n\n}\n\nvoid LLDrawPoolGrass::prerender()\n{\n\tmVertexShaderLevel = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT);\n}\n\n\nvoid LLDrawPoolGrass::beginRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_GRASS);\n\n\tif (LLPipeline::sUnderWaterRender)\n\t{\n\t\tsimple_shader = &gObjectSimpleWaterProgram;\n\t}\n\telse\n\t{\n\t\tsimple_shader = &gObjectSimpleProgram;\n\t}\n\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tsimple_shader->bind();\n\t}\n\telse \n\t{\n\t\t\/\/ don't use shaders!\n\t\tif (gGLManager.mHasShaderObjects)\n\t\t{\n\t\t\tLLGLSLShader::bindNoShader();\n\t\t}\t\t\n\t}\n}\n\nvoid LLDrawPoolGrass::endRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_GRASS);\n\tLLRenderPass::endRenderPass(pass);\n\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tsimple_shader->unbind();\n\t}\n}\n\nvoid LLDrawPoolGrass::render(S32 pass)\n{\n\tLLGLDisable blend(GL_BLEND);\n\tgGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);\n\n\t{\n\t\tLLFastTimer t(FTM_RENDER_GRASS);\n\t\tLLGLEnable test(GL_ALPHA_TEST);\n\t\tgGL.setSceneBlendType(LLRender::BT_ALPHA);\n\t\t\/\/render grass\n\t\tLLRenderPass::renderTexture(LLRenderPass::PASS_GRASS, getVertexDataMask());\n\t}\t\t\t\n\n\tgGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);\n}\n\nvoid LLDrawPoolGrass::beginDeferredPass(S32 pass)\n{\n\n}\n\nvoid LLDrawPoolGrass::endDeferredPass(S32 pass)\n{\n\n}\n\nvoid LLDrawPoolGrass::renderDeferred(S32 pass)\n{\n\tgGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.f);\n\n\t{\n\t\tLLFastTimer t(FTM_RENDER_GRASS_DEFERRED);\n\t\tgDeferredTreeProgram.bind();\n\t\tLLGLEnable test(GL_ALPHA_TEST);\n\t\t\/\/render grass\n\t\tLLRenderPass::renderTexture(LLRenderPass::PASS_GRASS, getVertexDataMask());\n\t}\t\t\t\n\n\tgGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);\n}\n\n\n\/\/ Fullbright drawpool\nLLDrawPoolFullbright::LLDrawPoolFullbright() :\n\tLLRenderPass(POOL_FULLBRIGHT)\n{\n}\n\nvoid LLDrawPoolFullbright::prerender()\n{\n\tmVertexShaderLevel = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT);\n}\n\nvoid LLDrawPoolFullbright::beginRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_FULLBRIGHT);\n\t\n\tif (LLPipeline::sUnderWaterRender)\n\t{\n\t\tfullbright_shader = &gObjectFullbrightWaterProgram;\n\t}\n\telse\n\t{\n\t\tfullbright_shader = &gObjectFullbrightProgram;\n\t}\n}\n\nvoid LLDrawPoolFullbright::endRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_FULLBRIGHT);\n\tLLRenderPass::endRenderPass(pass);\n\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tfullbright_shader->unbind();\n\t}\n}\n\nvoid LLDrawPoolFullbright::render(S32 pass)\n{ \/\/render fullbright\n\tLLFastTimer t(FTM_RENDER_FULLBRIGHT);\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tfullbright_shader->bind();\n\t\tfullbright_shader->uniform1f(LLViewerShaderMgr::FULLBRIGHT, 1.f);\n\t}\n\telse\n\t{\n\t\tgPipeline.enableLightsFullbright(LLColor4(1,1,1,1));\n\t}\n\t\n\t\/\/gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.25f);\n\t\n\t\/\/LLGLEnable test(GL_ALPHA_TEST);\n\t\/\/LLGLEnable blend(GL_BLEND);\n\tgGL.setSceneBlendType(LLRender::BT_ALPHA);\n\tU32 fullbright_mask = LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_TEXCOORD0 | LLVertexBuffer::MAP_COLOR;\n\trenderTexture(LLRenderPass::PASS_FULLBRIGHT, fullbright_mask);\n\n\t\/\/gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);\n}\n\nS32 LLDrawPoolFullbright::getNumPasses()\n{ \n\treturn 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 Cloudera, Inc. All rights reserved.\n\n#include \"sparrow\/state-store-subscriber-service.h\"\n\n#include <iostream>\n#include <utility>\n\n#include <boost\/algorithm\/string\/join.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/format.hpp>\n#include <concurrency\/PosixThreadFactory.h>\n#include <concurrency\/Thread.h>\n#include <concurrency\/ThreadManager.h>\n#include <glog\/logging.h>\n#include <gflags\/gflags.h>\n#include <protocol\/TBinaryProtocol.h>\n#include <transport\/TBufferTransports.h>\n#include <transport\/TServerSocket.h>\n#include <transport\/TSocket.h>\n\n#include \"common\/status.h\"\n#include \"gen-cpp\/StateStoreService_types.h\"\n#include \"gen-cpp\/StateStoreSubscriberService_types.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace ::apache::thrift;\nusing namespace ::apache::thrift::protocol;\nusing namespace ::apache::thrift::transport;\nusing namespace ::apache::thrift::server;\nusing impala::Status;\nusing impala::THostPort;\nusing impala::TStatusCode;\n\nnamespace sparrow {\n\nconst char* StateStoreSubscriber::DISCONNECTED_FROM_STATE_STORE_ERROR =\n \"Client disconnected from state store\";\n\nStateStoreSubscriber::StateStoreSubscriber(const string& host, int port,\n const string& state_store_host,\n int state_store_port)\n : server_running_(false) {\n host_port_.host = host;\n host_port_.port = port;\n state_store_host_port_.host = state_store_host;\n state_store_host_port_.port = state_store_port;\n}\n\nStateStoreSubscriber::~StateStoreSubscriber() {\n if (!IsRunning()) {\n LOG(ERROR) << \"StateStoreSubscriber destructed before being properly shut \"\n << \"down (using Stop())\";\n \/\/ This assumes that Stop() cannot be called in a different thread.\n Stop();\n }\n}\n\nStatus StateStoreSubscriber::RegisterService(const string& service_id,\n const THostPort& address) {\n RETURN_IF_ERROR(InitClient());\n\n TRegisterServiceRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_service_id(service_id);\n request.__set_service_address(address);\n TRegisterServiceResponse response;\n VLOG(1) << \"Attempting to register service \" << request.service_id\n << \" on subscriber at \" << request.subscriber_address.host << \":\"\n << request.subscriber_address.port;\n\n try {\n client_->RegisterService(response, request);\n } catch (TTransportException& e) {\n \/\/ Client has gotten disconnected from the state store.\n Status status(e.what());\n status.AddErrorMsg(DISCONNECTED_FROM_STATE_STORE_ERROR);\n return status;\n }\n Status status(response.status);\n if (status.ok()) {\n services_.insert(service_id);\n }\n return status;\n}\n\nStatus StateStoreSubscriber::UnregisterService(const string& service_id) {\n RETURN_IF_ERROR(InitClient());\n\n unordered_set<string>::iterator service = services_.find(service_id);\n if (service == services_.end()) {\n format error_status(\"Service id %1% not registered with this subscriber\");\n error_status % service_id;\n return Status(error_status.str());\n }\n\n TUnregisterServiceRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_service_id(service_id);\n TUnregisterServiceResponse response;\n\n try {\n client_->UnregisterService(response, request);\n } catch ( TTransportException& e) {\n Status status(e.what());\n status.AddErrorMsg(DISCONNECTED_FROM_STATE_STORE_ERROR);\n return status;\n }\n Status status(response.status);\n if (status.ok()) {\n services_.erase(service);\n }\n return status;\n}\n\nStatus StateStoreSubscriber::RegisterSubscription(\n const SubscriptionManager::UpdateCallback& update_callback,\n const unordered_set<string>& update_services, SubscriptionId* id) {\n RETURN_IF_ERROR(InitClient());\n\n TRegisterSubscriptionRequest request;\n request.__set_subscriber_address(host_port_);\n request.services.insert(update_services.begin(), update_services.end());\n request.__isset.services = true;\n TRegisterSubscriptionResponse response;\n VLOG(1) << \"Attempting to register subscriber for services \"\n << algorithm::join(update_services, \", \") << \" at \"\n << request.subscriber_address.host << \":\" << request.subscriber_address.port;\n\n try {\n client_->RegisterSubscription(response, request);\n } catch (TTransportException& e) {\n \/\/ Client has gotten disconnected from the state store.\n Status status(e.what());\n status.AddErrorMsg(DISCONNECTED_FROM_STATE_STORE_ERROR);\n return status;\n }\n\n Status status(response.status);\n if (!status.ok()) {\n return status;\n }\n if (!response.__isset.subscription_id) {\n status.AddErrorMsg(\"Invalid response: subscription_id not set.\");\n return status;\n }\n\n *id = response.subscription_id;\n lock_guard<mutex> lock(update_callbacks_lock_);\n update_callbacks_.insert(make_pair(response.subscription_id, update_callback));\n return status;\n}\n\nStatus StateStoreSubscriber::UnregisterSubscription(SubscriptionId id) {\n RETURN_IF_ERROR(InitClient());\n\n {\n lock_guard<mutex> lock(update_callbacks_lock_);\n UpdateCallbacks::iterator callback = update_callbacks_.find(id);\n if (callback == update_callbacks_.end()) {\n format error_status(\"Subscription id %1% not registered with this subscriber\");\n error_status % id;\n return Status(error_status.str());\n }\n }\n\n TUnregisterSubscriptionRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_subscription_id(id);\n TUnregisterSubscriptionResponse response;\n try {\n client_->UnregisterSubscription(response, request);\n } catch (TTransportException& e) {\n Status status(e.what());\n status.AddErrorMsg(DISCONNECTED_FROM_STATE_STORE_ERROR);\n return status;\n }\n\n Status status(response.status);\n if (status.ok()) {\n lock_guard<mutex> lock(update_callbacks_lock_);\n \/\/ Don't use the iterator to erase, because it may have been invalidated by now.\n update_callbacks_.erase(id);\n }\n return Status(response.status);\n}\n\nvoid StateStoreSubscriber::UpdateState(TUpdateStateResponse& response,\n const TUpdateStateRequest& request) {\n RETURN_IF_UNSET(request, service_memberships, response);\n\n ServiceStateMap state;\n StateFromThrift(request, &state);\n\n \/\/ Log all of the new state we just got.\n stringstream new_state;\n BOOST_FOREACH(const ServiceStateMap::value_type& service_state, state) {\n new_state << \"State for service \" << service_state.first << \":\\n\" << \"Membership: \";\n BOOST_FOREACH(const Membership::value_type& instance,\n service_state.second.membership) {\n new_state << instance.second.host << \":\" << instance.second.port\n << \" (at subscriber \" << instance.first << \"),\";\n }\n new_state << \"\\n\";\n \/\/ TODO: Log object updates here too, once we include them.\n }\n VLOG(1) << \"Received new state:\\n\" << new_state.str();\n\n \/\/ Make a copy of update_callbacks_, to avoid problems if one of the callbacks\n \/\/ calls back into this StateStoreSubscriber, which may deadlock if we are holding\n \/\/ the update_callbacks_lock_.\n UpdateCallbacks update_callbacks_copy;\n {\n lock_guard<mutex> lock(update_callbacks_lock_);\n update_callbacks_copy = update_callbacks_;\n }\n\n \/\/ TODO: This is problematic if any of the callbacks take a long time. Eventually,\n \/\/ we'll probably want to execute the callbacks asynchronously in a different thread.\n BOOST_FOREACH(UpdateCallbacks::value_type& update, update_callbacks_copy) {\n update.second(state);\n }\n RETURN_AND_SET_STATUS_OK(response);\n}\n\nvoid StateStoreSubscriber::Start() {\n shared_ptr<TProcessor> processor(\n new StateStoreSubscriberServiceProcessor(shared_from_this()));\n shared_ptr<TServerTransport> server_transport(new TServerSocket(host_port_.port));\n shared_ptr<TTransportFactory> transport_factory(new TBufferedTransportFactory());\n shared_ptr<TProtocolFactory> protocol_factory(new TBinaryProtocolFactory());\n\n LOG(INFO) << \"StateStoreSubscriber listening on \" << host_port_.port;\n server_.reset(new TSimpleServer(processor, server_transport, transport_factory,\n protocol_factory));\n\n DCHECK(!server_running_);\n server_running_ = true;\n server_thread_.reset(new thread(&TSimpleServer::serve, server_));\n}\n\nbool StateStoreSubscriber::IsRunning() {\n return server_running_;\n}\n\nvoid StateStoreSubscriber::Stop() {\n Status status = InitClient();\n if (status.ok()) {\n try {\n \/\/ Unregister all running services.\n BOOST_FOREACH(const string& service_id, services_) {\n TUnregisterServiceRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_service_id(service_id);\n TUnregisterServiceResponse response;\n client_->UnregisterService(response, request);\n Status unregister_status(response.status);\n if (!unregister_status.ok()) {\n LOG(ERROR) << \"Error when unregistering service \" << service_id << \":\"\n << unregister_status.GetErrorMsg();\n }\n }\n\n lock_guard<mutex> lock(update_callbacks_lock_);\n \/\/ Unregister all subscriptions.\n BOOST_FOREACH(const UpdateCallbacks::value_type& callback_pair,\n update_callbacks_) {\n SubscriptionId id = callback_pair.first;\n TUnregisterSubscriptionRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_subscription_id(id);\n TUnregisterSubscriptionResponse response;\n \/\/ Ignore any errors in the response.\n client_->UnregisterSubscription(response, request);\n Status unregister_status(response.status);\n if (!unregister_status.ok()) {\n string error_msg;\n unregister_status.GetErrorMsg(&error_msg);\n VLOG(1) << \"Error when unregistering subscription \" << id << \":\"\n << error_msg;\n }\n }\n } catch (TTransportException& e) {\n LOG(ERROR) << \"Connection to state store disrupted when trying to unregister; \"\n << \"received error: \" << e.what();\n }\n }\n\n DCHECK(server_running_);\n server_->stop();\n server_running_ = false;\n \/\/ TODO: The server seems to keep going indefinitely if the subscriber still has a\n \/\/ connection to the state store, causing this to not return. See if this is possible\n \/\/ to fix.\n \/\/server_thread_->join();\n}\n\nStatus StateStoreSubscriber::InitClient() {\n DCHECK(server_running_);\n\n Status status;\n if (client_.get() == NULL) {\n shared_ptr<TSocket> socket(new TSocket(state_store_host_port_.host,\n state_store_host_port_.port));\n shared_ptr<TTransport> transport(new TBufferedTransport(socket));\n shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));\n client_.reset(new StateStoreServiceClient(protocol));\n\n try {\n transport->open();\n } catch (TTransportException& e) {\n status.AddErrorMsg(e.what());\n status.AddErrorMsg(\"Unable to register with the StateStore\");\n }\n }\n return status;\n}\n\n}\n<commit_msg>Fix backend test failures<commit_after>\/\/ Copyright (c) 2012 Cloudera, Inc. All rights reserved.\n\n#include \"sparrow\/state-store-subscriber-service.h\"\n\n#include <iostream>\n#include <utility>\n\n#include <boost\/algorithm\/string\/join.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/format.hpp>\n#include <concurrency\/PosixThreadFactory.h>\n#include <concurrency\/Thread.h>\n#include <concurrency\/ThreadManager.h>\n#include <glog\/logging.h>\n#include <gflags\/gflags.h>\n#include <protocol\/TBinaryProtocol.h>\n#include <transport\/TBufferTransports.h>\n#include <transport\/TServerSocket.h>\n#include <transport\/TSocket.h>\n\n#include \"common\/status.h\"\n#include \"gen-cpp\/StateStoreService_types.h\"\n#include \"gen-cpp\/StateStoreSubscriberService_types.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace ::apache::thrift;\nusing namespace ::apache::thrift::protocol;\nusing namespace ::apache::thrift::transport;\nusing namespace ::apache::thrift::server;\nusing impala::Status;\nusing impala::THostPort;\nusing impala::TStatusCode;\n\nnamespace sparrow {\n\nconst char* StateStoreSubscriber::DISCONNECTED_FROM_STATE_STORE_ERROR =\n \"Client disconnected from state store\";\n\nStateStoreSubscriber::StateStoreSubscriber(const string& host, int port,\n const string& state_store_host,\n int state_store_port)\n : server_running_(false) {\n host_port_.host = host;\n host_port_.port = port;\n state_store_host_port_.host = state_store_host;\n state_store_host_port_.port = state_store_port;\n}\n\nStateStoreSubscriber::~StateStoreSubscriber() {\n if (IsRunning()) {\n Stop();\n }\n}\n\nStatus StateStoreSubscriber::RegisterService(const string& service_id,\n const THostPort& address) {\n RETURN_IF_ERROR(InitClient());\n\n TRegisterServiceRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_service_id(service_id);\n request.__set_service_address(address);\n TRegisterServiceResponse response;\n VLOG(1) << \"Attempting to register service \" << request.service_id\n << \" on subscriber at \" << request.subscriber_address.host << \":\"\n << request.subscriber_address.port;\n\n try {\n client_->RegisterService(response, request);\n } catch (TTransportException& e) {\n \/\/ Client has gotten disconnected from the state store.\n Status status(e.what());\n status.AddErrorMsg(DISCONNECTED_FROM_STATE_STORE_ERROR);\n return status;\n }\n Status status(response.status);\n if (status.ok()) {\n services_.insert(service_id);\n }\n return status;\n}\n\nStatus StateStoreSubscriber::UnregisterService(const string& service_id) {\n RETURN_IF_ERROR(InitClient());\n\n unordered_set<string>::iterator service = services_.find(service_id);\n if (service == services_.end()) {\n format error_status(\"Service id %1% not registered with this subscriber\");\n error_status % service_id;\n return Status(error_status.str());\n }\n\n TUnregisterServiceRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_service_id(service_id);\n TUnregisterServiceResponse response;\n\n try {\n client_->UnregisterService(response, request);\n } catch ( TTransportException& e) {\n Status status(e.what());\n status.AddErrorMsg(DISCONNECTED_FROM_STATE_STORE_ERROR);\n return status;\n }\n Status status(response.status);\n if (status.ok()) {\n services_.erase(service);\n }\n return status;\n}\n\nStatus StateStoreSubscriber::RegisterSubscription(\n const SubscriptionManager::UpdateCallback& update_callback,\n const unordered_set<string>& update_services, SubscriptionId* id) {\n RETURN_IF_ERROR(InitClient());\n\n TRegisterSubscriptionRequest request;\n request.__set_subscriber_address(host_port_);\n request.services.insert(update_services.begin(), update_services.end());\n request.__isset.services = true;\n TRegisterSubscriptionResponse response;\n VLOG(1) << \"Attempting to register subscriber for services \"\n << algorithm::join(update_services, \", \") << \" at \"\n << request.subscriber_address.host << \":\" << request.subscriber_address.port;\n\n try {\n client_->RegisterSubscription(response, request);\n } catch (TTransportException& e) {\n \/\/ Client has gotten disconnected from the state store.\n Status status(e.what());\n status.AddErrorMsg(DISCONNECTED_FROM_STATE_STORE_ERROR);\n return status;\n }\n\n Status status(response.status);\n if (!status.ok()) {\n return status;\n }\n if (!response.__isset.subscription_id) {\n status.AddErrorMsg(\"Invalid response: subscription_id not set.\");\n return status;\n }\n\n *id = response.subscription_id;\n lock_guard<mutex> lock(update_callbacks_lock_);\n update_callbacks_.insert(make_pair(response.subscription_id, update_callback));\n return status;\n}\n\nStatus StateStoreSubscriber::UnregisterSubscription(SubscriptionId id) {\n RETURN_IF_ERROR(InitClient());\n\n {\n lock_guard<mutex> lock(update_callbacks_lock_);\n UpdateCallbacks::iterator callback = update_callbacks_.find(id);\n if (callback == update_callbacks_.end()) {\n format error_status(\"Subscription id %1% not registered with this subscriber\");\n error_status % id;\n return Status(error_status.str());\n }\n }\n\n TUnregisterSubscriptionRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_subscription_id(id);\n TUnregisterSubscriptionResponse response;\n try {\n client_->UnregisterSubscription(response, request);\n } catch (TTransportException& e) {\n Status status(e.what());\n status.AddErrorMsg(DISCONNECTED_FROM_STATE_STORE_ERROR);\n return status;\n }\n\n Status status(response.status);\n if (status.ok()) {\n lock_guard<mutex> lock(update_callbacks_lock_);\n \/\/ Don't use the iterator to erase, because it may have been invalidated by now.\n update_callbacks_.erase(id);\n }\n return Status(response.status);\n}\n\nvoid StateStoreSubscriber::UpdateState(TUpdateStateResponse& response,\n const TUpdateStateRequest& request) {\n RETURN_IF_UNSET(request, service_memberships, response);\n\n ServiceStateMap state;\n StateFromThrift(request, &state);\n\n \/\/ Log all of the new state we just got.\n stringstream new_state;\n BOOST_FOREACH(const ServiceStateMap::value_type& service_state, state) {\n new_state << \"State for service \" << service_state.first << \":\\n\" << \"Membership: \";\n BOOST_FOREACH(const Membership::value_type& instance,\n service_state.second.membership) {\n new_state << instance.second.host << \":\" << instance.second.port\n << \" (at subscriber \" << instance.first << \"),\";\n }\n new_state << \"\\n\";\n \/\/ TODO: Log object updates here too, once we include them.\n }\n VLOG(1) << \"Received new state:\\n\" << new_state.str();\n\n \/\/ Make a copy of update_callbacks_, to avoid problems if one of the callbacks\n \/\/ calls back into this StateStoreSubscriber, which may deadlock if we are holding\n \/\/ the update_callbacks_lock_.\n UpdateCallbacks update_callbacks_copy;\n {\n lock_guard<mutex> lock(update_callbacks_lock_);\n update_callbacks_copy = update_callbacks_;\n }\n\n \/\/ TODO: This is problematic if any of the callbacks take a long time. Eventually,\n \/\/ we'll probably want to execute the callbacks asynchronously in a different thread.\n BOOST_FOREACH(UpdateCallbacks::value_type& update, update_callbacks_copy) {\n update.second(state);\n }\n RETURN_AND_SET_STATUS_OK(response);\n}\n\nvoid StateStoreSubscriber::Start() {\n shared_ptr<TProcessor> processor(\n new StateStoreSubscriberServiceProcessor(shared_from_this()));\n shared_ptr<TServerTransport> server_transport(new TServerSocket(host_port_.port));\n shared_ptr<TTransportFactory> transport_factory(new TBufferedTransportFactory());\n shared_ptr<TProtocolFactory> protocol_factory(new TBinaryProtocolFactory());\n\n LOG(INFO) << \"StateStoreSubscriber listening on \" << host_port_.port;\n server_.reset(new TSimpleServer(processor, server_transport, transport_factory,\n protocol_factory));\n\n DCHECK(!server_running_);\n server_running_ = true;\n server_thread_.reset(new thread(&TSimpleServer::serve, server_));\n}\n\nbool StateStoreSubscriber::IsRunning() {\n return server_running_;\n}\n\nvoid StateStoreSubscriber::Stop() {\n Status status = InitClient();\n if (status.ok()) {\n try {\n \/\/ Unregister all running services.\n BOOST_FOREACH(const string& service_id, services_) {\n TUnregisterServiceRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_service_id(service_id);\n TUnregisterServiceResponse response;\n client_->UnregisterService(response, request);\n Status unregister_status(response.status);\n if (!unregister_status.ok()) {\n LOG(ERROR) << \"Error when unregistering service \" << service_id << \":\"\n << unregister_status.GetErrorMsg();\n }\n }\n\n lock_guard<mutex> lock(update_callbacks_lock_);\n \/\/ Unregister all subscriptions.\n BOOST_FOREACH(const UpdateCallbacks::value_type& callback_pair,\n update_callbacks_) {\n SubscriptionId id = callback_pair.first;\n TUnregisterSubscriptionRequest request;\n request.__set_subscriber_address(host_port_);\n request.__set_subscription_id(id);\n TUnregisterSubscriptionResponse response;\n \/\/ Ignore any errors in the response.\n client_->UnregisterSubscription(response, request);\n Status unregister_status(response.status);\n if (!unregister_status.ok()) {\n string error_msg;\n unregister_status.GetErrorMsg(&error_msg);\n VLOG(1) << \"Error when unregistering subscription \" << id << \":\"\n << error_msg;\n }\n }\n } catch (TTransportException& e) {\n LOG(ERROR) << \"Connection to state store disrupted when trying to unregister; \"\n << \"received error: \" << e.what();\n }\n }\n\n DCHECK(server_running_);\n server_->stop();\n server_running_ = false;\n \/\/ TODO: The server seems to keep going indefinitely if the subscriber still has a\n \/\/ connection to the state store, causing this to not return. See if this is possible\n \/\/ to fix.\n \/\/server_thread_->join();\n}\n\nStatus StateStoreSubscriber::InitClient() {\n DCHECK(server_running_);\n\n Status status;\n if (client_.get() == NULL) {\n shared_ptr<TSocket> socket(new TSocket(state_store_host_port_.host,\n state_store_host_port_.port));\n shared_ptr<TTransport> transport(new TBufferedTransport(socket));\n shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));\n client_.reset(new StateStoreServiceClient(protocol));\n\n try {\n transport->open();\n } catch (TTransportException& e) {\n status.AddErrorMsg(e.what());\n status.AddErrorMsg(\"Unable to register with the StateStore\");\n }\n }\n return status;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ Kruskal's algorithm for minimum spanning trees.\n\/\/\n\n#ifndef _KRUSKAL_MST_HH\n#define _KRUSKAL_MST_HH\n\n#include <algorithm>\n\n#include \"disjoint_sets.hh\"\n#include \"graph.hh\"\n\n\/\/ Utility function to compare edge weights, used in sorting.\nbool compare_edge_ptr_weight(const Edge* x, const Edge* y) {\n return x->weight < y->weight;\n}\n\n\/\/ Find the edges in the minimum spanning tree of g. Returns a pointer\n\/\/ to a vector of Edge pointers. The Edge pointers refer to the Edge\n\/\/ objects owned by g. The client is responsible for eventually\n\/\/ deleting the returned vector.\nvector<const Edge*>* kruskal_mst_edges(const Graph& g) {\n assert(!g.empty());\n\n \/\/ Sort the edges into nonincreasing order by weight. We use a\n \/\/ stable sort to make unit testing easier, but stability is not\n \/\/ otherwise necessary.\n vector<Edge*> sorted_edges = g.edges;\n stable_sort(sorted_edges.begin(),\n\t sorted_edges.end(),\n\t compare_edge_ptr_weight);\n\n \/\/ Use a disjoint set data structure to keep track of the patchwork\n \/\/ forest of spanned subgraphs that we'll create. Initially every\n \/\/ vertex is its own component; every time we add an edge, those\n \/\/ components get connected. When we're done the whole graph has\n \/\/ been connected into one component.\n DisjointSets parts(g.n());\n\n \/\/ Edges in the minimum spanning tree.\n vector<const Edge*>* in_tree(new vector<const Edge*>());\n\n for (vector<Edge*>::iterator i = sorted_edges.begin();\n i != sorted_edges.end(); ++i) {\n const Edge& e = **i;\n \/\/ Does this edge connect distinct components?\n if (parts.find(e.v) != parts.find(e.w)) {\n in_tree->push_back(&e); \/\/ Yes, so add it to the tree\n parts.merge(e.v, e.w); \/\/ Now the components are one\n }\n }\n\n return in_tree;\n}\n\n#endif\n<commit_msg>Fix comment typo<commit_after>\n\/\/\n\/\/ Kruskal's algorithm for minimum spanning trees.\n\/\/\n\n#ifndef _KRUSKAL_MST_HH\n#define _KRUSKAL_MST_HH\n\n#include <algorithm>\n\n#include \"disjoint_sets.hh\"\n#include \"graph.hh\"\n\n\/\/ Utility function to compare edge weights, used in sorting.\nbool compare_edge_ptr_weight(const Edge* x, const Edge* y) {\n return x->weight < y->weight;\n}\n\n\/\/ Find the edges in the minimum spanning tree of g. Returns a pointer\n\/\/ to a vector of Edge pointers. The Edge pointers refer to the Edge\n\/\/ objects owned by g. The client is responsible for eventually\n\/\/ deleting the returned vector.\nvector<const Edge*>* kruskal_mst_edges(const Graph& g) {\n assert(!g.empty());\n\n \/\/ Sort the edges into nondecreasing order by weight. We use a\n \/\/ stable sort to make unit testing easier, but stability is not\n \/\/ otherwise necessary.\n vector<Edge*> sorted_edges = g.edges;\n stable_sort(sorted_edges.begin(),\n\t sorted_edges.end(),\n\t compare_edge_ptr_weight);\n\n \/\/ Use a disjoint set data structure to keep track of the patchwork\n \/\/ forest of spanned subgraphs that we'll create. Initially every\n \/\/ vertex is its own component; every time we add an edge, those\n \/\/ components get connected. When we're done the whole graph has\n \/\/ been connected into one component.\n DisjointSets parts(g.n());\n\n \/\/ Edges in the minimum spanning tree.\n vector<const Edge*>* in_tree(new vector<const Edge*>());\n\n for (vector<Edge*>::iterator i = sorted_edges.begin();\n i != sorted_edges.end(); ++i) {\n const Edge& e = **i;\n \/\/ Does this edge connect distinct components?\n if (parts.find(e.v) != parts.find(e.w)) {\n in_tree->push_back(&e); \/\/ Yes, so add it to the tree\n parts.merge(e.v, e.w); \/\/ Now the components are one\n }\n }\n\n return in_tree;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file \tGraphParser.cpp\n * @author \tFabian Wegscheider\n * @date \tJul 10, 2017\n *\/\n\n#include <boost\/spirit\/include\/qi.hpp>\n#include \"GraphParser.h\"\n\nusing std::string;\nusing namespace boost::spirit;\nusing qi::int_;\nusing qi::double_;\nusing qi::phrase_parse;\nusing ascii::space;\n\n\nGraphParser::GraphParser(string file) {\n\tinputFile.open(file);\n\treadSuccessfully = !inputFile.fail();\n}\n\nbool GraphParser::readFirstLine(int& numVertices, int& numEdges) {\n\n\tstring line;\n\tgetline(inputFile, line);\t\/\/first line is read\n\n\tauto it = line.begin();\n\tint n, m;\n\tbool success = phrase_parse(it, line.end(),\n\t\t\tint_[([&n](int j){ n = j; })]\n\t\t\t\t >> int_[([&m](int j){ m = j; })], space);\n\n\tif (!success || it != line.end()) return false;\n\tnumVertices = n;\n\tnumEdges = m;\n\n\treturn true;\n}\n\n\nbool GraphParser::read(Edge edges[], double weights[]) {\n\n\n\tassert(NULL != edges);\n\tassert(NULL != weights);\n\n\n\t\/* we use boost::spirit to parse each line *\/\n\tstring line;\n\n\tint i = 0;\n\n\t\/\/read line by line\n\twhile (getline(inputFile, line)) {\n\n\t\tauto it = line.begin();\n\t\tint start;\n\t\tint end;\n\t\tdouble weight;\n\t\tbool success = phrase_parse(it, line.end(),\n\t\t\t\tint_[([&start](int j){ start = j; })]\n\t\t\t\t\t >> int_[([&end](int j){ end = j; })]\n\t\t\t\t\t\t\t >> double_[([&weight](double j){ weight = j; })], space);\n\t\tif (success && it == line.end()) {\n\t\t\tedges[i] = Edge(start-1, end-1);\n\t\t\tweights[i] = weight;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t\t++i;\n\t}\n\n\n\treturn true;\n}\n\n\n\n<commit_msg>Delete GraphParser.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ ExporterBridge.cpp : Defines the exported functions for the DLL application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"HTMLContentControlBridge.h\"\n#include \"resource.h\"\n\n#include <unknwn.h>\n#include <tchar.h>\n#include <msclr\\auto_gcroot.h>\n\n#include \"..\\..\\..\\..\\ToDoList_Dev\\Interfaces\\ITransText.h\"\n#include \"..\\..\\..\\..\\ToDoList_Dev\\Interfaces\\UITheme.h\"\n#include \"..\\..\\..\\..\\ToDoList_Dev\\Interfaces\\IPreferences.h\"\n#include \"..\\..\\..\\..\\ToDoList_Dev\\Interfaces\\ISpellcheck.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#using <PluginHelpers.dll> as_friend\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace HTMLContentControl;\nusing namespace System;\nusing namespace System::Collections::Generic;\nusing namespace System::Runtime::InteropServices;\n\nusing namespace Abstractspoon::Tdl::PluginHelpers;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ REPLACE THIS WITH NEW GUID!\nconst LPCWSTR HTML_GUID = L\"FE0B6B6E-2B61-4AEB-AA0D-98DBE5942F02\";\nconst LPCWSTR HTML_NAME = L\"Html\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCHTMLContentBridge::CHTMLContentBridge() : m_hIcon(NULL)\n{\n HMODULE hMod = LoadLibrary(L\"HTMLContentControlBridge.dll\"); \/\/ us\n\n m_hIcon = ::LoadIcon(hMod, MAKEINTRESOURCE(IDI_HTML));\n}\n\nCHTMLContentBridge::~CHTMLContentBridge()\n{\n ::DestroyIcon(m_hIcon);\n}\n\nvoid CHTMLContentBridge::Release()\n{\n\tdelete this;\n}\n\nvoid CHTMLContentBridge::SetLocalizer(ITransText* \/*pTT*\/)\n{\n\t\/\/ TODO\n}\n\nLPCWSTR CHTMLContentBridge::GetTypeDescription() const\n{\n\treturn HTML_NAME;\n}\n\nHICON CHTMLContentBridge::GetTypeIcon() const\n{\n return m_hIcon;\n}\n\nLPCWSTR CHTMLContentBridge::GetTypeID() const\n{\n\treturn HTML_GUID;\n}\n\nIContentControl* CHTMLContentBridge::CreateCtrl(unsigned short nCtrlID, unsigned long nStyle, \n\tlong nLeft, long nTop, long nWidth, long nHeight, HWND hwndParent)\n{\n\tCHTMLContentControlBridge* pCtrl = new CHTMLContentControlBridge();\n\n\tif (!pCtrl->Create(nCtrlID, nStyle, nLeft, nTop, nWidth, nHeight, hwndParent))\n\t{\n\t\tpCtrl->Release();\n\t\tpCtrl = NULL;\n\t}\n\n\treturn pCtrl;\n}\n\nvoid CHTMLContentBridge::SavePreferences(IPreferences* pPrefs, LPCWSTR szKey) const\n{\n\t\/\/ TODO\n\n}\n\nvoid CHTMLContentBridge::LoadPreferences(const IPreferences* pPrefs, LPCWSTR szKey, bool bAppOnly)\n{\n\t\/\/ TODO\n}\n\n\/\/ returns the length of the html or zero if not supported\nint CHTMLContentBridge::ConvertToHtml(const unsigned char* pContent, int nLength,\n\tLPCWSTR szCharSet, LPWSTR& szHtml, LPCWSTR szImageDir)\n{\n\tszHtml = nullptr;\n\treturn 0;\n}\n\nvoid CHTMLContentBridge::FreeHtmlBuffer(LPWSTR& szHtml)\n{\n\tdelete [] szHtml;\n\tszHtml = nullptr;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This is the constructor of a class that has been exported.\n\/\/ see ExporterBridge.h for the class definition\nCHTMLContentControlBridge::CHTMLContentControlBridge()\n{\n}\n\nBOOL CHTMLContentControlBridge::Create(UINT nCtrlID, DWORD nStyle, \n\tlong nLeft, long nTop, long nWidth, long nHeight, HWND hwndParent)\n{\n\tm_wnd = gcnew HTMLContentControl::HTMLContentControlCore(static_cast<IntPtr>(hwndParent));\n\n\tHWND hWnd = GetHwnd();\n\n\tif (hWnd)\n\t{\n\t\t::SetParent(hWnd, hwndParent);\n\t\t::SetWindowLong(hWnd, GWL_ID, nCtrlID);\n\t\t::SetWindowLong(hWnd, GWL_STYLE, nStyle);\n\t\t::MoveWindow(hWnd, nLeft, nTop, nWidth, nHeight, FALSE);\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nint CHTMLContentControlBridge::GetContent(unsigned char* pContent) const\n{\n\tcli::array<Byte>^ content = m_wnd->GetContent();\n\tint nLength = content->Length;\n\n\tif (pContent && nLength)\n\t{\n\t\tpin_ptr<Byte> ptrContent = &content[content->GetLowerBound(0)];\n\t\tCopyMemory(pContent, ptrContent, nLength);\n\t}\n\n\treturn nLength;\n}\n\nbool CHTMLContentControlBridge::SetContent(const unsigned char* pContent, int nLength, bool bResetSelection)\n{\n\tcli::array<Byte>^ content = gcnew cli::array<Byte>(nLength);\n\n\tfor (int i = 0; i < nLength; i++)\n\t\tcontent[i] = pContent[i];\n\n\treturn m_wnd->SetContent(content, bResetSelection);\n}\n\nLPCWSTR CHTMLContentControlBridge::GetTypeID() const\n{\n\treturn HTML_GUID;\n}\n\n\/\/ text content if supported. return false if not supported\nint CHTMLContentControlBridge::GetTextContent(LPWSTR szContent, int nLength) const\n{\n\tString^ content = m_wnd->GetTextContent();\n\tnLength = content->Length;\n\n\tif (szContent != nullptr)\n\t{\n\t\tAbstractspoon::Tdl::PluginHelpers::MarshalledString msContent(content);\n\t\tCopyMemory(szContent, msContent, (nLength * sizeof(WCHAR)));\n\t}\n\n\treturn nLength;\n}\n\nbool CHTMLContentControlBridge::SetTextContent(LPCWSTR szContent, bool bResetSelection)\n{\n\tmsclr::auto_gcroot<String^> content = gcnew String(szContent);\n\n\treturn m_wnd->SetTextContent(content, bResetSelection);\n}\n\nvoid CHTMLContentControlBridge::SetReadOnly(bool bReadOnly)\n{\n\n}\n\nHWND CHTMLContentControlBridge::GetHwnd() const\n{\n\treturn static_cast<HWND>(m_wnd->Handle.ToPointer());\n}\n\nvoid CHTMLContentControlBridge::Release()\n{\n\t::DestroyWindow(GetHwnd());\n\tdelete this;\n}\n\nbool CHTMLContentControlBridge::ProcessMessage(MSG* pMsg)\n{\n\treturn false;\n}\n\nISpellCheck* CHTMLContentControlBridge::GetSpellCheckInterface()\n{\n\treturn nullptr;\n}\n\nbool CHTMLContentControlBridge::Undo()\n{\n\treturn false;\n}\n\nbool CHTMLContentControlBridge::Redo()\n{\n\treturn false;\n}\n\nvoid CHTMLContentControlBridge::SetUITheme(const UITHEME* pTheme)\n{\n\tmsclr::auto_gcroot<UITheme^> theme = gcnew UITheme(pTheme);\n\n\tm_wnd->SetUITheme(theme.get());\n}\n\nvoid CHTMLContentControlBridge::SavePreferences(IPreferences* pPrefs, LPCWSTR szKey) const\n{\n\n}\n\nvoid CHTMLContentControlBridge::LoadPreferences(const IPreferences* pPrefs, LPCWSTR szKey, bool bAppOnly)\n{\n\tmsclr::auto_gcroot<Preferences^> prefs = gcnew Preferences(pPrefs);\n\tmsclr::auto_gcroot<String^> key = gcnew String(szKey);\n\n\tm_wnd->LoadPreferences(prefs.get(), key.get(), bAppOnly);\n}\n<commit_msg>Implement conversion to html<commit_after>\/\/ ExporterBridge.cpp : Defines the exported functions for the DLL application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"HTMLContentControlBridge.h\"\n#include \"resource.h\"\n\n#include <unknwn.h>\n#include <tchar.h>\n#include <msclr\\auto_gcroot.h>\n\n#include \"..\\..\\..\\..\\ToDoList_Dev\\Interfaces\\ITransText.h\"\n#include \"..\\..\\..\\..\\ToDoList_Dev\\Interfaces\\UITheme.h\"\n#include \"..\\..\\..\\..\\ToDoList_Dev\\Interfaces\\IPreferences.h\"\n#include \"..\\..\\..\\..\\ToDoList_Dev\\Interfaces\\ISpellcheck.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#using <PluginHelpers.dll> as_friend\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace HTMLContentControl;\nusing namespace System;\nusing namespace System::Collections::Generic;\nusing namespace System::Runtime::InteropServices;\n\nusing namespace Abstractspoon::Tdl::PluginHelpers;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ REPLACE THIS WITH NEW GUID!\nconst LPCWSTR HTML_GUID = L\"FE0B6B6E-2B61-4AEB-AA0D-98DBE5942F02\";\nconst LPCWSTR HTML_NAME = L\"Html\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCHTMLContentBridge::CHTMLContentBridge() : m_hIcon(NULL)\n{\n HMODULE hMod = LoadLibrary(L\"HTMLContentControlBridge.dll\"); \/\/ us\n\n m_hIcon = ::LoadIcon(hMod, MAKEINTRESOURCE(IDI_HTML));\n}\n\nCHTMLContentBridge::~CHTMLContentBridge()\n{\n ::DestroyIcon(m_hIcon);\n}\n\nvoid CHTMLContentBridge::Release()\n{\n\tdelete this;\n}\n\nvoid CHTMLContentBridge::SetLocalizer(ITransText* \/*pTT*\/)\n{\n\t\/\/ TODO\n}\n\nLPCWSTR CHTMLContentBridge::GetTypeDescription() const\n{\n\treturn HTML_NAME;\n}\n\nHICON CHTMLContentBridge::GetTypeIcon() const\n{\n return m_hIcon;\n}\n\nLPCWSTR CHTMLContentBridge::GetTypeID() const\n{\n\treturn HTML_GUID;\n}\n\nIContentControl* CHTMLContentBridge::CreateCtrl(unsigned short nCtrlID, unsigned long nStyle, \n\tlong nLeft, long nTop, long nWidth, long nHeight, HWND hwndParent)\n{\n\tCHTMLContentControlBridge* pCtrl = new CHTMLContentControlBridge();\n\n\tif (!pCtrl->Create(nCtrlID, nStyle, nLeft, nTop, nWidth, nHeight, hwndParent))\n\t{\n\t\tpCtrl->Release();\n\t\tpCtrl = NULL;\n\t}\n\n\treturn pCtrl;\n}\n\nvoid CHTMLContentBridge::SavePreferences(IPreferences* pPrefs, LPCWSTR szKey) const\n{\n\t\/\/ TODO\n\n}\n\nvoid CHTMLContentBridge::LoadPreferences(const IPreferences* pPrefs, LPCWSTR szKey, bool bAppOnly)\n{\n\t\/\/ TODO\n}\n\n\/\/ returns the length of the html or zero if not supported\nint CHTMLContentBridge::ConvertToHtml(const unsigned char* pContent, int nLength,\n\tLPCWSTR szCharSet, LPWSTR& szHtml, LPCWSTR szImageDir)\n{\n\tif (nLength == 0)\n\t\treturn 0;\n\n\t\/\/ pContent is the body\n\tint nCharLen = ((nLength \/ 2) + 1);\n\tszHtml = new WCHAR[nCharLen];\n\n\tZeroMemory(szHtml, nCharLen * sizeof(WCHAR));\n\tCopyMemory(szHtml, pContent, nLength);\n\t\n\treturn nCharLen;\n}\n\nvoid CHTMLContentBridge::FreeHtmlBuffer(LPWSTR& szHtml)\n{\n\tdelete [] szHtml;\n\tszHtml = nullptr;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This is the constructor of a class that has been exported.\n\/\/ see ExporterBridge.h for the class definition\nCHTMLContentControlBridge::CHTMLContentControlBridge()\n{\n}\n\nBOOL CHTMLContentControlBridge::Create(UINT nCtrlID, DWORD nStyle, \n\tlong nLeft, long nTop, long nWidth, long nHeight, HWND hwndParent)\n{\n\tm_wnd = gcnew HTMLContentControl::HTMLContentControlCore(static_cast<IntPtr>(hwndParent));\n\n\tHWND hWnd = GetHwnd();\n\n\tif (hWnd)\n\t{\n\t\t::SetParent(hWnd, hwndParent);\n\t\t::SetWindowLong(hWnd, GWL_ID, nCtrlID);\n\t\t::SetWindowLong(hWnd, GWL_STYLE, nStyle);\n\t\t::MoveWindow(hWnd, nLeft, nTop, nWidth, nHeight, FALSE);\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nint CHTMLContentControlBridge::GetContent(unsigned char* pContent) const\n{\n\tcli::array<Byte>^ content = m_wnd->GetContent();\n\tint nLength = content->Length;\n\n\tif (pContent && nLength)\n\t{\n\t\tpin_ptr<Byte> ptrContent = &content[content->GetLowerBound(0)];\n\t\tCopyMemory(pContent, ptrContent, nLength);\n\t}\n\n\treturn nLength;\n}\n\nbool CHTMLContentControlBridge::SetContent(const unsigned char* pContent, int nLength, bool bResetSelection)\n{\n\tcli::array<Byte>^ content = gcnew cli::array<Byte>(nLength);\n\n\tfor (int i = 0; i < nLength; i++)\n\t\tcontent[i] = pContent[i];\n\n\treturn m_wnd->SetContent(content, bResetSelection);\n}\n\nLPCWSTR CHTMLContentControlBridge::GetTypeID() const\n{\n\treturn HTML_GUID;\n}\n\n\/\/ text content if supported. return false if not supported\nint CHTMLContentControlBridge::GetTextContent(LPWSTR szContent, int nLength) const\n{\n\tString^ content = m_wnd->GetTextContent();\n\tnLength = content->Length;\n\n\tif (szContent != nullptr)\n\t{\n\t\tAbstractspoon::Tdl::PluginHelpers::MarshalledString msContent(content);\n\t\tCopyMemory(szContent, msContent, (nLength * sizeof(WCHAR)));\n\t}\n\n\treturn nLength;\n}\n\nbool CHTMLContentControlBridge::SetTextContent(LPCWSTR szContent, bool bResetSelection)\n{\n\tmsclr::auto_gcroot<String^> content = gcnew String(szContent);\n\n\treturn m_wnd->SetTextContent(content, bResetSelection);\n}\n\nvoid CHTMLContentControlBridge::SetReadOnly(bool bReadOnly)\n{\n\n}\n\nHWND CHTMLContentControlBridge::GetHwnd() const\n{\n\treturn static_cast<HWND>(m_wnd->Handle.ToPointer());\n}\n\nvoid CHTMLContentControlBridge::Release()\n{\n\t::DestroyWindow(GetHwnd());\n\tdelete this;\n}\n\nbool CHTMLContentControlBridge::ProcessMessage(MSG* pMsg)\n{\n\treturn false;\n}\n\nISpellCheck* CHTMLContentControlBridge::GetSpellCheckInterface()\n{\n\treturn nullptr;\n}\n\nbool CHTMLContentControlBridge::Undo()\n{\n\treturn false;\n}\n\nbool CHTMLContentControlBridge::Redo()\n{\n\treturn false;\n}\n\nvoid CHTMLContentControlBridge::SetUITheme(const UITHEME* pTheme)\n{\n\tmsclr::auto_gcroot<UITheme^> theme = gcnew UITheme(pTheme);\n\n\tm_wnd->SetUITheme(theme.get());\n}\n\nvoid CHTMLContentControlBridge::SavePreferences(IPreferences* pPrefs, LPCWSTR szKey) const\n{\n\n}\n\nvoid CHTMLContentControlBridge::LoadPreferences(const IPreferences* pPrefs, LPCWSTR szKey, bool bAppOnly)\n{\n\tmsclr::auto_gcroot<Preferences^> prefs = gcnew Preferences(pPrefs);\n\tmsclr::auto_gcroot<String^> key = gcnew String(szKey);\n\n\tm_wnd->LoadPreferences(prefs.get(), key.get(), bAppOnly);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: load32bitOShack.cc,v 1.8 2002\/04\/18 00:22:19 bdenney Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\n#include \"bochs.h\"\n#define LOG_THIS genlog->\n\n\n\nstatic void bx_load_linux_hack(void);\nstatic void bx_load_null_kernel_hack(void);\nstatic Bit32u bx_load_kernel_image(char *path, Bit32u paddr);\n\n void\nbx_load32bitOSimagehack(void)\n{\n \/\/ Replay IO from log to initialize IO devices to\n \/\/ a reasonable state needed for the OS. This is done\n \/\/ in lieu of running the 16-bit BIOS to init things,\n \/\/ since we want to test straight 32bit stuff for\n \/\/ freemware.\n\n FILE *fp;\n\n fp = fopen(bx_options.load32bitOSImage.Oiolog->getptr (), \"r\");\n\n if (fp == NULL) {\n BX_PANIC((\"could not open IO init file.\"));\n }\n\n while (1) {\n unsigned len, op, port, val;\n int ret;\n ret = fscanf(fp, \"%u %u %x %x\\n\",\n &len, &op, &port, &val);\n if (ret != 4) {\n BX_PANIC((\"could not open IO init file.\"));\n }\n if (op == 0) {\n \/\/ read\n (void) bx_devices.inp(port, len);\n }\n else if (op == 1) {\n \/\/ write\n bx_devices.outp(port, val, len);\n }\n else {\n BX_PANIC((\"bad IO op in init filen\"));\n }\n if (feof(fp)) break;\n }\n\n \/\/ Invoke proper hack depending on which OS image we're loading\n switch (bx_options.load32bitOSImage.OwhichOS->get ()) {\n case Load32bitOSLinux:\n bx_load_linux_hack();\n break;\n case Load32bitOSNullKernel:\n bx_load_null_kernel_hack();\n break;\n default:\n BX_PANIC((\"load32bitOSImage: OS not recognized\"));\n }\n}\n\nstruct gdt_entry\n{\n Bit32u low;\n Bit32u high;\n};\nstruct linux_setup_params\n{\n \/* 0x000 *\/ Bit8u orig_x;\n \/* 0x001 *\/ Bit8u orig_y;\n \/* 0x002 *\/ Bit16u memory_size_std;\n \/* 0x004 *\/ Bit16u orig_video_page;\n \/* 0x006 *\/ Bit8u orig_video_mode;\n \/* 0x007 *\/ Bit8u orig_video_cols;\n \/* 0x008 *\/ Bit16u unused1;\n \/* 0x00a *\/ Bit16u orig_video_ega_bx;\n \/* 0x00c *\/ Bit16u unused2;\n \/* 0x00e *\/ Bit8u orig_video_lines;\n \/* 0x00f *\/ Bit8u orig_video_isVGA;\n \/* 0x010 *\/ Bit16u orig_video_points;\n \/* 0x012 *\/ Bit8u pad1[0x40 - 0x12];\n \/* 0x040 *\/ Bit8u apm_info[0x80 - 0x40];\n \/* 0x080 *\/ Bit8u hd0_info[16];\n \/* 0x090 *\/ Bit8u hd1_info[16];\n \/* 0x0a0 *\/ Bit8u pad2[0x1e0 - 0xa0];\n \/* 0x1e0 *\/ Bit32u memory_size_ext;\n \/* 0x1e4 *\/ Bit8u pad3[0x1f1 - 0x1e4];\n \/* 0x1f1 *\/ Bit8u setup_sects;\n \/* 0x1f2 *\/ Bit16u mount_root_rdonly;\n \/* 0x1f4 *\/ Bit16u sys_size;\n \/* 0x1f6 *\/ Bit16u swap_dev;\n \/* 0x1f8 *\/ Bit16u ramdisk_flags;\n \/* 0x1fa *\/ Bit16u vga_mode;\n \/* 0x1fc *\/ Bit16u orig_root_dev;\n \/* 0x1fe *\/ Bit16u bootsect_magic;\n \/* 0x200 *\/ Bit8u pad4[0x210 - 0x200];\n \/* 0x210 *\/ Bit32u loader_type;\n \/* 0x214 *\/ Bit32u kernel_start;\n \/* 0x218 *\/ Bit32u initrd_start;\n \/* 0x21c *\/ Bit32u initrd_size;\n \/* 0x220 *\/ Bit8u pad5[0x400 - 0x220];\n \/* 0x400 *\/ struct gdt_entry gdt[128];\n \/* 0x800 *\/ Bit8u commandline[2048];\n};\n\n static void\nbx_load_linux_setup_params( Bit32u initrd_start, Bit32u initrd_size )\n{\n BX_MEM_C *mem = BX_MEM(0);\n struct linux_setup_params *params =\n (struct linux_setup_params *) &mem->vector[0x00090000];\n\n memset( params, '\\0', sizeof(*params) );\n\n \/* Video settings (standard VGA) *\/\n params->orig_x = 0;\n params->orig_y = 0;\n params->orig_video_page = 0;\n params->orig_video_mode = 3;\n params->orig_video_cols = 80;\n params->orig_video_lines = 25;\n params->orig_video_points = 16;\n params->orig_video_isVGA = 1;\n params->orig_video_ega_bx = 3;\n\n \/* Memory size (total mem - 1MB, in KB) *\/\n params->memory_size_ext = (mem->megabytes - 1) * 1024;\n\n \/* Boot parameters *\/\n params->loader_type = 1;\n params->bootsect_magic = 0xaa55;\n params->mount_root_rdonly = 0;\n params->orig_root_dev = 0x0100;\n params->initrd_start = initrd_start;\n params->initrd_size = initrd_size;\n\n \/* Initial GDT *\/\n params->gdt[2].high = 0x00cf9a00;\n params->gdt[2].low = 0x0000ffff;\n params->gdt[3].high = 0x00cf9200;\n params->gdt[3].low = 0x0000ffff;\n}\n\n void\nbx_load_linux_hack(void)\n{\n Bit32u initrd_start = 0, initrd_size = 0;\n\n \/\/ The RESET function will have been called first.\n \/\/ Set CPU and memory features which are assumed at this point.\n\n \/\/ Load Linux kernel image\n bx_load_kernel_image( bx_options.load32bitOSImage.Opath->getptr (), 0x100000 );\n\n \/\/ Load initial ramdisk image if requested\n if ( bx_options.load32bitOSImage.Oinitrd->getptr () )\n {\n initrd_start = 0x00800000; \/* FIXME: load at top of memory *\/\n initrd_size = bx_load_kernel_image( bx_options.load32bitOSImage.Oinitrd->getptr (), initrd_start );\n }\n\n \/\/ Setup Linux startup parameters buffer\n bx_load_linux_setup_params( initrd_start, initrd_size );\n\n \/\/ Enable A20 line\n BX_SET_ENABLE_A20( 1 );\n\n \/\/ Setup PICs the way Linux likes it\n BX_OUTP( 0x20, 0x11, 1 );\n BX_OUTP( 0xA0, 0x11, 1 );\n BX_OUTP( 0x21, 0x20, 1 );\n BX_OUTP( 0xA1, 0x28, 1 );\n BX_OUTP( 0x21, 0x04, 1 );\n BX_OUTP( 0xA1, 0x02, 1 );\n BX_OUTP( 0x21, 0x01, 1 );\n BX_OUTP( 0xA1, 0x01, 1 );\n BX_OUTP( 0x21, 0xFF, 1 );\n BX_OUTP( 0xA1, 0xFB, 1 );\n\n \/\/ Disable interrupts and NMIs\n BX_CPU(0)->eflags.if_ = 0;\n BX_OUTP( 0x70, 0x80, 1 );\n\n \/\/ Enter protected mode\n BX_CPU(0)->cr0.pe = 1;\n BX_CPU(0)->cr0.val32 |= 0x01;\n\n \/\/ Set up initial GDT\n BX_CPU(0)->gdtr.limit = 0x400;\n BX_CPU(0)->gdtr.base = 0x00090400;\n\n \/\/ Jump to protected mode entry point\n BX_CPU(0)->jump_protected( NULL, 0x10, 0x00100000 );\n}\n\n void\nbx_load_null_kernel_hack(void)\n{\n \/\/ The RESET function will have been called first.\n \/\/ Set CPU and memory features which are assumed at this point.\n\n bx_load_kernel_image(bx_options.load32bitOSImage.Opath->getptr (), 0x100000);\n\n \/\/ EIP deltas\n BX_CPU(0)->prev_eip =\n BX_CPU(0)->eip = 0x00100000;\n\n \/\/ CS deltas\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.base = 0x00000000;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit = 0xFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit_scaled = 0xFFFFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.g = 1; \/\/ page gran\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.d_b = 1; \/\/ 32bit\n\n \/\/ DS deltas\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.base = 0x00000000;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit = 0xFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit_scaled = 0xFFFFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.g = 1; \/\/ page gran\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.d_b = 1; \/\/ 32bit\n\n \/\/ CR0 deltas\n BX_CPU(0)->cr0.pe = 1; \/\/ protected mode\n}\n\n Bit32u\nbx_load_kernel_image(char *path, Bit32u paddr)\n{\n struct stat stat_buf;\n int fd, ret;\n unsigned long size, offset;\n Bit32u page_size;\n\n \/\/ read in ROM BIOS image file\n fd = open(path, O_RDONLY\n#ifdef O_BINARY\n | O_BINARY\n#endif\n );\n if (fd < 0) {\n BX_INFO(( \"load_kernel_image: couldn't open image file '%s'.\", path ));\n BX_EXIT(1);\n }\n ret = fstat(fd, &stat_buf);\n if (ret) {\n BX_INFO(( \"load_kernel_image: couldn't stat image file '%s'.\", path ));\n BX_EXIT(1);\n }\n\n size = stat_buf.st_size;\n page_size = ((Bit32u)size + 0xfff) & ~0xfff;\n\n BX_MEM_C *mem = BX_MEM(0);\n if ( (paddr + size) > mem->len ) {\n BX_INFO(( \"load_kernel_image: address range > physical memsize!\" ));\n BX_EXIT(1);\n }\n\n offset = 0;\n while (size > 0) {\n ret = read(fd, (bx_ptr_t) &mem->vector[paddr + offset], size);\n if (ret <= 0) {\n BX_INFO(( \"load_kernel_image: read failed on image\" ));\n BX_EXIT(1);\n }\n size -= ret;\n offset += ret;\n }\n close(fd);\n BX_INFO(( \"#(%u) load_kernel_image: '%s', size=%u read into memory at %08x\",\n BX_SIM_ID, path,\n (unsigned) stat_buf.st_size,\n (unsigned) paddr ));\n\n return page_size;\n}\n<commit_msg>- use eflags accessor instead of using field directly<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: load32bitOShack.cc,v 1.9 2002\/09\/11 03:56:22 bdenney Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\n#include \"bochs.h\"\n#define LOG_THIS genlog->\n\n\n\nstatic void bx_load_linux_hack(void);\nstatic void bx_load_null_kernel_hack(void);\nstatic Bit32u bx_load_kernel_image(char *path, Bit32u paddr);\n\n void\nbx_load32bitOSimagehack(void)\n{\n \/\/ Replay IO from log to initialize IO devices to\n \/\/ a reasonable state needed for the OS. This is done\n \/\/ in lieu of running the 16-bit BIOS to init things,\n \/\/ since we want to test straight 32bit stuff for\n \/\/ freemware.\n\n FILE *fp;\n\n fp = fopen(bx_options.load32bitOSImage.Oiolog->getptr (), \"r\");\n\n if (fp == NULL) {\n BX_PANIC((\"could not open IO init file.\"));\n }\n\n while (1) {\n unsigned len, op, port, val;\n int ret;\n ret = fscanf(fp, \"%u %u %x %x\\n\",\n &len, &op, &port, &val);\n if (ret != 4) {\n BX_PANIC((\"could not open IO init file.\"));\n }\n if (op == 0) {\n \/\/ read\n (void) bx_devices.inp(port, len);\n }\n else if (op == 1) {\n \/\/ write\n bx_devices.outp(port, val, len);\n }\n else {\n BX_PANIC((\"bad IO op in init filen\"));\n }\n if (feof(fp)) break;\n }\n\n \/\/ Invoke proper hack depending on which OS image we're loading\n switch (bx_options.load32bitOSImage.OwhichOS->get ()) {\n case Load32bitOSLinux:\n bx_load_linux_hack();\n break;\n case Load32bitOSNullKernel:\n bx_load_null_kernel_hack();\n break;\n default:\n BX_PANIC((\"load32bitOSImage: OS not recognized\"));\n }\n}\n\nstruct gdt_entry\n{\n Bit32u low;\n Bit32u high;\n};\nstruct linux_setup_params\n{\n \/* 0x000 *\/ Bit8u orig_x;\n \/* 0x001 *\/ Bit8u orig_y;\n \/* 0x002 *\/ Bit16u memory_size_std;\n \/* 0x004 *\/ Bit16u orig_video_page;\n \/* 0x006 *\/ Bit8u orig_video_mode;\n \/* 0x007 *\/ Bit8u orig_video_cols;\n \/* 0x008 *\/ Bit16u unused1;\n \/* 0x00a *\/ Bit16u orig_video_ega_bx;\n \/* 0x00c *\/ Bit16u unused2;\n \/* 0x00e *\/ Bit8u orig_video_lines;\n \/* 0x00f *\/ Bit8u orig_video_isVGA;\n \/* 0x010 *\/ Bit16u orig_video_points;\n \/* 0x012 *\/ Bit8u pad1[0x40 - 0x12];\n \/* 0x040 *\/ Bit8u apm_info[0x80 - 0x40];\n \/* 0x080 *\/ Bit8u hd0_info[16];\n \/* 0x090 *\/ Bit8u hd1_info[16];\n \/* 0x0a0 *\/ Bit8u pad2[0x1e0 - 0xa0];\n \/* 0x1e0 *\/ Bit32u memory_size_ext;\n \/* 0x1e4 *\/ Bit8u pad3[0x1f1 - 0x1e4];\n \/* 0x1f1 *\/ Bit8u setup_sects;\n \/* 0x1f2 *\/ Bit16u mount_root_rdonly;\n \/* 0x1f4 *\/ Bit16u sys_size;\n \/* 0x1f6 *\/ Bit16u swap_dev;\n \/* 0x1f8 *\/ Bit16u ramdisk_flags;\n \/* 0x1fa *\/ Bit16u vga_mode;\n \/* 0x1fc *\/ Bit16u orig_root_dev;\n \/* 0x1fe *\/ Bit16u bootsect_magic;\n \/* 0x200 *\/ Bit8u pad4[0x210 - 0x200];\n \/* 0x210 *\/ Bit32u loader_type;\n \/* 0x214 *\/ Bit32u kernel_start;\n \/* 0x218 *\/ Bit32u initrd_start;\n \/* 0x21c *\/ Bit32u initrd_size;\n \/* 0x220 *\/ Bit8u pad5[0x400 - 0x220];\n \/* 0x400 *\/ struct gdt_entry gdt[128];\n \/* 0x800 *\/ Bit8u commandline[2048];\n};\n\n static void\nbx_load_linux_setup_params( Bit32u initrd_start, Bit32u initrd_size )\n{\n BX_MEM_C *mem = BX_MEM(0);\n struct linux_setup_params *params =\n (struct linux_setup_params *) &mem->vector[0x00090000];\n\n memset( params, '\\0', sizeof(*params) );\n\n \/* Video settings (standard VGA) *\/\n params->orig_x = 0;\n params->orig_y = 0;\n params->orig_video_page = 0;\n params->orig_video_mode = 3;\n params->orig_video_cols = 80;\n params->orig_video_lines = 25;\n params->orig_video_points = 16;\n params->orig_video_isVGA = 1;\n params->orig_video_ega_bx = 3;\n\n \/* Memory size (total mem - 1MB, in KB) *\/\n params->memory_size_ext = (mem->megabytes - 1) * 1024;\n\n \/* Boot parameters *\/\n params->loader_type = 1;\n params->bootsect_magic = 0xaa55;\n params->mount_root_rdonly = 0;\n params->orig_root_dev = 0x0100;\n params->initrd_start = initrd_start;\n params->initrd_size = initrd_size;\n\n \/* Initial GDT *\/\n params->gdt[2].high = 0x00cf9a00;\n params->gdt[2].low = 0x0000ffff;\n params->gdt[3].high = 0x00cf9200;\n params->gdt[3].low = 0x0000ffff;\n}\n\n void\nbx_load_linux_hack(void)\n{\n Bit32u initrd_start = 0, initrd_size = 0;\n\n \/\/ The RESET function will have been called first.\n \/\/ Set CPU and memory features which are assumed at this point.\n\n \/\/ Load Linux kernel image\n bx_load_kernel_image( bx_options.load32bitOSImage.Opath->getptr (), 0x100000 );\n\n \/\/ Load initial ramdisk image if requested\n if ( bx_options.load32bitOSImage.Oinitrd->getptr () )\n {\n initrd_start = 0x00800000; \/* FIXME: load at top of memory *\/\n initrd_size = bx_load_kernel_image( bx_options.load32bitOSImage.Oinitrd->getptr (), initrd_start );\n }\n\n \/\/ Setup Linux startup parameters buffer\n bx_load_linux_setup_params( initrd_start, initrd_size );\n\n \/\/ Enable A20 line\n BX_SET_ENABLE_A20( 1 );\n\n \/\/ Setup PICs the way Linux likes it\n BX_OUTP( 0x20, 0x11, 1 );\n BX_OUTP( 0xA0, 0x11, 1 );\n BX_OUTP( 0x21, 0x20, 1 );\n BX_OUTP( 0xA1, 0x28, 1 );\n BX_OUTP( 0x21, 0x04, 1 );\n BX_OUTP( 0xA1, 0x02, 1 );\n BX_OUTP( 0x21, 0x01, 1 );\n BX_OUTP( 0xA1, 0x01, 1 );\n BX_OUTP( 0x21, 0xFF, 1 );\n BX_OUTP( 0xA1, 0xFB, 1 );\n\n \/\/ Disable interrupts and NMIs\n BX_CPU(0)->eflags.clear_IF ();\n BX_OUTP( 0x70, 0x80, 1 );\n\n \/\/ Enter protected mode\n BX_CPU(0)->cr0.pe = 1;\n BX_CPU(0)->cr0.val32 |= 0x01;\n\n \/\/ Set up initial GDT\n BX_CPU(0)->gdtr.limit = 0x400;\n BX_CPU(0)->gdtr.base = 0x00090400;\n\n \/\/ Jump to protected mode entry point\n BX_CPU(0)->jump_protected( NULL, 0x10, 0x00100000 );\n}\n\n void\nbx_load_null_kernel_hack(void)\n{\n \/\/ The RESET function will have been called first.\n \/\/ Set CPU and memory features which are assumed at this point.\n\n bx_load_kernel_image(bx_options.load32bitOSImage.Opath->getptr (), 0x100000);\n\n \/\/ EIP deltas\n BX_CPU(0)->prev_eip =\n BX_CPU(0)->eip = 0x00100000;\n\n \/\/ CS deltas\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.base = 0x00000000;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit = 0xFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit_scaled = 0xFFFFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.g = 1; \/\/ page gran\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.d_b = 1; \/\/ 32bit\n\n \/\/ DS deltas\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.base = 0x00000000;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit = 0xFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit_scaled = 0xFFFFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.g = 1; \/\/ page gran\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.d_b = 1; \/\/ 32bit\n\n \/\/ CR0 deltas\n BX_CPU(0)->cr0.pe = 1; \/\/ protected mode\n}\n\n Bit32u\nbx_load_kernel_image(char *path, Bit32u paddr)\n{\n struct stat stat_buf;\n int fd, ret;\n unsigned long size, offset;\n Bit32u page_size;\n\n \/\/ read in ROM BIOS image file\n fd = open(path, O_RDONLY\n#ifdef O_BINARY\n | O_BINARY\n#endif\n );\n if (fd < 0) {\n BX_INFO(( \"load_kernel_image: couldn't open image file '%s'.\", path ));\n BX_EXIT(1);\n }\n ret = fstat(fd, &stat_buf);\n if (ret) {\n BX_INFO(( \"load_kernel_image: couldn't stat image file '%s'.\", path ));\n BX_EXIT(1);\n }\n\n size = stat_buf.st_size;\n page_size = ((Bit32u)size + 0xfff) & ~0xfff;\n\n BX_MEM_C *mem = BX_MEM(0);\n if ( (paddr + size) > mem->len ) {\n BX_INFO(( \"load_kernel_image: address range > physical memsize!\" ));\n BX_EXIT(1);\n }\n\n offset = 0;\n while (size > 0) {\n ret = read(fd, (bx_ptr_t) &mem->vector[paddr + offset], size);\n if (ret <= 0) {\n BX_INFO(( \"load_kernel_image: read failed on image\" ));\n BX_EXIT(1);\n }\n size -= ret;\n offset += ret;\n }\n close(fd);\n BX_INFO(( \"#(%u) load_kernel_image: '%s', size=%u read into memory at %08x\",\n BX_SIM_ID, path,\n (unsigned) stat_buf.st_size,\n (unsigned) paddr ));\n\n return page_size;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n\n#include \"sequence.h\"\n\nnamespace relative\n{\n\n\/\/------------------------------------------------------------------------------\n\nSequence::Sequence()\n{\n this->sigma = 0;\n}\n\nSequence::Sequence(int_vector_buffer<8>& buffer, uint64_t _size, uint64_t _sigma)\n{\n this->sigma = _sigma;\n if(this->sigma > 0) { this->data.width(bitlength(this->sigma - 1)); }\n else { this->data.width(8); }\n this->data.resize(_size);\n for(uint64_t i = 0; i < this->size(); i++) { this->data[i] = buffer[i]; }\n\n if(this->sigma == 0)\n {\n util::bit_compress(this->data);\n this->sigma = *std::max_element(this->data.begin(), this->data.end()) + 1;\n }\n\n this->buildRank();\n}\n\nSequence::Sequence(const Sequence& s)\n{\n this->copy(s);\n}\n\nSequence::Sequence(Sequence&& s)\n{\n *this = std::move(s);\n}\n\nSequence::~Sequence()\n{\n}\n\nvoid\nSequence::copy(const Sequence& s)\n{\n this->data = s.data;\n this->samples = s.samples;\n this->sigma = s.sigma;\n}\n\nvoid\nSequence::swap(Sequence& s)\n{\n if(this != &s)\n {\n this->data.swap(s.data);\n this->samples.swap(s.samples);\n std::swap(this->sigma, s.sigma);\n }\n}\n\nSequence&\nSequence::operator=(const Sequence& s)\n{\n if(this != &s) { this->copy(s); }\n return *this;\n}\n\nSequence&\nSequence::operator=(Sequence&& s)\n{\n if(this != &s)\n {\n this->data = std::move(s.data);\n this->samples = std::move(s.samples);\n this->sigma = s.sigma;\n }\n return *this;\n}\n\nuint64_t\nSequence::serialize(std::ostream& out, structure_tree_node* s, std::string name) const\n{\n structure_tree_node* child = structure_tree::add_child(s, name, util::class_name(*this));\n uint64_t written_bytes = 0;\n written_bytes += this->data.serialize(out, child, \"data\");\n written_bytes += this->samples.serialize(out, child, \"samples\");\n written_bytes += write_member(this->sigma, out, child, \"sigma\");\n structure_tree::add_size(child, written_bytes);\n return written_bytes;\n}\n\nvoid\nSequence::load(std::istream& in)\n{\n this->data.load(in);\n this->samples.load(in);\n read_member(this->sigma, in);\n}\n\nvoid\nSequence::buildRank()\n{\n uint64_t blocks = (this->size() + SAMPLE_RATE - 1) \/ SAMPLE_RATE;\n int_vector<0> temp((blocks + 1) * this->sigma, 0, bitlength(this->size()));\n for(uint64_t block = 0; block < blocks; block++)\n {\n for(uint64_t c = 0; c < this->sigma; c++) { temp[(block + 1) * this->sigma + c] = temp[block * this->sigma + c]; }\n uint64_t limit = std::min(this->size(), (block + 1) * SAMPLE_RATE);\n for(uint64_t i = block * SAMPLE_RATE; i < limit; i++) { temp[(block + 1) * this->sigma + this->data[i]]++; }\n }\n util::bit_compress(temp); this->samples.swap(temp);\n}\n\n\/\/------------------------------------------------------------------------------\n\nRLSequence::RLSequence()\n{\n}\n\ninline void\naddBasicRun(uint64_t c, uint64_t run, std::vector<uint8_t>& runs)\n{\n runs.push_back(c + RLSequence::SIGMA * (run - 1));\n}\n\nvoid\naddRun(uint64_t c, uint64_t run, std::vector<uint8_t>& runs)\n{\n while(run > 0)\n {\n \/\/ Runs of length <= 41 are encoded in a single byte.\n if(run < RLSequence::MAX_RUN)\n {\n addBasicRun(c, run, runs);\n return;\n }\n\n uint64_t bytes_remaining = RLSequence::SAMPLE_RATE - (runs.size() % RLSequence::SAMPLE_RATE);\n uint64_t l = (bytes_remaining < 2 ? RLSequence::MAX_RUN - 1 : RLSequence::MAX_RUN);\n addBasicRun(c, l, runs); run -= l;\n if(bytes_remaining < 2) { continue; } \/\/ No room for the additional run length in the current block.\n bytes_remaining--;\n\n \/\/ Write the rest of the run with 7 bits\/byte, least significant byte first.\n if(bitlength(run) > 7 * bytes_remaining) \/\/ Cannot encode the entire run in current block.\n {\n uint64_t temp = 0;\n for(uint64_t i = 1; i < bytes_remaining; i++) { runs.push_back(0xFF); temp = (temp << 7) | 0x7F; }\n runs.push_back(0x7F); run -= (temp << 7) | 0x7F;\n }\n else\n {\n do\n {\n uint8_t val = run & 0x7F; run >>= 7;\n if(run > 0) { val |= 0x80; }\n runs.push_back(val);\n }\n while(run > 0);\n }\n }\n}\n\nRLSequence::RLSequence(int_vector_buffer<8>& buffer, uint64_t _size)\n{\n \/\/ Process the input.\n uint64_t c = 0, run = 0;\n for(uint64_t i = 0; i < _size; i++)\n {\n if(buffer[i] == c) { run++; }\n else\n {\n addRun(c, run, this->data);\n c = buffer[i]; run = 1;\n }\n }\n addRun(c, run, this->data);\n\n \/\/ Blocks and samples.\n this->buildRank();\n}\n\nRLSequence::RLSequence(const RLSequence& s)\n{\n this->copy(s);\n}\n\nRLSequence::RLSequence(RLSequence&& s)\n{\n *this = std::move(s);\n}\n\nRLSequence::~RLSequence()\n{\n}\n\nvoid\nRLSequence::copy(const RLSequence& s)\n{\n this->data = s.data;\n for(uint64_t c = 0; c < SIGMA; c++) { this->samples[c] = s.samples[c]; }\n this->block_boundaries = s.block_boundaries;\n util::init_support(this->block_rank, &(this->block_boundaries));\n util::init_support(this->block_select, &(this->block_boundaries));\n}\n\nvoid\nRLSequence::swap(RLSequence& s)\n{\n if(this != &s)\n {\n this->data.swap(s.data);\n for(uint64_t c = 0; c < SIGMA; c++) { this->samples[c].swap(s.samples[c]); }\n this->block_boundaries.swap(s.block_boundaries);\n util::swap_support(this->block_rank, s.block_rank, &(this->block_boundaries), &(s.block_boundaries));\n util::swap_support(this->block_select, s.block_select, &(this->block_boundaries), &(s.block_boundaries));\n }\n}\n\nRLSequence&\nRLSequence::operator=(const RLSequence& s)\n{\n if(this != &s) { this->copy(s); }\n return *this;\n}\n\nRLSequence&\nRLSequence::operator=(RLSequence&& s)\n{\n if(this != &s)\n {\n this->data = std::move(s.data);\n for(uint64_t c = 0; c < SIGMA; c++) { this->samples[c] = std::move(s.samples[c]); }\n this->block_boundaries = std::move(s.block_boundaries);\n util::init_support(this->block_rank, &(this->block_boundaries));\n util::init_support(this->block_select, &(this->block_boundaries));\n }\n return *this;\n}\n\nuint64_t\nRLSequence::serialize(std::ostream& out, structure_tree_node* s, std::string name) const\n{\n structure_tree_node* child = structure_tree::add_child(s, name, util::class_name(*this));\n uint64_t written_bytes = 0;\n written_bytes += write_vector(this->data, out, child, \"data\");\n for(uint64_t c = 0; c < SIGMA; c++)\n {\n std::stringstream ss; ss << \"samples_\" << c;\n written_bytes += this->samples[c].serialize(out, child, ss.str());\n }\n written_bytes += this->block_boundaries.serialize(out, child, \"block_boundaries\");\n written_bytes += this->block_rank.serialize(out, child, \"block_rank\");\n written_bytes += this->block_select.serialize(out, child, \"block_select\");\n structure_tree::add_size(child, written_bytes);\n return written_bytes;\n}\n\nvoid\nRLSequence::load(std::istream& in, bool rebuild_samples)\n{\n read_vector(this->data, in);\n if(rebuild_samples)\n {\n this->buildRank();\n }\n else\n {\n for(uint64_t c = 0; c < SIGMA; c++) { this->samples[c].load(in); }\n this->block_boundaries.load(in);\n this->block_rank.load(in, &(this->block_boundaries));\n this->block_select.load(in, &(this->block_boundaries));\n }\n}\n\nvoid\nRLSequence::buildRank()\n{\n std::vector<uint64_t> block_ends;\n uint64_t seq_pos = 0, rle_pos = 0;\n while(rle_pos < this->runs())\n {\n range_type run = this->readRun(rle_pos); seq_pos += run.second;\n if(rle_pos >= this->runs() || rle_pos % SAMPLE_RATE == 0) { block_ends.push_back(seq_pos - 1); }\n }\n\n \/\/ Block boundaries.\n uint64_t blocks = block_ends.size();\n {\n sd_vector<> temp(block_ends.begin(), block_ends.end());\n util::clear(block_ends);\n this->block_boundaries.swap(temp);\n util::init_support(this->block_rank, &(this->block_boundaries));\n util::init_support(this->block_select, &(this->block_boundaries));\n }\n\n \/\/ Samples. SIGMA passes vs. higher space usage? Multi-threaded?\n for(uint64_t c = 0; c < SIGMA; c++)\n {\n int_vector<0> temp(blocks, 0, bitlength(this->size()));\n for(uint64_t block = 0; block < blocks; block++)\n {\n uint64_t rle_pos = block * SAMPLE_RATE, limit = std::min(this->runs(), (block + 1) * SAMPLE_RATE);\n while(rle_pos < limit)\n {\n range_type run = this->readRun(rle_pos);\n if(run.first == c) { temp[block] += run.second; }\n }\n }\n util::assign(this->samples[c], CumulativeArray(temp, temp.size()));\n }\n}\n\nuint64_t\nRLSequence::hash(const Alphabet& alpha) const\n{\n uint64_t rle_pos = 0, val = FNV_OFFSET_BASIS;\n while(rle_pos < this->runs())\n {\n range_type run = this->readRun(rle_pos); run.first = alpha.comp2char[run.first];\n for(uint64_t i = 0; i < run.second; i++) { val = fnv1a_hash(run.first, val); }\n }\n return val;\n}\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<>\nSimpleFM<RLSequence>::SimpleFM(const std::string& base_name, LoadMode mode)\n{\n this->sample_rate = 0;\n\n if(mode == mode_native || mode == mode_ropebwt2)\n {\n std::string filename = base_name + NATIVE_BWT_EXTENSION;\n std::ifstream in(filename.c_str(), std::ios_base::binary);\n if(!in)\n {\n std::cerr << \"SimpleFM::SimpleFM(): Cannot open BWT file \" << filename << \" (native format)\" << std::endl;\n return;\n }\n this->bwt.load(in, mode == mode_ropebwt2); in.close();\n }\n else\n {\n int_vector_buffer<8> buffer(base_name + BWT_EXTENSION);\n RLSequence temp(buffer, buffer.size());\n this->bwt.swap(temp);\n }\n\n this->loadAlphabet(base_name);\n this->loadSamples(base_name);\n}\n\ntemplate<>\nvoid\ncharacterCounts(const RLSequence& sequence, uint64_t size, int_vector<64>& counts)\n{\n for(uint64_t c = 0; c < counts.size(); c++) { counts[c] = 0; }\n\n uint64_t rle_pos = 0;\n while(rle_pos < sequence.runs())\n {\n range_type run = sequence.readRun(rle_pos);\n counts[run.first] += run.second;\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\n} \/\/ namespace relative\n<commit_msg>Fixed the RLSequence::hash(). Now it uses the right hash function.<commit_after>#include <sstream>\n\n#include \"sequence.h\"\n\nnamespace relative\n{\n\n\/\/------------------------------------------------------------------------------\n\nSequence::Sequence()\n{\n this->sigma = 0;\n}\n\nSequence::Sequence(int_vector_buffer<8>& buffer, uint64_t _size, uint64_t _sigma)\n{\n this->sigma = _sigma;\n if(this->sigma > 0) { this->data.width(bitlength(this->sigma - 1)); }\n else { this->data.width(8); }\n this->data.resize(_size);\n for(uint64_t i = 0; i < this->size(); i++) { this->data[i] = buffer[i]; }\n\n if(this->sigma == 0)\n {\n util::bit_compress(this->data);\n this->sigma = *std::max_element(this->data.begin(), this->data.end()) + 1;\n }\n\n this->buildRank();\n}\n\nSequence::Sequence(const Sequence& s)\n{\n this->copy(s);\n}\n\nSequence::Sequence(Sequence&& s)\n{\n *this = std::move(s);\n}\n\nSequence::~Sequence()\n{\n}\n\nvoid\nSequence::copy(const Sequence& s)\n{\n this->data = s.data;\n this->samples = s.samples;\n this->sigma = s.sigma;\n}\n\nvoid\nSequence::swap(Sequence& s)\n{\n if(this != &s)\n {\n this->data.swap(s.data);\n this->samples.swap(s.samples);\n std::swap(this->sigma, s.sigma);\n }\n}\n\nSequence&\nSequence::operator=(const Sequence& s)\n{\n if(this != &s) { this->copy(s); }\n return *this;\n}\n\nSequence&\nSequence::operator=(Sequence&& s)\n{\n if(this != &s)\n {\n this->data = std::move(s.data);\n this->samples = std::move(s.samples);\n this->sigma = s.sigma;\n }\n return *this;\n}\n\nuint64_t\nSequence::serialize(std::ostream& out, structure_tree_node* s, std::string name) const\n{\n structure_tree_node* child = structure_tree::add_child(s, name, util::class_name(*this));\n uint64_t written_bytes = 0;\n written_bytes += this->data.serialize(out, child, \"data\");\n written_bytes += this->samples.serialize(out, child, \"samples\");\n written_bytes += write_member(this->sigma, out, child, \"sigma\");\n structure_tree::add_size(child, written_bytes);\n return written_bytes;\n}\n\nvoid\nSequence::load(std::istream& in)\n{\n this->data.load(in);\n this->samples.load(in);\n read_member(this->sigma, in);\n}\n\nvoid\nSequence::buildRank()\n{\n uint64_t blocks = (this->size() + SAMPLE_RATE - 1) \/ SAMPLE_RATE;\n int_vector<0> temp((blocks + 1) * this->sigma, 0, bitlength(this->size()));\n for(uint64_t block = 0; block < blocks; block++)\n {\n for(uint64_t c = 0; c < this->sigma; c++) { temp[(block + 1) * this->sigma + c] = temp[block * this->sigma + c]; }\n uint64_t limit = std::min(this->size(), (block + 1) * SAMPLE_RATE);\n for(uint64_t i = block * SAMPLE_RATE; i < limit; i++) { temp[(block + 1) * this->sigma + this->data[i]]++; }\n }\n util::bit_compress(temp); this->samples.swap(temp);\n}\n\n\/\/------------------------------------------------------------------------------\n\nRLSequence::RLSequence()\n{\n}\n\ninline void\naddBasicRun(uint64_t c, uint64_t run, std::vector<uint8_t>& runs)\n{\n runs.push_back(c + RLSequence::SIGMA * (run - 1));\n}\n\nvoid\naddRun(uint64_t c, uint64_t run, std::vector<uint8_t>& runs)\n{\n while(run > 0)\n {\n \/\/ Runs of length <= 41 are encoded in a single byte.\n if(run < RLSequence::MAX_RUN)\n {\n addBasicRun(c, run, runs);\n return;\n }\n\n uint64_t bytes_remaining = RLSequence::SAMPLE_RATE - (runs.size() % RLSequence::SAMPLE_RATE);\n uint64_t l = (bytes_remaining < 2 ? RLSequence::MAX_RUN - 1 : RLSequence::MAX_RUN);\n addBasicRun(c, l, runs); run -= l;\n if(bytes_remaining < 2) { continue; } \/\/ No room for the additional run length in the current block.\n bytes_remaining--;\n\n \/\/ Write the rest of the run with 7 bits\/byte, least significant byte first.\n if(bitlength(run) > 7 * bytes_remaining) \/\/ Cannot encode the entire run in current block.\n {\n uint64_t temp = 0;\n for(uint64_t i = 1; i < bytes_remaining; i++) { runs.push_back(0xFF); temp = (temp << 7) | 0x7F; }\n runs.push_back(0x7F); run -= (temp << 7) | 0x7F;\n }\n else\n {\n do\n {\n uint8_t val = run & 0x7F; run >>= 7;\n if(run > 0) { val |= 0x80; }\n runs.push_back(val);\n }\n while(run > 0);\n }\n }\n}\n\nRLSequence::RLSequence(int_vector_buffer<8>& buffer, uint64_t _size)\n{\n \/\/ Process the input.\n uint64_t c = 0, run = 0;\n for(uint64_t i = 0; i < _size; i++)\n {\n if(buffer[i] == c) { run++; }\n else\n {\n addRun(c, run, this->data);\n c = buffer[i]; run = 1;\n }\n }\n addRun(c, run, this->data);\n\n \/\/ Blocks and samples.\n this->buildRank();\n}\n\nRLSequence::RLSequence(const RLSequence& s)\n{\n this->copy(s);\n}\n\nRLSequence::RLSequence(RLSequence&& s)\n{\n *this = std::move(s);\n}\n\nRLSequence::~RLSequence()\n{\n}\n\nvoid\nRLSequence::copy(const RLSequence& s)\n{\n this->data = s.data;\n for(uint64_t c = 0; c < SIGMA; c++) { this->samples[c] = s.samples[c]; }\n this->block_boundaries = s.block_boundaries;\n util::init_support(this->block_rank, &(this->block_boundaries));\n util::init_support(this->block_select, &(this->block_boundaries));\n}\n\nvoid\nRLSequence::swap(RLSequence& s)\n{\n if(this != &s)\n {\n this->data.swap(s.data);\n for(uint64_t c = 0; c < SIGMA; c++) { this->samples[c].swap(s.samples[c]); }\n this->block_boundaries.swap(s.block_boundaries);\n util::swap_support(this->block_rank, s.block_rank, &(this->block_boundaries), &(s.block_boundaries));\n util::swap_support(this->block_select, s.block_select, &(this->block_boundaries), &(s.block_boundaries));\n }\n}\n\nRLSequence&\nRLSequence::operator=(const RLSequence& s)\n{\n if(this != &s) { this->copy(s); }\n return *this;\n}\n\nRLSequence&\nRLSequence::operator=(RLSequence&& s)\n{\n if(this != &s)\n {\n this->data = std::move(s.data);\n for(uint64_t c = 0; c < SIGMA; c++) { this->samples[c] = std::move(s.samples[c]); }\n this->block_boundaries = std::move(s.block_boundaries);\n util::init_support(this->block_rank, &(this->block_boundaries));\n util::init_support(this->block_select, &(this->block_boundaries));\n }\n return *this;\n}\n\nuint64_t\nRLSequence::serialize(std::ostream& out, structure_tree_node* s, std::string name) const\n{\n structure_tree_node* child = structure_tree::add_child(s, name, util::class_name(*this));\n uint64_t written_bytes = 0;\n written_bytes += write_vector(this->data, out, child, \"data\");\n for(uint64_t c = 0; c < SIGMA; c++)\n {\n std::stringstream ss; ss << \"samples_\" << c;\n written_bytes += this->samples[c].serialize(out, child, ss.str());\n }\n written_bytes += this->block_boundaries.serialize(out, child, \"block_boundaries\");\n written_bytes += this->block_rank.serialize(out, child, \"block_rank\");\n written_bytes += this->block_select.serialize(out, child, \"block_select\");\n structure_tree::add_size(child, written_bytes);\n return written_bytes;\n}\n\nvoid\nRLSequence::load(std::istream& in, bool rebuild_samples)\n{\n read_vector(this->data, in);\n if(rebuild_samples)\n {\n this->buildRank();\n }\n else\n {\n for(uint64_t c = 0; c < SIGMA; c++) { this->samples[c].load(in); }\n this->block_boundaries.load(in);\n this->block_rank.load(in, &(this->block_boundaries));\n this->block_select.load(in, &(this->block_boundaries));\n }\n}\n\nvoid\nRLSequence::buildRank()\n{\n std::vector<uint64_t> block_ends;\n uint64_t seq_pos = 0, rle_pos = 0;\n while(rle_pos < this->runs())\n {\n range_type run = this->readRun(rle_pos); seq_pos += run.second;\n if(rle_pos >= this->runs() || rle_pos % SAMPLE_RATE == 0) { block_ends.push_back(seq_pos - 1); }\n }\n\n \/\/ Block boundaries.\n uint64_t blocks = block_ends.size();\n {\n sd_vector<> temp(block_ends.begin(), block_ends.end());\n util::clear(block_ends);\n this->block_boundaries.swap(temp);\n util::init_support(this->block_rank, &(this->block_boundaries));\n util::init_support(this->block_select, &(this->block_boundaries));\n }\n\n \/\/ Samples. SIGMA passes vs. higher space usage? Multi-threaded?\n for(uint64_t c = 0; c < SIGMA; c++)\n {\n int_vector<0> temp(blocks, 0, bitlength(this->size()));\n for(uint64_t block = 0; block < blocks; block++)\n {\n uint64_t rle_pos = block * SAMPLE_RATE, limit = std::min(this->runs(), (block + 1) * SAMPLE_RATE);\n while(rle_pos < limit)\n {\n range_type run = this->readRun(rle_pos);\n if(run.first == c) { temp[block] += run.second; }\n }\n }\n util::assign(this->samples[c], CumulativeArray(temp, temp.size()));\n }\n}\n\nuint64_t\nRLSequence::hash(const Alphabet& alpha) const\n{\n uint64_t rle_pos = 0, val = FNV_OFFSET_BASIS;\n while(rle_pos < this->runs())\n {\n range_type run = this->readRun(rle_pos);\n uint8_t c = alpha.comp2char[run.first];\n for(uint64_t i = 0; i < run.second; i++) { val = fnv1a_hash(c, val); }\n }\n return val;\n}\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<>\nSimpleFM<RLSequence>::SimpleFM(const std::string& base_name, LoadMode mode)\n{\n this->sample_rate = 0;\n\n if(mode == mode_native || mode == mode_ropebwt2)\n {\n std::string filename = base_name + NATIVE_BWT_EXTENSION;\n std::ifstream in(filename.c_str(), std::ios_base::binary);\n if(!in)\n {\n std::cerr << \"SimpleFM::SimpleFM(): Cannot open BWT file \" << filename << \" (native format)\" << std::endl;\n return;\n }\n this->bwt.load(in, mode == mode_ropebwt2); in.close();\n }\n else\n {\n int_vector_buffer<8> buffer(base_name + BWT_EXTENSION);\n RLSequence temp(buffer, buffer.size());\n this->bwt.swap(temp);\n }\n\n this->loadAlphabet(base_name);\n this->loadSamples(base_name);\n}\n\ntemplate<>\nvoid\ncharacterCounts(const RLSequence& sequence, uint64_t size, int_vector<64>& counts)\n{\n for(uint64_t c = 0; c < counts.size(); c++) { counts[c] = 0; }\n\n uint64_t rle_pos = 0;\n while(rle_pos < sequence.runs())\n {\n range_type run = sequence.readRun(rle_pos);\n counts[run.first] += run.second;\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\n} \/\/ namespace relative\n<|endoftext|>"} {"text":"<commit_before>#include \"perlin.h\"\n\n#include <armadillo\/armadillo>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <algorithm>\n#include <functional>\n\n#include \"mathshelper.h\"\n#include \"interpolation.h\"\n\nusing namespace arma;\nusing namespace maths;\n\nnamespace perlin {\n \/\/PRIVATE gnre un nombre alatoire entre 0 et 1\n double generateRandom() {\n return rand() \/ (double) RAND_MAX;\n }\n\n void generatePerlinOctave(Mat<double> &output,\n int offset,\n float frequency,\n bool repeatable) {\n\n \/\/Dtermination de la taille de la matrice\n int size = (int) std::min(output.n_rows, output.n_cols);\n \/\/marche le mieux avec des tailles de pattern de la forme 2^n + 1 et frquence en 2^i\n int period = max((int) ((size - 1) \/ frequency), 1);\n\n \/\/ Implmentation de la rptabilit\n int firstX = 0, firstY = firstX;\n int lastX = repeatable ? size - period : size, lastY = lastX;\n\n int overflowX = period * ((size - 1) \/ period);\n if (repeatable) {\n overflowX = size;\n }\n int overflowY = overflowX;\n\n \/\/Gnration des valeurs alatoires\n for (int x = firstX; x < lastX; x += period) {\n for (int y = firstY; y < lastY; y += period) {\n output(x, y) = generateRandom();\n }\n }\n\n \/\/Interpolation\n for (int x = 0; x < size; x++) {\n for (int y = 0; y < size; y++) {\n\n if (x % period != 0 || x >= lastX || \n\t\t\t\t\ty % period != 0 || y >= lastY) {\n\n \/\/Calcul des bornes\n int borneX1, borneX2, borneY1, borneY2;\n\n int tileX = min(x, lastX) \/ period;\n int tileY = min(y, lastY) \/ period;\n\n borneX1 = tileX * period;\n borneY1 = tileY * period;\n borneX2 = borneX1 + period;\n borneY2 = borneY1 + period;\n\n if (borneX2 >= lastX) {\n borneX2 = overflowX;\n }\n if (borneY2 >= lastY) {\n borneY2 = overflowY;\n }\n\n\n \/\/Interpolation\n double v1 = interpolate(borneX1, output(borneX1, borneY1),\n borneX2, output(borneX2 % size, borneY1),\n x);\n\n double v2 = interpolate(borneX1, output(borneX1, borneY2 % size),\n borneX2, output(borneX2 % size, borneY2 % size),\n x);\n\n output(x, y) = interpolate(borneY1, v1, borneY2, v2, y);\n }\n }\n }\n }\n\n void generatePerlinNoise2D(Mat<double> &output,\n int offset,\n int octaveCount,\n float frequency,\n float persistence,\n bool repeatable) {\n\n \/\/Initialisation du random avec une seed quelconque\n srand(time(NULL));\n\n \/\/Dtermination de la taille de la matrice\n const uword size = std::min(output.n_rows, output.n_cols);\n\n output.fill(0);\n\n double persistenceSum = 0;\n for (int i = 1; i <= octaveCount; i++) {\n persistenceSum += pow(persistence, i);\n }\n\n Mat<double> octave(size, size);\n for (int i = 1; i <= octaveCount; i++) {\n generatePerlinOctave(octave, offset * (i - 1), frequency * (float) pow(2, i - 1), repeatable);\n output += octave * pow(persistence, i) \/ persistenceSum;\n }\n }\n\n Mat<double> generatePerlinNoise2D(int size,\n int offset,\n int octaves,\n float frequency,\n float persistence,\n bool repeatable) {\n\n Mat<double> result(size, size);\n generatePerlinNoise2D(result, offset, octaves, frequency, persistence, repeatable);\n return result;\n }\n\n\tvoid join(arma::Mat<double> &mat1,\n\t\t arma::Mat<double> &mat2,\n\t\t const Direction & direction,\n\t\t int octaves,\n\t\t float frequency,\n\t\t float persistence) {\n\n\t\t\/\/ Vrification des dimensions de mat1 et mat2\n\t\tint length1, length2, depth1, depth2;\n\t\tif (direction == Direction::AXIS_Y) {\n\t\t\tlength1 = mat1.n_cols;\n\t\t\tlength2 = mat2.n_cols;\n\t\t\tdepth1 = mat1.n_rows;\n\t\t\tdepth2 = mat2.n_rows;\n\t\t}\n\t\telse {\n\t\t\tlength1 = mat1.n_rows;\n\t\t\tlength2 = mat2.n_rows;\n\t\t\tdepth1 = mat1.n_cols;\n\t\t\tdepth2 = mat2.n_cols;\n\t\t}\n\n\t\t\/\/ TODO dfinir le comportement lorsque length2 \/= length1\n\t\tint length = min(length1, length2);\n\t\tint depth = min(depth1, depth2);\n\n\t\t\/\/ Permet d'abstraire les directions.\n\t\t\/\/ les x sont dans le sens de la longueur des deux matrices joindre\n\t\t\/\/ les y reprsentent l'loignement la jointure.\n\t\t\/\/ y ngatif -> mat1, y positifs -> mat2\n\t\tstd::function<double & (int, int)> at;\n\n\t\tswitch (direction) {\n\t\tcase Direction::AXIS_Y:\n\t\t\tat = [&mat1, &mat2](int x, int y) -> double & {\n\t\t\t\tif (y < 0) {\n\t\t\t\t\treturn mat1(x, mat1.n_cols + y);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn mat2(x, y);\n\t\t\t\t}\n\t\t\t};\n\t\t\tbreak;\n\t\tcase Direction::AXIS_X:\n\t\t\tat = [&mat1, &mat2](int x, int y) -> double & {\n\t\t\t\tif (y < 0) {\n\t\t\t\t\treturn mat1(mat1.n_rows + y, x);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn mat2(y, x);\n\t\t\t\t}\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Perlin\n\t\tint period = (int)ceil(depth \/ frequency);\n\t\tint joinDepth1 = (depth1 \/ period - 1) * period - depth1;\n\t\tint joinDepth2 = period;\n\n\t\tfor (int i = 0; i < octaves; i++) {\n\t\t\t\/\/ Gnration des points\n\t\t\tfor (int y = joinDepth2; y >= joinDepth1 + period; y -= period) {\n\n\t\t\t}\n\n\t\t\t\/\/ Interpolation entre les points\n\n\t\t\t\/\/ Ajout de l'octave au joint\n\n\t\t\t\/\/ Incrmentation de la priode\n\t\t\tperiod = (int) ceil(period \/ 2.0);\n\t\t}\n\t}\n}\n<commit_msg>Algo join perlin : calcul des offsets<commit_after>#include \"perlin.h\"\n\n#include <armadillo\/armadillo>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <algorithm>\n#include <functional>\n\n#include \"mathshelper.h\"\n#include \"interpolation.h\"\n\nusing namespace arma;\nusing namespace maths;\n\nnamespace perlin {\n \/\/PRIVATE gnre un nombre alatoire entre 0 et 1\n double generateRandom() {\n return rand() \/ (double) RAND_MAX;\n }\n\n void generatePerlinOctave(Mat<double> &output,\n int offset,\n float frequency,\n bool repeatable) {\n\n \/\/Dtermination de la taille de la matrice\n int size = (int) std::min(output.n_rows, output.n_cols);\n \/\/marche le mieux avec des tailles de pattern de la forme 2^n + 1 et frquence en 2^i\n int period = max((int) ((size - 1) \/ frequency), 1);\n\n \/\/ Implmentation de la rptabilit\n int firstX = 0, firstY = firstX;\n int lastX = repeatable ? size - period : size, lastY = lastX;\n\n int overflowX = period * ((size - 1) \/ period);\n if (repeatable) {\n overflowX = size;\n }\n int overflowY = overflowX;\n\n \/\/Gnration des valeurs alatoires\n for (int x = firstX; x < lastX; x += period) {\n for (int y = firstY; y < lastY; y += period) {\n output(x, y) = generateRandom();\n }\n }\n\n \/\/Interpolation\n for (int x = 0; x < size; x++) {\n for (int y = 0; y < size; y++) {\n\n if (x % period != 0 || x >= lastX || \n\t\t\t\t\ty % period != 0 || y >= lastY) {\n\n \/\/Calcul des bornes\n int borneX1, borneX2, borneY1, borneY2;\n\n int tileX = min(x, lastX) \/ period;\n int tileY = min(y, lastY) \/ period;\n\n borneX1 = tileX * period;\n borneY1 = tileY * period;\n borneX2 = borneX1 + period;\n borneY2 = borneY1 + period;\n\n if (borneX2 >= lastX) {\n borneX2 = overflowX;\n }\n if (borneY2 >= lastY) {\n borneY2 = overflowY;\n }\n\n\n \/\/Interpolation\n double v1 = interpolate(borneX1, output(borneX1, borneY1),\n borneX2, output(borneX2 % size, borneY1),\n x);\n\n double v2 = interpolate(borneX1, output(borneX1, borneY2 % size),\n borneX2, output(borneX2 % size, borneY2 % size),\n x);\n\n output(x, y) = interpolate(borneY1, v1, borneY2, v2, y);\n }\n }\n }\n }\n\n void generatePerlinNoise2D(Mat<double> &output,\n int offset,\n int octaveCount,\n float frequency,\n float persistence,\n bool repeatable) {\n\n \/\/Initialisation du random avec une seed quelconque\n srand((uint32_t) time(NULL));\n\n \/\/Dtermination de la taille de la matrice\n const uword size = std::min(output.n_rows, output.n_cols);\n\n output.fill(0);\n\n double persistenceSum = 0;\n for (int i = 1; i <= octaveCount; i++) {\n persistenceSum += pow(persistence, i);\n }\n\n Mat<double> octave(size, size);\n for (int i = 1; i <= octaveCount; i++) {\n generatePerlinOctave(octave, offset * (i - 1), frequency * (float) pow(2, i - 1), repeatable);\n output += octave * pow(persistence, i) \/ persistenceSum;\n }\n }\n\n Mat<double> generatePerlinNoise2D(int size,\n int offset,\n int octaves,\n float frequency,\n float persistence,\n bool repeatable) {\n\n Mat<double> result((uword) size, (uword) size);\n generatePerlinNoise2D(result, offset, octaves, frequency, persistence, repeatable);\n return result;\n }\n\n\tvoid join(arma::Mat<double> &mat1,\n\t\t arma::Mat<double> &mat2,\n\t\t const Direction & direction,\n\t\t int octaves,\n\t\t float frequency,\n\t\t float persistence) {\n\n\t\t\/\/ Vrification des dimensions de mat1 et mat2\n\t\tint length1, length2, depth1, depth2;\n\t\tif (direction == Direction::AXIS_Y) {\n\t\t\tlength1 = (int) mat1.n_cols;\n\t\t\tlength2 = (int) mat2.n_cols;\n\t\t\tdepth1 = (int) mat1.n_rows;\n\t\t\tdepth2 = (int) mat2.n_rows;\n\t\t}\n\t\telse {\n\t\t\tlength1 = (int) mat1.n_rows;\n\t\t\tlength2 = (int) mat2.n_rows;\n\t\t\tdepth1 = (int) mat1.n_cols;\n\t\t\tdepth2 = (int) mat2.n_cols;\n\t\t}\n\n\t\t\/\/ TODO dfinir le comportement lorsque length2 \/= length1\n\t\tint length = min(length1, length2);\n\t\tint depth = min(depth1, depth2);\n int period = (int) ceil((double) (depth \/ frequency));\n\n int joinDepth1 = - (depth1 % period) - period;\n int joinDepth2 = period;\n int joinDepth = joinDepth2 - joinDepth1 - 2;\n int joinOffset = - 1 - joinDepth1;\n\n\t\t\/\/ Permet d'abstraire les directions.\n\t\t\/\/ les x sont dans le sens de la longueur des deux matrices joindre\n\t\t\/\/ les y reprsentent l'loignement la jointure.\n\t\t\/\/ y < joinOffset -> mat1, y > joinOffset -> mat2\n\t\tstd::function<double & (int, int)> at;\n\n\t\tswitch (direction) {\n\t\tcase Direction::AXIS_Y:\n\t\t\tat = [&mat1, &mat2, &joinOffset](int x, int y) -> double & {\n y -= joinOffset;\n\t\t\t\tif (y < 0) {\n\t\t\t\t\treturn mat1(x, mat1.n_cols + y);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn mat2(x, y);\n\t\t\t\t}\n\t\t\t};\n\t\t\tbreak;\n\t\tcase Direction::AXIS_X:\n\t\t\tat = [&mat1, &mat2, &joinOffset](int x, int y) -> double & {\n y -= joinOffset;\n\t\t\t\tif (y < 0) {\n\t\t\t\t\treturn mat1(mat1.n_rows + y, x);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn mat2(y, x);\n\t\t\t\t}\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Perlin\n\n Mat<double> octave((uword) length, (uword) joinDepth);\n\n\t\tfor (int i = 0; i < octaves; i++) {\n Mat<double> join((uword) length, (uword) joinDepth);\n\n\t\t\t\/\/ Gnration des points\n\t\t\tfor (int y = joinDepth2 - period; y >= joinDepth1 + period; y -= period) {\n for (int x = 0; x < length; x += period) {\n \/\/join(x, y + 1 - joinDepth1);\n }\n\t\t\t}\n\n\t\t\t\/\/ Interpolation entre les points\n\n\t\t\t\/\/ Ajout de l'octave au joint\n\n\t\t\t\/\/ Incrmentation de la priode\n\t\t\tperiod = (int) ceil(period \/ 2.0);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n mapihd.cpp - description\n -------------------\n begin : Tue Jul 25 2000\n copyright : (C) 2000 by Hans Dijkema\n email : kmailcvt@hum.org\n ***************************************************************************\/\n\n\/***************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"pab_pablib.h\"\n\nbool operator < (mapitag_t & a,mapitag_t & b) { return a._order<b._order; }\nbool operator > (mapitag_t & a,mapitag_t & b) { return a._order>b._order; }\nbool operator == (mapitag_t & a,mapitag_t & b) { return a._order==b._order; }\n\nword_t\nmap_givenname[]=\n { pr_givenname,\n SET_MS_GIVEN_NAME,\n 0\n },\nmap_email[]=\n { pr_email,\n SET_MS_EMAIL,\n 0\n },\nmap_firstname[]=\n { pr_firstname,\n\t SET_MS_FIRSTNAME,\n 0\n },\nmap_lastname[]=\n { pr_lastname,\n SET_MS_LASTNAME,\n 0\n },\nmap_additionalname[]=\n { pr_additionalname,\n SET_MS_MIDDLENAME,\n 0\n },\nmap_title[]=\n { pr_title,\n SET_MS_TITLE,\n 0\n },\nmap_address[]=\n { pr_address,\n SET_MS_ADDRESS,\n 0\n },\nmap_zip[]=\n { pr_zip,\n SET_MS_ZIP,\n 0\n },\nmap_state[]=\n { pr_state,\n SET_MS_STATE,\n 0\n },\nmap_town[]=\n { pr_town,\n SET_MS_TOWN,\n 0\n },\nmap_country[]=\n { pr_country,\n SET_MS_COUNTRY,\n 0\n },\nmap_tel[]=\n { pr_tel,\n SET_MS_TEL,\n 0\n },\nmap_mobile[]=\n { pr_mobile,\n SET_MS_MOBILE,\n 0\n },\nmap_fax[]=\n { pr_fax,\n SET_MS_FAX,\n 0\n },\nmap_job[]=\n { pr_job,\n HP_OPENMAIL_JOB,\n 0\n },\nmap_organization[]=\n { pr_organization,\n SET_MS_ORGANIZATION,\n HP_OPENMAIL_ORGANIZATION,\n 0\n },\nmap_department[]=\n { pr_department,\n SET_MS_DEPARTMENT,\n HP_OPENMAIL_DEPARTMENT,\n 0\n },\nmap_subdep[]=\n { pr_subdep,\n HP_OPENMAIL_SUBDEP,\n 0\n },\nmap_notes[]=\n { pr_notes,\n SET_MS_COMMENT,\n 0\n },\nmap_notused[]=\n { pr_notused,\n HP_OPENMAIL_LOCATION_OF_WORK, \/\/ location of work\n\t SET_NOT_USED,\n 0\n };\n\n\nword_t *mapi_map[]={ map_givenname, map_email,\n map_firstname, map_lastname, map_additionalname,map_title,\n map_address, map_town, map_zip, map_state, map_country,\n map_tel, map_mobile, map_fax,\n map_organization, map_department, map_subdep, map_job,\n map_notes,\n map_notused,\n NULL\n };\n\npabrec_entry mapitag_t::matchTag(void)\n{\nint i,j;\npabrec_entry e=pr_unknown;\n\n for(i=0;mapi_map[i]!=NULL && e==pr_unknown;i++) {\n for(j=1;mapi_map[i][j]!=0 && _tag!=mapi_map[i][j];j++);\n if (mapi_map[i][j]!=0) {\n e=(pabrec_entry) mapi_map[i][0];\n }\n }\nreturn e;\n}\n\npabfields_t::pabfields_t(pabrec & R, QWidget * \/*parent*\/)\n{\n \/\/ Skip the first two words, because they're always the\n \/\/ same 000c 0014 ==> 0014 gives us the types, so we\n \/\/ parse from 0014 till the next offset and order the tags.\n\n int mb,me;\n uint i,k;\n content_t _tag,_order;\n\n mb=R[1];\n me=R[2];\n\n while (mb<me) {\n _tag=R.read(mb);mb+=sizeof(_tag);\n _order=R.read(mb);mb+=sizeof(_order);\n\n {mapitag_t mt(_tag,_order);\n tags[tags.size()]=mt;\n context_tags[context_tags.size()]=mt;\n }\n }\n tags.sort();\n\n \/\/ get the right entries now\n\n for(i=2,k=0;i<R.N() && k<tags.size();i++,k++) {\n if (!isUsed(k)) { i-=1; }\n else {pabrec_entry e;\n QString E;\n\n e=isWhat(k);\n E=R.getEntry(i);\n { QString s=E;\n s=s.stripWhiteSpace();\n E=s;\n }\n\n \/*\n { char m[1024];\n snprintf(m, sizeof(m), \"%d %d %04x %08lx %d %s %d %d\",i,k,literal(k),order(k),e,E.latin1(),E[0].latin1(),E.length());\n info->addLog(m);\n }\n *\/\n\n if (!E.isEmpty()) {\n\n switch (e) {\n case pr_givenname: givenName=E;\n break;\n case pr_email: email=E;\n break;\n case pr_firstname: firstName=E;\n break;\n case pr_additionalname: additionalName=E;\n break;\n case pr_lastname: lastName=E;\n break;\n case pr_title: title=E;\n break;\n case pr_address: address=E;\n break;\n case pr_town: town=E;\n break;\n case pr_state: state=E;\n break;\n case pr_zip: zip=E;\n break;\n case pr_country: country=E;\n break;\n case pr_organization: organization=E;\n break;\n case pr_department: department=E;\n break;\n case pr_subdep: subDep=E;\n break;\n case pr_job: job=E;\n break;\n case pr_tel: tel=E;\n break;\n case pr_fax: fax=E;\n break;\n case pr_modem: modem=E;\n break;\n case pr_mobile: mobile=E;\n break;\n case pr_url: homepage=E;\n break;\n case pr_talk: talk=E;\n break;\n case pr_notes: comment=E;\n break;\n case pr_birthday: birthday=E;\n break;\n case pr_notused:\n break;\n default: {\/*char m[250];\n snprintf(m,sizeof(m),\"unknown tag '%x'\",literal(k));\n info->log(m);*\/\n }\n break;\n }\n }\n }\n }\n\n if (!firstName.isEmpty() && !lastName.isEmpty()) {\n givenName=lastName+\", \"+firstName;\n }\n\n \/\/ Determine if the record is ok.\n\n OK=true;\n}\n\nbool pabfields_t::isUsed(int k)\n{\nreturn tags[k].isUsed();\n}\n\npabrec_entry pabfields_t::isWhat(int k)\n{\nreturn tags[k].matchTag();\n}\n\nword_t pabfields_t::literal(int k)\n{\nreturn tags[k].literal();\n}\n\ncontent_t pabfields_t::order(int k)\n{\nreturn tags[k].order();\n}\n\nKABC::Addressee pabfields_t::get() {\n KABC::Addressee a;\n if (!givenName.isEmpty()) a.setFormattedName(givenName);\n if (!email.isEmpty()) a.insertEmail(email);\n if (!title.isEmpty()) a.setTitle(title);\n if (!firstName.isEmpty()) a.setName(firstName);\n if (!additionalName.isEmpty()) a.setAdditionalName(additionalName);\n if (!lastName.isEmpty()) a.setFamilyName(lastName);\n\n KABC::Address addr;\n if (!address.isEmpty()) addr.setStreet(address);\n if (!town.isEmpty()) addr.setLocality(town);\n if (!zip.isEmpty()) addr.setPostalCode(zip);\n if (!state.isEmpty()) addr.setRegion(state);\n if (!country.isEmpty()) addr.setCountry(country);\n a.insertAddress(addr);\n\n if (!organization.isEmpty()) a.setOrganization(organization);\n if (!department.isEmpty()) a.setRole(department);\n \/\/ Miss out department, subDep, job\n if (!tel.isEmpty()) a.insertPhoneNumber( KABC::PhoneNumber( tel, KABC::PhoneNumber::Voice ) );\n if (!fax.isEmpty()) a.insertPhoneNumber( KABC::PhoneNumber( fax, KABC::PhoneNumber::Fax ) );\n if (!mobile.isEmpty()) a.insertPhoneNumber( KABC::PhoneNumber( mobile, KABC::PhoneNumber::Cell ) );\n if (!modem.isEmpty()) a.insertPhoneNumber( KABC::PhoneNumber( modem, KABC::PhoneNumber::Modem ) );\n if (!homepage.isEmpty()) a.setUrl(homepage);\n \/\/ Miss out talk\n if (!comment.isEmpty()) a.setNote(comment);\n \/\/ Miss out birthday\n return a;\n}\n\n\n\n\n\/* class pabrec {\n private:\n char entry[1024];\n byte *_mem;\n word_t *_N;\n word_t *_w;\n public:\n pabrec(pab *); \/\/ expects record the begin at reading point (ftell).\n ~pabrec();\n public:\n word_t N(void) { return _N[0]; }\n word_t operator[](int i) { return _w[i]; }\n const char *getEntry(int i);\n public:\n content_t read(word_t offset);\n };\n*\/\n\npabrec::pabrec(pab & P)\n{\nadr_t A=P.tell();\ncontent_t hdr;\nword_t offset,size,dummy;\nint i;\n\n hdr=P.go(A);\n offset=P.lower(hdr);\n\n size=offset;\n _mem=new byte[size];\n P.read(_mem,size);\n\n P.go(A+offset);\n P.read(m_N);\n m_W=new word_t[m_N+1];\n\n P.read(dummy);\n for(i=0;i<=m_N;i++) {\n P.read(m_W[i]);\n }\n}\n\npabrec::~pabrec()\n{\n delete _mem;\n delete m_W;\n}\n\n\ncontent_t pabrec::read(word_t offset)\n{\ncontent_t R;\n R=_mem[offset+3];\n R<<=8;R+=_mem[offset+2];\n R<<=8;R+=_mem[offset+1];\n R<<=8;R+=_mem[offset];\nreturn R;\n}\n\nconst char *pabrec::getEntry(int i)\n{\nint mb,me;\nint k;\n mb=m_W[i];me=m_W[i+1];\n for(k=0;mb!=me;mb++) {\n if (_mem[mb]>=' ' || _mem[mb]=='\\n' || _mem[mb]==13 || _mem[mb]=='\\t') {\n if (_mem[mb]==13) { entry[k]='\\n'; }\n else { entry[k]=_mem[mb]; }\n k+=1;\n }\n }\n entry[k]='\\0';\nreturn (const char *) entry;\n}\n<commit_msg>+static<commit_after>\/***************************************************************************\n mapihd.cpp - description\n -------------------\n begin : Tue Jul 25 2000\n copyright : (C) 2000 by Hans Dijkema\n email : kmailcvt@hum.org\n ***************************************************************************\/\n\n\/***************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"pab_pablib.h\"\n\nbool operator < (mapitag_t & a,mapitag_t & b) { return a._order<b._order; }\nbool operator > (mapitag_t & a,mapitag_t & b) { return a._order>b._order; }\nbool operator == (mapitag_t & a,mapitag_t & b) { return a._order==b._order; }\n\nstatic word_t\nmap_givenname[]=\n { pr_givenname,\n SET_MS_GIVEN_NAME,\n 0\n },\nmap_email[]=\n { pr_email,\n SET_MS_EMAIL,\n 0\n },\nmap_firstname[]=\n { pr_firstname,\n\t SET_MS_FIRSTNAME,\n 0\n },\nmap_lastname[]=\n { pr_lastname,\n SET_MS_LASTNAME,\n 0\n },\nmap_additionalname[]=\n { pr_additionalname,\n SET_MS_MIDDLENAME,\n 0\n },\nmap_title[]=\n { pr_title,\n SET_MS_TITLE,\n 0\n },\nmap_address[]=\n { pr_address,\n SET_MS_ADDRESS,\n 0\n },\nmap_zip[]=\n { pr_zip,\n SET_MS_ZIP,\n 0\n },\nmap_state[]=\n { pr_state,\n SET_MS_STATE,\n 0\n },\nmap_town[]=\n { pr_town,\n SET_MS_TOWN,\n 0\n },\nmap_country[]=\n { pr_country,\n SET_MS_COUNTRY,\n 0\n },\nmap_tel[]=\n { pr_tel,\n SET_MS_TEL,\n 0\n },\nmap_mobile[]=\n { pr_mobile,\n SET_MS_MOBILE,\n 0\n },\nmap_fax[]=\n { pr_fax,\n SET_MS_FAX,\n 0\n },\nmap_job[]=\n { pr_job,\n HP_OPENMAIL_JOB,\n 0\n },\nmap_organization[]=\n { pr_organization,\n SET_MS_ORGANIZATION,\n HP_OPENMAIL_ORGANIZATION,\n 0\n },\nmap_department[]=\n { pr_department,\n SET_MS_DEPARTMENT,\n HP_OPENMAIL_DEPARTMENT,\n 0\n },\nmap_subdep[]=\n { pr_subdep,\n HP_OPENMAIL_SUBDEP,\n 0\n },\nmap_notes[]=\n { pr_notes,\n SET_MS_COMMENT,\n 0\n },\nmap_notused[]=\n { pr_notused,\n HP_OPENMAIL_LOCATION_OF_WORK, \/\/ location of work\n\t SET_NOT_USED,\n 0\n };\n\n\nstatic word_t *mapi_map[]={ map_givenname, map_email,\n map_firstname, map_lastname, map_additionalname,map_title,\n map_address, map_town, map_zip, map_state, map_country,\n map_tel, map_mobile, map_fax,\n map_organization, map_department, map_subdep, map_job,\n map_notes,\n map_notused,\n NULL\n };\n\npabrec_entry mapitag_t::matchTag(void)\n{\nint i,j;\npabrec_entry e=pr_unknown;\n\n for(i=0;mapi_map[i]!=NULL && e==pr_unknown;i++) {\n for(j=1;mapi_map[i][j]!=0 && _tag!=mapi_map[i][j];j++);\n if (mapi_map[i][j]!=0) {\n e=(pabrec_entry) mapi_map[i][0];\n }\n }\nreturn e;\n}\n\npabfields_t::pabfields_t(pabrec & R, QWidget * \/*parent*\/)\n{\n \/\/ Skip the first two words, because they're always the\n \/\/ same 000c 0014 ==> 0014 gives us the types, so we\n \/\/ parse from 0014 till the next offset and order the tags.\n\n int mb,me;\n uint i,k;\n content_t _tag,_order;\n\n mb=R[1];\n me=R[2];\n\n while (mb<me) {\n _tag=R.read(mb);mb+=sizeof(_tag);\n _order=R.read(mb);mb+=sizeof(_order);\n\n {mapitag_t mt(_tag,_order);\n tags[tags.size()]=mt;\n context_tags[context_tags.size()]=mt;\n }\n }\n tags.sort();\n\n \/\/ get the right entries now\n\n for(i=2,k=0;i<R.N() && k<tags.size();i++,k++) {\n if (!isUsed(k)) { i-=1; }\n else {pabrec_entry e;\n QString E;\n\n e=isWhat(k);\n E=R.getEntry(i);\n { QString s=E;\n s=s.stripWhiteSpace();\n E=s;\n }\n\n \/*\n { char m[1024];\n snprintf(m, sizeof(m), \"%d %d %04x %08lx %d %s %d %d\",i,k,literal(k),order(k),e,E.latin1(),E[0].latin1(),E.length());\n info->addLog(m);\n }\n *\/\n\n if (!E.isEmpty()) {\n\n switch (e) {\n case pr_givenname: givenName=E;\n break;\n case pr_email: email=E;\n break;\n case pr_firstname: firstName=E;\n break;\n case pr_additionalname: additionalName=E;\n break;\n case pr_lastname: lastName=E;\n break;\n case pr_title: title=E;\n break;\n case pr_address: address=E;\n break;\n case pr_town: town=E;\n break;\n case pr_state: state=E;\n break;\n case pr_zip: zip=E;\n break;\n case pr_country: country=E;\n break;\n case pr_organization: organization=E;\n break;\n case pr_department: department=E;\n break;\n case pr_subdep: subDep=E;\n break;\n case pr_job: job=E;\n break;\n case pr_tel: tel=E;\n break;\n case pr_fax: fax=E;\n break;\n case pr_modem: modem=E;\n break;\n case pr_mobile: mobile=E;\n break;\n case pr_url: homepage=E;\n break;\n case pr_talk: talk=E;\n break;\n case pr_notes: comment=E;\n break;\n case pr_birthday: birthday=E;\n break;\n case pr_notused:\n break;\n default: {\/*char m[250];\n snprintf(m,sizeof(m),\"unknown tag '%x'\",literal(k));\n info->log(m);*\/\n }\n break;\n }\n }\n }\n }\n\n if (!firstName.isEmpty() && !lastName.isEmpty()) {\n givenName=lastName+\", \"+firstName;\n }\n\n \/\/ Determine if the record is ok.\n\n OK=true;\n}\n\nbool pabfields_t::isUsed(int k)\n{\nreturn tags[k].isUsed();\n}\n\npabrec_entry pabfields_t::isWhat(int k)\n{\nreturn tags[k].matchTag();\n}\n\nword_t pabfields_t::literal(int k)\n{\nreturn tags[k].literal();\n}\n\ncontent_t pabfields_t::order(int k)\n{\nreturn tags[k].order();\n}\n\nKABC::Addressee pabfields_t::get() {\n KABC::Addressee a;\n if (!givenName.isEmpty()) a.setFormattedName(givenName);\n if (!email.isEmpty()) a.insertEmail(email);\n if (!title.isEmpty()) a.setTitle(title);\n if (!firstName.isEmpty()) a.setName(firstName);\n if (!additionalName.isEmpty()) a.setAdditionalName(additionalName);\n if (!lastName.isEmpty()) a.setFamilyName(lastName);\n\n KABC::Address addr;\n if (!address.isEmpty()) addr.setStreet(address);\n if (!town.isEmpty()) addr.setLocality(town);\n if (!zip.isEmpty()) addr.setPostalCode(zip);\n if (!state.isEmpty()) addr.setRegion(state);\n if (!country.isEmpty()) addr.setCountry(country);\n a.insertAddress(addr);\n\n if (!organization.isEmpty()) a.setOrganization(organization);\n if (!department.isEmpty()) a.setRole(department);\n \/\/ Miss out department, subDep, job\n if (!tel.isEmpty()) a.insertPhoneNumber( KABC::PhoneNumber( tel, KABC::PhoneNumber::Voice ) );\n if (!fax.isEmpty()) a.insertPhoneNumber( KABC::PhoneNumber( fax, KABC::PhoneNumber::Fax ) );\n if (!mobile.isEmpty()) a.insertPhoneNumber( KABC::PhoneNumber( mobile, KABC::PhoneNumber::Cell ) );\n if (!modem.isEmpty()) a.insertPhoneNumber( KABC::PhoneNumber( modem, KABC::PhoneNumber::Modem ) );\n if (!homepage.isEmpty()) a.setUrl(homepage);\n \/\/ Miss out talk\n if (!comment.isEmpty()) a.setNote(comment);\n \/\/ Miss out birthday\n return a;\n}\n\n\n\n\n\/* class pabrec {\n private:\n char entry[1024];\n byte *_mem;\n word_t *_N;\n word_t *_w;\n public:\n pabrec(pab *); \/\/ expects record the begin at reading point (ftell).\n ~pabrec();\n public:\n word_t N(void) { return _N[0]; }\n word_t operator[](int i) { return _w[i]; }\n const char *getEntry(int i);\n public:\n content_t read(word_t offset);\n };\n*\/\n\npabrec::pabrec(pab & P)\n{\nadr_t A=P.tell();\ncontent_t hdr;\nword_t offset,size,dummy;\nint i;\n\n hdr=P.go(A);\n offset=P.lower(hdr);\n\n size=offset;\n _mem=new byte[size];\n P.read(_mem,size);\n\n P.go(A+offset);\n P.read(m_N);\n m_W=new word_t[m_N+1];\n\n P.read(dummy);\n for(i=0;i<=m_N;i++) {\n P.read(m_W[i]);\n }\n}\n\npabrec::~pabrec()\n{\n delete _mem;\n delete m_W;\n}\n\n\ncontent_t pabrec::read(word_t offset)\n{\ncontent_t R;\n R=_mem[offset+3];\n R<<=8;R+=_mem[offset+2];\n R<<=8;R+=_mem[offset+1];\n R<<=8;R+=_mem[offset];\nreturn R;\n}\n\nconst char *pabrec::getEntry(int i)\n{\nint mb,me;\nint k;\n mb=m_W[i];me=m_W[i+1];\n for(k=0;mb!=me;mb++) {\n if (_mem[mb]>=' ' || _mem[mb]=='\\n' || _mem[mb]==13 || _mem[mb]=='\\t') {\n if (_mem[mb]==13) { entry[k]='\\n'; }\n else { entry[k]=_mem[mb]; }\n k+=1;\n }\n }\n entry[k]='\\0';\nreturn (const char *) entry;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KAddressbook.\n Copyright (c) 2000 Hans Dijkema <kmailcvt@hum.org>\n Copyright (c) 2003 Helge Deller <deller@kde.org>\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; 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. 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <QFile>\n\n#include <kdebug.h>\n#include <kfiledialog.h>\n#include <kio\/netaccess.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <k3process.h>\n#include <kstandarddirs.h>\n#include <ktemporaryfile.h>\n#include <kurl.h>\n\n#include \"xxportmanager.h\"\n\n#include \"pab_xxport.h\"\n\nK_EXPORT_KADDRESSBOOK_XXFILTER( libkaddrbk_pab_xxport, PABXXPort )\n\nPABXXPort::PABXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )\n : KAB::XXPort( ab, parent, name )\n{\n createImportAction( i18n(\"Import MS Exchange Personal Address Book (.PAB)\") );\n}\n\nKABC::Addressee::List PABXXPort::importContacts( const QString& ) const\n{\n KABC::Addressee::List addrList;\n\n QString fileName = KFileDialog::getOpenFileName( QDir::homePath(),\n \t\t\"*.[pP][aA][bB]|\" + i18n(\"MS Exchange Personal Address Book Files (*.pab)\"), 0 );\n if ( fileName.isEmpty() )\n return addrList;\n if ( !QFile::exists( fileName ) ) {\n KMessageBox::sorry( parentWidget(), i18n( \"<qt>Could not find a MS Exchange Personal Address Book <b>%1<\/b>.<\/qt>\", fileName ) );\n return addrList;\n }\n\n \/\/ pab PAB(QFile::encodeName(file),this,info);\n \/\/ info->setFrom(file);\n \/\/ PAB.convert();\n\n return addrList;\n}\n\n#include \"pab_xxport.moc\"\n\n\/\/ vim: ts=2 sw=2 et\n<commit_msg>unnecessary. kaddressbook: check<commit_after>\/*\n This file is part of KAddressbook.\n Copyright (c) 2000 Hans Dijkema <kmailcvt@hum.org>\n Copyright (c) 2003 Helge Deller <deller@kde.org>\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; 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. 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <QFile>\n\n#include <kdebug.h>\n#include <kfiledialog.h>\n#include <kio\/netaccess.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kstandarddirs.h>\n#include <ktemporaryfile.h>\n#include <kurl.h>\n\n#include \"xxportmanager.h\"\n\n#include \"pab_xxport.h\"\n\nK_EXPORT_KADDRESSBOOK_XXFILTER( libkaddrbk_pab_xxport, PABXXPort )\n\nPABXXPort::PABXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )\n : KAB::XXPort( ab, parent, name )\n{\n createImportAction( i18n(\"Import MS Exchange Personal Address Book (.PAB)\") );\n}\n\nKABC::Addressee::List PABXXPort::importContacts( const QString& ) const\n{\n KABC::Addressee::List addrList;\n\n QString fileName = KFileDialog::getOpenFileName( QDir::homePath(),\n \t\t\"*.[pP][aA][bB]|\" + i18n(\"MS Exchange Personal Address Book Files (*.pab)\"), 0 );\n if ( fileName.isEmpty() )\n return addrList;\n if ( !QFile::exists( fileName ) ) {\n KMessageBox::sorry( parentWidget(), i18n( \"<qt>Could not find a MS Exchange Personal Address Book <b>%1<\/b>.<\/qt>\", fileName ) );\n return addrList;\n }\n\n \/\/ pab PAB(QFile::encodeName(file),this,info);\n \/\/ info->setFrom(file);\n \/\/ PAB.convert();\n\n return addrList;\n}\n\n#include \"pab_xxport.moc\"\n\n\/\/ vim: ts=2 sw=2 et\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013 Google Inc. 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:\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 disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. 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\n#include \"config.h\"\n#include \"core\/html\/imports\/HTMLImport.h\"\n\n#include \"core\/dom\/Document.h\"\n#include \"core\/html\/imports\/HTMLImportStateResolver.h\"\n\nnamespace WebCore {\n\nHTMLImport* HTMLImport::root()\n{\n HTMLImport* i = this;\n while (i->parent())\n i = i->parent();\n return i;\n}\n\nbool HTMLImport::precedes(HTMLImport* import)\n{\n for (HTMLImport* i = this; i; i = traverseNext(i)) {\n if (i == import)\n return true;\n }\n\n return false;\n}\n\nbool HTMLImport::formsCycle() const\n{\n for (const HTMLImport* i = this->parent(); i; i = i->parent()) {\n if (i->document() == this->document())\n return true;\n }\n\n return false;\n\n}\n\nvoid HTMLImport::appendImport(HTMLImport* child)\n{\n appendChild(child);\n\n \/\/ This prevents HTML parser from going beyond the\n \/\/ blockage line before the precise state is computed by recalcState().\n if (child->isSync())\n m_state = HTMLImportState::blockedState();\n\n stateWillChange();\n}\n\nvoid HTMLImport::stateDidChange()\n{\n if (!state().shouldBlockScriptExecution()) {\n if (Document* document = this->document())\n document->didLoadAllImports();\n }\n}\n\nvoid HTMLImport::recalcTreeState(HTMLImport* root)\n{\n HashMap<HTMLImport*, HTMLImportState> snapshot;\n Vector<HTMLImport*> updated;\n\n for (HTMLImport* i = root; i; i = traverseNext(i)) {\n snapshot.add(i, i->state());\n i->m_state = HTMLImportState::invalidState();\n }\n\n \/\/ The post-visit DFS order matters here because\n \/\/ HTMLImportStateResolver in recalcState() Depends on\n \/\/ |m_state| of its children and precedents of ancestors.\n \/\/ Accidental cycle dependency of state computation is prevented\n \/\/ by invalidateCachedState() and isStateCacheValid() check.\n for (HTMLImport* i = traverseFirstPostOrder(root); i; i = traverseNextPostOrder(i)) {\n ASSERT(!i->m_state.isValid());\n i->m_state = HTMLImportStateResolver(i).resolve();\n\n HTMLImportState newState = i->state();\n HTMLImportState oldState = snapshot.get(i);\n \/\/ Once the state reaches Ready, it shouldn't go back.\n ASSERT(!oldState.isReady() || oldState <= newState);\n if (newState != oldState)\n updated.append(i);\n }\n\n for (size_t i = 0; i < updated.size(); ++i)\n updated[i]->stateDidChange();\n}\n\n#if !defined(NDEBUG)\nvoid HTMLImport::show()\n{\n root()->showTree(this, 0);\n}\n\nvoid HTMLImport::showTree(HTMLImport* highlight, unsigned depth)\n{\n for (unsigned i = 0; i < depth*4; ++i)\n fprintf(stderr, \" \");\n\n fprintf(stderr, \"%s\", this == highlight ? \"*\" : \" \");\n showThis();\n fprintf(stderr, \"\\n\");\n for (HTMLImport* child = firstChild(); child; child = child->next())\n child->showTree(highlight, depth + 1);\n}\n\nvoid HTMLImport::showThis()\n{\n fprintf(stderr, \"%p state=%d\", this, m_state.peekValueForDebug());\n}\n#endif\n\n} \/\/ namespace WebCore\n<commit_msg>Oilpan: have HTMLImport::recalcTreeState() use on-heap local variables.<commit_after>\/*\n * Copyright (C) 2013 Google Inc. 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:\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 disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. 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\n#include \"config.h\"\n#include \"core\/html\/imports\/HTMLImport.h\"\n\n#include \"core\/dom\/Document.h\"\n#include \"core\/html\/imports\/HTMLImportStateResolver.h\"\n\nnamespace WebCore {\n\nHTMLImport* HTMLImport::root()\n{\n HTMLImport* i = this;\n while (i->parent())\n i = i->parent();\n return i;\n}\n\nbool HTMLImport::precedes(HTMLImport* import)\n{\n for (HTMLImport* i = this; i; i = traverseNext(i)) {\n if (i == import)\n return true;\n }\n\n return false;\n}\n\nbool HTMLImport::formsCycle() const\n{\n for (const HTMLImport* i = this->parent(); i; i = i->parent()) {\n if (i->document() == this->document())\n return true;\n }\n\n return false;\n\n}\n\nvoid HTMLImport::appendImport(HTMLImport* child)\n{\n appendChild(child);\n\n \/\/ This prevents HTML parser from going beyond the\n \/\/ blockage line before the precise state is computed by recalcState().\n if (child->isSync())\n m_state = HTMLImportState::blockedState();\n\n stateWillChange();\n}\n\nvoid HTMLImport::stateDidChange()\n{\n if (!state().shouldBlockScriptExecution()) {\n if (Document* document = this->document())\n document->didLoadAllImports();\n }\n}\n\nvoid HTMLImport::recalcTreeState(HTMLImport* root)\n{\n WillBeHeapHashMap<RawPtrWillBeMember<HTMLImport>, HTMLImportState> snapshot;\n WillBeHeapVector<RawPtrWillBeMember<HTMLImport> > updated;\n\n for (HTMLImport* i = root; i; i = traverseNext(i)) {\n snapshot.add(i, i->state());\n i->m_state = HTMLImportState::invalidState();\n }\n\n \/\/ The post-visit DFS order matters here because\n \/\/ HTMLImportStateResolver in recalcState() Depends on\n \/\/ |m_state| of its children and precedents of ancestors.\n \/\/ Accidental cycle dependency of state computation is prevented\n \/\/ by invalidateCachedState() and isStateCacheValid() check.\n for (HTMLImport* i = traverseFirstPostOrder(root); i; i = traverseNextPostOrder(i)) {\n ASSERT(!i->m_state.isValid());\n i->m_state = HTMLImportStateResolver(i).resolve();\n\n HTMLImportState newState = i->state();\n HTMLImportState oldState = snapshot.get(i);\n \/\/ Once the state reaches Ready, it shouldn't go back.\n ASSERT(!oldState.isReady() || oldState <= newState);\n if (newState != oldState)\n updated.append(i);\n }\n\n for (size_t i = 0; i < updated.size(); ++i)\n updated[i]->stateDidChange();\n}\n\n#if !defined(NDEBUG)\nvoid HTMLImport::show()\n{\n root()->showTree(this, 0);\n}\n\nvoid HTMLImport::showTree(HTMLImport* highlight, unsigned depth)\n{\n for (unsigned i = 0; i < depth*4; ++i)\n fprintf(stderr, \" \");\n\n fprintf(stderr, \"%s\", this == highlight ? \"*\" : \" \");\n showThis();\n fprintf(stderr, \"\\n\");\n for (HTMLImport* child = firstChild(); child; child = child->next())\n child->showTree(highlight, depth + 1);\n}\n\nvoid HTMLImport::showThis()\n{\n fprintf(stderr, \"%p state=%d\", this, m_state.peekValueForDebug());\n}\n#endif\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>#include \"GLPolygonWidget.h\"\n\nGLPolygonWidget::GLPolygonWidget(QWidget* parent, GLPolygon* initialPolygon) :\n\tQGLWidget(parent), polygon(initialPolygon), oldMouseY(0.0f)\n{\n\tsetMouseTracking(true);\n}\n\nvoid GLPolygonWidget::setPolygon(GLPolygon* newPolygon)\n{\n\tpolygon = newPolygon;\n}\n\nvoid GLPolygonWidget::initializeGL()\n{\n\tglClearColor(0.3, 0.3, 0.3, 0.0);\n}\n\nvoid GLPolygonWidget::resizeGL(int width, int height)\n{\n\tglViewport(0, 0, width, height);\n}\n\nvoid GLPolygonWidget::paintGL()\n{\n\tglClear(GL_COLOR_BUFFER_BIT);\n\n\tpolygon->render();\n\n\tglFlush();\n}\n\nbool GLPolygonWidget::processMouseEvent(QMouseEvent* event)\n{\n\tbool changeMade = false; \/\/ set to true if state of polygon changed\n\n\t\/\/ Check which mouse buttons are pressed\n\tif (event->buttons() & Qt::LeftButton) \/\/ if left button pressed\n\t{\n\t\tstatic const float radius = 0.75;\n\t\tfloat newX = (static_cast<float>(event->x()) \/ this->width()) - (radius \/ 2);\n\t\tfloat newY = -(static_cast<float>(event->y()) \/ this->height()) + (radius \/ 2);\n\t\tpolygon->setX(newX);\n\t\tpolygon->setY(newY);\n\t\tchangeMade = true;\n\t}\n\tif (event->buttons() & Qt::RightButton) \/\/ if right button pressed\n\t{\n\t\tfloat difference = oldMouseY - event->y();\n\t\tfloat newDegrees = polygon->rotationDegrees() + difference;\n\t\tpolygon->setRotationDegrees(newDegrees);\n\t\tchangeMade = true;\n\t}\n\n\t\/\/ If no mouse button pressed and no change made, just return false\n\tif (!changeMade) return false;\n\n\t\/\/ Ensure polygon does not go out of bounds\n\tif (polygon->x() < -1.0f) polygon->setX(-1.0f);\n\telse if (polygon->x() > 1.0f) polygon->setX(1.0f);\n\tif (polygon->y() < -1.0f) polygon->setY(-1.0f);\n\telse if (polygon->y() > 1.0f) polygon->setY(1.0f);\n\tif (polygon->rotationDegrees() < 0.0f || polygon->rotationDegrees() > 360.0f)\n\t\tpolygon->setRotationDegrees(0.0f);\n\t\n\t\/\/ Accept event so it's not processed further and redraw widget to reflect changes\n\tevent->accept();\n\t\/\/ Also keep track of the Y value for later use\n\toldMouseY = event->y();\n\n\treturn true; \/\/ change made to return true\n}\n\nvoid GLPolygonWidget::mouseMoveEvent(QMouseEvent* event)\n{\n\tif (processMouseEvent(event))\n\t\temit changed();\n}\n\nvoid GLPolygonWidget::mousePressEvent(QMouseEvent* event)\n{\n\tif (processMouseEvent(event))\n\t\temit changed();\n}\n<commit_msg>Added depth to OpenGL rendering<commit_after>#include \"GLPolygonWidget.h\"\n\nGLPolygonWidget::GLPolygonWidget(QWidget* parent, GLPolygon* initialPolygon) :\n\tQGLWidget(parent), polygon(initialPolygon), oldMouseY(0.0f)\n{\n\tsetMouseTracking(true);\n}\n\nvoid GLPolygonWidget::setPolygon(GLPolygon* newPolygon)\n{\n\tpolygon = newPolygon;\n}\n\nvoid GLPolygonWidget::initializeGL()\n{\n\tglClearColor(0.3, 0.3, 0.3, 0.0);\n\tglEnable(GL_DEPTH_TEST);\n\tglDepthFunc(GL_LEQUAL);\n}\n\nvoid GLPolygonWidget::resizeGL(int width, int height)\n{\n\tglViewport(0, 0, width, height);\n}\n\nvoid GLPolygonWidget::paintGL()\n{\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tpolygon->render();\n\n\tglFlush();\n}\n\nbool GLPolygonWidget::processMouseEvent(QMouseEvent* event)\n{\n\tbool changeMade = false; \/\/ set to true if state of polygon changed\n\n\t\/\/ Check which mouse buttons are pressed\n\tif (event->buttons() & Qt::LeftButton) \/\/ if left button pressed\n\t{\n\t\tstatic const float radius = 0.75;\n\t\tfloat newX = (static_cast<float>(event->x()) \/ this->width()) - (radius \/ 2);\n\t\tfloat newY = -(static_cast<float>(event->y()) \/ this->height()) + (radius \/ 2);\n\t\tpolygon->setX(newX);\n\t\tpolygon->setY(newY);\n\t\tchangeMade = true;\n\t}\n\tif (event->buttons() & Qt::RightButton) \/\/ if right button pressed\n\t{\n\t\tfloat difference = oldMouseY - event->y();\n\t\tfloat newDegrees = polygon->rotationDegrees() + difference;\n\t\tpolygon->setRotationDegrees(newDegrees);\n\t\tchangeMade = true;\n\t}\n\n\t\/\/ If no mouse button pressed and no change made, just return false\n\tif (!changeMade) return false;\n\n\t\/\/ Ensure polygon does not go out of bounds\n\tif (polygon->x() < -1.0f) polygon->setX(-1.0f);\n\telse if (polygon->x() > 1.0f) polygon->setX(1.0f);\n\tif (polygon->y() < -1.0f) polygon->setY(-1.0f);\n\telse if (polygon->y() > 1.0f) polygon->setY(1.0f);\n\tif (polygon->rotationDegrees() < 0.0f || polygon->rotationDegrees() > 360.0f)\n\t\tpolygon->setRotationDegrees(0.0f);\n\t\n\t\/\/ Accept event so it's not processed further and redraw widget to reflect changes\n\tevent->accept();\n\t\/\/ Also keep track of the Y value for later use\n\toldMouseY = event->y();\n\n\treturn true; \/\/ change made to return true\n}\n\nvoid GLPolygonWidget::mouseMoveEvent(QMouseEvent* event)\n{\n\tif (processMouseEvent(event))\n\t\temit changed();\n}\n\nvoid GLPolygonWidget::mousePressEvent(QMouseEvent* event)\n{\n\tif (processMouseEvent(event))\n\t\temit changed();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012-2013 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n * \n * BrewPi 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 3 of the License, or\n * (at your option) any later version.\n * \n * BrewPi 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 BrewPi. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"Platform.h\"\n#include \"Brewpi.h\"\n#include \"Ticks.h\"\n#include \"Display.h\"\n#include \"TempControl.h\"\n#include \"PiLink.h\"\n#include \"TempSensor.h\"\n#include \"TempSensorMock.h\"\n#include \"TempSensorExternal.h\"\n#include \"ActuatorMocks.h\"\n#include \"Sensor.h\"\n#include \"SettingsManager.h\"\n#include \"UI.h\"\n\n#if BREWPI_SIMULATE\n\t#include \"Simulator.h\"\n#endif\n\n\/\/ global class objects static and defined in class cpp and h files\n\n\/\/ instantiate and configure the sensors, actuators and controllers we want to use\n\n\nvoid setup(void);\nvoid loop (void);\n\n\/* Configure the counter and delay timer. The actual type of these will vary depending upon the environment.\n * They are non-virtual to keep code size minimal, so typedefs and preprocessing are used to select the actual compile-time type used. *\/\nTicksImpl ticks = TicksImpl(TICKS_IMPL_CONFIG);\nDelayImpl wait = DelayImpl(DELAY_IMPL_CONFIG);\n\nUI ui;\n\nvoid setup()\n{\n boardInit();\n bool resetEeprom = platform_init();\n eepromManager.init();\n if (resetEeprom) {\n eepromManager.initializeEeprom();\n }\n\tui.init();\n\tpiLink.init();\n\t\/\/ flush any waiting input.\n \/\/ Linux can put garbage in the serial input buffer during connect\n piLink.flushInput();\n\n logDebug(\"started\");\n\n uint32_t start = ticks.millis();\n uint32_t delay = ui.showStartupPage();\n while (ticks.millis()-start <= delay) {\n ui.ticks();\n }\n \n \/\/ initialize OneWire\n if (!primaryOneWireBus.init()) {\n logError(ERROR_ONEWIRE_INIT_FAILED);\n }\n\n#if BREWPI_SIMULATE\n\tsimulator.step();\n\t\/\/ initialize the filters with the assigned initial temp value\n\t\/\/tempControl.beerSensor->init();\n\t\/\/tempControl.fridgeSensor->init();\n#endif\t\n settingsManager.loadSettings();\n\n control.update();\n\n ui.showControllerPage();\n \t\t\t\n\tlogDebug(\"init complete\");\n}\n\nvoid brewpiLoop(void)\n{\n\tstatic unsigned long lastUpdate = -1000; \/\/ init at -1000 to update immediately\n ui.ticks();\n \n if(!ui.inStartup() && (ticks.millis() - lastUpdate >= (1000))) { \/\/update settings every second\n\t\tlastUpdate = ticks.millis();\n\t\tcontrol.update();\n ui.update();\n }\n\n control.fastUpdate(); \/\/ update actuators as often as possible for PWM\n\n \/\/listen for incoming serial connections while waiting to update\n piLink.receive();\n}\n\nvoid loop() {\n\t#if BREWPI_SIMULATE\n\tsimulateLoop();\n\t#else\n\tbrewpiLoop();\n\t#endif\n}\n\n<commit_msg>show startup screen before serial\/wifi init<commit_after>\/*\n * Copyright 2012-2013 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n * \n * BrewPi 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 3 of the License, or\n * (at your option) any later version.\n * \n * BrewPi 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 BrewPi. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"Platform.h\"\n#include \"Brewpi.h\"\n#include \"Ticks.h\"\n#include \"Display.h\"\n#include \"TempControl.h\"\n#include \"PiLink.h\"\n#include \"TempSensor.h\"\n#include \"TempSensorMock.h\"\n#include \"TempSensorExternal.h\"\n#include \"ActuatorMocks.h\"\n#include \"Sensor.h\"\n#include \"SettingsManager.h\"\n#include \"UI.h\"\n\n#if BREWPI_SIMULATE\n\t#include \"Simulator.h\"\n#endif\n\n\/\/ global class objects static and defined in class cpp and h files\n\n\/\/ instantiate and configure the sensors, actuators and controllers we want to use\n\n\nvoid setup(void);\nvoid loop (void);\n\n\/* Configure the counter and delay timer. The actual type of these will vary depending upon the environment.\n * They are non-virtual to keep code size minimal, so typedefs and preprocessing are used to select the actual compile-time type used. *\/\nTicksImpl ticks = TicksImpl(TICKS_IMPL_CONFIG);\nDelayImpl wait = DelayImpl(DELAY_IMPL_CONFIG);\n\nUI ui;\n\nvoid setup()\n{\n boardInit();\n bool resetEeprom = platform_init();\n eepromManager.init();\n if (resetEeprom) {\n eepromManager.initializeEeprom();\n }\n\tui.init();\n\n uint32_t start = ticks.millis();\n uint32_t delay = ui.showStartupPage();\n\n piLink.init();\n \/\/ flush any waiting input.\n \/\/ Linux can put garbage in the serial input buffer during connect\n piLink.flushInput();\n\n logDebug(\"started\");\n\n while (ticks.millis()-start <= delay) {\n ui.ticks();\n }\n \n \/\/ initialize OneWire\n if (!primaryOneWireBus.init()) {\n logError(ERROR_ONEWIRE_INIT_FAILED);\n }\n\n#if BREWPI_SIMULATE\n\tsimulator.step();\n\t\/\/ initialize the filters with the assigned initial temp value\n\t\/\/tempControl.beerSensor->init();\n\t\/\/tempControl.fridgeSensor->init();\n#endif\t\n settingsManager.loadSettings();\n\n control.update();\n\n ui.showControllerPage();\n \t\t\t\n\tlogDebug(\"init complete\");\n}\n\nvoid brewpiLoop(void)\n{\n\tstatic unsigned long lastUpdate = -1000; \/\/ init at -1000 to update immediately\n ui.ticks();\n \n if(!ui.inStartup() && (ticks.millis() - lastUpdate >= (1000))) { \/\/update settings every second\n\t\tlastUpdate = ticks.millis();\n\t\tcontrol.update();\n ui.update();\n }\n\n control.fastUpdate(); \/\/ update actuators as often as possible for PWM\n\n \/\/listen for incoming serial connections while waiting to update\n piLink.receive();\n}\n\nvoid loop() {\n\t#if BREWPI_SIMULATE\n\tsimulateLoop();\n\t#else\n\tbrewpiLoop();\n\t#endif\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Client.h\"\n\n\/*\nCopyright (C) 2016 AGC.\n\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as\npublished by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\nusing namespace x801::game;\n\n#include <algorithm>\n#include <iostream>\n#include <GLFW\/glfw3.h>\n#include <BitStream.h>\n#include <SecureHandshake.h>\n\nvoid x801::game::Client::initialise() {\n peer = RakNet::RakPeerInterface::GetInstance();\n RakNet::SocketDescriptor clientSocket(0, 0);\n clientSocket.socketFamily = useIPV6 ? AF_INET6 : AF_INET;\n peer->Startup(1, &clientSocket, 1);\n peer->SetOccasionalPing(true);\n RakNet::PublicKey pk;\n pk.publicKeyMode = RakNet::PKM_ACCEPT_ANY_PUBLIC_KEY;\n publicKey = new char[cat::EasyHandshake::PUBLIC_KEY_BYTES];\n pk.remoteServerPublicKey = publicKey;\n auto status = peer->Connect(ipAddress.c_str(), port, nullptr, 0, &pk);\n if (status != RakNet::CONNECTION_ATTEMPT_STARTED) {\n throw \"Connection failed...\";\n }\n \/\/ set packet callbacks\n PacketCallback logoutCallback = {\n [](\n uint8_t packetType,\n uint8_t* body, size_t length,\n RakNet::Packet* p) {\n (void) packetType; (void) body; (void) length; (void) p;\n std::cout << \"You have been disconnected.\";\n }, -1\n };\n callbacks.insert({ID_CONNECTION_LOST, logoutCallback});\n callbacks.insert({ID_DISCONNECTION_NOTIFICATION, logoutCallback});\n PacketCallback connectCallback = {\n [this](\n uint8_t packetType,\n uint8_t* body, size_t length,\n RakNet::Packet* p) {\n (void) packetType; (void) body; (void) length; (void) p;\n std::cout << \"MOTD:\\n\";\n this->requestMOTD();\n }, -1\n };\n callbacks.insert({ID_CONNECTION_REQUEST_ACCEPTED, connectCallback});\n openWindowConcurrent();\n listen();\n}\n\nbool x801::game::Client::handlePacket(\n uint8_t packetType,\n uint8_t* body, size_t length,\n RakNet::Packet* p) {\n (void) body; (void) length; (void) p;\n std::cerr << \"It's a packet! ID = \" << (int) packetType << \"\\n\";\n switch (packetType) {\n case ID_NO_FREE_INCOMING_CONNECTIONS:\n std::cout << \"The server is full.\\n\";\n return false;\n case ID_CONNECTION_LOST:\n case ID_DISCONNECTION_NOTIFICATION:\n std::cout << \"Connection lost.\\n\";\n return false;\n case ID_CONNECTION_ATTEMPT_FAILED:\n std::cout << \"Failed to connect to server.\\n\";\n return false;\n }\n auto range = callbacks.equal_range(packetType);\n for (auto iterator = range.first; iterator != range.second;) {\n (iterator->second.call)(packetType, body, length, p);\n if (iterator->second.timesLeft != -1) --iterator->second.timesLeft;\n if (iterator->second.timesLeft == 0) iterator = callbacks.erase(iterator);\n else ++iterator;\n }\n return true;\n}\nbool x801::game::Client::handleLPacket(\n uint16_t lPacketType,\n uint8_t* lbody, size_t llength,\n RakNet::Packet* p) {\n \/\/ TODO implement\n (void) lbody; (void) llength; (void) p;\n std::cerr << \"It's an lpacket!\\n\";\n switch (lPacketType) {\n \/\/\n }\n auto range = lCallbacks.equal_range(lPacketType);\n for (auto iterator = range.first; iterator != range.second;) {\n (iterator->second.call)(lPacketType, nullptr, lbody, llength, p);\n if (iterator->second.timesLeft != -1) --iterator->second.timesLeft;\n if (iterator->second.timesLeft == 0) iterator = lCallbacks.erase(iterator);\n else ++iterator;\n }\n return true;\n}\n\nvoid x801::game::Client::listen() {\n bool shouldContinue = true;\n while (shouldContinue) {\n for (\n RakNet::Packet* p = peer->Receive();\n p != nullptr;\n peer->DeallocatePacket(p), p = peer->Receive()) {\n uint8_t packetType = getPacketType(p);\n size_t offset = getPacketOffset(p);\n uint8_t* body = p->data + offset;\n size_t length = p->length - offset;\n if (packetType == PACKET_IM_LOGGED_IN) {\n uint16_t lpacketType = (body[0] << 8) | body[1];\n uint8_t* lbody = body + 2;\n size_t llength = length - 2;\n shouldContinue = handleLPacket(lpacketType, lbody, llength, p);\n } else {\n shouldContinue = handlePacket(packetType, body, length, p);\n }\n }\n }\n if (cw != nullptr) glfwSetWindowShouldClose(cw->underlying(), true);\n}\n\nvoid x801::game::Client::requestMOTD(PacketCallback motdCallback) {\n RakNet::BitStream stream;\n stream.Write(static_cast<uint8_t>(PACKET_MOTD));\n peer->Send(\n &stream, HIGH_PRIORITY, RELIABLE_ORDERED, 0,\n RakNet::UNASSIGNED_RAKNET_GUID, true\n );\n callbacks.insert({PACKET_MOTD, motdCallback});\n}\n\nvoid x801::game::Client::requestMOTD() {\n PacketCallback motdCallback = {\n [this](\n uint8_t packetType,\n uint8_t* body, size_t length,\n RakNet::Packet* p) {\n (void) packetType; (void) p;\n RakNet::BitStream stream(body, length, false);\n const char* s = readStringFromBitstream32(stream);\n std::cout << s << '\\n';\n delete[] s;\n }, 1\n };\n requestMOTD(motdCallback);\n}\n\nvoid x801::game::Client::openWindow() {\n cw = new ClientWindow(1024, 768, 0, 0, \"Experiment801\", 3, 3, false);\n cw->c = this;\n cw->start();\n}\n\nvoid x801::game::Client::openWindowConcurrent() {\n windowThread = std::thread([this]() { this->openWindow(); });\n}\n\nx801::game::Client::~Client() {\n done = true;\n RakNet::RakPeerInterface::DestroyInstance(peer);\n delete[] publicKey;\n}\n<commit_msg>Reorder callback registration and packet sending in requestMOTD<commit_after>#include \"Client.h\"\n\n\/*\nCopyright (C) 2016 AGC.\n\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as\npublished by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\nusing namespace x801::game;\n\n#include <algorithm>\n#include <iostream>\n#include <GLFW\/glfw3.h>\n#include <BitStream.h>\n#include <SecureHandshake.h>\n\nvoid x801::game::Client::initialise() {\n peer = RakNet::RakPeerInterface::GetInstance();\n RakNet::SocketDescriptor clientSocket(0, 0);\n clientSocket.socketFamily = useIPV6 ? AF_INET6 : AF_INET;\n peer->Startup(1, &clientSocket, 1);\n peer->SetOccasionalPing(true);\n RakNet::PublicKey pk;\n pk.publicKeyMode = RakNet::PKM_ACCEPT_ANY_PUBLIC_KEY;\n publicKey = new char[cat::EasyHandshake::PUBLIC_KEY_BYTES];\n pk.remoteServerPublicKey = publicKey;\n auto status = peer->Connect(ipAddress.c_str(), port, nullptr, 0, &pk);\n if (status != RakNet::CONNECTION_ATTEMPT_STARTED) {\n throw \"Connection failed...\";\n }\n \/\/ set packet callbacks\n PacketCallback logoutCallback = {\n [](\n uint8_t packetType,\n uint8_t* body, size_t length,\n RakNet::Packet* p) {\n (void) packetType; (void) body; (void) length; (void) p;\n std::cout << \"You have been disconnected.\";\n }, -1\n };\n callbacks.insert({ID_CONNECTION_LOST, logoutCallback});\n callbacks.insert({ID_DISCONNECTION_NOTIFICATION, logoutCallback});\n PacketCallback connectCallback = {\n [this](\n uint8_t packetType,\n uint8_t* body, size_t length,\n RakNet::Packet* p) {\n (void) packetType; (void) body; (void) length; (void) p;\n std::cout << \"MOTD:\\n\";\n this->requestMOTD();\n }, -1\n };\n callbacks.insert({ID_CONNECTION_REQUEST_ACCEPTED, connectCallback});\n openWindowConcurrent();\n listen();\n}\n\nbool x801::game::Client::handlePacket(\n uint8_t packetType,\n uint8_t* body, size_t length,\n RakNet::Packet* p) {\n (void) body; (void) length; (void) p;\n std::cerr << \"It's a packet! ID = \" << (int) packetType << \"\\n\";\n switch (packetType) {\n case ID_NO_FREE_INCOMING_CONNECTIONS:\n std::cout << \"The server is full.\\n\";\n return false;\n case ID_CONNECTION_LOST:\n case ID_DISCONNECTION_NOTIFICATION:\n std::cout << \"Connection lost.\\n\";\n return false;\n case ID_CONNECTION_ATTEMPT_FAILED:\n std::cout << \"Failed to connect to server.\\n\";\n return false;\n }\n auto range = callbacks.equal_range(packetType);\n for (auto iterator = range.first; iterator != range.second;) {\n (iterator->second.call)(packetType, body, length, p);\n if (iterator->second.timesLeft != -1) --iterator->second.timesLeft;\n if (iterator->second.timesLeft == 0) iterator = callbacks.erase(iterator);\n else ++iterator;\n }\n return true;\n}\nbool x801::game::Client::handleLPacket(\n uint16_t lPacketType,\n uint8_t* lbody, size_t llength,\n RakNet::Packet* p) {\n \/\/ TODO implement\n (void) lbody; (void) llength; (void) p;\n std::cerr << \"It's an lpacket!\\n\";\n switch (lPacketType) {\n \/\/\n }\n auto range = lCallbacks.equal_range(lPacketType);\n for (auto iterator = range.first; iterator != range.second;) {\n (iterator->second.call)(lPacketType, nullptr, lbody, llength, p);\n if (iterator->second.timesLeft != -1) --iterator->second.timesLeft;\n if (iterator->second.timesLeft == 0) iterator = lCallbacks.erase(iterator);\n else ++iterator;\n }\n return true;\n}\n\nvoid x801::game::Client::listen() {\n bool shouldContinue = true;\n while (shouldContinue) {\n for (\n RakNet::Packet* p = peer->Receive();\n p != nullptr;\n peer->DeallocatePacket(p), p = peer->Receive()) {\n uint8_t packetType = getPacketType(p);\n size_t offset = getPacketOffset(p);\n uint8_t* body = p->data + offset;\n size_t length = p->length - offset;\n if (packetType == PACKET_IM_LOGGED_IN) {\n uint16_t lpacketType = (body[0] << 8) | body[1];\n uint8_t* lbody = body + 2;\n size_t llength = length - 2;\n shouldContinue = handleLPacket(lpacketType, lbody, llength, p);\n } else {\n shouldContinue = handlePacket(packetType, body, length, p);\n }\n }\n }\n if (cw != nullptr) glfwSetWindowShouldClose(cw->underlying(), true);\n}\n\nvoid x801::game::Client::requestMOTD(PacketCallback motdCallback) {\n RakNet::BitStream stream;\n stream.Write(static_cast<uint8_t>(PACKET_MOTD));\n callbacks.insert({PACKET_MOTD, motdCallback});\n peer->Send(\n &stream, HIGH_PRIORITY, RELIABLE_ORDERED, 0,\n RakNet::UNASSIGNED_RAKNET_GUID, true\n );\n}\n\nvoid x801::game::Client::requestMOTD() {\n PacketCallback motdCallback = {\n [this](\n uint8_t packetType,\n uint8_t* body, size_t length,\n RakNet::Packet* p) {\n (void) packetType; (void) p;\n RakNet::BitStream stream(body, length, false);\n const char* s = readStringFromBitstream32(stream);\n std::cout << s << '\\n';\n delete[] s;\n }, 1\n };\n requestMOTD(motdCallback);\n}\n\nvoid x801::game::Client::openWindow() {\n cw = new ClientWindow(1024, 768, 0, 0, \"Experiment801\", 3, 3, false);\n cw->c = this;\n cw->start();\n}\n\nvoid x801::game::Client::openWindowConcurrent() {\n windowThread = std::thread([this]() { this->openWindow(); });\n}\n\nx801::game::Client::~Client() {\n done = true;\n RakNet::RakPeerInterface::DestroyInstance(peer);\n delete[] publicKey;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Core\/Serialization.h>\n#include \"Mappers.h\"\n\nnamespace\n{\n static const uint32_t ROM_BANK_SIZE = 0x4000;\n\n static const uint32_t BANK_SIZE_EXTERNAL_RAM = 0x2000;\n\n static const uint8_t MBC1_RAM_ENABLE_MASK = 0x0f;\n static const uint8_t MBC1_RAM_ENABLE_VALUE = 0x0a;\n\n static const uint8_t MBC1_ROM_BANK_LOW_MASK = 0x1f;\n static const uint8_t MBC1_ROM_BANK_HIGH_VALID = 0x60;\n static const uint8_t MBC1_ROM_BANK_HIGH_MASK = 0x60;\n static const uint8_t MBC1_ROM_BANK_HIGH_SHIFT = 5;\n static const uint8_t MBC1_ROM_BANK_INVALID_MASK = 0x1f;\n static const uint8_t MBC1_ROM_BANK_INVALID_ADJ = 0x01;\n\n static const uint8_t MBC1_RAM_BANK_MODE = 0x01;\n\n static const uint8_t MBC5_RAM_ENABLE_MASK = 0x0f;\n static const uint8_t MBC5_RAM_ENABLE_VALUE = 0x0a;\n\n static const uint16_t MBC5_ROM_BANK_LOW_MASK = 0x00ff;\n static const uint16_t MBC5_ROM_BANK_HIGH_MASK = 0x0100;\n static const uint16_t MBC5_ROM_BANK_HIGH_SHIFT = 8;\n\n uint8_t read8null(void* context, int32_t tick, uint32_t addr)\n {\n EMU_INVOKE_ONCE(printf(\"External RAM read disabled!\\n\"));\n return 0;\n }\n\n void write8null(void* context, int32_t tick, uint32_t addr, uint8_t value)\n {\n EMU_INVOKE_ONCE(printf(\"External RAM write disabled!\\n\"));\n }\n}\n\nnamespace gb\n{\n MapperBase::MapperBase()\n {\n initialize();\n }\n\n MapperBase::~MapperBase()\n {\n destroy();\n }\n\n void MapperBase::initialize()\n {\n mRom = nullptr;\n mMemory = nullptr;\n mEnableExternalRAM = false;\n }\n\n bool MapperBase::create(const Rom& rom, emu::MemoryBus& memory)\n {\n mRom = &rom;\n mMemory = &memory;\n\n const auto& desc = rom.getDescription();\n uint8_t* pRAM = nullptr;\n if (desc.hasRam)\n {\n mExternalRAM.resize(desc.ramSize, 0);\n pRAM = mExternalRAM.data();\n }\n\n const uint8_t* pROM = mRom->getContent().rom;\n for (uint32_t bank = 0, offset = 0; bank < EMU_ARRAY_SIZE(mBankMapROM); ++bank, offset += ROM_BANK_SIZE)\n {\n if (offset >= desc.romSize)\n offset = 0;\n mBankMapROM[bank] = pROM + offset;\n }\n for (uint32_t bank = 0, offset = 0; bank < EMU_ARRAY_SIZE(mBankMapRAM); ++bank, offset += BANK_SIZE_EXTERNAL_RAM)\n {\n if (offset >= desc.ramSize)\n offset = 0;\n mBankMapRAM[bank] = pRAM + offset;\n }\n\n reset();\n\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_READ, 0x0000, 0x3fff, mMemoryROM[0]));\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_READ, 0x4000, 0x7fff, mMemoryROM[1]));\n uint16_t size = 0;\n if (!mExternalRAM.empty())\n {\n uint16_t size = static_cast<uint16_t>(mExternalRAM.size());\n if (size > BANK_SIZE_EXTERNAL_RAM)\n size = BANK_SIZE_EXTERNAL_RAM;\n EMU_VERIFY(mMemory->addMemoryRange(0xa000, 0xa000 + size - 1, mMemoryExternalRAM));\n }\n if (size < BANK_SIZE_EXTERNAL_RAM)\n {\n EMU_VERIFY(mMemory->addMemoryRange(0xa000, 0xa000 + BANK_SIZE_EXTERNAL_RAM - size - 1, mMemoryExternalRAMEmpty));\n }\n return true;\n }\n\n void MapperBase::destroy()\n {\n mExternalRAM.clear();\n initialize();\n }\n\n void MapperBase::reset()\n {\n mBankROM[0] = 0;\n mBankROM[1] = 1;\n mBankExternalRAM = 0xff;\n mEnableExternalRAM = false;\n updateMemoryMap();\n }\n\n void MapperBase::enableRam(bool enable)\n {\n mEnableExternalRAM = enable;\n }\n\n bool MapperBase::updateMemoryMap()\n {\n mMemoryROM[0].setReadMemory(mBankMapROM[mBankROM[0]]);\n mMemoryROM[1].setReadMemory(mBankMapROM[mBankROM[1]]);\n if (!mExternalRAM.empty() && (mEnableExternalRAM || !mRom->getDescription().hasBattery))\n {\n mMemoryExternalRAM.setReadWriteMemory(mBankMapRAM[mBankExternalRAM]);\n }\n else\n {\n mMemoryExternalRAM.read.setReadMethod(&read8null, this);\n mMemoryExternalRAM.write.setWriteMethod(&write8null, this);\n }\n mMemoryExternalRAMEmpty.read.setReadMethod(&read8null, this);\n mMemoryExternalRAMEmpty.write.setWriteMethod(&write8null, this);\n return true;\n }\n\n void MapperBase::serializeGameData(emu::ISerializer& serializer)\n {\n if (mRom->getDescription().hasBattery)\n serializer.serialize(mExternalRAM);\n }\n\n void MapperBase::serializeGameState(emu::ISerializer& serializer)\n {\n serializer.serialize(mExternalRAM);\n serializer.serialize(mBankROM, EMU_ARRAY_SIZE(mBankROM));\n serializer.serialize(mBankExternalRAM);\n serializer.serialize(mEnableExternalRAM);\n updateMemoryMap();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MapperROM::MapperROM()\n {\n }\n\n bool MapperROM::create(const Rom& rom, emu::MemoryBus& memory)\n {\n EMU_VERIFY(MapperBase::create(rom, memory));\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_WRITE, 0x0000, 0x7fff, mMemoryControlRegs.setWriteMethod(&write8, this)));\n return true;\n }\n\n void MapperROM::write8(void* context, int32_t tick, uint32_t addr, uint8_t value)\n {\n EMU_NOT_IMPLEMENTED();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MapperMBC1::MapperMBC1()\n {\n }\n\n bool MapperMBC1::create(const Rom& rom, emu::MemoryBus& memory)\n {\n EMU_VERIFY(MapperBase::create(rom, memory));\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_WRITE, 0x0000, 0x7fff, mMemoryControlRegs.setWriteMethod(&MapperMBC1::write8, this)));\n return true;\n }\n\n void MapperMBC1::reset()\n {\n mBankROM = 0;\n mBankRAM = 0;\n mRamBankMode = false;\n MapperBase::reset();\n }\n\n void MapperMBC1::serializeGameState(emu::ISerializer& serializer)\n {\n serializer.serialize(mBankROM);\n serializer.serialize(mBankRAM);\n serializer.serialize(mRamBankMode);\n MapperBase::serializeGameState(serializer);\n }\n\n bool MapperMBC1::updateMemoryMap()\n {\n uint8_t validBankROM = mBankROM;\n if ((validBankROM & MBC1_ROM_BANK_INVALID_MASK) == 0)\n validBankROM |= MBC1_ROM_BANK_INVALID_ADJ;\n setRomBank(validBankROM);\n setRamBank(mBankRAM);\n return MapperBase::updateMemoryMap();\n }\n\n void MapperMBC1::write8(int32_t tick, uint32_t addr, uint8_t value)\n {\n switch (addr >> 13)\n {\n case 0:\n {\n bool enable = (value & MBC1_RAM_ENABLE_MASK) == MBC1_RAM_ENABLE_VALUE;\n enableRam(enable);\n break;\n }\n case 1:\n {\n mBankROM = (mBankROM & ~MBC1_ROM_BANK_LOW_MASK) | (value & MBC1_ROM_BANK_LOW_MASK);\n break;\n }\n case 2:\n {\n value = value & MBC1_ROM_BANK_HIGH_VALID;\n if (mRamBankMode)\n {\n mBankRAM = value;\n }\n else\n {\n mBankROM = (mBankROM & ~MBC1_ROM_BANK_HIGH_MASK) | ((value << MBC1_ROM_BANK_HIGH_SHIFT) & MBC1_ROM_BANK_HIGH_MASK);\n }\n break;\n }\n case 3:\n {\n mRamBankMode = (value & MBC1_RAM_BANK_MODE) != 0;\n break;\n }\n default:\n EMU_ASSERT(false);\n }\n updateMemoryMap();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MapperMBC5::MapperMBC5()\n {\n }\n\n bool MapperMBC5::create(const Rom& rom, emu::MemoryBus& memory)\n {\n EMU_VERIFY(MapperBase::create(rom, memory));\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_WRITE, 0x0000, 0x7fff, mMemoryControlRegs.setWriteMethod(&MapperMBC5::write8, this)));\n return true;\n }\n\n void MapperMBC5::reset()\n {\n mRamBankMode = false;\n MapperBase::reset();\n }\n\n void MapperMBC5::serializeGameState(emu::ISerializer& serializer)\n {\n serializer.serialize(mRamBankMode);\n MapperBase::serializeGameState(serializer);\n }\n\n bool MapperMBC5::updateMemoryMap()\n {\n return MapperBase::updateMemoryMap();\n }\n\n void MapperMBC5::write8(int32_t tick, uint32_t addr, uint8_t value)\n {\n switch (addr >> 12)\n {\n case 0:\n case 1:\n {\n bool enable = (value & MBC5_RAM_ENABLE_MASK) == MBC5_RAM_ENABLE_VALUE;\n enableRam(enable);\n break;\n }\n case 2:\n {\n uint16_t bank = getRomBank();\n bank = (bank & ~MBC5_ROM_BANK_LOW_MASK) | (value & MBC5_ROM_BANK_LOW_MASK);\n setRomBank(bank);\n break;\n }\n case 3:\n {\n uint16_t bank = getRomBank();\n bank = (bank & ~MBC5_ROM_BANK_HIGH_MASK) | ((value << MBC5_ROM_BANK_HIGH_SHIFT) & MBC5_ROM_BANK_HIGH_MASK);\n setRomBank(bank);\n break;\n }\n case 4:\n case 5:\n {\n setRamBank(value);\n break;\n }\n default:\n break;\n }\n\n updateMemoryMap();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n IMapper* createMapper(const Rom& rom, emu::MemoryBus& memory)\n {\n const auto& desc = rom.getDescription();\n\n switch (desc.mapper)\n {\n case Rom::Mapper::ROM:\n {\n auto mapper = new MapperROM();\n if (mapper->create(rom, memory))\n return mapper;\n delete mapper;\n break;\n }\n\n case Rom::Mapper::MBC1:\n {\n auto mapper = new MapperMBC1();\n if (mapper->create(rom, memory))\n return mapper;\n delete mapper;\n break;\n }\n\n case Rom::Mapper::MBC5:\n {\n auto mapper = new MapperMBC5();\n if (mapper->create(rom, memory))\n return mapper;\n delete mapper;\n break;\n }\n\n default:\n EMU_NOT_IMPLEMENTED();\n }\n return nullptr;\n }\n}\n<commit_msg>Fix a external RAM mapping issues.<commit_after>#include <Core\/Serialization.h>\n#include \"Mappers.h\"\n\nnamespace\n{\n static const uint32_t ROM_BANK_SIZE = 0x4000;\n\n static const uint32_t BANK_SIZE_EXTERNAL_RAM = 0x2000;\n\n static const uint8_t MBC1_RAM_ENABLE_MASK = 0x0f;\n static const uint8_t MBC1_RAM_ENABLE_VALUE = 0x0a;\n\n static const uint8_t MBC1_ROM_BANK_LOW_MASK = 0x1f;\n static const uint8_t MBC1_ROM_BANK_HIGH_VALID = 0x60;\n static const uint8_t MBC1_ROM_BANK_HIGH_MASK = 0x60;\n static const uint8_t MBC1_ROM_BANK_HIGH_SHIFT = 5;\n static const uint8_t MBC1_ROM_BANK_INVALID_MASK = 0x1f;\n static const uint8_t MBC1_ROM_BANK_INVALID_ADJ = 0x01;\n\n static const uint8_t MBC1_RAM_BANK_MODE = 0x01;\n\n static const uint8_t MBC5_RAM_ENABLE_MASK = 0x0f;\n static const uint8_t MBC5_RAM_ENABLE_VALUE = 0x0a;\n\n static const uint16_t MBC5_ROM_BANK_LOW_MASK = 0x00ff;\n static const uint16_t MBC5_ROM_BANK_HIGH_MASK = 0x0100;\n static const uint16_t MBC5_ROM_BANK_HIGH_SHIFT = 8;\n\n uint8_t read8null(void* context, int32_t tick, uint32_t addr)\n {\n EMU_INVOKE_ONCE(printf(\"External RAM read disabled!\\n\"));\n return 0;\n }\n\n void write8null(void* context, int32_t tick, uint32_t addr, uint8_t value)\n {\n EMU_INVOKE_ONCE(printf(\"External RAM write disabled!\\n\"));\n }\n}\n\nnamespace gb\n{\n MapperBase::MapperBase()\n {\n initialize();\n }\n\n MapperBase::~MapperBase()\n {\n destroy();\n }\n\n void MapperBase::initialize()\n {\n mRom = nullptr;\n mMemory = nullptr;\n mEnableExternalRAM = false;\n }\n\n bool MapperBase::create(const Rom& rom, emu::MemoryBus& memory)\n {\n mRom = &rom;\n mMemory = &memory;\n\n const auto& desc = rom.getDescription();\n uint8_t* pRAM = nullptr;\n if (desc.hasRam)\n {\n mExternalRAM.resize(desc.ramSize, 0);\n pRAM = mExternalRAM.data();\n }\n\n const uint8_t* pROM = mRom->getContent().rom;\n for (uint32_t bank = 0, offset = 0; bank < EMU_ARRAY_SIZE(mBankMapROM); ++bank, offset += ROM_BANK_SIZE)\n {\n if (offset >= desc.romSize)\n offset = 0;\n mBankMapROM[bank] = pROM + offset;\n }\n for (uint32_t bank = 0, offset = 0; bank < EMU_ARRAY_SIZE(mBankMapRAM); ++bank, offset += BANK_SIZE_EXTERNAL_RAM)\n {\n if (offset >= desc.ramSize)\n offset = 0;\n mBankMapRAM[bank] = pRAM + offset;\n }\n\n reset();\n\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_READ, 0x0000, 0x3fff, mMemoryROM[0]));\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_READ, 0x4000, 0x7fff, mMemoryROM[1]));\n uint16_t size = 0;\n if (!mExternalRAM.empty())\n {\n size = static_cast<uint16_t>(mExternalRAM.size());\n if (size > BANK_SIZE_EXTERNAL_RAM)\n size = BANK_SIZE_EXTERNAL_RAM;\n EMU_VERIFY(mMemory->addMemoryRange(0xa000, 0xa000 + size - 1, mMemoryExternalRAM));\n }\n if (size < BANK_SIZE_EXTERNAL_RAM)\n {\n EMU_VERIFY(mMemory->addMemoryRange(0xa000, 0xa000 + BANK_SIZE_EXTERNAL_RAM - size - 1, mMemoryExternalRAMEmpty));\n }\n return true;\n }\n\n void MapperBase::destroy()\n {\n mExternalRAM.clear();\n initialize();\n }\n\n void MapperBase::reset()\n {\n mBankROM[0] = 0;\n mBankROM[1] = 1;\n mBankExternalRAM = 0x00;\n mEnableExternalRAM = false;\n updateMemoryMap();\n }\n\n void MapperBase::enableRam(bool enable)\n {\n mEnableExternalRAM = enable;\n }\n\n bool MapperBase::updateMemoryMap()\n {\n mMemoryROM[0].setReadMemory(mBankMapROM[mBankROM[0]]);\n mMemoryROM[1].setReadMemory(mBankMapROM[mBankROM[1]]);\n if (!mExternalRAM.empty() && (mEnableExternalRAM || !mRom->getDescription().hasBattery))\n {\n mMemoryExternalRAM.setReadWriteMemory(mBankMapRAM[mBankExternalRAM]);\n }\n else\n {\n mMemoryExternalRAM.read.setReadMethod(&read8null, this);\n mMemoryExternalRAM.write.setWriteMethod(&write8null, this);\n }\n mMemoryExternalRAMEmpty.read.setReadMethod(&read8null, this);\n mMemoryExternalRAMEmpty.write.setWriteMethod(&write8null, this);\n return true;\n }\n\n void MapperBase::serializeGameData(emu::ISerializer& serializer)\n {\n if (mRom->getDescription().hasBattery)\n serializer.serialize(mExternalRAM);\n }\n\n void MapperBase::serializeGameState(emu::ISerializer& serializer)\n {\n serializer.serialize(mExternalRAM);\n serializer.serialize(mBankROM, EMU_ARRAY_SIZE(mBankROM));\n serializer.serialize(mBankExternalRAM);\n serializer.serialize(mEnableExternalRAM);\n updateMemoryMap();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MapperROM::MapperROM()\n {\n }\n\n bool MapperROM::create(const Rom& rom, emu::MemoryBus& memory)\n {\n EMU_VERIFY(MapperBase::create(rom, memory));\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_WRITE, 0x0000, 0x7fff, mMemoryControlRegs.setWriteMethod(&write8, this)));\n return true;\n }\n\n void MapperROM::write8(void* context, int32_t tick, uint32_t addr, uint8_t value)\n {\n EMU_NOT_IMPLEMENTED();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MapperMBC1::MapperMBC1()\n {\n }\n\n bool MapperMBC1::create(const Rom& rom, emu::MemoryBus& memory)\n {\n EMU_VERIFY(MapperBase::create(rom, memory));\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_WRITE, 0x0000, 0x7fff, mMemoryControlRegs.setWriteMethod(&MapperMBC1::write8, this)));\n return true;\n }\n\n void MapperMBC1::reset()\n {\n mBankROM = 0;\n mBankRAM = 0;\n mRamBankMode = false;\n MapperBase::reset();\n }\n\n void MapperMBC1::serializeGameState(emu::ISerializer& serializer)\n {\n serializer.serialize(mBankROM);\n serializer.serialize(mBankRAM);\n serializer.serialize(mRamBankMode);\n MapperBase::serializeGameState(serializer);\n }\n\n bool MapperMBC1::updateMemoryMap()\n {\n uint8_t validBankROM = mBankROM;\n if ((validBankROM & MBC1_ROM_BANK_INVALID_MASK) == 0)\n validBankROM |= MBC1_ROM_BANK_INVALID_ADJ;\n setRomBank(validBankROM);\n setRamBank(mBankRAM);\n return MapperBase::updateMemoryMap();\n }\n\n void MapperMBC1::write8(int32_t tick, uint32_t addr, uint8_t value)\n {\n switch (addr >> 13)\n {\n case 0:\n {\n bool enable = (value & MBC1_RAM_ENABLE_MASK) == MBC1_RAM_ENABLE_VALUE;\n enableRam(enable);\n break;\n }\n case 1:\n {\n mBankROM = (mBankROM & ~MBC1_ROM_BANK_LOW_MASK) | (value & MBC1_ROM_BANK_LOW_MASK);\n break;\n }\n case 2:\n {\n value = value & MBC1_ROM_BANK_HIGH_VALID;\n if (mRamBankMode)\n {\n mBankRAM = value;\n }\n else\n {\n mBankROM = (mBankROM & ~MBC1_ROM_BANK_HIGH_MASK) | ((value << MBC1_ROM_BANK_HIGH_SHIFT) & MBC1_ROM_BANK_HIGH_MASK);\n }\n break;\n }\n case 3:\n {\n mRamBankMode = (value & MBC1_RAM_BANK_MODE) != 0;\n break;\n }\n default:\n EMU_ASSERT(false);\n }\n updateMemoryMap();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MapperMBC5::MapperMBC5()\n {\n }\n\n bool MapperMBC5::create(const Rom& rom, emu::MemoryBus& memory)\n {\n EMU_VERIFY(MapperBase::create(rom, memory));\n EMU_VERIFY(mMemory->addMemoryRange(MEMORY_BUS::PAGE_TABLE_WRITE, 0x0000, 0x7fff, mMemoryControlRegs.setWriteMethod(&MapperMBC5::write8, this)));\n return true;\n }\n\n void MapperMBC5::reset()\n {\n mRamBankMode = false;\n MapperBase::reset();\n }\n\n void MapperMBC5::serializeGameState(emu::ISerializer& serializer)\n {\n serializer.serialize(mRamBankMode);\n MapperBase::serializeGameState(serializer);\n }\n\n bool MapperMBC5::updateMemoryMap()\n {\n return MapperBase::updateMemoryMap();\n }\n\n void MapperMBC5::write8(int32_t tick, uint32_t addr, uint8_t value)\n {\n switch (addr >> 12)\n {\n case 0:\n case 1:\n {\n bool enable = (value & MBC5_RAM_ENABLE_MASK) == MBC5_RAM_ENABLE_VALUE;\n enableRam(enable);\n break;\n }\n case 2:\n {\n uint16_t bank = getRomBank();\n bank = (bank & ~MBC5_ROM_BANK_LOW_MASK) | (value & MBC5_ROM_BANK_LOW_MASK);\n setRomBank(bank);\n break;\n }\n case 3:\n {\n uint16_t bank = getRomBank();\n bank = (bank & ~MBC5_ROM_BANK_HIGH_MASK) | ((value << MBC5_ROM_BANK_HIGH_SHIFT) & MBC5_ROM_BANK_HIGH_MASK);\n setRomBank(bank);\n break;\n }\n case 4:\n case 5:\n {\n setRamBank(value);\n break;\n }\n default:\n break;\n }\n\n updateMemoryMap();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n IMapper* createMapper(const Rom& rom, emu::MemoryBus& memory)\n {\n const auto& desc = rom.getDescription();\n\n switch (desc.mapper)\n {\n case Rom::Mapper::ROM:\n {\n auto mapper = new MapperROM();\n if (mapper->create(rom, memory))\n return mapper;\n delete mapper;\n break;\n }\n\n case Rom::Mapper::MBC1:\n {\n auto mapper = new MapperMBC1();\n if (mapper->create(rom, memory))\n return mapper;\n delete mapper;\n break;\n }\n\n case Rom::Mapper::MBC5:\n {\n auto mapper = new MapperMBC5();\n if (mapper->create(rom, memory))\n return mapper;\n delete mapper;\n break;\n }\n\n default:\n EMU_NOT_IMPLEMENTED();\n }\n return nullptr;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: c++; c-basic-offset:4 -*-\n uiserver\/echocommand.cpp\n\n This file is part of Kleopatra, the KDE keymanager\n Copyright (c) 2007 Klarälvdalens Datakonsult AB\n\n Kleopatra 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 Kleopatra 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 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"echocommand.h\"\n\n#include <gpg-error.h>\n\n#include <QVariant>\n#include <QByteArray>\n#include <QIODevice>\n#include <QList>\n\n#include <boost\/bind.hpp>\n\n#include <string>\n#include <algorithm>\n\nusing namespace Kleo;\nusing namespace boost;\n\nstatic const char option_prefix[] = \"prefix\";\n\nclass EchoCommand::Private {\npublic:\n Private() : operationsInFlight( 0 ), buffer() {}\n\n int operationsInFlight;\n QByteArray buffer;\n};\n\nEchoCommand::EchoCommand()\n : QObject(), AssuanCommandMixin<EchoCommand>(), d( new Private ) {}\n\nEchoCommand::~EchoCommand() {}\n\nint EchoCommand::start( const std::string & line ) {\n\n if ( bulkInputDevice( \"IN\" ) && !bulkOutputDevice( \"OUT\" ) )\n return makeError( GPG_ERR_NOT_SUPPORTED );\n\n if ( hasOption( option_prefix ) && !option( option_prefix ).toByteArray().isEmpty() )\n return makeError( GPG_ERR_NOT_IMPLEMENTED );\n\n QList<QByteArray> tokens = QByteArray( line.c_str() ).split( ' ' );\n tokens.erase( std::remove_if( tokens.begin(), tokens.end(),\n bind( &QByteArray::isEmpty, _1 ) ),\n tokens.end() );\n\n std::string keyword;\n if ( !tokens.empty() && tokens.front() == \"--inquire\" ) {\n tokens.pop_front();\n if ( tokens.empty() )\n return makeError( GPG_ERR_MISSING_VALUE );\n keyword = tokens.front().constData();\n tokens.pop_front();\n }\n\n bool optionsExpected = true;\n QByteArray output;\n Q_FOREACH( QByteArray token, tokens ) {\n if ( token == \"--\" )\n optionsExpected = false;\n else if ( optionsExpected && token.startsWith( \"--\" ) )\n if ( token == \"--inquire\" )\n return makeError( GPG_ERR_DUP_VALUE ); \/\/ duplicate\n else\n return makeError( GPG_ERR_UNKNOWN_OPTION );\n else\n if ( output.isEmpty() )\n output = token;\n else\n output += ' ' + token;\n }\n\n \/\/ aaand ACTION:\n\n \/\/ 1. echo the command line though the status channel\n if ( const int err = sendStatus( \"ECHO\", output.constData() ) )\n return err;\n\n \/\/ 2. if --inquire was given, inquire more data from the client:\n if ( !keyword.empty() )\n if ( const int err = inquire( keyword.c_str(), this,\n SLOT(slotInquireData(int,QByteArray)) ) )\n return err;\n else\n ++d->operationsInFlight;\n\n \/\/ 3. if INPUT was given, start the data pump for input->output\n if ( QIODevice * const in = bulkInputDevice( \"IN\" ) ) {\n QIODevice * const out = bulkOutputDevice( \"OUT\" );\n\n ++d->operationsInFlight;\n\n connect( in, SIGNAL(readyRead()), this, SLOT(slotInputReadyRead()) );\n connect( out, SIGNAL(bytesWritten(qint64)), this, SLOT(slotOutputBytesWritten()) );\n\n if ( in->bytesAvailable() )\n slotInputReadyRead();\n }\n\n if ( !d->operationsInFlight )\n done();\n return 0;\n}\n\nvoid EchoCommand::canceled() {\n\n}\n\nvoid EchoCommand::slotInquireData( int rc, const QByteArray & data ) {\n\n --d->operationsInFlight;\n\n if ( rc )\n done( rc );\n\n \/\/else if ( const int err = sendData( data ) )\n else if ( const int err = sendStatus( \"ECHOINQ\", data ) )\n done( err );\n\n else if ( !d->operationsInFlight )\n done();\n\n}\n\nvoid EchoCommand::slotInputReadyRead() {\n QIODevice * const in = bulkInputDevice( \"IN\" );\n assert( in );\n\n if ( !in->atEnd() )\n d->buffer += in->readAll();\n\n slotOutputBytesWritten();\n}\n\n\nvoid EchoCommand::slotOutputBytesWritten() {\n QIODevice * const out = bulkOutputDevice( \"OUT\" );\n assert( out );\n\n if ( d->buffer.isEmpty() ) {\n if ( bulkInputDevice( \"IN\" )->atEnd() && out->isOpen() ) {\n out->close();\n if ( !--d->operationsInFlight )\n done();\n }\n return;\n }\n\n if ( out->bytesToWrite() )\n return;\n\n const qint64 written = out->write( d->buffer );\n if ( written == -1 ) {\n done( makeError( GPG_ERR_EIO ) );\n return;\n }\n d->buffer.remove( 0, written );\n\n}\n\n#include \"moc_echocommand.cpp\"\n<commit_msg>Don't hang when output is a file<commit_after>\/* -*- mode: c++; c-basic-offset:4 -*-\n uiserver\/echocommand.cpp\n\n This file is part of Kleopatra, the KDE keymanager\n Copyright (c) 2007 Klarälvdalens Datakonsult AB\n\n Kleopatra 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 Kleopatra 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 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"echocommand.h\"\n\n#include <gpg-error.h>\n\n#include <QVariant>\n#include <QByteArray>\n#include <QIODevice>\n#include <QList>\n\n#include <boost\/bind.hpp>\n\n#include <string>\n#include <algorithm>\n\nusing namespace Kleo;\nusing namespace boost;\n\nstatic const char option_prefix[] = \"prefix\";\n\nclass EchoCommand::Private {\npublic:\n Private() : operationsInFlight( 0 ), buffer() {}\n\n int operationsInFlight;\n QByteArray buffer;\n};\n\nEchoCommand::EchoCommand()\n : QObject(), AssuanCommandMixin<EchoCommand>(), d( new Private ) {}\n\nEchoCommand::~EchoCommand() {}\n\nint EchoCommand::start( const std::string & line ) {\n\n if ( bulkInputDevice( \"IN\" ) && !bulkOutputDevice( \"OUT\" ) )\n return makeError( GPG_ERR_NOT_SUPPORTED );\n\n if ( hasOption( option_prefix ) && !option( option_prefix ).toByteArray().isEmpty() )\n return makeError( GPG_ERR_NOT_IMPLEMENTED );\n\n QList<QByteArray> tokens = QByteArray( line.c_str() ).split( ' ' );\n tokens.erase( std::remove_if( tokens.begin(), tokens.end(),\n bind( &QByteArray::isEmpty, _1 ) ),\n tokens.end() );\n\n std::string keyword;\n if ( !tokens.empty() && tokens.front() == \"--inquire\" ) {\n tokens.pop_front();\n if ( tokens.empty() )\n return makeError( GPG_ERR_MISSING_VALUE );\n keyword = tokens.front().constData();\n tokens.pop_front();\n }\n\n bool optionsExpected = true;\n QByteArray output;\n Q_FOREACH( QByteArray token, tokens ) {\n if ( token == \"--\" )\n optionsExpected = false;\n else if ( optionsExpected && token.startsWith( \"--\" ) )\n if ( token == \"--inquire\" )\n return makeError( GPG_ERR_DUP_VALUE ); \/\/ duplicate\n else\n return makeError( GPG_ERR_UNKNOWN_OPTION );\n else\n if ( output.isEmpty() )\n output = token;\n else\n output += ' ' + token;\n }\n\n \/\/ aaand ACTION:\n\n \/\/ 1. echo the command line though the status channel\n if ( const int err = sendStatus( \"ECHO\", output.constData() ) )\n return err;\n\n \/\/ 2. if --inquire was given, inquire more data from the client:\n if ( !keyword.empty() )\n if ( const int err = inquire( keyword.c_str(), this,\n SLOT(slotInquireData(int,QByteArray)) ) )\n return err;\n else\n ++d->operationsInFlight;\n\n \/\/ 3. if INPUT was given, start the data pump for input->output\n if ( QIODevice * const in = bulkInputDevice( \"IN\" ) ) {\n QIODevice * const out = bulkOutputDevice( \"OUT\" );\n\n ++d->operationsInFlight;\n\n connect( in, SIGNAL(readyRead()), this, SLOT(slotInputReadyRead()) );\n connect( out, SIGNAL(bytesWritten(qint64)), this, SLOT(slotOutputBytesWritten()) );\n\n if ( in->bytesAvailable() )\n slotInputReadyRead();\n }\n\n if ( !d->operationsInFlight )\n done();\n return 0;\n}\n\nvoid EchoCommand::canceled() {\n\n}\n\nvoid EchoCommand::slotInquireData( int rc, const QByteArray & data ) {\n\n --d->operationsInFlight;\n\n if ( rc )\n done( rc );\n\n \/\/else if ( const int err = sendData( data ) )\n else if ( const int err = sendStatus( \"ECHOINQ\", data ) )\n done( err );\n\n else if ( !d->operationsInFlight )\n done();\n\n}\n\nvoid EchoCommand::slotInputReadyRead() {\n QIODevice * const in = bulkInputDevice( \"IN\" );\n assert( in );\n\n QByteArray buffer;\n buffer.resize( in->bytesAvailable() );\n const qint64 read = in->read( buffer.data(), buffer.size() );\n if ( read == - 1 ) {\n done( makeError( GPG_ERR_EIO ) );\n return;\n }\n if ( read == 0 || !in->isSequential() && read == in->size() )\n in->close();\n\n buffer.resize( read );\n d->buffer += buffer;\n\n slotOutputBytesWritten();\n}\n\n\nvoid EchoCommand::slotOutputBytesWritten() {\n QIODevice * const out = bulkOutputDevice( \"OUT\" );\n assert( out );\n\n if ( !d->buffer.isEmpty() ) {\n\n if ( out->bytesToWrite() )\n return;\n\n const qint64 written = out->write( d->buffer );\n if ( written == -1 ) {\n done( makeError( GPG_ERR_EIO ) );\n return;\n }\n d->buffer.remove( 0, written );\n\n }\n\n if ( out->isOpen() && d->buffer.isEmpty() && !bulkInputDevice( \"IN\" )->isOpen() ) {\n out->close();\n if ( !--d->operationsInFlight )\n done();\n }\n}\n\n#include \"moc_echocommand.cpp\"\n<|endoftext|>"} {"text":"<commit_before>#include \"managesievescriptsdialog.h\"\n#include \"managesievescriptsdialog_p.h\"\n\n#include \"sieveconfig.h\"\n#include \"accountmanager.h\"\n#include \"imapaccountbase.h\"\n#include \"sievejob.h\"\n#include \"kmkernel.h\"\n\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kwin.h>\n#include <kapplication.h>\n#include <kinputdialog.h>\n#include <kglobalsettings.h>\n#include <kmessagebox.h>\n\n#include <qlayout.h>\n#include <qlistview.h>\n#include <qtextedit.h>\n#include <qpopupmenu.h>\n\n#include <cassert>\n\ninline QCheckListItem * qcli_cast( QListViewItem * lvi ) {\n return lvi && lvi->rtti() == 1 ? static_cast<QCheckListItem*>( lvi ) : 0 ;\n}\ninline const QCheckListItem * qcli_cast( const QListViewItem * lvi ) {\n return lvi && lvi->rtti() == 1 ? static_cast<const QCheckListItem*>( lvi ) : 0 ;\n}\n\nKMail::ManageSieveScriptsDialog::ManageSieveScriptsDialog( QWidget * parent, const char * name )\n : KDialogBase( Plain, i18n( \"Manage Sieve Scripts\" ), Ok|Close, Ok, parent, name, false ),\n mSieveEditor( 0 ),\n mContextMenuItem( 0 ),\n mWasActive( false )\n{\n setWFlags( WGroupLeader|WDestructiveClose );\n KWin::setIcons( winId(), kapp->icon(), kapp->miniIcon() );\n\n QVBoxLayout * vlay = new QVBoxLayout( plainPage(), 0, 0 );\n\n mListView = new QListView( plainPage() );\n mListView->addColumn( i18n( \"Available Scripts\" ) );\n mListView->setResizeMode( QListView::LastColumn );\n mListView->setRootIsDecorated( true );\n mListView->setSelectionMode( QListView::Single );\n connect( mListView, SIGNAL(contextMenuRequested(QListViewItem*,const QPoint&,int)),\n this, SLOT(slotContextMenuRequested(QListViewItem*, const QPoint&)) );\n connect( mListView, SIGNAL(doubleClicked(QListViewItem*,const QPoint&,int)),\n this, SLOT(slotDoubleClicked(QListViewItem*)) );\n connect( mListView, SIGNAL(selectionChanged(QListViewItem*)),\n this, SLOT(slotSelectionChanged(QListViewItem*)) );\n vlay->addWidget( mListView );\n\n resize( 2 * sizeHint().width(), sizeHint().height() );\n\n slotRefresh();\n}\n\nKMail::ManageSieveScriptsDialog::~ManageSieveScriptsDialog() {\n killAllJobs();\n}\n\nvoid KMail::ManageSieveScriptsDialog::killAllJobs() {\n for ( QMap<SieveJob*,QCheckListItem*>::const_iterator it = mJobs.constBegin(), end = mJobs.constEnd() ; it != end ; ++it )\n it.key()->kill();\n mJobs.clear();\n}\n\nstatic KURL findUrlForAccount( const KMail::ImapAccountBase * a ) {\n assert( a );\n const KMail::SieveConfig sieve = a->sieveConfig();\n if ( !sieve.managesieveSupported() )\n return KURL();\n if ( sieve.reuseConfig() ) {\n \/\/ assemble Sieve url from the settings of the account:\n KURL u;\n u.setProtocol( \"sieve\" );\n u.setHost( a->host() );\n u.setUser( a->login() );\n u.setPass( a->passwd() );\n u.setPort( sieve.port() );\n \/\/ Translate IMAP LOGIN to PLAIN:\n u.setQuery( \"x-mech=\" + ( a->auth() == \"*\" ? \"PLAIN\" : a->auth() ) );\n return u;\n } else {\n return sieve.alternateURL();\n }\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotRefresh() {\n killAllJobs();\n mUrls.clear();\n mListView->clear();\n\n KMail::AccountManager * am = kmkernel->acctMgr();\n assert( am );\n QCheckListItem * last = 0;\n for ( KMAccount * a = am->first() ; a ; a = am->next() ) {\n last = new QCheckListItem( mListView, last, a->name(), QCheckListItem::Controller );\n last->setPixmap( 0, SmallIcon( \"server\" ) );\n if ( ImapAccountBase * iab = dynamic_cast<ImapAccountBase*>( a ) ) {\n const KURL u = ::findUrlForAccount( iab );\n if ( u.isEmpty() )\n continue;\n SieveJob * job = SieveJob::list( u );\n connect( job, SIGNAL(item(KMail::SieveJob*,const QString&,bool)),\n this, SLOT(slotItem(KMail::SieveJob*,const QString&,bool)) );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotResult(KMail::SieveJob*,bool,const QString&,bool)) );\n mJobs.insert( job, last );\n mUrls.insert( last, u );\n } else {\n QListViewItem * item = new QListViewItem( last, i18n( \"No Sieve URL configured\" ) );\n item->setEnabled( false );\n last->setOpen( true );\n }\n }\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotResult( KMail::SieveJob * job, bool success, const QString &, bool ) {\n QCheckListItem * parent = mJobs[job];\n if ( !parent )\n return;\n\n mJobs.remove( job );\n\n parent->setOpen( true );\n\n if ( success )\n return;\n\n QListViewItem * item = new QListViewItem( parent, i18n( \"Failed to fetch the list of scripts\" ) );\n item->setEnabled( false );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotItem( KMail::SieveJob * job, const QString & filename, bool isActive ) {\n QCheckListItem * parent = mJobs[job];\n if ( !parent )\n return;\n QCheckListItem * item = new QCheckListItem( parent, filename, QCheckListItem::RadioButton );\n if ( isActive ) {\n item->setOn( true );\n mSelectedItems[parent] = item;\n }\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotContextMenuRequested( QListViewItem * i, const QPoint & p ) {\n QCheckListItem * item = qcli_cast( i );\n if ( !item )\n return;\n if ( !item->depth() && !mUrls.count( item ) )\n return;\n QPopupMenu menu;\n mContextMenuItem = item;\n if ( item->depth() ) {\n \/\/ script items:\n menu.insertItem( i18n( \"Delete Script\" ), this, SLOT(slotDeleteScript()) );\n menu.insertItem( i18n( \"Edit Script...\" ), this, SLOT(slotEditScript()) );\n } else {\n \/\/ top-levels:\n menu.insertItem( i18n( \"New Script...\" ), this, SLOT(slotNewScript()) );\n }\n menu.exec( p );\n mContextMenuItem = 0;\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotSelectionChanged( QListViewItem * i ) {\n QCheckListItem * item = qcli_cast( i );\n if ( !item )\n return;\n QCheckListItem * parent = qcli_cast( item->parent() );\n if ( !parent )\n return;\n if ( item->isOn() && mSelectedItems[parent] != item ) {\n mSelectedItems[parent] = item;\n changeActiveScript( parent );\n }\n}\n\nvoid KMail::ManageSieveScriptsDialog::changeActiveScript( QCheckListItem * item ) {\n if ( !item )\n return;\n if ( !mUrls.count( item ) )\n return;\n if ( !mSelectedItems.count( item ) )\n return;\n KURL u = mUrls[item];\n if ( u.isEmpty() )\n return;\n QCheckListItem * selected = mSelectedItems[item];\n if ( !selected )\n return;\n u.setFileName( selected->text( 0 ) );\n\n SieveJob * job = SieveJob::activate( u );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotRefresh()) );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotDoubleClicked( QListViewItem * i ) {\n QCheckListItem * item = qcli_cast( i );\n if ( !item )\n return;\n if ( !item->depth() )\n return;\n mContextMenuItem = item;\n slotEditScript();\n mContextMenuItem = 0;\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotDeleteScript() {\n if ( !mContextMenuItem )\n return;\n if ( !mContextMenuItem->depth() )\n return;\n\n QCheckListItem * parent = qcli_cast( mContextMenuItem->parent() );\n if ( !parent )\n return;\n\n if ( !mUrls.count( parent ) )\n return;\n\n KURL u = mUrls[parent];\n if ( u.isEmpty() )\n return;\n\n u.setFileName( mContextMenuItem->text( 0 ) );\n\n if ( KMessageBox::questionYesNo( this, i18n( \"Really delete script \\\"%1\\\" from the server?\" ).arg( u.fileName() ),\n i18n( \"Delete Sieve Script Confirmation\" ),\n KStdGuiItem::del(), KStdGuiItem::cancel() )\n != KMessageBox::Yes )\n return;\n\n SieveJob * job = SieveJob::del( u );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotRefresh()) );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotEditScript() {\n if ( !mContextMenuItem )\n return;\n if ( !mContextMenuItem->depth() )\n return;\n QCheckListItem * parent = qcli_cast( mContextMenuItem->parent() );\n if ( !mUrls.count( parent ) )\n return;\n KURL url = mUrls[parent];\n if ( url.isEmpty() )\n return;\n url.setFileName( mContextMenuItem->text( 0 ) );\n mCurrentURL = url;\n SieveJob * job = SieveJob::get( url );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotGetResult(KMail::SieveJob*,bool,const QString&,bool)) );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotNewScript() {\n if ( !mContextMenuItem )\n return;\n if ( mContextMenuItem->depth() )\n mContextMenuItem = qcli_cast( mContextMenuItem->parent() );\n if ( !mContextMenuItem )\n return;\n\n if ( !mUrls.count( mContextMenuItem ) )\n return;\n\n KURL u = mUrls[mContextMenuItem];\n if ( u.isEmpty() )\n return;\n\n bool ok = false;\n const QString name = KInputDialog::getText( i18n( \"New Sieve Script\" ),\n i18n( \"Please enter a name for the new Sieve script:\" ),\n i18n( \"unnamed\" ), &ok, this );\n if ( !ok || name.isEmpty() )\n return;\n\n u.setFileName( name );\n\n (void) new QCheckListItem( mContextMenuItem, name, QCheckListItem::RadioButton );\n\n mCurrentURL = u;\n slotGetResult( 0, true, QString::null, false );\n}\n\nKMail::SieveEditor::SieveEditor( QWidget * parent, const char * name )\n : KDialogBase( Plain, i18n( \"Edit Sieve Script\" ), Ok|Cancel, Ok, parent, name )\n{\n QVBoxLayout * vlay = new QVBoxLayout( plainPage(), 0, spacingHint() );\n mTextEdit = new QTextEdit( plainPage() );\n vlay->addWidget( mTextEdit );\n mTextEdit->setTextFormat( QTextEdit::PlainText );\n mTextEdit->setWordWrap( QTextEdit::NoWrap );\n mTextEdit->setFont( KGlobalSettings::fixedFont() );\n\n resize( 3 * sizeHint() );\n}\n\nKMail::SieveEditor::~SieveEditor() {}\n\nvoid KMail::ManageSieveScriptsDialog::slotGetResult( KMail::SieveJob *, bool success, const QString & script, bool isActive ) {\n if ( !success )\n return;\n\n if ( mSieveEditor )\n return;\n\n mSieveEditor = new SieveEditor( this );\n mSieveEditor->setScript( script );\n connect( mSieveEditor, SIGNAL(okClicked()), this, SLOT(slotSieveEditorOkClicked()) );\n connect( mSieveEditor, SIGNAL(cancelClicked()), this, SLOT(slotSieveEditorCancelClicked()) );\n mSieveEditor->show();\n mWasActive = isActive;\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotSieveEditorOkClicked() {\n if ( !mSieveEditor )\n return;\n SieveJob * job = SieveJob::put( mCurrentURL,mSieveEditor->script(), mWasActive, mWasActive );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotPutResult(KMail::SieveJob*,bool)) );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotSieveEditorCancelClicked() {\n mSieveEditor->deleteLater(); mSieveEditor = 0;\n mCurrentURL = KURL();\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotPutResult( KMail::SieveJob *, bool success ) {\n if ( success ) {\n KMessageBox::information( this, i18n( \"The Sieve script was successfully uploaded.\" ),\n i18n( \"Sieve Script Upload\" ) );\n mSieveEditor->deleteLater(); mSieveEditor = 0;\n mCurrentURL = KURL();\n } else {\n mSieveEditor->show();\n }\n}\n\n#include \"managesievescriptsdialog.moc\"\n#include \"managesievescriptsdialog_p.moc\"\n<commit_msg>The \"Ok\" button was unnecessary and downright confusing.<commit_after>#include \"managesievescriptsdialog.h\"\n#include \"managesievescriptsdialog_p.h\"\n\n#include \"sieveconfig.h\"\n#include \"accountmanager.h\"\n#include \"imapaccountbase.h\"\n#include \"sievejob.h\"\n#include \"kmkernel.h\"\n\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kwin.h>\n#include <kapplication.h>\n#include <kinputdialog.h>\n#include <kglobalsettings.h>\n#include <kmessagebox.h>\n\n#include <qlayout.h>\n#include <qlistview.h>\n#include <qtextedit.h>\n#include <qpopupmenu.h>\n\n#include <cassert>\n\ninline QCheckListItem * qcli_cast( QListViewItem * lvi ) {\n return lvi && lvi->rtti() == 1 ? static_cast<QCheckListItem*>( lvi ) : 0 ;\n}\ninline const QCheckListItem * qcli_cast( const QListViewItem * lvi ) {\n return lvi && lvi->rtti() == 1 ? static_cast<const QCheckListItem*>( lvi ) : 0 ;\n}\n\nKMail::ManageSieveScriptsDialog::ManageSieveScriptsDialog( QWidget * parent, const char * name )\n : KDialogBase( Plain, i18n( \"Manage Sieve Scripts\" ), Close, Close,\n parent, name, false ),\n mSieveEditor( 0 ),\n mContextMenuItem( 0 ),\n mWasActive( false )\n{\n setWFlags( WGroupLeader|WDestructiveClose );\n KWin::setIcons( winId(), kapp->icon(), kapp->miniIcon() );\n\n QVBoxLayout * vlay = new QVBoxLayout( plainPage(), 0, 0 );\n\n mListView = new QListView( plainPage() );\n mListView->addColumn( i18n( \"Available Scripts\" ) );\n mListView->setResizeMode( QListView::LastColumn );\n mListView->setRootIsDecorated( true );\n mListView->setSelectionMode( QListView::Single );\n connect( mListView, SIGNAL(contextMenuRequested(QListViewItem*,const QPoint&,int)),\n this, SLOT(slotContextMenuRequested(QListViewItem*, const QPoint&)) );\n connect( mListView, SIGNAL(doubleClicked(QListViewItem*,const QPoint&,int)),\n this, SLOT(slotDoubleClicked(QListViewItem*)) );\n connect( mListView, SIGNAL(selectionChanged(QListViewItem*)),\n this, SLOT(slotSelectionChanged(QListViewItem*)) );\n vlay->addWidget( mListView );\n\n resize( 2 * sizeHint().width(), sizeHint().height() );\n\n slotRefresh();\n}\n\nKMail::ManageSieveScriptsDialog::~ManageSieveScriptsDialog() {\n killAllJobs();\n}\n\nvoid KMail::ManageSieveScriptsDialog::killAllJobs() {\n for ( QMap<SieveJob*,QCheckListItem*>::const_iterator it = mJobs.constBegin(), end = mJobs.constEnd() ; it != end ; ++it )\n it.key()->kill();\n mJobs.clear();\n}\n\nstatic KURL findUrlForAccount( const KMail::ImapAccountBase * a ) {\n assert( a );\n const KMail::SieveConfig sieve = a->sieveConfig();\n if ( !sieve.managesieveSupported() )\n return KURL();\n if ( sieve.reuseConfig() ) {\n \/\/ assemble Sieve url from the settings of the account:\n KURL u;\n u.setProtocol( \"sieve\" );\n u.setHost( a->host() );\n u.setUser( a->login() );\n u.setPass( a->passwd() );\n u.setPort( sieve.port() );\n \/\/ Translate IMAP LOGIN to PLAIN:\n u.setQuery( \"x-mech=\" + ( a->auth() == \"*\" ? \"PLAIN\" : a->auth() ) );\n return u;\n } else {\n return sieve.alternateURL();\n }\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotRefresh() {\n killAllJobs();\n mUrls.clear();\n mListView->clear();\n\n KMail::AccountManager * am = kmkernel->acctMgr();\n assert( am );\n QCheckListItem * last = 0;\n for ( KMAccount * a = am->first() ; a ; a = am->next() ) {\n last = new QCheckListItem( mListView, last, a->name(), QCheckListItem::Controller );\n last->setPixmap( 0, SmallIcon( \"server\" ) );\n if ( ImapAccountBase * iab = dynamic_cast<ImapAccountBase*>( a ) ) {\n const KURL u = ::findUrlForAccount( iab );\n if ( u.isEmpty() )\n continue;\n SieveJob * job = SieveJob::list( u );\n connect( job, SIGNAL(item(KMail::SieveJob*,const QString&,bool)),\n this, SLOT(slotItem(KMail::SieveJob*,const QString&,bool)) );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotResult(KMail::SieveJob*,bool,const QString&,bool)) );\n mJobs.insert( job, last );\n mUrls.insert( last, u );\n } else {\n QListViewItem * item = new QListViewItem( last, i18n( \"No Sieve URL configured\" ) );\n item->setEnabled( false );\n last->setOpen( true );\n }\n }\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotResult( KMail::SieveJob * job, bool success, const QString &, bool ) {\n QCheckListItem * parent = mJobs[job];\n if ( !parent )\n return;\n\n mJobs.remove( job );\n\n parent->setOpen( true );\n\n if ( success )\n return;\n\n QListViewItem * item = new QListViewItem( parent, i18n( \"Failed to fetch the list of scripts\" ) );\n item->setEnabled( false );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotItem( KMail::SieveJob * job, const QString & filename, bool isActive ) {\n QCheckListItem * parent = mJobs[job];\n if ( !parent )\n return;\n QCheckListItem * item = new QCheckListItem( parent, filename, QCheckListItem::RadioButton );\n if ( isActive ) {\n item->setOn( true );\n mSelectedItems[parent] = item;\n }\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotContextMenuRequested( QListViewItem * i, const QPoint & p ) {\n QCheckListItem * item = qcli_cast( i );\n if ( !item )\n return;\n if ( !item->depth() && !mUrls.count( item ) )\n return;\n QPopupMenu menu;\n mContextMenuItem = item;\n if ( item->depth() ) {\n \/\/ script items:\n menu.insertItem( i18n( \"Delete Script\" ), this, SLOT(slotDeleteScript()) );\n menu.insertItem( i18n( \"Edit Script...\" ), this, SLOT(slotEditScript()) );\n } else {\n \/\/ top-levels:\n menu.insertItem( i18n( \"New Script...\" ), this, SLOT(slotNewScript()) );\n }\n menu.exec( p );\n mContextMenuItem = 0;\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotSelectionChanged( QListViewItem * i ) {\n QCheckListItem * item = qcli_cast( i );\n if ( !item )\n return;\n QCheckListItem * parent = qcli_cast( item->parent() );\n if ( !parent )\n return;\n if ( item->isOn() && mSelectedItems[parent] != item ) {\n mSelectedItems[parent] = item;\n changeActiveScript( parent );\n }\n}\n\nvoid KMail::ManageSieveScriptsDialog::changeActiveScript( QCheckListItem * item ) {\n if ( !item )\n return;\n if ( !mUrls.count( item ) )\n return;\n if ( !mSelectedItems.count( item ) )\n return;\n KURL u = mUrls[item];\n if ( u.isEmpty() )\n return;\n QCheckListItem * selected = mSelectedItems[item];\n if ( !selected )\n return;\n u.setFileName( selected->text( 0 ) );\n\n SieveJob * job = SieveJob::activate( u );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotRefresh()) );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotDoubleClicked( QListViewItem * i ) {\n QCheckListItem * item = qcli_cast( i );\n if ( !item )\n return;\n if ( !item->depth() )\n return;\n mContextMenuItem = item;\n slotEditScript();\n mContextMenuItem = 0;\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotDeleteScript() {\n if ( !mContextMenuItem )\n return;\n if ( !mContextMenuItem->depth() )\n return;\n\n QCheckListItem * parent = qcli_cast( mContextMenuItem->parent() );\n if ( !parent )\n return;\n\n if ( !mUrls.count( parent ) )\n return;\n\n KURL u = mUrls[parent];\n if ( u.isEmpty() )\n return;\n\n u.setFileName( mContextMenuItem->text( 0 ) );\n\n if ( KMessageBox::questionYesNo( this, i18n( \"Really delete script \\\"%1\\\" from the server?\" ).arg( u.fileName() ),\n i18n( \"Delete Sieve Script Confirmation\" ),\n KStdGuiItem::del(), KStdGuiItem::cancel() )\n != KMessageBox::Yes )\n return;\n\n SieveJob * job = SieveJob::del( u );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotRefresh()) );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotEditScript() {\n if ( !mContextMenuItem )\n return;\n if ( !mContextMenuItem->depth() )\n return;\n QCheckListItem * parent = qcli_cast( mContextMenuItem->parent() );\n if ( !mUrls.count( parent ) )\n return;\n KURL url = mUrls[parent];\n if ( url.isEmpty() )\n return;\n url.setFileName( mContextMenuItem->text( 0 ) );\n mCurrentURL = url;\n SieveJob * job = SieveJob::get( url );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotGetResult(KMail::SieveJob*,bool,const QString&,bool)) );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotNewScript() {\n if ( !mContextMenuItem )\n return;\n if ( mContextMenuItem->depth() )\n mContextMenuItem = qcli_cast( mContextMenuItem->parent() );\n if ( !mContextMenuItem )\n return;\n\n if ( !mUrls.count( mContextMenuItem ) )\n return;\n\n KURL u = mUrls[mContextMenuItem];\n if ( u.isEmpty() )\n return;\n\n bool ok = false;\n const QString name = KInputDialog::getText( i18n( \"New Sieve Script\" ),\n i18n( \"Please enter a name for the new Sieve script:\" ),\n i18n( \"unnamed\" ), &ok, this );\n if ( !ok || name.isEmpty() )\n return;\n\n u.setFileName( name );\n\n (void) new QCheckListItem( mContextMenuItem, name, QCheckListItem::RadioButton );\n\n mCurrentURL = u;\n slotGetResult( 0, true, QString::null, false );\n}\n\nKMail::SieveEditor::SieveEditor( QWidget * parent, const char * name )\n : KDialogBase( Plain, i18n( \"Edit Sieve Script\" ), Ok|Cancel, Ok, parent, name )\n{\n QVBoxLayout * vlay = new QVBoxLayout( plainPage(), 0, spacingHint() );\n mTextEdit = new QTextEdit( plainPage() );\n vlay->addWidget( mTextEdit );\n mTextEdit->setTextFormat( QTextEdit::PlainText );\n mTextEdit->setWordWrap( QTextEdit::NoWrap );\n mTextEdit->setFont( KGlobalSettings::fixedFont() );\n\n resize( 3 * sizeHint() );\n}\n\nKMail::SieveEditor::~SieveEditor() {}\n\nvoid KMail::ManageSieveScriptsDialog::slotGetResult( KMail::SieveJob *, bool success, const QString & script, bool isActive ) {\n if ( !success )\n return;\n\n if ( mSieveEditor )\n return;\n\n mSieveEditor = new SieveEditor( this );\n mSieveEditor->setScript( script );\n connect( mSieveEditor, SIGNAL(okClicked()), this, SLOT(slotSieveEditorOkClicked()) );\n connect( mSieveEditor, SIGNAL(cancelClicked()), this, SLOT(slotSieveEditorCancelClicked()) );\n mSieveEditor->show();\n mWasActive = isActive;\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotSieveEditorOkClicked() {\n if ( !mSieveEditor )\n return;\n SieveJob * job = SieveJob::put( mCurrentURL,mSieveEditor->script(), mWasActive, mWasActive );\n connect( job, SIGNAL(result(KMail::SieveJob*,bool,const QString&,bool)),\n this, SLOT(slotPutResult(KMail::SieveJob*,bool)) );\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotSieveEditorCancelClicked() {\n mSieveEditor->deleteLater(); mSieveEditor = 0;\n mCurrentURL = KURL();\n}\n\nvoid KMail::ManageSieveScriptsDialog::slotPutResult( KMail::SieveJob *, bool success ) {\n if ( success ) {\n KMessageBox::information( this, i18n( \"The Sieve script was successfully uploaded.\" ),\n i18n( \"Sieve Script Upload\" ) );\n mSieveEditor->deleteLater(); mSieveEditor = 0;\n mCurrentURL = KURL();\n } else {\n mSieveEditor->show();\n }\n}\n\n#include \"managesievescriptsdialog.moc\"\n#include \"managesievescriptsdialog_p.moc\"\n<|endoftext|>"} {"text":"<commit_before>int main(int argc, char const *argv[]) {\n printf(\"%s\\n\", \"hellooooooo world by YzolaPhilo!!!\");\n return 0;\n}\n<commit_msg>测试SourceTree提交<commit_after>int main(int argc, char const *argv[]) {\n printf(\"%s\\n\", \"hellooooooo world by YzolaPhilo!!!\");\n printf(\"this is a changed, test github!!!\\n\", );\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The local APIC manages internal (non-I\/O) interrupts.\n\/\/ See Chapter 8 & Appendix C of Intel processor manual volume 3.\n\n#include \"types.h\"\n#include \"amd64.h\"\n#include \"kernel.hh\"\n#include \"traps.h\"\n#include \"bits.hh\"\n#include \"cpu.hh\"\n#include \"apic.hh\"\n\n\/\/ Local APIC registers, divided by 4 for use as uint[] indices.\n#define ID (0x0020\/4) \/\/ ID\n#define VER (0x0030\/4) \/\/ Version\n#define TPR (0x0080\/4) \/\/ Task Priority\n#define EOI (0x00B0\/4) \/\/ EOI\n#define SVR (0x00F0\/4) \/\/ Spurious Interrupt Vector\n #define ENABLE 0x00000100 \/\/ Unit Enable\n#define ESR (0x0280\/4) \/\/ Error Status\n#define ICRLO (0x0300\/4) \/\/ Interrupt Command\n #define INIT 0x00000500 \/\/ INIT\/RESET\n #define STARTUP 0x00000600 \/\/ Startup IPI\n #define DELIVS 0x00001000 \/\/ Delivery status\n #define ASSERT 0x00004000 \/\/ Assert interrupt (vs deassert)\n #define DEASSERT 0x00000000\n #define LEVEL 0x00008000 \/\/ Level triggered\n #define BCAST 0x00080000 \/\/ Send to all APICs, including self.\n #define BUSY 0x00001000\n #define FIXED 0x00000000\n#define ICRHI (0x0310\/4) \/\/ Interrupt Command [63:32]\n#define TIMER (0x0320\/4) \/\/ Local Vector Table 0 (TIMER)\n #define X1 0x0000000B \/\/ divide counts by 1\n #define PERIODIC 0x00020000 \/\/ Periodic\n#define PCINT (0x0340\/4) \/\/ Performance Counter LVT\n#define LINT0 (0x0350\/4) \/\/ Local Vector Table 1 (LINT0)\n#define LINT1 (0x0360\/4) \/\/ Local Vector Table 2 (LINT1)\n#define ERROR (0x0370\/4) \/\/ Local Vector Table 3 (ERROR)\n #define MASKED 0x00010000 \/\/ Interrupt masked\n #define MT_NMI 0x00000400 \/\/ NMI message type\n #define MT_FIX 0x00000000 \/\/ Fixed message type\n#define TICR (0x0380\/4) \/\/ Timer Initial Count\n#define TCCR (0x0390\/4) \/\/ Timer Current Count\n#define TDCR (0x03E0\/4) \/\/ Timer Divide Configuration\n\n#define IO_RTC 0x70\n\nstatic volatile u32 *xapic = (u32 *)(KBASE + 0xfee00000);\nstatic u64 xapichz;\n\nstatic void\nxapicw(int index, int value)\n{\n xapic[index] = value;\n xapic[ID]; \/\/ wait for write to finish, by reading\n}\n\nstatic u32\nxapicr(u32 off)\n{\n return xapic[off];\n}\n\nstatic int\nxapicwait()\n{\n int i = 100000;\n while ((xapicr(ICRLO) & BUSY) != 0) {\n nop_pause();\n i--;\n if (i == 0) {\n cprintf(\"xapicwait: wedged?\\n\");\n return -1;\n }\n }\n return 0;\n}\n\nvoid\ninitxapic(void)\n{\n u64 count;\n u64 apicbar;\n\n \/\/ See Intel Arch. Manual Vol 3a, the APIC section\n \/\/ Check if x2APIC is enabled, disable it if so..\n apicbar = readmsr(MSR_APIC_BAR);\n if (apicbar & APIC_BAR_X2APIC_EN) {\n \/\/ Disable x2APIC and the xAPIC\n apicbar &= ~(APIC_BAR_XAPIC_EN | APIC_BAR_X2APIC_EN);\n writemsr(MSR_APIC_BAR, apicbar);\n \/\/ Re-enable the xAPIC\n apicbar |= APIC_BAR_XAPIC_EN;\n writemsr(MSR_APIC_BAR, apicbar);\n \/\/ Sanity-check..\n u32 ebx;\n cpuid(CPUID_FEATURES, 0, &ebx, 0, 0);\n assert(xapic[ID]>>24 == FEATURE_EBX_APIC(ebx));\n }\n\n \/\/ Enable local APIC; set spurious interrupt vector.\n xapicw(SVR, ENABLE | (T_IRQ0 + IRQ_SPURIOUS));\n\n if (xapichz == 0) {\n \/\/ Measure the TICR frequency\n xapicw(TDCR, X1); \n xapicw(TICR, 0xffffffff); \n u64 ccr0 = xapicr(TCCR);\n microdelay(10 * 1000); \/\/ 1\/100th of a second\n u64 ccr1 = xapicr(TCCR);\n xapichz = 100 * (ccr0 - ccr1);\n }\n\n count = (QUANTUM*xapichz) \/ 1000;\n if (count > 0xffffffff)\n panic(\"initxapic: QUANTUM too large\");\n\n \/\/ The timer repeatedly counts down at bus frequency\n \/\/ from xapic[TICR] and then issues an interrupt. \n xapicw(TDCR, X1);\n xapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));\n xapicw(TICR, count); \n\n \/\/ Disable logical interrupt lines.\n xapicw(LINT0, MASKED);\n xapicw(LINT1, MASKED);\n\n \/\/ Disable performance counter overflow interrupts\n \/\/ on machines that provide that interrupt entry.\n if(((xapic[VER]>>16) & 0xFF) >= 4)\n xapicpc(0);\n\n \/\/ Map error interrupt to IRQ_ERROR.\n xapicw(ERROR, T_IRQ0 + IRQ_ERROR);\n\n \/\/ Clear error status register (requires back-to-back writes).\n xapicw(ESR, 0);\n xapicw(ESR, 0);\n\n \/\/ Ack any outstanding interrupts.\n xapicw(EOI, 0);\n\n \/\/ Send an Init Level De-Assert to synchronise arbitration ID's.\n xapicw(ICRHI, 0);\n xapicw(ICRLO, BCAST | INIT | LEVEL);\n while(xapic[ICRLO] & DELIVS)\n ;\n\n \/\/ Enable interrupts on the APIC (but not on the processor).\n xapicw(TPR, 0);\n}\n\nvoid\nxapicpc(char mask)\n{\n xapicw(PCINT, mask ? MASKED : MT_NMI);\n}\n\nhwid_t\nxapicid(void)\n{\n if (readrflags() & FL_IF) {\n cli();\n panic(\"cpunum() called from %p with interrupts enabled\\n\",\n __builtin_return_address(0));\n }\n\n \/\/ To be safe, read the APIC ID from the CPUID register\n u32 ebx;\n cpuid(CPUID_FEATURES, 0, &ebx, 0, 0);\n return HWID(FEATURE_EBX_APIC(ebx));\n\n#if 0\n \/\/ It should be safe to read from the APIC's MMIO anytime,\n \/\/ but it's not. The BIOS might have enabled the x2APIC,\n \/\/ in which case the value of xapic[ID]>>24 is undefined.\n if (xapic == nullptr)\n panic(\"xapicid\");\n return HWID(xapic[ID]>>24);\n#endif\n}\n\n\/\/ Acknowledge interrupt.\nvoid\nxapiceoi(void)\n{\n if(xapic)\n xapicw(EOI, 0);\n}\n\n\/\/ Send IPI\nvoid\nxapic_ipi(hwid_t hwid, int ino)\n{\n xapicw(ICRHI, hwid.num << 24);\n xapicw(ICRLO, FIXED | DEASSERT | ino);\n if (xapicwait() < 0)\n panic(\"xapic_ipi: xapicwait failure\");\n}\n\nvoid\nxapic_tlbflush(hwid_t hwid)\n{\n xapic_ipi(hwid, T_TLBFLUSH);\n}\n\nvoid\nxapic_sampconf(hwid_t hwid)\n{\n xapic_ipi(hwid, T_SAMPCONF);\n}\n\n\/\/ Start additional processor running bootstrap code at addr.\n\/\/ See Appendix B of MultiProcessor Specification.\nvoid\nxapicstartap(hwid hwid, u32 addr)\n{\n int i;\n volatile u16 *wrv;\n\n \/\/ \"The BSP must initialize CMOS shutdown code to 0AH\n \/\/ and the warm reset vector (DWORD based at 40:67) to point at\n \/\/ the AP startup code prior to the [universal startup algorithm].\"\n outb(IO_RTC, 0xF); \/\/ offset 0xF is shutdown code\n outb(IO_RTC+1, 0x0A);\n wrv = (u16*)(0x40<<4 | 0x67); \/\/ Warm reset vector\n wrv[0] = 0;\n wrv[1] = addr >> 4;\n\n \/\/ \"Universal startup algorithm.\"\n \/\/ Send INIT (level-triggered) interrupt to reset other CPU.\n xapicw(ICRHI, hwid.num<<24);\n xapicw(ICRLO, hwid.num | INIT | LEVEL | ASSERT);\n xapicwait();\n microdelay(10000);\n xapicw(ICRLO, hwid.num |INIT | LEVEL);\n xapicwait();\n microdelay(10000); \/\/ should be 10ms, but too slow in Bochs!\n \n \/\/ Send startup IPI (twice!) to enter bootstrap code.\n \/\/ Regular hardware is supposed to only accept a STARTUP\n \/\/ when it is in the halted state due to an INIT. So the second\n \/\/ should be ignored, but it is part of the official Intel algorithm.\n \/\/ Bochs complains about the second one. Too bad for Bochs.\n for(i = 0; i < 2; i++){\n xapicw(ICRHI, hwid.num<<24);\n xapicw(ICRLO, STARTUP | (addr>>12));\n microdelay(200);\n }\n}\n<commit_msg>Some XXX on the old xapic code<commit_after>\/\/ The local APIC manages internal (non-I\/O) interrupts.\n\/\/ See Chapter 8 & Appendix C of Intel processor manual volume 3.\n\n#include \"types.h\"\n#include \"amd64.h\"\n#include \"kernel.hh\"\n#include \"traps.h\"\n#include \"bits.hh\"\n#include \"cpu.hh\"\n#include \"apic.hh\"\n\n\/\/ Local APIC registers, divided by 4 for use as uint[] indices.\n#define ID (0x0020\/4) \/\/ ID\n#define VER (0x0030\/4) \/\/ Version\n#define TPR (0x0080\/4) \/\/ Task Priority\n#define EOI (0x00B0\/4) \/\/ EOI\n#define SVR (0x00F0\/4) \/\/ Spurious Interrupt Vector\n #define ENABLE 0x00000100 \/\/ Unit Enable\n#define ESR (0x0280\/4) \/\/ Error Status\n#define ICRLO (0x0300\/4) \/\/ Interrupt Command\n #define INIT 0x00000500 \/\/ INIT\/RESET\n #define STARTUP 0x00000600 \/\/ Startup IPI\n #define DELIVS 0x00001000 \/\/ Delivery status\n #define ASSERT 0x00004000 \/\/ Assert interrupt (vs deassert)\n #define DEASSERT 0x00000000\n #define LEVEL 0x00008000 \/\/ Level triggered\n #define BCAST 0x00080000 \/\/ Send to all APICs, including self.\n\/\/ XXX(sbw) BUSY and DELIVS?\n #define BUSY 0x00001000\n #define FIXED 0x00000000\n#define ICRHI (0x0310\/4) \/\/ Interrupt Command [63:32]\n#define TIMER (0x0320\/4) \/\/ Local Vector Table 0 (TIMER)\n #define X1 0x0000000B \/\/ divide counts by 1\n #define PERIODIC 0x00020000 \/\/ Periodic\n#define PCINT (0x0340\/4) \/\/ Performance Counter LVT\n#define LINT0 (0x0350\/4) \/\/ Local Vector Table 1 (LINT0)\n#define LINT1 (0x0360\/4) \/\/ Local Vector Table 2 (LINT1)\n#define ERROR (0x0370\/4) \/\/ Local Vector Table 3 (ERROR)\n #define MASKED 0x00010000 \/\/ Interrupt masked\n #define MT_NMI 0x00000400 \/\/ NMI message type\n #define MT_FIX 0x00000000 \/\/ Fixed message type\n#define TICR (0x0380\/4) \/\/ Timer Initial Count\n#define TCCR (0x0390\/4) \/\/ Timer Current Count\n#define TDCR (0x03E0\/4) \/\/ Timer Divide Configuration\n\n#define IO_RTC 0x70\n\nstatic volatile u32 *xapic = (u32 *)(KBASE + 0xfee00000);\nstatic u64 xapichz;\n\nstatic void\nxapicw(int index, int value)\n{\n xapic[index] = value;\n xapic[ID]; \/\/ wait for write to finish, by reading\n}\n\nstatic u32\nxapicr(u32 off)\n{\n return xapic[off];\n}\n\nstatic int\nxapicwait()\n{\n int i = 100000;\n while ((xapicr(ICRLO) & BUSY) != 0) {\n nop_pause();\n i--;\n if (i == 0) {\n cprintf(\"xapicwait: wedged?\\n\");\n return -1;\n }\n }\n return 0;\n}\n\nvoid\ninitxapic(void)\n{\n u64 count;\n u64 apicbar;\n\n \/\/ See Intel Arch. Manual Vol 3a, the APIC section\n \/\/ Check if x2APIC is enabled, disable it if so..\n apicbar = readmsr(MSR_APIC_BAR);\n if (apicbar & APIC_BAR_X2APIC_EN) {\n \/\/ Disable x2APIC and the xAPIC\n apicbar &= ~(APIC_BAR_XAPIC_EN | APIC_BAR_X2APIC_EN);\n writemsr(MSR_APIC_BAR, apicbar);\n \/\/ Re-enable the xAPIC\n apicbar |= APIC_BAR_XAPIC_EN;\n writemsr(MSR_APIC_BAR, apicbar);\n \/\/ Sanity-check..\n u32 ebx;\n cpuid(CPUID_FEATURES, 0, &ebx, 0, 0);\n assert(xapic[ID]>>24 == FEATURE_EBX_APIC(ebx));\n }\n\n \/\/ Enable local APIC; set spurious interrupt vector.\n xapicw(SVR, ENABLE | (T_IRQ0 + IRQ_SPURIOUS));\n\n if (xapichz == 0) {\n \/\/ Measure the TICR frequency\n xapicw(TDCR, X1); \n xapicw(TICR, 0xffffffff); \n u64 ccr0 = xapicr(TCCR);\n microdelay(10 * 1000); \/\/ 1\/100th of a second\n u64 ccr1 = xapicr(TCCR);\n xapichz = 100 * (ccr0 - ccr1);\n }\n\n count = (QUANTUM*xapichz) \/ 1000;\n if (count > 0xffffffff)\n panic(\"initxapic: QUANTUM too large\");\n\n \/\/ The timer repeatedly counts down at bus frequency\n \/\/ from xapic[TICR] and then issues an interrupt. \n xapicw(TDCR, X1);\n xapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));\n xapicw(TICR, count); \n\n \/\/ Disable logical interrupt lines.\n xapicw(LINT0, MASKED);\n xapicw(LINT1, MASKED);\n\n \/\/ Disable performance counter overflow interrupts\n \/\/ on machines that provide that interrupt entry.\n if(((xapic[VER]>>16) & 0xFF) >= 4)\n xapicpc(0);\n\n \/\/ Map error interrupt to IRQ_ERROR.\n xapicw(ERROR, T_IRQ0 + IRQ_ERROR);\n\n \/\/ Clear error status register (requires back-to-back writes).\n xapicw(ESR, 0);\n xapicw(ESR, 0);\n\n \/\/ Ack any outstanding interrupts.\n xapicw(EOI, 0);\n\n \/\/ Send an Init Level De-Assert to synchronise arbitration ID's.\n xapicw(ICRHI, 0);\n xapicw(ICRLO, BCAST | INIT | LEVEL);\n while(xapic[ICRLO] & DELIVS)\n ;\n\n \/\/ Enable interrupts on the APIC (but not on the processor).\n xapicw(TPR, 0);\n}\n\nvoid\nxapicpc(char mask)\n{\n xapicw(PCINT, mask ? MASKED : MT_NMI);\n}\n\nhwid_t\nxapicid(void)\n{\n if (readrflags() & FL_IF) {\n cli();\n panic(\"cpunum() called from %p with interrupts enabled\\n\",\n __builtin_return_address(0));\n }\n\n \/\/ To be safe, read the APIC ID from the CPUID register\n u32 ebx;\n cpuid(CPUID_FEATURES, 0, &ebx, 0, 0);\n return HWID(FEATURE_EBX_APIC(ebx));\n\n#if 0\n \/\/ It should be safe to read from the APIC's MMIO anytime,\n \/\/ but it's not. The BIOS might have enabled the x2APIC,\n \/\/ in which case the value of xapic[ID]>>24 is undefined.\n if (xapic == nullptr)\n panic(\"xapicid\");\n return HWID(xapic[ID]>>24);\n#endif\n}\n\n\/\/ Acknowledge interrupt.\nvoid\nxapiceoi(void)\n{\n if(xapic)\n xapicw(EOI, 0);\n}\n\n\/\/ Send IPI\nvoid\nxapic_ipi(hwid_t hwid, int ino)\n{\n xapicw(ICRHI, hwid.num << 24);\n xapicw(ICRLO, FIXED | DEASSERT | ino);\n if (xapicwait() < 0)\n panic(\"xapic_ipi: xapicwait failure\");\n}\n\nvoid\nxapic_tlbflush(hwid_t hwid)\n{\n xapic_ipi(hwid, T_TLBFLUSH);\n}\n\nvoid\nxapic_sampconf(hwid_t hwid)\n{\n xapic_ipi(hwid, T_SAMPCONF);\n}\n\n\/\/ Start additional processor running bootstrap code at addr.\n\/\/ See Appendix B of MultiProcessor Specification.\nvoid\nxapicstartap(hwid hwid, u32 addr)\n{\n int i;\n volatile u16 *wrv;\n\n \/\/ \"The BSP must initialize CMOS shutdown code to 0AH\n \/\/ and the warm reset vector (DWORD based at 40:67) to point at\n \/\/ the AP startup code prior to the [universal startup algorithm].\"\n outb(IO_RTC, 0xF); \/\/ offset 0xF is shutdown code\n outb(IO_RTC+1, 0x0A);\n wrv = (u16*)(0x40<<4 | 0x67); \/\/ Warm reset vector\n wrv[0] = 0;\n wrv[1] = addr >> 4;\n\n \/\/ \"Universal startup algorithm.\"\n \/\/ Send INIT (level-triggered) interrupt to reset other CPU.\n \n\n xapicw(ICRHI, hwid.num<<24);\n \/\/ XXX(sbw) why hwid.num in ICRLO?\n xapicw(ICRLO, hwid.num | INIT | LEVEL | ASSERT);\n xapicwait();\n microdelay(10000);\n \/\/ XXX(sbw) why hwid.num in ICRLO?\n xapicw(ICRLO, hwid.num |INIT | LEVEL);\n xapicwait();\n microdelay(10000); \/\/ should be 10ms, but too slow in Bochs!\n \n \/\/ Send startup IPI (twice!) to enter bootstrap code.\n \/\/ Regular hardware is supposed to only accept a STARTUP\n \/\/ when it is in the halted state due to an INIT. So the second\n \/\/ should be ignored, but it is part of the official Intel algorithm.\n \/\/ Bochs complains about the second one. Too bad for Bochs.\n for(i = 0; i < 2; i++){\n xapicw(ICRHI, hwid.num<<24);\n xapicw(ICRLO, STARTUP | (addr>>12));\n microdelay(200);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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 \"net\/base\/cert_database.h\"\n\n#include <openssl\/x509.h>\n\n#include \"base\/logging.h\"\n#include \"net\/base\/crypto_module.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/openssl_private_key_store.h\"\n#include \"net\/base\/x509_certificate.h\"\n\nnamespace net {\n\nCertDatabase::CertDatabase() {\n}\n\nint CertDatabase::CheckUserCert(X509Certificate* cert) {\n if (!cert)\n return ERR_CERT_INVALID;\n if (cert->HasExpired())\n return ERR_CERT_DATE_INVALID;\n\n if (!OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(\n X509_PUBKEY_get(X509_get_X509_PUBKEY(cert->os_cert_handle()))))\n return ERR_NO_PRIVATE_KEY_FOR_CERT;\n\n return OK;\n}\n\nint CertDatabase::AddUserCert(X509Certificate* cert) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return ERR_NOT_IMPLEMENTED;\n}\n\nvoid CertDatabase::ListCerts(CertificateList* certs) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n}\n\nCryptoModule* CertDatabase::GetPublicModule() const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return NULL;\n}\n\nCryptoModule* CertDatabase::GetPrivateModule() const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid CertDatabase::ListModules(CryptoModuleList* modules, bool need_rw) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n modules->clear();\n}\n\nint CertDatabase::ImportFromPKCS12(CryptoModule* module,\n const std::string& data,\n const string16& password,\n bool is_extractable) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return ERR_NOT_IMPLEMENTED;\n}\n\nint CertDatabase::ExportToPKCS12(const CertificateList& certs,\n const string16& password,\n std::string* output) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return 0;\n}\n\nbool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return false;\n}\n\nCertDatabase::TrustBits CertDatabase::GetCertTrust(const X509Certificate* cert,\n CertType type) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return 0;\n}\n\nbool CertDatabase::SetCertTrust(const X509Certificate* cert,\n CertType type,\n TrustBits trust_bits) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return false;\n}\n\n} \/\/ namespace net\n<commit_msg>net: build fix for OpenSSL from r113998<commit_after>\/\/ Copyright (c) 2011 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 \"net\/base\/cert_database.h\"\n\n#include <openssl\/x509.h>\n\n#include \"base\/logging.h\"\n#include \"net\/base\/crypto_module.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/openssl_private_key_store.h\"\n#include \"net\/base\/x509_certificate.h\"\n\nnamespace net {\n\nCertDatabase::CertDatabase() {\n}\n\nint CertDatabase::CheckUserCert(X509Certificate* cert) {\n if (!cert)\n return ERR_CERT_INVALID;\n if (cert->HasExpired())\n return ERR_CERT_DATE_INVALID;\n\n if (!OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(\n X509_PUBKEY_get(X509_get_X509_PUBKEY(cert->os_cert_handle()))))\n return ERR_NO_PRIVATE_KEY_FOR_CERT;\n\n return OK;\n}\n\nint CertDatabase::AddUserCert(X509Certificate* cert) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return ERR_NOT_IMPLEMENTED;\n}\n\nvoid CertDatabase::ListCerts(CertificateList* certs) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n}\n\nCryptoModule* CertDatabase::GetPublicModule() const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return NULL;\n}\n\nCryptoModule* CertDatabase::GetPrivateModule() const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid CertDatabase::ListModules(CryptoModuleList* modules, bool need_rw) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n modules->clear();\n}\n\nint CertDatabase::ImportFromPKCS12(CryptoModule* module,\n const std::string& data,\n const string16& password,\n bool is_extractable,\n CertificateList* imported_certs) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return ERR_NOT_IMPLEMENTED;\n}\n\nint CertDatabase::ExportToPKCS12(const CertificateList& certs,\n const string16& password,\n std::string* output) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return 0;\n}\n\nbool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return false;\n}\n\nCertDatabase::TrustBits CertDatabase::GetCertTrust(const X509Certificate* cert,\n CertType type) const {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return 0;\n}\n\nbool CertDatabase::SetCertTrust(const X509Certificate* cert,\n CertType type,\n TrustBits trust_bits) {\n \/\/ TODO(bulach): implement me.\n NOTIMPLEMENTED();\n return false;\n}\n\n} \/\/ namespace net\n<|endoftext|>"} {"text":"<commit_before>\/**\n Copyright 2017 Daniel Garcia Vaglio <degv364@gmail.com> Esteban Zamora Alvarado <estebanzacr.20@gmail.com>\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\n associated documentation files (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge, publish, distribute,\n sublicense, and\/or sell 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 all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES\n OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **\/\n\n\/* Standard Includes *\/\n#include <ti\/devices\/msp432p4xx\/driverlib\/driverlib.h>\n#include <stdint.h>\n#include <stdbool.h>\n#include \"msp.h\"\n\n\/* Project Includes*\/\n#include \"common_def.hh\"\n#include \"hd\/periph.hh\"\n#include \"hi\/hi_def.hh\"\n\n\/*Variables defined in other files*\/\nextern volatile uint64_t g_SystemTicks;\n\n\/\/FIXME: Remove after testing ADC config\nextern volatile int16_t resultsBuffer[3];\n\n\/*Interrupt Service Routines (ISR) Definition*\/\nextern \"C\"\n{\n\n\/* ISR activated by Timer32-1 for time measurement through the\n * software timer update\n*\/\nvoid T32_INT1_IRQHandler(void)\n{\n __disable_irq();\n\n periph::Timer::cleanIRQ(TIMER32_0_BASE);\n g_SystemTicks++;\n\n __enable_irq();\n}\n\n\n\/* ISR activated by Timer32-2 for ADC sampling frequency\n*\/\nvoid T32_INT2_IRQHandler(void)\n{\n __disable_irq();\n\n periph::Timer::cleanIRQ(TIMER32_1_BASE);\n \/\/FIXME: Implement ADC Timer ISR\n MAP_ADC14_toggleConversionTrigger();\n\n __enable_irq();\n}\n\n\/* ISR that manages the ADC Accelerometer reading\n * sampling frequency\n*\/\nvoid ADC14_IRQHandler(void)\n{\n __disable_irq();\n \/\/FIXME: Implement ADC ISR\n\n if (periph::AccelADC::CheckAndCleanIRQ(ADC_INT2))\n {\n resultsBuffer[0] = ADC14_getResult(ADC_MEM0);\n resultsBuffer[1] = ADC14_getResult(ADC_MEM1);\n resultsBuffer[2] = ADC14_getResult(ADC_MEM2);\n }\n\n __enable_irq();\n}\n\n}\n\n<commit_msg>Updated Lab2 ISR Fixmes<commit_after>\/**\n Copyright 2017 Daniel Garcia Vaglio <degv364@gmail.com> Esteban Zamora Alvarado <estebanzacr.20@gmail.com>\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\n associated documentation files (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge, publish, distribute,\n sublicense, and\/or sell 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 all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES\n OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **\/\n\n\/* Standard Includes *\/\n#include <ti\/devices\/msp432p4xx\/driverlib\/driverlib.h>\n#include <stdint.h>\n#include <stdbool.h>\n#include \"msp.h\"\n\n\/* Project Includes*\/\n#include \"common_def.hh\"\n#include \"hd\/periph.hh\"\n#include \"hi\/hi_def.hh\"\n\n\/*Variables defined in other files*\/\nextern volatile uint64_t g_SystemTicks;\n\n\/\/FIXME: Remove after testing ADC config\nextern volatile int16_t resultsBuffer[3];\n\n\/*Interrupt Service Routines (ISR) Definition*\/\nextern \"C\"\n{\n\n\/* ISR activated by Timer32-1 for time measurement through the\n * software timer update\n*\/\nvoid T32_INT1_IRQHandler(void)\n{\n __disable_irq();\n\n periph::Timer::cleanIRQ(TIMER32_0_BASE);\n \/\/FIXME: Check if frame is finished\n g_SystemTicks++;\n\n __enable_irq();\n}\n\n\n\/* ISR activated by Timer32-2 for ADC sampling frequency\n*\/\nvoid T32_INT2_IRQHandler(void)\n{\n __disable_irq();\n\n periph::Timer::cleanIRQ(TIMER32_1_BASE);\n MAP_ADC14_toggleConversionTrigger();\n\n __enable_irq();\n}\n\n\/* ISR that manages the ADC Accelerometer reading\n * sampling frequency\n*\/\nvoid ADC14_IRQHandler(void)\n{\n __disable_irq();\n \/\/FIXME: Implement ADC ISR\n\n if (periph::AccelADC::CheckAndCleanIRQ(ADC_INT2))\n {\n resultsBuffer[0] = ADC14_getResult(ADC_MEM0);\n resultsBuffer[1] = ADC14_getResult(ADC_MEM1);\n resultsBuffer[2] = ADC14_getResult(ADC_MEM2);\n }\n\n __enable_irq();\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 09\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_TDATASOURCE\n#define ROOT_TDATASOURCE\n\n#include \"RStringView.h\"\n#include \"RtypesCore.h\" \/\/ ULong64_t\n#include <algorithm> \/\/ std::transform\n#include <vector>\n#include <typeinfo>\n\nnamespace ROOT {\nnamespace Experimental {\nnamespace TDF {\n\n\/**\n\\class ROOT::Experimental::TDF::TDataSource\n\\ingroup dataframe\n\\brief The TDataSource interface dictates how a TDataFrame interface to an arbitrary data format should look like.\n\nA TDataSource allows to seamlessly provide an adaptor for any kind of data set or data format to the TDataFrame. Another way to imagine it is a veritable \"cursor\".\n*\/\nclass TDataSource {\npublic:\n virtual ~TDataSource() = default;\n\n \/\/\/ \\brief Returns a reference to the collection of the dataset's column names\n virtual const std::vector<std::string> &GetColumnNames() const = 0;\n\n \/\/\/ \\brief Checks if the dataset has a certain column\n \/\/\/ \\param[in] columnName The name of the column\n virtual bool HasColumn(std::string_view) const = 0;\n\n \/\/\/ \\brief Type of a column as a string, e.g. `GetTypeName(\"x\") == \"double\"`. Required for jitting e.g. `df.Filter(\"x>0\")`.\n \/\/\/ \\param[in] columnName The name of the column\n virtual std::string GetTypeName(std::string_view) const = 0;\n\n \/\/\/ Called at most once per column by TDF. Return vector of pointers to pointers to column values - one per slot.\n \/\/\/ \\tparam T The type of the data stored in the column\n \/\/\/ \\param[in] columnName The name of the column\n \/\/\/\n \/\/\/ These pointers are veritable cursors: it's a responsibility of the TDataSource implementation that they point to the\n \/\/\/ \"right\" memory region.\n template <typename T>\n std::vector<T **> GetColumnReaders(std::string_view columnName)\n {\n auto typeErasedVec = GetColumnReadersImpl(columnName, typeid(T));\n std::vector<T **> typedVec(typeErasedVec.size());\n std::transform(typeErasedVec.begin(), typeErasedVec.end(), typedVec.begin(),\n [](void *p) { return static_cast<T **>(p); });\n return typedVec;\n }\n\n \/\/\/ \\brief Return ranges of entries to distribute to tasks.\n \/\/\/ They are required to be contiguous intervals with no entries skipped. Supposing a dataset with nEntries, the intervals\n \/\/\/ must start at 0 and end at nEntries, e.g. [0-5],[5-10] for 10 entries.\n virtual const std::vector<std::pair<ULong64_t, ULong64_t>> &GetEntryRanges() const = 0;\n\n \/\/\/ \\brief Advance the \"cursors\" returned by GetColumnReaders to the selected entry for a particular slot.\n \/\/\/ \\param[in] slot The data processing slot that needs to be considered\n \/\/\/ \\param[in] entry The entry which needs to be pointed to by the reader pointers\n \/\/\/ Slots are adopted to accommodate parallel data processing. Different workers will loop over different ranges and will\n \/\/\/ be labelled by different \"slot\" values.\n virtual void SetEntry(unsigned int slot, ULong64_t entry) = 0;\n\n \/\/\/ \\brief Convenience method to set the number of slots\n \/\/\/ For some implementation it's necessary to know the number of slots in advance for optimisation purposes.\n virtual void SetNSlots(unsigned int nSlots) = 0;\n\n \/\/\/ \\brief Convenience method called at the start of the data processing.\n \/\/\/ \\param[in] slot The data processing slot wihch needs to be initialised\n \/\/\/ \\param[in] firstEntry The first entry of the range that the task will process.\n virtual void InitSlot(unsigned int \/*slot*\/, ULong64_t \/*firstEntry*\/) {}\n\nprotected:\n \/\/\/ type-erased vector of pointers to pointers to column values - one per slot\n virtual std::vector<void *>\n GetColumnReadersImpl(std::string_view name, const std::type_info &) = 0;\n};\n\n} \/\/ ns TDF\n} \/\/ ns Experimental\n} \/\/ ns ROOT\n\n#endif \/\/ ROOT_TDATASOURCE\n<commit_msg>[TDF] Add to the TDataSource the FinaliseSlot method<commit_after>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 09\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_TDATASOURCE\n#define ROOT_TDATASOURCE\n\n#include \"RStringView.h\"\n#include \"RtypesCore.h\" \/\/ ULong64_t\n#include <algorithm> \/\/ std::transform\n#include <vector>\n#include <typeinfo>\n\nnamespace ROOT {\nnamespace Experimental {\nnamespace TDF {\n\n\/**\n\\class ROOT::Experimental::TDF::TDataSource\n\\ingroup dataframe\n\\brief The TDataSource interface dictates how a TDataFrame interface to an arbitrary data format should look like.\n\nA TDataSource allows to seamlessly provide an adaptor for any kind of data set or data format to the TDataFrame. Another way to imagine it is a veritable \"cursor\".\n*\/\nclass TDataSource {\npublic:\n virtual ~TDataSource() = default;\n\n \/\/\/ \\brief Returns a reference to the collection of the dataset's column names\n virtual const std::vector<std::string> &GetColumnNames() const = 0;\n\n \/\/\/ \\brief Checks if the dataset has a certain column\n \/\/\/ \\param[in] columnName The name of the column\n virtual bool HasColumn(std::string_view) const = 0;\n\n \/\/\/ \\brief Type of a column as a string, e.g. `GetTypeName(\"x\") == \"double\"`. Required for jitting e.g. `df.Filter(\"x>0\")`.\n \/\/\/ \\param[in] columnName The name of the column\n virtual std::string GetTypeName(std::string_view) const = 0;\n\n \/\/\/ Called at most once per column by TDF. Return vector of pointers to pointers to column values - one per slot.\n \/\/\/ \\tparam T The type of the data stored in the column\n \/\/\/ \\param[in] columnName The name of the column\n \/\/\/\n \/\/\/ These pointers are veritable cursors: it's a responsibility of the TDataSource implementation that they point to the\n \/\/\/ \"right\" memory region.\n template <typename T>\n std::vector<T **> GetColumnReaders(std::string_view columnName)\n {\n auto typeErasedVec = GetColumnReadersImpl(columnName, typeid(T));\n std::vector<T **> typedVec(typeErasedVec.size());\n std::transform(typeErasedVec.begin(), typeErasedVec.end(), typedVec.begin(),\n [](void *p) { return static_cast<T **>(p); });\n return typedVec;\n }\n\n \/\/\/ \\brief Return ranges of entries to distribute to tasks.\n \/\/\/ They are required to be contiguous intervals with no entries skipped. Supposing a dataset with nEntries, the intervals\n \/\/\/ must start at 0 and end at nEntries, e.g. [0-5],[5-10] for 10 entries.\n virtual const std::vector<std::pair<ULong64_t, ULong64_t>> &GetEntryRanges() const = 0;\n\n \/\/\/ \\brief Advance the \"cursors\" returned by GetColumnReaders to the selected entry for a particular slot.\n \/\/\/ \\param[in] slot The data processing slot that needs to be considered\n \/\/\/ \\param[in] entry The entry which needs to be pointed to by the reader pointers\n \/\/\/ Slots are adopted to accommodate parallel data processing. Different workers will loop over different ranges and will\n \/\/\/ be labelled by different \"slot\" values.\n virtual void SetEntry(unsigned int slot, ULong64_t entry) = 0;\n\n \/\/\/ \\brief Convenience method to set the number of slots\n \/\/\/ For some implementation it's necessary to know the number of slots in advance for optimisation purposes.\n virtual void SetNSlots(unsigned int nSlots) = 0;\n\n \/\/\/ \\brief Convenience method called at the start of the data processing associated to a slot.\n \/\/\/ \\param[in] slot The data processing slot wihch needs to be initialised\n \/\/\/ \\param[in] firstEntry The first entry of the range that the task will process.\n virtual void InitSlot(unsigned int \/*slot*\/, ULong64_t \/*firstEntry*\/) {}\n\n \/\/\/ \\brief Convenience method called at the end of the data processing associated to a slot.\n \/\/\/ \\param[in] slot The data processing slot wihch needs to be finalised\n virtual void FinaliseSlot(unsigned int \/*slot*\/) {}\n\nprotected:\n \/\/\/ type-erased vector of pointers to pointers to column values - one per slot\n virtual std::vector<void *>\n GetColumnReadersImpl(std::string_view name, const std::type_info &) = 0;\n};\n\n} \/\/ ns TDF\n} \/\/ ns Experimental\n} \/\/ ns ROOT\n\n#endif \/\/ ROOT_TDATASOURCE\n<|endoftext|>"} {"text":"<commit_before>void MUONtestabso (Int_t evNumber1=0,Int_t evNumber2=0) \n{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This macro is a small example of a ROOT macro\n\/\/ illustrating how to read the output of GALICE\n\/\/ and do some analysis.\n\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Dynamically link some shared libs \n static Float_t xmuon, ymuon;\n \n if (gClassTable->GetID(\"AliRun\") < 0) {\n gROOT->LoadMacro(\"loadlibs.C\");\n loadlibs();\n }\n\n\/\/ Connect the Root Galice file containing Geometry, Kine and Hits\n\n TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(\"galice.root\");\n\n \n if (!file) {\n\tprintf(\"\\n Creating galice.root \\n\");\n\tfile = new TFile(\"galice.root\");\n } else {\n\tprintf(\"\\n galice.root found in file list\");\n }\n file->ls();\n \n\/\/ Get AliRun object from file or create it if not on file\n if (!gAlice) {\n\tgAlice = (AliRun*)(file->Get(\"gAlice\"));\n\tif (gAlice) printf(\"AliRun object found on file\\n\");\n\tif (!gAlice) {\n\t printf(\"\\n Create new gAlice object\");\n\t gAlice = new AliRun(\"gAlice\",\"Alice test program\");\n\t}\n }\n\n \n\/\/ Create some histograms\n\n\n TH1F *zv = new TH1F(\"zv\",\"z vertex\" ,140,470.,505.);\n TH1F *xv = new TH1F(\"xv\",\"x vertex\" ,140,-70.,70.);\n TH1F *yv = new TH1F(\"yv\",\"y vertex\", 140,-70.,70.);\n\n TH1F *ip = new TH1F(\"ip\",\"geant part\",50,0.,10.);\n TH2F *rzv = new TH2F(\"rzv\",\"R-z vert\",100,502,504.,100,0.,100.);\n\n TH1F *ptUps = new TH1F(\"ptUps\",\"pT Upsilon\",50,0.,25.);\n TH1F *hde = new TH1F(\"hde\",\"dE\",200,0.,50);\n TH1F *hde2 = new TH1F(\"hde2\",\"dE\",100,1.5,5.5);\n TH2F *hdevsn = new TH2F(\"hdevsn\",\"dE vs N electron\",100,0.,15., 20, 0.,20.);\n\n TH1F *ekine = new TH1F(\"ekine\",\"E_kin electrons\",70,-5,2);\n TH1F *etheta = new TH1F(\"etheta\",\"Theta electrons\",90,0,90);\n TH1F *edr = new TH1F(\"edr\",\"Distance to muon\",100,0,10);\n\n TH1F *de = new TH1F(\"de\",\"correction\",100,-1,1);\n\n TH1F *dtheta = new TH1F(\"dtheta\",\"Delta Theta\" ,200,-5.,5.);\n AliMUONChamber* iChamber;\n\/\/\n\/\/ Loop over events \n\/\/\n Int_t Nh=0;\n Int_t Nh1=0;\n Int_t Nel1=0;\n Int_t Nel2=0;\n Int_t Nel3=0;\n Int_t Nel4=0;\n \n for (Int_t nev=0; nev<= evNumber2; nev++) {\n \/\/cout << \"nev \" << nev <<endl;\n Int_t nparticles = gAlice->GetEvent(nev);\n \/\/cout << \"nparticles \" << nparticles <<endl;\n if (nev < evNumber1) continue;\n if (nparticles <= 0) return;\n \n AliMUON *MUON = (AliMUON*) gAlice->GetModule(\"MUON\");\n\n\n TTree *TH = gAlice->TreeH();\n Int_t ntracks = TH->GetEntries();\n\/\/\n\/\/ Loop over tracks\n\/\/\n\n Float_t dE;\n \n for (Int_t track=0; track<ntracks;track++) {\n\t Int_t Nelt=0;\t \n\t printf(\"\\n nev %d %d %d %d %d\\n \", nev, Nel1, Nel2, Nel3, Nel4);\n\t gAlice->ResetHits();\n\t Int_t nbytes += TH->GetEvent(track);\n\t if (MUON) {\n\t for(AliMUONHit* mHit=(AliMUONHit*)MUON->FirstHit(-1); \n\t\t mHit;\n\t\t mHit=(AliMUONHit*)MUON->NextHit()) \n\t {\n\t\t Int_t nch = mHit->fChamber; \/\/ chamber number\n\t\t Float_t x = mHit->fX; \/\/ x-pos of hit\n\t\t Float_t y = mHit->fY; \/\/ y-pos\n\t\t Float_t z = mHit->fZ; \/\/ y-pos\n\t\t \n\t\t if (nch != 1) continue;\n\t\t \n\t\t Int_t ipart = mHit->fParticle;\n\t\t TClonesArray *fPartArray = gAlice->Particles();\n\t\t TParticle *Part;\n\t\t Int_t ftrack = mHit->fTrack;\n\t\t Part = (TParticle*) fPartArray->UncheckedAt(ftrack);\n\t\t Int_t ipart = Part->GetPdgCode();\n\t\t ip->Fill((float)ipart);\n\t\t TParticle *Mother;\n\t\t \n\t\t Float_t px0=Part->Px();\n\t\t Float_t py0=Part->Py();\t\t \n\t\t Float_t pz0=Part->Pz();\n\t\t Float_t thetax0=TMath::ATan2(px0,pz0);\n\t\t Float_t thetay0=TMath::ATan2(py0,pz0);\t\t \n\t\t \n\t\t if (ipart == kMuonPlus || ipart == kMuonMinus) {\n\/\/\t\t Int_t imo = Part->GetFirstMother();\n\/\/\t\t Mother = (TParticle*) fPartArray->UncheckedAt(imo);\n\/\/\t\t Float_t pt = Mother->Pt();\n\/\/\t\t ptUps->Fill(pt, (float) 1);\n\t\t Float_t E=Part->Energy();\n\t\t Float_t Eloc=mHit->fPTot;\n\t\t Float_t corr=Eloc+CorrectP(Eloc,mHit->fTheta);\n\t\t printf(\"\\n %f %f %f\", E, Eloc, corr);\n\t\t de->Fill(E-corr,1.);\n\t\t dE = E-Eloc;\n\t\t if (dE<50) hde->Fill(dE, (float) 1);\n\t\t if (dE<5.5) hde2->Fill(dE, (float) 1);\n\t\t xmuon=mHit->fX;\n\t\t ymuon=mHit->fY;\n\t\t Float_t thetax=TMath::ATan2(mHit->Px(), mHit->Momentum());\n\t\t Float_t thetay=TMath::ATan2(mHit->Py(), mHit->Momentum());\n\t\t dtheta->Fill((thetax-thetax0)*1000., 1.);\n\t\t dtheta->Fill((thetay-thetay0)*1000., 1.);\t\t \n\t\t }\n\t\t \n\t\t if (ipart == kElectron || ipart == kPositron) {\n\n\t\t \n\t\t Float_t xvert = Part->Vx(); \/\/ vertex \n\t\t Float_t yvert = Part->Vy(); \/\/ vertex\n\t\t Float_t zvert = Part->Vz(); \/\/ z vertex \n\t\t if (zvert < 503 && mHit->fTheta<90) {\n\t\t\t Nelt++;\n\t\t\t Float_t px = Part->Px();\n\t\t\t Float_t py = Part->Py();\n\t\t\t Float_t pz = Part->Pz();\n\t\t\t Float_t Ek = Part->Energy()-Part->GetMass();\n\t\t\t \n\t\t\t Int_t imo = Part->GetFirstMother();\n\t\t\t Mother = (TParticle*) fPartArray->UncheckedAt(imo);\n\t\t\t Int_t imot = Mother->GetPdgCode();\n\t\t\t xv->Fill(xvert);\n\t\t\t yv->Fill(yvert);\n\t\t\t zv->Fill(zvert);\n\t\t\t Float_t rvert=TMath::Sqrt(xvert*xvert+yvert*yvert);\n\t\t\t rzv->Fill(zvert,rvert);\n\t\t\t ekine->Fill(TMath::Log10(Ek),1.);\n\t\t\t etheta->Fill(mHit->fTheta,1.);\n\t\t\t Float_t ex=mHit->fX;\n\t\t\t Float_t ey=mHit->fY;\n\t\t\t dr=TMath::Sqrt((ex-xmuon)*(ex-xmuon)+(ey-ymuon)*(ey-ymuon));\n\t\t\t edr->Fill(dr,1.);\n\t\t\t \n\t\t }\n\t\t }\n\t\t \n\t } \/\/ hits \n\t } \/\/ if MUON \n\t if (Nelt == 1) Nel1++;\n\t if (Nelt == 2) Nel2++;\n\t if (Nelt == 3) Nel3++;\n\t if (Nelt > 3) Nel4++;\n\t hdevsn->Fill(dE, (float) Nelt, (float) 1);\n\n } \/\/ tracks\n\n } \/\/ event\n\n \n\/\/Create a canvas, set the view range, show histograms\n TCanvas *c1 = new TCanvas(\"c1\",\"Vetices from electrons and positrons\",400,10,600,700);\n c1->Divide(2,2);\n \n c1->cd(1);\n ip->SetFillColor(42);\n ip->SetXTitle(\"ipart\");\n ip->Draw();\n\n c1->cd(2);\n xv->SetFillColor(42);\n xv->SetXTitle(\"xvert\");\n xv->Draw();\n\n c1->cd(3);\n yv->SetFillColor(42);\n yv->SetXTitle(\"yvert\");\n yv->Draw();\n\n c1->cd(4);\n zv->SetFillColor(42);\n zv->SetXTitle(\"zvert\");\n zv->Draw();\n\n TCanvas *c2 = new TCanvas(\"c2\",\" \",400,10,600,700);\n c2->Divide(2,2);\n c2->cd(1);\n rzv->SetXTitle(\"zvert\");\n rzv->SetYTitle(\"rvert\");\n rzv->Draw();\n\n c2->cd(2);\n ptUps->SetXTitle(\"pt\");\n ptUps->Draw();\n\n c2->cd(3);\n hde->SetXTitle(\"dE\");\n hde->Draw();\n\n\n c2->cd(4);\n hde2->SetXTitle(\"dE\");\n hde2->Draw();\n TCanvas *c3 = new TCanvas(\"c3\",\" \",400,10,600,700);\n c3->Divide(2,2);\n c3->cd(1);\n ekine->SetXTitle(\"E_kin\");\n ekine->Draw();\n\n c3->cd(2);\n etheta->SetXTitle(\"Theta\");\n etheta->Draw();\n\n c3->cd(3);\n edr->SetXTitle(\"Distance to muon\");\n edr->Draw();\n\n c3->cd(4);\n dtheta->SetXTitle(\" \");\n dtheta->Draw();\n\n}\n\nFloat_t CorrectP(Float_t p, Float_t theta)\n{\n printf(\"\\n %f%\", theta);\n \n if (theta<3.) {\n\/\/W\n\tif (p<15) {\n\t return 2.737+0.0494*p-0.001123*p*p;\n\t} else {\n\t return 3.0643+0.01346*p;\n\t}\n } else {\n\/\/Pb\n\tif (p<15) {\n\t return 2.1380+0.0351*p-0.000853*p*p;\n\t} else {\n\t return 2.407+0.00702*p;\n\t}\n }\n}\n\n<commit_msg>remove obsolete macro<commit_after><|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <winsock.h>\n#include \"..\/lib\/as3.hpp\"\n#include <string>\nusing std::string; using std::to_string;\n#include <iostream>\nusing std::cout; using std::endl; using std::cin;\n\nnamespace as3\n{\n auto inline make_address() -> sockaddr_in\n {\n auto addr = sockaddr_in{};\n memset(&addr, 0, sizeof(addr));\n return addr;\n }\n\n auto inline bind(as3::Socket const& sock, sockaddr_in const& addr) -> bool\n {\n if ( 0 != ::bind(sock.get(), (struct sockaddr *)(&addr), sizeof(addr)) )\n {\n as3::println(\"Bind failed!\");\n return false;\n }\n return true;\n }\n}\n\nint main(int argc, char *argv[])\n{\n as3::setup_win_sock_api(as3::WSVERS);\n as3::Socket sock{ AF_INET, SOCK_STREAM, 0 };\n if (sock.is_failed()) as3::println( \"socket failed\" );\n\n auto local_addr = as3::make_address();\n {\n local_addr.sin_family = AF_INET;\n if (argc == 2) local_addr.sin_port = htons((u_short)atoi(argv[1]));\n else local_addr.sin_port = htons(1234);\/\/default listening port\n local_addr.sin_addr.s_addr = INADDR_ANY;\/\/server IP address should be local\n }\n\n if (as3::bind(sock, local_addr) == false) return 1;\n \/\/if (bind(sock.get(), (struct sockaddr *)(&local_addr), sizeof(local_addr)) != 0)\n \/\/{\n \/\/ as3::println(\"Bind failed!\");\n \/\/ exit(0);\n \/\/}\n\n auto remote_addr = as3::make_address();\n for (listen(sock.get(), 5); true; as3::println(\"disconnected from \" + string(inet_ntoa(remote_addr.sin_addr))))\n {\n int addrlen = sizeof(remote_addr);\n as3::Socket new_sock{ ::accept(sock.get(), (sockaddr*)(&remote_addr), &addrlen) };\n if (new_sock.is_failed()) break;\n as3::println(\"accepted connection from IP \" + string(inet_ntoa(remote_addr.sin_addr)) + \" port \" + to_string(ntohs(remote_addr.sin_port)));\n \n for (auto receive = as3::Receive{}; receive.is_normal(); )\n {\n auto message_reveived = receive(new_sock);\n if (!receive.is_normal()) break;\n as3::println(\"The client is sending:\\n\" + message_reveived);\n \n auto feed_back = \"<<< SERVER SAYS:The client typed '\" + message_reveived + \"' -- \" + to_string(message_reveived.size()) + \" bytes in total\\r\\n\";\n as3::send(new_sock.get(), feed_back);\n }\n }\n return 0;\n}<commit_msg>\tmodified: src\/2015a3\/rsa\/server\/server.cpp<commit_after>#include <stdlib.h>\n#include <winsock.h>\n#include \"..\/lib\/as3.hpp\"\n#include <string>\nusing std::string; using std::to_string;\n#include <iostream>\nusing std::cout; using std::endl; using std::cin;\n\nnamespace as3\n{\n auto inline make_address() -> sockaddr_in\n {\n auto addr = sockaddr_in{};\n memset(&addr, 0, sizeof(addr));\n return addr;\n }\n\n auto inline bind(as3::Socket const& sock, sockaddr_in const& addr) -> bool\n {\n if ( 0 != ::bind(sock.get(), (struct sockaddr *)(&addr), sizeof(addr)) )\n {\n as3::println(\"Bind failed!\");\n return false;\n }\n return true;\n }\n}\n\nint main(int argc, char *argv[])\n{\n as3::setup_win_sock_api(as3::WSVERS);\n as3::Socket sock{ AF_INET, SOCK_STREAM, 0 };\n if (sock.is_failed()) as3::println( \"socket failed\" );\n\n auto local_addr = as3::make_address();\n {\n local_addr.sin_family = AF_INET;\n if (argc == 2) local_addr.sin_port = htons((u_short)atoi(argv[1]));\n else local_addr.sin_port = htons(1234);\/\/default listening port\n local_addr.sin_addr.s_addr = INADDR_ANY;\/\/server IP address should be local\n }\n\n if (as3::bind(sock, local_addr) == false) return 1;\n auto remote_addr = as3::make_address();\n for (listen(sock.get(), 5); true; as3::println(\"disconnected from \" + string(inet_ntoa(remote_addr.sin_addr))))\n {\n int addrlen = sizeof(remote_addr);\n as3::Socket new_sock{ ::accept(sock.get(), (sockaddr*)(&remote_addr), &addrlen) };\n if (new_sock.is_failed()) break;\n as3::println(\"accepted connection from IP \" + string(inet_ntoa(remote_addr.sin_addr)) + \" port \" + to_string(ntohs(remote_addr.sin_port)));\n \n for (auto receive = as3::Receive{}; receive.is_normal(); )\n {\n auto message_reveived = receive(new_sock);\n if (!receive.is_normal()) break;\n as3::println(\"The client is sending:\\n\" + message_reveived);\n \n auto feed_back = \"<<< SERVER SAYS:The client typed '\" + message_reveived + \"' -- \" + to_string(message_reveived.size()) + \" bytes in total\\r\\n\";\n as3::send(new_sock.get(), feed_back);\n }\n }\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"chrome\/common\/child_thread.h\"\n\n#include \"base\/command_line.h\"\n#include \"chrome\/common\/child_process.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/ipc_logging.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nChildThread::ChildThread(Thread::Options options)\n : Thread(\"Chrome_ChildThread\"),\n owner_loop_(MessageLoop::current()),\n in_send_(0),\n options_(options) {\n DCHECK(owner_loop_);\n channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValue(\n switches::kProcessChannelID);\n\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUserAgent)) {\n#if defined(OS_WIN)\n \/\/ TODO(port): calling this connects an, otherwise disconnected, subgraph\n \/\/ of symbols, causing huge numbers of linker errors.\n webkit_glue::SetUserAgent(WideToUTF8(\n CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kUserAgent)));\n#endif\n }\n}\n\nChildThread::~ChildThread() {\n}\n\nbool ChildThread::Run() {\n return StartWithOptions(options_);\n}\n\nvoid ChildThread::OnChannelError() {\n owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());\n}\n\nbool ChildThread::Send(IPC::Message* msg) {\n if (!channel_.get()) {\n delete msg;\n return false;\n }\n\n in_send_++;\n bool rv = channel_->Send(msg);\n in_send_--;\n return rv;\n}\n\nvoid ChildThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) {\n DCHECK(MessageLoop::current() == message_loop());\n\n router_.AddRoute(routing_id, listener);\n}\n\nvoid ChildThread::RemoveRoute(int32 routing_id) {\n DCHECK(MessageLoop::current() == message_loop());\n\n router_.RemoveRoute(routing_id);\n}\n\nvoid ChildThread::OnMessageReceived(const IPC::Message& msg) {\n if (msg.routing_id() == MSG_ROUTING_CONTROL) {\n OnControlMessageReceived(msg);\n } else {\n router_.OnMessageReceived(msg);\n }\n}\n\nChildThread* ChildThread::current() {\n return ChildProcess::current()->child_thread();\n}\n\nvoid ChildThread::Init() {\n channel_.reset(new IPC::SyncChannel(channel_name_,\n IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true,\n ChildProcess::current()->GetShutDownEvent()));\n#ifdef IPC_MESSAGE_LOG_ENABLED\n IPC::Logging::current()->SetIPCSender(this);\n#endif\n}\n\nvoid ChildThread::CleanUp() {\n#ifdef IPC_MESSAGE_LOG_ENABLED\n IPC::Logging::current()->SetIPCSender(NULL);\n#endif\n \/\/ Need to destruct the SyncChannel to the browser before we go away because\n \/\/ it caches a pointer to this thread.\n channel_.reset();\n}\n<commit_msg>Fix release build break<commit_after>\/\/ 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 \"chrome\/common\/child_thread.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/common\/child_process.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/ipc_logging.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nChildThread::ChildThread(Thread::Options options)\n : Thread(\"Chrome_ChildThread\"),\n owner_loop_(MessageLoop::current()),\n in_send_(0),\n options_(options) {\n DCHECK(owner_loop_);\n channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValue(\n switches::kProcessChannelID);\n\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUserAgent)) {\n#if defined(OS_WIN)\n \/\/ TODO(port): calling this connects an, otherwise disconnected, subgraph\n \/\/ of symbols, causing huge numbers of linker errors.\n webkit_glue::SetUserAgent(WideToUTF8(\n CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kUserAgent)));\n#endif\n }\n}\n\nChildThread::~ChildThread() {\n}\n\nbool ChildThread::Run() {\n return StartWithOptions(options_);\n}\n\nvoid ChildThread::OnChannelError() {\n owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());\n}\n\nbool ChildThread::Send(IPC::Message* msg) {\n if (!channel_.get()) {\n delete msg;\n return false;\n }\n\n in_send_++;\n bool rv = channel_->Send(msg);\n in_send_--;\n return rv;\n}\n\nvoid ChildThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) {\n DCHECK(MessageLoop::current() == message_loop());\n\n router_.AddRoute(routing_id, listener);\n}\n\nvoid ChildThread::RemoveRoute(int32 routing_id) {\n DCHECK(MessageLoop::current() == message_loop());\n\n router_.RemoveRoute(routing_id);\n}\n\nvoid ChildThread::OnMessageReceived(const IPC::Message& msg) {\n if (msg.routing_id() == MSG_ROUTING_CONTROL) {\n OnControlMessageReceived(msg);\n } else {\n router_.OnMessageReceived(msg);\n }\n}\n\nChildThread* ChildThread::current() {\n return ChildProcess::current()->child_thread();\n}\n\nvoid ChildThread::Init() {\n channel_.reset(new IPC::SyncChannel(channel_name_,\n IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true,\n ChildProcess::current()->GetShutDownEvent()));\n#ifdef IPC_MESSAGE_LOG_ENABLED\n IPC::Logging::current()->SetIPCSender(this);\n#endif\n}\n\nvoid ChildThread::CleanUp() {\n#ifdef IPC_MESSAGE_LOG_ENABLED\n IPC::Logging::current()->SetIPCSender(NULL);\n#endif\n \/\/ Need to destruct the SyncChannel to the browser before we go away because\n \/\/ it caches a pointer to this thread.\n channel_.reset();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Crash on serious error in sqlite (release build)<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2013 David Edmundson <davidedmundson@kde.org>\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, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n\n#include \"kpeople-actions-plugin.h\"\n\n#include <QAction>\n\n#include <QIcon>\n#include <KLocalizedString>\n#include <KPluginFactory>\n#include <QFileDialog>\n\n#include \"KTp\/contact.h\"\n#include \"KTp\/actions.h\"\n#include \"KTp\/core.h\"\n#include \"KTp\/global-contact-manager.h\"\n\n#include <TelepathyQt\/Account>\n#include <TelepathyQt\/ContactManager>\n\n#include <KPeople\/PersonData>\n\nenum IMActionType {\n TextChannel,\n AudioChannel,\n VideoChannel,\n FileTransfer,\n LogViewer,\n CollabEditing\n};\n\nclass IMAction : public QAction {\n Q_OBJECT\npublic:\n IMAction(const QString &text, const QIcon &icon, const KTp::ContactPtr &contact,\n const Tp::AccountPtr &account, IMActionType type, QObject *parent);\n IMAction(const QString &text, const QIcon &icon, const QUrl &uri,\n IMActionType type, QObject *parent);\n KTp::ContactPtr contact() const;\n Tp::AccountPtr account() const;\n IMActionType type() const;\n QUrl uri() const;\nprivate:\n KTp::ContactPtr m_contact;\n Tp::AccountPtr m_account;\n QUrl m_uri;\n IMActionType m_type;\n};\n\nIMAction::IMAction(const QString &text, const QIcon &icon, const KTp::ContactPtr &contact,\n const Tp::AccountPtr &account, IMActionType type, QObject *parent):\n QAction(icon, text, parent),\n m_contact(contact),\n m_account(account),\n m_type(type)\n{\n}\n\nIMAction::IMAction(const QString &text, const QIcon &icon, const QUrl &uri,\n IMActionType type, QObject *parent):\n QAction(icon, text, parent),\n m_uri(uri),\n m_type(type)\n{\n}\n\nKTp::ContactPtr IMAction::contact() const\n{\n return m_contact;\n}\n\nTp::AccountPtr IMAction::account() const\n{\n return m_account;\n}\n\nIMActionType IMAction::type() const\n{\n return m_type;\n}\n\nQUrl IMAction::uri() const\n{\n return m_uri;\n}\n\nKPeopleActionsPlugin::KPeopleActionsPlugin(QObject *parent, const QVariantList &args)\n : AbstractPersonAction(parent)\n{\n Q_UNUSED(args);\n}\n\nQList<QAction*> KPeopleActionsPlugin::actionsForPerson(const KPeople::PersonData &person,\n QObject *parent) const\n{\n QList<QAction*> actions;\n\n \/\/ === TODO ===\n \/\/ This creates actions just for the \"most online contact\", what we want is to query all\n \/\/ the subcontacts for all capabilities and fill them in on the Person, so if eg. one of\n \/\/ the subcontacts can do audio calls and the other can do video calls, the Person\n \/\/ should have both actions present.\n QString accountPath = person.contactCustomProperty(QLatin1String(\"telepathy-accountPath\")).toString();\n QString contactId = person.contactCustomProperty(QLatin1String(\"telepathy-contactId\")).toString();\n\n const Tp::AccountPtr account = KTp::contactManager()->accountForAccountPath(accountPath);\n if (!account) {\n return actions;\n }\n\n const KTp::ContactPtr contact = KTp::contactManager()->contactForContactId(accountPath, contactId);\n if (!contact || !contact->manager()) {\n return actions;\n }\n\n if (contact->textChatCapability()) {\n QAction *action = new IMAction(i18n(\"Start Chat Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"text-x-generic\")),\n contact,\n account,\n TextChannel,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n if (contact->audioCallCapability()) {\n QAction *action = new IMAction(i18n(\"Start Audio Call Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"audio-headset\")),\n contact,\n account,\n AudioChannel,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n if (contact->videoCallCapability()) {\n QAction *action = new IMAction(i18n(\"Start Video Call Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"camera-web\")),\n contact,\n account,\n VideoChannel,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n\n if (contact->fileTransferCapability()) {\n QAction *action = new IMAction(i18n(\"Send Files Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"mail-attachment\")),\n contact,\n account,\n FileTransfer,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n if (contact->collaborativeEditingCapability()) {\n QAction *action = new IMAction(i18n(\"Collaboratively edit a document Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"document-edit\")),\n contact,\n account,\n CollabEditing,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n\n \/\/FIXME-KPEOPLE\n\/\/ QAction *action = new IMAction(i18n(\"Open Log Viewer...\"),\n\/\/ QIcon::fromTheme(QStringLiteral(\"documentation\")),\n\/\/ personData->uri(),\n\/\/ LogViewer,\n\/\/ parent);\n\/\/ connect(action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n\/\/ actions << action;\n return actions;\n}\n\nvoid KPeopleActionsPlugin::onActionTriggered()\n{\n IMAction *action = qobject_cast<IMAction*>(sender());\n KTp::ContactPtr contact = action->contact();\n Tp::AccountPtr account = action->account();\n IMActionType type = action->type();\n\n switch (type) {\n case TextChannel:\n KTp::Actions::startChat(account, contact);\n break;\n case AudioChannel:\n KTp::Actions::startAudioCall(account, contact);\n break;\n case VideoChannel:\n KTp::Actions::startAudioVideoCall(account, contact);\n break;\n case FileTransfer: {\n const QStringList fileNames = QFileDialog::getOpenFileNames(Q_NULLPTR, i18n(\"Choose files to send to %1\", contact->alias()),\n QStringLiteral(\"kfiledialog:\/\/\/FileTransferLastDirectory\"));\n Q_FOREACH(const QString& file, fileNames) {\n KTp::Actions::startFileTransfer(account, contact, file);\n }\n break;\n }\n case LogViewer:\n KTp::Actions::openLogViewer(action->uri());\n break;\n case CollabEditing: {\n const QUrl file = QFileDialog::getOpenFileName(Q_NULLPTR, i18n(\"Choose a file to edit with %1\", contact->alias()),\n QStringLiteral(\"kfiledialog:\/\/\/CollabEditingLastDirectory\"));\n KTp::Actions::startCollaborativeEditing(account, contact, QList<QUrl>() << file, true);\n break;\n }\n }\n}\n\nK_PLUGIN_FACTORY( KPeopleActionsPluginFactory, registerPlugin<KPeopleActionsPlugin>(); )\nK_EXPORT_PLUGIN( KPeopleActionsPluginFactory(\"ktp_kpeople_plugin\", \"ktp-common-internals\") )\n\n#include \"kpeople-actions-plugin.moc\"\n<commit_msg>Make actions plugin return actions also for all subcontacts<commit_after>\/*\n Copyright (C) 2013 David Edmundson <davidedmundson@kde.org>\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, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n\n#include \"kpeople-actions-plugin.h\"\n\n#include <QAction>\n\n#include <QIcon>\n#include <KLocalizedString>\n#include <KPluginFactory>\n#include <QFileDialog>\n\n#include \"KTp\/contact.h\"\n#include \"KTp\/actions.h\"\n#include \"KTp\/core.h\"\n#include \"KTp\/global-contact-manager.h\"\n\n#include <TelepathyQt\/Account>\n#include <TelepathyQt\/ContactManager>\n#include <TelepathyQt\/Constants>\n\n#include <KPeople\/PersonData>\n\nenum IMActionType {\n TextChannel,\n AudioChannel,\n VideoChannel,\n FileTransfer,\n LogViewer,\n CollabEditing\n};\n\nclass IMAction : public QAction {\n Q_OBJECT\npublic:\n IMAction(const QString &text, const QIcon &icon, const KTp::ContactPtr &contact,\n const Tp::AccountPtr &account, IMActionType type, QObject *parent);\n IMAction(const QString &text, const QIcon &icon, const QUrl &uri,\n IMActionType type, QObject *parent);\n KTp::ContactPtr contact() const;\n Tp::AccountPtr account() const;\n IMActionType type() const;\n QUrl uri() const;\nprivate:\n KTp::ContactPtr m_contact;\n Tp::AccountPtr m_account;\n QUrl m_uri;\n IMActionType m_type;\n};\n\nIMAction::IMAction(const QString &text, const QIcon &icon, const KTp::ContactPtr &contact,\n const Tp::AccountPtr &account, IMActionType type, QObject *parent):\n QAction(icon, text, parent),\n m_contact(contact),\n m_account(account),\n m_type(type)\n{\n}\n\nIMAction::IMAction(const QString &text, const QIcon &icon, const QUrl &uri,\n IMActionType type, QObject *parent):\n QAction(icon, text, parent),\n m_uri(uri),\n m_type(type)\n{\n}\n\nKTp::ContactPtr IMAction::contact() const\n{\n return m_contact;\n}\n\nTp::AccountPtr IMAction::account() const\n{\n return m_account;\n}\n\nIMActionType IMAction::type() const\n{\n return m_type;\n}\n\nQUrl IMAction::uri() const\n{\n return m_uri;\n}\n\nKPeopleActionsPlugin::KPeopleActionsPlugin(QObject *parent, const QVariantList &args)\n : AbstractPersonAction(parent)\n{\n Q_UNUSED(args);\n}\n\nQList<QAction*> KPeopleActionsPlugin::actionsForPerson(const KPeople::PersonData &person,\n QObject *parent) const\n{\n QList<QAction*> actions;\n\n \/\/ Get the most online account path and contact id\n QString personAccountPath = person.contactCustomProperty(QLatin1String(\"telepathy-accountPath\")).toString();\n\n \/\/ The property for \"telepathy-accountPath\" is in form \"\/org\/freedesktop\/Telepathy\/Account\/gabble\/jabber\/myjabberaccount\"\n \/\/ which is needed for retrieving the account from Tp::AccountManager. However we can only retrieve the other\n \/\/ contact uri list, not any objects which would give us the \"telepathy-accountPath\" for the subcontact.\n \/\/ So the code below constructs the account path from the contact uri which is known to be for ktp contacts\n \/\/ in form of \"ktp:\/\/ + short account path + ? + contact id\". But in order to not have the same actions\n \/\/ twice in the menu (one for most online and one from the contactUris()), this turns these properties into regular\n \/\/ uri format and puts it into the first position in the list, making sure that they will appear at the beggining.\n \/\/ It's also easier to simply remove it here and not having to check each uri separately in the foreach below.\n \/\/ And it cannot take the person.personUri() because for metacontacts that is in form of \"kpeople:\/\/num_id\".\n personAccountPath = personAccountPath.right(personAccountPath.length() - TP_QT_ACCOUNT_OBJECT_PATH_BASE.size() - 1);\n QString personContactId = person.contactCustomProperty(QLatin1String(\"telepathy-contactId\")).toString();\n QString mostOnlineUri = QStringLiteral(\"ktp:\/\/\") + personAccountPath + QLatin1Char('?') + personContactId;\n\n QStringList uris{mostOnlineUri};\n QStringList contactUris = person.contactUris();\n\n \/\/ Only append the child contacts if there is more than 1, otherwise\n \/\/ it means this contact has only itself as a subcontact.\n if (contactUris.size() > 1) {\n uris.append(contactUris);\n \/\/ Make sure we don't have duplicate uris in the list\n uris.removeDuplicates();\n }\n\n Q_FOREACH (const QString &uri, uris) {\n if (!uri.startsWith(QStringLiteral(\"ktp:\/\/\"))) {\n continue;\n }\n\n int delimiterIndex = uri.indexOf(QLatin1Char('?'));\n QString contactId = uri.right(uri.length() - delimiterIndex - 1);\n QString accountPath = uri.mid(6, delimiterIndex - 6);\n \/\/ Prepend the \"\/org\/freedesktop\/Telepathy\" part so that Tp::AccountManager\n \/\/ returns valid account\n accountPath.prepend(TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('\/'));\n\n\n const Tp::AccountPtr account = KTp::contactManager()->accountForAccountPath(accountPath);\n if (!account) {\n continue;\n }\n\n const KTp::ContactPtr contact = KTp::contactManager()->contactForContactId(accountPath, contactId);\n if (!contact || !contact->manager()) {\n continue;\n }\n\n if (contact->textChatCapability()) {\n QAction *action = new IMAction(i18n(\"Start Chat Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"text-x-generic\")),\n contact,\n account,\n TextChannel,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n if (contact->audioCallCapability()) {\n QAction *action = new IMAction(i18n(\"Start Audio Call Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"audio-headset\")),\n contact,\n account,\n AudioChannel,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n if (contact->videoCallCapability()) {\n QAction *action = new IMAction(i18n(\"Start Video Call Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"camera-web\")),\n contact,\n account,\n VideoChannel,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n\n if (contact->fileTransferCapability()) {\n QAction *action = new IMAction(i18n(\"Send Files Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"mail-attachment\")),\n contact,\n account,\n FileTransfer,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n if (contact->collaborativeEditingCapability()) {\n QAction *action = new IMAction(i18n(\"Collaboratively edit a document Using %1...\", account->displayName()),\n QIcon::fromTheme(QStringLiteral(\"document-edit\")),\n contact,\n account,\n CollabEditing,\n parent);\n connect (action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n }\n }\n\n QAction *action = new IMAction(i18n(\"Previous Conversations...\"),\n QIcon::fromTheme(QStringLiteral(\"documentation\")),\n person.personUri(),\n LogViewer,\n parent);\n connect(action, SIGNAL(triggered(bool)), SLOT(onActionTriggered()));\n actions << action;\n\n return actions;\n}\n\nvoid KPeopleActionsPlugin::onActionTriggered()\n{\n IMAction *action = qobject_cast<IMAction*>(sender());\n KTp::ContactPtr contact = action->contact();\n Tp::AccountPtr account = action->account();\n IMActionType type = action->type();\n\n switch (type) {\n case TextChannel:\n KTp::Actions::startChat(account, contact);\n break;\n case AudioChannel:\n KTp::Actions::startAudioCall(account, contact);\n break;\n case VideoChannel:\n KTp::Actions::startAudioVideoCall(account, contact);\n break;\n case FileTransfer: {\n const QStringList fileNames = QFileDialog::getOpenFileNames(Q_NULLPTR, i18n(\"Choose files to send to %1\", contact->alias()),\n QStringLiteral(\"kfiledialog:\/\/\/FileTransferLastDirectory\"));\n Q_FOREACH(const QString& file, fileNames) {\n KTp::Actions::startFileTransfer(account, contact, file);\n }\n break;\n }\n case LogViewer:\n KTp::Actions::openLogViewer(action->uri());\n break;\n case CollabEditing: {\n const QUrl file = QFileDialog::getOpenFileName(Q_NULLPTR, i18n(\"Choose a file to edit with %1\", contact->alias()),\n QStringLiteral(\"kfiledialog:\/\/\/CollabEditingLastDirectory\"));\n KTp::Actions::startCollaborativeEditing(account, contact, QList<QUrl>() << file, true);\n break;\n }\n }\n}\n\nK_PLUGIN_FACTORY( KPeopleActionsPluginFactory, registerPlugin<KPeopleActionsPlugin>(); )\nK_EXPORT_PLUGIN( KPeopleActionsPluginFactory(\"ktp_kpeople_plugin\", \"ktp-common-internals\") )\n\n#include \"kpeople-actions-plugin.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- c++ -*- \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This file is part of Miro (The Middleware for Robots)\n\/\/ Copyright (C) 1999-2013\n\/\/ Department of Neural Information Processing, University of Ulm\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2, or (at your option)\n\/\/ 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. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/\n\n#define QT_ALTERNATE_QTSMANIP\n\n#include \"ConfigDocumentXML.h\"\n#include \"Section.h\"\n\n#include \"miroWidgets\/ConfigFile.h\"\n\n#include \"params\/Generator.h\"\n\n#include <QTreeWidget>\n#include <QTreeWidgetItem>\n#include <QMenu>\n#include <qstring.h>\n\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n\n\nconst QString ConfigDocumentXML::XML_DOCTYPE(\"MiroConfigDocument\");\nconst QString ConfigDocumentXML::XML_TAG(\"config\");\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ public methods\n\nConfigDocumentXML::ConfigDocumentXML(QDomDocument const& _document,\n\t\t\t\t QTreeWidget * _treeWidget,\n\t\t\t\t QObject * _parent, const char * _name) :\n Super(_document, _treeWidget, _parent, _name),\n menuAddSection_(NULL)\n{\n}\n\nConfigDocumentXML::~ConfigDocumentXML()\n{}\n\n\/\/---------------------------------------------------------------------------- \n\/\/ inherited public methods\n\nvoid\nConfigDocumentXML::contextMenu(QMenu& _menu)\n{\n \/\/ The context menu has one QAction, \"Add Section\"\n \/\/ The \"Add Section\" menu is a submenu of the menu passed as argument.\n \/\/ Its signal is invoked when it is activated, not triggered.\n menuAddSection_ = _menu.addMenu(tr(\"Add Section\"));\n\n Miro::CFG::QStringVector childSections;\n QTreeWidgetItem * const pTreeWidgetItem = treeWidgetItem();\n assert(pTreeWidgetItem != NULL);\n QTreeWidgetItem * const pParentTreeWidgetItem = pTreeWidgetItem->parent();\n if (pParentTreeWidgetItem != NULL)\n {\n \/\/ It is not the root, so it may have siblings\n for (int i = 0; i < pParentTreeWidgetItem->childCount(); ++i)\n {\n const QTreeWidgetItem * const pChildTreeWidgetItem =\n\tpParentTreeWidgetItem->child(i);\n assert(pChildTreeWidgetItem != NULL);\n const QString text = pChildTreeWidgetItem->text(0);\n childSections.push_back(text);\n }\n }\n\n \/\/ submenu: add all section names\n \/\/ not yet available in the document\n Miro::CFG::QStringVector sections =\n ConfigFile::instance()->description().groups();\n Miro::CFG::QStringVector::const_iterator first, last = sections.end();\n for (first = sections.begin(); first != last; ++first) {\n\n \/\/ if this section already exists, don't add it\n Miro::CFG::QStringVector::const_iterator i = \n std::find(childSections.begin(), childSections.end(), *first);\n if (i != childSections.end())\n continue;\n\n \/\/ count the final parameter classes in the section\n int itemCount = 0;\n Miro::CFG::GroupMap::const_iterator f, l;\n ConfigFile::instance()->description().getGroupedTypes(*first, f, l);\n for (; f != l; ++f) {\n if (f->second.isFinal()) {\n\t++itemCount;\n }\n }\n\n \/\/ if this section is empty, don't add it\n if (itemCount == 0)\n continue;\n\n \/\/ The name of the Action\n const QString name = *first;\n \/\/ From \"http:\/\/qt-project.org\/doc\/qt4-8\/qaction.html\":\n \/\/ \"We recommend that actions are created as children of the window they\n \/\/ are used in. In most cases, actions will be children of the application's\n \/\/ main window.\"\n \/\/ This class doesn't have a handle to any window.\n QWidget * const pActionParent = NULL;\n QAction * const pAction = new QAction(name, pActionParent);\n connect(pAction, SIGNAL(activated(int)), this, SLOT(onAddSection(int)));\n \/\/ Add the Action to the Menu\n menuAddSection_->addAction(pAction);\n }\n}\n\n\/\/---------------------------------------------------------------------------- \n\/\/ public slots\n\nvoid \nConfigDocumentXML::onAddSection(int _n)\n{\n QDomElement config = document_.documentElement();\n QDomElement e = document_.createElement(Section::XML_TAG);\n e.setAttribute(Section::XML_ATTRIBUTE_KEY, menuAddSection_->text(_n));\n\n QDomNode n = config.firstChild();\n QDomNode newChild; \n\n if (config.firstChild().isNull())\n newChild = config.appendChild(e);\n else\n newChild = config.insertBefore(e, n);\n\n assert(!newChild.isNull());\n new Section(newChild, \n\t treeWidgetItem(), NULL, \n\t this, menuAddSection_->text(_n));\n setModified();\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ protected methods\n\nvoid\nConfigDocumentXML::parse()\n{\n QDomNode n = document_.firstChild();\n if (!n.isNull()) {\n QDomNode n1 = n.firstChild();\n QTreeWidgetItem * pre = NULL;\n while (!n1.isNull()) {\n QDomElement e = n1.toElement();\n if (!e.isNull() &&\n\t e.tagName() == Section::XML_TAG) {\n\tSection * section =\n\t new Section(e, \n\t\t treeWidgetItem(), pre,\n\t\t this, e.attribute(\"name\"));\n\tpre = section->treeWidgetItem();\n }\n n1 = n1.nextSibling();\n }\n }\n}\n<commit_msg>Context menu wasn't filtering the sections<commit_after>\/\/ -*- c++ -*- \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This file is part of Miro (The Middleware for Robots)\n\/\/ Copyright (C) 1999-2013\n\/\/ Department of Neural Information Processing, University of Ulm\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2, or (at your option)\n\/\/ 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. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/\n\n#define QT_ALTERNATE_QTSMANIP\n\n#include \"ConfigDocumentXML.h\"\n#include \"Section.h\"\n\n#include \"miroWidgets\/ConfigFile.h\"\n\n#include \"params\/Generator.h\"\n\n#include <QTreeWidget>\n#include <QTreeWidgetItem>\n#include <QMenu>\n#include <qstring.h>\n\n#include <algorithm>\n#include <cassert>\n\nconst QString ConfigDocumentXML::XML_DOCTYPE(\"MiroConfigDocument\");\nconst QString ConfigDocumentXML::XML_TAG(\"config\");\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ public methods\n\nConfigDocumentXML::ConfigDocumentXML(QDomDocument const& _document,\n\t\t\t\t QTreeWidget * _treeWidget,\n\t\t\t\t QObject * _parent, const char * _name) :\n Super(_document, _treeWidget, _parent, _name),\n menuAddSection_(NULL)\n{\n}\n\nConfigDocumentXML::~ConfigDocumentXML()\n{}\n\n\/\/---------------------------------------------------------------------------- \n\/\/ inherited public methods\n\nvoid\nConfigDocumentXML::contextMenu(QMenu& _menu)\n{\n \/\/ The context menu has one QAction, \"Add Section\"\n \/\/ The \"Add Section\" menu is a submenu of the menu passed as argument.\n \/\/ Its signal is invoked when it is activated, not triggered.\n menuAddSection_ = _menu.addMenu(tr(\"Add Section\"));\n\n \/\/ Construct a list of all siblings of the QTreeWidgetItem\n Miro::CFG::QStringVector childSections;\n \/\/ Fetch the QTreeWidgetItem\n QTreeWidgetItem * const pTreeWidgetItem = treeWidgetItem();\n assert(pTreeWidgetItem != NULL);\n \/\/ For each child of the QTreeWidgetItem\n for (int i = 0; i < pTreeWidgetItem->childCount(); ++i)\n {\n \/\/ Fetch the ith sibling\n const QTreeWidgetItem * const pChildTreeWidgetItem =\n\tpTreeWidgetItem->child(i);\n assert(pChildTreeWidgetItem != NULL);\n \/\/ Fetch the sibling's label text\n const QString text = pChildTreeWidgetItem->text(0);\n \/\/ Append the label text to the QStringVector\n childSections.push_back(text);\n }\n \/\/ The QStringVector should have as many elements as the parent has children\n assert(static_cast<size_t>(pTreeWidgetItem->childCount()) == \n\t static_cast<size_t>(childSections.size()));\n\n\n \/\/ submenu: add all section names not yet available in the document\n Miro::CFG::QStringVector sections =\n ConfigFile::instance()->description().groups();\n\n Miro::CFG::QStringVector::const_iterator first, last = sections.end();\n for (first = sections.begin(); first != last; ++first) {\n\n \/\/ if this section already exists, don't add it\n Miro::CFG::QStringVector::const_iterator i = \n std::find(childSections.begin(), childSections.end(), *first);\n if (i != childSections.end())\n continue;\n\n \/\/ count the final parameter classes in the section\n int itemCount = 0;\n Miro::CFG::GroupMap::const_iterator f, l;\n ConfigFile::instance()->description().getGroupedTypes(*first, f, l);\n for (; f != l; ++f) {\n if (f->second.isFinal()) {\n\t++itemCount;\n }\n }\n\n \/\/ if this section is empty, don't add it\n if (itemCount == 0)\n continue;\n\n \/\/ The name of the Action\n const QString name = *first;\n \/\/ From \"http:\/\/qt-project.org\/doc\/qt4-8\/qaction.html\":\n \/\/ \"We recommend that actions are created as children of the window they\n \/\/ are used in. In most cases, actions will be children of the application's\n \/\/ main window.\"\n \/\/ This class doesn't have a handle to any window.\n QWidget * const pActionParent = NULL;\n QAction * const pAction = new QAction(name, pActionParent);\n connect(pAction, SIGNAL(activated(int)), this, SLOT(onAddSection(int)));\n \/\/ Add the Action to the Menu\n menuAddSection_->addAction(pAction);\n }\n}\n\n\/\/---------------------------------------------------------------------------- \n\/\/ public slots\n\nvoid \nConfigDocumentXML::onAddSection(int _n)\n{\n QDomElement config = document_.documentElement();\n QDomElement e = document_.createElement(Section::XML_TAG);\n e.setAttribute(Section::XML_ATTRIBUTE_KEY, menuAddSection_->text(_n));\n\n QDomNode n = config.firstChild();\n QDomNode newChild; \n\n if (config.firstChild().isNull())\n newChild = config.appendChild(e);\n else\n newChild = config.insertBefore(e, n);\n\n assert(!newChild.isNull());\n new Section(newChild, \n\t treeWidgetItem(), NULL, \n\t this, menuAddSection_->text(_n));\n setModified();\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ protected methods\n\nvoid\nConfigDocumentXML::parse()\n{\n QDomNode n = document_.firstChild();\n if (!n.isNull()) {\n QDomNode n1 = n.firstChild();\n QTreeWidgetItem * pre = NULL;\n while (!n1.isNull()) {\n QDomElement e = n1.toElement();\n if (!e.isNull() &&\n\t e.tagName() == Section::XML_TAG) {\n\tSection * section =\n\t new Section(e, \n\t\t treeWidgetItem(), pre,\n\t\t this, e.attribute(\"name\"));\n\tpre = section->treeWidgetItem();\n }\n n1 = n1.nextSibling();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ C++ General Utility Library (mailto:cgul@zethes.com)\n\/\/ Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall\n\/\/ All rights reserved.\n\n\/** @file ImageHandler.cpp\n *\/\n\n#include \"ImageHandler.hpp\"\n#include \"..\/Exceptions\/ImageException.hpp\"\n\n#ifdef PNG_FOUND\n# include \"PNG.hpp\"\n#endif\n\n#ifdef JPEG_FOUND\n# include \"JPEG.hpp\"\n#endif\n#include \"BMP.hpp\"\n\n_CGUL_EXPORT CGUL::ImageHandler::ImageHandler()\n{\n \/\/ Add default image loaders\n# ifdef PNG_FOUND\n Register(new ImageLoaders::PNG());\n# endif\n# ifdef JPEG_FOUND\n Register(new ImageLoaders::JPEG());\n# endif\n Register(new ImageLoaders::BMP());\n}\n\n_CGUL_EXPORT CGUL::ImageHandler::~ImageHandler()\n{\n for (Vector< ImageLoader* >::iterator itr = loaders.begin(), itrEnd = loaders.end(); itr != itrEnd; ++itr)\n {\n delete *itr;\n }\n}\n\n_CGUL_EXPORT CGUL::ImageHandler* CGUL::ImageHandler::GetInstance()\n{\n static CGUL::ImageHandler instance;\n return &instance;\n}\n\n_CGUL_EXPORT void CGUL::ImageHandler::Register(ImageLoader* loader)\n{\n loaders.push_back(loader);\n}\n\n_CGUL_EXPORT CGUL::ImageLoader* CGUL::ImageHandler::GetLoaderByName(const String& name)\n{\n for (UInt32 i = 0; i < loaders.size(); i++)\n {\n if (loaders[i]->GetName() == name)\n {\n return loaders[i];\n }\n }\n return NULL;\n}\n\n_CGUL_EXPORT CGUL::ImageLoader* CGUL::ImageHandler::GetLoaderByExtension(const String& ext)\n{\n for (UInt32 i = 0; i < loaders.size(); i++)\n {\n if (loaders[i]->GetExtension().GetLower() == ext.GetLower())\n {\n return loaders[i];\n }\n }\n return NULL;\n}\n\n_CGUL_EXPORT CGUL::ImageLoader* CGUL::ImageHandler::GetLoaderByFile(const String& file)\n{\n for (UInt32 i = 0; i < loaders.size(); i++)\n {\n if (loaders[i]->CanLoad(file))\n {\n return loaders[i];\n }\n }\n return NULL;\n}\n\n_CGUL_EXPORT void CGUL::ImageHandler::GetAllLoaders(FixedList< ImageLoader* >* loaders)\n{\n loaders->SetSize(this->loaders.size());\n Size count = 0;\n for (Vector< ImageLoader* >::iterator itr = this->loaders.begin(), itrEnd = this->loaders.end(); itr != itrEnd; ++itr)\n {\n loaders->Set(count++, *itr);\n }\n}\n<commit_msg>Commented out bitmap references. It's not added yet.<commit_after>\/\/ C++ General Utility Library (mailto:cgul@zethes.com)\n\/\/ Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall\n\/\/ All rights reserved.\n\n\/** @file ImageHandler.cpp\n *\/\n\n#include \"ImageHandler.hpp\"\n#include \"..\/Exceptions\/ImageException.hpp\"\n\n#ifdef PNG_FOUND\n# include \"PNG.hpp\"\n#endif\n\n#ifdef JPEG_FOUND\n# include \"JPEG.hpp\"\n#endif\n\/\/#include \"BMP.hpp\"\n\n_CGUL_EXPORT CGUL::ImageHandler::ImageHandler()\n{\n \/\/ Add default image loaders\n# ifdef PNG_FOUND\n Register(new ImageLoaders::PNG());\n# endif\n# ifdef JPEG_FOUND\n Register(new ImageLoaders::JPEG());\n# endif\n \/\/Register(new ImageLoaders::BMP());\n}\n\n_CGUL_EXPORT CGUL::ImageHandler::~ImageHandler()\n{\n for (Vector< ImageLoader* >::iterator itr = loaders.begin(), itrEnd = loaders.end(); itr != itrEnd; ++itr)\n {\n delete *itr;\n }\n}\n\n_CGUL_EXPORT CGUL::ImageHandler* CGUL::ImageHandler::GetInstance()\n{\n static CGUL::ImageHandler instance;\n return &instance;\n}\n\n_CGUL_EXPORT void CGUL::ImageHandler::Register(ImageLoader* loader)\n{\n loaders.push_back(loader);\n}\n\n_CGUL_EXPORT CGUL::ImageLoader* CGUL::ImageHandler::GetLoaderByName(const String& name)\n{\n for (UInt32 i = 0; i < loaders.size(); i++)\n {\n if (loaders[i]->GetName() == name)\n {\n return loaders[i];\n }\n }\n return NULL;\n}\n\n_CGUL_EXPORT CGUL::ImageLoader* CGUL::ImageHandler::GetLoaderByExtension(const String& ext)\n{\n for (UInt32 i = 0; i < loaders.size(); i++)\n {\n if (loaders[i]->GetExtension().GetLower() == ext.GetLower())\n {\n return loaders[i];\n }\n }\n return NULL;\n}\n\n_CGUL_EXPORT CGUL::ImageLoader* CGUL::ImageHandler::GetLoaderByFile(const String& file)\n{\n for (UInt32 i = 0; i < loaders.size(); i++)\n {\n if (loaders[i]->CanLoad(file))\n {\n return loaders[i];\n }\n }\n return NULL;\n}\n\n_CGUL_EXPORT void CGUL::ImageHandler::GetAllLoaders(FixedList< ImageLoader* >* loaders)\n{\n loaders->SetSize(this->loaders.size());\n Size count = 0;\n for (Vector< ImageLoader* >::iterator itr = this->loaders.begin(), itrEnd = this->loaders.end(); itr != itrEnd; ++itr)\n {\n loaders->Set(count++, *itr);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef EXECUTORS_H\n#define EXECUTORS_H\n\n#include \"processes.hpp\"\n#include \"objects.hpp\"\n#include \"reader.hpp\" \/\/ for Bytecode classes\n#include \"types.hpp\"\n\n#include <map>\n\n#include <boost\/smart_ptr.hpp>\n\n\/*\n hl functions are represented by a Closure structure, which has an\n attached bytecode_t array.\n\n Calling convention:\n\n proc.stack[0] *must* be a Closure\n !! for now, at least. in the future we will change this so that\n !! calls to non-Closure objects will be transformed to calls to\n !! the global <axiom>call*, which *should* be a Closure\n !! -- almkglor\n\n proc.stack[0] contains the closure. If it is a \"normal\" \n function, proc.stack[1] is the \"continuation\" function \n and proc.stack[2..n] are the parameters. \n proc.stack.size() is the number of parameters including \n the function itself and the continuation.\n \n If it is a \"continuation\" function, proc.stack[1] is always \n the return value. proc.stack.size() will be 2.\n\n Functions never return.\n*\/\n\n#define PASTE_SYMBOLS(x,y) x##y\n\n\/*\n Not necessary when using GCC.\n NOTE! We retain this and even add references to\n an _e_bytecode_label type so that modders who\n happen to use *only* GCC will remember to update\n the declarations for the benefit of non-GCC\n users.\n*\/\n\n#define DECLARE_BYTECODES enum _e_bytecode_label {\n#define BYTECODE_ENUM(x) PASTE_SYMBOLS(_bytecode_, x)\n#define A_BYTECODE(x) BYTECODE_ENUM(x),\n#define END_DECLARE_BYTECODES __null_bytecode };\nDECLARE_BYTECODES\n\tA_BYTECODE(apply)\n\tA_BYTECODE(apply_invert_k)\n\tA_BYTECODE(apply_list)\n\tA_BYTECODE(apply_k_release)\n A_BYTECODE(build_closure)\n\tA_BYTECODE(build_k_closure)\n\tA_BYTECODE(build_k_closure_recreate)\n\tA_BYTECODE(build_k_closure_reuse)\n\tA_BYTECODE(car)\n\tA_BYTECODE(car_local_push)\n\tA_BYTECODE(car_clos_push)\n\tA_BYTECODE(ccc)\n\tA_BYTECODE(cdr)\n\tA_BYTECODE(cdr_local_push)\n\tA_BYTECODE(cdr_clos_push)\n\tA_BYTECODE(check_vars)\n\tA_BYTECODE(closure_ref)\n\tA_BYTECODE(composeo)\n\tA_BYTECODE(composeo_continuation)\n\tA_BYTECODE(cons)\n A_BYTECODE(const_ref)\n\tA_BYTECODE(b_continue)\n\tA_BYTECODE(continue_local)\n\tA_BYTECODE(continue_on_clos)\n\tA_BYTECODE(global)\n\tA_BYTECODE(global_set)\n\tA_BYTECODE(halt)\n\tA_BYTECODE(halt_local_push)\n\tA_BYTECODE(halt_clos_push)\n\tA_BYTECODE(jmp_nil)\n \/\/A_BYTECODE(if_local)\n\tA_BYTECODE(b_int)\n\tA_BYTECODE(b_float)\n\tA_BYTECODE(lit_nil)\n\tA_BYTECODE(lit_t)\n\tA_BYTECODE(local)\n\tA_BYTECODE(monomethod)\n\tA_BYTECODE(reducto)\n A_BYTECODE(reducto_continuation)\n\tA_BYTECODE(rep)\n\tA_BYTECODE(rep_local_push)\n\tA_BYTECODE(rep_clos_push)\n\tA_BYTECODE(scar)\n\tA_BYTECODE(scdr)\n\tA_BYTECODE(sv)\n\tA_BYTECODE(sv_local_push)\n\tA_BYTECODE(sv_clos_push)\n\tA_BYTECODE(sv_ref)\n\tA_BYTECODE(sv_ref_local_push)\n\tA_BYTECODE(sv_ref_clos_push)\n\tA_BYTECODE(sv_set)\n\tA_BYTECODE(sym)\n\tA_BYTECODE(symeval)\n\tA_BYTECODE(table_create)\n\tA_BYTECODE(table_ref)\n\tA_BYTECODE(table_sref)\n\tA_BYTECODE(table_map)\n\tA_BYTECODE(tag)\n\tA_BYTECODE(type)\n\tA_BYTECODE(type_local_push)\n\tA_BYTECODE(type_clos_push)\n\tA_BYTECODE(variadic)\n\t\/*maybe organize by alphabetical order of bytecodes ^^*\/\n\tA_BYTECODE(do_executor)\n\tA_BYTECODE(plus)\n\tA_BYTECODE(minus)\n\tA_BYTECODE(mul)\n\tA_BYTECODE(div)\n\tA_BYTECODE(mod)\nEND_DECLARE_BYTECODES\n\n#ifdef __GNUC__\n\n\/\/ use indirect goto when using GCC\n\ntypedef void* _bytecode_label;\n#define DISPATCH_BYTECODES \\\n bytecode_t *pc = expect_type<Bytecode>(clos->code())->getCode();\\\n\tgoto *(pc->op);\n#define NEXT_BYTECODE goto *((++pc)->op)\n#define BYTECODE(x) BYTECODE_ENUM(x); PASTE_SYMBOLS(label_b_, x)\n#define THE_BYTECODE_LABEL(x) &&PASTE_SYMBOLS(label_b_, x)\n\n#else \/\/ __GNUC__\n\n\/\/ use an enum when using standard C\n\ntypedef enum _e_bytecode_label _bytecode_label;\n#define DISPATCH_BYTECODES \\\n\tbytecode_t *pc = expect_type<Bytecode>(clos->code())->getCode();\\\n\tswitch(pc->op)\n#define NEXT_BYTECODE {pc++; continue;}\n#define BYTECODE(x) case BYTECODE_ENUM(x)\n#define THE_BYTECODE_LABEL(x) BYTECODE_ENUM(x)\n\n#endif \/\/ __GNUC__\n\nclass Process;\nclass ProcessStack;\n\nclass Executor;\n\nclass ExecutorTable : public std::map<Symbol*, Executor*> {\npublic:\n\t~ExecutorTable();\n};\n\n\/* \n * Generic executor\n * An executor represents a built-in function\n *\/\nclass Executor {\nprivate:\n \/\/ table of available executors\n static ExecutorTable tbl;\npublic:\n \/\/ register an executor in the system\n \/\/ no locks: executors should be registered only during startup\n static void reg(Symbol *s, Executor *e) {\n tbl[s] = e;\n }\n \/\/ no locks: tbl stucture is immutable after initialization\n static Executor* findExecutor(Symbol *s) {\n std::map<Symbol*,Executor*>::iterator it = tbl.find(s);\n if (it==tbl.end())\n return NULL;\n else\n return it->second;\n }\n virtual ~Executor() {}\n \/\/ return true if a function call must be performed, false otherwise\n virtual bool run(Process & proc, size_t & reductions) = 0;\n};\n\ninline ExecutorTable::~ExecutorTable() {\n\tfor(iterator i = begin(); i != end(); ++i) {\n\t\tdelete i->second;\n\t}\n}\n\n\/*\n * The bytecode read by the reader should be assembled before execution\n * an assembled bytecode is an array of bytecode_t\n * The executor can assume that the bytecodes are correct\n * The assembler must have already catched eventual errors\n *\/\nstruct bytecode_t {\n _bytecode_label op; \/\/ operation code\n intptr_t val; \/\/ simple value argument (may be invalid)\n};\n\n\/\/ a bytecode object contains a table of complex constants such as gensyms\nclass Bytecode : public GenericDerivedVariadic<Bytecode> {\nprivate:\n \/\/ TODO: rearrange to let code be shared between different processes\n \/\/ ?? what exactly does the above comment mean? -- almkglor\n boost::shared_array<bytecode_t> code;\n size_t codeSize;\n size_t nextCode; \/\/ next free position in code\n size_t nextPos; \/\/ next free position in variadic space\n\npublic:\n Bytecode(size_t sz) \n : GenericDerivedVariadic<Bytecode>(sz), codeSize(0), nextCode(0), \n nextPos(0) {}\n virtual ~Bytecode() {}\n\n Object::ref& operator[](size_t i) {\n if (i < size())\n return index(i);\n else\n throw_HlError(\"internal: trying to access objects in bytecode with an index too large!\");\n }\n\n Object::ref type(void) const {\n return Object::to_ref(symbol_bytecode);\n }\n\n bytecode_t* getCode() { return code.get(); }\n\n \/\/ close a complex constants\n size_t closeOver(Object::ref obj) {\n if (nextPos >= size())\n throw_HlError(\"internal: trying to close over, but there is no space left in Bytecode\");\n index(nextPos) = obj;\n return nextPos++;\n }\n\n \/\/ add a bytecode at the end of the sequence\n void push(bytecode_t b);\n void push(_bytecode_label op, intptr_t val);\n void push(Symbol *s, intptr_t val);\n void push(const char *s, intptr_t val);\n\n void traverse_references(GenericTraverser *gt) {\n for(size_t i = 0; i < nextPos; ++i) {\n gt->traverse(index(i));\n }\n }\n};\n\n#define INTPARAM(name) intptr_t name = pc->val\n#define SYMPARAM(name) Symbol *name = (Symbol*)pc->val\n#define FLOATPARAM(name) Float *name = (Float*)pc->val\n\nclass AsOp {\npublic:\n \/\/ expect arguments on the stack:\n \/\/ - sequence arg (stack top)\n \/\/ - simple arg\n \/\/ - Bytecode object being assembled\n \/\/ - seq being assembled\n virtual void assemble(Process & proc) = 0;\n};\n\nclass Assembler {\nprivate:\n typedef std::map<Symbol*, AsOp*> sym_op_tbl;\n sym_op_tbl tbl;\n\n \/\/ extracts a value pointer\/immediate object, throwing away the type tag\n static intptr_t simpleVal(Object::ref sa);\npublic:\n ~Assembler() { \n for (sym_op_tbl::iterator i = tbl.begin(); i!=tbl.end(); i++)\n delete i->second;\n }\n\n \/\/ register a new assembler operation\n template <class T>\n void reg(Symbol* s) { tbl[s] = new T(); }\n\n \/\/ do the assembly, leave a Bytecode on the stack, expect a sequence on \n \/\/ the stack\n void go(Process & proc); \n\n \/\/ count number of comples constants in seq (not recursive)\n static size_t countConsts(Object::ref seq);\n \/\/ tells if an object is a complex one or not\n static bool isComplexConst(Object::ref obj);\n};\n\nextern Assembler assembler;\n\n\/\/ Execute a given process\nProcessStatus execute(Process & proc, size_t& reductions, Process*& Q, bool init = 0);\n\n#endif \/\/ EXECUTORS_H\n<commit_msg>executors.hpp: removed solved TODO<commit_after>#ifndef EXECUTORS_H\n#define EXECUTORS_H\n\n#include \"processes.hpp\"\n#include \"objects.hpp\"\n#include \"reader.hpp\" \/\/ for Bytecode classes\n#include \"types.hpp\"\n\n#include <map>\n\n#include <boost\/smart_ptr.hpp>\n\n\/*\n hl functions are represented by a Closure structure, which has an\n attached bytecode_t array.\n\n Calling convention:\n\n proc.stack[0] *must* be a Closure\n !! for now, at least. in the future we will change this so that\n !! calls to non-Closure objects will be transformed to calls to\n !! the global <axiom>call*, which *should* be a Closure\n !! -- almkglor\n\n proc.stack[0] contains the closure. If it is a \"normal\" \n function, proc.stack[1] is the \"continuation\" function \n and proc.stack[2..n] are the parameters. \n proc.stack.size() is the number of parameters including \n the function itself and the continuation.\n \n If it is a \"continuation\" function, proc.stack[1] is always \n the return value. proc.stack.size() will be 2.\n\n Functions never return.\n*\/\n\n#define PASTE_SYMBOLS(x,y) x##y\n\n\/*\n Not necessary when using GCC.\n NOTE! We retain this and even add references to\n an _e_bytecode_label type so that modders who\n happen to use *only* GCC will remember to update\n the declarations for the benefit of non-GCC\n users.\n*\/\n\n#define DECLARE_BYTECODES enum _e_bytecode_label {\n#define BYTECODE_ENUM(x) PASTE_SYMBOLS(_bytecode_, x)\n#define A_BYTECODE(x) BYTECODE_ENUM(x),\n#define END_DECLARE_BYTECODES __null_bytecode };\nDECLARE_BYTECODES\n\tA_BYTECODE(apply)\n\tA_BYTECODE(apply_invert_k)\n\tA_BYTECODE(apply_list)\n\tA_BYTECODE(apply_k_release)\n A_BYTECODE(build_closure)\n\tA_BYTECODE(build_k_closure)\n\tA_BYTECODE(build_k_closure_recreate)\n\tA_BYTECODE(build_k_closure_reuse)\n\tA_BYTECODE(car)\n\tA_BYTECODE(car_local_push)\n\tA_BYTECODE(car_clos_push)\n\tA_BYTECODE(ccc)\n\tA_BYTECODE(cdr)\n\tA_BYTECODE(cdr_local_push)\n\tA_BYTECODE(cdr_clos_push)\n\tA_BYTECODE(check_vars)\n\tA_BYTECODE(closure_ref)\n\tA_BYTECODE(composeo)\n\tA_BYTECODE(composeo_continuation)\n\tA_BYTECODE(cons)\n A_BYTECODE(const_ref)\n\tA_BYTECODE(b_continue)\n\tA_BYTECODE(continue_local)\n\tA_BYTECODE(continue_on_clos)\n\tA_BYTECODE(global)\n\tA_BYTECODE(global_set)\n\tA_BYTECODE(halt)\n\tA_BYTECODE(halt_local_push)\n\tA_BYTECODE(halt_clos_push)\n\tA_BYTECODE(jmp_nil)\n \/\/A_BYTECODE(if_local)\n\tA_BYTECODE(b_int)\n\tA_BYTECODE(b_float)\n\tA_BYTECODE(lit_nil)\n\tA_BYTECODE(lit_t)\n\tA_BYTECODE(local)\n\tA_BYTECODE(monomethod)\n\tA_BYTECODE(reducto)\n A_BYTECODE(reducto_continuation)\n\tA_BYTECODE(rep)\n\tA_BYTECODE(rep_local_push)\n\tA_BYTECODE(rep_clos_push)\n\tA_BYTECODE(scar)\n\tA_BYTECODE(scdr)\n\tA_BYTECODE(sv)\n\tA_BYTECODE(sv_local_push)\n\tA_BYTECODE(sv_clos_push)\n\tA_BYTECODE(sv_ref)\n\tA_BYTECODE(sv_ref_local_push)\n\tA_BYTECODE(sv_ref_clos_push)\n\tA_BYTECODE(sv_set)\n\tA_BYTECODE(sym)\n\tA_BYTECODE(symeval)\n\tA_BYTECODE(table_create)\n\tA_BYTECODE(table_ref)\n\tA_BYTECODE(table_sref)\n\tA_BYTECODE(table_map)\n\tA_BYTECODE(tag)\n\tA_BYTECODE(type)\n\tA_BYTECODE(type_local_push)\n\tA_BYTECODE(type_clos_push)\n\tA_BYTECODE(variadic)\n\t\/*maybe organize by alphabetical order of bytecodes ^^*\/\n\tA_BYTECODE(do_executor)\n\tA_BYTECODE(plus)\n\tA_BYTECODE(minus)\n\tA_BYTECODE(mul)\n\tA_BYTECODE(div)\n\tA_BYTECODE(mod)\nEND_DECLARE_BYTECODES\n\n#ifdef __GNUC__\n\n\/\/ use indirect goto when using GCC\n\ntypedef void* _bytecode_label;\n#define DISPATCH_BYTECODES \\\n bytecode_t *pc = expect_type<Bytecode>(clos->code())->getCode();\\\n\tgoto *(pc->op);\n#define NEXT_BYTECODE goto *((++pc)->op)\n#define BYTECODE(x) BYTECODE_ENUM(x); PASTE_SYMBOLS(label_b_, x)\n#define THE_BYTECODE_LABEL(x) &&PASTE_SYMBOLS(label_b_, x)\n\n#else \/\/ __GNUC__\n\n\/\/ use an enum when using standard C\n\ntypedef enum _e_bytecode_label _bytecode_label;\n#define DISPATCH_BYTECODES \\\n\tbytecode_t *pc = expect_type<Bytecode>(clos->code())->getCode();\\\n\tswitch(pc->op)\n#define NEXT_BYTECODE {pc++; continue;}\n#define BYTECODE(x) case BYTECODE_ENUM(x)\n#define THE_BYTECODE_LABEL(x) BYTECODE_ENUM(x)\n\n#endif \/\/ __GNUC__\n\nclass Process;\nclass ProcessStack;\n\nclass Executor;\n\nclass ExecutorTable : public std::map<Symbol*, Executor*> {\npublic:\n\t~ExecutorTable();\n};\n\n\/* \n * Generic executor\n * An executor represents a built-in function\n *\/\nclass Executor {\nprivate:\n \/\/ table of available executors\n static ExecutorTable tbl;\npublic:\n \/\/ register an executor in the system\n \/\/ no locks: executors should be registered only during startup\n static void reg(Symbol *s, Executor *e) {\n tbl[s] = e;\n }\n \/\/ no locks: tbl stucture is immutable after initialization\n static Executor* findExecutor(Symbol *s) {\n std::map<Symbol*,Executor*>::iterator it = tbl.find(s);\n if (it==tbl.end())\n return NULL;\n else\n return it->second;\n }\n virtual ~Executor() {}\n \/\/ return true if a function call must be performed, false otherwise\n virtual bool run(Process & proc, size_t & reductions) = 0;\n};\n\ninline ExecutorTable::~ExecutorTable() {\n\tfor(iterator i = begin(); i != end(); ++i) {\n\t\tdelete i->second;\n\t}\n}\n\n\/*\n * The bytecode read by the reader should be assembled before execution\n * an assembled bytecode is an array of bytecode_t\n * The executor can assume that the bytecodes are correct\n * The assembler must have already catched eventual errors\n *\/\nstruct bytecode_t {\n _bytecode_label op; \/\/ operation code\n intptr_t val; \/\/ simple value argument (may be invalid)\n};\n\n\/\/ a bytecode object contains a table of complex constants such as gensyms\nclass Bytecode : public GenericDerivedVariadic<Bytecode> {\nprivate:\n boost::shared_array<bytecode_t> code;\n size_t codeSize;\n size_t nextCode; \/\/ next free position in code\n size_t nextPos; \/\/ next free position in variadic space\n\npublic:\n Bytecode(size_t sz) \n : GenericDerivedVariadic<Bytecode>(sz), codeSize(0), nextCode(0), \n nextPos(0) {}\n virtual ~Bytecode() {}\n\n Object::ref& operator[](size_t i) {\n if (i < size())\n return index(i);\n else\n throw_HlError(\"internal: trying to access objects in bytecode with an index too large!\");\n }\n\n Object::ref type(void) const {\n return Object::to_ref(symbol_bytecode);\n }\n\n bytecode_t* getCode() { return code.get(); }\n\n \/\/ close a complex constants\n size_t closeOver(Object::ref obj) {\n if (nextPos >= size())\n throw_HlError(\"internal: trying to close over, but there is no space left in Bytecode\");\n index(nextPos) = obj;\n return nextPos++;\n }\n\n \/\/ add a bytecode at the end of the sequence\n void push(bytecode_t b);\n void push(_bytecode_label op, intptr_t val);\n void push(Symbol *s, intptr_t val);\n void push(const char *s, intptr_t val);\n\n void traverse_references(GenericTraverser *gt) {\n for(size_t i = 0; i < nextPos; ++i) {\n gt->traverse(index(i));\n }\n }\n};\n\n#define INTPARAM(name) intptr_t name = pc->val\n#define SYMPARAM(name) Symbol *name = (Symbol*)pc->val\n#define FLOATPARAM(name) Float *name = (Float*)pc->val\n\nclass AsOp {\npublic:\n \/\/ expect arguments on the stack:\n \/\/ - sequence arg (stack top)\n \/\/ - simple arg\n \/\/ - Bytecode object being assembled\n \/\/ - seq being assembled\n virtual void assemble(Process & proc) = 0;\n};\n\nclass Assembler {\nprivate:\n typedef std::map<Symbol*, AsOp*> sym_op_tbl;\n sym_op_tbl tbl;\n\n \/\/ extracts a value pointer\/immediate object, throwing away the type tag\n static intptr_t simpleVal(Object::ref sa);\npublic:\n ~Assembler() { \n for (sym_op_tbl::iterator i = tbl.begin(); i!=tbl.end(); i++)\n delete i->second;\n }\n\n \/\/ register a new assembler operation\n template <class T>\n void reg(Symbol* s) { tbl[s] = new T(); }\n\n \/\/ do the assembly, leave a Bytecode on the stack, expect a sequence on \n \/\/ the stack\n void go(Process & proc); \n\n \/\/ count number of comples constants in seq (not recursive)\n static size_t countConsts(Object::ref seq);\n \/\/ tells if an object is a complex one or not\n static bool isComplexConst(Object::ref obj);\n};\n\nextern Assembler assembler;\n\n\/\/ Execute a given process\nProcessStatus execute(Process & proc, size_t& reductions, Process*& Q, bool init = 0);\n\n#endif \/\/ EXECUTORS_H\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <Eigen\/Dense>\n#include <unsupported\/Eigen\/MatrixFunctions>\n\n#include <map>\n#include <vector>\n\nusing std::vector;\nusing std::map;\n\n\nnamespace mcl_cpp\n{\n\tclass mcl\n\t{\n\tpublic:\n\t\t\/\/! @brief MCL ctor. Register a callback function to return the cluster results\n\t\tmcl(const Eigen::MatrixXd& Min, std::function< void(size_t cluster_j, size_t member_i) > f) : M(Min), ClusterResultCallback(f) {}\n\n\t\t\/*! @brief Apply Markov clustering algorithm with specified parameters and return clusters\n\t\t\tFor each cluster, returns the list of node-ids that belong to that cluster\n\t\t\t*\/\n\t\tEigen::MatrixXd cluster_mcl(double expand_factor = 2, double inflate_factor = 2, double max_loop = 10, double mult_factor = 1)\n\t\t{\n\t\t\tEigen::MatrixXd M_selfloop = M + mult_factor * Eigen::MatrixXd::Identity(M.cols(), M.rows());\n\t\t\tEigen::MatrixXd M_normalized = normalize(M_selfloop);\n\t\t\tint i;\n\t\t\tfor (i = 0; i < max_loop && !stop(M_normalized, i); i++)\n\t\t\t{\n\t\t\t\tinflate(M_normalized, inflate_factor);\n\t\t\t\texpand(M_normalized, expand_factor);\n\t\t\t}\n\t\t\tfor (auto row = 0; row<M_normalized.rows(); row++)\n\t\t\t{\n\t\t\t\tif (M_normalized(row, row) > 0)\n\t\t\t\t{\n\t\t\t\t\tfor (auto col = 0; col < M_normalized.cols(); col++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (M_normalized.coeff(row, col) > 0)\n\t\t\t\t\t\t\tClusterResultCallback(row, col);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn std::move(M_normalized);\n\t\t}\n\n\tprivate:\n\t\tbool stop(const Eigen::MatrixXd& in, int i)\n\t\t{\n\t\t\tauto m = in*in;\n\t\t\tauto diff = (m - in);\n\t\t\tauto mx = diff.maxCoeff(), mn = diff.minCoeff();\n\t\t\treturn (diff.maxCoeff() == diff.minCoeff());\n\t\t}\n\n\t\tEigen::MatrixXd normalize(Eigen::MatrixXd& in)\n\t\t{\n\t\t\tauto one_over_col_sum = in.colwise().sum().cwiseInverse();\n\t\t\tEigen::MatrixXd M_normalized = in * one_over_col_sum.asDiagonal();\n\t\t\treturn std::move(M_normalized);\n\t\t}\n\n\t\tvoid expand(Eigen::MatrixXd& in, double expand_factor)\n\t\t{\n\t\t\tEigen::MatrixPower<Eigen::MatrixXd> Apow(in);\n\t\t\tin = Apow(expand_factor);\n\t\t}\n\n\t\tvoid inflate(Eigen::MatrixXd& in, double inflate_factor)\n\t\t{\n\t\t\tauto lam = [inflate_factor](double x) -> double { return std::pow(x, inflate_factor); };\n\t\t\tin = in.unaryExpr(lam);\n\t\t\tin = normalize(in);\n\t\t}\n\n\t\tconst Eigen::MatrixXd & M;\n\t\tstd::function< void(size_t cls_i, size_t mem_j) > ClusterResultCallback;\n\t};\n\n\n\n\n\n\n}<commit_msg>Auto does some bad things on Visual Studio 2012.<commit_after>#pragma once\n\n#include <Eigen\/Dense>\n#include <unsupported\/Eigen\/MatrixFunctions>\n\n#include <map>\n#include <vector>\n\nusing std::vector;\nusing std::map;\n\n\nnamespace mcl_cpp\n{\n\tclass mcl\n\t{\n\tpublic:\n\t\t\/\/! @brief MCL ctor. Register a callback function to return the cluster results\n\t\tmcl(const Eigen::MatrixXd& Min, std::function< void(size_t cluster_j, size_t member_i) > f) : M(Min), ClusterResultCallback(f) {}\n\n\t\t\/*! @brief Apply Markov clustering algorithm with specified parameters and return clusters\n\t\t\tFor each cluster, returns the list of node-ids that belong to that cluster\n\t\t\t*\/\n\t\tEigen::MatrixXd cluster_mcl(double expand_factor = 2, double inflate_factor = 2, double max_loop = 10, double mult_factor = 1)\n\t\t{\n\t\t\tEigen::MatrixXd M_selfloop = M + mult_factor * Eigen::MatrixXd::Identity(M.cols(), M.rows());\n\t\t\tEigen::MatrixXd M_normalized = normalize(M_selfloop);\n\t\t\tint i;\n\t\t\tfor (i = 0; i < max_loop && !stop(M_normalized, i); i++)\n\t\t\t{\n\t\t\t\tinflate(M_normalized, inflate_factor);\n\t\t\t\texpand(M_normalized, expand_factor);\n\t\t\t}\n\t\t\tfor (auto row = 0; row<M_normalized.rows(); row++)\n\t\t\t{\n\t\t\t\tif (M_normalized(row, row) > 0)\n\t\t\t\t{\n\t\t\t\t\tfor (auto col = 0; col < M_normalized.cols(); col++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (M_normalized.coeff(row, col) > 0)\n\t\t\t\t\t\t\tClusterResultCallback(row, col);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn std::move(M_normalized);\n\t\t}\n\n\tprivate:\n\t\tbool stop(const Eigen::MatrixXd& in, int i)\n\t\t{\n\t\t\tEigen::MatrixXd m = in*in;\n\t\t\tEigen::MatrixXd diff = (m - in);\n\t\t\tdouble mx = diff.maxCoeff(), mn = diff.minCoeff();\n\t\t\treturn (diff.maxCoeff() == diff.minCoeff());\n\t\t}\n\n\t\tEigen::MatrixXd normalize(Eigen::MatrixXd& in)\n\t\t{\n\t\t\tEigen::MatrixXd one_over_col_sum = in.colwise().sum().cwiseInverse();\n\t\t\tEigen::MatrixXd M_normalized = in * one_over_col_sum.asDiagonal();\n\t\t\treturn std::move(M_normalized);\n\t\t}\n\n\t\tvoid expand(Eigen::MatrixXd& in, double expand_factor)\n\t\t{\n\t\t\tEigen::MatrixPower<Eigen::MatrixXd> Apow(in);\n\t\t\tin = Apow(expand_factor);\n\t\t}\n\n\t\tvoid inflate(Eigen::MatrixXd& in, double inflate_factor)\n\t\t{\n\t\t\tauto lam = [inflate_factor](double x) -> double { return std::pow(x, inflate_factor); };\n\t\t\tin = in.unaryExpr(lam);\n\t\t\tin = normalize(in);\n\t\t}\n\n\t\tconst Eigen::MatrixXd & M;\n\t\tstd::function< void(size_t cls_i, size_t mem_j) > ClusterResultCallback;\n\t};\n\n\n\n\n\n\n}<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2011, 2017 OpenWorm.\n * http:\/\/openworm.org\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the MIT License\n * which accompanies this distribution, and is available at\n * http:\/\/opensource.org\/licenses\/MIT\n *\n * Contributors:\n * \tOpenWorm - http:\/\/openworm.org\/people.html\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.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n *******************************************************************************\/\n#ifndef X_SPHMODEL\n#define X_SPHMODEL\n\n#include \"particle.h\"\n#include \"util\/x_error.h\"\n#include <array>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <regex>\n#include <string>\n#include <vector>\n\nnamespace x_engine {\nnamespace model {\nenum LOADMODE { NOMODE = -1, PARAMS, MODEL, POS, VEL };\n\ntemplate <class T = float, class container = std::vector<particle<T>>>\nclass sph_model {\n typedef std::map<std::string, size_t> sph_config;\n\npublic:\n sph_model(const std::string &config_file) {\n config = {{\"particles\", 0}, {\"x_max\", 0}, {\"x_min\", 0}, {\"y_max\", 0},\n {\"y_min\", 0}, {\"z_max\", 0}, {\"z_min\", 0}};\n read_model(config_file);\n std::cout << \"Model was loaded: \" << particles.size() << \" partticles.\"\n << std::endl;\n }\n const sph_config &get_config() const { return config; }\n\nprivate:\n container particles;\n sph_config config;\n std::map<std::string, T> phys_consts;\n std::shared_ptr<std::array<T, 4>> get_vector(const std::string &line) {\n std::shared_ptr<std::array<T, 4>> v(new std::array<T, 4>());\n std::stringstream ss(line);\n ss >> (*v)[0] >> (*v)[1] >> (*v)[2] >> (*v)[3]; \/\/ TODO check here!!!\n return v;\n }\n void read_model(const std::string &model_file) {\n std::ifstream file(model_file.c_str(), std::ios_base::binary);\n LOADMODE mode = NOMODE;\n bool is_model_mode = false;\n int index = 0;\n if (file.is_open()) {\n while (file.good()) {\n std::string cur_line;\n std::getline(file, cur_line);\n if (mode == NOMODE) {\n cur_line.erase(std::remove(cur_line.begin(), cur_line.end(), ' '),\n cur_line.end());\n cur_line.erase(std::remove(cur_line.begin(), cur_line.end(), '\\t'),\n cur_line.end());\n }\n if (cur_line.compare(\"parametrs[\") == 0) {\n mode = PARAMS;\n continue;\n } else if (cur_line.compare(\"model[\") == 0) {\n mode = MODEL;\n is_model_mode = true;\n continue;\n } else if (cur_line.compare(\"position[\") == 0) {\n mode = POS;\n continue;\n } else if (cur_line.compare(\"velocity[\") == 0) {\n mode = VEL;\n continue;\n } else if (cur_line.compare(\"]\") == 0) {\n mode = NOMODE;\n continue;\n }\n if (mode == PARAMS) {\n std::regex rgx(\"[\\\\t ]*(\\\\w+) *: *(\\\\d+) *([\/\/]*.*)\");\n std::smatch matches;\n if (std::regex_search(cur_line, matches, rgx)) {\n if (matches.size() > 2) {\n if (config.find(matches[1]) != config.end()) {\n config[matches[1]] =\n static_cast<size_t>(stoi(matches[2].str()));\n continue;\n }\n } else {\n std::string msg = x_engine::make_msg(\n \"Problem with parsing parametrs:\", matches[0].str(),\n \"Please check parametrs.\");\n throw parser_error(msg);\n }\n } else {\n throw parser_error(\n \"Please check parametrs section there are no parametrs.\");\n }\n }\n if (is_model_mode) {\n switch (mode) {\n case POS: {\n particle<T> p;\n p.pos = *get_vector(cur_line);\n particles.push_back(p);\n break;\n }\n case VEL: {\n if (index >= particles.size())\n throw parser_error(\n \"Config file problem. Velocities more than partiles is.\");\n particles[index].vel = *get_vector(cur_line);\n ++index;\n break;\n }\n default: { break; }\n }\n }\n }\n }\n file.close();\n }\n};\n}\n}\n#endif \/\/ X_SPHMODEL\n<commit_msg>work with reader<commit_after>\/*******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2011, 2017 OpenWorm.\n * http:\/\/openworm.org\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the MIT License\n * which accompanies this distribution, and is available at\n * http:\/\/opensource.org\/licenses\/MIT\n *\n * Contributors:\n * \tOpenWorm - http:\/\/openworm.org\/people.html\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.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n *******************************************************************************\/\n#ifndef X_SPHMODEL\n#define X_SPHMODEL\n\n#include \"particle.h\"\n#include \"util\/x_error.h\"\n#include <array>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <regex>\n#include <string>\n#include <vector>\n\nnamespace x_engine {\nnamespace model {\nenum LOADMODE { NOMODE = -1, PARAMS, MODEL, POS, VEL };\n\ntemplate <class T = float, class container = std::vector<particle<T>>>\nclass sph_model {\n typedef std::map<std::string, size_t> sph_config;\n\npublic:\n sph_model(const std::string &config_file) {\n config = {{\"particles\", 0}, {\"x_max\", 0}, {\"x_min\", 0}, {\"y_max\", 0},\n {\"y_min\", 0}, {\"z_max\", 0}, {\"z_min\", 0}};\n read_model(config_file);\n std::cout << \"Model was loaded: \" << particles.size() << \" partticles.\"\n << std::endl;\n }\n const sph_config &get_config() const { return config; }\n\nprivate:\n container particles;\n sph_config config;\n std::map<std::string, T> phys_consts;\n std::shared_ptr<std::array<T, 4>> get_vector(const std::string &line) {\n std::shared_ptr<std::array<T, 4>> v(new std::array<T, 4>());\n std::stringstream ss(line);\n ss >> (*v)[0] >> (*v)[1] >> (*v)[2] >> (*v)[3]; \/\/ TODO check here!!!\n return v;\n }\n void read_model(const std::string &model_file) {\n std::ifstream file(model_file.c_str(), std::ios_base::binary);\n LOADMODE mode = NOMODE;\n bool is_model_mode = false;\n int index = 0;\n if (file.is_open()) {\n while (file.good()) {\n std::string cur_line;\n std::getline(file, cur_line);\n auto i_space = cur_line.find_first_not_of(\" \");\n auto i_tab = cur_line.find_first_not_of(\"\\t\");\n cur_line.erase(\n std::remove(cur_line.begin(), cur_line.begin() + i_space, ' '),\n cur_line.end());\n cur_line.erase(\n std::remove(cur_line.begin(), cur_line.end() + i_tab, '\\t'),\n cur_line.end());\n if (cur_line.compare(\"parametrs[\") == 0) {\n mode = PARAMS;\n continue;\n } else if (cur_line.compare(\"model[\") == 0) {\n mode = MODEL;\n is_model_mode = true;\n continue;\n } else if (cur_line.compare(\"position[\") == 0) {\n mode = POS;\n continue;\n } else if (cur_line.compare(\"velocity[\") == 0) {\n mode = VEL;\n continue;\n } else if (cur_line.compare(\"]\") == 0) {\n mode = NOMODE;\n continue;\n }\n if (mode == PARAMS) {\n std::regex rgx(\"[\\\\t ]*(\\\\w+) *: *(\\\\d+) *([\/\/]*.*)\");\n std::smatch matches;\n if (std::regex_search(cur_line, matches, rgx)) {\n if (matches.size() > 2) {\n if (config.find(matches[1]) != config.end()) {\n config[matches[1]] =\n static_cast<size_t>(stoi(matches[2].str()));\n continue;\n }\n } else {\n std::string msg = x_engine::make_msg(\n \"Problem with parsing parametrs:\", matches[0].str(),\n \"Please check parametrs.\");\n throw parser_error(msg);\n }\n } else {\n throw parser_error(\n \"Please check parametrs section there are no parametrs.\");\n }\n }\n if (is_model_mode) {\n switch (mode) {\n case POS: {\n particle<T> p;\n p.pos = *get_vector(cur_line);\n particles.push_back(p);\n break;\n }\n case VEL: {\n if (index >= particles.size())\n throw parser_error(\n \"Config file problem. Velocities more than partiles is.\");\n particles[index].vel = *get_vector(cur_line);\n ++index;\n break;\n }\n default: { break; }\n }\n }\n }\n }\n file.close();\n }\n};\n}\n}\n#endif \/\/ X_SPHMODEL\n<|endoftext|>"} {"text":"<commit_before>#ifndef ___GFTOOLS_KMESH_HPP___\n#define ___GFTOOLS_KMESH_HPP___\n\n#include \"Grid.hpp\"\n#include <numeric>\n\nnamespace GFTools { \n\nclass KMesh : public Grid<RealType, KMesh>\n{\npublic:\n int _points;\n KMesh(size_t n_points);\n KMesh(const KMesh& rhs);\n KMesh(KMesh &&rhs);\n KMesh(){};\n KMesh& operator=(KMesh &&rhs){_points = rhs._points; _vals.swap(rhs._vals); return (*this);};\n KMesh& operator=(const KMesh &rhs){_points = rhs._points; _vals = rhs._vals; return (*this);};\n std::tuple <bool, size_t, RealType> find (RealType in) const ;\n template <class Obj> auto integrate(const Obj &in) const ->decltype(in(_vals[0]));\n template <class Obj, typename ...OtherArgTypes> auto integrate(const Obj &in, OtherArgTypes... Args) const -> decltype(in(_vals[0],Args...));\n \/\/template <class Obj> auto gridIntegrate(std::vector<Obj> &in) const -> Obj;\n template <class Obj> auto getValue(Obj &in, RealType x) const ->decltype(in[0]);\n template <class Obj> auto getValue(Obj &in, point x) const ->decltype(in[0]);\n point shift(point in, point shift_arg) const;\n template <class ArgType> point shift(point in, ArgType shift_arg) const;\n template <class ArgType> RealType shift(RealType in, ArgType shift_arg) const;\n};\n\nstruct KMeshPatch : public KMesh \n{\n std::map<size_t,size_t> _map_vals;\npublic:\n const KMesh& _parent;\n size_t _npoints;\n using KMesh::_vals;\n KMeshPatch(const KMesh& parent, std::vector<size_t> indices);\n KMeshPatch(const KMesh& parent);\n template <class Obj> auto getValue(Obj &in, RealType x) const ->decltype(in[0]);\n template <class Obj> auto getValue(Obj &in, KMesh::point x) const ->decltype(in[0]);\n size_t getIndex(KMesh::point x) const;\n};\ntemplate <>\ninline std::ostream& operator<<(std::ostream& lhs, const __num_format< typename KMesh::point> &in){lhs << std::setprecision(in._prec) << RealType(in._v._val); return lhs;};\n\n\/\/\n\/\/ KMesh\n\/\/\n\nKMesh::KMesh(size_t n_points):\nGrid<RealType,KMesh>(0,n_points,[n_points](size_t in){return 2.0*PI\/n_points*in;}),\n_points(n_points)\n{\n}\n\nKMesh::KMesh(const KMesh& rhs):Grid(rhs._vals),_points(rhs._points)\n{\n}\n\nKMesh::KMesh(KMesh &&rhs):Grid(rhs._vals),_points(rhs._points)\n{\n}\n\ninline std::tuple <bool, size_t, RealType> KMesh::find (RealType in) const\n{\n assert(in>=0 && in < 2.0*PI);\n int n = std::lround(in\/2.0\/PI*_points);\n if (n<0) { ERROR(\"KMesh point is out of bounds, \" << in << \"<\" << 0); return std::make_tuple(0,0,0); };\n if (n==_points) n=0; \n if (n>_points) { ERROR(\"KMesh point is out of bounds, \" << in << \"> 2*PI\"); return std::make_tuple(0,_points,0); };\n RealType weight=in\/2.0\/PI*_points-RealType(n);\n return std::make_tuple (1,n,weight);\n}\n\ntemplate <class Obj>\ninline auto KMesh::getValue(Obj &in, RealType x) const ->decltype(in[0]) \n{\n const auto find_result=this->find(x);\n if (!std::get<0>(find_result)) throw (exWrongIndex()); \n return in[std::get<1>(find_result)];\n}\n\n\ntemplate <class Obj>\ninline auto KMesh::getValue(Obj &in, KMesh::point x) const ->decltype(in[0]) \n{\n if (x._index < _vals.size() && x == _vals[x._index])\n return in[x._index];\n else { \n #ifndef NDEBUG\n ERROR (\"Point not found\"); \n #endif\n return this->getValue(in, RealType(x)); \n };\n}\n\ntemplate <class Obj> \nauto KMesh::integrate(const Obj &in) const -> decltype(in(_vals[0]))\n{\n decltype(in(_vals[0])) R = in(RealType(_vals[0]));\n R=std::accumulate(_vals.begin()+1, _vals.end(), R,[&](decltype(in(_vals[0]))& y,const decltype(_vals[0]) &x) {return y+in(x);}); \n return R\/_points;\n}\n\ntemplate <class Obj, typename ...OtherArgTypes> \nauto KMesh::integrate(const Obj &in, OtherArgTypes... Args) const -> decltype(in(_vals[0],Args...))\n{\n decltype(in(_vals[0],Args...)) R = in(_vals[0],Args...);\n R=std::accumulate(_vals.begin()+1, _vals.end(), R,[&](decltype(in(_vals[0]))& y,const decltype(_vals[0]) &x) {return y+in(x,Args...);}); \n return R\/_points;\n}\n\ntemplate <class ArgType>\ninline RealType KMesh::shift(RealType in, ArgType shift_arg) const\n{\n assert (in>=0 && in < 2.0*PI);\n \/\/if (std::abs(RealType(shift_arg))<std::numeric_limits<RealType>::epsilon()) return in;\n RealType out;\n out = in + RealType(shift_arg); \n out-= std::floor(out\/(2.0*PI))*2.0*PI;\n return out;\n}\n\n\ntemplate <class ArgType>\ninline typename KMesh::point KMesh::shift(point in, ArgType shift_arg) const\n{\n if (std::abs(RealType(shift_arg))<std::numeric_limits<RealType>::epsilon()) return in;\n point out;\n out._val = this->shift(in._val, shift_arg);\n auto find_result = this->find(out._val);\n if (!std::get<0>(find_result)) throw (exWrongIndex());\n out._index = std::get<1>(find_result);\n return (*this)[out._index];\n}\n\ninline typename KMesh::point KMesh::shift(point in, point shift_arg) const\n{\n size_t index = (in._index + shift_arg._index)%_points;\n #ifndef NDEBUG\n RealType val = this->shift(in._val, shift_arg._val);\n if (std::abs(val - _vals[index])>1e-3) throw (exWrongIndex()); \n #endif\n \/\/out._val = _vals[out._index];\n return _vals[index];\n}\n\n\n\n\/\/\n\/\/ KMeshPatch\n\/\/\n\n\nKMeshPatch::KMeshPatch(const KMesh& parent, std::vector<size_t> indices):\n _parent(parent),\n _npoints(indices.size())\n{\n _vals.resize(_npoints); \n for (size_t i=0; i<_npoints; ++i) {\n _vals[i]=_parent[indices[i]]; \n _map_vals[size_t(_vals[i])] = i;\n }\n}\n\nKMeshPatch::KMeshPatch(const KMesh& parent):\n _parent(parent),\n _npoints(parent.getSize())\n{\n _vals = parent.getPoints();\n for (size_t i=0; i<_npoints; ++i) {\n _map_vals[size_t(_vals[i])] = i;\n }\n}\n\ntemplate <class Obj> \ninline auto KMeshPatch::getValue(Obj &in, RealType x) const ->decltype(in[0])\n{\n const auto find_result=_parent.find(x);\n if (!std::get<0>(find_result)) throw (exWrongIndex()); \n return getValue(in, KMesh::point(std::get<1>(find_result), x));\n}\n\ntemplate <class Obj> \ninline auto KMeshPatch::getValue(Obj &in, KMesh::point x) const ->decltype(in[0])\n{\n return in[getIndex(x)];\n}\n\ninline size_t KMeshPatch::getIndex(KMesh::point x) const\n{\n auto f1 = _map_vals.find(size_t(x));\n if (f1!=_map_vals.end()) { return f1->second; }\n else throw (exWrongIndex());\n}\n\n} \/\/ end of namespace GFTools\n#endif \/\/ endif :: ifndef ___GFTOOLS_KMESH_HPP___\n<commit_msg>KMesh: default constructors and variable length<commit_after>#ifndef ___GFTOOLS_KMESH_HPP___\n#define ___GFTOOLS_KMESH_HPP___\n\n#include \"Grid.hpp\"\n#include <numeric>\n\nnamespace GFTools { \n\nclass KMesh : public Grid<RealType, KMesh>\n{\n mutable RealType _domain_len = 2.0*PI;\npublic:\n int _points;\n KMesh(size_t n_points, RealType len = 2.0*PI);\n KMesh(const KMesh& rhs) = default;\n KMesh(KMesh &&rhs) = default;\n KMesh() = default;\n KMesh& operator=(KMesh &&rhs) {_points = rhs._points; _domain_len = rhs._domain_len; _vals.swap(rhs._vals); return (*this);};\n KMesh& operator=(const KMesh &rhs) {_points = rhs._points; _domain_len = rhs._domain_len;_vals = rhs._vals; return (*this);};\n std::tuple <bool, size_t, RealType> find (RealType in) const ;\n template <class Obj> auto integrate(const Obj &in) const ->decltype(in(_vals[0]));\n template <class Obj, typename ...OtherArgTypes> auto integrate(const Obj &in, OtherArgTypes... Args) const -> decltype(in(_vals[0],Args...));\n \/\/template <class Obj> auto gridIntegrate(std::vector<Obj> &in) const -> Obj;\n template <class Obj> auto getValue(Obj &in, RealType x) const ->decltype(in[0]);\n template <class Obj> auto getValue(Obj &in, point x) const ->decltype(in[0]);\n point shift(point in, point shift_arg) const;\n template <class ArgType> point shift(point in, ArgType shift_arg) const;\n template <class ArgType> RealType shift(RealType in, ArgType shift_arg) const;\n};\n\nstruct KMeshPatch : public KMesh \n{\n std::map<size_t,size_t> _map_vals;\npublic:\n const KMesh& _parent;\n size_t _npoints;\n using KMesh::_vals;\n KMeshPatch(const KMesh& parent, std::vector<size_t> indices);\n KMeshPatch(const KMesh& parent);\n template <class Obj> auto getValue(Obj &in, RealType x) const ->decltype(in[0]);\n template <class Obj> auto getValue(Obj &in, KMesh::point x) const ->decltype(in[0]);\n size_t getIndex(KMesh::point x) const;\n};\ntemplate <>\ninline std::ostream& operator<<(std::ostream& lhs, const __num_format< typename KMesh::point> &in){lhs << std::setprecision(in._prec) << RealType(in._v._val); return lhs;};\n\n\/\/\n\/\/ KMesh\n\/\/\n\nKMesh::KMesh(size_t n_points, RealType len):\nGrid<RealType,KMesh>(0,n_points,[n_points,len](size_t in){return len\/n_points*in;}),\n_domain_len(len),\n_points(n_points)\n{\n}\n\/*\nKMesh::KMesh(const KMesh& rhs):Grid(rhs._vals),_points(rhs._points)\n{\n}\n\nKMesh::KMesh(KMesh &&rhs):Grid(rhs._vals),_points(rhs._points)\n{\n}\n*\/\ninline std::tuple <bool, size_t, RealType> KMesh::find (RealType in) const\n{\n assert(in>=0 && in < _domain_len);\n int n = std::lround(in\/_domain_len*_points);\n if (n<0) { ERROR(\"KMesh point is out of bounds, \" << in << \"<\" << 0); return std::make_tuple(0,0,0); };\n if (n==_points) n=0; \n if (n>_points) { ERROR(\"KMesh point is out of bounds, \" << in << \">\" << _domain_len); return std::make_tuple(0,_points,0); };\n RealType weight=in\/_domain_len*_points-RealType(n);\n return std::make_tuple (1,n,weight);\n}\n\ntemplate <class Obj>\ninline auto KMesh::getValue(Obj &in, RealType x) const ->decltype(in[0]) \n{\n const auto find_result=this->find(x);\n if (!std::get<0>(find_result)) throw (exWrongIndex()); \n return in[std::get<1>(find_result)];\n}\n\n\ntemplate <class Obj>\ninline auto KMesh::getValue(Obj &in, KMesh::point x) const ->decltype(in[0]) \n{\n if (x._index < _vals.size() && x == _vals[x._index])\n return in[x._index];\n else { \n #ifndef NDEBUG\n ERROR (\"Point not found\"); \n #endif\n return this->getValue(in, RealType(x)); \n };\n}\n\ntemplate <class Obj> \nauto KMesh::integrate(const Obj &in) const -> decltype(in(_vals[0]))\n{\n decltype(in(_vals[0])) R = in(RealType(_vals[0]));\n R=std::accumulate(_vals.begin()+1, _vals.end(), R,[&](decltype(in(_vals[0]))& y,const decltype(_vals[0]) &x) {return y+in(x);}); \n return R\/_points;\n}\n\ntemplate <class Obj, typename ...OtherArgTypes> \nauto KMesh::integrate(const Obj &in, OtherArgTypes... Args) const -> decltype(in(_vals[0],Args...))\n{\n decltype(in(_vals[0],Args...)) R = in(_vals[0],Args...);\n R=std::accumulate(_vals.begin()+1, _vals.end(), R,[&](decltype(in(_vals[0]))& y,const decltype(_vals[0]) &x) {return y+in(x,Args...);}); \n return R\/_points;\n}\n\ntemplate <class ArgType>\ninline RealType KMesh::shift(RealType in, ArgType shift_arg) const\n{\n assert (in>=0 && in < _domain_len);\n \/\/if (std::abs(RealType(shift_arg))<std::numeric_limits<RealType>::epsilon()) return in;\n RealType out;\n out = in + RealType(shift_arg); \n out-= std::floor(out\/_domain_len)*_domain_len;\n return out;\n}\n\n\ntemplate <class ArgType>\ninline typename KMesh::point KMesh::shift(point in, ArgType shift_arg) const\n{\n if (std::abs(RealType(shift_arg))<std::numeric_limits<RealType>::epsilon()) return in;\n point out;\n out._val = this->shift(in._val, shift_arg);\n auto find_result = this->find(out._val);\n if (!std::get<0>(find_result)) throw (exWrongIndex());\n out._index = std::get<1>(find_result);\n return (*this)[out._index];\n}\n\ninline typename KMesh::point KMesh::shift(point in, point shift_arg) const\n{\n size_t index = (in._index + shift_arg._index)%_points;\n #ifndef NDEBUG\n RealType val = this->shift(in._val, shift_arg._val);\n if (std::abs(val - _vals[index])>1e-3) throw (exWrongIndex()); \n #endif\n \/\/out._val = _vals[out._index];\n return _vals[index];\n}\n\n\n\n\/\/\n\/\/ KMeshPatch\n\/\/\n\n\nKMeshPatch::KMeshPatch(const KMesh& parent, std::vector<size_t> indices):\n _parent(parent),\n _npoints(indices.size())\n{\n _vals.resize(_npoints); \n for (size_t i=0; i<_npoints; ++i) {\n _vals[i]=_parent[indices[i]]; \n _map_vals[size_t(_vals[i])] = i;\n }\n}\n\nKMeshPatch::KMeshPatch(const KMesh& parent):\n _parent(parent),\n _npoints(parent.getSize())\n{\n _vals = parent.getPoints();\n for (size_t i=0; i<_npoints; ++i) {\n _map_vals[size_t(_vals[i])] = i;\n }\n}\n\ntemplate <class Obj> \ninline auto KMeshPatch::getValue(Obj &in, RealType x) const ->decltype(in[0])\n{\n const auto find_result=_parent.find(x);\n if (!std::get<0>(find_result)) throw (exWrongIndex()); \n return getValue(in, KMesh::point(std::get<1>(find_result), x));\n}\n\ntemplate <class Obj> \ninline auto KMeshPatch::getValue(Obj &in, KMesh::point x) const ->decltype(in[0])\n{\n return in[getIndex(x)];\n}\n\ninline size_t KMeshPatch::getIndex(KMesh::point x) const\n{\n auto f1 = _map_vals.find(size_t(x));\n if (f1!=_map_vals.end()) { return f1->second; }\n else throw (exWrongIndex());\n}\n\n} \/\/ end of namespace GFTools\n#endif \/\/ endif :: ifndef ___GFTOOLS_KMESH_HPP___\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2014 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (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 **********************************************************************************************************************\/\n\n#include \"Cursor.h\"\n#include \"..\/items\/Item.h\"\n#include \"..\/items\/ItemStyle.h\"\n\nnamespace Visualization {\n\nCursor::Cursor(Item* owner, CursorType type, Item* visualization)\n\t: owner_{owner}, visualization_{nullptr}, type_{type}, notLocationEquivalent_{false}\n{\n\tif (visualization) setVisualization(visualization);\n}\n\nCursor::Cursor(const Cursor& other) :\tposition_{other.position_}, region_{other.region_}, owner_{other.owner_},\n\t\ttype_{other.type_}, notLocationEquivalent_{other.notLocationEquivalent_}\n{}\n\nCursor::~Cursor()\n{\n\tsetVisualization(nullptr);\n}\n\nCursor* Cursor::clone() const\n{\n\treturn new Cursor(*this);\n}\n\nvoid Cursor::update()\n{\n\tif (type_ == BoxCursor)\n\t{\n\t\tsetRegion( owner_->boundingRect().toRect() );\n\t\tsetPosition( region_.center() );\n\t}\n}\n\nItem* Cursor::owner() const\n{\n\treturn owner_;\n}\n\nvoid Cursor::setVisualization(Item* visualization)\n{\n\tSAFE_DELETE_ITEM(visualization_);\n\tvisualization_ = visualization;\n\n\tif (visualization_)\n\t{\n\t\tauto item = owner();\n\t\twhile (item)\n\t\t{\n\t\t\tif (item->flags() & Item::ItemIgnoresTransformations)\n\t\t\t{\n\t\t\t\tvisualization_->setFlag(Item::ItemIgnoresTransformations);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\titem = item->parent();\n\t\t}\n\t}\n}\n\nbool Cursor::isSame(Cursor* other)\n{\n\treturn owner() == other->owner() && position() == other->position();\n}\n\nbool Cursor::isAtBoundary() const\n{\n\treturn false;\n}\n\nbool Cursor::isLocationEquivalent(Cursor* c)\n{\n\treturn isLocationEquivalent(c->notLocationEquivalent(), c->type(), c->isAtBoundary(), c->owner());\n}\n\nbool Cursor::isLocationEquivalent(bool otherNotLocationEquivalent, CursorType otherType, bool otherIsAtBoundary,\n\t\tItem* otherOwner)\n{\n\tif (otherNotLocationEquivalent || notLocationEquivalent() ) return false;\n\tif (otherType != type() || otherType == BoxCursor) return false;\n\tif (!otherIsAtBoundary && ! isAtBoundary()) return false;\n\tif (owner() == otherOwner) return false;\n\tif (!( owner()->isAncestorOf(otherOwner) && allowEquivalentCursorsAcrossBoundaries(owner(), otherOwner))\n\t\t\t&& !(otherOwner->isAncestorOf(owner()) && allowEquivalentCursorsAcrossBoundaries(otherOwner, owner()) ) )\n\t\treturn false;\n\n\treturn true;\n}\n\nbool Cursor::allowEquivalentCursorsAcrossBoundaries(Item* parent, Item* child)\n{\n\tif (!parent->style()->allowEquivalentCursorsThroughBoundary()) return false;\n\twhile (child != parent)\n\t{\n\t\tif (!child->style()->allowEquivalentCursorsThroughBoundary()) return false;\n\t\tchild = child->parent();\n\t};\n\treturn true;\n}\n\nQRect Cursor::sceneRegion()\n{\n\treturn owner()->mapToScene(region()).boundingRect().toRect();\n}\n\n}\n<commit_msg>remove semicolon after loop<commit_after>\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2014 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (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 **********************************************************************************************************************\/\n\n#include \"Cursor.h\"\n#include \"..\/items\/Item.h\"\n#include \"..\/items\/ItemStyle.h\"\n\nnamespace Visualization {\n\nCursor::Cursor(Item* owner, CursorType type, Item* visualization)\n\t: owner_{owner}, visualization_{nullptr}, type_{type}, notLocationEquivalent_{false}\n{\n\tif (visualization) setVisualization(visualization);\n}\n\nCursor::Cursor(const Cursor& other) :\tposition_{other.position_}, region_{other.region_}, owner_{other.owner_},\n\t\ttype_{other.type_}, notLocationEquivalent_{other.notLocationEquivalent_}\n{}\n\nCursor::~Cursor()\n{\n\tsetVisualization(nullptr);\n}\n\nCursor* Cursor::clone() const\n{\n\treturn new Cursor(*this);\n}\n\nvoid Cursor::update()\n{\n\tif (type_ == BoxCursor)\n\t{\n\t\tsetRegion( owner_->boundingRect().toRect() );\n\t\tsetPosition( region_.center() );\n\t}\n}\n\nItem* Cursor::owner() const\n{\n\treturn owner_;\n}\n\nvoid Cursor::setVisualization(Item* visualization)\n{\n\tSAFE_DELETE_ITEM(visualization_);\n\tvisualization_ = visualization;\n\n\tif (visualization_)\n\t{\n\t\tauto item = owner();\n\t\twhile (item)\n\t\t{\n\t\t\tif (item->flags() & Item::ItemIgnoresTransformations)\n\t\t\t{\n\t\t\t\tvisualization_->setFlag(Item::ItemIgnoresTransformations);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\titem = item->parent();\n\t\t}\n\t}\n}\n\nbool Cursor::isSame(Cursor* other)\n{\n\treturn owner() == other->owner() && position() == other->position();\n}\n\nbool Cursor::isAtBoundary() const\n{\n\treturn false;\n}\n\nbool Cursor::isLocationEquivalent(Cursor* c)\n{\n\treturn isLocationEquivalent(c->notLocationEquivalent(), c->type(), c->isAtBoundary(), c->owner());\n}\n\nbool Cursor::isLocationEquivalent(bool otherNotLocationEquivalent, CursorType otherType, bool otherIsAtBoundary,\n\t\tItem* otherOwner)\n{\n\tif (otherNotLocationEquivalent || notLocationEquivalent() ) return false;\n\tif (otherType != type() || otherType == BoxCursor) return false;\n\tif (!otherIsAtBoundary && ! isAtBoundary()) return false;\n\tif (owner() == otherOwner) return false;\n\tif (!( owner()->isAncestorOf(otherOwner) && allowEquivalentCursorsAcrossBoundaries(owner(), otherOwner))\n\t\t\t&& !(otherOwner->isAncestorOf(owner()) && allowEquivalentCursorsAcrossBoundaries(otherOwner, owner()) ) )\n\t\treturn false;\n\n\treturn true;\n}\n\nbool Cursor::allowEquivalentCursorsAcrossBoundaries(Item* parent, Item* child)\n{\n\tif (!parent->style()->allowEquivalentCursorsThroughBoundary()) return false;\n\twhile (child != parent)\n\t{\n\t\tif (!child->style()->allowEquivalentCursorsThroughBoundary()) return false;\n\t\tchild = child->parent();\n\t}\n\treturn true;\n}\n\nQRect Cursor::sceneRegion()\n{\n\treturn owner()->mapToScene(region()).boundingRect().toRect();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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 \"views\/focus\/accelerator_handler.h\"\n\n#include <bitset>\n#include <gtk\/gtk.h>\n#if defined(HAVE_XINPUT2)\n#include <X11\/extensions\/XInput2.h>\n#else\n#include <X11\/Xlib.h>\n#endif\n\n#include \"views\/accelerator.h\"\n#include \"views\/events\/event.h\"\n#include \"views\/focus\/focus_manager.h\"\n#include \"views\/ime\/input_method.h\"\n#include \"views\/touchui\/touch_factory.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_gtk.h\"\n\nnamespace views {\n\nnamespace {\n\nWidget* FindWidgetForGdkWindow(GdkWindow* gdk_window) {\n gpointer data = NULL;\n gdk_window_get_user_data(gdk_window, &data);\n GtkWidget* gtk_widget = reinterpret_cast<GtkWidget*>(data);\n if (!gtk_widget || !GTK_IS_WIDGET(gtk_widget)) {\n DLOG(WARNING) << \"no GtkWidget found for that GdkWindow\";\n return NULL;\n }\n NativeWidget* widget = NativeWidget::GetNativeWidgetForNativeView(gtk_widget);\n\n if (!widget) {\n DLOG(WARNING) << \"no WidgetGtk found for that GtkWidget\";\n return NULL;\n }\n return widget->GetWidget();\n}\n\n#if defined(HAVE_XINPUT2)\nbool X2EventIsTouchEvent(XEvent* xev) {\n \/\/ TODO(sad): Determine if the captured event is a touch-event.\n XGenericEventCookie* cookie = &xev->xcookie;\n switch (cookie->evtype) {\n case XI_ButtonPress:\n case XI_ButtonRelease:\n case XI_Motion: {\n \/\/ Is the event coming from a touch device?\n return TouchFactory::GetInstance()->IsTouchDevice(\n static_cast<XIDeviceEvent*>(cookie->data)->sourceid);\n }\n default:\n return false;\n }\n}\n#endif \/\/ HAVE_XINPUT2\n\n} \/\/ namespace\n\n#if defined(HAVE_XINPUT2)\nbool DispatchX2Event(RootView* root, XEvent* xev) {\n XGenericEventCookie* cookie = &xev->xcookie;\n bool touch_event = false;\n\n if (X2EventIsTouchEvent(xev)) {\n \/\/ Hide the cursor when a touch event comes in.\n TouchFactory::GetInstance()->SetCursorVisible(false, false);\n touch_event = true;\n\n \/\/ Create a TouchEvent, and send it off to |root|. If the event\n \/\/ is processed by |root|, then return. Otherwise let it fall through so it\n \/\/ can be used (if desired) as a mouse event.\n Event::FromNativeEvent2 from_native;\n TouchEvent touch(xev, from_native);\n if (root->OnTouchEvent(touch) != views::View::TOUCH_STATUS_UNKNOWN)\n return true;\n }\n\n switch (cookie->evtype) {\n case XI_KeyPress:\n case XI_KeyRelease: {\n \/\/ TODO(sad): We don't capture XInput2 events from keyboard yet.\n break;\n }\n case XI_ButtonPress:\n case XI_ButtonRelease:\n case XI_Motion: {\n \/\/ Scrolling the wheel generates press\/release events with button id's 4\n \/\/ and 5. In case of a wheelscroll, we do not want to show the cursor.\n XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(cookie->data);\n if (xievent->detail == 4 || xievent->detail == 5) {\n Event::FromNativeEvent2 from_native;\n MouseWheelEvent wheelev(xev, from_native);\n return root->OnMouseWheel(wheelev);\n }\n\n Event::FromNativeEvent2 from_native;\n MouseEvent mouseev(xev, from_native);\n if (!touch_event) {\n \/\/ Show the cursor, and decide whether or not the cursor should be\n \/\/ automatically hidden after a certain time of inactivity.\n int button_flags = mouseev.flags() & (ui::EF_RIGHT_BUTTON_DOWN |\n ui::EF_MIDDLE_BUTTON_DOWN | ui::EF_LEFT_BUTTON_DOWN);\n bool start_timer = false;\n\n switch (cookie->evtype) {\n case XI_ButtonPress:\n start_timer = false;\n break;\n case XI_ButtonRelease:\n \/\/ For a release, start the timer if this was only button pressed\n \/\/ that is being released.\n if (button_flags == ui::EF_RIGHT_BUTTON_DOWN ||\n button_flags == ui::EF_LEFT_BUTTON_DOWN ||\n button_flags == ui::EF_MIDDLE_BUTTON_DOWN)\n start_timer = true;\n break;\n case XI_Motion:\n start_timer = !button_flags;\n break;\n }\n TouchFactory::GetInstance()->SetCursorVisible(true, start_timer);\n }\n\n \/\/ Dispatch the event.\n switch (cookie->evtype) {\n case XI_ButtonPress:\n return root->OnMousePressed(mouseev);\n case XI_ButtonRelease:\n root->OnMouseReleased(mouseev);\n return true;\n case XI_Motion: {\n if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {\n return root->OnMouseDragged(mouseev);\n } else {\n root->OnMouseMoved(mouseev);\n return true;\n }\n }\n }\n }\n }\n\n return false;\n}\n\n#endif \/\/ HAVE_XINPUT2\n\nbool DispatchXEvent(XEvent* xev) {\n GdkDisplay* gdisp = gdk_display_get_default();\n XID xwindow = xev->xany.window;\n\n#if defined(HAVE_XINPUT2)\n if (xev->type == GenericEvent) {\n if (!TouchFactory::GetInstance()->ShouldProcessXI2Event(xev))\n return true; \/\/ Consume the event.\n\n XGenericEventCookie* cookie = &xev->xcookie;\n if (cookie->evtype == XI_HierarchyChanged) {\n TouchFactory::GetInstance()->UpdateDeviceList(cookie->display);\n return true;\n }\n\n XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);\n xwindow = xiev->event;\n }\n#endif\n\n GdkWindow* gwind = gdk_window_lookup_for_display(gdisp, xwindow);\n Widget* widget = FindWidgetForGdkWindow(gwind);\n if (widget) {\n RootView* root = widget->GetRootView();\n switch (xev->type) {\n case KeyPress:\n case KeyRelease: {\n Event::FromNativeEvent2 from_native;\n KeyEvent keyev(xev, from_native);\n InputMethod* ime = widget->GetInputMethod();\n \/\/ Always dispatch key events to the input method first, to make sure\n \/\/ that the input method's hotkeys work all time.\n if (ime) {\n ime->DispatchKeyEvent(keyev);\n return true;\n }\n return widget->OnKeyEvent(keyev);\n }\n\n case ButtonPress:\n case ButtonRelease: {\n if (xev->xbutton.button == 4 || xev->xbutton.button == 5) {\n \/\/ Scrolling the wheel triggers button press\/release events.\n Event::FromNativeEvent2 from_native;\n MouseWheelEvent wheelev(xev, from_native);\n return root->OnMouseWheel(wheelev);\n } else {\n Event::FromNativeEvent2 from_native;\n MouseEvent mouseev(xev, from_native);\n if (xev->type == ButtonPress) {\n return root->OnMousePressed(mouseev);\n } else {\n root->OnMouseReleased(mouseev);\n return true; \/\/ Assume the event has been processed to make sure we\n \/\/ don't process it twice.\n }\n }\n }\n\n case MotionNotify: {\n Event::FromNativeEvent2 from_native;\n MouseEvent mouseev(xev, from_native);\n if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {\n return root->OnMouseDragged(mouseev);\n } else {\n root->OnMouseMoved(mouseev);\n return true;\n }\n }\n\n#if defined(HAVE_XINPUT2)\n case GenericEvent: {\n return DispatchX2Event(root, xev);\n }\n#endif\n }\n }\n\n return false;\n}\n\n#if defined(HAVE_XINPUT2)\nvoid SetTouchDeviceList(std::vector<unsigned int>& devices) {\n TouchFactory::GetInstance()->SetTouchDeviceList(devices);\n}\n#endif\n\nAcceleratorHandler::AcceleratorHandler() {}\n\nbool AcceleratorHandler::Dispatch(GdkEvent* event) {\n gtk_main_do_event(event);\n return true;\n}\n\nbase::MessagePumpGlibXDispatcher::DispatchStatus\n AcceleratorHandler::DispatchX(XEvent* xev) {\n return DispatchXEvent(xev) ?\n base::MessagePumpGlibXDispatcher::EVENT_PROCESSED :\n base::MessagePumpGlibXDispatcher::EVENT_IGNORED;\n}\n\n} \/\/ namespace views\n<commit_msg>Refactor some mouse\/wheel\/touch XEvent handling. Delegate logic to Widget; nix most direct RootView uses.<commit_after>\/\/ Copyright (c) 2011 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 \"views\/focus\/accelerator_handler.h\"\n\n#include <bitset>\n#include <gtk\/gtk.h>\n#if defined(HAVE_XINPUT2)\n#include <X11\/extensions\/XInput2.h>\n#else\n#include <X11\/Xlib.h>\n#endif\n\n#include \"views\/accelerator.h\"\n#include \"views\/events\/event.h\"\n#include \"views\/focus\/focus_manager.h\"\n#include \"views\/ime\/input_method.h\"\n#include \"views\/touchui\/touch_factory.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_gtk.h\"\n\nnamespace views {\n\nnamespace {\n\nWidget* FindWidgetForGdkWindow(GdkWindow* gdk_window) {\n gpointer data = NULL;\n gdk_window_get_user_data(gdk_window, &data);\n GtkWidget* gtk_widget = reinterpret_cast<GtkWidget*>(data);\n if (!gtk_widget || !GTK_IS_WIDGET(gtk_widget)) {\n DLOG(WARNING) << \"no GtkWidget found for that GdkWindow\";\n return NULL;\n }\n NativeWidget* widget = NativeWidget::GetNativeWidgetForNativeView(gtk_widget);\n\n if (!widget) {\n DLOG(WARNING) << \"no WidgetGtk found for that GtkWidget\";\n return NULL;\n }\n return widget->GetWidget();\n}\n\n} \/\/ namespace\n\n#if defined(HAVE_XINPUT2)\nbool DispatchX2Event(Widget* widget, XEvent* xev) {\n XGenericEventCookie* cookie = &xev->xcookie;\n switch (cookie->evtype) {\n case XI_KeyPress:\n case XI_KeyRelease: {\n \/\/ TODO(sad): We don't capture XInput2 events from keyboard yet.\n break;\n }\n case XI_ButtonPress:\n case XI_ButtonRelease:\n case XI_Motion: {\n XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(cookie->data);\n Event::FromNativeEvent2 from_native;\n\n \/\/ Scrolling the wheel generates press\/release events with button id's 4\n \/\/ and 5. In case of a wheelscroll, we do not want to show the cursor.\n if (xievent->detail == 4 || xievent->detail == 5) {\n MouseWheelEvent wheelev(xev, from_native);\n return widget->OnMouseEvent(wheelev);\n }\n\n MouseEvent mouseev(xev, from_native);\n \/\/ TODO(sad): Determine if the captured event is a touch-event.\n \/\/ Is the event coming from a touch device?\n if (TouchFactory::GetInstance()->IsTouchDevice(xievent->sourceid)) {\n \/\/ Hide the cursor when a touch event comes in.\n TouchFactory::GetInstance()->SetCursorVisible(false, false);\n \/\/ If the TouchEvent is processed by |root|, then return. Otherwise let\n \/\/ it fall through so it can be used as a MouseEvent, if desired.\n TouchEvent touch(xev, from_native);\n RootView* root = widget->GetRootView();\n if (root->OnTouchEvent(touch) != views::View::TOUCH_STATUS_UNKNOWN)\n return true;\n } else {\n \/\/ Show the cursor. Start a timer to hide the cursor after a delay on\n \/\/ move (not drag) events, or if the only button pressed is released.\n bool start_timer = mouseev.type() == ui::ET_MOUSE_MOVED;\n start_timer |= mouseev.type() == ui::ET_MOUSE_RELEASED &&\n (mouseev.IsOnlyLeftMouseButton() ||\n mouseev.IsOnlyMiddleMouseButton() ||\n mouseev.IsOnlyRightMouseButton());\n TouchFactory::GetInstance()->SetCursorVisible(true, start_timer);\n }\n return widget->OnMouseEvent(mouseev);\n }\n }\n return false;\n}\n\n#endif \/\/ HAVE_XINPUT2\n\nbool DispatchXEvent(XEvent* xev) {\n GdkDisplay* gdisp = gdk_display_get_default();\n XID xwindow = xev->xany.window;\n\n#if defined(HAVE_XINPUT2)\n if (xev->type == GenericEvent) {\n if (!TouchFactory::GetInstance()->ShouldProcessXI2Event(xev))\n return true; \/\/ Consume the event.\n\n XGenericEventCookie* cookie = &xev->xcookie;\n if (cookie->evtype == XI_HierarchyChanged) {\n TouchFactory::GetInstance()->UpdateDeviceList(cookie->display);\n return true;\n }\n\n XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);\n xwindow = xiev->event;\n }\n#endif\n\n GdkWindow* gwind = gdk_window_lookup_for_display(gdisp, xwindow);\n Widget* widget = FindWidgetForGdkWindow(gwind);\n if (widget) {\n Event::FromNativeEvent2 from_native;\n switch (xev->type) {\n case KeyPress:\n case KeyRelease: {\n KeyEvent keyev(xev, from_native);\n InputMethod* ime = widget->GetInputMethod();\n \/\/ Always dispatch key events to the input method first, to make sure\n \/\/ that the input method's hotkeys work all time.\n if (ime) {\n ime->DispatchKeyEvent(keyev);\n return true;\n }\n return widget->OnKeyEvent(keyev);\n }\n case ButtonPress:\n case ButtonRelease:\n if (xev->xbutton.button == 4 || xev->xbutton.button == 5) {\n \/\/ Scrolling the wheel triggers button press\/release events.\n MouseWheelEvent wheelev(xev, from_native);\n return widget->OnMouseEvent(wheelev);\n }\n \/\/ fallthrough\n case MotionNotify: {\n MouseEvent mouseev(xev, from_native);\n return widget->OnMouseEvent(mouseev);\n }\n\n#if defined(HAVE_XINPUT2)\n case GenericEvent: {\n return DispatchX2Event(widget, xev);\n }\n#endif\n }\n }\n\n return false;\n}\n\n#if defined(HAVE_XINPUT2)\nvoid SetTouchDeviceList(std::vector<unsigned int>& devices) {\n TouchFactory::GetInstance()->SetTouchDeviceList(devices);\n}\n#endif\n\nAcceleratorHandler::AcceleratorHandler() {}\n\nbool AcceleratorHandler::Dispatch(GdkEvent* event) {\n gtk_main_do_event(event);\n return true;\n}\n\nbase::MessagePumpGlibXDispatcher::DispatchStatus\n AcceleratorHandler::DispatchX(XEvent* xev) {\n return DispatchXEvent(xev) ?\n base::MessagePumpGlibXDispatcher::EVENT_PROCESSED :\n base::MessagePumpGlibXDispatcher::EVENT_IGNORED;\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in license.txt\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n\n#include \"Framework.h\"\n#include \"Profiler.h\"\n#include \"IRenderer.h\"\n#include \"CoreException.h\"\n#include \"Application.h\"\n#include \"VersionInfo.h\"\n#include \"ConfigAPI.h\"\n#include \"PluginAPI.h\"\n#include \"LoggingFunctions.h\"\n#include \"IModule.h\"\n#include \"FrameAPI.h\"\n\n#include \"InputAPI.h\"\n#include \"AssetAPI.h\"\n#include \"AudioAPI.h\"\n#include \"ConsoleAPI.h\"\n#include \"SceneAPI.h\"\n#include \"UiAPI.h\"\n#include \"UiMainWindow.h\"\n\n#include <iostream>\n#include <QDir>\n\n#include \"MemoryLeakCheck.h\"\n\n\/\/\/ Temporary utility structure for strong supported command line parameters and their descriptions.\nstruct CommandLineParameterMap\n{\n \/\/\/ Prints the structure to std::cout.\n void Print() const\n {\n QMap<QString, QString>::const_iterator it = commands.begin();\n while(it != commands.end())\n {\n int charIdx = 0;\n const int treshold = 15;\n const int maxLineWidth = 80; \/\/\/< @todo 80 on Windows, but how bout on other platforms?\n int cmdLength = it.key().length();\n std::cout << it.key().toStdString();\n if (cmdLength >= treshold)\n {\n std::cout << std::endl;\n for(charIdx = 0; charIdx < treshold ; ++charIdx)\n std::cout << \" \";\n }\n else\n for(charIdx = cmdLength; charIdx < treshold ; ++charIdx)\n std::cout << \" \";\n\n for(QString::const_iterator descIter = it.value().begin(); descIter != it.value().end(); ++descIter)\n {\n std::cout << (*descIter).toAscii();\n ++charIdx;\n if (charIdx >= maxLineWidth)\n {\n charIdx = 0;\n for(charIdx; charIdx < treshold ; ++charIdx)\n std::cout << \" \";\n }\n }\n\n std::cout << std::endl;\n ++it;\n }\n }\n\n QMap<QString, QString> commands;\n};\n\nFramework *Framework::instance = 0;\n\nFramework::Framework(int argc, char** argv) :\n exit_signal_(false),\n argc_(argc),\n argv_(argv),\n headless_(false),\n application(0),\n frame(0),\n console(0),\n scene(0),\n input(0),\n asset(0),\n audio(0),\n plugin(0),\n config(0),\n ui(0),\n#ifdef PROFILING\n profiler(0),\n#endif\n renderer(0),\n apiVersionInfo(0),\n applicationVersionInfo(0)\n{ \/\/ Remember this Framework instance in a static pointer. Note that this does not help visibility for external DLL code linking to Framework.\n instance = this;\n\n \/\/ Api\/Application name and version. Can be accessed via ApiVersionInfo() and ApplicationVersionInfo().\n \/\/\/ @note Modify these values when you are making a custom Tundra. Also the version needs to be changed here on releases.\n apiVersionInfo = new ApiVersionInfo(2, 0, 0, 0);\n applicationVersionInfo = new ApplicationVersionInfo(2, 0, 0, 0, \"realXtend\", \"Tundra\");\n\n CommandLineParameterMap cmdLineDescs;\n \/\/\/\\todo We cannot specify all commands here, since it is not extensible. Generate a method for modules to specify their own options (probably\n \/\/\/ best is to have them parse their own options).\n cmdLineDescs.commands[\"--help\"] = \"Produce help message\"; \/\/ Framework\n cmdLineDescs.commands[\"--headless\"] = \"Run in headless mode without any windows or rendering\"; \/\/ Framework & OgreRenderingModule\n cmdLineDescs.commands[\"--disablerunonload\"] = \"Do not start script applications (EC_Script's with applicationName defined) automatically\";\n cmdLineDescs.commands[\"--server\"] = \"Start Tundra server\";\n cmdLineDescs.commands[\"--port\"] = \"Start server in the specified port\"; \/\/ TundraLogicModule\n cmdLineDescs.commands[\"--protocol\"] = \"Start server with the specified protocol. Options: '--protocol tcp' and '--protocol udp'. Defaults to tcp if no protocol is spesified.\"; \/\/ KristalliProtocolModule\n cmdLineDescs.commands[\"--fpslimit\"] = \"Specifies the fps cap to use in rendering. Default: 60. Pass in 0 to disable\"; \/\/ OgreRenderingModule\n cmdLineDescs.commands[\"--run\"] = \"Run script on startup\"; \/\/ JavaScriptModule\n cmdLineDescs.commands[\"--file\"] = \"Load scene on startup. Accepts absolute and relative paths, local:\/\/ and http:\/\/ are accepted and fetched via the AssetAPI.\"; \/\/ TundraLogicModule & AssetModule\n cmdLineDescs.commands[\"--storage\"] = \"Adds the given directory as a local storage directory on startup\"; \/\/ AssetModule\n cmdLineDescs.commands[\"--config\"] = \"Specifies the startup configration file to use\"; \/\/ Framework\n cmdLineDescs.commands[\"--login\"] = \"Automatically login to server using provided data. Url syntax: {tundra|http|https}:\/\/host[:port]\/?username=x[&password=y&avatarurl=z&protocol={udp|tcp}]. Minimum information needed to try a connection in the url are host and username\";\n cmdLineDescs[\"--clear-asset-cache\"] = \"At the start of Tundra, remove all data and metadata files from asset cache.\";\n\n if (HasCommandLineParameter(\"--help\"))\n {\n std::cout << \"Supported command line arguments: \" << std::endl;\n cmdLineDescs.Print();\n Exit();\n }\n else\n {\n if (HasCommandLineParameter(\"--headless\"))\n headless_ = true;\n#ifdef PROFILING\n profiler = new Profiler();\n PROFILE(FW_Startup);\n#endif\n \/\/ Create ConfigAPI, pass application data and prepare data folder.\n config = new ConfigAPI(this);\n config->PrepareDataFolder(\"configuration\");\n\n \/\/ Create QApplication\n application = new Application(this, argc_, argv_); \n\n \/\/ Create core APIs\n frame = new FrameAPI(this);\n scene = new SceneAPI(this);\n asset = new AssetAPI(this, headless_);\n asset->OpenAssetCache(Application::UserDataDirectory() + QDir::separator() + \"assetcache\");\n ui = new UiAPI(this);\n audio = new AudioAPI(this, asset); \/\/ AudioAPI depends on the AssetAPI, so must be loaded after it.\n input = new InputAPI(this);\n plugin = new PluginAPI(this);\n console = new ConsoleAPI(this);\n console->RegisterCommand(\"exit\", \"Shuts down gracefully.\", this, SLOT(Exit()));\n\n \/\/ Initialize SceneAPI.\n scene->Initialise();\n\n RegisterDynamicObject(\"ui\", ui);\n RegisterDynamicObject(\"frame\", frame);\n RegisterDynamicObject(\"input\", input);\n RegisterDynamicObject(\"console\", console);\n RegisterDynamicObject(\"asset\", asset);\n RegisterDynamicObject(\"audio\", audio);\n RegisterDynamicObject(\"application\", application);\n RegisterDynamicObject(\"apiversion\", apiVersionInfo);\n RegisterDynamicObject(\"applicationversion\", applicationVersionInfo);\n }\n}\n\nFramework::~Framework()\n{\n SAFE_DELETE(input);\n SAFE_DELETE(asset);\n SAFE_DELETE(audio);\n SAFE_DELETE(plugin);\n#ifdef PROFILING\n \/\/\/ \\todo Deleting the profiler currently causes a crash, therefore disabled\n \/\/SAFE_DELETE(profiler);\n#endif\n SAFE_DELETE(console);\n SAFE_DELETE(scene);\n SAFE_DELETE(frame);\n SAFE_DELETE(ui);\n\n SAFE_DELETE(apiVersionInfo);\n SAFE_DELETE(applicationVersionInfo);\n\n \/\/ This delete must be the last one in Framework since application derives QApplication.\n \/\/ When we delete QApplication, we must have ensured that all QObjects have been deleted.\n \/\/\/ \\bug Framework is itself a QObject and we should delete application only after Framework has been deleted. A refactor is required.\n delete application;\n}\n\nvoid Framework::ProcessOneFrame()\n{\n if (exit_signal_ == true)\n return; \/\/ We've accidentally ended up to update a frame, but we're actually quitting.\n\n PROFILE(Framework_ProcessOneFrame);\n\n static tick_t clock_freq;\n static tick_t last_clocktime;\n\n if (!last_clocktime)\n last_clocktime = GetCurrentClockTime();\n\n if (!clock_freq)\n clock_freq = GetCurrentClockFreq();\n\n tick_t curr_clocktime = GetCurrentClockTime();\n double frametime = ((double)curr_clocktime - (double)last_clocktime) \/ (double) clock_freq;\n last_clocktime = curr_clocktime;\n\n for(size_t i = 0; i < modules.size(); ++i)\n {\n try\n {\n#ifdef PROFILING\n ProfilerSection ps((\"Module_\" + modules[i]->Name() + \"_Update\").c_str());\n#endif\n modules[i]->Update(frametime);\n }\n catch(const std::exception &e)\n {\n std::cout << \"ProcessOneFrame caught an exception while updating module \" << modules[i]->Name()\n << \": \" << (e.what() ? e.what() : \"(null)\") << std::endl;\n LogError(std::string(\"ProcessOneFrame caught an exception while updating module \" + modules[i]->Name()\n + \": \" + (e.what() ? e.what() : \"(null)\")));\n }\n catch(...)\n {\n std::cout << \"ProcessOneFrame caught an unknown exception while updating module \" << modules[i]->Name() << std::endl;\n LogError(std::string(\"ProcessOneFrame caught an unknown exception while updating module \" + modules[i]->Name()));\n }\n }\n\n asset->Update(frametime);\n input->Update(frametime);\n audio->Update(frametime);\n console->Update(frametime);\n frame->Update(frametime);\n\n if (renderer)\n renderer->Render(frametime);\n}\n\nvoid Framework::Go()\n{\n \/\/ Check if we were never supposed to run\n if (exit_signal_)\n return;\n \n srand(time(0));\n\n plugin->LoadPluginsFromXML(plugin->ConfigurationFile());\n\n for(size_t i = 0; i < modules.size(); ++i)\n {\n LogDebug(\"Initializing module \" + modules[i]->Name());\n modules[i]->Initialize();\n }\n\n \/\/ Run our QApplication subclass.\n application->Go();\n\n \/\/ Qt main loop execution has ended, we are exiting.\n exit_signal_ = true;\n\n for(size_t i = 0; i < modules.size(); ++i)\n {\n LogDebug(\"Uninitializing module \" + modules[i]->Name());\n modules[i]->Uninitialize();\n }\n\n \/\/ Deinitialize all core APIs.\n scene->Reset();\n asset->Reset();\n console->Reset();\n frame->Reset();\n input->SaveKeyBindingsToFile();\n input->Reset();\n audio->Reset();\n\n for(size_t i = 0; i < modules.size(); ++i)\n {\n LogDebug(\"Unloading module \" + modules[i]->Name());\n modules[i]->Unload();\n }\n\n \/\/ Actually unload all DLLs from memory.\n modules.clear();\n plugin->UnloadPlugins();\n}\n\nvoid Framework::Exit()\n{\n exit_signal_ = true;\n if (application)\n application->AboutToExit();\n}\n\nvoid Framework::ForceExit()\n{\n exit_signal_ = true;\n if (application)\n application->quit();\n}\n\nvoid Framework::CancelExit()\n{\n exit_signal_ = false;\n\n \/\/ Our main loop is stopped when we are exiting,\n \/\/ we need to start it back up again if something canceled the exit.\n if (application)\n application->UpdateFrame();\n}\n\nApplication *Framework::App() const\n{\n return application;\n}\n\n#ifdef PROFILING\nProfiler *Framework::GetProfiler() const\n{\n return profiler;\n}\n#endif\n\nFrameAPI *Framework::Frame() const\n{\n return frame;\n}\n\nInputAPI *Framework::Input() const\n{\n return input;\n}\n\nUiAPI *Framework::Ui() const\n{\n return ui;\n}\n\nConsoleAPI *Framework::Console() const\n{\n return console;\n}\n\nAudioAPI *Framework::Audio() const\n{\n return audio;\n}\n\nAssetAPI *Framework::Asset() const\n{\n return asset;\n}\n\nSceneAPI *Framework::Scene() const\n{\n return scene;\n}\n\nConfigAPI *Framework::Config() const\n{\n return config;\n}\n\/*\nConnectionAPI *Framework::Connection() const\n{\n return connection;\n}\n\nServerAPI *Framework::Server() const\n{\n return server;\n}\n*\/\nPluginAPI *Framework::Plugins() const\n{\n return plugin;\n}\n\nIRenderer *Framework::Renderer() const\n{\n return renderer;\n}\n\nApiVersionInfo *Framework::ApiVersion() const\n{\n return apiVersionInfo;\n}\n\nApplicationVersionInfo *Framework::ApplicationVersion() const\n{\n return applicationVersionInfo; \n}\n\nvoid Framework::RegisterRenderer(IRenderer *renderer_)\n{\n renderer = renderer_;\n}\n\nvoid Framework::RegisterModule(IModule *module)\n{\n module->SetFramework(this);\n modules.push_back(boost::shared_ptr<IModule>(module));\n module->Load();\n}\n\nIModule *Framework::GetModuleByName(const QString &name) const\n{\n for(size_t i = 0; i < modules.size(); ++i)\n if (modules[i]->Name() == name.toStdString())\n return modules[i].get();\n\n return 0;\n}\n\nbool Framework::RegisterDynamicObject(QString name, QObject *object)\n{\n if (name.length() == 0 || !object)\n return false;\n\n \/\/ We never override a property if it already exists.\n if (property(name.toStdString().c_str()).isValid())\n return false;\n\n setProperty(name.toStdString().c_str(), QVariant::fromValue<QObject*>(object));\n\n return true;\n}\n\nbool Framework::HasCommandLineParameter(const QString &value) const\n{\n for(int i = 0; i < argc_; ++i)\n if (QString(argv_[i]) == value)\n return true;\n return false;\n}\n\nQStringList Framework::CommandLineParameters(const QString &key) const\n{\n QStringList ret;\n for(int i = 0; i < argc_; ++i)\n if (QString(argv_[i]) == key && i+1 < argc_ && !QString(argv_[i+1]).startsWith(\"--\"))\n ret.append(argv_[++i]);\n return ret;\n}\n\n<commit_msg>Update todo-text.<commit_after>\/\/ For conditions of distribution and use, see copyright notice in license.txt\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n\n#include \"Framework.h\"\n#include \"Profiler.h\"\n#include \"IRenderer.h\"\n#include \"CoreException.h\"\n#include \"Application.h\"\n#include \"VersionInfo.h\"\n#include \"ConfigAPI.h\"\n#include \"PluginAPI.h\"\n#include \"LoggingFunctions.h\"\n#include \"IModule.h\"\n#include \"FrameAPI.h\"\n\n#include \"InputAPI.h\"\n#include \"AssetAPI.h\"\n#include \"AudioAPI.h\"\n#include \"ConsoleAPI.h\"\n#include \"SceneAPI.h\"\n#include \"UiAPI.h\"\n#include \"UiMainWindow.h\"\n\n#include <iostream>\n#include <QDir>\n\n#include \"MemoryLeakCheck.h\"\n\n\/\/\/ Temporary utility structure for strong supported command line parameters and their descriptions.\nstruct CommandLineParameterMap\n{\n \/\/\/ Prints the structure to std::cout.\n void Print() const\n {\n QMap<QString, QString>::const_iterator it = commands.begin();\n while(it != commands.end())\n {\n int charIdx = 0;\n const int treshold = 15;\n const int maxLineWidth = 80; \/\/\/< @todo 80 on Windows, but how bout on other platforms?\n int cmdLength = it.key().length();\n std::cout << it.key().toStdString();\n if (cmdLength >= treshold)\n {\n std::cout << std::endl;\n for(charIdx = 0; charIdx < treshold ; ++charIdx)\n std::cout << \" \";\n }\n else\n for(charIdx = cmdLength; charIdx < treshold ; ++charIdx)\n std::cout << \" \";\n\n for(QString::const_iterator descIter = it.value().begin(); descIter != it.value().end(); ++descIter)\n {\n std::cout << (*descIter).toAscii();\n ++charIdx;\n if (charIdx >= maxLineWidth)\n {\n charIdx = 0;\n for(charIdx; charIdx < treshold ; ++charIdx)\n std::cout << \" \";\n }\n }\n\n std::cout << std::endl;\n ++it;\n }\n }\n\n QMap<QString, QString> commands;\n};\n\nFramework *Framework::instance = 0;\n\nFramework::Framework(int argc, char** argv) :\n exit_signal_(false),\n argc_(argc),\n argv_(argv),\n headless_(false),\n application(0),\n frame(0),\n console(0),\n scene(0),\n input(0),\n asset(0),\n audio(0),\n plugin(0),\n config(0),\n ui(0),\n#ifdef PROFILING\n profiler(0),\n#endif\n renderer(0),\n apiVersionInfo(0),\n applicationVersionInfo(0)\n{ \/\/ Remember this Framework instance in a static pointer. Note that this does not help visibility for external DLL code linking to Framework.\n instance = this;\n\n \/\/ Api\/Application name and version. Can be accessed via ApiVersionInfo() and ApplicationVersionInfo().\n \/\/\/ @note Modify these values when you are making a custom Tundra. Also the version needs to be changed here on releases.\n apiVersionInfo = new ApiVersionInfo(2, 0, 0, 0);\n applicationVersionInfo = new ApplicationVersionInfo(2, 0, 0, 0, \"realXtend\", \"Tundra\");\n\n CommandLineParameterMap cmdLineDescs;\n \/\/\/\\todo Make it possible for modules to know when \"--help\" command was issued and list the command line parameters they support.\n \/\/\/\\todo Remove non-Framework parameters from the list below.\n cmdLineDescs.commands[\"--help\"] = \"Produce help message\"; \/\/ Framework\n cmdLineDescs.commands[\"--headless\"] = \"Run in headless mode without any windows or rendering\"; \/\/ Framework & OgreRenderingModule\n cmdLineDescs.commands[\"--disablerunonload\"] = \"Do not start script applications (EC_Script's with applicationName defined) automatically\"; \/\/JavascriptModule\n cmdLineDescs.commands[\"--server\"] = \"Start Tundra server\"; \/\/ TundraLogicModule\n cmdLineDescs.commands[\"--port\"] = \"Start server in the specified port\"; \/\/ TundraLogicModule\n cmdLineDescs.commands[\"--protocol\"] = \"Start server with the specified protocol. Options: '--protocol tcp' and '--protocol udp'. Defaults to tcp if no protocol is spesified.\"; \/\/ KristalliProtocolModule\n cmdLineDescs.commands[\"--fpslimit\"] = \"Specifies the fps cap to use in rendering. Default: 60. Pass in 0 to disable\"; \/\/ OgreRenderingModule\n cmdLineDescs.commands[\"--run\"] = \"Run script on startup\"; \/\/ JavaScriptModule\n cmdLineDescs.commands[\"--file\"] = \"Load scene on startup. Accepts absolute and relative paths, local:\/\/ and http:\/\/ are accepted and fetched via the AssetAPI.\"; \/\/ TundraLogicModule & AssetModule\n cmdLineDescs.commands[\"--storage\"] = \"Adds the given directory as a local storage directory on startup\"; \/\/ AssetModule\n cmdLineDescs.commands[\"--config\"] = \"Specifies the startup configration file to use\"; \/\/ Framework\n cmdLineDescs.commands[\"--login\"] = \"Automatically login to server using provided data. Url syntax: {tundra|http|https}:\/\/host[:port]\/?username=x[&password=y&avatarurl=z&protocol={udp|tcp}]. Minimum information needed to try a connection in the url are host and username\";\n cmdLineDescs[\"--clear-asset-cache\"] = \"At the start of Tundra, remove all data and metadata files from asset cache.\";\n\n if (HasCommandLineParameter(\"--help\"))\n {\n std::cout << \"Supported command line arguments: \" << std::endl;\n cmdLineDescs.Print();\n Exit();\n }\n else\n {\n if (HasCommandLineParameter(\"--headless\"))\n headless_ = true;\n#ifdef PROFILING\n profiler = new Profiler();\n PROFILE(FW_Startup);\n#endif\n \/\/ Create ConfigAPI, pass application data and prepare data folder.\n config = new ConfigAPI(this);\n config->PrepareDataFolder(\"configuration\");\n\n \/\/ Create QApplication\n application = new Application(this, argc_, argv_); \n\n \/\/ Create core APIs\n frame = new FrameAPI(this);\n scene = new SceneAPI(this);\n asset = new AssetAPI(this, headless_);\n asset->OpenAssetCache(Application::UserDataDirectory() + QDir::separator() + \"assetcache\");\n ui = new UiAPI(this);\n audio = new AudioAPI(this, asset); \/\/ AudioAPI depends on the AssetAPI, so must be loaded after it.\n input = new InputAPI(this);\n plugin = new PluginAPI(this);\n console = new ConsoleAPI(this);\n console->RegisterCommand(\"exit\", \"Shuts down gracefully.\", this, SLOT(Exit()));\n\n \/\/ Initialize SceneAPI.\n scene->Initialise();\n\n RegisterDynamicObject(\"ui\", ui);\n RegisterDynamicObject(\"frame\", frame);\n RegisterDynamicObject(\"input\", input);\n RegisterDynamicObject(\"console\", console);\n RegisterDynamicObject(\"asset\", asset);\n RegisterDynamicObject(\"audio\", audio);\n RegisterDynamicObject(\"application\", application);\n RegisterDynamicObject(\"apiversion\", apiVersionInfo);\n RegisterDynamicObject(\"applicationversion\", applicationVersionInfo);\n }\n}\n\nFramework::~Framework()\n{\n SAFE_DELETE(input);\n SAFE_DELETE(asset);\n SAFE_DELETE(audio);\n SAFE_DELETE(plugin);\n#ifdef PROFILING\n \/\/\/ \\todo Deleting the profiler currently causes a crash, therefore disabled\n \/\/SAFE_DELETE(profiler);\n#endif\n SAFE_DELETE(console);\n SAFE_DELETE(scene);\n SAFE_DELETE(frame);\n SAFE_DELETE(ui);\n\n SAFE_DELETE(apiVersionInfo);\n SAFE_DELETE(applicationVersionInfo);\n\n \/\/ This delete must be the last one in Framework since application derives QApplication.\n \/\/ When we delete QApplication, we must have ensured that all QObjects have been deleted.\n \/\/\/ \\bug Framework is itself a QObject and we should delete application only after Framework has been deleted. A refactor is required.\n delete application;\n}\n\nvoid Framework::ProcessOneFrame()\n{\n if (exit_signal_ == true)\n return; \/\/ We've accidentally ended up to update a frame, but we're actually quitting.\n\n PROFILE(Framework_ProcessOneFrame);\n\n static tick_t clock_freq;\n static tick_t last_clocktime;\n\n if (!last_clocktime)\n last_clocktime = GetCurrentClockTime();\n\n if (!clock_freq)\n clock_freq = GetCurrentClockFreq();\n\n tick_t curr_clocktime = GetCurrentClockTime();\n double frametime = ((double)curr_clocktime - (double)last_clocktime) \/ (double) clock_freq;\n last_clocktime = curr_clocktime;\n\n for(size_t i = 0; i < modules.size(); ++i)\n {\n try\n {\n#ifdef PROFILING\n ProfilerSection ps((\"Module_\" + modules[i]->Name() + \"_Update\").c_str());\n#endif\n modules[i]->Update(frametime);\n }\n catch(const std::exception &e)\n {\n std::cout << \"ProcessOneFrame caught an exception while updating module \" << modules[i]->Name()\n << \": \" << (e.what() ? e.what() : \"(null)\") << std::endl;\n LogError(std::string(\"ProcessOneFrame caught an exception while updating module \" + modules[i]->Name()\n + \": \" + (e.what() ? e.what() : \"(null)\")));\n }\n catch(...)\n {\n std::cout << \"ProcessOneFrame caught an unknown exception while updating module \" << modules[i]->Name() << std::endl;\n LogError(std::string(\"ProcessOneFrame caught an unknown exception while updating module \" + modules[i]->Name()));\n }\n }\n\n asset->Update(frametime);\n input->Update(frametime);\n audio->Update(frametime);\n console->Update(frametime);\n frame->Update(frametime);\n\n if (renderer)\n renderer->Render(frametime);\n}\n\nvoid Framework::Go()\n{\n \/\/ Check if we were never supposed to run\n if (exit_signal_)\n return;\n \n srand(time(0));\n\n plugin->LoadPluginsFromXML(plugin->ConfigurationFile());\n\n for(size_t i = 0; i < modules.size(); ++i)\n {\n LogDebug(\"Initializing module \" + modules[i]->Name());\n modules[i]->Initialize();\n }\n\n \/\/ Run our QApplication subclass.\n application->Go();\n\n \/\/ Qt main loop execution has ended, we are exiting.\n exit_signal_ = true;\n\n for(size_t i = 0; i < modules.size(); ++i)\n {\n LogDebug(\"Uninitializing module \" + modules[i]->Name());\n modules[i]->Uninitialize();\n }\n\n \/\/ Deinitialize all core APIs.\n scene->Reset();\n asset->Reset();\n console->Reset();\n frame->Reset();\n input->SaveKeyBindingsToFile();\n input->Reset();\n audio->Reset();\n\n for(size_t i = 0; i < modules.size(); ++i)\n {\n LogDebug(\"Unloading module \" + modules[i]->Name());\n modules[i]->Unload();\n }\n\n \/\/ Actually unload all DLLs from memory.\n modules.clear();\n plugin->UnloadPlugins();\n}\n\nvoid Framework::Exit()\n{\n exit_signal_ = true;\n if (application)\n application->AboutToExit();\n}\n\nvoid Framework::ForceExit()\n{\n exit_signal_ = true;\n if (application)\n application->quit();\n}\n\nvoid Framework::CancelExit()\n{\n exit_signal_ = false;\n\n \/\/ Our main loop is stopped when we are exiting,\n \/\/ we need to start it back up again if something canceled the exit.\n if (application)\n application->UpdateFrame();\n}\n\nApplication *Framework::App() const\n{\n return application;\n}\n\n#ifdef PROFILING\nProfiler *Framework::GetProfiler() const\n{\n return profiler;\n}\n#endif\n\nFrameAPI *Framework::Frame() const\n{\n return frame;\n}\n\nInputAPI *Framework::Input() const\n{\n return input;\n}\n\nUiAPI *Framework::Ui() const\n{\n return ui;\n}\n\nConsoleAPI *Framework::Console() const\n{\n return console;\n}\n\nAudioAPI *Framework::Audio() const\n{\n return audio;\n}\n\nAssetAPI *Framework::Asset() const\n{\n return asset;\n}\n\nSceneAPI *Framework::Scene() const\n{\n return scene;\n}\n\nConfigAPI *Framework::Config() const\n{\n return config;\n}\n\/*\nConnectionAPI *Framework::Connection() const\n{\n return connection;\n}\n\nServerAPI *Framework::Server() const\n{\n return server;\n}\n*\/\nPluginAPI *Framework::Plugins() const\n{\n return plugin;\n}\n\nIRenderer *Framework::Renderer() const\n{\n return renderer;\n}\n\nApiVersionInfo *Framework::ApiVersion() const\n{\n return apiVersionInfo;\n}\n\nApplicationVersionInfo *Framework::ApplicationVersion() const\n{\n return applicationVersionInfo; \n}\n\nvoid Framework::RegisterRenderer(IRenderer *renderer_)\n{\n renderer = renderer_;\n}\n\nvoid Framework::RegisterModule(IModule *module)\n{\n module->SetFramework(this);\n modules.push_back(boost::shared_ptr<IModule>(module));\n module->Load();\n}\n\nIModule *Framework::GetModuleByName(const QString &name) const\n{\n for(size_t i = 0; i < modules.size(); ++i)\n if (modules[i]->Name() == name.toStdString())\n return modules[i].get();\n\n return 0;\n}\n\nbool Framework::RegisterDynamicObject(QString name, QObject *object)\n{\n if (name.length() == 0 || !object)\n return false;\n\n \/\/ We never override a property if it already exists.\n if (property(name.toStdString().c_str()).isValid())\n return false;\n\n setProperty(name.toStdString().c_str(), QVariant::fromValue<QObject*>(object));\n\n return true;\n}\n\nbool Framework::HasCommandLineParameter(const QString &value) const\n{\n for(int i = 0; i < argc_; ++i)\n if (QString(argv_[i]) == value)\n return true;\n return false;\n}\n\nQStringList Framework::CommandLineParameters(const QString &key) const\n{\n QStringList ret;\n for(int i = 0; i < argc_; ++i)\n if (QString(argv_[i]) == key && i+1 < argc_ && !QString(argv_[i+1]).startsWith(\"--\"))\n ret.append(argv_[++i]);\n return ret;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n main.cpp - description\n -------------------\n begin : Wed Dec 26 03:12:10 CLST 2001\n copyright : (C) 2001 by Duncan Mac-Vicar Prett\n email : duncan@kde.org\n ***************************************************************************\/\n\n\/***************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include <kcmdlineargs.h>\n#include <kaboutdata.h>\n#include <klocale.h>\n#include \"kopete.h\"\n\nstatic const char *description =\n\tI18N_NOOP(\"Kopete, the KDE Instant Messenger\");\n\n#define KOPETE_VERSION \"0.4.1\"\n\t\nstatic KCmdLineOptions options[] =\n{\n { 0, 0, 0 }\n};\n\nint main(int argc, char *argv[])\n{\n\tKAboutData aboutData( \"kopete\", I18N_NOOP(\"Kopete\"),\n\t\tKOPETE_VERSION, description, KAboutData::License_GPL,\n\t\t\"(c) 2001,2002, Duncan Mac-Vicar Prett\\n(c) 2002, The Kopete Development Team\", \"kopete-devel@kde.org\", \"http:\/\/kopete.kde.org\");\n\n\taboutData.addAuthor ( \"Duncan Mac-Vicar Prett\", I18N_NOOP(\"Original author, core developer\"), \"duncan@kde.org\", \"http:\/\/www.mac-vicar.com\" );\n\taboutData.addAuthor ( \"Nick Betcher\", I18N_NOOP(\"Core developer, fastest plugin developer on earth.\"), \"nbetcher@usinternet.com\", \"http:\/\/www.kdedevelopers.net\" );\n\taboutData.addAuthor ( \"Ryan Cumming\", I18N_NOOP(\"Core developer\"), \"bodnar42@phalynx.dhs.org\" );\n\taboutData.addAuthor ( \"Martijn Klingens\", I18N_NOOP(\"Core developer\"), \"klingens@kde.org\" );\n\taboutData.addAuthor ( \"Richard Stellingwerff\", I18N_NOOP(\"Developer\"), \"remenic@linuxfromscratch.org\");\n\taboutData.addAuthor ( \"Daniel Stone\", I18N_NOOP(\"Core developer, Jabber plugin\"), \"dstone@kde.org\", \"http:\/\/raging.dropbear.id.au\/daniel\/\");\n aboutData.addAuthor ( \"Hendrik vom Lehn\", I18N_NOOP(\"Developer\"), \"hennevl@hennevl.de\", \"http:\/\/www.hennevl.de\");\n\taboutData.addAuthor ( \"Andres Krapf\", I18N_NOOP(\"Random hacks and bugfixes\"), \"dae@chez.com\" );\n\n\taboutData.addCredit ( \"Herwin Jan Steehouwer\", I18N_NOOP(\"KxEngine ICQ code\") );\n\taboutData.addCredit ( \"Olaf Lueg\", I18N_NOOP(\"Kmerlin MSN code\") );\n\taboutData.addCredit ( \"Neil Stevens\", I18N_NOOP(\"TAim engine AIM code\") );\n\taboutData.addCredit ( \"Justin Karneges\", I18N_NOOP(\"Psi Jabber code\") );\n\n\tKCmdLineArgs::init( argc, argv, &aboutData );\n\tKCmdLineArgs::addCmdLineOptions( options ); \/\/ Add our own options.\n\tKUniqueApplication::addCmdLineOptions();\n\n\tKopete kopete;\n\tkopete.exec();\n}\n<commit_msg>Added mETz to credits<commit_after>\/***************************************************************************\n main.cpp - description\n -------------------\n begin : Wed Dec 26 03:12:10 CLST 2001\n copyright : (C) 2001 by Duncan Mac-Vicar Prett\n email : duncan@kde.org\n ***************************************************************************\/\n\n\/***************************************************************************\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include <kcmdlineargs.h>\n#include <kaboutdata.h>\n#include <klocale.h>\n#include \"kopete.h\"\n\nstatic const char *description =\n\tI18N_NOOP(\"Kopete, the KDE Instant Messenger\");\n\n#define KOPETE_VERSION \"0.4.1\"\n\t\nstatic KCmdLineOptions options[] =\n{\n { 0, 0, 0 }\n};\n\nint main(int argc, char *argv[])\n{\n\tKAboutData aboutData( \"kopete\", I18N_NOOP(\"Kopete\"),\n\t\tKOPETE_VERSION, description, KAboutData::License_GPL,\n\t\t\"(c) 2001,2002, Duncan Mac-Vicar Prett\\n(c) 2002, The Kopete Development Team\", \"kopete-devel@kde.org\", \"http:\/\/kopete.kde.org\");\n\n\taboutData.addAuthor ( \"Duncan Mac-Vicar Prett\", I18N_NOOP(\"Original author, core developer\"), \"duncan@kde.org\", \"http:\/\/www.mac-vicar.com\" );\n\taboutData.addAuthor ( \"Nick Betcher\", I18N_NOOP(\"Core developer, fastest plugin developer on earth.\"), \"nbetcher@usinternet.com\", \"http:\/\/www.kdedevelopers.net\" );\n\taboutData.addAuthor ( \"Ryan Cumming\", I18N_NOOP(\"Core developer\"), \"bodnar42@phalynx.dhs.org\" );\n\taboutData.addAuthor ( \"Martijn Klingens\", I18N_NOOP(\"Core developer\"), \"klingens@kde.org\" );\n\taboutData.addAuthor ( \"Richard Stellingwerff\", I18N_NOOP(\"Developer\"), \"remenic@linuxfromscratch.org\");\n\taboutData.addAuthor ( \"Daniel Stone\", I18N_NOOP(\"Core developer, Jabber plugin\"), \"dstone@kde.org\", \"http:\/\/raging.dropbear.id.au\/daniel\/\");\n aboutData.addAuthor ( \"Hendrik vom Lehn\", I18N_NOOP(\"Developer\"), \"hennevl@hennevl.de\", \"http:\/\/www.hennevl.de\");\n aboutData.addAuthor ( \"Stefan Gehn\", I18N_NOOP(\"Developer\"), \"sgehn@gmx.net\", \"http:\/\/metz81.mine.nu\" );\n\taboutData.addAuthor ( \"Andres Krapf\", I18N_NOOP(\"Random hacks and bugfixes\"), \"dae@chez.com\" );\n\n\taboutData.addCredit ( \"Herwin Jan Steehouwer\", I18N_NOOP(\"KxEngine ICQ code\") );\n\taboutData.addCredit ( \"Olaf Lueg\", I18N_NOOP(\"Kmerlin MSN code\") );\n\taboutData.addCredit ( \"Neil Stevens\", I18N_NOOP(\"TAim engine AIM code\") );\n\taboutData.addCredit ( \"Justin Karneges\", I18N_NOOP(\"Psi Jabber code\") );\n\n\tKCmdLineArgs::init( argc, argv, &aboutData );\n\tKCmdLineArgs::addCmdLineOptions( options ); \/\/ Add our own options.\n\tKUniqueApplication::addCmdLineOptions();\n\n\tKopete kopete;\n\tkopete.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>\n\n This file is part of Magnum.\n\n Magnum 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 Magnum 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*\/\n\n#include \"ShapeRenderer.h\"\n\n#include \"ResourceManager.h\"\n#include \"Physics\/AbstractShape.h\"\n#include \"Physics\/AxisAlignedBox.h\"\n#include \"Physics\/Box.h\"\n#include \"Physics\/ObjectShape.h\"\n#include \"Physics\/ShapeGroup.h\"\n#include \"SceneGraph\/AbstractCamera.h\"\n\n#include \"Implementation\/AxisAlignedBoxRenderer.h\"\n#include \"Implementation\/BoxRenderer.h\"\n\nnamespace Magnum { namespace DebugTools {\n\n#ifndef DOXYGEN_GENERATING_OUTPUT\nnamespace Implementation {\n\ntemplate<> void createDebugMesh(ShapeRenderer<2>* renderer, Physics::AbstractShape<2>* shape) {\n switch(shape->type()) {\n case Physics::AbstractShape2D::Type::AxisAlignedBox:\n renderer->renderers.push_back(new Implementation::AxisAlignedBoxRenderer<2>(*static_cast<Physics::AxisAlignedBox2D*>(shape)));\n case Physics::AbstractShape2D::Type::Box:\n renderer->renderers.push_back(new Implementation::BoxRenderer<2>(*static_cast<Physics::Box2D*>(shape)));\n break;\n case Physics::AbstractShape2D::Type::ShapeGroup: {\n Physics::ShapeGroup2D* group = static_cast<Physics::ShapeGroup2D*>(shape);\n if(group->first()) createDebugMesh(renderer, group->first());\n if(group->second()) createDebugMesh(renderer, group->second());\n } break;\n default:\n Warning() << \"DebugTools::ShapeRenderer2D::createShapeRenderer(): type\" << shape->type() << \"not implemented\";\n }\n}\n\ntemplate<> void createDebugMesh(ShapeRenderer<3>* renderer, Physics::AbstractShape<3>* shape) {\n switch(shape->type()) {\n case Physics::AbstractShape3D::Type::AxisAlignedBox:\n renderer->renderers.push_back(new Implementation::AxisAlignedBoxRenderer<3>(*static_cast<Physics::AxisAlignedBox3D*>(shape)));\n case Physics::AbstractShape3D::Type::Box:\n renderer->renderers.push_back(new Implementation::BoxRenderer<3>(*static_cast<Physics::Box3D*>(shape)));\n break;\n case Physics::AbstractShape3D::Type::ShapeGroup: {\n Physics::ShapeGroup3D* group = static_cast<Physics::ShapeGroup3D*>(shape);\n if(group->first()) createDebugMesh(renderer, group->first());\n if(group->second()) createDebugMesh(renderer, group->second());\n } break;\n default:\n Warning() << \"DebugTools::ShapeRenderer3D::createShapeRenderer(): type\" << shape->type() << \"not implemented\";\n }\n}\n\n}\n#endif\n\ntemplate<std::uint8_t dimensions> ShapeRenderer<dimensions>::ShapeRenderer(Physics::ObjectShape<dimensions>* shape, ResourceKey options, SceneGraph::DrawableGroup<dimensions>* drawables): SceneGraph::Drawable<dimensions>(shape->object(), drawables), options(ResourceManager::instance()->get<ShapeRendererOptions>(options)) {\n CORRADE_ASSERT(shape->shape() != nullptr, \"DebugTools::ShapeRenderer: cannot create renderer for empty shape\", );\n Implementation::createDebugMesh(this, shape->shape());\n}\n\ntemplate<std::uint8_t dimensions> ShapeRenderer<dimensions>::~ShapeRenderer() {\n for(auto i: renderers) delete i;\n}\n\ntemplate<std::uint8_t dimensions> void ShapeRenderer<dimensions>::draw(const typename DimensionTraits<dimensions>::MatrixType&, SceneGraph::AbstractCamera<dimensions>* camera) {\n typename DimensionTraits<dimensions>::MatrixType projectionMatrix = camera->projectionMatrix()*camera->cameraMatrix();\n for(auto i: renderers) i->draw(options, projectionMatrix);\n}\n\ntemplate class ShapeRenderer<2>;\ntemplate class ShapeRenderer<3>;\n\n}}\n<commit_msg>DebugTools: missing break in switch.<commit_after>\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>\n\n This file is part of Magnum.\n\n Magnum 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 Magnum 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*\/\n\n#include \"ShapeRenderer.h\"\n\n#include \"ResourceManager.h\"\n#include \"Physics\/AbstractShape.h\"\n#include \"Physics\/AxisAlignedBox.h\"\n#include \"Physics\/Box.h\"\n#include \"Physics\/ObjectShape.h\"\n#include \"Physics\/ShapeGroup.h\"\n#include \"SceneGraph\/AbstractCamera.h\"\n\n#include \"Implementation\/AxisAlignedBoxRenderer.h\"\n#include \"Implementation\/BoxRenderer.h\"\n\nnamespace Magnum { namespace DebugTools {\n\n#ifndef DOXYGEN_GENERATING_OUTPUT\nnamespace Implementation {\n\ntemplate<> void createDebugMesh(ShapeRenderer<2>* renderer, Physics::AbstractShape<2>* shape) {\n switch(shape->type()) {\n case Physics::AbstractShape2D::Type::AxisAlignedBox:\n renderer->renderers.push_back(new Implementation::AxisAlignedBoxRenderer<2>(*static_cast<Physics::AxisAlignedBox2D*>(shape)));\n break;\n case Physics::AbstractShape2D::Type::Box:\n renderer->renderers.push_back(new Implementation::BoxRenderer<2>(*static_cast<Physics::Box2D*>(shape)));\n break;\n case Physics::AbstractShape2D::Type::ShapeGroup: {\n Physics::ShapeGroup2D* group = static_cast<Physics::ShapeGroup2D*>(shape);\n if(group->first()) createDebugMesh(renderer, group->first());\n if(group->second()) createDebugMesh(renderer, group->second());\n } break;\n default:\n Warning() << \"DebugTools::ShapeRenderer2D::createShapeRenderer(): type\" << shape->type() << \"not implemented\";\n }\n}\n\ntemplate<> void createDebugMesh(ShapeRenderer<3>* renderer, Physics::AbstractShape<3>* shape) {\n switch(shape->type()) {\n case Physics::AbstractShape3D::Type::AxisAlignedBox:\n renderer->renderers.push_back(new Implementation::AxisAlignedBoxRenderer<3>(*static_cast<Physics::AxisAlignedBox3D*>(shape)));\n break;\n case Physics::AbstractShape3D::Type::Box:\n renderer->renderers.push_back(new Implementation::BoxRenderer<3>(*static_cast<Physics::Box3D*>(shape)));\n break;\n case Physics::AbstractShape3D::Type::ShapeGroup: {\n Physics::ShapeGroup3D* group = static_cast<Physics::ShapeGroup3D*>(shape);\n if(group->first()) createDebugMesh(renderer, group->first());\n if(group->second()) createDebugMesh(renderer, group->second());\n } break;\n default:\n Warning() << \"DebugTools::ShapeRenderer3D::createShapeRenderer(): type\" << shape->type() << \"not implemented\";\n }\n}\n\n}\n#endif\n\ntemplate<std::uint8_t dimensions> ShapeRenderer<dimensions>::ShapeRenderer(Physics::ObjectShape<dimensions>* shape, ResourceKey options, SceneGraph::DrawableGroup<dimensions>* drawables): SceneGraph::Drawable<dimensions>(shape->object(), drawables), options(ResourceManager::instance()->get<ShapeRendererOptions>(options)) {\n CORRADE_ASSERT(shape->shape() != nullptr, \"DebugTools::ShapeRenderer: cannot create renderer for empty shape\", );\n Implementation::createDebugMesh(this, shape->shape());\n}\n\ntemplate<std::uint8_t dimensions> ShapeRenderer<dimensions>::~ShapeRenderer() {\n for(auto i: renderers) delete i;\n}\n\ntemplate<std::uint8_t dimensions> void ShapeRenderer<dimensions>::draw(const typename DimensionTraits<dimensions>::MatrixType&, SceneGraph::AbstractCamera<dimensions>* camera) {\n typename DimensionTraits<dimensions>::MatrixType projectionMatrix = camera->projectionMatrix()*camera->cameraMatrix();\n for(auto i: renderers) i->draw(options, projectionMatrix);\n}\n\ntemplate class ShapeRenderer<2>;\ntemplate class ShapeRenderer<3>;\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/* Crash_Plugin - for licensing and copyright see license.txt *\/\n\n#include <StdAfx.h>\n\n#include <CPluginCrash.h>\n#include <Nodes\/G2FlowBaseNode.h>\n\nnamespace CrashPlugin\n{\n class CFlowCrashNode :\n public CFlowBaseNode<eNCT_Instanced>\n {\n enum EInputPorts\n {\n EIP_CRASH = 0,\n };\n\n public:\n virtual void GetMemoryUsage( ICrySizer* s ) const\n {\n s->Add( *this );\n }\n\n virtual IFlowNodePtr Clone( SActivationInfo* pActInfo )\n {\n return new CFlowCrashNode( pActInfo );\n }\n\n CFlowCrashNode( SActivationInfo* pActInfo )\n {\n\n }\n\n virtual void GetConfiguration( SFlowNodeConfig& config )\n {\n static const SInputPortConfig inputs[] =\n {\n InputPortConfig_Void( \"Crash\", _HELP( \"Crash Game\" ) ),\n {0},\n };\n\n config.pInputPorts = inputs;\n config.pOutputPorts = NULL;\n config.sDescription = _HELP( \" Crash Game\" );\n\n config.SetCategory( EFLN_APPROVED );\n }\n\n virtual void ProcessEvent( EFlowEvent evt, SActivationInfo* pActInfo )\n {\n switch ( evt )\n {\n case eFE_Activate:\n\n if ( IsPortActive( pActInfo, EIP_CRASH ) )\n {\n gPlugin->Crash();\n }\n\n break;\n }\n }\n };\n}\n\nREGISTER_FLOW_NODE_EX( \"Crash_Plugin:Crash\", CrashPlugin::CFlowCrashNode, CFlowCrashNode );\n<commit_msg>3.4.4 compatiblity<commit_after>\/* Crash_Plugin - for licensing and copyright see license.txt *\/\n\n#include <StdAfx.h>\n\n#include <CPluginCrash.h>\n#include <Nodes\/G2FlowBaseNode.h>\n\nnamespace CrashPlugin\n{\n class CFlowCrashNode :\n public CFlowBaseNode<eNCT_Instanced>\n {\n enum EInputPorts\n {\n EIP_CRASH = 0,\n };\n\n public:\n virtual void GetMemoryUsage( ICrySizer* s ) const\n {\n s->Add( *this );\n }\n\n virtual IFlowNodePtr Clone( SActivationInfo* pActInfo )\n {\n return new CFlowCrashNode( pActInfo );\n }\n\n CFlowCrashNode( SActivationInfo* pActInfo )\n {\n\n }\n\n virtual void GetConfiguration( SFlowNodeConfig& config )\n {\n static const SInputPortConfig inputs[] =\n {\n InputPortConfig_Void( \"Crash\", _HELP( \"Crash Game\" ) ),\n InputPortConfig_Null(),\n };\n\n config.pInputPorts = inputs;\n config.pOutputPorts = NULL;\n config.sDescription = _HELP( \" Crash Game\" );\n\n config.SetCategory( EFLN_APPROVED );\n }\n\n virtual void ProcessEvent( EFlowEvent evt, SActivationInfo* pActInfo )\n {\n switch ( evt )\n {\n case eFE_Activate:\n\n if ( IsPortActive( pActInfo, EIP_CRASH ) )\n {\n gPlugin->Crash();\n }\n\n break;\n }\n }\n };\n}\n\nREGISTER_FLOW_NODE_EX( \"Crash_Plugin:Crash\", CrashPlugin::CFlowCrashNode, CFlowCrashNode );\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\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 with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/filesystem.hpp\"\n#include \"boost\/algorithm\/string\/predicate.hpp\"\n\n#include \"IECore\/PreWorldRenderable.h\"\n#include \"IECore\/Camera.h\"\n#include \"IECore\/WorldBlock.h\"\n#include \"IECore\/Light.h\"\n#include \"IECore\/Shader.h\"\n#include \"IECore\/AttributeBlock.h\"\n#include \"IECore\/Display.h\"\n#include \"IECore\/TransformBlock.h\"\n#include \"IECore\/CoordinateSystem.h\"\n#include \"IECore\/ClippingPlane.h\"\n#include \"IECore\/VisibleRenderable.h\"\n\n#include \"Gaffer\/Context.h\"\n#include \"Gaffer\/Metadata.h\"\n\n#include \"GafferScene\/RendererAlgo.h\"\n#include \"GafferScene\/SceneProcedural.h\"\n#include \"GafferScene\/PathMatcherData.h\"\n#include \"GafferScene\/SceneAlgo.h\"\n\nusing namespace std;\nusing namespace Imath;\nusing namespace IECore;\nusing namespace Gaffer;\n\nnamespace GafferScene\n{\n\nvoid outputScene( const ScenePlug *scene, IECore::Renderer *renderer )\n{\n\tConstCompoundObjectPtr globals = scene->globalsPlug()->getValue();\n\toutputOptions( globals.get(), renderer );\n\toutputOutputs( globals.get(), renderer );\n\toutputCamera( scene, globals.get(), renderer );\n\t{\n\t\tWorldBlock world( renderer );\n\n\t\toutputGlobalAttributes( globals.get(), renderer );\n\t\toutputCoordinateSystems( scene, globals.get(), renderer );\n\t\toutputLights( scene, globals.get(), renderer );\n\n\t\tSceneProceduralPtr proc = new SceneProcedural( scene, Context::current() );\n\t\trenderer->procedural( proc );\n\t}\n}\n\nvoid outputOutputs( const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tCompoundObject::ObjectMap::const_iterator it, eIt;\n\tfor( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )\n\t{\n\t\tif( !boost::starts_with( it->first.c_str(), \"output:\" ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif( const Display *d = runTimeCast<Display>( it->second.get() ) )\n\t\t{\n\t\t\td->render( renderer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow IECore::Exception( \"Global \\\"\" + it->first.string() + \"\\\" is not an IECore::Display\" );\n\t\t}\n\t}\n}\n\nvoid outputOptions( const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tCompoundObject::ObjectMap::const_iterator it, eIt;\n\tfor( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )\n\t{\n\t\tif( !boost::starts_with( it->first.c_str(), \"option:\" ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif( const Data *d = runTimeCast<Data>( it->second.get() ) )\n\t\t{\n\t\t\trenderer->setOption( it->first.c_str() + 7, d );\n\t\t}\n\t\telse if( const PreWorldRenderable *r = runTimeCast<PreWorldRenderable>( it->second.get() ) )\n\t\t{\n\t\t\tr->render( renderer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow IECore::Exception( \"Global \\\"\" + it->first.string() + \"\\\" is not IECore::Data or an IECore::PreWorldRenderable\" );\n\t\t}\n\t}\n}\n\nvoid outputCameras( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tConstPathMatcherDataPtr cameraSetData = scene->set( \"__cameras\" );\n\tconst PathMatcher &cameraSet = cameraSetData->readable();\n\n\t\/\/ Output all the cameras, skipping the primary one - we need to output this\n\t\/\/ last, as that's how cortex determines the primary camera.\n\tScenePlug::ScenePath primaryCameraPath;\n\tif( const StringData *primaryCameraPathData = globals->member<StringData>( \"option:render:camera\" ) )\n\t{\n\t\tScenePlug::stringToPath( primaryCameraPathData->readable(), primaryCameraPath );\n\t}\n\n\tfor( PathMatcher::Iterator it = cameraSet.begin(), eIt = cameraSet.end(); it != eIt; ++it )\n\t{\n\t\tif( *it != primaryCameraPath )\n\t\t{\n\t\t\toutputCamera( scene, *it, globals, renderer );\n\t\t}\n\t}\n\n\t\/\/ Output the primary camera, or a default if it doesn't exist.\n\n\toutputCamera( scene, globals, renderer );\n\n}\n\nvoid outputCamera( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tIECore::CameraPtr camera = GafferScene::camera( scene, globals );\n\tcamera->render( renderer );\n}\n\nvoid outputCamera( const ScenePlug *scene, const ScenePlug::ScenePath &cameraPath, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tIECore::CameraPtr camera = GafferScene::camera( scene, cameraPath, globals );\n\tcamera->render( renderer );\n}\n\nvoid outputGlobalAttributes( const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tCompoundObject::ObjectMap::const_iterator it, eIt;\n\tfor( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )\n\t{\n\t\tif( !boost::starts_with( it->first.c_str(), \"attribute:\" ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif( const Data *d = runTimeCast<Data>( it->second.get() ) )\n\t\t{\n\t\t\trenderer->setAttribute( it->first.c_str() + 10, d );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow IECore::Exception( \"Global \\\"\" + it->first.string() + \"\\\" is not IECore::Data\" );\n\t\t}\n\t}\n}\n\nvoid outputLights( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tConstPathMatcherDataPtr lightSetData = scene->set( \"__lights\" );\n\tconst PathMatcher &lightSet = lightSetData->readable();\n\n\tfor( PathMatcher::Iterator it = lightSet.begin(), eIt = lightSet.end(); it != eIt; ++it )\n\t{\n\t\toutputLight( scene, *it, renderer );\n\t}\n}\n\nbool outputLight( const ScenePlug *scene, const ScenePlug::ScenePath &path, IECore::Renderer *renderer )\n{\n\tif( !visible( scene, path ) )\n\t{\n\t\t\/\/\/ \\todo Since both visible() and fullAttributes() perform similar work,\n\t\t\/\/\/ we may want to combine them into one query if we see this function\n\t\t\/\/\/ being a significant fraction of render time. Maybe something like\n\t\t\/\/\/ `fullAttributes( returnNullIfInvisible = true )`? It probably also\n\t\t\/\/\/ makes sense to migrate all the convenience functions from ScenePlug\n\t\t\/\/\/ into SceneAlgo.\n\t\treturn false;\n\t}\n\n\tConstCompoundObjectPtr attributes = scene->fullAttributes( path );\n\tConstObjectPtr object = scene->object( path );\n\tconst M44f transform = scene->fullTransform( path );\n\n\tstd::string lightHandle;\n\tScenePlug::pathToString( path, lightHandle );\n\n\t{\n\t\tAttributeBlock attributeBlock( renderer );\n\n\t\trenderer->setAttribute( \"name\", new StringData( lightHandle ) );\n\t\toutputAttributes( attributes.get(), renderer );\n\t\trenderer->concatTransform( transform );\n\n\n\t\t\/\/\/ \\todo Outputting a light object is now optional\n\t\t\/\/\/ We are currently setting up lights like shaders, as attributes instead of objects\n\t\t\/\/\/ Support for light objects is just for backwards compatibility with old light rig sccs,\n\t\t\/\/\/ and can be removed in the future.\n\t\tIECore::ConstLightPtr lightObject = runTimeCast<const IECore::Light>( scene->object( path ) );\n\t\tif( lightObject )\n\t\t{\n\t\t\tLightPtr light = lightObject->copy();\n\t\t\tlight->setHandle( lightHandle );\n\t\t\tlight->render( renderer );\n\t\t}\n\n\n\t\tfor( IECore::CompoundObject::ObjectMap::const_iterator it = attributes->members().begin();\n\t\t\tit != attributes->members().end(); it++ )\n\t\t{\n\t\t\tconst std::string &key = it->first.string();\n\t\t\tif( ( key.size() >= 6 && key.compare( key.length() - 6, 6, \":light\" ) == 0 ) || key == \"light\" )\n\t\t\t{\n\t\t\t\tconst IECore::ObjectVector *lightShaders = runTimeCast<const IECore::ObjectVector>( it->second.get() );\n\n\t\t\t\tif( !lightShaders || lightShaders->members().size() == 0 ) continue;\n\n\t\t\t\tIECore::ConstLightPtr constLight = runTimeCast< const IECore::Light >(\n\t\t\t\t\tlightShaders->members()[ lightShaders->members().size() - 1 ] );\n\n\t\t\t\tif( !constLight ) continue;\n\n\t\t\t\tInternedString metadataTarget = \"light:\" + constLight->getName();\n\t\t\t\tConstM44fDataPtr orientation = Metadata::value<M44fData>( metadataTarget, \"renderOrientation\" );\n\n\t\t\t\tAttributeBlock attributeBlock( renderer );\n\t\t\t\tif( orientation )\n\t\t\t\t{\n\t\t\t\t\trenderer->concatTransform( orientation->readable() );\n\t\t\t\t}\n\n\t\t\t\tfor( unsigned int i = 0; i < lightShaders->members().size() - 1; i++ )\n\t\t\t\t{\n\t\t\t\t\tIECore::ConstStateRenderablePtr shader = runTimeCast< const IECore::StateRenderable >( lightShaders->members()[i] );\n\t\t\t\t\tif( shader )\n\t\t\t\t\t{\n\t\t\t\t\t\tshader->render( renderer );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tLightPtr light = NULL;\n\t\t\t\tlight = constLight->copy();\n\t\t\t\tlight->setHandle( lightHandle );\n\n\t\t\t\tlight->render( renderer );\n\t\t\t}\n\t\t}\n\n\t\tif( const VisibleRenderable* renderable = runTimeCast< const VisibleRenderable >( object.get() ) )\n\t\t{\n\t\t\trenderable->render( renderer );\n\t\t}\n\t}\n\n\n\trenderer->illuminate( lightHandle, true );\n\n\treturn true;\n}\n\nvoid outputCoordinateSystems( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tConstPathMatcherDataPtr coordinateSystemSetData = scene->set( \"__coordinateSystems\" );\n\tconst PathMatcher &coordinateSystemSet = coordinateSystemSetData->readable();\n\n\tfor( PathMatcher::Iterator it = coordinateSystemSet.begin(), eIt = coordinateSystemSet.end(); it != eIt; ++it )\n\t{\n\t\toutputCoordinateSystem( scene, *it, renderer );\n\t}\n}\n\nbool outputCoordinateSystem( const ScenePlug *scene, const ScenePlug::ScenePath &path, IECore::Renderer *renderer )\n{\n\tIECore::ConstCoordinateSystemPtr constCoordinateSystem = runTimeCast<const IECore::CoordinateSystem>( scene->object( path ) );\n\tif( !constCoordinateSystem )\n\t{\n\t\treturn false;\n\t}\n\n\tif( !visible( scene, path ) )\n\t{\n\t\treturn false;\n\t}\n\n\tconst M44f transform = scene->fullTransform( path );\n\n\tstd::string coordinateSystemName;\n\tScenePlug::pathToString( path, coordinateSystemName );\n\n\tCoordinateSystemPtr coordinateSystem = constCoordinateSystem->copy();\n\tcoordinateSystem->setName( coordinateSystemName );\n\n\t{\n\t\tTransformBlock transformBlock( renderer );\n\t\trenderer->concatTransform( transform );\n\t\tcoordinateSystem->render( renderer );\n\t}\n\n\treturn true;\n}\n\nvoid outputClippingPlanes( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tConstPathMatcherDataPtr clippingPlanesSetData = scene->set( \"__clippingPlanes\" );\n\tconst PathMatcher &clippingPlanesSet = clippingPlanesSetData->readable();\n\n\tfor( PathMatcher::Iterator it = clippingPlanesSet.begin(), eIt = clippingPlanesSet.end(); it != eIt; ++it )\n\t{\n\t\toutputClippingPlane( scene, *it, renderer );\n\t}\n}\n\nbool outputClippingPlane( const ScenePlug *scene, const ScenePlug::ScenePath &path, IECore::Renderer *renderer )\n{\n\tIECore::ConstClippingPlanePtr clippingPlane = runTimeCast<const IECore::ClippingPlane>( scene->object( path ) );\n\tif( !clippingPlane )\n\t{\n\t\treturn false;\n\t}\n\n\tif( !visible( scene, path ) )\n\t{\n\t\treturn false;\n\t}\n\n\tconst M44f transform = scene->fullTransform( path );\n\n\tTransformBlock transformBlock( renderer );\n\trenderer->concatTransform( transform );\n\tclippingPlane->render( renderer );\n\n\treturn true;\n}\n\nvoid createDisplayDirectories( const IECore::CompoundObject *globals )\n{\n\tCompoundObject::ObjectMap::const_iterator it, eIt;\n\tfor( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )\n\t{\n\t\tif( const Display *d = runTimeCast<Display>( it->second.get() ) )\n\t\t{\n\t\t\tboost::filesystem::path fileName( d->getName() );\n\t\t\tboost::filesystem::path directory = fileName.parent_path();\n\t\t\tif( !directory.empty() )\n\t\t\t{\n\t\t\t\tboost::filesystem::create_directories( directory );\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid outputAttributes( const IECore::CompoundObject *attributes, IECore::Renderer *renderer )\n{\n\t\/\/ Output attributes before other state\n\t\/\/ This covers a special case in 3delight: when reading attributes in the construct() of a shader, they will only be visible\n\t\/\/ if they are declared before the shader\n\tfor( CompoundObject::ObjectMap::const_iterator it = attributes->members().begin(), eIt = attributes->members().end(); it != eIt; it++ )\n\t{\n\t\tif( const Data *d = runTimeCast<const Data>( it->second.get() ) )\n\t\t{\n\t\t\trenderer->setAttribute( it->first, d );\n\t\t}\n\t}\n\n\tfor( CompoundObject::ObjectMap::const_iterator it = attributes->members().begin(), eIt = attributes->members().end(); it != eIt; it++ )\n\t{\n\t\tif( boost::ends_with( it->first.c_str(), \":light\" ) || it->first == \"light\" )\n\t\t{\n\t\t\t\/\/ Currently lights are output in separate prepass\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( const StateRenderable *s = runTimeCast<const StateRenderable>( it->second.get() ) )\n\t\t{\n\t\t\ts->render( renderer );\n\t\t}\n\t\telse if( const ObjectVector *o = runTimeCast<const ObjectVector>( it->second.get() ) )\n\t\t{\n\t\t\tfor( ObjectVector::MemberContainer::const_iterator it = o->members().begin(), eIt = o->members().end(); it != eIt; it++ )\n\t\t\t{\n\t\t\t\tconst StateRenderable *s = runTimeCast<const StateRenderable>( it->get() );\n\t\t\t\tif( s )\n\t\t\t\t{\n\t\t\t\t\ts->render( renderer );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n} \/\/ namespace GafferScene\n<commit_msg>Only add extra attribute block and orientation metadata for non-arealights<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\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 with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/filesystem.hpp\"\n#include \"boost\/algorithm\/string\/predicate.hpp\"\n\n#include \"IECore\/PreWorldRenderable.h\"\n#include \"IECore\/Camera.h\"\n#include \"IECore\/WorldBlock.h\"\n#include \"IECore\/Light.h\"\n#include \"IECore\/Shader.h\"\n#include \"IECore\/AttributeBlock.h\"\n#include \"IECore\/Display.h\"\n#include \"IECore\/TransformBlock.h\"\n#include \"IECore\/CoordinateSystem.h\"\n#include \"IECore\/ClippingPlane.h\"\n#include \"IECore\/VisibleRenderable.h\"\n\n#include \"Gaffer\/Context.h\"\n#include \"Gaffer\/Metadata.h\"\n\n#include \"GafferScene\/RendererAlgo.h\"\n#include \"GafferScene\/SceneProcedural.h\"\n#include \"GafferScene\/PathMatcherData.h\"\n#include \"GafferScene\/SceneAlgo.h\"\n\nusing namespace std;\nusing namespace Imath;\nusing namespace IECore;\nusing namespace Gaffer;\n\nnamespace GafferScene\n{\n\nvoid outputScene( const ScenePlug *scene, IECore::Renderer *renderer )\n{\n\tConstCompoundObjectPtr globals = scene->globalsPlug()->getValue();\n\toutputOptions( globals.get(), renderer );\n\toutputOutputs( globals.get(), renderer );\n\toutputCamera( scene, globals.get(), renderer );\n\t{\n\t\tWorldBlock world( renderer );\n\n\t\toutputGlobalAttributes( globals.get(), renderer );\n\t\toutputCoordinateSystems( scene, globals.get(), renderer );\n\t\toutputLights( scene, globals.get(), renderer );\n\n\t\tSceneProceduralPtr proc = new SceneProcedural( scene, Context::current() );\n\t\trenderer->procedural( proc );\n\t}\n}\n\nvoid outputOutputs( const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tCompoundObject::ObjectMap::const_iterator it, eIt;\n\tfor( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )\n\t{\n\t\tif( !boost::starts_with( it->first.c_str(), \"output:\" ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif( const Display *d = runTimeCast<Display>( it->second.get() ) )\n\t\t{\n\t\t\td->render( renderer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow IECore::Exception( \"Global \\\"\" + it->first.string() + \"\\\" is not an IECore::Display\" );\n\t\t}\n\t}\n}\n\nvoid outputOptions( const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tCompoundObject::ObjectMap::const_iterator it, eIt;\n\tfor( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )\n\t{\n\t\tif( !boost::starts_with( it->first.c_str(), \"option:\" ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif( const Data *d = runTimeCast<Data>( it->second.get() ) )\n\t\t{\n\t\t\trenderer->setOption( it->first.c_str() + 7, d );\n\t\t}\n\t\telse if( const PreWorldRenderable *r = runTimeCast<PreWorldRenderable>( it->second.get() ) )\n\t\t{\n\t\t\tr->render( renderer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow IECore::Exception( \"Global \\\"\" + it->first.string() + \"\\\" is not IECore::Data or an IECore::PreWorldRenderable\" );\n\t\t}\n\t}\n}\n\nvoid outputCameras( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tConstPathMatcherDataPtr cameraSetData = scene->set( \"__cameras\" );\n\tconst PathMatcher &cameraSet = cameraSetData->readable();\n\n\t\/\/ Output all the cameras, skipping the primary one - we need to output this\n\t\/\/ last, as that's how cortex determines the primary camera.\n\tScenePlug::ScenePath primaryCameraPath;\n\tif( const StringData *primaryCameraPathData = globals->member<StringData>( \"option:render:camera\" ) )\n\t{\n\t\tScenePlug::stringToPath( primaryCameraPathData->readable(), primaryCameraPath );\n\t}\n\n\tfor( PathMatcher::Iterator it = cameraSet.begin(), eIt = cameraSet.end(); it != eIt; ++it )\n\t{\n\t\tif( *it != primaryCameraPath )\n\t\t{\n\t\t\toutputCamera( scene, *it, globals, renderer );\n\t\t}\n\t}\n\n\t\/\/ Output the primary camera, or a default if it doesn't exist.\n\n\toutputCamera( scene, globals, renderer );\n\n}\n\nvoid outputCamera( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tIECore::CameraPtr camera = GafferScene::camera( scene, globals );\n\tcamera->render( renderer );\n}\n\nvoid outputCamera( const ScenePlug *scene, const ScenePlug::ScenePath &cameraPath, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tIECore::CameraPtr camera = GafferScene::camera( scene, cameraPath, globals );\n\tcamera->render( renderer );\n}\n\nvoid outputGlobalAttributes( const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tCompoundObject::ObjectMap::const_iterator it, eIt;\n\tfor( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )\n\t{\n\t\tif( !boost::starts_with( it->first.c_str(), \"attribute:\" ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif( const Data *d = runTimeCast<Data>( it->second.get() ) )\n\t\t{\n\t\t\trenderer->setAttribute( it->first.c_str() + 10, d );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow IECore::Exception( \"Global \\\"\" + it->first.string() + \"\\\" is not IECore::Data\" );\n\t\t}\n\t}\n}\n\nvoid outputLights( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tConstPathMatcherDataPtr lightSetData = scene->set( \"__lights\" );\n\tconst PathMatcher &lightSet = lightSetData->readable();\n\n\tfor( PathMatcher::Iterator it = lightSet.begin(), eIt = lightSet.end(); it != eIt; ++it )\n\t{\n\t\toutputLight( scene, *it, renderer );\n\t}\n}\n\nbool outputLight( const ScenePlug *scene, const ScenePlug::ScenePath &path, IECore::Renderer *renderer )\n{\n\tif( !visible( scene, path ) )\n\t{\n\t\t\/\/\/ \\todo Since both visible() and fullAttributes() perform similar work,\n\t\t\/\/\/ we may want to combine them into one query if we see this function\n\t\t\/\/\/ being a significant fraction of render time. Maybe something like\n\t\t\/\/\/ `fullAttributes( returnNullIfInvisible = true )`? It probably also\n\t\t\/\/\/ makes sense to migrate all the convenience functions from ScenePlug\n\t\t\/\/\/ into SceneAlgo.\n\t\treturn false;\n\t}\n\n\tConstCompoundObjectPtr attributes = scene->fullAttributes( path );\n\tConstObjectPtr object = scene->object( path );\n\tconst M44f transform = scene->fullTransform( path );\n\n\tstd::string lightHandle;\n\tScenePlug::pathToString( path, lightHandle );\n\n\t{\n\t\tAttributeBlock attributeBlock( renderer );\n\n\t\trenderer->setAttribute( \"name\", new StringData( lightHandle ) );\n\t\toutputAttributes( attributes.get(), renderer );\n\t\trenderer->concatTransform( transform );\n\n\n\t\t\/\/\/ \\todo Outputting a light object is now optional\n\t\t\/\/\/ We are currently setting up lights like shaders, as attributes instead of objects\n\t\t\/\/\/ Support for light objects is just for backwards compatibility with old light rig sccs,\n\t\t\/\/\/ and can be removed in the future.\n\t\tIECore::ConstLightPtr lightObject = runTimeCast<const IECore::Light>( scene->object( path ) );\n\t\tif( lightObject )\n\t\t{\n\t\t\tLightPtr light = lightObject->copy();\n\t\t\tlight->setHandle( lightHandle );\n\t\t\tlight->render( renderer );\n\t\t}\n\n\n\t\tfor( IECore::CompoundObject::ObjectMap::const_iterator it = attributes->members().begin();\n\t\t\tit != attributes->members().end(); it++ )\n\t\t{\n\t\t\tconst std::string &key = it->first.string();\n\t\t\tif( ( key.size() >= 6 && key.compare( key.length() - 6, 6, \":light\" ) == 0 ) || key == \"light\" )\n\t\t\t{\n\t\t\t\tconst IECore::ObjectVector *lightShaders = runTimeCast<const IECore::ObjectVector>( it->second.get() );\n\n\t\t\t\tif( !lightShaders || lightShaders->members().size() == 0 ) continue;\n\n\t\t\t\tIECore::ConstLightPtr constLight = runTimeCast< const IECore::Light >(\n\t\t\t\t\tlightShaders->members()[ lightShaders->members().size() - 1 ] );\n\n\t\t\t\tif( !constLight ) continue;\n\n\t\t\t\tLightPtr light = constLight->copy();\n\n\t\t\t\tbool areaLight = false;\n\t\t\t\tconst BoolData *areaLightParm = light->parametersData()->member<BoolData>( \"__areaLight\" );\n\t\t\t\tif( areaLightParm )\n\t\t\t\t{\n\t\t\t\t\tareaLight = areaLightParm->readable();\n\t\t\t\t}\n\n\t\t\t\t\/\/\/ If this is a non-areaLight which could have orientation metadata,\n\t\t\t\t\/\/\/ add an extra attribute block to contain it\n\t\t\t\tAttributeBlock attributeBlock( renderer, !areaLight );\n\n\t\t\t\tif( !areaLight )\n\t\t\t\t{\n\t\t\t\t\tInternedString metadataTarget = \"light:\" + constLight->getName();\n\t\t\t\t\tConstM44fDataPtr orientation = Metadata::value<M44fData>( metadataTarget, \"renderOrientation\" );\n\n\t\t\t\t\tif( orientation )\n\t\t\t\t\t{\n\t\t\t\t\t\trenderer->concatTransform( orientation->readable() );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor( unsigned int i = 0; i < lightShaders->members().size() - 1; i++ )\n\t\t\t\t{\n\t\t\t\t\tIECore::ConstStateRenderablePtr shader = runTimeCast< const IECore::StateRenderable >( lightShaders->members()[i] );\n\t\t\t\t\tif( shader )\n\t\t\t\t\t{\n\t\t\t\t\t\tshader->render( renderer );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlight->setHandle( lightHandle );\n\n\t\t\t\tlight->render( renderer );\n\t\t\t}\n\t\t}\n\n\t\tif( const VisibleRenderable* renderable = runTimeCast< const VisibleRenderable >( object.get() ) )\n\t\t{\n\t\t\trenderable->render( renderer );\n\t\t}\n\t}\n\n\n\trenderer->illuminate( lightHandle, true );\n\n\treturn true;\n}\n\nvoid outputCoordinateSystems( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tConstPathMatcherDataPtr coordinateSystemSetData = scene->set( \"__coordinateSystems\" );\n\tconst PathMatcher &coordinateSystemSet = coordinateSystemSetData->readable();\n\n\tfor( PathMatcher::Iterator it = coordinateSystemSet.begin(), eIt = coordinateSystemSet.end(); it != eIt; ++it )\n\t{\n\t\toutputCoordinateSystem( scene, *it, renderer );\n\t}\n}\n\nbool outputCoordinateSystem( const ScenePlug *scene, const ScenePlug::ScenePath &path, IECore::Renderer *renderer )\n{\n\tIECore::ConstCoordinateSystemPtr constCoordinateSystem = runTimeCast<const IECore::CoordinateSystem>( scene->object( path ) );\n\tif( !constCoordinateSystem )\n\t{\n\t\treturn false;\n\t}\n\n\tif( !visible( scene, path ) )\n\t{\n\t\treturn false;\n\t}\n\n\tconst M44f transform = scene->fullTransform( path );\n\n\tstd::string coordinateSystemName;\n\tScenePlug::pathToString( path, coordinateSystemName );\n\n\tCoordinateSystemPtr coordinateSystem = constCoordinateSystem->copy();\n\tcoordinateSystem->setName( coordinateSystemName );\n\n\t{\n\t\tTransformBlock transformBlock( renderer );\n\t\trenderer->concatTransform( transform );\n\t\tcoordinateSystem->render( renderer );\n\t}\n\n\treturn true;\n}\n\nvoid outputClippingPlanes( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer )\n{\n\tConstPathMatcherDataPtr clippingPlanesSetData = scene->set( \"__clippingPlanes\" );\n\tconst PathMatcher &clippingPlanesSet = clippingPlanesSetData->readable();\n\n\tfor( PathMatcher::Iterator it = clippingPlanesSet.begin(), eIt = clippingPlanesSet.end(); it != eIt; ++it )\n\t{\n\t\toutputClippingPlane( scene, *it, renderer );\n\t}\n}\n\nbool outputClippingPlane( const ScenePlug *scene, const ScenePlug::ScenePath &path, IECore::Renderer *renderer )\n{\n\tIECore::ConstClippingPlanePtr clippingPlane = runTimeCast<const IECore::ClippingPlane>( scene->object( path ) );\n\tif( !clippingPlane )\n\t{\n\t\treturn false;\n\t}\n\n\tif( !visible( scene, path ) )\n\t{\n\t\treturn false;\n\t}\n\n\tconst M44f transform = scene->fullTransform( path );\n\n\tTransformBlock transformBlock( renderer );\n\trenderer->concatTransform( transform );\n\tclippingPlane->render( renderer );\n\n\treturn true;\n}\n\nvoid createDisplayDirectories( const IECore::CompoundObject *globals )\n{\n\tCompoundObject::ObjectMap::const_iterator it, eIt;\n\tfor( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )\n\t{\n\t\tif( const Display *d = runTimeCast<Display>( it->second.get() ) )\n\t\t{\n\t\t\tboost::filesystem::path fileName( d->getName() );\n\t\t\tboost::filesystem::path directory = fileName.parent_path();\n\t\t\tif( !directory.empty() )\n\t\t\t{\n\t\t\t\tboost::filesystem::create_directories( directory );\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid outputAttributes( const IECore::CompoundObject *attributes, IECore::Renderer *renderer )\n{\n\t\/\/ Output attributes before other state\n\t\/\/ This covers a special case in 3delight: when reading attributes in the construct() of a shader, they will only be visible\n\t\/\/ if they are declared before the shader\n\tfor( CompoundObject::ObjectMap::const_iterator it = attributes->members().begin(), eIt = attributes->members().end(); it != eIt; it++ )\n\t{\n\t\tif( const Data *d = runTimeCast<const Data>( it->second.get() ) )\n\t\t{\n\t\t\trenderer->setAttribute( it->first, d );\n\t\t}\n\t}\n\n\tfor( CompoundObject::ObjectMap::const_iterator it = attributes->members().begin(), eIt = attributes->members().end(); it != eIt; it++ )\n\t{\n\t\tif( boost::ends_with( it->first.c_str(), \":light\" ) || it->first == \"light\" )\n\t\t{\n\t\t\t\/\/ Currently lights are output in separate prepass\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( const StateRenderable *s = runTimeCast<const StateRenderable>( it->second.get() ) )\n\t\t{\n\t\t\ts->render( renderer );\n\t\t}\n\t\telse if( const ObjectVector *o = runTimeCast<const ObjectVector>( it->second.get() ) )\n\t\t{\n\t\t\tfor( ObjectVector::MemberContainer::const_iterator it = o->members().begin(), eIt = o->members().end(); it != eIt; it++ )\n\t\t\t{\n\t\t\t\tconst StateRenderable *s = runTimeCast<const StateRenderable>( it->get() );\n\t\t\t\tif( s )\n\t\t\t\t{\n\t\t\t\t\ts->render( renderer );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n} \/\/ namespace GafferScene\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2009, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/PDCParticleReader.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/VectorTypedData.h\"\n#include \"IECore\/ByteOrder.h\"\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/FileNameParameter.h\"\n#include \"IECore\/Timer.h\"\n\n#include \"OpenEXR\/ImathRandom.h\"\n\n#include <algorithm>\n\n\n#include <fstream>\n#include <cassert>\n\nusing namespace IECore;\nusing namespace boost;\nusing namespace Imath;\nusing namespace std;\n\nIE_CORE_DEFINERUNTIMETYPED( PDCParticleReader );\n\nconst Reader::ReaderDescription<PDCParticleReader> PDCParticleReader::m_readerDescription( \"pdc\" );\n\nPDCParticleReader::PDCParticleReader( )\n\t:\tParticleReader( \"PDCParticleReader\", \"Reads Maya .pdc format particle caches\" ), m_iStream( 0 ), m_idAttribute( 0 )\n{\n}\n\nPDCParticleReader::PDCParticleReader( const std::string &fileName )\n\t:\tParticleReader( \"PDCParticleReader\", \"Reads Maya .pdc format particle caches\" ), m_iStream( 0 ), m_idAttribute( 0 )\n{\n\tm_fileNameParameter->setTypedValue( fileName );\n}\n\nPDCParticleReader::~PDCParticleReader()\n{\n\tdelete m_iStream;\n}\n\nbool PDCParticleReader::canRead( const std::string &fileName )\n{\n\tifstream i( fileName.c_str() );\n\tif( !i.is_open() )\n\t{\n\t\treturn false;\n\t}\n\tchar id[4];\n\ti.read( id, 4 );\n\tif( strncmp( \"PDC \", id, 4 ) )\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool PDCParticleReader::open()\n{\n\tif( !m_iStream || m_streamFileName!=fileName() )\n\t{\n\t\tdelete m_iStream;\n\t\tm_iStream = new ifstream( fileName().c_str() );\n\t\tif( !m_iStream->is_open() || !m_iStream->good() )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tchar pdc[4];\n\t\tm_iStream->read( pdc, 4 );\n\t\tif( strncmp( \"PDC \", pdc, 4 ) )\n\t\t{\n\t\t\tm_header.valid = false;\n\t\t\treturn false;\n\t\t}\n\n\t\tm_iStream->read( (char *)&m_header.version, sizeof( m_header.version ) );\n\n\t\tint endian = 0;\n\t\tm_iStream->read( (char *)&endian, sizeof( endian ) );\n\t\tif( endian!=1 )\n\t\t{\n\t\t\tm_header.reverseBytes = true;\n\t\t\tm_header.version = reverseBytes( m_header.version );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_header.reverseBytes = false;\n\t\t}\n\n\t\tif( m_header.version > 1 )\n\t\t{\n\t\t\tmsg( Msg::Warning, \"PDCParticleReader::open()\", format( \"File \\\"%s\\\" has unknown version %d.\" ) % fileName() % m_header.version );\n\t\t}\n\n\t\tint unused = 0;\n\t\tm_iStream->read( (char *)&unused, sizeof( unused ) );\n\t\tm_iStream->read( (char *)&unused, sizeof( unused ) );\n\n\t\tm_iStream->read( (char *)&m_header.numParticles, sizeof( m_header.numParticles ) );\n\t\tif( m_header.reverseBytes )\n\t\t{\n\t\t\tm_header.numParticles = reverseBytes( m_header.numParticles );\n\t\t}\n\n\t\tint numAttributes;\n\t\tm_iStream->read( (char *)&numAttributes, sizeof( numAttributes ) );\n\t\tif( m_header.reverseBytes )\n\t\t{\n\t\t\tnumAttributes = reverseBytes( numAttributes );\n\t\t}\n\t\tfor( int i=0; i<numAttributes; i++ )\n\t\t{\n\t\t\tint nameLength;\n\t\t\tm_iStream->read( (char *)&nameLength, sizeof( nameLength ) );\n\t\t\tif( m_header.reverseBytes )\n\t\t\t{\n\t\t\t\tnameLength = reverseBytes( nameLength );\n\t\t\t}\n\t\t\tstring attrName; char c;\n\t\t\tfor( int j=0; j<nameLength; j++ )\n\t\t\t{\n\t\t\t\tm_iStream->read( &c, 1 );\n\t\t\t\tattrName += c;\n\t\t\t}\n\t\t\tif( attrName==\"ghostFrames\" )\n\t\t\t{\n\t\t\t\t\/\/ alias' own pdc files don't match their own spec.\n\t\t\t\t\/\/ they have a junk attributes on the end with no\n\t\t\t\t\/\/ type and no data. it's called ghostframes and\n\t\t\t\t\/\/ we need to skip it to prevent our stream from\n\t\t\t\t\/\/ going bad.\n\t\t\t\tassert( i==numAttributes-1 ); \/\/ we're assuming the bad attribute is always the last one\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRecord r;\n\t\t\tm_iStream->read( (char *)&r.type, sizeof( r.type ) );\n\t\t\tif( m_header.reverseBytes )\n\t\t\t{\n\t\t\t\tr.type = reverseBytes( r.type );\n\t\t\t}\n\t\t\tr.position = m_iStream->tellg();\n\t\t\tm_header.attributes[attrName] = r;\n\t\t\tswitch( r.type )\n\t\t\t{\n\t\t\t\tcase Integer :\n\t\t\t\t\tm_iStream->seekg( sizeof( int ), ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase IntegerArray :\n\t\t\t\t\tm_iStream->seekg( sizeof( int ) * m_header.numParticles, ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase Double :\n\t\t\t\t\tm_iStream->seekg( sizeof( double ), ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase DoubleArray :\n\t\t\t\t\tm_iStream->seekg( sizeof( double ) * m_header.numParticles, ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase Vector :\n\t\t\t\t\tm_iStream->seekg( sizeof( double ) * 3, ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase VectorArray :\n\t\t\t\t\tm_iStream->seekg( sizeof( double ) * 3 * m_header.numParticles, ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tdefault :\n\t\t\t\t\tassert( r.type < 6 ); \/\/ unknown type\n\t\t\t}\n\n\t\t}\n\n\t\tm_header.valid = m_iStream->good();\n\t\tm_streamFileName = fileName();\n\t\tm_idAttribute = 0;\n\t}\n\treturn m_iStream->good() && m_header.valid;\n}\n\nunsigned long PDCParticleReader::numParticles()\n{\n\tif( open() )\n\t{\n\t\treturn m_header.numParticles;\n\t}\n\treturn 0;\n}\n\nvoid PDCParticleReader::attributeNames( std::vector<std::string> &names )\n{\n\tnames.clear();\n\tif( open() )\n\t{\n\t\tmap<string, Record>::const_iterator it;\n\t\tfor( it=m_header.attributes.begin(); it!=m_header.attributes.end(); it++ )\n\t\t{\n\t\t\tnames.push_back( it->first );\n\t\t}\n\t}\n}\n\ntemplate<typename T>\nvoid PDCParticleReader::readElements( T *buffer, std::streampos pos, unsigned long n ) const\n{\n\tm_iStream->seekg( pos );\n\tm_iStream->read( (char *)buffer, n * sizeof( T ) );\n\tif( m_header.reverseBytes )\n\t{\n\t\tfor( unsigned long i=0; i<n; i++ )\n\t\t{\n\t\t\t*buffer = reverseBytes( *buffer );\n\t\t\tbuffer++;\n\t\t}\n\t}\n\tassert( m_iStream->good() );\n}\n\ntemplate<typename T, typename F>\ntypename T::Ptr PDCParticleReader::filterAttr( typename F::ConstPtr attr, float percentage )\n{\n\tif( percentage < 100.0f )\n\t{\n\t\tConstDoubleVectorDataPtr idAttr = idAttribute();\n\t\tif( idAttr )\n\t\t{\n\t\t\t\/\/ percentage filtering (and type conversion if necessary)\n\t\t\ttypename T::Ptr result( new T );\n\t\t\tconst typename F::ValueType &in = attr->readable();\n\t\t\ttypename T::ValueType &out = result->writable();\n\t\t\tconst vector<double> &ids = idAttr->readable();\n\t\t\tint seed = particlePercentageSeed();\n\t\t\tfloat fraction = percentage \/ 100.0f;\n\t\t\tRand48 r;\n\t\t\tfor( typename F::ValueType::size_type i=0; i<in.size(); i++ )\n\t\t\t{\n\t\t\t\tr.init( seed + (int)ids[i] );\n\t\t\t\tif( r.nextf() <= fraction )\n\t\t\t\t{\n\t\t\t\t\tout.push_back( in[i] );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg( Msg::Warning, \"PDCParticleReader::filterAttr\", format( \"Percentage filtering requested but file \\\"%s\\\" contains no particleId attribute.\" ) % fileName() );\n\t\t\t\/\/ fall through to allow basic loading to happen anyway.\n\t\t}\n\t}\n\n\tif( T::staticTypeId()!=F::staticTypeId() )\n\t{\n\t\t\/\/ type conversion only\n\t\ttypename T::Ptr result( new T );\n\t\tconst typename F::ValueType &in = attr->readable();\n\t\ttypename T::ValueType &out = result->writable();\n\t\tout.resize( in.size() );\n\t\tcopy( in.begin(), in.end(), out.begin() );\n\t\treturn result;\n\t}\n\n\t\/\/ no filtering of any sort needed\n\treturn typename T::Ptr( (T *)attr.get() );\n}\n\nDataPtr PDCParticleReader::readAttribute( const std::string &name )\n{\n\tif( !open() )\n\t{\n\t\treturn 0;\n\t}\n\n\tmap<string, Record>::const_iterator it = m_header.attributes.find( name );\n\tif( it==m_header.attributes.end() )\n\t{\n\t\treturn 0;\n\t}\n\n\tDataPtr result = 0;\n\tswitch( it->second.type )\n\t{\n\t\tcase Integer :\n\t\t\t{\n\t\t\t\tIntDataPtr d( new IntData );\n\t\t\t\treadElements( &d->writable(), it->second.position, 1 );\n\t\t\t\tresult = d;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase IntegerArray :\n\t\t\t{\n\t\t\t\tIntVectorDataPtr d( new IntVectorData );\n\t\t\t\td->writable().resize( numParticles() );\n\t\t\t\treadElements( &d->writable()[0], it->second.position, numParticles() );\n\t\t\t\tresult = filterAttr<IntVectorData, IntVectorData>( d, particlePercentage() );\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Double :\n\t\t\t{\n\t\t\t\tDoubleDataPtr d( new DoubleData );\n\t\t\t\treadElements( &d->writable(), it->second.position, 1 );\n\t\t\t\tswitch( realType() )\n\t\t\t\t{\n\t\t\t\t\tcase Native :\n\t\t\t\t\tcase Double :\n\t\t\t\t\t\tresult = d;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Float :\n\t\t\t\t\t\tresult = new FloatData( d->readable() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DoubleArray :\n\t\t\t{\n\t\t\t\tDoubleVectorDataPtr d( new DoubleVectorData );\n\t\t\t\td->writable().resize( numParticles() );\n\t\t\t\treadElements( &d->writable()[0], it->second.position, numParticles() );\n\t\t\t\tswitch( realType() )\n\t\t\t\t{\n\t\t\t\t\tcase Native :\n\t\t\t\t\tcase Double :\n\t\t\t\t\t\tresult = filterAttr<DoubleVectorData, DoubleVectorData>( d, particlePercentage() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Float :\n\t\t\t\t\t\tresult = filterAttr<FloatVectorData, DoubleVectorData>( d, particlePercentage() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Vector :\n\t\t\t{\n\t\t\t\tV3dDataPtr d( new V3dData );\n\t\t\t\treadElements( (double *)&d->writable(), it->second.position, 3 );\n\t\t\t\tswitch( realType() )\n\t\t\t\t{\n\t\t\t\t\tcase Native :\n\t\t\t\t\tcase Double :\n\t\t\t\t\t\tresult = d;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Float :\n\t\t\t\t\t\tresult = new V3fData( d->readable() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase VectorArray :\n\t\t\t{\n\t\t\t\tV3dVectorDataPtr d( new V3dVectorData );\n\t\t\t\t\/\/\/ \\todo\n\t\t\t\t\/\/\/ by all accounts the line below should be this :\n\t\t\t\t\/\/\/\n\t\t\t\t\/\/\/ d->writable().resize( numParticles() );\n\t\t\t\t\/\/\/\n\t\t\t\t\/\/\/ ie it shouldn't initialize the memory. but for some reason\n\t\t\t\t\/\/\/ that runs far far slower for us (at least an order of magnitude\n\t\t\t\t\/\/\/ slower) when we're in maya or python. we don't know why but it seems\n\t\t\t\t\/\/\/ to be related to libstdc++ (maya has it's own). so we're opting for\n\t\t\t\t\/\/\/ the initialized version - this seems slightly (~10%) slower when the planets\n\t\t\t\t\/\/\/ are aligned correctly, but so much faster when the planets are aligned against\n\t\t\t\t\/\/\/ us, as they seem to be whenever we're coding in maya. testing seems to show that\n\t\t\t\t\/\/\/ this resize problem only occurs with V3d, and not with V3f, or double, or even\n\t\t\t\t\/\/\/ a struct with 3 doubles in, or even a template struct with 3 doubles in.\n\t\t\t\td->writable().resize( numParticles(), V3d( 0 ) );\n\t\t\t\treadElements( (double *)&d->writable()[0], it->second.position, numParticles() * 3 );\n\t\t\t\tswitch( realType() )\n\t\t\t\t{\n\t\t\t\t\tcase Native :\n\t\t\t\t\tcase Double :\n\t\t\t\t\t\tresult = filterAttr<V3dVectorData, V3dVectorData>( d, particlePercentage() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Float :\n\t\t\t\t\t\tresult = filterAttr<V3fVectorData, V3dVectorData>( d, particlePercentage() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault :\n\t\t\tassert( it->second.type < 6 ); \/\/ unknown type\n\n\t}\n\treturn result;\n}\n\nConstDoubleVectorDataPtr PDCParticleReader::idAttribute()\n{\n\tif( !open() )\n\t{\n\t\treturn 0;\n\t}\n\tif( !m_idAttribute )\n\t{\n\t\tmap<string, Record>::const_iterator it = m_header.attributes.find( \"particleId\" );\n\t\tif( it!=m_header.attributes.end() )\n\t\t{\n\t\t\tif( it->second.type==DoubleArray )\n\t\t\t{\n\t\t\t\tm_idAttribute = new DoubleVectorData;\n\t\t\t\tm_idAttribute->writable().resize( numParticles() );\n\t\t\t\treadElements( &m_idAttribute->writable()[0], it->second.position, numParticles() );\n\t\t\t}\n\t\t}\n\t}\n\treturn m_idAttribute;\n}\n<commit_msg>mirroring commit from the branch<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2009, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/PDCParticleReader.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/VectorTypedData.h\"\n#include \"IECore\/ByteOrder.h\"\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/FileNameParameter.h\"\n#include \"IECore\/Timer.h\"\n\n#include \"OpenEXR\/ImathRandom.h\"\n\n#include <algorithm>\n\n\n#include <fstream>\n#include <cassert>\n\nusing namespace IECore;\nusing namespace boost;\nusing namespace Imath;\nusing namespace std;\n\nIE_CORE_DEFINERUNTIMETYPED( PDCParticleReader );\n\nconst Reader::ReaderDescription<PDCParticleReader> PDCParticleReader::m_readerDescription( \"pdc\" );\n\nPDCParticleReader::PDCParticleReader( )\n\t:\tParticleReader( \"PDCParticleReader\", \"Reads Maya .pdc format particle caches\" ), m_iStream( 0 ), m_idAttribute( 0 )\n{\n}\n\nPDCParticleReader::PDCParticleReader( const std::string &fileName )\n\t:\tParticleReader( \"PDCParticleReader\", \"Reads Maya .pdc format particle caches\" ), m_iStream( 0 ), m_idAttribute( 0 )\n{\n\tm_fileNameParameter->setTypedValue( fileName );\n}\n\nPDCParticleReader::~PDCParticleReader()\n{\n\tdelete m_iStream;\n}\n\nbool PDCParticleReader::canRead( const std::string &fileName )\n{\n\tifstream i( fileName.c_str() );\n\tif( !i.is_open() )\n\t{\n\t\treturn false;\n\t}\n\tchar id[4];\n\ti.read( id, 4 );\n\tif( strncmp( \"PDC \", id, 4 ) )\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool PDCParticleReader::open()\n{\n\tif( !m_iStream || m_streamFileName!=fileName() )\n\t{\n\t\tdelete m_iStream;\n\t\tm_iStream = new ifstream( fileName().c_str() );\n\t\tif( !m_iStream->is_open() || !m_iStream->good() )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tchar pdc[4];\n\t\tm_iStream->read( pdc, 4 );\n\t\tif( strncmp( \"PDC \", pdc, 4 ) )\n\t\t{\n\t\t\tm_header.valid = false;\n\t\t\treturn false;\n\t\t}\n\n\t\tm_iStream->read( (char *)&m_header.version, sizeof( m_header.version ) );\n\n\t\tint endian = 0;\n\t\tm_iStream->read( (char *)&endian, sizeof( endian ) );\n\t\tif( endian!=1 )\n\t\t{\n\t\t\tm_header.reverseBytes = true;\n\t\t\tm_header.version = reverseBytes( m_header.version );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_header.reverseBytes = false;\n\t\t}\n\n\t\tif( m_header.version > 1 )\n\t\t{\n\t\t\tmsg( Msg::Warning, \"PDCParticleReader::open()\", format( \"File \\\"%s\\\" has unknown version %d.\" ) % fileName() % m_header.version );\n\t\t}\n\n\t\tint unused = 0;\n\t\tm_iStream->read( (char *)&unused, sizeof( unused ) );\n\t\tm_iStream->read( (char *)&unused, sizeof( unused ) );\n\n\t\tm_iStream->read( (char *)&m_header.numParticles, sizeof( m_header.numParticles ) );\n\t\tif( m_header.reverseBytes )\n\t\t{\n\t\t\tm_header.numParticles = reverseBytes( m_header.numParticles );\n\t\t}\n\n\t\tint numAttributes;\n\t\tm_iStream->read( (char *)&numAttributes, sizeof( numAttributes ) );\n\t\tif( m_header.reverseBytes )\n\t\t{\n\t\t\tnumAttributes = reverseBytes( numAttributes );\n\t\t}\n\t\tfor( int i=0; i<numAttributes; i++ )\n\t\t{\n\t\t\tint nameLength;\n\t\t\tm_iStream->read( (char *)&nameLength, sizeof( nameLength ) );\n\t\t\tif( m_header.reverseBytes )\n\t\t\t{\n\t\t\t\tnameLength = reverseBytes( nameLength );\n\t\t\t}\n\t\t\tstring attrName; char c;\n\t\t\tfor( int j=0; j<nameLength; j++ )\n\t\t\t{\n\t\t\t\tm_iStream->read( &c, 1 );\n\t\t\t\tattrName += c;\n\t\t\t}\n\t\t\tif( attrName==\"ghostFrames\" )\n\t\t\t{\n\t\t\t\t\/\/ alias' own pdc files don't match their own spec.\n\t\t\t\t\/\/ they have a junk attributes on the end with no\n\t\t\t\t\/\/ type and no data. it's called ghostframes and\n\t\t\t\t\/\/ we need to skip it to prevent our stream from\n\t\t\t\t\/\/ going bad.\n\t\t\t\tassert( i==numAttributes-1 ); \/\/ we're assuming the bad attribute is always the last one\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRecord r;\n\t\t\tm_iStream->read( (char *)&r.type, sizeof( r.type ) );\n\t\t\tif( m_header.reverseBytes )\n\t\t\t{\n\t\t\t\tr.type = reverseBytes( r.type );\n\t\t\t}\n\t\t\tr.position = m_iStream->tellg();\n\t\t\tm_header.attributes[attrName] = r;\n\t\t\tswitch( r.type )\n\t\t\t{\n\t\t\t\tcase Integer :\n\t\t\t\t\tm_iStream->seekg( sizeof( int ), ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase IntegerArray :\n\t\t\t\t\tm_iStream->seekg( sizeof( int ) * m_header.numParticles, ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase Double :\n\t\t\t\t\tm_iStream->seekg( sizeof( double ), ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase DoubleArray :\n\t\t\t\t\tm_iStream->seekg( sizeof( double ) * m_header.numParticles, ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase Vector :\n\t\t\t\t\tm_iStream->seekg( sizeof( double ) * 3, ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tcase VectorArray :\n\t\t\t\t\tm_iStream->seekg( sizeof( double ) * 3 * m_header.numParticles, ios_base::cur );\n\t\t\t\t\tbreak;\n\t\t\t\tdefault :\n\t\t\t\t\tassert( r.type < 6 ); \/\/ unknown type\n\t\t\t}\n\n\t\t}\n\n\t\tm_header.valid = m_iStream->good();\n\t\tm_streamFileName = fileName();\n\t\tm_idAttribute = 0;\n\t}\n\treturn m_iStream->good() && m_header.valid;\n}\n\nunsigned long PDCParticleReader::numParticles()\n{\n\tif( open() )\n\t{\n\t\treturn m_header.numParticles;\n\t}\n\treturn 0;\n}\n\nvoid PDCParticleReader::attributeNames( std::vector<std::string> &names )\n{\n\tnames.clear();\n\tif( open() )\n\t{\n\t\tmap<string, Record>::const_iterator it;\n\t\tfor( it=m_header.attributes.begin(); it!=m_header.attributes.end(); it++ )\n\t\t{\n\t\t\tnames.push_back( it->first );\n\t\t}\n\t}\n}\n\ntemplate<typename T>\nvoid PDCParticleReader::readElements( T *buffer, std::streampos pos, unsigned long n ) const\n{\n\tm_iStream->seekg( pos );\n\tm_iStream->read( (char *)buffer, n * sizeof( T ) );\n\tif( m_header.reverseBytes )\n\t{\n\t\tfor( unsigned long i=0; i<n; i++ )\n\t\t{\n\t\t\t*buffer = reverseBytes( *buffer );\n\t\t\tbuffer++;\n\t\t}\n\t}\n\tassert( m_iStream->good() );\n}\n\ntemplate<typename T, typename F>\ntypename T::Ptr PDCParticleReader::filterAttr( typename F::ConstPtr attr, float percentage )\n{\n\tif( percentage < 100.0f )\n\t{\n\t\tConstDoubleVectorDataPtr idAttr = idAttribute();\n\t\tif( idAttr )\n\t\t{\n\t\t\t\/\/ percentage filtering (and type conversion if necessary)\n\t\t\ttypename T::Ptr result( new T );\n\t\t\tconst typename F::ValueType &in = attr->readable();\n\t\t\ttypename T::ValueType &out = result->writable();\n\t\t\tconst vector<double> &ids = idAttr->readable();\n\t\t\tint seed = particlePercentageSeed();\n\t\t\tfloat fraction = percentage \/ 100.0f;\n\t\t\tRand48 r;\n\t\t\tfor( typename F::ValueType::size_type i=0; i<in.size(); i++ )\n\t\t\t{\n\t\t\t\tr.init( seed + (int)ids[i] );\n\t\t\t\tif( r.nextf() <= fraction )\n\t\t\t\t{\n\t\t\t\t\tout.push_back( in[i] );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg( Msg::Warning, \"PDCParticleReader::filterAttr\", format( \"Percentage filtering requested but file \\\"%s\\\" contains no particleId attribute.\" ) % fileName() );\n\t\t\t\/\/ fall through to allow basic loading to happen anyway.\n\t\t}\n\t}\n\n\tif( T::staticTypeId()!=F::staticTypeId() )\n\t{\n\t\t\/\/ type conversion only\n\t\ttypename T::Ptr result( new T );\n\t\tconst typename F::ValueType &in = attr->readable();\n\t\ttypename T::ValueType &out = result->writable();\n\t\tout.resize( in.size() );\n\t\tcopy( in.begin(), in.end(), out.begin() );\n\t\treturn result;\n\t}\n\n\t\/\/ no filtering of any sort needed\n\treturn typename T::Ptr( (T *)attr.get() );\n}\n\nDataPtr PDCParticleReader::readAttribute( const std::string &name )\n{\n\tif( !open() )\n\t{\n\t\treturn 0;\n\t}\n\n\tmap<string, Record>::const_iterator it = m_header.attributes.find( name );\n\tif( it==m_header.attributes.end() )\n\t{\n\t\treturn 0;\n\t}\n\n\tDataPtr result = 0;\n\tswitch( it->second.type )\n\t{\n\t\tcase Integer :\n\t\t\t{\n\t\t\t\tIntDataPtr d( new IntData );\n\t\t\t\treadElements( &d->writable(), it->second.position, 1 );\n\t\t\t\tresult = d;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase IntegerArray :\n\t\t\t{\n\t\t\t\tIntVectorDataPtr d( new IntVectorData );\n\t\t\t\td->writable().resize( numParticles() );\n\t\t\t\treadElements( &d->writable()[0], it->second.position, numParticles() );\n\t\t\t\tresult = filterAttr<IntVectorData, IntVectorData>( d, particlePercentage() );\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Double :\n\t\t\t{\n\t\t\t\tDoubleDataPtr d( new DoubleData );\n\t\t\t\treadElements( &d->writable(), it->second.position, 1 );\n\t\t\t\tswitch( realType() )\n\t\t\t\t{\n\t\t\t\t\tcase Native :\n\t\t\t\t\tcase Double :\n\t\t\t\t\t\tresult = d;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Float :\n\t\t\t\t\t\tresult = new FloatData( d->readable() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DoubleArray :\n\t\t\t{\n\t\t\t\tDoubleVectorDataPtr d( new DoubleVectorData );\n\t\t\t\td->writable().resize( numParticles() );\n\t\t\t\treadElements( &d->writable()[0], it->second.position, numParticles() );\n\t\t\t\tswitch( realType() )\n\t\t\t\t{\n\t\t\t\t\tcase Native :\n\t\t\t\t\tcase Double :\n\t\t\t\t\t\tresult = filterAttr<DoubleVectorData, DoubleVectorData>( d, particlePercentage() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Float :\n\t\t\t\t\t\tresult = filterAttr<FloatVectorData, DoubleVectorData>( d, particlePercentage() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Vector :\n\t\t\t{\n\t\t\t\tV3dDataPtr d( new V3dData );\n\t\t\t\treadElements( (double *)&d->writable(), it->second.position, 3 );\n\t\t\t\tswitch( realType() )\n\t\t\t\t{\n\t\t\t\t\tcase Native :\n\t\t\t\t\tcase Double :\n\t\t\t\t\t\tresult = d;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Float :\n\t\t\t\t\t\tresult = new V3fData( d->readable() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase VectorArray :\n\t\t\t{\n\t\t\t\tV3dVectorDataPtr d( new V3dVectorData );\n\t\t\t\t\/\/\/ \\todo\n\t\t\t\t\/\/\/ by all accounts the line below should be this :\n\t\t\t\t\/\/\/\n\t\t\t\t\/\/\/ d->writable().resize( numParticles() );\n\t\t\t\t\/\/\/\n\t\t\t\t\/\/\/ ie it shouldn't initialize the memory. but for some reason\n\t\t\t\t\/\/\/ that runs far far slower for us (at least an order of magnitude\n\t\t\t\t\/\/\/ slower) when we're in maya or python. we don't know why but it seems\n\t\t\t\t\/\/\/ to be related to libstdc++ (maya has it's own). so we're opting for\n\t\t\t\t\/\/\/ the initialized version - this seems slightly (~10%) slower when the planets\n\t\t\t\t\/\/\/ are aligned correctly, but so much faster when the planets are aligned against\n\t\t\t\t\/\/\/ us, as they seem to be whenever we're coding in maya. testing seems to show that\n\t\t\t\t\/\/\/ this resize problem only occurs with V3d, and not with V3f, or double, or even\n\t\t\t\t\/\/\/ a struct with 3 doubles in, or even a template struct with 3 doubles in.\n\t\t\t\td->writable().resize( numParticles(), V3d( 0 ) );\n\t\t\t\treadElements( (double *)&d->writable()[0], it->second.position, numParticles() * 3 );\n\t\t\t\tswitch( realType() )\n\t\t\t\t{\n\t\t\t\t\tcase Native :\n\t\t\t\t\tcase Double :\n\t\t\t\t\t\tresult = filterAttr<V3dVectorData, V3dVectorData>( d, particlePercentage() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Float :\n\t\t\t\t\t\tresult = filterAttr<V3fVectorData, V3dVectorData>( d, particlePercentage() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault :\n\t\t\tassert( it->second.type < 6 ); \/\/ unknown type\n\n\t}\n\treturn result;\n}\n\nConstDoubleVectorDataPtr PDCParticleReader::idAttribute()\n{\n\tif( !open() )\n\t{\n\t\treturn 0;\n\t}\n\tif( !m_idAttribute )\n\t{\n\t\tmap<string, Record>::const_iterator it = m_header.attributes.find( \"particleId\" );\n\t\tif( it == m_header.attributes.end() )\n\t\t{\n\t\t\tit = m_header.attributes.find( \"id\" );\n\t\t}\n\t\t\n\t\tif( it!=m_header.attributes.end() )\n\t\t{\n\t\t\tif( it->second.type==DoubleArray )\n\t\t\t{\n\t\t\t\tm_idAttribute = new DoubleVectorData;\n\t\t\t\tm_idAttribute->writable().resize( numParticles() );\n\t\t\t\treadElements( &m_idAttribute->writable()[0], it->second.position, numParticles() );\n\t\t\t}\n\t\t}\n\t}\n\treturn m_idAttribute;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n#include <fstream>\n\n#include \"paddle\/fluid\/framework\/data_type_transform.h\"\n#include \"paddle\/fluid\/framework\/op_registry.h\"\n#include \"paddle\/fluid\/platform\/device_context.h\"\n#include \"paddle\/fluid\/platform\/profiler.h\"\n\nnamespace paddle {\nnamespace operators {\n\nclass LoadOp : public framework::OperatorBase {\n public:\n LoadOp(const std::string &type, const framework::VariableNameMap &inputs,\n const framework::VariableNameMap &outputs,\n const framework::AttributeMap &attrs)\n : OperatorBase(type, inputs, outputs, attrs) {}\n\n private:\n void RunImpl(const framework::Scope &scope,\n const platform::Place &place) const override {\n auto *dev_ctx = platform::DeviceContextPool::Instance().Get(place);\n platform::RecordEvent record_event(Type(), dev_ctx);\n\n auto filename = Attr<std::string>(\"file_path\");\n std::ifstream fin(filename);\n PADDLE_ENFORCE(static_cast<bool>(fin), \"Cannot open file %s for load op\",\n filename);\n\n auto out_var_name = Output(\"Out\");\n auto *out_var = scope.FindVar(out_var_name);\n PADDLE_ENFORCE(out_var != nullptr, \"Output variable %s cannot be found\",\n out_var_name);\n\n }\n }\n\n void LoadLodTensor(const std::string &filename, const platform::Place &place,\n framework::Variable *var) const {\n auto &tensor = var->Get<framework::LoDTensor>();\n\n \/\/ get device context from pool\n platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();\n auto &dev_ctx = *pool.Get(place);\n\n \/\/ FIXME(yuyang18): We save variable to local file now, but we should change\n \/\/ it to save an output stream.\n std::ifstream fin(filename);\n PADDLE_ENFORCE(static_cast<bool>(fout), \"Cannot open %s to write\",\n filename);\n\n auto *tensor = out_var->GetMutable<framework::LoDTensor>();\n\n DeserializeFromStream(fin, tensor, *dev_ctx);\n\n auto load_as_fp16 = Attr<bool>(\"load_as_fp16\");\n auto in_dtype = framework::ToDataType(tensor->type());\n auto out_dtype = load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype;\n\n if (in_dtype != out_dtype) {\n \/\/ convert to float16 tensor\n auto in_kernel_type = framework::OpKernelType(in_dtype, place);\n auto out_kernel_type = framework::OpKernelType(out_dtype, place);\n framework::LoDTensor fp16_tensor;\n \/\/ copy LoD info to the new tensor\n fp16_tensor.set_lod(tensor->lod());\n framework::TransDataType(in_kernel_type, out_kernel_type, *tensor,\n &fp16_tensor);\n\n \/\/ reset output tensor\n out_var->Clear();\n tensor = out_var->GetMutable<framework::LoDTensor>();\n tensor->set_lod(fp16_tensor.lod());\n tensor->ShareDataWith(fp16_tensor);\n }\n\n void LoadSelectedRows(const std::string &filename,\n const framework::Scope &scope,\n const platform::Place &place,\n framework::Variable *var) const {\n\n auto &selectedRows = var->Get<framework::SelectedRows>();\n\n \/\/ get device context from pool\n platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();\n auto &dev_ctx = *pool.Get(place);\n\n \/\/ FIXME(yuyang18): We save variable to local file now, but we should change\n \/\/ it to save an output stream.\n std::ifstream fin(filename);\n PADDLE_ENFORCE(static_cast<bool>(fin), \"Cannot open %s to write\",\n filename);\n framework::DeserializeFromStream(fin, selectedRows, dev_ctx);\n }\n};\n\nclass LoadOpProtoMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddOutput(\"Out\", \"The tensor need to be loaded\");\n AddAttr<bool>(\n \"load_as_fp16\",\n \"If true, the tensor will be first loaded and then \"\n \"converted to float16 data type. Otherwise, the tensor will be \"\n \"directly loaded without data type conversion. Default is false.\")\n .SetDefault(false);\n AddAttr<std::string>(\"file_path\",\n R\"(Variable will be loaded from \"file_path\")\")\n .AddCustomChecker(\n [](const std::string &path) { return !path.empty(); });\n AddComment(\"Load operator will load a tensor variable from disk file.\");\n }\n};\n} \/\/ namespace operators\n} \/\/ namespace paddle\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(load, ops::LoadOp, ops::LoadOpProtoMaker);\n<commit_msg>load op add seletedRows<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n#include <fstream>\n\n#include \"paddle\/fluid\/framework\/data_type_transform.h\"\n#include \"paddle\/fluid\/framework\/op_registry.h\"\n#include \"paddle\/fluid\/platform\/device_context.h\"\n#include \"paddle\/fluid\/platform\/profiler.h\"\n\nnamespace paddle {\nnamespace operators {\n\nclass LoadOp : public framework::OperatorBase {\n public:\n LoadOp(const std::string &type, const framework::VariableNameMap &inputs,\n const framework::VariableNameMap &outputs,\n const framework::AttributeMap &attrs)\n : OperatorBase(type, inputs, outputs, attrs) {}\n\n private:\n void RunImpl(const framework::Scope &scope,\n const platform::Place &place) const override {\n auto *dev_ctx = platform::DeviceContextPool::Instance().Get(place);\n platform::RecordEvent record_event(Type(), dev_ctx);\n\n auto filename = Attr<std::string>(\"file_path\");\n std::ifstream fin(filename);\n PADDLE_ENFORCE(static_cast<bool>(fin), \"Cannot open file %s for load op\",\n filename);\n\n auto out_var_name = Output(\"Out\");\n auto *out_var = scope.FindVar(out_var_name);\n PADDLE_ENFORCE(out_var != nullptr, \"Output variable %s cannot be found\",\n out_var_name);\n\n if (out_var->IsType<framework::LoDTensor>()) {\n SaveLodTensor(filename, place, out_var);\n } else if (out_var->IsType<framework::SelectedRows>()) {\n SaveSelectedRows(filename, scope, place, out_var);\n } else {\n PADDLE_ENFORCE(\n false,\n \"Load only support LoDTensor and SelectedRows, %s has wrong type\",\n iname);\n }\n }\n }\n\n void LoadLodTensor(const std::string &filename, const platform::Place &place,\n framework::Variable *var) const {\n auto &tensor = var->Get<framework::LoDTensor>();\n\n \/\/ get device context from pool\n platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();\n auto &dev_ctx = *pool.Get(place);\n\n \/\/ FIXME(yuyang18): We save variable to local file now, but we should change\n \/\/ it to save an output stream.\n std::ifstream fin(filename);\n PADDLE_ENFORCE(static_cast<bool>(fout), \"Cannot open %s to write\",\n filename);\n\n auto *tensor = out_var->GetMutable<framework::LoDTensor>();\n\n DeserializeFromStream(fin, tensor, *dev_ctx);\n\n auto load_as_fp16 = Attr<bool>(\"load_as_fp16\");\n auto in_dtype = framework::ToDataType(tensor->type());\n auto out_dtype = load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype;\n\n if (in_dtype != out_dtype) {\n \/\/ convert to float16 tensor\n auto in_kernel_type = framework::OpKernelType(in_dtype, place);\n auto out_kernel_type = framework::OpKernelType(out_dtype, place);\n framework::LoDTensor fp16_tensor;\n \/\/ copy LoD info to the new tensor\n fp16_tensor.set_lod(tensor->lod());\n framework::TransDataType(in_kernel_type, out_kernel_type, *tensor,\n &fp16_tensor);\n\n \/\/ reset output tensor\n out_var->Clear();\n tensor = out_var->GetMutable<framework::LoDTensor>();\n tensor->set_lod(fp16_tensor.lod());\n tensor->ShareDataWith(fp16_tensor);\n }\n\n void LoadSelectedRows(const std::string &filename,\n const framework::Scope &scope,\n const platform::Place &place,\n framework::Variable *var) const {\n\n auto *selectedRows = var->GetMutable<framework::SelectedRows>();\n\n \/\/ get device context from pool\n platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();\n auto &dev_ctx = *pool.Get(place);\n\n \/\/ FIXME(yuyang18): We save variable to local file now, but we should change\n \/\/ it to save an output stream.\n std::ifstream fin(filename);\n PADDLE_ENFORCE(static_cast<bool>(fin), \"Cannot open %s to write\",\n filename);\n framework::DeserializeFromStream(fin, selectedRows, dev_ctx);\n }\n};\n\nclass LoadOpProtoMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddOutput(\"Out\", \"The tensor need to be loaded\");\n AddAttr<bool>(\n \"load_as_fp16\",\n \"If true, the tensor will be first loaded and then \"\n \"converted to float16 data type. Otherwise, the tensor will be \"\n \"directly loaded without data type conversion. Default is false.\")\n .SetDefault(false);\n AddAttr<std::string>(\"file_path\",\n R\"(Variable will be loaded from \"file_path\")\")\n .AddCustomChecker(\n [](const std::string &path) { return !path.empty(); });\n AddComment(\"Load operator will load a tensor variable from disk file.\");\n }\n};\n} \/\/ namespace operators\n} \/\/ namespace paddle\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(load, ops::LoadOp, ops::LoadOpProtoMaker);\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tbinsert.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2004-07-06 12:53:48 $\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\/\/ System - Includes -----------------------------------------------------\n\n#include <string> \/\/ HACK: prevent conflict between STLPORT and Workshop headers\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include <tools\/shl.hxx>\n#include <svtools\/intitem.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/viewsh.hxx>\n#include <sfx2\/viewfrm.hxx>\n#include <sfx2\/imagemgr.hxx>\n\n#include \"tbinsert.hxx\"\n#include \"tbinsert.hrc\"\n#include \"global.hxx\"\n#include \"scmod.hxx\"\n#include \"scresid.hxx\"\n#include \"sc.hrc\"\n\n\/\/ -----------------------------------------------------------------------\n\nSFX_IMPL_TOOLBOX_CONTROL( ScTbxInsertCtrl, SfxUInt16Item);\n\n\/\/------------------------------------------------------------------\n\/\/\n\/\/ ToolBox - Controller\n\/\/\n\/\/------------------------------------------------------------------\n\nScTbxInsertCtrl::ScTbxInsertCtrl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :\n SfxToolBoxControl( nSlotId, nId, rTbx ),\n nLastSlotId(0)\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n}\n\n__EXPORT ScTbxInsertCtrl::~ScTbxInsertCtrl()\n{\n}\n\nvoid __EXPORT ScTbxInsertCtrl::StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState )\n{\n GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );\n\n if( eState == SFX_ITEM_AVAILABLE )\n {\n\n const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );\n if(pItem)\n {\n nLastSlotId = pItem->GetValue();\n USHORT nImageId = nLastSlotId ? nLastSlotId : GetSlotId();\n rtl::OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( \"slot:\" ));\n aSlotURL += rtl::OUString::valueOf( sal_Int32( nImageId ));\n Image aImage = GetImage( m_xFrame,\n aSlotURL,\n hasBigImages(),\n GetToolBox().GetDisplayBackground().GetColor().IsDark() );\n\/*\n Image aImage = GetBindings().GetImageManager()->GetImage( nImageId,\n GetToolBox().GetDisplayBackground().GetColor().IsDark(),\n SC_MOD() );\n*\/\n GetToolBox().SetItemImage(GetId(), aImage);\n }\n }\n}\n\nSfxPopupWindow* __EXPORT ScTbxInsertCtrl::CreatePopupWindow()\n{\n USHORT nWinResId, nTbxResId;\n USHORT nSlotId = GetSlotId();\n if (nSlotId == SID_TBXCTL_INSERT)\n {\n rtl::OUString aInsertBarResStr( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/insertbar\" ));\n createAndPositionSubToolBar( aInsertBarResStr );\n\/\/ nWinResId = RID_TBXCTL_INSERT;\n\/\/ nTbxResId = RID_TOOLBOX_INSERT;\n }\n else if (nSlotId == SID_TBXCTL_INSCELLS)\n {\n rtl::OUString aInsertCellsBarResStr( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/insertcellsbar\" ));\n createAndPositionSubToolBar( aInsertCellsBarResStr );\n\/\/ nWinResId = RID_TBXCTL_INSCELLS;\n\/\/ nTbxResId = RID_TOOLBOX_INSCELLS;\n }\n else \/* SID_TBXCTL_INSOBJ *\/\n {\n rtl::OUString aInsertObjectBarResStr( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/insertobjectbar\" ));\n createAndPositionSubToolBar( aInsertObjectBarResStr );\n\/\/ nWinResId = RID_TBXCTL_INSOBJ;\n\/\/ nTbxResId = RID_TOOLBOX_INSOBJ;\n }\n\/*\n WindowAlign eNewAlign = ( GetToolBox().IsHorizontal() ) ? WINDOWALIGN_LEFT : WINDOWALIGN_TOP;\n ScTbxInsertPopup *pWin = new ScTbxInsertPopup( nSlotId, eNewAlign,\n ScResId(nWinResId), ScResId(nTbxResId), GetBindings() );\n pWin->StartPopupMode(&GetToolBox(), TRUE);\n pWin->StartSelection();\n pWin->Show();\n return pWin;\n*\/\n return NULL;\n}\n\nSfxPopupWindowType __EXPORT ScTbxInsertCtrl::GetPopupWindowType() const\n{\n return nLastSlotId ? SFX_POPUPWINDOW_ONTIMEOUT : SFX_POPUPWINDOW_ONCLICK;\n}\n\nvoid __EXPORT ScTbxInsertCtrl::Select( BOOL bMod1 )\n{\n SfxViewShell* pCurSh( SfxViewShell::Current() );\n SfxDispatcher* pDispatch( 0 );\n\n if ( pCurSh )\n {\n SfxViewFrame* pViewFrame = pCurSh->GetViewFrame();\n if ( pViewFrame )\n pDispatch = pViewFrame->GetDispatcher();\n }\n\n if ( pDispatch )\n pDispatch->Execute(nLastSlotId);\n}\n\/*\n\/\/------------------------------------------------------------------\n\/\/\n\/\/ Popup - Window\n\/\/\n\/\/------------------------------------------------------------------\n\nScTbxInsertPopup::ScTbxInsertPopup( USHORT nId, WindowAlign eNewAlign,\n const ResId& rRIdWin, const ResId& rRIdTbx,\n SfxBindings& rBindings ) :\n SfxPopupWindow ( nId, rRIdWin, rBindings),\n aTbx ( this, GetBindings(), rRIdTbx ),\n aRIdWinTemp(rRIdWin),\n aRIdTbxTemp(rRIdTbx)\n{\n aTbx.UseDefault();\n FreeResource();\n\n aTbx.GetToolBox().SetAlign( eNewAlign );\n if (eNewAlign == WINDOWALIGN_LEFT || eNewAlign == WINDOWALIGN_RIGHT)\n SetText( EMPTY_STRING );\n\n Size aSize = aTbx.CalcWindowSizePixel();\n aTbx.SetPosSizePixel( Point(), aSize );\n SetOutputSizePixel( aSize );\n aTbx.GetToolBox().SetSelectHdl( LINK(this, ScTbxInsertPopup, TbxSelectHdl));\n aTbxClickHdl = aTbx.GetToolBox().GetClickHdl();\n aTbx.GetToolBox().SetClickHdl( LINK(this, ScTbxInsertPopup, TbxClickHdl));\n}\n\nScTbxInsertPopup::~ScTbxInsertPopup()\n{\n}\n\nSfxPopupWindow* __EXPORT ScTbxInsertPopup::Clone() const\n{\n return new ScTbxInsertPopup( GetId(), aTbx.GetToolBox().GetAlign(),\n aRIdWinTemp, aRIdTbxTemp,\n (SfxBindings&) GetBindings() );\n}\n\nvoid ScTbxInsertPopup::StartSelection()\n{\n aTbx.GetToolBox().StartSelection();\n}\n\nIMPL_LINK(ScTbxInsertPopup, TbxSelectHdl, ToolBox*, pBox)\n{\n EndPopupMode();\n\n USHORT nLastSlotId = pBox->GetCurItemId();\n SfxUInt16Item aItem( GetId(), nLastSlotId );\n SfxDispatcher* pDisp = GetBindings().GetDispatcher();\n pDisp->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );\n pDisp->Execute( nLastSlotId, SFX_CALLMODE_ASYNCHRON );\n return 0;\n}\n\nIMPL_LINK(ScTbxInsertPopup, TbxClickHdl, ToolBox*, pBox)\n{\n USHORT nLastSlotId = pBox->GetCurItemId();\n SfxUInt16Item aItem( GetId(), nLastSlotId );\n GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );\n if(aTbxClickHdl.IsSet())\n aTbxClickHdl.Call(pBox);\n return 0;\n}\n\nvoid __EXPORT ScTbxInsertPopup::PopupModeEnd()\n{\n aTbx.GetToolBox().EndSelection();\n SfxPopupWindow::PopupModeEnd();\n}\n*\/\n\n\n<commit_msg>INTEGRATION: CWS oooicons (1.5.146); FILE MERGED 2004\/10\/29 15:45:21 cd 1.5.146.1: #i35368# Adapt code to use static sfx imagelist and removed obsolete images<commit_after>\/*************************************************************************\n *\n * $RCSfile: tbinsert.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2004-11-19 11:15: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\/\/ System - Includes -----------------------------------------------------\n\n#include <string> \/\/ HACK: prevent conflict between STLPORT and Workshop headers\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include <tools\/shl.hxx>\n#include <svtools\/intitem.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/viewsh.hxx>\n#include <sfx2\/viewfrm.hxx>\n#include <sfx2\/imagemgr.hxx>\n\n#include \"tbinsert.hxx\"\n#include \"tbinsert.hrc\"\n#include \"global.hxx\"\n#include \"scmod.hxx\"\n#include \"scresid.hxx\"\n#include \"sc.hrc\"\n\n\/\/ -----------------------------------------------------------------------\n\nSFX_IMPL_TOOLBOX_CONTROL( ScTbxInsertCtrl, SfxUInt16Item);\n\n\/\/------------------------------------------------------------------\n\/\/\n\/\/ ToolBox - Controller\n\/\/\n\/\/------------------------------------------------------------------\n\nScTbxInsertCtrl::ScTbxInsertCtrl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :\n SfxToolBoxControl( nSlotId, nId, rTbx ),\n nLastSlotId(0)\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n}\n\n__EXPORT ScTbxInsertCtrl::~ScTbxInsertCtrl()\n{\n}\n\nvoid __EXPORT ScTbxInsertCtrl::StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState )\n{\n GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );\n\n if( eState == SFX_ITEM_AVAILABLE )\n {\n\n const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );\n if(pItem)\n {\n nLastSlotId = pItem->GetValue();\n USHORT nImageId = nLastSlotId ? nLastSlotId : GetSlotId();\n rtl::OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( \"slot:\" ));\n aSlotURL += rtl::OUString::valueOf( sal_Int32( nImageId ));\n Image aImage = GetImage( m_xFrame,\n aSlotURL,\n hasBigImages(),\n GetToolBox().GetDisplayBackground().GetColor().IsDark() );\n GetToolBox().SetItemImage(GetId(), aImage);\n }\n }\n}\n\nSfxPopupWindow* __EXPORT ScTbxInsertCtrl::CreatePopupWindow()\n{\n USHORT nWinResId, nTbxResId;\n USHORT nSlotId = GetSlotId();\n if (nSlotId == SID_TBXCTL_INSERT)\n {\n rtl::OUString aInsertBarResStr( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/insertbar\" ));\n createAndPositionSubToolBar( aInsertBarResStr );\n\/\/ nWinResId = RID_TBXCTL_INSERT;\n\/\/ nTbxResId = RID_TOOLBOX_INSERT;\n }\n else if (nSlotId == SID_TBXCTL_INSCELLS)\n {\n rtl::OUString aInsertCellsBarResStr( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/insertcellsbar\" ));\n createAndPositionSubToolBar( aInsertCellsBarResStr );\n\/\/ nWinResId = RID_TBXCTL_INSCELLS;\n\/\/ nTbxResId = RID_TOOLBOX_INSCELLS;\n }\n else \/* SID_TBXCTL_INSOBJ *\/\n {\n rtl::OUString aInsertObjectBarResStr( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/insertobjectbar\" ));\n createAndPositionSubToolBar( aInsertObjectBarResStr );\n\/\/ nWinResId = RID_TBXCTL_INSOBJ;\n\/\/ nTbxResId = RID_TOOLBOX_INSOBJ;\n }\n\/*\n WindowAlign eNewAlign = ( GetToolBox().IsHorizontal() ) ? WINDOWALIGN_LEFT : WINDOWALIGN_TOP;\n ScTbxInsertPopup *pWin = new ScTbxInsertPopup( nSlotId, eNewAlign,\n ScResId(nWinResId), ScResId(nTbxResId), GetBindings() );\n pWin->StartPopupMode(&GetToolBox(), TRUE);\n pWin->StartSelection();\n pWin->Show();\n return pWin;\n*\/\n return NULL;\n}\n\nSfxPopupWindowType __EXPORT ScTbxInsertCtrl::GetPopupWindowType() const\n{\n return nLastSlotId ? SFX_POPUPWINDOW_ONTIMEOUT : SFX_POPUPWINDOW_ONCLICK;\n}\n\nvoid __EXPORT ScTbxInsertCtrl::Select( BOOL bMod1 )\n{\n SfxViewShell* pCurSh( SfxViewShell::Current() );\n SfxDispatcher* pDispatch( 0 );\n\n if ( pCurSh )\n {\n SfxViewFrame* pViewFrame = pCurSh->GetViewFrame();\n if ( pViewFrame )\n pDispatch = pViewFrame->GetDispatcher();\n }\n\n if ( pDispatch )\n pDispatch->Execute(nLastSlotId);\n}\n\/*\n\/\/------------------------------------------------------------------\n\/\/\n\/\/ Popup - Window\n\/\/\n\/\/------------------------------------------------------------------\n\nScTbxInsertPopup::ScTbxInsertPopup( USHORT nId, WindowAlign eNewAlign,\n const ResId& rRIdWin, const ResId& rRIdTbx,\n SfxBindings& rBindings ) :\n SfxPopupWindow ( nId, rRIdWin, rBindings),\n aTbx ( this, GetBindings(), rRIdTbx ),\n aRIdWinTemp(rRIdWin),\n aRIdTbxTemp(rRIdTbx)\n{\n aTbx.UseDefault();\n FreeResource();\n\n aTbx.GetToolBox().SetAlign( eNewAlign );\n if (eNewAlign == WINDOWALIGN_LEFT || eNewAlign == WINDOWALIGN_RIGHT)\n SetText( EMPTY_STRING );\n\n Size aSize = aTbx.CalcWindowSizePixel();\n aTbx.SetPosSizePixel( Point(), aSize );\n SetOutputSizePixel( aSize );\n aTbx.GetToolBox().SetSelectHdl( LINK(this, ScTbxInsertPopup, TbxSelectHdl));\n aTbxClickHdl = aTbx.GetToolBox().GetClickHdl();\n aTbx.GetToolBox().SetClickHdl( LINK(this, ScTbxInsertPopup, TbxClickHdl));\n}\n\nScTbxInsertPopup::~ScTbxInsertPopup()\n{\n}\n\nSfxPopupWindow* __EXPORT ScTbxInsertPopup::Clone() const\n{\n return new ScTbxInsertPopup( GetId(), aTbx.GetToolBox().GetAlign(),\n aRIdWinTemp, aRIdTbxTemp,\n (SfxBindings&) GetBindings() );\n}\n\nvoid ScTbxInsertPopup::StartSelection()\n{\n aTbx.GetToolBox().StartSelection();\n}\n\nIMPL_LINK(ScTbxInsertPopup, TbxSelectHdl, ToolBox*, pBox)\n{\n EndPopupMode();\n\n USHORT nLastSlotId = pBox->GetCurItemId();\n SfxUInt16Item aItem( GetId(), nLastSlotId );\n SfxDispatcher* pDisp = GetBindings().GetDispatcher();\n pDisp->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );\n pDisp->Execute( nLastSlotId, SFX_CALLMODE_ASYNCHRON );\n return 0;\n}\n\nIMPL_LINK(ScTbxInsertPopup, TbxClickHdl, ToolBox*, pBox)\n{\n USHORT nLastSlotId = pBox->GetCurItemId();\n SfxUInt16Item aItem( GetId(), nLastSlotId );\n GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );\n if(aTbxClickHdl.IsSet())\n aTbxClickHdl.Call(pBox);\n return 0;\n}\n\nvoid __EXPORT ScTbxInsertPopup::PopupModeEnd()\n{\n aTbx.GetToolBox().EndSelection();\n SfxPopupWindow::PopupModeEnd();\n}\n*\/\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Sketcher: clean up general commands tooltips<commit_after><|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk> *\n * *\n * This file is part of the FreeCAD CAx development system. *\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 *\n * GNU 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; see the file COPYING.LIB. If not, *\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\n * Suite 330, Boston, MA 02111-1307, USA *\n * *\n ***************************************************************************\/\n\n#include \"PreCompiled.h\"\n#ifndef _PreComp_\n#include <QAction>\n#include <QApplication>\n#include <QContextMenuEvent>\n#include <QGraphicsScene>\n#include <QMouseEvent>\n#include <QGraphicsSceneHoverEvent>\n#include <QPainterPathStroker>\n#include <QPainter>\n#include <QStyleOptionGraphicsItem>\n#include <QBitmap>\n#include <QFile>\n#include <QFileInfo>\n#endif\n\n#include <QFile>\n#include <QTextStream>\n#include <QRectF>\n#include <QPointF>\n\n#include <cmath>\n\n#include <App\/Application.h>\n#include <App\/Material.h>\n#include <Base\/Console.h>\n#include <Base\/Parameter.h>\n\n#include <Mod\/TechDraw\/App\/DrawUtil.h>\n\n#include \"Rez.h\"\n#include \"QGCustomSvg.h\"\n#include \"QGCustomRect.h\"\n#include \"QGIFace.h\"\n\nusing namespace TechDrawGui;\nusing namespace TechDraw;\n\nQGIFace::QGIFace(int index) :\n projIndex(index),\n m_colDefFill(Qt::white), \/\/Qt::transparent? paper colour?\n m_styleDef(Qt::SolidPattern),\n m_styleSelect(Qt::SolidPattern)\n{\n setFillMode(NoFill);\n isHatched(false);\n setFlag(QGraphicsItem::ItemClipsChildrenToShape,true);\n\n \/\/setStyle(Qt::NoPen); \/\/don't draw face lines, just fill for debugging\n setStyle(Qt::DashLine);\n\n m_styleNormal = m_styleDef;\n m_fillStyle = m_styleDef;\n m_colNormalFill = m_colDefFill;\n m_geomColor = QColor(Qt::black);\n setLineWeight(0.5); \/\/0 = cosmetic\n \n setPrettyNormal();\n m_texture = nullptr; \/\/empty texture\n\n m_svg = new QGCustomSvg();\n\n m_rect = new QGCustomRect();\n m_rect->setParentItem(this);\n\n m_svgCol = SVGCOLDEFAULT;\n m_fillScale = 1.0;\n}\n\nQGIFace::~QGIFace()\n{\n \/\/nothing to do. every item is a child of QGIFace & will get removed\/deleted when QGIF is deleted\n}\n\nvoid QGIFace::draw() \n{\n setPath(m_outline); \/\/Face boundary\n\n if (isHatched()) { \n if (m_mode == GeomHatchFill) { \/\/crosshatch\n if (!m_geomHatchPaths.empty()) { \/\/surrogate for LineSets.empty\n m_brush.setTexture(nullptr);\n m_fillStyle = m_styleDef;\n m_styleNormal = m_fillStyle;\n int pathNo = 0;\n for (auto& pp: m_geomHatchPaths) {\n QGraphicsPathItem* fillItem = m_fillItems.at(pathNo); \n fillItem->setPath(pp); \n QPen geomPen = setGeomPen(pathNo);\n fillItem->setPen(geomPen);\n pathNo++;\n }\n }\n } else if ((m_mode == FromFile) ||\n (m_mode == SvgFill) ||\n (m_mode == BitmapFill)) { \n QFileInfo hfi(QString::fromUtf8(m_fileSpec.data(),m_fileSpec.size()));\n if (hfi.isReadable()) {\n QString ext = hfi.suffix();\n if (ext.toUpper() == QString::fromUtf8(\"SVG\")) {\n setFillMode(SvgFill);\n m_brush.setTexture(nullptr);\n m_fillStyle = m_styleDef;\n m_styleNormal = m_fillStyle;\n loadSvgHatch(m_fileSpec);\n buildSvgHatch();\n toggleSvg(true);\n } else if ((ext.toUpper() == QString::fromUtf8(\"JPG\")) ||\n (ext.toUpper() == QString::fromUtf8(\"PNG\")) ||\n (ext.toUpper() == QString::fromUtf8(\"JPEG\")) ||\n (ext.toUpper() == QString::fromUtf8(\"BMP\")) ) {\n setFillMode(BitmapFill);\n toggleSvg(false);\n m_fillStyle = Qt::TexturePattern;\n m_texture = textureFromBitmap(m_fileSpec);\n m_brush.setTexture(m_texture);\n }\n }\n }\n }\n show();\n}\n\nvoid QGIFace::setPrettyNormal() {\n if (isHatched() &&\n (m_mode == BitmapFill) ) { \/\/hatch with bitmap fill\n m_fillStyle = Qt::TexturePattern;\n m_brush.setTexture(m_texture);\n } else {\n m_fillStyle = m_styleNormal;\n m_brush.setTexture(nullptr);\n m_brush.setStyle(m_fillStyle);\n m_fillColor = m_colNormalFill;\n }\n QGIPrimPath::setPrettyNormal();\n}\n\nvoid QGIFace::setPrettyPre() {\n m_brush.setTexture(nullptr);\n m_fillStyle = m_styleSelect;\n m_fillColor = getPreColor();\n QGIPrimPath::setPrettyPre();\n}\n\nvoid QGIFace::setPrettySel() {\n m_brush.setTexture(nullptr);\n m_fillStyle = m_styleSelect;\n m_fillColor = getSelectColor();\n QGIPrimPath::setPrettySel();\n}\n\nvoid QGIFace::setDrawEdges(bool b) {\n if (b) {\n setStyle(Qt::DashLine);\n } else {\n setStyle(Qt::NoPen); \/\/don't draw face lines, just fill\n }\n}\n\nvoid QGIFace::setHatchFile(std::string fileSpec)\n{\n m_fileSpec = fileSpec;\n} \n \nvoid QGIFace::loadSvgHatch(std::string fileSpec)\n{\n QString qfs(QString::fromUtf8(fileSpec.data(),fileSpec.size()));\n QFile f(qfs);\n if (!f.open(QFile::ReadOnly | QFile::Text)) {\n Base::Console().Error(\"QGIFace could not read %s\\n\",fileSpec.c_str());\n return;\n }\n m_svgXML = f.readAll();\n if (!m_svg->load(&m_svgXML)) {\n Base::Console().Error(\"Error - Could not load hatch into SVG renderer for %s\\n\", fileSpec.c_str());\n return;\n }\n}\n\nvoid QGIFace::setFillMode(QGIFace::fillMode m)\n{\n m_mode = m;\n if ((m_mode == NoFill) ||\n (m_mode == PlainFill)) {\n isHatched(false);\n } else {\n isHatched(true);\n }\n}\n\nvoid QGIFace::setOutline(const QPainterPath & path)\n{\n m_outline = path;\n}\n\nvoid QGIFace::clearLineSets(void) \n{\n m_geomHatchPaths.clear();\n m_dashSpecs.clear();\n clearFillItems();\n}\n\n\/\/each line set needs a painterpath, a dashspec and a QGPItem to show them\nvoid QGIFace::addLineSet(QPainterPath pp, std::vector<double> dp)\n{\n m_geomHatchPaths.push_back(pp);\n m_dashSpecs.push_back(DashSpec(dp));\n addFillItem();\n} \n\nQGraphicsPathItem* QGIFace::addFillItem()\n{\n QGraphicsPathItem* fillItem = new QGraphicsPathItem();\n fillItem->setParentItem(this);\n m_fillItems.push_back(fillItem);\n return fillItem;\n}\n \nvoid QGIFace::clearFillItems(void)\n{\n for (auto& f: m_fillItems) {\n f->setParentItem(nullptr);\n this->scene()->removeItem(f);\n delete f;\n }\n}\n\n\/\/convert from PAT style \"-1,0,-1,+1\" to Qt style \"mark,space,mark,space\"\nQVector<qreal> QGIFace::decodeDashSpec(DashSpec patDash)\n{\n \/\/Rez::guiX(something)?\n double dotLength = 3.0;\n double unitLength = 6.0;\n\/\/ double penWidth = m_geomWeight; \/\/mark, space and dot lengths are to be in terms of penWidth(Qt) or mm(PAT)??\n\/\/ \/\/if we want it in terms of mm, we need to divide by penWidth?\n\/\/ double minPen = 0.01; \/\/avoid trouble with cosmetic pen (zero width)\n std::vector<double> result;\n std::string prim;\n for (auto& d: patDash.get()) {\n double strokeLength;\n if (DrawUtil::fpCompare(d,0.0)) { \/\/pat dot\n strokeLength = dotLength;\n } else if (Rez::guiX(d) < 0) { \/\/pat space\n strokeLength = fabs(Rez::guiX(d)) * unitLength;\n } else { \/\/pat dash\n strokeLength = Rez::guiX(d) * unitLength;\n }\n result.push_back(strokeLength);\n }\n return QVector<qreal>::fromStdVector( result ); \n}\n\n\nQPen QGIFace::setGeomPen(int i)\n{\n \/\/m_dashSpecs[i].dump(\"spec test\");\n DashSpec ourSpec = m_dashSpecs.at(i);\n \/\/ourSpec.dump(\"our spec\");\n \n QPen result;\n result.setWidthF(Rez::guiX(m_geomWeight)); \/\/Rez::guiX() ?? line weights are in mm?\n result.setColor(m_geomColor);\n if (ourSpec.empty()) {\n result.setStyle(Qt::SolidLine);\n } else {\n result.setStyle(Qt::CustomDashLine);\n result.setDashPattern(decodeDashSpec(ourSpec));\n }\n return result;\n}\n\nvoid QGIFace::buildSvgHatch()\n{\n double wTile = SVGSIZEW * m_fillScale;\n double hTile = SVGSIZEH * m_fillScale;\n double w = m_outline.boundingRect().width();\n double h = m_outline.boundingRect().height();\n QRectF r = m_outline.boundingRect();\n QPointF fCenter = r.center();\n double nw = ceil(w \/ wTile);\n double nh = ceil(h \/ hTile);\n w = nw * wTile;\n h = nh * hTile;\n m_rect->setRect(0.,0.,w,-h);\n m_rect->centerAt(fCenter);\n r = m_rect->rect();\n QByteArray before,after;\n before.append(QString::fromStdString(SVGCOLPREFIX + SVGCOLDEFAULT));\n after.append(QString::fromStdString(SVGCOLPREFIX + m_svgCol));\n QByteArray colorXML = m_svgXML.replace(before,after);\n for (int iw = 0; iw < int(nw); iw++) {\n for (int ih = 0; ih < int(nh); ih++) {\n QGCustomSvg* tile = new QGCustomSvg();\n tile->setScale(m_fillScale);\n if (tile->load(&colorXML)) {\n tile->setParentItem(m_rect);\n tile->setPos(iw*wTile,-h + ih*hTile);\n }\n }\n }\n}\n\nvoid QGIFace::clearSvg()\n{\n toggleSvg(false);\n}\n\n\/\/this isn't used currently\nQPixmap QGIFace::textureFromSvg(std::string fileSpec)\n{\n QPixmap result;\n QString qs(QString::fromStdString(fileSpec));\n QFileInfo ffi(qs);\n if (ffi.isReadable()) {\n QSvgRenderer renderer(qs);\n QPixmap pixMap(renderer.defaultSize());\n pixMap.fill(Qt::white); \/\/try Qt::transparent?\n QPainter painter(&pixMap);\n renderer.render(&painter); \/\/svg texture -> bitmap\n result = pixMap.scaled(m_fillScale,m_fillScale);\n } \/\/else return empty pixmap\n return result;\n}\n\nvoid QGIFace::setHatchColor(App::Color c)\n{\n m_svgCol = c.asCSSString();\n m_geomColor = c.asValue<QColor>();\n}\n\nvoid QGIFace::setHatchScale(double s)\n{\n m_fillScale = s;\n}\n\n\/\/QtSvg does not handle clipping, so we must be able to turn the hatching on\/off\nvoid QGIFace::toggleSvg(bool b)\n{\n if (b) {\n m_rect->show();\n } else {\n m_rect->hide();\n }\n update();\n}\n\nQPixmap QGIFace::textureFromBitmap(std::string fileSpec)\n{\n QPixmap pix;\n QString qs = QString::fromUtf8(fileSpec.data(),fileSpec.size());\n QFileInfo ffi(qs);\n if (ffi.isReadable()) {\n QImage img = QImage(qs);\n img = img.scaled(Rez::guiX(m_fillScale),Rez::guiX(m_fillScale));\n pix = QPixmap::fromImage(img);\n }\n return pix;\n}\n\nvoid QGIFace::setFill(QColor c, Qt::BrushStyle s) {\n m_colNormalFill = c;\n m_styleNormal = s;\n}\n\nvoid QGIFace::setFill(QBrush b) {\n m_colNormalFill = b.color();\n m_styleNormal = b.style();\n}\n\nvoid QGIFace::resetFill() {\n m_colNormalFill = m_colDefFill;\n m_styleNormal = m_styleDef;\n}\n\nvoid QGIFace::setLineWeight(double w) {\n m_geomWeight = w;\n}\n\n\nQRectF QGIFace::boundingRect() const\n{\n return shape().controlPointRect();\n}\n\nQPainterPath QGIFace::shape() const\n{\n return path();\n}\n\nvoid QGIFace::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) {\n QStyleOptionGraphicsItem myOption(*option);\n myOption.state &= ~QStyle::State_Selected;\n\n m_brush.setStyle(m_fillStyle);\n m_brush.setColor(m_fillColor);\n setBrush(m_brush);\n QGIPrimPath::paint (painter, &myOption, widget);\n}\n\n<commit_msg>can't assign nullptr to a QPixmap<commit_after>\/***************************************************************************\n * Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk> *\n * *\n * This file is part of the FreeCAD CAx development system. *\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 *\n * GNU 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; see the file COPYING.LIB. If not, *\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\n * Suite 330, Boston, MA 02111-1307, USA *\n * *\n ***************************************************************************\/\n\n#include \"PreCompiled.h\"\n#ifndef _PreComp_\n#include <QAction>\n#include <QApplication>\n#include <QContextMenuEvent>\n#include <QGraphicsScene>\n#include <QMouseEvent>\n#include <QGraphicsSceneHoverEvent>\n#include <QPainterPathStroker>\n#include <QPainter>\n#include <QStyleOptionGraphicsItem>\n#include <QBitmap>\n#include <QFile>\n#include <QFileInfo>\n#endif\n\n#include <QFile>\n#include <QTextStream>\n#include <QRectF>\n#include <QPointF>\n\n#include <cmath>\n\n#include <App\/Application.h>\n#include <App\/Material.h>\n#include <Base\/Console.h>\n#include <Base\/Parameter.h>\n\n#include <Mod\/TechDraw\/App\/DrawUtil.h>\n\n#include \"Rez.h\"\n#include \"QGCustomSvg.h\"\n#include \"QGCustomRect.h\"\n#include \"QGIFace.h\"\n\nusing namespace TechDrawGui;\nusing namespace TechDraw;\n\nQGIFace::QGIFace(int index) :\n projIndex(index),\n m_colDefFill(Qt::white), \/\/Qt::transparent? paper colour?\n m_styleDef(Qt::SolidPattern),\n m_styleSelect(Qt::SolidPattern)\n{\n setFillMode(NoFill);\n isHatched(false);\n setFlag(QGraphicsItem::ItemClipsChildrenToShape,true);\n\n \/\/setStyle(Qt::NoPen); \/\/don't draw face lines, just fill for debugging\n setStyle(Qt::DashLine);\n\n m_styleNormal = m_styleDef;\n m_fillStyle = m_styleDef;\n m_colNormalFill = m_colDefFill;\n m_geomColor = QColor(Qt::black);\n setLineWeight(0.5); \/\/0 = cosmetic\n \n setPrettyNormal();\n m_texture = QPixmap(); \/\/empty texture\n\n m_svg = new QGCustomSvg();\n\n m_rect = new QGCustomRect();\n m_rect->setParentItem(this);\n\n m_svgCol = SVGCOLDEFAULT;\n m_fillScale = 1.0;\n}\n\nQGIFace::~QGIFace()\n{\n \/\/nothing to do. every item is a child of QGIFace & will get removed\/deleted when QGIF is deleted\n}\n\nvoid QGIFace::draw() \n{\n setPath(m_outline); \/\/Face boundary\n\n if (isHatched()) { \n if (m_mode == GeomHatchFill) { \/\/crosshatch\n if (!m_geomHatchPaths.empty()) { \/\/surrogate for LineSets.empty\n m_brush.setTexture(QPixmap());\n m_fillStyle = m_styleDef;\n m_styleNormal = m_fillStyle;\n int pathNo = 0;\n for (auto& pp: m_geomHatchPaths) {\n QGraphicsPathItem* fillItem = m_fillItems.at(pathNo); \n fillItem->setPath(pp); \n QPen geomPen = setGeomPen(pathNo);\n fillItem->setPen(geomPen);\n pathNo++;\n }\n }\n } else if ((m_mode == FromFile) ||\n (m_mode == SvgFill) ||\n (m_mode == BitmapFill)) { \n QFileInfo hfi(QString::fromUtf8(m_fileSpec.data(),m_fileSpec.size()));\n if (hfi.isReadable()) {\n QString ext = hfi.suffix();\n if (ext.toUpper() == QString::fromUtf8(\"SVG\")) {\n setFillMode(SvgFill);\n m_brush.setTexture(QPixmap());\n m_fillStyle = m_styleDef;\n m_styleNormal = m_fillStyle;\n loadSvgHatch(m_fileSpec);\n buildSvgHatch();\n toggleSvg(true);\n } else if ((ext.toUpper() == QString::fromUtf8(\"JPG\")) ||\n (ext.toUpper() == QString::fromUtf8(\"PNG\")) ||\n (ext.toUpper() == QString::fromUtf8(\"JPEG\")) ||\n (ext.toUpper() == QString::fromUtf8(\"BMP\")) ) {\n setFillMode(BitmapFill);\n toggleSvg(false);\n m_fillStyle = Qt::TexturePattern;\n m_texture = textureFromBitmap(m_fileSpec);\n m_brush.setTexture(m_texture);\n }\n }\n }\n }\n show();\n}\n\nvoid QGIFace::setPrettyNormal() {\n if (isHatched() &&\n (m_mode == BitmapFill) ) { \/\/hatch with bitmap fill\n m_fillStyle = Qt::TexturePattern;\n m_brush.setTexture(m_texture);\n } else {\n m_fillStyle = m_styleNormal;\n m_brush.setTexture(QPixmap());\n m_brush.setStyle(m_fillStyle);\n m_fillColor = m_colNormalFill;\n }\n QGIPrimPath::setPrettyNormal();\n}\n\nvoid QGIFace::setPrettyPre() {\n m_brush.setTexture(QPixmap());\n m_fillStyle = m_styleSelect;\n m_fillColor = getPreColor();\n QGIPrimPath::setPrettyPre();\n}\n\nvoid QGIFace::setPrettySel() {\n m_brush.setTexture(QPixmap());\n m_fillStyle = m_styleSelect;\n m_fillColor = getSelectColor();\n QGIPrimPath::setPrettySel();\n}\n\nvoid QGIFace::setDrawEdges(bool b) {\n if (b) {\n setStyle(Qt::DashLine);\n } else {\n setStyle(Qt::NoPen); \/\/don't draw face lines, just fill\n }\n}\n\nvoid QGIFace::setHatchFile(std::string fileSpec)\n{\n m_fileSpec = fileSpec;\n} \n \nvoid QGIFace::loadSvgHatch(std::string fileSpec)\n{\n QString qfs(QString::fromUtf8(fileSpec.data(),fileSpec.size()));\n QFile f(qfs);\n if (!f.open(QFile::ReadOnly | QFile::Text)) {\n Base::Console().Error(\"QGIFace could not read %s\\n\",fileSpec.c_str());\n return;\n }\n m_svgXML = f.readAll();\n if (!m_svg->load(&m_svgXML)) {\n Base::Console().Error(\"Error - Could not load hatch into SVG renderer for %s\\n\", fileSpec.c_str());\n return;\n }\n}\n\nvoid QGIFace::setFillMode(QGIFace::fillMode m)\n{\n m_mode = m;\n if ((m_mode == NoFill) ||\n (m_mode == PlainFill)) {\n isHatched(false);\n } else {\n isHatched(true);\n }\n}\n\nvoid QGIFace::setOutline(const QPainterPath & path)\n{\n m_outline = path;\n}\n\nvoid QGIFace::clearLineSets(void) \n{\n m_geomHatchPaths.clear();\n m_dashSpecs.clear();\n clearFillItems();\n}\n\n\/\/each line set needs a painterpath, a dashspec and a QGPItem to show them\nvoid QGIFace::addLineSet(QPainterPath pp, std::vector<double> dp)\n{\n m_geomHatchPaths.push_back(pp);\n m_dashSpecs.push_back(DashSpec(dp));\n addFillItem();\n} \n\nQGraphicsPathItem* QGIFace::addFillItem()\n{\n QGraphicsPathItem* fillItem = new QGraphicsPathItem();\n fillItem->setParentItem(this);\n m_fillItems.push_back(fillItem);\n return fillItem;\n}\n \nvoid QGIFace::clearFillItems(void)\n{\n for (auto& f: m_fillItems) {\n f->setParentItem(nullptr);\n this->scene()->removeItem(f);\n delete f;\n }\n}\n\n\/\/convert from PAT style \"-1,0,-1,+1\" to Qt style \"mark,space,mark,space\"\nQVector<qreal> QGIFace::decodeDashSpec(DashSpec patDash)\n{\n \/\/Rez::guiX(something)?\n double dotLength = 3.0;\n double unitLength = 6.0;\n\/\/ double penWidth = m_geomWeight; \/\/mark, space and dot lengths are to be in terms of penWidth(Qt) or mm(PAT)??\n\/\/ \/\/if we want it in terms of mm, we need to divide by penWidth?\n\/\/ double minPen = 0.01; \/\/avoid trouble with cosmetic pen (zero width)\n std::vector<double> result;\n std::string prim;\n for (auto& d: patDash.get()) {\n double strokeLength;\n if (DrawUtil::fpCompare(d,0.0)) { \/\/pat dot\n strokeLength = dotLength;\n } else if (Rez::guiX(d) < 0) { \/\/pat space\n strokeLength = fabs(Rez::guiX(d)) * unitLength;\n } else { \/\/pat dash\n strokeLength = Rez::guiX(d) * unitLength;\n }\n result.push_back(strokeLength);\n }\n return QVector<qreal>::fromStdVector( result ); \n}\n\n\nQPen QGIFace::setGeomPen(int i)\n{\n \/\/m_dashSpecs[i].dump(\"spec test\");\n DashSpec ourSpec = m_dashSpecs.at(i);\n \/\/ourSpec.dump(\"our spec\");\n \n QPen result;\n result.setWidthF(Rez::guiX(m_geomWeight)); \/\/Rez::guiX() ?? line weights are in mm?\n result.setColor(m_geomColor);\n if (ourSpec.empty()) {\n result.setStyle(Qt::SolidLine);\n } else {\n result.setStyle(Qt::CustomDashLine);\n result.setDashPattern(decodeDashSpec(ourSpec));\n }\n return result;\n}\n\nvoid QGIFace::buildSvgHatch()\n{\n double wTile = SVGSIZEW * m_fillScale;\n double hTile = SVGSIZEH * m_fillScale;\n double w = m_outline.boundingRect().width();\n double h = m_outline.boundingRect().height();\n QRectF r = m_outline.boundingRect();\n QPointF fCenter = r.center();\n double nw = ceil(w \/ wTile);\n double nh = ceil(h \/ hTile);\n w = nw * wTile;\n h = nh * hTile;\n m_rect->setRect(0.,0.,w,-h);\n m_rect->centerAt(fCenter);\n r = m_rect->rect();\n QByteArray before,after;\n before.append(QString::fromStdString(SVGCOLPREFIX + SVGCOLDEFAULT));\n after.append(QString::fromStdString(SVGCOLPREFIX + m_svgCol));\n QByteArray colorXML = m_svgXML.replace(before,after);\n for (int iw = 0; iw < int(nw); iw++) {\n for (int ih = 0; ih < int(nh); ih++) {\n QGCustomSvg* tile = new QGCustomSvg();\n tile->setScale(m_fillScale);\n if (tile->load(&colorXML)) {\n tile->setParentItem(m_rect);\n tile->setPos(iw*wTile,-h + ih*hTile);\n }\n }\n }\n}\n\nvoid QGIFace::clearSvg()\n{\n toggleSvg(false);\n}\n\n\/\/this isn't used currently\nQPixmap QGIFace::textureFromSvg(std::string fileSpec)\n{\n QPixmap result;\n QString qs(QString::fromStdString(fileSpec));\n QFileInfo ffi(qs);\n if (ffi.isReadable()) {\n QSvgRenderer renderer(qs);\n QPixmap pixMap(renderer.defaultSize());\n pixMap.fill(Qt::white); \/\/try Qt::transparent?\n QPainter painter(&pixMap);\n renderer.render(&painter); \/\/svg texture -> bitmap\n result = pixMap.scaled(m_fillScale,m_fillScale);\n } \/\/else return empty pixmap\n return result;\n}\n\nvoid QGIFace::setHatchColor(App::Color c)\n{\n m_svgCol = c.asCSSString();\n m_geomColor = c.asValue<QColor>();\n}\n\nvoid QGIFace::setHatchScale(double s)\n{\n m_fillScale = s;\n}\n\n\/\/QtSvg does not handle clipping, so we must be able to turn the hatching on\/off\nvoid QGIFace::toggleSvg(bool b)\n{\n if (b) {\n m_rect->show();\n } else {\n m_rect->hide();\n }\n update();\n}\n\nQPixmap QGIFace::textureFromBitmap(std::string fileSpec)\n{\n QPixmap pix;\n QString qs = QString::fromUtf8(fileSpec.data(),fileSpec.size());\n QFileInfo ffi(qs);\n if (ffi.isReadable()) {\n QImage img = QImage(qs);\n img = img.scaled(Rez::guiX(m_fillScale),Rez::guiX(m_fillScale));\n pix = QPixmap::fromImage(img);\n }\n return pix;\n}\n\nvoid QGIFace::setFill(QColor c, Qt::BrushStyle s) {\n m_colNormalFill = c;\n m_styleNormal = s;\n}\n\nvoid QGIFace::setFill(QBrush b) {\n m_colNormalFill = b.color();\n m_styleNormal = b.style();\n}\n\nvoid QGIFace::resetFill() {\n m_colNormalFill = m_colDefFill;\n m_styleNormal = m_styleDef;\n}\n\nvoid QGIFace::setLineWeight(double w) {\n m_geomWeight = w;\n}\n\n\nQRectF QGIFace::boundingRect() const\n{\n return shape().controlPointRect();\n}\n\nQPainterPath QGIFace::shape() const\n{\n return path();\n}\n\nvoid QGIFace::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) {\n QStyleOptionGraphicsItem myOption(*option);\n myOption.state &= ~QStyle::State_Selected;\n\n m_brush.setStyle(m_fillStyle);\n m_brush.setColor(m_fillColor);\n setBrush(m_brush);\n QGIPrimPath::paint (painter, &myOption, widget);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n*@file\n *\/\n#pragma once\n\n#include \"numbirch\/utility.hpp\"\n#include \"numbirch\/cuda\/cuda.hpp\"\n#include \"numbirch\/cuda\/curand.hpp\"\n\nnamespace numbirch {\n\nstruct simulate_bernoulli_functor {\n curandState_t* rngs;\n simulate_bernoulli_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE bool operator()(const real rho) {\n #ifndef __CUDA_ARCH__\n return std::bernoulli_distribution(rho)(stl<bool>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_uniform_double(curand_rng(rngs)) <= rho;\n } else {\n return curand_uniform(curand_rng(rngs)) <= rho;\n }\n #endif\n }\n};\n\nstruct simulate_beta_functor {\n curandState_t* rngs;\n simulate_beta_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real alpha, const real beta) {\n real u, v;\n #ifndef __CUDA_ARCH__\n auto& rng = stl<real>::rng();\n u = std::gamma_distribution<real>(alpha)(rng);\n v = std::gamma_distribution<real>(beta)(rng);\n #else\n if constexpr (std::is_same_v<real,double>) {\n u = curand_gamma_double(curand_rng(rngs), alpha);\n v = curand_gamma_double(curand_rng(rngs), beta);\n } else {\n u = curand_gamma(curand_rng(rngs), alpha);\n v = curand_gamma(curand_rng(rngs), beta);\n }\n #endif\n return u\/(u + v);\n }\n};\n\nstruct simulate_binomial_functor {\n curandState_t* rngs;\n simulate_binomial_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE int operator()(const real n, const real rho) {\n #ifndef __CUDA_ARCH__\n return std::binomial_distribution<int>(n, rho)(stl<int>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_binomial_double(curand_rng(rngs), n, rho);\n } else {\n return curand_binomial(curand_rng(rngs), n, rho);\n }\n #endif\n }\n};\n\nstruct simulate_chi_squared_functor {\n curandState_t* rngs;\n simulate_chi_squared_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real nu) {\n #ifndef __CUDA_ARCH__\n return std::chi_squared_distribution<real>(nu)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return real(2.0)*curand_gamma_double(curand_rng(rngs), real(0.5)*nu);\n } else {\n return real(2.0)*curand_gamma(curand_rng(rngs), real(0.5)*nu);\n }\n #endif\n }\n};\n\nstruct simulate_exponential_functor {\n curandState_t* rngs;\n simulate_exponential_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real lambda) {\n #ifndef __CUDA_ARCH__\n return std::exponential_distribution<real>(lambda)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return -std::log(curand_uniform_double(curand_rng(rngs)))\/lambda;\n } else {\n return -std::log(curand_uniform(curand_rng(rngs)))\/lambda;\n }\n #endif\n }\n};\n\nstruct simulate_gamma_functor {\n curandState_t* rngs;\n simulate_gamma_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real k, const real theta) {\n #ifndef __CUDA_ARCH__\n return std::gamma_distribution<real>(k, theta)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_gamma(curand_rng(rngs), k)*theta;\n } else {\n return curand_gamma_double(curand_rng(rngs), k)*theta;\n }\n #endif\n }\n};\n\nstruct simulate_gaussian_functor {\n curandState_t* rngs;\n simulate_gaussian_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real mu, const real sigma2) {\n #ifndef __CUDA_ARCH__\n return std::normal_distribution<real>(mu, std::sqrt(sigma2))(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return mu + std::sqrt(sigma2)*curand_normal_double(curand_rng(rngs));\n } else {\n return mu + std::sqrt(sigma2)*curand_normal(curand_rng(rngs));\n }\n #endif\n }\n};\n\nstruct simulate_negative_binomial_functor {\n curandState_t* rngs;\n simulate_negative_binomial_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real k, const real rho) {\n #ifndef __CUDA_ARCH__\n return std::negative_binomial_distribution<int>(k, rho)(stl<real>::rng());\n \/\/ ^ negative_binomial_distribution requires integral type\n #else\n real theta, lambda;\n theta = (real(1.0) - rho)\/rho;\n if constexpr (std::is_same_v<real,double>) {\n lambda = curand_gamma_double(curand_rng(rngs), k);\n } else {\n lambda = curand_gamma(curand_rng(rngs), k);\n }\n return curand_poisson(curand_rng(rngs), lambda*theta);\n #endif\n }\n};\n\nstruct simulate_poisson_functor {\n curandState_t* rngs;\n simulate_poisson_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE int operator()(const real lambda) {\n #ifndef __CUDA_ARCH__\n return std::poisson_distribution<int>(lambda)(stl<real>::rng());\n \/\/ ^ poisson_distribution requires integral type\n #else\n return curand_poisson(curand_rng(rngs), lambda);\n #endif\n }\n};\n\nstruct simulate_uniform_functor {\n curandState_t* rngs;\n simulate_uniform_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real l, const real u) {\n #ifndef __CUDA_ARCH__\n return std::uniform_real_distribution<real>(l, u)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return l + (u - l)*curand_uniform_double(curand_rng(rngs));\n } else {\n return l + (u - l)*curand_uniform(curand_rng(rngs));\n }\n #endif\n }\n};\n\nstruct simulate_uniform_int_functor {\n curandState_t* rngs;\n simulate_uniform_int_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE int operator()(const int l, const int u) {\n #ifndef __CUDA_ARCH__\n return std::uniform_int_distribution<int>(l, u)(stl<int>::rng());\n \/\/ ^ uniform_int_distribution requires integral type\n #else\n return int(l + (u - l + 1)*curand_uniform(curand_rng(rngs)));\n #endif\n }\n};\n\nstruct simulate_weibull_functor {\n curandState_t* rngs;\n simulate_weibull_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real k, const real lambda) {\n #ifndef __CUDA_ARCH__\n return std::weibull_distribution<real>(k, lambda)(stl<real>::rng());\n #else\n real u;\n if constexpr (std::is_same_v<real,double>) {\n u = curand_uniform_double(curand_rng(rngs));\n } else {\n u = curand_uniform(curand_rng(rngs));\n }\n return lambda*std::pow(-std::log(real(1.0) - u), real(1.0)\/k);\n #endif\n }\n};\n\nstruct standard_gaussian_functor {\n curandState_t* rngs;\n standard_gaussian_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const int i, const int j) {\n #ifndef __CUDA_ARCH__\n return std::normal_distribution<real>()(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_normal_double(curand_rng(rngs));\n } else {\n return curand_normal(curand_rng(rngs));\n }\n #endif\n }\n};\n\ntemplate<class T>\nstruct standard_wishart_functor {\n T k;\n int n;\n curandState_t* rngs;\n standard_wishart_functor(const T& k, const int n) :\n k(k),\n n(n),\n rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const int i, const int j) {\n if (i == j) {\n \/* on diagonal *\/\n real nu = get(k) + (n - 1 - i); \/\/ i is 0-based here\n real x;\n #ifndef __CUDA_ARCH__\n x = std::chi_squared_distribution<real>(nu)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n x = real(2.0)*curand_gamma_double(curand_rng(rngs), real(0.5)*nu);\n } else {\n x = real(2.0)*curand_gamma(curand_rng(rngs), real(0.5)*nu);\n }\n #endif\n return std::sqrt(x);\n } else if (i > j) {\n \/* in lower triangle *\/\n #ifndef __CUDA_ARCH__\n return std::normal_distribution<real>()(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_normal_double(curand_rng(rngs));\n } else {\n return curand_normal(curand_rng(rngs));\n }\n #endif\n } else {\n \/* in upper triangle *\/\n return real(0.0);\n }\n }\n};\n\n}\n<commit_msg>Added double code path for simulate_uniform_int().<commit_after>\/**\n*@file\n *\/\n#pragma once\n\n#include \"numbirch\/utility.hpp\"\n#include \"numbirch\/cuda\/cuda.hpp\"\n#include \"numbirch\/cuda\/curand.hpp\"\n\nnamespace numbirch {\n\nstruct simulate_bernoulli_functor {\n curandState_t* rngs;\n simulate_bernoulli_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE bool operator()(const real rho) {\n #ifndef __CUDA_ARCH__\n return std::bernoulli_distribution(rho)(stl<bool>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_uniform_double(curand_rng(rngs)) <= rho;\n } else {\n return curand_uniform(curand_rng(rngs)) <= rho;\n }\n #endif\n }\n};\n\nstruct simulate_beta_functor {\n curandState_t* rngs;\n simulate_beta_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real alpha, const real beta) {\n real u, v;\n #ifndef __CUDA_ARCH__\n auto& rng = stl<real>::rng();\n u = std::gamma_distribution<real>(alpha)(rng);\n v = std::gamma_distribution<real>(beta)(rng);\n #else\n if constexpr (std::is_same_v<real,double>) {\n u = curand_gamma_double(curand_rng(rngs), alpha);\n v = curand_gamma_double(curand_rng(rngs), beta);\n } else {\n u = curand_gamma(curand_rng(rngs), alpha);\n v = curand_gamma(curand_rng(rngs), beta);\n }\n #endif\n return u\/(u + v);\n }\n};\n\nstruct simulate_binomial_functor {\n curandState_t* rngs;\n simulate_binomial_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE int operator()(const real n, const real rho) {\n #ifndef __CUDA_ARCH__\n return std::binomial_distribution<int>(n, rho)(stl<int>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_binomial_double(curand_rng(rngs), n, rho);\n } else {\n return curand_binomial(curand_rng(rngs), n, rho);\n }\n #endif\n }\n};\n\nstruct simulate_chi_squared_functor {\n curandState_t* rngs;\n simulate_chi_squared_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real nu) {\n #ifndef __CUDA_ARCH__\n return std::chi_squared_distribution<real>(nu)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return real(2.0)*curand_gamma_double(curand_rng(rngs), real(0.5)*nu);\n } else {\n return real(2.0)*curand_gamma(curand_rng(rngs), real(0.5)*nu);\n }\n #endif\n }\n};\n\nstruct simulate_exponential_functor {\n curandState_t* rngs;\n simulate_exponential_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real lambda) {\n #ifndef __CUDA_ARCH__\n return std::exponential_distribution<real>(lambda)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return -std::log(curand_uniform_double(curand_rng(rngs)))\/lambda;\n } else {\n return -std::log(curand_uniform(curand_rng(rngs)))\/lambda;\n }\n #endif\n }\n};\n\nstruct simulate_gamma_functor {\n curandState_t* rngs;\n simulate_gamma_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real k, const real theta) {\n #ifndef __CUDA_ARCH__\n return std::gamma_distribution<real>(k, theta)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_gamma(curand_rng(rngs), k)*theta;\n } else {\n return curand_gamma_double(curand_rng(rngs), k)*theta;\n }\n #endif\n }\n};\n\nstruct simulate_gaussian_functor {\n curandState_t* rngs;\n simulate_gaussian_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real mu, const real sigma2) {\n #ifndef __CUDA_ARCH__\n return std::normal_distribution<real>(mu, std::sqrt(sigma2))(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return mu + std::sqrt(sigma2)*curand_normal_double(curand_rng(rngs));\n } else {\n return mu + std::sqrt(sigma2)*curand_normal(curand_rng(rngs));\n }\n #endif\n }\n};\n\nstruct simulate_negative_binomial_functor {\n curandState_t* rngs;\n simulate_negative_binomial_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real k, const real rho) {\n #ifndef __CUDA_ARCH__\n return std::negative_binomial_distribution<int>(k, rho)(stl<real>::rng());\n \/\/ ^ negative_binomial_distribution requires integral type\n #else\n real theta, lambda;\n theta = (real(1.0) - rho)\/rho;\n if constexpr (std::is_same_v<real,double>) {\n lambda = curand_gamma_double(curand_rng(rngs), k);\n } else {\n lambda = curand_gamma(curand_rng(rngs), k);\n }\n return curand_poisson(curand_rng(rngs), lambda*theta);\n #endif\n }\n};\n\nstruct simulate_poisson_functor {\n curandState_t* rngs;\n simulate_poisson_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE int operator()(const real lambda) {\n #ifndef __CUDA_ARCH__\n return std::poisson_distribution<int>(lambda)(stl<real>::rng());\n \/\/ ^ poisson_distribution requires integral type\n #else\n return curand_poisson(curand_rng(rngs), lambda);\n #endif\n }\n};\n\nstruct simulate_uniform_functor {\n curandState_t* rngs;\n simulate_uniform_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real l, const real u) {\n #ifndef __CUDA_ARCH__\n return std::uniform_real_distribution<real>(l, u)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return l + (u - l)*curand_uniform_double(curand_rng(rngs));\n } else {\n return l + (u - l)*curand_uniform(curand_rng(rngs));\n }\n #endif\n }\n};\n\nstruct simulate_uniform_int_functor {\n curandState_t* rngs;\n simulate_uniform_int_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE int operator()(const int l, const int u) {\n #ifndef __CUDA_ARCH__\n return std::uniform_int_distribution<int>(l, u)(stl<int>::rng());\n \/\/ ^ uniform_int_distribution requires integral type\n #else\n if constexpr (std::is_same_v<real,double>) {\n return l + int(real(u - l + 1)*curand_uniform_double(curand_rng(rngs)));\n } else {\n return l + int(real(u - l + 1)*curand_uniform(curand_rng(rngs)));\n }\n #endif\n }\n};\n\nstruct simulate_weibull_functor {\n curandState_t* rngs;\n simulate_weibull_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const real k, const real lambda) {\n #ifndef __CUDA_ARCH__\n return std::weibull_distribution<real>(k, lambda)(stl<real>::rng());\n #else\n real u;\n if constexpr (std::is_same_v<real,double>) {\n u = curand_uniform_double(curand_rng(rngs));\n } else {\n u = curand_uniform(curand_rng(rngs));\n }\n return lambda*std::pow(-std::log(real(1.0) - u), real(1.0)\/k);\n #endif\n }\n};\n\nstruct standard_gaussian_functor {\n curandState_t* rngs;\n standard_gaussian_functor() : rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const int i, const int j) {\n #ifndef __CUDA_ARCH__\n return std::normal_distribution<real>()(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_normal_double(curand_rng(rngs));\n } else {\n return curand_normal(curand_rng(rngs));\n }\n #endif\n }\n};\n\ntemplate<class T>\nstruct standard_wishart_functor {\n T k;\n int n;\n curandState_t* rngs;\n standard_wishart_functor(const T& k, const int n) :\n k(k),\n n(n),\n rngs(numbirch::rngs) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE real operator()(const int i, const int j) {\n if (i == j) {\n \/* on diagonal *\/\n real nu = get(k) + (n - 1 - i); \/\/ i is 0-based here\n real x;\n #ifndef __CUDA_ARCH__\n x = std::chi_squared_distribution<real>(nu)(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n x = real(2.0)*curand_gamma_double(curand_rng(rngs), real(0.5)*nu);\n } else {\n x = real(2.0)*curand_gamma(curand_rng(rngs), real(0.5)*nu);\n }\n #endif\n return std::sqrt(x);\n } else if (i > j) {\n \/* in lower triangle *\/\n #ifndef __CUDA_ARCH__\n return std::normal_distribution<real>()(stl<real>::rng());\n #else\n if constexpr (std::is_same_v<real,double>) {\n return curand_normal_double(curand_rng(rngs));\n } else {\n return curand_normal(curand_rng(rngs));\n }\n #endif\n } else {\n \/* in upper triangle *\/\n return real(0.0);\n }\n }\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Baldur Karlsson\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\n#include \"renderdoccmd.h\"\n\nint main(int argc, char *argv[])\n{\n return 0;\n}\n<commit_msg>Add support for GGP in \"renderdoccmd replay\"<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Baldur Karlsson\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\n#include \"renderdoccmd.h\"\n#include <signal.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <ggp_c\/ggp.h>\n#include <replay\/renderdoc_replay.h>\n\nconst uint64_t kMicrosecondsPerFrame = 16666L;\n\n\/\/ struct appData: Global application data\nstatic struct\n{\n \/\/ GGP\n GgpEventQueue event_queue;\n uint32_t stream_started_handler_id;\n uint32_t stream_stopped_handler_id;\n \/\/ General\n bool quit;\n} app_data = {0};\n\nvoid Daemonise()\n{\n \/\/ don't change dir, but close stdin\/stdout\n daemon(1, 0);\n}\n\nWindowingData DisplayRemoteServerPreview(bool active, const rdcarray<WindowingSystem> &systems)\n{\n static WindowingData remoteServerPreview = {WindowingSystem::Unknown};\n \/\/ No preview implemented.\n return remoteServerPreview;\n}\n\n\/\/ ClockNowMicroSeconds(): Return current time in microseconds\nstatic inline uint64_t ClockNowMicroSeconds()\n{\n struct timespec now = {};\n clock_gettime(CLOCK_MONOTONIC_RAW, &now);\n uint64_t nanoseconds = (now.tv_sec * 1000000000LL) + now.tv_nsec;\n uint64_t microseconds = nanoseconds \/ 1000LL;\n return microseconds;\n}\n\n\/\/ HandleStreamStarted(): Client connected handler\nstatic void HandleStreamStarted(void *user_data)\n{\n std::cout << \"GGP client connected\" << std::endl;\n}\n\n\/\/ HandleStreamStopped(): Client disconnected handler\nstatic void HandleStreamStopped(const GgpStreamStoppedEvent *event, void *user_data)\n{\n std::cout << \"GGP client disconnected\" << std::endl;\n \/\/ Exit the application if the client disconnects to exit.\n if(event->stream_stopped_reason == kGgpStreamStopped_Exited)\n {\n app_data.quit = true;\n }\n else if(event->stream_stopped_reason == kGgpStreamStopped_Unexpected)\n {\n GgpSuspended();\n }\n}\n\n\/\/ UnregisterCallback(): Handler unregistered\nstatic void UnregisterCallback(void *user_data)\n{\n std::cout << \"Unregistered callback\" << std::endl;\n}\n\n\/\/ Initialize(): Initialize application\nstatic void Initialize()\n{\n \/\/ Initialize event queue\n app_data.event_queue = GgpEventQueueCreate();\n std::cout << \"GGP event queue created\" << std::endl;\n \/\/ Add client connection handlers\n app_data.stream_started_handler_id = GgpAddStreamStartedHandler(\n app_data.event_queue, HandleStreamStarted, NULL, UnregisterCallback);\n app_data.stream_stopped_handler_id = GgpAddStreamStoppedHandler(\n app_data.event_queue, HandleStreamStopped, NULL, UnregisterCallback);\n \/\/ Signal that the session is ready to receive events.\n GgpHandlersRegistered();\n\n GgpReadyToStream();\n std::cout << \"GGP ready to stream\" << std::endl;\n}\n\n\/\/ Finalize(): Clean up application resources\nstatic void Finalize()\n{\n \/\/ Destroy the event queue\n GgpEventQueueDestroy(app_data.event_queue);\n std::cout << \"GGP event queue destroyed\" << std::endl;\n \/\/ Remove client connection handlers.\n GgpRemoveStreamStartedHandler(app_data.stream_started_handler_id);\n GgpRemoveStreamStoppedHandler(app_data.stream_stopped_handler_id);\n \/\/ Indicate that GGP should shutdown.\n GgpShutDown();\n}\n\nvoid DisplayRendererPreview(IReplayController *renderer, TextureDisplay &displayCfg, uint32_t width,\n uint32_t height, uint32_t numLoops)\n{\n Initialize();\n\n IReplayOutput *out = renderer->CreateOutput(CreateGgpWindowingData(), ReplayOutputType::Texture);\n out->SetTextureDisplay(displayCfg);\n\n \/\/ Wait until user closes the window, then exit\n while(!app_data.quit)\n {\n uint64_t whenToResume = ClockNowMicroSeconds() + kMicrosecondsPerFrame;\n while(GgpEventQueueProcessEvent(app_data.event_queue, 0))\n {\n }\n renderer->SetFrameEvent(10000000, true);\n out->Display();\n \/\/ Sleep for 1\/60 second (one frame)\n uint64_t timeLeft = whenToResume - ClockNowMicroSeconds();\n if(timeLeft > 0)\n {\n struct timespec sleepTime = {};\n sleepTime.tv_nsec = timeLeft * 1000LL;\n nanosleep(&sleepTime, NULL);\n }\n }\n\n Finalize();\n}\n\nvoid sig_handler(int signo)\n{\n if(usingKillSignal)\n killSignal = true;\n else\n exit(1);\n}\n\nint main(int argc, char *argv[])\n{\n setlocale(LC_CTYPE, \"\");\n\n signal(SIGINT, sig_handler);\n signal(SIGTERM, sig_handler);\n\n GlobalEnvironment env;\n\n \/\/ add compiled-in support to version line\n {\n std::string support = \"APIs supported at compile-time: \";\n int count = 0;\n\n#if defined(RENDERDOC_SUPPORT_VULKAN)\n support += \"Vulkan, \";\n count++;\n#endif\n\n if(count == 0)\n {\n support += \"None.\";\n }\n else\n {\n \/\/ remove trailing ', '\n support.pop_back();\n support.pop_back();\n support += \".\";\n }\n\n add_version_line(support);\n\n support = \"Windowing systems supported at compile-time: \";\n count = 0;\n\n support += \"GGP, \";\n count++;\n\n#if defined(RENDERDOC_SUPPORT_VULKAN)\n support += \"Vulkan KHR_display, \";\n count++;\n#endif\n\n if(count == 0)\n {\n support += \"None.\";\n }\n else\n {\n \/\/ remove trailing ', '\n support.pop_back();\n support.pop_back();\n support += \".\";\n }\n\n add_version_line(support);\n }\n\n int ret = renderdoccmd(env, argc, argv);\n\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright(c) 2016 Oleg Linkin <MaledictusDeMagog@gmail.com>\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\n#include \"bookmarksmodel.h\"\n#include <QtDebug>\n\nnamespace LinksBag\n{\nBookmarksModel::BookmarksModel(QObject *parent)\n: QAbstractListModel(parent)\n{\n}\n\nBookmarksModel::~BookmarksModel()\n{\n}\n\nQVariant BookmarksModel::data(const QModelIndex& index, int role) const\n{\n if(index.row() < 0 || index.row() > m_Bookmarks.count())\n {\n return QVariant();\n }\n\n auto bookmark = m_Bookmarks.at(index.row());\n switch(role)\n {\n case BRID:\n return bookmark.GetID();\n case BRUrl:\n return bookmark.GetUrl();\n case BRTitle:\n return bookmark.GetTitle();\n case BRDescription:\n return bookmark.GetDescription();\n case BRImageUrl:\n return bookmark.GetImageUrl();\n case BRFavorite:\n return bookmark.IsFavorite();\n case BRRead:\n return bookmark.IsRead();\n case BRTags:\n return bookmark.GetTags().join(',');\n case BRAddTime:\n return bookmark.GetAddTime();\n case BRUpdateTime:\n return bookmark.GetUpdateTime();\n case BRStatus:\n return bookmark.GetStatus();\n default:\n return QVariant();\n }\n}\n\nint BookmarksModel::rowCount(const QModelIndex&) const\n{\n return m_Bookmarks.count();\n}\n\nQHash<int, QByteArray> BookmarksModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles [BRID] = \"bookmarkID\";\n roles [BRUrl] = \"bookmarkUrl\";\n roles [BRTitle] = \"bookmarkTitle\";\n roles [BRDescription] = \"bookmarkDescription\";\n roles [BRImageUrl] = \"bookmarkImageUrl\";\n roles [BRFavorite] = \"bookmarkFavorite\";\n roles [BRRead] = \"bookmarkRead\";\n roles [BRTags] = \"bookmarkTags\";\n roles [BRAddTime] = \"bookmarkAddTime\";\n roles [BRUpdateTime] = \"bookmarkUpdateTime\";\n roles [BRStatus] = \"bookmarkStatus\";\n\n return roles;\n}\n\nvoid BookmarksModel::Clear()\n{\n m_Bookmarks.clear();\n}\n\nvoid BookmarksModel::RemoveBookmark(const QString& id)\n{\n auto it = std::find_if(m_Bookmarks.begin(), m_Bookmarks.end(),\n [id](decltype(m_Bookmarks.front()) bookmark)\n {\n return id == bookmark.GetID();\n });\n if(it != m_Bookmarks.end())\n {\n const int pos = std::distance(m_Bookmarks.begin(), it);\n beginRemoveRows(QModelIndex(), pos, pos);\n m_Bookmarks.removeAt(pos);\n endRemoveRows();\n }\n}\n\nvoid BookmarksModel::AddBookmarks(const Bookmarks_t& bookmarks)\n{\n Bookmarks_t bmss = bookmarks;\n for(int i = bmss.count() - 1; !m_Bookmarks.isEmpty() && i >= 0; --i)\n {\n auto bms = bmss.at(i);\n auto it = std::find_if(m_Bookmarks.begin(), m_Bookmarks.end(),\n [bms](decltype(m_Bookmarks.front()) bookmark)\n {\n return bms.GetID() == bookmark.GetID();\n });\n if (it != m_Bookmarks.end())\n {\n const int pos = std::distance(m_Bookmarks.begin(), it);\n switch(bms.GetStatus())\n {\n case Bookmark::SDeleted:\n RemoveBookmark(bms.GetID());\n break;\n case Bookmark::SArchived:\n {\n Bookmark bm = m_Bookmarks[pos];\n bm.SetIsRead(true);\n\n emit dataChanged(index(pos), index(pos));\n break;\n }\n default:\n {\n Bookmark bm = m_Bookmarks[pos];\n bm.SetUrl(bms.GetUrl());\n bm.SetTitle(bms.GetTitle());\n bm.SetDescription(bms.GetDescription());\n bm.SetIsFavorite(bms.IsFavorite());\n bm.SetIsRead(bms.IsRead());\n bm.SetAddTime(bms.GetAddTime());\n bm.SetUpdateTime(bms.GetUpdateTime());\n bm.SetTags(bms.GetTags());\n bm.SetImageUrl(bms.GetImageUrl());\n bm.SetStatus(bms.GetStatus());\n\n emit dataChanged(index(pos), index(pos));\n break;\n }\n }\n }\n }\n\n beginInsertRows(QModelIndex(), rowCount(), rowCount() + bmss.count() - 1);\n m_Bookmarks.append(bmss);\n endInsertRows();\n}\n\nvoid BookmarksModel::SetBookmarks(const Bookmarks_t& bookmarks)\n{\n beginResetModel();\n m_Bookmarks = bookmarks;\n endResetModel();\n}\n\nvoid BookmarksModel::MarkBookmarkAsFavorite(const QString& id, bool favorite)\n{\n for(int i = 0, size = m_Bookmarks.count(); i < size; ++i)\n {\n auto& bm = m_Bookmarks[i];\n if(bm.GetID() == id)\n {\n bm.SetIsFavorite(favorite);\n emit dataChanged(index(i, 0), index(i, 0));\n break;\n }\n }\n}\n\nvoid BookmarksModel::MarkBookmarkAsRead(const QString& id, bool read)\n{\n for(int i = 0, size = m_Bookmarks.count(); i < size; ++i)\n {\n auto& bm = m_Bookmarks[i];\n if(bm.GetID() == id)\n {\n bm.SetIsRead(read);\n emit dataChanged(index(i, 0), index(i, 0));\n break;\n }\n }\n}\n\nBookmarks_t BookmarksModel::GetBookmarks() const\n{\n return m_Bookmarks;\n}\n\nQVariantMap BookmarksModel::getBookmark(const QString& id) const\n{\n auto it = std::find_if(m_Bookmarks.begin(), m_Bookmarks.end(),\n [id](decltype(m_Bookmarks.front()) bookmark)\n {\n return bookmark.GetID() == id;\n });\n if(it == m_Bookmarks.end())\n {\n return QVariantMap();\n }\n\n return it->ToMap();\n}\n} \/\/ namespace LinksBag\n<commit_msg>Fix addbookmarks method in model<commit_after>\/*\n Copyright(c) 2016 Oleg Linkin <MaledictusDeMagog@gmail.com>\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\n#include \"bookmarksmodel.h\"\n#include <QtDebug>\n\nnamespace LinksBag\n{\nBookmarksModel::BookmarksModel(QObject *parent)\n: QAbstractListModel(parent)\n{\n}\n\nBookmarksModel::~BookmarksModel()\n{\n}\n\nQVariant BookmarksModel::data(const QModelIndex& index, int role) const\n{\n if(index.row() < 0 || index.row() > m_Bookmarks.count())\n {\n return QVariant();\n }\n\n auto bookmark = m_Bookmarks.at(index.row());\n switch(role)\n {\n case BRID:\n return bookmark.GetID();\n case BRUrl:\n return bookmark.GetUrl();\n case BRTitle:\n return bookmark.GetTitle();\n case BRDescription:\n return bookmark.GetDescription();\n case BRImageUrl:\n return bookmark.GetImageUrl();\n case BRFavorite:\n return bookmark.IsFavorite();\n case BRRead:\n return bookmark.IsRead();\n case BRTags:\n return bookmark.GetTags().join(',');\n case BRAddTime:\n return bookmark.GetAddTime();\n case BRUpdateTime:\n return bookmark.GetUpdateTime();\n case BRStatus:\n return bookmark.GetStatus();\n default:\n return QVariant();\n }\n}\n\nint BookmarksModel::rowCount(const QModelIndex&) const\n{\n return m_Bookmarks.count();\n}\n\nQHash<int, QByteArray> BookmarksModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles [BRID] = \"bookmarkID\";\n roles [BRUrl] = \"bookmarkUrl\";\n roles [BRTitle] = \"bookmarkTitle\";\n roles [BRDescription] = \"bookmarkDescription\";\n roles [BRImageUrl] = \"bookmarkImageUrl\";\n roles [BRFavorite] = \"bookmarkFavorite\";\n roles [BRRead] = \"bookmarkRead\";\n roles [BRTags] = \"bookmarkTags\";\n roles [BRAddTime] = \"bookmarkAddTime\";\n roles [BRUpdateTime] = \"bookmarkUpdateTime\";\n roles [BRStatus] = \"bookmarkStatus\";\n\n return roles;\n}\n\nvoid BookmarksModel::Clear()\n{\n m_Bookmarks.clear();\n}\n\nvoid BookmarksModel::RemoveBookmark(const QString& id)\n{\n auto it = std::find_if(m_Bookmarks.begin(), m_Bookmarks.end(),\n [id](decltype(m_Bookmarks.front()) bookmark)\n {\n return id == bookmark.GetID();\n });\n if(it != m_Bookmarks.end())\n {\n const int pos = std::distance(m_Bookmarks.begin(), it);\n beginRemoveRows(QModelIndex(), pos, pos);\n m_Bookmarks.removeAt(pos);\n endRemoveRows();\n }\n}\n\nvoid BookmarksModel::AddBookmarks(const Bookmarks_t& bookmarks)\n{\n Bookmarks_t bmss = bookmarks;\n for(int i = bmss.count() - 1; i >= 0; --i)\n {\n auto bms = bmss.at(i);\n auto it = std::find_if(m_Bookmarks.begin(), m_Bookmarks.end(),\n [bms](decltype(m_Bookmarks.front()) bookmark)\n {\n return bms.GetID() == bookmark.GetID();\n });\n if (it != m_Bookmarks.end())\n {\n const int pos = std::distance(m_Bookmarks.begin(), it);\n switch(bms.GetStatus())\n {\n case Bookmark::SDeleted:\n RemoveBookmark(bms.GetID());\n break;\n case Bookmark::SArchived:\n {\n Bookmark bm = m_Bookmarks[pos];\n bm.SetIsRead(true);\n\n emit dataChanged(index(pos), index(pos));\n break;\n }\n default:\n {\n Bookmark bm = m_Bookmarks[pos];\n bm.SetUrl(bms.GetUrl());\n bm.SetTitle(bms.GetTitle());\n bm.SetDescription(bms.GetDescription());\n bm.SetIsFavorite(bms.IsFavorite());\n bm.SetIsRead(bms.IsRead());\n bm.SetAddTime(bms.GetAddTime());\n bm.SetUpdateTime(bms.GetUpdateTime());\n bm.SetTags(bms.GetTags());\n bm.SetImageUrl(bms.GetImageUrl());\n bm.SetStatus(bms.GetStatus());\n\n emit dataChanged(index(pos), index(pos));\n break;\n }\n }\n }\n else {\n beginInsertRows(QModelIndex(), rowCount(), rowCount());\n m_Bookmarks.append(bms);\n endInsertRows();\n }\n }\n}\n\nvoid BookmarksModel::SetBookmarks(const Bookmarks_t& bookmarks)\n{\n beginResetModel();\n m_Bookmarks = bookmarks;\n endResetModel();\n}\n\nvoid BookmarksModel::MarkBookmarkAsFavorite(const QString& id, bool favorite)\n{\n for(int i = 0, size = m_Bookmarks.count(); i < size; ++i)\n {\n auto& bm = m_Bookmarks[i];\n if(bm.GetID() == id)\n {\n bm.SetIsFavorite(favorite);\n emit dataChanged(index(i, 0), index(i, 0));\n break;\n }\n }\n}\n\nvoid BookmarksModel::MarkBookmarkAsRead(const QString& id, bool read)\n{\n for(int i = 0, size = m_Bookmarks.count(); i < size; ++i)\n {\n auto& bm = m_Bookmarks[i];\n if(bm.GetID() == id)\n {\n bm.SetIsRead(read);\n emit dataChanged(index(i, 0), index(i, 0));\n break;\n }\n }\n}\n\nBookmarks_t BookmarksModel::GetBookmarks() const\n{\n return m_Bookmarks;\n}\n\nQVariantMap BookmarksModel::getBookmark(const QString& id) const\n{\n auto it = std::find_if(m_Bookmarks.begin(), m_Bookmarks.end(),\n [id](decltype(m_Bookmarks.front()) bookmark)\n {\n return bookmark.GetID() == id;\n });\n if(it == m_Bookmarks.end())\n {\n return QVariantMap();\n }\n\n return it->ToMap();\n}\n} \/\/ namespace LinksBag\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This program 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"PythonMacros.h\"\n#include \"Binding.h\"\n#include \"Binding_SofaModule.h\"\n\n#include \"Binding_Data.h\"\n#include \"Binding_DisplayFlagsData.h\"\n#include \"Binding_OptionsGroupData.h\"\n#include \"Binding_DataFileName.h\"\n#include \"Binding_DataFileNameVector.h\"\n#include \"Binding_VectorLinearSpringData.h\"\n#include \"Binding_Link.h\"\n#include \"Binding_Base.h\"\n#include \"Binding_BaseObject.h\"\n#include \"Binding_BaseState.h\"\n#include \"Binding_BaseContext.h\"\n#include \"Binding_Context.h\"\n#include \"Binding_Node.h\"\n#include \"Binding_Vector.h\"\n#include \"Binding_TopologyChange.h\"\n#include \"Binding_BaseLoader.h\"\n#include \"Binding_MeshLoader.h\"\n#include \"Binding_Topology.h\"\n#include \"Binding_BaseMeshTopology.h\"\n#include \"Binding_MeshTopology.h\"\n#include \"Binding_GridTopology.h\"\n#include \"Binding_RegularGridTopology.h\"\n#include \"Binding_BaseMechanicalState.h\"\n#include \"Binding_MechanicalObject.h\"\n#include \"Binding_PythonScriptController.h\"\n#include \"Binding_LinearSpring.h\"\n#include \"Binding_BaseTopologyObject.h\"\n#include \"Binding_TriangleSetTopologyModifier.h\"\n#include \"Binding_PointSetTopologyModifier.h\"\n#include \"Binding_BaseMapping.h\"\n#include \"Binding_SubsetMultiMapping.h\"\n#include \"Binding_VisualModel.h\"\n#include \"Binding_OBJExporter.h\"\n#include \"Binding_STLExporter.h\"\n#include \"Binding_DataEngine.h\"\n#include \"PythonFactory.h\"\n\nusing sofa::PythonFactory;\n\n\nvoid bindSofaPythonModule()\n{\n PythonFactory::s_sofaPythonModule = SP_INIT_MODULE(Sofa)\n\n \/\/\/ non Base-Inherited types\n SP_ADD_CLASS_IN_SOFAMODULE(Data)\n\n \/\/\/ special Data cases\n SP_ADD_CLASS_IN_FACTORY(DisplayFlagsData,sofa::core::objectmodel::Data<sofa::core::visual::DisplayFlags>)\n SP_ADD_CLASS_IN_FACTORY(OptionsGroupData,sofa::core::objectmodel::Data<sofa::helper::OptionsGroup>)\n SP_ADD_CLASS_IN_FACTORY(DataFileName,sofa::core::objectmodel::DataFileName)\n SP_ADD_CLASS_IN_FACTORY(DataFileNameVector,sofa::core::objectmodel::DataFileNameVector)\n SP_ADD_CLASS_IN_SOFAMODULE(PointAncestorElem)\n SP_ADD_CLASS_IN_FACTORY(VectorLinearSpringData,sofa::core::objectmodel::Data<sofa::helper::vector<sofa::component::interactionforcefield::LinearSpring<SReal>>>)\n\n SP_ADD_CLASS_IN_SOFAMODULE(Link)\n SP_ADD_CLASS_IN_SOFAMODULE(Vector3)\n SP_ADD_CLASS_IN_SOFAMODULE(LinearSpring)\n\n \/\/\/ special component categories gettable by static_cast\n SP_ADD_CLASS_IN_SOFAMODULE(Base)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseContext)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseObject)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseTopologyObject)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseState)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseMechanicalState)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseMapping)\n SP_ADD_CLASS_IN_SOFAMODULE(DataEngine)\n SP_ADD_CLASS_IN_SOFAMODULE(VisualModel)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseLoader)\n SP_ADD_CLASS_IN_SOFAMODULE(Topology)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseMeshTopology)\n\n \/\/\/ regular component bindings\n SP_ADD_CLASS_IN_FACTORY(Context,sofa::core::objectmodel::Context)\n SP_ADD_CLASS_IN_FACTORY(Node,sofa::simulation::Node)\n SP_ADD_CLASS_IN_FACTORY(VisualModelImpl,sofa::component::visualmodel::VisualModelImpl)\n SP_ADD_CLASS_IN_FACTORY(MeshLoader,sofa::core::loader::MeshLoader)\n SP_ADD_CLASS_IN_FACTORY(MeshTopology,sofa::component::topology::MeshTopology)\n SP_ADD_CLASS_IN_FACTORY(GridTopology,sofa::component::topology::GridTopology)\n SP_ADD_CLASS_IN_FACTORY(RegularGridTopology,sofa::component::topology::RegularGridTopology)\n SP_ADD_CLASS_IN_FACTORY(OBJExporter,sofa::component::misc::OBJExporter)\n SP_ADD_CLASS_IN_FACTORY(STLExporter,sofa::component::misc::STLExporter)\n SP_ADD_CLASS_IN_FACTORY(PythonScriptController,sofa::component::controller::PythonScriptController)\n SP_ADD_CLASS_IN_FACTORY(PointSetTopologyModifier,sofa::component::topology::PointSetTopologyModifier)\n SP_ADD_CLASS_IN_FACTORY(TriangleSetTopologyModifier,sofa::component::topology::TriangleSetTopologyModifier)\n\n \/\/\/ Custom Exception\n const char* name = \"Sofa.SofaException\";\n const char* doc = \"Base exception class for the SofaPython module.\" ;\n PyObject* PyExc_SofaException = PyErr_NewExceptionWithDoc(\n (char*) \"Sofa.SofaException\",\n (char*) \"Base exception class for the SofaPython module.\",\n NULL, NULL);\n\n if ( PyExc_SofaException )\n PyModule_AddObject(PythonFactory::s_sofaPythonModule, \"SofaException\", PyExc_SofaException);\n}\n\n\n\n\n<commit_msg>[SofaPython] Fix unused char*.<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This program 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"PythonMacros.h\"\n#include \"Binding.h\"\n#include \"Binding_SofaModule.h\"\n\n#include \"Binding_Data.h\"\n#include \"Binding_DisplayFlagsData.h\"\n#include \"Binding_OptionsGroupData.h\"\n#include \"Binding_DataFileName.h\"\n#include \"Binding_DataFileNameVector.h\"\n#include \"Binding_VectorLinearSpringData.h\"\n#include \"Binding_Link.h\"\n#include \"Binding_Base.h\"\n#include \"Binding_BaseObject.h\"\n#include \"Binding_BaseState.h\"\n#include \"Binding_BaseContext.h\"\n#include \"Binding_Context.h\"\n#include \"Binding_Node.h\"\n#include \"Binding_Vector.h\"\n#include \"Binding_TopologyChange.h\"\n#include \"Binding_BaseLoader.h\"\n#include \"Binding_MeshLoader.h\"\n#include \"Binding_Topology.h\"\n#include \"Binding_BaseMeshTopology.h\"\n#include \"Binding_MeshTopology.h\"\n#include \"Binding_GridTopology.h\"\n#include \"Binding_RegularGridTopology.h\"\n#include \"Binding_BaseMechanicalState.h\"\n#include \"Binding_MechanicalObject.h\"\n#include \"Binding_PythonScriptController.h\"\n#include \"Binding_LinearSpring.h\"\n#include \"Binding_BaseTopologyObject.h\"\n#include \"Binding_TriangleSetTopologyModifier.h\"\n#include \"Binding_PointSetTopologyModifier.h\"\n#include \"Binding_BaseMapping.h\"\n#include \"Binding_SubsetMultiMapping.h\"\n#include \"Binding_VisualModel.h\"\n#include \"Binding_OBJExporter.h\"\n#include \"Binding_STLExporter.h\"\n#include \"Binding_DataEngine.h\"\n#include \"PythonFactory.h\"\n\nusing sofa::PythonFactory;\n\n\nvoid bindSofaPythonModule()\n{\n PythonFactory::s_sofaPythonModule = SP_INIT_MODULE(Sofa)\n\n \/\/\/ non Base-Inherited types\n SP_ADD_CLASS_IN_SOFAMODULE(Data)\n\n \/\/\/ special Data cases\n SP_ADD_CLASS_IN_FACTORY(DisplayFlagsData,sofa::core::objectmodel::Data<sofa::core::visual::DisplayFlags>)\n SP_ADD_CLASS_IN_FACTORY(OptionsGroupData,sofa::core::objectmodel::Data<sofa::helper::OptionsGroup>)\n SP_ADD_CLASS_IN_FACTORY(DataFileName,sofa::core::objectmodel::DataFileName)\n SP_ADD_CLASS_IN_FACTORY(DataFileNameVector,sofa::core::objectmodel::DataFileNameVector)\n SP_ADD_CLASS_IN_SOFAMODULE(PointAncestorElem)\n SP_ADD_CLASS_IN_FACTORY(VectorLinearSpringData,sofa::core::objectmodel::Data<sofa::helper::vector<sofa::component::interactionforcefield::LinearSpring<SReal>>>)\n\n SP_ADD_CLASS_IN_SOFAMODULE(Link)\n SP_ADD_CLASS_IN_SOFAMODULE(Vector3)\n SP_ADD_CLASS_IN_SOFAMODULE(LinearSpring)\n\n \/\/\/ special component categories gettable by static_cast\n SP_ADD_CLASS_IN_SOFAMODULE(Base)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseContext)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseObject)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseTopologyObject)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseState)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseMechanicalState)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseMapping)\n SP_ADD_CLASS_IN_SOFAMODULE(DataEngine)\n SP_ADD_CLASS_IN_SOFAMODULE(VisualModel)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseLoader)\n SP_ADD_CLASS_IN_SOFAMODULE(Topology)\n SP_ADD_CLASS_IN_SOFAMODULE(BaseMeshTopology)\n\n \/\/\/ regular component bindings\n SP_ADD_CLASS_IN_FACTORY(Context,sofa::core::objectmodel::Context)\n SP_ADD_CLASS_IN_FACTORY(Node,sofa::simulation::Node)\n SP_ADD_CLASS_IN_FACTORY(VisualModelImpl,sofa::component::visualmodel::VisualModelImpl)\n SP_ADD_CLASS_IN_FACTORY(MeshLoader,sofa::core::loader::MeshLoader)\n SP_ADD_CLASS_IN_FACTORY(MeshTopology,sofa::component::topology::MeshTopology)\n SP_ADD_CLASS_IN_FACTORY(GridTopology,sofa::component::topology::GridTopology)\n SP_ADD_CLASS_IN_FACTORY(RegularGridTopology,sofa::component::topology::RegularGridTopology)\n SP_ADD_CLASS_IN_FACTORY(OBJExporter,sofa::component::misc::OBJExporter)\n SP_ADD_CLASS_IN_FACTORY(STLExporter,sofa::component::misc::STLExporter)\n SP_ADD_CLASS_IN_FACTORY(PythonScriptController,sofa::component::controller::PythonScriptController)\n SP_ADD_CLASS_IN_FACTORY(PointSetTopologyModifier,sofa::component::topology::PointSetTopologyModifier)\n SP_ADD_CLASS_IN_FACTORY(TriangleSetTopologyModifier,sofa::component::topology::TriangleSetTopologyModifier)\n\n \/\/\/ Custom Exception\n PyObject* PyExc_SofaException = PyErr_NewExceptionWithDoc(\n (char*) \"Sofa.SofaException\",\n (char*) \"Base exception class for the SofaPython module.\",\n NULL, NULL);\n\n if ( PyExc_SofaException )\n PyModule_AddObject(PythonFactory::s_sofaPythonModule, \"SofaException\", PyExc_SofaException);\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Copyright (C) 2011-2012 Michael Krufky\n *\n * Author: Michael Krufky <mkrufky@linuxtv.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 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 *****************************************************************************\/\n#define DBG 0\n\n#include <string.h>\n#include \"rbuf.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"rbuf\"\n\n#define dprintf(fmt, arg...) __dprintf(DBG_OUTPUT, fmt, ##arg)\n\nrbuf::rbuf()\n : capacity(0)\n , p_data(NULL)\n , idx_read(0)\n , idx_write(0)\n{\n\tdprintf(\"()\");\n\tpthread_mutex_init(&mutex, 0);\n}\n\nrbuf::~rbuf()\n{\n\tdprintf(\"()\");\n\tpthread_mutex_lock(&mutex);\n\n\tif (p_data)\n\t\tdelete p_data;\n\n\tpthread_mutex_unlock(&mutex);\n\tpthread_mutex_destroy(&mutex);\n}\n\nvoid rbuf::set_capacity(int cap)\n{\n\tdprintf(\"(%d)\", cap);\n\tpthread_mutex_lock(&mutex);\n\n\tif (p_data)\n\t\tdelete p_data;\n\n\tp_data = new char[(capacity = cap)];\n\t__reset();\n\n\tpthread_mutex_unlock(&mutex);\n}\n\nint rbuf::get_capacity()\n{\n\tdprintf(\"(%d)\", capacity);\n\treturn capacity;\n}\n\nint rbuf::get_size()\n{\n#if DBG\n\tdprintf(\"()\");\n#endif\n\tpthread_mutex_lock(&mutex);\n\n\tint ret = __get_size();\n\n\tpthread_mutex_unlock(&mutex);\n\n\treturn ret;\n}\n\nvoid rbuf::reset()\n{\n\tdprintf(\"()\");\n\tpthread_mutex_lock(&mutex);\n\n\t__reset();\n\n\tpthread_mutex_unlock(&mutex);\n}\n\n\nint rbuf::get_write_ptr(void** p)\n{\n\tpthread_mutex_lock(&mutex);\n\n\treturn __get_write_ptr(p);\n}\n\nvoid rbuf::put_write_ptr(int size)\n{\n\t__put_write_ptr(size);\n\n\tpthread_mutex_unlock(&mutex);\n}\n\n#if 0\nbool rbuf::write(const void* p, int size)\n{\n\tpthread_mutex_lock(&mutex);\n\n\tif (__get_size() + size > capacity)\n\t\treturn false;\n\n if (idx_write + size > capacity) {\n\t\tint split = capacity - idx_write;\n\t\tmemcpy(p_data + idx_write, p, split);\n\t\tidx_write = size - split;\n\t\tmemcpy(p_data, (const char*) p + split, idx_write);\n } else {\n\t\tmemcpy(p_data + idx_write, p, size);\n\t\tidx_write += size;\n\t\tif (idx_write == capacity)\n\t\t\tidx_write = 0;\n }\n\tpthread_mutex_unlock(&mutex);\n return true;\n}\n#else\nbool rbuf::write(const void* p, int size)\n{\n\tpthread_mutex_lock(&mutex);\n\tif (__get_size() + size > capacity)\n\t\treturn false;\n\n\tvoid *q = NULL;\n\tchar *r = (char*)p;\n\tint available;\n\n\twhile (size) {\n\t\tavailable = __get_write_ptr(&q);\n\t\tif (available >= size) {\n\t\t\tmemcpy(q, r, size);\n\t\t\t__put_write_ptr(size);\n\t\t\tsize = 0;\n\t\t} else if (available > 0) {\n\t\t\tmemcpy(q, r, available);\n\t\t\t__put_write_ptr(available);\n\t\t\tsize -= available;\n\t\t\tr += available;\n\t\t}\n#if 0\n\t\telse {\n\/\/\t\t\tpthread_mutex_unlock(&mutex);\n\t\t\treturn false;\n\t\t}\n#endif\n\t}\n\tpthread_mutex_unlock(&mutex);\n\treturn true;\n}\n#endif\n\n\nint rbuf::get_read_ptr(void**p, int size)\n{\n\tpthread_mutex_lock(&mutex);\n\n\treturn __get_read_ptr(p, size);\n}\n\nvoid rbuf::put_read_ptr(int size)\n{\n\t__put_read_ptr(size);\n\n\tpthread_mutex_unlock(&mutex);\n}\n\nint rbuf::read(void* p, int size)\n{\n\tvoid *q = NULL;\n\tint newsize = get_read_ptr(&q, size);\n\n\tif (newsize)\n\t\tmemcpy(p, q, newsize);\n\n\tput_read_ptr(newsize);\n\treturn newsize;\n}\n\n\nint rbuf::__get_size()\n{\n\tint ret = idx_write - idx_read;\n\n\tif (ret < 0)\n\t\tret += capacity;\n\n\treturn ret;\n}\n\nvoid rbuf::__reset()\n{\n\tidx_read = idx_write = 0;\n}\n\nint rbuf::__get_write_ptr(void** p)\n{\n\tint available = (idx_read <= idx_write) ? capacity - idx_write : idx_read - idx_write;\n\n\tif (available <= 0) {\n\t\tpthread_mutex_unlock(&mutex);\n\t\treturn available;\n\t}\n\t*p = &p_data[idx_write];\n\n\treturn available;\n}\n\nvoid rbuf::__put_write_ptr(int size)\n{\n\tif (idx_write + size >= capacity) { \/\/ == should be enough FIXME!\n\t\tidx_write = 0;\n\t} else {\n\t\tidx_write += size;\n\t}\n}\n\nint rbuf::__get_read_ptr(void**p, int size)\n{\n\tint max_size = __get_size();\n\n\tif (max_size == 0)\n\t\treturn 0;\n\n\tif (size > max_size)\n\t\tsize = max_size;\n\n\tif (idx_read + size >= capacity) {\n\t\tsize = capacity - idx_read;\n\t\t*p = p_data + idx_read;\n\t} else {\n\t\t*p = p_data + idx_read;\n\t}\n\treturn size;\n}\n\nvoid rbuf::__put_read_ptr(int size)\n{\n\tif (idx_read + size >= capacity) {\n\t\tidx_read = 0;\n\t} else {\n\t\tidx_read += size;\n\t}\n}\n<commit_msg>rbuf: make get_capacity() less verbose<commit_after>\/*****************************************************************************\n * Copyright (C) 2011-2012 Michael Krufky\n *\n * Author: Michael Krufky <mkrufky@linuxtv.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 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 *****************************************************************************\/\n#define DBG 0\n\n#include <string.h>\n#include \"rbuf.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"rbuf\"\n\n#define dprintf(fmt, arg...) __dprintf(DBG_OUTPUT, fmt, ##arg)\n\nrbuf::rbuf()\n : capacity(0)\n , p_data(NULL)\n , idx_read(0)\n , idx_write(0)\n{\n\tdprintf(\"()\");\n\tpthread_mutex_init(&mutex, 0);\n}\n\nrbuf::~rbuf()\n{\n\tdprintf(\"()\");\n\tpthread_mutex_lock(&mutex);\n\n\tif (p_data)\n\t\tdelete p_data;\n\n\tpthread_mutex_unlock(&mutex);\n\tpthread_mutex_destroy(&mutex);\n}\n\nvoid rbuf::set_capacity(int cap)\n{\n\tdprintf(\"(%d)\", cap);\n\tpthread_mutex_lock(&mutex);\n\n\tif (p_data)\n\t\tdelete p_data;\n\n\tp_data = new char[(capacity = cap)];\n\t__reset();\n\n\tpthread_mutex_unlock(&mutex);\n}\n\nint rbuf::get_capacity()\n{\n#if DBG\n\tdprintf(\"(%d)\", capacity);\n#endif\n\treturn capacity;\n}\n\nint rbuf::get_size()\n{\n#if DBG\n\tdprintf(\"()\");\n#endif\n\tpthread_mutex_lock(&mutex);\n\n\tint ret = __get_size();\n\n\tpthread_mutex_unlock(&mutex);\n\n\treturn ret;\n}\n\nvoid rbuf::reset()\n{\n\tdprintf(\"()\");\n\tpthread_mutex_lock(&mutex);\n\n\t__reset();\n\n\tpthread_mutex_unlock(&mutex);\n}\n\n\nint rbuf::get_write_ptr(void** p)\n{\n\tpthread_mutex_lock(&mutex);\n\n\treturn __get_write_ptr(p);\n}\n\nvoid rbuf::put_write_ptr(int size)\n{\n\t__put_write_ptr(size);\n\n\tpthread_mutex_unlock(&mutex);\n}\n\n#if 0\nbool rbuf::write(const void* p, int size)\n{\n\tpthread_mutex_lock(&mutex);\n\n\tif (__get_size() + size > capacity)\n\t\treturn false;\n\n if (idx_write + size > capacity) {\n\t\tint split = capacity - idx_write;\n\t\tmemcpy(p_data + idx_write, p, split);\n\t\tidx_write = size - split;\n\t\tmemcpy(p_data, (const char*) p + split, idx_write);\n } else {\n\t\tmemcpy(p_data + idx_write, p, size);\n\t\tidx_write += size;\n\t\tif (idx_write == capacity)\n\t\t\tidx_write = 0;\n }\n\tpthread_mutex_unlock(&mutex);\n return true;\n}\n#else\nbool rbuf::write(const void* p, int size)\n{\n\tpthread_mutex_lock(&mutex);\n\tif (__get_size() + size > capacity)\n\t\treturn false;\n\n\tvoid *q = NULL;\n\tchar *r = (char*)p;\n\tint available;\n\n\twhile (size) {\n\t\tavailable = __get_write_ptr(&q);\n\t\tif (available >= size) {\n\t\t\tmemcpy(q, r, size);\n\t\t\t__put_write_ptr(size);\n\t\t\tsize = 0;\n\t\t} else if (available > 0) {\n\t\t\tmemcpy(q, r, available);\n\t\t\t__put_write_ptr(available);\n\t\t\tsize -= available;\n\t\t\tr += available;\n\t\t}\n#if 0\n\t\telse {\n\/\/\t\t\tpthread_mutex_unlock(&mutex);\n\t\t\treturn false;\n\t\t}\n#endif\n\t}\n\tpthread_mutex_unlock(&mutex);\n\treturn true;\n}\n#endif\n\n\nint rbuf::get_read_ptr(void**p, int size)\n{\n\tpthread_mutex_lock(&mutex);\n\n\treturn __get_read_ptr(p, size);\n}\n\nvoid rbuf::put_read_ptr(int size)\n{\n\t__put_read_ptr(size);\n\n\tpthread_mutex_unlock(&mutex);\n}\n\nint rbuf::read(void* p, int size)\n{\n\tvoid *q = NULL;\n\tint newsize = get_read_ptr(&q, size);\n\n\tif (newsize)\n\t\tmemcpy(p, q, newsize);\n\n\tput_read_ptr(newsize);\n\treturn newsize;\n}\n\n\nint rbuf::__get_size()\n{\n\tint ret = idx_write - idx_read;\n\n\tif (ret < 0)\n\t\tret += capacity;\n\n\treturn ret;\n}\n\nvoid rbuf::__reset()\n{\n\tidx_read = idx_write = 0;\n}\n\nint rbuf::__get_write_ptr(void** p)\n{\n\tint available = (idx_read <= idx_write) ? capacity - idx_write : idx_read - idx_write;\n\n\tif (available <= 0) {\n\t\tpthread_mutex_unlock(&mutex);\n\t\treturn available;\n\t}\n\t*p = &p_data[idx_write];\n\n\treturn available;\n}\n\nvoid rbuf::__put_write_ptr(int size)\n{\n\tif (idx_write + size >= capacity) { \/\/ == should be enough FIXME!\n\t\tidx_write = 0;\n\t} else {\n\t\tidx_write += size;\n\t}\n}\n\nint rbuf::__get_read_ptr(void**p, int size)\n{\n\tint max_size = __get_size();\n\n\tif (max_size == 0)\n\t\treturn 0;\n\n\tif (size > max_size)\n\t\tsize = max_size;\n\n\tif (idx_read + size >= capacity) {\n\t\tsize = capacity - idx_read;\n\t\t*p = p_data + idx_read;\n\t} else {\n\t\t*p = p_data + idx_read;\n\t}\n\treturn size;\n}\n\nvoid rbuf::__put_read_ptr(int size)\n{\n\tif (idx_read + size >= capacity) {\n\t\tidx_read = 0;\n\t} else {\n\t\tidx_read += size;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program 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 General Public License for *\n* 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., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*\n* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *\n* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\n#include \"FileManagement.h\"\n#include <iostream>\n\nnamespace sofa\n{\nnamespace gui\n{\nnamespace qt\n{\n\n\n#ifndef SOFA_QT4\ntypedef QFileDialog Q3FileDialog;\n#include <qdir.h>\n#include <qfileinfo.h>\n#else\n#include <QDir>\n#endif\n\nQString getExistingDirectory ( QWidget* parent, const QString & dir, const char * name, const QString & caption)\n{\n#ifdef SOFA_QT4\n QFileDialog::Options options = QFileDialog::ShowDirsOnly;\n \/\/\toptions |= QFileDialog::DontUseNativeDialog;\n options |= QFileDialog::QFileDialog::DontUseSheet;\n return QFileDialog::getExistingDirectory ( parent, name?QString(name):caption, dir, options );\n#else\n return Q3FileDialog::getExistingDirectory( dir, parent, name, caption );\n#endif\n};\n\nQString getOpenFileName ( QWidget* parent, const QString & startWith, const QString & filter, const char * name, const QString & caption, QString * selectedFilter )\n{\n#ifdef SOFA_QT4\n QFileDialog::Options options = 0;\n \/\/\toptions |= QFileDialog::DontUseNativeDialog;\n options |= QFileDialog::DontUseSheet;\n return QFileDialog::getOpenFileName ( parent, name?QString(name):caption, startWith, filter, selectedFilter, options );\n#else\n return Q3FileDialog::getOpenFileName ( startWith, filter, parent, name, caption, selectedFilter );\n#endif\n};\n\nQString getSaveFileName ( QWidget* parent, const QString & startWith, const QString & filter, const char * name, const QString & caption, QString * selectedFilter )\n{\n#ifdef SOFA_QT4\n QFileDialog::Options options = 0;\n \/\/\toptions |= QFileDialog::DontUseNativeDialog;\n options |= QFileDialog::DontUseSheet;\n return QFileDialog::getSaveFileName ( parent, name?QString(name):caption, startWith, filter, selectedFilter, options );\n#else\n return Q3FileDialog::getSaveFileName ( startWith, filter, parent, name, caption, selectedFilter );\n#endif\n};\n\nvoid getFilesInDirectory( const QString &p, std::vector< QString > &files, bool recursive, const std::vector< QString > &filter )\n{\n QString path=p;\n if (path.endsWith(\"\/\"))\n {\n int slash=path.find('\/',-1);\n path.truncate(slash);\n }\n else if (path.endsWith(\"\\\\\"))\n {\n int slash=path.find('\\\\',-1);\n path.truncate(slash);\n }\n\n QDir d(path);\n\n d.setFilter( QDir::Dirs | QDir::Hidden | QDir::NoSymLinks );\n\n std::vector< QString > subDir;\n\n const QFileInfoList &listDirectories =\n#ifdef SOFA_QT4\n d.entryInfoList();\n QStringList filters;\n for (unsigned int i=0; i<filter.size(); ++i)\n filters << filter[i];\n\n d.setNameFilters(filters);\n for (int j = 0; j < listDirectories.size(); ++j)\n {\n QFileInfo fileInfo=listDirectories.at(j);\n#else\n *(d.entryInfoList());\n QString filters;\n for (unsigned int i=0; i<filter.size(); ++i)\n filters+= filter[i] + QString(\" \");\n\n d.setNameFilter(filters);\n QFileInfoListIterator itDir( listDirectories );\n while ( (itDir.current()) != 0 )\n {\n\n QFileInfo fileInfo=*(itDir.current());\n#endif\n subDir.push_back(fileInfo.fileName());\n#ifndef SOFA_QT4\n ++itDir;\n#endif\n }\n\n d.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks );\n\n const QFileInfoList &listFiles =\n#ifdef SOFA_QT4\n d.entryInfoList();\n for (int j = 0; j < listFiles.size(); ++j)\n {\n QFileInfo fileInfo=listFiles.at(j);\n#else\n *(d.entryInfoList());\n QFileInfoListIterator itFile( listFiles );\n while ( (itFile.current()) != 0 )\n {\n QFileInfo fileInfo=*(itFile.current());\n#endif\n files.push_back(path+QString(\"\/\")+fileInfo.fileName());\n#ifndef SOFA_QT4\n ++itFile;\n#endif\n }\n\n if (recursive)\n {\n for (unsigned int i=0; i<subDir.size(); ++i)\n {\n if (subDir[i].left(1) == QString(\".\")) continue;\n if (subDir[i] == QString(\"OBJ\")) continue;\n\n QString nextDir=path+QString(\"\/\")+subDir[i];\n getFilesInDirectory(nextDir, files, recursive, filter);\n }\n }\n}\n\n} \/\/ namespace qt\n\n} \/\/ namespace gui\n\n} \/\/ namespace sofa\n\n<commit_msg>r4822\/sofa-dev : FIX: small namespace mistake for sofa_QT4.<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program 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 General Public License for *\n* 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., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*\n* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *\n* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\n#include \"FileManagement.h\"\n#include <iostream>\n\nnamespace sofa\n{\nnamespace gui\n{\nnamespace qt\n{\n\n\n#ifndef SOFA_QT4\ntypedef QFileDialog Q3FileDialog;\n#include <qdir.h>\n#include <qfileinfo.h>\n#else\n#include <QDir>\n#endif\n\nQString getExistingDirectory ( QWidget* parent, const QString & dir, const char * name, const QString & caption)\n{\n#ifdef SOFA_QT4\n QFileDialog::Options options = QFileDialog::ShowDirsOnly;\n \/\/\toptions |= QFileDialog::DontUseNativeDialog;\n options |= QFileDialog::DontUseSheet;\n return QFileDialog::getExistingDirectory ( parent, name?QString(name):caption, dir, options );\n#else\n return Q3FileDialog::getExistingDirectory( dir, parent, name, caption );\n#endif\n};\n\nQString getOpenFileName ( QWidget* parent, const QString & startWith, const QString & filter, const char * name, const QString & caption, QString * selectedFilter )\n{\n#ifdef SOFA_QT4\n QFileDialog::Options options = 0;\n \/\/\toptions |= QFileDialog::DontUseNativeDialog;\n options |= QFileDialog::DontUseSheet;\n return QFileDialog::getOpenFileName ( parent, name?QString(name):caption, startWith, filter, selectedFilter, options );\n#else\n return Q3FileDialog::getOpenFileName ( startWith, filter, parent, name, caption, selectedFilter );\n#endif\n};\n\nQString getSaveFileName ( QWidget* parent, const QString & startWith, const QString & filter, const char * name, const QString & caption, QString * selectedFilter )\n{\n#ifdef SOFA_QT4\n QFileDialog::Options options = 0;\n \/\/\toptions |= QFileDialog::DontUseNativeDialog;\n options |= QFileDialog::DontUseSheet;\n return QFileDialog::getSaveFileName ( parent, name?QString(name):caption, startWith, filter, selectedFilter, options );\n#else\n return Q3FileDialog::getSaveFileName ( startWith, filter, parent, name, caption, selectedFilter );\n#endif\n};\n\nvoid getFilesInDirectory( const QString &p, std::vector< QString > &files, bool recursive, const std::vector< QString > &filter )\n{\n QString path=p;\n if (path.endsWith(\"\/\"))\n {\n int slash=path.find('\/',-1);\n path.truncate(slash);\n }\n else if (path.endsWith(\"\\\\\"))\n {\n int slash=path.find('\\\\',-1);\n path.truncate(slash);\n }\n\n QDir d(path);\n\n d.setFilter( QDir::Dirs | QDir::Hidden | QDir::NoSymLinks );\n\n std::vector< QString > subDir;\n\n const QFileInfoList &listDirectories =\n#ifdef SOFA_QT4\n d.entryInfoList();\n QStringList filters;\n for (unsigned int i=0; i<filter.size(); ++i)\n filters << filter[i];\n\n d.setNameFilters(filters);\n for (int j = 0; j < listDirectories.size(); ++j)\n {\n QFileInfo fileInfo=listDirectories.at(j);\n#else\n *(d.entryInfoList());\n QString filters;\n for (unsigned int i=0; i<filter.size(); ++i)\n filters+= filter[i] + QString(\" \");\n\n d.setNameFilter(filters);\n QFileInfoListIterator itDir( listDirectories );\n while ( (itDir.current()) != 0 )\n {\n\n QFileInfo fileInfo=*(itDir.current());\n#endif\n subDir.push_back(fileInfo.fileName());\n#ifndef SOFA_QT4\n ++itDir;\n#endif\n }\n\n d.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks );\n\n const QFileInfoList &listFiles =\n#ifdef SOFA_QT4\n d.entryInfoList();\n for (int j = 0; j < listFiles.size(); ++j)\n {\n QFileInfo fileInfo=listFiles.at(j);\n#else\n *(d.entryInfoList());\n QFileInfoListIterator itFile( listFiles );\n while ( (itFile.current()) != 0 )\n {\n QFileInfo fileInfo=*(itFile.current());\n#endif\n files.push_back(path+QString(\"\/\")+fileInfo.fileName());\n#ifndef SOFA_QT4\n ++itFile;\n#endif\n }\n\n if (recursive)\n {\n for (unsigned int i=0; i<subDir.size(); ++i)\n {\n if (subDir[i].left(1) == QString(\".\")) continue;\n if (subDir[i] == QString(\"OBJ\")) continue;\n\n QString nextDir=path+QString(\"\/\")+subDir[i];\n getFilesInDirectory(nextDir, files, recursive, filter);\n }\n }\n}\n\n} \/\/ namespace qt\n\n} \/\/ namespace gui\n\n} \/\/ namespace sofa\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is 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 OR\n 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\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Physics\/Capsule.h\"\n#include \"Physics\/Point.h\"\n#include \"Physics\/Sphere.h\"\n\n#include \"ShapeTestBase.h\"\n\nnamespace Magnum { namespace Physics { namespace Test {\n\nclass CapsuleTest: public Corrade::TestSuite::Tester, ShapeTestBase {\n public:\n CapsuleTest();\n\n void applyTransformation();\n void collisionPoint();\n void collisionSphere();\n};\n\nCapsuleTest::CapsuleTest() {\n addTests({&CapsuleTest::applyTransformation,\n &CapsuleTest::collisionPoint});\n}\n\nvoid CapsuleTest::applyTransformation() {\n Physics::Capsule3D capsule({1.0f, 2.0f, 3.0f}, {-1.0f, -2.0f, -3.0f}, 7.0f);\n\n capsule.applyTransformationMatrix(Matrix4::rotation(Deg(90.0f), Vector3::zAxis()));\n CORRADE_COMPARE(capsule.transformedA(), Vector3(-2.0f, 1.0f, 3.0f));\n CORRADE_COMPARE(capsule.transformedB(), Vector3(2.0f, -1.0f, -3.0f));\n CORRADE_COMPARE(capsule.radius(), 7.0f);\n\n \/* Apply average scaling to radius *\/\n capsule.applyTransformationMatrix(Matrix4::scaling({Constants::sqrt3(), -Constants::sqrt2(), 2.0f}));\n CORRADE_COMPARE(capsule.transformedRadius(), Constants::sqrt3()*7.0f);\n}\n\nvoid CapsuleTest::collisionPoint() {\n Physics::Capsule3D capsule({-1.0f, -1.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, 2.0f);\n Physics::Point3D point({2.0f, 0.0f, 0.0f});\n Physics::Point3D point1({2.9f, 1.0f, 0.0f});\n Physics::Point3D point2({1.0f, 3.1f, 0.0f});\n\n randomTransformation(capsule);\n randomTransformation(point);\n randomTransformation(point1);\n randomTransformation(point2);\n\n VERIFY_COLLIDES(capsule, point);\n VERIFY_COLLIDES(capsule, point1);\n VERIFY_NOT_COLLIDES(capsule, point2);\n}\n\nvoid CapsuleTest::collisionSphere() {\n Physics::Capsule3D capsule({-1.0f, -1.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, 2.0f);\n Physics::Sphere3D sphere({3.0f, 0.0f, 0.0f}, 0.9f);\n Physics::Sphere3D sphere1({3.5f, 1.0f, 0.0f}, 0.6f);\n Physics::Sphere3D sphere2({1.0f, 4.1f, 0.0f}, 1.0f);\n\n randomTransformation(capsule);\n randomTransformation(sphere);\n randomTransformation(sphere1);\n randomTransformation(sphere2);\n\n VERIFY_COLLIDES(capsule, sphere);\n VERIFY_COLLIDES(capsule, sphere1);\n VERIFY_NOT_COLLIDES(capsule, sphere2);\n}\n\n}}}\n\nCORRADE_TEST_MAIN(Magnum::Physics::Test::CapsuleTest)\n<commit_msg>Physics: forgot to add test case to the list.<commit_after>\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is 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 OR\n 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\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Physics\/Capsule.h\"\n#include \"Physics\/Point.h\"\n#include \"Physics\/Sphere.h\"\n\n#include \"ShapeTestBase.h\"\n\nnamespace Magnum { namespace Physics { namespace Test {\n\nclass CapsuleTest: public Corrade::TestSuite::Tester, ShapeTestBase {\n public:\n CapsuleTest();\n\n void applyTransformation();\n void collisionPoint();\n void collisionSphere();\n};\n\nCapsuleTest::CapsuleTest() {\n addTests({&CapsuleTest::applyTransformation,\n &CapsuleTest::collisionPoint,\n &CapsuleTest::collisionSphere});\n}\n\nvoid CapsuleTest::applyTransformation() {\n Physics::Capsule3D capsule({1.0f, 2.0f, 3.0f}, {-1.0f, -2.0f, -3.0f}, 7.0f);\n\n capsule.applyTransformationMatrix(Matrix4::rotation(Deg(90.0f), Vector3::zAxis()));\n CORRADE_COMPARE(capsule.transformedA(), Vector3(-2.0f, 1.0f, 3.0f));\n CORRADE_COMPARE(capsule.transformedB(), Vector3(2.0f, -1.0f, -3.0f));\n CORRADE_COMPARE(capsule.radius(), 7.0f);\n\n \/* Apply average scaling to radius *\/\n capsule.applyTransformationMatrix(Matrix4::scaling({Constants::sqrt3(), -Constants::sqrt2(), 2.0f}));\n CORRADE_COMPARE(capsule.transformedRadius(), Constants::sqrt3()*7.0f);\n}\n\nvoid CapsuleTest::collisionPoint() {\n Physics::Capsule3D capsule({-1.0f, -1.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, 2.0f);\n Physics::Point3D point({2.0f, 0.0f, 0.0f});\n Physics::Point3D point1({2.9f, 1.0f, 0.0f});\n Physics::Point3D point2({1.0f, 3.1f, 0.0f});\n\n randomTransformation(capsule);\n randomTransformation(point);\n randomTransformation(point1);\n randomTransformation(point2);\n\n VERIFY_COLLIDES(capsule, point);\n VERIFY_COLLIDES(capsule, point1);\n VERIFY_NOT_COLLIDES(capsule, point2);\n}\n\nvoid CapsuleTest::collisionSphere() {\n Physics::Capsule3D capsule({-1.0f, -1.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, 2.0f);\n Physics::Sphere3D sphere({3.0f, 0.0f, 0.0f}, 0.9f);\n Physics::Sphere3D sphere1({3.5f, 1.0f, 0.0f}, 0.6f);\n Physics::Sphere3D sphere2({1.0f, 4.1f, 0.0f}, 1.0f);\n\n randomTransformation(capsule);\n randomTransformation(sphere);\n randomTransformation(sphere1);\n randomTransformation(sphere2);\n\n VERIFY_COLLIDES(capsule, sphere);\n VERIFY_COLLIDES(capsule, sphere1);\n VERIFY_NOT_COLLIDES(capsule, sphere2);\n}\n\n}}}\n\nCORRADE_TEST_MAIN(Magnum::Physics::Test::CapsuleTest)\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- RegisterScavenging.cpp - Machine register scavenging --------------===\/\/\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\/\/ This file implements the machine register scavenger. It can provide\n\/\/ information, such as unused registers, at any point in a machine basic block.\n\/\/ It also provides a mechanism to make registers available by evicting them to\n\/\/ spill slots.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"reg-scavenging\"\n#include \"llvm\/CodeGen\/RegisterScavenging.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineBasicBlock.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\nusing namespace llvm;\n\n\/\/\/ setUsed - Set the register and its sub-registers as being used.\nvoid RegScavenger::setUsed(unsigned Reg) {\n RegsAvailable.reset(Reg);\n\n for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);\n unsigned SubReg = *SubRegs; ++SubRegs)\n RegsAvailable.reset(SubReg);\n}\n\nbool RegScavenger::isAliasUsed(unsigned Reg) const {\n if (isUsed(Reg))\n return true;\n for (const unsigned *R = TRI->getAliasSet(Reg); *R; ++R)\n if (isUsed(*R))\n return true;\n return false;\n}\n\nvoid RegScavenger::initRegState() {\n ScavengedReg = 0;\n ScavengedRC = NULL;\n ScavengeRestore = NULL;\n\n \/\/ All registers started out unused.\n RegsAvailable.set();\n\n \/\/ Reserved registers are always used.\n RegsAvailable ^= ReservedRegs;\n\n if (!MBB)\n return;\n\n \/\/ Live-in registers are in use.\n for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),\n E = MBB->livein_end(); I != E; ++I)\n setUsed(*I);\n\n \/\/ Pristine CSRs are also unavailable.\n BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);\n for (int I = PR.find_first(); I>0; I = PR.find_next(I))\n setUsed(I);\n}\n\nvoid RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {\n MachineFunction &MF = *mbb->getParent();\n const TargetMachine &TM = MF.getTarget();\n TII = TM.getInstrInfo();\n TRI = TM.getRegisterInfo();\n MRI = &MF.getRegInfo();\n\n assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&\n \"Target changed?\");\n\n \/\/ Self-initialize.\n if (!MBB) {\n NumPhysRegs = TRI->getNumRegs();\n RegsAvailable.resize(NumPhysRegs);\n\n \/\/ Create reserved registers bitvector.\n ReservedRegs = TRI->getReservedRegs(MF);\n\n \/\/ Create callee-saved registers bitvector.\n CalleeSavedRegs.resize(NumPhysRegs);\n const unsigned *CSRegs = TRI->getCalleeSavedRegs(&MF);\n if (CSRegs != NULL)\n for (unsigned i = 0; CSRegs[i]; ++i)\n CalleeSavedRegs.set(CSRegs[i]);\n }\n\n MBB = mbb;\n initRegState();\n\n Tracking = false;\n}\n\nvoid RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {\n BV.set(Reg);\n for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)\n BV.set(*R);\n}\n\nvoid RegScavenger::addRegWithAliases(BitVector &BV, unsigned Reg) {\n BV.set(Reg);\n for (const unsigned *R = TRI->getAliasSet(Reg); *R; R++)\n BV.set(*R);\n}\n\nvoid RegScavenger::forward() {\n \/\/ Move ptr forward.\n if (!Tracking) {\n MBBI = MBB->begin();\n Tracking = true;\n } else {\n assert(MBBI != MBB->end() && \"Already past the end of the basic block!\");\n MBBI = llvm::next(MBBI);\n }\n assert(MBBI != MBB->end() && \"Already at the end of the basic block!\");\n\n MachineInstr *MI = MBBI;\n\n if (MI == ScavengeRestore) {\n ScavengedReg = 0;\n ScavengedRC = NULL;\n ScavengeRestore = NULL;\n }\n\n if (MI->isDebugValue())\n return;\n\n \/\/ Find out which registers are early clobbered, killed, defined, and marked\n \/\/ def-dead in this instruction.\n \/\/ FIXME: The scavenger is not predication aware. If the instruction is\n \/\/ predicated, conservatively assume \"kill\" markers do not actually kill the\n \/\/ register. Similarly ignores \"dead\" markers.\n bool isPred = TII->isPredicated(MI);\n BitVector EarlyClobberRegs(NumPhysRegs);\n BitVector KillRegs(NumPhysRegs);\n BitVector DefRegs(NumPhysRegs);\n BitVector DeadRegs(NumPhysRegs);\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (!MO.isReg())\n continue;\n unsigned Reg = MO.getReg();\n if (!Reg || isReserved(Reg))\n continue;\n\n if (MO.isUse()) {\n \/\/ Ignore undef uses.\n if (MO.isUndef())\n continue;\n \/\/ Two-address operands implicitly kill.\n if (!isPred && (MO.isKill() || MI->isRegTiedToDefOperand(i)))\n addRegWithSubRegs(KillRegs, Reg);\n } else {\n assert(MO.isDef());\n if (!isPred && MO.isDead())\n addRegWithSubRegs(DeadRegs, Reg);\n else\n addRegWithSubRegs(DefRegs, Reg);\n if (MO.isEarlyClobber())\n addRegWithAliases(EarlyClobberRegs, Reg);\n }\n }\n\n \/\/ Verify uses and defs.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (!MO.isReg())\n continue;\n unsigned Reg = MO.getReg();\n if (!Reg || isReserved(Reg))\n continue;\n if (MO.isUse()) {\n if (MO.isUndef())\n continue;\n if (!isUsed(Reg)) {\n \/\/ Check if it's partial live: e.g.\n \/\/ D0 = insert_subreg D0<undef>, S0\n \/\/ ... D0\n \/\/ The problem is the insert_subreg could be eliminated. The use of\n \/\/ D0 is using a partially undef value. This is not *incorrect* since\n \/\/ S1 is can be freely clobbered.\n \/\/ Ideally we would like a way to model this, but leaving the\n \/\/ insert_subreg around causes both correctness and performance issues.\n bool SubUsed = false;\n for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);\n unsigned SubReg = *SubRegs; ++SubRegs)\n if (isUsed(SubReg)) {\n SubUsed = true;\n break;\n }\n#ifndef NDEBUG\n if (!SubUsed) {\n MBB->getParent()->verify(NULL, \"In Register Scavenger\");\n llvm_unreachable(\"Using an undefined register!\");\n }\n#endif\n (void)SubUsed;\n }\n assert((!EarlyClobberRegs.test(Reg) || MI->isRegTiedToDefOperand(i)) &&\n \"Using an early clobbered register!\");\n } else {\n assert(MO.isDef());\n#if 0\n \/\/ FIXME: Enable this once we've figured out how to correctly transfer\n \/\/ implicit kills during codegen passes like the coalescer.\n assert((KillRegs.test(Reg) || isUnused(Reg) ||\n isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&\n \"Re-defining a live register!\");\n#endif\n }\n }\n\n \/\/ Commit the changes.\n setUnused(KillRegs);\n setUnused(DeadRegs);\n setUsed(DefRegs);\n}\n\nvoid RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {\n if (includeReserved)\n used = ~RegsAvailable;\n else\n used = ~RegsAvailable & ~ReservedRegs;\n}\n\nunsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {\n for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();\n I != E; ++I)\n if (!isAliasUsed(*I)) {\n DEBUG(dbgs() << \"Scavenger found unused reg: \" << TRI->getName(*I) <<\n \"\\n\");\n return *I;\n }\n return 0;\n}\n\n\/\/\/ getRegsAvailable - Return all available registers in the register class\n\/\/\/ in Mask.\nBitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {\n BitVector Mask(TRI->getNumRegs());\n for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();\n I != E; ++I)\n if (!isAliasUsed(*I))\n Mask.set(*I);\n return Mask;\n}\n\n\/\/\/ findSurvivorReg - Return the candidate register that is unused for the\n\/\/\/ longest after StargMII. UseMI is set to the instruction where the search\n\/\/\/ stopped.\n\/\/\/\n\/\/\/ No more than InstrLimit instructions are inspected.\n\/\/\/\nunsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,\n BitVector &Candidates,\n unsigned InstrLimit,\n MachineBasicBlock::iterator &UseMI) {\n int Survivor = Candidates.find_first();\n assert(Survivor > 0 && \"No candidates for scavenging\");\n\n MachineBasicBlock::iterator ME = MBB->getFirstTerminator();\n assert(StartMI != ME && \"MI already at terminator\");\n MachineBasicBlock::iterator RestorePointMI = StartMI;\n MachineBasicBlock::iterator MI = StartMI;\n\n bool inVirtLiveRange = false;\n for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {\n if (MI->isDebugValue()) {\n ++InstrLimit; \/\/ Don't count debug instructions\n continue;\n }\n bool isVirtKillInsn = false;\n bool isVirtDefInsn = false;\n \/\/ Remove any candidates touched by instruction.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (!MO.isReg() || MO.isUndef() || !MO.getReg())\n continue;\n if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {\n if (MO.isDef())\n isVirtDefInsn = true;\n else if (MO.isKill())\n isVirtKillInsn = true;\n continue;\n }\n Candidates.reset(MO.getReg());\n for (const unsigned *R = TRI->getAliasSet(MO.getReg()); *R; R++)\n Candidates.reset(*R);\n }\n \/\/ If we're not in a virtual reg's live range, this is a valid\n \/\/ restore point.\n if (!inVirtLiveRange) RestorePointMI = MI;\n\n \/\/ Update whether we're in the live range of a virtual register\n if (isVirtKillInsn) inVirtLiveRange = false;\n if (isVirtDefInsn) inVirtLiveRange = true;\n\n \/\/ Was our survivor untouched by this instruction?\n if (Candidates.test(Survivor))\n continue;\n\n \/\/ All candidates gone?\n if (Candidates.none())\n break;\n\n Survivor = Candidates.find_first();\n }\n \/\/ If we ran off the end, that's where we want to restore.\n if (MI == ME) RestorePointMI = ME;\n assert (RestorePointMI != StartMI &&\n \"No available scavenger restore location!\");\n\n \/\/ We ran out of candidates, so stop the search.\n UseMI = RestorePointMI;\n return Survivor;\n}\n\nunsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,\n MachineBasicBlock::iterator I,\n int SPAdj) {\n \/\/ Consider all allocatable registers in the register class initially\n BitVector Candidates =\n TRI->getAllocatableSet(*I->getParent()->getParent(), RC);\n\n \/\/ Exclude all the registers being used by the instruction.\n for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {\n MachineOperand &MO = I->getOperand(i);\n if (MO.isReg() && MO.getReg() != 0 &&\n !TargetRegisterInfo::isVirtualRegister(MO.getReg()))\n Candidates.reset(MO.getReg());\n }\n\n \/\/ Try to find a register that's unused if there is one, as then we won't\n \/\/ have to spill. Search explicitly rather than masking out based on\n \/\/ RegsAvailable, as RegsAvailable does not take aliases into account.\n \/\/ That's what getRegsAvailable() is for.\n BitVector Available = getRegsAvailable(RC);\n\n if ((Candidates & Available).any())\n Candidates &= Available;\n\n \/\/ Find the register whose use is furthest away.\n MachineBasicBlock::iterator UseMI;\n unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);\n\n \/\/ If we found an unused register there is no reason to spill it.\n if (!isAliasUsed(SReg)) {\n DEBUG(dbgs() << \"Scavenged register: \" << TRI->getName(SReg) << \"\\n\");\n return SReg;\n }\n\n assert(ScavengedReg == 0 &&\n \"Scavenger slot is live, unable to scavenge another register!\");\n\n \/\/ Avoid infinite regress\n ScavengedReg = SReg;\n\n \/\/ If the target knows how to save\/restore the register, let it do so;\n \/\/ otherwise, use the emergency stack spill slot.\n if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {\n \/\/ Spill the scavenged register before I.\n assert(ScavengingFrameIndex >= 0 &&\n \"Cannot scavenge register without an emergency spill slot!\");\n TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);\n MachineBasicBlock::iterator II = prior(I);\n TRI->eliminateFrameIndex(II, SPAdj, this);\n\n \/\/ Restore the scavenged register before its use (or first terminator).\n TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);\n II = prior(UseMI);\n TRI->eliminateFrameIndex(II, SPAdj, this);\n }\n\n ScavengeRestore = prior(UseMI);\n\n \/\/ Doing this here leads to infinite regress.\n \/\/ ScavengedReg = SReg;\n ScavengedRC = RC;\n\n DEBUG(dbgs() << \"Scavenged register (with spill): \" << TRI->getName(SReg) <<\n \"\\n\");\n\n return SReg;\n}\n<commit_msg>Avoid creating BitVector temporaries.<commit_after>\/\/===-- RegisterScavenging.cpp - Machine register scavenging --------------===\/\/\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\/\/ This file implements the machine register scavenger. It can provide\n\/\/ information, such as unused registers, at any point in a machine basic block.\n\/\/ It also provides a mechanism to make registers available by evicting them to\n\/\/ spill slots.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"reg-scavenging\"\n#include \"llvm\/CodeGen\/RegisterScavenging.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineBasicBlock.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\nusing namespace llvm;\n\n\/\/\/ setUsed - Set the register and its sub-registers as being used.\nvoid RegScavenger::setUsed(unsigned Reg) {\n RegsAvailable.reset(Reg);\n\n for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);\n unsigned SubReg = *SubRegs; ++SubRegs)\n RegsAvailable.reset(SubReg);\n}\n\nbool RegScavenger::isAliasUsed(unsigned Reg) const {\n if (isUsed(Reg))\n return true;\n for (const unsigned *R = TRI->getAliasSet(Reg); *R; ++R)\n if (isUsed(*R))\n return true;\n return false;\n}\n\nvoid RegScavenger::initRegState() {\n ScavengedReg = 0;\n ScavengedRC = NULL;\n ScavengeRestore = NULL;\n\n \/\/ All registers started out unused.\n RegsAvailable.set();\n\n \/\/ Reserved registers are always used.\n RegsAvailable ^= ReservedRegs;\n\n if (!MBB)\n return;\n\n \/\/ Live-in registers are in use.\n for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),\n E = MBB->livein_end(); I != E; ++I)\n setUsed(*I);\n\n \/\/ Pristine CSRs are also unavailable.\n BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);\n for (int I = PR.find_first(); I>0; I = PR.find_next(I))\n setUsed(I);\n}\n\nvoid RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {\n MachineFunction &MF = *mbb->getParent();\n const TargetMachine &TM = MF.getTarget();\n TII = TM.getInstrInfo();\n TRI = TM.getRegisterInfo();\n MRI = &MF.getRegInfo();\n\n assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&\n \"Target changed?\");\n\n \/\/ Self-initialize.\n if (!MBB) {\n NumPhysRegs = TRI->getNumRegs();\n RegsAvailable.resize(NumPhysRegs);\n\n \/\/ Create reserved registers bitvector.\n ReservedRegs = TRI->getReservedRegs(MF);\n\n \/\/ Create callee-saved registers bitvector.\n CalleeSavedRegs.resize(NumPhysRegs);\n const unsigned *CSRegs = TRI->getCalleeSavedRegs(&MF);\n if (CSRegs != NULL)\n for (unsigned i = 0; CSRegs[i]; ++i)\n CalleeSavedRegs.set(CSRegs[i]);\n }\n\n MBB = mbb;\n initRegState();\n\n Tracking = false;\n}\n\nvoid RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {\n BV.set(Reg);\n for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)\n BV.set(*R);\n}\n\nvoid RegScavenger::addRegWithAliases(BitVector &BV, unsigned Reg) {\n BV.set(Reg);\n for (const unsigned *R = TRI->getAliasSet(Reg); *R; R++)\n BV.set(*R);\n}\n\nvoid RegScavenger::forward() {\n \/\/ Move ptr forward.\n if (!Tracking) {\n MBBI = MBB->begin();\n Tracking = true;\n } else {\n assert(MBBI != MBB->end() && \"Already past the end of the basic block!\");\n MBBI = llvm::next(MBBI);\n }\n assert(MBBI != MBB->end() && \"Already at the end of the basic block!\");\n\n MachineInstr *MI = MBBI;\n\n if (MI == ScavengeRestore) {\n ScavengedReg = 0;\n ScavengedRC = NULL;\n ScavengeRestore = NULL;\n }\n\n if (MI->isDebugValue())\n return;\n\n \/\/ Find out which registers are early clobbered, killed, defined, and marked\n \/\/ def-dead in this instruction.\n \/\/ FIXME: The scavenger is not predication aware. If the instruction is\n \/\/ predicated, conservatively assume \"kill\" markers do not actually kill the\n \/\/ register. Similarly ignores \"dead\" markers.\n bool isPred = TII->isPredicated(MI);\n BitVector EarlyClobberRegs(NumPhysRegs);\n BitVector KillRegs(NumPhysRegs);\n BitVector DefRegs(NumPhysRegs);\n BitVector DeadRegs(NumPhysRegs);\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (!MO.isReg())\n continue;\n unsigned Reg = MO.getReg();\n if (!Reg || isReserved(Reg))\n continue;\n\n if (MO.isUse()) {\n \/\/ Ignore undef uses.\n if (MO.isUndef())\n continue;\n \/\/ Two-address operands implicitly kill.\n if (!isPred && (MO.isKill() || MI->isRegTiedToDefOperand(i)))\n addRegWithSubRegs(KillRegs, Reg);\n } else {\n assert(MO.isDef());\n if (!isPred && MO.isDead())\n addRegWithSubRegs(DeadRegs, Reg);\n else\n addRegWithSubRegs(DefRegs, Reg);\n if (MO.isEarlyClobber())\n addRegWithAliases(EarlyClobberRegs, Reg);\n }\n }\n\n \/\/ Verify uses and defs.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (!MO.isReg())\n continue;\n unsigned Reg = MO.getReg();\n if (!Reg || isReserved(Reg))\n continue;\n if (MO.isUse()) {\n if (MO.isUndef())\n continue;\n if (!isUsed(Reg)) {\n \/\/ Check if it's partial live: e.g.\n \/\/ D0 = insert_subreg D0<undef>, S0\n \/\/ ... D0\n \/\/ The problem is the insert_subreg could be eliminated. The use of\n \/\/ D0 is using a partially undef value. This is not *incorrect* since\n \/\/ S1 is can be freely clobbered.\n \/\/ Ideally we would like a way to model this, but leaving the\n \/\/ insert_subreg around causes both correctness and performance issues.\n bool SubUsed = false;\n for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);\n unsigned SubReg = *SubRegs; ++SubRegs)\n if (isUsed(SubReg)) {\n SubUsed = true;\n break;\n }\n#ifndef NDEBUG\n if (!SubUsed) {\n MBB->getParent()->verify(NULL, \"In Register Scavenger\");\n llvm_unreachable(\"Using an undefined register!\");\n }\n#endif\n (void)SubUsed;\n }\n assert((!EarlyClobberRegs.test(Reg) || MI->isRegTiedToDefOperand(i)) &&\n \"Using an early clobbered register!\");\n } else {\n assert(MO.isDef());\n#if 0\n \/\/ FIXME: Enable this once we've figured out how to correctly transfer\n \/\/ implicit kills during codegen passes like the coalescer.\n assert((KillRegs.test(Reg) || isUnused(Reg) ||\n isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&\n \"Re-defining a live register!\");\n#endif\n }\n }\n\n \/\/ Commit the changes.\n setUnused(KillRegs);\n setUnused(DeadRegs);\n setUsed(DefRegs);\n}\n\nvoid RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {\n used = RegsAvailable;\n if (!includeReserved)\n used |= ReservedRegs;\n used.flip();\n}\n\nunsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {\n for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();\n I != E; ++I)\n if (!isAliasUsed(*I)) {\n DEBUG(dbgs() << \"Scavenger found unused reg: \" << TRI->getName(*I) <<\n \"\\n\");\n return *I;\n }\n return 0;\n}\n\n\/\/\/ getRegsAvailable - Return all available registers in the register class\n\/\/\/ in Mask.\nBitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {\n BitVector Mask(TRI->getNumRegs());\n for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();\n I != E; ++I)\n if (!isAliasUsed(*I))\n Mask.set(*I);\n return Mask;\n}\n\n\/\/\/ findSurvivorReg - Return the candidate register that is unused for the\n\/\/\/ longest after StargMII. UseMI is set to the instruction where the search\n\/\/\/ stopped.\n\/\/\/\n\/\/\/ No more than InstrLimit instructions are inspected.\n\/\/\/\nunsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,\n BitVector &Candidates,\n unsigned InstrLimit,\n MachineBasicBlock::iterator &UseMI) {\n int Survivor = Candidates.find_first();\n assert(Survivor > 0 && \"No candidates for scavenging\");\n\n MachineBasicBlock::iterator ME = MBB->getFirstTerminator();\n assert(StartMI != ME && \"MI already at terminator\");\n MachineBasicBlock::iterator RestorePointMI = StartMI;\n MachineBasicBlock::iterator MI = StartMI;\n\n bool inVirtLiveRange = false;\n for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {\n if (MI->isDebugValue()) {\n ++InstrLimit; \/\/ Don't count debug instructions\n continue;\n }\n bool isVirtKillInsn = false;\n bool isVirtDefInsn = false;\n \/\/ Remove any candidates touched by instruction.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (!MO.isReg() || MO.isUndef() || !MO.getReg())\n continue;\n if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {\n if (MO.isDef())\n isVirtDefInsn = true;\n else if (MO.isKill())\n isVirtKillInsn = true;\n continue;\n }\n Candidates.reset(MO.getReg());\n for (const unsigned *R = TRI->getAliasSet(MO.getReg()); *R; R++)\n Candidates.reset(*R);\n }\n \/\/ If we're not in a virtual reg's live range, this is a valid\n \/\/ restore point.\n if (!inVirtLiveRange) RestorePointMI = MI;\n\n \/\/ Update whether we're in the live range of a virtual register\n if (isVirtKillInsn) inVirtLiveRange = false;\n if (isVirtDefInsn) inVirtLiveRange = true;\n\n \/\/ Was our survivor untouched by this instruction?\n if (Candidates.test(Survivor))\n continue;\n\n \/\/ All candidates gone?\n if (Candidates.none())\n break;\n\n Survivor = Candidates.find_first();\n }\n \/\/ If we ran off the end, that's where we want to restore.\n if (MI == ME) RestorePointMI = ME;\n assert (RestorePointMI != StartMI &&\n \"No available scavenger restore location!\");\n\n \/\/ We ran out of candidates, so stop the search.\n UseMI = RestorePointMI;\n return Survivor;\n}\n\nunsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,\n MachineBasicBlock::iterator I,\n int SPAdj) {\n \/\/ Consider all allocatable registers in the register class initially\n BitVector Candidates =\n TRI->getAllocatableSet(*I->getParent()->getParent(), RC);\n\n \/\/ Exclude all the registers being used by the instruction.\n for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {\n MachineOperand &MO = I->getOperand(i);\n if (MO.isReg() && MO.getReg() != 0 &&\n !TargetRegisterInfo::isVirtualRegister(MO.getReg()))\n Candidates.reset(MO.getReg());\n }\n\n \/\/ Try to find a register that's unused if there is one, as then we won't\n \/\/ have to spill. Search explicitly rather than masking out based on\n \/\/ RegsAvailable, as RegsAvailable does not take aliases into account.\n \/\/ That's what getRegsAvailable() is for.\n BitVector Available = getRegsAvailable(RC);\n Available &= Candidates;\n if (Available.any())\n Candidates = Available;\n\n \/\/ Find the register whose use is furthest away.\n MachineBasicBlock::iterator UseMI;\n unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);\n\n \/\/ If we found an unused register there is no reason to spill it.\n if (!isAliasUsed(SReg)) {\n DEBUG(dbgs() << \"Scavenged register: \" << TRI->getName(SReg) << \"\\n\");\n return SReg;\n }\n\n assert(ScavengedReg == 0 &&\n \"Scavenger slot is live, unable to scavenge another register!\");\n\n \/\/ Avoid infinite regress\n ScavengedReg = SReg;\n\n \/\/ If the target knows how to save\/restore the register, let it do so;\n \/\/ otherwise, use the emergency stack spill slot.\n if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {\n \/\/ Spill the scavenged register before I.\n assert(ScavengingFrameIndex >= 0 &&\n \"Cannot scavenge register without an emergency spill slot!\");\n TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);\n MachineBasicBlock::iterator II = prior(I);\n TRI->eliminateFrameIndex(II, SPAdj, this);\n\n \/\/ Restore the scavenged register before its use (or first terminator).\n TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);\n II = prior(UseMI);\n TRI->eliminateFrameIndex(II, SPAdj, this);\n }\n\n ScavengeRestore = prior(UseMI);\n\n \/\/ Doing this here leads to infinite regress.\n \/\/ ScavengedReg = SReg;\n ScavengedRC = RC;\n\n DEBUG(dbgs() << \"Scavenged register (with spill): \" << TRI->getName(SReg) <<\n \"\\n\");\n\n return SReg;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Boost.Foreach support for pugixml classes.\n * This file is provided to the public domain.\n * Written by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)\n *\/\n\n#ifndef HEADER_PUGIXML_FOREACH_HPP\n#define HEADER_PUGIXML_FOREACH_HPP\n\n#include \"pugixml.hpp\"\n\n\/*\n * These types add support for BOOST_FOREACH macro to xml_node and xml_document classes (child iteration only).\n * Example usage:\n * BOOST_FOREACH(xml_node n, doc) {}\n *\/\n\nnamespace boost\n{\n\ttemplate <typename> struct range_mutable_iterator;\n\ttemplate <typename> struct range_const_iterator;\n\n\ttemplate<> struct range_mutable_iterator<pugi::xml_node>\n\t{\n\t\ttypedef pugi::xml_node::iterator type;\n\t};\n\n\ttemplate<> struct range_const_iterator<pugi::xml_node>\n\t{\n\t\ttypedef pugi::xml_node::iterator type;\n\t};\n\n\ttemplate<> struct range_mutable_iterator<pugi::xml_document>\n\t{\n\t\ttypedef pugi::xml_document::iterator type;\n\t};\n\n\ttemplate<> struct range_const_iterator<pugi::xml_document>\n\t{\n\t\ttypedef pugi::xml_document::iterator type;\n\t};\n}\n\n\/*\n * These types add support for BOOST_FOREACH macro to xml_node and xml_document classes (child\/attribute iteration).\n * Example usage:\n * BOOST_FOREACH(xml_node n, children(doc)) {}\n * BOOST_FOREACH(xml_node n, attributes(doc)) {}\n *\/\n\nnamespace pugi\n{\n\tstruct xml_node_children_adapter\n\t{\n\t\ttypedef pugi::xml_node::iterator iterator;\n\t\ttypedef pugi::xml_node::iterator const_iterator;\n\n\t\txml_node node;\n\n\t\tconst_iterator begin() const\n\t\t{\n\t\t\treturn node.begin();\n\t\t}\n\n\t\tconst_iterator end() const\n\t\t{\n\t\t\treturn node.end();\n\t\t}\n\t};\n\n\tinline xml_node_children_adapter children(const pugi::xml_node& node)\n\t{\n\t\txml_node_children_adapter result = {node};\n\t\treturn result;\n\t}\n\n\tstruct xml_node_attribute_adapter\n\t{\n\t\ttypedef pugi::xml_node::attribute_iterator iterator;\n\t\ttypedef pugi::xml_node::attribute_iterator const_iterator;\n\n\t\txml_node node;\n\n\t\tconst_iterator begin() const\n\t\t{\n\t\t\treturn node.attributes_begin();\n\t\t}\n\n\t\tconst_iterator end() const\n\t\t{\n\t\t\treturn node.attributes_end();\n\t\t}\n\t};\n\n\tinline xml_node_attribute_adapter attributes(const pugi::xml_node& node)\n\t{\n\t\txml_node_attribute_adapter result = {node};\n\t\treturn result;\n\t}\n}\n\n#endif\n<commit_msg>contrib: Foreach contrib file is not really needed any more; left for compatibility, + removed node\/attribute adapters since we now have object range support in pugixml.hpp<commit_after>\/*\n * Boost.Foreach support for pugixml classes.\n * This file is provided to the public domain.\n * Written by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)\n *\/\n\n#ifndef HEADER_PUGIXML_FOREACH_HPP\n#define HEADER_PUGIXML_FOREACH_HPP\n\n#include \"pugixml.hpp\"\n\n\/*\n * These types add support for BOOST_FOREACH macro to xml_node and xml_document classes (child iteration only).\n * Example usage:\n * BOOST_FOREACH(xml_node n, doc) {}\n *\/\n\nnamespace boost\n{\n\ttemplate <typename> struct range_mutable_iterator;\n\ttemplate <typename> struct range_const_iterator;\n\n\ttemplate<> struct range_mutable_iterator<pugi::xml_node>\n\t{\n\t\ttypedef pugi::xml_node::iterator type;\n\t};\n\n\ttemplate<> struct range_const_iterator<pugi::xml_node>\n\t{\n\t\ttypedef pugi::xml_node::iterator type;\n\t};\n\n\ttemplate<> struct range_mutable_iterator<pugi::xml_document>\n\t{\n\t\ttypedef pugi::xml_document::iterator type;\n\t};\n\n\ttemplate<> struct range_const_iterator<pugi::xml_document>\n\t{\n\t\ttypedef pugi::xml_document::iterator type;\n\t};\n}\n\n\/*\n * These types add support for BOOST_FOREACH macro to xml_node and xml_document classes (child\/attribute iteration).\n * Example usage:\n * BOOST_FOREACH(xml_node n, children(doc)) {}\n * BOOST_FOREACH(xml_node n, attributes(doc)) {}\n *\/\n\nnamespace pugi\n{\n\tinline xml_object_range<xml_node_iterator> children(const pugi::xml_node& node)\n\t{\n return node.children();\n\t}\n\n\tinline xml_object_range<xml_attribute_iterator> attributes(const pugi::xml_node& node)\n\t{\n return node.attributes();\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\nnamespace DO {\n\n \/\/! \\defgroup ColorTypes Color typedefs\n \/\/! @{\n\n \/\/ ======================================================================== \/\/\n \/\/! self-explanatory.\n typedef unsigned char gray8;\n \/\/! self-explanatory.\n typedef char gray8s;\n \/\/! self-explanatory.\n typedef unsigned short gray16;\n \/\/! self-explanatory.\n typedef short gray16s;\n \/\/! self-explanatory.\n typedef unsigned int gray32;\n \/\/! self-explanatory.\n typedef int gray32s;\n \/\/! self-explanatory.\n typedef float gray32f;\n \/\/! self-explanatory.\n typedef double gray64f;\n\n \/\/ ======================================================================== \/\/\n \/\/! Macro for generic color typedefs\n#define DEFINE_GENERIC_COLOR_TYPEDEFS(N) \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<unsigned char, N, 1> Color##N##ub; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<char, N, 1> Color##N##b; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<unsigned short, N, 1> Color##N##us;\\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<short, N, 1> Color##N##s; \\\n \/*! \\brief Color{NumChannels}{ChannelType}. *\/ \\\n typedef Matrix<unsigned int, N, 1> Color##N##ui; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<int, N, 1> Color##N##i; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<float, N, 1> Color##N##f; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<double, N, 1> Color##N##d;\n\n DEFINE_GENERIC_COLOR_TYPEDEFS(3)\n DEFINE_GENERIC_COLOR_TYPEDEFS(4)\n#undef DEFINE_GENERIC_COLOR_TYPEDEFS\n\n \/\/ ======================================================================== \/\/\n \/\/! Macro for color typedefs.\n#define DEFINE_COLOR_TYPES(colorspace) \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<unsigned char, colorspace> colorspace##8; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<unsigned short, colorspace> colorspace##16; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<unsigned int, colorspace> colorspace##32; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<char, colorspace> colorspace##8s; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<short, colorspace> colorspace##16s; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<int, colorspace> colorspace##32s; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<float, colorspace> colorspace##32f; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<double, colorspace> colorspace##64f;\n\n DEFINE_COLOR_TYPES(Rgb)\n DEFINE_COLOR_TYPES(Rgba)\n DEFINE_COLOR_TYPES(Cmyk)\n DEFINE_COLOR_TYPES(Yuv)\n#undef DEFINE_COLOR_TYPES\n \/\/! @} ColorTypes\n\n \/\/ ======================================================================== \/\/\n \/\/! \\defgroup PrimaryColors Primary Colors in RGB.\n \/\/! @{\n\n \/\/! White color function.\n template <typename T> inline Matrix<T, 3, 1> white()\n { \n return Matrix<T,3,1>(\n ChannelTraits<T>::max(),\n ChannelTraits<T>::max(),\n ChannelTraits<T>::max() ); \n }\n \/\/! Black color function.\n template <typename T> inline Matrix<T, 3, 1> black()\n { \n return Matrix<T,3,1>(\n ChannelTraits<T>::min(),\n ChannelTraits<T>::min(),\n ChannelTraits<T>::min() ); \n }\n \/\/! Red color function.\n template <typename T> inline Matrix<T, 3, 1> red()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::max(),\n ChannelTraits<T>::min(),\n ChannelTraits<T>::min() ); \n }\n \/\/! Green color function.\n template <typename T> inline Matrix<T, 3, 1> green()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::min(),\n ChannelTraits<T>::max(),\n ChannelTraits<T>::min() );\n }\n \/\/! Blue color function.\n template <typename T> inline Matrix<T, 3, 1> blue()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::min(),\n ChannelTraits<T>::min(),\n ChannelTraits<T>::max() ); \n }\n \/\/! Cyan color function.\n template <typename T> inline Matrix<T, 3, 1> cyan()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::min(),\n ChannelTraits<T>::max(),\n ChannelTraits<T>::max() ); \n }\n \/\/! Yellow color function.\n template <typename T> inline Matrix<T, 3, 1> yellow()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::max(),\n ChannelTraits<T>::max(),\n ChannelTraits<T>::min() ); \n }\n \/\/! Magenta color function.\n template <typename T> inline Matrix<T, 3, 1> magenta()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::max(),\n ChannelTraits<T>::min(),\n ChannelTraits<T>::max() ); \n }\n\n \/\/! Primary color definition.\n#define DEFINE_COLOR_CONSTANT(Name, function) \\\n \/*! \\brief Return primary color of type Rgb8. *\/ \\\n const Rgb8 Name##8(function<unsigned char>()); \\\n \/*! \\brief Return primary color of type Rgb8s. *\/ \\\n const Rgb8s Name##8s(function<char>()); \\\n \/*! \\brief Return primary color of type Rgb16. *\/ \\\n const Rgb16 Name##16(function<unsigned short>()); \\\n \/*! \\brief Return primary color of type Rgb16s. *\/\\\n const Rgb16s Name##16s(function<short>()); \\\n \/*! \\brief Return primary color of type Rgb32. *\/ \\\n const Rgb32 Name##32(function<unsigned int>()); \\\n \/*! \\brief Return primary color of type Rgb32s. *\/\\\n const Rgb32s Name##32s(function<int>()); \\\n \/*! \\brief Return primary color of type Rgb32f. *\/\\\n const Rgb32f Name##32f(function<float>()); \\\n \/*! \\brief Return primary color of type Rgb64f. *\/\\\n const Rgb64f Name##64f(function<double>());\n\n DEFINE_COLOR_CONSTANT(Red, red)\n DEFINE_COLOR_CONSTANT(Green, green)\n DEFINE_COLOR_CONSTANT(Blue, blue)\n DEFINE_COLOR_CONSTANT(Cyan, cyan)\n DEFINE_COLOR_CONSTANT(Magenta, magenta)\n DEFINE_COLOR_CONSTANT(Yellow, yellow)\n DEFINE_COLOR_CONSTANT(Black, black)\n DEFINE_COLOR_CONSTANT(White, white)\n#undef DEFINE_COLOR_CONSTANT\n \/\/! @}\n\n \/\/! @}\n\n\n} \/* namespace DO *\/<commit_msg>Remove unused typedefs.<commit_after>#pragma once\n\nnamespace DO {\n\n \/\/! \\defgroup ColorTypes Color typedefs\n \/\/! @{\n\n\n \/\/ ======================================================================== \/\/\n \/\/! Macro for generic color typedefs\n#define DEFINE_GENERIC_COLOR_TYPEDEFS(N) \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<unsigned char, N, 1> Color##N##ub; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<char, N, 1> Color##N##b; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<unsigned short, N, 1> Color##N##us;\\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<short, N, 1> Color##N##s; \\\n \/*! \\brief Color{NumChannels}{ChannelType}. *\/ \\\n typedef Matrix<unsigned int, N, 1> Color##N##ui; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<int, N, 1> Color##N##i; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<float, N, 1> Color##N##f; \\\n \/*! \\brief Color{NumChannels}{ChannelType} *\/ \\\n typedef Matrix<double, N, 1> Color##N##d;\n\n DEFINE_GENERIC_COLOR_TYPEDEFS(3)\n DEFINE_GENERIC_COLOR_TYPEDEFS(4)\n#undef DEFINE_GENERIC_COLOR_TYPEDEFS\n\n \/\/ ======================================================================== \/\/\n \/\/! Macro for color typedefs.\n#define DEFINE_COLOR_TYPES(colorspace) \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<unsigned char, colorspace> colorspace##8; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<unsigned short, colorspace> colorspace##16; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<unsigned int, colorspace> colorspace##32; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<char, colorspace> colorspace##8s; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<short, colorspace> colorspace##16s; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<int, colorspace> colorspace##32s; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<float, colorspace> colorspace##32f; \\\n \/*! \\brief {ColorSpace}{BitDepthPerChannel} *\/ \\\n typedef Color<double, colorspace> colorspace##64f;\n\n DEFINE_COLOR_TYPES(Rgb)\n DEFINE_COLOR_TYPES(Rgba)\n DEFINE_COLOR_TYPES(Cmyk)\n DEFINE_COLOR_TYPES(Yuv)\n#undef DEFINE_COLOR_TYPES\n \/\/! @} ColorTypes\n\n \/\/ ======================================================================== \/\/\n \/\/! \\defgroup PrimaryColors Primary Colors in RGB.\n \/\/! @{\n\n \/\/! White color function.\n template <typename T> inline Matrix<T, 3, 1> white()\n { \n return Matrix<T,3,1>(\n ChannelTraits<T>::max(),\n ChannelTraits<T>::max(),\n ChannelTraits<T>::max() ); \n }\n \/\/! Black color function.\n template <typename T> inline Matrix<T, 3, 1> black()\n { \n return Matrix<T,3,1>(\n ChannelTraits<T>::min(),\n ChannelTraits<T>::min(),\n ChannelTraits<T>::min() ); \n }\n \/\/! Red color function.\n template <typename T> inline Matrix<T, 3, 1> red()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::max(),\n ChannelTraits<T>::min(),\n ChannelTraits<T>::min() ); \n }\n \/\/! Green color function.\n template <typename T> inline Matrix<T, 3, 1> green()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::min(),\n ChannelTraits<T>::max(),\n ChannelTraits<T>::min() );\n }\n \/\/! Blue color function.\n template <typename T> inline Matrix<T, 3, 1> blue()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::min(),\n ChannelTraits<T>::min(),\n ChannelTraits<T>::max() ); \n }\n \/\/! Cyan color function.\n template <typename T> inline Matrix<T, 3, 1> cyan()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::min(),\n ChannelTraits<T>::max(),\n ChannelTraits<T>::max() ); \n }\n \/\/! Yellow color function.\n template <typename T> inline Matrix<T, 3, 1> yellow()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::max(),\n ChannelTraits<T>::max(),\n ChannelTraits<T>::min() ); \n }\n \/\/! Magenta color function.\n template <typename T> inline Matrix<T, 3, 1> magenta()\n {\n return Matrix<T,3,1>(\n ChannelTraits<T>::max(),\n ChannelTraits<T>::min(),\n ChannelTraits<T>::max() ); \n }\n\n \/\/! Primary color definition.\n#define DEFINE_COLOR_CONSTANT(Name, function) \\\n \/*! \\brief Return primary color of type Rgb8. *\/ \\\n const Rgb8 Name##8(function<unsigned char>()); \\\n \/*! \\brief Return primary color of type Rgb8s. *\/ \\\n const Rgb8s Name##8s(function<char>()); \\\n \/*! \\brief Return primary color of type Rgb16. *\/ \\\n const Rgb16 Name##16(function<unsigned short>()); \\\n \/*! \\brief Return primary color of type Rgb16s. *\/\\\n const Rgb16s Name##16s(function<short>()); \\\n \/*! \\brief Return primary color of type Rgb32. *\/ \\\n const Rgb32 Name##32(function<unsigned int>()); \\\n \/*! \\brief Return primary color of type Rgb32s. *\/\\\n const Rgb32s Name##32s(function<int>()); \\\n \/*! \\brief Return primary color of type Rgb32f. *\/\\\n const Rgb32f Name##32f(function<float>()); \\\n \/*! \\brief Return primary color of type Rgb64f. *\/\\\n const Rgb64f Name##64f(function<double>());\n\n DEFINE_COLOR_CONSTANT(Red, red)\n DEFINE_COLOR_CONSTANT(Green, green)\n DEFINE_COLOR_CONSTANT(Blue, blue)\n DEFINE_COLOR_CONSTANT(Cyan, cyan)\n DEFINE_COLOR_CONSTANT(Magenta, magenta)\n DEFINE_COLOR_CONSTANT(Yellow, yellow)\n DEFINE_COLOR_CONSTANT(Black, black)\n DEFINE_COLOR_CONSTANT(White, white)\n#undef DEFINE_COLOR_CONSTANT\n \/\/! @}\n\n \/\/! @}\n\n\n} \/* namespace DO *\/<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n\nnamespace {\n\ttemplate <typename T>\n\tvoid swapEndian (T* p) {\n\t\tuint8_t* q = reinterpret_cast<uint8_t*>(p);\n\n\t\tstd::reverse(q, q + sizeof(T));\n\t}\n}\n\nstruct Slice {\n\tuint8_t* begin;\n\tuint8_t* end;\n\n\tSlice() : begin(nullptr), end(nullptr) {}\n\tSlice(uint8_t* begin, uint8_t* end) : begin(begin), end(end) {\n\t\tassert(begin);\n\t\tassert(end);\n\t}\n\n\tvoid popFrontN (size_t n) {\n\t\tassert(this->length() >= n);\n\t\tbegin += n;\n\t}\n\n\tvoid popFront () {\n\t\tthis->popFrontN(1);\n\t}\n\n\tauto drop (size_t n) const {\n\t\tassert(this->length() >= n);\n\t\treturn Slice(this->begin + n, this->end);\n\t}\n\n\tauto take (size_t n) const {\n\t\tassert(this->length() >= n);\n\t\treturn Slice(this->begin, this->begin + n);\n\t}\n\n\tsize_t length () const {\n\t\treturn static_cast<size_t>(this->end - this->begin);\n\t}\n\n\ttemplate <typename Y = uint8_t>\n\tY peek (size_t offset = 0) const {\n\t\treturn *(reinterpret_cast<Y*>(this->begin + offset));\n\t}\n\n\ttemplate <typename Y, bool swap = false>\n\tvoid put (Y value, size_t offset = 0) {\n\t\tassert(this->length() >= offset + sizeof(Y));\n\t\tauto ptr = reinterpret_cast<Y*>(this->begin + offset);\n\t\t*ptr = value;\n\n\t\tif (swap) swapEndian(ptr);\n\t}\n\n\tvoid put (uint8_t* value, size_t n, size_t offset = 0) {\n\t\tassert(this->length() >= offset + n);\n\t\tmemcpy(this->begin + offset, value, n);\n\t}\n\n\tvoid put (Slice value, size_t offset = 0) {\n\t\tthis->put(value.begin, value.length(), offset);\n\t}\n\n\ttemplate <typename Y = uint8_t>\n\tY read () {\n\t\tconst Y value = this->peek<Y>();\n\t\tthis->popFrontN(sizeof(Y));\n\t\treturn value;\n\t}\n\n\ttemplate <typename Y, bool swap = false>\n\tvoid write (Y value) {\n\t\tthis->put<Y, swap>(value);\n\t\tthis->popFrontN(sizeof(Y));\n\t}\n\n\tvoid write (Slice value) {\n\t\tthis->put(value);\n\t\tthis->popFrontN(value.length());\n\t}\n\n\tvoid write (uint8_t* value, size_t n) {\n\t\tthis->put(value, n);\n\t\tthis->popFrontN(n);\n\t}\n\n\tuint8_t& operator[](const size_t i) {\n\t\tassert(this->length() >= i);\n\t\treturn this->begin[i];\n\t}\n\n\tconst uint8_t& operator[](const size_t i) const {\n\t\tassert(this->length() >= i);\n\t\treturn this->begin[i];\n\t}\n};\n<commit_msg>slice: use < over >=<commit_after>#pragma once\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n\nnamespace {\n\ttemplate <typename T>\n\tvoid swapEndian (T* p) {\n\t\tuint8_t* q = reinterpret_cast<uint8_t*>(p);\n\n\t\tstd::reverse(q, q + sizeof(T));\n\t}\n}\n\nstruct Slice {\n\tuint8_t* begin;\n\tuint8_t* end;\n\n\tSlice(uint8_t* begin, uint8_t* end) : begin(begin), end(end) {\n\t\tassert(begin);\n\t\tassert(end);\n\t}\n\n\tvoid popFrontN (size_t n) {\n\t\tassert(n < this->length());\n\t\tbegin += n;\n\t}\n\n\tvoid popFront () {\n\t\tthis->popFrontN(1);\n\t}\n\n\tauto drop (size_t n) const {\n\t\tassert(n < this->length());\n\t\treturn Slice(this->begin + n, this->end);\n\t}\n\n\tauto take (size_t n) const {\n\t\tassert(n < this->length());\n\t\treturn Slice(this->begin, this->begin + n);\n\t}\n\n\tsize_t length () const {\n\t\treturn static_cast<size_t>(this->end - this->begin);\n\t}\n\n\ttemplate <typename Y = uint8_t>\n\tY peek (size_t offset = 0) const {\n\t\treturn *(reinterpret_cast<Y*>(this->begin + offset));\n\t}\n\n\ttemplate <typename Y, bool swap = false>\n\tvoid put (Y value, size_t offset = 0) {\n\t\tassert(offset + sizeof(Y) < this->length());\n\t\tauto ptr = reinterpret_cast<Y*>(this->begin + offset);\n\t\t*ptr = value;\n\n\t\tif (swap) swapEndian(ptr);\n\t}\n\n\tvoid put (uint8_t* value, size_t n, size_t offset = 0) {\n\t\tassert(offset + n < this->length());\n\t\tmemcpy(this->begin + offset, value, n);\n\t}\n\n\tvoid put (Slice value, size_t offset = 0) {\n\t\tthis->put(value.begin, value.length(), offset);\n\t}\n\n\ttemplate <typename Y = uint8_t>\n\tY read () {\n\t\tconst Y value = this->peek<Y>();\n\t\tthis->popFrontN(sizeof(Y));\n\t\treturn value;\n\t}\n\n\ttemplate <typename Y, bool swap = false>\n\tvoid write (Y value) {\n\t\tthis->put<Y, swap>(value);\n\t\tthis->popFrontN(sizeof(Y));\n\t}\n\n\tvoid write (Slice value) {\n\t\tthis->put(value);\n\t\tthis->popFrontN(value.length());\n\t}\n\n\tvoid write (uint8_t* value, size_t n) {\n\t\tthis->put(value, n);\n\t\tthis->popFrontN(n);\n\t}\n\n\tuint8_t& operator[](const size_t i) {\n\t\tassert(i < this->length());\n\t\treturn this->begin[i];\n\t}\n\n\tconst uint8_t& operator[](const size_t i) const {\n\t\tassert(i < this->length());\n\t\treturn this->begin[i];\n\t}\n};\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n\ntemplate <typename T>\nclass stack\n{\npublic:\n\tstack();\n\tsize_t count() const;\n\tsize_t array_size() const;\n\tT * operator[](unsigned int index) const;\n\tvoid push(T const &);\n\tvoid pop();\n\tT top();\n\tT last()const;\n\tvoid print();\n\tvoid swap();\n\tbool empty();\nprivate:\n\tT * array_;\n\tsize_t array_size_;\n\tsize_t count_;\n};\n\ntemplate <typename T>\nstack<T>::stack()\n{\n\tarray_ = nullptr;\n\tarray_size_ = 0;\n\tcount_ = 0;\n}\ntemplate <typename T>\nsize_t stack<T>::array_size() const\n{\n\treturn array_size_;\n}\ntemplate <typename T>\nsize_t stack<T>::count() const\n{\n\treturn count_;\n}\ntemplate <typename T>\nT * stack<T>::operator[](unsigned int index) const\n{\n\treturn array_[index];\n}\ntemplate <typename T>\nvoid stack<T>::push(T const & value)\n{\n\tif (array_size_ == 0)\n\t{\n\t\tarray_size_ = 1;\n\t\tarray_ = new T[array_size_]();\n\t}\n\telse if (array_size_ == count_)\n\t{\n\t\tarray_size_ *= 2;\n\t\tswap();\n\t}\n\tarray_[count_++] = value;\n}\ntemplate <typename T>\nvoid stack<T>::pop()\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse\n\t{\n\t\tif (count_ - 1 == array_size_ \/ 2)\n\t\t\tarray_size_ \/= 2;\n\t\tswap();\n\t}\n}\nT stack<T>::top()\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse return array_[count - 1];\n}\ntemplate <typename T>\nT stack<T>::last()const\n{\n\tif (count_ == 0)\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse return array_[count_ - 1];\n}\ntemplate <typename T>\nvoid stack<T>::print()\n{\n\tfor (unsigned int i = 0; i < count_; ++i)\n\t\tstd::cout << array_[i] << \" \";\n\tstd::cout << std::endl;\n}\ntemplate <typename T>\nvoid stack<T>::swap()\n{\n\tT * new_array = new T[array_size_]();\n\tstd::copy(array_, array_ + count_, new_array);\n\tdelete[] array_;\n\tarray_ = new_array;\n}\ntemplate <typename T>\nbool stack<T>::empty()\n{\n\treturn (count_ == 0) ? true : false;\n}\n<commit_msg>Update stack.hpp<commit_after>#include <iostream>\n#include <algorithm>\n#include <stdexcept>\n\ntemplate <typename T>\nclass stack\n{\npublic:\n\tstack();\n\tsize_t count() const;\n\tsize_t array_size() const;\n\tT * operator[](unsigned int index) const;\n\tvoid push(T const &);\n\tvoid pop();\n\tT top();\n\tT last()const;\n\tvoid print();\n\tvoid swap();\n\tbool empty();\nprivate:\n\tT * array_;\n\tsize_t array_size_;\n\tsize_t count_;\n};\n\ntemplate <typename T>\nstack<T>::stack()\n{\n\tarray_ = nullptr;\n\tarray_size_ = 0;\n\tcount_ = 0;\n}\ntemplate <typename T>\nsize_t stack<T>::array_size() const\n{\n\treturn array_size_;\n}\ntemplate <typename T>\nsize_t stack<T>::count() const\n{\n\treturn count_;\n}\ntemplate <typename T>\nT * stack<T>::operator[](unsigned int index) const\n{\n\treturn array_[index];\n}\ntemplate <typename T>\nvoid stack<T>::push(T const & value)\n{\n\tif (array_size_ == 0)\n\t{\n\t\tarray_size_ = 1;\n\t\tarray_ = new T[array_size_]();\n\t}\n\telse if (array_size_ == count_)\n\t{\n\t\tarray_size_ *= 2;\n\t\tswap();\n\t}\n\tarray_[count_++] = value;\n}\ntemplate <typename T>\nvoid stack<T>::pop()\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse\n\t{\n\t\tif (count_ - 1 == array_size_ \/ 2)\n\t\t\tarray_size_ \/= 2;\n\t\tswap();\n\t}\n}\nT stack<T>::top()\n{\n\tif (empty())\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse return array_[count - 1];\n}\ntemplate <typename T>\nT stack<T>::last()const\n{\n\tif (count_ == 0)\n\t\tthrow std::logic_error(\"Stack is empty\");\n\telse return array_[count_ - 1];\n}\ntemplate <typename T>\nvoid stack<T>::print()\n{\n\tfor (unsigned int i = 0; i < count_; ++i)\n\t\tstd::cout << array_[i] << \" \";\n\tstd::cout << std::endl;\n}\ntemplate <typename T>\nvoid stack<T>::swap()\n{\n\tT * new_array = new T[array_size_]();\n\tstd::copy(array_, array_ + count_, new_array);\n\tdelete[] array_;\n\tarray_ = new_array;\n}\ntemplate <typename T>\nbool stack<T>::empty()\n{\n\treturn (count_ == 0) ? true : false;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef stack_cpp\r\n#define stack_cpp\r\n#pragma once\r\n#include <iostream>\r\n#include <memory>\r\n\r\nclass bitset\r\n{\r\npublic:\r\n\texplicit\r\n\t\tbitset(size_t size) \/*strong*\/;\r\n\r\n\tbitset(bitset const & other) = delete;\r\n\tauto operator =(bitset const & other)->bitset & = delete;\r\n\r\n\tbitset(bitset && other) = delete;\r\n\tauto operator =(bitset && other)->bitset & = delete;\r\n\r\n\tauto set(size_t index) \/*strong*\/ -> void;\r\n\tauto reset(size_t index) \/*strong*\/ -> void;\r\n\tauto test(size_t index) \/*strong*\/ -> bool;\r\n\r\n\tauto size() \/*noexcept*\/ -> size_t;\r\n\tauto counter() \/*noexcept*\/ -> size_t;\r\n\r\nprivate:\r\n\tstd::unique_ptr<bool[]> ptr_;\r\n\tsize_t size_;\r\n\tsize_t counter_;\r\n};\r\n\r\nbitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {}\r\n\r\nauto bitset::set(size_t index) -> void\r\n{ if (index >= 0 && index < size_) {\r\n\tptr_[index] = true; \r\n\t++counter_; }\r\n\telse throw; \r\n}\r\n\r\nauto bitset::reset(size_t index) -> void\r\n{\tif (index >= 0 && index < size_)\r\n\t{\r\n\t\tptr_[index] = false;\r\n\t\t--counter_;\r\n\t}\r\nelse throw;\r\n}\r\n\r\nauto bitset::test(size_t index) -> bool\r\n{\r\n\tif (index >= 0 && index < size_)\r\n\t{\r\n\t\treturn !ptr_[index];\r\n\t}\r\n\telse throw;\r\n\t\r\n}\r\nauto bitset::size() -> size_t\r\n{\r\n\treturn size_;\r\n}\r\n\r\nauto bitset::counter() -> size_t\r\n{\r\n\treturn counter_;\r\n}\r\n\t\r\n\r\ntemplate <typename T>\r\nclass allocator\r\n{\r\npublic:\r\n\texplicit\r\n\t\tallocator(std::size_t size = 0) \/*strong*\/;\r\n\tallocator(allocator const & other) \/*strong*\/;\r\n\tauto operator =(allocator const & other)->allocator & = delete;\r\n\t~allocator();\r\n\r\n\tauto resize() \/*strong*\/ -> void;\r\n\r\n\tauto construct(T * ptr, T const & value) \/*strong*\/ -> void;\r\n\tauto destroy(T * ptr) \/*noexcept*\/ -> void;\r\n\r\n\tauto get() \/*noexcept*\/ -> T *;\r\n\tauto get() const \/*noexcept*\/ -> T const *;\r\n\r\n\tauto count() const \/*noexcept*\/ -> size_t;\r\n\tauto full() const \/*noexcept*\/ -> bool;\r\n\tauto empty() const \/*noexcept*\/ -> bool;\r\nprivate:\r\n\tauto destroy(T * first, T * last) \/*noexcept*\/ -> void;\r\n\tauto swap(allocator & other) \/*noexcept*\/ -> void;\r\n\r\n\r\n\tT * ptr_;\r\n\tsize_t size_;\r\n\tstd::unique_ptr<bitset> map_;\r\n};\r\n\r\ntemplate <typename T>\r\nclass stack\r\n{\r\npublic:\r\n\texplicit\r\n\t\tstack(size_t size = 0);\r\n\tauto operator =(stack const & other) \/*strong*\/ -> stack &;\r\n\r\n\tauto empty() const \/*noexcept*\/ -> bool;\r\n\tauto count() const \/*noexcept*\/ -> size_t;\r\n\r\n\tauto push(T const & value) \/*strong*\/ -> void;\r\n\tauto pop() \/*strong*\/ -> void;\r\n\tauto top() \/*strong*\/ -> T &;\r\n\tauto top() const \/*strong*\/ -> T const &;\r\n\r\nprivate:\r\n\tallocator<T> allocator_;\r\n\r\n\tauto throw_is_empty() const -> void;\r\n};\r\n\r\ntemplate <typename T>\r\nallocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {};\r\n\r\ntemplate<typename T>\r\n\tallocator<T>::allocator(allocator const& other) : \r\nptr_(static_cast<T*>(operator new(other.size_))),\r\nsize_(other.size_), map_(std::make_unique<bitset>(size_)){\r\n\tfor (size_t i; i < size_; i++)\r\n\t\tconstruct(ptr_ + i, other.ptr_[i]);\r\n}\r\ntemplate<typename T>\r\nallocator<T>::~allocator() { operator delete(ptr_); }\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::resize() -> void\r\n{\r\n\tallocator<T> buff(size_ * 2 + (size_ == 0));\r\n\tfor (size_t i = 0; i < size_; i++) construct(buff.ptr_ + i, ptr_[i]);\r\n\tthis->swap(buff);\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::construct(T * ptr, T const & value)->void {\r\n\tif (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) {\r\n\t\tnew(ptr)T(value);\r\n\t\tmap_->set(ptr - ptr_);\r\n\t}\r\n\telse throw(\"error\");\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::destroy(T * ptr) -> void {\r\n\tptr->~T();\r\n\tmap_->reset(ptr-ptr_);\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::destroy(T * first, T * last) -> void\r\n{\r\n\tfor (; first != last; ++first) {\r\n\t\tdestroy(&*first);\r\n\t}\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::get()-> T* {\r\n\treturn ptr_; \r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::get() const -> T const * { \r\n\treturn ptr_; \r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::count() const -> size_t\r\n{\r\n\treturn map_->counter();\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::full() const -> bool\r\n{\r\n\treturn map_->counter()==size_;\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::empty() const -> bool\r\n{\r\n\treturn map_->counter()==0;\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::swap(allocator & other) -> void {\r\n\tstd::swap(ptr_, other.ptr_);\r\n\tstd::swap(map_, other.map_);\r\n\tstd::swap(size_, other.size_);\r\n}\r\n\r\ntemplate <typename T>\r\nsize_t stack<T>::count() const\r\n{\r\n\treturn allocator_.count_;\r\n}\r\ntemplate <typename T>\r\nstack<T>::stack(size_t size) :allocator<T>(size) {}\r\n\r\ntemplate <typename T>\r\nvoid stack<T>::push(T const &item) {\r\n\tif (allocator_.full()) allocator_.resize(); \r\n\tallocator_.construct(allocator_.get() + this->count(), value);\r\ntemplate<typename T>\r\n\r\nvoid stack<T>::pop()\r\n{\r\n\tif (this->count() > 0) \r\n\t\tallocator_.destroy(allocator_.get() + this->count());\r\n\telse throw_is_empty();\r\n}\r\ntemplate<typename T>\r\nauto stack<T>::top() -> T &\r\n{\r\n\tif (allocator<T>::count_ == 0) {\r\n\t\tthrow_is_empty();\r\n\t}\r\n\treturn allocator<T>::ptr_[allocator<T>::count_ - 1];\r\n}\r\n\r\ntemplate<typename T>\r\nauto stack<T>::top() const -> T const &\r\n{\r\n\tif (allocator<T>::count_ == 0) {\r\n\t\tthrow_is_empty();\r\n\t}\r\n\treturn allocator<T>::ptr_[allocator<T>::count_ - 1];\r\n}\r\n\r\ntemplate<typename T>\r\nauto stack<T>::throw_is_empty() const -> void\r\n{\r\n\t\tthrow(\"Stack is empty!\");\r\n}\r\n\r\ntemplate<typename T>\r\nauto stack<T>::operator=(stack const & right) -> stack & {\r\n\tif (this != &right) {\r\n\t\tstack<T> temp(right.size_);\r\n\t\twhile (temp.count_ < right.count_) {\r\n\t\t\tconstruct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]);\r\n\t\t\t++temp.count_;\r\n\t\t}\r\n\t\tthis->swap(temp);\r\n\t}\r\n\treturn *this;\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nauto stack<T>::empty() const -> bool {\r\n\treturn allocator_.empty;\r\n\r\n#endif\r\n<commit_msg>Update stack.hpp<commit_after>#ifndef stack_cpp\r\n#define stack_cpp\r\n#pragma once\r\n#include <iostream>\r\n#include <memory>\r\n\r\nclass bitset\r\n{\r\npublic:\r\n\texplicit\r\n\t\tbitset(size_t size) \/*strong*\/;\r\n\r\n\tbitset(bitset const & other) = delete;\r\n\tauto operator =(bitset const & other)->bitset & = delete;\r\n\r\n\tbitset(bitset && other) = delete;\r\n\tauto operator =(bitset && other)->bitset & = delete;\r\n\r\n\tauto set(size_t index) \/*strong*\/ -> void;\r\n\tauto reset(size_t index) \/*strong*\/ -> void;\r\n\tauto test(size_t index) \/*strong*\/ -> bool;\r\n\r\n\tauto size() \/*noexcept*\/ -> size_t;\r\n\tauto counter() \/*noexcept*\/ -> size_t;\r\n\r\nprivate:\r\n\tstd::unique_ptr<bool[]> ptr_;\r\n\tsize_t size_;\r\n\tsize_t counter_;\r\n};\r\n\r\nbitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {}\r\n\r\nauto bitset::set(size_t index) -> void\r\n{ if (index >= 0 && index < size_) {\r\n\tptr_[index] = true; \r\n\t++counter_; }\r\n\telse throw; \r\n}\r\n\r\nauto bitset::reset(size_t index) -> void\r\n{\tif (index >= 0 && index < size_)\r\n\t{\r\n\t\tptr_[index] = false;\r\n\t\t--counter_;\r\n\t}\r\nelse throw;\r\n}\r\n\r\nauto bitset::test(size_t index) -> bool\r\n{\r\n\tif (index >= 0 && index < size_)\r\n\t{\r\n\t\treturn !ptr_[index];\r\n\t}\r\n\telse throw;\r\n\t\r\n}\r\nauto bitset::size() -> size_t\r\n{\r\n\treturn size_;\r\n}\r\n\r\nauto bitset::counter() -> size_t\r\n{\r\n\treturn counter_;\r\n}\r\n\t\r\n\r\ntemplate <typename T>\r\nclass allocator\r\n{\r\npublic:\r\n\texplicit\r\n\t\tallocator(std::size_t size = 0) \/*strong*\/;\r\n\tallocator(allocator const & other) \/*strong*\/;\r\n\tauto operator =(allocator const & other)->allocator & = delete;\r\n\t~allocator();\r\n\r\n\tauto resize() \/*strong*\/ -> void;\r\n\r\n\tauto construct(T * ptr, T const & value) \/*strong*\/ -> void;\r\n\tauto destroy(T * ptr) \/*noexcept*\/ -> void;\r\n\r\n\tauto get() \/*noexcept*\/ -> T *;\r\n\tauto get() const \/*noexcept*\/ -> T const *;\r\n\r\n\tauto count() const \/*noexcept*\/ -> size_t;\r\n\tauto full() const \/*noexcept*\/ -> bool;\r\n\tauto empty() const \/*noexcept*\/ -> bool;\r\nprivate:\r\n\tauto destroy(T * first, T * last) \/*noexcept*\/ -> void;\r\n\tauto swap(allocator & other) \/*noexcept*\/ -> void;\r\n\r\n\r\n\tT * ptr_;\r\n\tsize_t size_;\r\n\tstd::unique_ptr<bitset> map_;\r\n};\r\n\r\ntemplate <typename T>\r\nclass stack\r\n{\r\npublic:\r\n\texplicit\r\n\t\tstack(size_t size = 0);\r\n\tauto operator =(stack const & other) \/*strong*\/ -> stack &;\r\n\r\n\tauto empty() const \/*noexcept*\/ -> bool;\r\n\tauto count() const \/*noexcept*\/ -> size_t;\r\n\r\n\tauto push(T const & value) \/*strong*\/ -> void;\r\n\tauto pop() \/*strong*\/ -> void;\r\n\tauto top() \/*strong*\/ -> T &;\r\n\tauto top() const \/*strong*\/ -> T const &;\r\n\r\nprivate:\r\n\tallocator<T> allocator_;\r\n\r\n\tauto throw_is_empty() const -> void;\r\n};\r\n\r\ntemplate <typename T>\r\nallocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {};\r\n\r\ntemplate<typename T>\r\n\tallocator<T>::allocator(allocator const& other) : \r\nptr_(static_cast<T*>(operator new(other.size_))),\r\nsize_(other.size_), map_(std::make_unique<bitset>(size_)){\r\n\tfor (size_t i; i < size_; i++)\r\n\t\tconstruct(ptr_ + i, other.ptr_[i]);\r\n}\r\ntemplate<typename T>\r\nallocator<T>::~allocator() { operator delete(ptr_); }\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::resize() -> void\r\n{\r\n\tallocator<T> buff(size_ * 2 + (size_ == 0));\r\n\tfor (size_t i = 0; i < size_; i++) construct(buff.ptr_ + i, ptr_[i]);\r\n\tthis->swap(buff);\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::construct(T * ptr, T const & value)->void {\r\n\tif (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) {\r\n\t\tnew(ptr)T(value);\r\n\t\tmap_->set(ptr - ptr_);\r\n\t}\r\n\telse throw(\"error\");\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::destroy(T * ptr) -> void {\r\n\tptr->~T();\r\n\tmap_->reset(ptr-ptr_);\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::destroy(T * first, T * last) -> void\r\n{\r\n\tfor (; first != last; ++first) {\r\n\t\tdestroy(&*first);\r\n\t}\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::get()-> T* {\r\n\treturn ptr_; \r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::get() const -> T const * { \r\n\treturn ptr_; \r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::count() const -> size_t\r\n{\r\n\treturn map_->counter();\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::full() const -> bool\r\n{\r\n\treturn map_->counter()==size_;\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::empty() const -> bool\r\n{\r\n\treturn map_->counter()==0;\r\n}\r\n\r\ntemplate<typename T>\r\nauto allocator<T>::swap(allocator & other) -> void {\r\n\tstd::swap(ptr_, other.ptr_);\r\n\tstd::swap(map_, other.map_);\r\n\tstd::swap(size_, other.size_);\r\n}\r\n\r\ntemplate <typename T>\r\nsize_t stack<T>::count() const\r\n{\r\n\treturn allocator_.count_;\r\n}\r\ntemplate <typename T>\r\nstack<T>::stack(size_t size) :allocator<T>(size) {}\r\n\r\ntemplate <typename T>\r\nvoid stack<T>::push(T const &item) {\r\n\tif (allocator_.full()) allocator_.resize(); \r\n\tallocator_.construct(allocator_.get() + this->count(), item;\r\n}\r\ntemplate<typename T>\r\nvoid stack<T>::pop()\r\n{\r\n\tif (this->count() > 0) \r\n\t\tallocator_.destroy(allocator_.get() + this->count());\r\n\telse throw_is_empty();\r\n}\r\ntemplate<typename T>\r\nauto stack<T>::top() -> T &\r\n{\r\n\tif (allocator<T>::count_ == 0) {\r\n\t\tthrow_is_empty();\r\n\t}\r\n\treturn allocator<T>::ptr_[allocator<T>::count_ - 1];\r\n}\r\n\r\ntemplate<typename T>\r\nauto stack<T>::top() const -> T const &\r\n{\r\n\tif (allocator<T>::count_ == 0) {\r\n\t\tthrow_is_empty();\r\n\t}\r\n\treturn allocator<T>::ptr_[allocator<T>::count_ - 1];\r\n}\r\n\r\ntemplate<typename T>\r\nauto stack<T>::throw_is_empty() const -> void\r\n{\r\n\t\tthrow(\"Stack is empty!\");\r\n}\r\n\r\ntemplate<typename T>\r\nauto stack<T>::operator=(stack const & right) -> stack & {\r\n\tif (this != &right) {\r\n\t\tstack<T> temp(right.size_);\r\n\t\twhile (temp.count_ < right.count_) {\r\n\t\t\tconstruct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]);\r\n\t\t\t++temp.count_;\r\n\t\t}\r\n\t\tthis->swap(temp);\r\n\t}\r\n\treturn *this;\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nauto stack<T>::empty() const -> bool {\r\n\treturn allocator_.empty;\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Removed unused include<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014 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#ifndef UTILS_HPP\n#define UTILS_HPP\n\ntemplate<typename Container>\nvoid scale_each(Container& values){\n for(auto& vec : values){\n for(auto& v : vec){\n v \/= 255.0;\n }\n }\n}\n\ntemplate<typename Container>\nvoid binarize_each(Container& values, double threshold = 30.0){\n for(auto& vec : values){\n for(auto& v : vec){\n v = v > threshold ? 1.0 : 0.0;\n }\n }\n}\n\ntemplate<typename Container>\ndouble mean(const Container& container){\n double mean = 0.0;\n for(auto& value : container){\n mean += value;\n }\n return mean \/ container.size();\n}\n\ntemplate<typename Container>\ndouble stddev(const Container& container, double mean){\n double std = 0.0;\n for(auto& value : container){\n std += (value - mean) * (value - mean);\n }\n return std::sqrt(std \/ container.size());\n}\n\ntemplate<typename Container>\nvoid normalize(Container& values){\n for(auto& vec : values){\n \/\/zero-mean\n auto m = mean(vec);\n for(auto& v : vec){\n v -= m;\n }\n \/\/unit variance\n auto s = stddev(vec, 0.0);\n for(auto& v : vec){\n v \/= s;\n }\n }\n}\n\n#endif\n<commit_msg>Fix missing include<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014 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#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <cmath>\n\ntemplate<typename Container>\nvoid scale_each(Container& values){\n for(auto& vec : values){\n for(auto& v : vec){\n v \/= 255.0;\n }\n }\n}\n\ntemplate<typename Container>\nvoid binarize_each(Container& values, double threshold = 30.0){\n for(auto& vec : values){\n for(auto& v : vec){\n v = v > threshold ? 1.0 : 0.0;\n }\n }\n}\n\ntemplate<typename Container>\ndouble mean(const Container& container){\n double mean = 0.0;\n for(auto& value : container){\n mean += value;\n }\n return mean \/ container.size();\n}\n\ntemplate<typename Container>\ndouble stddev(const Container& container, double mean){\n double std = 0.0;\n for(auto& value : container){\n std += (value - mean) * (value - mean);\n }\n return std::sqrt(std \/ container.size());\n}\n\ntemplate<typename Container>\nvoid normalize(Container& values){\n for(auto& vec : values){\n \/\/zero-mean\n auto m = mean(vec);\n for(auto& v : vec){\n v -= m;\n }\n \/\/unit variance\n auto s = stddev(vec, 0.0);\n for(auto& v : vec){\n v \/= s;\n }\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014-2015, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\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 with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferTest\/ContextTest.h\"\n\n#include \"GafferTest\/Assert.h\"\n\n#include \"Gaffer\/Context.h\"\n\n#include \"IECore\/Timer.h\"\n#include \"IECore\/VectorTypedData.h\"\n#include \"IECore\/PathMatcherData.h\"\n\n#include \"boost\/lexical_cast.hpp\"\n#include \"tbb\/parallel_for.h\"\n#include <unordered_set>\n\nusing namespace std;\nusing namespace boost;\nusing namespace IECore;\nusing namespace Gaffer;\n\n\/\/ A test useful for assessing the performance\n\/\/ of the Context class.\nvoid GafferTest::testManyContexts()\n{\n\t\/\/ our typical context doesn't have a huge number of keys - we'll\n\t\/\/ use a working set of 20 for this test.\n\n\tContextPtr base = new Context();\n\tconst int numKeys = 20;\n\tvector<InternedString> keys;\n\tfor( int i = 0; i < numKeys; ++i )\n\t{\n\t\tInternedString key = string( \"testKey\" ) + lexical_cast<string>( i );\n\t\tkeys.push_back( key );\n\t\tbase->set( key, -1 - i );\n\t}\n\tconst MurmurHash baseHash = base->hash();\n\n\t\/\/ then typically we create new temporary contexts based on that one,\n\t\/\/ change a value or two, and then continue.\n\n\tTimer t;\n\tfor( int i = 0; i < 1000000; ++i )\n\t{\n\t\t\/\/ In order to efficiently manipulate a context, we need to create an EditableScope.\n\t\t\/\/ ( On the other hand, using a Context directly copies new memory for the value to\n\t\t\/\/ create a fully independent context, which is pretty slow ).\n\t\tContext::EditableScope tmp( base.get() );\n\t\ttmp.set( keys[i%numKeys], &i );\n\t\tGAFFERTEST_ASSERT( tmp.context()->get<int>( keys[i%numKeys] ) == i );\n\t\tGAFFERTEST_ASSERT( tmp.context()->hash() != baseHash );\n\t}\n}\n\n\/\/ Useful for assessing the performance of substitutions.\nvoid GafferTest::testManySubstitutions()\n{\n\tContextPtr context = new Context();\n\tcontext->set( \"foodType\", std::string( \"kipper\" ) );\n\tcontext->set( \"cookingMethod\", std::string( \"smoke\" ) );\n\n\tconst std::string phrase( \"${cookingMethod} me a ${foodType}\" );\n\tconst std::string expectedResult( \"smoke me a kipper\" );\n\n\tTimer t;\n\tfor( int i = 0; i < 1000000; ++i )\n\t{\n\t\tconst std::string s = context->substitute( phrase );\n\t\tGAFFERTEST_ASSERT( s == expectedResult );\n\t}\n}\n\n\/\/ Useful for assessing the performance of environment variable substitutions.\nvoid GafferTest::testManyEnvironmentSubstitutions()\n{\n\tContextPtr context = new Context();\n\n\tconst std::string phrase( \"${GAFFER_ROOT}\" );\n\tconst std::string expectedResult( getenv( \"GAFFER_ROOT\") );\n\n\tTimer t;\n\tfor( int i = 0; i < 1000000; ++i )\n\t{\n\t\tconst std::string s = context->substitute( phrase );\n\t\tGAFFERTEST_ASSERT( s == expectedResult );\n\t}\n}\n\n\/\/ Tests that scoping a null context is a no-op\nvoid GafferTest::testScopingNullContext()\n{\n\tContextPtr context = new Context();\n\tcontext->set( \"foodType\", std::string( \"kipper\" ) );\n\tcontext->set( \"cookingMethod\", std::string( \"smoke\" ) );\n\n\tconst std::string phrase( \"${cookingMethod} me a ${foodType}\" );\n\tconst std::string expectedResult( \"smoke me a kipper\" );\n\n\t{\n\t\tContext::Scope scope( context.get() );\n\t\tconst std::string s = Context::current()->substitute( phrase );\n\t\tGAFFERTEST_ASSERT( s == expectedResult );\n\n\t\tconst Context *nullContext = nullptr;\n\t\t{\n\t\t\tContext::Scope scope( nullContext );\n\t\t\tconst std::string s = Context::current()->substitute( phrase );\n\t\t\tGAFFERTEST_ASSERT( s == expectedResult );\n\t\t}\n\t}\n}\n\nvoid GafferTest::testEditableScope()\n{\n\ttestEditableScopeTyped<IECore::IntData>( 10, 20 );\n\ttestEditableScopeTyped<IECore::FloatData>( 10.0, 20.0 );\n\ttestEditableScopeTyped<IECore::StringData>( std::string( \"a\" ), std::string( \"b\" ) );\n\ttestEditableScopeTyped<IECore::InternedStringData>( IECore::InternedString( \"a\" ), IECore::InternedString( \"b\" ) );\n\ttestEditableScopeTyped<IECore::FloatVectorData>( std::vector<float>{ 1, 2, 3, 4 }, std::vector<float>{ 5, 6, 7 } );\n\ttestEditableScopeTyped<IECore::StringVectorData>( std::vector<std::string>{ \"a\", \"AA\" }, std::vector<std::string>{ \"bbbbbbb\" } );\n\ttestEditableScopeTyped<IECore::InternedStringVectorData>( std::vector<IECore::InternedString>{ \"a\", \"AA\" }, std::vector<IECore::InternedString>{ \"bbbbbbb\" } );\n\n\tPathMatcher a;\n\ta.addPath( \"\/a\/y\" );\n\ta.addPath( \"\/b\/y\" );\n\ta.addPath( \"\/c\/y\" );\n\tPathMatcher b;\n\tb.addPath( \"\/a\/x\" );\n\tb.addPath( \"\/b\/x\" );\n\ttestEditableScopeTyped<IECore::PathMatcherData>( a, b );\n\n\t\/\/ Test specific calls for dealing with time\n\tGaffer::ContextPtr baseContext = new Gaffer::Context();\n\tGaffer::Context::EditableScope scope( baseContext.get() );\n\tconst Gaffer::Context *currentContext = Gaffer::Context::current();\n\n\tscope.setFrame( 5 );\n\tGAFFERTEST_ASSERT( currentContext->getFrame() == 5 );\n\n\tfloat framesPerSecond = 8;\n\tscope.setFramesPerSecond( &framesPerSecond );\n\tGAFFERTEST_ASSERT( currentContext->getFramesPerSecond() == 8 );\n\n\tscope.setTime( 9 );\n\tGAFFERTEST_ASSERT( currentContext->getFrame() == 72 );\n\n\tscope.setTime( 8.5 );\n\tGAFFERTEST_ASSERT( currentContext->getFrame() == 68 );\n\n}\n\n\/\/ Create the number of contexts specified, and return counts for how many collisions there are\n\/\/ in each of the four 32 bit sections of the context hash. MurmurHash performs good mixing, so\n\/\/ the four sections should be independent, and as long as collisions within each section occur only\n\/\/ at the expected rate, the chance of a full collision across all 4 should be infinitesimal\n\/\/ ( we don't want to check for collisions in the whole 128 bit hash, since it would take years\n\/\/ for one to occur randomly )\n\/\/ \"mode\" switches betwen 4 modes for creating contexts:\n\/\/ 0 : 1 entry with a single increment int\n\/\/ 1 : 40 fixed strings, plus a single incrementing int\n\/\/ 2 : 20 random floats\n\/\/ 3 : an even mixture of the previous 3 modes\n\/\/ \"seed\" can be used to perform different runs to get an average number.\n\/\/ The goal is that regardless of how we create the contexts, they are all unique, and should therefore\n\/\/ have an identical chance of collisions if our hashing performs ideally.\nstd::tuple<int,int,int,int> GafferTest::countContextHash32Collisions( int contexts, int mode, int seed )\n{\n\tstd::unordered_set<uint32_t> used[4];\n\n\tInternedString a( \"a\" );\n\tInternedString numberNames[40];\n\tfor( int i = 0; i < 40; i++ )\n\t{\n\t\tnumberNames[i] = InternedString( i );\n\t}\n\n\tunsigned int rand_seed = seed;\n\tint collisions[4] = {0,0,0,0};\n\tfor( int i = 0; i < contexts; i++ )\n\t{\n\t\tint curMode = mode;\n\t\tint elementSeed = seed * contexts + i;\n\t\tif( curMode == 3 )\n\t\t{\n\t\t\tcurMode = i % 3;\n\t\t\telementSeed = seed * contexts + i \/ 3;\n\t\t}\n\n\t\tContext c;\n\t\tif( curMode == 0 )\n\t\t{\n\t\t\tc.set( a, elementSeed );\n\t\t}\n\t\telse if( curMode == 1 )\n\t\t{\n\t\t\tfor( int j = 0; j < 40; j++ )\n\t\t\t{\n\t\t\t\tc.set( numberNames[j], j );\n\t\t\t}\n\t\t\tc.set( a, elementSeed );\n\t\t}\n\t\telse if( curMode == 2 )\n\t\t{\n\t\t\tfor( int j = 0; j < 20; j++ )\n\t\t\t{\n\t\t\t\tc.set( numberNames[j], rand_r( &rand_seed ) );\n\t\t\t}\n\t\t}\n\n\t\tif( !used[0].insert( (uint32_t)( c.hash().h1() ) ).second )\n\t\t{\n\t\t\tcollisions[0]++;\n\t\t}\n\t\tif( !used[1].insert( (uint32_t)( c.hash().h1() >> 32 ) ).second )\n\t\t{\n\t\t\tcollisions[1]++;\n\t\t}\n\t\tif( !used[2].insert( (uint32_t)( c.hash().h2() ) ).second )\n\t\t{\n\t\t\tcollisions[2]++;\n\t\t}\n\t\tif( !used[3].insert( (uint32_t)( c.hash().h2() >> 32 ) ).second )\n\t\t{\n\t\t\tcollisions[3]++;\n\t\t}\n\t}\n\n\treturn std::make_tuple( collisions[0], collisions[1], collisions[2], collisions[3] );\n}\n\nvoid GafferTest::testContextHashPerformance( int numEntries, int entrySize, bool startInitialized )\n{\n\t\/\/ We usually deal with contexts that already have some stuff in them, so adding some entries\n\t\/\/ to the context makes this test more realistic\n\tContextPtr baseContext = new Context();\n\tfor( int i = 0; i < numEntries; i++ )\n\t{\n\t\tbaseContext->set( InternedString( i ), std::string( entrySize, 'x') );\n\t}\n\n\tconst InternedString varyingVarName = \"varyVar\";\n\tif( startInitialized )\n\t{\n\t\tbaseContext->set( varyingVarName, -1 );\n\t}\n\n\tContext::Scope baseScope( baseContext.get() );\n\n\tconst ThreadState &threadState = ThreadState::current();\n\n\ttbb::parallel_for( tbb::blocked_range<int>( 0, 10000000 ), [&threadState, &varyingVarName]( const tbb::blocked_range<int> &r )\n\t\t{\n\t\t\tfor( int i = r.begin(); i != r.end(); ++i )\n\t\t\t{\n\t\t\t\tContext::EditableScope scope( threadState );\n\t\t\t\tscope.set( varyingVarName, &i );\n\n\t\t\t\t\/\/ This call is relied on by ValuePlug's HashCacheKey, so it is crucial that it be fast\n\t\t\t\tscope.context()->hash();\n\t\t\t}\n\t\t}\n\t);\n\n}\n\nvoid GafferTest::testContextCopyPerformance( int numEntries, int entrySize )\n{\n\t\/\/ We usually deal with contexts that already have some stuff in them, so adding some entries\n\t\/\/ to the context makes this test more realistic\n\tContextPtr baseContext = new Context();\n\tfor( int i = 0; i < numEntries; i++ )\n\t{\n\t\tbaseContext->set( InternedString( i ), std::string( entrySize, 'x') );\n\t}\n\n\tconst InternedString varyingVarName = \"varyVar\";\n\n\ttbb::parallel_for( tbb::blocked_range<int>( 0, 1000000 ), [&baseContext, &varyingVarName]( const tbb::blocked_range<int> &r )\n\t\t{\n\t\t\tfor( int i = r.begin(); i != r.end(); ++i )\n\t\t\t{\n\t\t\t\tContextPtr copy = new Context( *baseContext );\n\t\t\t}\n\t\t}\n\t);\n\n}\n<commit_msg>ContextTest : Remove unused variable<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014-2015, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\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 with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferTest\/ContextTest.h\"\n\n#include \"GafferTest\/Assert.h\"\n\n#include \"Gaffer\/Context.h\"\n\n#include \"IECore\/Timer.h\"\n#include \"IECore\/VectorTypedData.h\"\n#include \"IECore\/PathMatcherData.h\"\n\n#include \"boost\/lexical_cast.hpp\"\n#include \"tbb\/parallel_for.h\"\n#include <unordered_set>\n\nusing namespace std;\nusing namespace boost;\nusing namespace IECore;\nusing namespace Gaffer;\n\n\/\/ A test useful for assessing the performance\n\/\/ of the Context class.\nvoid GafferTest::testManyContexts()\n{\n\t\/\/ our typical context doesn't have a huge number of keys - we'll\n\t\/\/ use a working set of 20 for this test.\n\n\tContextPtr base = new Context();\n\tconst int numKeys = 20;\n\tvector<InternedString> keys;\n\tfor( int i = 0; i < numKeys; ++i )\n\t{\n\t\tInternedString key = string( \"testKey\" ) + lexical_cast<string>( i );\n\t\tkeys.push_back( key );\n\t\tbase->set( key, -1 - i );\n\t}\n\tconst MurmurHash baseHash = base->hash();\n\n\t\/\/ then typically we create new temporary contexts based on that one,\n\t\/\/ change a value or two, and then continue.\n\n\tTimer t;\n\tfor( int i = 0; i < 1000000; ++i )\n\t{\n\t\t\/\/ In order to efficiently manipulate a context, we need to create an EditableScope.\n\t\t\/\/ ( On the other hand, using a Context directly copies new memory for the value to\n\t\t\/\/ create a fully independent context, which is pretty slow ).\n\t\tContext::EditableScope tmp( base.get() );\n\t\ttmp.set( keys[i%numKeys], &i );\n\t\tGAFFERTEST_ASSERT( tmp.context()->get<int>( keys[i%numKeys] ) == i );\n\t\tGAFFERTEST_ASSERT( tmp.context()->hash() != baseHash );\n\t}\n}\n\n\/\/ Useful for assessing the performance of substitutions.\nvoid GafferTest::testManySubstitutions()\n{\n\tContextPtr context = new Context();\n\tcontext->set( \"foodType\", std::string( \"kipper\" ) );\n\tcontext->set( \"cookingMethod\", std::string( \"smoke\" ) );\n\n\tconst std::string phrase( \"${cookingMethod} me a ${foodType}\" );\n\tconst std::string expectedResult( \"smoke me a kipper\" );\n\n\tTimer t;\n\tfor( int i = 0; i < 1000000; ++i )\n\t{\n\t\tconst std::string s = context->substitute( phrase );\n\t\tGAFFERTEST_ASSERT( s == expectedResult );\n\t}\n}\n\n\/\/ Useful for assessing the performance of environment variable substitutions.\nvoid GafferTest::testManyEnvironmentSubstitutions()\n{\n\tContextPtr context = new Context();\n\n\tconst std::string phrase( \"${GAFFER_ROOT}\" );\n\tconst std::string expectedResult( getenv( \"GAFFER_ROOT\") );\n\n\tTimer t;\n\tfor( int i = 0; i < 1000000; ++i )\n\t{\n\t\tconst std::string s = context->substitute( phrase );\n\t\tGAFFERTEST_ASSERT( s == expectedResult );\n\t}\n}\n\n\/\/ Tests that scoping a null context is a no-op\nvoid GafferTest::testScopingNullContext()\n{\n\tContextPtr context = new Context();\n\tcontext->set( \"foodType\", std::string( \"kipper\" ) );\n\tcontext->set( \"cookingMethod\", std::string( \"smoke\" ) );\n\n\tconst std::string phrase( \"${cookingMethod} me a ${foodType}\" );\n\tconst std::string expectedResult( \"smoke me a kipper\" );\n\n\t{\n\t\tContext::Scope scope( context.get() );\n\t\tconst std::string s = Context::current()->substitute( phrase );\n\t\tGAFFERTEST_ASSERT( s == expectedResult );\n\n\t\tconst Context *nullContext = nullptr;\n\t\t{\n\t\t\tContext::Scope scope( nullContext );\n\t\t\tconst std::string s = Context::current()->substitute( phrase );\n\t\t\tGAFFERTEST_ASSERT( s == expectedResult );\n\t\t}\n\t}\n}\n\nvoid GafferTest::testEditableScope()\n{\n\ttestEditableScopeTyped<IECore::IntData>( 10, 20 );\n\ttestEditableScopeTyped<IECore::FloatData>( 10.0, 20.0 );\n\ttestEditableScopeTyped<IECore::StringData>( std::string( \"a\" ), std::string( \"b\" ) );\n\ttestEditableScopeTyped<IECore::InternedStringData>( IECore::InternedString( \"a\" ), IECore::InternedString( \"b\" ) );\n\ttestEditableScopeTyped<IECore::FloatVectorData>( std::vector<float>{ 1, 2, 3, 4 }, std::vector<float>{ 5, 6, 7 } );\n\ttestEditableScopeTyped<IECore::StringVectorData>( std::vector<std::string>{ \"a\", \"AA\" }, std::vector<std::string>{ \"bbbbbbb\" } );\n\ttestEditableScopeTyped<IECore::InternedStringVectorData>( std::vector<IECore::InternedString>{ \"a\", \"AA\" }, std::vector<IECore::InternedString>{ \"bbbbbbb\" } );\n\n\tPathMatcher a;\n\ta.addPath( \"\/a\/y\" );\n\ta.addPath( \"\/b\/y\" );\n\ta.addPath( \"\/c\/y\" );\n\tPathMatcher b;\n\tb.addPath( \"\/a\/x\" );\n\tb.addPath( \"\/b\/x\" );\n\ttestEditableScopeTyped<IECore::PathMatcherData>( a, b );\n\n\t\/\/ Test specific calls for dealing with time\n\tGaffer::ContextPtr baseContext = new Gaffer::Context();\n\tGaffer::Context::EditableScope scope( baseContext.get() );\n\tconst Gaffer::Context *currentContext = Gaffer::Context::current();\n\n\tscope.setFrame( 5 );\n\tGAFFERTEST_ASSERT( currentContext->getFrame() == 5 );\n\n\tfloat framesPerSecond = 8;\n\tscope.setFramesPerSecond( &framesPerSecond );\n\tGAFFERTEST_ASSERT( currentContext->getFramesPerSecond() == 8 );\n\n\tscope.setTime( 9 );\n\tGAFFERTEST_ASSERT( currentContext->getFrame() == 72 );\n\n\tscope.setTime( 8.5 );\n\tGAFFERTEST_ASSERT( currentContext->getFrame() == 68 );\n\n}\n\n\/\/ Create the number of contexts specified, and return counts for how many collisions there are\n\/\/ in each of the four 32 bit sections of the context hash. MurmurHash performs good mixing, so\n\/\/ the four sections should be independent, and as long as collisions within each section occur only\n\/\/ at the expected rate, the chance of a full collision across all 4 should be infinitesimal\n\/\/ ( we don't want to check for collisions in the whole 128 bit hash, since it would take years\n\/\/ for one to occur randomly )\n\/\/ \"mode\" switches betwen 4 modes for creating contexts:\n\/\/ 0 : 1 entry with a single increment int\n\/\/ 1 : 40 fixed strings, plus a single incrementing int\n\/\/ 2 : 20 random floats\n\/\/ 3 : an even mixture of the previous 3 modes\n\/\/ \"seed\" can be used to perform different runs to get an average number.\n\/\/ The goal is that regardless of how we create the contexts, they are all unique, and should therefore\n\/\/ have an identical chance of collisions if our hashing performs ideally.\nstd::tuple<int,int,int,int> GafferTest::countContextHash32Collisions( int contexts, int mode, int seed )\n{\n\tstd::unordered_set<uint32_t> used[4];\n\n\tInternedString a( \"a\" );\n\tInternedString numberNames[40];\n\tfor( int i = 0; i < 40; i++ )\n\t{\n\t\tnumberNames[i] = InternedString( i );\n\t}\n\n\tunsigned int rand_seed = seed;\n\tint collisions[4] = {0,0,0,0};\n\tfor( int i = 0; i < contexts; i++ )\n\t{\n\t\tint curMode = mode;\n\t\tint elementSeed = seed * contexts + i;\n\t\tif( curMode == 3 )\n\t\t{\n\t\t\tcurMode = i % 3;\n\t\t\telementSeed = seed * contexts + i \/ 3;\n\t\t}\n\n\t\tContext c;\n\t\tif( curMode == 0 )\n\t\t{\n\t\t\tc.set( a, elementSeed );\n\t\t}\n\t\telse if( curMode == 1 )\n\t\t{\n\t\t\tfor( int j = 0; j < 40; j++ )\n\t\t\t{\n\t\t\t\tc.set( numberNames[j], j );\n\t\t\t}\n\t\t\tc.set( a, elementSeed );\n\t\t}\n\t\telse if( curMode == 2 )\n\t\t{\n\t\t\tfor( int j = 0; j < 20; j++ )\n\t\t\t{\n\t\t\t\tc.set( numberNames[j], rand_r( &rand_seed ) );\n\t\t\t}\n\t\t}\n\n\t\tif( !used[0].insert( (uint32_t)( c.hash().h1() ) ).second )\n\t\t{\n\t\t\tcollisions[0]++;\n\t\t}\n\t\tif( !used[1].insert( (uint32_t)( c.hash().h1() >> 32 ) ).second )\n\t\t{\n\t\t\tcollisions[1]++;\n\t\t}\n\t\tif( !used[2].insert( (uint32_t)( c.hash().h2() ) ).second )\n\t\t{\n\t\t\tcollisions[2]++;\n\t\t}\n\t\tif( !used[3].insert( (uint32_t)( c.hash().h2() >> 32 ) ).second )\n\t\t{\n\t\t\tcollisions[3]++;\n\t\t}\n\t}\n\n\treturn std::make_tuple( collisions[0], collisions[1], collisions[2], collisions[3] );\n}\n\nvoid GafferTest::testContextHashPerformance( int numEntries, int entrySize, bool startInitialized )\n{\n\t\/\/ We usually deal with contexts that already have some stuff in them, so adding some entries\n\t\/\/ to the context makes this test more realistic\n\tContextPtr baseContext = new Context();\n\tfor( int i = 0; i < numEntries; i++ )\n\t{\n\t\tbaseContext->set( InternedString( i ), std::string( entrySize, 'x') );\n\t}\n\n\tconst InternedString varyingVarName = \"varyVar\";\n\tif( startInitialized )\n\t{\n\t\tbaseContext->set( varyingVarName, -1 );\n\t}\n\n\tContext::Scope baseScope( baseContext.get() );\n\n\tconst ThreadState &threadState = ThreadState::current();\n\n\ttbb::parallel_for( tbb::blocked_range<int>( 0, 10000000 ), [&threadState, &varyingVarName]( const tbb::blocked_range<int> &r )\n\t\t{\n\t\t\tfor( int i = r.begin(); i != r.end(); ++i )\n\t\t\t{\n\t\t\t\tContext::EditableScope scope( threadState );\n\t\t\t\tscope.set( varyingVarName, &i );\n\n\t\t\t\t\/\/ This call is relied on by ValuePlug's HashCacheKey, so it is crucial that it be fast\n\t\t\t\tscope.context()->hash();\n\t\t\t}\n\t\t}\n\t);\n\n}\n\nvoid GafferTest::testContextCopyPerformance( int numEntries, int entrySize )\n{\n\t\/\/ We usually deal with contexts that already have some stuff in them, so adding some entries\n\t\/\/ to the context makes this test more realistic\n\tContextPtr baseContext = new Context();\n\tfor( int i = 0; i < numEntries; i++ )\n\t{\n\t\tbaseContext->set( InternedString( i ), std::string( entrySize, 'x') );\n\t}\n\n\ttbb::parallel_for(\n\t\ttbb::blocked_range<int>( 0, 1000000 ),\n\t\t[&baseContext]( const tbb::blocked_range<int> &r )\n\t\t{\n\t\t\tfor( int i = r.begin(); i != r.end(); ++i )\n\t\t\t{\n\t\t\t\tContextPtr copy = new Context( *baseContext );\n\t\t\t}\n\t\t}\n\t);\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Add constant for VPD #W keyword<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\ncontact: Boris.Polishchuk@cern.ch\nlink: see comments in the $ALICE_ROOT\/PHOS\/AliPHOSRcuDA1.cxx\nreference run: \/alice\/data\/2009\/LHC09b_PHOS\/000075883\/raw\/09000075883017.20.root\nrun type: PHYSICS\nDA type: MON \nnumber of events needed: 1000\ninput files: Mod0RCU0.data Mod0RCU1.data Mod0RCU2.data Mod0RCU3.data Mod1RCU0.data Mod1RCU1.data Mod1RCU2.data Mod1RCU3.data Mod2RCU0.data Mod2RCU1.data Mod2RCU2.data Mod2RCU3.data Mod3RCU0.data Mod3RCU1.data Mod3RCU2.data Mod3RCU3.data Mod4RCU0.data Mod4RCU1.data Mod4RCU2.data Mod4RCU3.data zs.txt\nOutput files: PHOS_Calib.root \nTrigger types used: PHYSICS\n*\/\n\n\n#include \"event.h\"\n#include \"monitor.h\"\nextern \"C\" {\n#include \"daqDA.h\"\n}\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <TSystem.h>\n#include <TROOT.h>\n#include <TPluginManager.h>\n\n#include \"AliRawReader.h\"\n#include \"AliRawReaderDate.h\"\n#include \"AliPHOSRcuDA1.h\"\n#include \"AliPHOSRawFitterv0.h\"\n#include \"AliCaloAltroMapping.h\"\n#include \"AliCaloRawStreamV3.h\"\n#include \"AliLog.h\"\n\n\/* Main routine\n Arguments: \n 1- monitoring data source\n*\/\nint main(int argc, char **argv) {\n\n gROOT->GetPluginManager()->AddHandler(\"TVirtualStreamerInfo\",\n\t\t\t\t\t\"*\",\n\t\t\t\t\t\"TStreamerInfo\",\n\t\t\t\t\t\"RIO\",\n\t\t\t\t\t\"TStreamerInfo()\");\n\n AliLog::SetGlobalDebugLevel(0) ;\n AliLog::SetGlobalLogLevel(AliLog::kFatal);\n \n int status;\n \n if (argc!=2) {\n printf(\"Wrong number of arguments\\n\");\n return -1;\n }\n \n \/* Retrieve ZS parameters from DAQ DB *\/\n const char* zsfile = \"zs.txt\";\n int failZS = daqDA_DB_getFile(zsfile, zsfile);\n \n Int_t offset,threshold;\n \n if(!failZS) {\n FILE *f = fopen(zsfile,\"r\");\n int scan = fscanf(f,\"%d %d\",&offset,&threshold);\n }\n \n \/* Retrieve mapping files from DAQ DB *\/ \n const char* mapFiles[20] = {\n \"Mod0RCU0.data\",\n \"Mod0RCU1.data\",\n \"Mod0RCU2.data\",\n \"Mod0RCU3.data\",\n \"Mod1RCU0.data\",\n \"Mod1RCU1.data\",\n \"Mod1RCU2.data\",\n \"Mod1RCU3.data\",\n \"Mod2RCU0.data\",\n \"Mod2RCU1.data\",\n \"Mod2RCU2.data\",\n \"Mod2RCU3.data\",\n \"Mod3RCU0.data\",\n \"Mod3RCU1.data\",\n \"Mod3RCU2.data\",\n \"Mod3RCU3.data\",\n \"Mod4RCU0.data\",\n \"Mod4RCU1.data\",\n \"Mod4RCU2.data\",\n \"Mod4RCU3.data\"\n };\n \n for(Int_t iFile=0; iFile<20; iFile++) {\n int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]);\n if(failed) { \n printf(\"Cannot retrieve file %s from DAQ DB. Exit.\\n\",mapFiles[iFile]);\n return -1;\n }\n }\n \n \/* Open mapping files *\/\n AliAltroMapping *mapping[20];\n TString path = \".\/\";\n \n path += \"Mod\";\n TString path2;\n TString path3;\n Int_t iMap = 0;\n \n for(Int_t iMod = 0; iMod < 5; iMod++) {\n path2 = path;\n path2 += iMod;\n path2 += \"RCU\";\n \n for(Int_t iRCU=0; iRCU<4; iRCU++) {\n path3 = path2;\n path3 += iRCU;\n path3 += \".data\";\n mapping[iMap] = new AliCaloAltroMapping(path3.Data());\n iMap++;\n }\n }\n \n \/* define data source : this is argument 1 *\/ \n status=monitorSetDataSource( argv[1] );\n if (status!=0) {\n printf(\"monitorSetDataSource() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n\n\n \/* declare monitoring program *\/\n status=monitorDeclareMp( __FILE__ );\n if (status!=0) {\n printf(\"monitorDeclareMp() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n\n\n \/* define wait event timeout - 1s max *\/\n monitorSetNowait();\n monitorSetNoWaitNetworkTimeout(1000);\n \n \/* init some counters *\/\n int nevents_physics=0;\n int nevents_total=0;\n\n AliRawReader *rawReader = NULL;\n AliPHOSRcuDA1* dAs[5];\n\n for(Int_t iMod=0; iMod<5; iMod++) {\n dAs[iMod] = 0;\n }\n \n Float_t e[64][56][2];\n Float_t t[64][56][2];\n\n for(Int_t iX=0; iX<64; iX++) {\n for(Int_t iZ=0; iZ<56; iZ++) {\n for(Int_t iGain=0; iGain<2; iGain++) {\n\te[iX][iZ][iGain] = 0.;\n\tt[iX][iZ][iGain] = 0.;\n }\n }\n }\n \n Int_t cellX = -1;\n Int_t cellZ = -1;\n Int_t nBunches = 0;\n Int_t sigStart, sigLength;\n Int_t caloFlag;\n\n \/* main loop (infinite) *\/\n for(;;) {\n struct eventHeaderStruct *event;\n eventTypeType eventT;\n \n \/* check shutdown condition *\/\n if (daqDA_checkShutdown()) {break;}\n \n \/* get next event (blocking call until timeout) *\/\n status=monitorGetEventDynamic((void **)&event);\n if (status==MON_ERR_EOF) {\n printf (\"End of File detected\\n\");\n break; \/* end of monitoring file has been reached *\/\n }\n \n if (status!=0) {\n printf(\"monitorGetEventDynamic() failed : %s\\n\",monitorDecodeError(status));\n break;\n }\n\n \/* retry if got no event *\/\n if (event==NULL) {\n continue;\n }\n\n\n \/* use event - here, just write event id to result file *\/\n eventT=event->eventType;\n \n if (eventT==PHYSICS_EVENT) {\n \n rawReader = new AliRawReaderDate((void*)event);\n AliCaloRawStreamV3 stream(rawReader,\"PHOS\",mapping);\n AliPHOSRawFitterv0 fitter;\n fitter.SubtractPedestals(kTRUE); \/\/ assume that data is non-ZS\n \n if(!failZS) {\n\tfitter.SubtractPedestals(kFALSE);\n\tfitter.SetAmpOffset(offset);\n\tfitter.SetAmpThreshold(threshold);\n }\n \n while (stream.NextDDL()) {\n\twhile (stream.NextChannel()) {\n\t \n\t \/* Retrieve ZS parameters from data*\/\n\t if(failZS) {\n\t short value = stream.GetAltroCFG1();\n\t bool ZeroSuppressionEnabled = (value >> 15) & 0x1;\n\t bool AutomaticBaselineSubtraction = (value >> 14) & 0x1;\n\t if(ZeroSuppressionEnabled) {\n\t offset = (value >> 10) & 0xf;\n\t threshold = value & 0x3ff;\n\t fitter.SubtractPedestals(kFALSE);\n\t fitter.SetAmpOffset(offset);\n\t fitter.SetAmpThreshold(threshold);\n\t }\n\t }\n\t \n\t cellX = stream.GetCellX();\n\t cellZ = stream.GetCellZ();\n\t caloFlag = stream.GetCaloFlag(); \/\/ 0=LG, 1=HG, 2=TRU\n\t \n\t if(caloFlag!=0 && caloFlag!=1) continue; \/\/TRU data!\n\t \n\t \/\/ In case of oscillating signals with ZS, \n\t \/\/a channel can have several bunches.\n\t \n\t nBunches = 0;\n\t while (stream.NextBunch()) {\n\t nBunches++;\n\t if (nBunches > 1) continue;\n\t sigStart = stream.GetStartTimeBin();\n\t sigLength = stream.GetBunchLength();\n\t fitter.SetChannelGeo(stream.GetModule(),cellX,cellZ,caloFlag);\n\t fitter.Eval(stream.GetSignals(),sigStart,sigLength);\n\t } \/\/ End of NextBunch()\n\t \n\t if (nBunches != 1) continue;\n\t \n\t e[cellX][cellZ][caloFlag] = fitter.GetEnergy();\n\t t[cellX][cellZ][caloFlag] = fitter.GetTime();\n\t}\n\t\n\tif(stream.GetModule()<0 || stream.GetModule()>4) continue;\n\t\n\tif(dAs[stream.GetModule()])\n\t dAs[stream.GetModule()]->FillHistograms(e,t);\n\telse {\n\t dAs[stream.GetModule()] = new AliPHOSRcuDA1(stream.GetModule(),-1,0);\n\t dAs[stream.GetModule()]->FillHistograms(e,t);\n\t}\n\t\n\tfor(Int_t iX=0; iX<64; iX++) {\n\t for(Int_t iZ=0; iZ<56; iZ++) {\n\t for(Int_t iGain=0; iGain<2; iGain++) {\n\t e[iX][iZ][iGain] = 0.;\n\t t[iX][iZ][iGain] = 0.;\n\t }\n\t }\n\t}\n\n }\n\n\/\/ da1.FillHistograms(e,t);\n\/\/ \/\/da1.UpdateHistoFile();\n \n\tdelete rawReader; \n\tnevents_physics++;\n }\n \n nevents_total++;\n \n \/* free resources *\/\n free(event);\n \n \/* exit when last event received, no need to wait for TERM signal *\/\n if (eventT==END_OF_RUN) {\n printf(\"EOR event detected\\n\");\n break;\n }\n }\n \n for(Int_t i = 0; i < 20; i++) delete mapping[i]; \n \n \/* Be sure that all histograms are saved *\/\n\n const TH2F* h2=0;\n const TH1F* h1=0;\n char localfile[128];\n \n sprintf(localfile,\"PHOS_Calib.root\");\n TFile* f = new TFile(localfile,\"recreate\");\n \n for(Int_t iMod=0; iMod<5; iMod++) {\n if(!dAs[iMod]) continue;\n \n printf(\"DA1 for module %d detected.\\n\",iMod);\n \n for(Int_t iX=0; iX<64; iX++) {\n for(Int_t iZ=0; iZ<56; iZ++) {\n\t\n\th1 = dAs[iMod]->GetHgLgRatioHistogram(iX,iZ); \/\/ High Gain\/Low Gain ratio\n\tif(h1) h1->Write(); \n\t\n\tfor(Int_t iGain=0; iGain<2; iGain++) {\n\t h2 = dAs[iMod]->GetTimeEnergyHistogram(iX,iZ,iGain); \/\/ Time vs Energy\n\t if(h2) h2->Write();\n\t}\n }\n }\n }\n \n f->Close();\n \n \/* Store output files to the File Exchange Server *\/\n daqDA_FES_storeFile(localfile,\"AMPLITUDES\");\n \n return status;\n}\n<commit_msg>Added possibility to accumulate statistics through the number of runs.<commit_after>\/*\ncontact: Boris.Polishchuk@cern.ch\nlink: see comments in the $ALICE_ROOT\/PHOS\/AliPHOSRcuDA1.cxx\nreference run: \/alice\/data\/2009\/LHC09b_PHOS\/000075883\/raw\/09000075883017.20.root\nrun type: PHYSICS\nDA type: MON \nnumber of events needed: 1000\ninput files: Mod0RCU0.data Mod0RCU1.data Mod0RCU2.data Mod0RCU3.data Mod1RCU0.data Mod1RCU1.data Mod1RCU2.data Mod1RCU3.data Mod2RCU0.data Mod2RCU1.data Mod2RCU2.data Mod2RCU3.data Mod3RCU0.data Mod3RCU1.data Mod3RCU2.data Mod3RCU3.data Mod4RCU0.data Mod4RCU1.data Mod4RCU2.data Mod4RCU3.data zs.txt\nOutput files: PHOS_Calib_Total.root contains cumulative statistics for a number of runs. \nTrigger types used: PHYSICS\n*\/\n\n\n#include \"event.h\"\n#include \"monitor.h\"\nextern \"C\" {\n#include \"daqDA.h\"\n}\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <TSystem.h>\n#include <TROOT.h>\n#include <TPluginManager.h>\n\n#include \"AliRawReader.h\"\n#include \"AliRawReaderDate.h\"\n#include \"AliPHOSRcuDA1.h\"\n#include \"AliPHOSRawFitterv0.h\"\n#include \"AliCaloAltroMapping.h\"\n#include \"AliCaloRawStreamV3.h\"\n#include \"AliLog.h\"\n\n\/* Main routine\n Arguments: \n 1- monitoring data source\n*\/\nint main(int argc, char **argv) {\n\n gROOT->GetPluginManager()->AddHandler(\"TVirtualStreamerInfo\",\n\t\t\t\t\t\"*\",\n\t\t\t\t\t\"TStreamerInfo\",\n\t\t\t\t\t\"RIO\",\n\t\t\t\t\t\"TStreamerInfo()\");\n\n AliLog::SetGlobalDebugLevel(0) ;\n AliLog::SetGlobalLogLevel(AliLog::kFatal);\n \n int status;\n \n if (argc!=2) {\n printf(\"Wrong number of arguments\\n\");\n return -1;\n }\n \n \/* Retrieve ZS parameters from DAQ DB *\/\n const char* zsfile = \"zs.txt\";\n int failZS = daqDA_DB_getFile(zsfile, zsfile);\n \n Int_t offset,threshold;\n \n if(!failZS) {\n FILE *f = fopen(zsfile,\"r\");\n int scan = fscanf(f,\"%d %d\",&offset,&threshold);\n }\n \n \/* Retrieve mapping files from DAQ DB *\/ \n const char* mapFiles[20] = {\n \"Mod0RCU0.data\",\n \"Mod0RCU1.data\",\n \"Mod0RCU2.data\",\n \"Mod0RCU3.data\",\n \"Mod1RCU0.data\",\n \"Mod1RCU1.data\",\n \"Mod1RCU2.data\",\n \"Mod1RCU3.data\",\n \"Mod2RCU0.data\",\n \"Mod2RCU1.data\",\n \"Mod2RCU2.data\",\n \"Mod2RCU3.data\",\n \"Mod3RCU0.data\",\n \"Mod3RCU1.data\",\n \"Mod3RCU2.data\",\n \"Mod3RCU3.data\",\n \"Mod4RCU0.data\",\n \"Mod4RCU1.data\",\n \"Mod4RCU2.data\",\n \"Mod4RCU3.data\"\n };\n \n for(Int_t iFile=0; iFile<20; iFile++) {\n int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]);\n if(failed) { \n printf(\"Cannot retrieve file %s from DAQ DB. Exit.\\n\",mapFiles[iFile]);\n return -1;\n }\n }\n \n \/* Open mapping files *\/\n AliAltroMapping *mapping[20];\n TString path = \".\/\";\n \n path += \"Mod\";\n TString path2;\n TString path3;\n Int_t iMap = 0;\n \n for(Int_t iMod = 0; iMod < 5; iMod++) {\n path2 = path;\n path2 += iMod;\n path2 += \"RCU\";\n \n for(Int_t iRCU=0; iRCU<4; iRCU++) {\n path3 = path2;\n path3 += iRCU;\n path3 += \".data\";\n mapping[iMap] = new AliCaloAltroMapping(path3.Data());\n iMap++;\n }\n }\n \n \/* define data source : this is argument 1 *\/ \n status=monitorSetDataSource( argv[1] );\n if (status!=0) {\n printf(\"monitorSetDataSource() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n\n\n \/* declare monitoring program *\/\n status=monitorDeclareMp( __FILE__ );\n if (status!=0) {\n printf(\"monitorDeclareMp() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n\n\n \/* define wait event timeout - 1s max *\/\n monitorSetNowait();\n monitorSetNoWaitNetworkTimeout(1000);\n \n \/* init some counters *\/\n int nevents_physics=0;\n int nevents_total=0;\n\n AliRawReader *rawReader = NULL;\n AliPHOSRcuDA1* dAs[5];\n\n for(Int_t iMod=0; iMod<5; iMod++) {\n dAs[iMod] = 0;\n }\n \n Float_t e[64][56][2];\n Float_t t[64][56][2];\n\n for(Int_t iX=0; iX<64; iX++) {\n for(Int_t iZ=0; iZ<56; iZ++) {\n for(Int_t iGain=0; iGain<2; iGain++) {\n\te[iX][iZ][iGain] = 0.;\n\tt[iX][iZ][iGain] = 0.;\n }\n }\n }\n \n Int_t cellX = -1;\n Int_t cellZ = -1;\n Int_t nBunches = 0;\n Int_t sigStart, sigLength;\n Int_t caloFlag;\n\n \/* main loop (infinite) *\/\n for(;;) {\n struct eventHeaderStruct *event;\n eventTypeType eventT;\n \n \/* check shutdown condition *\/\n if (daqDA_checkShutdown()) {break;}\n \n \/* get next event (blocking call until timeout) *\/\n status=monitorGetEventDynamic((void **)&event);\n if (status==MON_ERR_EOF) {\n printf (\"End of File detected\\n\");\n break; \/* end of monitoring file has been reached *\/\n }\n \n if (status!=0) {\n printf(\"monitorGetEventDynamic() failed : %s\\n\",monitorDecodeError(status));\n break;\n }\n\n \/* retry if got no event *\/\n if (event==NULL) {\n continue;\n }\n\n\n \/* use event - here, just write event id to result file *\/\n eventT=event->eventType;\n \n if (eventT==PHYSICS_EVENT) {\n \n rawReader = new AliRawReaderDate((void*)event);\n AliCaloRawStreamV3 stream(rawReader,\"PHOS\",mapping);\n AliPHOSRawFitterv0 fitter;\n fitter.SubtractPedestals(kTRUE); \/\/ assume that data is non-ZS\n \n if(!failZS) {\n\tfitter.SubtractPedestals(kFALSE);\n\tfitter.SetAmpOffset(offset);\n\tfitter.SetAmpThreshold(threshold);\n }\n \n while (stream.NextDDL()) {\n\twhile (stream.NextChannel()) {\n\t \n\t \/* Retrieve ZS parameters from data*\/\n\t if(failZS) {\n\t short value = stream.GetAltroCFG1();\n\t bool ZeroSuppressionEnabled = (value >> 15) & 0x1;\n\t bool AutomaticBaselineSubtraction = (value >> 14) & 0x1;\n\t if(ZeroSuppressionEnabled) {\n\t offset = (value >> 10) & 0xf;\n\t threshold = value & 0x3ff;\n\t fitter.SubtractPedestals(kFALSE);\n\t fitter.SetAmpOffset(offset);\n\t fitter.SetAmpThreshold(threshold);\n\t }\n\t }\n\t \n\t cellX = stream.GetCellX();\n\t cellZ = stream.GetCellZ();\n\t caloFlag = stream.GetCaloFlag(); \/\/ 0=LG, 1=HG, 2=TRU\n\t \n\t if(caloFlag!=0 && caloFlag!=1) continue; \/\/TRU data!\n\t \n\t \/\/ In case of oscillating signals with ZS, \n\t \/\/a channel can have several bunches.\n\t \n\t nBunches = 0;\n\t while (stream.NextBunch()) {\n\t nBunches++;\n\t if (nBunches > 1) continue;\n\t sigStart = stream.GetStartTimeBin();\n\t sigLength = stream.GetBunchLength();\n\t fitter.SetChannelGeo(stream.GetModule(),cellX,cellZ,caloFlag);\n\t fitter.Eval(stream.GetSignals(),sigStart,sigLength);\n\t } \/\/ End of NextBunch()\n\t \n\t if (nBunches != 1) continue;\n\t \n\t e[cellX][cellZ][caloFlag] = fitter.GetEnergy();\n\t t[cellX][cellZ][caloFlag] = fitter.GetTime();\n\t}\n\t\n\tif(stream.GetModule()<0 || stream.GetModule()>4) continue;\n\t\n\tif(dAs[stream.GetModule()])\n\t dAs[stream.GetModule()]->FillHistograms(e,t);\n\telse {\n\t dAs[stream.GetModule()] = new AliPHOSRcuDA1(stream.GetModule(),-1,0);\n\t dAs[stream.GetModule()]->FillHistograms(e,t);\n\t}\n\t\n\tfor(Int_t iX=0; iX<64; iX++) {\n\t for(Int_t iZ=0; iZ<56; iZ++) {\n\t for(Int_t iGain=0; iGain<2; iGain++) {\n\t e[iX][iZ][iGain] = 0.;\n\t t[iX][iZ][iGain] = 0.;\n\t }\n\t }\n\t}\n\n }\n\n\/\/ da1.FillHistograms(e,t);\n\/\/ \/\/da1.UpdateHistoFile();\n \n\tdelete rawReader; \n\tnevents_physics++;\n }\n \n nevents_total++;\n \n \/* free resources *\/\n free(event);\n \n \/* exit when last event received, no need to wait for TERM signal *\/\n if (eventT==END_OF_RUN) {\n printf(\"EOR event detected\\n\");\n break;\n }\n }\n \n for(Int_t i = 0; i < 20; i++) delete mapping[i]; \n \n \/* Be sure that all histograms are saved *\/\n\n char h2name[80];\n char totfile[80];\n \n \/\/Write the Total file (accumulated statistics for number of runs)\n sprintf(totfile,\"PHOS_Calib_Total.root\");\n TFile * ftot = new TFile(totfile,\"update\");\n \n if (!ftot->IsZombie()){\n printf(\"Updating file %s.\\n\",ftot->GetName());\n\n for(Int_t iMod=0; iMod<5; iMod++) {\n if(!dAs[iMod]) continue;\n \n printf(\"DA1 for module %d detected.\\n\",iMod);\n \n for(Int_t iX=0; iX<64; iX++) {\n\tfor(Int_t iZ=0; iZ<56; iZ++) {\n\t\n\t for(Int_t iGain=0; iGain<2; iGain++) {\n\t sprintf(h2name,\"%d_%d_%d_%d\",iMod,iX,iZ,iGain);\n\t TH2F* h2tot = (TH2F*)ftot->Get(h2name);\n\t const TH2F* h2run = dAs[iMod]->GetTimeEnergyHistogram(iX,iZ,iGain); \/\/ Time vs Energy\n\t if(!h2tot && h2run) h2run->Write();\n\t if(h2tot && h2run) { h2tot->Add(h2run); h2tot->Write(h2tot->GetName(),TObject::kWriteDelete); }\n\t }\n\t}\n }\n }\n }\n \n ftot->Close();\n \n \/* Store output files to the File Exchange Server *\/\n daqDA_FES_storeFile(totfile,\"AMPLITUDES\");\n \n return status;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n\/\/ Make sure LLVMFuzzerInitialize is called.\n#include <assert.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic char *argv0;\n\nextern \"C\" int LLVMFuzzerInitialize(int *argc, char ***argv) {\n assert(*argc > 0);\n argv0 = **argv;\n fprintf(stderr, \"LLVMFuzzerInitialize: %s\\n\", argv0);\n return 0;\n}\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n if (Size == strlen(argv0) &&\n !strncmp(reinterpret_cast<const char *>(Data), argv0, Size)) {\n fprintf(stderr, \"BINGO %s\\n\", argv0);\n exit(1);\n }\n return 0;\n}\n<commit_msg>[libFuzzer] Un-reverting change in tests after fixing the failure on Linux.<commit_after>\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n\/\/ Make sure LLVMFuzzerInitialize is called.\n#include <assert.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic char *argv0;\n\nextern \"C\" int LLVMFuzzerInitialize(int *argc, char ***argv) {\n assert(*argc > 0);\n argv0 = **argv;\n fprintf(stderr, \"LLVMFuzzerInitialize: %s\\n\", argv0);\n return 0;\n}\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n if (Size == strlen(argv0) &&\n !memmem(Data, Size, argv0, Size)) {\n fprintf(stderr, \"BINGO %s\\n\", argv0);\n exit(1);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Globals.h\"\n\n#include \"FluidSimulator.h\"\n#include \"..\/World.h\"\n\n\n\n\n\ncFluidSimulator::cFluidSimulator(cWorld & a_World, BLOCKTYPE a_Fluid, BLOCKTYPE a_StationaryFluid) :\n\tsuper(a_World),\n\tm_FluidBlock(a_Fluid),\n\tm_StationaryFluidBlock(a_StationaryFluid)\n{\n}\n\n\n\n\n\nbool cFluidSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType)\n{\n\treturn ((a_BlockType == m_FluidBlock) || (a_BlockType == m_StationaryFluidBlock));\n}\n\n\n\n\n\nbool cFluidSimulator::CanWashAway(BLOCKTYPE a_BlockType)\n{\n\tswitch (a_BlockType)\n\t{\n\t\tcase E_BLOCK_BROWN_MUSHROOM:\n\t\tcase E_BLOCK_CACTUS:\n\t\tcase E_BLOCK_COBWEB:\n\t\tcase E_BLOCK_CROPS:\n\t\tcase E_BLOCK_DEAD_BUSH:\n\t\tcase E_BLOCK_RAIL:\n\t\tcase E_BLOCK_REDSTONE_TORCH_OFF:\n\t\tcase E_BLOCK_REDSTONE_TORCH_ON:\n\t\tcase E_BLOCK_REDSTONE_WIRE:\n\t\tcase E_BLOCK_RED_MUSHROOM:\n\t\tcase E_BLOCK_RED_ROSE:\n\t\tcase E_BLOCK_SNOW:\n\t\tcase E_BLOCK_SUGARCANE:\n\t\tcase E_BLOCK_TALL_GRASS:\n\t\tcase E_BLOCK_TORCH:\n\t\tcase E_BLOCK_YELLOW_FLOWER:\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n\n\n\n\nbool cFluidSimulator::IsSolidBlock(BLOCKTYPE a_BlockType)\n{\n\treturn !IsPassableForFluid(a_BlockType);\n}\n\n\n\n\n\nbool cFluidSimulator::IsPassableForFluid(BLOCKTYPE a_BlockType)\n{\n\treturn (\n\t\t(a_BlockType == E_BLOCK_AIR) ||\n\t\t(a_BlockType == E_BLOCK_FIRE) ||\n\t\tIsAllowedBlock(a_BlockType) ||\n\t\tCanWashAway(a_BlockType)\n\t);\n}\n\n\n\n\n\nbool cFluidSimulator::IsHigherMeta(NIBBLETYPE a_Meta1, NIBBLETYPE a_Meta2)\n{\n\tif (a_Meta1 == 0)\n\t{\n\t\t\/\/ Source block is higher than anything, even itself.\n\t\treturn true;\n\t}\n\tif ((a_Meta1 & 0x08) != 0)\n\t{\n\t\t\/\/ Falling fluid is higher than anything, including self\n\t\treturn true;\n\t}\n\t\n\tif (a_Meta2 == 0)\n\t{\n\t\t\/\/ Second block is a source and first block isn't\n\t\treturn false;\n\t}\n\tif ((a_Meta2 & 0x08) != 0)\n\t{\n\t\t\/\/ Second block is falling and the first one is neither a source nor falling\n\t\treturn false;\n\t}\n\t\n\t\/\/ All special cases have been handled, now it's just a raw comparison:\n\treturn (a_Meta1 < a_Meta2);\n}\n\n\n\n\n\n\/\/ TODO Not working very well yet :s\nDirection cFluidSimulator::GetFlowingDirection(int a_X, int a_Y, int a_Z, bool a_Over)\n{\n\tif ((a_Y < 0) || (a_Y >= cChunkDef::Height))\n\t{\n\t\treturn NONE;\n\t}\n\tBLOCKTYPE BlockID = m_World.GetBlock(a_X, a_Y, a_Z);\n\tif (!IsAllowedBlock(BlockID))\t\/\/ No Fluid -> No Flowing direction :D\n\t{\n\t\treturn NONE;\n\t}\n\n\t\/*\n\tDisabled because of causing problems and being useless atm\n\tchar BlockBelow = m_World.GetBlock(a_X, a_Y - 1, a_Z);\t\t\/\/If there is nothing or fluid below it -> dominating flow is down :D\n\tif (BlockBelow == E_BLOCK_AIR || IsAllowedBlock(BlockBelow))\n\t\treturn Y_MINUS;\n\t*\/\n\n\tNIBBLETYPE LowestPoint = m_World.GetBlockMeta(a_X, a_Y, a_Z);\t\/\/Current Block Meta so only lower points will be counted\n\tint X = 0, Z = 0;\t\t\t\t\t\t\t\t\t\/\/Lowest Pos will be stored here\n\n\tif (IsAllowedBlock(m_World.GetBlock(a_X, a_Y + 1, a_Z)) && a_Over)\t\t\/\/check for upper block to flow because this also affects the flowing direction\n\t{\n\t\treturn GetFlowingDirection(a_X, a_Y + 1, a_Z, false);\n\t}\n\n\tstd::vector< Vector3i * > Points;\n\n\tPoints.reserve(4);\t\/\/Already allocate 4 places :D\n\n\t\/\/add blocks around the checking pos\n\tPoints.push_back(new Vector3i(a_X - 1, a_Y, a_Z));\n\tPoints.push_back(new Vector3i(a_X + 1, a_Y, a_Z));\n\tPoints.push_back(new Vector3i(a_X, a_Y, a_Z + 1));\n\tPoints.push_back(new Vector3i(a_X, a_Y, a_Z - 1));\n\n\tfor (std::vector<Vector3i *>::iterator it = Points.begin(); it < Points.end(); it++)\n\t{\n\t\tVector3i *Pos = (*it);\n\t\tchar BlockID = m_World.GetBlock(Pos->x, Pos->y, Pos->z);\n\t\tif(IsAllowedBlock(BlockID))\n\t\t{\n\t\t\tchar Meta = m_World.GetBlockMeta(Pos->x, Pos->y, Pos->z);\n\n\t\t\tif(Meta > LowestPoint)\n\t\t\t{\n\t\t\t\tLowestPoint = Meta;\n\t\t\t\tX = Pos->x;\n\t\t\t\tPos->y; \/\/Remove if no side effects\n\t\t\t\tZ = Pos->z;\n\t\t\t}\n\t\t}else if(BlockID == E_BLOCK_AIR)\n\t\t{\n\t\t\tLowestPoint = 9;\t\t\/\/This always dominates\n\t\t\tX = Pos->x;\n\t\t\tPos->y; \/\/Remove if no side effects\n\t\t\tZ = Pos->z;\n\t\t\n\t\t}\n\t\tdelete Pos;\n\t}\n\n\tif (LowestPoint == m_World.GetBlockMeta(a_X, a_Y, a_Z))\n\t\treturn NONE;\n\n\tif (a_X - X > 0)\n\t{\n\t\treturn X_MINUS;\n\t}\n\n\tif (a_X - X < 0)\n\t{\n\t\treturn X_PLUS;\n\t}\n\n\tif (a_Z - Z > 0)\n\t{\n\t\treturn Z_MINUS;\n\t}\n\n\tif (a_Z - Z < 0)\n\t{\n\t\treturn Z_PLUS;\n\t}\n\n\treturn NONE;\n}\n\n\n\n\n<commit_msg>Removed unused lookups<commit_after>#include \"Globals.h\"\n\n#include \"FluidSimulator.h\"\n#include \"..\/World.h\"\n\n\n\n\n\ncFluidSimulator::cFluidSimulator(cWorld & a_World, BLOCKTYPE a_Fluid, BLOCKTYPE a_StationaryFluid) :\n\tsuper(a_World),\n\tm_FluidBlock(a_Fluid),\n\tm_StationaryFluidBlock(a_StationaryFluid)\n{\n}\n\n\n\n\n\nbool cFluidSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType)\n{\n\treturn ((a_BlockType == m_FluidBlock) || (a_BlockType == m_StationaryFluidBlock));\n}\n\n\n\n\n\nbool cFluidSimulator::CanWashAway(BLOCKTYPE a_BlockType)\n{\n\tswitch (a_BlockType)\n\t{\n\t\tcase E_BLOCK_BROWN_MUSHROOM:\n\t\tcase E_BLOCK_CACTUS:\n\t\tcase E_BLOCK_COBWEB:\n\t\tcase E_BLOCK_CROPS:\n\t\tcase E_BLOCK_DEAD_BUSH:\n\t\tcase E_BLOCK_RAIL:\n\t\tcase E_BLOCK_REDSTONE_TORCH_OFF:\n\t\tcase E_BLOCK_REDSTONE_TORCH_ON:\n\t\tcase E_BLOCK_REDSTONE_WIRE:\n\t\tcase E_BLOCK_RED_MUSHROOM:\n\t\tcase E_BLOCK_RED_ROSE:\n\t\tcase E_BLOCK_SNOW:\n\t\tcase E_BLOCK_SUGARCANE:\n\t\tcase E_BLOCK_TALL_GRASS:\n\t\tcase E_BLOCK_TORCH:\n\t\tcase E_BLOCK_YELLOW_FLOWER:\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n\n\n\n\nbool cFluidSimulator::IsSolidBlock(BLOCKTYPE a_BlockType)\n{\n\treturn !IsPassableForFluid(a_BlockType);\n}\n\n\n\n\n\nbool cFluidSimulator::IsPassableForFluid(BLOCKTYPE a_BlockType)\n{\n\treturn (\n\t\t(a_BlockType == E_BLOCK_AIR) ||\n\t\t(a_BlockType == E_BLOCK_FIRE) ||\n\t\tIsAllowedBlock(a_BlockType) ||\n\t\tCanWashAway(a_BlockType)\n\t);\n}\n\n\n\n\n\nbool cFluidSimulator::IsHigherMeta(NIBBLETYPE a_Meta1, NIBBLETYPE a_Meta2)\n{\n\tif (a_Meta1 == 0)\n\t{\n\t\t\/\/ Source block is higher than anything, even itself.\n\t\treturn true;\n\t}\n\tif ((a_Meta1 & 0x08) != 0)\n\t{\n\t\t\/\/ Falling fluid is higher than anything, including self\n\t\treturn true;\n\t}\n\t\n\tif (a_Meta2 == 0)\n\t{\n\t\t\/\/ Second block is a source and first block isn't\n\t\treturn false;\n\t}\n\tif ((a_Meta2 & 0x08) != 0)\n\t{\n\t\t\/\/ Second block is falling and the first one is neither a source nor falling\n\t\treturn false;\n\t}\n\t\n\t\/\/ All special cases have been handled, now it's just a raw comparison:\n\treturn (a_Meta1 < a_Meta2);\n}\n\n\n\n\n\n\/\/ TODO Not working very well yet :s\nDirection cFluidSimulator::GetFlowingDirection(int a_X, int a_Y, int a_Z, bool a_Over)\n{\n\tif ((a_Y < 0) || (a_Y >= cChunkDef::Height))\n\t{\n\t\treturn NONE;\n\t}\n\tBLOCKTYPE BlockID = m_World.GetBlock(a_X, a_Y, a_Z);\n\tif (!IsAllowedBlock(BlockID))\t\/\/ No Fluid -> No Flowing direction :D\n\t{\n\t\treturn NONE;\n\t}\n\n\t\/*\n\tDisabled because of causing problems and being useless atm\n\tchar BlockBelow = m_World.GetBlock(a_X, a_Y - 1, a_Z);\t\t\/\/If there is nothing or fluid below it -> dominating flow is down :D\n\tif (BlockBelow == E_BLOCK_AIR || IsAllowedBlock(BlockBelow))\n\t\treturn Y_MINUS;\n\t*\/\n\n\tNIBBLETYPE LowestPoint = m_World.GetBlockMeta(a_X, a_Y, a_Z);\t\/\/Current Block Meta so only lower points will be counted\n\tint X = 0, Z = 0;\t\t\t\t\t\t\t\t\t\/\/Lowest Pos will be stored here\n\n\tif (IsAllowedBlock(m_World.GetBlock(a_X, a_Y + 1, a_Z)) && a_Over)\t\t\/\/check for upper block to flow because this also affects the flowing direction\n\t{\n\t\treturn GetFlowingDirection(a_X, a_Y + 1, a_Z, false);\n\t}\n\n\tstd::vector< Vector3i * > Points;\n\n\tPoints.reserve(4);\t\/\/Already allocate 4 places :D\n\n\t\/\/add blocks around the checking pos\n\tPoints.push_back(new Vector3i(a_X - 1, a_Y, a_Z));\n\tPoints.push_back(new Vector3i(a_X + 1, a_Y, a_Z));\n\tPoints.push_back(new Vector3i(a_X, a_Y, a_Z + 1));\n\tPoints.push_back(new Vector3i(a_X, a_Y, a_Z - 1));\n\n\tfor (std::vector<Vector3i *>::iterator it = Points.begin(); it < Points.end(); it++)\n\t{\n\t\tVector3i *Pos = (*it);\n\t\tchar BlockID = m_World.GetBlock(Pos->x, Pos->y, Pos->z);\n\t\tif(IsAllowedBlock(BlockID))\n\t\t{\n\t\t\tchar Meta = m_World.GetBlockMeta(Pos->x, Pos->y, Pos->z);\n\n\t\t\tif(Meta > LowestPoint)\n\t\t\t{\n\t\t\t\tLowestPoint = Meta;\n\t\t\t\tX = Pos->x;\n\t\t\t\tZ = Pos->z;\n\t\t\t}\n\t\t}else if(BlockID == E_BLOCK_AIR)\n\t\t{\n\t\t\tLowestPoint = 9;\t\t\/\/This always dominates\n\t\t\tX = Pos->x;\n\t\t\tZ = Pos->z;\n\t\t\n\t\t}\n\t\tdelete Pos;\n\t}\n\n\tif (LowestPoint == m_World.GetBlockMeta(a_X, a_Y, a_Z))\n\t\treturn NONE;\n\n\tif (a_X - X > 0)\n\t{\n\t\treturn X_MINUS;\n\t}\n\n\tif (a_X - X < 0)\n\t{\n\t\treturn X_PLUS;\n\t}\n\n\tif (a_Z - Z > 0)\n\t{\n\t\treturn Z_MINUS;\n\t}\n\n\tif (a_Z - Z < 0)\n\t{\n\t\treturn Z_PLUS;\n\t}\n\n\treturn NONE;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"BatmanScene.h\"\n#include \"DrawingSettings.h\"\n\n\/\/ OpenGL imports\n#include <GL\/glut.h>\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n\nBatmanScene::BatmanScene() :\n Scene(),\n pi(3.141592)\n{\n createScene();\n}\n\nvoid BatmanScene::createScene()\n{\n GLfloat light_position[] = {0.0, 1.0, 1.0, 0.0};\n glLightfv(GL_LIGHT0, GL_POSITION, light_position);\n\n setupCamera();\n\n \/\/ cannot put more than 7 rigidity for cloth\n cape = new Cloth(15.0, 15.0, 15, 2);\n\n setupClothTips();\n setClothMass(1.0);\n \/\/ createRunningScene();\n createCenterCollisionBallScene();\n addForces();\n\n time = 0.0;\n}\n\nvoid BatmanScene::createRunningScene()\n{\n setupFeet();\n createBoundaries();\n}\n\nvoid BatmanScene::addForces()\n{\n Vector3 gravity(0.0, -1.0, 0.0);\n Vector3 wind(0.0, 0.0, 10.0);\n\n cape->addForce(gravity);\n cape->addForce(wind);\n}\n\nvoid BatmanScene::createCenterCollisionBallScene()\n{\n otherSpheres.push_back(Sphere(Vector3(7.5, 10.0, 5.0), 2.0));\n}\n\nvoid BatmanScene::setupFeet()\n{\n Vector3 centerBetweenFeet(5.0, 2.0, -1.0);\n\n \/\/ left foot\n leftFoot.push_back(Sphere(centerBetweenFeet + Vector3(-2.0, 0.0, 0.0 ), 1.2));\n\n \/\/ right foot\n rightFoot.push_back(Sphere(centerBetweenFeet + Vector3( 2.0, 0.0, 0.0 ), 1.2));\n}\n\nvoid BatmanScene::setupCamera()\n{\n nearPlane = 1.0;\n farPlane = 200.0;\n\n camera = new Camera();\n camera->setPosition(Vector3(-10.0, 7.5, 20.0));\n camera->setViewDirection(Vector3(1.0, 0.0, -1.0));\n camera->setUpDirection(Vector3(0.0, 1.0, 0.0));\n camera->saveCameraSetup();\n}\n\nvoid BatmanScene::setClothMass(float mass)\n{\n for(int x = 0; x < cape->getNumberNodesWidth() - 1; x += 1)\n {\n for(int y = 0; y < cape->getNumberNodesHeight() - 1; y += 1)\n {\n cape->getNode(x, y)->setMass(mass);\n }\n }\n}\n\nvoid BatmanScene::setupClothTips()\n{\n cape->getNode(0 , cape->getNumberNodesHeight() - 1)->setMoveable(false);\n cape->getNode(cape->getNumberNodesWidth() - 1, cape->getNumberNodesHeight() - 1)->setMoveable(false);\n}\n\nvoid BatmanScene::createBoundaries()\n{\n float spacing = cape->getClothWidth() \/ cape->getNumberNodesWidth();\n for(int x = 0; x < cape->getNumberNodesWidth(); x += 1)\n {\n float xPos = x * spacing;\n\n for(int y = 0; y < cape->getNumberNodesHeight(); y += 1)\n {\n float yPos = y * spacing;\n\n \/\/ put elements in rectangular grid with yPos depth\n boundaries.push_back(Sphere(Vector3(xPos, yPos, -1.0), 0.5));\n boundaries.push_back(Sphere(Vector3(xPos, yPos, -yPos) + Vector3(0.0, 0.0, 15), 0.5));\n }\n }\n}\n\nvoid BatmanScene::translateBoundaries()\n{\n float leftShoulderZ = cape->getNode(0, cape->getNumberNodesHeight() - 1)->getPosition().z;\n\n for(std::vector<Sphere>::iterator it = boundaries.begin();\n it != boundaries.end();\n ++it)\n {\n it->translate(Vector3(0.0, 0.0, leftShoulderZ) - boundaries[0].getCenter());\n }\n}\n\nvoid BatmanScene::simulate()\n{\n float timeStep = DrawingSettings::getInstance()->getTimeStep();\n if(timeStep != 0.0)\n {\n time += timeStep;\n cape->applyForces(timeStep);\n cape->satisfyConstraints();\n\n \/\/ swingLeftFoot();\n \/\/ swingLeftShoulder();\n \/\/ swingRightFoot();\n \/\/ swingRightShoulder();\n\n \/\/ translateBoundaries();\n \/\/ cape->handleSphereIntersections(&leftFoot);\n \/\/ cape->handleSphereIntersections(&rightFoot);\n \/\/ cape->handleSphereIntersections(&boundaries);\n cape->handleSphereIntersections(&otherSpheres);\n cape->handleSelfIntersections();\n }\n}\n\nvoid BatmanScene::drawFeet()\n{\n drawBodyElement(&leftFoot);\n drawBodyElement(&rightFoot);\n}\n\nvoid BatmanScene::drawOtherSpheres()\n{\n drawBodyElement(&otherSpheres);\n}\n\nvoid BatmanScene::draw()\n{\n DrawingSettings::getInstance()->chooseRenderingMethod();\n drawWorldAxis();\n cape->draw();\n drawFeet();\n drawOtherSpheres();\n\n \/\/ TODO : remove\n drawBodyElement(&boundaries);\n}\n\nvoid BatmanScene::drawBodyElement(std::vector<Sphere>* elements)\n{\n for(std::vector<Sphere>::iterator sphereIterator = elements->begin();\n sphereIterator != elements->end();\n ++sphereIterator)\n {\n sphereIterator->draw();\n }\n}\n\nvoid BatmanScene::swingLeftFoot()\n{\n Sphere* left = &leftFoot[0];\n float r = 1.5;\n float t = time * 100;\n\n float x = left->getCenter().x;\n float y = r * (1 - cos(t));\n float z = -r * (t - sin(t));\n\n Vector3 position(x, y, z);\n left->setCenter(position);\n}\n\nvoid BatmanScene::swingRightFoot()\n{\n Sphere* right = &rightFoot[0];\n float r = 1.5;\n float t = time * 100;\n\n float x = right->getCenter().x;\n float y = r * (1 - cos(t - pi));\n float z = -r * (t - sin(t - pi));\n\n Vector3 position(x, y, z);\n right->setCenter(position);\n}\n\nvoid BatmanScene::swingLeftShoulder()\n{\n Node* left = cape->getNode(0, cape->getNumberNodesHeight() - 1);\n float r = 1.5;\n float t = time * 100;\n\n float x = left->getPosition().x;\n float y = left->getPosition().y;\n float z = -r * (t - sin(t - pi));\n\n Vector3 position(x, y, z);\n left->setPosition(position);\n}\n\nvoid BatmanScene::swingRightShoulder()\n{\n Node* right = cape->getNode(cape->getNumberNodesWidth() - 1, cape->getNumberNodesHeight() - 1);\n float r = 1.5;\n float t = time * 100;\n\n float x = right->getPosition().x;\n float y = right->getPosition().y;\n float z = -r * (t - sin(t));\n\n Vector3 position(x, y, z);\n right->setPosition(position);\n}<commit_msg>running scene boolean<commit_after>#include \"BatmanScene.h\"\n#include \"DrawingSettings.h\"\n\n\/\/ OpenGL imports\n#include <GL\/glut.h>\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n\nBatmanScene::BatmanScene() :\n Scene(),\n pi(3.141592)\n{\n createScene();\n}\n\nvoid BatmanScene::createScene()\n{\n GLfloat light_position[] = {0.0, 1.0, 1.0, 0.0};\n glLightfv(GL_LIGHT0, GL_POSITION, light_position);\n\n setupCamera();\n\n \/\/ cannot put more than 7 rigidity for cloth\n cape = new Cloth(15.0, 15.0, 20, 2);\n\n setupClothTips();\n setClothMass(1.0);\n createRunningScene();\n \/\/ createCenterCollisionBallScene();\n addForces();\n\n time = 0.0;\n}\n\nvoid BatmanScene::createRunningScene()\n{\n setupFeet();\n createBoundaries();\n}\n\nvoid BatmanScene::addForces()\n{\n Vector3 gravity(0.0, -1.0, 0.0);\n Vector3 wind(0.0, 0.0, 10.0);\n\n cape->addForce(gravity);\n cape->addForce(wind);\n}\n\nvoid BatmanScene::createCenterCollisionBallScene()\n{\n otherSpheres.push_back(Sphere(Vector3(7.5, 10.0, 5.0), 2.0));\n}\n\nvoid BatmanScene::setupFeet()\n{\n Vector3 centerBetweenFeet(5.0, 2.0, -1.0);\n\n \/\/ left foot\n leftFoot.push_back(Sphere(centerBetweenFeet + Vector3(-2.0, 0.0, 0.0 ), 1.2));\n\n \/\/ right foot\n rightFoot.push_back(Sphere(centerBetweenFeet + Vector3( 2.0, 0.0, 0.0 ), 1.2));\n}\n\nvoid BatmanScene::setupCamera()\n{\n nearPlane = 1.0;\n farPlane = 200.0;\n\n camera = new Camera();\n camera->setPosition(Vector3(-10.0, 7.5, 20.0));\n camera->setViewDirection(Vector3(1.0, 0.0, -1.0));\n camera->setUpDirection(Vector3(0.0, 1.0, 0.0));\n camera->saveCameraSetup();\n}\n\nvoid BatmanScene::setClothMass(float mass)\n{\n for(int x = 0; x < cape->getNumberNodesWidth() - 1; x += 1)\n {\n for(int y = 0; y < cape->getNumberNodesHeight() - 1; y += 1)\n {\n cape->getNode(x, y)->setMass(mass);\n }\n }\n}\n\nvoid BatmanScene::setupClothTips()\n{\n cape->getNode(0 , cape->getNumberNodesHeight() - 1)->setMoveable(false);\n cape->getNode(cape->getNumberNodesWidth() - 1, cape->getNumberNodesHeight() - 1)->setMoveable(false);\n}\n\nvoid BatmanScene::createBoundaries()\n{\n float spacing = cape->getClothWidth() \/ cape->getNumberNodesWidth();\n for(int x = 0; x < cape->getNumberNodesWidth(); x += 1)\n {\n float xPos = x * spacing;\n\n for(int y = 0; y < cape->getNumberNodesHeight(); y += 1)\n {\n float yPos = y * spacing;\n\n \/\/ put elements in rectangular grid with yPos depth\n boundaries.push_back(Sphere(Vector3(xPos, yPos, -1.0), 0.5));\n boundaries.push_back(Sphere(Vector3(xPos, yPos, -yPos) + Vector3(0.0, 0.0, 15), 0.5));\n }\n }\n}\n\nvoid BatmanScene::translateBoundaries()\n{\n float leftShoulderZ = cape->getNode(0, cape->getNumberNodesHeight() - 1)->getPosition().z;\n\n for(std::vector<Sphere>::iterator it = boundaries.begin();\n it != boundaries.end();\n ++it)\n {\n it->translate(Vector3(0.0, 0.0, leftShoulderZ) - boundaries[0].getCenter());\n }\n}\n\nvoid BatmanScene::simulate()\n{\n float timeStep = DrawingSettings::getInstance()->getTimeStep();\n if(timeStep != 0.0)\n {\n time += timeStep;\n cape->applyForces(timeStep);\n cape->satisfyConstraints();\n\n if(runningSceneEnabled)\n {\n swingLeftFoot();\n swingLeftShoulder();\n swingRightFoot();\n swingRightShoulder();\n\n translateBoundaries();\n cape->handleSphereIntersections(&leftFoot);\n cape->handleSphereIntersections(&rightFoot);\n cape->handleSphereIntersections(&boundaries);\n }\n else\n {\n cape->handleSphereIntersections(&otherSpheres);\n }\n\n cape->handleSelfIntersections();\n }\n}\n\nvoid BatmanScene::drawFeet()\n{\n drawBodyElement(&leftFoot);\n drawBodyElement(&rightFoot);\n}\n\nvoid BatmanScene::drawOtherSpheres()\n{\n drawBodyElement(&otherSpheres);\n}\n\nvoid BatmanScene::draw()\n{\n DrawingSettings::getInstance()->chooseRenderingMethod();\n drawWorldAxis();\n cape->draw();\n drawFeet();\n drawOtherSpheres();\n\n \/\/ TODO : remove\n drawBodyElement(&boundaries);\n}\n\nvoid BatmanScene::drawBodyElement(std::vector<Sphere>* elements)\n{\n for(std::vector<Sphere>::iterator sphereIterator = elements->begin();\n sphereIterator != elements->end();\n ++sphereIterator)\n {\n sphereIterator->draw();\n }\n}\n\nvoid BatmanScene::swingLeftFoot()\n{\n Sphere* left = &leftFoot[0];\n float r = 1.5;\n float t = time * 100;\n\n float x = left->getCenter().x;\n float y = r * (1 - cos(t));\n float z = -r * (t - sin(t));\n\n Vector3 position(x, y, z);\n left->setCenter(position);\n}\n\nvoid BatmanScene::swingRightFoot()\n{\n Sphere* right = &rightFoot[0];\n float r = 1.5;\n float t = time * 100;\n\n float x = right->getCenter().x;\n float y = r * (1 - cos(t - pi));\n float z = -r * (t - sin(t - pi));\n\n Vector3 position(x, y, z);\n right->setCenter(position);\n}\n\nvoid BatmanScene::swingLeftShoulder()\n{\n Node* left = cape->getNode(0, cape->getNumberNodesHeight() - 1);\n float r = 1.5;\n float t = time * 100;\n\n float x = left->getPosition().x;\n float y = left->getPosition().y;\n float z = -r * (t - sin(t - pi));\n\n Vector3 position(x, y, z);\n left->setPosition(position);\n}\n\nvoid BatmanScene::swingRightShoulder()\n{\n Node* right = cape->getNode(cape->getNumberNodesWidth() - 1, cape->getNumberNodesHeight() - 1);\n float r = 1.5;\n float t = time * 100;\n\n float x = right->getPosition().x;\n float y = right->getPosition().y;\n float z = -r * (t - sin(t));\n\n Vector3 position(x, y, z);\n right->setPosition(position);\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS oj30 (1.38.98); FILE MERGED 2008\/01\/10 07:59:45 oj 1.38.98.1: #i85085# add std<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_PERSISTENCE_PAIRS_HH__\n#define ALEPH_PERSISTENCE_PAIRS_HH__\n\n#include \"BoundaryMatrix.hh\"\n#include \"PersistencePairing.hh\"\n\n#include <iostream>\n#include <tuple>\n\nnamespace aleph\n{\n\ntemplate <class ReductionAlgorithm, class Representation> void computePersistencePairs( const BoundaryMatrix<Representation>& M )\n{\n using Index = typename Representation::Index;\n using PersistencePairing = PersistencePairing<Index>;\n\n BoundaryMatrix<Representation> B = M;\n\n ReductionAlgorithm reductionAlgorithm;\n reductionAlgorithm( B );\n\n PersistencePairing pairing;\n\n auto numColumns = B.getNumColumns();\n\n for( Index j = Index(0); j < numColumns; j++ )\n {\n Index i;\n bool valid;\n\n std::tie( i, valid ) = B.getMaximumIndex( j );\n if( valid )\n {\n std::cout << \"Pair: \" << i << \"--\" << j << std::endl;\n\n pairing.add( i, j );\n }\n }\n}\n\n}\n\n#endif\n<commit_msg>Extended calculation of persistence pairs<commit_after>#ifndef ALEPH_PERSISTENCE_PAIRS_HH__\n#define ALEPH_PERSISTENCE_PAIRS_HH__\n\n#include \"BoundaryMatrix.hh\"\n#include \"PersistencePairing.hh\"\n\n#include <iostream>\n#include <tuple>\n\nnamespace aleph\n{\n\ntemplate <\n class ReductionAlgorithm,\n class Representation\n> PersistencePairing<typename Representation::Index> computePersistencePairs( const BoundaryMatrix<Representation>& M )\n{\n using Index = typename Representation::Index;\n using PersistencePairing = PersistencePairing<Index>;\n\n BoundaryMatrix<Representation> B = M;\n\n ReductionAlgorithm reductionAlgorithm;\n reductionAlgorithm( B );\n\n PersistencePairing pairing;\n\n auto numColumns = B.getNumColumns();\n\n for( Index j = Index(0); j < numColumns; j++ )\n {\n Index i;\n bool valid;\n\n std::tie( i, valid ) = B.getMaximumIndex( j );\n if( valid )\n {\n std::cout << \"Pair: \" << i << \"--\" << j << std::endl;\n\n pairing.add( i, j );\n }\n }\n\n return pairing;\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\r\nCopyright 2017 Intel Corporation\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of\r\nthis software and associated documentation files (the \"Software\"), to deal in\r\nthe Software without restriction, including without limitation the rights to\r\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\r\nof the Software, and to permit persons to whom the Software is furnished to do\r\nso, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n*\/\r\n\r\n#include <assert.h>\r\n#include <thread>\r\n#include <windows.h>\r\n\r\n#include \"CommandLine.hpp\"\r\n#include \"PresentMon.hpp\"\r\n\r\nnamespace {\r\n\r\nenum {\r\n HOTKEY_ID = 0x80,\r\n\r\n WM_STOP_ETW_THREADS = WM_USER + 0,\r\n};\r\n\r\nHWND g_hWnd = 0;\r\nbool g_originalScrollLockEnabled = false;\r\n\r\nstd::thread g_EtwConsumingThread;\r\nbool g_StopEtwThreads = true;\r\n\r\nbool EtwThreadsRunning()\r\n{\r\n return g_EtwConsumingThread.joinable();\r\n}\r\n\r\nvoid StartEtwThreads(CommandLineArgs const& args)\r\n{\r\n assert(!EtwThreadsRunning());\r\n assert(EtwThreadsShouldQuit());\r\n g_StopEtwThreads = false;\r\n g_EtwConsumingThread = std::thread(EtwConsumingThread, args);\r\n}\r\n\r\nvoid StopEtwThreads(CommandLineArgs* args)\r\n{\r\n assert(EtwThreadsRunning());\r\n assert(g_StopEtwThreads == false);\r\n g_StopEtwThreads = true;\r\n g_EtwConsumingThread.join();\r\n args->mRecordingCount++;\r\n}\r\n\r\nBOOL WINAPI ConsoleCtrlHandler(\r\n _In_ DWORD dwCtrlType\r\n )\r\n{\r\n (void) dwCtrlType;\r\n PostStopRecording();\r\n PostQuitProcess();\r\n return TRUE;\r\n}\r\n\r\nLRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\r\n{\r\n auto args = (CommandLineArgs*) GetWindowLongPtrW(hWnd, GWLP_USERDATA);\r\n\r\n switch (uMsg) {\r\n case WM_HOTKEY:\r\n if (wParam == HOTKEY_ID) {\r\n if (EtwThreadsRunning()) {\r\n StopEtwThreads(args);\r\n } else {\r\n StartEtwThreads(*args);\r\n }\r\n }\r\n break;\r\n\r\n case WM_STOP_ETW_THREADS:\r\n if (EtwThreadsRunning()) {\r\n StopEtwThreads(args);\r\n }\r\n break;\r\n }\r\n\r\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\r\n}\r\n\r\nHWND CreateMessageQueue(CommandLineArgs& args)\r\n{\r\n WNDCLASSEXW Class = { sizeof(Class) };\r\n Class.lpfnWndProc = WindowProc;\r\n Class.lpszClassName = L\"PresentMon\";\r\n if (!RegisterClassExW(&Class)) {\r\n fprintf(stderr, \"error: failed to register hotkey class.\\n\");\r\n return 0;\r\n }\r\n\r\n HWND hWnd = CreateWindowExW(0, Class.lpszClassName, L\"PresentMonWnd\", 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, nullptr);\r\n if (!hWnd) {\r\n fprintf(stderr, \"error: failed to create hotkey window.\\n\");\r\n return 0;\r\n }\r\n\r\n if (args.mHotkeySupport) {\r\n if (!RegisterHotKey(hWnd, HOTKEY_ID, args.mHotkeyModifiers, args.mHotkeyVirtualKeyCode)) {\r\n fprintf(stderr, \"error: failed to register hotkey.\\n\");\r\n DestroyWindow(hWnd);\r\n return 0;\r\n }\r\n }\r\n\r\n SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(&args));\r\n\r\n return hWnd;\r\n}\r\n\r\nbool HaveAdministratorPrivileges()\r\n{\r\n enum {\r\n PRIVILEGE_UNKNOWN,\r\n PRIVILEGE_ELEVATED,\r\n PRIVILEGE_NOT_ELEVATED,\r\n } static privilege = PRIVILEGE_UNKNOWN;\r\n\r\n if (privilege == PRIVILEGE_UNKNOWN) {\r\n typedef BOOL(WINAPI *OpenProcessTokenProc)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle);\r\n typedef BOOL(WINAPI *GetTokenInformationProc)(HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, DWORD *ReturnLength);\r\n HMODULE advapi = LoadLibraryA(\"advapi32\");\r\n if (advapi) {\r\n OpenProcessTokenProc OpenProcessToken = (OpenProcessTokenProc)GetProcAddress(advapi, \"OpenProcessToken\");\r\n GetTokenInformationProc GetTokenInformation = (GetTokenInformationProc)GetProcAddress(advapi, \"GetTokenInformation\");\r\n if (OpenProcessToken && GetTokenInformation) {\r\n HANDLE hToken = NULL;\r\n if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {\r\n \/** BEGIN WORKAROUND: struct TOKEN_ELEVATION and enum value\r\n * TokenElevation are not defined in the vs2003 headers, so\r\n * we reproduce them here. **\/\r\n enum { WA_TokenElevation = 20 };\r\n struct {\r\n DWORD TokenIsElevated;\r\n } token = {};\r\n \/** END WA **\/\r\n\r\n DWORD dwSize = 0;\r\n if (GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) WA_TokenElevation, &token, sizeof(token), &dwSize)) {\r\n privilege = token.TokenIsElevated ? PRIVILEGE_ELEVATED : PRIVILEGE_NOT_ELEVATED;\r\n }\r\n\r\n CloseHandle(hToken);\r\n }\r\n }\r\n FreeLibrary(advapi);\r\n }\r\n }\r\n\r\n return privilege == PRIVILEGE_ELEVATED;\r\n}\r\n\r\n}\r\n\r\nbool EtwThreadsShouldQuit()\r\n{\r\n return g_StopEtwThreads;\r\n}\r\n\r\nvoid PostToggleRecording(CommandLineArgs const& args)\r\n{\r\n PostMessage(g_hWnd, WM_HOTKEY, HOTKEY_ID, args.mHotkeyModifiers & ~MOD_NOREPEAT);\r\n}\r\n\r\nvoid PostStopRecording()\r\n{\r\n PostMessage(g_hWnd, WM_STOP_ETW_THREADS, 0, 0);\r\n}\r\n\r\nvoid PostQuitProcess()\r\n{\r\n PostMessage(g_hWnd, WM_QUIT, 0, 0);\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n \/\/ Parse command line arguments\r\n CommandLineArgs args;\r\n if (!ParseCommandLine(argc, argv, &args)) {\r\n return 1;\r\n }\r\n\r\n \/\/ Check required privilege\r\n if (!args.mEtlFileName && !HaveAdministratorPrivileges()) {\r\n if (args.mTryToElevate) {\r\n fprintf(stderr, \"warning: process requires administrator privilege; attempting to elevate.\\n\");\r\n if (!RestartAsAdministrator(argc, argv)) {\r\n return 1;\r\n }\r\n } else {\r\n fprintf(stderr, \"error: process requires administrator privilege.\\n\");\r\n }\r\n return 2;\r\n }\r\n\r\n int ret = 0;\r\n\r\n \/\/ Set console title to command line arguments\r\n SetConsoleTitle(argc, argv);\r\n\r\n \/\/ If the user wants to use the scroll lock key as an indicator of when\r\n \/\/ present mon is recording events, make sure it is disabled to start.\r\n if (args.mScrollLockIndicator) {\r\n g_originalScrollLockEnabled = EnableScrollLock(false);\r\n }\r\n\r\n \/\/ Create a message queue to handle WM_HOTKEY, WM_STOP_ETW_THREADS, and\r\n \/\/ WM_QUIT messages.\r\n HWND hWnd = CreateMessageQueue(args);\r\n if (hWnd == 0) {\r\n ret = 3;\r\n goto clean_up;\r\n }\r\n\r\n \/\/ Set CTRL handler to capture when the user tries to close the process by\r\n \/\/ closing the console window or CTRL-C or similar. The handler will\r\n \/\/ ignore this and instead post WM_QUIT to our message queue.\r\n \/\/\r\n \/\/ We must set g_hWnd before setting the handler.\r\n g_hWnd = hWnd;\r\n SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);\r\n\r\n \/\/ If the user didn't specify -hotkey, simulate a hotkey press to start the\r\n \/\/ recording right away.\r\n if (!args.mHotkeySupport) {\r\n PostToggleRecording(args);\r\n }\r\n\r\n \/\/ Enter the main thread message loop. This thread will block waiting for\r\n \/\/ any messages, which will control the hotkey-toggling and process\r\n \/\/ shutdown.\r\n for (MSG message = {}; GetMessageW(&message, hWnd, 0, 0); ) {\r\n TranslateMessage(&message);\r\n DispatchMessageW(&message);\r\n }\r\n\r\n \/\/ Everything should be shutdown by now.\r\n assert(!EtwThreadsRunning());\r\n\r\nclean_up:\r\n \/\/ Restore original scroll lock state\r\n if (args.mScrollLockIndicator) {\r\n EnableScrollLock(g_originalScrollLockEnabled);\r\n }\r\n\r\n return ret;\r\n}\r\n<commit_msg>Fix for consistently getting events from processes under separate accounts (like dwm.exe).<commit_after>\/*\r\nCopyright 2017 Intel Corporation\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of\r\nthis software and associated documentation files (the \"Software\"), to deal in\r\nthe Software without restriction, including without limitation the rights to\r\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\r\nof the Software, and to permit persons to whom the Software is furnished to do\r\nso, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n*\/\r\n\r\n#include <assert.h>\r\n#include <thread>\r\n#include <windows.h>\r\n\r\n#include \"CommandLine.hpp\"\r\n#include \"PresentMon.hpp\"\r\n\r\nnamespace {\r\n\r\nenum {\r\n HOTKEY_ID = 0x80,\r\n\r\n WM_STOP_ETW_THREADS = WM_USER + 0,\r\n};\r\n\r\nHWND g_hWnd = 0;\r\nbool g_originalScrollLockEnabled = false;\r\n\r\nstd::thread g_EtwConsumingThread;\r\nbool g_StopEtwThreads = true;\r\n\r\nbool EtwThreadsRunning()\r\n{\r\n return g_EtwConsumingThread.joinable();\r\n}\r\n\r\nvoid StartEtwThreads(CommandLineArgs const& args)\r\n{\r\n assert(!EtwThreadsRunning());\r\n assert(EtwThreadsShouldQuit());\r\n g_StopEtwThreads = false;\r\n g_EtwConsumingThread = std::thread(EtwConsumingThread, args);\r\n}\r\n\r\nvoid StopEtwThreads(CommandLineArgs* args)\r\n{\r\n assert(EtwThreadsRunning());\r\n assert(g_StopEtwThreads == false);\r\n g_StopEtwThreads = true;\r\n g_EtwConsumingThread.join();\r\n args->mRecordingCount++;\r\n}\r\n\r\nBOOL WINAPI ConsoleCtrlHandler(\r\n _In_ DWORD dwCtrlType\r\n )\r\n{\r\n (void) dwCtrlType;\r\n PostStopRecording();\r\n PostQuitProcess();\r\n return TRUE;\r\n}\r\n\r\nLRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\r\n{\r\n auto args = (CommandLineArgs*) GetWindowLongPtrW(hWnd, GWLP_USERDATA);\r\n\r\n switch (uMsg) {\r\n case WM_HOTKEY:\r\n if (wParam == HOTKEY_ID) {\r\n if (EtwThreadsRunning()) {\r\n StopEtwThreads(args);\r\n } else {\r\n StartEtwThreads(*args);\r\n }\r\n }\r\n break;\r\n\r\n case WM_STOP_ETW_THREADS:\r\n if (EtwThreadsRunning()) {\r\n StopEtwThreads(args);\r\n }\r\n break;\r\n }\r\n\r\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\r\n}\r\n\r\nHWND CreateMessageQueue(CommandLineArgs& args)\r\n{\r\n WNDCLASSEXW Class = { sizeof(Class) };\r\n Class.lpfnWndProc = WindowProc;\r\n Class.lpszClassName = L\"PresentMon\";\r\n if (!RegisterClassExW(&Class)) {\r\n fprintf(stderr, \"error: failed to register hotkey class.\\n\");\r\n return 0;\r\n }\r\n\r\n HWND hWnd = CreateWindowExW(0, Class.lpszClassName, L\"PresentMonWnd\", 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, nullptr);\r\n if (!hWnd) {\r\n fprintf(stderr, \"error: failed to create hotkey window.\\n\");\r\n return 0;\r\n }\r\n\r\n if (args.mHotkeySupport) {\r\n if (!RegisterHotKey(hWnd, HOTKEY_ID, args.mHotkeyModifiers, args.mHotkeyVirtualKeyCode)) {\r\n fprintf(stderr, \"error: failed to register hotkey.\\n\");\r\n DestroyWindow(hWnd);\r\n return 0;\r\n }\r\n }\r\n\r\n SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(&args));\r\n\r\n return hWnd;\r\n}\r\n\r\nbool HaveAdministratorPrivileges()\r\n{\r\n enum {\r\n PRIVILEGE_UNKNOWN,\r\n PRIVILEGE_ELEVATED,\r\n PRIVILEGE_NOT_ELEVATED,\r\n } static privilege = PRIVILEGE_UNKNOWN;\r\n\r\n if (privilege == PRIVILEGE_UNKNOWN) {\r\n typedef BOOL(WINAPI *OpenProcessTokenProc)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle);\r\n typedef BOOL(WINAPI *GetTokenInformationProc)(HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, DWORD *ReturnLength);\r\n HMODULE advapi = LoadLibraryA(\"advapi32\");\r\n if (advapi) {\r\n OpenProcessTokenProc OpenProcessToken = (OpenProcessTokenProc)GetProcAddress(advapi, \"OpenProcessToken\");\r\n GetTokenInformationProc GetTokenInformation = (GetTokenInformationProc)GetProcAddress(advapi, \"GetTokenInformation\");\r\n if (OpenProcessToken && GetTokenInformation) {\r\n HANDLE hToken = NULL;\r\n if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {\r\n \/** BEGIN WORKAROUND: struct TOKEN_ELEVATION and enum value\r\n * TokenElevation are not defined in the vs2003 headers, so\r\n * we reproduce them here. **\/\r\n enum { WA_TokenElevation = 20 };\r\n struct {\r\n DWORD TokenIsElevated;\r\n } token = {};\r\n \/** END WA **\/\r\n\r\n DWORD dwSize = 0;\r\n if (GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) WA_TokenElevation, &token, sizeof(token), &dwSize)) {\r\n privilege = token.TokenIsElevated ? PRIVILEGE_ELEVATED : PRIVILEGE_NOT_ELEVATED;\r\n }\r\n\r\n CloseHandle(hToken);\r\n }\r\n }\r\n FreeLibrary(advapi);\r\n }\r\n }\r\n\r\n return privilege == PRIVILEGE_ELEVATED;\r\n}\r\n\r\nbool SetPrivilege(HANDLE hToken, LPCSTR lpszPrivilege, bool bEnablePrivilege)\r\n{\r\n bool bPrivilegeSet = false;\r\n typedef BOOL(WINAPI *LookupPrivilegeValueAProc)(LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid);\r\n typedef BOOL(WINAPI *AdjustTokenPrivilegesProc)(HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength);\r\n HMODULE advapi = LoadLibraryA(\"advapi32\");\r\n if (advapi) {\r\n LookupPrivilegeValueAProc LookupPrivilegeValueA = (LookupPrivilegeValueAProc)GetProcAddress(advapi, \"LookupPrivilegeValueA\");\r\n AdjustTokenPrivilegesProc AdjustTokenPrivileges = (AdjustTokenPrivilegesProc)GetProcAddress(advapi, \"AdjustTokenPrivileges\");\r\n if (LookupPrivilegeValueA && AdjustTokenPrivileges) {\r\n LUID luid;\r\n if (LookupPrivilegeValueA(NULL, lpszPrivilege, &luid)) {\r\n TOKEN_PRIVILEGES tp;\r\n tp.PrivilegeCount = 1;\r\n tp.Privileges[0].Luid = luid;\r\n tp.Privileges[0].Attributes = bEnablePrivilege ? SE_PRIVILEGE_ENABLED : 0;\r\n\r\n if (AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL)) {\r\n if (GetLastError() != ERROR_NOT_ALL_ASSIGNED) {\r\n bPrivilegeSet = true;\r\n }\r\n else {\r\n fprintf(stderr, \"error: token does not have the specified privilege.\\n\");\r\n }\r\n }\r\n else {\r\n fprintf(stderr, \"error: failed to adjust token privileges (%u).\\n\", GetLastError());\r\n }\r\n }\r\n else {\r\n fprintf(stderr, \"error: failed to lookup privilege value (%u).\\n\", GetLastError());\r\n }\r\n }\r\n FreeLibrary(advapi);\r\n }\r\n\r\n return bPrivilegeSet;\r\n}\r\n\r\nbool AdjustPrivileges()\r\n{\r\n \/\/ DWM processes run under a separate account.\r\n \/\/ We need permissions to get data about a process owned by another account.\r\n bool bPrivilegesSet = false;\r\n typedef BOOL(WINAPI *OpenProcessTokenProc)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle);\r\n HMODULE advapi = LoadLibraryA(\"advapi32\");\r\n if (advapi) {\r\n OpenProcessTokenProc OpenProcessToken = (OpenProcessTokenProc)GetProcAddress(advapi, \"OpenProcessToken\");\r\n if (OpenProcessToken) {\r\n HANDLE hToken = NULL;\r\n if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) {\r\n if (SetPrivilege(hToken, \"SeDebugPrivilege\", true)) {\r\n bPrivilegesSet = true;\r\n }\r\n else {\r\n fprintf(stderr, \"error: failed to enable SeDebugPrivilege.\\n\");\r\n }\r\n\r\n CloseHandle(hToken);\r\n }\r\n }\r\n FreeLibrary(advapi);\r\n }\r\n\r\n return bPrivilegesSet;\r\n}\r\n\r\n}\r\n\r\nbool EtwThreadsShouldQuit()\r\n{\r\n return g_StopEtwThreads;\r\n}\r\n\r\nvoid PostToggleRecording(CommandLineArgs const& args)\r\n{\r\n PostMessage(g_hWnd, WM_HOTKEY, HOTKEY_ID, args.mHotkeyModifiers & ~MOD_NOREPEAT);\r\n}\r\n\r\nvoid PostStopRecording()\r\n{\r\n PostMessage(g_hWnd, WM_STOP_ETW_THREADS, 0, 0);\r\n}\r\n\r\nvoid PostQuitProcess()\r\n{\r\n PostMessage(g_hWnd, WM_QUIT, 0, 0);\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n \/\/ Parse command line arguments\r\n CommandLineArgs args;\r\n if (!ParseCommandLine(argc, argv, &args)) {\r\n return 1;\r\n }\r\n\r\n \/\/ Check required privilege\r\n if (!args.mEtlFileName && !HaveAdministratorPrivileges()) {\r\n if (args.mTryToElevate) {\r\n fprintf(stderr, \"warning: process requires administrator privilege; attempting to elevate.\\n\");\r\n if (!RestartAsAdministrator(argc, argv)) {\r\n return 1;\r\n }\r\n } else {\r\n fprintf(stderr, \"error: process requires administrator privilege.\\n\");\r\n }\r\n return 2;\r\n }\r\n\r\n \/\/ Adjust process privileges for real-time\r\n if (!args.mEtlFileName && !AdjustPrivileges()) {\r\n fprintf(stderr, \"error: process requires special privileges.\\n\");\r\n }\r\n\r\n int ret = 0;\r\n\r\n \/\/ Set console title to command line arguments\r\n SetConsoleTitle(argc, argv);\r\n\r\n \/\/ If the user wants to use the scroll lock key as an indicator of when\r\n \/\/ present mon is recording events, make sure it is disabled to start.\r\n if (args.mScrollLockIndicator) {\r\n g_originalScrollLockEnabled = EnableScrollLock(false);\r\n }\r\n\r\n \/\/ Create a message queue to handle WM_HOTKEY, WM_STOP_ETW_THREADS, and\r\n \/\/ WM_QUIT messages.\r\n HWND hWnd = CreateMessageQueue(args);\r\n if (hWnd == 0) {\r\n ret = 3;\r\n goto clean_up;\r\n }\r\n\r\n \/\/ Set CTRL handler to capture when the user tries to close the process by\r\n \/\/ closing the console window or CTRL-C or similar. The handler will\r\n \/\/ ignore this and instead post WM_QUIT to our message queue.\r\n \/\/\r\n \/\/ We must set g_hWnd before setting the handler.\r\n g_hWnd = hWnd;\r\n SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);\r\n\r\n \/\/ If the user didn't specify -hotkey, simulate a hotkey press to start the\r\n \/\/ recording right away.\r\n if (!args.mHotkeySupport) {\r\n PostToggleRecording(args);\r\n }\r\n\r\n \/\/ Enter the main thread message loop. This thread will block waiting for\r\n \/\/ any messages, which will control the hotkey-toggling and process\r\n \/\/ shutdown.\r\n for (MSG message = {}; GetMessageW(&message, hWnd, 0, 0); ) {\r\n TranslateMessage(&message);\r\n DispatchMessageW(&message);\r\n }\r\n\r\n \/\/ Everything should be shutdown by now.\r\n assert(!EtwThreadsRunning());\r\n\r\nclean_up:\r\n \/\/ Restore original scroll lock state\r\n if (args.mScrollLockIndicator) {\r\n EnableScrollLock(g_originalScrollLockEnabled);\r\n }\r\n\r\n return ret;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"xml_doc.hpp\"\n#include \"libxml2_error_handlers.hpp\"\n#include <libxml\/xpath.h>\n#include <memory>\n\nclass FreeXPathCtxt {\npublic:\n auto operator( )( xmlXPathContext *xpathCtxt ) const -> void {\n xmlXPathFreeContext( xpathCtxt );\n }\n};\n\nclass XPathCtxt {\n friend class XPathQuery;\n\npublic:\n XPathCtxt( ) : xpathCtxt_{nullptr} {}\n explicit XPathCtxt( const XmlDoc &xml )\n : xpathCtxt_{xmlXPathNewContext( xml.xmlDoc_.get( ) )} {\n xpathHandler_.registerHandler( xpathCtxt_.get( ) );\n }\n XPathCtxt( const XPathCtxt &xpathCtxt ) {\n xpathCtxt_.reset( xmlXPathNewContext( xpathCtxt.xpathCtxt_->doc ) );\n xpathHandler_.registerHandler( xpathCtxt_.get( ) );\n }\n XPathCtxt( XPathCtxt &&xpathCtxt )\n : xpathCtxt_{std::move( xpathCtxt.xpathCtxt_ )},\n xpathHandler_{std::move( xpathCtxt.xpathHandler_ )} {}\n auto operator=( const XPathCtxt &rhs ) -> XPathCtxt & {\n if ( this != &rhs ) {\n xpathCtxt_.reset( xmlXPathNewContext( rhs.xpathCtxt_->doc ) );\n xpathHandler_ = rhs.xpathHandler_;\n }\n return *this;\n }\n auto operator=( XPathCtxt &&xpathCtxt ) -> XPathCtxt & {\n xpathCtxt_ = std::move( xpathCtxt.xpathCtxt_ );\n xpathHandler_ = std::move( xpathCtxt.xpathHandler_ );\n return *this;\n }\n explicit operator bool( ) const { return ( xpathCtxt_ != nullptr ); }\n friend auto operator>>( const XmlDoc &xml, XPathCtxt &xpathCtxt ) -> XPathCtxt & {\n xpathCtxt.xpathCtxt_.reset( xmlXPathNewContext( xml.xmlDoc_.get( ) ) );\n xpathCtxt.xpathHandler_.registerHandler(\n xpathCtxt.xpathCtxt_.get( ) ); \/\/ ist this correct?\n return xpathCtxt;\n }\n auto errorHandler( ) const -> const IErrorHandler & { return xpathHandler_; }\n\nprivate:\n using XPathCtxtT = std::unique_ptr<xmlXPathContext, FreeXPathCtxt>;\n XPathCtxtT xpathCtxt_;\n XPathErrorHandler xpathHandler_;\n};\n\n<commit_msg>operator bool() returns false for empty XmlDoc<commit_after>#pragma once\n\n#include \"xml_doc.hpp\"\n#include \"libxml2_error_handlers.hpp\"\n#include <libxml\/xpath.h>\n#include <memory>\n#include <iostream>\n\nclass FreeXPathCtxt {\npublic:\n auto operator( )( xmlXPathContext *xpathCtxt ) const -> void {\n xmlXPathFreeContext( xpathCtxt );\n }\n};\n\nclass XPathCtxt {\n friend class XPathQuery;\n\npublic:\n XPathCtxt( ) : xpathCtxt_{nullptr} {}\n explicit XPathCtxt( const XmlDoc &xml )\n : xpathCtxt_{xmlXPathNewContext( xml.xmlDoc_.get( ) )} {\n xpathHandler_.registerHandler( xpathCtxt_.get( ) );\n }\n XPathCtxt( const XPathCtxt &xpathCtxt ) {\n xpathCtxt_.reset( xmlXPathNewContext( xpathCtxt.xpathCtxt_->doc ) );\n xpathHandler_.registerHandler( xpathCtxt_.get( ) );\n }\n XPathCtxt( XPathCtxt &&xpathCtxt )\n : xpathCtxt_{std::move( xpathCtxt.xpathCtxt_ )},\n xpathHandler_{std::move( xpathCtxt.xpathHandler_ )} {}\n auto operator=( const XPathCtxt &rhs ) -> XPathCtxt & {\n if ( this != &rhs ) {\n xpathCtxt_.reset( xmlXPathNewContext( rhs.xpathCtxt_->doc ) );\n xpathHandler_ = rhs.xpathHandler_;\n }\n return *this;\n }\n auto operator=( XPathCtxt &&xpathCtxt ) -> XPathCtxt & {\n xpathCtxt_ = std::move( xpathCtxt.xpathCtxt_ );\n xpathHandler_ = std::move( xpathCtxt.xpathHandler_ );\n return *this;\n }\n explicit operator bool( ) const {\n return ( xpathCtxt_ != nullptr && xpathCtxt_->doc != nullptr );\n }\n friend auto operator>>( const XmlDoc &xml, XPathCtxt &xpathCtxt ) -> XPathCtxt & {\n xpathCtxt.xpathCtxt_.reset( xmlXPathNewContext( xml.xmlDoc_.get( ) ) );\n xpathCtxt.xpathHandler_.registerHandler(\n xpathCtxt.xpathCtxt_.get( ) ); \/\/ ist this correct?\n return xpathCtxt;\n }\n auto errorHandler( ) const -> const IErrorHandler & { return xpathHandler_; }\n\nprivate:\n using XPathCtxtT = std::unique_ptr<xmlXPathContext, FreeXPathCtxt>;\n XPathCtxtT xpathCtxt_;\n XPathErrorHandler xpathHandler_;\n};\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Oilpan: Add a comment to markPointer<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"test\/test_bitcoin.h\"\n\n#include \"policy\/policy.h\"\n#include \"script\/interpreter.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <array>\n\ntypedef std::vector<uint8_t> valtype;\ntypedef std::vector<valtype> stacktype;\n\nBOOST_FIXTURE_TEST_SUITE(checkdatasig_tests, BasicTestingSetup)\n\nstd::array<uint32_t, 3> flagset{\n {0, STANDARD_SCRIPT_VERIFY_FLAGS, MANDATORY_SCRIPT_VERIFY_FLAGS}};\n\n\/**\n * General utility functions to check for script passing\/failing.\n *\/\nstatic void CheckTestResultForAllFlags(const stacktype &original_stack,\n const CScript &script,\n const stacktype &expected) {\n BaseSignatureChecker sigchecker;\n\n for (uint32_t flags : flagset) {\n \/\/ The opcode are not implemented yet, so we get a bad opcode error when\n \/\/ passing the activation flag.\n ScriptError err = SCRIPT_ERR_OK;\n stacktype stack{original_stack};\n bool r = EvalScript(stack, script, flags | SCRIPT_ENABLE_CHECKDATASIG,\n sigchecker, &err);\n BOOST_CHECK(!r);\n BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);\n\n \/\/ Make sure that we get a bad opcode when the activation flag is not\n \/\/ passed.\n stack = original_stack;\n r = EvalScript(stack, script, flags, sigchecker, &err);\n BOOST_CHECK(!r);\n BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);\n }\n}\n\nBOOST_AUTO_TEST_CASE(checkdatasig_test) {\n CheckTestResultForAllFlags({}, CScript() << OP_CHECKDATASIG, {});\n CheckTestResultForAllFlags({}, CScript() << OP_CHECKDATASIGVERIFY, {});\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Check GetOpName(..) for completeness<commit_after>\/\/ Copyright (c) 2018 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"test\/test_bitcoin.h\"\n\n#include \"policy\/policy.h\"\n#include \"script\/interpreter.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <array>\n\ntypedef std::vector<uint8_t> valtype;\ntypedef std::vector<valtype> stacktype;\n\nBOOST_FIXTURE_TEST_SUITE(checkdatasig_tests, BasicTestingSetup)\n\nstd::array<uint32_t, 3> flagset{\n {0, STANDARD_SCRIPT_VERIFY_FLAGS, MANDATORY_SCRIPT_VERIFY_FLAGS}};\n\n\/**\n * General utility functions to check for script passing\/failing.\n *\/\nstatic void CheckTestResultForAllFlags(const stacktype &original_stack,\n const CScript &script,\n const stacktype &expected) {\n BaseSignatureChecker sigchecker;\n\n for (uint32_t flags : flagset) {\n \/\/ The opcode are not implemented yet, so we get a bad opcode error when\n \/\/ passing the activation flag.\n ScriptError err = SCRIPT_ERR_OK;\n stacktype stack{original_stack};\n bool r = EvalScript(stack, script, flags | SCRIPT_ENABLE_CHECKDATASIG,\n sigchecker, &err);\n BOOST_CHECK(!r);\n BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);\n\n \/\/ Make sure that we get a bad opcode when the activation flag is not\n \/\/ passed.\n stack = original_stack;\n r = EvalScript(stack, script, flags, sigchecker, &err);\n BOOST_CHECK(!r);\n BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);\n }\n}\n\nBOOST_AUTO_TEST_CASE(checkdatasig_test) {\n CheckTestResultForAllFlags({}, CScript() << OP_CHECKDATASIG, {});\n CheckTestResultForAllFlags({}, CScript() << OP_CHECKDATASIGVERIFY, {});\n}\n\nBOOST_AUTO_TEST_CASE(checkdatasig_opcode_formatting) {\n BOOST_CHECK_EQUAL(GetOpName(OP_CHECKDATASIG), \"OP_CHECKDATASIG\");\n BOOST_CHECK_EQUAL(GetOpName(OP_CHECKDATASIGVERIFY), \"OP_CHECKDATASIGVERIFY\");\n}\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file contains sample wrappers showing Android Java Developers\n * who are not familiar with the NDK or JNI how to get data in and out of the\n * CPP and how to incorporate the sample code in\n * http:\/\/leveldb.googlecode.com\/svn\/trunk\/doc\/index.html into their JNI\n *\/\n#include <string.h>\n#include <jni.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <android\/log.h>\n\n#include \"leveldb\/db.h\"\n\n#define LOG_TAG \"AndroidLevelDB\"\n#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)\n#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)\n\n\nleveldb::DB* db;\n\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbGet(JNIEnv * env, jobject thiz, jstring key1);\n};\n\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbGet(JNIEnv * env, jobject thiz, jstring key1)\n{\n\n\tLOGI(\"In the get \");\n\n\tconst char* key = env->GetStringUTFChars(key1,0);\n\tLOGI(\"Key\");\n\tLOGI(key);\n\n\tstd::string value;\n\tleveldb::Status status = db->Get(leveldb::ReadOptions(), key, &value);\n\n\n\tif (status.ok()) {\n\t\tconst char* re = value.c_str();\n\t\treturn env->NewStringUTF(re);\n\t}else{\n\t\tconst char* re = status.ToString().c_str();\n\t\treturn env->NewStringUTF(re);\n\t}\n\n}\n\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbPut(JNIEnv * env, jobject thiz, jstring key1, jstring value1);\n};\n\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbPut(JNIEnv * env, jobject thiz, jstring key1, jstring value1)\n{\n\tLOGI(\"In the put \");\n\n\tconst char* key = env->GetStringUTFChars(key1,0);\n\tconst char* value = env->GetStringUTFChars(value1,0);\n\tLOGI(\"Key\");\n\tLOGI(key);\n\tLOGI(\"Value\");\n\tLOGI(value);\n\n\tleveldb::Status status = db->Put(leveldb::WriteOptions(), key, value);\n\tif (status.ok()) {\n\t\tconst char* re = status.ToString().c_str();\n\t\treturn env->NewStringUTF(value);\n\t}else{\n\t\tconst char* re = status.ToString().c_str();\n\t\treturn env->NewStringUTF(re);\n\t}\n\n}\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbOpen(JNIEnv* env, jobject thiz, jstring dbpath);\n\n\n};\n\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbOpen(JNIEnv* env, jobject thiz, jstring dbpath)\n{\n\tconst char* path = env->GetStringUTFChars(dbpath,0);\n\tLOGI(\"Opening database\");\n\tLOGI(path);\n\n\tleveldb::Options options;\n\toptions.create_if_missing = true;\n\tleveldb::Status status = leveldb::DB::Open(options, path, &db);\n\tconst char* re = status.ToString().c_str();\n\treturn env->NewStringUTF(re);\n}\n\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbClose(JNIEnv* env, jobject thiz, jstring dbpath);\n\n\n};\n\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbClose(JNIEnv* env, jobject thiz, jstring dbpath)\n{\n\tdelete db;\n\tLOGI(\"Closed database\");\n\treturn env->NewStringUTF(\"Closed database\");\n}\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbDelete(JNIEnv * env, jobject thiz, jstring key1);\n};\n\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_dbDelete(JNIEnv * env, jobject thiz, jstring key1)\n{\n\n\tLOGI(\"In the delete \");\n\n\tconst char* key = env->GetStringUTFChars(key1,0);\n\tLOGI(\"Key\");\n\tLOGI(key);\n\n\tleveldb::Status status = db->Delete(leveldb::WriteOptions(), key);\n\n\n\tif (status.ok()) {\n\t\tconst char* re = status.ToString().c_str();\n\t\treturn env->NewStringUTF(re);\n\t}else{\n\t\tconst char* re = status.ToString().c_str();\n\t\treturn env->NewStringUTF(re);\n\t}\n\n}\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_GetProperty(JNIEnv * env, jobject thiz);\n};\n\nJNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_GetProperty(JNIEnv * env, jobject thiz)\n{\n\treturn env->NewStringUTF(\"calling get property to find out db size etc\");\n}\n<commit_msg>adding safetly checking and changing class names to the leveldb google code namespace<commit_after>\/*\n * This file contains sample wrappers showing Android Java Developers\n * who are not familiar with the NDK or JNI how to get data in and out of the\n * CPP and how to incorporate the sample code in\n * http:\/\/leveldb.googlecode.com\/svn\/trunk\/doc\/index.html into their JNI\n *\/\n#include <string.h>\n#include <jni.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <android\/log.h>\n\n#include \"leveldb\/db.h\"\n\n#define LOG_TAG \"AndroidLevelDB\"\n#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)\n#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)\n\n\nleveldb::DB* db;\nbool isDBopen;\nchar* databasePath;\n\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbGet(JNIEnv * env, jobject thiz, jstring key1);\n};\n\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbGet(JNIEnv * env, jobject thiz, jstring key1)\n{\n\t\/\/LOGI(\"In the get \");\n\tif(! isDBopen){\n\t\tLOGE(\"Trying to get when DB wasn't open\");\n\/\/\t\tLOGI(\"Opening database\");\n\n\t\tleveldb::Options options;\n\t\toptions.create_if_missing = true;\n\t\tleveldb::Status status = leveldb::DB::Open(options, databasePath, &db);\n\t\tif (status.ok()) {\n\t\t\tLOGI(\"Opened database\");\n\t\t\tisDBopen = true;\n\t\t}else{\n\t\t\tLOGE(\"Failed to open database\");\n\t\t\tisDBopen = false;\n\t\t\tdatabasePath = const_cast<char*>(\"\");\n\t\t\treturn env->NewStringUTF(\"NotFound\");\n\t\t}\n\t}\n\tconst char* key = env->GetStringUTFChars(key1,0);\n\t\/\/LOGI(\"Key\");\n\/\/\tLOGI(key);\n\n\tstd::string value;\n\tleveldb::Status status = db->Get(leveldb::ReadOptions(), key, &value);\n\n\n\tif (status.ok()) {\n\t\tconst char* re = value.c_str();\n\/\/\t\tLOGI(re);\n\t\treturn env->NewStringUTF(re);\n\t}else{\n\t\tconst char* re = status.ToString().c_str();\n\/\/\t\tLOGI(re);\n\t\treturn env->NewStringUTF(\"NotFound\");\n\t}\n\n}\n\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbPut(JNIEnv * env, jobject thiz, jstring key1, jstring value1);\n};\n\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbPut(JNIEnv * env, jobject thiz, jstring key1, jstring value1)\n{\n\tif(! isDBopen){\n\t\tLOGE(\"Trying to put when DB wasn't open\");\n\/\/\t\tLOGI(\"Opening database\");\n\t\tleveldb::Options options;\n\t\toptions.create_if_missing = true;\n\t\tleveldb::Status status = leveldb::DB::Open(options, databasePath, &db);\n\t\tif (status.ok()) {\n\t\t\tLOGI(\"Opened database\");\n\t\t\tisDBopen = true;\n\t\t}else{\n\t\t\tLOGE(\"Failed to open database\");\n\t\t\tisDBopen = false;\n\t\t\tdatabasePath = const_cast<char*>(\"\");\n\t\t\treturn env->NewStringUTF(\"NotFound\");\n\t\t}\n\t}\n\/\/\tLOGI(\"In the put \");\n\n\tconst char* key = env->GetStringUTFChars(key1,0);\n\tconst char* value = env->GetStringUTFChars(value1,0);\n\t\/\/LOGI(\"Key\");\n\/\/\tLOGI(key);\n\t\/\/LOGI(\"Value\");\n\/\/\tLOGI(value);\n\n\tleveldb::Status status = db->Put(leveldb::WriteOptions(), key, value);\n\tif (status.ok()) {\n\t\tconst char* re = status.ToString().c_str();\n\/\/\t\tLOGI(re);\n\t\treturn env->NewStringUTF(value);\n\t}else{\n\t\tconst char* re = status.ToString().c_str();\n\t\treturn env->NewStringUTF(\"NotFound\");\n\t}\n\n}\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbOpen(JNIEnv* env, jobject thiz, jstring dbpath);\n};\n\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbOpen(JNIEnv* env, jobject thiz, jstring dbpath)\n{\n\tif(isDBopen){\n\t\tLOGI(\"DB was already open\");\n\t\treturn env->NewStringUTF(\"DB was already open\");\n\t}\n\tconst char* path = env->GetStringUTFChars(dbpath,0);\n\/\/\tLOGI(\"Opening database\");\n\n\tleveldb::Options options;\n\toptions.create_if_missing = true;\n\tleveldb::Status status = leveldb::DB::Open(options, path, &db);\n\tif (status.ok()) {\n\t\tLOGI(path);\n\t\tLOGI(\"Opened database\");\n\t\tisDBopen = true;\n\t\tdatabasePath = const_cast<char*>(path);\n\t}else{\n\t\tLOGE(\"Failed to open database\");\n\t\tisDBopen = false;\n\t\tdatabasePath = const_cast<char*>(\"\");\n\t}\n\tconst char* re = status.ToString().c_str();\n\treturn env->NewStringUTF(re);\n}\n\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbClose(JNIEnv* env, jobject thiz, jstring dbpath);\n\n};\n\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbClose(JNIEnv* env, jobject thiz, jstring dbpath)\n{\n\tif(isDBopen){\n\t\tdelete db;\n\t\tisDBopen = false;\n\t\tLOGI(\"Closed database\");\n\t}else{\n\t\tLOGI(\"DB was already closed.\");\n\t}\n\treturn env->NewStringUTF(\"Closed database\");\n}\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbDestroy(JNIEnv* env, jobject thiz, jstring dbpath);\n\n};\n\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbDestroy(JNIEnv* env, jobject thiz, jstring dbpath)\n{\n\tif(isDBopen){\n\t\tdelete db;\n\t}\n\tconst char* path = env->GetStringUTFChars(dbpath,0);\n\tleveldb::Options options;\n\toptions.create_if_missing = true;\n\tleveldb::Status status = DestroyDB(path, options);\n\tLOGI(\"Destroyed (ie, cleared) database\");\n\n\t\/*re-open database *\/\n\tstatus = leveldb::DB::Open(options, path, &db);\n\tif (status.ok()) {\n\t\tLOGI(path);\n\t\tLOGI(\"Opened database\");\n\t\tisDBopen = true;\n\t\tdatabasePath = const_cast<char*>(path);\n\t}else{\n\t\tLOGE(\"Failed to open database\");\n\t\tisDBopen = false;\n\t\tdatabasePath = const_cast<char*>(\"\");\n\t}\n\treturn env->NewStringUTF(\"Destroyed (ie, cleared) database\");\n}\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbDelete(JNIEnv * env, jobject thiz, jstring key1);\n};\n\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbDelete(JNIEnv * env, jobject thiz, jstring key1)\n{\n\tif(! isDBopen){\n\t\tLOGE(\"Trying to delete when DB wasn't open\");\n\/\/\t\tLOGI(\"Opening database\");\n\t\tleveldb::Options options;\n\t\toptions.create_if_missing = true;\n\t\tleveldb::Status status = leveldb::DB::Open(options, databasePath, &db);\n\t\tif (status.ok()) {\n\t\t\tLOGI(\"Opened database\");\n\t\t\tisDBopen = true;\n\t\t}else{\n\t\t\tLOGE(\"Failed to open database\");\n\t\t\tisDBopen = false;\n\t\t\tdatabasePath = const_cast<char*>(\"\");\n\t\t\treturn env->NewStringUTF(\"NotFound\");\n\t\t}\n\t}\n\tLOGI(\"In the delete \");\n\n\tconst char* key = env->GetStringUTFChars(key1,0);\n\t\/\/LOGI(\"Key\");\n\/\/\tLOGI(key);\n\n\tleveldb::Status status = db->Delete(leveldb::WriteOptions(), key);\n\tif (status.ok()) {\n\t\tconst char* re = status.ToString().c_str();\n\t\treturn env->NewStringUTF(re);\n\t}else{\n\t\tconst char* re = status.ToString().c_str();\n\t\treturn env->NewStringUTF(\"NotFound\");\n\t}\n\n}\nextern \"C\" {\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_GetProperty(JNIEnv * env, jobject thiz);\n};\n\nJNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_GetProperty(JNIEnv * env, jobject thiz)\n{\n\treturn env->NewStringUTF(\"calling get property to find out db size etc\");\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Criando estruturas de dados<commit_after>#include <iostream>\n#include <string>\n\nusing namespace std;\n\ntypedef struct {\n String nome;\n String cpf;\n float saldo;\n} Conta;\n\nint main() {\n Conta conta;\n\n init_conta( conta );\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 Matt Hill\n\/\/ Use of this source code is governed by The MIT License\n\/\/ that can be found in the LICENSE file.\n\n#include \"DisplayUpdater.h\"\n#include \"RgbMatrix.h\"\n#include \"RgbMatrixContainer.h\"\n#include \"Thread.h\"\n\n#include <cstdlib>\n#include <stdio.h>\n#include <unistd.h>\n\n\n\/\/ Below are several classes that demo the capabilities of the RgbMatrix class.\n\n\n\/\/ Demo of the capabilities of the RgbMatrix class\nclass RgbMatrixDrawShapes1 : public RgbMatrixContainer\n{\npublic:\n RgbMatrixDrawShapes1(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n Color red;\n red.red = 135;\n\n Color green;\n green.green = 135;\n\n Color blue;\n blue.blue = 80;\n\n _matrix->setTextCursor(1, 19);\n _matrix->setFontSize(2);\n _matrix->setFontColor(green);\n _matrix->writeLetter('S');\n _matrix->writeLetter('i');\n _matrix->writeLetter('m');\n _matrix->writeLetter('p');\n _matrix->writeLetter('l');\n _matrix->writeLetter('e');\n\n _matrix->setTextCursor(1, 26);\n _matrix->setFontColor(blue);\n _matrix->writeLetter('S');\n _matrix->writeLetter('h');\n _matrix->writeLetter('a');\n _matrix->writeLetter('p');\n _matrix->writeLetter('e');\n _matrix->writeLetter('s');\n\n _matrix->drawRect(1, 1, 6, 6, blue);\n\n _matrix->drawCircle(10, 7, 3, red);\n\n _matrix->drawTriangle(25, 1, 31, 8, 20, 8, green);\n }\n\n};\n\n\n\/\/ Demo of the capabilities of the RgbMatrix class\nclass RgbMatrixDrawShapes2 : public RgbMatrixContainer\n{\npublic:\n RgbMatrixDrawShapes2(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n Color b1;\n b1.blue = 155;\n\n Color b2;\n b2.green = 17;\n b2.blue = 205;\n\n Color b3;\n b3.green = 17;\n b3.blue = 224;\n\n Color b4;\n b4.green = 17;\n b4.blue = 234;\n\n Color b5;\n b5.blue = 255;\n \n _matrix->drawRect(0, 0, 1, 32, b1);\n _matrix->drawRect(9, 15, 1, 17, b2);\n _matrix->drawRect(10, 15, 1, 17, b3);\n _matrix->drawRect(11, 15, 1, 17, b4);\n _matrix->drawRect(12, 15, 1, 17, b5);\n _matrix->drawRect(13, 15, 1, 17, b1);\n _matrix->drawRect(14, 15, 1, 17, b2);\n _matrix->drawRect(15, 15, 1, 17, b3);\n _matrix->drawRect(16, 15, 1, 17, b4);\n _matrix->drawRect(17, 15, 1, 17, b5);\n }\n\n};\n\n\n\n\/\/ Cycle through colors, and pulse the entire matrix the same color.\nclass RgbMatrixPulsePixels : public RgbMatrixContainer\n{\npublic:\n RgbMatrixPulsePixels(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n uint32_t count = 0;\n \n while (!isDone())\n {\n count++;\n\n int color = (count >> 9) % 7;\n int value = count & 0xFF;\n\n if (count & 0x100) value = 255 - value;\n\n int r, g, b;\n\n switch (color)\n {\n case 0: r = value; g = b = 0; break;\n case 1: g = value; r = b = 0; break;\n case 2: b = value; r = g = 0; break;\n case 3: r = g = value; b = 0; break;\n case 4: r = b = value; g = 0; break;\n case 5: g = b = value; r = 0; break;\n default: r = g = b = value; break;\n }\n\n Color pulse;\n pulse.red = r;\n pulse.green = g;\n pulse.blue = b;\n\n _matrix->fillScreen(pulse);\n\n usleep(5000);\n }\n }\n\n};\n\n\n\n\/\/ Demo of the capabilities of the RgbMatrix class\nclass RgbMatrixPulsePixelsGradient : public RgbMatrixContainer\n{\npublic:\n RgbMatrixPulsePixelsGradient(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n uint32_t count = 0;\n\n Color fish;\n fish.red = 255;\n\n _matrix->drawPixel(0, 0, fish);\n \n while (!isDone())\n {\n count++;\n\n int color = (count >> 9) % 7; \/\/512 steps for each color (256 up \/ 256 down)\n int value = count & 0xFF;\n\n if (count & 0x100) value = 255 - value; \/\/ pulse down\n\n int r, g, b;\n\n switch (color)\n {\n case 0: r = value; g = b = 0; break;\n case 1: g = value; r = b = 0; break;\n case 2: b = value; r = g = 0; break;\n case 3: r = g = value; b = 0; break;\n case 4: r = b = value; g = 0; break;\n case 5: g = b = value; r = 0; break;\n default: r = g = b = value; break;\n }\n\n for (int i=0; i < 32; i++)\n {\n Color iColor;\n iColor.red = (((i+1) * 8) > r) ? r : 0;\n iColor.green = (((i+1) * 8) > g) ? g : 0;\n iColor.blue = (((i+1) * 8) > b) ? b : 0;\n\n \/\/int numero = rand() % 32;\n \/\/_matrix->drawRect(i, numero, 1, 31 - numero, iColor);\n\n _matrix->drawRect(0, i, 32, 1, iColor);\n }\n\n usleep(2500);\n }\n }\n\n};\n\n\n\n\/\/ Draw a color wheel on the matrix. \nclass RgbMatrixColorWheel : public RgbMatrixContainer\n{\npublic:\n RgbMatrixColorWheel(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n _matrix->drawColorWheel();\n }\n};\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Display a menu and allow choosing different demos.\n\nRgbMatrix *m = NULL;\n\nRgbMatrixContainer *display = NULL;\nRgbMatrixContainer *updater = NULL;\n\n\nvoid displayMenu()\n{\n std::system(\"clear\");\n printf(\" |------------------------------------------------|\\n\");\n printf(\" | Select an option from the menu below: |\\n\");\n printf(\" |------------------------------------------------|\\n\");\n printf(\" | (1) Pulse All Pixels |\\n\");\n printf(\" | (2) Pulse All Pixels with a Gradient |\\n\");\n printf(\" | (3) Demo of Drawing Shapes |\\n\");\n printf(\" | (4) Another Demo of Drawing Shapes |\\n\");\n printf(\" | (5) Draw a Color Wheel |\\n\");\n printf(\" | (6) Quit |\\n\");\n printf(\" |------------------------------------------------|\\n\");\n printf(\" Your Choice: \");\n}\n\n\nvoid runDemo()\n{\n updater->start(10);\n display->start();\n\n printf(\"Press <RETURN> when done viewing demo.\\n\");\n getchar();\n\n delete display;\n delete updater;\n\n display = NULL;\n updater = NULL;\n\n m->clearDisplay();\n m->updateDisplay();\n}\n\n\n\nint main(int argc, char *argv[])\n{\n GpioProxy io;\n\n if (!io.initialize())\n return 1;\n\n m = new RgbMatrix(&io);\n\n char choice = '1';\n\n while (choice != '6' && choice != 'q' && choice != 'Q')\n {\n displayMenu();\n\n choice = getchar();\n getchar(); \/\/consume the \\n\n\n switch (choice)\n {\n case '1':\n display = new RgbMatrixPulsePixels(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #1.\\n\\n\");\n runDemo();\n break;\n\n case '2':\n display = new RgbMatrixPulsePixelsGradient(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #2.\\n\\n\");\n runDemo();\n break;\n\n case '3':\n display = new RgbMatrixDrawShapes1(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #3.\\n\\n\");\n runDemo();\n break;\n\n case '4':\n display = new RgbMatrixDrawShapes2(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #4.\\n\\n\");\n runDemo(); \n break;\n\n case '5':\n display = new RgbMatrixColorWheel(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #5.\\n\\n\");\n runDemo();\n break;\n\n case '6':\n printf(\"\\n\\nHave a nice day!\\n\\n\");\n break;\n\n default:\n break;\n }\n }\n\n \/\/ Stop threads and wait for them to join.\n if (display) delete display;\n if (updater) delete updater;\n\n \/\/ Clear and refresh the display.\n m->clearDisplay();\n m->updateDisplay();\n\n delete m;\n\n return 0;\n}\n\n<commit_msg>Add demo of drawing shapes.<commit_after>\/\/ Copyright (c) 2013 Matt Hill\n\/\/ Use of this source code is governed by The MIT License\n\/\/ that can be found in the LICENSE file.\n\n#include \"DisplayUpdater.h\"\n#include \"RgbMatrix.h\"\n#include \"RgbMatrixContainer.h\"\n#include \"Thread.h\"\n\n#include <cstdlib>\n#include <stdio.h>\n#include <unistd.h>\n\n\n\/\/ Below are several classes that demo the capabilities of the RgbMatrix class.\n\n\n\/\/ Draw some shapes on the RGB Matrix. \nclass RgbMatrixDrawShapes1 : public RgbMatrixContainer\n{\npublic:\n RgbMatrixDrawShapes1(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n Color red;\n red.red = 255;\n\n Color green;\n green.green = 255;\n\n Color blue;\n blue.blue = 255;\n\n Color purple;\n purple.red = 135;\n purple.blue = 255;\n\n Color yellow;\n yellow.red = 255;\n yellow.green = 255;\n\n Color turquoise;\n turquoise.green = 255;\n turquoise.blue = 255;\n\n \/\/ Draw some shapes\n _matrix->drawRect(1, 1, 8, 8, blue);\n\n _matrix->drawCircle(14, 5, 4, red);\n\n _matrix->drawTriangle(25, 1, 30, 8, 20, 8, green);\n\n _matrix->drawRect(1, 11, 9, 6, purple);\n\n _matrix->drawRoundRect(11, 11, 10, 6, 2, yellow);\n\n _matrix->drawWedge(30, 18, 8, 190, 270, turquoise);\n\n \/\/ Write some text\n _matrix->setTextCursor(1, 19);\n _matrix->setFontSize(2); \/\/ Medium (4x6) Font\n _matrix->setFontColor(green);\n _matrix->writeLetter('S');\n _matrix->writeLetter('i');\n _matrix->writeLetter('m');\n _matrix->writeLetter('p');\n _matrix->writeLetter('l');\n _matrix->writeLetter('e');\n\n _matrix->setTextCursor(1, 26);\n _matrix->setFontColor(blue);\n _matrix->writeLetter('S');\n _matrix->writeLetter('h');\n _matrix->writeLetter('a');\n _matrix->writeLetter('p');\n _matrix->writeLetter('e');\n _matrix->writeLetter('s');\n }\n\n};\n\n\n\/\/ Draw and fill some shapes on the RGB Matrix.\nclass RgbMatrixDrawShapes2 : public RgbMatrixContainer\n{\npublic:\n RgbMatrixDrawShapes2(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n Color red;\n red.red = 255;\n\n Color green;\n green.green = 255;\n\n Color blue;\n blue.blue = 255;\n\n Color purple;\n purple.red = 135;\n purple.blue = 255;\n\n Color yellow;\n yellow.red = 255;\n yellow.green = 255;\n\n Color turquoise;\n turquoise.green = 255;\n turquoise.blue = 255;\n\n Color white;\n white.red = 255;\n white.green = 255;\n white.blue = 255;\n\n \/\/ Draw some shapes\n _matrix->drawRect(1, 1, 8, 8, blue);\n _matrix->fillRect(2, 2, 6, 6, red);\n\n _matrix->drawCircle(14, 5, 4, red);\n _matrix->fillCircle(14, 5, 3, blue);\n\n _matrix->drawTriangle(25, 1, 30, 8, 20, 8, green);\n _matrix->fillTriangle(25, 2, 29, 7, 21, 7, yellow);\n\n _matrix->fillRect(1, 11, 9, 6, purple);\n\n _matrix->drawRoundRect(11, 11, 10, 6, 2, yellow);\n _matrix->fillRoundRect(12, 12, 8, 4, 0, white);\n\n _matrix->fillCircleHalf(26, 14, 4, 1, 0, turquoise);\n _matrix->fillCircleHalf(26, 14, 4, 2, 0, purple);\n\n \/\/ Write some text\n _matrix->setTextCursor(1, 19);\n _matrix->setFontSize(2); \/\/ Medium (4x6) Font\n _matrix->setFontColor(green);\n _matrix->writeLetter('F');\n _matrix->writeLetter('i');\n _matrix->writeLetter('l');\n _matrix->writeLetter('l');\n _matrix->writeLetter('e');\n _matrix->writeLetter('d');\n\n _matrix->setTextCursor(1, 26);\n _matrix->setFontColor(blue);\n _matrix->writeLetter('S');\n _matrix->writeLetter('h');\n _matrix->writeLetter('a');\n _matrix->writeLetter('p');\n _matrix->writeLetter('e');\n _matrix->writeLetter('s');\n }\n\n};\n\n\n\/\/ Cycle through colors and pulse the entire matrix the same color.\nclass RgbMatrixPulsePixels : public RgbMatrixContainer\n{\npublic:\n RgbMatrixPulsePixels(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n uint32_t count = 0;\n \n while (!isDone())\n {\n count++;\n\n int color = (count >> 9) % 7;\n int value = count & 0xFF;\n\n if (count & 0x100) value = 255 - value;\n\n int r, g, b;\n\n switch (color)\n {\n case 0: r = value; g = b = 0; break;\n case 1: g = value; r = b = 0; break;\n case 2: b = value; r = g = 0; break;\n case 3: r = g = value; b = 0; break;\n case 4: r = b = value; g = 0; break;\n case 5: g = b = value; r = 0; break;\n default: r = g = b = value; break;\n }\n\n Color pulse;\n pulse.red = r;\n pulse.green = g;\n pulse.blue = b;\n\n _matrix->fillScreen(pulse);\n\n usleep(5000);\n }\n }\n\n};\n\n\n\/\/ Cycle through colors and pulse the matrix in a gradient pattern.\nclass RgbMatrixPulsePixelsGradient : public RgbMatrixContainer\n{\npublic:\n RgbMatrixPulsePixelsGradient(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n uint32_t count = 0;\n\n while (!isDone())\n {\n count++;\n\n int color = (count >> 9) % 7; \/\/512 steps for each color (256 up \/ 256 down)\n int value = count & 0xFF;\n\n if (count & 0x100) value = 255 - value; \/\/ pulse down\n\n int r, g, b;\n\n switch (color)\n {\n case 0: r = value; g = b = 0; break;\n case 1: g = value; r = b = 0; break;\n case 2: b = value; r = g = 0; break;\n case 3: r = g = value; b = 0; break;\n case 4: r = b = value; g = 0; break;\n case 5: g = b = value; r = 0; break;\n default: r = g = b = value; break;\n }\n\n for (int i=0; i < 32; i++)\n {\n Color iColor;\n iColor.red = (((i+1) * 8) > r) ? r : 0;\n iColor.green = (((i+1) * 8) > g) ? g : 0;\n iColor.blue = (((i+1) * 8) > b) ? b : 0;\n\n _matrix->drawRect(0, i, 32, 1, iColor);\n }\n\n usleep(2500);\n }\n }\n\n};\n\n\n\/\/ Draw a color wheel on the matrix. \nclass RgbMatrixColorWheel : public RgbMatrixContainer\n{\npublic:\n RgbMatrixColorWheel(RgbMatrix *m) : RgbMatrixContainer(m) {}\n\n void run()\n {\n _matrix->drawColorWheel();\n }\n};\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Display a menu and allow choosing different demos.\n\nRgbMatrix *m = NULL;\n\nRgbMatrixContainer *display = NULL;\nRgbMatrixContainer *updater = NULL;\n\n\nvoid displayMenu()\n{\n std::system(\"clear\");\n printf(\" |------------------------------------------------|\\n\");\n printf(\" | Select an option from the menu below: |\\n\");\n printf(\" |------------------------------------------------|\\n\");\n printf(\" | (1) Draw Simple Shapes |\\n\");\n printf(\" | (2) Draw and Fill Shapes |\\n\");\n printf(\" | (3) Pulse All Pixels |\\n\");\n printf(\" | (4) Pulse Pixels with a Gradient |\\n\");\n printf(\" | (5) Draw a Color Wheel |\\n\");\n printf(\" | (6) Quit |\\n\");\n printf(\" |------------------------------------------------|\\n\");\n printf(\" Your Choice: \");\n}\n\n\nvoid runDemo()\n{\n updater->start(10);\n display->start();\n\n printf(\"Press <RETURN> when done viewing demo.\\n\");\n getchar();\n\n delete display;\n delete updater;\n\n display = NULL;\n updater = NULL;\n\n m->clearDisplay();\n m->updateDisplay();\n}\n\n\nint main(int argc, char *argv[])\n{\n GpioProxy io;\n\n if (!io.initialize())\n return 1;\n\n m = new RgbMatrix(&io);\n\n char choice = '1';\n\n while (choice != '6' && choice != 'q' && choice != 'Q')\n {\n displayMenu();\n\n choice = getchar();\n getchar(); \/\/consume the \\n\n\n switch (choice)\n {\n case '1':\n display = new RgbMatrixDrawShapes1(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #1.\\n\\n\");\n runDemo();\n break;\n\n case '2':\n display = new RgbMatrixDrawShapes2(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #2.\\n\\n\");\n runDemo();\n break;\n\n case '3':\n display = new RgbMatrixPulsePixels(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #3.\\n\\n\");\n runDemo();\n break;\n\n case '4':\n display = new RgbMatrixPulsePixelsGradient(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #4.\\n\\n\");\n runDemo(); \n break;\n\n case '5':\n display = new RgbMatrixColorWheel(m);\n updater = new DisplayUpdater(m);\n printf(\"\\n\\nRunning Demo #5.\\n\\n\");\n runDemo();\n break;\n\n case '6':\n case 'q':\n case 'Q':\n printf(\"\\n\\nHave a nice day!\\n\\n\");\n break;\n\n default:\n break;\n }\n }\n\n \/\/ Stop threads and wait for them to join.\n if (display) delete display;\n if (updater) delete updater;\n\n \/\/ Clear and refresh the display.\n m->clearDisplay();\n m->updateDisplay();\n\n delete m;\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * appctorsdtors.cpp\n *\n * Created on: 30 janv. 2013\n * Author: fsulima\n *\/\n\n#include <stdio.h>\n\nclass CtorDtorExample {\nprotected:\n\tint field1;\npublic:\n\tCtorDtorExample(int i) : field1(i) {\n\t\tprintf(\"CtorDtorExample %p,%x constructor.\\n\", this, field1);\n\t}\n\t~CtorDtorExample() {\n\t\tprintf(\"CtorDtorExample %p,%x destructor.\\n\", this, field1);\n\t}\n};\n\nstatic CtorDtorExample obj1(1);\n\nint main (int argc, char **argv) {\n\tstatic CtorDtorExample obj2(2);\n\tprintf(\"CtorDtorExample main\\n\");\n}\n<commit_msg>tests: cxx: Remove appctordtor example<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ tbMgr.cc\n\/\/-----------------------------------------------------------------------------\n#include \"Pre.h\"\n#include \"tbMgr.h\"\n#include \"Core\/Core.h\"\n#include \"Core\/RunLoop.h\"\n#include \"IO\/Core\/URLBuilder.h\"\n#include \"Gfx\/Gfx.h\"\n#include \"Input\/Input.h\"\n#include \"animation\/tb_widget_animation.h\"\n#include \"tb_font_renderer.h\"\n\nvoid register_tbbf_font_renderer();\n\nusing namespace tb;\n\nnamespace Oryol {\nnamespace _priv {\n\n\/\/-----------------------------------------------------------------------------\ntbMgr::~tbMgr() {\n o_assert(!this->IsValid());\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::Setup(const TBUISetup& setup) {\n o_assert_dbg(!this->IsValid());\n o_assert_dbg(setup.DefaultSkin.IsValid());\n o_assert_dbg(!setup.Fonts.Empty());\n o_assert_dbg(setup.DefaultFontName.IsValid());\n \n \/\/ initialize turbobadger\n this->renderer = Memory::New<tbOryolBatchRenderer>();\n this->renderer->Setup();\n\ttb_core_init(this->renderer, setup.Locale.AsCStr());\n \n \/\/ initialize turbobadger skin\n if (!g_tb_skin->Load(setup.DefaultSkin.AsCStr(), setup.OverrideSkin.AsCStr())) {\n o_error(\"tbMgr::Setup(): Failed to load skins!\");\n }\n \n \/\/ use turbobadger's built-in font renderer\n register_tbbf_font_renderer();\n \n \/\/ setup fonts\n for (const auto& font : setup.Fonts) {\n g_font_manager->AddFontInfo(font.Location.AsCStr(), font.Name.AsCStr());\n }\n TBFontDescription fontDesc;\n fontDesc.SetID(TBIDC(setup.DefaultFontName.AsCStr()));\n fontDesc.SetSize(g_tb_skin->GetDimensionConverter()->DpToPx(setup.DefaultFontSize));\n g_font_manager->SetDefaultFontDescription(fontDesc);\n TBFontFace* font = g_font_manager->CreateFontFace(g_font_manager->GetDefaultFontDescription());\n if (font) {\n font->RenderGlyphs(setup.GlyphSet.AsCStr());\n }\n\n \/\/ input event handlers\n Input::SubscribeMouse([this](const Mouse::Event& e) {\n switch (e.Type) {\n case Mouse::Event::Move:\n this->onMouseMove((int)e.Position.x, (int)e.Position.y);\n break;\n case Mouse::Event::ButtonDown:\n this->onMouseButton(e.Button, true);\n break;\n case Mouse::Event::ButtonUp:\n this->onMouseButton(e.Button, false);\n break;\n case Mouse::Event::Scroll:\n this->onScroll((int)e.ScrollMovement.x, (int)e.ScrollMovement.y);\n break;\n default:\n break;\n }\n });\n Input::SubscribeKeyboard([this](const Keyboard::Event& e) {\n switch (e.Type) {\n case Keyboard::Event::KeyDown:\n case Keyboard::Event::KeyRepeat:\n this->onKey(e.KeyCode, true, false);\n break;\n case Keyboard::Event::KeyUp:\n this->onKey(e.KeyCode, false, true);\n break;\n case Keyboard::Event::WChar:\n this->onWChar(e.WCharCode);\n break;\n default:\n break;\n }\n });\n Input::SubscribeTouchpad([this](const Touchpad::Event& e) {\n switch (e.Type) {\n case Touchpad::Event::Tapped:\n this->onTapped(e.Position[0]);\n break;\n case Touchpad::Event::PanningStarted:\n this->onPanningStarted(e.StartPosition[0]);\n break;\n case Touchpad::Event::Panning:\n this->onPanning(e.Position[0]);\n break;\n case Touchpad::Event::PanningEnded:\n this->onPanningEnded(e.Position[0]);\n break;\n default:\n break;\n }\n });\n\n \/\/ add per-frame update method\n Core::PostRunLoop()->Add([this] {\n this->update();\n });\n \n TBWidgetsAnimationManager::Init();\n \n this->isValid = true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::Discard() {\n o_assert_dbg(this->IsValid());\n \n TBWidgetsAnimationManager::Shutdown();\n\n tb_core_shutdown();\n\n this->renderer->Discard();\n Memory::Delete(this->renderer);\n \n this->isValid = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool\ntbMgr::IsValid() const {\n return this->isValid;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::update() {\n this->rootWidget.InvokeProcessStates();\n this->rootWidget.InvokeProcess();\n\n \/\/ send a release for each tap\n glm::vec2 pos;\n while (!this->touchTaps.Empty()) {\n this->touchTaps.Dequeue(pos);\n this->rootWidget.InvokePointerUp((int)pos.x, (int)pos.y, this->modifierKeys, true);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::Draw() {\n o_assert_dbg(this->IsValid());\n o_assert_dbg(this->renderer);\n\n const DisplayAttrs& disp = Gfx::RenderTargetAttrs();\n this->rootWidget.SetRect(TBRect(0, 0, disp.FramebufferWidth, disp.FramebufferHeight));\n\n TBAnimationManager::Update();\n\n this->renderer->BeginPaint(disp.FramebufferWidth, disp.FramebufferHeight);\n this->rootWidget.InvokePaint(TBWidget::PaintProps());\n this->renderer->EndPaint();\n\n \/\/ if animations are running, reinvalidate immediately\n if (TBAnimationManager::HasAnimationsRunning()) {\n this->rootWidget.Invalidate();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\ntbOryolRootWidget*\ntbMgr::GetRootWidget() {\n o_assert_dbg(this->IsValid());\n return &this->rootWidget;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onMouseMove(int posX, int posY) {\n this->mouseX = posX;\n this->mouseY = posY;\n this->rootWidget.InvokePointerMove(this->mouseX, this->mouseY, this->modifierKeys, false);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onMouseButton(Mouse::Button btn, bool down) {\n if (btn == Mouse::LMB) {\n if (down) {\n this->rootWidget.InvokePointerDown(this->mouseX, this->mouseY, 1, this->modifierKeys, false);\n }\n else {\n this->rootWidget.InvokePointerUp(this->mouseX, this->mouseY, this->modifierKeys, false);\n }\n }\n else if (btn == Mouse::RMB) {\n this->rootWidget.InvokePointerMove(this->mouseX, this->mouseY, this->modifierKeys, false);\n if (TBWidget::hovered_widget)\n {\n TBWidget::hovered_widget->ConvertFromRoot(this->mouseX, this->mouseY);\n TBWidgetEvent ev(EVENT_TYPE_CONTEXT_MENU, this->mouseX, this->mouseY, false, this->modifierKeys);\n TBWidget::hovered_widget->InvokeEvent(ev);\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onTapped(const glm::vec2& pos) {\n this->touchTaps.Enqueue(pos);\n this->rootWidget.InvokePointerDown((int)pos.x, (int)pos.y, 1, this->modifierKeys, true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onPanningStarted(const glm::vec2& pos) {\n this->rootWidget.InvokePointerDown((int)pos.x, (int)pos.y, 1, this->modifierKeys, true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onPanningEnded(const glm::vec2& pos) {\n this->rootWidget.InvokePointerUp((int)pos.x, (int)pos.y, this->modifierKeys, true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onPanning(const glm::vec2& pos) {\n this->rootWidget.InvokePointerMove((int)pos.x, (int)pos.y, this->modifierKeys, true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onScroll(int wheelX, int wheelY) {\n this->rootWidget.InvokeWheel(this->mouseX, this->mouseY, wheelX, wheelY, this->modifierKeys);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int\ntoupr_ascii(int ascii)\n{\n if (ascii >= 'a' && ascii <= 'z') {\n return ascii + 'A' - 'a';\n }\n return ascii;\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic bool\ninvokeShortcut(int key, SPECIAL_KEY specialKey, MODIFIER_KEYS modifierKeys, bool down) {\n\n #ifdef FIPS_OSX\n bool shortcut_key = (modifierKeys & TB_SUPER) ? true : false;\n #else\n bool shortcut_key = (modifierKeys & TB_CTRL) ? true : false;\n #endif\n if (!TBWidget::focused_widget || !down || !shortcut_key) {\n return false;\n }\n bool reverse_key = (modifierKeys & TB_SHIFT) ? true : false;\n int upper_key = toupr_ascii(key);\n TBID id;\n if (upper_key == 'X') {\n id = TBIDC(\"cut\");\n }\n else if (upper_key == 'C' || specialKey == TB_KEY_INSERT) {\n id = TBIDC(\"copy\");\n }\n else if (upper_key == 'V' || (specialKey == TB_KEY_INSERT && reverse_key)) {\n id = TBIDC(\"paste\");\n }\n else if (upper_key == 'A') {\n id = TBIDC(\"selectall\");\n }\n else if (upper_key == 'Z' || upper_key == 'Y') {\n bool undo = upper_key == 'Z';\n if (reverse_key) {\n undo = !undo;\n }\n id = undo ? TBIDC(\"undo\") : TBIDC(\"redo\");\n }\n else if (upper_key == 'N') {\n id = TBIDC(\"new\");\n }\n else if (upper_key == 'O') {\n id = TBIDC(\"open\");\n }\n else if (upper_key == 'S') {\n id = TBIDC(\"save\");\n }\n else if (upper_key == 'W') {\n id = TBIDC(\"close\");\n }\n else if (specialKey == TB_KEY_PAGE_UP) {\n id = TBIDC(\"prev_doc\");\n }\n else if (specialKey == TB_KEY_PAGE_DOWN) {\n id = TBIDC(\"next_doc\");\n }\n else {\n return false;\n }\n\n TBWidgetEvent ev(EVENT_TYPE_SHORTCUT);\n ev.modifierkeys = modifierKeys;\n ev.ref_id = id;\n return TBWidget::focused_widget->InvokeEvent(ev);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic bool\ninvokeKey(tbOryolRootWidget* rootWidget, unsigned int key, SPECIAL_KEY specialKey, MODIFIER_KEYS modifierKeys, bool down)\n{\n if (invokeShortcut(key, specialKey, modifierKeys, down)) {\n return true;\n }\n rootWidget->InvokeKey(key, specialKey, modifierKeys, down);\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onWChar(wchar_t c) {\n if ((c >= 0xE000) && (c <= 0xF8FF)) {\n return;\n }\n invokeKey(&this->rootWidget, c, TB_KEY_UNDEFINED, this->modifierKeys, true);\n invokeKey(&this->rootWidget, c, TB_KEY_UNDEFINED, this->modifierKeys, false);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onKey(Key::Code key, bool down, bool up) {\n\n SPECIAL_KEY tbKey = TB_KEY_UNDEFINED;\n switch (key)\n {\n case Key::F1: tbKey = TB_KEY_F1; break;\n case Key::F2: tbKey = TB_KEY_F2; break;\n case Key::F3: tbKey = TB_KEY_F3; break;\n case Key::F4: tbKey = TB_KEY_F4; break;\n case Key::F5: tbKey = TB_KEY_F5; break;\n case Key::F6: tbKey = TB_KEY_F6; break;\n case Key::F7: tbKey = TB_KEY_F7; break;\n case Key::F8: tbKey = TB_KEY_F8; break;\n case Key::F9: tbKey = TB_KEY_F9; break;\n case Key::F10: tbKey = TB_KEY_F10; break;\n case Key::F11: tbKey = TB_KEY_F11; break;\n case Key::F12: tbKey = TB_KEY_F12; break;\n case Key::Left: tbKey = TB_KEY_LEFT; break;\n case Key::Up: tbKey = TB_KEY_UP; break;\n case Key::Right: tbKey = TB_KEY_RIGHT; break;\n case Key::Down: tbKey = TB_KEY_DOWN; break;\n case Key::PageUp: tbKey = TB_KEY_PAGE_UP; break;\n case Key::PageDown: tbKey = TB_KEY_PAGE_DOWN; break;\n case Key::Home: tbKey = TB_KEY_HOME; break;\n case Key::End: tbKey = TB_KEY_END; break;\n case Key::Insert: tbKey = TB_KEY_INSERT; break;\n case Key::Tab: tbKey = TB_KEY_TAB; break;\n case Key::Delete: tbKey = TB_KEY_DELETE; break;\n case Key::BackSpace: tbKey = TB_KEY_BACKSPACE; break;\n case Key::Enter:\n case Key::NumEnter:\n tbKey = TB_KEY_ENTER; break;\n case Key::Escape: tbKey = TB_KEY_ESC; break;\n case Key::Menu:\n if (TBWidget::focused_widget && !down) {\n TBWidgetEvent ev(EVENT_TYPE_CONTEXT_MENU);\n ev.modifierkeys = modifierKeys;\n TBWidget::focused_widget->InvokeEvent(ev);\n }\n break;\n case Key::LeftShift:\n case Key::RightShift:\n if (down) {\n this->modifierKeys |= TB_SHIFT;\n }\n else {\n this->modifierKeys &= ~TB_SHIFT;\n }\n break;\n case Key::LeftControl:\n case Key::RightControl:\n if (down) {\n this->modifierKeys |= TB_CTRL;\n }\n else {\n this->modifierKeys &= ~TB_CTRL;\n }\n break;\n case Key::LeftAlt:\n case Key::RightAlt:\n if (down) {\n this->modifierKeys |= TB_ALT;\n }\n else {\n this->modifierKeys &= ~TB_ALT;\n }\n break;\n case Key::LeftSuper:\n case Key::RightSuper:\n if (down) {\n this->modifierKeys |= TB_SUPER;\n }\n else {\n this->modifierKeys &= ~TB_SUPER;\n }\n break;\n default:\n break;\n }\n if (TB_KEY_UNDEFINED != tbKey) {\n invokeKey(&this->rootWidget, 0, tbKey, this->modifierKeys, down);\n }\n}\n\n} \/\/ namespace _priv\n} \/\/ namespace Oryol\n\n\n<commit_msg>Fix Turbobadger module to latest turbobadger API change.<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ tbMgr.cc\n\/\/-----------------------------------------------------------------------------\n#include \"Pre.h\"\n#include \"tbMgr.h\"\n#include \"Core\/Core.h\"\n#include \"Core\/RunLoop.h\"\n#include \"IO\/Core\/URLBuilder.h\"\n#include \"Gfx\/Gfx.h\"\n#include \"Input\/Input.h\"\n#include \"animation\/tb_widget_animation.h\"\n#include \"tb_font_renderer.h\"\n#include \"tb_language.h\"\n\nvoid register_tbbf_font_renderer();\n\nusing namespace tb;\n\nnamespace Oryol {\nnamespace _priv {\n\n\/\/-----------------------------------------------------------------------------\ntbMgr::~tbMgr() {\n o_assert(!this->IsValid());\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::Setup(const TBUISetup& setup) {\n o_assert_dbg(!this->IsValid());\n o_assert_dbg(setup.DefaultSkin.IsValid());\n o_assert_dbg(!setup.Fonts.Empty());\n o_assert_dbg(setup.DefaultFontName.IsValid());\n \n \/\/ initialize turbobadger\n this->renderer = Memory::New<tbOryolBatchRenderer>();\n this->renderer->Setup();\n tb_core_init(this->renderer);\n g_tb_lng->Load(setup.Locale.AsCStr());\n \n \/\/ initialize turbobadger skin\n if (!g_tb_skin->Load(setup.DefaultSkin.AsCStr(), setup.OverrideSkin.AsCStr())) {\n o_error(\"tbMgr::Setup(): Failed to load skins!\");\n }\n \n \/\/ use turbobadger's built-in font renderer\n register_tbbf_font_renderer();\n \n \/\/ setup fonts\n for (const auto& font : setup.Fonts) {\n g_font_manager->AddFontInfo(font.Location.AsCStr(), font.Name.AsCStr());\n }\n TBFontDescription fontDesc;\n fontDesc.SetID(TBIDC(setup.DefaultFontName.AsCStr()));\n fontDesc.SetSize(g_tb_skin->GetDimensionConverter()->DpToPx(setup.DefaultFontSize));\n g_font_manager->SetDefaultFontDescription(fontDesc);\n TBFontFace* font = g_font_manager->CreateFontFace(g_font_manager->GetDefaultFontDescription());\n if (font) {\n font->RenderGlyphs(setup.GlyphSet.AsCStr());\n }\n\n \/\/ input event handlers\n Input::SubscribeMouse([this](const Mouse::Event& e) {\n switch (e.Type) {\n case Mouse::Event::Move:\n this->onMouseMove((int)e.Position.x, (int)e.Position.y);\n break;\n case Mouse::Event::ButtonDown:\n this->onMouseButton(e.Button, true);\n break;\n case Mouse::Event::ButtonUp:\n this->onMouseButton(e.Button, false);\n break;\n case Mouse::Event::Scroll:\n this->onScroll((int)e.ScrollMovement.x, (int)e.ScrollMovement.y);\n break;\n default:\n break;\n }\n });\n Input::SubscribeKeyboard([this](const Keyboard::Event& e) {\n switch (e.Type) {\n case Keyboard::Event::KeyDown:\n case Keyboard::Event::KeyRepeat:\n this->onKey(e.KeyCode, true, false);\n break;\n case Keyboard::Event::KeyUp:\n this->onKey(e.KeyCode, false, true);\n break;\n case Keyboard::Event::WChar:\n this->onWChar(e.WCharCode);\n break;\n default:\n break;\n }\n });\n Input::SubscribeTouchpad([this](const Touchpad::Event& e) {\n switch (e.Type) {\n case Touchpad::Event::Tapped:\n this->onTapped(e.Position[0]);\n break;\n case Touchpad::Event::PanningStarted:\n this->onPanningStarted(e.StartPosition[0]);\n break;\n case Touchpad::Event::Panning:\n this->onPanning(e.Position[0]);\n break;\n case Touchpad::Event::PanningEnded:\n this->onPanningEnded(e.Position[0]);\n break;\n default:\n break;\n }\n });\n\n \/\/ add per-frame update method\n Core::PostRunLoop()->Add([this] {\n this->update();\n });\n \n TBWidgetsAnimationManager::Init();\n \n this->isValid = true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::Discard() {\n o_assert_dbg(this->IsValid());\n \n TBWidgetsAnimationManager::Shutdown();\n\n tb_core_shutdown();\n\n this->renderer->Discard();\n Memory::Delete(this->renderer);\n \n this->isValid = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool\ntbMgr::IsValid() const {\n return this->isValid;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::update() {\n this->rootWidget.InvokeProcessStates();\n this->rootWidget.InvokeProcess();\n\n \/\/ send a release for each tap\n glm::vec2 pos;\n while (!this->touchTaps.Empty()) {\n this->touchTaps.Dequeue(pos);\n this->rootWidget.InvokePointerUp((int)pos.x, (int)pos.y, this->modifierKeys, true);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::Draw() {\n o_assert_dbg(this->IsValid());\n o_assert_dbg(this->renderer);\n\n const DisplayAttrs& disp = Gfx::RenderTargetAttrs();\n this->rootWidget.SetRect(TBRect(0, 0, disp.FramebufferWidth, disp.FramebufferHeight));\n\n TBAnimationManager::Update();\n\n this->renderer->BeginPaint(disp.FramebufferWidth, disp.FramebufferHeight);\n this->rootWidget.InvokePaint(TBWidget::PaintProps());\n this->renderer->EndPaint();\n\n \/\/ if animations are running, reinvalidate immediately\n if (TBAnimationManager::HasAnimationsRunning()) {\n this->rootWidget.Invalidate();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\ntbOryolRootWidget*\ntbMgr::GetRootWidget() {\n o_assert_dbg(this->IsValid());\n return &this->rootWidget;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onMouseMove(int posX, int posY) {\n this->mouseX = posX;\n this->mouseY = posY;\n this->rootWidget.InvokePointerMove(this->mouseX, this->mouseY, this->modifierKeys, false);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onMouseButton(Mouse::Button btn, bool down) {\n if (btn == Mouse::LMB) {\n if (down) {\n this->rootWidget.InvokePointerDown(this->mouseX, this->mouseY, 1, this->modifierKeys, false);\n }\n else {\n this->rootWidget.InvokePointerUp(this->mouseX, this->mouseY, this->modifierKeys, false);\n }\n }\n else if (btn == Mouse::RMB) {\n this->rootWidget.InvokePointerMove(this->mouseX, this->mouseY, this->modifierKeys, false);\n if (TBWidget::hovered_widget)\n {\n TBWidget::hovered_widget->ConvertFromRoot(this->mouseX, this->mouseY);\n TBWidgetEvent ev(EVENT_TYPE_CONTEXT_MENU, this->mouseX, this->mouseY, false, this->modifierKeys);\n TBWidget::hovered_widget->InvokeEvent(ev);\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onTapped(const glm::vec2& pos) {\n this->touchTaps.Enqueue(pos);\n this->rootWidget.InvokePointerDown((int)pos.x, (int)pos.y, 1, this->modifierKeys, true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onPanningStarted(const glm::vec2& pos) {\n this->rootWidget.InvokePointerDown((int)pos.x, (int)pos.y, 1, this->modifierKeys, true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onPanningEnded(const glm::vec2& pos) {\n this->rootWidget.InvokePointerUp((int)pos.x, (int)pos.y, this->modifierKeys, true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onPanning(const glm::vec2& pos) {\n this->rootWidget.InvokePointerMove((int)pos.x, (int)pos.y, this->modifierKeys, true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onScroll(int wheelX, int wheelY) {\n this->rootWidget.InvokeWheel(this->mouseX, this->mouseY, wheelX, wheelY, this->modifierKeys);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int\ntoupr_ascii(int ascii)\n{\n if (ascii >= 'a' && ascii <= 'z') {\n return ascii + 'A' - 'a';\n }\n return ascii;\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic bool\ninvokeShortcut(int key, SPECIAL_KEY specialKey, MODIFIER_KEYS modifierKeys, bool down) {\n\n #ifdef FIPS_OSX\n bool shortcut_key = (modifierKeys & TB_SUPER) ? true : false;\n #else\n bool shortcut_key = (modifierKeys & TB_CTRL) ? true : false;\n #endif\n if (!TBWidget::focused_widget || !down || !shortcut_key) {\n return false;\n }\n bool reverse_key = (modifierKeys & TB_SHIFT) ? true : false;\n int upper_key = toupr_ascii(key);\n TBID id;\n if (upper_key == 'X') {\n id = TBIDC(\"cut\");\n }\n else if (upper_key == 'C' || specialKey == TB_KEY_INSERT) {\n id = TBIDC(\"copy\");\n }\n else if (upper_key == 'V' || (specialKey == TB_KEY_INSERT && reverse_key)) {\n id = TBIDC(\"paste\");\n }\n else if (upper_key == 'A') {\n id = TBIDC(\"selectall\");\n }\n else if (upper_key == 'Z' || upper_key == 'Y') {\n bool undo = upper_key == 'Z';\n if (reverse_key) {\n undo = !undo;\n }\n id = undo ? TBIDC(\"undo\") : TBIDC(\"redo\");\n }\n else if (upper_key == 'N') {\n id = TBIDC(\"new\");\n }\n else if (upper_key == 'O') {\n id = TBIDC(\"open\");\n }\n else if (upper_key == 'S') {\n id = TBIDC(\"save\");\n }\n else if (upper_key == 'W') {\n id = TBIDC(\"close\");\n }\n else if (specialKey == TB_KEY_PAGE_UP) {\n id = TBIDC(\"prev_doc\");\n }\n else if (specialKey == TB_KEY_PAGE_DOWN) {\n id = TBIDC(\"next_doc\");\n }\n else {\n return false;\n }\n\n TBWidgetEvent ev(EVENT_TYPE_SHORTCUT);\n ev.modifierkeys = modifierKeys;\n ev.ref_id = id;\n return TBWidget::focused_widget->InvokeEvent(ev);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic bool\ninvokeKey(tbOryolRootWidget* rootWidget, unsigned int key, SPECIAL_KEY specialKey, MODIFIER_KEYS modifierKeys, bool down)\n{\n if (invokeShortcut(key, specialKey, modifierKeys, down)) {\n return true;\n }\n rootWidget->InvokeKey(key, specialKey, modifierKeys, down);\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onWChar(wchar_t c) {\n if ((c >= 0xE000) && (c <= 0xF8FF)) {\n return;\n }\n invokeKey(&this->rootWidget, c, TB_KEY_UNDEFINED, this->modifierKeys, true);\n invokeKey(&this->rootWidget, c, TB_KEY_UNDEFINED, this->modifierKeys, false);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\ntbMgr::onKey(Key::Code key, bool down, bool up) {\n\n SPECIAL_KEY tbKey = TB_KEY_UNDEFINED;\n switch (key)\n {\n case Key::F1: tbKey = TB_KEY_F1; break;\n case Key::F2: tbKey = TB_KEY_F2; break;\n case Key::F3: tbKey = TB_KEY_F3; break;\n case Key::F4: tbKey = TB_KEY_F4; break;\n case Key::F5: tbKey = TB_KEY_F5; break;\n case Key::F6: tbKey = TB_KEY_F6; break;\n case Key::F7: tbKey = TB_KEY_F7; break;\n case Key::F8: tbKey = TB_KEY_F8; break;\n case Key::F9: tbKey = TB_KEY_F9; break;\n case Key::F10: tbKey = TB_KEY_F10; break;\n case Key::F11: tbKey = TB_KEY_F11; break;\n case Key::F12: tbKey = TB_KEY_F12; break;\n case Key::Left: tbKey = TB_KEY_LEFT; break;\n case Key::Up: tbKey = TB_KEY_UP; break;\n case Key::Right: tbKey = TB_KEY_RIGHT; break;\n case Key::Down: tbKey = TB_KEY_DOWN; break;\n case Key::PageUp: tbKey = TB_KEY_PAGE_UP; break;\n case Key::PageDown: tbKey = TB_KEY_PAGE_DOWN; break;\n case Key::Home: tbKey = TB_KEY_HOME; break;\n case Key::End: tbKey = TB_KEY_END; break;\n case Key::Insert: tbKey = TB_KEY_INSERT; break;\n case Key::Tab: tbKey = TB_KEY_TAB; break;\n case Key::Delete: tbKey = TB_KEY_DELETE; break;\n case Key::BackSpace: tbKey = TB_KEY_BACKSPACE; break;\n case Key::Enter:\n case Key::NumEnter:\n tbKey = TB_KEY_ENTER; break;\n case Key::Escape: tbKey = TB_KEY_ESC; break;\n case Key::Menu:\n if (TBWidget::focused_widget && !down) {\n TBWidgetEvent ev(EVENT_TYPE_CONTEXT_MENU);\n ev.modifierkeys = modifierKeys;\n TBWidget::focused_widget->InvokeEvent(ev);\n }\n break;\n case Key::LeftShift:\n case Key::RightShift:\n if (down) {\n this->modifierKeys |= TB_SHIFT;\n }\n else {\n this->modifierKeys &= ~TB_SHIFT;\n }\n break;\n case Key::LeftControl:\n case Key::RightControl:\n if (down) {\n this->modifierKeys |= TB_CTRL;\n }\n else {\n this->modifierKeys &= ~TB_CTRL;\n }\n break;\n case Key::LeftAlt:\n case Key::RightAlt:\n if (down) {\n this->modifierKeys |= TB_ALT;\n }\n else {\n this->modifierKeys &= ~TB_ALT;\n }\n break;\n case Key::LeftSuper:\n case Key::RightSuper:\n if (down) {\n this->modifierKeys |= TB_SUPER;\n }\n else {\n this->modifierKeys &= ~TB_SUPER;\n }\n break;\n default:\n break;\n }\n if (TB_KEY_UNDEFINED != tbKey) {\n invokeKey(&this->rootWidget, 0, tbKey, this->modifierKeys, down);\n }\n}\n\n} \/\/ namespace _priv\n} \/\/ namespace Oryol\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright(c) 2016-2017 benikabocha.\n\/\/ Distributed under the MIT License (http:\/\/opensource.org\/licenses\/MIT)\n\/\/\n\n#include <Saba\/Base\/UnicodeUtil.h>\n#include <Saba\/Base\/Path.h>\n#include <Saba\/Model\/MMD\/MMDModel.h>\n#include <Saba\/Model\/MMD\/PMDModel.h>\n#include <Saba\/Model\/MMD\/PMXModel.h>\n#include <Saba\/Model\/MMD\/VMDFile.h>\n#include <Saba\/Model\/MMD\/VMDAnimation.h>\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <memory>\n\nvoid Usage()\n{\n\tstd::cout << \"mmd2obj <pmd\/pmx file> [-vmd <vmd file>] [-t <animation time (sec)>]\\n\";\n}\n\nbool MMD2Obj(const std::vector<std::string>& args)\n{\n\tif (args.size() <= 1)\n\t{\n\t\tUsage();\n\t\treturn false;\n\t}\n\n\t\/\/ Analyze commad line.\n\tconst std::string& modelPath = args[1];\n\tstd::vector<std::string> vmdPaths;\n\tdouble\tanimTime = 0.0;\n\n\tfor (size_t i = 2; i < args.size(); i++)\n\t{\n\t\tif (args[i] == \"-vmd\")\n\t\t{\n\t\t\ti++;\n\t\t\tif (i < args.size())\n\t\t\t{\n\t\t\t\tvmdPaths.push_back(args[i]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tUsage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (args[i] == \"-t\")\n\t\t{\n\t\t\ti++;\n\t\t\tif (i < args.size())\n\t\t\t{\n\t\t\t\tanimTime = std::stod(args[i]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tUsage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tUsage();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ Load model.\n\tstd::shared_ptr<saba::MMDModel> mmdModel;\n\tstd::string mmdDataPath = \"\";\t\/\/ Set MMD data path(default toon texture path).\n\tstd::string ext = saba::PathUtil::GetExt(modelPath);\n\tif (ext == \"pmd\")\n\t{\n\t\tauto pmdModel = std::make_unique<saba::PMDModel>();\n\t\tif (!pmdModel->Load(modelPath, mmdDataPath))\n\t\t{\n\t\t\tstd::cout << \"Load PMDModel Fail.\\n\";\n\t\t\treturn false;\n\t\t}\n\t\tmmdModel = std::move(pmdModel);\n\t}\n\telse if (ext == \"pmx\")\n\t{\n\t\tauto pmxModel = std::make_unique<saba::PMXModel>();\n\t\tif (!pmxModel->Load(modelPath, mmdDataPath))\n\t\t{\n\t\t\tstd::cout << \"Load PMXModel Fail.\\n\";\n\t\t\treturn false;\n\t\t}\n\t\tmmdModel = std::move(pmxModel);\n\t}\n\telse\n\t{\n\t\tstd::cout << \"Unsupported Model Ext : \" << ext << \"\\n\";\n\t\treturn false;\n\t}\n\n\t\/\/ Load animation.\n\tauto vmdAnim = std::make_unique<saba::VMDAnimation>();\n\tif (!vmdAnim->Create(mmdModel))\n\t{\n\t\tstd::cout << \"Create VMDAnimation Fail.\\n\";\n\t\treturn false;\n\t}\n\tfor (const auto& vmdPath : vmdPaths)\n\t{\n\t\tsaba::VMDFile vmdFile;\n\t\tif (!saba::ReadVMDFile(&vmdFile, vmdPath.c_str()))\n\t\t{\n\t\t\tstd::cout << \"Read VMD File Fail.\\n\";\n\t\t\treturn false;\n\t\t}\n\t\tif (!vmdAnim->Add(vmdFile))\n\t\t{\n\t\t\tstd::cout << \"Add VMDAnimation Fail.\\n\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ Initialize pose.\n\t{\n\t\t\/\/ Sync physics animation.\n\t\tmmdModel->InitializeAnimation();\n\t\tvmdAnim->SyncPhysics((float)animTime * 30.0f);\n\t}\n\n\t\/\/ Update animation(animation loop).\n\t{\n\t\t\/\/ Update bone animation.\n\t\tmmdModel->BeginAnimation();\n\t\tvmdAnim->Evaluate((float)animTime * 30.0f);\n\t\tmmdModel->UpdateAnimation();\n\t\tmmdModel->EndAnimation();\n\n\t\t\/\/ Update physics animation.\n\t\tmmdModel->UpdatePhysics(1.0f \/ 60.0f);\n\n\t\t\/\/ Update vertex.\n\t\tmmdModel->Update();\n\t}\n\n\t\/\/ Output OBJ file.\n\tstd::ofstream objFile;\n\tobjFile.open(\"output.obj\");\n\tif (!objFile.is_open())\n\t{\n\t\tstd::cout << \"Open OBJ File Fail.\\n\";\n\t\treturn false;\n\t}\n\tobjFile << \"# mmmd2obj\\n\";\n\tobjFile << \"mtllib output.mtl\\n\";\n\n\t\/\/ Write positions.\n\tsize_t vtxCount = mmdModel->GetVertexCount();\n\tconst glm::vec3* positions = mmdModel->GetUpdatePositions();\n\tfor (size_t i = 0; i < vtxCount; i++)\n\t{\n\t\tobjFile << \"v \" << positions[i].x << \" \" << positions[i].y << \" \" << positions[i].z << \"\\n\";\n\t}\n\tconst glm::vec3* normals = mmdModel->GetUpdateNormals();\n\tfor (size_t i = 0; i < vtxCount; i++)\n\t{\n\t\tobjFile << \"vn \" << normals[i].x << \" \" << normals[i].y << \" \" << normals[i].z << \"\\n\";\n\t}\n\tconst glm::vec2* uvs = mmdModel->GetUpdateUVs();\n\tfor (size_t i = 0; i < vtxCount; i++)\n\t{\n\t\tobjFile << \"vt \" << uvs[i].x << \" \" << uvs[i].y << \"\\n\";\n\t}\n\n\t\/\/ Copy vertex indices.\n\tstd::vector<size_t> indices(mmdModel->GetIndexCount());\n\tif (mmdModel->GetIndexElementSize() == 1)\n\t{\n\t\tuint8_t* mmdIndices = (uint8_t*)mmdModel->GetIndices();\n\t\tfor (size_t i = 0; i < indices.size(); i++)\n\t\t{\n\t\t\tindices[i] = mmdIndices[i];\n\t\t}\n\t}\n\telse if (mmdModel->GetIndexElementSize() == 2)\n\t{\n\t\tuint16_t* mmdIndices = (uint16_t*)mmdModel->GetIndices();\n\t\tfor (size_t i = 0; i < indices.size(); i++)\n\t\t{\n\t\t\tindices[i] = mmdIndices[i];\n\t\t}\n\t}\n\telse if (mmdModel->GetIndexElementSize() == 4)\n\t{\n\t\tuint32_t* mmdIndices = (uint32_t*)mmdModel->GetIndices();\n\t\tfor (size_t i = 0; i < indices.size(); i++)\n\t\t{\n\t\t\tindices[i] = mmdIndices[i];\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/ Write faces.\n\tsize_t subMeshCount = mmdModel->GetSubMeshCount();\n\tconst saba::MMDSubMesh* subMeshes = mmdModel->GetSubMeshes();\n\tfor (size_t i = 0; i < subMeshCount; i++)\n\t{\n\t\tobjFile << \"\\n\";\n\t\tobjFile << \"usemtl \" << subMeshes[i].m_materialID << \"\\n\";\n\n\t\tfor (size_t j = 0; j < subMeshes[i].m_vertexCount; j += 3)\n\t\t{\n\t\t\tauto vtxIdx = subMeshes[i].m_beginIndex + j;\n\t\t\tauto vi0 = indices[vtxIdx + 0] + 1;\n\t\t\tauto vi1 = indices[vtxIdx + 1] + 1;\n\t\t\tauto vi2 = indices[vtxIdx + 2] + 1;\n\t\t\tobjFile << \"f \"\n\t\t\t\t<< vi0 << \"\/\" << vi0 << \"\/\" << vi0 << \" \"\n\t\t\t\t<< vi1 << \"\/\" << vi1 << \"\/\" << vi1 << \" \"\n\t\t\t\t<< vi2 << \"\/\" << vi2 << \"\/\" << vi2 << \"\\n\";\n\t\t}\n\t}\n\tobjFile.close();\n\n\t\/\/ Write materials.\n\tstd::ofstream mtlFile;\n\tmtlFile.open(\"output.mtl\");\n\tif (!mtlFile.is_open())\n\t{\n\t\tstd::cout << \"Open MTL File Fail.\\n\";\n\t\treturn false;\n\t}\n\n\tobjFile << \"# mmmd2obj\\n\";\n\tsize_t materialCount = mmdModel->GetMaterialCount();\n\tconst saba::MMDMaterial* materials = mmdModel->GetMaterials();\n\tfor (size_t i = 0; i < materialCount; i++)\n\t{\n\t\tconst auto& m = materials[i];\n\t\tmtlFile << \"newmtl \" << i << \"\\n\";\n\n\t\tmtlFile << \"Ka \" << m.m_ambient.r << \" \" << m.m_ambient.g << \" \" << m.m_ambient.b << \"\\n\";\n\t\tmtlFile << \"Kd \" << m.m_diffuse.r << \" \" << m.m_diffuse.g << \" \" << m.m_diffuse.b << \"\\n\";\n\t\tmtlFile << \"Ks \" << m.m_specular.r << \" \" << m.m_specular.g << \" \" << m.m_specular.b << \"\\n\";\n\t\tmtlFile << \"d \" << m.m_alpha << \"\\n\";\n\t\tmtlFile << \"map_Kd \" << m.m_texture << \"\\n\";\n\t\tmtlFile << \"\\n\";\n\t}\n\tmtlFile.close();\n\n\treturn true;\n}\n\n#if _WIN32\nint wmain(int argc, wchar_t** argv)\n{\n\tstd::vector<std::string> args(argc);\n\tfor (int i = 0; i < argc; i++)\n\t{\n\t\targs[i] = saba::ToUtf8String(argv[i]);\n\t}\n\n\tif (!MMD2Obj(args))\n\t{\n\t\tstd::cout << \"Convert Fail.\\n\";\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n#else \/\/ _WIN32\nint main(int argc, char** argv)\n{\n\tstd::vector<std::string> args(argc);\n\tfor (int i = 0; i < argc; i++)\n\t{\n\t\targs[i] = argv[i];\n\t}\n\n\tif (!MMD2Obj(args))\n\t{\n\t\tstd::cout << \"Convert Fail.\\n\";\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n#endif \/\/ _WIN32<commit_msg>mmd2obj : add vpd support<commit_after>\/\/\n\/\/ Copyright(c) 2016-2017 benikabocha.\n\/\/ Distributed under the MIT License (http:\/\/opensource.org\/licenses\/MIT)\n\/\/\n\n#include <Saba\/Base\/UnicodeUtil.h>\n#include <Saba\/Base\/Path.h>\n#include <Saba\/Model\/MMD\/MMDModel.h>\n#include <Saba\/Model\/MMD\/PMDModel.h>\n#include <Saba\/Model\/MMD\/PMXModel.h>\n#include <Saba\/Model\/MMD\/VMDFile.h>\n#include <Saba\/Model\/MMD\/VMDAnimation.h>\n#include <Saba\/Model\/MMD\/VPDFile.h>\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <memory>\n\nvoid Usage()\n{\n\tstd::cout << \"mmd2obj <pmd\/pmx file> [-vmd <vmd file>] [-t <animation time (sec)>] [-vpd <vpd file>]\\n\";\n}\n\nbool MMD2Obj(const std::vector<std::string>& args)\n{\n\tif (args.size() <= 1)\n\t{\n\t\tUsage();\n\t\treturn false;\n\t}\n\n\t\/\/ Analyze commad line.\n\tconst std::string& modelPath = args[1];\n\tstd::vector<std::string> vmdPaths;\n\tstd::string vpdPath;\n\tdouble\tanimTime = 0.0;\n\n\tfor (size_t i = 2; i < args.size(); i++)\n\t{\n\t\tif (args[i] == \"-vmd\")\n\t\t{\n\t\t\ti++;\n\t\t\tif (i < args.size())\n\t\t\t{\n\t\t\t\tvmdPaths.push_back(args[i]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tUsage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (args[i] == \"-t\")\n\t\t{\n\t\t\ti++;\n\t\t\tif (i < args.size())\n\t\t\t{\n\t\t\t\tanimTime = std::stod(args[i]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tUsage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (args[i] == \"-vpd\")\n\t\t{\n\t\t\ti++;\n\t\t\tif (i < args.size())\n\t\t\t{\n\t\t\t\tvpdPath = args[i];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tUsage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tUsage();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ Load model.\n\tstd::shared_ptr<saba::MMDModel> mmdModel;\n\tstd::string mmdDataPath = \"\";\t\/\/ Set MMD data path(default toon texture path).\n\tstd::string ext = saba::PathUtil::GetExt(modelPath);\n\tif (ext == \"pmd\")\n\t{\n\t\tauto pmdModel = std::make_unique<saba::PMDModel>();\n\t\tif (!pmdModel->Load(modelPath, mmdDataPath))\n\t\t{\n\t\t\tstd::cout << \"Failed to load PMDModel.\\n\";\n\t\t\treturn false;\n\t\t}\n\t\tmmdModel = std::move(pmdModel);\n\t}\n\telse if (ext == \"pmx\")\n\t{\n\t\tauto pmxModel = std::make_unique<saba::PMXModel>();\n\t\tif (!pmxModel->Load(modelPath, mmdDataPath))\n\t\t{\n\t\t\tstd::cout << \"Failed to load PMXModel.\\n\";\n\t\t\treturn false;\n\t\t}\n\t\tmmdModel = std::move(pmxModel);\n\t}\n\telse\n\t{\n\t\tstd::cout << \"Unsupported Model Ext : \" << ext << \"\\n\";\n\t\treturn false;\n\t}\n\n\t\/\/ Load animation.\n\tbool useVMDAnimation = !vmdPaths.empty();\n\tauto vmdAnim = std::make_unique<saba::VMDAnimation>();\n\tif (!vmdAnim->Create(mmdModel))\n\t{\n\t\tstd::cout << \"Failed to create VMDAnimation.\\n\";\n\t\treturn false;\n\t}\n\tfor (const auto& vmdPath : vmdPaths)\n\t{\n\t\tsaba::VMDFile vmdFile;\n\t\tif (!saba::ReadVMDFile(&vmdFile, vmdPath.c_str()))\n\t\t{\n\t\t\tstd::cout << \"Failed to read VMD file.\\n\";\n\t\t\treturn false;\n\t\t}\n\t\tif (!vmdAnim->Add(vmdFile))\n\t\t{\n\t\t\tstd::cout << \"Failed to add VMDAnimation.\\n\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ Load pose.\n\tsaba::VPDFile vpdFile;\n\tif (!vpdPath.empty())\n\t{\n\t\tif (!vmdPaths.empty())\n\t\t{\n\t\t\tstd::cout << \"Warning : Canceled to read VPD file.\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!saba::ReadVPDFile(&vpdFile, vpdPath.c_str()))\n\t\t\t{\n\t\t\t\tstd::cout << \"Failed to read VPD file.\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t}\n\t}\n\n\t\/\/ Initialize pose.\n\t{\n\t\t\/\/ Sync physics animation.\n\t\tmmdModel->InitializeAnimation();\n\t\tif (useVMDAnimation)\n\t\t{\n\t\t\tvmdAnim->SyncPhysics((float)animTime * 30.0f);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmmdModel->LoadPose(vpdFile);\n\t\t}\n\t}\n\n\t\/\/ Update animation(animation loop).\n\t{\n\t\t\/\/ Update bone animation.\n\t\tmmdModel->BeginAnimation();\n\t\tif (useVMDAnimation)\n\t\t{\n\t\t\tvmdAnim->Evaluate((float)animTime * 30.0f);\n\t\t}\n\t\tmmdModel->UpdateAnimation();\n\t\tmmdModel->EndAnimation();\n\n\t\t\/\/ Update physics animation.\n\t\tmmdModel->UpdatePhysics(1.0f \/ 60.0f);\n\n\t\t\/\/ Update vertex.\n\t\tmmdModel->Update();\n\t}\n\n\t\/\/ Output OBJ file.\n\tstd::ofstream objFile;\n\tobjFile.open(\"output.obj\");\n\tif (!objFile.is_open())\n\t{\n\t\tstd::cout << \"Failed to open OBJ file.\\n\";\n\t\treturn false;\n\t}\n\tobjFile << \"# mmmd2obj\\n\";\n\tobjFile << \"mtllib output.mtl\\n\";\n\n\t\/\/ Write positions.\n\tsize_t vtxCount = mmdModel->GetVertexCount();\n\tconst glm::vec3* positions = mmdModel->GetUpdatePositions();\n\tfor (size_t i = 0; i < vtxCount; i++)\n\t{\n\t\tobjFile << \"v \" << positions[i].x << \" \" << positions[i].y << \" \" << positions[i].z << \"\\n\";\n\t}\n\tconst glm::vec3* normals = mmdModel->GetUpdateNormals();\n\tfor (size_t i = 0; i < vtxCount; i++)\n\t{\n\t\tobjFile << \"vn \" << normals[i].x << \" \" << normals[i].y << \" \" << normals[i].z << \"\\n\";\n\t}\n\tconst glm::vec2* uvs = mmdModel->GetUpdateUVs();\n\tfor (size_t i = 0; i < vtxCount; i++)\n\t{\n\t\tobjFile << \"vt \" << uvs[i].x << \" \" << uvs[i].y << \"\\n\";\n\t}\n\n\t\/\/ Copy vertex indices.\n\tstd::vector<size_t> indices(mmdModel->GetIndexCount());\n\tif (mmdModel->GetIndexElementSize() == 1)\n\t{\n\t\tuint8_t* mmdIndices = (uint8_t*)mmdModel->GetIndices();\n\t\tfor (size_t i = 0; i < indices.size(); i++)\n\t\t{\n\t\t\tindices[i] = mmdIndices[i];\n\t\t}\n\t}\n\telse if (mmdModel->GetIndexElementSize() == 2)\n\t{\n\t\tuint16_t* mmdIndices = (uint16_t*)mmdModel->GetIndices();\n\t\tfor (size_t i = 0; i < indices.size(); i++)\n\t\t{\n\t\t\tindices[i] = mmdIndices[i];\n\t\t}\n\t}\n\telse if (mmdModel->GetIndexElementSize() == 4)\n\t{\n\t\tuint32_t* mmdIndices = (uint32_t*)mmdModel->GetIndices();\n\t\tfor (size_t i = 0; i < indices.size(); i++)\n\t\t{\n\t\t\tindices[i] = mmdIndices[i];\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/ Write faces.\n\tsize_t subMeshCount = mmdModel->GetSubMeshCount();\n\tconst saba::MMDSubMesh* subMeshes = mmdModel->GetSubMeshes();\n\tfor (size_t i = 0; i < subMeshCount; i++)\n\t{\n\t\tobjFile << \"\\n\";\n\t\tobjFile << \"usemtl \" << subMeshes[i].m_materialID << \"\\n\";\n\n\t\tfor (size_t j = 0; j < subMeshes[i].m_vertexCount; j += 3)\n\t\t{\n\t\t\tauto vtxIdx = subMeshes[i].m_beginIndex + j;\n\t\t\tauto vi0 = indices[vtxIdx + 0] + 1;\n\t\t\tauto vi1 = indices[vtxIdx + 1] + 1;\n\t\t\tauto vi2 = indices[vtxIdx + 2] + 1;\n\t\t\tobjFile << \"f \"\n\t\t\t\t<< vi0 << \"\/\" << vi0 << \"\/\" << vi0 << \" \"\n\t\t\t\t<< vi1 << \"\/\" << vi1 << \"\/\" << vi1 << \" \"\n\t\t\t\t<< vi2 << \"\/\" << vi2 << \"\/\" << vi2 << \"\\n\";\n\t\t}\n\t}\n\tobjFile.close();\n\n\t\/\/ Write materials.\n\tstd::ofstream mtlFile;\n\tmtlFile.open(\"output.mtl\");\n\tif (!mtlFile.is_open())\n\t{\n\t\tstd::cout << \"Failed to open MTL file.\\n\";\n\t\treturn false;\n\t}\n\n\tobjFile << \"# mmmd2obj\\n\";\n\tsize_t materialCount = mmdModel->GetMaterialCount();\n\tconst saba::MMDMaterial* materials = mmdModel->GetMaterials();\n\tfor (size_t i = 0; i < materialCount; i++)\n\t{\n\t\tconst auto& m = materials[i];\n\t\tmtlFile << \"newmtl \" << i << \"\\n\";\n\n\t\tmtlFile << \"Ka \" << m.m_ambient.r << \" \" << m.m_ambient.g << \" \" << m.m_ambient.b << \"\\n\";\n\t\tmtlFile << \"Kd \" << m.m_diffuse.r << \" \" << m.m_diffuse.g << \" \" << m.m_diffuse.b << \"\\n\";\n\t\tmtlFile << \"Ks \" << m.m_specular.r << \" \" << m.m_specular.g << \" \" << m.m_specular.b << \"\\n\";\n\t\tmtlFile << \"d \" << m.m_alpha << \"\\n\";\n\t\tmtlFile << \"map_Kd \" << m.m_texture << \"\\n\";\n\t\tmtlFile << \"\\n\";\n\t}\n\tmtlFile.close();\n\n\treturn true;\n}\n\n#if _WIN32\nint wmain(int argc, wchar_t** argv)\n{\n\tstd::vector<std::string> args(argc);\n\tfor (int i = 0; i < argc; i++)\n\t{\n\t\targs[i] = saba::ToUtf8String(argv[i]);\n\t}\n\n\tif (!MMD2Obj(args))\n\t{\n\t\tstd::cout << \"Failed to convert model data.\\n\";\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n#else \/\/ _WIN32\nint main(int argc, char** argv)\n{\n\tstd::vector<std::string> args(argc);\n\tfor (int i = 0; i < argc; i++)\n\t{\n\t\targs[i] = argv[i];\n\t}\n\n\tif (!MMD2Obj(args))\n\t{\n\t\tstd::cout << \"Failed to convert model data.\\n\";\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n#endif \/\/ _WIN32<|endoftext|>"} {"text":"<commit_before>\/*\n\nopenfx-arena - https:\/\/github.com\/olear\/openfx-arena\n\nCopyright (c) 2015, Ole-André Rodlie <olear@fxarena.net>\nCopyright (c) 2015, FxArena DA <mail@fxarena.net>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Neither the name of FxArena DA 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* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\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 ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"ReadPSD.h\"\n#include <iostream>\n#include <string>\n#include <Magick++.h>\n#include \"GenericReader.h\"\n#include \"GenericOCIO.h\"\n#include \"ofxsMacros.h\"\n\n#ifdef OFX_IO_USING_OCIO\n#include <OpenColorIO\/OpenColorIO.h>\n#endif\n\n#define kPluginName \"ReadPSD\"\n#define kPluginGrouping \"Image\/Readers\"\n#define kPluginIdentifier \"net.fxarena.openfx.ReadPSD\"\n#define kPluginVersionMajor 1\n#define kPluginVersionMinor 6\n\n#define kSupportsRGBA true\n#define kSupportsRGB false\n#define kSupportsAlpha false\n#define kSupportsTiles false\n#define kIsMultiPlanar true\n\nclass ReadPSDPlugin : public GenericReaderPlugin\n{\npublic:\n ReadPSDPlugin(OfxImageEffectHandle handle);\n virtual ~ReadPSDPlugin();\nprivate:\n virtual bool isVideoStream(const std::string& \/*filename*\/) OVERRIDE FINAL { return false; }\n virtual void decode(const std::string& filename, OfxTime time, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds,\n OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, int rowBytes) OVERRIDE FINAL\n {\n std::string rawComps;\n switch (pixelComponents) {\n case OFX::ePixelComponentAlpha:\n rawComps = kOfxImageComponentAlpha;\n break;\n case OFX::ePixelComponentRGB:\n rawComps = kOfxImageComponentRGB;\n break;\n case OFX::ePixelComponentRGBA:\n rawComps = kOfxImageComponentRGBA;\n break;\n default:\n OFX::throwSuiteStatusException(kOfxStatFailed);\n return;\n }\n decodePlane(filename, time, renderWindow, pixelData, bounds, pixelComponents, pixelComponentCount, rawComps, rowBytes);\n }\n virtual void getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents) OVERRIDE FINAL;\n virtual void decodePlane(const std::string& filename, OfxTime time, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds, OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, const std::string& rawComponents, int rowBytes) OVERRIDE FINAL;\n virtual bool getFrameBounds(const std::string& filename, OfxTime time, OfxRectI *bounds, double *par, std::string *error) OVERRIDE FINAL;\n virtual void restoreState(const std::string& filename) OVERRIDE FINAL;\n virtual void onInputFileChanged(const std::string& newFile, OFX::PreMultiplicationEnum *premult, OFX::PixelComponentEnum *components, int *componentCount) OVERRIDE FINAL;\n std::string _filename;\n std::vector<Magick::Image> _psd;\n};\n\nReadPSDPlugin::ReadPSDPlugin(OfxImageEffectHandle handle)\n: GenericReaderPlugin(handle, kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles,\n#ifdef OFX_EXTENSIONS_NUKE\n(OFX::getImageEffectHostDescription() && OFX::getImageEffectHostDescription()->isMultiPlanar) ? kIsMultiPlanar : false\n#else\nfalse\n#endif\n)\n{\n Magick::InitializeMagick(NULL);\n assert(_outputComponents);\n}\n\nReadPSDPlugin::~ReadPSDPlugin()\n{\n}\n\nvoid ReadPSDPlugin::getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents)\n{\n #ifdef DEBUG\n std::cout << \"getClipComponents ...\" << std::endl;\n #endif\n assert(isMultiPlanar());\n clipComponents.addClipComponents(*_outputClip, getOutputComponents());\n clipComponents.setPassThroughClip(NULL, args.time, args.view);\n if (_psd.size()>0) {\n int startLayer = 0;\n if (_psd[0].format()==\"Adobe Photoshop bitmap\")\n startLayer++;\n for (int i = startLayer; i < (int)_psd.size(); i++) {\n std::ostringstream layerName;\n layerName << _psd[i].label();\n if (layerName.str().empty())\n layerName << \"Image Layer #\" << i; \/\/ add a label if empty\n std::string component(kNatronOfxImageComponentsPlane);\n component.append(layerName.str());\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"R\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"G\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"B\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"A\");\n clipComponents.addClipComponents(*_outputClip, component);\n }\n }\n}\n\nvoid ReadPSDPlugin::decodePlane(const std::string& \/*filename*\/, OfxTime \/*time*\/, const OfxRectI& \/*renderWindow*\/, float *pixelData, const OfxRectI& bounds,\n OFX::PixelComponentEnum \/*pixelComponents*\/, int \/*pixelComponentCount*\/, const std::string& rawComponents, int \/*rowBytes*\/)\n{\n #ifdef DEBUG\n std::cout << \"decodePlane ...\" << std::endl;\n #endif\n int offsetX = 0;\n int offsetY = 0;\n int layer = 0;\n int width = bounds.x2;\n int height = bounds.y2;\n std::string layerName;\n std::vector<std::string> layerChannels = OFX::mapPixelComponentCustomToLayerChannels(rawComponents);\n int numChannels = layerChannels.size();\n if (numChannels==5) \/\/ layer+R+G+B+A\n layerName=layerChannels[0];\n if (!layerName.empty()) {\n for (size_t i = 0; i < _psd.size(); i++) {\n bool foundLayer = false;\n std::ostringstream psdLayer;\n psdLayer << \"Image Layer #\" << i;\n if (_psd[i].label()==layerName)\n foundLayer = true;\n if (psdLayer.str()==layerName && !foundLayer)\n foundLayer = true;\n if (foundLayer) {\n if ((int)_psd[i].columns()!=bounds.x2)\n offsetX = _psd[i].page().xOff();\n if ((int)_psd[i].rows()!=bounds.y2)\n offsetY = _psd[i].page().yOff();\n layer = i;\n break;\n }\n }\n }\n Magick::Image container(Magick::Geometry(width,height),Magick::Color(\"rgba(0,0,0,0)\"));\n container.composite(_psd[layer],offsetX,offsetY,Magick::OverCompositeOp);\n container.flip();\n container.write(0,0,width,height,\"RGBA\",Magick::FloatPixel,pixelData);\n}\n\nbool ReadPSDPlugin::getFrameBounds(const std::string& \/*filename*\/,\n OfxTime \/*time*\/,\n OfxRectI *bounds,\n double *par,\n std::string *\/*error*\/)\n{\n #ifdef DEBUG\n std::cout << \"getFrameBounds ...\" << std::endl;\n #endif\n if (_psd[0].columns()>0 && _psd[0].rows()>0) {\n bounds->x1 = 0;\n bounds->x2 = _psd[0].columns();\n bounds->y1 = 0;\n bounds->y2 = _psd[0].rows();\n *par = 1.0;\n }\n #ifdef DEBUG\n std::cout << \"bounds \" << bounds->x2 << \"x\" << bounds->y2 << std::endl;\n #endif\n return true;\n}\n\nvoid ReadPSDPlugin::restoreState(const std::string& filename)\n{\n #ifdef DEBUG\n std::cout << \"restoreState ...\" << std::endl;\n #endif\n _psd.clear();\n try {\n Magick::readImages(&_psd, filename);\n }\n catch(Magick::Exception) {\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n if (_psd[0].columns()>0 && _psd[0].rows()>0)\n _filename = filename;\n else {\n _psd.clear();\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n}\n\nvoid ReadPSDPlugin::onInputFileChanged(const std::string& newFile,\n OFX::PreMultiplicationEnum *premult,\n OFX::PixelComponentEnum *components,int *\/*componentCount*\/)\n{\n #ifdef DEBUG\n std::cout << \"onInputFileChanged ...\" << std::endl;\n #endif\n assert(premult && components);\n if (newFile!=_filename)\n restoreState(newFile);\n # ifdef OFX_IO_USING_OCIO\n switch(_psd[0].colorSpace()) {\n case Magick::RGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::sRGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::scRGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::Rec709LumaColorspace:\n _ocio->setInputColorspace(\"Rec709\");\n break;\n case Magick::Rec709YCbCrColorspace:\n _ocio->setInputColorspace(\"Rec709\");\n break;\n default:\n _ocio->setInputColorspace(\"Linear\");\n break;\n }\n # endif \/\/ OFX_IO_USING_OCIO\n *components = OFX::ePixelComponentRGBA;\n *premult = OFX::eImageOpaque;\n}\n\nusing namespace OFX;\n\nmDeclareReaderPluginFactory(ReadPSDPluginFactory, {}, {}, false);\n\n\/** @brief The basic describe function, passed a plugin descriptor *\/\nvoid ReadPSDPluginFactory::describe(OFX::ImageEffectDescriptor &desc)\n{\n GenericReaderDescribe(desc, kSupportsTiles, kIsMultiPlanar);\n desc.setLabel(kPluginName);\n\n #ifdef OFX_EXTENSIONS_TUTTLE\n const char* extensions[] = {\"psd\", \"xcf\", NULL};\n desc.addSupportedExtensions(extensions);\n desc.setPluginEvaluation(92);\n #endif\n\n std::string magickV = MagickCore::GetMagickVersion(NULL);\n desc.setPluginDescription(\"Read Photoshop\/GIMP\/Cinepaint image formats.\\n\\nWritten by Ole-André Rodlie <olear@fxarena.net>\\n\\nPowered by \"+magickV);\n}\n\n\/** @brief The describe in context function, passed a plugin descriptor and a context *\/\nvoid ReadPSDPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum context)\n{\n PageParamDescriptor *page = GenericReaderDescribeInContextBegin(desc, context, isVideoStreamPlugin(), kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles);\n GenericReaderDescribeInContextEnd(desc, context, page, \"reference\", \"reference\");\n}\n\n\/** @brief The create instance function, the plugin must return an object derived from the \\ref OFX::ImageEffect class *\/\nImageEffect* ReadPSDPluginFactory::createInstance(OfxImageEffectHandle handle,\n ContextEnum \/*context*\/)\n{\n ReadPSDPlugin* ret = new ReadPSDPlugin(handle);\n ret->restoreStateFromParameters();\n return ret;\n}\n\nvoid getReadPSDPluginID(OFX::PluginFactoryArray &ids)\n{\n static ReadPSDPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);\n ids.push_back(&p);\n}\n<commit_msg>ReadPSD: get icc profiles and add to choice param<commit_after>\/*\n\nopenfx-arena - https:\/\/github.com\/olear\/openfx-arena\n\nCopyright (c) 2015, Ole-André Rodlie <olear@fxarena.net>\nCopyright (c) 2015, FxArena DA <mail@fxarena.net>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Neither the name of FxArena DA 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* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\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 ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"ReadPSD.h\"\n#include <iostream>\n#include <string>\n#include <Magick++.h>\n#include \"GenericReader.h\"\n#include \"GenericOCIO.h\"\n#include \"ofxsMacros.h\"\n#include <lcms2.h>\n#include <dirent.h>\n\n#ifdef OFX_IO_USING_OCIO\n#include <OpenColorIO\/OpenColorIO.h>\n#endif\n\n#define kPluginName \"ReadPSD\"\n#define kPluginGrouping \"Image\/Readers\"\n#define kPluginIdentifier \"net.fxarena.openfx.ReadPSD\"\n#define kPluginVersionMajor 1\n#define kPluginVersionMinor 7\n\n#define kSupportsRGBA true\n#define kSupportsRGB false\n#define kSupportsAlpha false\n#define kSupportsTiles false\n#define kIsMultiPlanar true\n\n#define kParamICC \"icc\"\n#define kParamICCLabel \"ICC profile\"\n#define kParamICCHint \"Convert to the selected ICC profile\"\n\nvoid _getProFiles(std::vector<std::string> &files, bool desc) {\n std::vector<std::string> paths;\n paths.push_back(\"\/usr\/share\/color\/icc\/\");\n paths.push_back(\"\\\\Windows\\\\system32\\\\spool\\\\drivers\\\\color\\\\\");\n paths.push_back(\"\/Library\/ColorSync\/Profiles\/\");\n for (unsigned int i = 0; i < paths.size(); i++) {\n DIR *dp;\n struct dirent *dirp;\n if((dp=opendir(paths[i].c_str())) != NULL) {\n while ((dirp=readdir(dp)) != NULL) {\n std::string proFile = dirp->d_name;\n std::ostringstream profileDesc;\n cmsHPROFILE lcmsProfile;\n char buffer[500];\n std::ostringstream path;\n bool rgb = false;\n path << paths[i] << proFile;\n lcmsProfile = cmsOpenProfileFromFile(path.str().c_str(), \"r\");\n if (lcmsProfile) {\n cmsGetProfileInfoASCII(lcmsProfile, cmsInfoDescription, \"en\", \"US\", buffer, 500);\n profileDesc << buffer;\n if(cmsGetColorSpace(lcmsProfile) == cmsSigRgbData)\n rgb = true;\n }\n cmsCloseProfile(lcmsProfile);\n if (!profileDesc.str().empty() && rgb) {\n if (desc)\n files.push_back(profileDesc.str());\n else\n files.push_back(std::string(dirp->d_name));\n }\n }\n }\n closedir(dp);\n }\n}\n\nclass ReadPSDPlugin : public GenericReaderPlugin\n{\npublic:\n ReadPSDPlugin(OfxImageEffectHandle handle);\n virtual ~ReadPSDPlugin();\nprivate:\n virtual bool isVideoStream(const std::string& \/*filename*\/) OVERRIDE FINAL { return false; }\n virtual void decode(const std::string& filename, OfxTime time, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds,\n OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, int rowBytes) OVERRIDE FINAL\n {\n std::string rawComps;\n switch (pixelComponents) {\n case OFX::ePixelComponentAlpha:\n rawComps = kOfxImageComponentAlpha;\n break;\n case OFX::ePixelComponentRGB:\n rawComps = kOfxImageComponentRGB;\n break;\n case OFX::ePixelComponentRGBA:\n rawComps = kOfxImageComponentRGBA;\n break;\n default:\n OFX::throwSuiteStatusException(kOfxStatFailed);\n return;\n }\n decodePlane(filename, time, renderWindow, pixelData, bounds, pixelComponents, pixelComponentCount, rawComps, rowBytes);\n }\n virtual void getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents) OVERRIDE FINAL;\n virtual void decodePlane(const std::string& filename, OfxTime time, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds, OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, const std::string& rawComponents, int rowBytes) OVERRIDE FINAL;\n virtual bool getFrameBounds(const std::string& filename, OfxTime time, OfxRectI *bounds, double *par, std::string *error) OVERRIDE FINAL;\n virtual void restoreState(const std::string& filename) OVERRIDE FINAL;\n virtual void onInputFileChanged(const std::string& newFile, OFX::PreMultiplicationEnum *premult, OFX::PixelComponentEnum *components, int *componentCount) OVERRIDE FINAL;\n std::string _filename;\n std::vector<Magick::Image> _psd;\n OFX::ChoiceParam *_icc;\n};\n\nReadPSDPlugin::ReadPSDPlugin(OfxImageEffectHandle handle)\n: GenericReaderPlugin(handle, kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles,\n#ifdef OFX_EXTENSIONS_NUKE\n(OFX::getImageEffectHostDescription() && OFX::getImageEffectHostDescription()->isMultiPlanar) ? kIsMultiPlanar : false\n#else\nfalse\n#endif\n)\n{\n Magick::InitializeMagick(NULL);\n\n _icc = fetchChoiceParam(kParamICC);\n assert(_outputComponents && _icc);\n}\n\nReadPSDPlugin::~ReadPSDPlugin()\n{\n}\n\nvoid ReadPSDPlugin::getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents)\n{\n #ifdef DEBUG\n std::cout << \"getClipComponents ...\" << std::endl;\n #endif\n assert(isMultiPlanar());\n clipComponents.addClipComponents(*_outputClip, getOutputComponents());\n clipComponents.setPassThroughClip(NULL, args.time, args.view);\n if (_psd.size()>0) {\n int startLayer = 0;\n if (_psd[0].format()==\"Adobe Photoshop bitmap\")\n startLayer++;\n for (int i = startLayer; i < (int)_psd.size(); i++) {\n std::ostringstream layerName;\n layerName << _psd[i].label();\n if (layerName.str().empty())\n layerName << \"Image Layer #\" << i; \/\/ add a label if empty\n std::string component(kNatronOfxImageComponentsPlane);\n component.append(layerName.str());\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"R\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"G\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"B\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"A\");\n clipComponents.addClipComponents(*_outputClip, component);\n }\n }\n}\n\nvoid ReadPSDPlugin::decodePlane(const std::string& \/*filename*\/, OfxTime time, const OfxRectI& \/*renderWindow*\/, float *pixelData, const OfxRectI& bounds,\n OFX::PixelComponentEnum \/*pixelComponents*\/, int \/*pixelComponentCount*\/, const std::string& rawComponents, int \/*rowBytes*\/)\n{\n #ifdef DEBUG\n std::cout << \"decodePlane ...\" << std::endl;\n #endif\n int offsetX = 0;\n int offsetY = 0;\n int layer = 0;\n int width = bounds.x2;\n int height = bounds.y2;\n std::string layerName;\n int iccProfileID = 0;\n std::vector<std::string> layerChannels = OFX::mapPixelComponentCustomToLayerChannels(rawComponents);\n int numChannels = layerChannels.size();\n _icc->getValueAtTime(time, iccProfileID);\n if (numChannels==5) \/\/ layer+R+G+B+A\n layerName=layerChannels[0];\n if (!layerName.empty()) {\n for (size_t i = 0; i < _psd.size(); i++) {\n bool foundLayer = false;\n std::ostringstream psdLayer;\n psdLayer << \"Image Layer #\" << i;\n if (_psd[i].label()==layerName)\n foundLayer = true;\n if (psdLayer.str()==layerName && !foundLayer)\n foundLayer = true;\n if (foundLayer) {\n if ((int)_psd[i].columns()!=bounds.x2)\n offsetX = _psd[i].page().xOff();\n if ((int)_psd[i].rows()!=bounds.y2)\n offsetY = _psd[i].page().yOff();\n layer = i;\n break;\n }\n }\n }\n Magick::Image container(Magick::Geometry(width,height),Magick::Color(\"rgba(0,0,0,0)\"));\n container.composite(_psd[layer],offsetX,offsetY,Magick::OverCompositeOp);\n container.flip();\n container.write(0,0,width,height,\"RGBA\",Magick::FloatPixel,pixelData);\n}\n\nbool ReadPSDPlugin::getFrameBounds(const std::string& \/*filename*\/,\n OfxTime \/*time*\/,\n OfxRectI *bounds,\n double *par,\n std::string *\/*error*\/)\n{\n #ifdef DEBUG\n std::cout << \"getFrameBounds ...\" << std::endl;\n #endif\n if (_psd[0].columns()>0 && _psd[0].rows()>0) {\n bounds->x1 = 0;\n bounds->x2 = _psd[0].columns();\n bounds->y1 = 0;\n bounds->y2 = _psd[0].rows();\n *par = 1.0;\n }\n #ifdef DEBUG\n std::cout << \"bounds \" << bounds->x2 << \"x\" << bounds->y2 << std::endl;\n #endif\n return true;\n}\n\nvoid ReadPSDPlugin::restoreState(const std::string& filename)\n{\n #ifdef DEBUG\n std::cout << \"restoreState ...\" << std::endl;\n #endif\n _psd.clear();\n try {\n Magick::readImages(&_psd, filename);\n }\n catch(Magick::Exception) {\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n if (_psd[0].columns()>0 && _psd[0].rows()>0) {\n _filename = filename;\n if (_psd[0].iccColorProfile().length()>0) { \/\/ image has an icc profile\n }\n }\n else {\n _psd.clear();\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n}\n\nvoid ReadPSDPlugin::onInputFileChanged(const std::string& newFile,\n OFX::PreMultiplicationEnum *premult,\n OFX::PixelComponentEnum *components,int *\/*componentCount*\/)\n{\n #ifdef DEBUG\n std::cout << \"onInputFileChanged ...\" << std::endl;\n #endif\n assert(premult && components);\n if (newFile!=_filename)\n restoreState(newFile);\n # ifdef OFX_IO_USING_OCIO\n switch(_psd[0].colorSpace()) {\n case Magick::RGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::sRGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::scRGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::Rec709LumaColorspace:\n _ocio->setInputColorspace(\"Rec709\");\n break;\n case Magick::Rec709YCbCrColorspace:\n _ocio->setInputColorspace(\"Rec709\");\n break;\n default:\n _ocio->setInputColorspace(\"Linear\");\n break;\n }\n # endif \/\/ OFX_IO_USING_OCIO\n *components = OFX::ePixelComponentRGBA;\n *premult = OFX::eImageOpaque;\n}\n\nusing namespace OFX;\n\nmDeclareReaderPluginFactory(ReadPSDPluginFactory, {}, {}, false);\n\n\/** @brief The basic describe function, passed a plugin descriptor *\/\nvoid ReadPSDPluginFactory::describe(OFX::ImageEffectDescriptor &desc)\n{\n GenericReaderDescribe(desc, kSupportsTiles, kIsMultiPlanar);\n desc.setLabel(kPluginName);\n\n #ifdef OFX_EXTENSIONS_TUTTLE\n const char* extensions[] = {\"psd\", \"xcf\", NULL};\n desc.addSupportedExtensions(extensions);\n desc.setPluginEvaluation(92);\n #endif\n\n std::string magickV = MagickCore::GetMagickVersion(NULL);\n desc.setPluginDescription(\"Read Photoshop\/GIMP\/Cinepaint image formats.\\n\\nWritten by Ole-André Rodlie <olear@fxarena.net>\\n\\nPowered by \"+magickV);\n}\n\n\/** @brief The describe in context function, passed a plugin descriptor and a context *\/\nvoid ReadPSDPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum context)\n{\n PageParamDescriptor *page = GenericReaderDescribeInContextBegin(desc, context, isVideoStreamPlugin(), kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles);\n {\n ChoiceParamDescriptor* param = desc.defineChoiceParam(kParamICC);\n param->setLabel(kParamICCLabel);\n param->setHint(kParamICCHint);\n param->appendOption(\"Undefined\");\n std::vector<std::string> profiles;\n _getProFiles(profiles, true);\n for (unsigned int i = 0;i < profiles.size();i++)\n param->appendOption(profiles[i]);\n page->addChild(*param);\n }\n GenericReaderDescribeInContextEnd(desc, context, page, \"reference\", \"reference\");\n}\n\n\/** @brief The create instance function, the plugin must return an object derived from the \\ref OFX::ImageEffect class *\/\nImageEffect* ReadPSDPluginFactory::createInstance(OfxImageEffectHandle handle,\n ContextEnum \/*context*\/)\n{\n ReadPSDPlugin* ret = new ReadPSDPlugin(handle);\n ret->restoreStateFromParameters();\n return ret;\n}\n\nvoid getReadPSDPluginID(OFX::PluginFactoryArray &ids)\n{\n static ReadPSDPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);\n ids.push_back(&p);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra\n *\n * This file is part of Essentia\n *\n * Essentia is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License as published by the Free\n * Software Foundation (FSF), either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the Affero GNU General Public License\n * version 3 along with this program. If not, see http:\/\/www.gnu.org\/licenses\/\n *\/\n\n#include \"vibrato.h\"\n#include \"essentiamath.h\"\n\nusing namespace std;\nusing namespace essentia;\nusing namespace standard;\n\nconst char* Vibrato::name = \"Vibrato\";\nconst char* Vibrato::category = \"Pitch\";\nconst char* Vibrato::description = DOC(\"This algorithm detects the presence of vibrato and estimates its parameters given a pitch contour [Hz]. The result is the vibrato frequency in Hz and the extend (peak to peak) in cents. If no vibrato is detected in a frame, the output of both values is zero.\\n\"\n\"\\n\"\n\"This algorithm should be given the outputs of a pitch estimator, i.e. PredominantMelody, PitchYinFFT or PitchMelodia and the corresponding sample rate with which it was computed.\\n\"\n\"\\n\"\n\"The algorithm is an extended version of the vocal vibrato detection in PerdominantMelody.\"\n\"\\n\"\n\"References:\\n\"\n\" [1] J. Salamon and E. Gómez, \\\"Melody extraction from polyphonic music\\n\"\n\" signals using pitch contour characteristics,\\\" IEEE Transactions on Audio,\\n\"\n\" Speech, and Language Processing, vol. 20, no. 6, pp. 1759–1770, 2012.\\n\\n\");\n\n\nvoid Vibrato::configure() {\n \n _minFrequency = parameter(\"minFrequency\").toReal();\n _maxFrequency = parameter(\"maxFrequency\").toReal();\n _minExtend = parameter(\"minExtend\").toReal();\n _maxExtend = parameter(\"maxExtend\").toReal();\n _sampleRate = parameter(\"sampleRate\").toReal();\n \n frameSize = int(0.350 * _sampleRate);\n fftSize = 4*frameSize;\n \n frameCutter->configure(\"frameSize\", frameSize, \"hopSize\", 1, \"startFromZero\", true);\n window->configure(\"type\", \"hann\", \"zeroPadding\", 3*frameSize);\n spectrum->configure(\"size\", fftSize);\n spectralPeaks->configure(\"sampleRate\", _sampleRate, \"maxPeaks\", 3, \"orderBy\", \"magnitude\");\n}\n\nvoid Vibrato::compute() {\n \n Real vibdBDropLobe = 15.;\n Real vibdBDropSecondPeak = 20.;\n \n const vector<Real>& pitch = _pitch.get();\n vector<Real>& vibratoFrequency =_vibratoFrequency.get();\n vector<Real>& vibratoExtend = _vibratoExtend.get();\n\n \/\/ if pitch vector is empty\n if (pitch.empty()) {\n vibratoFrequency.clear();\n vibratoExtend.clear();\n return;\n }\n\n vibratoFrequency.assign(pitch.size(), 0.);\n vibratoExtend.assign(pitch.size(), 0.);\n \n vector<Real> pitchP;\n \n \/\/ set negative pitch values to zero\n for (int i=0; i<(int)pitch.size(); i++) {\n if (pitch[i]<0) {\n pitchP.push_back(0.0);\n } else {\n pitchP.push_back(pitch[i]);\n }\n }\n\n \/\/ get contour start and end indices\n vector<Real> startC, endC;\n if (pitchP[0]>0){\n startC.push_back(0);\n }\n for (int i=0; i<(int)pitchP.size()-1; i++) {\n if (pitchP[i+1]>0 && pitchP[i]==0){\n startC.push_back(i+1);\n }\n if (pitchP[i+1]==0 && pitchP[i]>0) {\n endC.push_back(i);\n }\n }\n if (endC.size()<startC.size()) {\n endC.push_back(pitch.size()-1);\n }\n\n \/\/ iterate over contour segments\n for (int i=0; i<(int)startC.size(); i++) {\n \/\/ get a segment in cents\n vector<Real> contour;\n for (int ii=startC[i]; ii<=endC[i]; ii++) {\n contour.push_back(1200*log2(pitch[ii]\/55.0));\n }\n \n \/\/ setup algorithm I\/O\n vector<Real> frame;\n frameCutter->input(\"signal\").set(contour);\n frameCutter->output(\"frame\").set(frame);\n vector<Real> windowedFrame;\n window->input(\"frame\").set(frame);\n window->output(\"frame\").set(windowedFrame);\n vector<Real> vibSpectrum;\n spectrum->input(\"frame\").set(windowedFrame);\n spectrum->output(\"spectrum\").set(vibSpectrum);\n vector<Real> peakFrequencies, peakMagnitudes;\n spectralPeaks->input(\"spectrum\").set(vibSpectrum);\n spectralPeaks->output(\"frequencies\").set(peakFrequencies);\n spectralPeaks->output(\"magnitudes\").set(peakMagnitudes);\n frameCutter->reset();\n \n int frameNumber=0;\n \n \/\/ frame-wise processing\n while (true) {\n \n \/\/get a frame\n frameCutter->compute();\n frameNumber++;\n \n if(!frame.size()) {\n break;\n }\n \n \/\/ subtract mean pitch from frame\n Real m = mean(frame, 0, frame.size()-1);\n for (int ii=0; ii<(int)frame.size(); ii++) {\n frame[ii]-=m;\n }\n \n \/\/ spectral peaks\n window->compute();\n spectrum->compute();\n spectralPeaks->compute();\n \n int numberPeaks = peakFrequencies.size();\n if (!numberPeaks) {\n continue;\n }\n \n if (peakFrequencies[0] < _minFrequency || peakFrequencies[0] > _maxFrequency) {\n continue;\n }\n\n if (numberPeaks > 1) { \/\/ there is at least one extra peak\n if (peakFrequencies[1] <= _maxFrequency) {\n continue;\n }\n if (20 * log10(peakMagnitudes[0]\/peakMagnitudes[1]) < vibdBDropLobe) {\n continue;\n }\n }\n \n if (numberPeaks > 2) { \/\/ there is a second extra peak\n if (peakFrequencies[2] <= _maxFrequency) {\n continue;\n }\n if (20 * log10(peakMagnitudes[0]\/peakMagnitudes[2]) < vibdBDropSecondPeak) {\n continue;\n }\n }\n \n Real ext = frame[argmax(frame)] + abs(frame[argmin(frame)]);\n if (ext<_minExtend || ext>_maxExtend){\n continue;\n }\n \n for (int ii=startC[i]+frameNumber-1; ii<startC[i]+frameNumber+frameSize-1; ii++) {\n vibratoFrequency[ii]=peakFrequencies[0];\n vibratoExtend[ii]=ext;\n }\n }\n }\n}\n\nVibrato::~Vibrato() {\n delete frameCutter;\n delete window;\n delete spectrum;\n delete spectralPeaks;\n}\n\nvoid Vibrato::reset() {\n Algorithm::reset();\n frameCutter->reset();\n spectralPeaks->reset();\n spectrum->reset();\n window->reset();\n}\n<commit_msg>Fix memory bug in Vibrato<commit_after>\/*\n * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra\n *\n * This file is part of Essentia\n *\n * Essentia is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License as published by the Free\n * Software Foundation (FSF), either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the Affero GNU General Public License\n * version 3 along with this program. If not, see http:\/\/www.gnu.org\/licenses\/\n *\/\n\n#include \"vibrato.h\"\n#include \"essentiamath.h\"\n\nusing namespace std;\nusing namespace essentia;\nusing namespace standard;\n\nconst char* Vibrato::name = \"Vibrato\";\nconst char* Vibrato::category = \"Pitch\";\nconst char* Vibrato::description = DOC(\"This algorithm detects the presence of vibrato and estimates its parameters given a pitch contour [Hz]. The result is the vibrato frequency in Hz and the extend (peak to peak) in cents. If no vibrato is detected in a frame, the output of both values is zero.\\n\"\n\"\\n\"\n\"This algorithm should be given the outputs of a pitch estimator, i.e. PredominantMelody, PitchYinFFT or PitchMelodia and the corresponding sample rate with which it was computed.\\n\"\n\"\\n\"\n\"The algorithm is an extended version of the vocal vibrato detection in PerdominantMelody.\"\n\"\\n\"\n\"References:\\n\"\n\" [1] J. Salamon and E. Gómez, \\\"Melody extraction from polyphonic music\\n\"\n\" signals using pitch contour characteristics,\\\" IEEE Transactions on Audio,\\n\"\n\" Speech, and Language Processing, vol. 20, no. 6, pp. 1759–1770, 2012.\\n\\n\");\n\n\nvoid Vibrato::configure() {\n \n _minFrequency = parameter(\"minFrequency\").toReal();\n _maxFrequency = parameter(\"maxFrequency\").toReal();\n _minExtend = parameter(\"minExtend\").toReal();\n _maxExtend = parameter(\"maxExtend\").toReal();\n _sampleRate = parameter(\"sampleRate\").toReal();\n \n frameSize = int(0.350 * _sampleRate);\n fftSize = 4*frameSize;\n \n frameCutter->configure(\"frameSize\", frameSize, \"hopSize\", 1, \"startFromZero\", true);\n window->configure(\"type\", \"hann\", \"zeroPadding\", 3*frameSize);\n spectrum->configure(\"size\", fftSize);\n spectralPeaks->configure(\"sampleRate\", _sampleRate, \"maxPeaks\", 3, \"orderBy\", \"magnitude\");\n}\n\nvoid Vibrato::compute() {\n \n Real vibdBDropLobe = 15.;\n Real vibdBDropSecondPeak = 20.;\n \n const vector<Real>& pitch = _pitch.get();\n vector<Real>& vibratoFrequency =_vibratoFrequency.get();\n vector<Real>& vibratoExtend = _vibratoExtend.get();\n\n \/\/ if pitch vector is empty\n if (pitch.empty()) {\n vibratoFrequency.clear();\n vibratoExtend.clear();\n return;\n }\n\n vibratoFrequency.assign(pitch.size(), 0.);\n vibratoExtend.assign(pitch.size(), 0.);\n \n vector<Real> pitchP;\n \n \/\/ set negative pitch values to zero\n for (int i=0; i<(int)pitch.size(); i++) {\n if (pitch[i]<0) {\n pitchP.push_back(0.0);\n } else {\n pitchP.push_back(pitch[i]);\n }\n }\n\n \/\/ get contour start and end indices\n vector<Real> startC, endC;\n if (pitchP[0]>0){\n startC.push_back(0);\n }\n for (int i=0; i<(int)pitchP.size()-1; i++) {\n if (pitchP[i+1]>0 && pitchP[i]==0) {\n startC.push_back(i+1);\n }\n if (pitchP[i+1]==0 && pitchP[i]>0) {\n endC.push_back(i);\n }\n }\n if (endC.size()<startC.size()) {\n endC.push_back(pitch.size()-1);\n }\n\n \/\/ iterate over contour segments\n for (int i=0; i<(int)startC.size(); i++) {\n \/\/ get a segment in cents\n vector<Real> contour;\n for (int ii=startC[i]; ii<=endC[i]; ii++) {\n contour.push_back(1200*log2(pitch[ii]\/55.0));\n }\n \n \/\/ setup algorithm I\/O\n vector<Real> frame;\n frameCutter->input(\"signal\").set(contour);\n frameCutter->output(\"frame\").set(frame);\n vector<Real> windowedFrame;\n window->input(\"frame\").set(frame);\n window->output(\"frame\").set(windowedFrame);\n vector<Real> vibSpectrum;\n spectrum->input(\"frame\").set(windowedFrame);\n spectrum->output(\"spectrum\").set(vibSpectrum);\n vector<Real> peakFrequencies, peakMagnitudes;\n spectralPeaks->input(\"spectrum\").set(vibSpectrum);\n spectralPeaks->output(\"frequencies\").set(peakFrequencies);\n spectralPeaks->output(\"magnitudes\").set(peakMagnitudes);\n frameCutter->reset();\n \n int frameNumber=0;\n \n \/\/ frame-wise processing\n while (true) {\n \n \/\/get a frame\n frameCutter->compute();\n frameNumber++;\n \n if(!frame.size()) {\n break;\n }\n\n \/\/ subtract mean pitch from frame\n Real m = mean(frame, 0, frame.size()-1);\n for (int ii=0; ii<(int)frame.size(); ii++) {\n frame[ii]-=m;\n }\n \n \/\/ spectral peaks\n window->compute();\n spectrum->compute();\n spectralPeaks->compute();\n \n int numberPeaks = peakFrequencies.size();\n if (!numberPeaks) {\n continue;\n }\n \n if (peakFrequencies[0] < _minFrequency || peakFrequencies[0] > _maxFrequency) {\n continue;\n }\n\n if (numberPeaks > 1) { \/\/ there is at least one extra peak\n if (peakFrequencies[1] <= _maxFrequency) {\n continue;\n }\n if (20 * log10(peakMagnitudes[0]\/peakMagnitudes[1]) < vibdBDropLobe) {\n continue;\n }\n }\n \n if (numberPeaks > 2) { \/\/ there is a second extra peak\n if (peakFrequencies[2] <= _maxFrequency) {\n continue;\n }\n if (20 * log10(peakMagnitudes[0]\/peakMagnitudes[2]) < vibdBDropSecondPeak) {\n continue;\n }\n }\n \n Real ext = frame[argmax(frame)] + abs(frame[argmin(frame)]);\n if (ext<_minExtend || ext>_maxExtend){\n continue;\n }\n\n int ii = startC[i]+frameNumber-1;\n vibratoFrequency[ii] = peakFrequencies[0];\n vibratoExtend[ii] = ext;\n \/\/ NOTE: no need to loop over the frame, as the hopSize is 1\n \/*\n for (int ii=startC[i]+frameNumber-1; ii<startC[i]+frameNumber-1+frameSize; ii++) { \n vibratoFrequency[ii]=peakFrequencies[0];\n vibratoExtend[ii]=ext;\n }\n *\/\n }\n }\n}\n\nVibrato::~Vibrato() {\n delete frameCutter;\n delete window;\n delete spectrum;\n delete spectralPeaks;\n}\n\nvoid Vibrato::reset() {\n Algorithm::reset();\n frameCutter->reset();\n spectralPeaks->reset();\n spectrum->reset();\n window->reset();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Copyright (C) 2011-2013 Michael Krufky\n *\n * Author: Michael Krufky <mkrufky@linuxtv.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 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 *****************************************************************************\/\n\n#define DBG 0\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"functions.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"desc\"\n\n#include \"dvbpsi\/dr_48.h\" \/* service descriptor *\/\n#include \"dvbpsi\/dr_4d.h\" \/* short event descriptor *\/\n#include \"dvbpsi\/dr_62.h\" \/* frequency list descriptor *\/\n#include \"dvbpsi\/dr_83.h\" \/* LCN descriptor *\/\n\n#include \"desc.h\"\n\n#define dprintf(fmt, arg...) __dprintf(DBG_DESC, fmt, ##arg)\n\n#define DT_Service 0x48\n#define DT_ShortEvent 0x4d\n#define DT_Teletext 0x56\n#define DT_FrequencyList 0x62\n#define DT_LogicalChannelNumber 0x83\n\n\ndesc::desc()\n\/\/ : f_kill_thread(false)\n{\n\tdprintf(\"()\");\n}\n\ndesc::~desc()\n{\n\tdprintf(\"()\");\n}\n\nbool desc::service(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_Service)\n\t\treturn false;\n\n\tdvbpsi_service_dr_t* dr = dvbpsi_DecodeServiceDr(p_descriptor);\n\tif (!dr) return false;\n\n\tget_descriptor_text(dr->i_service_provider_name, dr->i_service_provider_name_length, provider_name);\n\tget_descriptor_text(dr->i_service_name, dr->i_service_name_length, service_name);\n\n\tdprintf(\"%s, %s\", provider_name, service_name);\n\n\treturn true;\n}\n\nbool desc::short_event(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_ShortEvent)\n\t\treturn false;\n\n\tdvbpsi_short_event_dr_t* dr = dvbpsi_DecodeShortEventDr(p_descriptor);\n\tif (!dr) return false;\n\n\tmemcpy(_4d.lang, dr->i_iso_639_code, 3);\n\tget_descriptor_text(dr->i_event_name, dr->i_event_name_length, _4d.name);\n\tget_descriptor_text(dr->i_text, dr->i_text_length, _4d.text);\n\n\tdprintf(\"%s, %s, %s\", _4d.lang, _4d.name, _4d.text);\n\n\treturn true;\n}\n\n\nbool desc::freq_list(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_FrequencyList)\n\t\treturn false;\n\n\tdvbpsi_frequency_list_dr_t* dr = dvbpsi_DecodeFrequencyListDr(p_descriptor);\n\tif (!dr) return false;\n\n\tfor (int i = 0; i < dr->i_number_of_frequencies; ++i) {\n#if 0\n\t\t= dr->p_center_frequencies[i]\n#else\n\t\tdprintf(\"%d\", dr->p_center_frequencies[i]);\n#endif\n\t}\n\treturn true;\n}\n\nbool desc::_lcn(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_LogicalChannelNumber)\n\t\treturn false;\n\n\tdvbpsi_lcn_dr_t* dr = dvbpsi_DecodeLCNDr(p_descriptor);\n\tif (!dr) return false;\n\n\tfor (int i = 0; i < dr->i_number_of_entries; i ++) {\n#if 0\n\t\t= lcn->p_entries[i].i_service_id;\n\t\t= lcn->p_entries[i].i_logical_channel_number;\n#else\n\t\tlcn[dr->p_entries[i].i_service_id] = dr->p_entries[i].i_logical_channel_number;\n\t\tdprintf(\"%d, %d\", dr->p_entries[i].i_service_id, lcn[dr->p_entries[i].i_service_id]);\n#endif\n\t}\n\n\treturn true;\n}\n\nvoid desc::decode(dvbpsi_descriptor_t* p_descriptor)\n{\n\twhile (p_descriptor) {\n\t\tswitch (p_descriptor->i_tag) {\n\t\tcase DT_Service:\n\t\t\tservice(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_ShortEvent:\n\t\t\tshort_event(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_FrequencyList:\n\t\t\tfreq_list(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_LogicalChannelNumber:\n\t\t\t_lcn(p_descriptor);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdprintf(\"unknown descriptor tag: %02x\", p_descriptor->i_tag);\n\t\t\tbreak;\n\t\t}\n\t\tp_descriptor = p_descriptor->p_next;\n\t}\n}\n<commit_msg>desc: display debug message if decoder failed<commit_after>\/*****************************************************************************\n * Copyright (C) 2011-2013 Michael Krufky\n *\n * Author: Michael Krufky <mkrufky@linuxtv.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 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 *****************************************************************************\/\n\n#define DBG 0\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"functions.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"desc\"\n\n#include \"dvbpsi\/dr_48.h\" \/* service descriptor *\/\n#include \"dvbpsi\/dr_4d.h\" \/* short event descriptor *\/\n#include \"dvbpsi\/dr_62.h\" \/* frequency list descriptor *\/\n#include \"dvbpsi\/dr_83.h\" \/* LCN descriptor *\/\n\n#include \"desc.h\"\n\n#define dprintf(fmt, arg...) __dprintf(DBG_DESC, fmt, ##arg)\n\n#define DT_Service 0x48\n#define DT_ShortEvent 0x4d\n#define DT_Teletext 0x56\n#define DT_FrequencyList 0x62\n#define DT_LogicalChannelNumber 0x83\n\n#define desc_dr_failed(dr)\t\t\t\\\n ({\t\t\t\t\t\t\\\n bool __ret = !dr;\t\t\t\t\\\n if (__ret) dprintf(\"decoder failed!\");\t\\\n __ret;\t\t\t\t\t\\\n })\n\ndesc::desc()\n\/\/ : f_kill_thread(false)\n{\n\tdprintf(\"()\");\n}\n\ndesc::~desc()\n{\n\tdprintf(\"()\");\n}\n\nbool desc::service(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_Service)\n\t\treturn false;\n\n\tdvbpsi_service_dr_t* dr = dvbpsi_DecodeServiceDr(p_descriptor);\n\tif (desc_dr_failed(dr)) return false;\n\n\tget_descriptor_text(dr->i_service_provider_name, dr->i_service_provider_name_length, provider_name);\n\tget_descriptor_text(dr->i_service_name, dr->i_service_name_length, service_name);\n\n\tdprintf(\"%s, %s\", provider_name, service_name);\n\n\treturn true;\n}\n\nbool desc::short_event(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_ShortEvent)\n\t\treturn false;\n\n\tdvbpsi_short_event_dr_t* dr = dvbpsi_DecodeShortEventDr(p_descriptor);\n\tif (desc_dr_failed(dr)) return false;\n\n\tmemcpy(_4d.lang, dr->i_iso_639_code, 3);\n\tget_descriptor_text(dr->i_event_name, dr->i_event_name_length, _4d.name);\n\tget_descriptor_text(dr->i_text, dr->i_text_length, _4d.text);\n\n\tdprintf(\"%s, %s, %s\", _4d.lang, _4d.name, _4d.text);\n\n\treturn true;\n}\n\n\nbool desc::freq_list(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_FrequencyList)\n\t\treturn false;\n\n\tdvbpsi_frequency_list_dr_t* dr = dvbpsi_DecodeFrequencyListDr(p_descriptor);\n\tif (desc_dr_failed(dr)) return false;\n\n\tfor (int i = 0; i < dr->i_number_of_frequencies; ++i) {\n#if 0\n\t\t= dr->p_center_frequencies[i]\n#else\n\t\tdprintf(\"%d\", dr->p_center_frequencies[i]);\n#endif\n\t}\n\treturn true;\n}\n\nbool desc::_lcn(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_LogicalChannelNumber)\n\t\treturn false;\n\n\tdvbpsi_lcn_dr_t* dr = dvbpsi_DecodeLCNDr(p_descriptor);\n\tif (desc_dr_failed(dr)) return false;\n\n\tfor (int i = 0; i < dr->i_number_of_entries; i ++) {\n#if 0\n\t\t= lcn->p_entries[i].i_service_id;\n\t\t= lcn->p_entries[i].i_logical_channel_number;\n#else\n\t\tlcn[dr->p_entries[i].i_service_id] = dr->p_entries[i].i_logical_channel_number;\n\t\tdprintf(\"%d, %d\", dr->p_entries[i].i_service_id, lcn[dr->p_entries[i].i_service_id]);\n#endif\n\t}\n\n\treturn true;\n}\n\nvoid desc::decode(dvbpsi_descriptor_t* p_descriptor)\n{\n\twhile (p_descriptor) {\n\t\tswitch (p_descriptor->i_tag) {\n\t\tcase DT_Service:\n\t\t\tservice(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_ShortEvent:\n\t\t\tshort_event(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_FrequencyList:\n\t\t\tfreq_list(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_LogicalChannelNumber:\n\t\t\t_lcn(p_descriptor);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdprintf(\"unknown descriptor tag: %02x\", p_descriptor->i_tag);\n\t\t\tbreak;\n\t\t}\n\t\tp_descriptor = p_descriptor->p_next;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifndef _SYMBOL_LOADER_HXX\n#define _SYMBOL_LOADER_HXX\n\n#include <iostream>\n#include <osl\/module.h>\n#include <rtl\/ustring.hxx>\n\n#define SYM_MAP(a) { #a, (SymbolFunc *)&a }\n\ntypedef void (*SymbolFunc) (void);\n\nstruct ApiMap\n{\n const char *symName;\n SymbolFunc *refValue;\n};\n\nnamespace\n{\n const char *libNames[] = {\n \"libvlc.so.5\",\n \"libvlccore.so.5\",\n \"libvlc.dll\",\n \"libvlc.dylib\"\n };\n\n template<size_t N>\n bool tryLink( oslModule &aModule, const ApiMap ( &pMap )[N] )\n {\n for (uint i = 0; i < N; ++i)\n {\n SymbolFunc aMethod = ( SymbolFunc )osl_getFunctionSymbol\n ( aModule, OUString::createFromAscii( pMap[ i ].symName ).pData );\n if ( !aMethod )\n return false;\n\n *pMap[ i ].refValue = aMethod;\n }\n\n return true;\n }\n}\n\ntemplate<size_t N>\nbool InitApiMap( const ApiMap ( &pMap )[N] )\n{\n oslModule aModule;\n\n for (uint j = 0; j < sizeof(libNames) \/ sizeof(libNames[0]); ++j)\n {\n aModule = osl_loadModule( OUString::createFromAscii\n ( libNames[ j ] ).pData,\n SAL_LOADMODULE_DEFAULT );\n\n if( aModule == NULL)\n continue;\n\n tryLink( aModule, pMap );\n\n osl_unloadModule( aModule );\n }\n\n return false;\n}\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Fixing symbol loader. Returns true if successful. false otherwise.<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifndef _SYMBOL_LOADER_HXX\n#define _SYMBOL_LOADER_HXX\n\n#include <iostream>\n#include <osl\/module.h>\n#include <rtl\/ustring.hxx>\n\n#define SYM_MAP(a) { #a, (SymbolFunc *)&a }\n\ntypedef void (*SymbolFunc) (void);\n\nstruct ApiMap\n{\n const char *symName;\n SymbolFunc *refValue;\n};\n\nnamespace\n{\n const char *libNames[] = {\n \"libvlc.so.5\",\n \"libvlc.dll\",\n \"libvlc.dylib\"\n };\n\n template<size_t N>\n bool tryLink( oslModule &aModule, const ApiMap ( &pMap )[N] )\n {\n for (uint i = 0; i < N; ++i)\n {\n SymbolFunc aMethod = ( SymbolFunc )osl_getFunctionSymbol\n ( aModule, OUString::createFromAscii( pMap[ i ].symName ).pData );\n if ( !aMethod )\n {\n std::cerr << \"Cannot load method \" << pMap[ i ].symName << std::endl;\n *pMap[ i ].refValue = NULL;\n return false;\n }\n\n *pMap[ i ].refValue = aMethod;\n }\n\n return true;\n }\n}\n\ntemplate<size_t N>\nbool InitApiMap( const ApiMap ( &pMap )[N] )\n{\n oslModule aModule;\n\n for (uint j = 0; j < sizeof(libNames) \/ sizeof(libNames[0]); ++j)\n {\n aModule = osl_loadModule( OUString::createFromAscii\n ( libNames[ j ] ).pData,\n SAL_LOADMODULE_DEFAULT );\n\n if( aModule == NULL)\n continue;\n\n if (tryLink( aModule, pMap ))\n {\n osl_unloadModule( aModule );\n return true;\n }\n\n osl_unloadModule( aModule );\n }\n\n std::cerr << \"Cannot load libvlc\" << std::endl;\n return false;\n}\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#pragma ident \"$Id: \/\/depot\/sgl\/gpstk\/dev\/apps\/MDPtools\/NavProc.cpp#7 $\"\n\n\/*\n Think, navdmp for mdp, with bonus output that you get data from all code\/carrier\n combos.\n*\/\n\n#include \"Geodetic.hpp\"\n#include \"NavProc.hpp\"\n\n#include \"FormatConversionFunctions.hpp\"\n\nusing namespace std;\nusing namespace gpstk;\nusing namespace gpstk::StringUtils;\n\n\n\/\/-----------------------------------------------------------------------------\nMDPNavProcessor::MDPNavProcessor(gpstk::MDPStream& in, std::ofstream& out)\n : MDPProcessor(in, out),\n firstNav(true), almOut(false), ephOut(false),\n badNavSubframeCount(0), navSubframeCount(0)\n{\n timeFormat = \"%4Y\/%03j\/%02H:%02M:%02S\";\n}\n\n\n\/\/-----------------------------------------------------------------------------\nMDPNavProcessor::~MDPNavProcessor()\n{\n using gpstk::RangeCode;\n using gpstk::CarrierCode;\n using gpstk::StringUtils::asString;\n \n out << \"Done processing data.\" << endl << endl;\n\n out << endl << \"Navigation Subframe message summary:\" << endl;\n if (firstNav)\n out << \" No Navigation Subframe messages processed.\" << endl;\n else\n {\n out << \" navSubframeCount: \" << navSubframeCount << endl;\n out << \" badNavSubframeCount: \" << badNavSubframeCount << endl;\n }\n \n out << endl;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid MDPNavProcessor::process(const gpstk::MDPNavSubframe& msg)\n{\n if (firstNav)\n {\n firstNav = false;\n if (verboseLevel)\n out << msg.time.printf(timeFormat)\n << \" Received first Navigation Subframe message\"\n << endl;\n }\n\n navSubframeCount++;\n short sfid = msg.getSFID();\n short svid = msg.getSVID();\n bool isAlm = sfid > 3;\n long sow = msg.getHOWTime();\n short page = ((sow-6) \/ 30) % 25 + 1;\n\n if (verboseLevel>2)\n {\n out << msg.time.printf(timeFormat)\n << \" prn:\" << setw(2) << msg.prn\n << \" \" << asString(msg.carrier)\n << \":\" << setw(6) << left << asString(msg.range)\n << \" nav:\" << static_cast<int>(msg.nav)\n << \" SOW:\" << setw(6) << sow\n << \" SFID:\" << sfid;\n if (isAlm)\n out << \" SVID:\" << svid\n << \" Page:\" << page;\n out << endl;\n }\n\n \/\/ Sanity check on the header time versus the HOW time\n short week = msg.time.GPSfullweek();\n if (sow <0 || sow>=604800)\n {\n badNavSubframeCount++;\n if (verboseLevel>1)\n out << msg.time.printf(timeFormat)\n << \" SOW bad: \" << sow\n << endl;\n return;\n }\n \n DayTime howTime(week, msg.getHOWTime());\n if (howTime == msg.time)\n {\n \/\/ Move this back down to verboseLevel>0 when ITT fixes their code...\n if (verboseLevel>2)\n out << msg.time.printf(timeFormat) << \" header time is HOW time\" << endl;\n }\n else if (howTime != msg.time+6)\n {\n badNavSubframeCount++;\n if (verboseLevel>1)\n out << msg.time.printf(timeFormat)\n << \" HOW\/header time miscompare \" << howTime.printf(timeFormat)\n << endl;\n return;\n }\n\n if ((isAlm && !almOut) || (!isAlm && !ephOut))\n return;\n\n NavIndex ni(RangeCarrierPair(msg.range, msg.carrier), msg.prn);\n prev[ni] = curr[ni];\n curr[ni] = msg;\n\n long sfa[10];\n msg.fillArray(sfa);\n long long_sfa[10];\n for( int j = 0; j < 10; j++ )\n long_sfa[j] = static_cast<long>( sfa[j] );\n\n if (gpstk::EngNav::subframeParity(long_sfa))\n {\n if (isAlm)\n {\n AlmanacPages& almPages = almPageStore[ni];\n EngAlmanac& engAlm = almStore[ni];\n SubframePage sp(sfid, page);\n almPages[sp] = msg;\n almPages.insert(make_pair(sp, msg));\n \n if (makeEngAlmanac(engAlm, almPages))\n {\n out << msg.time.printf(timeFormat)\n << \" Built complete alm from prn \" << setw(2) << ni.second\n << \" \" << setw(2) << asString(ni.first.second)\n << \" \" << left << setw(6) << asString(ni.first.first)\n << endl;\n if (verboseLevel>1)\n engAlm.dump(out);\n almPages.clear();\n engAlm = EngAlmanac();\n } \n }\n else\n {\n EphemerisPages& ephPages = ephPageStore[ni];\n ephPages[sfid] = msg;\n EngEphemeris engEph;\n\n if (makeEngEphemeris(engEph, ephPages))\n {\n out << msg.time.printf(timeFormat)\n << \" Built complete eph from prn \" << setw(2) << ni.second\n << \" \" << setw(2) << asString(ni.first.second)\n << \" \" << left << setw(6) << asString(ni.first.first)\n << \" iocd:0x\" << hex << setw(3) << engEph.getIODC() << dec\n << endl;\n if (verboseLevel>1)\n out << engEph;\n ephStore[ni] = engEph;\n }\n }\n }\n else\n {\n badNavSubframeCount++;\n out << msg.time.printf(timeFormat)\n << \" Parity error on prn:\" << setw(2) << msg.prn\n << \" \" << asString(msg.carrier)\n << \":\" << setw(6) << left << asString(msg.range)\n << \" TOW:\" << setw(6) << msg.getHOWTime()\n << \" SFID:\" << sfid\n << endl;\n }\n} \/\/ end of process()\n<commit_msg>Made the parity check get executed for all subframes.<commit_after>#pragma ident \"$Id: NavProc.cpp,v 1.1 2006\/07\/28 14:31:42 littlej Exp $\"\n\n\/*\n Think, navdmp for mdp, with bonus output that you get data from all code\/carrier\n combos.\n*\/\n\n#include \"Geodetic.hpp\"\n#include \"NavProc.hpp\"\n\n#include \"FormatConversionFunctions.hpp\"\n\nusing namespace std;\nusing namespace gpstk;\nusing namespace gpstk::StringUtils;\n\n\n\/\/-----------------------------------------------------------------------------\nMDPNavProcessor::MDPNavProcessor(gpstk::MDPStream& in, std::ofstream& out)\n : MDPProcessor(in, out),\n firstNav(true), almOut(false), ephOut(false),\n badNavSubframeCount(0), navSubframeCount(0)\n{\n timeFormat = \"%4Y\/%03j\/%02H:%02M:%02S\";\n}\n\n\n\/\/-----------------------------------------------------------------------------\nMDPNavProcessor::~MDPNavProcessor()\n{\n using gpstk::RangeCode;\n using gpstk::CarrierCode;\n using gpstk::StringUtils::asString;\n \n out << \"Done processing data.\" << endl << endl;\n\n out << endl << \"Navigation Subframe message summary:\" << endl;\n if (firstNav)\n out << \" No Navigation Subframe messages processed.\" << endl;\n else\n {\n out << \" navSubframeCount: \" << navSubframeCount << endl;\n out << \" badNavSubframeCount: \" << badNavSubframeCount << endl;\n }\n \n out << endl;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid MDPNavProcessor::process(const gpstk::MDPNavSubframe& msg)\n{\n if (firstNav)\n {\n firstNav = false;\n if (verboseLevel)\n out << msg.time.printf(timeFormat)\n << \" Received first Navigation Subframe message\"\n << endl;\n }\n\n navSubframeCount++;\n short sfid = msg.getSFID();\n short svid = msg.getSVID();\n bool isAlm = sfid > 3;\n long sow = msg.getHOWTime();\n short page = ((sow-6) \/ 30) % 25 + 1;\n\n if (verboseLevel>2)\n {\n out << msg.time.printf(timeFormat)\n << \" prn:\" << setw(2) << msg.prn\n << \" \" << asString(msg.carrier)\n << \":\" << setw(6) << left << asString(msg.range)\n << \" nav:\" << static_cast<int>(msg.nav)\n << \" SOW:\" << setw(6) << sow\n << \" SFID:\" << sfid;\n if (isAlm)\n out << \" SVID:\" << svid\n << \" Page:\" << page;\n out << endl;\n }\n\n \/\/ Sanity check on the header time versus the HOW time\n short week = msg.time.GPSfullweek();\n if (sow <0 || sow>=604800)\n {\n badNavSubframeCount++;\n if (verboseLevel>1)\n out << msg.time.printf(timeFormat)\n << \" SOW bad: \" << sow\n << endl;\n return;\n }\n \n DayTime howTime(week, msg.getHOWTime());\n if (howTime == msg.time)\n {\n \/\/ Move this back down to verboseLevel>0 when ITT fixes their code...\n if (verboseLevel>2)\n out << msg.time.printf(timeFormat) << \" header time is HOW time\" << endl;\n }\n else if (howTime != msg.time+6)\n {\n badNavSubframeCount++;\n if (verboseLevel>1)\n out << msg.time.printf(timeFormat)\n << \" HOW\/header time miscompare \" << howTime.printf(timeFormat)\n << endl;\n return;\n }\n\n\/\/ if ((isAlm && !almOut) || (!isAlm && !ephOut))\n\/\/ return;\n\n NavIndex ni(RangeCarrierPair(msg.range, msg.carrier), msg.prn);\n prev[ni] = curr[ni];\n curr[ni] = msg;\n\n long sfa[10];\n msg.fillArray(sfa);\n long long_sfa[10];\n for( int j = 0; j < 10; j++ )\n long_sfa[j] = static_cast<long>( sfa[j] );\n\n if (gpstk::EngNav::subframeParity(long_sfa))\n {\n if (isAlm && almOut)\n {\n AlmanacPages& almPages = almPageStore[ni];\n EngAlmanac& engAlm = almStore[ni];\n SubframePage sp(sfid, page);\n almPages[sp] = msg;\n almPages.insert(make_pair(sp, msg));\n \n if (makeEngAlmanac(engAlm, almPages))\n {\n out << msg.time.printf(timeFormat)\n << \" Built complete alm from prn \" << setw(2) << ni.second\n << \" \" << setw(2) << asString(ni.first.second)\n << \" \" << left << setw(6) << asString(ni.first.first)\n << endl;\n if (verboseLevel>1)\n engAlm.dump(out);\n almPages.clear();\n engAlm = EngAlmanac();\n } \n }\n if (!isAlm && ephOut)\n {\n EphemerisPages& ephPages = ephPageStore[ni];\n ephPages[sfid] = msg;\n EngEphemeris engEph;\n\n if (makeEngEphemeris(engEph, ephPages))\n {\n out << msg.time.printf(timeFormat)\n << \" Built complete eph from prn \" << setw(2) << ni.second\n << \" \" << setw(2) << asString(ni.first.second)\n << \" \" << left << setw(6) << asString(ni.first.first)\n << \" iocd:0x\" << hex << setw(3) << engEph.getIODC() << dec\n << endl;\n if (verboseLevel>1)\n out << engEph;\n ephStore[ni] = engEph;\n }\n }\n }\n else\n {\n badNavSubframeCount++;\n out << msg.time.printf(timeFormat)\n << \" Parity error on prn:\" << setw(2) << msg.prn\n << \" \" << asString(msg.carrier)\n << \":\" << setw(6) << left << asString(msg.range)\n << \" TOW:\" << setw(6) << msg.getHOWTime()\n << \" SFID:\" << sfid\n << endl;\n }\n} \/\/ end of process()\n<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2019 Intel Corporation \/\/\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#include \"..\/ImageOp.h\"\n#include \"ToneMapper_ispc.h\"\n\nusing namespace ospcommon;\n\nnamespace ospray {\n\n \/*! \\brief Generic tone mapping operator approximating ACES by default. *\/\n struct OSPRAY_SDK_INTERFACE ToneMapper : public TileOp\n {\n void commit() override;\n\n std::unique_ptr<LiveImageOp> attach(FrameBufferView &fbView) override;\n\n std::string toString() const override;\n\n \/\/ Params for the tone mapping curve\n float a, b, c, d;\n bool acesColor;\n float exposure;\n };\n\n struct OSPRAY_SDK_INTERFACE LiveToneMapper : public LiveTileOp\n {\n LiveToneMapper(FrameBufferView &fbView, void *ispcEquiv);\n\n ~LiveToneMapper() override;\n\n void process(Tile &t) override;\n\n void *ispcEquiv;\n };\n\n \/\/ Definitions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n void ToneMapper::commit()\n {\n ImageOp::commit();\n\n exposure = getParam1f(\"exposure\", 1.f);\n \/\/ Default parameters fitted to the ACES 1.0 grayscale curve\n \/\/ (RRT.a1.0.3 + ODT.Academy.Rec709_100nits_dim.a1.0.3)\n \/\/ We included exposure adjustment to match 18% middle gray\n \/\/ (ODT(RRT(0.18)) = 0.18)\n const float aces_contrast = 1.6773f;\n const float aces_shoulder = 0.9714f;\n const float aces_midIn = 0.18f;\n const float aces_midOut = 0.18f;\n const float aces_hdrMax = 11.0785f;\n\n a = max(getParam1f(\"contrast\", aces_contrast), 0.0001f);\n float d = clamp(getParam1f(\"shoulder\", aces_shoulder), 0.0001f, 1.f);\n float m = clamp(getParam1f(\"midIn\", aces_midIn), 0.0001f, 1.f);\n float n = clamp(getParam1f(\"midOut\", aces_midOut), 0.0001f, 1.f);\n float w = max(getParam1f(\"hdrMax\", aces_hdrMax), 1.f);\n acesColor = getParam1b(\"acesColor\", true);\n\n \/\/ Solve b and c\n b = -((powf(m, -a * d) *\n (-powf(m, a) + (n * (powf(m, a * d) * n * powf(w, a) -\n powf(m, a) * powf(w, a * d))) \/\n (powf(m, a * d) * n - n * powf(w, a * d)))) \/\n n);\n\n \/\/ avoid discontinuous curve by clamping to 0\n c = max((powf(m, a * d) * n * powf(w, a) - powf(m, a) * powf(w, a * d)) \/\n (powf(m, a * d) * n - n * powf(w, a * d)),\n 0.f);\n }\n\n std::unique_ptr<LiveImageOp> ToneMapper::attach(FrameBufferView &fbView)\n {\n void *ispcEquiv = ispc::ToneMapper_create();\n ispc::ToneMapper_set(ispcEquiv, exposure, a, b, c, d, acesColor);\n return ospcommon::make_unique<LiveToneMapper>(fbView, ispcEquiv);\n }\n\n std::string ToneMapper::toString() const\n {\n return \"ospray::ToneMapper\";\n }\n\n LiveToneMapper::LiveToneMapper(FrameBufferView &_fbView, void *ispcEquiv)\n : LiveTileOp(_fbView), ispcEquiv(ispcEquiv)\n {\n }\n\n LiveToneMapper::~LiveToneMapper()\n {\n \/\/ TODO WILL: Release the ISPC equiv\n }\n\n void LiveToneMapper::process(Tile &tile)\n {\n ToneMapper_apply(ispcEquiv, (ispc::Tile &)tile);\n }\n\n OSP_REGISTER_IMAGE_OP(ToneMapper, tonemapper);\n\n} \/\/ namespace ospray\n<commit_msg>fix bug where garbage value was used in ToneMapper (d)<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2019 Intel Corporation \/\/\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#include \"..\/ImageOp.h\"\n#include \"ToneMapper_ispc.h\"\n\nusing namespace ospcommon;\n\nnamespace ospray {\n\n \/*! \\brief Generic tone mapping operator approximating ACES by default. *\/\n struct OSPRAY_SDK_INTERFACE ToneMapper : public TileOp\n {\n void commit() override;\n\n std::unique_ptr<LiveImageOp> attach(FrameBufferView &fbView) override;\n\n std::string toString() const override;\n\n \/\/ Params for the tone mapping curve\n float a, b, c, d;\n bool acesColor;\n float exposure;\n };\n\n struct OSPRAY_SDK_INTERFACE LiveToneMapper : public LiveTileOp\n {\n LiveToneMapper(FrameBufferView &fbView, void *ispcEquiv);\n\n ~LiveToneMapper() override;\n\n void process(Tile &t) override;\n\n void *ispcEquiv;\n };\n\n \/\/ Definitions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n void ToneMapper::commit()\n {\n ImageOp::commit();\n\n exposure = getParam1f(\"exposure\", 1.f);\n \/\/ Default parameters fitted to the ACES 1.0 grayscale curve\n \/\/ (RRT.a1.0.3 + ODT.Academy.Rec709_100nits_dim.a1.0.3)\n \/\/ We included exposure adjustment to match 18% middle gray\n \/\/ (ODT(RRT(0.18)) = 0.18)\n const float aces_contrast = 1.6773f;\n const float aces_shoulder = 0.9714f;\n const float aces_midIn = 0.18f;\n const float aces_midOut = 0.18f;\n const float aces_hdrMax = 11.0785f;\n\n a = max(getParam1f(\"contrast\", aces_contrast), 0.0001f);\n d = clamp(getParam1f(\"shoulder\", aces_shoulder), 0.0001f, 1.f);\n\n float m = clamp(getParam1f(\"midIn\", aces_midIn), 0.0001f, 1.f);\n float n = clamp(getParam1f(\"midOut\", aces_midOut), 0.0001f, 1.f);\n\n float w = max(getParam1f(\"hdrMax\", aces_hdrMax), 1.f);\n acesColor = getParam1b(\"acesColor\", true);\n\n \/\/ Solve b and c\n b = -((powf(m, -a * d) *\n (-powf(m, a) + (n * (powf(m, a * d) * n * powf(w, a) -\n powf(m, a) * powf(w, a * d))) \/\n (powf(m, a * d) * n - n * powf(w, a * d)))) \/\n n);\n\n \/\/ avoid discontinuous curve by clamping to 0\n c = max((powf(m, a * d) * n * powf(w, a) - powf(m, a) * powf(w, a * d)) \/\n (powf(m, a * d) * n - n * powf(w, a * d)),\n 0.f);\n }\n\n std::unique_ptr<LiveImageOp> ToneMapper::attach(FrameBufferView &fbView)\n {\n void *ispcEquiv = ispc::ToneMapper_create();\n ispc::ToneMapper_set(ispcEquiv, exposure, a, b, c, d, acesColor);\n return ospcommon::make_unique<LiveToneMapper>(fbView, ispcEquiv);\n }\n\n std::string ToneMapper::toString() const\n {\n return \"ospray::ToneMapper\";\n }\n\n LiveToneMapper::LiveToneMapper(FrameBufferView &_fbView, void *ispcEquiv)\n : LiveTileOp(_fbView), ispcEquiv(ispcEquiv)\n {\n }\n\n LiveToneMapper::~LiveToneMapper()\n {\n \/\/ TODO WILL: Release the ISPC equiv\n }\n\n void LiveToneMapper::process(Tile &tile)\n {\n ToneMapper_apply(ispcEquiv, (ispc::Tile &)tile);\n }\n\n OSP_REGISTER_IMAGE_OP(ToneMapper, tonemapper);\n\n} \/\/ namespace ospray\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <stdexcept>\n#include <vector>\n#include <unordered_map>\n\nusing namespace std;\n\n\nstd::unordered_map<std::string, double> constants =\n {\n {\"Pi\", 3.14},\n {\"e\", 2.7}\n };\n\nenum class Token {\n Invalid,\n Minus,\n BinaryMinus,\n UnaryMinus,\n Plus,\n Mul,\n Div,\n Number,\n LeftBracket,\n RightBracket,\n End\n};\n\n\/*\n * class for holding tokens and their values(in case of numbers\/constants)\n * also has some useful methods\n *\/\nstruct Token_value {\n explicit Token_value(Token token, double value = 0.0) : token(token), value(value) {}\n\n \/*\n * true if token is an operator\n *\/\n bool isOperator() {\n if ((token == Token::Plus) ||\n (token == Token::BinaryMinus) ||\n (token == Token::UnaryMinus) ||\n (token == Token::Mul) ||\n (token == Token::Div))\n return true;\n else\n return false;\n }\n\n \/*\n * true if token is a binary + -\n *\/\n bool isPM() {\n if ((token == Token::Plus) ||\n (token == Token::BinaryMinus))\n return true;\n else\n return false;\n }\n\n Token token;\n double value;\n};\n\n\/*\n * node for the calculation tree\n *\/\nstruct Node {\n \/*\n * a leaf\n *\/\n Node(Token token, double value) :\n token(token), value(value) {}\n\n \/*\n * a branch\n *\/\n Node(Token token, Node *left, Node *right) :\n token(token), left(left), right(right) {}\n\n Token token;\n double value = 0.0;\n Node *left = nullptr;\n Node *right = nullptr;\n};\n\nToken getToken(const char *&text) {\n\n while (const auto c = *text++) {\n\n switch (c) {\n case ' ':\n continue;\n case '-':\n return Token::Minus;\n case '+':\n return Token::Plus;\n case '*':\n return Token::Mul;\n case '\/':\n return Token::Div;\n case '0':\n return Token::Number;\n case '(':\n return Token::LeftBracket;\n case ')':\n return Token::RightBracket;\n }\n\n if (c >= '1' && c <= '9') {\n for (auto c = *text; c >= '0' && c <= '9';) {\n text++;\n c = *text;\n }\n return Token::Number;\n }\n\n if (c == 'e')\n return Token::Number;\n if (c == 'P') {\n char d = *text;\n if (d == 'i') {\n text++;\n return Token::Number;\n } else\n return Token::Invalid;\n }\n return Token::Invalid;\n }\n return Token::End;\n\n};\n\ndouble getNumber(const char *start, const char *end) {\n\n double result = 0.0;\n\n if (*start == 'e')\n return constants[\"e\"];\n else if (*start == 'P')\n return constants[\"Pi\"];\n while (start <= end) {\n if (*start != ' ') {\n if (*start >= '0' && *start <= '9')\n result = result * 10 + *start - 48;\n }\n ++start;\n }\n\n return result;\n\n}\n\n\/*\n * create a calculation tree from Token_values vector\n * by finding the operator with least priority and splitting\n *\/\nNode *createTree(vector<Token_value> vector) {\n\n Node *nodeP;\n\n \/\/variables for keeping count of brackets\n int min_priority = -1;\n int current_priority = 0;\n\n \/\/variables describing current operator candidate to split on\n bool is_PM = false;\n bool is_unary_minus = false;\n\n \/\/does current operator have less priority?\n bool changed = false;\n\n int opIndex = -1;\n int numberIndex = -1;\n int count = 0;\n for (auto token_v : vector) {\n\n if (token_v.token == Token::Number) {\n numberIndex = count;\n count++;\n continue;\n }\n\n if (token_v.isOperator()) {\n if ((min_priority == -1) || (current_priority < min_priority)) {\n changed = true;\n } else if (current_priority == min_priority) {\n if (token_v.isPM())\n changed = true;\n else if (not is_PM) {\n if (token_v.token == Token::UnaryMinus) {\n if (opIndex == -1)\n changed = true;\n } else\n changed = true;\n }\n }\n\n if (changed) {\n opIndex = count;\n min_priority = current_priority;\n is_unary_minus = (token_v.token == Token::UnaryMinus);\n is_PM = token_v.isPM();\n changed = false;\n }\n\n }\n if (token_v.token == Token::LeftBracket) {\n current_priority++;\n }\n if (token_v.token == Token::RightBracket) {\n current_priority--;\n }\n count++;\n }\n\n if (opIndex == -1) {\n nodeP = new Node(Token::Number, vector[numberIndex].value);\n return nodeP;\n }\n std::vector<Token_value> left_v;\n std::vector<Token_value> right_v;\n\n \/\/min_priority = number of brackets we need to trim in the\n \/\/beginning and end of the vector\n for (int count_2 = 0; count_2 < count; ++count_2) {\n if (count_2 + min_priority >= count)\n break;\n if (count_2 < min_priority) {\n continue;\n }\n if (count_2 < opIndex) {\n left_v.push_back(vector[count_2]);\n }\n if (count_2 > opIndex) {\n right_v.push_back(vector[count_2]);\n }\n }\n\n Node *leftNode;\n if (is_unary_minus) {\n leftNode = new Node(Token::Number, 0);\n } else\n leftNode = createTree(left_v);\n\n nodeP = new Node(vector[opIndex].token, leftNode, createTree(right_v));\n\n return nodeP;\n\n}\n\n\/*\n * function for solving the calculation tree\n *\/\ndouble solveTree(Node *node) {\n if (node->token == Token::Number) {\n double result = node->value;\n delete node;\n return result;\n }\n double lValue = solveTree(node->left);\n double rValue = solveTree(node->right);\n auto token = node->token;\n delete node;\n switch (token) {\n case Token::BinaryMinus:\n return lValue - rValue;\n case Token::UnaryMinus:\n return -rValue;\n case Token::Plus:\n return lValue + rValue;\n case Token::Mul:\n return lValue * rValue;\n case Token::Div: {\n if (rValue == 0)\n throw std::overflow_error(\"Exception: zero division\");\n return lValue \/ rValue;\n }\n default:\n throw std::invalid_argument(\"Exception: could not solve tree\");\n }\n}\n\n\/*\n * main class that receives the expression,\n * checks its validity and has\n * a method for calculating it\n *\/\nstruct Calculator {\n explicit Calculator(char const *text) :\n ZeroDivision(false),\n n_tokens(0),\n result(0),\n text(text) {}\n\n bool isValid() {\n const char *end = text;\n bool invalid = false;\n bool is_operator = true;\n bool l_bracket = false;\n int openBrackets = 0;\n\n auto token = getToken(end);\n while (token != Token::End) {\n n_tokens++;\n switch (token) {\n case Token::Invalid: {\n invalid = true;\n break;\n }\n case Token::Number: {\n if ((not is_operator) && (not l_bracket))\n invalid = true;\n l_bracket = false;\n is_operator = false;\n break;\n }\n case Token::Minus: {\n is_operator = true;\n l_bracket = false;\n break;\n }\n case Token::LeftBracket: {\n if ((not is_operator) && (not l_bracket))\n invalid = true;\n l_bracket = true;\n is_operator = false;\n openBrackets++;\n break;\n }\n case Token::RightBracket: {\n if (is_operator || l_bracket || (openBrackets < 1))\n invalid = true;\n l_bracket = false;\n is_operator = false;\n openBrackets--;\n break;\n }\n default: {\n if (is_operator || l_bracket)\n invalid = true;\n is_operator = true;\n }\n }\n if (invalid)\n break;\n token = getToken(end);\n }\n if (invalid || is_operator || openBrackets)\n return false;\n return true;\n }\n\n void tokenize() {\n const char *ptr1 = text;\n const char *ptr2 = text;\n bool prev_is_number_or_rbracket = false;\n\n for (int i = 0; i < n_tokens; ++i) {\n auto token = getToken(ptr2);\n\n if (token == Token::Number) {\n vector.emplace_back(token, getNumber(ptr1, ptr2));\n prev_is_number_or_rbracket = true;\n } else if (token == Token::Minus) {\n if (prev_is_number_or_rbracket)\n vector.emplace_back(Token::BinaryMinus);\n else\n vector.emplace_back(Token::UnaryMinus);\n prev_is_number_or_rbracket = false;\n } else {\n if (token == Token::RightBracket)\n prev_is_number_or_rbracket = true;\n else\n prev_is_number_or_rbracket = false;\n vector.emplace_back(token);\n }\n ptr1 = ptr2;\n }\n }\n\n double calculate() {\n this->tokenize();\n Node *tree;\n tree = createTree(vector);\n try {\n result = solveTree(tree);\n } catch (std::overflow_error &e) {\n ZeroDivision = true;\n return 0;\n }\n return result;\n }\n\n bool ZeroDivision;\n int n_tokens;\n double result;\n char const *text;\n std::vector<Token_value> vector;\n};\n\nint main(int argc, char const *argv[]) {\n if (argc == 1) {\n cout << \"No expression provided\";\n return 1;\n }\n\n char const *text = argv[1];\n bool isvalid;\n double result;\n\n Calculator calculator(text);\n isvalid = calculator.isValid();\n\n if (not isvalid) {\n cout << \"Invalid expression\";\n return 1;\n } else {\n result = calculator.calculate();\n if (calculator.ZeroDivision) {\n cout << \"Exception: zero division\";\n return 1;\n } else\n cout << result;\n }\n\n return 0;\n}\n<commit_msg>Koshman_hw03: fixed constants parsing<commit_after>#include <iostream>\n#include <stdexcept>\n#include <vector>\n#include <unordered_map>\n\nusing namespace std;\n\n\nstd::unordered_map<std::string, double> constants =\n {\n {\"Pi\", 3.14},\n {\"e\", 2.7}\n };\n\nenum class Token {\n Invalid,\n Minus,\n BinaryMinus,\n UnaryMinus,\n Plus,\n Mul,\n Div,\n Number,\n LeftBracket,\n RightBracket,\n End\n};\n\n\/*\n * class for holding tokens and their values(in case of numbers\/constants)\n * also has some useful methods\n *\/\nstruct Token_value {\n explicit Token_value(Token token, double value = 0.0) : token(token), value(value) {}\n\n \/*\n * true if token is an operator\n *\/\n bool isOperator() {\n if ((token == Token::Plus) ||\n (token == Token::BinaryMinus) ||\n (token == Token::UnaryMinus) ||\n (token == Token::Mul) ||\n (token == Token::Div))\n return true;\n else\n return false;\n }\n\n \/*\n * true if token is a binary + -\n *\/\n bool isPM() {\n if ((token == Token::Plus) ||\n (token == Token::BinaryMinus))\n return true;\n else\n return false;\n }\n\n Token token;\n double value;\n};\n\n\/*\n * node for the calculation tree\n *\/\nstruct Node {\n \/*\n * a leaf\n *\/\n Node(Token token, double value) :\n token(token), value(value) {}\n\n \/*\n * a branch\n *\/\n Node(Token token, Node *left, Node *right) :\n token(token), left(left), right(right) {}\n\n Token token;\n double value = 0.0;\n Node *left = nullptr;\n Node *right = nullptr;\n};\n\nToken getToken(const char *&text) {\n\n while (const auto c = *text++) {\n\n switch (c) {\n case ' ':\n continue;\n case '-':\n return Token::Minus;\n case '+':\n return Token::Plus;\n case '*':\n return Token::Mul;\n case '\/':\n return Token::Div;\n case '0':\n return Token::Number;\n case '(':\n return Token::LeftBracket;\n case ')':\n return Token::RightBracket;\n }\n\n if (c >= '1' && c <= '9') {\n for (auto c = *text; c >= '0' && c <= '9';) {\n text++;\n c = *text;\n }\n return Token::Number;\n }\n\n if (c == 'e')\n return Token::Number;\n if (c == 'P') {\n char d = *text;\n if (d == 'i') {\n text++;\n return Token::Number;\n } else\n return Token::Invalid;\n }\n return Token::Invalid;\n }\n return Token::End;\n\n};\n\ndouble getNumber(const char *start, const char *end) {\n\n double result = 0.0;\n while (*start == ' ')\n ++start;\n if (*start == 'e')\n return constants[\"e\"];\n if (*start == 'P')\n return constants[\"Pi\"];\n\n while (start < end) {\n result = result * 10 + *start - 48;\n ++start;\n }\n\n return result;\n\n}\n\n\/*\n * create a calculation tree from Token_values vector\n * by finding the operator with least priority and splitting\n *\/\nNode *createTree(vector<Token_value> vector) {\n\n Node *nodeP;\n\n \/\/variables for keeping count of brackets\n int min_priority = -1;\n int current_priority = 0;\n\n \/\/variables describing current operator candidate to split on\n bool is_PM = false;\n bool is_unary_minus = false;\n\n \/\/does current operator have less priority?\n bool changed = false;\n\n int opIndex = -1;\n int numberIndex = -1;\n int count = 0;\n for (auto token_v : vector) {\n\n if (token_v.token == Token::Number) {\n numberIndex = count;\n count++;\n continue;\n }\n\n if (token_v.isOperator()) {\n if ((min_priority == -1) || (current_priority < min_priority)) {\n changed = true;\n } else if (current_priority == min_priority) {\n if (token_v.isPM())\n changed = true;\n else if (not is_PM) {\n if (token_v.token == Token::UnaryMinus) {\n if (opIndex == -1)\n changed = true;\n } else\n changed = true;\n }\n }\n\n if (changed) {\n opIndex = count;\n min_priority = current_priority;\n is_unary_minus = (token_v.token == Token::UnaryMinus);\n is_PM = token_v.isPM();\n changed = false;\n }\n\n }\n if (token_v.token == Token::LeftBracket) {\n current_priority++;\n }\n if (token_v.token == Token::RightBracket) {\n current_priority--;\n }\n count++;\n }\n\n if (opIndex == -1) {\n nodeP = new Node(Token::Number, vector[numberIndex].value);\n return nodeP;\n }\n std::vector<Token_value> left_v;\n std::vector<Token_value> right_v;\n\n \/\/min_priority = number of brackets we need to trim in the\n \/\/beginning and end of the vector\n for (int count_2 = 0; count_2 < count; ++count_2) {\n if (count_2 + min_priority >= count)\n break;\n if (count_2 < min_priority) {\n continue;\n }\n if (count_2 < opIndex) {\n left_v.push_back(vector[count_2]);\n }\n if (count_2 > opIndex) {\n right_v.push_back(vector[count_2]);\n }\n }\n\n Node *leftNode;\n if (is_unary_minus) {\n leftNode = new Node(Token::Number, 0);\n } else\n leftNode = createTree(left_v);\n\n nodeP = new Node(vector[opIndex].token, leftNode, createTree(right_v));\n\n return nodeP;\n\n}\n\n\/*\n * function for solving the calculation tree\n *\/\ndouble solveTree(Node *node) {\n if (node->token == Token::Number) {\n double result = node->value;\n delete node;\n return result;\n }\n double lValue = solveTree(node->left);\n double rValue = solveTree(node->right);\n auto token = node->token;\n delete node;\n switch (token) {\n case Token::BinaryMinus:\n return lValue - rValue;\n case Token::UnaryMinus:\n return -rValue;\n case Token::Plus:\n return lValue + rValue;\n case Token::Mul:\n return lValue * rValue;\n case Token::Div: {\n if (rValue == 0)\n throw std::overflow_error(\"Exception: zero division\");\n return lValue \/ rValue;\n }\n default:\n throw std::invalid_argument(\"Exception: could not solve tree\");\n }\n}\n\n\/*\n * main class that receives the expression,\n * checks its validity and has\n * a method for calculating it\n *\/\nstruct Calculator {\n explicit Calculator(char const *text) :\n ZeroDivision(false),\n n_tokens(0),\n result(0),\n text(text) {}\n\n bool isValid() {\n const char *end = text;\n bool invalid = false;\n bool is_operator = true;\n bool l_bracket = false;\n int openBrackets = 0;\n\n auto token = getToken(end);\n while (token != Token::End) {\n n_tokens++;\n switch (token) {\n case Token::Invalid: {\n invalid = true;\n break;\n }\n case Token::Number: {\n if ((not is_operator) && (not l_bracket))\n invalid = true;\n l_bracket = false;\n is_operator = false;\n break;\n }\n case Token::Minus: {\n is_operator = true;\n l_bracket = false;\n break;\n }\n case Token::LeftBracket: {\n if ((not is_operator) && (not l_bracket))\n invalid = true;\n l_bracket = true;\n is_operator = false;\n openBrackets++;\n break;\n }\n case Token::RightBracket: {\n if (is_operator || l_bracket || (openBrackets < 1))\n invalid = true;\n l_bracket = false;\n is_operator = false;\n openBrackets--;\n break;\n }\n default: {\n if (is_operator || l_bracket)\n invalid = true;\n is_operator = true;\n }\n }\n if (invalid)\n break;\n token = getToken(end);\n }\n if (invalid || is_operator || openBrackets)\n return false;\n return true;\n }\n\n void tokenize() {\n const char *ptr1 = text;\n const char *ptr2 = text;\n bool prev_is_number_or_rbracket = false;\n\n for (int i = 0; i < n_tokens; ++i) {\n auto token = getToken(ptr2);\n\n if (token == Token::Number) {\n vector.emplace_back(token, getNumber(ptr1, ptr2));\n prev_is_number_or_rbracket = true;\n } else if (token == Token::Minus) {\n if (prev_is_number_or_rbracket)\n vector.emplace_back(Token::BinaryMinus);\n else\n vector.emplace_back(Token::UnaryMinus);\n prev_is_number_or_rbracket = false;\n } else {\n if (token == Token::RightBracket)\n prev_is_number_or_rbracket = true;\n else\n prev_is_number_or_rbracket = false;\n vector.emplace_back(token);\n }\n ptr1 = ptr2;\n }\n }\n\n double calculate() {\n this->tokenize();\n Node *tree;\n tree = createTree(vector);\n try {\n result = solveTree(tree);\n } catch (std::overflow_error &e) {\n ZeroDivision = true;\n return 0;\n }\n return result;\n }\n\n bool ZeroDivision;\n int n_tokens;\n double result;\n char const *text;\n std::vector<Token_value> vector;\n};\n\nint main(int argc, char const *argv[]) {\n if (argc == 1) {\n cout << \"No expression provided\";\n return 1;\n }\n\n char const *text = argv[1];\n bool isvalid;\n double result;\n\n Calculator calculator(text);\n isvalid = calculator.isValid();\n\n if (not isvalid) {\n cout << \"Invalid expression\";\n return 1;\n } else {\n result = calculator.calculate();\n if (calculator.ZeroDivision) {\n cout << \"Exception: zero division\";\n return 1;\n } else\n cout << result;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"compiler\/grammar.hpp\"\n#include \"compiler\/conversions.hpp\"\n\n#include <boost\/spirit\/home\/qi.hpp>\n#include <boost\/spirit\/home\/lex.hpp>\n\nusing namespace std::string_literals;\n\nnamespace perseus\n{\n namespace detail\n {\n \/\/ rule definition; optional attributes are generated from the matched code\n template< typename attribute = boost::spirit::unused_type >\n using rule = boost::spirit::qi::rule< token_iterator, attribute(), skip_grammar >;\n\n \/\/ terminals\n\n static rule< ast::string_literal > string{ string_literal_parser{}, \"string literal\"s };\n static rule< std::int32_t > decimal_integer{ decimal_integer_literal_parser{}, \"decimal integer\"s };\n static rule< std::int32_t > hexadecimal_integer{ hexadecimal_integer_literal_parser{}, \"hexadecimal integer\"s };\n static rule< std::int32_t > binary_integer{ binary_integer_literal_parser{}, \"binary integer\"s };\n static rule< std::int32_t > integer{ decimal_integer | hexadecimal_integer | binary_integer, \"integer\"s };\n\n static rule< ast::identifier > identifier{ boost::spirit::qi::token( token_id::identifier ), \"identifier\"s };\n static rule< ast::operator_identifier > operator_identifier{ boost::spirit::qi::token( token_id::operator_identifier ), \"operator identifier\"s };\n\n static rule<> if_{ boost::spirit::qi::token( token_id::if_ ), \"if\"s };\n static rule<> else_{ boost::spirit::qi::token( token_id::else_ ), \"else\"s };\n static rule<> while_{ boost::spirit::qi::token( token_id::while_ ), \"while\"s };\n static rule<> return_{ boost::spirit::qi::token( token_id::if_ ), \"return\"s };\n\n static rule<> colon{ boost::spirit::qi::token( token_id::colon ), \"colon\"s };\n static rule<> semicolon{ boost::spirit::qi::token( token_id::semicolon ), \"semicolon\"s };\n static rule<> dot{ boost::spirit::qi::token( token_id::dot ), \"dot\"s };\n static rule<> comma{ boost::spirit::qi::token( token_id::comma ), \"comma\"s };\n static rule<> equals{ boost::spirit::qi::token( token_id::equals ), \"equals sign\"s };\n static rule<> backtick{ boost::spirit::qi::token( token_id::backtick ), \"backtick\"s };\n\n static rule<> paren_open{ boost::spirit::qi::token( token_id::paren_open ), \"opening paren\"s };\n static rule<> paren_close{ boost::spirit::qi::token( token_id::paren_close ), \"closing paren\"s };\n static rule<> brace_open{ boost::spirit::qi::token( token_id::brace_open ), \"opening brace\"s };\n static rule<> brace_close{ boost::spirit::qi::token( token_id::brace_close ), \"closing brace\"s };\n static rule<> square_bracket_open{ boost::spirit::qi::token( token_id::square_bracket_open ), \"opening square bracket\"s };\n static rule<> square_bracket_close{ boost::spirit::qi::token( token_id::square_bracket_close ), \"closing square bracket\"s };\n\n \/\/ non-terminals\n static grammar::start_type file;\n\n static rule< ast::expression > expression{ \"expression\"s };\n static rule< ast::operand > operand{ \"operand\"s };\n static rule< ast::operation > operation{ \"operation\"s };\n static rule< ast::binary_operation > binary_operation{ \"binary operation\"s };\n static rule< ast::unary_operation > unary_operation{ \"unary operation\"s };\n static rule< ast::if_expression > if_expression{ \"if expression\"s };\n static rule< ast::while_expression > while_expression{ \"while expression\"s };\n static rule< ast::call_expression > call_expression{ \"call expression\"s };\n static rule< ast::block_expression > block_expression{ \"block expression\"s };\n static rule< ast::parens_expression > parens_expression{ \"parens expression\"s };\n static rule< ast::index_expression > index_expression{ \"index expression\"s };\n\n\n grammar::grammar()\n : base_type( file, \"perseus script\"s )\n {\n \/\/ EOI = End of Input\n file %= expression > boost::spirit::qi::eoi;\n\n \/\/ what about operator_identifier? first class functions and all that?\n \/\/ this split is required to prevent left recursion, which in the parser turns into an infinite recursion.\n expression = operand >> *operation;\n operand = string | integer | identifier | unary_operation | if_expression | while_expression | block_expression | parens_expression;\n operation = binary_operation | call_expression | index_expression;\n {\n \/\/ x `op` y\n binary_operation = operator_identifier >> expression;\n\n \/\/ name( arg1, arg2 )\n \/\/ a % b means list of a separated by b; that has a minimum length of 1, thus the - (optional)\n call_expression = paren_open > -( expression % comma ) > paren_close;\n \n \/\/ object[index]\n index_expression = square_bracket_open > expression > square_bracket_close;\n\n \/\/ `op` x\n unary_operation = operator_identifier > expression;\n\n \/\/ if cond then_body else_body\n \/\/ Logically there's always an else, but it may be \"nothing\" (i.e. void).\n \/\/ > is an expectation concatenation: after an \"if\" terminal there *must* be an expression (allows for early abortion in case of errors and better errors)\n \/\/ this parsing is eager, i.e. `if c1 if c2 t else e` means `if c1 { if c2 t else e }`\n if_expression = if_ > expression > expression > ( ( else_ > expression ) | boost::spirit::qi::attr( ast::expression{ ast::void_expression{}, {} } ) );\n\n \/\/ while cond body\n while_expression = while_ > expression > expression;\n\n \/\/ { exp1; exp2 }\n block_expression = brace_open > ( expression % semicolon ) > brace_close;\n\n \/\/ ( expression )\n parens_expression = paren_open > expression > paren_close;\n }\n }\n }\n namespace detail\n {\n using skip_rule = boost::spirit::qi::rule< token_iterator >;\n\n \/\/ terminals\n static skip_rule whitespace{ boost::spirit::qi::token( token_id::whitespace ), \"whitespace\"s };\n static skip_rule comment{ boost::spirit::qi::token( token_id::whitespace ), \"comment\"s };\n \/\/ start symbol\n static skip_grammar::start_type skip{ whitespace | comment };\n\n skip_grammar::skip_grammar()\n : base_type( skip )\n {\n }\n }\n}\n<commit_msg>allow void expressions in blocks, e.g. {} and {foo;}<commit_after>#include \"compiler\/grammar.hpp\"\n#include \"compiler\/conversions.hpp\"\n\n#include <boost\/spirit\/home\/qi.hpp>\n#include <boost\/spirit\/home\/lex.hpp>\n\nusing namespace std::string_literals;\n\nnamespace perseus\n{\n namespace detail\n {\n \/\/ rule definition; optional attributes are generated from the matched code\n template< typename attribute = boost::spirit::unused_type >\n using rule = boost::spirit::qi::rule< token_iterator, attribute(), skip_grammar >;\n\n \/\/ terminals\n\n static rule< ast::string_literal > string{ string_literal_parser{}, \"string literal\"s };\n static rule< std::int32_t > decimal_integer{ decimal_integer_literal_parser{}, \"decimal integer\"s };\n static rule< std::int32_t > hexadecimal_integer{ hexadecimal_integer_literal_parser{}, \"hexadecimal integer\"s };\n static rule< std::int32_t > binary_integer{ binary_integer_literal_parser{}, \"binary integer\"s };\n static rule< std::int32_t > integer{ decimal_integer | hexadecimal_integer | binary_integer, \"integer\"s };\n\n static rule< ast::identifier > identifier{ boost::spirit::qi::token( token_id::identifier ), \"identifier\"s };\n static rule< ast::operator_identifier > operator_identifier{ boost::spirit::qi::token( token_id::operator_identifier ), \"operator identifier\"s };\n\n static rule<> if_{ boost::spirit::qi::token( token_id::if_ ), \"if\"s };\n static rule<> else_{ boost::spirit::qi::token( token_id::else_ ), \"else\"s };\n static rule<> while_{ boost::spirit::qi::token( token_id::while_ ), \"while\"s };\n static rule<> return_{ boost::spirit::qi::token( token_id::if_ ), \"return\"s };\n\n static rule<> colon{ boost::spirit::qi::token( token_id::colon ), \"colon\"s };\n static rule<> semicolon{ boost::spirit::qi::token( token_id::semicolon ), \"semicolon\"s };\n static rule<> dot{ boost::spirit::qi::token( token_id::dot ), \"dot\"s };\n static rule<> comma{ boost::spirit::qi::token( token_id::comma ), \"comma\"s };\n static rule<> equals{ boost::spirit::qi::token( token_id::equals ), \"equals sign\"s };\n static rule<> backtick{ boost::spirit::qi::token( token_id::backtick ), \"backtick\"s };\n\n static rule<> paren_open{ boost::spirit::qi::token( token_id::paren_open ), \"opening paren\"s };\n static rule<> paren_close{ boost::spirit::qi::token( token_id::paren_close ), \"closing paren\"s };\n static rule<> brace_open{ boost::spirit::qi::token( token_id::brace_open ), \"opening brace\"s };\n static rule<> brace_close{ boost::spirit::qi::token( token_id::brace_close ), \"closing brace\"s };\n static rule<> square_bracket_open{ boost::spirit::qi::token( token_id::square_bracket_open ), \"opening square bracket\"s };\n static rule<> square_bracket_close{ boost::spirit::qi::token( token_id::square_bracket_close ), \"closing square bracket\"s };\n\n \/\/ non-terminals\n static grammar::start_type file;\n\n static rule< ast::expression > expression{ \"expression\"s };\n static rule< ast::operand > operand{ \"operand\"s };\n static rule< ast::operation > operation{ \"operation\"s };\n static rule< ast::binary_operation > binary_operation{ \"binary operation\"s };\n static rule< ast::unary_operation > unary_operation{ \"unary operation\"s };\n static rule< ast::if_expression > if_expression{ \"if expression\"s };\n static rule< ast::while_expression > while_expression{ \"while expression\"s };\n static rule< ast::call_expression > call_expression{ \"call expression\"s };\n static rule< ast::block_expression > block_expression{ \"block expression\"s };\n static rule< ast::parens_expression > parens_expression{ \"parens expression\"s };\n static rule< ast::index_expression > index_expression{ \"index expression\"s };\n\n\n grammar::grammar()\n : base_type( file, \"perseus script\"s )\n {\n \/\/ EOI = End of Input\n file %= expression > boost::spirit::qi::eoi;\n\n \/\/ what about operator_identifier? first class functions and all that?\n \/\/ this split is required to prevent left recursion, which in the parser turns into an infinite recursion.\n expression = operand >> *operation;\n operand = string | integer | identifier | unary_operation | if_expression | while_expression | block_expression | parens_expression;\n operation = binary_operation | call_expression | index_expression;\n {\n \/\/ x `op` y\n binary_operation = operator_identifier >> expression;\n\n \/\/ name( arg1, arg2 )\n \/\/ a % b means list of a separated by b; that has a minimum length of 1, thus the - (optional)\n call_expression = paren_open > -( expression % comma ) > paren_close;\n \n \/\/ object[index]\n index_expression = square_bracket_open > expression > square_bracket_close;\n\n \/\/ `op` x\n unary_operation = operator_identifier > expression;\n\n \/\/ if cond then_body else_body\n \/\/ Logically there's always an else, but it may be \"nothing\" (i.e. void).\n \/\/ > is an expectation concatenation: after an \"if\" terminal there *must* be an expression (allows for early abortion in case of errors and better errors)\n \/\/ this parsing is eager, i.e. `if c1 if c2 t else e` means `if c1 { if c2 t else e }`\n auto default_to_void = boost::spirit::qi::attr( ast::expression{ ast::void_expression{},{} } );\n if_expression = if_ > expression > expression > ( ( else_ > expression ) | default_to_void );\n\n \/\/ while cond body\n while_expression = while_ > expression > expression;\n\n \/\/ { exp1; exp2 }\n block_expression = brace_open > ( ( expression | default_to_void ) % semicolon ) > brace_close;\n\n \/\/ ( expression )\n parens_expression = paren_open > expression > paren_close;\n }\n }\n }\n namespace detail\n {\n using skip_rule = boost::spirit::qi::rule< token_iterator >;\n\n \/\/ terminals\n static skip_rule whitespace{ boost::spirit::qi::token( token_id::whitespace ), \"whitespace\"s };\n static skip_rule comment{ boost::spirit::qi::token( token_id::whitespace ), \"comment\"s };\n \/\/ start symbol\n static skip_grammar::start_type skip{ whitespace | comment };\n\n skip_grammar::skip_grammar()\n : base_type( skip )\n {\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2010 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n#include <boost\/python.hpp>\n#include <boost\/python\/suite\/indexing\/vector_indexing_suite.hpp>\n#include <mapnik\/raster_colorizer.hpp>\n\nusing mapnik::raster_colorizer;\nusing mapnik::raster_colorizer_ptr;\nusing mapnik::color_band;\nusing mapnik::color_bands;\nusing mapnik::color;\n\nnamespace {\nvoid append_band1(raster_colorizer_ptr & rc, color_band b)\n{\n rc->append_band(b);\n}\nvoid append_band2(raster_colorizer_ptr & rc, color_band b, unsigned m)\n{\n rc->append_band(b, m);\n}\nvoid append_band3(raster_colorizer_ptr & rc, float v, color c)\n{\n rc->append_band(v, c);\n}\nvoid append_band4(raster_colorizer_ptr & rc, float v, color c, unsigned m)\n{\n rc->append_band(v, c, m);\n}\nvoid append_band5(raster_colorizer_ptr & rc, float v, float vm, color c, unsigned m)\n{\n rc->append_band(v, vm, c, m);\n}\nvoid append_band6(raster_colorizer_ptr & rc, float v, float vm, color c)\n{\n rc->append_band(v, vm, c);\n}\ncolor_bands const& get_color_bands(raster_colorizer_ptr & rc)\n{\n return rc->get_color_bands();\n}\n}\n\nvoid export_raster_colorizer()\n{\n using namespace boost::python;\n\n class_<raster_colorizer,raster_colorizer_ptr>(\"RasterColorizer\", init<>(\"Default ctor.\"))\n \n .add_property(\"bands\",make_function\n (get_color_bands,\n return_value_policy<reference_existing_object>()))\n .def(\"append_band\", append_band1, \"TODO: Write docs\")\n .def(\"append_band\", append_band2, \"TODO: Write docs\")\n .def(\"append_band\", append_band3, \"TODO: Write docs\")\n .def(\"append_band\", append_band4, \"TODO: Write docs\")\n .def(\"append_band\", append_band5, \"TODO: Write docs\")\n .def(\"append_band\", append_band6, \"TODO: Write docs\")\n .def(\"get_color\", &raster_colorizer::get_color, \"TODO: Write docs\")\n ; \n\n\n\n class_<color_bands>(\"ColorBands\",init<>(\"Default ctor.\"))\n .def(vector_indexing_suite<color_bands>())\n ;\n\n\n class_<color_band>(\"ColorBand\",\n init<float,color const&>(\"Deafult ctor.\"))\n .add_property(\"color\", make_function\n (&color_band::get_color,\n return_value_policy<reference_existing_object>()))\n .add_property(\"value\", &color_band::get_value)\n .add_property(\"max_value\", &color_band::get_max_value)\n .def(self == self)\n .def(\"__str__\",&color_band::to_string)\n ;\n}\n<commit_msg>619_raster_colorizer_documentation.patch from tmcw - closes #619<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2010 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n#include <boost\/python.hpp>\n#include <boost\/python\/suite\/indexing\/vector_indexing_suite.hpp>\n#include <mapnik\/raster_colorizer.hpp>\n\nusing mapnik::raster_colorizer;\nusing mapnik::raster_colorizer_ptr;\nusing mapnik::color_band;\nusing mapnik::color_bands;\nusing mapnik::color;\n\nnamespace {\nvoid append_band1(raster_colorizer_ptr & rc, color_band b)\n{\n rc->append_band(b);\n}\nvoid append_band2(raster_colorizer_ptr & rc, color_band b, unsigned m)\n{\n rc->append_band(b, m);\n}\nvoid append_band3(raster_colorizer_ptr & rc, float v, color c)\n{\n rc->append_band(v, c);\n}\nvoid append_band4(raster_colorizer_ptr & rc, float v, color c, unsigned m)\n{\n rc->append_band(v, c, m);\n}\nvoid append_band5(raster_colorizer_ptr & rc, float v, float vm, color c, unsigned m)\n{\n rc->append_band(v, vm, c, m);\n}\nvoid append_band6(raster_colorizer_ptr & rc, float v, float vm, color c)\n{\n rc->append_band(v, vm, c);\n}\ncolor_bands const& get_color_bands(raster_colorizer_ptr & rc)\n{\n return rc->get_color_bands();\n}\n}\n\nvoid export_raster_colorizer()\n{\n using namespace boost::python;\n\n class_<raster_colorizer,raster_colorizer_ptr>(\"RasterColorizer\", init<>(\"Default ctor.\"))\n \n .add_property(\"bands\",make_function\n (get_color_bands,\n return_value_policy<reference_existing_object>()))\n .def(\"append_band\", append_band1,\n (arg(\"color_band\")),\n \"Append a color band to the raster colorizer.\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> colorizer = mapnik.ColorBand()\\n\"\n \">>> color = mapnik.Color(\\\"#0044cc\\\")\\n\"\n \">>> color_band = mapnik.ColorBand(3, color)\\n\"\n \">>> colorizer.append_band(color_band)\\n\"\n )\n .def(\"append_band\", append_band2,\n (arg(\"color_band\"), arg(\"midpoint\")),\n \"Append a color band with a midpoint to the raster colorizer.\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> colorizer = mapnik.ColorBand()\\n\"\n \">>> color = mapnik.Color(\\\"#0044cc\\\")\\n\"\n \">>> color_band = mapnik.ColorBand(3, color)\\n\"\n \">>> colorizer.append_band(color_band, 1)\\n\"\n )\n .def(\"append_band\", append_band3, \n (arg(\"value\"), arg(\"color\")),\n \"Append a color for a specific value to the raster colorizer\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> colorizer = mapnik.RasterColorizer()\\n\"\n \">>> color = mapnik.Color(\\\"#0044cc\\\")\\n\"\n \">>> colorizer.append_band(30, color)\\n\"\n )\n .def(\"append_band\", append_band4, \n (arg(\"value\"), arg(\"color\"), arg(\"midpoints\")),\n \"Append a color for a certain value to the raster colorizer,\\n\"\n \"with a specified midpoint.\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> colorizer = mapnik.RasterColorizer()\\n\"\n \">>> color = mapnik.Color(\\\"#0044cc\\\")\\n\"\n \">>> colorizer.append_band(30, color, 4)\\n\"\n )\n .def(\"append_band\", append_band5, \n (arg(\"value\"), arg(\"value_max\"), arg(\"color\"), arg(\"midpoints\")),\n \"Append a color for a value range from value to value_max\\n\"\n \"to the raster colorizer, with a specified midpoint.\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> colorizer = mapnik.RasterColorizer()\\n\"\n \">>> color = mapnik.Color(\\\"#0044cc\\\")\\n\"\n \">>> colorizer.append_band(30, 40, color, 4)\\n\"\n )\n .def(\"append_band\", append_band6, \n (arg(\"value\"), arg(\"value_max\"), arg(\"color\")),\n \"Append a color for a value range from value to value_max\\n\"\n \"to the raster colorizer.\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> colorizer = mapnik.RasterColorizer()\\n\"\n \">>> color = mapnik.Color(\\\"#0044cc\\\")\\n\"\n \">>> colorizer.append_band(30, 40, color)\\n\"\n )\n .def(\"get_color\", &raster_colorizer::get_color, \n \"Get the color assigned to a certain value in raster data.\\n\"\n \"By default, returns Color(\\\"transparent\\\")\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> colorizer = mapnik.RasterColorizer()\\n\"\n \">>> color = mapnik.Color(\\\"#0044cc\\\")\\n\"\n \">>> colorizer.append_band(30, 40, color)\\n\"\n \">>> colorizer.get_color(35)\\n\"\n \"Color('#0044cc')\\n\"\n )\n ; \n\n\n\n class_<color_bands>(\"ColorBands\",init<>(\"Default ctor.\"))\n .def(vector_indexing_suite<color_bands>())\n ;\n\n\n class_<color_band>(\"ColorBand\",init<float,color const&>(\n \"A Color Band object.\\n\"\n \"Create with a value and color\\n\"\n \"\\n\"\n \"Usage:\"\n \">>> color = mapnik.Color(\\\"#fff000\\\")\\n\"\n \">>> color_band = mapnik.ColorBand(4, color)\\n\"\n ))\n .add_property(\"color\", make_function\n (&color_band::get_color,\n return_value_policy<reference_existing_object>()))\n .add_property(\"value\", &color_band::get_value)\n .add_property(\"max_value\", &color_band::get_max_value)\n .def(self == self)\n .def(\"__str__\",&color_band::to_string)\n ;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * gucefCORE: GUCEF module providing O\/S abstraction and generic solutions\r\n * Copyright (C) 2002 - 2007. Dinand Vanvelzen\r\n *\r\n * This library is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n *\/\r\n\r\n\/*-------------------------------------------------------------------------\/\/\r\n\/\/ \/\/\r\n\/\/ INCLUDES \/\/\r\n\/\/ \/\/\r\n\/\/-------------------------------------------------------------------------*\/\r\n\r\n#include <assert.h>\r\n\r\n#ifndef GUCEF_CORE_CNOTIFICATIONIDREGISTRY_H\r\n#include \"CNotificationIDRegistry.h\"\r\n#define GUCEF_CORE_CNOTIFICATIONIDREGISTRY_H\r\n#endif \/* GUCEF_CORE_CNOTIFICATIONIDREGISTRY_H ? *\/\r\n\r\n#ifndef GUCEF_CORE_GUCEF_ESSENTIALS_H\r\n#include \"gucef_essentials.h\"\r\n#define GUCEF_CORE_GUCEF_ESSENTIALS_H\r\n#endif \/* GUCEF_CORE_GUCEF_ESSENTIALS_H ? *\/\r\n\r\n#include \"CEvent.h\"\r\n\r\n\/*-------------------------------------------------------------------------\/\/\r\n\/\/ \/\/\r\n\/\/ NAMESPACE \/\/\r\n\/\/ \/\/\r\n\/\/-------------------------------------------------------------------------*\/\r\n\r\nnamespace GUCEF {\r\nnamespace CORE {\r\n\r\n\/*-------------------------------------------------------------------------\/\/\r\n\/\/ \/\/\r\n\/\/ UTILITIES \/\/\r\n\/\/ \/\/\r\n\/\/-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( void )\r\n : m_eventID( 0 ) ,\r\n m_eventName()\r\n{GUCEF_TRACE;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( const char* eventName )\r\n : m_eventID( 0 ) ,\r\n m_eventName( eventName )\r\n{GUCEF_TRACE;\r\n\r\n \/\/ Wait for delayed initialization\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( const CORE::CString& eventName )\r\n : m_eventID( 0 ) ,\r\n m_eventName( eventName )\r\n{GUCEF_TRACE;\r\n\r\n \/\/ Wait for delayed initialization\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( const UInt32 eventID ,\r\n const CString& eventName )\r\n : m_eventID( eventID ) ,\r\n m_eventName( eventName )\r\n{GUCEF_TRACE;\r\n\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( const CEvent& src )\r\n : m_eventID( src.m_eventID ) ,\r\n m_eventName( src.m_eventName )\r\n{GUCEF_TRACE;\r\n\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::~CEvent()\r\n{GUCEF_TRACE;\r\n\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent&\r\nCEvent::operator=( const CEvent& src )\r\n{GUCEF_TRACE;\r\n\r\n if ( &src != this )\r\n {\r\n m_eventName = src.m_eventName;\r\n m_eventID = src.m_eventID;\r\n }\r\n return *this;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent&\r\nCEvent::operator=( const CORE::CString& eventName )\r\n{GUCEF_TRACE;\r\n\r\n if ( eventName != m_eventName )\r\n {\r\n m_eventName = eventName;\r\n m_eventID = 0; \/\/ <- Wait for delayed initialization\r\n }\r\n return *this;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent&\r\nCEvent::operator=( const char* eventName )\r\n{GUCEF_TRACE;\r\n\r\n if ( eventName != m_eventName )\r\n {\r\n m_eventName = eventName;\r\n m_eventID = 0; \/\/ <- Wait for delayed initialization\r\n }\r\n return *this;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nbool\r\nCEvent::operator==( const CEvent& other ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ If you hit the asserts below then the event object was not initialized\r\n assert( m_eventID > 0 );\r\n assert( other.m_eventID > 0 );\r\n return m_eventID == other.m_eventID;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nbool\r\nCEvent::operator!=( const CEvent& other ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ If you hit the asserts below then the event object was not initialized\r\n assert( m_eventID > 0 );\r\n assert( other.m_eventID > 0 );\r\n return m_eventID != other.m_eventID;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nbool\r\nCEvent::operator<( const CEvent& other ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ If you hit the asserts below then the event object was not initialized\r\n assert( m_eventID > 0 );\r\n assert( other.m_eventID > 0 );\r\n return m_eventID < other.m_eventID;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nUInt32\r\nCEvent::GetID( void ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ If you hit the asserts below then the event object was not initialized\r\n assert( m_eventID > 0 );\r\n return m_eventID;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCORE::CString\r\nCEvent::GetName( void ) const\r\n{GUCEF_TRACE;\r\n\r\n return m_eventName;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nvoid\r\nCEvent::Initialize( void ) const\r\n{GUCEF_TRACE;\r\n \/*\r\n * In this rare occasion a const_cast is legit since we are preforming\r\n * an action that has conceptually already occurred,.. initialization.\r\n *\r\n * The fact that we cannot initialize objects right from the start\r\n * while allowing event objects to be defined globally is an implementation level problem.\r\n *\/\r\n const_cast< CEvent& >( *this ) = CORE::CCoreGlobal::Instance()->GetNotificationIDRegistry().Lookup( m_eventName, true );\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nbool\r\nCEvent::IsInitialized( void ) const\r\n{GUCEF_TRACE;\r\n\r\n return m_eventID > 0;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------\/\/\r\n\/\/ \/\/\r\n\/\/ NAMESPACE \/\/\r\n\/\/ \/\/\r\n\/\/-------------------------------------------------------------------------*\/\r\n\r\n}; \/* namespace CORE *\/\r\n}; \/* namespace GUCEF *\/\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n<commit_msg>Event: Don't perform redundant lookups. A lot of events are globally defined and as such benefit from a small check to ensure we can reduce redundant lookups of event IDs on object creation<commit_after>\/*\r\n * gucefCORE: GUCEF module providing O\/S abstraction and generic solutions\r\n * Copyright (C) 2002 - 2007. Dinand Vanvelzen\r\n *\r\n * This library is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n *\/\r\n\r\n\/*-------------------------------------------------------------------------\/\/\r\n\/\/ \/\/\r\n\/\/ INCLUDES \/\/\r\n\/\/ \/\/\r\n\/\/-------------------------------------------------------------------------*\/\r\n\r\n#include <assert.h>\r\n\r\n#ifndef GUCEF_CORE_CNOTIFICATIONIDREGISTRY_H\r\n#include \"CNotificationIDRegistry.h\"\r\n#define GUCEF_CORE_CNOTIFICATIONIDREGISTRY_H\r\n#endif \/* GUCEF_CORE_CNOTIFICATIONIDREGISTRY_H ? *\/\r\n\r\n#ifndef GUCEF_CORE_GUCEF_ESSENTIALS_H\r\n#include \"gucef_essentials.h\"\r\n#define GUCEF_CORE_GUCEF_ESSENTIALS_H\r\n#endif \/* GUCEF_CORE_GUCEF_ESSENTIALS_H ? *\/\r\n\r\n#include \"CEvent.h\"\r\n\r\n\/*-------------------------------------------------------------------------\/\/\r\n\/\/ \/\/\r\n\/\/ NAMESPACE \/\/\r\n\/\/ \/\/\r\n\/\/-------------------------------------------------------------------------*\/\r\n\r\nnamespace GUCEF {\r\nnamespace CORE {\r\n\r\n\/*-------------------------------------------------------------------------\/\/\r\n\/\/ \/\/\r\n\/\/ UTILITIES \/\/\r\n\/\/ \/\/\r\n\/\/-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( void )\r\n : m_eventID( 0 ) ,\r\n m_eventName()\r\n{GUCEF_TRACE;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( const char* eventName )\r\n : m_eventID( 0 ) ,\r\n m_eventName( eventName )\r\n{GUCEF_TRACE;\r\n\r\n \/\/ Wait for delayed initialization\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( const CORE::CString& eventName )\r\n : m_eventID( 0 ) ,\r\n m_eventName( eventName )\r\n{GUCEF_TRACE;\r\n\r\n \/\/ Wait for delayed initialization\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( const UInt32 eventID ,\r\n const CString& eventName )\r\n : m_eventID( eventID ) ,\r\n m_eventName( eventName )\r\n{GUCEF_TRACE;\r\n\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::CEvent( const CEvent& src )\r\n : m_eventID( src.m_eventID ) ,\r\n m_eventName( src.m_eventName )\r\n{GUCEF_TRACE;\r\n\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent::~CEvent()\r\n{GUCEF_TRACE;\r\n\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent&\r\nCEvent::operator=( const CEvent& src )\r\n{GUCEF_TRACE;\r\n\r\n if ( &src != this )\r\n {\r\n m_eventName = src.m_eventName;\r\n m_eventID = src.m_eventID;\r\n }\r\n return *this;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent&\r\nCEvent::operator=( const CORE::CString& eventName )\r\n{GUCEF_TRACE;\r\n\r\n if ( eventName != m_eventName )\r\n {\r\n m_eventName = eventName;\r\n m_eventID = 0; \/\/ <- Wait for delayed initialization\r\n }\r\n return *this;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCEvent&\r\nCEvent::operator=( const char* eventName )\r\n{GUCEF_TRACE;\r\n\r\n if ( eventName != m_eventName )\r\n {\r\n m_eventName = eventName;\r\n m_eventID = 0; \/\/ <- Wait for delayed initialization\r\n }\r\n return *this;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nbool\r\nCEvent::operator==( const CEvent& other ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ If you hit the asserts below then the event object was not initialized\r\n assert( m_eventID > 0 );\r\n assert( other.m_eventID > 0 );\r\n return m_eventID == other.m_eventID;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nbool\r\nCEvent::operator!=( const CEvent& other ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ If you hit the asserts below then the event object was not initialized\r\n assert( m_eventID > 0 );\r\n assert( other.m_eventID > 0 );\r\n return m_eventID != other.m_eventID;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nbool\r\nCEvent::operator<( const CEvent& other ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ If you hit the asserts below then the event object was not initialized\r\n assert( m_eventID > 0 );\r\n assert( other.m_eventID > 0 );\r\n return m_eventID < other.m_eventID;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nUInt32\r\nCEvent::GetID( void ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ If you hit the asserts below then the event object was not initialized\r\n assert( m_eventID > 0 );\r\n return m_eventID;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nCORE::CString\r\nCEvent::GetName( void ) const\r\n{GUCEF_TRACE;\r\n\r\n return m_eventName;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nvoid\r\nCEvent::Initialize( void ) const\r\n{GUCEF_TRACE;\r\n\r\n \/\/ For performance reasons we don't perform the lookup again on a non-zero id\r\n \/\/ Since this is for performance only we don't need to worry about thread safety on\r\n \/\/ the branch as a race condition merely results in an extra lookup\r\n if ( 0 == m_eventID )\r\n {\r\n \/*\r\n * In this rare occasion a const_cast is legit since we are preforming\r\n * an action that has conceptually already occurred,.. initialization.\r\n *\r\n * The fact that we cannot initialize objects right from the start\r\n * while allowing event objects to be defined globally is an implementation level problem.\r\n *\/\r\n const_cast< CEvent& >( *this ) = CORE::CCoreGlobal::Instance()->GetNotificationIDRegistry().Lookup( m_eventName, true );\r\n }\r\n}\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n\r\nbool\r\nCEvent::IsInitialized( void ) const\r\n{GUCEF_TRACE;\r\n\r\n return m_eventID > 0;\r\n}\r\n\r\n\/*-------------------------------------------------------------------------\/\/\r\n\/\/ \/\/\r\n\/\/ NAMESPACE \/\/\r\n\/\/ \/\/\r\n\/\/-------------------------------------------------------------------------*\/\r\n\r\n}; \/* namespace CORE *\/\r\n}; \/* namespace GUCEF *\/\r\n\r\n\/*-------------------------------------------------------------------------*\/\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright © 2020 Samsung Electronics Co Ltd and Contributors. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#include \"ReduceLayer.hpp\"\n#include \"LayerCloneBase.hpp\"\n\n#include <armnn\/TypesUtils.hpp>\n\n#include <backendsCommon\/WorkloadData.hpp>\n#include <backendsCommon\/WorkloadFactory.hpp>\n\nnamespace armnn\n{\n\nReduceLayer::ReduceLayer(const ReduceDescriptor& param, const char* name)\n : LayerWithParameters(1, 1, LayerType::Reduce, param, name)\n{\n}\n\nstd::unique_ptr<IWorkload> ReduceLayer::CreateWorkload(const IWorkloadFactory& factory) const\n{\n ReduceQueueDescriptor descriptor;\n return factory.CreateReduce(descriptor, PrepInfoAndDesc(descriptor));\n}\n\nReduceLayer* ReduceLayer::Clone(Graph& graph) const\n{\n return CloneBase<ReduceLayer>(graph, m_Param, GetName());\n}\n\nvoid ReduceLayer::ValidateTensorShapesFromInputs()\n{\n VerifyLayerConnections(1, CHECK_LOCATION());\n\n const TensorShape& outputShape = GetOutputSlot(0).GetTensorInfo().GetShape();\n\n VerifyShapeInferenceType(outputShape, m_ShapeInferenceMethod);\n\n const TensorInfo& input = GetInputSlot(0).GetConnection()->GetTensorInfo();\n\n ARMNN_ASSERT_MSG(input.GetNumDimensions() > 0 && input.GetNumDimensions() <= 4,\n \"ReduceLayer: Reduce supports up to 4D input.\");\n\n unsigned int rank = input.GetNumDimensions();\n unsigned int outputRank = 0;\n\n \/\/ Calculate output dimension\n if (m_Param.m_KeepDims)\n {\n outputRank = rank;\n }\n else if (m_Param.m_vAxis.empty())\n {\n outputRank = 1;\n }\n else if (m_Param.m_vAxis.size() > input.GetNumDimensions())\n {\n throw LayerValidationException(\"ReduceLayer: Dimensions to reduce can not be bigger than input dimensions\");\n }\n else\n {\n outputRank = input.GetNumDimensions() - armnn::numeric_cast<unsigned int>(m_Param.m_vAxis.size());\n if (outputRank == 0)\n {\n outputRank = 1;\n }\n }\n\n std::vector<unsigned int> dimSizes(outputRank, 1);\n if (!m_Param.m_vAxis.empty())\n {\n \/\/ Skip the dimension that has been reduced unless keepDims is true.\n unsigned int outputIndex = 0;\n for (unsigned int i = 0; i < input.GetNumDimensions(); ++i)\n {\n if (std::find(m_Param.m_vAxis.begin(), m_Param.m_vAxis.end(), i) == m_Param.m_vAxis.end())\n {\n dimSizes[outputIndex] = armnn::numeric_cast<unsigned int>(input.GetShape()[i]);\n ++outputIndex;\n }\n else if (m_Param.m_KeepDims)\n {\n dimSizes[outputIndex] = 1;\n ++outputIndex;\n }\n }\n }\n const TensorShape& inferredShape = TensorShape(outputRank, dimSizes.data());\n\n ValidateAndCopyShape(outputShape, inferredShape, m_ShapeInferenceMethod, \"ReduceLayer\");\n}\n\nvoid ReduceLayer::Accept(ILayerVisitor& visitor) const\n{\n visitor.VisitReduceLayer(this, GetParameters(), GetName());\n}\n\n} \/\/ namespace armnn\n<commit_msg>IVGCVSW-5767 'Regression on SqueezeNet v1.1'<commit_after>\/\/\n\/\/ Copyright © 2020 Samsung Electronics Co Ltd and Contributors. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#include \"ReduceLayer.hpp\"\n#include \"LayerCloneBase.hpp\"\n\n#include <armnn\/TypesUtils.hpp>\n\n#include <backendsCommon\/WorkloadData.hpp>\n#include <backendsCommon\/WorkloadFactory.hpp>\n\nnamespace armnn\n{\n\nReduceLayer::ReduceLayer(const ReduceDescriptor& param, const char* name)\n : LayerWithParameters(1, 1, LayerType::Reduce, param, name)\n{\n}\n\nstd::unique_ptr<IWorkload> ReduceLayer::CreateWorkload(const IWorkloadFactory& factory) const\n{\n ReduceQueueDescriptor descriptor;\n descriptor.m_Parameters.m_vAxis = m_Param.m_vAxis;\n descriptor.m_Parameters.m_KeepDims = m_Param.m_KeepDims;\n descriptor.m_Parameters.m_ReduceOperation = m_Param.m_ReduceOperation;\n SetAdditionalInfo(descriptor);\n\n return factory.CreateReduce(descriptor, PrepInfoAndDesc(descriptor));\n}\n\nReduceLayer* ReduceLayer::Clone(Graph& graph) const\n{\n auto layer = CloneBase<ReduceLayer>(graph, m_Param, GetName());\n layer->m_Param.m_vAxis = m_Param.m_vAxis;\n layer->m_Param.m_KeepDims = m_Param.m_KeepDims;\n layer->m_Param.m_ReduceOperation = m_Param.m_ReduceOperation;\n\n return std::move(layer);\n}\n\nvoid ReduceLayer::ValidateTensorShapesFromInputs()\n{\n VerifyLayerConnections(1, CHECK_LOCATION());\n\n const TensorShape& outputShape = GetOutputSlot(0).GetTensorInfo().GetShape();\n\n VerifyShapeInferenceType(outputShape, m_ShapeInferenceMethod);\n\n const TensorInfo& input = GetInputSlot(0).GetConnection()->GetTensorInfo();\n\n ARMNN_ASSERT_MSG(input.GetNumDimensions() > 0 && input.GetNumDimensions() <= 4,\n \"ReduceLayer: Reduce supports up to 4D input.\");\n\n unsigned int rank = input.GetNumDimensions();\n unsigned int outputRank = 0;\n\n \/\/ Calculate output dimension\n if (m_Param.m_KeepDims)\n {\n outputRank = rank;\n }\n else if (m_Param.m_vAxis.empty())\n {\n outputRank = 1;\n }\n else if (m_Param.m_vAxis.size() > input.GetNumDimensions())\n {\n throw LayerValidationException(\"ReduceLayer: Dimensions to reduce can not be bigger than input dimensions\");\n }\n else\n {\n outputRank = input.GetNumDimensions() - armnn::numeric_cast<unsigned int>(m_Param.m_vAxis.size());\n if (outputRank == 0)\n {\n outputRank = 1;\n }\n }\n\n std::vector<unsigned int> dimSizes(outputRank, 1);\n if (!m_Param.m_vAxis.empty())\n {\n \/\/ Skip the dimension that has been reduced unless keepDims is true.\n unsigned int outputIndex = 0;\n for (unsigned int i = 0; i < input.GetNumDimensions(); ++i)\n {\n if (std::find(m_Param.m_vAxis.begin(), m_Param.m_vAxis.end(), i) == m_Param.m_vAxis.end())\n {\n dimSizes[outputIndex] = armnn::numeric_cast<unsigned int>(input.GetShape()[i]);\n ++outputIndex;\n }\n else if (m_Param.m_KeepDims)\n {\n dimSizes[outputIndex] = 1;\n ++outputIndex;\n }\n }\n }\n const TensorShape& inferredShape = TensorShape(outputRank, dimSizes.data());\n\n ValidateAndCopyShape(outputShape, inferredShape, m_ShapeInferenceMethod, \"ReduceLayer\");\n}\n\nvoid ReduceLayer::Accept(ILayerVisitor& visitor) const\n{\n visitor.VisitReduceLayer(this, GetParameters(), GetName());\n}\n\n} \/\/ namespace armnn\n<|endoftext|>"} {"text":"<commit_before>\n\n\/\/#if ETH_JSONRPC && 1\n\n#include <boost\/test\/unit_test.hpp>\n#include <libdevcore\/Log.h>\n#include <libdevcore\/CommonIO.h>\n#include <libdevcore\/CommonJS.h>\n#include <libwebthree\/WebThree.h>\n#include <libethrpc\/EthStubServer.h>\n#include <libethrpc\/CorsHttpServer.h>\n#include <jsonrpc\/connectors\/httpserver.h>\n#include <jsonrpc\/connectors\/httpclient.h>\n#include \"JsonSpiritHeaders.h\"\n#include \"TestHelper.h\"\n#include \"ethstubclient.h\"\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\nnamespace js = json_spirit;\n\n\nnamespace jsonrpc_tests {\n\nstring name = \"Ethereum(++) tests\";\nstring dbPath;\ndev::WebThreeDirect web3(name, dbPath, true);\n\nauto_ptr<EthStubServer> jsonrpcServer;\nauto_ptr<EthStubClient> jsonrpcClient;\n\n\nstruct JsonrpcFixture {\n JsonrpcFixture()\n {\n cnote << \"setup jsonrpc\";\n\n web3.setIdealPeerCount(5);\n web3.ethereum()->setForceMining(true);\n jsonrpcServer = auto_ptr<EthStubServer>(new EthStubServer(new jsonrpc::CorsHttpServer(8080), web3));\n jsonrpcServer->StartListening();\n \n jsonrpcClient = auto_ptr<EthStubClient>(new EthStubClient(new jsonrpc::HttpClient(\"http:\/\/localhost:8080\")));\n }\n ~JsonrpcFixture()\n {\n cnote << \"teardown jsonrpc\";\n }\n};\n \nBOOST_GLOBAL_FIXTURE(JsonrpcFixture)\n\nBOOST_AUTO_TEST_CASE(jsonrpc_balanceAt)\n{\n cnote << \"Testing jsonrpc balanceAt...\";\n dev::KeyPair key = KeyPair::create();\n auto address = key.address();\n string balance = jsonrpcClient->balanceAt(toJS(address), 0);\n BOOST_CHECK_EQUAL(jsToDecimal(toJS(web3.ethereum()->balanceAt(address))), balance);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_block)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_call)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_coinbase)\n{\n cnote << \"Testing jsonrpc coinbase...\";\n string coinbase = jsonrpcClient->coinbase();\n BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3.ethereum()->address());\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_countAt)\n{\n cnote << \"Testing jsonrpc countAt...\";\n dev::KeyPair key = KeyPair::create();\n auto address = key.address();\n double countAt = jsonrpcClient->countAt(toJS(address), 0);\n BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3.ethereum()->countAt(address, 0));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_defaultBlock)\n{\n cnote << \"Testing jsonrpc defaultBlock...\";\n int defaultBlock = jsonrpcClient->defaultBlock();\n BOOST_CHECK_EQUAL(defaultBlock, web3.ethereum()->getDefault());\n}\n \nBOOST_AUTO_TEST_CASE(jsonrpc_fromAscii)\n{\n cnote << \"Testing jsonrpc fromAscii...\";\n string testString = \"1234567890987654\";\n string fromAscii = jsonrpcClient->fromAscii(32, testString);\n BOOST_CHECK_EQUAL(fromAscii, jsFromBinary(testString, 32));\n\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_fromFixed)\n{\n cnote << \"Testing jsonrpc fromFixed...\";\n string testString = \"1234567890987654\";\n double fromFixed = jsonrpcClient->fromFixed(testString);\n BOOST_CHECK_EQUAL(jsFromFixed(testString), fromFixed);\n BOOST_CHECK_EQUAL(testString, jsToFixed(fromFixed));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_gasPrice)\n{\n cnote << \"Testing jsonrpc gasPrice...\";\n string gasPrice = jsonrpcClient->gasPrice();\n BOOST_CHECK_EQUAL(gasPrice, toJS(10 * dev::eth::szabo));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_isListening)\n{\n \/\/TODO\n cnote << \"Testing jsonrpc isListening...\";\n string testString = \"1234567890987654\";\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_isMining)\n{\n cnote << \"Testing jsonrpc isMining...\";\n\n web3.ethereum()->startMining();\n bool miningOn = jsonrpcClient->isMining();\n BOOST_CHECK_EQUAL(miningOn, web3.ethereum()->isMining());\n\n web3.ethereum()->stopMining();\n bool miningOff = jsonrpcClient->isMining();\n BOOST_CHECK_EQUAL(miningOff, web3.ethereum()->isMining());\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_key)\n{\n cnote << \"Testing jsonrpc key...\";\n dev::KeyPair key = KeyPair::create();\n jsonrpcServer->setKeys({key});\n string clientSecret = jsonrpcClient->key();\n jsonrpcServer->setKeys({});\n BOOST_CHECK_EQUAL(jsToSecret(clientSecret), key.secret());\n}\n \nBOOST_AUTO_TEST_CASE(jsonrpc_keys)\n{\n cnote << \"Testing jsonrpc keys...\";\n std::vector <dev::KeyPair> keys = {KeyPair::create(), KeyPair::create()};\n jsonrpcServer->setKeys(keys);\n Json::Value k = jsonrpcClient->keys();\n jsonrpcServer->setKeys({});\n BOOST_CHECK_EQUAL(k.isArray(), true);\n BOOST_CHECK_EQUAL(k.size(), keys.size());\n for (unsigned i = 0; i < k.size(); i++)\n BOOST_CHECK_EQUAL(jsToSecret(k[i].asString()) , keys[i].secret());\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_lll)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_messages)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_number)\n{\n cnote << \"Testing jsonrpc number...\";\n int number = jsonrpcClient->number();\n BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_number2)\n{\n cnote << \"Testing jsonrpc number2...\";\n int number = jsonrpcClient->number();\n BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);\n dev::eth::mine(*(web3.ethereum()), 1);\n int numberAfter = jsonrpcClient->number();\n BOOST_CHECK_EQUAL(number + 1, numberAfter);\n BOOST_CHECK_EQUAL(numberAfter, web3.ethereum()->number() + 1);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_peerCount)\n{\n cnote << \"Testing jsonrpc peerCount...\";\n \/\/TODO\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_secretToAddress)\n{\n cnote << \"Testing jsonrpc secretToAddress...\";\n dev::KeyPair pair = dev::KeyPair::create();\n string address = jsonrpcClient->secretToAddress(toJS(pair.secret()));\n BOOST_CHECK_EQUAL(jsToAddress(address), pair.address());\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_setListening)\n{\n cnote << \"Testing jsonrpc setListening...\";\n \/\/TODO\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_setMining)\n{\n cnote << \"Testing jsonrpc setMining...\";\n\n jsonrpcClient->setMining(true);\n BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), true);\n\n jsonrpcClient->setMining(false);\n BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), false);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_sha3)\n{\n cnote << \"Testing jsonrpc sha3...\";\n string testString = \"1234567890987654\";\n string sha3 = jsonrpcClient->sha3(testString);\n BOOST_CHECK_EQUAL(jsToFixed<32>(sha3), dev::eth::sha3(jsToBytes(testString)));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_stateAt)\n{\n cnote << \"Testing jsonrpc stateAt...\";\n dev::KeyPair key = KeyPair::create();\n auto address = key.address();\n string stateAt = jsonrpcClient->stateAt(toJS(address), 0, \"0\");\n BOOST_CHECK_EQUAL(toJS(web3.ethereum()->stateAt(address, jsToU256(\"0\"), 0)), stateAt);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_toAscii)\n{\n cnote << \"Testing jsonrpc toAscii...\";\n string testString = \"1234567890987654\";\n string ascii = jsonrpcClient->toAscii(testString);\n BOOST_CHECK_EQUAL(jsToBinary(testString), ascii);\n BOOST_CHECK_EQUAL(testString, jsFromBinary(ascii)); \/\/ failing!\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_toDecimal)\n{\n cnote << \"Testing jsonrpc toDecimal...\";\n string testString = \"1234567890987654\";\n string decimal = jsonrpcClient->toDecimal(testString);\n BOOST_CHECK_EQUAL(jsToDecimal(testString), decimal);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_toFixed)\n{\n cnote << \"Testing jsonrpc toFixed...\";\n double testValue = 123567;\n string fixed = jsonrpcClient->toFixed(testValue);\n BOOST_CHECK_EQUAL(jsToFixed(testValue), fixed);\n BOOST_CHECK_EQUAL(testValue, jsFromFixed(fixed));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_transact)\n{\n cnote << \"Testing jsonrpc transact...\";\n dev::KeyPair key = KeyPair::create();\n auto address = key.address();\n auto receiver = KeyPair::create();\n \n web3.ethereum()->setAddress(address);\n dev::eth::mine(*(web3.ethereum()), 1);\n auto balance = web3.ethereum()->balanceAt(address, 0);\n BOOST_REQUIRE(balance > 0);\n auto txAmount = balance \/ 2u;\n auto gasPrice = 10 * dev::eth::szabo;\n auto gas = dev::eth::c_txGas;\n \n Json::Value t;\n t[\"from\"] = toJS(key.secret());\n t[\"value\"] = toJS(txAmount);\n t[\"to\"] = toJS(receiver.address());\n t[\"data\"] = toJS(bytes());\n t[\"gas\"] = toJS(gas);\n t[\"gasPrice\"] = toJS(gasPrice);\n \n jsonrpcClient->transact(t);\n \n dev::eth::mine(*(web3.ethereum()), 1);\n auto balance2 = web3.ethereum()->balanceAt(receiver.address());\n BOOST_REQUIRE(balance2 > 0);\n BOOST_CHECK_EQUAL(txAmount, balance2);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_transaction)\n{\n\n\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_uncle)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_watch)\n{\n\n}\n\n\n\n\n}\n\n\/\/#endif\n\n\n\n<commit_msg>common changes<commit_after>\n\n#if ETH_JSONRPC && 1\n\n#include <boost\/test\/unit_test.hpp>\n#include <libdevcore\/Log.h>\n#include <libdevcore\/CommonIO.h>\n#include <libdevcore\/CommonJS.h>\n#include <libwebthree\/WebThree.h>\n#include <libethrpc\/EthStubServer.h>\n#include <libethrpc\/CorsHttpServer.h>\n#include <jsonrpc\/connectors\/httpserver.h>\n#include <jsonrpc\/connectors\/httpclient.h>\n#include \"JsonSpiritHeaders.h\"\n#include \"TestHelper.h\"\n#include \"ethstubclient.h\"\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\nnamespace js = json_spirit;\n\n\nnamespace jsonrpc_tests {\n\nstring name = \"Ethereum(++) tests\";\nstring dbPath;\ndev::WebThreeDirect web3(name, dbPath, true);\n\nauto_ptr<EthStubServer> jsonrpcServer;\nauto_ptr<EthStubClient> jsonrpcClient;\n\n\nstruct JsonrpcFixture {\n JsonrpcFixture()\n {\n cnote << \"setup jsonrpc\";\n\n web3.setIdealPeerCount(5);\n web3.ethereum()->setForceMining(true);\n jsonrpcServer = auto_ptr<EthStubServer>(new EthStubServer(new jsonrpc::CorsHttpServer(8080), web3));\n jsonrpcServer->StartListening();\n \n jsonrpcClient = auto_ptr<EthStubClient>(new EthStubClient(new jsonrpc::HttpClient(\"http:\/\/localhost:8080\")));\n }\n ~JsonrpcFixture()\n {\n cnote << \"teardown jsonrpc\";\n }\n};\n \nBOOST_GLOBAL_FIXTURE(JsonrpcFixture)\n\nBOOST_AUTO_TEST_CASE(jsonrpc_balanceAt)\n{\n cnote << \"Testing jsonrpc balanceAt...\";\n dev::KeyPair key = KeyPair::create();\n auto address = key.address();\n string balance = jsonrpcClient->balanceAt(toJS(address), 0);\n BOOST_CHECK_EQUAL(jsToDecimal(toJS(web3.ethereum()->balanceAt(address))), balance);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_block)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_call)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_coinbase)\n{\n cnote << \"Testing jsonrpc coinbase...\";\n string coinbase = jsonrpcClient->coinbase();\n BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3.ethereum()->address());\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_countAt)\n{\n cnote << \"Testing jsonrpc countAt...\";\n dev::KeyPair key = KeyPair::create();\n auto address = key.address();\n double countAt = jsonrpcClient->countAt(toJS(address), 0);\n BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3.ethereum()->countAt(address, 0));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_defaultBlock)\n{\n cnote << \"Testing jsonrpc defaultBlock...\";\n int defaultBlock = jsonrpcClient->defaultBlock();\n BOOST_CHECK_EQUAL(defaultBlock, web3.ethereum()->getDefault());\n}\n \nBOOST_AUTO_TEST_CASE(jsonrpc_fromAscii)\n{\n cnote << \"Testing jsonrpc fromAscii...\";\n string testString = \"1234567890987654\";\n string fromAscii = jsonrpcClient->fromAscii(32, testString);\n BOOST_CHECK_EQUAL(fromAscii, jsFromBinary(testString, 32));\n\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_fromFixed)\n{\n cnote << \"Testing jsonrpc fromFixed...\";\n string testString = \"1234567890987654\";\n double fromFixed = jsonrpcClient->fromFixed(testString);\n BOOST_CHECK_EQUAL(jsFromFixed(testString), fromFixed);\n BOOST_CHECK_EQUAL(testString, jsToFixed(fromFixed));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_gasPrice)\n{\n cnote << \"Testing jsonrpc gasPrice...\";\n string gasPrice = jsonrpcClient->gasPrice();\n BOOST_CHECK_EQUAL(gasPrice, toJS(10 * dev::eth::szabo));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_isListening)\n{\n \/\/TODO\n cnote << \"Testing jsonrpc isListening...\";\n string testString = \"1234567890987654\";\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_isMining)\n{\n cnote << \"Testing jsonrpc isMining...\";\n\n web3.ethereum()->startMining();\n bool miningOn = jsonrpcClient->isMining();\n BOOST_CHECK_EQUAL(miningOn, web3.ethereum()->isMining());\n\n web3.ethereum()->stopMining();\n bool miningOff = jsonrpcClient->isMining();\n BOOST_CHECK_EQUAL(miningOff, web3.ethereum()->isMining());\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_key)\n{\n cnote << \"Testing jsonrpc key...\";\n dev::KeyPair key = KeyPair::create();\n jsonrpcServer->setKeys({key});\n string clientSecret = jsonrpcClient->key();\n jsonrpcServer->setKeys({});\n BOOST_CHECK_EQUAL(jsToSecret(clientSecret), key.secret());\n}\n \nBOOST_AUTO_TEST_CASE(jsonrpc_keys)\n{\n cnote << \"Testing jsonrpc keys...\";\n std::vector <dev::KeyPair> keys = {KeyPair::create(), KeyPair::create()};\n jsonrpcServer->setKeys(keys);\n Json::Value k = jsonrpcClient->keys();\n jsonrpcServer->setKeys({});\n BOOST_CHECK_EQUAL(k.isArray(), true);\n BOOST_CHECK_EQUAL(k.size(), keys.size());\n for (unsigned i = 0; i < k.size(); i++)\n BOOST_CHECK_EQUAL(jsToSecret(k[i].asString()) , keys[i].secret());\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_lll)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_messages)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_number)\n{\n cnote << \"Testing jsonrpc number...\";\n int number = jsonrpcClient->number();\n BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_number2)\n{\n cnote << \"Testing jsonrpc number2...\";\n int number = jsonrpcClient->number();\n BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);\n dev::eth::mine(*(web3.ethereum()), 1);\n int numberAfter = jsonrpcClient->number();\n BOOST_CHECK_EQUAL(number + 1, numberAfter);\n BOOST_CHECK_EQUAL(numberAfter, web3.ethereum()->number() + 1);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_peerCount)\n{\n cnote << \"Testing jsonrpc peerCount...\";\n \/\/TODO\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_secretToAddress)\n{\n cnote << \"Testing jsonrpc secretToAddress...\";\n dev::KeyPair pair = dev::KeyPair::create();\n string address = jsonrpcClient->secretToAddress(toJS(pair.secret()));\n BOOST_CHECK_EQUAL(jsToAddress(address), pair.address());\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_setListening)\n{\n cnote << \"Testing jsonrpc setListening...\";\n \/\/TODO\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_setMining)\n{\n cnote << \"Testing jsonrpc setMining...\";\n\n jsonrpcClient->setMining(true);\n BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), true);\n\n jsonrpcClient->setMining(false);\n BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), false);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_sha3)\n{\n cnote << \"Testing jsonrpc sha3...\";\n string testString = \"1234567890987654\";\n string sha3 = jsonrpcClient->sha3(testString);\n BOOST_CHECK_EQUAL(jsToFixed<32>(sha3), dev::eth::sha3(jsToBytes(testString)));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_stateAt)\n{\n cnote << \"Testing jsonrpc stateAt...\";\n dev::KeyPair key = KeyPair::create();\n auto address = key.address();\n string stateAt = jsonrpcClient->stateAt(toJS(address), 0, \"0\");\n BOOST_CHECK_EQUAL(toJS(web3.ethereum()->stateAt(address, jsToU256(\"0\"), 0)), stateAt);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_toAscii)\n{\n cnote << \"Testing jsonrpc toAscii...\";\n string testString = \"1234567890987654\";\n string ascii = jsonrpcClient->toAscii(testString);\n BOOST_CHECK_EQUAL(jsToBinary(testString), ascii);\n BOOST_CHECK_EQUAL(testString, jsFromBinary(ascii)); \/\/ failing!\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_toDecimal)\n{\n cnote << \"Testing jsonrpc toDecimal...\";\n string testString = \"1234567890987654\";\n string decimal = jsonrpcClient->toDecimal(testString);\n BOOST_CHECK_EQUAL(jsToDecimal(testString), decimal);\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_toFixed)\n{\n cnote << \"Testing jsonrpc toFixed...\";\n double testValue = 123567;\n string fixed = jsonrpcClient->toFixed(testValue);\n BOOST_CHECK_EQUAL(jsToFixed(testValue), fixed);\n BOOST_CHECK_EQUAL(testValue, jsFromFixed(fixed));\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_transact)\n{\n cnote << \"Testing jsonrpc transact...\";\n dev::KeyPair key = KeyPair::create();\n auto address = key.address();\n auto receiver = KeyPair::create();\n \n web3.ethereum()->setAddress(address);\n dev::eth::mine(*(web3.ethereum()), 1);\n auto balance = web3.ethereum()->balanceAt(address, 0);\n BOOST_REQUIRE(balance > 0);\n auto txAmount = balance \/ 2u;\n auto gasPrice = 10 * dev::eth::szabo;\n auto gas = dev::eth::c_txGas;\n \n Json::Value t;\n t[\"from\"] = toJS(key.secret());\n t[\"value\"] = toJS(txAmount);\n t[\"to\"] = toJS(receiver.address());\n t[\"data\"] = toJS(bytes());\n t[\"gas\"] = toJS(gas);\n t[\"gasPrice\"] = toJS(gasPrice);\n \n jsonrpcClient->transact(t);\n \n dev::eth::mine(*(web3.ethereum()), 1);\n auto balance2 = web3.ethereum()->balanceAt(receiver.address());\n auto number = web3.ethereum()->number();\n BOOST_REQUIRE(balance2 > 0);\n BOOST_CHECK_EQUAL(txAmount, balance2);\n \n \/\/ auto ax = jsToFixed(number);\n \/\/ Json::Value p = jsonrpcClient->transaction(0, jsToFixed(number));\n \/\/ TODO, check transactions\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_transaction)\n{\n \n\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_uncle)\n{\n}\n\nBOOST_AUTO_TEST_CASE(jsonrpc_watch)\n{\n\n}\n\n\n\n\n}\n\n#endif\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include <fcntl.h>\n#include <unistd.h>\n#include <linux\/input.h>\n#include \"EventDevice.hpp\"\n#include \"InputSystemLinux.hpp\"\n#include \"input\/KeyboardDevice.hpp\"\n#include \"input\/GamepadDevice.hpp\"\n#include \"input\/MouseDevice.hpp\"\n#include \"input\/TouchpadDevice.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Errors.hpp\"\n#include \"utils\/Log.hpp\"\n\nstatic const uint32_t BITS_PER_LONG = 8 * sizeof(long);\n#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) \/ (d))\n#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_LONG)\n\nstatic inline bool isBitSet(const unsigned long* array, int bit)\n{\n return (array[bit \/ BITS_PER_LONG] & (1LL << (bit % BITS_PER_LONG))) != 0;\n}\n\nnamespace ouzel\n{\n namespace input\n {\n EventDevice::EventDevice(InputSystemLinux& inputSystem, const std::string& initFilename):\n filename(initFilename)\n {\n fd = open(filename.c_str(), O_RDONLY);\n\n if (fd == -1)\n throw SystemError(\"Failed to open device file\");\n\n if (ioctl(fd, EVIOCGRAB, 1) == -1)\n Log(Log::Level::WARN) << \"Failed to grab device\";\n\n char deviceName[256];\n if (ioctl(fd, EVIOCGNAME(sizeof(deviceName) - 1), deviceName) == -1)\n Log(Log::Level::WARN) << \"Failed to get device name\";\n else\n {\n name = deviceName;\n Log(Log::Level::INFO) << \"Got device: \" << name;\n }\n\n unsigned long eventBits[BITS_TO_LONGS(EV_CNT)];\n unsigned long absBits[BITS_TO_LONGS(ABS_CNT)];\n unsigned long relBits[BITS_TO_LONGS(REL_CNT)];\n unsigned long keyBits[BITS_TO_LONGS(KEY_CNT)];\n\n if (ioctl(fd, EVIOCGBIT(0, sizeof(eventBits)), eventBits) == -1 ||\n ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits) == -1 ||\n ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), relBits) == -1 ||\n ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits) == -1)\n throw SystemError(\"Failed to get device event bits\");\n\n if (isBitSet(eventBits, EV_KEY) && (\n isBitSet(keyBits, KEY_1) ||\n isBitSet(keyBits, KEY_2) ||\n isBitSet(keyBits, KEY_3) ||\n isBitSet(keyBits, KEY_4) ||\n isBitSet(keyBits, KEY_5) ||\n isBitSet(keyBits, KEY_6) ||\n isBitSet(keyBits, KEY_7) ||\n isBitSet(keyBits, KEY_8) ||\n isBitSet(keyBits, KEY_9) ||\n isBitSet(keyBits, KEY_0)\n ))\n keyboardDevice.reset(new KeyboardDevice(inputSystem, inputSystem.getNextDeviceId()));\n\n if (isBitSet(eventBits, EV_ABS) && isBitSet(absBits, ABS_X) && isBitSet(absBits, ABS_Y))\n {\n if ((isBitSet(keyBits, BTN_STYLUS) || isBitSet(keyBits, BTN_TOOL_PEN)) || \/\/ tablet\n (isBitSet(keyBits, BTN_TOOL_FINGER) && !isBitSet(keyBits, BTN_TOOL_PEN)) || \/\/ touchpad\n isBitSet(keyBits, BTN_TOUCH)) \/\/ touchscreen\n {\n touchpadDevice.reset(new TouchpadDevice(inputSystem, inputSystem.getNextDeviceId()));\n\n input_absinfo info;\n\n if (ioctl(fd, EVIOCGABS(ABS_MT_SLOT), &info) == -1)\n throw SystemError(\"Failed to get device info\");\n\n touchSlots.resize(info.maximum + 1);\n\n if (ioctl(fd, EVIOCGABS(ABS_MT_POSITION_X), &info) == -1)\n throw SystemError(\"Failed to get device info\");\n \n touchMinX = info.minimum;\n touchMaxX = info.maximum;\n touchRangeX = touchMaxX - touchMinX;\n\n if (ioctl(fd, EVIOCGABS(ABS_MT_POSITION_Y), &info) == -1)\n throw SystemError(\"Failed to get device info\");\n\n touchMinY = info.minimum;\n touchMaxY = info.maximum;\n touchRangeY = touchMaxY - touchMinY;\n }\n else if (isBitSet(keyBits, BTN_MOUSE)) \/\/ mouse\n mouseDevice.reset(new MouseDevice(inputSystem, inputSystem.getNextDeviceId()));\n \n }\n else if (isBitSet(eventBits, EV_REL) && isBitSet(relBits, REL_X) && isBitSet(relBits, REL_Y))\n {\n if (isBitSet(keyBits, BTN_MOUSE))\n mouseDevice.reset(new MouseDevice(inputSystem, inputSystem.getNextDeviceId()));\n }\n\n if (isBitSet(keyBits, BTN_JOYSTICK) || \/\/ joystick\n isBitSet(keyBits, BTN_GAMEPAD)) \/\/ gamepad\n gamepadDevice.reset(new GamepadDevice(inputSystem, inputSystem.getNextDeviceId()));\n\n struct input_id id;\n ioctl(fd, EVIOCGID, &id);\n vendor = id.vendor;\n product = id.product;\n }\n\n EventDevice::~EventDevice()\n {\n if (fd != -1)\n {\n if (ioctl(fd, EVIOCGRAB, 0) == -1)\n Log(Log::Level::WARN) << \"Failed to release device\";\n\n close(fd);\n }\n }\n\n void EventDevice::update()\n {\n input_event events[32];\n ssize_t bytesRead = read(fd, events, sizeof(events));\n\n if (bytesRead == -1)\n throw SystemError(\"Failed to read from \" + filename); \/\/ TODO: disconnect the device\n\n int count = bytesRead \/ sizeof(input_event);\n\n for (int i = 0; i < count; ++i)\n {\n input_event& event = events[i];\n\n if (keyboardDevice)\n {\n switch (event.type)\n {\n case EV_KEY:\n if (event.value == 1 || event.value == 2) \/\/ press or repeat\n keyboardDevice->handleKeyPress(InputSystemLinux::convertKeyCode(event.code));\n else if (event.value == 0) \/\/ release\n keyboardDevice->handleKeyRelease(InputSystemLinux::convertKeyCode(event.code));\n break;\n }\n }\n if (mouseDevice)\n {\n switch (event.type)\n {\n case EV_ABS:\n {\n switch (event.code)\n {\n case ABS_X:\n cursorPosition.x = engine->getWindow()->convertWindowToNormalizedLocation(Vector2(static_cast<float>(event.value), 0.0F)).x;\n break;\n case ABS_Y:\n cursorPosition.y = engine->getWindow()->convertWindowToNormalizedLocation(Vector2(0.0F, static_cast<float>(event.value))).y;\n break;\n }\n\n mouseDevice->handleMove(cursorPosition);\n break;\n }\n case EV_REL:\n {\n Vector2 relativePos;\n\n switch (event.code)\n {\n case REL_X:\n relativePos.x = static_cast<float>(event.value);\n break;\n case REL_Y:\n relativePos.y = static_cast<float>(event.value);\n break;\n case REL_WHEEL:\n mouseDevice->handleScroll(Vector2(0.0F, static_cast<float>(event.value)), cursorPosition);\n break;\n case REL_HWHEEL:\n mouseDevice->handleScroll(Vector2(static_cast<float>(event.value), 0.0F), cursorPosition);\n break;\n }\n\n mouseDevice->handleRelativeMove(engine->getWindow()->convertWindowToNormalizedLocation(relativePos));\n break;\n }\n case EV_KEY:\n {\n Mouse::Button button = Mouse::Button::NONE;\n\n switch (event.code)\n {\n case BTN_LEFT:\n button = Mouse::Button::LEFT;\n break;\n case BTN_RIGHT:\n button = Mouse::Button::RIGHT;\n break;\n case BTN_MIDDLE:\n button = Mouse::Button::MIDDLE;\n break;\n }\n\n if (event.value == 1)\n mouseDevice->handleButtonPress(button, cursorPosition);\n else if (event.value == 0)\n mouseDevice->handleButtonRelease(button, cursorPosition);\n break;\n }\n }\n }\n if (touchpadDevice)\n {\n switch (event.type)\n {\n case EV_ABS:\n {\n switch (event.code)\n {\n case ABS_MT_SLOT:\n {\n currentTouchSlot = event.value;\n break;\n }\n case ABS_MT_TRACKING_ID:\n {\n if (event.value >= 0)\n {\n touchSlots[currentTouchSlot].trackingId = event.value;\n touchSlots[currentTouchSlot].action = Slot::Action::BEGIN;\n }\n else\n touchSlots[currentTouchSlot].action = Slot::Action::END;\n break;\n }\n case ABS_MT_POSITION_X:\n {\n touchSlots[currentTouchSlot].positionX = event.value;\n touchSlots[currentTouchSlot].action = Slot::Action::MOVE;\n break;\n }\n case ABS_MT_POSITION_Y:\n {\n touchSlots[currentTouchSlot].positionY = event.value;\n touchSlots[currentTouchSlot].action = Slot::Action::MOVE;\n break;\n }\n }\n break;\n }\n case EV_SYN:\n {\n switch (event.code)\n {\n case SYN_REPORT:\n {\n for (Slot& slot : touchSlots)\n {\n if (slot.action != Slot::Action::NONE)\n {\n Vector2 position(static_cast<float>(slot.positionX - touchMinX) \/ touchRangeX,\n static_cast<float>(slot.positionY - touchMinY) \/ touchRangeY);\n\n switch (slot.action)\n {\n case Slot::Action::NONE:\n break;\n case Slot::Action::BEGIN:\n touchpadDevice->handleTouchBegin(static_cast<uint64_t>(slot.trackingId), position, 1.0F);\n break;\n case Slot::Action::END:\n touchpadDevice->handleTouchEnd(static_cast<uint64_t>(slot.trackingId), position, 1.0F);\n break;\n case Slot::Action::MOVE:\n touchpadDevice->handleTouchMove(static_cast<uint64_t>(slot.trackingId), position, 1.0F);\n break;\n }\n\n slot.action = Slot::Action::NONE;\n }\n }\n break;\n }\n case SYN_DROPPED:\n {\n for (Slot& slot : touchSlots)\n slot.action = Slot::Action::NONE;\n break;\n }\n }\n break;\n }\n }\n }\n if (gamepadDevice)\n {\n switch(event.type)\n {\n case EV_ABS:\n {\n \/\/ TODO: implement\n break;\n }\n case EV_REL:\n {\n \/\/ TODO: implement\n break;\n }\n case EV_KEY:\n {\n \/\/ TODO: implement\n break;\n }\n }\n }\n }\n }\n } \/\/ namespace input\n} \/\/ namespace ouzel\n<commit_msg>Handle SYN_DROPPED<commit_after>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include <fcntl.h>\n#include <unistd.h>\n#include <linux\/input.h>\n#include \"EventDevice.hpp\"\n#include \"InputSystemLinux.hpp\"\n#include \"input\/KeyboardDevice.hpp\"\n#include \"input\/GamepadDevice.hpp\"\n#include \"input\/MouseDevice.hpp\"\n#include \"input\/TouchpadDevice.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Errors.hpp\"\n#include \"utils\/Log.hpp\"\n\nstatic const uint32_t BITS_PER_LONG = 8 * sizeof(long);\n#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) \/ (d))\n#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_LONG)\n\nstatic inline bool isBitSet(const unsigned long* array, int bit)\n{\n return (array[bit \/ BITS_PER_LONG] & (1LL << (bit % BITS_PER_LONG))) != 0;\n}\n\nnamespace ouzel\n{\n namespace input\n {\n EventDevice::EventDevice(InputSystemLinux& inputSystem, const std::string& initFilename):\n filename(initFilename)\n {\n fd = open(filename.c_str(), O_RDONLY);\n\n if (fd == -1)\n throw SystemError(\"Failed to open device file\");\n\n if (ioctl(fd, EVIOCGRAB, 1) == -1)\n Log(Log::Level::WARN) << \"Failed to grab device\";\n\n char deviceName[256];\n if (ioctl(fd, EVIOCGNAME(sizeof(deviceName) - 1), deviceName) == -1)\n Log(Log::Level::WARN) << \"Failed to get device name\";\n else\n {\n name = deviceName;\n Log(Log::Level::INFO) << \"Got device: \" << name;\n }\n\n unsigned long eventBits[BITS_TO_LONGS(EV_CNT)];\n unsigned long absBits[BITS_TO_LONGS(ABS_CNT)];\n unsigned long relBits[BITS_TO_LONGS(REL_CNT)];\n unsigned long keyBits[BITS_TO_LONGS(KEY_CNT)];\n\n if (ioctl(fd, EVIOCGBIT(0, sizeof(eventBits)), eventBits) == -1 ||\n ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits) == -1 ||\n ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), relBits) == -1 ||\n ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits) == -1)\n throw SystemError(\"Failed to get device event bits\");\n\n if (isBitSet(eventBits, EV_KEY) && (\n isBitSet(keyBits, KEY_1) ||\n isBitSet(keyBits, KEY_2) ||\n isBitSet(keyBits, KEY_3) ||\n isBitSet(keyBits, KEY_4) ||\n isBitSet(keyBits, KEY_5) ||\n isBitSet(keyBits, KEY_6) ||\n isBitSet(keyBits, KEY_7) ||\n isBitSet(keyBits, KEY_8) ||\n isBitSet(keyBits, KEY_9) ||\n isBitSet(keyBits, KEY_0)\n ))\n keyboardDevice.reset(new KeyboardDevice(inputSystem, inputSystem.getNextDeviceId()));\n\n if (isBitSet(eventBits, EV_ABS) && isBitSet(absBits, ABS_X) && isBitSet(absBits, ABS_Y))\n {\n if ((isBitSet(keyBits, BTN_STYLUS) || isBitSet(keyBits, BTN_TOOL_PEN)) || \/\/ tablet\n (isBitSet(keyBits, BTN_TOOL_FINGER) && !isBitSet(keyBits, BTN_TOOL_PEN)) || \/\/ touchpad\n isBitSet(keyBits, BTN_TOUCH)) \/\/ touchscreen\n {\n touchpadDevice.reset(new TouchpadDevice(inputSystem, inputSystem.getNextDeviceId()));\n\n input_absinfo info;\n\n if (ioctl(fd, EVIOCGABS(ABS_MT_SLOT), &info) == -1)\n throw SystemError(\"Failed to get device info\");\n\n touchSlots.resize(info.maximum + 1);\n\n if (ioctl(fd, EVIOCGABS(ABS_MT_POSITION_X), &info) == -1)\n throw SystemError(\"Failed to get device info\");\n \n touchMinX = info.minimum;\n touchMaxX = info.maximum;\n touchRangeX = touchMaxX - touchMinX;\n\n if (ioctl(fd, EVIOCGABS(ABS_MT_POSITION_Y), &info) == -1)\n throw SystemError(\"Failed to get device info\");\n\n touchMinY = info.minimum;\n touchMaxY = info.maximum;\n touchRangeY = touchMaxY - touchMinY;\n }\n else if (isBitSet(keyBits, BTN_MOUSE)) \/\/ mouse\n mouseDevice.reset(new MouseDevice(inputSystem, inputSystem.getNextDeviceId()));\n \n }\n else if (isBitSet(eventBits, EV_REL) && isBitSet(relBits, REL_X) && isBitSet(relBits, REL_Y))\n {\n if (isBitSet(keyBits, BTN_MOUSE))\n mouseDevice.reset(new MouseDevice(inputSystem, inputSystem.getNextDeviceId()));\n }\n\n if (isBitSet(keyBits, BTN_JOYSTICK) || \/\/ joystick\n isBitSet(keyBits, BTN_GAMEPAD)) \/\/ gamepad\n gamepadDevice.reset(new GamepadDevice(inputSystem, inputSystem.getNextDeviceId()));\n\n struct input_id id;\n ioctl(fd, EVIOCGID, &id);\n vendor = id.vendor;\n product = id.product;\n }\n\n EventDevice::~EventDevice()\n {\n if (fd != -1)\n {\n if (ioctl(fd, EVIOCGRAB, 0) == -1)\n Log(Log::Level::WARN) << \"Failed to release device\";\n\n close(fd);\n }\n }\n\n void EventDevice::update()\n {\n input_event events[32];\n ssize_t bytesRead = read(fd, events, sizeof(events));\n\n if (bytesRead == -1)\n throw SystemError(\"Failed to read from \" + filename); \/\/ TODO: disconnect the device\n\n int count = bytesRead \/ sizeof(input_event);\n\n for (int i = 0; i < count; ++i)\n {\n input_event& event = events[i];\n\n if (keyboardDevice)\n {\n switch (event.type)\n {\n case EV_KEY:\n if (event.value == 1 || event.value == 2) \/\/ press or repeat\n keyboardDevice->handleKeyPress(InputSystemLinux::convertKeyCode(event.code));\n else if (event.value == 0) \/\/ release\n keyboardDevice->handleKeyRelease(InputSystemLinux::convertKeyCode(event.code));\n break;\n }\n }\n if (mouseDevice)\n {\n switch (event.type)\n {\n case EV_ABS:\n {\n switch (event.code)\n {\n case ABS_X:\n cursorPosition.x = engine->getWindow()->convertWindowToNormalizedLocation(Vector2(static_cast<float>(event.value), 0.0F)).x;\n break;\n case ABS_Y:\n cursorPosition.y = engine->getWindow()->convertWindowToNormalizedLocation(Vector2(0.0F, static_cast<float>(event.value))).y;\n break;\n }\n\n mouseDevice->handleMove(cursorPosition);\n break;\n }\n case EV_REL:\n {\n Vector2 relativePos;\n\n switch (event.code)\n {\n case REL_X:\n relativePos.x = static_cast<float>(event.value);\n break;\n case REL_Y:\n relativePos.y = static_cast<float>(event.value);\n break;\n case REL_WHEEL:\n mouseDevice->handleScroll(Vector2(0.0F, static_cast<float>(event.value)), cursorPosition);\n break;\n case REL_HWHEEL:\n mouseDevice->handleScroll(Vector2(static_cast<float>(event.value), 0.0F), cursorPosition);\n break;\n }\n\n mouseDevice->handleRelativeMove(engine->getWindow()->convertWindowToNormalizedLocation(relativePos));\n break;\n }\n case EV_KEY:\n {\n Mouse::Button button = Mouse::Button::NONE;\n\n switch (event.code)\n {\n case BTN_LEFT:\n button = Mouse::Button::LEFT;\n break;\n case BTN_RIGHT:\n button = Mouse::Button::RIGHT;\n break;\n case BTN_MIDDLE:\n button = Mouse::Button::MIDDLE;\n break;\n }\n\n if (event.value == 1)\n mouseDevice->handleButtonPress(button, cursorPosition);\n else if (event.value == 0)\n mouseDevice->handleButtonRelease(button, cursorPosition);\n break;\n }\n }\n }\n if (touchpadDevice)\n {\n switch (event.type)\n {\n case EV_ABS:\n {\n switch (event.code)\n {\n case ABS_MT_SLOT:\n {\n currentTouchSlot = event.value;\n break;\n }\n case ABS_MT_TRACKING_ID:\n {\n if (event.value >= 0)\n {\n touchSlots[currentTouchSlot].trackingId = event.value;\n touchSlots[currentTouchSlot].action = Slot::Action::BEGIN;\n }\n else\n touchSlots[currentTouchSlot].action = Slot::Action::END;\n break;\n }\n case ABS_MT_POSITION_X:\n {\n touchSlots[currentTouchSlot].positionX = event.value;\n touchSlots[currentTouchSlot].action = Slot::Action::MOVE;\n break;\n }\n case ABS_MT_POSITION_Y:\n {\n touchSlots[currentTouchSlot].positionY = event.value;\n touchSlots[currentTouchSlot].action = Slot::Action::MOVE;\n break;\n }\n }\n break;\n }\n case EV_SYN:\n {\n switch (event.code)\n {\n case SYN_REPORT:\n {\n for (Slot& slot : touchSlots)\n {\n if (slot.action != Slot::Action::NONE)\n {\n Vector2 position(static_cast<float>(slot.positionX - touchMinX) \/ touchRangeX,\n static_cast<float>(slot.positionY - touchMinY) \/ touchRangeY);\n\n switch (slot.action)\n {\n case Slot::Action::NONE:\n break;\n case Slot::Action::BEGIN:\n touchpadDevice->handleTouchBegin(static_cast<uint64_t>(slot.trackingId), position, 1.0F);\n break;\n case Slot::Action::END:\n touchpadDevice->handleTouchEnd(static_cast<uint64_t>(slot.trackingId), position, 1.0F);\n break;\n case Slot::Action::MOVE:\n touchpadDevice->handleTouchMove(static_cast<uint64_t>(slot.trackingId), position, 1.0F);\n break;\n }\n\n slot.action = Slot::Action::NONE;\n }\n }\n break;\n }\n case SYN_DROPPED:\n {\n struct input_mt_request_layout\n {\n __u32 code;\n __s32 values[1];\n };\n\n size_t size = sizeof(__u32) + sizeof(__s32) * touchSlots.size();\n std::vector<uint8_t> data(size);\n\n input_mt_request_layout* request = reinterpret_cast<input_mt_request_layout*>(data.data());\n\n request->code = ABS_MT_TRACKING_ID;\n if (ioctl(fd, EVIOCGMTSLOTS(size), request) == -1)\n throw SystemError(\"Failed to get device info\");\n\n for (size_t i = 0; i < touchSlots.size(); ++i)\n {\n if (touchSlots[i].trackingId < 0 &&\n request->values[i] >= 0)\n {\n touchSlots[i].trackingId = request->values[i];\n touchSlots[i].action = Slot::Action::BEGIN;\n }\n else if (touchSlots[i].trackingId >= 0 &&\n request->values[i] < 0)\n {\n touchSlots[i].trackingId = request->values[i];\n touchSlots[i].action = Slot::Action::END;\n }\n }\n\n request->code = ABS_MT_POSITION_X;\n if (ioctl(fd, EVIOCGMTSLOTS(size), request) == -1)\n throw SystemError(\"Failed to get device info\");\n\n for (size_t i = 0; i < touchSlots.size(); ++i)\n {\n if (touchSlots[i].trackingId >= 0 &&\n touchSlots[i].positionX != request->values[i])\n {\n touchSlots[i].positionX = request->values[i];\n if (touchSlots[i].action == Slot::Action::NONE)\n touchSlots[i].action = Slot::Action::MOVE;\n }\n }\n \n request->code = ABS_MT_POSITION_Y;\n if (ioctl(fd, EVIOCGMTSLOTS(size), request) == -1)\n throw SystemError(\"Failed to get device info\");\n\n for (size_t i = 0; i < touchSlots.size(); ++i)\n {\n if (touchSlots[i].trackingId >= 0 &&\n touchSlots[i].positionY != request->values[i])\n {\n touchSlots[i].positionY = request->values[i];\n if (touchSlots[i].action == Slot::Action::NONE)\n touchSlots[i].action = Slot::Action::MOVE;\n }\n }\n\n input_absinfo info;\n if (ioctl(fd, EVIOCGABS(ABS_MT_SLOT), &info) == -1)\n throw SystemError(\"Failed to get device info\");\n currentTouchSlot = info.value;\n\n break;\n }\n }\n break;\n }\n }\n }\n if (gamepadDevice)\n {\n switch(event.type)\n {\n case EV_ABS:\n {\n \/\/ TODO: implement\n break;\n }\n case EV_REL:\n {\n \/\/ TODO: implement\n break;\n }\n case EV_KEY:\n {\n \/\/ TODO: implement\n break;\n }\n }\n }\n }\n }\n } \/\/ namespace input\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fix creation of substreams for OLE2<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief infrastructure for query optimizer\n\/\/\/\n\/\/\/ @file arangod\/Aql\/Optimizer.cpp\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2010-2014 triagens GmbH, Cologne, Germany\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\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Max Neunhoeffer\n\/\/\/ @author Copyright 2014, triagens GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Aql\/Optimizer.h\"\n#include \"Aql\/ExecutionEngine.h\"\n#include \"Aql\/OptimizerRules.h\"\n#include \"Cluster\/ServerState.h\"\n\nusing namespace triagens::aql;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- the optimizer class\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- static initializations\n\/\/ -----------------------------------------------------------------------------\n \ntriagens::basics::Mutex Optimizer::SetupLock;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief list of all rules\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::map<int, Optimizer::Rule> Optimizer::_rules;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief lookup from rule name to rule level\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::unordered_map<std::string, int> Optimizer::_ruleLookup;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors \/ destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief constructor, this will initialize the rules database\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nOptimizer::Optimizer (size_t maxNumberOfPlans) \n : _maxNumberOfPlans(maxNumberOfPlans > 0 ? maxNumberOfPlans : DefaultMaxNumberOfPlans) {\n\n if (_rules.empty()) {\n setupRules();\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief add a plan to the optimizer\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Optimizer::addPlan (ExecutionPlan* plan,\n RuleLevel level,\n bool wasModified) {\n TRI_ASSERT(plan != nullptr);\n\n _newPlans.push_back(plan, level);\n\n if (wasModified) {\n \/\/ register which rules modified \/ created the plan\n plan->addAppliedRule(_currentRule);\n plan->invalidateCost();\n }\n\n if (_newPlans.size() >= _maxNumberOfPlans) {\n return false;\n }\n \n return true; \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief the actual optimization\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint Optimizer::createPlans (ExecutionPlan* plan,\n std::vector<std::string> const& rulesSpecification,\n bool inspectSimplePlans) {\n if (! inspectSimplePlans &&\n ! ExecutionEngine::isCoordinator() && \n plan->isDeadSimple()) {\n \/\/ the plan is so simple that any further optimizations would probably cost\n \/\/ more than simply executing the plan\n _plans.clear();\n _plans.push_back(plan, 0);\n estimatePlans();\n\n return TRI_ERROR_NO_ERROR;\n }\n\n bool runOnlyRequiredRules = false;\n int leastDoneLevel = 0;\n\n TRI_ASSERT(! _rules.empty());\n int maxRuleLevel = _rules.rbegin()->first;\n\n \/\/ which optimizer rules are disabled?\n std::unordered_set<int> const&& disabledIds = getDisabledRuleIds(rulesSpecification);\n\n\n \/\/ _plans contains the previous optimisation result\n _plans.clear();\n _plans.push_back(plan, 0);\n\n _newPlans.clear();\n\n while (leastDoneLevel < maxRuleLevel) {\n \/\/ Find variable usage for all old plans now:\n for (auto p : _plans.list) {\n if (! p->varUsageComputed()) {\n p->findVarUsage();\n }\n }\n\n \/\/ std::cout << \"Have \" << _plans.size() << \" plans:\" << std::endl;\n \/*\n for (auto p : _plans.list) {\n p->show();\n std::cout << std::endl;\n }\n *\/\n\n \/\/ int count = 0;\n\n \/\/ For all current plans:\n while (_plans.size() > 0) {\n int level;\n auto p = _plans.pop_front(level);\n\n if (level >= maxRuleLevel) {\n _newPlans.push_back(p, level); \/\/ nothing to do, just keep it\n }\n else { \/\/ find next rule\n auto it = _rules.upper_bound(level);\n TRI_ASSERT(it != _rules.end());\n \n \/* \n std::cout << \"Trying rule \" << it->second.name << \" with level \"\n << it->first << \" on plan \" << count++\n << std::endl;\n *\/\n\n level = (*it).first;\n if ((runOnlyRequiredRules || disabledIds.find(level) != disabledIds.end()) &&\n (*it).second.canBeDisabled) {\n \/\/ we picked a disabled rule or we have reached the max number of plans\n \/\/ and just skip this rule\n level = it->first;\n\n _newPlans.push_back(p, level); \/\/ nothing to do, just keep it\n \/\/ now try next\n continue;\n }\n\n _currentRule = level;\n\n int res;\n try {\n res = (*it).second.func(this, p, &(it->second));\n }\n catch (...) {\n delete p;\n throw;\n }\n\n if (res != TRI_ERROR_NO_ERROR) {\n return res;\n }\n }\n\n \/\/ TODO: abort early here if we found a good-enough plan\n \/\/ a good-enough plan is probably every plan with costs below some\n \/\/ defined threshold. this requires plan costs to be calculated here\n }\n\n _plans.steal(_newPlans);\n leastDoneLevel = maxRuleLevel;\n for (auto l : _plans.levelDone) {\n if (l < leastDoneLevel) {\n leastDoneLevel = l;\n }\n }\n \/\/ std::cout << \"Least done level is \" << leastDoneLevel << std::endl;\n\n \/\/ Stop if the result gets out of hand:\n if (! runOnlyRequiredRules &&\n _plans.size() >= _maxNumberOfPlans) {\n \/\/ must still iterate over all REQUIRED remaining transformation rules \n \/\/ because there are some rules which are required to make the query\n \/\/ work in cluster mode\n runOnlyRequiredRules = true;\n }\n }\n \n TRI_ASSERT(_plans.size() >= 1);\n\n estimatePlans();\n sortPlans();\n \/*\n std::cout << \"Optimisation ends with \" << _plans.size() << \" plans.\"\n << std::endl;\n for (auto p : _plans.list) {\n p->show();\n std::cout << \"costing: \" << p->getCost() << std::endl;\n std::cout << std::endl;\n }\n *\/\n\n return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief translate a list of rule ids into rule name\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::vector<std::string> Optimizer::translateRules (std::vector<int> const& rules) {\n std::vector<std::string> names;\n\n for (auto r : rules) {\n auto it = _rules.find(r);\n if (it != _rules.end()) {\n names.emplace_back((*it).second.name);\n }\n }\n return names;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief estimatePlans\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Optimizer::estimatePlans () {\n for (auto p : _plans.list) {\n p->getCost();\n \/\/ this value is cached in the plan, so formally this step is\n \/\/ unnecessary, but for the sake of cleanliness...\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief sortPlans\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Optimizer::sortPlans () {\n std::sort(_plans.list.begin(), _plans.list.end(), [](ExecutionPlan* const& a, ExecutionPlan* const& b) -> bool {\n return a->getCost() < b->getCost();\n });\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief look up the ids of all disabled rules\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::unordered_set<int> Optimizer::getDisabledRuleIds (std::vector<std::string> const& names) const {\n std::unordered_set<int> disabled;\n\n \/\/ lookup ids of all disabled rules\n for (auto name : names) {\n if (name[0] == '-') {\n \/\/ disable rule\n if (name == \"-all\") {\n \/\/ disable all rules\n for (auto it : _rules) {\n disabled.insert(it.first);\n }\n }\n else {\n \/\/ disable a specific rule\n auto it = _ruleLookup.find(std::string(name.c_str() + 1));\n if (it != _ruleLookup.end()) {\n disabled.insert((*it).second);\n }\n }\n }\n else if (name[0] == '+') {\n \/\/ enable rule\n if (name == \"+all\") {\n \/\/ enable all rules\n disabled.clear();\n }\n else {\n auto it = _ruleLookup.find(std::string(name.c_str() + 1));\n if (it != _ruleLookup.end()) {\n disabled.erase((*it).second);\n }\n }\n }\n }\n\n return disabled;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief set up the optimizer rules once and forever\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Optimizer::setupRules () {\n MUTEX_LOCKER(SetupLock);\n \n if (! _rules.empty()) {\n \/\/ race condition... prevent duplicate registration of rules\n return;\n }\n\n \/\/ List all the rules in the system here:\n \/\/ lower level values mean earlier rule execution\n \n \/\/ note that levels must be unique\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ \"Pass 1\": moving nodes \"up\" (potentially outside loops):\n \/\/ please use levels between 1 and 99 here\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ move calculations up the dependency chain (to pull them out of\n \/\/ inner loops etc.)\n registerRule(\"move-calculations-up\",\n moveCalculationsUpRule,\n moveCalculationsUpRule_pass1, \n true);\n\n \/\/ move filters up the dependency chain (to make result sets as small\n \/\/ as possible as early as possible)\n registerRule(\"move-filters-up\",\n moveFiltersUpRule,\n moveFiltersUpRule_pass1,\n true);\n \n \/\/ remove redundant calculations\n registerRule(\"remove-redundant-calculations\", \n removeRedundantCalculationsRule,\n removeRedundantCalculationsRule_pass1, \n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \"Pass 2\": try to remove redundant or unnecessary nodes\n \/\/\/ use levels between 101 and 199 for this\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ remove filters from the query that are not necessary at all\n \/\/ filters that are always true will be removed entirely\n \/\/ filters that are always false will be replaced with a NoResults node\n registerRule(\"remove-unnecessary-filters\",\n removeUnnecessaryFiltersRule,\n removeUnnecessaryFiltersRule_pass2,\n true);\n \n \/\/ remove calculations that are never necessary\n registerRule(\"remove-unnecessary-calculations\", \n removeUnnecessaryCalculationsRule,\n removeUnnecessaryCalculationsRule_pass2,\n true);\n\n \/\/ remove redundant sort blocks\n registerRule(\"remove-redundant-sorts\",\n removeRedundantSorts,\n removeRedundantSorts_pass2,\n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \"Pass 3\": interchange EnumerateCollection nodes in all possible ways\n \/\/\/ this is level 500, please never let new plans from higher\n \/\/\/ levels go back to this or lower levels!\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n registerRule(\"interchange-adjacent-enumerations\", \n interchangeAdjacentEnumerations,\n interchangeAdjacentEnumerations_pass3,\n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ \"Pass 4\": moving nodes \"up\" (potentially outside loops) (second try):\n \/\/ please use levels between 501 and 599 here\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ move calculations up the dependency chain (to pull them out of\n \/\/ inner loops etc.)\n registerRule(\"move-calculations-up-2\",\n moveCalculationsUpRule,\n moveCalculationsUpRule_pass4,\n true);\n\n \/\/ move filters up the dependency chain (to make result sets as small\n \/\/ as possible as early as possible)\n registerRule(\"move-filters-up-2\",\n moveFiltersUpRule,\n moveFiltersUpRule_pass4,\n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \"Pass 5\": try to remove redundant or unnecessary nodes (second try)\n \/\/\/ use levels between 601 and 699 for this\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ remove filters from the query that are not necessary at all\n \/\/ filters that are always true will be removed entirely\n \/\/ filters that are always false will be replaced with a NoResults node\n registerRule(\"remove-unnecessary-filters-2\",\n removeUnnecessaryFiltersRule,\n removeUnnecessaryFiltersRule_pass5,\n true);\n \n \/\/ remove calculations that are never necessary\n registerRule(\"remove-unnecessary-calculations-2\", \n removeUnnecessaryCalculationsRule,\n removeUnnecessaryCalculationsRule_pass5,\n true);\n\n \/\/ remove redundant sort blocks\n registerRule(\"remove-redundant-sorts-2\",\n removeRedundantSorts,\n removeRedundantSorts_pass5,\n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \"Pass 6\": use indexes if possible for FILTER and\/or SORT nodes\n \/\/\/ use levels between 701 and 799 for this\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ try to find a filter after an enumerate collection and find an index . . . \n registerRule(\"use-index-range\",\n useIndexRange,\n useIndexRange_pass6,\n true);\n\n \/\/ try to find sort blocks which are superseeded by indexes\n registerRule(\"use-index-for-sort\",\n useIndexForSort,\n useIndexForSort_pass6,\n true);\n\n if (ExecutionEngine::isCoordinator()) {\n \/\/ distribute operations in cluster\n registerRule(\"scatter-in-cluster\",\n scatterInCluster,\n scatterInCluster_pass10,\n false);\n \n registerRule(\"distribute-in-cluster\",\n distributeInCluster,\n distributeInCluster_pass10,\n false);\n\n \/\/ distribute operations in cluster\n registerRule(\"distribute-filtercalc-to-cluster\",\n distributeFilternCalcToCluster,\n distributeFilternCalcToCluster_pass10,\n true);\n\n registerRule(\"distribute-sort-to-cluster\",\n distributeSortToCluster,\n distributeSortToCluster_pass10,\n true);\n \n registerRule(\"remove-unnecessary-remote-scatter\",\n removeUnnecessaryRemoteScatter,\n removeUnnecessaryRemoteScatter_pass10,\n true);\n \n registerRule(\"undistribute-remove-after-enum-coll\",\n undistributeRemoveAfterEnumColl,\n undistributeRemoveAfterEnumColl_pass10,\n true);\n\n }\n}\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"^\\\\(\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\\\\)\"\n\/\/ End:\n\n<commit_msg>Take out some debugging output.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief infrastructure for query optimizer\n\/\/\/\n\/\/\/ @file arangod\/Aql\/Optimizer.cpp\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2010-2014 triagens GmbH, Cologne, Germany\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\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Max Neunhoeffer\n\/\/\/ @author Copyright 2014, triagens GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Aql\/Optimizer.h\"\n#include \"Aql\/ExecutionEngine.h\"\n#include \"Aql\/OptimizerRules.h\"\n#include \"Cluster\/ServerState.h\"\n\nusing namespace triagens::aql;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- the optimizer class\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- static initializations\n\/\/ -----------------------------------------------------------------------------\n \ntriagens::basics::Mutex Optimizer::SetupLock;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief list of all rules\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::map<int, Optimizer::Rule> Optimizer::_rules;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief lookup from rule name to rule level\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::unordered_map<std::string, int> Optimizer::_ruleLookup;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors \/ destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief constructor, this will initialize the rules database\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nOptimizer::Optimizer (size_t maxNumberOfPlans) \n : _maxNumberOfPlans(maxNumberOfPlans > 0 ? maxNumberOfPlans : DefaultMaxNumberOfPlans) {\n\n if (_rules.empty()) {\n setupRules();\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief add a plan to the optimizer\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Optimizer::addPlan (ExecutionPlan* plan,\n RuleLevel level,\n bool wasModified) {\n TRI_ASSERT(plan != nullptr);\n\n _newPlans.push_back(plan, level);\n\n if (wasModified) {\n \/\/ register which rules modified \/ created the plan\n plan->addAppliedRule(_currentRule);\n plan->invalidateCost();\n }\n\n if (_newPlans.size() >= _maxNumberOfPlans) {\n return false;\n }\n \n return true; \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief the actual optimization\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint Optimizer::createPlans (ExecutionPlan* plan,\n std::vector<std::string> const& rulesSpecification,\n bool inspectSimplePlans) {\n if (! inspectSimplePlans &&\n ! ExecutionEngine::isCoordinator() && \n plan->isDeadSimple()) {\n \/\/ the plan is so simple that any further optimizations would probably cost\n \/\/ more than simply executing the plan\n _plans.clear();\n _plans.push_back(plan, 0);\n estimatePlans();\n\n return TRI_ERROR_NO_ERROR;\n }\n\n bool runOnlyRequiredRules = false;\n int leastDoneLevel = 0;\n\n TRI_ASSERT(! _rules.empty());\n int maxRuleLevel = _rules.rbegin()->first;\n\n \/\/ which optimizer rules are disabled?\n std::unordered_set<int> const&& disabledIds = getDisabledRuleIds(rulesSpecification);\n\n\n \/\/ _plans contains the previous optimisation result\n _plans.clear();\n _plans.push_back(plan, 0);\n\n _newPlans.clear();\n\n while (leastDoneLevel < maxRuleLevel) {\n \/\/ Find variable usage for all old plans now:\n for (auto p : _plans.list) {\n if (! p->varUsageComputed()) {\n p->findVarUsage();\n }\n }\n\n \/\/ std::cout << \"Have \" << _plans.size() << \" plans:\" << std::endl;\n \/*\n for (auto p : _plans.list) {\n p->show();\n std::cout << std::endl;\n }\n *\/\n\n \/\/ int count = 0;\n\n \/\/ For all current plans:\n while (_plans.size() > 0) {\n int level;\n auto p = _plans.pop_front(level);\n\n if (level >= maxRuleLevel) {\n _newPlans.push_back(p, level); \/\/ nothing to do, just keep it\n }\n else { \/\/ find next rule\n auto it = _rules.upper_bound(level);\n TRI_ASSERT(it != _rules.end());\n \n \/* \n std::cout << \"Trying rule \" << it->second.name << \" with level \"\n << it->first << \" on plan \" << count++\n << std::endl;\n *\/\n\n level = (*it).first;\n if ((runOnlyRequiredRules || disabledIds.find(level) != disabledIds.end()) &&\n (*it).second.canBeDisabled) {\n \/\/ we picked a disabled rule or we have reached the max number of plans\n \/\/ and just skip this rule\n level = it->first;\n\n _newPlans.push_back(p, level); \/\/ nothing to do, just keep it\n \/\/ now try next\n continue;\n }\n\n _currentRule = level;\n\n int res;\n try {\n res = (*it).second.func(this, p, &(it->second));\n }\n catch (...) {\n delete p;\n throw;\n }\n\n if (res != TRI_ERROR_NO_ERROR) {\n return res;\n }\n }\n\n \/\/ TODO: abort early here if we found a good-enough plan\n \/\/ a good-enough plan is probably every plan with costs below some\n \/\/ defined threshold. this requires plan costs to be calculated here\n }\n\n _plans.steal(_newPlans);\n leastDoneLevel = maxRuleLevel;\n for (auto l : _plans.levelDone) {\n if (l < leastDoneLevel) {\n leastDoneLevel = l;\n }\n }\n \/\/ std::cout << \"Least done level is \" << leastDoneLevel << std::endl;\n\n \/\/ Stop if the result gets out of hand:\n if (! runOnlyRequiredRules &&\n _plans.size() >= _maxNumberOfPlans) {\n \/\/ must still iterate over all REQUIRED remaining transformation rules \n \/\/ because there are some rules which are required to make the query\n \/\/ work in cluster mode\n runOnlyRequiredRules = true;\n }\n }\n \n TRI_ASSERT(_plans.size() >= 1);\n\n estimatePlans();\n sortPlans();\n#if 0\n \/\/ Only for debugging:\n std::cout << \"Optimisation ends with \" << _plans.size() << \" plans.\"\n << std::endl;\n for (auto p : _plans.list) {\n p->show();\n std::cout << \"costing: \" << p->getCost() << std::endl;\n std::cout << std::endl;\n }\n#endif\n\n return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief translate a list of rule ids into rule name\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::vector<std::string> Optimizer::translateRules (std::vector<int> const& rules) {\n std::vector<std::string> names;\n\n for (auto r : rules) {\n auto it = _rules.find(r);\n if (it != _rules.end()) {\n names.emplace_back((*it).second.name);\n }\n }\n return names;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief estimatePlans\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Optimizer::estimatePlans () {\n for (auto p : _plans.list) {\n p->getCost();\n \/\/ this value is cached in the plan, so formally this step is\n \/\/ unnecessary, but for the sake of cleanliness...\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief sortPlans\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Optimizer::sortPlans () {\n std::sort(_plans.list.begin(), _plans.list.end(), [](ExecutionPlan* const& a, ExecutionPlan* const& b) -> bool {\n return a->getCost() < b->getCost();\n });\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief look up the ids of all disabled rules\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::unordered_set<int> Optimizer::getDisabledRuleIds (std::vector<std::string> const& names) const {\n std::unordered_set<int> disabled;\n\n \/\/ lookup ids of all disabled rules\n for (auto name : names) {\n if (name[0] == '-') {\n \/\/ disable rule\n if (name == \"-all\") {\n \/\/ disable all rules\n for (auto it : _rules) {\n disabled.insert(it.first);\n }\n }\n else {\n \/\/ disable a specific rule\n auto it = _ruleLookup.find(std::string(name.c_str() + 1));\n if (it != _ruleLookup.end()) {\n disabled.insert((*it).second);\n }\n }\n }\n else if (name[0] == '+') {\n \/\/ enable rule\n if (name == \"+all\") {\n \/\/ enable all rules\n disabled.clear();\n }\n else {\n auto it = _ruleLookup.find(std::string(name.c_str() + 1));\n if (it != _ruleLookup.end()) {\n disabled.erase((*it).second);\n }\n }\n }\n }\n\n return disabled;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief set up the optimizer rules once and forever\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Optimizer::setupRules () {\n MUTEX_LOCKER(SetupLock);\n \n if (! _rules.empty()) {\n \/\/ race condition... prevent duplicate registration of rules\n return;\n }\n\n \/\/ List all the rules in the system here:\n \/\/ lower level values mean earlier rule execution\n \n \/\/ note that levels must be unique\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ \"Pass 1\": moving nodes \"up\" (potentially outside loops):\n \/\/ please use levels between 1 and 99 here\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ move calculations up the dependency chain (to pull them out of\n \/\/ inner loops etc.)\n registerRule(\"move-calculations-up\",\n moveCalculationsUpRule,\n moveCalculationsUpRule_pass1, \n true);\n\n \/\/ move filters up the dependency chain (to make result sets as small\n \/\/ as possible as early as possible)\n registerRule(\"move-filters-up\",\n moveFiltersUpRule,\n moveFiltersUpRule_pass1,\n true);\n \n \/\/ remove redundant calculations\n registerRule(\"remove-redundant-calculations\", \n removeRedundantCalculationsRule,\n removeRedundantCalculationsRule_pass1, \n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \"Pass 2\": try to remove redundant or unnecessary nodes\n \/\/\/ use levels between 101 and 199 for this\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ remove filters from the query that are not necessary at all\n \/\/ filters that are always true will be removed entirely\n \/\/ filters that are always false will be replaced with a NoResults node\n registerRule(\"remove-unnecessary-filters\",\n removeUnnecessaryFiltersRule,\n removeUnnecessaryFiltersRule_pass2,\n true);\n \n \/\/ remove calculations that are never necessary\n registerRule(\"remove-unnecessary-calculations\", \n removeUnnecessaryCalculationsRule,\n removeUnnecessaryCalculationsRule_pass2,\n true);\n\n \/\/ remove redundant sort blocks\n registerRule(\"remove-redundant-sorts\",\n removeRedundantSorts,\n removeRedundantSorts_pass2,\n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \"Pass 3\": interchange EnumerateCollection nodes in all possible ways\n \/\/\/ this is level 500, please never let new plans from higher\n \/\/\/ levels go back to this or lower levels!\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n registerRule(\"interchange-adjacent-enumerations\", \n interchangeAdjacentEnumerations,\n interchangeAdjacentEnumerations_pass3,\n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ \"Pass 4\": moving nodes \"up\" (potentially outside loops) (second try):\n \/\/ please use levels between 501 and 599 here\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ move calculations up the dependency chain (to pull them out of\n \/\/ inner loops etc.)\n registerRule(\"move-calculations-up-2\",\n moveCalculationsUpRule,\n moveCalculationsUpRule_pass4,\n true);\n\n \/\/ move filters up the dependency chain (to make result sets as small\n \/\/ as possible as early as possible)\n registerRule(\"move-filters-up-2\",\n moveFiltersUpRule,\n moveFiltersUpRule_pass4,\n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \"Pass 5\": try to remove redundant or unnecessary nodes (second try)\n \/\/\/ use levels between 601 and 699 for this\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ remove filters from the query that are not necessary at all\n \/\/ filters that are always true will be removed entirely\n \/\/ filters that are always false will be replaced with a NoResults node\n registerRule(\"remove-unnecessary-filters-2\",\n removeUnnecessaryFiltersRule,\n removeUnnecessaryFiltersRule_pass5,\n true);\n \n \/\/ remove calculations that are never necessary\n registerRule(\"remove-unnecessary-calculations-2\", \n removeUnnecessaryCalculationsRule,\n removeUnnecessaryCalculationsRule_pass5,\n true);\n\n \/\/ remove redundant sort blocks\n registerRule(\"remove-redundant-sorts-2\",\n removeRedundantSorts,\n removeRedundantSorts_pass5,\n true);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \"Pass 6\": use indexes if possible for FILTER and\/or SORT nodes\n \/\/\/ use levels between 701 and 799 for this\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ try to find a filter after an enumerate collection and find an index . . . \n registerRule(\"use-index-range\",\n useIndexRange,\n useIndexRange_pass6,\n true);\n\n \/\/ try to find sort blocks which are superseeded by indexes\n registerRule(\"use-index-for-sort\",\n useIndexForSort,\n useIndexForSort_pass6,\n true);\n\n if (ExecutionEngine::isCoordinator()) {\n \/\/ distribute operations in cluster\n registerRule(\"scatter-in-cluster\",\n scatterInCluster,\n scatterInCluster_pass10,\n false);\n \n registerRule(\"distribute-in-cluster\",\n distributeInCluster,\n distributeInCluster_pass10,\n false);\n\n \/\/ distribute operations in cluster\n registerRule(\"distribute-filtercalc-to-cluster\",\n distributeFilternCalcToCluster,\n distributeFilternCalcToCluster_pass10,\n true);\n\n registerRule(\"distribute-sort-to-cluster\",\n distributeSortToCluster,\n distributeSortToCluster_pass10,\n true);\n \n registerRule(\"remove-unnecessary-remote-scatter\",\n removeUnnecessaryRemoteScatter,\n removeUnnecessaryRemoteScatter_pass10,\n true);\n \n registerRule(\"undistribute-remove-after-enum-coll\",\n undistributeRemoveAfterEnumColl,\n undistributeRemoveAfterEnumColl_pass10,\n true);\n\n }\n}\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"^\\\\(\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\\\\)\"\n\/\/ End:\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Project: RooFit *\n * Package: RooFitModels *\n * File: $Id$\n * Authors: *\n * GR, Gerhard Raven, Nikhef & VU, Gerhard.Raven@nikhef.nl\n * *\n * Copyright (c) 2010, Nikhef & VU. All rights reserved.\n * *\n * Redistribution and use in source and binary forms, *\n * with or without modification, are permitted according to the terms *\n * listed in LICENSE (http:\/\/roofit.sourceforge.net\/license.txt) *\n *****************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ BEGIN_HTML\n\/\/ END_HTML\n\/\/\n\n#include \"RooFit.h\"\n#include \"Riostream.h\"\n#include <math.h>\n\n#include \"RooLegendre.h\"\n#include \"RooAbsReal.h\"\n#include \"Math\/SpecFunc.h\"\n#include \"TMath.h\"\n\nClassImp(RooLegendre)\n;\n\n\n\/\/_____________________________________________________________________________\nnamespace {\n inline double a(int p, int l, int m) {\n double r = TMath::Factorial(l+m)\/TMath::Factorial(m+p)\/TMath::Factorial(p)\/TMath::Factorial(l-m-2*p);\n r \/= pow(2.,m+2*p);\n return p%2==0 ? r : -r ;\n }\n}\n\n\/\/_____________________________________________________________________________\nRooLegendre::RooLegendre()\n{\n}\n\n\/\/_____________________________________________________________________________\nRooLegendre::RooLegendre(const char* name, const char* title, RooAbsReal& ctheta, int l, int m) \n : RooAbsReal(name, title)\n , _ctheta(\"ctheta\", \"ctheta\", this, ctheta)\n , _l1(l),_m1(m),_l2(0),_m2(0)\n{\n \/\/TODO: for now, we assume that ctheta has a range [-1,1]\n \/\/ should map the ctheta range onto this interval, and adjust integrals...\n\n \/\/TODO: we assume m>=0\n \/\/ should map m<0 back to m>=0...\n}\n\n\/\/_____________________________________________________________________________\nRooLegendre::RooLegendre(const char* name, const char* title, RooAbsReal& ctheta, int l1, int m1, int l2, int m2) \n : RooAbsReal(name, title)\n , _ctheta(\"ctheta\", \"ctheta\", this, ctheta)\n , _l1(l1),_m1(m1),_l2(l2),_m2(m2)\n{\n}\n\n\/\/_____________________________________________________________________________\nRooLegendre::RooLegendre(const RooLegendre& other, const char* name) \n : RooAbsReal(other, name)\n , _ctheta(\"ctheta\", this, other._ctheta)\n , _l1(other._l1), _m1(other._m1)\n , _l2(other._l2), _m2(other._m2)\n{\n}\n\n\/\/_____________________________________________________________________________\nDouble_t RooLegendre::evaluate() const \n{\n \/\/ TODO: check that 0<=m_i<=l_i; on the other hand, assoc_legendre already does that ;-)\n \/\/ Note: P_0^0 = 1, so P_l^m = P_l^m P_0^0\n double r = 1;\n if (_l1!=0||_m1!=0) r *= ROOT::Math::assoc_legendre(_l1,_m1,_ctheta);\n if (_l2!=0||_m2!=0) r *= ROOT::Math::assoc_legendre(_l2,_m2,_ctheta);\n if ((_m1+_m2)%2==1) r = -r;\n return r;\n}\n\n\/\/_____________________________________________________________________________\nInt_t RooLegendre::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const \n{\n \/\/ don't support indefinite integrals...\n if (rangeName && strlen(rangeName) ) return 0;\n if (matchArgs(allVars, analVars, _ctheta)) return 1;\n return 0;\n}\n\n\/\/_____________________________________________________________________________\nDouble_t RooLegendre::analyticalIntegral(Int_t code, const char* ) const \n{\n \/\/ this was verified to match mathematica for \n \/\/ l1 in [0,2], m1 in [0,l1], l2 in [l1,4], m2 in [0,l2]\n assert(code==1) ;\n if ( _m1==_m2 ) return ( _l1 == _l2) ? TMath::Factorial(_l1+_m2)\/TMath::Factorial(_l1-_m1)*double(2)\/(2*_l1+1) : 0.;\n if ( (_l1+_l2-_m1-_m2)%2 != 0 ) return 0; \/\/ these combinations are odd under x -> -x\n\n \/\/ from B.R. Wong, \"On the overlap integral of associated Legendre Polynomials\" 1998 J. Phys. A: Math. Gen. 31 1101\n \/\/ Note: this paper gets the sign wrong if _m1+_m2 is odd..\n \/\/ TODO: update to the result of http:\/\/iopscience.iop.org\/0305-4470\/32\/13\/011\/pdf\/0305-4470_32_13_011.pdf\n double r=0;\n for (int p1=0; 2*p1 <= _l1-_m1 ;++p1) {\n double a1 = a(p1,_l1,_m1);\n for (int p2=0; 2*p2 <= _l2-_m2 ; ++p2) {\n double a2 = a(p2,_l2,_m2);\n r+= a1*a2*TMath::Gamma( double(_l1+_l2-_m1-_m2-2*p1-2*p2+1)\/2 )*TMath::Gamma( double(_m1+_m2+2*p1+2*p2+2)\/2 );\n }\n }\n r \/= TMath::Gamma( double(_l1+_l2+3)\/2 );\n\n if ((_m1+_m2)%2==1) r = -r;\n return r;\n}\n\nInt_t RooLegendre::getMaxVal( const RooArgSet& \/*vars*\/) const {\n if (_m1==0&&_m2==0) return 1;\n \/\/ does anyone know the analytical expression for the max values in case m!=0??\n if (_l1<3&&_l2<3) return 1;\n return 0;\n}\n\nnamespace {\n inline double maxSingle(int i, int j) {\n assert(j<=i);\n \/\/ x0 : 1 (ordinary Legendre)\n if (j==0) return 1;\n assert(i<3);\n \/\/ 11: 1\n if (i<2) return 1;\n \/\/ 21: 3 22: 3\n static const double m2[3] = { 3,3 };\n return m2[j-1];\n }\n}\nDouble_t RooLegendre::maxVal( Int_t \/*code*\/) const {\n return maxSingle(_l1,_m1)*maxSingle(_l2,_m2);\n}\n<commit_msg><commit_after>\/*****************************************************************************\n * Project: RooFit *\n * Package: RooFitModels *\n * File: $Id$\n * Authors: *\n * GR, Gerhard Raven, Nikhef & VU, Gerhard.Raven@nikhef.nl\n * *\n * Copyright (c) 2010, Nikhef & VU. All rights reserved.\n * *\n * Redistribution and use in source and binary forms, *\n * with or without modification, are permitted according to the terms *\n * listed in LICENSE (http:\/\/roofit.sourceforge.net\/license.txt) *\n *****************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ BEGIN_HTML\n\/\/ END_HTML\n\/\/\n\n#include \"RooFit.h\"\n#include \"Riostream.h\"\n#include <math.h>\n#include <string>\n\n#include \"RooLegendre.h\"\n#include \"RooAbsReal.h\"\n#include \"Math\/SpecFunc.h\"\n#include \"TMath.h\"\n\nClassImp(RooLegendre)\n;\n\n\n\/\/_____________________________________________________________________________\nnamespace {\n inline double a(int p, int l, int m) {\n double r = TMath::Factorial(l+m)\/TMath::Factorial(m+p)\/TMath::Factorial(p)\/TMath::Factorial(l-m-2*p);\n r \/= pow(2.,m+2*p);\n return p%2==0 ? r : -r ;\n }\n}\n\n\/\/_____________________________________________________________________________\nRooLegendre::RooLegendre()\n{\n}\n\n\/\/_____________________________________________________________________________\nRooLegendre::RooLegendre(const char* name, const char* title, RooAbsReal& ctheta, int l, int m) \n : RooAbsReal(name, title)\n , _ctheta(\"ctheta\", \"ctheta\", this, ctheta)\n , _l1(l),_m1(m),_l2(0),_m2(0)\n{\n \/\/TODO: for now, we assume that ctheta has a range [-1,1]\n \/\/ should map the ctheta range onto this interval, and adjust integrals...\n\n \/\/TODO: we assume m>=0\n \/\/ should map m<0 back to m>=0...\n}\n\n\/\/_____________________________________________________________________________\nRooLegendre::RooLegendre(const char* name, const char* title, RooAbsReal& ctheta, int l1, int m1, int l2, int m2) \n : RooAbsReal(name, title)\n , _ctheta(\"ctheta\", \"ctheta\", this, ctheta)\n , _l1(l1),_m1(m1),_l2(l2),_m2(m2)\n{\n}\n\n\/\/_____________________________________________________________________________\nRooLegendre::RooLegendre(const RooLegendre& other, const char* name) \n : RooAbsReal(other, name)\n , _ctheta(\"ctheta\", this, other._ctheta)\n , _l1(other._l1), _m1(other._m1)\n , _l2(other._l2), _m2(other._m2)\n{\n}\n\n\/\/_____________________________________________________________________________\nDouble_t RooLegendre::evaluate() const \n{\n \/\/ TODO: check that 0<=m_i<=l_i; on the other hand, assoc_legendre already does that ;-)\n \/\/ Note: P_0^0 = 1, so P_l^m = P_l^m P_0^0\n#ifdef MATHMORE\n double r = 1;\n if (_l1!=0||_m1!=0) r *= ROOT::Math::assoc_legendre(_l1,_m1,_ctheta);\n if (_l2!=0||_m2!=0) r *= ROOT::Math::assoc_legendre(_l2,_m2,_ctheta);\n if ((_m1+_m2)%2==1) r = -r;\n return r;\n#else\n throw std::string(\"RooLegendre: ERROR: This class require installation of the MathMore library\") ;\n return 0 ;\n#endif\n}\n\n\/\/_____________________________________________________________________________\nInt_t RooLegendre::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const \n{\n \/\/ don't support indefinite integrals...\n if (rangeName && strlen(rangeName) ) return 0;\n if (matchArgs(allVars, analVars, _ctheta)) return 1;\n return 0;\n}\n\n\/\/_____________________________________________________________________________\nDouble_t RooLegendre::analyticalIntegral(Int_t code, const char* ) const \n{\n \/\/ this was verified to match mathematica for \n \/\/ l1 in [0,2], m1 in [0,l1], l2 in [l1,4], m2 in [0,l2]\n assert(code==1) ;\n if ( _m1==_m2 ) return ( _l1 == _l2) ? TMath::Factorial(_l1+_m2)\/TMath::Factorial(_l1-_m1)*double(2)\/(2*_l1+1) : 0.;\n if ( (_l1+_l2-_m1-_m2)%2 != 0 ) return 0; \/\/ these combinations are odd under x -> -x\n\n \/\/ from B.R. Wong, \"On the overlap integral of associated Legendre Polynomials\" 1998 J. Phys. A: Math. Gen. 31 1101\n \/\/ Note: this paper gets the sign wrong if _m1+_m2 is odd..\n \/\/ TODO: update to the result of http:\/\/iopscience.iop.org\/0305-4470\/32\/13\/011\/pdf\/0305-4470_32_13_011.pdf\n double r=0;\n for (int p1=0; 2*p1 <= _l1-_m1 ;++p1) {\n double a1 = a(p1,_l1,_m1);\n for (int p2=0; 2*p2 <= _l2-_m2 ; ++p2) {\n double a2 = a(p2,_l2,_m2);\n r+= a1*a2*TMath::Gamma( double(_l1+_l2-_m1-_m2-2*p1-2*p2+1)\/2 )*TMath::Gamma( double(_m1+_m2+2*p1+2*p2+2)\/2 );\n }\n }\n r \/= TMath::Gamma( double(_l1+_l2+3)\/2 );\n\n if ((_m1+_m2)%2==1) r = -r;\n return r;\n}\n\nInt_t RooLegendre::getMaxVal( const RooArgSet& \/*vars*\/) const {\n if (_m1==0&&_m2==0) return 1;\n \/\/ does anyone know the analytical expression for the max values in case m!=0??\n if (_l1<3&&_l2<3) return 1;\n return 0;\n}\n\nnamespace {\n inline double maxSingle(int i, int j) {\n assert(j<=i);\n \/\/ x0 : 1 (ordinary Legendre)\n if (j==0) return 1;\n assert(i<3);\n \/\/ 11: 1\n if (i<2) return 1;\n \/\/ 21: 3 22: 3\n static const double m2[3] = { 3,3 };\n return m2[j-1];\n }\n}\nDouble_t RooLegendre::maxVal( Int_t \/*code*\/) const {\n return maxSingle(_l1,_m1)*maxSingle(_l2,_m2);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inwnt.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2006-04-07 14:38:15 $\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 _SAL_CONFIG_H_\n#include <sal\/config.h>\n#endif\n\n#include <windef.h> \/\/ needed by winnls.h\n#include <winbase.h> \/\/ needed by winnls.h\n#include <winnls.h>\n\n#ifndef INCLUDED_RTL_INSTANCE_HXX\n#include <rtl\/instance.hxx>\n#endif\n\n#ifndef INCLUDED_I18NPOOL_MSLANGID_HXX\n#include \"i18npool\/mslangid.hxx\"\n#endif\n\nstatic LanguageType nImplSystemLanguage = LANGUAGE_DONTKNOW;\nstatic LanguageType nImplSystemUILanguage = LANGUAGE_DONTKNOW;\n\n\/\/ =======================================================================\n\nstatic LanguageType GetSVLang( LANGID nWinLangId )\n{\n \/\/ No Translation, we work with the original MS code without the SORT_ID.\n \/\/ So we can get never LANG-ID's from MS, which are currently not defined\n \/\/ by us.\n return LanguageType( static_cast<sal_uInt16>(nWinLangId & 0xffff));\n}\n\n\/\/ -----------------------------------------------------------------------\n\ntypedef LANGID (WINAPI *getLangFromEnv)();\n\nstatic void getPlatformSystemLanguageImpl( LanguageType& rSystemLanguage,\n getLangFromEnv pGetUserDefault, getLangFromEnv pGetSystemDefault )\n{\n LanguageType nLang = rSystemLanguage;\n if ( nLang == LANGUAGE_DONTKNOW )\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex());\n nLang = rSystemLanguage;\n if ( nLang == LANGUAGE_DONTKNOW )\n {\n LANGID nLangId;\n\n nLangId = (pGetUserDefault)();\n nLang = GetSVLang( nLangId );\n\n if ( nLang == LANGUAGE_DONTKNOW )\n {\n nLangId = (pGetSystemDefault)();\n nLang = GetSVLang( nLangId );\n }\n OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();\n rSystemLanguage = nLang;\n }\n else\n OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nLanguageType MsLangId::getPlatformSystemLanguage()\n{\n getPlatformSystemLanguageImpl( nImplSystemLanguage,\n &GetUserDefaultLangID, &GetSystemDefaultLangID);\n return nImplSystemLanguage;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nLanguageType MsLangId::getPlatformSystemUILanguage()\n{\n \/\/ TODO: this could be distinguished, #if(WINVER >= 0x0500)\n \/\/ needs _run_ time differentiation though, not at compile time.\n#if 0\n getPlatformSystemLanguageImpl( nImplSystemUILanguage,\n &GetUserDefaultUILanguage, &GetSystemDefaultUILanguage);\n#endif\n getPlatformSystemLanguageImpl( nImplSystemUILanguage,\n &GetUserDefaultLangID, &GetSystemDefaultLangID);\n return nImplSystemUILanguage;\n}\n<commit_msg>INTEGRATION: CWS warnings01 (1.2.18); FILE MERGED 2006\/05\/29 09:59:28 sb 1.2.18.1: #i53898# Made code warning-free and\/or compile at all after resync to SRC680m170.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inwnt.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 04:46:25 $\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 _SAL_CONFIG_H_\n#include <sal\/config.h>\n#endif\n\n#pragma warning(push,1) \/\/ disable warnings within system headers\n#include <windef.h> \/\/ needed by winnls.h\n#include <winbase.h> \/\/ needed by winnls.h\n#include <winnls.h>\n#pragma warning(pop)\n\n#ifndef INCLUDED_RTL_INSTANCE_HXX\n#include <rtl\/instance.hxx>\n#endif\n\n#ifndef INCLUDED_I18NPOOL_MSLANGID_HXX\n#include \"i18npool\/mslangid.hxx\"\n#endif\n\nstatic LanguageType nImplSystemLanguage = LANGUAGE_DONTKNOW;\nstatic LanguageType nImplSystemUILanguage = LANGUAGE_DONTKNOW;\n\n\/\/ =======================================================================\n\nstatic LanguageType GetSVLang( LANGID nWinLangId )\n{\n \/\/ No Translation, we work with the original MS code without the SORT_ID.\n \/\/ So we can get never LANG-ID's from MS, which are currently not defined\n \/\/ by us.\n return LanguageType( static_cast<sal_uInt16>(nWinLangId & 0xffff));\n}\n\n\/\/ -----------------------------------------------------------------------\n\ntypedef LANGID (WINAPI *getLangFromEnv)();\n\nstatic void getPlatformSystemLanguageImpl( LanguageType& rSystemLanguage,\n getLangFromEnv pGetUserDefault, getLangFromEnv pGetSystemDefault )\n{\n LanguageType nLang = rSystemLanguage;\n if ( nLang == LANGUAGE_DONTKNOW )\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex());\n nLang = rSystemLanguage;\n if ( nLang == LANGUAGE_DONTKNOW )\n {\n LANGID nLangId;\n\n nLangId = (pGetUserDefault)();\n nLang = GetSVLang( nLangId );\n\n if ( nLang == LANGUAGE_DONTKNOW )\n {\n nLangId = (pGetSystemDefault)();\n nLang = GetSVLang( nLangId );\n }\n OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();\n rSystemLanguage = nLang;\n }\n else\n OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nLanguageType MsLangId::getPlatformSystemLanguage()\n{\n getPlatformSystemLanguageImpl( nImplSystemLanguage,\n &GetUserDefaultLangID, &GetSystemDefaultLangID);\n return nImplSystemLanguage;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nLanguageType MsLangId::getPlatformSystemUILanguage()\n{\n \/\/ TODO: this could be distinguished, #if(WINVER >= 0x0500)\n \/\/ needs _run_ time differentiation though, not at compile time.\n#if 0\n getPlatformSystemLanguageImpl( nImplSystemUILanguage,\n &GetUserDefaultUILanguage, &GetSystemDefaultUILanguage);\n#endif\n getPlatformSystemLanguageImpl( nImplSystemUILanguage,\n &GetUserDefaultLangID, &GetSystemDefaultLangID);\n return nImplSystemUILanguage;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2012, Stuart W Baker\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 met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file HwInit.cxx\n * This file represents the interrupt vector table for TI Stellaris MCUs.\n *\n * @author Stuart W. Baker\n * @date 5 January 2013\n *\/\n\n#define PART_LM4F120H5QR\n\n#include <cstdint>\n#include <new>\n\n#include \"inc\/hw_types.h\"\n#include \"inc\/hw_memmap.h\"\n#include \"inc\/hw_ints.h\"\n#include \"driverlib\/rom.h\"\n#include \"driverlib\/rom_map.h\"\n#include \"driverlib\/sysctl.h\"\n#include \"driverlib\/gpio.h\"\n#include \"driverlib\/timer.h\"\n#include \"driverlib\/interrupt.h\"\n#include \"os\/OS.hxx\"\n#include \"StellarisDev.hxx\"\n\n\/** override stdin *\/\nconst char *STDIN_DEVICE = \"\/dev\/ser0\";\n\n\/** override stdout *\/\nconst char *STDOUT_DEVICE = \"\/dev\/ser0\";\n\n\/** override stderr *\/\nconst char *STDERR_DEVICE = \"\/dev\/ser0\";\n\n\/** USB Device CDC serial driver instance *\/\nstatic StellarisCdc cdc0(\"\/dev\/serUSB0\");\n\n\/** UART 0 serial driver instance *\/\nstatic StellarisUart uart0(\"\/dev\/ser0\", UART0_BASE);\n\n\/** CAN 0 CAN driver instance *\/\nstatic StellarisCan can0(\"\/dev\/can0\", CAN0_BASE);\n\n\/** Blink LED *\/\nextern \"C\" {\nuint32_t blinker_pattern = 0;\nstatic uint32_t rest_pattern = 0;\n\nvoid resetblink(uint32_t pattern)\n{\n blinker_pattern = pattern;\n \/* make a timer event trigger immediately *\/\n}\n\nvoid timer5a_interrupt_handler(void)\n{\n \/\/\n \/\/ Clear the timer interrupt.\n \/\/\n MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);\n \/\/ Set output LED.\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, (rest_pattern & 1) ? GPIO_PIN_1 : 0);\n \/\/ Shift and maybe reset pattern.\n rest_pattern >>= 1;\n if (!rest_pattern)\n rest_pattern = blinker_pattern;\n}\n\nvoid diewith(uint32_t pattern) {\n vPortClearInterruptMask( 0x20 );\n asm(\"cpsie i\\n\");\n\n resetblink(pattern);\n while(1);\n}\n\n}\n\n\/** Initialize the processor hardware.\n *\/\nvoid hw_init(void)\n{\n \/* Globally disables interrupts until the FreeRTOS scheduler is up. *\/\n asm(\"cpsid i\\n\");\n\n \/* Setup the system clock. *\/\n MAP_SysCtlClockSet( SYSCTL_SYSDIV_10 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ );\n\n \/* Red LED pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, GPIO_PIN_1);\n MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1);\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, GPIO_PIN_1);\n\n \/* Blinker timer initialization. *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);\n MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);\n MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() \/ 8);\n MAP_IntEnable(INT_TIMER5A);\n \/* This interrupt should hit even during kernel operations. *\/\n MAP_IntPrioritySet(INT_TIMER5A, 0);\n MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);\n MAP_TimerEnable(TIMER5_BASE, TIMER_A);\n\n \/* UART0 pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);\n MAP_GPIOPinConfigure(GPIO_PA0_U0RX);\n MAP_GPIOPinConfigure(GPIO_PA1_U0TX);\n MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);\n\n \/* USB0 pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);\n MAP_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4);\n\n \/* CAN pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);\n MAP_GPIOPinConfigure(GPIO_PE4_CAN0RX);\n MAP_GPIOPinConfigure(GPIO_PE5_CAN0TX);\n MAP_GPIOPinTypeCAN(GPIO_PORTE_BASE, GPIO_PIN_4 | GPIO_PIN_5);\n \n \/* Blue LED pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, GPIO_PIN_2);\n MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_2);\n \n \/* Green LED pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_3, GPIO_PIN_3);\n MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3);\n \n \/* Initialize timer0a interrupt *\/\n\n MAP_IntPrioritySet(INT_USB0, 0xff); \/\/ USB interrupt low priority\n\n \n\n}\n\n<commit_msg>Fixes style of HwInit.cxx<commit_after>\/** \\copyright\n * Copyright (c) 2012, Stuart W Baker\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 met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file HwInit.cxx\n * This file represents the interrupt vector table for TI Stellaris MCUs.\n *\n * @author Stuart W. Baker\n * @date 5 January 2013\n *\/\n\n#define PART_LM4F120H5QR\n\n#include <cstdint>\n#include <new>\n\n#include \"inc\/hw_types.h\"\n#include \"inc\/hw_memmap.h\"\n#include \"inc\/hw_ints.h\"\n#include \"driverlib\/rom.h\"\n#include \"driverlib\/rom_map.h\"\n#include \"driverlib\/sysctl.h\"\n#include \"driverlib\/gpio.h\"\n#include \"driverlib\/timer.h\"\n#include \"driverlib\/interrupt.h\"\n#include \"os\/OS.hxx\"\n#include \"StellarisDev.hxx\"\n\n\/** override stdin *\/\nconst char *STDIN_DEVICE = \"\/dev\/ser0\";\n\n\/** override stdout *\/\nconst char *STDOUT_DEVICE = \"\/dev\/ser0\";\n\n\/** override stderr *\/\nconst char *STDERR_DEVICE = \"\/dev\/ser0\";\n\n\/** USB Device CDC serial driver instance *\/\nstatic StellarisCdc cdc0(\"\/dev\/serUSB0\");\n\n\/** UART 0 serial driver instance *\/\nstatic StellarisUart uart0(\"\/dev\/ser0\", UART0_BASE);\n\n\/** CAN 0 CAN driver instance *\/\nstatic StellarisCan can0(\"\/dev\/can0\", CAN0_BASE);\n\n\/** Blink LED *\/\nextern \"C\" {\nuint32_t blinker_pattern = 0;\nstatic uint32_t rest_pattern = 0;\n\nvoid resetblink(uint32_t pattern)\n{\n blinker_pattern = pattern;\n \/* make a timer event trigger immediately *\/\n}\n\nvoid timer5a_interrupt_handler(void)\n{\n \/\/\n \/\/ Clear the timer interrupt.\n \/\/\n MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);\n \/\/ Set output LED.\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1,\n (rest_pattern & 1) ? GPIO_PIN_1 : 0);\n \/\/ Shift and maybe reset pattern.\n rest_pattern >>= 1;\n if (!rest_pattern)\n rest_pattern = blinker_pattern;\n}\n\nvoid diewith(uint32_t pattern)\n{\n vPortClearInterruptMask(0x20);\n asm(\"cpsie i\\n\");\n\n resetblink(pattern);\n while (1)\n ;\n}\n}\n\n\/** Initialize the processor hardware.\n *\/\nvoid hw_init(void)\n{\n \/* Globally disables interrupts until the FreeRTOS scheduler is up. *\/\n asm(\"cpsid i\\n\");\n\n \/* Setup the system clock. *\/\n MAP_SysCtlClockSet(SYSCTL_SYSDIV_10 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |\n SYSCTL_XTAL_16MHZ);\n\n \/* Red LED pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, GPIO_PIN_1);\n MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1);\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, GPIO_PIN_1);\n\n \/* Blinker timer initialization. *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);\n MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);\n MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() \/ 8);\n MAP_IntEnable(INT_TIMER5A);\n \/* This interrupt should hit even during kernel operations. *\/\n MAP_IntPrioritySet(INT_TIMER5A, 0);\n MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);\n MAP_TimerEnable(TIMER5_BASE, TIMER_A);\n\n \/* UART0 pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);\n MAP_GPIOPinConfigure(GPIO_PA0_U0RX);\n MAP_GPIOPinConfigure(GPIO_PA1_U0TX);\n MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);\n\n \/* USB0 pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);\n MAP_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4);\n\n \/* CAN pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);\n MAP_GPIOPinConfigure(GPIO_PE4_CAN0RX);\n MAP_GPIOPinConfigure(GPIO_PE5_CAN0TX);\n MAP_GPIOPinTypeCAN(GPIO_PORTE_BASE, GPIO_PIN_4 | GPIO_PIN_5);\n\n \/* Blue LED pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, GPIO_PIN_2);\n MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_2);\n\n \/* Green LED pin initialization *\/\n MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);\n MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_3, GPIO_PIN_3);\n MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3);\n\n \/* Initialize timer0a interrupt *\/\n\n MAP_IntPrioritySet(INT_USB0, 0xff); \/\/ USB interrupt low priority\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-------------FDTD.cpp-------------------------------------------------------\/\/\n*\n* Finite Difference Time Domain\n*\n* Purpose: To replicate the results of our invisible lense raytracer with \n* FDTD. Woo!\n*\n* Notes: Most of this is coming from the following link:\n* http:\/\/www.eecs.wsu.edu\/~schneidj\/ufdtd\/chap3.pdf\n* http:\/\/www.eecs.wsu.edu\/~schneidj\/ufdtd\/chap8.pdf\n*\n*-----------------------------------------------------------------------------*\/\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <fstream>\n\nstatic const size_t space = 200;\n\nstruct Bound{\n int x,y;\n};\n\nstruct Loss{\n std::vector <double> EzH = std::vector<double>(space * space, 0), \n EzE = std::vector<double>(space * space, 0), \n HyE = std::vector<double>(space * space, 0), \n HyH = std::vector<double>(space * space, 0),\n HxE = std::vector<double>(space * space, 0), \n HxH = std::vector<double>(space * space, 0);\n};\n\nstruct Loss1d{\n std::vector <double> EzH = std::vector<double>(space, 0), \n EzE = std::vector<double>(space, 0), \n HyE = std::vector<double>(space, 0), \n HyH = std::vector<double>(space, 0),\n HxE = std::vector<double>(space, 0), \n HxH = std::vector<double>(space, 0);\n};\n\nstruct Field{\n std::vector <double> Hx = std::vector<double>(space * space, 0), \n Hy = std::vector<double>(space * space, 0),\n Ez = std::vector<double>(space * space, 0);\n int t;\n};\n\nstruct Field1d{\n std::vector <double> Hx = std::vector<double>(space, 0), \n Hy = std::vector<double>(space, 0),\n Ez = std::vector<double>(space, 0);\n};\n\n#define EzH(i, j) EzH[(i) + (j) * space]\n#define EzE(i, j) EzE[(i) + (j) * space]\n#define HyH(i, j) HyH[(i) + (j) * space]\n#define HyE(i, j) HyE[(i) + (j) * space]\n#define HxH(i, j) HxH[(i) + (j) * space]\n#define HxE(i, j) HxE[(i) + (j) * space]\n#define Hx(i, j) Hx[(i) + (j) * space] \n#define Hy(i, j) Hy[(i) + (j) * space] \n#define Ez(i, j) Ez[(i) + (j) * space] \n\nvoid FDTD(Field EM, Field1d EM1d,\n const int final_time, const double eps, const int space,\n std::ofstream& output);\n\n\/\/ Adding ricker solutuion\ndouble ricker(int time, int loc, double Cour);\n\n\/\/ 2 dimensional functions for E \/ H movement\nField Hupdate2d(Field EM, Loss lass, int t);\nField Eupdate2d(Field EM, Loss lass, int t);\n\n\/\/ 1 dimensional update functions for E \/ H\nField1d Hupdate1d(Field1d EM1d, Loss lass, int t);\nField1d Eupdate1d(Field1d EM1d, Loss lass, int t);\n\n\/\/ Creating loss\nLoss createloss2d(Loss lass, double eps, double Cour, double loss);\nLoss1d createloss1d(Loss1d lass1d, double eps, double Cour, double loss);\n\n\/\/ TFSF boundaries\nField TFSF(Field EM, Loss lass, Field1d EM1d, Loss1d lass1d, double Cour);\n\n\/*----------------------------------------------------------------------------\/\/\n* MAIN\n*-----------------------------------------------------------------------------*\/\n\nint main(){\n\n \/\/ defines output\n std::ofstream output(\"FDTD.dat\", std::ofstream::out);\n\n int final_time = 1000;\n double eps = 377.0;\n\n \/\/ define initial E and H fields\n \/\/ std::vector<double> Ez(space, 0.0), Hy(space, 0.0);\n Field EM;\n Field1d EM1d;\n EM.t = 0;\n\n FDTD(EM, EM1d, final_time, eps, space, output);\n\n}\n\n\/*----------------------------------------------------------------------------\/\/\n* SUBROUTINES\n*-----------------------------------------------------------------------------*\/\n\n\/\/ This is the function we writs the bulk of the code in\nvoid FDTD(Field EM, Field1d EM1d,\n const int final_time, const double eps, const int space,\n std::ofstream& output){\n\n \/\/ For magnetic field:\n \/\/ double offset = 0.00005;\n\n \/\/ for electric field:\n \/\/double offset = 0.05;\n double loss = 0.0;\n double Cour = 1.0 \/ sqrt(2.0);\n\n Loss lass;\n lass = createloss2d(lass, eps, Cour, loss);\n Loss1d lass1d;\n lass1d = createloss1d(lass1d, eps, Cour, loss);\n\n \/\/ Time looping\n for (int t = 0; t < final_time; t++){\n\n EM = Hupdate2d(EM, lass, t);\n EM = TFSF(EM, lass, EM1d, lass1d, Cour);\n EM = Eupdate2d(EM,lass,t);\n \/\/EM.Ez(0,100) = ricker(t, 0, Cour);\n \n \/\/ Outputting to a file\n int check = 5;\n if (t % check == 0){\n for (int dx = 0; dx < space; dx = dx + check){\n for (int dy = 0; dy < space; dy = dy + check){\n output << t << '\\t' << dx <<'\\t' << dy << '\\t'\n << EM.Ez(dx, dy) << '\\t' << EM.Hy(dx, dy) \n << '\\t' << EM.Hx(dx, dy) << '\\t' << '\\n';\n \/\/output << Ez(dx,dy) + (t * offset) << '\\n';\n \/\/output << Hy[dx] + (t * offset) << '\\n';\n }\n }\n\n output << '\\n' << '\\n';\n }\n\n }\n}\n\n\/\/ Adding the ricker solution\ndouble ricker(int time, int loc, double Cour){\n double Ricky;\n double temp_const = 3.14159*((Cour*(double)time - (double)loc)\/20.0 - 1.0);\n temp_const = temp_const * temp_const;\n Ricky = (1.0 - 2.0 * temp_const) * exp(-temp_const);\n return Ricky;\n\n}\n\n\/\/ 2 dimensional functions for E \/ H movement\nField Hupdate2d(Field EM, Loss lass, int t){\n \/\/ update magnetic field, x direction\n for (size_t dx = 0; dx < space; dx++){\n for (size_t dy = 0; dy < space - 1; dy++){\n EM.Hx(dx,dy) = lass.HxH(dx,dy) * EM.Hx(dx, dy) \n - lass.HxE(dx,dy) * (EM.Ez(dx,dy + 1) \n - EM.Ez(dx,dy));\n }\n }\n\n\n \/\/ update magnetic field, y direction\n for (size_t dx = 0; dx < space - 1; dx++){\n for (size_t dy = 0; dy < space; dy++){\n EM.Hy(dx,dy) = lass.HyH(dx,dy) * EM.Hy(dx,dy) \n + lass.HyE(dx,dy) * (EM.Ez(dx + 1,dy) \n - EM.Ez(dx,dy));\n }\n }\n\n return EM;\n\n}\n\n\nField Eupdate2d(Field EM, Loss lass, int t){\n \/\/ update electric field\n for (size_t dx = 1; dx < space - 1; dx++){\n for (size_t dy = 1; dy < space - 1; dy++){\n EM.Ez(dx,dy) = lass.EzE(dx,dy) * EM.Ez(dx,dy)\n + lass.EzH(dx,dy) * ((EM.Hy(dx, dy)\n - EM.Hy(dx - 1, dy))\n - (EM.Hx(dx,dy)\n - EM.Hx(dx, dy - 1)));\n }\n }\n return EM;\n}\n\n\/\/ 1 dimensional update functions for E \/ H\nField1d Hupdate1d(Field1d EM1d, Loss1d lass1d, int t){\n \/\/ update magnetic field, y direction\n for (size_t dx = 0; dx < space - 1; dx++){\n EM1d.Hy[dx] = lass1d.HyH[dx] * EM1d.Hy[dx] \n + lass1d.HyE[dx] * (EM1d.Ez[dx + 1] - EM1d.Ez[dx]);\n }\n\n return EM1d;\n}\n\nField1d Eupdate1d(Field1d EM1d, Loss1d lass1d, int t){\n \/\/ update electric field, y direction\n for (size_t dx = 1; dx < space - 1; dx++){\n EM1d.Ez[dx] = lass1d.EzE[dx] * EM1d.Ez[dx] \n + lass1d.EzH[dx] * (EM1d.Hy[dx] - EM1d.Hy[dx - 1]);\n }\n\n return EM1d;\n\n}\n\n\/\/ Creating loss\nLoss createloss2d(Loss lass, double eps, double Cour, double loss){\n for (size_t dx = 0; dx < space; dx++){\n for (size_t dy = 0; dy < space; dy++){\n \/\/if (dx > 100 && dx < 150){\n\/*\n lass.EzH(dx, dy) = Cour * eps;\n lass.EzE(dx, dy) = 1.0;\n lass.HyH(dx, dy) = 1.0;\n lass.HyE(dx, dy) = Cour \/ eps;\n lass.HxE(dx, dy) = Cour \/ eps;\n lass.HxH(dx, dy) = 1.0;\n*\/\n\n lass.EzH(dx, dy) = eps \/ 9.0 \/(1.0 - loss);\n lass.EzE(dx, dy) = (1.0 - loss) \/ (1.0 + loss);\n lass.HyH(dx, dy) = (1.0 - loss) \/ (1.0 + loss);\n lass.HyE(dx, dy) = (1.0 \/ eps) \/ (1.0 + loss);\n lass.HxE(dx, dy) = (1.0 \/ eps) \/ (1.0 + loss);\n lass.HxH(dx, dy) = (1.0 - loss) \/ (1.0 + loss);\n \/\/}\n \/*\n else{\n lass.EzH(dx, dy) = Cour * eps;\n lass.EzE(dx, dy) = 1.0;\n lass.HyH(dx, dy) = 1.0;\n lass.HyE(dx, dy) = Cour \/ eps;\n lass.HxE(dx, dy) = Cour \/ eps;\n lass.HxH(dx, dy) = 1.0;\n \n lass.EzH(dx, dy) = eps;\n lass.EzE(dx, dy) = 1.0;\n lass.HyH(dx, dy) = 1.0;\n lass.HyE(dx, dy) = (1.0 \/ eps);\n lass.HxE(dx, dy) = (1.0 \/ eps);\n lass.HxH(dx, dy) = 1.0;\n \n }\n *\/\n }\n }\n\n\n return lass;\n}\nLoss1d createloss1d(Loss1d lass1d, double eps, double Cour, double loss){\n for (size_t dx = 0; dx < space; dx++){\n \/\/if (dx > 100 && dx < 150){\n\n lass1d.EzH[dx ]= Cour * eps;\n lass1d.EzE[dx] = 1.0;\n lass1d.HyH[dx] = 1.0;\n lass1d.HyE[dx] = Cour \/ eps;\n\/*\n\n lass1d.EzH[dx] = eps \/ 9.0 \/(1.0 - loss);\n lass1d.EzE[dx] = (1.0 - loss) \/ (1.0 + loss);\n lass1d.HyH[dx] = (1.0 - loss) \/ (1.0 + loss);\n*\/\n lass1d.HyE[dx] = (1.0 \/ eps) \/ (1.0 + loss);\n \/\/}\n \/*\n else{\n lass1d.EzH[dx] = Cour * eps;\n lass1d.EzE[dx] = 1.0;\n lass1d.HyH[dx] = 1.0;\n lass1d.HyE[dx] = Cour \/ eps;\n \n lass1d.EzH[dx] = eps;\n lass1d.EzE[dx] = 1.0;\n lass1d.HyH[dx] = 1.0;\n lass1d.HyE[dx] = (1.0 \/ eps);\n \n }\n *\/\n }\n\n\n return lass1d;\n\n}\n\n\/\/ TFSF boundaries\nField TFSF(Field EM, Loss lass, Field1d EM1d, Loss1d lass1d, double Cour){\n \/\/ TFSF boundary\n Bound first, last;\n first.x = 50; last.x = 150;\n first.y = 50; last.y = 150;\n\n \/\/ Updating along left edge\n int dx = first.x - 1;\n for (int dy = first.y; dy <= last.y; dy++){\n EM.Hy(dx,dy) -= lass.HyE(dx, dy) * EM1d.Ez[dx+1];\n }\n\n \/\/ Update along right edge!\n dx = last.x;\n for (int dy = first.y; dy <= last.y; dy++){\n EM.Hy(dx,dy) += lass.HyE(dx, dy) * EM1d.Ez[dx];\n }\n\n \/\/ Update along bot\n int dy = first.y - 1;\n for (int dx = first.x; dx <= last.x; dx++){\n EM.Hx(dx,dy) += lass.HxE(dx, dy) * EM1d.Ez[dx];\n }\n\n \/\/ Updating along top\n dy = last.y;\n for (int dx = first.x; dx <= last.x; dx++){\n EM.Hx(dx,dy) -= lass.HxE(dx, dy) * EM1d.Ez[dx];\n }\n\n \/\/ Insert 1d grid stuff here. Update magnetic and electric field\n Hupdate1d(EM1d, lass1d, EM.t);\n Eupdate1d(EM1d, lass1d, EM.t);\n EM1d.Ez[100] = ricker(EM.t,0, Cour);\n EM.t++;\n std::cout << EM.t << '\\n';\n\n \/\/ Check mag instead of ricker.\n \/\/ Updating Ez along left\n dx = first.x;\n for (int dy = first.y; dy <= last.y; dy++){\n EM.Ez(dx, dy) -= lass.EzH(dx, dy) * EM1d.Hy[dx - 1];\n }\n\n \/\/ Update along right\n dx = last.x;\n for (int dy = first.y; dy <= last.y; dy++){\n EM.Ez(dx, dy) += lass.EzH(dx, dy) * EM1d.Hy[dx];\n }\n\n return EM;\n\n}\n<commit_msg>TFSF working!<commit_after>\/*-------------FDTD.cpp-------------------------------------------------------\/\/\n*\n* Finite Difference Time Domain\n*\n* Purpose: To replicate the results of our invisible lense raytracer with \n* FDTD. Woo!\n*\n* Notes: Most of this is coming from the following link:\n* http:\/\/www.eecs.wsu.edu\/~schneidj\/ufdtd\/chap3.pdf\n* http:\/\/www.eecs.wsu.edu\/~schneidj\/ufdtd\/chap8.pdf\n*\n*-----------------------------------------------------------------------------*\/\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <fstream>\n\nstatic const size_t space = 200;\n\nstruct Bound{\n int x,y;\n};\n\nstruct Loss{\n std::vector <double> EzH = std::vector<double>(space * space, 0), \n EzE = std::vector<double>(space * space, 0), \n HyE = std::vector<double>(space * space, 0), \n HyH = std::vector<double>(space * space, 0),\n HxE = std::vector<double>(space * space, 0), \n HxH = std::vector<double>(space * space, 0);\n};\n\nstruct Loss1d{\n std::vector <double> EzH = std::vector<double>(space, 0), \n EzE = std::vector<double>(space, 0), \n HyE = std::vector<double>(space, 0), \n HyH = std::vector<double>(space, 0),\n HxE = std::vector<double>(space, 0), \n HxH = std::vector<double>(space, 0);\n};\n\nstruct Field{\n std::vector <double> Hx = std::vector<double>(space * space, 0), \n Hy = std::vector<double>(space * space, 0),\n Ez = std::vector<double>(space * space, 0);\n\n std::vector <double> Hy1d = std::vector<double>(space, 0), \n Ez1d = std::vector<double>(space, 0);\n\n int t;\n};\n\n#define EzH(i, j) EzH[(i) + (j) * space]\n#define EzE(i, j) EzE[(i) + (j) * space]\n#define HyH(i, j) HyH[(i) + (j) * space]\n#define HyE(i, j) HyE[(i) + (j) * space]\n#define HxH(i, j) HxH[(i) + (j) * space]\n#define HxE(i, j) HxE[(i) + (j) * space]\n#define Hx(i, j) Hx[(i) + (j) * space] \n#define Hy(i, j) Hy[(i) + (j) * space] \n#define Ez(i, j) Ez[(i) + (j) * space] \n\nvoid FDTD(Field EM,\n const int final_time, const double eps, const int space,\n std::ofstream& output);\n\n\/\/ Adding ricker solutuion\ndouble ricker(int time, int loc, double Cour);\n\n\/\/ 2 dimensional functions for E \/ H movement\nField Hupdate2d(Field EM, Loss lass, int t);\nField Eupdate2d(Field EM, Loss lass, int t);\n\n\/\/ 1 dimensional update functions for E \/ H\nField Hupdate1d(Field EM, Loss lass, int t);\nField Eupdate1d(Field EM, Loss lass, int t);\n\n\/\/ Creating loss\nLoss createloss2d(Loss lass, double eps, double Cour, double loss);\nLoss1d createloss1d(Loss1d lass1d, double eps, double Cour, double loss);\n\n\/\/ TFSF boundaries\nField TFSF(Field EM, Loss lass, Loss1d lass1d, double Cour);\n\n\/*----------------------------------------------------------------------------\/\/\n* MAIN\n*-----------------------------------------------------------------------------*\/\n\nint main(){\n\n \/\/ defines output\n std::ofstream output(\"FDTD.dat\", std::ofstream::out);\n\n int final_time = 1000;\n double eps = 377.0;\n\n \/\/ define initial E and H fields\n \/\/ std::vector<double> Ez(space, 0.0), Hy(space, 0.0);\n Field EM;\n EM.t = 0;\n\n FDTD(EM, final_time, eps, space, output);\n\n}\n\n\/*----------------------------------------------------------------------------\/\/\n* SUBROUTINES\n*-----------------------------------------------------------------------------*\/\n\n\/\/ This is the function we writs the bulk of the code in\nvoid FDTD(Field EM,\n const int final_time, const double eps, const int space,\n std::ofstream& output){\n\n \/\/ For magnetic field:\n \/\/ double offset = 0.00005;\n\n \/\/ for electric field:\n \/\/double offset = 0.05;\n double loss = 0.0;\n double Cour = 1.0 \/ sqrt(2.0);\n\n Loss lass;\n lass = createloss2d(lass, eps, Cour, loss);\n Loss1d lass1d;\n lass1d = createloss1d(lass1d, eps, Cour, loss);\n\n \/\/ Time looping\n for (int t = 0; t < final_time; t++){\n\n EM = Hupdate2d(EM, lass, t);\n EM = TFSF(EM, lass, lass1d, Cour);\n EM = Eupdate2d(EM,lass,t);\n \/\/EM.Ez(0,100) = ricker(t, 0, Cour);\n \n \/\/ Outputting to a file\n int check = 5;\n if (t % check == 0){\n for (int dx = 0; dx < space; dx = dx + check){\n for (int dy = 0; dy < space; dy = dy + check){\n output << t << '\\t' << dx <<'\\t' << dy << '\\t'\n << EM.Ez(dx, dy) << '\\t' << EM.Hy(dx, dy) \n << '\\t' << EM.Hx(dx, dy) << '\\t' << '\\n';\n \/\/output << Ez(dx,dy) + (t * offset) << '\\n';\n \/\/output << Hy[dx] + (t * offset) << '\\n';\n }\n }\n\n output << '\\n' << '\\n';\n }\n\n }\n}\n\n\/\/ Adding the ricker solution\ndouble ricker(int time, int loc, double Cour){\n double Ricky;\n double temp_const = 3.14159*((Cour*(double)time - (double)loc)\/20.0 - 1.0);\n temp_const = temp_const * temp_const;\n Ricky = (1.0 - 2.0 * temp_const) * exp(-temp_const);\n return Ricky;\n\n}\n\n\/\/ 2 dimensional functions for E \/ H movement\nField Hupdate2d(Field EM, Loss lass, int t){\n \/\/ update magnetic field, x direction\n for (size_t dx = 0; dx < space; dx++){\n for (size_t dy = 0; dy < space - 1; dy++){\n EM.Hx(dx,dy) = lass.HxH(dx,dy) * EM.Hx(dx, dy) \n - lass.HxE(dx,dy) * (EM.Ez(dx,dy + 1) \n - EM.Ez(dx,dy));\n }\n }\n\n\n \/\/ update magnetic field, y direction\n for (size_t dx = 0; dx < space - 1; dx++){\n for (size_t dy = 0; dy < space; dy++){\n EM.Hy(dx,dy) = lass.HyH(dx,dy) * EM.Hy(dx,dy) \n + lass.HyE(dx,dy) * (EM.Ez(dx + 1,dy) \n - EM.Ez(dx,dy));\n }\n }\n\n return EM;\n\n}\n\n\nField Eupdate2d(Field EM, Loss lass, int t){\n \/\/ update electric field\n for (size_t dx = 1; dx < space - 1; dx++){\n for (size_t dy = 1; dy < space - 1; dy++){\n EM.Ez(dx,dy) = lass.EzE(dx,dy) * EM.Ez(dx,dy)\n + lass.EzH(dx,dy) * ((EM.Hy(dx, dy)\n - EM.Hy(dx - 1, dy))\n - (EM.Hx(dx,dy)\n - EM.Hx(dx, dy - 1)));\n }\n }\n return EM;\n}\n\n\/\/ 1 dimensional update functions for E \/ H\nField Hupdate1d(Field EM, Loss1d lass1d, int t){\n \/\/ update magnetic field, y direction\n for (size_t dx = 0; dx < space - 1; dx++){\n EM.Hy1d[dx] = lass1d.HyH[dx] * EM.Hy1d[dx] \n + lass1d.HyE[dx] * (EM.Ez1d[dx + 1] - EM.Ez1d[dx]);\n }\n\n return EM;\n}\n\nField Eupdate1d(Field EM, Loss1d lass1d, int t){\n \/\/ update electric field, y direction\n for (size_t dx = 1; dx < space - 1; dx++){\n EM.Ez1d[dx] = lass1d.EzE[dx] * EM.Ez1d[dx] \n + lass1d.EzH[dx] * (EM.Hy1d[dx] - EM.Hy1d[dx - 1]);\n }\n\n return EM;\n\n}\n\n\/\/ Creating loss\nLoss createloss2d(Loss lass, double eps, double Cour, double loss){\n for (size_t dx = 0; dx < space; dx++){\n for (size_t dy = 0; dy < space; dy++){\n \/\/if (dx > 100 && dx < 150){\n\/*\n lass.EzH(dx, dy) = Cour * eps;\n lass.EzE(dx, dy) = 1.0;\n lass.HyH(dx, dy) = 1.0;\n lass.HyE(dx, dy) = Cour \/ eps;\n lass.HxE(dx, dy) = Cour \/ eps;\n lass.HxH(dx, dy) = 1.0;\n*\/\n\n lass.EzH(dx, dy) = eps \/ 9.0 \/(1.0 - loss);\n lass.EzE(dx, dy) = (1.0 - loss) \/ (1.0 + loss);\n lass.HyH(dx, dy) = (1.0 - loss) \/ (1.0 + loss);\n lass.HyE(dx, dy) = (1.0 \/ eps) \/ (1.0 + loss);\n lass.HxE(dx, dy) = (1.0 \/ eps) \/ (1.0 + loss);\n lass.HxH(dx, dy) = (1.0 - loss) \/ (1.0 + loss);\n \/\/}\n \/*\n else{\n lass.EzH(dx, dy) = Cour * eps;\n lass.EzE(dx, dy) = 1.0;\n lass.HyH(dx, dy) = 1.0;\n lass.HyE(dx, dy) = Cour \/ eps;\n lass.HxE(dx, dy) = Cour \/ eps;\n lass.HxH(dx, dy) = 1.0;\n \n lass.EzH(dx, dy) = eps;\n lass.EzE(dx, dy) = 1.0;\n lass.HyH(dx, dy) = 1.0;\n lass.HyE(dx, dy) = (1.0 \/ eps);\n lass.HxE(dx, dy) = (1.0 \/ eps);\n lass.HxH(dx, dy) = 1.0;\n \n }\n *\/\n }\n }\n\n\n return lass;\n}\nLoss1d createloss1d(Loss1d lass1d, double eps, double Cour, double loss){\n for (size_t dx = 0; dx < space; dx++){\n \/\/if (dx > 100 && dx < 150){\n\n lass1d.EzH[dx ]= Cour * eps;\n lass1d.EzE[dx] = 1.0;\n lass1d.HyH[dx] = 1.0;\n lass1d.HyE[dx] = Cour \/ eps;\n\/*\n\n lass1d.EzH[dx] = eps \/ 9.0 \/(1.0 - loss);\n lass1d.EzE[dx] = (1.0 - loss) \/ (1.0 + loss);\n lass1d.HyH[dx] = (1.0 - loss) \/ (1.0 + loss);\n*\/\n lass1d.HyE[dx] = (1.0 \/ eps) \/ (1.0 + loss);\n \/\/}\n \/*\n else{\n lass1d.EzH[dx] = Cour * eps;\n lass1d.EzE[dx] = 1.0;\n lass1d.HyH[dx] = 1.0;\n lass1d.HyE[dx] = Cour \/ eps;\n \n lass1d.EzH[dx] = eps;\n lass1d.EzE[dx] = 1.0;\n lass1d.HyH[dx] = 1.0;\n lass1d.HyE[dx] = (1.0 \/ eps);\n \n }\n *\/\n }\n\n\n return lass1d;\n\n}\n\n\/\/ TFSF boundaries\nField TFSF(Field EM, Loss lass, Loss1d lass1d, double Cour){\n \/\/ TFSF boundary\n Bound first, last;\n first.x = 50; last.x = 150;\n first.y = 50; last.y = 150;\n\n \/\/ Updating along left edge\n int dx = first.x - 1;\n for (int dy = first.y; dy <= last.y; dy++){\n EM.Hy(dx,dy) -= lass.HyE(dx, dy) * EM.Ez1d[dx+1];\n }\n\n \/\/ Update along right edge!\n dx = last.x;\n for (int dy = first.y; dy <= last.y; dy++){\n EM.Hy(dx,dy) += lass.HyE(dx, dy) * EM.Ez1d[dx];\n }\n\n \/\/ Update along bot\n int dy = first.y - 1;\n for (int dx = first.x; dx <= last.x; dx++){\n EM.Hx(dx,dy) += lass.HxE(dx, dy) * EM.Ez1d[dx];\n }\n\n \/\/ Updating along top\n dy = last.y;\n for (int dx = first.x; dx <= last.x; dx++){\n EM.Hx(dx,dy) -= lass.HxE(dx, dy) * EM.Ez1d[dx];\n }\n\n \/\/ Insert 1d grid stuff here. Update magnetic and electric field\n Hupdate1d(EM, lass1d, EM.t);\n Eupdate1d(EM, lass1d, EM.t);\n EM.Ez1d[50] = ricker(EM.t,0, Cour);\n EM.t++;\n std::cout << EM.t << '\\n';\n\n \/\/ Check mag instead of ricker.\n \/\/ Updating Ez along left\n dx = first.x;\n for (int dy = first.y; dy <= last.y; dy++){\n EM.Ez(dx, dy) -= lass.EzH(dx, dy) * EM.Hy1d[dx - 1];\n }\n\n \/\/ Update along right\n dx = last.x;\n for (int dy = first.y; dy <= last.y; dy++){\n EM.Ez(dx, dy) += lass.EzH(dx, dy) * EM.Hy1d[dx];\n }\n\n return EM;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 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. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"File.h\"\n\n#include \"Media.h\"\n#include \"Folder.h\"\n\nconst std::string policy::FileTable::Name = \"File\";\nconst std::string policy::FileTable::PrimaryKeyColumn = \"id_file\";\nunsigned int File::* const policy::FileTable::PrimaryKey = &File::m_id;\n\nFile::File( DBConnection dbConnection, sqlite::Row& row )\n : m_dbConnection( dbConnection )\n{\n row >> m_id\n >> m_mediaId\n >> m_mrl\n >> m_type\n >> m_lastModificationDate\n >> m_isParsed\n >> m_folderId\n >> m_isPresent\n >> m_isRemovable;\n}\n\nFile::File( unsigned int mediaId, Type type, const fs::IFile& file, unsigned int folderId, bool isRemovable )\n : m_id( 0 )\n , m_mediaId( mediaId )\n , m_mrl( isRemovable == true ? file.name() : file.fullPath() )\n , m_type( type )\n , m_lastModificationDate( file.lastModificationDate() )\n , m_isParsed( false )\n , m_folderId( folderId )\n , m_isPresent( true )\n , m_isRemovable( isRemovable )\n{\n}\n\nunsigned int File::id() const\n{\n return m_id;\n}\n\nconst std::string& File::mrl() const\n{\n if ( m_isRemovable == false )\n return m_mrl;\n\n auto lock = m_fullPath.lock();\n if ( m_fullPath.isCached() )\n return m_fullPath;\n auto folder = Folder::fetch( m_dbConnection, m_folderId );\n if ( folder == nullptr )\n return m_mrl;\n m_fullPath = folder->path() + m_mrl;\n return m_fullPath;\n}\n\nIFile::Type File::type() const\n{\n return m_type;\n}\n\nunsigned int File::lastModificationDate() const\n{\n return m_lastModificationDate;\n}\n\nbool File::isParsed() const\n{\n return m_isParsed;\n}\n\nstd::shared_ptr<Media> File::media() const\n{\n auto lock = m_media.lock();\n if ( m_media.isCached() == false )\n {\n m_media = Media::fetch( m_dbConnection, m_mediaId );\n }\n return m_media.get().lock();\n}\n\nbool File::destroy()\n{\n return DatabaseHelpers::destroy( m_dbConnection, m_id );\n}\n\nvoid File::markParsed()\n{\n if ( m_isParsed == true )\n return;\n static const std::string req = \"UPDATE \" + policy::FileTable::Name + \" SET parsed = 1 WHERE id_file = ?\";\n if ( sqlite::Tools::executeUpdate( m_dbConnection, req, m_id ) == false )\n return;\n m_isParsed = true;\n}\n\nbool File::createTable( DBConnection dbConnection )\n{\n std::string req = \"CREATE TABLE IF NOT EXISTS \" + policy::FileTable::Name + \"(\"\n \"id_file INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"media_id INT NOT NULL,\"\n \"mrl TEXT,\"\n \"type UNSIGNED INTEGER,\"\n \"last_modification_date UNSIGNED INT,\"\n \"parsed BOOLEAN NOT NULL DEFAULT 0,\"\n \"folder_id UNSIGNED INTEGER,\"\n \"is_present BOOLEAN NOT NULL DEFAULT 1,\"\n \"is_removable BOOLEAN NOT NULL,\"\n \"FOREIGN KEY (media_id) REFERENCES \" + policy::MediaTable::Name\n + \"(id_media) ON DELETE CASCADE,\"\n \"FOREIGN KEY (folder_id) REFERENCES \" + policy::FolderTable::Name\n + \"(id_folder) ON DELETE CASCADE,\"\n \"UNIQUE( mrl, folder_id ) ON CONFLICT FAIL\"\n \")\";\n std::string triggerReq = \"CREATE TRIGGER IF NOT EXISTS is_folder_present AFTER UPDATE OF is_present ON \"\n + policy::FolderTable::Name +\n \" BEGIN\"\n \" UPDATE \" + policy::FileTable::Name + \" SET is_present = new.is_present WHERE folder_id = new.id_folder;\"\n \" END\";\n return sqlite::Tools::executeRequest( dbConnection, req ) &&\n sqlite::Tools::executeRequest( dbConnection, triggerReq );\n}\n\nstd::shared_ptr<File> File::create( DBConnection dbConnection, unsigned int mediaId, Type type, const fs::IFile& fileFs, unsigned int folderId, bool isRemovable )\n{\n auto self = std::make_shared<File>( mediaId, type, fileFs, folderId, isRemovable );\n static const std::string req = \"INSERT INTO \" + policy::FileTable::Name +\n \"(media_id, mrl, type, folder_id, last_modification_date, is_removable) VALUES(?, ?, ?, ?, ?, ?)\";\n\n if ( insert( dbConnection, self, req, mediaId, self->m_mrl, type, sqlite::ForeignKey( folderId ),\n self->m_lastModificationDate, isRemovable ) == false )\n return nullptr;\n self->m_dbConnection = dbConnection;\n self->m_fullPath = fileFs.fullPath();\n return self;\n}\n<commit_msg>File: Index media_id<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 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. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"File.h\"\n\n#include \"Media.h\"\n#include \"Folder.h\"\n\nconst std::string policy::FileTable::Name = \"File\";\nconst std::string policy::FileTable::PrimaryKeyColumn = \"id_file\";\nunsigned int File::* const policy::FileTable::PrimaryKey = &File::m_id;\n\nFile::File( DBConnection dbConnection, sqlite::Row& row )\n : m_dbConnection( dbConnection )\n{\n row >> m_id\n >> m_mediaId\n >> m_mrl\n >> m_type\n >> m_lastModificationDate\n >> m_isParsed\n >> m_folderId\n >> m_isPresent\n >> m_isRemovable;\n}\n\nFile::File( unsigned int mediaId, Type type, const fs::IFile& file, unsigned int folderId, bool isRemovable )\n : m_id( 0 )\n , m_mediaId( mediaId )\n , m_mrl( isRemovable == true ? file.name() : file.fullPath() )\n , m_type( type )\n , m_lastModificationDate( file.lastModificationDate() )\n , m_isParsed( false )\n , m_folderId( folderId )\n , m_isPresent( true )\n , m_isRemovable( isRemovable )\n{\n}\n\nunsigned int File::id() const\n{\n return m_id;\n}\n\nconst std::string& File::mrl() const\n{\n if ( m_isRemovable == false )\n return m_mrl;\n\n auto lock = m_fullPath.lock();\n if ( m_fullPath.isCached() )\n return m_fullPath;\n auto folder = Folder::fetch( m_dbConnection, m_folderId );\n if ( folder == nullptr )\n return m_mrl;\n m_fullPath = folder->path() + m_mrl;\n return m_fullPath;\n}\n\nIFile::Type File::type() const\n{\n return m_type;\n}\n\nunsigned int File::lastModificationDate() const\n{\n return m_lastModificationDate;\n}\n\nbool File::isParsed() const\n{\n return m_isParsed;\n}\n\nstd::shared_ptr<Media> File::media() const\n{\n auto lock = m_media.lock();\n if ( m_media.isCached() == false )\n {\n m_media = Media::fetch( m_dbConnection, m_mediaId );\n }\n return m_media.get().lock();\n}\n\nbool File::destroy()\n{\n return DatabaseHelpers::destroy( m_dbConnection, m_id );\n}\n\nvoid File::markParsed()\n{\n if ( m_isParsed == true )\n return;\n static const std::string req = \"UPDATE \" + policy::FileTable::Name + \" SET parsed = 1 WHERE id_file = ?\";\n if ( sqlite::Tools::executeUpdate( m_dbConnection, req, m_id ) == false )\n return;\n m_isParsed = true;\n}\n\nbool File::createTable( DBConnection dbConnection )\n{\n std::string req = \"CREATE TABLE IF NOT EXISTS \" + policy::FileTable::Name + \"(\"\n \"id_file INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"media_id INT NOT NULL,\"\n \"mrl TEXT,\"\n \"type UNSIGNED INTEGER,\"\n \"last_modification_date UNSIGNED INT,\"\n \"parsed BOOLEAN NOT NULL DEFAULT 0,\"\n \"folder_id UNSIGNED INTEGER,\"\n \"is_present BOOLEAN NOT NULL DEFAULT 1,\"\n \"is_removable BOOLEAN NOT NULL,\"\n \"FOREIGN KEY (media_id) REFERENCES \" + policy::MediaTable::Name\n + \"(id_media) ON DELETE CASCADE,\"\n \"FOREIGN KEY (folder_id) REFERENCES \" + policy::FolderTable::Name\n + \"(id_folder) ON DELETE CASCADE,\"\n \"UNIQUE( mrl, folder_id ) ON CONFLICT FAIL\"\n \")\";\n std::string triggerReq = \"CREATE TRIGGER IF NOT EXISTS is_folder_present AFTER UPDATE OF is_present ON \"\n + policy::FolderTable::Name +\n \" BEGIN\"\n \" UPDATE \" + policy::FileTable::Name + \" SET is_present = new.is_present WHERE folder_id = new.id_folder;\"\n \" END\";\n std::string indexReq = \"CREATE INDEX IF NOT EXISTS file_media_id_index ON \" +\n policy::FileTable::Name + \"(media_id)\";\n return sqlite::Tools::executeRequest( dbConnection, req ) &&\n sqlite::Tools::executeRequest( dbConnection, triggerReq ) &&\n sqlite::Tools::executeRequest( dbConnection, indexReq );\n}\n\nstd::shared_ptr<File> File::create( DBConnection dbConnection, unsigned int mediaId, Type type, const fs::IFile& fileFs, unsigned int folderId, bool isRemovable )\n{\n auto self = std::make_shared<File>( mediaId, type, fileFs, folderId, isRemovable );\n static const std::string req = \"INSERT INTO \" + policy::FileTable::Name +\n \"(media_id, mrl, type, folder_id, last_modification_date, is_removable) VALUES(?, ?, ?, ?, ?, ?)\";\n\n if ( insert( dbConnection, self, req, mediaId, self->m_mrl, type, sqlite::ForeignKey( folderId ),\n self->m_lastModificationDate, isRemovable ) == false )\n return nullptr;\n self->m_dbConnection = dbConnection;\n self->m_fullPath = fileFs.fullPath();\n return self;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: load32bitOShack.cc,v 1.13 2002\/09\/13 00:15:23 kevinlawton Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\n#include \"bochs.h\"\n#define LOG_THIS genlog->\n\n\n\nstatic void bx_load_linux_hack(void);\nstatic void bx_load_null_kernel_hack(void);\nstatic Bit32u bx_load_kernel_image(char *path, Bit32u paddr);\n\n void\nbx_load32bitOSimagehack(void)\n{\n \/\/ Replay IO from log to initialize IO devices to\n \/\/ a reasonable state needed for the OS. This is done\n \/\/ in lieu of running the 16-bit BIOS to init things,\n \/\/ since we want to test straight 32bit stuff for\n \/\/ freemware.\n\n FILE *fp;\n\n fp = fopen(bx_options.load32bitOSImage.Oiolog->getptr (), \"r\");\n\n if (fp == NULL) {\n BX_PANIC((\"could not open IO init file.\"));\n }\n\n while (1) {\n unsigned len, op, port, val;\n int ret;\n ret = fscanf(fp, \"%u %u %x %x\\n\",\n &len, &op, &port, &val);\n if (ret != 4) {\n BX_PANIC((\"could not open IO init file.\"));\n }\n if (op == 0) {\n \/\/ read\n (void) bx_devices.inp(port, len);\n }\n else if (op == 1) {\n \/\/ write\n bx_devices.outp(port, val, len);\n }\n else {\n BX_PANIC((\"bad IO op in init filen\"));\n }\n if (feof(fp)) break;\n }\n\n \/\/ Invoke proper hack depending on which OS image we're loading\n switch (bx_options.load32bitOSImage.OwhichOS->get ()) {\n case Load32bitOSLinux:\n bx_load_linux_hack();\n break;\n case Load32bitOSNullKernel:\n bx_load_null_kernel_hack();\n break;\n default:\n BX_PANIC((\"load32bitOSImage: OS not recognized\"));\n }\n}\n\nstruct gdt_entry\n{\n Bit32u low;\n Bit32u high;\n};\nstruct linux_setup_params\n{\n \/* 0x000 *\/ Bit8u orig_x;\n \/* 0x001 *\/ Bit8u orig_y;\n \/* 0x002 *\/ Bit16u memory_size_std;\n \/* 0x004 *\/ Bit16u orig_video_page;\n \/* 0x006 *\/ Bit8u orig_video_mode;\n \/* 0x007 *\/ Bit8u orig_video_cols;\n \/* 0x008 *\/ Bit16u unused1;\n \/* 0x00a *\/ Bit16u orig_video_ega_bx;\n \/* 0x00c *\/ Bit16u unused2;\n \/* 0x00e *\/ Bit8u orig_video_lines;\n \/* 0x00f *\/ Bit8u orig_video_isVGA;\n \/* 0x010 *\/ Bit16u orig_video_points;\n \/* 0x012 *\/ Bit8u pad1[0x40 - 0x12];\n \/* 0x040 *\/ Bit8u apm_info[0x80 - 0x40];\n \/* 0x080 *\/ Bit8u hd0_info[16];\n \/* 0x090 *\/ Bit8u hd1_info[16];\n \/* 0x0a0 *\/ Bit8u pad2[0x1e0 - 0xa0];\n \/* 0x1e0 *\/ Bit32u memory_size_ext;\n \/* 0x1e4 *\/ Bit8u pad3[0x1f1 - 0x1e4];\n \/* 0x1f1 *\/ Bit8u setup_sects;\n \/* 0x1f2 *\/ Bit16u mount_root_rdonly;\n \/* 0x1f4 *\/ Bit16u sys_size;\n \/* 0x1f6 *\/ Bit16u swap_dev;\n \/* 0x1f8 *\/ Bit16u ramdisk_flags;\n \/* 0x1fa *\/ Bit16u vga_mode;\n \/* 0x1fc *\/ Bit16u orig_root_dev;\n \/* 0x1fe *\/ Bit16u bootsect_magic;\n \/* 0x200 *\/ Bit8u pad4[0x210 - 0x200];\n \/* 0x210 *\/ Bit32u loader_type;\n \/* 0x214 *\/ Bit32u kernel_start;\n \/* 0x218 *\/ Bit32u initrd_start;\n \/* 0x21c *\/ Bit32u initrd_size;\n \/* 0x220 *\/ Bit8u pad5[0x400 - 0x220];\n \/* 0x400 *\/ struct gdt_entry gdt[128];\n \/* 0x800 *\/ Bit8u commandline[2048];\n};\n\n static void\nbx_load_linux_setup_params( Bit32u initrd_start, Bit32u initrd_size )\n{\n BX_MEM_C *mem = BX_MEM(0);\n struct linux_setup_params *params =\n (struct linux_setup_params *) &mem->vector[0x00090000];\n\n memset( params, '\\0', sizeof(*params) );\n\n \/* Video settings (standard VGA) *\/\n params->orig_x = 0;\n params->orig_y = 0;\n params->orig_video_page = 0;\n params->orig_video_mode = 3;\n params->orig_video_cols = 80;\n params->orig_video_lines = 25;\n params->orig_video_points = 16;\n params->orig_video_isVGA = 1;\n params->orig_video_ega_bx = 3;\n\n \/* Memory size (total mem - 1MB, in KB) *\/\n params->memory_size_ext = (mem->megabytes - 1) * 1024;\n\n \/* Boot parameters *\/\n params->loader_type = 1;\n params->bootsect_magic = 0xaa55;\n params->mount_root_rdonly = 0;\n params->orig_root_dev = 0x0100;\n params->initrd_start = initrd_start;\n params->initrd_size = initrd_size;\n\n \/* Initial GDT *\/\n params->gdt[2].high = 0x00cf9a00;\n params->gdt[2].low = 0x0000ffff;\n params->gdt[3].high = 0x00cf9200;\n params->gdt[3].low = 0x0000ffff;\n}\n\n void\nbx_load_linux_hack(void)\n{\n Bit32u initrd_start = 0, initrd_size = 0;\n\n \/\/ The RESET function will have been called first.\n \/\/ Set CPU and memory features which are assumed at this point.\n\n \/\/ Load Linux kernel image\n bx_load_kernel_image( bx_options.load32bitOSImage.Opath->getptr (), 0x100000 );\n\n \/\/ Load initial ramdisk image if requested\n if ( bx_options.load32bitOSImage.Oinitrd->getptr () )\n {\n initrd_start = 0x00800000; \/* FIXME: load at top of memory *\/\n initrd_size = bx_load_kernel_image( bx_options.load32bitOSImage.Oinitrd->getptr (), initrd_start );\n }\n\n \/\/ Setup Linux startup parameters buffer\n bx_load_linux_setup_params( initrd_start, initrd_size );\n\n \/\/ Enable A20 line\n BX_SET_ENABLE_A20( 1 );\n\n \/\/ Setup PICs the way Linux likes it\n BX_OUTP( 0x20, 0x11, 1 );\n BX_OUTP( 0xA0, 0x11, 1 );\n BX_OUTP( 0x21, 0x20, 1 );\n BX_OUTP( 0xA1, 0x28, 1 );\n BX_OUTP( 0x21, 0x04, 1 );\n BX_OUTP( 0xA1, 0x02, 1 );\n BX_OUTP( 0x21, 0x01, 1 );\n BX_OUTP( 0xA1, 0x01, 1 );\n BX_OUTP( 0x21, 0xFF, 1 );\n BX_OUTP( 0xA1, 0xFB, 1 );\n\n \/\/ Disable interrupts and NMIs\n BX_CPU(0)->clear_IF ();\n BX_OUTP( 0x70, 0x80, 1 );\n\n \/\/ Enter protected mode\n BX_CPU(0)->cr0.pe = 1;\n BX_CPU(0)->cr0.val32 |= 0x01;\n\n \/\/ Set up initial GDT\n BX_CPU(0)->gdtr.limit = 0x400;\n BX_CPU(0)->gdtr.base = 0x00090400;\n\n \/\/ Jump to protected mode entry point\n BX_CPU(0)->jump_protected( NULL, 0x10, 0x00100000 );\n}\n\n void\nbx_load_null_kernel_hack(void)\n{\n \/\/ The RESET function will have been called first.\n \/\/ Set CPU and memory features which are assumed at this point.\n\n bx_load_kernel_image(bx_options.load32bitOSImage.Opath->getptr (), 0x100000);\n\n \/\/ EIP deltas\n BX_CPU(0)->prev_eip =\n BX_CPU(0)->dword.eip = 0x00100000;\n\n \/\/ CS deltas\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.base = 0x00000000;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit = 0xFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit_scaled = 0xFFFFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.g = 1; \/\/ page gran\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.d_b = 1; \/\/ 32bit\n\n \/\/ DS deltas\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.base = 0x00000000;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit = 0xFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit_scaled = 0xFFFFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.g = 1; \/\/ page gran\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.d_b = 1; \/\/ 32bit\n\n \/\/ CR0 deltas\n BX_CPU(0)->cr0.pe = 1; \/\/ protected mode\n}\n\n Bit32u\nbx_load_kernel_image(char *path, Bit32u paddr)\n{\n struct stat stat_buf;\n int fd, ret;\n unsigned long size, offset;\n Bit32u page_size;\n\n \/\/ read in ROM BIOS image file\n fd = open(path, O_RDONLY\n#ifdef O_BINARY\n | O_BINARY\n#endif\n );\n if (fd < 0) {\n BX_INFO(( \"load_kernel_image: couldn't open image file '%s'.\", path ));\n BX_EXIT(1);\n }\n ret = fstat(fd, &stat_buf);\n if (ret) {\n BX_INFO(( \"load_kernel_image: couldn't stat image file '%s'.\", path ));\n BX_EXIT(1);\n }\n\n size = stat_buf.st_size;\n page_size = ((Bit32u)size + 0xfff) & ~0xfff;\n\n BX_MEM_C *mem = BX_MEM(0);\n if ( (paddr + size) > mem->len ) {\n BX_INFO(( \"load_kernel_image: address range > physical memsize!\" ));\n BX_EXIT(1);\n }\n\n offset = 0;\n while (size > 0) {\n ret = read(fd, (bx_ptr_t) &mem->vector[paddr + offset], size);\n if (ret <= 0) {\n BX_INFO(( \"load_kernel_image: read failed on image\" ));\n BX_EXIT(1);\n }\n size -= ret;\n offset += ret;\n }\n close(fd);\n BX_INFO(( \"#(%u) load_kernel_image: '%s', size=%u read into memory at %08x\",\n BX_SIM_ID, path,\n (unsigned) stat_buf.st_size,\n (unsigned) paddr ));\n\n return page_size;\n}\n<commit_msg>- applied SF patch #748414 load32bitOShack bug<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: load32bitOShack.cc,v 1.14 2003\/08\/08 00:05:53 cbothamy Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\n#include \"bochs.h\"\n#define LOG_THIS genlog->\n\n\n\nstatic void bx_load_linux_hack(void);\nstatic void bx_load_null_kernel_hack(void);\nstatic Bit32u bx_load_kernel_image(char *path, Bit32u paddr);\n\n void\nbx_load32bitOSimagehack(void)\n{\n \/\/ Replay IO from log to initialize IO devices to\n \/\/ a reasonable state needed for the OS. This is done\n \/\/ in lieu of running the 16-bit BIOS to init things,\n \/\/ since we want to test straight 32bit stuff for\n \/\/ freemware.\n\n FILE *fp;\n\n fp = fopen(bx_options.load32bitOSImage.Oiolog->getptr (), \"r\");\n\n if (fp == NULL) {\n BX_PANIC((\"could not open IO init file.\"));\n }\n\n while (1) {\n unsigned len, op, port, val;\n int ret;\n ret = fscanf(fp, \"%u %u %x %x\\n\",\n &len, &op, &port, &val);\n if (ret != 4) {\n BX_PANIC((\"could not open IO init file.\"));\n }\n if (op == 0) {\n \/\/ read\n (void) bx_devices.inp(port, len);\n }\n else if (op == 1) {\n \/\/ write\n bx_devices.outp(port, val, len);\n }\n else {\n BX_PANIC((\"bad IO op in init filen\"));\n }\n if (feof(fp)) break;\n }\n\n \/\/ Invoke proper hack depending on which OS image we're loading\n switch (bx_options.load32bitOSImage.OwhichOS->get ()) {\n case Load32bitOSLinux:\n bx_load_linux_hack();\n break;\n case Load32bitOSNullKernel:\n bx_load_null_kernel_hack();\n break;\n default:\n BX_PANIC((\"load32bitOSImage: OS not recognized\"));\n }\n}\n\nstruct gdt_entry\n{\n Bit32u low;\n Bit32u high;\n};\nstruct linux_setup_params\n{\n \/* 0x000 *\/ Bit8u orig_x;\n \/* 0x001 *\/ Bit8u orig_y;\n \/* 0x002 *\/ Bit16u memory_size_std;\n \/* 0x004 *\/ Bit16u orig_video_page;\n \/* 0x006 *\/ Bit8u orig_video_mode;\n \/* 0x007 *\/ Bit8u orig_video_cols;\n \/* 0x008 *\/ Bit16u unused1;\n \/* 0x00a *\/ Bit16u orig_video_ega_bx;\n \/* 0x00c *\/ Bit16u unused2;\n \/* 0x00e *\/ Bit8u orig_video_lines;\n \/* 0x00f *\/ Bit8u orig_video_isVGA;\n \/* 0x010 *\/ Bit16u orig_video_points;\n \/* 0x012 *\/ Bit8u pad1[0x40 - 0x12];\n \/* 0x040 *\/ Bit8u apm_info[0x80 - 0x40];\n \/* 0x080 *\/ Bit8u hd0_info[16];\n \/* 0x090 *\/ Bit8u hd1_info[16];\n \/* 0x0a0 *\/ Bit8u pad2[0x1e0 - 0xa0];\n \/* 0x1e0 *\/ Bit32u memory_size_ext;\n \/* 0x1e4 *\/ Bit8u pad3[0x1f1 - 0x1e4];\n \/* 0x1f1 *\/ Bit8u setup_sects;\n \/* 0x1f2 *\/ Bit16u mount_root_rdonly;\n \/* 0x1f4 *\/ Bit16u sys_size;\n \/* 0x1f6 *\/ Bit16u swap_dev;\n \/* 0x1f8 *\/ Bit16u ramdisk_flags;\n \/* 0x1fa *\/ Bit16u vga_mode;\n \/* 0x1fc *\/ Bit16u orig_root_dev;\n \/* 0x1fe *\/ Bit16u bootsect_magic;\n \/* 0x200 *\/ Bit8u pad4[0x210 - 0x200];\n \/* 0x210 *\/ Bit32u loader_type;\n \/* 0x214 *\/ Bit32u kernel_start;\n \/* 0x218 *\/ Bit32u initrd_start;\n \/* 0x21c *\/ Bit32u initrd_size;\n \/* 0x220 *\/ Bit8u pad5[0x400 - 0x220];\n \/* 0x400 *\/ struct gdt_entry gdt[128];\n \/* 0x800 *\/ Bit8u commandline[2048];\n};\n\n static void\nbx_load_linux_setup_params( Bit32u initrd_start, Bit32u initrd_size )\n{\n BX_MEM_C *mem = BX_MEM(0);\n struct linux_setup_params *params =\n (struct linux_setup_params *) &mem->vector[0x00090000];\n\n memset( params, '\\0', sizeof(*params) );\n\n \/* Video settings (standard VGA) *\/\n params->orig_x = 0;\n params->orig_y = 0;\n params->orig_video_page = 0;\n params->orig_video_mode = 3;\n params->orig_video_cols = 80;\n params->orig_video_lines = 25;\n params->orig_video_points = 16;\n params->orig_video_isVGA = 1;\n params->orig_video_ega_bx = 3;\n\n \/* Memory size (total mem - 1MB, in KB) *\/\n params->memory_size_ext = (mem->megabytes - 1) * 1024;\n\n \/* Boot parameters *\/\n params->loader_type = 1;\n params->bootsect_magic = 0xaa55;\n params->mount_root_rdonly = 0;\n params->orig_root_dev = 0x0100;\n params->initrd_start = initrd_start;\n params->initrd_size = initrd_size;\n\n \/* Initial GDT *\/\n params->gdt[2].high = 0x00cf9a00;\n params->gdt[2].low = 0x0000ffff;\n params->gdt[3].high = 0x00cf9200;\n params->gdt[3].low = 0x0000ffff;\n}\n\n void\nbx_load_linux_hack(void)\n{\n Bit32u initrd_start = 0, initrd_size = 0;\n\n \/\/ The RESET function will have been called first.\n \/\/ Set CPU and memory features which are assumed at this point.\n\n \/\/ Load Linux kernel image\n bx_load_kernel_image( bx_options.load32bitOSImage.Opath->getptr (), 0x100000 );\n\n \/\/ Load initial ramdisk image if requested\n if ( bx_options.load32bitOSImage.Oinitrd->getptr () )\n {\n initrd_start = 0x00800000; \/* FIXME: load at top of memory *\/\n initrd_size = bx_load_kernel_image( bx_options.load32bitOSImage.Oinitrd->getptr (), initrd_start );\n }\n\n \/\/ Setup Linux startup parameters buffer\n bx_load_linux_setup_params( initrd_start, initrd_size );\n\n \/\/ Enable A20 line\n BX_SET_ENABLE_A20( 1 );\n\n \/\/ Setup PICs the way Linux likes it\n BX_OUTP( 0x20, 0x11, 1 );\n BX_OUTP( 0xA0, 0x11, 1 );\n BX_OUTP( 0x21, 0x20, 1 );\n BX_OUTP( 0xA1, 0x28, 1 );\n BX_OUTP( 0x21, 0x04, 1 );\n BX_OUTP( 0xA1, 0x02, 1 );\n BX_OUTP( 0x21, 0x01, 1 );\n BX_OUTP( 0xA1, 0x01, 1 );\n BX_OUTP( 0x21, 0xFF, 1 );\n BX_OUTP( 0xA1, 0xFB, 1 );\n\n \/\/ Disable interrupts and NMIs\n BX_CPU(0)->clear_IF ();\n BX_OUTP( 0x70, 0x80, 1 );\n\n \/\/ Enter protected mode\n \/\/ Fixed by george (kyriazis at nvidia.com)\n \/\/ BX_CPU(0)->cr0.pe = 1;\n \/\/ BX_CPU(0)->cr0.val32 |= 0x01;\n\n BX_CPU(0)->SetCR0(BX_CPU(0)->cr0.val32 | 0x01);\n \n \/\/ load esi with real_mode\n BX_CPU(0)->gen_reg[BX_32BIT_REG_ESI].dword.erx = 0x90000; \n\n \/\/ Set up initial GDT\n BX_CPU(0)->gdtr.limit = 0x400;\n BX_CPU(0)->gdtr.base = 0x00090400;\n\n \/\/ Jump to protected mode entry point\n BX_CPU(0)->jump_protected( NULL, 0x10, 0x00100000 );\n}\n\n void\nbx_load_null_kernel_hack(void)\n{\n \/\/ The RESET function will have been called first.\n \/\/ Set CPU and memory features which are assumed at this point.\n\n bx_load_kernel_image(bx_options.load32bitOSImage.Opath->getptr (), 0x100000);\n\n \/\/ EIP deltas\n BX_CPU(0)->prev_eip =\n BX_CPU(0)->dword.eip = 0x00100000;\n\n \/\/ CS deltas\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.base = 0x00000000;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit = 0xFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit_scaled = 0xFFFFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.g = 1; \/\/ page gran\n BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.d_b = 1; \/\/ 32bit\n\n \/\/ DS deltas\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.base = 0x00000000;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit = 0xFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit_scaled = 0xFFFFFFFF;\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.g = 1; \/\/ page gran\n BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.d_b = 1; \/\/ 32bit\n\n \/\/ CR0 deltas\n BX_CPU(0)->cr0.pe = 1; \/\/ protected mode\n}\n\n Bit32u\nbx_load_kernel_image(char *path, Bit32u paddr)\n{\n struct stat stat_buf;\n int fd, ret;\n unsigned long size, offset;\n Bit32u page_size;\n\n \/\/ read in ROM BIOS image file\n fd = open(path, O_RDONLY\n#ifdef O_BINARY\n | O_BINARY\n#endif\n );\n if (fd < 0) {\n BX_INFO(( \"load_kernel_image: couldn't open image file '%s'.\", path ));\n BX_EXIT(1);\n }\n ret = fstat(fd, &stat_buf);\n if (ret) {\n BX_INFO(( \"load_kernel_image: couldn't stat image file '%s'.\", path ));\n BX_EXIT(1);\n }\n\n size = stat_buf.st_size;\n page_size = ((Bit32u)size + 0xfff) & ~0xfff;\n\n BX_MEM_C *mem = BX_MEM(0);\n if ( (paddr + size) > mem->len ) {\n BX_INFO(( \"load_kernel_image: address range > physical memsize!\" ));\n BX_EXIT(1);\n }\n\n offset = 0;\n while (size > 0) {\n ret = read(fd, (bx_ptr_t) &mem->vector[paddr + offset], size);\n if (ret <= 0) {\n BX_INFO(( \"load_kernel_image: read failed on image\" ));\n BX_EXIT(1);\n }\n size -= ret;\n offset += ret;\n }\n close(fd);\n BX_INFO(( \"#(%u) load_kernel_image: '%s', size=%u read into memory at %08x\",\n BX_SIM_ID, path,\n (unsigned) stat_buf.st_size,\n (unsigned) paddr ));\n\n return page_size;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xsecparser.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 14:41:05 $\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_xmlsecurity.hxx\"\n\n#include \"xsecparser.hxx\"\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen wg. DBG_ASSERT\n#include <tools\/debug.hxx>\n#endif\n#include \"cppuhelper\/exc_hlp.hxx\"\n\nnamespace cssu = com::sun::star::uno;\nnamespace cssxs = com::sun::star::xml::sax;\n\n#define RTL_ASCII_USTRINGPARAM( asciiStr ) asciiStr, strlen( asciiStr ), RTL_TEXTENCODING_ASCII_US\n\nXSecParser::XSecParser(\n XSecController* pXSecController,\n const cssu::Reference< cssxs::XDocumentHandler >& xNextHandler )\n : m_pXSecController(pXSecController),\n m_xNextHandler(xNextHandler),\n m_bReferenceUnresolved(false)\n{\n}\n\nrtl::OUString XSecParser::getIdAttr(const cssu::Reference< cssxs::XAttributeList >& xAttribs )\n{\n rtl::OUString ouIdAttr = xAttribs->getValueByName(\n rtl::OUString(RTL_ASCII_USTRINGPARAM(\"id\")));\n\n if (ouIdAttr == NULL)\n {\n ouIdAttr = xAttribs->getValueByName(\n rtl::OUString(RTL_ASCII_USTRINGPARAM(\"Id\")));\n }\n\n return ouIdAttr;\n}\n\n\/*\n * XDocumentHandler\n *\/\nvoid SAL_CALL XSecParser::startDocument( )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n m_bInX509IssuerName = false;\n m_bInX509SerialNumber = false;\n m_bInX509Certificate = false;\n m_bInSignatureValue = false;\n m_bInDigestValue = false;\n m_bInDate = false;\n \/\/m_bInTime = false;\n\n if (m_xNextHandler.is())\n {\n m_xNextHandler->startDocument();\n }\n}\n\nvoid SAL_CALL XSecParser::endDocument( )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_xNextHandler.is())\n {\n m_xNextHandler->endDocument();\n }\n}\n\nvoid SAL_CALL XSecParser::startElement(\n const rtl::OUString& aName,\n const cssu::Reference< cssxs::XAttributeList >& xAttribs )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n try\n {\n rtl::OUString ouIdAttr = getIdAttr(xAttribs);\n if (ouIdAttr != NULL)\n {\n m_pXSecController->collectToVerify( ouIdAttr );\n }\n\n if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATURE)) )\n {\n m_pXSecController->addSignature();\n if (ouIdAttr != NULL)\n {\n m_pXSecController->setId( ouIdAttr );\n }\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_REFERENCE)) )\n {\n rtl::OUString ouUri = xAttribs->getValueByName(rtl::OUString(RTL_ASCII_USTRINGPARAM(ATTR_URI)));\n DBG_ASSERT( ouUri != NULL, \"URI == NULL\" );\n\n if (0 == ouUri.compareTo(rtl::OUString(RTL_ASCII_USTRINGPARAM(CHAR_FRAGMENT)),1))\n {\n \/*\n * remove the first character '#' from the attribute value\n *\/\n m_pXSecController->addReference( ouUri.copy(1) );\n }\n else\n {\n \/*\n * remember the uri\n *\/\n m_currentReferenceURI = ouUri;\n m_bReferenceUnresolved = true;\n }\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TRANSFORM)))\n {\n if ( m_bReferenceUnresolved )\n {\n rtl::OUString ouAlgorithm = xAttribs->getValueByName(rtl::OUString(RTL_ASCII_USTRINGPARAM(ATTR_ALGORITHM)));\n\n if (ouAlgorithm != NULL && ouAlgorithm == rtl::OUString(RTL_ASCII_USTRINGPARAM(ALGO_C14N)))\n \/*\n * a xml stream\n *\/\n {\n m_pXSecController->addStreamReference( m_currentReferenceURI, sal_False);\n m_bReferenceUnresolved = false;\n }\n }\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509ISSUERNAME)))\n {\n m_ouX509IssuerName = rtl::OUString::createFromAscii(\"\");\n m_bInX509IssuerName = true;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509SERIALNUMBER)))\n {\n m_ouX509SerialNumber = rtl::OUString::createFromAscii(\"\");\n m_bInX509SerialNumber = true;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509CERTIFICATE)))\n {\n m_ouX509Certificate = rtl::OUString::createFromAscii(\"\");\n m_bInX509Certificate = true;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREVALUE)))\n {\n m_ouSignatureValue = rtl::OUString::createFromAscii(\"\");\n m_bInSignatureValue = true;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_DIGESTVALUE)))\n {\n m_ouDigestValue = rtl::OUString::createFromAscii(\"\");\n m_bInDigestValue = true;\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREPROPERTY)) )\n {\n if (ouIdAttr != NULL)\n {\n m_pXSecController->setPropertyId( ouIdAttr );\n }\n }\n else if (aName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(NSTAG_DC))\n +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\":\"))\n +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(TAG_DATE)))\n {\n m_ouDate = rtl::OUString::createFromAscii(\"\");\n m_bInDate = true;\n }\n \/*\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TIME)))\n {\n m_ouTime = rtl::OUString::createFromAscii(\"\");\n m_bInTime = true;\n }\n *\/\n\n if (m_xNextHandler.is())\n {\n m_xNextHandler->startElement(aName, xAttribs);\n }\n }\n catch (cssu::Exception& )\n {\/\/getCaughtException MUST be the first line in the catch block\n cssu::Any exc = cppu::getCaughtException();\n throw cssxs::SAXException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n \"xmlsecurity: Exception in XSecParser::startElement\")),\n 0, exc);\n }\n catch (...)\n {\n throw cssxs::SAXException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"xmlsecurity: unexpected exception in XSecParser::startElement\")), 0,\n cssu::Any());\n }\n}\n\nvoid SAL_CALL XSecParser::endElement( const rtl::OUString& aName )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n try\n {\n if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_DIGESTVALUE)))\n {\n m_bInDigestValue = false;\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_REFERENCE)) )\n {\n if ( m_bReferenceUnresolved )\n \/*\n * it must be a octet stream\n *\/\n {\n m_pXSecController->addStreamReference( m_currentReferenceURI, sal_True);\n m_bReferenceUnresolved = false;\n }\n\n m_pXSecController->setDigestValue( m_ouDigestValue );\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNEDINFO)) )\n {\n m_pXSecController->setReferenceCount();\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREVALUE)) )\n {\n m_pXSecController->setSignatureValue( m_ouSignatureValue );\n m_bInSignatureValue = false;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509ISSUERNAME)))\n {\n m_pXSecController->setX509IssuerName( m_ouX509IssuerName );\n m_bInX509IssuerName = false;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509SERIALNUMBER)))\n {\n m_pXSecController->setX509SerialNumber( m_ouX509SerialNumber );\n m_bInX509SerialNumber = false;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509CERTIFICATE)))\n {\n m_pXSecController->setX509Certificate( m_ouX509Certificate );\n m_bInX509Certificate = false;\n }\n else if (aName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(NSTAG_DC))\n +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\":\"))\n +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(TAG_DATE)))\n {\n m_pXSecController->setDate( m_ouDate );\n m_bInDate = false;\n }\n \/*\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TIME)) )\n {\n m_pXSecController->setTime( m_ouTime );\n m_bInTime = false;\n }\n *\/\n\n if (m_xNextHandler.is())\n {\n m_xNextHandler->endElement(aName);\n }\n }\n catch (cssu::Exception& )\n {\/\/getCaughtException MUST be the first line in the catch block\n cssu::Any exc = cppu::getCaughtException();\n throw cssxs::SAXException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n \"xmlsecurity: Exception in XSecParser::endElement\")),\n 0, exc);\n }\n catch (...)\n {\n throw cssxs::SAXException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"xmlsecurity: unexpected exception in XSecParser::endElement\")), 0,\n cssu::Any());\n }\n}\n\nvoid SAL_CALL XSecParser::characters( const rtl::OUString& aChars )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_bInX509IssuerName)\n {\n m_ouX509IssuerName += aChars;\n }\n else if (m_bInX509SerialNumber)\n {\n m_ouX509SerialNumber += aChars;\n }\n else if (m_bInX509Certificate)\n {\n m_ouX509Certificate += aChars;\n }\n else if (m_bInSignatureValue)\n {\n m_ouSignatureValue += aChars;\n }\n else if (m_bInDigestValue)\n {\n m_ouDigestValue += aChars;\n }\n else if (m_bInDate)\n {\n m_ouDate += aChars;\n }\n \/*\n else if (m_bInTime)\n {\n m_ouTime += aChars;\n }\n *\/\n\n if (m_xNextHandler.is())\n {\n m_xNextHandler->characters(aChars);\n }\n}\n\nvoid SAL_CALL XSecParser::ignorableWhitespace( const rtl::OUString& aWhitespaces )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_xNextHandler.is())\n {\n m_xNextHandler->ignorableWhitespace( aWhitespaces );\n }\n}\n\nvoid SAL_CALL XSecParser::processingInstruction( const rtl::OUString& aTarget, const rtl::OUString& aData )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_xNextHandler.is())\n {\n m_xNextHandler->processingInstruction(aTarget, aData);\n }\n}\n\nvoid SAL_CALL XSecParser::setDocumentLocator( const cssu::Reference< cssxs::XLocator >& xLocator )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_xNextHandler.is())\n {\n m_xNextHandler->setDocumentLocator( xLocator );\n }\n}\n\n\/*\n * XInitialization\n *\/\nvoid SAL_CALL XSecParser::initialize(\n const cssu::Sequence< cssu::Any >& aArguments )\n throw(cssu::Exception, cssu::RuntimeException)\n{\n aArguments[0] >>= m_xNextHandler;\n}\n<commit_msg>INTEGRATION: CWS gcc430two (1.6.94); FILE MERGED 2008\/01\/28 09:53:15 rene 1.6.94.1: more gcc 4.3.0 things<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xsecparser.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: ihi $ $Date: 2008-02-04 13:43:11 $\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_xmlsecurity.hxx\"\n\n#include \"xsecparser.hxx\"\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen wg. DBG_ASSERT\n#include <tools\/debug.hxx>\n#endif\n#include \"cppuhelper\/exc_hlp.hxx\"\n\n#include <string.h>\n\nnamespace cssu = com::sun::star::uno;\nnamespace cssxs = com::sun::star::xml::sax;\n\n#define RTL_ASCII_USTRINGPARAM( asciiStr ) asciiStr, strlen( asciiStr ), RTL_TEXTENCODING_ASCII_US\n\nXSecParser::XSecParser(\n XSecController* pXSecController,\n const cssu::Reference< cssxs::XDocumentHandler >& xNextHandler )\n : m_pXSecController(pXSecController),\n m_xNextHandler(xNextHandler),\n m_bReferenceUnresolved(false)\n{\n}\n\nrtl::OUString XSecParser::getIdAttr(const cssu::Reference< cssxs::XAttributeList >& xAttribs )\n{\n rtl::OUString ouIdAttr = xAttribs->getValueByName(\n rtl::OUString(RTL_ASCII_USTRINGPARAM(\"id\")));\n\n if (ouIdAttr == NULL)\n {\n ouIdAttr = xAttribs->getValueByName(\n rtl::OUString(RTL_ASCII_USTRINGPARAM(\"Id\")));\n }\n\n return ouIdAttr;\n}\n\n\/*\n * XDocumentHandler\n *\/\nvoid SAL_CALL XSecParser::startDocument( )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n m_bInX509IssuerName = false;\n m_bInX509SerialNumber = false;\n m_bInX509Certificate = false;\n m_bInSignatureValue = false;\n m_bInDigestValue = false;\n m_bInDate = false;\n \/\/m_bInTime = false;\n\n if (m_xNextHandler.is())\n {\n m_xNextHandler->startDocument();\n }\n}\n\nvoid SAL_CALL XSecParser::endDocument( )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_xNextHandler.is())\n {\n m_xNextHandler->endDocument();\n }\n}\n\nvoid SAL_CALL XSecParser::startElement(\n const rtl::OUString& aName,\n const cssu::Reference< cssxs::XAttributeList >& xAttribs )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n try\n {\n rtl::OUString ouIdAttr = getIdAttr(xAttribs);\n if (ouIdAttr != NULL)\n {\n m_pXSecController->collectToVerify( ouIdAttr );\n }\n\n if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATURE)) )\n {\n m_pXSecController->addSignature();\n if (ouIdAttr != NULL)\n {\n m_pXSecController->setId( ouIdAttr );\n }\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_REFERENCE)) )\n {\n rtl::OUString ouUri = xAttribs->getValueByName(rtl::OUString(RTL_ASCII_USTRINGPARAM(ATTR_URI)));\n DBG_ASSERT( ouUri != NULL, \"URI == NULL\" );\n\n if (0 == ouUri.compareTo(rtl::OUString(RTL_ASCII_USTRINGPARAM(CHAR_FRAGMENT)),1))\n {\n \/*\n * remove the first character '#' from the attribute value\n *\/\n m_pXSecController->addReference( ouUri.copy(1) );\n }\n else\n {\n \/*\n * remember the uri\n *\/\n m_currentReferenceURI = ouUri;\n m_bReferenceUnresolved = true;\n }\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TRANSFORM)))\n {\n if ( m_bReferenceUnresolved )\n {\n rtl::OUString ouAlgorithm = xAttribs->getValueByName(rtl::OUString(RTL_ASCII_USTRINGPARAM(ATTR_ALGORITHM)));\n\n if (ouAlgorithm != NULL && ouAlgorithm == rtl::OUString(RTL_ASCII_USTRINGPARAM(ALGO_C14N)))\n \/*\n * a xml stream\n *\/\n {\n m_pXSecController->addStreamReference( m_currentReferenceURI, sal_False);\n m_bReferenceUnresolved = false;\n }\n }\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509ISSUERNAME)))\n {\n m_ouX509IssuerName = rtl::OUString::createFromAscii(\"\");\n m_bInX509IssuerName = true;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509SERIALNUMBER)))\n {\n m_ouX509SerialNumber = rtl::OUString::createFromAscii(\"\");\n m_bInX509SerialNumber = true;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509CERTIFICATE)))\n {\n m_ouX509Certificate = rtl::OUString::createFromAscii(\"\");\n m_bInX509Certificate = true;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREVALUE)))\n {\n m_ouSignatureValue = rtl::OUString::createFromAscii(\"\");\n m_bInSignatureValue = true;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_DIGESTVALUE)))\n {\n m_ouDigestValue = rtl::OUString::createFromAscii(\"\");\n m_bInDigestValue = true;\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREPROPERTY)) )\n {\n if (ouIdAttr != NULL)\n {\n m_pXSecController->setPropertyId( ouIdAttr );\n }\n }\n else if (aName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(NSTAG_DC))\n +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\":\"))\n +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(TAG_DATE)))\n {\n m_ouDate = rtl::OUString::createFromAscii(\"\");\n m_bInDate = true;\n }\n \/*\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TIME)))\n {\n m_ouTime = rtl::OUString::createFromAscii(\"\");\n m_bInTime = true;\n }\n *\/\n\n if (m_xNextHandler.is())\n {\n m_xNextHandler->startElement(aName, xAttribs);\n }\n }\n catch (cssu::Exception& )\n {\/\/getCaughtException MUST be the first line in the catch block\n cssu::Any exc = cppu::getCaughtException();\n throw cssxs::SAXException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n \"xmlsecurity: Exception in XSecParser::startElement\")),\n 0, exc);\n }\n catch (...)\n {\n throw cssxs::SAXException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"xmlsecurity: unexpected exception in XSecParser::startElement\")), 0,\n cssu::Any());\n }\n}\n\nvoid SAL_CALL XSecParser::endElement( const rtl::OUString& aName )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n try\n {\n if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_DIGESTVALUE)))\n {\n m_bInDigestValue = false;\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_REFERENCE)) )\n {\n if ( m_bReferenceUnresolved )\n \/*\n * it must be a octet stream\n *\/\n {\n m_pXSecController->addStreamReference( m_currentReferenceURI, sal_True);\n m_bReferenceUnresolved = false;\n }\n\n m_pXSecController->setDigestValue( m_ouDigestValue );\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNEDINFO)) )\n {\n m_pXSecController->setReferenceCount();\n }\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREVALUE)) )\n {\n m_pXSecController->setSignatureValue( m_ouSignatureValue );\n m_bInSignatureValue = false;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509ISSUERNAME)))\n {\n m_pXSecController->setX509IssuerName( m_ouX509IssuerName );\n m_bInX509IssuerName = false;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509SERIALNUMBER)))\n {\n m_pXSecController->setX509SerialNumber( m_ouX509SerialNumber );\n m_bInX509SerialNumber = false;\n }\n else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509CERTIFICATE)))\n {\n m_pXSecController->setX509Certificate( m_ouX509Certificate );\n m_bInX509Certificate = false;\n }\n else if (aName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(NSTAG_DC))\n +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\":\"))\n +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(TAG_DATE)))\n {\n m_pXSecController->setDate( m_ouDate );\n m_bInDate = false;\n }\n \/*\n else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TIME)) )\n {\n m_pXSecController->setTime( m_ouTime );\n m_bInTime = false;\n }\n *\/\n\n if (m_xNextHandler.is())\n {\n m_xNextHandler->endElement(aName);\n }\n }\n catch (cssu::Exception& )\n {\/\/getCaughtException MUST be the first line in the catch block\n cssu::Any exc = cppu::getCaughtException();\n throw cssxs::SAXException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n \"xmlsecurity: Exception in XSecParser::endElement\")),\n 0, exc);\n }\n catch (...)\n {\n throw cssxs::SAXException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"xmlsecurity: unexpected exception in XSecParser::endElement\")), 0,\n cssu::Any());\n }\n}\n\nvoid SAL_CALL XSecParser::characters( const rtl::OUString& aChars )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_bInX509IssuerName)\n {\n m_ouX509IssuerName += aChars;\n }\n else if (m_bInX509SerialNumber)\n {\n m_ouX509SerialNumber += aChars;\n }\n else if (m_bInX509Certificate)\n {\n m_ouX509Certificate += aChars;\n }\n else if (m_bInSignatureValue)\n {\n m_ouSignatureValue += aChars;\n }\n else if (m_bInDigestValue)\n {\n m_ouDigestValue += aChars;\n }\n else if (m_bInDate)\n {\n m_ouDate += aChars;\n }\n \/*\n else if (m_bInTime)\n {\n m_ouTime += aChars;\n }\n *\/\n\n if (m_xNextHandler.is())\n {\n m_xNextHandler->characters(aChars);\n }\n}\n\nvoid SAL_CALL XSecParser::ignorableWhitespace( const rtl::OUString& aWhitespaces )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_xNextHandler.is())\n {\n m_xNextHandler->ignorableWhitespace( aWhitespaces );\n }\n}\n\nvoid SAL_CALL XSecParser::processingInstruction( const rtl::OUString& aTarget, const rtl::OUString& aData )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_xNextHandler.is())\n {\n m_xNextHandler->processingInstruction(aTarget, aData);\n }\n}\n\nvoid SAL_CALL XSecParser::setDocumentLocator( const cssu::Reference< cssxs::XLocator >& xLocator )\n throw (cssxs::SAXException, cssu::RuntimeException)\n{\n if (m_xNextHandler.is())\n {\n m_xNextHandler->setDocumentLocator( xLocator );\n }\n}\n\n\/*\n * XInitialization\n *\/\nvoid SAL_CALL XSecParser::initialize(\n const cssu::Sequence< cssu::Any >& aArguments )\n throw(cssu::Exception, cssu::RuntimeException)\n{\n aArguments[0] >>= m_xNextHandler;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ZipFile.cxx,v $\n *\n * $Revision: 1.22 $\n *\n * last change: $Author: mtg $ $Date: 2001-05-31 09:48:20 $\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): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_FILE_HXX\n#include <ZipFile.hxx>\n#endif\n#ifndef _ENTRY_INPUT_STREAM_HXX\n#include <EntryInputStream.hxx>\n#endif\n#ifndef _ZIP_ENUMERATION_HXX\n#include <ZipEnumeration.hxx>\n#endif\n#ifndef _VOS_DIAGNOSE_H_\n#include <vos\/diagnose.hxx>\n#endif\n#ifndef _COM_SUN_STAR_PACKAGES_ZIPCONSTANTS_HPP_\n#include <com\/sun\/star\/packages\/ZipConstants.hpp>\n#endif\n#include <vector>\n\n\nusing namespace rtl;\nusing namespace com::sun::star;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::packages;\nusing namespace com::sun::star::packages::ZipConstants;\n\n\/** This class is used to read entries from a zip file\n *\/\nZipFile::ZipFile( Reference < io::XInputStream > &xInput, sal_Bool bInitialise)\n throw(io::IOException, ZipException, RuntimeException)\n: xStream(xInput)\n, aGrabber(xInput)\n, aInflater (sal_True)\n{\n if (bInitialise)\n readCEN();\n}\nvoid ZipFile::setInputStream ( Reference < io::XInputStream > xNewStream )\n{\n xStream = xNewStream;\n aGrabber.setInputStream ( xStream );\n}\n\nZipFile::~ZipFile()\n{\n aEntries.clear();\n}\n\nvoid SAL_CALL ZipFile::close( )\n throw(io::IOException, RuntimeException)\n{\n}\n\nZipEnumeration * SAL_CALL ZipFile::entries( )\n{\n return new ZipEnumeration ( aEntries );\n}\n\n::rtl::OUString SAL_CALL ZipFile::getName( )\n throw(RuntimeException)\n{\n return sName;\n}\n\nsal_Int32 SAL_CALL ZipFile::getSize( )\n throw(RuntimeException)\n{\n return aEntries.size();\n}\n\nType SAL_CALL ZipFile::getElementType( )\n throw(RuntimeException)\n{\n return ::getCppuType((ZipEntry *) 0);\n}\n\nsal_Bool SAL_CALL ZipFile::hasElements( )\n throw(RuntimeException)\n{\n return (aEntries.size()>0);\n}\n\nAny SAL_CALL ZipFile::getByName( const ::rtl::OUString& aName )\n throw(container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)\n{\n Any aAny;\n EntryHash::const_iterator aCI = aEntries.find(sName);\n if (aCI == aEntries.end())\n throw container::NoSuchElementException();\n aAny <<= (*aCI).second;\n return aAny;\n}\n\nSequence< ::rtl::OUString > SAL_CALL ZipFile::getElementNames( )\n throw(RuntimeException)\n{\n sal_uInt32 i=0, nSize = aEntries.size();\n OUString *pNames = new OUString[aEntries.size()];\n for (EntryHash::const_iterator aIterator = aEntries.begin(); aIterator != aEntries.end(); aIterator++,i++)\n pNames[i] = (*aIterator).first;\n return Sequence<OUString> (pNames, nSize);\n}\n\nsal_Bool SAL_CALL ZipFile::hasByName( const ::rtl::OUString& aName )\n throw(RuntimeException)\n{\n return aEntries.find(aName) != aEntries.end();\n}\n\nReference< io::XInputStream > SAL_CALL ZipFile::getInputStream( ZipEntry& rEntry,\n const vos::ORef < EncryptionData > &rData)\n throw(io::IOException, ZipException, RuntimeException)\n{\n if (rEntry.nOffset <= 0)\n readLOC(rEntry);\n Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_False );\n return xStreamRef;\n}\n\nReference< io::XInputStream > SAL_CALL ZipFile::getRawStream( ZipEntry& rEntry,\n const vos::ORef < EncryptionData > &rData)\n throw(io::IOException, ZipException, RuntimeException)\n{\n if (rEntry.nOffset <= 0)\n readLOC(rEntry);\n Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_True );\n return xStreamRef;\n}\n\nsal_Bool ZipFile::readLOC( ZipEntry &rEntry )\n throw(io::IOException, ZipException, RuntimeException)\n{\n sal_uInt32 nTestSig, nTime, nCRC, nSize, nCompressedSize;\n sal_uInt16 nVersion, nFlag, nHow, nNameLen, nExtraLen;\n sal_Int32 nPos = -rEntry.nOffset;\n\n aGrabber.seek(nPos);\n aGrabber >> nTestSig;\n\n if (nTestSig != LOCSIG)\n throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid LOC header (bad signature\") ), Reference < XInterface > () );\n aGrabber >> nVersion;\n aGrabber >> nFlag;\n aGrabber >> nHow;\n aGrabber >> nTime;\n aGrabber >> nCRC;\n aGrabber >> nCompressedSize;\n aGrabber >> nSize;\n aGrabber >> nNameLen;\n aGrabber >> nExtraLen;\n rEntry.nOffset = static_cast < sal_Int32 > (aGrabber.getPosition()) + nNameLen + nExtraLen;\n return sal_True;\n}\n\nsal_Int32 ZipFile::findEND( )\n throw(io::IOException, ZipException, RuntimeException)\n{\n sal_Int32 nLength=0, nPos=0;\n Sequence < sal_Int8 > aByteSeq;\n nLength = nPos = static_cast <sal_Int32 > (aGrabber.getLength());\n\n if (nLength == 0)\n return -1;\n \/\/throw (ZipException( OUString::createFromAscii(\"Trying to find Zip END signature in a zero length file!\"), Reference < XInterface> () ));\n\n aGrabber.seek( nLength );\n\n while (nLength - nPos < 0xFFFF)\n {\n sal_uInt32 nCount = 0xFFFF - ( nLength - nPos);\n if (nCount > ENDHDR)\n nCount = ENDHDR;\n nPos -= nCount;\n\n for (sal_uInt16 i=0; i <nCount;i++)\n {\n sal_uInt32 nTest=0, nFoo=ENDSIG;\n aGrabber.seek (nPos+i);\n aGrabber >> nTest;\n if (nTest == ENDSIG)\n {\n sal_uInt16 nCommentLength;\n sal_Int32 nEndPos = nPos + i;\n aGrabber.seek(nEndPos+ENDCOM);\n aGrabber >> nCommentLength;\n if (nEndPos + ENDHDR + nCommentLength == nLength)\n {\n if (nCommentLength>0)\n {\n aByteSeq.realloc(nCommentLength+1);\n aGrabber.readBytes(Sequence< sal_Int8>(aByteSeq.getArray(), nCommentLength), nCommentLength);\n aByteSeq[nCommentLength]='\\0';\n sComment = OUString((sal_Char*)aByteSeq.getConstArray(), nCommentLength+1, RTL_TEXTENCODING_ASCII_US);\n\n }\n return nPos + i;\n }\n }\n }\n }\n throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Zip END signature not found!\") ), Reference < XInterface> () );\n}\n\nsal_Int32 ZipFile::readCEN()\n throw(io::IOException, ZipException, RuntimeException)\n{\n sal_Int32 nEndPos, nLocPos;\n sal_Int16 nCount, nTotal;\n sal_Int32 nCenLen, nCenPos, nCenOff;\n\n nEndPos = findEND();\n if (nEndPos == -1)\n return -1;\n aGrabber.seek(nEndPos + ENDTOT);\n aGrabber >> nTotal;\n aGrabber >> nCenLen;\n aGrabber >> nCenOff;\n\n if (nTotal<0 || nTotal * CENHDR > nCenLen)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"invalid END header (bad entry count)\") ), Reference < XInterface > ());\n\n if (nTotal > ZIP_MAXENTRIES)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"too many entries in ZIP File\") ), Reference < XInterface > ());\n\n if (nCenLen < 0 || nCenLen > nEndPos)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid END header (bad central directory size)\") ), Reference < XInterface > ());\n\n nCenPos = nEndPos - nCenLen;\n\n if (nCenOff < 0 || nCenOff > nCenPos)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid END header (bad central directory size)\") ), Reference < XInterface > ());\n\n nLocPos = nCenPos - nCenOff;\n aGrabber.seek(nCenPos);\n\n ZipEntry *pEntry = new ZipEntry;\n for (nCount = 0 ; nCount < nTotal; nCount++)\n {\n sal_Int32 nTestSig, nCRC, nCompressedSize, nTime, nSize, nExtAttr, nOffset;\n sal_Int16 nVerMade, nVersion, nFlag, nHow, nNameLen, nExtraLen, nCommentLen;\n sal_Int16 nDisk, nIntAttr;\n\n if (aGrabber.getPosition() - nCenPos + CENHDR > nCenLen)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (bad header size check 1)\") ), Reference < XInterface > ());\n\n aGrabber >> nTestSig;\n if (nTestSig != CENSIG)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (bad signature)\") ), Reference < XInterface > ());\n\n aGrabber >> nVerMade;\n aGrabber >> nVersion;\n if ((nVersion & 1) == 1)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (encrypted entry)\") ), Reference < XInterface > ());\n\n aGrabber >> nFlag;\n aGrabber >> nHow;\n if (nHow != STORED && nHow != DEFLATED)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (bad compression method)\") ), Reference < XInterface > ());\n\n aGrabber >> nTime;\n aGrabber >> nCRC;\n aGrabber >> nCompressedSize;\n aGrabber >> nSize;\n aGrabber >> nNameLen;\n aGrabber >> nExtraLen;\n aGrabber >> nCommentLen;\n aGrabber >> nDisk;\n aGrabber >> nIntAttr;\n aGrabber >> nExtAttr;\n aGrabber >> nOffset;\n\n if (aGrabber.getPosition() - nCenPos + nNameLen + nExtraLen + nCommentLen > nCenLen)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (bad header size check 2)\") ), Reference < XInterface > ());\n\n if (nNameLen > ZIP_MAXNAMELEN)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"name length exceeds 512 bytes\" ) ), Reference < XInterface > ());\n\n if (nExtraLen > ZIP_MAXEXTRA)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"extra header info exceeds 256 bytes\") ), Reference < XInterface > ());\n\n pEntry->nTime = nTime;\n pEntry->nCrc = nCRC;\n pEntry->nSize = nSize;\n pEntry->nCompressedSize = nCompressedSize;\n pEntry->nMethod = nHow;\n pEntry->nFlag = nFlag;\n pEntry->nVersion= nVersion;\n pEntry->nOffset = nOffset + nLocPos;\n\n pEntry->nOffset *= -1;\n \/*\n if (nHow == STORED)\n pEntry->nCompressedSize = 0;\n *\/\n Sequence < sal_Int8> aSequence (nNameLen);\n aGrabber.readBytes(aSequence, nNameLen);\n pEntry->sName = OUString((sal_Char*)aSequence.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US);\n\n aGrabber.seek(aGrabber.getPosition() + nExtraLen);\n if (nCommentLen>0)\n {\n Sequence < sal_Int8 > aCommentSeq( nCommentLen );\n aGrabber.readBytes(aCommentSeq, nCommentLen);\n pEntry->sComment = OUString((sal_Char*)aCommentSeq.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US);\n }\n aEntries[pEntry->sName] = *pEntry;\n }\n delete pEntry;\n\n if (nCount != nTotal)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Count != Total\") ), Reference < XInterface > ());\n\n return nCenPos;\n}\n<commit_msg>#88256# If we have a potentially corrupt file, just assert and then keep going<commit_after>\/*************************************************************************\n *\n * $RCSfile: ZipFile.cxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: mtg $ $Date: 2001-06-14 17:36:15 $\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): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_FILE_HXX\n#include <ZipFile.hxx>\n#endif\n#ifndef _ENTRY_INPUT_STREAM_HXX\n#include <EntryInputStream.hxx>\n#endif\n#ifndef _ZIP_ENUMERATION_HXX\n#include <ZipEnumeration.hxx>\n#endif\n#ifndef _VOS_DIAGNOSE_H_\n#include <vos\/diagnose.hxx>\n#endif\n#ifndef _COM_SUN_STAR_PACKAGES_ZIPCONSTANTS_HPP_\n#include <com\/sun\/star\/packages\/ZipConstants.hpp>\n#endif\n#include <vector>\n\n\nusing namespace rtl;\nusing namespace com::sun::star;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::packages;\nusing namespace com::sun::star::packages::ZipConstants;\n\n\/** This class is used to read entries from a zip file\n *\/\nZipFile::ZipFile( Reference < io::XInputStream > &xInput, sal_Bool bInitialise)\n throw(io::IOException, ZipException, RuntimeException)\n: xStream(xInput)\n, aGrabber(xInput)\n, aInflater (sal_True)\n{\n if (bInitialise)\n readCEN();\n}\nvoid ZipFile::setInputStream ( Reference < io::XInputStream > xNewStream )\n{\n xStream = xNewStream;\n aGrabber.setInputStream ( xStream );\n}\n\nZipFile::~ZipFile()\n{\n aEntries.clear();\n}\n\nvoid SAL_CALL ZipFile::close( )\n throw(io::IOException, RuntimeException)\n{\n}\n\nZipEnumeration * SAL_CALL ZipFile::entries( )\n{\n return new ZipEnumeration ( aEntries );\n}\n\n::rtl::OUString SAL_CALL ZipFile::getName( )\n throw(RuntimeException)\n{\n return sName;\n}\n\nsal_Int32 SAL_CALL ZipFile::getSize( )\n throw(RuntimeException)\n{\n return aEntries.size();\n}\n\nType SAL_CALL ZipFile::getElementType( )\n throw(RuntimeException)\n{\n return ::getCppuType((ZipEntry *) 0);\n}\n\nsal_Bool SAL_CALL ZipFile::hasElements( )\n throw(RuntimeException)\n{\n return (aEntries.size()>0);\n}\n\nAny SAL_CALL ZipFile::getByName( const ::rtl::OUString& aName )\n throw(container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)\n{\n Any aAny;\n EntryHash::const_iterator aCI = aEntries.find(sName);\n if (aCI == aEntries.end())\n throw container::NoSuchElementException();\n aAny <<= (*aCI).second;\n return aAny;\n}\n\nSequence< ::rtl::OUString > SAL_CALL ZipFile::getElementNames( )\n throw(RuntimeException)\n{\n sal_uInt32 i=0, nSize = aEntries.size();\n OUString *pNames = new OUString[aEntries.size()];\n for (EntryHash::const_iterator aIterator = aEntries.begin(); aIterator != aEntries.end(); aIterator++,i++)\n pNames[i] = (*aIterator).first;\n return Sequence<OUString> (pNames, nSize);\n}\n\nsal_Bool SAL_CALL ZipFile::hasByName( const ::rtl::OUString& aName )\n throw(RuntimeException)\n{\n return aEntries.find(aName) != aEntries.end();\n}\n\nReference< io::XInputStream > SAL_CALL ZipFile::getInputStream( ZipEntry& rEntry,\n const vos::ORef < EncryptionData > &rData)\n throw(io::IOException, ZipException, RuntimeException)\n{\n if (rEntry.nOffset <= 0)\n readLOC(rEntry);\n Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_False );\n return xStreamRef;\n}\n\nReference< io::XInputStream > SAL_CALL ZipFile::getRawStream( ZipEntry& rEntry,\n const vos::ORef < EncryptionData > &rData)\n throw(io::IOException, ZipException, RuntimeException)\n{\n if (rEntry.nOffset <= 0)\n readLOC(rEntry);\n Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_True );\n return xStreamRef;\n}\n\nsal_Bool ZipFile::readLOC( ZipEntry &rEntry )\n throw(io::IOException, ZipException, RuntimeException)\n{\n sal_uInt32 nTestSig, nTime, nCRC, nSize, nCompressedSize;\n sal_uInt16 nVersion, nFlag, nHow, nNameLen, nExtraLen;\n sal_Int32 nPos = -rEntry.nOffset;\n\n aGrabber.seek(nPos);\n aGrabber >> nTestSig;\n\n if (nTestSig != LOCSIG)\n throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid LOC header (bad signature\") ), Reference < XInterface > () );\n aGrabber >> nVersion;\n aGrabber >> nFlag;\n aGrabber >> nHow;\n aGrabber >> nTime;\n aGrabber >> nCRC;\n aGrabber >> nCompressedSize;\n aGrabber >> nSize;\n aGrabber >> nNameLen;\n aGrabber >> nExtraLen;\n rEntry.nOffset = static_cast < sal_Int32 > (aGrabber.getPosition()) + nNameLen + nExtraLen;\n return sal_True;\n}\n\nsal_Int32 ZipFile::findEND( )\n throw(io::IOException, ZipException, RuntimeException)\n{\n sal_Int32 nLength=0, nPos=0;\n Sequence < sal_Int8 > aByteSeq;\n nLength = nPos = static_cast <sal_Int32 > (aGrabber.getLength());\n\n if (nLength == 0)\n return -1;\n \/\/throw (ZipException( OUString::createFromAscii(\"Trying to find Zip END signature in a zero length file!\"), Reference < XInterface> () ));\n\n aGrabber.seek( nLength );\n\n while (nLength - nPos < 0xFFFF)\n {\n sal_uInt32 nCount = 0xFFFF - ( nLength - nPos);\n if (nCount > ENDHDR)\n nCount = ENDHDR;\n nPos -= nCount;\n\n for (sal_uInt16 i=0; i <nCount;i++)\n {\n sal_uInt32 nTest=0, nFoo=ENDSIG;\n aGrabber.seek (nPos+i);\n aGrabber >> nTest;\n if (nTest == ENDSIG)\n {\n\n\n sal_uInt16 nCommentLength;\n sal_Int32 nEndPos = nPos + i;\n aGrabber.seek(nEndPos+ENDCOM);\n aGrabber >> nCommentLength;\n \/*\n if (nEndPos + ENDHDR + nCommentLength == nLength)\n {\n Since we don't actually use the comment ourselves, we'll just ignore it, and also skip the check\n below. Neither WinZip nor InfoZip's unzip perform such checking and happily open files with\n garbage bytes on the end, so we should do so too! I will 'assert' however that the file has garbage\n at the end, and hope that the file hasn't suffered any other abuse\n\n if (nCommentLength>0)\n {\n aByteSeq.realloc(nCommentLength+1);\n aGrabber.readBytes(Sequence< sal_Int8>(aByteSeq.getArray(), nCommentLength), nCommentLength);\n aByteSeq[nCommentLength]='\\0';\n sComment = OUString((sal_Char*)aByteSeq.getConstArray(), nCommentLength+1, RTL_TEXTENCODING_ASCII_US);\n\n }\n }\n *\/\n VOS_ENSURE ( nEndPos + ENDHDR + nCommentLength == nLength, \"This Zip File is potentially corrupt - it has garbage after the END descriptor! Hoping for the best...!\");\n return nPos + i;\n }\n }\n }\n throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Zip END signature not found!\") ), Reference < XInterface> () );\n}\n\nsal_Int32 ZipFile::readCEN()\n throw(io::IOException, ZipException, RuntimeException)\n{\n sal_Int32 nEndPos, nLocPos;\n sal_Int16 nCount, nTotal;\n sal_Int32 nCenLen, nCenPos, nCenOff;\n\n nEndPos = findEND();\n if (nEndPos == -1)\n return -1;\n aGrabber.seek(nEndPos + ENDTOT);\n aGrabber >> nTotal;\n aGrabber >> nCenLen;\n aGrabber >> nCenOff;\n\n if (nTotal<0 || nTotal * CENHDR > nCenLen)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"invalid END header (bad entry count)\") ), Reference < XInterface > ());\n\n if (nTotal > ZIP_MAXENTRIES)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"too many entries in ZIP File\") ), Reference < XInterface > ());\n\n if (nCenLen < 0 || nCenLen > nEndPos)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid END header (bad central directory size)\") ), Reference < XInterface > ());\n\n nCenPos = nEndPos - nCenLen;\n\n if (nCenOff < 0 || nCenOff > nCenPos)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid END header (bad central directory size)\") ), Reference < XInterface > ());\n\n nLocPos = nCenPos - nCenOff;\n aGrabber.seek(nCenPos);\n\n ZipEntry *pEntry = new ZipEntry;\n for (nCount = 0 ; nCount < nTotal; nCount++)\n {\n sal_Int32 nTestSig, nCRC, nCompressedSize, nTime, nSize, nExtAttr, nOffset;\n sal_Int16 nVerMade, nVersion, nFlag, nHow, nNameLen, nExtraLen, nCommentLen;\n sal_Int16 nDisk, nIntAttr;\n\n if (aGrabber.getPosition() - nCenPos + CENHDR > nCenLen)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (bad header size check 1)\") ), Reference < XInterface > ());\n\n aGrabber >> nTestSig;\n if (nTestSig != CENSIG)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (bad signature)\") ), Reference < XInterface > ());\n\n aGrabber >> nVerMade;\n aGrabber >> nVersion;\n if ((nVersion & 1) == 1)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (encrypted entry)\") ), Reference < XInterface > ());\n\n aGrabber >> nFlag;\n aGrabber >> nHow;\n if (nHow != STORED && nHow != DEFLATED)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (bad compression method)\") ), Reference < XInterface > ());\n\n aGrabber >> nTime;\n aGrabber >> nCRC;\n aGrabber >> nCompressedSize;\n aGrabber >> nSize;\n aGrabber >> nNameLen;\n aGrabber >> nExtraLen;\n aGrabber >> nCommentLen;\n aGrabber >> nDisk;\n aGrabber >> nIntAttr;\n aGrabber >> nExtAttr;\n aGrabber >> nOffset;\n\n if (aGrabber.getPosition() - nCenPos + nNameLen + nExtraLen + nCommentLen > nCenLen)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Invalid CEN header (bad header size check 2)\") ), Reference < XInterface > ());\n\n if (nNameLen > ZIP_MAXNAMELEN)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"name length exceeds 512 bytes\" ) ), Reference < XInterface > ());\n\n if (nExtraLen > ZIP_MAXEXTRA)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"extra header info exceeds 256 bytes\") ), Reference < XInterface > ());\n\n pEntry->nTime = nTime;\n pEntry->nCrc = nCRC;\n pEntry->nSize = nSize;\n pEntry->nCompressedSize = nCompressedSize;\n pEntry->nMethod = nHow;\n pEntry->nFlag = nFlag;\n pEntry->nVersion= nVersion;\n pEntry->nOffset = nOffset + nLocPos;\n\n pEntry->nOffset *= -1;\n \/*\n if (nHow == STORED)\n pEntry->nCompressedSize = 0;\n *\/\n Sequence < sal_Int8> aSequence (nNameLen);\n aGrabber.readBytes(aSequence, nNameLen);\n pEntry->sName = OUString((sal_Char*)aSequence.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US);\n\n aGrabber.seek(aGrabber.getPosition() + nExtraLen);\n if (nCommentLen>0)\n {\n Sequence < sal_Int8 > aCommentSeq( nCommentLen );\n aGrabber.readBytes(aCommentSeq, nCommentLen);\n pEntry->sComment = OUString((sal_Char*)aCommentSeq.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US);\n }\n aEntries[pEntry->sName] = *pEntry;\n }\n delete pEntry;\n\n if (nCount != nTotal)\n throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( \"Count != Total\") ), Reference < XInterface > ());\n\n return nCenPos;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ Project specific\n\/\/ This class\n#include <Manager\/EntitySpawnManager.hpp>\n\/\/ Handlers\n#include <EntityComponent\/EntityHandler.hpp>\n#include <EntityComponent\/EntityHandlerServer.hpp>\n#include <EventHandler\/EventHandler.hpp>\n#include <PlayerHandler.hpp>\n\/\/ Components\n#include <EntityComponent\/Components\/EntitySpawnerComponent.hpp>\n#include <EntityComponent\/Components\/PhysicsMaterialComponent.hpp>\n#include <EntityComponent\/Components\/RigidBodyComponent.hpp>\n#include <EntityComponent\/Components\/EntityTypeComponent.hpp>\n#include <EntityComponent\/Components\/TransformComponent.hpp>\n#include <EntityComponent\/Components\/PotentialFieldComponent.hpp>\n#include <EntityComponent\/Components\/HealthComponent.hpp>\n\/\/ Events\n#include <EventHandler\/Events\/SpecialEntityCreatedEvent.hpp>\n\n\/\/\/ Engine\n\/\/ Physics\n#include <DoremiEngine\/Physics\/Include\/PhysicsModule.hpp>\n#include <DoremiEngine\/Physics\/Include\/PhysicsMaterialManager.hpp>\n#include <DoremiEngine\/Physics\/Include\/RigidBodyManager.hpp>\n#include <DoremiEngine\/Physics\/Include\/CharacterControlManager.hpp>\n\/\/ AI\n#include <DoremiEngine\/AI\/Include\/Interface\/SubModule\/PotentialFieldSubModule.hpp>\n#include <DoremiEngine\/AI\/Include\/Interface\/PotentialField\/PotentialFieldActor.hpp>\n#include <DoremiEngine\/AI\/Include\/AIModule.hpp>\n\/\/\/ Third party\n#include <DirectXMath.h>\nusing namespace DirectX;\n\n\/\/ DEBUG\n#include <iostream>\n#include <Doremi\/Core\/Include\/EntityComponent\/Components\/RenderComponent.hpp>\nusing namespace std;\n\nnamespace Doremi\n{\n namespace Core\n {\n EntitySpawnManager::EntitySpawnManager(const DoremiEngine::Core::SharedContext& p_sharedContext)\n : Manager(p_sharedContext, \"EntitySpawnManager\")\n {\n }\n\n EntitySpawnManager::~EntitySpawnManager() {}\n\n\n void EntitySpawnManager::Update(double p_dt)\n {\n\t\t\tstatic int DEBUGcount = 0;\n EntityHandler& entityHandler = EntityHandler::GetInstance();\n \/\/ Loop through all entities\n const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();\n for(size_t i = 0; i < length; i++)\n {\n \/\/ Check that the current entity has the relevant components\n if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::EntitySpawner) | (int)ComponentType::Transform)\n {\n \/\/ We've found an entity spawner\n EntitySpawnComponent* spawnComp = EntityHandler::GetInstance().GetComponentFromStorage<EntitySpawnComponent>(i);\n \/\/ Check if its a timed spawned\n if(spawnComp->type == SpawnerType::TimedSpawner)\n {\n \/\/ Update time since last spawn\n spawnComp->timeSinceLastSpawn += p_dt;\n \/\/ Check if it's time to spawn and if we haven't already spawned the max number\n if(spawnComp->timeSinceLastSpawn >= spawnComp->timeBetweenSpawns && spawnComp->currentNumSpawnedEntities < spawnComp->maxNumSpawnedEntites)\n {\n \/\/ Hax to ensure nothing spawns when no players are active, which apparently is a no-can-do\n if(PlayerHandler::GetInstance()->GetPlayerMap().size() > 0)\n {\n \/\/ We should spawn something\n CreateEntity(spawnComp->entityBlueprint, i);\n spawnComp->currentNumSpawnedEntities++;\n }\n \/\/ Reset timer\n spawnComp->timeSinceLastSpawn = 0;\n }\n else\n {\n \/\/ Nothing\n }\n }\n else\n {\n \/\/ nothing\n }\n }\n }\n }\n\n void EntitySpawnManager::OnEvent(Event* p_event) {}\n\n void EntitySpawnManager::CreateEntity(Blueprints p_blueprint, int p_spawnerID)\n {\n EntityHandler& entityHandler = EntityHandler::GetInstance();\n switch(p_blueprint)\n {\n case Blueprints::EnemyEntity:\n TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);\n \/\/ Spawn inside the spawner. This might be changed in the future\n XMFLOAT3 spawnPosition = transComp->position;\n int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::EnemyEntity, spawnPosition);\n\n\n \/\/ TODOCONFIG HP pool for monsters\n \/\/ healthComp->maxHealth = 200;\n \/\/ healthComp->currentHealth = 200;\n\n \/\/ Send event that enemy has been created\n\n SpecialEntityCreatedEvent* AIGroupActorCreated = new Core::SpecialEntityCreatedEvent(newID, Core::EventType::AiGroupActorCreation);\n\n EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated);\n break;\n\n \/\/ case Blueprints::PlayerEntity:\n \/\/ TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);\n \/\/ \/\/ Spawn inside the spawner. This might be changed in the future\n \/\/ XMFLOAT3 spawnPosition = transComp->position;\n \/\/ int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::PlayerEntity, spawnPosition);\n\n \/\/ \/\/ Send event that enemy has been created\n \/\/ EntityCreatedEvent* PlayerCreated = new Core::EntityCreatedEvent(newID, Core::EventType::PlayerCreation);\n \/\/ EventHandler::GetInstance()->BroadcastEvent(PlayerCreated);\n \/\/ break;\n }\n }\n }\n}<commit_msg>WORK IN PROGRESS removed all AI spawned from spawners<commit_after>\/\/\/ Project specific\n\/\/ This class\n#include <Manager\/EntitySpawnManager.hpp>\n\/\/ Handlers\n#include <EntityComponent\/EntityHandler.hpp>\n#include <EntityComponent\/EntityHandlerServer.hpp>\n#include <EventHandler\/EventHandler.hpp>\n#include <PlayerHandler.hpp>\n\/\/ Components\n#include <EntityComponent\/Components\/EntitySpawnerComponent.hpp>\n#include <EntityComponent\/Components\/PhysicsMaterialComponent.hpp>\n#include <EntityComponent\/Components\/RigidBodyComponent.hpp>\n#include <EntityComponent\/Components\/EntityTypeComponent.hpp>\n#include <EntityComponent\/Components\/TransformComponent.hpp>\n#include <EntityComponent\/Components\/PotentialFieldComponent.hpp>\n#include <EntityComponent\/Components\/HealthComponent.hpp>\n\/\/ Events\n#include <EventHandler\/Events\/SpecialEntityCreatedEvent.hpp>\n\n\/\/\/ Engine\n\/\/ Physics\n#include <DoremiEngine\/Physics\/Include\/PhysicsModule.hpp>\n#include <DoremiEngine\/Physics\/Include\/PhysicsMaterialManager.hpp>\n#include <DoremiEngine\/Physics\/Include\/RigidBodyManager.hpp>\n#include <DoremiEngine\/Physics\/Include\/CharacterControlManager.hpp>\n\/\/ AI\n#include <DoremiEngine\/AI\/Include\/Interface\/SubModule\/PotentialFieldSubModule.hpp>\n#include <DoremiEngine\/AI\/Include\/Interface\/PotentialField\/PotentialFieldActor.hpp>\n#include <DoremiEngine\/AI\/Include\/AIModule.hpp>\n\/\/\/ Third party\n#include <DirectXMath.h>\nusing namespace DirectX;\n\n\/\/ DEBUG\n#include <iostream>\n#include <Doremi\/Core\/Include\/EntityComponent\/Components\/RenderComponent.hpp>\nusing namespace std;\n\nnamespace Doremi\n{\n namespace Core\n {\n EntitySpawnManager::EntitySpawnManager(const DoremiEngine::Core::SharedContext& p_sharedContext)\n : Manager(p_sharedContext, \"EntitySpawnManager\")\n {\n }\n\n EntitySpawnManager::~EntitySpawnManager() {}\n\n\n void EntitySpawnManager::Update(double p_dt)\n {\n\t\t\tstatic int DEBUGcount = 0;\n EntityHandler& entityHandler = EntityHandler::GetInstance();\n \/\/ Loop through all entities\n const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();\n for(size_t i = 0; i < length; i++)\n {\n \/\/ Check that the current entity has the relevant components\n if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::EntitySpawner) | (int)ComponentType::Transform)\n {\n \/\/ We've found an entity spawner\n EntitySpawnComponent* spawnComp = EntityHandler::GetInstance().GetComponentFromStorage<EntitySpawnComponent>(i);\n \/\/ Check if its a timed spawned\n if(spawnComp->type == SpawnerType::TimedSpawner)\n {\n \/\/ Update time since last spawn\n spawnComp->timeSinceLastSpawn += p_dt;\n \/\/ Check if it's time to spawn and if we haven't already spawned the max number\n if(spawnComp->timeSinceLastSpawn >= spawnComp->timeBetweenSpawns && spawnComp->currentNumSpawnedEntities < spawnComp->maxNumSpawnedEntites)\n {\n \/\/ Hax to ensure nothing spawns when no players are active, which apparently is a no-can-do\n if(PlayerHandler::GetInstance()->GetPlayerMap().size() > 0)\n {\n \/\/ We should spawn something\n \/\/CreateEntity(spawnComp->entityBlueprint, i);\n \/\/spawnComp->currentNumSpawnedEntities++;\n }\n \/\/ Reset timer\n spawnComp->timeSinceLastSpawn = 0;\n }\n else\n {\n \/\/ Nothing\n }\n }\n else\n {\n \/\/ nothing\n }\n }\n }\n }\n\n void EntitySpawnManager::OnEvent(Event* p_event) {}\n\n void EntitySpawnManager::CreateEntity(Blueprints p_blueprint, int p_spawnerID)\n {\n EntityHandler& entityHandler = EntityHandler::GetInstance();\n switch(p_blueprint)\n {\n case Blueprints::EnemyEntity:\n TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);\n \/\/ Spawn inside the spawner. This might be changed in the future\n XMFLOAT3 spawnPosition = transComp->position;\n int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::EnemyEntity, spawnPosition);\n\n\n \/\/ TODOCONFIG HP pool for monsters\n \/\/ healthComp->maxHealth = 200;\n \/\/ healthComp->currentHealth = 200;\n\n \/\/ Send event that enemy has been created\n\n SpecialEntityCreatedEvent* AIGroupActorCreated = new Core::SpecialEntityCreatedEvent(newID, Core::EventType::AiGroupActorCreation);\n\n EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated);\n break;\n\n \/\/ case Blueprints::PlayerEntity:\n \/\/ TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);\n \/\/ \/\/ Spawn inside the spawner. This might be changed in the future\n \/\/ XMFLOAT3 spawnPosition = transComp->position;\n \/\/ int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::PlayerEntity, spawnPosition);\n\n \/\/ \/\/ Send event that enemy has been created\n \/\/ EntityCreatedEvent* PlayerCreated = new Core::EntityCreatedEvent(newID, Core::EventType::PlayerCreation);\n \/\/ EventHandler::GetInstance()->BroadcastEvent(PlayerCreated);\n \/\/ break;\n }\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\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 | 1. Redistributions of source code must retain the above copyright |\n | notice, this list of conditions and the following disclaimer. |\n | 2. 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 |\n | distribution. |\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 | Authors: David Soria Parra <dsp@php.net> |\n +----------------------------------------------------------------------+\n*\/\n\n\/* $ Id: $ *\/ \n\n#include \"php_ktaglib.h\"\n#include \"ktaglibrary.h\"\n\n#if HAVE_TAGLIB\n\n\/* {{{ Class definitions *\/\n\n\/* {{{ Class KTaglib_File *\/\nPHPAPI zend_class_entry *ktaglib_ce_FileNotFoundException;\nPHPAPI zend_class_entry *ktaglib_ce_TagNotFoundException;\n\nstatic zend_class_entry * KTaglib_File_ce_ptr = NULL;\n\nvoid ktaglib_ref_class(ze_ktaglib_object * zo, ze_ktaglib_file_object *zo_file)\n{\n\tzo->zo_file = zo_file;\n\tzo_file->refcount++;\n}\n\n\/* Exceptions *\/\nvoid ktaglib_init_class(zend_class_entry ** ppce, zend_class_entry *pce, const char * name, zend_function_entry * functions TSRMLS_DC)\n{\n\tzend_class_entry ce;\n\n\tINIT_CLASS_ENTRY(ce, name, functions);\n\tce.name_length = strlen(name);\n\t*ppce = zend_register_internal_class_ex(&ce, pce, NULL TSRMLS_CC);\n\t(*ppce)->create_object = pce->create_object;\n}\n\nvoid ktaglib_init_KTaglib_Exceptions(void)\n{\n\tktaglib_init_class(&ktaglib_ce_FileNotFoundException, zend_exception_get_default(TSRMLS_C), \"KTaglib_FileNotFoundException\", NULL);\n\tktaglib_init_class(&ktaglib_ce_TagNotFoundException, zend_exception_get_default(TSRMLS_C), \"KTaglib_TagNotFoundException\", NULL);\n}\n\n\nvoid ktaglib_init_KTaglib_File_free(void *object TSRMLS_DC) \/* {{{ *\/\n{\n\tze_ktaglib_file_object * intern = (ze_ktaglib_file_object *) object;\n\n\tintern->refcount--;\n\tif (intern->refcount <= 0 && intern->file) {\n\t\tdelete intern->file;\n\t}\n\n\tzend_object_std_dtor(&intern->zo TSRMLS_CC);\n\tefree(intern);\n}\n\n\nvoid ktaglib_init_KTaglib_free(void *object TSRMLS_DC) \/* {{{ *\/\n{\n\tze_ktaglib_object * intern = (ze_ktaglib_object *) object;\n\n\tif (intern->zo_file) {\n\t\tintern->zo_file->refcount--;\n\t}\n\n\tzend_object_std_dtor(&intern->zo TSRMLS_CC);\n\tefree(intern);\n}\n\nzend_object_value ktaglib_init_KTaglib_File_new(zend_class_entry *class_type TSRMLS_DC) \/* {{{ *\/\n{\n\tze_ktaglib_file_object *intern;\n\tzval *tmp;\n\tzend_object_value retval;\n\n\tintern = (ze_ktaglib_file_object*) emalloc(sizeof(ze_ktaglib_file_object));\n\tmemset(&intern->zo, 0, sizeof(zend_object));\n\n\tintern->file = NULL;\n\tintern->refcount = 1;\n\n\tzend_object_std_init(&intern->zo, class_type TSRMLS_CC);\n\tzend_hash_copy(intern->zo.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref,\n\t\t\t\t\t(void *) &tmp, sizeof(zval *));\n\n\tretval.handle = zend_objects_store_put(intern,\n\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t(zend_objects_free_object_storage_t) ktaglib_init_KTaglib_File_free,\n\t\t\t\t\t\tNULL TSRMLS_CC);\n\n\tretval.handlers = zend_get_std_object_handlers();\n\n \/* Preventing object cloning is easier than creating the handlers for clone :) *\/\n retval.handlers->clone_obj = NULL;\n\treturn retval;\n\n}\n\n\nzend_object_value ktaglib_init_KTaglib_new(zend_class_entry *class_type TSRMLS_DC) \/* {{{ *\/\n{\n\tze_ktaglib_object *intern;\n\tzval *tmp;\n\tzend_object_value retval;\n\n\tintern = (ze_ktaglib_object*) emalloc(sizeof(ze_ktaglib_object));\n\tmemset(&intern->zo, 0, sizeof(zend_object));\n\n\tintern->zo_file = NULL;\n\tintern->tag = NULL;\n\tintern->frame = NULL;\n\n\tzend_object_std_init(&intern->zo, class_type TSRMLS_CC);\n\tzend_hash_copy(intern->zo.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref,\n\t\t\t\t\t(void *) &tmp, sizeof(zval *));\n\n\tretval.handle = zend_objects_store_put(intern,\n\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t(zend_objects_free_object_storage_t) ktaglib_init_KTaglib_free,\n\t\t\t\t\t\tNULL TSRMLS_CC);\n\n\tretval.handlers = zend_get_std_object_handlers();\n\tretval.handlers->clone_obj = NULL;\n\treturn retval;\n\n}\n\n\/* }}} Methods *\/\n\/* }}} Class KTaglib *\/\n\n\n\/* {{{ ktaglib_functions[] *\/\nfunction_entry ktaglib_functions[] = {\n\t{ NULL, NULL, NULL }\n};\n\/* }}} *\/\n\n\n\/* {{{ ktaglib_module_entry\n *\/\nzend_module_entry ktaglib_module_entry = {\n\tSTANDARD_MODULE_HEADER,\n\t\"ktaglib\",\n\tktaglib_functions,\n\tPHP_MINIT(ktaglib), \/* Replace with NULL if there is nothing to do at php startup *\/ \n\tPHP_MSHUTDOWN(ktaglib), \/* Replace with NULL if there is nothing to do at php shutdown *\/\n\tPHP_RINIT(ktaglib), \/* Replace with NULL if there is nothing to do at request start *\/\n\tPHP_RSHUTDOWN(ktaglib), \/* Replace with NULL if there is nothing to do at request end *\/\n\tPHP_MINFO(ktaglib),\n\tPHP_KTAGLIB_VERSION,\n\tSTANDARD_MODULE_PROPERTIES\n};\n\/* }}} *\/\n\n#ifdef COMPILE_DL_KTAGLIB\nextern \"C\" {\nZEND_GET_MODULE(ktaglib)\n} \/\/ extern \"C\"\n#endif\n\n\n\/* {{{ PHP_MINIT_FUNCTION *\/\nPHP_MINIT_FUNCTION(ktaglib)\n{\n\tktaglib_init_KTaglib_Exceptions();\n\tktaglib_init_KTaglib_MPEG_File();\n\tktaglib_init_KTaglib_Tag();\n\tktaglib_init_KTaglib_ID3v1_Tag();\n\tktaglib_init_KTaglib_ID3v2_Tag();\n\tktaglib_init_KTaglib_ID3v2_Frame();\n\tktaglib_init_KTaglib_ID3v2_PictureFrame();\n\tktaglib_init_KTaglib_ID3v2_CommentsFrame();\n\tktaglib_init_KTaglib_MPEG_AudioProperties();\n\tktaglib_init_KTaglib_MPEG_Header();\n\n\treturn SUCCESS;\n}\n\/* }}} *\/\n\n\n\/* {{{ PHP_MSHUTDOWN_FUNCTION *\/\nPHP_MSHUTDOWN_FUNCTION(ktaglib)\n{\n\treturn SUCCESS;\n}\n\/* }}} *\/\n\n\n\/* {{{ PHP_RINIT_FUNCTION *\/\nPHP_RINIT_FUNCTION(ktaglib)\n{\n\treturn SUCCESS;\n}\n\/* }}} *\/\n\n\n\/* {{{ PHP_RSHUTDOWN_FUNCTION *\/\nPHP_RSHUTDOWN_FUNCTION(ktaglib)\n{\n\treturn SUCCESS;\n}\n\/* }}} *\/\n\n\n\/* {{{ PHP_MINFO_FUNCTION *\/\nPHP_MINFO_FUNCTION(ktaglib)\n{\n\tchar version[5];\n\n\tsprintf(version, \"%1d.%1d.%1d\", \n\t\t\tTAGLIB_MAJOR_VERSION, TAGLIB_MINOR_VERSION, TAGLIB_PATCH_VERSION);\n\n\tphp_info_print_table_start();\n\tphp_info_print_table_row(2, \"ktaglib Support\", \"enabled\");\n\tphp_info_print_table_row(2, \"taglib Version\", version);\n\tphp_info_print_table_row(2, \"Supported Formats\", \"ID3v1, ID3v2\");\n\tphp_info_print_table_row(2, \"Version\", PHP_KTAGLIB_VERSION);\n\tphp_info_print_table_end();\n\n}\n\/* }}} *\/\n\n#endif \/* HAVE_TAGLIB *\/\n\n\n\/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: noet sw=4 ts=4 fdm=marker\n * vim<600: noet sw=4 ts=4\n *\/\n<commit_msg>Coding style<commit_after>\/*\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 | 1. Redistributions of source code must retain the above copyright |\n | notice, this list of conditions and the following disclaimer. |\n | 2. 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 |\n | distribution. |\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 | Authors: David Soria Parra <dsp@php.net> |\n +----------------------------------------------------------------------+\n*\/\n\n\/* $ Id: $ *\/ \n\n#include \"php_ktaglib.h\"\n#include \"ktaglibrary.h\"\n\n#if HAVE_TAGLIB\n\n\/* {{{ Class definitions *\/\n\n\/* {{{ Class KTaglib_File *\/\nPHPAPI zend_class_entry *ktaglib_ce_FileNotFoundException;\nPHPAPI zend_class_entry *ktaglib_ce_TagNotFoundException;\n\nstatic zend_class_entry * KTaglib_File_ce_ptr = NULL;\n\nvoid ktaglib_ref_class(ze_ktaglib_object * zo, ze_ktaglib_file_object *zo_file)\n{\n\tzo->zo_file = zo_file;\n\tzo_file->refcount++;\n}\n\n\/* Exceptions *\/\nvoid ktaglib_init_class(zend_class_entry ** ppce, zend_class_entry *pce, const char * name, zend_function_entry * functions TSRMLS_DC)\n{\n\tzend_class_entry ce;\n\n\tINIT_CLASS_ENTRY(ce, name, functions);\n\tce.name_length = strlen(name);\n\t*ppce = zend_register_internal_class_ex(&ce, pce, NULL TSRMLS_CC);\n\t(*ppce)->create_object = pce->create_object;\n}\n\nvoid ktaglib_init_KTaglib_Exceptions(void)\n{\n\tktaglib_init_class(&ktaglib_ce_FileNotFoundException, zend_exception_get_default(TSRMLS_C), \"KTaglib_FileNotFoundException\", NULL);\n\tktaglib_init_class(&ktaglib_ce_TagNotFoundException, zend_exception_get_default(TSRMLS_C), \"KTaglib_TagNotFoundException\", NULL);\n}\n\n\nvoid ktaglib_init_KTaglib_File_free(void *object TSRMLS_DC) \/* {{{ *\/\n{\n\tze_ktaglib_file_object * intern = (ze_ktaglib_file_object *) object;\n\n\tintern->refcount--;\n\tif (intern->refcount <= 0 && intern->file) {\n\t\tdelete intern->file;\n\t}\n\n\tzend_object_std_dtor(&intern->zo TSRMLS_CC);\n\tefree(intern);\n}\n\n\nvoid ktaglib_init_KTaglib_free(void *object TSRMLS_DC) \/* {{{ *\/\n{\n\tze_ktaglib_object * intern = (ze_ktaglib_object *) object;\n\n\tif (intern->zo_file) {\n\t\tintern->zo_file->refcount--;\n\t}\n\n\tzend_object_std_dtor(&intern->zo TSRMLS_CC);\n\tefree(intern);\n}\n\nzend_object_value ktaglib_init_KTaglib_File_new(zend_class_entry *class_type TSRMLS_DC) \/* {{{ *\/\n{\n\tze_ktaglib_file_object *intern;\n\tzval *tmp;\n\tzend_object_value retval;\n\n\tintern = (ze_ktaglib_file_object*) emalloc(sizeof(ze_ktaglib_file_object));\n\tmemset(&intern->zo, 0, sizeof(zend_object));\n\n\tintern->file = NULL;\n\tintern->refcount = 1;\n\n\tzend_object_std_init(&intern->zo, class_type TSRMLS_CC);\n\tzend_hash_copy(intern->zo.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref,\n\t\t\t\t\t(void *) &tmp, sizeof(zval *));\n\n\tretval.handle = zend_objects_store_put(intern,\n\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t(zend_objects_free_object_storage_t) ktaglib_init_KTaglib_File_free,\n\t\t\t\t\t\tNULL TSRMLS_CC);\n\n\tretval.handlers = zend_get_std_object_handlers();\n\n\t\/* Preventing object cloning is easier than creating the handlers for clone :) *\/\n\tretval.handlers->clone_obj = NULL;\n\n\treturn retval;\n\n}\n\n\nzend_object_value ktaglib_init_KTaglib_new(zend_class_entry *class_type TSRMLS_DC) \/* {{{ *\/\n{\n\tze_ktaglib_object *intern;\n\tzval *tmp;\n\tzend_object_value retval;\n\n\tintern = (ze_ktaglib_object*) emalloc(sizeof(ze_ktaglib_object));\n\tmemset(&intern->zo, 0, sizeof(zend_object));\n\n\tintern->zo_file = NULL;\n\tintern->tag = NULL;\n\tintern->frame = NULL;\n\n\tzend_object_std_init(&intern->zo, class_type TSRMLS_CC);\n\tzend_hash_copy(intern->zo.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref,\n\t\t\t\t\t(void *) &tmp, sizeof(zval *));\n\n\tretval.handle = zend_objects_store_put(intern,\n\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t(zend_objects_free_object_storage_t) ktaglib_init_KTaglib_free,\n\t\t\t\t\t\tNULL TSRMLS_CC);\n\n\tretval.handlers = zend_get_std_object_handlers();\n\tretval.handlers->clone_obj = NULL;\n\treturn retval;\n\n}\n\n\/* }}} Methods *\/\n\/* }}} Class KTaglib *\/\n\n\n\/* {{{ ktaglib_functions[] *\/\nfunction_entry ktaglib_functions[] = {\n\t{ NULL, NULL, NULL }\n};\n\/* }}} *\/\n\n\n\/* {{{ ktaglib_module_entry\n *\/\nzend_module_entry ktaglib_module_entry = {\n\tSTANDARD_MODULE_HEADER,\n\t\"ktaglib\",\n\tktaglib_functions,\n\tPHP_MINIT(ktaglib), \/* Replace with NULL if there is nothing to do at php startup *\/ \n\tPHP_MSHUTDOWN(ktaglib), \/* Replace with NULL if there is nothing to do at php shutdown *\/\n\tPHP_RINIT(ktaglib), \/* Replace with NULL if there is nothing to do at request start *\/\n\tPHP_RSHUTDOWN(ktaglib), \/* Replace with NULL if there is nothing to do at request end *\/\n\tPHP_MINFO(ktaglib),\n\tPHP_KTAGLIB_VERSION,\n\tSTANDARD_MODULE_PROPERTIES\n};\n\/* }}} *\/\n\n#ifdef COMPILE_DL_KTAGLIB\nextern \"C\" {\nZEND_GET_MODULE(ktaglib)\n} \/\/ extern \"C\"\n#endif\n\n\n\/* {{{ PHP_MINIT_FUNCTION *\/\nPHP_MINIT_FUNCTION(ktaglib)\n{\n\tktaglib_init_KTaglib_Exceptions();\n\tktaglib_init_KTaglib_MPEG_File();\n\tktaglib_init_KTaglib_Tag();\n\tktaglib_init_KTaglib_ID3v1_Tag();\n\tktaglib_init_KTaglib_ID3v2_Tag();\n\tktaglib_init_KTaglib_ID3v2_Frame();\n\tktaglib_init_KTaglib_ID3v2_PictureFrame();\n\tktaglib_init_KTaglib_ID3v2_CommentsFrame();\n\tktaglib_init_KTaglib_MPEG_AudioProperties();\n\tktaglib_init_KTaglib_MPEG_Header();\n\n\treturn SUCCESS;\n}\n\/* }}} *\/\n\n\n\/* {{{ PHP_MSHUTDOWN_FUNCTION *\/\nPHP_MSHUTDOWN_FUNCTION(ktaglib)\n{\n\treturn SUCCESS;\n}\n\/* }}} *\/\n\n\n\/* {{{ PHP_RINIT_FUNCTION *\/\nPHP_RINIT_FUNCTION(ktaglib)\n{\n\treturn SUCCESS;\n}\n\/* }}} *\/\n\n\n\/* {{{ PHP_RSHUTDOWN_FUNCTION *\/\nPHP_RSHUTDOWN_FUNCTION(ktaglib)\n{\n\treturn SUCCESS;\n}\n\/* }}} *\/\n\n\n\/* {{{ PHP_MINFO_FUNCTION *\/\nPHP_MINFO_FUNCTION(ktaglib)\n{\n\tchar version[5];\n\n\tsprintf(version, \"%1d.%1d.%1d\", \n\t\t\tTAGLIB_MAJOR_VERSION, TAGLIB_MINOR_VERSION, TAGLIB_PATCH_VERSION);\n\n\tphp_info_print_table_start();\n\tphp_info_print_table_row(2, \"ktaglib Support\", \"enabled\");\n\tphp_info_print_table_row(2, \"taglib Version\", version);\n\tphp_info_print_table_row(2, \"Supported Formats\", \"ID3v1, ID3v2\");\n\tphp_info_print_table_row(2, \"Version\", PHP_KTAGLIB_VERSION);\n\tphp_info_print_table_end();\n\n}\n\/* }}} *\/\n\n#endif \/* HAVE_TAGLIB *\/\n\n\n\/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: noet sw=4 ts=4 fdm=marker\n * vim<600: noet sw=4 ts=4\n *\/\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <mutex>\n#include <condition_variable>\n#include \"protocol.h\"\n#include \"verbose.h\"\n#include \"RF33_adapter.hpp\"\n\n\/\/ RFSwitch library only accepts C function pointer.\nstatic std::mutex m;\nstatic std::condition_variable cv;\n\nvoid transmissionHandler() {\n \/\/ A signal is being received, wake up program\n cv.notify_all();\n}\n\nint RF33Adapter::init(int pin) {\n \/\/ Init wiring PI\n if(wiringPiSetupSys() == -1) {\n std::cerr << \"wiringPiSetup failed, exiting...\" << std::endl;\n return 1;\n }\n \/\/ Init RF Switch\n \/\/ if (pulseLength != 0) _rfSwitch.setPulseLength(pulseLength);\n _rfSwitch.enableReceive(pin);\n _rfSwitch.registerCustomInterruptHandler(transmissionHandler);\n return 0;\n}\n\nint RF33Adapter::receiveMessage(std::function<void(const packet_s &)> callback) {\n bool receiving_first = true;\n uint64_t previous_value = 0;\n uint64_t value = 0;\n uint64_t count = 0;\n packet_t raw_packet = 0;\n VERBOSE(std::cout << \"listening...\" << std::endl);\n while(1) {\n std::unique_lock<std::mutex> lk(m);\n cv.wait(lk);\n\n if (_rfSwitch.available()) {\n value = _rfSwitch.getReceivedValue();\n \/\/ std::cout << value << std::endl;\n _rfSwitch.resetAvailable();\n count++;\n VERBOSE(std::cout << \"value received (\" << count << \"): \" << value << std::endl);\n if (value == previous_value)\n continue; \/\/ If we receive the same value, this is just a repeat\n previous_value = value;\n raw_packet |= value;\n \/\/ If we are receiving the first part of the packet, shift the value by\n \/\/ 32 to let room for the second half\n if (receiving_first) {\n raw_packet <<= 32;\n receiving_first = false;\n } else {\n \/\/ We received the second part, process it\n packet_s packet;\n int ret = read_packet(raw_packet, &packet);\n if (ret == WRONG_MAGIC_ERROR) {\n std::cout << \"DEBUG: Wrong magic number, dismiss message\" << std::endl;\n continue;\n } else if (ret == PARITY_ERROR) {\n std::cerr << \"ERROR: Parity error in message, tread lightly\" << std::endl;\n }\n callback(packet);\n receiving_first = true;\n raw_packet = 0;\n value = 0;\n }\n }\n }\n\n}\n\n<commit_msg>Use new one word protocol.<commit_after>#include <iostream>\n#include <mutex>\n#include <condition_variable>\n#include \"protocol.h\"\n#include \"verbose.h\"\n#include \"RF33_adapter.hpp\"\n\n\/\/ RFSwitch library only accepts C function pointer.\nstatic std::mutex m;\nstatic std::condition_variable cv;\n\nvoid transmissionHandler() {\n \/\/ A signal is being received, wake up program\n cv.notify_all();\n}\n\nint RF33Adapter::init(int pin) {\n \/\/ Init wiring PI\n if(wiringPiSetupSys() == -1) {\n std::cerr << \"wiringPiSetup failed, exiting...\" << std::endl;\n return 1;\n }\n \/\/ Init RF Switch\n \/\/ if (pulseLength != 0) _rfSwitch.setPulseLength(pulseLength);\n _rfSwitch.enableReceive(pin);\n _rfSwitch.registerCustomInterruptHandler(transmissionHandler);\n return 0;\n}\n\nint RF33Adapter::receiveMessage(std::function<void(const packet_s &)> callback) {\n bool receiving_first = true;\n packet_t value = 0;\n packet_t previous_value = 0;\n uint64_t count = 0;\n VERBOSE(std::cout << \"listening...\" << std::endl);\n while(1) {\n std::unique_lock<std::mutex> lk(m);\n cv.wait(lk);\n\n if (_rfSwitch.available()) {\n value = _rfSwitch.getReceivedValue();\n \/\/ std::cout << value << std::endl;\n _rfSwitch.resetAvailable();\n count++;\n VERBOSE(std::cout << \"value received (\" << count << \"): \" << value << std::endl);\n if (value == previous_value)\n continue; \/\/ If we receive the same value, this is just a repeat\n previous_value = value;\n \/\/ Now unpack it\n packet_s packet;\n int ret = read_packet(value, &packet);\n if (ret == WRONG_MAGIC_ERROR) {\n std::cout << \"DEBUG: Wrong magic number, dismiss message\" << std::endl;\n continue;\n } else if (ret == PARITY_ERROR) {\n std::cerr << \"ERROR: Parity error in message, tread lightly\" << std::endl;\n }\n callback(packet);\n value = 0;\n }\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n\n#include \"Flow.hpp\"\n\nFlow::Flow(ContentElement* content, PonUser destination, SimTime eta,\n uint chunkId, FlowType flowType, PonUser source) {\n this->source = source;\n this->destination = destination;\n this->content = content;\n this->eta = eta;\n this->bandwidth = 0;\n this->sizeDownloaded = 0;\n this->start = INF_TIME;\n this->lastUpdate = start;\n this->P2PFlow = true;\n this->flowType = flowType;\n this->chunkId = chunkId;\n}\n\nFlow::~Flow() {\n content = nullptr;\n}\n\n\/\/ debug method\nstd::string Flow::toString() const {\n std::stringstream ss;\n ss << \"s\" << this->getSource().first << \"d\" << this->getDestination().first <<\n \", c\" << this->getContent()->getName() << \":\" << this->getChunkId() <<\n \", t:\" << this->getStart() << \"-\" << this->getEta() << \"; dl \"\n << this->getSizeDownloaded() << \" @\" << this->lastUpdate\n << \", bw:\" << this->getBandwidth() << \", type: \" \n << (int) this->getFlowType();\n return ss.str(); \n}\n\nvoid Flow::updateSizeDownloaded(SimTime now) {\n if (now > this->lastUpdate)\n this->sizeDownloaded += ((now - this->lastUpdate) * this->bandwidth);\n if (this->sizeDownloaded > this->getChunkSize()) {\n \/* This is inevitable due to approximations and having a discrete time scale\n *\/\n this->sizeDownloaded = this->getChunkSize();\n }\n this->setLastUpdate(now);\n}<commit_msg>First batch of Doxygen documentation added.<commit_after>#include <sstream>\n\n#include \"Flow.hpp\"\n\nFlow::Flow(ContentElement* content, PonUser destination, SimTime eta,\n uint chunkId, FlowType flowType, PonUser source) {\n this->source = source;\n this->destination = destination;\n this->content = content;\n this->eta = eta;\n this->bandwidth = 0;\n this->sizeDownloaded = 0;\n this->start = INF_TIME;\n this->lastUpdate = start;\n this->P2PFlow = true;\n this->flowType = flowType;\n this->chunkId = chunkId;\n}\n\nFlow::~Flow() {\n content = nullptr;\n}\n\n\/**\n * @deprecated Debug method, no longer used.\n * @return A string with a concatation of some of the interal fields of the class.\n *\/\nstd::string Flow::toString() const {\n std::stringstream ss;\n ss << \"s\" << this->getSource().first << \"d\" << this->getDestination().first <<\n \", c\" << this->getContent()->getName() << \":\" << this->getChunkId() <<\n \", t:\" << this->getStart() << \"-\" << this->getEta() << \"; dl \"\n << this->getSizeDownloaded() << \" @\" << this->lastUpdate\n << \", bw:\" << this->getBandwidth() << \", type: \" \n << (int) this->getFlowType();\n return ss.str(); \n}\n\n\/**\n * Updates Flow::sizeDownloaded by taking the previous value and adding to it\n * the Capacity that has been downloaded with the current Flow::bandwidth\n * between Flow::lastUpdate and now. \n * @param now current SimTime.\n *\/\nvoid Flow::updateSizeDownloaded(SimTime now) {\n if (now > this->lastUpdate)\n this->sizeDownloaded += ((now - this->lastUpdate) * this->bandwidth);\n if (this->sizeDownloaded > this->getChunkSize()) {\n \/* This is inevitable due to approximations and having a discrete time scale\n *\/\n this->sizeDownloaded = this->getChunkSize();\n }\n this->setLastUpdate(now);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 the V8 project 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 \"src\/base\/division-by-constant.h\"\n\n#include <stdint.h>\n\n#include \"src\/base\/logging.h\"\n#include \"src\/base\/macros.h\"\n\nnamespace v8 {\nnamespace base {\n\ntemplate <class T>\nbool MagicNumbersForDivision<T>::operator==(\n const MagicNumbersForDivision& rhs) const {\n return multiplier == rhs.multiplier && shift == rhs.shift && add == rhs.add;\n}\n\n\ntemplate <class T>\nMagicNumbersForDivision<T> SignedDivisionByConstant(T d) {\n STATIC_ASSERT(static_cast<T>(0) < static_cast<T>(-1));\n DCHECK(d != static_cast<T>(-1) && d != 0 && d != 1);\n const unsigned bits = static_cast<unsigned>(sizeof(T)) * 8;\n const T min = (static_cast<T>(1) << (bits - 1));\n const bool neg = (min & d) != 0;\n const T ad = neg ? (0 - d) : d;\n const T t = min + (d >> (bits - 1));\n const T anc = t - 1 - t % ad; \/\/ Absolute value of nc\n unsigned p = bits - 1; \/\/ Init. p.\n T q1 = min \/ anc; \/\/ Init. q1 = 2**p\/|nc|.\n T r1 = min - q1 * anc; \/\/ Init. r1 = rem(2**p, |nc|).\n T q2 = min \/ ad; \/\/ Init. q2 = 2**p\/|d|.\n T r2 = min - q2 * ad; \/\/ Init. r2 = rem(2**p, |d|).\n T delta;\n do {\n p = p + 1;\n q1 = 2 * q1; \/\/ Update q1 = 2**p\/|nc|.\n r1 = 2 * r1; \/\/ Update r1 = rem(2**p, |nc|).\n if (r1 >= anc) { \/\/ Must be an unsigned comparison here.\n q1 = q1 + 1;\n r1 = r1 - anc;\n }\n q2 = 2 * q2; \/\/ Update q2 = 2**p\/|d|.\n r2 = 2 * r2; \/\/ Update r2 = rem(2**p, |d|).\n if (r2 >= ad) { \/\/ Must be an unsigned comparison here.\n q2 = q2 + 1;\n r2 = r2 - ad;\n }\n delta = ad - r2;\n } while (q1 < delta || (q1 == delta && r1 == 0));\n T mul = q2 + 1;\n return {neg ? (0 - mul) : mul, p - bits, false};\n}\n\n\ntemplate <class T>\nMagicNumbersForDivision<T> UnsignedDivisionByConstant(T d,\n unsigned leading_zeros) {\n STATIC_ASSERT(static_cast<T>(0) < static_cast<T>(-1));\n DCHECK(d != 0);\n const unsigned bits = static_cast<unsigned>(sizeof(T)) * 8;\n const T ones = ~static_cast<T>(0) >> leading_zeros;\n const T min = static_cast<T>(1) << (bits - 1);\n const T max = ~static_cast<T>(0) >> 1;\n const T nc = ones - (ones - d) % d;\n bool a = false; \/\/ Init. \"add\" indicator.\n unsigned p = bits - 1; \/\/ Init. p.\n T q1 = min \/ nc; \/\/ Init. q1 = 2**p\/nc\n T r1 = min - q1 * nc; \/\/ Init. r1 = rem(2**p,nc)\n T q2 = max \/ d; \/\/ Init. q2 = (2**p - 1)\/d.\n T r2 = max - q2 * d; \/\/ Init. r2 = rem(2**p - 1, d).\n T delta;\n do {\n p = p + 1;\n if (r1 >= nc - r1) {\n q1 = 2 * q1 + 1;\n r1 = 2 * r1 - nc;\n } else {\n q1 = 2 * q1;\n r1 = 2 * r1;\n }\n if (r2 + 1 >= d - r2) {\n if (q2 >= max) a = true;\n q2 = 2 * q2 + 1;\n r2 = 2 * r2 + 1 - d;\n } else {\n if (q2 >= min) a = true;\n q2 = 2 * q2;\n r2 = 2 * r2 + 1;\n }\n delta = d - 1 - r2;\n } while (p < bits * 2 && (q1 < delta || (q1 == delta && r1 == 0)));\n return {q2 + 1, p - bits, a};\n}\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Instantiations.\n\ntemplate struct MagicNumbersForDivision<uint32_t>;\ntemplate struct MagicNumbersForDivision<uint64_t>;\n\ntemplate MagicNumbersForDivision<uint32_t> SignedDivisionByConstant(uint32_t d);\ntemplate MagicNumbersForDivision<uint64_t> SignedDivisionByConstant(uint64_t d);\n\ntemplate MagicNumbersForDivision<uint32_t> UnsignedDivisionByConstant(\n uint32_t d, unsigned leading_zeros);\ntemplate MagicNumbersForDivision<uint64_t> UnsignedDivisionByConstant(\n uint64_t d, unsigned leading_zeros);\n\n} \/\/ namespace base\n} \/\/ namespace v8\n<commit_msg>Fixed compilation with older clang versions.<commit_after>\/\/ Copyright 2014 the V8 project 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 \"src\/base\/division-by-constant.h\"\n\n#include <stdint.h>\n\n#include \"src\/base\/logging.h\"\n#include \"src\/base\/macros.h\"\n\nnamespace v8 {\nnamespace base {\n\ntemplate <class T>\nbool MagicNumbersForDivision<T>::operator==(\n const MagicNumbersForDivision& rhs) const {\n return multiplier == rhs.multiplier && shift == rhs.shift && add == rhs.add;\n}\n\n\ntemplate <class T>\nMagicNumbersForDivision<T> SignedDivisionByConstant(T d) {\n STATIC_ASSERT(static_cast<T>(0) < static_cast<T>(-1));\n DCHECK(d != static_cast<T>(-1) && d != 0 && d != 1);\n const unsigned bits = static_cast<unsigned>(sizeof(T)) * 8;\n const T min = (static_cast<T>(1) << (bits - 1));\n const bool neg = (min & d) != 0;\n const T ad = neg ? (0 - d) : d;\n const T t = min + (d >> (bits - 1));\n const T anc = t - 1 - t % ad; \/\/ Absolute value of nc\n unsigned p = bits - 1; \/\/ Init. p.\n T q1 = min \/ anc; \/\/ Init. q1 = 2**p\/|nc|.\n T r1 = min - q1 * anc; \/\/ Init. r1 = rem(2**p, |nc|).\n T q2 = min \/ ad; \/\/ Init. q2 = 2**p\/|d|.\n T r2 = min - q2 * ad; \/\/ Init. r2 = rem(2**p, |d|).\n T delta;\n do {\n p = p + 1;\n q1 = 2 * q1; \/\/ Update q1 = 2**p\/|nc|.\n r1 = 2 * r1; \/\/ Update r1 = rem(2**p, |nc|).\n if (r1 >= anc) { \/\/ Must be an unsigned comparison here.\n q1 = q1 + 1;\n r1 = r1 - anc;\n }\n q2 = 2 * q2; \/\/ Update q2 = 2**p\/|d|.\n r2 = 2 * r2; \/\/ Update r2 = rem(2**p, |d|).\n if (r2 >= ad) { \/\/ Must be an unsigned comparison here.\n q2 = q2 + 1;\n r2 = r2 - ad;\n }\n delta = ad - r2;\n } while (q1 < delta || (q1 == delta && r1 == 0));\n T mul = q2 + 1;\n return MagicNumbersForDivision<T>(neg ? (0 - mul) : mul, p - bits, false);\n}\n\n\ntemplate <class T>\nMagicNumbersForDivision<T> UnsignedDivisionByConstant(T d,\n unsigned leading_zeros) {\n STATIC_ASSERT(static_cast<T>(0) < static_cast<T>(-1));\n DCHECK(d != 0);\n const unsigned bits = static_cast<unsigned>(sizeof(T)) * 8;\n const T ones = ~static_cast<T>(0) >> leading_zeros;\n const T min = static_cast<T>(1) << (bits - 1);\n const T max = ~static_cast<T>(0) >> 1;\n const T nc = ones - (ones - d) % d;\n bool a = false; \/\/ Init. \"add\" indicator.\n unsigned p = bits - 1; \/\/ Init. p.\n T q1 = min \/ nc; \/\/ Init. q1 = 2**p\/nc\n T r1 = min - q1 * nc; \/\/ Init. r1 = rem(2**p,nc)\n T q2 = max \/ d; \/\/ Init. q2 = (2**p - 1)\/d.\n T r2 = max - q2 * d; \/\/ Init. r2 = rem(2**p - 1, d).\n T delta;\n do {\n p = p + 1;\n if (r1 >= nc - r1) {\n q1 = 2 * q1 + 1;\n r1 = 2 * r1 - nc;\n } else {\n q1 = 2 * q1;\n r1 = 2 * r1;\n }\n if (r2 + 1 >= d - r2) {\n if (q2 >= max) a = true;\n q2 = 2 * q2 + 1;\n r2 = 2 * r2 + 1 - d;\n } else {\n if (q2 >= min) a = true;\n q2 = 2 * q2;\n r2 = 2 * r2 + 1;\n }\n delta = d - 1 - r2;\n } while (p < bits * 2 && (q1 < delta || (q1 == delta && r1 == 0)));\n return MagicNumbersForDivision<T>(q2 + 1, p - bits, a);\n}\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Instantiations.\n\ntemplate struct MagicNumbersForDivision<uint32_t>;\ntemplate struct MagicNumbersForDivision<uint64_t>;\n\ntemplate MagicNumbersForDivision<uint32_t> SignedDivisionByConstant(uint32_t d);\ntemplate MagicNumbersForDivision<uint64_t> SignedDivisionByConstant(uint64_t d);\n\ntemplate MagicNumbersForDivision<uint32_t> UnsignedDivisionByConstant(\n uint32_t d, unsigned leading_zeros);\ntemplate MagicNumbersForDivision<uint64_t> UnsignedDivisionByConstant(\n uint64_t d, unsigned leading_zeros);\n\n} \/\/ namespace base\n} \/\/ namespace v8\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Robarts Visualization Toolkit\n\nCopyright (c) John Stuart Haberl Baxter, Robarts Research Institute\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkBMPReader.h\"\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDirectedAcyclicGraphMaxFlowSegmentation.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkImageCast.h\"\n#include \"vtkImageData.h\"\n#include \"vtkImageExtractComponents.h\"\n#include \"vtkMetaImageWriter.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkRootedDirectedAcyclicGraph.h\"\n#include \"vtkRootedDirectedAcyclicGraphBackwardIterator.h\"\n#include \"vtkRootedDirectedAcyclicGraphForwardIterator.h\"\n#include \"vtkRootedDirectedAcyclicGraphIterator.h\"\n#include \"vtksys\/CommandLineArguments.hxx\"\n#include \"vtksys\/SystemTools.hxx\"\n#include <iostream>\n#include <vtkSmartPointer.h>\n#include <vtkVersion.h>\n\nint main(int argc, char** argv)\n{\n \/\/ Check command line arguments.\n bool printHelp(false);\n std::string outputDirectory;\n\n vtksys::CommandLineArguments args;\n args.Initialize( argc, argv );\n\n args.AddArgument(\"--help\", vtksys::CommandLineArguments::NO_ARGUMENT, &printHelp, \"Print this help.\");\n args.AddArgument( \"--output-dir\", vtksys::CommandLineArguments::EQUAL_ARGUMENT, &outputDirectory, \"Name of the output directory.\" );\n\n if ( !args.Parse() )\n {\n std::cerr << \"Problem parsing arguments.\" << std::endl;\n std::cout << \"Help: \" << args.GetHelp() << std::endl;\n exit(EXIT_FAILURE);\n }\n\n if ( printHelp )\n {\n std::cout << args.GetHelp() << std::endl;\n exit(EXIT_SUCCESS);\n }\n\n if( !vtksys::SystemTools::FileExists(outputDirectory.c_str(), false) && !vtksys::SystemTools::MakeDirectory(outputDirectory) )\n {\n std::cerr << \"Output directory doesn't exist and can't be created.\" << std::endl;\n }\n\n vtkSmartPointer<vtkMutableDirectedGraph> mut = vtkSmartPointer<vtkMutableDirectedGraph>::New();\n vtkIdType source = mut->AddVertex();\n vtkIdType bkg = mut->AddVertex();\n vtkIdType c1 = mut->AddVertex();\n vtkIdType c2 = mut->AddVertex();\n vtkIdType l1 = mut->AddVertex();\n vtkIdType l2 = mut->AddVertex();\n vtkIdType l3 = mut->AddVertex();\n\n vtkSmartPointer<vtkFloatArray> Weights = vtkSmartPointer<vtkFloatArray>::New();\n Weights->SetName(\"Weights\");\n Weights->InsertValue((mut->AddEdge(source,bkg)).Id,1.0f);\n Weights->InsertValue((mut->AddEdge(source,c1)).Id,1.0f);\n Weights->InsertValue((mut->AddEdge(source,c2)).Id,1.0f);\n Weights->InsertValue((mut->AddEdge(source,l1)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(source,l2)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(c1,l1)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(c2,l2)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(c1,l3)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(c2,l3)).Id,0.5f);\n\n vtkSmartPointer<vtkRootedDirectedAcyclicGraph> DAG = vtkSmartPointer<vtkRootedDirectedAcyclicGraph>::New();\n DAG->CheckedShallowCopy(mut);\n\n vtkSmartPointer<vtkBMPReader> cost0 = vtkSmartPointer<vtkBMPReader>::New();\n cost0->SetFileName( std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\/cost0.bmp\").c_str() );\n vtkSmartPointer<vtkBMPReader> cost1 = vtkSmartPointer<vtkBMPReader>::New();\n cost1->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\/cost1.bmp\").c_str());\n vtkSmartPointer<vtkBMPReader> cost2 = vtkSmartPointer<vtkBMPReader>::New();\n cost2->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\/cost2.bmp\").c_str());\n vtkSmartPointer<vtkBMPReader> cost3 = vtkSmartPointer<vtkBMPReader>::New();\n cost3->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\/cost3.bmp\").c_str());\n\n\n vtkSmartPointer<vtkImageExtractComponents> extract0 = vtkSmartPointer<vtkImageExtractComponents>::New();\n extract0->SetComponents(0);\n extract0->SetInputConnection(cost0->GetOutputPort());\n vtkSmartPointer<vtkImageCast> cast0 = vtkSmartPointer<vtkImageCast>::New();\n cast0->SetOutputScalarTypeToFloat();\n cast0->SetInputConnection(extract0->GetOutputPort());\n vtkSmartPointer<vtkImageExtractComponents> extract1 = vtkSmartPointer<vtkImageExtractComponents>::New();\n extract1->SetComponents(0);\n extract1->SetInputConnection(cost1->GetOutputPort());\n vtkSmartPointer<vtkImageCast> cast1 = vtkSmartPointer<vtkImageCast>::New();\n cast1->SetOutputScalarTypeToFloat();\n cast1->SetInputConnection(extract1->GetOutputPort());\n vtkSmartPointer<vtkImageExtractComponents> extract2 = vtkSmartPointer<vtkImageExtractComponents>::New();\n extract2->SetComponents(0);\n extract2->SetInputConnection(cost2->GetOutputPort());\n vtkSmartPointer<vtkImageCast> cast2 = vtkSmartPointer<vtkImageCast>::New();\n cast2->SetOutputScalarTypeToFloat();\n cast2->SetInputConnection(extract2->GetOutputPort());\n vtkSmartPointer<vtkImageExtractComponents> extract3 = vtkSmartPointer<vtkImageExtractComponents>::New();\n extract3->SetComponents(0);\n extract3->SetInputConnection(cost3->GetOutputPort());\n vtkSmartPointer<vtkImageCast> cast3 = vtkSmartPointer<vtkImageCast>::New();\n cast3->SetOutputScalarTypeToFloat();\n cast3->SetInputConnection(extract3->GetOutputPort());\n\n \/\/cast0->Update();\n \/\/cast1->Update();\n \/\/cast2->Update();\n \/\/cast3->Update();\n\n vtkSmartPointer<vtkDirectedAcyclicGraphMaxFlowSegmentation> dagmf =\n vtkSmartPointer<vtkDirectedAcyclicGraphMaxFlowSegmentation>::New();\n dagmf->SetStructure(DAG);\n dagmf->SetDataInputConnection(bkg,cast0->GetOutputPort());\n dagmf->SetDataInputConnection(l1,cast1->GetOutputPort());\n dagmf->SetDataInputConnection(l2,cast2->GetOutputPort());\n dagmf->SetDataInputConnection(l3,cast3->GetOutputPort());\n dagmf->AddSmoothnessScalar(bkg,0.01);\n dagmf->AddSmoothnessScalar(l1, 0.01);\n dagmf->AddSmoothnessScalar(l2, 0.01);\n dagmf->AddSmoothnessScalar(l3, 0.01);\n dagmf->AddSmoothnessScalar(c1, 50);\n dagmf->AddSmoothnessScalar(c2, 50);\n dagmf->SetCC(0.01);\n dagmf->SetStepSize(0.1);\n dagmf->SetNumberOfIterations(100);\n \/\/dagmf->Update();\n\n vtkSmartPointer<vtkMetaImageWriter> writer = vtkSmartPointer<vtkMetaImageWriter>::New();\n writer->SetInputConnection(dagmf->GetOutputPort(bkg));\n writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l0.mhd\").c_str());\n writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l0.raw\").c_str());\n writer->Update();\n writer->Write();\n writer->SetInputConnection(dagmf->GetOutputPort(l1));\n writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l1.mhd\").c_str());\n writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l1.raw\").c_str());\n writer->Update();\n writer->Write();\n writer->SetInputConnection(dagmf->GetOutputPort(l2));\n writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l2.mhd\").c_str());\n writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l2.raw\").c_str());\n writer->Update();\n writer->Write();\n writer->SetInputConnection(dagmf->GetOutputPort(l3));\n writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l3.mhd\").c_str());\n writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l3.raw\").c_str());\n writer->Update();\n writer->Write();\n\n return 0;\n}\n<commit_msg>Cleaned up old commented out code no longer in use<commit_after>\/*=========================================================================\n\nProgram: Robarts Visualization Toolkit\n\nCopyright (c) John Stuart Haberl Baxter, Robarts Research Institute\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkBMPReader.h\"\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDirectedAcyclicGraphMaxFlowSegmentation.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkImageCast.h\"\n#include \"vtkImageData.h\"\n#include \"vtkImageExtractComponents.h\"\n#include \"vtkMetaImageWriter.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkRootedDirectedAcyclicGraph.h\"\n#include \"vtkRootedDirectedAcyclicGraphBackwardIterator.h\"\n#include \"vtkRootedDirectedAcyclicGraphForwardIterator.h\"\n#include \"vtkRootedDirectedAcyclicGraphIterator.h\"\n#include \"vtksys\/CommandLineArguments.hxx\"\n#include \"vtksys\/SystemTools.hxx\"\n#include <iostream>\n#include <vtkSmartPointer.h>\n#include <vtkVersion.h>\n\nint main(int argc, char** argv)\n{\n \/\/ Check command line arguments.\n bool printHelp(false);\n std::string outputDirectory;\n\n vtksys::CommandLineArguments args;\n args.Initialize( argc, argv );\n\n args.AddArgument(\"--help\", vtksys::CommandLineArguments::NO_ARGUMENT, &printHelp, \"Print this help.\");\n args.AddArgument( \"--output-dir\", vtksys::CommandLineArguments::EQUAL_ARGUMENT, &outputDirectory, \"Name of the output directory.\" );\n\n if ( !args.Parse() )\n {\n std::cerr << \"Problem parsing arguments.\" << std::endl;\n std::cout << \"Help: \" << args.GetHelp() << std::endl;\n exit(EXIT_FAILURE);\n }\n\n if ( printHelp )\n {\n std::cout << args.GetHelp() << std::endl;\n exit(EXIT_SUCCESS);\n }\n\n if( !vtksys::SystemTools::FileExists(outputDirectory.c_str(), false) && !vtksys::SystemTools::MakeDirectory(outputDirectory) )\n {\n std::cerr << \"Output directory doesn't exist and can't be created.\" << std::endl;\n }\n\n vtkSmartPointer<vtkMutableDirectedGraph> mut = vtkSmartPointer<vtkMutableDirectedGraph>::New();\n vtkIdType source = mut->AddVertex();\n vtkIdType bkg = mut->AddVertex();\n vtkIdType c1 = mut->AddVertex();\n vtkIdType c2 = mut->AddVertex();\n vtkIdType l1 = mut->AddVertex();\n vtkIdType l2 = mut->AddVertex();\n vtkIdType l3 = mut->AddVertex();\n\n vtkSmartPointer<vtkFloatArray> Weights = vtkSmartPointer<vtkFloatArray>::New();\n Weights->SetName(\"Weights\");\n Weights->InsertValue((mut->AddEdge(source,bkg)).Id,1.0f);\n Weights->InsertValue((mut->AddEdge(source,c1)).Id,1.0f);\n Weights->InsertValue((mut->AddEdge(source,c2)).Id,1.0f);\n Weights->InsertValue((mut->AddEdge(source,l1)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(source,l2)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(c1,l1)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(c2,l2)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(c1,l3)).Id,0.5f);\n Weights->InsertValue((mut->AddEdge(c2,l3)).Id,0.5f);\n\n vtkSmartPointer<vtkRootedDirectedAcyclicGraph> DAG = vtkSmartPointer<vtkRootedDirectedAcyclicGraph>::New();\n DAG->CheckedShallowCopy(mut);\n\n vtkSmartPointer<vtkBMPReader> cost0 = vtkSmartPointer<vtkBMPReader>::New();\n cost0->SetFileName( std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\/cost0.bmp\").c_str() );\n vtkSmartPointer<vtkBMPReader> cost1 = vtkSmartPointer<vtkBMPReader>::New();\n cost1->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\/cost1.bmp\").c_str());\n vtkSmartPointer<vtkBMPReader> cost2 = vtkSmartPointer<vtkBMPReader>::New();\n cost2->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\/cost2.bmp\").c_str());\n vtkSmartPointer<vtkBMPReader> cost3 = vtkSmartPointer<vtkBMPReader>::New();\n cost3->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\/cost3.bmp\").c_str());\n\n\n vtkSmartPointer<vtkImageExtractComponents> extract0 = vtkSmartPointer<vtkImageExtractComponents>::New();\n extract0->SetComponents(0);\n extract0->SetInputConnection(cost0->GetOutputPort());\n vtkSmartPointer<vtkImageCast> cast0 = vtkSmartPointer<vtkImageCast>::New();\n cast0->SetOutputScalarTypeToFloat();\n cast0->SetInputConnection(extract0->GetOutputPort());\n vtkSmartPointer<vtkImageExtractComponents> extract1 = vtkSmartPointer<vtkImageExtractComponents>::New();\n extract1->SetComponents(0);\n extract1->SetInputConnection(cost1->GetOutputPort());\n vtkSmartPointer<vtkImageCast> cast1 = vtkSmartPointer<vtkImageCast>::New();\n cast1->SetOutputScalarTypeToFloat();\n cast1->SetInputConnection(extract1->GetOutputPort());\n vtkSmartPointer<vtkImageExtractComponents> extract2 = vtkSmartPointer<vtkImageExtractComponents>::New();\n extract2->SetComponents(0);\n extract2->SetInputConnection(cost2->GetOutputPort());\n vtkSmartPointer<vtkImageCast> cast2 = vtkSmartPointer<vtkImageCast>::New();\n cast2->SetOutputScalarTypeToFloat();\n cast2->SetInputConnection(extract2->GetOutputPort());\n vtkSmartPointer<vtkImageExtractComponents> extract3 = vtkSmartPointer<vtkImageExtractComponents>::New();\n extract3->SetComponents(0);\n extract3->SetInputConnection(cost3->GetOutputPort());\n vtkSmartPointer<vtkImageCast> cast3 = vtkSmartPointer<vtkImageCast>::New();\n cast3->SetOutputScalarTypeToFloat();\n cast3->SetInputConnection(extract3->GetOutputPort());\n\n vtkSmartPointer<vtkDirectedAcyclicGraphMaxFlowSegmentation> dagmf =\n vtkSmartPointer<vtkDirectedAcyclicGraphMaxFlowSegmentation>::New();\n dagmf->SetStructure(DAG);\n dagmf->SetDataInputConnection(bkg,cast0->GetOutputPort());\n dagmf->SetDataInputConnection(l1,cast1->GetOutputPort());\n dagmf->SetDataInputConnection(l2,cast2->GetOutputPort());\n dagmf->SetDataInputConnection(l3,cast3->GetOutputPort());\n dagmf->AddSmoothnessScalar(bkg,0.01);\n dagmf->AddSmoothnessScalar(l1, 0.01);\n dagmf->AddSmoothnessScalar(l2, 0.01);\n dagmf->AddSmoothnessScalar(l3, 0.01);\n dagmf->AddSmoothnessScalar(c1, 50);\n dagmf->AddSmoothnessScalar(c2, 50);\n dagmf->SetCC(0.01);\n dagmf->SetStepSize(0.1);\n dagmf->SetNumberOfIterations(100);\n\n vtkSmartPointer<vtkMetaImageWriter> writer = vtkSmartPointer<vtkMetaImageWriter>::New();\n writer->SetInputConnection(dagmf->GetOutputPort(bkg));\n writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l0.mhd\").c_str());\n writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l0.raw\").c_str());\n writer->Update();\n writer->Write();\n writer->SetInputConnection(dagmf->GetOutputPort(l1));\n writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l1.mhd\").c_str());\n writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l1.raw\").c_str());\n writer->Update();\n writer->Write();\n writer->SetInputConnection(dagmf->GetOutputPort(l2));\n writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l2.mhd\").c_str());\n writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l2.raw\").c_str());\n writer->Update();\n writer->Write();\n writer->SetInputConnection(dagmf->GetOutputPort(l3));\n writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l3.mhd\").c_str());\n writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + \"\\\\l3.raw\").c_str());\n writer->Update();\n writer->Write();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ UjoImro, 2013\n\/\/ Experimental code for the CARP Project\n\/\/ Copyright (c) RealEyes, 2013\n\/\/ This version tests the responseMap calculation with input dumps\n\n\n\/*\n extern int EF_ALIGNMENT = 0;\n extern int EF_PROTECT_BELOW = 0;\n extern int EF_PROTECT_FREE = 0;\n extern int EF_ALLOW_MALLOC_0 = 1;\n extern int EF_FILL = 1922;\n*\/\n\n#include <iomanip>\n#include <boost\/smart_ptr.hpp>\n\n#include \"opencl.hpp\"\n#include \"memory.hpp\"\n#include \"bench_mlp.hpp\"\n\nconst int processed_frames = 100;\n\nint main()\n{\n conductor_t conductor; \/\/ the class for importing the input from the clm\n carp::opencl::device device;\n device.compile( {\"mlp_impl.cl\"}, {\"calculateMaps\"} );\n \n int fail = 0;\n long int elapsed_time = 0;\n int64_t maxnetallocated = 0;\n int64_t maxgrossallocated = 0;\n \n \n for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id);\n ((conductor.id != -1) and (conductor.id != processed_frames));\n \/\/ conductor.id != -1;\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)\n )\n {\n PRINT(conductor.id);\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n\n int groupsize = conductor.hack.m_visibleLandmarks_size;\n\n boost::shared_array<char> buffer( new char[groupsize * local_memsize] );\n \n \/\/ std::vector<carp::memory::buddy> pools( groupsize, carp::memory::buddy({local_memsize, uint8_t()}));\n std::vector<carp::memory::dense> pools( groupsize, carp::memory::dense({local_memsize, uint8_t()}));\n carp::memory::local_memory_manager locmm( groupsize * local_memsize, groupsize, local_memsize );\n \n void * self = buffer.get();\n std::vector<int> segments = locmm.get_segments();\n \n \/\/ here comes the function call\n { \n auto calcpackages = convertHackToMlp( self, pools, segments, conductor.hack );\n\n for ( auto & pool : pools ) {\n\/\/ PRINT(pool.grossallocated());\n\/\/ PRINT(pool.netallocated());\n maxgrossallocated = std::max( maxgrossallocated, pool.grossallocated() );\n maxnetallocated = std::max( maxnetallocated, pool.netallocated() );\n }\n\n \/\/ preparing the opencl data\n carp::opencl::array<uint8_t> clSelf( device, groupsize * local_memsize, self );\n carp::opencl::array<int> clSegments( device, segments );\n carp::opencl::array<calcpackage> clCalcpackages( device, calcpackages );\n \n auto start = std::chrono::high_resolution_clock::now();\n device[\"calculateMaps\"](\n clSelf.cl(),\n clSegments.cl(),\n conductor.hack.m_visibleLandmarks_size,\n conductor.hack.m_mapSize,\n clCalcpackages.cl(),\n carp::opencl::buffer(48 * KiB)\n ).groupsize({32},{32*conductor.hack.m_visibleLandmarks_size});\n auto end = std::chrono::high_resolution_clock::now();\n elapsed_time += microseconds(end - start);\n\n \/\/ copying the data back to the CPU\n auto processed = clSelf.get();\n void * results = reinterpret_cast<void*>(processed.data());\n\n clMat patch = GetMatFromVector( results + segments[9], calcpackages[9].tmp.patches, 0 );\n patch.rows = patch.rows * patch.cols;\n patch.cols = 1;\n patch.step = 1;\n \n clMat imagePatch = GetBlockChar( results + segments[9], calcpackages[9].input.alignedImage, 5, 16, 52, 63 );\n clMat xOuts = GetMatFromVector( results + segments[9], calcpackages[9].tmp.xOuts, 0 );\n clMat e = GetMatFromVector( results + segments[9], calcpackages[9].tmp.es, 0 );\n \n \/\/ printMatChar( results + segments[9], imagePatch, \"imagePatch\" );\n \/\/ printMatFloat( results + segments[9], patch, \"patch\");\n \/\/ printMatFloat( results + segments[9], e, \"e\"); \n \/\/ printMatFloat( results + segments[9], xOuts, \"xOuts\");\n\n \/\/ printMatFloat( results + segments[9], calcpackages[9].output.responseMap, \"calcpackages[9].output.responseMap\");\n \n\/\/ assert(false);\n \n \/\/ converting the outputs \n std::vector< cv::Mat_<double> > calculatedResults;\n for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)\n {\n cv::Mat_<double> nextResult;\n nextResult = convertMatFloatToCV( results + segments[q], calcpackages[q].output.responseMap );\n calculatedResults.push_back(nextResult); \n }\n \n \/\/ testing the output\n for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)\n {\n \/\/ std::cout << \"cv::norm( conductor.hack.responseMaps[\" << q << \"] - calculatedResults[\" << q << \"] ) = \"\n \/\/ << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;\n\n \/\/ for (int row=0; row<calculatedResults[q].rows; row++ )\n \/\/ for (int col=0; col<calculatedResults[q].cols; col++ )\n \/\/ if ( (conductor.hack.responseMaps[q](row,col) - calculatedResults[q](row,col)) > 0.0001 )\n \/\/ {\n \/\/ PRINT(row);\n \/\/ PRINT(col);\n \/\/ PRINT(conductor.hack.responseMaps[q](row,col));\n \/\/ PRINT(calculatedResults[q](row,col));\n \/\/ }\n \n PRINT(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ));\n assert(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) < 0.08);\n }\n \n }\n }\n \n std::cout << \"total elapsed time = \" << elapsed_time \/ 1000000. << \" s.\" << std::endl;\n std::cout << std::setprecision(2) << std::fixed;\n std::cout << \"processing speed = \" << 1000000. * processed_frames \/ elapsed_time << \"fps\" << std::endl;\n \/\/conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n\n PRINT(maxnetallocated);\n PRINT(maxgrossallocated);\n \n return EXIT_SUCCESS;\n} \/\/ int main\n\n\n\/\/ LuM end of file\n<commit_msg>the unittest strenghtened after Robi has fixed the initialization<commit_after>\/\/ UjoImro, 2013\n\/\/ Experimental code for the CARP Project\n\/\/ Copyright (c) RealEyes, 2013\n\/\/ This version tests the responseMap calculation with input dumps\n\n\n\/*\n extern int EF_ALIGNMENT = 0;\n extern int EF_PROTECT_BELOW = 0;\n extern int EF_PROTECT_FREE = 0;\n extern int EF_ALLOW_MALLOC_0 = 1;\n extern int EF_FILL = 1922;\n*\/\n\n#include <iomanip>\n#include <boost\/smart_ptr.hpp>\n\n#include \"opencl.hpp\"\n#include \"memory.hpp\"\n#include \"bench_mlp.hpp\"\n\nconst int processed_frames = 100;\n\nint main()\n{\n conductor_t conductor; \/\/ the class for importing the input from the clm\n carp::opencl::device device;\n device.compile( {\"mlp_impl.cl\"}, {\"calculateMaps\"} );\n \n int fail = 0;\n long int elapsed_time = 0;\n int64_t maxnetallocated = 0;\n int64_t maxgrossallocated = 0;\n \n \n for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id);\n ((conductor.id != -1) and (conductor.id != processed_frames));\n \/\/ conductor.id != -1;\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)\n )\n {\n PRINT(conductor.id);\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n\n int groupsize = conductor.hack.m_visibleLandmarks_size;\n\n boost::shared_array<char> buffer( new char[groupsize * local_memsize] );\n \n \/\/ std::vector<carp::memory::buddy> pools( groupsize, carp::memory::buddy({local_memsize, uint8_t()}));\n std::vector<carp::memory::dense> pools( groupsize, carp::memory::dense({local_memsize, uint8_t()}));\n carp::memory::local_memory_manager locmm( groupsize * local_memsize, groupsize, local_memsize );\n \n void * self = buffer.get();\n std::vector<int> segments = locmm.get_segments();\n \n \/\/ here comes the function call\n { \n auto calcpackages = convertHackToMlp( self, pools, segments, conductor.hack );\n\n for ( auto & pool : pools ) {\n\/\/ PRINT(pool.grossallocated());\n\/\/ PRINT(pool.netallocated());\n maxgrossallocated = std::max( maxgrossallocated, pool.grossallocated() );\n maxnetallocated = std::max( maxnetallocated, pool.netallocated() );\n }\n\n \/\/ preparing the opencl data\n carp::opencl::array<uint8_t> clSelf( device, groupsize * local_memsize, self );\n carp::opencl::array<int> clSegments( device, segments );\n carp::opencl::array<calcpackage> clCalcpackages( device, calcpackages );\n \n auto start = std::chrono::high_resolution_clock::now();\n device[\"calculateMaps\"](\n clSelf.cl(),\n clSegments.cl(),\n conductor.hack.m_visibleLandmarks_size,\n conductor.hack.m_mapSize,\n clCalcpackages.cl(),\n carp::opencl::buffer(48 * KiB)\n ).groupsize({32},{32*conductor.hack.m_visibleLandmarks_size});\n auto end = std::chrono::high_resolution_clock::now();\n elapsed_time += microseconds(end - start);\n\n \/\/ copying the data back to the CPU\n auto processed = clSelf.get();\n void * results = reinterpret_cast<void*>(processed.data());\n\n clMat patch = GetMatFromVector( results + segments[9], calcpackages[9].tmp.patches, 0 );\n patch.rows = patch.rows * patch.cols;\n patch.cols = 1;\n patch.step = 1;\n \n clMat imagePatch = GetBlockChar( results + segments[9], calcpackages[9].input.alignedImage, 5, 16, 52, 63 );\n clMat xOuts = GetMatFromVector( results + segments[9], calcpackages[9].tmp.xOuts, 0 );\n clMat e = GetMatFromVector( results + segments[9], calcpackages[9].tmp.es, 0 );\n \n \/\/ printMatChar( results + segments[9], imagePatch, \"imagePatch\" );\n \/\/ printMatFloat( results + segments[9], patch, \"patch\");\n \/\/ printMatFloat( results + segments[9], e, \"e\"); \n \/\/ printMatFloat( results + segments[9], xOuts, \"xOuts\");\n\n \/\/ printMatFloat( results + segments[9], calcpackages[9].output.responseMap, \"calcpackages[9].output.responseMap\");\n \n\/\/ assert(false);\n \n \/\/ converting the outputs \n std::vector< cv::Mat_<double> > calculatedResults;\n for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)\n {\n cv::Mat_<double> nextResult;\n nextResult = convertMatFloatToCV( results + segments[q], calcpackages[q].output.responseMap );\n calculatedResults.push_back(nextResult); \n }\n \n \/\/ testing the output\n for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)\n {\n \/\/ std::cout << \"cv::norm( conductor.hack.responseMaps[\" << q << \"] - calculatedResults[\" << q << \"] ) = \"\n \/\/ << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;\n\n \/\/ for (int row=0; row<calculatedResults[q].rows; row++ )\n \/\/ for (int col=0; col<calculatedResults[q].cols; col++ )\n \/\/ if ( (conductor.hack.responseMaps[q](row,col) - calculatedResults[q](row,col)) > 0.0001 )\n \/\/ {\n \/\/ PRINT(row);\n \/\/ PRINT(col);\n \/\/ PRINT(conductor.hack.responseMaps[q](row,col));\n \/\/ PRINT(calculatedResults[q](row,col));\n \/\/ }\n \n assert(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) < 0.0001);\n }\n \n }\n }\n \n std::cout << \"total elapsed time = \" << elapsed_time \/ 1000000. << \" s.\" << std::endl;\n std::cout << std::setprecision(2) << std::fixed;\n std::cout << \"processing speed = \" << 1000000. * processed_frames \/ elapsed_time << \"fps\" << std::endl;\n \/\/conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n\n PRINT(maxnetallocated);\n PRINT(maxgrossallocated);\n \n return EXIT_SUCCESS;\n} \/\/ int main\n\n\n\/\/ LuM end of file\n<|endoftext|>"} {"text":"<commit_before>#include \"kwm.h\"\n#include \"helpers.h\"\n#include \"daemon.h\"\n#include \"display.h\"\n#include \"space.h\"\n#include \"window.h\"\n#include \"keys.h\"\n#include \"interpreter.h\"\n#include \"scratchpad.h\"\n#include \"border.h\"\n#include \"config.h\"\n#include \"command.h\"\n#include \"cursor.h\"\n#include \"axlib\/axlib.h\"\n\n#define internal static\nconst std::string KwmCurrentVersion = \"Kwm Version 3.0.3\";\nstd::map<const char *, space_info> WindowTree;\n\nax_state AXState = {};\nax_display *FocusedDisplay = NULL;\nax_application *FocusedApplication = NULL;\nax_window *MarkedWindow = NULL;\n\nkwm_mach KWMMach = {};\nkwm_path KWMPath = {};\nkwm_settings KWMSettings = {};\nkwm_thread KWMThread = {};\nkwm_hotkeys KWMHotkeys = {};\nkwm_border FocusedBorder = {};\nkwm_border MarkedBorder = {};\nscratchpad Scratchpad = {};\n\nCGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)\n{\n switch(Type)\n {\n case kCGEventTapDisabledByTimeout:\n case kCGEventTapDisabledByUserInput:\n {\n if(!KWMMach.DisableEventTapInternal)\n {\n DEBUG(\"Restarting Event Tap\");\n CGEventTapEnable(KWMMach.EventTap, true);\n }\n } break;\n case kCGEventKeyDown:\n {\n \/* TODO(koekeishiya): Is there a better way to decide whether\n we should eat the CGEventRef or not (?) *\/\n if(KWMSettings.UseBuiltinHotkeys)\n {\n hotkey Eventkey = {}, *Hotkey = NULL;\n Hotkey = new hotkey;\n if(Hotkey)\n {\n CreateHotkeyFromCGEvent(Event, &Eventkey);\n if(HotkeyExists(Eventkey.Flags, Eventkey.Key, Hotkey, KWMHotkeys.ActiveMode->Name))\n {\n AXLibConstructEvent(AXEvent_HotkeyPressed, Hotkey, false);\n if(!Hotkey->Passthrough)\n return NULL;\n }\n else\n {\n delete Hotkey;\n }\n }\n }\n } break;\n case kCGEventMouseMoved:\n {\n if(KWMSettings.Focus == FocusModeAutoraise)\n AXLibConstructEvent(AXEvent_MouseMoved, NULL, false);\n } break;\n default: {} break;\n }\n\n return Event;\n}\n\ninternal bool\nCheckPrivileges()\n{\n bool Result = false;\n const void * Keys[] = { kAXTrustedCheckOptionPrompt };\n const void * Values[] = { kCFBooleanTrue };\n\n CFDictionaryRef Options;\n Options = CFDictionaryCreate(kCFAllocatorDefault,\n Keys, Values, sizeof(Keys) \/ sizeof(*Keys),\n &kCFCopyStringDictionaryKeyCallBacks,\n &kCFTypeDictionaryValueCallBacks);\n\n Result = AXIsProcessTrustedWithOptions(Options);\n CFRelease(Options);\n\n return Result;\n}\n\ninternal bool\nCheckArguments(int argc, char **argv)\n{\n bool Result = false;\n\n if(argc == 2)\n {\n std::string Arg = argv[1];\n if(Arg == \"--version\")\n {\n std::cout << KwmCurrentVersion << std::endl;\n Result = true;\n }\n }\n\n return Result;\n}\n\ninternal bool\nGetKwmFilePath()\n{\n bool Result = false;\n char PathBuf[PROC_PIDPATHINFO_MAXSIZE];\n pid_t Pid = getpid();\n int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));\n if (Ret > 0)\n {\n KWMPath.FilePath = PathBuf;\n\n std::size_t Split = KWMPath.FilePath.find_last_of(\"\/\\\\\");\n KWMPath.FilePath = KWMPath.FilePath.substr(0, Split);\n Result = true;\n }\n\n return Result;\n}\n\ninternal void\nKwmClearSettings()\n{\n KWMHotkeys.Modes.clear();\n KWMSettings.WindowRules.clear();\n KWMSettings.SpaceSettings.clear();\n KWMSettings.DisplaySettings.clear();\n KWMHotkeys.ActiveMode = GetBindingMode(\"default\");\n}\n\ninternal void\nKwmExecuteConfig()\n{\n char *HomeP = std::getenv(\"HOME\");\n if(!HomeP)\n {\n DEBUG(\"Failed to get environment variable 'HOME'\");\n return;\n }\n\n KWMPath.EnvHome = HomeP;\n KwmParseConfig(KWMPath.ConfigFile);\n}\n\ninternal void\nKwmExecuteInitScript()\n{\n std::string InitFile = KWMPath.EnvHome + \"\/\" + KWMPath.ConfigFolder + \"\/init\";\n\n struct stat Buffer;\n if(stat(InitFile.c_str(), &Buffer) == 0)\n KwmExecuteThreadedSystemCommand(InitFile);\n}\n\ninternal void\nSignalHandler(int Signum)\n{\n ShowAllScratchpadWindows();\n DEBUG(\"SignalHandler() \" << Signum);\n\n CloseBorder(&FocusedBorder);\n CloseBorder(&MarkedBorder);\n exit(Signum);\n}\n\ninternal void\nFatal(const std::string &Err)\n{\n std::cout << Err << std::endl;\n exit(1);\n}\n\ninternal void\nKwmInit()\n{\n if(!CheckPrivileges())\n Fatal(\"Error: Could not access OSX Accessibility!\");\n\n if(KwmStartDaemon())\n pthread_create(&KWMThread.Daemon, NULL, &KwmDaemonHandleConnectionBG, NULL);\n else\n Fatal(\"Error: Could not start daemon!\");\n\n#ifndef DEBUG_BUILD\n signal(SIGSEGV, SignalHandler);\n signal(SIGABRT, SignalHandler);\n signal(SIGTRAP, SignalHandler);\n signal(SIGTERM, SignalHandler);\n signal(SIGKILL, SignalHandler);\n signal(SIGINT, SignalHandler);\n#else\n printf(\"Kwm: Signal handlers are disabled!\\n\");\n#endif\n\n KWMSettings.SplitRatio = 0.5;\n KWMSettings.SplitMode = SPLIT_OPTIMAL;\n KWMSettings.DefaultOffset = CreateDefaultScreenOffset();\n\n KWMSettings.UseBuiltinHotkeys = true;\n KWMSettings.UseMouseFollowsFocus = true;\n KWMSettings.OptimalRatio = 1.618;\n KWMSettings.LockToContainer = true;\n\n KWMSettings.Space = SpaceModeBSP;\n KWMSettings.Focus = FocusModeAutoraise;\n KWMSettings.Cycle = CycleModeScreen;\n\n FocusedBorder.Radius = -1;\n MarkedBorder.Radius = -1;\n\n KWMPath.ConfigFile = \"kwmrc\";\n KWMPath.ConfigFolder = \".kwm\";\n KWMPath.BSPLayouts = \"layouts\";\n KWMHotkeys.ActiveMode = GetBindingMode(\"default\");\n\n GetKwmFilePath();\n}\n\nvoid KwmQuit()\n{\n ShowAllScratchpadWindows();\n CloseBorder(&FocusedBorder);\n CloseBorder(&MarkedBorder);\n\n exit(0);\n}\n\nvoid KwmReloadConfig()\n{\n KwmClearSettings();\n KwmExecuteConfig();\n}\n\nint main(int argc, char **argv)\n{\n if(CheckArguments(argc, argv))\n return 0;\n\n NSApplicationLoad();\n if(!AXLibDisplayHasSeparateSpaces())\n Fatal(\"Error: 'Displays have separate spaces' must be enabled!\");\n\n \/* NOTE(koekeishiya): Initialize AXLIB *\/\n AXLibInit(&AXState);\n AXLibStartEventLoop();\n\n ax_display *MainDisplay = AXLibMainDisplay();\n ax_display *Display = MainDisplay;\n do\n {\n ax_space *PrevSpace = Display->Space;\n Display->Space = AXLibGetActiveSpace(Display);\n Display->PrevSpace = PrevSpace;\n Display = AXLibNextDisplay(Display);\n } while(Display != MainDisplay);\n\n FocusedDisplay = MainDisplay;\n FocusedApplication = AXLibGetFocusedApplication();\n \/* ----------------------------------- *\/\n\n KwmInit();\n KwmExecuteConfig();\n KwmExecuteInitScript();\n CreateWindowNodeTree(MainDisplay);\n\n if(CGSIsSecureEventInputSet())\n fprintf(stderr, \"Secure Keyboard Entry is enabled, hotkeys will not work!\\n\");\n\n KWMMach.EventMask = ((1 << kCGEventKeyDown) |\n (1 << kCGEventMouseMoved));\n\n KWMMach.EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, KWMMach.EventMask, CGEventCallback, NULL);\n if(!KWMMach.EventTap || !CGEventTapIsEnabled(KWMMach.EventTap))\n Fatal(\"Error: Could not create event-tap!\");\n\n CFRunLoopAddSource(CFRunLoopGetMain(),\n CFMachPortCreateRunLoopSource(kCFAllocatorDefault, KWMMach.EventTap, 0),\n kCFRunLoopCommonModes);\n CGEventTapEnable(KWMMach.EventTap, true);\n CFRunLoopRun();\n return 0;\n}\n<commit_msg>version 3.0.4<commit_after>#include \"kwm.h\"\n#include \"helpers.h\"\n#include \"daemon.h\"\n#include \"display.h\"\n#include \"space.h\"\n#include \"window.h\"\n#include \"keys.h\"\n#include \"interpreter.h\"\n#include \"scratchpad.h\"\n#include \"border.h\"\n#include \"config.h\"\n#include \"command.h\"\n#include \"cursor.h\"\n#include \"axlib\/axlib.h\"\n\n#define internal static\nconst std::string KwmCurrentVersion = \"Kwm Version 3.0.4\";\nstd::map<const char *, space_info> WindowTree;\n\nax_state AXState = {};\nax_display *FocusedDisplay = NULL;\nax_application *FocusedApplication = NULL;\nax_window *MarkedWindow = NULL;\n\nkwm_mach KWMMach = {};\nkwm_path KWMPath = {};\nkwm_settings KWMSettings = {};\nkwm_thread KWMThread = {};\nkwm_hotkeys KWMHotkeys = {};\nkwm_border FocusedBorder = {};\nkwm_border MarkedBorder = {};\nscratchpad Scratchpad = {};\n\nCGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)\n{\n switch(Type)\n {\n case kCGEventTapDisabledByTimeout:\n case kCGEventTapDisabledByUserInput:\n {\n if(!KWMMach.DisableEventTapInternal)\n {\n DEBUG(\"Restarting Event Tap\");\n CGEventTapEnable(KWMMach.EventTap, true);\n }\n } break;\n case kCGEventKeyDown:\n {\n \/* TODO(koekeishiya): Is there a better way to decide whether\n we should eat the CGEventRef or not (?) *\/\n if(KWMSettings.UseBuiltinHotkeys)\n {\n hotkey Eventkey = {}, *Hotkey = NULL;\n Hotkey = new hotkey;\n if(Hotkey)\n {\n CreateHotkeyFromCGEvent(Event, &Eventkey);\n if(HotkeyExists(Eventkey.Flags, Eventkey.Key, Hotkey, KWMHotkeys.ActiveMode->Name))\n {\n AXLibConstructEvent(AXEvent_HotkeyPressed, Hotkey, false);\n if(!Hotkey->Passthrough)\n return NULL;\n }\n else\n {\n delete Hotkey;\n }\n }\n }\n } break;\n case kCGEventMouseMoved:\n {\n if(KWMSettings.Focus == FocusModeAutoraise)\n AXLibConstructEvent(AXEvent_MouseMoved, NULL, false);\n } break;\n default: {} break;\n }\n\n return Event;\n}\n\ninternal bool\nCheckPrivileges()\n{\n bool Result = false;\n const void * Keys[] = { kAXTrustedCheckOptionPrompt };\n const void * Values[] = { kCFBooleanTrue };\n\n CFDictionaryRef Options;\n Options = CFDictionaryCreate(kCFAllocatorDefault,\n Keys, Values, sizeof(Keys) \/ sizeof(*Keys),\n &kCFCopyStringDictionaryKeyCallBacks,\n &kCFTypeDictionaryValueCallBacks);\n\n Result = AXIsProcessTrustedWithOptions(Options);\n CFRelease(Options);\n\n return Result;\n}\n\ninternal bool\nCheckArguments(int argc, char **argv)\n{\n bool Result = false;\n\n if(argc == 2)\n {\n std::string Arg = argv[1];\n if(Arg == \"--version\")\n {\n std::cout << KwmCurrentVersion << std::endl;\n Result = true;\n }\n }\n\n return Result;\n}\n\ninternal bool\nGetKwmFilePath()\n{\n bool Result = false;\n char PathBuf[PROC_PIDPATHINFO_MAXSIZE];\n pid_t Pid = getpid();\n int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));\n if (Ret > 0)\n {\n KWMPath.FilePath = PathBuf;\n\n std::size_t Split = KWMPath.FilePath.find_last_of(\"\/\\\\\");\n KWMPath.FilePath = KWMPath.FilePath.substr(0, Split);\n Result = true;\n }\n\n return Result;\n}\n\ninternal void\nKwmClearSettings()\n{\n KWMHotkeys.Modes.clear();\n KWMSettings.WindowRules.clear();\n KWMSettings.SpaceSettings.clear();\n KWMSettings.DisplaySettings.clear();\n KWMHotkeys.ActiveMode = GetBindingMode(\"default\");\n}\n\ninternal void\nKwmExecuteConfig()\n{\n char *HomeP = std::getenv(\"HOME\");\n if(!HomeP)\n {\n DEBUG(\"Failed to get environment variable 'HOME'\");\n return;\n }\n\n KWMPath.EnvHome = HomeP;\n KwmParseConfig(KWMPath.ConfigFile);\n}\n\ninternal void\nKwmExecuteInitScript()\n{\n std::string InitFile = KWMPath.EnvHome + \"\/\" + KWMPath.ConfigFolder + \"\/init\";\n\n struct stat Buffer;\n if(stat(InitFile.c_str(), &Buffer) == 0)\n KwmExecuteThreadedSystemCommand(InitFile);\n}\n\ninternal void\nSignalHandler(int Signum)\n{\n ShowAllScratchpadWindows();\n DEBUG(\"SignalHandler() \" << Signum);\n\n CloseBorder(&FocusedBorder);\n CloseBorder(&MarkedBorder);\n exit(Signum);\n}\n\ninternal void\nFatal(const std::string &Err)\n{\n std::cout << Err << std::endl;\n exit(1);\n}\n\ninternal void\nKwmInit()\n{\n if(!CheckPrivileges())\n Fatal(\"Error: Could not access OSX Accessibility!\");\n\n if(KwmStartDaemon())\n pthread_create(&KWMThread.Daemon, NULL, &KwmDaemonHandleConnectionBG, NULL);\n else\n Fatal(\"Error: Could not start daemon!\");\n\n#ifndef DEBUG_BUILD\n signal(SIGSEGV, SignalHandler);\n signal(SIGABRT, SignalHandler);\n signal(SIGTRAP, SignalHandler);\n signal(SIGTERM, SignalHandler);\n signal(SIGKILL, SignalHandler);\n signal(SIGINT, SignalHandler);\n#else\n printf(\"Kwm: Signal handlers are disabled!\\n\");\n#endif\n\n KWMSettings.SplitRatio = 0.5;\n KWMSettings.SplitMode = SPLIT_OPTIMAL;\n KWMSettings.DefaultOffset = CreateDefaultScreenOffset();\n\n KWMSettings.UseBuiltinHotkeys = true;\n KWMSettings.UseMouseFollowsFocus = true;\n KWMSettings.OptimalRatio = 1.618;\n KWMSettings.LockToContainer = true;\n\n KWMSettings.Space = SpaceModeBSP;\n KWMSettings.Focus = FocusModeAutoraise;\n KWMSettings.Cycle = CycleModeScreen;\n\n FocusedBorder.Radius = -1;\n MarkedBorder.Radius = -1;\n\n KWMPath.ConfigFile = \"kwmrc\";\n KWMPath.ConfigFolder = \".kwm\";\n KWMPath.BSPLayouts = \"layouts\";\n KWMHotkeys.ActiveMode = GetBindingMode(\"default\");\n\n GetKwmFilePath();\n}\n\nvoid KwmQuit()\n{\n ShowAllScratchpadWindows();\n CloseBorder(&FocusedBorder);\n CloseBorder(&MarkedBorder);\n\n exit(0);\n}\n\nvoid KwmReloadConfig()\n{\n KwmClearSettings();\n KwmExecuteConfig();\n}\n\nint main(int argc, char **argv)\n{\n if(CheckArguments(argc, argv))\n return 0;\n\n NSApplicationLoad();\n if(!AXLibDisplayHasSeparateSpaces())\n Fatal(\"Error: 'Displays have separate spaces' must be enabled!\");\n\n \/* NOTE(koekeishiya): Initialize AXLIB *\/\n AXLibInit(&AXState);\n AXLibStartEventLoop();\n\n ax_display *MainDisplay = AXLibMainDisplay();\n ax_display *Display = MainDisplay;\n do\n {\n ax_space *PrevSpace = Display->Space;\n Display->Space = AXLibGetActiveSpace(Display);\n Display->PrevSpace = PrevSpace;\n Display = AXLibNextDisplay(Display);\n } while(Display != MainDisplay);\n\n FocusedDisplay = MainDisplay;\n FocusedApplication = AXLibGetFocusedApplication();\n \/* ----------------------------------- *\/\n\n KwmInit();\n KwmExecuteConfig();\n KwmExecuteInitScript();\n CreateWindowNodeTree(MainDisplay);\n\n if(CGSIsSecureEventInputSet())\n fprintf(stderr, \"Secure Keyboard Entry is enabled, hotkeys will not work!\\n\");\n\n KWMMach.EventMask = ((1 << kCGEventKeyDown) |\n (1 << kCGEventMouseMoved));\n\n KWMMach.EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, KWMMach.EventMask, CGEventCallback, NULL);\n if(!KWMMach.EventTap || !CGEventTapIsEnabled(KWMMach.EventTap))\n Fatal(\"Error: Could not create event-tap!\");\n\n CFRunLoopAddSource(CFRunLoopGetMain(),\n CFMachPortCreateRunLoopSource(kCFAllocatorDefault, KWMMach.EventTap, 0),\n kCFRunLoopCommonModes);\n CGEventTapEnable(KWMMach.EventTap, true);\n CFRunLoopRun();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(n^3)\n\/\/ Space: O(n^2)\n\nclass Solution {\npublic:\n \/**\n * @param A an integer array\n * @param k an integer\n * @return an integer\n *\/\n int postOffice(vector<int>& A, int k) {\n const int n = A.size();\n if (A.empty() || k >= n) {\n return 0;\n }\n\n sort(A.begin(), A.end()); \/\/ Time: O(nlogn)\n\n \/\/ Precompute cost.\n \/\/ Time: O(n^3)\n \/\/ Space: O(n^2)\n vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0));\n computeMinCost(A, &cost);\n\n \/\/ DP of sum.\n \/\/ Time: O(k * n^2)\n \/\/ Space: O(n)\n \/\/ sum[i][j] denotes the smallest sum of\n \/\/ picking i post offices for the first j houses.\n vector<vector<int>> sum(2, vector<int>(A.size() + 1, INT_MAX));\n sum[0][0] = 0;\n for (int i = 1; i <= k; ++i) {\n for (int j = 0; j <= n; ++j) {\n sum[i % 2][j] = INT_MAX;\n for (int r = 1; r <= j; ++r) {\n if (sum[(i - 1) % 2][j - r] != INT_MAX) {\n sum[i % 2][j] = min(sum[i % 2][j],\n sum[(i - 1) % 2][j - r] +\n cost[j - r + 1][j]);\n }\n }\n }\n }\n return sum[k % 2][n];\n }\n\n void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) {\n \/\/ Min cost of building a post office between house (i, j).\n \/\/ This post office must be in median position.\n const int n = A.size();\n for (int i = 0; i < n; ++i) {\n for (int j = i; j < n; ++j) {\n int mid = (i + j) \/ 2;\n for (int r = i; r <= mid; ++r) {\n (*cost)[i + 1][j + 1] += A[mid] - A[r];\n }\n for (int r = mid + 1; r <= j; ++r) {\n (*cost)[i + 1][j + 1] += A[r] - A[mid];\n }\n }\n }\n }\n};\n\n\/\/ Time: O(n^3)\n\/\/ Space: O(n^2)\nclass Solution2 {\npublic:\n \/**\n * @param A an integer array\n * @param k an integer\n * @return an integer\n *\/\n int postOffice(vector<int>& A, int k) {\n const int n = A.size();\n if (A.empty() || k >= n) {\n return 0;\n }\n\n sort(A.begin(), A.end()); \/\/ Time: O(nlogn)\n\n \/\/ Precompute cost.\n \/\/ Time: O(n^3)\n \/\/ Space: O(n^2)\n vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0));\n computeMinCost(A, &cost);\n\n \/\/ DP of sum.\n \/\/ Time: O(k * n^2)\n \/\/ Space: O(k * n)\n \/\/ sum[i][j] denotes the smallest sum of\n \/\/ picking i post offices for the first j houses.\n vector<vector<int>> sum(k + 1, vector<int>(A.size() + 1, INT_MAX));\n sum[0][0] = 0;\n for (int i = 1; i <= k; ++i) {\n for (int j = 0; j < n; ++j) {\n if (sum[i - 1][j] != INT_MAX) {\n for (int r = 1; j + r <= n; ++r) {\n sum[i][j + r] = min(sum[i][j + r],\n sum[i - 1][j] + cost[j + 1][j + r]);\n }\n }\n }\n }\n return sum[k][n];\n }\n\n void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) {\n \/\/ Min cost of building a post office between house (i, j).\n \/\/ This post office must be in median position.\n const int n = A.size();\n for (int i = 0; i < n; ++i) {\n for (int j = i; j < n; ++j) {\n int mid = (i + j) \/ 2;\n for (int r = i; r <= mid; ++r) {\n (*cost)[i + 1][j + 1] += A[mid] - A[r];\n }\n for (int r = mid + 1; r <= j; ++r) {\n (*cost)[i + 1][j + 1] += A[r] - A[mid];\n }\n }\n }\n }\n};\n<commit_msg>Update post-office-problem.cpp<commit_after>\/\/ Time: O(n^3)\n\/\/ Space: O(n^2)\n\nclass Solution {\npublic:\n \/**\n * @param A an integer array\n * @param k an integer\n * @return an integer\n *\/\n int postOffice(vector<int>& A, int k) {\n const int n = A.size();\n if (A.empty() || k >= n) {\n return 0;\n }\n\n sort(A.begin(), A.end()); \/\/ Time: O(nlogn)\n\n \/\/ Precompute cost.\n \/\/ Time: O(n^3)\n \/\/ Space: O(n^2)\n vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0));\n computeMinCost(A, &cost);\n\n \/\/ DP of sum.\n \/\/ Time: O(k * n^2)\n \/\/ Space: O(n)\n \/\/ sum[i][j] denotes the smallest sum of\n \/\/ picking i post offices for the first j houses.\n vector<vector<int>> sum(2, vector<int>(A.size() + 1, INT_MAX));\n sum[0][0] = 0;\n for (int i = 1; i <= k; ++i) {\n for (int j = 0; j <= n; ++j) {\n \/\/ sum[i % 2][j] = INT_MAX;\n for (int r = 1; r <= j; ++r) {\n if (sum[(i - 1) % 2][j - r] != INT_MAX) {\n sum[i % 2][j] = min(sum[i % 2][j],\n sum[(i - 1) % 2][j - r] +\n cost[j - r + 1][j]);\n }\n }\n }\n }\n return sum[k % 2][n];\n }\n\n void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) {\n \/\/ Min cost of building a post office between house (i, j).\n \/\/ This post office must be in median position.\n const int n = A.size();\n for (int i = 0; i < n; ++i) {\n for (int j = i; j < n; ++j) {\n int mid = (i + j) \/ 2;\n for (int r = i; r <= mid; ++r) {\n (*cost)[i + 1][j + 1] += A[mid] - A[r];\n }\n for (int r = mid + 1; r <= j; ++r) {\n (*cost)[i + 1][j + 1] += A[r] - A[mid];\n }\n }\n }\n }\n};\n\n\/\/ Time: O(n^3)\n\/\/ Space: O(n^2)\nclass Solution2 {\npublic:\n \/**\n * @param A an integer array\n * @param k an integer\n * @return an integer\n *\/\n int postOffice(vector<int>& A, int k) {\n const int n = A.size();\n if (A.empty() || k >= n) {\n return 0;\n }\n\n sort(A.begin(), A.end()); \/\/ Time: O(nlogn)\n\n \/\/ Precompute cost.\n \/\/ Time: O(n^3)\n \/\/ Space: O(n^2)\n vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0));\n computeMinCost(A, &cost);\n\n \/\/ DP of sum.\n \/\/ Time: O(k * n^2)\n \/\/ Space: O(k * n)\n \/\/ sum[i][j] denotes the smallest sum of\n \/\/ picking i post offices for the first j houses.\n vector<vector<int>> sum(k + 1, vector<int>(A.size() + 1, INT_MAX));\n sum[0][0] = 0;\n for (int i = 1; i <= k; ++i) {\n for (int j = 0; j < n; ++j) {\n if (sum[i - 1][j] != INT_MAX) {\n for (int r = 1; j + r <= n; ++r) {\n sum[i][j + r] = min(sum[i][j + r],\n sum[i - 1][j] + cost[j + 1][j + r]);\n }\n }\n }\n }\n return sum[k][n];\n }\n\n void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) {\n \/\/ Min cost of building a post office between house (i, j).\n \/\/ This post office must be in median position.\n const int n = A.size();\n for (int i = 0; i < n; ++i) {\n for (int j = i; j < n; ++j) {\n int mid = (i + j) \/ 2;\n for (int r = i; r <= mid; ++r) {\n (*cost)[i + 1][j + 1] += A[mid] - A[r];\n }\n for (int r = mid + 1; r <= j; ++r) {\n (*cost)[i + 1][j + 1] += A[r] - A[mid];\n }\n }\n }\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Library\n Module: GeomF.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file\nor its contents may be copied, reproduced or altered in any way\nwithout the express written consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n#include \"GeomF.hh\"\n\n\/\/ Description:\n\/\/ Construct with all types of clipping turned off.\nvlGeometryFilter::vlGeometryFilter()\n{\n this->PointMinimum = 0;\n this->PointMaximum = LARGE_INTEGER;\n\n this->CellMinimum = 0;\n this->CellMaximum = LARGE_INTEGER;\n\n this->Extent[0] = -LARGE_FLOAT;\n this->Extent[1] = LARGE_FLOAT;\n this->Extent[2] = -LARGE_FLOAT;\n this->Extent[3] = LARGE_FLOAT;\n this->Extent[4] = -LARGE_FLOAT;\n this->Extent[5] = LARGE_FLOAT;\n\n this->PointClipping = 0;\n this->CellClipping = 0;\n this->ExtentClipping = 0;\n}\n\nvoid vlGeometryFilter::SetExtent(float xMin, float xMax, float yMin,\n float yMax, float zMin, float zMax)\n{\n float extent[6];\n\n extent[0] = xMin;\n extent[1] = xMax;\n extent[2] = yMin;\n extent[3] = yMax;\n extent[4] = zMin;\n extent[5] = zMax;\n\n this->SetExtent(extent);\n}\n\n\/\/ Description:\n\/\/ Specify a (xmin,xmax, ymin,ymax, zmin,zmax) bounding box to clip data.\nvoid vlGeometryFilter::SetExtent(float *extent)\n{\n int i;\n\n if ( extent[0] != this->Extent[0] || extent[1] != this->Extent[1] ||\n extent[2] != this->Extent[2] || extent[3] != this->Extent[3] ||\n extent[4] != this->Extent[4] || extent[5] != this->Extent[5] )\n {\n this->Modified();\n for (i=0; i<3; i++)\n {\n if ( extent[2*i] < 0 ) extent[2*i] = 0;\n if ( extent[2*i+1] < extent[2*i] ) extent[2*i+1] = extent[2*i];\n this->Extent[2*i] = extent[2*i];\n this->Extent[2*i+1] = extent[2*i+1];\n }\n }\n}\n\nvoid vlGeometryFilter::Execute()\n{\n int cellId, i, j;\n int numPts=this->Input->GetNumberOfPoints();\n int numCells=this->Input->GetNumberOfCells();\n char *cellVis;\n vlCell *cell, *face;\n float *x;\n vlIdList *ptIds;\n static vlIdList cellIds(MAX_CELL_SIZE);\n vlFloatPoints *newPts;\n int ptId;\n int npts, pts[MAX_CELL_SIZE];\n vlPointData *pd = this->Input->GetPointData();\n int allVisible;\n\n this->Initialize();\n\n if ( (!this->CellClipping) && (!this->PointClipping) && \n (!this->ExtentClipping) )\n {\n allVisible = 1;\n cellVis = NULL;\n }\n else\n {\n allVisible = 0;\n cellVis = new char[numCells];\n }\n\/\/\n\/\/ Mark cells as being visible or not\n\/\/\n if ( ! allVisible )\n {\n for(cellId=0; cellId < numCells; cellId++)\n {\n if ( this->CellClipping && cellId < this->CellMinimum ||\n cellId > this->CellMaximum )\n {\n cellVis[cellId] = 0;\n }\n else\n {\n cell = this->Input->GetCell(cellId);\n ptIds = cell->GetPointIds();\n for (i=0; i < ptIds->GetNumberOfIds(); i++) \n {\n ptId = ptIds->GetId(i);\n x = this->Input->GetPoint(ptId);\n\n if ( (this->PointClipping && (ptId < this->PointMinimum ||\n ptId > this->PointMaximum) ) &&\n (this->ExtentClipping && \n (x[0] < this->Extent[0] || x[0] > this->Extent[1] ||\n x[1] < this->Extent[2] || x[1] > this->Extent[3] ||\n x[2] < this->Extent[4] || x[2] > this->Extent[5] )) )\n {\n cellVis[cellId] = 0;\n break;\n }\n }\n if ( i >= ptIds->GetNumberOfIds() ) cellVis[cellId] = 1;\n }\n }\n }\n\/\/\n\/\/ Allocate\n\/\/\n newPts = new vlFloatPoints(numPts,numPts\/2);\n this->Allocate(4*numCells,numCells\/2);\n this->PointData.CopyAllocate(pd,numPts,numPts\/2);\n\/\/\n\/\/ Traverse cells to extract geometry\n\/\/\n for(cellId=0; cellId < numCells; cellId++)\n {\n if ( allVisible || cellVis[cellId] )\n {\n cell = this->Input->GetCell(cellId);\n switch (cell->GetCellDimension())\n {\n \/\/ create new points and then cell\n case 0: case 1: case 2:\n \n npts = cell->GetNumberOfPoints();\n for ( i=0; i < npts; i++)\n {\n ptId = cell->GetPointId(i);\n x = this->Input->GetPoint(ptId);\n pts[i] = newPts->InsertNextPoint(x);\n this->PointData.CopyData(pd,ptId,pts[i]);\n }\n this->InsertNextCell(cell->GetCellType(), npts, pts);\n break;\n\n case 3:\n for (j=0; j < cell->GetNumberOfFaces(); j++)\n {\n face = cell->GetFace(j);\n this->Input->GetCellNeighbors(cellId, face->PointIds, cellIds);\n if ( cellIds.GetNumberOfIds() <= 0 || \n (!allVisible && !cellVis[cellIds.GetId(0)]) )\n {\n npts = face->GetNumberOfPoints();\n for ( i=0; i < npts; i++)\n {\n ptId = cell->GetPointId(i);\n x = this->Input->GetPoint(ptId);\n pts[i] = newPts->InsertNextPoint(x);\n this->PointData.CopyData(pd,ptId,pts[i]);\n }\n this->InsertNextCell(face->GetCellType(), npts, pts);\n }\n }\n break;\n\n } \/\/switch\n } \/\/if visible\n } \/\/for all cells\n\/\/\n\/\/ Update ourselves\n\/\/\n this->SetPoints(newPts);\n this->Squeeze();\n\n if ( cellVis ) delete [] cellVis;\n\n}\n\nvoid vlGeometryFilter::PrintSelf(ostream& os, vlIndent indent)\n{\n vlDataSetToPolyFilter::PrintSelf(os,indent);\n\n os << indent << \"Point Minimum : \" << this->PointMinimum << \"\\n\";\n os << indent << \"Point Maximum : \" << this->PointMaximum << \"\\n\";\n\n os << indent << \"Cell Minimum : \" << this->CellMinimum << \"\\n\";\n os << indent << \"Cell Maximum : \" << this->CellMaximum << \"\\n\";\n\n os << indent << \"Extent: (\" \n << this->Extent[0] << \", \" << this->Extent[1] << \")\\n(\"\n << this->Extent[2] << \", \" << this->Extent[3] << \")\\n(\" \n << this->Extent[4] << \", \" << this->Extent[5] << \")\\n\";\n\n os << indent << \"PointClipping: \" << (this->PointClipping ? \"On\\n\" : \"Off\\n\");\n os << indent << \"CellClipping: \" << (this->CellClipping ? \"On\\n\" : \"Off\\n\");\n os << indent << \"ExtentClipping: \" << (this->ExtentClipping ? \"On\\n\" : \"Off\\n\");\n\n}\n\n<commit_msg>ERR: Fixed print method.<commit_after>\/*=========================================================================\n\n Program: Visualization Library\n Module: GeomF.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file\nor its contents may be copied, reproduced or altered in any way\nwithout the express written consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n#include \"GeomF.hh\"\n\n\/\/ Description:\n\/\/ Construct with all types of clipping turned off.\nvlGeometryFilter::vlGeometryFilter()\n{\n this->PointMinimum = 0;\n this->PointMaximum = LARGE_INTEGER;\n\n this->CellMinimum = 0;\n this->CellMaximum = LARGE_INTEGER;\n\n this->Extent[0] = -LARGE_FLOAT;\n this->Extent[1] = LARGE_FLOAT;\n this->Extent[2] = -LARGE_FLOAT;\n this->Extent[3] = LARGE_FLOAT;\n this->Extent[4] = -LARGE_FLOAT;\n this->Extent[5] = LARGE_FLOAT;\n\n this->PointClipping = 0;\n this->CellClipping = 0;\n this->ExtentClipping = 0;\n}\n\nvoid vlGeometryFilter::SetExtent(float xMin, float xMax, float yMin,\n float yMax, float zMin, float zMax)\n{\n float extent[6];\n\n extent[0] = xMin;\n extent[1] = xMax;\n extent[2] = yMin;\n extent[3] = yMax;\n extent[4] = zMin;\n extent[5] = zMax;\n\n this->SetExtent(extent);\n}\n\n\/\/ Description:\n\/\/ Specify a (xmin,xmax, ymin,ymax, zmin,zmax) bounding box to clip data.\nvoid vlGeometryFilter::SetExtent(float *extent)\n{\n int i;\n\n if ( extent[0] != this->Extent[0] || extent[1] != this->Extent[1] ||\n extent[2] != this->Extent[2] || extent[3] != this->Extent[3] ||\n extent[4] != this->Extent[4] || extent[5] != this->Extent[5] )\n {\n this->Modified();\n for (i=0; i<3; i++)\n {\n if ( extent[2*i] < 0 ) extent[2*i] = 0;\n if ( extent[2*i+1] < extent[2*i] ) extent[2*i+1] = extent[2*i];\n this->Extent[2*i] = extent[2*i];\n this->Extent[2*i+1] = extent[2*i+1];\n }\n }\n}\n\nvoid vlGeometryFilter::Execute()\n{\n int cellId, i, j;\n int numPts=this->Input->GetNumberOfPoints();\n int numCells=this->Input->GetNumberOfCells();\n char *cellVis;\n vlCell *cell, *face;\n float *x;\n vlIdList *ptIds;\n static vlIdList cellIds(MAX_CELL_SIZE);\n vlFloatPoints *newPts;\n int ptId;\n int npts, pts[MAX_CELL_SIZE];\n vlPointData *pd = this->Input->GetPointData();\n int allVisible;\n\n this->Initialize();\n\n if ( (!this->CellClipping) && (!this->PointClipping) && \n (!this->ExtentClipping) )\n {\n allVisible = 1;\n cellVis = NULL;\n }\n else\n {\n allVisible = 0;\n cellVis = new char[numCells];\n }\n\/\/\n\/\/ Mark cells as being visible or not\n\/\/\n if ( ! allVisible )\n {\n for(cellId=0; cellId < numCells; cellId++)\n {\n if ( this->CellClipping && cellId < this->CellMinimum ||\n cellId > this->CellMaximum )\n {\n cellVis[cellId] = 0;\n }\n else\n {\n cell = this->Input->GetCell(cellId);\n ptIds = cell->GetPointIds();\n for (i=0; i < ptIds->GetNumberOfIds(); i++) \n {\n ptId = ptIds->GetId(i);\n x = this->Input->GetPoint(ptId);\n\n if ( (this->PointClipping && (ptId < this->PointMinimum ||\n ptId > this->PointMaximum) ) &&\n (this->ExtentClipping && \n (x[0] < this->Extent[0] || x[0] > this->Extent[1] ||\n x[1] < this->Extent[2] || x[1] > this->Extent[3] ||\n x[2] < this->Extent[4] || x[2] > this->Extent[5] )) )\n {\n cellVis[cellId] = 0;\n break;\n }\n }\n if ( i >= ptIds->GetNumberOfIds() ) cellVis[cellId] = 1;\n }\n }\n }\n\/\/\n\/\/ Allocate\n\/\/\n newPts = new vlFloatPoints(numPts,numPts\/2);\n this->Allocate(4*numCells,numCells\/2);\n this->PointData.CopyAllocate(pd,numPts,numPts\/2);\n\/\/\n\/\/ Traverse cells to extract geometry\n\/\/\n for(cellId=0; cellId < numCells; cellId++)\n {\n if ( allVisible || cellVis[cellId] )\n {\n cell = this->Input->GetCell(cellId);\n switch (cell->GetCellDimension())\n {\n \/\/ create new points and then cell\n case 0: case 1: case 2:\n \n npts = cell->GetNumberOfPoints();\n for ( i=0; i < npts; i++)\n {\n ptId = cell->GetPointId(i);\n x = this->Input->GetPoint(ptId);\n pts[i] = newPts->InsertNextPoint(x);\n this->PointData.CopyData(pd,ptId,pts[i]);\n }\n this->InsertNextCell(cell->GetCellType(), npts, pts);\n break;\n\n case 3:\n for (j=0; j < cell->GetNumberOfFaces(); j++)\n {\n face = cell->GetFace(j);\n this->Input->GetCellNeighbors(cellId, face->PointIds, cellIds);\n if ( cellIds.GetNumberOfIds() <= 0 || \n (!allVisible && !cellVis[cellIds.GetId(0)]) )\n {\n npts = face->GetNumberOfPoints();\n for ( i=0; i < npts; i++)\n {\n ptId = cell->GetPointId(i);\n x = this->Input->GetPoint(ptId);\n pts[i] = newPts->InsertNextPoint(x);\n this->PointData.CopyData(pd,ptId,pts[i]);\n }\n this->InsertNextCell(face->GetCellType(), npts, pts);\n }\n }\n break;\n\n } \/\/switch\n } \/\/if visible\n } \/\/for all cells\n\/\/\n\/\/ Update ourselves\n\/\/\n this->SetPoints(newPts);\n this->Squeeze();\n\n if ( cellVis ) delete [] cellVis;\n\n}\n\nvoid vlGeometryFilter::PrintSelf(ostream& os, vlIndent indent)\n{\n vlDataSetToPolyFilter::PrintSelf(os,indent);\n\n os << indent << \"Point Minimum : \" << this->PointMinimum << \"\\n\";\n os << indent << \"Point Maximum : \" << this->PointMaximum << \"\\n\";\n\n os << indent << \"Cell Minimum : \" << this->CellMinimum << \"\\n\";\n os << indent << \"Cell Maximum : \" << this->CellMaximum << \"\\n\";\n\n os << indent << \"Extent: \\n\";\n os << indent << \" Xmin,Xmax: (\" << this->Extent[0] << \", \" << this->Extent[1] << \")\\n\";\n os << indent << \" Ymin,Ymax: (\" << this->Extent[2] << \", \" << this->Extent[3] << \")\\n\";\n os << indent << \" Zmin,Zmax: (\" << this->Extent[4] << \", \" << this->Extent[5] << \")\\n\";\n\n os << indent << \"PointClipping: \" << (this->PointClipping ? \"On\\n\" : \"Off\\n\");\n os << indent << \"CellClipping: \" << (this->CellClipping ? \"On\\n\" : \"Off\\n\");\n os << indent << \"ExtentClipping: \" << (this->ExtentClipping ? \"On\\n\" : \"Off\\n\");\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"file_data.hpp\"\n\n#include \"..\/reader.hpp\" \/\/ For Reader exceptions.\n#include \"..\/writer.hpp\" \/\/ For Writer exceptions.\n\n#include \"..\/..\/base\/exception.hpp\"\n#include \"..\/..\/base\/logging.hpp\"\n\n#include \"..\/..\/base\/start_mem_debug.hpp\"\n\n\nnamespace my {\n\nFileData::FileData(string const & fileName, Op op)\n : m_FileName(fileName), m_Op(op)\n{\n char const * const modes [] = {\"rb\", \"wb\", \"r+b\", \"ab\"};\n#ifdef OMIM_OS_BADA\n result error = m_File.Construct(fileName.c_str(), modes[op]);\n if (error == E_SUCCESS)\n return;\n#else\n m_File = fopen(fileName.c_str(), modes[op]);\n int error = m_File ? ferror(m_File) : 0;\n if (m_File && !error)\n return;\n if (op == OP_WRITE_EXISTING)\n {\n \/\/ Special case, since \"r+b\" fails if file doesn't exist.\n if (m_File)\n fclose(m_File);\n m_File = fopen(fileName.c_str(), \"wb\");\n error = m_File ? ferror(m_File) : 0;\n }\n if (m_File && !error)\n return;\n#endif\n \/\/ if we're here - something bad is happened\n if (m_Op)\n MYTHROW(Writer::OpenException, (fileName, error));\n else\n MYTHROW(Reader::OpenException, (fileName, error));\n}\n\nFileData::~FileData()\n{\n#ifndef OMIM_OS_BADA\n if (int error = fclose(m_File))\n {\n LOG(LWARNING, (\"Error closing file\", m_FileName, m_Op, error));\n }\n#endif\n}\n\nuint64_t FileData::Size() const\n{\n#ifdef OMIM_OS_BADA\n Osp::Io::FileAttributes attr;\n result error = Osp::Io::File::GetAttributes(m_FileName.c_str(), attr);\n if (IsFailed(error))\n MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));\n return attr.GetFileSize();\n#else\n uint64_t const pos = Pos();\n fseek64(m_File, 0, SEEK_END);\n if (int error = ferror(m_File))\n MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));\n uint64_t size = ftell64(m_File);\n if (int error = ferror(m_File))\n MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));\n fseek64(m_File, pos, SEEK_SET);\n if (int error = ferror(m_File))\n MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));\n return size;\n#endif\n}\n\nvoid FileData::Read(uint64_t pos, void * p, size_t size)\n{\n#ifdef OMIM_OS_BADA\n result error = m_File.Seek(Osp::Io::FILESEEKPOSITION_BEGIN, pos);\n if (IsFailed(error))\n MYTHROW(Reader::ReadException, (error, pos));\n int bytesRead = m_File.Read(p, size);\n error = GetLastResult();\n if (static_cast<size_t>(bytesRead) != size || IsFailed(error))\n MYTHROW(Reader::ReadException, (m_FileName, m_Op, error, bytesRead, pos, size));\n#else\n fseek64(m_File, pos, SEEK_SET);\n if (int error = ferror(m_File))\n MYTHROW(Reader::ReadException, (error, pos));\n size_t bytesRead = fread(p, 1, size, m_File);\n int error = ferror(m_File);\n if (bytesRead != size || error)\n MYTHROW(Reader::ReadException, (m_FileName, m_Op, error, bytesRead, pos, size));\n#endif\n}\n\nuint64_t FileData::Pos() const\n{\n#ifdef OMIM_OS_BADA\n int pos = m_File.Tell();\n result error = GetLastResult();\n if (IsFailed(error))\n MYTHROW(Writer::PosException, (m_FileName, m_Op, error, pos));\n return pos;\n#else\n uint64_t result = ftell64(m_File);\n if (int error = ferror(m_File))\n MYTHROW(Writer::PosException, (m_FileName, m_Op, error, result));\n return result;\n#endif\n}\n\nvoid FileData::Seek(uint64_t pos)\n{\n ASSERT_NOT_EQUAL(m_Op, OP_APPEND, (m_FileName, m_Op, pos));\n#ifdef OMIM_OS_BADA\n result error = m_File.Seek(Osp::Io::FILESEEKPOSITION_BEGIN, pos);\n if (IsFailed(error))\n MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));\n#else\n fseek64(m_File, pos, SEEK_SET);\n if (int error = ferror(m_File))\n MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));\n#endif\n}\n\nvoid FileData::Write(void const * p, size_t size)\n{\n#ifdef OMIM_OS_BADA\n result error = m_File.Write(p, size);\n if (IsFailed(error))\n MYTHROW(Writer::WriteException, (m_FileName, m_Op, error, size));\n#else\n size_t bytesWritten = fwrite(p, 1, size, m_File);\n int error = ferror(m_File);\n if (bytesWritten != size || error)\n MYTHROW(Writer::WriteException, (m_FileName, m_Op, error, bytesWritten, size));\n#endif\n}\n\nvoid FileData::Flush()\n{\n#ifdef OMIM_OS_BADA\n result error = m_File.Flush();\n if (IsFailed(error))\n MYTHROW(Writer::WriteException, (m_FileName, m_Op, error));\n#else\n fflush(m_File);\n if (int error = ferror(m_File))\n MYTHROW(Writer::WriteException, (m_FileName, m_Op, error));\n#endif\n}\n\nvoid FileData::Truncate(uint64_t sz)\n{\n#ifdef OMIM_OS_WINDOWS\n _chsize(fileno(m_File), sz);\n#else\n ftruncate(fileno(m_File), sz);\n#endif\n}\n\nbool GetFileSize(string const & fName, uint64_t & sz)\n{\n try\n {\n typedef my::FileData fdata_t;\n fdata_t f(fName, fdata_t::OP_READ);\n sz = f.Size();\n return true;\n }\n catch (RootException const &)\n {\n \/\/ supress all exceptions here\n return false;\n }\n}\n\nvoid DeleteFileX(string const & fName)\n{\n#ifdef OMIM_OS_BADA\n Osp::Io::File::Remove(fName.c_str());\n#else\n\n \/\/ Erase file.\n if (0 != remove(fName.c_str()))\n {\n \/\/ additional check if file really was removed correctly\n FILE * f = fopen(fName.c_str(), \"r\");\n if (f)\n {\n fclose(f);\n LOG(LERROR, (\"File exists but can't be deleted. Sharing violation?\", fName));\n }\n }\n#endif\n}\n\nbool RenameFileX(string const & fOld, string const & fNew)\n{\n#ifdef OMIM_OS_BADA\n return Osp::Io::File::Rename(fOld.c_str(), fNew.c_str());\n#else\n return (0 == rename(fOld.c_str(), fNew.c_str()));\n#endif\n}\n\n}\n<commit_msg>[msvc] Compile error.<commit_after>#include \"file_data.hpp\"\n\n#include \"..\/reader.hpp\" \/\/ For Reader exceptions.\n#include \"..\/writer.hpp\" \/\/ For Writer exceptions.\n\n#include \"..\/..\/base\/exception.hpp\"\n#include \"..\/..\/base\/logging.hpp\"\n\n#include \"..\/..\/std\/target_os.hpp\"\n\n#ifdef OMIM_OS_WINDOWS\n#include <io.h>\n#endif\n\n#include \"..\/..\/base\/start_mem_debug.hpp\"\n\n\nnamespace my {\n\nFileData::FileData(string const & fileName, Op op)\n : m_FileName(fileName), m_Op(op)\n{\n char const * const modes [] = {\"rb\", \"wb\", \"r+b\", \"ab\"};\n#ifdef OMIM_OS_BADA\n result error = m_File.Construct(fileName.c_str(), modes[op]);\n if (error == E_SUCCESS)\n return;\n#else\n m_File = fopen(fileName.c_str(), modes[op]);\n int error = m_File ? ferror(m_File) : 0;\n if (m_File && !error)\n return;\n if (op == OP_WRITE_EXISTING)\n {\n \/\/ Special case, since \"r+b\" fails if file doesn't exist.\n if (m_File)\n fclose(m_File);\n m_File = fopen(fileName.c_str(), \"wb\");\n error = m_File ? ferror(m_File) : 0;\n }\n if (m_File && !error)\n return;\n#endif\n \/\/ if we're here - something bad is happened\n if (m_Op)\n MYTHROW(Writer::OpenException, (fileName, error));\n else\n MYTHROW(Reader::OpenException, (fileName, error));\n}\n\nFileData::~FileData()\n{\n#ifndef OMIM_OS_BADA\n if (int error = fclose(m_File))\n {\n LOG(LWARNING, (\"Error closing file\", m_FileName, m_Op, error));\n }\n#endif\n}\n\nuint64_t FileData::Size() const\n{\n#ifdef OMIM_OS_BADA\n Osp::Io::FileAttributes attr;\n result error = Osp::Io::File::GetAttributes(m_FileName.c_str(), attr);\n if (IsFailed(error))\n MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));\n return attr.GetFileSize();\n#else\n uint64_t const pos = Pos();\n fseek64(m_File, 0, SEEK_END);\n if (int error = ferror(m_File))\n MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));\n uint64_t size = ftell64(m_File);\n if (int error = ferror(m_File))\n MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));\n fseek64(m_File, pos, SEEK_SET);\n if (int error = ferror(m_File))\n MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));\n return size;\n#endif\n}\n\nvoid FileData::Read(uint64_t pos, void * p, size_t size)\n{\n#ifdef OMIM_OS_BADA\n result error = m_File.Seek(Osp::Io::FILESEEKPOSITION_BEGIN, pos);\n if (IsFailed(error))\n MYTHROW(Reader::ReadException, (error, pos));\n int bytesRead = m_File.Read(p, size);\n error = GetLastResult();\n if (static_cast<size_t>(bytesRead) != size || IsFailed(error))\n MYTHROW(Reader::ReadException, (m_FileName, m_Op, error, bytesRead, pos, size));\n#else\n fseek64(m_File, pos, SEEK_SET);\n if (int error = ferror(m_File))\n MYTHROW(Reader::ReadException, (error, pos));\n size_t bytesRead = fread(p, 1, size, m_File);\n int error = ferror(m_File);\n if (bytesRead != size || error)\n MYTHROW(Reader::ReadException, (m_FileName, m_Op, error, bytesRead, pos, size));\n#endif\n}\n\nuint64_t FileData::Pos() const\n{\n#ifdef OMIM_OS_BADA\n int pos = m_File.Tell();\n result error = GetLastResult();\n if (IsFailed(error))\n MYTHROW(Writer::PosException, (m_FileName, m_Op, error, pos));\n return pos;\n#else\n uint64_t result = ftell64(m_File);\n if (int error = ferror(m_File))\n MYTHROW(Writer::PosException, (m_FileName, m_Op, error, result));\n return result;\n#endif\n}\n\nvoid FileData::Seek(uint64_t pos)\n{\n ASSERT_NOT_EQUAL(m_Op, OP_APPEND, (m_FileName, m_Op, pos));\n#ifdef OMIM_OS_BADA\n result error = m_File.Seek(Osp::Io::FILESEEKPOSITION_BEGIN, pos);\n if (IsFailed(error))\n MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));\n#else\n fseek64(m_File, pos, SEEK_SET);\n if (int error = ferror(m_File))\n MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));\n#endif\n}\n\nvoid FileData::Write(void const * p, size_t size)\n{\n#ifdef OMIM_OS_BADA\n result error = m_File.Write(p, size);\n if (IsFailed(error))\n MYTHROW(Writer::WriteException, (m_FileName, m_Op, error, size));\n#else\n size_t bytesWritten = fwrite(p, 1, size, m_File);\n int error = ferror(m_File);\n if (bytesWritten != size || error)\n MYTHROW(Writer::WriteException, (m_FileName, m_Op, error, bytesWritten, size));\n#endif\n}\n\nvoid FileData::Flush()\n{\n#ifdef OMIM_OS_BADA\n result error = m_File.Flush();\n if (IsFailed(error))\n MYTHROW(Writer::WriteException, (m_FileName, m_Op, error));\n#else\n fflush(m_File);\n if (int error = ferror(m_File))\n MYTHROW(Writer::WriteException, (m_FileName, m_Op, error));\n#endif\n}\n\nvoid FileData::Truncate(uint64_t sz)\n{\n#ifdef OMIM_OS_WINDOWS\n _chsize(fileno(m_File), sz);\n#else\n ftruncate(fileno(m_File), sz);\n#endif\n}\n\nbool GetFileSize(string const & fName, uint64_t & sz)\n{\n try\n {\n typedef my::FileData fdata_t;\n fdata_t f(fName, fdata_t::OP_READ);\n sz = f.Size();\n return true;\n }\n catch (RootException const &)\n {\n \/\/ supress all exceptions here\n return false;\n }\n}\n\nvoid DeleteFileX(string const & fName)\n{\n#ifdef OMIM_OS_BADA\n Osp::Io::File::Remove(fName.c_str());\n#else\n\n \/\/ Erase file.\n if (0 != remove(fName.c_str()))\n {\n \/\/ additional check if file really was removed correctly\n FILE * f = fopen(fName.c_str(), \"r\");\n if (f)\n {\n fclose(f);\n LOG(LERROR, (\"File exists but can't be deleted. Sharing violation?\", fName));\n }\n }\n#endif\n}\n\nbool RenameFileX(string const & fOld, string const & fNew)\n{\n#ifdef OMIM_OS_BADA\n return Osp::Io::File::Rename(fOld.c_str(), fNew.c_str());\n#else\n return (0 == rename(fOld.c_str(), fNew.c_str()));\n#endif\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n irkick.cpp - Implementation of the main window\n -------------------\n copyright : (C) 2002 by Gav Wood\n email : gav@indigoarchive.net\n***************************************************************************\/\n\n\/\/ This program is free software.\n\n#include <qwidget.h>\n#include <qdialog.h>\n#include <qtooltip.h>\n#include <qregexp.h>\n#include <qtimer.h>\n#include <qevent.h>\n\n#include <kdeversion.h>\n#include <kapplication.h>\n#include <kaction.h>\n#if !(KDE_VERSION_MINOR<=1 && KDE_VERSION_RELEASE<=5)\n#include <kactioncollection.h>\n#endif\n#include <ksimpleconfig.h>\n#include <ksystemtray.h>\n#include <kiconloader.h>\n#include <kpassivepopup.h>\n#include <kmessagebox.h>\n#include <kpopupmenu.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kaboutdialog.h>\n#include <kaboutkde.h>\n#include <kwinmodule.h>\n#include <kwin.h>\n#include <khelpmenu.h>\n#include <kglobal.h>\n\n#include <dcopclient.h>\n#include <dcopref.h>\n\n#include \"profileserver.h\"\n#include \"irkick.h\"\n\nvoid IRKTrayIcon::mousePressEvent(QMouseEvent *e)\n{\n\tKSystemTray::mousePressEvent(new QMouseEvent(QEvent::MouseButtonPress, e->pos(), e->globalPos(), e->button() == LeftButton ? RightButton : e->button(), e->state()));\n}\n\nIRKick::IRKick(const QCString &obj) : QObject(), DCOPObject(obj), npApp(QString::null)\n{\n\ttheClient = new KLircClient();\n\n\ttheTrayIcon = new IRKTrayIcon();\n\tif(theClient->isConnected())\n\t{\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n\t\tQToolTip::add(theTrayIcon, i18n(\"KDE Lirc Server: Ready.\"));\n\t}\n\telse\n\t{\ttheTrayIcon->setPixmap(SmallIcon(\"irkickoff\"));\n\t\tQToolTip::add(theTrayIcon, i18n(\"KDE Lirc Server: No infra-red remote controls found.\"));\n\t\tQTimer::singleShot(10000, this, SLOT(checkLirc()));\n\t}\n\ttheFlashOff = new QTimer(theTrayIcon);\n\tconnect(theFlashOff, SIGNAL(timeout()), SLOT(flashOff()));\n\n\ttheResetCount = 0;\n\tslotReloadConfiguration();\n\tconnect(theClient, SIGNAL(connectionClosed()), this, SLOT(slotClosed()));\n\tconnect(theClient, SIGNAL(remotesRead()), this, SLOT(resetModes()));\n\tconnect(theClient, SIGNAL(commandReceived(const QString &, const QString &, int)), this, SLOT(gotMessage(const QString &, const QString &, int)));\n\n\ttheTrayIcon->contextMenu()->changeTitle(0, \"IRKick\");\n\ttheTrayIcon->contextMenu()->insertItem(SmallIcon( \"configure\" ), i18n(\"&Configure...\"), this, SLOT(slotConfigure()));\n\ttheTrayIcon->contextMenu()->insertSeparator();\n\ttheTrayIcon->contextMenu()->insertItem(SmallIcon( \"help\" ), i18n(\"&Help\"), (new KHelpMenu(theTrayIcon, KGlobal::instance()->aboutData()))->menu());\n\ttheTrayIcon->actionCollection()->action(\"file_quit\")->disconnect(SIGNAL(activated()));\n\tconnect(theTrayIcon->actionCollection()->action(\"file_quit\"), SIGNAL(activated()), SLOT(doQuit()));\n\n\ttheTrayIcon->show();\n}\n\nIRKick::~IRKick()\n{\n\tdelete theTrayIcon;\n\tfor(QMap<QString,IRKTrayIcon *>::iterator i = currentModeIcons.begin(); i != currentModeIcons.end(); i++)\n\t\tif(*i) delete *i;\n}\n\nvoid IRKick::slotClosed()\n{\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkickoff\"));\n\tKPassivePopup::message(\"IRKick\", i18n(\"The infrared system has severed its connection. Remote controls are no longer available.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\tQTimer::singleShot(1000, this, SLOT(checkLirc()));\n}\n\nvoid IRKick::checkLirc()\n{\n\tif(!theClient->isConnected())\n\t\tif(theClient->connectToLirc())\n\t\t{\tKPassivePopup::message(\"IRKick\", i18n(\"A connection to the infrared system has been made. Remote controls may now be available.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\t\t\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n\t\t}\n\t\telse\n\t\t\tQTimer::singleShot(10000, this, SLOT(checkLirc()));\n}\n\nvoid IRKick::flashOff()\n{\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n}\n\nvoid IRKick::doQuit()\n{\n\tKSimpleConfig theConfig(\"irkickrc\");\n\ttheConfig.setGroup(\"General\");\n\tswitch(KMessageBox::questionYesNoCancel(0, i18n(\"Should the Infrared Remote Control server start automatically when you begin KDE?\"), i18n(\"Automatically Start?\")))\n\t{\tcase KMessageBox::No: theConfig.writeEntry(\"AutoStart\", false); break;\n\t\tcase KMessageBox::Yes: theConfig.writeEntry(\"AutoStart\", true); break;\n\t\tcase KMessageBox::Cancel: return;\n\t}\n\tKApplication::kApplication()->quit();\n}\n\nvoid IRKick::resetModes()\n{\n\tif(theResetCount > 1)\n\t\tKPassivePopup::message(\"IRKick\", i18n(\"Resetting all modes.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\tif(!theResetCount)\n\t\tallModes.generateNulls(theClient->remotes());\n\n\tQStringList remotes = theClient->remotes();\n\tfor(QStringList::iterator i = remotes.begin(); i != remotes.end(); i++)\n\t{\tcurrentModes[*i] = allModes.getDefault(*i).name();\n\t\tif(theResetCount && currentModeIcons[*i]) delete currentModeIcons[*i];\n\t\tcurrentModeIcons[*i] = 0;\n\t}\n\tupdateModeIcons();\n\ttheResetCount++;\n}\n\nvoid IRKick::slotReloadConfiguration()\n{\n\t\/\/ load configuration from config file\n\tKSimpleConfig theConfig(\"irkickrc\");\n\tallActions.loadFromConfig(theConfig);\n\tallModes.loadFromConfig(theConfig);\n\tif(currentModes.count() && theResetCount)\n\t\tresetModes();\n}\n\nvoid IRKick::slotConfigure()\n{\n\tKApplication::startServiceByDesktopName(\"kcmlirc\");\n}\n\nvoid IRKick::updateModeIcons()\n{\n\tfor(QMap<QString,QString>::iterator i = currentModes.begin(); i != currentModes.end(); i++)\n\t{\tMode mode = allModes.getMode(i.key(), i.data());\n\t\tif(mode.iconFile() == QString::null || mode.iconFile() == \"\")\n\t\t{\tif(currentModeIcons[i.key()])\n\t\t\t{\tdelete currentModeIcons[i.key()];\n\t\t\t\tcurrentModeIcons[i.key()] = 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\tif(!currentModeIcons[i.key()])\n\t\t\t{\tcurrentModeIcons[i.key()] = new IRKTrayIcon();\n\t\t\t\tcurrentModeIcons[i.key()]->show();\n\t\t\t\tcurrentModeIcons[i.key()]->contextMenu()->changeTitle(0, mode.remoteName());\n\t\t\t\tcurrentModeIcons[i.key()]->actionCollection()->action(\"file_quit\")->setEnabled(false);\n\t\t\t}\n\t\t\tcurrentModeIcons[i.key()]->setPixmap(KIconLoader().loadIcon(mode.iconFile(), KIcon::Panel));\n\t\t\tQToolTip::add(currentModeIcons[i.key()], mode.remoteName() + \": <b>\" + mode.name() + \"<\/b>\");\n\t\t}\n\t}\n}\n\nbool IRKick::getPrograms(const IRAction &action, QStringList &programs)\n{\n\tDCOPClient *theDC = KApplication::dcopClient();\n\tprograms.clear();\n\n\tif(action.unique())\n\t{\tif(theDC->isApplicationRegistered(action.program().utf8()))\n\t\t\tprograms += action.program();\n\t}\n\telse\n\t{\n\t\tQRegExp r = QRegExp(\"^\" + action.program() + \"-(\\\\d+)$\");\n\t\t\/\/ find all instances...\n\t\tQCStringList buf = theDC->registeredApplications();\n\t\tfor(QCStringList::iterator i = buf.begin(); i != buf.end(); i++)\n\t\t{\n\t\t\tQString program = QString::fromUtf8(*i);\n\t\t\tif(program.contains(r))\n\t\t\t\tprograms += program;\n\t\t}\n\t\tif(programs.size() > 1 && action.ifMulti() == IM_DONTSEND)\n\t\t\treturn false;\n\t\telse if(programs.size() > 1 && action.ifMulti() == IM_SENDTOTOP)\n\t\t{\tQValueList<WId> s = KWinModule().stackingOrder();\n\t\t\t\/\/ go through all the (ordered) window pids\n\t\t\tfor(QValueList<WId>::iterator i = s.fromLast(); i != s.end(); i--)\n\t\t\t{\tint p = KWin::info(*i).pid;\n\t\t\t\tQString id = action.program() + \"-\" + QString().setNum(p);\n\t\t\t\tif(programs.contains(id))\n\t\t\t\t{\tprograms.clear();\n\t\t\t\t\tprograms += id;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile(programs.size() > 1) programs.remove(programs.begin());\n\t\t}\n\t\telse if(programs.size() > 1 && action.ifMulti() == IM_SENDTOBOTTOM)\n\t\t{\tQValueList<WId> s = KWinModule().stackingOrder();\n\t\t\t\/\/ go through all the (ordered) window pids\n\t\t\tfor(QValueList<WId>::iterator i = s.begin(); i != s.end(); i++)\n\t\t\t{\tint p = KWin::info(*i).pid;\n\t\t\t\tQString id = action.program() + \"-\" + QString().setNum(p);\n\t\t\t\tif(programs.contains(id))\n\t\t\t\t{\tprograms.clear();\n\t\t\t\t\tprograms += id;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile(programs.size() > 1) programs.remove(programs.begin());\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid IRKick::executeAction(const IRAction &action)\n{\n\tDCOPClient *theDC = KApplication::dcopClient();\n\tQStringList programs;\n\n\tif(!getPrograms(action, programs)) return;\n\n\t\/\/ if programs.size()==0 here, then the app is definately not running.\n\tif(action.autoStart() && !programs.size())\n\t{\tQString sname = ProfileServer::profileServer()->getServiceName(action.program());\n\t\tif(sname != QString::null)\n\t\t{\n\t\t\tKPassivePopup::message(\"IRKick\", i18n(\"Starting <b>%1<\/b>...\").arg(action.application()), SmallIcon(\"irkick\"), theTrayIcon);\n\t\t\tKApplication::startServiceByDesktopName(sname);\n\t\t}\n\t}\n\tif(action.isJustStart()) return;\n\n\tif(!getPrograms(action, programs)) return;\n\n\tfor(QStringList::iterator i = programs.begin(); i != programs.end(); i++)\n\t{\tconst QString &program = *i;\n\t\tif(theDC->isApplicationRegistered(program.utf8()))\n\t\t{\tQByteArray data; QDataStream arg(data, IO_WriteOnly);\n\t\t\tkdDebug() << \"Sending data (\" << program << \", \" << action.object() << \", \" << action.method().prototypeNR() << endl;\n\t\t\tfor(Arguments::const_iterator j = action.arguments().begin(); j != action.arguments().end(); j++)\n\t\t\t{\tkdDebug() << \"Got argument...\" << endl;\n\t\t\t\tswitch((*j).type())\n\t\t\t\t{\tcase QVariant::Int: arg << (*j).toInt(); break;\n\t\t\t\t\tcase QVariant::CString: arg << (*j).toCString(); break;\n\t\t\t\t\tcase QVariant::StringList: arg << (*j).toStringList(); break;\n\t\t\t\t\tcase QVariant::UInt: arg << (*j).toUInt(); break;\n\t\t\t\t\tcase QVariant::Bool: arg << (*j).toBool(); break;\n\t\t\t\t\tcase QVariant::Double: arg << (*j).toDouble(); break;\n\t\t\t\t\tdefault: arg << (*j).toString(); break;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttheDC->send(program.utf8(), action.object().utf8(), action.method().prototypeNR().utf8(), data);\n\t\t}\n\t}\n}\n\nvoid IRKick::gotMessage(const QString &theRemote, const QString &theButton, int theRepeatCounter)\n{\n\tkdDebug() << \"Got message: \" << theRemote << \": \" << theButton << \" (\" << theRepeatCounter << \")\" << endl;\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkickflash\"));\n\ttheFlashOff->start(200, true);\n\tif(npApp != QString::null)\n\t{\n\t\tQString theApp = npApp;\n\t\tnpApp = QString::null;\n\t\t\/\/ send notifier by DCOP to npApp\/npModule\/npMethod(theRemote, theButton);\n\t\tQByteArray data; QDataStream arg(data, IO_WriteOnly);\n\t\targ << theRemote << theButton;\n\t\tKApplication::dcopClient()->send(theApp.utf8(), npModule.utf8(), npMethod.utf8(), data);\n\t}\n\telse\n\t{\n\t\tif(currentModes[theRemote].isNull()) currentModes[theRemote] = \"\";\n\t\tIRAItList l = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton);\n\t\tif(currentModes[theRemote] != \"\")\n\t\t\tl += allActions.findByModeButton(Mode(theRemote, \"\"), theButton);\n\t\tbool doBefore = true, doAfter = false;\n\t\tfor(IRAItList::const_iterator i = l.begin(); i != l.end(); i++)\n\t\t\tif((**i).isModeChange() && !theRepeatCounter)\n\t\t\t{\t\/\/ mode switch\n\t\t\t\tcurrentModes[theRemote] = (**i).modeChange();\n\t\t\t\tMode mode = allModes.getMode(theRemote, (**i).modeChange());\n\t\t\t\tupdateModeIcons();\n\t\t\t\tdoBefore = (**i).doBefore();\n\t\t\t\tdoAfter = (**i).doAfter();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tfor(int after = 0; after < 2; after++)\n\t\t{\tif(doBefore && !after || doAfter && after)\n\t\t\t\tfor(IRAItList::const_iterator i = l.begin(); i != l.end(); i++)\n\t\t\t\t\tif(!(**i).isModeChange() && ((**i).repeat() || !theRepeatCounter))\n\t\t\t\t\t{\texecuteAction(**i);\n\t\t\t\t\t}\n\t\t\tif(!after && doAfter)\n\t\t\t{\tl = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton);\n\t\t\t\tif(currentModes[theRemote] != \"\")\n\t\t\t\t\tl += allActions.findByModeButton(Mode(theRemote, \"\"), theButton);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid IRKick::stealNextPress(QString app, QString module, QString method)\n{\n\tnpApp = app;\n\tnpModule = module;\n\tnpMethod = method;\n}\n\nvoid IRKick::dontStealNextPress()\n{\n\tnpApp = QString::null;\n}\n\n#include \"irkick.moc\"\n<commit_msg>Make \"IRKick\" the default DCOPObject<commit_after>\/***************************************************************************\n irkick.cpp - Implementation of the main window\n -------------------\n copyright : (C) 2002 by Gav Wood\n email : gav@indigoarchive.net\n***************************************************************************\/\n\n\/\/ This program is free software.\n\n#include <qwidget.h>\n#include <qdialog.h>\n#include <qtooltip.h>\n#include <qregexp.h>\n#include <qtimer.h>\n#include <qevent.h>\n\n#include <kdeversion.h>\n#include <kapplication.h>\n#include <kaction.h>\n#if !(KDE_VERSION_MINOR<=1 && KDE_VERSION_RELEASE<=5)\n#include <kactioncollection.h>\n#endif\n#include <ksimpleconfig.h>\n#include <ksystemtray.h>\n#include <kiconloader.h>\n#include <kpassivepopup.h>\n#include <kmessagebox.h>\n#include <kpopupmenu.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kaboutdialog.h>\n#include <kaboutkde.h>\n#include <kwinmodule.h>\n#include <kwin.h>\n#include <khelpmenu.h>\n#include <kglobal.h>\n\n#include <dcopclient.h>\n#include <dcopref.h>\n\n#include \"profileserver.h\"\n#include \"irkick.h\"\n\nvoid IRKTrayIcon::mousePressEvent(QMouseEvent *e)\n{\n\tKSystemTray::mousePressEvent(new QMouseEvent(QEvent::MouseButtonPress, e->pos(), e->globalPos(), e->button() == LeftButton ? RightButton : e->button(), e->state()));\n}\n\nIRKick::IRKick(const QCString &obj) : QObject(), DCOPObject(obj), npApp(QString::null)\n{\n kapp->dcopClient()->setDefaultObject(obj);\n\ttheClient = new KLircClient();\n\n\ttheTrayIcon = new IRKTrayIcon();\n\tif(theClient->isConnected())\n\t{\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n\t\tQToolTip::add(theTrayIcon, i18n(\"KDE Lirc Server: Ready.\"));\n\t}\n\telse\n\t{\ttheTrayIcon->setPixmap(SmallIcon(\"irkickoff\"));\n\t\tQToolTip::add(theTrayIcon, i18n(\"KDE Lirc Server: No infra-red remote controls found.\"));\n\t\tQTimer::singleShot(10000, this, SLOT(checkLirc()));\n\t}\n\ttheFlashOff = new QTimer(theTrayIcon);\n\tconnect(theFlashOff, SIGNAL(timeout()), SLOT(flashOff()));\n\n\ttheResetCount = 0;\n\tslotReloadConfiguration();\n\tconnect(theClient, SIGNAL(connectionClosed()), this, SLOT(slotClosed()));\n\tconnect(theClient, SIGNAL(remotesRead()), this, SLOT(resetModes()));\n\tconnect(theClient, SIGNAL(commandReceived(const QString &, const QString &, int)), this, SLOT(gotMessage(const QString &, const QString &, int)));\n\n\ttheTrayIcon->contextMenu()->changeTitle(0, \"IRKick\");\n\ttheTrayIcon->contextMenu()->insertItem(SmallIcon( \"configure\" ), i18n(\"&Configure...\"), this, SLOT(slotConfigure()));\n\ttheTrayIcon->contextMenu()->insertSeparator();\n\ttheTrayIcon->contextMenu()->insertItem(SmallIcon( \"help\" ), i18n(\"&Help\"), (new KHelpMenu(theTrayIcon, KGlobal::instance()->aboutData()))->menu());\n\ttheTrayIcon->actionCollection()->action(\"file_quit\")->disconnect(SIGNAL(activated()));\n\tconnect(theTrayIcon->actionCollection()->action(\"file_quit\"), SIGNAL(activated()), SLOT(doQuit()));\n\n\ttheTrayIcon->show();\n}\n\nIRKick::~IRKick()\n{\n\tdelete theTrayIcon;\n\tfor(QMap<QString,IRKTrayIcon *>::iterator i = currentModeIcons.begin(); i != currentModeIcons.end(); i++)\n\t\tif(*i) delete *i;\n}\n\nvoid IRKick::slotClosed()\n{\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkickoff\"));\n\tKPassivePopup::message(\"IRKick\", i18n(\"The infrared system has severed its connection. Remote controls are no longer available.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\tQTimer::singleShot(1000, this, SLOT(checkLirc()));\n}\n\nvoid IRKick::checkLirc()\n{\n\tif(!theClient->isConnected())\n\t\tif(theClient->connectToLirc())\n\t\t{\tKPassivePopup::message(\"IRKick\", i18n(\"A connection to the infrared system has been made. Remote controls may now be available.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\t\t\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n\t\t}\n\t\telse\n\t\t\tQTimer::singleShot(10000, this, SLOT(checkLirc()));\n}\n\nvoid IRKick::flashOff()\n{\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkick\"));\n}\n\nvoid IRKick::doQuit()\n{\n\tKSimpleConfig theConfig(\"irkickrc\");\n\ttheConfig.setGroup(\"General\");\n\tswitch(KMessageBox::questionYesNoCancel(0, i18n(\"Should the Infrared Remote Control server start automatically when you begin KDE?\"), i18n(\"Automatically Start?\")))\n\t{\tcase KMessageBox::No: theConfig.writeEntry(\"AutoStart\", false); break;\n\t\tcase KMessageBox::Yes: theConfig.writeEntry(\"AutoStart\", true); break;\n\t\tcase KMessageBox::Cancel: return;\n\t}\n\tKApplication::kApplication()->quit();\n}\n\nvoid IRKick::resetModes()\n{\n\tif(theResetCount > 1)\n\t\tKPassivePopup::message(\"IRKick\", i18n(\"Resetting all modes.\"), SmallIcon(\"irkick\"), theTrayIcon);\n\tif(!theResetCount)\n\t\tallModes.generateNulls(theClient->remotes());\n\n\tQStringList remotes = theClient->remotes();\n\tfor(QStringList::iterator i = remotes.begin(); i != remotes.end(); i++)\n\t{\tcurrentModes[*i] = allModes.getDefault(*i).name();\n\t\tif(theResetCount && currentModeIcons[*i]) delete currentModeIcons[*i];\n\t\tcurrentModeIcons[*i] = 0;\n\t}\n\tupdateModeIcons();\n\ttheResetCount++;\n}\n\nvoid IRKick::slotReloadConfiguration()\n{\n\t\/\/ load configuration from config file\n\tKSimpleConfig theConfig(\"irkickrc\");\n\tallActions.loadFromConfig(theConfig);\n\tallModes.loadFromConfig(theConfig);\n\tif(currentModes.count() && theResetCount)\n\t\tresetModes();\n}\n\nvoid IRKick::slotConfigure()\n{\n\tKApplication::startServiceByDesktopName(\"kcmlirc\");\n}\n\nvoid IRKick::updateModeIcons()\n{\n\tfor(QMap<QString,QString>::iterator i = currentModes.begin(); i != currentModes.end(); i++)\n\t{\tMode mode = allModes.getMode(i.key(), i.data());\n\t\tif(mode.iconFile() == QString::null || mode.iconFile() == \"\")\n\t\t{\tif(currentModeIcons[i.key()])\n\t\t\t{\tdelete currentModeIcons[i.key()];\n\t\t\t\tcurrentModeIcons[i.key()] = 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\tif(!currentModeIcons[i.key()])\n\t\t\t{\tcurrentModeIcons[i.key()] = new IRKTrayIcon();\n\t\t\t\tcurrentModeIcons[i.key()]->show();\n\t\t\t\tcurrentModeIcons[i.key()]->contextMenu()->changeTitle(0, mode.remoteName());\n\t\t\t\tcurrentModeIcons[i.key()]->actionCollection()->action(\"file_quit\")->setEnabled(false);\n\t\t\t}\n\t\t\tcurrentModeIcons[i.key()]->setPixmap(KIconLoader().loadIcon(mode.iconFile(), KIcon::Panel));\n\t\t\tQToolTip::add(currentModeIcons[i.key()], mode.remoteName() + \": <b>\" + mode.name() + \"<\/b>\");\n\t\t}\n\t}\n}\n\nbool IRKick::getPrograms(const IRAction &action, QStringList &programs)\n{\n\tDCOPClient *theDC = KApplication::dcopClient();\n\tprograms.clear();\n\n\tif(action.unique())\n\t{\tif(theDC->isApplicationRegistered(action.program().utf8()))\n\t\t\tprograms += action.program();\n\t}\n\telse\n\t{\n\t\tQRegExp r = QRegExp(\"^\" + action.program() + \"-(\\\\d+)$\");\n\t\t\/\/ find all instances...\n\t\tQCStringList buf = theDC->registeredApplications();\n\t\tfor(QCStringList::iterator i = buf.begin(); i != buf.end(); i++)\n\t\t{\n\t\t\tQString program = QString::fromUtf8(*i);\n\t\t\tif(program.contains(r))\n\t\t\t\tprograms += program;\n\t\t}\n\t\tif(programs.size() > 1 && action.ifMulti() == IM_DONTSEND)\n\t\t\treturn false;\n\t\telse if(programs.size() > 1 && action.ifMulti() == IM_SENDTOTOP)\n\t\t{\tQValueList<WId> s = KWinModule().stackingOrder();\n\t\t\t\/\/ go through all the (ordered) window pids\n\t\t\tfor(QValueList<WId>::iterator i = s.fromLast(); i != s.end(); i--)\n\t\t\t{\tint p = KWin::info(*i).pid;\n\t\t\t\tQString id = action.program() + \"-\" + QString().setNum(p);\n\t\t\t\tif(programs.contains(id))\n\t\t\t\t{\tprograms.clear();\n\t\t\t\t\tprograms += id;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile(programs.size() > 1) programs.remove(programs.begin());\n\t\t}\n\t\telse if(programs.size() > 1 && action.ifMulti() == IM_SENDTOBOTTOM)\n\t\t{\tQValueList<WId> s = KWinModule().stackingOrder();\n\t\t\t\/\/ go through all the (ordered) window pids\n\t\t\tfor(QValueList<WId>::iterator i = s.begin(); i != s.end(); i++)\n\t\t\t{\tint p = KWin::info(*i).pid;\n\t\t\t\tQString id = action.program() + \"-\" + QString().setNum(p);\n\t\t\t\tif(programs.contains(id))\n\t\t\t\t{\tprograms.clear();\n\t\t\t\t\tprograms += id;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile(programs.size() > 1) programs.remove(programs.begin());\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid IRKick::executeAction(const IRAction &action)\n{\n\tDCOPClient *theDC = KApplication::dcopClient();\n\tQStringList programs;\n\n\tif(!getPrograms(action, programs)) return;\n\n\t\/\/ if programs.size()==0 here, then the app is definately not running.\n\tif(action.autoStart() && !programs.size())\n\t{\tQString sname = ProfileServer::profileServer()->getServiceName(action.program());\n\t\tif(sname != QString::null)\n\t\t{\n\t\t\tKPassivePopup::message(\"IRKick\", i18n(\"Starting <b>%1<\/b>...\").arg(action.application()), SmallIcon(\"irkick\"), theTrayIcon);\n\t\t\tKApplication::startServiceByDesktopName(sname);\n\t\t}\n\t}\n\tif(action.isJustStart()) return;\n\n\tif(!getPrograms(action, programs)) return;\n\n\tfor(QStringList::iterator i = programs.begin(); i != programs.end(); i++)\n\t{\tconst QString &program = *i;\n\t\tif(theDC->isApplicationRegistered(program.utf8()))\n\t\t{\tQByteArray data; QDataStream arg(data, IO_WriteOnly);\n\t\t\tkdDebug() << \"Sending data (\" << program << \", \" << action.object() << \", \" << action.method().prototypeNR() << endl;\n\t\t\tfor(Arguments::const_iterator j = action.arguments().begin(); j != action.arguments().end(); j++)\n\t\t\t{\tkdDebug() << \"Got argument...\" << endl;\n\t\t\t\tswitch((*j).type())\n\t\t\t\t{\tcase QVariant::Int: arg << (*j).toInt(); break;\n\t\t\t\t\tcase QVariant::CString: arg << (*j).toCString(); break;\n\t\t\t\t\tcase QVariant::StringList: arg << (*j).toStringList(); break;\n\t\t\t\t\tcase QVariant::UInt: arg << (*j).toUInt(); break;\n\t\t\t\t\tcase QVariant::Bool: arg << (*j).toBool(); break;\n\t\t\t\t\tcase QVariant::Double: arg << (*j).toDouble(); break;\n\t\t\t\t\tdefault: arg << (*j).toString(); break;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttheDC->send(program.utf8(), action.object().utf8(), action.method().prototypeNR().utf8(), data);\n\t\t}\n\t}\n}\n\nvoid IRKick::gotMessage(const QString &theRemote, const QString &theButton, int theRepeatCounter)\n{\n\tkdDebug() << \"Got message: \" << theRemote << \": \" << theButton << \" (\" << theRepeatCounter << \")\" << endl;\n\ttheTrayIcon->setPixmap(SmallIcon(\"irkickflash\"));\n\ttheFlashOff->start(200, true);\n\tif(npApp != QString::null)\n\t{\n\t\tQString theApp = npApp;\n\t\tnpApp = QString::null;\n\t\t\/\/ send notifier by DCOP to npApp\/npModule\/npMethod(theRemote, theButton);\n\t\tQByteArray data; QDataStream arg(data, IO_WriteOnly);\n\t\targ << theRemote << theButton;\n\t\tKApplication::dcopClient()->send(theApp.utf8(), npModule.utf8(), npMethod.utf8(), data);\n\t}\n\telse\n\t{\n\t\tif(currentModes[theRemote].isNull()) currentModes[theRemote] = \"\";\n\t\tIRAItList l = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton);\n\t\tif(currentModes[theRemote] != \"\")\n\t\t\tl += allActions.findByModeButton(Mode(theRemote, \"\"), theButton);\n\t\tbool doBefore = true, doAfter = false;\n\t\tfor(IRAItList::const_iterator i = l.begin(); i != l.end(); i++)\n\t\t\tif((**i).isModeChange() && !theRepeatCounter)\n\t\t\t{\t\/\/ mode switch\n\t\t\t\tcurrentModes[theRemote] = (**i).modeChange();\n\t\t\t\tMode mode = allModes.getMode(theRemote, (**i).modeChange());\n\t\t\t\tupdateModeIcons();\n\t\t\t\tdoBefore = (**i).doBefore();\n\t\t\t\tdoAfter = (**i).doAfter();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tfor(int after = 0; after < 2; after++)\n\t\t{\tif(doBefore && !after || doAfter && after)\n\t\t\t\tfor(IRAItList::const_iterator i = l.begin(); i != l.end(); i++)\n\t\t\t\t\tif(!(**i).isModeChange() && ((**i).repeat() || !theRepeatCounter))\n\t\t\t\t\t{\texecuteAction(**i);\n\t\t\t\t\t}\n\t\t\tif(!after && doAfter)\n\t\t\t{\tl = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton);\n\t\t\t\tif(currentModes[theRemote] != \"\")\n\t\t\t\t\tl += allActions.findByModeButton(Mode(theRemote, \"\"), theButton);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid IRKick::stealNextPress(QString app, QString module, QString method)\n{\n\tnpApp = app;\n\tnpModule = module;\n\tnpMethod = method;\n}\n\nvoid IRKick::dontStealNextPress()\n{\n\tnpApp = QString::null;\n}\n\n#include \"irkick.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2016-2021 Couchbase, Inc.\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#ifndef LIBCOUCHBASE_CAPI_COLLECTION_QUALIFIER_HH\n#define LIBCOUCHBASE_CAPI_COLLECTION_QUALIFIER_HH\n\n#include <cstddef>\n#include <cstdint>\n#include <string>\n#include <sstream>\n#include <stdexcept>\n\nnamespace lcb\n{\n\/**\n * @private\n *\/\nstruct collection_qualifier {\n collection_qualifier() = default;\n\n collection_qualifier(const char *scope_name, std::size_t scope_name_len, const char *collection_name,\n std::size_t collection_name_len)\n {\n if (!is_valid_collection_element(scope_name, scope_name_len)) {\n throw std::invalid_argument(\"invalid scope name\");\n }\n if (!is_valid_collection_element(collection_name, collection_name_len)) {\n throw std::invalid_argument(\"invalid collection name\");\n }\n\n if (scope_name != nullptr && scope_name_len > 0) {\n scope_.assign(scope_name, scope_name_len);\n }\n if (collection_name != nullptr && collection_name_len > 0) {\n collection_.assign(collection_name, collection_name_len);\n }\n std::stringstream ss;\n ss << (scope_.empty() ? \"_default\" : scope_);\n ss << '.';\n ss << (collection_.empty() ? \"_default\" : collection_);\n spec_ = ss.str();\n }\n\n const std::string &scope() const\n {\n return scope_;\n }\n\n const std::string &collection() const\n {\n return collection_;\n }\n\n bool has_default_scope() const\n {\n return scope_.empty() || scope_ == \"_default\";\n }\n\n bool is_default_collection() const\n {\n return has_default_scope() && (collection_.empty() || collection_ == \"_default\");\n }\n\n bool is_resolved() const\n {\n return resolved_;\n }\n\n std::uint32_t collection_id() const\n {\n return resolved_collection_id_;\n }\n\n void collection_id(std::uint32_t id)\n {\n resolved_collection_id_ = id;\n resolved_ = true;\n }\n\n const std::string &spec() const\n {\n return spec_;\n }\n\n private:\n static bool is_valid_collection_char(char ch)\n {\n if (ch >= 'A' && ch <= 'Z') {\n return true;\n }\n if (ch >= 'a' && ch <= 'z') {\n return true;\n }\n if (ch >= '0' && ch <= '9') {\n return true;\n }\n switch (ch) {\n case '_':\n case '-':\n case '%':\n return true;\n default:\n return false;\n }\n }\n\n static bool is_valid_collection_element(const char *element, size_t element_len)\n {\n if (element_len == 0 || element == nullptr) {\n \/* nullptr\/0 for collection is mapped to default collection *\/\n return true;\n }\n if (element_len < 1 || element_len > 30) {\n return false;\n }\n for (size_t i = 0; i < element_len; ++i) {\n if (!is_valid_collection_char(element[i])) {\n return false;\n }\n }\n return true;\n }\n\n std::string scope_{\"_default\"};\n std::string collection_{\"_default\"};\n std::string spec_{};\n std::uint32_t resolved_collection_id_{0};\n bool resolved_{false};\n};\n} \/\/ namespace lcb\n\n#endif \/\/ LIBCOUCHBASE_CAPI_COLLECTION_QUALIFIER_HH\n<commit_msg>CCBC-1525: remove stringstream in collection_qualifier<commit_after>\/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2016-2021 Couchbase, Inc.\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#ifndef LIBCOUCHBASE_CAPI_COLLECTION_QUALIFIER_HH\n#define LIBCOUCHBASE_CAPI_COLLECTION_QUALIFIER_HH\n\n#include <cstddef>\n#include <cstdint>\n#include <string>\n#include <stdexcept>\n\nnamespace lcb\n{\n\/**\n * @private\n *\/\nstruct collection_qualifier {\n collection_qualifier() = default;\n\n collection_qualifier(const char *scope_name, std::size_t scope_name_len, const char *collection_name,\n std::size_t collection_name_len)\n {\n if (!is_valid_collection_element(scope_name, scope_name_len)) {\n throw std::invalid_argument(\"invalid scope name\");\n }\n if (!is_valid_collection_element(collection_name, collection_name_len)) {\n throw std::invalid_argument(\"invalid collection name\");\n }\n\n if (scope_name != nullptr && scope_name_len > 0) {\n scope_.assign(scope_name, scope_name_len);\n }\n if (collection_name != nullptr && collection_name_len > 0) {\n collection_.assign(collection_name, collection_name_len);\n }\n\n spec_ = (scope_.empty() ? \"_default\" : scope_) +\n '.' +\n (collection_.empty() ? \"_default\" : collection_);\n }\n\n const std::string &scope() const\n {\n return scope_;\n }\n\n const std::string &collection() const\n {\n return collection_;\n }\n\n bool has_default_scope() const\n {\n return scope_.empty() || scope_ == \"_default\";\n }\n\n bool is_default_collection() const\n {\n return has_default_scope() && (collection_.empty() || collection_ == \"_default\");\n }\n\n bool is_resolved() const\n {\n return resolved_;\n }\n\n std::uint32_t collection_id() const\n {\n return resolved_collection_id_;\n }\n\n void collection_id(std::uint32_t id)\n {\n resolved_collection_id_ = id;\n resolved_ = true;\n }\n\n const std::string &spec() const\n {\n return spec_;\n }\n\n private:\n static bool is_valid_collection_char(char ch)\n {\n if (ch >= 'A' && ch <= 'Z') {\n return true;\n }\n if (ch >= 'a' && ch <= 'z') {\n return true;\n }\n if (ch >= '0' && ch <= '9') {\n return true;\n }\n switch (ch) {\n case '_':\n case '-':\n case '%':\n return true;\n default:\n return false;\n }\n }\n\n static bool is_valid_collection_element(const char *element, size_t element_len)\n {\n if (element_len == 0 || element == nullptr) {\n \/* nullptr\/0 for collection is mapped to default collection *\/\n return true;\n }\n if (element_len < 1 || element_len > 30) {\n return false;\n }\n for (size_t i = 0; i < element_len; ++i) {\n if (!is_valid_collection_char(element[i])) {\n return false;\n }\n }\n return true;\n }\n\n std::string scope_{\"_default\"};\n std::string collection_{\"_default\"};\n std::string spec_{};\n std::uint32_t resolved_collection_id_{0};\n bool resolved_{false};\n};\n} \/\/ namespace lcb\n\n#endif \/\/ LIBCOUCHBASE_CAPI_COLLECTION_QUALIFIER_HH\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_TOPOLOGY_IO_TIKZ_HH__\n#define ALEPH_TOPOLOGY_IO_TIKZ_HH__\n\n#include <fstream>\n#include <ostream>\n#include <stdexcept>\n#include <string>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\nnamespace io\n{\n\n\/**\n @class TikZ\n @brief Writes files as a TikZ picture\n\n This writer class uses coordinate information of a simplicial complex\n to represent its 1-skeleton, i.e. its vertices and edges. All data is\n stored as a picture for the TikZ LaTeX toolkit, resulting in a clean,\n modern output for publications.\n\n The output is configurable and permits the following adjustments:\n\n - point size\n - line width\n*\/\n\nclass TikZ\n{\npublic:\n\n \/** Writes the simplicial complex to a new file. *\/\n template <class SimplicialComplex, class Container> void operator()( const std::string& filename,\n const SimplicialComplex& K,\n const Container& container )\n {\n std::ofstream out( filename );\n if( !out )\n throw std::runtime_error( \"Unable to open output file\" );\n\n this->operator()( out, K, container );\n }\n\n \/** Writes the simplicial complex to a new output stream. *\/\n template <class SimplicialComplex, class Container> void operator()( std::ostream& out,\n const SimplicialComplex& K,\n const Container& container )\n {\n out << \"\\\\begin{tikzpicture}\\n\";\n\n \/\/ Render vertices as points ---------------------------------------\n\n out << \"% 0-simplices\\n\";\n\n for( auto&& s : K )\n {\n if( s.dimension() != 0 )\n continue;\n\n auto u = s[0]; \/\/ vertex\n auto p = container[u]; \/\/ coordinate\n\n if( p.size() >= 2 )\n writePoint( out, u, p );\n else\n throw std::runtime_error( \"Insufficient number of dimensions for storing coordinates\" );\n }\n\n \/\/ Render edges as lines -------------------------------------------\n\n out << \"% 1-simplices\\n\";\n\n for( auto&& s : K )\n {\n if( s.dimension() != 1 )\n continue;\n\n auto u = s[0]; \/\/ vertex\n auto v = s[1]; \/\/ vertex\n\n writeEdge(out, u, v);\n }\n\n out << \"\\\\end{tikzpicture}\\n\";\n }\n\n bool showVertexLabels() const noexcept\n {\n return _showVertexLabels;\n }\n\n void showVertexLabels( bool value ) noexcept\n {\n _showVertexLabels = value;\n }\n\n bool showBalls() const noexcept\n {\n return _showBalls;\n }\n\n void showBalls( bool value ) noexcept\n {\n _showBalls = value;\n }\n\n double ballRadius() const noexcept\n {\n return _ballRadius;\n }\n\n void ballRadius( double radius )\n {\n _ballRadius = radius;\n }\n\nprivate:\n\n \/**\n Auxiliary function for creating a point in TikZ format. The point\n will be shown as a circle of a given size.\n\n @param out Output stream to which the point will be appended\n @param v Vertex index\n @param p Coordinates for the vertex (only two dimensions will be used)\n *\/\n\n template <class Coordinate, class Index> void writePoint( std::ostream& out, Index v, Coordinate& p )\n {\n auto x = p[0];\n auto y = p[1];\n\n out << \"\\\\coordinate\";\n\n if( _showVertexLabels )\n out << \"[label=\" << _labelPosition << \":\" << std::to_string(v) << \"] \";\n\n out << \"(\" << v << \") at (\" << x << \",\" << y << \");\\n\";\n\n out << \"\\\\filldraw[\" << _pointColour << \"]\"\n << \" \" << \"(\" << v << \") circle (\" << _pointSize << _pointSizeUnit << \");\\n\";\n\n if( _showBalls )\n {\n out << \"\\\\fill[\" << _ballColour << \",\"\n << \" fill opacity=\" << _ballOpacity\n << \"]\"\n << \" \" << \"(\" << v << \") circle (\" << _ballRadius << \"cm\" << \");\\n\";\n }\n }\n\n \/**\n Auxiliary function for creating an edge in TikZ format. The edge\n will be shown as a line connecting the two vertices.\n\n @param out Output stream to which the edge will be appended\n @param u Source vertex index\n @param v Target vertex index\n *\/\n\n template <class Index> void writeEdge( std::ostream& out, Index u, Index v )\n {\n out << \"\\\\draw[\" << _lineColour << \",\"\n << \" line width=\" << _lineWidth << _lineWidthUnit\n <<\"]\"\n << \" \" << \"(\" << u << \") -- (\" << v << \");\\n\";\n }\n\n bool _showBalls = false;\n double _ballOpacity = 0.1;\n double _ballRadius = 0.0;\n std::string _ballColour = \"black\";\n\n bool _showVertexLabels = false;\n std::string _labelPosition = \"above\";\n\n \/\/ Node\/vertex configuration options ---------------------------------\n\n std::string _pointColour = \"black\";\n std::string _pointSizeUnit = \"pt\";\n double _pointSize = 1;\n\n \/\/ Line\/edge configuration options -----------------------------------\n\n std::string _lineColour = \"black\";\n std::string _lineWidthUnit = \"mm\";\n double _lineWidth = 0.50;\n};\n\n} \/\/ namespace io\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n\n#endif\n<commit_msg>Started adding support for rendering $2$-simplices<commit_after>#ifndef ALEPH_TOPOLOGY_IO_TIKZ_HH__\n#define ALEPH_TOPOLOGY_IO_TIKZ_HH__\n\n#include <fstream>\n#include <ostream>\n#include <stdexcept>\n#include <string>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\nnamespace io\n{\n\n\/**\n @class TikZ\n @brief Writes files as a TikZ picture\n\n This writer class uses coordinate information of a simplicial complex\n to represent its 1-skeleton, i.e. its vertices and edges. All data is\n stored as a picture for the TikZ LaTeX toolkit, resulting in a clean,\n modern output for publications.\n\n The output is configurable and permits the following adjustments:\n\n - point size\n - line width\n*\/\n\nclass TikZ\n{\npublic:\n\n \/** Writes the simplicial complex to a new file. *\/\n template <class SimplicialComplex, class Container> void operator()( const std::string& filename,\n const SimplicialComplex& K,\n const Container& container )\n {\n std::ofstream out( filename );\n if( !out )\n throw std::runtime_error( \"Unable to open output file\" );\n\n this->operator()( out, K, container );\n }\n\n \/** Writes the simplicial complex to a new output stream. *\/\n template <class SimplicialComplex, class Container> void operator()( std::ostream& out,\n const SimplicialComplex& K,\n const Container& container )\n {\n out << \"\\\\begin{tikzpicture}\\n\";\n\n \/\/ Render vertices as points ---------------------------------------\n\n out << \"% 0-simplices\\n\";\n\n for( auto&& s : K )\n {\n if( s.dimension() != 0 )\n continue;\n\n auto u = s[0]; \/\/ vertex\n auto p = container[u]; \/\/ coordinate\n\n if( p.size() >= 2 )\n writePoint( out, u, p );\n else\n throw std::runtime_error( \"Insufficient number of dimensions for storing coordinates\" );\n }\n\n \/\/ Render edges as lines -------------------------------------------\n\n out << \"% 1-simplices\\n\";\n\n for( auto&& s : K )\n {\n if( s.dimension() != 1 )\n continue;\n\n auto u = s[0]; \/\/ vertex\n auto v = s[1]; \/\/ vertex\n\n writeEdge(out, u, v);\n }\n\n \/\/ Render 2-simplices as triangles ----------------------------------\n\n if( _showTriangles )\n {\n out << \"% 2-simplices\\n\";\n\n for( auto&& s : K )\n {\n if( s.dimension() != 2 )\n continue;\n\n auto u = s[0];\n auto v = s[1];\n auto w = s[2];\n\n writeTriangle(out, u, v, w);\n }\n }\n\n out << \"\\\\end{tikzpicture}\\n\";\n }\n\n bool showVertexLabels() const noexcept\n {\n return _showVertexLabels;\n }\n\n void showVertexLabels( bool value ) noexcept\n {\n _showVertexLabels = value;\n }\n\n bool showBalls() const noexcept\n {\n return _showBalls;\n }\n\n void showBalls( bool value ) noexcept\n {\n _showBalls = value;\n }\n\n double ballRadius() const noexcept\n {\n return _ballRadius;\n }\n\n void ballRadius( double radius )\n {\n _ballRadius = radius;\n }\n\n bool showTriangles() const noexcept\n {\n return _showTriangles;\n }\n\n void showTriangles( bool value ) noexcept\n {\n _showTriangles = value;\n }\n\nprivate:\n\n \/**\n Auxiliary function for creating a point in TikZ format. The point\n will be shown as a circle of a given size.\n\n @param out Output stream to which the point will be appended\n @param v Vertex index\n @param p Coordinates for the vertex (only two dimensions will be used)\n *\/\n\n template <class Coordinate, class Index> void writePoint( std::ostream& out, Index v, Coordinate& p )\n {\n auto x = p[0];\n auto y = p[1];\n\n out << \"\\\\coordinate\";\n\n if( _showVertexLabels )\n out << \"[label=\" << _labelPosition << \":\" << std::to_string(v) << \"] \";\n\n out << \"(\" << v << \") at (\" << x << \",\" << y << \");\\n\";\n\n out << \"\\\\filldraw[\" << _pointColour << \"]\"\n << \" \" << \"(\" << v << \") circle (\" << _pointSize << _pointSizeUnit << \");\\n\";\n\n if( _showBalls )\n {\n out << \"\\\\fill[\" << _ballColour << \",\"\n << \" fill opacity=\" << _ballOpacity\n << \"]\"\n << \" \" << \"(\" << v << \") circle (\" << _ballRadius << \"cm\" << \");\\n\";\n }\n }\n\n \/**\n Auxiliary function for creating an edge in TikZ format. The edge\n will be shown as a line connecting the two vertices.\n\n @param out Output stream to which the edge will be appended\n @param u Source vertex index\n @param v Target vertex index\n *\/\n\n template <class Index> void writeEdge( std::ostream& out, Index u, Index v )\n {\n out << \"\\\\draw[\" << _lineColour << \",\"\n << \" line width=\" << _lineWidth << _lineWidthUnit\n <<\"]\"\n << \" \" << \"(\" << u << \") -- (\" << v << \");\\n\";\n }\n\n \/**\n Auxiliary function for creating a triangle in TikZ format. It is\n supposed to represent a 2-simplex.\n\n @param out Output stream to which the triangle will be appended\n @param u First vertex index\n @param v Second vertex index\n @param w Third vertex index\n *\/\n\n template <class Index> void writeTriangle( std::ostream& out, Index u, Index v, Index w )\n {\n out << \"\\\\filldraw[\" << _triangleColour << \",\"\n << \" fill opacity=\" << _triangleOpacity\n <<\"]\"\n << \" \" << \"(\" << u << \") -- (\" << v << \") -- (\" << w << \") -- cycle;\\n\";\n }\n\n bool _showBalls = false;\n double _ballOpacity = 0.1;\n double _ballRadius = 0.0;\n std::string _ballColour = \"black\";\n\n bool _showVertexLabels = false;\n std::string _labelPosition = \"above\";\n\n \/\/ Node\/vertex configuration options ---------------------------------\n\n std::string _pointColour = \"black\";\n std::string _pointSizeUnit = \"pt\";\n double _pointSize = 1;\n\n \/\/ Line\/edge configuration options -----------------------------------\n\n std::string _lineColour = \"black\";\n std::string _lineWidthUnit = \"mm\";\n double _lineWidth = 0.50;\n\n \/\/ Triangles ---------------------------------------------------------\n\n bool _showTriangles = false;\n std::string _triangleColour = \"black\";\n double _triangleOpacity = 0.50;\n};\n\n} \/\/ namespace io\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (C) 2003-2011 Victor Semionov\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and\/or other materials provided with the distribution.\r\n * * Neither the name of the copyright holder nor the names of the contributors\r\n * may be used to endorse or promote products derived from this software\r\n * without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include <windows.h>\r\n\r\n#include <gl\/gl.h>\r\n\r\n#ifdef _MSC_VER\r\n#define _USE_MATH_DEFINES\r\n#endif\r\n#include <math.h>\r\n\r\n#include \"Window.h\"\r\n#include \"Body.h\"\r\n#include \"Error.h\"\r\n#include \"Info.h\"\r\n\r\n\r\n\r\n#define NAME_FONT_NAME \"Arial\"\r\n#define NAME_FONT_SIZE_AT_H600 24\r\n#define NAME_FONT_SIZE (int)(NAME_FONT_SIZE_AT_H600*scrheight\/600)\r\n\r\n#define NAME_TEXT_COLOR_R 1.00f\r\n#define NAME_TEXT_COLOR_G 1.00f\r\n#define NAME_TEXT_COLOR_B 1.00f\r\n#define NAME_TEXT_COLOR_A 0.50f\r\n\r\n#define INFO_FONT_NAME \"Arial\"\r\n#define INFO_FONT_SIZE_AT_H600 16\r\n#define INFO_FONT_SIZE (int)(INFO_FONT_SIZE_AT_H600*scrheight\/600)\r\n\r\n#define INFO_TEXT_COLOR_R 1.00f\r\n#define INFO_TEXT_COLOR_G 1.00f\r\n#define INFO_TEXT_COLOR_B 1.00f\r\n#define INFO_TEXT_COLOR_A 0.50f\r\n\r\n#define SCREEN_SIZE_RATIO_STD (4.0f\/3.0f)\r\n#define FONT_SIZE_COEFF (4.6f\/3.0f) \/\/ do not change!\r\n#define SPACING_COEF 1.15f\r\n#define LINES_AFTER_NAME 1.125f\r\n\r\n\r\n#define WINDOW_COLOR_R 0.50f\r\n#define WINDOW_COLOR_G 0.50f\r\n#define WINDOW_COLOR_B 0.50f\r\n#define WINDOW_COLOR_A 0.25f\r\n\r\n#define MAX_FADE_TIME 3.0f\r\n#define FADE_TIME_RATIO 0.10f\r\n#define FADE_TIME(totaltime) min(MAX_FADE_TIME, (totaltime)*FADE_TIME_RATIO)\r\n\r\n\r\n#define WINDOW_BORDER_REL 0.0125f\r\n#define WINDOW_BORDER (int)(WINDOW_BORDER_REL*scrheight)\r\n\r\n#define MARGIN_TOP_REL 0.0250f\r\n#define MARGIN_BOTTOM_REL 0.0050f\r\n#define MARGIN_LEFT_REL (0.0200f*SCREEN_SIZE_RATIO_STD)\r\n#define MARGIN_LEFT_WIDTH (int)(MARGIN_LEFT_REL*scrheight)\r\n#define MARGIN_TOP_HEIGHT (int)(MARGIN_TOP_REL*scrheight)\r\n#define MARGIN_BOTTOM_HEIGHT (int)(MARGIN_BOTTOM_REL*scrheight)\r\n\r\n#define WINDOW_WIDTH_REL_Y (0.3050f*SCREEN_SIZE_RATIO_STD)\r\n#define WINDOW_WIDTH (int)(WINDOW_WIDTH_REL_Y*scrheight)\r\n#define WINDOW_HEIGHT (MARGIN_TOP_HEIGHT+MARGIN_BOTTOM_HEIGHT+(int)(NAME_FONT_SIZE*LINES_AFTER_NAME*SPACING_COEF*FONT_SIZE_COEFF)+3*(int)(INFO_FONT_SIZE*SPACING_COEF*FONT_SIZE_COEFF))\r\n\r\n#define WINDOW_POS_X1 (WINDOW_BORDER)\r\n#define WINDOW_POS_Y1 (WINDOW_BORDER)\r\n#define WINDOW_POS_X2 (WINDOW_POS_X1+WINDOW_WIDTH)\r\n#define WINDOW_POS_Y2 (WINDOW_POS_Y1+WINDOW_HEIGHT)\r\n\r\n\r\n\r\n\r\n\r\nCInfo::CInfo()\r\n{\r\n\tInit();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nCInfo::~CInfo()\r\n{\r\n\tFree();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Init()\r\n{\r\n\tloaded=false;\r\n\tscrwidth=0;\r\n\tscrheight=0;\r\n\twinlist=0;\r\n\tnamelist=infolist=0;\r\n\ttime=0;\r\n\tstarttime=endtime=0;\r\n\tfadetime=1;\r\n\talpha=0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Free()\r\n{\r\n\tnametext.Free();\r\n\tinfotext.Free();\r\n\tif (winlist)\r\n\t{\r\n\t\tif (glIsList(winlist))\r\n\t\t\tglDeleteLists(winlist,3);\r\n\t}\r\n\tInit();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CInfo::Load()\r\n{\r\n\tFree();\r\n\r\n\tscrwidth=CWindow::GetWidth();\r\n\tscrheight=CWindow::GetHeight();\r\n\r\n\twinlist=glGenLists(3);\r\n\tif (!winlist)\r\n\t{\r\n\t\tCError::LogError(WARNING_CODE,\"Unable to load planet info - failed to generate display lists.\");\r\n\t\tFree();\r\n\t\treturn false;\r\n\t}\r\n\tnamelist=winlist+1;\r\n\tinfolist=namelist+1;\r\n\r\n\tMakeWindow(winlist);\r\n\r\n\tloaded=true;\r\n\tloaded&=nametext.BuildFTFont(NAME_FONT_NAME,NAME_FONT_SIZE);\r\n\tloaded&=infotext.BuildFTFont(INFO_FONT_NAME,INFO_FONT_SIZE);\r\n\tif (!loaded)\r\n\t{\r\n\t\tCError::LogError(WARNING_CODE,\"Unable to load planet info - failed to load font.\");\r\n\t\tFree();\r\n\t}\r\n\r\n\treturn loaded;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::MakeWindow(int list)\r\n{\r\n\tglNewList(list,GL_COMPILE);\r\n\t{\r\n\t\tint l=WINDOW_POS_X1;\r\n\t\tint r=WINDOW_POS_X2;\r\n\t\tint b=WINDOW_POS_Y1;\r\n\t\tint t=WINDOW_POS_Y2;\r\n\t\tglDisable(GL_TEXTURE_2D);\r\n\t\tglLoadIdentity();\r\n\t\tglBegin(GL_QUADS);\r\n\t\t{\r\n\t\t\tglVertex2f((float)l,(float)b);\r\n\t\t\tglVertex2f((float)r,(float)b);\r\n\t\t\tglVertex2f((float)r,(float)t);\r\n\t\t\tglVertex2f((float)l,(float)t);\r\n\t\t}\r\n\t\tglEnd();\r\n\t}\r\n\tglEndList();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::GetNameCoords(const char *text, int *x, int *y)\r\n{\r\n\tfloat tw;\r\n\tnametext.GetTextSize(text,&tw,NULL);\r\n\tint th=NAME_FONT_SIZE;\r\n\r\n\tif (x) *x=WINDOW_POS_X1+(WINDOW_WIDTH-(int)tw)\/2;\r\n\tif (y) *y=WINDOW_POS_Y2-MARGIN_TOP_HEIGHT-th;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::GetInfoCoords(int linenum, int *x, int *y)\r\n{\r\n\tint ymargin=WINDOW_POS_Y2-MARGIN_TOP_HEIGHT;\r\n\r\n\tfloat nameheight;\r\n\tnametext.GetTextSize(\"\",NULL,&nameheight);\r\n\r\n\tfloat nameadd;\r\n\tnameadd=nameheight*SPACING_COEF*LINES_AFTER_NAME;\r\n\r\n\tint ioffset=INFO_FONT_SIZE;\r\n\r\n\tfloat th;\r\n\tinfotext.GetTextSize(\"\",NULL,&th);\r\n\tth*=SPACING_COEF;\r\n\tint thi=(int)th*(linenum-1);\r\n\r\n\tif (x) *x=WINDOW_POS_X1+MARGIN_LEFT_WIDTH;\r\n\tif (y) *y=ymargin-(int)nameadd-ioffset-thi;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::MakeName(int list, char *targetname)\r\n{\r\n\tif (!targetname) return;\r\n\tif (*targetname==' ') targetname++;\r\n\tint x,y;\r\n\tGetNameCoords(targetname,&x,&y);\r\n\tglNewList(list,GL_COMPILE);\r\n\t{\r\n\t\tglEnable(GL_TEXTURE_2D);\r\n\t\tglLoadIdentity();\r\n\t\tglTranslatef((float)x,(float)y,0);\r\n\t\tnametext.Print(targetname);\r\n\t}\r\n\tglEndList();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::MakeInfoLine(int linenum, char *line)\r\n{\r\n\tint x,y;\r\n\tGetInfoCoords(linenum,&x,&y);\r\n\tglPushMatrix();\r\n\tglTranslatef((float)x,(float)y,0);\r\n\tinfotext.Print(line);\r\n\tglPopMatrix();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::MakeInfo(int list, CBody *targetbody)\r\n{\r\n\tbool star=(targetbody==NULL);\r\n\tif (star) targetbody=CBody::bodycache[0];\r\n\tglNewList(list,GL_COMPILE);\r\n\t{\r\n\t\tint n=0;\r\n\t\tglEnable(GL_TEXTURE_2D);\r\n\t\tglLoadIdentity();\r\n\t\tif (star)\r\n\t\t{\r\n\t\t\tchar line[64];\r\n\t\t\tn++;\r\n\t\t\tsprintf(line,\"star name: %s\",targetbody->name);\r\n\t\t\tMakeInfoLine(n,line);\r\n\t\t}\r\n\t\tfor (int i=0;i<targetbody->info.numlines;i++)\r\n\t\t{\r\n\t\t\tif (targetbody->info.textlines[i][0]=='\/') continue;\r\n\t\t\tn++;\r\n\t\t\tMakeInfoLine(n,targetbody->info.textlines[i]);\r\n\t\t}\r\n\t}\r\n\tglEndList();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Start(float seconds, float duration, char *targetname, CBody *targetbody)\r\n{\r\n\tif (!loaded)\r\n\t\treturn;\r\n\tchar name[32];\r\n\tstrcpy(name,targetname);\r\n\tint l=strlen(name);\r\n\tfor (int i=0;i<l;i++)\r\n\t\tif (name[i]=='_')\r\n\t\t\tname[i]=' ';\r\n\tstarttime=seconds;\r\n\tendtime=starttime+duration;\r\n\tfadetime=FADE_TIME(duration);\r\n\tMakeName(namelist,name);\r\n\tMakeInfo(infolist,targetbody);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Update(float seconds)\r\n{\r\n\ttime=seconds;\r\n\tif (time<(endtime-fadetime))\r\n\t\talpha=min(1,(time-starttime)\/fadetime);\r\n\telse\r\n\t\talpha=max(0,(endtime-time)\/fadetime);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Restart()\r\n{\r\n\tstarttime-=time;\r\n\tendtime-=time;\r\n\ttime=0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Draw()\r\n{\r\n\tif (!alpha || !loaded)\r\n\t\treturn;\r\n\r\n\tglDisable(GL_LIGHTING);\r\n\tglDisable(GL_DEPTH_TEST);\r\n\tglDisable(GL_CULL_FACE);\r\n\tglEnable(GL_BLEND);\r\n\r\n\tglColor4f(WINDOW_COLOR_R,WINDOW_COLOR_G,WINDOW_COLOR_B,WINDOW_COLOR_A*alpha);\r\n\tglCallList(winlist);\r\n\r\n\tglColor4f(NAME_TEXT_COLOR_R,NAME_TEXT_COLOR_G,NAME_TEXT_COLOR_B,NAME_TEXT_COLOR_A*alpha);\r\n\tglCallList(namelist);\r\n\r\n\tglColor4f(INFO_TEXT_COLOR_R,INFO_TEXT_COLOR_G,INFO_TEXT_COLOR_B,INFO_TEXT_COLOR_A*alpha);\r\n\tglCallList(infolist);\r\n}\r\n<commit_msg>Refactoring - trim underscores and spaces from body names.<commit_after>\/*\r\n * Copyright (C) 2003-2011 Victor Semionov\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and\/or other materials provided with the distribution.\r\n * * Neither the name of the copyright holder nor the names of the contributors\r\n * may be used to endorse or promote products derived from this software\r\n * without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include <windows.h>\r\n\r\n#include <gl\/gl.h>\r\n\r\n#ifdef _MSC_VER\r\n#define _USE_MATH_DEFINES\r\n#endif\r\n#include <math.h>\r\n\r\n#include \"Window.h\"\r\n#include \"Body.h\"\r\n#include \"Error.h\"\r\n#include \"Info.h\"\r\n\r\n\r\n\r\n#define NAME_FONT_NAME \"Arial\"\r\n#define NAME_FONT_SIZE_AT_H600 24\r\n#define NAME_FONT_SIZE (int)(NAME_FONT_SIZE_AT_H600*scrheight\/600)\r\n\r\n#define NAME_TEXT_COLOR_R 1.00f\r\n#define NAME_TEXT_COLOR_G 1.00f\r\n#define NAME_TEXT_COLOR_B 1.00f\r\n#define NAME_TEXT_COLOR_A 0.50f\r\n\r\n#define INFO_FONT_NAME \"Arial\"\r\n#define INFO_FONT_SIZE_AT_H600 16\r\n#define INFO_FONT_SIZE (int)(INFO_FONT_SIZE_AT_H600*scrheight\/600)\r\n\r\n#define INFO_TEXT_COLOR_R 1.00f\r\n#define INFO_TEXT_COLOR_G 1.00f\r\n#define INFO_TEXT_COLOR_B 1.00f\r\n#define INFO_TEXT_COLOR_A 0.50f\r\n\r\n#define SCREEN_SIZE_RATIO_STD (4.0f\/3.0f)\r\n#define FONT_SIZE_COEFF (4.6f\/3.0f) \/\/ do not change!\r\n#define SPACING_COEF 1.15f\r\n#define LINES_AFTER_NAME 1.125f\r\n\r\n\r\n#define WINDOW_COLOR_R 0.50f\r\n#define WINDOW_COLOR_G 0.50f\r\n#define WINDOW_COLOR_B 0.50f\r\n#define WINDOW_COLOR_A 0.25f\r\n\r\n#define MAX_FADE_TIME 3.0f\r\n#define FADE_TIME_RATIO 0.10f\r\n#define FADE_TIME(totaltime) min(MAX_FADE_TIME, (totaltime)*FADE_TIME_RATIO)\r\n\r\n\r\n#define WINDOW_BORDER_REL 0.0125f\r\n#define WINDOW_BORDER (int)(WINDOW_BORDER_REL*scrheight)\r\n\r\n#define MARGIN_TOP_REL 0.0250f\r\n#define MARGIN_BOTTOM_REL 0.0050f\r\n#define MARGIN_LEFT_REL (0.0200f*SCREEN_SIZE_RATIO_STD)\r\n#define MARGIN_LEFT_WIDTH (int)(MARGIN_LEFT_REL*scrheight)\r\n#define MARGIN_TOP_HEIGHT (int)(MARGIN_TOP_REL*scrheight)\r\n#define MARGIN_BOTTOM_HEIGHT (int)(MARGIN_BOTTOM_REL*scrheight)\r\n\r\n#define WINDOW_WIDTH_REL_Y (0.3050f*SCREEN_SIZE_RATIO_STD)\r\n#define WINDOW_WIDTH (int)(WINDOW_WIDTH_REL_Y*scrheight)\r\n#define WINDOW_HEIGHT (MARGIN_TOP_HEIGHT+MARGIN_BOTTOM_HEIGHT+(int)(NAME_FONT_SIZE*LINES_AFTER_NAME*SPACING_COEF*FONT_SIZE_COEFF)+3*(int)(INFO_FONT_SIZE*SPACING_COEF*FONT_SIZE_COEFF))\r\n\r\n#define WINDOW_POS_X1 (WINDOW_BORDER)\r\n#define WINDOW_POS_Y1 (WINDOW_BORDER)\r\n#define WINDOW_POS_X2 (WINDOW_POS_X1+WINDOW_WIDTH)\r\n#define WINDOW_POS_Y2 (WINDOW_POS_Y1+WINDOW_HEIGHT)\r\n\r\n\r\n\r\n\r\n\r\nCInfo::CInfo()\r\n{\r\n\tInit();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nCInfo::~CInfo()\r\n{\r\n\tFree();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Init()\r\n{\r\n\tloaded=false;\r\n\tscrwidth=0;\r\n\tscrheight=0;\r\n\twinlist=0;\r\n\tnamelist=infolist=0;\r\n\ttime=0;\r\n\tstarttime=endtime=0;\r\n\tfadetime=1;\r\n\talpha=0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Free()\r\n{\r\n\tnametext.Free();\r\n\tinfotext.Free();\r\n\tif (winlist)\r\n\t{\r\n\t\tif (glIsList(winlist))\r\n\t\t\tglDeleteLists(winlist,3);\r\n\t}\r\n\tInit();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CInfo::Load()\r\n{\r\n\tFree();\r\n\r\n\tscrwidth=CWindow::GetWidth();\r\n\tscrheight=CWindow::GetHeight();\r\n\r\n\twinlist=glGenLists(3);\r\n\tif (!winlist)\r\n\t{\r\n\t\tCError::LogError(WARNING_CODE,\"Unable to load planet info - failed to generate display lists.\");\r\n\t\tFree();\r\n\t\treturn false;\r\n\t}\r\n\tnamelist=winlist+1;\r\n\tinfolist=namelist+1;\r\n\r\n\tMakeWindow(winlist);\r\n\r\n\tloaded=true;\r\n\tloaded&=nametext.BuildFTFont(NAME_FONT_NAME,NAME_FONT_SIZE);\r\n\tloaded&=infotext.BuildFTFont(INFO_FONT_NAME,INFO_FONT_SIZE);\r\n\tif (!loaded)\r\n\t{\r\n\t\tCError::LogError(WARNING_CODE,\"Unable to load planet info - failed to load font.\");\r\n\t\tFree();\r\n\t}\r\n\r\n\treturn loaded;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::MakeWindow(int list)\r\n{\r\n\tglNewList(list,GL_COMPILE);\r\n\t{\r\n\t\tint l=WINDOW_POS_X1;\r\n\t\tint r=WINDOW_POS_X2;\r\n\t\tint b=WINDOW_POS_Y1;\r\n\t\tint t=WINDOW_POS_Y2;\r\n\t\tglDisable(GL_TEXTURE_2D);\r\n\t\tglLoadIdentity();\r\n\t\tglBegin(GL_QUADS);\r\n\t\t{\r\n\t\t\tglVertex2f((float)l,(float)b);\r\n\t\t\tglVertex2f((float)r,(float)b);\r\n\t\t\tglVertex2f((float)r,(float)t);\r\n\t\t\tglVertex2f((float)l,(float)t);\r\n\t\t}\r\n\t\tglEnd();\r\n\t}\r\n\tglEndList();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::GetNameCoords(const char *text, int *x, int *y)\r\n{\r\n\tfloat tw;\r\n\tnametext.GetTextSize(text,&tw,NULL);\r\n\tint th=NAME_FONT_SIZE;\r\n\r\n\tif (x) *x=WINDOW_POS_X1+(WINDOW_WIDTH-(int)tw)\/2;\r\n\tif (y) *y=WINDOW_POS_Y2-MARGIN_TOP_HEIGHT-th;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::GetInfoCoords(int linenum, int *x, int *y)\r\n{\r\n\tint ymargin=WINDOW_POS_Y2-MARGIN_TOP_HEIGHT;\r\n\r\n\tfloat nameheight;\r\n\tnametext.GetTextSize(\"\",NULL,&nameheight);\r\n\r\n\tfloat nameadd;\r\n\tnameadd=nameheight*SPACING_COEF*LINES_AFTER_NAME;\r\n\r\n\tint ioffset=INFO_FONT_SIZE;\r\n\r\n\tfloat th;\r\n\tinfotext.GetTextSize(\"\",NULL,&th);\r\n\tth*=SPACING_COEF;\r\n\tint thi=(int)th*(linenum-1);\r\n\r\n\tif (x) *x=WINDOW_POS_X1+MARGIN_LEFT_WIDTH;\r\n\tif (y) *y=ymargin-(int)nameadd-ioffset-thi;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::MakeName(int list, char *targetname)\r\n{\r\n\tif (!targetname) return;\r\n\tint x,y;\r\n\tGetNameCoords(targetname,&x,&y);\r\n\tglNewList(list,GL_COMPILE);\r\n\t{\r\n\t\tglEnable(GL_TEXTURE_2D);\r\n\t\tglLoadIdentity();\r\n\t\tglTranslatef((float)x,(float)y,0);\r\n\t\tnametext.Print(targetname);\r\n\t}\r\n\tglEndList();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::MakeInfoLine(int linenum, char *line)\r\n{\r\n\tint x,y;\r\n\tGetInfoCoords(linenum,&x,&y);\r\n\tglPushMatrix();\r\n\tglTranslatef((float)x,(float)y,0);\r\n\tinfotext.Print(line);\r\n\tglPopMatrix();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::MakeInfo(int list, CBody *targetbody)\r\n{\r\n\tbool star=(targetbody==NULL);\r\n\tif (star) targetbody=CBody::bodycache[0];\r\n\tglNewList(list,GL_COMPILE);\r\n\t{\r\n\t\tint n=0;\r\n\t\tglEnable(GL_TEXTURE_2D);\r\n\t\tglLoadIdentity();\r\n\t\tif (star)\r\n\t\t{\r\n\t\t\tchar line[64];\r\n\t\t\tn++;\r\n\t\t\tsprintf(line,\"star name: %s\",targetbody->name);\r\n\t\t\tMakeInfoLine(n,line);\r\n\t\t}\r\n\t\tfor (int i=0;i<targetbody->info.numlines;i++)\r\n\t\t{\r\n\t\t\tif (targetbody->info.textlines[i][0]=='\/') continue;\r\n\t\t\tn++;\r\n\t\t\tMakeInfoLine(n,targetbody->info.textlines[i]);\r\n\t\t}\r\n\t}\r\n\tglEndList();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Start(float seconds, float duration, char *targetname, CBody *targetbody)\r\n{\r\n\tint l;\r\n\tint i;\r\n\tint idx;\r\n\tchar name[32];\r\n\tif (!loaded)\r\n\t\treturn;\r\n\tstrcpy(name,targetname);\r\n\tl=strlen(name);\r\n\tfor (i=0;i<l;i++)\r\n\t\tif (name[i]=='_')\r\n\t\t\tname[i]=' ';\r\n\tfor (i=l-1;i>=0;i--)\r\n\t{\r\n\t\tif (name[i]!=' ')\r\n\t\t\tbreak;\r\n\t\tname[i]=0;\r\n\t}\r\n\tfor (idx=0;idx<l;idx++)\r\n\t\tif (name[idx]!=' ')\r\n\t\t\tbreak;\r\n\tstarttime=seconds;\r\n\tendtime=starttime+duration;\r\n\tfadetime=FADE_TIME(duration);\r\n\tMakeName(namelist,name+idx);\r\n\tMakeInfo(infolist,targetbody);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Update(float seconds)\r\n{\r\n\ttime=seconds;\r\n\tif (time<(endtime-fadetime))\r\n\t\talpha=min(1,(time-starttime)\/fadetime);\r\n\telse\r\n\t\talpha=max(0,(endtime-time)\/fadetime);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Restart()\r\n{\r\n\tstarttime-=time;\r\n\tendtime-=time;\r\n\ttime=0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CInfo::Draw()\r\n{\r\n\tif (!alpha || !loaded)\r\n\t\treturn;\r\n\r\n\tglDisable(GL_LIGHTING);\r\n\tglDisable(GL_DEPTH_TEST);\r\n\tglDisable(GL_CULL_FACE);\r\n\tglEnable(GL_BLEND);\r\n\r\n\tglColor4f(WINDOW_COLOR_R,WINDOW_COLOR_G,WINDOW_COLOR_B,WINDOW_COLOR_A*alpha);\r\n\tglCallList(winlist);\r\n\r\n\tglColor4f(NAME_TEXT_COLOR_R,NAME_TEXT_COLOR_G,NAME_TEXT_COLOR_B,NAME_TEXT_COLOR_A*alpha);\r\n\tglCallList(namelist);\r\n\r\n\tglColor4f(INFO_TEXT_COLOR_R,INFO_TEXT_COLOR_G,INFO_TEXT_COLOR_B,INFO_TEXT_COLOR_A*alpha);\r\n\tglCallList(infolist);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"mpdas.h\"\n\n#define APIKEY\t\t\"a0ed2629d3d28606f67d7214c916788d\"\n#define\tSECRET\t\t\"295f31c5d28215215b1503fb0327cc01\"\n#define CURL_MAX_RETRIES 3\n#define CURL_RETRY_DELAY 3 \/\/ Seconds\n\nCAudioScrobbler* AudioScrobbler = 0;\n\n#define CLEANUP()\t_response.clear()\n\nsize_t writecb(void* ptr, size_t size, size_t nmemb, void *stream)\n{\n AudioScrobbler->ReportResponse((char*)ptr, size*nmemb);\n return size*nmemb;\n}\n\nCAudioScrobbler::CAudioScrobbler()\n{\n _failcount = 0;\n _authed = false;\n _response = \"\";\n _handle = curl_easy_init();\n if(!_handle) {\n\teprintf(\"%s\", \"Could not initialize CURL.\");\n\texit(EXIT_FAILURE);\n }\n}\n\nCAudioScrobbler::~CAudioScrobbler()\n{\n curl_easy_cleanup(_handle);\n curl_global_cleanup();\n}\n\nstd::string CAudioScrobbler::GetServiceURL()\n{\n if(Config->getService() == LibreFm) {\n\treturn \"https:\/\/libre.fm\/2.0\/\";\n }\n return \"http:\/\/ws.audioscrobbler.com\/2.0\/\";\n}\n\nvoid CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0)\n{\n curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0);\n curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1);\n curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb);\n curl_easy_setopt(_handle, CURLOPT_TIMEOUT, 10);\n\n if(postfields) {\n\tcurl_easy_setopt(_handle, CURLOPT_POST, 1);\n\tcurl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields);\n }\n else\n\tcurl_easy_setopt(_handle, CURLOPT_POST, 0);\n if(errbuf)\n\tcurl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf);\n\n curl_easy_setopt(_handle, CURLOPT_URL, url.c_str());\n CURLcode res = curl_easy_perform(_handle);\n\n \/\/ Sometimes last.fm likes to just timeout for no reason, leaving us hanging.\n \/\/ If this happens, retry a few times with a small delay.\n if (res != CURLE_OK) {\n eprintf(\"libcurl: (%d)\", res);\n eprintf(\"%s\", curl_easy_strerror(res));\n eprintf(\"Will retry %d times with a %d second delay.\", CURL_MAX_RETRIES, CURL_RETRY_DELAY);\n\n int retries = 0;\n do {\n sleep(CURL_RETRY_DELAY);\n retries++;\n eprintf(\"Retry %d\/%d\", retries, CURL_MAX_RETRIES);\n res = curl_easy_perform(_handle);\n } while (res != CURLE_OK || retries < CURL_MAX_RETRIES);\n\n eprintf(\"Failed after %d retries, try again later.\", CURL_MAX_RETRIES);\n }\n}\n\n\nvoid CAudioScrobbler::ReportResponse(char* buf, size_t size)\n{\n _response.append(buf);\n}\n\nstd::string CAudioScrobbler::CreateScrobbleMessage(int index, const CacheEntry& entry)\n{\n const Song& song = entry.getSong();\n std::ostringstream msg, sigmsg ;\n std::string artist, title, album, array = \"=\";\n\n char* temp = 0;\n temp = curl_easy_escape(_handle, song.getArtist().c_str(), song.getArtist().length());\n artist = temp;\n curl_free(temp);\n temp = curl_easy_escape(_handle, song.getTitle().c_str(), song.getTitle().length());\n title = temp;\n curl_free(temp);\n temp = curl_easy_escape(_handle, song.getAlbum().c_str(), song.getAlbum().length());\n album = temp;\n curl_free(temp);\n\n msg << \"&album\" << array << album;\n msg << \"&api_key=\" << APIKEY;\n msg << \"&artist\" << array << artist;\n msg << \"&duration\" << array << song.getDuration();\n msg << \"&method=track.Scrobble\";\n msg << \"×tamp\" << array << entry.getStartTime();\n msg << \"&track\" << array << title;\n msg << \"&sk=\" << _sessionid;\n\n array = \"\";\n\n sigmsg << \"album\" << array << song.getAlbum();\n sigmsg << \"api_key\" << APIKEY;\n sigmsg << \"artist\" << array << song.getArtist();\n sigmsg << \"duration\" << array << song.getDuration();\n sigmsg << \"methodtrack.Scrobble\";\n sigmsg << \"sk\" << _sessionid;\n sigmsg << \"timestamp\" << array << entry.getStartTime();\n sigmsg << \"track\" << array << song.getTitle();\n sigmsg << SECRET;\n\n std::string sighash(md5sum((char*)\"%s\", sigmsg.str().c_str()));\n msg << \"&api_sig=\" << sighash;\n\n return msg.str();\n}\n\nvoid CAudioScrobbler::Failure()\n{\n _failcount += 1;\n if(_failcount >= 3) {\n\teprintf(\"%s\", \"Re-Handshaking!\");\n\t_failcount = 0;\n\tHandshake();\n }\n}\n\nbool CAudioScrobbler::CheckFailure(std::string response)\n{\n bool retval = false;\n\n size_t start, end;\n start = _response.find(\"<error code=\\\"\")+13;\n end = _response.find(\">\", start)-1;\n std::string errorcode = _response.substr(start, end-start);\n int code = strtol(errorcode.c_str(), 0, 10);\n\n eprintf(\"%s%i\", \"Code: \", code);\n\n switch(code) {\n\tcase 3:\n\t eprintf(\"Invalid Method. This should not happen.\");\n\t retval = true;\n\t break;\n\tcase 4:\n\t eprintf(\"Authentication failed. Please check your login data.\");\n\t exit(EXIT_FAILURE);\n\tcase 9:\n\t eprintf(\"Invalid session key. Re-authenticating.\");\n\t retval = true;\n\t _failcount = 3;\n\t break;\n\tcase 10:\n\t eprintf(\"Invalid API-Key. Let's bugger off.\");\n\t exit(EXIT_FAILURE);\n\tcase 16:\n\t eprintf(\"The service is temporarily unavailable, we will try again later..\");\n\t retval = true;\n\t break;\n\tcase 26:\n\t eprintf(\"Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm\");\n\t exit(EXIT_FAILURE);\n }\n\n return retval;\n}\n\nbool CAudioScrobbler::Scrobble(const CacheEntry& entry)\n{\n bool retval = false;\n if(!_authed) {\n\teprintf(\"Handshake hasn't been done yet.\");\n\tHandshake();\n\treturn retval;\n }\n iprintf(\"Scrobbling: %s - %s\", entry.getSong().getArtist().c_str(), entry.getSong().getTitle().c_str());\n\n OpenURL(GetServiceURL(), CreateScrobbleMessage(0, entry).c_str());\n if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"Scrobbled successfully.\");\n\tretval = true;\n }\n else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while scrobbling:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t Failure();\n }\n CLEANUP();\n\n return retval;\n}\n\nbool CAudioScrobbler::LoveTrack(const Song& song, bool unlove)\n{\n bool retval = false;\n\n char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);\n char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);\n\n std::ostringstream query, sig;\n query << (unlove ? \"method=track.unlove&\" : \"method=track.love&\")\n\t<< \"&track=\" << title\n\t<< \"&artist=\" << artist\n\t<< \"&api_key=\" << APIKEY\n\t<< \"&sk=\" << _sessionid;\n\n curl_free(artist);\n curl_free(title);\n\n sig << \"api_key\" << APIKEY\n\t<< \"artist\" << song.getArtist()\n\t<< \"method\" << (unlove ? \"track.unlove\" : \"track.love\")\n\t<< \"sk\" << _sessionid\n\t<< \"track\" << song.getTitle()\n\t<< SECRET;\n\n std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n query << \"&api_sig=\" << sighash;\n\n OpenURL(GetServiceURL(), query.str().c_str());\n\n if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"(Un)loved track successfully.\");\n\tretval = true;\n }\n else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while (un)loving the currently playing track:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t Failure();\n }\n\n CLEANUP();\n return retval;\n}\n\nbool CAudioScrobbler::SendNowPlaying(const Song& song)\n{\n bool retval = false;\n\n char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);\n char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);\n char* album = song.getAlbum().empty() ? 0 : curl_easy_escape(_handle, song.getAlbum().c_str(), 0);\n\n std::ostringstream query, sig;\n query << \"method=track.updateNowPlaying&track=\" << title\n\t<< \"&artist=\" << artist\n\t<< \"&duration=\" << song.getDuration()\n\t<< \"&api_key=\" << APIKEY\n\t<< \"&sk=\" << _sessionid;\n if(album) {\n\tquery << \"&album=\" << album;\n\tsig << \"album\" << song.getAlbum();\n }\n\n curl_free(artist);\n curl_free(title);\n curl_free(album);\n\n sig << \"api_key\" << APIKEY\n\t<< \"artist\" << song.getArtist()\n\t<< \"duration\" << song.getDuration()\n\t<< \"methodtrack.updateNowPlaying\"\n\t<< \"sk\" << _sessionid\n\t<< \"track\" << song.getTitle()\n\t<< SECRET;\n\n std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n query << \"&api_sig=\" << sighash;\n\n OpenURL(GetServiceURL(), query.str().c_str());\n\n if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"Updated \\\"Now Playing\\\" status successfully.\");\n\tretval = true;\n }\n else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while updating the currently playing track:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t Failure();\n }\n\n CLEANUP();\n return retval;\n}\n\nvoid CAudioScrobbler::Handshake()\n{\n std::string username=\"\";\n for(unsigned int i = 0; i < Config->getLUsername().length(); i++) {\n\tusername.append(1, tolower(Config->getLUsername().c_str()[i]));\n }\n std::string authtoken(md5sum((char*)\"%s%s\", username.c_str(), Config->getLPassword().c_str()));\n\n std::ostringstream query, sig;\n query << \"method=auth.getMobileSession&username=\" << username << \"&authToken=\" << authtoken << \"&api_key=\" << APIKEY;\n\n sig << \"api_key\" << APIKEY << \"authToken\" << authtoken << \"methodauth.getMobileSessionusername\" << username << SECRET;\n std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n query << \"&api_sig=\" << sighash;\n\n OpenURL(GetServiceURL(), query.str().c_str());\n\n if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tsize_t start, end;\n\tstart = _response.find(\"<key>\") + 5;\n\tend = _response.find(\"<\/key>\");\n\t_sessionid = _response.substr(start, end-start);\n\tiprintf(\"%s%s\", \"Last.fm handshake successful. SessionID: \", _sessionid.c_str());\n\t_authed = true;\n }\n else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\tCheckFailure(_response);\n\texit(EXIT_FAILURE);\n }\n\n CLEANUP();\n}\n<commit_msg>|| -> &&<commit_after>#include \"mpdas.h\"\n\n#define APIKEY\t\t\"a0ed2629d3d28606f67d7214c916788d\"\n#define\tSECRET\t\t\"295f31c5d28215215b1503fb0327cc01\"\n#define CURL_MAX_RETRIES 3\n#define CURL_RETRY_DELAY 3 \/\/ Seconds\n\nCAudioScrobbler* AudioScrobbler = 0;\n\n#define CLEANUP()\t_response.clear()\n\nsize_t writecb(void* ptr, size_t size, size_t nmemb, void *stream)\n{\n AudioScrobbler->ReportResponse((char*)ptr, size*nmemb);\n return size*nmemb;\n}\n\nCAudioScrobbler::CAudioScrobbler()\n{\n _failcount = 0;\n _authed = false;\n _response = \"\";\n _handle = curl_easy_init();\n if(!_handle) {\n\teprintf(\"%s\", \"Could not initialize CURL.\");\n\texit(EXIT_FAILURE);\n }\n}\n\nCAudioScrobbler::~CAudioScrobbler()\n{\n curl_easy_cleanup(_handle);\n curl_global_cleanup();\n}\n\nstd::string CAudioScrobbler::GetServiceURL()\n{\n if(Config->getService() == LibreFm) {\n\treturn \"https:\/\/libre.fm\/2.0\/\";\n }\n return \"http:\/\/ws.audioscrobbler.com\/2.0\/\";\n}\n\nvoid CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0)\n{\n curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0);\n curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1);\n curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb);\n curl_easy_setopt(_handle, CURLOPT_TIMEOUT, 10);\n\n if(postfields) {\n\tcurl_easy_setopt(_handle, CURLOPT_POST, 1);\n\tcurl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields);\n }\n else\n\tcurl_easy_setopt(_handle, CURLOPT_POST, 0);\n if(errbuf)\n\tcurl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf);\n\n curl_easy_setopt(_handle, CURLOPT_URL, url.c_str());\n CURLcode res = curl_easy_perform(_handle);\n\n \/\/ Sometimes last.fm likes to just timeout for no reason, leaving us hanging.\n \/\/ If this happens, retry a few times with a small delay.\n if (res != CURLE_OK) {\n eprintf(\"libcurl: (%d)\", res);\n eprintf(\"%s\", curl_easy_strerror(res));\n eprintf(\"Will retry %d times with a %d second delay.\", CURL_MAX_RETRIES, CURL_RETRY_DELAY);\n\n int retries = 0;\n do {\n sleep(CURL_RETRY_DELAY);\n retries++;\n eprintf(\"Retry %d\/%d\", retries, CURL_MAX_RETRIES);\n res = curl_easy_perform(_handle);\n } while (res != CURLE_OK && retries < CURL_MAX_RETRIES);\n\n eprintf(\"Failed after %d retries, try again later.\", CURL_MAX_RETRIES);\n }\n}\n\n\nvoid CAudioScrobbler::ReportResponse(char* buf, size_t size)\n{\n _response.append(buf);\n}\n\nstd::string CAudioScrobbler::CreateScrobbleMessage(int index, const CacheEntry& entry)\n{\n const Song& song = entry.getSong();\n std::ostringstream msg, sigmsg ;\n std::string artist, title, album, array = \"=\";\n\n char* temp = 0;\n temp = curl_easy_escape(_handle, song.getArtist().c_str(), song.getArtist().length());\n artist = temp;\n curl_free(temp);\n temp = curl_easy_escape(_handle, song.getTitle().c_str(), song.getTitle().length());\n title = temp;\n curl_free(temp);\n temp = curl_easy_escape(_handle, song.getAlbum().c_str(), song.getAlbum().length());\n album = temp;\n curl_free(temp);\n\n msg << \"&album\" << array << album;\n msg << \"&api_key=\" << APIKEY;\n msg << \"&artist\" << array << artist;\n msg << \"&duration\" << array << song.getDuration();\n msg << \"&method=track.Scrobble\";\n msg << \"×tamp\" << array << entry.getStartTime();\n msg << \"&track\" << array << title;\n msg << \"&sk=\" << _sessionid;\n\n array = \"\";\n\n sigmsg << \"album\" << array << song.getAlbum();\n sigmsg << \"api_key\" << APIKEY;\n sigmsg << \"artist\" << array << song.getArtist();\n sigmsg << \"duration\" << array << song.getDuration();\n sigmsg << \"methodtrack.Scrobble\";\n sigmsg << \"sk\" << _sessionid;\n sigmsg << \"timestamp\" << array << entry.getStartTime();\n sigmsg << \"track\" << array << song.getTitle();\n sigmsg << SECRET;\n\n std::string sighash(md5sum((char*)\"%s\", sigmsg.str().c_str()));\n msg << \"&api_sig=\" << sighash;\n\n return msg.str();\n}\n\nvoid CAudioScrobbler::Failure()\n{\n _failcount += 1;\n if(_failcount >= 3) {\n\teprintf(\"%s\", \"Re-Handshaking!\");\n\t_failcount = 0;\n\tHandshake();\n }\n}\n\nbool CAudioScrobbler::CheckFailure(std::string response)\n{\n bool retval = false;\n\n size_t start, end;\n start = _response.find(\"<error code=\\\"\")+13;\n end = _response.find(\">\", start)-1;\n std::string errorcode = _response.substr(start, end-start);\n int code = strtol(errorcode.c_str(), 0, 10);\n\n eprintf(\"%s%i\", \"Code: \", code);\n\n switch(code) {\n\tcase 3:\n\t eprintf(\"Invalid Method. This should not happen.\");\n\t retval = true;\n\t break;\n\tcase 4:\n\t eprintf(\"Authentication failed. Please check your login data.\");\n\t exit(EXIT_FAILURE);\n\tcase 9:\n\t eprintf(\"Invalid session key. Re-authenticating.\");\n\t retval = true;\n\t _failcount = 3;\n\t break;\n\tcase 10:\n\t eprintf(\"Invalid API-Key. Let's bugger off.\");\n\t exit(EXIT_FAILURE);\n\tcase 16:\n\t eprintf(\"The service is temporarily unavailable, we will try again later..\");\n\t retval = true;\n\t break;\n\tcase 26:\n\t eprintf(\"Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm\");\n\t exit(EXIT_FAILURE);\n }\n\n return retval;\n}\n\nbool CAudioScrobbler::Scrobble(const CacheEntry& entry)\n{\n bool retval = false;\n if(!_authed) {\n\teprintf(\"Handshake hasn't been done yet.\");\n\tHandshake();\n\treturn retval;\n }\n iprintf(\"Scrobbling: %s - %s\", entry.getSong().getArtist().c_str(), entry.getSong().getTitle().c_str());\n\n OpenURL(GetServiceURL(), CreateScrobbleMessage(0, entry).c_str());\n if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"Scrobbled successfully.\");\n\tretval = true;\n }\n else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while scrobbling:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t Failure();\n }\n CLEANUP();\n\n return retval;\n}\n\nbool CAudioScrobbler::LoveTrack(const Song& song, bool unlove)\n{\n bool retval = false;\n\n char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);\n char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);\n\n std::ostringstream query, sig;\n query << (unlove ? \"method=track.unlove&\" : \"method=track.love&\")\n\t<< \"&track=\" << title\n\t<< \"&artist=\" << artist\n\t<< \"&api_key=\" << APIKEY\n\t<< \"&sk=\" << _sessionid;\n\n curl_free(artist);\n curl_free(title);\n\n sig << \"api_key\" << APIKEY\n\t<< \"artist\" << song.getArtist()\n\t<< \"method\" << (unlove ? \"track.unlove\" : \"track.love\")\n\t<< \"sk\" << _sessionid\n\t<< \"track\" << song.getTitle()\n\t<< SECRET;\n\n std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n query << \"&api_sig=\" << sighash;\n\n OpenURL(GetServiceURL(), query.str().c_str());\n\n if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"(Un)loved track successfully.\");\n\tretval = true;\n }\n else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while (un)loving the currently playing track:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t Failure();\n }\n\n CLEANUP();\n return retval;\n}\n\nbool CAudioScrobbler::SendNowPlaying(const Song& song)\n{\n bool retval = false;\n\n char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);\n char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);\n char* album = song.getAlbum().empty() ? 0 : curl_easy_escape(_handle, song.getAlbum().c_str(), 0);\n\n std::ostringstream query, sig;\n query << \"method=track.updateNowPlaying&track=\" << title\n\t<< \"&artist=\" << artist\n\t<< \"&duration=\" << song.getDuration()\n\t<< \"&api_key=\" << APIKEY\n\t<< \"&sk=\" << _sessionid;\n if(album) {\n\tquery << \"&album=\" << album;\n\tsig << \"album\" << song.getAlbum();\n }\n\n curl_free(artist);\n curl_free(title);\n curl_free(album);\n\n sig << \"api_key\" << APIKEY\n\t<< \"artist\" << song.getArtist()\n\t<< \"duration\" << song.getDuration()\n\t<< \"methodtrack.updateNowPlaying\"\n\t<< \"sk\" << _sessionid\n\t<< \"track\" << song.getTitle()\n\t<< SECRET;\n\n std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n query << \"&api_sig=\" << sighash;\n\n OpenURL(GetServiceURL(), query.str().c_str());\n\n if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"Updated \\\"Now Playing\\\" status successfully.\");\n\tretval = true;\n }\n else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while updating the currently playing track:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t Failure();\n }\n\n CLEANUP();\n return retval;\n}\n\nvoid CAudioScrobbler::Handshake()\n{\n std::string username=\"\";\n for(unsigned int i = 0; i < Config->getLUsername().length(); i++) {\n\tusername.append(1, tolower(Config->getLUsername().c_str()[i]));\n }\n std::string authtoken(md5sum((char*)\"%s%s\", username.c_str(), Config->getLPassword().c_str()));\n\n std::ostringstream query, sig;\n query << \"method=auth.getMobileSession&username=\" << username << \"&authToken=\" << authtoken << \"&api_key=\" << APIKEY;\n\n sig << \"api_key\" << APIKEY << \"authToken\" << authtoken << \"methodauth.getMobileSessionusername\" << username << SECRET;\n std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n query << \"&api_sig=\" << sighash;\n\n OpenURL(GetServiceURL(), query.str().c_str());\n\n if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tsize_t start, end;\n\tstart = _response.find(\"<key>\") + 5;\n\tend = _response.find(\"<\/key>\");\n\t_sessionid = _response.substr(start, end-start);\n\tiprintf(\"%s%s\", \"Last.fm handshake successful. SessionID: \", _sessionid.c_str());\n\t_authed = true;\n }\n else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\tCheckFailure(_response);\n\texit(EXIT_FAILURE);\n }\n\n CLEANUP();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"modules.h\"\n\n#ifndef MODBASE_ROBOBO\n#define MODBASE_ROBOBO\nModule::Module() {}\n\nModule::~Module() {}\n\nvoid Module::init(ModuleInterface* modFace) {\n\tserverData = modFace;\n}\n\nvoid Module::onChannelMsg(std::string server, std::string channel, char target, std::string nick, std::string message) {}\n\nvoid Module::onUserMsg(std::string server, std::string nick, std::string message) {}\n\nvoid Module::onChannelNotice(std::string server, std::string channel, char target, std::string nick, std::string message) {}\n\nvoid Module::onUserNotice(std::string server, std::string nick, std::string message) {}\n\nvoid Module::onChannelCTCP(std::string server, std::string channel, char target, std::string nick, std::string message) {}\n\nvoid Module::onUserCTCP(std::string server, std::string nick, std::string message) {}\n\nvoid Module::onChannelCTCPReply(std::string server, std::string channel, char target, std::string nick, std::string message) {}\n\nvoid Module::onUserCTCPReply(std::string server, std::string nick, std::string message) {}\n\nvoid Module::onChannelJoin(std::string server, std::string channel, std::string hostmask) {}\n\nvoid Module::onChannelPart(std::string server, std::string channel, std::string hostmask, std::string reason) {}\n\nvoid Module::onUserQuit(std::string server, std::string hostmask, std::string reason) {}\n\nvoid Module::onChannelKick(std::string server, std::string channel, std::string kicker, std::string kickee, std::string reason) {}\n\nvoid Module::onChannelMode(std::string server, std::string channel, std::string setter, char mode, bool add, std::string param) {}\n\nvoid Module::onNumeric(std::string server, std::string numeric, std::vector<std::string> parsedLine) {}\n\nvoid Module::onOtherData(std::string server, std::vector<std::string> parsedLine) {}\n\nvoid Module::onOutChannelMessage(std::string server, std::string target, char status, std::string message) {}\n\nvoid Module::onOutUserMessage(std::string server, std::string target, std::string message) {}\n\nvoid Module::onOutChannelNotice(std::string server, std::string target, char status, std::string message) {}\n\nvoid Module::onOutUserNotice(std::string server, std::string target, std::string message) {}\n\nvoid Module::onOutChannelCTCP(std::string server, std::string target, char status, std::string message) {}\n\nvoid Module::onOutUserCTCP(std::string server, std::string target, std::string message) {}\n\nvoid Module::onOutChannelCTCPReply(std::string server, std::string target, char status, std::string message) {}\n\nvoid Module::onOutUserCTCPReply(std::string server, std::string target, std::string message) {}\n\nvoid Module::sendPrivMsg(std::string server, std::string target, std::string message) {\n\tserverData->sendToServer(server, \"PRIVMSG \" + target + \" :\" + message);\n}\n\nvoid Module::sendNotice(std::string server, std::string target, std::string message) {\n\tserverData->sendToServer(server, \"NOTICE \" + target + \" :\" + message);\n}\n\nvoid Module::sendCTCP(std::string server, std::string target, std::string type, std::string params) {\n\tif (params == \"\")\n\t\tserverData->sendToServer(server, \"PRIVMSG \" + target + \" :\" + (char)1 + type + (char)1);\n\telse\n\t\tserverData->sendToServer(server, \"PRIVMSG \" + target + \" :\" + (char)1 + type + \" \" + params + (char)1);\n}\n\nvoid Module::sendCTCPReply(std::string server, std::string target, std::string type, std::string data) {\n\tif (data == \"\")\n\t\tserverData->sendToServer(server, \"NOTICE \" + target + \" :\" + (char)1 + type + (char)1);\n\telse\n\t\tserverData->sendToServer(server, \"NOTICE \" + target + \" :\" + (char)1 + type + \" \" + data + (char)1);\n}\n\nvoid Module::joinChannel(std::string server, std::string channel, std::string key) {\n\tserverData->sendToServer(server, \"JOIN \" + channel + \" \" + key);\n}\n\nvoid Module::partChannel(std::string server, std::string channel, std::string reason) {\n\tserverData->sendToServer(server, \"PART \" + channel + \" :\" + reason);\n}\n\nvoid Module::kickChannelUser(std::string server, std::string channel, std::string nick, std::string reason) {\n\tserverData->sendToServer(server, \"KICK \" + channel + \" \" + nick + \" :\" + reason);\n}\n\nvoid Module::setMode(std::string server, std::string channel, char mode, bool add, std::string param) {\n\tif (param == \"\") {\n\t\tif (add)\n\t\t\tserverData->sendToServer(server, \"MODE \" + channel + \" +\" + mode);\n\t\telse\n\t\t\tserverData->sendToServer(server, \"MODE \" + channel + \" -\" + mode);\n\t} else {\n\t\tif (add)\n\t\t\tserverData->sendToServer(server, \"MODE \" + channel + \" +\" + mode + \" \" + param);\n\t\telse\n\t\t\tserverData->sendToServer(server, \"MODE \" + channel + \" -\" + mode + \" \" + param);\n\t}\n}\n\nvoid Module::quitServer(std::string server, std::string reason) {\n\tserverData->sendToServer(server, \"QUIT :\" + reason);\n}\n\nstd::vector<std::string> Module::splitHostmask(std::string hostmask) {\n\tstd::vector<std::string> splitmask;\n\tint exclamationPoint = hostmask.find_first_of('!');\n\tint atSign = hostmask.find_first_of('@');\n\tsplitmask.push_back(hostmask.substr(0, exclamationPoint));\n\tsplitmask.push_back(hostmask.substr(exclamationPoint, atSign - exclamationPoint));\n\tsplitmask.push_back(hostmask.substr(atSign));\n\treturn splitmask;\n}\n\nstd::vector<std::string> Module::splitBySpace(std::string line) {\n\tstd::vector<std::string> split;\n\tstd::string temp = \"\";\n\tfor (unsigned int i = 0; i < line.size(); i++) {\n\t\tif (line[i] == ' ') {\n\t\t\tsplit.push_back(temp);\n\t\t\ttemp = \"\";\n\t\t} else\n\t\t\ttemp += line[i];\n\t}\n\treturn split;\n}\n\nstd::list<std::string> Module::getServers() {\n\treturn serverData->getServers();\n}\n\nstd::tr1::unordered_map<std::string, Module*> Module::getModules() {\n\treturn serverData->getModules();\n}\n#endif<commit_msg>Fix splitBySpace() to add the last word when it doesn't end in a space.<commit_after>#include \"modules.h\"\n\n#ifndef MODBASE_ROBOBO\n#define MODBASE_ROBOBO\nModule::Module() {}\n\nModule::~Module() {}\n\nvoid Module::init(ModuleInterface* modFace) {\n\tserverData = modFace;\n}\n\nvoid Module::onChannelMsg(std::string server, std::string channel, char target, std::string nick, std::string message) {}\n\nvoid Module::onUserMsg(std::string server, std::string nick, std::string message) {}\n\nvoid Module::onChannelNotice(std::string server, std::string channel, char target, std::string nick, std::string message) {}\n\nvoid Module::onUserNotice(std::string server, std::string nick, std::string message) {}\n\nvoid Module::onChannelCTCP(std::string server, std::string channel, char target, std::string nick, std::string message) {}\n\nvoid Module::onUserCTCP(std::string server, std::string nick, std::string message) {}\n\nvoid Module::onChannelCTCPReply(std::string server, std::string channel, char target, std::string nick, std::string message) {}\n\nvoid Module::onUserCTCPReply(std::string server, std::string nick, std::string message) {}\n\nvoid Module::onChannelJoin(std::string server, std::string channel, std::string hostmask) {}\n\nvoid Module::onChannelPart(std::string server, std::string channel, std::string hostmask, std::string reason) {}\n\nvoid Module::onUserQuit(std::string server, std::string hostmask, std::string reason) {}\n\nvoid Module::onChannelKick(std::string server, std::string channel, std::string kicker, std::string kickee, std::string reason) {}\n\nvoid Module::onChannelMode(std::string server, std::string channel, std::string setter, char mode, bool add, std::string param) {}\n\nvoid Module::onNumeric(std::string server, std::string numeric, std::vector<std::string> parsedLine) {}\n\nvoid Module::onOtherData(std::string server, std::vector<std::string> parsedLine) {}\n\nvoid Module::onOutChannelMessage(std::string server, std::string target, char status, std::string message) {}\n\nvoid Module::onOutUserMessage(std::string server, std::string target, std::string message) {}\n\nvoid Module::onOutChannelNotice(std::string server, std::string target, char status, std::string message) {}\n\nvoid Module::onOutUserNotice(std::string server, std::string target, std::string message) {}\n\nvoid Module::onOutChannelCTCP(std::string server, std::string target, char status, std::string message) {}\n\nvoid Module::onOutUserCTCP(std::string server, std::string target, std::string message) {}\n\nvoid Module::onOutChannelCTCPReply(std::string server, std::string target, char status, std::string message) {}\n\nvoid Module::onOutUserCTCPReply(std::string server, std::string target, std::string message) {}\n\nvoid Module::sendPrivMsg(std::string server, std::string target, std::string message) {\n\tserverData->sendToServer(server, \"PRIVMSG \" + target + \" :\" + message);\n}\n\nvoid Module::sendNotice(std::string server, std::string target, std::string message) {\n\tserverData->sendToServer(server, \"NOTICE \" + target + \" :\" + message);\n}\n\nvoid Module::sendCTCP(std::string server, std::string target, std::string type, std::string params) {\n\tif (params == \"\")\n\t\tserverData->sendToServer(server, \"PRIVMSG \" + target + \" :\" + (char)1 + type + (char)1);\n\telse\n\t\tserverData->sendToServer(server, \"PRIVMSG \" + target + \" :\" + (char)1 + type + \" \" + params + (char)1);\n}\n\nvoid Module::sendCTCPReply(std::string server, std::string target, std::string type, std::string data) {\n\tif (data == \"\")\n\t\tserverData->sendToServer(server, \"NOTICE \" + target + \" :\" + (char)1 + type + (char)1);\n\telse\n\t\tserverData->sendToServer(server, \"NOTICE \" + target + \" :\" + (char)1 + type + \" \" + data + (char)1);\n}\n\nvoid Module::joinChannel(std::string server, std::string channel, std::string key) {\n\tserverData->sendToServer(server, \"JOIN \" + channel + \" \" + key);\n}\n\nvoid Module::partChannel(std::string server, std::string channel, std::string reason) {\n\tserverData->sendToServer(server, \"PART \" + channel + \" :\" + reason);\n}\n\nvoid Module::kickChannelUser(std::string server, std::string channel, std::string nick, std::string reason) {\n\tserverData->sendToServer(server, \"KICK \" + channel + \" \" + nick + \" :\" + reason);\n}\n\nvoid Module::setMode(std::string server, std::string channel, char mode, bool add, std::string param) {\n\tif (param == \"\") {\n\t\tif (add)\n\t\t\tserverData->sendToServer(server, \"MODE \" + channel + \" +\" + mode);\n\t\telse\n\t\t\tserverData->sendToServer(server, \"MODE \" + channel + \" -\" + mode);\n\t} else {\n\t\tif (add)\n\t\t\tserverData->sendToServer(server, \"MODE \" + channel + \" +\" + mode + \" \" + param);\n\t\telse\n\t\t\tserverData->sendToServer(server, \"MODE \" + channel + \" -\" + mode + \" \" + param);\n\t}\n}\n\nvoid Module::quitServer(std::string server, std::string reason) {\n\tserverData->sendToServer(server, \"QUIT :\" + reason);\n}\n\nstd::vector<std::string> Module::splitHostmask(std::string hostmask) {\n\tstd::vector<std::string> splitmask;\n\tint exclamationPoint = hostmask.find_first_of('!');\n\tint atSign = hostmask.find_first_of('@');\n\tsplitmask.push_back(hostmask.substr(0, exclamationPoint));\n\tsplitmask.push_back(hostmask.substr(exclamationPoint, atSign - exclamationPoint));\n\tsplitmask.push_back(hostmask.substr(atSign));\n\treturn splitmask;\n}\n\nstd::vector<std::string> Module::splitBySpace(std::string line) {\n\tstd::vector<std::string> split;\n\tstd::string temp = \"\";\n\tfor (unsigned int i = 0; i < line.size(); i++) {\n\t\tif (line[i] == ' ') {\n\t\t\tsplit.push_back(temp);\n\t\t\ttemp = \"\";\n\t\t} else\n\t\t\ttemp += line[i];\n\t}\n\tif (temp != \"\")\n\t\tsplit.push_back(temp);\n\treturn split;\n}\n\nstd::list<std::string> Module::getServers() {\n\treturn serverData->getServers();\n}\n\nstd::tr1::unordered_map<std::string, Module*> Module::getModules() {\n\treturn serverData->getModules();\n}\n#endif<|endoftext|>"} {"text":"<commit_before>#include \"chainerx\/routines\/activation.h\"\n\n#include <cmath>\n#include <numeric>\n#include <utility>\n#include <vector>\n\n#include \"chainerx\/array.h\"\n#include \"chainerx\/device.h\"\n#include \"chainerx\/dtype.h\"\n#include \"chainerx\/enum.h\"\n#include \"chainerx\/error.h\"\n#include \"chainerx\/graph.h\"\n#include \"chainerx\/macro.h\"\n#include \"chainerx\/routines\/arithmetic.h\"\n#include \"chainerx\/routines\/creation.h\"\n#include \"chainerx\/routines\/explog.h\"\n#include \"chainerx\/routines\/hyperbolic.h\"\n#include \"chainerx\/routines\/indexing.h\"\n#include \"chainerx\/routines\/manipulation.h\"\n#include \"chainerx\/routines\/misc.h\"\n#include \"chainerx\/routines\/type_util.h\"\n#include \"chainerx\/scalar.h\"\n#include \"chainerx\/shape.h\"\n\nnamespace chainerx {\n\nnamespace {\n\nstd::vector<Array> ExtractGates(Array x, int64_t n_splits, int64_t axis) {\n StackVector<int64_t, kMaxNdim> shape_vec;\n shape_vec.emplace_back(x.shape()[0]);\n if (axis == 1) {\n shape_vec.emplace_back(n_splits);\n shape_vec.emplace_back(static_cast<int64_t>(x.shape()[1] \/ n_splits));\n } else {\n shape_vec.emplace_back(static_cast<int64_t>(x.shape()[1] \/ n_splits));\n shape_vec.emplace_back(n_splits);\n }\n for (int64_t i = 2; i < x.ndim(); i++) {\n shape_vec.emplace_back(x.shape()[i]);\n }\n Shape shape{shape_vec};\n Array x_r = Reshape(x, shape);\n std::vector<Array> x_split = Split(x_r, n_splits, axis);\n return x_split;\n}\n\n} \/\/ namespace\n\nArray ClippedRelu(const Array& x, Scalar z) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n return Minimum(Maximum(0, x_cast), z);\n}\n\nArray CRelu(const Array& x, int8_t axis) {\n \/\/ TODO(aksub99): Optimize implementation to use a single memory allocation.\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n std::vector<Array> c{x_cast, Negative(x_cast)};\n Array concat = Concatenate(c, axis);\n return Relu(concat);\n}\n\nArray Elu(const Array& x, double alpha) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n \/\/ TODO(aksub99): Replace x > zero with x > 0 when operator > supports scalars.\n Array zero = Zeros({}, x_cast.dtype(), x_cast.device());\n return Where(x_cast > zero, x_cast, alpha * Expm1(x_cast));\n}\n\nArray Sigmoid(const Array& x) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n return Reciprocal(1 + Exp(-x_cast));\n}\n\nArray Relu(const Array& x) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n return Maximum(0, x_cast);\n}\n\nArray LeakyRelu(const Array& x, Scalar slope) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n \/\/ TODO(hamaji): Replace x >= zero with x >= 0 when operator >= supports scalars.\n Array zero = Zeros({}, x_cast.dtype(), x_cast.device());\n return Where(x_cast >= zero, x_cast, slope * x_cast);\n}\n\nstd::vector<Array> SLstm(const Array& c_prev1, const Array& c_prev2, const Array& x1, const Array& x2) {\n std::vector<Array> x1_gates = ExtractGates(x1, 4, 2);\n std::vector<Array> x2_gates = ExtractGates(x2, 4, 2);\n Array a1 = Squeeze(x1_gates[0]);\n Array i1 = Squeeze(x1_gates[1]);\n Array f1 = Squeeze(x1_gates[2]);\n Array o1 = Squeeze(x1_gates[3]);\n\n Array a2 = Squeeze(x2_gates[0]);\n Array i2 = Squeeze(x2_gates[1]);\n Array f2 = Squeeze(x2_gates[2]);\n Array o2 = Squeeze(x2_gates[3]);\n\n a1 = Tanh(a1);\n i1 = Sigmoid(i1);\n f1 = Sigmoid(f1);\n\n a2 = Tanh(a2);\n i2 = Sigmoid(i2);\n f2 = Sigmoid(f2);\n\n Array o = Sigmoid(o1 + o2);\n Array c = a1 * i1 + a2 * i2 + f1 * c_prev1 + f2 * c_prev2;\n Array h = o * Tanh(c);\n\n return {c, h};\n}\n\nArray Softplus(const Array& x, double beta) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n double beta_inv = 1.0 \/ beta;\n Array bx = beta * x_cast;\n Array y = (Maximum(bx, 0) + Log1p(Exp(-Fabs(bx)))) * beta_inv;\n return y;\n}\n\n} \/\/ namespace chainerx\n<commit_msg>fix clang error<commit_after>#include \"chainerx\/routines\/activation.h\"\n\n#include <cmath>\n#include <numeric>\n#include <utility>\n#include <vector>\n\n#include \"chainerx\/array.h\"\n#include \"chainerx\/device.h\"\n#include \"chainerx\/dtype.h\"\n#include \"chainerx\/enum.h\"\n#include \"chainerx\/error.h\"\n#include \"chainerx\/graph.h\"\n#include \"chainerx\/macro.h\"\n#include \"chainerx\/routines\/arithmetic.h\"\n#include \"chainerx\/routines\/creation.h\"\n#include \"chainerx\/routines\/explog.h\"\n#include \"chainerx\/routines\/hyperbolic.h\"\n#include \"chainerx\/routines\/indexing.h\"\n#include \"chainerx\/routines\/manipulation.h\"\n#include \"chainerx\/routines\/misc.h\"\n#include \"chainerx\/routines\/type_util.h\"\n#include \"chainerx\/scalar.h\"\n#include \"chainerx\/shape.h\"\n\nnamespace chainerx {\n\nnamespace {\n\nstd::vector<Array> ExtractGates(const Array& x, int64_t n_splits, int64_t axis) {\n StackVector<int64_t, kMaxNdim> shape_vec;\n shape_vec.emplace_back(x.shape()[0]);\n if (axis == 1) {\n shape_vec.emplace_back(n_splits);\n shape_vec.emplace_back(static_cast<int64_t>(x.shape()[1] \/ n_splits));\n } else {\n shape_vec.emplace_back(static_cast<int64_t>(x.shape()[1] \/ n_splits));\n shape_vec.emplace_back(n_splits);\n }\n for (int64_t i = 2; i < x.ndim(); i++) {\n shape_vec.emplace_back(x.shape()[i]);\n }\n Shape shape{shape_vec};\n Array x_r = Reshape(x, shape);\n std::vector<Array> x_split = Split(x_r, n_splits, axis);\n return x_split;\n}\n\n} \/\/ namespace\n\nArray ClippedRelu(const Array& x, Scalar z) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n return Minimum(Maximum(0, x_cast), z);\n}\n\nArray CRelu(const Array& x, int8_t axis) {\n \/\/ TODO(aksub99): Optimize implementation to use a single memory allocation.\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n std::vector<Array> c{x_cast, Negative(x_cast)};\n Array concat = Concatenate(c, axis);\n return Relu(concat);\n}\n\nArray Elu(const Array& x, double alpha) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n \/\/ TODO(aksub99): Replace x > zero with x > 0 when operator > supports scalars.\n Array zero = Zeros({}, x_cast.dtype(), x_cast.device());\n return Where(x_cast > zero, x_cast, alpha * Expm1(x_cast));\n}\n\nArray Sigmoid(const Array& x) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n return Reciprocal(1 + Exp(-x_cast));\n}\n\nArray Relu(const Array& x) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n return Maximum(0, x_cast);\n}\n\nArray LeakyRelu(const Array& x, Scalar slope) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n \/\/ TODO(hamaji): Replace x >= zero with x >= 0 when operator >= supports scalars.\n Array zero = Zeros({}, x_cast.dtype(), x_cast.device());\n return Where(x_cast >= zero, x_cast, slope * x_cast);\n}\n\nstd::vector<Array> SLstm(const Array& c_prev1, const Array& c_prev2, const Array& x1, const Array& x2) {\n std::vector<Array> x1_gates = ExtractGates(x1, 4, 2);\n std::vector<Array> x2_gates = ExtractGates(x2, 4, 2);\n Array a1 = Squeeze(x1_gates[0]);\n Array i1 = Squeeze(x1_gates[1]);\n Array f1 = Squeeze(x1_gates[2]);\n Array o1 = Squeeze(x1_gates[3]);\n\n Array a2 = Squeeze(x2_gates[0]);\n Array i2 = Squeeze(x2_gates[1]);\n Array f2 = Squeeze(x2_gates[2]);\n Array o2 = Squeeze(x2_gates[3]);\n\n a1 = Tanh(a1);\n i1 = Sigmoid(i1);\n f1 = Sigmoid(f1);\n\n a2 = Tanh(a2);\n i2 = Sigmoid(i2);\n f2 = Sigmoid(f2);\n\n Array o = Sigmoid(o1 + o2);\n Array c = a1 * i1 + a2 * i2 + f1 * c_prev1 + f2 * c_prev2;\n Array h = o * Tanh(c);\n\n return {c, h};\n}\n\nArray Softplus(const Array& x, double beta) {\n Dtype dtype = internal::GetMathResultDtype(x.dtype());\n const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);\n double beta_inv = 1.0 \/ beta;\n Array bx = beta * x_cast;\n Array y = (Maximum(bx, 0) + Log1p(Exp(-Fabs(bx)))) * beta_inv;\n return y;\n}\n\n} \/\/ namespace chainerx\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestTreeHeatmapItem.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkTreeHeatmapItem.h\"\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkNew.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTable.h\"\n#include \"vtkTree.h\"\n\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkContextInteractorStyle.h\"\n#include \"vtkContextActor.h\"\n#include \"vtkContextMouseEvent.h\"\n#include \"vtkContextScene.h\"\n#include \"vtkContextTransform.h\"\n#include \"vtkNew.h\"\n\n#include \"vtkRegressionTestImage.h\"\n\n\/\/----------------------------------------------------------------------------\nint TestTreeHeatmapItem(int argc, char* argv[])\n{\n vtkNew<vtkMutableDirectedGraph> graph;\n vtkIdType root = graph->AddVertex();\n vtkIdType internalOne = graph->AddChild(root);\n vtkIdType internalTwo = graph->AddChild(internalOne);\n vtkIdType a = graph->AddChild(internalTwo);\n vtkIdType b = graph->AddChild(internalTwo);\n vtkIdType c = graph->AddChild(internalOne);\n\n vtkNew<vtkDoubleArray> weights;\n weights->SetNumberOfTuples(5);\n weights->SetValue(graph->GetEdgeId(root, internalOne), 1.0f);\n weights->SetValue(graph->GetEdgeId(internalOne, internalTwo), 2.0f);\n weights->SetValue(graph->GetEdgeId(internalTwo, a), 1.0f);\n weights->SetValue(graph->GetEdgeId(internalTwo, b), 1.0f);\n weights->SetValue(graph->GetEdgeId(internalOne, c), 3.0f);\n\n weights->SetName(\"weight\");\n graph->GetEdgeData()->AddArray(weights.GetPointer());\n\n vtkNew<vtkStringArray> names;\n names->SetNumberOfTuples(6);\n names->SetValue(a, \"a\");\n names->SetValue(b, \"b\");\n names->SetValue(c, \"c\");\n\n names->SetName(\"node name\");\n graph->GetVertexData()->AddArray(names.GetPointer());\n\n vtkNew<vtkDoubleArray> nodeWeights;\n nodeWeights->SetNumberOfTuples(6);\n nodeWeights->SetValue(root, 0.0f);\n nodeWeights->SetValue(internalOne, 1.0f);\n nodeWeights->SetValue(internalTwo, 3.0f);\n nodeWeights->SetValue(a, 4.0f);\n nodeWeights->SetValue(b, 4.0f);\n nodeWeights->SetValue(c, 4.0f);\n nodeWeights->SetName(\"node weight\");\n graph->GetVertexData()->AddArray(nodeWeights.GetPointer());\n\n vtkNew<vtkTable> table;\n vtkNew<vtkStringArray> tableNames;\n vtkNew<vtkDoubleArray> m1;\n vtkNew<vtkDoubleArray> m2;\n vtkNew<vtkDoubleArray> m3;\n\n tableNames->SetNumberOfTuples(3);\n tableNames->SetValue(0, \"c\");\n tableNames->SetValue(1, \"b\");\n tableNames->SetValue(2, \"a\");\n tableNames->SetName(\"name\");\n\n m1->SetNumberOfTuples(3);\n m2->SetNumberOfTuples(3);\n m3->SetNumberOfTuples(3);\n\n m1->SetName(\"m1\");\n m2->SetName(\"m2\");\n m3->SetName(\"m3\");\n\n m1->SetValue(0, 1.0f);\n m1->SetValue(1, 3.0f);\n m1->SetValue(2, 1.0f);\n\n m2->SetValue(0, 2.0f);\n m2->SetValue(1, 2.0f);\n m2->SetValue(2, 2.0f);\n\n m3->SetValue(0, 3.0f);\n m3->SetValue(1, 1.0f);\n m3->SetValue(2, 3.0f);\n\n table->AddColumn(tableNames.GetPointer());\n table->AddColumn(m1.GetPointer());\n table->AddColumn(m2.GetPointer());\n table->AddColumn(m3.GetPointer());\n\n vtkNew<vtkContextActor> actor;\n\n vtkNew<vtkTree> tree;\n tree->ShallowCopy(graph.GetPointer());\n\n vtkNew<vtkTreeHeatmapItem> treeItem;\n treeItem->SetTree(tree.GetPointer());\n treeItem->SetTable(table.GetPointer());\n\n vtkNew<vtkContextTransform> trans;\n trans->SetInteractive(true);\n trans->AddItem(treeItem.GetPointer());\n actor->GetScene()->AddItem(trans.GetPointer());\n\n vtkNew<vtkRenderer> renderer;\n renderer->SetBackground(1.0, 1.0, 1.0);\n\n vtkNew<vtkRenderWindow> renderWindow;\n renderWindow->SetSize(400, 200);\n renderWindow->AddRenderer(renderer.GetPointer());\n renderer->AddActor(actor.GetPointer());\n actor->GetScene()->SetRenderer(renderer.GetPointer());\n\n vtkNew<vtkContextInteractorStyle> interactorStyle;\n interactorStyle->SetScene(actor->GetScene());\n\n vtkNew<vtkRenderWindowInteractor> interactor;\n interactor->SetInteractorStyle(interactorStyle.GetPointer());\n interactor->SetRenderWindow(renderWindow.GetPointer());\n renderWindow->SetMultiSamples(0);\n renderWindow->Render();\n\n \/\/ collapse and expand a subtree\n vtkContextMouseEvent mouseEvent;\n mouseEvent.SetInteractor(interactor.GetPointer());\n vtkVector2f pos;\n mouseEvent.SetButton(vtkContextMouseEvent::LEFT_BUTTON);\n pos.Set(78, 50);\n mouseEvent.SetPos(pos);\n treeItem ->MouseDoubleClickEvent(mouseEvent);\n renderWindow->Render();\n treeItem ->MouseDoubleClickEvent(mouseEvent);\n\n int retVal = vtkRegressionTestImage(renderWindow.GetPointer());\n if (retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n renderWindow->Render();\n interactor->Start();\n retVal = vtkRegressionTester::PASSED;\n }\n return !retVal;\n}\n<commit_msg>Update TestTreeHeatmapItem for recent changes to collapse\/expand<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestTreeHeatmapItem.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkTreeHeatmapItem.h\"\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkNew.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTable.h\"\n#include \"vtkTree.h\"\n\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkContextInteractorStyle.h\"\n#include \"vtkContextActor.h\"\n#include \"vtkContextMouseEvent.h\"\n#include \"vtkContextScene.h\"\n#include \"vtkContextTransform.h\"\n#include \"vtkNew.h\"\n\n#include \"vtkRegressionTestImage.h\"\n\n\/\/----------------------------------------------------------------------------\nint TestTreeHeatmapItem(int argc, char* argv[])\n{\n vtkNew<vtkMutableDirectedGraph> graph;\n vtkIdType root = graph->AddVertex();\n vtkIdType internalOne = graph->AddChild(root);\n vtkIdType internalTwo = graph->AddChild(internalOne);\n vtkIdType a = graph->AddChild(internalTwo);\n vtkIdType b = graph->AddChild(internalTwo);\n vtkIdType c = graph->AddChild(internalOne);\n\n vtkNew<vtkDoubleArray> weights;\n weights->SetNumberOfTuples(5);\n weights->SetValue(graph->GetEdgeId(root, internalOne), 1.0f);\n weights->SetValue(graph->GetEdgeId(internalOne, internalTwo), 2.0f);\n weights->SetValue(graph->GetEdgeId(internalTwo, a), 1.0f);\n weights->SetValue(graph->GetEdgeId(internalTwo, b), 1.0f);\n weights->SetValue(graph->GetEdgeId(internalOne, c), 3.0f);\n\n weights->SetName(\"weight\");\n graph->GetEdgeData()->AddArray(weights.GetPointer());\n\n vtkNew<vtkStringArray> names;\n names->SetNumberOfTuples(6);\n names->SetValue(a, \"a\");\n names->SetValue(b, \"b\");\n names->SetValue(c, \"c\");\n\n names->SetName(\"node name\");\n graph->GetVertexData()->AddArray(names.GetPointer());\n\n vtkNew<vtkDoubleArray> nodeWeights;\n nodeWeights->SetNumberOfTuples(6);\n nodeWeights->SetValue(root, 0.0f);\n nodeWeights->SetValue(internalOne, 1.0f);\n nodeWeights->SetValue(internalTwo, 3.0f);\n nodeWeights->SetValue(a, 4.0f);\n nodeWeights->SetValue(b, 4.0f);\n nodeWeights->SetValue(c, 4.0f);\n nodeWeights->SetName(\"node weight\");\n graph->GetVertexData()->AddArray(nodeWeights.GetPointer());\n\n vtkNew<vtkTable> table;\n vtkNew<vtkStringArray> tableNames;\n vtkNew<vtkDoubleArray> m1;\n vtkNew<vtkDoubleArray> m2;\n vtkNew<vtkDoubleArray> m3;\n\n tableNames->SetNumberOfTuples(3);\n tableNames->SetValue(0, \"c\");\n tableNames->SetValue(1, \"b\");\n tableNames->SetValue(2, \"a\");\n tableNames->SetName(\"name\");\n\n m1->SetNumberOfTuples(3);\n m2->SetNumberOfTuples(3);\n m3->SetNumberOfTuples(3);\n\n m1->SetName(\"m1\");\n m2->SetName(\"m2\");\n m3->SetName(\"m3\");\n\n m1->SetValue(0, 1.0f);\n m1->SetValue(1, 3.0f);\n m1->SetValue(2, 1.0f);\n\n m2->SetValue(0, 2.0f);\n m2->SetValue(1, 2.0f);\n m2->SetValue(2, 2.0f);\n\n m3->SetValue(0, 3.0f);\n m3->SetValue(1, 1.0f);\n m3->SetValue(2, 3.0f);\n\n table->AddColumn(tableNames.GetPointer());\n table->AddColumn(m1.GetPointer());\n table->AddColumn(m2.GetPointer());\n table->AddColumn(m3.GetPointer());\n\n vtkNew<vtkContextActor> actor;\n\n vtkNew<vtkTree> tree;\n tree->ShallowCopy(graph.GetPointer());\n\n vtkNew<vtkTreeHeatmapItem> treeItem;\n treeItem->SetTree(tree.GetPointer());\n treeItem->SetTable(table.GetPointer());\n\n vtkNew<vtkContextTransform> trans;\n trans->SetInteractive(true);\n trans->AddItem(treeItem.GetPointer());\n actor->GetScene()->AddItem(trans.GetPointer());\n\n vtkNew<vtkRenderer> renderer;\n renderer->SetBackground(1.0, 1.0, 1.0);\n\n vtkNew<vtkRenderWindow> renderWindow;\n renderWindow->SetSize(400, 200);\n renderWindow->AddRenderer(renderer.GetPointer());\n renderer->AddActor(actor.GetPointer());\n actor->GetScene()->SetRenderer(renderer.GetPointer());\n\n vtkNew<vtkContextInteractorStyle> interactorStyle;\n interactorStyle->SetScene(actor->GetScene());\n\n vtkNew<vtkRenderWindowInteractor> interactor;\n interactor->SetInteractorStyle(interactorStyle.GetPointer());\n interactor->SetRenderWindow(renderWindow.GetPointer());\n renderWindow->SetMultiSamples(0);\n renderWindow->Render();\n\n \/\/ collapse and expand a subtree\n vtkContextMouseEvent mouseEvent;\n mouseEvent.SetInteractor(interactor.GetPointer());\n vtkVector2f pos;\n mouseEvent.SetButton(vtkContextMouseEvent::LEFT_BUTTON);\n pos.Set(78, 50);\n mouseEvent.SetPos(pos);\n treeItem->MouseDoubleClickEvent(mouseEvent);\n renderWindow->Render();\n pos.Set(43, 4);\n mouseEvent.SetPos(pos);\n treeItem->MouseDoubleClickEvent(mouseEvent);\n\n int retVal = vtkRegressionTestImage(renderWindow.GetPointer());\n if (retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n renderWindow->Render();\n interactor->Start();\n retVal = vtkRegressionTester::PASSED;\n }\n return !retVal;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $\n\n\/\/ mapnik\n#include <mapnik\/global.hpp>\n#include <mapnik\/ptree_helpers.hpp>\n#include \"connection_manager.hpp\"\n#include \"postgis.hpp\"\n\n\/\/ boost\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/tokenizer.hpp>\n\n\/\/ stl\n#include <string>\n#include <algorithm>\n#include <set>\n#include <sstream>\n#include <iomanip>\n\n#ifndef MAPNIK_BIG_ENDIAN\n#define WKB_ENCODING \"NDR\"\n#else\n#define WKB_ENCODING \"XDR\"\n#endif\n\nDATASOURCE_PLUGIN(postgis_datasource)\n\nconst std::string postgis_datasource::GEOMETRY_COLUMNS=\"geometry_columns\";\nconst std::string postgis_datasource::SPATIAL_REF_SYS=\"spatial_ref_system\";\n\nusing std::clog;\nusing std::endl;\n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\nusing boost::shared_ptr;\n\nusing mapnik::PoolGuard;\nusing mapnik::attribute_descriptor;\n\npostgis_datasource::postgis_datasource(parameters const& params)\n : datasource (params),\n table_(*params.get<std::string>(\"table\",\"\")),\n geometry_field_(*params.get<std::string>(\"geometry_field\",\"\")),\n cursor_fetch_size_(*params_.get<int>(\"cursor_size\",0)),\n row_limit_(*params_.get<int>(\"row_limit\",0)),\n type_(datasource::Vector),\n extent_initialized_(false),\n desc_(*params.get<std::string>(\"type\"),\"utf-8\"),\n creator_(params.get<std::string>(\"host\"),\n params.get<std::string>(\"port\"),\n params.get<std::string>(\"dbname\"),\n params.get<std::string>(\"user\"),\n params.get<std::string>(\"password\")),\n bbox_token_(\"!bbox!\")\n{ \n\n boost::optional<int> initial_size = params_.get<int>(\"inital_size\",1);\n boost::optional<int> max_size = params_.get<int>(\"max_size\",10);\n\n multiple_geometries_ = *params_.get<mapnik::boolean>(\"multiple_geometries\",false);\n \n boost::optional<std::string> ext = params_.get<std::string>(\"extent\");\n if (ext)\n {\n boost::char_separator<char> sep(\",\");\n boost::tokenizer<boost::char_separator<char> > tok(*ext,sep);\n unsigned i = 0;\n bool success = false;\n double d[4];\n for (boost::tokenizer<boost::char_separator<char> >::iterator beg=tok.begin(); \n beg!=tok.end();++beg)\n {\n try \n {\n d[i] = boost::lexical_cast<double>(boost::trim_copy(*beg));\n }\n catch (boost::bad_lexical_cast & ex)\n {\n std::clog << *beg << \" : \" << ex.what() << \"\\n\";\n break;\n }\n if (i==3) \n {\n success = true;\n break;\n }\n ++i;\n }\n if (success)\n {\n extent_.init(d[0],d[1],d[2],d[3]);\n extent_initialized_ = true;\n }\n } \n\n ConnectionManager *mgr=ConnectionManager::instance(); \n mgr->registerPool(creator_, *initial_size, *max_size);\n \n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n { \n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n PoolGuard<shared_ptr<Connection>,\n shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n \n desc_.set_encoding(conn->client_encoding());\n \n std::string table_name=table_from_sql(table_);\n std::string schema_name=\"\";\n std::string::size_type idx=table_name.find_last_of('.');\n if (idx!=std::string::npos)\n {\n schema_name=table_name.substr(0,idx);\n table_name=table_name.substr(idx+1);\n }\n else\n {\n table_name=table_name.substr(0);\n }\n\n std::ostringstream s;\n s << \"select f_geometry_column,srid,type from \";\n s << GEOMETRY_COLUMNS <<\" where f_table_name='\" << table_name<<\"'\";\n \n if (schema_name.length() > 0)\n s <<\" and f_table_schema='\"<< schema_name <<\"'\";\n\n if (geometry_field_.length() > 0)\n s << \" and f_geometry_column = '\" << geometry_field_ << \"'\";\n \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n try \n {\n srid_ = lexical_cast<int>(rs->getValue(\"srid\"));\n }\n catch (bad_lexical_cast &ex)\n {\n clog << rs->getValue(\"srid\") << \":\" << ex.what() << endl;\n }\n geometryColumn_=rs->getValue(\"f_geometry_column\");\n std::string postgisType=rs->getValue(\"type\");\n }\n rs->close();\n \n \/\/ collect attribute desc\n s.str(\"\");\n std::string table_with_bbox = populate_sql_bbox(table_,extent_);\n s << \"select * from \" << table_with_bbox << \" limit 0\";\n rs=conn->executeQuery(s.str());\n int count = rs->getNumFields();\n for (int i=0;i<count;++i)\n {\n std::string fld_name=rs->getFieldName(i);\n int type_oid = rs->getTypeOID(i);\n switch (type_oid)\n {\n case 21: \/\/ int2\n case 23: \/\/ int4\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));\n break;\n case 700: \/\/ float4 \n case 701: \/\/ float8\n case 1700: \/\/ numeric ??\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));\n case 1042: \/\/ bpchar\n case 1043: \/\/ varchar\n case 25: \/\/ text\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n break;\n default: \/\/ shouldn't get here\n#ifdef MAPNIK_DEBUG\n clog << \"unknown type_oid=\"<<type_oid<<endl;\n#endif\n break;\n }\t \n }\n }\n }\n}\n\nstd::string const postgis_datasource::name_=\"postgis\";\n\nstd::string postgis_datasource::name()\n{\n return name_;\n}\n\nint postgis_datasource::type() const\n{\n return type_;\n}\n\nlayer_descriptor postgis_datasource::get_descriptor() const\n{\n return desc_;\n}\n\nstd::string postgis_datasource::populate_sql_bbox(const std::string& sql, Envelope<double> const& box) const\n{\n std::string sql_with_bbox = boost::algorithm::to_lower_copy(sql);\n std::ostringstream b;\n b << \"SetSRID('BOX3D(\";\n b << std::setprecision(16);\n b << box.minx() << \" \" << box.miny() << \",\";\n b << box.maxx() << \" \" << box.maxy() << \")'::box3d,\" << srid_ << \")\";\n if ( boost::algorithm::icontains(sql,bbox_token_) )\n {\n boost::algorithm::replace_all(sql_with_bbox,bbox_token_,b.str());\n return sql_with_bbox;\n }\n else\n {\n std::ostringstream s;\n s << \" WHERE \\\"\" << geometryColumn_ << \"\\\" && \" << b.str();\n return sql_with_bbox + s.str(); \n }\n}\n\nstd::string postgis_datasource::table_from_sql(const std::string& sql)\n{\n std::string table_name = boost::algorithm::to_lower_copy(sql);\n boost::algorithm::replace_all(table_name,\"\\n\",\" \");\n \n std::string::size_type idx = table_name.rfind(\" from \");\n if (idx!=std::string::npos)\n {\n \n idx=table_name.find_first_not_of(\" \",idx+5);\n if (idx != std::string::npos)\n {\n table_name=table_name.substr(idx);\n }\n idx=table_name.find_first_of(\" )\");\n if (idx != std::string::npos)\n {\n table_name = table_name.substr(0,idx);\n }\n }\n return table_name;\n}\n\nboost::shared_ptr<IResultSet> postgis_datasource::get_resultset(boost::shared_ptr<Connection> const &conn, const std::string &sql) const\n{\n if (cursor_fetch_size_ > 0) {\n \/\/ cursor\n std::ostringstream csql;\n std::string cursor_name = conn->new_cursor_name();\n\n csql << \"DECLARE \" << cursor_name << \" BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR \" << sql << \" FOR READ ONLY\";\n\n#ifdef MAPNIK_DEBUG\n std::clog << csql.str() << \"\\n\";\n#endif\n if (!conn->execute(csql.str())) {\n throw mapnik::datasource_exception( \"PSQL Error: Creating cursor for data select.\" );\n }\n return shared_ptr<CursorResultSet>(new CursorResultSet(conn, cursor_name, cursor_fetch_size_));\n\n } else {\n \/\/ no cursor\n#ifdef MAPNIK_DEBUG\n std::clog << sql << \"\\n\";\n#endif\n return conn->executeQuery(sql,1);\n }\n}\n\nfeatureset_ptr postgis_datasource::features(const query& q) const\n{\n Envelope<double> const& box=q.get_bbox();\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n\n std::ostringstream s;\n s << \"SELECT AsBinary(\\\"\"<<geometryColumn_<<\"\\\",'\"<< WKB_ENCODING << \"') AS geom\";\n std::set<std::string> const& props=q.property_names();\n std::set<std::string>::const_iterator pos=props.begin();\n std::set<std::string>::const_iterator end=props.end();\n while (pos != end)\n {\n s <<\",\\\"\"<<*pos<<\"\\\"\";\n ++pos;\n }\t \n\n std::string table_with_bbox = populate_sql_bbox(table_,box);\n\n s << \" from \" << table_with_bbox;\n\n if (row_limit_ > 0) {\n s << \" LIMIT \" << row_limit_;\n }\n \n boost::shared_ptr<IResultSet> rs = get_resultset(conn, s.str());\n return featureset_ptr(new postgis_featureset(rs,desc_.get_encoding(),multiple_geometries_,props.size()));\n }\n }\n return featureset_ptr();\n}\n\nfeatureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const\n{\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"SELECT AsBinary(\\\"\" << geometryColumn_ << \"\\\",'\"<< WKB_ENCODING << \"') AS geom\";\n \n std::vector<attribute_descriptor>::const_iterator itr = desc_.get_descriptors().begin();\n std::vector<attribute_descriptor>::const_iterator end = desc_.get_descriptors().end();\n unsigned size=0;\n while (itr != end)\n {\n s <<\",\\\"\"<< itr->get_name() << \"\\\"\";\n ++itr;\n ++size;\n }\n\n Envelope<double> box(pt.x,pt.y,pt.x,pt.y);\n std::string table_with_bbox = populate_sql_bbox(table_,box);\n\n s << \" from \" << table_with_bbox;\n \n if (row_limit_ > 0) {\n s << \" LIMIT \" << row_limit_;\n }\n \n boost::shared_ptr<IResultSet> rs = get_resultset(conn, s.str());\n return featureset_ptr(new postgis_featureset(rs,desc_.get_encoding(),multiple_geometries_, size));\n }\n }\n return featureset_ptr();\n}\n\nEnvelope<double> postgis_datasource::envelope() const\n{\n if (extent_initialized_) return extent_;\n \n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::ostringstream s;\n std::string table_name = table_from_sql(table_);\n boost::optional<std::string> estimate_extent = params_.get<std::string>(\"estimate_extent\");\n \n if (estimate_extent && *estimate_extent == \"true\")\n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select estimated_extent('\" \n << table_name <<\"','\" \n << geometryColumn_ << \"') as ext) as tmp\";\n }\n else \n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select extent(\" <<geometryColumn_<< \") as ext from \" \n << table_name << \") as tmp\";\n }\n \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n try \n {\n double lox=lexical_cast<double>(rs->getValue(0));\n double loy=lexical_cast<double>(rs->getValue(1));\n double hix=lexical_cast<double>(rs->getValue(2));\n double hiy=lexical_cast<double>(rs->getValue(3));\t\t \n extent_.init(lox,loy,hix,hiy);\n extent_initialized_ = true;\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n }\n rs->close();\n }\n }\n return extent_;\n}\n\npostgis_datasource::~postgis_datasource() {}\n<commit_msg>postgis: add a hint if the extent parsing fails<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $\n\n\/\/ mapnik\n#include <mapnik\/global.hpp>\n#include <mapnik\/ptree_helpers.hpp>\n#include \"connection_manager.hpp\"\n#include \"postgis.hpp\"\n\n\/\/ boost\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/tokenizer.hpp>\n\n\/\/ stl\n#include <string>\n#include <algorithm>\n#include <set>\n#include <sstream>\n#include <iomanip>\n\n#ifndef MAPNIK_BIG_ENDIAN\n#define WKB_ENCODING \"NDR\"\n#else\n#define WKB_ENCODING \"XDR\"\n#endif\n\nDATASOURCE_PLUGIN(postgis_datasource)\n\nconst std::string postgis_datasource::GEOMETRY_COLUMNS=\"geometry_columns\";\nconst std::string postgis_datasource::SPATIAL_REF_SYS=\"spatial_ref_system\";\n\nusing std::clog;\nusing std::endl;\n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\nusing boost::shared_ptr;\n\nusing mapnik::PoolGuard;\nusing mapnik::attribute_descriptor;\n\npostgis_datasource::postgis_datasource(parameters const& params)\n : datasource (params),\n table_(*params.get<std::string>(\"table\",\"\")),\n geometry_field_(*params.get<std::string>(\"geometry_field\",\"\")),\n cursor_fetch_size_(*params_.get<int>(\"cursor_size\",0)),\n row_limit_(*params_.get<int>(\"row_limit\",0)),\n type_(datasource::Vector),\n extent_initialized_(false),\n desc_(*params.get<std::string>(\"type\"),\"utf-8\"),\n creator_(params.get<std::string>(\"host\"),\n params.get<std::string>(\"port\"),\n params.get<std::string>(\"dbname\"),\n params.get<std::string>(\"user\"),\n params.get<std::string>(\"password\")),\n bbox_token_(\"!bbox!\")\n{ \n\n boost::optional<int> initial_size = params_.get<int>(\"inital_size\",1);\n boost::optional<int> max_size = params_.get<int>(\"max_size\",10);\n\n multiple_geometries_ = *params_.get<mapnik::boolean>(\"multiple_geometries\",false);\n \n boost::optional<std::string> ext = params_.get<std::string>(\"extent\");\n if (ext)\n {\n boost::char_separator<char> sep(\",\");\n boost::tokenizer<boost::char_separator<char> > tok(*ext,sep);\n unsigned i = 0;\n bool success = false;\n double d[4];\n for (boost::tokenizer<boost::char_separator<char> >::iterator beg=tok.begin(); \n beg!=tok.end();++beg)\n {\n try \n {\n d[i] = boost::lexical_cast<double>(boost::trim_copy(*beg));\n }\n catch (boost::bad_lexical_cast & ex)\n {\n std::clog << *beg << \" : \" << ex.what() << \"\\nAre your coordinates each separated by commas?\\n\";\n break;\n }\n if (i==3) \n {\n success = true;\n break;\n }\n ++i;\n }\n if (success)\n {\n extent_.init(d[0],d[1],d[2],d[3]);\n extent_initialized_ = true;\n }\n } \n\n ConnectionManager *mgr=ConnectionManager::instance(); \n mgr->registerPool(creator_, *initial_size, *max_size);\n \n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n { \n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n PoolGuard<shared_ptr<Connection>,\n shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n \n desc_.set_encoding(conn->client_encoding());\n \n std::string table_name=table_from_sql(table_);\n std::string schema_name=\"\";\n std::string::size_type idx=table_name.find_last_of('.');\n if (idx!=std::string::npos)\n {\n schema_name=table_name.substr(0,idx);\n table_name=table_name.substr(idx+1);\n }\n else\n {\n table_name=table_name.substr(0);\n }\n\n std::ostringstream s;\n s << \"select f_geometry_column,srid,type from \";\n s << GEOMETRY_COLUMNS <<\" where f_table_name='\" << table_name<<\"'\";\n \n if (schema_name.length() > 0)\n s <<\" and f_table_schema='\"<< schema_name <<\"'\";\n\n if (geometry_field_.length() > 0)\n s << \" and f_geometry_column = '\" << geometry_field_ << \"'\";\n \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n try \n {\n srid_ = lexical_cast<int>(rs->getValue(\"srid\"));\n }\n catch (bad_lexical_cast &ex)\n {\n clog << rs->getValue(\"srid\") << \":\" << ex.what() << endl;\n }\n geometryColumn_=rs->getValue(\"f_geometry_column\");\n std::string postgisType=rs->getValue(\"type\");\n }\n rs->close();\n \n \/\/ collect attribute desc\n s.str(\"\");\n std::string table_with_bbox = populate_sql_bbox(table_,extent_);\n s << \"select * from \" << table_with_bbox << \" limit 0\";\n rs=conn->executeQuery(s.str());\n int count = rs->getNumFields();\n for (int i=0;i<count;++i)\n {\n std::string fld_name=rs->getFieldName(i);\n int type_oid = rs->getTypeOID(i);\n switch (type_oid)\n {\n case 21: \/\/ int2\n case 23: \/\/ int4\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));\n break;\n case 700: \/\/ float4 \n case 701: \/\/ float8\n case 1700: \/\/ numeric ??\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));\n case 1042: \/\/ bpchar\n case 1043: \/\/ varchar\n case 25: \/\/ text\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n break;\n default: \/\/ shouldn't get here\n#ifdef MAPNIK_DEBUG\n clog << \"unknown type_oid=\"<<type_oid<<endl;\n#endif\n break;\n }\t \n }\n }\n }\n}\n\nstd::string const postgis_datasource::name_=\"postgis\";\n\nstd::string postgis_datasource::name()\n{\n return name_;\n}\n\nint postgis_datasource::type() const\n{\n return type_;\n}\n\nlayer_descriptor postgis_datasource::get_descriptor() const\n{\n return desc_;\n}\n\nstd::string postgis_datasource::populate_sql_bbox(const std::string& sql, Envelope<double> const& box) const\n{\n std::string sql_with_bbox = boost::algorithm::to_lower_copy(sql);\n std::ostringstream b;\n b << \"SetSRID('BOX3D(\";\n b << std::setprecision(16);\n b << box.minx() << \" \" << box.miny() << \",\";\n b << box.maxx() << \" \" << box.maxy() << \")'::box3d,\" << srid_ << \")\";\n if ( boost::algorithm::icontains(sql,bbox_token_) )\n {\n boost::algorithm::replace_all(sql_with_bbox,bbox_token_,b.str());\n return sql_with_bbox;\n }\n else\n {\n std::ostringstream s;\n s << \" WHERE \\\"\" << geometryColumn_ << \"\\\" && \" << b.str();\n return sql_with_bbox + s.str(); \n }\n}\n\nstd::string postgis_datasource::table_from_sql(const std::string& sql)\n{\n std::string table_name = boost::algorithm::to_lower_copy(sql);\n boost::algorithm::replace_all(table_name,\"\\n\",\" \");\n \n std::string::size_type idx = table_name.rfind(\" from \");\n if (idx!=std::string::npos)\n {\n \n idx=table_name.find_first_not_of(\" \",idx+5);\n if (idx != std::string::npos)\n {\n table_name=table_name.substr(idx);\n }\n idx=table_name.find_first_of(\" )\");\n if (idx != std::string::npos)\n {\n table_name = table_name.substr(0,idx);\n }\n }\n return table_name;\n}\n\nboost::shared_ptr<IResultSet> postgis_datasource::get_resultset(boost::shared_ptr<Connection> const &conn, const std::string &sql) const\n{\n if (cursor_fetch_size_ > 0) {\n \/\/ cursor\n std::ostringstream csql;\n std::string cursor_name = conn->new_cursor_name();\n\n csql << \"DECLARE \" << cursor_name << \" BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR \" << sql << \" FOR READ ONLY\";\n\n#ifdef MAPNIK_DEBUG\n std::clog << csql.str() << \"\\n\";\n#endif\n if (!conn->execute(csql.str())) {\n throw mapnik::datasource_exception( \"PSQL Error: Creating cursor for data select.\" );\n }\n return shared_ptr<CursorResultSet>(new CursorResultSet(conn, cursor_name, cursor_fetch_size_));\n\n } else {\n \/\/ no cursor\n#ifdef MAPNIK_DEBUG\n std::clog << sql << \"\\n\";\n#endif\n return conn->executeQuery(sql,1);\n }\n}\n\nfeatureset_ptr postgis_datasource::features(const query& q) const\n{\n Envelope<double> const& box=q.get_bbox();\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n\n std::ostringstream s;\n s << \"SELECT AsBinary(\\\"\"<<geometryColumn_<<\"\\\",'\"<< WKB_ENCODING << \"') AS geom\";\n std::set<std::string> const& props=q.property_names();\n std::set<std::string>::const_iterator pos=props.begin();\n std::set<std::string>::const_iterator end=props.end();\n while (pos != end)\n {\n s <<\",\\\"\"<<*pos<<\"\\\"\";\n ++pos;\n }\t \n\n std::string table_with_bbox = populate_sql_bbox(table_,box);\n\n s << \" from \" << table_with_bbox;\n\n if (row_limit_ > 0) {\n s << \" LIMIT \" << row_limit_;\n }\n \n boost::shared_ptr<IResultSet> rs = get_resultset(conn, s.str());\n return featureset_ptr(new postgis_featureset(rs,desc_.get_encoding(),multiple_geometries_,props.size()));\n }\n }\n return featureset_ptr();\n}\n\nfeatureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const\n{\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"SELECT AsBinary(\\\"\" << geometryColumn_ << \"\\\",'\"<< WKB_ENCODING << \"') AS geom\";\n \n std::vector<attribute_descriptor>::const_iterator itr = desc_.get_descriptors().begin();\n std::vector<attribute_descriptor>::const_iterator end = desc_.get_descriptors().end();\n unsigned size=0;\n while (itr != end)\n {\n s <<\",\\\"\"<< itr->get_name() << \"\\\"\";\n ++itr;\n ++size;\n }\n\n Envelope<double> box(pt.x,pt.y,pt.x,pt.y);\n std::string table_with_bbox = populate_sql_bbox(table_,box);\n\n s << \" from \" << table_with_bbox;\n \n if (row_limit_ > 0) {\n s << \" LIMIT \" << row_limit_;\n }\n \n boost::shared_ptr<IResultSet> rs = get_resultset(conn, s.str());\n return featureset_ptr(new postgis_featureset(rs,desc_.get_encoding(),multiple_geometries_, size));\n }\n }\n return featureset_ptr();\n}\n\nEnvelope<double> postgis_datasource::envelope() const\n{\n if (extent_initialized_) return extent_;\n \n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::ostringstream s;\n std::string table_name = table_from_sql(table_);\n boost::optional<std::string> estimate_extent = params_.get<std::string>(\"estimate_extent\");\n \n if (estimate_extent && *estimate_extent == \"true\")\n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select estimated_extent('\" \n << table_name <<\"','\" \n << geometryColumn_ << \"') as ext) as tmp\";\n }\n else \n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select extent(\" <<geometryColumn_<< \") as ext from \" \n << table_name << \") as tmp\";\n }\n \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n try \n {\n double lox=lexical_cast<double>(rs->getValue(0));\n double loy=lexical_cast<double>(rs->getValue(1));\n double hix=lexical_cast<double>(rs->getValue(2));\n double hiy=lexical_cast<double>(rs->getValue(3));\t\t \n extent_.init(lox,loy,hix,hiy);\n extent_initialized_ = true;\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n }\n rs->close();\n }\n }\n return extent_;\n}\n\npostgis_datasource::~postgis_datasource() {}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* ref.hpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#ifndef GODOT_CPP_REF_HPP\n#define GODOT_CPP_REF_HPP\n\n#include <godot_cpp\/core\/defs.hpp>\n\n#include <godot_cpp\/classes\/object.hpp>\n#include <godot_cpp\/classes\/ref_counted.hpp>\n#include <godot_cpp\/core\/memory.hpp>\n#include <godot_cpp\/variant\/variant.hpp>\n\nnamespace godot {\n\n\/\/ Helper class for RefCounted objects, same as Godot one.\n\nclass RefCounted;\n\ntemplate <class T>\nclass Ref {\n\tT *reference = nullptr;\n\n\tvoid ref(const Ref &p_from) {\n\t\tif (p_from.reference == reference) {\n\t\t\treturn;\n\t\t}\n\n\t\tunref();\n\n\t\treference = p_from.reference;\n\t\tif (reference) {\n\t\t\treference->reference();\n\t\t}\n\t}\n\n\tvoid ref_pointer(T *p_ref) {\n\t\tERR_FAIL_COND(!p_ref);\n\n\t\tif (p_ref->init_ref()) {\n\t\t\treference = p_ref;\n\t\t}\n\t}\n\npublic:\n\t_FORCE_INLINE_ bool operator==(const T *p_ptr) const {\n\t\treturn reference == p_ptr;\n\t}\n\t_FORCE_INLINE_ bool operator!=(const T *p_ptr) const {\n\t\treturn reference != p_ptr;\n\t}\n\n\t_FORCE_INLINE_ bool operator<(const Ref<T> &p_r) const {\n\t\treturn reference < p_r.reference;\n\t}\n\t_FORCE_INLINE_ bool operator==(const Ref<T> &p_r) const {\n\t\treturn reference == p_r.reference;\n\t}\n\t_FORCE_INLINE_ bool operator!=(const Ref<T> &p_r) const {\n\t\treturn reference != p_r.reference;\n\t}\n\n\t_FORCE_INLINE_ T *operator->() {\n\t\treturn reference;\n\t}\n\n\t_FORCE_INLINE_ T *operator*() {\n\t\treturn reference;\n\t}\n\n\t_FORCE_INLINE_ const T *operator->() const {\n\t\treturn reference;\n\t}\n\n\t_FORCE_INLINE_ const T *ptr() const {\n\t\treturn reference;\n\t}\n\t_FORCE_INLINE_ T *ptr() {\n\t\treturn reference;\n\t}\n\n\t_FORCE_INLINE_ const T *operator*() const {\n\t\treturn reference;\n\t}\n\n\toperator Variant() const {\n\t\treturn Variant(reference);\n\t}\n\n\tvoid operator=(const Ref &p_from) {\n\t\tref(p_from);\n\t}\n\n\ttemplate <class T_Other>\n\tvoid operator=(const Ref<T_Other> &p_from) {\n\t\tRefCounted *refb = const_cast<RefCounted *>(static_cast<const RefCounted *>(p_from.ptr()));\n\t\tif (!refb) {\n\t\t\tunref();\n\t\t\treturn;\n\t\t}\n\t\tRef r;\n\t\tr.reference = Object::cast_to<T>(refb);\n\t\tref(r);\n\t\tr.reference = nullptr;\n\t}\n\n\tvoid operator=(const Variant &p_variant) {\n\t\t\/\/ FIXME\n\t\t\/\/ Object *object = p_variant.get_validated_object();\n\n\t\t\/\/ if (object == reference) {\n\t\t\/\/ \treturn;\n\t\t\/\/ }\n\n\t\t\/\/ unref();\n\n\t\t\/\/ if (!object) {\n\t\t\/\/ \treturn;\n\t\t\/\/ }\n\n\t\t\/\/ T *r = Object::cast_to<T>(object);\n\t\t\/\/ if (r && r->reference()) {\n\t\t\/\/ \treference = r;\n\t\t\/\/ }\n\t}\n\n\ttemplate <class T_Other>\n\tvoid reference_ptr(T_Other *p_ptr) {\n\t\tif (reference == p_ptr) {\n\t\t\treturn;\n\t\t}\n\t\tunref();\n\n\t\tT *r = Object::cast_to<T>(p_ptr);\n\t\tif (r) {\n\t\t\tref_pointer(r);\n\t\t}\n\t}\n\n\tRef(const Ref &p_from) {\n\t\tref(p_from);\n\t}\n\n\tRef(T *p_reference) {\n\t\tif (p_reference) {\n\t\t\tref_pointer(p_reference);\n\t\t}\n\t}\n\n\tRef(const Variant &p_variant) {\n\t\t\/\/ FIXME\n\t\t\/\/ Object *object = p_variant.get_validated_object();\n\n\t\t\/\/ if (!object) {\n\t\t\/\/ \treturn;\n\t\t\/\/ }\n\n\t\t\/\/ T *r = Object::cast_to<T>(object);\n\t\t\/\/ if (r && r->reference()) {\n\t\t\/\/ \treference = r;\n\t\t\/\/ }\n\t}\n\n\tinline bool is_valid() const { return reference != nullptr; }\n\tinline bool is_null() const { return reference == nullptr; }\n\n\tvoid unref() {\n\t\tif (reference && reference->unreference()) {\n\t\t\tmemdelete(reference);\n\t\t}\n\t\treference = nullptr;\n\t}\n\n\tvoid instantiate() {\n\t\tref(memnew(T()));\n\t}\n\n\tRef() {}\n\n\t~Ref() {\n\t\tunref();\n\t}\n\n\t\/\/ Used exclusively in the bindings to recreate the Ref Godot encapsulates in return values,\n\t\/\/ without adding to the refcount.\n\tinline static Ref<T> ___internal_constructor(Object *obj) {\n\t\tRef<T> r;\n\t\tr.reference = (T *)obj;\n\t\treturn r;\n\t}\n};\n\n} \/\/ namespace godot\n\n#endif \/\/ ! GODOT_CPP_REF_HPP\n<commit_msg>Implement Ref copy constructor<commit_after>\/*************************************************************************\/\n\/* ref.hpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#ifndef GODOT_CPP_REF_HPP\n#define GODOT_CPP_REF_HPP\n\n#include <godot_cpp\/core\/defs.hpp>\n\n#include <godot_cpp\/classes\/object.hpp>\n#include <godot_cpp\/classes\/ref_counted.hpp>\n#include <godot_cpp\/core\/memory.hpp>\n#include <godot_cpp\/variant\/variant.hpp>\n\nnamespace godot {\n\n\/\/ Helper class for RefCounted objects, same as Godot one.\n\nclass RefCounted;\n\ntemplate <class T>\nclass Ref {\n\tT *reference = nullptr;\n\n\tvoid ref(const Ref &p_from) {\n\t\tif (p_from.reference == reference) {\n\t\t\treturn;\n\t\t}\n\n\t\tunref();\n\n\t\treference = p_from.reference;\n\t\tif (reference) {\n\t\t\treference->reference();\n\t\t}\n\t}\n\n\tvoid ref_pointer(T *p_ref) {\n\t\tERR_FAIL_COND(!p_ref);\n\n\t\tif (p_ref->init_ref()) {\n\t\t\treference = p_ref;\n\t\t}\n\t}\n\npublic:\n\t_FORCE_INLINE_ bool operator==(const T *p_ptr) const {\n\t\treturn reference == p_ptr;\n\t}\n\t_FORCE_INLINE_ bool operator!=(const T *p_ptr) const {\n\t\treturn reference != p_ptr;\n\t}\n\n\t_FORCE_INLINE_ bool operator<(const Ref<T> &p_r) const {\n\t\treturn reference < p_r.reference;\n\t}\n\t_FORCE_INLINE_ bool operator==(const Ref<T> &p_r) const {\n\t\treturn reference == p_r.reference;\n\t}\n\t_FORCE_INLINE_ bool operator!=(const Ref<T> &p_r) const {\n\t\treturn reference != p_r.reference;\n\t}\n\n\t_FORCE_INLINE_ T *operator->() {\n\t\treturn reference;\n\t}\n\n\t_FORCE_INLINE_ T *operator*() {\n\t\treturn reference;\n\t}\n\n\t_FORCE_INLINE_ const T *operator->() const {\n\t\treturn reference;\n\t}\n\n\t_FORCE_INLINE_ const T *ptr() const {\n\t\treturn reference;\n\t}\n\t_FORCE_INLINE_ T *ptr() {\n\t\treturn reference;\n\t}\n\n\t_FORCE_INLINE_ const T *operator*() const {\n\t\treturn reference;\n\t}\n\n\toperator Variant() const {\n\t\treturn Variant(reference);\n\t}\n\n\tvoid operator=(const Ref &p_from) {\n\t\tref(p_from);\n\t}\n\n\ttemplate <class T_Other>\n\tvoid operator=(const Ref<T_Other> &p_from) {\n\t\tRefCounted *refb = const_cast<RefCounted *>(static_cast<const RefCounted *>(p_from.ptr()));\n\t\tif (!refb) {\n\t\t\tunref();\n\t\t\treturn;\n\t\t}\n\n\t\tRef r;\n\t\tr.reference = Object::cast_to<T>(refb);\n\t\tref(r);\n\t\tr.reference = nullptr;\n\t}\n\n\tvoid operator=(const Variant &p_variant) {\n\t\t\/\/ Needs testing, Variant has a cast to Object * here.\n\n\t\t\/\/ Object *object = p_variant.get_validated_object();\n\t\tObject *object = p_variant;\n\n\t\tif (object == reference) {\n\t\t\treturn;\n\t\t}\n\n\t\tunref();\n\n\t\tif (!object) {\n\t\t\treturn;\n\t\t}\n\n\t\tT *r = Object::cast_to<T>(object);\n\t\tif (r && r->reference()) {\n\t\t\treference = r;\n\t\t}\n\t}\n\n\ttemplate <class T_Other>\n\tvoid reference_ptr(T_Other *p_ptr) {\n\t\tif (reference == p_ptr) {\n\t\t\treturn;\n\t\t}\n\t\tunref();\n\n\t\tT *r = Object::cast_to<T>(p_ptr);\n\t\tif (r) {\n\t\t\tref_pointer(r);\n\t\t}\n\t}\n\n\tRef(const Ref &p_from) {\n\t\tref(p_from);\n\t}\n\n\ttemplate <class T_Other>\n\tRef(const Ref<T_Other> &p_from) {\n\t\tRefCounted *refb = const_cast<RefCounted *>(static_cast<const RefCounted *>(p_from.ptr()));\n\t\tif (!refb) {\n\t\t\tunref();\n\t\t\treturn;\n\t\t}\n\n\t\tRef r;\n\t\tr.reference = Object::cast_to<T>(refb);\n\t\tref(r);\n\t\tr.reference = nullptr;\n\t}\n\n\tRef(T *p_reference) {\n\t\tif (p_reference) {\n\t\t\tref_pointer(p_reference);\n\t\t}\n\t}\n\n\tRef(const Variant &p_variant) {\n\t\t\/\/ Needs testing, Variant has a cast to Object * here.\n\n\t\t\/\/ Object *object = p_variant.get_validated_object();\n\t\tObject *object = p_variant;\n\n\t\tif (!object) {\n\t\t\treturn;\n\t\t}\n\n\t\tT *r = Object::cast_to<T>(object);\n\t\tif (r && r->reference()) {\n\t\t\treference = r;\n\t\t}\n\t}\n\n\tinline bool is_valid() const { return reference != nullptr; }\n\tinline bool is_null() const { return reference == nullptr; }\n\n\tvoid unref() {\n\t\tif (reference && reference->unreference()) {\n\t\t\tmemdelete(reference);\n\t\t}\n\t\treference = nullptr;\n\t}\n\n\tvoid instantiate() {\n\t\tref(memnew(T()));\n\t}\n\n\tRef() {}\n\n\t~Ref() {\n\t\tunref();\n\t}\n\n\t\/\/ Used exclusively in the bindings to recreate the Ref Godot encapsulates in return values,\n\t\/\/ without adding to the refcount.\n\tinline static Ref<T> ___internal_constructor(Object *obj) {\n\t\tRef<T> r;\n\t\tr.reference = (T *)obj;\n\t\treturn r;\n\t}\n};\n\n} \/\/ namespace godot\n\n#endif \/\/ ! GODOT_CPP_REF_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/main:$Id$\n\/\/ Author: Fons Rademakers 15\/02\/97\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ PMain \/\/\n\/\/ \/\/\n\/\/ Main program used to create PROOF server application. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <stdio.h>\n#include <errno.h>\n\n#ifdef WIN32\n#include <io.h>\n#endif\n#include <stdio.h>\n#include <errno.h>\n#include <stdlib.h>\n\n#include \"RConfigure.h\"\n#ifdef R__AFS\n#include \"TAFS.h\"\n#endif\n#include \"TApplication.h\"\n#include \"TInterpreter.h\"\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n\n\/\/ Special type for the hook to the TXProofServ constructor, needed to avoid\n\/\/ using the plugin manager\ntypedef TApplication *(*TProofServ_t)(Int_t *argc, char **argv, FILE *flog);\n#ifdef R__AFS\n\/\/ Special type for the hook to the TAFS constructor, needed to avoid\n\/\/ using the plugin manager\ntypedef TAFS *(*TAFS_t)(const char *, const char *, Int_t);\n\/\/ Instance of the AFS token class\nstatic TAFS *gAFS = 0;\n#endif\n\n\/\/______________________________________________________________________________\nstatic void ReadPutEnvs(const char *envfile)\n{\n \/\/ Read envs from file 'envfile' and add them to the env space\n\n \/\/ Check inputs\n if (!envfile || strlen(envfile) <= 0) return;\n\n \/\/ Open the file\n FILE *fenv = fopen(envfile, \"r\");\n if (!fenv) return;\n\n \/\/ Read lines\n char ln[4096];\n while (fgets(ln, sizeof(ln), fenv)) {\n int l = strlen(ln);\n \/\/ Strip '\\n'\n if (l > 0 && ln[l-1] == '\\n') { ln[l-1] = '\\0'; l--; }\n \/\/ Skip comments or empty line\n if (l <= 0 || ln[0] == '#') continue;\n \/\/ Skip lines not in the form '<name>=<value>'\n if (!strchr(ln, '=')) continue;\n \/\/ Good line\n char *ev = new char[l+1];\n strcpy(ev, ln);\n putenv(ev);\n }\n\n \/\/ Close the file\n fclose(fenv);\n}\n\n\/\/______________________________________________________________________________\nstatic FILE *RedirectOutput(const char *logfile, const char *loc)\n{\n \/\/ Redirect stdout to 'logfile'. This log file will be flushed to the\n \/\/ client or master after each command.\n \/\/ On success return a pointer to the open log file. Return 0 on failure.\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: enter: %s\\n\", loc, logfile);\n\n if (!logfile || strlen(logfile) <= 0) {\n fprintf(stderr,\"%s: RedirectOutput: logfile path undefined\\n\", loc);\n return 0;\n }\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: reopen %s\\n\", loc, logfile);\n FILE *flog = freopen(logfile, \"a\", stdout);\n if (!flog) {\n fprintf(stderr,\"%s: RedirectOutput: could not freopen stdout\\n\", loc);\n return 0;\n }\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: dup2 ...\\n\", loc);\n if ((dup2(fileno(stdout), fileno(stderr))) < 0) {\n fprintf(stderr,\"%s: RedirectOutput: could not redirect stderr\\n\", loc);\n return 0;\n }\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: read open ...\\n\", loc);\n FILE *fLog = fopen(logfile, \"r\");\n if (!fLog) {\n fprintf(stderr,\"%s: RedirectOutput: could not open logfile %s\\n\", loc, logfile);\n return 0;\n }\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: done!\\n\", loc);\n \/\/ We are done\n return fLog;\n}\n\n#ifdef R__AFS\n\/\/______________________________________________________________________________\nstatic Int_t InitAFS(const char *fileafs, const char *loc)\n{\n \/\/ Init AFS token using credentials at fileafs\n\n TString getter(\"GetTAFS\");\n char *p = 0;\n TString afslib = \"libAFSAuth\";\n if ((p = gSystem->DynamicPathName(afslib, kTRUE))) {\n delete[] p;\n if (gSystem->Load(afslib) == -1) {\n if (loc)\n fprintf(stderr,\"%s: can't load %s\\n\", loc, afslib.Data());\n return -1;\n }\n } else {\n if (loc)\n fprintf(stderr,\"%s: can't locate %s\\n\", loc, afslib.Data());\n return -1;\n }\n\n \/\/ Locate constructor\n Func_t f = gSystem->DynFindSymbol(afslib, getter);\n if (f) {\n gAFS = (*((TAFS_t)f))(fileafs, 0, -1);\n if (!gAFS) {\n if (loc)\n fprintf(stderr,\"%s: could not initialize a valid TAFS\\n\", loc);\n return -1;\n }\n } else {\n if (loc)\n fprintf(stderr,\"%s: can't find %s\\n\", loc, getter.Data());\n return -1;\n }\n\n \/\/ Done\n return 0;\n}\n#endif\n\n\/\/______________________________________________________________________________\nint main(int argc, char **argv)\n{\n \/\/ PROOF server main program.\n\n#ifdef R__DEBUG\n int debug = 1;\n while (debug)\n ;\n#endif\n if (argc >= 6) {\n \/\/ Read and put system envs\n ReadPutEnvs(argv[5]);\n }\n\n int loglevel = (argc >= 5) ? strtol(argv[4], 0, 10) : -1;\n if (loglevel < 0 && getenv(\"ROOTPROOFLOGLEVEL\"))\n loglevel = atoi(getenv(\"ROOTPROOFLOGLEVEL\"));\n if (loglevel > 0)\n fprintf(stderr,\"%s: starting %s\\n\", argv[1], argv[0]);\n\n \/\/ Redirect the output\n FILE *fLog = 0;\n char *loc = 0;\n char *logfile = (char *)getenv(\"ROOTPROOFLOGFILE\");\n if (logfile && !getenv(\"ROOTPROOFDONOTREDIR\")) {\n loc = (loglevel > 0) ? argv[1] : 0;\n if (loglevel > 0)\n fprintf(stderr,\"%s: redirecting output to %s\\n\", argv[1], logfile);\n if (!(fLog = RedirectOutput(logfile, loc))) {\n fprintf(stderr,\"%s: problems redirecting output to file %s\\n\", argv[1], logfile);\n exit(1);\n }\n }\n if (loglevel > 0)\n fprintf(stderr,\"%s: output redirected to: %s\\n\",\n argv[1], (logfile ? logfile : \"+++not redirected+++\"));\n\n#ifdef R__AFS\n \/\/ Init AFS, if required\n if (getenv(\"ROOTPROOFAFSCREDS\")) {\n if (InitAFS(getenv(\"ROOTPROOFAFSCREDS\"), loc) != 0) {\n fprintf(stderr,\"%s: unable to initialize the AFS token\\n\", argv[1]);\n } else {\n if (loglevel > 0)\n fprintf(stderr,\"%s: AFS token initialized\\n\", argv[1]);\n }\n }\n#endif\n\n gROOT->SetBatch();\n TApplication *theApp = 0;\n\n \/\/ Enable autoloading\n gInterpreter->EnableAutoLoading();\n\n TString getter(\"GetTProofServ\");\n TString prooflib = \"libProof\";\n if (argc > 2) {\n if (!strcmp(argv[2], \"lite\")) {\n \/\/ Lite version for local processing\n getter = \"GetTProofServLite\";\n } else if (!strcmp(argv[2], \"xpd\")) {\n \/\/ XPD: additionally load the appropriate library\n prooflib = \"libProofx\";\n getter = \"GetTXProofServ\";\n }\n }\n char *p = 0;\n if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {\n delete[] p;\n if (gSystem->Load(prooflib) == -1) {\n fprintf(stderr,\"%s: can't load %s\\n\", argv[1], prooflib.Data());\n exit(1);\n }\n } else {\n fprintf(stderr,\"%s: can't locate %s\\n\", argv[1], prooflib.Data());\n exit(1);\n }\n\n \/\/ Locate constructor\n Func_t f = gSystem->DynFindSymbol(prooflib, getter);\n if (f) {\n theApp = (TApplication *) (*((TProofServ_t)f))(&argc, argv, fLog);\n } else {\n fprintf(stderr,\"%s: can't find %s\\n\", argv[1], getter.Data());\n exit(1);\n }\n\n \/\/ Ready to run\n if (loglevel > 0)\n fprintf(stderr,\"%s: running the TProofServ application\\n\", argv[1]);\n\n theApp->Run();\n\n#ifdef R__AFS\n \/\/ Cleanup\n if (gAFS)\n delete gAFS;\n#endif\n\n \/\/ We can exit now\n gSystem->Exit(0);\n}\n<commit_msg>From Gerri: Enable the possibility to set hard and soft limits on the virtual memory used by the worker processes. This is done by calls to setrlimit with flag RLIMIT_AS. The two envs are called ROOTPROOFASSOFT and ROOTPROOFASHARD and the values are in MBs.<commit_after>\/\/ @(#)root\/main:$Id$\n\/\/ Author: Fons Rademakers 15\/02\/97\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ PMain \/\/\n\/\/ \/\/\n\/\/ Main program used to create PROOF server application. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <stdio.h>\n#include <errno.h>\n\n#ifdef WIN32\n#include <io.h>\n#endif\n#include <stdio.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/resource.h>\n\n#include \"RConfig.h\"\n#include \"RConfigure.h\"\n#ifdef R__AFS\n#include \"TAFS.h\"\n#endif\n#include \"TApplication.h\"\n#include \"TInterpreter.h\"\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n\n\/\/ Macros to check memory ranges\n#ifdef R__B64\n# define P_LONGOK(x) (1)\n#else\n# define P_LONGOK(x) (x > LONG_MIN && x < LONG_MAX)\n#endif\n#define P_MBTOBYTES (1024*1024)\n\nstatic int gLogLevel = 0;\n\n\/\/ Special type for the hook to the TXProofServ constructor, needed to avoid\n\/\/ using the plugin manager\ntypedef TApplication *(*TProofServ_t)(Int_t *argc, char **argv, FILE *flog);\n\n#ifdef R__AFS\n\/\/ Special type for the hook to the TAFS constructor, needed to avoid\n\/\/ using the plugin manager\ntypedef TAFS *(*TAFS_t)(const char *, const char *, Int_t);\n\/\/ Instance of the AFS token class\nstatic TAFS *gAFS = 0;\n#endif\n\n\/\/______________________________________________________________________________\nstatic void ReadPutEnvs(const char *envfile)\n{\n \/\/ Read envs from file 'envfile' and add them to the env space\n\n \/\/ Check inputs\n if (!envfile || strlen(envfile) <= 0) return;\n\n \/\/ Open the file\n FILE *fenv = fopen(envfile, \"r\");\n if (!fenv) return;\n\n \/\/ Read lines\n char ln[4096];\n while (fgets(ln, sizeof(ln), fenv)) {\n int l = strlen(ln);\n \/\/ Strip '\\n'\n if (l > 0 && ln[l-1] == '\\n') { ln[l-1] = '\\0'; l--; }\n \/\/ Skip comments or empty line\n if (l <= 0 || ln[0] == '#') continue;\n \/\/ Skip lines not in the form '<name>=<value>'\n if (!strchr(ln, '=')) continue;\n \/\/ Good line\n char *ev = new char[l+1];\n strcpy(ev, ln);\n putenv(ev);\n }\n\n \/\/ Close the file\n fclose(fenv);\n}\n\n\/\/______________________________________________________________________________\nstatic FILE *RedirectOutput(const char *logfile, const char *loc)\n{\n \/\/ Redirect stdout to 'logfile'. This log file will be flushed to the\n \/\/ client or master after each command.\n \/\/ On success return a pointer to the open log file. Return 0 on failure.\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: enter: %s\\n\", loc, logfile);\n\n if (!logfile || strlen(logfile) <= 0) {\n fprintf(stderr,\"%s: RedirectOutput: logfile path undefined\\n\", loc);\n return 0;\n }\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: reopen %s\\n\", loc, logfile);\n FILE *flog = freopen(logfile, \"a\", stdout);\n if (!flog) {\n fprintf(stderr,\"%s: RedirectOutput: could not freopen stdout\\n\", loc);\n return 0;\n }\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: dup2 ...\\n\", loc);\n if ((dup2(fileno(stdout), fileno(stderr))) < 0) {\n fprintf(stderr,\"%s: RedirectOutput: could not redirect stderr\\n\", loc);\n return 0;\n }\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: read open ...\\n\", loc);\n FILE *fLog = fopen(logfile, \"r\");\n if (!fLog) {\n fprintf(stderr,\"%s: RedirectOutput: could not open logfile %s\\n\", loc, logfile);\n return 0;\n }\n\n if (loc)\n fprintf(stderr,\"%s: RedirectOutput: done!\\n\", loc);\n \/\/ We are done\n return fLog;\n}\n\n\/\/______________________________________________________________________________\nstatic void SetMaxMemLimits(const char *prog)\n{\n \/\/ Set limits on the address space (virtual memory) if required.\n\n const char *assoft = gSystem->Getenv(\"ROOTPROOFASSOFT\");\n const char *ashard = gSystem->Getenv(\"ROOTPROOFASHARD\");\n\n if (assoft || ashard) {\n struct rlimit aslim, aslimref;\n if (getrlimit(RLIMIT_AS, &aslimref) != 0) {\n fprintf(stderr,\"%s: problems getting RLIMIT_AS values (errno: %d)\\n\", prog, errno);\n exit(1);\n }\n if (gLogLevel > 0)\n fprintf(stderr, \"%s: memory limits currently set to %lld (soft) and %lld (hard) bytes\\n\",\n prog, (Long64_t)aslimref.rlim_cur, (Long64_t)aslimref.rlim_max);\n aslim.rlim_cur = aslimref.rlim_cur;\n aslim.rlim_max = aslimref.rlim_max;\n if (assoft) {\n long rlim_cur = strtol(assoft, 0, 10);\n if (P_LONGOK(rlim_cur) && rlim_cur > 0)\n aslim.rlim_cur = (unsigned long) rlim_cur * P_MBTOBYTES;\n }\n if (ashard) {\n long rlim_max = strtol(ashard, 0, 10);\n if (P_LONGOK(rlim_max) && rlim_max > 0)\n aslim.rlim_max = (unsigned long) rlim_max * P_MBTOBYTES;\n }\n \/\/ Change the limits, if required\n if (aslim.rlim_cur != aslimref.rlim_cur || aslim.rlim_max != aslimref.rlim_max) {\n fprintf(stderr, \"%s: setting memory limits to %lld (soft) and %lld (hard) bytes\\n\",\n prog, (Long64_t)aslim.rlim_cur, (Long64_t)aslim.rlim_max);\n if (setrlimit(RLIMIT_AS, &aslim) != 0) {\n fprintf(stderr,\"%s: problems setting RLIMIT_AS values (errno: %d)\\n\", prog, errno);\n exit(1);\n }\n }\n }\n}\n\n#ifdef R__AFS\n\/\/______________________________________________________________________________\nstatic Int_t InitAFS(const char *fileafs, const char *loc)\n{\n \/\/ Init AFS token using credentials at fileafs\n\n TString getter(\"GetTAFS\");\n char *p = 0;\n TString afslib = \"libAFSAuth\";\n if ((p = gSystem->DynamicPathName(afslib, kTRUE))) {\n delete[] p;\n if (gSystem->Load(afslib) == -1) {\n if (loc)\n fprintf(stderr,\"%s: can't load %s\\n\", loc, afslib.Data());\n return -1;\n }\n } else {\n if (loc)\n fprintf(stderr,\"%s: can't locate %s\\n\", loc, afslib.Data());\n return -1;\n }\n\n \/\/ Locate constructor\n Func_t f = gSystem->DynFindSymbol(afslib, getter);\n if (f) {\n gAFS = (*((TAFS_t)f))(fileafs, 0, -1);\n if (!gAFS) {\n if (loc)\n fprintf(stderr,\"%s: could not initialize a valid TAFS\\n\", loc);\n return -1;\n }\n } else {\n if (loc)\n fprintf(stderr,\"%s: can't find %s\\n\", loc, getter.Data());\n return -1;\n }\n\n \/\/ Done\n return 0;\n}\n#endif\n\n\/\/______________________________________________________________________________\nint main(int argc, char **argv)\n{\n \/\/ PROOF server main program.\n\n#ifdef R__DEBUG\n int debug = 1;\n while (debug)\n ;\n#endif\n if (argc >= 6) {\n \/\/ Read and put system envs\n ReadPutEnvs(argv[5]);\n }\n\n gLogLevel = (argc >= 5) ? strtol(argv[4], 0, 10) : -1;\n if (gLogLevel < 0 && gSystem->Getenv(\"ROOTPROOFLOGLEVEL\"))\n gLogLevel = atoi(gSystem->Getenv(\"ROOTPROOFLOGLEVEL\"));\n if (gLogLevel > 0)\n fprintf(stderr,\"%s: starting %s\\n\", argv[1], argv[0]);\n\n \/\/ Redirect the output\n FILE *fLog = 0;\n const char *loc = 0;\n const char *logfile = gSystem->Getenv(\"ROOTPROOFLOGFILE\");\n if (logfile && !gSystem->Getenv(\"ROOTPROOFDONOTREDIR\")) {\n loc = (gLogLevel > 0) ? argv[1] : 0;\n if (gLogLevel > 0)\n fprintf(stderr,\"%s: redirecting output to %s\\n\", argv[1], logfile);\n if (!(fLog = RedirectOutput(logfile, loc))) {\n fprintf(stderr,\"%s: problems redirecting output to file %s\\n\", argv[1], logfile);\n exit(1);\n }\n }\n if (gLogLevel > 0)\n fprintf(stderr,\"%s: output redirected to: %s\\n\",\n argv[1], (logfile ? logfile : \"+++not redirected+++\"));\n\n SetMaxMemLimits(argv[1]);\n\n#ifdef R__AFS\n \/\/ Init AFS, if required\n if (gSystem->Getenv(\"ROOTPROOFAFSCREDS\")) {\n if (InitAFS(gSystem->Getenv(\"ROOTPROOFAFSCREDS\"), loc) != 0) {\n fprintf(stderr,\"%s: unable to initialize the AFS token\\n\", argv[1]);\n } else {\n if (gLogLevel > 0)\n fprintf(stderr,\"%s: AFS token initialized\\n\", argv[1]);\n }\n }\n#endif\n\n gROOT->SetBatch();\n TApplication *theApp = 0;\n\n \/\/ Enable autoloading\n gInterpreter->EnableAutoLoading();\n\n TString getter(\"GetTProofServ\");\n TString prooflib = \"libProof\";\n if (argc > 2) {\n if (!strcmp(argv[2], \"lite\")) {\n \/\/ Lite version for local processing\n getter = \"GetTProofServLite\";\n } else if (!strcmp(argv[2], \"xpd\")) {\n \/\/ XPD: additionally load the appropriate library\n prooflib = \"libProofx\";\n getter = \"GetTXProofServ\";\n }\n }\n char *p = 0;\n if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {\n delete[] p;\n if (gSystem->Load(prooflib) == -1) {\n fprintf(stderr,\"%s: can't load %s\\n\", argv[1], prooflib.Data());\n exit(1);\n }\n } else {\n fprintf(stderr,\"%s: can't locate %s\\n\", argv[1], prooflib.Data());\n exit(1);\n }\n\n \/\/ Locate constructor\n Func_t f = gSystem->DynFindSymbol(prooflib, getter);\n if (f) {\n theApp = (TApplication *) (*((TProofServ_t)f))(&argc, argv, fLog);\n } else {\n fprintf(stderr,\"%s: can't find %s\\n\", argv[1], getter.Data());\n exit(1);\n }\n\n \/\/ Ready to run\n if (gLogLevel > 0)\n fprintf(stderr,\"%s: running the TProofServ application\\n\", argv[1]);\n\n theApp->Run();\n\n#ifdef R__AFS\n \/\/ Cleanup\n if (gAFS)\n delete gAFS;\n#endif\n\n \/\/ We can exit now\n gSystem->Exit(0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkStructuredPointsReader.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkStructuredPointsReader.h\"\n#include \"vtkObjectFactory.h\"\n\n\/\/--------------------------------------------------------------------------\nvtkStructuredPointsReader* vtkStructuredPointsReader::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkStructuredPointsReader\");\n if(ret)\n {\n return (vtkStructuredPointsReader*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkStructuredPointsReader;\n}\n\nvtkStructuredPointsReader::vtkStructuredPointsReader()\n{\n this->SetOutput(vtkStructuredPoints::New());\n \/\/ Releasing data for pipeline parallism.\n \/\/ Filters will know it is empty. \n this->Outputs[0]->ReleaseData();\n this->Outputs[0]->Delete();\n this->ExecuteExtent[0] = this->ExecuteExtent[2] = this->ExecuteExtent[4] = 0;\n this->ExecuteExtent[1] = this->ExecuteExtent[3] = this->ExecuteExtent[5] = 0;\n}\n\nvtkStructuredPointsReader::~vtkStructuredPointsReader()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkStructuredPointsReader::SetOutput(vtkStructuredPoints *output)\n{\n this->vtkSource::SetNthOutput(0, output);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkStructuredPoints *vtkStructuredPointsReader::GetOutput()\n{\n if (this->NumberOfOutputs < 1)\n {\n return NULL;\n }\n \n return (vtkStructuredPoints *)(this->Outputs[0]);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Default method performs Update to get information. Not all the old\n\/\/ structured points sources compute information\nvoid vtkStructuredPointsReader::ExecuteInformation()\n{\n vtkStructuredPoints *output = this->GetOutput();\n vtkScalars *scalars;\n \n \/\/ Now here is a problem.\n \/\/ Update Extent needs to be set incase the RequestExactExtent flag is on.\n \/\/ Bypass to superclasses update.\n output->vtkDataObject::UpdateData();\n scalars = output->GetPointData()->GetScalars();\n\n if (scalars)\n {\n output->SetScalarType(scalars->GetDataType());\n output->SetNumberOfScalarComponents(scalars->GetNumberOfComponents());\n }\n\n output->SetWholeExtent(output->GetExtent());\n}\n\nvoid vtkStructuredPointsReader::Execute()\n{\n int numPts=0, numCells=0;\n char line[256];\n int npts, ncells;\n int dimsRead=0, arRead=0, originRead=0;\n int done=0;\n vtkStructuredPoints *output = this->GetOutput();\n \n \/\/ ImageSource superclass does not do this.\n output->ReleaseData();\n\n vtkDebugMacro(<<\"Reading vtk structured points file...\");\n\n if (!this->OpenVTKFile() || !this->ReadHeader())\n {\n return;\n }\n\n \/\/ Read structured points specific stuff\n \/\/\n if (!this->ReadString(line))\n {\n vtkErrorMacro(<<\"Data file ends prematurely!\");\n this->CloseVTKFile ();\n return;\n }\n\n if ( !strncmp(this->LowerCase(line),\"dataset\",(unsigned long)7) )\n {\n \/\/ Make sure we're reading right type of geometry\n \/\/\n if (!this->ReadString(line))\n {\n vtkErrorMacro(<<\"Data file ends prematurely!\");\n this->CloseVTKFile ();\n return;\n } \n\n if ( strncmp(this->LowerCase(line),\"structured_points\",17) )\n {\n vtkErrorMacro(<< \"Cannot read dataset type: \" << line);\n this->CloseVTKFile ();\n return;\n }\n\n \/\/ Read keyword and number of points\n \/\/\n numPts = output->GetNumberOfPoints(); \/\/ get default\n while (!done)\n {\n if (!this->ReadString(line))\n\t{\n\tbreak;\n\t}\n\n if (! strncmp(this->LowerCase(line), \"field\", 5))\n\t{\n\tvtkFieldData* fd = this->ReadFieldData();\n\toutput->SetFieldData(fd);\n\tfd->Delete(); \/\/ ?\n\t}\n else if ( ! strncmp(line, \"dimensions\",10) )\n {\n int dim[3];\n if (!(this->Read(dim) && \n\t this->Read(dim+1) && \n\t this->Read(dim+2)))\n {\n vtkErrorMacro(<<\"Error reading dimensions!\");\n this->CloseVTKFile ();\n return;\n }\n\n numPts = dim[0] * dim[1] * dim[2];\n output->SetDimensions(dim);\n\tnumCells = output->GetNumberOfCells();\n dimsRead = 1;\n }\n\n else if ( !strncmp(line,\"aspect_ratio\",12) || !strncmp(line,\"spacing\",7) )\n {\n float ar[3];\n if (!(this->Read(ar) && \n\t this->Read(ar+1) && \n\t this->Read(ar+2)))\n {\n vtkErrorMacro(<<\"Error reading spacing!\");\n this->CloseVTKFile ();\n return;\n }\n\n output->SetSpacing(ar);\n arRead = 1;\n }\n\n else if ( ! strncmp(line,\"origin\",6) )\n {\n float origin[3];\n if (!(this->Read(origin) && \n\t this->Read(origin+1) && \n\t this->Read(origin+2)))\n {\n vtkErrorMacro(<<\"Error reading origin!\");\n this->CloseVTKFile ();\n return;\n }\n\n output->SetOrigin(origin);\n originRead = 1;\n }\n\n else if ( ! strncmp(line, \"cell_data\", 9) )\n {\n if (!this->Read(&ncells))\n {\n vtkErrorMacro(<<\"Cannot read cell data!\");\n this->CloseVTKFile ();\n return;\n }\n \n if ( ncells != numCells )\n {\n vtkErrorMacro(<<\"Number of cells don't match data values!\");\n this->CloseVTKFile ();\n return;\n }\n\n this->ReadCellData(output, ncells);\n break; \/\/out of this loop\n }\n\n else if ( ! strncmp(line, \"point_data\", 10) )\n {\n if (!this->Read(&npts))\n {\n vtkErrorMacro(<<\"Cannot read point data!\");\n this->CloseVTKFile ();\n return;\n }\n \n if ( npts != numPts )\n {\n vtkErrorMacro(<<\"Number of points don't match data values!\");\n this->CloseVTKFile ();\n return;\n }\n\n this->ReadPointData(output, npts);\n break; \/\/out of this loop\n }\n\n else\n {\n vtkErrorMacro(<< \"Unrecognized keyword: \" << line);\n this->CloseVTKFile ();\n return;\n }\n }\n\n if ( !dimsRead ) vtkWarningMacro(<<\"No dimensions read.\");\n if ( !arRead ) vtkWarningMacro(<<\"No spacing read.\");\n if ( !originRead ) vtkWarningMacro(<<\"No origin read.\");\n }\n\n else if ( !strncmp(line,\"cell_data\",9) )\n {\n vtkWarningMacro(<<\"No geometry defined in data file!\");\n if (!this->Read(&ncells))\n {\n vtkErrorMacro(<<\"Cannot read cell data!\");\n this->CloseVTKFile ();\n return;\n }\n this->ReadCellData(output, numCells);\n }\n\n else if ( !strncmp(line,\"point_data\",10) )\n {\n vtkWarningMacro(<<\"No geometry defined in data file!\");\n if (!this->Read(&npts))\n {\n vtkErrorMacro(<<\"Cannot read point data!\");\n this->CloseVTKFile ();\n return;\n }\n this->ReadPointData(output, numPts);\n }\n\n else \n {\n vtkErrorMacro(<< \"Unrecognized keyword: \" << line);\n }\n this->CloseVTKFile ();\n}\n\nvoid vtkStructuredPointsReader::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataReader::PrintSelf(os,indent);\n}\n<commit_msg>bug: Causing problem with animVectors.tcl<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkStructuredPointsReader.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkStructuredPointsReader.h\"\n#include \"vtkObjectFactory.h\"\n\n\/\/--------------------------------------------------------------------------\nvtkStructuredPointsReader* vtkStructuredPointsReader::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkStructuredPointsReader\");\n if(ret)\n {\n return (vtkStructuredPointsReader*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkStructuredPointsReader;\n}\n\nvtkStructuredPointsReader::vtkStructuredPointsReader()\n{\n this->SetOutput(vtkStructuredPoints::New());\n \/\/ Releasing data for pipeline parallism.\n \/\/ Filters will know it is empty. \n this->Outputs[0]->ReleaseData();\n this->Outputs[0]->Delete();\n this->ExecuteExtent[0] = this->ExecuteExtent[2] = this->ExecuteExtent[4] = 0;\n this->ExecuteExtent[1] = this->ExecuteExtent[3] = this->ExecuteExtent[5] = 0;\n}\n\nvtkStructuredPointsReader::~vtkStructuredPointsReader()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkStructuredPointsReader::SetOutput(vtkStructuredPoints *output)\n{\n this->vtkSource::SetNthOutput(0, output);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkStructuredPoints *vtkStructuredPointsReader::GetOutput()\n{\n if (this->NumberOfOutputs < 1)\n {\n return NULL;\n }\n \n return (vtkStructuredPoints *)(this->Outputs[0]);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Default method performs Update to get information. Not all the old\n\/\/ structured points sources compute information\nvoid vtkStructuredPointsReader::ExecuteInformation()\n{\n vtkStructuredPoints *output = this->GetOutput();\n vtkScalars *scalars;\n int saveRequestFlag;\n \n \/\/ Now here is a problem.\n \/\/ Update Extent needs to be set incase the RequestExactExtent flag is on.\n \/\/ Bypass to superclasses update. \n \/\/ Well that solution no longer works because the superclass now handles\n \/\/ the RequestForExactExtent flag. Lets try disabling the flag temporarily.\n saveRequestFlag = output->GetRequestExactExtent();\n output->SetRequestExactExtent(0);\n output->vtkDataObject::UpdateData();\n output->SetRequestExactExtent(saveRequestFlag);\n \n scalars = output->GetPointData()->GetScalars();\n if (scalars)\n {\n output->SetScalarType(scalars->GetDataType());\n output->SetNumberOfScalarComponents(scalars->GetNumberOfComponents());\n }\n\n output->SetWholeExtent(output->GetExtent());\n}\n\nvoid vtkStructuredPointsReader::Execute()\n{\n int numPts=0, numCells=0;\n char line[256];\n int npts, ncells;\n int dimsRead=0, arRead=0, originRead=0;\n int done=0;\n vtkStructuredPoints *output = this->GetOutput();\n \n \/\/ ImageSource superclass does not do this.\n output->ReleaseData();\n\n vtkDebugMacro(<<\"Reading vtk structured points file...\");\n\n if (!this->OpenVTKFile() || !this->ReadHeader())\n {\n return;\n }\n\n \/\/ Read structured points specific stuff\n \/\/\n if (!this->ReadString(line))\n {\n vtkErrorMacro(<<\"Data file ends prematurely!\");\n this->CloseVTKFile ();\n return;\n }\n\n if ( !strncmp(this->LowerCase(line),\"dataset\",(unsigned long)7) )\n {\n \/\/ Make sure we're reading right type of geometry\n \/\/\n if (!this->ReadString(line))\n {\n vtkErrorMacro(<<\"Data file ends prematurely!\");\n this->CloseVTKFile ();\n return;\n } \n\n if ( strncmp(this->LowerCase(line),\"structured_points\",17) )\n {\n vtkErrorMacro(<< \"Cannot read dataset type: \" << line);\n this->CloseVTKFile ();\n return;\n }\n\n \/\/ Read keyword and number of points\n \/\/\n numPts = output->GetNumberOfPoints(); \/\/ get default\n while (!done)\n {\n if (!this->ReadString(line))\n\t{\n\tbreak;\n\t}\n\n if (! strncmp(this->LowerCase(line), \"field\", 5))\n\t{\n\tvtkFieldData* fd = this->ReadFieldData();\n\toutput->SetFieldData(fd);\n\tfd->Delete(); \/\/ ?\n\t}\n else if ( ! strncmp(line, \"dimensions\",10) )\n {\n int dim[3];\n if (!(this->Read(dim) && \n\t this->Read(dim+1) && \n\t this->Read(dim+2)))\n {\n vtkErrorMacro(<<\"Error reading dimensions!\");\n this->CloseVTKFile ();\n return;\n }\n\n numPts = dim[0] * dim[1] * dim[2];\n output->SetDimensions(dim);\n\tnumCells = output->GetNumberOfCells();\n dimsRead = 1;\n }\n\n else if ( !strncmp(line,\"aspect_ratio\",12) || !strncmp(line,\"spacing\",7) )\n {\n float ar[3];\n if (!(this->Read(ar) && \n\t this->Read(ar+1) && \n\t this->Read(ar+2)))\n {\n vtkErrorMacro(<<\"Error reading spacing!\");\n this->CloseVTKFile ();\n return;\n }\n\n output->SetSpacing(ar);\n arRead = 1;\n }\n\n else if ( ! strncmp(line,\"origin\",6) )\n {\n float origin[3];\n if (!(this->Read(origin) && \n\t this->Read(origin+1) && \n\t this->Read(origin+2)))\n {\n vtkErrorMacro(<<\"Error reading origin!\");\n this->CloseVTKFile ();\n return;\n }\n\n output->SetOrigin(origin);\n originRead = 1;\n }\n\n else if ( ! strncmp(line, \"cell_data\", 9) )\n {\n if (!this->Read(&ncells))\n {\n vtkErrorMacro(<<\"Cannot read cell data!\");\n this->CloseVTKFile ();\n return;\n }\n \n if ( ncells != numCells )\n {\n vtkErrorMacro(<<\"Number of cells don't match data values!\");\n this->CloseVTKFile ();\n return;\n }\n\n this->ReadCellData(output, ncells);\n break; \/\/out of this loop\n }\n\n else if ( ! strncmp(line, \"point_data\", 10) )\n {\n if (!this->Read(&npts))\n {\n vtkErrorMacro(<<\"Cannot read point data!\");\n this->CloseVTKFile ();\n return;\n }\n \n if ( npts != numPts )\n {\n vtkErrorMacro(<<\"Number of points don't match data values!\");\n this->CloseVTKFile ();\n return;\n }\n\n this->ReadPointData(output, npts);\n break; \/\/out of this loop\n }\n\n else\n {\n vtkErrorMacro(<< \"Unrecognized keyword: \" << line);\n this->CloseVTKFile ();\n return;\n }\n }\n\n if ( !dimsRead ) vtkWarningMacro(<<\"No dimensions read.\");\n if ( !arRead ) vtkWarningMacro(<<\"No spacing read.\");\n if ( !originRead ) vtkWarningMacro(<<\"No origin read.\");\n }\n\n else if ( !strncmp(line,\"cell_data\",9) )\n {\n vtkWarningMacro(<<\"No geometry defined in data file!\");\n if (!this->Read(&ncells))\n {\n vtkErrorMacro(<<\"Cannot read cell data!\");\n this->CloseVTKFile ();\n return;\n }\n this->ReadCellData(output, numCells);\n }\n\n else if ( !strncmp(line,\"point_data\",10) )\n {\n vtkWarningMacro(<<\"No geometry defined in data file!\");\n if (!this->Read(&npts))\n {\n vtkErrorMacro(<<\"Cannot read point data!\");\n this->CloseVTKFile ();\n return;\n }\n this->ReadPointData(output, numPts);\n }\n\n else \n {\n vtkErrorMacro(<< \"Unrecognized keyword: \" << line);\n }\n this->CloseVTKFile ();\n}\n\nvoid vtkStructuredPointsReader::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataReader::PrintSelf(os,indent);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* _______ __ __ __ ______ __ __ _______ __ __\n * \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___ \/\\ \/ |\\\/ \/\\\n * \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n * \/ \/ \/__ \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/ \/ ___ \/ \/\/ ___ \/ \/\/ \/| ' \/ \/\n * \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_ \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ | \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson\n *\n * Js_.\/\n * Per Larsson a.k.a finalman _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem _asww7!uY`> )\\a\/\/\n * _Qhm`] _f \"'c 1!5m\n * Visit: http:\/\/guichan.darkbits.org )Qk<P ` _: :+' .' \"{[\n * .)j(] .d_\/ '-( P . S\n * License: (BSD) <Td\/Z <fP\"5(\\\"??\"\\a. .L\n * Redistribution and use in source and _dV>ws?a-?' ._\/L #'\n * binary forms, with or without )4d[#7r, . ' )d`)[\n * modification, are permitted provided _Q-5'5W..j\/?' -?!\\)cam'\n * that the following conditions are met: j<<WP+k\/);. _W=j f\n * 1. Redistributions of source code must .$%w\\\/]Q . .\"' . mj$\n * retain the above copyright notice, ]E.pYY(Q]>. a J@\\\n * this list of conditions and the j(]1u<sE\"L,. . .\/^ ]{a\n * following disclaimer. 4'_uomm\\. )L);-4 (3=\n * 2. Redistributions in binary form must )_]X{Z('a_\"a7'<a\"a, ]\"[\n * reproduce the above copyright notice, #}<]m7`Za??4,P-\"'7. ).m\n * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ\/\n * following disclaimer in the <B!<\/]C)d_, '(<' .f. =C+m\n * documentation and\/or other materials .Z!=J ]e []('-4f _ ) -.)m]'\n * provided with the distribution. .w[5]' _[ \/.)_-\"+? _\/ <W\"\n * 3. Neither the name of Guichan nor the :$we` _! + _\/ . j?\n * names of its contributors may be used =3)= _f (_yQmWW$#( \"\n * to endorse or promote products derived - W, sQQQQmZQ#Wwa]..\n * from this software without specific (js, \\[QQW$QWW#?!V\"\".\n * prior written permission. ]y:.<\\.. .\n * -]n w\/ ' [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )\/ )\/ !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY < (; sac , '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f\/<[]\/ ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%\"' \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef GCN_DEATHLISTENER_HPP\n#define GCN_DEATHLISTENER_HPP\n\n#include <string>\n\n#include \"guichan\/event.hpp\"\n#include \"guichan\/platform.hpp\"\n\nnamespace gcn\n{\n \/**\n * Listener of death events from Widgets. To be able to\n * listen for deaths you must make a class which inherits\n * from this class and implements the death function.\n *\n * @see Widget::addDeathListener\n * @author Olof Naessn\n * @since 0.6.0\n *\/\n class GCN_CORE_DECLSPEC DeathListener\n {\n public:\n\n \/**\n * Destructor.\n *\/\n virtual ~DeathListener() { }\n\n \/**\n * Called when a death from a widget is recieved. It is used\n * to be able to recieve a notification that a death has occured.\n *\n * @param event the event of the death.\n *\/\n virtual void death(const Event& event) = 0;\n\n };\n}\n\n#endif \/\/ end GCN_DEATHLISTENER_HPP\n<commit_msg>Comment has been updated.<commit_after>\/* _______ __ __ __ ______ __ __ _______ __ __\n * \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___ \/\\ \/ |\\\/ \/\\\n * \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n * \/ \/ \/__ \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/ \/ ___ \/ \/\/ ___ \/ \/\/ \/| ' \/ \/\n * \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_ \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ | \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson\n *\n * Js_.\/\n * Per Larsson a.k.a finalman _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem _asww7!uY`> )\\a\/\/\n * _Qhm`] _f \"'c 1!5m\n * Visit: http:\/\/guichan.darkbits.org )Qk<P ` _: :+' .' \"{[\n * .)j(] .d_\/ '-( P . S\n * License: (BSD) <Td\/Z <fP\"5(\\\"??\"\\a. .L\n * Redistribution and use in source and _dV>ws?a-?' ._\/L #'\n * binary forms, with or without )4d[#7r, . ' )d`)[\n * modification, are permitted provided _Q-5'5W..j\/?' -?!\\)cam'\n * that the following conditions are met: j<<WP+k\/);. _W=j f\n * 1. Redistributions of source code must .$%w\\\/]Q . .\"' . mj$\n * retain the above copyright notice, ]E.pYY(Q]>. a J@\\\n * this list of conditions and the j(]1u<sE\"L,. . .\/^ ]{a\n * following disclaimer. 4'_uomm\\. )L);-4 (3=\n * 2. Redistributions in binary form must )_]X{Z('a_\"a7'<a\"a, ]\"[\n * reproduce the above copyright notice, #}<]m7`Za??4,P-\"'7. ).m\n * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ\/\n * following disclaimer in the <B!<\/]C)d_, '(<' .f. =C+m\n * documentation and\/or other materials .Z!=J ]e []('-4f _ ) -.)m]'\n * provided with the distribution. .w[5]' _[ \/.)_-\"+? _\/ <W\"\n * 3. Neither the name of Guichan nor the :$we` _! + _\/ . j?\n * names of its contributors may be used =3)= _f (_yQmWW$#( \"\n * to endorse or promote products derived - W, sQQQQmZQ#Wwa]..\n * from this software without specific (js, \\[QQW$QWW#?!V\"\".\n * prior written permission. ]y:.<\\.. .\n * -]n w\/ ' [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )\/ )\/ !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY < (; sac , '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f\/<[]\/ ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%\"' \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef GCN_DEATHLISTENER_HPP\n#define GCN_DEATHLISTENER_HPP\n\n#include <string>\n\n#include \"guichan\/event.hpp\"\n#include \"guichan\/platform.hpp\"\n\nnamespace gcn\n{\n \/**\n * Listener of death events from Widgets. To be able to\n * listen for deaths you must make a class which inherits\n * from this class and implements the death function.\n *\n * @see Widget::addDeathListener\n * @author Olof Naessn\n * @since 0.6.0\n *\/\n class GCN_CORE_DECLSPEC DeathListener\n {\n public:\n\n \/**\n * Destructor.\n *\/\n virtual ~DeathListener() { }\n\n \/**\n * Called when a widget dies. It is used to be able to recieve \n * a notification when a death of a widget occurs.\n *\n * @param event the event of the death.\n *\/\n virtual void death(const Event& event) = 0;\n\n };\n}\n\n#endif \/\/ end GCN_DEATHLISTENER_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"VMState.hpp\"\n#include \"Register.hpp\"\n#include \"Opcodes.hpp\"\n\n#ifdef _WIN32\n#include <Windows.h>\n#else\n#include <unistd.h>\n#include <termios.h>\n#undef CR0\n#endif\n\nint main(int argc, char** argv)\n{\n#ifdef _WIN32\n SetConsoleTitle(\"Cynosure\");\n#else\n struct termios termattr;\n tcgetattr(0, &termattr);\n termattr.c_lflag &= ~(ICANON | ECHO);\n tcsetattr(0, TCSANOW, &termattr);\n#endif\n\n VMState* state = nullptr;\n try\n {\n state = new VMState(\"floppy_1_44.img\", \"debug.log\", 1024 * 1024);\n }\n catch (std::exception const& e)\n {\n std::cerr << \"[INIT] Failed to initialize: \" << e.what();\n return EXIT_FAILURE;\n }\n state->CR0.protectedMode = false;\n state->CR0.emulation = true;\n\n state->eflags.direction = false;\n\n Opcode opcodes[256];\n opcodesGenerate(opcodes);\n\n state->running = true;\n while (state->running)\n {\n Opcode opcode = opcodes[state->ReadIPRelative(0)];\n\n Log << \"0x\" << std::setw(2) << std::hex << (uint32_t)opcode.opcode << \": \"\n << opcode.name;\n\n opcode.func(state, opcode);\n state->eip += opcode.GetFinalOffset(state);\n\n Log << std::endl;\n }\n\n delete state;\n return 0;\n}<commit_msg>Fixed bug where opcode printout wasn't in uppercase; VMState is now in a unique_ptr<commit_after>#include \"VMState.hpp\"\n#include \"Register.hpp\"\n#include \"Opcodes.hpp\"\n\n#ifdef _WIN32\n#include <Windows.h>\n#else\n#include <unistd.h>\n#include <termios.h>\n#undef CR0\n#endif\n\n#include <memory>\n\nint main(int argc, char** argv)\n{\n#ifdef _WIN32\n SetConsoleTitle(\"Cynosure\");\n#else\n struct termios termattr;\n tcgetattr(0, &termattr);\n termattr.c_lflag &= ~(ICANON | ECHO);\n tcsetattr(0, TCSANOW, &termattr);\n#endif\n\n std::unique_ptr<VMState> state;\n try\n {\n state.reset(new VMState(\"floppy_1_44.img\", \"debug.log\", 1024 * 1024));\n }\n catch (std::exception const& e)\n {\n std::cerr << \"[INIT] Failed to initialize: \" << e.what();\n return EXIT_FAILURE;\n }\n state->CR0.protectedMode = false;\n state->CR0.emulation = true;\n\n state->eflags.direction = false;\n\n Opcode opcodes[256];\n opcodesGenerate(opcodes);\n\n state->running = true;\n while (state->running)\n {\n Opcode opcode = opcodes[state->ReadIPRelative(0)];\n\n Log << \"0x\" << std::setw(2) << std::hex << std::uppercase\n << (uint32_t)opcode.opcode << \": \" << opcode.name;\n\n opcode.func(state.get(), opcode);\n state->eip += opcode.GetFinalOffset(state.get());\n\n Log << std::endl;\n }\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <iostream> \/\/ temp!!\n\n#include \"filepage.h\"\n\n#define PAGE_MAGIC\t\t\"LFBX01E\"\t\/* Magic checkup *\/\n\n#define PAGE_FLAG_NIL\t0x0\n#define PAGE_FLAG_INV\t0x2\n#define PAGE_FLAG_GZIP\t0x8\n#define PAGE_FLAG_FULL\t0x12\n\nstruct pageHeader {\n\tchar magic[8];\/\/ = PAGE_MAGIC;\n\tunsigned short elements = 0;\n\tunsigned int allocated = 0;\n\tunsigned int first_free = 0;\n\tint flags = PAGE_FLAG_NIL;\n};\n\nstruct pageIndex {\n\tchar name[40];\n\tint item = 0;\n};\n\nsize_t Filepage::size() {\n\treturn m_Elements;\n}\n\nvoid Filepage::create(unsigned int alloc) {\n\tm_pFile = fopen(m_File.c_str(), \"w+\");\n\n\tpageHeader header;\n\tstrcpy(header.magic, PAGE_MAGIC);\n\theader.allocated = alloc;\n\theader.first_free = sizeof(pageHeader) + (sizeof(pageIndex) * header.allocated);\n\tfwrite((const char *)&header, sizeof(pageHeader), 1, m_pFile);\n\n\t\/* Allocate page on disk *\/\n\tfseek(m_pFile, sizeof(pageHeader) + (sizeof(pageIndex) * header.allocated) + (ITEM_SIZE * header.allocated), SEEK_CUR);\n\tfwrite(\"\\0\", 1, 1, m_pFile);\n\n\tfflush(m_pFile);\n\n\tm_Elements = header.elements;\n\tm_Allocated = header.allocated;\n\tm_FirstFree = header.first_free;\n}\n\nvoid Filepage::open() {\n\tm_pFile = fopen(m_File.c_str(), \"r+\");\n\n\tpageHeader header;\n\tfread((char *)&header, sizeof(pageHeader), 1, m_pFile);\n\n\tif (strcmp((const char *)header.magic, PAGE_MAGIC)) {\n\t\tputs(\"Magic error 1\"); \/\/ throw error\n\t\treturn;\n\t}\n\n\tif (header.elements > header.allocated) {\n\t\tputs(\"Overflow error\"); \/\/ throw error\n\t\treturn;\n\t}\n\n\tm_Elements = header.elements;\n\tm_Allocated = header.allocated;\n\tm_FirstFree = header.first_free;\n}\n\nvoid Filepage::writeHeader() {\n\tfseek(m_pFile, 0, SEEK_SET);\n\n\tpageHeader header;\n\tstrcpy(header.magic, PAGE_MAGIC);\n\theader.elements = m_Elements;\n\theader.allocated = m_Allocated;\n\theader.first_free = m_FirstFree;\n\n\tfwrite((const char *)&header, sizeof(pageHeader), 1, m_pFile);\n\n\tfflush(m_pFile);\n}\n\nvoid Filepage::storeItem(std::string name, std::string data) {\n\tif (name.size() > 40) {\n\t\tputs(\"Name overflows index\");\n\t\treturn;\n\t}\n\n\tstd::cout << \"Current allocation size: \" << (m_Allocated * ITEM_SIZE) << std::endl;\n\tstd::cout << \"Elements: \" << m_Elements << std::endl;\n\tstd::cout << \"Free offset: \" << m_FirstFree << std::endl;\n\tstd::cout << \"New data size: \" << data.size() << std::endl;\n\n\tif (m_FirstFree + data.size() > (m_Allocated * ITEM_SIZE)) {\n\t\tputs(\"Should grow\");\n\t\treturn;\n\t}\n\n\tif (m_Elements == m_Allocated) {\n\t\tputs(\"Should grow certainly, fullhouse\");\n\t\treturn;\n\t}\n\n\t{\n\t\tsize_t namepos = sizeof(pageHeader) + (sizeof(pageIndex) * m_Elements);\n\t\tstd::cout << \"Position for new name: \" << namepos << std::endl;\n\n\t\tfseek(m_pFile, namepos, SEEK_CUR);\n\n\t\tpageIndex index;\n\t\tstrcpy(index.name, name.c_str());\n\t\tindex.item = m_FirstFree;\n\n\t\tfwrite((const char *)&index, sizeof(pageIndex), 1, m_pFile);\n\t}\n\n\t{\n\t\tstd::cout << \"Position for new data: \" << m_FirstFree << std::endl;\n\t\tfseek(m_pFile, m_FirstFree, SEEK_CUR);\n\n\t\tfwrite(data.c_str(), 1, data.size(), m_pFile);\n\n\t\tm_FirstFree += data.size();\n\t}\n\n\tm_Elements++;\n\n\twriteHeader();\n\n\tfflush(m_pFile);\n}\n<commit_msg>Grow page<commit_after>#include <fstream>\n#include <iostream> \/\/ temp!!\n\n#include \"filepage.h\"\n\n#define PAGE_MAGIC\t\t\"LFBX01E\"\t\/* Magic checkup *\/\n\n#define PAGE_FLAG_NIL\t0x0\n#define PAGE_FLAG_INV\t0x2\n#define PAGE_FLAG_GZIP\t0x8\n#define PAGE_FLAG_FULL\t0x12\n\n#define INDEX_FLAG_NIL\t0x0\n#define INDEX_FLAG_DEL\t0x2\n\nstruct pageHeader {\n\tchar magic[8];\n\tunsigned short elements = 0;\n\tunsigned int allocated = 0;\n\tunsigned int first_free = 0;\n\tint flags = PAGE_FLAG_NIL;\n};\n\nstruct pageIndex {\n\tchar name[40];\n\tunsigned int item = 0;\n\tchar flags = INDEX_FLAG_NIL;\n};\n\nsize_t Filepage::size() {\n\treturn m_Elements;\n}\n\nvoid Filepage::create(unsigned int alloc) {\n\tm_pFile = fopen(m_File.c_str(), \"w+\");\n\n\tpageHeader header;\n\tstrcpy(header.magic, PAGE_MAGIC);\n\theader.allocated = alloc;\n\theader.first_free = sizeof(pageHeader) + (sizeof(pageIndex) * header.allocated);\n\tfwrite((const char *)&header, sizeof(pageHeader), 1, m_pFile);\n\n\t\/* Allocate page on disk *\/\n\tfseek(m_pFile, sizeof(pageHeader) + header.first_free + (ITEM_SIZE * header.allocated), SEEK_CUR);\n\tfwrite(\"\\0\", 1, 1, m_pFile);\n\n\tfflush(m_pFile);\n\n\tm_Elements = header.elements;\n\tm_Allocated = header.allocated;\n\tm_FirstFree = header.first_free;\n}\n\nvoid Filepage::open() {\n\tm_pFile = fopen(m_File.c_str(), \"r+\");\n\n\tpageHeader header;\n\tfread((char *)&header, sizeof(pageHeader), 1, m_pFile);\n\n\tif (strcmp((const char *)header.magic, PAGE_MAGIC)) {\n\t\tputs(\"Magic error 1\"); \/\/ throw error\n\t\treturn;\n\t}\n\n\tif (header.elements > header.allocated) {\n\t\tputs(\"Overflow error\"); \/\/ throw error\n\t\treturn;\n\t}\n\n\tm_Elements = header.elements;\n\tm_Allocated = header.allocated;\n\tm_FirstFree = header.first_free;\n}\n\nvoid Filepage::writeHeader() {\n\tfseek(m_pFile, 0, SEEK_SET);\n\n\tpageHeader header;\n\tstrcpy(header.magic, PAGE_MAGIC);\n\theader.elements = m_Elements;\n\theader.allocated = m_Allocated;\n\theader.first_free = m_FirstFree;\n\n\tfwrite((const char *)&header, sizeof(pageHeader), 1, m_pFile);\n\n\tfflush(m_pFile);\n}\n\nvoid Filepage::grow() {\n\tm_Allocated *= 2;\n\n\tm_FirstFree += (sizeof(pageIndex) * (m_Allocated \/ 2));\n\n\t\/* Allocate page on disk *\/\n\tfseek(m_pFile, m_FirstFree + (ITEM_SIZE * m_Allocated), SEEK_CUR);\n\tfwrite(\"\\0\", 1, 1, m_pFile);\n\n\twriteHeader();\n}\n\nvoid Filepage::storeItem(std::string name, std::string data) {\n\tif (name.size() > 40) {\n\t\tputs(\"Name overflows index\");\n\t\treturn;\n\t}\n\n\tstd::cout << \"Current allocation size: \" << (m_Allocated * ITEM_SIZE) << std::endl;\n\tstd::cout << \"Elements: \" << m_Elements << std::endl;\n\tstd::cout << \"Free offset: \" << m_FirstFree << std::endl;\n\tstd::cout << \"New data size: \" << data.size() << std::endl;\n\n\tif (m_FirstFree + data.size() > (m_Allocated * ITEM_SIZE)) {\n\t\tputs(\"Should grow\");\n\t\treturn;\n\t}\n\n\tif (m_Elements == m_Allocated) {\n\t\tputs(\"Should grow certainly, fullhouse\");\n\t\tgrow();\n\t\treturn;\n\t}\n\n\t{\n\t\tsize_t namepos = sizeof(pageHeader) + (sizeof(pageIndex) * m_Elements);\n\t\tstd::cout << \"Position for new name: \" << namepos << std::endl;\n\n\t\tfseek(m_pFile, namepos, SEEK_CUR);\n\n\t\tpageIndex index;\n\t\tstrcpy(index.name, name.c_str());\n\t\tindex.item = m_FirstFree;\n\n\t\tfwrite((const char *)&index, sizeof(pageIndex), 1, m_pFile);\n\t}\n\n\t{\n\t\tstd::cout << \"Position for new data: \" << m_FirstFree << std::endl;\n\t\tfseek(m_pFile, m_FirstFree, SEEK_CUR);\n\n\t\tfwrite(data.c_str(), 1, data.size(), m_pFile);\n\n\t\tm_FirstFree += data.size();\n\t}\n\n\tm_Elements++;\n\n\twriteHeader();\n\n\tfflush(m_pFile);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: GridProperties.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2007-07-25 08:50:24 $\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_chart2.hxx\"\n\n#include \"GridProperties.hxx\"\n#include \"LineProperties.hxx\"\n#include \"UserDefinedProperties.hxx\"\n#include \"PropertyHelper.hxx\"\n#include \"macros.hxx\"\n#include \"ContainerHelper.hxx\"\n\n#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_\n#include <com\/sun\/star\/style\/XStyle.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\nusing namespace ::com::sun::star;\n\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::beans::Property;\nusing ::osl::MutexGuard;\nusing ::rtl::OUString;\n\n\/\/ ____________________________________________________________\n\nnamespace\n{\n\nstatic const ::rtl::OUString lcl_aServiceName(\n RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.comp.chart2.GridProperties\" ));\n\nenum\n{\n PROP_GRID_SHOW\n};\n\nvoid lcl_AddPropertiesToVector(\n ::std::vector< Property > & rOutProperties )\n{\n rOutProperties.push_back(\n Property( C2U( \"Show\" ),\n PROP_GRID_SHOW,\n ::getBooleanCppuType(),\n beans::PropertyAttribute::BOUND\n | beans::PropertyAttribute::MAYBEDEFAULT ));\n}\n\nvoid lcl_addDefaultsToMap( ::chart::tPropertyValueMap & rOutMap )\n{\n ::chart::LineProperties::AddDefaultsToMap( rOutMap );\n\n OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_GRID_SHOW ));\n rOutMap[ PROP_GRID_SHOW ] = uno::makeAny( sal_False );\n\n \/\/ override other defaults\n rOutMap[ ::chart::LineProperties::PROP_LINE_COLOR ] =\n uno::makeAny( static_cast< sal_Int32 >( 0xb3b3b3 ) ); \/\/ gray30\n}\n\nconst Sequence< Property > & lcl_getPropertySequence()\n{\n static Sequence< Property > aPropSeq;\n\n \/\/ \/--\n MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if( 0 == aPropSeq.getLength() )\n {\n \/\/ get properties\n ::std::vector< Property > aProperties;\n lcl_AddPropertiesToVector( aProperties );\n ::chart::LineProperties::AddPropertiesToVector( aProperties );\n ::chart::UserDefinedProperties::AddPropertiesToVector( aProperties );\n\n \/\/ and sort them for access via bsearch\n ::std::sort( aProperties.begin(), aProperties.end(),\n ::chart::PropertyNameLess() );\n\n \/\/ transfer result to static Sequence\n aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );\n }\n\n return aPropSeq;\n}\n\n::cppu::IPropertyArrayHelper & lcl_getInfoHelper()\n{\n static ::cppu::OPropertyArrayHelper aArrayHelper(\n lcl_getPropertySequence(),\n \/* bSorted = *\/ sal_True );\n\n return aArrayHelper;\n}\n\n} \/\/ anonymous namespace\n\n\/\/ ____________________________________________________________\n\nnamespace chart\n{\n\nGridProperties::GridProperties( Reference< uno::XComponentContext > const & \/* xContext *\/ ) :\n ::property::OPropertySet( m_aMutex ),\n m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder( m_aMutex ))\n{\n}\n\nGridProperties::GridProperties() :\n ::property::OPropertySet( m_aMutex ),\n m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder( m_aMutex ))\n{}\n\nGridProperties::GridProperties( const GridProperties & rOther ) :\n MutexContainer(),\n impl::GridProperties_Base(),\n ::property::OPropertySet( rOther, m_aMutex ),\n m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder( m_aMutex ))\n{\n}\n\nGridProperties::~GridProperties()\n{}\n\n\/\/ ____ OPropertySet ____\nuno::Any GridProperties::GetDefaultValue( sal_Int32 nHandle ) const\n throw(beans::UnknownPropertyException)\n{\n static tPropertyValueMap aStaticDefaults;\n\n \/\/ \/--\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if( 0 == aStaticDefaults.size() )\n lcl_addDefaultsToMap( aStaticDefaults );\n\n tPropertyValueMap::const_iterator aFound(\n aStaticDefaults.find( nHandle ));\n\n if( aFound == aStaticDefaults.end())\n return uno::Any();\n\n return (*aFound).second;\n \/\/ \\--\n}\n\n::cppu::IPropertyArrayHelper & SAL_CALL GridProperties::getInfoHelper()\n{\n return lcl_getInfoHelper();\n}\n\n\/\/ ____ XPropertySet ____\nReference< beans::XPropertySetInfo > SAL_CALL\n GridProperties::getPropertySetInfo()\n throw (uno::RuntimeException)\n{\n static Reference< beans::XPropertySetInfo > xInfo;\n\n \/\/ \/--\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if( !xInfo.is())\n {\n xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(\n lcl_getInfoHelper());\n }\n\n return xInfo;\n \/\/ \\--\n}\n\n::osl::Mutex & GridProperties::GetMutex()\n{\n return m_aMutex;\n}\n\n\/\/ ____ XCloneable ____\nuno::Reference< util::XCloneable > SAL_CALL GridProperties::createClone()\n throw (uno::RuntimeException)\n{\n return uno::Reference< util::XCloneable >( new GridProperties( *this ));\n}\n\n\/\/ ____ XModifyBroadcaster ____\nvoid SAL_CALL GridProperties::addModifyListener( const Reference< util::XModifyListener >& aListener )\n throw (uno::RuntimeException)\n{\n try\n {\n Reference< util::XModifyBroadcaster > xBroadcaster( m_xModifyEventForwarder, uno::UNO_QUERY_THROW );\n xBroadcaster->addModifyListener( aListener );\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n}\n\nvoid SAL_CALL GridProperties::removeModifyListener( const Reference< util::XModifyListener >& aListener )\n throw (uno::RuntimeException)\n{\n try\n {\n Reference< util::XModifyBroadcaster > xBroadcaster( m_xModifyEventForwarder, uno::UNO_QUERY_THROW );\n xBroadcaster->removeModifyListener( aListener );\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n}\n\n\/\/ ____ XModifyListener ____\nvoid SAL_CALL GridProperties::modified( const lang::EventObject& aEvent )\n throw (uno::RuntimeException)\n{\n m_xModifyEventForwarder->modified( aEvent );\n}\n\n\/\/ ____ XEventListener (base of XModifyListener) ____\nvoid SAL_CALL GridProperties::disposing( const lang::EventObject& \/* Source *\/ )\n throw (uno::RuntimeException)\n{\n \/\/ nothing\n}\n\n\/\/ ____ OPropertySet ____\nvoid GridProperties::firePropertyChangeEvent()\n{\n fireModifyEvent();\n}\n\nvoid GridProperties::fireModifyEvent()\n{\n m_xModifyEventForwarder->modified( lang::EventObject( static_cast< uno::XWeak* >( this )));\n}\n\n\/\/ ================================================================================\n\nSequence< OUString > GridProperties::getSupportedServiceNames_Static()\n{\n Sequence< OUString > aServices( 2 );\n aServices[ 0 ] = C2U( \"com.sun.star.chart2.GridProperties\" );\n aServices[ 1 ] = C2U( \"com.sun.star.beans.PropertySet\" );\n return aServices;\n}\n\n\/\/ implement XServiceInfo methods basing upon getSupportedServiceNames_Static\nAPPHELPER_XSERVICEINFO_IMPL( GridProperties, lcl_aServiceName );\n\n\/\/ needed by MSC compiler\nusing impl::GridProperties_Base;\n\nIMPLEMENT_FORWARD_XINTERFACE2( GridProperties, GridProperties_Base, ::property::OPropertySet )\nIMPLEMENT_FORWARD_XTYPEPROVIDER2( GridProperties, GridProperties_Base, ::property::OPropertySet )\n\n} \/\/ namespace chart\n<commit_msg>INTEGRATION: CWS chart11 (1.4.2); FILE MERGED 2007\/07\/31 22:19:25 bm 1.4.2.2: #i79522# warnings on Solaris removed 2007\/07\/31 12:56:45 bm 1.4.2.1: #i80084# avoid usage of map operator[] with enums as keys, simplify initialization of default property values<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: GridProperties.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2007-09-18 15:01:41 $\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_chart2.hxx\"\n\n#include \"GridProperties.hxx\"\n#include \"LineProperties.hxx\"\n#include \"UserDefinedProperties.hxx\"\n#include \"PropertyHelper.hxx\"\n#include \"macros.hxx\"\n#include \"ContainerHelper.hxx\"\n\n#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_\n#include <com\/sun\/star\/style\/XStyle.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\nusing namespace ::com::sun::star;\n\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::beans::Property;\nusing ::osl::MutexGuard;\nusing ::rtl::OUString;\n\n\/\/ ____________________________________________________________\n\nnamespace\n{\n\nstatic const ::rtl::OUString lcl_aServiceName(\n RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.comp.chart2.GridProperties\" ));\n\nenum\n{\n PROP_GRID_SHOW\n};\n\nvoid lcl_AddPropertiesToVector(\n ::std::vector< Property > & rOutProperties )\n{\n rOutProperties.push_back(\n Property( C2U( \"Show\" ),\n PROP_GRID_SHOW,\n ::getBooleanCppuType(),\n beans::PropertyAttribute::BOUND\n | beans::PropertyAttribute::MAYBEDEFAULT ));\n}\n\nvoid lcl_addDefaultsToMap( ::chart::tPropertyValueMap & rOutMap )\n{\n ::chart::LineProperties::AddDefaultsToMap( rOutMap );\n\n ::chart::PropertyHelper::setPropertyValueDefault( rOutMap, PROP_GRID_SHOW, false );\n\n \/\/ override other defaults\n ::chart::PropertyHelper::setPropertyValue< sal_Int32 >(\n rOutMap, ::chart::LineProperties::PROP_LINE_COLOR, 0xb3b3b3 ); \/\/ gray30\n}\n\nconst Sequence< Property > & lcl_getPropertySequence()\n{\n static Sequence< Property > aPropSeq;\n\n \/\/ \/--\n MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if( 0 == aPropSeq.getLength() )\n {\n \/\/ get properties\n ::std::vector< Property > aProperties;\n lcl_AddPropertiesToVector( aProperties );\n ::chart::LineProperties::AddPropertiesToVector( aProperties );\n ::chart::UserDefinedProperties::AddPropertiesToVector( aProperties );\n\n \/\/ and sort them for access via bsearch\n ::std::sort( aProperties.begin(), aProperties.end(),\n ::chart::PropertyNameLess() );\n\n \/\/ transfer result to static Sequence\n aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );\n }\n\n return aPropSeq;\n}\n\n::cppu::IPropertyArrayHelper & lcl_getInfoHelper()\n{\n static ::cppu::OPropertyArrayHelper aArrayHelper(\n lcl_getPropertySequence(),\n \/* bSorted = *\/ sal_True );\n\n return aArrayHelper;\n}\n\n} \/\/ anonymous namespace\n\n\/\/ ____________________________________________________________\n\nnamespace chart\n{\n\nGridProperties::GridProperties( Reference< uno::XComponentContext > const & \/* xContext *\/ ) :\n ::property::OPropertySet( m_aMutex ),\n m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder( m_aMutex ))\n{\n}\n\nGridProperties::GridProperties() :\n ::property::OPropertySet( m_aMutex ),\n m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder( m_aMutex ))\n{}\n\nGridProperties::GridProperties( const GridProperties & rOther ) :\n MutexContainer(),\n impl::GridProperties_Base(),\n ::property::OPropertySet( rOther, m_aMutex ),\n m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder( m_aMutex ))\n{\n}\n\nGridProperties::~GridProperties()\n{}\n\n\/\/ ____ OPropertySet ____\nuno::Any GridProperties::GetDefaultValue( sal_Int32 nHandle ) const\n throw(beans::UnknownPropertyException)\n{\n static tPropertyValueMap aStaticDefaults;\n\n \/\/ \/--\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if( 0 == aStaticDefaults.size() )\n lcl_addDefaultsToMap( aStaticDefaults );\n\n tPropertyValueMap::const_iterator aFound(\n aStaticDefaults.find( nHandle ));\n\n if( aFound == aStaticDefaults.end())\n return uno::Any();\n\n return (*aFound).second;\n \/\/ \\--\n}\n\n::cppu::IPropertyArrayHelper & SAL_CALL GridProperties::getInfoHelper()\n{\n return lcl_getInfoHelper();\n}\n\n\/\/ ____ XPropertySet ____\nReference< beans::XPropertySetInfo > SAL_CALL\n GridProperties::getPropertySetInfo()\n throw (uno::RuntimeException)\n{\n static Reference< beans::XPropertySetInfo > xInfo;\n\n \/\/ \/--\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if( !xInfo.is())\n {\n xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(\n lcl_getInfoHelper());\n }\n\n return xInfo;\n \/\/ \\--\n}\n\n\/\/ ____ XCloneable ____\nuno::Reference< util::XCloneable > SAL_CALL GridProperties::createClone()\n throw (uno::RuntimeException)\n{\n return uno::Reference< util::XCloneable >( new GridProperties( *this ));\n}\n\n\/\/ ____ XModifyBroadcaster ____\nvoid SAL_CALL GridProperties::addModifyListener( const Reference< util::XModifyListener >& aListener )\n throw (uno::RuntimeException)\n{\n try\n {\n Reference< util::XModifyBroadcaster > xBroadcaster( m_xModifyEventForwarder, uno::UNO_QUERY_THROW );\n xBroadcaster->addModifyListener( aListener );\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n}\n\nvoid SAL_CALL GridProperties::removeModifyListener( const Reference< util::XModifyListener >& aListener )\n throw (uno::RuntimeException)\n{\n try\n {\n Reference< util::XModifyBroadcaster > xBroadcaster( m_xModifyEventForwarder, uno::UNO_QUERY_THROW );\n xBroadcaster->removeModifyListener( aListener );\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n}\n\n\/\/ ____ XModifyListener ____\nvoid SAL_CALL GridProperties::modified( const lang::EventObject& aEvent )\n throw (uno::RuntimeException)\n{\n m_xModifyEventForwarder->modified( aEvent );\n}\n\n\/\/ ____ XEventListener (base of XModifyListener) ____\nvoid SAL_CALL GridProperties::disposing( const lang::EventObject& \/* Source *\/ )\n throw (uno::RuntimeException)\n{\n \/\/ nothing\n}\n\n\/\/ ____ OPropertySet ____\nvoid GridProperties::firePropertyChangeEvent()\n{\n fireModifyEvent();\n}\n\nvoid GridProperties::fireModifyEvent()\n{\n m_xModifyEventForwarder->modified( lang::EventObject( static_cast< uno::XWeak* >( this )));\n}\n\n\/\/ ================================================================================\n\nSequence< OUString > GridProperties::getSupportedServiceNames_Static()\n{\n Sequence< OUString > aServices( 2 );\n aServices[ 0 ] = C2U( \"com.sun.star.chart2.GridProperties\" );\n aServices[ 1 ] = C2U( \"com.sun.star.beans.PropertySet\" );\n return aServices;\n}\n\n\/\/ implement XServiceInfo methods basing upon getSupportedServiceNames_Static\nAPPHELPER_XSERVICEINFO_IMPL( GridProperties, lcl_aServiceName );\n\n\/\/ needed by MSC compiler\nusing impl::GridProperties_Base;\n\nIMPLEMENT_FORWARD_XINTERFACE2( GridProperties, GridProperties_Base, ::property::OPropertySet )\nIMPLEMENT_FORWARD_XTYPEPROVIDER2( GridProperties, GridProperties_Base, ::property::OPropertySet )\n\n} \/\/ namespace chart\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file tc.hxx\n * @author Muhammad A. Awad (mawad@ucdavis.edu)\n * @brief Triangle Counting algorithm.\n * @version 0.1\n * @date 2022-08-06\n *\n * @copyright Copyright (c) 2022\n *\n *\/\n#pragma once\n\n#include <gunrock\/algorithms\/algorithms.hxx>\n#include <gunrock\/util\/timer.hxx>\n\nnamespace gunrock {\nnamespace tc {\n\ntemplate <typename vertex_t>\nstruct param_t {\n bool reduce_all_triangles;\n param_t(bool _reduce_all_triangles)\n : reduce_all_triangles(_reduce_all_triangles) {}\n};\n\ntemplate <typename vertex_t>\nstruct result_t {\n vertex_t* vertex_triangles_count;\n std::size_t* total_triangles_count;\n result_t(vertex_t* _vertex_triangles_count, uint64_t* _total_triangles_count)\n : vertex_triangles_count(_vertex_triangles_count),\n total_triangles_count(_total_triangles_count) {}\n};\n\ntemplate <typename graph_t, typename param_type, typename result_type>\nstruct problem_t : gunrock::problem_t<graph_t> {\n param_type param;\n result_type result;\n\n problem_t(graph_t& G,\n param_type& _param,\n result_type& _result,\n std::shared_ptr<gcuda::multi_context_t> _context)\n : gunrock::problem_t<graph_t>(G, _context),\n param(_param),\n result(_result) {}\n\n using vertex_t = typename graph_t::vertex_type;\n using edge_t = typename graph_t::edge_type;\n\n void init() override {}\n\n void reset() override {}\n};\n\ntemplate <typename problem_t>\nstruct enactor_t : gunrock::enactor_t<problem_t> {\n enactor_t(problem_t* _problem,\n std::shared_ptr<gcuda::multi_context_t> _context,\n enactor_properties_t _properties)\n : gunrock::enactor_t<problem_t>(_problem, _context, _properties) {}\n\n using vertex_t = typename problem_t::vertex_t;\n using edge_t = typename problem_t::edge_t;\n using weight_t = typename problem_t::weight_t;\n using frontier_t = typename enactor_t<problem_t>::frontier_t;\n\n void loop(gcuda::multi_context_t& context) override {\n \/\/ Data slice\n auto E = this->get_enactor();\n auto P = this->get_problem();\n auto G = P->get_graph();\n\n auto vertex_triangles_count = P->result.vertex_triangles_count;\n\n auto intersect = [G, vertex_triangles_count] __host__ __device__(\n vertex_t const& source, \/\/ ... source\n vertex_t const& neighbor, \/\/ neighbor\n edge_t const& edge, \/\/ edge\n weight_t const& weight \/\/ weight (tuple).\n ) -> bool {\n if (neighbor > source) {\n auto src_vertex_triangles_count = G.get_intersection_count(\n source, neighbor,\n [vertex_triangles_count](auto intersection_vertex) {\n math::atomic::add(&(vertex_triangles_count[intersection_vertex]),\n vertex_t{1});\n });\n }\n return false;\n };\n\n \/\/ Execute advance operator on the provided lambda\n operators::advance::execute<operators::load_balance_t::block_mapped,\n operators::advance_direction_t::forward,\n operators::advance_io_type_t::graph,\n operators::advance_io_type_t::none>(\n G, E, intersect, context);\n }\n\n virtual bool is_converged(gcuda::multi_context_t& context) {\n if (this->iteration == 1)\n return true;\n return false;\n }\n\n float post_process() {\n util::timer_t timer;\n timer.begin();\n auto P = this->get_problem();\n auto G = P->get_graph();\n\n if (P->param.reduce_all_triangles) {\n auto policy = this->context->get_context(0)->execution_policy();\n *P->result.total_triangles_count = thrust::transform_reduce(\n policy, P->result.vertex_triangles_count,\n P->result.vertex_triangles_count + G.get_number_of_vertices(),\n [] __device__(const vertex_t& vertex_triangles) {\n return static_cast<std::size_t>(vertex_triangles);\n },\n std::size_t{0}, thrust::plus<std::size_t>());\n }\n return timer.end();\n }\n}; \/\/ struct enactor_t\n\ntemplate <typename graph_t>\nfloat run(graph_t& G,\n bool reduce_all_triangles,\n typename graph_t::vertex_type* vertex_triangles_count, \/\/ Output\n std::size_t* total_triangles_count, \/\/ Output\n std::shared_ptr<gcuda::multi_context_t> context =\n std::shared_ptr<gcuda::multi_context_t>(\n new gcuda::multi_context_t(0)) \/\/ Context\n) {\n \/\/ <user-defined>\n using vertex_t = typename graph_t::vertex_type;\n using weight_t = typename graph_t::weight_type;\n\n using param_type = param_t<vertex_t>;\n using result_type = result_t<vertex_t>;\n\n param_type param(reduce_all_triangles);\n result_type result(vertex_triangles_count, total_triangles_count);\n \/\/ <\/user-defined>\n\n using problem_type = problem_t<graph_t, param_type, result_type>;\n using enactor_type = enactor_t<problem_type>;\n\n problem_type problem(G, param, result, context);\n problem.init();\n problem.reset();\n\n \/\/ Disable internal-frontiers:\n enactor_properties_t props;\n props.self_manage_frontiers = true;\n enactor_type enactor(&problem, context, props);\n auto time = enactor.enact();\n time += enactor.post_process();\n\n \/\/ <\/boiler-plate>\n return time;\n}\n\n} \/\/ namespace tc\n} \/\/ namespace gunrock<commit_msg>Handle self loops in intersection lambda<commit_after>\/**\n * @file tc.hxx\n * @author Muhammad A. Awad (mawad@ucdavis.edu)\n * @brief Triangle Counting algorithm.\n * @version 0.1\n * @date 2022-08-06\n *\n * @copyright Copyright (c) 2022\n *\n *\/\n#pragma once\n\n#include <gunrock\/algorithms\/algorithms.hxx>\n#include <gunrock\/util\/timer.hxx>\n\nnamespace gunrock {\nnamespace tc {\n\ntemplate <typename vertex_t>\nstruct param_t {\n bool reduce_all_triangles;\n param_t(bool _reduce_all_triangles)\n : reduce_all_triangles(_reduce_all_triangles) {}\n};\n\ntemplate <typename vertex_t>\nstruct result_t {\n vertex_t* vertex_triangles_count;\n std::size_t* total_triangles_count;\n result_t(vertex_t* _vertex_triangles_count, uint64_t* _total_triangles_count)\n : vertex_triangles_count(_vertex_triangles_count),\n total_triangles_count(_total_triangles_count) {}\n};\n\ntemplate <typename graph_t, typename param_type, typename result_type>\nstruct problem_t : gunrock::problem_t<graph_t> {\n param_type param;\n result_type result;\n\n problem_t(graph_t& G,\n param_type& _param,\n result_type& _result,\n std::shared_ptr<gcuda::multi_context_t> _context)\n : gunrock::problem_t<graph_t>(G, _context),\n param(_param),\n result(_result) {}\n\n using vertex_t = typename graph_t::vertex_type;\n using edge_t = typename graph_t::edge_type;\n\n void init() override {}\n\n void reset() override {}\n};\n\ntemplate <typename problem_t>\nstruct enactor_t : gunrock::enactor_t<problem_t> {\n enactor_t(problem_t* _problem,\n std::shared_ptr<gcuda::multi_context_t> _context,\n enactor_properties_t _properties)\n : gunrock::enactor_t<problem_t>(_problem, _context, _properties) {}\n\n using vertex_t = typename problem_t::vertex_t;\n using edge_t = typename problem_t::edge_t;\n using weight_t = typename problem_t::weight_t;\n using frontier_t = typename enactor_t<problem_t>::frontier_t;\n\n void loop(gcuda::multi_context_t& context) override {\n \/\/ Data slice\n auto E = this->get_enactor();\n auto P = this->get_problem();\n auto G = P->get_graph();\n\n auto vertex_triangles_count = P->result.vertex_triangles_count;\n\n auto intersect = [G, vertex_triangles_count] __host__ __device__(\n vertex_t const& source, \/\/ ... source\n vertex_t const& neighbor, \/\/ neighbor\n edge_t const& edge, \/\/ edge\n weight_t const& weight \/\/ weight (tuple).\n ) -> bool {\n if (neighbor > source) {\n auto src_vertex_triangles_count = G.get_intersection_count(\n source, neighbor,\n [vertex_triangles_count, source,\n neighbor](auto intersection_vertex) {\n if (source != intersection_vertex &&\n neighbor != intersection_vertex) {\n math::atomic::add(\n &(vertex_triangles_count[intersection_vertex]),\n vertex_t{1});\n }\n });\n }\n return false;\n };\n\n \/\/ Execute advance operator on the provided lambda\n operators::advance::execute<operators::load_balance_t::block_mapped,\n operators::advance_direction_t::forward,\n operators::advance_io_type_t::graph,\n operators::advance_io_type_t::none>(\n G, E, intersect, context);\n }\n\n virtual bool is_converged(gcuda::multi_context_t& context) {\n if (this->iteration == 1)\n return true;\n return false;\n }\n\n float post_process() {\n util::timer_t timer;\n timer.begin();\n auto P = this->get_problem();\n auto G = P->get_graph();\n\n if (P->param.reduce_all_triangles) {\n auto policy = this->context->get_context(0)->execution_policy();\n *P->result.total_triangles_count = thrust::transform_reduce(\n policy, P->result.vertex_triangles_count,\n P->result.vertex_triangles_count + G.get_number_of_vertices(),\n [] __device__(const vertex_t& vertex_triangles) {\n return static_cast<std::size_t>(vertex_triangles);\n },\n std::size_t{0}, thrust::plus<std::size_t>());\n }\n return timer.end();\n }\n}; \/\/ struct enactor_t\n\ntemplate <typename graph_t>\nfloat run(graph_t& G,\n bool reduce_all_triangles,\n typename graph_t::vertex_type* vertex_triangles_count, \/\/ Output\n std::size_t* total_triangles_count, \/\/ Output\n std::shared_ptr<gcuda::multi_context_t> context =\n std::shared_ptr<gcuda::multi_context_t>(\n new gcuda::multi_context_t(0)) \/\/ Context\n) {\n \/\/ <user-defined>\n using vertex_t = typename graph_t::vertex_type;\n using weight_t = typename graph_t::weight_type;\n\n using param_type = param_t<vertex_t>;\n using result_type = result_t<vertex_t>;\n\n param_type param(reduce_all_triangles);\n result_type result(vertex_triangles_count, total_triangles_count);\n \/\/ <\/user-defined>\n\n using problem_type = problem_t<graph_t, param_type, result_type>;\n using enactor_type = enactor_t<problem_type>;\n\n problem_type problem(G, param, result, context);\n problem.init();\n problem.reset();\n\n \/\/ Disable internal-frontiers:\n enactor_properties_t props;\n props.self_manage_frontiers = true;\n enactor_type enactor(&problem, context, props);\n auto time = enactor.enact();\n time += enactor.post_process();\n\n \/\/ <\/boiler-plate>\n return time;\n}\n\n} \/\/ namespace tc\n} \/\/ namespace gunrock<|endoftext|>"} {"text":"<commit_before>\/*\n +----------------------------------------------------------------------+\n | HipHop for PHP |\n +----------------------------------------------------------------------+\n | Copyright (c) 2015 Alexandre Kalendarev |\n +----------------------------------------------------------------------+\n | This source file is subject to version 3.01 of the PHP license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.php.net\/license\/3_01.txt |\n | If you did not receive a copy of the PHP license and are unable to |\n | obtain it through the world-wide-web, please send a note to |\n | license@php.net so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n\n\t part this code was derived from tarantool\/msgpuck, author Roman Tsisyk\n\n\t for HHVM version 3.13\n*\/\n\n\/*\n KindOfUninit = 0x00, \/\/ 00000000 0\n KindOfNull = 0x01, \/\/ 00000001 1\n KindOfBoolean = 0x09, \/\/ 00001001 9\n KindOfInt64 = 0x11, \/\/ 00010001 17\n KindOfDouble = 0x19, \/\/ 00011001 25 \n KindOfPersistentString = 0x1b, \/\/ 00011011 27\n KindOfPersistentArray = 0x1d, \/\/ 00011101 29\n KindOfString = 0x22, \/\/ 00100010 34 \n KindOfArray = 0x34, \/\/ 00110100 52\n KindOfObject = 0x40, \/\/ 01000000 64 \n KindOfResource = 0x50, \/\/ 01010000\n KindOfRef = 0x60, \/\/ 01100000\n*\/\n\n\n#include \"hphp\/runtime\/ext\/extension.h\"\n#include \"hphp\/runtime\/base\/execution-context.h\" \/\/ g_context\n\n#define MP_SOURCE 1\n#include \"msgpuck.h\"\n#include \"msgpack.h\"\n\nnamespace HPHP {\n\n\nstatic void printVariant(const Variant& data);\nstatic void packVariant(const Variant& el);\n\n\nstatic int sizeof_pack( const Array& data ) {\n\t\t\n\tint size = 0;\n\n\tfor (int i=0; i < data.length(); i++) {\n\t\tVariant el(data[i]);\n\t\tswitch(el.getType()) {\n\t\t\t\n\t\t\tcase KindOfInt64 : {\n\t\t\t\tsize += mp_sizeof_int( el.toInt64() ); \n\t\t\t\tbreak; \n\t\t\t}\n\t\t\t\n\t\t\tcase KindOfNull : {\n\t\t\t\tsize += mp_sizeof_nil();\n\t\t\t\tbreak; \n\t\t\t}\n\t\t\t\n\t\t\tcase KindOfPersistentString:\n\t\t\tcase KindOfString : {\n\t\t\t\tsize += mp_sizeof_str( el.toString().length());\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase KindOfPersistentArray:\n\t\t\tcase KindOfArray : {\n\t\t\t\tsize += mp_sizeof_array( el.toArray().size() );\n\t\t\t\tint arr_size = sizeof_pack( el.toArray() );\n\t\t\t\tsize += arr_size;\n\t\t\t\tbreak; \n\t\t\t}\n\n\t\t\tcase KindOfDouble : \n\t\t\t\tsize += mp_sizeof_float(el.toDouble());\n\t\t\t\tbreak;\n\t\t \n\t\t\tcase KindOfBoolean : \n\t\t\t\tsize += mp_sizeof_bool(el.toBoolean());\n\t\t\t\tbreak;\n\n\n\t\t\tdefault : g_context->write( \"wrong\\n\");\n\t\t}\n\t}\n\n\treturn size;\n}\n\nstatic void arrayIteration(ArrayData* data, void (arrayIterationCb) (const Variant& , const Variant&)) {\n\n\tfor (ssize_t pos = data->iter_begin(); pos != data->iter_end();\n\t pos = data->iter_advance(pos)) {\n\t const Variant key = data->getKey(pos);\n\t \t const Variant val = data->getValue(pos);\n\t \t arrayIterationCb(key, val);\n\t}\n}\n\nstatic void encodeArrayElement(const Variant& key, const Variant& val) {\n\tpackVariant(key);\n\tpackVariant(val); \n}\n\n\nstatic void packVariant(const Variant& el) {\n\t\t\n\tswitch(el.getType()) {\n\t\tcase KindOfInt64 : { \n\t\t\tint64_t int_val = el.toInt64();\n\t\t\tif (int_val >= 0)\n\t\t\t\tMsgpackExtension::BufferPtr = mp_encode_uint(MsgpackExtension::BufferPtr, int_val );\n\t\t\telse\n\t\t\t\tMsgpackExtension::BufferPtr = mp_encode_int(MsgpackExtension::BufferPtr, int_val );\n\t\t\tbreak; }\n\t\t\n\t\tcase KindOfNull : { \n\t\t\tMsgpackExtension::BufferPtr = mp_encode_nil(MsgpackExtension::BufferPtr);\n\t\t\tbreak; }\n\n\t\tcase KindOfBoolean : { \n\t\t\tMsgpackExtension::BufferPtr = mp_encode_bool(MsgpackExtension::BufferPtr, el.toBoolean());\n\t\t\tbreak; \n\t\t}\n\n\t\tcase KindOfPersistentString:\n\t\tcase KindOfString : {\n\t\t\tMsgpackExtension::BufferPtr = mp_encode_str(MsgpackExtension::BufferPtr, el.toString().c_str(), el.toString().length());\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase KindOfPersistentArray:\n\t\tcase KindOfArray : {\n\n\t\t\t\tMsgpackExtension::BufferPtr = mp_encode_map(MsgpackExtension::BufferPtr, el.toArray().length());\n\t\t\t\tArrayData* ad = el.toArray().get();\n\t\t\t\tarrayIteration(ad, encodeArrayElement);\n\t\t\t\tbreak; \n\t\t\t}\n\n\t\tcase KindOfDouble : {\n\t\t\tMsgpackExtension::BufferPtr = mp_encode_double(MsgpackExtension::BufferPtr, el.toDouble());\n\t\t\tbreak;\n\t \t}\n\t\t\n\t\tdefault : raise_warning(\"error type of data element\");\n\t}\n};\n\nvoid unpackElement( char **p, Variant* pout) {\n\n\tconst char c = (**p);\n\tchar * pos = *p;\n\tmp_type type = mp_typeof(c);\n\t\n\tswitch(type) {\n\n\t\tcase MP_NIL : {\n\t\t\tpout->setNull();\n\t\t\t(*p)++;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase MP_UINT : {\n\t\t\tint64_t intval = mp_decode_uint(const_cast<const char**>(&pos));\n\t\n\t\t\t*pout = intval;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tcase MP_INT : {\n\t\t\tint64_t intval = mp_decode_int(const_cast<const char**>(&pos));\n\t\n\t\t\t*pout = intval;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tcase MP_STR : {\n\t\t\tuint32_t len = 0;\n\t\t\tconst char * res = mp_decode_str(const_cast<const char**>(&pos), &len);\n\t\t\t*p = pos;\n\t\t\t*pout = String(StringData::Make( res, len, CopyString ));\n\t\t\tbreak;\n\t\t}\n\n\t\tcase MP_BOOL : {\n\t\t\tconst bool res = mp_decode_bool(const_cast<const char**>(&pos));\n\t\t\t*p = pos;\n\t\t\t*pout = res ? true : false;\n\t\t\tbreak;\n\n\t\t}\n\n\t\tcase MP_DOUBLE : {\n\t\t\tdouble dbl_val = mp_decode_double(const_cast<const char**>(&pos));\n\t\t\t*pout = dbl_val;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tcase MP_ARRAY : {\n\t\t\tint count = mp_decode_array(const_cast<const char**>(&pos));\n\t\t\tArray ret = Array::Create();\n\t\t\tfor(int i = 0; i < count; ++i) {\n\t\t\t\tVariant val;\n\t\t\t\tunpackElement( &pos, &val);\n\t\t\t\tret.add(i,val);\n\t\t\t}\n\n\t\t\t*pout = ret;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tcase MP_MAP : {\n\t\t\tint count = mp_decode_map(const_cast<const char**>(&pos));\n\n\t\t\tArray ret = Array::Create();\n\t\t\tfor(int i = 0; i < count; ++i) {\n\t\t\t\tVariant key, val;\n\t\t\t\tunpackElement( &pos, &key);\n\t\t\t\tunpackElement( &pos, &val);\n\n\t\t\t\tret.add(key,val,true);\n\t\t\t}\n\n\t\t\t*pout = ret;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tdefault : \n\t\t\traise_warning(\"unpack error data element\");\n\t\t\tpout->setNull();\t\n\t\t\tmp_next(const_cast<const char**>(p));\n\t}\n\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MsgpackExtension::moduleInit() {\n\t\n\tHHVM_FE(msgpack_pack);\n\tHHVM_FE(msgpack_unpack);\n\n\tloadSystemlib();\n\n\tMsgpackExtension::BufferSize = BUFFSIZE;\n\tMsgpackExtension::Buffer = malloc(BUFFSIZE);\t\n\n}\n\nvoid MsgpackExtension::moduleShutdown() {\n\n\tfree(MsgpackExtension::Buffer);\n\t\/\/ printf(\"moduleShutdown size=%d\\n\", MsgpackExtension::BufferSize);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ static \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint MsgpackExtension::BufferSize = 0;\nint MsgpackExtension::Level = 0;\nvoid* MsgpackExtension::Buffer = NULL;\nchar* MsgpackExtension::BufferPtr = NULL;\n\n\nstatic MsgpackExtension s_msgpack_extension;\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ HHVM_FUNCTION \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nstatic String HHVM_FUNCTION(msgpack_pack, const Array& data) {\n\n\tMsgpackExtension::Level = 0;\t\n\tMsgpackExtension::BufferPtr = static_cast<char*>(MsgpackExtension::Buffer);\n\tMsgpackExtension::BufferPtr = mp_encode_array( MsgpackExtension::BufferPtr, data.length());\t\n\t\n\n\tfor (int i = 0; i < data.length(); ++i)\t{\n\t\tpackVariant(data[i]);\n\t}\n\tsize_t len = reinterpret_cast<uint64_t>(MsgpackExtension::BufferPtr) - reinterpret_cast<uint64_t>(MsgpackExtension::Buffer);\n\n\tStringData* str = StringData::Make(reinterpret_cast<const char*>(MsgpackExtension::Buffer), len, CopyString);\n\n\treturn String(str);\n}\n\n\nstatic Array HHVM_FUNCTION(msgpack_unpack, const String& data) {\n\tArray ret = Array::Create();\n\n\tchar * p = const_cast<char *>(data.c_str());\n\tchar c = *p;\n\n\tif ( mp_typeof(c) != MP_ARRAY ) {\n \t\traise_warning(\"the root element must be array\");\n\t\treturn ret;\n\t}\n\tint count = mp_decode_array( const_cast<const char**>(&p));\n\n\tprintf(\"elements %d\\n\", count);\n\n\tfor (int i =0; i < count; i++) {\n\t\tVariant el;\n\t\tunpackElement(&p, &el);\n\t\tret.set(i, el);\n\t}\n\n\treturn ret;\n}\n\n\n\nHHVM_GET_MODULE(msgpack);\n\n} \/\/ namespace HPHP<commit_msg>remove comments<commit_after>\/*\n +----------------------------------------------------------------------+\n | HipHop for PHP |\n +----------------------------------------------------------------------+\n | Copyright (c) 2015 Alexandre Kalendarev |\n +----------------------------------------------------------------------+\n | This source file is subject to version 3.01 of the PHP license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.php.net\/license\/3_01.txt |\n | If you did not receive a copy of the PHP license and are unable to |\n | obtain it through the world-wide-web, please send a note to |\n | license@php.net so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n\n\t part this code was derived from tarantool\/msgpuck, author Roman Tsisyk\n\n\t for HHVM version 3.13\n*\/\n\n#include \"hphp\/runtime\/ext\/extension.h\"\n#include \"hphp\/runtime\/base\/execution-context.h\" \/\/ g_context\n\n#define MP_SOURCE 1\n#include \"msgpuck.h\"\n#include \"msgpack.h\"\n\nnamespace HPHP {\n\n\nstatic void printVariant(const Variant& data);\nstatic void packVariant(const Variant& el);\n\n\nstatic int sizeof_pack( const Array& data ) {\n\t\t\n\tint size = 0;\n\n\tfor (int i=0; i < data.length(); i++) {\n\t\tVariant el(data[i]);\n\t\tswitch(el.getType()) {\n\t\t\t\n\t\t\tcase KindOfInt64 : {\n\t\t\t\tsize += mp_sizeof_int( el.toInt64() ); \n\t\t\t\tbreak; \n\t\t\t}\n\t\t\t\n\t\t\tcase KindOfNull : {\n\t\t\t\tsize += mp_sizeof_nil();\n\t\t\t\tbreak; \n\t\t\t}\n\t\t\t\n\t\t\tcase KindOfPersistentString:\n\t\t\tcase KindOfString : {\n\t\t\t\tsize += mp_sizeof_str( el.toString().length());\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase KindOfPersistentArray:\n\t\t\tcase KindOfArray : {\n\t\t\t\tsize += mp_sizeof_array( el.toArray().size() );\n\t\t\t\tint arr_size = sizeof_pack( el.toArray() );\n\t\t\t\tsize += arr_size;\n\t\t\t\tbreak; \n\t\t\t}\n\n\t\t\tcase KindOfDouble : \n\t\t\t\tsize += mp_sizeof_float(el.toDouble());\n\t\t\t\tbreak;\n\t\t \n\t\t\tcase KindOfBoolean : \n\t\t\t\tsize += mp_sizeof_bool(el.toBoolean());\n\t\t\t\tbreak;\n\n\n\t\t\tdefault : g_context->write( \"wrong\\n\");\n\t\t}\n\t}\n\n\treturn size;\n}\n\nstatic void arrayIteration(ArrayData* data, void (arrayIterationCb) (const Variant& , const Variant&)) {\n\n\tfor (ssize_t pos = data->iter_begin(); pos != data->iter_end();\n\t pos = data->iter_advance(pos)) {\n\t const Variant key = data->getKey(pos);\n\t \t const Variant val = data->getValue(pos);\n\t \t arrayIterationCb(key, val);\n\t}\n}\n\nstatic void encodeArrayElement(const Variant& key, const Variant& val) {\n\tpackVariant(key);\n\tpackVariant(val); \n}\n\n\nstatic void packVariant(const Variant& el) {\n\t\t\n\tswitch(el.getType()) {\n\t\tcase KindOfInt64 : { \n\t\t\tint64_t int_val = el.toInt64();\n\t\t\tif (int_val >= 0)\n\t\t\t\tMsgpackExtension::BufferPtr = mp_encode_uint(MsgpackExtension::BufferPtr, int_val );\n\t\t\telse\n\t\t\t\tMsgpackExtension::BufferPtr = mp_encode_int(MsgpackExtension::BufferPtr, int_val );\n\t\t\tbreak; }\n\t\t\n\t\tcase KindOfNull : { \n\t\t\tMsgpackExtension::BufferPtr = mp_encode_nil(MsgpackExtension::BufferPtr);\n\t\t\tbreak; }\n\n\t\tcase KindOfBoolean : { \n\t\t\tMsgpackExtension::BufferPtr = mp_encode_bool(MsgpackExtension::BufferPtr, el.toBoolean());\n\t\t\tbreak; \n\t\t}\n\n\t\tcase KindOfPersistentString:\n\t\tcase KindOfString : {\n\t\t\tMsgpackExtension::BufferPtr = mp_encode_str(MsgpackExtension::BufferPtr, el.toString().c_str(), el.toString().length());\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase KindOfPersistentArray:\n\t\tcase KindOfArray : {\n\n\t\t\t\tMsgpackExtension::BufferPtr = mp_encode_map(MsgpackExtension::BufferPtr, el.toArray().length());\n\t\t\t\tArrayData* ad = el.toArray().get();\n\t\t\t\tarrayIteration(ad, encodeArrayElement);\n\t\t\t\tbreak; \n\t\t\t}\n\n\t\tcase KindOfDouble : {\n\t\t\tMsgpackExtension::BufferPtr = mp_encode_double(MsgpackExtension::BufferPtr, el.toDouble());\n\t\t\tbreak;\n\t \t}\n\t\t\n\t\tdefault : raise_warning(\"error type of data element\");\n\t}\n};\n\nvoid unpackElement( char **p, Variant* pout) {\n\n\tconst char c = (**p);\n\tchar * pos = *p;\n\tmp_type type = mp_typeof(c);\n\t\n\tswitch(type) {\n\n\t\tcase MP_NIL : {\n\t\t\tpout->setNull();\n\t\t\t(*p)++;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase MP_UINT : {\n\t\t\tint64_t intval = mp_decode_uint(const_cast<const char**>(&pos));\n\t\n\t\t\t*pout = intval;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tcase MP_INT : {\n\t\t\tint64_t intval = mp_decode_int(const_cast<const char**>(&pos));\n\t\n\t\t\t*pout = intval;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tcase MP_STR : {\n\t\t\tuint32_t len = 0;\n\t\t\tconst char * res = mp_decode_str(const_cast<const char**>(&pos), &len);\n\t\t\t*p = pos;\n\t\t\t*pout = String(StringData::Make( res, len, CopyString ));\n\t\t\tbreak;\n\t\t}\n\n\t\tcase MP_BOOL : {\n\t\t\tconst bool res = mp_decode_bool(const_cast<const char**>(&pos));\n\t\t\t*p = pos;\n\t\t\t*pout = res ? true : false;\n\t\t\tbreak;\n\n\t\t}\n\n\t\tcase MP_DOUBLE : {\n\t\t\tdouble dbl_val = mp_decode_double(const_cast<const char**>(&pos));\n\t\t\t*pout = dbl_val;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tcase MP_ARRAY : {\n\t\t\tint count = mp_decode_array(const_cast<const char**>(&pos));\n\t\t\tArray ret = Array::Create();\n\t\t\tfor(int i = 0; i < count; ++i) {\n\t\t\t\tVariant val;\n\t\t\t\tunpackElement( &pos, &val);\n\t\t\t\tret.add(i,val);\n\t\t\t}\n\n\t\t\t*pout = ret;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tcase MP_MAP : {\n\t\t\tint count = mp_decode_map(const_cast<const char**>(&pos));\n\n\t\t\tArray ret = Array::Create();\n\t\t\tfor(int i = 0; i < count; ++i) {\n\t\t\t\tVariant key, val;\n\t\t\t\tunpackElement( &pos, &key);\n\t\t\t\tunpackElement( &pos, &val);\n\n\t\t\t\tret.add(key,val,true);\n\t\t\t}\n\n\t\t\t*pout = ret;\n\t\t\t*p = pos;\n\t\t\tbreak; \n\t\t}\n\n\t\tdefault : \n\t\t\traise_warning(\"unpack error data element\");\n\t\t\tpout->setNull();\t\n\t\t\tmp_next(const_cast<const char**>(p));\n\t}\n\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MsgpackExtension::moduleInit() {\n\t\n\tHHVM_FE(msgpack_pack);\n\tHHVM_FE(msgpack_unpack);\n\n\tloadSystemlib();\n\n\tMsgpackExtension::BufferSize = BUFFSIZE;\n\tMsgpackExtension::Buffer = malloc(BUFFSIZE);\t\n\n}\n\nvoid MsgpackExtension::moduleShutdown() {\n\n\tfree(MsgpackExtension::Buffer);\n\t\/\/ printf(\"moduleShutdown size=%d\\n\", MsgpackExtension::BufferSize);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ static \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint MsgpackExtension::BufferSize = 0;\nint MsgpackExtension::Level = 0;\nvoid* MsgpackExtension::Buffer = NULL;\nchar* MsgpackExtension::BufferPtr = NULL;\n\n\nstatic MsgpackExtension s_msgpack_extension;\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ HHVM_FUNCTION \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nstatic String HHVM_FUNCTION(msgpack_pack, const Array& data) {\n\n\tMsgpackExtension::Level = 0;\t\n\tMsgpackExtension::BufferPtr = static_cast<char*>(MsgpackExtension::Buffer);\n\tMsgpackExtension::BufferPtr = mp_encode_array( MsgpackExtension::BufferPtr, data.length());\t\n\t\n\n\tfor (int i = 0; i < data.length(); ++i)\t{\n\t\tpackVariant(data[i]);\n\t}\n\tsize_t len = reinterpret_cast<uint64_t>(MsgpackExtension::BufferPtr) - reinterpret_cast<uint64_t>(MsgpackExtension::Buffer);\n\n\tStringData* str = StringData::Make(reinterpret_cast<const char*>(MsgpackExtension::Buffer), len, CopyString);\n\n\treturn String(str);\n}\n\n\nstatic Array HHVM_FUNCTION(msgpack_unpack, const String& data) {\n\tArray ret = Array::Create();\n\n\tchar * p = const_cast<char *>(data.c_str());\n\tchar c = *p;\n\n\tif ( mp_typeof(c) != MP_ARRAY ) {\n \t\traise_warning(\"the root element must be array\");\n\t\treturn ret;\n\t}\n\tint count = mp_decode_array( const_cast<const char**>(&p));\n\n\tprintf(\"elements %d\\n\", count);\n\n\tfor (int i =0; i < count; i++) {\n\t\tVariant el;\n\t\tunpackElement(&p, &el);\n\t\tret.set(i, el);\n\t}\n\n\treturn ret;\n}\n\n\n\nHHVM_GET_MODULE(msgpack);\n\n} \/\/ namespace HPHP<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 Giorgio Marcias\n\/\/\n\/\/ This file is part of distance_transform, a C++11 implementation of the\n\/\/ algorithm in \"Distance Transforms of Sampled Functions\"\n\/\/ Pedro F. Felzenszwalb, Daniel P. Huttenlocher\n\/\/ Theory of Computing, Vol. 8, No. 19, September 2012\n\/\/\n\/\/ This source code is subject to Apache 2.0 License.\n\/\/\n\/\/ Author: Giorgio Marcias\n\/\/ email: marcias.giorgio@gmail.com\n\n#ifndef multiple_array_hpp\n#define multiple_array_hpp\n\n#include <cstddef>\n#include <cstring>\n#include <memory>\n#include <type_traits>\n#include <exception>\n#include <sstream>\n#include <utility>\n\ntemplate < typename T, std::size_t D >\nclass MArray {\npublic:\n MArray() : _array(nullptr), _accumulatedOffset(0)\n {\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = 0;\n _offset[i] = 0;\n }\n }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[D])\n : _array(const_cast<T*>(array))\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n {\n for (std::size_t i = 0; i < D; ++i)\n _size[i] = _array ? size[i] : 0;\n _offset[D-1] = 1;\n for (std::size_t j = D-1; j > 0; --j)\n _offset[j-1] = _size[j-1] * _offset[j];\n }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[D], const std::size_t offset[D])\n : _array(const_cast<T*>(array))\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n {\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = _array ? size[i] : 0;\n _offset[i] = _array ? offset[i] : 0;\n }\n }\n\n MArray(const MArray &ma)\n : _array(ma._array)\n , _accumulatedOffset(ma._accumulatedOffset)\n {\n for (std::size_t i = 0; i < D; ++i)\n _size[i] = ma._size[i];\n _offset[D-1] = 1;\n for (std::size_t j = D-1; j > 0; --j)\n _offset[j-1] = _size[j-1] * _offset[j];\n }\n\n MArray(MArray &&ma)\n : _array(ma._array)\n , _accumulatedOffset(ma._accumulatedOffset)\n {\n ma._array = nullptr;\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = ma._size[i];\n ma._size[i] = 0;\n _offset[i] = ma._offset[i];\n ma._offset[i] = 0;\n }\n }\n\n inline MArray & operator=(const MArray &ma)\n {\n if (&ma != this) {\n _array = ma._array;\n _accumulatedOffset = ma._accumulatedOffset;\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = ma._size[i];\n _offset[i] = ma._offset[i];\n }\n }\n return *this;\n }\n\n inline MArray & operator=(MArray &&ma)\n {\n if (&ma != this) {\n _array = ma._array;\n ma._array = nullptr;\n _accumulatedOffset = ma._accumulatedOffset;\n ma._accumulatedOffset = 0;\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = ma._size[i];\n ma._size[i] = 0;\n _offset[i] = ma._offset[i];\n ma._offset[i] = 0;\n }\n }\n return *this;\n }\n\n inline MArray<T, D-1> operator[](const std::size_t i) const\n {\n if (i >= _size[0]) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size[0]-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return MArray<T, D-1>(_array + _offset[0] * i, accumulatedOffset(i), _size + 1, _offset + 1);\n }\n\n inline MArray<T, D-1> slice(const std::size_t d, const std::size_t i) const\n {\n if (d >= D) {\n std::stringstream stream;\n stream << \"Index \" << d << \" is out of range [0, \" << D-1 << ']';\n throw std::out_of_range(stream.str());\n }\n if (i >= _size[d]) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size[d]-1 << ']';\n throw std::out_of_range(stream.str());\n }\n std::size_t size[D-1];\n std::size_t offset[D-1];\n std::size_t k = 0;\n for (std::size_t j = 0; j < d; ++j, ++k) {\n size[k] = _size[j];\n offset[k] = _offset[j];\n }\n for (std::size_t j = d+1; j < D; ++j, ++k) {\n size[k] = _size[j];\n offset[k] = _offset[j];\n }\n return MArray<T, D-1>(_array + _offset[d] * i, accumulatedOffset(i, d), size, offset);\n }\n\n inline std::size_t size(const std::size_t d = 0) const\n {\n return _size[d];\n }\n\n inline void size(std::size_t s[D]) const\n {\n for (std::size_t i = 0; i < D; ++i)\n s[i] = _size[i];\n }\n\n inline std::size_t totalSize() const\n {\n std::size_t total = _size[0];\n for (std::size_t i = 1; i < D; ++i)\n total *= _size[i];\n return total;\n }\n\n inline std::size_t accumulatedOffset(const std::size_t i, const std::size_t d = 0) const\n {\n if (d >= D) {\n std::stringstream stream;\n stream << \"Index \" << d << \" is out of range [0, \" << D-1 << ']';\n throw std::out_of_range(stream.str());\n }\n if (i >= _size[0]) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size[d]-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return _accumulatedOffset + _offset[d] * i;\n }\n\nprivate:\n T *_array;\n std::size_t _accumulatedOffset;\n\nprotected:\n std::size_t _size[D];\n\nprivate:\n std::size_t _offset[D];\n};\n\ntemplate < typename T >\nclass MArray<T, 1> {\npublic:\n MArray()\n : _array(nullptr)\n , _accumulatedOffset(0)\n , _size(0)\n , _offset(0)\n { }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size)\n : _array(array)\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n , _size(_array ? size : 0)\n , _offset(0)\n { }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size, const std::size_t offset)\n : _array(array)\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n , _size(_array ? size : 0)\n , _offset(_array ? offset : 0)\n { }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[1])\n : _array(const_cast<T*>(array))\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n , _size(_array ? size[0] : 0)\n , _offset(0)\n { }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[1], const std::size_t offset[1])\n : _array(const_cast<T*>(array))\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n , _size(_array ? size[0] : 0)\n , _offset(_array ? offset[0] : 0)\n { }\n\n MArray(const MArray &ma)\n : _array(ma._array)\n , _accumulatedOffset(ma._accumulatedOffset)\n , _size(ma._size)\n , _offset(ma._offset)\n { }\n\n MArray(MArray &&ma)\n : _array(ma._array)\n , _accumulatedOffset(ma._accumulatedOffset)\n , _size(ma._size)\n , _offset(ma._offset)\n {\n ma._array = nullptr;\n ma._accumulatedOffset = 0;\n ma._size = 0;\n ma._offset = 0;\n }\n\n MArray & operator=(const MArray &ma)\n {\n if (&ma != this) {\n _array = ma._array;\n _size = ma._size;\n _offset = ma._offset;\n }\n return *this;\n }\n\n MArray & operator=(MArray &&ma)\n {\n if (&ma != this) {\n _array = ma._array;\n _size = ma._size;\n _offset = ma._offset;\n ma._array = nullptr;\n ma._size = 0;\n ma._offset = 0;\n }\n return *this;\n }\n\n inline const T & operator[](const std::size_t i) const\n {\n if (i >= _size) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return *(_array + i * _offset);\n }\n\n inline T & operator[](const std::size_t i)\n {\n if (i >= _size) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return *(_array + i * _offset);\n }\n\n inline const T & slice(const std::size_t i) const\n {\n return *this[i];\n }\n\n inline T & slice(const std::size_t i)\n {\n return *this[i];\n }\n\n inline std::size_t size() const\n {\n return _size;\n }\n\n inline std::size_t accumulatedOffset(const std::size_t i = 0) const\n {\n if (i >= _size) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return _accumulatedOffset + _offset * i;\n }\n\nprivate:\n T *_array;\n std::size_t _accumulatedOffset;\n\nprotected:\n std::size_t _size;\n\nprivate:\n std::size_t _offset;\n};\n\ntemplate < typename T, std::size_t D >\nclass MMArray : public MArray<T, D> {\npublic:\n MMArray()\n : MArray<T, D>()\n , _array(nullptr)\n { }\n\n MMArray(const std::size_t size[D])\n {\n std::size_t total = size[0];\n for (std::size_t i = 1; i < D; ++i)\n total *= size[i];\n _array.reset(new T[total]);\n MArray<T, D>::operator=(MArray<T, D>(_array.get(), 0, size));\n }\n\n MMArray(const MMArray<T, D> &mma)\n {\n *this = mma;\n }\n\n MMArray(MMArray &&mma)\n : MArray<T, D>(std::forward<MMArray<T, D>>(mma))\n , _array(std::move(mma._array))\n { }\n\n MMArray & operator=(const MMArray &mma)\n {\n if (&mma != this) {\n _array.reset(new T[mma.totalSize()]);\n std::memcpy(_array.get(), mma._array.get(), mma.totalSize() * sizeof(T));\n std::size_t size[D];\n mma.size(size);\n MArray<T, D>::operator=(MArray<T, D>(_array.get(), 0, size));\n }\n return *this;\n }\n\n MMArray & operator=(MMArray &&mma)\n {\n if (&mma != this) {\n MArray<T, D>::operator=(std::forward<MMArray<T, D>>(mma));\n _array = std::move(mma._array);\n }\n return *this;\n }\n\nprivate:\n std::unique_ptr<T[]> _array;\n};\n\n#endif \/* multiple_array_hpp *\/\n<commit_msg>Added array resizing<commit_after>\/\/ Copyright (c) 2015 Giorgio Marcias\n\/\/\n\/\/ This file is part of distance_transform, a C++11 implementation of the\n\/\/ algorithm in \"Distance Transforms of Sampled Functions\"\n\/\/ Pedro F. Felzenszwalb, Daniel P. Huttenlocher\n\/\/ Theory of Computing, Vol. 8, No. 19, September 2012\n\/\/\n\/\/ This source code is subject to Apache 2.0 License.\n\/\/\n\/\/ Author: Giorgio Marcias\n\/\/ email: marcias.giorgio@gmail.com\n\n#ifndef multiple_array_hpp\n#define multiple_array_hpp\n\n#include <cstddef>\n#include <cstring>\n#include <memory>\n#include <type_traits>\n#include <exception>\n#include <sstream>\n#include <utility>\n\ntemplate < typename T, std::size_t D >\nclass MArray {\npublic:\n MArray() : _array(nullptr), _accumulatedOffset(0)\n {\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = 0;\n _offset[i] = 0;\n }\n }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[D])\n : _array(const_cast<T*>(array))\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n {\n for (std::size_t i = 0; i < D; ++i)\n _size[i] = _array ? size[i] : 0;\n _offset[D-1] = 1;\n for (std::size_t j = D-1; j > 0; --j)\n _offset[j-1] = _size[j-1] * _offset[j];\n }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[D], const std::size_t offset[D])\n : _array(const_cast<T*>(array))\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n {\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = _array ? size[i] : 0;\n _offset[i] = _array ? offset[i] : 0;\n }\n }\n\n MArray(const MArray &ma)\n : _array(ma._array)\n , _accumulatedOffset(ma._accumulatedOffset)\n {\n for (std::size_t i = 0; i < D; ++i)\n _size[i] = ma._size[i];\n _offset[D-1] = 1;\n for (std::size_t j = D-1; j > 0; --j)\n _offset[j-1] = _size[j-1] * _offset[j];\n }\n\n MArray(MArray &&ma)\n : _array(ma._array)\n , _accumulatedOffset(ma._accumulatedOffset)\n {\n ma._array = nullptr;\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = ma._size[i];\n ma._size[i] = 0;\n _offset[i] = ma._offset[i];\n ma._offset[i] = 0;\n }\n }\n\n inline MArray & operator=(const MArray &ma)\n {\n if (&ma != this) {\n _array = ma._array;\n _accumulatedOffset = ma._accumulatedOffset;\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = ma._size[i];\n _offset[i] = ma._offset[i];\n }\n }\n return *this;\n }\n\n inline MArray & operator=(MArray &&ma)\n {\n if (&ma != this) {\n _array = ma._array;\n ma._array = nullptr;\n _accumulatedOffset = ma._accumulatedOffset;\n ma._accumulatedOffset = 0;\n for (std::size_t i = 0; i < D; ++i) {\n _size[i] = ma._size[i];\n ma._size[i] = 0;\n _offset[i] = ma._offset[i];\n ma._offset[i] = 0;\n }\n }\n return *this;\n }\n\n inline MArray<T, D-1> operator[](const std::size_t i) const\n {\n if (i >= _size[0]) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size[0]-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return MArray<T, D-1>(_array + _offset[0] * i, accumulatedOffset(i), _size + 1, _offset + 1);\n }\n\n inline MArray<T, D-1> slice(const std::size_t d, const std::size_t i) const\n {\n if (d >= D) {\n std::stringstream stream;\n stream << \"Index \" << d << \" is out of range [0, \" << D-1 << ']';\n throw std::out_of_range(stream.str());\n }\n if (i >= _size[d]) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size[d]-1 << ']';\n throw std::out_of_range(stream.str());\n }\n std::size_t size[D-1];\n std::size_t offset[D-1];\n std::size_t k = 0;\n for (std::size_t j = 0; j < d; ++j, ++k) {\n size[k] = _size[j];\n offset[k] = _offset[j];\n }\n for (std::size_t j = d+1; j < D; ++j, ++k) {\n size[k] = _size[j];\n offset[k] = _offset[j];\n }\n return MArray<T, D-1>(_array + _offset[d] * i, accumulatedOffset(i, d), size, offset);\n }\n\n inline std::size_t size(const std::size_t d = 0) const\n {\n return _size[d];\n }\n\n inline void size(std::size_t s[D]) const\n {\n for (std::size_t i = 0; i < D; ++i)\n s[i] = _size[i];\n }\n\n inline std::size_t totalSize() const\n {\n std::size_t total = _size[0];\n for (std::size_t i = 1; i < D; ++i)\n total *= _size[i];\n return total;\n }\n\n inline std::size_t accumulatedOffset(const std::size_t i, const std::size_t d = 0) const\n {\n if (d >= D) {\n std::stringstream stream;\n stream << \"Index \" << d << \" is out of range [0, \" << D-1 << ']';\n throw std::out_of_range(stream.str());\n }\n if (i >= _size[0]) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size[d]-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return _accumulatedOffset + _offset[d] * i;\n }\n\nprivate:\n T *_array;\n std::size_t _accumulatedOffset;\n\nprotected:\n std::size_t _size[D];\n\nprivate:\n std::size_t _offset[D];\n};\n\ntemplate < typename T >\nclass MArray<T, 1> {\npublic:\n MArray()\n : _array(nullptr)\n , _accumulatedOffset(0)\n , _size(0)\n , _offset(0)\n { }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size)\n : _array(array)\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n , _size(_array ? size : 0)\n , _offset(0)\n { }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size, const std::size_t offset)\n : _array(array)\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n , _size(_array ? size : 0)\n , _offset(_array ? offset : 0)\n { }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[1])\n : _array(const_cast<T*>(array))\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n , _size(_array ? size[0] : 0)\n , _offset(0)\n { }\n\n MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[1], const std::size_t offset[1])\n : _array(const_cast<T*>(array))\n , _accumulatedOffset(_array ? accumulatedOffset : 0)\n , _size(_array ? size[0] : 0)\n , _offset(_array ? offset[0] : 0)\n { }\n\n MArray(const MArray &ma)\n : _array(ma._array)\n , _accumulatedOffset(ma._accumulatedOffset)\n , _size(ma._size)\n , _offset(ma._offset)\n { }\n\n MArray(MArray &&ma)\n : _array(ma._array)\n , _accumulatedOffset(ma._accumulatedOffset)\n , _size(ma._size)\n , _offset(ma._offset)\n {\n ma._array = nullptr;\n ma._accumulatedOffset = 0;\n ma._size = 0;\n ma._offset = 0;\n }\n\n MArray & operator=(const MArray &ma)\n {\n if (&ma != this) {\n _array = ma._array;\n _size = ma._size;\n _offset = ma._offset;\n }\n return *this;\n }\n\n MArray & operator=(MArray &&ma)\n {\n if (&ma != this) {\n _array = ma._array;\n _size = ma._size;\n _offset = ma._offset;\n ma._array = nullptr;\n ma._size = 0;\n ma._offset = 0;\n }\n return *this;\n }\n\n inline const T & operator[](const std::size_t i) const\n {\n if (i >= _size) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return *(_array + i * _offset);\n }\n\n inline T & operator[](const std::size_t i)\n {\n if (i >= _size) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return *(_array + i * _offset);\n }\n\n inline const T & slice(const std::size_t i) const\n {\n return *this[i];\n }\n\n inline T & slice(const std::size_t i)\n {\n return *this[i];\n }\n\n inline std::size_t size() const\n {\n return _size;\n }\n\n inline std::size_t accumulatedOffset(const std::size_t i = 0) const\n {\n if (i >= _size) {\n std::stringstream stream;\n stream << \"Index \" << i << \" is out of range [0, \" << _size-1 << ']';\n throw std::out_of_range(stream.str());\n }\n return _accumulatedOffset + _offset * i;\n }\n\nprivate:\n T *_array;\n std::size_t _accumulatedOffset;\n\nprotected:\n std::size_t _size;\n\nprivate:\n std::size_t _offset;\n};\n\ntemplate < typename T, std::size_t D >\nclass MMArray : public MArray<T, D> {\npublic:\n MMArray()\n : MArray<T, D>()\n , _array(nullptr)\n { }\n\n MMArray(const std::size_t size[D])\n {\n resize(size);\n }\n\n MMArray(const MMArray<T, D> &mma)\n {\n *this = mma;\n }\n\n MMArray(MMArray &&mma)\n : MArray<T, D>(std::forward<MMArray<T, D>>(mma))\n , _array(std::move(mma._array))\n { }\n\n MMArray & operator=(const MMArray &mma)\n {\n if (&mma != this) {\n _array.reset(new T[mma.totalSize()]);\n std::memcpy(_array.get(), mma._array.get(), mma.totalSize() * sizeof(T));\n std::size_t size[D];\n mma.size(size);\n MArray<T, D>::operator=(MArray<T, D>(_array.get(), 0, size));\n }\n return *this;\n }\n\n MMArray & operator=(MMArray &&mma)\n {\n if (&mma != this) {\n MArray<T, D>::operator=(std::forward<MMArray<T, D>>(mma));\n _array = std::move(mma._array);\n }\n return *this;\n }\n \n inline void resize(const std::size_t size[D])\n {\n std::size_t total = size[0];\n for (std::size_t i = 1; i < D; ++i)\n total *= size[i];\n _array.reset(new T[total]); \/\/ Be aware: data is LOST!\n MArray<T, D>::operator=(MArray<T, D>(_array.get(), 0, size));\n }\n\nprivate:\n std::unique_ptr<T[]> _array;\n};\n\n#endif \/* multiple_array_hpp *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef IMQUE_QUEUE_IMPL_HH\n#define IMQUE_QUEUE_IMPL_HH\n\n#include \"..\/ipc\/shared_memory.hh\" \/\/ XXX: 最終的には無くす\n#include \"..\/block_allocator.hh\"\n#include \"..\/atomic\/atomic.hh\"\n\n#include <inttypes.h>\n#include <string.h>\n\nnamespace imque {\n class QueueImpl {\n struct Entry {\n uint32_t state:2;\n uint32_t value:30;\n\n enum STATE {\n FREE = 0,\n USED = 1\n };\n }__attribute__((__packed__));\n\n struct Stat {\n uint32_t overflowed_count;\n };\n\n struct Header {\n uint32_t version; \/\/ XXX: name\n volatile uint32_t read_pos;\n volatile uint32_t write_pos;\n Stat stat;\n uint32_t entry_count;\n Entry entries[0];\n \n uint32_t next_read_pos() const { return (read_pos+1)%entry_count; }\n uint32_t next_write_pos() const { return (write_pos+1)%entry_count; }\n };\n\n public:\n QueueImpl(size_t entry_count, SharedMemory& shm)\n : que_(shm.ptr<Header>()),\n alc_(shm.ptr<void>(que_size(entry_count)), shm.size()-que_size(entry_count)) {\n if(shm) {\n que_->entry_count = entry_count;\n }\n }\n\n operator bool() const { return alc_; }\n \n void init() {\n alc_.init();\n \n que_->version = 0;\n que_->read_pos = 0;\n que_->write_pos = 0;\n que_->stat.overflowed_count = 0;\n memset(que_->entries, 0, sizeof(Entry)*que_->entry_count);\n }\n\n bool enq(const void* data, size_t size) {\n if(isFull()) {\n atomic::add_and_fetch(&que_->stat.overflowed_count, 1);\n return false;\n }\n \n uint32_t alloc_id = alc_.allocate(sizeof(size_t) + size);\n if(alloc_id == 0) {\n atomic::add_and_fetch(&que_->stat.overflowed_count, 1);\n return false;\n }\n\n alc_.ptr<size_t>(alloc_id)[0] = size;\n memcpy(alc_.ptr<void>(alloc_id, sizeof(size_t)), data, size);\n\n if(enq_impl(alloc_id) == false) {\n atomic::add_and_fetch(&que_->stat.overflowed_count, 1);\n alc_.release(alloc_id);\n return false;\n }\n \n return true;\n }\n\n bool deq(std::string& buf) {\n if(isEmpty()) {\n return false;\n }\n\n uint32_t alloc_id = deq_impl();\n if(alloc_id == 0) {\n return false;\n }\n\n size_t size = alc_.ptr<size_t>(alloc_id)[0];\n char* data = alc_.ptr<char>(alloc_id, sizeof(size_t));\n buf.assign(data, size);\n \n assert(alc_.release(alloc_id));\n \n return true;\n }\n\n bool isEmpty() const { return que_->read_pos == que_->write_pos; }\n bool isFull() const { return que_->read_pos == que_->next_write_pos(); }\n\n static size_t calc_need_byte_size(size_t entry_count, size_t data_size) {\n return que_size(entry_count) + dat_size(data_size);\n }\n\n size_t overflowedCount() const { return que_->stat.overflowed_count; }\n void resetOverflowedCount() { que_->stat.overflowed_count = 0; }\n\n private:\n bool enq_impl(uint32_t value) {\n uint32_t curr_read = que_->read_pos;\n uint32_t curr_write = que_->write_pos;\n uint32_t next_write = (curr_write+1) % que_->entry_count;\n \n if(curr_read == next_write) {\n atomic::add_and_fetch(&que_->stat.overflowed_count, 1);\n return false;\n }\n \n Entry* pe = &que_->entries[curr_write];\n Entry e = *pe;\n if(e.state != Entry::FREE) {\n atomic::compare_and_swap(&que_->write_pos, curr_write, next_write);\n return enq_impl(value);\n }\n\n Entry new_e = {Entry::USED, value};\n if(atomic::compare_and_swap(pe, e, new_e) == false) {\n return enq_impl(value);\n }\n \n atomic::compare_and_swap(&que_->write_pos, curr_write, next_write); \n return true;\n }\n\n uint32_t deq_impl() {\n uint32_t curr_read = que_->read_pos;\n uint32_t curr_write = que_->write_pos;\n uint32_t next_read = (curr_read+1) % que_->entry_count;\n \n if(curr_read == curr_write) {\n return 0;\n }\n\n Entry* pe = &que_->entries[curr_read];\n Entry e = *pe;\n if(e.state == Entry::FREE) {\n atomic::compare_and_swap(&que_->read_pos, curr_read, next_read);\n return deq_impl();\n }\n\n uint32_t new_version = atomic::fetch_and_add(&que_->version, 1);\n Entry new_e = {Entry::FREE, new_version};\n if(atomic::compare_and_swap(pe, e, new_e) == false) {\n return deq_impl();\n }\n \n atomic::compare_and_swap(&que_->read_pos, curr_read, next_read);\n return e.value;\n }\n\n static size_t que_size(size_t entry_count) {\n return sizeof(Header) + sizeof(Entry)*entry_count;\n }\n \n static size_t dat_size(size_t data_size) {\n return Allocator::calc_need_byte_size(data_size);\n }\n\n private:\n Header* que_;\n BlockAllocator alc_;\n };\n}\n\n#endif \n<commit_msg>volatile対応<commit_after>#ifndef IMQUE_QUEUE_IMPL_HH\n#define IMQUE_QUEUE_IMPL_HH\n\n#include \"..\/ipc\/shared_memory.hh\" \/\/ XXX: 最終的には無くす\n#include \"..\/block_allocator.hh\"\n#include \"..\/atomic\/atomic.hh\"\n\n#include <inttypes.h>\n#include <string.h>\n\nnamespace imque {\n class QueueImpl {\n struct Entry {\n uint32_t state:2;\n uint32_t value:30;\n\n enum STATE {\n FREE = 0,\n USED = 1\n };\n }__attribute__((__packed__));\n\n struct Stat {\n uint32_t overflowed_count;\n };\n\n struct Header {\n volatile uint32_t version; \/\/ XXX: name\n volatile uint32_t read_pos;\n volatile uint32_t write_pos;\n Stat stat;\n uint32_t entry_count;\n Entry entries[0];\n \n uint32_t next_read_pos() const { return (read_pos+1)%entry_count; }\n uint32_t next_write_pos() const { return (write_pos+1)%entry_count; }\n };\n\n public:\n QueueImpl(size_t entry_count, SharedMemory& shm)\n : que_(shm.ptr<Header>()),\n alc_(shm.ptr<void>(que_size(entry_count)), shm.size()-que_size(entry_count)) {\n if(shm) {\n que_->entry_count = entry_count;\n }\n }\n\n operator bool() const { return alc_; }\n \n void init() {\n alc_.init();\n \n que_->version = 0;\n que_->read_pos = 0;\n que_->write_pos = 0;\n que_->stat.overflowed_count = 0;\n memset(que_->entries, 0, sizeof(Entry)*que_->entry_count);\n }\n\n bool enq(const void* data, size_t size) {\n if(isFull()) {\n atomic::add_and_fetch(&que_->stat.overflowed_count, 1);\n return false;\n }\n \n uint32_t alloc_id = alc_.allocate(sizeof(size_t) + size);\n if(alloc_id == 0) {\n atomic::add_and_fetch(&que_->stat.overflowed_count, 1);\n return false;\n }\n\n alc_.ptr<size_t>(alloc_id)[0] = size;\n memcpy(alc_.ptr<void>(alloc_id, sizeof(size_t)), data, size);\n\n if(enq_impl(alloc_id) == false) {\n atomic::add_and_fetch(&que_->stat.overflowed_count, 1);\n alc_.release(alloc_id);\n return false;\n }\n \n return true;\n }\n\n bool deq(std::string& buf) {\n if(isEmpty()) {\n return false;\n }\n\n uint32_t alloc_id = deq_impl();\n if(alloc_id == 0) {\n return false;\n }\n\n size_t size = alc_.ptr<size_t>(alloc_id)[0];\n char* data = alc_.ptr<char>(alloc_id, sizeof(size_t));\n buf.assign(data, size);\n \n assert(alc_.release(alloc_id));\n \n return true;\n }\n\n bool isEmpty() const { return que_->read_pos == que_->write_pos; }\n bool isFull() const { return que_->read_pos == que_->next_write_pos(); }\n\n static size_t calc_need_byte_size(size_t entry_count, size_t data_size) {\n return que_size(entry_count) + dat_size(data_size);\n }\n\n size_t overflowedCount() const { return que_->stat.overflowed_count; }\n void resetOverflowedCount() { que_->stat.overflowed_count = 0; }\n\n private:\n bool enq_impl(uint32_t value) {\n uint32_t curr_read = que_->read_pos;\n uint32_t curr_write = que_->write_pos;\n uint32_t next_write = (curr_write+1) % que_->entry_count;\n \n if(curr_read == next_write) {\n atomic::add_and_fetch(&que_->stat.overflowed_count, 1);\n return false;\n }\n \n Entry* pe = &que_->entries[curr_write];\n Entry e = *pe;\n if(e.state != Entry::FREE) {\n atomic::compare_and_swap(&que_->write_pos, curr_write, next_write);\n return enq_impl(value);\n }\n\n Entry new_e = {Entry::USED, value};\n if(atomic::compare_and_swap(pe, e, new_e) == false) {\n return enq_impl(value);\n }\n \n atomic::compare_and_swap(&que_->write_pos, curr_write, next_write); \n return true;\n }\n\n uint32_t deq_impl() {\n uint32_t curr_read = que_->read_pos;\n uint32_t curr_write = que_->write_pos;\n uint32_t next_read = (curr_read+1) % que_->entry_count;\n \n if(curr_read == curr_write) {\n return 0;\n }\n\n Entry* pe = &que_->entries[curr_read];\n Entry e = *pe;\n if(e.state == Entry::FREE) {\n atomic::compare_and_swap(&que_->read_pos, curr_read, next_read);\n return deq_impl();\n }\n\n uint32_t new_version = atomic::fetch_and_add(&que_->version, 1);\n Entry new_e = {Entry::FREE, new_version};\n if(atomic::compare_and_swap(pe, e, new_e) == false) {\n return deq_impl();\n }\n \n atomic::compare_and_swap(&que_->read_pos, curr_read, next_read);\n return e.value;\n }\n\n static size_t que_size(size_t entry_count) {\n return sizeof(Header) + sizeof(Entry)*entry_count;\n }\n \n static size_t dat_size(size_t data_size) {\n return Allocator::calc_need_byte_size(data_size);\n }\n\n private:\n Header* que_;\n BlockAllocator alc_;\n };\n}\n\n#endif \n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004 Justin Karneges\n * Copyright (C) 2004 Brad Hards <bradh@frogmouth.net>\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\/\n#include \"qcaprovider.h\"\n#include <qstringlist.h>\n#include <gcrypt.h>\n#include <iostream>\n\nvoid check_error( gcry_error_t err )\n{\n if ( GPG_ERR_NO_ERROR != err ) {\n\tstd::cout << \"Failure: \" ;\n\t\tstd::cout << gcry_strsource(err) << \"\/\";\n\t\tstd::cout << gcry_strerror(err) << std::endl;\n }\n}\n\nclass gcryHashContext : public QCA::HashContext\n{\npublic:\n gcryHashContext(QCA::Provider *p, const QString &type) : QCA::HashContext(p, type) {};\n\n void clear()\n {\n\tgcry_md_reset( context );\n }\n \n void update(const QSecureArray &a)\n {\n\tgcry_md_write( context, a.data(), a.size() );\n }\n \n QSecureArray final()\n {\n\tunsigned char *md;\n\tQSecureArray a( gcry_md_get_algo_dlen( hashAlgorithm ) );\n\tmd = gcry_md_read( context, hashAlgorithm );\n\tmemcpy( a.data(), md, a.size() );\n\treturn a;\n }\n \nprotected:\n gcry_md_hd_t context;\n gcry_error_t err;\n int hashAlgorithm;\n};\t\n\nclass SHA1Context : public gcryHashContext\n{\npublic:\n\tSHA1Context(QCA::Provider *p) : gcryHashContext(p, \"sha1\")\n\t{\n\t\tgcry_check_version(\"GCRYPT_VERSION\");\n\t\thashAlgorithm = GCRY_MD_SHA1;\n\t\terr = gcry_md_open( &context, hashAlgorithm, 0 );\n\t\tif ( GPG_ERR_NO_ERROR != err ) {\n\t\t\tstd::cout << \"Failure: \" ;\n\t\t\tstd::cout << gcry_strsource(err) << \"\/\";\n\t\t\tstd::cout << gcry_strerror(err) << std::endl;\n\t\t}\n\t}\n\n\t~SHA1Context()\n\t{\n\t\tgcry_md_close( context );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA1Context(*this);\n\t}\n};\n\n\nclass SHA256Context : public gcryHashContext\n{\npublic:\n SHA256Context(QCA::Provider *p) : gcryHashContext(p, \"sha256\")\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\thashAlgorithm = GCRY_MD_SHA256;\n\terr = gcry_md_open( &context, hashAlgorithm, 0 );\n\tif ( GPG_ERR_NO_ERROR != err ) {\n\t std::cout << \"Failure: \" ;\n\t std::cout << gcry_strsource(err) << \"\/\";\n\t std::cout << gcry_strerror(err) << std::endl;\n\t}\n }\n\t\n ~SHA256Context()\n {\n\tgcry_md_close( context );\n }\n\n Context *clone() const\n {\n\treturn new SHA256Context(*this);\n }\n};\n\nclass SHA384Context : public gcryHashContext\n{\npublic:\n\tSHA384Context(QCA::Provider *p) : gcryHashContext(p, \"sha384\")\n\t{\n\t\tgcry_check_version(\"GCRYPT_VERSION\");\n\t\thashAlgorithm = GCRY_MD_SHA384;\n\t\terr = gcry_md_open( &context, hashAlgorithm, 0 );\n\t\tif ( GPG_ERR_NO_ERROR != err ) {\n\t\t\tstd::cout << \"Failure: \" ;\n\t\t\tstd::cout << gcry_strsource(err) << \"\/\";\n\t\t\tstd::cout << gcry_strerror(err) << std::endl;\n\t\t}\n\t}\n\n\t~SHA384Context()\n\t{\n\t\tgcry_md_close( context );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA384Context(*this);\n\t}\n};\n\n\n\n\nclass SHA512Context : public gcryHashContext\n{\npublic:\n\tSHA512Context(QCA::Provider *p) : gcryHashContext(p, \"sha512\")\n\t{\n\t\tgcry_check_version(\"GCRYPT_VERSION\");\n\t\thashAlgorithm = GCRY_MD_SHA512;\n\t\terr = gcry_md_open( &context, hashAlgorithm, 0 );\n\t\tif ( GPG_ERR_NO_ERROR != err ) {\n\t\t\tstd::cout << \"Failure: \" ;\n\t\t\tstd::cout << gcry_strsource(err) << \"\/\";\n\t\t\tstd::cout << gcry_strerror(err) << std::endl;\n\t\t}\n\t}\n\n\t~SHA512Context()\n\t{\n\t\tgcry_md_close( context );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA512Context(*this);\n\t}\n};\n\nstatic int gcry_mode( QCA::CipherContext::Mode mode )\n{\n int retmode;\n switch (mode)\n {\n case QCA::CipherContext::ECB :\n\tretmode = GCRY_CIPHER_MODE_ECB;\n\tbreak;\n case QCA::CipherContext::CBC :\n\tretmode = GCRY_CIPHER_MODE_CBC;\n\tbreak;\n case QCA::CipherContext::CFB :\n\tretmode = GCRY_CIPHER_MODE_CFB;\n\tbreak;\n default:\n\tretmode = GCRY_CIPHER_MODE_NONE;\n }\n return retmode;\n};\n\n\nclass gcryCipherContext : public QCA::CipherContext\n{\npublic:\n gcryCipherContext(QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type) {}\n\n void setup(const QCA::SymmetricKey &key,\n\t QCA::CipherContext::Mode m,\n\t QCA::Direction dir,\n\t const QCA::InitializationVector &iv)\n {\n\tm_direction = dir;\n\terr = gcry_cipher_open( &context, cryptoAlgorithm, gcry_mode(m), 0 );\n\tcheck_error( err );\n\terr = gcry_cipher_setkey( context, key.data(), key.size() );\n\tcheck_error( err );\n\terr = gcry_cipher_setiv( context, iv.data(), iv.size() );\n\tcheck_error( err ); \n }\n\n int blockSize() const\n {\n\tint blockSize;\n\tgcry_cipher_algo_info( cryptoAlgorithm, GCRYCTL_GET_BLKLEN, 0, (size_t*)&blockSize );\n\treturn blockSize;\n }\n \n bool update(const QSecureArray &in, QSecureArray *out)\n {\n\tQSecureArray result( in.size() );\n\tif (QCA::Encode == m_direction) {\n\t err = gcry_cipher_encrypt( context, (unsigned char*)result.data(), result.size(), (unsigned char*)in.data(), in.size() );\n\t} else {\n\t err = gcry_cipher_decrypt( context, (unsigned char*)result.data(), result.size(), (unsigned char*)in.data(), in.size() );\n\t}\n\tcheck_error(err );\n\tresult.resize( in.size() );\n\t*out = result;\n\treturn true;\n }\n \n bool final(QSecureArray *out)\n {\n\t*out = QSecureArray();\n\treturn true;\n }\n\nprotected:\n gcry_cipher_hd_t context;\n gcry_error_t err;\n int cryptoAlgorithm;\n QCA::Direction m_direction;\n};\n\nclass AES128Context : public gcryCipherContext\n{\npublic:\n AES128Context(QCA::Provider *p) : gcryCipherContext( p, \"aes128\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_AES128;\n }\n\t\n Context *clone() const\n {\n\treturn new AES128Context( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\t\/\/ Must be 128 bits\n\treturn QCA::KeyLength( 16, 16, 1);\n }\n \n\n};\n\nclass AES192Context : public gcryCipherContext\n{\npublic:\n AES192Context(QCA::Provider *p) : gcryCipherContext( p, \"aes192\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_AES192;\n }\n\t\n Context *clone() const\n {\n\treturn new AES192Context( *this );\n }\n\n QCA::KeyLength keyLength() const\n {\n\t\/\/ Must be 192 bits\n\treturn QCA::KeyLength( 24, 24, 1);\n }\n};\n\n\nclass AES256Context : public gcryCipherContext\n{\npublic:\n AES256Context(QCA::Provider *p) : gcryCipherContext( p, \"aes256\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_AES256;\n }\n\t\n Context *clone() const\n {\n\treturn new AES256Context( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\t\/\/ Must be 256 bits\n\treturn QCA::KeyLength( 32, 32, 1);\n }\n};\n\n\nclass BlowFishContext : public gcryCipherContext\n{\npublic:\n BlowFishContext(QCA::Provider *p) : gcryCipherContext( p, \"blowfish\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_BLOWFISH;\n }\n\t\n Context *clone() const\n {\n\treturn new BlowFishContext( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\t\/\/ Don't know - TODO\n\treturn QCA::KeyLength( 1, 32, 1);\n }\n};\n\nclass TripleDESContext : public gcryCipherContext\n{\npublic:\n TripleDESContext(QCA::Provider *p) : gcryCipherContext( p, \"tripledes\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_3DES;\n }\n\t\n Context *clone() const\n {\n\treturn new TripleDESContext( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\treturn QCA::KeyLength( 24, 24, 1);\n }\n};\n\n\nclass gcryptProvider : public QCA::Provider\n{\npublic:\n\tvoid init()\n\t{\n\t}\n\n\tQString name() const\n\t{\n\t\treturn \"qca-gcrypt\";\n\t}\n\n\tQStringList features() const\n\t{\n\t\tQStringList list;\n\t\tlist += \"sha1\";\n\t\tlist += \"sha256\";\n\t\tlist += \"sha384\";\n\t\tlist += \"sha512\";\n\t\tlist += \"aes128\";\n\t\tlist += \"aes192\";\n\t\tlist += \"aes256\";\n\t\tlist += \"blowfish\";\n\t\tlist += \"tripledes\";\n\t\treturn list;\n\t}\n\n\tContext *createContext(const QString &type)\n\t{\n\t\tif ( type == \"sha1\" )\n\t\t\treturn new SHA1Context( this );\n\t\telse if ( type == \"sha256\" )\n\t\t\treturn new SHA256Context( this );\n\t\telse if ( type == \"sha384\" )\n\t\t\treturn new SHA384Context( this );\n\t\telse if ( type == \"sha512\" )\n\t\t\treturn new SHA512Context( this );\n\t\telse if ( type == \"aes128\" )\n\t\t\treturn new AES128Context( this );\n\t\telse if ( type == \"aes192\" )\n\t\t\treturn new AES192Context( this );\n\t\telse if ( type == \"aes256\" )\n\t\t\treturn new AES256Context( this );\n\t\telse if ( type == \"blowfish\" )\n\t\t\treturn new BlowFishContext( this );\n\t\telse if ( type == \"tripledes\" )\n\t\t\treturn new TripleDESContext( this );\n\t\telse\n\t\t\treturn 0;\n\t}\n};\n\nQCA_EXPORT_PLUGIN(gcryptProvider);\n<commit_msg>DES provider<commit_after>\/*\n * Copyright (C) 2004 Justin Karneges\n * Copyright (C) 2004 Brad Hards <bradh@frogmouth.net>\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\/\n#include \"qcaprovider.h\"\n#include <qstringlist.h>\n#include <gcrypt.h>\n#include <iostream>\n\nvoid check_error( gcry_error_t err )\n{\n if ( GPG_ERR_NO_ERROR != err ) {\n\tstd::cout << \"Failure: \" ;\n\t\tstd::cout << gcry_strsource(err) << \"\/\";\n\t\tstd::cout << gcry_strerror(err) << std::endl;\n }\n}\n\nclass gcryHashContext : public QCA::HashContext\n{\npublic:\n gcryHashContext(QCA::Provider *p, const QString &type) : QCA::HashContext(p, type) {};\n\n void clear()\n {\n\tgcry_md_reset( context );\n }\n \n void update(const QSecureArray &a)\n {\n\tgcry_md_write( context, a.data(), a.size() );\n }\n \n QSecureArray final()\n {\n\tunsigned char *md;\n\tQSecureArray a( gcry_md_get_algo_dlen( hashAlgorithm ) );\n\tmd = gcry_md_read( context, hashAlgorithm );\n\tmemcpy( a.data(), md, a.size() );\n\treturn a;\n }\n \nprotected:\n gcry_md_hd_t context;\n gcry_error_t err;\n int hashAlgorithm;\n};\t\n\nclass SHA1Context : public gcryHashContext\n{\npublic:\n\tSHA1Context(QCA::Provider *p) : gcryHashContext(p, \"sha1\")\n\t{\n\t\tgcry_check_version(\"GCRYPT_VERSION\");\n\t\thashAlgorithm = GCRY_MD_SHA1;\n\t\terr = gcry_md_open( &context, hashAlgorithm, 0 );\n\t\tif ( GPG_ERR_NO_ERROR != err ) {\n\t\t\tstd::cout << \"Failure: \" ;\n\t\t\tstd::cout << gcry_strsource(err) << \"\/\";\n\t\t\tstd::cout << gcry_strerror(err) << std::endl;\n\t\t}\n\t}\n\n\t~SHA1Context()\n\t{\n\t\tgcry_md_close( context );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA1Context(*this);\n\t}\n};\n\n\nclass SHA256Context : public gcryHashContext\n{\npublic:\n SHA256Context(QCA::Provider *p) : gcryHashContext(p, \"sha256\")\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\thashAlgorithm = GCRY_MD_SHA256;\n\terr = gcry_md_open( &context, hashAlgorithm, 0 );\n\tif ( GPG_ERR_NO_ERROR != err ) {\n\t std::cout << \"Failure: \" ;\n\t std::cout << gcry_strsource(err) << \"\/\";\n\t std::cout << gcry_strerror(err) << std::endl;\n\t}\n }\n\t\n ~SHA256Context()\n {\n\tgcry_md_close( context );\n }\n\n Context *clone() const\n {\n\treturn new SHA256Context(*this);\n }\n};\n\nclass SHA384Context : public gcryHashContext\n{\npublic:\n\tSHA384Context(QCA::Provider *p) : gcryHashContext(p, \"sha384\")\n\t{\n\t\tgcry_check_version(\"GCRYPT_VERSION\");\n\t\thashAlgorithm = GCRY_MD_SHA384;\n\t\terr = gcry_md_open( &context, hashAlgorithm, 0 );\n\t\tif ( GPG_ERR_NO_ERROR != err ) {\n\t\t\tstd::cout << \"Failure: \" ;\n\t\t\tstd::cout << gcry_strsource(err) << \"\/\";\n\t\t\tstd::cout << gcry_strerror(err) << std::endl;\n\t\t}\n\t}\n\n\t~SHA384Context()\n\t{\n\t\tgcry_md_close( context );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA384Context(*this);\n\t}\n};\n\n\n\n\nclass SHA512Context : public gcryHashContext\n{\npublic:\n\tSHA512Context(QCA::Provider *p) : gcryHashContext(p, \"sha512\")\n\t{\n\t\tgcry_check_version(\"GCRYPT_VERSION\");\n\t\thashAlgorithm = GCRY_MD_SHA512;\n\t\terr = gcry_md_open( &context, hashAlgorithm, 0 );\n\t\tif ( GPG_ERR_NO_ERROR != err ) {\n\t\t\tstd::cout << \"Failure: \" ;\n\t\t\tstd::cout << gcry_strsource(err) << \"\/\";\n\t\t\tstd::cout << gcry_strerror(err) << std::endl;\n\t\t}\n\t}\n\n\t~SHA512Context()\n\t{\n\t\tgcry_md_close( context );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA512Context(*this);\n\t}\n};\n\nstatic int gcry_mode( QCA::CipherContext::Mode mode )\n{\n int retmode;\n switch (mode)\n {\n case QCA::CipherContext::ECB :\n\tretmode = GCRY_CIPHER_MODE_ECB;\n\tbreak;\n case QCA::CipherContext::CBC :\n\tretmode = GCRY_CIPHER_MODE_CBC;\n\tbreak;\n case QCA::CipherContext::CFB :\n\tretmode = GCRY_CIPHER_MODE_CFB;\n\tbreak;\n default:\n\tretmode = GCRY_CIPHER_MODE_NONE;\n }\n return retmode;\n};\n\n\nclass gcryCipherContext : public QCA::CipherContext\n{\npublic:\n gcryCipherContext(QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type) {}\n\n void setup(const QCA::SymmetricKey &key,\n\t QCA::CipherContext::Mode m,\n\t QCA::Direction dir,\n\t const QCA::InitializationVector &iv)\n {\n\tm_direction = dir;\n\terr = gcry_cipher_open( &context, cryptoAlgorithm, gcry_mode(m), 0 );\n\tcheck_error( err );\n\terr = gcry_cipher_setkey( context, key.data(), key.size() );\n\tcheck_error( err );\n\terr = gcry_cipher_setiv( context, iv.data(), iv.size() );\n\tcheck_error( err ); \n }\n\n unsigned int blockSize() const\n {\n\tunsigned int blockSize;\n\tgcry_cipher_algo_info( cryptoAlgorithm, GCRYCTL_GET_BLKLEN, 0, (size_t*)&blockSize );\n\treturn blockSize;\n }\n \n bool update(const QSecureArray &in, QSecureArray *out)\n {\n\tQSecureArray result( in.size() );\n\tif (QCA::Encode == m_direction) {\n\t err = gcry_cipher_encrypt( context, (unsigned char*)result.data(), result.size(), (unsigned char*)in.data(), in.size() );\n\t} else {\n\t err = gcry_cipher_decrypt( context, (unsigned char*)result.data(), result.size(), (unsigned char*)in.data(), in.size() );\n\t}\n\tcheck_error(err );\n\tresult.resize( in.size() );\n\t*out = result;\n\treturn true;\n }\n \n bool final(QSecureArray *out)\n {\n\t*out = QSecureArray();\n\treturn true;\n }\n\nprotected:\n gcry_cipher_hd_t context;\n gcry_error_t err;\n int cryptoAlgorithm;\n QCA::Direction m_direction;\n};\n\nclass AES128Context : public gcryCipherContext\n{\npublic:\n AES128Context(QCA::Provider *p) : gcryCipherContext( p, \"aes128\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_AES128;\n }\n\t\n Context *clone() const\n {\n\treturn new AES128Context( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\t\/\/ Must be 128 bits\n\treturn QCA::KeyLength( 16, 16, 1);\n }\n \n\n};\n\nclass AES192Context : public gcryCipherContext\n{\npublic:\n AES192Context(QCA::Provider *p) : gcryCipherContext( p, \"aes192\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_AES192;\n }\n\t\n Context *clone() const\n {\n\treturn new AES192Context( *this );\n }\n\n QCA::KeyLength keyLength() const\n {\n\t\/\/ Must be 192 bits\n\treturn QCA::KeyLength( 24, 24, 1);\n }\n};\n\n\nclass AES256Context : public gcryCipherContext\n{\npublic:\n AES256Context(QCA::Provider *p) : gcryCipherContext( p, \"aes256\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_AES256;\n }\n\t\n Context *clone() const\n {\n\treturn new AES256Context( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\t\/\/ Must be 256 bits\n\treturn QCA::KeyLength( 32, 32, 1);\n }\n};\n\n\nclass BlowFishContext : public gcryCipherContext\n{\npublic:\n BlowFishContext(QCA::Provider *p) : gcryCipherContext( p, \"blowfish\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_BLOWFISH;\n }\n\t\n Context *clone() const\n {\n\treturn new BlowFishContext( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\t\/\/ Don't know - TODO\n\treturn QCA::KeyLength( 1, 32, 1);\n }\n};\n\nclass TripleDESContext : public gcryCipherContext\n{\npublic:\n TripleDESContext(QCA::Provider *p) : gcryCipherContext( p, \"tripledes\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_3DES;\n }\n\t\n Context *clone() const\n {\n\treturn new TripleDESContext( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\treturn QCA::KeyLength( 24, 24, 1);\n }\n};\n\nclass DESContext : public gcryCipherContext\n{\npublic:\n DESContext(QCA::Provider *p) : gcryCipherContext( p, \"des\" )\n {\n\tgcry_check_version(\"GCRYPT_VERSION\");\n\tcryptoAlgorithm = GCRY_CIPHER_DES;\n }\n\t\n Context *clone() const\n {\n\treturn new DESContext( *this );\n }\n \n QCA::KeyLength keyLength() const\n {\n\treturn QCA::KeyLength( 8, 8, 1);\n }\n};\n\n\nclass gcryptProvider : public QCA::Provider\n{\npublic:\n\tvoid init()\n\t{\n\t}\n\n\tQString name() const\n\t{\n\t\treturn \"qca-gcrypt\";\n\t}\n\n\tQStringList features() const\n\t{\n\t\tQStringList list;\n\t\tlist += \"sha1\";\n\t\tlist += \"sha256\";\n\t\tlist += \"sha384\";\n\t\tlist += \"sha512\";\n\t\tlist += \"aes128\";\n\t\tlist += \"aes192\";\n\t\tlist += \"aes256\";\n\t\tlist += \"blowfish\";\n\t\tlist += \"tripledes\";\n\t\tlist += \"des\";\n\t\treturn list;\n\t}\n\n\tContext *createContext(const QString &type)\n\t{\n\t\tif ( type == \"sha1\" )\n\t\t\treturn new SHA1Context( this );\n\t\telse if ( type == \"sha256\" )\n\t\t\treturn new SHA256Context( this );\n\t\telse if ( type == \"sha384\" )\n\t\t\treturn new SHA384Context( this );\n\t\telse if ( type == \"sha512\" )\n\t\t\treturn new SHA512Context( this );\n\t\telse if ( type == \"aes128\" )\n\t\t\treturn new AES128Context( this );\n\t\telse if ( type == \"aes192\" )\n\t\t\treturn new AES192Context( this );\n\t\telse if ( type == \"aes256\" )\n\t\t\treturn new AES256Context( this );\n\t\telse if ( type == \"blowfish\" )\n\t\t\treturn new BlowFishContext( this );\n\t\telse if ( type == \"tripledes\" )\n\t\t\treturn new TripleDESContext( this );\n\t\telse if ( type == \"des\" )\n\t\t\treturn new DESContext( this );\n\t\telse\n\t\t\treturn 0;\n\t}\n};\n\nQCA_EXPORT_PLUGIN(gcryptProvider);\n<|endoftext|>"} {"text":"<commit_before>\/* Implementation of an accelerator datapath that uses a private scratchpad for\n * local memory.\n *\/\n\n#include <string>\n\n#include \"ScratchpadDatapath.h\"\n\nScratchpadDatapath::ScratchpadDatapath(std::string bench,\n std::string trace_file,\n std::string config_file)\n : BaseDatapath(bench, trace_file, config_file) {\n std::cerr << \"-------------------------------\" << std::endl;\n std::cerr << \" Setting ScratchPad \" << std::endl;\n std::cerr << \"-------------------------------\" << std::endl;\n scratchpad = new Scratchpad(1, cycleTime);\n scratchpadCanService = true;\n}\n\nScratchpadDatapath::~ScratchpadDatapath() { delete scratchpad; }\n\nvoid ScratchpadDatapath::globalOptimizationPass() {\n \/\/ Node removals must come first.\n removePhiNodes();\n \/*memoryAmibguation() should execute after removeInductionDependence() because\n * it needs induction_nodes.*\/\n removeInductionDependence();\n memoryAmbiguation();\n \/\/ Base address must be initialized next.\n initBaseAddress();\n completePartition();\n scratchpadPartition();\n loopFlatten();\n loopUnrolling();\n removeSharedLoads();\n storeBuffer();\n removeRepeatedStores();\n treeHeightReduction();\n \/\/ Must do loop pipelining last; after all the data\/control dependences are\n \/\/ fixed\n loopPipelining();\n}\n\n\/* First, compute all base addresses, then check each node to make sure that\n * each entry is valid.\n *\/\nvoid ScratchpadDatapath::initBaseAddress() {\n BaseDatapath::initBaseAddress();\n std::unordered_map<std::string, unsigned> comp_part_config;\n readCompletePartitionConfig(comp_part_config);\n std::unordered_map<std::string, partitionEntry> part_config;\n readPartitionConfig(part_config);\n\n for (auto it = nodeToLabel.begin(); it != nodeToLabel.end(); ++it) {\n unsigned node_id = it->first;\n std::string part_name = nodeToLabel[node_id];\n if (part_config.find(part_name) == part_config.end() &&\n comp_part_config.find(part_name) == comp_part_config.end()) {\n std::cerr << \"Unknown partition : \" << part_name << \"@inst: \" << node_id\n << std::endl;\n exit(-1);\n }\n }\n}\n\n\/*\n * Modify scratchpad\n *\/\nvoid ScratchpadDatapath::completePartition() {\n std::unordered_map<std::string, unsigned> comp_part_config;\n if (!readCompletePartitionConfig(comp_part_config))\n return;\n\n std::cerr << \"-------------------------------\" << std::endl;\n std::cerr << \" Mem to Reg Conv \" << std::endl;\n std::cerr << \"-------------------------------\" << std::endl;\n\n for (auto it = comp_part_config.begin(); it != comp_part_config.end(); ++it) {\n std::string base_addr = it->first;\n unsigned size = it->second;\n\n registers.createRegister(base_addr, size, cycleTime);\n }\n}\n\n\/*\n * Modify: baseAddress\n *\/\nvoid ScratchpadDatapath::scratchpadPartition() {\n \/\/ read the partition config file to get the address range\n \/\/ <base addr, <type, part_factor> >\n std::unordered_map<std::string, partitionEntry> part_config;\n if (!readPartitionConfig(part_config))\n return;\n\n std::cerr << \"-------------------------------\" << std::endl;\n std::cerr << \" ScratchPad Partition \" << std::endl;\n std::cerr << \"-------------------------------\" << std::endl;\n std::string bn(benchName);\n\n std::unordered_map<unsigned, MemAccess> address;\n initAddress(address);\n \/\/ set scratchpad\n for (auto it = part_config.begin(); it != part_config.end(); ++it) {\n std::string base_addr = it->first;\n unsigned size = it->second.array_size; \/\/ num of bytes\n unsigned p_factor = it->second.part_factor;\n unsigned wordsize = it->second.wordsize; \/\/ in bytes\n unsigned per_size = ceil(((float)size) \/ p_factor);\n\n for (unsigned i = 0; i < p_factor; i++) {\n ostringstream oss;\n oss << base_addr << \"-\" << i;\n scratchpad->setScratchpad(oss.str(), per_size, wordsize);\n }\n }\n\n for (unsigned node_id = 0; node_id < numTotalNodes; node_id++) {\n if (!is_memory_op(microop.at(node_id)))\n continue;\n\n if (nodeToLabel.find(node_id) == nodeToLabel.end())\n continue;\n std::string base_label = nodeToLabel[node_id];\n long long int base_addr = arrayBaseAddress[base_label];\n\n auto part_it = part_config.find(base_label);\n if (part_it != part_config.end()) {\n std::string p_type = part_it->second.type;\n assert((!p_type.compare(\"block\")) || (!p_type.compare(\"cyclic\")));\n\n unsigned num_of_elements = part_it->second.array_size;\n unsigned p_factor = part_it->second.part_factor;\n long long int abs_addr = address[node_id].vaddr;\n unsigned data_size = address[node_id].size \/ 8; \/\/ in bytes\n unsigned rel_addr = (abs_addr - base_addr) \/ data_size;\n if (!p_type.compare(\"block\")) \/\/ block partition\n {\n ostringstream oss;\n unsigned num_of_elements_in_2 = next_power_of_two(num_of_elements);\n oss << base_label << \"-\"\n << (int)(rel_addr \/ ceil(num_of_elements_in_2 \/ p_factor));\n nodeToLabel[node_id] = oss.str();\n } else \/\/ cyclic partition\n {\n ostringstream oss;\n oss << base_label << \"-\" << (rel_addr) % p_factor;\n nodeToLabel[node_id] = oss.str();\n }\n }\n }\n writeBaseAddress();\n}\n\nvoid ScratchpadDatapath::setGraphForStepping() {\n BaseDatapath::setGraphForStepping();\n timeBeforeNodeExecution.assign(numTotalNodes, 0);\n}\nbool ScratchpadDatapath::step() {\n if (!BaseDatapath::step()) {\n scratchpad->step();\n scratchpadCanService = true;\n return false;\n } else {\n return true;\n }\n}\n\nvoid ScratchpadDatapath::stepExecutingQueue() {\n auto it = executingQueue.begin();\n int index = 0;\n while (it != executingQueue.end()) {\n unsigned node_id = *it;\n if (is_memory_op(microop.at(node_id))) {\n std::string node_part = nodeToLabel[node_id];\n if (registers.has(node_part)) {\n if (is_load_op(microop.at(node_id)))\n registers.getRegister(node_part)->increment_loads();\n else\n registers.getRegister(node_part)->increment_stores();\n markNodeCompleted(it, index);\n } else if (scratchpadCanService) {\n if (scratchpad->canServicePartition(node_part)) {\n if (is_load_op(microop.at(node_id)))\n scratchpad->increment_loads(node_part);\n else\n scratchpad->increment_stores(node_part);\n markNodeCompleted(it, index);\n } else {\n scratchpadCanService = scratchpad->canService();\n ++it;\n ++index;\n }\n } else {\n ++it;\n ++index;\n }\n } else {\n markNodeCompleted(it, index);\n }\n }\n}\nint ScratchpadDatapath::rescheduleNodesWhenNeeded(){\n std::vector<Vertex> topo_nodes;\n boost::topological_sort(graph_, std::back_inserter(topo_nodes));\n \/\/ bottom nodes first\n std::vector<float> alap_finish_time(numTotalNodes, num_cycles * cycleTime);\n for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi) {\n unsigned node_id = vertexToName[*vi];\n if (finalIsolated.at(node_id))\n continue;\n unsigned node_microop = microop.at(node_id);\n float alap_executing_time = alap_finish_time.at(node_id);\n if (!is_memory_op(node_microop) && !is_branch_op(node_microop)) {\n alap_executing_time -= node_latency(node_microop);\n if (alap_executing_time > (newLevel.at(node_id) + 1) * cycleTime) {\n newLevel.at(node_id) = floor(alap_executing_time \/ cycleTime);\n }\n } else {\n alap_executing_time = newLevel.at(node_id) * cycleTime;\n }\n\n in_edge_iter in_i, in_end;\n for (tie(in_i, in_end) = in_edges(*vi, graph_); in_i != in_end; ++in_i) {\n int parent_id = vertexToName[source(*in_i, graph_)];\n if (alap_finish_time.at(parent_id) > alap_executing_time)\n alap_finish_time.at(parent_id) = alap_executing_time;\n }\n }\n return num_cycles;\n}\nvoid ScratchpadDatapath::updateChildren(unsigned node_id) {\n if (nameToVertex.find(node_id) == nameToVertex.end())\n return;\n float latency_after_current_node = node_latency(microop.at(node_id));\n if (timeBeforeNodeExecution.at(node_id) > num_cycles * cycleTime) {\n latency_after_current_node += timeBeforeNodeExecution.at(node_id);\n }\n else {\n latency_after_current_node += num_cycles * cycleTime;\n }\n Vertex node = nameToVertex[node_id];\n out_edge_iter out_edge_it, out_edge_end;\n for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_);\n out_edge_it != out_edge_end;\n ++out_edge_it) {\n unsigned child_id = vertexToName[target(*out_edge_it, graph_)];\n int edge_parid = edgeToParid[*out_edge_it];\n float child_earliest_time = timeBeforeNodeExecution.at(child_id);\n if (edge_parid != CONTROL_EDGE && child_earliest_time < latency_after_current_node)\n timeBeforeNodeExecution.at(child_id) = latency_after_current_node;\n if (numParents[child_id] > 0) {\n numParents[child_id]--;\n if (numParents[child_id] == 0) {\n unsigned child_microop = microop.at(child_id);\n if ((node_latency(child_microop) == 0 ||\n node_latency(microop.at(node_id)) == 0) &&\n edge_parid != CONTROL_EDGE)\n executingQueue.push_back(child_id);\n else if (is_memory_op(child_microop)) {\n if (is_store_op(child_microop))\n readyToExecuteQueue.push_front(child_id);\n else\n readyToExecuteQueue.push_back(child_id);\n }\n else {\n float after_child_time = timeBeforeNodeExecution.at(child_id)\n + node_latency(microop.at(node_id));\n if (after_child_time < (num_cycles + 1) * cycleTime &&\n edge_parid != CONTROL_EDGE )\n executingQueue.push_back(child_id);\n else\n readyToExecuteQueue.push_back(child_id);\n }\n numParents[child_id] = -1;\n }\n }\n }\n}\n\nvoid ScratchpadDatapath::dumpStats() {\n BaseDatapath::dumpStats();\n BaseDatapath::writePerCycleActivity();\n}\n\ndouble ScratchpadDatapath::getTotalMemArea() {\n return scratchpad->getTotalArea();\n}\n\nunsigned ScratchpadDatapath::getTotalMemSize() {\n return scratchpad->getTotalSize();\n}\n\nvoid ScratchpadDatapath::getMemoryBlocks(std::vector<std::string>& names) {\n scratchpad->getMemoryBlocks(names);\n}\n\nvoid ScratchpadDatapath::getAverageMemPower(unsigned int cycles,\n float* avg_power,\n float* avg_dynamic,\n float* avg_leak) {\n scratchpad->getAveragePower(cycles, avg_power, avg_dynamic, avg_leak);\n}\n<commit_msg>Fixed a typo in updateChildren().<commit_after>\/* Implementation of an accelerator datapath that uses a private scratchpad for\n * local memory.\n *\/\n\n#include <string>\n\n#include \"ScratchpadDatapath.h\"\n\nScratchpadDatapath::ScratchpadDatapath(std::string bench,\n std::string trace_file,\n std::string config_file)\n : BaseDatapath(bench, trace_file, config_file) {\n std::cerr << \"-------------------------------\" << std::endl;\n std::cerr << \" Setting ScratchPad \" << std::endl;\n std::cerr << \"-------------------------------\" << std::endl;\n scratchpad = new Scratchpad(1, cycleTime);\n scratchpadCanService = true;\n}\n\nScratchpadDatapath::~ScratchpadDatapath() { delete scratchpad; }\n\nvoid ScratchpadDatapath::globalOptimizationPass() {\n \/\/ Node removals must come first.\n removePhiNodes();\n \/*memoryAmibguation() should execute after removeInductionDependence() because\n * it needs induction_nodes.*\/\n removeInductionDependence();\n memoryAmbiguation();\n \/\/ Base address must be initialized next.\n initBaseAddress();\n completePartition();\n scratchpadPartition();\n loopFlatten();\n loopUnrolling();\n removeSharedLoads();\n storeBuffer();\n removeRepeatedStores();\n treeHeightReduction();\n \/\/ Must do loop pipelining last; after all the data\/control dependences are\n \/\/ fixed\n loopPipelining();\n}\n\n\/* First, compute all base addresses, then check each node to make sure that\n * each entry is valid.\n *\/\nvoid ScratchpadDatapath::initBaseAddress() {\n BaseDatapath::initBaseAddress();\n std::unordered_map<std::string, unsigned> comp_part_config;\n readCompletePartitionConfig(comp_part_config);\n std::unordered_map<std::string, partitionEntry> part_config;\n readPartitionConfig(part_config);\n\n for (auto it = nodeToLabel.begin(); it != nodeToLabel.end(); ++it) {\n unsigned node_id = it->first;\n std::string part_name = nodeToLabel[node_id];\n if (part_config.find(part_name) == part_config.end() &&\n comp_part_config.find(part_name) == comp_part_config.end()) {\n std::cerr << \"Unknown partition : \" << part_name << \"@inst: \" << node_id\n << std::endl;\n exit(-1);\n }\n }\n}\n\n\/*\n * Modify scratchpad\n *\/\nvoid ScratchpadDatapath::completePartition() {\n std::unordered_map<std::string, unsigned> comp_part_config;\n if (!readCompletePartitionConfig(comp_part_config))\n return;\n\n std::cerr << \"-------------------------------\" << std::endl;\n std::cerr << \" Mem to Reg Conv \" << std::endl;\n std::cerr << \"-------------------------------\" << std::endl;\n\n for (auto it = comp_part_config.begin(); it != comp_part_config.end(); ++it) {\n std::string base_addr = it->first;\n unsigned size = it->second;\n\n registers.createRegister(base_addr, size, cycleTime);\n }\n}\n\n\/*\n * Modify: baseAddress\n *\/\nvoid ScratchpadDatapath::scratchpadPartition() {\n \/\/ read the partition config file to get the address range\n \/\/ <base addr, <type, part_factor> >\n std::unordered_map<std::string, partitionEntry> part_config;\n if (!readPartitionConfig(part_config))\n return;\n\n std::cerr << \"-------------------------------\" << std::endl;\n std::cerr << \" ScratchPad Partition \" << std::endl;\n std::cerr << \"-------------------------------\" << std::endl;\n std::string bn(benchName);\n\n std::unordered_map<unsigned, MemAccess> address;\n initAddress(address);\n \/\/ set scratchpad\n for (auto it = part_config.begin(); it != part_config.end(); ++it) {\n std::string base_addr = it->first;\n unsigned size = it->second.array_size; \/\/ num of bytes\n unsigned p_factor = it->second.part_factor;\n unsigned wordsize = it->second.wordsize; \/\/ in bytes\n unsigned per_size = ceil(((float)size) \/ p_factor);\n\n for (unsigned i = 0; i < p_factor; i++) {\n ostringstream oss;\n oss << base_addr << \"-\" << i;\n scratchpad->setScratchpad(oss.str(), per_size, wordsize);\n }\n }\n\n for (unsigned node_id = 0; node_id < numTotalNodes; node_id++) {\n if (!is_memory_op(microop.at(node_id)))\n continue;\n\n if (nodeToLabel.find(node_id) == nodeToLabel.end())\n continue;\n std::string base_label = nodeToLabel[node_id];\n long long int base_addr = arrayBaseAddress[base_label];\n\n auto part_it = part_config.find(base_label);\n if (part_it != part_config.end()) {\n std::string p_type = part_it->second.type;\n assert((!p_type.compare(\"block\")) || (!p_type.compare(\"cyclic\")));\n\n unsigned num_of_elements = part_it->second.array_size;\n unsigned p_factor = part_it->second.part_factor;\n long long int abs_addr = address[node_id].vaddr;\n unsigned data_size = address[node_id].size \/ 8; \/\/ in bytes\n unsigned rel_addr = (abs_addr - base_addr) \/ data_size;\n if (!p_type.compare(\"block\")) \/\/ block partition\n {\n ostringstream oss;\n unsigned num_of_elements_in_2 = next_power_of_two(num_of_elements);\n oss << base_label << \"-\"\n << (int)(rel_addr \/ ceil(num_of_elements_in_2 \/ p_factor));\n nodeToLabel[node_id] = oss.str();\n } else \/\/ cyclic partition\n {\n ostringstream oss;\n oss << base_label << \"-\" << (rel_addr) % p_factor;\n nodeToLabel[node_id] = oss.str();\n }\n }\n }\n writeBaseAddress();\n}\n\nvoid ScratchpadDatapath::setGraphForStepping() {\n BaseDatapath::setGraphForStepping();\n timeBeforeNodeExecution.assign(numTotalNodes, 0);\n}\nbool ScratchpadDatapath::step() {\n if (!BaseDatapath::step()) {\n scratchpad->step();\n scratchpadCanService = true;\n return false;\n } else {\n return true;\n }\n}\n\nvoid ScratchpadDatapath::stepExecutingQueue() {\n auto it = executingQueue.begin();\n int index = 0;\n while (it != executingQueue.end()) {\n unsigned node_id = *it;\n if (is_memory_op(microop.at(node_id))) {\n std::string node_part = nodeToLabel[node_id];\n if (registers.has(node_part)) {\n if (is_load_op(microop.at(node_id)))\n registers.getRegister(node_part)->increment_loads();\n else\n registers.getRegister(node_part)->increment_stores();\n markNodeCompleted(it, index);\n } else if (scratchpadCanService) {\n if (scratchpad->canServicePartition(node_part)) {\n if (is_load_op(microop.at(node_id)))\n scratchpad->increment_loads(node_part);\n else\n scratchpad->increment_stores(node_part);\n markNodeCompleted(it, index);\n } else {\n scratchpadCanService = scratchpad->canService();\n ++it;\n ++index;\n }\n } else {\n ++it;\n ++index;\n }\n } else {\n markNodeCompleted(it, index);\n }\n }\n}\nint ScratchpadDatapath::rescheduleNodesWhenNeeded(){\n std::vector<Vertex> topo_nodes;\n boost::topological_sort(graph_, std::back_inserter(topo_nodes));\n \/\/ bottom nodes first\n std::vector<float> alap_finish_time(numTotalNodes, num_cycles * cycleTime);\n for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi) {\n unsigned node_id = vertexToName[*vi];\n if (finalIsolated.at(node_id))\n continue;\n unsigned node_microop = microop.at(node_id);\n float alap_executing_time = alap_finish_time.at(node_id);\n if (!is_memory_op(node_microop) && !is_branch_op(node_microop)) {\n alap_executing_time -= node_latency(node_microop);\n if (alap_executing_time > (newLevel.at(node_id) + 1) * cycleTime) {\n newLevel.at(node_id) = floor(alap_executing_time \/ cycleTime);\n }\n } else {\n alap_executing_time = newLevel.at(node_id) * cycleTime;\n }\n\n in_edge_iter in_i, in_end;\n for (tie(in_i, in_end) = in_edges(*vi, graph_); in_i != in_end; ++in_i) {\n int parent_id = vertexToName[source(*in_i, graph_)];\n if (alap_finish_time.at(parent_id) > alap_executing_time)\n alap_finish_time.at(parent_id) = alap_executing_time;\n }\n }\n return num_cycles;\n}\nvoid ScratchpadDatapath::updateChildren(unsigned node_id) {\n if (nameToVertex.find(node_id) == nameToVertex.end())\n return;\n float latency_after_current_node = node_latency(microop.at(node_id));\n if (timeBeforeNodeExecution.at(node_id) > num_cycles * cycleTime) {\n latency_after_current_node += timeBeforeNodeExecution.at(node_id);\n }\n else {\n latency_after_current_node += num_cycles * cycleTime;\n }\n Vertex node = nameToVertex[node_id];\n out_edge_iter out_edge_it, out_edge_end;\n for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_);\n out_edge_it != out_edge_end;\n ++out_edge_it) {\n unsigned child_id = vertexToName[target(*out_edge_it, graph_)];\n int edge_parid = edgeToParid[*out_edge_it];\n float child_earliest_time = timeBeforeNodeExecution.at(child_id);\n if (edge_parid != CONTROL_EDGE && child_earliest_time < latency_after_current_node)\n timeBeforeNodeExecution.at(child_id) = latency_after_current_node;\n if (numParents[child_id] > 0) {\n numParents[child_id]--;\n if (numParents[child_id] == 0) {\n unsigned child_microop = microop.at(child_id);\n if ((node_latency(child_microop) == 0 ||\n node_latency(microop.at(node_id)) == 0) &&\n edge_parid != CONTROL_EDGE)\n executingQueue.push_back(child_id);\n else if (is_memory_op(child_microop)) {\n if (is_store_op(child_microop))\n readyToExecuteQueue.push_front(child_id);\n else\n readyToExecuteQueue.push_back(child_id);\n }\n else {\n float after_child_time = timeBeforeNodeExecution.at(child_id)\n + node_latency(microop.at(child_id));\n if (after_child_time < (num_cycles + 1) * cycleTime &&\n edge_parid != CONTROL_EDGE )\n executingQueue.push_back(child_id);\n else\n readyToExecuteQueue.push_back(child_id);\n }\n numParents[child_id] = -1;\n }\n }\n }\n}\n\nvoid ScratchpadDatapath::dumpStats() {\n BaseDatapath::dumpStats();\n BaseDatapath::writePerCycleActivity();\n}\n\ndouble ScratchpadDatapath::getTotalMemArea() {\n return scratchpad->getTotalArea();\n}\n\nunsigned ScratchpadDatapath::getTotalMemSize() {\n return scratchpad->getTotalSize();\n}\n\nvoid ScratchpadDatapath::getMemoryBlocks(std::vector<std::string>& names) {\n scratchpad->getMemoryBlocks(names);\n}\n\nvoid ScratchpadDatapath::getAverageMemPower(unsigned int cycles,\n float* avg_power,\n float* avg_dynamic,\n float* avg_leak) {\n scratchpad->getAveragePower(cycles, avg_power, avg_dynamic, avg_leak);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright 2009-2013 Merethis\n**\n** This file is part of Centreon Broker.\n**\n** Centreon Broker is free software: you can redistribute it and\/or\n** modify it under the terms of the GNU General Public License version 2\n** as published by the Free Software Foundation.\n**\n** Centreon Broker 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** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Centreon Broker. If not, see\n** <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <memory>\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n#include \"com\/centreon\/broker\/neb\/callbacks.hh\"\n#include \"com\/centreon\/broker\/neb\/events.hh\"\n#include \"com\/centreon\/broker\/neb\/initial.hh\"\n#include \"com\/centreon\/broker\/neb\/internal.hh\"\n#include \"com\/centreon\/engine\/broker.hh\"\n#include \"com\/centreon\/engine\/common.hh\"\n#include \"com\/centreon\/engine\/nebcallbacks.hh\"\n#include \"com\/centreon\/engine\/nebstructs.hh\"\n#include \"com\/centreon\/engine\/objects.hh\"\n\n\/\/ Internal Nagios host list.\nextern \"C\" {\n extern host* host_list;\n extern hostdependency* hostdependency_list;\n extern hostgroup* hostgroup_list;\n extern service* service_list;\n extern servicedependency* servicedependency_list;\n extern servicegroup* servicegroup_list;\n}\n\nusing namespace com::centreon::broker;\n\n\/\/ NEB module list.\nextern \"C\" {\n nebmodule* neb_module_list;\n}\n\n\/**************************************\n* *\n* Static Functions *\n* *\n**************************************\/\n\n\/**\n * Send to the global publisher the list of custom variables.\n *\/\nstatic void send_custom_variables_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning custom variables dump\";\n\n \/\/ Iterate through all hosts.\n for (host* h(host_list); h; h = h->next)\n \/\/ Send all custom variables.\n for (customvariablesmember* cv(h->custom_variables);\n cv;\n cv = cv->next) {\n \/\/ Fill callback struct.\n nebstruct_custom_variable_data nscvd;\n memset(&nscvd, 0, sizeof(nscvd));\n nscvd.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD;\n nscvd.timestamp.tv_sec = time(NULL);\n nscvd.var_name = cv->variable_name;\n nscvd.var_value = cv->variable_value;\n nscvd.object_ptr = h;\n\n \/\/ Callback.\n neb::callback_custom_variable(\n NEBCALLBACK_CUSTOM_VARIABLE_DATA,\n &nscvd);\n }\n\n \/\/ Iterate through all services.\n for (service* s(service_list); s; s = s->next)\n \/\/ Send all custom variables.\n for (customvariablesmember* cv(s->custom_variables);\n cv;\n cv = cv->next) {\n \/\/ Fill callback struct.\n nebstruct_custom_variable_data nscvd;\n memset(&nscvd, 0, sizeof(nscvd));\n nscvd.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD;\n nscvd.timestamp.tv_sec = time(NULL);\n nscvd.var_name = cv->variable_name;\n nscvd.var_value = cv->variable_value;\n nscvd.object_ptr = s;\n\n \/\/ Callback.\n neb::callback_custom_variable(\n NEBCALLBACK_CUSTOM_VARIABLE_DATA,\n &nscvd);\n }\n\n \/\/ End log message.\n logging::info(logging::medium)\n << \"init: end of custom variables dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of host dependencies within Nagios.\n *\/\nstatic void send_host_dependencies_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning host dependencies dump\";\n\n \/\/ Loop through all dependencies.\n for (hostdependency* hd = hostdependency_list; hd; hd = hd->next) {\n misc::shared_ptr<neb::host_dependency> host_dependency(\n new neb::host_dependency);\n std::map<std::string, int>::const_iterator it;\n\n \/\/ Set host dependency parameters.\n if (hd->dependency_period)\n host_dependency->dependency_period = hd->dependency_period;\n if (hd->dependent_host_name) {\n it = neb::gl_hosts.find(hd->dependent_host_name);\n if (it != neb::gl_hosts.end())\n host_dependency->dependent_host_id = it->second;\n }\n host_dependency->inherits_parent = hd->inherits_parent;\n if (hd->host_name) {\n it = neb::gl_hosts.find(hd->host_name);\n if (it != neb::gl_hosts.end())\n host_dependency->host_id = it->second;\n }\n\n \/\/ Send host dependency event.\n logging::info(logging::low) << \"init: host \"\n << host_dependency->dependent_host_id << \" depends on host \"\n << host_dependency->host_id;\n neb::gl_publisher.write(host_dependency.staticCast<io::data>());\n }\n\n \/\/ End log message.\n logging::info(logging::medium)\n << \"init: end of host dependencies dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of host groups within Engine.\n *\/\nstatic void send_host_group_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning host group dump\";\n\n \/\/ Loop through all host groups.\n for (hostgroup* hg(hostgroup_list); hg; hg = hg->next) {\n \/\/ Fill callback struct.\n nebstruct_group_data nsgd;\n memset(&nsgd, 0, sizeof(nsgd));\n nsgd.type = NEBTYPE_HOSTGROUP_ADD;\n nsgd.object_ptr = hg;\n\n \/\/ Callback.\n neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd);\n\n \/\/ Dump host group members.\n for (hostsmember* hgm(hg->members); hgm; hgm = hgm->next) {\n \/\/ Fill callback struct.\n nebstruct_group_member_data nsgmd;\n memset(&nsgmd, 0, sizeof(nsgmd));\n nsgmd.type = NEBTYPE_HOSTGROUPMEMBER_ADD;\n nsgmd.object_ptr = hgm->host_ptr;\n nsgmd.group_ptr = hg;\n\n \/\/ Callback.\n neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd);\n }\n }\n\n \/\/ End log message.\n logging::info(logging::medium)\n << \"init: end of host group dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of hosts within Nagios.\n *\/\nstatic void send_host_list() {\n \/\/ Start log message.\n logging::info(logging::medium) << \"init: beginning host dump\";\n\n \/\/ Loop through all hosts.\n for (host* h(host_list); h; h = h->next) {\n \/\/ Fill callback struct.\n nebstruct_adaptive_host_data nsahd;\n memset(&nsahd, 0, sizeof(nsahd));\n nsahd.type = NEBTYPE_HOST_ADD;\n nsahd.command_type = CMD_NONE;\n nsahd.modified_attribute = MODATTR_ALL;\n nsahd.modified_attributes = MODATTR_ALL;\n nsahd.object_ptr = h;\n\n \/\/ Callback.\n neb::callback_host(NEBCALLBACK_ADAPTIVE_HOST_DATA, &nsahd);\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of host dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of host parents within Nagios.\n *\/\nstatic void send_host_parents_list() {\n \/\/ Start log message.\n logging::info(logging::medium) << \"init: beginning host parents dump\";\n\n \/\/ Loop through all hosts.\n int host_id;\n for (host* h = host_list; h; h = h->next) {\n std::map<std::string, int>::const_iterator it;\n\n \/\/ Search host_id.\n if (h->name) {\n it = neb::gl_hosts.find(h->name);\n if (it != neb::gl_hosts.end())\n host_id = it->second;\n else\n host_id = 0;\n }\n else\n host_id = 0;\n\n \/\/ Loop through all dependencies.\n for (hostsmember* parent = h->parent_hosts; parent; parent = parent->next) {\n misc::shared_ptr<neb::host_parent> hp(new neb::host_parent);\n std::map<std::string, int>::const_iterator it;\n\n hp->host_id = host_id;\n if (parent->host_name) {\n it = neb::gl_hosts.find(parent->host_name);\n if (it != neb::gl_hosts.end())\n hp->parent_id = it->second;\n }\n\n \/\/ Send host parent event.\n logging::info(logging::low) << \"init: host \" << hp->parent_id\n << \" is parent of host \" << hp->host_id;\n neb::gl_publisher.write(hp.staticCast<io::data>());\n }\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of host parents dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of modules loaded by Engine.\n *\/\nstatic void send_module_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning modules dump\";\n\n \/\/ Browse module list.\n for (nebmodule* nm(neb_module_list); nm; nm = nm->next)\n if (nm->filename) {\n \/\/ Fill callback struct.\n nebstruct_module_data nsmd;\n memset(&nsmd, 0, sizeof(nsmd));\n nsmd.module = nm->filename;\n nsmd.args = nm->args;\n nsmd.type = NEBTYPE_MODULE_ADD;\n\n \/\/ Callback.\n neb::callback_module(NEBTYPE_MODULE_ADD, &nsmd);\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of modules dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of service dependencies within\n * Nagios.\n *\/\nstatic void send_service_dependencies_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning service dependencies dump\";\n\n \/\/ Loop through all dependencies.\n for (servicedependency* sd = servicedependency_list; sd; sd = sd->next) {\n std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator it;\n misc::shared_ptr<neb::service_dependency>\n service_dependency(new neb::service_dependency);\n\n \/\/ Search IDs.\n if (sd->dependent_host_name && sd->dependent_service_description) {\n it = neb::gl_services.find(std::make_pair<std::string, std::string>(\n sd->dependent_host_name, sd->dependent_service_description));\n if (it != neb::gl_services.end()) {\n service_dependency->dependent_host_id = it->second.first;\n service_dependency->dependent_service_id = it->second.second;\n }\n }\n if (sd->dependency_period)\n service_dependency->dependency_period = sd->dependency_period;\n service_dependency->inherits_parent = sd->inherits_parent;\n if (sd->host_name && sd->service_description) {\n it = neb::gl_services.find(std::make_pair<std::string, std::string>(\n sd->host_name, sd->service_description));\n if (it != neb::gl_services.end()) {\n service_dependency->host_id = it->second.first;\n service_dependency->service_id = it->second.second;\n }\n }\n\n \/\/ Send service dependency event.\n logging::info(logging::low) << \"init: service (\"\n << service_dependency->dependent_host_id << \", \"\n << service_dependency->dependent_service_id\n << \") depends on service (\" << service_dependency->host_id\n << \", \" << service_dependency->service_id << \")\";\n neb::gl_publisher.write(service_dependency.staticCast<io::data>());\n }\n\n \/\/ End log message.\n logging::info(logging::medium)\n << \"init: end of service dependencies dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of service groups within Engine.\n *\/\nstatic void send_service_group_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning service group dump\";\n\n \/\/ Loop through all service groups.\n for (servicegroup* sg(servicegroup_list); sg; sg = sg->next) {\n \/\/ Fill callback struct.\n nebstruct_group_data nsgd;\n memset(&nsgd, 0, sizeof(nsgd));\n nsgd.type = NEBTYPE_SERVICEGROUP_ADD;\n nsgd.object_ptr = sg;\n\n \/\/ Callback.\n neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd);\n\n \/\/ Dump service group members.\n for (servicesmember* sgm(sg->members); sgm; sgm = sgm->next) {\n \/\/ Fill callback struct.\n nebstruct_group_member_data nsgmd;\n memset(&nsgmd, 0, sizeof(nsgmd));\n nsgmd.type = NEBTYPE_SERVICEGROUPMEMBER_ADD;\n nsgmd.object_ptr = sgm->service_ptr;\n nsgmd.group_ptr = sg;\n\n \/\/ Callback.\n neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd);\n }\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of service groups dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of services within Nagios.\n *\/\nstatic void send_service_list() {\n \/\/ Start log message.\n logging::info(logging::medium) << \"init: beginning service dump\";\n\n \/\/ Loop through all services.\n for (service* s = service_list; s; s = s->next) {\n \/\/ Fill callback struct.\n nebstruct_adaptive_service_data nsasd;\n memset(&nsasd, 0, sizeof(nsasd));\n nsasd.type = NEBTYPE_SERVICE_ADD;\n nsasd.command_type = CMD_NONE;\n nsasd.modified_attribute = MODATTR_ALL;\n nsasd.modified_attributes = MODATTR_ALL;\n nsasd.object_ptr = s;\n\n \/\/ Callback.\n neb::callback_service(NEBCALLBACK_ADAPTIVE_SERVICE_DATA, &nsasd);\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of services dump\";\n\n return ;\n}\n\n\/**************************************\n* *\n* Global Functions *\n* *\n**************************************\/\n\n\/**\n * Send initial configuration to the global publisher.\n *\/\nvoid neb::send_initial_configuration() {\n send_host_list();\n send_service_list();\n send_custom_variables_list();\n send_host_parents_list();\n send_host_group_list();\n send_service_group_list();\n send_host_dependencies_list();\n send_service_dependencies_list();\n send_module_list();\n return ;\n}\n<commit_msg>NEB: create initial host parents using callback.<commit_after>\/*\n** Copyright 2009-2013 Merethis\n**\n** This file is part of Centreon Broker.\n**\n** Centreon Broker is free software: you can redistribute it and\/or\n** modify it under the terms of the GNU General Public License version 2\n** as published by the Free Software Foundation.\n**\n** Centreon Broker 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** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Centreon Broker. If not, see\n** <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <memory>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n#include \"com\/centreon\/broker\/neb\/callbacks.hh\"\n#include \"com\/centreon\/broker\/neb\/events.hh\"\n#include \"com\/centreon\/broker\/neb\/initial.hh\"\n#include \"com\/centreon\/broker\/neb\/internal.hh\"\n#include \"com\/centreon\/engine\/broker.hh\"\n#include \"com\/centreon\/engine\/common.hh\"\n#include \"com\/centreon\/engine\/nebcallbacks.hh\"\n#include \"com\/centreon\/engine\/nebstructs.hh\"\n#include \"com\/centreon\/engine\/objects.hh\"\n\n\/\/ Internal Nagios host list.\nextern \"C\" {\n extern host* host_list;\n extern hostdependency* hostdependency_list;\n extern hostgroup* hostgroup_list;\n extern service* service_list;\n extern servicedependency* servicedependency_list;\n extern servicegroup* servicegroup_list;\n}\n\nusing namespace com::centreon::broker;\n\n\/\/ NEB module list.\nextern \"C\" {\n nebmodule* neb_module_list;\n}\n\n\/**************************************\n* *\n* Static Functions *\n* *\n**************************************\/\n\n\/**\n * Send to the global publisher the list of custom variables.\n *\/\nstatic void send_custom_variables_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning custom variables dump\";\n\n \/\/ Iterate through all hosts.\n for (host* h(host_list); h; h = h->next)\n \/\/ Send all custom variables.\n for (customvariablesmember* cv(h->custom_variables);\n cv;\n cv = cv->next) {\n \/\/ Fill callback struct.\n nebstruct_custom_variable_data nscvd;\n memset(&nscvd, 0, sizeof(nscvd));\n nscvd.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD;\n nscvd.timestamp.tv_sec = time(NULL);\n nscvd.var_name = cv->variable_name;\n nscvd.var_value = cv->variable_value;\n nscvd.object_ptr = h;\n\n \/\/ Callback.\n neb::callback_custom_variable(\n NEBCALLBACK_CUSTOM_VARIABLE_DATA,\n &nscvd);\n }\n\n \/\/ Iterate through all services.\n for (service* s(service_list); s; s = s->next)\n \/\/ Send all custom variables.\n for (customvariablesmember* cv(s->custom_variables);\n cv;\n cv = cv->next) {\n \/\/ Fill callback struct.\n nebstruct_custom_variable_data nscvd;\n memset(&nscvd, 0, sizeof(nscvd));\n nscvd.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD;\n nscvd.timestamp.tv_sec = time(NULL);\n nscvd.var_name = cv->variable_name;\n nscvd.var_value = cv->variable_value;\n nscvd.object_ptr = s;\n\n \/\/ Callback.\n neb::callback_custom_variable(\n NEBCALLBACK_CUSTOM_VARIABLE_DATA,\n &nscvd);\n }\n\n \/\/ End log message.\n logging::info(logging::medium)\n << \"init: end of custom variables dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of host dependencies within Nagios.\n *\/\nstatic void send_host_dependencies_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning host dependencies dump\";\n\n \/\/ Loop through all dependencies.\n for (hostdependency* hd = hostdependency_list; hd; hd = hd->next) {\n misc::shared_ptr<neb::host_dependency> host_dependency(\n new neb::host_dependency);\n std::map<std::string, int>::const_iterator it;\n\n \/\/ Set host dependency parameters.\n if (hd->dependency_period)\n host_dependency->dependency_period = hd->dependency_period;\n if (hd->dependent_host_name) {\n it = neb::gl_hosts.find(hd->dependent_host_name);\n if (it != neb::gl_hosts.end())\n host_dependency->dependent_host_id = it->second;\n }\n host_dependency->inherits_parent = hd->inherits_parent;\n if (hd->host_name) {\n it = neb::gl_hosts.find(hd->host_name);\n if (it != neb::gl_hosts.end())\n host_dependency->host_id = it->second;\n }\n\n \/\/ Send host dependency event.\n logging::info(logging::low) << \"init: host \"\n << host_dependency->dependent_host_id << \" depends on host \"\n << host_dependency->host_id;\n neb::gl_publisher.write(host_dependency.staticCast<io::data>());\n }\n\n \/\/ End log message.\n logging::info(logging::medium)\n << \"init: end of host dependencies dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of host groups within Engine.\n *\/\nstatic void send_host_group_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning host group dump\";\n\n \/\/ Loop through all host groups.\n for (hostgroup* hg(hostgroup_list); hg; hg = hg->next) {\n \/\/ Fill callback struct.\n nebstruct_group_data nsgd;\n memset(&nsgd, 0, sizeof(nsgd));\n nsgd.type = NEBTYPE_HOSTGROUP_ADD;\n nsgd.object_ptr = hg;\n\n \/\/ Callback.\n neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd);\n\n \/\/ Dump host group members.\n for (hostsmember* hgm(hg->members); hgm; hgm = hgm->next) {\n \/\/ Fill callback struct.\n nebstruct_group_member_data nsgmd;\n memset(&nsgmd, 0, sizeof(nsgmd));\n nsgmd.type = NEBTYPE_HOSTGROUPMEMBER_ADD;\n nsgmd.object_ptr = hgm->host_ptr;\n nsgmd.group_ptr = hg;\n\n \/\/ Callback.\n neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd);\n }\n }\n\n \/\/ End log message.\n logging::info(logging::medium)\n << \"init: end of host group dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of hosts within Nagios.\n *\/\nstatic void send_host_list() {\n \/\/ Start log message.\n logging::info(logging::medium) << \"init: beginning host dump\";\n\n \/\/ Loop through all hosts.\n for (host* h(host_list); h; h = h->next) {\n \/\/ Fill callback struct.\n nebstruct_adaptive_host_data nsahd;\n memset(&nsahd, 0, sizeof(nsahd));\n nsahd.type = NEBTYPE_HOST_ADD;\n nsahd.command_type = CMD_NONE;\n nsahd.modified_attribute = MODATTR_ALL;\n nsahd.modified_attributes = MODATTR_ALL;\n nsahd.object_ptr = h;\n\n \/\/ Callback.\n neb::callback_host(NEBCALLBACK_ADAPTIVE_HOST_DATA, &nsahd);\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of host dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of host parents within Nagios.\n *\/\nstatic void send_host_parents_list() {\n \/\/ Start log message.\n logging::info(logging::medium) << \"init: beginning host parents dump\";\n\n try {\n \/\/ Loop through all hosts.\n for (host* h(host_list); h; h = h->next)\n \/\/ Loop through all parents.\n for (hostsmember* parent(h->parent_hosts);\n parent;\n parent = parent->next) {\n \/\/ Fill callback struct.\n nebstruct_relation_data nsrd;\n memset(&nsrd, 0, sizeof(nsrd));\n nsrd.type = NEBTYPE_PARENT_ADD;\n nsrd.flags = NEBFLAG_NONE;\n nsrd.attr = NEBATTR_NONE;\n nsrd.timestamp.tv_sec = time(NULL);\n nsrd.hst = parent->host_ptr;\n nsrd.dep_hst = h;\n\n \/\/ Callback.\n neb::callback_relation(NEBTYPE_PARENT_ADD, &nsrd);\n }\n }\n catch (std::exception const& e) {\n logging::error(logging::high)\n << \"init: error occurred while dumping host parents: \"\n << e.what();\n }\n catch (...) {\n logging::error(logging::high)\n << \"init: unknown error occurred while dumping host parents\";\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of host parents dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of modules loaded by Engine.\n *\/\nstatic void send_module_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning modules dump\";\n\n \/\/ Browse module list.\n for (nebmodule* nm(neb_module_list); nm; nm = nm->next)\n if (nm->filename) {\n \/\/ Fill callback struct.\n nebstruct_module_data nsmd;\n memset(&nsmd, 0, sizeof(nsmd));\n nsmd.module = nm->filename;\n nsmd.args = nm->args;\n nsmd.type = NEBTYPE_MODULE_ADD;\n\n \/\/ Callback.\n neb::callback_module(NEBTYPE_MODULE_ADD, &nsmd);\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of modules dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of service dependencies within\n * Nagios.\n *\/\nstatic void send_service_dependencies_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning service dependencies dump\";\n\n \/\/ Loop through all dependencies.\n for (servicedependency* sd = servicedependency_list; sd; sd = sd->next) {\n std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator it;\n misc::shared_ptr<neb::service_dependency>\n service_dependency(new neb::service_dependency);\n\n \/\/ Search IDs.\n if (sd->dependent_host_name && sd->dependent_service_description) {\n it = neb::gl_services.find(std::make_pair<std::string, std::string>(\n sd->dependent_host_name, sd->dependent_service_description));\n if (it != neb::gl_services.end()) {\n service_dependency->dependent_host_id = it->second.first;\n service_dependency->dependent_service_id = it->second.second;\n }\n }\n if (sd->dependency_period)\n service_dependency->dependency_period = sd->dependency_period;\n service_dependency->inherits_parent = sd->inherits_parent;\n if (sd->host_name && sd->service_description) {\n it = neb::gl_services.find(std::make_pair<std::string, std::string>(\n sd->host_name, sd->service_description));\n if (it != neb::gl_services.end()) {\n service_dependency->host_id = it->second.first;\n service_dependency->service_id = it->second.second;\n }\n }\n\n \/\/ Send service dependency event.\n logging::info(logging::low) << \"init: service (\"\n << service_dependency->dependent_host_id << \", \"\n << service_dependency->dependent_service_id\n << \") depends on service (\" << service_dependency->host_id\n << \", \" << service_dependency->service_id << \")\";\n neb::gl_publisher.write(service_dependency.staticCast<io::data>());\n }\n\n \/\/ End log message.\n logging::info(logging::medium)\n << \"init: end of service dependencies dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of service groups within Engine.\n *\/\nstatic void send_service_group_list() {\n \/\/ Start log message.\n logging::info(logging::medium)\n << \"init: beginning service group dump\";\n\n \/\/ Loop through all service groups.\n for (servicegroup* sg(servicegroup_list); sg; sg = sg->next) {\n \/\/ Fill callback struct.\n nebstruct_group_data nsgd;\n memset(&nsgd, 0, sizeof(nsgd));\n nsgd.type = NEBTYPE_SERVICEGROUP_ADD;\n nsgd.object_ptr = sg;\n\n \/\/ Callback.\n neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd);\n\n \/\/ Dump service group members.\n for (servicesmember* sgm(sg->members); sgm; sgm = sgm->next) {\n \/\/ Fill callback struct.\n nebstruct_group_member_data nsgmd;\n memset(&nsgmd, 0, sizeof(nsgmd));\n nsgmd.type = NEBTYPE_SERVICEGROUPMEMBER_ADD;\n nsgmd.object_ptr = sgm->service_ptr;\n nsgmd.group_ptr = sg;\n\n \/\/ Callback.\n neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd);\n }\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of service groups dump\";\n\n return ;\n}\n\n\/**\n * Send to the global publisher the list of services within Nagios.\n *\/\nstatic void send_service_list() {\n \/\/ Start log message.\n logging::info(logging::medium) << \"init: beginning service dump\";\n\n \/\/ Loop through all services.\n for (service* s = service_list; s; s = s->next) {\n \/\/ Fill callback struct.\n nebstruct_adaptive_service_data nsasd;\n memset(&nsasd, 0, sizeof(nsasd));\n nsasd.type = NEBTYPE_SERVICE_ADD;\n nsasd.command_type = CMD_NONE;\n nsasd.modified_attribute = MODATTR_ALL;\n nsasd.modified_attributes = MODATTR_ALL;\n nsasd.object_ptr = s;\n\n \/\/ Callback.\n neb::callback_service(NEBCALLBACK_ADAPTIVE_SERVICE_DATA, &nsasd);\n }\n\n \/\/ End log message.\n logging::info(logging::medium) << \"init: end of services dump\";\n\n return ;\n}\n\n\/**************************************\n* *\n* Global Functions *\n* *\n**************************************\/\n\n\/**\n * Send initial configuration to the global publisher.\n *\/\nvoid neb::send_initial_configuration() {\n send_host_list();\n send_service_list();\n send_custom_variables_list();\n send_host_parents_list();\n send_host_group_list();\n send_service_group_list();\n send_host_dependencies_list();\n send_service_dependencies_list();\n send_module_list();\n return ;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n#define MAX_PAIR_NUM 1000\n\nint main() {\n cout << \"test\";\n cout << \"test2\";\n cout << \"test3\";\n cout << \"test4\";\n}\n<commit_msg>revisit p1009<commit_after>#include <iostream>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n#define MAX_PAIR_NUM 1000\n\nint pixel_pair[MAX_PAIR_NUM][2];\nint img_width;\n\nint main() {\n while (cin >> img_width && img_width > 0) {\n int num, pixel;\n int pair_cnt = 0;\n int pixel_cnt = 0; \n\n while (cin >> pixel >> num && num != 0 && pixel != 0) {\n pixel_pair[pair_cnt][0] = pixel; \n pixel_pair[pair_cnt][1] = num;\n\n pair_cnt++;\n\n pixel_cnt += num;\n }\n\n for (int i = 0; i < pair_cnt; i++)\n cout << pixel_pair[i][0] << \" \" << pixel_pair[i][1] << endl;\n\n cout << pixel_cnt << endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2006, 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#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED\n#define TORRENT_EXTENSIONS_HPP_INCLUDED\n\n#ifndef TORRENT_DISABLE_EXTENSIONS\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/weak_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux { struct session_impl; }\n\n\tstruct peer_plugin;\n\tclass bt_peer_connection;\n\tstruct peer_request;\n\tclass peer_connection;\n\tclass entry;\n\tstruct lazy_entry;\n\tstruct disk_buffer_holder;\n\tstruct bitfield;\n\tclass alert;\n\n\tstruct TORRENT_EXPORT plugin\n\t{\n\t\tvirtual ~plugin() {}\n\n\t\tvirtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)\n\t\t{ return boost::shared_ptr<torrent_plugin>(); }\n\n\t\t\/\/ called when plugin is added to a session\n\t\tvirtual void added(boost::weak_ptr<aux::session_impl> s) {}\n\n\t\t\/\/ called when an alert is posted\n\t\t\/\/ alerts that are filtered are not\n\t\t\/\/ posted\n\t\tvirtual void on_alert(alert const* a) {}\n\n\t\t\/\/ called once per second\n\t\tvirtual void on_tick() {}\n\n\t\t\/\/ called when saving settings state\n\t\tvirtual void save_state(entry& ent) const {}\n\n\t\t\/\/ called when loading settings state\n\t\tvirtual void load_state(lazy_entry const& ent) {}\n\t};\n\n\tstruct TORRENT_EXPORT torrent_plugin\n\t{\n\t\tvirtual ~torrent_plugin() {}\n\t\t\/\/ throwing an exception closes the connection\n\t\t\/\/ returning a 0 pointer is valid and will not add\n\t\t\/\/ the peer_plugin to the peer_connection\n\t\tvirtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)\n\t\t{ return boost::shared_ptr<peer_plugin>(); }\n\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ if true is returned, it means the handler handled the event,\n\t\t\/\/ and no other plugins will have their handlers called, and the\n\t\t\/\/ default behavior will be skipped\n\t\tvirtual bool on_pause() { return false; }\n\t\tvirtual bool on_resume() { return false; }\n\n\t\t\/\/ this is called when the initial checking of\n\t\t\/\/ files is completed.\n\t\tvirtual void on_files_checked() {}\n\n\t\t\/\/ called when the torrent changes state\n\t\t\/\/ the state is one of torrent_status::state_t\n\t\t\/\/ enum members\n\t\tvirtual void on_state(int s) {}\n\t};\n\n\tstruct TORRENT_EXPORT peer_plugin\n\t{\n\t\tvirtual ~peer_plugin() {}\n\n\t\tvirtual char const* type() const { return \"\"; }\n\n\t\t\/\/ can add entries to the extension handshake\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual void add_handshake(entry&) {}\n\t\t\n\t\t\/\/ throwing an exception from any of the handlers (except add_handshake)\n\t\t\/\/ closes the connection\n\t\t\n\t\t\/\/ this is called when the initial BT handshake is received. Returning false\n\t\t\/\/ means that the other end doesn't support this extension and will remove\n\t\t\/\/ it from the list of plugins.\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_handshake(char const* reserved_bits) { return true; }\n\t\t\n\t\t\/\/ called when the extension handshake from the other end is received\n\t\t\/\/ if this returns false, it means that this extension isn't\n\t\t\/\/ supported by this peer. It will result in this peer_plugin\n\t\t\/\/ being removed from the peer_connection and destructed. \n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extension_handshake(lazy_entry const& h) { return true; }\n\n\t\t\/\/ returning true from any of the message handlers\n\t\t\/\/ indicates that the plugin has handeled the message.\n\t\t\/\/ it will break the plugin chain traversing and not let\n\t\t\/\/ anyone else handle the message, including the default\n\t\t\/\/ handler.\n\n\t\tvirtual bool on_choke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_unchoke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_not_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_bitfield(bitfield const& bitfield)\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_all()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_none()\n\t\t{ return false; }\n\n\t\tvirtual bool on_allowed_fast(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_request(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)\n\t\t{ return false; }\n\n\t\tvirtual bool on_cancel(peer_request const& req)\n\t\t{ return false; }\n\t\n\t\tvirtual bool on_reject(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_suggest(int index)\n\t\t{ return false; }\n\n\t\t\/\/ called when an extended message is received. If returning true,\n\t\t\/\/ the message is not processed by any other plugin and if false\n\t\t\/\/ is returned the next plugin in the chain will receive it to\n\t\t\/\/ be able to handle it\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extended(int length\n\t\t\t, int msg, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_unknown_message(int length, int msg\n\t\t\t, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ called when a piece that this peer participated in either\n\t\t\/\/ fails or passes the hash_check\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ called each time a request message is to be sent. If true\n\t\t\/\/ is returned, the original request message won't be sent and\n\t\t\/\/ no other plugin will have this function called.\n\t\tvirtual bool write_request(peer_request const& r) { return false; }\n\t};\n\n}\n\n#endif\n\n#endif \/\/ TORRENT_EXTENSIONS_HPP_INCLUDED\n\n<commit_msg>fix build<commit_after>\/*\n\nCopyright (c) 2006, 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#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED\n#define TORRENT_EXTENSIONS_HPP_INCLUDED\n\n#ifndef TORRENT_DISABLE_EXTENSIONS\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/weak_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux { struct session_impl; }\n\n\tstruct peer_plugin;\n\tclass bt_peer_connection;\n\tstruct peer_request;\n\tclass peer_connection;\n\tclass entry;\n\tstruct lazy_entry;\n\tstruct disk_buffer_holder;\n\tstruct bitfield;\n\tclass alert;\n\tstruct torrent_plugin;\n\n\tstruct TORRENT_EXPORT plugin\n\t{\n\t\tvirtual ~plugin() {}\n\n\t\tvirtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)\n\t\t{ return boost::shared_ptr<torrent_plugin>(); }\n\n\t\t\/\/ called when plugin is added to a session\n\t\tvirtual void added(boost::weak_ptr<aux::session_impl> s) {}\n\n\t\t\/\/ called when an alert is posted\n\t\t\/\/ alerts that are filtered are not\n\t\t\/\/ posted\n\t\tvirtual void on_alert(alert const* a) {}\n\n\t\t\/\/ called once per second\n\t\tvirtual void on_tick() {}\n\n\t\t\/\/ called when saving settings state\n\t\tvirtual void save_state(entry& ent) const {}\n\n\t\t\/\/ called when loading settings state\n\t\tvirtual void load_state(lazy_entry const& ent) {}\n\t};\n\n\tstruct TORRENT_EXPORT torrent_plugin\n\t{\n\t\tvirtual ~torrent_plugin() {}\n\t\t\/\/ throwing an exception closes the connection\n\t\t\/\/ returning a 0 pointer is valid and will not add\n\t\t\/\/ the peer_plugin to the peer_connection\n\t\tvirtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)\n\t\t{ return boost::shared_ptr<peer_plugin>(); }\n\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ if true is returned, it means the handler handled the event,\n\t\t\/\/ and no other plugins will have their handlers called, and the\n\t\t\/\/ default behavior will be skipped\n\t\tvirtual bool on_pause() { return false; }\n\t\tvirtual bool on_resume() { return false; }\n\n\t\t\/\/ this is called when the initial checking of\n\t\t\/\/ files is completed.\n\t\tvirtual void on_files_checked() {}\n\n\t\t\/\/ called when the torrent changes state\n\t\t\/\/ the state is one of torrent_status::state_t\n\t\t\/\/ enum members\n\t\tvirtual void on_state(int s) {}\n\t};\n\n\tstruct TORRENT_EXPORT peer_plugin\n\t{\n\t\tvirtual ~peer_plugin() {}\n\n\t\tvirtual char const* type() const { return \"\"; }\n\n\t\t\/\/ can add entries to the extension handshake\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual void add_handshake(entry&) {}\n\t\t\n\t\t\/\/ throwing an exception from any of the handlers (except add_handshake)\n\t\t\/\/ closes the connection\n\t\t\n\t\t\/\/ this is called when the initial BT handshake is received. Returning false\n\t\t\/\/ means that the other end doesn't support this extension and will remove\n\t\t\/\/ it from the list of plugins.\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_handshake(char const* reserved_bits) { return true; }\n\t\t\n\t\t\/\/ called when the extension handshake from the other end is received\n\t\t\/\/ if this returns false, it means that this extension isn't\n\t\t\/\/ supported by this peer. It will result in this peer_plugin\n\t\t\/\/ being removed from the peer_connection and destructed. \n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extension_handshake(lazy_entry const& h) { return true; }\n\n\t\t\/\/ returning true from any of the message handlers\n\t\t\/\/ indicates that the plugin has handeled the message.\n\t\t\/\/ it will break the plugin chain traversing and not let\n\t\t\/\/ anyone else handle the message, including the default\n\t\t\/\/ handler.\n\n\t\tvirtual bool on_choke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_unchoke()\n\t\t{ return false; }\n\n\t\tvirtual bool on_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_not_interested()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_bitfield(bitfield const& bitfield)\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_all()\n\t\t{ return false; }\n\n\t\tvirtual bool on_have_none()\n\t\t{ return false; }\n\n\t\tvirtual bool on_allowed_fast(int index)\n\t\t{ return false; }\n\n\t\tvirtual bool on_request(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)\n\t\t{ return false; }\n\n\t\tvirtual bool on_cancel(peer_request const& req)\n\t\t{ return false; }\n\t\n\t\tvirtual bool on_reject(peer_request const& req)\n\t\t{ return false; }\n\n\t\tvirtual bool on_suggest(int index)\n\t\t{ return false; }\n\n\t\t\/\/ called when an extended message is received. If returning true,\n\t\t\/\/ the message is not processed by any other plugin and if false\n\t\t\/\/ is returned the next plugin in the chain will receive it to\n\t\t\/\/ be able to handle it\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_extended(int length\n\t\t\t, int msg, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ this is not called for web seeds\n\t\tvirtual bool on_unknown_message(int length, int msg\n\t\t\t, buffer::const_interval body)\n\t\t{ return false; }\n\n\t\t\/\/ called when a piece that this peer participated in either\n\t\t\/\/ fails or passes the hash_check\n\t\tvirtual void on_piece_pass(int index) {}\n\t\tvirtual void on_piece_failed(int index) {}\n\n\t\t\/\/ called aproximately once every second\n\t\tvirtual void tick() {}\n\n\t\t\/\/ called each time a request message is to be sent. If true\n\t\t\/\/ is returned, the original request message won't be sent and\n\t\t\/\/ no other plugin will have this function called.\n\t\tvirtual bool write_request(peer_request const& r) { return false; }\n\t};\n\n}\n\n#endif\n\n#endif \/\/ TORRENT_EXTENSIONS_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/\/- Standard Library -\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <vector>\n#include <algorithm>\n\n\/\/- Beach Judge -\n#include <BeachJudge\/Base.h>\n#include <BeachJudge\/Page.h>\n\nusing namespace std;\n\nconst char *includePrefix = \"..\/www\/\";\n\nnamespace beachjudge\n{\n\tmap<string, Page *> g_pageMap;\n\tmap<string, void (*)(stringstream &, Socket *, Session *, std::string)> g_templateMap;\n\n\tvoid Page::RegisterTemplate(string entry, void (*func)(stringstream &, Socket *, Session *, string))\n\t{\n\t\tg_templateMap[entry] = func;\n\t}\n\tvoid Page::RegisterDefaultTemplates()\n\t{\n\t}\n\tPage *Page::Create(string file)\n\t{\n\t\tif(!fileExists(file.c_str()))\n\t\t\treturn 0;\n\n\t\tif(g_pageMap.count(file))\n\t\t\treturn g_pageMap[file];\n\n\t\tstring html, lineIn;\n\t\tifstream inFile(file.c_str());\n\t\twhile(getline(inFile, lineIn))\n\t\t{\n\t\t\thtml = html.append(lineIn);\n\t\t\thtml = html.append(\"\\r\\n\");\n\t\t}\n\n\t\tPage *page = new Page();\n\t\tpage->m_fileSource = file;\n\t\tpage->m_html = html;\n\t\tg_pageMap[file] = page;\n\t\treturn page;\n\t}\n\tvoid Page::Cleanup()\n\t{\n\t\twhile(g_pageMap.size())\n\t\t\tdelete g_pageMap.begin()->second;\n\t}\n\n\tPage::Page()\n\t{\n\t}\n\tPage::~Page()\n\t{\n\t\tg_pageMap.erase(m_fileSource);\n\t}\n\tvoid Page::AddToStream(stringstream &stream, Socket *client, Session *session, map<string, string> *masterLocalVars)\n\t{\n\t\tstringstream pageStream(m_html);\n\t\tstring chunk, varChunk, arg, val;\n\t\tvector<string> ifStack;\n\t\tmap<string, string> localVars;\n\n\t\twhile(getline(pageStream, chunk, '$'))\n\t\t{\n\t\t\tbool valid = true;\n\t\t\tif(ifStack.size())\n\t\t\t{\n\t\t\t\tif(session)\n\t\t\t\t{\n\t\t\t\t\tfor(vector<string>::iterator it = ifStack.begin(); it != ifStack.end(); it++)\n\t\t\t\t\t\tif(session->GetVariable(*it) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(ifStack.front().compare(\"loggedOut\"))\n\t\t\t\t\tvalid = false;\n\t\t\t}\n\n\t\t\tif(valid)\n\t\t\t\tstream << chunk;\n\n\t\t\tif(pageStream.eof())\n\t\t\t\tbreak;\n\n\t\t\tvarChunk = \"\";\n\t\t\twhile(true)\n\t\t\t{\n\t\t\t\tchar peek = pageStream.peek();\n\t\t\t\tif((peek >= 'A' && peek <= 'Z') || (peek >= 'a' && peek <= 'z'))\n\t\t\t\t{\n\t\t\t\t\tvarChunk.push_back(peek);\n\t\t\t\t\tpageStream.get();\n\t\t\t\t}\n\t\t\t\telse if(peek == ':')\n\t\t\t\t{\n\t\t\t\t\targ = \"\";\n\t\t\t\t\tpageStream.get();\n\t\t\t\t\twhile(true)\n\t\t\t\t\t{\n\t\t\t\t\t\tchar argPeek = pageStream.peek();\n\t\t\t\t\t\tif((argPeek >= 'A' && argPeek <= 'Z') || (argPeek >= 'a' && argPeek <= 'z') || argPeek == '.' || argPeek == '\/')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\targ.push_back(argPeek);\n\t\t\t\t\t\t\tpageStream.get();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(argPeek == '=')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tval = \"\";\n\t\t\t\t\t\t\tpageStream.get();\n\t\t\t\t\t\t\twhile(true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tchar valPeek = pageStream.peek();\n\t\t\t\t\t\t\t\tif((valPeek >= 'A' && valPeek <= 'Z') || (valPeek >= 'a' && valPeek <= 'z') || (valPeek >= '0' && valPeek <= '9') || valPeek == '.' || valPeek == '\/' || valPeek == ' ')\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tval.push_back(valPeek);\n\t\t\t\t\t\t\t\t\tpageStream.get();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tif(!varChunk.compare(\"if\"))\n\t\t\t\tifStack.push_back(arg);\n\t\t\telse if(!varChunk.compare(\"endif\"))\n\t\t\t\tifStack.erase(find(ifStack.begin(), ifStack.end(), arg));\n\t\t\telse if(!varChunk.compare(\"set\"))\n\t\t\t{\n\t\t\t\tif(arg.size() && val.size())\n\t\t\t\t{\n\t\t\t\t\tif(masterLocalVars)\n\t\t\t\t\t\tmasterLocalVars->operator[](arg) = val;\n\t\t\t\t\telse\n\t\t\t\t\t\tlocalVars[arg] = val;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tstream << \"$\" << varChunk << \":\" << arg << \"=\" << val;\n\t\t\t}\n\t\t\telse if(!varChunk.compare(\"get\"))\n\t\t\t{\n\t\t\t\tbool fail = false;\n\t\t\t\tif(masterLocalVars)\n\t\t\t\t{\n\t\t\t\t\tif(masterLocalVars->count(arg))\n\t\t\t\t\t\tstream << masterLocalVars->operator[](arg);\n\t\t\t\t\telse\n\t\t\t\t\t\tfail = true;\n\t\t\t\t}\n\t\t\t\telse if(localVars.count(arg))\n\t\t\t\t\tstream << localVars[arg];\n\t\t\t\telse\n\t\t\t\t\tfail = true;\n\n\t\t\t\tif(fail)\n\t\t\t\t\tstream << \"$\" << varChunk << \":\" << arg;\n\t\t\t}\n\t\t\telse if(!varChunk.compare(\"include\"))\n\t\t\t{\n\t\t\t\tstring file(includePrefix);\n\t\t\t\tfile.append(arg);\n\t\t\t\tif(fileExists(file.c_str()))\n\t\t\t\t{\n\t\t\t\t\tPage *page = Page::Create(file);\n\t\t\t\t\tpage->AddToStream(stream, client, session, &localVars);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(valid)\n\t\t\t{\n\t\t\t\tif(g_templateMap.count(varChunk))\n\t\t\t\t\tg_templateMap[varChunk](stream, client, session, arg);\n\t\t\t\telse\n\t\t\t\t\tstream << \"$\" << varChunk;\n\t\t\t}\n\t\t}\n\n\t\tdelete this;\n\t}\n}\n<commit_msg>Addressed Page generation bug with includes<commit_after>\/\/- Standard Library -\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <vector>\n#include <algorithm>\n\n\/\/- Beach Judge -\n#include <BeachJudge\/Base.h>\n#include <BeachJudge\/Page.h>\n\nusing namespace std;\n\nconst char *includePrefix = \"..\/www\/\";\n\nnamespace beachjudge\n{\n\tmap<string, Page *> g_pageMap;\n\tmap<string, void (*)(stringstream &, Socket *, Session *, std::string)> g_templateMap;\n\n\tvoid Page::RegisterTemplate(string entry, void (*func)(stringstream &, Socket *, Session *, string))\n\t{\n\t\tg_templateMap[entry] = func;\n\t}\n\tvoid Page::RegisterDefaultTemplates()\n\t{\n\t}\n\tPage *Page::Create(string file)\n\t{\n\t\tif(!fileExists(file.c_str()))\n\t\t\treturn 0;\n\n\t\tif(g_pageMap.count(file))\n\t\t\treturn g_pageMap[file];\n\n\t\tstring html, lineIn;\n\t\tifstream inFile(file.c_str());\n\t\twhile(getline(inFile, lineIn))\n\t\t{\n\t\t\thtml = html.append(lineIn);\n\t\t\thtml = html.append(\"\\r\\n\");\n\t\t}\n\n\t\tPage *page = new Page();\n\t\tpage->m_fileSource = file;\n\t\tpage->m_html = html;\n\t\tg_pageMap[file] = page;\n\t\treturn page;\n\t}\n\tvoid Page::Cleanup()\n\t{\n\t\twhile(g_pageMap.size())\n\t\t\tdelete g_pageMap.begin()->second;\n\t}\n\n\tPage::Page()\n\t{\n\t}\n\tPage::~Page()\n\t{\n\t\tg_pageMap.erase(m_fileSource);\n\t}\n\tvoid Page::AddToStream(stringstream &stream, Socket *client, Session *session, map<string, string> *masterLocalVars)\n\t{\n\t\tstringstream pageStream(m_html);\n\t\tstring chunk, varChunk, arg, val;\n\t\tvector<string> ifStack;\n\t\tmap<string, string> localVars;\n\n\t\twhile(getline(pageStream, chunk, '$'))\n\t\t{\n\t\t\tbool valid = true;\n\t\t\tif(ifStack.size())\n\t\t\t{\n\t\t\t\tif(session)\n\t\t\t\t{\n\t\t\t\t\tfor(vector<string>::iterator it = ifStack.begin(); it != ifStack.end(); it++)\n\t\t\t\t\t\tif(session->GetVariable(*it) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(ifStack.front().compare(\"loggedOut\"))\n\t\t\t\t\tvalid = false;\n\t\t\t}\n\n\t\t\tif(valid)\n\t\t\t\tstream << chunk;\n\n\t\t\tif(pageStream.eof())\n\t\t\t\tbreak;\n\n\t\t\tvarChunk = \"\";\n\t\t\twhile(true)\n\t\t\t{\n\t\t\t\tchar peek = pageStream.peek();\n\t\t\t\tif((peek >= 'A' && peek <= 'Z') || (peek >= 'a' && peek <= 'z'))\n\t\t\t\t{\n\t\t\t\t\tvarChunk.push_back(peek);\n\t\t\t\t\tpageStream.get();\n\t\t\t\t}\n\t\t\t\telse if(peek == ':')\n\t\t\t\t{\n\t\t\t\t\targ = \"\";\n\t\t\t\t\tpageStream.get();\n\t\t\t\t\twhile(true)\n\t\t\t\t\t{\n\t\t\t\t\t\tchar argPeek = pageStream.peek();\n\t\t\t\t\t\tif((argPeek >= 'A' && argPeek <= 'Z') || (argPeek >= 'a' && argPeek <= 'z') || argPeek == '.' || argPeek == '\/')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\targ.push_back(argPeek);\n\t\t\t\t\t\t\tpageStream.get();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(argPeek == '=')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tval = \"\";\n\t\t\t\t\t\t\tpageStream.get();\n\t\t\t\t\t\t\twhile(true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tchar valPeek = pageStream.peek();\n\t\t\t\t\t\t\t\tif((valPeek >= 'A' && valPeek <= 'Z') || (valPeek >= 'a' && valPeek <= 'z') || (valPeek >= '0' && valPeek <= '9') || valPeek == '.' || valPeek == '\/' || valPeek == ' ')\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tval.push_back(valPeek);\n\t\t\t\t\t\t\t\t\tpageStream.get();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tif(!varChunk.compare(\"if\"))\n\t\t\t\tifStack.push_back(arg);\n\t\t\telse if(!varChunk.compare(\"endif\"))\n\t\t\t\tifStack.erase(find(ifStack.begin(), ifStack.end(), arg));\n\t\t\telse if(valid)\n\t\t\t{\n\t\t\t\tif(!varChunk.compare(\"set\"))\n\t\t\t\t{\n\t\t\t\t\tif(arg.size() && val.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tif(masterLocalVars)\n\t\t\t\t\t\t\tmasterLocalVars->operator[](arg) = val;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tlocalVars[arg] = val;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tstream << \"$\" << varChunk << \":\" << arg << \"=\" << val;\n\t\t\t\t}\n\t\t\t\telse if(!varChunk.compare(\"get\"))\n\t\t\t\t{\n\t\t\t\t\tbool fail = false;\n\t\t\t\t\tif(masterLocalVars)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(masterLocalVars->count(arg))\n\t\t\t\t\t\t\tstream << masterLocalVars->operator[](arg);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tfail = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if(localVars.count(arg))\n\t\t\t\t\t\tstream << localVars[arg];\n\t\t\t\t\telse\n\t\t\t\t\t\tfail = true;\n\n\t\t\t\t\tif(fail)\n\t\t\t\t\t\tstream << \"$\" << varChunk << \":\" << arg;\n\t\t\t\t}\n\t\t\t\telse if(!varChunk.compare(\"include\"))\n\t\t\t\t{\n\t\t\t\t\tstring file(includePrefix);\n\t\t\t\t\tfile.append(arg);\n\t\t\t\t\tif(fileExists(file.c_str()))\n\t\t\t\t\t{\n\t\t\t\t\t\tPage *page = Page::Create(file);\n\t\t\t\t\t\tpage->AddToStream(stream, client, session, &localVars);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(g_templateMap.count(varChunk))\n\t\t\t\t\tg_templateMap[varChunk](stream, client, session, arg);\n\t\t\t\telse\n\t\t\t\t\tstream << \"$\" << varChunk;\n\t\t\t}\n\t\t}\n\n\t\tdelete this;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\n\/*\n * Main authors:\n * Guido Tack <guido.tack@monash.edu>\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n \n#include <iostream>\n#include <fstream>\n\n#include <minizinc\/model.hh>\n#include <minizinc\/parser.hh>\n#include <minizinc\/prettyprinter.hh>\n#include <minizinc\/typecheck.hh>\n#include <minizinc\/exception.hh>\n\n#include <minizinc\/flatten.hh>\n#include <minizinc\/optimize.hh>\n#include <minizinc\/builtins.hh>\n\nusing namespace MiniZinc;\nusing namespace std;\n\nint main(int argc, char** argv) {\n int i=1;\n string filename;\n vector<string> datafiles;\n vector<string> includePaths; \n bool flag_ignoreStdlib = false;\n bool flag_typecheck = true;\n bool flag_eval = true;\n bool flag_output = true;\n bool flag_verbose = false;\n bool flag_newfzn = false;\n bool flag_optimize = true;\n if (argc < 2)\n goto error;\n\n GC::init();\n\n for (;;) {\n if (string(argv[i])==string(\"-h\") || string(argv[i])==string(\"--help\"))\n goto error;\n if (string(argv[i])==string(\"-I\")) {\n i++;\n if (i==argc) {\n goto error;\n }\n includePaths.push_back(argv[i]+string(\"\/\"));\n } else if (string(argv[i])==string(\"--ignore-stdlib\")) {\n flag_ignoreStdlib = true;\n } else if (string(argv[i])==string(\"--no-output\")) {\n flag_output = false;\n } else if (string(argv[i])==string(\"--no-typecheck\")) {\n flag_typecheck = false; flag_eval=false;\n } else if (string(argv[i])==string(\"--no-eval\")) {\n flag_eval = false;\n } else if (string(argv[i])==string(\"--verbose\")) {\n flag_verbose = true;\n } else if (string(argv[i])==string(\"--newfzn\")) {\n flag_newfzn = true;\n } else if (string(argv[i])==string(\"--no-optimize\")) {\n flag_optimize = false;\n } else {\n break;\n }\n i++;\n }\n\n if (i==argc) {\n goto error;\n }\n filename = argv[i++];\n \n while (i<argc)\n datafiles.push_back(argv[i++]);\n\n {\n if (flag_verbose)\n std::cerr << \"Parsing '\" << filename << \"' ...\" << std::endl;\n if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib, \n std::cerr)) {\n try {\n if (flag_typecheck) {\n if (flag_verbose)\n std::cerr << \"Typechecking...\" << std::endl;\n MiniZinc::typecheck(m);\n MiniZinc::registerBuiltins(m);\n\n if (flag_verbose)\n std::cerr << \"Flattening...\" << std::endl;\n Model* flat = flatten(m);\n\n if (flag_optimize) {\n if (flag_verbose)\n std::cerr << \"Optimizing...\" << std::endl;\n optimize(flat);\n }\n\n if (flag_output) {\n if (!flag_newfzn) {\n if (flag_verbose)\n std::cerr << \"Converting to old FlatZinc...\" << std::endl;\n oldflatzinc(flat);\n }\n\n if (flag_verbose)\n std::cerr << \"Printing FlatZinc...\" << std::endl;\n Printer p;\n p.print(flat,std::cout);\n }\n delete flat;\n } else if (flag_output) { \/\/ !flag_typecheck\n Printer p;\n p.print(m,std::cout);\n }\n } catch (LocationException& e) {\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n std::cerr << e.loc() << std::endl;\n exit(EXIT_FAILURE);\n } catch (Exception& e) {\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n exit(EXIT_FAILURE);\n }\n delete m;\n }\n }\n\n if (flag_verbose)\n std::cerr << \"Done.\" << std::endl;\n return 0;\n\nerror:\n std::cerr << \"Usage: \"<< argv[0]\n << \" [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \"\\t--help -h\\tPrint this help message\" << std::endl\n << \"\\t--ignore-stdlib\\tIgnore the standard libraries stdlib.mzn and builtins.mzn\" << std::endl\n << \"\\t--newfzn\\tOutput in the new FlatZinc format\" << std::endl\n << \"\\t--verbose\\tPrint progress statements\" << std::endl\n << \"\\t--no-typecheck\\tDo not typecheck (implies --no-eval)\" << std::endl\n << \"\\t--no-eval\\tDo not evaluate\" << std::endl\n << \"\\t--no-optimize\\tDo not optimize the FlatZinc (may speed up large instances)\" << std::endl\n << \"\\t--no-output\\tDo not print the output\" << std::endl;\n\n exit(EXIT_FAILURE);\n}\n<commit_msg>Use the simple pretty printer for outputting flatzinc<commit_after>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\n\/*\n * Main authors:\n * Guido Tack <guido.tack@monash.edu>\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n \n#include <iostream>\n#include <fstream>\n\n#include <minizinc\/model.hh>\n#include <minizinc\/parser.hh>\n#include <minizinc\/prettyprinter.hh>\n#include <minizinc\/typecheck.hh>\n#include <minizinc\/exception.hh>\n\n#include <minizinc\/flatten.hh>\n#include <minizinc\/optimize.hh>\n#include <minizinc\/builtins.hh>\n\nusing namespace MiniZinc;\nusing namespace std;\n\nint main(int argc, char** argv) {\n int i=1;\n string filename;\n vector<string> datafiles;\n vector<string> includePaths; \n bool flag_ignoreStdlib = false;\n bool flag_typecheck = true;\n bool flag_eval = true;\n bool flag_output = true;\n bool flag_verbose = false;\n bool flag_newfzn = false;\n bool flag_optimize = true;\n if (argc < 2)\n goto error;\n\n GC::init();\n\n for (;;) {\n if (string(argv[i])==string(\"-h\") || string(argv[i])==string(\"--help\"))\n goto error;\n if (string(argv[i])==string(\"-I\")) {\n i++;\n if (i==argc) {\n goto error;\n }\n includePaths.push_back(argv[i]+string(\"\/\"));\n } else if (string(argv[i])==string(\"--ignore-stdlib\")) {\n flag_ignoreStdlib = true;\n } else if (string(argv[i])==string(\"--no-output\")) {\n flag_output = false;\n } else if (string(argv[i])==string(\"--no-typecheck\")) {\n flag_typecheck = false; flag_eval=false;\n } else if (string(argv[i])==string(\"--no-eval\")) {\n flag_eval = false;\n } else if (string(argv[i])==string(\"--verbose\")) {\n flag_verbose = true;\n } else if (string(argv[i])==string(\"--newfzn\")) {\n flag_newfzn = true;\n } else if (string(argv[i])==string(\"--no-optimize\")) {\n flag_optimize = false;\n } else {\n break;\n }\n i++;\n }\n\n if (i==argc) {\n goto error;\n }\n filename = argv[i++];\n \n while (i<argc)\n datafiles.push_back(argv[i++]);\n\n {\n if (flag_verbose)\n std::cerr << \"Parsing '\" << filename << \"' ...\" << std::endl;\n if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib, \n std::cerr)) {\n try {\n if (flag_typecheck) {\n if (flag_verbose)\n std::cerr << \"Typechecking...\" << std::endl;\n MiniZinc::typecheck(m);\n MiniZinc::registerBuiltins(m);\n\n if (flag_verbose)\n std::cerr << \"Flattening...\" << std::endl;\n Model* flat = flatten(m);\n\n if (flag_optimize) {\n if (flag_verbose)\n std::cerr << \"Optimizing...\" << std::endl;\n optimize(flat);\n }\n\n if (flag_output) {\n if (!flag_newfzn) {\n if (flag_verbose)\n std::cerr << \"Converting to old FlatZinc...\" << std::endl;\n oldflatzinc(flat);\n }\n\n if (flag_verbose)\n std::cerr << \"Printing FlatZinc...\" << std::endl;\n Printer p;\n p.print(flat,std::cout,0);\n }\n delete flat;\n } else if (flag_output) { \/\/ !flag_typecheck\n Printer p;\n p.print(m,std::cout);\n }\n } catch (LocationException& e) {\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n std::cerr << e.loc() << std::endl;\n exit(EXIT_FAILURE);\n } catch (Exception& e) {\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n exit(EXIT_FAILURE);\n }\n delete m;\n }\n }\n\n if (flag_verbose)\n std::cerr << \"Done.\" << std::endl;\n return 0;\n\nerror:\n std::cerr << \"Usage: \"<< argv[0]\n << \" [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \"\\t--help -h\\tPrint this help message\" << std::endl\n << \"\\t--ignore-stdlib\\tIgnore the standard libraries stdlib.mzn and builtins.mzn\" << std::endl\n << \"\\t--newfzn\\tOutput in the new FlatZinc format\" << std::endl\n << \"\\t--verbose\\tPrint progress statements\" << std::endl\n << \"\\t--no-typecheck\\tDo not typecheck (implies --no-eval)\" << std::endl\n << \"\\t--no-eval\\tDo not evaluate\" << std::endl\n << \"\\t--no-optimize\\tDo not optimize the FlatZinc (may speed up large instances)\" << std::endl\n << \"\\t--no-output\\tDo not print the output\" << std::endl;\n\n exit(EXIT_FAILURE);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"physics.h\"\n#include \"GLDebugDrawer.h\"\n#include \"..\/state\/state.h\"\n#include <iostream>\n#include <BulletCollision\/CollisionDispatch\/btInternalEdgeUtility.h>\n#include <BulletCollision\/CollisionShapes\/btTriangleShape.h>\n#include <btBulletDynamicsCommon.h>\n\nusing namespace Physics;\n\nSimulation::Simulation()\n{\n\tm_broadphase = new btDbvtBroadphase();\n\tm_collisionConfiguration = new btDefaultCollisionConfiguration();\n\tm_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);\n\tm_solver = new btSequentialImpulseConstraintSolver;\n\tm_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);\n\n\tm_world->setGravity(btVector3(0,-5,0));\n\n\tmb.request(Events::EventType::Input);\n}\n\nSimulation::~Simulation()\n{\n\t\/*\n\tdelete m_world;\n\tdelete m_solver;\n\tdelete m_broadphase;\n\tdelete m_dispatcher;\n\tdelete m_collisionConfiguration;\n\t*\/\n}\n\n\/\/ Tuning\n\/\/ Credit to:\n\/\/ http:\/\/bullet.googlecode.com\/svn-history\/r2704\/trunk\/Demos\/ForkLiftDemo\/ForkLiftDemo.cpp\n\/\/ Also:\n\/\/ https:\/\/code.google.com\/p\/bullet\/source\/browse\/trunk\/Demos\/VehicleDemo\/VehicleDemo.cpp\n\nfloat\tgVehicleSteering = 0.0f;\nfloat\tgEngineForce = 0.0f;\nfloat\tgBrakingForce = 0.0f;\n\nfloat\twheelFriction = 5;\nfloat\tsuspensionStiffness = 10;\nfloat\tsuspensionDamping = 0.5f;\nfloat\tsuspensionCompression = 0.3f;\nfloat\trollInfluence = 0.015f; \/\/ Keep low to prevent car flipping\n\nbtScalar suspensionRestLength(0.1f);\/\/ Suspension Interval = rest +\/- travel * 0.01\nfloat\tsuspensionTravelcm = 20;\n\nbtRigidBody *Simulation::addRigidBody(double mass, const btTransform& startTransform, btCollisionShape* shape)\n{\n\tbtVector3 localInertia(0, 0, 0);\n\tif (mass != 0.0) {\n\t\tshape->calculateLocalInertia((btScalar)mass, localInertia);\n\t}\t\n\n\tbtDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);\n\t\n\tbtRigidBody::btRigidBodyConstructionInfo cInfo((btScalar)mass,myMotionState,shape,localInertia);\n\t\n\tbtRigidBody* body = new btRigidBody(cInfo);\n\tbody->setContactProcessingThreshold(0.1f);\n\t\n\tm_world->addRigidBody(body);\n\n\treturn body;\n}\n\nstatic bool CustomMaterialCombinerCallback(btManifoldPoint& cp,\tconst btCollisionObjectWrapper* colObj0Wrap,int partId0,int index0,const btCollisionObjectWrapper* colObj1Wrap,int partId1,int index1)\n{\n\tbtAdjustInternalEdgeContacts(cp,colObj1Wrap,colObj0Wrap, partId1,index1);\n\treturn true;\n}\n\nextern ContactAddedCallback gContactAddedCallback;\n\nint Simulation::loadWorld()\n{\n\t\/\/ Create car\n#define CAR_WIDTH (0.11f)\n#define CAR_LENGTH (0.15f)\n#define CAR_MASS (800.0f)\n\n\tbtCollisionShape* chassisShape = new btBoxShape(btVector3(CAR_WIDTH, CAR_WIDTH, CAR_LENGTH));\n\tbtCompoundShape* compound = new btCompoundShape();\n\tm_collisionShapes.push_back(chassisShape);\n\tm_collisionShapes.push_back(compound);\n\n\tbtTransform localTrans;\n\tlocalTrans.setIdentity();\n\tlocalTrans.setOrigin(btVector3(0,0.05f, 0));\n\tcompound->addChildShape(localTrans, chassisShape);\n\n\tbtTransform tr;\n\ttr.setIdentity();\n\ttr.setOrigin(btVector3(0,2,0));\t\t\/\/ This sets where the car initially spawns\n\tm_carChassis = addRigidBody(CAR_MASS, tr, compound);\n\n\tm_vehicleRayCaster = new btDefaultVehicleRaycaster(m_world);\n\n\tm_vehicle = new btRaycastVehicle(m_tuning,m_carChassis, m_vehicleRayCaster);\n\tm_carChassis->setActivationState(DISABLE_DEACTIVATION);\n\tm_vehicle->setCoordinateSystem(0,1,0);\n\tm_world->addVehicle(m_vehicle);\n\n\tfloat connectionHeight = 0.10f;\n\tbtVector3 wheelDirectionCS0(0,-1,0);\n\tbtVector3 wheelAxleCS(-1,0,0);\n\n#define CON1 (CAR_WIDTH)\n#define CON2 (CAR_LENGTH)\n\n\tfloat\twheelRadius = 0.15f;\n\t\n\t\/\/ Setup front 2 wheels\n\tbool isFrontWheel=true;\n\tbtVector3 connectionPointCS0(CON1,connectionHeight,CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\tconnectionPointCS0 = btVector3(-CON1,connectionHeight,CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\t\/\/ Setup rear 2 wheels\n\tisFrontWheel = false;\n\n\tconnectionPointCS0 = btVector3(-CON1,connectionHeight,-CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\tconnectionPointCS0 = btVector3(CON1,connectionHeight,-CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\t\n\n\tfor (int i=0;i<m_vehicle->getNumWheels();i++)\n\t{\n\t\tbtWheelInfo& wheel = m_vehicle->getWheelInfo(i);\n\t\t\n\t\twheel.m_maxSuspensionTravelCm = suspensionTravelcm;\n\t\twheel.m_suspensionStiffness = suspensionStiffness;\n\t\twheel.m_wheelsDampingRelaxation = suspensionDamping;\n\t\twheel.m_wheelsDampingCompression = suspensionCompression;\n\t\twheel.m_frictionSlip = wheelFriction;\n\t\twheel.m_rollInfluence = rollInfluence;\n\n\t\t\n\t}\n\n\t\/\/ Add map\n\t\/\/ Credit to http:\/\/bulletphysics.org\/Bullet\/phpBB3\/viewtopic.php?t=6662\n\t\/\/ for solution to wheels bouncing off triangle edges\n\tgContactAddedCallback = CustomMaterialCombinerCallback;\n\tStateData *state = GetMutState();\n\tbtBvhTriangleMeshShape *arenaShape = new btBvhTriangleMeshShape(state->bttmArena, true, true);\n\n\tm_arena = addRigidBody(0.0, btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), arenaShape);\n\tm_arena->setCollisionFlags(m_arena->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);\n\tbtTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();\n\tbtGenerateInternalEdgeInfo(arenaShape, triangleInfoMap);\n\n\tfor (int i=0;i<m_vehicle->getNumWheels();i++)\n\t{\n\t\t\/\/synchronize the wheels with the (interpolated) chassis worldtransform\n\t\tm_vehicle->updateWheelTransform(i,true);\n\t}\n\n\treturn 0;\n}\n\nvoid Simulation::step(double seconds)\n{\n#define STEER_MAX_ANGLE (25)\n#define ENGINE_MAX_FORCE (1500)\n#define BRAKE_MAX_FORCE (1000)\n#define E_BRAKE_FORCE (200)\n#define MAX_SPEED (25.0)\n\n\tfor ( Events::Event *event : (mb.checkMail()) )\n\t{\n\t\tswitch ( event->type )\n\t\t{\n\t\tcase Events::EventType::Input:\n\t\t{\n\t\t\tEvents::InputEvent *input = (Events::InputEvent *)event;\n\n\t\t\tReal fTurnSqr = pow(input->leftThumbStickRL, 8);\n\t\t\tgVehicleSteering = DEGTORAD(STEER_MAX_ANGLE) * ( input->leftThumbStickRL < 0 ? -fTurnSqr : fTurnSqr );\n\n\t\t\tgBrakingForce = input->bPressed ? E_BRAKE_FORCE : 0;\n\t\t\tgEngineForce = ENGINE_MAX_FORCE * input->rightTrigger - BRAKE_MAX_FORCE * input->leftTrigger;\n\n\t\t\tif( GetState().key_map['r'] )\n\t\t\t{\n\t\t\t\tbtTransform trans;\n\t\t\t\ttrans.setOrigin( btVector3( 0, 5, 0 ) );\n\t\t\t\ttrans.setRotation( btQuaternion( 0, 0, 0, 1 ) );\n\t\t\t\tm_vehicle->getRigidBody()->setWorldTransform( trans );\n\t\t\t\tm_vehicle->getRigidBody()->setLinearVelocity(btVector3(0,0,0));\n\t\t\t}\n\n\t\t\tif( input->yPressed )\n\t\t\t{\n\t\t\t\tbtTransform trans = m_vehicle->getRigidBody()->getWorldTransform();\n\t\t\t\tbtVector3 orig = trans.getOrigin();\n\t\t\t\torig.setY( orig.getY() + 0.01f );\n\t\t\t\ttrans.setOrigin( orig );\n\t\t\t\ttrans.setRotation( btQuaternion( 0, 0, 0, 1 ) );\n\t\t\t\tm_vehicle->getRigidBody()->setWorldTransform( trans );\n\t\t\t}\n\n\/\/\t\t\tDEBUGOUT(\"Bforce: %lf, Eforce: %lf, Steer: %f\\n\", gBrakingForce, gEngineForce, gVehicleSteering);\n\/\/\t\t\tDEBUGOUT(\"Speed: %f\\n\", (float)ABS( m_vehicle->getCurrentSpeedKmHour() ) );\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\tmb.emptyMail();\n\n\tif( ABS( m_vehicle->getCurrentSpeedKmHour() ) > MAX_SPEED )\n\t\tgEngineForce = 0;\n\n\t\/\/ Apply steering to front wheels\n\tm_vehicle->setSteeringValue(gVehicleSteering, 0);\n\tm_vehicle->setSteeringValue(gVehicleSteering, 1);\n\n\t\/\/ Apply braking and engine force to rear wheels\n\tm_vehicle->applyEngineForce(gEngineForce, 0);\n\tm_vehicle->applyEngineForce(gEngineForce, 1);\n\tm_vehicle->setBrake(gBrakingForce, 2);\n\tm_vehicle->setBrake(gBrakingForce, 3);\n\n\tm_world->stepSimulation((btScalar)seconds, 10);\n\n\tif( m_vehicle->getRigidBody()->getWorldTransform().getOrigin().y() < -1.0f )\n\t{\n\t\tbtTransform trans;\n\t\ttrans.setOrigin( btVector3( 0, 5, 0 ) );\n\t\ttrans.setRotation( btQuaternion( 0, 0, 0, 1 ) );\n\t\tm_vehicle->getRigidBody()->setWorldTransform( trans );\n\t\tm_vehicle->getRigidBody()->setLinearVelocity(btVector3(0,0,0));\n\t}\n\n\tUpdateGameState(seconds);\n}\n\n\/\/ Updates the car placement in the world state\nvoid Simulation::UpdateGameState(double seconds)\n{\n\t\/\/ -- Kart position ------------------------\n\tStateData *state = GetMutState();\n\tbtTransform car1 = m_vehicle->getChassisWorldTransform();\n\n\tbtVector3 pos = car1.getOrigin();\n\tstate->Karts[0].vPos.x = (Real)pos.getX();\n\tstate->Karts[0].vPos.y = (Real)pos.getY();\n\tstate->Karts[0].vPos.z = (Real)pos.getZ();\n\n\tbtQuaternion rot = car1.getRotation();\n\tstate->Karts[0].qOrient.x = (Real)rot.getX();\n\tstate->Karts[0].qOrient.y = (Real)rot.getY();\n\tstate->Karts[0].qOrient.z = (Real)rot.getZ();\n\tstate->Karts[0].qOrient.w = (Real)-rot.getW();\n\n\t\/\/ -- Chase Cam ----------------------------\n\t\/\/ Get car direction\n\tbtVector3 dir = m_vehicle->getForwardVector() \/ m_vehicle->getForwardVector().length();\n\tbtVector3 camera = dir.rotate(btVector3(0,1,0), DEGTORAD(90)); \/\/ forward vector points left, somehow\n\n\n\tif (camera.getY() < 0.4) {\n\t\tcamera.setY(0.4);\n\t}\n\n\t\/\/ Mixin car direction history\n\tReal DIR_DROPOFF = 3 * seconds;\n\tstatic btVector3 dir_history = camera;\n\tdir_history *= (1.0 - DIR_DROPOFF);\n\tdir_history += camera * DIR_DROPOFF;\n\n\tcamera = dir_history;\n\n\t\/\/ Mixin historic speeds\n\tReal SPEED_DROPOFF = 0.1 * seconds;\n\tReal speed = m_vehicle->getCurrentSpeedKmHour();\n\tstatic Real speed_history = speed;\n\tspeed_history *= (1.0 - SPEED_DROPOFF);\n\tspeed_history += speed * SPEED_DROPOFF;\n\n\t\/\/ Make camera focus during acceleration\n\tReal diff = (speed - speed_history) \/ MAX_SPEED;\n\tdiff = diff > 0.0 ? diff : 0;\n\tdiff *= diff;\n\tdiff = (pow(2, diff) - 1) \/ 1;\n\tdiff = MIN(diff, 0.3);\n\tReal DIFF_DROPOFF = 0.1;\n\tstatic Real diff_history = diff * seconds;\n\tif (diff > 0.0) {\n\t\tdiff_history *= (1.0 - DIFF_DROPOFF);\n\t\tdiff_history += diff * DIFF_DROPOFF;\n\t}\n\tdiff = diff_history;\n\n\tcamera.setY((0.9 * (1 - MAX((diff * 3.7), 0.7)) + camera.getY()));\n\tcamera *= 3.0 - diff * 1;\n\tstate->Camera.fFOV = 60.0f * (1 - diff * 1.4);\n\n\t\/\/ Add camera vector to kart position for camera position\n\tstate->Camera.vPos = state->Karts[0].vPos;\n\tstate->Camera.vPos.x += camera.getX();\n\tstate->Camera.vPos.y += camera.getY();\n\tstate->Camera.vPos.z += camera.getZ();\n\n\t\/\/ Focus on car\n\tbtVector3 chase = dir.rotate(btVector3(0,1,0), DEGTORAD(-90)); \/\/ forward vector points left, somehow\n\tchase.setY(0);\n\tbtVector3 focus = pos + chase * (2.0 + speed_history * 6 * (diff -0.1));\n\tReal FOCUS_DROPOFF = seconds * 3;\n\tFOCUS_DROPOFF = MIN(FOCUS_DROPOFF, 1);\n\tstatic btVector3 focus_history = focus;\n\tfocus_history *= (1 - FOCUS_DROPOFF);\n\tfocus_history += focus * FOCUS_DROPOFF;\n\tstate->Camera.vFocus.x = focus_history.getX();\n\tstate->Camera.vFocus.y = focus_history.getY();\n\tstate->Camera.vFocus.z = focus_history.getZ();\n}\n\nvoid Simulation::enableDebugView()\n{\n}\n<commit_msg>Fix car traveling to screen top during tight turns<commit_after>#include \"physics.h\"\n#include \"GLDebugDrawer.h\"\n#include \"..\/state\/state.h\"\n#include <iostream>\n#include <BulletCollision\/CollisionDispatch\/btInternalEdgeUtility.h>\n#include <BulletCollision\/CollisionShapes\/btTriangleShape.h>\n#include <btBulletDynamicsCommon.h>\n\nusing namespace Physics;\n\nSimulation::Simulation()\n{\n\tm_broadphase = new btDbvtBroadphase();\n\tm_collisionConfiguration = new btDefaultCollisionConfiguration();\n\tm_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);\n\tm_solver = new btSequentialImpulseConstraintSolver;\n\tm_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);\n\n\tm_world->setGravity(btVector3(0,-5,0));\n\n\tmb.request(Events::EventType::Input);\n}\n\nSimulation::~Simulation()\n{\n\t\/*\n\tdelete m_world;\n\tdelete m_solver;\n\tdelete m_broadphase;\n\tdelete m_dispatcher;\n\tdelete m_collisionConfiguration;\n\t*\/\n}\n\n\/\/ Tuning\n\/\/ Credit to:\n\/\/ http:\/\/bullet.googlecode.com\/svn-history\/r2704\/trunk\/Demos\/ForkLiftDemo\/ForkLiftDemo.cpp\n\/\/ Also:\n\/\/ https:\/\/code.google.com\/p\/bullet\/source\/browse\/trunk\/Demos\/VehicleDemo\/VehicleDemo.cpp\n\nfloat\tgVehicleSteering = 0.0f;\nfloat\tgEngineForce = 0.0f;\nfloat\tgBrakingForce = 0.0f;\n\nfloat\twheelFriction = 5;\nfloat\tsuspensionStiffness = 10;\nfloat\tsuspensionDamping = 0.5f;\nfloat\tsuspensionCompression = 0.3f;\nfloat\trollInfluence = 0.015f; \/\/ Keep low to prevent car flipping\n\nbtScalar suspensionRestLength(0.1f);\/\/ Suspension Interval = rest +\/- travel * 0.01\nfloat\tsuspensionTravelcm = 20;\n\nbtRigidBody *Simulation::addRigidBody(double mass, const btTransform& startTransform, btCollisionShape* shape)\n{\n\tbtVector3 localInertia(0, 0, 0);\n\tif (mass != 0.0) {\n\t\tshape->calculateLocalInertia((btScalar)mass, localInertia);\n\t}\t\n\n\tbtDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);\n\t\n\tbtRigidBody::btRigidBodyConstructionInfo cInfo((btScalar)mass,myMotionState,shape,localInertia);\n\t\n\tbtRigidBody* body = new btRigidBody(cInfo);\n\tbody->setContactProcessingThreshold(0.1f);\n\t\n\tm_world->addRigidBody(body);\n\n\treturn body;\n}\n\nstatic bool CustomMaterialCombinerCallback(btManifoldPoint& cp,\tconst btCollisionObjectWrapper* colObj0Wrap,int partId0,int index0,const btCollisionObjectWrapper* colObj1Wrap,int partId1,int index1)\n{\n\tbtAdjustInternalEdgeContacts(cp,colObj1Wrap,colObj0Wrap, partId1,index1);\n\treturn true;\n}\n\nextern ContactAddedCallback gContactAddedCallback;\n\nint Simulation::loadWorld()\n{\n\t\/\/ Create car\n#define CAR_WIDTH (0.11f)\n#define CAR_LENGTH (0.15f)\n#define CAR_MASS (800.0f)\n\n\tbtCollisionShape* chassisShape = new btBoxShape(btVector3(CAR_WIDTH, CAR_WIDTH, CAR_LENGTH));\n\tbtCompoundShape* compound = new btCompoundShape();\n\tm_collisionShapes.push_back(chassisShape);\n\tm_collisionShapes.push_back(compound);\n\n\tbtTransform localTrans;\n\tlocalTrans.setIdentity();\n\tlocalTrans.setOrigin(btVector3(0,0.05f, 0));\n\tcompound->addChildShape(localTrans, chassisShape);\n\n\tbtTransform tr;\n\ttr.setIdentity();\n\ttr.setOrigin(btVector3(0,2,0));\t\t\/\/ This sets where the car initially spawns\n\tm_carChassis = addRigidBody(CAR_MASS, tr, compound);\n\n\tm_vehicleRayCaster = new btDefaultVehicleRaycaster(m_world);\n\n\tm_vehicle = new btRaycastVehicle(m_tuning,m_carChassis, m_vehicleRayCaster);\n\tm_carChassis->setActivationState(DISABLE_DEACTIVATION);\n\tm_vehicle->setCoordinateSystem(0,1,0);\n\tm_world->addVehicle(m_vehicle);\n\n\tfloat connectionHeight = 0.10f;\n\tbtVector3 wheelDirectionCS0(0,-1,0);\n\tbtVector3 wheelAxleCS(-1,0,0);\n\n#define CON1 (CAR_WIDTH)\n#define CON2 (CAR_LENGTH)\n\n\tfloat\twheelRadius = 0.15f;\n\t\n\t\/\/ Setup front 2 wheels\n\tbool isFrontWheel=true;\n\tbtVector3 connectionPointCS0(CON1,connectionHeight,CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\tconnectionPointCS0 = btVector3(-CON1,connectionHeight,CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\t\/\/ Setup rear 2 wheels\n\tisFrontWheel = false;\n\n\tconnectionPointCS0 = btVector3(-CON1,connectionHeight,-CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\tconnectionPointCS0 = btVector3(CON1,connectionHeight,-CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\t\n\n\tfor (int i=0;i<m_vehicle->getNumWheels();i++)\n\t{\n\t\tbtWheelInfo& wheel = m_vehicle->getWheelInfo(i);\n\t\t\n\t\twheel.m_maxSuspensionTravelCm = suspensionTravelcm;\n\t\twheel.m_suspensionStiffness = suspensionStiffness;\n\t\twheel.m_wheelsDampingRelaxation = suspensionDamping;\n\t\twheel.m_wheelsDampingCompression = suspensionCompression;\n\t\twheel.m_frictionSlip = wheelFriction;\n\t\twheel.m_rollInfluence = rollInfluence;\n\n\t\t\n\t}\n\n\t\/\/ Add map\n\t\/\/ Credit to http:\/\/bulletphysics.org\/Bullet\/phpBB3\/viewtopic.php?t=6662\n\t\/\/ for solution to wheels bouncing off triangle edges\n\tgContactAddedCallback = CustomMaterialCombinerCallback;\n\tStateData *state = GetMutState();\n\tbtBvhTriangleMeshShape *arenaShape = new btBvhTriangleMeshShape(state->bttmArena, true, true);\n\n\tm_arena = addRigidBody(0.0, btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), arenaShape);\n\tm_arena->setCollisionFlags(m_arena->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);\n\tbtTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();\n\tbtGenerateInternalEdgeInfo(arenaShape, triangleInfoMap);\n\n\tfor (int i=0;i<m_vehicle->getNumWheels();i++)\n\t{\n\t\t\/\/synchronize the wheels with the (interpolated) chassis worldtransform\n\t\tm_vehicle->updateWheelTransform(i,true);\n\t}\n\n\treturn 0;\n}\n\nvoid Simulation::step(double seconds)\n{\n#define STEER_MAX_ANGLE (25)\n#define ENGINE_MAX_FORCE (1500)\n#define BRAKE_MAX_FORCE (1000)\n#define E_BRAKE_FORCE (200)\n#define MAX_SPEED (25.0)\n\n\tfor ( Events::Event *event : (mb.checkMail()) )\n\t{\n\t\tswitch ( event->type )\n\t\t{\n\t\tcase Events::EventType::Input:\n\t\t{\n\t\t\tEvents::InputEvent *input = (Events::InputEvent *)event;\n\n\t\t\tReal fTurnSqr = pow(input->leftThumbStickRL, 8);\n\t\t\tgVehicleSteering = DEGTORAD(STEER_MAX_ANGLE) * ( input->leftThumbStickRL < 0 ? -fTurnSqr : fTurnSqr );\n\n\t\t\tgBrakingForce = input->bPressed ? E_BRAKE_FORCE : 0;\n\t\t\tgEngineForce = ENGINE_MAX_FORCE * input->rightTrigger - BRAKE_MAX_FORCE * input->leftTrigger;\n\n\t\t\tif( GetState().key_map['r'] )\n\t\t\t{\n\t\t\t\tbtTransform trans;\n\t\t\t\ttrans.setOrigin( btVector3( 0, 5, 0 ) );\n\t\t\t\ttrans.setRotation( btQuaternion( 0, 0, 0, 1 ) );\n\t\t\t\tm_vehicle->getRigidBody()->setWorldTransform( trans );\n\t\t\t\tm_vehicle->getRigidBody()->setLinearVelocity(btVector3(0,0,0));\n\t\t\t}\n\n\t\t\tif( input->yPressed )\n\t\t\t{\n\t\t\t\tbtTransform trans = m_vehicle->getRigidBody()->getWorldTransform();\n\t\t\t\tbtVector3 orig = trans.getOrigin();\n\t\t\t\torig.setY( orig.getY() + 0.01f );\n\t\t\t\ttrans.setOrigin( orig );\n\t\t\t\ttrans.setRotation( btQuaternion( 0, 0, 0, 1 ) );\n\t\t\t\tm_vehicle->getRigidBody()->setWorldTransform( trans );\n\t\t\t}\n\n\/\/\t\t\tDEBUGOUT(\"Bforce: %lf, Eforce: %lf, Steer: %f\\n\", gBrakingForce, gEngineForce, gVehicleSteering);\n\/\/\t\t\tDEBUGOUT(\"Speed: %f\\n\", (float)ABS( m_vehicle->getCurrentSpeedKmHour() ) );\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\tmb.emptyMail();\n\n\tif( ABS( m_vehicle->getCurrentSpeedKmHour() ) > MAX_SPEED )\n\t\tgEngineForce = 0;\n\n\t\/\/ Apply steering to front wheels\n\tm_vehicle->setSteeringValue(gVehicleSteering, 0);\n\tm_vehicle->setSteeringValue(gVehicleSteering, 1);\n\n\t\/\/ Apply braking and engine force to rear wheels\n\tm_vehicle->applyEngineForce(gEngineForce, 0);\n\tm_vehicle->applyEngineForce(gEngineForce, 1);\n\tm_vehicle->setBrake(gBrakingForce, 2);\n\tm_vehicle->setBrake(gBrakingForce, 3);\n\n\tm_world->stepSimulation((btScalar)seconds, 10);\n\n\tif( m_vehicle->getRigidBody()->getWorldTransform().getOrigin().y() < -1.0f )\n\t{\n\t\tbtTransform trans;\n\t\ttrans.setOrigin( btVector3( 0, 5, 0 ) );\n\t\ttrans.setRotation( btQuaternion( 0, 0, 0, 1 ) );\n\t\tm_vehicle->getRigidBody()->setWorldTransform( trans );\n\t\tm_vehicle->getRigidBody()->setLinearVelocity(btVector3(0,0,0));\n\t}\n\n\tUpdateGameState(seconds);\n}\n\n\/\/ Updates the car placement in the world state\nvoid Simulation::UpdateGameState(double seconds)\n{\n\t\/\/ -- Kart position ------------------------\n\tStateData *state = GetMutState();\n\tbtTransform car1 = m_vehicle->getChassisWorldTransform();\n\n\tbtVector3 pos = car1.getOrigin();\n\tstate->Karts[0].vPos.x = (Real)pos.getX();\n\tstate->Karts[0].vPos.y = (Real)pos.getY();\n\tstate->Karts[0].vPos.z = (Real)pos.getZ();\n\n\tbtQuaternion rot = car1.getRotation();\n\tstate->Karts[0].qOrient.x = (Real)rot.getX();\n\tstate->Karts[0].qOrient.y = (Real)rot.getY();\n\tstate->Karts[0].qOrient.z = (Real)rot.getZ();\n\tstate->Karts[0].qOrient.w = (Real)-rot.getW();\n\n\t\/\/ -- Chase Cam ----------------------------\n\t\/\/ Note: I cannot explain these numbers\n\n\t\/\/ Get car direction\n\tbtVector3 dir = m_vehicle->getForwardVector() \/ m_vehicle->getForwardVector().length();\n\tbtVector3 camera = dir.rotate(btVector3(0,1,0), DEGTORAD(90)); \/\/ forward vector points left, somehow\n\n\n\tif (camera.getY() < 0.4) {\n\t\tcamera.setY(0.4);\n\t}\n\n\t\/\/ Mixin car direction history\n\tReal DIR_DROPOFF = 3 * seconds;\n\tstatic btVector3 dir_history = camera;\n\tdir_history *= (1.0 - DIR_DROPOFF);\n\tdir_history += camera * DIR_DROPOFF;\n\n\tcamera = dir_history;\n\n\t\/\/ Mixin historic speeds\n\tReal SPEED_DROPOFF = 0.1 * seconds;\n\tReal speed = m_vehicle->getCurrentSpeedKmHour();\n\tstatic Real speed_history = speed;\n\tspeed_history *= (1.0 - SPEED_DROPOFF);\n\tspeed_history += speed * SPEED_DROPOFF;\n\n\t\/\/ Make camera focus during acceleration\n\tReal diff = (speed - speed_history) \/ MAX_SPEED;\n\tdiff = diff > 0.0 ? diff : diff \/ 2;\n\tdiff *= diff;\n\tdiff = (pow(2, diff) - 1) \/ 1;\n\tdiff = MIN(diff, 0.3);\n\tReal DIFF_DROPOFF = 0.1;\n\tstatic Real diff_history = diff * seconds;\n\tif (diff > 0.0) {\n\t\tdiff_history *= (1.0 - DIFF_DROPOFF);\n\t\tdiff_history += diff * DIFF_DROPOFF;\n\t}\n\tdiff = diff_history;\n\n\tcamera.setY(0.1 * (1 - MIN(speed_history , 1)) + camera.getY());\n\tcamera *= 3.0 - diff * 1;\n\tstate->Camera.fFOV = 60.0f * (1 - diff * 1.1);\n\n\t\/\/ Add camera vector to kart position for camera position\n\tstate->Camera.vPos = state->Karts[0].vPos;\n\tstate->Camera.vPos.x += camera.getX();\n\tstate->Camera.vPos.y += camera.getY();\n\tstate->Camera.vPos.z += camera.getZ();\n\n\t\/\/ Focus on car\n\tbtVector3 chase = dir.rotate(btVector3(0,1,0), DEGTORAD(-90)); \/\/ forward vector points left, somehow\n\tchase.setY(0);\n\tbtVector3 focus = pos + chase * (1.5 + speed_history * 5 * diff);\n\tReal FOCUS_DROPOFF = seconds * 3;\n\tFOCUS_DROPOFF = MIN(FOCUS_DROPOFF, 1);\n\tstatic btVector3 focus_history = focus;\n\tfocus_history *= (1 - FOCUS_DROPOFF);\n\tfocus_history += focus * FOCUS_DROPOFF;\n\tstate->Camera.vFocus.x = focus_history.getX();\n\tstate->Camera.vFocus.y = focus_history.getY();\n\tstate->Camera.vFocus.z = focus_history.getZ();\n}\n\nvoid Simulation::enableDebugView()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file UPnP.cpp\n * @authors:\n * Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n\n#include \"UPnP.h\"\n\n#include <stdio.h>\n#include <string.h>\n#if ETH_MINIUPNPC\n#include <miniupnpc\/miniwget.h>\n#include <miniupnpc\/miniupnpc.h>\n#include <miniupnpc\/upnpcommands.h>\n#endif\n#include <libdevcore\/Exceptions.h>\n#include <libdevcore\/Common.h>\n#include <libdevcore\/CommonIO.h>\n#include <libdevcore\/Log.h>\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\n\nUPnP::UPnP()\n{\n#if ETH_MINIUPNPC\n\tm_urls.reset(new UPNPUrls);\n\tm_data.reset(new IGDdatas);\n\n\tm_ok = false;\n\n\tstruct UPNPDev* devlist;\n\tstruct UPNPDev* dev;\n\tchar* descXML;\n\tint descXMLsize = 0;\n\tint upnperror = 0;\n\tmemset(m_urls.get(), 0, sizeof(struct UPNPUrls));\n\tmemset(m_data.get(), 0, sizeof(struct IGDdatas));\n\tdevlist = upnpDiscover(2000, NULL\/*multicast interface*\/, NULL\/*minissdpd socket path*\/, 0\/*sameport*\/, 0\/*ipv6*\/, &upnperror);\n\tif (devlist)\n\t{\n\t\tdev = devlist;\n\t\twhile (dev)\n\t\t{\n\t\t\tif (strstr (dev->st, \"InternetGatewayDevice\"))\n\t\t\t\tbreak;\n\t\t\tdev = dev->pNext;\n\t\t}\n\t\tif (!dev)\n\t\t\tdev = devlist; \/* defaulting to first device *\/\n\n\t\tcnote << \"UPnP device:\" << dev->descURL << \"[st:\" << dev->st << \"]\";\n#if MINIUPNPC_API_VERSION >= 9\n\t\tdescXML = (char*)miniwget(dev->descURL, &descXMLsize, 0);\n#else\n\t\tdescXML = (char*)miniwget(dev->descURL, &descXMLsize);\n#endif\n\t\tif (descXML)\n\t\t{\n\t\t\tparserootdesc (descXML, descXMLsize, m_data.get());\n\t\t\tfree (descXML); descXML = 0;\n#if MINIUPNPC_API_VERSION >= 9\n\t\t\tGetUPNPUrls (m_urls.get(), m_data.get(), dev->descURL, 0);\n#else\n\t\t\tGetUPNPUrls (m_urls.get(), m_data.get(), dev->descURL);\n#endif\n\t\t\tm_ok = true;\n\t\t}\n\t\tfreeUPNPDevlist(devlist);\n\t}\n\telse\n#endif\n\t{\n\t\tcnote << \"UPnP device not found.\";\n\t\tBOOST_THROW_EXCEPTION(NoUPnPDevice());\n\t}\n}\n\nUPnP::~UPnP()\n{\n\tauto r = m_reg;\n\tfor (auto i: r)\n\t\tremoveRedirect(i);\n}\n\nstring UPnP::externalIP()\n{\n#if ETH_MINIUPNPC\n\tchar addr[16];\n\tif (!UPNP_GetExternalIPAddress(m_urls->controlURL, m_data->first.servicetype, addr))\n\t\treturn addr;\n\telse\n#endif\n\t\treturn \"0.0.0.0\";\n}\n\nint UPnP::addRedirect(char const* _addr, int _port)\n{\n\t(void)_addr;\n\t(void)_port;\n#if ETH_MINIUPNPC\n\tif (m_urls->controlURL[0] == '\\0')\n\t{\n\t\tcwarn << \"UPnP::addRedirect() called without proper initialisation?\";\n\t\treturn -1;\n\t}\n\n\t\/\/ Try direct mapping first (port external, port internal).\n\tchar port_str[16];\n\tchar ext_port_str[16];\n\tsprintf(port_str, \"%d\", _port);\n\tif (!UPNP_AddPortMapping(m_urls->controlURL, m_data->first.servicetype, port_str, port_str, _addr, \"ethereum\", \"TCP\", NULL, NULL))\n\t\treturn _port;\n\n\t\/\/ Failed - now try (random external, port internal) and cycle up to 10 times.\n\tsrand(time(NULL));\n\tfor (unsigned i = 0; i < 10; ++i)\n\t{\n\t\t_port = rand() % (65535 - 1024) + 1024;\n\t\tsprintf(ext_port_str, \"%d\", _port);\n\t\tif (!UPNP_AddPortMapping(m_urls->controlURL, m_data->first.servicetype, ext_port_str, port_str, _addr, \"ethereum\", \"TCP\", NULL, NULL))\n\t\t\treturn _port;\n\t}\n\n\t\/\/ Failed. Try asking the router to give us a free external port.\n\tif (UPNP_AddPortMapping(m_urls->controlURL, m_data->first.servicetype, port_str, NULL, _addr, \"ethereum\", \"TCP\", NULL, NULL))\n\t\t\/\/ Failed. Exit.\n\t\treturn 0;\n\n\t\/\/ We got mapped, but we don't know which ports we got mapped to. Now to find...\n\tunsigned num = 0;\n\tUPNP_GetPortMappingNumberOfEntries(m_urls->controlURL, m_data->first.servicetype, &num);\n\tfor (unsigned i = 0; i < num; ++i)\n\t{\n\t\tchar extPort[16];\n\t\tchar intClient[16];\n\t\tchar intPort[6];\n\t\tchar protocol[4];\n\t\tchar desc[80];\n\t\tchar enabled[4];\n\t\tchar rHost[64];\n\t\tchar duration[16];\n\t\tUPNP_GetGenericPortMappingEntry(m_urls->controlURL, m_data->first.servicetype, toString(i).c_str(), extPort, intClient, intPort, protocol, desc, enabled, rHost, duration);\n\t\tif (string(\"ethereum\") == desc)\n\t\t{\n\t\t\tm_reg.insert(atoi(extPort));\n\t\t\treturn atoi(extPort);\n\t\t}\n\t}\n\tcerr << \"ERROR: Mapped port not found.\" << endl;\n#endif\n\treturn 0;\n}\n\nvoid UPnP::removeRedirect(int _port)\n{\n\t(void)_port;\n#if ETH_MINIUPNPC\n\tchar port_str[16];\n\/\/\t\tint t;\n\tprintf(\"TB : upnp_rem_redir (%d)\\n\", _port);\n\tif (m_urls->controlURL[0] == '\\0')\n\t{\n\t\tprintf(\"TB : the init was not done !\\n\");\n\t\treturn;\n\t}\n\tsprintf(port_str, \"%d\", _port);\n\tUPNP_DeletePortMapping(m_urls->controlURL, m_data->first.servicetype, port_str, \"TCP\", NULL);\n\tm_reg.erase(_port);\n#endif\n}\n<commit_msg>remove private ports from upnp port range<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file UPnP.cpp\n * @authors:\n * Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n\n#include \"UPnP.h\"\n\n#include <stdio.h>\n#include <string.h>\n#if ETH_MINIUPNPC\n#include <miniupnpc\/miniwget.h>\n#include <miniupnpc\/miniupnpc.h>\n#include <miniupnpc\/upnpcommands.h>\n#endif\n#include <libdevcore\/Exceptions.h>\n#include <libdevcore\/Common.h>\n#include <libdevcore\/CommonIO.h>\n#include <libdevcore\/Log.h>\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\n\nUPnP::UPnP()\n{\n#if ETH_MINIUPNPC\n\tm_urls.reset(new UPNPUrls);\n\tm_data.reset(new IGDdatas);\n\n\tm_ok = false;\n\n\tstruct UPNPDev* devlist;\n\tstruct UPNPDev* dev;\n\tchar* descXML;\n\tint descXMLsize = 0;\n\tint upnperror = 0;\n\tmemset(m_urls.get(), 0, sizeof(struct UPNPUrls));\n\tmemset(m_data.get(), 0, sizeof(struct IGDdatas));\n\tdevlist = upnpDiscover(2000, NULL\/*multicast interface*\/, NULL\/*minissdpd socket path*\/, 0\/*sameport*\/, 0\/*ipv6*\/, &upnperror);\n\tif (devlist)\n\t{\n\t\tdev = devlist;\n\t\twhile (dev)\n\t\t{\n\t\t\tif (strstr (dev->st, \"InternetGatewayDevice\"))\n\t\t\t\tbreak;\n\t\t\tdev = dev->pNext;\n\t\t}\n\t\tif (!dev)\n\t\t\tdev = devlist; \/* defaulting to first device *\/\n\n\t\tcnote << \"UPnP device:\" << dev->descURL << \"[st:\" << dev->st << \"]\";\n#if MINIUPNPC_API_VERSION >= 9\n\t\tdescXML = (char*)miniwget(dev->descURL, &descXMLsize, 0);\n#else\n\t\tdescXML = (char*)miniwget(dev->descURL, &descXMLsize);\n#endif\n\t\tif (descXML)\n\t\t{\n\t\t\tparserootdesc (descXML, descXMLsize, m_data.get());\n\t\t\tfree (descXML); descXML = 0;\n#if MINIUPNPC_API_VERSION >= 9\n\t\t\tGetUPNPUrls (m_urls.get(), m_data.get(), dev->descURL, 0);\n#else\n\t\t\tGetUPNPUrls (m_urls.get(), m_data.get(), dev->descURL);\n#endif\n\t\t\tm_ok = true;\n\t\t}\n\t\tfreeUPNPDevlist(devlist);\n\t}\n\telse\n#endif\n\t{\n\t\tcnote << \"UPnP device not found.\";\n\t\tBOOST_THROW_EXCEPTION(NoUPnPDevice());\n\t}\n}\n\nUPnP::~UPnP()\n{\n\tauto r = m_reg;\n\tfor (auto i: r)\n\t\tremoveRedirect(i);\n}\n\nstring UPnP::externalIP()\n{\n#if ETH_MINIUPNPC\n\tchar addr[16];\n\tif (!UPNP_GetExternalIPAddress(m_urls->controlURL, m_data->first.servicetype, addr))\n\t\treturn addr;\n\telse\n#endif\n\t\treturn \"0.0.0.0\";\n}\n\nint UPnP::addRedirect(char const* _addr, int _port)\n{\n\t(void)_addr;\n\t(void)_port;\n#if ETH_MINIUPNPC\n\tif (m_urls->controlURL[0] == '\\0')\n\t{\n\t\tcwarn << \"UPnP::addRedirect() called without proper initialisation?\";\n\t\treturn -1;\n\t}\n\n\t\/\/ Try direct mapping first (port external, port internal).\n\tchar port_str[16];\n\tchar ext_port_str[16];\n\tsprintf(port_str, \"%d\", _port);\n\tif (!UPNP_AddPortMapping(m_urls->controlURL, m_data->first.servicetype, port_str, port_str, _addr, \"ethereum\", \"TCP\", NULL, NULL))\n\t\treturn _port;\n\n\t\/\/ Failed - now try (random external, port internal) and cycle up to 10 times.\n\tsrand(time(NULL));\n\tfor (unsigned i = 0; i < 10; ++i)\n\t{\n\t\t_port = rand() % (32768 - 1024) + 1024;\n\t\tsprintf(ext_port_str, \"%d\", _port);\n\t\tif (!UPNP_AddPortMapping(m_urls->controlURL, m_data->first.servicetype, ext_port_str, port_str, _addr, \"ethereum\", \"TCP\", NULL, NULL))\n\t\t\treturn _port;\n\t}\n\n\t\/\/ Failed. Try asking the router to give us a free external port.\n\tif (UPNP_AddPortMapping(m_urls->controlURL, m_data->first.servicetype, port_str, NULL, _addr, \"ethereum\", \"TCP\", NULL, NULL))\n\t\t\/\/ Failed. Exit.\n\t\treturn 0;\n\n\t\/\/ We got mapped, but we don't know which ports we got mapped to. Now to find...\n\tunsigned num = 0;\n\tUPNP_GetPortMappingNumberOfEntries(m_urls->controlURL, m_data->first.servicetype, &num);\n\tfor (unsigned i = 0; i < num; ++i)\n\t{\n\t\tchar extPort[16];\n\t\tchar intClient[16];\n\t\tchar intPort[6];\n\t\tchar protocol[4];\n\t\tchar desc[80];\n\t\tchar enabled[4];\n\t\tchar rHost[64];\n\t\tchar duration[16];\n\t\tUPNP_GetGenericPortMappingEntry(m_urls->controlURL, m_data->first.servicetype, toString(i).c_str(), extPort, intClient, intPort, protocol, desc, enabled, rHost, duration);\n\t\tif (string(\"ethereum\") == desc)\n\t\t{\n\t\t\tm_reg.insert(atoi(extPort));\n\t\t\treturn atoi(extPort);\n\t\t}\n\t}\n\tcerr << \"ERROR: Mapped port not found.\" << endl;\n#endif\n\treturn 0;\n}\n\nvoid UPnP::removeRedirect(int _port)\n{\n\t(void)_port;\n#if ETH_MINIUPNPC\n\tchar port_str[16];\n\/\/\t\tint t;\n\tprintf(\"TB : upnp_rem_redir (%d)\\n\", _port);\n\tif (m_urls->controlURL[0] == '\\0')\n\t{\n\t\tprintf(\"TB : the init was not done !\\n\");\n\t\treturn;\n\t}\n\tsprintf(port_str, \"%d\", _port);\n\tUPNP_DeletePortMapping(m_urls->controlURL, m_data->first.servicetype, port_str, \"TCP\", NULL);\n\tm_reg.erase(_port);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\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#ifndef TORRENT_LAZY_ENTRY_HPP_INCLUDED\n#define TORRENT_LAZY_ENTRY_HPP_INCLUDED\n\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstring>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/size_type.hpp\"\n\n#if TORRENT_USE_IOSTREAM\n#include <iosfwd>\n#endif\n\nnamespace libtorrent\n{\n\tstruct lazy_entry;\n\n\tTORRENT_EXPORT char const* parse_int(char const* start, char const* end\n\t\t, char delimiter, boost::int64_t& val);\n\t\/\/ return 0 = success\n\tTORRENT_EXPORT int lazy_bdecode(char const* start, char const* end, lazy_entry& ret, int depth_limit = 1000);\n\n\tstruct pascal_string\n\t{\n\t\tpascal_string(char const* p, int l): len(l), ptr(p) {}\n\t\tint len;\n\t\tchar const* ptr;\n\t\tbool operator<(pascal_string const& rhs) const\n\t\t{\n\t\t\treturn std::memcmp(ptr, rhs.ptr, (std::min)(len, rhs.len)) < 0\n\t\t\t\t|| len < rhs.len;\n\t\t}\n\t};\n\n\tstruct lazy_dict_entry;\n\n\tstruct TORRENT_EXPORT lazy_entry\n\t{\n\t\tenum entry_type_t\n\t\t{\n\t\t\tnone_t, dict_t, list_t, string_t, int_t\n\t\t};\n\n\t\tlazy_entry() : m_type(none_t), m_begin(0), m_end(0)\n\t\t{ m_data.start = 0; }\n\n\t\tentry_type_t type() const { return m_type; }\n\n\t\t\/\/ start points to the first decimal digit\n\t\t\/\/ length is the number of digits\n\t\tvoid construct_int(char const* start, int length)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = int_t;\n\t\t\tm_data.start = start;\n\t\t\tm_size = length;\n\t\t\tm_begin = start - 1; \/\/ include 'i'\n\t\t\tm_end = start + length + 1; \/\/ include 'e'\n\t\t}\n\n\t\tsize_type int_value() const;\n\n\t\t\/\/ string functions\n\t\t\/\/ ================\n\n\t\tvoid construct_string(char const* start, int length);\n\n\t\t\/\/ the string is not null-terminated!\n\t\tchar const* string_ptr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn m_data.start;\n\t\t}\n\n\t\t\/\/ this will return a null terminated string\n\t\t\/\/ it will write to the source buffer!\n\t\tchar const* string_cstr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\tconst_cast<char*>(m_data.start)[m_size] = 0;\n\t\t\treturn m_data.start;\n\t\t}\n\n\t\tpascal_string string_pstr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn pascal_string(m_data.start, m_size);\n\t\t}\n\n\t\tstd::string string_value() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn std::string(m_data.start, m_size);\n\t\t}\n\n\t\tint string_length() const\n\t\t{ return m_size; }\n\n\t\t\/\/ dictionary functions\n\t\t\/\/ ====================\n\n\t\tvoid construct_dict(char const* begin)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = dict_t;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_begin = begin;\n\t\t}\n\n\t\tlazy_entry* dict_append(char const* name);\n\t\tlazy_entry* dict_find(char const* name);\n\t\tlazy_entry const* dict_find(char const* name) const\n\t\t{ return const_cast<lazy_entry*>(this)->dict_find(name); }\n\n\t\tstd::string dict_find_string_value(char const* name) const;\n\t\tpascal_string dict_find_pstr(char const* name) const;\n\t\tsize_type dict_find_int_value(char const* name, size_type default_val = 0) const;\n\t\tlazy_entry const* dict_find_dict(char const* name) const;\n\t\tlazy_entry const* dict_find_list(char const* name) const;\n\t\tlazy_entry const* dict_find_string(char const* name) const;\n\t\tlazy_entry const* dict_find_int(char const* name) const;\n\n\t\tstd::pair<std::string, lazy_entry const*> dict_at(int i) const;\n\n\t\tint dict_size() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == dict_t);\n\t\t\treturn m_size;\n\t\t}\n\n\t\t\/\/ list functions\n\t\t\/\/ ==============\n\n\t\tvoid construct_list(char const* begin)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = list_t;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_begin = begin;\n\t\t}\n\n\t\tlazy_entry* list_append();\n\t\tlazy_entry* list_at(int i)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == list_t);\n\t\t\tTORRENT_ASSERT(i < m_size);\n\t\t\treturn &m_data.list[i];\n\t\t}\n\t\tlazy_entry const* list_at(int i) const\n\t\t{ return const_cast<lazy_entry*>(this)->list_at(i); }\n\n\t\tstd::string list_string_value_at(int i) const;\n\t\tpascal_string list_pstr_at(int i) const;\n\t\tsize_type list_int_value_at(int i, size_type default_val = 0) const;\n\n\t\tint list_size() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == list_t);\n\t\t\treturn m_size;\n\t\t}\n\n\t\t\/\/ end points one byte passed last byte\n\t\tvoid set_end(char const* end)\n\t\t{\n\t\t\tTORRENT_ASSERT(end > m_begin);\n\t\t\tm_end = end;\n\t\t}\n\t\t\n\t\tvoid clear();\n\n\t\t\/\/ releases ownership of any memory allocated\n\t\tvoid release()\n\t\t{\n\t\t\tm_data.start = 0;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_type = none_t;\n\t\t}\n\n\t\t~lazy_entry()\n\t\t{ clear(); }\n\n\t\t\/\/ returns pointers into the source buffer where\n\t\t\/\/ this entry has its bencoded data\n\t\tstd::pair<char const*, int> data_section() const;\n\n\t\tvoid swap(lazy_entry& e)\n\t\t{\n\t\t\tusing std::swap;\n\t\t\tswap(m_type, e.m_type);\n\t\t\tswap(m_data.start, e.m_data.start);\n\t\t\tswap(m_size, e.m_size);\n\t\t\tswap(m_capacity, e.m_capacity);\n\t\t\tswap(m_begin, e.m_begin);\n\t\t\tswap(m_end, e.m_end);\n\t\t}\n\n\tprivate:\n\n\t\tentry_type_t m_type;\n\t\tunion data_t\n\t\t{\n\t\t\tlazy_dict_entry* dict;\n\t\t\tlazy_entry* list;\n\t\t\tchar const* start;\n\t\t} m_data;\n\n\t\tint m_size; \/\/ if list or dictionary, the number of items\n\t\tint m_capacity; \/\/ if list or dictionary, allocated number of items\n\t\t\/\/ used for dictionaries and lists to record the range\n\t\t\/\/ in the original buffer they are based on\n\t\tchar const* m_begin;\n\t\tchar const* m_end;\n\n\t\t\/\/ non-copyable\n\t\tlazy_entry(lazy_entry const&);\n\t\tlazy_entry const& operator=(lazy_entry const&);\n\t};\n\n\tstruct lazy_dict_entry\n\t{\n\t\tchar const* name;\n\t\tlazy_entry val;\n\t};\n\n\tTORRENT_EXPORT std::string print_entry(lazy_entry const& e, bool single_line = false);\n#if TORRENT_USE_IOSTREAM\n\tTORRENT_EXPORT std::ostream& operator<<(std::ostream& os, lazy_entry const& e);\n#endif\n\n}\n\n\n#endif\n\n<commit_msg>and this goes with it<commit_after>\/*\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#ifndef TORRENT_LAZY_ENTRY_HPP_INCLUDED\n#define TORRENT_LAZY_ENTRY_HPP_INCLUDED\n\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstring>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/size_type.hpp\"\n\n#if TORRENT_USE_IOSTREAM\n#include <iosfwd>\n#endif\n\nnamespace libtorrent\n{\n\tstruct lazy_entry;\n\n\tTORRENT_EXPORT char const* parse_int(char const* start, char const* end\n\t\t, char delimiter, boost::int64_t& val);\n\t\/\/ return 0 = success\n\tTORRENT_EXPORT int lazy_bdecode(char const* start, char const* end, lazy_entry& ret, int depth_limit = 1000);\n\n\tstruct pascal_string\n\t{\n\t\tpascal_string(char const* p, int l): len(l), ptr(p) {}\n\t\tint len;\n\t\tchar const* ptr;\n\t\tbool operator<(pascal_string const& rhs) const\n\t\t{\n\t\t\treturn std::memcmp(ptr, rhs.ptr, (std::min)(len, rhs.len)) < 0\n\t\t\t\t|| len < rhs.len;\n\t\t}\n\t};\n\n\tstruct lazy_dict_entry;\n\n\tstruct TORRENT_EXPORT lazy_entry\n\t{\n\t\tenum entry_type_t\n\t\t{\n\t\t\tnone_t, dict_t, list_t, string_t, int_t\n\t\t};\n\n\t\tlazy_entry() : m_type(none_t), m_begin(0), m_end(0)\n\t\t{ m_data.start = 0; }\n\n\t\tentry_type_t type() const { return m_type; }\n\n\t\t\/\/ start points to the first decimal digit\n\t\t\/\/ length is the number of digits\n\t\tvoid construct_int(char const* start, int length)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = int_t;\n\t\t\tm_data.start = start;\n\t\t\tm_size = length;\n\t\t\tm_begin = start - 1; \/\/ include 'i'\n\t\t\tm_end = start + length + 1; \/\/ include 'e'\n\t\t}\n\n\t\tsize_type int_value() const;\n\n\t\t\/\/ string functions\n\t\t\/\/ ================\n\n\t\tvoid construct_string(char const* start, int length);\n\n\t\t\/\/ the string is not null-terminated!\n\t\tchar const* string_ptr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn m_data.start;\n\t\t}\n\n\t\t\/\/ this will return a null terminated string\n\t\t\/\/ it will write to the source buffer!\n\t\tchar const* string_cstr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\tconst_cast<char*>(m_data.start)[m_size] = 0;\n\t\t\treturn m_data.start;\n\t\t}\n\n\t\tpascal_string string_pstr() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn pascal_string(m_data.start, m_size);\n\t\t}\n\n\t\tstd::string string_value() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == string_t);\n\t\t\treturn std::string(m_data.start, m_size);\n\t\t}\n\n\t\tint string_length() const\n\t\t{ return m_size; }\n\n\t\t\/\/ dictionary functions\n\t\t\/\/ ====================\n\n\t\tvoid construct_dict(char const* begin)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = dict_t;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_begin = begin;\n\t\t}\n\n\t\tlazy_entry* dict_append(char const* name);\n\t\tlazy_entry* dict_find(char const* name);\n\t\tlazy_entry const* dict_find(char const* name) const\n\t\t{ return const_cast<lazy_entry*>(this)->dict_find(name); }\n\n\t\tstd::string dict_find_string_value(char const* name) const;\n\t\tpascal_string dict_find_pstr(char const* name) const;\n\t\tsize_type dict_find_int_value(char const* name, size_type default_val = 0) const;\n\t\tlazy_entry const* dict_find_dict(char const* name) const;\n\t\tlazy_entry const* dict_find_list(char const* name) const;\n\t\tlazy_entry const* dict_find_string(char const* name) const;\n\t\tlazy_entry const* dict_find_int(char const* name) const;\n\n\t\tstd::pair<std::string, lazy_entry const*> dict_at(int i) const;\n\n\t\tint dict_size() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == dict_t);\n\t\t\treturn m_size;\n\t\t}\n\n\t\t\/\/ list functions\n\t\t\/\/ ==============\n\n\t\tvoid construct_list(char const* begin)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == none_t);\n\t\t\tm_type = list_t;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_begin = begin;\n\t\t}\n\n\t\tlazy_entry* list_append();\n\t\tlazy_entry* list_at(int i)\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == list_t);\n\t\t\tTORRENT_ASSERT(i < m_size);\n\t\t\treturn &m_data.list[i];\n\t\t}\n\t\tlazy_entry const* list_at(int i) const\n\t\t{ return const_cast<lazy_entry*>(this)->list_at(i); }\n\n\t\tstd::string list_string_value_at(int i) const;\n\t\tpascal_string list_pstr_at(int i) const;\n\t\tsize_type list_int_value_at(int i, size_type default_val = 0) const;\n\n\t\tint list_size() const\n\t\t{\n\t\t\tTORRENT_ASSERT(m_type == list_t);\n\t\t\treturn m_size;\n\t\t}\n\n\t\t\/\/ end points one byte passed last byte\n\t\tvoid set_end(char const* end)\n\t\t{\n\t\t\tTORRENT_ASSERT(end > m_begin);\n\t\t\tm_end = end;\n\t\t}\n\t\t\n\t\tvoid clear();\n\n\t\t\/\/ releases ownership of any memory allocated\n\t\tvoid release()\n\t\t{\n\t\t\tm_data.start = 0;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t\tm_type = none_t;\n\t\t}\n\n\t\t~lazy_entry()\n\t\t{ clear(); }\n\n\t\t\/\/ returns pointers into the source buffer where\n\t\t\/\/ this entry has its bencoded data\n\t\tstd::pair<char const*, int> data_section() const;\n\n\t\tvoid swap(lazy_entry& e)\n\t\t{\n\t\t\tusing std::swap;\n\t\t\tswap(m_type, e.m_type);\n\t\t\tswap(m_data.start, e.m_data.start);\n\t\t\tswap(m_size, e.m_size);\n\t\t\tswap(m_capacity, e.m_capacity);\n\t\t\tswap(m_begin, e.m_begin);\n\t\t\tswap(m_end, e.m_end);\n\t\t}\n\n\tprivate:\n\n\t\tentry_type_t m_type;\n\t\tunion data_t\n\t\t{\n\t\t\tlazy_dict_entry* dict;\n\t\t\tlazy_entry* list;\n\t\t\tchar const* start;\n\t\t} m_data;\n\n\t\tint m_size; \/\/ if list or dictionary, the number of items\n\t\tint m_capacity; \/\/ if list or dictionary, allocated number of items\n\t\t\/\/ used for dictionaries and lists to record the range\n\t\t\/\/ in the original buffer they are based on\n\t\tchar const* m_begin;\n\t\tchar const* m_end;\n\n\t\t\/\/ non-copyable\n\t\tlazy_entry(lazy_entry const&);\n\t\tlazy_entry const& operator=(lazy_entry const&);\n\t};\n\n\tstruct lazy_dict_entry\n\t{\n\t\tchar const* name;\n\t\tlazy_entry val;\n\t};\n\n\tTORRENT_EXPORT std::string print_entry(lazy_entry const& e\n\t\t, bool single_line = false, int indent = 0);\n#if TORRENT_USE_IOSTREAM\n\tTORRENT_EXPORT std::ostream& operator<<(std::ostream& os, lazy_entry const& e);\n#endif\n\n}\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include \"base.hpp\"\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/sstream.hpp\"\n#include \"..\/std\/string.hpp\"\n\n#ifndef SRC_LOGGING\n#define SRC_LOGGING 1\n#endif\n\n#if SRC_LOGGING\n#define SRC() my::SrcPoint(__FILE__, __LINE__, __FUNCTION__)\n#else\n#define SRC() my::SrcPoint()\n#endif\n\nnamespace my\n{\n class SrcPoint\n {\n public:\n SrcPoint() : m_FileName(\"\"), m_Line(-1), m_Function(\"\")\n {\n TruncateFileName();\n }\n\n SrcPoint(char const * fileName, int line, char const * function)\n : m_FileName(fileName), m_Line(line), m_Function(function)\n {\n TruncateFileName();\n }\n\n inline char const * FileName() const\n {\n return m_FileName;\n }\n\n inline int Line() const\n {\n return m_Line;\n }\n\n inline char const * Function() const\n {\n return m_Function;\n }\n private:\n void TruncateFileName()\n {\n size_t const maxLen = 10000;\n char const * p[] = { m_FileName, m_FileName };\n for (size_t i = 0; i < maxLen && m_FileName[i]; ++i)\n {\n if (m_FileName[i] == '\\\\' || m_FileName[i] == '\/')\n {\n swap(p[0], p[1]);\n p[0] = m_FileName + i + 1;\n }\n }\n m_FileName = p[1];\n }\n\n char const * m_FileName;\n int m_Line;\n char const * m_Function;\n };\n}\n\ninline string DebugPrint(my::SrcPoint const & srcPoint)\n{\n ostringstream out;\n if (srcPoint.Line() > 0)\n out << srcPoint.FileName() << \":\" << srcPoint.Line() << \" \" << srcPoint.Function() << \"()\";\n return out.str();\n}\n\n\n<commit_msg>Improved log formatting - do not print \"()\" for ObjectiveC functions<commit_after>#pragma once\n\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/sstream.hpp\"\n#include \"..\/std\/string.hpp\"\n\n#ifndef SRC_LOGGING\n #define SRC_LOGGING 1\n#endif\n\n#if SRC_LOGGING\n #ifndef __OBJC__\n #define SRC() my::SrcPoint(__FILE__, __LINE__, __FUNCTION__, \"()\")\n #else\n #define SRC() my::SrcPoint(__FILE__, __LINE__, __FUNCTION__)\n #endif\n#else\n #define SRC() my::SrcPoint()\n#endif\n\nnamespace my\n{\n class SrcPoint\n {\n public:\n SrcPoint() : m_fileName(\"\"), m_line(-1), m_function(\"\")\n {\n TruncateFileName();\n }\n\n SrcPoint(char const * fileName, int line, char const * function, char const * postfix = \"\")\n : m_fileName(fileName), m_line(line), m_function(function), m_postfix(postfix)\n {\n TruncateFileName();\n }\n\n inline char const * FileName() const\n {\n return m_fileName;\n }\n\n inline int Line() const\n {\n return m_line;\n }\n\n inline char const * Function() const\n {\n return m_function;\n }\n\n inline char const * Postfix() const\n {\n return m_postfix;\n }\n\n private:\n void TruncateFileName()\n {\n size_t const maxLen = 10000;\n char const * p[] = { m_fileName, m_fileName };\n for (size_t i = 0; i < maxLen && m_fileName[i]; ++i)\n {\n if (m_fileName[i] == '\\\\' || m_fileName[i] == '\/')\n {\n swap(p[0], p[1]);\n p[0] = m_fileName + i + 1;\n }\n }\n m_fileName = p[1];\n }\n\n char const * m_fileName;\n int m_line;\n char const * m_function;\n char const * m_postfix;\n };\n}\n\ninline string DebugPrint(my::SrcPoint const & srcPoint)\n{\n ostringstream out;\n if (srcPoint.Line() > 0)\n out << srcPoint.FileName() << \":\" << srcPoint.Line() << \" \" << srcPoint.Function()\n << srcPoint.Postfix() << \" \";\n return out.str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, 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#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED\n#define TORRENT_UDP_SOCKET_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/io_service.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/deadline_timer.hpp\"\n\n#include <vector>\n#include <boost\/function\/function4.hpp>\n\nnamespace libtorrent\n{\n\tclass connection_queue;\n\n\tclass udp_socket\n\t{\n\tpublic:\n\t\ttypedef boost::function<void(error_code const& ec\n\t\t\t, udp::endpoint const&, char const* buf, int size)> callback_t;\n\n\t\tudp_socket(io_service& ios, callback_t const& c, connection_queue& cc);\n\t\t~udp_socket();\n\n\t\tbool is_open() const\n\t\t{\n\t\t\treturn m_ipv4_sock.is_open()\n#if TORRENT_USE_IPV6\n\t\t\t\t|| m_ipv6_sock.is_open()\n#endif\n\t\t\t\t;\n\t\t}\n\t\tio_service& get_io_service() { return m_ipv4_sock.get_io_service(); }\n\n\t\tvoid send(udp::endpoint const& ep, char const* p, int len, error_code& ec);\n\t\tvoid bind(udp::endpoint const& ep, error_code& ec);\n\t\tvoid bind(int port);\n\t\tvoid close();\n\t\tint local_port() const { return m_bind_port; }\n\n\t\tvoid set_proxy_settings(proxy_settings const& ps);\n\t\tproxy_settings const& get_proxy_settings() { return m_proxy_settings; }\n\n\t\tbool is_closed() const { return m_abort; }\n\t\ttcp::endpoint local_endpoint() const\n\t\t{\n\t\t\tudp::endpoint ep = m_ipv4_sock.local_endpoint();\n\t\t\treturn tcp::endpoint(ep.address(), ep.port());\n\t\t}\n\n\tprotected:\n\n\t\tstruct queued_packet\n\t\t{\n\t\t\tudp::endpoint ep;\n\t\t\tbuffer buf;\n\t\t};\n\n\tprivate:\n\n\t\tcallback_t m_callback;\n\n\t\tvoid on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred);\n\t\tvoid on_name_lookup(error_code const& e, tcp::resolver::iterator i);\n\t\tvoid on_timeout();\n\t\tvoid on_connect(int ticket);\n\t\tvoid on_connected(error_code const& ec);\n\t\tvoid handshake1(error_code const& e);\n\t\tvoid handshake2(error_code const& e);\n\t\tvoid handshake3(error_code const& e);\n\t\tvoid handshake4(error_code const& e);\n\t\tvoid socks_forward_udp(mutex::scoped_lock& l);\n\t\tvoid connect1(error_code const& e);\n\t\tvoid connect2(error_code const& e);\n\n\t\tvoid wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);\n\t\tvoid unwrap(error_code const& e, char const* buf, int size);\n\n\t\tmutable mutex m_mutex;\n\n\t\tudp::socket m_ipv4_sock;\n\t\tudp::endpoint m_v4_ep;\n\t\tchar m_v4_buf[1600];\n\n#if TORRENT_USE_IPV6\n\t\tudp::socket m_ipv6_sock;\n\t\tudp::endpoint m_v6_ep;\n\t\tchar m_v6_buf[1600];\n#endif\n\n\t\tint m_bind_port;\n\t\tchar m_outstanding;\n\n\t\ttcp::socket m_socks5_sock;\n\t\tint m_connection_ticket;\n\t\tproxy_settings m_proxy_settings;\n\t\tconnection_queue& m_cc;\n\t\ttcp::resolver m_resolver;\n\t\tchar m_tmp_buf[100];\n\t\tbool m_queue_packets;\n\t\tbool m_tunnel_packets;\n\t\tbool m_abort;\n\t\tudp::endpoint m_proxy_addr;\n\t\t\/\/ while we're connecting to the proxy\n\t\t\/\/ we have to queue the packets, we'll flush\n\t\t\/\/ them once we're connected\n\t\tstd::list<queued_packet> m_queue;\n#ifdef TORRENT_DEBUG\n\t\tbool m_started;\n\t\tint m_magic;\n\t\tint m_outstanding_when_aborted;\n#endif\n\t};\n\n\tstruct rate_limited_udp_socket : public udp_socket\n\t{\n\t\trate_limited_udp_socket(io_service& ios, callback_t const& c, connection_queue& cc);\n\t\tvoid set_rate_limit(int limit) { m_rate_limit = limit; }\n\t\tbool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; }\n\t\tbool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);\n\t\tvoid close();\n\n\tprivate:\n\t\tvoid on_tick(error_code const& e);\n\n\t\tdeadline_timer m_timer;\n\t\tint m_queue_size_limit;\n\t\tint m_rate_limit;\n\t\tint m_quota;\n\t\tptime m_last_tick;\n\t\tstd::list<queued_packet> m_queue;\n\t};\n}\n\n#endif\n\n<commit_msg>ignore failures in when asking for local_endpoint<commit_after>\/*\n\nCopyright (c) 2007, 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#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED\n#define TORRENT_UDP_SOCKET_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/io_service.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/deadline_timer.hpp\"\n\n#include <vector>\n#include <boost\/function\/function4.hpp>\n\nnamespace libtorrent\n{\n\tclass connection_queue;\n\n\tclass udp_socket\n\t{\n\tpublic:\n\t\ttypedef boost::function<void(error_code const& ec\n\t\t\t, udp::endpoint const&, char const* buf, int size)> callback_t;\n\n\t\tudp_socket(io_service& ios, callback_t const& c, connection_queue& cc);\n\t\t~udp_socket();\n\n\t\tbool is_open() const\n\t\t{\n\t\t\treturn m_ipv4_sock.is_open()\n#if TORRENT_USE_IPV6\n\t\t\t\t|| m_ipv6_sock.is_open()\n#endif\n\t\t\t\t;\n\t\t}\n\t\tio_service& get_io_service() { return m_ipv4_sock.get_io_service(); }\n\n\t\tvoid send(udp::endpoint const& ep, char const* p, int len, error_code& ec);\n\t\tvoid bind(udp::endpoint const& ep, error_code& ec);\n\t\tvoid bind(int port);\n\t\tvoid close();\n\t\tint local_port() const { return m_bind_port; }\n\n\t\tvoid set_proxy_settings(proxy_settings const& ps);\n\t\tproxy_settings const& get_proxy_settings() { return m_proxy_settings; }\n\n\t\tbool is_closed() const { return m_abort; }\n\t\ttcp::endpoint local_endpoint() const\n\t\t{\n\t\t\terror_code ec;\n\t\t\tudp::endpoint ep = m_ipv4_sock.local_endpoint(ec);\n\t\t\treturn tcp::endpoint(ep.address(), ep.port());\n\t\t}\n\n\tprotected:\n\n\t\tstruct queued_packet\n\t\t{\n\t\t\tudp::endpoint ep;\n\t\t\tbuffer buf;\n\t\t};\n\n\tprivate:\n\n\t\tcallback_t m_callback;\n\n\t\tvoid on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred);\n\t\tvoid on_name_lookup(error_code const& e, tcp::resolver::iterator i);\n\t\tvoid on_timeout();\n\t\tvoid on_connect(int ticket);\n\t\tvoid on_connected(error_code const& ec);\n\t\tvoid handshake1(error_code const& e);\n\t\tvoid handshake2(error_code const& e);\n\t\tvoid handshake3(error_code const& e);\n\t\tvoid handshake4(error_code const& e);\n\t\tvoid socks_forward_udp(mutex::scoped_lock& l);\n\t\tvoid connect1(error_code const& e);\n\t\tvoid connect2(error_code const& e);\n\n\t\tvoid wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);\n\t\tvoid unwrap(error_code const& e, char const* buf, int size);\n\n\t\tmutable mutex m_mutex;\n\n\t\tudp::socket m_ipv4_sock;\n\t\tudp::endpoint m_v4_ep;\n\t\tchar m_v4_buf[1600];\n\n#if TORRENT_USE_IPV6\n\t\tudp::socket m_ipv6_sock;\n\t\tudp::endpoint m_v6_ep;\n\t\tchar m_v6_buf[1600];\n#endif\n\n\t\tint m_bind_port;\n\t\tchar m_outstanding;\n\n\t\ttcp::socket m_socks5_sock;\n\t\tint m_connection_ticket;\n\t\tproxy_settings m_proxy_settings;\n\t\tconnection_queue& m_cc;\n\t\ttcp::resolver m_resolver;\n\t\tchar m_tmp_buf[100];\n\t\tbool m_queue_packets;\n\t\tbool m_tunnel_packets;\n\t\tbool m_abort;\n\t\tudp::endpoint m_proxy_addr;\n\t\t\/\/ while we're connecting to the proxy\n\t\t\/\/ we have to queue the packets, we'll flush\n\t\t\/\/ them once we're connected\n\t\tstd::list<queued_packet> m_queue;\n#ifdef TORRENT_DEBUG\n\t\tbool m_started;\n\t\tint m_magic;\n\t\tint m_outstanding_when_aborted;\n#endif\n\t};\n\n\tstruct rate_limited_udp_socket : public udp_socket\n\t{\n\t\trate_limited_udp_socket(io_service& ios, callback_t const& c, connection_queue& cc);\n\t\tvoid set_rate_limit(int limit) { m_rate_limit = limit; }\n\t\tbool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; }\n\t\tbool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);\n\t\tvoid close();\n\n\tprivate:\n\t\tvoid on_tick(error_code const& e);\n\n\t\tdeadline_timer m_timer;\n\t\tint m_queue_size_limit;\n\t\tint m_rate_limit;\n\t\tint m_quota;\n\t\tptime m_last_tick;\n\t\tstd::list<queued_packet> m_queue;\n\t};\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 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 \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/automation\/url_request_mock_http_job.h\"\n#include \"chrome\/browser\/download\/save_package.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nconst std::wstring kTestDir = L\"save_page\";\n\nclass SavePageTest : public UITest {\n protected:\n SavePageTest() : UITest() {}\n\n void CheckFile(const std::wstring& client_file,\n const std::wstring& server_file,\n bool check_equal) {\n bool exist = false;\n for (int i = 0; i < 20; ++i) {\n if (file_util::PathExists(client_file)) {\n exist = true;\n break;\n }\n Sleep(sleep_timeout_ms());\n }\n EXPECT_TRUE(exist);\n\n if (check_equal) {\n std::wstring server_file_name;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA,\n &server_file_name));\n server_file_name += L\"\\\\\" + kTestDir + L\"\\\\\" + server_file;\n ASSERT_TRUE(file_util::PathExists(server_file_name));\n\n int64 client_file_size = 0;\n int64 server_file_size = 0;\n EXPECT_TRUE(file_util::GetFileSize(client_file, &client_file_size));\n EXPECT_TRUE(file_util::GetFileSize(server_file_name, &server_file_size));\n EXPECT_EQ(client_file_size, server_file_size);\n EXPECT_TRUE(file_util::ContentsEqual(client_file, server_file_name));\n }\n\n EXPECT_TRUE(DieFileDie(client_file, false));\n }\n\n virtual void SetUp() {\n UITest::SetUp();\n EXPECT_TRUE(file_util::CreateNewTempDirectory(L\"\", &save_dir_));\n save_dir_ += FilePath::kSeparators[0];\n\n download_dir_ = GetDownloadDirectory();\n download_dir_ += FilePath::kSeparators[0];\n }\n\n virtual void TearDown() {\n UITest::TearDown();\n DieFileDie(save_dir_, true);\n }\n\n std::wstring save_dir_;\n std::wstring download_dir_;\n};\n\nTEST_F(SavePageTest, SaveHTMLOnly) {\n std::wstring file_name = L\"a.htm\";\n std::wstring full_file_name = save_dir_ + file_name;\n std::wstring dir = save_dir_ + L\"a_files\";\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L\"\/\" + file_name);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_TRUE(tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));\n\n CheckFile(full_file_name, file_name, true);\n EXPECT_FALSE(file_util::PathExists(dir));\n}\n\nTEST_F(SavePageTest, SaveCompleteHTML) {\n std::wstring file_name = L\"b.htm\";\n std::wstring full_file_name = save_dir_ + file_name;\n std::wstring dir = save_dir_ + L\"b_files\";\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L\"\/\" + file_name);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_TRUE(tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));\n\n CheckFile(dir + L\"\\\\1.png\", L\"1.png\", true);\n CheckFile(dir + L\"\\\\1.css\", L\"1.css\", true);\n CheckFile(full_file_name, file_name, false);\n EXPECT_TRUE(DieFileDie(dir, true));\n}\n\nTEST_F(SavePageTest, NoSave) {\n std::wstring file_name = L\"c.htm\";\n std::wstring full_file_name = save_dir_ + file_name;\n std::wstring dir = save_dir_ + L\"c_files\";\n\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(GURL(L\"about:blank\")));\n WaitUntilTabCount(1);\n\n EXPECT_FALSE(tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get()));\n}\n\nTEST_F(SavePageTest, FilenameFromPageTitle) {\n std::wstring file_name = L\"b.htm\";\n std::wstring full_file_name = download_dir_ +\n L\"Test page for saving page feature.htm\";\n std::wstring dir = download_dir_ +\n L\"Test page for saving page feature_files\";\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L\"\/\" + file_name);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n automation()->SavePackageShouldPromptUser(false);\n EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE));\n EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));\n automation()->SavePackageShouldPromptUser(true);\n\n CheckFile(dir + L\"\\\\1.png\", L\"1.png\", true);\n CheckFile(dir + L\"\\\\1.css\", L\"1.css\", true);\n CheckFile(full_file_name, file_name, false);\n EXPECT_TRUE(DieFileDie(full_file_name, false));\n EXPECT_TRUE(DieFileDie(dir, true));\n}\n\nTEST_F(SavePageTest, CleanFilenameFromPageTitle) {\n std::wstring file_name = L\"c.htm\";\n std::wstring full_file_name = download_dir_ + L\"test.htm\";\n std::wstring dir = download_dir_ + L\"test_files\";\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L\"\/\" + file_name);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n automation()->SavePackageShouldPromptUser(false);\n EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE));\n EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));\n automation()->SavePackageShouldPromptUser(true);\n\n CheckFile(full_file_name, file_name, false);\n EXPECT_TRUE(DieFileDie(full_file_name, false));\n EXPECT_TRUE(DieFileDie(dir, true));\n}\n<commit_msg>Disable the test SavePageTest.CleanFilenameFromPageTitle due to bug 6514. Review URL: http:\/\/codereview.chromium.org\/18154<commit_after>\/\/ Copyright (c) 2006-2008 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 \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/automation\/url_request_mock_http_job.h\"\n#include \"chrome\/browser\/download\/save_package.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nconst std::wstring kTestDir = L\"save_page\";\n\nclass SavePageTest : public UITest {\n protected:\n SavePageTest() : UITest() {}\n\n void CheckFile(const std::wstring& client_file,\n const std::wstring& server_file,\n bool check_equal) {\n bool exist = false;\n for (int i = 0; i < 20; ++i) {\n if (file_util::PathExists(client_file)) {\n exist = true;\n break;\n }\n Sleep(sleep_timeout_ms());\n }\n EXPECT_TRUE(exist);\n\n if (check_equal) {\n std::wstring server_file_name;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA,\n &server_file_name));\n server_file_name += L\"\\\\\" + kTestDir + L\"\\\\\" + server_file;\n ASSERT_TRUE(file_util::PathExists(server_file_name));\n\n int64 client_file_size = 0;\n int64 server_file_size = 0;\n EXPECT_TRUE(file_util::GetFileSize(client_file, &client_file_size));\n EXPECT_TRUE(file_util::GetFileSize(server_file_name, &server_file_size));\n EXPECT_EQ(client_file_size, server_file_size);\n EXPECT_TRUE(file_util::ContentsEqual(client_file, server_file_name));\n }\n\n EXPECT_TRUE(DieFileDie(client_file, false));\n }\nSavePageTest\n virtual void SetUp() {\n UITest::SetUp();\n EXPECT_TRUE(file_util::CreateNewTempDirectory(L\"\", &save_dir_));\n save_dir_ += FilePath::kSeparators[0];\n\n download_dir_ = GetDownloadDirectory();\n download_dir_ += FilePath::kSeparators[0];\n }\n\n virtual void TearDown() {\n UITest::TearDown();\n DieFileDie(save_dir_, true);\n }\n\n std::wstring save_dir_;\n std::wstring download_dir_;\n};\n\nTEST_F(SavePageTest, SaveHTMLOnly) {\n std::wstring file_name = L\"a.htm\";\n std::wstring full_file_name = save_dir_ + file_name;\n std::wstring dir = save_dir_ + L\"a_files\";\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L\"\/\" + file_name);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_TRUE(tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));\n\n CheckFile(full_file_name, file_name, true);\n EXPECT_FALSE(file_util::PathExists(dir));\n}\n\nTEST_F(SavePageTest, SaveCompleteHTML) {\n std::wstring file_name = L\"b.htm\";\n std::wstring full_file_name = save_dir_ + file_name;\n std::wstring dir = save_dir_ + L\"b_files\";\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L\"\/\" + file_name);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_TRUE(tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));\n\n CheckFile(dir + L\"\\\\1.png\", L\"1.png\", true);\n CheckFile(dir + L\"\\\\1.css\", L\"1.css\", true);\n CheckFile(full_file_name, file_name, false);\n EXPECT_TRUE(DieFileDie(dir, true));\n}\n\nTEST_F(SavePageTest, NoSave) {\n std::wstring file_name = L\"c.htm\";\n std::wstring full_file_name = save_dir_ + file_name;\n std::wstring dir = save_dir_ + L\"c_files\";\n\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(GURL(L\"about:blank\")));\n WaitUntilTabCount(1);\n\n EXPECT_FALSE(tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get()));\n}\n\nTEST_F(SavePageTest, FilenameFromPageTitle) {\n std::wstring file_name = L\"b.htm\";\n std::wstring full_file_name = download_dir_ +\n L\"Test page for saving page feature.htm\";\n std::wstring dir = download_dir_ +\n L\"Test page for saving page feature_files\";\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L\"\/\" + file_name);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n automation()->SavePackageShouldPromptUser(false);\n EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE));\n EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));\n automation()->SavePackageShouldPromptUser(true);\n\n CheckFile(dir + L\"\\\\1.png\", L\"1.png\", true);\n CheckFile(dir + L\"\\\\1.css\", L\"1.css\", true);\n CheckFile(full_file_name, file_name, false);\n EXPECT_TRUE(DieFileDie(full_file_name, false));\n EXPECT_TRUE(DieFileDie(dir, true));\n}\n\n\/\/ BUG 6514\nTEST_F(SavePageTest, DISABLED_CleanFilenameFromPageTitle) {\n std::wstring file_name = L\"c.htm\";\n std::wstring full_file_name = download_dir_ + L\"test.htm\";\n std::wstring dir = download_dir_ + L\"test_files\";\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L\"\/\" + file_name);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n automation()->SavePackageShouldPromptUser(false);\n EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE));\n EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));\n automation()->SavePackageShouldPromptUser(true);\n\n CheckFile(full_file_name, file_name, false);\n EXPECT_TRUE(DieFileDie(full_file_name, false));\n EXPECT_TRUE(DieFileDie(dir, true));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n *\n * FILE\n *\tpqxx\/transaction_base.hxx\n *\n * DESCRIPTION\n * common code and definitions for the transaction classes.\n * pqxx::transaction_base defines the interface for any abstract class that\n * represents a database transaction\n * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/transaction_base instead.\n *\n * Copyright (c) 2001-2007, Jeroen T. Vermeulen <jtv@xs4all.nl>\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/compiler-public.hxx\"\n#include \"pqxx\/compiler-internal-pre.hxx\"\n\n\/* End-user programs need not include this file, unless they define their own\n * transaction classes. This is not something the typical program should want\n * to do.\n *\n * However, reading this file is worthwhile because it defines the public\n * interface for the available transaction classes such as transaction and\n * nontransaction.\n *\/\n\n#include \"pqxx\/connection_base\"\n#include \"pqxx\/isolation\"\n#include \"pqxx\/result\"\n\n\/* Methods tested in eg. self-test program test001 are marked with \"\/\/[t1]\"\n *\/\n\nnamespace pqxx\n{\nclass connection_base;\nclass transaction_base;\n\n\nnamespace internal\n{\nclass lowlevel_cursor;\n\nclass PQXX_LIBEXPORT transactionfocus : public virtual namedclass\n{\npublic:\n explicit transactionfocus(transaction_base &t) :\n namedclass(\"transactionfocus\"),\n m_Trans(t),\n m_registered(false)\n {\n }\n\nprotected:\n void register_me();\n void unregister_me() throw ();\n void reg_pending_error(const PGSTD::string &) throw ();\n bool registered() const throw () { return m_registered; }\n\n transaction_base &m_Trans;\n\nprivate:\n bool m_registered;\n\n \/\/\/ Not allowed\n transactionfocus();\n \/\/\/ Not allowed\n transactionfocus(const transactionfocus &);\n \/\/\/ Not allowed\n transactionfocus &operator=(const transactionfocus &);\n};\n\n} \/\/ namespace internal\n\n\n\n\/\/\/ Interface definition (and common code) for \"transaction\" classes.\n\/**\n * @addtogroup transaction Transaction classes\n * All database access must be channeled through one of these classes for\n * safety, although not all implementations of this interface need to provide\n * full transactional integrity.\n *\n * Several implementations of this interface are shipped with libpqxx, including\n * the plain transaction class, the entirely unprotected nontransaction, and the\n * more cautions robusttransaction.\n *\/\nclass PQXX_LIBEXPORT transaction_base : public virtual internal::namedclass\n{\npublic:\n \/\/\/ If nothing else is known, our isolation level is at least read_committed\n typedef isolation_traits<read_committed> isolation_tag;\n\n virtual ~transaction_base() =0;\t\t\t\t\t\/\/[t1]\n\n \/\/\/ Commit the transaction\n \/** Unless this function is called explicitly, the transaction will not be\n * committed (actually the nontransaction implementation breaks this rule,\n * hence the name).\n *\n * Once this function returns, the whole transaction will typically be\n * irrevocably completed in the database. There is also, however, a minute\n * risk that the connection to the database may be lost at just the wrong\n * moment. In that case, libpqxx may be unable to determine whether the\n * transaction was completed or aborted and an in_doubt_error will be thrown\n * to make this fact known to the caller. The robusttransaction\n * implementation takes some special precautions to reduce this risk.\n *\/\n void commit();\t\t\t\t\t\t\t\/\/[t1]\n\n \/\/\/ Abort the transaction\n \/** No special effort is required to call this function; it will be called\n * implicitly when the transaction is destructed.\n *\/\n void abort();\t\t\t\t\t\t\t\t\/\/[t10]\n\n \/**\n * @addtogroup escaping String escaping\n *\/\n \/\/@{\n \/\/\/ Escape string for use as SQL string literal in this transaction\n PGSTD::string esc(const char str[]) const;\t\t\t\t\/\/[t90]\n \/\/\/ Escape string for use as SQL string literal in this transaction\n PGSTD::string esc(const char str[], size_t maxlen) const\t\t\/\/[t90]\n\t{ return m_Conn.esc(str,maxlen); }\n \/\/\/ Escape string for use as SQL string literal in this transaction\n PGSTD::string esc(const PGSTD::string &) const;\t\t\t\/\/[t90]\n\n \/\/\/ Escape binary data for use as SQL string literal in this transaction\n \/** Raw, binary data is treated differently from regular strings. Binary\n * strings are never interpreted as text, so they may safely include byte\n * values or byte sequences that don't happen to represent valid characters in\n * the character encoding being used.\n *\n * The binary string does not stop at the first zero byte, as is the case with\n * textual strings. Instead, they may contain zero bytes anywhere. If it\n * happens to contain bytes that look like quote characters, or other things\n * that can disrupt their use in SQL queries, they will be replaced with\n * special escape sequences.\n *\/\n PGSTD::string esc_raw(const unsigned char str[], size_t len) const\t\/\/[t62]\n\t{ return m_Conn.esc_raw(str, len); }\n \/\/\/ Escape binary data for use as SQL string literal in this transaction\n PGSTD::string esc_raw(const PGSTD::string &) const;\t\t\t\/\/[t62]\n \/\/@}\n\n \/\/\/ Execute query\n \/** Perform a query in this transaction.\n *\n * This is one of the most important functions in libpqxx.\n *\n * Most libpqxx exceptions can be thrown from here, including sql_error,\n * broken_connection, and many sql_error subtypes such as\n * feature_not_supported or insufficient_privilege. But any exception thrown\n * by the C++ standard library may also occur here. All exceptions will be\n * derived from std::exception, however, and all libpqxx-specific exception\n * types are derived from pqxx::pqxx_exception.\n *\n * @param Query Query or command to execute\n * @param Desc Optional identifier for query, to help pinpoint SQL errors\n * @return A result set describing the query's or command's result\n *\/\n result exec(const PGSTD::string &Query,\n\t const PGSTD::string &Desc=PGSTD::string());\t\t\/\/[t1]\n\n result exec(const PGSTD::stringstream &Query,\n\t const PGSTD::string &Desc=PGSTD::string())\t\t\/\/[t9]\n\t{ return exec(Query.str(), Desc); }\n\n \/**\n * @name Prepared statements\n *\/\n \/\/@{\n \/\/\/ Execute prepared statement\n \/** Prepared statements are defined using the connection classes' prepare()\n * function, and continue to live on in the ongoing session regardless of\n * the context they were defined in (unless explicitly dropped using the\n * connection's unprepare() function). Their execution however, like other\n * forms of query execution, requires a transaction object.\n *\n * Just like param_declaration is a helper class that lets you tag parameter\n * declarations onto the statement declaration, the invocation class returned\n * here lets you tag parameter values onto the call:\n *\n * @code\n * result run_mystatement(transaction_base &T)\n * {\n * return T.prepared(\"mystatement\")(\"param1\")(2)()(4).exec();\n * }\n * @endcode\n *\n * Here, parameter 1 (written as \"<tt>$1<\/tt>\" in the statement's body) is a\n * string that receives the value \"param1\"; the second parameter is an integer\n * with the value 2; the third receives a null, making its type irrelevant;\n * and number 4 again is an integer. The ultimate invocation of exec() is\n * essential; if you forget this, nothing happens.\n *\n * @warning Do not try to execute a prepared statement manually through direct\n * SQL statements. This is likely not to work, and even if it does, is likely\n * to be slower than using the proper libpqxx functions. Also, libpqxx knows\n * how to emulate prepared statements if some part of the infrastructure does\n * not support them.\n *\n * @warning Actual definition of the prepared statement on the backend may be\n * deferred until its first use, which means that any errors in the prepared\n * statement may not show up until it is executed--and perhaps abort the\n * ongoing transaction in the process.\n *\/\n prepare::invocation prepared(const PGSTD::string &statement);\t\t\/\/[t85]\n\n \/\/@}\n\n \/**\n * @name Error\/warning output\n *\/\n \/\/@{\n \/\/\/ Have connection process warning message\n void process_notice(const char Msg[]) const\t\t\t\t\/\/[t14]\n\t{ m_Conn.process_notice(Msg); }\n \/\/\/ Have connection process warning message\n void process_notice(const PGSTD::string &Msg) const\t\t\t\/\/[t14]\n\t{ m_Conn.process_notice(Msg); }\n \/\/@}\n\n \/\/\/ Connection this transaction is running in\n connection_base &conn() const { return m_Conn; }\t\t\t\/\/[t4]\n\n \/\/\/ Set session variable in this connection\n \/** The new value is typically forgotten if the transaction aborts.\n * Known exceptions to this rule are nontransaction, and PostgreSQL versions\n * prior to 7.3. In the case of nontransaction, the set value will be kept\n * regardless; but in that case, if the connection ever needs to be recovered,\n * the set value will not be restored.\n * @param Var The variable to set\n * @param Val The new value to store in the variable\n *\/\n void set_variable(const PGSTD::string &Var, const PGSTD::string &Val);\/\/[t61]\n\n \/\/\/ Get currently applicable value of variable\n \/** First consults an internal cache of variables that have been set (whether\n * in the ongoing transaction or in the connection) using the set_variable\n * functions. If it is not found there, the database is queried.\n *\n * @warning Do not mix the set_variable with raw \"SET\" queries, and do not\n * try to set or get variables while a pipeline or table stream is active.\n *\n * @warning This function used to be declared as @c const but isn't anymore.\n *\/\n PGSTD::string get_variable(const PGSTD::string &);\t\t\t\/\/[t61]\n\n\nprotected:\n \/\/\/ Create a transaction (to be called by implementation classes only)\n \/** The optional name, if nonempty, must begin with a letter and may contain\n * letters and digits only.\n *\n * @param direct running directly in connection context (i.e. not nested)?\n *\/\n explicit transaction_base(connection_base &, bool direct=true);\n\n \/\/\/ Begin transaction (to be called by implementing class)\n \/** Will typically be called from implementing class' constructor.\n *\/\n void Begin();\n\n \/\/\/ End transaction. To be called by implementing class' destructor\n void End() throw ();\n\n \/\/\/ To be implemented by derived implementation class: start transaction\n virtual void do_begin() =0;\n \/\/\/ To be implemented by derived implementation class: perform query\n virtual result do_exec(const char Query[]) =0;\n \/\/\/ To be implemented by derived implementation class: commit transaction\n virtual void do_commit() =0;\n \/\/\/ To be implemented by derived implementation class: abort transaction\n virtual void do_abort() =0;\n\n \/\/ For use by implementing class:\n\n \/\/\/ Execute query on connection directly\n \/**\n * @param C Query or command to execute\n * @param Retries Number of times to retry the query if it fails. Be\n * extremely careful with this option; if you retry in the middle of a\n * transaction, you may be setting up a new connection transparently and\n * executing the latter part of the transaction without a backend transaction\n * being active (and with the former part aborted).\n *\/\n result DirectExec(const char C[], int Retries=0);\n\n \/\/\/ Forget about any reactivation-blocking resources we tried to allocate\n void reactivation_avoidance_clear() throw ()\n\t{m_reactivation_avoidance.clear();}\n\nprivate:\n \/* A transaction goes through the following stages in its lifecycle:\n * <ul>\n * <li> nascent: the transaction hasn't actually begun yet. If our connection\n * fails at this stage, it may recover and the transaction can attempt to\n * establish itself again.\n * <li> active: the transaction has begun. Since no commit command has been\n * issued, abortion is implicit if the connection fails now.\n * <li> aborted: an abort has been issued; the transaction is terminated and\n * its changes to the database rolled back. It will accept no further\n * commands.\n * <li> committed: the transaction has completed successfully, meaning that a\n * commit has been issued. No further commands are accepted.\n * <li> in_doubt: the connection was lost at the exact wrong time, and there\n * is no way of telling whether the transaction was committed or aborted.\n * <\/ul>\n *\n * Checking and maintaining state machine logic is the responsibility of the\n * base class (ie., this one).\n *\/\n enum Status\n {\n st_nascent,\n st_active,\n st_aborted,\n st_committed,\n st_in_doubt\n };\n\n\n void PQXX_PRIVATE CheckPendingError();\n\n template<typename T> bool parm_is_null(T *p) const throw () { return !p; }\n template<typename T> bool parm_is_null(T) const throw () { return false; }\n\n friend class Cursor;\n friend class pqxx::internal::lowlevel_cursor;\n void MakeEmpty(result &R) const { m_Conn.MakeEmpty(R); }\n\n friend class internal::transactionfocus;\n void PQXX_PRIVATE RegisterFocus(internal::transactionfocus *);\n void PQXX_PRIVATE UnregisterFocus(internal::transactionfocus *) throw ();\n void PQXX_PRIVATE RegisterPendingError(const PGSTD::string &) throw ();\n friend class tablereader;\n void PQXX_PRIVATE BeginCopyRead(const PGSTD::string &, const PGSTD::string &);\n bool ReadCopyLine(PGSTD::string &L) { return m_Conn.ReadCopyLine(L); }\n friend class tablewriter;\n void PQXX_PRIVATE BeginCopyWrite(const PGSTD::string &Table,\n\tconst PGSTD::string &Columns = PGSTD::string());\n void WriteCopyLine(const PGSTD::string &L) { m_Conn.WriteCopyLine(L); }\n void EndCopyWrite() { m_Conn.EndCopyWrite(); }\n\n friend class pipeline;\n void start_exec(const PGSTD::string &Q) { m_Conn.start_exec(Q); }\n internal::pq::PGresult *get_result() { return m_Conn.get_result(); }\n void consume_input() throw () { m_Conn.consume_input(); }\n bool is_busy() const throw () { return m_Conn.is_busy(); }\n\n friend class prepare::invocation;\n result prepared_exec(const PGSTD::string &,\n\tconst char *const[],\n\tconst int[],\n\tint);\n\n connection_base &m_Conn;\n\n internal::unique<internal::transactionfocus> m_Focus;\n Status m_Status;\n bool m_Registered;\n PGSTD::map<PGSTD::string, PGSTD::string> m_Vars;\n PGSTD::string m_PendingError;\n\n friend class subtransaction;\n \/\/\/ Resources allocated in this transaction that make reactivation impossible\n \/** This number may be negative!\n *\/\n internal::reactivation_avoidance_counter m_reactivation_avoidance;\n\n \/\/\/ Not allowed\n transaction_base();\n \/\/\/ Not allowed\n transaction_base(const transaction_base &);\n \/\/\/ Not allowed\n transaction_base &operator=(const transaction_base &);\n};\n\n} \/\/ namespace pqxx\n\n\n#include \"pqxx\/compiler-internal-post.hxx\"\n<commit_msg>Let cursor_base access m_reactivation_avoidance. Thanks Richard B. Kreckel.<commit_after>\/*-------------------------------------------------------------------------\n *\n * FILE\n *\tpqxx\/transaction_base.hxx\n *\n * DESCRIPTION\n * common code and definitions for the transaction classes.\n * pqxx::transaction_base defines the interface for any abstract class that\n * represents a database transaction\n * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/transaction_base instead.\n *\n * Copyright (c) 2001-2007, Jeroen T. Vermeulen <jtv@xs4all.nl>\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/compiler-public.hxx\"\n#include \"pqxx\/compiler-internal-pre.hxx\"\n\n\/* End-user programs need not include this file, unless they define their own\n * transaction classes. This is not something the typical program should want\n * to do.\n *\n * However, reading this file is worthwhile because it defines the public\n * interface for the available transaction classes such as transaction and\n * nontransaction.\n *\/\n\n#include \"pqxx\/connection_base\"\n#include \"pqxx\/isolation\"\n#include \"pqxx\/result\"\n\n\/* Methods tested in eg. self-test program test001 are marked with \"\/\/[t1]\"\n *\/\n\nnamespace pqxx\n{\nclass connection_base;\nclass transaction_base;\n\n\nnamespace internal\n{\nclass lowlevel_cursor;\n\nclass PQXX_LIBEXPORT transactionfocus : public virtual namedclass\n{\npublic:\n explicit transactionfocus(transaction_base &t) :\n namedclass(\"transactionfocus\"),\n m_Trans(t),\n m_registered(false)\n {\n }\n\nprotected:\n void register_me();\n void unregister_me() throw ();\n void reg_pending_error(const PGSTD::string &) throw ();\n bool registered() const throw () { return m_registered; }\n\n transaction_base &m_Trans;\n\nprivate:\n bool m_registered;\n\n \/\/\/ Not allowed\n transactionfocus();\n \/\/\/ Not allowed\n transactionfocus(const transactionfocus &);\n \/\/\/ Not allowed\n transactionfocus &operator=(const transactionfocus &);\n};\n\n} \/\/ namespace internal\n\n\n\n\/\/\/ Interface definition (and common code) for \"transaction\" classes.\n\/**\n * @addtogroup transaction Transaction classes\n * All database access must be channeled through one of these classes for\n * safety, although not all implementations of this interface need to provide\n * full transactional integrity.\n *\n * Several implementations of this interface are shipped with libpqxx, including\n * the plain transaction class, the entirely unprotected nontransaction, and the\n * more cautions robusttransaction.\n *\/\nclass PQXX_LIBEXPORT transaction_base : public virtual internal::namedclass\n{\npublic:\n \/\/\/ If nothing else is known, our isolation level is at least read_committed\n typedef isolation_traits<read_committed> isolation_tag;\n\n virtual ~transaction_base() =0;\t\t\t\t\t\/\/[t1]\n\n \/\/\/ Commit the transaction\n \/** Unless this function is called explicitly, the transaction will not be\n * committed (actually the nontransaction implementation breaks this rule,\n * hence the name).\n *\n * Once this function returns, the whole transaction will typically be\n * irrevocably completed in the database. There is also, however, a minute\n * risk that the connection to the database may be lost at just the wrong\n * moment. In that case, libpqxx may be unable to determine whether the\n * transaction was completed or aborted and an in_doubt_error will be thrown\n * to make this fact known to the caller. The robusttransaction\n * implementation takes some special precautions to reduce this risk.\n *\/\n void commit();\t\t\t\t\t\t\t\/\/[t1]\n\n \/\/\/ Abort the transaction\n \/** No special effort is required to call this function; it will be called\n * implicitly when the transaction is destructed.\n *\/\n void abort();\t\t\t\t\t\t\t\t\/\/[t10]\n\n \/**\n * @addtogroup escaping String escaping\n *\/\n \/\/@{\n \/\/\/ Escape string for use as SQL string literal in this transaction\n PGSTD::string esc(const char str[]) const;\t\t\t\t\/\/[t90]\n \/\/\/ Escape string for use as SQL string literal in this transaction\n PGSTD::string esc(const char str[], size_t maxlen) const\t\t\/\/[t90]\n\t{ return m_Conn.esc(str,maxlen); }\n \/\/\/ Escape string for use as SQL string literal in this transaction\n PGSTD::string esc(const PGSTD::string &) const;\t\t\t\/\/[t90]\n\n \/\/\/ Escape binary data for use as SQL string literal in this transaction\n \/** Raw, binary data is treated differently from regular strings. Binary\n * strings are never interpreted as text, so they may safely include byte\n * values or byte sequences that don't happen to represent valid characters in\n * the character encoding being used.\n *\n * The binary string does not stop at the first zero byte, as is the case with\n * textual strings. Instead, they may contain zero bytes anywhere. If it\n * happens to contain bytes that look like quote characters, or other things\n * that can disrupt their use in SQL queries, they will be replaced with\n * special escape sequences.\n *\/\n PGSTD::string esc_raw(const unsigned char str[], size_t len) const\t\/\/[t62]\n\t{ return m_Conn.esc_raw(str, len); }\n \/\/\/ Escape binary data for use as SQL string literal in this transaction\n PGSTD::string esc_raw(const PGSTD::string &) const;\t\t\t\/\/[t62]\n \/\/@}\n\n \/\/\/ Execute query\n \/** Perform a query in this transaction.\n *\n * This is one of the most important functions in libpqxx.\n *\n * Most libpqxx exceptions can be thrown from here, including sql_error,\n * broken_connection, and many sql_error subtypes such as\n * feature_not_supported or insufficient_privilege. But any exception thrown\n * by the C++ standard library may also occur here. All exceptions will be\n * derived from std::exception, however, and all libpqxx-specific exception\n * types are derived from pqxx::pqxx_exception.\n *\n * @param Query Query or command to execute\n * @param Desc Optional identifier for query, to help pinpoint SQL errors\n * @return A result set describing the query's or command's result\n *\/\n result exec(const PGSTD::string &Query,\n\t const PGSTD::string &Desc=PGSTD::string());\t\t\/\/[t1]\n\n result exec(const PGSTD::stringstream &Query,\n\t const PGSTD::string &Desc=PGSTD::string())\t\t\/\/[t9]\n\t{ return exec(Query.str(), Desc); }\n\n \/**\n * @name Prepared statements\n *\/\n \/\/@{\n \/\/\/ Execute prepared statement\n \/** Prepared statements are defined using the connection classes' prepare()\n * function, and continue to live on in the ongoing session regardless of\n * the context they were defined in (unless explicitly dropped using the\n * connection's unprepare() function). Their execution however, like other\n * forms of query execution, requires a transaction object.\n *\n * Just like param_declaration is a helper class that lets you tag parameter\n * declarations onto the statement declaration, the invocation class returned\n * here lets you tag parameter values onto the call:\n *\n * @code\n * result run_mystatement(transaction_base &T)\n * {\n * return T.prepared(\"mystatement\")(\"param1\")(2)()(4).exec();\n * }\n * @endcode\n *\n * Here, parameter 1 (written as \"<tt>$1<\/tt>\" in the statement's body) is a\n * string that receives the value \"param1\"; the second parameter is an integer\n * with the value 2; the third receives a null, making its type irrelevant;\n * and number 4 again is an integer. The ultimate invocation of exec() is\n * essential; if you forget this, nothing happens.\n *\n * @warning Do not try to execute a prepared statement manually through direct\n * SQL statements. This is likely not to work, and even if it does, is likely\n * to be slower than using the proper libpqxx functions. Also, libpqxx knows\n * how to emulate prepared statements if some part of the infrastructure does\n * not support them.\n *\n * @warning Actual definition of the prepared statement on the backend may be\n * deferred until its first use, which means that any errors in the prepared\n * statement may not show up until it is executed--and perhaps abort the\n * ongoing transaction in the process.\n *\/\n prepare::invocation prepared(const PGSTD::string &statement);\t\t\/\/[t85]\n\n \/\/@}\n\n \/**\n * @name Error\/warning output\n *\/\n \/\/@{\n \/\/\/ Have connection process warning message\n void process_notice(const char Msg[]) const\t\t\t\t\/\/[t14]\n\t{ m_Conn.process_notice(Msg); }\n \/\/\/ Have connection process warning message\n void process_notice(const PGSTD::string &Msg) const\t\t\t\/\/[t14]\n\t{ m_Conn.process_notice(Msg); }\n \/\/@}\n\n \/\/\/ Connection this transaction is running in\n connection_base &conn() const { return m_Conn; }\t\t\t\/\/[t4]\n\n \/\/\/ Set session variable in this connection\n \/** The new value is typically forgotten if the transaction aborts.\n * Known exceptions to this rule are nontransaction, and PostgreSQL versions\n * prior to 7.3. In the case of nontransaction, the set value will be kept\n * regardless; but in that case, if the connection ever needs to be recovered,\n * the set value will not be restored.\n * @param Var The variable to set\n * @param Val The new value to store in the variable\n *\/\n void set_variable(const PGSTD::string &Var, const PGSTD::string &Val);\/\/[t61]\n\n \/\/\/ Get currently applicable value of variable\n \/** First consults an internal cache of variables that have been set (whether\n * in the ongoing transaction or in the connection) using the set_variable\n * functions. If it is not found there, the database is queried.\n *\n * @warning Do not mix the set_variable with raw \"SET\" queries, and do not\n * try to set or get variables while a pipeline or table stream is active.\n *\n * @warning This function used to be declared as @c const but isn't anymore.\n *\/\n PGSTD::string get_variable(const PGSTD::string &);\t\t\t\/\/[t61]\n\n\nprotected:\n \/\/\/ Create a transaction (to be called by implementation classes only)\n \/** The optional name, if nonempty, must begin with a letter and may contain\n * letters and digits only.\n *\n * @param direct running directly in connection context (i.e. not nested)?\n *\/\n explicit transaction_base(connection_base &, bool direct=true);\n\n \/\/\/ Begin transaction (to be called by implementing class)\n \/** Will typically be called from implementing class' constructor.\n *\/\n void Begin();\n\n \/\/\/ End transaction. To be called by implementing class' destructor\n void End() throw ();\n\n \/\/\/ To be implemented by derived implementation class: start transaction\n virtual void do_begin() =0;\n \/\/\/ To be implemented by derived implementation class: perform query\n virtual result do_exec(const char Query[]) =0;\n \/\/\/ To be implemented by derived implementation class: commit transaction\n virtual void do_commit() =0;\n \/\/\/ To be implemented by derived implementation class: abort transaction\n virtual void do_abort() =0;\n\n \/\/ For use by implementing class:\n\n \/\/\/ Execute query on connection directly\n \/**\n * @param C Query or command to execute\n * @param Retries Number of times to retry the query if it fails. Be\n * extremely careful with this option; if you retry in the middle of a\n * transaction, you may be setting up a new connection transparently and\n * executing the latter part of the transaction without a backend transaction\n * being active (and with the former part aborted).\n *\/\n result DirectExec(const char C[], int Retries=0);\n\n \/\/\/ Forget about any reactivation-blocking resources we tried to allocate\n void reactivation_avoidance_clear() throw ()\n\t{m_reactivation_avoidance.clear();}\n\nprivate:\n \/* A transaction goes through the following stages in its lifecycle:\n * <ul>\n * <li> nascent: the transaction hasn't actually begun yet. If our connection\n * fails at this stage, it may recover and the transaction can attempt to\n * establish itself again.\n * <li> active: the transaction has begun. Since no commit command has been\n * issued, abortion is implicit if the connection fails now.\n * <li> aborted: an abort has been issued; the transaction is terminated and\n * its changes to the database rolled back. It will accept no further\n * commands.\n * <li> committed: the transaction has completed successfully, meaning that a\n * commit has been issued. No further commands are accepted.\n * <li> in_doubt: the connection was lost at the exact wrong time, and there\n * is no way of telling whether the transaction was committed or aborted.\n * <\/ul>\n *\n * Checking and maintaining state machine logic is the responsibility of the\n * base class (ie., this one).\n *\/\n enum Status\n {\n st_nascent,\n st_active,\n st_aborted,\n st_committed,\n st_in_doubt\n };\n\n\n void PQXX_PRIVATE CheckPendingError();\n\n template<typename T> bool parm_is_null(T *p) const throw () { return !p; }\n template<typename T> bool parm_is_null(T) const throw () { return false; }\n\n friend class Cursor;\n friend class cursor_base;\n friend class pqxx::internal::lowlevel_cursor;\n void MakeEmpty(result &R) const { m_Conn.MakeEmpty(R); }\n\n friend class internal::transactionfocus;\n void PQXX_PRIVATE RegisterFocus(internal::transactionfocus *);\n void PQXX_PRIVATE UnregisterFocus(internal::transactionfocus *) throw ();\n void PQXX_PRIVATE RegisterPendingError(const PGSTD::string &) throw ();\n friend class tablereader;\n void PQXX_PRIVATE BeginCopyRead(const PGSTD::string &, const PGSTD::string &);\n bool ReadCopyLine(PGSTD::string &L) { return m_Conn.ReadCopyLine(L); }\n friend class tablewriter;\n void PQXX_PRIVATE BeginCopyWrite(const PGSTD::string &Table,\n\tconst PGSTD::string &Columns = PGSTD::string());\n void WriteCopyLine(const PGSTD::string &L) { m_Conn.WriteCopyLine(L); }\n void EndCopyWrite() { m_Conn.EndCopyWrite(); }\n\n friend class pipeline;\n void start_exec(const PGSTD::string &Q) { m_Conn.start_exec(Q); }\n internal::pq::PGresult *get_result() { return m_Conn.get_result(); }\n void consume_input() throw () { m_Conn.consume_input(); }\n bool is_busy() const throw () { return m_Conn.is_busy(); }\n\n friend class prepare::invocation;\n result prepared_exec(const PGSTD::string &,\n\tconst char *const[],\n\tconst int[],\n\tint);\n\n connection_base &m_Conn;\n\n internal::unique<internal::transactionfocus> m_Focus;\n Status m_Status;\n bool m_Registered;\n PGSTD::map<PGSTD::string, PGSTD::string> m_Vars;\n PGSTD::string m_PendingError;\n\n friend class subtransaction;\n \/\/\/ Resources allocated in this transaction that make reactivation impossible\n \/** This number may be negative!\n *\/\n internal::reactivation_avoidance_counter m_reactivation_avoidance;\n\n \/\/\/ Not allowed\n transaction_base();\n \/\/\/ Not allowed\n transaction_base(const transaction_base &);\n \/\/\/ Not allowed\n transaction_base &operator=(const transaction_base &);\n};\n\n} \/\/ namespace pqxx\n\n\n#include \"pqxx\/compiler-internal-post.hxx\"\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nListNode* reverse(ListNode *A) {\n\tif (A == NULL) {\n\t\treturn NULL;\n\t}\n\telse {\n\t\tListNode *temp, *prev, *next;\n\t\ttemp = A;\n\t\tprev = NULL;\n\t\twhile(temp!=NULL) {\n\t\t\tnext = temp->next;\n\t\t\ttemp->next = prev;\n\t\t\tprev = temp;\n\t\t\ttemp = next;\n\t\t}\n\t\tA = prev;\n\t\treturn A;\n\t}\n}\n\nint main() {\n\treturn 0;\n}<commit_msg>linkedlist is palindrome<commit_after>#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nListNode* reverse(ListNode *A) {\n\tif (A == NULL) {\n\t\treturn NULL;\n\t}\n\telse {\n\t\tListNode *temp, *prev, *next;\n\t\ttemp = A;\n\t\tprev = NULL;\n\t\twhile(temp!=NULL) {\n\t\t\tnext = temp->next;\n\t\t\ttemp->next = prev;\n\t\t\tprev = temp;\n\t\t\ttemp = next;\n\t\t}\n\t\tA = prev;\n\t\treturn A;\n\t}\n}\n\nint Solution::lPalin(ListNode* A) {\n\tstack\t<int> s;\n\tListNode *temp = A;\n\twhile(temp!=NULL) {\n\t\ts.push(temp->val);\n\t\ttemp = temp->next;\n\t}\n\ttemp = A;\n\twhile(temp!=NULL) {\n\t\tif(s.top() != temp->val) {\n\t\t\treturn 0;\n\t\t}\n\t\ts.pop();\n\t\ttemp = temp->next;\n\t}\n\treturn 1;\n}\n\nint main() {\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of Simdee, see homepage at http:\/\/github.com\/tufak\/simdee\n\/\/ This file is distributed under the MIT license.\n\n#ifndef SIMDEE_UTIL_MALLOC_HPP\n#define SIMDEE_UTIL_MALLOC_HPP\n\n#include <type_traits>\n#include <exception>\n#include <cstdlib>\n#include <cstdint>\n#include \"noexcept.hpp\"\n\nnamespace sd {\n\n namespace detail {\n#if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)\n \/\/ type_traits is buggered in libstdc++ up until GCC 5\n template <typename T>\n using is_trivially_default_constructible = std::has_trivial_default_constructor<T>;\n#else\n template <typename T>\n using is_trivially_default_constructible = std::is_trivially_default_constructible<T>;\n#endif\n\n inline constexpr bool is_pow2(std::size_t x) {\n return x && (x & (x - 1)) == 0;\n }\n\n template <typename T, std::size_t Align>\n struct aligned_allocator;\n template <typename T, std::size_t Align = alignof(T), bool Switch = (Align > alignof(double))>\n struct alloc;\n\n template <typename T, std::size_t Align>\n struct alloc<T, Align, false> {\n static T* malloc(std::size_t bytes) {\n return (T*)std::malloc(bytes);\n }\n static void free(T* ptr) {\n std::free(ptr);\n }\n using allocator = std::allocator<T>;\n using deleter = std::default_delete<T>;\n };\n\n template <typename T, std::size_t Align>\n struct alloc<T, Align, true> {\n static_assert(detail::is_pow2(Align), \"alignment must be a power of 2\");\n static_assert(Align <= 128, \"alignment is too large\");\n static_assert(Align > alignof(double), \"alignment is too small -- use malloc\");\n\n static T* malloc(std::size_t bytes) {\n auto orig = (uintptr_t)std::malloc(bytes + Align);\n if (orig == 0) return nullptr;\n auto aligned = (orig + Align) & ~(Align - 1);\n auto offset = int8_t(orig - aligned);\n ((int8_t*)aligned)[-1] = offset;\n return (T*)aligned;\n }\n\n static void free(T* aligned) {\n if (aligned == nullptr) return;\n auto offset = ((int8_t*)aligned)[-1];\n auto orig = uintptr_t(aligned) + offset;\n std::free((void*)orig);\n }\n\n using allocator = aligned_allocator<T, Align>;\n\n struct deleter {\n template <typename S>\n void operator()(S* ptr) {\n free(ptr);\n }\n };\n };\n\n template <typename T, std::size_t Align>\n struct aligned_allocator {\n using value_type = T;\n using alloc_t = alloc<T, Align>;\n\n aligned_allocator() = default;\n\n template <typename S>\n aligned_allocator(const aligned_allocator<S, Align>&) {}\n\n T* allocate(std::size_t count) const SIMDEE_NOEXCEPT {\n return alloc_t::malloc(sizeof(T) * count);\n }\n\n void deallocate(T* ptr, std::size_t) const SIMDEE_NOEXCEPT {\n alloc_t::free(ptr);\n }\n\n void destroy(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_destructible<T>::value) {\n if (!std::is_trivially_destructible<T>::value) {\n ptr->~T();\n }\n else {\n no_op(ptr); \/\/ just to suppress MSVC warning \"ptr not referenced\"\n }\n }\n\n static void no_op(T*) {}\n\n void construct(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_constructible<T>::value) {\n if (!is_trivially_default_constructible<T>::value) {\n new (ptr)T;\n }\n }\n\n template <typename A1, typename... A>\n void construct(T* ptr, A1&& a1, A&&... a2) const {\n new (ptr)T(std::forward<A1>(a1), std::forward<A...>(a2)...);\n }\n\n \/\/ default rebind should do just this, doesn't seem to work in MSVC though\n template <typename S>\n struct rebind {\n using other = aligned_allocator<S, Align>;\n };\n };\n\n template <typename T, typename U, std::size_t TS, std::size_t US>\n inline bool operator==(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return true; }\n template <typename T, typename U, std::size_t TS, std::size_t US>\n inline bool operator!=(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return false; }\n }\n\n template <typename T, std::size_t Align = alignof(T)>\n using allocator = typename detail::alloc<T, Align>::allocator;\n template <typename T, std::size_t Align = alignof(T)>\n using deleter = typename detail::alloc<T, Align>::deleter;\n}\n\n#endif \/\/ SIMDEE_UTIL_MALLOC_HPP\n<commit_msg>Add missing include<commit_after>\/\/ This file is a part of Simdee, see homepage at http:\/\/github.com\/tufak\/simdee\n\/\/ This file is distributed under the MIT license.\n\n#ifndef SIMDEE_UTIL_MALLOC_HPP\n#define SIMDEE_UTIL_MALLOC_HPP\n\n#include <type_traits>\n#include <exception>\n#include <cstdlib>\n#include <cstdint>\n#include <memory>\n#include \"noexcept.hpp\"\n\nnamespace sd {\n\n namespace detail {\n#if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)\n \/\/ type_traits is buggered in libstdc++ up until GCC 5\n template <typename T>\n using is_trivially_default_constructible = std::has_trivial_default_constructor<T>;\n#else\n template <typename T>\n using is_trivially_default_constructible = std::is_trivially_default_constructible<T>;\n#endif\n\n inline constexpr bool is_pow2(std::size_t x) {\n return x && (x & (x - 1)) == 0;\n }\n\n template <typename T, std::size_t Align>\n struct aligned_allocator;\n template <typename T, std::size_t Align = alignof(T), bool Switch = (Align > alignof(double))>\n struct alloc;\n\n template <typename T, std::size_t Align>\n struct alloc<T, Align, false> {\n static T* malloc(std::size_t bytes) {\n return (T*)std::malloc(bytes);\n }\n static void free(T* ptr) {\n std::free(ptr);\n }\n using allocator = std::allocator<T>;\n using deleter = std::default_delete<T>;\n };\n\n template <typename T, std::size_t Align>\n struct alloc<T, Align, true> {\n static_assert(detail::is_pow2(Align), \"alignment must be a power of 2\");\n static_assert(Align <= 128, \"alignment is too large\");\n static_assert(Align > alignof(double), \"alignment is too small -- use malloc\");\n\n static T* malloc(std::size_t bytes) {\n auto orig = (uintptr_t)std::malloc(bytes + Align);\n if (orig == 0) return nullptr;\n auto aligned = (orig + Align) & ~(Align - 1);\n auto offset = int8_t(orig - aligned);\n ((int8_t*)aligned)[-1] = offset;\n return (T*)aligned;\n }\n\n static void free(T* aligned) {\n if (aligned == nullptr) return;\n auto offset = ((int8_t*)aligned)[-1];\n auto orig = uintptr_t(aligned) + offset;\n std::free((void*)orig);\n }\n\n using allocator = aligned_allocator<T, Align>;\n\n struct deleter {\n template <typename S>\n void operator()(S* ptr) {\n free(ptr);\n }\n };\n };\n\n template <typename T, std::size_t Align>\n struct aligned_allocator {\n using value_type = T;\n using alloc_t = alloc<T, Align>;\n\n aligned_allocator() = default;\n\n template <typename S>\n aligned_allocator(const aligned_allocator<S, Align>&) {}\n\n T* allocate(std::size_t count) const SIMDEE_NOEXCEPT {\n return alloc_t::malloc(sizeof(T) * count);\n }\n\n void deallocate(T* ptr, std::size_t) const SIMDEE_NOEXCEPT {\n alloc_t::free(ptr);\n }\n\n void destroy(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_destructible<T>::value) {\n if (!std::is_trivially_destructible<T>::value) {\n ptr->~T();\n }\n else {\n no_op(ptr); \/\/ just to suppress MSVC warning \"ptr not referenced\"\n }\n }\n\n static void no_op(T*) {}\n\n void construct(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_constructible<T>::value) {\n if (!is_trivially_default_constructible<T>::value) {\n new (ptr)T;\n }\n }\n\n template <typename A1, typename... A>\n void construct(T* ptr, A1&& a1, A&&... a2) const {\n new (ptr)T(std::forward<A1>(a1), std::forward<A...>(a2)...);\n }\n\n \/\/ default rebind should do just this, doesn't seem to work in MSVC though\n template <typename S>\n struct rebind {\n using other = aligned_allocator<S, Align>;\n };\n };\n\n template <typename T, typename U, std::size_t TS, std::size_t US>\n inline bool operator==(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return true; }\n template <typename T, typename U, std::size_t TS, std::size_t US>\n inline bool operator!=(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return false; }\n }\n\n template <typename T, std::size_t Align = alignof(T)>\n using allocator = typename detail::alloc<T, Align>::allocator;\n template <typename T, std::size_t Align = alignof(T)>\n using deleter = typename detail::alloc<T, Align>::deleter;\n}\n\n#endif \/\/ SIMDEE_UTIL_MALLOC_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef SIMDIFY_UTIL_INTEGRAL\n#define SIMDIFY_UTIL_INTEGRAL\n\n#include \"inline.hpp\"\n#include <cstdint>\n#include <type_traits>\n\nnamespace simd {\n\n template <std::size_t Size>\n struct select_sint;\n template <>\n struct select_sint<1> { using type = int8_t; };\n template <>\n struct select_sint<2> { using type = int16_t; };\n template <>\n struct select_sint<4> { using type = int32_t; };\n template <>\n struct select_sint<8> { using type = int64_t; };\n\n template <std::size_t Size>\n struct select_uint;\n template <>\n struct select_uint<1> { using type = uint8_t; };\n template <>\n struct select_uint<2> { using type = uint16_t; };\n template <>\n struct select_uint<4> { using type = uint32_t; };\n template <>\n struct select_uint<8> { using type = uint64_t; };\n\n template <std::size_t Size>\n using select_sint_t = typename select_sint<Size>::type;\n template <std::size_t Size>\n using select_uint_t = typename select_uint<Size>::type;\n\n template <std::size_t x>\n struct is_power_of_2 : std::integral_constant < bool, x && (x & (x - 1)) == 0 > {};\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t div_floor(std::size_t a) { return a \/ b; }\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t div_ceil(std::size_t a) { return (a + (b - 1)) \/ b; }\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t div_floor_shift(std::size_t a) {\n if (is_power_of_2<b>::value)\n return a & ~(b - 1);\n else\n return (a \/ b) * b;\n }\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t div_ceil_shift(std::size_t a) {\n if (is_power_of_2<b>::value)\n return (a + (b - 1)) & ~(b - 1);\n else\n return ((a + (b - 1)) \/ b) * b;\n }\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t mod(std::size_t a) {\n if (is_power_of_2<b>::value)\n return a & (b - 1);\n else\n return a % b;\n }\n\n}\n\n#endif \/\/ SIMDIFY_UTIL_INTEGRAL\n<commit_msg>Added sequences for fake iteration using expanded parameter packs<commit_after>#ifndef SIMDIFY_UTIL_INTEGRAL\n#define SIMDIFY_UTIL_INTEGRAL\n\n#include \"inline.hpp\"\n#include <cstdint>\n#include <type_traits>\n\nnamespace simd {\n\n template <std::size_t Size>\n struct select_sint;\n template <>\n struct select_sint<1> { using type = int8_t; };\n template <>\n struct select_sint<2> { using type = int16_t; };\n template <>\n struct select_sint<4> { using type = int32_t; };\n template <>\n struct select_sint<8> { using type = int64_t; };\n\n template <std::size_t Size>\n struct select_uint;\n template <>\n struct select_uint<1> { using type = uint8_t; };\n template <>\n struct select_uint<2> { using type = uint16_t; };\n template <>\n struct select_uint<4> { using type = uint32_t; };\n template <>\n struct select_uint<8> { using type = uint64_t; };\n\n template <std::size_t Size>\n using select_sint_t = typename select_sint<Size>::type;\n template <std::size_t Size>\n using select_uint_t = typename select_uint<Size>::type;\n\n template <std::size_t x>\n struct is_power_of_2 : std::integral_constant < bool, x && (x & (x - 1)) == 0 > {};\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t div_floor(std::size_t a) { return a \/ b; }\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t div_ceil(std::size_t a) { return (a + (b - 1)) \/ b; }\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t div_floor_shift(std::size_t a) {\n if (is_power_of_2<b>::value)\n return a & ~(b - 1);\n else\n return (a \/ b) * b;\n }\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t div_ceil_shift(std::size_t a) {\n if (is_power_of_2<b>::value)\n return (a + (b - 1)) & ~(b - 1);\n else\n return ((a + (b - 1)) \/ b) * b;\n }\n\n template <std::size_t b>\n SIMDIFY_FORCE_INLINE std::size_t mod(std::size_t a) {\n if (is_power_of_2<b>::value)\n return a & (b - 1);\n else\n return a % b;\n }\n\n template <std::size_t... I>\n struct sequence {};\n\n template <std::size_t I1, std::size_t I2, std::size_t... I>\n struct make_sequence_impl : make_sequence_impl<I1, I2 - 1, I2, I...> {};\n\n template <std::size_t I1, std::size_t... I>\n struct make_sequence_impl<I1, I1, I...> { using type = sequence<I1, I...>; };\n\n template <std::size_t I1, std::size_t I2, typename Enable = void>\n struct make_sequence;\n\n template <std::size_t I1, std::size_t I2>\n struct make_sequence<I1, I2, typename std::enable_if<(I1 < I2)>::type> : make_sequence_impl<I1, I2 - 1> {};\n\n template <std::size_t I1, std::size_t I2>\n struct make_sequence<I1, I2, typename std::enable_if<(I1 == I2)>::type> { using type = sequence<>; };\n\n template <std::size_t I1, std::size_t I2>\n struct make_sequence<I1, I2, typename std::enable_if<(I1 > I2)>::type> {\n static_assert(I1 <= I2, \"invalid make_sequence: negative size\");\n };\n\n template <std::size_t I1, std::size_t I2>\n using make_sequence_t = typename make_sequence<I1, I2>::type;\n\n}\n\n#endif \/\/ SIMDIFY_UTIL_INTEGRAL\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2012 Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\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#include \"cmlformat.h\"\n\n#include <avogadro\/core\/elements.h>\n\n#include <pugixml.cpp>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <fstream>\n#include <streambuf>\n#include <iostream>\n#include <map>\n\nnamespace Avogadro {\nnamespace Io {\n\nusing std::ifstream;\nusing std::string;\nusing std::cout;\nusing std::endl;\n\nusing pugi::xml_document;\nusing pugi::xml_node;\nusing pugi::xml_attribute;\n\nusing namespace Core;\n\nnamespace {\nclass CmlFormatPrivate\n{\npublic:\n CmlFormatPrivate(std::vector<Molecule *> &molecules,\n pugi::xml_document &document)\n : success(false), molecule(NULL), moleculeNode(NULL)\n {\n \/\/ Parse the CML document, and create molecules\/elements as necessary.\n moleculeNode = document.child(\"molecule\");\n if (moleculeNode) {\n if (molecules.size() == 0) {\n molecules.resize(1, new Molecule());\n }\n else {\n delete molecules[0];\n molecules[0] = new Molecule();\n }\n \/\/ We know there is a molecule, and only one molecule.\n molecule = molecules[0];\n \/\/ Parse the various components we know about.\n properties();\n bool atomsExist(atoms());\n bool bondsExist(bonds());\n success = atomsExist && bondsExist;\n }\n else {\n cout << \"Error, no molecule node found.\" << endl;\n success = false;\n }\n }\n\n void properties()\n {\n xml_attribute attribute;\n xml_node node;\n node = moleculeNode.child(\"name\");\n if (node && node.value())\n molecule->setData(\"name\", std::string(node.child_value()));\n node = moleculeNode.child(\"identifier\");\n if (node && node.value()) {\n attribute = node.attribute(\"convention\");\n if (attribute && std::string(attribute.value()) == \"iupac:inchi\") {\n attribute = node.attribute(\"value\");\n if (attribute && std::string(attribute.name()) == \"value\")\n molecule->setData(\"inchi\", std::string(attribute.value()));\n }\n }\n }\n\n bool atoms()\n {\n xml_node atomArray = moleculeNode.child(\"atomArray\");\n if (!atomArray)\n return false;\n\n xml_node node = atomArray.child(\"atom\");\n Atom atom;\n while (node) {\n \/\/ Step through all of the atom attributes and store them.\n xml_attribute attribute = node.attribute(\"elementType\");\n if (attribute) {\n unsigned char atomicNumber =\n Elements::atomicNumberFromSymbol(attribute.value());\n atom = molecule->addAtom(atomicNumber);\n }\n else {\n \/\/ There is no element data, this atom node is corrupt.\n cout << \"Warning, corrupt element node found.\" << endl;\n return false;\n }\n\n attribute = node.attribute(\"id\");\n if (attribute)\n atomIds[std::string(attribute.value())] = atom.index();\n else \/\/ Atom nodes must have IDs - bail.\n return false;\n\n \/\/ Check for 3D geometry.\n attribute = node.attribute(\"x3\");\n if (attribute) {\n xml_attribute y3 = node.attribute(\"y3\");\n xml_attribute z3 = node.attribute(\"z3\");\n if (y3 && z3) {\n \/\/ It looks like we have a valid 3D position.\n Vector3 position(strtod(attribute.value(), 0),\n strtod(y3.value(), 0),\n strtod(z3.value(), 0));\n atom.setPosition3d(position);\n }\n else {\n \/\/ Corrupt 3D position supplied for atom.\n return false;\n }\n }\n\n \/\/ Check for 2D geometry.\n attribute = node.attribute(\"x2\");\n if (attribute) {\n xml_attribute y2 = node.attribute(\"y2\");\n if (y2) {\n Vector2 position(strtod(attribute.value(), 0),\n strtod(y2.value(), 0));\n atom.setPosition2d(position);\n }\n else {\n \/\/ Corrupt 2D position supplied for atom.\n return false;\n }\n }\n\n \/\/ Move on to the next atom node (if there is one).\n node = node.next_sibling(\"atom\");\n }\n return true;\n }\n\n bool bonds()\n {\n xml_node bondArray = moleculeNode.child(\"bondArray\");\n if (!bondArray)\n return false;\n\n xml_node node = bondArray.child(\"bond\");\n\n while (node) {\n xml_attribute attribute = node.attribute(\"atomRefs2\");\n Bond bond;\n if (attribute) {\n \/\/ Should contain two elements separated by a space.\n std::string refs(attribute.value());\n std::vector<std::string> tokens;\n boost::split(tokens, refs, boost::is_any_of(\" \"));\n if (tokens.size() != 2) \/\/ Corrupted file\/input we don't understand\n return false;\n std::map<std::string, size_t>::const_iterator begin, end;\n begin = atomIds.find(tokens[0]);\n end = atomIds.find(tokens[1]);\n if (begin != atomIds.end() && end != atomIds.end()\n && begin->second < molecule->atomCount()\n && end->second < molecule->atomCount()) {\n bond = molecule->addBond(molecule->atom(begin->second),\n molecule->atom(end->second));\n }\n else { \/\/ Couldn't parse the bond begin and end.\n return false;\n }\n }\n\n attribute = node.attribute(\"order\");\n if (attribute)\n bond.setOrder(atoi(attribute.value()));\n\n \/\/ Move on to the next bond node (if there is one).\n node = node.next_sibling(\"bond\");\n }\n\n return true;\n }\n\n bool success;\n Molecule *molecule;\n xml_node moleculeNode;\n std::map<std::string, size_t> atomIds;\n};\n}\n\nCmlFormat::CmlFormat()\n{\n}\n\nCmlFormat::~CmlFormat()\n{\n}\n\nbool CmlFormat::readFile(const std::string &fileName)\n{\n \/\/ Read the file into a string.\n std::ifstream file(fileName.c_str());\n if (!file.is_open()) {\n cout << \"Error opening file: \" << fileName << endl;\n return false;\n }\n\n xml_document document;\n pugi::xml_parse_result result = document.load(file);\n if (!result) {\n cout << \"Error parsing XML: \" << result.description() << endl;\n return false;\n }\n\n CmlFormatPrivate parser(m_molecules, document);\n\n return result == true;\n}\n\nbool CmlFormat::writeFile(const std::string &)\n{\n return true;\n}\n\nMolecule * CmlFormat::molecule(size_t index)\n{\n if (index < m_molecules.size())\n return m_molecules[index];\n else\n return 0;\n}\n\n} \/\/ end Io namespace\n} \/\/ end Avogadro namespace\n<commit_msg>Return true if we get this far, already checked for errors<commit_after>\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2012 Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\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#include \"cmlformat.h\"\n\n#include <avogadro\/core\/elements.h>\n\n#include <pugixml.cpp>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <fstream>\n#include <streambuf>\n#include <iostream>\n#include <map>\n\nnamespace Avogadro {\nnamespace Io {\n\nusing std::ifstream;\nusing std::string;\nusing std::cout;\nusing std::endl;\n\nusing pugi::xml_document;\nusing pugi::xml_node;\nusing pugi::xml_attribute;\n\nusing namespace Core;\n\nnamespace {\nclass CmlFormatPrivate\n{\npublic:\n CmlFormatPrivate(std::vector<Molecule *> &molecules,\n pugi::xml_document &document)\n : success(false), molecule(NULL), moleculeNode(NULL)\n {\n \/\/ Parse the CML document, and create molecules\/elements as necessary.\n moleculeNode = document.child(\"molecule\");\n if (moleculeNode) {\n if (molecules.size() == 0) {\n molecules.resize(1, new Molecule());\n }\n else {\n delete molecules[0];\n molecules[0] = new Molecule();\n }\n \/\/ We know there is a molecule, and only one molecule.\n molecule = molecules[0];\n \/\/ Parse the various components we know about.\n properties();\n bool atomsExist(atoms());\n bool bondsExist(bonds());\n success = atomsExist && bondsExist;\n }\n else {\n cout << \"Error, no molecule node found.\" << endl;\n success = false;\n }\n }\n\n void properties()\n {\n xml_attribute attribute;\n xml_node node;\n node = moleculeNode.child(\"name\");\n if (node && node.value())\n molecule->setData(\"name\", std::string(node.child_value()));\n node = moleculeNode.child(\"identifier\");\n if (node && node.value()) {\n attribute = node.attribute(\"convention\");\n if (attribute && std::string(attribute.value()) == \"iupac:inchi\") {\n attribute = node.attribute(\"value\");\n if (attribute && std::string(attribute.name()) == \"value\")\n molecule->setData(\"inchi\", std::string(attribute.value()));\n }\n }\n }\n\n bool atoms()\n {\n xml_node atomArray = moleculeNode.child(\"atomArray\");\n if (!atomArray)\n return false;\n\n xml_node node = atomArray.child(\"atom\");\n Atom atom;\n while (node) {\n \/\/ Step through all of the atom attributes and store them.\n xml_attribute attribute = node.attribute(\"elementType\");\n if (attribute) {\n unsigned char atomicNumber =\n Elements::atomicNumberFromSymbol(attribute.value());\n atom = molecule->addAtom(atomicNumber);\n }\n else {\n \/\/ There is no element data, this atom node is corrupt.\n cout << \"Warning, corrupt element node found.\" << endl;\n return false;\n }\n\n attribute = node.attribute(\"id\");\n if (attribute)\n atomIds[std::string(attribute.value())] = atom.index();\n else \/\/ Atom nodes must have IDs - bail.\n return false;\n\n \/\/ Check for 3D geometry.\n attribute = node.attribute(\"x3\");\n if (attribute) {\n xml_attribute y3 = node.attribute(\"y3\");\n xml_attribute z3 = node.attribute(\"z3\");\n if (y3 && z3) {\n \/\/ It looks like we have a valid 3D position.\n Vector3 position(strtod(attribute.value(), 0),\n strtod(y3.value(), 0),\n strtod(z3.value(), 0));\n atom.setPosition3d(position);\n }\n else {\n \/\/ Corrupt 3D position supplied for atom.\n return false;\n }\n }\n\n \/\/ Check for 2D geometry.\n attribute = node.attribute(\"x2\");\n if (attribute) {\n xml_attribute y2 = node.attribute(\"y2\");\n if (y2) {\n Vector2 position(strtod(attribute.value(), 0),\n strtod(y2.value(), 0));\n atom.setPosition2d(position);\n }\n else {\n \/\/ Corrupt 2D position supplied for atom.\n return false;\n }\n }\n\n \/\/ Move on to the next atom node (if there is one).\n node = node.next_sibling(\"atom\");\n }\n return true;\n }\n\n bool bonds()\n {\n xml_node bondArray = moleculeNode.child(\"bondArray\");\n if (!bondArray)\n return false;\n\n xml_node node = bondArray.child(\"bond\");\n\n while (node) {\n xml_attribute attribute = node.attribute(\"atomRefs2\");\n Bond bond;\n if (attribute) {\n \/\/ Should contain two elements separated by a space.\n std::string refs(attribute.value());\n std::vector<std::string> tokens;\n boost::split(tokens, refs, boost::is_any_of(\" \"));\n if (tokens.size() != 2) \/\/ Corrupted file\/input we don't understand\n return false;\n std::map<std::string, size_t>::const_iterator begin, end;\n begin = atomIds.find(tokens[0]);\n end = atomIds.find(tokens[1]);\n if (begin != atomIds.end() && end != atomIds.end()\n && begin->second < molecule->atomCount()\n && end->second < molecule->atomCount()) {\n bond = molecule->addBond(molecule->atom(begin->second),\n molecule->atom(end->second));\n }\n else { \/\/ Couldn't parse the bond begin and end.\n return false;\n }\n }\n\n attribute = node.attribute(\"order\");\n if (attribute)\n bond.setOrder(atoi(attribute.value()));\n\n \/\/ Move on to the next bond node (if there is one).\n node = node.next_sibling(\"bond\");\n }\n\n return true;\n }\n\n bool success;\n Molecule *molecule;\n xml_node moleculeNode;\n std::map<std::string, size_t> atomIds;\n};\n}\n\nCmlFormat::CmlFormat()\n{\n}\n\nCmlFormat::~CmlFormat()\n{\n}\n\nbool CmlFormat::readFile(const std::string &fileName)\n{\n \/\/ Read the file into a string.\n std::ifstream file(fileName.c_str());\n if (!file.is_open()) {\n cout << \"Error opening file: \" << fileName << endl;\n return false;\n }\n\n xml_document document;\n pugi::xml_parse_result result = document.load(file);\n if (!result) {\n cout << \"Error parsing XML: \" << result.description() << endl;\n return false;\n }\n\n CmlFormatPrivate parser(m_molecules, document);\n\n return true;\n}\n\nbool CmlFormat::writeFile(const std::string &)\n{\n return true;\n}\n\nMolecule * CmlFormat::molecule(size_t index)\n{\n if (index < m_molecules.size())\n return m_molecules[index];\n else\n return 0;\n}\n\n} \/\/ end Io namespace\n} \/\/ end Avogadro namespace\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <vector>\n#include \"allocore\/system\/al_Time.hpp\"\n#include \"allocore\/graphics\/al_OpenGL.hpp\"\n#include \"allocore\/graphics\/al_Screenshot.hpp\"\n\nnamespace al{\n\nbool Screenshot::save(unsigned w, unsigned h, const std::string& filePath){\n\tstd::ofstream fs;\n\tauto derivedFilePath = filePath;\n\tif(derivedFilePath.empty()){\n\t\tderivedFilePath = mPath + \"screenshot_\" + timecodeNow(\"D_HMS\") + \".\" + mExt;\n\t}\n\n\tfs.open(derivedFilePath);\n\n\tif(!fs.is_open()) return false;\n\n\tstd::vector<unsigned char> pix(w*h*3, 0);\n\tglReadPixels(0,0, w,h, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)&pix[0]);\n\t\/\/printf(\"%d %d %d\\n\", pix[0], pix[1], pix[2]);\n\n\tauto lsB = [](unsigned x){ return (unsigned char)(x&255); };\n\tauto msB = [](unsigned x){ return (unsigned char)((x>>8)&255); };\n\n\t\/\/ TGA (simplest format, widely supported)\n\t\/\/ http:\/\/www.paulbourke.net\/dataformats\/tga\/\n\tunsigned char hdr[18] = {\n\t\t0,\t\t\t\/\/ image ID length\n\t\t0,\t\t\t\/\/ color map\n\t\t2,\t\t\t\/\/ uncompressed true-color\n\t\t0,0,0,0,0,\t\/\/ color map\n\t\t0,0, 0,0,\t\/\/ image origin\n\t\tlsB(w), msB(w), lsB(h), msB(h), \/\/ width,height in pixels\n\t\t24,\t\t\t\/\/ bits\/pixel\n\t\t0\t\t\t\/\/ image descriptor\n\t};\n\tfs.write((char*)hdr, sizeof(hdr));\n\t\/\/ Annoyingly, TGA is little endian, so we have to write BGR\n\tfor(unsigned i=0; i<pix.size(); i+=3) std::swap(pix[i], pix[i+2]);\n\tfs.write((char*)&pix[0], pix.size());\n\n\t\/\/ Other potential formats to support in future...\n\n\t\/\/ PNG (really complicated)\n\t\/\/unsigned char hdr[] = {137,'P','N','G',13,10,26,10};\n\n\t\/\/ PBM (simple, but ASCII format so big files)\n\n\t\/* TIFF (a bit complicated)\n\t\/\/ http:\/\/paulbourke.net\/dataformats\/tiff\/\n\t\/\/ http:\/\/www.fileformat.info\/format\/tiff\/corion.htm\n\tfs.open(RUN_MAIN_SOURCE_PATH \"screenshot.tif.txt\");\n\tunsigned char hdr[] = {\n\t\t'M','M',0,42,0,0,0,8, \/\/ big endian\n\t\t0x01,0x00, 0,3, 0,0,0,1, msB(w), lsB(w), 0,0), \/\/ width\n\t\t0x01,0x01, 0,3, 0,0,0,1, msB(h), lsB(h), 0,0), \/\/ height\n\t\t0x01,0x02, 0,3, 0,0,0,1, 0, 24, 0,0, \/\/ bits\/sample\n\t\t0x01,0x03, 0,3, 0,0,0,1, 0, 1, 0,0, \/\/ compression\n\t\t0x01,0x06, 0,3, 0,0,0,1, 0, 2, 0,0, \/\/ RGB\n\t};\n\t\/\/fs.write((char*)hdr,8);\n\t\/\/*\/\n\n\treturn true;\n}\n\n} \/\/ al::\n<commit_msg>Screenshot: open file in binary mode<commit_after>#include <fstream>\n#include <vector>\n#include \"allocore\/system\/al_Time.hpp\"\n#include \"allocore\/graphics\/al_OpenGL.hpp\"\n#include \"allocore\/graphics\/al_Screenshot.hpp\"\n\nnamespace al{\n\nbool Screenshot::save(unsigned w, unsigned h, const std::string& filePath){\n\tauto derivedFilePath = filePath;\n\tif(derivedFilePath.empty()){\n\t\tderivedFilePath = mPath + \"screenshot_\" + timecodeNow(\"D_HMS\") + \".\" + mExt;\n\t}\n\n\tstd::ofstream fs(derivedFilePath, std::ofstream::out | std::ofstream::binary);\n\n\tif(!fs.is_open()) return false;\n\n\tstd::vector<unsigned char> pix(w*h*3, 0);\n\tglReadPixels(0,0, w,h, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)&pix[0]);\n\t\/\/printf(\"%d %d %d\\n\", pix[0], pix[1], pix[2]);\n\n\tauto lsB = [](unsigned x){ return (unsigned char)(x&255); };\n\tauto msB = [](unsigned x){ return (unsigned char)((x>>8)&255); };\n\n\t\/\/ TGA (simplest format, widely supported)\n\t\/\/ http:\/\/www.paulbourke.net\/dataformats\/tga\/\n\tunsigned char hdr[18] = {\n\t\t0,\t\t\t\/\/ image ID length\n\t\t0,\t\t\t\/\/ color map\n\t\t2,\t\t\t\/\/ uncompressed true-color\n\t\t0,0,0,0,0,\t\/\/ color map\n\t\t0,0, 0,0,\t\/\/ image origin\n\t\tlsB(w), msB(w), lsB(h), msB(h), \/\/ width,height in pixels\n\t\t24,\t\t\t\/\/ bits\/pixel\n\t\t0\t\t\t\/\/ descriptor: 00vhaaaa - v\/h vert\/hor flip, a alpha bits\n\t};\n\tfs.write((char*)hdr, sizeof(hdr));\n\t\/\/ Annoyingly, TGA is little endian, so we have to write BGR\n\tfor(unsigned i=0; i<pix.size(); i+=3) std::swap(pix[i], pix[i+2]);\n\tfs.write((char*)&pix[0], pix.size());\n\n\t\/\/ Other potential formats to support in future...\n\n\t\/\/ PNG (really complicated)\n\t\/\/unsigned char hdr[] = {137,'P','N','G',13,10,26,10};\n\n\t\/\/ PBM (simple, but ASCII format so big files)\n\n\t\/* TIFF (a bit complicated)\n\t\/\/ http:\/\/paulbourke.net\/dataformats\/tiff\/\n\t\/\/ http:\/\/www.fileformat.info\/format\/tiff\/corion.htm\n\tfs.open(RUN_MAIN_SOURCE_PATH \"screenshot.tif.txt\");\n\tunsigned char hdr[] = {\n\t\t'M','M',0,42,0,0,0,8, \/\/ big endian\n\t\t0x01,0x00, 0,3, 0,0,0,1, msB(w), lsB(w), 0,0), \/\/ width\n\t\t0x01,0x01, 0,3, 0,0,0,1, msB(h), lsB(h), 0,0), \/\/ height\n\t\t0x01,0x02, 0,3, 0,0,0,1, 0, 24, 0,0, \/\/ bits\/sample\n\t\t0x01,0x03, 0,3, 0,0,0,1, 0, 1, 0,0, \/\/ compression\n\t\t0x01,0x06, 0,3, 0,0,0,1, 0, 2, 0,0, \/\/ RGB\n\t};\n\t\/\/fs.write((char*)hdr,8);\n\t\/\/*\/\n\n\treturn true;\n}\n\n} \/\/ al::\n<|endoftext|>"} {"text":"<commit_before>#include \"analyzing_dataflash_message_handler.h\"\n\nvoid Analyzing_DataFlash_Message_Handler::handle_format_message_received(const char *name, const struct log_Format &format, const char *msg) {\n uint8_t new_msg_type = ((struct log_Format*)(msg))->type;\n if (streq(name, \"AHR2\")) {\n ahr2_handler= new LA_MsgHandler_AHR2(name, format, _analyze, _vehicle);\n handlers[new_msg_type] = ahr2_handler;\n if (have_pos) {\n ahr2_handler->set_canonical_for_position(false);\n }\n if (have_orgn) {\n ahr2_handler->set_canonical_for_origin(false);\n }\n } else if (streq(name, \"ATT\")) {\n handlers[new_msg_type] = new LA_MsgHandler_ATT(name, format, _analyze, _vehicle);\n } else if (streq(name, \"BARO\")) {\n handlers[new_msg_type] = new LA_MsgHandler_BARO(name, format, _analyze, _vehicle);\n } else if (streq(name, \"EKF1\")) {\n handlers[new_msg_type] = new LA_MsgHandler_EKF1(name, format, _analyze, _vehicle);\n } else if (streq(name, \"EKF4\")) {\n handlers[new_msg_type] = new LA_MsgHandler_EKF4(name, format, _analyze, _vehicle);\n } else if (streq(name, \"ERR\")) {\n handlers[new_msg_type] = new LA_MsgHandler_ERR(name, format, _analyze, _vehicle);\n } else if (streq(name, \"EV\")) {\n handlers[new_msg_type] = new LA_MsgHandler_EV(name, format, _analyze, _vehicle);\n } else if (streq(name, \"GPS\")) {\n handlers[new_msg_type] = new LA_MsgHandler_GPS(name, format, _analyze, _vehicle);\n } else if (streq(name, \"GPS2\")) {\n handlers[new_msg_type] = new LA_MsgHandler_GPS(name, format, _analyze, _vehicle);\n } else if (streq(name, \"MAG\")) {\n handlers[new_msg_type] = new LA_MsgHandler_MAG(name, format, _analyze, _vehicle);\n } else if (streq(name, \"MAG2\")) {\n handlers[new_msg_type] = new LA_MsgHandler_MAG(name, format, _analyze, _vehicle);\n } else if (streq(name, \"MAG3\")) {\n handlers[new_msg_type] = new LA_MsgHandler_MAG(name, format, _analyze, _vehicle);\n } else if (streq(name, \"MSG\")) {\n handlers[new_msg_type] = new LA_MsgHandler_MSG(name, format, _analyze, _vehicle);\n } else if (streq(name, \"ORGN\")) {\n have_orgn = true;\n handlers[new_msg_type] = new LA_MsgHandler_ORGN(name, format, _analyze, _vehicle);\n if (ahr2_handler != NULL) {\n ahr2_handler->set_canonical_for_origin(false);\n }\n } else if (streq(name, \"PARM\")) {\n handlers[new_msg_type] = new LA_MsgHandler_PARM(name, format, _analyze, _vehicle);\n } else if (streq(name, \"PM\")) {\n handlers[new_msg_type] = new LA_MsgHandler_PM(name, format, _analyze, _vehicle);\n } else if (streq(name, \"POS\")) {\n handlers[new_msg_type] = new LA_MsgHandler_POS(name, format, _analyze, _vehicle);\n have_pos = true;\n if (ahr2_handler != NULL) {\n ahr2_handler->set_canonical_for_position(false);\n }\n } else if (streq(name, \"RCOU\")) {\n handlers[new_msg_type] = new LA_MsgHandler_RCOU(name, format, _analyze, _vehicle);\n } else if (streq(name, \"STAT\")) {\n handlers[new_msg_type] = new LA_MsgHandler_STAT(name, format, _analyze, _vehicle);\n } else if (streq(name, \"VIBE\")) {\n handlers[new_msg_type] = new LA_MsgHandler_VIBE(name, format, _analyze, _vehicle);\n } else {\n return;\n }\n if (handlers[new_msg_type] == NULL) {\n ::fprintf(stderr, \"Failed to construct\");\n abort();\n }\n}\n\n\nvoid Analyzing_DataFlash_Message_Handler::handle_message_received(const struct log_Format &format, const uint8_t *msg)\n{\n\n LA_MsgHandler *handler = handlers[format.type];\n if (handler == NULL) {\n \/\/ ::fprintf(stderr, \"No handler for (%u) (%s)\\n\", format.type, format_names[format.type]);\n return;\n }\n\n handler->process(msg);\n}\n\nvoid Analyzing_DataFlash_Message_Handler::end_of_log(uint32_t packet_count, uint64_t bytes_dropped UNUSED)\n{\n _analyze->end_of_log(packet_count);\n}\n<commit_msg>analyzing_dataflash_message_handler: handle IMU messages<commit_after>#include \"analyzing_dataflash_message_handler.h\"\n\nvoid Analyzing_DataFlash_Message_Handler::handle_format_message_received(const char *name, const struct log_Format &format, const char *msg) {\n uint8_t new_msg_type = ((struct log_Format*)(msg))->type;\n if (streq(name, \"AHR2\")) {\n ahr2_handler= new LA_MsgHandler_AHR2(name, format, _analyze, _vehicle);\n handlers[new_msg_type] = ahr2_handler;\n if (have_pos) {\n ahr2_handler->set_canonical_for_position(false);\n }\n if (have_orgn) {\n ahr2_handler->set_canonical_for_origin(false);\n }\n } else if (streq(name, \"ATT\")) {\n handlers[new_msg_type] = new LA_MsgHandler_ATT(name, format, _analyze, _vehicle);\n } else if (streq(name, \"BARO\")) {\n handlers[new_msg_type] = new LA_MsgHandler_BARO(name, format, _analyze, _vehicle);\n } else if (streq(name, \"EKF1\")) {\n handlers[new_msg_type] = new LA_MsgHandler_EKF1(name, format, _analyze, _vehicle);\n } else if (streq(name, \"EKF4\")) {\n handlers[new_msg_type] = new LA_MsgHandler_EKF4(name, format, _analyze, _vehicle);\n } else if (streq(name, \"ERR\")) {\n handlers[new_msg_type] = new LA_MsgHandler_ERR(name, format, _analyze, _vehicle);\n } else if (streq(name, \"EV\")) {\n handlers[new_msg_type] = new LA_MsgHandler_EV(name, format, _analyze, _vehicle);\n } else if (streq(name, \"GPS\")) {\n handlers[new_msg_type] = new LA_MsgHandler_GPS(name, format, _analyze, _vehicle);\n } else if (streq(name, \"GPS2\")) {\n handlers[new_msg_type] = new LA_MsgHandler_GPS(name, format, _analyze, _vehicle);\n } else if (streq(name, \"IMU\")) {\n handlers[new_msg_type] = new LA_MsgHandler_IMU(name, format, _analyze, _vehicle);\n } else if (streq(name, \"IMU2\")) {\n handlers[new_msg_type] = new LA_MsgHandler_IMU(name, format, _analyze, _vehicle);\n } else if (streq(name, \"IMU3\")) {\n handlers[new_msg_type] = new LA_MsgHandler_IMU(name, format, _analyze, _vehicle);\n } else if (streq(name, \"MAG\")) {\n handlers[new_msg_type] = new LA_MsgHandler_MAG(name, format, _analyze, _vehicle);\n } else if (streq(name, \"MAG2\")) {\n handlers[new_msg_type] = new LA_MsgHandler_MAG(name, format, _analyze, _vehicle);\n } else if (streq(name, \"MAG3\")) {\n handlers[new_msg_type] = new LA_MsgHandler_MAG(name, format, _analyze, _vehicle);\n } else if (streq(name, \"MSG\")) {\n handlers[new_msg_type] = new LA_MsgHandler_MSG(name, format, _analyze, _vehicle);\n } else if (streq(name, \"ORGN\")) {\n have_orgn = true;\n handlers[new_msg_type] = new LA_MsgHandler_ORGN(name, format, _analyze, _vehicle);\n if (ahr2_handler != NULL) {\n ahr2_handler->set_canonical_for_origin(false);\n }\n } else if (streq(name, \"PARM\")) {\n handlers[new_msg_type] = new LA_MsgHandler_PARM(name, format, _analyze, _vehicle);\n } else if (streq(name, \"PM\")) {\n handlers[new_msg_type] = new LA_MsgHandler_PM(name, format, _analyze, _vehicle);\n } else if (streq(name, \"POS\")) {\n handlers[new_msg_type] = new LA_MsgHandler_POS(name, format, _analyze, _vehicle);\n have_pos = true;\n if (ahr2_handler != NULL) {\n ahr2_handler->set_canonical_for_position(false);\n }\n } else if (streq(name, \"RCOU\")) {\n handlers[new_msg_type] = new LA_MsgHandler_RCOU(name, format, _analyze, _vehicle);\n } else if (streq(name, \"STAT\")) {\n handlers[new_msg_type] = new LA_MsgHandler_STAT(name, format, _analyze, _vehicle);\n } else if (streq(name, \"VIBE\")) {\n handlers[new_msg_type] = new LA_MsgHandler_VIBE(name, format, _analyze, _vehicle);\n } else {\n return;\n }\n if (handlers[new_msg_type] == NULL) {\n ::fprintf(stderr, \"Failed to construct\");\n abort();\n }\n}\n\n\nvoid Analyzing_DataFlash_Message_Handler::handle_message_received(const struct log_Format &format, const uint8_t *msg)\n{\n\n LA_MsgHandler *handler = handlers[format.type];\n if (handler == NULL) {\n \/\/ ::fprintf(stderr, \"No handler for (%u) (%s)\\n\", format.type, format_names[format.type]);\n return;\n }\n\n handler->process(msg);\n}\n\nvoid Analyzing_DataFlash_Message_Handler::end_of_log(uint32_t packet_count, uint64_t bytes_dropped UNUSED)\n{\n _analyze->end_of_log(packet_count);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n\n#include <setjmp.h>\n\n#include <readline\/readline.h>\n#include <readline\/history.h>\n\n#include \"shared.hh\"\n#include \"eval.hh\"\n#include \"eval-inline.hh\"\n#include \"store-api.hh\"\n#include \"common-opts.hh\"\n\nusing namespace std;\nusing namespace nix;\n\n\nstring programId = \"nix-repl\";\n\n\nstruct NixRepl\n{\n string curDir;\n EvalState state;\n\n StaticEnv staticEnv;\n Env * env;\n int displ;\n\n NixRepl();\n void mainLoop();\n void processLine(string line);\n void addAttrsToScope(Value & attrs);\n void addVarToScope(const Symbol & name, Value * v);\n Expr * parseString(string s);\n void evalString(string s, Value & v);\n};\n\n\nvoid printHelp()\n{\n std::cout << \"Usage: nix-repl\\n\";\n}\n\n\n\/* Apparently, the only way to get readline() to return on Ctrl-C\n (SIGINT) is to use siglongjmp(). That's fucked up... *\/\nstatic sigjmp_buf sigintJmpBuf;\n\n\nstatic void sigintHandler(int signo)\n{\n siglongjmp(sigintJmpBuf, 1);\n}\n\n\nbool getLine(string & line)\n{\n struct sigaction act, old;\n act.sa_handler = sigintHandler;\n sigfillset(&act.sa_mask);\n act.sa_flags = 0;\n if (sigaction(SIGINT, &act, &old))\n throw SysError(\"installing handler for SIGINT\");\n\n if (sigsetjmp(sigintJmpBuf, 1))\n line = \"\";\n else {\n char * s = readline(\"nix-repl> \");\n if (!s) return false;\n line = chomp(string(s));\n free(s);\n if (line != \"\") {\n add_history(line.c_str());\n append_history(1, 0);\n }\n }\n\n _isInterrupted = 0;\n\n if (sigaction(SIGINT, &old, 0))\n throw SysError(\"restoring handler for SIGINT\");\n\n return true;\n}\n\n\nstring removeWhitespace(string s)\n{\n s = chomp(s);\n size_t n = s.find_first_not_of(\" \\n\\r\\t\");\n if (n != string::npos) s = string(s, n);\n return s;\n}\n\n\nNixRepl::NixRepl()\n : staticEnv(false, &state.staticBaseEnv)\n{\n curDir = absPath(\".\");\n\n env = &state.allocEnv(32768);\n env->up = &state.baseEnv;\n displ = 0;\n\n store = openStore();\n}\n\n\nvoid NixRepl::mainLoop()\n{\n std::cerr << \"Welcome to Nix version \" << NIX_VERSION << \". Type :? for help.\" << std::endl << std::endl;\n\n using_history();\n read_history(0);\n\n while (true) {\n string line;\n if (!getLine(line)) break;\n\n try {\n processLine(removeWhitespace(line));\n } catch (Error & e) {\n printMsg(lvlError, e.msg());\n }\n\n std::cout << std::endl;\n }\n\n std::cout << std::endl;\n}\n\n\nvoid NixRepl::processLine(string line)\n{\n if (line == \"\") return;\n\n if (string(line, 0, 2) == \":a\") {\n Value v;\n evalString(string(line, 2), v);\n addAttrsToScope(v);\n }\n\n else if (string(line, 0, 2) == \":l\") {\n state.resetFileCache();\n Path path = lookupFileArg(state, removeWhitespace(string(line, 2)));\n Value v, v2;\n state.evalFile(path, v);\n Bindings bindings;\n state.autoCallFunction(bindings, v, v2);\n addAttrsToScope(v2);\n }\n\n else if (string(line, 0, 2) == \":t\") {\n Value v;\n evalString(string(line, 2), v);\n std::cout << showType(v) << std::endl;\n }\n\n else if (string(line, 0, 1) == \":\") {\n throw Error(format(\"unknown command ‘%1%’\") % string(line, 0, 2));\n }\n\n else {\n Value v;\n evalString(line, v);\n state.strictForceValue(v);\n std::cout << v << std::endl;\n }\n}\n\n\nvoid NixRepl::addAttrsToScope(Value & attrs)\n{\n state.forceAttrs(attrs);\n foreach (Bindings::iterator, i, *attrs.attrs)\n addVarToScope(i->name, i->value);\n}\n\n\nvoid NixRepl::addVarToScope(const Symbol & name, Value * v)\n{\n staticEnv.vars[name] = displ;\n env->values[displ++] = v;\n}\n\n\nExpr * NixRepl::parseString(string s)\n{\n Expr * e = state.parseExprFromString(s, curDir, staticEnv);\n return e;\n}\n\n\nvoid NixRepl::evalString(string s, Value & v)\n{\n Expr * e = parseString(s);\n e->eval(state, *env, v);\n state.forceValue(v);\n}\n\n\nvoid run(nix::Strings args)\n{\n NixRepl repl;\n repl.mainLoop();\n}\n<commit_msg>Don't exit on SIGINT during evaluation<commit_after>#include <iostream>\n#include <cstdlib>\n\n#include <setjmp.h>\n\n#include <readline\/readline.h>\n#include <readline\/history.h>\n\n#include \"shared.hh\"\n#include \"eval.hh\"\n#include \"eval-inline.hh\"\n#include \"store-api.hh\"\n#include \"common-opts.hh\"\n\nusing namespace std;\nusing namespace nix;\n\n\nstring programId = \"nix-repl\";\n\n\nstruct NixRepl\n{\n string curDir;\n EvalState state;\n\n StaticEnv staticEnv;\n Env * env;\n int displ;\n\n NixRepl();\n void mainLoop();\n void processLine(string line);\n void addAttrsToScope(Value & attrs);\n void addVarToScope(const Symbol & name, Value * v);\n Expr * parseString(string s);\n void evalString(string s, Value & v);\n};\n\n\nvoid printHelp()\n{\n std::cout << \"Usage: nix-repl\\n\";\n}\n\n\n\/* Apparently, the only way to get readline() to return on Ctrl-C\n (SIGINT) is to use siglongjmp(). That's fucked up... *\/\nstatic sigjmp_buf sigintJmpBuf;\n\n\nstatic void sigintHandler(int signo)\n{\n siglongjmp(sigintJmpBuf, 1);\n}\n\n\nbool getLine(string & line)\n{\n struct sigaction act, old;\n act.sa_handler = sigintHandler;\n sigfillset(&act.sa_mask);\n act.sa_flags = 0;\n if (sigaction(SIGINT, &act, &old))\n throw SysError(\"installing handler for SIGINT\");\n\n if (sigsetjmp(sigintJmpBuf, 1))\n line = \"\";\n else {\n char * s = readline(\"nix-repl> \");\n if (!s) return false;\n line = chomp(string(s));\n free(s);\n if (line != \"\") {\n add_history(line.c_str());\n append_history(1, 0);\n }\n }\n\n _isInterrupted = 0;\n\n if (sigaction(SIGINT, &old, 0))\n throw SysError(\"restoring handler for SIGINT\");\n\n return true;\n}\n\n\nstring removeWhitespace(string s)\n{\n s = chomp(s);\n size_t n = s.find_first_not_of(\" \\n\\r\\t\");\n if (n != string::npos) s = string(s, n);\n return s;\n}\n\n\nNixRepl::NixRepl()\n : staticEnv(false, &state.staticBaseEnv)\n{\n curDir = absPath(\".\");\n\n env = &state.allocEnv(32768);\n env->up = &state.baseEnv;\n displ = 0;\n\n store = openStore();\n}\n\n\nvoid NixRepl::mainLoop()\n{\n std::cerr << \"Welcome to Nix version \" << NIX_VERSION << \". Type :? for help.\" << std::endl << std::endl;\n\n using_history();\n read_history(0);\n\n while (true) {\n string line;\n if (!getLine(line)) break;\n\n try {\n processLine(removeWhitespace(line));\n } catch (Error & e) {\n printMsg(lvlError, e.msg());\n } catch (Interrupted & e) {\n printMsg(lvlError, e.msg());\n }\n\n std::cout << std::endl;\n }\n\n std::cout << std::endl;\n}\n\n\nvoid NixRepl::processLine(string line)\n{\n if (line == \"\") return;\n\n if (string(line, 0, 2) == \":a\") {\n Value v;\n evalString(string(line, 2), v);\n addAttrsToScope(v);\n }\n\n else if (string(line, 0, 2) == \":l\") {\n state.resetFileCache();\n Path path = lookupFileArg(state, removeWhitespace(string(line, 2)));\n Value v, v2;\n state.evalFile(path, v);\n Bindings bindings;\n state.autoCallFunction(bindings, v, v2);\n addAttrsToScope(v2);\n }\n\n else if (string(line, 0, 2) == \":t\") {\n Value v;\n evalString(string(line, 2), v);\n std::cout << showType(v) << std::endl;\n }\n\n else if (string(line, 0, 1) == \":\") {\n throw Error(format(\"unknown command ‘%1%’\") % string(line, 0, 2));\n }\n\n else {\n Value v;\n evalString(line, v);\n state.strictForceValue(v);\n std::cout << v << std::endl;\n }\n}\n\n\nvoid NixRepl::addAttrsToScope(Value & attrs)\n{\n state.forceAttrs(attrs);\n foreach (Bindings::iterator, i, *attrs.attrs)\n addVarToScope(i->name, i->value);\n printMsg(lvlError, format(\"added %1% variables\") % attrs.attrs->size());\n}\n\n\nvoid NixRepl::addVarToScope(const Symbol & name, Value * v)\n{\n staticEnv.vars[name] = displ;\n env->values[displ++] = v;\n}\n\n\nExpr * NixRepl::parseString(string s)\n{\n Expr * e = state.parseExprFromString(s, curDir, staticEnv);\n return e;\n}\n\n\nvoid NixRepl::evalString(string s, Value & v)\n{\n Expr * e = parseString(s);\n e->eval(state, *env, v);\n state.forceValue(v);\n}\n\n\nvoid run(nix::Strings args)\n{\n NixRepl repl;\n repl.mainLoop();\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n\r\n#include \"..\/libmmdpi\/mmdpi.h\"\r\n\/\/#include \"..\/gl_xfile\/gl_xfile.h\"\r\n\r\n#ifdef _WIN32\r\n#\tifdef _DEBUG\r\n#\t\tpragma comment( lib, \"..\/Debug\/libmmdpi.lib\" )\r\n#\telse\r\n#\t\tpragma comment( lib, \"..\/Release\/libmmdpi.lib\" )\r\n#\tendif\r\n#endif\r\n\r\n\/\/#ifdef _DEBUG\r\n\/\/\t#pragma comment( lib, \"..\/Debug\/gl_xfile.lib\" )\r\n\/\/#else\r\n\/\/\t#pragma comment( lib, \"..\/Release\/gl_xfile.lib\" )\r\n\/\/#endif\r\n\r\n\r\n#include <iostream>\r\n#include \"GL\/glut.h\"\r\n\r\n\r\nconst int\t\t_zoom_default_\t= -1024 * 2 * 0.1f;\/\/ * 16;\r\nfloat\t\t\t_y_pos_\t\t\t= 11 * 0.1f;\r\nstatic mmdpi*\tp = NULL;\r\nint\t\t\t\t_fps_\t\t\t= 30;\r\nint \t\t\tmotion_flag = 0;\r\nfloat\t\t\tZoom;\r\nfloat\t\t\tRotate;\r\n\r\nfloat\t\t\tRotationAxis[ 3 ];\r\n\r\nint\t\t\t\tscreen_width, screen_height;\r\n\r\nint\t\t\t\tArgc;\r\nconst char**\t\t\tArgv;\r\n\r\n#include \"fps.h\"\r\n\r\nFps* fps = NULL;\r\n\r\nvoid end( void );\r\n\r\nvoid display( void )\r\n{\r\n\tGLfloat light0pos[] = { 4.0, 16.0, -8.0, 1.0 };\r\n\t\r\n\tglEnable( GL_DEPTH_TEST );\r\n\r\n\tglEnable( GL_LIGHTING );\r\n\tglEnable( GL_LIGHT0 );\r\n\t\r\n\t\/\/glClearColor( 0.0, 0.0, 1.0, 1.0 );\t\/\/\tbule\r\n\t\/\/glClearColor( 0.0, 0.2, 0.0, 1.0 );\t\/\/\tbule\r\n\t\/\/glClearColor( 0.0, 0.0, 0.0, 1.0 );\t\/\/\tblack\r\n\tglClearColor( 1.0, 1.0, 1.0, 1.0 );\t\/\/\twhite\r\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\r\n\r\n\tglColor3d( 1.0, 0.0, 0.0 );\r\n\r\n\tglLightfv( GL_LIGHT0, GL_POSITION, light0pos );\r\n\r\n\tfloat diffuse[] = { 1.0, 1.0, 1.0, 1.0 };\r\n\tfloat ambient[] = { 1.0, 1.0, 1.0, 1.0 };\r\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse );\r\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, ambient );\r\n\r\n\tstatic float rot = 0.0f;\r\n\r\n\t\/\/ カメラ\r\n\tglMatrixMode( GL_MODELVIEW );\r\n \r\n\tglPushMatrix();\r\n\t{\r\n\t\/\/\tglRotatef( rot, 1, 0, 0 );\r\n\t\t\/\/glRotatef( 3.14f, 0, 1, 0 );\r\n\t\t\/\/glRotatef( rot, 0, 1, 0 );\r\n\t\t\/\/glTranslatef( 0, 0, Zoom );\r\n\r\n\t\t\/\/glutSolidTeapot( 0.5 );\r\n\r\n\t\tglRotatef( RotationAxis[ 0 ], 1, 0, 0 );\r\n\t\tglRotatef( RotationAxis[ 1 ], 0, 1, 0 );\r\n\r\n\t\tglScalef( 0.1f, 0.1f, 0.1f );\r\n\t\tp->draw();\r\n\t}\r\n\tglPopMatrix();\r\n\r\n\t\/\/rot += 0.1f;\r\n\r\n\tglutSwapBuffers();\r\n}\r\n\r\nvoid keyboard( unsigned char key, int x, int y )\r\n{\r\n\tswitch( key )\r\n\t{\r\n\tcase 'q':\r\n\tcase 'Q':\r\n\tcase '\\033': \/* '\\033' は ESC の ASCII コード *\/\r\n\t\tend();\r\n\t\texit( 0 );\r\n\tcase 'u':\r\n\t\t\/\/\tfps\r\n\t\tif( fps->get_fps() < 120 )\r\n\t\t{\r\n\t\t\tfps->set_fps( fps->get_fps() + 5 );\r\n\t\t\tp->set_fps( fps->get_fps() );\r\n\t\t}\r\n\t\tbreak;\r\n\tcase 'd':\r\n\t\tif( fps->get_fps() > 10 )\r\n\t\t{\r\n\t\t\tfps->set_fps( fps->get_fps() - 5 );\r\n\t\t\tp->set_fps( fps->get_fps() );\r\n\t\t}\r\n\t\tbreak;\r\n\treturn ;\r\n\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid sp_keyboard( int key, int x, int y )\r\n{\r\n\t\/\/static float\trotate\t= 0;\r\n\t\/\/static float\tzoom\t= _zoom_default_;\r\n\r\n\tswitch( key )\r\n\t{\r\n\t\tcase GLUT_KEY_PAGE_UP: \t_y_pos_ += 0.1f;\tbreak;\r\n\t\tcase GLUT_KEY_PAGE_DOWN:_y_pos_ -= 0.1f;\tbreak;\r\n\t\tcase GLUT_KEY_LEFT\t:\tRotate += -0.05f;\tbreak;\t\t\/\/\t←\r\n\t\tcase GLUT_KEY_UP\t:\tZoom += +4;\t\t\tbreak;\t\t\/\/\t↑\r\n\t\tcase GLUT_KEY_RIGHT\t:\tRotate += +0.05f;\tbreak;\t\t\/\/\t→\r\n\t\tcase GLUT_KEY_DOWN\t:\tZoom += -4;\t\t\tbreak;\t\t\/\/\t↓\r\n\t}\r\n\r\n\tglMatrixMode( GL_MODELVIEW );\r\n\tglLoadIdentity();\r\n\tgluLookAt( sin( Rotate ) * Zoom, _y_pos_, cos( Rotate ) * Zoom, 0, _y_pos_, 0, 0, 1, 0 );\r\n}\r\n\r\nvoid idle( void )\r\n{\r\n\t\/\/glutPostRedisplay();\r\n}\r\n\r\nvoid timer( int value ) \r\n{\r\n\t\/\/glutTimerFunc( fps->get_wait_time() * 1000.0f, timer, 0 );\r\n\tglutTimerFunc( 1000.0f \/ fps->get_fps(), timer, 0 );\r\n\tfps->draw();\r\n\tfps->update();\r\n\t\r\n\tif( motion_flag )\r\n\t{\r\n\t\tfloat\tframe = 30.0f \/ fps->get_mfps();\t\/\/fps->get_dframe();\r\n\t\t\/\/\tフレームを進める関数\r\n\t\t\/\/(MMD は1秒間に30フレームがデフォルト)\r\n\t\t\/\/\t60fpsで実行の場合、0.5frame ずつフレームにたいしてモーションを進める\r\n\t\t( *p->get_vmd( 0 ) ) += frame;\r\n\t\t\/\/( *p->get_vmd( 0 ) ) ++;\r\n\r\n\t\tif( p->get_vmd( 0 )->is_end() )\r\n\t\t\texit( 0 );\r\n\t}\r\n\t\r\n\tmmdpiMatrix\tmatrix;\r\n\tstatic float dy = 3.14f;\r\n\t\/\/dy += 0.01f;\r\n\t\/\/matrix.rotation( 0, 1, 0, dy );\r\n\t\/\/matrix.rotation( 0, 1, 0, 3.14f );\r\n\tp->set_bone_matrix( 0, matrix );\r\n\r\n\tglutPostRedisplay();\r\n}\r\n\r\nvoid resize( int w, int h )\r\n{\r\n\tglViewport( 0, 0, w, h );\r\n\t\r\n\tglMatrixMode( GL_MODELVIEW );\r\n\tglLoadIdentity();\r\n\t\/\/gluLookAt( 0.0f, _y_pos_, _zoom_default_, 0, _y_pos_, 0, 0, 1, 0 );\r\n\tgluLookAt( sin( Rotate ) * Zoom, _y_pos_, cos( Rotate ) * Zoom, 0, _y_pos_, 0, 0, 1, 0 );\r\n\r\n\tglMatrixMode( GL_PROJECTION );\r\n\tglLoadIdentity();\r\n\t\/\/\t透視投影\r\n\tgluPerspective( 2.0f \/ 3, ( GLfloat )w \/ ( GLfloat )h, 1.0f, 65536.0f );\r\n\t\/\/\t正投影\r\n\t\/\/glOrtho( -1.5, 1.5, -1.5, 1.5, -1.0, 1.0 );\r\n\r\n\tglMatrixMode( GL_MODELVIEW );\r\n\r\n\tscreen_width = w;\r\n\tscreen_height = h;\r\n}\r\n\r\nint\t\tMousePushFlag = 0;\r\nint\t\tMousePosX = 0, MousePosY = 0;\r\nvoid mouse_func( int button, int state, int x, int y )\r\n{\t\t\t\r\n\tswitch( button )\r\n\t{\r\n\tcase GLUT_LEFT_BUTTON:\r\n\t\t{\r\n\t\t\tswitch( state )\r\n\t\t\t{\r\n\t\t\tcase GLUT_DOWN:\r\n\t\t\t\t{\r\n\t\t\t\t\tMousePushFlag = 1;\r\n\t\t\t\t\tMousePosX = x;\r\n\t\t\t\t\tMousePosY = y;\r\n\t\t\t\t} break;\r\n\t\t\tcase GLUT_UP:\r\n\t\t\t\t{\r\n\t\t\t\t\tMousePushFlag = 0;\r\n\t\t\t\t} break;\r\n\t\t\t}\r\n\t\t} break;\r\n\t}\r\n}\r\n\r\n\/\/\t押してないとき\r\nvoid mouse_passive_func( int x, int y )\r\n{\r\n}\r\n\r\n\/\/\t押してるとき\r\nvoid mouse_motion( int x, int y )\r\n{\r\n\tif( MousePushFlag )\r\n\t{\r\n\t\tfloat\tdy = ( float )( x - MousePosX ) \/ 4.0f;\r\n\t\tfloat\tdx = ( float )( y - MousePosY ) \/ 4.0f;\r\n\r\n\t\tMousePosX = x;\r\n\t\tMousePosY = y;\r\n\r\n\t\tRotationAxis[ 0 ] -= dx;\r\n\t\tRotationAxis[ 1 ] += dy;\r\n\t}\r\n}\r\n\r\nvoid init( void )\r\n{\r\n\tp = new mmdpi();\t\r\n\tif( p == NULL )\r\n\t\texit( 0 );\r\n\t\/\/p->set_physics_engine( 0 );\r\n\t\r\n\t\/\/ Test\r\n\tputs( Argv[ 1 ] );\r\n\tif( p->load( Argv[ 1 ] ) )\r\n\t\/\/if( p->load( \"udon\/udon.pmx\" ) )\r\n\t\/\/if( p->load( \"sakuya\/sakuya.pmx\" ) )\r\n\t\texit( 0 );\r\n\t\/\/p->load( \"..\/Release\/reimu\/reimu.pmd\"\/*Argv[ 1 ]*\/ );\r\n\t\r\n\t\/\/\tSound\r\n\tif( Argc > 4 )\r\n\t\tsystem( ( const char* )Argv[ 4 ] );\r\n\t\r\n\tif( Argc > 2 )\r\n\t{\r\n\t\tmotion_flag = 1;\r\n\t\tputs( Argv[ 2 ] );\r\n\t\tif( p->vmd_load( Argv[ 2 ] ) )\r\n\t\t\tmotion_flag = 0;\r\n\t}\r\n\t\/\/motion_flag = 1;\r\n\t\/\/if( p->vmd_load( \"vmd\/nolifequeen.vmd\" ) )\r\n\t\/\/\tmotion_flag = 0;\r\n\r\n\tif( Argc > 3 )\r\n\t{\r\n\t\t_fps_ = atoi( Argv[ 3 ] );\r\n\t\t_fps_ = ( _fps_ < 6 || 480 < _fps_ )? 30.0f : _fps_ ;\r\n\t}\r\n\tfps = new Fps();\r\n\tfps->set_fps( _fps_ );\r\n\r\n\tp->set_fps( _fps_ );\r\n\r\n\tputs( \"END Loading.\" );\r\n}\r\n\r\nvoid end( void )\r\n{\r\n\tdelete fps;\r\n\tdelete p;\r\n}\r\n\r\nint main( int argc, char *argv[] )\r\n{\r\n\tif( argc < 2 )\r\n\t{\r\n\t\tprintf( \"モデル、モーションを!\\n\\n\" );\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\tZoom = _zoom_default_;\r\n\tRotate = 0;\r\n\r\n\tArgc = argc;\r\n\tArgv = argv;\r\n\t\r\n\tglutInitWindowPosition( 200, 200 );\r\n\tglutInitWindowSize( 640, 480 );\r\n\tglutInit( &argc, argv );\r\n\tglutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );\r\n\tglutCreateWindow( argv[ 0 ] );\r\n\r\n\tglutDisplayFunc( display );\r\n\tglutReshapeFunc( resize );\r\n\t\r\n\tglutKeyboardFunc( keyboard );\r\n\tglutSpecialFunc( sp_keyboard );\r\n\tglutMouseFunc( mouse_func );\r\n\tglutPassiveMotionFunc( mouse_passive_func );\r\n\tglutMotionFunc( mouse_motion );\r\n\r\n\tinit();\r\n\r\n\t\/\/glutIdleFunc( idle );\r\n\tglutTimerFunc( 1000.0f \/ 30.0f , timer, 0 );\r\n\r\n\tglutMainLoop();\r\n\r\n\tend();\r\n\r\n\treturn 0;\r\n}\r\n<commit_msg>Update gl_main.cpp<commit_after>\r\n\r\n#include \"..\/libmmdpi\/mmdpi.h\"\r\n\/\/#include \"..\/gl_xfile\/gl_xfile.h\"\r\n\r\n#ifdef _WIN32\r\n#\tifdef _DEBUG\r\n#\t\tpragma comment( lib, \"..\/Debug\/libmmdpi.lib\" )\r\n#\telse\r\n#\t\tpragma comment( lib, \"..\/Release\/libmmdpi.lib\" )\r\n#\tendif\r\n#endif\r\n\r\n\/\/#ifdef _DEBUG\r\n\/\/\t#pragma comment( lib, \"..\/Debug\/gl_xfile.lib\" )\r\n\/\/#else\r\n\/\/\t#pragma comment( lib, \"..\/Release\/gl_xfile.lib\" )\r\n\/\/#endif\r\n\r\n\r\n#include <iostream>\r\n#include \"GL\/glut.h\"\r\n\r\n\r\nconst int\t\t_zoom_default_\t= -1024 * 2 * 0.1f;\/\/ * 16;\r\nfloat\t\t\t_y_pos_\t\t\t= 11 * 0.1f;\r\nstatic mmdpi*\tp = NULL;\r\nint\t\t\t\t_fps_\t\t\t= 30;\r\nint \t\t\tmotion_flag = 0;\r\nfloat\t\t\tZoom;\r\nfloat\t\t\tRotate;\r\n\r\nfloat\t\t\tRotationAxis[ 3 ];\r\n\r\nint\t\t\tscreen_width, screen_height;\r\n\r\nint\t\t\tArgc;\r\nchar**\t\t\tArgv;\r\n\r\n#include \"fps.h\"\r\n\r\nFps* fps = NULL;\r\n\r\nvoid end( void );\r\n\r\nvoid display( void )\r\n{\r\n\tGLfloat light0pos[] = { 4.0, 16.0, -8.0, 1.0 };\r\n\t\r\n\tglEnable( GL_DEPTH_TEST );\r\n\r\n\tglEnable( GL_LIGHTING );\r\n\tglEnable( GL_LIGHT0 );\r\n\t\r\n\t\/\/glClearColor( 0.0, 0.0, 1.0, 1.0 );\t\/\/\tbule\r\n\t\/\/glClearColor( 0.0, 0.2, 0.0, 1.0 );\t\/\/\tbule\r\n\t\/\/glClearColor( 0.0, 0.0, 0.0, 1.0 );\t\/\/\tblack\r\n\tglClearColor( 1.0, 1.0, 1.0, 1.0 );\t\/\/\twhite\r\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\r\n\r\n\tglColor3d( 1.0, 0.0, 0.0 );\r\n\r\n\tglLightfv( GL_LIGHT0, GL_POSITION, light0pos );\r\n\r\n\tfloat diffuse[] = { 1.0, 1.0, 1.0, 1.0 };\r\n\tfloat ambient[] = { 1.0, 1.0, 1.0, 1.0 };\r\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse );\r\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, ambient );\r\n\r\n\tstatic float rot = 0.0f;\r\n\r\n\t\/\/ カメラ\r\n\tglMatrixMode( GL_MODELVIEW );\r\n \r\n\tglPushMatrix();\r\n\t{\r\n\t\/\/\tglRotatef( rot, 1, 0, 0 );\r\n\t\t\/\/glRotatef( 3.14f, 0, 1, 0 );\r\n\t\t\/\/glRotatef( rot, 0, 1, 0 );\r\n\t\t\/\/glTranslatef( 0, 0, Zoom );\r\n\r\n\t\t\/\/glutSolidTeapot( 0.5 );\r\n\r\n\t\tglRotatef( RotationAxis[ 0 ], 1, 0, 0 );\r\n\t\tglRotatef( RotationAxis[ 1 ], 0, 1, 0 );\r\n\r\n\t\tglScalef( 0.1f, 0.1f, 0.1f );\r\n\t\tp->draw();\r\n\t}\r\n\tglPopMatrix();\r\n\r\n\t\/\/rot += 0.1f;\r\n\r\n\tglutSwapBuffers();\r\n}\r\n\r\nvoid keyboard( unsigned char key, int x, int y )\r\n{\r\n\tswitch( key )\r\n\t{\r\n\tcase 'q':\r\n\tcase 'Q':\r\n\tcase '\\033': \/* '\\033' は ESC の ASCII コード *\/\r\n\t\tend();\r\n\t\texit( 0 );\r\n\tcase 'u':\r\n\t\t\/\/\tfps\r\n\t\tif( fps->get_fps() < 120 )\r\n\t\t{\r\n\t\t\tfps->set_fps( fps->get_fps() + 5 );\r\n\t\t\tp->set_fps( fps->get_fps() );\r\n\t\t}\r\n\t\tbreak;\r\n\tcase 'd':\r\n\t\tif( fps->get_fps() > 10 )\r\n\t\t{\r\n\t\t\tfps->set_fps( fps->get_fps() - 5 );\r\n\t\t\tp->set_fps( fps->get_fps() );\r\n\t\t}\r\n\t\tbreak;\r\n\treturn ;\r\n\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid sp_keyboard( int key, int x, int y )\r\n{\r\n\t\/\/static float\trotate\t= 0;\r\n\t\/\/static float\tzoom\t= _zoom_default_;\r\n\r\n\tswitch( key )\r\n\t{\r\n\t\tcase GLUT_KEY_PAGE_UP: \t_y_pos_ += 0.1f;\tbreak;\r\n\t\tcase GLUT_KEY_PAGE_DOWN:_y_pos_ -= 0.1f;\tbreak;\r\n\t\tcase GLUT_KEY_LEFT\t:\tRotate += -0.05f;\tbreak;\t\t\/\/\t←\r\n\t\tcase GLUT_KEY_UP\t:\tZoom += +4;\t\t\tbreak;\t\t\/\/\t↑\r\n\t\tcase GLUT_KEY_RIGHT\t:\tRotate += +0.05f;\tbreak;\t\t\/\/\t→\r\n\t\tcase GLUT_KEY_DOWN\t:\tZoom += -4;\t\t\tbreak;\t\t\/\/\t↓\r\n\t}\r\n\r\n\tglMatrixMode( GL_MODELVIEW );\r\n\tglLoadIdentity();\r\n\tgluLookAt( sin( Rotate ) * Zoom, _y_pos_, cos( Rotate ) * Zoom, 0, _y_pos_, 0, 0, 1, 0 );\r\n}\r\n\r\nvoid idle( void )\r\n{\r\n\t\/\/glutPostRedisplay();\r\n}\r\n\r\nvoid timer( int value ) \r\n{\r\n\t\/\/glutTimerFunc( fps->get_wait_time() * 1000.0f, timer, 0 );\r\n\tglutTimerFunc( 1000.0f \/ fps->get_fps(), timer, 0 );\r\n\tfps->draw();\r\n\tfps->update();\r\n\t\r\n\tif( motion_flag )\r\n\t{\r\n\t\tfloat\tframe = 30.0f \/ fps->get_mfps();\t\/\/fps->get_dframe();\r\n\t\t\/\/\tフレームを進める関数\r\n\t\t\/\/(MMD は1秒間に30フレームがデフォルト)\r\n\t\t\/\/\t60fpsで実行の場合、0.5frame ずつフレームにたいしてモーションを進める\r\n\t\t( *p->get_vmd( 0 ) ) += frame;\r\n\t\t\/\/( *p->get_vmd( 0 ) ) ++;\r\n\r\n\t\tif( p->get_vmd( 0 )->is_end() )\r\n\t\t\texit( 0 );\r\n\t}\r\n\t\r\n\tmmdpiMatrix\tmatrix;\r\n\tstatic float dy = 3.14f;\r\n\t\/\/dy += 0.01f;\r\n\t\/\/matrix.rotation( 0, 1, 0, dy );\r\n\t\/\/matrix.rotation( 0, 1, 0, 3.14f );\r\n\tp->set_bone_matrix( 0, matrix );\r\n\r\n\tglutPostRedisplay();\r\n}\r\n\r\nvoid resize( int w, int h )\r\n{\r\n\tglViewport( 0, 0, w, h );\r\n\t\r\n\tglMatrixMode( GL_MODELVIEW );\r\n\tglLoadIdentity();\r\n\t\/\/gluLookAt( 0.0f, _y_pos_, _zoom_default_, 0, _y_pos_, 0, 0, 1, 0 );\r\n\tgluLookAt( sin( Rotate ) * Zoom, _y_pos_, cos( Rotate ) * Zoom, 0, _y_pos_, 0, 0, 1, 0 );\r\n\r\n\tglMatrixMode( GL_PROJECTION );\r\n\tglLoadIdentity();\r\n\t\/\/\t透視投影\r\n\tgluPerspective( 2.0f \/ 3, ( GLfloat )w \/ ( GLfloat )h, 1.0f, 65536.0f );\r\n\t\/\/\t正投影\r\n\t\/\/glOrtho( -1.5, 1.5, -1.5, 1.5, -1.0, 1.0 );\r\n\r\n\tglMatrixMode( GL_MODELVIEW );\r\n\r\n\tscreen_width = w;\r\n\tscreen_height = h;\r\n}\r\n\r\nint\t\tMousePushFlag = 0;\r\nint\t\tMousePosX = 0, MousePosY = 0;\r\nvoid mouse_func( int button, int state, int x, int y )\r\n{\t\t\t\r\n\tswitch( button )\r\n\t{\r\n\tcase GLUT_LEFT_BUTTON:\r\n\t\t{\r\n\t\t\tswitch( state )\r\n\t\t\t{\r\n\t\t\tcase GLUT_DOWN:\r\n\t\t\t\t{\r\n\t\t\t\t\tMousePushFlag = 1;\r\n\t\t\t\t\tMousePosX = x;\r\n\t\t\t\t\tMousePosY = y;\r\n\t\t\t\t} break;\r\n\t\t\tcase GLUT_UP:\r\n\t\t\t\t{\r\n\t\t\t\t\tMousePushFlag = 0;\r\n\t\t\t\t} break;\r\n\t\t\t}\r\n\t\t} break;\r\n\t}\r\n}\r\n\r\n\/\/\t押してないとき\r\nvoid mouse_passive_func( int x, int y )\r\n{\r\n}\r\n\r\n\/\/\t押してるとき\r\nvoid mouse_motion( int x, int y )\r\n{\r\n\tif( MousePushFlag )\r\n\t{\r\n\t\tfloat\tdy = ( float )( x - MousePosX ) \/ 4.0f;\r\n\t\tfloat\tdx = ( float )( y - MousePosY ) \/ 4.0f;\r\n\r\n\t\tMousePosX = x;\r\n\t\tMousePosY = y;\r\n\r\n\t\tRotationAxis[ 0 ] -= dx;\r\n\t\tRotationAxis[ 1 ] += dy;\r\n\t}\r\n}\r\n\r\nvoid init( void )\r\n{\r\n\tp = new mmdpi();\t\r\n\tif( p == NULL )\r\n\t\texit( 0 );\r\n\t\/\/p->set_physics_engine( 0 );\r\n\t\r\n\t\/\/ Test\r\n\tputs( Argv[ 1 ] );\r\n\tif( p->load( Argv[ 1 ] ) )\r\n\t\/\/if( p->load( \"udon\/udon.pmx\" ) )\r\n\t\/\/if( p->load( \"sakuya\/sakuya.pmx\" ) )\r\n\t\texit( 0 );\r\n\t\/\/p->load( \"..\/Release\/reimu\/reimu.pmd\"\/*Argv[ 1 ]*\/ );\r\n\t\r\n\t\/\/\/\/\tSound\r\n\t\/\/if( Argc > 4 )\r\n\t\/\/\tsystem( ( const char* )Argv[ 4 ] );\r\n\t\r\n\tif( Argc > 2 )\r\n\t{\r\n\t\tmotion_flag = 1;\r\n\t\tputs( Argv[ 2 ] );\r\n\t\tif( p->vmd_load( Argv[ 2 ] ) )\r\n\t\t\tmotion_flag = 0;\r\n\t}\r\n\t\/\/motion_flag = 1;\r\n\t\/\/if( p->vmd_load( \"vmd\/nolifequeen.vmd\" ) )\r\n\t\/\/\tmotion_flag = 0;\r\n\r\n\tif( Argc > 3 )\r\n\t{\r\n\t\t_fps_ = atoi( Argv[ 3 ] );\r\n\t\t_fps_ = ( _fps_ < 6 || 480 < _fps_ )? 30.0f : _fps_ ;\r\n\t}\r\n\tfps = new Fps();\r\n\tfps->set_fps( _fps_ );\r\n\r\n\tp->set_fps( _fps_ );\r\n\r\n\tputs( \"END Loading.\" );\r\n}\r\n\r\nvoid end( void )\r\n{\r\n\tdelete fps;\r\n\tdelete p;\r\n}\r\n\r\nint main( int argc, char *argv[] )\r\n{\r\n\tif( argc < 2 )\r\n\t{\r\n\t\tprintf( \"モデル、モーションを!\\n\\n\" );\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\tZoom = _zoom_default_;\r\n\tRotate = 0;\r\n\r\n\tArgc = argc;\r\n\tArgv = argv;\r\n\t\r\n\tglutInitWindowPosition( 200, 200 );\r\n\tglutInitWindowSize( 640, 480 );\r\n\tglutInit( &argc, argv );\r\n\tglutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );\r\n\tglutCreateWindow( argv[ 0 ] );\r\n\r\n\tglutDisplayFunc( display );\r\n\tglutReshapeFunc( resize );\r\n\t\r\n\tglutKeyboardFunc( keyboard );\r\n\tglutSpecialFunc( sp_keyboard );\r\n\tglutMouseFunc( mouse_func );\r\n\tglutPassiveMotionFunc( mouse_passive_func );\r\n\tglutMotionFunc( mouse_motion );\r\n\r\n\tinit();\r\n\r\n\t\/\/glutIdleFunc( idle );\r\n\tglutTimerFunc( 1000.0f \/ 30.0f , timer, 0 );\r\n\r\n\tglutMainLoop();\r\n\r\n\tend();\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Significantly increase timeouts to reduce flakiness<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 1999-2010 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n# include \"config.h\"\n\n\/*\n * This functor scans the design looking for dangling objects and\n * excess local signals. These deletions are not necessarily required\n * for proper functioning of anything, but they can clean up the\n * appearance of design files that are generated.\n *\/\n# include \"functor.h\"\n# include \"netlist.h\"\n# include \"compiler.h\"\n\nclass nodangle_f : public functor_t {\n public:\n void event(Design*des, NetEvent*ev);\n void signal(Design*des, NetNet*sig);\n\n unsigned iteration;\n unsigned stotal, etotal;\n bool scontinue, econtinue;\n bool scomplete, ecomplete;\n};\n\nvoid nodangle_f::event(Design*, NetEvent*ev)\n{\n if (ecomplete) return;\n\n\t\/* If there are no references to this event, then go right\n\t ahead and delete it. There is no use looking further at\n\t it. *\/\n if ((ev->nwait() + ev->ntrig() + ev->nexpr()) == 0) {\n\t delete ev;\n\t etotal += 1;\n\t return;\n }\n\n if (iteration == 0) {\n \/* Try to remove duplicate probes from the event. This\n is done as a separate initial pass to ensure similar\n events are detected as soon as possible in subsequent\n iterations. *\/\n for (unsigned idx = 0 ; idx < ev->nprobe() ; idx += 1) {\n unsigned jdx = idx + 1;\n while (jdx < ev->nprobe()) {\n NetEvProbe*ip = ev->probe(idx);\n NetEvProbe*jp = ev->probe(jdx);\n\n if (ip->edge() != jp->edge()) {\n jdx += 1;\n continue;\n }\n\n bool fully_connected = true;\n for (unsigned jpin = 0; jpin < jp->pin_count(); jpin += 1) {\n unsigned ipin = 0;\n bool connected_flag = false;\n for (ipin = 0 ; ipin < ip->pin_count(); ipin += 1)\n if (connected(ip->pin(ipin), jp->pin(jpin))) {\n connected_flag = true;\n break;\n }\n\n if (!connected_flag) {\n fully_connected = false;\n break;\n }\n }\n\n if (fully_connected) {\n delete jp;\n } else {\n jdx += 1;\n }\n }\n }\n econtinue = true;\n } else {\n \/* Postpone examining events in an automatic scope until the\n third (optional) pass. This will mean similar events are\n biased towards being stored in static scopes. *\/\n if (ev->scope()->is_auto()) {\n if (iteration == 1) {\n econtinue = true;\n return;\n }\n } else {\n if (iteration == 2) {\n return;\n }\n }\n\n \/* Try to find all the events that are similar to me, and\n replace their references with references to me. *\/\n list<NetEvent*> match;\n ev->find_similar_event(match);\n for (list<NetEvent*>::iterator idx = match.begin()\n ; idx != match.end() ; ++ idx ) {\n\n NetEvent*tmp = *idx;\n assert(tmp != ev);\n\t\t tmp ->replace_event(ev);\n }\n }\n}\n\nstatic bool floating_net_tested(NetNet*sig)\n{\n static set<NetNet*> tested_set;\n\n pair< set<NetNet*>::iterator, bool > cur = tested_set.insert(sig);\n return !cur.second;\n}\n\nstatic void check_is_floating(NetNet*sig)\n{\n if (sig->type() == NetNet::SUPPLY0) return;\n if (sig->type() == NetNet::SUPPLY1) return;\n if (sig->type() == NetNet::TRI0) return;\n if (sig->type() == NetNet::TRI1) return;\n if (sig->type() == NetNet::IMPLICIT_REG) return;\n if (sig->type() == NetNet::REG) return ;\n\n if (sig->peek_lref() > 0) return;\n\n for (unsigned idx = 0 ; idx < sig->pin_count() ; idx += 1) {\n\t if (sig->pin(idx).get_dir() == Link::OUTPUT)\n\t\t continue;\n\n\t if (sig->pin(idx).nexus()->drivers_present())\n\t\t continue;\n\n\t if (sig->port_type() == PortType::NOT_A_PORT && sig->pin_count()==1) {\n\t\t cerr << sig->get_fileline() << \": warning: \"\n\t\t << \"Signal \" << scope_path(sig->scope())\n\t\t << \".\" << sig->name()\n\t\t << \" has no drivers.\" << endl;\n\t } else if (sig->port_type()==PortType::NOT_A_PORT) {\n\t\t cerr << sig->get_fileline() << \": warning: \"\n\t\t << \"Signal \" << scope_path(sig->scope())\n\t\t << \".\" << sig->name()\n\t\t << \"[\" << idx << \"]\"\n\t\t << \" has no drivers.\" << endl;\n\t } else {\n\t\t cerr << sig->get_fileline() << \": warning: \"\n\t\t << \"Port \" << sig->name()\n\t\t << \" of \" << scope_path(sig->scope())\n\t\t << \" has no drivers.\" << endl;\n\t }\n }\n\n}\n\nvoid nodangle_f::signal(Design*, NetNet*sig)\n{\n if (scomplete) return;\n\n if (warn_floating_nets && !floating_net_tested(sig)) {\n\t check_is_floating(sig);\n }\n\n\t\/* Cannot delete signals referenced in an expression\n\t or an l-value. *\/\n if (sig->get_refs() > 0)\n\t return;\n\n\t\/* Cannot delete the ports of tasks, functions or modules. There\n\t are too many places where they are referenced. *\/\n if ((sig->port_type() != NetNet::NOT_A_PORT) &&\n\t ((sig->scope()->type() == NetScope::TASK) ||\n\t (sig->scope()->type() == NetScope::FUNC) ||\n\t (sig->scope()->type() == NetScope::MODULE)))\n\t return;\n\n\t\/* Can't delete ports of cells. *\/\n if ((sig->port_type() != NetNet::NOT_A_PORT)\n\t && (sig->scope()->attribute(perm_string::literal(\"ivl_synthesis_cell\")) != verinum()))\n\t return;\n\n\t\/* Don't delete signals that are marked with the\n\t ivl_do_not_elide property. *\/\n if (!sig->local_flag()\n\t && (sig->attribute(perm_string::literal(\"ivl_do_not_elide\")) != verinum()))\n\t return;\n\n\t\/* Check to see if the signal is completely unconnected. If\n\t all the bits are unlinked, then delete it. *\/\n if (! sig->is_linked()) {\n\t delete sig;\n\t stotal += 1;\n\t return;\n }\n\n\t\/* The remaining things can only be done to synthesized\n\t signals, not ones that appear in the original Verilog. *\/\n if (! sig->local_flag())\n\t return;\n\n\t\/* Check to see if there is some significant signal connected\n\t to every pin of this signal. *\/\n unsigned significant_flags = 0;\n for (unsigned idx = 0 ; idx < sig->pin_count() ; idx += 1) {\n\t Nexus*nex = sig->pin(idx).nexus();\n\n\t for (Link*cur = nex->first_nlink()\n\t\t ; cur ; cur = cur->next_nlink()) {\n\n\t\t if (cur == &sig->pin(idx))\n\t\t\tcontinue;\n\n\t\t NetNet*cursig = dynamic_cast<NetNet*>(cur->get_obj());\n\t\t if (cursig == 0)\n\t\t\tcontinue;\n\n\t\t if (cursig->local_flag())\n\t\t\tcontinue;\n\n\t\t significant_flags += 1;\n\t\t break;\n\t }\n\n\t if (significant_flags <= idx)\n\t\t break;\n }\n\n\t\/* If every pin is connected to another significant signal,\n\t then I can delete this one. *\/\n if (significant_flags == sig->pin_count()) {\n\t delete sig;\n\t stotal += 1;\n }\n}\n\nvoid nodangle(Design*des)\n{\n nodangle_f fun;\n fun.iteration = 0;\n fun.stotal = 0;\n fun.etotal = 0;\n fun.scomplete = false;\n fun.ecomplete = false;\n do {\n\t if (verbose_flag) {\n\t\t cout << \" ... scan for dangling signal and event nodes. \"\n\t\t << \"(scomplete=\" << (fun.scomplete? \"T\" : \"F\")\n\t\t << \", ecomplete=\" << (fun.ecomplete? \"T\" : \"F\")\n\t\t << \")\" << endl << flush;\n\t }\n\n fun.scontinue = false;\n fun.econtinue = false;\n\t des->functor(&fun);\n\t fun.iteration += 1;\n fun.scomplete = !fun.scontinue;\n fun.ecomplete = !fun.econtinue;\n\n\t if (verbose_flag) {\n\t\t cout << \" ... \" << fun.iteration << \" iterations\"\n\t\t << \" deleted \" << fun.stotal << \" dangling signals\"\n\t\t << \" and \" << fun.etotal << \" events.\" << endl << flush;\n\t }\n\n } while (fun.scontinue || fun.econtinue);\n\n if (verbose_flag) {\n\t cout << \" ... done\" << endl << flush;\n }\n}\n<commit_msg>Don't warning about floating local\/internal symbols.<commit_after>\/*\n * Copyright (c) 1999-2010 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n# include \"config.h\"\n\n\/*\n * This functor scans the design looking for dangling objects and\n * excess local signals. These deletions are not necessarily required\n * for proper functioning of anything, but they can clean up the\n * appearance of design files that are generated.\n *\/\n# include \"functor.h\"\n# include \"netlist.h\"\n# include \"compiler.h\"\n\nclass nodangle_f : public functor_t {\n public:\n void event(Design*des, NetEvent*ev);\n void signal(Design*des, NetNet*sig);\n\n unsigned iteration;\n unsigned stotal, etotal;\n bool scontinue, econtinue;\n bool scomplete, ecomplete;\n};\n\nvoid nodangle_f::event(Design*, NetEvent*ev)\n{\n if (ecomplete) return;\n\n\t\/* If there are no references to this event, then go right\n\t ahead and delete it. There is no use looking further at\n\t it. *\/\n if ((ev->nwait() + ev->ntrig() + ev->nexpr()) == 0) {\n\t delete ev;\n\t etotal += 1;\n\t return;\n }\n\n if (iteration == 0) {\n \/* Try to remove duplicate probes from the event. This\n is done as a separate initial pass to ensure similar\n events are detected as soon as possible in subsequent\n iterations. *\/\n for (unsigned idx = 0 ; idx < ev->nprobe() ; idx += 1) {\n unsigned jdx = idx + 1;\n while (jdx < ev->nprobe()) {\n NetEvProbe*ip = ev->probe(idx);\n NetEvProbe*jp = ev->probe(jdx);\n\n if (ip->edge() != jp->edge()) {\n jdx += 1;\n continue;\n }\n\n bool fully_connected = true;\n for (unsigned jpin = 0; jpin < jp->pin_count(); jpin += 1) {\n unsigned ipin = 0;\n bool connected_flag = false;\n for (ipin = 0 ; ipin < ip->pin_count(); ipin += 1)\n if (connected(ip->pin(ipin), jp->pin(jpin))) {\n connected_flag = true;\n break;\n }\n\n if (!connected_flag) {\n fully_connected = false;\n break;\n }\n }\n\n if (fully_connected) {\n delete jp;\n } else {\n jdx += 1;\n }\n }\n }\n econtinue = true;\n } else {\n \/* Postpone examining events in an automatic scope until the\n third (optional) pass. This will mean similar events are\n biased towards being stored in static scopes. *\/\n if (ev->scope()->is_auto()) {\n if (iteration == 1) {\n econtinue = true;\n return;\n }\n } else {\n if (iteration == 2) {\n return;\n }\n }\n\n \/* Try to find all the events that are similar to me, and\n replace their references with references to me. *\/\n list<NetEvent*> match;\n ev->find_similar_event(match);\n for (list<NetEvent*>::iterator idx = match.begin()\n ; idx != match.end() ; ++ idx ) {\n\n NetEvent*tmp = *idx;\n assert(tmp != ev);\n\t\t tmp ->replace_event(ev);\n }\n }\n}\n\nstatic bool floating_net_tested(NetNet*sig)\n{\n static set<NetNet*> tested_set;\n\n pair< set<NetNet*>::iterator, bool > cur = tested_set.insert(sig);\n return !cur.second;\n}\n\nstatic void check_is_floating(NetNet*sig)\n{\n\t\/\/ Some signal types are implicitly driven if nothing else.\n if (sig->type() == NetNet::SUPPLY0) return;\n if (sig->type() == NetNet::SUPPLY1) return;\n if (sig->type() == NetNet::TRI0) return;\n if (sig->type() == NetNet::TRI1) return;\n if (sig->type() == NetNet::IMPLICIT_REG) return;\n if (sig->type() == NetNet::REG) return ;\n\n\t\/\/ Asignments drive a signal.\n if (sig->peek_lref() > 0) return;\n\n for (unsigned idx = 0 ; idx < sig->pin_count() ; idx += 1) {\n\t if (sig->pin(idx).get_dir() == Link::OUTPUT)\n\t\t continue;\n\n\t if (sig->pin(idx).nexus()->drivers_present())\n\t\t continue;\n\n\t if (sig->port_type() == PortType::NOT_A_PORT && sig->pin_count()==1) {\n\t\t cerr << sig->get_fileline() << \": warning: \"\n\t\t << \"Signal \" << scope_path(sig->scope())\n\t\t << \".\" << sig->name()\n\t\t << \" has no drivers.\" << endl;\n\t } else if (sig->port_type()==PortType::NOT_A_PORT) {\n\t\t cerr << sig->get_fileline() << \": warning: \"\n\t\t << \"Signal \" << scope_path(sig->scope())\n\t\t << \".\" << sig->name()\n\t\t << \"[\" << idx << \"]\"\n\t\t << \" has no drivers.\" << endl;\n\t } else {\n\t\t cerr << sig->get_fileline() << \": warning: \"\n\t\t << \"Port \" << sig->name()\n\t\t << \" of \" << scope_path(sig->scope())\n\t\t << \" has no drivers.\" << endl;\n\t }\n }\n\n}\n\nvoid nodangle_f::signal(Design*, NetNet*sig)\n{\n if (scomplete) return;\n\n if (warn_floating_nets && !sig->local_flag() && !floating_net_tested(sig)) {\n\t check_is_floating(sig);\n }\n\n\t\/* Cannot delete signals referenced in an expression\n\t or an l-value. *\/\n if (sig->get_refs() > 0)\n\t return;\n\n\t\/* Cannot delete the ports of tasks, functions or modules. There\n\t are too many places where they are referenced. *\/\n if ((sig->port_type() != NetNet::NOT_A_PORT) &&\n\t ((sig->scope()->type() == NetScope::TASK) ||\n\t (sig->scope()->type() == NetScope::FUNC) ||\n\t (sig->scope()->type() == NetScope::MODULE)))\n\t return;\n\n\t\/* Can't delete ports of cells. *\/\n if ((sig->port_type() != NetNet::NOT_A_PORT)\n\t && (sig->scope()->attribute(perm_string::literal(\"ivl_synthesis_cell\")) != verinum()))\n\t return;\n\n\t\/* Don't delete signals that are marked with the\n\t ivl_do_not_elide property. *\/\n if (!sig->local_flag()\n\t && (sig->attribute(perm_string::literal(\"ivl_do_not_elide\")) != verinum()))\n\t return;\n\n\t\/* Check to see if the signal is completely unconnected. If\n\t all the bits are unlinked, then delete it. *\/\n if (! sig->is_linked()) {\n\t delete sig;\n\t stotal += 1;\n\t return;\n }\n\n\t\/* The remaining things can only be done to synthesized\n\t signals, not ones that appear in the original Verilog. *\/\n if (! sig->local_flag())\n\t return;\n\n\t\/* Check to see if there is some significant signal connected\n\t to every pin of this signal. *\/\n unsigned significant_flags = 0;\n for (unsigned idx = 0 ; idx < sig->pin_count() ; idx += 1) {\n\t Nexus*nex = sig->pin(idx).nexus();\n\n\t for (Link*cur = nex->first_nlink()\n\t\t ; cur ; cur = cur->next_nlink()) {\n\n\t\t if (cur == &sig->pin(idx))\n\t\t\tcontinue;\n\n\t\t NetNet*cursig = dynamic_cast<NetNet*>(cur->get_obj());\n\t\t if (cursig == 0)\n\t\t\tcontinue;\n\n\t\t if (cursig->local_flag())\n\t\t\tcontinue;\n\n\t\t significant_flags += 1;\n\t\t break;\n\t }\n\n\t if (significant_flags <= idx)\n\t\t break;\n }\n\n\t\/* If every pin is connected to another significant signal,\n\t then I can delete this one. *\/\n if (significant_flags == sig->pin_count()) {\n\t delete sig;\n\t stotal += 1;\n }\n}\n\nvoid nodangle(Design*des)\n{\n nodangle_f fun;\n fun.iteration = 0;\n fun.stotal = 0;\n fun.etotal = 0;\n fun.scomplete = false;\n fun.ecomplete = false;\n do {\n\t if (verbose_flag) {\n\t\t cout << \" ... scan for dangling signal and event nodes. \"\n\t\t << \"(scomplete=\" << (fun.scomplete? \"T\" : \"F\")\n\t\t << \", ecomplete=\" << (fun.ecomplete? \"T\" : \"F\")\n\t\t << \")\" << endl << flush;\n\t }\n\n fun.scontinue = false;\n fun.econtinue = false;\n\t des->functor(&fun);\n\t fun.iteration += 1;\n fun.scomplete = !fun.scontinue;\n fun.ecomplete = !fun.econtinue;\n\n\t if (verbose_flag) {\n\t\t cout << \" ... \" << fun.iteration << \" iterations\"\n\t\t << \" deleted \" << fun.stotal << \" dangling signals\"\n\t\t << \" and \" << fun.etotal << \" events.\" << endl << flush;\n\t }\n\n } while (fun.scontinue || fun.econtinue);\n\n if (verbose_flag) {\n\t cout << \" ... done\" << endl << flush;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <thread>\n#include <vector>\n#include <atomic>\n\n#include \"spdlog\/spdlog.h\"\n\n#include <iostream>\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n\n int thread_count = 10;\n if(argc > 1)\n thread_count = atoi(argv[1]);\n\n int howmany = 1000000;\n\n namespace spd = spdlog;\n \/\/\/Create a file rotating logger with 5mb size max and 3 rotated files\n auto logger = spd::rotating_logger_mt(\"file_logger\", \"logs\/spd-sample\", 10 *1024 * 1024 , 5);\n\n logger->set_pattern(\"[%Y-%b-%d %T.%e]: %v\");\n\n std::atomic<int > msg_counter {0};\n vector<thread> threads;\n\n for (int t = 0; t < thread_count; ++t)\n {\n threads.push_back(std::thread([&]()\n {\n while (true)\n {\n int counter = ++msg_counter;\n if (counter > howmany) break;\n logger->info() << \"spdlog message #\" << counter << \": This is some text for your pleasure\";\n }\n }));\n }\n\n\n for(auto &t:threads)\n {\n t.join();\n };\n\n\n\n return 0;\n}\n<commit_msg>small fix in comment<commit_after>#include <thread>\n#include <vector>\n#include <atomic>\n\n#include \"spdlog\/spdlog.h\"\n\n#include <iostream>\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n\n int thread_count = 10;\n if(argc > 1)\n thread_count = atoi(argv[1]);\n\n int howmany = 1000000;\n\n namespace spd = spdlog;\n \/\/\/Create a file rotating logger with 5mb size max and 5 rotated files\n auto logger = spd::rotating_logger_mt(\"file_logger\", \"logs\/spd-sample\", 10 *1024 * 1024 , 5);\n\n logger->set_pattern(\"[%Y-%b-%d %T.%e]: %v\");\n\n std::atomic<int > msg_counter {0};\n vector<thread> threads;\n\n for (int t = 0; t < thread_count; ++t)\n {\n threads.push_back(std::thread([&]()\n {\n while (true)\n {\n int counter = ++msg_counter;\n if (counter > howmany) break;\n logger->info() << \"spdlog message #\" << counter << \": This is some text for your pleasure\";\n }\n }));\n }\n\n\n for(auto &t:threads)\n {\n t.join();\n };\n\n\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"blendMap.h\"\n#include \"HeightMap.h\"\n#include \"PivotPoint.h\"\n#include \"utility.h\"\n\nBlendMap::BlendMap()\n{\n\tm_texBlendMap = NULL;\n\tm_srvBlendMap = NULL;\n}\nBlendMap::~BlendMap()\n{\n\tSAFE_RELEASE(m_texBlendMap);\n\tSAFE_RELEASE(m_srvBlendMap);\n}\n\nvoid BlendMap::update(ID3D11DeviceContext* p_devcon,\n\t\t\t\t\t PivotPoint* p_pivot,\n\t\t\t\t\t HeightMap* p_heightMap,\n\t\t\t\t\t ManagementMenu::ToolPropertyIds toolProperty)\n{\n\tint col\t\t = p_heightMap->getCol(p_pivot->getPosition().x);\n\tint row\t\t = p_heightMap->getRow(p_pivot->getPosition().z);\n\tfloat radius = p_pivot->getSize();\n\tfloat speed = p_pivot->getSpeed();\n\n\tfor( int x=col-radius; x<col+radius; x++ )\n\t{\n\t\tfor( int z=row-radius; z<row+radius; z++ ) \n\t\t{\t\n\t\t\t\n\t\t\tif(insideCircle(radius, x, z, col, row))\n\t\t\t{\n\t\t\t\tint index = z*m_width + x;\n\t\t\t\tif(index >= 0 && index < m_numTexels)\n\t\t\t\t{\n\t\t\t\t\tif(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_0)\n\t\t\t\t\t\tmodifyRed(speed, index);\n\t\t\t\t\telse if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_1)\n\t\t\t\t\t\tmodifyGreen(speed, index);\n\t\t\t\t\telse if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_2)\n\t\t\t\t\t\tmodifyBlue(speed, index);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tupdateTexture(p_devcon);\n}\n\nvoid BlendMap::setTexel(ID3D11DeviceContext* p_devcon, Texel p_texel, int p_x, int p_y)\n{\n\tm_texels[p_x * m_width + p_y] = p_texel;\n\tupdateTexture(p_devcon);\n}\nvoid BlendMap::setAllTexels(ID3D11DeviceContext* p_devcon, Texel p_texel)\n{\n\tfor(unsigned int i=0; i<m_texels.size(); i++)\n\t\tm_texels[i] = p_texel;\n\n\tupdateTexture(p_devcon);\n}\n\nvoid BlendMap::psSetBlendMap(ID3D11DeviceContext* p_devcon, unsigned int startSlott)\n{\n\tp_devcon->PSSetShaderResources(startSlott, 1, &m_srvBlendMap);\n}\n\nID3D11Texture2D* BlendMap::getTexBlendMap() const\n{\n\treturn m_texBlendMap;\n}\nID3D11ShaderResourceView* BlendMap::getSrvBlendMap() const\n{\n\treturn m_srvBlendMap;\n}\n\nHRESULT BlendMap::init(ID3D11Device* p_device, int p_width, int p_height)\n{\n\tm_width\t\t= p_width;\n\tm_height\t= p_height;\n\tm_numTexels = m_width * m_height;\n\tm_texels.resize(p_width*p_height, Texel(0, 0, 0, 0));\n\n\tHRESULT hr = S_OK;\n\thr = initTexBlendMap(p_device, p_width, p_height);\n\tif(SUCCEEDED(hr))\n\t\thr = initSrvBlendMap(p_device);\n\n\treturn hr;\n}\nHRESULT BlendMap::initTexBlendMap(ID3D11Device* p_device, int p_width, int p_height)\n{\n\tHRESULT hr = S_OK;\n\n\tD3D11_TEXTURE2D_DESC texDesc;\n\tZeroMemory(&texDesc, sizeof(texDesc));\n\n\ttexDesc.Width\t\t\t\t= p_width;\n\ttexDesc.Height\t\t\t\t= p_height;\n\ttexDesc.MipLevels\t\t\t= 1;\n\ttexDesc.ArraySize\t\t\t= 1;\n\ttexDesc.Format\t\t\t\t= DXGI_FORMAT_R8G8B8A8_UNORM;\n\ttexDesc.SampleDesc.Count\t= 1;\n\ttexDesc.SampleDesc.Quality\t= 0;\n\ttexDesc.Usage\t\t\t\t= D3D11_USAGE_DYNAMIC;\n\ttexDesc.BindFlags\t\t\t= D3D11_BIND_SHADER_RESOURCE;\n\ttexDesc.CPUAccessFlags\t\t= D3D11_CPU_ACCESS_WRITE;\n\ttexDesc.MiscFlags\t\t\t= 0;\n\n\thr = p_device->CreateTexture2D(&texDesc, NULL, &m_texBlendMap);\n\tif(FAILED(hr))\n\t\tMessageBox(NULL, L\"BlendMap::initTexBlendMap() | device->CreateTexture2D() | Failed\", L\"BlendMap\", MB_OK | MB_ICONEXCLAMATION);\n\n\treturn hr;\n}\nHRESULT BlendMap::initSrvBlendMap(ID3D11Device* p_device)\n{\n\tHRESULT hr = S_OK;\n\n\tD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;\n\tZeroMemory(&srvDesc, sizeof(srvDesc));\n\n\tsrvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n\tsrvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;\n\tsrvDesc.Texture2D.MostDetailedMip = 0;\n\tsrvDesc.Texture2D.MipLevels = 1;\n\n\thr = p_device->CreateShaderResourceView(m_texBlendMap, &srvDesc, &m_srvBlendMap);\n\tif(FAILED(hr))\n\t\tMessageBox(NULL, L\"BlendMap::initSrvBlendMap() | device->CreateShaderResourceView() | Failed\", L\"BlendMap\", MB_OK | MB_ICONEXCLAMATION);\n\n\treturn hr;\n}\n\nHRESULT BlendMap::updateTexture(ID3D11DeviceContext* p_devcon)\n{\n\tD3D11_MAPPED_SUBRESOURCE resource;\n\tZeroMemory(&resource, sizeof(resource));\n\n\tHRESULT hr = S_OK;\n\thr = p_devcon->Map(m_texBlendMap, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource);\n\tif(FAILED(hr))\n\t\tMessageBox(NULL, L\"BlendMap::setPixel() | devcon->Map() | Failed\", L\"BlendMap\", MB_OK | MB_ICONEXCLAMATION);\n\n\tmemcpy( resource.pData,& m_texels[0], sizeof(m_texels[0])*m_texels.size() );\n\n\tp_devcon->Unmap(m_texBlendMap, 0);\n\n\treturn hr;\n}\n\nvoid BlendMap::modifyRed(float p_value, int p_index)\n{\n\tint newValue = m_texels[p_index].m_red;\n\tnewValue += p_value;\n\tif(newValue > 254)\n\t\tnewValue = 254;\n\telse if(newValue < 0)\n\t\tnewValue = 0;\n\t\n\tm_texels[p_index].m_red = newValue;\n}\nvoid BlendMap::modifyGreen(float p_value, int p_index)\n{\n\tint newValue = m_texels[p_index].m_green;\n\tnewValue += p_value;\n\tif(newValue > 254)\n\t\tnewValue = 254;\n\telse if(newValue < 0)\n\t\tnewValue = 0;\n\t\n\tm_texels[p_index].m_green = newValue;\n}\nvoid BlendMap::modifyBlue(float p_value, int p_index)\n{\n\tint newValue = m_texels[p_index].m_blue;\n\tnewValue += p_value;\n\tif(newValue > 254)\n\t\tnewValue = 254;\n\telse if(newValue < 0)\n\t\tnewValue = 0;\n\t\n\tm_texels[p_index].m_blue = newValue;\n}\n\nbool BlendMap::insideCircle(float p_radius, int p_x, int p_z, int p_col, int p_row)\n{\n\tfloat hyp = sqrt((p_col-p_x)*(p_col-p_x)+(p_row-p_z)*(p_row-p_z));\n\n\treturn hyp < p_radius;\n}<commit_msg>Removed a coule of warnings.<commit_after>#include \"blendMap.h\"\n#include \"HeightMap.h\"\n#include \"PivotPoint.h\"\n#include \"utility.h\"\n\nBlendMap::BlendMap()\n{\n\tm_texBlendMap = NULL;\n\tm_srvBlendMap = NULL;\n}\nBlendMap::~BlendMap()\n{\n\tSAFE_RELEASE(m_texBlendMap);\n\tSAFE_RELEASE(m_srvBlendMap);\n}\n\nvoid BlendMap::update(ID3D11DeviceContext* p_devcon,\n\t\t\t\t\t PivotPoint* p_pivot,\n\t\t\t\t\t HeightMap* p_heightMap,\n\t\t\t\t\t ManagementMenu::ToolPropertyIds toolProperty)\n{\n\tint col\t\t = p_heightMap->getCol(p_pivot->getPosition().x);\n\tint row\t\t = p_heightMap->getRow(p_pivot->getPosition().z);\n\tfloat radius = p_pivot->getSize();\n\tfloat speed = p_pivot->getSpeed();\n\n\tint lowX = col - static_cast<int>(radius);\n\tint highX = col + static_cast<int>(radius);\n\tint lowZ = row - static_cast<int>(radius);\n\tint highZ = row + static_cast<int>(radius);\n\n\tfor( int x=lowX; x<highX; x++ )\n\t{\n\t\tfor( int z=lowZ; z<highZ; z++ ) \n\t\t{\t\n\t\t\t\n\t\t\tif(insideCircle(radius, x, z, col, row))\n\t\t\t{\n\t\t\t\tint index = z*m_width + x;\n\t\t\t\tif(index >= 0 && index < m_numTexels)\n\t\t\t\t{\n\t\t\t\t\tif(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_0)\n\t\t\t\t\t\tmodifyRed(speed, index);\n\t\t\t\t\telse if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_1)\n\t\t\t\t\t\tmodifyGreen(speed, index);\n\t\t\t\t\telse if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_2)\n\t\t\t\t\t\tmodifyBlue(speed, index);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tupdateTexture(p_devcon);\n}\n\nvoid BlendMap::setTexel(ID3D11DeviceContext* p_devcon, Texel p_texel, int p_x, int p_y)\n{\n\tm_texels[p_x * m_width + p_y] = p_texel;\n\tupdateTexture(p_devcon);\n}\nvoid BlendMap::setAllTexels(ID3D11DeviceContext* p_devcon, Texel p_texel)\n{\n\tfor(unsigned int i=0; i<m_texels.size(); i++)\n\t\tm_texels[i] = p_texel;\n\n\tupdateTexture(p_devcon);\n}\n\nvoid BlendMap::psSetBlendMap(ID3D11DeviceContext* p_devcon, unsigned int startSlott)\n{\n\tp_devcon->PSSetShaderResources(startSlott, 1, &m_srvBlendMap);\n}\n\nID3D11Texture2D* BlendMap::getTexBlendMap() const\n{\n\treturn m_texBlendMap;\n}\nID3D11ShaderResourceView* BlendMap::getSrvBlendMap() const\n{\n\treturn m_srvBlendMap;\n}\n\nHRESULT BlendMap::init(ID3D11Device* p_device, int p_width, int p_height)\n{\n\tm_width\t\t= p_width;\n\tm_height\t= p_height;\n\tm_numTexels = m_width * m_height;\n\tm_texels.resize(p_width*p_height, Texel(0, 0, 0, 0));\n\n\tHRESULT hr = S_OK;\n\thr = initTexBlendMap(p_device, p_width, p_height);\n\tif(SUCCEEDED(hr))\n\t\thr = initSrvBlendMap(p_device);\n\n\treturn hr;\n}\nHRESULT BlendMap::initTexBlendMap(ID3D11Device* p_device, int p_width, int p_height)\n{\n\tHRESULT hr = S_OK;\n\n\tD3D11_TEXTURE2D_DESC texDesc;\n\tZeroMemory(&texDesc, sizeof(texDesc));\n\n\ttexDesc.Width\t\t\t\t= p_width;\n\ttexDesc.Height\t\t\t\t= p_height;\n\ttexDesc.MipLevels\t\t\t= 1;\n\ttexDesc.ArraySize\t\t\t= 1;\n\ttexDesc.Format\t\t\t\t= DXGI_FORMAT_R8G8B8A8_UNORM;\n\ttexDesc.SampleDesc.Count\t= 1;\n\ttexDesc.SampleDesc.Quality\t= 0;\n\ttexDesc.Usage\t\t\t\t= D3D11_USAGE_DYNAMIC;\n\ttexDesc.BindFlags\t\t\t= D3D11_BIND_SHADER_RESOURCE;\n\ttexDesc.CPUAccessFlags\t\t= D3D11_CPU_ACCESS_WRITE;\n\ttexDesc.MiscFlags\t\t\t= 0;\n\n\thr = p_device->CreateTexture2D(&texDesc, NULL, &m_texBlendMap);\n\tif(FAILED(hr))\n\t\tMessageBox(NULL, L\"BlendMap::initTexBlendMap() | device->CreateTexture2D() | Failed\", L\"BlendMap\", MB_OK | MB_ICONEXCLAMATION);\n\n\treturn hr;\n}\nHRESULT BlendMap::initSrvBlendMap(ID3D11Device* p_device)\n{\n\tHRESULT hr = S_OK;\n\n\tD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;\n\tZeroMemory(&srvDesc, sizeof(srvDesc));\n\n\tsrvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n\tsrvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;\n\tsrvDesc.Texture2D.MostDetailedMip = 0;\n\tsrvDesc.Texture2D.MipLevels = 1;\n\n\thr = p_device->CreateShaderResourceView(m_texBlendMap, &srvDesc, &m_srvBlendMap);\n\tif(FAILED(hr))\n\t\tMessageBox(NULL, L\"BlendMap::initSrvBlendMap() | device->CreateShaderResourceView() | Failed\", L\"BlendMap\", MB_OK | MB_ICONEXCLAMATION);\n\n\treturn hr;\n}\n\nHRESULT BlendMap::updateTexture(ID3D11DeviceContext* p_devcon)\n{\n\tD3D11_MAPPED_SUBRESOURCE resource;\n\tZeroMemory(&resource, sizeof(resource));\n\n\tHRESULT hr = S_OK;\n\thr = p_devcon->Map(m_texBlendMap, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource);\n\tif(FAILED(hr))\n\t\tMessageBox(NULL, L\"BlendMap::setPixel() | devcon->Map() | Failed\", L\"BlendMap\", MB_OK | MB_ICONEXCLAMATION);\n\n\tmemcpy( resource.pData,& m_texels[0], sizeof(m_texels[0])*m_texels.size() );\n\n\tp_devcon->Unmap(m_texBlendMap, 0);\n\n\treturn hr;\n}\n\nvoid BlendMap::modifyRed(float p_value, int p_index)\n{\n\tint newValue = m_texels[p_index].m_red;\n\tnewValue += static_cast<int>(p_value);\n\tif(newValue > 254)\n\t\tnewValue = 254;\n\telse if(newValue < 0)\n\t\tnewValue = 0;\n\t\n\tm_texels[p_index].m_red = newValue;\n}\nvoid BlendMap::modifyGreen(float p_value, int p_index)\n{\n\tint newValue = m_texels[p_index].m_green;\n\tnewValue += static_cast<int>(p_value);\n\tif(newValue > 254)\n\t\tnewValue = 254;\n\telse if(newValue < 0)\n\t\tnewValue = 0;\n\t\n\tm_texels[p_index].m_green = newValue;\n}\nvoid BlendMap::modifyBlue(float p_value, int p_index)\n{\n\tint newValue = m_texels[p_index].m_blue;\n\tnewValue += static_cast<int>(p_value);\n\tif(newValue > 254)\n\t\tnewValue = 254;\n\telse if(newValue < 0)\n\t\tnewValue = 0;\n\t\n\tm_texels[p_index].m_blue = newValue;\n}\n\nbool BlendMap::insideCircle(float p_radius, int p_x, int p_z, int p_col, int p_row)\n{\n\tint temp = (p_col-p_x)*(p_col-p_x)+(p_row-p_z)*(p_row-p_z);\n\tfloat hyp = sqrtf(static_cast<float>(temp));\n\n\treturn hyp < p_radius;\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: The OpenIGTLink Library\n Language: C++\n Web page: http:\/\/openigtlink.org\/\n\n Copyright (c) Insight Software Consortium. All rights reserved.\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 \"igtlUnit.h\"\n#include \"igtl_unit.h\"\n\n\/\/ Disable warning C4996 (strncpy() may be unsafe) in Windows. \n#define _CRT_SECURE_NO_WARNINGS\n\nnamespace igtl {\n\nUnit::Unit():\n Object()\n{\n Init();\n}\n\n\nUnit::~Unit()\n{\n}\n\n\nvoid Unit::Init()\n{\n this->m_Prefix = SI_PREFIX_NONE;\n this->m_NUnits = 0;\n\n for (int i = 0; i < 6; i ++)\n {\n this->m_Unit[i] = SI_BASE_NONE;\n this->m_Exp[i] = 0;\n }\n}\n\n\nint Unit::SetPrefix(int prefix)\n{\n if (prefix >= SI_PREFIX_NONE && prefix <= SI_PREFIX_FEMTO)\n {\n this->m_Prefix = prefix;\n return 1;\n }\n else\n {\n return 0;\n }\n}\n\n\nint Unit::Append(int unit, int exp)\n{\n \/\/ Check number of units already appended\n if (this->m_NUnits >= 6)\n {\n return 0;\n }\n\n \/\/ Check range\n if (unit < SI_BASE_NONE || unit >= SI_NUM_UNIT_TYPES)\n {\n return 0;\n }\n if (exp < -7 || exp > 7)\n {\n return 0;\n }\n \n \/\/ Append\n this->m_Unit[this->m_NUnits] = (igtlUint8)unit;\n this->m_Exp[this->m_NUnits] = (igtlInt8)exp;\n\n return 1;\n}\n\n\nigtlUnit Unit::Pack()\n{\n igtl_unit_data data;\n\n igtl_unit_init(&data);\n\n data.prefix = this->m_Prefix;\n for (int i = 0; i < 6; i ++)\n {\n data.unit[i] = this->m_Unit[i];\n data.exp[i] = this->m_Exp[i];\n }\n \n return (igtlUnit) igtl_unit_pack(&data);\n}\n\n\nint Unit::Unpack(igtlUnit unit)\n{\n igtl_unit_data data;\n\n if (igtl_unit_unpack((igtl_unit)unit, &data) == 0)\n {\n return 0;\n }\n\n Init();\n \n this->m_Prefix = data.prefix;\n for (int i = 0; i < 6; i ++)\n {\n this->m_Unit[i] = data.unit[i];\n this->m_Exp[i] = data.exp[i];\n }\n\n return 1;\n \n}\n\n\n} \/\/ namespace igtl\n\n\n\n\n\n<commit_msg>igtlUnit index incremented after one assignment<commit_after>\/*=========================================================================\n\n Program: The OpenIGTLink Library\n Language: C++\n Web page: http:\/\/openigtlink.org\/\n\n Copyright (c) Insight Software Consortium. All rights reserved.\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 \"igtlUnit.h\"\n#include \"igtl_unit.h\"\n\n\/\/ Disable warning C4996 (strncpy() may be unsafe) in Windows. \n#define _CRT_SECURE_NO_WARNINGS\n\nnamespace igtl {\n\nUnit::Unit():\n Object()\n{\n Init();\n}\n\n\nUnit::~Unit()\n{\n}\n\n\nvoid Unit::Init()\n{\n this->m_Prefix = SI_PREFIX_NONE;\n this->m_NUnits = 0;\n\n for (int i = 0; i < 6; i ++)\n {\n this->m_Unit[i] = SI_BASE_NONE;\n this->m_Exp[i] = 0;\n }\n}\n\n\nint Unit::SetPrefix(int prefix)\n{\n if (prefix >= SI_PREFIX_NONE && prefix <= SI_PREFIX_FEMTO)\n {\n this->m_Prefix = prefix;\n return 1;\n }\n else\n {\n return 0;\n }\n}\n\n\nint Unit::Append(int unit, int exp)\n{\n \/\/ Check number of units already appended\n if (this->m_NUnits >= 6)\n {\n return 0;\n }\n\n \/\/ Check range\n if (unit < SI_BASE_NONE || unit >= SI_NUM_UNIT_TYPES)\n {\n return 0;\n }\n if (exp < -7 || exp > 7)\n {\n return 0;\n }\n \n \/\/ Append\n this->m_Unit[this->m_NUnits] = (igtlUint8)unit;\n this->m_Exp[this->m_NUnits] = (igtlInt8)exp;\n this->m_NUnits++;\n return 1;\n}\n\n\nigtlUnit Unit::Pack()\n{\n igtl_unit_data data;\n\n igtl_unit_init(&data);\n\n data.prefix = this->m_Prefix;\n for (int i = 0; i < 6; i ++)\n {\n data.unit[i] = this->m_Unit[i];\n data.exp[i] = this->m_Exp[i];\n }\n \n return (igtlUnit) igtl_unit_pack(&data);\n}\n\n\nint Unit::Unpack(igtlUnit unit)\n{\n igtl_unit_data data;\n\n if (igtl_unit_unpack((igtl_unit)unit, &data) == 0)\n {\n return 0;\n }\n\n Init();\n \n this->m_Prefix = data.prefix;\n for (int i = 0; i < 6; i ++)\n {\n this->m_Unit[i] = data.unit[i];\n this->m_Exp[i] = data.exp[i];\n }\n\n return 1;\n \n}\n\n\n} \/\/ namespace igtl\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <Toolbox\/catch.hpp>\n\n#include \"TestSink.h\"\n#include <Toolbox\/Sink\/ThreadSafeProxySink.h>\n#include <thread>\n#include <sstream>\n\nusing namespace Toolbox::Sink;\n\nTEST_CASE (\"ThreadSafeProxySink with lvalue Sink\")\n{\n std::string rc;\n Test::Sink sink (rc);\n ThreadSafeProxySink<Test::Sink> proxySink (std::move (sink));\n std::string message = \"test\";\n proxySink << message;\n \n REQUIRE (rc == message);\n}\n\nTEST_CASE (\"ThreadSafeProxySink with rvalue Sink\")\n{\n std::string rc;\n ThreadSafeProxySink<Test::Sink> proxySink (Test::Sink {rc});\n std::string message = \"test\";\n proxySink << message;\n \n REQUIRE (rc == message);\n}\n\nTEST_CASE (\"Instantiate ThreadSafeProxySink using make_thread_safe\")\n{\n std::string rc;\n auto proxySink = make_thread_safe<Test::Sink>(rc);\n std::string message = \"test\";\n proxySink << message;\n\n REQUIRE (rc == message);\n}\n\nTEST_CASE (\"ThreadSafeSink\")\n{\n std::string rc;\n Test::SafeSink safeSink (rc);\n std::string message = \"test\";\n safeSink << message;\n\n REQUIRE (rc == message);\n}<commit_msg>added make_unique_thread_safe test<commit_after>#include <Toolbox\/catch.hpp>\n\n#include \"TestSink.h\"\n#include <Toolbox\/Sink\/ThreadSafeProxySink.h>\n#include <thread>\n#include <sstream>\n\nusing namespace Toolbox::Sink;\n\nTEST_CASE (\"ThreadSafeProxySink with lvalue Sink\")\n{\n std::string rc;\n Test::Sink sink (rc);\n ThreadSafeProxySink<Test::Sink> proxySink (std::move (sink));\n std::string message = \"test\";\n proxySink << message;\n \n REQUIRE (rc == message);\n}\n\nTEST_CASE (\"ThreadSafeProxySink with rvalue Sink\")\n{\n std::string rc;\n ThreadSafeProxySink<Test::Sink> proxySink (Test::Sink {rc});\n std::string message = \"test\";\n proxySink << message;\n \n REQUIRE (rc == message);\n}\n\nTEST_CASE (\"Instantiate ThreadSafeProxySink using make_thread_safe\")\n{\n std::string rc;\n auto proxySink = make_thread_safe<Test::Sink>(rc);\n std::string message = \"test\";\n proxySink << message;\n\n REQUIRE (rc == message);\n}\n\nTEST_CASE (\"Instantiate a unique_ptr<ThreadSafeProxySink> using make_unique_thread_safe\")\n{\n std::string rc;\n auto proxySink = make_unique_thread_safe<Test::Sink>(rc);\n std::string message = \"test\";\n (*proxySink) << message;\n\n REQUIRE (rc == message);\n}\n\nTEST_CASE (\"ThreadSafeSink\")\n{\n std::string rc;\n Test::SafeSink safeSink (rc);\n std::string message = \"test\";\n safeSink << message;\n\n REQUIRE (rc == message);\n}<|endoftext|>"} {"text":"<commit_before>\n#include \"NNSound.h\"\n#include \"NNApplication.h\"\n\nvoid GetFileExtenstion(const wchar_t * file_name, wchar_t * file_ext, size_t file_ext_size)\r\n{ \r\n\t_wsplitpath_s(file_name, NULL, 0, NULL, 0, NULL, 0, file_ext, file_ext_size);\r\n\twprintf(L\"%s\\n\", file_ext);\r\n\t\r\n\t\/*wchar_t* _file_name = nullptr;\n\t_file_name = (wchar_t*)malloc(1024);\n\twcscpy_s(_file_name, 256, file_name);\n\tint file_name_len = wcslen (_file_name); \n\t_file_name +=file_name_len ;\n\n\twchar_t *file_ext = nullptr;\n\tfor(int i = 0 ; i <file_name_len ; i ++)\n\t{\n\t\tif(* _file_name == '.' )\n\t\t{\n\t\t\tfile_ext = _file_name +1 ;\n\t\t\tbreak;\n\t\t} \n\t\t_file_name --;\n\t} \n\treturn file_ext ;*\/\r\n\t\/\/return file_ext;\r\n}\n\nNNSound::NNSound()\n\t: m_Playing(false)\n{\n}\nNNSound::~NNSound()\n{\n\tDestroy();\n}\n\nvoid NNSound::Create( std::wstring path )\n{\n\tMCI_OPEN_PARMS mciOpen = {0};\n\tMCIERROR mciError = {0};\n\twchar_t file_ext[10];\n\t\n\tGetFileExtenstion(path.c_str(), file_ext, sizeof(file_ext) \/ sizeof(wchar_t));\n\n\tif(wcscmp(file_ext, L\".mp3\") == 0 )\n\t{\n\t\t\/\/mp3\n\t\tmciOpen.lpstrDeviceType = L\"MPEGVideo\";\/\/(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;\n\t}\n\telse if(wcscmp(file_ext, L\".wav\") == 0 )\n\t{\n\t\tmciOpen.lpstrDeviceType = L\"waveaudio\";\/\/(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;\n\t}\n\tmciOpen.lpstrElementName = path.c_str();\n\n\tmciError = mciSendCommand( NULL, MCI_OPEN, MCI_OPEN_ELEMENT|MCI_OPEN_TYPE, (DWORD)&mciOpen );\n\tif ( mciError )\n\t{\n\t\treturn;\n\t}\n\n\tm_MciDevice = mciOpen.wDeviceID;\n\tm_Playing = false;\n}\n\nvoid NNSound::Destroy()\n{\n\tif ( m_Playing )\n\t{\n\t\tStop();\n\t}\n\tif ( m_MciDevice )\n\t{\n\t\tmciSendCommand( m_MciDevice, MCI_CLOSE, 0, 0 );\n\t}\n}\n\nvoid NNSound::Play()\n{\n\tif ( !m_MciDevice )\n\t{\n\t\treturn;\n\t}\n\tMCI_PLAY_PARMS mciPlay = {0};\n\tMCIERROR mciError = {0};\n\n\tmciPlay.dwCallback = (DWORD_PTR)NNApplication::GetInstance()->GetHWND();\n\tmciError = mciSendCommand( m_MciDevice, MCI_PLAY, MCI_FROM|MCI_NOTIFY, (DWORD)&mciPlay );\n\tif ( !mciError )\n\t{\n\t\tm_Playing = true;\n\t}\n}\nvoid NNSound::Pause()\n{\n\tif ( !m_MciDevice )\n\t{\n\t\treturn;\n\t}\n\tmciSendCommand( m_MciDevice, MCI_PAUSE, 0, 0 );\n}\nvoid NNSound::Resume()\n{\n\tif ( !m_MciDevice )\n\t{\n\t\treturn;\n\t}\n\tmciSendCommand( m_MciDevice, MCI_RESUME, 0, 0 );\n}\nvoid NNSound::Stop()\n{\n\tif ( !m_MciDevice )\n\t{\n\t\treturn;\n\t}\n\tmciSendCommand( m_MciDevice, MCI_STOP, 0, 0 );\n\tm_Playing = false;\n}\n\n<commit_msg>불필요한 함수 삭제 및 수정<commit_after>\n#include \"NNSound.h\"\n#include \"NNApplication.h\"\n\nNNSound::NNSound()\n\t: m_Playing(false)\n{\n}\nNNSound::~NNSound()\n{\n\tDestroy();\n}\n\nvoid NNSound::Create( std::wstring path )\n{\n\tMCI_OPEN_PARMS mciOpen = {0};\n\tMCIERROR mciError = {0};\n\twchar_t file_ext[10];\n\t\r\n\t\/\/ Ȯ \r\n\t_wsplitpath_s(path.c_str(), NULL, 0, NULL, 0, NULL, 0, file_ext, sizeof(file_ext) \/ sizeof(wchar_t));\r\n\t\n\tif(wcscmp(file_ext, L\".mp3\") == 0 )\n\t{\n\t\t\/\/mp3\n\t\tmciOpen.lpstrDeviceType = L\"MPEGVideo\";\/\/(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;\n\t}\n\telse if(wcscmp(file_ext, L\".wav\") == 0 )\n\t{\n\t\tmciOpen.lpstrDeviceType = L\"waveaudio\";\/\/(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;\n\t}\n\tmciOpen.lpstrElementName = path.c_str();\n\n\tmciError = mciSendCommand( NULL, MCI_OPEN, MCI_OPEN_ELEMENT|MCI_OPEN_TYPE, (DWORD)&mciOpen );\n\tif ( mciError )\n\t{\n\t\treturn;\n\t}\n\n\tm_MciDevice = mciOpen.wDeviceID;\n\tm_Playing = false;\n}\n\nvoid NNSound::Destroy()\n{\n\tif ( m_Playing )\n\t{\n\t\tStop();\n\t}\n\tif ( m_MciDevice )\n\t{\n\t\tmciSendCommand( m_MciDevice, MCI_CLOSE, 0, 0 );\n\t}\n}\n\nvoid NNSound::Play()\n{\n\tif ( !m_MciDevice )\n\t{\n\t\treturn;\n\t}\n\tMCI_PLAY_PARMS mciPlay = {0};\n\tMCIERROR mciError = {0};\n\n\tmciPlay.dwCallback = (DWORD_PTR)NNApplication::GetInstance()->GetHWND();\n\tmciError = mciSendCommand( m_MciDevice, MCI_PLAY, MCI_FROM|MCI_NOTIFY, (DWORD)&mciPlay );\n\tif ( !mciError )\n\t{\n\t\tm_Playing = true;\n\t}\n}\nvoid NNSound::Pause()\n{\n\tif ( !m_MciDevice )\n\t{\n\t\treturn;\n\t}\n\tmciSendCommand( m_MciDevice, MCI_PAUSE, 0, 0 );\n}\nvoid NNSound::Resume()\n{\n\tif ( !m_MciDevice )\n\t{\n\t\treturn;\n\t}\n\tmciSendCommand( m_MciDevice, MCI_RESUME, 0, 0 );\n}\nvoid NNSound::Stop()\n{\n\tif ( !m_MciDevice )\n\t{\n\t\treturn;\n\t}\n\tmciSendCommand( m_MciDevice, MCI_STOP, 0, 0 );\n\tm_Playing = false;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of the GUI library.\n\tCopyright (C) 2008-2012 Benjamin Eikel <benjamin@eikel.org>\n\tCopyright (C) 2008-2012 Claudius Jähn <claudius@uni-paderborn.de>\n\tCopyright (C) 2008-2012 Ralf Petring <ralf@petring.net>\n\t\n\tThis library is subject to the terms of the Mozilla Public License, v. 2.0.\n\tYou should have received a copy of the MPL along with this library; see the \n\tfile LICENSE. If not, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n#include \"StdShapes.h\"\n#include \"..\/Base\/Draw.h\"\n#include \"..\/Base\/BasicColors.h\"\n#include \"Colors.h\"\n#include <Geometry\/Interpolation.h>\n#include <Util\/References.h>\n#include <iostream>\n\nusing namespace Geometry;\n\nnamespace GUI {\n\n\/\/! OuterRectShadowShape ---|> AbstractShape\nvoid OuterRectShadowShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tGeometry::Rect rect2(rect.getMinX()-size_left,rect.getMinX()-size_top,rect.getWidth()+size_left+size_right,rect.getHeight()+size_top+size_bottom);\n\tDraw::dropShadow(rect,rect2,color);\n}\n\/\/! RectShape ---|> AbstractShape\nvoid RectShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tDraw::drawFilledRect(rect,bgColor,blend);\n\tDraw::drawLineRect(rect,lineColor,blend);\n}\n\n\/\/! Rect3dShape ---|> AbstractShape\nvoid Rect3dShape::display(const Rect & rect,flag_t flags){\n\tDraw::draw3DRect(rect, (flags&ACTIVE)^invert , bgColor1, bgColor2);\n}\n\n\/\/! ScrollableMarkerShape ---|> AbstractShape\nvoid ScrollableMarkerShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tif(!colorTop.isTransparent()){\n\t\tDraw::drawFilledRect(Rect(rect.getMinX(),rect.getMinY(),rect.getWidth(),width),\n\t\t\t\t\t\tcolorTop,Colors::NO_COLOR,Colors::NO_COLOR,colorTop);\n\t}\n\telse if(!colorRight.isTransparent()){\n\t\tDraw::drawFilledRect(Rect(rect.getMaxX()-width,rect.getMinY(),width,rect.getHeight()),\n\t\t\t\t\t\tColors::NO_COLOR,Colors::NO_COLOR,colorRight,colorRight);\n\t}\n\telse if(!colorBottom.isTransparent()){\n\t\tDraw::drawFilledRect(Rect(rect.getMinX(),rect.getMaxY()-width,rect.getWidth(),width),\n\t\t\t\t\t\tColors::NO_COLOR,colorBottom,colorBottom,Colors::NO_COLOR);\n\t}\n\telse if(!colorLeft.isTransparent()){\n\t\tDraw::drawFilledRect(Rect(rect.getMinX(),rect.getMinY(),width,rect.getHeight()),\n\t\t\t\t\t\tcolorLeft,colorLeft,Colors::NO_COLOR,Colors::NO_COLOR);\n\t}\n\n}\n\/\/! ShadowedRectShape ---|> AbstractShape\nvoid ShadowedRectShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tDraw::drawFilledRect(rect,bgColor,blend);\n\tDraw::drawLineRect(rect,lineColor,blend);\n\tDraw::dropShadow(rect);\n}\n\n\/\/! SliderMarkerShape ---|> AbstractShape\nvoid SliderMarkerShape::display(const Rect & rect,flag_t flags){\n\tif (flags&ACTIVE)\n\t\tDraw::draw3DRect(rect,true,color1,color2);\n\telse\n\t\tDraw::draw3DRect(rect,false,color1,color2);\n\tVec2 c=rect.getCenter();\n\tDraw::draw3DRect(Rect(c.x()-1 , c.y()-1 ,2,2),false,color1,color2);\n}\n\n\/\/! TabHeaderShape ---|> AbstractShape\nvoid TabHeaderShape::display(const Rect & rect,flag_t \/*flags*\/){\n\tDraw::drawTab(rect,color1,color2,color3);\n}\n\n\/\/! Rounded3dRectShape ---|> AbstractShape\nvoid Rounded3dRectShape::display(const Rect & rect,flag_t flags){\n\tconst bool down=flags&ACTIVE;\n\tif (bgColor1 != Colors::NO_COLOR){\n\t\tstd::vector<float> vertices;\n\t\tstd::vector<uint32_t> colors;\n\t\tvertices.reserve(8*2);\n\t\tcolors.reserve(8);\n\n\t\tcolors.insert(colors.end(),4, (down ? bgColor2:bgColor1).getAsUInt());\n\t\tvertices.push_back(rect.getMaxX());\t\t\t\tvertices.push_back(rect.getMinY()+roundnessTR);\n\t\tvertices.push_back(rect.getMaxX()-roundnessTR);\tvertices.push_back(rect.getMinY());\n\t\tvertices.push_back(rect.getMinX()+roundnessTL);\tvertices.push_back(rect.getMinY());\n\t\tvertices.push_back(rect.getMinX());\t\t\t\tvertices.push_back(rect.getMinY()+roundnessTL);\n\n\t\tcolors.insert(colors.end(),4,(down ? bgColor1:bgColor2).getAsUInt());\n\t\tvertices.push_back(rect.getMinX());\t\t\t\tvertices.push_back(rect.getMaxY()-roundnessBL);\n\t\tvertices.push_back(rect.getMinX()+roundnessBL);\tvertices.push_back(rect.getMaxY());\n\t\tvertices.push_back(rect.getMaxX()-roundnessBR);\tvertices.push_back(rect.getMaxY());\n\t\tvertices.push_back(rect.getMaxX());\t\t\t\tvertices.push_back(rect.getMaxY()-roundnessBR);\n\n\t\tDraw::drawTriangleFan(vertices,colors);\n\t}\n\n\t{\t\/\/ draw border\n\t\tconst Util::Color4ub c1 = down ? Colors::BRIGHT_COLOR : Colors::DARK_COLOR;\n\t\tconst Util::Color4ub c2 = down ? Colors::DARK_COLOR : Colors::BRIGHT_COLOR;\n\n\t\tstd::vector<float> vertices;\n\t\tstd::vector<uint32_t> colors;\n\t\tvertices.reserve(10*2);\n\t\tcolors.reserve(10);\n\n\t\tconst Geometry::Rect_i r2(rect);\n\t\tGeometry::Rect r3(r2);\n\t\tr3.moveRel(0.5f,0.5f);\n\t\n\t\tcolors.insert(colors.end(),5,c1.getAsUInt());\n\t\tvertices.push_back(r3.getMinX());\t\t\t\tvertices.push_back(r3.getMaxY()-roundnessBL);\n\t\tvertices.push_back(r3.getMinX()+roundnessBL);\tvertices.push_back(r3.getMaxY());\n\t\tvertices.push_back(r3.getMaxX()-roundnessBR);\tvertices.push_back(r3.getMaxY());\n\t\tvertices.push_back(r3.getMaxX());\t\t\t\tvertices.push_back(r3.getMaxY()-roundnessBR);\n\t\tvertices.push_back(r3.getMaxX());\t\t\t\tvertices.push_back(r3.getMinY()+roundnessTR);\n\n\t\tcolors.insert(colors.end(),5,c2.getAsUInt());\n\t\tvertices.push_back(r3.getMaxX());\t\t\t\tvertices.push_back(r3.getMinY()+roundnessTR);\n\t\tvertices.push_back(r3.getMaxX()-roundnessTR);\tvertices.push_back(r3.getMinY());\n\t\tvertices.push_back(r3.getMinX()+roundnessTL);\tvertices.push_back(r3.getMinY());\n\t\tvertices.push_back(r3.getMinX());\t\t\t\tvertices.push_back(r3.getMinY()+roundnessTL);\n\t\tvertices.push_back(r3.getMinX());\t\t\t\tvertices.push_back(r3.getMaxY()-roundnessBL);\n\t\tDraw::drawLine(vertices,colors,1.0);\n\t}\n}\n\/\/\n\/\/! ResizerShape ---|> AbstractShape\nvoid ResizerShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tconst float w=floorf(rect.getWidth()\/4.0f);\n\tconst float h=floorf(rect.getWidth()\/4.0f);\n\tconst float x=floorf(rect.getX());\n\tconst float y=floorf(rect.getY());\n\tDraw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*0.25f), w,h) ,color,blend);\n\n\tDraw::drawFilledRect(Rect(x + floorf(w*1.5f) , y+ floorf(h*1.5f), w,h) ,color,blend);\n\tDraw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*1.5f), w,h) ,color,blend);\n\n\tDraw::drawFilledRect(Rect(x + floorf(w*0.25f), y+ floorf(h*2.75f), w,h) ,color,blend);\n\tDraw::drawFilledRect(Rect(x + floorf(w*1.5f) , y+ floorf(h*2.75f), w,h) ,color,blend);\n\tDraw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*2.75f), w,h) ,color,blend);\n}\/\/\n\n\/\/! TriangleAtCornerShape ---|> AbstractShape\nvoid TriangleAtCornerShape::display(const Rect & rect,flag_t\/* flags*\/){\n\tstd::vector<float> vertices;\n\tstd::vector<uint32_t> colors;\n\tvertices.reserve(3*2);\n\tcolors.reserve(3);\n\n\tcolors.insert(colors.end(),3, color.getAsUInt());\n\n\tconst Geometry::Vec2 corner = rect.getCorner(CORNER_XY);\n\tvertices.push_back(corner.x());\t\t\t\tvertices.push_back(corner.y());\n\tvertices.push_back(corner.x());\t\t\t\tvertices.push_back(corner.y()-size);\n\tvertices.push_back(corner.x()-size);\t\tvertices.push_back(corner.y());\n\n\tDraw::drawTriangleFan(vertices,colors);\n}\n\n\/\/! TriangleSelectorShape ---|> AbstractShape\nvoid TriangleSelectorShape::display(const Rect & rect,flag_t flags){\n\tstd::vector<float> vertices;\n\tstd::vector<uint32_t> colors;\n\tvertices.reserve(3*2);\n\tcolors.reserve(3);\n\n\tcolors.insert(colors.end(),3, color.getAsUInt());\n\n\tconst float sideLength = std::min(rect.getWidth(),rect.getHeight());\n\tconst float halfSideLength = sideLength*0.5;\n\tconst float h = std::sqrt( sideLength*sideLength - halfSideLength*halfSideLength );\n\tconst float halfH = h*0.5;\n\tconst Geometry::Vec2 center = rect.getCenter();\n\tif(flags&ACTIVE){\n\t\tvertices.push_back(center.x()-halfSideLength);\t\tvertices.push_back(center.y()-halfH);\n\t\tvertices.push_back(center.x());\t\t\t\t\t\tvertices.push_back(center.y()+halfH);\n\t\tvertices.push_back(center.x()+halfSideLength);\t\tvertices.push_back(center.y()-halfH);\n\t}else{\n\t\tvertices.push_back(center.x()-halfH);\t\t\t\tvertices.push_back(center.y()-halfSideLength);\n\t\tvertices.push_back(center.x()-halfH);\t\t\t\tvertices.push_back(center.y()+halfSideLength);\n\t\tvertices.push_back(center.x()+halfH);\t\t\t\tvertices.push_back(center.y());\n\t}\n\tDraw::drawTriangleFan(vertices,colors);\n}\n\n\/\/! GridShape ---|> AbstractShape\nvoid GridShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tstd::vector<float> vertices;\n\tstd::vector<uint32_t> colors;\n\n\t\/\/ horizontal lines\n\tif(hDistance>0){\n\t\tint count=0;\n\t\tfor(float pos=0;pos<=rect.getHeight();pos+=hDistance){\n\t\t\tcolors.insert(colors.end(),2,(((count++ % (hNumMinors+1)) ==0) ? majorColor : minorColor).getAsUInt());\n\t\t\tvertices.push_back(0);\t\t\t\t\t\tvertices.push_back(pos);\n\t\t\tvertices.push_back(rect.getWidth());\t\tvertices.push_back(pos);\n\t\t}\n\t}\n\t\/\/ vertical lines\n\tif(vDistance>0){\n\t\tint count=0;\n\t\tfor(float pos=0;pos<=rect.getWidth();pos+=vDistance){\n\t\t\tcolors.insert(colors.end(),2,(((count++ % (vNumMinors+1)) ==0) ? majorColor : minorColor).getAsUInt());\n\t\t\tvertices.push_back(pos);\t\t\t\t\tvertices.push_back(0);\n\t\t\tvertices.push_back(pos);\t\t\t\t\tvertices.push_back(rect.getHeight());\n\t\t}\n\t}\n\tDraw::drawLines(vertices,colors);\n}\n\n\/\/! CrossShape ---|> AbstractShape\nvoid CrossShape::display(const Rect & rect,flag_t flags){\n\tDraw::drawCross(rect,flags&ACTIVE ? color2 : color1,lineWidth);\n}\n\n\n\/\/! StraightLineShape ---|> LineShape\nvoid StraightLineShape::displayLine(const std::vector<Geometry::Vec2> & points,flag_t){\n\tstd::vector<float> vertices;\n\tvertices.reserve(points.size()*2);\n\tfor(auto & point : points){\n\t\tvertices.push_back(static_cast<int>(point.x())+0.5f);\n\t\tvertices.push_back(static_cast<int>(point.y())+0.5f);\n\t}\n\n\tstd::vector<uint32_t> colors;\n\tcolors.insert(colors.end(),vertices.size(),color.getAsUInt());\n\tDraw::drawLine(vertices,colors,lineWidth,true);\n}\n\n\/\/! SmoothConnectorShape ---|> LineShape\nvoid SmoothConnectorShape::displayLine(const std::vector<Geometry::Vec2> & points,flag_t){\n\tstd::vector<float> vertices;\n\tfor(size_t i=1;i<points.size();++i){\n\t\tconst Geometry::Vec2 p0(points[i-1]); \/\/ startPoint\n\t\tconst Geometry::Vec2 p3(points[i]); \/\/ endPoint\n\t\tconst float d = std::min(p0.distance(p3)*0.4,100.0);\n\t\tconst Geometry::Vec2 p1(p0+Geometry::Vec2(d,0));\n\t\tconst Geometry::Vec2 p2(p3-Geometry::Vec2(d,0));\n\n\t\tvertices.push_back(p0.x());\n\t\tvertices.push_back(p0.y());\n\t\tfor(float t=0.0;t<=1.00;t += t<0.5 ? ((t*t)+0.1)*0.1 : (( (1.0-t)*(1.0-t))+0.1)*0.1 ){\n\t\t\tconst Geometry::Vec2 p_t = Interpolation::cubicBezier(p0, p1, p2, p3, t);\n\t\t\tvertices.push_back(p_t.x());\n\t\t\tvertices.push_back(p_t.y());\n\t\t}\n\t}\n\tstd::vector<uint32_t> colors;\n\tcolors.insert(colors.end(),vertices.size(),color.getAsUInt());\n\tDraw::drawLine(vertices,colors,lineWidth,true);\n}\n\n\n}\n<commit_msg>Adapt to changes in Geometry<commit_after>\/*\n\tThis file is part of the GUI library.\n\tCopyright (C) 2008-2012 Benjamin Eikel <benjamin@eikel.org>\n\tCopyright (C) 2008-2012 Claudius Jähn <claudius@uni-paderborn.de>\n\tCopyright (C) 2008-2012 Ralf Petring <ralf@petring.net>\n\t\n\tThis library is subject to the terms of the Mozilla Public License, v. 2.0.\n\tYou should have received a copy of the MPL along with this library; see the \n\tfile LICENSE. If not, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n#include \"StdShapes.h\"\n#include \"..\/Base\/Draw.h\"\n#include \"..\/Base\/BasicColors.h\"\n#include \"Colors.h\"\n#include <Geometry\/Interpolation.h>\n#include <Util\/References.h>\n#include <iostream>\n\nusing namespace Geometry;\n\nnamespace GUI {\n\n\/\/! OuterRectShadowShape ---|> AbstractShape\nvoid OuterRectShadowShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tGeometry::Rect rect2(rect.getMinX()-size_left,rect.getMinX()-size_top,rect.getWidth()+size_left+size_right,rect.getHeight()+size_top+size_bottom);\n\tDraw::dropShadow(rect,rect2,color);\n}\n\/\/! RectShape ---|> AbstractShape\nvoid RectShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tDraw::drawFilledRect(rect,bgColor,blend);\n\tDraw::drawLineRect(rect,lineColor,blend);\n}\n\n\/\/! Rect3dShape ---|> AbstractShape\nvoid Rect3dShape::display(const Rect & rect,flag_t flags){\n\tDraw::draw3DRect(rect, (flags&ACTIVE)^invert , bgColor1, bgColor2);\n}\n\n\/\/! ScrollableMarkerShape ---|> AbstractShape\nvoid ScrollableMarkerShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tif(!colorTop.isTransparent()){\n\t\tDraw::drawFilledRect(Rect(rect.getMinX(),rect.getMinY(),rect.getWidth(),width),\n\t\t\t\t\t\tcolorTop,Colors::NO_COLOR,Colors::NO_COLOR,colorTop);\n\t}\n\telse if(!colorRight.isTransparent()){\n\t\tDraw::drawFilledRect(Rect(rect.getMaxX()-width,rect.getMinY(),width,rect.getHeight()),\n\t\t\t\t\t\tColors::NO_COLOR,Colors::NO_COLOR,colorRight,colorRight);\n\t}\n\telse if(!colorBottom.isTransparent()){\n\t\tDraw::drawFilledRect(Rect(rect.getMinX(),rect.getMaxY()-width,rect.getWidth(),width),\n\t\t\t\t\t\tColors::NO_COLOR,colorBottom,colorBottom,Colors::NO_COLOR);\n\t}\n\telse if(!colorLeft.isTransparent()){\n\t\tDraw::drawFilledRect(Rect(rect.getMinX(),rect.getMinY(),width,rect.getHeight()),\n\t\t\t\t\t\tcolorLeft,colorLeft,Colors::NO_COLOR,Colors::NO_COLOR);\n\t}\n\n}\n\/\/! ShadowedRectShape ---|> AbstractShape\nvoid ShadowedRectShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tDraw::drawFilledRect(rect,bgColor,blend);\n\tDraw::drawLineRect(rect,lineColor,blend);\n\tDraw::dropShadow(rect);\n}\n\n\/\/! SliderMarkerShape ---|> AbstractShape\nvoid SliderMarkerShape::display(const Rect & rect,flag_t flags){\n\tif (flags&ACTIVE)\n\t\tDraw::draw3DRect(rect,true,color1,color2);\n\telse\n\t\tDraw::draw3DRect(rect,false,color1,color2);\n\tVec2 c=rect.getCenter();\n\tDraw::draw3DRect(Rect(c.x()-1 , c.y()-1 ,2,2),false,color1,color2);\n}\n\n\/\/! TabHeaderShape ---|> AbstractShape\nvoid TabHeaderShape::display(const Rect & rect,flag_t \/*flags*\/){\n\tDraw::drawTab(rect,color1,color2,color3);\n}\n\n\/\/! Rounded3dRectShape ---|> AbstractShape\nvoid Rounded3dRectShape::display(const Rect & rect,flag_t flags){\n\tconst bool down=flags&ACTIVE;\n\tif (bgColor1 != Colors::NO_COLOR){\n\t\tstd::vector<float> vertices;\n\t\tstd::vector<uint32_t> colors;\n\t\tvertices.reserve(8*2);\n\t\tcolors.reserve(8);\n\n\t\tcolors.insert(colors.end(),4, (down ? bgColor2:bgColor1).getAsUInt());\n\t\tvertices.push_back(rect.getMaxX());\t\t\t\tvertices.push_back(rect.getMinY()+roundnessTR);\n\t\tvertices.push_back(rect.getMaxX()-roundnessTR);\tvertices.push_back(rect.getMinY());\n\t\tvertices.push_back(rect.getMinX()+roundnessTL);\tvertices.push_back(rect.getMinY());\n\t\tvertices.push_back(rect.getMinX());\t\t\t\tvertices.push_back(rect.getMinY()+roundnessTL);\n\n\t\tcolors.insert(colors.end(),4,(down ? bgColor1:bgColor2).getAsUInt());\n\t\tvertices.push_back(rect.getMinX());\t\t\t\tvertices.push_back(rect.getMaxY()-roundnessBL);\n\t\tvertices.push_back(rect.getMinX()+roundnessBL);\tvertices.push_back(rect.getMaxY());\n\t\tvertices.push_back(rect.getMaxX()-roundnessBR);\tvertices.push_back(rect.getMaxY());\n\t\tvertices.push_back(rect.getMaxX());\t\t\t\tvertices.push_back(rect.getMaxY()-roundnessBR);\n\n\t\tDraw::drawTriangleFan(vertices,colors);\n\t}\n\n\t{\t\/\/ draw border\n\t\tconst Util::Color4ub c1 = down ? Colors::BRIGHT_COLOR : Colors::DARK_COLOR;\n\t\tconst Util::Color4ub c2 = down ? Colors::DARK_COLOR : Colors::BRIGHT_COLOR;\n\n\t\tstd::vector<float> vertices;\n\t\tstd::vector<uint32_t> colors;\n\t\tvertices.reserve(10*2);\n\t\tcolors.reserve(10);\n\n\t\tconst Geometry::Rect_i r2(rect);\n\t\tGeometry::Rect r3(r2);\n\t\tr3.moveRel(0.5f,0.5f);\n\t\n\t\tcolors.insert(colors.end(),5,c1.getAsUInt());\n\t\tvertices.push_back(r3.getMinX());\t\t\t\tvertices.push_back(r3.getMaxY()-roundnessBL);\n\t\tvertices.push_back(r3.getMinX()+roundnessBL);\tvertices.push_back(r3.getMaxY());\n\t\tvertices.push_back(r3.getMaxX()-roundnessBR);\tvertices.push_back(r3.getMaxY());\n\t\tvertices.push_back(r3.getMaxX());\t\t\t\tvertices.push_back(r3.getMaxY()-roundnessBR);\n\t\tvertices.push_back(r3.getMaxX());\t\t\t\tvertices.push_back(r3.getMinY()+roundnessTR);\n\n\t\tcolors.insert(colors.end(),5,c2.getAsUInt());\n\t\tvertices.push_back(r3.getMaxX());\t\t\t\tvertices.push_back(r3.getMinY()+roundnessTR);\n\t\tvertices.push_back(r3.getMaxX()-roundnessTR);\tvertices.push_back(r3.getMinY());\n\t\tvertices.push_back(r3.getMinX()+roundnessTL);\tvertices.push_back(r3.getMinY());\n\t\tvertices.push_back(r3.getMinX());\t\t\t\tvertices.push_back(r3.getMinY()+roundnessTL);\n\t\tvertices.push_back(r3.getMinX());\t\t\t\tvertices.push_back(r3.getMaxY()-roundnessBL);\n\t\tDraw::drawLine(vertices,colors,1.0);\n\t}\n}\n\/\/\n\/\/! ResizerShape ---|> AbstractShape\nvoid ResizerShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tconst float w=floorf(rect.getWidth()\/4.0f);\n\tconst float h=floorf(rect.getWidth()\/4.0f);\n\tconst float x=floorf(rect.getX());\n\tconst float y=floorf(rect.getY());\n\tDraw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*0.25f), w,h) ,color,blend);\n\n\tDraw::drawFilledRect(Rect(x + floorf(w*1.5f) , y+ floorf(h*1.5f), w,h) ,color,blend);\n\tDraw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*1.5f), w,h) ,color,blend);\n\n\tDraw::drawFilledRect(Rect(x + floorf(w*0.25f), y+ floorf(h*2.75f), w,h) ,color,blend);\n\tDraw::drawFilledRect(Rect(x + floorf(w*1.5f) , y+ floorf(h*2.75f), w,h) ,color,blend);\n\tDraw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*2.75f), w,h) ,color,blend);\n}\/\/\n\n\/\/! TriangleAtCornerShape ---|> AbstractShape\nvoid TriangleAtCornerShape::display(const Rect & rect,flag_t\/* flags*\/){\n\tstd::vector<float> vertices;\n\tstd::vector<uint32_t> colors;\n\tvertices.reserve(3*2);\n\tcolors.reserve(3);\n\n\tcolors.insert(colors.end(),3, color.getAsUInt());\n\n\tconst Geometry::Vec2 corner = rect.getCorner(Geometry::rectCorner_t::XY);\n\tvertices.push_back(corner.x());\t\t\t\tvertices.push_back(corner.y());\n\tvertices.push_back(corner.x());\t\t\t\tvertices.push_back(corner.y()-size);\n\tvertices.push_back(corner.x()-size);\t\tvertices.push_back(corner.y());\n\n\tDraw::drawTriangleFan(vertices,colors);\n}\n\n\/\/! TriangleSelectorShape ---|> AbstractShape\nvoid TriangleSelectorShape::display(const Rect & rect,flag_t flags){\n\tstd::vector<float> vertices;\n\tstd::vector<uint32_t> colors;\n\tvertices.reserve(3*2);\n\tcolors.reserve(3);\n\n\tcolors.insert(colors.end(),3, color.getAsUInt());\n\n\tconst float sideLength = std::min(rect.getWidth(),rect.getHeight());\n\tconst float halfSideLength = sideLength*0.5;\n\tconst float h = std::sqrt( sideLength*sideLength - halfSideLength*halfSideLength );\n\tconst float halfH = h*0.5;\n\tconst Geometry::Vec2 center = rect.getCenter();\n\tif(flags&ACTIVE){\n\t\tvertices.push_back(center.x()-halfSideLength);\t\tvertices.push_back(center.y()-halfH);\n\t\tvertices.push_back(center.x());\t\t\t\t\t\tvertices.push_back(center.y()+halfH);\n\t\tvertices.push_back(center.x()+halfSideLength);\t\tvertices.push_back(center.y()-halfH);\n\t}else{\n\t\tvertices.push_back(center.x()-halfH);\t\t\t\tvertices.push_back(center.y()-halfSideLength);\n\t\tvertices.push_back(center.x()-halfH);\t\t\t\tvertices.push_back(center.y()+halfSideLength);\n\t\tvertices.push_back(center.x()+halfH);\t\t\t\tvertices.push_back(center.y());\n\t}\n\tDraw::drawTriangleFan(vertices,colors);\n}\n\n\/\/! GridShape ---|> AbstractShape\nvoid GridShape::display(const Rect & rect,flag_t \/*flag*\/){\n\tstd::vector<float> vertices;\n\tstd::vector<uint32_t> colors;\n\n\t\/\/ horizontal lines\n\tif(hDistance>0){\n\t\tint count=0;\n\t\tfor(float pos=0;pos<=rect.getHeight();pos+=hDistance){\n\t\t\tcolors.insert(colors.end(),2,(((count++ % (hNumMinors+1)) ==0) ? majorColor : minorColor).getAsUInt());\n\t\t\tvertices.push_back(0);\t\t\t\t\t\tvertices.push_back(pos);\n\t\t\tvertices.push_back(rect.getWidth());\t\tvertices.push_back(pos);\n\t\t}\n\t}\n\t\/\/ vertical lines\n\tif(vDistance>0){\n\t\tint count=0;\n\t\tfor(float pos=0;pos<=rect.getWidth();pos+=vDistance){\n\t\t\tcolors.insert(colors.end(),2,(((count++ % (vNumMinors+1)) ==0) ? majorColor : minorColor).getAsUInt());\n\t\t\tvertices.push_back(pos);\t\t\t\t\tvertices.push_back(0);\n\t\t\tvertices.push_back(pos);\t\t\t\t\tvertices.push_back(rect.getHeight());\n\t\t}\n\t}\n\tDraw::drawLines(vertices,colors);\n}\n\n\/\/! CrossShape ---|> AbstractShape\nvoid CrossShape::display(const Rect & rect,flag_t flags){\n\tDraw::drawCross(rect,flags&ACTIVE ? color2 : color1,lineWidth);\n}\n\n\n\/\/! StraightLineShape ---|> LineShape\nvoid StraightLineShape::displayLine(const std::vector<Geometry::Vec2> & points,flag_t){\n\tstd::vector<float> vertices;\n\tvertices.reserve(points.size()*2);\n\tfor(auto & point : points){\n\t\tvertices.push_back(static_cast<int>(point.x())+0.5f);\n\t\tvertices.push_back(static_cast<int>(point.y())+0.5f);\n\t}\n\n\tstd::vector<uint32_t> colors;\n\tcolors.insert(colors.end(),vertices.size(),color.getAsUInt());\n\tDraw::drawLine(vertices,colors,lineWidth,true);\n}\n\n\/\/! SmoothConnectorShape ---|> LineShape\nvoid SmoothConnectorShape::displayLine(const std::vector<Geometry::Vec2> & points,flag_t){\n\tstd::vector<float> vertices;\n\tfor(size_t i=1;i<points.size();++i){\n\t\tconst Geometry::Vec2 p0(points[i-1]); \/\/ startPoint\n\t\tconst Geometry::Vec2 p3(points[i]); \/\/ endPoint\n\t\tconst float d = std::min(p0.distance(p3)*0.4,100.0);\n\t\tconst Geometry::Vec2 p1(p0+Geometry::Vec2(d,0));\n\t\tconst Geometry::Vec2 p2(p3-Geometry::Vec2(d,0));\n\n\t\tvertices.push_back(p0.x());\n\t\tvertices.push_back(p0.y());\n\t\tfor(float t=0.0;t<=1.00;t += t<0.5 ? ((t*t)+0.1)*0.1 : (( (1.0-t)*(1.0-t))+0.1)*0.1 ){\n\t\t\tconst Geometry::Vec2 p_t = Interpolation::cubicBezier(p0, p1, p2, p3, t);\n\t\t\tvertices.push_back(p_t.x());\n\t\t\tvertices.push_back(p_t.y());\n\t\t}\n\t}\n\tstd::vector<uint32_t> colors;\n\tcolors.insert(colors.end(),vertices.size(),color.getAsUInt());\n\tDraw::drawLine(vertices,colors,lineWidth,true);\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#ifndef LUABIND_CONFIG_HPP_INCLUDED\n#define LUABIND_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n\n#ifdef BOOST_MSVC\n\t#define LUABIND_ANONYMOUS_FIX static\n#else\n\t#define LUABIND_ANONYMOUS_FIX\n#endif\n\n#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1200)\n\n#define for if (false) {} else for\n\n#include <cstring>\n\nnamespace std\n{\n\tusing ::strlen;\n\tusing ::strcmp;\n\tusing ::type_info;\n}\n\n#endif\n\n\n#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1300)\n\t#define LUABIND_MSVC_TYPENAME\n#else\n\t#define LUABIND_MSVC_TYPENAME typename\n#endif\n\n\/\/ the maximum number of arguments of functions that's\n\/\/ registered. Must at least be 2\n#ifndef LUABIND_MAX_ARITY\n\t#define LUABIND_MAX_ARITY 10\n#elif LUABIND_MAX_ARITY <= 1\n\t#undef LUABIND_MAX_ARITY\n\t#define LUABIND_MAX_ARITY 2\n#endif\n\n\/\/ the maximum number of classes one class\n\/\/ can derive from\n\/\/ max bases must at least be 1\n#ifndef LUABIND_MAX_BASES\n\t#define LUABIND_MAX_BASES 4\n#elif LUABIND_MAX_BASES <= 0\n\t#undef LUABIND_MAX_BASES\n\t#define LUABIND_MAX_BASES 1\n#endif\n\n\/\/ LUABIND_NO_ERROR_CHECKING\n\/\/ define this to remove all error checks\n\/\/ this will improve performance and memory\n\/\/ footprint.\n\/\/ if it is defined matchers will only be called on\n\/\/ overloaded functions, functions that's\n\/\/ not overloaded will be called directly. The\n\/\/ parameters on the lua stack are assumed\n\/\/ to match those of the function.\n\/\/ exceptions will still be catched when there's\n\/\/ no error checking.\n\n\/\/ LUABIND_NOT_THREADSAFE\n\/\/ this define will make luabind non-thread safe. That is,\n\/\/ it will rely on a static variable. You can still have\n\/\/ multiple lua states and use coroutines, but only\n\/\/ one of your real threads may run lua code.\n\n\/\/ LUABIND_NO_EXCEPTIONS\n\/\/ this define will disable all usage of try, catch and throw in\n\/\/ luabind. This will in many cases disable runtime-errors, such\n\/\/ as invalid casts, when calling lua-functions that fails or\n\/\/ returns values that cannot be converted by the given policy.\n\/\/ Luabind requires that no function called directly or indirectly\n\/\/ by luabind throws an exception (throwing exceptions through\n\/\/ C code has undefined behavior, lua is written in C).\n\n#ifdef LUABIND_DYNAMIC_LINK\n# ifdef BOOST_WINDOWS\n# ifdef LUABIND_BUILDING\n# define LUABIND_API __declspec(dllexport)\n# else\n# define LUABIND_API __declspec(dllimport)\n# endif\n# else\n# if defined(_GNUC_) && _GNUC_ >=4\n# define LUABIND_API __attribute__ ((visibility(\"default\")))\n# endif\n# endif\n#endif\n\n#ifndef LUABIND_API\n# define LUABIND_API\n#endif\n\nnamespace luabind {\n\nLUABIND_API void disable_super_deprecation();\n\n} \/\/ namespace luabind\n\n#endif \/\/ LUABIND_CONFIG_HPP_INCLUDED\n\n<commit_msg>Don't homebrew our own import\/export macro detection - let boost do it.<commit_after>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#ifndef LUABIND_CONFIG_HPP_INCLUDED\n#define LUABIND_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n\n#ifdef BOOST_MSVC\n\t#define LUABIND_ANONYMOUS_FIX static\n#else\n\t#define LUABIND_ANONYMOUS_FIX\n#endif\n\n#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1200)\n\n#define for if (false) {} else for\n\n#include <cstring>\n\nnamespace std\n{\n\tusing ::strlen;\n\tusing ::strcmp;\n\tusing ::type_info;\n}\n\n#endif\n\n\n#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1300)\n\t#define LUABIND_MSVC_TYPENAME\n#else\n\t#define LUABIND_MSVC_TYPENAME typename\n#endif\n\n\/\/ the maximum number of arguments of functions that's\n\/\/ registered. Must at least be 2\n#ifndef LUABIND_MAX_ARITY\n\t#define LUABIND_MAX_ARITY 10\n#elif LUABIND_MAX_ARITY <= 1\n\t#undef LUABIND_MAX_ARITY\n\t#define LUABIND_MAX_ARITY 2\n#endif\n\n\/\/ the maximum number of classes one class\n\/\/ can derive from\n\/\/ max bases must at least be 1\n#ifndef LUABIND_MAX_BASES\n\t#define LUABIND_MAX_BASES 4\n#elif LUABIND_MAX_BASES <= 0\n\t#undef LUABIND_MAX_BASES\n\t#define LUABIND_MAX_BASES 1\n#endif\n\n\/\/ LUABIND_NO_ERROR_CHECKING\n\/\/ define this to remove all error checks\n\/\/ this will improve performance and memory\n\/\/ footprint.\n\/\/ if it is defined matchers will only be called on\n\/\/ overloaded functions, functions that's\n\/\/ not overloaded will be called directly. The\n\/\/ parameters on the lua stack are assumed\n\/\/ to match those of the function.\n\/\/ exceptions will still be catched when there's\n\/\/ no error checking.\n\n\/\/ LUABIND_NOT_THREADSAFE\n\/\/ this define will make luabind non-thread safe. That is,\n\/\/ it will rely on a static variable. You can still have\n\/\/ multiple lua states and use coroutines, but only\n\/\/ one of your real threads may run lua code.\n\n\/\/ LUABIND_NO_EXCEPTIONS\n\/\/ this define will disable all usage of try, catch and throw in\n\/\/ luabind. This will in many cases disable runtime-errors, such\n\/\/ as invalid casts, when calling lua-functions that fails or\n\/\/ returns values that cannot be converted by the given policy.\n\/\/ Luabind requires that no function called directly or indirectly\n\/\/ by luabind throws an exception (throwing exceptions through\n\/\/ C code has undefined behavior, lua is written in C).\n\n#ifdef LUABIND_DYNAMIC_LINK\n# ifdef LUABIND_BUILDING\n# define LUABIND_API BOOST_SYMBOL_EXPORT\n# else\n# define LUABIND_API BOOST_SYMBOL_IMPORT\n# endif\n#endif\n\n#ifndef LUABIND_API\n# define LUABIND_API\n#endif\n\nnamespace luabind {\n\nLUABIND_API void disable_super_deprecation();\n\n} \/\/ namespace luabind\n\n#endif \/\/ LUABIND_CONFIG_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>#include \"opencv2\/core\/utility.hpp\"\n#include \"opencv2\/imgproc.hpp\"\n#include \"opencv2\/imgcodecs.hpp\"\n#include \"opencv2\/highgui.hpp\"\n\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\n\nconst auto RED = cv::Scalar(0,0,255);\nconst auto PINK = cv::Scalar(230,130,255);\nconst auto BLUE = cv::Scalar(255,0,0);\nconst auto LIGHTBLUE = cv::Scalar(255,255,160);\nconst auto GREEN = cv::Scalar(0,255,0);\nconst auto IMAGE_SCALE = .25;\n\nclass MyData\n{\npublic:\n const cv::Mat original_image;\n cv::Mat image;\n MyData( auto _image ) : original_image(_image)\n {\n original_image.copyTo(image);\n }\n void reset() { original_image.copyTo(image); };\n void update(auto _newImage) { _newImage.copyTo(image); };\n\n};\n\nclass MyWindow\n{\nprotected:\n const string winName;\n MyData d;\n\npublic:\n \/* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; *\/\n MyWindow( auto _winName, auto _image ):\n winName( _winName ), d( _image )\n {\n cv::namedWindow( winName, WINDOW_AUTOSIZE );\n }\n virtual ~MyWindow();\n virtual void showImage();\n virtual void reset();\n};\n\nMyWindow::~MyWindow()\n{\n cv::destroyWindow( winName );\n}\n\nvoid MyWindow::reset()\n{\n d.reset();\n showImage();\n}\n\nvoid MyWindow::showImage()\n{\n cv::imshow( winName, d.image );\n}\n\nclass MyOperationWindow : public MyWindow\n{\nprotected:\n \/* virtual void setControls(){}; *\/\n virtual string getDescription() {}\npublic:\n MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) {}\n void apply( MyData& _d, std::vector<string>& _process_pile )\n {\n _d.update(d.image);\n _process_pile.push_back(getDescription());\n }\n};\n\nclass MyThreshold : public MyOperationWindow\n{\n int th;\npublic:\n MyThreshold( auto _winName, auto _image)\n : MyOperationWindow( _winName, _image ), th(125) { setControls(); };\n MyThreshold( auto _winName, auto _image, auto _th )\n : MyOperationWindow( _winName, _image ), th(_th) { setControls(); };\n static void thresholdCallback( int _th, void* ptr);\nprivate:\n string getDescription() override;\n void setControls(); \/\/\n void thresholdImage();\n void _thresholdCallback( int _th );\n};\n\nvoid MyThreshold::setControls() \/\/\n{\n const std::string bar_name = winName + \"_thBar\";\n cv::createTrackbar( bar_name, winName, &th, 255, MyThreshold::thresholdCallback );\n}\n\nvoid MyThreshold::thresholdCallback( int _th, void* ptr)\n{\n MyThreshold* that = (MyThreshold*) (ptr);\n that->_thresholdCallback(_th);\n}\n\nvoid MyThreshold::_thresholdCallback( int _th )\n{\n th = _th;\n thresholdImage();\n showImage();\n}\n\nstring MyThreshold::getDescription()\n{\n return \"th \" + std::to_string(th);\n}\n\nvoid MyThreshold::thresholdImage()\n{\n enum ThresholdType {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED,\n THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED };\n ThresholdType const threshold_type = BINARY;\n int const max_BINARY_value = 255;\n\n threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type );\n}\n\n\nclass MyApp : public MyWindow\n{\n vector<string> process;\n \/\/ std::unique_ptr<MyOperationWindow> current_operation;\n \/\/ MyOperationWindow* current_operation;\n string* current_operation;\npublic:\n MyApp( auto _winName, auto _image);\n\n void showImage();\n char option(auto _option);\n ~MyApp();\n};\n\nMyApp::~MyApp()\n{\n if (current_operation != nullptr)\n delete(current_operation);\n cv::destroyWindow( winName );\n}\n\nstatic void help()\n{\n cout << \"L (or a) - list image transformations\\n\"\n << \"R (or s) - restore original image\\n\"\n << \"t (or d) - activate threshold window\\n\"\n << \"r (or f) - reset the operation window\\n\"\n << \"(enter) (or g) - accept changes and kill the operation window\\n\"\n << \"(backspace) (or h)- ignore changes and kill the operation window\\n\"\n << endl;\n}\n\nMyApp::MyApp(auto _winName,auto _image) :\n MyWindow( _winName, _image ),\n current_operation(nullptr) {}\n\nchar MyApp::option( auto _option )\n{\n switch(_option)\n {\n case 't': case 'd':\n \/\/\/ create the threshold window\n if (current_operation == nullptr)\n current_operation = new string(\"Hi\");\n \/\/current_operation = new MyThreshold(\"theshold\", d.image);\n break;\n case 'R': case 's':\n \/\/\/ reset the whole application\n reset();\n case 'r': case 'f':\n \/\/\/ reset the threshold window\n if (current_operation != nullptr)\n std::cout << \"option r says ...\" << current_operation << std::endl;\n \/\/ current_operation->reset();\n break;\n }\n return _option;\n}\n\n\nconst char* keys =\n{\n \"{help h||}{@image|..\/..\/testdata\/A\/A05_38.bmp|input image file}\"\n};\n\n\nint main( int argc, const char** argv )\n{\n cv::CommandLineParser parser(argc, argv, keys);\n if (parser.has(\"help\"))\n {\n help();\n return 0;\n }\n std::string inputImage = parser.get<string>(0);\n\n \/\/ Load the source image. HighGUI use.\n cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE );\n if(image.empty())\n {\n std::cerr << \"Cannot read image file: \" << inputImage << std::endl;\n return -1;\n }\n\n \/\/ TODO: check size and reduce it only if needed\n cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);\n help();\n\n \/\/\/ Create the GUI\n std::string winName = \"main window\";\n MyApp appHandle = MyApp(winName, image);\n\n \/\/\/ Loop until the user kills the program\n const auto ESC_KEY = '\\x1b';\n while ( appHandle.option((char) waitKey(0)) != ESC_KEY )\n {\n \/* until ESC *\/\n }\n std::cout << \"Exit\" << std::endl;\n return 0;\n}\n\n\n<commit_msg>bug found virtual method was not implemented<commit_after>#include \"opencv2\/core\/utility.hpp\"\n#include \"opencv2\/imgproc.hpp\"\n#include \"opencv2\/imgcodecs.hpp\"\n#include \"opencv2\/highgui.hpp\"\n\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\n\nconst auto RED = cv::Scalar(0,0,255);\nconst auto PINK = cv::Scalar(230,130,255);\nconst auto BLUE = cv::Scalar(255,0,0);\nconst auto LIGHTBLUE = cv::Scalar(255,255,160);\nconst auto GREEN = cv::Scalar(0,255,0);\nconst auto IMAGE_SCALE = .25;\n\nclass MyData\n{\npublic:\n const cv::Mat& original_image;\n cv::Mat image;\n MyData(const cv::Mat& _image ) : original_image(_image)\n {\n original_image.copyTo(image);\n }\n void reset() { original_image.copyTo(image); };\n void update(auto _newImage) { _newImage.copyTo(image); };\n\n};\n\nclass MyWindow\n{\nprotected:\n const string winName;\n MyData d;\n\npublic:\n \/* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; *\/\n MyWindow( const string& _winName, const cv::Mat& _image ):\n winName( _winName ), d( _image )\n {\n cv::namedWindow( winName, WINDOW_AUTOSIZE );\n }\n virtual ~MyWindow();\n virtual void showImage();\n virtual void reset();\n};\n\nMyWindow::~MyWindow()\n{\n cv::destroyWindow( winName );\n}\n\nvoid MyWindow::reset()\n{\n d.reset();\n showImage();\n}\n\nvoid MyWindow::showImage()\n{\n cv::imshow( winName, d.image );\n}\n\nclass MyOperationWindow : public MyWindow\n{\nprotected:\n \/* virtual void setControls(){}; *\/\n virtual string getDescription() {}\npublic:\n MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) {}\n void apply( MyData& _d, std::vector<string>& _process_pile )\n {\n _d.update(d.image);\n _process_pile.push_back(getDescription());\n }\n};\n\nclass MyThreshold : public MyOperationWindow\n{\n int th;\npublic:\n MyThreshold( auto _winName, auto _image)\n : MyOperationWindow( _winName, _image ), th(125) { setControls(); }\n MyThreshold( auto _winName, auto _image, auto _th )\n : MyOperationWindow( _winName, _image ), th(_th) { setControls(); }\n static void thresholdCallback( int _th, void* ptr);\nprivate:\n string getDescription() override;\n void setControls(); \/\/\n void thresholdImage();\n void _thresholdCallback( int _th );\n};\n\nvoid MyThreshold::setControls() \/\/\n{\n const std::string bar_name = winName + \"_thBar\";\n cv::createTrackbar( bar_name, winName, &th, 255, MyThreshold::thresholdCallback );\n}\n\nvoid MyThreshold::thresholdCallback( int _th, void* ptr)\n{\n MyThreshold* that = (MyThreshold*) (ptr);\n that->_thresholdCallback(_th);\n}\n\nvoid MyThreshold::_thresholdCallback( int _th )\n{\n th = _th;\n thresholdImage();\n showImage();\n}\n\nstring MyThreshold::getDescription()\n{\n return \"th \" + std::to_string(th);\n}\n\nvoid MyThreshold::thresholdImage()\n{\n enum ThresholdType {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED,\n THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED };\n ThresholdType const threshold_type = BINARY;\n int const max_BINARY_value = 255;\n\n threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type );\n}\n\n\nclass MyApp : public MyWindow\n{\n vector<string> process;\n \/\/ std::unique_ptr<MyOperationWindow> current_operation;\n \/\/ MyOperationWindow* current_operation;\n string* current_operation;\npublic:\n MyApp(const std::string& _winName, const cv::Mat& _image);\n\n \/\/void showImage() {}\n char option(char _option);\n ~MyApp();\n};\n\nMyApp::~MyApp()\n{\n if (current_operation != nullptr)\n delete(current_operation);\n \/\/cv::destroyWindow( winName );\n}\n\nMyApp::MyApp(const string &_winName, const Mat &_image) :\n MyWindow( _winName, _image ),\n current_operation(nullptr) {}\n\nchar MyApp::option( char _option )\n{\n switch(_option)\n {\n case 't': case 'd':\n \/\/\/ create the threshold window\n if (current_operation == nullptr)\n current_operation = new string(\"Hi\");\n \/\/current_operation = new MyThreshold(\"theshold\", d.image);\n break;\n case 'R': case 's':\n \/\/\/ reset the whole application\n \/\/reset();\n case 'r': case 'f':\n \/\/\/ reset the threshold window\n if (current_operation != nullptr)\n std::cout << \"option r says ...\" << current_operation << std::endl;\n \/\/ current_operation->reset();\n break;\n }\n return _option;\n}\n\n\nconst char* keys =\n{\n \"{help h||}{@image|..\/..\/testdata\/A\/A05_38.bmp|input image file}\"\n};\n\n\nstatic void help();\n\nint main( int argc, const char** argv )\n{\n cv::CommandLineParser parser(argc, argv, keys);\n if (parser.has(\"help\"))\n {\n help();\n return 0;\n }\n std::string inputImage = parser.get<string>(0);\n\n \/\/ Load the source image. HighGUI use.\n cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE );\n if(image.empty())\n {\n std::cerr << \"Cannot read image file: \" << inputImage << std::endl;\n return -1;\n }\n\n \/\/ TODO: check size and reduce it only if needed\n cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);\n help();\n\n \/\/\/ Create the GUI\n std::string winName = \"main window\";\n MyApp appHandle = MyApp(winName, image);\n\n \/\/\/ Loop until the user kills the program\n const auto ESC_KEY = '\\x1b';\n while ( appHandle.option((char) waitKey(0)) != ESC_KEY )\n {\n \/* until ESC *\/\n }\n std::cout << \"Exit\" << std::endl;\n return 0;\n}\n\n\nstatic void help()\n{\n cout << \"L (or a) - list image transformations\\n\"\n << \"R (or s) - restore original image\\n\"\n << \"t (or d) - activate threshold window\\n\"\n << \"r (or f) - reset the operation window\\n\"\n << \"(enter) (or g) - accept changes and kill the operation window\\n\"\n << \"(backspace) (or h)- ignore changes and kill the operation window\\n\"\n << endl;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS dba30 (1.18.6); FILE MERGED 2006\/07\/19 10:25:04 fs 1.18.6.4: RESYNC: (1.20-1.21); FILE MERGED 2006\/04\/18 13:10:17 oj 1.18.6.3: RESYNC: (1.19-1.20); FILE MERGED 2005\/09\/28 12:11:44 fs 1.18.6.2: RESYNC: (1.18-1.19); FILE MERGED 2005\/04\/06 07:10:24 fs 1.18.6.1: #i46768# some assertions on the type of connection properties<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: htmlimp.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 10:49:39 $\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#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------------\n\n#include \"scitems.hxx\"\n#include <svx\/eeitem.hxx>\n#define ITEMID_FIELD EE_FEATURE_FIELD\n\n#include <svx\/lrspitem.hxx>\n#include <svx\/paperinf.hxx>\n#include <svx\/sizeitem.hxx>\n#include <svx\/ulspitem.hxx>\n#include <svx\/boxitem.hxx>\n#include <vcl\/svapp.hxx>\n\n#include \"htmlimp.hxx\"\n#include \"htmlpars.hxx\"\n#include \"filter.hxx\"\n#include \"global.hxx\"\n#include \"document.hxx\"\n#include \"editutil.hxx\"\n#include \"stlpool.hxx\"\n#include \"stlsheet.hxx\"\n#include \"compiler.hxx\"\n#include \"rangenam.hxx\"\n#include \"attrib.hxx\"\n#include \"ftools.hxx\"\n\n\n\/\/------------------------------------------------------------------------\n\nFltError ScImportHTML( SvStream &rStream, ScDocument *pDoc,\n ScRange& rRange, double nOutputFactor, BOOL bCalcWidthHeight )\n{\n ScHTMLImport aImp( pDoc, rRange, bCalcWidthHeight );\n FltError nErr = (FltError) aImp.Read( rStream );\n ScRange aR = aImp.GetRange();\n rRange.aEnd = aR.aEnd;\n aImp.WriteToDocument( TRUE, nOutputFactor );\n return nErr;\n}\n\n\nScHTMLImport::ScHTMLImport( ScDocument* pDocP, const ScRange& rRange, BOOL bCalcWidthHeight ) :\n ScEEImport( pDocP, rRange )\n{\n Size aPageSize;\n OutputDevice* pDefaultDev = Application::GetDefaultDevice();\n const String& aPageStyle = pDoc->GetPageStyle( rRange.aStart.Tab() );\n ScStyleSheet* pStyleSheet = (ScStyleSheet*)pDoc->\n GetStyleSheetPool()->Find( aPageStyle, SFX_STYLE_FAMILY_PAGE );\n if ( pStyleSheet )\n {\n const SfxItemSet& rSet = pStyleSheet->GetItemSet();\n const SvxLRSpaceItem* pLRItem = (const SvxLRSpaceItem*) &rSet.Get( ATTR_LRSPACE );\n long nLeftMargin = pLRItem->GetLeft();\n long nRightMargin = pLRItem->GetRight();\n const SvxULSpaceItem* pULItem = (const SvxULSpaceItem*) &rSet.Get( ATTR_ULSPACE );\n long nTopMargin = pULItem->GetUpper();\n long nBottomMargin = pULItem->GetLower();\n aPageSize = ((const SvxSizeItem&) rSet.Get(ATTR_PAGE_SIZE)).GetSize();\n if ( !aPageSize.Width() || !aPageSize.Height() )\n {\n DBG_ERRORFILE(\"PageSize Null ?!?!?\");\n aPageSize = SvxPaperInfo::GetPaperSize( SVX_PAPER_A4 );\n }\n aPageSize.Width() -= nLeftMargin + nRightMargin;\n aPageSize.Height() -= nTopMargin + nBottomMargin;\n aPageSize = pDefaultDev->LogicToPixel( aPageSize, MapMode( MAP_TWIP ) );\n }\n else\n {\n DBG_ERRORFILE(\"kein StyleSheet?!?\");\n aPageSize = pDefaultDev->LogicToPixel(\n SvxPaperInfo::GetPaperSize( SVX_PAPER_A4 ), MapMode( MAP_TWIP ) );\n }\n if( bCalcWidthHeight )\n pParser = new ScHTMLLayoutParser( pEngine, aPageSize, pDocP );\n else\n pParser = new ScHTMLQueryParser( pEngine, pDocP );\n}\n\n\nScHTMLImport::~ScHTMLImport()\n{\n \/\/ Reihenfolge wichtig, sonst knallt's irgendwann irgendwo in irgendeinem Dtor!\n \/\/ Ist gewaehrleistet, da ScEEImport Basisklasse ist\n delete (ScHTMLParser*) pParser; \/\/ vor EditEngine!\n}\n\n\nvoid ScHTMLImport::InsertRangeName( ScDocument* pDoc, const String& rName, const ScRange& rRange )\n{\n ComplRefData aRefData;\n aRefData.InitRange( rRange );\n ScTokenArray aTokArray;\n aTokArray.AddDoubleReference( aRefData );\n ScRangeData* pRangeData = new ScRangeData( pDoc, rName, aTokArray );\n if( !pDoc->GetRangeName()->Insert( pRangeData ) )\n delete pRangeData;\n}\n\nvoid ScHTMLImport::WriteToDocument( BOOL bSizeColsRows, double nOutputFactor )\n{\n ScEEImport::WriteToDocument( bSizeColsRows, nOutputFactor );\n\n const ScHTMLParser* pParser = GetParser();\n const ScHTMLTable* pGlobTable = pParser->GetGlobalTable();\n if( !pGlobTable )\n return;\n\n \/\/ set cell borders for HTML table cells\n pGlobTable->ApplyCellBorders( pDoc, aRange.aStart );\n\n \/\/ correct cell borders for merged cells\n for ( ScEEParseEntry* pEntry = pParser->First(); pEntry; pEntry = pParser->Next() )\n {\n if( (pEntry->nColOverlap > 1) || (pEntry->nRowOverlap > 1) )\n {\n SCTAB nTab = aRange.aStart.Tab();\n const ScMergeAttr* pItem = (ScMergeAttr*) pDoc->GetAttr( pEntry->nCol, pEntry->nRow, nTab, ATTR_MERGE );\n if( pItem->IsMerged() )\n {\n SCCOL nColMerge = pItem->GetColMerge();\n SCROW nRowMerge = pItem->GetRowMerge();\n\n const SvxBoxItem* pToItem = (const SvxBoxItem*)\n pDoc->GetAttr( pEntry->nCol, pEntry->nRow, nTab, ATTR_BORDER );\n SvxBoxItem aNewItem( *pToItem );\n if( nColMerge > 1 )\n {\n const SvxBoxItem* pFromItem = (const SvxBoxItem*)\n pDoc->GetAttr( pEntry->nCol + nColMerge - 1, pEntry->nRow, nTab, ATTR_BORDER );\n aNewItem.SetLine( pFromItem->GetLine( BOX_LINE_RIGHT ), BOX_LINE_RIGHT );\n }\n if( nRowMerge > 1 )\n {\n const SvxBoxItem* pFromItem = (const SvxBoxItem*)\n pDoc->GetAttr( pEntry->nCol, pEntry->nRow + nRowMerge - 1, nTab, ATTR_BORDER );\n aNewItem.SetLine( pFromItem->GetLine( BOX_LINE_BOTTOM ), BOX_LINE_BOTTOM );\n }\n pDoc->ApplyAttr( pEntry->nCol, pEntry->nRow, nTab, aNewItem );\n }\n }\n }\n\n \/\/ create ranges for HTML tables\n \/\/ 1 - entire document\n ScRange aNewRange( aRange.aStart );\n aNewRange.aEnd.IncCol( static_cast<SCsCOL>(pGlobTable->GetDocSize( tdCol )) - 1 );\n aNewRange.aEnd.IncRow( pGlobTable->GetDocSize( tdRow ) - 1 );\n InsertRangeName( pDoc, ScfTools::GetHTMLDocName(), aNewRange );\n\n \/\/ 2 - all tables\n InsertRangeName( pDoc, ScfTools::GetHTMLTablesName(), ScRange( aRange.aStart ) );\n\n \/\/ 3 - single tables\n SCsCOL nColDiff = (SCsCOL)aRange.aStart.Col();\n SCsROW nRowDiff = (SCsROW)aRange.aStart.Row();\n SCsTAB nTabDiff = (SCsTAB)aRange.aStart.Tab();\n\n ScHTMLTable* pTable = NULL;\n ScHTMLTableId nTableId = SC_HTML_GLOBAL_TABLE;\n while( pTable = pGlobTable->FindNestedTable( ++nTableId ) )\n {\n pTable->GetDocRange( aNewRange );\n aNewRange.Move( nColDiff, nRowDiff, nTabDiff );\n \/\/ insert table number as name\n InsertRangeName( pDoc, ScfTools::GetNameFromHTMLIndex( nTableId ), aNewRange );\n \/\/ insert table id as name\n if( pTable->GetTableName().Len() )\n {\n String aName( ScfTools::GetNameFromHTMLName( pTable->GetTableName() ) );\n USHORT nPos;\n if( !pDoc->GetRangeName()->SearchName( aName, nPos ) )\n InsertRangeName( pDoc, aName, aNewRange );\n }\n }\n}\n\nString ScHTMLImport::GetHTMLRangeNameList( ScDocument* pDoc, const String& rOrigName )\n{\n DBG_ASSERT( pDoc, \"ScHTMLImport::GetHTMLRangeNameList - missing document\" );\n\n String aNewName;\n ScRangeName* pRangeNames = pDoc->GetRangeName();\n ScRangeList aRangeList;\n xub_StrLen nTokenCnt = rOrigName.GetTokenCount( ';' );\n xub_StrLen nStringIx = 0;\n for( xub_StrLen nToken = 0; nToken < nTokenCnt; nToken++ )\n {\n String aToken( rOrigName.GetToken( 0, ';', nStringIx ) );\n if( pRangeNames && ScfTools::IsHTMLTablesName( aToken ) )\n { \/\/ build list with all HTML tables\n ULONG nIndex = 1;\n USHORT nPos;\n BOOL bLoop = TRUE;\n while( bLoop )\n {\n aToken = ScfTools::GetNameFromHTMLIndex( nIndex++ );\n bLoop = pRangeNames->SearchName( aToken, nPos );\n if( bLoop )\n {\n const ScRangeData* pRangeData = (*pRangeNames)[ nPos ];\n ScRange aRange;\n if( pRangeData && pRangeData->IsReference( aRange ) && !aRangeList.In( aRange ) )\n {\n ScGlobal::AddToken( aNewName, aToken, ';' );\n aRangeList.Append( aRange );\n }\n }\n }\n }\n else\n ScGlobal::AddToken( aNewName, aToken, ';' );\n }\n return aNewName;\n}\n\n<commit_msg>INTEGRATION: CWS sb19 (1.12.132); FILE MERGED 2004\/10\/27 07:31:48 mba 1.12.132.1: #110407#: remove static BaseURL<commit_after>\/*************************************************************************\n *\n * $RCSfile: htmlimp.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2005-01-11 13:17:31 $\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#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------------\n\n#include \"scitems.hxx\"\n#include <svx\/eeitem.hxx>\n#define ITEMID_FIELD EE_FEATURE_FIELD\n\n#include <svx\/lrspitem.hxx>\n#include <svx\/paperinf.hxx>\n#include <svx\/sizeitem.hxx>\n#include <svx\/ulspitem.hxx>\n#include <svx\/boxitem.hxx>\n#include <vcl\/svapp.hxx>\n\n#include \"htmlimp.hxx\"\n#include \"htmlpars.hxx\"\n#include \"filter.hxx\"\n#include \"global.hxx\"\n#include \"document.hxx\"\n#include \"editutil.hxx\"\n#include \"stlpool.hxx\"\n#include \"stlsheet.hxx\"\n#include \"compiler.hxx\"\n#include \"rangenam.hxx\"\n#include \"attrib.hxx\"\n#include \"ftools.hxx\"\n\n\n\/\/------------------------------------------------------------------------\n\nFltError ScImportHTML( SvStream &rStream, const String& rBaseURL, ScDocument *pDoc,\n ScRange& rRange, double nOutputFactor, BOOL bCalcWidthHeight )\n{\n ScHTMLImport aImp( pDoc, rBaseURL, rRange, bCalcWidthHeight );\n FltError nErr = (FltError) aImp.Read( rStream, rBaseURL );\n ScRange aR = aImp.GetRange();\n rRange.aEnd = aR.aEnd;\n aImp.WriteToDocument( TRUE, nOutputFactor );\n return nErr;\n}\n\n\nScHTMLImport::ScHTMLImport( ScDocument* pDocP, const String& rBaseURL, const ScRange& rRange, BOOL bCalcWidthHeight ) :\n ScEEImport( pDocP, rRange )\n{\n Size aPageSize;\n OutputDevice* pDefaultDev = Application::GetDefaultDevice();\n const String& aPageStyle = pDoc->GetPageStyle( rRange.aStart.Tab() );\n ScStyleSheet* pStyleSheet = (ScStyleSheet*)pDoc->\n GetStyleSheetPool()->Find( aPageStyle, SFX_STYLE_FAMILY_PAGE );\n if ( pStyleSheet )\n {\n const SfxItemSet& rSet = pStyleSheet->GetItemSet();\n const SvxLRSpaceItem* pLRItem = (const SvxLRSpaceItem*) &rSet.Get( ATTR_LRSPACE );\n long nLeftMargin = pLRItem->GetLeft();\n long nRightMargin = pLRItem->GetRight();\n const SvxULSpaceItem* pULItem = (const SvxULSpaceItem*) &rSet.Get( ATTR_ULSPACE );\n long nTopMargin = pULItem->GetUpper();\n long nBottomMargin = pULItem->GetLower();\n aPageSize = ((const SvxSizeItem&) rSet.Get(ATTR_PAGE_SIZE)).GetSize();\n if ( !aPageSize.Width() || !aPageSize.Height() )\n {\n DBG_ERRORFILE(\"PageSize Null ?!?!?\");\n aPageSize = SvxPaperInfo::GetPaperSize( SVX_PAPER_A4 );\n }\n aPageSize.Width() -= nLeftMargin + nRightMargin;\n aPageSize.Height() -= nTopMargin + nBottomMargin;\n aPageSize = pDefaultDev->LogicToPixel( aPageSize, MapMode( MAP_TWIP ) );\n }\n else\n {\n DBG_ERRORFILE(\"kein StyleSheet?!?\");\n aPageSize = pDefaultDev->LogicToPixel(\n SvxPaperInfo::GetPaperSize( SVX_PAPER_A4 ), MapMode( MAP_TWIP ) );\n }\n if( bCalcWidthHeight )\n pParser = new ScHTMLLayoutParser( pEngine, rBaseURL, aPageSize, pDocP );\n else\n pParser = new ScHTMLQueryParser( pEngine, pDocP );\n}\n\n\nScHTMLImport::~ScHTMLImport()\n{\n \/\/ Reihenfolge wichtig, sonst knallt's irgendwann irgendwo in irgendeinem Dtor!\n \/\/ Ist gewaehrleistet, da ScEEImport Basisklasse ist\n delete (ScHTMLParser*) pParser; \/\/ vor EditEngine!\n}\n\n\nvoid ScHTMLImport::InsertRangeName( ScDocument* pDoc, const String& rName, const ScRange& rRange )\n{\n ComplRefData aRefData;\n aRefData.InitRange( rRange );\n ScTokenArray aTokArray;\n aTokArray.AddDoubleReference( aRefData );\n ScRangeData* pRangeData = new ScRangeData( pDoc, rName, aTokArray );\n if( !pDoc->GetRangeName()->Insert( pRangeData ) )\n delete pRangeData;\n}\n\nvoid ScHTMLImport::WriteToDocument( BOOL bSizeColsRows, double nOutputFactor )\n{\n ScEEImport::WriteToDocument( bSizeColsRows, nOutputFactor );\n\n const ScHTMLParser* pParser = GetParser();\n const ScHTMLTable* pGlobTable = pParser->GetGlobalTable();\n if( !pGlobTable )\n return;\n\n \/\/ set cell borders for HTML table cells\n pGlobTable->ApplyCellBorders( pDoc, aRange.aStart );\n\n \/\/ correct cell borders for merged cells\n for ( ScEEParseEntry* pEntry = pParser->First(); pEntry; pEntry = pParser->Next() )\n {\n if( (pEntry->nColOverlap > 1) || (pEntry->nRowOverlap > 1) )\n {\n SCTAB nTab = aRange.aStart.Tab();\n const ScMergeAttr* pItem = (ScMergeAttr*) pDoc->GetAttr( pEntry->nCol, pEntry->nRow, nTab, ATTR_MERGE );\n if( pItem->IsMerged() )\n {\n SCCOL nColMerge = pItem->GetColMerge();\n SCROW nRowMerge = pItem->GetRowMerge();\n\n const SvxBoxItem* pToItem = (const SvxBoxItem*)\n pDoc->GetAttr( pEntry->nCol, pEntry->nRow, nTab, ATTR_BORDER );\n SvxBoxItem aNewItem( *pToItem );\n if( nColMerge > 1 )\n {\n const SvxBoxItem* pFromItem = (const SvxBoxItem*)\n pDoc->GetAttr( pEntry->nCol + nColMerge - 1, pEntry->nRow, nTab, ATTR_BORDER );\n aNewItem.SetLine( pFromItem->GetLine( BOX_LINE_RIGHT ), BOX_LINE_RIGHT );\n }\n if( nRowMerge > 1 )\n {\n const SvxBoxItem* pFromItem = (const SvxBoxItem*)\n pDoc->GetAttr( pEntry->nCol, pEntry->nRow + nRowMerge - 1, nTab, ATTR_BORDER );\n aNewItem.SetLine( pFromItem->GetLine( BOX_LINE_BOTTOM ), BOX_LINE_BOTTOM );\n }\n pDoc->ApplyAttr( pEntry->nCol, pEntry->nRow, nTab, aNewItem );\n }\n }\n }\n\n \/\/ create ranges for HTML tables\n \/\/ 1 - entire document\n ScRange aNewRange( aRange.aStart );\n aNewRange.aEnd.IncCol( static_cast<SCsCOL>(pGlobTable->GetDocSize( tdCol )) - 1 );\n aNewRange.aEnd.IncRow( pGlobTable->GetDocSize( tdRow ) - 1 );\n InsertRangeName( pDoc, ScfTools::GetHTMLDocName(), aNewRange );\n\n \/\/ 2 - all tables\n InsertRangeName( pDoc, ScfTools::GetHTMLTablesName(), ScRange( aRange.aStart ) );\n\n \/\/ 3 - single tables\n SCsCOL nColDiff = (SCsCOL)aRange.aStart.Col();\n SCsROW nRowDiff = (SCsROW)aRange.aStart.Row();\n SCsTAB nTabDiff = (SCsTAB)aRange.aStart.Tab();\n\n ScHTMLTable* pTable = NULL;\n ScHTMLTableId nTableId = SC_HTML_GLOBAL_TABLE;\n while( pTable = pGlobTable->FindNestedTable( ++nTableId ) )\n {\n pTable->GetDocRange( aNewRange );\n aNewRange.Move( nColDiff, nRowDiff, nTabDiff );\n \/\/ insert table number as name\n InsertRangeName( pDoc, ScfTools::GetNameFromHTMLIndex( nTableId ), aNewRange );\n \/\/ insert table id as name\n if( pTable->GetTableName().Len() )\n {\n String aName( ScfTools::GetNameFromHTMLName( pTable->GetTableName() ) );\n USHORT nPos;\n if( !pDoc->GetRangeName()->SearchName( aName, nPos ) )\n InsertRangeName( pDoc, aName, aNewRange );\n }\n }\n}\n\nString ScHTMLImport::GetHTMLRangeNameList( ScDocument* pDoc, const String& rOrigName )\n{\n DBG_ASSERT( pDoc, \"ScHTMLImport::GetHTMLRangeNameList - missing document\" );\n\n String aNewName;\n ScRangeName* pRangeNames = pDoc->GetRangeName();\n ScRangeList aRangeList;\n xub_StrLen nTokenCnt = rOrigName.GetTokenCount( ';' );\n xub_StrLen nStringIx = 0;\n for( xub_StrLen nToken = 0; nToken < nTokenCnt; nToken++ )\n {\n String aToken( rOrigName.GetToken( 0, ';', nStringIx ) );\n if( pRangeNames && ScfTools::IsHTMLTablesName( aToken ) )\n { \/\/ build list with all HTML tables\n ULONG nIndex = 1;\n USHORT nPos;\n BOOL bLoop = TRUE;\n while( bLoop )\n {\n aToken = ScfTools::GetNameFromHTMLIndex( nIndex++ );\n bLoop = pRangeNames->SearchName( aToken, nPos );\n if( bLoop )\n {\n const ScRangeData* pRangeData = (*pRangeNames)[ nPos ];\n ScRange aRange;\n if( pRangeData && pRangeData->IsReference( aRange ) && !aRangeList.In( aRange ) )\n {\n ScGlobal::AddToken( aNewName, aToken, ';' );\n aRangeList.Append( aRange );\n }\n }\n }\n }\n else\n ScGlobal::AddToken( aNewName, aToken, ';' );\n }\n return aNewName;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix for texture Upload()<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: xerecord.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2004-09-08 15:45:11 $\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_XERECORD_HXX\n#define SC_XERECORD_HXX\n\n#ifndef SC_XLCONST_HXX\n#include \"xlconst.hxx\"\n#endif\n#ifndef SC_XESTREAM_HXX\n#include \"xestream.hxx\"\n#endif\n\n\/\/ Base classes to export Excel records =======================================\n\n\/** Base class for all Excel records.\n\n Derive from this class to implement any functionality performed during\n saving the records - except really writing a record (i.e. write a list of\n records contained in the class). Derive from XclExpRecord (instead from\n this class) to write common records.\n *\/\nclass XclExpRecordBase\n{\npublic:\n virtual ~XclExpRecordBase();\n\n \/** Overwrite this method to do any operation while saving the record. *\/\n virtual void Save( XclExpStream& rStrm );\n\n \/** Calls Save(XclExpStream&) nCount times. *\/\n void SaveRepeated( XclExpStream& rStrm, sal_uInt32 nCount );\n};\n\ntypedef ScfRef< XclExpRecordBase > XclExpRecordRef;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Base class for single records with any content.\n\n This class handles writing the record header. Derived classes only have to\n write the record body. Calculating the record size before saving optimizes\n the write process (the stream does not have to seek back and update the\n written record size). But it is not required to calculate a valid size\n (maybe it would be too complex or just impossible until the record is\n really written).\n *\/\nclass XclExpRecord : public XclExpRecordBase\n{\npublic:\n \/** @param nRecId The record ID of this record. May be set later with SetRecId().\n @param nRecSize The predicted record size. May be set later with SetRecSize(). *\/\n explicit XclExpRecord(\n sal_uInt16 nRecId = EXC_ID_UNKNOWN,\n sal_uInt32 nRecSize = 0 );\n\n virtual ~XclExpRecord();\n\n \/** Returns the current record ID. *\/\n inline sal_uInt16 GetRecId() const { return mnRecId; }\n \/** Returns the current record size prediction. *\/\n inline sal_uInt32 GetRecSize() const { return mnRecSize; }\n\n \/** Sets a new record ID. *\/\n inline void SetRecId( sal_uInt16 nRecId ) { mnRecId = nRecId; }\n \/** Sets a new record size prediction. *\/\n inline void SetRecSize( sal_uInt32 nRecSize ) { mnRecSize = nRecSize; }\n \/** Sets record ID and size with one call. *\/\n void SetRecHeader( sal_uInt16 nRecId, sal_uInt32 nRecSize );\n\n \/** Writes the record header and calls WriteBody(). *\/\n virtual void Save( XclExpStream& rStrm );\n\nprivate:\n \/** Writes the body of the record (without record header).\n @descr Usually this method will be overwritten by derived classes. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n sal_uInt32 mnRecSize; \/\/\/ The predicted record size.\n sal_uInt16 mnRecId; \/\/\/ The record ID.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record without body. Only the record ID and the size 0 will be written. *\/\nclass XclExpEmptyRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record. *\/\n inline explicit XclExpEmptyRecord( sal_uInt16 nRecId );\n};\n\ninline XclExpEmptyRecord::XclExpEmptyRecord( sal_uInt16 nRecId ) :\n XclExpRecord( nRecId, 0 )\n{\n}\n\n\/\/ ============================================================================\n\n\/** A record with a single value of type Type.\n @descr Requires operator<<( XclExpStream&, const Type& ). *\/\ntemplate< typename Type >\nclass XclExpValueRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param rValue The value for the record body.\n @param nSize Record size. Uses sizeof( Type ), if this parameter is omitted. *\/\n inline explicit XclExpValueRecord(\n sal_uInt16 nRecId,\n const Type& rValue,\n sal_uInt32 nSize = sizeof( Type ) );\n\n \/** Returns the value of the record. *\/\n inline const Type& GetValue() const { return maValue; }\n \/** Sets a new record value. *\/\n inline void SetValue( const Type& rValue ) { maValue = rValue; }\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n Type maValue; \/\/\/ The record data.\n};\n\ntemplate< typename Type >\ninline XclExpValueRecord< Type >::XclExpValueRecord( sal_uInt16 nRecId, const Type& rValue, sal_uInt32 nSize ) :\n XclExpRecord( nRecId, nSize ),\n maValue( rValue )\n{\n}\n\ntemplate< typename Type >\nvoid XclExpValueRecord< Type >::WriteBody( XclExpStream& rStrm )\n{\n rStrm << maValue;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record containing an unsigned 16-bit value. *\/\ntypedef XclExpValueRecord< sal_uInt16 > XclExpUInt16Record;\n\n\/** A record containing an unsigned 32-bit value. *\/\ntypedef XclExpValueRecord< sal_uInt32 > XclExpUInt32Record;\n\n\/** A record containing a double value. *\/\ntypedef XclExpValueRecord< double > XclExpDoubleRecord;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Record which contains a Boolean value.\n @descr The value is stored as 16-bit value: 0x0000 = FALSE, 0x0001 = TRUE. *\/\nclass XclExpBoolRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param nValue The value for the record body. *\/\n inline explicit XclExpBoolRecord( sal_uInt16 nRecId, bool bValue ) :\n XclExpRecord( nRecId, 2 ), mbValue( bValue ) {}\n\n \/** Returns the Boolean value of the record. *\/\n inline bool GetBool() const { return mbValue; }\n \/** Sets a new Boolean record value. *\/\n inline void SetBool( bool bValue ) { mbValue = bValue; }\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n bool mbValue; \/\/\/ The record data.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Record which exports a memory data array. *\/\nclass XclExpDummyRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param pRecData Pointer to the data array representing the record body.\n @param nRecSize Size of the data array. *\/\n explicit XclExpDummyRecord(\n sal_uInt16 nRecId, const void* pRecData, sal_uInt32 nRecSize );\n\n \/** Sets a data array. *\/\n void SetData( const void* pRecData, sal_uInt32 nRecSize );\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n const void* mpData; \/\/\/ The record data.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record that stores a reference to an existing record object.\n\n The record object does not take ownership of the passed record. This class\n should be used to insert an existing record into another record list. This\n prevents that the list takes ownership of the passed record.\n *\/\nclass XclExpRefRecord : public XclExpRecordBase\n{\npublic:\n inline explicit XclExpRefRecord( XclExpRecordBase& rRec ) : mrRec( rRec ) {}\n\n \/** Writes the entire record. *\/\n virtual void Save( XclExpStream& rStrm );\n\nprotected:\n XclExpRecordBase& mrRec; \/\/\/ Reference to the record.\n};\n\n\/\/ List of records ============================================================\n\n\/** A list of Excel record objects.\n\n Provides saving the compete list. This class is derived from\n XclExpRecordBase, so it can be used as record in another record list.\n Requires RecType::Save( XclExpStream& ).\n *\/\ntemplate< typename RecType = XclExpRecordBase >\nclass XclExpRecordList : public XclExpRecordBase\n{\npublic:\n typedef ScfRef< RecType > RecordRefType;\n\n \/** Returns pointer to an existing record or 0 on error. *\/\n inline bool Empty() const { return maRecs.empty(); }\n \/** Returns pointer to an existing record or 0 on error. *\/\n inline size_t Size() const { return maRecs.size(); }\n\n \/** Returns reference to an existing record or empty reference on error. *\/\n inline const RecordRefType GetRecord( size_t nPos ) const\n { return (nPos < maRecs.size()) ? maRecs[ nPos ] : RecordRefType(); }\n \/** Returns reference to an existing record or empty reference on error. *\/\n inline RecordRefType GetRecord( size_t nPos )\n { return (nPos < maRecs.size()) ? maRecs[ nPos ] : RecordRefType(); }\n\n \/** Returns reference to the last existing record or empty reference, if list is empty. *\/\n inline const RecordRefType GetLastRecord() const\n { return maRecs.empty() ? RecordRefType() : maRecs.back(); }\n \/** Returns reference to the last existing record or empty reference, if list is empty. *\/\n inline RecordRefType GetLastRecord()\n { return maRecs.empty() ? RecordRefType() : maRecs.back(); }\n\n \/** Inserts a new record at the specified position into the list. *\/\n inline void InsertRecord( RecordRefType xRec, size_t nPos )\n { if( xRec.get() ) maRecs.insert( maRecs.begin() + ::std::min( nPos, maRecs.size() ), xRec ); }\n \/** Appends a new record to the list. *\/\n inline void AppendRecord( RecordRefType xRec )\n { if( xRec.get() ) maRecs.push_back( xRec ); }\n\n \/** Removes the record at the specified position from the list. *\/\n inline void RemoveRecord( size_t nPos )\n { if( nPos < maRecs.size() ) maRecs.erase( maRecs.begin() + nPos ); }\n \/** Removes all records from the list. *\/\n inline void RemoveAllRecords() { maRecs.clear(); }\n\n \/** Replaces the record at the specified position from the list with the passed record. *\/\n inline void ReplaceRecord( RecordRefType xRec, size_t nPos )\n { RemoveRecord( nPos ); InsertRecord( xRec, nPos ); }\n\n \/** Writes the complete record list. *\/\n virtual void Save( XclExpStream& rStrm );\n\nprivate:\n typedef ::std::vector< RecordRefType > RecordVec;\n RecordVec maRecs;\n};\n\ntemplate< typename RecType >\nvoid XclExpRecordList< RecType >::Save( XclExpStream& rStrm )\n{\n for( typename RecordVec::iterator aIt = maRecs.begin(), aEnd = maRecs.end(); aIt != aEnd; ++aIt )\n (*aIt)->Save( rStrm );\n}\n\n\/\/ ============================================================================\n\n#endif\n\n<commit_msg>INTEGRATION: CWS dr31 (1.6.118); FILE MERGED 2004\/12\/20 17:41:43 dr 1.6.118.3: #i38792# #i38821# formula handling changed, export of add-ins to BIFF5 2004\/12\/17 15:07:28 dr 1.6.118.2: #i38792# #i38821# Excel export of defined names and database ranges reimplemented 2004\/12\/09 09:04:39 dr 1.6.118.1: #i37965# import\/export of control<->macro links, code cleanup<commit_after>\/*************************************************************************\n *\n * $RCSfile: xerecord.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2005-01-14 12:10:19 $\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_XERECORD_HXX\n#define SC_XERECORD_HXX\n\n#ifndef SC_XLCONST_HXX\n#include \"xlconst.hxx\"\n#endif\n#ifndef SC_XESTREAM_HXX\n#include \"xestream.hxx\"\n#endif\n\n\/\/ Base classes to export Excel records =======================================\n\n\/** Base class for all Excel records.\n\n Derive from this class to implement any functionality performed during\n saving the records - except really writing a record (i.e. write a list of\n records contained in the class). Derive from XclExpRecord (instead from\n this class) to write common records.\n *\/\nclass XclExpRecordBase\n{\npublic:\n virtual ~XclExpRecordBase();\n\n \/** Overwrite this method to do any operation while saving the record. *\/\n virtual void Save( XclExpStream& rStrm );\n\n \/** Calls Save(XclExpStream&) nCount times. *\/\n void SaveRepeated( XclExpStream& rStrm, sal_uInt32 nCount );\n};\n\ntypedef ScfRef< XclExpRecordBase > XclExpRecordRef;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Base class for single records with any content.\n\n This class handles writing the record header. Derived classes only have to\n write the record body. Calculating the record size before saving optimizes\n the write process (the stream does not have to seek back and update the\n written record size). But it is not required to calculate a valid size\n (maybe it would be too complex or just impossible until the record is\n really written).\n *\/\nclass XclExpRecord : public XclExpRecordBase\n{\npublic:\n \/** @param nRecId The record ID of this record. May be set later with SetRecId().\n @param nRecSize The predicted record size. May be set later with SetRecSize(). *\/\n explicit XclExpRecord(\n sal_uInt16 nRecId = EXC_ID_UNKNOWN,\n sal_uInt32 nRecSize = 0 );\n\n virtual ~XclExpRecord();\n\n \/** Returns the current record ID. *\/\n inline sal_uInt16 GetRecId() const { return mnRecId; }\n \/** Returns the current record size prediction. *\/\n inline sal_uInt32 GetRecSize() const { return mnRecSize; }\n\n \/** Sets a new record ID. *\/\n inline void SetRecId( sal_uInt16 nRecId ) { mnRecId = nRecId; }\n \/** Sets a new record size prediction. *\/\n inline void SetRecSize( sal_uInt32 nRecSize ) { mnRecSize = nRecSize; }\n \/** Adds a size value to the record size prediction. *\/\n inline void AddRecSize( sal_uInt32 nRecSize ) { mnRecSize += nRecSize; }\n \/** Sets record ID and size with one call. *\/\n void SetRecHeader( sal_uInt16 nRecId, sal_uInt32 nRecSize );\n\n \/** Writes the record header and calls WriteBody(). *\/\n virtual void Save( XclExpStream& rStrm );\n\nprivate:\n \/** Writes the body of the record (without record header).\n @descr Usually this method will be overwritten by derived classes. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n sal_uInt32 mnRecSize; \/\/\/ The predicted record size.\n sal_uInt16 mnRecId; \/\/\/ The record ID.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record without body. Only the record ID and the size 0 will be written. *\/\nclass XclExpEmptyRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record. *\/\n inline explicit XclExpEmptyRecord( sal_uInt16 nRecId );\n};\n\ninline XclExpEmptyRecord::XclExpEmptyRecord( sal_uInt16 nRecId ) :\n XclExpRecord( nRecId, 0 )\n{\n}\n\n\/\/ ============================================================================\n\n\/** A record with a single value of type Type.\n @descr Requires operator<<( XclExpStream&, const Type& ). *\/\ntemplate< typename Type >\nclass XclExpValueRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param rValue The value for the record body.\n @param nSize Record size. Uses sizeof( Type ), if this parameter is omitted. *\/\n inline explicit XclExpValueRecord(\n sal_uInt16 nRecId,\n const Type& rValue,\n sal_uInt32 nSize = sizeof( Type ) );\n\n \/** Returns the value of the record. *\/\n inline const Type& GetValue() const { return maValue; }\n \/** Sets a new record value. *\/\n inline void SetValue( const Type& rValue ) { maValue = rValue; }\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n Type maValue; \/\/\/ The record data.\n};\n\ntemplate< typename Type >\ninline XclExpValueRecord< Type >::XclExpValueRecord( sal_uInt16 nRecId, const Type& rValue, sal_uInt32 nSize ) :\n XclExpRecord( nRecId, nSize ),\n maValue( rValue )\n{\n}\n\ntemplate< typename Type >\nvoid XclExpValueRecord< Type >::WriteBody( XclExpStream& rStrm )\n{\n rStrm << maValue;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record containing an unsigned 16-bit value. *\/\ntypedef XclExpValueRecord< sal_uInt16 > XclExpUInt16Record;\n\n\/** A record containing an unsigned 32-bit value. *\/\ntypedef XclExpValueRecord< sal_uInt32 > XclExpUInt32Record;\n\n\/** A record containing a double value. *\/\ntypedef XclExpValueRecord< double > XclExpDoubleRecord;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Record which contains a Boolean value.\n @descr The value is stored as 16-bit value: 0x0000 = FALSE, 0x0001 = TRUE. *\/\nclass XclExpBoolRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param nValue The value for the record body. *\/\n inline explicit XclExpBoolRecord( sal_uInt16 nRecId, bool bValue ) :\n XclExpRecord( nRecId, 2 ), mbValue( bValue ) {}\n\n \/** Returns the Boolean value of the record. *\/\n inline bool GetBool() const { return mbValue; }\n \/** Sets a new Boolean record value. *\/\n inline void SetBool( bool bValue ) { mbValue = bValue; }\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n bool mbValue; \/\/\/ The record data.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Record which exports a memory data array. *\/\nclass XclExpDummyRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param pRecData Pointer to the data array representing the record body.\n @param nRecSize Size of the data array. *\/\n explicit XclExpDummyRecord(\n sal_uInt16 nRecId, const void* pRecData, sal_uInt32 nRecSize );\n\n \/** Sets a data array. *\/\n void SetData( const void* pRecData, sal_uInt32 nRecSize );\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n const void* mpData; \/\/\/ The record data.\n};\n\n\/\/ List of records ============================================================\n\n\/** A list of Excel record objects.\n\n Provides saving the compete list. This class is derived from\n XclExpRecordBase, so it can be used as record in another record list.\n Requires RecType::Save( XclExpStream& ).\n *\/\ntemplate< typename RecType = XclExpRecordBase >\nclass XclExpRecordList : public XclExpRecordBase\n{\npublic:\n typedef ScfRef< RecType > RecordRefType;\n\n \/** Returns pointer to an existing record or 0 on error. *\/\n inline bool Empty() const { return maRecs.empty(); }\n \/** Returns pointer to an existing record or 0 on error. *\/\n inline size_t Size() const { return maRecs.size(); }\n\n \/** Returns true, if the passed index points to an exiting record. *\/\n inline bool HasRecord( size_t nPos ) const\n { return (0 <= nPos) && (nPos < maRecs.size()); }\n\n \/** Returns reference to an existing record or empty reference on error. *\/\n inline const RecordRefType GetRecord( size_t nPos ) const\n { return (nPos < maRecs.size()) ? maRecs[ nPos ] : RecordRefType(); }\n \/** Returns reference to an existing record or empty reference on error. *\/\n inline RecordRefType GetRecord( size_t nPos )\n { return (nPos < maRecs.size()) ? maRecs[ nPos ] : RecordRefType(); }\n\n \/** Returns reference to the last existing record or empty reference, if list is empty. *\/\n inline const RecordRefType GetLastRecord() const\n { return maRecs.empty() ? RecordRefType() : maRecs.back(); }\n \/** Returns reference to the last existing record or empty reference, if list is empty. *\/\n inline RecordRefType GetLastRecord()\n { return maRecs.empty() ? RecordRefType() : maRecs.back(); }\n\n \/** Inserts a record at the specified position into the list. *\/\n inline void InsertRecord( RecordRefType xRec, size_t nPos )\n { if( xRec.get() ) maRecs.insert( maRecs.begin() + ::std::min( nPos, maRecs.size() ), xRec ); }\n \/** Appends a record to the list. *\/\n inline void AppendRecord( RecordRefType xRec )\n { if( xRec.get() ) maRecs.push_back( xRec ); }\n \/** Replaces the record at the specified position from the list with the passed record. *\/\n inline void ReplaceRecord( RecordRefType xRec, size_t nPos )\n { RemoveRecord( nPos ); InsertRecord( xRec, nPos ); }\n\n \/** Inserts a newly created record at the specified position into the list. *\/\n inline void InsertNewRecord( RecType* pRec, size_t nPos )\n { if( pRec ) InsertRecord( RecordRefType( pRec ), nPos ); }\n \/** Appends a newly created record to the list. *\/\n inline void AppendNewRecord( RecType* pRec )\n { if( pRec ) AppendRecord( RecordRefType( pRec ) ); }\n \/** Replaces the record at the specified position from the list with the passed newly created record. *\/\n inline void ReplaceNewRecord( RecType* pRec, size_t nPos )\n { RemoveRecord( nPos ); InsertNewRecord( pRec, nPos ); }\n\n \/** Removes the record at the specified position from the list. *\/\n inline void RemoveRecord( size_t nPos )\n { if( nPos < maRecs.size() ) maRecs.erase( maRecs.begin() + nPos ); }\n \/** Removes all records from the list. *\/\n inline void RemoveAllRecords() { maRecs.clear(); }\n\n \/** Writes the complete record list. *\/\n virtual void Save( XclExpStream& rStrm );\n\nprivate:\n typedef ::std::vector< RecordRefType > RecordVec;\n RecordVec maRecs;\n};\n\ntemplate< typename RecType >\nvoid XclExpRecordList< RecType >::Save( XclExpStream& rStrm )\n{\n for( typename RecordVec::iterator aIt = maRecs.begin(), aEnd = maRecs.end(); aIt != aEnd; ++aIt )\n (*aIt)->Save( rStrm );\n}\n\n\/\/ ============================================================================\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: xerecord.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2005-01-14 12:10:19 $\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_XERECORD_HXX\n#define SC_XERECORD_HXX\n\n#ifndef SC_XLCONST_HXX\n#include \"xlconst.hxx\"\n#endif\n#ifndef SC_XESTREAM_HXX\n#include \"xestream.hxx\"\n#endif\n\n\/\/ Base classes to export Excel records =======================================\n\n\/** Base class for all Excel records.\n\n Derive from this class to implement any functionality performed during\n saving the records - except really writing a record (i.e. write a list of\n records contained in the class). Derive from XclExpRecord (instead from\n this class) to write common records.\n *\/\nclass XclExpRecordBase\n{\npublic:\n virtual ~XclExpRecordBase();\n\n \/** Overwrite this method to do any operation while saving the record. *\/\n virtual void Save( XclExpStream& rStrm );\n\n \/** Calls Save(XclExpStream&) nCount times. *\/\n void SaveRepeated( XclExpStream& rStrm, sal_uInt32 nCount );\n};\n\ntypedef ScfRef< XclExpRecordBase > XclExpRecordRef;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Base class for single records with any content.\n\n This class handles writing the record header. Derived classes only have to\n write the record body. Calculating the record size before saving optimizes\n the write process (the stream does not have to seek back and update the\n written record size). But it is not required to calculate a valid size\n (maybe it would be too complex or just impossible until the record is\n really written).\n *\/\nclass XclExpRecord : public XclExpRecordBase\n{\npublic:\n \/** @param nRecId The record ID of this record. May be set later with SetRecId().\n @param nRecSize The predicted record size. May be set later with SetRecSize(). *\/\n explicit XclExpRecord(\n sal_uInt16 nRecId = EXC_ID_UNKNOWN,\n sal_uInt32 nRecSize = 0 );\n\n virtual ~XclExpRecord();\n\n \/** Returns the current record ID. *\/\n inline sal_uInt16 GetRecId() const { return mnRecId; }\n \/** Returns the current record size prediction. *\/\n inline sal_uInt32 GetRecSize() const { return mnRecSize; }\n\n \/** Sets a new record ID. *\/\n inline void SetRecId( sal_uInt16 nRecId ) { mnRecId = nRecId; }\n \/** Sets a new record size prediction. *\/\n inline void SetRecSize( sal_uInt32 nRecSize ) { mnRecSize = nRecSize; }\n \/** Adds a size value to the record size prediction. *\/\n inline void AddRecSize( sal_uInt32 nRecSize ) { mnRecSize += nRecSize; }\n \/** Sets record ID and size with one call. *\/\n void SetRecHeader( sal_uInt16 nRecId, sal_uInt32 nRecSize );\n\n \/** Writes the record header and calls WriteBody(). *\/\n virtual void Save( XclExpStream& rStrm );\n\nprivate:\n \/** Writes the body of the record (without record header).\n @descr Usually this method will be overwritten by derived classes. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n sal_uInt32 mnRecSize; \/\/\/ The predicted record size.\n sal_uInt16 mnRecId; \/\/\/ The record ID.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record without body. Only the record ID and the size 0 will be written. *\/\nclass XclExpEmptyRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record. *\/\n inline explicit XclExpEmptyRecord( sal_uInt16 nRecId );\n};\n\ninline XclExpEmptyRecord::XclExpEmptyRecord( sal_uInt16 nRecId ) :\n XclExpRecord( nRecId, 0 )\n{\n}\n\n\/\/ ============================================================================\n\n\/** A record with a single value of type Type.\n @descr Requires operator<<( XclExpStream&, const Type& ). *\/\ntemplate< typename Type >\nclass XclExpValueRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param rValue The value for the record body.\n @param nSize Record size. Uses sizeof( Type ), if this parameter is omitted. *\/\n inline explicit XclExpValueRecord(\n sal_uInt16 nRecId,\n const Type& rValue,\n sal_uInt32 nSize = sizeof( Type ) );\n\n \/** Returns the value of the record. *\/\n inline const Type& GetValue() const { return maValue; }\n \/** Sets a new record value. *\/\n inline void SetValue( const Type& rValue ) { maValue = rValue; }\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n Type maValue; \/\/\/ The record data.\n};\n\ntemplate< typename Type >\ninline XclExpValueRecord< Type >::XclExpValueRecord( sal_uInt16 nRecId, const Type& rValue, sal_uInt32 nSize ) :\n XclExpRecord( nRecId, nSize ),\n maValue( rValue )\n{\n}\n\ntemplate< typename Type >\nvoid XclExpValueRecord< Type >::WriteBody( XclExpStream& rStrm )\n{\n rStrm << maValue;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record containing an unsigned 16-bit value. *\/\ntypedef XclExpValueRecord< sal_uInt16 > XclExpUInt16Record;\n\n\/** A record containing an unsigned 32-bit value. *\/\ntypedef XclExpValueRecord< sal_uInt32 > XclExpUInt32Record;\n\n\/** A record containing a double value. *\/\ntypedef XclExpValueRecord< double > XclExpDoubleRecord;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Record which contains a Boolean value.\n @descr The value is stored as 16-bit value: 0x0000 = FALSE, 0x0001 = TRUE. *\/\nclass XclExpBoolRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param nValue The value for the record body. *\/\n inline explicit XclExpBoolRecord( sal_uInt16 nRecId, bool bValue ) :\n XclExpRecord( nRecId, 2 ), mbValue( bValue ) {}\n\n \/** Returns the Boolean value of the record. *\/\n inline bool GetBool() const { return mbValue; }\n \/** Sets a new Boolean record value. *\/\n inline void SetBool( bool bValue ) { mbValue = bValue; }\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n bool mbValue; \/\/\/ The record data.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Record which exports a memory data array. *\/\nclass XclExpDummyRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param pRecData Pointer to the data array representing the record body.\n @param nRecSize Size of the data array. *\/\n explicit XclExpDummyRecord(\n sal_uInt16 nRecId, const void* pRecData, sal_uInt32 nRecSize );\n\n \/** Sets a data array. *\/\n void SetData( const void* pRecData, sal_uInt32 nRecSize );\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n const void* mpData; \/\/\/ The record data.\n};\n\n\/\/ List of records ============================================================\n\n\/** A list of Excel record objects.\n\n Provides saving the compete list. This class is derived from\n XclExpRecordBase, so it can be used as record in another record list.\n Requires RecType::Save( XclExpStream& ).\n *\/\ntemplate< typename RecType = XclExpRecordBase >\nclass XclExpRecordList : public XclExpRecordBase\n{\npublic:\n typedef ScfRef< RecType > RecordRefType;\n\n \/** Returns pointer to an existing record or 0 on error. *\/\n inline bool Empty() const { return maRecs.empty(); }\n \/** Returns pointer to an existing record or 0 on error. *\/\n inline size_t Size() const { return maRecs.size(); }\n\n \/** Returns true, if the passed index points to an exiting record. *\/\n inline bool HasRecord( size_t nPos ) const\n { return (0 <= nPos) && (nPos < maRecs.size()); }\n\n \/** Returns reference to an existing record or empty reference on error. *\/\n inline const RecordRefType GetRecord( size_t nPos ) const\n { return (nPos < maRecs.size()) ? maRecs[ nPos ] : RecordRefType(); }\n \/** Returns reference to an existing record or empty reference on error. *\/\n inline RecordRefType GetRecord( size_t nPos )\n { return (nPos < maRecs.size()) ? maRecs[ nPos ] : RecordRefType(); }\n\n \/** Returns reference to the last existing record or empty reference, if list is empty. *\/\n inline const RecordRefType GetLastRecord() const\n { return maRecs.empty() ? RecordRefType() : maRecs.back(); }\n \/** Returns reference to the last existing record or empty reference, if list is empty. *\/\n inline RecordRefType GetLastRecord()\n { return maRecs.empty() ? RecordRefType() : maRecs.back(); }\n\n \/** Inserts a record at the specified position into the list. *\/\n inline void InsertRecord( RecordRefType xRec, size_t nPos )\n { if( xRec.get() ) maRecs.insert( maRecs.begin() + ::std::min( nPos, maRecs.size() ), xRec ); }\n \/** Appends a record to the list. *\/\n inline void AppendRecord( RecordRefType xRec )\n { if( xRec.get() ) maRecs.push_back( xRec ); }\n \/** Replaces the record at the specified position from the list with the passed record. *\/\n inline void ReplaceRecord( RecordRefType xRec, size_t nPos )\n { RemoveRecord( nPos ); InsertRecord( xRec, nPos ); }\n\n \/** Inserts a newly created record at the specified position into the list. *\/\n inline void InsertNewRecord( RecType* pRec, size_t nPos )\n { if( pRec ) InsertRecord( RecordRefType( pRec ), nPos ); }\n \/** Appends a newly created record to the list. *\/\n inline void AppendNewRecord( RecType* pRec )\n { if( pRec ) AppendRecord( RecordRefType( pRec ) ); }\n \/** Replaces the record at the specified position from the list with the passed newly created record. *\/\n inline void ReplaceNewRecord( RecType* pRec, size_t nPos )\n { RemoveRecord( nPos ); InsertNewRecord( pRec, nPos ); }\n\n \/** Removes the record at the specified position from the list. *\/\n inline void RemoveRecord( size_t nPos )\n { if( nPos < maRecs.size() ) maRecs.erase( maRecs.begin() + nPos ); }\n \/** Removes all records from the list. *\/\n inline void RemoveAllRecords() { maRecs.clear(); }\n\n \/** Writes the complete record list. *\/\n virtual void Save( XclExpStream& rStrm );\n\nprivate:\n typedef ::std::vector< RecordRefType > RecordVec;\n RecordVec maRecs;\n};\n\ntemplate< typename RecType >\nvoid XclExpRecordList< RecType >::Save( XclExpStream& rStrm )\n{\n for( typename RecordVec::iterator aIt = maRecs.begin(), aEnd = maRecs.end(); aIt != aEnd; ++aIt )\n (*aIt)->Save( rStrm );\n}\n\n\/\/ ============================================================================\n\n#endif\n\n<commit_msg>INTEGRATION: CWS dr32 (1.7.2); FILE MERGED 2005\/02\/03 12:05:32 dr 1.7.2.1: #i40570# remove RootData::aStandard, changed ref handling<commit_after>\/*************************************************************************\n *\n * $RCSfile: xerecord.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: vg $ $Date: 2005-02-21 13:43:05 $\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_XERECORD_HXX\n#define SC_XERECORD_HXX\n\n#ifndef SC_XLCONST_HXX\n#include \"xlconst.hxx\"\n#endif\n#ifndef SC_XESTREAM_HXX\n#include \"xestream.hxx\"\n#endif\n\n\/\/ Base classes to export Excel records =======================================\n\n\/** Base class for all Excel records.\n\n Derive from this class to implement any functionality performed during\n saving the records - except really writing a record (i.e. write a list of\n records contained in the class). Derive from XclExpRecord (instead from\n this class) to write common records.\n *\/\nclass XclExpRecordBase\n{\npublic:\n virtual ~XclExpRecordBase();\n\n \/** Overwrite this method to do any operation while saving the record. *\/\n virtual void Save( XclExpStream& rStrm );\n\n \/** Calls Save(XclExpStream&) nCount times. *\/\n void SaveRepeated( XclExpStream& rStrm, sal_uInt32 nCount );\n};\n\ntypedef ScfRef< XclExpRecordBase > XclExpRecordRef;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Base class for single records with any content.\n\n This class handles writing the record header. Derived classes only have to\n write the record body. Calculating the record size before saving optimizes\n the write process (the stream does not have to seek back and update the\n written record size). But it is not required to calculate a valid size\n (maybe it would be too complex or just impossible until the record is\n really written).\n *\/\nclass XclExpRecord : public XclExpRecordBase\n{\npublic:\n \/** @param nRecId The record ID of this record. May be set later with SetRecId().\n @param nRecSize The predicted record size. May be set later with SetRecSize(). *\/\n explicit XclExpRecord(\n sal_uInt16 nRecId = EXC_ID_UNKNOWN,\n sal_uInt32 nRecSize = 0 );\n\n virtual ~XclExpRecord();\n\n \/** Returns the current record ID. *\/\n inline sal_uInt16 GetRecId() const { return mnRecId; }\n \/** Returns the current record size prediction. *\/\n inline sal_uInt32 GetRecSize() const { return mnRecSize; }\n\n \/** Sets a new record ID. *\/\n inline void SetRecId( sal_uInt16 nRecId ) { mnRecId = nRecId; }\n \/** Sets a new record size prediction. *\/\n inline void SetRecSize( sal_uInt32 nRecSize ) { mnRecSize = nRecSize; }\n \/** Adds a size value to the record size prediction. *\/\n inline void AddRecSize( sal_uInt32 nRecSize ) { mnRecSize += nRecSize; }\n \/** Sets record ID and size with one call. *\/\n void SetRecHeader( sal_uInt16 nRecId, sal_uInt32 nRecSize );\n\n \/** Writes the record header and calls WriteBody(). *\/\n virtual void Save( XclExpStream& rStrm );\n\nprivate:\n \/** Writes the body of the record (without record header).\n @descr Usually this method will be overwritten by derived classes. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n sal_uInt32 mnRecSize; \/\/\/ The predicted record size.\n sal_uInt16 mnRecId; \/\/\/ The record ID.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record without body. Only the record ID and the size 0 will be written. *\/\nclass XclExpEmptyRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record. *\/\n inline explicit XclExpEmptyRecord( sal_uInt16 nRecId );\n};\n\ninline XclExpEmptyRecord::XclExpEmptyRecord( sal_uInt16 nRecId ) :\n XclExpRecord( nRecId, 0 )\n{\n}\n\n\/\/ ============================================================================\n\n\/** A record with a single value of type Type.\n @descr Requires operator<<( XclExpStream&, const Type& ). *\/\ntemplate< typename Type >\nclass XclExpValueRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param rValue The value for the record body.\n @param nSize Record size. Uses sizeof( Type ), if this parameter is omitted. *\/\n inline explicit XclExpValueRecord(\n sal_uInt16 nRecId,\n const Type& rValue,\n sal_uInt32 nSize = sizeof( Type ) );\n\n \/** Returns the value of the record. *\/\n inline const Type& GetValue() const { return maValue; }\n \/** Sets a new record value. *\/\n inline void SetValue( const Type& rValue ) { maValue = rValue; }\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n Type maValue; \/\/\/ The record data.\n};\n\ntemplate< typename Type >\ninline XclExpValueRecord< Type >::XclExpValueRecord( sal_uInt16 nRecId, const Type& rValue, sal_uInt32 nSize ) :\n XclExpRecord( nRecId, nSize ),\n maValue( rValue )\n{\n}\n\ntemplate< typename Type >\nvoid XclExpValueRecord< Type >::WriteBody( XclExpStream& rStrm )\n{\n rStrm << maValue;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** A record containing an unsigned 16-bit value. *\/\ntypedef XclExpValueRecord< sal_uInt16 > XclExpUInt16Record;\n\n\/** A record containing an unsigned 32-bit value. *\/\ntypedef XclExpValueRecord< sal_uInt32 > XclExpUInt32Record;\n\n\/** A record containing a double value. *\/\ntypedef XclExpValueRecord< double > XclExpDoubleRecord;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Record which contains a Boolean value.\n @descr The value is stored as 16-bit value: 0x0000 = FALSE, 0x0001 = TRUE. *\/\nclass XclExpBoolRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param nValue The value for the record body. *\/\n inline explicit XclExpBoolRecord( sal_uInt16 nRecId, bool bValue ) :\n XclExpRecord( nRecId, 2 ), mbValue( bValue ) {}\n\n \/** Returns the Boolean value of the record. *\/\n inline bool GetBool() const { return mbValue; }\n \/** Sets a new Boolean record value. *\/\n inline void SetBool( bool bValue ) { mbValue = bValue; }\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n bool mbValue; \/\/\/ The record data.\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Record which exports a memory data array. *\/\nclass XclExpDummyRecord : public XclExpRecord\n{\npublic:\n \/** @param nRecId The record ID of this record.\n @param pRecData Pointer to the data array representing the record body.\n @param nRecSize Size of the data array. *\/\n explicit XclExpDummyRecord(\n sal_uInt16 nRecId, const void* pRecData, sal_uInt32 nRecSize );\n\n \/** Sets a data array. *\/\n void SetData( const void* pRecData, sal_uInt32 nRecSize );\n\nprivate:\n \/** Writes the body of the record. *\/\n virtual void WriteBody( XclExpStream& rStrm );\n\nprivate:\n const void* mpData; \/\/\/ The record data.\n};\n\n\/\/ List of records ============================================================\n\n\/** A list of Excel record objects.\n\n Provides saving the compete list. This class is derived from\n XclExpRecordBase, so it can be used as record in another record list.\n Requires RecType::Save( XclExpStream& ).\n *\/\ntemplate< typename RecType = XclExpRecordBase >\nclass XclExpRecordList : public XclExpRecordBase\n{\npublic:\n typedef ScfRef< RecType > RecordRefType;\n\n \/** Returns pointer to an existing record or 0 on error. *\/\n inline bool Empty() const { return maRecs.empty(); }\n \/** Returns pointer to an existing record or 0 on error. *\/\n inline size_t Size() const { return maRecs.size(); }\n\n \/** Returns true, if the passed index points to an exiting record. *\/\n inline bool HasRecord( size_t nPos ) const\n { return (0 <= nPos) && (nPos < maRecs.size()); }\n \/** Returns reference to an existing record or empty reference on error. *\/\n inline RecordRefType GetRecord( size_t nPos ) const\n { return (nPos < maRecs.size()) ? maRecs[ nPos ] : RecordRefType(); }\n \/** Returns reference to the first existing record or empty reference, if list is empty. *\/\n inline RecordRefType GetFirstRecord() const\n { return maRecs.empty() ? RecordRefType() : maRecs.front(); }\n \/** Returns reference to the last existing record or empty reference, if list is empty. *\/\n inline RecordRefType GetLastRecord() const\n { return maRecs.empty() ? RecordRefType() : maRecs.back(); }\n\n \/** Inserts a record at the specified position into the list. *\/\n inline void InsertRecord( RecordRefType xRec, size_t nPos )\n { if( xRec.get() ) maRecs.insert( maRecs.begin() + ::std::min( nPos, maRecs.size() ), xRec ); }\n \/** Appends a record to the list. *\/\n inline void AppendRecord( RecordRefType xRec )\n { if( xRec.get() ) maRecs.push_back( xRec ); }\n \/** Replaces the record at the specified position from the list with the passed record. *\/\n inline void ReplaceRecord( RecordRefType xRec, size_t nPos )\n { RemoveRecord( nPos ); InsertRecord( xRec, nPos ); }\n\n \/** Inserts a newly created record at the specified position into the list. *\/\n inline void InsertNewRecord( RecType* pRec, size_t nPos )\n { if( pRec ) InsertRecord( RecordRefType( pRec ), nPos ); }\n \/** Appends a newly created record to the list. *\/\n inline void AppendNewRecord( RecType* pRec )\n { if( pRec ) AppendRecord( RecordRefType( pRec ) ); }\n \/** Replaces the record at the specified position from the list with the passed newly created record. *\/\n inline void ReplaceNewRecord( RecType* pRec, size_t nPos )\n { RemoveRecord( nPos ); InsertNewRecord( pRec, nPos ); }\n\n \/** Removes the record at the specified position from the list. *\/\n inline void RemoveRecord( size_t nPos )\n { if( nPos < maRecs.size() ) maRecs.erase( maRecs.begin() + nPos ); }\n \/** Removes all records from the list. *\/\n inline void RemoveAllRecords() { maRecs.clear(); }\n\n \/** Writes the complete record list. *\/\n virtual void Save( XclExpStream& rStrm );\n\nprivate:\n typedef ::std::vector< RecordRefType > RecordVec;\n RecordVec maRecs;\n};\n\ntemplate< typename RecType >\nvoid XclExpRecordList< RecType >::Save( XclExpStream& rStrm )\n{\n for( typename RecordVec::iterator aIt = maRecs.begin(), aEnd = maRecs.end(); aIt != aEnd; ++aIt )\n (*aIt)->Save( rStrm );\n}\n\n\/\/ ============================================================================\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Unused variable.<commit_after><|endoftext|>"} {"text":"<commit_before>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef SC_XMLSUBTI_HXX\n#define SC_XMLSUBTI_HXX\n\n#include <xmloff\/xmlictxt.hxx>\n#include <xmloff\/xmlimp.hxx>\n#include <com\/sun\/star\/sheet\/XSpreadsheet.hpp>\n#include <com\/sun\/star\/drawing\/XDrawPage.hpp>\n#include <com\/sun\/star\/table\/CellAddress.hpp>\n#include <com\/sun\/star\/table\/XCellRange.hpp>\n#include <com\/sun\/star\/table\/CellRangeAddress.hpp>\n#include <com\/sun\/star\/frame\/XModel.hpp>\n\n#include \"XMLTableShapeResizer.hxx\"\n#include \"formula\/grammar.hxx\"\n#include \"tabprotection.hxx\"\n\n#include <vector>\n#include <list>\n#include <boost\/ptr_container\/ptr_vector.hpp>\n\nclass ScXMLImport;\n\ntypedef std::vector<sal_Int32> ScMysalIntVec;\ntypedef std::list<sal_Int32> ScMysalIntList;\n\nconst ScMysalIntVec::size_type nDefaultRowCount = 20;\nconst ScMysalIntVec::size_type nDefaultColCount = 20;\nconst ScMysalIntVec::size_type nDefaultTabCount = 10;\n\nclass ScMyTableData\n{\nprivate:\n com::sun::star::table::CellAddress aTableCellPos;\n ScMysalIntVec nColsPerCol;\n ScMysalIntVec nRealCols;\n ScMysalIntVec nRowsPerRow;\n ScMysalIntVec nRealRows;\n sal_Int32 nSpannedCols;\n sal_Int32 nColCount;\n sal_Int32 nSubTableSpanned;\n ScMysalIntList nChangedCols;\npublic:\n ScMyTableData(sal_Int32 nSheet = -1, sal_Int32 nCol = -1, sal_Int32 nRow = -1);\n ~ScMyTableData();\n com::sun::star::table::CellAddress GetCellPos() const { return aTableCellPos; }\n sal_Int32 GetRow() const { return aTableCellPos.Row; }\n sal_Int32 GetColumn() const { return aTableCellPos.Column; }\n void AddRow();\n void AddColumn();\n void SetFirstColumn() { aTableCellPos.Column = -1; }\n sal_Int32 GetColsPerCol(const sal_Int32 nIndex) const { return nColsPerCol[nIndex]; }\n void SetColsPerCol(const sal_Int32 nIndex, sal_Int32 nValue = 1) { nColsPerCol[nIndex] = nValue; }\n sal_Int32 GetRealCols(const sal_Int32 nIndex, const sal_Bool bIsNormal = sal_True) const;\n void SetRealCols(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealCols[nIndex] = nValue; }\n sal_Int32 GetRowsPerRow(const sal_Int32 nIndex) const { return nRowsPerRow[nIndex]; }\n void SetRowsPerRow(const sal_Int32 nIndex, const sal_Int32 nValue = 1) { nRowsPerRow[nIndex] = nValue; }\n sal_Int32 GetRealRows(const sal_Int32 nIndex) const { return nIndex < 0 ? 0 : nRealRows[nIndex]; }\n void SetRealRows(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealRows[nIndex] = nValue; }\n sal_Int32 GetSpannedCols() const { return nSpannedCols; }\n void SetSpannedCols(const sal_Int32 nTempSpannedCols) { nSpannedCols = nTempSpannedCols; }\n sal_Int32 GetColCount() const { return nColCount; }\n void SetColCount(const sal_Int32 nTempColCount) { nColCount = nTempColCount; }\n sal_Int32 GetSubTableSpanned() const { return nSubTableSpanned; }\n void SetSubTableSpanned(const sal_Int32 nValue) { nSubTableSpanned = nValue; }\n sal_Int32 GetChangedCols(const sal_Int32 nFromIndex, const sal_Int32 nToIndex) const;\n void SetChangedCols(const sal_Int32 nValue);\n};\n\n\/\/*******************************************************************************************************************************\n\nstruct ScMatrixRange\n{\n rtl::OUString sFormula;\n rtl::OUString sFormulaNmsp;\n formula::FormulaGrammar::Grammar eGrammar;\n com::sun::star::table::CellRangeAddress aRange;\n ScMatrixRange(const com::sun::star::table::CellRangeAddress& rRange, const rtl::OUString& rFormula, const rtl::OUString& rFormulaNmsp, const formula::FormulaGrammar::Grammar eGrammarP) :\n sFormula(rFormula),\n sFormulaNmsp(rFormulaNmsp),\n eGrammar(eGrammarP),\n aRange(rRange)\n {\n }\n};\n\nstruct ScXMLTabProtectionData\n{\n ::rtl::OUString maPassword;\n ScPasswordHash meHash1;\n ScPasswordHash meHash2;\n bool mbProtected;\n bool mbSelectProtectedCells;\n bool mbSelectUnprotectedCells;\n\n ScXMLTabProtectionData();\n};\n\nclass ScMyTables\n{\nprivate:\n typedef std::list<ScMatrixRange> ScMyMatrixRangeList;\n\n ScXMLImport& rImport;\n\n ScMyShapeResizer aResizeShapes;\n\n ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > xCurrentSheet;\n ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange > xCurrentCellRange;\n ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > xDrawPage;\n ::com::sun::star::uno::Reference < ::com::sun::star::drawing::XShapes > xShapes;\n rtl::OUString sCurrentSheetName;\n ::boost::ptr_vector<ScMyTableData> maTables;\n ScXMLTabProtectionData maProtectionData;\n ScMyMatrixRangeList aMatrixRangeList;\n com::sun::star::table::CellAddress aRealCellPos;\n sal_Int32 nCurrentColStylePos;\n sal_Int16 nCurrentDrawPage;\n sal_Int16 nCurrentXShapes;\n sal_Int32 nCurrentSheet;\n\n sal_Bool IsMerged (const com::sun::star::uno::Reference <com::sun::star::table::XCellRange>& xCellRange,\n const sal_Int32 nCol, const sal_Int32 nRow,\n com::sun::star::table::CellRangeAddress& aCellAddress) const;\n void UnMerge();\n void DoMerge(sal_Int32 nCount = -1);\n void InsertRow();\n void NewRow();\n void InsertColumn();\n void NewColumn(sal_Bool bIsCovered);\npublic:\n ScMyTables(ScXMLImport& rImport);\n ~ScMyTables();\n void NewSheet(const rtl::OUString& sTableName, const rtl::OUString& sStyleName,\n const ScXMLTabProtectionData& rProtectData);\n void AddRow();\n void SetRowStyle(const rtl::OUString& rCellStyleName);\n void AddColumn(sal_Bool bIsCovered);\n void NewTable(sal_Int32 nTempSpannedCols);\n void UpdateRowHeights();\n void ResizeShapes() { aResizeShapes.ResizeShapes(); }\n void DeleteTable();\n com::sun::star::table::CellAddress GetRealCellPos();\n void AddColCount(sal_Int32 nTempColCount);\n void AddColStyle(const sal_Int32 nRepeat, const rtl::OUString& rCellStyleName);\n ScXMLTabProtectionData& GetCurrentProtectionData() { return maProtectionData; }\n rtl::OUString GetCurrentSheetName() const { return sCurrentSheetName; }\n sal_Int32 GetCurrentSheet() const { return nCurrentSheet; }\n sal_Int32 GetCurrentColumn() const { return maTables.back().GetColCount(); }\n sal_Int32 GetCurrentRow() const { return maTables.back().GetRow(); }\n ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet >\n GetCurrentXSheet() { return xCurrentSheet; }\n ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange >\n GetCurrentXCellRange() { return xCurrentCellRange; }\n ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >\n GetCurrentXDrawPage();\n ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >\n GetCurrentXShapes();\n sal_Bool HasDrawPage();\n sal_Bool HasXShapes();\n void AddShape(com::sun::star::uno::Reference <com::sun::star::drawing::XShape>& rShape,\n rtl::OUString* pRangeList,\n com::sun::star::table::CellAddress& rStartAddress,\n com::sun::star::table::CellAddress& rEndAddress,\n sal_Int32 nEndX, sal_Int32 nEndY);\n\n void AddMatrixRange( sal_Int32 nStartColumn,\n sal_Int32 nStartRow,\n sal_Int32 nEndColumn,\n sal_Int32 nEndRow,\n const rtl::OUString& rFormula,\n const rtl::OUString& rFormulaNmsp,\n const formula::FormulaGrammar::Grammar );\n\n sal_Bool IsPartOfMatrix(sal_Int32 nColumn, sal_Int32 nRow);\n void SetMatrix( const com::sun::star::table::CellRangeAddress& rRange,\n const rtl::OUString& rFormula,\n const rtl::OUString& rFormulaNmsp,\n const formula::FormulaGrammar::Grammar );\n};\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>cppcheck: marked several methods const.<commit_after>\/* -*- 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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef SC_XMLSUBTI_HXX\n#define SC_XMLSUBTI_HXX\n\n#include <xmloff\/xmlictxt.hxx>\n#include <xmloff\/xmlimp.hxx>\n#include <com\/sun\/star\/sheet\/XSpreadsheet.hpp>\n#include <com\/sun\/star\/drawing\/XDrawPage.hpp>\n#include <com\/sun\/star\/table\/CellAddress.hpp>\n#include <com\/sun\/star\/table\/XCellRange.hpp>\n#include <com\/sun\/star\/table\/CellRangeAddress.hpp>\n#include <com\/sun\/star\/frame\/XModel.hpp>\n\n#include \"XMLTableShapeResizer.hxx\"\n#include \"formula\/grammar.hxx\"\n#include \"tabprotection.hxx\"\n\n#include <vector>\n#include <list>\n#include <boost\/ptr_container\/ptr_vector.hpp>\n\nclass ScXMLImport;\n\ntypedef std::vector<sal_Int32> ScMysalIntVec;\ntypedef std::list<sal_Int32> ScMysalIntList;\n\nconst ScMysalIntVec::size_type nDefaultRowCount = 20;\nconst ScMysalIntVec::size_type nDefaultColCount = 20;\nconst ScMysalIntVec::size_type nDefaultTabCount = 10;\n\nclass ScMyTableData\n{\nprivate:\n com::sun::star::table::CellAddress aTableCellPos;\n ScMysalIntVec nColsPerCol;\n ScMysalIntVec nRealCols;\n ScMysalIntVec nRowsPerRow;\n ScMysalIntVec nRealRows;\n sal_Int32 nSpannedCols;\n sal_Int32 nColCount;\n sal_Int32 nSubTableSpanned;\n ScMysalIntList nChangedCols;\npublic:\n ScMyTableData(sal_Int32 nSheet = -1, sal_Int32 nCol = -1, sal_Int32 nRow = -1);\n ~ScMyTableData();\n com::sun::star::table::CellAddress GetCellPos() const { return aTableCellPos; }\n sal_Int32 GetRow() const { return aTableCellPos.Row; }\n sal_Int32 GetColumn() const { return aTableCellPos.Column; }\n void AddRow();\n void AddColumn();\n void SetFirstColumn() { aTableCellPos.Column = -1; }\n sal_Int32 GetColsPerCol(const sal_Int32 nIndex) const { return nColsPerCol[nIndex]; }\n void SetColsPerCol(const sal_Int32 nIndex, sal_Int32 nValue = 1) { nColsPerCol[nIndex] = nValue; }\n sal_Int32 GetRealCols(const sal_Int32 nIndex, const sal_Bool bIsNormal = sal_True) const;\n void SetRealCols(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealCols[nIndex] = nValue; }\n sal_Int32 GetRowsPerRow(const sal_Int32 nIndex) const { return nRowsPerRow[nIndex]; }\n void SetRowsPerRow(const sal_Int32 nIndex, const sal_Int32 nValue = 1) { nRowsPerRow[nIndex] = nValue; }\n sal_Int32 GetRealRows(const sal_Int32 nIndex) const { return nIndex < 0 ? 0 : nRealRows[nIndex]; }\n void SetRealRows(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealRows[nIndex] = nValue; }\n sal_Int32 GetSpannedCols() const { return nSpannedCols; }\n void SetSpannedCols(const sal_Int32 nTempSpannedCols) { nSpannedCols = nTempSpannedCols; }\n sal_Int32 GetColCount() const { return nColCount; }\n void SetColCount(const sal_Int32 nTempColCount) { nColCount = nTempColCount; }\n sal_Int32 GetSubTableSpanned() const { return nSubTableSpanned; }\n void SetSubTableSpanned(const sal_Int32 nValue) { nSubTableSpanned = nValue; }\n sal_Int32 GetChangedCols(const sal_Int32 nFromIndex, const sal_Int32 nToIndex) const;\n void SetChangedCols(const sal_Int32 nValue);\n};\n\n\/\/*******************************************************************************************************************************\n\nstruct ScMatrixRange\n{\n rtl::OUString sFormula;\n rtl::OUString sFormulaNmsp;\n formula::FormulaGrammar::Grammar eGrammar;\n com::sun::star::table::CellRangeAddress aRange;\n ScMatrixRange(const com::sun::star::table::CellRangeAddress& rRange, const rtl::OUString& rFormula, const rtl::OUString& rFormulaNmsp, const formula::FormulaGrammar::Grammar eGrammarP) :\n sFormula(rFormula),\n sFormulaNmsp(rFormulaNmsp),\n eGrammar(eGrammarP),\n aRange(rRange)\n {\n }\n};\n\nstruct ScXMLTabProtectionData\n{\n ::rtl::OUString maPassword;\n ScPasswordHash meHash1;\n ScPasswordHash meHash2;\n bool mbProtected;\n bool mbSelectProtectedCells;\n bool mbSelectUnprotectedCells;\n\n ScXMLTabProtectionData();\n};\n\nclass ScMyTables\n{\nprivate:\n typedef std::list<ScMatrixRange> ScMyMatrixRangeList;\n\n ScXMLImport& rImport;\n\n ScMyShapeResizer aResizeShapes;\n\n ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > xCurrentSheet;\n ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange > xCurrentCellRange;\n ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > xDrawPage;\n ::com::sun::star::uno::Reference < ::com::sun::star::drawing::XShapes > xShapes;\n rtl::OUString sCurrentSheetName;\n ::boost::ptr_vector<ScMyTableData> maTables;\n ScXMLTabProtectionData maProtectionData;\n ScMyMatrixRangeList aMatrixRangeList;\n com::sun::star::table::CellAddress aRealCellPos;\n sal_Int32 nCurrentColStylePos;\n sal_Int16 nCurrentDrawPage;\n sal_Int16 nCurrentXShapes;\n sal_Int32 nCurrentSheet;\n\n sal_Bool IsMerged (const com::sun::star::uno::Reference <com::sun::star::table::XCellRange>& xCellRange,\n const sal_Int32 nCol, const sal_Int32 nRow,\n com::sun::star::table::CellRangeAddress& aCellAddress) const;\n void UnMerge();\n void DoMerge(sal_Int32 nCount = -1);\n void InsertRow();\n void NewRow();\n void InsertColumn();\n void NewColumn(sal_Bool bIsCovered);\npublic:\n ScMyTables(ScXMLImport& rImport);\n ~ScMyTables();\n void NewSheet(const rtl::OUString& sTableName, const rtl::OUString& sStyleName,\n const ScXMLTabProtectionData& rProtectData);\n void AddRow();\n void SetRowStyle(const rtl::OUString& rCellStyleName);\n void AddColumn(sal_Bool bIsCovered);\n void NewTable(sal_Int32 nTempSpannedCols);\n void UpdateRowHeights();\n void ResizeShapes() { aResizeShapes.ResizeShapes(); }\n void DeleteTable();\n com::sun::star::table::CellAddress GetRealCellPos();\n void AddColCount(sal_Int32 nTempColCount);\n void AddColStyle(const sal_Int32 nRepeat, const rtl::OUString& rCellStyleName);\n ScXMLTabProtectionData& GetCurrentProtectionData() { return maProtectionData; }\n rtl::OUString GetCurrentSheetName() const { return sCurrentSheetName; }\n sal_Int32 GetCurrentSheet() const { return nCurrentSheet; }\n sal_Int32 GetCurrentColumn() const { return maTables.back().GetColCount(); }\n sal_Int32 GetCurrentRow() const { return maTables.back().GetRow(); }\n ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet >\n GetCurrentXSheet() const { return xCurrentSheet; }\n ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange >\n GetCurrentXCellRange() const { return xCurrentCellRange; }\n ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >\n GetCurrentXDrawPage();\n ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >\n GetCurrentXShapes();\n sal_Bool HasDrawPage();\n sal_Bool HasXShapes();\n void AddShape(com::sun::star::uno::Reference <com::sun::star::drawing::XShape>& rShape,\n rtl::OUString* pRangeList,\n com::sun::star::table::CellAddress& rStartAddress,\n com::sun::star::table::CellAddress& rEndAddress,\n sal_Int32 nEndX, sal_Int32 nEndY);\n\n void AddMatrixRange( sal_Int32 nStartColumn,\n sal_Int32 nStartRow,\n sal_Int32 nEndColumn,\n sal_Int32 nEndRow,\n const rtl::OUString& rFormula,\n const rtl::OUString& rFormulaNmsp,\n const formula::FormulaGrammar::Grammar );\n\n sal_Bool IsPartOfMatrix(sal_Int32 nColumn, sal_Int32 nRow);\n void SetMatrix( const com::sun::star::table::CellRangeAddress& rRange,\n const rtl::OUString& rFormula,\n const rtl::OUString& rFormulaNmsp,\n const formula::FormulaGrammar::Grammar );\n};\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#705689: fix memory leak<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2010, The Mineserver Project\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 met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the The Mineserver Project nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY 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\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <deque>\n#include <fstream>\n#include <vector>\n#include <ctime>\n#include <math.h>\n#ifdef WIN32\n #include <winsock2.h>\n#else\n #include <netinet\/in.h>\n #include <string.h>\n#endif\n\n#include \"logger.h\"\n#include \"constants.h\"\n\n#include \"tools.h\"\n#include \"map.h\"\n#include \"user.h\"\n#include \"chat.h\"\n#include \"config.h\"\n#include \"physics.h\"\n\n\nChat &Chat::get()\n{\n static Chat instance;\n return instance;\n}\n\nChat::Chat()\n{\n registerStandardCommands();\n}\n\nvoid Chat::registerCommand(std::string name, ChatCommand command, bool adminOnly)\n{\n if(adminOnly)\n adminCommands[name] = command;\n else\n userCommands[name] = command;\n}\n\nbool Chat::checkMotd(std::string motdFile)\n{\n \/\/\n \/\/ Create motdfile is it doesn't exist\n \/\/\n std::ifstream ifs(motdFile.c_str());\n\n \/\/ If file does not exist\n if(ifs.fail())\n {\n std::cout << \"> Warning: \" << motdFile << \" not found. Creating...\" << std::endl;\n\n std::ofstream motdofs(motdFile.c_str());\n motdofs << DEFAULTMOTDFILE << std::endl;\n motdofs.close();\n }\n\n ifs.close();\n\n return true;\n}\n\nbool Chat::loadAdmins(std::string adminFile)\n{\n \/\/ Clear current admin-vector\n admins.clear();\n\n \/\/ Read admins to deque\n std::ifstream ifs(adminFile.c_str());\n\n \/\/ If file does not exist\n if(ifs.fail())\n {\n std::cout << \"> Warning: \" << adminFile << \" not found. Creating...\" << std::endl;\n\n std::ofstream adminofs(adminFile.c_str());\n adminofs << DEFAULTADMINFILE << std::endl;\n adminofs.close();\n\n return true;\n }\n\n std::string temp;\n while(getline(ifs, temp))\n {\n \/\/ If not commentline\n if(temp[0] != COMMENTPREFIX)\n admins.push_back(temp);\n }\n ifs.close();\n\n std::cout << \"Loaded admins from \" << adminFile << std::endl;\n\n return true;\n}\n\nbool Chat::sendUserlist(User *user)\n{\n this->sendMsg(user, COLOR_BLUE + \"[ Players online ]\", USER);\n\n for(unsigned int i = 0; i < Users.size(); i++)\n {\n this->sendMsg(user, \"> \" + Users[i]->nick, USER);\n }\n\n return true;\n}\n\nstd::deque<std::string> Chat::parseCmd(std::string cmd)\n{\n int del;\n std::deque<std::string> temp;\n\n while(cmd.length() > 0)\n {\n while(cmd[0] == ' ')\n cmd = cmd.substr(1);\n\n del = cmd.find(' ');\n\n if(del > -1)\n {\n temp.push_back(cmd.substr(0, del));\n cmd = cmd.substr(del+1);\n }\n else\n {\n temp.push_back(cmd);\n break;\n }\n }\n\n if(temp.empty())\n temp.push_back(\"empty\");\n\n return temp;\n}\n\nbool Chat::handleMsg(User *user, std::string msg)\n{\n \/\/ Timestamp\n time_t rawTime = time(NULL);\n struct tm *Tm = localtime(&rawTime);\n\n std::string timeStamp (asctime(Tm));\n timeStamp = timeStamp.substr(11, 5);\n\n \/\/\n \/\/ Chat commands\n \/\/\n\n \/\/ Servermsg (Admin-only)\n if(msg[0] == SERVERMSGPREFIX && user->admin)\n {\n \/\/ Decorate server message\n msg = COLOR_RED + \"[!] \" + COLOR_GREEN + msg.substr(1);\n this->sendMsg(user, msg, ALL);\n }\n\n \/\/ Adminchat\n else if(msg[0] == ADMINCHATPREFIX && user->admin)\n {\n msg = timeStamp + \" @@ <\"+ COLOR_DARK_MAGENTA + user->nick + COLOR_WHITE + \"> \" + msg.substr(1);\n this->sendMsg(user, msg, ADMINS);\n }\n\n \/\/ Command\n else if(msg[0] == CHATCMDPREFIX)\n {\n std::deque<std::string> cmd = this->parseCmd(msg.substr(1));\n\n std::string command = cmd[0];\n cmd.pop_front();\n\n \/\/ User commands\n CommandList::iterator iter;\n if((iter = userCommands.find(command)) != userCommands.end())\n iter->second(user, command, cmd);\n else if(user->admin && (iter = adminCommands.find(command)) != adminCommands.end())\n iter->second(user, command, cmd);\n }\n \/\/ Normal message\n else\n {\n if(user->admin)\n msg = timeStamp + \" <\"+ COLOR_DARK_MAGENTA + user->nick + COLOR_WHITE + \"> \" + msg;\n else\n msg = timeStamp + \" <\"+ user->nick + \"> \" + msg;\n\n LOG(msg);\n\n this->sendMsg(user, msg, ALL);\n }\n\n return true;\n}\n\nbool Chat::sendMsg(User *user, std::string msg, MessageTarget action)\n{\n size_t tmpArrayLen = msg.size()+3;\n uint8 *tmpArray = new uint8[tmpArrayLen];\n\n tmpArray[0] = 0x03;\n tmpArray[1] = 0;\n tmpArray[2] = msg.size()&0xff;\n\n for(unsigned int i = 0; i < msg.size(); i++)\n tmpArray[i+3] = msg[i];\n\n switch(action)\n {\n case ALL:\n user->sendAll(tmpArray, tmpArrayLen);\n break;\n\n case USER:\n user->buffer.addToWrite(tmpArray, tmpArrayLen);\n break;\n\n case ADMINS:\n user->sendAdmins(tmpArray, tmpArrayLen);\n break;\n\n case OTHERS:\n user->sendOthers(tmpArray, tmpArrayLen);\n break;\n }\n\n delete[] tmpArray;\n\n return true;\n}\n<commit_msg>ban + whitelist<commit_after>\/*\n Copyright (c) 2010, The Mineserver Project\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 met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the The Mineserver Project nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY 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\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <deque>\n#include <fstream>\n#include <vector>\n#include <ctime>\n#include <math.h>\n#ifdef WIN32\n #include <winsock2.h>\n#else\n #include <netinet\/in.h>\n #include <string.h>\n#endif\n\n#include \"logger.h\"\n#include \"constants.h\"\n\n#include \"tools.h\"\n#include \"map.h\"\n#include \"user.h\"\n#include \"chat.h\"\n#include \"config.h\"\n#include \"physics.h\"\n\n\nChat &Chat::get()\n{\n static Chat instance;\n return instance;\n}\n\nChat::Chat()\n{\n registerStandardCommands();\n}\n\nvoid Chat::registerCommand(std::string name, ChatCommand command, bool adminOnly)\n{\n if(adminOnly)\n adminCommands[name] = command;\n else\n userCommands[name] = command;\n}\n\nbool Chat::checkMotd(std::string motdFile)\n{\n \/\/\n \/\/ Create motdfile is it doesn't exist\n \/\/\n std::ifstream ifs(motdFile.c_str());\n\n \/\/ If file does not exist\n if(ifs.fail())\n {\n std::cout << \"> Warning: \" << motdFile << \" not found. Creating...\" << std::endl;\n\n std::ofstream motdofs(motdFile.c_str());\n motdofs << DEFAULTMOTDFILE << std::endl;\n motdofs.close();\n }\n\n ifs.close();\n\n return true;\n}\n\nbool Chat::loadAdmins(std::string adminFile)\n{\n \/\/ Clear current admin-vector\n admins.clear();\n\n \/\/ Read admins to deque\n std::ifstream ifs(adminFile.c_str());\n\n \/\/ If file does not exist\n if(ifs.fail())\n {\n std::cout << \"> Warning: \" << adminFile << \" not found. Creating...\" << std::endl;\n\n std::ofstream adminofs(adminFile.c_str());\n adminofs << DEFAULTADMINFILE << std::endl;\n adminofs.close();\n\n return true;\n }\n\n std::string temp;\n while(getline(ifs, temp))\n {\n \/\/ If not commentline\n if(temp[0] != COMMENTPREFIX)\n admins.push_back(temp);\n }\n ifs.close();\n\n std::cout << \"Loaded admins from \" << adminFile << std::endl;\n\n return true;\n}\n\nbool Chat::loadBanned(std::string bannedFile)\n{\n \/\/ Clear current banned-vector\n banned.clear();\n\n \/\/ Read banned to deque\n std::ifstream ifs(bannedFile.c_str());\n\n \/\/ If file does not exist\n if(ifs.fail())\n {\n std::cout << \"> Warning: \" << bannedFile << \" not found. Creating...\" << std::endl;\n\n std::ofstream bannedofs(bannedFile.c_str());\n bannedofs << DEFAULTBANNEDFILE << std::endl;\n bannedofs.close();\n\n return true;\n }\n\n std::string temp;\n while(getline(ifs, temp))\n {\n \/\/ If not commentline\n if(temp[0] != COMMENTPREFIX)\n banned.push_back(temp);\n }\n ifs.close();\n\n std::cout << \"Loaded banned users from \" << bannedFile << std::endl;\n\n return true;\n}\n\nbool Chat::loadWhitelist(std::string whitelistFile)\n{\n \/\/ Clear current whitelist-vector\n whitelist.clear();\n\n \/\/ Read whitelist to deque\n std::ifstream ifs(whitelistFile.c_str());\n\n \/\/ If file does not exist\n if(ifs.fail())\n {\n std::cout << \"> Warning: \" << whitelistFile << \" not found. Creating...\" << std::endl;\n\n std::ofstream whitelistofs(whitelistFile.c_str());\n whitelistofs << DEFAULTWHITELISTFILE << std::endl;\n whitelistofs.close();\n\n return true;\n }\n\n std::string temp;\n while(getline(ifs, temp))\n {\n \/\/ If not commentline\n if(temp[0] != COMMENTPREFIX)\n whitelist.push_back(temp);\n }\n ifs.close();\n\n std::cout << \"Loaded whitelisted users from \" << whitelistFile << std::endl;\n\n return true;\n}\n\nbool Chat::sendUserlist(User *user)\n{\n this->sendMsg(user, COLOR_BLUE + \"[ Players online ]\", USER);\n\n for(unsigned int i = 0; i < Users.size(); i++)\n {\n this->sendMsg(user, \"> \" + Users[i]->nick, USER);\n }\n\n return true;\n}\n\nstd::deque<std::string> Chat::parseCmd(std::string cmd)\n{\n int del;\n std::deque<std::string> temp;\n\n while(cmd.length() > 0)\n {\n while(cmd[0] == ' ')\n cmd = cmd.substr(1);\n\n del = cmd.find(' ');\n\n if(del > -1)\n {\n temp.push_back(cmd.substr(0, del));\n cmd = cmd.substr(del+1);\n }\n else\n {\n temp.push_back(cmd);\n break;\n }\n }\n\n if(temp.empty())\n temp.push_back(\"empty\");\n\n return temp;\n}\n\nbool Chat::handleMsg(User *user, std::string msg)\n{\n \/\/ Timestamp\n time_t rawTime = time(NULL);\n\n struct tm *Tm = localtime(&rawTime);\n\n std::string timeStamp (asctime(Tm));\n timeStamp = timeStamp.substr(11, 5);\n\n \/\/\n \/\/ Chat commands\n \/\/\n\n \/\/ Servermsg (Admin-only)\n if(msg[0] == SERVERMSGPREFIX && user->admin)\n {\n \/\/ Decorate server message\n msg = COLOR_RED + \"[!] \" + COLOR_GREEN + msg.substr(1);\n this->sendMsg(user, msg, ALL);\n }\n\n \/\/ Adminchat\n else if(msg[0] == ADMINCHATPREFIX && user->admin)\n {\n msg = timeStamp + \" @@ <\"+ COLOR_DARK_MAGENTA + user->nick + COLOR_WHITE + \"> \" + msg.substr(1);\n this->sendMsg(user, msg, ADMINS);\n }\n\n \/\/ Command\n else if(msg[0] == CHATCMDPREFIX)\n {\n std::deque<std::string> cmd = this->parseCmd(msg.substr(1));\n\n std::string command = cmd[0];\n cmd.pop_front();\n\n \/\/ User commands\n CommandList::iterator iter;\n if((iter = userCommands.find(command)) != userCommands.end())\n iter->second(user, command, cmd);\n else if(user->admin && (iter = adminCommands.find(command)) != adminCommands.end())\n iter->second(user, command, cmd);\n }\n \/\/ Normal message\n else\n {\n if(user->admin)\n msg = timeStamp + \" <\"+ COLOR_DARK_MAGENTA + user->nick + COLOR_WHITE + \"> \" + msg;\n else\n msg = timeStamp + \" <\"+ user->nick + \"> \" + msg;\n\n LOG(msg);\n\n this->sendMsg(user, msg, ALL);\n }\n\n return true;\n}\n\nbool Chat::sendMsg(User *user, std::string msg, MessageTarget action)\n{\n size_t tmpArrayLen = msg.size()+3;\n uint8 *tmpArray = new uint8[tmpArrayLen];\n\n tmpArray[0] = 0x03;\n tmpArray[1] = 0;\n tmpArray[2] = msg.size()&0xff;\n\n for(unsigned int i = 0; i < msg.size(); i++)\n tmpArray[i+3] = msg[i];\n\n switch(action)\n {\n case ALL:\n user->sendAll(tmpArray, tmpArrayLen);\n break;\n\n case USER:\n user->buffer.addToWrite(tmpArray, tmpArrayLen);\n break;\n\n case ADMINS:\n user->sendAdmins(tmpArray, tmpArrayLen);\n break;\n\n case OTHERS:\n user->sendOthers(tmpArray, tmpArrayLen);\n break;\n }\n\n delete[] tmpArray;\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Python.h>\n#include \"Quantuccia\/ql\/time\/calendar.hpp\"\n#include \"Quantuccia\/ql\/time\/date.hpp\"\n#include \"Quantuccia\/ql\/time\/calendars\/unitedkingdom.hpp\"\n\nstatic PyObject*\nunited_kingdom_is_business_day(PyObject *self, PyObject *args)\n{\n\tint year;\n\tint month;\n\tint day;\n if (!PyArg_ParseTuple(args, \"bbb|\", &year, &month, &day))\n return NULL;\n\tQuantLib::Day d = QuantLib::Day(day);\n\tQuantLib::Month m = QuantLib::Month(month);\n\tQuantLib::Year y = QuantLib::Year(year);\n\tQuantLib::Date date = QuantLib::Date(d, m, y);\n\tQuantLib::Calendar calendar = QuantLib::UnitedKingdom::UnitedKingdom(QuantLib::UnitedKingdom::Market::Exchange);\n return PyBool_FromLong(calendar.isBusinessDay(date));\n}\n \nstatic PyMethodDef QuantucciaMethods[] = {\n\t{\"united_kingdom_is_business_day\", (PyCFunction)united_kingdom_is_business_day, METH_VARARGS, NULL},\n\t{NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef quantuccia_module_def = {\n\tPyModuleDef_HEAD_INIT,\n\t\"quantuccia\",\n\tNULL,\n\t-1,\n\tQuantucciaMethods,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL\n};\n\nPyMODINIT_FUNC PyInit_quantuccia(void){\n PyObject *m;\n m = PyModule_Create(&quantuccia_module_def);\n return m;\n}\n<commit_msg>Add missing 'new's.<commit_after>#include <Python.h>\n#include \"Quantuccia\/ql\/time\/calendar.hpp\"\n#include \"Quantuccia\/ql\/time\/date.hpp\"\n#include \"Quantuccia\/ql\/time\/calendars\/unitedkingdom.hpp\"\n\nstatic PyObject*\nunited_kingdom_is_business_day(PyObject *self, PyObject *args)\n{\n\tint year;\n\tint month;\n\tint day;\n if (!PyArg_ParseTuple(args, \"bbb|\", &year, &month, &day))\n return NULL;\n\tQuantLib::Day d = new QuantLib::Day(day);\n\tQuantLib::Month m = new QuantLib::Month(month);\n\tQuantLib::Year y = new QuantLib::Year(year);\n\tQuantLib::Date date = new QuantLib::Date(d, m, y);\n\tQuantLib::Calendar calendar = new QuantLib::UnitedKingdom::UnitedKingdom(QuantLib::UnitedKingdom::Market::Exchange);\n return PyBool_FromLong(calendar.isBusinessDay(date));\n}\n \nstatic PyMethodDef QuantucciaMethods[] = {\n\t{\"united_kingdom_is_business_day\", (PyCFunction)united_kingdom_is_business_day, METH_VARARGS, NULL},\n\t{NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef quantuccia_module_def = {\n\tPyModuleDef_HEAD_INIT,\n\t\"quantuccia\",\n\tNULL,\n\t-1,\n\tQuantucciaMethods,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL\n};\n\nPyMODINIT_FUNC PyInit_quantuccia(void){\n PyObject *m;\n m = PyModule_Create(&quantuccia_module_def);\n return m;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#ifndef CONTAINERS_SHARED_BUFFER_HPP_\n#define CONTAINERS_SHARED_BUFFER_HPP_\n\n#include \"containers\/counted.hpp\"\n#include \"containers\/scoped.hpp\"\n#include \"errors.hpp\"\n\n\/* A `shared_buffer_t` is a reference counted binary buffer.\nYou can have multiple `shared_buf_ref_t`s pointing to different offsets in\nthe same `shared_buffer_t`. *\/\nclass shared_buf_t {\npublic:\n shared_buf_t() = delete;\n\n static scoped_ptr_t<shared_buf_t> create(size_t _size);\n static scoped_ptr_t<shared_buf_t> create_and_init(size_t _size, const char *_data);\n static void operator delete(void *p);\n\n char *data(size_t offset = 0);\n const char *data(size_t offset = 0) const;\n\nprivate:\n \/\/ We duplicate the implementation of slow_atomic_countable_t here for the\n \/\/ sole purpose of having full control over the layout of fields. This\n \/\/ is required because we manually allocate memory for the data field,\n \/\/ and C++ doesn't guarantee any specific field memory layout under inheritance\n \/\/ (as far as I know).\n friend void counted_add_ref(const shared_buf_t *p);\n friend void counted_release(const shared_buf_t *p);\n friend intptr_t counted_use_count(const shared_buf_t *p);\n\n mutable intptr_t refcount_;\n \/\/ We actually allocate more memory than this.\n \/\/ It's crucial that this field is the last one in this class.\n char data_[1];\n\n DISABLE_COPYING(shared_buf_t);\n};\n\n\n\/* A `shared_buf_ref_t` points at a specific offset of a `shared_buf_t`.\nIt is packed to reduce its memory footprint. Additionally you can specify\na smaller offset_t type if you don't need to access buffers of more than a certain\nsize. *\/\n\/\/ TODO (daniel): This should be templated on the offset type, so we can\n\/\/ save some memory when having buffers of a limited maximum size.\nclass shared_buf_ref_t {\npublic:\n shared_buf_ref_t(const counted_t<const shared_buf_t> &_buf, uint64_t _offset)\n : buf(_buf), offset(_offset) {\n rassert(buf.has());\n }\n shared_buf_ref_t(shared_buf_ref_t &&movee) noexcept\n : buf(std::move(movee.buf)), offset(movee.offset) {\n rassert(buf.has());\n }\n shared_buf_ref_t(const shared_buf_ref_t ©ee) noexcept\n : buf(copyee.buf), offset(copyee.offset) {\n rassert(buf.has());\n }\n shared_buf_ref_t &operator=(shared_buf_ref_t &&movee) noexcept {\n buf = std::move(movee.buf);\n offset = movee.offset;\n rassert(buf.has());\n return *this;\n }\n shared_buf_ref_t &operator=(const shared_buf_ref_t ©ee) noexcept {\n buf = copyee.buf;\n offset = copyee.offset;\n rassert(buf.has());\n return *this;\n }\n const char *get() const {\n rassert(buf.has());\n return buf->data(offset);\n }\nprivate:\n counted_t<const shared_buf_t> buf;\n uint64_t offset;\n} __attribute__((__packed__));\n\n\ninline void counted_add_ref(const shared_buf_t *p) {\n DEBUG_VAR intptr_t res = __sync_add_and_fetch(&p->refcount_, 1);\n rassert(res > 0);\n}\n\ninline void counted_release(const shared_buf_t *p) {\n intptr_t res = __sync_sub_and_fetch(&p->refcount_, 1);\n rassert(res >= 0);\n if (res == 0) {\n delete const_cast<shared_buf_t *>(p);\n }\n}\n\ninline intptr_t counted_use_count(const shared_buf_t *p) {\n \/\/ Finally a practical use for volatile.\n intptr_t tmp = static_cast<const volatile intptr_t&>(p->refcount_);\n rassert(tmp > 0);\n return tmp;\n}\n\n#endif \/\/ CONTAINERS_SHARED_BUFFER_HPP_\n<commit_msg>Fixes a compilation problem on GCC.<commit_after>\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#ifndef CONTAINERS_SHARED_BUFFER_HPP_\n#define CONTAINERS_SHARED_BUFFER_HPP_\n\n#include \"containers\/counted.hpp\"\n#include \"containers\/scoped.hpp\"\n#include \"errors.hpp\"\n\n\/* A `shared_buffer_t` is a reference counted binary buffer.\nYou can have multiple `shared_buf_ref_t`s pointing to different offsets in\nthe same `shared_buffer_t`. *\/\nclass shared_buf_t {\npublic:\n shared_buf_t() = delete;\n\n static scoped_ptr_t<shared_buf_t> create(size_t _size);\n static scoped_ptr_t<shared_buf_t> create_and_init(size_t _size, const char *_data);\n static void operator delete(void *p);\n\n char *data(size_t offset = 0);\n const char *data(size_t offset = 0) const;\n\nprivate:\n \/\/ We duplicate the implementation of slow_atomic_countable_t here for the\n \/\/ sole purpose of having full control over the layout of fields. This\n \/\/ is required because we manually allocate memory for the data field,\n \/\/ and C++ doesn't guarantee any specific field memory layout under inheritance\n \/\/ (as far as I know).\n friend void counted_add_ref(const shared_buf_t *p);\n friend void counted_release(const shared_buf_t *p);\n friend intptr_t counted_use_count(const shared_buf_t *p);\n\n mutable intptr_t refcount_;\n \/\/ We actually allocate more memory than this.\n \/\/ It's crucial that this field is the last one in this class.\n char data_[1];\n\n DISABLE_COPYING(shared_buf_t);\n};\n\n\n\/* A `shared_buf_ref_t` points at a specific offset of a `shared_buf_t`.\nIt is packed to reduce its memory footprint. Additionally you can specify\na smaller offset_t type if you don't need to access buffers of more than a certain\nsize. *\/\n\/\/ TODO (daniel): This should be templated on the offset type, so we can\n\/\/ save some memory when having buffers of a limited maximum size.\nclass shared_buf_ref_t {\npublic:\n shared_buf_ref_t(const counted_t<const shared_buf_t> &_buf, uint64_t _offset)\n : buf(_buf), offset(_offset) {\n rassert(buf.has());\n }\n shared_buf_ref_t(shared_buf_ref_t &&movee) noexcept\n : buf(std::move(movee.buf)), offset(movee.offset) {\n rassert(buf.has());\n }\n shared_buf_ref_t(const shared_buf_ref_t ©ee) noexcept\n : buf(copyee.buf), offset(copyee.offset) {\n rassert(buf.has());\n }\n shared_buf_ref_t &operator=(shared_buf_ref_t &&movee) noexcept {\n buf = std::move(movee.buf);\n offset = movee.offset;\n rassert(buf.has());\n return *this;\n }\n shared_buf_ref_t &operator=(const shared_buf_ref_t ©ee) noexcept {\n buf = copyee.buf;\n offset = copyee.offset;\n rassert(buf.has());\n return *this;\n }\n const char *get() const {\n rassert(buf.has());\n return buf->data(offset);\n }\nprivate:\n counted_t<const shared_buf_t> buf;\n uint64_t offset;\n};\n\n\ninline void counted_add_ref(const shared_buf_t *p) {\n DEBUG_VAR intptr_t res = __sync_add_and_fetch(&p->refcount_, 1);\n rassert(res > 0);\n}\n\ninline void counted_release(const shared_buf_t *p) {\n intptr_t res = __sync_sub_and_fetch(&p->refcount_, 1);\n rassert(res >= 0);\n if (res == 0) {\n delete const_cast<shared_buf_t *>(p);\n }\n}\n\ninline intptr_t counted_use_count(const shared_buf_t *p) {\n \/\/ Finally a practical use for volatile.\n intptr_t tmp = static_cast<const volatile intptr_t&>(p->refcount_);\n rassert(tmp > 0);\n return tmp;\n}\n\n#endif \/\/ CONTAINERS_SHARED_BUFFER_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"asset_manager.hpp\"\n\n#include \"..\/utils\/template_utils.hpp\"\n#include \"..\/utils\/log.hpp\"\n\n#include <physfs\/physfs.h>\n\n#include <cstring>\n#include <cstdio>\n\n#ifdef WIN\n\t#include <windows.h>\n\t#include <direct.h>\n#else\n\t#include <sys\/stat.h>\n\t#include <unistd.h>\n#endif\n\n#ifdef EMSCRIPTEN\n\t#include <emscripten.h>\n#endif\n\nusing namespace lux::util;\n\nnamespace {\n\n\tstd::string append_file(const std::string& folder, const std::string file) {\n\t\tif(ends_with(folder, \"\/\") || starts_with(file, \"\/\"))\n\t\t\treturn folder+file;\n\t\telse\n\t\t\treturn folder+\"\/\"+file;\n\t}\n\tvoid create_dir(const std::string& dir) {\n#ifdef WIN\n\t\tCreateDirectory(dir.c_str(), NULL);\n#else\n\t\tmkdir(dir.c_str(), 0777);\n#endif\n\t}\n\n\tstd::vector<std::string> list_files(\n\t\t\tconst std::string& dir, const std::string& prefix, const std::string& suffix)noexcept {\n\t\tstd::vector<std::string> res;\n\n\t\tchar **rc = PHYSFS_enumerateFiles(dir.c_str());\n\n\t\tfor (char **i = rc; *i != nullptr; i++) {\n\t\t\tstd::string str(*i);\n\t\t\tif( (prefix.length()==0 || str.find(prefix)==0) &&\n\t\t\t\t (suffix.length()==0 || str.find(suffix)==str.length()-suffix.length()) )\n\t\t\t\tres.emplace_back(std::move(str));\n\t\t}\n\n\t\tPHYSFS_freeList(rc);\n\n\t\treturn res;\n\t}\n\n\tbool exists_file(const std::string path) {\n\t\treturn PHYSFS_exists(path.c_str())!=0 && PHYSFS_isDirectory(path.c_str())==0;\n\t}\n\tbool exists_dir(const std::string path) {\n\t\treturn PHYSFS_exists(path.c_str())!=0 && PHYSFS_isDirectory(path.c_str())!=0;\n\t}\n\n\ttemplate<typename Stream>\n\tvoid print_dir_recursiv(const std::string& dir, uint8_t depth, Stream& stream) {\n\t\tstd::string p;\n\t\tfor(uint8_t i=0; i<depth; i++)\n\t\t\tp+=\" \";\n\n\t\tstream<<p<<dir<<\"\\n\";\n\t\tdepth++;\n\t\tfor(auto&& f : list_files(dir, \"\", \"\")) {\n\t\t\tif(depth>=5)\n\t\t\t\tstream<<p<<\" \"<<f<<\"\\n\";\n\t\t\telse\n\t\t\t\tprint_dir_recursiv(f, depth, stream);\n\t\t}\n\t}\n\n\tconstexpr auto default_source = {std::make_tuple(\"assets\", false), std::make_tuple(\"assets.zip\", true)};\n}\n\nnamespace lux {\nnamespace asset {\n\n\tstd::string pwd() {\n\t\tchar cCurrentPath[FILENAME_MAX];\n\n\t\t#ifdef WINDOWS\n\t\t\t_getcwd(cCurrentPath, sizeof(cCurrentPath));\n\t\t#else\n\t\t\tgetcwd(cCurrentPath, sizeof(cCurrentPath));\n\t\t#endif\n\n\t\treturn cCurrentPath;\n\t}\n\n\tstatic Asset_manager* current_instance = nullptr;\n\tauto get_asset_manager() -> Asset_manager& {\n\t\tINVARIANT(current_instance!=nullptr, \"Asset_manager has not been initialized!\");\n\t\treturn *current_instance;\n\t}\n\n\tAsset_manager::Asset_manager(const std::string& exe_name, const std::string& app_name) {\n\t\tif(!PHYSFS_init(exe_name.empty() ? nullptr : exe_name.c_str()))\n\t\t\tFAIL(\"PhysFS-Init failed for \\\"\"<<exe_name<<\"\\\": \"<< PHYSFS_getLastError());\n\n\t\t\/\/ TODO: Windows savegames should be stored in FOLDERID_SavedGames, but the API and conventions are a pain in the ass\n\t\tstd::string write_dir_parent = append_file(PHYSFS_getUserDir(),\n#ifdef WIN\n\t\t\t\"Documents\/My Games\"\n#else\n\t\t\t\".config\"\n#endif\n\t\t);\n\n#ifdef EMSCRIPTEN\n\t\tEM_ASM(\n\t\t\tFS.mkdir('\/persistent_data');\n\t\t\tFS.mount(IDBFS, {}, '\/persistent_data');\n\n\t\t\tModule.syncdone = 0;\n\n\t\t\t\/\/populate persistent_data directory with existing persistent source data\n\t\t\t\/\/stored with Indexed Db\n\t\t\t\/\/first parameter = \"true\" mean synchronize from Indexed Db to\n\t\t\t\/\/Emscripten file system,\n\t\t\t\/\/ \"false\" mean synchronize from Emscripten file system to Indexed Db\n\t\t\t\/\/second parameter = function called when data are synchronized\n\t\t\tFS.syncfs(true, function(err) {\n\t\t\t\t\/\/assert(!err);\n\t\t\t\tModule.print(\"end file sync..\");\n\t\t\t\tModule.syncdone = 1;\n\t\t\t});\n\t\t);\n\t\twrite_dir_parent = \"\/persistent_data\";\n#endif\n\n\t\tcreate_dir(write_dir_parent);\n\n\t\tstd::string write_dir = append_file(write_dir_parent, app_name);\n\t\tcreate_dir(write_dir);\n\n\t\tINFO(\"Write dir: \"<<write_dir);\n\n\t\tif(!PHYSFS_addToSearchPath(PHYSFS_getBaseDir(), 1) ||\n\t\t\t\t!PHYSFS_addToSearchPath(append_file(PHYSFS_getBaseDir(), \"..\").c_str(), 1) ||\n\t\t\t\t!PHYSFS_addToSearchPath(pwd().c_str(), 1) ||\n\t\t\t\t!PHYSFS_addToSearchPath(write_dir.c_str(), 0))\n\t\t\tFAIL(\"Unable to construct search path: \"<< PHYSFS_getLastError());\n\t\t\n\t\t\/\/ add optional search path\n\t\tPHYSFS_addToSearchPath(append_file(append_file(append_file(PHYSFS_getBaseDir(), \"..\"), \"magnum_opus\"), \"assets\").c_str(), 1);\n\n\t\tif(!PHYSFS_setWriteDir(write_dir.c_str()))\n\t\t\tFAIL(\"Unable to set write-dir to \\\"\"<<write_dir<<\"\\\": \"<< PHYSFS_getLastError());\n\n\n\t\tauto add_source = [](const char* path){\n\t\t\tif(!PHYSFS_addToSearchPath(path, 1))\n\t\t\t\tWARN(\"Error adding custom archive \\\"\"<<path<<\"\\\": \"<<PHYSFS_getLastError());\n\t\t};\n\n\t\tauto archive_file = _open(\"archives.lst\");\n\t\tif(!archive_file) {\n\t\t\tbool lost = true;\n\t\t\tfor(auto& s : default_source) {\n\t\t\t\tconst char* path;\n\t\t\t\tbool file;\n\n\t\t\t\tstd::tie(path, file) = s;\n\n\t\t\t\tif(file ? exists_file(path) : exists_dir(path)) {\n\t\t\t\t\tadd_source(path);\n\t\t\t\t\tlost = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(lost) {\n\t\t\t\tauto& log = util::fail (__func__, __FILE__, __LINE__);\n\t\t\t\tlog<<\"No archives.lst found. printing search-path...\\n\";\n\t\t\t\tprint_dir_recursiv(\"\/\", 0, log);\n\n\t\t\t\tlog<<std::endl; \/\/ crash with error\n\n\t\t\t} else {\n\t\t\t\tINFO(\"No archives.lst found. Using defaults.\");\n\t\t\t}\n\n\t\t} else {\n\t\t\t\/\/ load other archives\n\t\t\tarchive_file.process([&](istream& in) {\n\t\t\t\tfor(auto&& l : in.lines()) {\n\t\t\t\t\tadd_source(l.c_str());\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tfor(auto&& df : list_files(\"\", \"assets\", \".map\")) {\n\t\t\t_open(df).process([this](istream& in) {\n\t\t\t\tfor(auto&& l : in.lines()) {\n\t\t\t\t\tauto kvp =\tutil::split(l, \"=\");\n\t\t\t\t\tstd::string path = util::trim_copy(kvp.second);\n\t\t\t\t\tif(!path.empty()) {\n\t\t\t\t\t\t_dispatcher.emplace(AID{kvp.first}, std::move(path));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tcurrent_instance = this;\n\t}\n\n\tAsset_manager::~Asset_manager() {\n\t\tcurrent_instance = nullptr;\n\t\t_assets.clear();\n\t\tPHYSFS_deinit();\n\t}\n\n\tvoid Asset_manager::_post_write() {\n#ifdef EMSCRIPTEN\n\t\t\/\/persist Emscripten current data to Indexed Db\n\t\tEM_ASM(\n\t\t\tFS.syncfs(false,function (err) {\n\t\t\t\t\/\/assert(!err);\n\t\t\t});\n\t\t);\n#endif\n\t}\n\n\tutil::maybe<std::string> Asset_manager::_base_dir(Asset_type type)const {\n\t\tauto dir = _dispatcher.find(AID{type, \"\"}); \/\/ search for prefix-entry\n\n\t\tif(dir==_dispatcher.end())\n\t\t\treturn util::nothing();\n\n\t\tstd::string bdir = dir->second;\n\t\treturn bdir;\n\t}\n\n\tstd::vector<AID> Asset_manager::list(Asset_type type) {\n\t\tstd::vector<AID> res;\n\n\t\t_base_dir(type).process([&](const std::string& dir){\n\t\t\tfor(auto&& f : list_files(dir, \"\", \"\"))\n\t\t\t\tres.emplace_back(type, f);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tutil::maybe<istream> Asset_manager::_open(const std::string& path) {\n\t\treturn _open(path, AID{\"gen\"_strid, path});\n\t}\n\tutil::maybe<istream> Asset_manager::_open(const std::string& path, const AID& aid) {\n\t\treturn exists_file(path) ? util::just(istream{aid, *this, path}) : util::nothing();\n\t}\n\n\tAsset_manager::Asset::Asset(std::shared_ptr<void> data, Reloader reloader, int64_t last_modified)\n\t\t: data(data), reloader(reloader), last_modified(last_modified) {}\n\n\tvoid Asset_manager::_add_asset(const AID& id, const std::string& path,\n\t Reloader reloader, std::shared_ptr<void> asset) {\n\t\t_assets.emplace(id, Asset{asset, reloader, PHYSFS_getLastModTime(path.c_str())});\n\t}\n\n\tauto Asset_manager::_locate(const AID& id, bool warn)const -> std::tuple<Location_type, std::string> {\n\t\tauto res = _dispatcher.find(id);\n\n\t\tif(res!=_dispatcher.end()) {\n\t\t\tif(exists_file(res->second))\n\t\t\t\treturn std::make_tuple(Location_type::file, res->second);\n\t\t\telse if(util::contains(res->second, \":\"))\n\t\t\t\treturn std::make_tuple(Location_type::indirection, res->second);\n\t\t\telse if(warn)\n\t\t\t\tINFO(\"Asset not found in configured place: \"<<res->second);\n\t\t}\n\n\t\tif(exists_file(id.name()))\n\t\t\treturn std::make_tuple(Location_type::file, id.name());\n\n\t\tauto baseDir = _base_dir(id.type());\n\n\t\tif(baseDir.is_some()) {\n\t\t\tauto path = append_file(baseDir.get_or_throw(), id.name());\n\t\t\tif(exists_file(path))\n\t\t\t\treturn std::make_tuple(Location_type::file, std::move(path));\n\t\t\telse if(warn)\n\t\t\t\tDEBUG(\"asset \"<<id.str()<<\" not found in \"<<path);\n\t\t}\n\n\t\treturn std::make_tuple(Location_type::none, std::string());\n\t}\n\n\tostream Asset_manager::_create(const AID& id) throw(Loading_failed) {\n\t\tstd::string path;\n\n\t\tauto path_res = _dispatcher.find(id);\n\t\tif(path_res!=_dispatcher.end())\n\t\t\tpath = path_res->second;\n\n\t\telse {\n\t\t\tauto res = _dispatcher.find(AID{id.type(), \"\"}); \/\/ search for prefix-entry\n\n\t\t\tif(res!=_dispatcher.end()) {\n\t\t\t\tPHYSFS_mkdir(res->second.c_str());\n\t\t\t\tpath = append_file(res->second, id.name());\n\t\t\t} else {\n\t\t\t\tpath = id.name();\n\t\t\t}\n\t\t}\n\n\t\tif(exists_file(path))\n\t\t\tPHYSFS_delete(path.c_str());\n\n\t\treturn {id, *this, path};\n\t}\n\n\tauto Asset_manager::physical_location(const AID& id, bool warn)const noexcept -> util::maybe<std::string>{\n\t\tusing namespace std::literals;\n\n\t\tLocation_type type;\n\t\tstd::string location;\n\t\tstd::tie(type, location) = _locate(id, warn);\n\n\t\tif(type!=Location_type::file)\n\t\t\treturn util::nothing();\n\n\t\tauto dir = PHYSFS_getRealDir(location.c_str());\n\t\tif(!dir)\n\t\t\treturn util::nothing();\n\n\t\tauto file = dir + \"\/\"s + location;\n\t\treturn exists_file(file) ? util::just(std::move(file)) : util::nothing();\n\t}\n\n\tvoid Asset_manager::reload() {\n\t\tfor(auto& a : _assets) {\n\t\t\tLocation_type type;\n\t\t\tstd::string location;\n\t\t\tstd::tie(type, location) = _locate(a.first);\n\n\t\t\tif(type==Location_type::file) {\n\t\t\t\tauto last_mod = PHYSFS_getLastModTime(location.c_str());\n\t\t\t\tif(last_mod!=-1 && last_mod>a.second.last_modified) {\n\t\t\t\t\t_open(location, a.first).process([&](istream& in){\n\t\t\t\t\t\tDEBUG(\"Reload: \"<<a.first.str());\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\ta.second.reloader(a.second.data.get(), std::move(in));\n\n\t\t\t\t\t\t} catch(Loading_failed& e) {}\n\n\t\t\t\t\t\ta.second.last_modified = last_mod;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Asset_manager::shrink_to_fit()noexcept {\n\t\tutil::erase_if(_assets, [](const auto& v){return v.second.data.use_count()<=1;});\n\t}\n\n\tbool Asset_manager::exists(const AID& id)const noexcept {\n\t\tLocation_type type;\n\t\tstd::string location;\n\t\tstd::tie(type, location) = _locate(id);\n\n\t\tswitch(type) {\n\t\t\tcase Location_type::none:\n\t\t\t\treturn false;\n\n\t\t\tcase Location_type::file:\n\t\t\t\treturn exists_file(location);\n\n\t\t\tcase Location_type::indirection:\n\t\t\t\treturn true;\n\t\t}\n\n\t\tFAIL(\"Unexpected Location_type: \"<<(int)type);\n\t}\n\n\tauto Asset_manager::load_raw(const AID& id) -> util::maybe<istream> {\n\t\tLocation_type type;\n\t\tstd::string path;\n\t\tstd::tie(type, path) = _locate(id);\n\n\t\tif(type!=Location_type::file)\n\t\t\treturn util::nothing();\n\n\t\treturn _open(path, id);\n\t}\n\tauto Asset_manager::save_raw(const AID& id) -> ostream {\n\t\t_assets.erase(id);\n\t\treturn _create(id);\n\t}\n\n\tauto Asset_manager::find_by_path(const std::string& path) -> util::maybe<AID> {\n\t\tstatic const auto working_dir = util::replace(pwd(), \"\\\\\", \"\/\");\n\t\tauto path_cleared = util::replace(path,working_dir+\"\/\", \"\");\n\n\t\tfor(auto& aid_path : _dispatcher) {\n\t\t\tauto loc = physical_location(aid_path.first, false);\n\t\t\tif(loc.is_some()) {\n\t\t\t\tif(loc.get_or_throw()==path_cleared) {\n\t\t\t\t\treturn util::justCopy(aid_path.first);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tDEBUG(\"Couldn't finde asset for '\"<<path_cleared<<\"'\");\n\n\t\treturn util::nothing();\n\t}\n\n} \/* namespace asset *\/\n}\n<commit_msg>fixed backslashes in find_by_path<commit_after>#include \"asset_manager.hpp\"\n\n#include \"..\/utils\/template_utils.hpp\"\n#include \"..\/utils\/log.hpp\"\n\n#include <physfs\/physfs.h>\n\n#include <cstring>\n#include <cstdio>\n\n#ifdef WIN\n\t#include <windows.h>\n\t#include <direct.h>\n#else\n\t#include <sys\/stat.h>\n\t#include <unistd.h>\n#endif\n\n#ifdef EMSCRIPTEN\n\t#include <emscripten.h>\n#endif\n\nusing namespace lux::util;\n\nnamespace {\n\n\tstd::string append_file(const std::string& folder, const std::string file) {\n\t\tif(ends_with(folder, \"\/\") || starts_with(file, \"\/\"))\n\t\t\treturn folder+file;\n\t\telse\n\t\t\treturn folder+\"\/\"+file;\n\t}\n\tvoid create_dir(const std::string& dir) {\n#ifdef WIN\n\t\tCreateDirectory(dir.c_str(), NULL);\n#else\n\t\tmkdir(dir.c_str(), 0777);\n#endif\n\t}\n\n\tstd::vector<std::string> list_files(\n\t\t\tconst std::string& dir, const std::string& prefix, const std::string& suffix)noexcept {\n\t\tstd::vector<std::string> res;\n\n\t\tchar **rc = PHYSFS_enumerateFiles(dir.c_str());\n\n\t\tfor (char **i = rc; *i != nullptr; i++) {\n\t\t\tstd::string str(*i);\n\t\t\tif( (prefix.length()==0 || str.find(prefix)==0) &&\n\t\t\t\t (suffix.length()==0 || str.find(suffix)==str.length()-suffix.length()) )\n\t\t\t\tres.emplace_back(std::move(str));\n\t\t}\n\n\t\tPHYSFS_freeList(rc);\n\n\t\treturn res;\n\t}\n\n\tbool exists_file(const std::string path) {\n\t\treturn PHYSFS_exists(path.c_str())!=0 && PHYSFS_isDirectory(path.c_str())==0;\n\t}\n\tbool exists_dir(const std::string path) {\n\t\treturn PHYSFS_exists(path.c_str())!=0 && PHYSFS_isDirectory(path.c_str())!=0;\n\t}\n\n\ttemplate<typename Stream>\n\tvoid print_dir_recursiv(const std::string& dir, uint8_t depth, Stream& stream) {\n\t\tstd::string p;\n\t\tfor(uint8_t i=0; i<depth; i++)\n\t\t\tp+=\" \";\n\n\t\tstream<<p<<dir<<\"\\n\";\n\t\tdepth++;\n\t\tfor(auto&& f : list_files(dir, \"\", \"\")) {\n\t\t\tif(depth>=5)\n\t\t\t\tstream<<p<<\" \"<<f<<\"\\n\";\n\t\t\telse\n\t\t\t\tprint_dir_recursiv(f, depth, stream);\n\t\t}\n\t}\n\n\tconstexpr auto default_source = {std::make_tuple(\"assets\", false), std::make_tuple(\"assets.zip\", true)};\n}\n\nnamespace lux {\nnamespace asset {\n\n\tstd::string pwd() {\n\t\tchar cCurrentPath[FILENAME_MAX];\n\n\t\t#ifdef WINDOWS\n\t\t\t_getcwd(cCurrentPath, sizeof(cCurrentPath));\n\t\t#else\n\t\t\tgetcwd(cCurrentPath, sizeof(cCurrentPath));\n\t\t#endif\n\n\t\treturn cCurrentPath;\n\t}\n\n\tstatic Asset_manager* current_instance = nullptr;\n\tauto get_asset_manager() -> Asset_manager& {\n\t\tINVARIANT(current_instance!=nullptr, \"Asset_manager has not been initialized!\");\n\t\treturn *current_instance;\n\t}\n\n\tAsset_manager::Asset_manager(const std::string& exe_name, const std::string& app_name) {\n\t\tif(!PHYSFS_init(exe_name.empty() ? nullptr : exe_name.c_str()))\n\t\t\tFAIL(\"PhysFS-Init failed for \\\"\"<<exe_name<<\"\\\": \"<< PHYSFS_getLastError());\n\n\t\t\/\/ TODO: Windows savegames should be stored in FOLDERID_SavedGames, but the API and conventions are a pain in the ass\n\t\tstd::string write_dir_parent = append_file(PHYSFS_getUserDir(),\n#ifdef WIN\n\t\t\t\"Documents\/My Games\"\n#else\n\t\t\t\".config\"\n#endif\n\t\t);\n\n#ifdef EMSCRIPTEN\n\t\tEM_ASM(\n\t\t\tFS.mkdir('\/persistent_data');\n\t\t\tFS.mount(IDBFS, {}, '\/persistent_data');\n\n\t\t\tModule.syncdone = 0;\n\n\t\t\t\/\/populate persistent_data directory with existing persistent source data\n\t\t\t\/\/stored with Indexed Db\n\t\t\t\/\/first parameter = \"true\" mean synchronize from Indexed Db to\n\t\t\t\/\/Emscripten file system,\n\t\t\t\/\/ \"false\" mean synchronize from Emscripten file system to Indexed Db\n\t\t\t\/\/second parameter = function called when data are synchronized\n\t\t\tFS.syncfs(true, function(err) {\n\t\t\t\t\/\/assert(!err);\n\t\t\t\tModule.print(\"end file sync..\");\n\t\t\t\tModule.syncdone = 1;\n\t\t\t});\n\t\t);\n\t\twrite_dir_parent = \"\/persistent_data\";\n#endif\n\n\t\tcreate_dir(write_dir_parent);\n\n\t\tstd::string write_dir = append_file(write_dir_parent, app_name);\n\t\tcreate_dir(write_dir);\n\n\t\tINFO(\"Write dir: \"<<write_dir);\n\n\t\tif(!PHYSFS_addToSearchPath(PHYSFS_getBaseDir(), 1) ||\n\t\t\t\t!PHYSFS_addToSearchPath(append_file(PHYSFS_getBaseDir(), \"..\").c_str(), 1) ||\n\t\t\t\t!PHYSFS_addToSearchPath(pwd().c_str(), 1) ||\n\t\t\t\t!PHYSFS_addToSearchPath(write_dir.c_str(), 0))\n\t\t\tFAIL(\"Unable to construct search path: \"<< PHYSFS_getLastError());\n\t\t\n\t\t\/\/ add optional search path\n\t\tPHYSFS_addToSearchPath(append_file(append_file(append_file(PHYSFS_getBaseDir(), \"..\"), \"magnum_opus\"), \"assets\").c_str(), 1);\n\n\t\tif(!PHYSFS_setWriteDir(write_dir.c_str()))\n\t\t\tFAIL(\"Unable to set write-dir to \\\"\"<<write_dir<<\"\\\": \"<< PHYSFS_getLastError());\n\n\n\t\tauto add_source = [](const char* path){\n\t\t\tif(!PHYSFS_addToSearchPath(path, 1))\n\t\t\t\tWARN(\"Error adding custom archive \\\"\"<<path<<\"\\\": \"<<PHYSFS_getLastError());\n\t\t};\n\n\t\tauto archive_file = _open(\"archives.lst\");\n\t\tif(!archive_file) {\n\t\t\tbool lost = true;\n\t\t\tfor(auto& s : default_source) {\n\t\t\t\tconst char* path;\n\t\t\t\tbool file;\n\n\t\t\t\tstd::tie(path, file) = s;\n\n\t\t\t\tif(file ? exists_file(path) : exists_dir(path)) {\n\t\t\t\t\tadd_source(path);\n\t\t\t\t\tlost = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(lost) {\n\t\t\t\tauto& log = util::fail (__func__, __FILE__, __LINE__);\n\t\t\t\tlog<<\"No archives.lst found. printing search-path...\\n\";\n\t\t\t\tprint_dir_recursiv(\"\/\", 0, log);\n\n\t\t\t\tlog<<std::endl; \/\/ crash with error\n\n\t\t\t} else {\n\t\t\t\tINFO(\"No archives.lst found. Using defaults.\");\n\t\t\t}\n\n\t\t} else {\n\t\t\t\/\/ load other archives\n\t\t\tarchive_file.process([&](istream& in) {\n\t\t\t\tfor(auto&& l : in.lines()) {\n\t\t\t\t\tadd_source(l.c_str());\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tfor(auto&& df : list_files(\"\", \"assets\", \".map\")) {\n\t\t\t_open(df).process([this](istream& in) {\n\t\t\t\tfor(auto&& l : in.lines()) {\n\t\t\t\t\tauto kvp =\tutil::split(l, \"=\");\n\t\t\t\t\tstd::string path = util::trim_copy(kvp.second);\n\t\t\t\t\tif(!path.empty()) {\n\t\t\t\t\t\t_dispatcher.emplace(AID{kvp.first}, std::move(path));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tcurrent_instance = this;\n\t}\n\n\tAsset_manager::~Asset_manager() {\n\t\tcurrent_instance = nullptr;\n\t\t_assets.clear();\n\t\tPHYSFS_deinit();\n\t}\n\n\tvoid Asset_manager::_post_write() {\n#ifdef EMSCRIPTEN\n\t\t\/\/persist Emscripten current data to Indexed Db\n\t\tEM_ASM(\n\t\t\tFS.syncfs(false,function (err) {\n\t\t\t\t\/\/assert(!err);\n\t\t\t});\n\t\t);\n#endif\n\t}\n\n\tutil::maybe<std::string> Asset_manager::_base_dir(Asset_type type)const {\n\t\tauto dir = _dispatcher.find(AID{type, \"\"}); \/\/ search for prefix-entry\n\n\t\tif(dir==_dispatcher.end())\n\t\t\treturn util::nothing();\n\n\t\tstd::string bdir = dir->second;\n\t\treturn bdir;\n\t}\n\n\tstd::vector<AID> Asset_manager::list(Asset_type type) {\n\t\tstd::vector<AID> res;\n\n\t\t_base_dir(type).process([&](const std::string& dir){\n\t\t\tfor(auto&& f : list_files(dir, \"\", \"\"))\n\t\t\t\tres.emplace_back(type, f);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tutil::maybe<istream> Asset_manager::_open(const std::string& path) {\n\t\treturn _open(path, AID{\"gen\"_strid, path});\n\t}\n\tutil::maybe<istream> Asset_manager::_open(const std::string& path, const AID& aid) {\n\t\treturn exists_file(path) ? util::just(istream{aid, *this, path}) : util::nothing();\n\t}\n\n\tAsset_manager::Asset::Asset(std::shared_ptr<void> data, Reloader reloader, int64_t last_modified)\n\t\t: data(data), reloader(reloader), last_modified(last_modified) {}\n\n\tvoid Asset_manager::_add_asset(const AID& id, const std::string& path,\n\t Reloader reloader, std::shared_ptr<void> asset) {\n\t\t_assets.emplace(id, Asset{asset, reloader, PHYSFS_getLastModTime(path.c_str())});\n\t}\n\n\tauto Asset_manager::_locate(const AID& id, bool warn)const -> std::tuple<Location_type, std::string> {\n\t\tauto res = _dispatcher.find(id);\n\n\t\tif(res!=_dispatcher.end()) {\n\t\t\tif(exists_file(res->second))\n\t\t\t\treturn std::make_tuple(Location_type::file, res->second);\n\t\t\telse if(util::contains(res->second, \":\"))\n\t\t\t\treturn std::make_tuple(Location_type::indirection, res->second);\n\t\t\telse if(warn)\n\t\t\t\tINFO(\"Asset not found in configured place: \"<<res->second);\n\t\t}\n\n\t\tif(exists_file(id.name()))\n\t\t\treturn std::make_tuple(Location_type::file, id.name());\n\n\t\tauto baseDir = _base_dir(id.type());\n\n\t\tif(baseDir.is_some()) {\n\t\t\tauto path = append_file(baseDir.get_or_throw(), id.name());\n\t\t\tif(exists_file(path))\n\t\t\t\treturn std::make_tuple(Location_type::file, std::move(path));\n\t\t\telse if(warn)\n\t\t\t\tDEBUG(\"asset \"<<id.str()<<\" not found in \"<<path);\n\t\t}\n\n\t\treturn std::make_tuple(Location_type::none, std::string());\n\t}\n\n\tostream Asset_manager::_create(const AID& id) throw(Loading_failed) {\n\t\tstd::string path;\n\n\t\tauto path_res = _dispatcher.find(id);\n\t\tif(path_res!=_dispatcher.end())\n\t\t\tpath = path_res->second;\n\n\t\telse {\n\t\t\tauto res = _dispatcher.find(AID{id.type(), \"\"}); \/\/ search for prefix-entry\n\n\t\t\tif(res!=_dispatcher.end()) {\n\t\t\t\tPHYSFS_mkdir(res->second.c_str());\n\t\t\t\tpath = append_file(res->second, id.name());\n\t\t\t} else {\n\t\t\t\tpath = id.name();\n\t\t\t}\n\t\t}\n\n\t\tif(exists_file(path))\n\t\t\tPHYSFS_delete(path.c_str());\n\n\t\treturn {id, *this, path};\n\t}\n\n\tauto Asset_manager::physical_location(const AID& id, bool warn)const noexcept -> util::maybe<std::string>{\n\t\tusing namespace std::literals;\n\n\t\tLocation_type type;\n\t\tstd::string location;\n\t\tstd::tie(type, location) = _locate(id, warn);\n\n\t\tif(type!=Location_type::file)\n\t\t\treturn util::nothing();\n\n\t\tauto dir = PHYSFS_getRealDir(location.c_str());\n\t\tif(!dir)\n\t\t\treturn util::nothing();\n\n\t\tauto file = dir + \"\/\"s + location;\n\t\treturn exists_file(file) ? util::just(std::move(file)) : util::nothing();\n\t}\n\n\tvoid Asset_manager::reload() {\n\t\tfor(auto& a : _assets) {\n\t\t\tLocation_type type;\n\t\t\tstd::string location;\n\t\t\tstd::tie(type, location) = _locate(a.first);\n\n\t\t\tif(type==Location_type::file) {\n\t\t\t\tauto last_mod = PHYSFS_getLastModTime(location.c_str());\n\t\t\t\tif(last_mod!=-1 && last_mod>a.second.last_modified) {\n\t\t\t\t\t_open(location, a.first).process([&](istream& in){\n\t\t\t\t\t\tDEBUG(\"Reload: \"<<a.first.str());\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\ta.second.reloader(a.second.data.get(), std::move(in));\n\n\t\t\t\t\t\t} catch(Loading_failed& e) {}\n\n\t\t\t\t\t\ta.second.last_modified = last_mod;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Asset_manager::shrink_to_fit()noexcept {\n\t\tutil::erase_if(_assets, [](const auto& v){return v.second.data.use_count()<=1;});\n\t}\n\n\tbool Asset_manager::exists(const AID& id)const noexcept {\n\t\tLocation_type type;\n\t\tstd::string location;\n\t\tstd::tie(type, location) = _locate(id);\n\n\t\tswitch(type) {\n\t\t\tcase Location_type::none:\n\t\t\t\treturn false;\n\n\t\t\tcase Location_type::file:\n\t\t\t\treturn exists_file(location);\n\n\t\t\tcase Location_type::indirection:\n\t\t\t\treturn true;\n\t\t}\n\n\t\tFAIL(\"Unexpected Location_type: \"<<(int)type);\n\t}\n\n\tauto Asset_manager::load_raw(const AID& id) -> util::maybe<istream> {\n\t\tLocation_type type;\n\t\tstd::string path;\n\t\tstd::tie(type, path) = _locate(id);\n\n\t\tif(type!=Location_type::file)\n\t\t\treturn util::nothing();\n\n\t\treturn _open(path, id);\n\t}\n\tauto Asset_manager::save_raw(const AID& id) -> ostream {\n\t\t_assets.erase(id);\n\t\treturn _create(id);\n\t}\n\n\tauto Asset_manager::find_by_path(const std::string& path) -> util::maybe<AID> {\n\t\tstatic const auto working_dir = util::replace(pwd(), \"\\\\\", \"\/\");\n\t\tauto path_cleared = util::replace( util::replace(path, \"\\\\\", \"\/\"), working_dir+\"\/\", \"\");\n\n\t\tfor(auto& aid_path : _dispatcher) {\n\t\t\tauto loc = physical_location(aid_path.first, false);\n\t\t\tif(loc.is_some()) {\n\t\t\t\tif(loc.get_or_throw()==path_cleared) {\n\t\t\t\t\treturn util::justCopy(aid_path.first);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tDEBUG(\"Couldn't finde asset for '\"<<path_cleared<<\"'\");\n\n\t\treturn util::nothing();\n\t}\n\n} \/* namespace asset *\/\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"core.h\"\n#include <glibmm\/init.h>\n\nnamespace Davix {\n\nusing namespace Glib;\n\nCore::Core(AbstractSessionFactory* fsess) : _fsess(fsess)\n{\n _s_buff = 65536;\n _timeout = 10;\n}\n\nRefPtr<Core> Core::create(AbstractSessionFactory* fsess){\n return Glib::RefPtr<Core>(new Core(fsess));\n}\n\n\n\n\nAbstractSessionFactory* Core::getSessionFactory(){\n return _fsess.get();\n}\n\nvoid Core::set_buffer_size(const size_t value){\n _s_buff = value;\n}\n\n\n\n\n} \/\/ namespace Davix\n\n\nextern \"C\"{\n\n\/\/ glibmm initialization\n__attribute__((constructor))\nvoid core_init(){\n g_thread_init(NULL);\n Glib::init();\n}\n\n\n\n\n}\n<commit_msg>- remove glib C initialisation, done in background<commit_after>#include \"core.h\"\n#include <glibmm\/init.h>\n\nnamespace Davix {\n\nusing namespace Glib;\n\nCore::Core(AbstractSessionFactory* fsess) : _fsess(fsess)\n{\n _s_buff = 65536;\n _timeout = 10;\n}\n\nRefPtr<Core> Core::create(AbstractSessionFactory* fsess){\n return Glib::RefPtr<Core>(new Core(fsess));\n}\n\n\n\n\nAbstractSessionFactory* Core::getSessionFactory(){\n return _fsess.get();\n}\n\nvoid Core::set_buffer_size(const size_t value){\n _s_buff = value;\n}\n\n\n\n\n} \/\/ namespace Davix\n\n\nextern \"C\"{\n\n\/\/ glibmm initialization\n__attribute__((constructor))\nvoid core_init(){\n Glib::init();\n}\n\n\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\/\/\n\n#include \"dye.hpp\"\n#include <chrono>\n#include <iostream>\n#include <thread>\n\nvoid cadence(size_t ms=750) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }\n\nint main() {\n\tstd::cout << dye::black << \"black\" << std::endl; cadence();\n\tstd::cout << dye::red << \"red\" << std::endl; cadence();\n\tstd::cout << dye::green << \"green\" << std::endl; cadence();\n\tstd::cout << dye::yellow << \"yellow\" << std::endl; cadence();\n\tstd::cout << dye::blue << \"blue\" << std::endl; cadence();\n\tstd::cout << dye::magenta << \"magenta\" << std::endl; cadence();\n\tstd::cout << dye::cyan << \"cyan\" << std::endl; cadence();\n\tstd::cout << dye::white << \"white\" << std::endl; cadence();\n}\n\n\/\/–––––––––––––––––––––––––––––––––––– ∎ –––––––––––––––––––––––––––––––––––––\/\/\n<commit_msg>Adapt demo to showcase 256-palette and 24-bit colors<commit_after>\/\/––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\/\/\n\n#include \"dye.hpp\"\n#include <chrono>\n#include <iostream>\n#include <thread>\n\nvoid cadence(size_t ms=750) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }\n\nint main() {\n\t\/\/ Basic colors\n\n\tstd::cout << dye::black << \"black\" << std::endl;\n\tstd::cout << dye::red << \"red\" << std::endl;\n\tstd::cout << dye::green << \"green\" << std::endl;\n\tstd::cout << dye::yellow << \"yellow\" << std::endl;\n\tstd::cout << dye::blue << \"blue\" << std::endl;\n\tstd::cout << dye::magenta << \"magenta\" << std::endl;\n\tstd::cout << dye::cyan << \"cyan\" << std::endl;\n\tstd::cout << dye::white << \"white\" << std::endl;\n\n\t\/\/ 256 palette colors\n\n\tstd::cout << dye::reset << std::endl;\n\n\tfor (size_t i=0; i<256; ++i)\n\t\tstd::cout << dye::bg(i)(\" \");\n\tstd::cout << std::endl;\n\n\t\/\/ 24-bit colors\n\tstd::cout << std::endl;\n\n\tfor (size_t i=0; i<256; ++i)\n\t\tstd::cout << dye::bg(i,0,i)(\" \");\n\tstd::cout << std::endl;\n}\n\n\/\/–––––––––––––––––––––––––––––––––––– ∎ –––––––––––––––––––––––––––––––––––––\/\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Generates Documentation\n\n\ngb_global int print_entity_kind_ordering[Entity_Count] = {\n\t\/*Invalid*\/ -1,\n\t\/*Constant*\/ 0,\n\t\/*Variable*\/ 1,\n\t\/*TypeName*\/ 4,\n\t\/*Procedure*\/ 2,\n\t\/*ProcGroup*\/ 3,\n\t\/*Builtin*\/ -1,\n\t\/*ImportName*\/ -1,\n\t\/*LibraryName*\/ -1,\n\t\/*Nil*\/ -1,\n\t\/*Label*\/ -1,\n};\ngb_global char const *print_entity_names[Entity_Count] = {\n\t\/*Invalid*\/ \"\",\n\t\/*Constant*\/ \"constants\",\n\t\/*Variable*\/ \"variables\",\n\t\/*TypeName*\/ \"types\",\n\t\/*Procedure*\/ \"procedures\",\n\t\/*ProcGroup*\/ \"proc_group\",\n\t\/*Builtin*\/ \"\",\n\t\/*ImportName*\/ \"import names\",\n\t\/*LibraryName*\/ \"library names\",\n\t\/*Nil*\/ \"\",\n\t\/*Label*\/ \"\",\n};\n\n\nGB_COMPARE_PROC(cmp_entities_for_printing) {\n\tGB_ASSERT(a != nullptr);\n\tGB_ASSERT(b != nullptr);\n\tEntity *x = *cast(Entity **)a;\n\tEntity *y = *cast(Entity **)b;\n\tint res = 0;\n\tres = string_compare(x->pkg->name, y->pkg->name);\n\tif (res != 0) {\n\t\treturn res;\n\t}\n\tint ox = print_entity_kind_ordering[x->kind];\n\tint oy = print_entity_kind_ordering[y->kind];\n\tif (ox < oy) {\n\t\treturn -1;\n\t} else if (ox > oy) {\n\t\treturn +1;\n\t}\n\tres = string_compare(x->token.string, y->token.string);\n\treturn res;\n}\n\nGB_COMPARE_PROC(cmp_ast_package_by_name) {\n\tGB_ASSERT(a != nullptr);\n\tGB_ASSERT(b != nullptr);\n\tAstPackage *x = *cast(AstPackage **)a;\n\tAstPackage *y = *cast(AstPackage **)b;\n\treturn string_compare(x->name, y->name);\n}\n\n\nString alloc_comment_group_string(gbAllocator a, CommentGroup g) {\n\tisize len = 0;\n\tfor_array(i, g.list) {\n\t\tString comment = g.list[i].string;\n\t\tlen += comment.len;\n\t\tlen += 1; \/\/ for \\n\n\t}\n\tif (len == 0) {\n\t\treturn make_string(nullptr, 0);\n\t}\n\n\tu8 *text = gb_alloc_array(a, u8, len+1);\n\tlen = 0;\n\tfor_array(i, g.list) {\n\t\tString comment = g.list[i].string;\n\t\tif (comment[1] == '\/') {\n\t\t\tcomment.text += 2;\n\t\t\tcomment.len -= 2;\n\t\t} else if (comment[1] == '*') {\n\t\t\tcomment.text += 2;\n\t\t\tcomment.len -= 4;\n\t\t}\n\t\tcomment = string_trim_whitespace(comment);\n\t\tgb_memmove(text+len, comment.text, comment.len);\n\t\tlen += comment.len;\n\t\ttext[len++] = '\\n';\n\t}\n\treturn make_string(text, len);\n}\n\n\nvoid print_doc_line(i32 indent, char const *fmt, ...) {\n\twhile (indent --> 0) {\n\t\tgb_printf(\"\\t\");\n\t}\n\tva_list va;\n\tva_start(va, fmt);\n\tgb_printf_va(fmt, va);\n\tva_end(va);\n\tgb_printf(\"\\n\");\n}\nvoid print_doc_line_no_newline(i32 indent, char const *fmt, ...) {\n\twhile (indent --> 0) {\n\t\tgb_printf(\"\\t\");\n\t}\n\tva_list va;\n\tva_start(va, fmt);\n\tgb_printf_va(fmt, va);\n\tva_end(va);\n}\n\nbool print_doc_comment_group_string(i32 indent, CommentGroup *g) {\n\tif (g == nullptr) {\n\t\treturn false;\n\t}\n\tisize len = 0;\n\tfor_array(i, g->list) {\n\t\tString comment = g->list[i].string;\n\t\tlen += comment.len;\n\t\tlen += 1; \/\/ for \\n\n\t}\n\tif (len <= g->list.count) {\n\t\treturn false;\n\t}\n\n\tisize count = 0;\n\tfor_array(i, g->list) {\n\t\tString comment = g->list[i].string;\n\t\tif (comment[1] == '\/') {\n\t\t\tcomment.text += 2;\n\t\t\tcomment.len -= 2;\n\t\t} else if (comment[1] == '*') {\n\t\t\tcomment.text += 2;\n\t\t\tcomment.len -= 4;\n\t\t}\n\t\tif (comment.len > 0 && comment[0] == ' ') {\n\t\t\tcomment.text += 1;\n\t\t\tcomment.len -= 1;\n\t\t}\n\n\t\tif (string_starts_with(comment, str_lit(\"@(\"))) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tprint_doc_line(indent, \"%.*s\", LIT(comment));\n\t\tcount += 1;\n\t}\n\treturn count > 0;\n}\n\n\n\n\nvoid print_doc_expr(Ast *expr) {\n\tgbString s = nullptr;\n\tif (build_context.cmd_doc_flags & CmdDocFlag_All) {\n\t\ts = expr_to_string(expr);\n\t} else {\n\t\ts = expr_to_string_shorthand(expr);\n\t}\n\tgb_file_write(gb_file_get_standard(gbFileStandard_Output), s, gb_string_length(s));\n\tgb_string_free(s);\n}\n\n\nvoid print_doc_package(CheckerInfo *info, AstPackage *pkg) {\n\tif (pkg == nullptr) {\n\t\treturn;\n\t}\n\n\tprint_doc_line(0, \"package %.*s\", LIT(pkg->name));\n\n\n\tfor_array(i, pkg->files) {\n\t\tAstFile *f = pkg->files[i];\n\t\tif (f->pkg_decl) {\n\t\t\tGB_ASSERT(f->pkg_decl->kind == Ast_PackageDecl);\n\t\t\tif (print_doc_comment_group_string(1, f->pkg_decl->PackageDecl.docs)) {\n\t\t\t\tprint_doc_line(0, \"\");\n\t\t\t}\n\t\t}\n\t}\n\n\tif (pkg->scope != nullptr) {\n\t\tauto entities = array_make<Entity *>(heap_allocator(), 0, pkg->scope->elements.entries.count);\n\t\tdefer (array_free(&entities));\n\t\tfor_array(i, pkg->scope->elements.entries) {\n\t\t\tEntity *e = pkg->scope->elements.entries[i].value;\n\t\t\tswitch (e->kind) {\n\t\t\tcase Entity_Invalid:\n\t\t\tcase Entity_Builtin:\n\t\t\tcase Entity_Nil:\n\t\t\tcase Entity_Label:\n\t\t\t\tcontinue;\n\t\t\tcase Entity_Constant:\n\t\t\tcase Entity_Variable:\n\t\t\tcase Entity_TypeName:\n\t\t\tcase Entity_Procedure:\n\t\t\tcase Entity_ProcGroup:\n\t\t\tcase Entity_ImportName:\n\t\t\tcase Entity_LibraryName:\n\t\t\t\t\/\/ Fine\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tarray_add(&entities, e);\n\t\t}\n\t\tgb_sort_array(entities.data, entities.count, cmp_entities_for_printing);\n\n\t\tEntityKind curr_entity_kind = Entity_Invalid;\n\t\tfor_array(i, entities) {\n\t\t\tEntity *e = entities[i];\n\t\t\tif (e->pkg != pkg) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!is_entity_exported(e)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (curr_entity_kind != e->kind) {\n\t\t\t\tif (curr_entity_kind != Entity_Invalid) {\n\t\t\t\t\tprint_doc_line(0, \"\");\n\t\t\t\t}\n\t\t\t\tcurr_entity_kind = e->kind;\n\t\t\t\tprint_doc_line(1, \"%s\", print_entity_names[e->kind]);\n\t\t\t}\n\n\t\t\tAst *type_expr = nullptr;\n\t\t\tAst *init_expr = nullptr;\n\t\t\tAst *decl_node = nullptr;\n\t\t\tCommentGroup *comment = nullptr;\n\t\t\tCommentGroup *docs = nullptr;\n\t\t\tif (e->decl_info != nullptr) {\n\t\t\t\ttype_expr = e->decl_info->type_expr;\n\t\t\t\tinit_expr = e->decl_info->init_expr;\n\t\t\t\tdecl_node = e->decl_info->decl_node;\n\t\t\t\tcomment = e->decl_info->comment;\n\t\t\t\tdocs = e->decl_info->docs;\n\t\t\t}\n\t\t\tGB_ASSERT(type_expr != nullptr || init_expr != nullptr);\n\t\t\tprint_doc_line_no_newline(2, \"%.*s\", LIT(e->token.string));\n\t\t\tif (type_expr != nullptr) {\n\t\t\t\tgbString t = expr_to_string(type_expr);\n\t\t\t\tgb_printf(\": %s \", t);\n\t\t\t\tgb_string_free(t);\n\t\t\t} else {\n\t\t\t\tgb_printf(\" :\");\n\t\t\t}\n\t\t\tif (e->kind == Entity_Variable) {\n\t\t\t\tif (init_expr != nullptr) {\n\t\t\t\t\tgb_printf(\"= \");\n\t\t\t\t\tprint_doc_expr(init_expr);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgb_printf(\": \");\n\t\t\t\tprint_doc_expr(init_expr);\n\t\t\t}\n\n\t\t\tgb_printf(\";\\n\");\n\n\n\t\t\tif (build_context.cmd_doc_flags & CmdDocFlag_All) {\n\t\t\t\tif (comment) {\n\t\t\t\t\t\/\/ gb_printf(\" <comment>\");\n\t\t\t\t}\n\t\t\t\tif (print_doc_comment_group_string(3, docs)) {\n\t\t\t\t\tgb_printf(\"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprint_doc_line(0, \"\");\n\t}\n\n\tif (pkg->fullpath.len != 0) {\n\t\tprint_doc_line(0, \"\");\n\t\tprint_doc_line(1, \"fullpath: %.*s\", LIT(pkg->fullpath));\n\t\tprint_doc_line(1, \"files:\");\n\t\tfor_array(i, pkg->files) {\n\t\t\tAstFile *f = pkg->files[i];\n\t\t\tString filename = remove_directory_from_path(f->fullpath);\n\t\t\tprint_doc_line(2, \"%.*s\", LIT(filename));\n\t\t}\n\t}\n\n}\n\nvoid generate_documentation(Checker *c) {\n\tCheckerInfo *info = &c->info;\n\n\tif (build_context.doc_packages.count != 0) {\n\t\tauto pkgs = array_make<AstPackage *>(permanent_allocator(), 0, info->packages.entries.count);\n\t\tbool was_error = false;\n\t\tfor_array(j, build_context.doc_packages) {\n\t\t\tbool found = false;\n\t\t\tString name = build_context.doc_packages[j];\n\t\t\tfor_array(i, info->packages.entries) {\n\t\t\t\tAstPackage *pkg = info->packages.entries[i].value;\n\t\t\t\tif (name == pkg->name) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tarray_add(&pkgs, pkg);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) {\n\t\t\t\tgb_printf_err(\"Unknown package %.*s\\n\", LIT(name));\n\t\t\t\twas_error = true;\n\t\t\t}\n\t\t}\n\t\tif (was_error) {\n\t\t\tgb_exit(1);\n\t\t\treturn;\n\t\t}\n\n\t\tgb_sort_array(pkgs.data, pkgs.count, cmp_ast_package_by_name);\n\n\t\tfor_array(i, pkgs) {\n\t\t\tprint_doc_package(info, pkgs[i]);\n\t\t}\n\t} else if (build_context.cmd_doc_flags & CmdDocFlag_AllPackages) {\n\t\tauto pkgs = array_make<AstPackage *>(permanent_allocator(), 0, info->packages.entries.count);\n\t\tfor_array(i, info->packages.entries) {\n\t\t\tAstPackage *pkg = info->packages.entries[i].value;\n\t\t\tarray_add(&pkgs, pkg);\n\t\t}\n\n\t\tgb_sort_array(pkgs.data, pkgs.count, cmp_ast_package_by_name);\n\n\t\tfor_array(i, pkgs) {\n\t\t\tprint_doc_package(info, pkgs[i]);\n\t\t}\n\t} else {\n\t\tGB_ASSERT(info->init_scope->flags & ScopeFlag_Pkg);\n\t\tAstPackage *pkg = info->init_scope->pkg;\n\t\tprint_doc_package(info, pkg);\n\n\t}\n}\n<commit_msg>Ignore `+build` flags in packages comments with `odin doc`<commit_after>\/\/ Generates Documentation\n\n\ngb_global int print_entity_kind_ordering[Entity_Count] = {\n\t\/*Invalid*\/ -1,\n\t\/*Constant*\/ 0,\n\t\/*Variable*\/ 1,\n\t\/*TypeName*\/ 4,\n\t\/*Procedure*\/ 2,\n\t\/*ProcGroup*\/ 3,\n\t\/*Builtin*\/ -1,\n\t\/*ImportName*\/ -1,\n\t\/*LibraryName*\/ -1,\n\t\/*Nil*\/ -1,\n\t\/*Label*\/ -1,\n};\ngb_global char const *print_entity_names[Entity_Count] = {\n\t\/*Invalid*\/ \"\",\n\t\/*Constant*\/ \"constants\",\n\t\/*Variable*\/ \"variables\",\n\t\/*TypeName*\/ \"types\",\n\t\/*Procedure*\/ \"procedures\",\n\t\/*ProcGroup*\/ \"proc_group\",\n\t\/*Builtin*\/ \"\",\n\t\/*ImportName*\/ \"import names\",\n\t\/*LibraryName*\/ \"library names\",\n\t\/*Nil*\/ \"\",\n\t\/*Label*\/ \"\",\n};\n\n\nGB_COMPARE_PROC(cmp_entities_for_printing) {\n\tGB_ASSERT(a != nullptr);\n\tGB_ASSERT(b != nullptr);\n\tEntity *x = *cast(Entity **)a;\n\tEntity *y = *cast(Entity **)b;\n\tint res = 0;\n\tres = string_compare(x->pkg->name, y->pkg->name);\n\tif (res != 0) {\n\t\treturn res;\n\t}\n\tint ox = print_entity_kind_ordering[x->kind];\n\tint oy = print_entity_kind_ordering[y->kind];\n\tif (ox < oy) {\n\t\treturn -1;\n\t} else if (ox > oy) {\n\t\treturn +1;\n\t}\n\tres = string_compare(x->token.string, y->token.string);\n\treturn res;\n}\n\nGB_COMPARE_PROC(cmp_ast_package_by_name) {\n\tGB_ASSERT(a != nullptr);\n\tGB_ASSERT(b != nullptr);\n\tAstPackage *x = *cast(AstPackage **)a;\n\tAstPackage *y = *cast(AstPackage **)b;\n\treturn string_compare(x->name, y->name);\n}\n\nvoid print_doc_line(i32 indent, char const *fmt, ...) {\n\twhile (indent --> 0) {\n\t\tgb_printf(\"\\t\");\n\t}\n\tva_list va;\n\tva_start(va, fmt);\n\tgb_printf_va(fmt, va);\n\tva_end(va);\n\tgb_printf(\"\\n\");\n}\nvoid print_doc_line_no_newline(i32 indent, char const *fmt, ...) {\n\twhile (indent --> 0) {\n\t\tgb_printf(\"\\t\");\n\t}\n\tva_list va;\n\tva_start(va, fmt);\n\tgb_printf_va(fmt, va);\n\tva_end(va);\n}\n\nbool print_doc_comment_group_string(i32 indent, CommentGroup *g) {\n\tif (g == nullptr) {\n\t\treturn false;\n\t}\n\tisize len = 0;\n\tfor_array(i, g->list) {\n\t\tString comment = g->list[i].string;\n\t\tlen += comment.len;\n\t\tlen += 1; \/\/ for \\n\n\t}\n\tif (len <= g->list.count) {\n\t\treturn false;\n\t}\n\n\tisize count = 0;\n\tfor_array(i, g->list) {\n\t\tString comment = g->list[i].string;\n\t\tbool slash_slash = comment[1] == '\/';\n\t\tif (comment[1] == '\/') {\n\t\t\tcomment.text += 2;\n\t\t\tcomment.len -= 2;\n\t\t} else if (comment[1] == '*') {\n\t\t\tcomment.text += 2;\n\t\t\tcomment.len -= 4;\n\t\t}\n\n\t\t\/\/ Ignore the first space\n\t\tif (comment.len > 0 && comment[0] == ' ') {\n\t\t\tcomment.text += 1;\n\t\t\tcomment.len -= 1;\n\t\t}\n\n\t\tif (slash_slash) {\n\t\t\tif (string_starts_with(comment, str_lit(\"+\"))) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (string_starts_with(comment, str_lit(\"@(\"))) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tprint_doc_line(indent, \"%.*s\", LIT(comment));\n\t\tcount += 1;\n\t}\n\treturn count > 0;\n}\n\n\n\n\nvoid print_doc_expr(Ast *expr) {\n\tgbString s = nullptr;\n\tif (build_context.cmd_doc_flags & CmdDocFlag_All) {\n\t\ts = expr_to_string(expr);\n\t} else {\n\t\ts = expr_to_string_shorthand(expr);\n\t}\n\tgb_file_write(gb_file_get_standard(gbFileStandard_Output), s, gb_string_length(s));\n\tgb_string_free(s);\n}\n\n\nvoid print_doc_package(CheckerInfo *info, AstPackage *pkg) {\n\tif (pkg == nullptr) {\n\t\treturn;\n\t}\n\n\tprint_doc_line(0, \"package %.*s\", LIT(pkg->name));\n\n\n\tfor_array(i, pkg->files) {\n\t\tAstFile *f = pkg->files[i];\n\t\tif (f->pkg_decl) {\n\t\t\tGB_ASSERT(f->pkg_decl->kind == Ast_PackageDecl);\n\t\t\tif (print_doc_comment_group_string(1, f->pkg_decl->PackageDecl.docs)) {\n\t\t\t\tprint_doc_line(0, \"\");\n\t\t\t}\n\t\t}\n\t}\n\n\tif (pkg->scope != nullptr) {\n\t\tauto entities = array_make<Entity *>(heap_allocator(), 0, pkg->scope->elements.entries.count);\n\t\tdefer (array_free(&entities));\n\t\tfor_array(i, pkg->scope->elements.entries) {\n\t\t\tEntity *e = pkg->scope->elements.entries[i].value;\n\t\t\tswitch (e->kind) {\n\t\t\tcase Entity_Invalid:\n\t\t\tcase Entity_Builtin:\n\t\t\tcase Entity_Nil:\n\t\t\tcase Entity_Label:\n\t\t\t\tcontinue;\n\t\t\tcase Entity_Constant:\n\t\t\tcase Entity_Variable:\n\t\t\tcase Entity_TypeName:\n\t\t\tcase Entity_Procedure:\n\t\t\tcase Entity_ProcGroup:\n\t\t\tcase Entity_ImportName:\n\t\t\tcase Entity_LibraryName:\n\t\t\t\t\/\/ Fine\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tarray_add(&entities, e);\n\t\t}\n\t\tgb_sort_array(entities.data, entities.count, cmp_entities_for_printing);\n\n\t\tEntityKind curr_entity_kind = Entity_Invalid;\n\t\tfor_array(i, entities) {\n\t\t\tEntity *e = entities[i];\n\t\t\tif (e->pkg != pkg) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!is_entity_exported(e)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (curr_entity_kind != e->kind) {\n\t\t\t\tif (curr_entity_kind != Entity_Invalid) {\n\t\t\t\t\tprint_doc_line(0, \"\");\n\t\t\t\t}\n\t\t\t\tcurr_entity_kind = e->kind;\n\t\t\t\tprint_doc_line(1, \"%s\", print_entity_names[e->kind]);\n\t\t\t}\n\n\t\t\tAst *type_expr = nullptr;\n\t\t\tAst *init_expr = nullptr;\n\t\t\tAst *decl_node = nullptr;\n\t\t\tCommentGroup *comment = nullptr;\n\t\t\tCommentGroup *docs = nullptr;\n\t\t\tif (e->decl_info != nullptr) {\n\t\t\t\ttype_expr = e->decl_info->type_expr;\n\t\t\t\tinit_expr = e->decl_info->init_expr;\n\t\t\t\tdecl_node = e->decl_info->decl_node;\n\t\t\t\tcomment = e->decl_info->comment;\n\t\t\t\tdocs = e->decl_info->docs;\n\t\t\t}\n\t\t\tGB_ASSERT(type_expr != nullptr || init_expr != nullptr);\n\t\t\tprint_doc_line_no_newline(2, \"%.*s\", LIT(e->token.string));\n\t\t\tif (type_expr != nullptr) {\n\t\t\t\tgbString t = expr_to_string(type_expr);\n\t\t\t\tgb_printf(\": %s \", t);\n\t\t\t\tgb_string_free(t);\n\t\t\t} else {\n\t\t\t\tgb_printf(\" :\");\n\t\t\t}\n\t\t\tif (e->kind == Entity_Variable) {\n\t\t\t\tif (init_expr != nullptr) {\n\t\t\t\t\tgb_printf(\"= \");\n\t\t\t\t\tprint_doc_expr(init_expr);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgb_printf(\": \");\n\t\t\t\tprint_doc_expr(init_expr);\n\t\t\t}\n\n\t\t\tgb_printf(\";\\n\");\n\n\n\t\t\tif (build_context.cmd_doc_flags & CmdDocFlag_All) {\n\t\t\t\tif (comment) {\n\t\t\t\t\t\/\/ gb_printf(\" <comment>\");\n\t\t\t\t}\n\t\t\t\tif (print_doc_comment_group_string(3, docs)) {\n\t\t\t\t\tgb_printf(\"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprint_doc_line(0, \"\");\n\t}\n\n\tif (pkg->fullpath.len != 0) {\n\t\tprint_doc_line(0, \"\");\n\t\tprint_doc_line(1, \"fullpath: %.*s\", LIT(pkg->fullpath));\n\t\tprint_doc_line(1, \"files:\");\n\t\tfor_array(i, pkg->files) {\n\t\t\tAstFile *f = pkg->files[i];\n\t\t\tString filename = remove_directory_from_path(f->fullpath);\n\t\t\tprint_doc_line(2, \"%.*s\", LIT(filename));\n\t\t}\n\t}\n\n}\n\nvoid generate_documentation(Checker *c) {\n\tCheckerInfo *info = &c->info;\n\n\tif (build_context.doc_packages.count != 0) {\n\t\tauto pkgs = array_make<AstPackage *>(permanent_allocator(), 0, info->packages.entries.count);\n\t\tbool was_error = false;\n\t\tfor_array(j, build_context.doc_packages) {\n\t\t\tbool found = false;\n\t\t\tString name = build_context.doc_packages[j];\n\t\t\tfor_array(i, info->packages.entries) {\n\t\t\t\tAstPackage *pkg = info->packages.entries[i].value;\n\t\t\t\tif (name == pkg->name) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tarray_add(&pkgs, pkg);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) {\n\t\t\t\tgb_printf_err(\"Unknown package %.*s\\n\", LIT(name));\n\t\t\t\twas_error = true;\n\t\t\t}\n\t\t}\n\t\tif (was_error) {\n\t\t\tgb_exit(1);\n\t\t\treturn;\n\t\t}\n\n\t\tgb_sort_array(pkgs.data, pkgs.count, cmp_ast_package_by_name);\n\n\t\tfor_array(i, pkgs) {\n\t\t\tprint_doc_package(info, pkgs[i]);\n\t\t}\n\t} else if (build_context.cmd_doc_flags & CmdDocFlag_AllPackages) {\n\t\tauto pkgs = array_make<AstPackage *>(permanent_allocator(), 0, info->packages.entries.count);\n\t\tfor_array(i, info->packages.entries) {\n\t\t\tAstPackage *pkg = info->packages.entries[i].value;\n\t\t\tarray_add(&pkgs, pkg);\n\t\t}\n\n\t\tgb_sort_array(pkgs.data, pkgs.count, cmp_ast_package_by_name);\n\n\t\tfor_array(i, pkgs) {\n\t\t\tprint_doc_package(info, pkgs[i]);\n\t\t}\n\t} else {\n\t\tGB_ASSERT(info->init_scope->flags & ScopeFlag_Pkg);\n\t\tAstPackage *pkg = info->init_scope->pkg;\n\t\tprint_doc_package(info, pkg);\n\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\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 <boost\/filesystem\/operations.hpp>\n#include \"libtorrent\/file.hpp\"\n#include <sstream>\n\n#ifdef WIN32\n\n#include <io.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\ntypedef int mode_t;\n\n#else\n\n#define _FILE_OFFSET_BITS 64\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#endif\n\n#ifndef O_BINARY\n#define O_BINARY 0\n#endif\n\n#ifndef O_RANDOM\n#define O_RANDOM 0\n#endif\n\n\nnamespace fs = boost::filesystem;\n\nnamespace\n{\n\tenum { mode_in = 1, mode_out = 2 };\n\n\tmode_t map_open_mode(int m)\n\t{\n\/\/\t\tif (m == (mode_in | mode_out)) return O_RDWR | O_BINARY;\n\t\tif (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;\n\t\tassert(false);\n\t\treturn 0;\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tconst file::open_mode file::in(mode_in);\n\tconst file::open_mode file::out(mode_out);\n\n\tconst file::seek_mode file::begin(1);\n\tconst file::seek_mode file::end(2);\n\n\tstruct file::impl\n\t{\n\t\timpl()\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{}\n\n\t\timpl(fs::path const& path, int mode)\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{\n\t\t\topen(path, mode);\n\t\t}\n\n\t\t~impl()\n\t\t{\n\t\t\tclose();\n\t\t}\n\n\t\tvoid open(fs::path const& path, int mode)\n\t\t{\n\t\t\tclose();\n\t\t\tm_fd = ::open(\n\t\t\t\tpath.native_file_string().c_str()\n\t\t\t\t, map_open_mode(mode)\n\t\t\t\t, S_IREAD | S_IWRITE);\n\t\t\tif (m_fd == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"open failed: '\" << path.native_file_string() << \"'. \"\n\t\t\t\t\t<< strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\tm_open_mode = mode;\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (m_fd == -1) return;\n\n\t\t\tstd::stringstream str;\n\t\t\tstr << \"fd: \" << m_fd << \"\\n\";\n\n\t\t\t::close(m_fd);\n\t\t\tm_fd = -1;\n\t\t\tm_open_mode = 0;\n\t\t}\n\n\t\tsize_type read(char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode == mode_in);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tsize_type ret = ::read(m_fd, buf, num_bytes);\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"read failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type write(const char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode == mode_out);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tsize_type ret = ::write(m_fd, buf, num_bytes);\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"write failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tvoid seek(size_type offset, int m)\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tint seekdir = (m == 1)?SEEK_SET:SEEK_END;\n#ifdef WIN32\n\t\t\tsize_type ret = _lseeki64(m_fd, offset, seekdir);\n#else\n\t\t\tsize_type ret = lseek(m_fd, offset, seekdir);\n#endif\n\n\t\t\t\/\/ For some strange reason this fails\n\t\t\t\/\/ on win32. Use windows specific file\n\t\t\t\/\/ wrapper instead.\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"seek failed: '\" << strerror(errno)\n\t\t\t\t\t<< \"' fd: \" << m_fd\n\t\t\t\t\t<< \" offset: \" << offset\n\t\t\t\t\t<< \" seekdir: \" << seekdir;\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\n\t\t}\n\n\t\tsize_type tell()\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n#ifdef WIN32\n\t\t\treturn _telli64(m_fd);\n#else\n\t\t\treturn lseek(m_fd, 0, SEEK_CUR);\n#endif\n\t\t}\n\n\t\tint m_fd;\n\t\tint m_open_mode;\n\t};\n\n\t\/\/ pimpl forwardings\n\n\tfile::file() : m_impl(new impl()) {}\n\n\tfile::file(boost::filesystem::path const& p, file::open_mode m)\n\t\t: m_impl(new impl(p, m.m_mask))\n\t{}\n\n\tfile::~file() {}\n\n\tvoid file::open(boost::filesystem::path const& p, file::open_mode m)\n\t{\n\t\tm_impl->open(p, m.m_mask);\n\t}\n\n\tvoid file::close()\n\t{\n\t\tm_impl->close();\n\t}\n\n\tsize_type file::write(const char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->write(buf, num_bytes);\n\t}\n\n\tsize_type file::read(char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->read(buf, num_bytes);\n\t}\n\n\tvoid file::seek(size_type pos, file::seek_mode m)\n\t{\n\t\tm_impl->seek(pos, m.m_val);\n\t}\n\n\tsize_type file::tell()\n\t{\n\t\treturn m_impl->tell();\n\t}\n\n}\n<commit_msg>*** empty log message ***<commit_after>\/*\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 <boost\/filesystem\/operations.hpp>\n#include \"libtorrent\/file.hpp\"\n#include <sstream>\n\n#ifdef WIN32\n\n#include <io.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#ifndef _MODE_T_\ntypedef int mode_t;\n#endif\n\n#else\n\n#define _FILE_OFFSET_BITS 64\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#endif\n\n#ifndef O_BINARY\n#define O_BINARY 0\n#endif\n\n#ifndef O_RANDOM\n#define O_RANDOM 0\n#endif\n\n\nnamespace fs = boost::filesystem;\n\nnamespace\n{\n\tenum { mode_in = 1, mode_out = 2 };\n\n\tmode_t map_open_mode(int m)\n\t{\n\/\/\t\tif (m == (mode_in | mode_out)) return O_RDWR | O_BINARY;\n\t\tif (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;\n\t\tassert(false);\n\t\treturn 0;\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tconst file::open_mode file::in(mode_in);\n\tconst file::open_mode file::out(mode_out);\n\n\tconst file::seek_mode file::begin(1);\n\tconst file::seek_mode file::end(2);\n\n\tstruct file::impl\n\t{\n\t\timpl()\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{}\n\n\t\timpl(fs::path const& path, int mode)\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{\n\t\t\topen(path, mode);\n\t\t}\n\n\t\t~impl()\n\t\t{\n\t\t\tclose();\n\t\t}\n\n\t\tvoid open(fs::path const& path, int mode)\n\t\t{\n\t\t\tclose();\n\t\t\tm_fd = ::open(\n\t\t\t\tpath.native_file_string().c_str()\n\t\t\t\t, map_open_mode(mode)\n\t\t\t\t, S_IREAD | S_IWRITE);\n\t\t\tif (m_fd == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"open failed: '\" << path.native_file_string() << \"'. \"\n\t\t\t\t\t<< strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\tm_open_mode = mode;\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (m_fd == -1) return;\n\n\t\t\tstd::stringstream str;\n\t\t\tstr << \"fd: \" << m_fd << \"\\n\";\n\n\t\t\t::close(m_fd);\n\t\t\tm_fd = -1;\n\t\t\tm_open_mode = 0;\n\t\t}\n\n\t\tsize_type read(char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode == mode_in);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tsize_type ret = ::read(m_fd, buf, num_bytes);\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"read failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type write(const char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode == mode_out);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tsize_type ret = ::write(m_fd, buf, num_bytes);\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"write failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tvoid seek(size_type offset, int m)\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tint seekdir = (m == 1)?SEEK_SET:SEEK_END;\n#ifdef WIN32\n\t\t\tsize_type ret = _lseeki64(m_fd, offset, seekdir);\n#else\n\t\t\tsize_type ret = lseek(m_fd, offset, seekdir);\n#endif\n\n\t\t\t\/\/ For some strange reason this fails\n\t\t\t\/\/ on win32. Use windows specific file\n\t\t\t\/\/ wrapper instead.\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"seek failed: '\" << strerror(errno)\n\t\t\t\t\t<< \"' fd: \" << m_fd\n\t\t\t\t\t<< \" offset: \" << offset\n\t\t\t\t\t<< \" seekdir: \" << seekdir;\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\n\t\t}\n\n\t\tsize_type tell()\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n#ifdef WIN32\n\t\t\treturn _telli64(m_fd);\n#else\n\t\t\treturn lseek(m_fd, 0, SEEK_CUR);\n#endif\n\t\t}\n\n\t\tint m_fd;\n\t\tint m_open_mode;\n\t};\n\n\t\/\/ pimpl forwardings\n\n\tfile::file() : m_impl(new impl()) {}\n\n\tfile::file(boost::filesystem::path const& p, file::open_mode m)\n\t\t: m_impl(new impl(p, m.m_mask))\n\t{}\n\n\tfile::~file() {}\n\n\tvoid file::open(boost::filesystem::path const& p, file::open_mode m)\n\t{\n\t\tm_impl->open(p, m.m_mask);\n\t}\n\n\tvoid file::close()\n\t{\n\t\tm_impl->close();\n\t}\n\n\tsize_type file::write(const char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->write(buf, num_bytes);\n\t}\n\n\tsize_type file::read(char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->read(buf, num_bytes);\n\t}\n\n\tvoid file::seek(size_type pos, file::seek_mode m)\n\t{\n\t\tm_impl->seek(pos, m.m_val);\n\t}\n\n\tsize_type file::tell()\n\t{\n\t\treturn m_impl->tell();\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\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#ifdef _WIN32\n\/\/ windows part\n#include \"libtorrent\/utf8.hpp\"\n\n#include <io.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#ifndef _MODE_T_\ntypedef int mode_t;\n#endif\n\n#ifdef UNICODE\n#include \"libtorrent\/storage.hpp\"\n#endif\n\n#else\n\/\/ unix part\n#define _FILE_OFFSET_BITS 64\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <errno.h>\n\n#include <boost\/static_assert.hpp>\n\/\/ make sure the _FILE_OFFSET_BITS define worked\n\/\/ on this platform\nBOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);\n\n#endif\n\n#include <boost\/filesystem\/operations.hpp>\n#include \"libtorrent\/file.hpp\"\n#include <sstream>\n\n#ifndef O_BINARY\n#define O_BINARY 0\n#endif\n\n#ifndef O_RANDOM\n#define O_RANDOM 0\n#endif\n\n#ifdef UNICODE\n#include \"libtorrent\/storage.hpp\"\n#endif\n\n\nnamespace\n{\n\tenum { mode_in = 1, mode_out = 2 };\n\n\tmode_t map_open_mode(int m)\n\t{\n\t\tif (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;\n\t\tassert(false);\n\t\treturn 0;\n\t}\n\n#ifdef WIN32\n\tstd::string utf8_native(std::string const& s)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstd::wstring ws;\n\t\t\tlibtorrent::utf8_wchar(s, ws);\n\t\t\tstd::size_t size = wcstombs(0, ws.c_str(), 0);\n\t\t\tif (size == std::size_t(-1)) return s;\n\t\t\tstd::string ret;\n\t\t\tret.resize(size);\n\t\t\tsize = wcstombs(&ret[0], ws.c_str(), size + 1);\n\t\t\tif (size == wchar_t(-1)) return s;\n\t\t\tret.resize(size);\n\t\t\treturn ret;\n\t\t}\n\t\tcatch(std::exception)\n\t\t{\n\t\t\treturn s;\n\t\t}\n\t}\n#else\n\tstd::string utf8_native(std::string const& s)\n\t{\n\t\treturn s;\n\t}\n#endif\n\n}\n\nnamespace libtorrent\n{\n\n\tnamespace fs = boost::filesystem;\n\n\tconst file::open_mode file::in(mode_in);\n\tconst file::open_mode file::out(mode_out);\n\n\tconst file::seek_mode file::begin(1);\n\tconst file::seek_mode file::end(2);\n\n\tstruct file::impl\n\t{\n\t\timpl()\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{}\n\n\t\timpl(fs::path const& path, int mode)\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{\n\t\t\topen(path, mode);\n\t\t}\n\n\t\t~impl()\n\t\t{\n\t\t\tclose();\n\t\t}\n\n\t\tvoid open(fs::path const& path, int mode)\n\t\t{\n\t\t\tassert(path.is_complete());\n\t\t\tclose();\n#if defined(_WIN32) && defined(UNICODE)\n\t\t\tstd::wstring wpath(safe_convert(path.native_file_string()));\n\t\t\tm_fd = ::_wopen(\n\t\t\t\twpath.c_str()\n\t\t\t\t, map_open_mode(mode)\n\t\t\t\t, S_IREAD | S_IWRITE);\n#else\n#ifdef _WIN32\n\t\t\tm_fd = ::_open(\n#else\n\t\t\tm_fd = ::open(\n#endif\n\t\t\t\tutf8_native(path.native_file_string()).c_str()\n\t\t\t\t, map_open_mode(mode)\n#ifdef _WIN32\n\t\t\t\t, S_IREAD | S_IWRITE);\n#else\n\t\t\t\t, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n#endif\n#endif\n\t\t\tif (m_fd == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"open failed: '\" << path.native_file_string() << \"'. \"\n\t\t\t\t\t<< strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\tm_open_mode = mode;\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (m_fd == -1) return;\n\n#ifdef _WIN32\n\t\t\t::_close(m_fd);\n#else\n\t\t\t::close(m_fd);\n#endif\n\t\t\tm_fd = -1;\n\t\t\tm_open_mode = 0;\n\t\t}\n\n\t\tsize_type read(char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode & mode_in);\n\t\t\tassert(m_fd != -1);\n\n#ifdef _WIN32\n\t\t\tsize_type ret = ::_read(m_fd, buf, num_bytes);\n#else\n\t\t\tsize_type ret = ::read(m_fd, buf, num_bytes);\n#endif\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"read failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type write(const char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode & mode_out);\n\t\t\tassert(m_fd != -1);\n\n\t\t\t\/\/ TODO: Test this a bit more, what happens with random failures in\n\t\t\t\/\/ the files?\n\/\/\t\t\tif ((rand() % 100) > 80)\n\/\/\t\t\t\tthrow file_error(\"debug\");\n\n#ifdef _WIN32\n\t\t\tsize_type ret = ::_write(m_fd, buf, num_bytes);\n#else\n\t\t\tsize_type ret = ::write(m_fd, buf, num_bytes);\n#endif\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"write failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tvoid set_size(size_type s)\n\t\t{\n\t\t\tsize_type pos = tell();\n\t\t\t\/\/ Only set size if current file size not equals s.\n\t\t\t\/\/ 2 as \"m\" argument is to be sure seek() sets SEEK_END on\n\t\t\t\/\/ all compilers.\n\t\t\tif(s != seek(0, 2))\n\t\t\t{\n\t\t\t\tseek(s - 1);\n\t\t\t\tchar dummy = 0;\n\t\t\t\tread(&dummy, 1);\n\t\t\t\tseek(s - 1);\n\t\t\t\twrite(&dummy, 1);\n\t\t\t}\n\t\t\tseek(pos);\n\t\t}\n\n\t\tsize_type seek(size_type offset, int m = 1)\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tint seekdir = (m == 1)?SEEK_SET:SEEK_END;\n#ifdef _WIN32\n\t\t\tsize_type ret = _lseeki64(m_fd, offset, seekdir);\n#else\n\t\t\tsize_type ret = lseek(m_fd, offset, seekdir);\n#endif\n\n\t\t\t\/\/ For some strange reason this fails\n\t\t\t\/\/ on win32. Use windows specific file\n\t\t\t\/\/ wrapper instead.\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"seek failed: '\" << strerror(errno)\n\t\t\t\t\t<< \"' fd: \" << m_fd\n\t\t\t\t\t<< \" offset: \" << offset\n\t\t\t\t\t<< \" seekdir: \" << seekdir;\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type tell()\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n#ifdef _WIN32\n\t\t\treturn _telli64(m_fd);\n#else\n\t\t\treturn lseek(m_fd, 0, SEEK_CUR);\n#endif\n\t\t}\n\n\t\tint m_fd;\n\t\tint m_open_mode;\n\t};\n\n\t\/\/ pimpl forwardings\n\n\tfile::file() : m_impl(new impl()) {}\n\n\tfile::file(fs::path const& p, file::open_mode m)\n\t\t: m_impl(new impl(p, m.m_mask))\n\t{}\n\n\tfile::~file() {}\n\n\tvoid file::open(fs::path const& p, file::open_mode m)\n\t{\n\t\tm_impl->open(p, m.m_mask);\n\t}\n\n\tvoid file::close()\n\t{\n\t\tm_impl->close();\n\t}\n\n\tsize_type file::write(const char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->write(buf, num_bytes);\n\t}\n\n\tsize_type file::read(char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->read(buf, num_bytes);\n\t}\n\n\tvoid file::set_size(size_type s)\n\t{\n\t\tm_impl->set_size(s);\n\t}\n\n\tsize_type file::seek(size_type pos, file::seek_mode m)\n\t{\n\t\treturn m_impl->seek(pos, m.m_val);\n\t}\n\n\tsize_type file::tell()\n\t{\n\t\treturn m_impl->tell();\n\t}\n\n}\n<commit_msg>changed to use ftruncate to allocate files<commit_after>\/*\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#ifdef _WIN32\n\/\/ windows part\n#include \"libtorrent\/utf8.hpp\"\n\n#include <io.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#ifndef _MODE_T_\ntypedef int mode_t;\n#endif\n\n#ifdef UNICODE\n#include \"libtorrent\/storage.hpp\"\n#endif\n\n#else\n\/\/ unix part\n#define _FILE_OFFSET_BITS 64\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <errno.h>\n\n#include <boost\/static_assert.hpp>\n\/\/ make sure the _FILE_OFFSET_BITS define worked\n\/\/ on this platform\nBOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);\n\n#endif\n\n#include <boost\/filesystem\/operations.hpp>\n#include \"libtorrent\/file.hpp\"\n#include <sstream>\n\n#ifndef O_BINARY\n#define O_BINARY 0\n#endif\n\n#ifndef O_RANDOM\n#define O_RANDOM 0\n#endif\n\n#ifdef UNICODE\n#include \"libtorrent\/storage.hpp\"\n#endif\n\n\nnamespace\n{\n\tenum { mode_in = 1, mode_out = 2 };\n\n\tmode_t map_open_mode(int m)\n\t{\n\t\tif (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;\n\t\tassert(false);\n\t\treturn 0;\n\t}\n\n#ifdef WIN32\n\tstd::string utf8_native(std::string const& s)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstd::wstring ws;\n\t\t\tlibtorrent::utf8_wchar(s, ws);\n\t\t\tstd::size_t size = wcstombs(0, ws.c_str(), 0);\n\t\t\tif (size == std::size_t(-1)) return s;\n\t\t\tstd::string ret;\n\t\t\tret.resize(size);\n\t\t\tsize = wcstombs(&ret[0], ws.c_str(), size + 1);\n\t\t\tif (size == wchar_t(-1)) return s;\n\t\t\tret.resize(size);\n\t\t\treturn ret;\n\t\t}\n\t\tcatch(std::exception)\n\t\t{\n\t\t\treturn s;\n\t\t}\n\t}\n#else\n\tstd::string utf8_native(std::string const& s)\n\t{\n\t\treturn s;\n\t}\n#endif\n\n}\n\nnamespace libtorrent\n{\n\n\tnamespace fs = boost::filesystem;\n\n\tconst file::open_mode file::in(mode_in);\n\tconst file::open_mode file::out(mode_out);\n\n\tconst file::seek_mode file::begin(1);\n\tconst file::seek_mode file::end(2);\n\n\tstruct file::impl\n\t{\n\t\timpl()\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{}\n\n\t\timpl(fs::path const& path, int mode)\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{\n\t\t\topen(path, mode);\n\t\t}\n\n\t\t~impl()\n\t\t{\n\t\t\tclose();\n\t\t}\n\n\t\tvoid open(fs::path const& path, int mode)\n\t\t{\n\t\t\tassert(path.is_complete());\n\t\t\tclose();\n#if defined(_WIN32) && defined(UNICODE)\n\t\t\tstd::wstring wpath(safe_convert(path.native_file_string()));\n\t\t\tm_fd = ::_wopen(\n\t\t\t\twpath.c_str()\n\t\t\t\t, map_open_mode(mode)\n\t\t\t\t, S_IREAD | S_IWRITE);\n#else\n#ifdef _WIN32\n\t\t\tm_fd = ::_open(\n#else\n\t\t\tm_fd = ::open(\n#endif\n\t\t\t\tutf8_native(path.native_file_string()).c_str()\n\t\t\t\t, map_open_mode(mode)\n#ifdef _WIN32\n\t\t\t\t, S_IREAD | S_IWRITE);\n#else\n\t\t\t\t, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n#endif\n#endif\n\t\t\tif (m_fd == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"open failed: '\" << path.native_file_string() << \"'. \"\n\t\t\t\t\t<< strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\tm_open_mode = mode;\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (m_fd == -1) return;\n\n#ifdef _WIN32\n\t\t\t::_close(m_fd);\n#else\n\t\t\t::close(m_fd);\n#endif\n\t\t\tm_fd = -1;\n\t\t\tm_open_mode = 0;\n\t\t}\n\n\t\tsize_type read(char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode & mode_in);\n\t\t\tassert(m_fd != -1);\n\n#ifdef _WIN32\n\t\t\tsize_type ret = ::_read(m_fd, buf, num_bytes);\n#else\n\t\t\tsize_type ret = ::read(m_fd, buf, num_bytes);\n#endif\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"read failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type write(const char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode & mode_out);\n\t\t\tassert(m_fd != -1);\n\n\t\t\t\/\/ TODO: Test this a bit more, what happens with random failures in\n\t\t\t\/\/ the files?\n\/\/\t\t\tif ((rand() % 100) > 80)\n\/\/\t\t\t\tthrow file_error(\"debug\");\n\n#ifdef _WIN32\n\t\t\tsize_type ret = ::_write(m_fd, buf, num_bytes);\n#else\n\t\t\tsize_type ret = ::write(m_fd, buf, num_bytes);\n#endif\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"write failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tvoid set_size(size_type s)\n\t\t{\n#ifdef _WIN32\n#error file.cpp is for posix systems only. use file_win.cpp on windows\n#else\n\t\t\tif (ftruncate(m_fd, s) < 0)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"ftruncate failed: '\" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n#endif\n\t\t}\n\n\t\tsize_type seek(size_type offset, int m = 1)\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tint seekdir = (m == 1)?SEEK_SET:SEEK_END;\n#ifdef _WIN32\n\t\t\tsize_type ret = _lseeki64(m_fd, offset, seekdir);\n#else\n\t\t\tsize_type ret = lseek(m_fd, offset, seekdir);\n#endif\n\n\t\t\t\/\/ For some strange reason this fails\n\t\t\t\/\/ on win32. Use windows specific file\n\t\t\t\/\/ wrapper instead.\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"seek failed: '\" << strerror(errno)\n\t\t\t\t\t<< \"' fd: \" << m_fd\n\t\t\t\t\t<< \" offset: \" << offset\n\t\t\t\t\t<< \" seekdir: \" << seekdir;\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type tell()\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n#ifdef _WIN32\n\t\t\treturn _telli64(m_fd);\n#else\n\t\t\treturn lseek(m_fd, 0, SEEK_CUR);\n#endif\n\t\t}\n\n\t\tint m_fd;\n\t\tint m_open_mode;\n\t};\n\n\t\/\/ pimpl forwardings\n\n\tfile::file() : m_impl(new impl()) {}\n\n\tfile::file(fs::path const& p, file::open_mode m)\n\t\t: m_impl(new impl(p, m.m_mask))\n\t{}\n\n\tfile::~file() {}\n\n\tvoid file::open(fs::path const& p, file::open_mode m)\n\t{\n\t\tm_impl->open(p, m.m_mask);\n\t}\n\n\tvoid file::close()\n\t{\n\t\tm_impl->close();\n\t}\n\n\tsize_type file::write(const char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->write(buf, num_bytes);\n\t}\n\n\tsize_type file::read(char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->read(buf, num_bytes);\n\t}\n\n\tvoid file::set_size(size_type s)\n\t{\n\t\tm_impl->set_size(s);\n\t}\n\n\tsize_type file::seek(size_type pos, file::seek_mode m)\n\t{\n\t\treturn m_impl->seek(pos, m.m_val);\n\t}\n\n\tsize_type file::tell()\n\t{\n\t\treturn m_impl->tell();\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\n\/*\nCopyright (c) 2007-2009, Trustees of The Leland Stanford Junior University\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.\nNeither the name of the Stanford University nor the names of its contributors \nmay be used to endorse or promote products derived from this software without \nspecific prior written permission.\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 OWNER 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\/*flit.cpp\n *\n *flit struct is a flit, carries all the control signals that a flit needs\n *Add additional signals as necessary. Flits has no concept of length\n *it is a singluar object.\n *\n *When adding objects make sure to set a default value in this constructor\n *\/\n\n#include \"booksim.hpp\"\n#include \"flit.hpp\"\n\nstack<Flit *> Flit::_pool;\n\nostream& operator<<( ostream& os, const Flit& f )\n{\n os << \" Flit ID: \" << f.id << \" (\" << &f << \")\" \n << \" Packet ID: \" << f.pid\n << \" Type: \" << f.type \n << \" Head: \" << f.head << \" Tail: \" << f.tail << endl;\n os << \" Source: \" << f.src << \" Dest: \" << f.dest << \" Intm: \"<<f.intm<<endl;\n os << \" Injection time: \" << f.time << \" Transaction start: \" << f.ttime << \"Arrival time: \" << f.atime << \" Phase: \"<<f.ph<< endl;\n os << \" From router \"<<f.from_router<< \" VC: \" << f.vc << endl;\n return os;\n}\n\nFlit::Flit() \n{ \n Reset();\n} \n\nvoid Flit::Reset() \n{ \n type = ANY_TYPE ;\n vc = -1 ;\n head = false ;\n tail = false ;\n true_tail = false ;\n time = -1 ;\n ttime = -1 ;\n atime = -1 ;\n sn = 0 ;\n rob_time = 0 ;\n id = -1 ;\n pid = -1 ;\n hops = 0 ;\n watch = false ;\n record = false ;\n intm = 0;\n src = -1;\n dest = -1;\n pri = 0;\n intm =-1;\n ph = -1;\n dr = -1;\n minimal = 1;\n ring_par = -1;\n x_then_y = -1;\n data = 0;\n from_router = -1;\n} \n\nFlit * Flit::New() {\n Flit * f;\n if(_pool.empty()) {\n f = new Flit;\n } else {\n f = _pool.top();\n f->Reset();\n _pool.pop();\n }\n return f;\n}\n\nvoid Flit::Free() {\n _pool.push(this);\n}\n\nvoid Flit::FreePool() {\n while(_pool.empty()) {\n delete _pool.top();\n _pool.pop();\n }\n}\n<commit_msg>fix flit pool free<commit_after>\/\/ $Id$\n\n\/*\nCopyright (c) 2007-2009, Trustees of The Leland Stanford Junior University\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.\nNeither the name of the Stanford University nor the names of its contributors \nmay be used to endorse or promote products derived from this software without \nspecific prior written permission.\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 OWNER 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\/*flit.cpp\n *\n *flit struct is a flit, carries all the control signals that a flit needs\n *Add additional signals as necessary. Flits has no concept of length\n *it is a singluar object.\n *\n *When adding objects make sure to set a default value in this constructor\n *\/\n\n#include \"booksim.hpp\"\n#include \"flit.hpp\"\n\nstack<Flit *> Flit::_pool;\n\nostream& operator<<( ostream& os, const Flit& f )\n{\n os << \" Flit ID: \" << f.id << \" (\" << &f << \")\" \n << \" Packet ID: \" << f.pid\n << \" Type: \" << f.type \n << \" Head: \" << f.head << \" Tail: \" << f.tail << endl;\n os << \" Source: \" << f.src << \" Dest: \" << f.dest << \" Intm: \"<<f.intm<<endl;\n os << \" Injection time: \" << f.time << \" Transaction start: \" << f.ttime << \"Arrival time: \" << f.atime << \" Phase: \"<<f.ph<< endl;\n os << \" From router \"<<f.from_router<< \" VC: \" << f.vc << endl;\n return os;\n}\n\nFlit::Flit() \n{ \n Reset();\n} \n\nvoid Flit::Reset() \n{ \n type = ANY_TYPE ;\n vc = -1 ;\n head = false ;\n tail = false ;\n true_tail = false ;\n time = -1 ;\n ttime = -1 ;\n atime = -1 ;\n sn = 0 ;\n rob_time = 0 ;\n id = -1 ;\n pid = -1 ;\n hops = 0 ;\n watch = false ;\n record = false ;\n intm = 0;\n src = -1;\n dest = -1;\n pri = 0;\n intm =-1;\n ph = -1;\n dr = -1;\n minimal = 1;\n ring_par = -1;\n x_then_y = -1;\n data = 0;\n from_router = -1;\n} \n\nFlit * Flit::New() {\n Flit * f;\n if(_pool.empty()) {\n f = new Flit;\n } else {\n f = _pool.top();\n f->Reset();\n _pool.pop();\n }\n return f;\n}\n\nvoid Flit::Free() {\n _pool.push(this);\n}\n\nvoid Flit::FreePool() {\n while(!_pool.empty()) {\n delete _pool.top();\n _pool.pop();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _1af7690b_7fca_4464_9e14_c71bc5a29ee9\n#define _1af7690b_7fca_4464_9e14_c71bc5a29ee9\n\nnamespace fn{\n\nnamespace _ {\n\ntemplate<typename C>\nstruct noconst{ typedef C T; };\ntemplate<typename B>\nstruct noconst<B const&>{ typedef B T; };\n\ntemplate<typename T>\nstruct IsTrue{ bool operator()(T i)const {return static_cast<bool>(i);} };\n\ntemplate<typename T>\nconstexpr bool is_void() {return false;}\ntemplate<>\nconstexpr bool is_void<void>() {return true;}\n\ntemplate<typename T>\nclass Range\n{\n class IT\n {\n public:\n IT(T const& position): position(position) {}\n IT(T const& position, T const& step): position(position),step(step) {}\n bool operator!=(IT const& other)const {return position!=other.position;}\n IT const& operator++() {position+=step;return *this;}\n T const& operator*()const {return position;}\n private:\n T position;\n T step = 1;\n };\n\n IT from;\n IT const to;\npublic:\n Range(T const& to): from(0), to(to) {}\n IT const& begin()const { return from; }\n IT const& end()const { return to; }\n};};\n\ntemplate<typename T,typename ...Args>\nauto range(T const& t,Args const& ...args) -> _::Range<T>{\n return _::Range<T>(t,args...);\n}\n\nnamespace _ {\ntemplate<typename FN,typename G, typename OtherIT>\nclass Map\n{\n class IT\n {\n private:\n FN const& fn;\n OtherIT other_it;\n public:\n IT(FN fn,OtherIT other_it): fn(fn), other_it(other_it) {}\n bool operator!=(IT& other){return other_it!=other.other_it;}\n IT const& operator++() {++other_it;return *this;}\n auto operator*()const -> decltype(fn(*other_it)) {return fn(*other_it);}\n };\n\n IT const from;\n IT const to;\n\npublic:\n Map(FN fn, G const& g): from(fn,g.begin()), to(fn,g.end()) {}\n IT const& begin() const { return from; }\n IT const& end() const { return to; }\n};};\n\ntemplate<typename FN,typename G>\nauto map(FN const& fn,G const& g) -> _::Map<FN,G,\n typename _::noconst<decltype(g.begin())>::T>{\n return _::Map<FN,G,typename _::noconst<decltype(g.begin())>::T>(fn,g);\n}\n\nnamespace _ {\ntemplate<\n template<typename,typename> class PairT,\n typename A,\n typename B,\n typename OtherIT1,\n typename OtherIT2\n>\nclass Zip\n{\n class IT\n {\n private:\n OtherIT1 other_it1;\n OtherIT2 other_it2;\n typedef PairT<decltype(*other_it1),decltype(*other_it2)> Pair;\n\n public:\n IT(OtherIT1 other_it1,OtherIT2 other_it2):\n other_it1(other_it1),other_it2(other_it2) {}\n bool operator!=(IT& other){\n return (\n (other_it1!=other.other_it1) && (other_it2 != other.other_it2)\n );\n }\n IT const& operator++() {++other_it1;++other_it2;return *this;}\n auto operator*()const -> decltype(Pair{*other_it1,*other_it2}) {\n return Pair{*other_it1,*other_it2};\n }\n };\n\n IT const from;\n IT const to;\n\npublic:\n Zip(A const& a, B const& b):\n from(a.begin(),b.begin()), to(a.end(),b.end()) {}\n IT const& begin() const { return from; }\n IT const& end() const { return to; }\n};};\n\nnamespace _ {\ntemplate<typename A, typename B>\nstruct Pair\n{\n Pair(A&& a, B&& b):\n first(a),second(b),\n key(a),value(b),\n nr(a),item(b)\n {}\n\n A&& first;\n B&& second;\n\n A&& key;\n B&& value;\n\n A&& nr;\n B&& item;\n};};\n\ntemplate<template<typename,typename> class PairT=_::Pair, typename A,typename B>\nauto zip(A const& a,B const& b) -> _::Zip<PairT,A,B,\n typename _::noconst<decltype(a.begin())>::T,\n typename _::noconst<decltype(b.begin())>::T\n >{\n return _::Zip<PairT,A,B,\n typename _::noconst<decltype(a.begin())>::T,\n typename _::noconst<decltype(b.begin())>::T\n >(a,b);\n}\n\ntemplate<typename A>\nauto enumerate(A const& a)\n ->decltype(zip(range(-1),a))\n{\n return zip(range(-1),a);\n}\n\nnamespace _ {\ntemplate<typename FN,typename G, typename OtherIT>\nclass Filter\n{\n class IT\n {\n private:\n FN const& fn;\n OtherIT other_it;\n public:\n IT(FN fn,OtherIT other_it): fn(fn), other_it(other_it){}\n bool operator!=(IT& other){\n while(other_it!=other.other_it && !fn(*other_it)){ ++other_it; }\n return other_it!=other.other_it;\n }\n IT const& operator++() { ++other_it; return *this; }\n auto operator*()const -> decltype(*other_it) { return *other_it; }\n };\n\n IT const from;\n IT const to;\n\npublic:\n Filter(FN fn, G const& g): from(fn,g.begin()), to(fn,g.end()) {}\n IT const& begin() const { return from; }\n IT const& end() const { return to; }\n};};\n\ntemplate<typename FN,typename G>\nauto filter(FN const& fn,G const& g) -> _::Filter<FN,G,\n typename _::noconst<decltype(g.begin())>::T>\n{\n return _::Filter<FN,G,typename _::noconst<decltype(g.begin())>::T>(fn,g);\n}\n\ntemplate<typename G>\nauto filter(G const& g)\n -> decltype(filter(_::IsTrue<decltype(*g.begin())>{},(*g.begin(),g)))\n{\n return filter(_::IsTrue<decltype(*g.begin())>{},g);\n}\n\n\ntemplate<typename T>\nclass optional\n{\npublic:\n typedef T Type;\n optional(optional const&) = delete;\n inline optional(optional const&& original):\n has_value(original.has_value),\n value(original.value){}\n\n inline optional(): has_value(false){}\n inline optional(T const& value): has_value(true), value(value){}\n\n inline T const& operator||(T const& fallback) const\n {\n return (*this)(\n [](T const& v)->T const& {return v;},\n [&]()->T const& {return fallback;}\n );\n }\n\n template<typename ValueF>\n inline optional const& operator()(\n ValueF const& handle_value) const\n {\n static_assert(_::is_void<\n decltype(handle_value(const_cast<T const&>(value)))>() == true,\n \"this function must not have a return value\"\n );\n if(has_value) {handle_value(const_cast<T const&>(value));}\n return *this;\n }\n\n template<typename ValueF, typename EmptyF>\n inline auto operator()(\n ValueF const& handle_value,\n EmptyF const& handle_no_value) const\n ->decltype(handle_value(*reinterpret_cast<T*>(0)))\n {\n return has_value ?\n handle_value(const_cast<T const&>(value))\n : handle_no_value();\n }\n\n explicit operator bool() const& { return has_value; };\n\nprivate:\n bool const has_value;\n T value;\n};\n\n};\n\n#endif\n<commit_msg>Visual C++ fixes<commit_after>#ifndef _1af7690b_7fca_4464_9e14_c71bc5a29ee9\n#define _1af7690b_7fca_4464_9e14_c71bc5a29ee9\n\nnamespace fn{\n\nnamespace _ {\n\ntemplate<typename C>\nstruct noconst{ typedef C T; };\ntemplate<typename B>\nstruct noconst<B const&>{ typedef B T; };\n\ntemplate<typename T>\nstruct IsTrue{ bool operator()(T i)const {return static_cast<bool>(i);} };\n\n#ifndef _MSC_VER\ntemplate<typename T>\nconstexpr bool is_void() {return false;}\ntemplate<>\nconstexpr bool is_void<void>() {return true;}\n#else\n#define or ||\n#endif\n\ntemplate<typename T>\nclass Range\n{\n class IT\n {\n public:\n typedef T value_type;\n IT(T const& position): position(position) {}\n IT(T const& position, T const& step): position(position),step(step) {}\n bool operator!=(IT const& other)const {return position!=other.position;}\n IT const& operator++() {position+=step;return *this;}\n T const& operator*()const {return position;}\n private:\n T position;\n T step = 1;\n };\n\n IT from;\n IT const to;\npublic:\n Range(T const& to): from(0), to(to) {}\n IT const& begin()const { return from; }\n IT const& end()const { return to; }\n};};\n\ntemplate<typename T,typename ...Args>\nauto range(T const& t,Args const& ...args) -> _::Range<T>{\n return _::Range<T>(t,args...);\n}\n\nnamespace _ {\ntemplate<typename FN,typename G, typename OtherIT>\nclass Map\n{\n class IT\n {\n private:\n FN const& fn;\n OtherIT other_it;\n public:\n typedef decltype(fn(*other_it)) value_type;\n IT(FN fn,OtherIT other_it): fn(fn), other_it(other_it) {}\n bool operator!=(IT& other){return other_it!=other.other_it;}\n IT const& operator++() {++other_it;return *this;}\n auto operator*()const -> value_type {return fn(*other_it);}\n };\n\n IT const from;\n IT const to;\n\npublic:\n Map(FN fn, G const& g): from(fn,g.begin()), to(fn,g.end()) {}\n IT const& begin() const { return from; }\n IT const& end() const { return to; }\n};};\n\ntemplate<typename FN,typename G>\nauto map(FN const& fn,G const& g) -> _::Map<FN,G,\n typename _::noconst<decltype(g.begin())>::T>{\n return _::Map<FN,G,typename _::noconst<decltype(g.begin())>::T>(fn,g);\n}\n\nnamespace _ {\ntemplate<\n template<typename,typename> class PairT,\n typename A,\n typename B,\n typename OtherIT1,\n typename OtherIT2\n>\nclass Zip\n{\n class IT\n {\n private:\n OtherIT1 other_it1;\n OtherIT2 other_it2;\n typedef typename OtherIT1::value_type const OtherVal1;\n typedef typename OtherIT2::value_type const OtherVal2;\n typedef PairT<OtherVal1,OtherVal2> Pair;\n\n public:\n typedef Pair value_type;\n\n IT(OtherIT1 other_it1,OtherIT2 other_it2):\n other_it1(other_it1),other_it2(other_it2) {}\n bool operator!=(IT& other){\n return (\n (other_it1!=other.other_it1) && (other_it2 != other.other_it2)\n );\n }\n IT const& operator++() {++other_it1;++other_it2;return *this;}\n\n Pair operator*() {\n return Pair(*other_it1,*other_it2);\n }\n };\n\n IT const from;\n IT const to;\n\npublic:\n Zip(A const& a, B const& b):\n from(a.begin(),b.begin()), to(a.end(),b.end()) {}\n IT const& begin() const { return from; }\n IT const& end() const { return to; }\n};};\n\nnamespace _ {\ntemplate<typename A, typename B>\nstruct Pair\n{\n Pair(A& a, B& b):\n first(a),second(b),\n key(a),value(b),\n nr(a),item(b)\n {}\n\n A& first;\n B& second;\n\n A& key;\n B& value;\n\n A& nr;\n B& item;\n};};\n\ntemplate<template<typename,typename> class PairT=_::Pair, typename A,typename B>\nauto zip(A const& a,B const& b) -> _::Zip<PairT,A,B,\n typename _::noconst<decltype(a.begin())>::T,\n typename _::noconst<decltype(b.begin())>::T\n >{\n return _::Zip<PairT,A,B,\n typename _::noconst<decltype(a.begin())>::T,\n typename _::noconst<decltype(b.begin())>::T\n >(a,b);\n}\n\ntemplate<typename A>\nauto enumerate(A const& a)\n ->decltype(zip(range(-1),a))\n{\n return zip(range(-1),a);\n}\n\nnamespace _ {\ntemplate<typename FN,typename G, typename OtherIT>\nclass Filter\n{\n class IT\n {\n private:\n FN const& fn;\n OtherIT other_it;\n public:\n typedef typename OtherIT::value_type value_type;\n\n IT(FN fn,OtherIT other_it): fn(fn), other_it(other_it){}\n bool operator!=(IT& other){\n while(other_it!=other.other_it && !fn(*other_it)){ ++other_it; }\n return other_it!=other.other_it;\n }\n IT const& operator++() { ++other_it; return *this; }\n auto operator*()const -> decltype(*other_it) { return *other_it; }\n };\n\n IT const from;\n IT const to;\n\npublic:\n Filter(FN fn, G const& g): from(fn,g.begin()), to(fn,g.end()) {}\n IT const& begin() const { return from; }\n IT const& end() const { return to; }\n};};\n\ntemplate<typename FN,typename G>\nauto filter(FN const& fn,G const& g) -> _::Filter<FN,G,\n typename _::noconst<decltype(g.begin())>::T>\n{\n return _::Filter<FN,G,typename _::noconst<decltype(g.begin())>::T>(fn,g);\n}\n\ntemplate<typename G>\nauto filter(G const& g)\n -> decltype(filter(_::IsTrue<decltype(*g.begin())>{},(*g.begin(),g)))\n{\n return filter(_::IsTrue<decltype(*g.begin())>{},g);\n}\n\n\ntemplate<typename T>\nclass optional\n{\npublic:\n typedef T Type;\n optional(optional const&) = delete;\n inline optional(optional const&& original):\n has_value(original.has_value),\n value(original.value){}\n\n inline optional(): has_value(false){}\n inline optional(T const& value): has_value(true), value(value){}\n\n inline T const& operator||(T const& fallback) const\n {\n return (*this)(\n [](T const& v)->T const& {return v;},\n [&]()->T const& {return fallback;}\n );\n }\n\n template<typename ValueF>\n inline optional const& operator()(\n ValueF const& handle_value) const\n {\n#ifndef _MSC_VER\n static_assert(_::is_void<\n decltype(handle_value(const_cast<T const&>(value)))>() == true,\n \"this function must not have a return value\"\n );\n#endif\n if(has_value) {handle_value(const_cast<T const&>(value));}\n return *this;\n }\n\n template<typename ValueF, typename EmptyF>\n inline auto operator()(\n ValueF const& handle_value,\n EmptyF const& handle_no_value) const\n ->decltype(handle_value(*reinterpret_cast<T*>(0)))\n {\n return has_value ?\n handle_value(const_cast<T const&>(value))\n : handle_no_value();\n }\n\n explicit operator bool() const { return has_value; };\n\nprivate:\n bool const has_value;\n T value;\n};\n\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"game.hpp\"\n#include \"exception.hpp\"\n\nnamespace Quoridor {\n\n\/\/ order in which pawns are adding\n\/\/ pawns rotates according to their indexes: 0 -> 1 -> 2 -> 3 -> 0 -> ...\nstatic const std::vector<int> pawn_idx_list = {0, 2, 1, 3};\n\nGame::Game(int board_size) : board_size_(board_size), pawn_data_list_(),\n cur_pawn_idx_(-1), bg_(board_size_, board_size_), wg_(board_size_ + 1)\n{\n}\n\nGame::~Game()\n{\n}\n\nvoid Game::set_pawns(std::vector<std::shared_ptr<Pawn>> &pawn_list)\n{\n size_t pawn_num = pawn_list.size();\n if ((pawn_num != 2) && (pawn_num != 4)) {\n throw Exception(\"Invalid number of players: \" + std::to_string(pawn_num));\n }\n\n\n for (size_t i = 0; i < pawn_list.size(); ++i) {\n pawn_data_t pawn_data;\n pawn_data.pawn = pawn_list[i];\n\n pawn_data.idx = pawn_idx_list[i];\n switch (pawn_data.idx) {\n case 0:\n pawn_data.node.set_row(0);\n pawn_data.node.set_col(board_size_ \/ 2);\n bg_.block_node(pawn_data.node);\n for (int j = 0; j < board_size_; ++j) {\n Node gn(board_size_ - 1, j);\n pawn_data.goal_nodes.insert(gn);\n }\n break;\n case 1:\n pawn_data.node.set_row(board_size_ \/ 2);\n pawn_data.node.set_col(0);\n bg_.block_node(pawn_data.node);\n for (int j = 0; j < board_size_; ++j) {\n Node gn(j, board_size_ - 1);\n pawn_data.goal_nodes.insert(gn);\n }\n break;\n case 2:\n pawn_data.node.set_row(board_size_ - 1);\n pawn_data.node.set_col(board_size_ \/ 2);\n bg_.block_node(pawn_data.node);\n for (int j = 0; j < board_size_; ++j) {\n Node gn(0, j);\n pawn_data.goal_nodes.insert(gn);\n }\n break;\n case 3:\n pawn_data.node.set_row(board_size_ \/ 2);\n pawn_data.node.set_col(board_size_ - 1);\n bg_.block_node(pawn_data.node);\n for (int j = 0; j < board_size_; ++j) {\n Node gn(j, 0);\n pawn_data.goal_nodes.insert(gn);\n }\n break;\n }\n\n pawn_data_list_.insert(pawn_data);\n }\n}\n\nvoid Game::switch_pawn()\n{\n auto it = pawn_data_list_.upper_bound(cur_pawn_idx_);\n if (it == pawn_data_list_.end()) {\n it = pawn_data_list_.begin();\n }\n cur_pawn_idx_ = it->idx;\n}\n\nconst pawn_data_t &Game::cur_pawn_data() const\n{\n return *pawn_data_list_.find(cur_pawn_idx_);\n}\n\nconst pawn_data_list_t &Game::pawn_data_list() const\n{\n return pawn_data_list_;\n}\n\nconst pawn_data_t &Game::pawn_data(std::shared_ptr<Pawn> &pawn) const\n{\n return *pawn_data_list_.get<by_pawn>().find(pawn);\n}\n\nint Game::move_pawn(const Node &node)\n{\n const Node &cur_node = pawn_data_list_.find(cur_pawn_idx_)->node;\n\n if (bg_.is_adjacent(cur_node, node)) {\n bg_.unblock_node(cur_node);\n pawn_data_list_t::iterator it = pawn_data_list_.find(cur_pawn_idx_);\n pawn_data_list_.modify(it, [=](pawn_data_t &e){ e.node = node; });\n bg_.block_node(node);\n return 0;\n }\n else {\n return -1;\n }\n}\n\nint Game::add_wall(const Wall &wall)\n{\n std::vector<std::pair<Node, Node>> edges;\n\n if (try_add_wall(wall, &edges) < 0) {\n return -1;\n }\n\n wg_.apply_tmp_wall();\n for (auto edge : edges) {\n bg_.remove_edges(edge.first, edge.second);\n }\n\n return 0;\n}\n\nbool Game::is_finished() const\n{\n Node cur_node = pawn_data_list_.find(cur_pawn_idx_)->node;\n if (pawn_data_list_.find(cur_pawn_idx_)->goal_nodes.count(cur_node) != 0) {\n return true;\n }\n return false;\n}\n\nbool Game::get_path(std::shared_ptr<Pawn> pawn, const Node &node,\n std::list<Node> *path) const\n{\n return bg_.find_path(pawn_data(pawn).node, node, path);\n}\n\nint Game::try_add_wall(const Wall &wall,\n std::vector<std::pair<Node, Node>> *edges)\n{\n if (wg_.add_tmp_wall(wall) < 0) {\n return -1;\n }\n\n bg_.reset_filters();\n\n Node node1;\n Node node2;\n Node node_tmp;\n if (wall.orientation() == Wall::kHorizontal) {\n for (int i = 0; i < wall.cnt(); ++i) {\n node1 = Node(wall.row() - 1, wall.col() + i);\n node2 = Node(wall.row(), wall.col() + i);\n bg_.filter_edges(node1, node2);\n edges->push_back(std::make_pair(node1, node2));\n\n node_tmp = Node(wall.row() + 1, wall.col() + i);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n bg_.filter_edges(node1, node_tmp);\n edges->push_back(std::make_pair(node1, node_tmp));\n }\n\n node_tmp = Node(wall.row() - 2, wall.col() + i);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n bg_.filter_edges(node_tmp, node2);\n edges->push_back(std::make_pair(node_tmp, node2));\n }\n\n for (int j = i - 1; j <= i + 1; j += 2) {\n node_tmp = Node(wall.row(), wall.col() + j);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n bg_.filter_edges(node1, node_tmp);\n edges->push_back(std::make_pair(node1, node_tmp));\n }\n\n node_tmp = Node(wall.row() - 1, wall.col() + j);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n bg_.filter_edges(node_tmp, node2);\n edges->push_back(std::make_pair(node_tmp, node2));\n }\n }\n }\n }\n else if (wall.orientation() == Wall::kVertical) {\n for (int i = 0; i < wall.cnt(); ++i) {\n node1 = Node(wall.row() + i, wall.col() - 1);\n node2 = Node(wall.row() + i, wall.col());\n bg_.filter_edges(node1, node2);\n edges->push_back(std::make_pair(node1, node2));\n\n node_tmp = Node(wall.row() + i, wall.col() + 1);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n bg_.filter_edges(node1, node_tmp);\n edges->push_back(std::make_pair(node1, node_tmp));\n }\n\n node_tmp = Node(wall.row() + i, wall.col() - 2);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n bg_.filter_edges(node_tmp, node2);\n edges->push_back(std::make_pair(node_tmp, node2));\n }\n\n for (int j = i - 1; j <= i + 1; j += 2) {\n node_tmp = Node(wall.row() + j, wall.col());\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n bg_.filter_edges(node1, node_tmp);\n edges->push_back(std::make_pair(node1, node_tmp));\n }\n\n node_tmp = Node(wall.row() + j, wall.col() - 1);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n bg_.filter_edges(node_tmp, node2);\n edges->push_back(std::make_pair(node_tmp, node2));\n }\n }\n }\n }\n else {\n return -1;\n }\n\n bool path_blocked = false;\n\n for (auto pawn_data : pawn_data_list_) {\n path_blocked = true;\n for (auto goal_node : pawn_data.goal_nodes) {\n if (bg_.is_path_exists(pawn_data.node, goal_node)) {\n path_blocked = false;\n break;\n }\n }\n\n \/\/ wall blocks all pathes to the opposite side for one of pawns\n if (path_blocked) {\n break;\n }\n }\n\n if (path_blocked) {\n return -1;\n }\n\n return 0;\n}\n\n} \/\/ namespace Quoridor\n<commit_msg>Fix BoardGraph usage in Game<commit_after>#include \"game.hpp\"\n#include \"exception.hpp\"\n\nnamespace Quoridor {\n\n\/\/ order in which pawns are adding\n\/\/ pawns rotates according to their indexes: 0 -> 1 -> 2 -> 3 -> 0 -> ...\nstatic const std::vector<int> pawn_idx_list = {0, 2, 1, 3};\n\nGame::Game(int board_size) : board_size_(board_size), pawn_data_list_(),\n cur_pawn_idx_(-1), bg_(board_size_, board_size_), wg_(board_size_ + 1)\n{\n}\n\nGame::~Game()\n{\n}\n\nvoid Game::set_pawns(std::vector<std::shared_ptr<Pawn>> &pawn_list)\n{\n size_t pawn_num = pawn_list.size();\n if ((pawn_num != 2) && (pawn_num != 4)) {\n throw Exception(\"Invalid number of players: \" + std::to_string(pawn_num));\n }\n\n\n for (size_t i = 0; i < pawn_list.size(); ++i) {\n pawn_data_t pawn_data;\n pawn_data.pawn = pawn_list[i];\n\n pawn_data.idx = pawn_idx_list[i];\n switch (pawn_data.idx) {\n case 0:\n pawn_data.node.set_row(0);\n pawn_data.node.set_col(board_size_ \/ 2);\n bg_.block_node(pawn_data.node);\n for (int j = 0; j < board_size_; ++j) {\n Node gn(board_size_ - 1, j);\n pawn_data.goal_nodes.insert(gn);\n }\n break;\n case 1:\n pawn_data.node.set_row(board_size_ \/ 2);\n pawn_data.node.set_col(0);\n bg_.block_node(pawn_data.node);\n for (int j = 0; j < board_size_; ++j) {\n Node gn(j, board_size_ - 1);\n pawn_data.goal_nodes.insert(gn);\n }\n break;\n case 2:\n pawn_data.node.set_row(board_size_ - 1);\n pawn_data.node.set_col(board_size_ \/ 2);\n bg_.block_node(pawn_data.node);\n for (int j = 0; j < board_size_; ++j) {\n Node gn(0, j);\n pawn_data.goal_nodes.insert(gn);\n }\n break;\n case 3:\n pawn_data.node.set_row(board_size_ \/ 2);\n pawn_data.node.set_col(board_size_ - 1);\n bg_.block_node(pawn_data.node);\n for (int j = 0; j < board_size_; ++j) {\n Node gn(j, 0);\n pawn_data.goal_nodes.insert(gn);\n }\n break;\n }\n\n pawn_data_list_.insert(pawn_data);\n }\n}\n\nvoid Game::switch_pawn()\n{\n auto it = pawn_data_list_.upper_bound(cur_pawn_idx_);\n if (it == pawn_data_list_.end()) {\n it = pawn_data_list_.begin();\n }\n cur_pawn_idx_ = it->idx;\n}\n\nconst pawn_data_t &Game::cur_pawn_data() const\n{\n return *pawn_data_list_.find(cur_pawn_idx_);\n}\n\nconst pawn_data_list_t &Game::pawn_data_list() const\n{\n return pawn_data_list_;\n}\n\nconst pawn_data_t &Game::pawn_data(std::shared_ptr<Pawn> &pawn) const\n{\n return *pawn_data_list_.get<by_pawn>().find(pawn);\n}\n\nint Game::move_pawn(const Node &node)\n{\n const Node &cur_node = pawn_data_list_.find(cur_pawn_idx_)->node;\n\n if (bg_.is_adjacent(cur_node, node)) {\n bg_.unblock_node(cur_node);\n pawn_data_list_t::iterator it = pawn_data_list_.find(cur_pawn_idx_);\n pawn_data_list_.modify(it, [=](pawn_data_t &e){ e.node = node; });\n bg_.block_node(node);\n return 0;\n }\n else {\n return -1;\n }\n}\n\nint Game::add_wall(const Wall &wall)\n{\n std::vector<std::pair<Node, Node>> edges;\n\n if (try_add_wall(wall, &edges) < 0) {\n return -1;\n }\n\n wg_.apply_tmp_wall();\n for (auto edge : edges) {\n bg_.remove_edges(edge.first, edge.second);\n }\n\n return 0;\n}\n\nbool Game::is_finished() const\n{\n Node cur_node = pawn_data_list_.find(cur_pawn_idx_)->node;\n if (pawn_data_list_.find(cur_pawn_idx_)->goal_nodes.count(cur_node) != 0) {\n return true;\n }\n return false;\n}\n\nbool Game::get_path(std::shared_ptr<Pawn> pawn, const Node &node,\n std::list<Node> *path) const\n{\n return bg_.find_path(pawn_data(pawn).node, node, path);\n}\n\nint Game::try_add_wall(const Wall &wall,\n std::vector<std::pair<Node, Node>> *edges)\n{\n if (wg_.add_tmp_wall(wall) < 0) {\n return -1;\n }\n\n std::vector<std::pair<Node, Node>> edge_list;\n\n Node node1;\n Node node2;\n Node node_tmp;\n if (wall.orientation() == Wall::kHorizontal) {\n for (int i = 0; i < wall.cnt(); ++i) {\n node1 = Node(wall.row() - 1, wall.col() + i);\n node2 = Node(wall.row(), wall.col() + i);\n edge_list.push_back(std::make_pair(node1, node2));\n edges->push_back(std::make_pair(node1, node2));\n\n node_tmp = Node(wall.row() + 1, wall.col() + i);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n edge_list.push_back(std::make_pair(node1, node_tmp));\n edges->push_back(std::make_pair(node1, node_tmp));\n }\n\n node_tmp = Node(wall.row() - 2, wall.col() + i);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n edge_list.push_back(std::make_pair(node_tmp, node2));\n edges->push_back(std::make_pair(node_tmp, node2));\n }\n\n for (int j = i - 1; j <= i + 1; j += 2) {\n node_tmp = Node(wall.row(), wall.col() + j);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n edge_list.push_back(std::make_pair(node1, node_tmp));\n edges->push_back(std::make_pair(node1, node_tmp));\n }\n\n node_tmp = Node(wall.row() - 1, wall.col() + j);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n edge_list.push_back(std::make_pair(node_tmp, node2));\n edges->push_back(std::make_pair(node_tmp, node2));\n }\n }\n }\n }\n else if (wall.orientation() == Wall::kVertical) {\n for (int i = 0; i < wall.cnt(); ++i) {\n node1 = Node(wall.row() + i, wall.col() - 1);\n node2 = Node(wall.row() + i, wall.col());\n edge_list.push_back(std::make_pair(node1, node2));\n edges->push_back(std::make_pair(node1, node2));\n\n node_tmp = Node(wall.row() + i, wall.col() + 1);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n edge_list.push_back(std::make_pair(node1, node_tmp));\n edges->push_back(std::make_pair(node1, node_tmp));\n }\n\n node_tmp = Node(wall.row() + i, wall.col() - 2);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n edge_list.push_back(std::make_pair(node_tmp, node2));\n edges->push_back(std::make_pair(node_tmp, node2));\n }\n\n for (int j = i - 1; j <= i + 1; j += 2) {\n node_tmp = Node(wall.row() + j, wall.col());\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n edge_list.push_back(std::make_pair(node1, node_tmp));\n edges->push_back(std::make_pair(node1, node_tmp));\n }\n\n node_tmp = Node(wall.row() + j, wall.col() - 1);\n if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_)\n && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) {\n edge_list.push_back(std::make_pair(node_tmp, node2));\n edges->push_back(std::make_pair(node_tmp, node2));\n }\n }\n }\n }\n else {\n return -1;\n }\n\n bool path_blocked = false;\n\n for (auto pawn_data : pawn_data_list_) {\n path_blocked = true;\n for (auto goal_node : pawn_data.goal_nodes) {\n if (bg_.is_path_exists(pawn_data.node, goal_node, edge_list)) {\n path_blocked = false;\n break;\n }\n }\n\n \/\/ wall blocks all pathes to the opposite side for one of pawns\n if (path_blocked) {\n break;\n }\n }\n\n if (path_blocked) {\n return -1;\n }\n\n return 0;\n}\n\n} \/\/ namespace Quoridor\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n *\n * ddl.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/peloton\/src\/backend\/bridge\/ddl.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include <cassert>\n#include <iostream>\n\n#include \"backend\/bridge\/ddl\/ddl_table.h\"\n#include \"backend\/bridge\/ddl\/ddl_database.h\"\n#include \"backend\/bridge\/ddl\/ddl_index.h\"\n#include \"backend\/bridge\/ddl\/ddl_transaction.h\"\n#include \"backend\/bridge\/ddl\/ddl.h\"\n#include \"backend\/common\/logger.h\"\n\n#include \"postgres.h\"\n#include \"miscadmin.h\"\n#include \"c.h\"\n\nnamespace peloton {\nnamespace bridge {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Utilities.\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Process utility statement.\n * @param parsetree Parse tree\n *\/\nvoid DDL::ProcessUtility(Node *parsetree,\n const char *queryString,\n TransactionId txn_id){\n assert(parsetree != nullptr);\n assert(queryString != nullptr);\n\n static std::vector<IndexInfo> index_infos;\n\n \/* When we call a backend function from different thread, the thread's stack\n * is at a different location than the main thread's stack. so it sets up\n * reference point for stack depth checking\n *\/\n set_stack_base();\n\n \/\/ Process depending on type of utility statement\n switch (nodeTag(parsetree))\n {\n StartTransactionCommand();\n\n case T_CreatedbStmt:\n {\n DDLDatabase::ExecCreatedbStmt(parsetree);\n break;\n }\n\n case T_DropdbStmt:\n {\n DDLDatabase::ExecDropdbStmt(parsetree);\n break;\n }\n\n case T_CreateStmt:\n case T_CreateForeignTableStmt:\n {\n DDLTable::ExecCreateStmt(parsetree, index_infos);\n break;\n }\n\n case T_AlterTableStmt:\n {\n DDLTable::ExecAlterTableStmt(parsetree, queryString);\n break;\n }\n\n case T_DropStmt:\n {\n DDLTable::ExecDropStmt(parsetree);\n break;\n }\n\n case T_IndexStmt: \n {\n DDLIndex::ExecIndexStmt(parsetree, index_infos);\n break;\n }\n\n case T_VacuumStmt:\n {\n DDLDatabase::ExecVacuumStmt(parsetree);\n break;\n }\n\n CommitTransactionCommand();\n\n case T_TransactionStmt: {\n TransactionStmt *stmt = (TransactionStmt *) parsetree;\n\n DDLTransaction::ExecTransactionStmt(stmt, txn_id);\n }\n break;\n\n default: {\n LOG_WARN(\"unrecognized node type: %d\", (int) nodeTag(parsetree));\n }\n break;\n }\n\n}\n\n} \/\/ namespace bridge\n} \/\/ namespace peloton\n\n<commit_msg>Minor fix<commit_after>\/*-------------------------------------------------------------------------\n *\n * ddl.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/peloton\/src\/backend\/bridge\/ddl.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include <cassert>\n#include <iostream>\n\n#include \"backend\/bridge\/ddl\/ddl_table.h\"\n#include \"backend\/bridge\/ddl\/ddl_database.h\"\n#include \"backend\/bridge\/ddl\/ddl_index.h\"\n#include \"backend\/bridge\/ddl\/ddl_transaction.h\"\n#include \"backend\/bridge\/ddl\/ddl.h\"\n#include \"backend\/common\/logger.h\"\n\n#include \"postgres.h\"\n#include \"miscadmin.h\"\n#include \"c.h\"\n#include \"access\/xact.h\"\n\nnamespace peloton {\nnamespace bridge {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Utilities.\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Process utility statement.\n * @param parsetree Parse tree\n *\/\nvoid DDL::ProcessUtility(Node *parsetree,\n const char *queryString,\n TransactionId txn_id){\n assert(parsetree != nullptr);\n assert(queryString != nullptr);\n\n static std::vector<IndexInfo> index_infos;\n\n \/* When we call a backend function from different thread, the thread's stack\n * is at a different location than the main thread's stack. so it sets up\n * reference point for stack depth checking\n *\/\n set_stack_base();\n\n \/\/ Process depending on type of utility statement\n switch (nodeTag(parsetree))\n {\n StartTransactionCommand();\n\n case T_CreatedbStmt:\n {\n DDLDatabase::ExecCreatedbStmt(parsetree);\n break;\n }\n\n case T_DropdbStmt:\n {\n DDLDatabase::ExecDropdbStmt(parsetree);\n break;\n }\n\n case T_CreateStmt:\n case T_CreateForeignTableStmt:\n {\n DDLTable::ExecCreateStmt(parsetree, index_infos);\n break;\n }\n\n case T_AlterTableStmt:\n {\n DDLTable::ExecAlterTableStmt(parsetree, queryString);\n break;\n }\n\n case T_DropStmt:\n {\n DDLTable::ExecDropStmt(parsetree);\n break;\n }\n\n case T_IndexStmt: \n {\n DDLIndex::ExecIndexStmt(parsetree, index_infos);\n break;\n }\n\n case T_VacuumStmt:\n {\n DDLDatabase::ExecVacuumStmt(parsetree);\n break;\n }\n\n CommitTransactionCommand();\n\n case T_TransactionStmt: {\n TransactionStmt *stmt = (TransactionStmt *) parsetree;\n\n DDLTransaction::ExecTransactionStmt(stmt, txn_id);\n }\n break;\n\n default: {\n LOG_WARN(\"unrecognized node type: %d\", (int) nodeTag(parsetree));\n }\n break;\n }\n\n}\n\n} \/\/ namespace bridge\n} \/\/ namespace peloton\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n\n#include \"common\/ann_util.h\"\n\nnamespace ann {\nnamespace util {\n\nProgBar::ProgBar(size_t total): pv_(1), total_(total), percent_(0) {\n system(\"setterm -cursor off\");\n}\n\nProgBar::~ProgBar() {\n std::cerr << std::endl;\n system(\"setterm -cursor on\");\n}\n\nvoid ProgBar::update(size_t count) {\n\n \/\/ with changes after\n \/\/ https:\/\/nakkaya.com\/2009\/11\/08\/command-line-progress-bar\/\n \/\/\n auto percent = (pv_ * 100) \/ total_;\n pv_ += count;\n\n if (percent == percent_) {\n return;\n }\n\n percent_ = percent;\n std::string bar;\n\n for (size_t i = 0; i < 50; i++) {\n if (i < (percent \/ 2)) {\n bar.replace(i, 1, \"=\");\n } else if (i == (percent \/ 2)) {\n bar.replace(i, 1, \">\");\n } else {\n bar.replace(i, 1, \" \");\n }\n }\n\n std::cerr << \"\\r\" \"[\" << bar << \"] \";\n std::cerr.width(3);\n std::cerr << percent << \"% \" << std::flush;\n}\n}\n}\n<commit_msg>use c++ version of system<commit_after>#include <cstdlib>\n#include <iostream>\n#include <string>\n\n#include \"common\/ann_util.h\"\n\nnamespace ann {\nnamespace util {\n\nProgBar::ProgBar(size_t total): pv_(1), total_(total), percent_(0) {\n std::system(\"setterm -cursor off\");\n}\n\nProgBar::~ProgBar() {\n std::cerr << std::endl;\n std::system(\"setterm -cursor on\");\n}\n\nvoid ProgBar::update(size_t count) {\n\n \/\/ with changes after\n \/\/ https:\/\/nakkaya.com\/2009\/11\/08\/command-line-progress-bar\/\n \/\/\n auto percent = (pv_ * 100) \/ total_;\n pv_ += count;\n\n if (percent == percent_) {\n return;\n }\n\n percent_ = percent;\n std::string bar;\n\n for (size_t i = 0; i < 50; i++) {\n if (i < (percent \/ 2)) {\n bar.replace(i, 1, \"=\");\n } else if (i == (percent \/ 2)) {\n bar.replace(i, 1, \">\");\n } else {\n bar.replace(i, 1, \" \");\n }\n }\n\n std::cerr << \"\\r\" \"[\" << bar << \"] \";\n std::cerr.width(3);\n std::cerr << percent << \"% \" << std::flush;\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Yangqing Jia\n\n#include <cstring>\n\n#include \"cuda_runtime.h\"\n#include \"gtest\/gtest.h\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/syncedmem.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\nclass CommonTest : public ::testing::Test {};\n\nTEST_F(CommonTest, TestCublasHandler) {\n int cuda_device_id;\n CUDA_CHECK(cudaGetDevice(&cuda_device_id));\n EXPECT_TRUE(Caffe::cublas_handle());\n}\n\nTEST_F(CommonTest, TestVslStream) {\n EXPECT_TRUE(Caffe::vsl_stream());\n}\n\nTEST_F(CommonTest, TestBrewMode) {\n EXPECT_EQ(Caffe::mode(), Caffe::CPU);\n Caffe::set_mode(Caffe::GPU);\n EXPECT_EQ(Caffe::mode(), Caffe::GPU);\n}\n\nTEST_F(CommonTest, TestPhase) {\n EXPECT_EQ(Caffe::phase(), Caffe::TRAIN);\n Caffe::set_phase(Caffe::TEST);\n EXPECT_EQ(Caffe::phase(), Caffe::TEST);\n}\n\nTEST_F(CommonTest, TestRandSeedCPU) {\n SyncedMemory data_a(10 * sizeof(int));\n SyncedMemory data_b(10 * sizeof(int));\n Caffe::set_random_seed(1701);\n viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, Caffe::vsl_stream(),\n 10, reinterpret_cast<int*>(data_a.mutable_cpu_data()), 0.5);\n Caffe::set_random_seed(1701);\n viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, Caffe::vsl_stream(),\n 10, reinterpret_cast<int*>(data_b.mutable_cpu_data()), 0.5);\n for (int i = 0; i < 10; ++i) {\n EXPECT_EQ(((const int*)(data_a.cpu_data()))[i],\n ((const int*)(data_b.cpu_data()))[i]);\n }\n}\n\n\nTEST_F(CommonTest, TestRandSeedGPU) {\n SyncedMemory data_a(10 * sizeof(unsigned int));\n SyncedMemory data_b(10 * sizeof(unsigned int));\n Caffe::set_random_seed(1701);\n CURAND_CHECK(curandGenerate(Caffe::curand_generator(),\n reinterpret_cast<unsigned int*>(data_a.mutable_gpu_data()), 10));\n Caffe::set_random_seed(1701);\n CURAND_CHECK(curandGenerate(Caffe::curand_generator(),\n reinterpret_cast<unsigned int*>(data_b.mutable_gpu_data()), 10));\n for (int i = 0; i < 10; ++i) {\n EXPECT_EQ(((const unsigned int*)(data_a.cpu_data()))[i],\n ((const unsigned int*)(data_b.cpu_data()))[i]);\n }\n}\n\n\n} \/\/ namespace caffe\n<commit_msg>Fix a test assuming CPU mode without explicitly setting it.<commit_after>\/\/ Copyright 2013 Yangqing Jia\n\n#include <cstring>\n\n#include \"cuda_runtime.h\"\n#include \"gtest\/gtest.h\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/syncedmem.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\nclass CommonTest : public ::testing::Test {};\n\nTEST_F(CommonTest, TestCublasHandler) {\n int cuda_device_id;\n CUDA_CHECK(cudaGetDevice(&cuda_device_id));\n EXPECT_TRUE(Caffe::cublas_handle());\n}\n\nTEST_F(CommonTest, TestVslStream) {\n EXPECT_TRUE(Caffe::vsl_stream());\n}\n\nTEST_F(CommonTest, TestBrewMode) {\n Caffe::set_mode(Caffe::CPU);\n EXPECT_EQ(Caffe::mode(), Caffe::CPU);\n Caffe::set_mode(Caffe::GPU);\n EXPECT_EQ(Caffe::mode(), Caffe::GPU);\n}\n\nTEST_F(CommonTest, TestPhase) {\n EXPECT_EQ(Caffe::phase(), Caffe::TRAIN);\n Caffe::set_phase(Caffe::TEST);\n EXPECT_EQ(Caffe::phase(), Caffe::TEST);\n}\n\nTEST_F(CommonTest, TestRandSeedCPU) {\n SyncedMemory data_a(10 * sizeof(int));\n SyncedMemory data_b(10 * sizeof(int));\n Caffe::set_random_seed(1701);\n viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, Caffe::vsl_stream(),\n 10, reinterpret_cast<int*>(data_a.mutable_cpu_data()), 0.5);\n Caffe::set_random_seed(1701);\n viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, Caffe::vsl_stream(),\n 10, reinterpret_cast<int*>(data_b.mutable_cpu_data()), 0.5);\n for (int i = 0; i < 10; ++i) {\n EXPECT_EQ(((const int*)(data_a.cpu_data()))[i],\n ((const int*)(data_b.cpu_data()))[i]);\n }\n}\n\n\nTEST_F(CommonTest, TestRandSeedGPU) {\n SyncedMemory data_a(10 * sizeof(unsigned int));\n SyncedMemory data_b(10 * sizeof(unsigned int));\n Caffe::set_random_seed(1701);\n CURAND_CHECK(curandGenerate(Caffe::curand_generator(),\n reinterpret_cast<unsigned int*>(data_a.mutable_gpu_data()), 10));\n Caffe::set_random_seed(1701);\n CURAND_CHECK(curandGenerate(Caffe::curand_generator(),\n reinterpret_cast<unsigned int*>(data_b.mutable_gpu_data()), 10));\n for (int i = 0; i < 10; ++i) {\n EXPECT_EQ(((const unsigned int*)(data_a.cpu_data()))[i],\n ((const unsigned int*)(data_b.cpu_data()))[i]);\n }\n}\n\n\n} \/\/ namespace caffe\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\\\n\n This file is part of the C! library. A.K.A the cbang library.\n\n Copyright (c) 2003-2014, Cauldron Development LLC\n Copyright (c) 2003-2014, Stanford University\n All rights reserved.\n\n The C! library is free software: you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public License\n as published by the Free Software Foundation, either version 2.1 of\n the License, or (at your option) any later version.\n\n The C! 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 the C! library. If not, see\n <http:\/\/www.gnu.org\/licenses\/>.\n\n In addition, BSD licensing may be granted on a case by case basis\n by written permission from at least one of the copyright holders.\n You may request written permission by emailing the authors.\n\n For information regarding this software email:\n Joseph Coffland\n joseph@cauldrondevelopment.com\n\n\\******************************************************************************\/\n\n#include \"Revoked.h\"\n#include \"SSL.h\"\n#include \"Extension.h\"\n\n#include <openssl\/x509.h>\n\n#include <cbang\/Exception.h>\n\nusing namespace std;\nusing namespace cb;\n\n\nRevoked::Revoked() : rev(X509_REVOKED_new()), deallocate(true) {}\n\n\nRevoked::~Revoked() {\n if (deallocate) X509_REVOKED_free(rev);\n}\n\n\nvoid Revoked::setDate(uint64_t ts) {\n ASN1_TIME *tm = ASN1_TIME_new();\n X509_gmtime_adj(tm, ts);\n\n if (!X509_REVOKED_set_revocationDate(rev, tm)) {\n ASN1_TIME_free(tm);\n THROWS(\"Failed to set revocation date: \" << SSL::getErrorStr());\n }\n\n ASN1_TIME_free(tm);\n}\n\n\nvoid Revoked::setReason(const string &reason) {\n if (reason == \"unspecified\") return;\n\n const char *reasons[] = {\n\t\"unspecified\",\n\t\"keyCompromise\",\n\t\"CACompromise\",\n\t\"affiliationChanged\",\n\t\"superseded\", \n\t\"cessationOfOperation\",\n\t\"certificateHold\",\n \"removeFromCRL\",\n \"privilegeWithdrawn\",\n \"aACompromise\",\n 0\n };\n\n ASN1_ENUMERATED *a = ASN1_ENUMERATED_new();\n\n for (int i = 0; reasons[i]; i++)\n if (reason == reasons[i]) {\n ASN1_ENUMERATED_set(a, i);\n break;\n }\n\n if (!X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, a, 0, 0)) {\n THROWS(\"Failed to add extension 'CRLReason'='\" << reason\n << \"': \" << SSL::getErrorStr());\n \tASN1_ENUMERATED_free(a);\n }\n\n ASN1_ENUMERATED_free(a);\n}\n\n\nvoid Revoked::setSerial(int number) {\n ASN1_INTEGER *serial = ASN1_INTEGER_new();\n ASN1_INTEGER_set(serial, number);\n\n if (!X509_REVOKED_set_serialNumber(rev, serial))\n THROWS(\"Failed to set revoked serial number: \" << SSL::getErrorStr());\n\n ASN1_INTEGER_free(serial);\n}\n<commit_msg>testing web hook<commit_after>\/******************************************************************************\\\n\n This file is part of the C! library. A.K.A the cbang library.\n\n Copyright (c) 2003-2014, Cauldron Development LLC\n Copyright (c) 2003-2014, Stanford University\n All rights reserved.\n\n The C! library is free software: you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public License\n as published by the Free Software Foundation, either version 2.1 of\n the License, or (at your option) any later version.\n\n The C! 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 the C! library. If not, see\n <http:\/\/www.gnu.org\/licenses\/>.\n\n In addition, BSD licensing may be granted on a case by case basis\n by written permission from at least one of the copyright holders.\n You may request written permission by emailing the authors.\n\n For information regarding this software email:\n Joseph Coffland\n joseph@cauldrondevelopment.com\n\n\\******************************************************************************\/\n\n#include \"Revoked.h\"\n#include \"SSL.h\"\n#include \"Extension.h\"\n\n#include <openssl\/x509.h>\n\n#include <cbang\/Exception.h>\n\nusing namespace std;\nusing namespace cb;\n\n\nRevoked::Revoked() : rev(X509_REVOKED_new()), deallocate(true) {}\n\n\nRevoked::~Revoked() {\n if (deallocate) X509_REVOKED_free(rev);\n}\n\n\nvoid Revoked::setDate(uint64_t ts) {\n ASN1_TIME *tm = ASN1_TIME_new();\n X509_gmtime_adj(tm, ts);\n\n if (!X509_REVOKED_set_revocationDate(rev, tm)) {\n ASN1_TIME_free(tm);\n THROWS(\"Failed to set revocation date: \" << SSL::getErrorStr());\n }\n\n ASN1_TIME_free(tm);\n}\n\n\nvoid Revoked::setReason(const string &reason) {\n if (reason == \"unspecified\") return;\n\n const char *reasons[] = {\n\t\"unspecified\",\n\t\"keyCompromise\",\n\t\"CACompromise\",\n\t\"affiliationChanged\",\n\t\"superseded\",\n\t\"cessationOfOperation\",\n\t\"certificateHold\",\n \"removeFromCRL\",\n \"privilegeWithdrawn\",\n \"aACompromise\",\n 0\n };\n\n ASN1_ENUMERATED *a = ASN1_ENUMERATED_new();\n\n for (int i = 0; reasons[i]; i++)\n if (reason == reasons[i]) {\n ASN1_ENUMERATED_set(a, i);\n break;\n }\n\n if (!X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, a, 0, 0)) {\n THROWS(\"Failed to add extension 'CRLReason'='\" << reason\n << \"': \" << SSL::getErrorStr());\n \tASN1_ENUMERATED_free(a);\n }\n\n ASN1_ENUMERATED_free(a);\n}\n\n\nvoid Revoked::setSerial(int number) {\n ASN1_INTEGER *serial = ASN1_INTEGER_new();\n ASN1_INTEGER_set(serial, number);\n\n if (!X509_REVOKED_set_serialNumber(rev, serial))\n THROWS(\"Failed to set revoked serial number: \" << SSL::getErrorStr());\n\n ASN1_INTEGER_free(serial);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017 Pierre Fourgeaud\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"rendersystems\/GL\/indexbufferGL.h\"\n#include <glad\/glad.h>\n\nnamespace CodeHero {\n\nIndexBufferGL::IndexBufferGL() {\n glGenBuffers(1, &_GetGPUObjectHandle()->intHandle);\n}\n\nIndexBufferGL::~IndexBufferGL() {\n glDeleteBuffers(1, &_GetGPUObjectHandle()->intHandle);\n}\n\nvoid IndexBufferGL::Use() {\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GetGPUObject().intHandle);\n}\n\nvoid IndexBufferGL::Unuse() {\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n}\n\nvoid IndexBufferGL::_SetDataImpl(const void* iData) {\n Use();\n\n glBufferData(\n GL_ELEMENT_ARRAY_BUFFER,\n m_IndexSize,\n iData,\n m_IsDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);\n}\n\n} \/\/ namespace CodeHero\n\n<commit_msg>Fix wrong size for index buffer<commit_after>\/\/ Copyright (c) 2017 Pierre Fourgeaud\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"rendersystems\/GL\/indexbufferGL.h\"\n#include <glad\/glad.h>\n\nnamespace CodeHero {\n\nIndexBufferGL::IndexBufferGL() {\n glGenBuffers(1, &_GetGPUObjectHandle()->intHandle);\n}\n\nIndexBufferGL::~IndexBufferGL() {\n glDeleteBuffers(1, &_GetGPUObjectHandle()->intHandle);\n}\n\nvoid IndexBufferGL::Use() {\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GetGPUObject().intHandle);\n}\n\nvoid IndexBufferGL::Unuse() {\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n}\n\nvoid IndexBufferGL::_SetDataImpl(const void* iData) {\n Use();\n\n \/\/ TODO(pierre) The sizeof should be more abstracted\n glBufferData(\n GL_ELEMENT_ARRAY_BUFFER,\n m_IndexSize * sizeof(unsigned int),\n iData,\n m_IsDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);\n}\n\n} \/\/ namespace CodeHero\n\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * THE NEW CHRONOTEXT TOOLKIT: https:\/\/github.com\/arielm\/new-chronotext-toolkit\r\n * COPYRIGHT (C) 2012, ARIEL MALKA ALL RIGHTS RESERVED.\r\n *\r\n * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:\r\n * https:\/\/github.com\/arielm\/new-chronotext-toolkit\/blob\/master\/LICENSE.md\r\n *\/\r\n\r\n#include \"chronotext\/InputSource.h\"\r\n\r\n#include \"cinder\/app\/App.h\"\r\n#include \"cinder\/Utilities.h\"\r\n\r\nusing namespace std;\r\nusing namespace ci;\r\nusing namespace app;\r\n\r\nnamespace chronotext\r\n{\r\n InputSourceRef InputSource::getResource(const std::string &resourceName)\r\n {\r\n InputSource *source = new InputSource(TYPE_RESOURCE);\r\n source->resourceName = source->filePathHint = resourceName;\r\n \r\n#if defined(CINDER_COCOA)\r\n source->filePath = getResourcePath(resourceName);\r\n#endif\r\n \r\n return InputSourceRef(source);\r\n }\r\n \r\n DataSourceRef InputSource::loadResource(const std::string &resourceName)\r\n {\r\n return InputSource::getResource(resourceName)->loadDataSource();\r\n }\r\n \r\n InputSourceRef InputSource::getResource(const string &resourceName, int mswID, const std::string &mswType)\r\n {\r\n InputSource *source = new InputSource(TYPE_RESOURCE_MSW);\r\n source->mswID = mswID;\r\n source->mswType = mswType;\r\n source->resourceName = source->filePathHint = resourceName;\r\n \r\n return InputSourceRef(source);\r\n }\r\n \r\n DataSourceRef InputSource::loadResource(const string &resourceName, int mswID, const std::string &mswType)\r\n {\r\n return InputSource::getResource(resourceName, mswID, mswType)->loadDataSource();\r\n }\r\n \r\n InputSourceRef InputSource::getFileInDocuments(const std::string &relativePath)\r\n {\r\n return InputSource::getFile(getDocumentsDirectory() \/ relativePath);\r\n }\r\n \r\n DataSourceRef InputSource::loadFileInDocuments(const std::string &relativePath)\r\n {\r\n return DataSourcePath::create(getDocumentsDirectory() \/ relativePath);\r\n }\r\n \r\n InputSourceRef InputSource::getFile(const fs::path &filePath)\r\n {\r\n InputSource *source = new InputSource(TYPE_FILE);\r\n source->filePath = filePath;\r\n source->filePathHint = filePath.string();\r\n \r\n return InputSourceRef(source);\r\n }\r\n \r\n DataSourceRef InputSource::loadFile(const fs::path &filePath)\r\n {\r\n return DataSourcePath::create(filePath);\r\n }\r\n \r\n DataSourceRef InputSource::loadDataSource()\r\n {\r\n switch (type)\r\n {\r\n case TYPE_RESOURCE:\r\n {\r\n#if defined(CHR_COMPLEX) && defined(CINDER_ANDROID)\r\n AAsset* asset = AAssetManager_open(gAssetManager, resourceName.c_str(), AASSET_MODE_STREAMING);\r\n \r\n if (asset)\r\n {\r\n AAsset_close(asset);\r\n return DataSourceAsset::create(gAssetManager, resourceName);\r\n }\r\n else\r\n {\r\n throw Exception(\"RESOURCE NOT FOUND: \" + filePathHint);\r\n }\r\n#elif defined(CINDER_ANDROID)\r\n try\r\n {\r\n return app::loadResource(resourceName);\r\n }\r\n catch (exception &e)\r\n {\r\n throw Exception(\"RESOURCE NOT FOUND: \" + filePathHint);\r\n }\r\n#else\r\n if (fs::exists(filePath))\r\n {\r\n return DataSourcePath::create(filePath);\r\n }\r\n else\r\n {\r\n throw Exception(\"RESOURCE NOT FOUND: \" + filePathHint);\r\n }\r\n#endif\r\n }\r\n \r\n case TYPE_RESOURCE_MSW:\r\n {\r\n try\r\n {\r\n return app::loadResource(resourceName, mswID, mswType);\r\n }\r\n catch (exception &e)\r\n {\r\n throw Exception(\"RESOURCE NOT FOUND: \" + filePathHint);\r\n }\r\n }\r\n \r\n case TYPE_FILE:\r\n {\r\n if (fs::exists(filePath))\r\n {\r\n return DataSourcePath::create(filePath);\r\n }\r\n else\r\n {\r\n throw Exception(\"FILE NOT FOUND: \" + filePathHint);\r\n }\r\n }\r\n }\r\n \r\n return DataSourceRef();\r\n }\r\n \r\n bool InputSource::isFile() const\r\n {\r\n return !filePath.empty();\r\n }\r\n \r\n fs::path InputSource::getFilePath() const\r\n {\r\n return filePath;\r\n }\r\n \r\n string InputSource::getFilePathHint() const\r\n {\r\n return filePathHint;\r\n }\r\n \r\n string InputSource::getUniqueName() const\r\n {\r\n switch (type)\r\n {\r\n case TYPE_RESOURCE:\r\n return \"res:\/\/\" + resourceName;\r\n \r\n case TYPE_RESOURCE_MSW:\r\n return \"res_msw:\/\/\" + boost::lexical_cast<string>(mswID) + \"\/\" + mswType;\r\n \r\n case TYPE_FILE:\r\n if (fs::exists(filePath))\r\n {\r\n return \"file:\/\/\" + fs::canonical(filePath).string();\r\n }\r\n else\r\n {\r\n return \"file::\/\/undefined\";\r\n }\r\n }\r\n \r\n return \"\";\r\n }\r\n \r\n void InputSource::setFilePathHint(const string &hint)\r\n {\r\n filePathHint = hint;\r\n }\r\n \r\n#if defined(CINDER_COCOA)\r\n fs::path InputSource::getResourcePath()\r\n {\r\n#if defined(CHR_COMPLEX)\r\n CFBundleRef bundle = CFBundleGetMainBundle();\r\n CFURLRef url = CFBundleCopyBundleURL(bundle);\r\n CFStringRef tmp = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);\r\n \r\n CFIndex length = CFStringGetLength(tmp);\r\n CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);\r\n char *buffer = (char*)malloc(maxSize);\r\n CFStringGetCString(tmp, buffer, maxSize, kCFStringEncodingUTF8);\r\n \r\n fs::path path(buffer);\r\n \r\n CFRelease(url);\r\n CFRelease(tmp);\r\n free(buffer);\r\n \r\n return path;\r\n#else\r\n return App::getResourcePath();\r\n#endif\r\n }\r\n#endif\r\n \r\n#if defined(CINDER_COCOA)\r\n fs::path InputSource::getResourcePath(const string &resourceName)\r\n {\r\n#if defined(CHR_COMPLEX)\r\n return getResourcePath() \/ resourceName;\r\n#else\r\n return App::getResourcePath(resourceName);\r\n#endif\r\n }\r\n#endif\r\n \r\n#if defined(CHR_COMPLEX) && defined(CINDER_ANDROID)\r\n \r\n void InputSource::setAndroidAssetManager(AAssetManager *assetManager)\r\n {\r\n gAssetManager = assetManager;\r\n }\r\n \r\n AAssetManager* InputSource::getAndroidAssetManager()\r\n {\r\n return gAssetManager;\r\n }\r\n \r\n void InputSource::setAndroidInternalDataPath(const string &internalDataPath)\r\n {\r\n gInternalDataPath = fs::path(internalDataPath);\r\n }\r\n \r\n fs::path InputSource::getAndroidInternalDataPath()\r\n {\r\n return gInternalDataPath;\r\n }\r\n \r\n void InputSource::setAndroidApkPath(const string &apkPath)\r\n {\r\n gApkPath = fs::path(apkPath);\r\n }\r\n \r\n fs::path InputSource::getAndroidApkPath()\r\n {\r\n return gApkPath;\r\n }\r\n \r\n#endif\r\n}\r\n<commit_msg>InputSource: TWEAKS, IN ADDITION TO PREVIOUS Exception ENHANCEMENT<commit_after>\/*\r\n * THE NEW CHRONOTEXT TOOLKIT: https:\/\/github.com\/arielm\/new-chronotext-toolkit\r\n * COPYRIGHT (C) 2012, ARIEL MALKA ALL RIGHTS RESERVED.\r\n *\r\n * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:\r\n * https:\/\/github.com\/arielm\/new-chronotext-toolkit\/blob\/master\/LICENSE.md\r\n *\/\r\n\r\n#include \"chronotext\/InputSource.h\"\r\n\r\n#include \"cinder\/app\/App.h\"\r\n#include \"cinder\/Utilities.h\"\r\n\r\nusing namespace std;\r\nusing namespace ci;\r\nusing namespace app;\r\n\r\nnamespace chronotext\r\n{\r\n InputSourceRef InputSource::getResource(const std::string &resourceName)\r\n {\r\n InputSource *source = new InputSource(TYPE_RESOURCE);\r\n source->resourceName = source->filePathHint = resourceName;\r\n \r\n#if defined(CINDER_COCOA)\r\n source->filePath = getResourcePath(resourceName);\r\n#endif\r\n \r\n return InputSourceRef(source);\r\n }\r\n \r\n DataSourceRef InputSource::loadResource(const std::string &resourceName)\r\n {\r\n return InputSource::getResource(resourceName)->loadDataSource();\r\n }\r\n \r\n InputSourceRef InputSource::getResource(const string &resourceName, int mswID, const std::string &mswType)\r\n {\r\n InputSource *source = new InputSource(TYPE_RESOURCE_MSW);\r\n source->mswID = mswID;\r\n source->mswType = mswType;\r\n source->resourceName = source->filePathHint = resourceName;\r\n \r\n return InputSourceRef(source);\r\n }\r\n \r\n DataSourceRef InputSource::loadResource(const string &resourceName, int mswID, const std::string &mswType)\r\n {\r\n return InputSource::getResource(resourceName, mswID, mswType)->loadDataSource();\r\n }\r\n \r\n InputSourceRef InputSource::getFileInDocuments(const std::string &relativePath)\r\n {\r\n return InputSource::getFile(getDocumentsDirectory() \/ relativePath);\r\n }\r\n \r\n DataSourceRef InputSource::loadFileInDocuments(const std::string &relativePath)\r\n {\r\n return DataSourcePath::create(getDocumentsDirectory() \/ relativePath);\r\n }\r\n \r\n InputSourceRef InputSource::getFile(const fs::path &filePath)\r\n {\r\n InputSource *source = new InputSource(TYPE_FILE);\r\n source->filePath = filePath;\r\n source->filePathHint = filePath.string();\r\n \r\n return InputSourceRef(source);\r\n }\r\n \r\n DataSourceRef InputSource::loadFile(const fs::path &filePath)\r\n {\r\n return DataSourcePath::create(filePath);\r\n }\r\n \r\n DataSourceRef InputSource::loadDataSource()\r\n {\r\n switch (type)\r\n {\r\n case TYPE_RESOURCE:\r\n {\r\n#if defined(CHR_COMPLEX) && defined(CINDER_ANDROID)\r\n AAsset* asset = AAssetManager_open(gAssetManager, resourceName.c_str(), AASSET_MODE_STREAMING);\r\n \r\n if (asset)\r\n {\r\n AAsset_close(asset);\r\n return DataSourceAsset::create(gAssetManager, resourceName);\r\n }\r\n else\r\n {\r\n throw Exception(\"RESOURCE NOT FOUND: \" + filePathHint);\r\n }\r\n#elif defined(CINDER_ANDROID)\r\n try\r\n {\r\n return app::loadResource(resourceName);\r\n }\r\n catch (exception &e)\r\n {\r\n throw Exception(\"RESOURCE NOT FOUND: \" + filePathHint);\r\n }\r\n#else\r\n if (fs::exists(filePath))\r\n {\r\n return DataSourcePath::create(filePath);\r\n }\r\n else\r\n {\r\n throw Exception(\"RESOURCE NOT FOUND: \" + filePathHint);\r\n }\r\n#endif\r\n }\r\n \r\n case TYPE_RESOURCE_MSW:\r\n {\r\n try\r\n {\r\n return app::loadResource(resourceName, mswID, mswType);\r\n }\r\n catch (exception &e)\r\n {\r\n throw Exception(\"RESOURCE NOT FOUND: \" + filePathHint);\r\n }\r\n }\r\n \r\n case TYPE_FILE:\r\n {\r\n if (fs::exists(filePath))\r\n {\r\n return DataSourcePath::create(filePath);\r\n }\r\n else\r\n {\r\n throw Exception(\"FILE NOT FOUND: \" + filePathHint);\r\n }\r\n }\r\n }\r\n \r\n return DataSourceRef();\r\n }\r\n \r\n bool InputSource::isFile() const\r\n {\r\n return !filePath.empty();\r\n }\r\n \r\n fs::path InputSource::getFilePath() const\r\n {\r\n return filePath;\r\n }\r\n \r\n string InputSource::getFilePathHint() const\r\n {\r\n return filePathHint;\r\n }\r\n \r\n string InputSource::getUniqueName() const\r\n {\r\n switch (type)\r\n {\r\n case TYPE_RESOURCE:\r\n return \"res:\/\/\" + resourceName;\r\n \r\n case TYPE_RESOURCE_MSW:\r\n return \"res_msw:\/\/\" + boost::lexical_cast<string>(mswID) + \"\/\" + mswType;\r\n \r\n case TYPE_FILE:\r\n if (fs::exists(filePath))\r\n {\r\n return \"file:\/\/\" + fs::canonical(filePath).string();\r\n }\r\n else\r\n {\r\n return \"undefined:\/\/\" + filePathHint;\r\n }\r\n }\r\n \r\n return \"\";\r\n }\r\n \r\n void InputSource::setFilePathHint(const string &hint)\r\n {\r\n filePathHint = hint;\r\n }\r\n \r\n#if defined(CINDER_COCOA)\r\n fs::path InputSource::getResourcePath()\r\n {\r\n#if defined(CHR_COMPLEX)\r\n CFBundleRef bundle = CFBundleGetMainBundle();\r\n CFURLRef url = CFBundleCopyBundleURL(bundle);\r\n CFStringRef tmp = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);\r\n \r\n CFIndex length = CFStringGetLength(tmp);\r\n CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);\r\n char *buffer = (char*)malloc(maxSize);\r\n CFStringGetCString(tmp, buffer, maxSize, kCFStringEncodingUTF8);\r\n \r\n fs::path path(buffer);\r\n \r\n CFRelease(url);\r\n CFRelease(tmp);\r\n free(buffer);\r\n \r\n return path;\r\n#else\r\n return App::getResourcePath();\r\n#endif\r\n }\r\n#endif\r\n \r\n#if defined(CINDER_COCOA)\r\n fs::path InputSource::getResourcePath(const string &resourceName)\r\n {\r\n#if defined(CHR_COMPLEX)\r\n return getResourcePath() \/ resourceName;\r\n#else\r\n return App::getResourcePath(resourceName);\r\n#endif\r\n }\r\n#endif\r\n \r\n#if defined(CHR_COMPLEX) && defined(CINDER_ANDROID)\r\n \r\n void InputSource::setAndroidAssetManager(AAssetManager *assetManager)\r\n {\r\n gAssetManager = assetManager;\r\n }\r\n \r\n AAssetManager* InputSource::getAndroidAssetManager()\r\n {\r\n return gAssetManager;\r\n }\r\n \r\n void InputSource::setAndroidInternalDataPath(const string &internalDataPath)\r\n {\r\n gInternalDataPath = fs::path(internalDataPath);\r\n }\r\n \r\n fs::path InputSource::getAndroidInternalDataPath()\r\n {\r\n return gInternalDataPath;\r\n }\r\n \r\n void InputSource::setAndroidApkPath(const string &apkPath)\r\n {\r\n gApkPath = fs::path(apkPath);\r\n }\r\n \r\n fs::path InputSource::getAndroidApkPath()\r\n {\r\n return gApkPath;\r\n }\r\n \r\n#endif\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: propmultiplex.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2005-06-14 16:46:37 $\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 _COMPHELPER_PROPERTY_MULTIPLEX_HXX_\n#define _COMPHELPER_PROPERTY_MULTIPLEX_HXX_\n\n#ifndef _COMPHELPER_PROPERTY_STATE_HXX_\n#include <comphelper\/propstate.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n\/\/=========================================================================\n\/\/= property helper classes\n\/\/=========================================================================\n\n\/\/.........................................................................\nnamespace comphelper\n{\n\/\/.........................................................................\n\n class OPropertyChangeMultiplexer;\n\n \/\/==================================================================\n \/\/= OPropertyChangeListener\n \/\/==================================================================\n \/\/\/ simple listener adapter for property sets\n class COMPHELPER_DLLPUBLIC OPropertyChangeListener\n {\n friend class OPropertyChangeMultiplexer;\n\n OPropertyChangeMultiplexer* m_pAdapter;\n ::osl::Mutex& m_rMutex;\n\n public:\n OPropertyChangeListener(::osl::Mutex& _rMutex)\n : m_pAdapter(NULL), m_rMutex(_rMutex) { }\n virtual ~OPropertyChangeListener();\n\n virtual void _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& _rEvent) throw( ::com::sun::star::uno::RuntimeException) = 0;\n virtual void _disposing(const ::com::sun::star::lang::EventObject& _rSource) throw( ::com::sun::star::uno::RuntimeException);\n\n protected:\n \/** If the derivee also owns the mutex which we know as reference, then call this within your\n derivee's dtor.\n *\/\n void disposeAdapter();\n\n \/\/ pseudo-private. Making it private now could break compatibility\n void setAdapter( OPropertyChangeMultiplexer* _pAdapter );\n };\n\n \/\/==================================================================\n \/\/= OPropertyChangeMultiplexer\n \/\/==================================================================\n \/\/\/ multiplexer for property changes\n class COMPHELPER_DLLPUBLIC OPropertyChangeMultiplexer :public cppu::WeakImplHelper1< ::com::sun::star::beans::XPropertyChangeListener>\n {\n friend class OPropertyChangeListener;\n ::com::sun::star::uno::Sequence< ::rtl::OUString > m_aProperties;\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xSet;\n OPropertyChangeListener* m_pListener;\n sal_Int32 m_nLockCount;\n sal_Bool m_bListening : 1;\n sal_Bool m_bAutoSetRelease : 1;\n\n\n virtual ~OPropertyChangeMultiplexer();\n public:\n OPropertyChangeMultiplexer(OPropertyChangeListener* _pListener, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxSet, sal_Bool _bAutoReleaseSet = sal_True);\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertyChangeListener\n virtual void SAL_CALL propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw( ::com::sun::star::uno::RuntimeException);\n\n \/\/\/ incremental lock\n void lock();\n \/\/\/ incremental unlock\n void unlock();\n \/\/\/ get the lock count\n sal_Int32 locked() const { return m_nLockCount; }\n\n void addProperty(const ::rtl::OUString& aPropertyName);\n void dispose();\n };\n\n\/\/.........................................................................\n} \/\/ namespace comphelper\n\/\/.........................................................................\n\n#endif \/\/ _COMPHELPER_PROPERTY_MULTIPLEX_HXX_\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.8.30); FILE MERGED 2005\/09\/05 15:23:46 rt 1.8.30.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: propmultiplex.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:37:07 $\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 _COMPHELPER_PROPERTY_MULTIPLEX_HXX_\n#define _COMPHELPER_PROPERTY_MULTIPLEX_HXX_\n\n#ifndef _COMPHELPER_PROPERTY_STATE_HXX_\n#include <comphelper\/propstate.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n\/\/=========================================================================\n\/\/= property helper classes\n\/\/=========================================================================\n\n\/\/.........................................................................\nnamespace comphelper\n{\n\/\/.........................................................................\n\n class OPropertyChangeMultiplexer;\n\n \/\/==================================================================\n \/\/= OPropertyChangeListener\n \/\/==================================================================\n \/\/\/ simple listener adapter for property sets\n class COMPHELPER_DLLPUBLIC OPropertyChangeListener\n {\n friend class OPropertyChangeMultiplexer;\n\n OPropertyChangeMultiplexer* m_pAdapter;\n ::osl::Mutex& m_rMutex;\n\n public:\n OPropertyChangeListener(::osl::Mutex& _rMutex)\n : m_pAdapter(NULL), m_rMutex(_rMutex) { }\n virtual ~OPropertyChangeListener();\n\n virtual void _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& _rEvent) throw( ::com::sun::star::uno::RuntimeException) = 0;\n virtual void _disposing(const ::com::sun::star::lang::EventObject& _rSource) throw( ::com::sun::star::uno::RuntimeException);\n\n protected:\n \/** If the derivee also owns the mutex which we know as reference, then call this within your\n derivee's dtor.\n *\/\n void disposeAdapter();\n\n \/\/ pseudo-private. Making it private now could break compatibility\n void setAdapter( OPropertyChangeMultiplexer* _pAdapter );\n };\n\n \/\/==================================================================\n \/\/= OPropertyChangeMultiplexer\n \/\/==================================================================\n \/\/\/ multiplexer for property changes\n class COMPHELPER_DLLPUBLIC OPropertyChangeMultiplexer :public cppu::WeakImplHelper1< ::com::sun::star::beans::XPropertyChangeListener>\n {\n friend class OPropertyChangeListener;\n ::com::sun::star::uno::Sequence< ::rtl::OUString > m_aProperties;\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xSet;\n OPropertyChangeListener* m_pListener;\n sal_Int32 m_nLockCount;\n sal_Bool m_bListening : 1;\n sal_Bool m_bAutoSetRelease : 1;\n\n\n virtual ~OPropertyChangeMultiplexer();\n public:\n OPropertyChangeMultiplexer(OPropertyChangeListener* _pListener, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxSet, sal_Bool _bAutoReleaseSet = sal_True);\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertyChangeListener\n virtual void SAL_CALL propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw( ::com::sun::star::uno::RuntimeException);\n\n \/\/\/ incremental lock\n void lock();\n \/\/\/ incremental unlock\n void unlock();\n \/\/\/ get the lock count\n sal_Int32 locked() const { return m_nLockCount; }\n\n void addProperty(const ::rtl::OUString& aPropertyName);\n void dispose();\n };\n\n\/\/.........................................................................\n} \/\/ namespace comphelper\n\/\/.........................................................................\n\n#endif \/\/ _COMPHELPER_PROPERTY_MULTIPLEX_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: regpathhelper.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:38: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\n#ifndef _COMPHELPER_REGPATHHELPER_HXX_\n#define _COMPHELPER_REGPATHHELPER_HXX_\n\n#ifndef _RTL_OUSTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\nnamespace comphelper\n{\n\n\/**\n * This function returns a path to the user registry file.\n * Search for the user registry using the following rules:\n * <dl>\n * <dt> 1. (for further use) search in sversion.ini (.sversionrc) for an entry\n * REGISTRY_VERSION_STRING (example: UserRegistry 5.0\/505=test.rdb) in the section\n * [Registry]. If found, then take this value instead of the name \"user.rdb\".\n * <dt> 2. Search in the config directory of the user for a file \"user.rdb\". If\n * found return the full path and name of the file. If not found, retry this\n * step with a dot before \".user.rdb\".\n * <dt> 3. If not found a new user registry with name \"user.rdb\" will be created in the user\n * config directory.\n * <\/dl>\n *<BR>\n * @author Juergen Schmidt\n *\/\n::rtl::OUString getPathToUserRegistry();\n\n\/**\n * This function returns a path to the system registry file.\n * The system registry will always be searched in the same directory of the\n * executable. The name of the system registry is \"applicat.rdb\". If the system\n * registry was not found, then the environment variable STAR_REGISTRY will be checked.\n * If this variable was set, it must contain a full path to a valid system registry.\n * Search for the user registry using the following rules:\n *\n *<BR>\n * @author Juergen Schmidt\n *\/\n\n::rtl::OUString getPathToSystemRegistry();\n\n}\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.246); FILE MERGED 2008\/04\/01 15:05:23 thb 1.2.246.2: #i85898# Stripping all external header guards 2008\/03\/31 12:19:29 rt 1.2.246.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: regpathhelper.hxx,v $\n * $Revision: 1.3 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _COMPHELPER_REGPATHHELPER_HXX_\n#define _COMPHELPER_REGPATHHELPER_HXX_\n\n#include <rtl\/ustring.hxx>\n\nnamespace comphelper\n{\n\n\/**\n * This function returns a path to the user registry file.\n * Search for the user registry using the following rules:\n * <dl>\n * <dt> 1. (for further use) search in sversion.ini (.sversionrc) for an entry\n * REGISTRY_VERSION_STRING (example: UserRegistry 5.0\/505=test.rdb) in the section\n * [Registry]. If found, then take this value instead of the name \"user.rdb\".\n * <dt> 2. Search in the config directory of the user for a file \"user.rdb\". If\n * found return the full path and name of the file. If not found, retry this\n * step with a dot before \".user.rdb\".\n * <dt> 3. If not found a new user registry with name \"user.rdb\" will be created in the user\n * config directory.\n * <\/dl>\n *<BR>\n * @author Juergen Schmidt\n *\/\n::rtl::OUString getPathToUserRegistry();\n\n\/**\n * This function returns a path to the system registry file.\n * The system registry will always be searched in the same directory of the\n * executable. The name of the system registry is \"applicat.rdb\". If the system\n * registry was not found, then the environment variable STAR_REGISTRY will be checked.\n * If this variable was set, it must contain a full path to a valid system registry.\n * Search for the user registry using the following rules:\n *\n *<BR>\n * @author Juergen Schmidt\n *\/\n\n::rtl::OUString getPathToSystemRegistry();\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: propsetaccessimpl.hxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: jb $ $Date: 2000-11-07 14:34:32 $\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 CONFIGMGR_API_PROPERTYSETIMPL_HXX_\n#define CONFIGMGR_API_PROPERTYSETIMPL_HXX_\n\n#ifndef CONFIGMGR_APITYPES_HXX_\n#include \"apitypes.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XHIERARCHICALPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XHierarchicalPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XMultiPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XMULTIHIERARCHICALPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XMultiHierarchicalPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_\n#include <com\/sun\/star\/beans\/XPropertyState.hpp>\n#endif\n\nnamespace configmgr\n{\n namespace css = ::com::sun::star;\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n namespace beans = ::com::sun::star::beans;\n\n \/* implementations of the interfaces supported by a (parent) node\n within the configuration tree.\n (read-only operation)\n *\/\n namespace configapi\n {\n class NodeAccess;\n class NodeGroupInfoAccess;\n class NodeGroupAccess;\n\n \/\/ getting Property Metadata\n \/\/ XPropertySet & XMultiPropertySet\n uno::Reference< beans::XPropertySetInfo > implGetPropertySetInfo( NodeGroupInfoAccess& rNode )\n throw(uno::RuntimeException);\n\n \/\/ XHierarchicalPropertySet & XHierarchicalMultiPropertySet\n uno::Reference< beans::XHierarchicalPropertySetInfo > implGetHierarchicalPropertySetInfo( NodeGroupInfoAccess& rNode )\n throw(uno::RuntimeException);\n\n \/\/ setting values - may all throw (PropertyVeto)Exceptions on read-only property sets\n \/\/ XPropertySet\n void implSetPropertyValue( NodeGroupAccess& rNode, const OUString& aPropertyName, const uno::Any& aValue )\n throw(beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException,\n lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XMultiPropertySet\n void implSetPropertyValues( NodeGroupAccess& rNode, const uno::Sequence< OUString >& PropertyNames, const uno::Sequence< uno::Any >& Values )\n throw(beans::PropertyVetoException, lang::IllegalArgumentException,\n lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XHierarchicalPropertySet\n void implSetHierarchicalPropertyValue( NodeGroupAccess& rNode, const OUString& aPropertyName, const uno::Any& aValue )\n throw(beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException,\n lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XMultiHierarchicalPropertySet\n void implSetHierarchicalPropertyValues( NodeGroupAccess& rNode, const uno::Sequence< OUString >& PropertyNames, const uno::Sequence< uno::Any >& Values )\n throw(beans::PropertyVetoException, lang::IllegalArgumentException,\n lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ getting values\n \/\/ XPropertySet\n uno::Any implGetPropertyValue( NodeGroupInfoAccess& rNode,const OUString& PropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XMultiPropertySet\n uno::Sequence< uno::Any > implGetPropertyValues( NodeGroupInfoAccess& rNode, const uno::Sequence< OUString >& aPropertyNames )\n throw(uno::RuntimeException);\n\n \/\/ XHierarchicalPropertySet\n uno::Any implGetHierarchicalPropertyValue( NodeGroupInfoAccess& rNode, const OUString& PropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XMultiHierarchicalPropertySet\n uno::Sequence< uno::Any > implGetHierarchicalPropertyValues( NodeGroupInfoAccess& rNode, const uno::Sequence< OUString >& aPropertyNames )\n throw(uno::RuntimeException);\n\n \/\/ SPECIAL: firePropertiesChangeEvent\n \/\/ XMultiPropertySet\n void implFirePropertiesChangeEvent( NodeGroupInfoAccess& rNode, const uno::Sequence< OUString >& aPropertyNames, const uno::Reference< beans::XPropertiesChangeListener >& xListener )\n throw(uno::RuntimeException);\n\n \/\/ XPropertyState\n beans::PropertyState implGetPropertyState( NodeAccess& rNode, const OUString& PropertyName )\n throw(beans::UnknownPropertyException, uno::RuntimeException);\n\n uno::Sequence< beans::PropertyState > implGetPropertyStates( NodeAccess& rNode, const uno::Sequence< OUString >& aPropertyName )\n throw(beans::UnknownPropertyException, uno::RuntimeException);\n\n void implSetPropertyToDefault( NodeGroupAccess& rNode, const OUString& PropertyName )\n throw(beans::UnknownPropertyException, uno::RuntimeException);\n\n uno::Any implGetPropertyDefault( NodeAccess& rNode, const OUString& aPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException);\n\n }\n\n}\n#endif \/\/ CONFIGMGR_API_PROPERTYSETIMPL_HXX_\n\n\n<commit_msg>implGetPropertySetInfo takes an additional parameter<commit_after>\/*************************************************************************\n *\n * $RCSfile: propsetaccessimpl.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: fs $ $Date: 2000-11-21 19:19:09 $\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 CONFIGMGR_API_PROPERTYSETIMPL_HXX_\n#define CONFIGMGR_API_PROPERTYSETIMPL_HXX_\n\n#ifndef CONFIGMGR_APITYPES_HXX_\n#include \"apitypes.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XHIERARCHICALPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XHierarchicalPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XMultiPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XMULTIHIERARCHICALPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XMultiHierarchicalPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_\n#include <com\/sun\/star\/beans\/XPropertyState.hpp>\n#endif\n\nnamespace configmgr\n{\n namespace css = ::com::sun::star;\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n namespace beans = ::com::sun::star::beans;\n\n \/* implementations of the interfaces supported by a (parent) node\n within the configuration tree.\n (read-only operation)\n *\/\n namespace configapi\n {\n class NodeAccess;\n class NodeGroupInfoAccess;\n class NodeGroupAccess;\n\n \/\/ getting Property Metadata\n \/\/ XPropertySet & XMultiPropertySet\n uno::Reference< beans::XPropertySetInfo > implGetPropertySetInfo( NodeGroupInfoAccess& rNode, sal_Bool _bWriteable )\n throw(uno::RuntimeException);\n\n \/\/ XHierarchicalPropertySet & XHierarchicalMultiPropertySet\n uno::Reference< beans::XHierarchicalPropertySetInfo > implGetHierarchicalPropertySetInfo( NodeGroupInfoAccess& rNode )\n throw(uno::RuntimeException);\n\n \/\/ setting values - may all throw (PropertyVeto)Exceptions on read-only property sets\n \/\/ XPropertySet\n void implSetPropertyValue( NodeGroupAccess& rNode, const OUString& aPropertyName, const uno::Any& aValue )\n throw(beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException,\n lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XMultiPropertySet\n void implSetPropertyValues( NodeGroupAccess& rNode, const uno::Sequence< OUString >& PropertyNames, const uno::Sequence< uno::Any >& Values )\n throw(beans::PropertyVetoException, lang::IllegalArgumentException,\n lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XHierarchicalPropertySet\n void implSetHierarchicalPropertyValue( NodeGroupAccess& rNode, const OUString& aPropertyName, const uno::Any& aValue )\n throw(beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException,\n lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XMultiHierarchicalPropertySet\n void implSetHierarchicalPropertyValues( NodeGroupAccess& rNode, const uno::Sequence< OUString >& PropertyNames, const uno::Sequence< uno::Any >& Values )\n throw(beans::PropertyVetoException, lang::IllegalArgumentException,\n lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ getting values\n \/\/ XPropertySet\n uno::Any implGetPropertyValue( NodeGroupInfoAccess& rNode,const OUString& PropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XMultiPropertySet\n uno::Sequence< uno::Any > implGetPropertyValues( NodeGroupInfoAccess& rNode, const uno::Sequence< OUString >& aPropertyNames )\n throw(uno::RuntimeException);\n\n \/\/ XHierarchicalPropertySet\n uno::Any implGetHierarchicalPropertyValue( NodeGroupInfoAccess& rNode, const OUString& PropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XMultiHierarchicalPropertySet\n uno::Sequence< uno::Any > implGetHierarchicalPropertyValues( NodeGroupInfoAccess& rNode, const uno::Sequence< OUString >& aPropertyNames )\n throw(uno::RuntimeException);\n\n \/\/ SPECIAL: firePropertiesChangeEvent\n \/\/ XMultiPropertySet\n void implFirePropertiesChangeEvent( NodeGroupInfoAccess& rNode, const uno::Sequence< OUString >& aPropertyNames, const uno::Reference< beans::XPropertiesChangeListener >& xListener )\n throw(uno::RuntimeException);\n\n \/\/ XPropertyState\n beans::PropertyState implGetPropertyState( NodeAccess& rNode, const OUString& PropertyName )\n throw(beans::UnknownPropertyException, uno::RuntimeException);\n\n uno::Sequence< beans::PropertyState > implGetPropertyStates( NodeAccess& rNode, const uno::Sequence< OUString >& aPropertyName )\n throw(beans::UnknownPropertyException, uno::RuntimeException);\n\n void implSetPropertyToDefault( NodeGroupAccess& rNode, const OUString& PropertyName )\n throw(beans::UnknownPropertyException, uno::RuntimeException);\n\n uno::Any implGetPropertyDefault( NodeAccess& rNode, const OUString& aPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException);\n\n }\n\n}\n#endif \/\/ CONFIGMGR_API_PROPERTYSETIMPL_HXX_\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: serviceinfohelper.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: jb $ $Date: 2002-12-06 13:07:48 $\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: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"serviceinfohelper.hxx\"\n\nnamespace configmgr\n{\n\/\/ ---------------------------------------------------------------------------\n\n sal_Int32 ServiceInfoHelper::countServices( ) const\n {\n if (m_info == 0)\n return 0;\n\n sal_Int32 nCount = 0;\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n ++nCount;\n ++p;\n }\n }\n if (AsciiServiceName const* p= m_info->additionalServiceNames)\n {\n while (*p != 0)\n {\n ++nCount;\n ++p;\n }\n }\n\n return nCount;\n }\n\/\/ ---------------------------------------------------------------------------\n\n OUString ServiceInfoHelper::getImplementationName( ) const\n throw(uno::RuntimeException)\n {\n AsciiServiceName p= m_info ? m_info->implementationName : 0;\n\n return p ? OUString::createFromAscii(p) : OUString();\n }\n\/\/ ---------------------------------------------------------------------------\n\n sal_Bool ServiceInfoHelper::supportsService( OUString const & ServiceName ) const\n throw(uno::RuntimeException)\n {\n if (m_info == 0)\n return false;\n\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n if (ServiceName.equalsAscii(*p))\n return true;\n ++p;\n }\n }\n if (AsciiServiceName const* p= m_info->additionalServiceNames)\n {\n while (*p != 0)\n {\n if (ServiceName.equalsAscii(*p))\n return true;\n ++p;\n }\n }\n\n return false;\n }\n\/\/ ---------------------------------------------------------------------------\n\n uno::Sequence< OUString > ServiceInfoHelper::getSupportedServiceNames( ) const\n throw(uno::RuntimeException)\n {\n sal_Int32 const nCount = countServices();\n\n uno::Sequence< OUString > aServices( nCount );\n\n if (nCount)\n {\n OSL_ASSERT(m_info);\n sal_Int32 i = 0;\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n aServices[i++] = OUString::createFromAscii(*p++);\n }\n }\n if (AsciiServiceName const* p= m_info->additionalServiceNames)\n {\n while (*p != 0)\n {\n aServices[i++] = OUString::createFromAscii(*p++);\n }\n }\n OSL_ASSERT( i == nCount );\n }\n\n return aServices;\n }\n\/\/ ---------------------------------------------------------------------------\n\/\/ ---------------------------------------------------------------------------\n\n sal_Int32 ServiceRegistrationHelper::countServices( ) const\n {\n if (m_info == 0)\n return 0;\n\n sal_Int32 nCount = 0;\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n ++nCount;\n ++p;\n }\n }\n\n return nCount;\n }\n\/\/ ---------------------------------------------------------------------------\n\n OUString ServiceRegistrationHelper::getImplementationName( ) const\n throw(uno::RuntimeException)\n {\n AsciiServiceName p= m_info ? m_info->implementationName : 0;\n\n return p ? OUString::createFromAscii(p) : OUString();\n }\n\/\/ ---------------------------------------------------------------------------\n\n uno::Sequence< OUString > ServiceRegistrationHelper::getRegisteredServiceNames( ) const\n throw(uno::RuntimeException)\n {\n sal_Int32 const nCount = countServices();\n\n uno::Sequence< OUString > aServices( nCount );\n\n if (nCount)\n {\n OSL_ASSERT(m_info);\n sal_Int32 i = 0;\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n aServices[i++] = OUString::createFromAscii(*p++);\n }\n }\n OSL_ASSERT( i == nCount );\n }\n\n return aServices;\n }\n\/\/ ---------------------------------------------------------------------------\n} \/\/ namespace config\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.216); FILE MERGED 2005\/09\/05 17:04:59 rt 1.2.216.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: serviceinfohelper.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 04:12:42 $\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#include \"serviceinfohelper.hxx\"\n\nnamespace configmgr\n{\n\/\/ ---------------------------------------------------------------------------\n\n sal_Int32 ServiceInfoHelper::countServices( ) const\n {\n if (m_info == 0)\n return 0;\n\n sal_Int32 nCount = 0;\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n ++nCount;\n ++p;\n }\n }\n if (AsciiServiceName const* p= m_info->additionalServiceNames)\n {\n while (*p != 0)\n {\n ++nCount;\n ++p;\n }\n }\n\n return nCount;\n }\n\/\/ ---------------------------------------------------------------------------\n\n OUString ServiceInfoHelper::getImplementationName( ) const\n throw(uno::RuntimeException)\n {\n AsciiServiceName p= m_info ? m_info->implementationName : 0;\n\n return p ? OUString::createFromAscii(p) : OUString();\n }\n\/\/ ---------------------------------------------------------------------------\n\n sal_Bool ServiceInfoHelper::supportsService( OUString const & ServiceName ) const\n throw(uno::RuntimeException)\n {\n if (m_info == 0)\n return false;\n\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n if (ServiceName.equalsAscii(*p))\n return true;\n ++p;\n }\n }\n if (AsciiServiceName const* p= m_info->additionalServiceNames)\n {\n while (*p != 0)\n {\n if (ServiceName.equalsAscii(*p))\n return true;\n ++p;\n }\n }\n\n return false;\n }\n\/\/ ---------------------------------------------------------------------------\n\n uno::Sequence< OUString > ServiceInfoHelper::getSupportedServiceNames( ) const\n throw(uno::RuntimeException)\n {\n sal_Int32 const nCount = countServices();\n\n uno::Sequence< OUString > aServices( nCount );\n\n if (nCount)\n {\n OSL_ASSERT(m_info);\n sal_Int32 i = 0;\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n aServices[i++] = OUString::createFromAscii(*p++);\n }\n }\n if (AsciiServiceName const* p= m_info->additionalServiceNames)\n {\n while (*p != 0)\n {\n aServices[i++] = OUString::createFromAscii(*p++);\n }\n }\n OSL_ASSERT( i == nCount );\n }\n\n return aServices;\n }\n\/\/ ---------------------------------------------------------------------------\n\/\/ ---------------------------------------------------------------------------\n\n sal_Int32 ServiceRegistrationHelper::countServices( ) const\n {\n if (m_info == 0)\n return 0;\n\n sal_Int32 nCount = 0;\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n ++nCount;\n ++p;\n }\n }\n\n return nCount;\n }\n\/\/ ---------------------------------------------------------------------------\n\n OUString ServiceRegistrationHelper::getImplementationName( ) const\n throw(uno::RuntimeException)\n {\n AsciiServiceName p= m_info ? m_info->implementationName : 0;\n\n return p ? OUString::createFromAscii(p) : OUString();\n }\n\/\/ ---------------------------------------------------------------------------\n\n uno::Sequence< OUString > ServiceRegistrationHelper::getRegisteredServiceNames( ) const\n throw(uno::RuntimeException)\n {\n sal_Int32 const nCount = countServices();\n\n uno::Sequence< OUString > aServices( nCount );\n\n if (nCount)\n {\n OSL_ASSERT(m_info);\n sal_Int32 i = 0;\n if (AsciiServiceName const* p= m_info->registeredServiceNames)\n {\n while (*p != 0)\n {\n aServices[i++] = OUString::createFromAscii(*p++);\n }\n }\n OSL_ASSERT( i == nCount );\n }\n\n return aServices;\n }\n\/\/ ---------------------------------------------------------------------------\n} \/\/ namespace config\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"base\/command_line.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"content\/browser\/web_contents\/web_contents_impl.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"content\/shell\/shell.h\"\n#include \"content\/test\/content_browser_test.h\"\n#include \"content\/test\/content_browser_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\n#if defined(OS_WIN)\n#include \"base\/win\/windows_version.h\"\n#endif\n\nnamespace content {\n\nclass WebrtcBrowserTest: public ContentBrowserTest {\n public:\n WebrtcBrowserTest() {}\n virtual ~WebrtcBrowserTest() {}\n\n virtual void SetUpOnMainThread() OVERRIDE {\n \/\/ We need fake devices in this test since we want to run on naked VMs. We\n \/\/ assume this switch is set by default in content_browsertests.\n ASSERT_TRUE(CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kUseFakeDeviceForMediaStream));\n\n ASSERT_TRUE(test_server()->Start());\n }\n protected:\n bool ExecuteJavascript(const std::string& javascript) {\n return ExecuteScript(shell()->web_contents(), javascript);\n }\n\n void ExpectTitle(const std::string& expected_title) const {\n string16 expected_title16(ASCIIToUTF16(expected_title));\n TitleWatcher title_watcher(shell()->web_contents(), expected_title16);\n EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle());\n }\n};\n\n\/\/ These tests will all make a getUserMedia call with different constraints and\n\/\/ see that the success callback is called. If the error callback is called or\n\/\/ none of the callbacks are called the tests will simply time out and fail.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetVideoStreamAndStop) {\n GURL url(test_server()->GetURL(\"files\/media\/getusermedia_and_stop.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"getUserMedia({video: true});\"));\n\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetAudioAndVideoStreamAndStop) {\n GURL url(test_server()->GetURL(\"files\/media\/getusermedia_and_stop.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"getUserMedia({video: true, audio: true});\"));\n\n ExpectTitle(\"OK\");\n}\n\n\/\/ These tests will make a complete PeerConnection-based call and verify that\n\/\/ video is playing for the call.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupVideoCall) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"call({video: true});\"));\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCall) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"call({video: true, audio: true});\"));\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, MANUAL_CanSetupCallAndSendDtmf) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(\n ExecuteJavascript(\"callAndSendDtmf('123,abc');\"));\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,\n CanMakeEmptyCallThenAddStreamsAndRenegotiate) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n const char* kJavascript =\n \"makeEmptyCallThenAddOneStreamAndRenegotiate(\"\n \"{video: true, audio: true});\";\n EXPECT_TRUE(ExecuteJavascript(kJavascript));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a complete PeerConnection-based call but remove the\n\/\/ MSID and bundle attribute from the initial offer to verify that\n\/\/ video is playing for the call even if the initiating client don't support\n\/\/ MSID. http:\/\/tools.ietf.org\/html\/draft-alvestrand-rtcweb-msid-02\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,\n CanSetupAudioAndVideoCallWithoutMsidAndBundle) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithoutMsidAndBundle();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataOnly) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataOnly();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel and audio and video tracks.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndMedia) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataAndMedia();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel and later add an audio and video track.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndLaterAddMedia) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataAndLaterAddMedia();\"));\n ExpectTitle(\"OK\");\n}\n\n} \/\/ namespace content\n\n<commit_msg>Disable WebrtcBrowserTest.CallWithDataAndLaterAddMedia test.<commit_after>\/\/ 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 \"base\/command_line.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"content\/browser\/web_contents\/web_contents_impl.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"content\/shell\/shell.h\"\n#include \"content\/test\/content_browser_test.h\"\n#include \"content\/test\/content_browser_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\n#if defined(OS_WIN)\n#include \"base\/win\/windows_version.h\"\n#endif\n\nnamespace content {\n\nclass WebrtcBrowserTest: public ContentBrowserTest {\n public:\n WebrtcBrowserTest() {}\n virtual ~WebrtcBrowserTest() {}\n\n virtual void SetUpOnMainThread() OVERRIDE {\n \/\/ We need fake devices in this test since we want to run on naked VMs. We\n \/\/ assume this switch is set by default in content_browsertests.\n ASSERT_TRUE(CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kUseFakeDeviceForMediaStream));\n\n ASSERT_TRUE(test_server()->Start());\n }\n protected:\n bool ExecuteJavascript(const std::string& javascript) {\n return ExecuteScript(shell()->web_contents(), javascript);\n }\n\n void ExpectTitle(const std::string& expected_title) const {\n string16 expected_title16(ASCIIToUTF16(expected_title));\n TitleWatcher title_watcher(shell()->web_contents(), expected_title16);\n EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle());\n }\n};\n\n\/\/ These tests will all make a getUserMedia call with different constraints and\n\/\/ see that the success callback is called. If the error callback is called or\n\/\/ none of the callbacks are called the tests will simply time out and fail.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetVideoStreamAndStop) {\n GURL url(test_server()->GetURL(\"files\/media\/getusermedia_and_stop.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"getUserMedia({video: true});\"));\n\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetAudioAndVideoStreamAndStop) {\n GURL url(test_server()->GetURL(\"files\/media\/getusermedia_and_stop.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"getUserMedia({video: true, audio: true});\"));\n\n ExpectTitle(\"OK\");\n}\n\n\/\/ These tests will make a complete PeerConnection-based call and verify that\n\/\/ video is playing for the call.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupVideoCall) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"call({video: true});\"));\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCall) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"call({video: true, audio: true});\"));\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, MANUAL_CanSetupCallAndSendDtmf) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(\n ExecuteJavascript(\"callAndSendDtmf('123,abc');\"));\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,\n CanMakeEmptyCallThenAddStreamsAndRenegotiate) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n const char* kJavascript =\n \"makeEmptyCallThenAddOneStreamAndRenegotiate(\"\n \"{video: true, audio: true});\";\n EXPECT_TRUE(ExecuteJavascript(kJavascript));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a complete PeerConnection-based call but remove the\n\/\/ MSID and bundle attribute from the initial offer to verify that\n\/\/ video is playing for the call even if the initiating client don't support\n\/\/ MSID. http:\/\/tools.ietf.org\/html\/draft-alvestrand-rtcweb-msid-02\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,\n CanSetupAudioAndVideoCallWithoutMsidAndBundle) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithoutMsidAndBundle();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataOnly) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataOnly();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel and audio and video tracks.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndMedia) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataAndMedia();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel and later add an audio and video track.\n\/\/ TODO(perkj): Fix flakiness. See: http:\/\/crbug.com\/227409\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,\n DISABLED_CallWithDataAndLaterAddMedia) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataAndLaterAddMedia();\"));\n ExpectTitle(\"OK\");\n}\n\n} \/\/ namespace content\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ DCMQI includes\n#include \"dcmqi\/Helper.h\"\n\n\/\/ DCMTK includes\n#include <dcmtk\/ofstd\/oflist.h>\n\nnamespace dcmqi {\n\n bool Helper::isUndefinedOrPathDoesNotExist(const string &var, const string &humanReadableName) {\n return Helper::isUndefined(var, humanReadableName) || !Helper::pathExists(var);\n }\n\n bool Helper::isUndefinedOrPathsDoNotExist(vector<string> &var, const string &humanReadableName) {\n return Helper::isUndefined(var, humanReadableName) || !Helper::pathsExist(var);\n }\n\n bool Helper::pathsExist(const vector<string> &paths) {\n bool allExist = true;\n for(vector<string>::const_iterator iter = paths.begin(); iter != paths.end(); ++iter) {\n if (!Helper::pathExists(*iter)){\n allExist = false;\n }\n }\n return allExist;\n }\n\n bool Helper::pathExists(const string &path) {\n struct stat buffer;\n if (stat (path.c_str(), &buffer) != 0) {\n cerr << \"Error: \" << path << \" not found!\" << endl;\n return false;\n } else {\n return true;\n }\n }\n\n string Helper::getFileExtensionFromType(const string& type) {\n string extension = \".nrrd\";\n if (type == \"nii\" || type == \"nifti\")\n extension = \".nii.gz\";\n else if (type == \"mhd\")\n extension = \".mhd\";\n else if (type == \"mha\")\n extension = \".mha\";\n else if (type == \"img\")\n extension = \".img\";\n else if (type == \"hdr\")\n extension = \".hdr\";\n else if (type == \"nrrd\")\n extension = \".nrrd\";\n return extension;\n }\n\n vector<string> Helper::getFileListRecursively(string directory) {\n OFList<OFString> fileList;\n vector<string> dicomImageFiles;\n#if _WIN32\n replace(directory.begin(), directory.end(), '\/', PATH_SEPARATOR);\n#endif\n cout << \"Searching recursively \" << directory << \" for DICOM files\" << endl;\n if(OFStandard::searchDirectoryRecursively(directory.c_str(), fileList)) {\n for(OFListIterator(OFString) fileListIterator=fileList.begin(); fileListIterator!=fileList.end(); fileListIterator++) {\n dicomImageFiles.push_back((*fileListIterator).c_str());\n }\n }\n return dicomImageFiles;\n }\n\n vector<DcmDataset*> Helper::loadDatasets(const vector<string>& dicomImageFiles) {\n vector<DcmDataset*> dcmDatasets;\n OFString tmp, sopInstanceUID;\n DcmFileFormat* sliceFF = new DcmFileFormat();\n for(size_t dcmFileNumber=0; dcmFileNumber<dicomImageFiles.size(); dcmFileNumber++){\n if(sliceFF->loadFile(dicomImageFiles[dcmFileNumber].c_str()).good()){\n DcmDataset* currentDataset = sliceFF->getAndRemoveDataset();\n if(!currentDataset->tagExistsWithValue(DCM_PixelData)){\n std::cerr << \"Source DICOM file does not contain PixelData, skipping: \" << std::endl\n << \" >>> \" << dicomImageFiles[dcmFileNumber] << std::endl;\n continue;\n };\n currentDataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);\n bool exists = false;\n for(size_t i=0;i<dcmDatasets.size();i++) {\n dcmDatasets[i]->findAndGetOFString(DCM_SOPInstanceUID, tmp);\n if (tmp == sopInstanceUID) {\n cout << dicomImageFiles[dcmFileNumber].c_str() << \" with SOPInstanceUID: \" << sopInstanceUID\n << \" already exists\" << endl;\n exists = true;\n break;\n }\n }\n if (!exists) {\n dcmDatasets.push_back(currentDataset);\n }\n } else {\n cerr << \"Failed to read \" << dicomImageFiles[dcmFileNumber] << \". Skipping it.\" << endl;\n }\n }\n delete sliceFF;\n return dcmDatasets;\n }\n\n\n string Helper::floatToStr(float f) {\n ostringstream sstream;\n sstream.imbue(std::locale::classic());\n sstream.precision(9);\n sstream << f;\n string f_str = sstream.str();\n cout << \"Formatted float (length): \" << f_str << \"(\" << f_str.size() << \")\" << endl;\n return sstream.str();\n }\n\n void Helper::checkValidityOfFirstSrcImage(DcmSegmentation *segdoc) {\n FGInterface &fgInterface = segdoc->getFunctionalGroups();\n bool isPerFrame = false;\n FGDerivationImage *derimgfg = OFstatic_cast(FGDerivationImage*, fgInterface.get(0, DcmFGTypes::EFG_DERIVATIONIMAGE,\n isPerFrame));\n if(!derimgfg){\n cout << \"Debug: No derivation items present in the segmentation dataset\" << endl;\n }\n assert(isPerFrame);\n\n OFVector<DerivationImageItem *> &deritems = derimgfg->getDerivationImageItems();\n\n OFVector<SourceImageItem *> &srcitems = deritems[0]->getSourceImageItems();\n OFString codeValue;\n if(srcitems.size()>0){\n CodeSequenceMacro &code = srcitems[0]->getPurposeOfReferenceCode();\n if (!code.getCodeValue(codeValue).good()) {\n cout << \"Failed to look up purpose of reference code\" << endl;\n abort();\n }\n } else {\n cout << \"Warning: Source images are not initialized!\" << endl;\n }\n }\n\n void Helper::tokenizeString(string str, vector<string> &tokens, string delimiter) {\n \/\/ http:\/\/stackoverflow.com\/questions\/14265581\/parse-split-a-string-in-c-using-string-delimiter-standard-c\n size_t pos = 0;\n while ((pos = str.find(delimiter)) != string::npos) {\n string token = str.substr(0, pos);\n tokens.push_back(token);\n str.erase(0, pos + delimiter.length());\n }\n tokens.push_back(str);\n };\n\n void Helper::splitString(string str, string &head, string &tail, string delimiter) {\n \/\/ http:\/\/stackoverflow.com\/questions\/14265581\/parse-split-a-string-in-c-using-string-delimiter-standard-c\n size_t pos = str.find(delimiter);\n if (pos != string::npos) {\n head = str.substr(0, pos);\n tail = str.substr(pos + delimiter.length(), str.length() - 1);\n }\n };\n\n string Helper::toString(const unsigned int& value) {\n ostringstream oss;\n oss << value;\n return oss.str();\n }\n\n CodeSequenceMacro Helper::stringToCodeSequenceMacro(string str) {\n string tail, code, designator, meaning;\n splitString(str, code, tail, \",\");\n splitString(tail, designator, meaning, \",\");\n return CodeSequenceMacro(code.c_str(), designator.c_str(), meaning.c_str());\n }\n\n DSRCodedEntryValue Helper::stringToDSRCodedEntryValue(string str) {\n string tail, code, designator, meaning;\n splitString(str, code, tail, \",\");\n splitString(tail, designator, meaning, \",\");\n return DSRCodedEntryValue(code.c_str(), designator.c_str(), meaning.c_str());\n }\n\n CodeSequenceMacro* Helper::createNewCodeSequence(const string& code, const string& designator, const string& meaning) {\n if (code.empty() || designator.empty() || meaning.empty())\n throw CodeSequenceValueException();\n return new CodeSequenceMacro(code.c_str(), designator.c_str(), meaning.c_str());\n }\n\n\n}\n<commit_msg>CI: remove print<commit_after>\n\/\/ DCMQI includes\n#include \"dcmqi\/Helper.h\"\n\n\/\/ DCMTK includes\n#include <dcmtk\/ofstd\/oflist.h>\n\nnamespace dcmqi {\n\n bool Helper::isUndefinedOrPathDoesNotExist(const string &var, const string &humanReadableName) {\n return Helper::isUndefined(var, humanReadableName) || !Helper::pathExists(var);\n }\n\n bool Helper::isUndefinedOrPathsDoNotExist(vector<string> &var, const string &humanReadableName) {\n return Helper::isUndefined(var, humanReadableName) || !Helper::pathsExist(var);\n }\n\n bool Helper::pathsExist(const vector<string> &paths) {\n bool allExist = true;\n for(vector<string>::const_iterator iter = paths.begin(); iter != paths.end(); ++iter) {\n if (!Helper::pathExists(*iter)){\n allExist = false;\n }\n }\n return allExist;\n }\n\n bool Helper::pathExists(const string &path) {\n struct stat buffer;\n if (stat (path.c_str(), &buffer) != 0) {\n cerr << \"Error: \" << path << \" not found!\" << endl;\n return false;\n } else {\n return true;\n }\n }\n\n string Helper::getFileExtensionFromType(const string& type) {\n string extension = \".nrrd\";\n if (type == \"nii\" || type == \"nifti\")\n extension = \".nii.gz\";\n else if (type == \"mhd\")\n extension = \".mhd\";\n else if (type == \"mha\")\n extension = \".mha\";\n else if (type == \"img\")\n extension = \".img\";\n else if (type == \"hdr\")\n extension = \".hdr\";\n else if (type == \"nrrd\")\n extension = \".nrrd\";\n return extension;\n }\n\n vector<string> Helper::getFileListRecursively(string directory) {\n OFList<OFString> fileList;\n vector<string> dicomImageFiles;\n#if _WIN32\n replace(directory.begin(), directory.end(), '\/', PATH_SEPARATOR);\n#endif\n cout << \"Searching recursively \" << directory << \" for DICOM files\" << endl;\n if(OFStandard::searchDirectoryRecursively(directory.c_str(), fileList)) {\n for(OFListIterator(OFString) fileListIterator=fileList.begin(); fileListIterator!=fileList.end(); fileListIterator++) {\n dicomImageFiles.push_back((*fileListIterator).c_str());\n }\n }\n return dicomImageFiles;\n }\n\n vector<DcmDataset*> Helper::loadDatasets(const vector<string>& dicomImageFiles) {\n vector<DcmDataset*> dcmDatasets;\n OFString tmp, sopInstanceUID;\n DcmFileFormat* sliceFF = new DcmFileFormat();\n for(size_t dcmFileNumber=0; dcmFileNumber<dicomImageFiles.size(); dcmFileNumber++){\n if(sliceFF->loadFile(dicomImageFiles[dcmFileNumber].c_str()).good()){\n DcmDataset* currentDataset = sliceFF->getAndRemoveDataset();\n if(!currentDataset->tagExistsWithValue(DCM_PixelData)){\n std::cerr << \"Source DICOM file does not contain PixelData, skipping: \" << std::endl\n << \" >>> \" << dicomImageFiles[dcmFileNumber] << std::endl;\n continue;\n };\n currentDataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);\n bool exists = false;\n for(size_t i=0;i<dcmDatasets.size();i++) {\n dcmDatasets[i]->findAndGetOFString(DCM_SOPInstanceUID, tmp);\n if (tmp == sopInstanceUID) {\n cout << dicomImageFiles[dcmFileNumber].c_str() << \" with SOPInstanceUID: \" << sopInstanceUID\n << \" already exists\" << endl;\n exists = true;\n break;\n }\n }\n if (!exists) {\n dcmDatasets.push_back(currentDataset);\n }\n } else {\n cerr << \"Failed to read \" << dicomImageFiles[dcmFileNumber] << \". Skipping it.\" << endl;\n }\n }\n delete sliceFF;\n return dcmDatasets;\n }\n\n\n string Helper::floatToStr(float f) {\n ostringstream sstream;\n sstream.imbue(std::locale::classic());\n sstream.precision(9);\n sstream << f;\n \/\/string f_str = sstream.str();\n \/\/cout << \"Formatted float (length): \" << f_str << \"(\" << f_str.size() << \")\" << endl;\n return sstream.str();\n }\n\n void Helper::checkValidityOfFirstSrcImage(DcmSegmentation *segdoc) {\n FGInterface &fgInterface = segdoc->getFunctionalGroups();\n bool isPerFrame = false;\n FGDerivationImage *derimgfg = OFstatic_cast(FGDerivationImage*, fgInterface.get(0, DcmFGTypes::EFG_DERIVATIONIMAGE,\n isPerFrame));\n if(!derimgfg){\n cout << \"Debug: No derivation items present in the segmentation dataset\" << endl;\n }\n assert(isPerFrame);\n\n OFVector<DerivationImageItem *> &deritems = derimgfg->getDerivationImageItems();\n\n OFVector<SourceImageItem *> &srcitems = deritems[0]->getSourceImageItems();\n OFString codeValue;\n if(srcitems.size()>0){\n CodeSequenceMacro &code = srcitems[0]->getPurposeOfReferenceCode();\n if (!code.getCodeValue(codeValue).good()) {\n cout << \"Failed to look up purpose of reference code\" << endl;\n abort();\n }\n } else {\n cout << \"Warning: Source images are not initialized!\" << endl;\n }\n }\n\n void Helper::tokenizeString(string str, vector<string> &tokens, string delimiter) {\n \/\/ http:\/\/stackoverflow.com\/questions\/14265581\/parse-split-a-string-in-c-using-string-delimiter-standard-c\n size_t pos = 0;\n while ((pos = str.find(delimiter)) != string::npos) {\n string token = str.substr(0, pos);\n tokens.push_back(token);\n str.erase(0, pos + delimiter.length());\n }\n tokens.push_back(str);\n };\n\n void Helper::splitString(string str, string &head, string &tail, string delimiter) {\n \/\/ http:\/\/stackoverflow.com\/questions\/14265581\/parse-split-a-string-in-c-using-string-delimiter-standard-c\n size_t pos = str.find(delimiter);\n if (pos != string::npos) {\n head = str.substr(0, pos);\n tail = str.substr(pos + delimiter.length(), str.length() - 1);\n }\n };\n\n string Helper::toString(const unsigned int& value) {\n ostringstream oss;\n oss << value;\n return oss.str();\n }\n\n CodeSequenceMacro Helper::stringToCodeSequenceMacro(string str) {\n string tail, code, designator, meaning;\n splitString(str, code, tail, \",\");\n splitString(tail, designator, meaning, \",\");\n return CodeSequenceMacro(code.c_str(), designator.c_str(), meaning.c_str());\n }\n\n DSRCodedEntryValue Helper::stringToDSRCodedEntryValue(string str) {\n string tail, code, designator, meaning;\n splitString(str, code, tail, \",\");\n splitString(tail, designator, meaning, \",\");\n return DSRCodedEntryValue(code.c_str(), designator.c_str(), meaning.c_str());\n }\n\n CodeSequenceMacro* Helper::createNewCodeSequence(const string& code, const string& designator, const string& meaning) {\n if (code.empty() || designator.empty() || meaning.empty())\n throw CodeSequenceValueException();\n return new CodeSequenceMacro(code.c_str(), designator.c_str(), meaning.c_str());\n }\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *MIT License\n *\n * Copyright (c) 2017 Banuprathap Anandan\n *\n * AUTHOR : BANUPRATHAP ANANDAN\n * AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER\n * EMAIL : BPRATHAP@UMD.EDU\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 * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\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 THE\n * SOFTWARE.\n *\n *\n *\n * Project: Frontier Explorer for Turtlebot\n *\n *\n *\/\n\n\/**\n * @file main.cpp\n * @brief \n * @author Banuprathap Anandan\n * @date 04\/26\/2017\n *\/\n#include \"ros\/ros.h\"\n#include \"ros\/console.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"sensor_msgs\/LaserScan.h\"\n#include \"nav_msgs\/OccupancyGrid.h\"\n\n\/**\n * @brief Execution starts here\n *\n * @param[in] argc The argc\n * @param argv The argv\n *\n * @return Returns 0 upon successful execution\n *\/\nint main(int argc, char **argv) {\n \/\/ Implement me\n return 0;\n}\n<commit_msg>Class declaration - explorer<commit_after>\/*\n *MIT License\n *\n * Copyright (c) 2017 Banuprathap Anandan\n *\n * AUTHOR : BANUPRATHAP ANANDAN\n * AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER\n * EMAIL : BPRATHAP@UMD.EDU\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 * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\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 THE\n * SOFTWARE.\n *\n *\n *\n * Project: Frontier Explorer for Turtlebot\n *\n *\n *\/\n\n\/**\n * @file main.cpp\n * @brief\n * @author Banuprathap Anandan\n * @date 04\/26\/2017\n *\/\n#include \"ros\/ros.h\"\n#include \"ros\/console.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"sensor_msgs\/LaserScan.h\"\n#include \"nav_msgs\/OccupancyGrid.h\"\n#include \"wavefront_detection.hpp\"\n\/**\n * @brief Class for exploration task.\n *\/\nclass Explorer {\n public:\n \/**\n * @brief Default constructor to initiate publisher and subscriber\n *\n *\n * @param nh ROS NodeHandle\n *\/\n Explorer(ros::NodeHandle& nh);\n \/**\n * @brief Callback function from the map subscriber\n *\n * @param[in] map The map\n *\/\n void mapCallback(const nav_msgs::OccupancyGrid& map);\n protected:\n sensor_msgs::PointCloud frontier_cloud;\n ros::Publisher frontier_pub;\n ros::Subscriber mapSub;\n};\n\n\/**\n * @brief Execution starts here\n *\n * @param[in] argc The argc\n * @param argv The argv\n *\n * @return Returns 0 upon successful execution\n *\/\nint main(int argc, char **argv) {\n \/\/ Implement me\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <getopt.h>\n\n#include \"waveforms\/SquareWave.h\"\n\nstatic const std::string VERSION = \"1.0\";\nstatic const std::string USAGE = \"\"\n\"Usage: wfg [-hv]\\n\"\n\" wfg [-0 <duration>] [-1 <duration>] square\\n\"\n\"\\n\"\n\"Options:\\n\"\n\" -h, --help Print this menu and exit.\\n\"\n\" -v, --version Print the program version and exit.\\n\"\n\" -0 The milliseconds for active low.\\n\"\n\" -1 The milliseconds for active high.\\n\"\n\"\\n\";\n\nint main(int argc, char **argv)\n{\n int opt;\n int optionIndex;\n int lowDuration = 1000000;\n int highDuration = 1000000;\n struct option options[] = {\n { \"help\", no_argument, NULL, 'h' },\n { \"version\", no_argument, NULL, 'v' },\n { 0, 0, 0, 0 },\n };\n\n while (1) {\n opt = getopt_long(argc, argv, \"hv0:1:\", options, &optionIndex);\n\n if (opt == -1) {\n break;\n }\n\n switch (opt) {\n case 'h':\n std::cout << USAGE << std::endl;\n return 0;\n\n case 'v':\n std::cout << VERSION << std::endl;\n return 0;\n\n case '0': {\n std::stringstream str(optarg);\n str >> lowDuration;\n break;\n }\n\n case '1': {\n std::stringstream str(optarg);\n str >> highDuration;\n break;\n }\n\n case 0:\n case '?':\n default:\n return 1;\n }\n }\n\n if ((argc - optind) < 1) {\n std::cerr << \"No waveform type specified. See -h for usage.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::string waveStr(argv[optind]);\n\n if (waveStr == \"square\") {\n SquareWave wave(lowDuration, highDuration);\n wave.SetDuration(5000000);\n wave.Generate();\n }\n\n return 0;\n}\n<commit_msg>Added a -t, --timeout option to generate a wave for certain amount of time<commit_after>#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <getopt.h>\n\n#include \"waveforms\/SquareWave.h\"\n\nstatic const std::string VERSION = \"1.0\";\nstatic const std::string USAGE = \"\"\n\"Usage: wfg [-hv]\\n\"\n\" wfg [-0 <duration>] [-1 <duration>] square\\n\"\n\"\\n\"\n\"Options:\\n\"\n\" -h, --help Print this menu and exit.\\n\"\n\" -v, --version Print the program version and exit.\\n\"\n\" -t, --timeout The milliseconds for how long to generate wave.\\n\"\n\" -0 The milliseconds for active low.\\n\"\n\" -1 The milliseconds for active high.\\n\"\n\"\\n\";\n\nint main(int argc, char **argv)\n{\n int opt;\n int optionIndex;\n int lowDuration = 1000000;\n int highDuration = 1000000;\n int timeout = 0;\n struct option options[] = {\n { \"help\", no_argument, NULL, 'h' },\n { \"version\", no_argument, NULL, 'v' },\n { \"timeout\", required_argument, NULL, 't' },\n { 0, 0, 0, 0 },\n };\n\n while (1) {\n opt = getopt_long(argc, argv, \"hv0:1:t:\", options, &optionIndex);\n\n if (opt == -1) {\n break;\n }\n\n switch (opt) {\n case 'h':\n std::cout << USAGE << std::endl;\n return 0;\n\n case 'v':\n std::cout << VERSION << std::endl;\n return 0;\n\n case 't': {\n std::stringstream str(optarg);\n str >> timeout;\n break;\n }\n\n case '0': {\n std::stringstream str(optarg);\n str >> lowDuration;\n break;\n }\n\n case '1': {\n std::stringstream str(optarg);\n str >> highDuration;\n break;\n }\n\n case 0:\n case '?':\n default:\n return 1;\n }\n }\n\n if ((argc - optind) < 1) {\n std::cerr << \"No waveform type specified. See -h for usage.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::string waveStr(argv[optind]);\n\n if (waveStr == \"square\") {\n SquareWave wave(lowDuration, highDuration);\n wave.SetDuration(timeout);\n wave.Generate();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Arduino.h>\n#include \"scheduler.h\"\n\nstatic Scheduler scheduler;\nstatic const int UPDATE_PERIOD_MS = 50;\n\nvoid setup()\n{\n\tSerial.begin(115200);\n\tdelay(1000);\n\tSerial.println(\"Hello world\");\n \/\/scheduler.ScheduleFunction(TASK, UPDATE_PERIOD_MS);\n}\n\nvoid loop()\n{\n scheduler.Update();\n}\n<commit_msg>Main prepared for use of scanners<commit_after>#include <Arduino.h>\n#include \"scheduler.h\"\n#include \"shape_mapping_scanner.h\"\n#include \"defined_area_scanner.h\"\n\nstatic Scheduler scheduler;\nstatic const int UPDATE_PERIOD_MS = 50;\nstatic void AppUpdate(void);\n\n\/\/ Scanner objects\n\/\/ Switch the commented out portions for other type of scanning\nstatic ShapeMappingScanner scanner;\n\/\/static DefinedAreaScanner scanner;\n\nvoid setup()\n{\n\tSerial.begin(115200);\n scheduler.ScheduleFunction(AppUpdate, UPDATE_PERIOD_MS);\n scanner.HardwareSetup();\n delay(1000);\n scanner.SetReferenceInductance();\n scanner.SetHomePosition();\n scanner.SetScanOrigin(0, 150, 40);\n\n \/\/ Uncomment these for use of the DefinedAreaScanner\n \/\/ and update parameters if necessary\n \/\/scanner.SetDesiredHorizontalTravelMM(100);\n \/\/scanner.SetDesiredDepthTravelMM(40);\n \/\/scanner.SetDepthScanIncrementMM(5);\n\n}\n\nvoid loop()\n{\n scheduler.Update();\n}\n\nstatic void AppUpdate(void)\n{\n scanner.Update(UPDATE_PERIOD_MS);\n if (scanner.isScanComplete())\n {\n Serial.println(\"Scan complete!\");\n while(1);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <fcntl.h>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/tokenizer.hpp>\n#include <stdlib.h>\n#include <iostream>\n#include <unistd.h>\n#include <string>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <stdio.h>\n#include <errno.h>\n#include <vector>\n\nusing namespace boost;\nusing namespace std;\n\nint check_input(string usrString)\n{\n\tif (usrString.find(\"&&\") != string::npos ||\n\t\tusrString.find(\"||\") != string::npos ||\n\t\tusrString.find(\";\") != string::npos ||\n\t\tusrString.find(\"#\") != string::npos ||\n\t\t(usrString.find(\">\") == string::npos &&\n\t\tusrString.find(\"<\") == string::npos &&\n\t\tusrString.find(\"|\") == string::npos))\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\telse\n\t{\n\t\treturn 1;\n\t}\n\treturn -1;\n}\n\nbool popv(string usrString, vector<string> &iop, vector<vector<string> > &cmds)\n{\n\ttypedef tokenizer<char_separator<char> > tokenizer;\n\tchar_separator<char> sep(\" \", \"<>|\", drop_empty_tokens);\n\ttokenizer tokens(usrString, sep);\n\tint cnt = 0;\n\tbool first = true;\n\tfor (auto it = tokens.begin(); it != tokens.end(); ++it)\n\t{\n\t\tif(*it == \"|\" || *it == \"<\")\n\t\t{\n\t\t\tfirst = true;\n\t\t\tiop.push_back(*it);\n\t\t\t++cnt;\n\t\t\tcontinue;\n\t\t}\n\t\telse if(*it == \">\")\n\t\t{\n\t\t\tif(iop.empty())\n {\n \tfirst = true;\n \tiop.push_back(*it);\n \t++cnt;\n \tcontinue;\n }\n\n\t\t\telse if (iop.at(iop.size()-1) == \">\")\n\t\t\t{\n\t\t\t\tfirst = true;\n\t\t\t\tiop.at(iop.size()-1).append(\">\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfirst = true;\n\t\t\t\tiop.push_back(*it);\n\t\t\t\t++cnt;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(first)\n\t\t\t{\n\t\t\t\tfirst = false;\n\t\t\t\tvector<string> temp;\n\t\t\t\ttemp.push_back(*it);\n\t\t\t\tcmds.push_back(temp);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcmds.at(cnt).push_back(*it);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t\/\/Print check\n\t\/*\n\tcout << \"cmds: \";\n\tfor (size_t i = 0; i < cmds.size(); ++i)\n\t{\n\t\tfor(size_t j = 0; j < cmds.at(i).size(); ++j)\n\t\t{\n\t\t\tcout << cmds.at(i).at(j) << \" \";\n\t\t}\n\t}\n\tcout << endl;\n\t\n\tcout << \"iop: \";\n\tfor (size_t n = 0; n < iop.size(); ++n)\n\t{\n\t\tcout << iop.at(n) << \" \";\n\t}\n\tcout << endl;\n\t*\/\n\treturn true;\n}\n\n\t\n\/\/Function that parses a passed in string and executes the command it yields\nbool parse_exec(string usrString, int size)\n{\n\tint status;\n\tchar **args = new char*[size+1];\n\tchar *cstr = new char[size+1];\n\tstrcpy(cstr,usrString.c_str());\n\tchar *temp = strtok(cstr, \" &|;#\");\n\tint cnt = 0;\n\n\twhile (temp != 0){\n\t\targs[cnt] = temp;\n\t\t++cnt;\n\t\ttemp = strtok(NULL, \" &|\");\n\t}\n\tif (cnt == 0){\n\t\tdelete[] cstr;\n\t\tdelete[] args;\n\t\treturn false;\n\t}\n\targs[cnt] = NULL;\n\n\tif (!strcmp(args[0],\"exit\")){\n\t\texit(0);\n\t}\n\n\tint pid = fork();\n\tif (pid == -1){\n\t\tperror(\"fork\");\n\t}\n\telse if(pid == 0){\n\t\tif (execvp(args[0],args) == -1){\n\t\t\tperror(\"execvp\");\n\t\t\texit(1);\n\t\t}\n\t}\n\telse if(pid > 0){\n\t\tif(-1 == wait(&status)){\n\t\t\tperror(\"wait\");\n\t\t}\n\t}\n\n\tdelete[] cstr;\n\tdelete[] args;\n\t\n\tif(WEXITSTATUS(status) == 0){\n\t\treturn true;\n\t}\n\telse{\n\t\treturn false;\n\t}\n\treturn false;\n} \n\n\/\/Function checks for connectors and returns a number based on which one is found\n\/\/Pass in a string, a position integer, and a starting point integer\nint check_connect(const string& str, int& pos, int start){\n\tunsigned found = 0;\n\tfound = str.find_first_of(\";&|#\",start);\n\tif (found >= str.size()){\t\/\/If not found...\n\t\tpos = -1;\n\t\treturn -1;\n\t}\n\telse{\n\t\tif (str.at(found) == ';'){\n\t\t\tpos = found;\n\t\t\treturn 1;\n\t\t}\n\t\telse if (str.at(found) == '&'){\n\t\t\tif (str.at(found+1) == '&'){\n\t\t\t\tpos = found;\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn check_connect(str,pos,found+1);\n\t\t\t}\n\t\t}\n\n\t\telse if (str.at(found) == '|'){\n\t\t\tif (str.at(found+1) == '|'){\n\t\t\t\tpos = found;\n\t\t\t\treturn 3;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn 5; \n\t\t\t}\n\t\t}\n\t\telse if (str.at(found) == '#'){\n\t\t\tpos = found;\n\t\t\treturn 4;\n\t\t}\n\t}\n\treturn -1;\n}\n\nvoid my_close(int fd)\n{\n\tif (-1 == close(fd))\n\t{\n\t\tperror(\"close\");\n\t}\n}\nvoid redirect(int oldf, int newf)\n{\n\tif (oldf != newf)\n\t{\n\t\tif (-1 == dup2(oldf,newf))\n\t\t{\n\t\t\tperror(\"dup2\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmy_close(oldf);\n\t\t}\n\t}\n}\n\nvoid execute(vector<string> cmd, int in, int out)\n{\n\tredirect(in, STDIN_FILENO);\n\tredirect(out, STDOUT_FILENO);\n\n\tint n = cmd.size();\n\tint i;\n\tconst char **args = new const char*[ n+1 ];\n\tfor (i = 0; i < n; ++i)\n\t{\n\t\targs[i] = cmd.at(i).c_str();\n\t}\n\targs[i] = NULL;\n\n\texecvp(args[0], (char * const*)args);\n\tperror(\"execvp\");\n\texit(1);\n}\n\nvoid in_redir(vector<string> cmd, string file, int out, int cnt)\n{\n\tmy_close(0);\n\topen(file.c_str(), O_RDWR);\n\tsize_t i;\n\tconst char **args = new const char*[cmd.size()+1];\n\tfor (i = 0; i < cmd.size(); ++i)\n\t{\n\t\targs[i] = cmd.at(i).c_str();\n\t}\n\targs[i] = NULL;\n\tif ( cnt > 0 )\n\t{\n\t\tredirect(out,STDOUT_FILENO);\n\t}\n\tif(-1 == execvp(args[0], (char * const*)args))\n\t{\n\t\tperror(\"execvp\");\n\t\texit(1);\n\t}\n}\n\nvoid out1_redir(vector<string> cmd, string file, int out, int save_out)\n{\n\tint out2;\n\tif (-1 == (out2 = open(file.c_str(), O_WRONLY | O_CREAT | O_TRUNC)))\n\t{\n\t\tperror(\"open\");\n\t\texit(1);\n\t}\n\tsize_t i;\n\tconst char **args = new const char*[cmd.size()+1];\n\tfor (i = 0; i < cmd.size(); ++i)\n\t{\n\t\targs[i] = cmd.at(i).c_str();\n\t}\n\targs[i] = NULL;\n\t\n\tredirect(out2,STDOUT_FILENO);\n\tmy_close(out2);\n\tif (-1 == execvp(args[0], (char * const*)args))\n\t{\n\t\tperror(\"execvp\");\n\t\texit(1);\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main()\n{\n\t\/\/Get User Info\n\tstring hostname;\n\tstring username = getlogin();\n\tif(getlogin() == NULL){\n\t\tperror(\"login\");\n\t\tusername = \"UNKNOWN\";\n\t}\n\tchar host_temp[64];\n\tif(gethostname(host_temp,64) == -1){\n\t\tperror(\"hostname\");\n\t\thostname = \"UNKNOWN\";\n\t}\n\telse{\n\t\thostname = host_temp;\n\t}\n\n\n\twhile(1){\n\t\t\/\/Get User Input\n\t\tbool exec_stat = true;\t\t\/\/Execution Status\n\t\tint con_stat = 0;\t\t\t\/\/Connector Status\n\t\tint pos = 0;\t\t\t\t\/\/Position of Connector\n\t\tint start = 0;\t\t\t\t\/\/Start position for parse function\n\t\tint size = 0;\t\t\t\t\/\/Size of user input\n\t\tstring usrString;\t\t\t\/\/User Input String\n\t\tvector<string> iop;\n\t\tvector<vector<string> > cmds;\n\t\tcout << username << \"@\" << hostname << \"$ \";\n\t\tcin.sync();\n\t\tgetline(cin,usrString); size = usrString.size();\n\t\tif (size == 0){\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (1 == check_input(usrString))\n\t\t{\n\t\t\tiop.clear(); cmds.clear();\n\t\t\tpopv(usrString,iop,cmds);\n\n\t\t\tint pipe_cnt = 0;\n\t\t\tfor (size_t a = 0; a < iop.size(); ++a)\n\t\t\t{\n\t\t\t\tif (iop.at(a) == \"|\")\n\t\t\t\t{\n\t\t\t\t\t++pipe_cnt;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(cmds.empty())\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\/*\tint save_out;\n\t\t\tif (-1 == (save_out = dup(STDOUT_FILENO)))\n\t\t\t{\n\t\t\t\tperror(\"dup\");\n\t\t\t\texit(1);\n\t\t\t} *\/\n\n\t\t\tint save_in;\n\t\t\tif ( -1 == (save_in = dup(STDIN_FILENO)))\n\t\t\t{\n\t\t\t\tperror(\"dup\");\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\tpid_t pid;\n\t\t\tint in = STDIN_FILENO;\n\t\t\tsize_t i = 0;\n\t\t\tint fd[2];\n\n\t\t\tif (iop.at(0) == \"<\")\n\t\t\t{\n\t\t\t\tif (-1 == pipe(fd))\n\t\t\t\t{\n\t\t\t\t\tperror(\"pipe\");\n\t\t\t\t}\n\t\t\t\tif (-1 == (pid = fork()))\n\t\t\t\t{\n\t\t\t\t\tperror(\"fork\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\telse if (pid == 0)\n\t\t\t\t{\n\t\t\t\t\tmy_close(fd[0]);\n\t\t\t\t\tin_redir(cmds.at(0),cmds.at(1).at(0),fd[1],pipe_cnt);\n\t\t\t\t}\n\t\t\t\telse if (pid > 0)\n\t\t\t\t{\n\t\t\t\t\twait(0);\n\t\t\t\t\tmy_close(fd[1]);\n\t\t\t\t\tmy_close(in);\n\t\t\t\t\tin = fd[0];\n\t\t\t\t\ti = 2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((cmds.size() >= 2) && (pipe_cnt > 0))\n\t\t\t{\n\n\t\t\t\tfor (; i < cmds.size()-1; ++i)\n\t\t\t\t{\n\n\t\t\t\t\tif (-1 == pipe(fd))\n\t\t\t\t\t{\n\t\t\t\t\t\tperror(\"pipe\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (-1 == (pid = fork()))\n\t\t\t\t\t{\n\t\t\t\t\t\tperror(\"fork\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (pid == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmy_close(fd[0]);\n\t\t\t\t\t\texecute(cmds.at(i),in,fd[1]);\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (pid >0)\n\t\t\t\t\t{\n\t\t\t\t\t\twait(0);\n\t\t\t\t\t\tmy_close(fd[1]);\n\t\t\t\t\t\tmy_close(in);\n\t\t\t\t\t\tin = fd[0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (-1 == (pid = fork()))\n\t\t\t\t{\n\t\t\t\t\tperror(\"fork\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (pid == 0)\n\t\t\t\t{\n\t\t\t\t\texecute(cmds.at(i),in,STDOUT_FILENO);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\twait(0);\n\t\t\t\tmy_close(in);\n\t\t\t\tin = fd[0];\n\t\t\t\t\/*\n\t\t\t\telse if (iop.at(iop.size()-1) == \">\")\n\t\t\t\t{\n\t\t\t\t\tif (-1 == (pid = fork()))\n\t\t\t\t\t{\n\t\t\t\t\t\tperror(\"fork\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (pid == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmy_close(1);\n\t\t\t\t\t\tsize_t sz = cmds.size();\n\t\t\t\t\t\tout1_redir(cmds.at(sz-2),cmds.at(sz-1).at(0),in,save_out);\n\t\t\t\t\t}\n\t\t\t\t\telse if (pid > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\twait(0);\n\t\t\t\t\t\tmy_close(fd[1]);\n\t\t\t\t\t\tmy_close(in);\n\t\t\t\t\t\tin = fd[0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t*\/\n\t\t\t}\n\t\t\tdup2(save_in,STDIN_FILENO);\n\t\t\/\/\tdup2(save_out,STDOUT_FILENO);\n\t\t\tcontinue;\n\t\t\t\t\n\t\t}\n\n\n\n\n\t\telse\n\t\t{\n\t\t\t\/\/Check Connectors\n\t\t\twhile(1){\n\t\t\t\texec_stat = false;\n\t\t\t\tcon_stat = check_connect(usrString,pos,start);\n\t\t\t\tif (con_stat == -1){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start),size);\n\t\t\t\t\tbreak;\n\t\t\t\t\t\/\/If -1 there are no more connectors in the string so\n\t\t\t\t\t\/\/execute and break for more input\n\t\t\t\t}\n\t\t\t\telse if (con_stat == 1){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start,pos-start), size);\n\t\t\t\t\tstart = pos + 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t\t\/\/Semi-colon encountered so execute and continue with \n\t\t\t\t\t\/\/the rest of command line\n\t\t\t\t}\n\t\t\t\telse if (con_stat == 2){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start,pos-start), size);\n\t\t\t\t\tstart = pos + 2;\n\t\t\t\t\tif (exec_stat == true){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/AND connector encountered so execute and check it's exit status\n\t\t\t\t\t\/\/If success then continue with command line\n\t\t\t\t\t\/\/Else break for more input\n\t\t\t\t}\n\t\t\t\telse if (con_stat == 3){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start,pos-start), size);\n\t\t\t\t\tstart = pos + 2;\n\t\t\t\t\tif (exec_stat == true){\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/OR connector encountered so execute and check it's exit status\n\t\t\t\t\t\/\/If success then break for more input\n\t\t\t\t\t\/\/Else continue with command line\n\t\t\t\t}\n\t\t\t\telse if (con_stat == 4){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start,pos-start), size);\n\t\t\t\t\tbreak;\n\t\t\t\t\t\/\/COMMENT encountered so execute everything before and break\n\t\t\t\t\t\/\/for more input\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\t\n\t\n<commit_msg>fix fd bug<commit_after>#include <string.h>\n#include <fcntl.h>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/tokenizer.hpp>\n#include <stdlib.h>\n#include <iostream>\n#include <unistd.h>\n#include <string>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <stdio.h>\n#include <errno.h>\n#include <vector>\n\nusing namespace boost;\nusing namespace std;\n\nint check_input(string usrString)\n{\n\tif (usrString.find(\"&&\") != string::npos ||\n\t\tusrString.find(\"||\") != string::npos ||\n\t\tusrString.find(\";\") != string::npos ||\n\t\tusrString.find(\"#\") != string::npos ||\n\t\t(usrString.find(\">\") == string::npos &&\n\t\tusrString.find(\"<\") == string::npos &&\n\t\tusrString.find(\"|\") == string::npos))\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\telse\n\t{\n\t\treturn 1;\n\t}\n\treturn -1;\n}\n\nbool popv(string usrString, vector<string> &iop, vector<vector<string> > &cmds)\n{\n\ttypedef tokenizer<char_separator<char> > tokenizer;\n\tchar_separator<char> sep(\" \", \"<>|\", drop_empty_tokens);\n\ttokenizer tokens(usrString, sep);\n\tint cnt = 0;\n\tbool first = true;\n\tfor (auto it = tokens.begin(); it != tokens.end(); ++it)\n\t{\n\t\tif(*it == \"|\" || *it == \"<\")\n\t\t{\n\t\t\tfirst = true;\n\t\t\tiop.push_back(*it);\n\t\t\t++cnt;\n\t\t\tcontinue;\n\t\t}\n\t\telse if(*it == \">\")\n\t\t{\n\t\t\tif(iop.empty())\n {\n \tfirst = true;\n \tiop.push_back(*it);\n \t++cnt;\n \tcontinue;\n }\n\n\t\t\telse if (iop.at(iop.size()-1) == \">\")\n\t\t\t{\n\t\t\t\tfirst = true;\n\t\t\t\tiop.at(iop.size()-1).append(\">\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfirst = true;\n\t\t\t\tiop.push_back(*it);\n\t\t\t\t++cnt;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(first)\n\t\t\t{\n\t\t\t\tfirst = false;\n\t\t\t\tvector<string> temp;\n\t\t\t\ttemp.push_back(*it);\n\t\t\t\tcmds.push_back(temp);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcmds.at(cnt).push_back(*it);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t\/\/Print check\n\t\/*\n\tcout << \"cmds: \";\n\tfor (size_t i = 0; i < cmds.size(); ++i)\n\t{\n\t\tfor(size_t j = 0; j < cmds.at(i).size(); ++j)\n\t\t{\n\t\t\tcout << cmds.at(i).at(j) << \" \";\n\t\t}\n\t}\n\tcout << endl;\n\t\n\tcout << \"iop: \";\n\tfor (size_t n = 0; n < iop.size(); ++n)\n\t{\n\t\tcout << iop.at(n) << \" \";\n\t}\n\tcout << endl;\n\t*\/\n\treturn true;\n}\n\n\t\n\/\/Function that parses a passed in string and executes the command it yields\nbool parse_exec(string usrString, int size)\n{\n\tint status;\n\tchar **args = new char*[size+1];\n\tchar *cstr = new char[size+1];\n\tstrcpy(cstr,usrString.c_str());\n\tchar *temp = strtok(cstr, \" &|;#\");\n\tint cnt = 0;\n\n\twhile (temp != 0){\n\t\targs[cnt] = temp;\n\t\t++cnt;\n\t\ttemp = strtok(NULL, \" &|\");\n\t}\n\tif (cnt == 0){\n\t\tdelete[] cstr;\n\t\tdelete[] args;\n\t\treturn false;\n\t}\n\targs[cnt] = NULL;\n\n\tif (!strcmp(args[0],\"exit\")){\n\t\texit(0);\n\t}\n\n\tint pid = fork();\n\tif (pid == -1){\n\t\tperror(\"fork\");\n\t}\n\telse if(pid == 0){\n\t\tif (execvp(args[0],args) == -1){\n\t\t\tperror(\"execvp\");\n\t\t\texit(1);\n\t\t}\n\t}\n\telse if(pid > 0){\n\t\tif(-1 == wait(&status)){\n\t\t\tperror(\"wait\");\n\t\t}\n\t}\n\n\tdelete[] cstr;\n\tdelete[] args;\n\t\n\tif(WEXITSTATUS(status) == 0){\n\t\treturn true;\n\t}\n\telse{\n\t\treturn false;\n\t}\n\treturn false;\n} \n\n\/\/Function checks for connectors and returns a number based on which one is found\n\/\/Pass in a string, a position integer, and a starting point integer\nint check_connect(const string& str, int& pos, int start){\n\tunsigned found = 0;\n\tfound = str.find_first_of(\";&|#\",start);\n\tif (found >= str.size()){\t\/\/If not found...\n\t\tpos = -1;\n\t\treturn -1;\n\t}\n\telse{\n\t\tif (str.at(found) == ';'){\n\t\t\tpos = found;\n\t\t\treturn 1;\n\t\t}\n\t\telse if (str.at(found) == '&'){\n\t\t\tif (str.at(found+1) == '&'){\n\t\t\t\tpos = found;\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn check_connect(str,pos,found+1);\n\t\t\t}\n\t\t}\n\n\t\telse if (str.at(found) == '|'){\n\t\t\tif (str.at(found+1) == '|'){\n\t\t\t\tpos = found;\n\t\t\t\treturn 3;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn 5; \n\t\t\t}\n\t\t}\n\t\telse if (str.at(found) == '#'){\n\t\t\tpos = found;\n\t\t\treturn 4;\n\t\t}\n\t}\n\treturn -1;\n}\n\nvoid my_close(int fd)\n{\n\tif (-1 == close(fd))\n\t{\n\t\tperror(\"close\");\n\t}\n}\nvoid redirect(int oldf, int newf)\n{\n\tif (oldf != newf)\n\t{\n\t\tif (-1 == dup2(oldf,newf))\n\t\t{\n\t\t\tperror(\"dup2\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmy_close(oldf);\n\t\t}\n\t}\n}\n\nvoid execute(vector<string> cmd, int in, int out)\n{\n\tredirect(in, STDIN_FILENO);\n\tredirect(out, STDOUT_FILENO);\n\n\tint n = cmd.size();\n\tint i;\n\tconst char **args = new const char*[ n+1 ];\n\tfor (i = 0; i < n; ++i)\n\t{\n\t\targs[i] = cmd.at(i).c_str();\n\t}\n\targs[i] = NULL;\n\n\texecvp(args[0], (char * const*)args);\n\tperror(\"execvp\");\n\texit(1);\n}\n\nvoid in_redir(vector<string> cmd, string file, int out, int cnt)\n{\n\tmy_close(0);\n\topen(file.c_str(), O_RDWR);\n\tsize_t i;\n\tconst char **args = new const char*[cmd.size()+1];\n\tfor (i = 0; i < cmd.size(); ++i)\n\t{\n\t\targs[i] = cmd.at(i).c_str();\n\t}\n\targs[i] = NULL;\n\tif ( cnt > 0 )\n\t{\n\t\tredirect(out,STDOUT_FILENO);\n\t}\n\tif(-1 == execvp(args[0], (char * const*)args))\n\t{\n\t\tperror(\"execvp\");\n\t\texit(1);\n\t}\n}\n\nvoid out1_redir(vector<string> cmd, string file, int out, int save_out)\n{\n\tint out2;\n\tif (-1 == (out2 = open(file.c_str(), O_WRONLY | O_CREAT | O_TRUNC)))\n\t{\n\t\tperror(\"open\");\n\t\texit(1);\n\t}\n\tsize_t i;\n\tconst char **args = new const char*[cmd.size()+1];\n\tfor (i = 0; i < cmd.size(); ++i)\n\t{\n\t\targs[i] = cmd.at(i).c_str();\n\t}\n\targs[i] = NULL;\n\t\n\tredirect(out2,STDOUT_FILENO);\n\tmy_close(out2);\n\tif (-1 == execvp(args[0], (char * const*)args))\n\t{\n\t\tperror(\"execvp\");\n\t\texit(1);\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main()\n{\n\t\/\/Get User Info\n\tstring hostname;\n\tstring username = getlogin();\n\tif(getlogin() == NULL){\n\t\tperror(\"login\");\n\t\tusername = \"UNKNOWN\";\n\t}\n\tchar host_temp[64];\n\tif(gethostname(host_temp,64) == -1){\n\t\tperror(\"hostname\");\n\t\thostname = \"UNKNOWN\";\n\t}\n\telse{\n\t\thostname = host_temp;\n\t}\n\n\n\twhile(1){\n\t\t\/\/Get User Input\n\t\tbool exec_stat = true;\t\t\/\/Execution Status\n\t\tint con_stat = 0;\t\t\t\/\/Connector Status\n\t\tint pos = 0;\t\t\t\t\/\/Position of Connector\n\t\tint start = 0;\t\t\t\t\/\/Start position for parse function\n\t\tint size = 0;\t\t\t\t\/\/Size of user input\n\t\tstring usrString;\t\t\t\/\/User Input String\n\t\tvector<string> iop;\n\t\tvector<vector<string> > cmds;\n\t\tcout << username << \"@\" << hostname << \"$ \";\n\t\tcin.sync();\n\t\tgetline(cin,usrString); size = usrString.size();\n\t\tif (size == 0){\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (1 == check_input(usrString))\n\t\t{\n\t\t\tiop.clear(); cmds.clear();\n\t\t\tpopv(usrString,iop,cmds);\n\n\t\t\tint pipe_cnt = 0;\n\t\t\tfor (size_t a = 0; a < iop.size(); ++a)\n\t\t\t{\n\t\t\t\tif (iop.at(a) == \"|\")\n\t\t\t\t{\n\t\t\t\t\t++pipe_cnt;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(cmds.empty())\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/*int save_out;\n\t\t\tif (-1 == (save_out = dup(STDOUT_FILENO)))\n\t\t\t{\n\t\t\t\tperror(\"dup\");\n\t\t\t\texit(1);\n\t\t\t} *\/ \n\n\t\t\tint save_in;\n\t\t\tif ( -1 == (save_in = dup(STDIN_FILENO)))\n\t\t\t{\n\t\t\t\tperror(\"dup\");\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\tpid_t pid;\n\t\t\tint in = STDIN_FILENO;\n\t\t\tsize_t i = 0;\n\t\t\tint fd[2];\n\n\t\t\tif (iop.at(0) == \"<\")\n\t\t\t{\n\t\t\t\tif (-1 == pipe(fd))\n\t\t\t\t{\n\t\t\t\t\tperror(\"pipe\");\n\t\t\t\t}\n\t\t\t\tcout << \"fd[0] \" << fd[0] << endl;\n\t\t\t\tcout << \"fd[1] \" << fd[1] << endl;\n\t\t\t\tif (-1 == (pid = fork()))\n\t\t\t\t{\n\t\t\t\t\tperror(\"fork\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\telse if (pid == 0)\n\t\t\t\t{\n\t\t\t\t\tmy_close(fd[0]);\n\t\t\t\t\tin_redir(cmds.at(0),cmds.at(1).at(0),fd[1],pipe_cnt);\n\t\t\t\t}\n\t\t\t\telse if (pid > 0)\n\t\t\t\t{\n\t\t\t\t\twait(0);\n\t\t\t\t\tmy_close(fd[1]);\n\t\t\t\t\tmy_close(in);\n\t\t\t\t\tin = fd[0];\n\t\t\t\t\ti = 2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((cmds.size() >= 2) && (pipe_cnt > 0))\n\t\t\t{\n\n\t\t\t\tfor (; i < cmds.size()-1; ++i)\n\t\t\t\t{\n\n\t\t\t\t\tif (-1 == pipe(fd))\n\t\t\t\t\t{\n\t\t\t\t\t\tperror(\"pipe\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (-1 == (pid = fork()))\n\t\t\t\t\t{\n\t\t\t\t\t\tperror(\"fork\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (pid == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmy_close(fd[0]);\n\t\t\t\t\t\texecute(cmds.at(i),in,fd[1]);\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (pid >0)\n\t\t\t\t\t{\n\t\t\t\t\t\twait(0);\n\t\t\t\t\t\tmy_close(fd[1]);\n\t\t\t\t\t\tmy_close(in);\n\t\t\t\t\t\tin = fd[0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (-1 == (pid = fork()))\n\t\t\t\t{\n\t\t\t\t\tperror(\"fork\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (pid == 0)\n\t\t\t\t{\n\t\t\t\t\texecute(cmds.at(i),in,STDOUT_FILENO);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\telse if (pid > 0)\n\t\t\t\t{\n\t\t\t\t\twait(0);\n\t\t\t\t\tmy_close(in);\n\t\t\t\t\tin = fd[0];\n\t\t\t\t\tcout << \"fd[0]: \" << fd[0] << endl;\n\t\t\t\t\tcout << \"fd[1]: \" << fd[1] << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdup2(save_in,STDIN_FILENO);\n\t\t\tmy_close(save_in);\n\t\t\t\/\/dup2(save_out,fd[1]);\n\t\t\tcontinue;\n\t\t\t\t\n\t\t}\n\n\n\n\n\t\telse\n\t\t{\n\t\t\t\/\/Check Connectors\n\t\t\twhile(1){\n\t\t\t\texec_stat = false;\n\t\t\t\tcon_stat = check_connect(usrString,pos,start);\n\t\t\t\tif (con_stat == -1){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start),size);\n\t\t\t\t\tbreak;\n\t\t\t\t\t\/\/If -1 there are no more connectors in the string so\n\t\t\t\t\t\/\/execute and break for more input\n\t\t\t\t}\n\t\t\t\telse if (con_stat == 1){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start,pos-start), size);\n\t\t\t\t\tstart = pos + 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t\t\/\/Semi-colon encountered so execute and continue with \n\t\t\t\t\t\/\/the rest of command line\n\t\t\t\t}\n\t\t\t\telse if (con_stat == 2){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start,pos-start), size);\n\t\t\t\t\tstart = pos + 2;\n\t\t\t\t\tif (exec_stat == true){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/AND connector encountered so execute and check it's exit status\n\t\t\t\t\t\/\/If success then continue with command line\n\t\t\t\t\t\/\/Else break for more input\n\t\t\t\t}\n\t\t\t\telse if (con_stat == 3){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start,pos-start), size);\n\t\t\t\t\tstart = pos + 2;\n\t\t\t\t\tif (exec_stat == true){\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/OR connector encountered so execute and check it's exit status\n\t\t\t\t\t\/\/If success then break for more input\n\t\t\t\t\t\/\/Else continue with command line\n\t\t\t\t}\n\t\t\t\telse if (con_stat == 4){\n\t\t\t\t\texec_stat = parse_exec(usrString.substr(start,pos-start), size);\n\t\t\t\t\tbreak;\n\t\t\t\t\t\/\/COMMENT encountered so execute everything before and break\n\t\t\t\t\t\/\/for more input\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\t\n\t\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <vector>\n#include \"LogEntryFilter.h\"\n#include \"LogEntryRootFilter.h\"\n#include \"LogEntryMessageFilter.h\"\n#include \"LogEntryTimeFilter.h\"\n#include \"FileUtils.hpp\"\n#include \"CommandLineUtils.hpp\"\n#include \"LogEntryParser.h\"\n#include \"Rearranger.h\"\n#include \"LogEntryFilterFactory.h\"\n#include \"alphanum.hpp\"\n\nusing namespace std;\n\nvoid sortFiles(vector<string> &files);\n\nint main(int argc, char *argv[]) {\n int ret = 0;\n if (argc == 1 || cmdOptionExists(argv, argv + argc, \"--help\")) {\n cout << \"LogUtil: A handy tool to merge\/filter log files.\\n\";\n cout << \"usage :\\tlogutil\";\n cout << \"\\t[-d] [-f] [-o] [-r] [-start] [-end]\\n\";\n cout << \"\\n\";\n cout << \"\\t-d merge all files under the directory.\\n\";\n cout << \"\\t-f sort the log file.\\n\";\n cout << \"\\t-o output file. [<file_or_dirname>_ALL.log] will be used if not set.\\n\";\n cout << \"\\t-r filter rules.\\n\";\n cout << \"\\t-start\/end show logs between [start , end), \\\"YYYY-mm-dd hh:MM:SS.SSS\\\" .\\n\\n\";\n cout << \"examples :\\n\";\n cout << \"\\tlogutil -d ~\/LogDir\\n\";\n cout << \"\\tlogutil -d ~\/LogDir -start 2016-06-18\\n\";\n cout << \"\\tlogutil -d ~\/LogDir -start 2016-06-18 -end 2016-06-19\\n\";\n cout << \"\\tlogutil -d ~\/LogDir -f ~\/block_rules.json\\n\";\n cout << \"\\tlogutil -d ~\/LogDir -o ~\/Log_ALL.log\\n\";\n cout << \"\\tlogutil -f ~\/LogDir\/log.log -o ~\/Log_ALL.log\\n\";\n return 0;\n }\n vector<string> files;\n char *dirname = nullptr, *filename = nullptr, *outputFilename = nullptr;\n\n if (argc == 2) {\n if (isFile(argv[1])) {\n filename = argv[1];\n } else {\n dirname = argv[1];\n }\n } else {\n dirname = getCmdOption(argv, argv + argc, \"-d\");\n filename = getCmdOption(argv, argv + argc, \"-f\");\n }\n\n if (filename) {\n files.push_back(filename);\n }\n\n if (dirname) {\n ret = listFiles(dirname, files);\n sortFiles(files);\n }\n\n if (ret != 0) {\n return ret;\n }\n\n char *filterRultFile = getCmdOption(argv, argv + argc, \"-r\");\n char *startTime = getCmdOption(argv, argv + argc, \"-start\");\n char *endTime = getCmdOption(argv, argv + argc, \"-end\");\n\n outputFilename = getCmdOption(argv, argv + argc, \"-o\");\n if (!outputFilename) {\n if (filename) {\n string folderName, filenameWoDir;\n splitFilename(string(filename), folderName, filenameWoDir);\n\n string newFilename(folderName + \"\/All_\" + filenameWoDir);\n outputFilename = new char[newFilename.length() + 1];\n strcpy(outputFilename, newFilename.c_str());\n } else if (dirname) {\n string newFilename(string(dirname) + \"\/\" + \"All.log\");\n outputFilename = new char[newFilename.length() + 1];\n strcpy(outputFilename, newFilename.c_str());\n }\n }\n\n LogEntryFilterFactory::registerCreator(\"root\", LogEntryRootFilter::creator);\n LogEntryFilterFactory::registerCreator(\"log\", LogEntryMessageFilter::creator);\n LogEntryFilterFactory::registerCreator(\"time\", LogEntryTimeFilter::creator);\n\n LogEntryParser parser;\n\n if (filterRultFile) {\n auto fileRuleStream = fstream(filterRultFile);\n json fileRuleJson;\n fileRuleStream >> fileRuleJson;\n parser.addFilter(LogEntryFilterFactory::create(fileRuleJson));\n }\n\n if (startTime || endTime) {\n string start = startTime ? (string) startTime : \"\";\n string end = endTime ? (string) endTime : \"\";\n LogEntryTimeFilter *filter = new LogEntryTimeFilter(\n LogEntryTimeFilter::getDate(start),\n LogEntryTimeFilter::getTime(start),\n LogEntryTimeFilter::getDate(end),\n LogEntryTimeFilter::getTime(end),\n true);\n parser.addFilter(filter);\n }\n\n vector<LogEntry *> entries;\n\n for (string file : files) {\n try {\n parser.parseFile(file, entries);\n } catch (runtime_error &error) {\n cerr << \"Failed to parse file : \" << file << \". error: \" << error.what() << endl;\n } catch (...) {\n cerr << \"Failed to parse file : \" << file << endl;\n }\n }\n\n Rearranger rearranger;\n rearranger.sort(entries);\n\n int index = 1;\n for (LogEntry *entry : entries) {\n entry->line.orderedIndex = index;\n index += entry->line.lines.size();\n }\n\n if (outputFilename) {\n ofstream os(outputFilename);\n for (LogEntry *entry : entries) {\n os << *entry;\n }\n } else {\n for (LogEntry *entry : entries) {\n cout << *entry;\n }\n }\n\n return 0;\n}\n\nvoid sortFiles(vector<string> &files) {\n \/*\n * A little tricky here: files must be sorted in natural order on filename.\n * Or output result might be mis-ordered on log entries with same timestamp but stored in separate files.\n *\n * For example.\n *\n * We'ev two logs files:\n *\n * 9.log ([2000-1-1 00:00:00,000] A)\n * 10.log ([2000-1-1 00:00:00,000] B)\n *\n * log [A] is printed before log [B] but both in the same time [2000-1-1 00:00:00,000].\n *\n * After sorting by ascii comparing on filename:\n * 10.log\n * 9.log\n *\n * Then we first parse [B] from 10.log and then [A] from 9.log:\n *\n * [2000-1-1 00:00:00,000] B\n * [2000-1-1 00:00:00,000] A\n *\n * So the sorting order of files must be the same as generating.\n *\n *\/\n sort(files.begin(), files.end(), [](string &lhs, string &rhs) {\n return doj::alphanum_comp(lhs, rhs) < 0;\n });\n}<commit_msg>- : bug<commit_after>#include <fstream>\n#include <vector>\n#include \"LogEntryFilter.h\"\n#include \"LogEntryRootFilter.h\"\n#include \"LogEntryMessageFilter.h\"\n#include \"LogEntryTimeFilter.h\"\n#include \"FileUtils.hpp\"\n#include \"CommandLineUtils.hpp\"\n#include \"LogEntryParser.h\"\n#include \"Rearranger.h\"\n#include \"LogEntryFilterFactory.h\"\n#include \"alphanum.hpp\"\n\nusing namespace std;\n\nvoid sortFiles(vector<string> &files);\n\nint main(int argc, char *argv[]) {\n int ret = 0;\n if (argc == 1 || cmdOptionExists(argv, argv + argc, \"--help\")) {\n cout << \"LogUtil: A handy tool to merge\/filter log files.\\n\";\n cout << \"usage :\\tlogutil\";\n cout << \"\\t[-d] [-f] [-o] [-r] [-start] [-end]\\n\";\n cout << \"\\n\";\n cout << \"\\t-d merge all files under the directory.\\n\";\n cout << \"\\t-f sort the log file.\\n\";\n cout << \"\\t-o output file. [<file_or_dirname>_ALL.log] will be used if not set.\\n\";\n cout << \"\\t-r filter rules.\\n\";\n cout << \"\\t-start\/end show logs between [start , end), \\\"YYYY-mm-dd hh:MM:SS.SSS\\\" .\\n\\n\";\n cout << \"examples :\\n\";\n cout << \"\\tlogutil -d ~\/LogDir\\n\";\n cout << \"\\tlogutil -d ~\/LogDir -start 2016-06-18\\n\";\n cout << \"\\tlogutil -d ~\/LogDir -start 2016-06-18 -end 2016-06-19\\n\";\n cout << \"\\tlogutil -d ~\/LogDir -r ~\/block_rules.json\\n\";\n cout << \"\\tlogutil -d ~\/LogDir -o ~\/Log_ALL.log\\n\";\n cout << \"\\tlogutil -f ~\/LogDir\/log.log -o ~\/Log_ALL.log\\n\";\n return 0;\n }\n vector<string> files;\n char *dirname = nullptr, *filename = nullptr, *outputFilename = nullptr;\n\n if (argc == 2) {\n if (isFile(argv[1])) {\n filename = argv[1];\n } else {\n dirname = argv[1];\n }\n } else {\n dirname = getCmdOption(argv, argv + argc, \"-d\");\n filename = getCmdOption(argv, argv + argc, \"-f\");\n }\n\n if (filename) {\n files.push_back(filename);\n }\n\n if (dirname) {\n ret = listFiles(dirname, files);\n sortFiles(files);\n }\n\n if (ret != 0) {\n return ret;\n }\n\n char *filterRultFile = getCmdOption(argv, argv + argc, \"-r\");\n char *startTime = getCmdOption(argv, argv + argc, \"-start\");\n char *endTime = getCmdOption(argv, argv + argc, \"-end\");\n\n outputFilename = getCmdOption(argv, argv + argc, \"-o\");\n if (!outputFilename) {\n if (filename) {\n string folderName, filenameWoDir;\n splitFilename(string(filename), folderName, filenameWoDir);\n\n string newFilename(folderName + \"\/All_\" + filenameWoDir);\n outputFilename = new char[newFilename.length() + 1];\n strcpy(outputFilename, newFilename.c_str());\n } else if (dirname) {\n string newFilename(string(dirname) + \"\/\" + \"All.log\");\n outputFilename = new char[newFilename.length() + 1];\n strcpy(outputFilename, newFilename.c_str());\n }\n }\n\n LogEntryFilterFactory::registerCreator(\"root\", LogEntryRootFilter::creator);\n LogEntryFilterFactory::registerCreator(\"log\", LogEntryMessageFilter::creator);\n LogEntryFilterFactory::registerCreator(\"time\", LogEntryTimeFilter::creator);\n\n LogEntryParser parser;\n\n if (filterRultFile) {\n auto fileRuleStream = fstream(filterRultFile);\n json fileRuleJson;\n fileRuleStream >> fileRuleJson;\n parser.addFilter(LogEntryFilterFactory::create(fileRuleJson));\n }\n\n if (startTime || endTime) {\n string start = startTime ? (string) startTime : \"\";\n string end = endTime ? (string) endTime : \"\";\n LogEntryTimeFilter *filter = new LogEntryTimeFilter(\n LogEntryTimeFilter::getDate(start),\n LogEntryTimeFilter::getTime(start),\n LogEntryTimeFilter::getDate(end),\n LogEntryTimeFilter::getTime(end),\n true);\n parser.addFilter(filter);\n }\n\n vector<LogEntry *> entries;\n\n for (string file : files) {\n try {\n parser.parseFile(file, entries);\n } catch (runtime_error &error) {\n cerr << \"Failed to parse file : \" << file << \". error: \" << error.what() << endl;\n } catch (...) {\n cerr << \"Failed to parse file : \" << file << endl;\n }\n }\n\n Rearranger rearranger;\n rearranger.sort(entries);\n\n int index = 1;\n for (LogEntry *entry : entries) {\n entry->line.orderedIndex = index;\n index += entry->line.lines.size();\n }\n\n if (outputFilename) {\n ofstream os(outputFilename);\n for (LogEntry *entry : entries) {\n os << *entry;\n }\n } else {\n for (LogEntry *entry : entries) {\n cout << *entry;\n }\n }\n\n return 0;\n}\n\nvoid sortFiles(vector<string> &files) {\n \/*\n * A little tricky here: files must be sorted in natural order on filename.\n * Or output result might be mis-ordered on log entries with same timestamp but stored in separate files.\n *\n * For example.\n *\n * We'ev two logs files:\n *\n * 9.log ([2000-1-1 00:00:00,000] A)\n * 10.log ([2000-1-1 00:00:00,000] B)\n *\n * log [A] is printed before log [B] but both in the same time [2000-1-1 00:00:00,000].\n *\n * After sorting by ascii comparing on filename:\n * 10.log\n * 9.log\n *\n * Then we first parse [B] from 10.log and then [A] from 9.log:\n *\n * [2000-1-1 00:00:00,000] B\n * [2000-1-1 00:00:00,000] A\n *\n * So the sorting order of files must be the same as generating.\n *\n *\/\n sort(files.begin(), files.end(), [](string &lhs, string &rhs) {\n return doj::alphanum_comp(lhs, rhs) < 0;\n });\n}<|endoftext|>"} {"text":"<commit_before>\/*!\n * @file main.cpp\n *\n * @brief FGAP entry point\n *\n * @author Andrey Shelest\n * @author Oleksii Aliakin (alex@nls.la)\n * @date Created Jan 04, 2015\n * @date Modified Sep 05, 2015\n *\/\n\n#include \"log.h\"\n#include \"FgAircraftsModel.h\"\n#include \"utils\/Filesystem.h\"\n\n#include <QtQml>\n#include <QTextCodec>\n#include <QApplication>\n\nint main(int argc, char *argv[])\n{\n#ifdef FGAP_PLUGINS_PATH\n \/\/ Add path to search for Qt plugins\n QString pluginsPaths = fgap::path::join(\n QFileInfo(argv[0]).dir().path(),\n FGAP_PLUGINS_PATH);\n QCoreApplication::addLibraryPath(pluginsPaths);\n#endif\n\n QApplication app(argc, argv);\n qInstallMessageHandler(logMessageHandler);\n\n \/\/ Set up settings\n app.setOrganizationName(\"FlightgearAutopilot\");\n app.setApplicationName(\"Flightgear_autopilot\");\n QSettings::setDefaultFormat(QSettings::IniFormat);\n\n { \/\/ Copy default setting if settings file does not exist\n QSettings settings;\n QDir settingsDir = QFileInfo(settings.fileName()).absoluteDir();\n if (!settingsDir.exists())\n if (!settingsDir.mkpath(settingsDir.absolutePath()))\n qDebug() << \"Could not create settings directory \" << settingsDir.absolutePath();\n if (!QFile::exists(settings.fileName()))\n {\n QString configFileName(fgap::path::join(QCoreApplication::applicationDirPath(),\n CONFIG_PATH,\n \"example_multiplayWithoutServer.ini\"));\n qDebug() << \"Copying \"<< configFileName << \" settings to \" << settings.fileName();\n if (!QFile::copy(configFileName, settings.fileName()))\n qWarning() << \"Could not copy default settings to \" << settings.fileName();\n }\n }\n\n \/\/ Setup QML\n qmlRegisterType<FgAircraftsModel>(\"fgap\", 1, 0, \"FgAircraftsModel\");\n QQmlApplicationEngine engine;\n QString qmlFilesPath = fgap::path::join(\n QCoreApplication::applicationDirPath(),\n FGAP_QML_MODULES_PATH);\n qDebug() << \"qmlFilesPath = \" << qmlFilesPath;\n engine.addImportPath(qmlFilesPath);\n engine.load(QUrl(QStringLiteral(\"qrc:qml\/MainView.qml\")));\n\n return app.exec();\n}\n<commit_msg>Properly hanlde QML errors.<commit_after>\/*!\n * @file main.cpp\n *\n * @brief FGAP entry point\n *\n * @author Andrey Shelest\n * @author Oleksii Aliakin (alex@nls.la)\n * @date Created Jan 04, 2015\n * @date Modified Oct 21, 2015\n *\/\n\n#include \"log.h\"\n#include \"FgAircraftsModel.h\"\n#include \"utils\/Filesystem.h\"\n\n#include <QtQml>\n#include <QTextCodec>\n#include <QMessageBox>\n#include <QApplication>\n\nint main(int argc, char *argv[])\n{\n#ifdef FGAP_PLUGINS_PATH\n \/\/ Add path to search for Qt plugins\n QString pluginsPaths = fgap::path::join(\n QFileInfo(argv[0]).dir().path(),\n FGAP_PLUGINS_PATH);\n QCoreApplication::addLibraryPath(pluginsPaths);\n#endif\n\n QApplication app(argc, argv);\n qInstallMessageHandler(logMessageHandler);\n\n \/\/ Set up settings\n app.setOrganizationName(\"FlightgearAutopilot\");\n app.setApplicationName(\"Flightgear_autopilot\");\n QSettings::setDefaultFormat(QSettings::IniFormat);\n\n { \/\/ Copy default setting if settings file does not exist\n QSettings settings;\n QDir settingsDir = QFileInfo(settings.fileName()).absoluteDir();\n if (!settingsDir.exists())\n if (!settingsDir.mkpath(settingsDir.absolutePath()))\n qDebug() << \"Could not create settings directory \" << settingsDir.absolutePath();\n if (!QFile::exists(settings.fileName()))\n {\n QString configFileName(fgap::path::join(QCoreApplication::applicationDirPath(),\n CONFIG_PATH,\n \"example_multiplayWithoutServer.ini\"));\n qDebug() << \"Copying \"<< configFileName << \" settings to \" << settings.fileName();\n if (!QFile::copy(configFileName, settings.fileName()))\n qWarning() << \"Could not copy default settings to \" << settings.fileName();\n }\n }\n\n \/\/ Setup QML\n bool success = true;\n qmlRegisterType<FgAircraftsModel>(\"fgap\", 1, 0, \"FgAircraftsModel\");\n QQmlApplicationEngine engine;\n QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, [&app, &success](QObject *object, const QUrl &url){\n if (!object)\n {\n qWarning() << \"Could not load QML\";\n QMessageBox::critical(nullptr, \"Flightgear autopilot\",\n \"<b>Flightgear autopilot<\/b> is failed to start due to errors in the main QML file.\\n\"\n \"Please report the error following this link: \"\n \"<a href='https:\/\/github.com\/approximator\/FlightGear_Autopilot\/issues\/new'>\"\n \"https:\/\/github.com\/approximator\/FlightGear_Autopilot\/issues\/new<\/a>\");\n success = false;\n }\n else\n qDebug() << \"QML object created successfully: \" << url;\n });\n\n QString qmlFilesPath = fgap::path::join(\n QCoreApplication::applicationDirPath(),\n FGAP_QML_MODULES_PATH);\n qDebug() << \"qmlFilesPath = \" << qmlFilesPath;\n engine.addImportPath(qmlFilesPath);\n engine.load(QUrl(QStringLiteral(\"qrc:qml\/MainView.qml\")));\n\n return success ? app.exec() : 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <signal.h>\n#include <cv.h>\n#include <highgui.h>\n#include <iostream>\n#include <cstdlib>\n#include <list>\n\n#include <gflags\/gflags.h>\n\nusing namespace std;\nusing namespace cv;\n\nDEFINE_bool(display, true, \"Display video in window.\");\nDEFINE_bool(quiet, false, \"Suppress terminal output.\");\nDEFINE_string(save, \"\", \"Save output to file.\");\nDEFINE_string(axis, \"y\", \"Axis of rotation.\");\nDEFINE_double(fps, 24, \"Frame per second for output.\");\nDEFINE_bool(live, false, \"Use live feed.\");\nDEFINE_int32(postrotate, 0, \"Rotation of final frames to fix flipped source video.\\n\"\n \"\\t0\\tNo rotation\\n\"\n \"\\t1\\t90 degrees clockwise\\n\"\n \"\\t2\\t90 degrees counter-clockwise\\n\"\n \"\\t3\\t180 degrees\\n\"\n );\n\nenum postrotate_enum {\n ROT_NONE,\n ROT_90CW,\n ROT_90CCW,\n ROT_180\n};\n\nenum axis_enum {\n AXIS_X,\n AXIS_Y,\n AXIS_T\n};\n\ntypedef struct options_struct {\n enum axis_enum axis;\n Size size;\n int frame_count;\n VideoCapture *video_src;\n VideoWriter *video_dst;\n bool live;\n enum postrotate_enum postrotate;\n} options_type;\n\nint video_file_filter(options_type *o, char *window_name);\nint video_live_filter(options_type *o, char *window_name);\n\noptions_type * create_options(int *argc, char ***argv) {\n google::ParseCommandLineFlags(argc, argv, true);\n options_type *o = (options_type *) calloc(1, sizeof(options_type));\n \n if (FLAGS_live && *argc == 1) {\n o->live = true;\n } else if (*argc != 2) {\n o->live = false;\n cout << \"usage: \" << *argv[0] << \" input-video\" << endl;\n free(o);\n return NULL;\n }\n\n \/\/ Prerotation?\n o->postrotate = (enum postrotate_enum)FLAGS_postrotate;\n\n \/\/ open input video\n if (o->live) {\n o->video_src = new VideoCapture(0);\n } else {\n string input_file = (*argv)[(*argc) - 1];\n o->video_src = new VideoCapture(input_file);\n }\n if(!o->video_src->isOpened()) return NULL;\n\n \/\/ get axis\n if (FLAGS_axis == \"x\") {\n o->axis = AXIS_X;\n } else if (FLAGS_axis == \"y\") {\n o->axis = AXIS_Y;\n } else if (FLAGS_axis == \"t\") {\n o->axis = AXIS_T;\n } else {\n free(o);\n return NULL;\n }\n\n \/\/ get size of output video\n int width = o->video_src->get(CV_CAP_PROP_FRAME_WIDTH);\n int height = o->video_src->get(CV_CAP_PROP_FRAME_HEIGHT);\n int frame_count = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);\n if (o->live) {\n o->size = Size(width, height);\n o->frame_count = FLAGS_axis == \"x\" ? height : width;\n } else if (FLAGS_axis == \"x\") {\n o->size = Size(width, frame_count);\n o->frame_count = height;\n } else if (FLAGS_axis == \"y\") {\n o->size = Size(frame_count, height);\n o->frame_count = width;\n } else {\n free(o);\n return NULL;\n }\n\n \/\/ get output video\n if (!FLAGS_save.empty()) {\n o->video_dst = new VideoWriter;\n int ex = CV_FOURCC('I', 'Y', 'U', 'V');\n if (o->postrotate == ROT_NONE || o->postrotate == ROT_180) {\n o->video_dst->open(FLAGS_save, ex, FLAGS_fps, o->size);\n } else {\n o->video_dst->open(FLAGS_save, ex, FLAGS_fps, Size(o->size.height, o->size.width));\n }\n }\n\n return o;\n\n}\n\nint main(int argc, char **argv) {\n signal(SIGINT, SIG_IGN); \n\n google::SetUsageMessage(\"Rotate video in time.\");\n\n options_type *o = create_options(&argc, &argv);\n if (o == NULL)\n return -1;\n\n if (FLAGS_display) {\n namedWindow(argv[0],CV_WINDOW_NORMAL);\n setWindowProperty(argv[0], CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);\n }\n\n if (o->live)\n video_live_filter(o, argv[0]);\n else\n video_file_filter(o, argv[0]);\n\n delete o->video_src;\n delete o->video_dst;\n free(o);\n\n return 0;\n}\n\nint video_live_filter(options_type *o, char *window_name) {\n Mat frame_in;\n *(o->video_src) >> frame_in;\n Mat frame_out(o->size, frame_in.type());\n\n list<Mat> frame_list;\n for (int i = 0; i < o->frame_count; i++) {\n cout << \"Frame \" << i+1 << \" of \" << o->frame_count << endl;\n if (waitKey(1) == '\u001b')\n return 0;\n *(o->video_src) >> frame_in;\n frame_list.push_back(frame_in.clone());\n }\n\n int j = 0;\n int d = 1;\n for (;;) {\n int i = 0;\n for (list<Mat>::iterator it = frame_list.begin(); it != frame_list.end(); it++) {\n switch (o->axis) {\n case AXIS_X:\n it->row(j).copyTo(frame_out.row(i));\n break;\n case AXIS_Y:\n it->col(j).copyTo(frame_out.col(i));\n break;\n default:\n cout << \"UNIMPLEMENTED\" << endl;\n return -1;\n }\n i++;\n }\n if (j == o->frame_count - 1) {\n d = -1;\n } else if (j == 0) {\n d = 1;\n }\n j += d;\n\n\n imshow(window_name, frame_out);\n if (waitKey(1) == '\u001b')\n return 0;\n\n *(o->video_src) >> frame_in;\n frame_list.push_back(frame_in.clone());\n frame_list.pop_front();\n }\n\n}\n\nint video_file_filter(options_type *o, char *window_name) {\n Mat frame_in;\n *(o->video_src) >> frame_in;\n Mat frame_out(o->size, frame_in.type());\n\n int frame_count_src = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);\n for (int j = 0; j < o->frame_count; j++) {\n\n \/\/ Output status to console\n if (!FLAGS_quiet)\n cout << \"Frame \" << j+1 << \" of \" << o->frame_count << \".\" << endl;\n\n \/\/ Create a new frame.\n o->video_src->set(CV_CAP_PROP_POS_FRAMES, 0);\n for (int i = 0; i < frame_count_src; i++) {\n *(o->video_src) >> frame_in;\n switch (o->axis) {\n case AXIS_X:\n frame_in.row(j).copyTo(frame_out.row(i));\n break;\n case AXIS_Y:\n frame_in.col(j).copyTo(frame_out.col(i));\n break;\n default:\n cout << \"UNIMPLEMENTED\" << endl;\n return -1;\n }\n }\n\n\n \/\/ Do any postrotation required before finishing frame.\n Mat f;\n if (o->postrotate == ROT_90CW) {\n transpose(frame_out, f);\n flip(f, f, 1);\n } else if (o->postrotate == ROT_90CCW) {\n transpose(frame_out, f);\n flip(f, f, 0);\n } else if (o->postrotate == ROT_180) {\n flip(frame_out, f, -1);\n } else {\n f = frame_out;\n }\n \n \/\/ Display window\n if (FLAGS_display) {\n imshow(window_name, f);\n if (waitKey(1) == '\u001b')\n return 0;\n }\n\n \/\/ Save frame to file\n if (!FLAGS_save.empty())\n o->video_dst->write(f);\n\n }\n}\n<commit_msg>Added more detailed output about progress<commit_after>#include <signal.h>\n#include <cv.h>\n#include <highgui.h>\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <list>\n\n#include <gflags\/gflags.h>\n\nusing namespace std;\nusing namespace cv;\n\nDEFINE_bool(display, true, \"Display video in window.\");\nDEFINE_bool(quiet, false, \"Suppress terminal output.\");\nDEFINE_string(save, \"\", \"Save output to file.\");\nDEFINE_string(axis, \"y\", \"Axis of rotation.\");\nDEFINE_double(fps, 24, \"Frame per second for output.\");\nDEFINE_bool(live, false, \"Use live feed.\");\nDEFINE_int32(postrotate, 0, \"Rotation of final frames to fix flipped source video.\\n\"\n \"\\t0\\tNo rotation\\n\"\n \"\\t1\\t90 degrees clockwise\\n\"\n \"\\t2\\t90 degrees counter-clockwise\\n\"\n \"\\t3\\t180 degrees\\n\"\n );\n\nenum postrotate_enum {\n ROT_NONE,\n ROT_90CW,\n ROT_90CCW,\n ROT_180\n};\n\nenum axis_enum {\n AXIS_X,\n AXIS_Y,\n AXIS_T\n};\n\ntypedef struct options_struct {\n enum axis_enum axis;\n Size size;\n int frame_count;\n VideoCapture *video_src;\n VideoWriter *video_dst;\n bool live;\n enum postrotate_enum postrotate;\n} options_type;\n\nint video_file_filter(options_type *o, char *window_name);\nint video_live_filter(options_type *o, char *window_name);\n\noptions_type * create_options(int *argc, char ***argv) {\n google::ParseCommandLineFlags(argc, argv, true);\n options_type *o = (options_type *) calloc(1, sizeof(options_type));\n \n if (FLAGS_live && *argc == 1) {\n o->live = true;\n } else if (*argc != 2) {\n o->live = false;\n cout << \"usage: \" << *argv[0] << \" input-video\" << endl;\n free(o);\n return NULL;\n }\n\n \/\/ Prerotation?\n o->postrotate = (enum postrotate_enum)FLAGS_postrotate;\n\n \/\/ open input video\n if (o->live) {\n o->video_src = new VideoCapture(0);\n } else {\n string input_file = (*argv)[(*argc) - 1];\n o->video_src = new VideoCapture(input_file);\n }\n if(!o->video_src->isOpened()) return NULL;\n\n \/\/ get axis\n if (FLAGS_axis == \"x\") {\n o->axis = AXIS_X;\n } else if (FLAGS_axis == \"y\") {\n o->axis = AXIS_Y;\n } else if (FLAGS_axis == \"t\") {\n o->axis = AXIS_T;\n } else {\n free(o);\n return NULL;\n }\n\n \/\/ get size of output video\n int width = o->video_src->get(CV_CAP_PROP_FRAME_WIDTH);\n int height = o->video_src->get(CV_CAP_PROP_FRAME_HEIGHT);\n int frame_count = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);\n if (o->live) {\n o->size = Size(width, height);\n o->frame_count = FLAGS_axis == \"x\" ? height : width;\n } else if (FLAGS_axis == \"x\") {\n o->size = Size(width, frame_count);\n o->frame_count = height;\n } else if (FLAGS_axis == \"y\") {\n o->size = Size(frame_count, height);\n o->frame_count = width;\n } else {\n free(o);\n return NULL;\n }\n\n \/\/ get output video\n if (!FLAGS_save.empty()) {\n o->video_dst = new VideoWriter;\n int ex = CV_FOURCC('I', 'Y', 'U', 'V');\n if (o->postrotate == ROT_NONE || o->postrotate == ROT_180) {\n o->video_dst->open(FLAGS_save, ex, FLAGS_fps, o->size);\n } else {\n o->video_dst->open(FLAGS_save, ex, FLAGS_fps, Size(o->size.height, o->size.width));\n }\n }\n\n return o;\n\n}\n\nint main(int argc, char **argv) {\n signal(SIGINT, SIG_IGN); \n setbuf(stdout, NULL);\n\n google::SetUsageMessage(\"Rotate video in time.\");\n\n options_type *o = create_options(&argc, &argv);\n if (o == NULL)\n return -1;\n\n if (FLAGS_display) {\n namedWindow(argv[0],CV_WINDOW_NORMAL);\n setWindowProperty(argv[0], CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);\n }\n\n if (o->live)\n video_live_filter(o, argv[0]);\n else\n video_file_filter(o, argv[0]);\n\n delete o->video_src;\n delete o->video_dst;\n free(o);\n\n return 0;\n}\n\nint video_live_filter(options_type *o, char *window_name) {\n Mat frame_in;\n *(o->video_src) >> frame_in;\n Mat frame_out(o->size, frame_in.type());\n\n list<Mat> frame_list;\n for (int i = 0; i < o->frame_count; i++) {\n cout << \"Frame \" << i+1 << \" of \" << o->frame_count << endl;\n if (waitKey(1) == '\u001b')\n return 0;\n *(o->video_src) >> frame_in;\n frame_list.push_back(frame_in.clone());\n }\n\n int j = 0;\n int d = 1;\n for (;;) {\n int i = 0;\n for (list<Mat>::iterator it = frame_list.begin(); it != frame_list.end(); it++) {\n switch (o->axis) {\n case AXIS_X:\n it->row(j).copyTo(frame_out.row(i));\n break;\n case AXIS_Y:\n it->col(j).copyTo(frame_out.col(i));\n break;\n default:\n cout << \"UNIMPLEMENTED\" << endl;\n return -1;\n }\n i++;\n }\n if (j == o->frame_count - 1) {\n d = -1;\n } else if (j == 0) {\n d = 1;\n }\n j += d;\n\n\n imshow(window_name, frame_out);\n if (waitKey(1) == '\u001b')\n return 0;\n\n *(o->video_src) >> frame_in;\n frame_list.push_back(frame_in.clone());\n frame_list.pop_front();\n }\n\n}\n\nint video_file_filter(options_type *o, char *window_name) {\n Mat frame_in;\n *(o->video_src) >> frame_in;\n Mat frame_out(o->size, frame_in.type());\n\n int frame_count_src = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);\n for (int j = 0; j < o->frame_count; j++) {\n\n \/\/ Output status to console\n if (!FLAGS_quiet)\n printf(\"Frame %d of %d...\",j + 1, o->frame_count);\n\n \/\/ Create a new frame.\n o->video_src->set(CV_CAP_PROP_POS_FRAMES, 0);\n for (int i = 0; i < frame_count_src; i++) {\n *(o->video_src) >> frame_in;\n switch (o->axis) {\n case AXIS_X:\n frame_in.row(j).copyTo(frame_out.row(i));\n break;\n case AXIS_Y:\n frame_in.col(j).copyTo(frame_out.col(i));\n break;\n default:\n cout << \"UNIMPLEMENTED\" << endl;\n return -1;\n }\n }\n\n\n if (o->postrotate != ROT_NONE) {\n printf(\"postrotation...\");\n }\n\n \/\/ Do any postrotation required before finishing frame.\n Mat f;\n if (o->postrotate == ROT_90CW) {\n transpose(frame_out, f);\n flip(f, f, 1);\n } else if (o->postrotate == ROT_90CCW) {\n transpose(frame_out, f);\n flip(f, f, 0);\n } else if (o->postrotate == ROT_180) {\n flip(frame_out, f, -1);\n } else {\n f = frame_out;\n }\n \n \/\/ Display window\n if (FLAGS_display) {\n imshow(window_name, f);\n if (waitKey(1) == '\u001b')\n return 0;\n }\n\n \/\/ Save frame to file\n if (!FLAGS_save.empty()) {\n printf(\"writing...\");\n o->video_dst->write(f);\n }\n \n printf(\"done.\\n\");\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n#include <iomanip>\n#include <string>\n#include <unistd.h>\n#include <stdlib.h>\n#include <crafter.h>\n#include <crafter\/Utils\/IPResolver.h>\n\nusing namespace std;\nusing namespace Crafter;\n\nunsigned long max_threads = 254; \/\/ TODO: more elegantly, we should query for the max number of BPF devices we can use\n\nvoid usage() {\n cout << \"Usage: whosup -i interface -a addresses [-q] [-t threads] [-r retries] [-w timeout]\" << endl;\n exit(1);\n}\n\nint main(int argc, char *const *argv) {\n\n string iface, addresses;\n bool quiet = false;\n int threads = 0;\n int retries = 2;\n double timeout = 1.0;\n\n int c;\n extern char *optarg;\n extern int optind, optopt;\n if (argc < 5) usage();\n while((c = getopt(argc, argv, \":i:a:qt:r:w:\")) != EOF) {\n switch (c) {\n case 'i':\n iface = optarg;\n break;\n case 'a':\n addresses = optarg;\n break;\n case 'q':\n quiet = true;\n break;\n case 't':\n threads = atoi(optarg);\n break;\n case 'r':\n retries = atoi(optarg);\n break;\n case 'w':\n timeout = atof(optarg);\n break;\n case ':':\n cerr << \"Option -\" << (char)optopt << \" requires an operand\" << endl;\n usage();\n case '?':\n cerr << \"Unrecognised option: -\" << (char)optopt << endl;\n usage();\n }\n }\n\n string MyIP = GetMyIP(iface);\n string MyMAC = GetMyMAC(iface);\n\n Ethernet ether_header;\n ether_header.SetSourceMAC(MyMAC);\n ether_header.SetDestinationMAC(\"ff:ff:ff:ff:ff:ff\");\n ARP arp_header;\n arp_header.SetOperation(ARP::Request);\n arp_header.SetSenderIP(MyIP);\n arp_header.SetSenderMAC(MyMAC);\n\n vector<string> net = GetIPs(addresses);\n vector<string>::iterator ip_addr;\n vector<Packet*> request_packets;\n for(ip_addr = net.begin() ; ip_addr != net.end() ; ip_addr++) {\n arp_header.SetTargetIP(*ip_addr);\n Packet* packet = new Packet;\n packet->PushLayer(ether_header);\n packet->PushLayer(arp_header);\n request_packets.push_back(packet);\n }\n\n vector<Packet*> replies_packets(request_packets.size());\n if (threads == 0) {\n threads = min(net.size(), max_threads);\n }\n SendRecv(request_packets.begin(), request_packets.end(), replies_packets.begin(), iface, timeout, retries, threads);\n\n vector<Packet*>::iterator it_pck;\n if (!quiet) {\n cout << setfill(' ') << setw(18) << left << \"Host\" << setw(42) << left << \"Hostname\" << setw(18) << left << \"MAC Address\" << endl;\n }\n int counter = 0;\n for(it_pck = replies_packets.begin() ; it_pck < replies_packets.end() ; it_pck++) {\n Packet* reply_packet = (*it_pck);\n if(reply_packet) {\n ARP* arp_layer = reply_packet->GetLayer<ARP>();\n if (! quiet) {\n cout << setfill(' ') << setw(18) << left << arp_layer->GetSenderIP() << setw(42) << left << GetHostname(arp_layer->GetSenderIP()) << setw(18) << left << arp_layer->GetSenderMAC() << endl;\n }\n counter++;\n }\n }\n\n cout << counter << \" hosts up.\" << endl;\n\n for(it_pck = request_packets.begin() ; it_pck < request_packets.end() ; it_pck++)\n delete (*it_pck);\n for(it_pck = replies_packets.begin() ; it_pck < replies_packets.end() ; it_pck++)\n delete (*it_pck);\n\n return 0;\n}\n<commit_msg>Attempt to fix build on OpenWrt<commit_after>#include <iostream>\n#include <algorithm>\n#include <iomanip>\n#include <string>\n#include <unistd.h>\n#include <stdlib.h>\n#include <crafter.h>\n#include <crafter\/Utils\/IPResolver.h>\n\nusing namespace std;\nusing namespace Crafter;\n\nunsigned long max_threads = 254; \/\/ TODO: more elegantly, we should query for the max number of BPF devices we can use\n\nvoid usage() {\n cout << \"Usage: whosup -i interface -a addresses [-q] [-t threads] [-r retries] [-w timeout]\" << endl;\n exit(1);\n}\n\nint main(int argc, char *const *argv) {\n\n string iface, addresses;\n bool quiet = false;\n int threads = 0;\n int retries = 2;\n double timeout = 1.0;\n\n int c;\n extern char *optarg;\n extern int optind, optopt;\n if (argc < 5) usage();\n while((c = getopt(argc, argv, \":i:a:qt:r:w:\")) != EOF) {\n switch (c) {\n case 'i':\n iface = optarg;\n break;\n case 'a':\n addresses = optarg;\n break;\n case 'q':\n quiet = true;\n break;\n case 't':\n threads = atoi(optarg);\n break;\n case 'r':\n retries = atoi(optarg);\n break;\n case 'w':\n timeout = atof(optarg);\n break;\n case ':':\n cerr << \"Option -\" << (char)optopt << \" requires an operand\" << endl;\n usage();\n case '?':\n cerr << \"Unrecognised option: -\" << (char)optopt << endl;\n usage();\n }\n }\n\n string MyIP = GetMyIP(iface);\n string MyMAC = GetMyMAC(iface);\n\n Ethernet ether_header;\n ether_header.SetSourceMAC(MyMAC);\n ether_header.SetDestinationMAC(\"ff:ff:ff:ff:ff:ff\");\n ARP arp_header;\n arp_header.SetOperation(ARP::Request);\n arp_header.SetSenderIP(MyIP);\n arp_header.SetSenderMAC(MyMAC);\n\n vector<string> net = GetIPs(addresses);\n vector<string>::iterator ip_addr;\n vector<Packet*> request_packets;\n for(ip_addr = net.begin() ; ip_addr != net.end() ; ip_addr++) {\n arp_header.SetTargetIP(*ip_addr);\n Packet* packet = new Packet;\n packet->PushLayer(ether_header);\n packet->PushLayer(arp_header);\n request_packets.push_back(packet);\n }\n\n vector<Packet*> replies_packets(request_packets.size());\n if (threads == 0) {\n threads = min((unsigned long) net.size(), max_threads);\n }\n SendRecv(request_packets.begin(), request_packets.end(), replies_packets.begin(), iface, timeout, retries, threads);\n\n vector<Packet*>::iterator it_pck;\n if (!quiet) {\n cout << setfill(' ') << setw(18) << left << \"Host\" << setw(42) << left << \"Hostname\" << setw(18) << left << \"MAC Address\" << endl;\n }\n int counter = 0;\n for(it_pck = replies_packets.begin() ; it_pck < replies_packets.end() ; it_pck++) {\n Packet* reply_packet = (*it_pck);\n if(reply_packet) {\n ARP* arp_layer = reply_packet->GetLayer<ARP>();\n if (! quiet) {\n cout << setfill(' ') << setw(18) << left << arp_layer->GetSenderIP() << setw(42) << left << GetHostname(arp_layer->GetSenderIP()) << setw(18) << left << arp_layer->GetSenderMAC() << endl;\n }\n counter++;\n }\n }\n\n cout << counter << \" hosts up.\" << endl;\n\n for(it_pck = request_packets.begin() ; it_pck < request_packets.end() ; it_pck++)\n delete (*it_pck);\n for(it_pck = replies_packets.begin() ; it_pck < replies_packets.end() ; it_pck++)\n delete (*it_pck);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/gymnure.h\"\n\nint main(int argc, char** argv) {\n\n\t{\n\t\tunsigned int windowWidth = 800;\n\t\tunsigned int windowHeight = 600;\n\n\t\tGymnure* gymnure = new Gymnure(windowWidth, windowHeight);\n\n\t\tgymnure->insertData(\"..\/..\/assets\/sky.jpg\", \"..\/..\/assets\/cube.obj\");\n\t\tgymnure->insertData(\"..\/..\/assets\/chalet.jpg\", \"..\/..\/assets\/chalet.obj\");\n\t\t\n\t\twhile(1) {\n\t\t\tif(!gymnure->draw()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tdelete gymnure;\n\t\treturn (EXIT_SUCCESS);\n\t}\n}\n<commit_msg>remove medivh<commit_after>#include \"..\/gymnure.h\"\n\nint main(int argc, char** argv) {\n\n\t{\n\t\tunsigned int windowWidth = 800;\n\t\tunsigned int windowHeight = 600;\n\n\t\tGymnure* gymnure = new Gymnure(windowWidth, windowHeight);\n\n\t\tgymnure->insertData(\"..\/..\/assets\/sky.jpg\", \"..\/..\/assets\/cube.obj\");\n\t\tgymnure->insertData(\"..\/..\/assets\/chalet.jpg\", \"..\/..\/assets\/chalet.obj\");\n\n\t\twhile(1) {\n\t\t\tif(!gymnure->draw()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tdelete gymnure;\n\t\treturn (EXIT_SUCCESS);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* main.cpp\n * This file is a part of tasks library\n * Copyright (c) tasks authors (see file `COPYRIGHT` for the license)\n *\/\n#include <iostream>\n#include <boost\/array.hpp>\n#include <boost\/thread.hpp>\n#include <boost\/thread\/barrier.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/task.hpp>\n\nlong fibonacci( long n)\n{\n\tif ( n == 0) return 0;\n\tif ( n == 1) return 1;\n\tlong k1( 1), k2( 0);\n\tfor ( int i( 2); i <= n; ++i)\n\t{\n\t\tlong tmp( k1);\n\t\tk1 = k1 + k2;\n\t\tk2 = tmp;\n\t}\n\treturn k1;\n}\n\nint main()\n{\n\t\/\/ create a thread-pool\n\tboost::tasks::static_pool< boost::tasks::unbounded_fifo > pool( boost::tasks::poolsize( 5) );\n\n\t\/\/ execute tasks in thread-pool\n\t\/\/ move tasks ownership to executor\n\tboost::tasks::handle< long > h1(\n\t\tboost::tasks::async(\n\t\t\tboost::tasks::make_task( fibonacci, 10),\n\t\t\tpool));\n\tboost::tasks::handle< long > h2(\n\t\tboost::tasks::async(\n\t\t\tboost::tasks::make_task( fibonacci, 5),\n\t\t\tpool));\n\n\tstd::cout << \"h1: is ready == \" << std::boolalpha << h1.is_ready() << \"\\n\";\n\tstd::cout << \"h2: is ready == \" << std::boolalpha << h2.is_ready() << \"\\n\";\n\n\t\/\/ wait for completion of both tasks\n\tboost::tasks::waitfor_all( h1, h2);\n\n\tstd::cout << \"h1: is ready == \" << std::boolalpha << h1.is_ready() << \"\\n\";\n\tstd::cout << \"h2: is ready == \" << std::boolalpha << h2.is_ready() << \"\\n\";\n\tstd::cout << \"h1: has value == \" << std::boolalpha << h1.has_value() << \"\\n\";\n\tstd::cout << \"h2: has value == \" << std::boolalpha << h2.has_value() << \"\\n\";\n\tstd::cout << \"h1: has exception == \" << std::boolalpha << h1.has_exception() << \"\\n\";\n\tstd::cout << \"h2: has exception == \" << std::boolalpha << h2.has_exception() << \"\\n\";\n\n\t\/\/ get results\n\tstd::cout << \"fibonacci(10) == \" << h1.get() << std::endl;\n\tstd::cout << \"fibonacci(5) == \" << h2.get() << std::endl;\n\treturn 0;\n}\n\n<commit_msg>async and sync request handling with boost.task exteriments<commit_after>\/* main.cpp\n * This file is a part of tasks library\n * Copyright (c) tasks authors (see file `COPYRIGHT` for the license)\n *\/\n#include <iostream>\n#include <boost\/asio.hpp>\n#include <boost\/array.hpp>\n#include <boost\/thread.hpp>\n#include <boost\/thread\/barrier.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/task.hpp>\n\ntypedef boost::shared_ptr<class Request> RequestPtr;\nclass Request\n{\npublic:\n\tRequest(const std::string & data)\n\t\t: data_(data)\n\t{}\n\n\tconst std::string & Read() const\n\t{\n\t\tstd::cout<<\"\\tRequest \"<<this<<\" Read \"<<data_<<\"\\n\";\n\t\treturn data_;\n\t}\n\n\tvoid Write(const std::string & answer)\n\t{\n\t\tstd::cout<<\"\\tRequest \"<<this<<\" Write \"<<answer<<\"\\n\";\n\t}\n\nprivate:\n\tstd::string data_;\n};\n\nclass ExternalRequestHandler\n{\npublic:\n\tExternalRequestHandler(boost::asio::io_service & io_service)\n\t\t: timer_(io_service)\n\t{}\n\n\tvoid PerformExternalReqeust(const std::string & what, boost::tasks::spin::auto_reset_event * ev)\n\t{\n\t\twhat_ = what;\n\t\tstd::cout<<\"\\texternal request \"<<what_<<\" begin\\n\";\n\t\ttimer_.expires_from_now(boost::posix_time::milliseconds(rand()%100 + 10));\n\t\ttimer_.async_wait(boost::bind(&ExternalRequestHandler::HandleTimeout, this, ev));\n\t}\n\nprivate:\n\n\tvoid HandleTimeout(boost::tasks::spin::auto_reset_event * ev)\n\t{\n\t\tstd::cout<<\"\\texternal request \"<<what_<<\" end\\n\";\n\t\tev->set();\n\t}\n\nprivate:\n\tboost::asio::deadline_timer timer_;\n\tstd::string what_;\n};\n\ntypedef boost::shared_ptr<class RequestHandler> RequestHandlerPtr;\nclass RequestHandler\n{\npublic:\n\tRequestHandler(boost::asio::io_service & io_service, const RequestPtr & request)\n\t\t: io_service_(io_service)\n\t\t, request_(request)\n\t{}\n\n\tvoid Process() const\n\t{\n\t\tstd::cout<<\"\\tRequestHandler \"<<request_.get()<<\" exec begin\\n\";\n\n\t\tstd::string data = request_->Read();\n\n\t\tRequest(\"query1\");\n\n\t\tboost::tasks::handle< void > subtask1(\n\t\t\tboost::tasks::async(\n\t\t\t\tboost::tasks::make_task( &RequestHandler::Subtask1, this )));\n\t\tboost::tasks::handle< void > subtask2(\n\t\t\tboost::tasks::async(\n\t\t\t\tboost::tasks::make_task( &RequestHandler::Subtask2, this )));\n\n\t\tboost::tasks::waitfor_all( subtask1, subtask2);\n\n\t\tRequest(\"query5\");\n\n\t\trequest_->Write(\"some answer\");\n\n\t\tstd::cout<<\"\\tRequestHandler \"<<request_.get()<<\" exec end\\n\";\n\t}\n\nprivate:\n\n\tvoid Subtask1() const\n\t{\n\t\tRequest(\"query2\");\n\t\tExternalRequest(\"extquery1\");\n\t}\n\n\tvoid Subtask2() const\n\t{\n\t\tRequest(\"query3\");\n\t\tExternalRequest(\"extquery2\");\n\t\tRequest(\"query4\");\n\t}\n\n\tvoid Request(const std::string & what) const\n\t{\n\t\tstd::cout<<\"\\trequest \"<<what<<\" begin\\n\";\n\t\tboost::this_thread::sleep(boost::posix_time::milliseconds(rand()%100 + 10));\n\t\tstd::cout<<\"\\trequest \"<<what<<\" end\\n\";\n\t}\n\n\tvoid ExternalRequest(const std::string & what) const\n\t{\n\t\tstd::cout<<\"\\text request \"<<what<<\" begin\\n\";\n\t\tExternalRequestHandler external_handler(io_service_);\n\t\tboost::tasks::spin::auto_reset_event ev;\n\t\texternal_handler.PerformExternalReqeust(what, &ev);\n\t\tstd::cout<<\"\\text request \"<<what<<\" wait for completion\\n\";\n\t\tev.wait();\n\t\tstd::cout<<\"\\text request \"<<what<<\" end\\n\";\n\t}\n\nprivate:\n\tboost::asio::io_service & io_service_;\n\tRequestPtr request_;\n};\n\nvoid dummy_handler(const boost::system::error_code&) {}\n\nint main()\n{\n\tstd::cout<<\" * main\\n\";\n\n\tboost::tasks::static_pool< boost::tasks::unbounded_fifo > pool( boost::tasks::poolsize( 5) );\n\n\tstd::cout<<\" * creating asio::io_service\\n\";\n\tboost::asio::io_service io_service;\n\n\t\/\/ keep io_service busy\n\tboost::asio::deadline_timer dummy_timer(io_service);\n\tdummy_timer.expires_from_now(boost::posix_time::seconds(10));\n\tdummy_timer.async_wait(&dummy_handler);\n\n\tstd::cout<<\" * starting asio::io_service threads\\n\";\n\tboost::thread_group io_service_thread_pool;\n\tfor(int i = 0; i < 3; ++i)\n\t\tio_service_thread_pool.create_thread(\n\t\t\tboost::bind(&boost::asio::io_service::run, &io_service)\n\t\t);\n\n\tstd::cout<<\" * creating request\\n\";\n\tRequestPtr request(new Request(\"some data\"));\n\tstd::cout<<\" * creating handler\\n\";\n\tRequestHandlerPtr handler(new RequestHandler(io_service, request));\n\n\n\tstd::cout<<\" * creating task for handling request\\n\";\n\tboost::tasks::handle< void > request_processing(\n\t\tboost::tasks::async(\n\t\t\tboost::tasks::make_task( &RequestHandler::Process, handler ),\n\t\t\tpool));\n\n\tstd::cout<<\" * waiting task for colmpletion\\n\";\n\trequest_processing.wait();\n\n\tstd::cout<<\" * terminationg io_service threads\\n\";\n\tio_service.stop();\n\tio_service_thread_pool.join_all();\n\n\tstd::cout<<\" * done\\n\";\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <random>\n#include <string>\n\n#include <SFML\/Graphics.hpp>\n#include \"Particle.hpp\"\n\nstd::random_device randDevice;\nstd::mt19937 gen(randDevice());\nstd::uniform_real_distribution<> dist(0,5);\n\nfloat MapToRange(float valueToBeMapped, float lowInputRange = 0.0, int highInputRange = 600.0, int lowDestRange = 0.0, int highDestRange = 255.0)\n{\n return lowDestRange + ( valueToBeMapped - lowInputRange ) * ( highDestRange - lowDestRange ) \/ ( highInputRange - lowInputRange );\n}\n\nint main(int argc, char* argv[])\n{\n sf::RenderWindow window(sf::VideoMode(800, 600), \"Particle Motion\", sf::Style::Default);\n\n sf::Clock deltaTime;\n float dt = 0.00000001;\n\n int numberOfParticles = 800;\n int imageCounter = 0;\n\n std::vector<Particle> particles;\n\n for(size_t i = 0; i < numberOfParticles; ++i)\n {\n\n Particle particle;\n Position initialPosition;\n\n initialPosition.xPosition = (window.getSize().x \/ numberOfParticles)*i;\n initialPosition.yPosition = 0.0f;\n particle.setPosition(initialPosition);\n\n particle.setFillColor(sf::Color(0,0,100));\n auto gravFactor = dist(gen);\n float gravity = static_cast<float>(-9.8*gravFactor);\n\n particle.setGravity(gravity);\n\n particles.push_back(particle);\n }\n\n while(window.isOpen())\n {\n window.clear(sf::Color::White);\n ++imageCounter;\n\n \/\/Handle events\n sf::Event event;\n while(window.pollEvent(event))\n {\n \/\/Window closed or escape key pressed: Exit\n if((event.type == sf::Event::Closed) or\n ((event.type == sf::Event::KeyPressed) and (event.key.code == sf::Keyboard::Escape)))\n {\n window.close();\n break;\n }\n }\n\n for(auto& particle : particles)\n {\n particle.updatePosition(dt);\n auto position = particle.getPosition();\n\n auto redColorValue = MapToRange(position.yPosition);\n particle.setFillColor(sf::Color(redColorValue, 0, 100));\n\n window.draw(particle.getParticle());\n\n }\n\n window.display();\n sf::Image image = window.capture();\n std::string imagePath = \"images\/image\" + std::to_string(imageCounter) + \".jpg\";\n\n image.saveToFile(imagePath);\n\n\n\n dt = deltaTime.restart().asSeconds();\n }\n\n\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Removed image writing bit.<commit_after>#include <iostream>\n#include <random>\n#include <string>\n\n#include <SFML\/Graphics.hpp>\n#include \"Particle.hpp\"\n\nstd::random_device randDevice;\nstd::mt19937 gen(randDevice());\nstd::uniform_real_distribution<> dist(0,5);\n\nfloat MapToRange(float valueToBeMapped, float lowInputRange = 0.0, int highInputRange = 600.0, int lowDestRange = 0.0, int highDestRange = 255.0)\n{\n return lowDestRange + ( valueToBeMapped - lowInputRange ) * ( highDestRange - lowDestRange ) \/ ( highInputRange - lowInputRange );\n}\n\nint main(int argc, char* argv[])\n{\n sf::RenderWindow window(sf::VideoMode(800, 600), \"Particle Motion\", sf::Style::Default);\n\n sf::Clock deltaTime;\n float dt = 0.00000001;\n\n int numberOfParticles = 800;\n int imageCounter = 0;\n\n std::vector<Particle> particles;\n\n for(size_t i = 0; i < numberOfParticles; ++i)\n {\n\n Particle particle;\n Position initialPosition;\n\n initialPosition.xPosition = (window.getSize().x \/ numberOfParticles)*i;\n initialPosition.yPosition = 0.0f;\n particle.setPosition(initialPosition);\n\n particle.setFillColor(sf::Color(0,0,100));\n auto gravFactor = dist(gen);\n float gravity = static_cast<float>(-9.8*gravFactor);\n\n particle.setGravity(gravity);\n\n particles.push_back(particle);\n }\n\n while(window.isOpen())\n {\n window.clear(sf::Color::White);\n ++imageCounter;\n\n \/\/Handle events\n sf::Event event;\n while(window.pollEvent(event))\n {\n \/\/Window closed or escape key pressed: Exit\n if((event.type == sf::Event::Closed) or\n ((event.type == sf::Event::KeyPressed) and (event.key.code == sf::Keyboard::Escape)))\n {\n window.close();\n break;\n }\n }\n\n for(auto& particle : particles)\n {\n particle.updatePosition(dt);\n auto position = particle.getPosition();\n\n auto redColorValue = MapToRange(position.yPosition);\n particle.setFillColor(sf::Color(redColorValue, 0, 100));\n\n window.draw(particle.getParticle());\n\n }\n\n window.display();\n \n \/\/sf::Image image = window.capture();\n \/\/std::string imagePath = \"images\/image\" + std::to_string(imageCounter) + \".jpg\";\n \/\/image.saveToFile(imagePath);\n\n dt = deltaTime.restart().asSeconds();\n }\n\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"utils.h\"\n#include <stdio.h> \n#include <time.h>\n#include <stdlib.h>\n#include <vector>\n#include \"wall.h\"\n#include \"math.h\"\n#include \"drawing.h\"\n#include \"circle.h\"\n\n#include <GL\/gl.h> \n#include <GL\/glu.h> \n#include <GL\/glut.h> \n\nusing namespace std;\n\nvector<circle> cs ;\nvector<wall> ws;\nvector<wall> iws; \nvector<wall> gws; \n\ncircle puck(vec2(0,0), 0.03); \n\nvec2 p1(0,0); \n\nbool lmbPressed = false; \n\nvoid keyboard (unsigned char a, int b, int c) { \n \/\/ p1.x = ((float)(b - 300))\/300;\n \/\/ p1.y = -((float)(c - 300))\/300;\n}\n\n\nvoid mouseMoved (int a, int b) {\n\n float dx = (a - p1.x) \/ (600);\n float dy = (p1.y - b) \/ (600);\n\n\n if (lmbPressed) {\n cs[0].v.x += 0.05 * dx;\n cs[0].v.y += 0.05 * dy;\n\n }\n\n p1.x = a;\n p1.y = b;\n}\n\nvoid passiveMouseMoved (int b, int c) {\n p1.x = b;\n p1.y = c;\n}\n\nvoid mouseFunc (int button, int state, int x, int y) {\n if (button == GLUT_LEFT_BUTTON) {\n lmbPressed = state == GLUT_DOWN; \n } \n\n \/\/ if (state == GLUT_DOWN) { \n \/\/ lmbPressed = true;\n \/\/ }\n\n \/\/ if(state != GLUT_DOWN) return;\n \n \/\/ float window_width = glutGet(GLUT_WINDOW_WIDTH);\n \/\/ float window_height = glutGet(GLUT_WINDOW_HEIGHT);\n \n \/\/ unsigned int index;\n \/\/ glReadPixels(x, window_height - y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);\n \n \/\/ printf (\"Stencil at %d %d : %d \\n\", x, y, index); \n\n}\n\nvoid specialKey (int key, int b, int c) { \n \/\/ switch(key) {\n \/\/ case GLUT_KEY_UP: \n \/\/ cs[0].v.y += 0.001;\n \/\/ break;\n \/\/ case GLUT_KEY_DOWN: \n \/\/ cs[0].v.y -= 0.001;\n \/\/ break;\n \/\/ case GLUT_KEY_LEFT: \n \/\/ cs[0].v.x -= 0.001;\n \/\/ break;\n \/\/ case GLUT_KEY_RIGHT: \n \/\/ cs[0].v.x += 0.001; \n \/\/ break;\n \/\/ default:\n \/\/ return; \n \/\/ }\n}\n\nvoid collideWithWalls (vector<circle> & cs, vector<wall> & ws, float m) { \n for (int j = 0; j < cs.size(); j++) { \n for (int i = 0; i < ws.size(); i++) { \n vec2 o;\n wall w = ws[i];\n bool b = ws[i].collision(cs[j].c, cs[j].r, o);\n\n if (b) {\n \tcs[j].step(-m);\n\n \tvec2 vel(cs[j].v.x, cs[j].v.y);\n \tvel = vel.reflectedIn(ws[i].p0, ws[i].p1);\n \tcs[j].v = vel;\n\n \tcs[j].step(m);\n \tbreak; \n } \n }\n }\n}\n\nvoid display() { \n\n float m = 1;\n\n glClearStencil(0);\n\n \/\/ clear buffers\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n\n glEnable(GL_STENCIL_TEST);\n glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);\n\n glViewport (0, 0, 600, 600); \n\n\n \/\/ reset model view \n glMatrixMode (GL_MODELVIEW); \n glLoadIdentity (); \n \n \/\/ Draw the colour ramp scale \n \/\/ Clear the projection matrix\n glMatrixMode (GL_PROJECTION); \n glLoadIdentity (); \n\n for (wall & w : ws) { w.draw(); }\n\n glColor3f(0.3, 0.3, 0.3);\n for (wall & iw : iws) { iw.draw(); }\n for (wall & gw : gws) { gw.draw(); }\n glColor3f(1, 1, 1);\n\n glStencilFunc(GL_ALWAYS, 1, -1);\n cs[0].draw(); \n cs[0].step(m);\n glStencilFunc(GL_ALWAYS, 0, -1);\n\n for (int i = 1; i < cs.size(); i++) {\n cs[i].draw(); \n cs[i].step(m);\n }\n\n puck.draw(); \n puck.step(m); \n\n\n cs.push_back(puck); \n bool collided[cs.size()] ; \n for (int i = 0; i < cs.size() + 1; i++) collided[i] = false; \n\n \/\/ Collision with other pucks \n for (int i = 0; i < cs.size(); i++) { \n for (int j = 0; j < cs.size(); j++) { \n\n if (i != j && !collided[i] && !collided[j] && circle::collision(cs[i], cs[j])) { \n \tcs[i].step(-m); cs[j].step(-m);\n\n \tcircle::performCollision(cs[i], cs[j], 1); \n\n \tcs[i].step(m); cs[j].step(m);\n \tcollided[i] = collided[j] = true; \n\n } \n }\n }\n\n\n \n collideWithWalls(cs, ws, m);\n\n puck = cs[cs.size() - 1]; \n cs.pop_back(); \n\n collideWithWalls(cs, iws, m); \n collideWithWalls(cs, gws, m); \n \n \/\/ vector<circle> puck_; \n \/\/ puck_.push_back(puck);\n\n \/\/ collideWithWalls(puck_, ws, m);\n \n\n for (circle & c : cs) { \n c.v = c.v.scale(0.9); \n }\n puck.v.scale(0.9); \n\n glutSwapBuffers();\n glutPostRedisplay ();\n}\n\n\n\nint main(int argc, char** argv) {\n wall::genInitial(3, 0.8, 0.05, 0.2, cs, ws, iws, gws); \n\n \/\/ cs.push_back(circle(vec2(0, 0)), 0.01); \n\n \/\/ OpenGL\/glut setup\n glutInit(&argc, argv);\t\t\n glutInitDisplayMode(GLUT_ALPHA | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE | GLUT_DEPTH | GLUT_STENCIL);\n\n glutInitWindowSize(600, 600);\n glutInitWindowPosition(50, 50);\n \n glutCreateWindow(\"final project - Yuriy Toporovskyy, Mostapha Mohamed\"); \n \/\/ glClearColor(0.1, 0.3, 0.3,0.0);\n\n \/\/ glEnable(GL_LIGHTING);\n glEnable(GL_DEPTH_TEST); \n glEnable(GL_STENCIL_TEST);\n glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);\n \/\/ glEnable(GL_COLOR_MATERIAL);\n\n \/\/ Set up all callback functions.\n \/\/ glutIdleFunc ([] () { st.step(); });\n glutKeyboardFunc (keyboard);\n glutDisplayFunc (display); \n glutSpecialFunc (specialKey);\n glutMouseFunc (mouseFunc);\n glutMotionFunc (mouseMoved); \n glutPassiveMotionFunc (passiveMouseMoved); \n\n \/\/ glutMotionFunc ([] (int a, int b) { st.mouseMoved(a,b); }); \n \/\/ glutDisplayFunc ([] () { st.display(); });\n \/\/ glutPassiveMotionFunc ([] (int a, int b) { st.passiveMouseMoved(a,b); }); \n \/\/ glutReshapeFunc ([] (int a, int b) { st.reshape(a,b); });\n\n \/\/ glutSpecialFunc ([] (int a, int b, int c) { st.specialKey(a,b,c); });\n \/\/ glutIdleFunc ([] () { st.step(); });\n \/\/ glutKeyboardFunc ([] (unsigned char a, int b, int c) { st.keyboard(a,b,c); });\n \/\/ glutMotionFunc ([] (int a, int b) { st.mouseMoved(a,b); }); \n \/\/ glutDisplayFunc ([] () { st.display(); });\n \/\/ glutPassiveMotionFunc ([] (int a, int b) { st.passiveMouseMoved(a,b); }); \n \/\/ glutReshapeFunc ([] (int a, int b) { st.reshape(a,b); });\n \/\/ glutMouseFunc ([] (int a, int b, int c, int d) { st.mousePressed(a,b,c,d); });\n \/\/ glutSpecialFunc ([] (int a, int b, int c) { st.specialKey(a,b,c); });\n \n \/\/ \/\/ Initialize menus\n \/\/ \/\/ Menu containing generators.\n \/\/ int genMenu = glutCreateMenu \n \/\/ ([] (int i) { st.newMesh(&TerrainGenerator::generators[i]); });\n\n \/\/ for (int i = 0; i < (int)TerrainGenerator::generators.size(); i++) {\n \/\/ glutAddMenuEntry(TerrainGenerator::generators[i].name.c_str(), i);\n \/\/ }\n\n \/\/ \/\/ Colour ramp menu\n \/\/ int colMenu = glutCreateMenu \n \/\/ ([] (int i) { st.colourRamp = i; });\n\n \/\/ for (int i = 0; i < (int)ColourRamp::colourRamps.size(); i++) {\n \/\/ glutAddMenuEntry(ColourRamp::colourRamps[i].name.c_str(), i);\n \/\/ }\n\n \/\/ \/\/ Main menu.\n \/\/ glutCreateMenu ([] (int i) { });\n \/\/ glutAddSubMenu(\"Add to mesh...\", genMenu);\n \/\/ glutAddSubMenu(\"Select colour ramp...\", colMenu);\n \/\/ glutAttachMenu(GLUT_RIGHT_BUTTON);\n\n \/\/ \/\/ Second window with heightmap \n \/\/ glutInitWindowPosition(700, 50);\n\n \/\/ int heightMapWindow = glutCreateWindow (argv[0]);\n \/\/ glutSetWindowTitle(\"Heightmap\");\n \/\/ glutDisplayFunc ([] () { st.displayHM(); });\n \/\/ glutReshapeFunc ([] (int a, int b) { st.reshapeHM (a,b); });\n \/\/ glutMotionFunc ([] (int a, int b) { st.mouseMovedHM(a,b); }); \n \/\/ glutPassiveMotionFunc ([] (int a, int b) { st.passiveMouseMovedHM(a,b); }); \n \/\/ glutMouseFunc ([] (int a, int b, int c, int d) { st.mousePressedHM(a,b,c,d); });\n\n\n glutMainLoop();\t\t\t\t\n return(0);\n}\n\n\n\n\n<commit_msg>Added sort -of AI<commit_after>\n#include \"utils.h\"\n#include <stdio.h> \n#include <time.h>\n#include <stdlib.h>\n#include <vector>\n#include \"wall.h\"\n#include \"math.h\"\n#include \"drawing.h\"\n#include \"circle.h\"\n\n#include <GL\/gl.h> \n#include <GL\/glu.h> \n#include <GL\/glut.h> \n\nusing namespace std;\n\nvector<circle> cs ;\nvector<wall> ws;\nvector<wall> iws; \nvector<wall> gws; \n\nconst float puckRadius = 0.03;\n\ncircle puck(vec2(0,0), puckRadius); \n\nvec2 p1(0,0); \n\nbool lmbPressed = false; \n\nvoid keyboard (unsigned char a, int b, int c) { \n \/\/ p1.x = ((float)(b - 300))\/300;\n \/\/ p1.y = -((float)(c - 300))\/300;\n}\n\n\/\/ bool inSegment (int i, int n, float x0, float y0) { \n \n\/\/ }\n\n\nvoid stepAI (float m, float diff, int i, float n, circle & c, circle puck) { \n vec2 towardsPuck = puck.c - c.c ;\n float dist = towardsPuck.magnitude(); \n \n vec2 toAdd;\n\n if (dist < 0.4) { \n toAdd = towardsPuck.scale((3 * diff * m) \/ (1 + dist)); \n \/\/ c.v = c.v + toAdd; \n } else { \n\n float al = 2*PI*(4*i+1)\/(4.0*n);\n\n toAdd = vec2 (cosf(al), sinf(al));\n \n\n toAdd = toAdd.scale(0.55); \n\n \/\/ Test\n \/\/ drawPaddle(toAdd, 0.01); \n\n toAdd = (toAdd - c.v).scale(diff * m);\n }\n\n c.v = c.v + toAdd; \n\n \/\/ if (toAdd.x < 0 && toAdd.y < 0) { \n \/\/ c.v = c.v - toAdd; \n \/\/ } else {\n \/\/ c.v = c.v + toAdd; \n \/\/ }\n\n}\n\nvoid mouseMoved (int a, int b) {\n\n float dx = (a - p1.x) \/ (600);\n float dy = (p1.y - b) \/ (600);\n\n\n if (lmbPressed) {\n cs[0].v.x += 0.07 * dx;\n cs[0].v.y += 0.07 * dy;\n\n }\n\n p1.x = a;\n p1.y = b;\n}\n\nvoid passiveMouseMoved (int b, int c) {\n p1.x = b;\n p1.y = c;\n}\n\nvoid mouseFunc (int button, int state, int x, int y) {\n if (button == GLUT_LEFT_BUTTON) {\n lmbPressed = state == GLUT_DOWN; \n } \n\n \/\/ if (state == GLUT_DOWN) { \n \/\/ lmbPressed = true;\n \/\/ }\n\n \/\/ if(state != GLUT_DOWN) return;\n \n \/\/ float window_width = glutGet(GLUT_WINDOW_WIDTH);\n \/\/ float window_height = glutGet(GLUT_WINDOW_HEIGHT);\n \n \/\/ unsigned int index;\n \/\/ glReadPixels(x, window_height - y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);\n \n \/\/ printf (\"Stencil at %d %d : %d \\n\", x, y, index); \n\n}\n\nvoid specialKey (int key, int b, int c) { \n \/\/ switch(key) {\n \/\/ case GLUT_KEY_UP: \n \/\/ cs[0].v.y += 0.001;\n \/\/ break;\n \/\/ case GLUT_KEY_DOWN: \n \/\/ cs[0].v.y -= 0.001;\n \/\/ break;\n \/\/ case GLUT_KEY_LEFT: \n \/\/ cs[0].v.x -= 0.001;\n \/\/ break;\n \/\/ case GLUT_KEY_RIGHT: \n \/\/ cs[0].v.x += 0.001; \n \/\/ break;\n \/\/ default:\n \/\/ return; \n \/\/ }\n}\n\nbool collideWithWalls (vector<circle> & cs, vector<wall> & ws, float m) {\n boolean r = false;\n for (int j = 0; j < cs.size(); j++) { \n for (int i = 0; i < ws.size(); i++) { \n vec2 o;\n wall w = ws[i];\n bool b = ws[i].collision(cs[j].c, cs[j].r, o);\n\n if (b) {\n \tcs[j].step(-m);\n\n \tvec2 vel(cs[j].v.x, cs[j].v.y);\n \tvel = vel.reflectedIn(ws[i].p0, ws[i].p1);\n \tcs[j].v = vel;\n\n \tcs[j].step(m);\n\tr = true;\n \tbreak; \n } \n }\n }\n return r; \n}\n\nvoid display() { \n\n float m = 1;\n\n glClearStencil(0);\n\n \/\/ clear buffers\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n\n glEnable(GL_STENCIL_TEST);\n glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);\n\n glViewport (0, 0, 600, 600); \n\n\n \/\/ reset model view \n glMatrixMode (GL_MODELVIEW); \n glLoadIdentity (); \n \n \/\/ Draw the colour ramp scale \n \/\/ Clear the projection matrix\n glMatrixMode (GL_PROJECTION); \n glLoadIdentity (); \n\n for (wall & w : ws) { w.draw(); }\n\n glColor3f(0.3, 0.3, 0.3);\n for (wall & iw : iws) { iw.draw(); }\n for (wall & gw : gws) { gw.draw(); }\n glColor3f(1, 1, 1);\n\n glStencilFunc(GL_ALWAYS, 1, -1);\n cs[0].draw(); \n cs[0].step(m);\n glStencilFunc(GL_ALWAYS, 0, -1);\n\n for (int i = 1; i < cs.size(); i++) {\n cs[i].draw(); \n cs[i].step(m);\n\n\/\/ void stepAI (float m, float diff, int i, circle & c, circle puck) { \n\n stepAI(m, 0.005, i, 3, cs[i], puck); \n\n }\n\n puck.draw(); \n puck.step(m); \n\n\n cs.push_back(puck); \n bool collided[cs.size()] ; \n for (int i = 0; i < cs.size() + 1; i++) collided[i] = false; \n\n \/\/ Collision with other pucks \n for (int i = 0; i < cs.size(); i++) { \n for (int j = 0; j < cs.size(); j++) { \n\n if (i != j && !collided[i] && !collided[j] && circle::collision(cs[i], cs[j])) { \n \tcs[i].step(-m); cs[j].step(-m);\n\n \tcircle::performCollision(cs[i], cs[j], 1); \n\n \tcs[i].step(m); cs[j].step(m);\n \tcollided[i] = collided[j] = true; \n\n } \n }\n }\n\n\n \n collideWithWalls(cs, ws, m);\n\n puck = cs[cs.size() - 1]; \n cs.pop_back(); \n\n collideWithWalls(cs, iws, m); \n collideWithWalls(cs, gws, m); \n \n vector<wall> gwsC (gws); \n\n vector<circle> puck_; \n puck_.push_back(puck);\n\n if (collideWithWalls(puck_, gws, m)) { \n puck = circle(vec2(0,0), puckRadius);\n puck.m = 0.3; \n }\n \n\n for (circle & c : cs) { \n c.v = c.v.scale(0.9); \n }\n puck.v.scale(0.9); \n\n glutSwapBuffers();\n glutPostRedisplay ();\n}\n\n\n\nint main(int argc, char** argv) {\n wall::genInitial(3, 0.8, 0.05, 0.2, cs, ws, iws, gws); \n\n puck.m = 0.3; \n\n \/\/ OpenGL\/glut setup\n glutInit(&argc, argv);\t\t\n glutInitDisplayMode(GLUT_ALPHA | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE | GLUT_DEPTH | GLUT_STENCIL);\n\n glutInitWindowSize(600, 600);\n glutInitWindowPosition(50, 50);\n \n glutCreateWindow(\"final project - Yuriy Toporovskyy, Mostapha Mohamed\"); \n \/\/ glClearColor(0.1, 0.3, 0.3,0.0);\n\n \/\/ glEnable(GL_LIGHTING);\n glEnable(GL_DEPTH_TEST); \n glEnable(GL_STENCIL_TEST);\n glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);\n \/\/ glEnable(GL_COLOR_MATERIAL);\n\n \/\/ Set up all callback functions.\n \/\/ glutIdleFunc ([] () { st.step(); });\n glutKeyboardFunc (keyboard);\n glutDisplayFunc (display); \n glutSpecialFunc (specialKey);\n glutMouseFunc (mouseFunc);\n glutMotionFunc (mouseMoved); \n glutPassiveMotionFunc (passiveMouseMoved); \n\n \/\/ glutMotionFunc ([] (int a, int b) { st.mouseMoved(a,b); }); \n \/\/ glutDisplayFunc ([] () { st.display(); });\n \/\/ glutPassiveMotionFunc ([] (int a, int b) { st.passiveMouseMoved(a,b); }); \n \/\/ glutReshapeFunc ([] (int a, int b) { st.reshape(a,b); });\n\n \/\/ glutSpecialFunc ([] (int a, int b, int c) { st.specialKey(a,b,c); });\n \/\/ glutIdleFunc ([] () { st.step(); });\n \/\/ glutKeyboardFunc ([] (unsigned char a, int b, int c) { st.keyboard(a,b,c); });\n \/\/ glutMotionFunc ([] (int a, int b) { st.mouseMoved(a,b); }); \n \/\/ glutDisplayFunc ([] () { st.display(); });\n \/\/ glutPassiveMotionFunc ([] (int a, int b) { st.passiveMouseMoved(a,b); }); \n \/\/ glutReshapeFunc ([] (int a, int b) { st.reshape(a,b); });\n \/\/ glutMouseFunc ([] (int a, int b, int c, int d) { st.mousePressed(a,b,c,d); });\n \/\/ glutSpecialFunc ([] (int a, int b, int c) { st.specialKey(a,b,c); });\n \n \/\/ \/\/ Initialize menus\n \/\/ \/\/ Menu containing generators.\n \/\/ int genMenu = glutCreateMenu \n \/\/ ([] (int i) { st.newMesh(&TerrainGenerator::generators[i]); });\n\n \/\/ for (int i = 0; i < (int)TerrainGenerator::generators.size(); i++) {\n \/\/ glutAddMenuEntry(TerrainGenerator::generators[i].name.c_str(), i);\n \/\/ }\n\n \/\/ \/\/ Colour ramp menu\n \/\/ int colMenu = glutCreateMenu \n \/\/ ([] (int i) { st.colourRamp = i; });\n\n \/\/ for (int i = 0; i < (int)ColourRamp::colourRamps.size(); i++) {\n \/\/ glutAddMenuEntry(ColourRamp::colourRamps[i].name.c_str(), i);\n \/\/ }\n\n \/\/ \/\/ Main menu.\n \/\/ glutCreateMenu ([] (int i) { });\n \/\/ glutAddSubMenu(\"Add to mesh...\", genMenu);\n \/\/ glutAddSubMenu(\"Select colour ramp...\", colMenu);\n \/\/ glutAttachMenu(GLUT_RIGHT_BUTTON);\n\n \/\/ \/\/ Second window with heightmap \n \/\/ glutInitWindowPosition(700, 50);\n\n \/\/ int heightMapWindow = glutCreateWindow (argv[0]);\n \/\/ glutSetWindowTitle(\"Heightmap\");\n \/\/ glutDisplayFunc ([] () { st.displayHM(); });\n \/\/ glutReshapeFunc ([] (int a, int b) { st.reshapeHM (a,b); });\n \/\/ glutMotionFunc ([] (int a, int b) { st.mouseMovedHM(a,b); }); \n \/\/ glutPassiveMotionFunc ([] (int a, int b) { st.passiveMouseMovedHM(a,b); }); \n \/\/ glutMouseFunc ([] (int a, int b, int c, int d) { st.mousePressedHM(a,b,c,d); });\n\n\n glutMainLoop();\t\t\t\t\n return(0);\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <unistd.h>\n#include <sys\/time.h>\n#include \"server\/sess.h\"\n#include \"util\/msg_queue.h\"\n#include <iostream>\n#include <cstring>\n#include <thread>\n#include \"proto\/protob.pb.h\"\n#include \"arduino\/cArduino.h\"\n#include \"conf\/config.h\"\n#include <signal.h>\n\n\nusing namespace std;\n\nIUINT32 iclock();\n\n\n\nConfig *setting;\ncArduino *arduino;\n\n\/\/cArduino arduino(ArduinoBaundRate::B19200bps, \"\/dev\/ttyACM0\");\nstatic void sig_alarm(int signo);\n\n\nint main() {\n\n string file(\".\/cfg.conf\");\n setting = new Config(file);\n assert(setting != nullptr);\n\n struct timeval time;\n gettimeofday(&time, NULL);\n srand((time.tv_sec * 1000) + (time.tv_usec \/ 1000));\n\n string serverIP;\n serverIP = setting->GetString(\"serverIP\", \"127.0.0.1\");\n int port = setting->GetInt(\"serverPort\", 9999);\n KCPSession *sess = KCPSession::Dial(serverIP.c_str(), port);\n sess->NoDelay(1, 20, 2, 1);\n sess->WndSize(128, 128);\n sess->SetMtu(1400);\n assert(sess != nullptr);\n ssize_t nsent = {0};\n ssize_t nrecv = {0};\n char *buf = (char *) malloc(128);\n\n\n char *name = (char *) \"\/dev\/ttyACM0\";\n arduino = new cArduino(ArduinoBaundRate::B19200bps, name);\n\n\n sprintf(buf, \"iam\");\n sess->Write(buf, strlen(buf));\n for (;;) {\n sess->Update(iclock());\n memset(buf, 0, 128);\n ssize_t n = sess->Read(buf, 128);\n if (n > 0) {\n\n string msg(buf);\n Msg pb;\n pb.ParseFromString(msg);\n cout << pb.content() << endl;\n string cmd = pb.content().substr(0,1);\n string rev = pb.content();\n if (cmd.compare(\"3\")==0||cmd.compare(\"4\")==0){\n string cmdAngle;\/\/指令+角度\n for(int i=0;i<rev.size();i++){\n if (rev[i]!='-'){\n cmdAngle+=rev[i];\n }\n }\n arduino->write(cmdAngle);\n arduino->flush();\n } else if (cmd.compare(\"0\")==0||cmd.compare(\"1\")==0||cmd.compare(\"2\")==0){\n arduino->write(cmd);\n arduino->flush();\n if(pb.content().size()>=3){\n string t = pb.content().substr(2,pb.content().size()-2);\n int i=atoi(t.c_str());\n signal(SIGALRM, sig_alarm);\n alarm(i);\n }\n }\n\n\n }\n\n nrecv += n;\n\n usleep(33);\n }\n}\n\n\/\/shijian dao le de chuli\nstatic void sig_alarm(int signo){\n system(\"date\");\n arduino->write(\"0\");\n arduino->flush();\n return;\n}\n\n\n\nvoid\nitimeofday(long *sec, long *usec) {\n struct timeval time;\n gettimeofday(&time, NULL);\n if (sec) *sec = time.tv_sec;\n if (usec) *usec = time.tv_usec;\n}\n\nIUINT64 iclock64(void) {\n long s, u;\n IUINT64 value;\n itimeofday(&s, &u);\n value = ((IUINT64) s) * 1000 + (u \/ 1000);\n return value;\n}\n\nIUINT32 iclock() {\n return (IUINT32) (iclock64() & 0xfffffffful);\n}\n\/\/#include <unistd.h>\n\/\/#include <sys\/time.h>\n\/\/#include \"server\/sess.h\"\n\/\/#include \"util\/msg_queue.h\"\n\/\/#include <iostream>\n\/\/#include <cstring>\n\/\/#include <thread>\n\/\/#include \"proto\/protob.pb.h\"\n\/\/#include \"arduino\/cArduino.h\"\n\/\/#include \"conf\/config.h\"\n\/\/\n\/\/\n\/\/using namespace std;\n\/\/\n\/\/IUINT32 iclock();\n\/\/\n\/\/\n\/\/\n\/\/Config *setting;\n\/\/cArduino *arduino;\n\/\/\n\/\/int main() {\n\/\/\n\/\/ string file(\".\/cfg.conf\");\n\/\/ setting = new Config(file);\n\/\/ assert(setting != nullptr);\n\/\/\n\/\/ struct timeval time;\n\/\/ gettimeofday(&time, NULL);\n\/\/ srand((time.tv_sec * 1000) + (time.tv_usec \/ 1000));\n\/\/\n\/\/ string serverIP;\n\/\/ serverIP = setting->GetString(\"serverIP\", \"127.0.0.1\");\n\/\/ int port = setting->GetInt(\"serverPort\", 9999);\n\/\/ KCPSession *sess = KCPSession::Dial(serverIP.c_str(), port);\n\/\/ sess->NoDelay(1, 20, 2, 1);\n\/\/ sess->WndSize(128, 128);\n\/\/ sess->SetMtu(1400);\n\/\/ assert(sess != nullptr);\n\/\/ ssize_t nsent = {0};\n\/\/ ssize_t nrecv = {0};\n\/\/ char *buf = (char *) malloc(128);\n\/\/\n\/\/\n\/\/ char *name = (char *) \"\/dev\/ttyACM0\";\n\/\/ arduino = new cArduino(ArduinoBaundRate::B19200bps, name);\n\/\/\n\/\/\n\/\/ sprintf(buf, \"iam\");\n\/\/ sess->Write(buf, strlen(buf));\n\/\/ for (;;) {\n\/\/ sess->Update(iclock());\n\/\/ memset(buf, 0, 128);\n\/\/ ssize_t n = sess->Read(buf, 128);\n\/\/ if (n > 0) {\n\/\/\n\/\/ string msg(buf);\n\/\/ Msg pb;\n\/\/ pb.ParseFromString(msg);\n\/\/ cout << pb.content() << endl;\n\/\/ arduino->write(pb.content());\n\/\/ arduino->flush();\n\/\/ }\n\/\/ nrecv += n;\n\/\/\n\/\/ usleep(33);\n\/\/ }\n\/\/}\n\/\/\n\/\/\n\/\/void\n\/\/itimeofday(long *sec, long *usec) {\n\/\/ struct timeval time;\n\/\/ gettimeofday(&time, NULL);\n\/\/ if (sec) *sec = time.tv_sec;\n\/\/ if (usec) *usec = time.tv_usec;\n\/\/}\n\/\/\n\/\/IUINT64 iclock64(void) {\n\/\/ long s, u;\n\/\/ IUINT64 value;\n\/\/ itimeofday(&s, &u);\n\/\/ value = ((IUINT64) s) * 1000 + (u \/ 1000);\n\/\/ return value;\n\/\/}\n\/\/\n\/\/IUINT32 iclock() {\n\/\/ return (IUINT32) (iclock64() & 0xfffffffful);\n\/\/}\n<commit_msg>增加从树莓派读取数据的线程<commit_after>#include <unistd.h>\n#include <sys\/time.h>\n#include \"server\/sess.h\"\n#include \"util\/msg_queue.h\"\n#include <iostream>\n#include <cstring>\n#include <thread>\n#include \"proto\/protob.pb.h\"\n#include \"arduino\/cArduino.h\"\n#include \"conf\/config.h\"\n#include <signal.h>\n#include <thread>\n\n\nusing namespace std;\n\nIUINT32 iclock();\n\nConfig *setting;\ncArduino *arduino;\n\nvoid run(){\n while(true){\n string msg;\n msg = arduino->read();\n if (!msg.empty()){\n cout << \"from arduino: \" << msg << endl;\n }\n }\n}\n\n\/\/cArduino arduino(ArduinoBaundRate::B19200bps, \"\/dev\/ttyACM0\");\nstatic void sig_alarm(int signo);\n\n\nint main() {\n\n string file(\".\/cfg.conf\");\n setting = new Config(file);\n assert(setting != nullptr);\n\n struct timeval time;\n gettimeofday(&time, NULL);\n srand((time.tv_sec * 1000) + (time.tv_usec \/ 1000));\n\n string serverIP;\n serverIP = setting->GetString(\"serverIP\", \"127.0.0.1\");\n int port = setting->GetInt(\"serverPort\", 9999);\n KCPSession *sess = KCPSession::Dial(serverIP.c_str(), port);\n sess->NoDelay(1, 20, 2, 1);\n sess->WndSize(128, 128);\n sess->SetMtu(1400);\n assert(sess != nullptr);\n ssize_t nsent = {0};\n ssize_t nrecv = {0};\n char *buf = (char *) malloc(128);\n\n\n char *name = (char *) \"\/dev\/ttyACM0\";\n arduino = new cArduino(ArduinoBaundRate::B19200bps, name);\n\n\n thread readArduinoThread(run);\n readArduinoThread.detach();\n\n sprintf(buf, \"iam\");\n sess->Write(buf, strlen(buf));\n for (;;) {\n sess->Update(iclock());\n memset(buf, 0, 128);\n ssize_t n = sess->Read(buf, 128);\n if (n > 0) {\n\n string msg(buf);\n Msg pb;\n pb.ParseFromString(msg);\n cout << pb.content() << endl;\n string cmd = pb.content().substr(0,1);\n string rev = pb.content();\n if (cmd.compare(\"3\")==0||cmd.compare(\"4\")==0){\n string cmdAngle;\/\/指令+角度\n for(int i=0;i<rev.size();i++){\n if (rev[i]!='-'){\n cmdAngle+=rev[i];\n }\n }\n arduino->write(cmdAngle);\n arduino->flush();\n } else if (cmd.compare(\"0\")==0||cmd.compare(\"1\")==0||cmd.compare(\"2\")==0){\n arduino->write(cmd);\n arduino->flush();\n if(pb.content().size()>=3){\n string t = pb.content().substr(2,pb.content().size()-2);\n int i=atoi(t.c_str());\n signal(SIGALRM, sig_alarm);\n alarm(i);\n }\n }\n\n\n }\n\n nrecv += n;\n\n usleep(33);\n }\n}\n\n\/\/shijian dao le de chuli\nstatic void sig_alarm(int signo){\n system(\"date\");\n arduino->write(\"0\");\n arduino->flush();\n return;\n}\n\n\n\nvoid\nitimeofday(long *sec, long *usec) {\n struct timeval time;\n gettimeofday(&time, NULL);\n if (sec) *sec = time.tv_sec;\n if (usec) *usec = time.tv_usec;\n}\n\nIUINT64 iclock64(void) {\n long s, u;\n IUINT64 value;\n itimeofday(&s, &u);\n value = ((IUINT64) s) * 1000 + (u \/ 1000);\n return value;\n}\n\nIUINT32 iclock() {\n return (IUINT32) (iclock64() & 0xfffffffful);\n}\n\/\/#include <unistd.h>\n\/\/#include <sys\/time.h>\n\/\/#include \"server\/sess.h\"\n\/\/#include \"util\/msg_queue.h\"\n\/\/#include <iostream>\n\/\/#include <cstring>\n\/\/#include <thread>\n\/\/#include \"proto\/protob.pb.h\"\n\/\/#include \"arduino\/cArduino.h\"\n\/\/#include \"conf\/config.h\"\n\/\/\n\/\/\n\/\/using namespace std;\n\/\/\n\/\/IUINT32 iclock();\n\/\/\n\/\/\n\/\/\n\/\/Config *setting;\n\/\/cArduino *arduino;\n\/\/\n\/\/int main() {\n\/\/\n\/\/ string file(\".\/cfg.conf\");\n\/\/ setting = new Config(file);\n\/\/ assert(setting != nullptr);\n\/\/\n\/\/ struct timeval time;\n\/\/ gettimeofday(&time, NULL);\n\/\/ srand((time.tv_sec * 1000) + (time.tv_usec \/ 1000));\n\/\/\n\/\/ string serverIP;\n\/\/ serverIP = setting->GetString(\"serverIP\", \"127.0.0.1\");\n\/\/ int port = setting->GetInt(\"serverPort\", 9999);\n\/\/ KCPSession *sess = KCPSession::Dial(serverIP.c_str(), port);\n\/\/ sess->NoDelay(1, 20, 2, 1);\n\/\/ sess->WndSize(128, 128);\n\/\/ sess->SetMtu(1400);\n\/\/ assert(sess != nullptr);\n\/\/ ssize_t nsent = {0};\n\/\/ ssize_t nrecv = {0};\n\/\/ char *buf = (char *) malloc(128);\n\/\/\n\/\/\n\/\/ char *name = (char *) \"\/dev\/ttyACM0\";\n\/\/ arduino = new cArduino(ArduinoBaundRate::B19200bps, name);\n\/\/\n\/\/\n\/\/ sprintf(buf, \"iam\");\n\/\/ sess->Write(buf, strlen(buf));\n\/\/ for (;;) {\n\/\/ sess->Update(iclock());\n\/\/ memset(buf, 0, 128);\n\/\/ ssize_t n = sess->Read(buf, 128);\n\/\/ if (n > 0) {\n\/\/\n\/\/ string msg(buf);\n\/\/ Msg pb;\n\/\/ pb.ParseFromString(msg);\n\/\/ cout << pb.content() << endl;\n\/\/ arduino->write(pb.content());\n\/\/ arduino->flush();\n\/\/ }\n\/\/ nrecv += n;\n\/\/\n\/\/ usleep(33);\n\/\/ }\n\/\/}\n\/\/\n\/\/\n\/\/void\n\/\/itimeofday(long *sec, long *usec) {\n\/\/ struct timeval time;\n\/\/ gettimeofday(&time, NULL);\n\/\/ if (sec) *sec = time.tv_sec;\n\/\/ if (usec) *usec = time.tv_usec;\n\/\/}\n\/\/\n\/\/IUINT64 iclock64(void) {\n\/\/ long s, u;\n\/\/ IUINT64 value;\n\/\/ itimeofday(&s, &u);\n\/\/ value = ((IUINT64) s) * 1000 + (u \/ 1000);\n\/\/ return value;\n\/\/}\n\/\/\n\/\/IUINT32 iclock() {\n\/\/ return (IUINT32) (iclock64() & 0xfffffffful);\n\/\/}\n<|endoftext|>"} {"text":"<commit_before>#include <unistd.h>\n#include <string>\n#include <iostream>\n#include <boost\/tokenizer.hpp>\n#include <queue>\n#include <string.h>\n\nusing namespace std;\nusing namespace boost;\n\nvoid runexec(char** argv);\t\/\/will use system calls to run the \n\t\t\t\t\t\t\t\/\/commands provided\n\nstring findconnect(string str);\t\t\/\/outputs a string of every connector\n\nqueue<string> parseline(string str);\t\t\/\/separate commands by connectors from the original string\n\n\/\/char** parsecommand(string str);\t\/\/parse the spaces from each command and output as char*\n\n\/\/vector<string> parsecommand(string str);\t\/\/parse the spaces from each command and output as a string\n\nvector<char* > parsecommand(string str);\t\/\/parse the spaces from each command and output as char*\n\nint main(int argc, char** argv) {\n\tstring input;\n\tbool end = false;\n\twhile(!end) {\n\t\tcout << \"$ \";\n\t\tgetline(cin, input);\n\t\tstring connect = findconnect(input);\t\/\/connect stores every connector\n\t\tqueue<string> cmds = parseline(input);\n\t\twhile(!cmds.empty()) {\n\t\t\tcout << \"command: \" << cmds.front() << endl;\n\t\t\tvector<string> param = parsecommand(cmds.front());\n\t\t\tfor(int i=0; i<param.size(); ++i) {\n\t\t\t\tcout << \"param: \" << param[i] << endl;\n\t\t\t}\n\t\t\tcmds.pop();\n\t\t}\n\t\texecvp(\"ls\",\"ls -a\");\n\t\t\t\n\t}\n\t\/\/first we need to parse once by \n\t\/\/using find() to determine the closest\n\t\/\/connector to the current command\n\t\/\/\n\t\/\/then we take the token and execute it\n\t\/\/\n\t\/\/then we check the connector to see if we\n\t\/\/continue running commands\n\n\n\treturn 0; \n}\n\n\/\/will use system calls to run the commands provided\nvoid runexec(char** argv) {\n\n}\n\nstring findconnect(string str) {\n\tstring out;\n\tint orcon = str.find(\"||\"); \n\tint andcon = str.find(\"&&\"); \n\tint semicon = str.find(\";\");\n\t\n\tif(orcon==-1 && andcon==-1 && semicon==-1)\t\/\/if all equal to -1, it means that \n\t\treturn \"\";\t\t\t\t\t\t\t\t\/\/there are no more connectors\n\n\tif(andcon==-1) {\t\/\/if there is no \"&&\"\n\t\tif(semicon==-1) {\n\t\t\tout.push_back('|');\n\t\t\tstr.erase(orcon,2);\n\t\t}\n\t\telse if(orcon==-1) {\n\t\t\tout.push_back(';');\n\t\t\tstr.erase(semicon,1);\n\t\t}\n\t\telse if(orcon<semicon) {\n\t\t\tout.push_back('|');\n\t\t\tstr.erase(orcon,2);\n\t\t}\n\t\telse {\n\t\t\tout.push_back(';');\n\t\t\tstr.erase(semicon,1);\n\t\t}\n\t}\n\telse if(semicon==-1) {\t\/\/if there is no \";\"\n\t\tif(andcon==-1) {\n\t\t\tout.push_back('|');\n\t\t\tstr.erase(orcon,2);\n\t\t}\n\t\telse if(orcon==-1) {\n\t\t\tout.push_back('&');\n\t\t\tstr.erase(andcon,2);\n\t\t}\n\t\telse if(orcon<andcon) {\n\t\t\tout.push_back('|');\n\t\t\tstr.erase(orcon,2);\n\t\t}\n\t\telse {\n\t\t\tout.push_back('&');\n\t\t\tstr.erase(andcon,2);\n\t\t}\n\t}\n\telse if(orcon==-1) {\t\/\/if there is no \"||\"\n\t\tif(andcon==-1) {\n\t\t\tout.push_back(';');\n\t\t\tstr.erase(semicon,1);\n\t\t}\n\t\telse if(semicon==-1) {\n\t\t\tout.push_back('&');\n\t\t\tstr.erase(andcon,2);\n\t\t}\n\t\telse if(andcon<semicon) {\n\t\t\tout.push_back('&');\n\t\t\tstr.erase(andcon,2);\n\t\t}\n\t\telse {\n\t\t\tout.push_back(';');\n\t\t\tstr.erase(semicon,1);\n\t\t}\n\t}\n\telse if(orcon<andcon) { \/\/checks which connector is the closest if all are inputted\n\t\tif(orcon<andcon) {\n\t\t\tif(orcon<semicon) {\n\t\t\t\tout.push_back('|');\n\t\t\t\tstr.erase(orcon,2);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tout.push_back(';');\n\t\t\t\tstr.erase(semicon);\n\t\t\t}\n\t\t}\n\t}\n\telse if(andcon<semicon) {\n\t\tout.push_back('&'); str.erase(andcon,2);\n\t}\n\telse {\n\t\tout.push_back(';');\n\t\tstr.erase(semicon,1);\n\t}\n\tout = out + findconnect(str);\n\treturn out;\n}\n\nqueue<string> parseline(string str) {\n\tqueue<string> out;\n\tchar_separator<char> delim(\";&|\");\n\ttokenizer< char_separator<char> > token(str, delim);\n\t\n\tfor(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {\n\t\tout.push(*i);\n\t}\n\treturn out;\n}\n\n\/\/char** parsecommand(string str) {\n\/\/\tint size = 0;\n\t\/\/tokenizer<> token(str);\n\t\/\/for(tokenizer<>::iterator i=token.begin(); i!=token.end(); ++i) {\n\t\/\/\tsize++;\n\t\/\/}\n\t\/\/char** out;\t\n\t\/\/int j = 0;\n\t\/\/for(tokenizer<>::iterator i=token.begin(); i!=token.end(); ++i) {\n\t\/\/\t*(out+j) = (*i).c_str();\n\t\/\/\t++j;\n\t\/\/}\n\t\/\/return out;\n\/\/}\n\n\/\/vector<string> parsecommand(string str) {\n\/\/\tvector<string> out;\n\/\/\tchar_separator<char> delim(\" \");\n\/\/\ttokenizer< char_separator<char> > token(str, delim);\n\/\/\tfor(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {\n\/\/\t\tout.push_back(*i);\n\/\/\t\tcout << \"*i: \" << *i << endl;\n\/\/\t}\n\/\/\treturn out;\n\/\/}\n\nvector<const char* > parsecommand(string str) {\n\tvector<const char * > out;\n\tchar_separator<char> delim(\" \");\n\ttokenizer< char_separator<char> > token(str, delim);\n\tfor(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {\n\t\tconst char* temp = new char();\n\t\ttemp = (*i).c_str();\n\t\tout.push_back(temp);\n\t\tdelete temp;\n\t}\n\tout.push_back(NULL);\n\treturn out;\n}\n\n<commit_msg>parsed each arguement in one command and can run commands<commit_after>#include <unistd.h>\n#include <stdio.h>\n#include <string>\n#include <iostream>\n#include <boost\/tokenizer.hpp>\n#include <queue>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <string.h>\n\nusing namespace std;\nusing namespace boost;\n\nvoid runexec(char** argv);\t\/\/will use system calls to run the \n\t\t\t\t\t\t\t\/\/commands provided\n\nstring findconnect(string str);\t\t\/\/outputs a string of every connector\n\nqueue<string> parseline(string str);\t\t\/\/separate commands by connectors from the original string\n\nvoid parsecommand(char** &cstrarray, string str);\t\/\/parse the spaces from each command and output as char*\n\n\/\/vector<string> parsecommand(string str);\t\/\/parse the spaces from each command and output as a string\n\n\/\/vector<const char* > parsecommand(string str);\t\/\/parse the spaces from each command and output as char*\n\n\/\/void parsecommand(vector<const char* > arg, string str);\t\/\/parse the spaces from each command and output as char*\n\n\nint main(int argc, char** argv) {\n\tstring input;\n\tbool end = false;\n\twhile(!end) {\n\t\tcout << \"$ \";\n\t\tgetline(cin, input);\n\t\tstring connect = findconnect(input);\t\/\/connect stores every connector\n\t\tqueue<string> cmds = parseline(input);\n\t\twhile(!cmds.empty()) {\n\t\t\tcout << \"command: \" << cmds.front() << endl;\n\t\t\tchar** cstr = new char*[cmds.front().size()];\n\t\t\tfor(unsigned int i=0; i<cmds.front().size(); ++i) {\n\t\t\t\tcstr[i] = (char*) malloc (cmds.front().size());\n\t\t\t}\n\t\t\tparsecommand(cstr, cmds.front());\n\t\t\trunexec(cstr);\n\t\t\t\/\/vector<const char* > param = parsecommand(cmds.front());\n\t\t\t\/\/vector<const char* > param(cmds.front().size()+1);\n\t\t\t\/\/parsecommand(param, cmds.front());\n\t\t\t\/\/for(unsigned int i=0; i<param.size(); ++i) {\n\t\t\t\t\/\/for(unsigned int j=0; (param[i][j])!='\\0'; ++j) {\n\/\/\t\t\t\t\tcout << \"param: \" << (param[i][j]) << endl;\n\t\t\t\t\/\/}\n\t\t\t\t\/\/execvp(param[0],param);\n\t\t\t\t\/\/perror(\"Didn't work\");\n\t\t\t\/\/}\n\t\t\t\/\/vector<string> test;\n\t\t\t\/\/test.push_back(\"ls \");\n\t\t\t\/\/test.push_back(\"-a \");\n\t\t\t\/\/test.push_back(\"-l\");\n\t\t\t\/\/char** troll = new char*[test.size()*2];\n\t\t\t\/\/cout << \"test.size() : \" << test.size() << endl;\n\t\t\t\/\/for(unsigned i=0; i< test.size(); ++i) {\n\t\t\t\/\/\tcout << \"Errror at \" << i << endl;\n\t\t\t\/\/\tcout << \"test[\" << i << \"] : \" << test[i] << endl;\n\t\t\t\/\/\tstrcpy(troll[i],test[i].c_str());\n\t\t\t\/\/\tcout << \"troll[\" << i << \"] : \" << troll[i] << endl;\n\t\t\t\/\/}\n\t\t\t\/\/execvp(test[0], test);\n\n\t\t\tcmds.pop();\n\t\t\t\/\/for(unsigned int i=0; i<cmds.front().size(); ++i) {\n\t\t\t\/\/\tdelete test[i];\n\t\t\t\/\/}\n\t\t\t\/\/delete [] test;\n\t\t}\n\t\t\t\n\t}\n\t\/\/first we need to parse once by \n\t\/\/using find() to determine the closest\n\t\/\/connector to the current command\n\t\/\/\n\t\/\/then we take the token and execute it\n\t\/\/\n\t\/\/then we check the connector to see if we\n\t\/\/continue running commands\n\n\n\treturn 0; \n}\n\n\/\/will use system calls to run the commands provided\nvoid runexec(char** argv) {\n\tint pid = fork();\n\tif(pid==-1 ) {\t\/\/meaning fork() returned an error\n\t\tperror(\"Error with fork().\");\n\t\texit(1);\n\t}\n\telse if(pid==0) {\t\/\/meaning we're in the child process\n\t\tcout << \"This is the child process.\" << endl;\n\t\tcout << \"argv[0] : \" << argv[0] << endl;\n\t\tif(execvp(argv[0], argv)) {\n\t\t\tperror(\"There was an error in execvp.\" );\n\t\t}\n\t\texit(1);\n\t}\n\telse if(pid>0) {\t\/\/meaning we're in the parent process\n\t\tif(wait(0)==-1) {\n\t\t\tperror(\"There was an error with wait().\" );\n\t\t}\n\t}\n}\n\nstring findconnect(string str) {\n\tstring out;\n\tint orcon = str.find(\"||\"); \n\tint andcon = str.find(\"&&\"); \n\tint semicon = str.find(\";\");\n\t\n\tif(orcon==-1 && andcon==-1 && semicon==-1)\t\/\/if all equal to -1, it means that \n\t\treturn \"\";\t\t\t\t\t\t\t\t\/\/there are no more connectors\n\n\tif(andcon==-1) {\t\/\/if there is no \"&&\"\n\t\tif(semicon==-1) {\n\t\t\tout.push_back('|');\n\t\t\tstr.erase(orcon,2);\n\t\t}\n\t\telse if(orcon==-1) {\n\t\t\tout.push_back(';');\n\t\t\tstr.erase(semicon,1);\n\t\t}\n\t\telse if(orcon<semicon) {\n\t\t\tout.push_back('|');\n\t\t\tstr.erase(orcon,2);\n\t\t}\n\t\telse {\n\t\t\tout.push_back(';');\n\t\t\tstr.erase(semicon,1);\n\t\t}\n\t}\n\telse if(semicon==-1) {\t\/\/if there is no \";\"\n\t\tif(andcon==-1) {\n\t\t\tout.push_back('|');\n\t\t\tstr.erase(orcon,2);\n\t\t}\n\t\telse if(orcon==-1) {\n\t\t\tout.push_back('&');\n\t\t\tstr.erase(andcon,2);\n\t\t}\n\t\telse if(orcon<andcon) {\n\t\t\tout.push_back('|');\n\t\t\tstr.erase(orcon,2);\n\t\t}\n\t\telse {\n\t\t\tout.push_back('&');\n\t\t\tstr.erase(andcon,2);\n\t\t}\n\t}\n\telse if(orcon==-1) {\t\/\/if there is no \"||\"\n\t\tif(andcon==-1) {\n\t\t\tout.push_back(';');\n\t\t\tstr.erase(semicon,1);\n\t\t}\n\t\telse if(semicon==-1) {\n\t\t\tout.push_back('&');\n\t\t\tstr.erase(andcon,2);\n\t\t}\n\t\telse if(andcon<semicon) {\n\t\t\tout.push_back('&');\n\t\t\tstr.erase(andcon,2);\n\t\t}\n\t\telse {\n\t\t\tout.push_back(';');\n\t\t\tstr.erase(semicon,1);\n\t\t}\n\t}\n\telse if(orcon<andcon) { \/\/checks which connector is the closest if all are inputted\n\t\tif(orcon<andcon) {\n\t\t\tif(orcon<semicon) {\n\t\t\t\tout.push_back('|');\n\t\t\t\tstr.erase(orcon,2);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tout.push_back(';');\n\t\t\t\tstr.erase(semicon);\n\t\t\t}\n\t\t}\n\t}\n\telse if(andcon<semicon) {\n\t\tout.push_back('&'); str.erase(andcon,2);\n\t}\n\telse {\n\t\tout.push_back(';');\n\t\tstr.erase(semicon,1);\n\t}\n\tout = out + findconnect(str);\n\treturn out;\n}\n\nqueue<string> parseline(string str) {\n\tqueue<string> out;\n\tchar_separator<char> delim(\";&|\");\n\ttokenizer< char_separator<char> > token(str, delim);\n\t\n\tfor(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {\n\t\tout.push(*i);\n\t}\n\treturn out;\n}\n\nvoid parsecommand(char** &cstrarray, string str) {\n\tvector<string> vecstr;\n\tchar_separator<char> delim(\" \");\n\ttokenizer< char_separator<char> > token(str, delim);\n\tunsigned int in =0;\n\tfor(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {\n\t\tvecstr.push_back(*i);\n\t\t++in;\n\t}\n\tfor(unsigned int j=0; j<vecstr.size(); ++j) {\n\t\tstrcpy(cstrarray[j], vecstr[j].c_str());\n\t}\n\tcstrarray[vecstr.size()] = '\\0';\n}\n\n\/\/vector<string> parsecommand(string str) {\n\/\/\tvector<string> out;\n\/\/\tchar_separator<char> delim(\" \");\n\/\/\ttokenizer< char_separator<char> > token(str, delim);\n\/\/\tfor(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {\n\/\/\t\tout.push_back(*i);\n\/\/\t\tcout << \"*i: \" << *i << endl;\n\/\/\t}\n\/\/\treturn out;\n\/\/}\n\n\/\/vector<const char* > parsecommand(string str) {\n\/\/void parsecommand(vector<const char* > arg, string str) {\n\/\/\tvector<string> strarray;\n\/\/\tchar_separator<char> delim(\" \");\n\/\/\ttokenizer< char_separator<char> > token(str, delim);\n\/\/\tfor(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {\n\/\/\t\tstrarray.push_back(*i);\n\/\/\t}\n\/\/\tfor(unsigned int i=0; i<strarray.size(); ++i) {\n\/\/\t\targ[i] = &(strarray[i][0]);\n\/\/\t}\n\/\/\targ[strarray.size()] = NULL;\n\/\/}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Simplified way the rigid body tree is initialized.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"Consumer.h\"\n\/\/ public methods\nndn::Consumer::Consumer(string interest_name, int interest_lifetime)\n{\n this->interest_name = interest_name;\n this->interest_lifetime = interest_lifetime;\n}\n\nndn::Consumer::~Consumer()\n{\n cout << \"Bye you cruel world\" << endl;\n}\n\n\/\/ register prefix on NFD\nvoid ndn::Consumer::run()\n{\n Interest interest(Name(this->interest_name)); \/\/ e.g. \"\/example\/testApp\/randomData\"\n interest.setInterestLifetime(time::milliseconds(this->interest_lifetime)); \/\/ time::milliseconds(1000)\n interest.setMustBeFresh(true);\n\n m_face.expressInterest(interest,\n bind(&ndn::Consumer::onData, this, _1, _2),\n bind(&ndn::Consumer::onTimeout, this, _1));\n\n cout << \"Sending \" << interest << endl;\n\n \/\/ processEvents will block until the requested data received or timeout occurs\n m_face.processEvents();\n}\n\n\n\/\/ private methods\n\/\/ react to the reception of a reply from a Producer\nvoid ndn::Consumer::onData(const Interest& interest, const Data& data)\n{\n cout << \"data-packet received: \" << endl;\n Block block;\n size_t buffer_size;\n const u_int8_t* buffer;\n\n block = data.getContent();\n buffer = block.wire();\n buffer_size = block.size();\n\n for(int i = 0; i < buffer_size; i++)\n cout << (char)buffer[i];\n}\n\n\/\/ react on the request \/ Interest timing out\nvoid ndn::Consumer::onTimeout(const Interest& interest)\n{\n cout << \"Timeout \" << interest << endl;\n}\n\n\n\/\/\n\/\/ Main entry-point\n\/\/\nint main(int argc, char** argv)\n{\n string appName = boost::filesystem::basename(argv[0]);\n\n options_description desc(\"Programm Options\");\n desc.add_options ()\n (\"name,p\", value<string>()->required (), \"The name of the interest to be sent (Required)\")\n (\"lifetime,s\", value<int>(), \"The lifetime of the interest in milliseconds. (Default 1000ms)\");\n\n positional_options_description positionalOptions;\n variables_map vm;\n\n try\n {\n store(command_line_parser(argc, argv).options(desc)\n .positional(positionalOptions).run(),\n vm); \/\/ throws on error\n\n notify(vm); \/\/notify if required parameters are not provided.\n }\n catch(boost::program_options::required_option& e)\n {\n \/\/ user forgot to provide a required option\n cerr << \"name ... The name of the interest to be sent (Required)\" << endl;\n cerr << \"lifetime ... The lifetime of the interest in milliseconds. (Default 1000ms)\" << endl;\n cerr << \"usage-example: \" << \".\/\" << appName << \" --name \/example\/testApp\/randomData\" << endl;\n cerr << \"usage-example: \" << \".\/\" << appName << \" --name \/example\/testApp\/randomData --lifetime 1000\" << endl;\n\n cerr << \"ERROR: \" << e.what() << endl << endl;\n return -1;\n }\n catch(boost::program_options::error& e)\n {\n \/\/ a given parameter is faulty (e.g. given a string, asked for int)\n cerr << \"ERROR: \" << e.what() << endl << endl;\n return -1;\n }\n catch(exception& e)\n {\n cerr << \"Unhandled Exception reached the top of main: \"\n << e.what() << \", application will now exit\" << endl;\n return -1;\n }\n\n int lifetime = 1000;\n if(vm.count (\"lifetime\"))\n {\n lifetime = vm[\"lifetime\"].as<int>();\n }\n\n \/\/ create new Consumer instance with given parameters\n ndn::Consumer consumer(vm[\"name\"].as<string>(),lifetime);\n\n try\n {\n \/\/ start producer\n consumer.run();\n }\n catch (const exception& e)\n {\n \/\/ shit happens\n cerr << \"ERROR: \" << e.what() << endl;\n }\n\n return 0;\n}\n<commit_msg>client slipsum works<commit_after>#include \"Consumer.h\"\n\/\/ public methods\nndn::Consumer::Consumer(string interest_name, int interest_lifetime)\n{\n this->interest_name = interest_name;\n this->interest_lifetime = interest_lifetime;\n}\n\nndn::Consumer::~Consumer()\n{\n cout << \"Bye you cruel world\" << endl;\n}\n\n\/\/ register prefix on NFD\nvoid ndn::Consumer::run()\n{\n Interest interest(Name(this->interest_name)); \/\/ e.g. \"\/example\/testApp\/randomData\"\n interest.setInterestLifetime(time::milliseconds(this->interest_lifetime)); \/\/ time::milliseconds(1000)\n interest.setMustBeFresh(true);\n\n m_face.expressInterest(interest,\n bind(&ndn::Consumer::onData, this, _1, _2),\n bind(&ndn::Consumer::onTimeout, this, _1));\n\n cout << \"Sending \" << interest << endl;\n\n \/\/ processEvents will block until the requested data received or timeout occurs\n m_face.processEvents();\n}\n\n\n\/\/ private methods\n\/\/ react to the reception of a reply from a Producer\nvoid ndn::Consumer::onData(const Interest& interest, const Data& data)\n{\n cout << \"data-packet received: \" << endl;\n\n const Block& block = data.getContent();\n std::cout.write((const char*)block.value(),block.value_size());\n cout << endl;\n}\n\n\/\/ react on the request \/ Interest timing out\nvoid ndn::Consumer::onTimeout(const Interest& interest)\n{\n cout << \"Timeout \" << interest << endl;\n}\n\n\n\/\/\n\/\/ Main entry-point\n\/\/\nint main(int argc, char** argv)\n{\n string appName = boost::filesystem::basename(argv[0]);\n\n options_description desc(\"Programm Options\");\n desc.add_options ()\n (\"name,p\", value<string>()->required (), \"The name of the interest to be sent (Required)\")\n (\"lifetime,s\", value<int>(), \"The lifetime of the interest in milliseconds. (Default 1000ms)\");\n\n positional_options_description positionalOptions;\n variables_map vm;\n\n try\n {\n store(command_line_parser(argc, argv).options(desc)\n .positional(positionalOptions).run(),\n vm); \/\/ throws on error\n\n notify(vm); \/\/notify if required parameters are not provided.\n }\n catch(boost::program_options::required_option& e)\n {\n \/\/ user forgot to provide a required option\n cerr << \"name ... The name of the interest to be sent (Required)\" << endl;\n cerr << \"lifetime ... The lifetime of the interest in milliseconds. (Default 1000ms)\" << endl;\n cerr << \"usage-example: \" << \".\/\" << appName << \" --name \/example\/testApp\/randomData\" << endl;\n cerr << \"usage-example: \" << \".\/\" << appName << \" --name \/example\/testApp\/randomData --lifetime 1000\" << endl;\n\n cerr << \"ERROR: \" << e.what() << endl << endl;\n return -1;\n }\n catch(boost::program_options::error& e)\n {\n \/\/ a given parameter is faulty (e.g. given a string, asked for int)\n cerr << \"ERROR: \" << e.what() << endl << endl;\n return -1;\n }\n catch(exception& e)\n {\n cerr << \"Unhandled Exception reached the top of main: \"\n << e.what() << \", application will now exit\" << endl;\n return -1;\n }\n\n int lifetime = 1000;\n if(vm.count (\"lifetime\"))\n {\n lifetime = vm[\"lifetime\"].as<int>();\n }\n\n \/\/ create new Consumer instance with given parameters\n ndn::Consumer consumer(vm[\"name\"].as<string>(),lifetime);\n\n try\n {\n \/\/ start producer\n consumer.run();\n }\n catch (const exception& e)\n {\n \/\/ shit happens\n cerr << \"ERROR: \" << e.what() << endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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 \"remoting\/host\/heartbeat_sender.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/time.h\"\n#include \"remoting\/base\/constants.h\"\n#include \"remoting\/host\/host_config.h\"\n#include \"remoting\/jingle_glue\/iq_sender.h\"\n#include \"remoting\/jingle_glue\/jingle_thread.h\"\n#include \"remoting\/jingle_glue\/signal_strategy.h\"\n#include \"third_party\/libjingle\/source\/talk\/xmllite\/xmlelement.h\"\n#include \"third_party\/libjingle\/source\/talk\/xmpp\/constants.h\"\n\nusing buzz::QName;\nusing buzz::XmlElement;\n\nnamespace remoting {\n\nnamespace {\nconst char kHeartbeatQueryTag[] = \"heartbeat\";\nconst char kHostIdAttr[] = \"hostid\";\nconst char kHeartbeatSignatureTag[] = \"signature\";\nconst char kSignatureTimeAttr[] = \"time\";\n\nconst char kHeartbeatResultTag[] = \"heartbeat-result\";\nconst char kSetIntervalTag[] = \"set-interval\";\n\nconst int64 kDefaultHeartbeatIntervalMs = 5 * 60 * 1000; \/\/ 5 minutes.\n}\n\nHeartbeatSender::HeartbeatSender(base::MessageLoopProxy* message_loop,\n MutableHostConfig* config)\n\n : state_(CREATED),\n message_loop_(message_loop),\n config_(config),\n interval_ms_(kDefaultHeartbeatIntervalMs) {\n DCHECK(config_);\n}\n\nHeartbeatSender::~HeartbeatSender() {\n DCHECK(state_ == CREATED || state_ == INITIALIZED || state_ == STOPPED);\n}\n\nbool HeartbeatSender::Init() {\n DCHECK(state_ == CREATED);\n\n if (!config_->GetString(kHostIdConfigPath, &host_id_)) {\n LOG(ERROR) << \"host_id is not defined in the config.\";\n return false;\n }\n\n if (!key_pair_.Load(config_)) {\n return false;\n }\n\n state_ = INITIALIZED;\n\n return true;\n}\n\nvoid HeartbeatSender::OnSignallingConnected(SignalStrategy* signal_strategy,\n const std::string& full_jid) {\n DCHECK(message_loop_->BelongsToCurrentThread());\n DCHECK(state_ == INITIALIZED || state_ == STOPPED);\n state_ = STARTED;\n\n full_jid_ = full_jid;\n\n iq_sender_.reset(new IqSender(signal_strategy));\n\n DoSendStanza();\n timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(interval_ms_), this,\n &HeartbeatSender::DoSendStanza);\n}\n\nvoid HeartbeatSender::OnSignallingDisconnected() {\n DCHECK(message_loop_->BelongsToCurrentThread());\n state_ = STOPPED;\n request_.reset();\n iq_sender_.reset();\n}\n\n\/\/ Ignore any notifications other than signalling\n\/\/ connected\/disconnected events.\nvoid HeartbeatSender::OnAccessDenied() { }\nvoid HeartbeatSender::OnClientAuthenticated(const std::string& jid) { }\nvoid HeartbeatSender::OnClientDisconnected(const std::string& jid) { }\nvoid HeartbeatSender::OnShutdown() { }\n\nvoid HeartbeatSender::DoSendStanza() {\n DCHECK(message_loop_->BelongsToCurrentThread());\n DCHECK_EQ(state_, STARTED);\n\n VLOG(1) << \"Sending heartbeat stanza to \" << kChromotingBotJid;\n request_.reset(iq_sender_->SendIq(\n buzz::STR_SET, kChromotingBotJid, CreateHeartbeatMessage(),\n base::Bind(&HeartbeatSender::ProcessResponse,\n base::Unretained(this))));\n}\n\nvoid HeartbeatSender::ProcessResponse(const XmlElement* response) {\n DCHECK(message_loop_->BelongsToCurrentThread());\n\n std::string type = response->Attr(buzz::QN_TYPE);\n if (type == buzz::STR_ERROR) {\n LOG(ERROR) << \"Received error in response to heartbeat: \"\n << response->Str();\n return;\n }\n\n \/\/ This method must only be called for error or result stanzas.\n DCHECK_EQ(std::string(buzz::STR_RESULT), type);\n\n const XmlElement* result_element =\n response->FirstNamed(QName(kChromotingXmlNamespace, kHeartbeatResultTag));\n if (result_element) {\n const XmlElement* set_interval_element =\n result_element->FirstNamed(QName(kChromotingXmlNamespace,\n kSetIntervalTag));\n if (set_interval_element) {\n const std::string& interval_str = set_interval_element->BodyText();\n int interval;\n if (!base::StringToInt(interval_str, &interval) || interval <= 0) {\n LOG(ERROR) << \"Received invalid set-interval: \"\n << set_interval_element->Str();\n } else {\n SetInterval(interval * base::Time::kMillisecondsPerSecond);\n }\n }\n }\n}\n\nvoid HeartbeatSender::SetInterval(int interval) {\n if (interval != interval_ms_) {\n interval_ms_ = interval;\n\n \/\/ Restart the timer with the new interval.\n if (state_ == STARTED) {\n timer_.Stop();\n timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(interval_ms_),\n this, &HeartbeatSender::DoSendStanza);\n }\n }\n}\n\nXmlElement* HeartbeatSender::CreateHeartbeatMessage() {\n XmlElement* query = new XmlElement(\n QName(kChromotingXmlNamespace, kHeartbeatQueryTag));\n query->AddAttr(QName(kChromotingXmlNamespace, kHostIdAttr), host_id_);\n query->AddElement(CreateSignature());\n return query;\n}\n\nXmlElement* HeartbeatSender::CreateSignature() {\n XmlElement* signature_tag = new XmlElement(\n QName(kChromotingXmlNamespace, kHeartbeatSignatureTag));\n\n int64 time = static_cast<int64>(base::Time::Now().ToDoubleT());\n std::string time_str(base::Int64ToString(time));\n signature_tag->AddAttr(\n QName(kChromotingXmlNamespace, kSignatureTimeAttr), time_str);\n\n std::string message = full_jid_ + ' ' + time_str;\n std::string signature(key_pair_.GetSignature(message));\n signature_tag->AddText(signature);\n\n return signature_tag;\n}\n\n} \/\/ namespace remoting\n<commit_msg>Stop heartbeat timer when signalling is disconnected.<commit_after>\/\/ Copyright (c) 2011 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 \"remoting\/host\/heartbeat_sender.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/time.h\"\n#include \"remoting\/base\/constants.h\"\n#include \"remoting\/host\/host_config.h\"\n#include \"remoting\/jingle_glue\/iq_sender.h\"\n#include \"remoting\/jingle_glue\/jingle_thread.h\"\n#include \"remoting\/jingle_glue\/signal_strategy.h\"\n#include \"third_party\/libjingle\/source\/talk\/xmllite\/xmlelement.h\"\n#include \"third_party\/libjingle\/source\/talk\/xmpp\/constants.h\"\n\nusing buzz::QName;\nusing buzz::XmlElement;\n\nnamespace remoting {\n\nnamespace {\nconst char kHeartbeatQueryTag[] = \"heartbeat\";\nconst char kHostIdAttr[] = \"hostid\";\nconst char kHeartbeatSignatureTag[] = \"signature\";\nconst char kSignatureTimeAttr[] = \"time\";\n\nconst char kHeartbeatResultTag[] = \"heartbeat-result\";\nconst char kSetIntervalTag[] = \"set-interval\";\n\nconst int64 kDefaultHeartbeatIntervalMs = 5 * 60 * 1000; \/\/ 5 minutes.\n}\n\nHeartbeatSender::HeartbeatSender(base::MessageLoopProxy* message_loop,\n MutableHostConfig* config)\n\n : state_(CREATED),\n message_loop_(message_loop),\n config_(config),\n interval_ms_(kDefaultHeartbeatIntervalMs) {\n DCHECK(config_);\n}\n\nHeartbeatSender::~HeartbeatSender() {\n DCHECK(state_ == CREATED || state_ == INITIALIZED || state_ == STOPPED);\n}\n\nbool HeartbeatSender::Init() {\n DCHECK(state_ == CREATED);\n\n if (!config_->GetString(kHostIdConfigPath, &host_id_)) {\n LOG(ERROR) << \"host_id is not defined in the config.\";\n return false;\n }\n\n if (!key_pair_.Load(config_)) {\n return false;\n }\n\n state_ = INITIALIZED;\n\n return true;\n}\n\nvoid HeartbeatSender::OnSignallingConnected(SignalStrategy* signal_strategy,\n const std::string& full_jid) {\n DCHECK(message_loop_->BelongsToCurrentThread());\n DCHECK(state_ == INITIALIZED || state_ == STOPPED);\n state_ = STARTED;\n\n full_jid_ = full_jid;\n\n iq_sender_.reset(new IqSender(signal_strategy));\n\n DoSendStanza();\n timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(interval_ms_), this,\n &HeartbeatSender::DoSendStanza);\n}\n\nvoid HeartbeatSender::OnSignallingDisconnected() {\n DCHECK(message_loop_->BelongsToCurrentThread());\n state_ = STOPPED;\n request_.reset();\n iq_sender_.reset();\n timer_.Stop();\n}\n\n\/\/ Ignore any notifications other than signalling\n\/\/ connected\/disconnected events.\nvoid HeartbeatSender::OnAccessDenied() { }\nvoid HeartbeatSender::OnClientAuthenticated(const std::string& jid) { }\nvoid HeartbeatSender::OnClientDisconnected(const std::string& jid) { }\nvoid HeartbeatSender::OnShutdown() { }\n\nvoid HeartbeatSender::DoSendStanza() {\n DCHECK(message_loop_->BelongsToCurrentThread());\n DCHECK_EQ(state_, STARTED);\n\n VLOG(1) << \"Sending heartbeat stanza to \" << kChromotingBotJid;\n request_.reset(iq_sender_->SendIq(\n buzz::STR_SET, kChromotingBotJid, CreateHeartbeatMessage(),\n base::Bind(&HeartbeatSender::ProcessResponse,\n base::Unretained(this))));\n}\n\nvoid HeartbeatSender::ProcessResponse(const XmlElement* response) {\n DCHECK(message_loop_->BelongsToCurrentThread());\n\n std::string type = response->Attr(buzz::QN_TYPE);\n if (type == buzz::STR_ERROR) {\n LOG(ERROR) << \"Received error in response to heartbeat: \"\n << response->Str();\n return;\n }\n\n \/\/ This method must only be called for error or result stanzas.\n DCHECK_EQ(std::string(buzz::STR_RESULT), type);\n\n const XmlElement* result_element =\n response->FirstNamed(QName(kChromotingXmlNamespace, kHeartbeatResultTag));\n if (result_element) {\n const XmlElement* set_interval_element =\n result_element->FirstNamed(QName(kChromotingXmlNamespace,\n kSetIntervalTag));\n if (set_interval_element) {\n const std::string& interval_str = set_interval_element->BodyText();\n int interval;\n if (!base::StringToInt(interval_str, &interval) || interval <= 0) {\n LOG(ERROR) << \"Received invalid set-interval: \"\n << set_interval_element->Str();\n } else {\n SetInterval(interval * base::Time::kMillisecondsPerSecond);\n }\n }\n }\n}\n\nvoid HeartbeatSender::SetInterval(int interval) {\n if (interval != interval_ms_) {\n interval_ms_ = interval;\n\n \/\/ Restart the timer with the new interval.\n if (state_ == STARTED) {\n timer_.Stop();\n timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(interval_ms_),\n this, &HeartbeatSender::DoSendStanza);\n }\n }\n}\n\nXmlElement* HeartbeatSender::CreateHeartbeatMessage() {\n XmlElement* query = new XmlElement(\n QName(kChromotingXmlNamespace, kHeartbeatQueryTag));\n query->AddAttr(QName(kChromotingXmlNamespace, kHostIdAttr), host_id_);\n query->AddElement(CreateSignature());\n return query;\n}\n\nXmlElement* HeartbeatSender::CreateSignature() {\n XmlElement* signature_tag = new XmlElement(\n QName(kChromotingXmlNamespace, kHeartbeatSignatureTag));\n\n int64 time = static_cast<int64>(base::Time::Now().ToDoubleT());\n std::string time_str(base::Int64ToString(time));\n signature_tag->AddAttr(\n QName(kChromotingXmlNamespace, kSignatureTimeAttr), time_str);\n\n std::string message = full_jid_ + ' ' + time_str;\n std::string signature(key_pair_.GetSignature(message));\n signature_tag->AddText(signature);\n\n return signature_tag;\n}\n\n} \/\/ namespace remoting\n<|endoftext|>"} {"text":"<commit_before>#include <allegro5\/allegro5.h>\n#include <allegro5\/allegro_image.h>\n#include \"player.h\"\n\nint main()\n{\t\n\tal_init();\n\n\tal_init_image_addon();\n\n\tALLEGRO_DISPLAY *display;\n\tal_set_new_display_flags(ALLEGRO_WINDOWED);\n\tdisplay = al_create_display(800, 600);\n\t\n\tal_install_keyboard();\n\n\tALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();\n\tal_register_event_source(event_queue, (ALLEGRO_EVENT_SOURCE *)display);\n\tal_register_event_source(event_queue, al_get_keyboard_event_source());\n\n\tPlayer player;\n\tplayer.Set_position(20, al_get_display_height(display));\n\n\tfloat last_update = al_current_time();\n\tfloat dt;\n\n\twhile(1)\n\t{\n\t\tfloat current_time = al_current_time();\n\t\tdt = current_time - last_update;\n\t\tlast_update = current_time;\n\t\t\n\t\tALLEGRO_EVENT event;\n\t\tif (al_get_next_event(event_queue, &event))\n\t\t{\n\t\t\tif (ALLEGRO_EVENT_DISPLAY_CLOSE == event.type)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tplayer.Event(event);\n\t\t}\n\t\t\n\t\tplayer.Update(dt);\n\n\t\tplayer.Draw();\n\t\tal_flip_display();\n\t\tal_clear_to_color(al_map_rgb(0, 0, 0));\n\n\t\tal_rest(0.001);\n\t}\n\n\tal_destroy_event_queue(event_queue);\n\tal_destroy_display(display);\n}\n<commit_msg>Added ESC to quit.<commit_after>#include <allegro5\/allegro5.h>\n#include <allegro5\/allegro_image.h>\n#include \"player.h\"\n\nint main()\n{\t\n\tal_init();\n\n\tal_init_image_addon();\n\n\tALLEGRO_DISPLAY *display;\n\tal_set_new_display_flags(ALLEGRO_WINDOWED);\n\tdisplay = al_create_display(800, 600);\n\t\n\tal_install_keyboard();\n\n\tALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();\n\tal_register_event_source(event_queue, (ALLEGRO_EVENT_SOURCE *)display);\n\tal_register_event_source(event_queue, al_get_keyboard_event_source());\n\n\tPlayer player;\n\tplayer.Set_position(20, al_get_display_height(display));\n\n\tfloat last_update = al_current_time();\n\tfloat dt;\n\n\twhile(1)\n\t{\n\t\tfloat current_time = al_current_time();\n\t\tdt = current_time - last_update;\n\t\tlast_update = current_time;\n\t\t\n\t\tALLEGRO_EVENT event;\n\t\tif (al_get_next_event(event_queue, &event))\n\t\t{\n\t\t\tif (ALLEGRO_EVENT_DISPLAY_CLOSE == event.type ||\n\t\t\t\t\tALLEGRO_EVENT_KEY_DOWN == event.type &&\n\t\t\t\t\tALLEGRO_KEY_ESCAPE == event.keyboard.keycode)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tplayer.Event(event);\n\t\t}\n\t\t\n\t\tplayer.Update(dt);\n\n\t\tplayer.Draw();\n\t\tal_flip_display();\n\t\tal_clear_to_color(al_map_rgb(0, 0, 0));\n\n\t\tal_rest(0.001);\n\t}\n\n\tal_destroy_event_queue(event_queue);\n\tal_destroy_display(display);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* The MIT License (MIT)\n *\n * Copyright (c) 2014 Colin Wallace\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 all\n * 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 THE\n * SOFTWARE.\n *\/\n \n\/* \n * Printipi\/main.cpp\n *\n * main is the program's main entry point.\n * main handles command line arguments, and instantiates the serial communications, State, and machine-specific driver.\n * Driver type is passed into this compilation unit as a command-line argument (gcc -DMACHINE=...)\n *\n * Printipi Github repository: https:\/\/github.com\/Wallacoloo\/printipi\/\n * Printipi Google Group (forum): https:\/\/groups.google.com\/forum\/#!forum\/printipi\n *\n * Miscellaneous Printipi discussions:\n * http:\/\/forums.reprap.org\/read.php?2,396157\n * https:\/\/groups.google.com\/forum\/#!searchin\/deltabot\/wallacoloo|sort:relevance\/deltabot\/JQNpmnlYYUc\/_6V6SYcOGMUJ\n * http:\/\/youtube.com\/watch?v=g4UD5MRas3E\n * http:\/\/youtube.com\/watch?v=gAruwqOEuPs\n *\/\n\n#define COMPILING_MAIN \/\/used elsewhere to do one-time warnings, etc.\n\n#include \"compileflags.h\"\n\n\/\/Includes for the CATCH testing framework\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n\n#include <string>\n#include <sys\/mman.h> \/\/for mlockall\n#include <iostream> \/\/for std::cin\n#include \"common\/logging.h\"\n\n#include \"gparse\/com.h\"\n#include \"state.h\"\n#include \"argparse.h\"\n#include \"filesystem.h\"\n\n\/\/MACHINE_PATH is calculated in the Makefile and then passed as a define through the make system (ie gcc -DMACHINEPATH='\"path\"')\n\/\/To set the path, call make MACHINE_PATH=...\n\/\/or, call make MACHINE=<machine>, eg MACHINE=rpi::KosselPi (case-sensitive) and the path will be calculated from that (src\/machines\/rpi\/kossel.h)\n#include MACHINE_PATH\n\n\n#define STRINGIFY_(x) #x\n#define STRINGIFY(x) STRINGIFY_(x)\n\nstatic void printUsage(char* cmd) {\n \/\/#ifndef NO_USAGE_INFO\n LOGE(\"usage: %s [input-file] [output-file] [--help] [--quiet] [--verbose] [--do-tests [CATCH-arguments ...] ]\\n\", cmd);\n LOGE(\" if input-file is not provided, it defaults to stdin\\n\");\n LOGE(\" if output-file is not provided, it defaults to strout\\n\");\n LOGE(\" --do-tests is only recognized if program was compiled with ENABLE_TESTS=1\\n\");\n LOGE(\"examples:\\n\");\n LOGE(\" print a gcode file: %s file.gcode\\n\", cmd);\n LOGE(\" mock serial port: %s \/dev\/tty3dpm \/dev\/tty3dps\\n\", cmd);\n}\n\nint main_(int argc, char **argv) {\n \/\/useful to setup fail-safe exit routines first-thing for catching debug info.\n SchedulerBase::configureExitHandlers(); \n \n if (argparse::cmdOptionExists(argv, argv+argc, \"--quiet\")) {\n logging::disable();\n }\n if (argparse::cmdOptionExists(argv, argv+argc, \"--debug\")) {\n logging::enableDebug();\n }\n if (argparse::cmdOptionExists(argv, argv+argc, \"--verbose\")) {\n logging::enableVerbose();\n }\n if (argparse::cmdOptionExists(argv, argv+argc, \"-h\") || argparse::cmdOptionExists(argv, argv+argc, \"--help\")) {\n printUsage(argv[0]);\n return 0;\n } \n LOG(\"Printipi: built for machine: '\" STRINGIFY(MACHINE) \"'\\n\");\n \n char* fsRootArg = argparse::getArgumentForCmdOption(argv, argv+argc, \"--fsroot\");\n std::string fsRoot = fsRootArg ? std::string(fsRootArg) : \"\/\";\n LOG(\"Filesystem root: %s\\n\", fsRoot.c_str());\n FileSystem fs(fsRoot);\n\n #if ENABLE_TESTS\n int doTestsArgIdx = argparse::getCmdOptionIdx(argv, argv+argc, \"--do-tests\");\n if (doTestsArgIdx != -1) {\n \/\/ prepare arguments for the test suite:\n \/\/ place argv[0] (executable path) at current index, overwriting --do-tests\n \/\/ and modify argc & argv.\n argv[doTestsArgIdx] = argv[0];\n argc -= doTestsArgIdx;\n int result = Catch::Session().run(argc, argv);\n return result;\n }\n #endif\n\n \/\/ run the normal program\n gparse::Com com;\n \/\/if input is stdin, or a two-way pipe, then it likely means we want to keep that channel open forever\n \/\/ whereas if it's a gcode file, then calls to M32 (print from file) should pause the original input file\n bool keepPersistentCom = false;\n\n \/\/if no arguments, or if first argument (and therefore all args) is an option, \n \/\/ then take gcode commands from stdin\n if (argc < 2 || argv[1][0] == '-') { \n \/\/std::cin does not allow to check if there are characters to be read, whereas \/dev\/stdin DOES.\n \/\/ we need nonblocking I\/O, so this is crucial.\n \/\/com = std::move(gparse::Com(gparse::Com::shareOwnership(&std::cin)));\n com = std::move(gparse::Com(\"\/dev\/stdin\"));\n \/\/reading from stdin; want to keep that channel active even when printing from file, etc.\n keepPersistentCom = true;\n } else {\n \/\/otherwise, first parameter must be a filename from which to read gcode commands\n \/\/second argument is for the output file\n if (argc > 2 && argv[2][0] != '-') { \n com = std::move(gparse::Com(std::string(argv[1]), std::string(argv[2])));\n \/\/hints at a dual-way pipe (host <-> firmware communication); preserve communiation channel to host\n keepPersistentCom = true;\n } else {\n \/\/no second file; just read from the supplied input file\n com = std::move(gparse::Com(std::string(argv[1])));\n }\n }\n \n \/\/prevent page-swaps to increase performace:\n int retval = mlockall(MCL_FUTURE|MCL_CURRENT);\n if (retval) {\n LOGW(\"Warning: mlockall (prevent memory swaps) in main.cpp::main() returned non-zero: %i\\n\", retval);\n }\n \n State<machines::MACHINE> state(machines::MACHINE(), fs, keepPersistentCom);\n state.addComChannel(std::move(com));\n state.eventLoop();\n return 0;\n}\n\nint main(int argc, char** argv) {\n try { \/\/wrap in a try\/catch loop so we can safely clean up (disable IOs)\n return main_(argc, argv);\n } catch (const std::exception *e) {\n LOGE(\"caught std::exception*: %s. ... Exiting\\n\", e->what());\n #if CLEAN_EXIT\n return 1; \/\/don't rethrow exceptions; return an error code instead\n #endif\n throw;\n } catch (const std::exception &e) {\n LOGE(\"caught std::exception&: %s. ... Exiting\\n\", e.what());\n #if CLEAN_EXIT\n return 1; \/\/don't rethrow exceptions; return an error code instead\n #endif\n throw;\n } catch (...) {\n LOGE(\"caught unknown exception. Exiting\\n\");\n #if CLEAN_EXIT\n return 1; \/\/don't rethrow exceptions; return an error code instead\n #endif\n throw;\n }\n}\n\n<commit_msg>Fix command line parsing with Catch (--do-tests)<commit_after>\/* The MIT License (MIT)\n *\n * Copyright (c) 2014 Colin Wallace\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 all\n * 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 THE\n * SOFTWARE.\n *\/\n \n\/* \n * Printipi\/main.cpp\n *\n * main is the program's main entry point.\n * main handles command line arguments, and instantiates the serial communications, State, and machine-specific driver.\n * Driver type is passed into this compilation unit as a command-line argument (gcc -DMACHINE=...)\n *\n * Printipi Github repository: https:\/\/github.com\/Wallacoloo\/printipi\/\n * Printipi Google Group (forum): https:\/\/groups.google.com\/forum\/#!forum\/printipi\n *\n * Miscellaneous Printipi discussions:\n * http:\/\/forums.reprap.org\/read.php?2,396157\n * https:\/\/groups.google.com\/forum\/#!searchin\/deltabot\/wallacoloo|sort:relevance\/deltabot\/JQNpmnlYYUc\/_6V6SYcOGMUJ\n * http:\/\/youtube.com\/watch?v=g4UD5MRas3E\n * http:\/\/youtube.com\/watch?v=gAruwqOEuPs\n *\/\n\n#define COMPILING_MAIN \/\/used elsewhere to do one-time warnings, etc.\n\n#include \"compileflags.h\"\n\n\/\/Includes for the CATCH testing framework\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n\n#include <string>\n#include <sys\/mman.h> \/\/for mlockall\n#include <iostream> \/\/for std::cin\n#include \"common\/logging.h\"\n\n#include \"gparse\/com.h\"\n#include \"state.h\"\n#include \"argparse.h\"\n#include \"filesystem.h\"\n\n\/\/MACHINE_PATH is calculated in the Makefile and then passed as a define through the make system (ie gcc -DMACHINEPATH='\"path\"')\n\/\/To set the path, call make MACHINE_PATH=...\n\/\/or, call make MACHINE=<machine>, eg MACHINE=rpi::KosselPi (case-sensitive) and the path will be calculated from that (src\/machines\/rpi\/kossel.h)\n#include MACHINE_PATH\n\n\n#define STRINGIFY_(x) #x\n#define STRINGIFY(x) STRINGIFY_(x)\n\nstatic void printUsage(char* cmd) {\n \/\/#ifndef NO_USAGE_INFO\n LOGE(\"usage: %s [input-file] [output-file] [--help] [--quiet] [--verbose] [--do-tests [CATCH-arguments ...] ]\\n\", cmd);\n LOGE(\" if input-file is not provided, it defaults to stdin\\n\");\n LOGE(\" if output-file is not provided, it defaults to strout\\n\");\n LOGE(\" --do-tests is only recognized if program was compiled with ENABLE_TESTS=1\\n\");\n LOGE(\"examples:\\n\");\n LOGE(\" print a gcode file: %s file.gcode\\n\", cmd);\n LOGE(\" mock serial port: %s \/dev\/tty3dpm \/dev\/tty3dps\\n\", cmd);\n}\n\nint main_(int fullArgc, char **argv) {\n \/\/useful to setup fail-safe exit routines first-thing for catching debug info.\n SchedulerBase::configureExitHandlers(); \n \/\/ alter argc in order to ignore everything after \"--do-tests\"\n int doTestsArgIdx = argparse::getCmdOptionIdx(argv, argv+fullArgc, \"--do-tests\");\n int argc = (doTestsArgIdx == -1) ? fullArgc : doTestsArgIdx;\n if (argparse::cmdOptionExists(argv, argv+argc, \"--quiet\")) {\n logging::disable();\n }\n if (argparse::cmdOptionExists(argv, argv+argc, \"--debug\")) {\n logging::enableDebug();\n }\n if (argparse::cmdOptionExists(argv, argv+argc, \"--verbose\")) {\n logging::enableVerbose();\n }\n if (argparse::cmdOptionExists(argv, argv+argc, \"-h\") || argparse::cmdOptionExists(argv, argv+argc, \"--help\")) {\n printUsage(argv[0]);\n return 0;\n } \n LOG(\"Printipi: built for machine: '\" STRINGIFY(MACHINE) \"'\\n\");\n \n char* fsRootArg = argparse::getArgumentForCmdOption(argv, argv+argc, \"--fsroot\");\n std::string fsRoot = fsRootArg ? std::string(fsRootArg) : \"\/\";\n LOG(\"Filesystem root: %s\\n\", fsRoot.c_str());\n FileSystem fs(fsRoot);\n\n #if ENABLE_TESTS\n if (doTestsArgIdx != -1) {\n \/\/ prepare arguments for the test suite:\n \/\/ place argv[0] (executable path) at current index, overwriting --do-tests\n \/\/ and modify argc & argv.\n argv[doTestsArgIdx] = argv[0];\n int numToPass = fullArgc - doTestsArgIdx;\n int result = Catch::Session().run(numToPass, &argv[doTestsArgIdx]);\n return result;\n }\n #endif\n\n \/\/ run the normal program\n gparse::Com com;\n \/\/if input is stdin, or a two-way pipe, then it likely means we want to keep that channel open forever\n \/\/ whereas if it's a gcode file, then calls to M32 (print from file) should pause the original input file\n bool keepPersistentCom = false;\n\n \/\/if no arguments, or if first argument (and therefore all args) is an option, \n \/\/ then take gcode commands from stdin\n if (argc < 2 || argv[1][0] == '-') { \n \/\/std::cin does not allow to check if there are characters to be read, whereas \/dev\/stdin DOES.\n \/\/ we need nonblocking I\/O, so this is crucial.\n \/\/com = std::move(gparse::Com(gparse::Com::shareOwnership(&std::cin)));\n com = std::move(gparse::Com(\"\/dev\/stdin\"));\n \/\/reading from stdin; want to keep that channel active even when printing from file, etc.\n keepPersistentCom = true;\n } else {\n \/\/otherwise, first parameter must be a filename from which to read gcode commands\n \/\/second argument is for the output file\n if (argc > 2 && argv[2][0] != '-') { \n com = std::move(gparse::Com(std::string(argv[1]), std::string(argv[2])));\n \/\/hints at a dual-way pipe (host <-> firmware communication); preserve communiation channel to host\n keepPersistentCom = true;\n } else {\n \/\/no second file; just read from the supplied input file\n com = std::move(gparse::Com(std::string(argv[1])));\n }\n }\n \n \/\/prevent page-swaps to increase performace:\n int retval = mlockall(MCL_FUTURE|MCL_CURRENT);\n if (retval) {\n LOGW(\"Warning: mlockall (prevent memory swaps) in main.cpp::main() returned non-zero: %i\\n\", retval);\n }\n \n State<machines::MACHINE> state(machines::MACHINE(), fs, keepPersistentCom);\n state.addComChannel(std::move(com));\n state.eventLoop();\n return 0;\n}\n\nint main(int argc, char** argv) {\n try { \/\/wrap in a try\/catch loop so we can safely clean up (disable IOs)\n return main_(argc, argv);\n } catch (const std::exception *e) {\n LOGE(\"caught std::exception*: %s. ... Exiting\\n\", e->what());\n #if CLEAN_EXIT\n return 1; \/\/don't rethrow exceptions; return an error code instead\n #endif\n throw;\n } catch (const std::exception &e) {\n LOGE(\"caught std::exception&: %s. ... Exiting\\n\", e.what());\n #if CLEAN_EXIT\n return 1; \/\/don't rethrow exceptions; return an error code instead\n #endif\n throw;\n } catch (...) {\n LOGE(\"caught unknown exception. Exiting\\n\");\n #if CLEAN_EXIT\n return 1; \/\/don't rethrow exceptions; return an error code instead\n #endif\n throw;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <queue>\n#include <sys\/wait.h>\n#include <sys\/types.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include \"Shell.h\"\n#include \"Input.h\"\n\nusing namespace std;\n\nint main() {\n Input in;\n queue<string> tasks;\n \n \/\/ to exit while loop, user must type exit \n while(1) {\n\n in.getInput();\n \/\/ bool test = in.isTest();\n \/\/ cout << \"test: \" << test << endl;\n \/\/ exit(0);\n tasks = in.Parse();\n\n cout << \"size: \" << tasks.size() << endl;\n\n while (tasks.size() != 0) {\n cout << tasks.front() << endl;\n tasks.pop();\n }\n\n exit(0);\n \n \/\/ bool determines whether command was successful\n bool comp_status = true;\n char** c;\n Execute ex;\n while (tasks.size() != 0) {\n \n \/\/ if at any point the user has exit\n if (tasks.front() == \"exit\") {\n cout << \"You have exited shell.\" << endl;\n exit(0);\n }\n\n \/\/------------------------------------------------------------------\n\n else if (tasks.front() == \"&&\") {\n\t tasks.pop(); \/\/gets rid of the &&\n \/\/ if the command before this one does returns F,then dont do\n \/\/ \/\/the next command\n\t if(comp_status == false) {\n\t\t \/\/ so the && connector should have already been deleted,\n \/\/ this is a while loop to\n \/\/ delete the next commands so that they wont run if\n \/\/ the command before fails \n\t\t if(tasks.size() != 0) {\n\t\t\t if(tasks.front() != \"&&\" || tasks.front() != \"||\" ||\n tasks.front() != \";\") {\n\t\t\t\t tasks.pop();\n\t\t\t }\n\t\t }\n\t }\n }\n \/\/------------------------------------------------------------------\n\n\n else if (tasks.front() == \"||\") {\n\t\t tasks.pop(); \/\/ gets rid of the || \n\t\t if(comp_status == true) {\n\t\t\t if(tasks.size() != 0) {\n\t\t\t \t if (tasks.front() != \"&&\" || tasks.front() != \"||\" ||\n tasks.front() != \";\") {\n\t\t\t\t \t tasks.pop();\n\t\t\t \t }\n\t\t \t } \n\t\t }\n\t }\n \n \/\/ simply pop the semicolon and continue looping\n\t else if (tasks.front() == \";\") {\n tasks.pop();\n\t }\n\n\n \/\/-----------------------------------------------------------------\n\n \/\/ task was not a connector, and therefore a command \n else { \n c = in.toChar(tasks.front());\n ex.execute(c, comp_status);\n\t tasks.pop();\n\t }\n \n }\n cout << flush;\n\n }\n\n return 0;\n}\n<commit_msg>working on parentheses in main<commit_after>#include <iostream>\n#include <queue>\n#include <sys\/wait.h>\n#include <sys\/types.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include \"Shell.h\"\n#include \"Input.h\"\n\nusing namespace std;\n\nint main() {\n Input in;\n queue<string> tasks;\n \n \/\/ to exit while loop, user must type exit \n while(1) {\n\n in.getInput();\n \/\/ bool test = in.isTest();\n \/\/ cout << \"test: \" << test << endl;\n \/\/ exit(0);\n tasks = in.Parse();\n\n cout << \"size: \" << tasks.size() << endl;\n\n while (tasks.size() != 0) {\n cout << tasks.front() << endl;\n tasks.pop();\n }\n\n exit(0);\n \n \/\/ bool determines whether command was successful\n bool comp_status = true;\n char** c;\n\tint num = 0;\n Execute ex;\n while (tasks.size() != 0) {\n \n \/\/ if at any point the user has exit\n if (tasks.front() == \"exit\") {\n cout << \"You have exited shell.\" << endl;\n exit(0);\n }\n\n \/\/------------------------------------------------------------------\n\n else if (tasks.front() == \"&&\") {\n\t tasks.pop(); \/\/gets rid of the &&\n \/\/ if the command before this one does returns F,then dont do\n \/\/ \/\/the next command\n\t if(comp_status == false) {\n\t\t \/\/ so the && connector should have already been deleted,\n \/\/ this is a while loop to\n \/\/ delete the next commands so that they wont run if\n \/\/ the command before fails \n\t\t if(tasks.size() != 0) {\n\t\t\t if(tasks.front() != \"&&\" || tasks.front() != \"||\" ||\n tasks.front() != \";\") {\n\t\t\t\t tasks.pop();\n\t\t\t }\n\t\t }\n\t }\n }\n \/\/------------------------------------------------------------------\n\n\n else if (tasks.front() == \"||\") {\n\t\t tasks.pop(); \/\/ gets rid of the || \n\t\t if(comp_status == true) {\n\t\t\t if(tasks.size() != 0) {\n\t\t\t \t if (tasks.front() != \"&&\" || tasks.front() != \"||\" ||\n tasks.front() != \";\") {\n\t\t\t\t \t tasks.pop();\n\t\t\t \t }\n\t\t \t } \n\t\t }\n\t }\n \n \/\/ simply pop the semicolon and continue looping\n\t else if (tasks.front() == \";\") {\n\t\t tasks.pop();\n\t }\n\n\t \/\/------------------------------------------------------------------\n\t \n\t else if (tasks.front() == \"(\") {\n\t\t \/\/ gets rid of (\n\t\t tasks.pop();\n\t\t \n\n\n\n \/\/-----------------------------------------------------------------\n\n \/\/ task was not a connector, and therefore a command \n else { \n c = in.toChar(tasks.front());\n ex.execute(c, comp_status);\n\t tasks.pop();\n\t }\n \n }\n cout << flush;\n\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include\t<cstdlib>\n#include\t<cmath>\n#include\t<fstream>\n#include\t<sstream>\n#include\t<iostream>\n#include\t<iomanip>\n#include\t<string>\n#include\t<vector>\n#include\t<algorithm>\n#include\t<exception>\n#include\t<sys\/time.h>\n#include\t\"modules\/htmTree.h\"\n#include\t\"modules\/kdTree.h\"\n#include \"misc.h\"\n#include \"feat.h\"\n#include \"structs.h\"\n#include \"collision.h\"\n#include \"global.h\"\n\/\/reduce redistributes, updates 07\/02\/15 rnc\nint main(int argc, char **argv) {\n\t\/\/\/\/ Initializations ---------------------------------------------\n\tsrand48(1234); \/\/ Make sure we have reproducability\n\tcheck_args(argc);\n\tTime t, time; \/\/ t for global, time for local\n\tinit_time(t);\n\tFeat F;\n\n\t\/\/ Read parameters file \/\/\n\tF.readInputFile(argv[1]);\n\tprintFile(argv[1]);\n\t\/\/ Read galaxies\n\tGals G;\n if(F.Ascii){\n G=read_galaxies_ascii(F);}\n else{\n G = read_galaxies(F);\n }\n\tF.Ngal = G.size();\n\tprintf(\"# Read %s galaxies from %s \\n\",f(F.Ngal).c_str(),F.galFile.c_str());\n std::vector<int> count;\n count=count_galaxies(G);\n for(int i=0;i<8;i++){printf (\" %d \\n\",count[i]);}\n \/\/ make MTL\n MTL M=make_MTL(G,F);\n for(int i=0;i<M.priority_list.size();++i){\n printf(\" priority %d\",M.priority_list[i]);\n }\n printf(\" \\n\");\n assign_priority_class(M);\n \/\/find available SS and SF galaxies on each petal\n \n std::vector <int> count_class(M.priority_list.size(),0);\n for(int i;i<M.size();++i){\n count_class[M[i].priority_class]+=1;\n }\n for(int i;i<M.priority_list.size();++i){\n printf(\" class %d number %d\\n\",i,count_class[i]);\n }\n \n printf(\" number of MTL galaxies %d\\n\",M.size());\n printf(\"Read fiber center positions and compute related things\\n\");\n\tPP pp;\n\tpp.read_fiber_positions(F); \n\tF.Nfiber = pp.fp.size()\/2; \n\tF.Npetal = max(pp.spectrom)+1;\n printf(\"spectrometer has to be identified from 0 to F.Npetal-1\\n\");\n\tF.Nfbp = (int) (F.Nfiber\/F.Npetal);\/\/ fibers per petal = 500\n\tpp.get_neighbors(F); pp.compute_fibsofsp(F);\n printf(\"get neighbors of each fiber;\\n\");\n \/\/for each spectrometer, get list of fibers\n\n printf(\"Read plates in order they are to be observed\\n \");\n \n\tPlates P_original = read_plate_centers(F);\n F.Nplate=P_original.size();\n printf(\"This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\\n\");\n Plates P;\n P.resize(F.Nplate);\/\/don't permute plates\n\/* List permut = random_permut(F.Nplate);\n for (int jj=0; jj<F.Nplate; jj++){\n P[jj]=P_original[permut[jj]];\n }\n *\/\n P=P_original;\n\tprintf(\"# Read %s plate centers from %s and %d fibers from %s\\n\",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());\n \/\/diagnostic\n for (int j=0;j<F.Nplate;++j){\n printf(\"\\n j= %d \",j);\n for (int p=0;p<10;++p){\n printf(\" %d \",P[j].SS_av_gal[p].size());\n }\n\n }\n\t\/\/ Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions\n\tF.cb = create_cb(); \/\/ cb=central body\n\tF.fh = create_fh(); \/\/ fh=fiber holder\n\n\t\/\/\/\/ Collect available galaxies <-> tilefibers --------------------\n\t\/\/ HTM Tree of galaxies\n\tconst double MinTreeSize = 0.01;\n\tinit_time_at(time,\"# Start building HTM tree\",t);\n\thtmTree<struct target> T(M,MinTreeSize);\n\tprint_time(time,\"# ... took :\");\/\/T.stats();\n\t\n\t\/\/ For plates\/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]\n\tcollect_galaxies_for_all(M,T,P,pp,F);\n\n \n \n \n\t\/\/ For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]\n\tcollect_available_tilefibers(M,P,F);\n\n\t\/\/results_on_inputs(\"doc\/figs\/\",G,P,F,true);\n\n\t\/\/\/\/ Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||\n printf(\"before assignment\\n\");\n\tAssignment A(M,F);\n\tprint_time(t,\"# Start assignment at : \");\n\n\t\/\/ Make a plan ----------------------------------------------------\n\t\/\/new_assign_fibers(G,P,pp,F,A); \/\/ Plans whole survey without sky fibers, standard stars\n \/\/ assumes maximum number of observations needed for QSOs, LRGs\n printf(\" Nplate %d Ngal %d Nfiber %d \\n\", F.Nplate, F.Ngal, F.Nfiber);\n\n simple_assign(M,P,pp,F,A);\n diagnostic(M,G,F,A);\n print_hist(\"Unused fibers\",5,histogram(A.unused_fbp(pp,F),5),false); \/\/ Hist of unused fibs\n \/\/ Want to have even distribution of unused fibers\n \/\/ so we can put in sky fibers and standard stars\n\n\t\/\/ Smooth out distribution of free fibers, and increase the number of assignments\n \n\tfor (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);\/\/ more iterations will improve performance slightly\n\tfor (int i=0; i<1; i++) { \/\/ more iterations will improve performance slightly\n\t\timprove(M,P,pp,F,A);\n\t\tredistribute_tf(M,P,pp,F,A);\n\t\tredistribute_tf(M,P,pp,F,A);\n\t}\n\tfor (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);\n \n\tprint_hist(\"Unused fibers\",5,histogram(A.unused_fbp(pp,F),5),false);\n\n\t\/\/ Still not updated, so all QSO targets have multiple observations etc\n\t\/\/ Apply and update the plan --------------------------------------\n\tinit_time_at(time,\"# Begin real time assignment\",t);\n\tfor (int jj=0; jj<F.Nplate; jj++) {\n\t\tint j = A.next_plate;\n printf(\" j = %d is next plate\\n\",j);\n\t\t\n\t\tassign_sf_ss(j,M,P,pp,F,A); \/\/ Assign SS and SF just before an observation\n\t\t\/\/assign_unused(j,M,P,pp,F,A);\n\t\t\/\/if (j%2000==0) pyplotTile(j,\"doc\/figs\",G,P,pp,F,A); \/\/ Picture of positioners, galaxies\n\t\t\n\t\t\/\/printf(\" %s not as - \",format(5,f(A.unused_f(j,F))).c_str()); fl();\n\t\t\/\/ Update corrects all future occurrences of wrong QSOs etc and tries to observe something else\n printf(\"done with assign_sf_ss for plate %d\\n\", j);\n\t\tif (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf(\"\\n\");\n \n\t\tA.next_plate++;\n\t\t\/\/ Redistribute and improve on various occasions add more times if desired\n\/*\n\t\tif ( j==1000 || j==4000) {\n\t\t\tredistribute_tf(M,P,pp,F,A);\n\t\t\tredistribute_tf(M,P,pp,F,A);\n\t\t\timprove(M,P,pp,F,A);\n\t\t\tredistribute_tf(M,P,pp,F,A);\n \/\/diagnostic(M,G,F,A);\n\t\t}\n*\/\n }\n\tprint_time(time,\"# ... took :\");\n\n\t\/\/ Results -------------------------------------------------------\n\tif (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); \/\/ Write output\n\tdisplay_results(\"doc\/figs\/\",G,M,P,pp,F,A,true);\n\tif (F.Verif) A.verif(P,M,pp,F); \/\/ Verification that the assignment is sane\n\n\n\tprint_time(t,\"# Finished !... in\");\n\n\treturn(0);\n \n}\n<commit_msg>new diagnostics<commit_after>#include\t<cstdlib>\n#include\t<cmath>\n#include\t<fstream>\n#include\t<sstream>\n#include\t<iostream>\n#include\t<iomanip>\n#include\t<string>\n#include\t<vector>\n#include\t<algorithm>\n#include\t<exception>\n#include\t<sys\/time.h>\n#include\t\"modules\/htmTree.h\"\n#include\t\"modules\/kdTree.h\"\n#include \"misc.h\"\n#include \"feat.h\"\n#include \"structs.h\"\n#include \"collision.h\"\n#include \"global.h\"\n\/\/reduce redistributes, updates 07\/02\/15 rnc\nint main(int argc, char **argv) {\n\t\/\/\/\/ Initializations ---------------------------------------------\n\tsrand48(1234); \/\/ Make sure we have reproducability\n\tcheck_args(argc);\n\tTime t, time; \/\/ t for global, time for local\n\tinit_time(t);\n\tFeat F;\n\n\t\/\/ Read parameters file \/\/\n\tF.readInputFile(argv[1]);\n\tprintFile(argv[1]);\n\t\/\/ Read galaxies\n\tGals G;\n if(F.Ascii){\n G=read_galaxies_ascii(F);}\n else{\n G = read_galaxies(F);\n }\n\tF.Ngal = G.size();\n\tprintf(\"# Read %s galaxies from %s \\n\",f(F.Ngal).c_str(),F.galFile.c_str());\n std::vector<int> count;\n count=count_galaxies(G);\n for(int i=0;i<8;i++){printf (\" %d \\n\",count[i]);}\n \/\/ make MTL\n MTL M=make_MTL(G,F);\n for(int i=0;i<M.priority_list.size();++i){\n printf(\" priority %d\",M.priority_list[i]);\n }\n printf(\" \\n\");\n assign_priority_class(M);\n \/\/find available SS and SF galaxies on each petal\n \n std::vector <int> count_class(M.priority_list.size(),0);\n for(int i;i<M.size();++i){\n count_class[M[i].priority_class]+=1;\n }\n for(int i;i<M.priority_list.size();++i){\n printf(\" class %d number %d\\n\",i,count_class[i]);\n }\n \n printf(\" number of MTL galaxies %d\\n\",M.size());\n printf(\"Read fiber center positions and compute related things\\n\");\n\tPP pp;\n\tpp.read_fiber_positions(F); \n\tF.Nfiber = pp.fp.size()\/2; \n\tF.Npetal = max(pp.spectrom)+1;\n printf(\"spectrometer has to be identified from 0 to F.Npetal-1\\n\");\n\tF.Nfbp = (int) (F.Nfiber\/F.Npetal);\/\/ fibers per petal = 500\n\tpp.get_neighbors(F); pp.compute_fibsofsp(F);\n printf(\"get neighbors of each fiber;\\n\");\n \/\/for each spectrometer, get list of fibers\n\n printf(\"Read plates in order they are to be observed\\n \");\n \n\tPlates P_original = read_plate_centers(F);\n F.Nplate=P_original.size();\n printf(\"This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\\n\");\n Plates P;\n P.resize(F.Nplate);\/\/don't permute plates\n\/* List permut = random_permut(F.Nplate);\n for (int jj=0; jj<F.Nplate; jj++){\n P[jj]=P_original[permut[jj]];\n }\n *\/\n P=P_original;\n\tprintf(\"# Read %s plate centers from %s and %d fibers from %s\\n\",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());\n \/\/diagnostic\n for (int j=0;j<F.Nplate;++j){\n printf(\"\\n j= %d \",j);\n for (int p=0;p<10;++p){\n printf(\" %d \",P[j].av_gals[p].size());\n }\n\n }\n\t\/\/ Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions\n\tF.cb = create_cb(); \/\/ cb=central body\n\tF.fh = create_fh(); \/\/ fh=fiber holder\n\n\t\/\/\/\/ Collect available galaxies <-> tilefibers --------------------\n\t\/\/ HTM Tree of galaxies\n\tconst double MinTreeSize = 0.01;\n\tinit_time_at(time,\"# Start building HTM tree\",t);\n\thtmTree<struct target> T(M,MinTreeSize);\n\tprint_time(time,\"# ... took :\");\/\/T.stats();\n\t\n\t\/\/ For plates\/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]\n\tcollect_galaxies_for_all(M,T,P,pp,F);\n\n \n \n \n\t\/\/ For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]\n\tcollect_available_tilefibers(M,P,F);\n\n\t\/\/results_on_inputs(\"doc\/figs\/\",G,P,F,true);\n\n\t\/\/\/\/ Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||\n printf(\"before assignment\\n\");\n\tAssignment A(M,F);\n\tprint_time(t,\"# Start assignment at : \");\n\n\t\/\/ Make a plan ----------------------------------------------------\n\t\/\/new_assign_fibers(G,P,pp,F,A); \/\/ Plans whole survey without sky fibers, standard stars\n \/\/ assumes maximum number of observations needed for QSOs, LRGs\n printf(\" Nplate %d Ngal %d Nfiber %d \\n\", F.Nplate, F.Ngal, F.Nfiber);\n\n simple_assign(M,P,pp,F,A);\n diagnostic(M,G,F,A);\n print_hist(\"Unused fibers\",5,histogram(A.unused_fbp(pp,F),5),false); \/\/ Hist of unused fibs\n \/\/ Want to have even distribution of unused fibers\n \/\/ so we can put in sky fibers and standard stars\n\n\t\/\/ Smooth out distribution of free fibers, and increase the number of assignments\n \n\tfor (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);\/\/ more iterations will improve performance slightly\n\tfor (int i=0; i<1; i++) { \/\/ more iterations will improve performance slightly\n\t\timprove(M,P,pp,F,A);\n\t\tredistribute_tf(M,P,pp,F,A);\n\t\tredistribute_tf(M,P,pp,F,A);\n\t}\n\tfor (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);\n \n\tprint_hist(\"Unused fibers\",5,histogram(A.unused_fbp(pp,F),5),false);\n\n\t\/\/ Still not updated, so all QSO targets have multiple observations etc\n\t\/\/ Apply and update the plan --------------------------------------\n\tinit_time_at(time,\"# Begin real time assignment\",t);\n\tfor (int jj=0; jj<F.Nplate; jj++) {\n\t\tint j = A.next_plate;\n printf(\" j = %d is next plate\\n\",j);\n\t\t\n\t\tassign_sf_ss(j,M,P,pp,F,A); \/\/ Assign SS and SF just before an observation\n\t\t\/\/assign_unused(j,M,P,pp,F,A);\n\t\t\/\/if (j%2000==0) pyplotTile(j,\"doc\/figs\",G,P,pp,F,A); \/\/ Picture of positioners, galaxies\n\t\t\n\t\t\/\/printf(\" %s not as - \",format(5,f(A.unused_f(j,F))).c_str()); fl();\n\t\t\/\/ Update corrects all future occurrences of wrong QSOs etc and tries to observe something else\n printf(\"done with assign_sf_ss for plate %d\\n\", j);\n\t\tif (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf(\"\\n\");\n \n\t\tA.next_plate++;\n\t\t\/\/ Redistribute and improve on various occasions add more times if desired\n\/*\n\t\tif ( j==1000 || j==4000) {\n\t\t\tredistribute_tf(M,P,pp,F,A);\n\t\t\tredistribute_tf(M,P,pp,F,A);\n\t\t\timprove(M,P,pp,F,A);\n\t\t\tredistribute_tf(M,P,pp,F,A);\n \/\/diagnostic(M,G,F,A);\n\t\t}\n*\/\n }\n\tprint_time(time,\"# ... took :\");\n\n\t\/\/ Results -------------------------------------------------------\n\tif (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); \/\/ Write output\n\tdisplay_results(\"doc\/figs\/\",G,M,P,pp,F,A,true);\n\tif (F.Verif) A.verif(P,M,pp,F); \/\/ Verification that the assignment is sane\n\n\n\tprint_time(t,\"# Finished !... in\");\n\n\treturn(0);\n \n}\n<|endoftext|>"} {"text":"<commit_before>#include <Arduino.h>\n#include \"DiscoStrips.h\"\n#include \"FastLED.h\"\n#include <SPI.h>\n#include <WiFi101.h>\n#include \"Answer.h\"\n#include \"DuinoREST.h\"\n#include \"Modes.h\"\n\nusing namespace std;\n\nDiscoStrips* disco = NULL;\nDuinoREST* rest = NULL;\n\n#define NUM_STRIPS 1\n#define NUM_LEDS 10\n\nSimpleVector<CRGB>* ledArray;\nint currentMode = 0;\nint brightness = 25;\nint colour = 4;\n\nchar ssid[] = \"Resistance Is Futile 2\"; \/\/ created AP name\nchar pass[] = \"liss#dfe1AWdfew\"; \/\/ AP password (needed only for WEP, must be exactly 10 or 26 characters in length)\nint keyIndex = 0; \/\/ your network key Index number (needed only for WEP)\n\nint status = WL_IDLE_STATUS;\nWiFiServer server(80);\n\n\/\/ We loop to add the line for each strip\ntemplate< unsigned N > struct AddLeds{\n static void generate() __attribute__((always_inline)){\n FastLED.addLeds<NEOPIXEL, N-1>(ledArray->get(N-1), NUM_LEDS);\n AddLeds< N - 1 >::generate();\n }\n};\ntemplate<> struct AddLeds<0>{ static inline void generate(){} };\n\nvoid printWiFiStatus() {\n \/\/ print the SSID of the network you're attached to:\n Serial.print(\"SSID: \");\n Serial.println(WiFi.SSID());\n\n \/\/ print your WiFi shield's IP address:\n IPAddress ip = WiFi.localIP();\n Serial.print(\"IP Address: \");\n Serial.println(ip);\n\n \/\/ print the received signal strength:\n long rssi = WiFi.RSSI();\n Serial.print(\"signal strength (RSSI):\");\n Serial.print(rssi);\n Serial.println(\" dBm\");\n \/\/ print where to go in a browser:\n Serial.print(\"To see this page in action, open a browser to http:\/\/\");\n Serial.println(ip);\n\n}\n\nvoid discoFunc(String line, Answer* answer)\n{\n disco->rest_parsing(line, answer);\n}\n\nvoid brightnessFunc(String line, Answer* answer)\n{\n if(line.startsWith(\"PUT \/brightness\/\"))\n {\n brightness = line.substring(16).toInt();\n }\n answer->add(\"{\\\"brightness\\\":\");\n answer->add(String(brightness));\n answer->add(\"}\");\n}\n\nString colours[] = {\"red\", \"green\", \"yellow\", \"blue\", \"white\"};\nCRGB crgbs[] = {CRGB::Red, CRGB::DarkGreen, CRGB::Yellow, CRGB::Blue, CRGB::White};\n\nvoid colourFunc(String line, Answer* answer)\n{\n if(line.startsWith(\"PUT \/colour\/\"))\n {\n String colourReq = line.substring(12);\n for(int i=0; i < 5; i++)\n {\n if(colourReq.startsWith(colours[i]))\n {\n colour = i;\n break;\n }\n }\n }\n answer->add(\"{\\\"colour\\\":\");\n answer->add(colours[colour]);\n answer->add(\",\\\"options\\\":[\");\n for(int i=0; i < 5; i++)\n {\n answer->add(\"\\\"\");\n answer->add(colours[i]);\n answer->add(\"\\\"\");\n if(i < 4)\n {\n answer->add(\", \");\n }\n }\n answer->add(\"]}\");\n}\n\nvoid modesFunc(String line, Answer* answer)\n{\n if(line.startsWith(\"GET \/mode\"))\n {\n answer->add(\"{\\\"modes\\\":[\\\"off\\\", \\\"on\\\", \\\"night\\\", \\\"fisco\\\"]}\");\n }\n else if(line.startsWith(\"PUT \/mode\/on\"))\n {\n currentMode = 1;\n answer->add(\"{\\\"mode\\\":\\\"on\\\"}\");\n }\n else if(line.startsWith(\"PUT \/mode\/night\"))\n {\n currentMode = 2;\n answer->add(\"{\\\"mode\\\":\\\"Night\\\"}\");\n }\n else if(line.startsWith(\"PUT \/mode\/disco\"))\n {\n currentMode = 3;\n answer->add(\"{\\\"mode\\\":\\\"disco\\\"}\");\n }\n else\n {\n currentMode = 0;\n answer->add(\"{\\\"mode\\\":\\\"off\\\"}\");\n }\n}\n\nvoid setup()\n{\n Serial.begin(115200);\n delay(1000);\n Serial.println(\"Setup\");\n delay(1000);\n Serial.println(\"Setup\");\n ledArray = new SimpleVector<CRGB>(NUM_STRIPS, NUM_LEDS);\n AddLeds<NUM_STRIPS>::generate();\n\n disco = new DiscoStrips(ledArray);\n rest = new DuinoREST;\n\n \/\/ check for the presence of the shield:\n if (WiFi.status() == WL_NO_SHIELD) {\n Serial.println(\"WiFi shield not present\");\n \/\/ don't continue\n while (true);\n }\n\n \/\/ by default the local IP address of will be 192.168.1.1\n \/\/ you can override it with the following:\n \/\/ WiFi.config(IPAddress(10, 0, 0, 1));\n\n \/\/ Create open network. Change this line if you want to create an WEP network:\n \/\/ status = WiFi.beginAP(ssid);\n while (status != WL_CONNECTED) {\n Serial.print(\"Attempting to connect to Network named: \");\n Serial.println(ssid); \/\/ print the network name (SSID);\n\n \/\/ Connect to WPA\/WPA2 network. Change this line if using open or WEP network:\n status = WiFi.begin(ssid, pass);\n \/\/ wait 10 seconds for connection:\n\/\/ delay(1000);\n }\n\n \/\/ start the web server on port 80\n server.begin();\n\n \/\/ you're connected now, so print out the status\n printWiFiStatus();\n\n rest->addHandler(\"disco\", discoFunc);\n rest->addHandler(\"mode\", modesFunc);\n rest->addHandler(\"brightness\", brightnessFunc);\n rest->addHandler(\"colour\", colourFunc);\n}\n\nvoid allLedsOff()\n{\n for(int i=0; i < ledArray->rows(); i++)\n {\n for(int j=0; j < ledArray->cols(); j++)\n {\n *ledArray->get(i, j) = CRGB::Black;\n }\n }\n\n}\n\nvoid allLedsOn()\n{\n for(int i=0; i < ledArray->rows(); i++)\n {\n for(int j=0; j < ledArray->cols(); j++)\n {\n *ledArray->get(i, j) = crgbs[colour];\n *ledArray->get(i, j) %= brightness;\n }\n }\n}\n\nvoid loop()\n{\n \/\/ compare the previous status to the current status\n if (status != WiFi.status()) {\n \/\/ it has changed update the variable\n status = WiFi.status();\n\n if (status == WL_AP_CONNECTED) {\n byte remoteMac[6];\n\n \/\/ a device has connected to the AP\n Serial.print(\"Device connected to AP, MAC address: \");\n WiFi.APClientMacAddress(remoteMac);\n Serial.print(remoteMac[5], HEX);\n Serial.print(\":\");\n Serial.print(remoteMac[4], HEX);\n Serial.print(\":\");\n Serial.print(remoteMac[3], HEX);\n Serial.print(\":\");\n Serial.print(remoteMac[2], HEX);\n Serial.print(\":\");\n Serial.print(remoteMac[1], HEX);\n Serial.print(\":\");\n Serial.println(remoteMac[0], HEX);\n } else {\n \/\/ a device has disconnected from the AP, and we are back in listening mode\n Serial.println(\"Device disconnected from AP\");\n }\n }\n WiFiClient client = server.available(); \/\/ listen for incoming clients\n\n if (client) { \/\/ if you get a client,\n rest->handle(client);\n \/\/ close the connection:\n delay(1);\n client.stop();\n }\n\n switch(currentMode)\n {\n case 3:\n disco->enable();\n break;\n\n case 2:\n disco->disable();\n break;\n\n case 1:\n disco->disable();\n allLedsOn();\n break;\n\n case 0:\n default:\n disco->disable();\n allLedsOff();\n break;\n }\n\n disco->tick();\n FastLED.show();\n}\n<commit_msg>dev: Minor update<commit_after>#include <Arduino.h>\n#include \"DiscoStrips.h\"\n#include \"FastLED.h\"\n#include <SPI.h>\n#include <WiFi101.h>\n#include \"Answer.h\"\n#include \"DuinoREST.h\"\n#include \"Modes.h\"\n\nusing namespace std;\n\nDiscoStrips* disco = NULL;\nDuinoREST* rest = NULL;\n\n#define NUM_STRIPS 1\n#define NUM_LEDS 10\n\nSimpleVector<CRGB>* ledArray;\nint currentMode = 0;\nint brightness = 25;\nint colour = 4;\n\nchar ssid[] = \"<AP name>\";\nchar pass[] = \"<password>\";\nint keyIndex = 0;\n\nint status = WL_IDLE_STATUS;\nWiFiServer server(80);\n\n\/\/ We loop to add the line for each strip\ntemplate< unsigned N > struct AddLeds{\n static void generate() __attribute__((always_inline)){\n FastLED.addLeds<NEOPIXEL, N-1>(ledArray->get(N-1), NUM_LEDS);\n AddLeds< N - 1 >::generate();\n }\n};\ntemplate<> struct AddLeds<0>{ static inline void generate(){} };\n\nvoid printWiFiStatus() {\n \/\/ print the SSID of the network you're attached to:\n Serial.print(\"SSID: \");\n Serial.println(WiFi.SSID());\n\n \/\/ print your WiFi shield's IP address:\n IPAddress ip = WiFi.localIP();\n Serial.print(\"IP Address: \");\n Serial.println(ip);\n\n \/\/ print the received signal strength:\n long rssi = WiFi.RSSI();\n Serial.print(\"signal strength (RSSI):\");\n Serial.print(rssi);\n Serial.println(\" dBm\");\n \/\/ print where to go in a browser:\n Serial.print(\"To see this page in action, open a browser to http:\/\/\");\n Serial.println(ip);\n\n}\n\nvoid discoFunc(String line, Answer* answer)\n{\n disco->rest_parsing(line, answer);\n}\n\nvoid brightnessFunc(String line, Answer* answer)\n{\n if(line.startsWith(\"PUT \/brightness\/\"))\n {\n brightness = line.substring(16).toInt();\n }\n answer->add(\"{\\\"brightness\\\":\");\n answer->add(String(brightness));\n answer->add(\"}\");\n}\n\nString colours[] = {\"red\", \"green\", \"yellow\", \"blue\", \"white\"};\nCRGB crgbs[] = {CRGB::Red, CRGB::DarkGreen, CRGB::Yellow, CRGB::Blue, CRGB::White};\n\nvoid colourFunc(String line, Answer* answer)\n{\n if(line.startsWith(\"PUT \/colour\/\"))\n {\n String colourReq = line.substring(12);\n for(int i=0; i < 5; i++)\n {\n if(colourReq.startsWith(colours[i]))\n {\n colour = i;\n break;\n }\n }\n }\n answer->add(\"{\\\"colour\\\":\");\n answer->add(colours[colour]);\n answer->add(\",\\\"options\\\":[\");\n for(int i=0; i < 5; i++)\n {\n answer->add(\"\\\"\");\n answer->add(colours[i]);\n answer->add(\"\\\"\");\n if(i < 4)\n {\n answer->add(\", \");\n }\n }\n answer->add(\"]}\");\n}\n\nvoid modesFunc(String line, Answer* answer)\n{\n if(line.startsWith(\"GET \/mode\"))\n {\n answer->add(\"{\\\"modes\\\":[\\\"off\\\", \\\"on\\\", \\\"night\\\", \\\"fisco\\\"]}\");\n }\n else if(line.startsWith(\"PUT \/mode\/on\"))\n {\n currentMode = 1;\n answer->add(\"{\\\"mode\\\":\\\"on\\\"}\");\n }\n else if(line.startsWith(\"PUT \/mode\/night\"))\n {\n currentMode = 2;\n answer->add(\"{\\\"mode\\\":\\\"Night\\\"}\");\n }\n else if(line.startsWith(\"PUT \/mode\/disco\"))\n {\n currentMode = 3;\n answer->add(\"{\\\"mode\\\":\\\"disco\\\"}\");\n }\n else\n {\n currentMode = 0;\n answer->add(\"{\\\"mode\\\":\\\"off\\\"}\");\n }\n}\n\nvoid setup()\n{\n Serial.begin(115200);\n delay(1000);\n Serial.println(\"Setup\");\n delay(1000);\n Serial.println(\"Setup\");\n ledArray = new SimpleVector<CRGB>(NUM_STRIPS, NUM_LEDS);\n AddLeds<NUM_STRIPS>::generate();\n\n disco = new DiscoStrips(ledArray);\n rest = new DuinoREST;\n\n \/\/ check for the presence of the shield:\n if (WiFi.status() == WL_NO_SHIELD) {\n Serial.println(\"WiFi shield not present\");\n \/\/ don't continue\n while (true);\n }\n\n \/\/ by default the local IP address of will be 192.168.1.1\n \/\/ you can override it with the following:\n \/\/ WiFi.config(IPAddress(10, 0, 0, 1));\n\n \/\/ Create open network. Change this line if you want to create an WEP network:\n \/\/ status = WiFi.beginAP(ssid);\n while (status != WL_CONNECTED) {\n Serial.print(\"Attempting to connect to Network named: \");\n Serial.println(ssid); \/\/ print the network name (SSID);\n\n \/\/ Connect to WPA\/WPA2 network. Change this line if using open or WEP network:\n status = WiFi.begin(ssid, pass);\n \/\/ wait 10 seconds for connection:\n\/\/ delay(1000);\n }\n\n \/\/ start the web server on port 80\n server.begin();\n\n \/\/ you're connected now, so print out the status\n printWiFiStatus();\n\n rest->addHandler(\"disco\", discoFunc);\n rest->addHandler(\"mode\", modesFunc);\n rest->addHandler(\"brightness\", brightnessFunc);\n rest->addHandler(\"colour\", colourFunc);\n}\n\nvoid allLedsOff()\n{\n for(int i=0; i < ledArray->rows(); i++)\n {\n for(int j=0; j < ledArray->cols(); j++)\n {\n *ledArray->get(i, j) = CRGB::Black;\n }\n }\n\n}\n\nvoid allLedsOn()\n{\n for(int i=0; i < ledArray->rows(); i++)\n {\n for(int j=0; j < ledArray->cols(); j++)\n {\n *ledArray->get(i, j) = crgbs[colour];\n *ledArray->get(i, j) %= brightness;\n }\n }\n}\n\nvoid loop()\n{\n \/\/ compare the previous status to the current status\n if (status != WiFi.status()) {\n \/\/ it has changed update the variable\n status = WiFi.status();\n\n if (status == WL_AP_CONNECTED) {\n byte remoteMac[6];\n\n \/\/ a device has connected to the AP\n Serial.print(\"Device connected to AP, MAC address: \");\n WiFi.APClientMacAddress(remoteMac);\n Serial.print(remoteMac[5], HEX);\n Serial.print(\":\");\n Serial.print(remoteMac[4], HEX);\n Serial.print(\":\");\n Serial.print(remoteMac[3], HEX);\n Serial.print(\":\");\n Serial.print(remoteMac[2], HEX);\n Serial.print(\":\");\n Serial.print(remoteMac[1], HEX);\n Serial.print(\":\");\n Serial.println(remoteMac[0], HEX);\n } else {\n \/\/ a device has disconnected from the AP, and we are back in listening mode\n Serial.println(\"Device disconnected from AP\");\n }\n }\n WiFiClient client = server.available(); \/\/ listen for incoming clients\n\n if (client) { \/\/ if you get a client,\n rest->handle(client);\n \/\/ close the connection:\n delay(1);\n client.stop();\n }\n\n switch(currentMode)\n {\n case 3:\n disco->enable();\n break;\n\n case 2:\n disco->disable();\n break;\n\n case 1:\n disco->disable();\n allLedsOn();\n break;\n\n case 0:\n default:\n disco->disable();\n allLedsOff();\n break;\n }\n\n disco->tick();\n FastLED.show();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <avr\/io.h>\n#include <SD.h>\n#include <Arduino.h>\n\n#include \"bits.h\"\n#include \"session.h\"\n#include \"frame.h\"\n\n#define SD_CHIPSELECT 4\n#define SAMPLE_RATE 256\n\nuint8_t frame_buf[FRAME_SIZE];\nuint8_t frame_counter;\n\nint init_sd() \n{\n\tif (!SD.begin(SD_CHIPSELECT)) {\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint init_ecg()\n{\n\tframe_counter = 0;\n\tmemset(frame_buf, 0, FRAME_SIZE);\n\tif (init_sd() < 0) {\n\t\treturn -1;\n\t}\n\tuint64_t init_time = 1423297511ULL; \/\/ XXX: actually get time\n\tsession *s = session_init(init_time, FRAME_CHANNELS);\n\tif (s == NULL) {\n\t\treturn -2;\n\t}\n\treturn 0;\n}\n\nint main(void) \n{\n\tif (init_ecg() != 0) {\n\t\treturn -1;\n\t}\n\tfor (;;) {\n\t\tframe_buf[0] = frame_counter;\n\t\t\/\/ Counter will overflow at 256.\n\t\tframe_counter++;\n\t}\n}\n<commit_msg>Add error state and debugging output<commit_after>#include <avr\/io.h>\n#include <SD.h>\n#include <Arduino.h>\n\n#include \"bits.h\"\n#include \"session.h\"\n#include \"frame.h\"\n\n#define SD_CHIPSELECT 4\n#define SAMPLE_RATE 256\n\n#define PIN_ERROR_LED 13\n\n#define DEBUG 1\n\nuint8_t frame_buf[FRAME_SIZE];\nuint8_t frame_counter;\n\nvoid state_error()\n{\n\t#ifdef DEBUG\n\tSerial.println(\"Entering error state.\");\n\t#endif\n\tpinMode(PIN_ERROR_LED, OUTPUT);\n\tfor (;;) {\n\t\tdigitalWrite(PIN_ERROR_LED, HIGH);\n\t\tdelay(500);\n\t\tdigitalWrite(PIN_ERROR_LED, LOW);\n\t\tdelay(500);\n\t}\n}\n\nvoid state_run()\n{\n\tfor (;;) {\n\t\t\/\/ do stuff\n\t}\n}\n\nint init_sd() \n{\n\tif (!SD.begin(SD_CHIPSELECT)) {\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint init_ecg()\n{\n\tframe_counter = 0;\n\tmemset(frame_buf, 0, FRAME_SIZE);\n\tif (init_sd() < 0) {\n\t\t#ifdef DEBUG\n\t\tSerial.println(\"Could not initialize SD card.\");\n\t\t#endif\n\t\treturn -1;\n\t}\n\tuint64_t init_time = 1423297511ULL; \/\/ XXX: actually get time\n\tsession *s = session_init(init_time, FRAME_CHANNELS);\n\tif (s == NULL) {\n\t\t#ifdef DEBUG\n\t\tSerial.println(\"Could not initialize session.\");\n\t\t#endif\n\t\treturn -2;\n\t}\n\treturn 0;\n}\n\nint main(void) \n{\n\t#ifdef DEBUG\n\tSerial.begin(9600);\n\tSerial.println(\"ecg-datalogger initializing.\");\n\t#endif\n\tif (init_ecg() != 0) {\n\t\tstate_error();\n\t} else {\n\t\tstate_run();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <tclap\/CmdLine.h>\n#include <llvm\/IR\/Module.h>\n#include <fstream>\n#include <sstream>\n#include <chrono>\n\n#include \"utils\/util.hpp\"\n#include \"utils\/error.hpp\"\n#include \"lexer.hpp\"\n#include \"parser\/tokenParser.hpp\"\n#include \"parser\/xmlParser.hpp\"\n#include \"llvm\/compiler.hpp\"\n#include \"llvm\/runner.hpp\"\n\nenum ExitCodes: int {\n NORMAL_EXIT = 0, \/\/\/< Everything is OK\n TCLAP_ERROR = 11, \/\/\/< TCLAP did something bad, should not happen\n CLI_ERROR = 1, \/\/\/< The user used a wrong combination of options\n USER_PROGRAM_ERROR = 2, \/\/\/< The thing we had to lex\/parse\/run has an issue\n INTERNAL_ERROR = 3 \/\/\/< Unrecoverable error in this program, almost always a bug\n};\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmissing-declarations\"\n\nstd::unique_ptr<AST> parseXML(fs::path filePath, std::string cliEval) {\n if (!filePath.empty()) {\n \/\/ Read from file\n auto file = rapidxml::file<>(filePath.c_str());\n return std::make_unique<AST>(XMLParser().parse(file).getTree());\n } else {\n \/\/ Read from CLI\n char* mutableCode = new char[cliEval.size() + 1];\n std::move(ALL(cliEval), mutableCode);\n mutableCode[cliEval.size()] = '\\0';\n return std::make_unique<AST>(XMLParser().parse(mutableCode).getTree());\n }\n}\n\nstd::vector<Token> tokenize(fs::path filePath, std::string cliEval) {\n std::string input;\n if (!filePath.empty()) {\n std::ifstream file(filePath);\n std::stringstream buffer;\n buffer << file.rdbuf();\n input = buffer.str();\n } else {\n input = cliEval;\n }\n auto lx = Lexer();\n return lx.tokenize(input, filePath.empty() ? \"<cli-eval>\" : filePath).getTokens();\n}\n\nvoid assertCliIntegrity(TCLAP::CmdLine& cmd, bool value, std::string message) {\n if (!value) return;\n TCLAP::ArgException arg(message);\n cmd.getOutput()->failure(cmd, arg);\n}\n\nint notReallyMain(int argc, const char* argv[]) {\n try {\n TCLAP::CmdLine cmd(\"Xylene\", ' ', \"pre-release\");\n \n TCLAP::SwitchArg asXML(\"\", \"xml\", \"Read file using the XML parser\", cmd);\n \n TCLAP::SwitchArg printTokens(\"\", \"tokens\", \"Print token list (if applicable)\", cmd);\n TCLAP::SwitchArg printAST(\"\", \"ast\", \"Print AST (if applicable)\", cmd);\n TCLAP::SwitchArg printIR(\"\", \"ir\", \"Print LLVM IR (if applicable)\", cmd);\n \n TCLAP::SwitchArg doNotParse(\"\", \"no-parse\", \"Don't parse the token list\", cmd);\n TCLAP::SwitchArg doNotRun(\"\", \"no-run\", \"Don't execute the AST\", cmd);\n \n std::vector<std::string> runnerValues {\"interpret\", \"compile\"};\n TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues);\n TCLAP::ValueArg<std::string> runner(\"r\", \"runner\", \"How to run this code\", false,\n \"interpret\", &runnerConstraint, cmd, nullptr);\n \n TCLAP::ValueArg<std::string> code(\"e\", \"eval\", \"Code to evaluate\", false,\n std::string(), \"string\", cmd, nullptr);\n TCLAP::ValueArg<std::string> filePath(\"f\", \"file\", \"Load code from this file\",\n false, std::string(), \"path\", cmd, nullptr);\n TCLAP::ValueArg<std::string> outPath(\"o\", \"output\", \"Write exe to this file\",\n false, std::string(), \"path\", cmd, nullptr);\n cmd.parse(argc, argv);\n \n \/\/ There must be at least one input\n assertCliIntegrity(cmd, code.getValue().empty() && filePath.getValue().empty(),\n \"Must specify either option -e or -f\");\n \n \/\/ There is not much you can do to the XML without parsing it\n assertCliIntegrity(cmd, asXML.getValue() && doNotParse.getValue(),\n \"--no-parse and --xml are incompatible\");\n \n \/\/ The XML parser does not use tokens\n assertCliIntegrity(cmd, asXML.getValue() && printTokens.getValue(),\n \"--tokens and --xml are incompatible\");\n \n \/\/ Can't print AST without creating it first\n assertCliIntegrity(cmd, printAST.getValue() && doNotParse.getValue(),\n \"--no-parse and --ast are incompatible\");\n \n \/\/ Can't print IR without parsing the AST\n assertCliIntegrity(cmd, printIR.getValue() && doNotParse.getValue(),\n \"--no-parse and --ir are incompatible\");\n \n std::unique_ptr<AST> ast;\n \n if (asXML.getValue()) {\n ast = parseXML(filePath.getValue(), code.getValue());\n } else {\n auto tokens = tokenize(filePath.getValue(), code.getValue());\n if (printTokens.getValue()) for (auto tok : tokens) println(tok);\n \n if (doNotParse.getValue()) return NORMAL_EXIT;\n ast = std::make_unique<AST>(TokenParser().parse(tokens).getTree());\n }\n \n if (printAST.getValue()) ast->print();\n if (doNotRun.getValue()) return NORMAL_EXIT;\n \n ModuleCompiler::Link mc = ModuleCompiler::create(\"Command Line Module\", *ast);\n mc->visit();\n if (printIR.getValue()) mc->getModule()->dump();\n \n if (runner.getValue() == \"interpret\") {\n return Runner(mc).run();\n } else if (runner.getValue() == \"compile\") {\n Compiler(std::unique_ptr<llvm::Module>(mc->getModule()),\n filePath.getValue(), outPath.getValue()).compile();\n return NORMAL_EXIT;\n }\n } catch (const TCLAP::ExitException& arg) {\n return CLI_ERROR;\n } catch (const TCLAP::ArgException& arg) {\n println(\"TCLAP error\", arg.error(), \"for\", arg.argId());\n return TCLAP_ERROR;\n } catch (const Error& err) {\n println(err.what());\n return USER_PROGRAM_ERROR;\n }\n \/\/ If we're debugging, crash the program on InternalError\n #ifndef CRASH_ON_INTERNAL_ERROR\n catch (const InternalError& err) {\n println(err.what());\n return INTERNAL_ERROR;\n }\n #endif\n return 0;\n}\n\n#pragma GCC diagnostic pop\n\nint main(int argc, const char* argv[]) {\n #ifdef XYLENE_MEASURE_TIME\n auto begin = std::chrono::steady_clock::now();\n #endif\n \n int exitCode = notReallyMain(argc, argv);\n \n #ifdef XYLENE_MEASURE_TIME\n auto end = std::chrono::steady_clock::now();\n println(\n \"Time diff:\",\n std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(),\n \"μs\"\n );\n #endif\n\n return exitCode;\n}\n<commit_msg>Add documentation<commit_after>#include <tclap\/CmdLine.h>\n#include <llvm\/IR\/Module.h>\n#include <fstream>\n#include <sstream>\n#include <chrono>\n\n#include \"utils\/util.hpp\"\n#include \"utils\/error.hpp\"\n#include \"lexer.hpp\"\n#include \"parser\/tokenParser.hpp\"\n#include \"parser\/xmlParser.hpp\"\n#include \"llvm\/compiler.hpp\"\n#include \"llvm\/runner.hpp\"\n\nenum ExitCodes: int {\n NORMAL_EXIT = 0, \/\/\/< Everything is OK\n TCLAP_ERROR = 11, \/\/\/< TCLAP did something bad, should not happen\n CLI_ERROR = 1, \/\/\/< The user used a wrong combination of options\n USER_PROGRAM_ERROR = 2, \/\/\/< The thing we had to lex\/parse\/run has an issue\n INTERNAL_ERROR = 3 \/\/\/< Unrecoverable error in this program, almost always a bug\n};\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmissing-declarations\"\n\nstd::unique_ptr<AST> parseXML(fs::path filePath, std::string cliEval) {\n if (!filePath.empty()) {\n \/\/ Read from file\n auto file = rapidxml::file<>(filePath.c_str());\n return std::make_unique<AST>(XMLParser().parse(file).getTree());\n } else {\n \/\/ Read from CLI\n char* mutableCode = new char[cliEval.size() + 1];\n std::move(ALL(cliEval), mutableCode);\n mutableCode[cliEval.size()] = '\\0';\n return std::make_unique<AST>(XMLParser().parse(mutableCode).getTree());\n }\n}\n\nstd::vector<Token> tokenize(fs::path filePath, std::string cliEval) {\n std::string input;\n if (!filePath.empty()) {\n std::ifstream file(filePath);\n std::stringstream buffer;\n buffer << file.rdbuf();\n input = buffer.str();\n } else {\n input = cliEval;\n }\n auto lx = Lexer();\n return lx.tokenize(input, filePath.empty() ? \"<cli-eval>\" : filePath).getTokens();\n}\n\n\/\/\/ Throw if the assertion is false\nvoid assertCliIntegrity(TCLAP::CmdLine& cmd, bool assertion, std::string message) {\n if (!assertion) return;\n TCLAP::ArgException arg(message);\n cmd.getOutput()->failure(cmd, arg);\n}\n\n\/\/\/ Pseudo-main used to allow early returns while measuring execution time\nint notReallyMain(int argc, const char* argv[]) {\n try {\n TCLAP::CmdLine cmd(\"Xylene\", ' ', \"pre-release\");\n \n TCLAP::SwitchArg asXML(\"\", \"xml\", \"Read file using the XML parser\", cmd);\n \n TCLAP::SwitchArg printTokens(\"\", \"tokens\", \"Print token list (if applicable)\", cmd);\n TCLAP::SwitchArg printAST(\"\", \"ast\", \"Print AST (if applicable)\", cmd);\n TCLAP::SwitchArg printIR(\"\", \"ir\", \"Print LLVM IR (if applicable)\", cmd);\n \n TCLAP::SwitchArg doNotParse(\"\", \"no-parse\", \"Don't parse the token list\", cmd);\n TCLAP::SwitchArg doNotRun(\"\", \"no-run\", \"Don't execute the AST\", cmd);\n \n std::vector<std::string> runnerValues {\"interpret\", \"compile\"};\n TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues);\n TCLAP::ValueArg<std::string> runner(\"r\", \"runner\", \"How to run this code\", false,\n \"interpret\", &runnerConstraint, cmd, nullptr);\n \n TCLAP::ValueArg<std::string> code(\"e\", \"eval\", \"Code to evaluate\", false,\n std::string(), \"string\", cmd, nullptr);\n TCLAP::ValueArg<std::string> filePath(\"f\", \"file\", \"Load code from this file\",\n false, std::string(), \"path\", cmd, nullptr);\n TCLAP::ValueArg<std::string> outPath(\"o\", \"output\", \"Write exe to this file\",\n false, std::string(), \"path\", cmd, nullptr);\n cmd.parse(argc, argv);\n \n \/\/ There must be at least one input\n assertCliIntegrity(cmd, code.getValue().empty() && filePath.getValue().empty(),\n \"Must specify either option -e or -f\");\n \n \/\/ There is not much you can do to the XML without parsing it\n assertCliIntegrity(cmd, asXML.getValue() && doNotParse.getValue(),\n \"--no-parse and --xml are incompatible\");\n \n \/\/ The XML parser does not use tokens\n assertCliIntegrity(cmd, asXML.getValue() && printTokens.getValue(),\n \"--tokens and --xml are incompatible\");\n \n \/\/ Can't print AST without creating it first\n assertCliIntegrity(cmd, printAST.getValue() && doNotParse.getValue(),\n \"--no-parse and --ast are incompatible\");\n \n \/\/ Can't print IR without parsing the AST\n assertCliIntegrity(cmd, printIR.getValue() && doNotParse.getValue(),\n \"--no-parse and --ir are incompatible\");\n \n std::unique_ptr<AST> ast;\n \n if (asXML.getValue()) {\n ast = parseXML(filePath.getValue(), code.getValue());\n } else {\n auto tokens = tokenize(filePath.getValue(), code.getValue());\n if (printTokens.getValue()) for (auto tok : tokens) println(tok);\n \n if (doNotParse.getValue()) return NORMAL_EXIT;\n ast = std::make_unique<AST>(TokenParser().parse(tokens).getTree());\n }\n \n if (printAST.getValue()) ast->print();\n if (doNotRun.getValue()) return NORMAL_EXIT;\n \n ModuleCompiler::Link mc = ModuleCompiler::create(\"Command Line Module\", *ast);\n mc->visit();\n if (printIR.getValue()) mc->getModule()->dump();\n \n if (runner.getValue() == \"interpret\") {\n return Runner(mc).run();\n } else if (runner.getValue() == \"compile\") {\n Compiler(std::unique_ptr<llvm::Module>(mc->getModule()),\n filePath.getValue(), outPath.getValue()).compile();\n return NORMAL_EXIT;\n }\n } catch (const TCLAP::ExitException& arg) {\n return CLI_ERROR;\n } catch (const TCLAP::ArgException& arg) {\n println(\"TCLAP error\", arg.error(), \"for\", arg.argId());\n return TCLAP_ERROR;\n } catch (const Error& err) {\n println(err.what());\n return USER_PROGRAM_ERROR;\n }\n \/\/ If we're debugging, crash the program on InternalError\n #ifndef CRASH_ON_INTERNAL_ERROR\n catch (const InternalError& err) {\n println(err.what());\n return INTERNAL_ERROR;\n }\n #endif\n return 0;\n}\n\n#pragma GCC diagnostic pop\n\n\/\/\/ Measures execution time if XYLENE_MEASURE_TIME is defined \\see notReallyMain\nint main(int argc, const char* argv[]) {\n #ifdef XYLENE_MEASURE_TIME\n auto begin = std::chrono::steady_clock::now();\n #endif\n \n int exitCode = notReallyMain(argc, argv);\n \n #ifdef XYLENE_MEASURE_TIME\n auto end = std::chrono::steady_clock::now();\n println(\n \"Time diff:\",\n std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(),\n \"μs\"\n );\n #endif\n\n return exitCode;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* * * * * * * * * * * * *\\\n|* ╔═╗ v0.3 *|\n|* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *|\n|* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *|\n|* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *|\n|* * * * * * * * * ╚═╝ * *|\n|* Manipulation tool for *|\n|* ESRI Shapefiles *|\n|* * * * * * * * * * * * *|\n|* http:\/\/www.npolar.no\/ *|\n\\* * * * * * * * * * * * *\/\n\n#include \"handler.hpp\"\n\nint main(int argc, char* argv[])\n{\n reshp::handler reshp(argc, argv, \"0.3.4\");\n return reshp.run();\n}\n<commit_msg>Updated version number<commit_after>\/* * * * * * * * * * * * *\\\n|* ╔═╗ v0.3 *|\n|* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *|\n|* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *|\n|* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *|\n|* * * * * * * * * ╚═╝ * *|\n|* Manipulation tool for *|\n|* ESRI Shapefiles *|\n|* * * * * * * * * * * * *|\n|* http:\/\/www.npolar.no\/ *|\n\\* * * * * * * * * * * * *\/\n\n#include \"handler.hpp\"\n\nint main(int argc, char* argv[])\n{\n \/\/ TODO: Update version number\n reshp::handler reshp(argc, argv, \"0.3.5\");\n return reshp.run();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Adventures in OpenCL tutorial series\n * Part 2\n *\n * author: Ian Johnson\n * htt:\/\/enja.org\n * code based on advisor Gordon Erlebacher's work\n * NVIDIA's examples\n * as well as various blogs and resources on the internet\n *\n * Ported to GL4 and GFLW by Lubosz Sarnecki <lubosz@gmail.com>\n *\n *\/\n\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n#include \"Renderer.h\"\n#include \"Simulator.h\"\n#include \"util.h\"\n#include <math.h>\n\n#define NUM_PARTICLES 200\n\nSimulator* simulator;\nRenderer* renderer;\n\n\/\/GL related variables\nint window_width = 1280;\nint window_height = 720;\n\/\/ mouse controls\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\n\n\nstatic void windowFrameBufferCallback(GLFWwindow * \twindow, int width, int height) {\n renderer->updateProjection(width, height);\n}\n\n\nstatic void errorCallback(int error, const char* description)\n{\n fputs(description, stderr);\n}\nstatic void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\n glfwSetWindowShouldClose(window, GL_TRUE);\n}\n\nvoid scrollCallback(GLFWwindow* window, double xoffset, double yoffset)\n{\n renderer->translate(yoffset);\n}\n\nvoid buttonCallback(GLFWwindow* window, int button, int action, int mods)\n{\n \/\/handle mouse interaction for rotating\/zooming the view\n if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {\n mouse_buttons |= 1<<button;\n } else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {\n mouse_buttons = 0;\n }\n\n double x, y;\n glfwGetCursorPos(window, &x, &y);\n\n mouse_old_x = x;\n mouse_old_y = y;\n}\n\nstatic void cursorCallback(GLFWwindow* window, double x, double y)\n{\n \/\/hanlde the mouse motion for zooming and rotating the view\n float dx, dy;\n dx = x - mouse_old_x;\n dy = y - mouse_old_y;\n\n if (mouse_buttons & 1) {\n renderer->rotate(dx, dy);\n }\n\n mouse_old_x = x;\n mouse_old_y = y;\n}\n\nGLFWwindow* initGLFW() {\n GLFWwindow* window;\n glfwSetErrorCallback(errorCallback);\n if (!glfwInit())\n exit(EXIT_FAILURE);\n\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n window = glfwCreateWindow(window_width, window_height, \"Universe Simulator\", NULL, NULL);\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n glfwMakeContextCurrent(window);\n glfwSwapInterval(1);\n glfwSetKeyCallback(window, keyCallback);\n glfwSetMouseButtonCallback(window, buttonCallback);\n glfwSetScrollCallback(window, scrollCallback);\n glfwSetCursorPosCallback(window, cursorCallback);\n glfwSetFramebufferSizeCallback(window, windowFrameBufferCallback);\n\n return window;\n}\n\nvoid initParticles() {\n \/\/initialize our particle system with positions, velocities and color\n int num = NUM_PARTICLES;\n \/\/int num = 1;\n std::vector<Vec4> pos(num);\n std::vector<Vec4> vel(num);\n std::vector<Vec4> color(num);\n\n \/\/fill our vectors with initial data\n for(int i = 0; i < num; i++)\n {\n \/\/distribute the particles in a random circle around z axis\n float rad = randomFloat(.2, .5);\n \/\/float rad = 1.0;\n float x = rad * sin(2 * M_PI * i\/num);\n float z = 0.0f;\/\/ -.1 + .2f * i\/num;\n float y = rad * cos(2 * M_PI * i\/num);\n pos[i] = Vec4(x, y, z, 1.0f);\n\n \/\/give some initial velocity\n \/\/float xr = rand_float(-.1, .1);\n \/\/float yr = rand_float(1.f, 3.f);\n \/\/the life is the lifetime of the particle: 1 = alive 0 = dead\n \/\/as you will see in part2.cl we reset the particle when it dies\n \/\/float life_r = randomFloat(0.f, 1.f);\n \/\/vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);\n vel[i] =\n Vec4(\n randomFloat(-1.f, 1.f),\n randomFloat(-1.f, 1.f),\n randomFloat(-1.f, 1.f),\n 1.0);\n\n \/\/just make them red and full alpha\n color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);\n }\n\n \/\/our load data function sends our initial values to the GPU\n simulator->loadData(pos, vel, color);\n}\n\nint main(int argc, char** argv)\n{\n GLFWwindow* window = initGLFW();\n renderer = new Renderer(window_width, window_height);\n\n std::string kernel_source = readFile(\"gpu\/vortex.cl\");\n simulator = new Simulator();\n simulator->loadProgram(kernel_source);\n\n initParticles();\n \/\/initialize the kernel\n simulator->initKernel();\n\n while (!glfwWindowShouldClose(window))\n {\n \/\/this updates the particle system by calling the kernel\n simulator->runKernel();\n renderer->draw(simulator->positionVBO,\n simulator->colorVBO,\n simulator->particleCount);\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n glfwDestroyWindow(window);\n glfwTerminate();\n exit(EXIT_SUCCESS);\n}\n<commit_msg>do not use vsync<commit_after>\/*\n * Adventures in OpenCL tutorial series\n * Part 2\n *\n * author: Ian Johnson\n * htt:\/\/enja.org\n * code based on advisor Gordon Erlebacher's work\n * NVIDIA's examples\n * as well as various blogs and resources on the internet\n *\n * Ported to GL4 and GFLW by Lubosz Sarnecki <lubosz@gmail.com>\n *\n *\/\n\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n#include \"Renderer.h\"\n#include \"Simulator.h\"\n#include \"util.h\"\n#include <math.h>\n\n#define NUM_PARTICLES 200\n\nSimulator* simulator;\nRenderer* renderer;\n\n\/\/GL related variables\nint window_width = 1280;\nint window_height = 720;\n\/\/ mouse controls\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\n\n\nstatic void windowFrameBufferCallback(GLFWwindow * \twindow, int width, int height) {\n renderer->updateProjection(width, height);\n}\n\n\nstatic void errorCallback(int error, const char* description)\n{\n fputs(description, stderr);\n}\nstatic void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\n glfwSetWindowShouldClose(window, GL_TRUE);\n}\n\nvoid scrollCallback(GLFWwindow* window, double xoffset, double yoffset)\n{\n renderer->translate(yoffset);\n}\n\nvoid buttonCallback(GLFWwindow* window, int button, int action, int mods)\n{\n \/\/handle mouse interaction for rotating\/zooming the view\n if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {\n mouse_buttons |= 1<<button;\n } else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {\n mouse_buttons = 0;\n }\n\n double x, y;\n glfwGetCursorPos(window, &x, &y);\n\n mouse_old_x = x;\n mouse_old_y = y;\n}\n\nstatic void cursorCallback(GLFWwindow* window, double x, double y)\n{\n \/\/hanlde the mouse motion for zooming and rotating the view\n float dx, dy;\n dx = x - mouse_old_x;\n dy = y - mouse_old_y;\n\n if (mouse_buttons & 1) {\n renderer->rotate(dx, dy);\n }\n\n mouse_old_x = x;\n mouse_old_y = y;\n}\n\nGLFWwindow* initGLFW() {\n GLFWwindow* window;\n glfwSetErrorCallback(errorCallback);\n if (!glfwInit())\n exit(EXIT_FAILURE);\n\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n window = glfwCreateWindow(window_width, window_height, \"Universe Simulator\", NULL, NULL);\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n glfwMakeContextCurrent(window);\n \/\/glfwSwapInterval(1);\n glfwSetKeyCallback(window, keyCallback);\n glfwSetMouseButtonCallback(window, buttonCallback);\n glfwSetScrollCallback(window, scrollCallback);\n glfwSetCursorPosCallback(window, cursorCallback);\n glfwSetFramebufferSizeCallback(window, windowFrameBufferCallback);\n\n return window;\n}\n\nvoid initParticles() {\n \/\/initialize our particle system with positions, velocities and color\n int num = NUM_PARTICLES;\n \/\/int num = 1;\n std::vector<Vec4> pos(num);\n std::vector<Vec4> vel(num);\n std::vector<Vec4> color(num);\n\n \/\/fill our vectors with initial data\n for(int i = 0; i < num; i++)\n {\n \/\/distribute the particles in a random circle around z axis\n float rad = randomFloat(.2, .5);\n \/\/float rad = 1.0;\n float x = rad * sin(2 * M_PI * i\/num);\n float z = 0.0f;\/\/ -.1 + .2f * i\/num;\n float y = rad * cos(2 * M_PI * i\/num);\n pos[i] = Vec4(x, y, z, 1.0f);\n\n \/\/give some initial velocity\n \/\/float xr = rand_float(-.1, .1);\n \/\/float yr = rand_float(1.f, 3.f);\n \/\/the life is the lifetime of the particle: 1 = alive 0 = dead\n \/\/as you will see in part2.cl we reset the particle when it dies\n \/\/float life_r = randomFloat(0.f, 1.f);\n \/\/vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);\n vel[i] =\n Vec4(\n randomFloat(-1.f, 1.f),\n randomFloat(-1.f, 1.f),\n randomFloat(-1.f, 1.f),\n 1.0);\n\n \/\/just make them red and full alpha\n color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);\n }\n\n \/\/our load data function sends our initial values to the GPU\n simulator->loadData(pos, vel, color);\n}\n\nint main(int argc, char** argv)\n{\n GLFWwindow* window = initGLFW();\n renderer = new Renderer(window_width, window_height);\n\n std::string kernel_source = readFile(\"gpu\/vortex.cl\");\n simulator = new Simulator();\n simulator->loadProgram(kernel_source);\n\n initParticles();\n \/\/initialize the kernel\n simulator->initKernel();\n\n while (!glfwWindowShouldClose(window))\n {\n \/\/this updates the particle system by calling the kernel\n simulator->runKernel();\n renderer->draw(simulator->positionVBO,\n simulator->colorVBO,\n simulator->particleCount);\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n glfwDestroyWindow(window);\n glfwTerminate();\n exit(EXIT_SUCCESS);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes \/\/\n#include <SDL_image.h>\n#include <SDL.h>\n\n#include \"window.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\n\/\/ Loading an image from the disk.\nSDL_Texture* loadImage(Window& w, std::string path) {\n SDL_Surface* img = IMG_Load(path.c_str());\n if (img == nullptr)\n return nullptr;\n\n SDL_Texture* tex = SDL_CreateTextureFromSurface(\n w.getRenderer(),\n img\n );\n\n SDL_FreeSurface(img);\n return tex;\n}\n\n\/\/ Entry point!\nint main() {\n Window w(\"Hello World!\", 640, 480, false);\n\n SDL_Texture* tex = loadImage(w, \"res\/test.png\");\n if (tex == nullptr) {\n return 1;\n }\n\n SDL_RenderCopy(w.getRenderer(),\n tex,\n nullptr,\n nullptr);\n SDL_RenderPresent(w.getRenderer());\n\n SDL_Event e;\n while (SDL_WaitEvent(&e)) {\n if (e.type == SDL_QUIT)\n break;\n }\n\n return 0;\n}\n<commit_msg>Made the background not horrid.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes \/\/\n#include <SDL_image.h>\n#include <SDL.h>\n\n#include \"window.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\n\/\/ Loading an image from the disk.\nSDL_Texture* loadImage(Window& w, std::string path) {\n SDL_Surface* img = IMG_Load(path.c_str());\n if (img == nullptr)\n return nullptr;\n\n SDL_Texture* tex = SDL_CreateTextureFromSurface(\n w.getRenderer(),\n img\n );\n\n SDL_FreeSurface(img);\n return tex;\n}\n\n\/\/ Entry point!\nint main() {\n Window w(\"Hello World!\", 640, 480, false);\n\n SDL_Texture* tex = loadImage(w, \"res\/test.png\");\n if (tex == nullptr) {\n return 1;\n }\n\n SDL_RenderClear(w.getRenderer());\n SDL_RenderCopy(w.getRenderer(),\n tex,\n nullptr,\n nullptr);\n\n SDL_RenderPresent(w.getRenderer());\n\n SDL_Event e;\n while (SDL_WaitEvent(&e)) {\n if (e.type == SDL_QUIT)\n break;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * main.cpp\r\n *\r\n * Created on: May 25, 2015\r\n * Author: Vance Zuo\r\n *\/\r\n\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <cstring>\r\n#include <cmath>\r\n\r\n#include <fstream>\r\n#include <iostream>\r\n#include <vector>\r\n#include <chrono>\r\n\r\n#include <src\/grid.h>\r\n#include <src\/solver.h>\r\n\r\nusing std::string;\r\nusing std::vector;\r\nusing std::istream;\r\nusing std::ifstream;\r\nusing std::locale;\r\nusing std::chrono::high_resolution_clock;\r\nusing std::chrono::duration_cast;\r\nusing std::chrono::nanoseconds;\r\nusing sudoku::Grid;\r\nusing sudoku::Solver;\r\n\r\nvoid printGrid(const Grid& grid) {\r\n int numberSpacing = floor(log10(grid.getMaxValue())) + 1;\r\n for (int i = 0; i < grid.getNumRows(); ++i) {\r\n for (int j = 0; j < grid.getNumCols(); ++j) {\r\n if (grid.getValues(i, j).size() == 1) {\r\n printf(\"%*d \", numberSpacing, *grid.getValues(i, j).begin());\r\n } else {\r\n printf(\"%*s \", numberSpacing, \".\");\r\n }\r\n }\r\n printf(\"\\n\");\r\n }\r\n fflush(stdout);\r\n}\r\n\r\nint readGrid(istream& input, Grid& grid) {\r\n int value;\r\n for (int i = 0; i < grid.size(); ) {\r\n if (input.peek() == EOF)\r\n return i;\r\n if (!(input >> value)) {\r\n input.clear();\r\n input.ignore(1);\r\n continue;\r\n }\r\n grid.assign(i++, value);\r\n }\r\n return grid.size();\r\n}\r\n\r\nvoid printUsage() {\r\n printf(\"Usage: sudoku-solver.exe [-d SUBROWS SUBCOLS] [FILE]\\n\");\r\n}\r\n\r\n\/\/ Main method\r\n\/\/ Args: [-d SUBROWS SUBCOLS] [FILE]\r\nint main(int argc, char **argv) {\r\n int subrows = 3;\r\n int subcols = 3;\r\n istream *input;\r\n ifstream ifs;\r\n\r\n int i = 1;\r\n if (i < argc && !strcmp(argv[i], \"-d\")) {\r\n i = 4;\r\n if (*argv[2] == '\\0' || *argv[3] == '\\0') {\r\n printf(\"Error: Not enough arguments after -d.\\n\");\r\n printUsage();\r\n exit(1);\r\n }\r\n subrows = atoi(argv[2]);\r\n subcols = atoi(argv[3]);\r\n if (subrows == 0 || subcols == 0) {\r\n printf(\"Error: Illegal subrow\/col arguments (should be integers >0).\\n\");\r\n printUsage();\r\n exit(1);\r\n }\r\n }\r\n\r\n if (i < argc && *argv[i] != '\\0') {\r\n ifs.open(argv[i]);\r\n if (!ifs.is_open()) {\r\n printf(\"Error: Could not open file.\\n\");\r\n printUsage();\r\n exit(1);\r\n }\r\n input = &ifs;\r\n } else {\r\n input = &std::cin;\r\n printf(\"Enter the grid as a list of values (0 for blank):\\n\");\r\n }\r\n\r\n int completedGrids = 0;\r\n long totalNs = 0;\r\n while (true) {\r\n Grid grid(subrows, subcols);\r\n int numValues = readGrid(*input, grid);\r\n if (numValues < grid.size()) {\r\n if (numValues > 0 || completedGrids == 0)\r\n printf(\"Warning: Incomplete definition (%d values).\\n\", numValues);\r\n break;\r\n }\r\n if (input != &std::cin)\r\n printGrid(grid);\r\n\r\n auto begin = high_resolution_clock::now();\r\n\r\n Solver solver(grid);\r\n Grid solution;\r\n int steps;\r\n bool solved = solver.solve(solution, steps);\r\n\r\n auto end = high_resolution_clock::now();\r\n auto ns = duration_cast<nanoseconds>(end - begin).count();\r\n totalNs += ns;\r\n\r\n printf(\" ||\\n\");\r\n printf(\" || (%d steps, %.3fs)\\n\", steps, ns \/ 1000000000.0);\r\n printf(\" \\\\\/\\n\");\r\n if (solved) {\r\n printGrid(solution);\r\n } else {\r\n printf(\"[NO SOLUTION]\\n\");\r\n }\r\n printf(\"----\\n\");\r\n\r\n completedGrids++;\r\n }\r\n printf(\"Solved %d grids (%.3fs)\", completedGrids, totalNs \/ 1000000000.0);\r\n\r\n if (ifs.is_open())\r\n ifs.close();\r\n\r\n exit(0);\r\n}\r\n\r\n\r\n\r\n<commit_msg>Change totalNs variable to double type<commit_after>\/*\r\n * main.cpp\r\n *\r\n * Created on: May 25, 2015\r\n * Author: Vance Zuo\r\n *\/\r\n\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <cstring>\r\n#include <cmath>\r\n\r\n#include <fstream>\r\n#include <iostream>\r\n#include <vector>\r\n#include <chrono>\r\n\r\n#include <src\/grid.h>\r\n#include <src\/solver.h>\r\n\r\nusing std::string;\r\nusing std::vector;\r\nusing std::istream;\r\nusing std::ifstream;\r\nusing std::locale;\r\nusing std::chrono::high_resolution_clock;\r\nusing std::chrono::duration_cast;\r\nusing std::chrono::nanoseconds;\r\nusing sudoku::Grid;\r\nusing sudoku::Solver;\r\n\r\nvoid printGrid(const Grid& grid) {\r\n int numberSpacing = floor(log10(grid.getMaxValue())) + 1;\r\n for (int i = 0; i < grid.getNumRows(); ++i) {\r\n for (int j = 0; j < grid.getNumCols(); ++j) {\r\n if (grid.getValues(i, j).size() == 1) {\r\n printf(\"%*d \", numberSpacing, *grid.getValues(i, j).begin());\r\n } else {\r\n printf(\"%*s \", numberSpacing, \".\");\r\n }\r\n }\r\n printf(\"\\n\");\r\n }\r\n fflush(stdout);\r\n}\r\n\r\nint readGrid(istream& input, Grid& grid) {\r\n int value;\r\n for (int i = 0; i < grid.size(); ) {\r\n if (input.peek() == EOF)\r\n return i;\r\n if (!(input >> value)) {\r\n input.clear();\r\n input.ignore(1);\r\n continue;\r\n }\r\n grid.assign(i++, value);\r\n }\r\n return grid.size();\r\n}\r\n\r\nvoid printUsage() {\r\n printf(\"Usage: sudoku-solver.exe [-d SUBROWS SUBCOLS] [FILE]\\n\");\r\n}\r\n\r\n\/\/ Main method\r\n\/\/ Args: [-d SUBROWS SUBCOLS] [FILE]\r\nint main(int argc, char **argv) {\r\n int subrows = 3;\r\n int subcols = 3;\r\n istream *input;\r\n ifstream ifs;\r\n\r\n int i = 1;\r\n if (i < argc && !strcmp(argv[i], \"-d\")) {\r\n i = 4;\r\n if (*argv[2] == '\\0' || *argv[3] == '\\0') {\r\n printf(\"Error: Not enough arguments after -d.\\n\");\r\n printUsage();\r\n exit(1);\r\n }\r\n subrows = atoi(argv[2]);\r\n subcols = atoi(argv[3]);\r\n if (subrows == 0 || subcols == 0) {\r\n printf(\"Error: Illegal subrow\/col arguments (should be integers >0).\\n\");\r\n printUsage();\r\n exit(1);\r\n }\r\n }\r\n\r\n if (i < argc && *argv[i] != '\\0') {\r\n ifs.open(argv[i]);\r\n if (!ifs.is_open()) {\r\n printf(\"Error: Could not open file.\\n\");\r\n printUsage();\r\n exit(1);\r\n }\r\n input = &ifs;\r\n } else {\r\n input = &std::cin;\r\n printf(\"Enter the grid as a list of values (0 for blank):\\n\");\r\n }\r\n\r\n int completedGrids = 0;\r\n double totalNs = 0;\r\n while (true) {\r\n Grid grid(subrows, subcols);\r\n int numValues = readGrid(*input, grid);\r\n if (numValues < grid.size()) {\r\n if (numValues > 0 || completedGrids == 0)\r\n printf(\"Warning: Incomplete definition (%d values).\\n\", numValues);\r\n break;\r\n }\r\n if (input != &std::cin)\r\n printGrid(grid);\r\n\r\n auto begin = high_resolution_clock::now();\r\n\r\n Solver solver(grid);\r\n Grid solution;\r\n int steps;\r\n bool solved = solver.solve(solution, steps);\r\n\r\n auto end = high_resolution_clock::now();\r\n auto ns = duration_cast<nanoseconds>(end - begin).count();\r\n totalNs += ns;\r\n\r\n printf(\" ||\\n\");\r\n printf(\" || (%d steps, %.3fs)\\n\", steps, ns \/ 1000000000.0);\r\n printf(\" \\\\\/\\n\");\r\n if (solved) {\r\n printGrid(solution);\r\n } else {\r\n printf(\"[NO SOLUTION]\\n\");\r\n }\r\n printf(\"----\\n\");\r\n\r\n completedGrids++;\r\n }\r\n printf(\"Solved %d grids (%.3fs)\", completedGrids, totalNs \/ 1000000000.0);\r\n\r\n if (ifs.is_open())\r\n ifs.close();\r\n\r\n exit(0);\r\n}\r\n\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include \"SimpleClient.h\"\n#include \"Job\/Remote.h\"\n#include \"Job\/StdInput.h\"\n\n#include <string>\n#include <list>\n#include <iostream>\n\nvoid printSizes()\n{\n cefpdf::PageSizesMap::const_iterator it;\n\n for (it = cefpdf::pageSizesMap.begin(); it != cefpdf::pageSizesMap.end(); ++it) {\n std::cout << it->name << \" \" << it->width << \"x\" << it->height << std::endl;\n }\n}\n\nvoid printHelp(std::string name)\n{\n std::cout << name << \" v\" << cefpdf::constants::version << std::endl;\n std::cout << \" Creates PDF files from HTML pages\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Usage:\" << std::endl;\n std::cout << \" cef-pdf [options] [--url=<input>] [output]\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Options:\" << std::endl;\n std::cout << \" --help -h This help screen.\" << std::endl;\n std::cout << \" --url=<input> URL to load, may be http, file, data, anything supported by Chromium.\" << std::endl;\n std::cout << \" If omitted standard input is read.\" << std::endl;\n std::cout << \" --size=<size> Size (format) of the paper: A3, B2.. or custom <width>x<height> in mm.\" << std::endl;\n std::cout << \" A4 is the default.\" << std::endl;\n std::cout << \" --list-sizes Show all defined page sizes.\" << std::endl;\n std::cout << \" --landscape Wheather to print with a landscape page orientation.\" << std::endl;\n std::cout << \" Default is portrait\" << std::endl;\n std::cout << \" --margin=<margin> Paper margins in mm (much like CSS margin but without units)\" << std::endl;\n std::cout << \" If omitted default margin is applied.\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Output:\" << std::endl;\n std::cout << \" PDF file name to create. Default is output.pdf\" << std::endl;\n std::cout << std::endl;\n}\n\nstd::string getExecutableName(CefString path)\n{\n std::string program = path.ToString();\n\n \/\/ Remove directory if present.\n \/\/ Do this before extension removal in case directory has a period character.\n const std::size_t s = program.find_last_of(\"\\\\\/\");\n if (std::string::npos != s) {\n program.erase(0, s + 1);\n }\n\n \/\/ Remove extension if present.\n const std::size_t e = program.rfind('.');\n if (std::string::npos != e) {\n program.erase(e);\n }\n\n return program;\n}\n\nint main(int argc, char* argv[])\n{\n CefRefPtr<cefpdf::SimpleClient> app = new cefpdf::SimpleClient();\n\n \/\/ Execute the sub-process logic, if any. This will either return immediately for the browser\n \/\/ process or block until the sub-process should exit.\n CefMainArgs mainArgs;\n int exitCode = CefExecuteProcess(mainArgs, app, NULL);\n if (exitCode >= 0) {\n \/\/ The sub-process terminated, exit now.\n return exitCode;\n }\n\n CefRefPtr<CefCommandLine> commandLine = CefCommandLine::CreateCommandLine();\n\n#if defined(OS_WIN)\n commandLine->InitFromString(::GetCommandLineW());\n#else\n commandLine->InitFromArgv(argc, argv);\n#endif\n\n if (commandLine->HasSwitch(\"help\") || commandLine->HasSwitch(\"h\")) {\n printHelp(::getExecutableName(commandLine->GetProgram()));\n return 0;\n }\n\n if (commandLine->HasSwitch(\"list-sizes\")) {\n printSizes();\n return 0;\n }\n\n cefpdf::job::Job* job;\n\n if (commandLine->HasSwitch(\"url\")) {\n job = new cefpdf::job::Remote(commandLine->GetSwitchValue(\"url\"));\n } else {\n job = new cefpdf::job::StdInput;\n }\n\n \/\/ Set output file\n CefCommandLine::ArgumentList args;\n commandLine->GetArguments(args);\n if (!args.empty()) {\n job->SetOutputPath(args[0]);\n } else {\n job->SetOutputPath(\"output.pdf\");\n }\n\n try {\n if (commandLine->HasSwitch(\"size\")) {\n job->SetPageSize(commandLine->GetSwitchValue(\"size\"));\n }\n\n if (commandLine->HasSwitch(\"margin\")) {\n job->SetPageMargin(commandLine->GetSwitchValue(\"margin\"));\n }\n\n if (commandLine->HasSwitch(\"landscape\")) {\n job->SetLandscape();\n }\n } catch (std::string error) {\n std::cerr << \"ERROR: \" << error << std::endl;\n return 1;\n }\n\n app->QueueJob(job);\n app->Run();\n\n return 0;\n}\n<commit_msg>Small changes in main function<commit_after>#include \"SimpleClient.h\"\n#include \"Job\/Remote.h\"\n#include \"Job\/StdInput.h\"\n\n#include <string>\n#include <list>\n#include <iostream>\n\nvoid printSizes()\n{\n cefpdf::PageSizesMap::const_iterator it;\n\n for (it = cefpdf::pageSizesMap.begin(); it != cefpdf::pageSizesMap.end(); ++it) {\n std::cout << it->name << \" \" << it->width << \"x\" << it->height << std::endl;\n }\n}\n\nvoid printHelp(std::string name)\n{\n std::cout << name << \" v\" << cefpdf::constants::version << std::endl;\n std::cout << \" Creates PDF files from HTML pages\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Usage:\" << std::endl;\n std::cout << \" cef-pdf [options] [--url=<input>] [output]\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Options:\" << std::endl;\n std::cout << \" --help -h This help screen.\" << std::endl;\n std::cout << \" --url=<input> URL to load, may be http, file, data, anything supported by Chromium.\" << std::endl;\n std::cout << \" If omitted standard input is read.\" << std::endl;\n std::cout << \" --size=<size> Size (format) of the paper: A3, B2.. or custom <width>x<height> in mm.\" << std::endl;\n std::cout << \" A4 is the default.\" << std::endl;\n std::cout << \" --list-sizes Show all defined page sizes.\" << std::endl;\n std::cout << \" --landscape Wheather to print with a landscape page orientation.\" << std::endl;\n std::cout << \" Default is portrait\" << std::endl;\n std::cout << \" --margin=<margin> Paper margins in mm (much like CSS margin but without units)\" << std::endl;\n std::cout << \" If omitted default margin is applied.\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Output:\" << std::endl;\n std::cout << \" PDF file name to create. Default is output.pdf\" << std::endl;\n std::cout << std::endl;\n}\n\nstd::string getExecutableName(CefString path)\n{\n std::string program = path.ToString();\n\n \/\/ Remove directory if present.\n \/\/ Do this before extension removal in case directory has a period character.\n const std::size_t s = program.find_last_of(\"\\\\\/\");\n if (std::string::npos != s) {\n program.erase(0, s + 1);\n }\n\n \/\/ Remove extension if present.\n const std::size_t e = program.rfind('.');\n if (std::string::npos != e) {\n program.erase(e);\n }\n\n return program;\n}\n\nint runJob(CefRefPtr<CefCommandLine> commandLine)\n{\n cefpdf::job::Job* job;\n\n if (commandLine->HasSwitch(\"url\")) {\n job = new cefpdf::job::Remote(commandLine->GetSwitchValue(\"url\"));\n } else {\n job = new cefpdf::job::StdInput;\n }\n\n \/\/ Set output file\n CefCommandLine::ArgumentList args;\n commandLine->GetArguments(args);\n if (!args.empty()) {\n job->SetOutputPath(args[0]);\n } else {\n job->SetOutputPath(\"output.pdf\");\n }\n\n try {\n if (commandLine->HasSwitch(\"size\")) {\n job->SetPageSize(commandLine->GetSwitchValue(\"size\"));\n }\n\n if (commandLine->HasSwitch(\"margin\")) {\n job->SetPageMargin(commandLine->GetSwitchValue(\"margin\"));\n }\n\n if (commandLine->HasSwitch(\"landscape\")) {\n job->SetLandscape();\n }\n } catch (std::string error) {\n std::cerr << \"ERROR: \" << error << std::endl;\n return 1;\n }\n\n auto app = new cefpdf::SimpleClient();\n app->QueueJob(job);\n app->Run();\n\n return 0;\n}\n\nint main(int argc, char* argv[])\n{\n\n#if !defined(OS_MACOSX)\n#if defined(OS_WIN)\n CefMainArgs mainArgs(::GetModuleHandle(NULL));\n#else\n CefMainArgs mainArgs(argc, argv);\n#endif \/\/ OS_WIN\n \/\/ Execute the sub-process logic, if any. This will either return immediately for the browser\n \/\/ process or block until the sub-process should exit.\n int exitCode = CefExecuteProcess(mainArgs, NULL, NULL);\n if (exitCode >= 0) {\n \/\/ The sub-process terminated, exit now.\n return exitCode;\n }\n#endif \/\/ !OS_MACOSX\n\n CefRefPtr<CefCommandLine> commandLine = CefCommandLine::CreateCommandLine();\n\n#if defined(OS_WIN)\n commandLine->InitFromString(::GetCommandLine());\n#else\n commandLine->InitFromArgv(argc, argv);\n#endif \/\/ OS_WIN\n\n if (commandLine->HasSwitch(\"help\") || commandLine->HasSwitch(\"h\")) {\n printHelp(getExecutableName(commandLine->GetProgram()));\n return 0;\n }\n\n if (commandLine->HasSwitch(\"list-sizes\")) {\n printSizes();\n return 0;\n }\n\n return runJob(commandLine);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nusing namespace std;\n\nint int main(void) {\n cout << \"Hello World!\" << endl;\n cout << \"This program was written in C++\" << endl;\n cout << \"Bye now!\" << endl;\n\n return 0;\n}\n<commit_msg>Even an Hello World can have bugs :sweat_smile:<commit_after>#include <iostream>\n\nusing namespace std;\n\nint main(void) {\n cout << \"Hello World!\" << endl;\n cout << \"This program was written in C++\" << endl;\n cout << \"Bye now!\" << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <stdio.h>\n#include <unistd.h> \/\/used for fork(), execvp()\n#include <sys\/types.h> \/\/used for wait\n#include <sys\/wait.h> \/\/used for wait\n#include <sys\/stat.h>\n#include <string.h>\n#include <cstdlib>\n#include <vector>\n#include <stack>\n#include \"command.h\"\nusing namespace std;\n\nint main(){\n string user_input = \"\";\n \/\/ bool execStatus = true;\n bool allSpace = true;\n \/\/ vector<string> argsList;\n \n \n while (user_input != \"exit\") {\n Parse p;\n p.print();\n getline(cin, user_input);\n \/\/test for exit\n if(user_input == \"exit\") {\n exit(0);\n }\n \/\/test for empty string\n else if(user_input.size() == 0) {\n break;\n }\n \/\/test for only white spaces\n else {\n \/\/ argsList.clear();\n for(unsigned i = 0; i < user_input.size(); i++) {\n if(user_input.at(i) != ' ') {\n allSpace = false;\n break;\n }\n }\n \/\/the actual shell\n if(!allSpace) { \n p.sepParenthesis(user_input);\n \/\/ e.exec(argsList, execStatus);\n }\n else{\n break;\n }\n }\n }\n return 0;\n}<commit_msg>Delete main.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include <gtest\/gtest.h>\n\n#include <sstream>\n#include <pficommon\/text\/json.h>\n#include <pficommon\/lang\/cast.h>\n\n#include \"jsonconfig.hpp\"\n\nusing namespace std;\nusing namespace pfi::lang;\nusing namespace pfi::text::json;\n\nnamespace jubatus {\nnamespace jsonconfig {\n\nTEST(jsonconfig, bool) {\n json j = json(new json_bool(false));\n EXPECT_EQ(false, config_root(j).As<bool>());\n}\n\nTEST(jsonconfig, bool_type_error) {\n try {\n json j = json(new json_bool(false));\n config_root(j).As<int>();\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Bool, e.actual());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, int) {\n json j = json(new json_integer(10));\n EXPECT_EQ(10, config_root(j).As<int>());\n}\n\nTEST(jsonconfig, int_type_error) {\n try {\n json j = json(new json_integer(10));\n config_root(j).As<std::string>();\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Integer, e.actual());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, float) {\n json j = json(new json_float(0.1));\n EXPECT_FLOAT_EQ(0.1, config_root(j).As<float>());\n}\n\nTEST(jsonconfig, float_type_error) {\n try {\n json j = json(new json_float(0.1));\n config_root(j).As<std::string>();\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Float, e.actual());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, array) {\n json j = json(new json_array());\n j.add(json(new json_integer(10)));\n EXPECT_EQ(10, config_root(j)[0].As<int>());\n}\n\nTEST(jsonconfig, array_out_of_range) {\n json j = json(new json_array());\n try {\n config_root(j)[1].As<int>();\n FAIL();\n } catch (const out_of_range& e) {\n EXPECT_EQ(0u, e.size());\n EXPECT_EQ(1u, e.position());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, array_type_error) {\n json j = json(new json_integer(10));\n config_root c(j);\n try {\n c[1];\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Array, e.expect());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, object) {\n json j = json(new json_object());\n j[\"age\"] = json(new json_integer(10));\n EXPECT_EQ(10, config_root(j)[\"age\"].As<int>());\n}\n\nTEST(jsonconfig, object_not_found) {\n json j = json(new json_object());\n j[\"age\"] = json(new json_integer(10));\n config_root c(j);\n try {\n c[\"name\"];\n FAIL();\n } catch (not_found& e) {\n EXPECT_EQ(\"name\", e.key());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, object_type_error) {\n json j = json(new json_integer(10));\n config_root c(j);\n try {\n c[\"age\"];\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Object, e.expect());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, error_path) {\n json j = json(new json_array());\n j.add(json(new json_object()));\n j[0][\"user\"] = json(new json_object());\n j[0][\"user\"][\"age\"] = json(new json_integer(10));\n config_root c(j);\n try {\n c[0][\"user\"][\"age\"].As<std::string>();\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(\"[0].user.age\", e.path());\n }\n}\n\nTEST(jsonconfig_cast, int) {\n json j(new json_integer(1));\n config_root conf(j);\n EXPECT_EQ(1, config_cast<int>(conf));\n}\n\nTEST(jsonconfig_cast, string) {\n json j(new json_string(\"test\"));\n config_root conf(j);\n EXPECT_EQ(\"test\", config_cast<string>(conf));\n}\n\nTEST(jsonconfig_cast, vector_int) {\n config_root conf(lexical_cast<json>(\"[1,2,3]\"));\n vector<int> v;\n v.push_back(1);\n v.push_back(2);\n v.push_back(3);\n\n EXPECT_EQ(v, config_cast<vector<int> >(conf));\n}\n\nTEST(jsonconfig_cast, map) {\n config_root conf(lexical_cast<json>(\"{\\\"height\\\": 160, \\\"weight\\\": 60}\"));\n map<string, int> m;\n m[\"height\"] = 160;\n m[\"weight\"] = 60;\n\n EXPECT_EQ(m, (config_cast<map<string, int> >(conf)));\n}\n\nTEST(jsonconfig_cast, unordered_map) {\n config_root conf(lexical_cast<json>(\"{\\\"height\\\": 160, \\\"weight\\\": 60}\"));\n pfi::data::unordered_map<string, int> m;\n m[\"height\"] = 160;\n m[\"weight\"] = 60;\n\n pfi::data::unordered_map<string, int> v = config_cast<pfi::data::unordered_map<string, int> >(conf);\n EXPECT_EQ(m[\"height\"], v[\"height\"]);\n EXPECT_EQ(m[\"weight\"], v[\"weight\"]);\n}\n\nTEST(jsonconfig_cast, error_path) {\n config_root conf(lexical_cast<json>(\"{\\\"value\\\": [1,2,\\\"test\\\"]}\"));\n try {\n config_cast<map<string, vector<int> > >(conf);\n FAIL();\n } catch (type_error& e) {\n EXPECT_EQ(\".value[2]\", e.path());\n EXPECT_EQ(json::String, e.actual());\n EXPECT_EQ(json::Integer, e.expect());\n }\n}\n\n\/\/ epxect object[map<K, V>] but [array]\nTEST(jsonconfig_cast, error_convert_map) {\n config_root conf(lexical_cast<json>(\"{\\\"value\\\": []}\"));\n try {\n config_cast<map<string, map<string, string> > >(conf);\n FAIL();\n } catch (type_error& e) {\n EXPECT_EQ(\".value\", e.path());\n EXPECT_EQ(json::Array, e.actual());\n EXPECT_EQ(json::Object, e.expect());\n }\n}\n\n\/\/ epxect object[unordered_map<K, V>] but [array]\nTEST(jsonconfig_cast, error_convert_unordered_map) {\n config_root conf(lexical_cast<json>(\"{\\\"value\\\": []}\"));\n try {\n config_cast<map<string, pfi::data::unordered_map<string, string> > >(conf);\n FAIL();\n } catch (type_error& e) {\n EXPECT_EQ(\".value\", e.path());\n EXPECT_EQ(json::Array, e.actual());\n EXPECT_EQ(json::Object, e.expect());\n }\n}\n\nstruct opt1 {\n int abc;\n pfi::data::optional<int> def;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(abc) & MEMBER(def);\n }\n};\n\nTEST(jsonconfig_cast, named_not_found) {\n config_root conf(lexical_cast<json>(\"{\\\"def\\\": 456}\"));\n\n try {\n opt1 a = config_cast<opt1>(conf);\n FAIL();\n } catch (not_found& e) {\n EXPECT_EQ(\"\", e.path());\n EXPECT_EQ(\"abc\", e.key());\n }\n}\n\nTEST(jsonconfig_cast, named_type_null) {\n config_root conf(lexical_cast<json>(\"{\\\"abc\\\" : null }\"));\n\n try {\n config_cast<opt1>(conf);\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(\".abc\", e.path());\n EXPECT_EQ(json::Null, e.actual());\n EXPECT_EQ(json::Integer, e.expect());\n }\n}\n\nTEST(jsonconfig_cast, named_optional_nullable) {\n config_root conf(lexical_cast<json>(\"{\\\"abc\\\": 123, \\\"def\\\": null}\"));\n ASSERT_NO_THROW(config_cast<opt1>(conf));\n}\n\nstruct opt2 {\n int abc;\n pfi::data::optional<int> def;\n\n struct test {\n int a;\n int b;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(a) & MEMBER(b);\n }\n } test;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(abc) & MEMBER(def) & MEMBER(test);\n }\n};\n\n\nTEST(jsonconfig_cast, named_nest_not_found) {\n config_root conf(lexical_cast<json>(\"{\\\"abc\\\" : 124 }\"));\n\n try {\n config_cast<opt2>(conf);\n FAIL();\n } catch (not_found& e) {\n EXPECT_EQ(\"\", e.path());\n EXPECT_EQ(\"test\", e.key());\n }\n}\n\n#if 0\n\/\/ FIXME: this depends pficommon's issue #122\nTEST(jsonconfig_cast, named_bad_type) {\n config_root conf(lexical_cast<json>(\"{\\\"abc\\\" : 124, \\\"test\\\": [] }\"));\n\n try {\n config_cast<opt2>(conf);\n FAIL();\n } catch (type_error& e) {\n cout << e.what() << endl;\n EXPECT_EQ(\"\", e.path());\n } catch (std::exception& e) {\n cout << \"what?: \" << e.what() << endl;\n }\n}\n#endif\n\nstruct Person {\n string name;\n double height;\n int age;\n map<string, string> attributes;\n pfi::data::optional<string> sport;\n pfi::data::optional<string> hobby;\n\n bool operator ==(const Person& p) const {\n return name == p.name && height == p.height && age == p.age && attributes == p.attributes && sport == p.sport && hobby == p.hobby;\n }\n\n template <class Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(name) & MEMBER(height) & MEMBER(age) & MEMBER(attributes) & MEMBER(sport) & MEMBER(hobby);\n }\n};\n\nTEST(jsonconfig_cast, struct) {\n config_root conf(lexical_cast<json>(\"{\\\"name\\\": \\\"Taro\\\", \\\"height\\\": 160.0, \\\"age\\\": 20, \\\"attributes\\\": {\\\"address\\\": \\\"Tokyo\\\"}, \\\"sport\\\": \\\"tennis\\\"}\"));\n Person p;\n p.name = \"Taro\";\n p.height = 160.0;\n p.age = 20;\n p.attributes[\"address\"] = \"Tokyo\";\n p.sport = \"tennis\";\n\n EXPECT_EQ(p, config_cast<Person>(conf));\n}\n\nstruct server_conf {\n struct web_conf {\n std::string host;\n int port;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(host) & MEMBER(port);\n }\n } web_server;\n\n std::vector<std::string> users;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(web_server) & MEMBER(users);\n }\n};\n\nTEST(jsonconfig_cast, error) {\n config_root conf(lexical_cast<json>(\"{\\\"web_server\\\": { \\\"host\\\" : 123}, \\\"users\\\": [\\\"abc\\\", 1] }\"));\n\n config_error_list errors;\n server_conf c = config_cast<server_conf>(conf, errors);\n\n for (size_t i = 0; i < errors.size(); i++) {\n cout << errors[i]->what() << endl;\n }\n\n EXPECT_EQ(3, errors.size());\n\n type_error* e1 = dynamic_cast<type_error*>(errors[0].get());\n ASSERT_TRUE(e1);\n EXPECT_EQ(\".web_server.host\", e1->path());\n EXPECT_EQ(json::Integer, e1->actual());\n\n not_found* e2 = dynamic_cast<not_found*>(errors[1].get());\n ASSERT_TRUE(e2);\n EXPECT_EQ(\".web_server\", e2->path());\n EXPECT_EQ(\"port\", e2->key());\n\n type_error* e3 = dynamic_cast<type_error*>(errors[2].get());\n ASSERT_TRUE(e3);\n EXPECT_EQ(\".users[1]\", e3->path());\n EXPECT_EQ(json::Integer, e3->actual());\n}\n\n} \/\/ jsonconfig\n} \/\/ jubatus\n<commit_msg>Reformat jsonconfig test<commit_after>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.\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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include <gtest\/gtest.h>\n\n#include <sstream>\n#include <pficommon\/text\/json.h>\n#include <pficommon\/lang\/cast.h>\n\n#include \"jsonconfig.hpp\"\n\nusing namespace std;\nusing namespace pfi::lang;\nusing namespace pfi::text::json;\n\nnamespace jubatus {\nnamespace jsonconfig {\n\nTEST(jsonconfig, bool) {\n json j(new json_bool(false));\n EXPECT_EQ(false, config_root(j).As<bool>());\n}\n\nTEST(jsonconfig, bool_type_error) {\n try {\n json j(new json_bool(false));\n config_root(j).As<int>();\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Bool, e.actual());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, int) {\n json j(new json_integer(10));\n EXPECT_EQ(10, config_root(j).As<int>());\n}\n\nTEST(jsonconfig, int_type_error) {\n try {\n json j(new json_integer(10));\n config_root(j).As<std::string>();\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Integer, e.actual());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, float) {\n json j(new json_float(0.1));\n EXPECT_FLOAT_EQ(0.1, config_root(j).As<float>());\n}\n\nTEST(jsonconfig, float_type_error) {\n try {\n json j(new json_float(0.1));\n config_root(j).As<std::string>();\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Float, e.actual());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, array) {\n json j(new json_array());\n j.add(json(new json_integer(10)));\n EXPECT_EQ(10, config_root(j)[0].As<int>());\n}\n\nTEST(jsonconfig, array_out_of_range) {\n json j(new json_array());\n try {\n config_root(j)[1].As<int>();\n FAIL();\n } catch (const out_of_range& e) {\n EXPECT_EQ(0u, e.size());\n EXPECT_EQ(1u, e.position());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, array_type_error) {\n json j(new json_integer(10));\n config_root c(j);\n try {\n c[1];\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Array, e.expect());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, object) {\n json j(new json_object());\n j[\"age\"] = json(new json_integer(10));\n EXPECT_EQ(10, config_root(j)[\"age\"].As<int>());\n}\n\nTEST(jsonconfig, object_not_found) {\n json j(new json_object());\n j[\"age\"] = json(new json_integer(10));\n config_root c(j);\n try {\n c[\"name\"];\n FAIL();\n } catch (const not_found& e) {\n EXPECT_EQ(\"name\", e.key());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, object_type_error) {\n json j(new json_integer(10));\n config_root c(j);\n try {\n c[\"age\"];\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(json::Object, e.expect());\n EXPECT_EQ(\"\", e.path());\n }\n}\n\nTEST(jsonconfig, error_path) {\n json j(new json_array());\n j.add(json(new json_object()));\n j[0][\"user\"] = json(new json_object());\n j[0][\"user\"][\"age\"] = json(new json_integer(10));\n config_root c(j);\n try {\n c[0][\"user\"][\"age\"].As<std::string>();\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(\"[0].user.age\", e.path());\n }\n}\n\nTEST(jsonconfig_cast, int) {\n json j(new json_integer(1));\n config_root conf(j);\n EXPECT_EQ(1, config_cast<int>(conf));\n}\n\nTEST(jsonconfig_cast, string) {\n json j(new json_string(\"test\"));\n config_root conf(j);\n EXPECT_EQ(\"test\", config_cast<string>(conf));\n}\n\nTEST(jsonconfig_cast, vector_int) {\n config_root conf(lexical_cast<json>(\"[1,2,3]\"));\n vector<int> v;\n v.push_back(1);\n v.push_back(2);\n v.push_back(3);\n\n EXPECT_EQ(v, config_cast<vector<int> >(conf));\n}\n\nTEST(jsonconfig_cast, map) {\n config_root conf(lexical_cast<json>(\"{\\\"height\\\": 160, \\\"weight\\\": 60}\"));\n map<string, int> m;\n m[\"height\"] = 160;\n m[\"weight\"] = 60;\n\n EXPECT_EQ(m, (config_cast<map<string, int> >(conf)));\n}\n\nTEST(jsonconfig_cast, unordered_map) {\n config_root conf(lexical_cast<json>(\"{\\\"height\\\": 160, \\\"weight\\\": 60}\"));\n pfi::data::unordered_map<string, int> m;\n m[\"height\"] = 160;\n m[\"weight\"] = 60;\n\n pfi::data::unordered_map<string, int> v = config_cast<pfi::data::unordered_map<string, int> >(conf);\n EXPECT_EQ(m[\"height\"], v[\"height\"]);\n EXPECT_EQ(m[\"weight\"], v[\"weight\"]);\n}\n\nTEST(jsonconfig_cast, error_path) {\n config_root conf(lexical_cast<json>(\"{\\\"value\\\": [1,2,\\\"test\\\"]}\"));\n try {\n config_cast<map<string, vector<int> > >(conf);\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(\".value[2]\", e.path());\n EXPECT_EQ(json::String, e.actual());\n EXPECT_EQ(json::Integer, e.expect());\n }\n}\n\n\/\/ epxect object[map<K, V>] but [array]\nTEST(jsonconfig_cast, error_convert_map) {\n config_root conf(lexical_cast<json>(\"{\\\"value\\\": []}\"));\n try {\n config_cast<map<string, map<string, string> > >(conf);\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(\".value\", e.path());\n EXPECT_EQ(json::Array, e.actual());\n EXPECT_EQ(json::Object, e.expect());\n }\n}\n\n\/\/ epxect object[unordered_map<K, V>] but [array]\nTEST(jsonconfig_cast, error_convert_unordered_map) {\n config_root conf(lexical_cast<json>(\"{\\\"value\\\": []}\"));\n try {\n config_cast<map<string, pfi::data::unordered_map<string, string> > >(conf);\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(\".value\", e.path());\n EXPECT_EQ(json::Array, e.actual());\n EXPECT_EQ(json::Object, e.expect());\n }\n}\n\nstruct opt1 {\n int abc;\n pfi::data::optional<int> def;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(abc) & MEMBER(def);\n }\n};\n\nTEST(jsonconfig_cast, named_not_found) {\n config_root conf(lexical_cast<json>(\"{\\\"def\\\": 456}\"));\n\n try {\n opt1 a = config_cast<opt1>(conf);\n FAIL();\n } catch (const not_found& e) {\n EXPECT_EQ(\"\", e.path());\n EXPECT_EQ(\"abc\", e.key());\n }\n}\n\nTEST(jsonconfig_cast, named_type_null) {\n config_root conf(lexical_cast<json>(\"{\\\"abc\\\" : null }\"));\n\n try {\n config_cast<opt1>(conf);\n FAIL();\n } catch (const type_error& e) {\n EXPECT_EQ(\".abc\", e.path());\n EXPECT_EQ(json::Null, e.actual());\n EXPECT_EQ(json::Integer, e.expect());\n }\n}\n\nTEST(jsonconfig_cast, named_optional_nullable) {\n config_root conf(lexical_cast<json>(\"{\\\"abc\\\": 123, \\\"def\\\": null}\"));\n ASSERT_NO_THROW(config_cast<opt1>(conf));\n}\n\nstruct opt2 {\n int abc;\n pfi::data::optional<int> def;\n\n struct test {\n int a;\n int b;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(a) & MEMBER(b);\n }\n } test;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(abc) & MEMBER(def) & MEMBER(test);\n }\n};\n\n\nTEST(jsonconfig_cast, named_nest_not_found) {\n config_root conf(lexical_cast<json>(\"{\\\"abc\\\" : 124 }\"));\n\n try {\n config_cast<opt2>(conf);\n FAIL();\n } catch (const not_found& e) {\n EXPECT_EQ(\"\", e.path());\n EXPECT_EQ(\"test\", e.key());\n }\n}\n\n#if 0\n\/\/ FIXME: this depends pficommon's issue #122\nTEST(jsonconfig_cast, named_bad_type) {\n config_root conf(lexical_cast<json>(\"{\\\"abc\\\" : 124, \\\"test\\\": [] }\"));\n\n try {\n config_cast<opt2>(conf);\n FAIL();\n } catch (type_error& e) {\n cout << e.what() << endl;\n EXPECT_EQ(\"\", e.path());\n } catch (std::exception& e) {\n cout << \"what?: \" << e.what() << endl;\n }\n}\n#endif\n\nstruct Person {\n string name;\n double height;\n int age;\n map<string, string> attributes;\n pfi::data::optional<string> sport;\n pfi::data::optional<string> hobby;\n\n bool operator ==(const Person& p) const {\n return name == p.name && height == p.height && age == p.age && attributes == p.attributes && sport == p.sport && hobby == p.hobby;\n }\n\n template <class Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(name) & MEMBER(height) & MEMBER(age) & MEMBER(attributes) & MEMBER(sport) & MEMBER(hobby);\n }\n};\n\nTEST(jsonconfig_cast, struct) {\n config_root conf(lexical_cast<json>(\"{\\\"name\\\": \\\"Taro\\\", \\\"height\\\": 160.0, \\\"age\\\": 20, \\\"attributes\\\": {\\\"address\\\": \\\"Tokyo\\\"}, \\\"sport\\\": \\\"tennis\\\"}\"));\n Person p;\n p.name = \"Taro\";\n p.height = 160.0;\n p.age = 20;\n p.attributes[\"address\"] = \"Tokyo\";\n p.sport = \"tennis\";\n\n EXPECT_EQ(p, config_cast<Person>(conf));\n}\n\nstruct server_conf {\n struct web_conf {\n std::string host;\n int port;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(host) & MEMBER(port);\n }\n } web_server;\n\n std::vector<std::string> users;\n\n template <typename Ar>\n void serialize(Ar& ar) {\n ar & MEMBER(web_server) & MEMBER(users);\n }\n};\n\nTEST(jsonconfig_cast, error) {\n config_root conf(lexical_cast<json>(\"{\\\"web_server\\\": { \\\"host\\\" : 123}, \\\"users\\\": [\\\"abc\\\", 1] }\"));\n\n config_error_list errors;\n server_conf c = config_cast<server_conf>(conf, errors);\n\n for (size_t i = 0; i < errors.size(); i++) {\n cout << errors[i]->what() << endl;\n }\n\n EXPECT_EQ(3, errors.size());\n\n type_error* e1 = dynamic_cast<type_error*>(errors[0].get());\n ASSERT_TRUE(e1);\n EXPECT_EQ(\".web_server.host\", e1->path());\n EXPECT_EQ(json::Integer, e1->actual());\n\n not_found* e2 = dynamic_cast<not_found*>(errors[1].get());\n ASSERT_TRUE(e2);\n EXPECT_EQ(\".web_server\", e2->path());\n EXPECT_EQ(\"port\", e2->key());\n\n type_error* e3 = dynamic_cast<type_error*>(errors[2].get());\n ASSERT_TRUE(e3);\n EXPECT_EQ(\".users[1]\", e3->path());\n EXPECT_EQ(json::Integer, e3->actual());\n}\n\n} \/\/ jsonconfig\n} \/\/ jubatus\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 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 \"content\/shell\/browser\/shell_browser_main.h\"\n\n#include <iostream>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/strings\/sys_string_conversions.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"content\/public\/browser\/browser_main_runner.h\"\n#include \"content\/shell\/browser\/shell.h\"\n#include \"content\/shell\/browser\/webkit_test_controller.h\"\n#include \"content\/shell\/common\/shell_switches.h\"\n#include \"content\/shell\/common\/webkit_test_helpers.h\"\n#include \"content\/test\/webkit_support.h\"\n#include \"net\/base\/net_util.h\"\n\n#if defined(OS_ANDROID)\n#include \"base\/run_loop.h\"\n#include \"content\/shell\/browser\/shell_layout_tests_android.h\"\n#endif\n\nnamespace {\n\nGURL GetURLForLayoutTest(const std::string& test_name,\n base::FilePath* current_working_directory,\n bool* enable_pixel_dumping,\n std::string* expected_pixel_hash) {\n \/\/ A test name is formated like file:\/\/\/path\/to\/test'--pixel-test'pixelhash\n std::string path_or_url = test_name;\n std::string pixel_switch;\n std::string pixel_hash;\n std::string::size_type separator_position = path_or_url.find('\\'');\n if (separator_position != std::string::npos) {\n pixel_switch = path_or_url.substr(separator_position + 1);\n path_or_url.erase(separator_position);\n }\n separator_position = pixel_switch.find('\\'');\n if (separator_position != std::string::npos) {\n pixel_hash = pixel_switch.substr(separator_position + 1);\n pixel_switch.erase(separator_position);\n }\n if (enable_pixel_dumping) {\n *enable_pixel_dumping =\n (pixel_switch == \"--pixel-test\" || pixel_switch == \"-p\");\n }\n if (expected_pixel_hash)\n *expected_pixel_hash = pixel_hash;\n\n GURL test_url;\n#if defined(OS_ANDROID)\n if (content::GetTestUrlForAndroid(path_or_url, &test_url))\n return test_url;\n#endif\n\n test_url = GURL(path_or_url);\n if (!(test_url.is_valid() && test_url.has_scheme())) {\n \/\/ We're outside of the message loop here, and this is a test.\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n#if defined(OS_WIN)\n std::wstring wide_path_or_url =\n base::SysNativeMBToWide(path_or_url);\n base::FilePath local_file(wide_path_or_url);\n#else\n base::FilePath local_file(path_or_url);\n#endif\n if (!base::PathExists(local_file)) {\n local_file = content::GetWebKitRootDirFilePath()\n .Append(FILE_PATH_LITERAL(\"LayoutTests\")).Append(local_file);\n }\n test_url = net::FilePathToFileURL(base::MakeAbsoluteFilePath(local_file));\n }\n base::FilePath local_path;\n if (current_working_directory) {\n \/\/ We're outside of the message loop here, and this is a test.\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n if (net::FileURLToFilePath(test_url, &local_path))\n *current_working_directory = local_path.DirName();\n else\n file_util::GetCurrentDirectory(current_working_directory);\n }\n return test_url;\n}\n\nbool GetNextTest(const CommandLine::StringVector& args,\n size_t* position,\n std::string* test) {\n if (*position >= args.size())\n return false;\n if (args[*position] == FILE_PATH_LITERAL(\"-\"))\n return !!std::getline(std::cin, *test, '\\n');\n#if defined(OS_WIN)\n *test = WideToUTF8(args[(*position)++]);\n#else\n *test = args[(*position)++];\n#endif\n return true;\n}\n\n} \/\/ namespace\n\n\/\/ Main routine for running as the Browser process.\nint ShellBrowserMain(\n const content::MainFunctionParams& parameters,\n const scoped_ptr<content::BrowserMainRunner>& main_runner) {\n bool layout_test_mode =\n CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree);\n base::ScopedTempDir browser_context_path_for_layout_tests;\n\n if (layout_test_mode) {\n CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir());\n CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty());\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kContentShellDataPath,\n browser_context_path_for_layout_tests.path().MaybeAsASCII());\n\n#if defined(OS_ANDROID)\n content::EnsureInitializeForAndroidLayoutTests();\n#endif\n }\n\n int exit_code = main_runner->Initialize(parameters);\n DCHECK_LT(exit_code, 0)\n << \"BrowserMainRunner::Initialize failed in ShellBrowserMain\";\n\n if (exit_code >= 0)\n return exit_code;\n\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kCheckLayoutTestSysDeps)) {\n base::MessageLoop::current()->PostTask(FROM_HERE,\n base::MessageLoop::QuitClosure());\n main_runner->Run();\n content::Shell::CloseAllWindows();\n main_runner->Shutdown();\n return 0;\n }\n\n if (layout_test_mode) {\n content::WebKitTestController test_controller;\n {\n \/\/ We're outside of the message loop here, and this is a test.\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n base::FilePath temp_path;\n file_util::GetTempDir(&temp_path);\n test_controller.SetTempPath(temp_path);\n }\n std::string test_string;\n CommandLine::StringVector args =\n CommandLine::ForCurrentProcess()->GetArgs();\n size_t command_line_position = 0;\n bool ran_at_least_once = false;\n\n#if defined(OS_ANDROID)\n std::cout << \"#READY\\n\";\n std::cout.flush();\n#endif\n\n while (GetNextTest(args, &command_line_position, &test_string)) {\n if (test_string.empty())\n continue;\n if (test_string == \"QUIT\")\n break;\n\n bool enable_pixel_dumps;\n std::string pixel_hash;\n base::FilePath cwd;\n GURL test_url = GetURLForLayoutTest(\n test_string, &cwd, &enable_pixel_dumps, &pixel_hash);\n if (!content::WebKitTestController::Get()->PrepareForLayoutTest(\n test_url, cwd, enable_pixel_dumps, pixel_hash)) {\n break;\n }\n\n ran_at_least_once = true;\n#if defined(OS_ANDROID)\n \/\/ The message loop on Android is provided by the system, and does not\n \/\/ offer a blocking Run() method. For layout tests, use a nested loop\n \/\/ together with a base::RunLoop so it can block until a QuitClosure.\n base::RunLoop run_loop;\n run_loop.Run();\n#else\n main_runner->Run();\n#endif\n\n if (!content::WebKitTestController::Get()->ResetAfterLayoutTest())\n break;\n\n#if defined(OS_ANDROID)\n \/\/ There will be left-over tasks in the queue for Android because the\n \/\/ main window is being destroyed. Run them before starting the next test.\n base::MessageLoop::current()->RunUntilIdle();\n#endif\n }\n if (!ran_at_least_once) {\n base::MessageLoop::current()->PostTask(FROM_HERE,\n base::MessageLoop::QuitClosure());\n main_runner->Run();\n }\n\n#if defined(OS_ANDROID)\n \/\/ Android should only execute Shutdown() here when running layout tests.\n main_runner->Shutdown();\n#endif\n\n exit_code = 0;\n }\n\n#if !defined(OS_ANDROID)\n if (!layout_test_mode)\n exit_code = main_runner->Run();\n\n main_runner->Shutdown();\n#endif\n\n return exit_code;\n}\n<commit_msg>Print #READY from content_shell for non-Android platforms.<commit_after>\/\/ Copyright 2013 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 \"content\/shell\/browser\/shell_browser_main.h\"\n\n#include <iostream>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/strings\/sys_string_conversions.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"content\/public\/browser\/browser_main_runner.h\"\n#include \"content\/shell\/browser\/shell.h\"\n#include \"content\/shell\/browser\/webkit_test_controller.h\"\n#include \"content\/shell\/common\/shell_switches.h\"\n#include \"content\/shell\/common\/webkit_test_helpers.h\"\n#include \"content\/test\/webkit_support.h\"\n#include \"net\/base\/net_util.h\"\n\n#if defined(OS_ANDROID)\n#include \"base\/run_loop.h\"\n#include \"content\/shell\/browser\/shell_layout_tests_android.h\"\n#endif\n\nnamespace {\n\nGURL GetURLForLayoutTest(const std::string& test_name,\n base::FilePath* current_working_directory,\n bool* enable_pixel_dumping,\n std::string* expected_pixel_hash) {\n \/\/ A test name is formated like file:\/\/\/path\/to\/test'--pixel-test'pixelhash\n std::string path_or_url = test_name;\n std::string pixel_switch;\n std::string pixel_hash;\n std::string::size_type separator_position = path_or_url.find('\\'');\n if (separator_position != std::string::npos) {\n pixel_switch = path_or_url.substr(separator_position + 1);\n path_or_url.erase(separator_position);\n }\n separator_position = pixel_switch.find('\\'');\n if (separator_position != std::string::npos) {\n pixel_hash = pixel_switch.substr(separator_position + 1);\n pixel_switch.erase(separator_position);\n }\n if (enable_pixel_dumping) {\n *enable_pixel_dumping =\n (pixel_switch == \"--pixel-test\" || pixel_switch == \"-p\");\n }\n if (expected_pixel_hash)\n *expected_pixel_hash = pixel_hash;\n\n GURL test_url;\n#if defined(OS_ANDROID)\n if (content::GetTestUrlForAndroid(path_or_url, &test_url))\n return test_url;\n#endif\n\n test_url = GURL(path_or_url);\n if (!(test_url.is_valid() && test_url.has_scheme())) {\n \/\/ We're outside of the message loop here, and this is a test.\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n#if defined(OS_WIN)\n std::wstring wide_path_or_url =\n base::SysNativeMBToWide(path_or_url);\n base::FilePath local_file(wide_path_or_url);\n#else\n base::FilePath local_file(path_or_url);\n#endif\n if (!base::PathExists(local_file)) {\n local_file = content::GetWebKitRootDirFilePath()\n .Append(FILE_PATH_LITERAL(\"LayoutTests\")).Append(local_file);\n }\n test_url = net::FilePathToFileURL(base::MakeAbsoluteFilePath(local_file));\n }\n base::FilePath local_path;\n if (current_working_directory) {\n \/\/ We're outside of the message loop here, and this is a test.\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n if (net::FileURLToFilePath(test_url, &local_path))\n *current_working_directory = local_path.DirName();\n else\n file_util::GetCurrentDirectory(current_working_directory);\n }\n return test_url;\n}\n\nbool GetNextTest(const CommandLine::StringVector& args,\n size_t* position,\n std::string* test) {\n if (*position >= args.size())\n return false;\n if (args[*position] == FILE_PATH_LITERAL(\"-\"))\n return !!std::getline(std::cin, *test, '\\n');\n#if defined(OS_WIN)\n *test = WideToUTF8(args[(*position)++]);\n#else\n *test = args[(*position)++];\n#endif\n return true;\n}\n\n} \/\/ namespace\n\n\/\/ Main routine for running as the Browser process.\nint ShellBrowserMain(\n const content::MainFunctionParams& parameters,\n const scoped_ptr<content::BrowserMainRunner>& main_runner) {\n bool layout_test_mode =\n CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree);\n base::ScopedTempDir browser_context_path_for_layout_tests;\n\n if (layout_test_mode) {\n CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir());\n CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty());\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kContentShellDataPath,\n browser_context_path_for_layout_tests.path().MaybeAsASCII());\n\n#if defined(OS_ANDROID)\n content::EnsureInitializeForAndroidLayoutTests();\n#endif\n }\n\n int exit_code = main_runner->Initialize(parameters);\n DCHECK_LT(exit_code, 0)\n << \"BrowserMainRunner::Initialize failed in ShellBrowserMain\";\n\n if (exit_code >= 0)\n return exit_code;\n\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kCheckLayoutTestSysDeps)) {\n base::MessageLoop::current()->PostTask(FROM_HERE,\n base::MessageLoop::QuitClosure());\n main_runner->Run();\n content::Shell::CloseAllWindows();\n main_runner->Shutdown();\n return 0;\n }\n\n if (layout_test_mode) {\n content::WebKitTestController test_controller;\n {\n \/\/ We're outside of the message loop here, and this is a test.\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n base::FilePath temp_path;\n file_util::GetTempDir(&temp_path);\n test_controller.SetTempPath(temp_path);\n }\n std::string test_string;\n CommandLine::StringVector args =\n CommandLine::ForCurrentProcess()->GetArgs();\n size_t command_line_position = 0;\n bool ran_at_least_once = false;\n\n std::cout << \"#READY\\n\";\n std::cout.flush();\n\n while (GetNextTest(args, &command_line_position, &test_string)) {\n if (test_string.empty())\n continue;\n if (test_string == \"QUIT\")\n break;\n\n bool enable_pixel_dumps;\n std::string pixel_hash;\n base::FilePath cwd;\n GURL test_url = GetURLForLayoutTest(\n test_string, &cwd, &enable_pixel_dumps, &pixel_hash);\n if (!content::WebKitTestController::Get()->PrepareForLayoutTest(\n test_url, cwd, enable_pixel_dumps, pixel_hash)) {\n break;\n }\n\n ran_at_least_once = true;\n#if defined(OS_ANDROID)\n \/\/ The message loop on Android is provided by the system, and does not\n \/\/ offer a blocking Run() method. For layout tests, use a nested loop\n \/\/ together with a base::RunLoop so it can block until a QuitClosure.\n base::RunLoop run_loop;\n run_loop.Run();\n#else\n main_runner->Run();\n#endif\n\n if (!content::WebKitTestController::Get()->ResetAfterLayoutTest())\n break;\n\n#if defined(OS_ANDROID)\n \/\/ There will be left-over tasks in the queue for Android because the\n \/\/ main window is being destroyed. Run them before starting the next test.\n base::MessageLoop::current()->RunUntilIdle();\n#endif\n }\n if (!ran_at_least_once) {\n base::MessageLoop::current()->PostTask(FROM_HERE,\n base::MessageLoop::QuitClosure());\n main_runner->Run();\n }\n\n#if defined(OS_ANDROID)\n \/\/ Android should only execute Shutdown() here when running layout tests.\n main_runner->Shutdown();\n#endif\n\n exit_code = 0;\n }\n\n#if !defined(OS_ANDROID)\n if (!layout_test_mode)\n exit_code = main_runner->Run();\n\n main_runner->Shutdown();\n#endif\n\n return exit_code;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2013 Jolla Ltd.\n** Contact: Aaron Kennedy <aaron.kennedy@jollamobile.com>\n**\n** This file is part of lipstick.\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 <QDBusConnection>\n#include \"lipstickcompositorwindow.h\"\n#include \"lipstickcompositor.h\"\n#include \"windowmodel.h\"\n\nWindowModel::WindowModel()\n: m_complete(false)\n{\n LipstickCompositor *c = LipstickCompositor::instance();\n if (!c) {\n qWarning(\"WindowModel: Compositor must be created before WindowModel\");\n } else {\n c->m_windowModels.append(this);\n }\n\n QDBusConnection dbus = QDBusConnection::sessionBus();\n dbus.registerObject(\"\/WindowModel\", this, QDBusConnection::ExportAllSlots);\n dbus.registerService(\"org.nemomobile.lipstick\");\n}\n\nWindowModel::~WindowModel()\n{\n LipstickCompositor *c = LipstickCompositor::instance();\n if (c) c->m_windowModels.removeAll(this);\n}\n\nint WindowModel::itemCount() const\n{\n return m_items.count();\n}\n\nint WindowModel::windowId(int index) const\n{\n if (index < 0 || index >= m_items.count())\n return 0;\n return m_items.at(index);\n}\n\nint WindowModel::rowCount(const QModelIndex &) const\n{\n return m_items.count();\n}\n\nQVariant WindowModel::data(const QModelIndex &index, int role) const\n{\n int idx = index.row();\n if (idx < 0 || idx >= m_items.count())\n return QVariant();\n\n LipstickCompositor *c = LipstickCompositor::instance();\n if (role == Qt::UserRole + 1) {\n return m_items.at(idx);\n } else if (role == Qt::UserRole + 2) {\n QWaylandSurface *s = c->surfaceForId(m_items.at(idx));\n return s?s->processId():0;\n } else if (role == Qt::UserRole + 3) {\n LipstickCompositorWindow *w = static_cast<LipstickCompositorWindow *>(c->windowForId(m_items.at(idx)));\n return w->title();\n } else {\n return QVariant();\n }\n}\n\nQHash<int, QByteArray> WindowModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles[Qt::UserRole + 1] = \"window\";\n roles[Qt::UserRole + 2] = \"processId\";\n roles[Qt::UserRole + 3] = \"title\";\n return roles;\n}\n\nvoid WindowModel::classBegin()\n{\n}\n\nvoid WindowModel::componentComplete()\n{\n m_complete = true;\n refresh();\n}\n\n\/*!\n Reimplement this method to provide custom filtering.\n*\/\nbool WindowModel::approveWindow(LipstickCompositorWindow *window)\n{\n return window->isInProcess() == false && \n window->category() != QLatin1String(\"overlay\");\n}\n\nvoid WindowModel::addItem(int id)\n{\n if (!m_complete)\n return;\n\n LipstickCompositor *c = LipstickCompositor::instance();\n LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(c->windowForId(id));\n if (!approveWindow(window))\n return;\n\n beginInsertRows(QModelIndex(), m_items.count(), m_items.count());\n m_items.append(id);\n endInsertRows();\n emit itemAdded(m_items.count() - 1);\n emit itemCountChanged();\n}\n\nvoid WindowModel::remItem(int id)\n{\n if (!m_complete)\n return;\n\n int idx = m_items.indexOf(id);\n if (idx == -1)\n return;\n\n beginRemoveRows(QModelIndex(), idx, idx);\n m_items.removeAt(idx);\n endRemoveRows();\n emit itemCountChanged();\n}\n\nvoid WindowModel::titleChanged(int id)\n{\n if (!m_complete)\n return;\n\n int idx = m_items.indexOf(id);\n if (idx == -1)\n return;\n\n emit dataChanged(index(idx, 0), index(idx, 0));\n}\n\nvoid WindowModel::refresh()\n{\n LipstickCompositor *c = LipstickCompositor::instance();\n if (!m_complete || !c)\n return;\n\n beginResetModel();\n\n m_items.clear();\n\n for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin();\n iter != c->m_mappedSurfaces.end(); ++iter) {\n\n if (approveWindow(iter.value()))\n m_items.append(iter.key());\n }\n\n endResetModel();\n}\n\n\/\/ used by mapplauncherd to bring a binary to the front\nvoid WindowModel::launchProcess(const QString &binaryName)\n{\n LipstickCompositor *c = LipstickCompositor::instance();\n if (!m_complete || !c)\n return;\n\n for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin();\n iter != c->m_mappedSurfaces.end(); ++iter) {\n\n LipstickCompositorWindow *win = iter.value();\n if (!approveWindow(win))\n continue;\n\n QString pidFile = QString::fromLatin1(\"\/proc\/%1\/cmdline\").arg(win->processId());\n QFile f(pidFile);\n if (!f.open(QIODevice::ReadOnly)) {\n qWarning() << Q_FUNC_INFO << \"Cannot open cmdline for \" << pidFile;\n continue;\n }\n\n \/\/ cmdline contains a \\0, so we use constData to truncate that away\n QByteArray proc = QByteArray(f.readAll().constData());\n\n if (proc != binaryName)\n continue;\n\n win->surface()->raiseRequested();\n break;\n }\n}\n\n<commit_msg>[windowmodel] Add support for multi-arg binaryName in launchProcess<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2013 Jolla Ltd.\n** Contact: Aaron Kennedy <aaron.kennedy@jollamobile.com>\n**\n** This file is part of lipstick.\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 <QDBusConnection>\n#include \"lipstickcompositorwindow.h\"\n#include \"lipstickcompositor.h\"\n#include \"windowmodel.h\"\n\nWindowModel::WindowModel()\n: m_complete(false)\n{\n LipstickCompositor *c = LipstickCompositor::instance();\n if (!c) {\n qWarning(\"WindowModel: Compositor must be created before WindowModel\");\n } else {\n c->m_windowModels.append(this);\n }\n\n QDBusConnection dbus = QDBusConnection::sessionBus();\n dbus.registerObject(\"\/WindowModel\", this, QDBusConnection::ExportAllSlots);\n dbus.registerService(\"org.nemomobile.lipstick\");\n}\n\nWindowModel::~WindowModel()\n{\n LipstickCompositor *c = LipstickCompositor::instance();\n if (c) c->m_windowModels.removeAll(this);\n}\n\nint WindowModel::itemCount() const\n{\n return m_items.count();\n}\n\nint WindowModel::windowId(int index) const\n{\n if (index < 0 || index >= m_items.count())\n return 0;\n return m_items.at(index);\n}\n\nint WindowModel::rowCount(const QModelIndex &) const\n{\n return m_items.count();\n}\n\nQVariant WindowModel::data(const QModelIndex &index, int role) const\n{\n int idx = index.row();\n if (idx < 0 || idx >= m_items.count())\n return QVariant();\n\n LipstickCompositor *c = LipstickCompositor::instance();\n if (role == Qt::UserRole + 1) {\n return m_items.at(idx);\n } else if (role == Qt::UserRole + 2) {\n QWaylandSurface *s = c->surfaceForId(m_items.at(idx));\n return s?s->processId():0;\n } else if (role == Qt::UserRole + 3) {\n LipstickCompositorWindow *w = static_cast<LipstickCompositorWindow *>(c->windowForId(m_items.at(idx)));\n return w->title();\n } else {\n return QVariant();\n }\n}\n\nQHash<int, QByteArray> WindowModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles[Qt::UserRole + 1] = \"window\";\n roles[Qt::UserRole + 2] = \"processId\";\n roles[Qt::UserRole + 3] = \"title\";\n return roles;\n}\n\nvoid WindowModel::classBegin()\n{\n}\n\nvoid WindowModel::componentComplete()\n{\n m_complete = true;\n refresh();\n}\n\n\/*!\n Reimplement this method to provide custom filtering.\n*\/\nbool WindowModel::approveWindow(LipstickCompositorWindow *window)\n{\n return window->isInProcess() == false && \n window->category() != QLatin1String(\"overlay\");\n}\n\nvoid WindowModel::addItem(int id)\n{\n if (!m_complete)\n return;\n\n LipstickCompositor *c = LipstickCompositor::instance();\n LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(c->windowForId(id));\n if (!approveWindow(window))\n return;\n\n beginInsertRows(QModelIndex(), m_items.count(), m_items.count());\n m_items.append(id);\n endInsertRows();\n emit itemAdded(m_items.count() - 1);\n emit itemCountChanged();\n}\n\nvoid WindowModel::remItem(int id)\n{\n if (!m_complete)\n return;\n\n int idx = m_items.indexOf(id);\n if (idx == -1)\n return;\n\n beginRemoveRows(QModelIndex(), idx, idx);\n m_items.removeAt(idx);\n endRemoveRows();\n emit itemCountChanged();\n}\n\nvoid WindowModel::titleChanged(int id)\n{\n if (!m_complete)\n return;\n\n int idx = m_items.indexOf(id);\n if (idx == -1)\n return;\n\n emit dataChanged(index(idx, 0), index(idx, 0));\n}\n\nvoid WindowModel::refresh()\n{\n LipstickCompositor *c = LipstickCompositor::instance();\n if (!m_complete || !c)\n return;\n\n beginResetModel();\n\n m_items.clear();\n\n for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin();\n iter != c->m_mappedSurfaces.end(); ++iter) {\n\n if (approveWindow(iter.value()))\n m_items.append(iter.key());\n }\n\n endResetModel();\n}\n\n\/\/ used by mapplauncherd to bring a binary to the front\nvoid WindowModel::launchProcess(const QString &binaryName)\n{\n LipstickCompositor *c = LipstickCompositor::instance();\n if (!m_complete || !c)\n return;\n\n QStringList binaryParts = binaryName.split(QRegExp(QRegExp(\"\\\\s+\")));\n\n for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin();\n iter != c->m_mappedSurfaces.end(); ++iter) {\n\n LipstickCompositorWindow *win = iter.value();\n if (!approveWindow(win))\n continue;\n\n QString pidFile = QString::fromLatin1(\"\/proc\/%1\/cmdline\").arg(win->processId());\n QFile f(pidFile);\n if (!f.open(QIODevice::ReadOnly)) {\n qWarning() << Q_FUNC_INFO << \"Cannot open cmdline for \" << pidFile;\n continue;\n }\n\n \/\/ Command line arguments are split by '\\0' in \/proc\/*\/cmdline\n QStringList proc;\n QByteArray data = f.readAll();\n Q_FOREACH (const QByteArray &array, data.split('\\0')) {\n QString part = QString::fromUtf8(array);\n if (part.size() > 0) {\n proc << part;\n }\n }\n\n \/\/ Cannot match, as the cmdline has less arguments than then binary part\n if (binaryParts.size() > proc.size()) {\n continue;\n }\n\n bool match = true;\n\n \/\/ All parts of binaryName must be contained in this order in the\n \/\/ process command line to match the given process\n for (int i=0; i<binaryParts.count(); i++) {\n if (proc[i] != binaryParts[i]) {\n match = false;\n break;\n }\n }\n\n if (match) {\n win->surface()->raiseRequested();\n break;\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"MCAddress.h\"\n\n#include <libetpan\/libetpan.h>\n#include <string.h>\n\nusing namespace mailcore;\n\nstatic Array * lep_address_list_from_lep_mailbox(struct mailimf_mailbox_list * mb_list, int encoded);\nstatic Array * lep_address_list_from_lep_addr(struct mailimf_address_list * addr_list, int encoded);\n\nAddress::Address()\n{\n init();\n}\n\nAddress::Address(Address * other)\n{\n init();\n setDisplayName(other->displayName());\n setMailbox(other->mailbox());\n}\n\nvoid Address::init()\n{\n mDisplayName = NULL;\n mMailbox = NULL;\n}\n\nAddress::~Address()\n{\n MC_SAFE_RELEASE(mDisplayName);\n MC_SAFE_RELEASE(mMailbox);\n}\n\nAddress * Address::addressWithDisplayName(String * displayName, String * mailbox)\n{\n Address * result = new Address();\n result->setDisplayName(displayName);\n result->setMailbox(mailbox);\n return (Address *) result->autorelease();\n}\n\nAddress * Address::addressWithMailbox(String * mailbox)\n{\n return addressWithDisplayName(NULL, mailbox);\n}\n\nAddress * Address::addressWithIMFMailbox(struct mailimf_mailbox * mailbox)\n{\n Address * address;\n\t\n address = new Address();\n\tif (mailbox->mb_display_name != NULL) {\n address->setDisplayName(String::stringByDecodingMIMEHeaderValue(mailbox->mb_display_name));\n\t}\n\tif (mailbox->mb_addr_spec != NULL) {\n\t\taddress->setMailbox(String::stringWithUTF8Characters(mailbox->mb_addr_spec));\n\t}\n if (address->mailbox() == NULL) {\n address->setMailbox(String::string());\n }\n\t\n return (Address *) address->autorelease();\n}\n\nAddress * Address::addressWithIMAPAddress(struct mailimap_address * imap_addr)\n{\n char * dsp_name;\n Address * address;\n String * mailbox;\n\n if (imap_addr->ad_personal_name == NULL)\n dsp_name = NULL;\n else {\n dsp_name = imap_addr->ad_personal_name;\n }\n\n if (imap_addr->ad_host_name == NULL) {\n const char * addr;\n\n if (imap_addr->ad_mailbox_name == NULL) {\n addr = \"\";\n }\n else {\n addr = imap_addr->ad_mailbox_name;\n }\n mailbox = String::stringWithUTF8Characters(addr);\n if (mailbox == NULL) {\n mailbox = MCSTR(\"\");\n }\n }\n else if (imap_addr->ad_mailbox_name == NULL) {\n \/\/ fix by Gabor Cselle, (http:\/\/gaborcselle.com\/), reported 8\/16\/2009\n mailbox = String::stringWithUTF8Format(\"@%s\", imap_addr->ad_host_name);\n }\n else {\n mailbox = String::stringWithUTF8Format(\"%s@%s\", imap_addr->ad_mailbox_name, imap_addr->ad_host_name);\n }\n\n address = new Address();\n if (dsp_name != NULL) {\n address->setDisplayName(String::stringByDecodingMIMEHeaderValue(dsp_name));\n }\n address->setMailbox(mailbox);\n\n return (Address *) address->autorelease();\n}\n\nAddress * Address::addressWithRFC822String(String * RFC822String)\n{\n const char * utf8String;\n size_t currentIndex;\n struct mailimf_mailbox * mb;\n int r;\n Address * result;\n \n utf8String = RFC822String->UTF8Characters();\n currentIndex = 0;\n r = mailimf_mailbox_parse(utf8String, strlen(utf8String), ¤tIndex, &mb);\n if (r != MAILIMF_NO_ERROR)\n return NULL;\n \n result = addressWithIMFMailbox(mb);\n mailimf_mailbox_free(mb);\n \n return result;\n}\n\nAddress * Address::addressWithNonEncodedIMFMailbox(struct mailimf_mailbox * mailbox)\n{\n Address * address;\n\t\n address = new Address();\n\tif (mailbox->mb_display_name != NULL) {\n address->setDisplayName(String::stringWithUTF8Characters(mailbox->mb_display_name));\n\t}\n\tif (mailbox->mb_addr_spec != NULL) {\n\t\taddress->setMailbox(String::stringWithUTF8Characters(mailbox->mb_addr_spec));\n\t}\n if (address->mailbox() == NULL) {\n address->setMailbox(String::string());\n }\n\t\n return (Address *) address->autorelease();\n}\n\nAddress * Address::addressWithNonEncodedRFC822String(String * nonEncodedRFC822String)\n{\n const char * utf8String;\n size_t currentIndex;\n struct mailimf_mailbox * mb;\n int r;\n Address * result;\n \n utf8String = nonEncodedRFC822String->UTF8Characters();\n currentIndex = 0;\n r = mailimf_mailbox_parse(utf8String, strlen(utf8String), ¤tIndex, &mb);\n if (r != MAILIMF_NO_ERROR)\n return NULL;\n \n result = addressWithNonEncodedIMFMailbox(mb);\n mailimf_mailbox_free(mb);\n \n return result;\n}\n\nArray * Address::addressesWithRFC822String(String * string)\n{\n\tconst char * utf8String;\n\tsize_t currentIndex;\n\tstruct mailimf_address_list * addr_list;\n\tArray * result;\n\tint r;\n\t\n utf8String = string->UTF8Characters();\n currentIndex = 0;\n\t\n\tr = mailimf_address_list_parse(utf8String, strlen(utf8String), ¤tIndex, &addr_list);\n if (r != MAILIMF_NO_ERROR)\n return NULL;\n\t\n\tresult = lep_address_list_from_lep_addr(addr_list, 1);\n\tmailimf_address_list_free(addr_list);\n\t\n\treturn result;\n}\n\nArray * Address::addressesWithNonEncodedRFC822String(String * string)\n{\n\tconst char * utf8String;\n\tsize_t currentIndex;\n\tstruct mailimf_address_list * addr_list;\n\tArray * result;\n\tint r;\n\t\n utf8String = string->UTF8Characters();\n currentIndex = 0;\n\t\n\tr = mailimf_address_list_parse(utf8String, strlen(utf8String), ¤tIndex, &addr_list);\n if (r != MAILIMF_NO_ERROR)\n return NULL;\n\t\n\tresult = lep_address_list_from_lep_addr(addr_list, 0);\n\tmailimf_address_list_free(addr_list);\n\t\n\treturn result;\n}\n\nString * Address::RFC822StringForAddresses(Array * addresses)\n{\n String * result = String::string();\n for(unsigned int i = 0 ; i < addresses->count() ; i ++) {\n Address * address = (Address *) addresses->objectAtIndex(i);\n if (i != 0) {\n result->appendString(MCSTR(\", \"));\n }\n result->appendString(address->RFC822String());\n }\n return result;\n}\n\nString * Address::nonEncodedRFC822StringForAddresses(Array * addresses)\n{\n String * result = String::string();\n for(unsigned int i = 0 ; i < addresses->count() ; i ++) {\n Address * address = (Address *) addresses->objectAtIndex(i);\n if (i != 0) {\n result->appendString(MCSTR(\", \"));\n }\n result->appendString(address->nonEncodedRFC822String());\n }\n return result;\n}\n\nString * Address::description()\n{\n String * result = String::string();\n result->appendString(className());\n result->appendUTF8Format(\":%p \", this);\n if (mDisplayName != NULL) {\n result->appendString(mDisplayName);\n }\n result->appendUTF8Characters(\" <\");\n if (mMailbox != NULL) {\n result->appendString(mMailbox);\n }\n result->appendUTF8Characters(\">\");\n \n return result;\n}\n\nbool Address::isEqual(Object * otherObject)\n{\n Address * otherAddress = (Address *) otherObject;\n \n if (mDisplayName == NULL) {\n if (otherAddress->displayName() != NULL) {\n return false;\n }\n }\n else if (mDisplayName != NULL) {\n if (otherAddress->displayName() == NULL) {\n return false;\n }\n else {\n if (!mDisplayName->isEqual(otherAddress->displayName()))\n return false;\n }\n }\n \n if (mMailbox == NULL) {\n if (otherAddress->mailbox() != NULL) {\n return false;\n }\n }\n else if (mMailbox != NULL) {\n if (otherAddress->mailbox() == NULL) {\n return false;\n }\n else {\n if (!mMailbox->isEqual(otherAddress->mailbox()))\n return false;\n }\n }\n \n return true;\n}\n\nunsigned int Address::hash()\n{\n unsigned int value;\n \n value = 0;\n if (mDisplayName != NULL) {\n value += mDisplayName->hash();\n }\n if (mMailbox != NULL) {\n value += mMailbox->hash();\n }\n \n return value;\n}\n\nObject * Address::copy()\n{\n return new Address(this);\n}\n\nvoid Address::setDisplayName(String * displayName)\n{\n MC_SAFE_REPLACE_COPY(String, mDisplayName, displayName);\n}\n\nString * Address::displayName()\n{\n return mDisplayName;\n}\n\nvoid Address::setMailbox(String * mailbox)\n{\n MC_SAFE_REPLACE_COPY(String, mMailbox, mailbox);\n}\n\nString * Address::mailbox()\n{\n return mMailbox;\n}\n\nstruct mailimf_address * Address::createIMFAddress()\n{\n\tstruct mailimf_mailbox * mailbox;\n\tstruct mailimf_address * result;\n\t\n mailbox = createIMFMailbox();\n\tresult = mailimf_address_new(MAILIMF_ADDRESS_MAILBOX, mailbox, NULL);\n\t\n\treturn result;\n}\n\nstruct mailimf_mailbox * Address::createIMFMailbox()\n{\n\tstruct mailimf_mailbox * result;\n\tchar * display_name;\n\tchar * addr_spec;\n\t\n\tdisplay_name = NULL;\n\tif (displayName() != NULL) {\n if (displayName()->length() > 0) {\n Data * data;\n\n data = displayName()->encodedAddressDisplayNameValue();\n if (data->bytes() != NULL) {\n display_name = strdup(data->bytes());\n }\n }\n }\n\taddr_spec = strdup(mailbox()->UTF8Characters());\n\tresult = mailimf_mailbox_new(display_name, addr_spec);\n\t\n\treturn result;\n}\n\nString * Address::RFC822String()\n{\n struct mailimf_mailbox * mb;\n MMAPString * str;\n int col;\n struct mailimf_mailbox_list * mb_list;\n clist * list;\n String * result;\n \n mb = createIMFMailbox();\n\n list = clist_new();\n clist_append(list, mb);\n mb_list = mailimf_mailbox_list_new(list);\n \n str = mmap_string_new(\"\");\n col = 0;\n mailimf_mailbox_list_write_mem(str, &col, mb_list);\n \n result = String::stringWithUTF8Characters(str->str);\n \n mailimf_mailbox_list_free(mb_list);\n mmap_string_free(str);\n \n return result;\n}\n\nString * Address::nonEncodedRFC822String()\n{\n struct mailimf_mailbox * mb;\n MMAPString * str;\n int col;\n struct mailimf_mailbox_list * mb_list;\n clist * list;\n String * result;\n\tchar * display_name;\n\tchar * addr_spec;\n\t\n\tdisplay_name = NULL;\n\tif (displayName() != NULL) {\n if (displayName()->length() > 0) {\n display_name = strdup(displayName()->UTF8Characters());\n }\n }\n if ((mailbox() == NULL) || (mailbox()->length() == 0)) {\n addr_spec = strdup(\"invalid\");\n }\n else {\n addr_spec = strdup(mailbox()->UTF8Characters());\n }\n mb = mailimf_mailbox_new(display_name, addr_spec);\n \n list = clist_new();\n clist_append(list, mb);\n mb_list = mailimf_mailbox_list_new(list);\n \n str = mmap_string_new(\"\");\n col = 0;\n mailimf_mailbox_list_write_mem(str, &col, mb_list);\n \n result = String::stringWithUTF8Characters(str->str);\n \n mailimf_mailbox_list_free(mb_list);\n mmap_string_free(str);\n \n return result;\n}\n\nstatic Array * lep_address_list_from_lep_mailbox(struct mailimf_mailbox_list * mb_list, int encoded)\n{\n\tArray * result;\n\tclistiter * cur;\n\t\n\tresult = Array::array();\n\tfor(cur = clist_begin(mb_list->mb_list) ; cur != NULL ; cur = clist_next(cur)) {\n\t\tstruct mailimf_mailbox * mb;\n\t\tAddress * address;\n\t\t\n\t\tmb = (mailimf_mailbox *) clist_content(cur);\n\t\tif (encoded) {\n\t\t\taddress = Address::addressWithIMFMailbox(mb);\n\t\t}\n\t\telse {\n\t\t\taddress = Address::addressWithNonEncodedIMFMailbox(mb);\n\t\t}\n\t\tresult->addObject(address);\n\t}\n\t\n\treturn result;\n}\n\nstatic Array * lep_address_list_from_lep_addr(struct mailimf_address_list * addr_list, int encoded)\n{\n\tArray * result;\n\tclistiter * cur;\n\t\n\tresult = Array::array();\n\t\n\tfor(cur = clist_begin(addr_list->ad_list) ; cur != NULL ;\n\t\tcur = clist_next(cur)) {\n\t\tstruct mailimf_address * addr;\n\t\t\n\t\taddr = (mailimf_address *) clist_content(cur);\n\t\tswitch (addr->ad_type) {\n\t\t\tcase MAILIMF_ADDRESS_MAILBOX:\n\t\t\t{\n\t\t\t\tAddress * address;\n\t\t\t\t\n\t\t\t\tif (encoded) {\n\t\t\t\t\taddress = Address::addressWithIMFMailbox(addr->ad_data.ad_mailbox);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddress = Address::addressWithNonEncodedIMFMailbox(addr->ad_data.ad_mailbox);\n\t\t\t\t}\n\t\t\t\tresult->addObject(address);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\t\n\t\t\tcase MAILIMF_ADDRESS_GROUP:\n\t\t\t{\n\t\t\t\tif (addr->ad_data.ad_group->grp_mb_list != NULL) {\n\t\t\t\t\tArray * subArray;\n\t\t\t\t\t\n\t\t\t\t\tsubArray = lep_address_list_from_lep_mailbox(addr->ad_data.ad_group->grp_mb_list, encoded);\n\t\t\t\t\tresult->addObjectsFromArray(subArray);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn result;\n}\n\nstatic void * createObject()\n{\n return new Address();\n}\n\nHashMap * Address::serializable()\n{\n HashMap * result = Object::serializable();\n if (mailbox() != NULL) {\n result->setObjectForKey(MCSTR(\"mailbox\"), mailbox());\n }\n if (displayName() != NULL) {\n result->setObjectForKey(MCSTR(\"displayName\"), displayName());\n }\n return result;\n}\n\nvoid Address::importSerializable(HashMap * serializable)\n{\n setMailbox((String *) serializable->objectForKey(MCSTR(\"mailbox\")));\n setDisplayName((String *) serializable->objectForKey(MCSTR(\"mailbox\")));\n}\n\n__attribute__((constructor))\nstatic void initialize()\n{\n Object::registerObjectConstructor(\"mailcore::Address\", &createObject);\n}\n\n<commit_msg>use the correct key name when reading the Address displayName from a HashMap<commit_after>#include \"MCAddress.h\"\n\n#include <libetpan\/libetpan.h>\n#include <string.h>\n\nusing namespace mailcore;\n\nstatic Array * lep_address_list_from_lep_mailbox(struct mailimf_mailbox_list * mb_list, int encoded);\nstatic Array * lep_address_list_from_lep_addr(struct mailimf_address_list * addr_list, int encoded);\n\nAddress::Address()\n{\n init();\n}\n\nAddress::Address(Address * other)\n{\n init();\n setDisplayName(other->displayName());\n setMailbox(other->mailbox());\n}\n\nvoid Address::init()\n{\n mDisplayName = NULL;\n mMailbox = NULL;\n}\n\nAddress::~Address()\n{\n MC_SAFE_RELEASE(mDisplayName);\n MC_SAFE_RELEASE(mMailbox);\n}\n\nAddress * Address::addressWithDisplayName(String * displayName, String * mailbox)\n{\n Address * result = new Address();\n result->setDisplayName(displayName);\n result->setMailbox(mailbox);\n return (Address *) result->autorelease();\n}\n\nAddress * Address::addressWithMailbox(String * mailbox)\n{\n return addressWithDisplayName(NULL, mailbox);\n}\n\nAddress * Address::addressWithIMFMailbox(struct mailimf_mailbox * mailbox)\n{\n Address * address;\n\t\n address = new Address();\n\tif (mailbox->mb_display_name != NULL) {\n address->setDisplayName(String::stringByDecodingMIMEHeaderValue(mailbox->mb_display_name));\n\t}\n\tif (mailbox->mb_addr_spec != NULL) {\n\t\taddress->setMailbox(String::stringWithUTF8Characters(mailbox->mb_addr_spec));\n\t}\n if (address->mailbox() == NULL) {\n address->setMailbox(String::string());\n }\n\t\n return (Address *) address->autorelease();\n}\n\nAddress * Address::addressWithIMAPAddress(struct mailimap_address * imap_addr)\n{\n char * dsp_name;\n Address * address;\n String * mailbox;\n\n if (imap_addr->ad_personal_name == NULL)\n dsp_name = NULL;\n else {\n dsp_name = imap_addr->ad_personal_name;\n }\n\n if (imap_addr->ad_host_name == NULL) {\n const char * addr;\n\n if (imap_addr->ad_mailbox_name == NULL) {\n addr = \"\";\n }\n else {\n addr = imap_addr->ad_mailbox_name;\n }\n mailbox = String::stringWithUTF8Characters(addr);\n if (mailbox == NULL) {\n mailbox = MCSTR(\"\");\n }\n }\n else if (imap_addr->ad_mailbox_name == NULL) {\n \/\/ fix by Gabor Cselle, (http:\/\/gaborcselle.com\/), reported 8\/16\/2009\n mailbox = String::stringWithUTF8Format(\"@%s\", imap_addr->ad_host_name);\n }\n else {\n mailbox = String::stringWithUTF8Format(\"%s@%s\", imap_addr->ad_mailbox_name, imap_addr->ad_host_name);\n }\n\n address = new Address();\n if (dsp_name != NULL) {\n address->setDisplayName(String::stringByDecodingMIMEHeaderValue(dsp_name));\n }\n address->setMailbox(mailbox);\n\n return (Address *) address->autorelease();\n}\n\nAddress * Address::addressWithRFC822String(String * RFC822String)\n{\n const char * utf8String;\n size_t currentIndex;\n struct mailimf_mailbox * mb;\n int r;\n Address * result;\n \n utf8String = RFC822String->UTF8Characters();\n currentIndex = 0;\n r = mailimf_mailbox_parse(utf8String, strlen(utf8String), ¤tIndex, &mb);\n if (r != MAILIMF_NO_ERROR)\n return NULL;\n \n result = addressWithIMFMailbox(mb);\n mailimf_mailbox_free(mb);\n \n return result;\n}\n\nAddress * Address::addressWithNonEncodedIMFMailbox(struct mailimf_mailbox * mailbox)\n{\n Address * address;\n\t\n address = new Address();\n\tif (mailbox->mb_display_name != NULL) {\n address->setDisplayName(String::stringWithUTF8Characters(mailbox->mb_display_name));\n\t}\n\tif (mailbox->mb_addr_spec != NULL) {\n\t\taddress->setMailbox(String::stringWithUTF8Characters(mailbox->mb_addr_spec));\n\t}\n if (address->mailbox() == NULL) {\n address->setMailbox(String::string());\n }\n\t\n return (Address *) address->autorelease();\n}\n\nAddress * Address::addressWithNonEncodedRFC822String(String * nonEncodedRFC822String)\n{\n const char * utf8String;\n size_t currentIndex;\n struct mailimf_mailbox * mb;\n int r;\n Address * result;\n \n utf8String = nonEncodedRFC822String->UTF8Characters();\n currentIndex = 0;\n r = mailimf_mailbox_parse(utf8String, strlen(utf8String), ¤tIndex, &mb);\n if (r != MAILIMF_NO_ERROR)\n return NULL;\n \n result = addressWithNonEncodedIMFMailbox(mb);\n mailimf_mailbox_free(mb);\n \n return result;\n}\n\nArray * Address::addressesWithRFC822String(String * string)\n{\n\tconst char * utf8String;\n\tsize_t currentIndex;\n\tstruct mailimf_address_list * addr_list;\n\tArray * result;\n\tint r;\n\t\n utf8String = string->UTF8Characters();\n currentIndex = 0;\n\t\n\tr = mailimf_address_list_parse(utf8String, strlen(utf8String), ¤tIndex, &addr_list);\n if (r != MAILIMF_NO_ERROR)\n return NULL;\n\t\n\tresult = lep_address_list_from_lep_addr(addr_list, 1);\n\tmailimf_address_list_free(addr_list);\n\t\n\treturn result;\n}\n\nArray * Address::addressesWithNonEncodedRFC822String(String * string)\n{\n\tconst char * utf8String;\n\tsize_t currentIndex;\n\tstruct mailimf_address_list * addr_list;\n\tArray * result;\n\tint r;\n\t\n utf8String = string->UTF8Characters();\n currentIndex = 0;\n\t\n\tr = mailimf_address_list_parse(utf8String, strlen(utf8String), ¤tIndex, &addr_list);\n if (r != MAILIMF_NO_ERROR)\n return NULL;\n\t\n\tresult = lep_address_list_from_lep_addr(addr_list, 0);\n\tmailimf_address_list_free(addr_list);\n\t\n\treturn result;\n}\n\nString * Address::RFC822StringForAddresses(Array * addresses)\n{\n String * result = String::string();\n for(unsigned int i = 0 ; i < addresses->count() ; i ++) {\n Address * address = (Address *) addresses->objectAtIndex(i);\n if (i != 0) {\n result->appendString(MCSTR(\", \"));\n }\n result->appendString(address->RFC822String());\n }\n return result;\n}\n\nString * Address::nonEncodedRFC822StringForAddresses(Array * addresses)\n{\n String * result = String::string();\n for(unsigned int i = 0 ; i < addresses->count() ; i ++) {\n Address * address = (Address *) addresses->objectAtIndex(i);\n if (i != 0) {\n result->appendString(MCSTR(\", \"));\n }\n result->appendString(address->nonEncodedRFC822String());\n }\n return result;\n}\n\nString * Address::description()\n{\n String * result = String::string();\n result->appendString(className());\n result->appendUTF8Format(\":%p \", this);\n if (mDisplayName != NULL) {\n result->appendString(mDisplayName);\n }\n result->appendUTF8Characters(\" <\");\n if (mMailbox != NULL) {\n result->appendString(mMailbox);\n }\n result->appendUTF8Characters(\">\");\n \n return result;\n}\n\nbool Address::isEqual(Object * otherObject)\n{\n Address * otherAddress = (Address *) otherObject;\n \n if (mDisplayName == NULL) {\n if (otherAddress->displayName() != NULL) {\n return false;\n }\n }\n else if (mDisplayName != NULL) {\n if (otherAddress->displayName() == NULL) {\n return false;\n }\n else {\n if (!mDisplayName->isEqual(otherAddress->displayName()))\n return false;\n }\n }\n \n if (mMailbox == NULL) {\n if (otherAddress->mailbox() != NULL) {\n return false;\n }\n }\n else if (mMailbox != NULL) {\n if (otherAddress->mailbox() == NULL) {\n return false;\n }\n else {\n if (!mMailbox->isEqual(otherAddress->mailbox()))\n return false;\n }\n }\n \n return true;\n}\n\nunsigned int Address::hash()\n{\n unsigned int value;\n \n value = 0;\n if (mDisplayName != NULL) {\n value += mDisplayName->hash();\n }\n if (mMailbox != NULL) {\n value += mMailbox->hash();\n }\n \n return value;\n}\n\nObject * Address::copy()\n{\n return new Address(this);\n}\n\nvoid Address::setDisplayName(String * displayName)\n{\n MC_SAFE_REPLACE_COPY(String, mDisplayName, displayName);\n}\n\nString * Address::displayName()\n{\n return mDisplayName;\n}\n\nvoid Address::setMailbox(String * mailbox)\n{\n MC_SAFE_REPLACE_COPY(String, mMailbox, mailbox);\n}\n\nString * Address::mailbox()\n{\n return mMailbox;\n}\n\nstruct mailimf_address * Address::createIMFAddress()\n{\n\tstruct mailimf_mailbox * mailbox;\n\tstruct mailimf_address * result;\n\t\n mailbox = createIMFMailbox();\n\tresult = mailimf_address_new(MAILIMF_ADDRESS_MAILBOX, mailbox, NULL);\n\t\n\treturn result;\n}\n\nstruct mailimf_mailbox * Address::createIMFMailbox()\n{\n\tstruct mailimf_mailbox * result;\n\tchar * display_name;\n\tchar * addr_spec;\n\t\n\tdisplay_name = NULL;\n\tif (displayName() != NULL) {\n if (displayName()->length() > 0) {\n Data * data;\n\n data = displayName()->encodedAddressDisplayNameValue();\n if (data->bytes() != NULL) {\n display_name = strdup(data->bytes());\n }\n }\n }\n\taddr_spec = strdup(mailbox()->UTF8Characters());\n\tresult = mailimf_mailbox_new(display_name, addr_spec);\n\t\n\treturn result;\n}\n\nString * Address::RFC822String()\n{\n struct mailimf_mailbox * mb;\n MMAPString * str;\n int col;\n struct mailimf_mailbox_list * mb_list;\n clist * list;\n String * result;\n \n mb = createIMFMailbox();\n\n list = clist_new();\n clist_append(list, mb);\n mb_list = mailimf_mailbox_list_new(list);\n \n str = mmap_string_new(\"\");\n col = 0;\n mailimf_mailbox_list_write_mem(str, &col, mb_list);\n \n result = String::stringWithUTF8Characters(str->str);\n \n mailimf_mailbox_list_free(mb_list);\n mmap_string_free(str);\n \n return result;\n}\n\nString * Address::nonEncodedRFC822String()\n{\n struct mailimf_mailbox * mb;\n MMAPString * str;\n int col;\n struct mailimf_mailbox_list * mb_list;\n clist * list;\n String * result;\n\tchar * display_name;\n\tchar * addr_spec;\n\t\n\tdisplay_name = NULL;\n\tif (displayName() != NULL) {\n if (displayName()->length() > 0) {\n display_name = strdup(displayName()->UTF8Characters());\n }\n }\n if ((mailbox() == NULL) || (mailbox()->length() == 0)) {\n addr_spec = strdup(\"invalid\");\n }\n else {\n addr_spec = strdup(mailbox()->UTF8Characters());\n }\n mb = mailimf_mailbox_new(display_name, addr_spec);\n \n list = clist_new();\n clist_append(list, mb);\n mb_list = mailimf_mailbox_list_new(list);\n \n str = mmap_string_new(\"\");\n col = 0;\n mailimf_mailbox_list_write_mem(str, &col, mb_list);\n \n result = String::stringWithUTF8Characters(str->str);\n \n mailimf_mailbox_list_free(mb_list);\n mmap_string_free(str);\n \n return result;\n}\n\nstatic Array * lep_address_list_from_lep_mailbox(struct mailimf_mailbox_list * mb_list, int encoded)\n{\n\tArray * result;\n\tclistiter * cur;\n\t\n\tresult = Array::array();\n\tfor(cur = clist_begin(mb_list->mb_list) ; cur != NULL ; cur = clist_next(cur)) {\n\t\tstruct mailimf_mailbox * mb;\n\t\tAddress * address;\n\t\t\n\t\tmb = (mailimf_mailbox *) clist_content(cur);\n\t\tif (encoded) {\n\t\t\taddress = Address::addressWithIMFMailbox(mb);\n\t\t}\n\t\telse {\n\t\t\taddress = Address::addressWithNonEncodedIMFMailbox(mb);\n\t\t}\n\t\tresult->addObject(address);\n\t}\n\t\n\treturn result;\n}\n\nstatic Array * lep_address_list_from_lep_addr(struct mailimf_address_list * addr_list, int encoded)\n{\n\tArray * result;\n\tclistiter * cur;\n\t\n\tresult = Array::array();\n\t\n\tfor(cur = clist_begin(addr_list->ad_list) ; cur != NULL ;\n\t\tcur = clist_next(cur)) {\n\t\tstruct mailimf_address * addr;\n\t\t\n\t\taddr = (mailimf_address *) clist_content(cur);\n\t\tswitch (addr->ad_type) {\n\t\t\tcase MAILIMF_ADDRESS_MAILBOX:\n\t\t\t{\n\t\t\t\tAddress * address;\n\t\t\t\t\n\t\t\t\tif (encoded) {\n\t\t\t\t\taddress = Address::addressWithIMFMailbox(addr->ad_data.ad_mailbox);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddress = Address::addressWithNonEncodedIMFMailbox(addr->ad_data.ad_mailbox);\n\t\t\t\t}\n\t\t\t\tresult->addObject(address);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\t\n\t\t\tcase MAILIMF_ADDRESS_GROUP:\n\t\t\t{\n\t\t\t\tif (addr->ad_data.ad_group->grp_mb_list != NULL) {\n\t\t\t\t\tArray * subArray;\n\t\t\t\t\t\n\t\t\t\t\tsubArray = lep_address_list_from_lep_mailbox(addr->ad_data.ad_group->grp_mb_list, encoded);\n\t\t\t\t\tresult->addObjectsFromArray(subArray);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn result;\n}\n\nstatic void * createObject()\n{\n return new Address();\n}\n\nHashMap * Address::serializable()\n{\n HashMap * result = Object::serializable();\n if (mailbox() != NULL) {\n result->setObjectForKey(MCSTR(\"mailbox\"), mailbox());\n }\n if (displayName() != NULL) {\n result->setObjectForKey(MCSTR(\"displayName\"), displayName());\n }\n return result;\n}\n\nvoid Address::importSerializable(HashMap * serializable)\n{\n setMailbox((String *) serializable->objectForKey(MCSTR(\"mailbox\")));\n setDisplayName((String *) serializable->objectForKey(MCSTR(\"displayName\")));\n}\n\n__attribute__((constructor))\nstatic void initialize()\n{\n Object::registerObjectConstructor(\"mailcore::Address\", &createObject);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* \n * Bullet OSG Framework.\n * The bullet environment module.\n *\n * Copyright (c) 2015 Jérémie Decock <jd.jdhp@gmail.com>\n *\n * www.jdhp.org\n *\/\n\n#include \"bullet_environment.h\"\n\n#include <iostream>\n\n#include <Eigen\/Dense>\n\n#include <btBulletDynamicsCommon.h>\n\nstd::map<btDynamicsWorld *, botsim::BulletEnvironment *> botsim::BulletEnvironment::tickCallbackPointerMap;\n\n\/*\n * TODO\n * Well... it sucks; because of the way it has been designed in Bullet, this\n * callback *must* be a static function...\n * This is dirty and not convenient at all...\n *\/\nvoid botsim::BulletEnvironment::tickCallback(btDynamicsWorld * world, btScalar time_step) {\n \/\/std::cout << \"The world just ticked by \" << static_cast<float>(time_step) << \" seconds\" << std::endl;\n\n std::map<btDynamicsWorld *, BulletEnvironment *>::iterator it;\n it = botsim::BulletEnvironment::tickCallbackPointerMap.find(world);\n\n if(it != botsim::BulletEnvironment::tickCallbackPointerMap.end()) {\n \/\/ Element found;\n it->second->notifyTick();\n }\n}\n\n\nbotsim::BulletEnvironment::BulletEnvironment(\n std::set<botsim::Object *> object_set,\n std::set<botsim::Part *> part_set,\n std::set<botsim::Controller *> controller_set,\n double bullet_time_step_duration_sec,\n double bullet_tick_duration_sec,\n int bullet_max_ticks_per_time_step,\n double simulation_duration_sec) :\n objectSet(object_set),\n partSet(part_set),\n controllerSet(controller_set),\n bulletTimeStepDurationSec(bullet_time_step_duration_sec),\n bulletTickDurationSec(bullet_tick_duration_sec),\n bulletMaxTicksPerTimeStep(bullet_max_ticks_per_time_step),\n simulationDurationSec(simulation_duration_sec) {\n\n \/\/ Set bullet constants\n this->gravity = -10.;\n\n \/\/ Setup bullet\n this->broadphase = new btDbvtBroadphase();\n\n this->collisionConfiguration = new btDefaultCollisionConfiguration();\n this->collisionDispatcher = new btCollisionDispatcher(this->collisionConfiguration);\n\n this->constraintSolver = new btSequentialImpulseConstraintSolver();\n\n this->dynamicsWorld = new btDiscreteDynamicsWorld(this->collisionDispatcher,\n this->broadphase,\n this->constraintSolver,\n this->collisionConfiguration);\n this->dynamicsWorld->setGravity(btVector3(0, 0, this->gravity));\n\n \/\/ This is a workaround for btDynamicsWorld::setInternalTickCallback().\n botsim::BulletEnvironment::tickCallbackPointerMap[this->dynamicsWorld] = this;\n\n \/\/ setInternalTickCallback() attachs a callback for internal ticks (substeps).\n \/\/ Only one callback can be attached (this is not an \"observer pattern\").\n \/\/ See: http:\/\/bulletphysics.org\/mediawiki-1.5.8\/index.php\/Simulation_Tick_Callbacks\n this->dynamicsWorld->setInternalTickCallback(botsim::BulletEnvironment::tickCallback);\n\n \/\/ Add rigid bodies \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \/\/ Objects\n std::set<botsim::Object *>::iterator object_it;\n std::set<botsim::Part *>::iterator part_it;\n std::set<botsim::Joint *>::iterator joint_it;\n std::set<botsim::Actuator *>::iterator actuator_it;\n\n for(object_it = this->objectSet.begin() ; object_it != this->objectSet.end() ; object_it++) {\n std::set<botsim::Part *> part_set = (*object_it)->getPartSet();\n \n \/*\n * Directly adding object's parts to this->dynamicsWorld from here is\n * probably a bad idea:\n * - there are a risk to have the same part multiple times in\n * this->ObjectSet and this->partSet;\n * - requires to update other modules like osgEnvironment (requires to\n * add another loop to get objects parts to display for instance).\n * Instead, see the alternative method below.\n *\/\n \/\/for(part_it = part_set.begin() ; part_it != part_set.end() ; part_it++) {\n \/\/ this->dynamicsWorld->addRigidBody((*part_it)->getRigidBody());\n \/\/}\n\n \/*\n * Take each part of the object and add it to this->partSet.\n * This method has multiple advantages:\n * - no risk to have the same part multiple times in this->ObjectSet\n * and this->partSet ; this->partSet is the only set of parts\n * considered by bullet, open scene graph, ...\n * - no needs to update other modules like osgEnvironment (no need to\n * add another loop to get objects parts to display for instance).\n *\/\n this->partSet.insert(part_set.begin(), part_set.end());\n\n \/*\n * Add object's joints (i.e. Bullet's constraints).\n *\/\n std::set<botsim::Joint *> joint_set = (*object_it)->getJointSet();\n for(joint_it = joint_set.begin() ; joint_it != joint_set.end() ; joint_it++) {\n this->dynamicsWorld->addConstraint((*joint_it)->getBulletTypedConstraint());\n }\n\n \/*\n * Add object's actuators (i.e. Bullet's constraints).\n *\/\n std::set<botsim::Actuator *> actuator_set = (*object_it)->getActuatorSet();\n for(actuator_it = actuator_set.begin() ; actuator_it != actuator_set.end() ; actuator_it++) {\n this->dynamicsWorld->addConstraint((*actuator_it)->getBulletTypedConstraint());\n }\n }\n\n \/\/ Parts\n for(part_it = this->partSet.begin() ; part_it != this->partSet.end() ; part_it++) {\n std::cout << \"Add \" << (*part_it)->getName() << std::endl;\n this->dynamicsWorld->addRigidBody((*part_it)->getRigidBody());\n }\n\n \/\/ Start the user clock\n this->userStartTime = std::chrono::system_clock::now();\n \n \/\/ Init the simulation clock\n this->elapsedSimulationTimeSec = 0.;\n this->elapsedSimulationTimeSecTickRes = 0.;\n}\n\nbotsim::BulletEnvironment::~BulletEnvironment() {\n botsim::BulletEnvironment::tickCallbackPointerMap.erase(this->dynamicsWorld);\n\n delete this->dynamicsWorld;\n\n delete this->constraintSolver;\n delete this->collisionConfiguration;\n delete this->collisionDispatcher;\n delete this->broadphase;\n}\n\nbtDiscreteDynamicsWorld * botsim::BulletEnvironment::getDynamicsWorld() const {\n return this->dynamicsWorld;\n}\n\n\n\/**\n *\n *\/\nvoid botsim::BulletEnvironment::run() {\n\n \/\/ Check some variables \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \/\/ assert this->getBulletTimeStepDurationSec() > 0.\n if(this->getBulletTimeStepDurationSec() <= 0.) {\n throw std::invalid_argument(\"BulletEnvironment::bulletTimeStepDurationSec received a negative value. Within \\\"healless\\\" mode, this variable must receive a positive value.\");\n }\n\n \/\/ assert this->getSimulationDurationSec() > 0.\n if(this->getSimulationDurationSec() <= 0.) {\n throw std::invalid_argument(\"BulletEnvironment::simulationDurationSec received a negative value. Within \\\"healless\\\" mode, this variable must receive a positive value.\");\n }\n \n \/\/ Main loop (simulation loop) \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n while( this->getElapsedSimulationTimeSec() < this->getSimulationDurationSec() ) {\n \/\/ Update the physics\n this->stepSimulation(this->getBulletTimeStepDurationSec());\n }\n}\n\n\n\/**\n *\n *\/\nvoid botsim::BulletEnvironment::stepSimulation(const double time_step_duration_sec) {\n this->elapsedSimulationTimeSec += time_step_duration_sec;\n\n btScalar bullet_time_step_duration_sec = btScalar(time_step_duration_sec);\n btScalar bullet_tick_duration_sec = this->bulletTickDurationSec;\n int bullet_max_ticks_per_time_step = this->bulletMaxTicksPerTimeStep;\n\n \/\/ Warn the user if timeStepDuration > maxTicksPerTimeStep * tickDuration\n \/\/ cf. http:\/\/bulletphysics.org\/mediawiki-1.5.8\/index.php\/Stepping_The_World\n if(bullet_time_step_duration_sec > (bullet_max_ticks_per_time_step * bullet_tick_duration_sec)) {\n std::cerr << \"Warning: simulation time will be lost (timeStepDuration > maxTicksPerTimeStep * tickDuration)\" << std::endl; \/\/ TODO: improve this message...\n }\n\n \/*\n * getDynamicsWorld()->stepSimulation()\n * (cf. http:\/\/bulletphysics.org\/mediawiki-1.5.8\/index.php\/Stepping_The_World)\n *\n * The first parameter is the easy one. It's simply the amount of time to\n * step the simulation by. Typically you're going to be passing it the time\n * since you last called it\n *\n * Bullet maintains an internal clock, in order to keep the actual length\n * of ticks constant. This is pivotally important for framerate\n * independence. The third parameter is the size of that internal step.\n *\n * The second parameter is the maximum number of steps that Bullet is\n * allowed to take each time you call it. If you pass a very large timeStep\n * as the first parameter [say, five times the size of the fixed internal\n * time step], then you must increase the number of maxTicksPerTimeStep to\n * compensate for this, otherwise your simulation is \"losing\" time. \n *\/\n this->getDynamicsWorld()->stepSimulation(bullet_time_step_duration_sec, bullet_max_ticks_per_time_step, bullet_tick_duration_sec);\n\n this->notifyTimeStep();\n}\n\n\n\/**\n * Realtime case.\n *\/\nvoid botsim::BulletEnvironment::stepSimulation() {\n \/\/ Define the static variable previous_user_time: the previous actual user time (i.e. outside the simulation).\n static std::chrono::time_point<std::chrono::system_clock> previous_user_time = std::chrono::system_clock::now();\n\n \/\/ Get the elapsed user time (in seconds) since the previous time step.\n std::chrono::time_point<std::chrono::system_clock> current_user_time = std::chrono::system_clock::now();\n std::chrono::duration<double> elapsed_seconds_since_previous_step = current_user_time - previous_user_time;\n double time_step_duration_sec = elapsed_seconds_since_previous_step.count();\n\n \/\/ Update previous_user_time\n previous_user_time = std::chrono::system_clock::now();\n\n \/\/ Step simulation\n this->stepSimulation(time_step_duration_sec);\n}\n\n\nvoid botsim::BulletEnvironment::resetSimulation() {\n std::cout << \"Reset simulation\" << std::endl;\n\n \/\/ TODO\n\n \/\/this->constraintSolver->reset();\n \/\/this->dynamicsWorld->clearForces();\n \/\/this->broadphase->resetPool(this->collisionDispatcher);\n \/\/\/\/m_clock.reset();\n\n \/\/btOverlappingPairCache* pair_cache = this->dynamicsWorld->getBroadphase()->getOverlappingPairCache();\n \/\/btBroadphasePairArray& pair_array = pair_cache->getOverlappingPairArray();\n \/\/for(int i = 0; i < pair_array.size(); i++) {\n \/\/ pair_cache->cleanOverlappingPair(pair_array[i], this->dynamicsWorld->getDispatcher());\n \/\/}\n \/\/ TODO: reset the initial position, angle, velocity, mass, ... of each parts.\n}\n\n\nvoid botsim::BulletEnvironment::attachTickObserver(botsim::BulletTickObserver * p_observer) {\n this->tickObserverSet.insert(p_observer);\n}\n\n\nvoid botsim::BulletEnvironment::detachTickObserver(botsim::BulletTickObserver * p_observer) {\n this->tickObserverSet.erase(p_observer);\n}\n\n\nvoid botsim::BulletEnvironment::attachTimeStepObserver(botsim::TimeStepObserver * p_observer) {\n this->timeStepObserverSet.insert(p_observer);\n}\n\n\nvoid botsim::BulletEnvironment::detachTimeStepObserver(botsim::TimeStepObserver * p_observer) {\n this->timeStepObserverSet.erase(p_observer);\n}\n\n\nvoid botsim::BulletEnvironment::notifyTick() {\n\n \/\/ Udate elapsedSimulationTimeSecTickRes\n this->elapsedSimulationTimeSecTickRes += this->bulletTickDurationSec;\n\n \/\/ Update all observers\n std::set<botsim::BulletTickObserver *>::iterator it;\n for(it = this->tickObserverSet.begin() ; it != this->tickObserverSet.end() ; it++) {\n (*it)->update(this);\n }\n\n \/\/ Update each controller\n std::set<botsim::Controller *>::iterator controller_it;\n for(controller_it = this->controllerSet.begin() ; controller_it != this->controllerSet.end() ; controller_it++) {\n (*controller_it)->updateActuators();\n }\n}\n\n\nvoid botsim::BulletEnvironment::notifyTimeStep() {\n std::set<botsim::TimeStepObserver *>::iterator it;\n for(it = this->timeStepObserverSet.begin() ; it != this->timeStepObserverSet.end() ; it++) {\n (*it)->update(this);\n }\n}\n\n\n\/**\n * return the simulation time (i.e. the time within the simulation) elapsed\n * since the beginning of the simulation.\n *\/\ndouble botsim::BulletEnvironment::getElapsedSimulationTimeSec() const {\n return this->elapsedSimulationTimeSec;\n}\n\n\n\/**\n * return the simulation time (i.e. the time within the simulation) elapsed\n * since the beginning of the simulation.\n *\/\ndouble botsim::BulletEnvironment::getElapsedSimulationTimeSecTickRes() const {\n return this->elapsedSimulationTimeSecTickRes;\n}\n\n\n\/**\n * return the actual time (i.e. the time outside the simulation) elapsed since\n * the beginning of the simulation.\n *\/\ndouble botsim::BulletEnvironment::getElapsedUserTimeSec() const {\n std::chrono::time_point<std::chrono::system_clock> current_user_time = std::chrono::system_clock::now();\n std::chrono::duration<double> elapsed_seconds = current_user_time - this->userStartTime;\n return elapsed_seconds.count();\n}\n\n\/**\n * \n *\/\ndouble botsim::BulletEnvironment::getBulletTimeStepDurationSec() const {\n return this->bulletTimeStepDurationSec;\n}\n\n\/**\n * \n *\/\ndouble botsim::BulletEnvironment::getBulletTickDurationSec() const {\n return this->bulletTickDurationSec;\n}\n\n\/**\n * \n *\/\ndouble botsim::BulletEnvironment::getBulletMaxTicksPerTimeStep() const {\n return this->bulletMaxTicksPerTimeStep;\n}\n\n\/**\n * \n *\/\ndouble botsim::BulletEnvironment::getSimulationDurationSec() const {\n return this->simulationDurationSec;\n}\n<commit_msg>Let 'BulletEnvironment' be quiet.<commit_after>\/* \n * Bullet OSG Framework.\n * The bullet environment module.\n *\n * Copyright (c) 2015 Jérémie Decock <jd.jdhp@gmail.com>\n *\n * www.jdhp.org\n *\/\n\n#include \"bullet_environment.h\"\n\n#include <iostream>\n\n#include <Eigen\/Dense>\n\n#include <btBulletDynamicsCommon.h>\n\nstd::map<btDynamicsWorld *, botsim::BulletEnvironment *> botsim::BulletEnvironment::tickCallbackPointerMap;\n\n\/*\n * TODO\n * Well... it sucks; because of the way it has been designed in Bullet, this\n * callback *must* be a static function...\n * This is dirty and not convenient at all...\n *\/\nvoid botsim::BulletEnvironment::tickCallback(btDynamicsWorld * world, btScalar time_step) {\n \/\/std::cout << \"The world just ticked by \" << static_cast<float>(time_step) << \" seconds\" << std::endl;\n\n std::map<btDynamicsWorld *, BulletEnvironment *>::iterator it;\n it = botsim::BulletEnvironment::tickCallbackPointerMap.find(world);\n\n if(it != botsim::BulletEnvironment::tickCallbackPointerMap.end()) {\n \/\/ Element found;\n it->second->notifyTick();\n }\n}\n\n\nbotsim::BulletEnvironment::BulletEnvironment(\n std::set<botsim::Object *> object_set,\n std::set<botsim::Part *> part_set,\n std::set<botsim::Controller *> controller_set,\n double bullet_time_step_duration_sec,\n double bullet_tick_duration_sec,\n int bullet_max_ticks_per_time_step,\n double simulation_duration_sec) :\n objectSet(object_set),\n partSet(part_set),\n controllerSet(controller_set),\n bulletTimeStepDurationSec(bullet_time_step_duration_sec),\n bulletTickDurationSec(bullet_tick_duration_sec),\n bulletMaxTicksPerTimeStep(bullet_max_ticks_per_time_step),\n simulationDurationSec(simulation_duration_sec) {\n\n \/\/ Set bullet constants\n this->gravity = -10.;\n\n \/\/ Setup bullet\n this->broadphase = new btDbvtBroadphase();\n\n this->collisionConfiguration = new btDefaultCollisionConfiguration();\n this->collisionDispatcher = new btCollisionDispatcher(this->collisionConfiguration);\n\n this->constraintSolver = new btSequentialImpulseConstraintSolver();\n\n this->dynamicsWorld = new btDiscreteDynamicsWorld(this->collisionDispatcher,\n this->broadphase,\n this->constraintSolver,\n this->collisionConfiguration);\n this->dynamicsWorld->setGravity(btVector3(0, 0, this->gravity));\n\n \/\/ This is a workaround for btDynamicsWorld::setInternalTickCallback().\n botsim::BulletEnvironment::tickCallbackPointerMap[this->dynamicsWorld] = this;\n\n \/\/ setInternalTickCallback() attachs a callback for internal ticks (substeps).\n \/\/ Only one callback can be attached (this is not an \"observer pattern\").\n \/\/ See: http:\/\/bulletphysics.org\/mediawiki-1.5.8\/index.php\/Simulation_Tick_Callbacks\n this->dynamicsWorld->setInternalTickCallback(botsim::BulletEnvironment::tickCallback);\n\n \/\/ Add rigid bodies \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \/\/ Objects\n std::set<botsim::Object *>::iterator object_it;\n std::set<botsim::Part *>::iterator part_it;\n std::set<botsim::Joint *>::iterator joint_it;\n std::set<botsim::Actuator *>::iterator actuator_it;\n\n for(object_it = this->objectSet.begin() ; object_it != this->objectSet.end() ; object_it++) {\n std::set<botsim::Part *> part_set = (*object_it)->getPartSet();\n \n \/*\n * Directly adding object's parts to this->dynamicsWorld from here is\n * probably a bad idea:\n * - there are a risk to have the same part multiple times in\n * this->ObjectSet and this->partSet;\n * - requires to update other modules like osgEnvironment (requires to\n * add another loop to get objects parts to display for instance).\n * Instead, see the alternative method below.\n *\/\n \/\/for(part_it = part_set.begin() ; part_it != part_set.end() ; part_it++) {\n \/\/ this->dynamicsWorld->addRigidBody((*part_it)->getRigidBody());\n \/\/}\n\n \/*\n * Take each part of the object and add it to this->partSet.\n * This method has multiple advantages:\n * - no risk to have the same part multiple times in this->ObjectSet\n * and this->partSet ; this->partSet is the only set of parts\n * considered by bullet, open scene graph, ...\n * - no needs to update other modules like osgEnvironment (no need to\n * add another loop to get objects parts to display for instance).\n *\/\n this->partSet.insert(part_set.begin(), part_set.end());\n\n \/*\n * Add object's joints (i.e. Bullet's constraints).\n *\/\n std::set<botsim::Joint *> joint_set = (*object_it)->getJointSet();\n for(joint_it = joint_set.begin() ; joint_it != joint_set.end() ; joint_it++) {\n this->dynamicsWorld->addConstraint((*joint_it)->getBulletTypedConstraint());\n }\n\n \/*\n * Add object's actuators (i.e. Bullet's constraints).\n *\/\n std::set<botsim::Actuator *> actuator_set = (*object_it)->getActuatorSet();\n for(actuator_it = actuator_set.begin() ; actuator_it != actuator_set.end() ; actuator_it++) {\n this->dynamicsWorld->addConstraint((*actuator_it)->getBulletTypedConstraint());\n }\n }\n\n \/\/ Parts\n for(part_it = this->partSet.begin() ; part_it != this->partSet.end() ; part_it++) {\n \/\/std::cout << \"Add \" << (*part_it)->getName() << std::endl;\n this->dynamicsWorld->addRigidBody((*part_it)->getRigidBody());\n }\n\n \/\/ Start the user clock\n this->userStartTime = std::chrono::system_clock::now();\n \n \/\/ Init the simulation clock\n this->elapsedSimulationTimeSec = 0.;\n this->elapsedSimulationTimeSecTickRes = 0.;\n}\n\nbotsim::BulletEnvironment::~BulletEnvironment() {\n botsim::BulletEnvironment::tickCallbackPointerMap.erase(this->dynamicsWorld);\n\n delete this->dynamicsWorld;\n\n delete this->constraintSolver;\n delete this->collisionConfiguration;\n delete this->collisionDispatcher;\n delete this->broadphase;\n}\n\nbtDiscreteDynamicsWorld * botsim::BulletEnvironment::getDynamicsWorld() const {\n return this->dynamicsWorld;\n}\n\n\n\/**\n *\n *\/\nvoid botsim::BulletEnvironment::run() {\n\n \/\/ Check some variables \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \/\/ assert this->getBulletTimeStepDurationSec() > 0.\n if(this->getBulletTimeStepDurationSec() <= 0.) {\n throw std::invalid_argument(\"BulletEnvironment::bulletTimeStepDurationSec received a negative value. Within \\\"healless\\\" mode, this variable must receive a positive value.\");\n }\n\n \/\/ assert this->getSimulationDurationSec() > 0.\n if(this->getSimulationDurationSec() <= 0.) {\n throw std::invalid_argument(\"BulletEnvironment::simulationDurationSec received a negative value. Within \\\"healless\\\" mode, this variable must receive a positive value.\");\n }\n \n \/\/ Main loop (simulation loop) \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n while( this->getElapsedSimulationTimeSec() < this->getSimulationDurationSec() ) {\n \/\/ Update the physics\n this->stepSimulation(this->getBulletTimeStepDurationSec());\n }\n}\n\n\n\/**\n *\n *\/\nvoid botsim::BulletEnvironment::stepSimulation(const double time_step_duration_sec) {\n this->elapsedSimulationTimeSec += time_step_duration_sec;\n\n btScalar bullet_time_step_duration_sec = btScalar(time_step_duration_sec);\n btScalar bullet_tick_duration_sec = this->bulletTickDurationSec;\n int bullet_max_ticks_per_time_step = this->bulletMaxTicksPerTimeStep;\n\n \/\/ Warn the user if timeStepDuration > maxTicksPerTimeStep * tickDuration\n \/\/ cf. http:\/\/bulletphysics.org\/mediawiki-1.5.8\/index.php\/Stepping_The_World\n if(bullet_time_step_duration_sec > (bullet_max_ticks_per_time_step * bullet_tick_duration_sec)) {\n std::cerr << \"Warning: simulation time will be lost (timeStepDuration > maxTicksPerTimeStep * tickDuration)\" << std::endl; \/\/ TODO: improve this message...\n }\n\n \/*\n * getDynamicsWorld()->stepSimulation()\n * (cf. http:\/\/bulletphysics.org\/mediawiki-1.5.8\/index.php\/Stepping_The_World)\n *\n * The first parameter is the easy one. It's simply the amount of time to\n * step the simulation by. Typically you're going to be passing it the time\n * since you last called it\n *\n * Bullet maintains an internal clock, in order to keep the actual length\n * of ticks constant. This is pivotally important for framerate\n * independence. The third parameter is the size of that internal step.\n *\n * The second parameter is the maximum number of steps that Bullet is\n * allowed to take each time you call it. If you pass a very large timeStep\n * as the first parameter [say, five times the size of the fixed internal\n * time step], then you must increase the number of maxTicksPerTimeStep to\n * compensate for this, otherwise your simulation is \"losing\" time. \n *\/\n this->getDynamicsWorld()->stepSimulation(bullet_time_step_duration_sec, bullet_max_ticks_per_time_step, bullet_tick_duration_sec);\n\n this->notifyTimeStep();\n}\n\n\n\/**\n * Realtime case.\n *\/\nvoid botsim::BulletEnvironment::stepSimulation() {\n \/\/ Define the static variable previous_user_time: the previous actual user time (i.e. outside the simulation).\n static std::chrono::time_point<std::chrono::system_clock> previous_user_time = std::chrono::system_clock::now();\n\n \/\/ Get the elapsed user time (in seconds) since the previous time step.\n std::chrono::time_point<std::chrono::system_clock> current_user_time = std::chrono::system_clock::now();\n std::chrono::duration<double> elapsed_seconds_since_previous_step = current_user_time - previous_user_time;\n double time_step_duration_sec = elapsed_seconds_since_previous_step.count();\n\n \/\/ Update previous_user_time\n previous_user_time = std::chrono::system_clock::now();\n\n \/\/ Step simulation\n this->stepSimulation(time_step_duration_sec);\n}\n\n\nvoid botsim::BulletEnvironment::resetSimulation() {\n std::cout << \"Reset simulation\" << std::endl;\n\n \/\/ TODO\n\n \/\/this->constraintSolver->reset();\n \/\/this->dynamicsWorld->clearForces();\n \/\/this->broadphase->resetPool(this->collisionDispatcher);\n \/\/\/\/m_clock.reset();\n\n \/\/btOverlappingPairCache* pair_cache = this->dynamicsWorld->getBroadphase()->getOverlappingPairCache();\n \/\/btBroadphasePairArray& pair_array = pair_cache->getOverlappingPairArray();\n \/\/for(int i = 0; i < pair_array.size(); i++) {\n \/\/ pair_cache->cleanOverlappingPair(pair_array[i], this->dynamicsWorld->getDispatcher());\n \/\/}\n \/\/ TODO: reset the initial position, angle, velocity, mass, ... of each parts.\n}\n\n\nvoid botsim::BulletEnvironment::attachTickObserver(botsim::BulletTickObserver * p_observer) {\n this->tickObserverSet.insert(p_observer);\n}\n\n\nvoid botsim::BulletEnvironment::detachTickObserver(botsim::BulletTickObserver * p_observer) {\n this->tickObserverSet.erase(p_observer);\n}\n\n\nvoid botsim::BulletEnvironment::attachTimeStepObserver(botsim::TimeStepObserver * p_observer) {\n this->timeStepObserverSet.insert(p_observer);\n}\n\n\nvoid botsim::BulletEnvironment::detachTimeStepObserver(botsim::TimeStepObserver * p_observer) {\n this->timeStepObserverSet.erase(p_observer);\n}\n\n\nvoid botsim::BulletEnvironment::notifyTick() {\n\n \/\/ Udate elapsedSimulationTimeSecTickRes\n this->elapsedSimulationTimeSecTickRes += this->bulletTickDurationSec;\n\n \/\/ Update all observers\n std::set<botsim::BulletTickObserver *>::iterator it;\n for(it = this->tickObserverSet.begin() ; it != this->tickObserverSet.end() ; it++) {\n (*it)->update(this);\n }\n\n \/\/ Update each controller\n std::set<botsim::Controller *>::iterator controller_it;\n for(controller_it = this->controllerSet.begin() ; controller_it != this->controllerSet.end() ; controller_it++) {\n (*controller_it)->updateActuators();\n }\n}\n\n\nvoid botsim::BulletEnvironment::notifyTimeStep() {\n std::set<botsim::TimeStepObserver *>::iterator it;\n for(it = this->timeStepObserverSet.begin() ; it != this->timeStepObserverSet.end() ; it++) {\n (*it)->update(this);\n }\n}\n\n\n\/**\n * return the simulation time (i.e. the time within the simulation) elapsed\n * since the beginning of the simulation.\n *\/\ndouble botsim::BulletEnvironment::getElapsedSimulationTimeSec() const {\n return this->elapsedSimulationTimeSec;\n}\n\n\n\/**\n * return the simulation time (i.e. the time within the simulation) elapsed\n * since the beginning of the simulation.\n *\/\ndouble botsim::BulletEnvironment::getElapsedSimulationTimeSecTickRes() const {\n return this->elapsedSimulationTimeSecTickRes;\n}\n\n\n\/**\n * return the actual time (i.e. the time outside the simulation) elapsed since\n * the beginning of the simulation.\n *\/\ndouble botsim::BulletEnvironment::getElapsedUserTimeSec() const {\n std::chrono::time_point<std::chrono::system_clock> current_user_time = std::chrono::system_clock::now();\n std::chrono::duration<double> elapsed_seconds = current_user_time - this->userStartTime;\n return elapsed_seconds.count();\n}\n\n\/**\n * \n *\/\ndouble botsim::BulletEnvironment::getBulletTimeStepDurationSec() const {\n return this->bulletTimeStepDurationSec;\n}\n\n\/**\n * \n *\/\ndouble botsim::BulletEnvironment::getBulletTickDurationSec() const {\n return this->bulletTickDurationSec;\n}\n\n\/**\n * \n *\/\ndouble botsim::BulletEnvironment::getBulletMaxTicksPerTimeStep() const {\n return this->bulletMaxTicksPerTimeStep;\n}\n\n\/**\n * \n *\/\ndouble botsim::BulletEnvironment::getSimulationDurationSec() const {\n return this->simulationDurationSec;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016, The OpenThread Authors.\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 met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file includes macros for validating runtime conditions.\n *\/\n\n#ifndef CODE_UTILS_HPP_\n#define CODE_UTILS_HPP_\n\n#include \"openthread-core-config.h\"\n\n#include \"utils\/wrap_stdbool.h\"\n\n\/**\n * This macro calculates the number of elements in an array.\n *\n * @param[in] aArray Name of the array variable.\n *\n * @returns Number of elements in the array.\n *\n *\/\n#define OT_ARRAY_LENGTH(aArray) (sizeof(aArray) \/ sizeof(aArray[0]))\n\n\/**\n * This macro returns a pointer aligned by @p aAlignment.\n *\n * @param[in] aPointer A pointer to contiguous space.\n * @param[in] aAlignment The desired alignment.\n *\n * @returns The aligned pointer.\n *\n *\/\n#define otALIGN(aPointer, aAlignment) ((void *)(((uintptr_t)(aPointer) + (aAlignment)-1U) & ~((aAlignment)-1U)))\n\n\/\/ Calculates the aligned variable size.\n#define otALIGNED_VAR_SIZE(size, align_type) (((size) + (sizeof(align_type) - 1)) \/ sizeof(align_type))\n\n\/\/ Allocate the structure using \"raw\" storage.\n#define otDEFINE_ALIGNED_VAR(name, size, align_type) \\\n align_type name[(((size) + (sizeof(align_type) - 1)) \/ sizeof(align_type))]\n\n\/**\n * This macro checks for the specified status, which is expected to commonly be successful, and branches to the local\n * label 'exit' if the status is unsuccessful.\n *\n * @param[in] aStatus A scalar status to be evaluated against zero (0).\n *\n *\/\n#define SuccessOrExit(aStatus) \\\n do \\\n { \\\n if ((aStatus) != 0) \\\n { \\\n goto exit; \\\n } \\\n } while (false)\n\n\/**\n * This macro checks for the specified condition, which is expected to commonly be true, and both executes @a ... and\n * branches to the local label 'exit' if the condition is false.\n *\n * @param[in] aCondition A Boolean expression to be evaluated.\n * @param[in] ... An expression or block to execute when the assertion fails.\n *\n *\/\n#define VerifyOrExit(aCondition, ...) \\\n do \\\n { \\\n if (!(aCondition)) \\\n { \\\n __VA_ARGS__; \\\n goto exit; \\\n } \\\n } while (false)\n\n\/**\n * This macro unconditionally executes @a ... and branches to the local label 'exit'.\n *\n * @note The use of this interface implies neither success nor failure for the overall exit status of the enclosing\n * function body.\n *\n * @param[in] ... An optional expression or block to execute when the assertion fails.\n *\n *\/\n#define ExitNow(...) \\\n do \\\n { \\\n __VA_ARGS__; \\\n goto exit; \\\n } while (false)\n\n\/*\n * This macro executes the `statement` and ignores the return value.\n *\n * This is primarily used to indicate the intention of developer that the return value of a function\/method can be\n * safely ignored.\n *\n * @param[in] aStatement The function\/method to execute.\n *\n *\/\n#define IgnoreReturnValue(aStatement) \\\n do \\\n { \\\n if (aStatement) \\\n { \\\n } \\\n } while (false)\n\n#endif \/\/ CODE_UTILS_HPP_\n<commit_msg>[code-utils] fix wrong pointer size in otALIGN (#3468)<commit_after>\/*\n * Copyright (c) 2016, The OpenThread Authors.\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 met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file includes macros for validating runtime conditions.\n *\/\n\n#ifndef CODE_UTILS_HPP_\n#define CODE_UTILS_HPP_\n\n#include \"openthread-core-config.h\"\n\n#include \"utils\/wrap_stdbool.h\"\n\n\/**\n * This macro calculates the number of elements in an array.\n *\n * @param[in] aArray Name of the array variable.\n *\n * @returns Number of elements in the array.\n *\n *\/\n#define OT_ARRAY_LENGTH(aArray) (sizeof(aArray) \/ sizeof(aArray[0]))\n\n\/**\n * This macro returns a pointer aligned by @p aAlignment.\n *\n * @param[in] aPointer A pointer to contiguous space.\n * @param[in] aAlignment The desired alignment.\n *\n * @returns The aligned pointer.\n *\n *\/\n#define otALIGN(aPointer, aAlignment) \\\n ((void *)(((uintptr_t)(aPointer) + (aAlignment)-1UL) & ~((uintptr_t)(aAlignment)-1UL)))\n\n\/\/ Calculates the aligned variable size.\n#define otALIGNED_VAR_SIZE(size, align_type) (((size) + (sizeof(align_type) - 1)) \/ sizeof(align_type))\n\n\/\/ Allocate the structure using \"raw\" storage.\n#define otDEFINE_ALIGNED_VAR(name, size, align_type) \\\n align_type name[(((size) + (sizeof(align_type) - 1)) \/ sizeof(align_type))]\n\n\/**\n * This macro checks for the specified status, which is expected to commonly be successful, and branches to the local\n * label 'exit' if the status is unsuccessful.\n *\n * @param[in] aStatus A scalar status to be evaluated against zero (0).\n *\n *\/\n#define SuccessOrExit(aStatus) \\\n do \\\n { \\\n if ((aStatus) != 0) \\\n { \\\n goto exit; \\\n } \\\n } while (false)\n\n\/**\n * This macro checks for the specified condition, which is expected to commonly be true, and both executes @a ... and\n * branches to the local label 'exit' if the condition is false.\n *\n * @param[in] aCondition A Boolean expression to be evaluated.\n * @param[in] ... An expression or block to execute when the assertion fails.\n *\n *\/\n#define VerifyOrExit(aCondition, ...) \\\n do \\\n { \\\n if (!(aCondition)) \\\n { \\\n __VA_ARGS__; \\\n goto exit; \\\n } \\\n } while (false)\n\n\/**\n * This macro unconditionally executes @a ... and branches to the local label 'exit'.\n *\n * @note The use of this interface implies neither success nor failure for the overall exit status of the enclosing\n * function body.\n *\n * @param[in] ... An optional expression or block to execute when the assertion fails.\n *\n *\/\n#define ExitNow(...) \\\n do \\\n { \\\n __VA_ARGS__; \\\n goto exit; \\\n } while (false)\n\n\/*\n * This macro executes the `statement` and ignores the return value.\n *\n * This is primarily used to indicate the intention of developer that the return value of a function\/method can be\n * safely ignored.\n *\n * @param[in] aStatement The function\/method to execute.\n *\n *\/\n#define IgnoreReturnValue(aStatement) \\\n do \\\n { \\\n if (aStatement) \\\n { \\\n } \\\n } while (false)\n\n#endif \/\/ CODE_UTILS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \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\n\/*\n * Description:\n * Disk IO performance test\n *\n * Revision history:\n * 2016-01-05, Tianyi Wang, first version\n *\/\n\n#include <cinttypes>\n#include <gtest\/gtest.h>\n#include <dsn\/service_api_cpp.h>\n#include <dsn\/cpp\/test_utils.h>\n#include <boost\/lexical_cast.hpp>\n\nvoid aio_testcase(uint64_t block_size, size_t concurrency, bool is_write, bool shared)\n{\n std::unique_ptr<char[]> buffer(new char[block_size]);\n std::vector<dsn_handle_t> files;\n files.resize(concurrency);\n\n int flag;\n if (is_write)\n {\n flag = O_CREAT | O_RDWR;\n if (shared)\n {\n if (utils::filesystem::file_exists(\"temp\"))\n utils::filesystem::remove_path(\"temp\");\n }\n else\n {\n for (int i = 0; i < concurrency; i++)\n {\n std::stringstream ss;\n ss << \"temp.\" << i;\n auto file = ss.str();\n if (utils::filesystem::file_exists(file))\n utils::filesystem::remove_path(file);\n }\n }\n }\n else\n {\n flag = O_RDWR;\n }\n\n if (shared)\n {\n auto file_handle = dsn_file_open(\"temp\", flag, 0666);\n EXPECT_TRUE(file_handle != nullptr);\n for (int i = 0; i < concurrency; i++)\n files[i] = file_handle;\n }\n else\n {\n for (int i = 0; i < concurrency; i++)\n {\n std::stringstream ss;\n ss << \"temp.\" << i;\n auto file = ss.str();\n auto file_handle = dsn_file_open(file.c_str(), flag, 0666);\n EXPECT_TRUE(file_handle != nullptr);\n files[i] = file_handle;\n }\n }\n \n std::atomic<uint64_t> io_count(0);\n std::atomic<uint64_t> cb_flying_count(0);\n volatile bool exit = false;\n std::function<void(int)> cb;\n std::vector<uint64_t> offsets;\n offsets.resize(concurrency);\n \n cb = [&](int index)\n {\n if (!exit)\n {\n auto ioc = io_count++;\n uint64_t offset;\n if (!shared)\n {\n offset = offsets[index];\n offsets[index] += block_size;\n }\n else\n {\n offset = ioc * block_size;\n }\n\n cb_flying_count++;\n if (is_write)\n {\n file::write(files[index], buffer.get(), (int)block_size, offset,\n LPC_AIO_TEST, nullptr, [&](::dsn::error_code code, size_t sz) \n { \n if (ERR_OK == code)\n cb(index);\n cb_flying_count--;\n }); \n }\n else\n {\n file::read(files[index], buffer.get(), (int)block_size, offset,\n LPC_AIO_TEST, nullptr, [&](::dsn::error_code code, size_t sz)\n { \n if (ERR_OK == code)\n cb(index);\n cb_flying_count--;\n });\n }\n }\n };\n\n \/\/ start\n auto tic = std::chrono::steady_clock::now();\n for (int i = 0; i < concurrency; i++)\n {\n offsets[i] = 0;\n cb(i);\n }\n\n \/\/ run for seconds\n std::this_thread::sleep_for(std::chrono::seconds(10));\n auto ioc = io_count.load();\n auto bytes = ioc * block_size; \n auto toc = std::chrono::steady_clock::now();\n \n std::cout << \"is_write = \" << is_write \n << \", block_size = \" << block_size\n << \", shared = \" << shared\n << \", concurrency = \" << concurrency\n << \", iops = \" << (double)ioc \/ (double)std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() * 1000000.0 << \" #\/s\"\n << \", throughput = \" << (double)bytes \/ std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() << \" mB\/s\"\n << \", avg_latency = \" << (double)std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() \/ (double)(ioc \/ concurrency) << \" us\"\n << std::endl;\n\n \/\/ safe exit\n exit = true;\n\n while (cb_flying_count.load() > 0)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n }\n\n if (shared)\n {\n dsn_file_flush(files[0]);\n auto cok = dsn_file_close(files[0]);\n EXPECT_EQ(cok, ERR_OK);\n }\n else\n {\n for (auto& f : files)\n {\n dsn_file_flush(f);\n auto cok = dsn_file_close(f);\n EXPECT_EQ(cok, ERR_OK);\n }\n }\n}\n\nTEST(perf_core, aio)\n{\n for (auto is_write : { true, false })\n for (auto shared : { false, true })\n for (auto blk_size_bytes : { 256, 1024, 4 * 1024 })\n for (auto concurrency : { 1, 2, 4})\n aio_testcase(blk_size_bytes, concurrency, is_write, shared);\n}\n<commit_msg>fix aio perf test as the index value is referenced and changed to invalid value<commit_after>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \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\n\/*\n * Description:\n * Disk IO performance test\n *\n * Revision history:\n * 2016-01-05, Tianyi Wang, first version\n *\/\n\n#include <cinttypes>\n#include <gtest\/gtest.h>\n#include <dsn\/service_api_cpp.h>\n#include <dsn\/cpp\/test_utils.h>\n#include <boost\/lexical_cast.hpp>\n\nvoid aio_testcase(uint64_t block_size, size_t concurrency, bool is_write, bool shared)\n{\n std::unique_ptr<char[]> buffer(new char[block_size]);\n std::vector<dsn_handle_t> files;\n files.resize(concurrency);\n\n int flag;\n if (is_write)\n {\n flag = O_CREAT | O_RDWR;\n if (shared)\n {\n if (utils::filesystem::file_exists(\"temp\"))\n utils::filesystem::remove_path(\"temp\");\n }\n else\n {\n for (int i = 0; i < concurrency; i++)\n {\n std::stringstream ss;\n ss << \"temp.\" << i;\n auto file = ss.str();\n if (utils::filesystem::file_exists(file))\n utils::filesystem::remove_path(file);\n }\n }\n }\n else\n {\n flag = O_RDWR;\n }\n\n if (shared)\n {\n auto file_handle = dsn_file_open(\"temp\", flag, 0666);\n EXPECT_TRUE(file_handle != nullptr);\n for (int i = 0; i < concurrency; i++)\n files[i] = file_handle;\n }\n else\n {\n for (int i = 0; i < concurrency; i++)\n {\n std::stringstream ss;\n ss << \"temp.\" << i;\n auto file = ss.str();\n auto file_handle = dsn_file_open(file.c_str(), flag, 0666);\n EXPECT_TRUE(file_handle != nullptr);\n files[i] = file_handle;\n }\n }\n \n std::atomic<uint64_t> io_count(0);\n std::atomic<uint64_t> cb_flying_count(0);\n volatile bool exit = false;\n std::function<void(int)> cb;\n std::vector<uint64_t> offsets;\n offsets.resize(concurrency);\n \n cb = [&](int index)\n {\n if (!exit)\n {\n auto ioc = io_count++;\n uint64_t offset;\n if (!shared)\n {\n offset = offsets[index];\n offsets[index] += block_size;\n }\n else\n {\n offset = ioc * block_size;\n }\n\n cb_flying_count++;\n if (is_write)\n {\n file::write(files[index], buffer.get(), (int)block_size, offset,\n LPC_AIO_TEST, nullptr, [idx = index, &cb, &cb_flying_count](::dsn::error_code code, size_t sz) \n { \n if (ERR_OK == code)\n cb(idx);\n cb_flying_count--;\n }); \n }\n else\n {\n file::read(files[index], buffer.get(), (int)block_size, offset,\n LPC_AIO_TEST, nullptr, [idx = index, &cb, &cb_flying_count](::dsn::error_code code, size_t sz)\n { \n if (ERR_OK == code)\n cb(idx);\n cb_flying_count--;\n });\n }\n }\n };\n\n \/\/ start\n auto tic = std::chrono::steady_clock::now();\n for (int i = 0; i < concurrency; i++)\n {\n offsets[i] = 0;\n cb(i);\n }\n\n \/\/ run for seconds\n std::this_thread::sleep_for(std::chrono::seconds(10));\n auto ioc = io_count.load();\n auto bytes = ioc * block_size; \n auto toc = std::chrono::steady_clock::now();\n \n std::cout << \"is_write = \" << is_write \n << \", block_size = \" << block_size\n << \", shared = \" << shared\n << \", concurrency = \" << concurrency\n << \", iops = \" << (double)ioc \/ (double)std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() * 1000000.0 << \" #\/s\"\n << \", throughput = \" << (double)bytes \/ std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() << \" mB\/s\"\n << \", avg_latency = \" << (double)std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() \/ (double)(ioc \/ concurrency) << \" us\"\n << std::endl;\n\n \/\/ safe exit\n exit = true;\n\n while (cb_flying_count.load() > 0)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n }\n\n if (shared)\n {\n dsn_file_flush(files[0]);\n auto cok = dsn_file_close(files[0]);\n EXPECT_EQ(cok, ERR_OK);\n }\n else\n {\n for (auto& f : files)\n {\n dsn_file_flush(f);\n auto cok = dsn_file_close(f);\n EXPECT_EQ(cok, ERR_OK);\n }\n }\n}\n\nTEST(perf_core, aio)\n{\n for (auto is_write : { true, false })\n for (auto shared : { false, true })\n for (auto blk_size_bytes : { 256, 1024, 4 * 1024 })\n for (auto concurrency : { 1, 2, 4})\n aio_testcase(blk_size_bytes, concurrency, is_write, shared);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 Team Kamikakushi\n *\n * This software is provided 'as-is', without any express or implied\n * warranty. In no event will the authors be held liable for any damages\n * arising from the use of this software.\n *\n * Permission is granted to anyone to use this software for any purpose,\n * including commercial applications, and to alter it and redistribute it\n * freely, subject to the following restrictions:\n *\n * 1. The origin of this software must not be misrepresented; you must not\n * claim that you wrote the original software.\n * 2. Altered source versions must be plainly marked as such, and must not be\n * misrepresented as being the original software.\n * 3. This notice may not be removed or altered from any source distribution.\n **\/\n\n#include \"net4.h\"\n\n\/\/ To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS\n\/\/ and compile with -DPSAPI_VERSION=1\n\nbool loaded()\n{\n\treturn true;\n}\n\nconst char *version()\n{\n\treturn \"0.0.8\";\n}\n\nbool isProcessRunning( const char* processName )\n{\n\tHANDLE SnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );\n\n\tif( SnapShot == INVALID_HANDLE_VALUE )\n\t\treturn false;\n\n\tPROCESSENTRY32 procEntry;\n\tprocEntry.dwSize = sizeof( PROCESSENTRY32 );\n\n\tif( !Process32First( SnapShot, &procEntry ) )\n\t\treturn false;\n\n\tdo\n\t{\n\t\tif( strcmp( procEntry.szExeFile, processName ) == 0 )\n\t\t\treturn true;\n\t}\n\twhile( Process32Next( SnapShot, &procEntry ) );\n\n\treturn false;\n}\n\nbool isValidHandle(HANDLE handle)\n{\n\tif (handle != NULL && handle != INVALID_HANDLE_VALUE)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool isValidProcessID(DWORD ProcessID)\n{\n\tif (ProcessID != 0)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid WinAPI_MessageBox(const char *title, const char *message)\n{\n\tMessageBox(0,message,title,0);\n}\n\nDWORD WinAPI_GetProcessID(const char *processName)\n{\n\tPROCESSENTRY32 entryPoint32;\n\tHANDLE snapshotHandle;\n\tentryPoint32.dwSize = sizeof(PROCESSENTRY32);\n\tsnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n\tif (Process32First(snapshotHandle, &entryPoint32))\n\t{\n\t\tdo\n\t\t{\n\t\t\tif(strcmp(entryPoint32.szExeFile, processName) == 0)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\twhile(Process32Next(snapshotHandle, &entryPoint32));\n\t}\n\tif (isValidHandle(snapshotHandle))\n\t{\n\t\tCloseHandle(snapshotHandle);\n\t\treturn entryPoint32.th32ProcessID;\n\t}\n\treturn 0;\n}\n\nvoid *GetModuleBaseAddress(const char *processName, DWORD ProcessID) \n{ \n DWORD_PTR dwModuleBaseAddress = 0; \n HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, ProcessID); \n if (hSnapshot != INVALID_HANDLE_VALUE) \n { \n MODULEENTRY32 ModuleEntry32; \n ModuleEntry32.dwSize = sizeof(MODULEENTRY32); \n if (Module32First(hSnapshot, &ModuleEntry32)) \n { \n do \n { \n if (_tcsicmp(ModuleEntry32.szModule, processName) == 0) \n { \n dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr; \n break; \n } \n } \n while (Module32Next(hSnapshot, &ModuleEntry32)); \n } \n CloseHandle(hSnapshot); \n } \n return (void *)dwModuleBaseAddress;\n}\n\nvoid *GetHWND(const char *windowName)\n{\n\treturn (void *)FindWindow(NULL, windowName);\n}\n\nHANDLE WinAPI_OpenHandle(DWORD ProcessID)\n{\n\tHANDLE handle;\n\tif (isValidProcessID(ProcessID))\n\t{\n\t\thandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, ProcessID);\n\t\tif (isValidHandle(handle))\n\t\t{\n\t\t\treturn handle;\n\t\t}\n\t}\n\treturn NULL;\n}\n\nbool WinAPI_CloseHandle(HANDLE handle)\n{\n\tif (isValidHandle(handle))\n\t{\n\t\tCloseHandle(handle);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool SuspendProcess(DWORD ProcessID)\n{\n\tif (isValidProcessID(ProcessID))\n\t{\t\n\t\tif (DebugActiveProcess(ProcessID) != 0)\n\t\t{\n\t\t\tDebugSetProcessKillOnExit(false);\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool ResumeProcess(DWORD ProcessID)\n{\n\tif (ProcessID != 0)\n\t{\n\t\tbool debugPresent = false;\n\t\tHANDLE handle = WinAPI_OpenHandle(ProcessID);\n\t\tif (isValidHandle(handle))\n\t\t{\n\t\t\tif (CheckRemoteDebuggerPresent(handle, (PBOOL)&debugPresent) != 0 && debugPresent)\n\t\t\t{\n\t\t\t\tDebugActiveProcessStop(ProcessID);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\n\/\/ Memory Functions\n\nint ReadInt(HANDLE handle, DWORD address)\n{\n\tint value;\n\tReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);\n\tif (value == NULL)\n\t{\n\t\treturn 0;\n\t}\n\treturn value;\n}\n\nbool WriteInt(HANDLE handle, DWORD address, int value)\n{\n\tSIZE_T bytesWritten;\n\tWriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);\n\tif (bytesWritten == sizeof(value))\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ReadBool(HANDLE handle, DWORD address)\n{\n\tbool value;\n\tReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);\n\tif (value == NULL)\n\t{\n\t\treturn false;\n\t}\n\treturn value;\n}\n\nbool WriteBool(HANDLE handle, DWORD address, bool value)\n{\n\tSIZE_T bytesWritten;\n\tWriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);\n\tif (bytesWritten == sizeof(value))\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfloat ReadFloat(HANDLE handle, DWORD address)\n{\n\tfloat value;\n\tReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);\n\tif (value == NULL)\n\t{\n\t\treturn 0;\n\t}\n\treturn value;\n}\n\nbool WriteFloat(HANDLE handle, DWORD address, float value)\n{\n\tSIZE_T bytesWritten;\n\tWriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);\n\tif (bytesWritten == sizeof(value))\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid *SignatureScan(HANDLE handle, const char *signature, const char *mask, int offset)\n{\n\tint maskLength = (int)strlen(mask);\n\t\n\tstd::vector<unsigned char> dump;\n\t\n\tstd::string sigstring(signature);\n\tstd::istringstream sigstream(sigstring);\n\tstd::vector<unsigned char> sig;\n\tunsigned int c;\n\twhile (sigstream >> std::hex >> c)\n\t{\n\t\tsig.push_back(c);\n\t}\n\n\tbool canFind = true;\n\t\n\tMEMORY_BASIC_INFORMATION info;\n\t\n\tfor (long currentAddress = 0; VirtualQueryEx(handle, (void *)(UINT_PTR)currentAddress, &info, sizeof(info)) == sizeof(info); currentAddress += (long)info.RegionSize) \/\/ iterate through all regions\n\t{\n\t\tif (info.State == MEM_COMMIT && (info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))\n\t\t{\n\t\t\tSIZE_T bytesRead;\n\t\t\tdump.resize(info.RegionSize);\n\t\t\tReadProcessMemory(handle, (void *)(UINT_PTR)currentAddress, &dump[0], info.RegionSize, &bytesRead);\n\t\t\tdump.resize(bytesRead);\n\t\t\t\n\t\t\tif (bytesRead > 0) \/\/ memory is dumped\n\t\t\t{\n\t\t\t\tlong currentOffset = 0;\n\t\t\t\twhile (currentOffset < bytesRead-maskLength) \/\/ iterate through dumped region\n\t\t\t\t{\n\t\t\t\t\tcanFind = true;\n\t\t\t\t\tfor (int x = 0; x < maskLength-1; x++) \/\/ iterate through signature \/ mask at particular offset in dumped region\n\t\t\t\t\t{\n\t\t\t\t\t\tif (mask[x] == 'x' && dump[currentOffset+x] != sig[x])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcanFind = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (canFind) \/\/ found signature\n\t\t\t\t\t{\n\t\t\t\t\t\treturn (void *)(UINT_PTR)(currentAddress + currentOffset + offset - 1);\n\t\t\t\t\t}\n\t\t\t\t\tcurrentOffset++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn NULL;\n}\n<commit_msg>changed to MIT license<commit_after>\/**\nMIT License\n\nCopyright (c) 2017 Tsuneko Shirley Kogami\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n **\/\n\n#include \"net4.h\"\n\n\/\/ To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS\n\/\/ and compile with -DPSAPI_VERSION=1\n\nbool loaded()\n{\n\treturn true;\n}\n\nconst char *version()\n{\n\treturn \"0.0.8\";\n}\n\nbool isProcessRunning( const char* processName )\n{\n\tHANDLE SnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );\n\n\tif( SnapShot == INVALID_HANDLE_VALUE )\n\t\treturn false;\n\n\tPROCESSENTRY32 procEntry;\n\tprocEntry.dwSize = sizeof( PROCESSENTRY32 );\n\n\tif( !Process32First( SnapShot, &procEntry ) )\n\t\treturn false;\n\n\tdo\n\t{\n\t\tif( strcmp( procEntry.szExeFile, processName ) == 0 )\n\t\t\treturn true;\n\t}\n\twhile( Process32Next( SnapShot, &procEntry ) );\n\n\treturn false;\n}\n\nbool isValidHandle(HANDLE handle)\n{\n\tif (handle != NULL && handle != INVALID_HANDLE_VALUE)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool isValidProcessID(DWORD ProcessID)\n{\n\tif (ProcessID != 0)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid WinAPI_MessageBox(const char *title, const char *message)\n{\n\tMessageBox(0,message,title,0);\n}\n\nDWORD WinAPI_GetProcessID(const char *processName)\n{\n\tPROCESSENTRY32 entryPoint32;\n\tHANDLE snapshotHandle;\n\tentryPoint32.dwSize = sizeof(PROCESSENTRY32);\n\tsnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n\tif (Process32First(snapshotHandle, &entryPoint32))\n\t{\n\t\tdo\n\t\t{\n\t\t\tif(strcmp(entryPoint32.szExeFile, processName) == 0)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\twhile(Process32Next(snapshotHandle, &entryPoint32));\n\t}\n\tif (isValidHandle(snapshotHandle))\n\t{\n\t\tCloseHandle(snapshotHandle);\n\t\treturn entryPoint32.th32ProcessID;\n\t}\n\treturn 0;\n}\n\nvoid *GetModuleBaseAddress(const char *processName, DWORD ProcessID) \n{ \n DWORD_PTR dwModuleBaseAddress = 0; \n HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, ProcessID); \n if (hSnapshot != INVALID_HANDLE_VALUE) \n { \n MODULEENTRY32 ModuleEntry32; \n ModuleEntry32.dwSize = sizeof(MODULEENTRY32); \n if (Module32First(hSnapshot, &ModuleEntry32)) \n { \n do \n { \n if (_tcsicmp(ModuleEntry32.szModule, processName) == 0) \n { \n dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr; \n break; \n } \n } \n while (Module32Next(hSnapshot, &ModuleEntry32)); \n } \n CloseHandle(hSnapshot); \n } \n return (void *)dwModuleBaseAddress;\n}\n\nvoid *GetHWND(const char *windowName)\n{\n\treturn (void *)FindWindow(NULL, windowName);\n}\n\nHANDLE WinAPI_OpenHandle(DWORD ProcessID)\n{\n\tHANDLE handle;\n\tif (isValidProcessID(ProcessID))\n\t{\n\t\thandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, ProcessID);\n\t\tif (isValidHandle(handle))\n\t\t{\n\t\t\treturn handle;\n\t\t}\n\t}\n\treturn NULL;\n}\n\nbool WinAPI_CloseHandle(HANDLE handle)\n{\n\tif (isValidHandle(handle))\n\t{\n\t\tCloseHandle(handle);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool SuspendProcess(DWORD ProcessID)\n{\n\tif (isValidProcessID(ProcessID))\n\t{\t\n\t\tif (DebugActiveProcess(ProcessID) != 0)\n\t\t{\n\t\t\tDebugSetProcessKillOnExit(false);\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool ResumeProcess(DWORD ProcessID)\n{\n\tif (ProcessID != 0)\n\t{\n\t\tbool debugPresent = false;\n\t\tHANDLE handle = WinAPI_OpenHandle(ProcessID);\n\t\tif (isValidHandle(handle))\n\t\t{\n\t\t\tif (CheckRemoteDebuggerPresent(handle, (PBOOL)&debugPresent) != 0 && debugPresent)\n\t\t\t{\n\t\t\t\tDebugActiveProcessStop(ProcessID);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\n\/\/ Memory Functions\n\nint ReadInt(HANDLE handle, DWORD address)\n{\n\tint value;\n\tReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);\n\tif (value == NULL)\n\t{\n\t\treturn 0;\n\t}\n\treturn value;\n}\n\nbool WriteInt(HANDLE handle, DWORD address, int value)\n{\n\tSIZE_T bytesWritten;\n\tWriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);\n\tif (bytesWritten == sizeof(value))\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ReadBool(HANDLE handle, DWORD address)\n{\n\tbool value;\n\tReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);\n\tif (value == NULL)\n\t{\n\t\treturn false;\n\t}\n\treturn value;\n}\n\nbool WriteBool(HANDLE handle, DWORD address, bool value)\n{\n\tSIZE_T bytesWritten;\n\tWriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);\n\tif (bytesWritten == sizeof(value))\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfloat ReadFloat(HANDLE handle, DWORD address)\n{\n\tfloat value;\n\tReadProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), NULL);\n\tif (value == NULL)\n\t{\n\t\treturn 0;\n\t}\n\treturn value;\n}\n\nbool WriteFloat(HANDLE handle, DWORD address, float value)\n{\n\tSIZE_T bytesWritten;\n\tWriteProcessMemory(handle, (void *)(UINT_PTR)address, &value, sizeof(value), &bytesWritten);\n\tif (bytesWritten == sizeof(value))\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid *SignatureScan(HANDLE handle, const char *signature, const char *mask, int offset)\n{\n\tint maskLength = (int)strlen(mask);\n\t\n\tstd::vector<unsigned char> dump;\n\t\n\tstd::string sigstring(signature);\n\tstd::istringstream sigstream(sigstring);\n\tstd::vector<unsigned char> sig;\n\tunsigned int c;\n\twhile (sigstream >> std::hex >> c)\n\t{\n\t\tsig.push_back(c);\n\t}\n\n\tbool canFind = true;\n\t\n\tMEMORY_BASIC_INFORMATION info;\n\t\n\tfor (long currentAddress = 0; VirtualQueryEx(handle, (void *)(UINT_PTR)currentAddress, &info, sizeof(info)) == sizeof(info); currentAddress += (long)info.RegionSize) \/\/ iterate through all regions\n\t{\n\t\tif (info.State == MEM_COMMIT && (info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))\n\t\t{\n\t\t\tSIZE_T bytesRead;\n\t\t\tdump.resize(info.RegionSize);\n\t\t\tReadProcessMemory(handle, (void *)(UINT_PTR)currentAddress, &dump[0], info.RegionSize, &bytesRead);\n\t\t\tdump.resize(bytesRead);\n\t\t\t\n\t\t\tif (bytesRead > 0) \/\/ memory is dumped\n\t\t\t{\n\t\t\t\tlong currentOffset = 0;\n\t\t\t\twhile (currentOffset < bytesRead-maskLength) \/\/ iterate through dumped region\n\t\t\t\t{\n\t\t\t\t\tcanFind = true;\n\t\t\t\t\tfor (int x = 0; x < maskLength-1; x++) \/\/ iterate through signature \/ mask at particular offset in dumped region\n\t\t\t\t\t{\n\t\t\t\t\t\tif (mask[x] == 'x' && dump[currentOffset+x] != sig[x])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcanFind = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (canFind) \/\/ found signature\n\t\t\t\t\t{\n\t\t\t\t\t\treturn (void *)(UINT_PTR)(currentAddress + currentOffset + offset - 1);\n\t\t\t\t\t}\n\t\t\t\t\tcurrentOffset++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _NODE_H\r\n#define _NODE_H\r\n\r\n#include <vector>\r\n\r\nclass Node{\r\n\r\n private:\r\n\r\n union Content{\r\n double idX; \/\/var\r\n double value; \/\/const\r\n int function; \/\/func1 ou func2\r\n };\r\n \r\n \/\/não sei se enum e union deveriam ser globais ou declaradas dentro\r\n \/\/do node. A principio, acho que não é de interesse de nenhuma outra\r\n \/\/função acessar estas informação, mas pode ser que eu esteja enganado.\r\n\r\n Content C;\r\n int tipo; \/\/recebe o índice do content\r\n\r\n Node *left;\r\n Node *right;\r\n\r\n public:\r\n Node(bool copy = false);\r\n ~Node();\r\n\r\n double eval(std::vector<double> x);\r\n void print_node_d();\r\n Node *get_copy();\r\n};\r\n\r\n#endif\r\n<commit_msg>1.2.4 Fix<commit_after>\/\/node.hpp\r\n#ifndef _NODE_H\r\n#define _NODE_H\r\n\r\n\r\n#include <vector>\r\n\r\n\r\nclass Node{\r\n\r\n private:\r\n union Content{\r\n double idX; \/\/var\r\n double value; \/\/const\r\n int function; \/\/func1 ou func2\r\n };\r\n\r\n Content C;\r\n int tipo; \/\/recebe o índice do content\r\n\r\n Node *left;\r\n Node *right;\r\n\r\n public:\r\n Node(bool copy = false);\r\n ~Node();\r\n\r\n double eval(double x);\r\n void print_node_d();\r\n Node *get_copy();\r\n int get_type();\r\n};\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>#ifndef _PIPE_H_\n#define _PIPE_H_\n\n#include \"cmdline.hpp\"\n\n\nclass Pipe\n{\npublic:\n\tPipe();\n\tvirtual bool execute(vector<string> cmd, string &input) = 0;\n\t\/\/virtual bool isValid() = 0;\n\n};\n\n#endif\n<commit_msg>fixed pipe prototype<commit_after>#ifndef _PIPE_H_\n#define _PIPE_H_\n\n#include \"cmdline.hpp\"\n\n\nclass Pipe\n{\npublic:\n\tPipe();\n\tbool execute(vector<string> cmd, string &input);\n\t\/\/virtual bool isValid() = 0;\n\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2009 by Miguel Chavez Gamboa *\n * miguel@lemonpos.org *\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; 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. 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, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"mibitnotifier.h\"\n\n#include <QPixmap>\n#include <QIcon>\n#include <QString>\n#include <QLabel>\n#include <QHBoxLayout>\n#include <QVBoxLayout>\n#include <QTimeLine>\n#include <QTimer>\n#include <QKeyEvent>\n#include <QDebug>\n\nMibitNotifier::MibitNotifier(QWidget *parent, const QString &file, const QPixmap &icon, const QPixmap &closeIcon, const bool &onTop)\n : QSvgWidget( parent )\n{\n if (file != 0) setSVG(file);\n\n m_parent = parent;\n m_onTop = onTop;\n closedByUser = false;\n m_fileName = file;\n setMinimumHeight(100);\n setFixedSize(0,0); \/\/until show we grow it\n setMaxHeight(max_H); \/\/default sizes\n setMaxWidth(max_W);\n animRate = 500; \/\/default animation speed (half second rate).\n\n img = new QLabel();\n hLayout = new QHBoxLayout();\n message = new QLabel(\"\");\n btnClose = new QLabel(\"\"); \/\/only an image\n\n\n img->setPixmap(icon);\n img->setMaximumHeight(54); \/\/the icon size is hardcoded now.\n img->setMaximumWidth(54);\n img->setAlignment(Qt::AlignLeft);\n img->setMargin(4);\n\n btnClose->setPixmap(closeIcon);\n btnClose->setMaximumHeight(34); \/\/the icon size is hardcoded now.\n btnClose->setMaximumWidth(38);\n btnClose->setToolTip(\"Close Notification\"); \/\/what about translations?\n btnClose->setFixedSize(38,36);\n\n setLayout(hLayout);\n message->setWordWrap(true);\n message->setAlignment(Qt::AlignJustify|Qt::AlignVCenter);\n message->setMargin(10);\n\n hLayout->addWidget(img,0,Qt::AlignLeft);\n hLayout->addWidget(message,1,Qt::AlignLeft);\n hLayout->addWidget(btnClose,0,Qt::AlignRight);\n\n timeLine = new QTimeLine(animRate, this);\n connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int)));\n connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished()));\n}\n\nvoid MibitNotifier::showNotification( const QString &msg, const int &timeToLive) \/\/timeToLive = 0 : not auto hide it.\n{\n \/\/set default msg if the sent is empty.\n if (msg.isEmpty()) setMessage(message->text()); else setMessage( msg );\n\n if (!m_onTop) setSVG(\"rotated_\"+m_fileName); else setSVG(m_fileName);\n\n setGeometry(-1000,-1000,0,0);\n show();\n \/\/update steps for animation, now that the window is showing.\n\n int maxStep; int minStep = 0;\n\n if ( m_onTop ) {\n maxStep = maxHeight;\n minStep = 0;\n } else {\n maxStep = m_parent->geometry().height()-maxHeight;\n minStep = m_parent->geometry().height();\n }\n\n timeLine->setFrameRange(minStep,maxStep);\n \/\/make it grow\n timeLine->setDirection(QTimeLine::Forward);\n timeLine->start();\n btnClose->setFocus();\n\n if (timeToLive > 0 ) QTimer::singleShot(timeToLive,this,SLOT(hideDialog()));\n}\n\nvoid MibitNotifier::animate(const int &step)\n{\n \/\/get some sizes...\n QRect windowGeom = m_parent->geometry();\n int midPointX = (windowGeom.width()\/2);\n int newX; int newW;\n QRect dRect;\n int pheight = m_parent->geometry().height();\n if (maxWidth < min_W ) newW = min_W; else newW = maxWidth;\n if ((midPointX-(newW\/2)) < 0) newX = 0; else newX = midPointX - (newW\/2);\n\n dRect.setX(newX);\n setFixedWidth(newW);\n\n if (m_onTop) { \/\/ Sliding from top\n dRect.setY(0);\n setGeometry(dRect);\n setFixedHeight(step);\n } else { \/\/ Sliding from bottom\n int nh = pheight-step;\n if ( nh < min_H ) nh = min_H;\n dRect.setY(step);\n setGeometry(dRect);\n setFixedHeight(nh);\n\n }\n}\n\nvoid MibitNotifier::hideOnUserRequest()\n{\n hideDialog();\n closedByUser = true;\n}\n\nvoid MibitNotifier::hideDialog()\n{\n if ( !closedByUser ) {\n timeLine->toggleDirection();\/\/reverse!\n timeLine->start();\n } else closedByUser = !closedByUser;\n}\n\nvoid MibitNotifier::onAnimationFinished()\n{\n if (timeLine->direction() == QTimeLine::Backward) {\n close();\n }\n}\n\nvoid MibitNotifier::setOnBottom(const bool &sOnBottom)\n{\n m_onTop = !sOnBottom;\n}\n\n\nvoid MibitNotifier::setSVG(const QString &file)\n{\n load(file);\n}\n\nvoid MibitNotifier::setIcon(const QPixmap &icon)\n{\n img->setPixmap(icon);\n }\n\nvoid MibitNotifier::setMessage(const QString &msg)\n{\n message->setText(msg);\n}\n\nvoid MibitNotifier::setTextColor(const QString &color)\n{\n message->setStyleSheet(QString(\"color:%1\").arg(color));\n}\n\nvoid MibitNotifier::mousePressEvent ( QMouseEvent * )\n{\n hideOnUserRequest();\n}\n\n\nvoid MibitNotifier::keyPressEvent ( QKeyEvent * event )\n{\n if ( event->key() == Qt::Key_Escape )\n {\n hideOnUserRequest();\n } \/\/else ignore event.\n}\n\n\nMibitNotifier::~MibitNotifier() {}\n\n\n<commit_msg>Improving animation of the notifier...<commit_after>\/***************************************************************************\n * Copyright (C) 2009 by Miguel Chavez Gamboa *\n * miguel@lemonpos.org *\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; 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. 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, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"mibitnotifier.h\"\n\n#include <QPixmap>\n#include <QIcon>\n#include <QString>\n#include <QLabel>\n#include <QHBoxLayout>\n#include <QVBoxLayout>\n#include <QTimeLine>\n#include <QTimer>\n#include <QKeyEvent>\n#include <QDebug>\n\nMibitNotifier::MibitNotifier(QWidget *parent, const QString &file, const QPixmap &icon, const QPixmap &closeIcon, const bool &onTop)\n : QSvgWidget( parent )\n{\n if (file != 0) setSVG(file);\n\n m_parent = parent;\n m_onTop = onTop;\n closedByUser = false;\n m_fileName = file;\n setMinimumHeight(100);\n setFixedSize(0,0); \/\/until show we grow it\n setMaxHeight(max_H); \/\/default sizes\n setMaxWidth(max_W);\n animRate = 500; \/\/default animation speed (half second rate).\n\n img = new QLabel();\n hLayout = new QHBoxLayout();\n message = new QLabel(\"\");\n btnClose = new QLabel(\"\"); \/\/only an image\n\n\n img->setPixmap(icon);\n img->setMaximumHeight(54); \/\/the icon size is hardcoded now.\n img->setMaximumWidth(54);\n img->setAlignment(Qt::AlignLeft);\n img->setMargin(4);\n\n btnClose->setPixmap(closeIcon);\n btnClose->setMaximumHeight(34); \/\/the icon size is hardcoded now.\n btnClose->setMaximumWidth(38);\n btnClose->setToolTip(\"Close Notification\"); \/\/what about translations?\n btnClose->setFixedSize(38,36);\n\n setLayout(hLayout);\n message->setWordWrap(true);\n message->setAlignment(Qt::AlignJustify|Qt::AlignVCenter);\n message->setMargin(10);\n\n hLayout->addWidget(img,0,Qt::AlignLeft);\n hLayout->addWidget(message,1,Qt::AlignLeft);\n hLayout->addWidget(btnClose,0,Qt::AlignRight);\n\n timeLine = new QTimeLine(animRate, this);\n connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int)));\n connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished()));\n}\n\nvoid MibitNotifier::showNotification( const QString &msg, const int &timeToLive) \/\/timeToLive = 0 : not auto hide it.\n{\n \/\/\/ Warning: if a tip is showing, if another showTip() is called, it is ignored.\n if (timeLine->state() == QTimeLine::NotRunning && size().height() <= 0) {\n \/\/set default msg if the sent is empty.\n if (msg.isEmpty()) setMessage(message->text()); else setMessage( msg );\n \/\/change svg skin if is not on top.\n if (!m_onTop) setSVG(\"rotated_\"+m_fileName); else setSVG(m_fileName);\n setGeometry(-1000,-1000,0,0);\n show();\n \/\/update steps for animation, now that the window is showing.\n int maxStep; int minStep = 0;\n\n if ( m_onTop ) {\n minStep = -maxHeight;\n maxStep = 0;\n } else {\n maxStep = m_parent->geometry().height()-maxHeight;\n minStep = m_parent->geometry().height();\n }\n \/\/qDebug()<<\" MaxStep:\"<<maxStep<<\" MinStep:\"<<minStep;\n\n timeLine->setFrameRange(minStep,maxStep);\n \/\/make it grow\n timeLine->setDirection(QTimeLine::Forward);\n timeLine->start();\n btnClose->setFocus();\n\n if (timeToLive > 0 ) QTimer::singleShot(timeToLive,this,SLOT(hideDialog()));\n } \/*else qDebug()<<\"notification is already showing... \"<<size();*\/\n}\n\nvoid MibitNotifier::animate(const int &step)\n{\n \/\/get some sizes...\n QRect windowGeom = m_parent->geometry();\n int midPointX = (windowGeom.width()\/2);\n int newX; int newW;\n QRect dRect;\n int pheight = m_parent->geometry().height();\n if (maxWidth < min_W ) newW = min_W; else newW = maxWidth;\n if ((midPointX-(newW\/2)) < 0) newX = 0; else newX = midPointX - (newW\/2);\n\n dRect.setX(newX);\n setFixedWidth(newW);\n\n dRect.setY(step);\n setGeometry(dRect);\n setFixedHeight(maxHeight);\n\n if (m_onTop) { \/\/ Sliding from top\n if (step == -maxHeight) setFixedHeight(0);\n } else { \/\/ Sliding from bottom\n if (step == m_parent->geometry().height()) setFixedHeight(0);\n } \n}\n\nvoid MibitNotifier::hideOnUserRequest()\n{\n hideDialog();\n closedByUser = true;\n}\n\nvoid MibitNotifier::hideDialog()\n{\n if ( !closedByUser ) {\n timeLine->toggleDirection();\/\/reverse!\n timeLine->start();\n } else closedByUser = !closedByUser;\n}\n\nvoid MibitNotifier::onAnimationFinished()\n{\n if (timeLine->direction() == QTimeLine::Backward) {\n close();\n }\n}\n\nvoid MibitNotifier::setOnBottom(const bool &sOnBottom)\n{\n \/\/ only changes the position when the notification is not showing..\n if (timeLine->state() == QTimeLine::NotRunning && size().height() <= 0) m_onTop = !sOnBottom;\n}\n\n\nvoid MibitNotifier::setSVG(const QString &file)\n{\n load(file);\n}\n\nvoid MibitNotifier::setIcon(const QPixmap &icon)\n{\n img->setPixmap(icon);\n }\n\nvoid MibitNotifier::setMessage(const QString &msg)\n{\n message->setText(msg);\n}\n\nvoid MibitNotifier::setTextColor(const QString &color)\n{\n message->setStyleSheet(QString(\"color:%1\").arg(color));\n}\n\nvoid MibitNotifier::mousePressEvent ( QMouseEvent * )\n{\n hideOnUserRequest();\n}\n\n\nvoid MibitNotifier::keyPressEvent ( QKeyEvent * event )\n{\n if ( event->key() == Qt::Key_Escape )\n {\n hideOnUserRequest();\n } \/\/else ignore event.\n}\n\n\nMibitNotifier::~MibitNotifier() {}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <unistd.h>\n#include <dirent.h>\n#include \"omp.h\"\n\nvoid helpCheck(char *argv[]) {\n\tif (argv[1] == std::string(\"-h\") || argv[1] == std::string(\"--help\")) {\n\t\tstd::cout << \"\\nptxv - Parallel Tar XZ by Ryan Chui (2017)\\n\" << std::endl;\n\t\texit(0);\n\t}\n}\n\nvoid findAll(int *numFiles, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tfindAll(numFiles, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\t*numFiles += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tgetPaths(filePaths, filePath.c_str(), rootPath + fileBuff + \"\/\");\n\t\t\t\t} else {\n\t\t\t\t\tfilePaths->push_back(rootPath + fileBuff);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid compress(std::vector<std::string> *filePaths) {\n\t#pragma omp parallel for schedule(dynamic)\n\tfor (int i = 0; i < filePaths->size(); ++i) {\n\t\tstd::cout << filePaths->at(i) << std::endl;\n\t\tstd::string command = \"XZ_OPT=-9 tar cJf test.\" + std::to_string(i) + \".tar.xz \" + filePaths->at(i);\n\t\tsystem(command.c_str());\n\t}\n}\n\nchar cwd [PATH_MAX];\n\nint main(int argc, char *argv[]) {\n\tint *numFiles = new int(0);\n\t\n\tif (argc > 1) {\n\t\thelpCheck(argv);\n\t}\n\n\tgetcwd(cwd, PATH_MAX);\n\tfindAll(numFiles, cwd);\n\t\/\/ std::cout << *numFiles << std::endl;\n\n\tstd::vector<std::string> *filePaths = new std::vector<std::string>();\n\n\tgetPaths(filePaths, cwd, \"\");\n\tcompress(filePaths);\n\n\tdelete(numFiles);\n\treturn 0;\n}\n<commit_msg>moving to unsigned long long int for more reliability for int max size<commit_after>#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <unistd.h>\n#include <dirent.h>\n#include \"omp.h\"\n\nvoid helpCheck(char *argv[]) {\n\tif (argv[1] == std::string(\"-h\") || argv[1] == std::string(\"--help\")) {\n\t\tstd::cout << \"\\nptxv - Parallel Tar XZ by Ryan Chui (2017)\\n\" << std::endl;\n\t\texit(0);\n\t}\n}\n\nvoid findAll(int *numFiles, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tfindAll(numFiles, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\t*numFiles += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tgetPaths(filePaths, filePath.c_str(), rootPath + fileBuff + \"\/\");\n\t\t\t\t} else {\n\t\t\t\t\tfilePaths->push_back(rootPath + fileBuff);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid compress(std::vector<std::string> *filePaths) {\n\t#pragma omp parallel for schedule(dynamic)\n\tfor (unsigned long long int i = 0; i < filePaths->size(); ++i) {\n\t\tstd::cout << filePaths->at(i) << std::endl;\n\t\tstd::string command = \"XZ_OPT=-9 tar cJf test.\" + std::to_string(i) + \".tar.xz \" + filePaths->at(i);\n\t\tsystem(command.c_str());\n\t}\n}\n\nchar cwd [PATH_MAX];\n\nint main(int argc, char *argv[]) {\n\tint *numFiles = new int(0);\n\t\n\tif (argc > 1) {\n\t\thelpCheck(argv);\n\t}\n\n\tgetcwd(cwd, PATH_MAX);\n\tfindAll(numFiles, cwd);\n\t\/\/ std::cout << *numFiles << std::endl;\n\n\tstd::vector<std::string> *filePaths = new std::vector<std::string>();\n\n\tgetPaths(filePaths, cwd, \"\");\n\tcompress(filePaths);\n\n\tdelete(numFiles);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <unistd.h>\n#include <dirent.h>\n#include \"omp.h\"\n\nvoid helpCheck(char *argv[]) {\n\tif (argv[1] == std::string(\"-h\") || argv[1] == std::string(\"--help\")) {\n\t\tstd::cout << \"\\nptxv - Parallel Tar XZ by Ryan Chui (2017)\\n\" << std::endl;\n\t\texit(0);\n\t}\n}\n\nvoid findAll(int *numFiles, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tfindAll(numFiles, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\t*numFiles += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid getPaths(std::vector<std::string> *filePaths, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tgetPaths(filePaths, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tfilePaths->push_back(filePath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nchar cwd [PATH_MAX];\n\nint main(int argc, char *argv[]) {\n\tint *numFiles = new int(0);\n\t\n\tif (argc > 1) {\n\t\thelpCheck(argv);\n\t}\n\n\tgetcwd(cwd, PATH_MAX);\n\tfindAll(numFiles, cwd);\n\n\tstd::vector<std::string> *filePaths = new std::vector<std::string>();\n\n\tgetPaths(filePaths, cwd);\n\n\tint numThreads = omp_get_num_threads();\n\tstd::cout << numThreads << std::endl;\n\n\tdelete(numFiles);\n\treturn 0;\n}\n<commit_msg>\"Getting max threads not num threads\"<commit_after>#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <unistd.h>\n#include <dirent.h>\n#include \"omp.h\"\n\nvoid helpCheck(char *argv[]) {\n\tif (argv[1] == std::string(\"-h\") || argv[1] == std::string(\"--help\")) {\n\t\tstd::cout << \"\\nptxv - Parallel Tar XZ by Ryan Chui (2017)\\n\" << std::endl;\n\t\texit(0);\n\t}\n}\n\nvoid findAll(int *numFiles, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tfindAll(numFiles, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\t*numFiles += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid getPaths(std::vector<std::string> *filePaths, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tgetPaths(filePaths, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tfilePaths->push_back(filePath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nchar cwd [PATH_MAX];\n\nint main(int argc, char *argv[]) {\n\tint *numFiles = new int(0);\n\t\n\tif (argc > 1) {\n\t\thelpCheck(argv);\n\t}\n\n\tgetcwd(cwd, PATH_MAX);\n\tfindAll(numFiles, cwd);\n\n\tstd::vector<std::string> *filePaths = new std::vector<std::string>();\n\n\tgetPaths(filePaths, cwd);\n\n\tint numThreads = omp_get_max_threads();\n\tstd::cout << numThreads << std::endl;\n\n\tdelete(numFiles);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <unistd.h>\n#include <dirent.h>\n#include \"omp.h\"\n\nvoid helpCheck(char *argv[]) {\n\tif (argv[1] == std::string(\"-h\") || argv[1] == std::string(\"--help\")) {\n\t\tstd::cout << \"\\nptxv - Parallel Tar XZ by Ryan Chui (2017)\\n\" << std::endl;\n\t\texit(0);\n\t}\n}\n\nvoid findAll(int *numFiles, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tfindAll(numFiles, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\t*numFiles += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid getPaths(std::vector<std::string> *filePaths, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tgetPaths(filePaths, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tfilePaths->push_back(filePath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid compress(std::vector<std::string> *filePaths) {\n\tfor (int i = 0; i < filePaths->size(); ++i) {\n\t\tstd::string phrase = \"echo \" + std::stoi(i);\n\t\tsystem(phrase.c_str());\n\t}\n}\n\nchar cwd [PATH_MAX];\n\nint main(int argc, char *argv[]) {\n\tint *numFiles = new int(0);\n\t\n\tif (argc > 1) {\n\t\thelpCheck(argv);\n\t}\n\n\tgetcwd(cwd, PATH_MAX);\n\tfindAll(numFiles, cwd);\n\n\tstd::vector<std::string> *filePaths = new std::vector<std::string>();\n\n\tgetPaths(filePaths, cwd);\n\tcompress(filePaths);\n\n\tdelete(numFiles);\n\treturn 0;\n}\n<commit_msg>using to string isntead of stoi<commit_after>#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <unistd.h>\n#include <dirent.h>\n#include \"omp.h\"\n\nvoid helpCheck(char *argv[]) {\n\tif (argv[1] == std::string(\"-h\") || argv[1] == std::string(\"--help\")) {\n\t\tstd::cout << \"\\nptxv - Parallel Tar XZ by Ryan Chui (2017)\\n\" << std::endl;\n\t\texit(0);\n\t}\n}\n\nvoid findAll(int *numFiles, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tfindAll(numFiles, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\t*numFiles += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid getPaths(std::vector<std::string> *filePaths, const char *cwd) {\n\tDIR *dir;\n\tstruct dirent *ent;\n\n\t\/\/ Check if cwd is a directory\n\tif ((dir = opendir(cwd)) != NULL) {\n\t\t\/\/ Get all file paths within directory.\n\t\twhile ((ent = readdir (dir)) != NULL) {\n\t\t\tstd::string fileBuff = std::string(ent -> d_name);\n\t\t\tif (fileBuff != \".\" && fileBuff != \"..\") {\n\t\t\t\tDIR *dir2;\n\t\t\t\tstd::string filePath = std::string(cwd) + \"\/\" + fileBuff;\n\t\t\t\t\/\/ Check if file path is a directory.\n\t\t\t\tif ((dir2 = opendir(filePath.c_str())) != NULL) {\n\t\t\t\t\tclosedir(dir2);\n\t\t\t\t\tgetPaths(filePaths, filePath.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tfilePaths->push_back(filePath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(dir);\n\t}\n}\n\nvoid compress(std::vector<std::string> *filePaths) {\n\tfor (int i = 0; i < filePaths->size(); ++i) {\n\t\tstd::string phrase = \"echo \" + std::to_string(i);\n\t\tsystem(phrase.c_str());\n\t}\n}\n\nchar cwd [PATH_MAX];\n\nint main(int argc, char *argv[]) {\n\tint *numFiles = new int(0);\n\t\n\tif (argc > 1) {\n\t\thelpCheck(argv);\n\t}\n\n\tgetcwd(cwd, PATH_MAX);\n\tfindAll(numFiles, cwd);\n\n\tstd::vector<std::string> *filePaths = new std::vector<std::string>();\n\n\tgetPaths(filePaths, cwd);\n\tcompress(filePaths);\n\n\tdelete(numFiles);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <streambuf>\n\n#include <3pp\/mpc\/mpc.h>\n\nstd::string readFile(char *fname)\n{\n std::ifstream is(fname, std::ifstream::in);\n std::string str(\n (std::istreambuf_iterator<char>(is)),\n std::istreambuf_iterator<char>()\n );\n return str + '\\n';\n}\n\nint main(int argc, char **argv)\n{\n if (argc <= 1) {\n std::cout << \"Usage: \" << argv[0] << \"file\\n\";\n return 1;\n }\n mpc_parser_t* Comment = mpc_new(\"comment\");\n mpc_parser_t* Indent = mpc_new(\"indent\");\n mpc_parser_t* Newline = mpc_new(\"newline\");\n mpc_parser_t* WhiteSpace = mpc_new(\"ws\");\n mpc_parser_t* OptionalWhiteSpace = mpc_new(\"ows\");\n mpc_parser_t* OptionalWhiteSpaceNewline = mpc_new(\"owsn\");\n mpc_parser_t* Number = mpc_new(\"number\");\n mpc_parser_t* Operator = mpc_new(\"operator\");\n mpc_parser_t* FactorOperator = mpc_new(\"factorop\");\n mpc_parser_t* TermOperator = mpc_new(\"termop\");\n mpc_parser_t* Expr = mpc_new(\"expr\");\n mpc_parser_t* Body = mpc_new(\"body\");\n mpc_parser_t* Identifier = mpc_new(\"identifier\");\n mpc_parser_t* TypeIdent = mpc_new(\"typeident\");\n mpc_parser_t* Import = mpc_new(\"import\");\n mpc_parser_t* MethodRet = mpc_new(\"methodret\");\n mpc_parser_t* MethodDef = mpc_new(\"methoddef\");\n mpc_parser_t* ParamDef = mpc_new(\"paramdef\");\n mpc_parser_t* String = mpc_new(\"string\");\n mpc_parser_t* Args = mpc_new(\"args\");\n mpc_parser_t* Lexp = mpc_new(\"lexp\");\n mpc_parser_t* Factor = mpc_new(\"factor\");\n mpc_parser_t* MethodCall = mpc_new(\"methodcall\");\n mpc_parser_t* MapIndex = mpc_new(\"mapindex\");\n mpc_parser_t* ListItem = mpc_new(\"listitem\");\n mpc_parser_t* MapItem = mpc_new(\"mapitem\");\n mpc_parser_t* TupleMap = mpc_new(\"tuplemap\");\n mpc_parser_t* MapItems = mpc_new(\"mapitems\");\n mpc_parser_t* ListItems = mpc_new(\"listitems\");\n mpc_parser_t* List = mpc_new(\"list\");\n mpc_parser_t* Namespacedef = mpc_new(\"namespacedef\");\n mpc_parser_t* Primitive = mpc_new(\"primitive\");\n mpc_parser_t* Range = mpc_new(\"range\");\n mpc_parser_t* MatchCase = mpc_new(\"matchcase\");\n mpc_parser_t* Match = mpc_new(\"match\");\n mpc_parser_t* Assignment = mpc_new(\"assignment\");\n mpc_parser_t* Stmt = mpc_new(\"stmt\");\n mpc_parser_t* Term = mpc_new(\"term\");\n mpc_parser_t* Const = mpc_new(\"const\");\n mpc_parser_t* Pure = mpc_new(\"pure\");\n mpc_parser_t* TopLevel = mpc_new(\"toplevel\");\n mpc_parser_t* NolangPure = mpc_new(\"nolangpure\");\n\n mpc_err_t* err = mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE,\n \"comment : \/(#|\\\\\/\\\\\/)[^\\\\r\\\\n]*\/\"\n \" | \/\\\\\/\\\\*[^\\\\*]*(\\\\*[^\\\\\/][^\\\\*]*)*\\\\*\\\\\/\/ ;\"\n \"indent : \/\\\\s\\\\s+\/ ;\"\n \"newline : '\\\\n';\"\n \"ws : \/[\\\\s]+\/ ;\"\n \"ows : \/[\\\\s\\\\t]*\/ ;\"\n \"owsn : \/[\\\\s\\\\t\\\\n]*\/ ;\"\n \"identifier : \/[A-Za-z_][A-Za-z0-9_-]*\/ ;\"\n \"typeident : <identifier> <ows> ':' <ows> <identifier> ;\"\n \"number : \/[0-9]+\/ ;\"\n \"string : \/\\\"(\\\\\\\\.|[^\\\"])*\\\"\/ \"\n \" | \/\\'(\\\\\\\\.|[^\\'])*\\'\/ ; \"\n \"operator : '+' | '-' | '*' | '\/' ;\"\n \"factorop : '*'\"\n \" | '\/'\"\n \" | \\\"div\\\"\"\n \" | \\\"mod\\\"\"\n \" | \\\"rem\\\";\"\n \"termop : '+'\"\n \" | '-';\"\n \"import : \\\"import\\\" <ws> <identifier> <newline>;\"\n \"const : \\\"const\\\" <ws> <assignment> <newline>;\"\n \"methodret : <ows> ':' <ows> <identifier> ;\"\n \"methoddef : (<pure> <ws>)? <identifier> <ows> <args>? <methodret>? <ows> \\\"=>\\\" (<newline>|<ws>) <body> ;\"\n \"paramdef : <typeident>? <ows> (',' <ows> <typeident>)*; \"\n \"args : '(' <paramdef>? ')'; \"\n \"factor : <namespacedef>\"\n \" | '(' <lexp> ')'\"\n \" | <number>\"\n \" | <string>\"\n \" | <identifier>; \"\n \"term : <factor> (<ows> <factorop> <ows> <factor>)*;\"\n \"lexp : <term> (<ows> <termop> <ows> <term>)* ; \"\n \"expr : <list>\"\n \" | <lexp>;\"\n \"methodcall : '(' (<expr> (',' <ows> <expr>)*)? ')';\"\n \"mapindex : '[' <expr> ']';\"\n \"listitem : <expr>;\"\n \"mapitem : <string> <ows> ':' <owsn> <expr> ;\"\n \"tuplemap : '(' <string> <owsn> ',' <owsn> <lexp> ')';\"\n \"mapitems : (<tuplemap> | <mapitem>) <owsn> (',' <owsn> (<tuplemap> | <mapitem>)) *;\"\n \"listitems : <listitem> (<owsn> ',' <owsn> <listitem>) *;\"\n \"list : '[' <owsn> (<mapitems> | <listitems>)? <owsn> ']' ;\"\n \"namespacedef : <identifier> ('.' <identifier>)* (<methodcall> | <mapindex>)?;\"\n \"primitive : <identifier> | <number> | <string> ;\"\n \"range : <primitive> \\\"..\\\" <primitive>?;\"\n \"assignment : (<typeident>|<namespacedef>) <ws> '=' <ws> <expr>;\"\n \"matchcase : <comment> | (<indent> (<range> | <primitive> | '?') <ows> ':' <ows> <stmt> <newline>);\"\n \"match : \\\"match\\\" <ws> <stmt> <ows> \\\"=>\\\" <newline> <matchcase>+;\"\n \"stmt : <match>\"\n \" | <assignment>\"\n \" | <namespacedef>\"\n \" | <list>\"\n \" | <expr>\"\n \" | <comment>;\"\n \"body : ((<indent>+ <stmt>)? <newline>)* ;\"\n \"pure : \\\"pure\\\" ;\"\n \"toplevel : <import>\"\n \" | <const>\"\n \" | <comment>\"\n \" | <methoddef>\"\n \" | <newline>;\"\n \"nolangpure : \/^\/ <toplevel>* \/$\/;\"\n ,\n Comment, Indent, Newline,\n WhiteSpace, OptionalWhiteSpace, OptionalWhiteSpaceNewline,\n Identifier, TypeIdent,\n Number, String,\n Operator, FactorOperator, TermOperator,\n Import, Const,\n MethodRet, MethodDef, ParamDef, Args,\n Factor, Term, Lexp,\n Expr, MethodCall,\n MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,\n Namespacedef,\n Primitive, Range,\n Assignment, MatchCase, Match,\n Stmt,\n Body, Pure,\n TopLevel, NolangPure, NULL);\n\n if (err != NULL) {\n mpc_err_print(err);\n mpc_err_delete(err);\n exit(1);\n }\n\n mpc_result_t r;\n std::string data = readFile(argv[1]);\n if (mpc_parse(argv[1], data.c_str(), NolangPure, &r)) {\n mpc_ast_print(static_cast<mpc_ast_t*>(r.output));\n mpc_ast_delete(static_cast<mpc_ast_t*>(r.output));\n } else {\n mpc_err_print(r.error);\n mpc_err_delete(r.error);\n }\n\n mpc_cleanup(39,\n Comment, Indent, Newline,\n WhiteSpace, OptionalWhiteSpace, OptionalWhiteSpaceNewline,\n Identifier, TypeIdent,\n Number, String,\n Operator, FactorOperator, TermOperator,\n Import, Const,\n MethodRet, MethodDef, ParamDef, Args,\n Factor, Term, Lexp,\n Expr, MethodCall,\n MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,\n Namespacedef,\n Primitive, Range,\n Assignment, MatchCase, Match,\n Stmt,\n Body, Pure,\n TopLevel, NolangPure);\n\n return 0;\n}\n<commit_msg>Return statement, and failure at main<commit_after>#include <iostream>\n#include <fstream>\n#include <streambuf>\n\n#include <3pp\/mpc\/mpc.h>\n\nstd::string readFile(char *fname)\n{\n std::ifstream is(fname, std::ifstream::in);\n std::string str(\n (std::istreambuf_iterator<char>(is)),\n std::istreambuf_iterator<char>()\n );\n return str + '\\n';\n}\n\nint main(int argc, char **argv)\n{\n if (argc <= 1) {\n std::cout << \"Usage: \" << argv[0] << \"file\\n\";\n return 1;\n }\n mpc_parser_t* Comment = mpc_new(\"comment\");\n mpc_parser_t* Indent = mpc_new(\"indent\");\n mpc_parser_t* Newline = mpc_new(\"newline\");\n mpc_parser_t* WhiteSpace = mpc_new(\"ws\");\n mpc_parser_t* OptionalWhiteSpace = mpc_new(\"ows\");\n mpc_parser_t* OptionalWhiteSpaceNewline = mpc_new(\"owsn\");\n mpc_parser_t* Number = mpc_new(\"number\");\n mpc_parser_t* Operator = mpc_new(\"operator\");\n mpc_parser_t* FactorOperator = mpc_new(\"factorop\");\n mpc_parser_t* TermOperator = mpc_new(\"termop\");\n mpc_parser_t* Expr = mpc_new(\"expr\");\n mpc_parser_t* Body = mpc_new(\"body\");\n mpc_parser_t* Identifier = mpc_new(\"identifier\");\n mpc_parser_t* TypeIdent = mpc_new(\"typeident\");\n mpc_parser_t* Import = mpc_new(\"import\");\n mpc_parser_t* MethodRet = mpc_new(\"methodret\");\n mpc_parser_t* MethodDef = mpc_new(\"methoddef\");\n mpc_parser_t* ParamDef = mpc_new(\"paramdef\");\n mpc_parser_t* String = mpc_new(\"string\");\n mpc_parser_t* Args = mpc_new(\"args\");\n mpc_parser_t* Lexp = mpc_new(\"lexp\");\n mpc_parser_t* Factor = mpc_new(\"factor\");\n mpc_parser_t* MethodCall = mpc_new(\"methodcall\");\n mpc_parser_t* MapIndex = mpc_new(\"mapindex\");\n mpc_parser_t* ListItem = mpc_new(\"listitem\");\n mpc_parser_t* MapItem = mpc_new(\"mapitem\");\n mpc_parser_t* TupleMap = mpc_new(\"tuplemap\");\n mpc_parser_t* MapItems = mpc_new(\"mapitems\");\n mpc_parser_t* ListItems = mpc_new(\"listitems\");\n mpc_parser_t* List = mpc_new(\"list\");\n mpc_parser_t* Namespacedef = mpc_new(\"namespacedef\");\n mpc_parser_t* Primitive = mpc_new(\"primitive\");\n mpc_parser_t* Range = mpc_new(\"range\");\n mpc_parser_t* MatchCase = mpc_new(\"matchcase\");\n mpc_parser_t* Match = mpc_new(\"match\");\n mpc_parser_t* Assignment = mpc_new(\"assignment\");\n mpc_parser_t* Stmt = mpc_new(\"stmt\");\n mpc_parser_t* Term = mpc_new(\"term\");\n mpc_parser_t* Const = mpc_new(\"const\");\n mpc_parser_t* Return = mpc_new(\"return\");\n mpc_parser_t* Pure = mpc_new(\"pure\");\n mpc_parser_t* TopLevel = mpc_new(\"toplevel\");\n mpc_parser_t* NolangPure = mpc_new(\"nolangpure\");\n\n mpc_err_t* err = mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE,\n \"comment : \/(#|\\\\\/\\\\\/)[^\\\\r\\\\n]*\/\"\n \" | \/\\\\\/\\\\*[^\\\\*]*(\\\\*[^\\\\\/][^\\\\*]*)*\\\\*\\\\\/\/ ;\"\n \"indent : \/\\\\s\\\\s+\/ ;\"\n \"newline : '\\\\n';\"\n \"ws : \/[\\\\s]+\/ ;\"\n \"ows : \/[\\\\s\\\\t]*\/ ;\"\n \"owsn : \/[\\\\s\\\\t\\\\n]*\/ ;\"\n \"identifier : \/[A-Za-z_][A-Za-z0-9_-]*\/ ;\"\n \"typeident : <identifier> <ows> ':' <ows> <identifier> ;\"\n \"number : \/[0-9]+\/ ;\"\n \"string : \/\\\"(\\\\\\\\.|[^\\\"])*\\\"\/ \"\n \" | \/\\'(\\\\\\\\.|[^\\'])*\\'\/ ; \"\n \"operator : '+' | '-' | '*' | '\/' ;\"\n \"factorop : '*'\"\n \" | '\/'\"\n \" | \\\"div\\\"\"\n \" | \\\"mod\\\"\"\n \" | \\\"rem\\\";\"\n \"termop : '+'\"\n \" | '-';\"\n \"import : \\\"import\\\" <ws> <identifier> <newline>;\"\n \"const : \\\"const\\\" <ws> <assignment> <newline>;\"\n \"methodret : <ows> ':' <ows> <identifier> ;\"\n \"methoddef : (<pure> <ws>)? <identifier> <ows> <args>? <methodret>? <ows> \\\"=>\\\" (<newline>|<ws>) <body> ;\"\n \"paramdef : <typeident>? <ows> (',' <ows> <typeident>)*; \"\n \"args : '(' <paramdef>? ')'; \"\n \"factor : <namespacedef>\"\n \" | '(' <lexp> ')'\"\n \" | <number>\"\n \" | <string>\"\n \" | <identifier>; \"\n \"term : <factor> (<ows> <factorop> <ows> <factor>)*;\"\n \"lexp : <term> (<ows> <termop> <ows> <term>)* ; \"\n \"expr : <list>\"\n \" | <lexp>;\"\n \"methodcall : '(' (<expr> (',' <ows> <expr>)*)? ')';\"\n \"mapindex : '[' <expr> ']';\"\n \"listitem : <expr>;\"\n \"mapitem : <string> <ows> ':' <owsn> <expr> ;\"\n \"tuplemap : '(' <string> <owsn> ',' <owsn> <lexp> ')';\"\n \"mapitems : (<tuplemap> | <mapitem>) <owsn> (',' <owsn> (<tuplemap> | <mapitem>)) *;\"\n \"listitems : <listitem> (<owsn> ',' <owsn> <listitem>) *;\"\n \"list : '[' <owsn> (<mapitems> | <listitems>)? <owsn> ']' ;\"\n \"namespacedef : <identifier> ('.' <identifier>)* (<methodcall> | <mapindex>)?;\"\n \"primitive : <identifier> | <number> | <string> ;\"\n \"range : <primitive> \\\"..\\\" <primitive>?;\"\n \"assignment : (<typeident>|<namespacedef>) <ws> '=' <ws> <expr>;\"\n \"matchcase : <comment> | (<indent> (<range> | <primitive> | '?') <ows> ':' <ows> <stmt> <newline>);\"\n \"match : \\\"match\\\" <ws> <stmt> <ows> \\\"=>\\\" <newline> <matchcase>+;\"\n \"stmt : <match>\"\n \" | <assignment>\"\n \" | <namespacedef>\"\n \" | <list>\"\n \" | <expr>\"\n \" | <return>\"\n \" | <comment>;\"\n \"body : ((<indent>+ <stmt>)? <newline>)* ;\"\n \"pure : \\\"pure\\\" ;\"\n \"return : \\\"return \\\" <stmt>;\"\n \"toplevel : <import>\"\n \" | <const>\"\n \" | <comment>\"\n \" | <methoddef>\"\n \" | <newline>;\"\n \"nolangpure : \/^\/ <toplevel>* \/$\/;\"\n ,\n Comment, Indent, Newline,\n WhiteSpace, OptionalWhiteSpace, OptionalWhiteSpaceNewline,\n Identifier, TypeIdent,\n Number, String,\n Operator, FactorOperator, TermOperator,\n Import, Const,\n MethodRet, MethodDef, ParamDef, Args,\n Factor, Term, Lexp,\n Expr, MethodCall,\n MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,\n Namespacedef,\n Primitive, Range,\n Assignment, MatchCase, Match,\n Stmt,\n Body, Pure, Return,\n TopLevel, NolangPure, NULL);\n\n if (err != NULL) {\n mpc_err_print(err);\n mpc_err_delete(err);\n exit(1);\n }\n\n mpc_result_t r;\n std::string data = readFile(argv[1]);\n int res = 0;\n if (mpc_parse(argv[1], data.c_str(), NolangPure, &r)) {\n mpc_ast_print(static_cast<mpc_ast_t*>(r.output));\n mpc_ast_delete(static_cast<mpc_ast_t*>(r.output));\n } else {\n mpc_err_print(r.error);\n mpc_err_delete(r.error);\n res = 1;\n }\n\n mpc_cleanup(39,\n Comment, Indent, Newline,\n WhiteSpace, OptionalWhiteSpace, OptionalWhiteSpaceNewline,\n Identifier, TypeIdent,\n Number, String,\n Operator, FactorOperator, TermOperator,\n Import, Const,\n MethodRet, MethodDef, ParamDef, Args,\n Factor, Term, Lexp,\n Expr, MethodCall,\n MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,\n Namespacedef,\n Primitive, Range,\n Assignment, MatchCase, Match,\n Stmt,\n Body, Pure, Return,\n TopLevel, NolangPure);\n\n return res;\n}\n<|endoftext|>"} {"text":"<commit_before> \n#include <iostream>\n#include <limits>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <stdio.h>\n#include <stdarg.h>\n#include \"mosek.h\"\n\n\/* \n\nTODO: Solution may not be feasible (OPTIMAL), if so, return\n\n *\/\n\n\n\nstruct Node {\n int ID;\n double nodeObj;\n double lowerBound;\n double* nodeSoln;\n bool feasible;\n bool intfeasible;\n bool eliminated;\n MSKtask_t problem;\n Node* parent;\n std::vector< std::vector <int> > usedCuts;\n int depth;\n};\n\nstatic void MSKAPI printstr(void *handle, MSKCONST char str[])\n{\n printf(\"%s\",str);\n}\n\nMSKtask_t oProblem = NULL; \/\/ Original problem instance\ndouble globalUpperBound_ = std::numeric_limits<double>::infinity();\ndouble* bestSoln_;\nint branchingRule_ = 0; \/\/ 0: most fractional, 1: index-based, 2: value-based\nint cutPriority_ = 0; \/\/ 0: default, most fractional, 1: best-value\nint cutRule_ = 0; \/\/ 0: default, no cut, 1: always cut, 2: deep-heuristic-cut\nint cutLimit_ = 1; \/\/ max number of cuts to add, default is 1\nint nodesProcessed_ = 0;\nint totalNodes_ = 0;\nint numVars_ = 0;\nint N = 0; \/* number of assets, always 1 less than numVars *\/\nNode* root;\nstd::vector< Node* > nodeList_;\nstd::vector< Node* > allNodeList_; \/\/ Keeps pointer of all nodes for destructor\nint printLevel_ = 2;\n\nint startBB();\nint createProblem(MSKtask_t* originalProblem);\nint createNewNode(Node* parent, Node** newNode, int varID, double bound, int lower);\nint printTxt(int level, const char* fmt, ...);\nint selectNode(Node** activeNode);\nint solveLP(Node* aNode);\nint isIntFeasible(Node* aNode);\nint branch(Node* activeNode);\nint eliminateNodes();\n\nint main(int argc, char* argv[]) {\n\n std::cout << \"Working!\" << std::endl;\n root = NULL;\n \/\/ if(argc) ....\n numVars_ = 11;\n N = numVars_ - 1;\n \n MSKenv_t env = NULL;\n MSKtask_t task = NULL;\n MSKrescodee r;\n\n \/* Create the mosek environment. *\/\n r = MSK_makeenv(&env,NULL);\n r = MSK_maketask(env,3,N+1,&task);\n \n oProblem = task;\n \n startBB();\n \n return 1;\n}\n \nint startBB() {\n int status = 0;\n createProblem(&oProblem);\n \n root = (Node *) malloc(sizeof(Node));\n createNewNode(0, &root, -1 \/*var id*\/, 0 \/* bound *\/, 0 \/* lower *\/);\n \n while(true) {\n \n printTxt(2, \"Active Nodes: %d\", nodeList_.size());\n \n if(nodeList_.size() == 0) {\n break;\n }\n \n Node* activeNode;\n selectNode(&activeNode);\n \n\tif(!activeNode->eliminated) {\n\t solveLP(activeNode);\n\t} else {\n\t continue;\n\t}\n\n\tif( activeNode->feasible) { isIntFeasible(activeNode); }\n\n\tif( activeNode->feasible && activeNode->intfeasible) {\n\t if(activeNode->nodeObj < globalUpperBound_) {\n\t globalUpperBound_ = activeNode->nodeObj;\n\t bestSoln_ = activeNode->nodeSoln;\n\t eliminateNodes();\n\t printTxt(1, \"Best objective value: %f\", globalUpperBound_);\n\t }\n\t} else if(activeNode->feasible && !activeNode->intfeasible) {\n\t \/\/ branch\n\t if(activeNode->nodeObj <= globalUpperBound_) {\n\t printTxt(3, \"Upper bound: %f, current objective: %f, branching...\",globalUpperBound_,activeNode->nodeObj);\n\t branch(activeNode);\n\t }\n\t} else {\n\t continue;\n\t}\n \n }\n \n return status;\n}\n\nint branch(Node* activeNode) {\n int status = 0;\n\n \/\/ find most fractional\n int asset = 0;\n double mostfrac = 0;\n for(int i=0; i<N; ++i) {\n double cValue = activeNode->nodeSoln[i];\n double smallest = fmin(cValue - floor(cValue), ceil(cValue) - cValue);\n if(smallest >= mostfrac) {\n\tasset = i;\n\tmostfrac = smallest;\n }\n }\n\n \/\/ Call newNode twice\n\n \/\/ Left - Less than bound\n Node* leftNode = (Node*) malloc(sizeof(Node));\n createNewNode(activeNode \/*parent*\/, &leftNode, asset \/*var id*\/, floor(activeNode->nodeSoln[asset])\/* bound *\/, 0 \/* lower *\/);\n \/\/ Right - Greater than bound\n Node* rightNode = (Node*) malloc(sizeof(Node));\n createNewNode(activeNode \/*parent*\/, &rightNode, asset \/*var id*\/, ceil(activeNode->nodeSoln[asset]) \/* bound *\/, 1 \/* lower *\/);\n \n \n \/\/ Add them to active list\n \/\/ Done in create\n \n return status;\n}\n\nint cut() {\n int status = 0;\n \n \n \n \n \n return status;\n}\n\nint selectNode(Node** activeNode) {\n int status = 0;\n int selected = 0;\n int max_depth = 0;\n *activeNode = nodeList_[0];\n for(unsigned int i=0; i < nodeList_.size(); i++) {\n if(nodeList_[i]->depth > max_depth) {\n selected = i;\n *activeNode = nodeList_[i];\n }\n }\n nodeList_.erase(nodeList_.begin()+selected);\n \n printTxt(4,\"Node selected: %d (%p)\", (*activeNode)->ID, *activeNode);\n \n return status;\n}\n\nint eliminateNodes() {\n for(unsigned int i=0; i<nodeList_.size(); i++) {\n if(nodeList_[i]->lowerBound > globalUpperBound_) {\n nodeList_[i]->eliminated = true;\n }\n }\n}\n\nint createNewNode(Node* parent, Node** newNode, int varID, double bound, int lower) {\n int status = 0;\n \n \n if(!parent) {\n \n \n \n for (int i = 0; i < N; ++i) { \/\/ Initialize array of used cuts\n std::vector<int> row; \/\/ Create an empty row for each asset\n \/\/(*newNode)->usedCuts.push_back(row); \/\/ Add the row to the main vector\n }\n \n \n (*newNode)->ID = 0;\n (*newNode)->nodeObj = 0;\n (*newNode)->lowerBound = 0;\n (*newNode)->feasible = false;\n (*newNode)->intfeasible = false;\n\t(*newNode)->eliminated = false;\n (*newNode)->problem = oProblem;\n (*newNode)->parent = 0;\n \/\/(*newNode)->usedCuts = usedCuts;\n (*newNode)->depth = 0;\n \n printTxt(3, \"Root is created\");\n \n } else {\n \n printTxt(3, \"New node is created\");\n \n \/\/ Add branch constraint here\n \/\/ Change problem\n MSKtask_t newProblem;\n MSK_clonetask((parent->problem), &newProblem);\n\t\n\t\/\/MSK_analyzeproblem(parent->problem, MSK_STREAM_LOG);\n\t\n\t\/\/MSK_analyzeproblem(newProblem, MSK_STREAM_LOG);\n\t\n\t\n if(varID!=-1) {\n MSK_chgbound ( \n newProblem, \/\/MSKtask_t task, \n MSK_ACC_VAR, \/\/MSKaccmodee accmode, \n varID+1, \/\/MSKint32t i, \n lower, \/\/MSKint32t lower, \n 1, \/\/MSKint32t finite, \n bound \/\/MSKrealt value); \n );\n }\n \n std::vector< std::vector <int> > usedCuts;\n \/\/ copy usedCuts\n for (int i = 0; i < N; i++) { \/\/ Initialize array of used cuts\n\t \/\/std::vector<int> row = parent->usedCuts[i]; \/\/ Create an empty row for each asset\n \/\/usedCuts.push_back(row); \/\/ Add the row to the main vector\n }\n \n (*newNode)->ID = totalNodes_;\n (*newNode)->nodeObj = 0;\n (*newNode)->lowerBound = parent->lowerBound;\n (*newNode)->feasible = false;\n (*newNode)->intfeasible = false;\n\t(*newNode)->eliminated = false;\n \/\/(*newNode)->problem = &newProblem;\n (*newNode)->problem = newProblem;\n\t(*newNode)->parent = parent;\n \/\/(*newNode)->usedCuts = usedCuts;\n (*newNode)->depth = parent->depth+1;\n \n\t\n }\n \n \n nodeList_.push_back(*newNode);\n allNodeList_.push_back(*newNode);\n totalNodes_++;\n \n \n return status;\n}\n\n\nint solveLP(Node* aNode) {\n int status = 0;\n MSKtask_t mtask = NULL;\n \n \/\/MSK_analyzeproblem(mtask, MSK_STREAM_LOG);\n\n\n MSK_clonetask(aNode->problem, &mtask);\n \n \/\/MSKvariabletypee* vartype = malloc(numVars_*sizeof(MSKvariabletypee));\n for(int i=0; i<N; ++i) {\n MSK_putvartype (mtask, i+1, MSK_VAR_TYPE_CONT);\n }\n \/\/std::cout << \"Running so far!\" << std::endl;\n \/\/MSK_linkfunctotaskstream (mtask, MSK_STREAM_LOG, NULL, printstr);\n MSK_optimize(mtask);\n \n MSKsolstae solsta;\n MSK_getsolsta (mtask, MSK_SOL_ITR, &solsta); \n \n MSKrealt primalobj;\n\n \/\/if(solsta) {\n \/\/ Save it, etc..\n \n \/\/}\n\n switch( solsta ) \n { \n case MSK_SOL_STA_OPTIMAL: \n case MSK_SOL_STA_NEAR_OPTIMAL: \n { \n aNode->feasible = true;\n\t MSK_getprimalobj(mtask, MSK_SOL_ITR, &primalobj);\n\t aNode->nodeObj = primalobj;\n\t if(primalobj > aNode->lowerBound) {\n\t aNode -> lowerBound = primalobj;\n\t }\n\t aNode -> nodeSoln = (double*) malloc(N*sizeof(double));\n\t MSK_getsolutionslice(mtask, MSK_SOL_ITR, MSK_SOL_ITEM_XX, 1, N+1, aNode->nodeSoln);\n\t \n\t \/\/for(int j=0; j<N; ++j) {\n\t \/\/ std::cout << \"Variable \" << j << \" value: \" << aNode->nodeSoln[j] << std::endl;\n\t \/\/}\n\t \n\t \/\/ std::cout << primalobj << std::endl;\n printTxt(3, \"Node (%d) Optimal Objective: %f\", aNode->ID, aNode->nodeObj);\n break; \n } \n case MSK_SOL_STA_DUAL_INFEAS_CER: \n case MSK_SOL_STA_PRIM_INFEAS_CER: \n case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER: \n case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:\n\taNode->feasible = false;\n\tprintTxt(3,\"Node (%d) infeasibility certificate found.\", aNode->ID); \n\tbreak; \n default: \n\taNode->feasible = false;\n\tbreak; \n } \n \n \/\/MSK_solutionsummary (mtask, MSK_STREAM_LOG);\n \n \n return status;\n \n}\n\nint isIntFeasible(Node* aNode) {\n bool intfeasible = true;\n for(int i=0; i<N; ++i) {\n \n double intpart;\n if( std::modf(aNode->nodeSoln[i], &intpart) >= 1e-8) {\n intfeasible = false;\n printTxt(5,\"Integer infeasibility at asset %d, value: %f\",i, aNode->nodeSoln[i]);\n }\n }\n \n aNode->intfeasible = intfeasible;\n intfeasible ? printTxt(4,\"Node %d is integer feasible\",aNode->ID) : printTxt(4,\"Node %d is NOT integer feasible\",aNode->ID);\n return 1;\n}\n\nint printTxt(int level, const char* fmt, ...) {\n\n if(level<=printLevel_) {\n std::cout << level << \":\";\n for(int i=0; i<level; ++i) {\n std::cout << \" \";\n }\n va_list args;\n va_start(args,fmt);\n vprintf(fmt,args);\n va_end(args);\n std::cout << std::endl;\n }\n return 1;\n \n}\n\n\n\n<commit_msg>Report summary is added.<commit_after> \n#include <iostream>\n#include <limits>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <stdio.h>\n#include <stdarg.h>\n#include \"mosek.h\"\n\n\/* \n\nTODO: Solution may not be feasible (OPTIMAL), if so, return\n\n *\/\n\n\n\nstruct Node {\n int ID;\n double nodeObj;\n double lowerBound;\n double* nodeSoln;\n bool feasible;\n bool intfeasible;\n bool eliminated;\n MSKtask_t problem;\n Node* parent;\n std::vector< std::vector <int> > usedCuts;\n int depth;\n};\n\nstatic void MSKAPI printstr(void *handle, MSKCONST char str[])\n{\n printf(\"%s\",str);\n}\n\nMSKtask_t oProblem = NULL; \/\/ Original problem instance\ndouble globalUpperBound_ = std::numeric_limits<double>::infinity();\ndouble* bestSoln_;\nint branchingRule_ = 0; \/\/ 0: most fractional, 1: index-based, 2: value-based\nint cutPriority_ = 0; \/\/ 0: default, most fractional, 1: best-value\nint cutRule_ = 0; \/\/ 0: default, no cut, 1: always cut, 2: deep-heuristic-cut\nint cutLimit_ = 1; \/\/ max number of cuts to add, default is 1\nint nodesProcessed_ = 0;\nint totalNodes_ = 0;\nint numVars_ = 0;\nint N = 0; \/* number of assets, always 1 less than numVars *\/\nNode* root;\nstd::vector< Node* > nodeList_;\nstd::vector< Node* > allNodeList_; \/\/ Keeps pointer of all nodes for destructor\nint printLevel_ = 2;\n\nint startBB();\nint createProblem(MSKtask_t* originalProblem);\nint createNewNode(Node* parent, Node** newNode, int varID, double bound, int lower);\nint printTxt(int level, const char* fmt, ...);\nint selectNode(Node** activeNode);\nint solveLP(Node* aNode);\nint isIntFeasible(Node* aNode);\nint branch(Node* activeNode);\nint eliminateNodes();\n\nint main(int argc, char* argv[]) {\n\n std::cout << \"Working!\" << std::endl;\n root = NULL;\n \/\/ if(argc) ....\n numVars_ = 11;\n N = numVars_ - 1;\n \n MSKenv_t env = NULL;\n MSKtask_t task = NULL;\n MSKrescodee r;\n\n \/* Create the mosek environment. *\/\n r = MSK_makeenv(&env,NULL);\n r = MSK_maketask(env,3,N+1,&task);\n \n oProblem = task;\n \n startBB();\n \n return 1;\n}\n \nint startBB() {\n int status = 0;\n createProblem(&oProblem);\n \n root = (Node *) malloc(sizeof(Node));\n createNewNode(0, &root, -1 \/*var id*\/, 0 \/* bound *\/, 0 \/* lower *\/);\n \n while(true) {\n \n printTxt(3, \"Active Nodes: %d\", nodeList_.size());\n \n if(nodeList_.size() == 0) {\n break;\n }\n \n Node* activeNode;\n selectNode(&activeNode);\n \n\tif(!activeNode->eliminated) {\n\t solveLP(activeNode);\n\t} else {\n\t continue;\n\t}\n\n\tif( activeNode->feasible) { isIntFeasible(activeNode); }\n\n\tif( activeNode->feasible && activeNode->intfeasible) {\n\t if(activeNode->nodeObj < globalUpperBound_) {\n\t globalUpperBound_ = activeNode->nodeObj;\n\t bestSoln_ = activeNode->nodeSoln;\n\t eliminateNodes();\n\t printTxt(1, \"Best objective value: %f\", globalUpperBound_);\n\t }\n\t} else if(activeNode->feasible && !activeNode->intfeasible) {\n\t \/\/ branch\n\t if(activeNode->nodeObj <= globalUpperBound_) {\n\t printTxt(3, \"Upper bound: %f, current objective: %f, branching...\",globalUpperBound_,activeNode->nodeObj);\n\t branch(activeNode);\n\t }\n\t} else {\n\t continue;\n\t}\n \n }\n\n \/\/ Summary report\n printTxt(1, \"========== SUMMARY ==========\");\n printTxt(1, \"Best objective value: %f\", globalUpperBound_);\n printTxt(1, \"Values: \");\n for(int i=0; i<N; i++) {\n printTxt(1, \"\\t%d: %f\", (i+1), bestSoln_[i]);\n }\n printTxt(1,\"Done...\");\n return status;\n}\n\nint branch(Node* activeNode) {\n int status = 0;\n\n \/\/ find most fractional\n int asset = 0;\n double mostfrac = 0;\n for(int i=0; i<N; ++i) {\n double cValue = activeNode->nodeSoln[i];\n double smallest = fmin(cValue - floor(cValue), ceil(cValue) - cValue);\n if(smallest >= mostfrac) {\n\tasset = i;\n\tmostfrac = smallest;\n }\n }\n\n \/\/ Call newNode twice\n\n \/\/ Left - Less than bound\n Node* leftNode = (Node*) malloc(sizeof(Node));\n createNewNode(activeNode \/*parent*\/, &leftNode, asset \/*var id*\/, floor(activeNode->nodeSoln[asset])\/* bound *\/, 0 \/* lower *\/);\n \/\/ Right - Greater than bound\n Node* rightNode = (Node*) malloc(sizeof(Node));\n createNewNode(activeNode \/*parent*\/, &rightNode, asset \/*var id*\/, ceil(activeNode->nodeSoln[asset]) \/* bound *\/, 1 \/* lower *\/);\n \n \n \/\/ Add them to active list\n \/\/ Done in create\n \n return status;\n}\n\nint cut() {\n int status = 0;\n \n \n \n \n \n return status;\n}\n\nint selectNode(Node** activeNode) {\n int status = 0;\n int selected = 0;\n int max_depth = 0;\n *activeNode = nodeList_[0];\n for(unsigned int i=0; i < nodeList_.size(); i++) {\n if(nodeList_[i]->depth > max_depth) {\n selected = i;\n *activeNode = nodeList_[i];\n }\n }\n nodeList_.erase(nodeList_.begin()+selected);\n \n printTxt(4,\"Node selected: %d (%p)\", (*activeNode)->ID, *activeNode);\n \n return status;\n}\n\nint eliminateNodes() {\n for(unsigned int i=0; i<nodeList_.size(); i++) {\n if(nodeList_[i]->lowerBound > globalUpperBound_) {\n nodeList_[i]->eliminated = true;\n }\n }\n}\n\nint createNewNode(Node* parent, Node** newNode, int varID, double bound, int lower) {\n int status = 0;\n \n \n if(!parent) {\n \n \n \n for (int i = 0; i < N; ++i) { \/\/ Initialize array of used cuts\n std::vector<int> row; \/\/ Create an empty row for each asset\n \/\/(*newNode)->usedCuts.push_back(row); \/\/ Add the row to the main vector\n }\n \n \n (*newNode)->ID = 0;\n (*newNode)->nodeObj = 0;\n (*newNode)->lowerBound = 0;\n (*newNode)->feasible = false;\n (*newNode)->intfeasible = false;\n\t(*newNode)->eliminated = false;\n (*newNode)->problem = oProblem;\n (*newNode)->parent = 0;\n \/\/(*newNode)->usedCuts = usedCuts;\n (*newNode)->depth = 0;\n \n printTxt(3, \"Root is created\");\n \n } else {\n \n printTxt(3, \"New node is created\");\n \n \/\/ Add branch constraint here\n \/\/ Change problem\n MSKtask_t newProblem;\n MSK_clonetask((parent->problem), &newProblem);\n\t\n\t\/\/MSK_analyzeproblem(parent->problem, MSK_STREAM_LOG);\n\t\n\t\/\/MSK_analyzeproblem(newProblem, MSK_STREAM_LOG);\n\t\n\t\n if(varID!=-1) {\n MSK_chgbound ( \n newProblem, \/\/MSKtask_t task, \n MSK_ACC_VAR, \/\/MSKaccmodee accmode, \n varID+1, \/\/MSKint32t i, \n lower, \/\/MSKint32t lower, \n 1, \/\/MSKint32t finite, \n bound \/\/MSKrealt value); \n );\n }\n \n std::vector< std::vector <int> > usedCuts;\n \/\/ copy usedCuts\n for (int i = 0; i < N; i++) { \/\/ Initialize array of used cuts\n\t \/\/std::vector<int> row = parent->usedCuts[i]; \/\/ Create an empty row for each asset\n \/\/usedCuts.push_back(row); \/\/ Add the row to the main vector\n }\n \n (*newNode)->ID = totalNodes_;\n (*newNode)->nodeObj = 0;\n (*newNode)->lowerBound = parent->lowerBound;\n (*newNode)->feasible = false;\n (*newNode)->intfeasible = false;\n\t(*newNode)->eliminated = false;\n \/\/(*newNode)->problem = &newProblem;\n (*newNode)->problem = newProblem;\n\t(*newNode)->parent = parent;\n \/\/(*newNode)->usedCuts = usedCuts;\n (*newNode)->depth = parent->depth+1;\n \n\t\n }\n \n \n nodeList_.push_back(*newNode);\n allNodeList_.push_back(*newNode);\n totalNodes_++;\n \n \n return status;\n}\n\n\nint solveLP(Node* aNode) {\n int status = 0;\n MSKtask_t mtask = NULL;\n \n \/\/MSK_analyzeproblem(mtask, MSK_STREAM_LOG);\n\n\n MSK_clonetask(aNode->problem, &mtask);\n \n \/\/MSKvariabletypee* vartype = malloc(numVars_*sizeof(MSKvariabletypee));\n for(int i=0; i<N; ++i) {\n MSK_putvartype (mtask, i+1, MSK_VAR_TYPE_CONT);\n }\n \/\/std::cout << \"Running so far!\" << std::endl;\n \/\/MSK_linkfunctotaskstream (mtask, MSK_STREAM_LOG, NULL, printstr);\n MSK_optimize(mtask);\n \n MSKsolstae solsta;\n MSK_getsolsta (mtask, MSK_SOL_ITR, &solsta); \n \n MSKrealt primalobj;\n\n \/\/if(solsta) {\n \/\/ Save it, etc..\n \n \/\/}\n\n switch( solsta ) \n { \n case MSK_SOL_STA_OPTIMAL: \n case MSK_SOL_STA_NEAR_OPTIMAL: \n { \n aNode->feasible = true;\n\t MSK_getprimalobj(mtask, MSK_SOL_ITR, &primalobj);\n\t aNode->nodeObj = primalobj;\n\t if(primalobj > aNode->lowerBound) {\n\t aNode -> lowerBound = primalobj;\n\t }\n\t aNode -> nodeSoln = (double*) malloc(N*sizeof(double));\n\t MSK_getsolutionslice(mtask, MSK_SOL_ITR, MSK_SOL_ITEM_XX, 1, N+1, aNode->nodeSoln);\n\t \n\t \/\/for(int j=0; j<N; ++j) {\n\t \/\/ std::cout << \"Variable \" << j << \" value: \" << aNode->nodeSoln[j] << std::endl;\n\t \/\/}\n\t \n\t \/\/ std::cout << primalobj << std::endl;\n printTxt(3, \"Node (%d) Optimal Objective: %f\", aNode->ID, aNode->nodeObj);\n break; \n } \n case MSK_SOL_STA_DUAL_INFEAS_CER: \n case MSK_SOL_STA_PRIM_INFEAS_CER: \n case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER: \n case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:\n\taNode->feasible = false;\n\tprintTxt(3,\"Node (%d) infeasibility certificate found.\", aNode->ID); \n\tbreak; \n default: \n\taNode->feasible = false;\n\tbreak; \n } \n \n \/\/MSK_solutionsummary (mtask, MSK_STREAM_LOG);\n \n \n return status;\n \n}\n\nint isIntFeasible(Node* aNode) {\n bool intfeasible = true;\n for(int i=0; i<N; ++i) {\n \n double intpart;\n if( std::modf(aNode->nodeSoln[i], &intpart) >= 1e-8) {\n intfeasible = false;\n printTxt(5,\"Integer infeasibility at asset %d, value: %f\",i, aNode->nodeSoln[i]);\n }\n }\n \n aNode->intfeasible = intfeasible;\n intfeasible ? printTxt(4,\"Node %d is integer feasible\",aNode->ID) : printTxt(4,\"Node %d is NOT integer feasible\",aNode->ID);\n return 1;\n}\n\nint printTxt(int level, const char* fmt, ...) {\n\n if(level<=printLevel_) {\n std::cout << level << \":\";\n for(int i=0; i<level; ++i) {\n std::cout << \" \";\n }\n va_list args;\n va_start(args,fmt);\n vprintf(fmt,args);\n va_end(args);\n std::cout << std::endl;\n }\n return 1;\n \n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * =====================================================================================\n *\n * Filename: kmer_query.cc\n *\n * Description: \n *\n * Version: 1.0\n * Created: 04\/27\/2016 08:48:26 AM\n * Revision: none\n * Compiler: gcc\n *\n * Author: Prashant Pandey (), ppandey@cs.stonybrook.edu\n * Organization: Stony Brook University\n *\n * =====================================================================================\n *\/\n#include <iostream>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <set>\n#include <bitset>\n#include <cassert>\n#include <fstream>\n\n#include <boost\/thread\/thread.hpp>\n#include <boost\/lockfree\/queue.hpp>\n#include <boost\/lockfree\/spsc_queue.hpp>\n#include <boost\/atomic.hpp>\n\n#include <time.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys\/resource.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <sys\/mman.h>\n\n#include \"clipp.h\"\n#include \"ProgOpts.h\"\n#include \"gqf_cpp.h\"\n#include \"kmer.h\"\n\n\/*\n * === FUNCTION ======================================================================\n * Name: main\n * Description: \n * =====================================================================================\n *\/\nint query_main(QueryOpts& opts)\n{\n\tstruct timeval start, end;\n\tstruct timezone tzp;\n\tstd::unordered_set<uint64_t> kmers;\n\n\tsrand(time(NULL));\n\tspdlog::logger* console = opts.console.get();\n\n\t\/\/Initialize the QF\n\tconsole->info(\"Reading kmers into the QF off the disk.\");\n\tCQF<KeyObject> cqf(opts.squeakr_file, LOCKS_FORBIDDEN, FREAD);\n\n\t\/\/ seek to the end of the file and read the k-mer size\n\tstd::ifstream squeakr_file(opts.squeakr_file, std::ofstream::in);\n\tsqueakr_file.seekg(0, squeakr_file.end);\n\tuint64_t file_size = squeakr_file.tellg();\n\tuint64_t kmer_size;\n\tsqueakr_file.seekg(file_size - sizeof(kmer_size));\n\tsqueakr_file.read((char*)&kmer_size, sizeof(kmer_size));\n\tsqueakr_file.close();\n\tconsole->info(\"kmer size: {}\", kmer_size);\n\n\tif (cqf.is_exact() && kmer_size*2 != cqf.keybits()) {\n\t\tconsole->error(\"K-mer size is not correct.\");\n\t\treturn 1;\n\t}\n\n\tconsole->info(\"Parsing query file for {}-mers.\", kmer_size);\n\tKmer::parse_kmers(opts.queryfile.c_str(), kmer_size, kmers);\n\tconsole->info(\"Found {} k-mers\", kmers.size());\n\n\tstd::ofstream opfile(opts.output_file.c_str(), std::ofstream::out);\n\n\tconsole->info(\"Querying kmers in the QF.\");\n\tuint64_t num_not_found = 0;\n\tgettimeofday(&start, &tzp);\n\tfor (auto it = kmers.begin(); it != kmers.end(); ++it) {\n\t\tuint64_t count = cqf.query(KeyObject(*it, 0, 0));\n\t\tif (count == 0) {\n\t\t\tstd::cout << Kmer::int_to_str(*it, kmer_size) << std::endl;\n\t\t\tnum_not_found++;\n\t\t}\n\t\telse\n\t\t\topfile << Kmer::int_to_str(*it, kmer_size) << \"\\t\" << count << std::endl;\n\t}\n\tgettimeofday(&end, &tzp);\n\topfile.close();\n\tprint_time_elapsed(\"\", &start, &end, console);\n\n\tconsole->info(\"Not found: {}\", num_not_found);\n\n\treturn EXIT_SUCCESS;\n}\t\t\t\t\/* ---------- end of function main ---------- *\/\n\n<commit_msg>tested query and listing.<commit_after>\/*\n * =====================================================================================\n *\n * Filename: kmer_query.cc\n *\n * Description: \n *\n * Version: 1.0\n * Created: 04\/27\/2016 08:48:26 AM\n * Revision: none\n * Compiler: gcc\n *\n * Author: Prashant Pandey (), ppandey@cs.stonybrook.edu\n * Organization: Stony Brook University\n *\n * =====================================================================================\n *\/\n#include <iostream>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <set>\n#include <bitset>\n#include <cassert>\n#include <fstream>\n\n#include <boost\/thread\/thread.hpp>\n#include <boost\/lockfree\/queue.hpp>\n#include <boost\/lockfree\/spsc_queue.hpp>\n#include <boost\/atomic.hpp>\n\n#include <time.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys\/resource.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <sys\/mman.h>\n\n#include \"clipp.h\"\n#include \"ProgOpts.h\"\n#include \"gqf_cpp.h\"\n#include \"kmer.h\"\n\n\/*\n * === FUNCTION ======================================================================\n * Name: main\n * Description: \n * =====================================================================================\n *\/\nint query_main(QueryOpts& opts)\n{\n\tstruct timeval start, end;\n\tstruct timezone tzp;\n\tstd::unordered_set<uint64_t> kmers;\n\n\tsrand(time(NULL));\n\tspdlog::logger* console = opts.console.get();\n\n\t\/\/Initialize the QF\n\tconsole->info(\"Reading kmers into the QF off the disk.\");\n\tCQF<KeyObject> cqf(opts.squeakr_file, LOCKS_FORBIDDEN, FREAD);\n\n\t\/\/ seek to the end of the file and read the k-mer size\n\tstd::ifstream squeakr_file(opts.squeakr_file, std::ofstream::in);\n\tsqueakr_file.seekg(0, squeakr_file.end);\n\tuint64_t file_size = squeakr_file.tellg();\n\tuint64_t kmer_size;\n\tsqueakr_file.seekg(file_size - sizeof(kmer_size));\n\tsqueakr_file.read((char*)&kmer_size, sizeof(kmer_size));\n\tsqueakr_file.close();\n\tconsole->info(\"kmer size: {}\", kmer_size);\n\n\tif (cqf.is_exact() && kmer_size*2 != cqf.keybits()) {\n\t\tconsole->error(\"K-mer size is not correct.\");\n\t\treturn 1;\n\t}\n\n\tconsole->info(\"Parsing query file for {}-mers.\", kmer_size);\n\tKmer::parse_kmers(opts.queryfile.c_str(), kmer_size, kmers);\n\tconsole->info(\"Found {} k-mers\", kmers.size());\n\n\tstd::ofstream opfile(opts.output_file.c_str(), std::ofstream::out);\n\n\tconsole->info(\"Querying kmers in the QF.\");\n\tuint64_t num_not_found = 0;\n\tgettimeofday(&start, &tzp);\n\tfor (auto it = kmers.begin(); it != kmers.end(); ++it) {\n\t\tuint64_t count = cqf.query(KeyObject(*it, 0, 0));\n\t\tif (count == 0) {\n\t\t\tconsole->error(Kmer::int_to_str(*it, kmer_size));\n\t\t\tnum_not_found++;\n\t\t}\n\t\telse\n\t\t\topfile << Kmer::int_to_str(*it, kmer_size) << \"\\t\" << count << std::endl;\n\t}\n\tgettimeofday(&end, &tzp);\n\topfile.close();\n\tprint_time_elapsed(\"\", &start, &end, console);\n\n\tconsole->info(\"Not found: {}\", num_not_found);\n\n\treturn EXIT_SUCCESS;\n}\t\t\t\t\/* ---------- end of function main ---------- *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file Cosa\/Board\/ITEADStudio\/Iboard.hh\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2015, Mikael Patel\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 * This file is part of the Arduino Che Cosa project.\n *\/\n\n#ifndef COSA_BOARD_ITEADSTUDIO_IBOARD_HH\n#define COSA_BOARD_ITEADSTUDIO_IBOARD_HH\n\n\/* This board is based on ATmega328P *\/\n#define BOARD_ATMEGA328P\n\n\/**\n * Compiler warning on unused varable.\n *\/\n#if !defined(UNUSED)\n#define UNUSED(x) (void) (x)\n#endif\n\n\/**\n * Cosa pin symbol and hardware definitions for the ATmega328P based\n * board ITEAD Studio IBoard. Cosa does not use pin numbers as\n * Arduino\/Wiring, instead strong data type is used (enum types) for\n * the specific pin classes; DigitalPin, AnalogPin, PWMPin, etc.\n *\n * The pin numbers for ATmega328P are mapped as in Arduino. The static\n * inline functions, SFR, BIT and UART, rely on compiler optimizations\n * to be reduced.\n *\n * @section Board\n * @code\n * ITEAD Studio Iboard\n * ----- --------\n * +-|(o)|--------------| RJ45 |--+\n * | | | | | |\n * | ----- | | |\n * | -------- |\n * | |\n * | |\n * | |\n * | |\n * | |\n * | |\n * |ISP SD |\n * |[][] +--------+|\n * |[][] | \/|\n * |[][]* | | |\n * | | | |\n * D14\/A0 |[][][] | \\|\n * D15\/A1 |[][][] +--------+|\n * D16\/A2 |[][][] |\n * D17\/A3 |[][][] |\n * SDA\/D18\/A4 |[][][] |\n * SCL\/D19\/A5 |[][][] |\n * A6 |[][][] |\n * A7 |[][][] |\n * +------------------------------+\n * @endcode\n *\/\nclass Board {\n friend class Pin;\n friend class UART;\nprivate:\n \/**\n * Do not allow instances. This is a static singleton; name space.\n *\/\n Board() {}\n\n \/**\n * Return Special Function Register for given Arduino pin number.\n * @param[in] pin number.\n * @return special register pointer.\n *\/\n static volatile uint8_t* SFR(uint8_t pin)\n __attribute__((always_inline))\n {\n return (pin < 8 ? &PIND :\n\t pin < 14 ? &PINB :\n\t &PINC);\n }\n\n \/**\n * Return bit position for given Arduino pin number in Special\n * Function Register.\n * @param[in] pin number.\n * @return pin bit position.\n *\/\n static uint8_t BIT(uint8_t pin)\n __attribute__((always_inline))\n {\n return (pin < 8 ? pin :\n\t pin < 14 ? pin - 8 :\n \t pin - 14);\n }\n\n \/**\n * Return Pin Change Mask Register for given Arduino pin number.\n * @param[in] pin number.\n * @return pin change mask register pointer.\n *\/\n static volatile uint8_t* PCIMR(uint8_t pin)\n __attribute__((always_inline))\n {\n return (pin < 8 ? &PCMSK2 :\n\t pin < 14 ? &PCMSK0 :\n\t &PCMSK1);\n }\n\n \/**\n * Return UART Register for given Arduino serial port.\n * @param[in] port number.\n * @return UART register pointer.\n *\/\n static volatile uint8_t* UART(uint8_t port)\n __attribute__((always_inline))\n {\n UNUSED(port);\n return (&UCSR0A);\n }\n\npublic:\n \/**\n * Initiate board ports. Disable SPI chip select pins, i.e.\n * defined as output pins and set high.\n *\/\n static void init();\n\n \/**\n * Digital pin symbols\n *\/\n enum DigitalPin {\n D0 = 0,\t\t\t\/\/ PD0\/XBEE:DOUT\n D1,\t\t\t\t\/\/ PD1\/XBEE:DIN\n D2,\t\t\t\t\/\/ PD2\/NRF24L01:IRQ\n D3,\t\t\t\t\/\/ PD3\/NRF24L01:CE\n D4,\t\t\t\t\/\/ PD4\/SD:CS\n D5,\t\t\t\t\/\/ PD5\/NRF24L01:MOSI\n D6,\t\t\t\t\/\/ PD6\/NRF24L01:MISO\n D7,\t\t\t\t\/\/ PD7\/NRF24L01:SCK\n D8,\t\t\t\t\/\/ PB0\/NRF24L01:SS\n D9,\t\t\t\t\/\/ PB1\/NC\n D10,\t\t\t\/\/ PB2\/W5100:SS\n D11,\t\t\t\/\/ PB3\/MOSI\n D12,\t\t\t\/\/ PB4\/MISO\n D13,\t\t\t\/\/ PB5\/SCK\n D14,\t\t\t\/\/ PC0\/A0\n D15,\t\t\t\/\/ PC1\/A1\n D16,\t\t\t\/\/ PC2\/A2\n D17,\t\t\t\/\/ PC3\/A3\n D18,\t\t\t\/\/ PC4\/A4\n D19,\t\t\t\/\/ PC5\/A5\n LED = D13\n } __attribute__((packed));\n\n \/**\n * Analog pin symbols (ADC channel numbers)\n *\/\n enum AnalogPin {\n A0 = 0,\t\t\t\/\/ PC0\/D14\n A1,\t\t\t\t\/\/ PC1\/D15\n A2,\t\t\t\t\/\/ PC2\/D16\n A3,\t\t\t\t\/\/ PC3\/D17\n A4,\t\t\t\t\/\/ PC4\/D18\n A5,\t\t\t\t\/\/ PC5\/D19\n A6,\t\t\t\t\/\/ ADC6\n A7\t\t\t\t\/\/ ADC7\n } __attribute__((packed));\n\n \/**\n * Reference voltage; ARef pin, Vcc or internal 1V1.\n *\/\n enum Reference {\n APIN_REFERENCE = 0,\n AVCC_REFERENCE = _BV(REFS0),\n A1V1_REFERENCE = (_BV(REFS1) | _BV(REFS0))\n } __attribute__((packed));\n\n \/**\n * PWM pin symbols; sub-set of digital pins to allow compile\n * time checking\n *\/\n enum PWMPin {\n PWM0 = D3,\t\t\t\/\/ PD3 => OCR2B\n PWM1 = D5,\t\t\t\/\/ PD5 => OCR0B\n PWM2 = D6,\t\t\t\/\/ PD6 => OCR0A\n PWM3 = D9,\t\t\t\/\/ PB1 => OCR1A\n PWM4 = D10,\t\t\t\/\/ PB2 => OCR1B\n PWM5 = D11\t\t\t\/\/ PB3 => OCR2A\n } __attribute__((packed));\n\n \/**\n * External interrupt pin symbols; sub-set of digital pins\n * to allow compile time checking.\n *\/\n enum ExternalInterruptPin {\n EXT0 = D2,\t\t\t\/\/ PD2\n EXT1 = D3\t\t\t\/\/ PD3\n } __attribute__((packed));\n\n \/**\n * Pin change interrupt (PCI) pins (as digital pin number).\n *\/\n enum InterruptPin {\n PCI0 = D0,\t\t\t\/\/ PD0\n PCI1 = D1,\t\t\t\/\/ PD1\n PCI2 = D2,\t\t\t\/\/ PD2\n PCI3 = D3,\t\t\t\/\/ PD3\n PCI4 = D4,\t\t\t\/\/ PD4\n PCI5 = D5,\t\t\t\/\/ PD5\n PCI6 = D6,\t\t\t\/\/ PD6\n PCI7 = D7,\t\t\t\/\/ PD7\n PCI8 = D8,\t\t\t\/\/ PB0\n PCI9 = D9,\t\t\t\/\/ PB1\n PCI10 = D10,\t\t\/\/ PB2\n PCI11 = D11,\t\t\/\/ PB3\n PCI12 = D12,\t\t\/\/ PB4\n PCI13 = D13,\t\t\/\/ PB5\n PCI14 = D14,\t\t\/\/ PC0\n PCI15 = D15,\t\t\/\/ PC1\n PCI16 = D16,\t\t\/\/ PC2\n PCI17 = D17,\t\t\/\/ PC3\n PCI18 = D18,\t\t\/\/ PC4\n PCI19 = D19\t\t\t\/\/ PC5\n } __attribute__((packed));\n\n \/**\n * Size of pin maps.\n *\/\n enum {\n ANALOG_PIN_MAX = 8,\n DIGITAL_PIN_MAX = 20,\n EXT_PIN_MAX = 2,\n PCI_PIN_MAX = 20,\n PWM_PIN_MAX = 6\n };\n\n \/**\n * Pins used for TWI interface (port C, analog pins A4-A5).\n *\/\n enum TWIPin {\n SDA = 4,\t\t\t\/\/ PA4\/A4\n SCL = 5\t\t\t\/\/ PA4\/A5\n } __attribute__((packed));\n\n \/**\n * Pins used for SPI interface (port B, digital pins D10-D13).\n *\/\n enum SPIPin {\n SS = 2,\t\t\t\/\/ PB2\/D10\n MOSI = 3,\t\t\t\/\/ PB3\/D11\/ICSP\n MISO = 4,\t\t\t\/\/ PB4\/D12\/ICSP\n SCK = 5\t\t\t\/\/ PB5\/D13\/ICSP\n } __attribute__((packed));\n\n \/**\n * Auxiliary\n *\/\n enum {\n VBG = (_BV(MUX3) | _BV(MUX2) | _BV(MUX1)),\n UART_MAX = 1,\n EXT_MAX = 2,\n PCMSK_MAX = 3,\n PCINT_MAX = 24\n } __attribute__((packed));\n};\n\n\/**\n * Forward declare interrupt service routines to allow them as friends.\n *\/\nextern \"C\" {\n void ADC_vect(void) __attribute__ ((signal));\n void ANALOG_COMP_vect(void) __attribute__ ((signal));\n void INT0_vect(void) __attribute__ ((signal));\n void INT1_vect(void) __attribute__ ((signal));\n void PCINT0_vect(void) __attribute__ ((signal));\n void PCINT1_vect(void) __attribute__ ((signal));\n void PCINT2_vect(void) __attribute__ ((signal));\n void SPI_STC_vect(void) __attribute__ ((signal));\n void TIMER0_COMPA_vect(void) __attribute__ ((signal));\n void TIMER0_COMPB_vect(void) __attribute__ ((signal));\n void TIMER0_OVF_vect(void) __attribute__ ((signal));\n void TIMER1_CAPT_vect(void) __attribute__ ((signal));\n void TIMER1_COMPA_vect(void) __attribute__ ((signal));\n void TIMER1_COMPB_vect(void) __attribute__ ((signal));\n void TIMER1_OVF_vect(void) __attribute__ ((signal));\n void TIMER2_COMPA_vect(void) __attribute__ ((signal));\n void TIMER2_COMPB_vect(void) __attribute__ ((signal));\n void TIMER2_OVF_vect(void) __attribute__ ((signal));\n void TWI_vect(void) __attribute__ ((signal));\n void WDT_vect(void) __attribute__ ((signal));\n void USART_RX_vect(void) __attribute__ ((signal));\n void USART_TX_vect(void) __attribute__ ((signal));\n void USART_UDRE_vect(void) __attribute__ ((signal));\n}\n#endif\n<commit_msg>Cleanup.<commit_after>\/**\n * @file Cosa\/Board\/ITEADStudio\/IBoard.hh\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2015, Mikael Patel\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 * This file is part of the Arduino Che Cosa project.\n *\/\n\n#ifndef COSA_BOARD_ITEADSTUDIO_IBOARD_HH\n#define COSA_BOARD_ITEADSTUDIO_IBOARD_HH\n\n\/* This board is based on ATmega328P *\/\n#define BOARD_ATMEGA328P\n\n\/**\n * Compiler warning on unused varable.\n *\/\n#if !defined(UNUSED)\n#define UNUSED(x) (void) (x)\n#endif\n\n\/**\n * Cosa pin symbol and hardware definitions for the ATmega328P based\n * board ITEAD Studio IBoard. Cosa does not use pin numbers as\n * Arduino\/Wiring, instead strong data type is used (enum types) for\n * the specific pin classes; DigitalPin, AnalogPin, PWMPin, etc.\n *\n * The pin numbers for ATmega328P are mapped as in Arduino. The static\n * inline functions, SFR, BIT and UART, rely on compiler optimizations\n * to be reduced.\n *\n * @section Board\n * @code\n * ITEAD Studio IBoard\n * ----- --------\n * +-|(o)|--------------| RJ45 |--+\n * | | | | | |\n * | ----- | | |\n * | -------- |\n * | |\n * | |\n * | |\n * | |\n * | |\n * | |\n * |ISP SD |\n * |[][] +--------+|\n * |[][] | \/|\n * |[][]* | | |\n * | | | |\n * D14\/A0 |[][][] | \\|\n * D15\/A1 |[][][] +--------+|\n * D16\/A2 |[][][] |\n * D17\/A3 |[][][] |\n * SDA\/D18\/A4 |[][][] |\n * SCL\/D19\/A5 |[][][] |\n * A6 |[][][] |\n * A7 |[][][] |\n * +------------------------------+\n * @endcode\n *\/\nclass Board {\n friend class Pin;\n friend class UART;\nprivate:\n \/**\n * Do not allow instances. This is a static singleton; name space.\n *\/\n Board() {}\n\n \/**\n * Return Special Function Register for given Arduino pin number.\n * @param[in] pin number.\n * @return special register pointer.\n *\/\n static volatile uint8_t* SFR(uint8_t pin)\n __attribute__((always_inline))\n {\n return (pin < 8 ? &PIND :\n\t pin < 14 ? &PINB :\n\t &PINC);\n }\n\n \/**\n * Return bit position for given Arduino pin number in Special\n * Function Register.\n * @param[in] pin number.\n * @return pin bit position.\n *\/\n static uint8_t BIT(uint8_t pin)\n __attribute__((always_inline))\n {\n return (pin < 8 ? pin :\n\t pin < 14 ? pin - 8 :\n \t pin - 14);\n }\n\n \/**\n * Return Pin Change Mask Register for given Arduino pin number.\n * @param[in] pin number.\n * @return pin change mask register pointer.\n *\/\n static volatile uint8_t* PCIMR(uint8_t pin)\n __attribute__((always_inline))\n {\n return (pin < 8 ? &PCMSK2 :\n\t pin < 14 ? &PCMSK0 :\n\t &PCMSK1);\n }\n\n \/**\n * Return UART Register for given Arduino serial port.\n * @param[in] port number.\n * @return UART register pointer.\n *\/\n static volatile uint8_t* UART(uint8_t port)\n __attribute__((always_inline))\n {\n UNUSED(port);\n return (&UCSR0A);\n }\n\npublic:\n \/**\n * Initiate board ports. Disable SPI chip select pins, i.e.\n * defined as output pins and set high.\n *\/\n static void init();\n\n \/**\n * Digital pin symbols\n *\/\n enum DigitalPin {\n D0 = 0,\t\t\t\/\/ PD0\/XBEE:DOUT\n D1,\t\t\t\t\/\/ PD1\/XBEE:DIN\n D2,\t\t\t\t\/\/ PD2\/NRF24L01:IRQ\n D3,\t\t\t\t\/\/ PD3\/NRF24L01:CE\n D4,\t\t\t\t\/\/ PD4\/SD:CS\n D5,\t\t\t\t\/\/ PD5\/NRF24L01:MOSI\n D6,\t\t\t\t\/\/ PD6\/NRF24L01:MISO\n D7,\t\t\t\t\/\/ PD7\/NRF24L01:SCK\n D8,\t\t\t\t\/\/ PB0\/NRF24L01:SS\n D9,\t\t\t\t\/\/ PB1\/NC\n D10,\t\t\t\/\/ PB2\/W5100:SS\n D11,\t\t\t\/\/ PB3\/MOSI\n D12,\t\t\t\/\/ PB4\/MISO\n D13,\t\t\t\/\/ PB5\/SCK\n D14,\t\t\t\/\/ PC0\/A0\n D15,\t\t\t\/\/ PC1\/A1\n D16,\t\t\t\/\/ PC2\/A2\n D17,\t\t\t\/\/ PC3\/A3\n D18,\t\t\t\/\/ PC4\/A4\n D19,\t\t\t\/\/ PC5\/A5\n LED = D13\n } __attribute__((packed));\n\n \/**\n * Analog pin symbols (ADC channel numbers)\n *\/\n enum AnalogPin {\n A0 = 0,\t\t\t\/\/ PC0\/D14\n A1,\t\t\t\t\/\/ PC1\/D15\n A2,\t\t\t\t\/\/ PC2\/D16\n A3,\t\t\t\t\/\/ PC3\/D17\n A4,\t\t\t\t\/\/ PC4\/D18\n A5,\t\t\t\t\/\/ PC5\/D19\n A6,\t\t\t\t\/\/ ADC6\n A7\t\t\t\t\/\/ ADC7\n } __attribute__((packed));\n\n \/**\n * Reference voltage; ARef pin, Vcc or internal 1V1.\n *\/\n enum Reference {\n APIN_REFERENCE = 0,\n AVCC_REFERENCE = _BV(REFS0),\n A1V1_REFERENCE = (_BV(REFS1) | _BV(REFS0))\n } __attribute__((packed));\n\n \/**\n * PWM pin symbols; sub-set of digital pins to allow compile\n * time checking\n *\/\n enum PWMPin {\n PWM0 = D3,\t\t\t\/\/ PD3 => OCR2B\n PWM1 = D5,\t\t\t\/\/ PD5 => OCR0B\n PWM2 = D6,\t\t\t\/\/ PD6 => OCR0A\n PWM3 = D9,\t\t\t\/\/ PB1 => OCR1A\n PWM4 = D10,\t\t\t\/\/ PB2 => OCR1B\n PWM5 = D11\t\t\t\/\/ PB3 => OCR2A\n } __attribute__((packed));\n\n \/**\n * External interrupt pin symbols; sub-set of digital pins\n * to allow compile time checking.\n *\/\n enum ExternalInterruptPin {\n EXT0 = D2,\t\t\t\/\/ PD2\n EXT1 = D3\t\t\t\/\/ PD3\n } __attribute__((packed));\n\n \/**\n * Pin change interrupt (PCI) pins (as digital pin number).\n *\/\n enum InterruptPin {\n PCI0 = D0,\t\t\t\/\/ PD0\n PCI1 = D1,\t\t\t\/\/ PD1\n PCI2 = D2,\t\t\t\/\/ PD2\n PCI3 = D3,\t\t\t\/\/ PD3\n PCI4 = D4,\t\t\t\/\/ PD4\n PCI5 = D5,\t\t\t\/\/ PD5\n PCI6 = D6,\t\t\t\/\/ PD6\n PCI7 = D7,\t\t\t\/\/ PD7\n PCI8 = D8,\t\t\t\/\/ PB0\n PCI9 = D9,\t\t\t\/\/ PB1\n PCI10 = D10,\t\t\/\/ PB2\n PCI11 = D11,\t\t\/\/ PB3\n PCI12 = D12,\t\t\/\/ PB4\n PCI13 = D13,\t\t\/\/ PB5\n PCI14 = D14,\t\t\/\/ PC0\n PCI15 = D15,\t\t\/\/ PC1\n PCI16 = D16,\t\t\/\/ PC2\n PCI17 = D17,\t\t\/\/ PC3\n PCI18 = D18,\t\t\/\/ PC4\n PCI19 = D19\t\t\t\/\/ PC5\n } __attribute__((packed));\n\n \/**\n * Size of pin maps.\n *\/\n enum {\n ANALOG_PIN_MAX = 8,\n DIGITAL_PIN_MAX = 20,\n EXT_PIN_MAX = 2,\n PCI_PIN_MAX = 20,\n PWM_PIN_MAX = 6\n };\n\n \/**\n * Pins used for TWI interface (port C, analog pins A4-A5).\n *\/\n enum TWIPin {\n SDA = 4,\t\t\t\/\/ PA4\/A4\n SCL = 5\t\t\t\/\/ PA4\/A5\n } __attribute__((packed));\n\n \/**\n * Pins used for SPI interface (port B, digital pins D10-D13).\n *\/\n enum SPIPin {\n SS = 2,\t\t\t\/\/ PB2\/D10\n MOSI = 3,\t\t\t\/\/ PB3\/D11\/ICSP\n MISO = 4,\t\t\t\/\/ PB4\/D12\/ICSP\n SCK = 5\t\t\t\/\/ PB5\/D13\/ICSP\n } __attribute__((packed));\n\n \/**\n * Auxiliary\n *\/\n enum {\n VBG = (_BV(MUX3) | _BV(MUX2) | _BV(MUX1)),\n UART_MAX = 1,\n EXT_MAX = 2,\n PCMSK_MAX = 3,\n PCINT_MAX = 24\n } __attribute__((packed));\n};\n\n\/**\n * Forward declare interrupt service routines to allow them as friends.\n *\/\nextern \"C\" {\n void ADC_vect(void) __attribute__ ((signal));\n void ANALOG_COMP_vect(void) __attribute__ ((signal));\n void INT0_vect(void) __attribute__ ((signal));\n void INT1_vect(void) __attribute__ ((signal));\n void PCINT0_vect(void) __attribute__ ((signal));\n void PCINT1_vect(void) __attribute__ ((signal));\n void PCINT2_vect(void) __attribute__ ((signal));\n void SPI_STC_vect(void) __attribute__ ((signal));\n void TIMER0_COMPA_vect(void) __attribute__ ((signal));\n void TIMER0_COMPB_vect(void) __attribute__ ((signal));\n void TIMER0_OVF_vect(void) __attribute__ ((signal));\n void TIMER1_CAPT_vect(void) __attribute__ ((signal));\n void TIMER1_COMPA_vect(void) __attribute__ ((signal));\n void TIMER1_COMPB_vect(void) __attribute__ ((signal));\n void TIMER1_OVF_vect(void) __attribute__ ((signal));\n void TIMER2_COMPA_vect(void) __attribute__ ((signal));\n void TIMER2_COMPB_vect(void) __attribute__ ((signal));\n void TIMER2_OVF_vect(void) __attribute__ ((signal));\n void TWI_vect(void) __attribute__ ((signal));\n void WDT_vect(void) __attribute__ ((signal));\n void USART_RX_vect(void) __attribute__ ((signal));\n void USART_TX_vect(void) __attribute__ ((signal));\n void USART_UDRE_vect(void) __attribute__ ((signal));\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ the syntax for messages is:\n\/\/ wd 'mb type buttons title message'\n\/\/\n\/\/ type specifies the icon and default behaviour:\n\/\/ info (default OK button)\n\/\/ warn (default OK button)\n\/\/ critical (default OK button)\n\/\/ query (requires two or three buttons)\n\/\/\n\/\/ if one button, there is no result,\n\/\/ otherwise the result is the button name (ok, cancel, ...)\n\/\/\n\/\/ buttons are from the set:\n\/\/ mb_ok\n\/\/ mb_cancel\n\/\/ mb_yes\n\/\/ mb_no\n\/\/ mb_save\n\/\/ mb_discard\n\n#include <QApplication>\n#include <QColorDialog>\n#include <QFileDialog>\n#include <QFontDialog>\n#include <QMessageBox>\n#include <QTextDocument>\n\n#include \"wd.h\"\n#include \"cmd.h\"\n#include \"..\/base\/dialog.h\"\n\n#ifndef ANDROID\n#include <QPrinter>\n#include <QPrintDialog>\nextern QPrinter *pprinter;\n#endif\n\nQString mbcolor();\nQString mbdir();\nQString mbfont();\nQString mbinfo(QString);\n#ifndef ANDROID\nQString mbprint(bool);\nQString mbprintx(bool);\nQString mbprinter();\n#endif\nQString mbmsg();\nQString mbopen();\nQString mbsave();\n\nQString fixsep(QString s);\n\nQString type;\nQStringList arg;\n\nQMessageBox::StandardButton getdefaultbutton();\nQMessageBox::StandardButton getonebutton();\nQMessageBox::StandardButtons getotherbuttons();\nQString getname(int);\n\n\/\/ ---------------------------------------------------------------------\nQString mb(string p)\n{\n arg=qsplit(p);\n if (arg.size()<1) return mbinfo(\"missing mb type\");\n\n type=arg.first();\n arg.removeFirst();\n if (type==\"color\")\n return mbcolor();\n if (type==\"dir\")\n return mbdir();\n if (type==\"font\")\n return mbfont();\n if (type==\"open\")\n return mbopen();\n#ifndef ANDROID\n if (type==\"print\") {\n QString s=dlb(s2q(p.substr(5)));\n return mbprint('*'==s.at(0));\n }\n if (type==\"printx\") {\n QString s=dlb(s2q(p.substr(6)));\n return mbprintx('*'==s.at(0));\n }\n#endif\n if (type==\"save\")\n return mbsave();\n if (type==\"info\"||type==\"query\"||type==\"warn\"||type==\"critical\")\n return mbmsg();\n return mbinfo(\"invalid mb type: \" + type);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbmsg()\n{\n int r;\n QString t,m;\n\n QMessageBox::StandardButton button1=getdefaultbutton();\n QMessageBox::StandardButtons buttons=getotherbuttons();\n\n if (arg.size()==1) {\n t=\"Message Box\";\n m=arg.at(0);\n } else if (arg.size()==2) {\n t=arg.at(0);\n m=arg.at(1);\n } else {\n return mbinfo (\"Need title and message: \"+arg.join(\" \"));\n }\n\n if (button1==-1) {\n button1=QMessageBox::Ok;\n if (type==\"query\")\n buttons=QMessageBox::Cancel;\n }\n buttons|=button1;\n\n if (type==\"query\") {\n r=QMessageBox::question(QApplication::focusWidget(),t,m,buttons,button1);\n return getname(r);\n }\n if (type==\"critical\")\n QMessageBox::critical(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"info\")\n QMessageBox::information(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"warn\")\n QMessageBox::warning(QApplication::focusWidget(),t,m,buttons,button1);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbcolor()\n{\n QColor c;\n int r,g,b;\n\n if (arg.size()==3) {\n r=c_strtoi(q2s(arg.at(0)));\n g=c_strtoi(q2s(arg.at(1)));\n b=c_strtoi(q2s(arg.at(2)));\n c=QColor(r,g,b);\n } else\n c=Qt::white;\n c=QColorDialog::getColor(c,QApplication::focusWidget());\n if (!c.isValid()) return \"\";\n return s2q(i2s(c.red()) + \" \" + i2s(c.green()) + \" \" + i2s(c.blue()));\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbdir()\n{\n QString title,dir;\n if (arg.size()!=2)\n return mbinfo(\"dir needs title and directory\");\n title=arg.at(0);\n dir=arg.at(1);\n return QFileDialog::getExistingDirectory(\n QApplication::focusWidget(),title,dir);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbfont()\n{\n bool ok;\n QFont font, def;\n QString s;\n def.setStrikeOut(false);\n def.setUnderline(false);\n if (arg.size())\n def.setFamily(arg.at(0));\n if (arg.size()>1)\n def.setPointSize(arg.at(1).toFloat());\n for (int i=2; i<arg.size(); i++) {\n s=arg.at(i);\n if (s==\"bold\")\n def.setBold(true);\n if (s==\"italic\")\n def.setItalic(true);\n if (s==\"strikeout\")\n def.setStrikeOut(true);\n if (s==\"underline\")\n def.setUnderline(true);\n }\n font=QFontDialog::getFont(&ok,def,QApplication::focusWidget());\n if (!ok) return \"\";\n QString r;\n r=\"\\\"\" + font.family() + \"\\\" \" + QString::number(font.pointSize());\n if (font.bold()) r+=\" bold\";\n if (font.italic()) r+=\" italic\";\n if (font.strikeOut()) r+=\" strikeout\";\n if (font.underline()) r+=\" underline\";\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbopen()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"open needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=fixsep(arg.at(2));\n return QFileDialog::getOpenFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n#ifndef ANDROID\n\/\/ ---------------------------------------------------------------------\nQString mbprint(bool iftext)\n{\n QString s=arg.at(0);\n if (!iftext) {\n if (!cfexist(s)) {\n mbinfo(\"File not found: \" + s);\n return \"\";\n }\n s=cfread(s);\n }\n QTextDocument *d=new QTextDocument(s);\n dialogprint(QApplication::focusWidget(),d);\n return \"\";\n}\n#endif\n\n\/\/ ---------------------------------------------------------------------\nQString mbprintx(bool iftext)\n{\n QString s=arg.at(0);\n if (!iftext) {\n if (!cfexist(s)) {\n mbinfo(\"File not found: \" + s);\n return \"\";\n }\n s=cfread(s);\n }\n QTextDocument *d=new QTextDocument(s);\n QPrinter printer(QPrinter::HighResolution);\n d->print(&printer);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbsave()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"save needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=fixsep(arg.at(2));\n return QFileDialog::getSaveFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString getname(int b)\n{\n if (b==QMessageBox::Ok)\n return \"ok\";\n if (b==QMessageBox::Cancel)\n return \"cancel\";\n if (b==QMessageBox::Yes)\n return \"yes\";\n if (b==QMessageBox::No)\n return \"no\";\n if (b==QMessageBox::Save)\n return \"save\";\n if (b==QMessageBox::Discard)\n return \"discard\";\n return \"unknown button\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getonebutton()\n{\n if (arg.isEmpty()) return QMessageBox::NoButton;\n QString s=arg.first();\n if (s==\"mb_ok\")\n return QMessageBox::Ok;\n if (s==\"mb_cancel\")\n return QMessageBox::Cancel;\n if (s==\"mb_yes\")\n return QMessageBox::Yes;\n if (s==\"mb_no\")\n return QMessageBox::No;\n if (s==\"mb_save\")\n return QMessageBox::Save;\n if (s==\"mb_discard\")\n return QMessageBox::Discard;\n return QMessageBox::NoButton;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getdefaultbutton()\n{\n QMessageBox::StandardButton r=getonebutton();\n if (r!=QMessageBox::NoButton)\n arg.removeFirst();\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButtons getotherbuttons()\n{\n QMessageBox::StandardButtons r=QMessageBox::NoButton;\n QMessageBox::StandardButton b;\n while (arg.size()) {\n b=getonebutton();\n if (b==QMessageBox::NoButton)\n return r;\n r|=b;\n arg.removeFirst();\n }\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbinfo(QString s)\n{\n info(\"Message Box\",s);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString fixsep(QString s)\n{\n return s.replace(\"|\",\";;\");\n}\n<commit_msg>fix mbprintx<commit_after>\n\/\/ the syntax for messages is:\n\/\/ wd 'mb type buttons title message'\n\/\/\n\/\/ type specifies the icon and default behaviour:\n\/\/ info (default OK button)\n\/\/ warn (default OK button)\n\/\/ critical (default OK button)\n\/\/ query (requires two or three buttons)\n\/\/\n\/\/ if one button, there is no result,\n\/\/ otherwise the result is the button name (ok, cancel, ...)\n\/\/\n\/\/ buttons are from the set:\n\/\/ mb_ok\n\/\/ mb_cancel\n\/\/ mb_yes\n\/\/ mb_no\n\/\/ mb_save\n\/\/ mb_discard\n\n#include <QApplication>\n#include <QColorDialog>\n#include <QFileDialog>\n#include <QFontDialog>\n#include <QMessageBox>\n#include <QTextDocument>\n\n#include \"wd.h\"\n#include \"cmd.h\"\n#include \"..\/base\/dialog.h\"\n\n#ifndef ANDROID\n#include <QPrinter>\n#include <QPrintDialog>\nextern QPrinter *pprinter;\n#endif\n\nQString mbcolor();\nQString mbdir();\nQString mbfont();\nQString mbinfo(QString);\n#ifndef ANDROID\nQString mbprint(bool);\nQString mbprintx(bool);\nQString mbprinter();\n#endif\nQString mbmsg();\nQString mbopen();\nQString mbsave();\n\nQString fixsep(QString s);\n\nQString type;\nQStringList arg;\n\nQMessageBox::StandardButton getdefaultbutton();\nQMessageBox::StandardButton getonebutton();\nQMessageBox::StandardButtons getotherbuttons();\nQString getname(int);\n\n\/\/ ---------------------------------------------------------------------\nQString mb(string p)\n{\n arg=qsplit(p);\n if (arg.size()<1) return mbinfo(\"missing mb type\");\n\n type=arg.first();\n arg.removeFirst();\n if (type==\"color\")\n return mbcolor();\n if (type==\"dir\")\n return mbdir();\n if (type==\"font\")\n return mbfont();\n if (type==\"open\")\n return mbopen();\n#ifndef ANDROID\n if (type==\"print\") {\n QString s=dlb(s2q(p.substr(5)));\n return mbprint('*'==s.at(0));\n }\n if (type==\"printx\") {\n QString s=dlb(s2q(p.substr(6)));\n return mbprintx('*'==s.at(0));\n }\n#endif\n if (type==\"save\")\n return mbsave();\n if (type==\"info\"||type==\"query\"||type==\"warn\"||type==\"critical\")\n return mbmsg();\n return mbinfo(\"invalid mb type: \" + type);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbmsg()\n{\n int r;\n QString t,m;\n\n QMessageBox::StandardButton button1=getdefaultbutton();\n QMessageBox::StandardButtons buttons=getotherbuttons();\n\n if (arg.size()==1) {\n t=\"Message Box\";\n m=arg.at(0);\n } else if (arg.size()==2) {\n t=arg.at(0);\n m=arg.at(1);\n } else {\n return mbinfo (\"Need title and message: \"+arg.join(\" \"));\n }\n\n if (button1==-1) {\n button1=QMessageBox::Ok;\n if (type==\"query\")\n buttons=QMessageBox::Cancel;\n }\n buttons|=button1;\n\n if (type==\"query\") {\n r=QMessageBox::question(QApplication::focusWidget(),t,m,buttons,button1);\n return getname(r);\n }\n if (type==\"critical\")\n QMessageBox::critical(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"info\")\n QMessageBox::information(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"warn\")\n QMessageBox::warning(QApplication::focusWidget(),t,m,buttons,button1);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbcolor()\n{\n QColor c;\n int r,g,b;\n\n if (arg.size()==3) {\n r=c_strtoi(q2s(arg.at(0)));\n g=c_strtoi(q2s(arg.at(1)));\n b=c_strtoi(q2s(arg.at(2)));\n c=QColor(r,g,b);\n } else\n c=Qt::white;\n c=QColorDialog::getColor(c,QApplication::focusWidget());\n if (!c.isValid()) return \"\";\n return s2q(i2s(c.red()) + \" \" + i2s(c.green()) + \" \" + i2s(c.blue()));\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbdir()\n{\n QString title,dir;\n if (arg.size()!=2)\n return mbinfo(\"dir needs title and directory\");\n title=arg.at(0);\n dir=arg.at(1);\n return QFileDialog::getExistingDirectory(\n QApplication::focusWidget(),title,dir);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbfont()\n{\n bool ok;\n QFont font, def;\n QString s;\n def.setStrikeOut(false);\n def.setUnderline(false);\n if (arg.size())\n def.setFamily(arg.at(0));\n if (arg.size()>1)\n def.setPointSize(arg.at(1).toFloat());\n for (int i=2; i<arg.size(); i++) {\n s=arg.at(i);\n if (s==\"bold\")\n def.setBold(true);\n if (s==\"italic\")\n def.setItalic(true);\n if (s==\"strikeout\")\n def.setStrikeOut(true);\n if (s==\"underline\")\n def.setUnderline(true);\n }\n font=QFontDialog::getFont(&ok,def,QApplication::focusWidget());\n if (!ok) return \"\";\n QString r;\n r=\"\\\"\" + font.family() + \"\\\" \" + QString::number(font.pointSize());\n if (font.bold()) r+=\" bold\";\n if (font.italic()) r+=\" italic\";\n if (font.strikeOut()) r+=\" strikeout\";\n if (font.underline()) r+=\" underline\";\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbopen()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"open needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=fixsep(arg.at(2));\n return QFileDialog::getOpenFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n#ifndef ANDROID\n\/\/ ---------------------------------------------------------------------\nQString mbprint(bool iftext)\n{\n QString s=arg.at(0);\n if (!iftext) {\n if (!cfexist(s)) {\n mbinfo(\"File not found: \" + s);\n return \"\";\n }\n s=cfread(s);\n }\n QTextDocument *d=new QTextDocument(s);\n dialogprint(QApplication::focusWidget(),d);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\n\/\/ print with no dialog\nQString mbprintx(bool iftext)\n{\n QString s=arg.at(0);\n if (!iftext) {\n if (!cfexist(s)) {\n mbinfo(\"File not found: \" + s);\n return \"\";\n }\n s=cfread(s);\n }\n QTextDocument *d=new QTextDocument(s);\n QPrinter printer(QPrinter::HighResolution);\n d->print(&printer);\n return \"\";\n}\n#endif\n\n\/\/ ---------------------------------------------------------------------\nQString mbsave()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"save needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=fixsep(arg.at(2));\n return QFileDialog::getSaveFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString getname(int b)\n{\n if (b==QMessageBox::Ok)\n return \"ok\";\n if (b==QMessageBox::Cancel)\n return \"cancel\";\n if (b==QMessageBox::Yes)\n return \"yes\";\n if (b==QMessageBox::No)\n return \"no\";\n if (b==QMessageBox::Save)\n return \"save\";\n if (b==QMessageBox::Discard)\n return \"discard\";\n return \"unknown button\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getonebutton()\n{\n if (arg.isEmpty()) return QMessageBox::NoButton;\n QString s=arg.first();\n if (s==\"mb_ok\")\n return QMessageBox::Ok;\n if (s==\"mb_cancel\")\n return QMessageBox::Cancel;\n if (s==\"mb_yes\")\n return QMessageBox::Yes;\n if (s==\"mb_no\")\n return QMessageBox::No;\n if (s==\"mb_save\")\n return QMessageBox::Save;\n if (s==\"mb_discard\")\n return QMessageBox::Discard;\n return QMessageBox::NoButton;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getdefaultbutton()\n{\n QMessageBox::StandardButton r=getonebutton();\n if (r!=QMessageBox::NoButton)\n arg.removeFirst();\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButtons getotherbuttons()\n{\n QMessageBox::StandardButtons r=QMessageBox::NoButton;\n QMessageBox::StandardButton b;\n while (arg.size()) {\n b=getonebutton();\n if (b==QMessageBox::NoButton)\n return r;\n r|=b;\n arg.removeFirst();\n }\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbinfo(QString s)\n{\n info(\"Message Box\",s);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString fixsep(QString s)\n{\n return s.replace(\"|\",\";;\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Mapnik (c++ mapping toolkit)\n * Copyright (C) 2005 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or 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. 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, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id: style.hh 60 2004-11-04 09:40:49Z artem $\n\n#ifndef STYLE_HH\n#define STYLE_HH\n\n#include \"color.hh\"\n#include \"ptr.hh\"\n#include \"symbolizer.hh\"\n\n#include <vector>\n#include <algorithm>\n#include <functional>\n\nnamespace mapnik\n{\n \n class IsActive : public std::unary_function<ref_ptr<Symbolizer>, bool>\n {\n private:\n\tdouble scale_;\n public:\t\n\tIsActive(double scale)\n\t : scale_(scale) {}\n\tbool operator()(const ref_ptr<Symbolizer>& symbol)\n\t{\n\t return symbol->active(scale_);\n\t}\n };\n\n class Style \n {\n\ttypedef std::vector<ref_ptr<Symbolizer> >::const_iterator Iterator; \n private:\n\tstd::vector<ref_ptr<Symbolizer> > symbols_;\n\tstatic ref_ptr<Symbolizer> zero_symbol_;\n public:\n\tStyle() {}\n\n\tStyle(const ref_ptr<Symbolizer>& symbol) \n\t{\n\t symbols_.push_back(symbol);\n\t}\n\n\t~Style() {}\n\n\tStyle(const Style& rhs) \n\t : symbols_(rhs.symbols_) {}\n\t\n\tStyle& operator=(const Style& rhs)\n\t{\n\t if (this==&rhs) return *this;\n\t symbols_=rhs.symbols_;\n\t return *this;\n\t}\n\t\n\tvoid add(const ref_ptr<Symbolizer>& symbol) \n\t{\n\t symbols_.push_back(symbol);\n\t}\n \n\tIterator find(double scale) const \n\t{\n\t return std::find_if(symbols_.begin(),symbols_.end(),IsActive(scale));\n\t} \n\n\tIterator end() const \n\t{\n\t return symbols_.end();\n\t}\n }; \n}\n\n#endif \/\/STYLE_HH\n<commit_msg>public typedef to keep gcc3.3.3 happy<commit_after>\/* This file is part of Mapnik (c++ mapping toolkit)\n * Copyright (C) 2005 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or 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. 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, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n#ifndef STYLE_HH\n#define STYLE_HH\n\n#include \"color.hh\"\n#include \"ptr.hh\"\n#include \"symbolizer.hh\"\n\n#include <vector>\n#include <algorithm>\n#include <functional>\n\nnamespace mapnik\n{\n \n class IsActive : public std::unary_function<ref_ptr<Symbolizer>, bool>\n {\n private:\n\tdouble scale_;\n public:\t\n\tIsActive(double scale)\n\t : scale_(scale) {}\n\tbool operator()(const ref_ptr<Symbolizer>& symbol)\n\t{\n\t return symbol->active(scale_);\n\t}\n };\n\n class Style \n {\n private:\n\tstd::vector<ref_ptr<Symbolizer> > symbols_;\n\tstatic ref_ptr<Symbolizer> zero_symbol_;\n public:\n\ttypedef std::vector<ref_ptr<Symbolizer> >::const_iterator Iterator; \n\n\tStyle() {}\n\n\tStyle(const ref_ptr<Symbolizer>& symbol) \n\t{\n\t symbols_.push_back(symbol);\n\t}\n\n\t~Style() {}\n\n\tStyle(const Style& rhs) \n\t : symbols_(rhs.symbols_) {}\n\t\n\tStyle& operator=(const Style& rhs)\n\t{\n\t if (this==&rhs) return *this;\n\t symbols_=rhs.symbols_;\n\t return *this;\n\t}\n\t\n\tvoid add(const ref_ptr<Symbolizer>& symbol) \n\t{\n\t symbols_.push_back(symbol);\n\t}\n \n\tIterator find(double scale) const \n\t{\n\t return std::find_if(symbols_.begin(),symbols_.end(),IsActive(scale));\n\t} \n\n\tIterator end() const \n\t{\n\t return symbols_.end();\n\t}\n }; \n}\n\n#endif \/\/STYLE_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018-19 gatecat <gatecat@ds0.me>\n * Copyright (C) 2021 William D. Jones <wjones@wdj-consulting.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include <algorithm>\n#include <iterator>\n#include \"cells.h\"\n#include \"design_utils.h\"\n#include \"log.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\n\/\/ Pack LUTs and LUT-FF pairs\nstatic void pack_lut_lutffs(Context *ctx)\n{\n log_info(\"Packing LUT-FFs..\\n\");\n\n pool<IdString> packed_cells;\n std::vector<std::unique_ptr<CellInfo>> new_cells;\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (ctx->verbose)\n log_info(\"cell '%s' is of type '%s'\\n\", ci->name.c_str(ctx), ci->type.c_str(ctx));\n if (is_lut(ctx, ci)) {\n std::unique_ptr<CellInfo> packed = create_machxo2_cell(ctx, id_FACADE_SLICE, ci->name.str(ctx) + \"_LC\");\n for (auto &attr : ci->attrs)\n packed->attrs[attr.first] = attr.second;\n\n packed_cells.insert(ci->name);\n if (ctx->verbose)\n log_info(\"packed cell %s into %s\\n\", ci->name.c_str(ctx), packed->name.c_str(ctx));\n \/\/ See if we can pack into a DFF. Both LUT4 and FF outputs are\n \/\/ available for a given slice, so we can pack a FF even if the\n \/\/ LUT4 drives more than one FF.\n NetInfo *o = ci->ports.at(id_Z).net;\n CellInfo *dff = net_only_drives(ctx, o, is_ff, id_DI, false);\n auto lut_bel = ci->attrs.find(ctx->id(\"BEL\"));\n bool packed_dff = false;\n\n if (dff) {\n if (ctx->verbose)\n log_info(\"found attached dff %s\\n\", dff->name.c_str(ctx));\n auto dff_bel = dff->attrs.find(ctx->id(\"BEL\"));\n if (lut_bel != ci->attrs.end() && dff_bel != dff->attrs.end() && lut_bel->second != dff_bel->second) {\n \/\/ Locations don't match, can't pack\n } else {\n lut_to_lc(ctx, ci, packed.get(), false);\n dff_to_lc(ctx, dff, packed.get(), LutType::Normal);\n if (dff_bel != dff->attrs.end())\n packed->attrs[ctx->id(\"BEL\")] = dff_bel->second;\n packed_cells.insert(dff->name);\n if (ctx->verbose)\n log_info(\"packed cell %s into %s\\n\", dff->name.c_str(ctx), packed->name.c_str(ctx));\n packed_dff = true;\n }\n }\n if (!packed_dff) {\n lut_to_lc(ctx, ci, packed.get(), true);\n }\n new_cells.push_back(std::move(packed));\n }\n }\n\n for (auto pcell : packed_cells) {\n ctx->cells.erase(pcell);\n }\n for (auto &ncell : new_cells) {\n ctx->cells[ncell->name] = std::move(ncell);\n }\n}\n\nstatic void pack_remaining_ffs(Context *ctx)\n{\n log_info(\"Packing remaining FFs..\\n\");\n\n pool<IdString> packed_cells;\n std::vector<std::unique_ptr<CellInfo>> new_cells;\n\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n\n if (is_ff(ctx, ci)) {\n if (ctx->verbose)\n log_info(\"cell '%s' of type '%s remains unpacked'\\n\", ci->name.c_str(ctx), ci->type.c_str(ctx));\n\n std::unique_ptr<CellInfo> packed = create_machxo2_cell(ctx, id_FACADE_SLICE, ci->name.str(ctx) + \"_LC\");\n for (auto &attr : ci->attrs)\n packed->attrs[attr.first] = attr.second;\n\n auto dff_bel = ci->attrs.find(ctx->id(\"BEL\"));\n\n dff_to_lc(ctx, ci, packed.get(), LutType::None);\n\n if (dff_bel != ci->attrs.end())\n packed->attrs[ctx->id(\"BEL\")] = dff_bel->second;\n packed_cells.insert(ci->name);\n if (ctx->verbose)\n log_info(\"packed cell %s into %s\\n\", ci->name.c_str(ctx), packed->name.c_str(ctx));\n\n new_cells.push_back(std::move(packed));\n }\n }\n\n for (auto pcell : packed_cells) {\n ctx->cells.erase(pcell);\n }\n for (auto &ncell : new_cells) {\n ctx->cells[ncell->name] = std::move(ncell);\n }\n}\n\n\/\/ Merge a net into a constant net\nstatic void set_net_constant(Context *ctx, NetInfo *orig, NetInfo *constnet, bool constval)\n{\n (void)constval;\n\n pool<IdString> packed_cells;\n std::vector<std::unique_ptr<CellInfo>> new_cells;\n\n orig->driver.cell = nullptr;\n for (auto user : orig->users) {\n if (user.cell != nullptr) {\n CellInfo *uc = user.cell;\n if (ctx->verbose)\n log_info(\"%s user %s\\n\", orig->name.c_str(ctx), uc->name.c_str(ctx));\n\n if (uc->type == id_FACADE_FF && user.port == id_DI) {\n log_info(\"FACADE_FF %s is driven by a constant\\n\", uc->name.c_str(ctx));\n\n std::unique_ptr<CellInfo> lc = create_machxo2_cell(ctx, id_FACADE_SLICE, uc->name.str(ctx) + \"_CONST\");\n for (auto &attr : uc->attrs)\n lc->attrs[attr.first] = attr.second;\n\n dff_to_lc(ctx, uc, lc.get(), LutType::PassThru);\n packed_cells.insert(uc->name);\n\n lc->ports[id_A0].net = constnet;\n user.cell = lc.get();\n user.port = id_A0;\n\n new_cells.push_back(std::move(lc));\n } else {\n uc->ports[user.port].net = constnet;\n }\n\n constnet->users.push_back(user);\n }\n }\n orig->users.clear();\n\n for (auto pcell : packed_cells) {\n ctx->cells.erase(pcell);\n }\n for (auto &ncell : new_cells) {\n ctx->cells[ncell->name] = std::move(ncell);\n }\n}\n\n\/\/ Pack constants (based on simple implementation in generic).\n\/\/ VCC\/GND cells provided by nextpnr automatically.\nstatic void pack_constants(Context *ctx)\n{\n log_info(\"Packing constants..\\n\");\n\n std::unique_ptr<CellInfo> const_cell = create_machxo2_cell(ctx, id_FACADE_SLICE, \"$PACKER_CONST\");\n const_cell->params[id_LUT0_INITVAL] = Property(0, 16);\n const_cell->params[id_LUT1_INITVAL] = Property(0xFFFF, 16);\n\n std::unique_ptr<NetInfo> gnd_net = std::unique_ptr<NetInfo>(new NetInfo);\n gnd_net->name = ctx->id(\"$PACKER_GND_NET\");\n gnd_net->driver.cell = const_cell.get();\n gnd_net->driver.port = id_F0;\n const_cell->ports.at(id_F0).net = gnd_net.get();\n\n std::unique_ptr<NetInfo> vcc_net = std::unique_ptr<NetInfo>(new NetInfo);\n vcc_net->name = ctx->id(\"$PACKER_VCC_NET\");\n vcc_net->driver.cell = const_cell.get();\n vcc_net->driver.port = id_F1;\n const_cell->ports.at(id_F1).net = vcc_net.get();\n\n std::vector<IdString> dead_nets;\n\n for (auto &net : ctx->nets) {\n NetInfo *ni = net.second.get();\n if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id(\"GND\")) {\n IdString drv_cell = ni->driver.cell->name;\n set_net_constant(ctx, ni, gnd_net.get(), false);\n dead_nets.push_back(net.first);\n ctx->cells.erase(drv_cell);\n } else if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id(\"VCC\")) {\n IdString drv_cell = ni->driver.cell->name;\n set_net_constant(ctx, ni, vcc_net.get(), true);\n dead_nets.push_back(net.first);\n ctx->cells.erase(drv_cell);\n }\n }\n\n ctx->cells[const_cell->name] = std::move(const_cell);\n ctx->nets[gnd_net->name] = std::move(gnd_net);\n ctx->nets[vcc_net->name] = std::move(vcc_net);\n\n for (auto dn : dead_nets) {\n ctx->nets.erase(dn);\n }\n}\n\nstatic bool is_nextpnr_iob(Context *ctx, CellInfo *cell)\n{\n return cell->type == ctx->id(\"$nextpnr_ibuf\") || cell->type == ctx->id(\"$nextpnr_obuf\") ||\n cell->type == ctx->id(\"$nextpnr_iobuf\");\n}\n\nstatic bool is_facade_iob(const Context *ctx, const CellInfo *cell) { return cell->type == id_FACADE_IO; }\n\n\/\/ Pack IO buffers- Right now, all this does is remove $nextpnr_[io]buf cells.\n\/\/ User is expected to manually instantiate FACADE_IO with BEL\/IO_TYPE\n\/\/ attributes.\nstatic void pack_io(Context *ctx)\n{\n pool<IdString> packed_cells;\n\n log_info(\"Packing IOs..\\n\");\n\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (is_nextpnr_iob(ctx, ci)) {\n for (auto &p : ci->ports)\n disconnect_port(ctx, ci, p.first);\n packed_cells.insert(ci->name);\n } else if (is_facade_iob(ctx, ci)) {\n \/\/ If FACADE_IO has LOC attribute, convert the LOC (pin) to a BEL\n \/\/ attribute and place FACADE_IO at resulting BEL location. A BEL\n \/\/ attribute already on a FACADE_IO is an error. Attributes on\n \/\/ the pin attached to the PAD of FACADE_IO are ignored by this\n \/\/ packing phase.\n auto loc_attr_cell = ci->attrs.find(ctx->id(\"LOC\"));\n auto bel_attr_cell = ci->attrs.find(ctx->id(\"BEL\"));\n\n if (loc_attr_cell != ci->attrs.end()) {\n if (bel_attr_cell != ci->attrs.end()) {\n log_error(\"IO buffer %s has both a BEL attribute and LOC attribute.\\n\", ci->name.c_str(ctx));\n }\n\n log_info(\"found LOC attribute on IO buffer %s.\\n\", ci->name.c_str(ctx));\n std::string pin = loc_attr_cell->second.as_string();\n\n BelId pinBel = ctx->getPackagePinBel(pin);\n if (pinBel == BelId()) {\n log_error(\"IO buffer '%s' constrained to pin '%s', which does not exist for package '%s'.\\n\",\n ci->name.c_str(ctx), pin.c_str(), ctx->args.package.c_str());\n } else {\n log_info(\"pin '%s' constrained to Bel '%s'.\\n\", ci->name.c_str(ctx), ctx->nameOfBel(pinBel));\n }\n ci->attrs[ctx->id(\"BEL\")] = ctx->getBelName(pinBel).str(ctx);\n }\n }\n }\n\n for (auto pcell : packed_cells) {\n ctx->cells.erase(pcell);\n }\n}\n\n\/\/ Main pack function\nbool Arch::pack()\n{\n Context *ctx = getCtx();\n try {\n log_break();\n pack_constants(ctx);\n pack_io(ctx);\n pack_lut_lutffs(ctx);\n pack_remaining_ffs(ctx);\n ctx->settings[ctx->id(\"pack\")] = 1;\n ctx->assignArchInfo();\n log_info(\"Checksum: 0x%08x\\n\", ctx->checksum());\n return true;\n } catch (log_execution_error_exception) {\n return false;\n }\n}\n\nNEXTPNR_NAMESPACE_END\n<commit_msg>machxo2: Add packing logic to forbid designs lacking FACADE_IO top-level ports.<commit_after>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018-19 gatecat <gatecat@ds0.me>\n * Copyright (C) 2021 William D. Jones <wjones@wdj-consulting.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include <algorithm>\n#include <iterator>\n#include \"cells.h\"\n#include \"design_utils.h\"\n#include \"log.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\n\/\/ Pack LUTs and LUT-FF pairs\nstatic void pack_lut_lutffs(Context *ctx)\n{\n log_info(\"Packing LUT-FFs..\\n\");\n\n pool<IdString> packed_cells;\n std::vector<std::unique_ptr<CellInfo>> new_cells;\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (ctx->verbose)\n log_info(\"cell '%s' is of type '%s'\\n\", ci->name.c_str(ctx), ci->type.c_str(ctx));\n if (is_lut(ctx, ci)) {\n std::unique_ptr<CellInfo> packed = create_machxo2_cell(ctx, id_FACADE_SLICE, ci->name.str(ctx) + \"_LC\");\n for (auto &attr : ci->attrs)\n packed->attrs[attr.first] = attr.second;\n\n packed_cells.insert(ci->name);\n if (ctx->verbose)\n log_info(\"packed cell %s into %s\\n\", ci->name.c_str(ctx), packed->name.c_str(ctx));\n \/\/ See if we can pack into a DFF. Both LUT4 and FF outputs are\n \/\/ available for a given slice, so we can pack a FF even if the\n \/\/ LUT4 drives more than one FF.\n NetInfo *o = ci->ports.at(id_Z).net;\n CellInfo *dff = net_only_drives(ctx, o, is_ff, id_DI, false);\n auto lut_bel = ci->attrs.find(ctx->id(\"BEL\"));\n bool packed_dff = false;\n\n if (dff) {\n if (ctx->verbose)\n log_info(\"found attached dff %s\\n\", dff->name.c_str(ctx));\n auto dff_bel = dff->attrs.find(ctx->id(\"BEL\"));\n if (lut_bel != ci->attrs.end() && dff_bel != dff->attrs.end() && lut_bel->second != dff_bel->second) {\n \/\/ Locations don't match, can't pack\n } else {\n lut_to_lc(ctx, ci, packed.get(), false);\n dff_to_lc(ctx, dff, packed.get(), LutType::Normal);\n if (dff_bel != dff->attrs.end())\n packed->attrs[ctx->id(\"BEL\")] = dff_bel->second;\n packed_cells.insert(dff->name);\n if (ctx->verbose)\n log_info(\"packed cell %s into %s\\n\", dff->name.c_str(ctx), packed->name.c_str(ctx));\n packed_dff = true;\n }\n }\n if (!packed_dff) {\n lut_to_lc(ctx, ci, packed.get(), true);\n }\n new_cells.push_back(std::move(packed));\n }\n }\n\n for (auto pcell : packed_cells) {\n ctx->cells.erase(pcell);\n }\n for (auto &ncell : new_cells) {\n ctx->cells[ncell->name] = std::move(ncell);\n }\n}\n\nstatic void pack_remaining_ffs(Context *ctx)\n{\n log_info(\"Packing remaining FFs..\\n\");\n\n pool<IdString> packed_cells;\n std::vector<std::unique_ptr<CellInfo>> new_cells;\n\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n\n if (is_ff(ctx, ci)) {\n if (ctx->verbose)\n log_info(\"cell '%s' of type '%s remains unpacked'\\n\", ci->name.c_str(ctx), ci->type.c_str(ctx));\n\n std::unique_ptr<CellInfo> packed = create_machxo2_cell(ctx, id_FACADE_SLICE, ci->name.str(ctx) + \"_LC\");\n for (auto &attr : ci->attrs)\n packed->attrs[attr.first] = attr.second;\n\n auto dff_bel = ci->attrs.find(ctx->id(\"BEL\"));\n\n dff_to_lc(ctx, ci, packed.get(), LutType::None);\n\n if (dff_bel != ci->attrs.end())\n packed->attrs[ctx->id(\"BEL\")] = dff_bel->second;\n packed_cells.insert(ci->name);\n if (ctx->verbose)\n log_info(\"packed cell %s into %s\\n\", ci->name.c_str(ctx), packed->name.c_str(ctx));\n\n new_cells.push_back(std::move(packed));\n }\n }\n\n for (auto pcell : packed_cells) {\n ctx->cells.erase(pcell);\n }\n for (auto &ncell : new_cells) {\n ctx->cells[ncell->name] = std::move(ncell);\n }\n}\n\n\/\/ Merge a net into a constant net\nstatic void set_net_constant(Context *ctx, NetInfo *orig, NetInfo *constnet, bool constval)\n{\n (void)constval;\n\n pool<IdString> packed_cells;\n std::vector<std::unique_ptr<CellInfo>> new_cells;\n\n orig->driver.cell = nullptr;\n for (auto user : orig->users) {\n if (user.cell != nullptr) {\n CellInfo *uc = user.cell;\n if (ctx->verbose)\n log_info(\"%s user %s\\n\", orig->name.c_str(ctx), uc->name.c_str(ctx));\n\n if (uc->type == id_FACADE_FF && user.port == id_DI) {\n log_info(\"FACADE_FF %s is driven by a constant\\n\", uc->name.c_str(ctx));\n\n std::unique_ptr<CellInfo> lc = create_machxo2_cell(ctx, id_FACADE_SLICE, uc->name.str(ctx) + \"_CONST\");\n for (auto &attr : uc->attrs)\n lc->attrs[attr.first] = attr.second;\n\n dff_to_lc(ctx, uc, lc.get(), LutType::PassThru);\n packed_cells.insert(uc->name);\n\n lc->ports[id_A0].net = constnet;\n user.cell = lc.get();\n user.port = id_A0;\n\n new_cells.push_back(std::move(lc));\n } else {\n uc->ports[user.port].net = constnet;\n }\n\n constnet->users.push_back(user);\n }\n }\n orig->users.clear();\n\n for (auto pcell : packed_cells) {\n ctx->cells.erase(pcell);\n }\n for (auto &ncell : new_cells) {\n ctx->cells[ncell->name] = std::move(ncell);\n }\n}\n\n\/\/ Pack constants (based on simple implementation in generic).\n\/\/ VCC\/GND cells provided by nextpnr automatically.\nstatic void pack_constants(Context *ctx)\n{\n log_info(\"Packing constants..\\n\");\n\n std::unique_ptr<CellInfo> const_cell = create_machxo2_cell(ctx, id_FACADE_SLICE, \"$PACKER_CONST\");\n const_cell->params[id_LUT0_INITVAL] = Property(0, 16);\n const_cell->params[id_LUT1_INITVAL] = Property(0xFFFF, 16);\n\n std::unique_ptr<NetInfo> gnd_net = std::unique_ptr<NetInfo>(new NetInfo);\n gnd_net->name = ctx->id(\"$PACKER_GND_NET\");\n gnd_net->driver.cell = const_cell.get();\n gnd_net->driver.port = id_F0;\n const_cell->ports.at(id_F0).net = gnd_net.get();\n\n std::unique_ptr<NetInfo> vcc_net = std::unique_ptr<NetInfo>(new NetInfo);\n vcc_net->name = ctx->id(\"$PACKER_VCC_NET\");\n vcc_net->driver.cell = const_cell.get();\n vcc_net->driver.port = id_F1;\n const_cell->ports.at(id_F1).net = vcc_net.get();\n\n std::vector<IdString> dead_nets;\n\n for (auto &net : ctx->nets) {\n NetInfo *ni = net.second.get();\n if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id(\"GND\")) {\n IdString drv_cell = ni->driver.cell->name;\n set_net_constant(ctx, ni, gnd_net.get(), false);\n dead_nets.push_back(net.first);\n ctx->cells.erase(drv_cell);\n } else if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id(\"VCC\")) {\n IdString drv_cell = ni->driver.cell->name;\n set_net_constant(ctx, ni, vcc_net.get(), true);\n dead_nets.push_back(net.first);\n ctx->cells.erase(drv_cell);\n }\n }\n\n ctx->cells[const_cell->name] = std::move(const_cell);\n ctx->nets[gnd_net->name] = std::move(gnd_net);\n ctx->nets[vcc_net->name] = std::move(vcc_net);\n\n for (auto dn : dead_nets) {\n ctx->nets.erase(dn);\n }\n}\n\nstatic bool is_nextpnr_iob(Context *ctx, CellInfo *cell)\n{\n return cell->type == ctx->id(\"$nextpnr_ibuf\") || cell->type == ctx->id(\"$nextpnr_obuf\") ||\n cell->type == ctx->id(\"$nextpnr_iobuf\");\n}\n\nstatic bool is_facade_iob(const Context *ctx, const CellInfo *cell) { return cell->type == id_FACADE_IO; }\n\nstatic bool nextpnr_iob_connects_only_facade_iob(Context *ctx, CellInfo *iob, NetInfo *&top) {\n NPNR_ASSERT(is_nextpnr_iob(ctx, iob));\n\n if(iob->type == ctx->id(\"$nextpnr_ibuf\")) {\n NetInfo *o = iob->ports.at(id_O).net;\n top = o;\n\n CellInfo *fio = net_only_drives(ctx, o, is_facade_iob, id_PAD, true);\n return fio != nullptr;\n } else if(iob->type == ctx->id(\"$nextpnr_obuf\")) {\n NetInfo *i = iob->ports.at(id_I).net;\n top = i;\n\n \/\/ If connected to a FACADE_IO PAD, the net attached to an I port of an\n \/\/ $nextpnr_obuf will not have a driver, only users; an inout port\n \/\/ like PAD cannot be a driver in nextpnr. So net_driven_by won't\n \/\/ return anything. We exclude the IOB as one of the two users because\n \/\/ we already know that the net drives the $nextpnr_obuf.\n CellInfo *fio = net_only_drives(ctx, i, is_facade_iob, id_PAD, true, iob);\n return fio != nullptr;\n } else if(iob->type == ctx->id(\"$nextpnr_iobuf\")) {\n NetInfo *o = iob->ports.at(id_O).net;\n top = o;\n\n \/\/ When split_io is enabled in a frontend (it is for JSON), the I and O\n \/\/ ports of a $nextpnr_iobuf are split; the I port connects to the\n \/\/ driver of the original net before IOB insertion, and the O port\n \/\/ connects everything else. Because FACADE_IO PADs cannot be a driver\n \/\/ in nextpnr, the we can safely ignore the I port of an $nextpnr_iobuf\n \/\/ for any JSON input we're interested in accepting.\n CellInfo *fio_o = net_only_drives(ctx, o, is_facade_iob, id_PAD, true);\n return fio_o != nullptr;\n }\n\n \/\/ Unreachable!\n NPNR_ASSERT(false);\n}\n\n\/\/ Pack IO buffers- Right now, all this does is remove $nextpnr_[io]buf cells.\n\/\/ User is expected to manually instantiate FACADE_IO with BEL\/IO_TYPE\n\/\/ attributes.\nstatic void pack_io(Context *ctx)\n{\n pool<IdString> packed_cells;\n\n log_info(\"Packing IOs..\\n\");\n\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (is_nextpnr_iob(ctx, ci)) {\n NetInfo *top;\n\n if(!nextpnr_iob_connects_only_facade_iob(ctx, ci, top))\n log_error(\"Top level net '%s' is not connected to a FACADE_IO PAD port.\\n\", top->name.c_str(ctx));\n\n if (ctx->verbose)\n log_info(\"Removing top-level IOBUF '%s' of type '%s'\\n\", ci->name.c_str(ctx), ci->type.c_str(ctx));\n\n for (auto &p : ci->ports)\n disconnect_port(ctx, ci, p.first);\n packed_cells.insert(ci->name);\n } else if (is_facade_iob(ctx, ci)) {\n \/\/ If FACADE_IO has LOC attribute, convert the LOC (pin) to a BEL\n \/\/ attribute and place FACADE_IO at resulting BEL location. A BEL\n \/\/ attribute already on a FACADE_IO is an error. Attributes on\n \/\/ the pin attached to the PAD of FACADE_IO are ignored by this\n \/\/ packing phase.\n auto loc_attr_cell = ci->attrs.find(ctx->id(\"LOC\"));\n auto bel_attr_cell = ci->attrs.find(ctx->id(\"BEL\"));\n\n if (loc_attr_cell != ci->attrs.end()) {\n if (bel_attr_cell != ci->attrs.end()) {\n log_error(\"IO buffer %s has both a BEL attribute and LOC attribute.\\n\", ci->name.c_str(ctx));\n }\n\n log_info(\"found LOC attribute on IO buffer %s.\\n\", ci->name.c_str(ctx));\n std::string pin = loc_attr_cell->second.as_string();\n\n BelId pinBel = ctx->getPackagePinBel(pin);\n if (pinBel == BelId()) {\n log_error(\"IO buffer '%s' constrained to pin '%s', which does not exist for package '%s'.\\n\",\n ci->name.c_str(ctx), pin.c_str(), ctx->args.package.c_str());\n } else {\n log_info(\"pin '%s' constrained to Bel '%s'.\\n\", ci->name.c_str(ctx), ctx->nameOfBel(pinBel));\n }\n ci->attrs[ctx->id(\"BEL\")] = ctx->getBelName(pinBel).str(ctx);\n }\n }\n }\n\n for (auto pcell : packed_cells) {\n ctx->cells.erase(pcell);\n }\n}\n\n\/\/ Main pack function\nbool Arch::pack()\n{\n Context *ctx = getCtx();\n try {\n log_break();\n pack_constants(ctx);\n pack_io(ctx);\n pack_lut_lutffs(ctx);\n pack_remaining_ffs(ctx);\n ctx->settings[ctx->id(\"pack\")] = 1;\n ctx->assignArchInfo();\n log_info(\"Checksum: 0x%08x\\n\", ctx->checksum());\n return true;\n } catch (log_execution_error_exception) {\n return false;\n }\n}\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"sync.h\"\n\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include <stdio.h>\n\n#include <boost\/foreach.hpp>\n#include <boost\/thread.hpp>\n\n#ifdef DEBUG_LOCKCONTENTION\nvoid PrintLockContention(const char* pszName, const char* pszFile, int nLine)\n{\n LogPrintf(\"LOCKCONTENTION: %s\\n\", pszName);\n LogPrintf(\"Locker: %s:%d\\n\", pszFile, nLine);\n}\n#endif \/* DEBUG_LOCKCONTENTION *\/\n\n#ifdef DEBUG_LOCKORDER\n\/\/\n\/\/ Early deadlock detection.\n\/\/ Problem being solved:\n\/\/ Thread 1 locks A, then B, then C\n\/\/ Thread 2 locks D, then C, then A\n\/\/ --> may result in deadlock between the two threads, depending on when they run.\n\/\/ Solution implemented here:\n\/\/ Keep track of pairs of locks: (A before B), (A before C), etc.\n\/\/ Complain if any thread tries to lock in a different order.\n\/\/\n\nstruct CLockLocation {\n CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)\n {\n mutexName = pszName;\n sourceFile = pszFile;\n sourceLine = nLine;\n fTry = fTryIn;\n }\n\n std::string ToString() const\n {\n return mutexName + \" \" + sourceFile + \":\" + itostr(sourceLine) + (fTry ? \" (TRY)\" : \"\");\n }\n\n std::string MutexName() const { return mutexName; }\n\n bool fTry;\nprivate:\n std::string mutexName;\n std::string sourceFile;\n int sourceLine;\n};\n\ntypedef std::vector<std::pair<void*, CLockLocation> > LockStack;\ntypedef std::map<std::pair<void*, void*>, LockStack> LockOrders;\ntypedef std::set<std::pair<void*, void*> > InvLockOrders;\n\nstruct LockData {\n \/\/ Very ugly hack: as the global constructs and destructors run single\n \/\/ threaded, we use this boolean to know whether LockData still exists,\n \/\/ as DeleteLock can get called by global CCriticalSection destructors\n \/\/ after LockData disappears.\n bool available;\n LockData() : available(true) {}\n ~LockData() { available = false; }\n\n LockOrders lockorders;\n InvLockOrders invlockorders;\n boost::mutex dd_mutex;\n} static lockdata;\n\nboost::thread_specific_ptr<LockStack> lockstack;\n\nstatic void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)\n{\n \/\/ We attempt to not assert on probably-not deadlocks by assuming that\n \/\/ a try lock will immediately have otherwise bailed if it had\n \/\/ failed to get the lock\n \/\/ We do this by, for the locks which triggered the potential deadlock,\n \/\/ in either lockorder, checking that the second of the two which is locked\n \/\/ is only a TRY_LOCK, ignoring locks if they are reentrant.\n bool firstLocked = false;\n bool secondLocked = false;\n bool onlyMaybeDeadlock = false;\n\n LogPrintf(\"POTENTIAL DEADLOCK DETECTED\\n\");\n LogPrintf(\"Previous lock order was:\\n\");\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s2) {\n if (i.first == mismatch.first) {\n LogPrintf(\" (1)\");\n if (!firstLocked && secondLocked && i.second.fTry)\n onlyMaybeDeadlock = true;\n firstLocked = true;\n }\n if (i.first == mismatch.second) {\n LogPrintf(\" (2)\");\n if (!secondLocked && firstLocked && i.second.fTry)\n onlyMaybeDeadlock = true;\n secondLocked = true;\n }\n LogPrintf(\" %s\\n\", i.second.ToString());\n }\n firstLocked = false;\n secondLocked = false;\n LogPrintf(\"Current lock order is:\\n\");\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s1) {\n if (i.first == mismatch.first) {\n LogPrintf(\" (1)\");\n if (!firstLocked && secondLocked && i.second.fTry)\n onlyMaybeDeadlock = true;\n firstLocked = true;\n }\n if (i.first == mismatch.second) {\n LogPrintf(\" (2)\");\n if (!secondLocked && firstLocked && i.second.fTry)\n onlyMaybeDeadlock = true;\n secondLocked = true;\n }\n LogPrintf(\" %s\\n\", i.second.ToString());\n }\n assert(onlyMaybeDeadlock);\n}\n\nstatic void push_lock(void* c, const CLockLocation& locklocation, bool fTry)\n{\n if (lockstack.get() == NULL)\n lockstack.reset(new LockStack);\n\n boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);\n\n (*lockstack).push_back(std::make_pair(c, locklocation));\n\n if (!fTry) {\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, (*lockstack)) {\n if (i.first == c)\n break;\n\n std::pair<void*, void*> p1 = std::make_pair(i.first, c);\n if (lockdata.lockorders.count(p1))\n continue;\n lockdata.lockorders[p1] = (*lockstack);\n\n std::pair<void*, void*> p2 = std::make_pair(c, i.first);\n lockdata.invlockorders.insert(p2);\n if (lockdata.lockorders.count(p2))\n potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);\n }\n }\n}\n\nstatic void pop_lock()\n{\n (*lockstack).pop_back();\n}\n\nvoid EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)\n{\n push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);\n}\n\nvoid LeaveCritical()\n{\n pop_lock();\n}\n\nstd::string LocksHeld()\n{\n std::string result;\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)\n result += i.second.ToString() + std::string(\"\\n\");\n return result;\n}\n\nvoid AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)\n{\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)\n if (i.first == cs)\n return;\n fprintf(stderr, \"Assertion failed: lock %s not held in %s:%i; locks held:\\n%s\", pszName, pszFile, nLine, LocksHeld().c_str());\n abort();\n}\n\nvoid DeleteLock(void* cs)\n{\n if (!lockdata.available) {\n \/\/ We're already shutting down.\n return;\n }\n boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);\n std::pair<void*, void*> item = std::make_pair(cs, (void*)0);\n LockOrders::iterator it = lockdata.lockorders.lower_bound(item);\n while (it != lockdata.lockorders.end() && it->first.first == cs) {\n std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);\n lockdata.invlockorders.erase(invitem);\n lockdata.lockorders.erase(it++);\n }\n InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);\n while (invit != lockdata.invlockorders.end() && invit->first == cs) {\n std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);\n lockdata.lockorders.erase(invinvitem);\n lockdata.invlockorders.erase(invit++);\n }\n}\n\n#endif \/* DEBUG_LOCKORDER *\/\n<commit_msg>Always enforce lock strict lock ordering (try or not)<commit_after>\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"sync.h\"\n\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include <stdio.h>\n\n#include <boost\/foreach.hpp>\n#include <boost\/thread.hpp>\n\n#ifdef DEBUG_LOCKCONTENTION\nvoid PrintLockContention(const char* pszName, const char* pszFile, int nLine)\n{\n LogPrintf(\"LOCKCONTENTION: %s\\n\", pszName);\n LogPrintf(\"Locker: %s:%d\\n\", pszFile, nLine);\n}\n#endif \/* DEBUG_LOCKCONTENTION *\/\n\n#ifdef DEBUG_LOCKORDER\n\/\/\n\/\/ Early deadlock detection.\n\/\/ Problem being solved:\n\/\/ Thread 1 locks A, then B, then C\n\/\/ Thread 2 locks D, then C, then A\n\/\/ --> may result in deadlock between the two threads, depending on when they run.\n\/\/ Solution implemented here:\n\/\/ Keep track of pairs of locks: (A before B), (A before C), etc.\n\/\/ Complain if any thread tries to lock in a different order.\n\/\/\n\nstruct CLockLocation {\n CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)\n {\n mutexName = pszName;\n sourceFile = pszFile;\n sourceLine = nLine;\n fTry = fTryIn;\n }\n\n std::string ToString() const\n {\n return mutexName + \" \" + sourceFile + \":\" + itostr(sourceLine) + (fTry ? \" (TRY)\" : \"\");\n }\n\n std::string MutexName() const { return mutexName; }\n\n bool fTry;\nprivate:\n std::string mutexName;\n std::string sourceFile;\n int sourceLine;\n};\n\ntypedef std::vector<std::pair<void*, CLockLocation> > LockStack;\ntypedef std::map<std::pair<void*, void*>, LockStack> LockOrders;\ntypedef std::set<std::pair<void*, void*> > InvLockOrders;\n\nstruct LockData {\n \/\/ Very ugly hack: as the global constructs and destructors run single\n \/\/ threaded, we use this boolean to know whether LockData still exists,\n \/\/ as DeleteLock can get called by global CCriticalSection destructors\n \/\/ after LockData disappears.\n bool available;\n LockData() : available(true) {}\n ~LockData() { available = false; }\n\n LockOrders lockorders;\n InvLockOrders invlockorders;\n boost::mutex dd_mutex;\n} static lockdata;\n\nboost::thread_specific_ptr<LockStack> lockstack;\n\nstatic void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)\n{\n LogPrintf(\"POTENTIAL DEADLOCK DETECTED\\n\");\n LogPrintf(\"Previous lock order was:\\n\");\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s2) {\n if (i.first == mismatch.first) {\n LogPrintf(\" (1)\");\n }\n if (i.first == mismatch.second) {\n LogPrintf(\" (2)\");\n }\n LogPrintf(\" %s\\n\", i.second.ToString());\n }\n LogPrintf(\"Current lock order is:\\n\");\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s1) {\n if (i.first == mismatch.first) {\n LogPrintf(\" (1)\");\n }\n if (i.first == mismatch.second) {\n LogPrintf(\" (2)\");\n }\n LogPrintf(\" %s\\n\", i.second.ToString());\n }\n assert(false);\n}\n\nstatic void push_lock(void* c, const CLockLocation& locklocation, bool fTry)\n{\n if (lockstack.get() == NULL)\n lockstack.reset(new LockStack);\n\n boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);\n\n (*lockstack).push_back(std::make_pair(c, locklocation));\n\n if (!fTry) {\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, (*lockstack)) {\n if (i.first == c)\n break;\n\n std::pair<void*, void*> p1 = std::make_pair(i.first, c);\n if (lockdata.lockorders.count(p1))\n continue;\n lockdata.lockorders[p1] = (*lockstack);\n\n std::pair<void*, void*> p2 = std::make_pair(c, i.first);\n lockdata.invlockorders.insert(p2);\n if (lockdata.lockorders.count(p2))\n potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);\n }\n }\n}\n\nstatic void pop_lock()\n{\n (*lockstack).pop_back();\n}\n\nvoid EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)\n{\n push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);\n}\n\nvoid LeaveCritical()\n{\n pop_lock();\n}\n\nstd::string LocksHeld()\n{\n std::string result;\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)\n result += i.second.ToString() + std::string(\"\\n\");\n return result;\n}\n\nvoid AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)\n{\n BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)\n if (i.first == cs)\n return;\n fprintf(stderr, \"Assertion failed: lock %s not held in %s:%i; locks held:\\n%s\", pszName, pszFile, nLine, LocksHeld().c_str());\n abort();\n}\n\nvoid DeleteLock(void* cs)\n{\n if (!lockdata.available) {\n \/\/ We're already shutting down.\n return;\n }\n boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);\n std::pair<void*, void*> item = std::make_pair(cs, (void*)0);\n LockOrders::iterator it = lockdata.lockorders.lower_bound(item);\n while (it != lockdata.lockorders.end() && it->first.first == cs) {\n std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);\n lockdata.invlockorders.erase(invitem);\n lockdata.lockorders.erase(it++);\n }\n InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);\n while (invit != lockdata.invlockorders.end() && invit->first == cs) {\n std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);\n lockdata.lockorders.erase(invinvitem);\n lockdata.invlockorders.erase(invit++);\n }\n}\n\n#endif \/* DEBUG_LOCKORDER *\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @author Andrew Stone <a@stoney.io>\n * @copyright 2015 Andrew Stone\n *\n * This file is part of paratec and is released under the MIT License:\n * http:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#include \"test.hpp\"\n\nnamespace pt\n{\n\nsp<const Test> Test::bindTo(int64_t i, sp<const Opts> opts) const\n{\n\tvoid *vitem = this->vec_ == nullptr ? nullptr : ((char *)this->vec_);\n\tauto test = mksp<Test>(static_cast<const _paratec &>(*this), i, vitem);\n\n\ttest->opts_ = std::move(opts);\n\tconst auto &filts = test->opts_->filter_.filts_;\n\n\t\/\/ By default, not disabled. Once matched in a negative filter, however,\n\t\/\/ can't be re-enabled.\n\tbool disabled = false;\n\n\t\/\/ If there are no filters, everything is enabled.\n\tbool enabled = filts.size() == 0;\n\n\t\/\/ Every test becomes disabled by default if a single positive filter is\n\t\/\/ given. Only things that pass the filter run.\n\tbool hasPosFilt = false;\n\n\tfor (const auto &f : filts) {\n\t\tbool matches = strstr(test->name(), f.c_str()) == test->name();\n\n\t\thasPosFilt |= !f.neg_;\n\t\tif (matches) {\n\t\t\tdisabled |= f.neg_;\n\t\t\tenabled |= !f.neg_;\n\t\t}\n\t}\n\n\tif (hasPosFilt) {\n\t\ttest->enabled_ = !disabled && enabled;\n\t} else {\n\t\ttest->enabled_ = !disabled;\n\t}\n\n\treturn test;\n}\n\ntime::duration Test::bench(uint32_t n) const\n{\n\ttime::point start;\n\ttime::point end;\n\n\tif (this->setup_ != NULL) {\n\t\tthis->setup_();\n\t}\n\n\tstart = time::now();\n\tthis->fn_(this->i_, n, this->vitem_);\n\tend = time::now();\n\n\tif (this->teardown_ != NULL) {\n\t\tthis->teardown_();\n\t}\n\n\treturn end - start;\n}\n\nvoid Test::run() const\n{\n\tif (this->setup_ != NULL) {\n\t\tthis->setup_();\n\t}\n\n\tthis->fn_(this->i_, 0, this->vitem_);\n\n\tif (this->teardown_ != NULL) {\n\t\tthis->teardown_();\n\t}\n}\n\nvoid Test::cleanup() const\n{\n\tif (this->cleanup_ != nullptr) {\n\t\tthis->cleanup_();\n\t}\n}\n}\n<commit_msg>Fix function name shadowing<commit_after>\/**\n * @author Andrew Stone <a@stoney.io>\n * @copyright 2015 Andrew Stone\n *\n * This file is part of paratec and is released under the MIT License:\n * http:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#include \"test.hpp\"\n\nnamespace pt\n{\n\nsp<const Test> Test::bindTo(int64_t i, sp<const Opts> opts) const\n{\n\tvoid *vitem = this->vec_ == nullptr ? nullptr : ((char *)this->vec_);\n\tauto test = mksp<Test>(static_cast<const _paratec &>(*this), i, vitem);\n\n\ttest->opts_ = std::move(opts);\n\tconst auto &filts = test->opts_->filter_.filts_;\n\n\t\/\/ By default, not disabled. Once matched in a negative filter, however,\n\t\/\/ can't be re-enabled.\n\tbool disable = false;\n\n\t\/\/ If there are no filters, everything is enabled.\n\tbool enable = filts.size() == 0;\n\n\t\/\/ Every test becomes disabled by default if a single positive filter is\n\t\/\/ given. Only things that pass the filter run.\n\tbool hasPosFilt = false;\n\n\tfor (const auto &f : filts) {\n\t\tbool matches = strstr(test->name(), f.c_str()) == test->name();\n\n\t\thasPosFilt |= !f.neg_;\n\t\tif (matches) {\n\t\t\tdisable |= f.neg_;\n\t\t\tenable |= !f.neg_;\n\t\t}\n\t}\n\n\tif (hasPosFilt) {\n\t\ttest->enabled_ = !disable && enable;\n\t} else {\n\t\ttest->enabled_ = !disable;\n\t}\n\n\treturn test;\n}\n\ntime::duration Test::bench(uint32_t n) const\n{\n\ttime::point start;\n\ttime::point end;\n\n\tif (this->setup_ != NULL) {\n\t\tthis->setup_();\n\t}\n\n\tstart = time::now();\n\tthis->fn_(this->i_, n, this->vitem_);\n\tend = time::now();\n\n\tif (this->teardown_ != NULL) {\n\t\tthis->teardown_();\n\t}\n\n\treturn end - start;\n}\n\nvoid Test::run() const\n{\n\tif (this->setup_ != NULL) {\n\t\tthis->setup_();\n\t}\n\n\tthis->fn_(this->i_, 0, this->vitem_);\n\n\tif (this->teardown_ != NULL) {\n\t\tthis->teardown_();\n\t}\n}\n\nvoid Test::cleanup() const\n{\n\tif (this->cleanup_ != nullptr) {\n\t\tthis->cleanup_();\n\t}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <new>\n#include <algorithm>\n#include <ctime>\n#include <climits>\n#include <unistd.h>\n#include <cstring>\n\n#include \"Swimd.h\"\n\nusing namespace std;\n\nvoid fillRandomly(unsigned char* seq, int seqLength, int alphabetLength);\nint * createSimpleScoreMatrix(int alphabetLength, int match, int mismatch);\nint calculateSW(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[],\n int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, int scores[]);\nint calculateGlobal(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[],\n int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, int scores[], const char*);\nvoid printInts(int a[], int aLength);\nint maximum(int a[], int aLength);\n\nint main(int argc, char * const argv[]) {\n\n char mode[32] = \"SW\"; \/\/ \"SW\", \"NW\", \"HW\" or \"OV\"\n int option;\n if (argc > 1) {\n strcpy(mode, argv[1]);\n }\n \n clock_t start, finish;\n srand(time(NULL));\n\n int alphabetLength = 4;\n int gapOpen = 11;\n int gapExt = 1;\n\n \/\/ Create random query\n int queryLength = 300;\n unsigned char query[queryLength];\n fillRandomly(query, queryLength, alphabetLength);\n\n \/\/ Create random database\n int dbLength = 5000;\n unsigned char * db[dbLength];\n int dbSeqsLengths[dbLength];\n for (int i = 0; i < dbLength; i++) {\n dbSeqsLengths[i] = 150 + rand()%200;\n db[i] = new unsigned char[dbSeqsLengths[i]];\n fillRandomly(db[i], dbSeqsLengths[i], alphabetLength);\n }\n \n \/*\n printf(\"Query:\\n\");\n for (int i = 0; i < queryLength; i++)\n printf(\"%d \", query[i]);\n printf(\"\\n\");\n\n printf(\"Database:\\n\");\n for (int i = 0; i < dbLength; i++) {\n printf(\"%d. \", i); \n for (int j = 0; j < dbSeqsLengths[i]; j++)\n printf(\"%d \", db[i][j]);\n printf(\"\\n\");\n }\n *\/\n\n \/\/ Create score matrix\n int * scoreMatrix = createSimpleScoreMatrix(alphabetLength, 2, -1);\n\n\t\n \/\/ Run Swimd\n printf(\"Starting Swimd!\\n\");\n start = clock();\n int scores[dbLength];\n int resultCode;\n if (!strcmp(mode, \"SW\")) {\n resultCode = swimdSearchDatabase(query, queryLength, db, dbLength, dbSeqsLengths, \n gapOpen, gapExt, scoreMatrix, alphabetLength, scores);\n } else {\n resultCode = swimdSearchDatabaseGlobal(query, queryLength, db, dbLength, dbSeqsLengths, \n gapOpen, gapExt, scoreMatrix, alphabetLength, scores);\n }\n finish = clock();\n double time1 = ((double)(finish-start))\/CLOCKS_PER_SEC;\n printf(\"Time: %lf\\n\", time1);\n\n if (resultCode != 0) {\n printf(\"Overflow happened!\");\n exit(0);\n }\n \/\/ Print result\n printf(\"Result: \");\n printInts(scores, dbLength);\n printf(\"Maximum: %d\\n\", maximum(scores, dbLength));\t \n\n\n \/\/ Run normal SW\n printf(\"Starting normal!\\n\");\n start = clock();\n int scores2[dbLength];\n if (!strcmp(mode, \"SW\")) {\n resultCode = calculateSW(query, queryLength, db, dbLength, dbSeqsLengths, \n gapOpen, gapExt, scoreMatrix, alphabetLength, scores2);\n } else {\n resultCode = calculateGlobal(query, queryLength, db, dbLength, dbSeqsLengths, \n gapOpen, gapExt, scoreMatrix, alphabetLength, scores2, mode);\n }\n finish = clock();\n double time2 = ((double)(finish-start))\/CLOCKS_PER_SEC;\n printf(\"Time: %lf\\n\", time2);\n\n \/\/ Print result\n printf(\"Result: \");\n printInts(scores2, dbLength);\n printf(\"Maximum: %d\\n\", maximum(scores2, dbLength));\n \t\n\n \/\/ Print differences in results (hopefully there are none!)\n printf(\"Diff: \");\n for (int i = 0; i < dbLength; i++)\n if (scores[i] != scores2[i]) {\n printf(\"%d (%d,%d) \", i, scores[i], scores2[i]);\n }\n printf(\"\\n\");\n \n printf(\"Times faster: %lf\\n\", time2\/time1);\n\n \/\/ Free allocated memory\n for (int i = 0; i < dbLength; i++) {\n delete[] db[i];\n }\n delete[] scoreMatrix;\n}\n\nvoid fillRandomly(unsigned char* seq, int seqLength, int alphabetLength) {\n for (int i = 0; i < seqLength; i++)\n seq[i] = rand() % 4;\n}\n\nint * createSimpleScoreMatrix(int alphabetLength, int match, int mismatch) {\n int * scoreMatrix = new int[alphabetLength*alphabetLength];\n for (int i = 0; i < alphabetLength; i++) {\n for (int j = 0; j < alphabetLength; j++)\n scoreMatrix[i * alphabetLength + j] = (i==j ? match : mismatch);\n }\n return scoreMatrix;\n}\n\nint calculateSW(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[],\n int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, int scores[]) { \n int prevHs[queryLength];\n int prevEs[queryLength];\n\n for (int seqIdx = 0; seqIdx < dbLength; seqIdx++) {\n int maxH = 0;\n \/\/ Initialize all values to 0\n for (int i = 0; i < queryLength; i++) {\n prevHs[i] = prevEs[i] = 0;\n }\n\t\n for (int c = 0; c < dbSeqLengths[seqIdx]; c++) {\n int uF, uH, ulH;\n uF = uH = ulH = 0;\n\n for (int r = 0; r < queryLength; r++) {\n int E = max(prevHs[r] - gapOpen, prevEs[r] - gapExt);\n int F = max(uH - gapOpen, uF - gapExt);\n int score = scoreMatrix[query[r] * alphabetLength + db[seqIdx][c]];\n int H = max(0, max(E, max(F, ulH+score)));\n maxH = max(H, maxH);\n uF = F;\n uH = H;\n ulH = prevHs[r];\n\t\t\n prevHs[r] = H;\n prevEs[r] = E;\n }\n }\n\t\n scores[seqIdx] = maxH;\n }\n\n return 0;\n}\n\nint calculateGlobal(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[],\n int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, int scores[], const char* mode) { \n int prevHs[queryLength];\n int prevEs[queryLength];\n\n const int LOWER_SCORE_BOUND = INT_MIN + gapExt;\n\n for (int seqIdx = 0; seqIdx < dbLength; seqIdx++) {\n \/\/ Initialize all values to 0\n for (int i = 0; i < queryLength; i++) {\n prevHs[i] = 0; \/\/ Or -gapOpen - i * gapExt if bounded\n prevEs[i] = LOWER_SCORE_BOUND;\n }\n int maxLastRowH = INT_MIN;\n\n int maxH; \/\/ max H in column\n for (int c = 0; c < dbSeqLengths[seqIdx]; c++) {\n int uF, uH, ulH;\n int H;\n uF = LOWER_SCORE_BOUND;\n uH = 0;\n ulH = 0; \/\/ TODO: Set it specially to zero for first cell of first column\n maxH = INT_MIN;\n\n for (int r = 0; r < queryLength; r++) {\n int E = max(prevHs[r] - gapOpen, prevEs[r] - gapExt);\n int F = max(uH - gapOpen, uF - gapExt);\n int score = scoreMatrix[query[r] * alphabetLength + db[seqIdx][c]];\n H = max(E, max(F, ulH+score));\n maxH = max(H, maxH);\n uF = F;\n uH = H;\n ulH = prevHs[r];\n\t\t\n prevHs[r] = H;\n prevEs[r] = E;\n }\n maxLastRowH = max(maxLastRowH, H);\n }\n\t\n scores[seqIdx] = max(maxLastRowH, maxH);\n }\n\n return 0;\n}\n\nvoid printInts(int a[], int aLength) {\n for (int i = 0; i < aLength; i++)\n printf(\"%d \", a[i]);\n printf(\"\\n\");\n}\n\nint maximum(int a[], int aLength) {\n int maximum = 0;\n for (int i = 0; i < aLength; i++)\n if (a[i] > maximum)\n maximum = a[i];\n return maximum;\n}\n<commit_msg>Now I have normal OV, NW and HW<commit_after>#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <new>\n#include <algorithm>\n#include <ctime>\n#include <climits>\n#include <unistd.h>\n#include <cstring>\n\n#include \"Swimd.h\"\n\nusing namespace std;\n\nvoid fillRandomly(unsigned char* seq, int seqLength, int alphabetLength);\nint * createSimpleScoreMatrix(int alphabetLength, int match, int mismatch);\nint calculateSW(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[],\n int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, int scores[]);\nint calculateGlobal(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[],\n int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, int scores[], const char*);\nvoid printInts(int a[], int aLength);\nint maximum(int a[], int aLength);\n\nint main(int argc, char * const argv[]) {\n\n char mode[32] = \"SW\"; \/\/ \"SW\", \"NW\", \"HW\" or \"OV\"\n int option;\n if (argc > 1) {\n strcpy(mode, argv[1]);\n }\n \n clock_t start, finish;\n srand(time(NULL));\n\n int alphabetLength = 4;\n int gapOpen = 11;\n int gapExt = 1;\n\n \/\/ Create random query\n int queryLength = 300;\n unsigned char query[queryLength];\n fillRandomly(query, queryLength, alphabetLength);\n\n \/\/ Create random database\n int dbLength = 500;\n unsigned char * db[dbLength];\n int dbSeqsLengths[dbLength];\n for (int i = 0; i < dbLength; i++) {\n dbSeqsLengths[i] = 150 + rand()%200;\n db[i] = new unsigned char[dbSeqsLengths[i]];\n fillRandomly(db[i], dbSeqsLengths[i], alphabetLength);\n }\n \n \/*\n printf(\"Query:\\n\");\n for (int i = 0; i < queryLength; i++)\n printf(\"%d \", query[i]);\n printf(\"\\n\");\n\n printf(\"Database:\\n\");\n for (int i = 0; i < dbLength; i++) {\n printf(\"%d. \", i); \n for (int j = 0; j < dbSeqsLengths[i]; j++)\n printf(\"%d \", db[i][j]);\n printf(\"\\n\");\n }\n *\/\n\n \/\/ Create score matrix\n int * scoreMatrix = createSimpleScoreMatrix(alphabetLength, 2, -1);\n\n\t\n \/\/ Run Swimd\n printf(\"Starting Swimd!\\n\");\n start = clock();\n int scores[dbLength];\n int resultCode;\n \/*if (!strcmp(mode, \"SW\")) {\n resultCode = swimdSearchDatabase(query, queryLength, db, dbLength, dbSeqsLengths, \n gapOpen, gapExt, scoreMatrix, alphabetLength, scores);\n } else {\n resultCode = swimdSearchDatabaseGlobal(query, queryLength, db, dbLength, dbSeqsLengths, \n gapOpen, gapExt, scoreMatrix, alphabetLength, scores);\n }*\/\n resultCode = 0;\n finish = clock();\n double time1 = ((double)(finish-start))\/CLOCKS_PER_SEC;\n printf(\"Time: %lf\\n\", time1);\n\n if (resultCode != 0) {\n printf(\"Overflow happened!\");\n exit(0);\n }\n \/\/ Print result\n printf(\"Result: \");\n printInts(scores, dbLength);\n printf(\"Maximum: %d\\n\", maximum(scores, dbLength));\t \n\n\n \/\/ Run normal SW\n printf(\"Starting normal!\\n\");\n start = clock();\n int scores2[dbLength];\n if (!strcmp(mode, \"SW\")) {\n resultCode = calculateSW(query, queryLength, db, dbLength, dbSeqsLengths, \n gapOpen, gapExt, scoreMatrix, alphabetLength, scores2);\n } else {\n resultCode = calculateGlobal(query, queryLength, db, dbLength, dbSeqsLengths, \n gapOpen, gapExt, scoreMatrix, alphabetLength, scores2, mode);\n }\n finish = clock();\n double time2 = ((double)(finish-start))\/CLOCKS_PER_SEC;\n printf(\"Time: %lf\\n\", time2);\n\n \/\/ Print result\n printf(\"Result: \");\n printInts(scores2, dbLength);\n printf(\"Maximum: %d\\n\", maximum(scores2, dbLength));\n \t\n\n \/\/ Print differences in results (hopefully there are none!)\n printf(\"Diff: \");\n for (int i = 0; i < dbLength; i++)\n if (scores[i] != scores2[i]) {\n printf(\"%d (%d,%d) \", i, scores[i], scores2[i]);\n }\n printf(\"\\n\");\n \n printf(\"Times faster: %lf\\n\", time2\/time1);\n\n \/\/ Free allocated memory\n for (int i = 0; i < dbLength; i++) {\n delete[] db[i];\n }\n delete[] scoreMatrix;\n}\n\nvoid fillRandomly(unsigned char* seq, int seqLength, int alphabetLength) {\n for (int i = 0; i < seqLength; i++)\n seq[i] = rand() % 4;\n}\n\nint * createSimpleScoreMatrix(int alphabetLength, int match, int mismatch) {\n int * scoreMatrix = new int[alphabetLength*alphabetLength];\n for (int i = 0; i < alphabetLength; i++) {\n for (int j = 0; j < alphabetLength; j++)\n scoreMatrix[i * alphabetLength + j] = (i==j ? match : mismatch);\n }\n return scoreMatrix;\n}\n\nint calculateSW(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[],\n int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, int scores[]) { \n int prevHs[queryLength];\n int prevEs[queryLength];\n\n for (int seqIdx = 0; seqIdx < dbLength; seqIdx++) {\n int maxH = 0;\n \/\/ Initialize all values to 0\n for (int i = 0; i < queryLength; i++) {\n prevHs[i] = prevEs[i] = 0;\n }\n\t\n for (int c = 0; c < dbSeqLengths[seqIdx]; c++) {\n int uF, uH, ulH;\n uF = uH = ulH = 0;\n\n for (int r = 0; r < queryLength; r++) {\n int E = max(prevHs[r] - gapOpen, prevEs[r] - gapExt);\n int F = max(uH - gapOpen, uF - gapExt);\n int score = scoreMatrix[query[r] * alphabetLength + db[seqIdx][c]];\n int H = max(0, max(E, max(F, ulH+score)));\n maxH = max(H, maxH);\n uF = F;\n uH = H;\n ulH = prevHs[r];\n\t\t\n prevHs[r] = H;\n prevEs[r] = E;\n }\n }\n\t\n scores[seqIdx] = maxH;\n }\n\n return 0;\n}\n\nint calculateGlobal(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[],\n int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, int scores[], const char* mode) { \n int prevHs[queryLength];\n int prevEs[queryLength];\n\n const int LOWER_SCORE_BOUND = INT_MIN + gapExt;\n printf(\"Mode: %s\\n\", mode);\n\n for (int seqIdx = 0; seqIdx < dbLength; seqIdx++) {\n \/\/ Initialize all values to 0\n for (int r = 0; r < queryLength; r++) {\n \/\/ Query has fixed start and end if not OV\n prevHs[r] = !strcmp(mode, \"OV\") ? 0 : -1 * gapOpen - r * gapExt;\n prevEs[r] = LOWER_SCORE_BOUND;\n }\n int maxLastRowH = INT_MIN;\n\n int maxH; \/\/ max H in column\n int H;\n for (int c = 0; c < dbSeqLengths[seqIdx]; c++) {\n int uF, uH, ulH;\n uF = LOWER_SCORE_BOUND;\n if (!strcmp(mode, \"NW\")) { \/\/ Database sequence has fixed start and end only in NW\n uH = -1 * gapOpen - c * gapExt;\n ulH = uH + gapExt;\n } else {\n uH = ulH = 0;\n }\n if (c == 0)\n ulH = 0;\n \n maxH = INT_MIN;\n for (int r = 0; r < queryLength; r++) {\n int E = max(prevHs[r] - gapOpen, prevEs[r] - gapExt);\n int F = max(uH - gapOpen, uF - gapExt);\n int score = scoreMatrix[query[r] * alphabetLength + db[seqIdx][c]];\n H = max(E, max(F, ulH+score));\n maxH = max(H, maxH);\n uF = F;\n uH = H;\n ulH = prevHs[r];\n\t\t\n prevHs[r] = H;\n prevEs[r] = E;\n }\n maxLastRowH = max(maxLastRowH, H);\n }\n \n if (!strcmp(mode, \"OV\")) scores[seqIdx] = max(maxLastRowH, maxH);\n else if (!strcmp(mode, \"HW\")) scores[seqIdx] = maxLastRowH;\n else if (!strcmp(mode, \"NW\")) scores[seqIdx] = H; \n else return 1;\n }\n\n return 0;\n}\n\nvoid printInts(int a[], int aLength) {\n for (int i = 0; i < aLength; i++)\n printf(\"%d \", a[i]);\n printf(\"\\n\");\n}\n\nint maximum(int a[], int aLength) {\n int maximum = 0;\n for (int i = 0; i < aLength; i++)\n if (a[i] > maximum)\n maximum = a[i];\n return maximum;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright 2011-2013 The University of North Carolina at Chapel Hill\n * All rights reserved.\n *\n * Licensed under the MADAI Software License. You may obtain a copy of\n * this license at\n *\n * https:\/\/madai-public.cs.unc.edu\/software\/license\/\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#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n\n#include \"GaussianDistribution.h\"\n#include \"LatinHypercubeGenerator.h\"\n#include \"Parameter.h\"\n#include \"UniformDistribution.h\"\n\n#include \"madaisys\/SystemTools.hxx\"\n\n\nstatic const char usage[] =\n \"usage:\\n\"\n \" generateTrainingPoints [options] ParametersFile OutputDirectory\\n\"\n \"\\n\"\n \"ParametersFile is a file containing a list of parameters and their ranges\\n\"\n \"\\n\"\n \" The file should be a text file with a separate line for each parameter\\n\"\n \" listing the name of the parameter followed by a numeric minimum and maximum\\n\"\n \" defining the range of the parameter, such as\\n\"\n \"\\n\"\n \" temperature 245.2 288.0\\n\"\n \" pressure 4.7 5.9\\n\"\n \" ...\\n\"\n \"\\n\"\n \"OutputDirectory is a path to the name of the directory containing the parameter files\\n\"\n \"\\n\"\n \"Options:\\n\"\n \"\\n\"\n \" -h,--help Display help message.\\n\"\n \"\\n\"\n \" -v,--verbose Print extra information.\\n\"\n \"\\n\"\n \" -f,--format {directories,emulator} Select the output format.\"\n \"\\n\"\n \" -p,--percentile Partition space by parameter prior\\n\"\n \" distribution percentile.\\n\"\n \"\\n\"\n \" -s,--stddev <value> Number of standard deviations from\\n\"\n \" mean of a parameter's Gaussian\\n\"\n \" distributed prior to include in the\\n\"\n \" sampling.\\n\"\n \"\\n\";\n\ntypedef enum {\n DIRECTORIES_FORMAT, \/\/ Pratt format\n EMULATOR_FORMAT \/\/ GaussianProcessEmulator format\n} FormatType;\n\n\nstruct CommandLineOptions {\n bool verbose;\n const char * parametersFile; \/\/ First non-flag argument.\n const char * outputDirectory; \/\/ Second non-flag argument.\n FormatType formatType; \/\/ Type of the output\n bool partitionSpaceByPercentile;\n double standardDeviations;\n};\n\n\nstd::string LowerCase( char * buffer )\n{\n std::string outBuffer( buffer );\n\n std::transform( outBuffer.begin(), outBuffer.end(),\n outBuffer.begin(), ::tolower );\n\n return outBuffer;\n}\n\n\nbool ParseCommandLineOptions( int argc, char* argv[], struct CommandLineOptions & options)\n{\n \/\/ Default values for command-line options\n options.verbose = false;\n options.parametersFile = NULL;\n options.outputDirectory = NULL;\n options.formatType = DIRECTORIES_FORMAT;\n options.partitionSpaceByPercentile = false;\n options.standardDeviations = 3.0;\n\n \/\/ Parse options\n int argIndex;\n for ( argIndex = 1; argIndex < argc; ++argIndex ) {\n std::string argString( argv[ argIndex ] );\n\n if ( argString == \"-v\" || argString == \"--verbose\" ) {\n options.verbose = true;\n } else if ( argString == \"-h\" || argString == \"--help\" ) {\n std::cerr << usage;\n return false;\n } else if ( argString == \"-f\" || argString == \"--format\" ) {\n if ( argIndex + 1 < argc ) {\n std::string argString2 = LowerCase( argv[ argIndex + 1 ] );\n if ( argString2 == \"directories\" ) {\n options.formatType = DIRECTORIES_FORMAT;\n } else if ( argString2 == \"emulator\" ) {\n options.formatType = EMULATOR_FORMAT;\n } else {\n std::cerr << \"Unknown format type '\" << argString2 << \"' provided to '\"\n << argString << \"'. Expected 'directories' or 'emulator'.\\n\";\n return false;\n }\n argIndex++;\n } else {\n std::cerr << \"No format type provided to argument '\" << argString\n << \"'. Expected 'directories' or 'emulator'.\\n\";\n return false;\n }\n } else if ( argString == \"-p\" || argString == \"--percentile\" ) {\n options.partitionSpaceByPercentile = true;\n } else if ( argString == \"-s\" || argString == \"--stddev\" ) {\n if ( argIndex + 1 < argc ) {\n argIndex++;\n std::string argString2( argv[ argIndex ] );\n options.standardDeviations = atof( argString2.c_str() );\n if ( options.standardDeviations == 0.0 ) {\n std::cerr << \"Standard deviations set to 0.0 is not valid. \"\n << \"Did you supply a number to '\" << argString\n << \"'?\\n\";\n return false;\n }\n std::cout << \"argString2: \" << argString2 << options.standardDeviations << std::endl;\n } else {\n std::cerr << \"Missing value for '\" << argString << \"'.\\n\";\n return false;\n }\n } else {\n break; \/\/ No switch\n }\n }\n\n if ( argIndex < argc ) {\n options.parametersFile = argv[ argIndex++ ];\n } else {\n std::cerr << usage;\n return false;\n }\n\n if ( argIndex < argc ) {\n options.outputDirectory = argv[ argIndex++ ];\n } else {\n std::cerr << usage;\n return false;\n }\n\n if ( argIndex < argc ) {\n std::cerr << \"Extra arguments after '\" << options.outputDirectory << \"'\\n\";\n return false;\n }\n\n \/\/ Everything went well\n return true;\n}\n\n\nbool ReadParameters( const struct CommandLineOptions & options,\n std::vector< madai::Parameter > & parameters )\n{\n parameters.clear();\n\n FILE *fp = fopen( options.parametersFile, \"r\" );\n if ( !fp ) {\n return false;\n }\n\n if ( options.verbose ) {\n std::cout << \"Opened file '\" << options.parametersFile << \"'\\n\";\n }\n\n char buffer[4096];\n\n \/\/ Parse each parameter as it is listed on a line\n while ( 1 == fscanf( fp, \"%4095s\", buffer ) ) {\n std::string parameterName( buffer );\n\n if ( options.verbose ) {\n std::cout << \"Read parameter '\" << parameterName << \"' \";\n }\n\n if ( 1 != fscanf( fp, \"%4095s\", buffer ) ) {\n std::cerr << \"Could not read distribution type\\n\";\n fclose( fp );\n return false;\n }\n\n std::string distributionType( LowerCase( buffer ) );\n\n if ( options.verbose ) {\n std::cout << \"which is of type '\" << distributionType << \"' \";\n }\n\n madai::Distribution *distribution = NULL;\n madai::UniformDistribution uniform;\n madai::GaussianDistribution gaussian;\n\n if ( distributionType == \"uniform\" ) {\n \/\/ Parse minimum and maximum values\n double minimum, maximum;\n if ( 2 != fscanf( fp, \"%lf %lf\", &minimum, &maximum ) ) {\n std::cerr << \"Could not read uniform distribution minimum and maximum\\n\";\n fclose( fp );\n return false;\n }\n\n if ( options.verbose ) {\n std::cout << \"with range [\" << minimum << \", \" << maximum << \"]\\n\";\n }\n\n uniform.SetMinimum( minimum );\n uniform.SetMaximum( maximum );\n distribution = &uniform;\n\n } else if ( distributionType == \"gaussian\" ) {\n \/\/ Parse mean and standard deviation\n double mean, standardDeviation;\n if ( 2 != fscanf( fp, \"%lf %lf\", &mean, &standardDeviation ) ) {\n std::cerr << \"Could not read Gaussian distribution mean and standard deviation\\n\";\n fclose( fp );\n return false;\n }\n\n if ( options.verbose ) {\n std::cout << \"with mean \" << mean << \" and standard deviation \"\n << standardDeviation << \"\\n\";\n }\n\n gaussian.SetMean( mean );\n gaussian.SetStandardDeviation( standardDeviation );\n distribution = &gaussian;\n } else {\n std::cerr << \"Unknown distribution type '\" << distributionType << \"'\\n\";\n fclose( fp );\n return false;\n }\n\n parameters.push_back( madai::Parameter( parameterName, *distribution ) );\n }\n\n fclose( fp );\n\n \/\/ Everything went okay\n return true;\n}\n\n\nbool WriteDirectoriesFormat( const struct CommandLineOptions & options,\n const std::vector< madai::Parameter > & parameters,\n const std::vector< madai::Sample > & samples ) {\n \/\/ Create the directory structure\n bool directoryCreated = madaisys::SystemTools::MakeDirectory( options.outputDirectory );\n if ( !directoryCreated ) {\n std::cerr << \"Could not create directory '\" << options.outputDirectory\n << \"'\\n\";\n return false;\n }\n\n std::string directory( options.outputDirectory );\n std::string experimental_results( directory + \"\/experimental_results\" );\n std::string model_outputs( directory + \"\/model_outputs\" );\n std::string statistical_analysis( directory + \"\/statistical_analysis\" );\n\n directoryCreated = directoryCreated &&\n madaisys::SystemTools::MakeDirectory( experimental_results.c_str() );\n directoryCreated = directoryCreated &&\n madaisys::SystemTools::MakeDirectory( model_outputs.c_str() );\n directoryCreated = directoryCreated &&\n madaisys::SystemTools::MakeDirectory( statistical_analysis.c_str() );\n\n \/\/ Now create the run directories\n for ( size_t i = 0; i < samples.size(); ++i ) {\n const madai::Sample & sample = samples[i];\n\n char buffer[128];\n sprintf( buffer, \"\/model_outputs\/run%04d\", static_cast<int>( i ) );\n std::string runDirectory( directory + std::string( buffer ) );\n\n std::cout << runDirectory << \"\\n\";\n\n directoryCreated = directoryCreated &&\n madaisys::SystemTools::MakeDirectory( runDirectory.c_str() );\n\n \/\/ Write the parameters to the parameters.dat file\n std::string parametersFile( runDirectory + \"\/parameters.dat\" );\n FILE *fp = fopen( parametersFile.c_str(), \"w\" );\n if ( !fp ) {\n std::cerr << \"Could not open file '\" << parametersFile << \"'\\n\";\n return false;\n }\n\n assert( parameters.size() == sample.m_ParameterValues.size() );\n for ( size_t j = 0; j < parameters.size(); ++j ) {\n fprintf( fp, \"%s %f\\n\",\n parameters[ j ].m_Name.c_str(),\n sample.m_ParameterValues[ j ] );\n }\n\n fclose( fp );\n }\n\n return true;\n}\n\n\nbool WriteEmulatorFormat( const struct CommandLineOptions & options,\n const std::vector< madai::Parameter > & parameters,\n const std::vector< madai::Sample > & samples ) {\n \/\/ Create the output directory\n bool directoryCreated = madaisys::SystemTools::MakeDirectory( options.outputDirectory );\n if ( !directoryCreated ) {\n std::cerr << \"Could not create directory '\" << options.outputDirectory\n << \"'\\n\";\n return false;\n }\n\n \/\/ Open the output file\n std::string outputFile( options.outputDirectory );\n outputFile += \"\/emulator.dat\";\n FILE * fp = fopen( outputFile.c_str(), \"w\" );\n if ( !fp ) {\n std::cerr << \"Could not create output file '\" << outputFile << \"'\\n\";\n return false;\n }\n\n \/\/ Print VERSION\n fprintf( fp, \"VERSION 1\\n\" );\n\n \/\/ Print the PARAMETERS\n fprintf( fp, \"PARAMETERS\\n\" );\n\n for ( size_t i = 0; i < parameters.size(); ++i ) {\n fprintf( fp, \"%s \", parameters[i].m_Name.c_str() );\n const madai::Distribution * priorDistribution =\n parameters[i].GetPriorDistribution();\n const madai::UniformDistribution * uniformDistribution =\n dynamic_cast< const madai::UniformDistribution *>( priorDistribution );\n const madai::GaussianDistribution * gaussianDistribution =\n dynamic_cast< const madai::GaussianDistribution *>( priorDistribution );\n if ( uniformDistribution ) {\n fprintf( fp, \"UNIFORM %f %f\\n\",\n uniformDistribution->GetMinimum(),\n uniformDistribution->GetMaximum() );\n } else if ( gaussianDistribution ) {\n fprintf( fp, \"GAUSSIAN %f %f\\n\",\n gaussianDistribution->GetMean(),\n gaussianDistribution->GetStandardDeviation() );\n } else {\n std::cerr << \"Unknown prior type\\n\";\n return false;\n }\n }\n\n \/\/ Print training points\n fprintf( fp, \"NUMBER_OF_TRAINING_POINTS %d\\n\",\n static_cast< int >( samples.size() ) );\n\n \/\/ Print parameter values at training points\n fprintf( fp, \"PARAMETER_VALUES\\n\" );\n\n for ( size_t i = 0; i < samples.size(); ++i ) {\n const madai::Sample & sample = samples[i];\n\n for ( size_t j = 0; j < sample.m_ParameterValues.size(); ++j ) {\n fprintf( fp, \"%f \", sample.m_ParameterValues[j] );\n }\n fprintf( fp, \"\\n\" );\n }\n\n fclose( fp );\n\n return true;\n}\n\n\nint main( int argc, char * argv[] ) {\n struct CommandLineOptions options;\n if ( !ParseCommandLineOptions( argc, argv, options ) ) {\n return EXIT_FAILURE;\n }\n\n if ( options.verbose ) {\n std::cout << \"Options: \\n\";\n std::cout << \" --verbose: \" << options.verbose << \"\\n\";\n std::cout << \" --format: \";\n if ( options.formatType == DIRECTORIES_FORMAT ) std::cout << \"directories\\n\";\n if ( options.formatType == EMULATOR_FORMAT ) std::cout << \"emulator\\n\";\n std::cout << \" --percentile: \" << options.partitionSpaceByPercentile << \"\\n\";\n std::cout << \" --stddev: \" << options.standardDeviations << \"\\n\";\n std::cout << \" ParametersFile: \" << options.parametersFile << \"\\n\";\n std::cout << \" OutputDirectory: \" << options.outputDirectory << \"\\n\";\n }\n\n \/\/ Read in parameter priors\n std::vector< madai::Parameter > parameters;\n bool parametersRead = ReadParameters( options, parameters );\n if ( !parametersRead ) {\n std::cerr << \"Could not read parameters from prior file '\"\n << options.parametersFile << \"'\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Create the Latin hypercube sampling\n madai::LatinHypercubeGenerator sampleGenerator;\n std::vector< madai::Sample > samples = sampleGenerator.Generate( 100, parameters );\n sampleGenerator.SetStandardDeviations( options.standardDeviations );\n sampleGenerator.SetPartitionSpaceByPercentile( options.partitionSpaceByPercentile );\n\n if ( options.formatType == DIRECTORIES_FORMAT ) {\n WriteDirectoriesFormat( options, parameters, samples );\n } else if ( options.formatType == EMULATOR_FORMAT ) {\n WriteEmulatorFormat( options, parameters, samples );\n } else {\n std::cerr << \"Unknown output format type\" << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\n<commit_msg>Fixed bug where latin hypercube generator settings were being set after samples were generated<commit_after>\/*=========================================================================\n *\n * Copyright 2011-2013 The University of North Carolina at Chapel Hill\n * All rights reserved.\n *\n * Licensed under the MADAI Software License. You may obtain a copy of\n * this license at\n *\n * https:\/\/madai-public.cs.unc.edu\/software\/license\/\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#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n\n#include \"GaussianDistribution.h\"\n#include \"LatinHypercubeGenerator.h\"\n#include \"Parameter.h\"\n#include \"UniformDistribution.h\"\n\n#include \"madaisys\/SystemTools.hxx\"\n\n\nstatic const char usage[] =\n \"usage:\\n\"\n \" generateTrainingPoints [options] ParametersFile OutputDirectory\\n\"\n \"\\n\"\n \"ParametersFile is a file containing a list of parameters and their ranges\\n\"\n \"\\n\"\n \" The file should be a text file with a separate line for each parameter\\n\"\n \" listing the name of the parameter followed by a numeric minimum and maximum\\n\"\n \" defining the range of the parameter, such as\\n\"\n \"\\n\"\n \" temperature 245.2 288.0\\n\"\n \" pressure 4.7 5.9\\n\"\n \" ...\\n\"\n \"\\n\"\n \"OutputDirectory is a path to the name of the directory containing the parameter files\\n\"\n \"\\n\"\n \"Options:\\n\"\n \"\\n\"\n \" -h,--help Display help message.\\n\"\n \"\\n\"\n \" -v,--verbose Print extra information.\\n\"\n \"\\n\"\n \" -f,--format {directories,emulator} Select the output format.\"\n \"\\n\"\n \" -p,--percentile Partition space by parameter prior\\n\"\n \" distribution percentile.\\n\"\n \"\\n\"\n \" -s,--stddev <value> Number of standard deviations from\\n\"\n \" mean of a parameter's Gaussian\\n\"\n \" distributed prior to include in the\\n\"\n \" sampling.\\n\"\n \"\\n\";\n\ntypedef enum {\n DIRECTORIES_FORMAT, \/\/ Pratt format\n EMULATOR_FORMAT \/\/ GaussianProcessEmulator format\n} FormatType;\n\n\nstruct CommandLineOptions {\n bool verbose;\n const char * parametersFile; \/\/ First non-flag argument.\n const char * outputDirectory; \/\/ Second non-flag argument.\n FormatType formatType; \/\/ Type of the output\n bool partitionSpaceByPercentile;\n double standardDeviations;\n};\n\n\nstd::string LowerCase( char * buffer )\n{\n std::string outBuffer( buffer );\n\n std::transform( outBuffer.begin(), outBuffer.end(),\n outBuffer.begin(), ::tolower );\n\n return outBuffer;\n}\n\n\nbool ParseCommandLineOptions( int argc, char* argv[], struct CommandLineOptions & options)\n{\n \/\/ Default values for command-line options\n options.verbose = false;\n options.parametersFile = NULL;\n options.outputDirectory = NULL;\n options.formatType = DIRECTORIES_FORMAT;\n options.partitionSpaceByPercentile = false;\n options.standardDeviations = 3.0;\n\n \/\/ Parse options\n int argIndex;\n for ( argIndex = 1; argIndex < argc; ++argIndex ) {\n std::string argString( argv[ argIndex ] );\n\n if ( argString == \"-v\" || argString == \"--verbose\" ) {\n options.verbose = true;\n } else if ( argString == \"-h\" || argString == \"--help\" ) {\n std::cerr << usage;\n return false;\n } else if ( argString == \"-f\" || argString == \"--format\" ) {\n if ( argIndex + 1 < argc ) {\n std::string argString2 = LowerCase( argv[ argIndex + 1 ] );\n if ( argString2 == \"directories\" ) {\n options.formatType = DIRECTORIES_FORMAT;\n } else if ( argString2 == \"emulator\" ) {\n options.formatType = EMULATOR_FORMAT;\n } else {\n std::cerr << \"Unknown format type '\" << argString2 << \"' provided to '\"\n << argString << \"'. Expected 'directories' or 'emulator'.\\n\";\n return false;\n }\n argIndex++;\n } else {\n std::cerr << \"No format type provided to argument '\" << argString\n << \"'. Expected 'directories' or 'emulator'.\\n\";\n return false;\n }\n } else if ( argString == \"-p\" || argString == \"--percentile\" ) {\n options.partitionSpaceByPercentile = true;\n } else if ( argString == \"-s\" || argString == \"--stddev\" ) {\n if ( argIndex + 1 < argc ) {\n argIndex++;\n std::string argString2( argv[ argIndex ] );\n options.standardDeviations = atof( argString2.c_str() );\n if ( options.standardDeviations == 0.0 ) {\n std::cerr << \"Standard deviations set to 0.0 is not valid. \"\n << \"Did you supply a number to '\" << argString\n << \"'?\\n\";\n return false;\n }\n std::cout << \"argString2: \" << argString2 << options.standardDeviations << std::endl;\n } else {\n std::cerr << \"Missing value for '\" << argString << \"'.\\n\";\n return false;\n }\n } else {\n break; \/\/ No switch\n }\n }\n\n if ( argIndex < argc ) {\n options.parametersFile = argv[ argIndex++ ];\n } else {\n std::cerr << usage;\n return false;\n }\n\n if ( argIndex < argc ) {\n options.outputDirectory = argv[ argIndex++ ];\n } else {\n std::cerr << usage;\n return false;\n }\n\n if ( argIndex < argc ) {\n std::cerr << \"Extra arguments after '\" << options.outputDirectory << \"'\\n\";\n return false;\n }\n\n \/\/ Everything went well\n return true;\n}\n\n\nbool ReadParameters( const struct CommandLineOptions & options,\n std::vector< madai::Parameter > & parameters )\n{\n parameters.clear();\n\n FILE *fp = fopen( options.parametersFile, \"r\" );\n if ( !fp ) {\n return false;\n }\n\n if ( options.verbose ) {\n std::cout << \"Opened file '\" << options.parametersFile << \"'\\n\";\n }\n\n char buffer[4096];\n\n \/\/ Parse each parameter as it is listed on a line\n while ( 1 == fscanf( fp, \"%4095s\", buffer ) ) {\n std::string parameterName( buffer );\n\n if ( options.verbose ) {\n std::cout << \"Read parameter '\" << parameterName << \"' \";\n }\n\n if ( 1 != fscanf( fp, \"%4095s\", buffer ) ) {\n std::cerr << \"Could not read distribution type\\n\";\n fclose( fp );\n return false;\n }\n\n std::string distributionType( LowerCase( buffer ) );\n\n if ( options.verbose ) {\n std::cout << \"which is of type '\" << distributionType << \"' \";\n }\n\n madai::Distribution *distribution = NULL;\n madai::UniformDistribution uniform;\n madai::GaussianDistribution gaussian;\n\n if ( distributionType == \"uniform\" ) {\n \/\/ Parse minimum and maximum values\n double minimum, maximum;\n if ( 2 != fscanf( fp, \"%lf %lf\", &minimum, &maximum ) ) {\n std::cerr << \"Could not read uniform distribution minimum and maximum\\n\";\n fclose( fp );\n return false;\n }\n\n if ( options.verbose ) {\n std::cout << \"with range [\" << minimum << \", \" << maximum << \"]\\n\";\n }\n\n uniform.SetMinimum( minimum );\n uniform.SetMaximum( maximum );\n distribution = &uniform;\n\n } else if ( distributionType == \"gaussian\" ) {\n \/\/ Parse mean and standard deviation\n double mean, standardDeviation;\n if ( 2 != fscanf( fp, \"%lf %lf\", &mean, &standardDeviation ) ) {\n std::cerr << \"Could not read Gaussian distribution mean and standard deviation\\n\";\n fclose( fp );\n return false;\n }\n\n if ( options.verbose ) {\n std::cout << \"with mean \" << mean << \" and standard deviation \"\n << standardDeviation << \"\\n\";\n }\n\n gaussian.SetMean( mean );\n gaussian.SetStandardDeviation( standardDeviation );\n distribution = &gaussian;\n } else {\n std::cerr << \"Unknown distribution type '\" << distributionType << \"'\\n\";\n fclose( fp );\n return false;\n }\n\n parameters.push_back( madai::Parameter( parameterName, *distribution ) );\n }\n\n fclose( fp );\n\n \/\/ Everything went okay\n return true;\n}\n\n\nbool WriteDirectoriesFormat( const struct CommandLineOptions & options,\n const std::vector< madai::Parameter > & parameters,\n const std::vector< madai::Sample > & samples ) {\n \/\/ Create the directory structure\n bool directoryCreated = madaisys::SystemTools::MakeDirectory( options.outputDirectory );\n if ( !directoryCreated ) {\n std::cerr << \"Could not create directory '\" << options.outputDirectory\n << \"'\\n\";\n return false;\n }\n\n std::string directory( options.outputDirectory );\n std::string experimental_results( directory + \"\/experimental_results\" );\n std::string model_outputs( directory + \"\/model_outputs\" );\n std::string statistical_analysis( directory + \"\/statistical_analysis\" );\n\n directoryCreated = directoryCreated &&\n madaisys::SystemTools::MakeDirectory( experimental_results.c_str() );\n directoryCreated = directoryCreated &&\n madaisys::SystemTools::MakeDirectory( model_outputs.c_str() );\n directoryCreated = directoryCreated &&\n madaisys::SystemTools::MakeDirectory( statistical_analysis.c_str() );\n\n \/\/ Now create the run directories\n for ( size_t i = 0; i < samples.size(); ++i ) {\n const madai::Sample & sample = samples[i];\n\n char buffer[128];\n sprintf( buffer, \"\/model_outputs\/run%04d\", static_cast<int>( i ) );\n std::string runDirectory( directory + std::string( buffer ) );\n\n std::cout << runDirectory << \"\\n\";\n\n directoryCreated = directoryCreated &&\n madaisys::SystemTools::MakeDirectory( runDirectory.c_str() );\n\n \/\/ Write the parameters to the parameters.dat file\n std::string parametersFile( runDirectory + \"\/parameters.dat\" );\n FILE *fp = fopen( parametersFile.c_str(), \"w\" );\n if ( !fp ) {\n std::cerr << \"Could not open file '\" << parametersFile << \"'\\n\";\n return false;\n }\n\n assert( parameters.size() == sample.m_ParameterValues.size() );\n for ( size_t j = 0; j < parameters.size(); ++j ) {\n fprintf( fp, \"%s %f\\n\",\n parameters[ j ].m_Name.c_str(),\n sample.m_ParameterValues[ j ] );\n }\n\n fclose( fp );\n }\n\n return true;\n}\n\n\nbool WriteEmulatorFormat( const struct CommandLineOptions & options,\n const std::vector< madai::Parameter > & parameters,\n const std::vector< madai::Sample > & samples ) {\n \/\/ Create the output directory\n bool directoryCreated = madaisys::SystemTools::MakeDirectory( options.outputDirectory );\n if ( !directoryCreated ) {\n std::cerr << \"Could not create directory '\" << options.outputDirectory\n << \"'\\n\";\n return false;\n }\n\n \/\/ Open the output file\n std::string outputFile( options.outputDirectory );\n outputFile += \"\/emulator.dat\";\n FILE * fp = fopen( outputFile.c_str(), \"w\" );\n if ( !fp ) {\n std::cerr << \"Could not create output file '\" << outputFile << \"'\\n\";\n return false;\n }\n\n \/\/ Print VERSION\n fprintf( fp, \"VERSION 1\\n\" );\n\n \/\/ Print the PARAMETERS\n fprintf( fp, \"PARAMETERS\\n\" );\n\n for ( size_t i = 0; i < parameters.size(); ++i ) {\n fprintf( fp, \"%s \", parameters[i].m_Name.c_str() );\n const madai::Distribution * priorDistribution =\n parameters[i].GetPriorDistribution();\n const madai::UniformDistribution * uniformDistribution =\n dynamic_cast< const madai::UniformDistribution *>( priorDistribution );\n const madai::GaussianDistribution * gaussianDistribution =\n dynamic_cast< const madai::GaussianDistribution *>( priorDistribution );\n if ( uniformDistribution ) {\n fprintf( fp, \"UNIFORM %f %f\\n\",\n uniformDistribution->GetMinimum(),\n uniformDistribution->GetMaximum() );\n } else if ( gaussianDistribution ) {\n fprintf( fp, \"GAUSSIAN %f %f\\n\",\n gaussianDistribution->GetMean(),\n gaussianDistribution->GetStandardDeviation() );\n } else {\n std::cerr << \"Unknown prior type\\n\";\n return false;\n }\n }\n\n \/\/ Print training points\n fprintf( fp, \"NUMBER_OF_TRAINING_POINTS %d\\n\",\n static_cast< int >( samples.size() ) );\n\n \/\/ Print parameter values at training points\n fprintf( fp, \"PARAMETER_VALUES\\n\" );\n\n for ( size_t i = 0; i < samples.size(); ++i ) {\n const madai::Sample & sample = samples[i];\n\n for ( size_t j = 0; j < sample.m_ParameterValues.size(); ++j ) {\n fprintf( fp, \"%f \", sample.m_ParameterValues[j] );\n }\n fprintf( fp, \"\\n\" );\n }\n\n fclose( fp );\n\n return true;\n}\n\n\nint main( int argc, char * argv[] ) {\n struct CommandLineOptions options;\n if ( !ParseCommandLineOptions( argc, argv, options ) ) {\n return EXIT_FAILURE;\n }\n\n if ( options.verbose ) {\n std::cout << \"Options: \\n\";\n std::cout << \" --verbose: \" << options.verbose << \"\\n\";\n std::cout << \" --format: \";\n if ( options.formatType == DIRECTORIES_FORMAT ) std::cout << \"directories\\n\";\n if ( options.formatType == EMULATOR_FORMAT ) std::cout << \"emulator\\n\";\n std::cout << \" --percentile: \" << options.partitionSpaceByPercentile << \"\\n\";\n std::cout << \" --stddev: \" << options.standardDeviations << \"\\n\";\n std::cout << \" ParametersFile: \" << options.parametersFile << \"\\n\";\n std::cout << \" OutputDirectory: \" << options.outputDirectory << \"\\n\";\n }\n\n \/\/ Read in parameter priors\n std::vector< madai::Parameter > parameters;\n bool parametersRead = ReadParameters( options, parameters );\n if ( !parametersRead ) {\n std::cerr << \"Could not read parameters from prior file '\"\n << options.parametersFile << \"'\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Create the Latin hypercube sampling\n madai::LatinHypercubeGenerator sampleGenerator;\n sampleGenerator.SetStandardDeviations( options.standardDeviations );\n sampleGenerator.SetPartitionSpaceByPercentile( options.partitionSpaceByPercentile );\n\n std::vector< madai::Sample > samples = sampleGenerator.Generate( 100, parameters );\n\n if ( options.formatType == DIRECTORIES_FORMAT ) {\n WriteDirectoriesFormat( options, parameters, samples );\n } else if ( options.formatType == EMULATOR_FORMAT ) {\n WriteEmulatorFormat( options, parameters, samples );\n } else {\n std::cerr << \"Unknown output format type\" << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* ****************************************************************************\n*\n* FILE main_samsonKiller.cpp\n*\n* AUTHOR Ken Zangelin\n*\n* CREATION DATE Feb 25 2011\n*\n*\/\n#include \"parseArgs.h\" \/\/ parseArgs\n#include \"paUsage.h\" \/\/ paUsage\n#include \"traceLevels.h\" \/\/ Trace levels\n\n#include \"Endpoint.h\" \/\/ Endpoint\n#include \"ports.h\" \/\/ SPAWNER_PORT, CONTROLLER_PORT, WORKER_PORT\n#include \"iomConnect.h\" \/\/ iomConnect\n#include \"iomMsgSend.h\" \/\/ iomMsgSend\n\n\n\n\n\/* ****************************************************************************\n*\n* Option variables\n*\/\nchar name[80];\n\n\n\n\/* ****************************************************************************\n*\n* parse arguments\n*\/\nPaArgument paArgs[] =\n{\n\t{ \" \", name, \"NAME\", PaString, PaOpt, PaND, PaNL, PaNL, \"name of prcess to kill\" },\n\n\tPA_END_OF_ARGS\n};\n\n\n\n\/* ****************************************************************************\n*\n* killProcess - \n*\/\nstatic int killProcess(const char* name, unsigned short port)\n{\n\tss::Endpoint ep;\n\tss::Endpoint me;\n\n\tep.name = name;\n\tep.wFd = iomConnect(\"localhost\", port);\n\t\n\tif (ep.wFd == -1)\n\t{\n\t\tprintf(\"error connecting to %s at 'localhost', port %d - probably means the process isn't running\\n\", name, port);\n\t\treturn 3;\n\t}\n\n\tme.name = \"samsonKiller\";\n\n\tif (iomMsgSend(&ep, &me, ss::Message::Die, ss::Message::Msg) != 0)\n\t{\n\t\tprintf(\"error sending 'Die' message to endpoint (port %d)\\n\", port);\n\t\treturn 4;\n\t}\n\n\treturn 0;\n}\n\n\n\n\/* ****************************************************************************\n*\n* main - \n*\/\nint main(int argC, const char *argV[])\n{\n\tname[0] = 0;\n\n\tpaParse(paArgs, argC, (char**) argV, 1, false);\n\n#if 0\n\tprintf(\"Started with arguments:\\n\");\n\tfor (int ix = 0; ix < argC; ix++)\n\t\tprintf(\" %02d: '%s'\\n\", ix, argV[ix]);\n#endif\n\n\tif (name[0] != 0)\n\t{\n\t\tif ((strcasecmp(name, \"worker\") == 0) || (strcasecmp(name, \"samsonWorker\") == 0))\n return killProcess(\"samsonWorker\", WORKER_PORT);\n\t\telse if ((strcasecmp(name, \"controller\") == 0) || (strcasecmp(name, \"samsonController\") == 0))\n return killProcess(\"samsonController\", CONTROLLER_PORT);\n\t\telse if ((strcasecmp(name, \"spawner\") == 0) || (strcasecmp(name, \"samsonSpawner\") == 0))\n\t\t\treturn killProcess(\"samsonSpawner\", SPAWNER_PORT);\n\t\telse if (strcasecmp(name, \"all\") == 0)\n\t\t{\n\t\t killProcess(\"samsonWorker\", WORKER_PORT);\n\t\t killProcess(\"samsonController\", CONTROLLER_PORT);\n\t\t killProcess(\"samsonSpawner\", SPAWNER_PORT);\n\n\t\t return 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"non-familiar process '%s'\\n\", name);\n\t\t\texit(1);\n\t\t}\n\t}\n\n\treturn 0;\n}\n<commit_msg>samsonKiller now uses 'killall' if Die fails<commit_after>\/* ****************************************************************************\n*\n* FILE main_samsonKiller.cpp\n*\n* AUTHOR Ken Zangelin\n*\n* CREATION DATE Feb 25 2011\n*\n*\/\n#include \"parseArgs.h\" \/\/ parseArgs\n#include \"paUsage.h\" \/\/ paUsage\n#include \"traceLevels.h\" \/\/ Trace levels\n\n#include \"Endpoint.h\" \/\/ Endpoint\n#include \"ports.h\" \/\/ SPAWNER_PORT, CONTROLLER_PORT, WORKER_PORT\n#include \"iomConnect.h\" \/\/ iomConnect\n#include \"iomMsgSend.h\" \/\/ iomMsgSend\n\n\n\n\n\/* ****************************************************************************\n*\n* Option variables\n*\/\nchar name[80];\n\n\n\n\/* ****************************************************************************\n*\n* parse arguments\n*\/\nPaArgument paArgs[] =\n{\n\t{ \" \", name, \"NAME\", PaString, PaOpt, (long) \"all\", PaNL, PaNL, \"name of prcess to kill\" },\n\n\tPA_END_OF_ARGS\n};\n\n\n\n\/* ****************************************************************************\n*\n* sysKill - \n*\/\nstatic void sysKill(const char* name)\n{\n\tchar com[256];\n\n\tsnprintf(com, sizeof(com), \"killall -9 %s > \/dev\/null 2>&1\", name);\n\tsystem(com);\n\tprintf(\"Killed %s\\n\", name);\n}\n\n\n\n\/* ****************************************************************************\n*\n* killProcess - \n*\/\nstatic int killProcess(const char* name, unsigned short port)\n{\n\tss::Endpoint ep;\n\tss::Endpoint me;\n\tint s;\n\n\tep.name = name;\n\tep.wFd = iomConnect(\"localhost\", port);\n\tLM_M((\"%s: ep.wFd == %d\", name, ep.wFd));\n\tme.name = \"samsonKiller\";\n\t\n\tif ((ep.wFd == -1) || ((s = iomMsgSend(&ep, &me, ss::Message::Die, ss::Message::Msg)) != 0))\n\t{\n\t\tLM_M((\"%s: s = %d\", name, s));\n\t\tsysKill(name);\n\t}\n\telse\n\t{\n\t\tint fd = iomConnect(\"localhost\", port);\n\n\t\tLM_M((\"%s: second connect: fd == %d\", name, fd));\n\t\tif (fd != -1)\n\t\t\tsysKill(name);\n\t\telse\n\t\t\tprintf(\"killed '%s'\\n\", name);\n\t}\n\n\treturn 0;\n}\n\n\n\n\/* ****************************************************************************\n*\n* main - \n*\/\nint main(int argC, const char *argV[])\n{\n\tname[0] = 0;\n\n\tpaConfig(\"log to file\", (void*) true);\n\tpaParse(paArgs, argC, (char**) argV, 1, false);\n\n\tif (name[0] != 0)\n\t{\n\t\tif ((strcasecmp(name, \"worker\") == 0) || (strcasecmp(name, \"samsonWorker\") == 0))\n return killProcess(\"samsonWorker\", WORKER_PORT);\n\t\telse if ((strcasecmp(name, \"controller\") == 0) || (strcasecmp(name, \"samsonController\") == 0))\n return killProcess(\"samsonController\", CONTROLLER_PORT);\n\t\telse if ((strcasecmp(name, \"spawner\") == 0) || (strcasecmp(name, \"samsonSpawner\") == 0))\n\t\t\treturn killProcess(\"samsonSpawner\", SPAWNER_PORT);\n\t\telse if (strcasecmp(name, \"all\") == 0)\n\t\t{\n\t\t killProcess(\"samsonWorker\", WORKER_PORT);\n\t\t killProcess(\"samsonController\", CONTROLLER_PORT);\n\t\t killProcess(\"samsonSpawner\", SPAWNER_PORT);\n\n\t\t return 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"non-familiar process '%s'\\n\", name);\n\t\t\texit(1);\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief default handler for error handling and json in-\/output\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\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\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"RestBaseHandler.h\"\n\n#include \"Basics\/logging.h\"\n#include \"Basics\/tri-strings.h\"\n#include \"Basics\/StringBufferAdapter.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"Rest\/HttpRequest.h\"\n#include \"Rest\/HttpResponse.h\"\n\n\nusing namespace std;\nusing namespace triagens::basics;\nusing namespace triagens::rest;\nusing namespace triagens::admin;\n\ntypedef arangodb::velocypack::Dumper<StringBufferAdapter, false> StringBufferDumper;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRestBaseHandler::RestBaseHandler (HttpRequest* request)\n : HttpHandler(request) {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- Handler methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::handleError (Exception const& ex) {\n generateError(HttpResponse::responseCode(ex.code()),\n ex.code(),\n ex.what());\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a result from JSON\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateResult (TRI_json_t const* json) {\n generateResult(HttpResponse::OK, json);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a result from JSON\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateResult (HttpResponse::HttpResponseCode code,\n TRI_json_t const* json) {\n _response = createResponse(code);\n _response->setContentType(\"application\/json; charset=utf-8\");\n\n int res = TRI_StringifyJson(_response->body().stringBuffer(), json);\n\n if (res != TRI_ERROR_NO_ERROR) {\n generateError(HttpResponse::SERVER_ERROR,\n TRI_ERROR_INTERNAL,\n \"cannot generate output\");\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a result from VelocyPack\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateResult (VPackSlice& slice) {\n generateResult(HttpResponse::OK, slice);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a result from VelocyPack\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateResult (HttpResponse::HttpResponseCode code,\n VPackSlice& slice) {\n _response = createResponse(code);\n _response->setContentType(\"application\/json; charset=utf-8\");\n\n StringBufferAdapter buffer(_response->body().stringBuffer());\n\n StringBufferDumper dumper(buffer);\n try {\n dumper.dump(slice);\n }\n catch (...) {\n generateError(HttpResponse::SERVER_ERROR,\n TRI_ERROR_INTERNAL,\n \"cannot generate output\");\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a cancel message\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateCanceled () {\n VPackBuilder builder;\n builder.add(VPackValue(VPackValueType::Object));\n builder.add(\"error\", VPackValue(true));\n builder.add(\"code\", VPackValue((int32_t) HttpResponse::REQUEST_TIMEOUT));\n builder.add(\"errorNum\", VPackValue((int32_t) TRI_ERROR_REQUEST_CANCELED));\n builder.add(\"errorMessage\", VPackValue(\"request canceled\"));\n builder.close();\n\n VPackSlice slice(builder.start());\n generateResult(HttpResponse::REQUEST_TIMEOUT, slice);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates an error\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateError (HttpResponse::HttpResponseCode code,\n int errorCode) {\n char const* message = TRI_errno_string(errorCode);\n\n if (message) {\n generateError(code, errorCode, std::string(message));\n }\n else {\n generateError(code, errorCode, std::string(\"unknown error\"));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates an error\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateError (HttpResponse::HttpResponseCode code, int errorCode, std::string const& message) {\n\n _response = createResponse(code);\n _response->setContentType(\"application\/json; charset=utf-8\");\n\n _response->body().appendText(\"{\\\"error\\\":true,\\\"errorMessage\\\":\\\"\");\n if (message.empty()) {\n \/\/ prevent empty error messages\n _response->body().appendText(TRI_errno_string(errorCode));\n }\n else {\n _response->body().appendText(StringUtils::escapeUnicode(message));\n }\n\n _response->body().appendText(\"\\\",\\\"code\\\":\");\n _response->body().appendInteger(code);\n _response->body().appendText(\",\\\"errorNum\\\":\");\n _response->body().appendInteger(errorCode);\n _response->body().appendText(\"}\");\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<commit_msg>RestBaseHandler now uses VelocyPack internally<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief default handler for error handling and json in-\/output\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\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\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"RestBaseHandler.h\"\n\n#include \"Basics\/logging.h\"\n#include \"Basics\/tri-strings.h\"\n#include \"Basics\/StringBufferAdapter.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"Rest\/HttpRequest.h\"\n#include \"Rest\/HttpResponse.h\"\n\n\nusing namespace std;\nusing namespace triagens::basics;\nusing namespace triagens::rest;\nusing namespace triagens::admin;\n\ntypedef arangodb::velocypack::Dumper<StringBufferAdapter, false> StringBufferDumper;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRestBaseHandler::RestBaseHandler (HttpRequest* request)\n : HttpHandler(request) {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- Handler methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::handleError (Exception const& ex) {\n generateError(HttpResponse::responseCode(ex.code()),\n ex.code(),\n ex.what());\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a result from JSON\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateResult (TRI_json_t const* json) {\n generateResult(HttpResponse::OK, json);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a result from JSON\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateResult (HttpResponse::HttpResponseCode code,\n TRI_json_t const* json) {\n _response = createResponse(code);\n _response->setContentType(\"application\/json; charset=utf-8\");\n\n int res = TRI_StringifyJson(_response->body().stringBuffer(), json);\n\n if (res != TRI_ERROR_NO_ERROR) {\n generateError(HttpResponse::SERVER_ERROR,\n TRI_ERROR_INTERNAL,\n \"cannot generate output\");\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a result from VelocyPack\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateResult (VPackSlice& slice) {\n generateResult(HttpResponse::OK, slice);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a result from VelocyPack\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateResult (HttpResponse::HttpResponseCode code,\n VPackSlice& slice) {\n _response = createResponse(code);\n _response->setContentType(\"application\/json; charset=utf-8\");\n\n StringBufferAdapter buffer(_response->body().stringBuffer());\n\n StringBufferDumper dumper(buffer);\n try {\n dumper.dump(slice);\n }\n catch (...) {\n generateError(HttpResponse::SERVER_ERROR,\n TRI_ERROR_INTERNAL,\n \"cannot generate output\");\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates a cancel message\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateCanceled () {\n VPackBuilder builder;\n try {\n builder.add(VPackValue(VPackValueType::Object));\n builder.add(\"error\", VPackValue(true));\n builder.add(\"code\", VPackValue((int32_t) HttpResponse::REQUEST_TIMEOUT));\n builder.add(\"errorNum\", VPackValue((int32_t) TRI_ERROR_REQUEST_CANCELED));\n builder.add(\"errorMessage\", VPackValue(\"request canceled\"));\n builder.close();\n\n VPackSlice slice(builder.start());\n generateResult(HttpResponse::REQUEST_TIMEOUT, slice);\n } catch (...) {\n generateError(HttpResponse::SERVER_ERROR,\n TRI_ERROR_INTERNAL,\n \"cannot generate output\");\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates an error\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateError (HttpResponse::HttpResponseCode code,\n int errorCode) {\n char const* message = TRI_errno_string(errorCode);\n\n if (message) {\n generateError(code, errorCode, std::string(message));\n }\n else {\n generateError(code, errorCode, std::string(\"unknown error\"));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generates an error\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid RestBaseHandler::generateError (HttpResponse::HttpResponseCode code, int errorCode, std::string const& message) {\n\n _response = createResponse(code);\n _response->setContentType(\"application\/json; charset=utf-8\");\n\n VPackBuilder builder;\n try {\n builder.add(VPackValue(VPackValueType::Object));\n builder.add(\"error\", VPackValue(true));\n if (message.empty()) {\n \/\/ prevent empty error messages\n builder.add(\"errorMessage\", VPackValue(TRI_errno_string(errorCode)));\n }\n else {\n builder.add(\"errorMessage\", VPackValue(StringUtils::escapeUnicode(message)));\n }\n builder.add(\"code\", VPackValue(code));\n builder.add(\"errorNum\", VPackValue(errorCode));\n builder.close();\n VPackSlice slice(builder.start());\n StringBufferAdapter buffer(_response->body().stringBuffer());\n StringBufferDumper dumper(buffer);\n dumper.dump(slice);\n }\n catch (...) {\n \/\/ Building the error response failed\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tcommuni.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-03-18 16:03:49 $\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, 2002\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2002 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 EXPRESS 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: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#if SUPD >= 380\n#include <svtools\/communi.hxx>\n#else\n#include <communi.hxx>\n#endif\n#include <tools\/link.hxx>\n#include <svtools\/svarray.hxx>\n\n#include <vos\/thread.hxx>\n\n#ifndef _STRING_LIST\nDECLARE_LIST( StringList, String * );\n#define _STRING_LIST\n#endif\n\nclass Process;\n\nclass CommunicationManagerClientViaSocketTT : public CommunicationManagerClientViaSocket\n{\npublic:\n CommunicationManagerClientViaSocketTT();\n\n virtual BOOL StartCommunication();\n virtual BOOL StartCommunication( String aApp, String aParams );\n\nprotected:\n virtual BOOL RetryConnect();\n BOOL bApplicationStarted;\n Time aFirstRetryCall;\n String aAppPath;\n String aAppParams;\n Process *pProcess;\n};\n\n\nString GetHostConfig();\nULONG GetTTPortConfig();\nULONG GetUnoPortConfig();\n\n<commit_msg>INTEGRATION: CWS ause04 (1.2.22); FILE MERGED 2003\/07\/31 12:47:54 gh 1.2.22.1: removed 'if SUPD' precompiler stuff<commit_after>\/*************************************************************************\n *\n * $RCSfile: tcommuni.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2003-08-25 15:47: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, 2002\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2002 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 EXPRESS 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: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include <svtools\/communi.hxx>\n#include <tools\/link.hxx>\n#include <svtools\/svarray.hxx>\n\n#include <vos\/thread.hxx>\n\n#ifndef _STRING_LIST\nDECLARE_LIST( StringList, String * );\n#define _STRING_LIST\n#endif\n\nclass Process;\n\nclass CommunicationManagerClientViaSocketTT : public CommunicationManagerClientViaSocket\n{\npublic:\n CommunicationManagerClientViaSocketTT();\n\n virtual BOOL StartCommunication();\n virtual BOOL StartCommunication( String aApp, String aParams );\n\nprotected:\n virtual BOOL RetryConnect();\n BOOL bApplicationStarted;\n Time aFirstRetryCall;\n String aAppPath;\n String aAppParams;\n Process *pProcess;\n};\n\n\nString GetHostConfig();\nULONG GetTTPortConfig();\nULONG GetUnoPortConfig();\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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-CHROMIUM file.\n\n#include \"brightray\/browser\/browser_main_parts.h\"\n\n#include <stdlib.h>\n#include <sys\/stat.h>\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/feature_list.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"brightray\/browser\/browser_context.h\"\n#include \"brightray\/browser\/devtools_manager_delegate.h\"\n#include \"brightray\/browser\/web_ui_controller_factory.h\"\n#include \"brightray\/common\/application_info.h\"\n#include \"brightray\/common\/main_delegate.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"media\/base\/localized_strings.h\"\n#include \"net\/proxy\/proxy_resolver_v8.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/material_design\/material_design_controller.h\"\n\n#if defined(USE_AURA)\n#include \"ui\/display\/display.h\"\n#include \"ui\/display\/screen.h\"\n#include \"ui\/views\/widget\/desktop_aura\/desktop_screen.h\"\n#include \"ui\/wm\/core\/wm_state.h\"\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n#include \"brightray\/browser\/views\/views_delegate.h\"\n#endif\n\n#if defined(USE_X11)\n#include \"base\/environment.h\"\n#include \"base\/nix\/xdg_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/threading\/thread_task_runner_handle.h\"\n#include \"brightray\/browser\/brightray_paths.h\"\n#include \"chrome\/browser\/ui\/libgtkui\/gtk_ui.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/base\/x\/x11_util_internal.h\"\n#include \"ui\/views\/linux_ui\/linux_ui.h\"\n#endif\n\n#if defined(OS_WIN)\n#include \"ui\/base\/cursor\/cursor_loader_win.h\"\n#include \"ui\/base\/l10n\/l10n_util_win.h\"\n#include \"ui\/gfx\/platform_font_win.h\"\n#endif\n\n#if defined(OS_LINUX)\n#include \"device\/bluetooth\/bluetooth_adapter_factory.h\"\n#include \"device\/bluetooth\/dbus\/dbus_bluez_manager_wrapper_linux.h\"\n#endif\n\nnamespace brightray {\n\n\/\/ defined in browser_main_parts_mac\nvoid OverrideMacAppLogsPath();\n\nnamespace {\n\n#if defined(OS_WIN)\n\/\/ gfx::Font callbacks\nvoid AdjustUIFont(LOGFONT* logfont) {\n l10n_util::AdjustUIFont(logfont);\n}\n\nint GetMinimumFontSize() {\n return 10;\n}\n#endif\n\n#if defined(USE_X11)\n\/\/ Indicates that we're currently responding to an IO error (by shutting down).\nbool g_in_x11_io_error_handler = false;\n\n\/\/ Number of seconds to wait for UI thread to get an IO error if we get it on\n\/\/ the background thread.\nconst int kWaitForUIThreadSeconds = 10;\n\nvoid OverrideLinuxAppDataPath() {\n base::FilePath path;\n if (PathService::Get(DIR_APP_DATA, &path))\n return;\n std::unique_ptr<base::Environment> env(base::Environment::Create());\n path = base::nix::GetXDGDirectory(env.get(),\n base::nix::kXdgConfigHomeEnvVar,\n base::nix::kDotConfigDir);\n PathService::Override(DIR_APP_DATA, path);\n}\n\nvoid OverrideWinAppLogsPath() {\n std::string appName = GetApplicationName();\n std::string logPath = \"%HOMEDRIVE%%HOMEPATH%\\\\AppData\\\\Roaming\\\\\";\n std::string appLogPath = logPath + appName + \"\\\\logs\";\n\n int status = mkdir(appLogPath.c_str(), S_IRWXU | S_IRGRP | S_IROTH);\n\n PathService::Override(DIR_APP_LOGS, base::FilePath(appLogPath));\n}\n\nvoid OverrideLinuxAppLogsPath() {\n std::string appName = GetApplicationName();\n std::string homePath = std:string(getenv(\"HOME\"));\n std::string appLogPath = homePath + \"\/.config\/\" + appName + \"\/logs\";\n\n int status = mkdir(appLogPath.c_str(), S_IRWXU | S_IRGRP | S_IROTH);\n\n PathService::Override(DIR_APP_LOGS, base::FilePath(appLogPath));\n return;\n}\n\nint BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {\n if (!g_in_x11_io_error_handler) {\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));\n }\n return 0;\n}\n\n\/\/ This function is used to help us diagnose crash dumps that happen\n\/\/ during the shutdown process.\nNOINLINE void WaitingForUIThreadToHandleIOError() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(kWaitForUIThreadSeconds);\n}\n\nint BrowserX11IOErrorHandler(Display* d) {\n if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {\n \/\/ Wait for the UI thread (which has a different connection to the X server)\n \/\/ to get the error. We can't call shutdown from this thread without\n \/\/ tripping an error. Doing it through a function so that we'll be able\n \/\/ to see it in any crash dumps.\n WaitingForUIThreadToHandleIOError();\n return 0;\n }\n\n \/\/ If there's an IO error it likely means the X server has gone away.\n \/\/ If this CHECK fails, then that means SessionEnding() below triggered some\n \/\/ code that tried to talk to the X server, resulting in yet another error.\n CHECK(!g_in_x11_io_error_handler);\n\n g_in_x11_io_error_handler = true;\n LOG(ERROR) << \"X IO error received (X server probably went away)\";\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());\n\n return 0;\n}\n\nint X11EmptyErrorHandler(Display* d, XErrorEvent* error) {\n return 0;\n}\n\nint X11EmptyIOErrorHandler(Display* d) {\n return 0;\n}\n#endif\n\nbase::string16 MediaStringProvider(media::MessageId id) {\n switch (id) {\n case media::DEFAULT_AUDIO_DEVICE_NAME:\n return base::ASCIIToUTF16(\"Default\");\n#if defined(OS_WIN)\n case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:\n return base::ASCIIToUTF16(\"Communications\");\n#endif\n default:\n return base::string16();\n }\n}\n\n} \/\/ namespace\n\nBrowserMainParts::BrowserMainParts() {\n}\n\nBrowserMainParts::~BrowserMainParts() {\n}\n\nvoid BrowserMainParts::PreEarlyInitialization() {\n std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);\n feature_list->InitializeFromCommandLine(\"\", \"\");\n base::FeatureList::SetInstance(std::move(feature_list));\n#if defined(OS_MACOSX)\n OverrideMacAppLogsPath();\n#endif\n#if defined(OS_LINUX)\n OverrideLinuxAppLogsPath();\n#endif\n#if defined(OS_WIN)\n OverrideWinAppLogsPath();\n#endif\n#if defined(USE_X11)\n views::LinuxUI::SetInstance(BuildGtkUi());\n OverrideLinuxAppDataPath();\n\n \/\/ Installs the X11 error handlers for the browser process used during\n \/\/ startup. They simply print error messages and exit because\n \/\/ we can't shutdown properly while creating and initializing services.\n ui::SetX11ErrorHandlers(nullptr, nullptr);\n#endif\n}\n\nvoid BrowserMainParts::ToolkitInitialized() {\n ui::MaterialDesignController::Initialize();\n\n#if defined(USE_AURA) && defined(USE_X11)\n views::LinuxUI::instance()->Initialize();\n#endif\n\n#if defined(USE_AURA)\n wm_state_.reset(new wm::WMState);\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n views_delegate_.reset(new ViewsDelegate);\n#endif\n\n#if defined(OS_WIN)\n gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;\n gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;\n\n wchar_t module_name[MAX_PATH] = { 0 };\n if (GetModuleFileName(NULL, module_name, MAX_PATH))\n ui::CursorLoaderWin::SetCursorResourceModule(module_name);\n#endif\n}\n\nvoid BrowserMainParts::PreMainMessageLoopStart() {\n#if defined(OS_MACOSX)\n l10n_util::OverrideLocaleWithCocoaLocale();\n#endif\n InitializeResourceBundle(\"\");\n#if defined(OS_MACOSX)\n InitializeMainNib();\n#endif\n media::SetLocalizedStringProvider(MediaStringProvider);\n}\n\nvoid BrowserMainParts::PreMainMessageLoopRun() {\n content::WebUIControllerFactory::RegisterFactory(\n WebUIControllerFactory::GetInstance());\n\n \/\/ --remote-debugging-port\n auto command_line = base::CommandLine::ForCurrentProcess();\n if (command_line->HasSwitch(switches::kRemoteDebuggingPort))\n DevToolsManagerDelegate::StartHttpHandler();\n}\n\nvoid BrowserMainParts::PostMainMessageLoopStart() {\n#if defined(USE_X11)\n \/\/ Installs the X11 error handlers for the browser process after the\n \/\/ main message loop has started. This will allow us to exit cleanly\n \/\/ if X exits before us.\n ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);\n#endif\n#if defined(OS_LINUX)\n bluez::DBusBluezManagerWrapperLinux::Initialize();\n#endif\n}\n\nvoid BrowserMainParts::PostMainMessageLoopRun() {\n#if defined(USE_X11)\n \/\/ Unset the X11 error handlers. The X11 error handlers log the errors using a\n \/\/ |PostTask()| on the message-loop. But since the message-loop is in the\n \/\/ process of terminating, this can cause errors.\n ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);\n#endif\n}\n\nint BrowserMainParts::PreCreateThreads() {\n#if defined(USE_AURA)\n display::Screen* screen = views::CreateDesktopScreen();\n display::Screen::SetScreenInstance(screen);\n#if defined(USE_X11)\n views::LinuxUI::instance()->UpdateDeviceScaleFactor();\n#endif\n#endif\n\n if (!views::LayoutProvider::Get())\n layout_provider_.reset(new views::LayoutProvider());\n\n return 0;\n}\n\nvoid BrowserMainParts::PostDestroyThreads() {\n#if defined(OS_LINUX)\n device::BluetoothAdapterFactory::Shutdown();\n bluez::DBusBluezManagerWrapperLinux::Shutdown();\n#endif\n}\n\n} \/\/ namespace brightray\n<commit_msg>fix incorrect std namespacing<commit_after>\/\/ 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-CHROMIUM file.\n\n#include \"brightray\/browser\/browser_main_parts.h\"\n\n#include <stdlib.h>\n#include <sys\/stat.h>\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/feature_list.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"brightray\/browser\/browser_context.h\"\n#include \"brightray\/browser\/devtools_manager_delegate.h\"\n#include \"brightray\/browser\/web_ui_controller_factory.h\"\n#include \"brightray\/common\/application_info.h\"\n#include \"brightray\/common\/main_delegate.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"media\/base\/localized_strings.h\"\n#include \"net\/proxy\/proxy_resolver_v8.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/material_design\/material_design_controller.h\"\n\n#if defined(USE_AURA)\n#include \"ui\/display\/display.h\"\n#include \"ui\/display\/screen.h\"\n#include \"ui\/views\/widget\/desktop_aura\/desktop_screen.h\"\n#include \"ui\/wm\/core\/wm_state.h\"\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n#include \"brightray\/browser\/views\/views_delegate.h\"\n#endif\n\n#if defined(USE_X11)\n#include \"base\/environment.h\"\n#include \"base\/nix\/xdg_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/threading\/thread_task_runner_handle.h\"\n#include \"brightray\/browser\/brightray_paths.h\"\n#include \"chrome\/browser\/ui\/libgtkui\/gtk_ui.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/base\/x\/x11_util_internal.h\"\n#include \"ui\/views\/linux_ui\/linux_ui.h\"\n#endif\n\n#if defined(OS_WIN)\n#include \"ui\/base\/cursor\/cursor_loader_win.h\"\n#include \"ui\/base\/l10n\/l10n_util_win.h\"\n#include \"ui\/gfx\/platform_font_win.h\"\n#endif\n\n#if defined(OS_LINUX)\n#include \"device\/bluetooth\/bluetooth_adapter_factory.h\"\n#include \"device\/bluetooth\/dbus\/dbus_bluez_manager_wrapper_linux.h\"\n#endif\n\nnamespace brightray {\n\n\/\/ defined in browser_main_parts_mac\nvoid OverrideMacAppLogsPath();\n\nnamespace {\n\n#if defined(OS_WIN)\n\/\/ gfx::Font callbacks\nvoid AdjustUIFont(LOGFONT* logfont) {\n l10n_util::AdjustUIFont(logfont);\n}\n\nint GetMinimumFontSize() {\n return 10;\n}\n#endif\n\n#if defined(USE_X11)\n\/\/ Indicates that we're currently responding to an IO error (by shutting down).\nbool g_in_x11_io_error_handler = false;\n\n\/\/ Number of seconds to wait for UI thread to get an IO error if we get it on\n\/\/ the background thread.\nconst int kWaitForUIThreadSeconds = 10;\n\nvoid OverrideLinuxAppDataPath() {\n base::FilePath path;\n if (PathService::Get(DIR_APP_DATA, &path))\n return;\n std::unique_ptr<base::Environment> env(base::Environment::Create());\n path = base::nix::GetXDGDirectory(env.get(),\n base::nix::kXdgConfigHomeEnvVar,\n base::nix::kDotConfigDir);\n PathService::Override(DIR_APP_DATA, path);\n}\n\nvoid OverrideWinAppLogsPath() {\n std::string appName = GetApplicationName();\n std::string logPath = \"%HOMEDRIVE%%HOMEPATH%\\\\AppData\\\\Roaming\\\\\";\n std::string appLogPath = logPath + appName + \"\\\\logs\";\n\n int status = mkdir(appLogPath.c_str(), S_IRWXU | S_IRGRP | S_IROTH);\n\n PathService::Override(DIR_APP_LOGS, base::FilePath(appLogPath));\n}\n\nvoid OverrideLinuxAppLogsPath() {\n std::string appName = GetApplicationName();\n std::string homePath = std::string(getenv(\"HOME\"));\n std::string appLogPath = homePath + \"\/.config\/\" + appName + \"\/logs\";\n\n int status = mkdir(appLogPath.c_str(), S_IRWXU | S_IRGRP | S_IROTH);\n\n PathService::Override(DIR_APP_LOGS, base::FilePath(appLogPath));\n return;\n}\n\nint BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {\n if (!g_in_x11_io_error_handler) {\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));\n }\n return 0;\n}\n\n\/\/ This function is used to help us diagnose crash dumps that happen\n\/\/ during the shutdown process.\nNOINLINE void WaitingForUIThreadToHandleIOError() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(kWaitForUIThreadSeconds);\n}\n\nint BrowserX11IOErrorHandler(Display* d) {\n if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {\n \/\/ Wait for the UI thread (which has a different connection to the X server)\n \/\/ to get the error. We can't call shutdown from this thread without\n \/\/ tripping an error. Doing it through a function so that we'll be able\n \/\/ to see it in any crash dumps.\n WaitingForUIThreadToHandleIOError();\n return 0;\n }\n\n \/\/ If there's an IO error it likely means the X server has gone away.\n \/\/ If this CHECK fails, then that means SessionEnding() below triggered some\n \/\/ code that tried to talk to the X server, resulting in yet another error.\n CHECK(!g_in_x11_io_error_handler);\n\n g_in_x11_io_error_handler = true;\n LOG(ERROR) << \"X IO error received (X server probably went away)\";\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());\n\n return 0;\n}\n\nint X11EmptyErrorHandler(Display* d, XErrorEvent* error) {\n return 0;\n}\n\nint X11EmptyIOErrorHandler(Display* d) {\n return 0;\n}\n#endif\n\nbase::string16 MediaStringProvider(media::MessageId id) {\n switch (id) {\n case media::DEFAULT_AUDIO_DEVICE_NAME:\n return base::ASCIIToUTF16(\"Default\");\n#if defined(OS_WIN)\n case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:\n return base::ASCIIToUTF16(\"Communications\");\n#endif\n default:\n return base::string16();\n }\n}\n\n} \/\/ namespace\n\nBrowserMainParts::BrowserMainParts() {\n}\n\nBrowserMainParts::~BrowserMainParts() {\n}\n\nvoid BrowserMainParts::PreEarlyInitialization() {\n std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);\n feature_list->InitializeFromCommandLine(\"\", \"\");\n base::FeatureList::SetInstance(std::move(feature_list));\n#if defined(OS_MACOSX)\n OverrideMacAppLogsPath();\n#endif\n#if defined(OS_LINUX)\n OverrideLinuxAppLogsPath();\n#endif\n#if defined(OS_WIN)\n OverrideWinAppLogsPath();\n#endif\n#if defined(USE_X11)\n views::LinuxUI::SetInstance(BuildGtkUi());\n OverrideLinuxAppDataPath();\n\n \/\/ Installs the X11 error handlers for the browser process used during\n \/\/ startup. They simply print error messages and exit because\n \/\/ we can't shutdown properly while creating and initializing services.\n ui::SetX11ErrorHandlers(nullptr, nullptr);\n#endif\n}\n\nvoid BrowserMainParts::ToolkitInitialized() {\n ui::MaterialDesignController::Initialize();\n\n#if defined(USE_AURA) && defined(USE_X11)\n views::LinuxUI::instance()->Initialize();\n#endif\n\n#if defined(USE_AURA)\n wm_state_.reset(new wm::WMState);\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n views_delegate_.reset(new ViewsDelegate);\n#endif\n\n#if defined(OS_WIN)\n gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;\n gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;\n\n wchar_t module_name[MAX_PATH] = { 0 };\n if (GetModuleFileName(NULL, module_name, MAX_PATH))\n ui::CursorLoaderWin::SetCursorResourceModule(module_name);\n#endif\n}\n\nvoid BrowserMainParts::PreMainMessageLoopStart() {\n#if defined(OS_MACOSX)\n l10n_util::OverrideLocaleWithCocoaLocale();\n#endif\n InitializeResourceBundle(\"\");\n#if defined(OS_MACOSX)\n InitializeMainNib();\n#endif\n media::SetLocalizedStringProvider(MediaStringProvider);\n}\n\nvoid BrowserMainParts::PreMainMessageLoopRun() {\n content::WebUIControllerFactory::RegisterFactory(\n WebUIControllerFactory::GetInstance());\n\n \/\/ --remote-debugging-port\n auto command_line = base::CommandLine::ForCurrentProcess();\n if (command_line->HasSwitch(switches::kRemoteDebuggingPort))\n DevToolsManagerDelegate::StartHttpHandler();\n}\n\nvoid BrowserMainParts::PostMainMessageLoopStart() {\n#if defined(USE_X11)\n \/\/ Installs the X11 error handlers for the browser process after the\n \/\/ main message loop has started. This will allow us to exit cleanly\n \/\/ if X exits before us.\n ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);\n#endif\n#if defined(OS_LINUX)\n bluez::DBusBluezManagerWrapperLinux::Initialize();\n#endif\n}\n\nvoid BrowserMainParts::PostMainMessageLoopRun() {\n#if defined(USE_X11)\n \/\/ Unset the X11 error handlers. The X11 error handlers log the errors using a\n \/\/ |PostTask()| on the message-loop. But since the message-loop is in the\n \/\/ process of terminating, this can cause errors.\n ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);\n#endif\n}\n\nint BrowserMainParts::PreCreateThreads() {\n#if defined(USE_AURA)\n display::Screen* screen = views::CreateDesktopScreen();\n display::Screen::SetScreenInstance(screen);\n#if defined(USE_X11)\n views::LinuxUI::instance()->UpdateDeviceScaleFactor();\n#endif\n#endif\n\n if (!views::LayoutProvider::Get())\n layout_provider_.reset(new views::LayoutProvider());\n\n return 0;\n}\n\nvoid BrowserMainParts::PostDestroyThreads() {\n#if defined(OS_LINUX)\n device::BluetoothAdapterFactory::Shutdown();\n bluez::DBusBluezManagerWrapperLinux::Shutdown();\n#endif\n}\n\n} \/\/ namespace brightray\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: PageMasterImportPropMapper.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: sab $ $Date: 2000-10-26 10:35:27 $\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#pragma hdrstop\n\n#ifndef _XMLOFF_PAGEMASTERIMPORTPROPMAPPER_HXX\n#include \"PageMasterImportPropMapper.hxx\"\n#endif\n#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX\n#include \"PageMasterPropMapper.hxx\"\n#endif\n#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX\n#include \"PageMasterStyleMap.hxx\"\n#endif\n\n#ifndef _XMLOFF_PROPMAPPINGTYPES_HXX\n#include <xmloff\/maptype.hxx>\n#endif\n\nusing namespace ::com::sun::star;\n\nPageMasterImportPropertyMapper::PageMasterImportPropertyMapper(\n const UniReference< XMLPropertySetMapper >& rMapper ) :\n SvXMLImportPropertyMapper( rMapper )\n{\n}\n\nPageMasterImportPropertyMapper::~PageMasterImportPropertyMapper()\n{\n}\n\n\/*sal_Bool PageMasterImportPropertyMapper::handleSpecialItem(\n XMLPropertyState& rProperty,\n ::std::vector< XMLPropertyState >& rProperties,\n const ::rtl::OUString& rValue,\n const SvXMLUnitConverter& rUnitConverter,\n const SvXMLNamespaceMap& rNamespaceMap ) const\n{\n return sal_True;\n}*\/\n\n\/*sal_Bool PageMasterImportPropertyMapper::handleNoItem(\n sal_Int32 nIndex,\n ::std::vector< XMLPropertyState >& rProperties,\n const ::rtl::OUString& rValue,\n const SvXMLUnitConverter& rUnitConverter,\n const SvXMLNamespaceMap& rNamespaceMap ) const\n{\n return sal_True;\n}*\/\n\nvoid PageMasterImportPropertyMapper::finished(::std::vector< XMLPropertyState >& rProperties, sal_Int32 nStartIndex, sal_Int32 nEndIndex ) const\n{\n SvXMLImportPropertyMapper::finished(rProperties, nStartIndex, nEndIndex);\n XMLPropertyState* pAllPaddingProperty = NULL;\n XMLPropertyState* pAllBorderProperty = NULL;\n XMLPropertyState* pAllBorderWidthProperty = NULL;\n XMLPropertyState* pAllHeaderPaddingProperty = NULL;\n XMLPropertyState* pAllHeaderBorderProperty = NULL;\n XMLPropertyState* pAllHeaderBorderWidthProperty = NULL;\n XMLPropertyState* pAllFooterPaddingProperty = NULL;\n XMLPropertyState* pAllFooterBorderProperty = NULL;\n XMLPropertyState* pAllFooterBorderWidthProperty = NULL;\n XMLPropertyState* pHeaderHeight = NULL;\n XMLPropertyState* pHeaderMinHeight = NULL;\n XMLPropertyState* pFooterHeight = NULL;\n XMLPropertyState* pFooterMinHeight = NULL;\n ::std::vector< XMLPropertyState >::iterator i = rProperties.begin();\n for (i; i != rProperties.end(); i++)\n {\n sal_Int16 nContextID = getPropertySetMapper()->GetEntryContextId(i->mnIndex);\n switch (nContextID)\n {\n case CTF_PM_PADDINGALL :\n {\n pAllPaddingProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_BORDERALL :\n {\n pAllBorderProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_BORDERWIDTHALL :\n {\n pAllBorderWidthProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_HEADERPADDINGALL :\n {\n pAllHeaderPaddingProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_HEADERBORDERALL :\n {\n pAllHeaderBorderProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_HEADERBORDERWIDTHALL :\n {\n pAllHeaderBorderWidthProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_FOOTERPADDINGALL :\n {\n pAllFooterPaddingProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_FOOTERBORDERALL :\n {\n pAllFooterBorderProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_FOOTERBORDERWIDTHALL :\n {\n pAllFooterBorderWidthProperty = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_HEADERHEIGHT :\n {\n pHeaderHeight = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_HEADERMINHEIGHT :\n {\n pHeaderMinHeight = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_FOOTERHEIGHT :\n {\n pFooterHeight = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n case CTF_PM_FOOTERMINHEIGHT :\n {\n pFooterMinHeight = new XMLPropertyState(i->mnIndex, i->maValue);\n }\n break;\n }\n }\n if (pAllPaddingProperty)\n {\n sal_Int32 nIndex = pAllPaddingProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllPaddingProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pAllBorderProperty)\n {\n sal_Int32 nIndex = pAllBorderProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllBorderProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pAllBorderWidthProperty)\n {\n sal_Int32 nIndex = pAllBorderWidthProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllBorderWidthProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pAllHeaderPaddingProperty)\n {\n sal_Int32 nIndex = pAllHeaderPaddingProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllHeaderPaddingProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pAllHeaderBorderProperty)\n {\n sal_Int32 nIndex = pAllHeaderBorderProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllHeaderBorderProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pAllHeaderBorderWidthProperty)\n {\n sal_Int32 nIndex = pAllHeaderBorderWidthProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllHeaderBorderWidthProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pAllFooterPaddingProperty)\n {\n sal_Int32 nIndex = pAllFooterPaddingProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllFooterPaddingProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pAllFooterBorderProperty)\n {\n sal_Int32 nIndex = pAllFooterBorderProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllFooterBorderProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pAllFooterBorderWidthProperty)\n {\n sal_Int32 nIndex = pAllFooterBorderWidthProperty->mnIndex + 2;\n XMLPropertyState aNewProperty (nIndex, pAllFooterBorderWidthProperty->maValue);\n for (sal_Int16 j = 0; j < 3; j++)\n {\n aNewProperty.mnIndex = nIndex++;\n rProperties.push_back(aNewProperty);\n }\n }\n if (pHeaderHeight)\n {\n sal_Bool bValue(sal_False);\n uno::Any aAny;\n aAny.setValue( &bValue, ::getBooleanCppuType() );\n XMLPropertyState aNewProperty(pHeaderHeight->mnIndex + 2, aAny);\n rProperties.push_back(aNewProperty);\n }\n if (pHeaderMinHeight)\n {\n sal_Bool bValue(sal_True);\n uno::Any aAny;\n aAny.setValue( &bValue, ::getBooleanCppuType() );\n XMLPropertyState aNewProperty(pHeaderMinHeight->mnIndex + 1, aAny);\n rProperties.push_back(aNewProperty);\n }\n if (pFooterHeight)\n {\n sal_Bool bValue(sal_False);\n uno::Any aAny;\n aAny.setValue( &bValue, ::getBooleanCppuType() );\n XMLPropertyState aNewProperty(pFooterHeight->mnIndex + 2, aAny);\n rProperties.push_back(aNewProperty);\n }\n if (pFooterMinHeight)\n {\n sal_Bool bValue(sal_True);\n uno::Any aAny;\n aAny.setValue( &bValue, ::getBooleanCppuType() );\n XMLPropertyState aNewProperty(pFooterMinHeight->mnIndex + 1, aAny);\n rProperties.push_back(aNewProperty);\n }\n}\n\n<commit_msg>increase the performance and merge the border with border_width<commit_after>\/*************************************************************************\n *\n * $RCSfile: PageMasterImportPropMapper.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: sab $ $Date: 2000-10-27 03:56:15 $\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#pragma hdrstop\n\n#ifndef _XMLOFF_PAGEMASTERIMPORTPROPMAPPER_HXX\n#include \"PageMasterImportPropMapper.hxx\"\n#endif\n#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX\n#include \"PageMasterPropMapper.hxx\"\n#endif\n#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX\n#include \"PageMasterStyleMap.hxx\"\n#endif\n\n#ifndef _XMLOFF_PROPMAPPINGTYPES_HXX\n#include \"maptype.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_\n#include <com\/sun\/star\/table\/BorderLine.hpp>\n#endif\n\n#define XML_LINE_LEFT 0\n#define XML_LINE_RIGHT 0\n#define XML_LINE_TOP 0\n#define XML_LINE_BOTTOM 0\n\nusing namespace ::com::sun::star;\n\nPageMasterImportPropertyMapper::PageMasterImportPropertyMapper(\n const UniReference< XMLPropertySetMapper >& rMapper ) :\n SvXMLImportPropertyMapper( rMapper )\n{\n}\n\nPageMasterImportPropertyMapper::~PageMasterImportPropertyMapper()\n{\n}\n\n\/*sal_Bool PageMasterImportPropertyMapper::handleSpecialItem(\n XMLPropertyState& rProperty,\n ::std::vector< XMLPropertyState >& rProperties,\n const ::rtl::OUString& rValue,\n const SvXMLUnitConverter& rUnitConverter,\n const SvXMLNamespaceMap& rNamespaceMap ) const\n{\n return sal_True;\n}*\/\n\n\/*sal_Bool PageMasterImportPropertyMapper::handleNoItem(\n sal_Int32 nIndex,\n ::std::vector< XMLPropertyState >& rProperties,\n const ::rtl::OUString& rValue,\n const SvXMLUnitConverter& rUnitConverter,\n const SvXMLNamespaceMap& rNamespaceMap ) const\n{\n return sal_True;\n}*\/\n\nvoid PageMasterImportPropertyMapper::finished(::std::vector< XMLPropertyState >& rProperties, sal_Int32 nStartIndex, sal_Int32 nEndIndex ) const\n{\n SvXMLImportPropertyMapper::finished(rProperties, nStartIndex, nEndIndex);\n XMLPropertyState* pAllPaddingProperty = NULL;\n XMLPropertyState* pPadding[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pNewPadding[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pAllBorderProperty = NULL;\n XMLPropertyState* pBorders[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pNewBorders[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pAllBorderWidthProperty = NULL;\n XMLPropertyState* pBorderWidths[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pAllHeaderPaddingProperty = NULL;\n XMLPropertyState* pHeaderPadding[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pHeaderNewPadding[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pAllHeaderBorderProperty = NULL;\n XMLPropertyState* pHeaderBorders[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pHeaderNewBorders[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pAllHeaderBorderWidthProperty = NULL;\n XMLPropertyState* pHeaderBorderWidths[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pAllFooterPaddingProperty = NULL;\n XMLPropertyState* pFooterPadding[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pFooterNewPadding[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pAllFooterBorderProperty = NULL;\n XMLPropertyState* pFooterBorders[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pFooterNewBorders[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pAllFooterBorderWidthProperty = NULL;\n XMLPropertyState* pFooterBorderWidths[4] = { NULL, NULL, NULL, NULL };\n XMLPropertyState* pHeaderHeight = NULL;\n XMLPropertyState* pHeaderMinHeight = NULL;\n XMLPropertyState* pHeaderDynamic = NULL;\n XMLPropertyState* pFooterHeight = NULL;\n XMLPropertyState* pFooterMinHeight = NULL;\n XMLPropertyState* pFooterDynamic = NULL;\n ::std::vector< XMLPropertyState >::iterator property = rProperties.begin();\n for (property; property != rProperties.end(); property++)\n {\n sal_Int16 nContextID = getPropertySetMapper()->GetEntryContextId(property->mnIndex);\n if (property->mnIndex >= nStartIndex && property->mnIndex < nEndIndex)\n {\n switch (nContextID)\n {\n case CTF_PM_PADDINGALL : pAllPaddingProperty = property; break;\n case CTF_PM_PADDINGLEFT : pPadding[XML_LINE_LEFT] = property; break;\n case CTF_PM_PADDINGRIGHT : pPadding[XML_LINE_RIGHT] = property; break;\n case CTF_PM_PADDINGTOP : pPadding[XML_LINE_TOP] = property; break;\n case CTF_PM_PADDINGBOTTOM : pPadding[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_BORDERALL : pAllBorderProperty = property; break;\n case CTF_PM_BORDERLEFT : pBorders[XML_LINE_LEFT] = property; break;\n case CTF_PM_BORDERRIGHT : pBorders[XML_LINE_RIGHT] = property; break;\n case CTF_PM_BORDERTOP : pBorders[XML_LINE_TOP] = property; break;\n case CTF_PM_BORDERBOTTOM : pBorders[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_BORDERWIDTHALL : pAllBorderWidthProperty = property; break;\n case CTF_PM_BORDERWIDTHLEFT : pBorderWidths[XML_LINE_LEFT] = property; break;\n case CTF_PM_BORDERWIDTHRIGHT : pBorderWidths[XML_LINE_RIGHT] = property; break;\n case CTF_PM_BORDERWIDTHTOP : pBorderWidths[XML_LINE_TOP] = property; break;\n case CTF_PM_BORDERWIDTHBOTTOM : pBorderWidths[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_HEADERPADDINGALL : pAllHeaderPaddingProperty = property; break;\n case CTF_PM_HEADERPADDINGLEFT : pHeaderPadding[XML_LINE_LEFT] = property; break;\n case CTF_PM_HEADERPADDINGRIGHT : pHeaderPadding[XML_LINE_RIGHT] = property; break;\n case CTF_PM_HEADERPADDINGTOP : pHeaderPadding[XML_LINE_TOP] = property; break;\n case CTF_PM_HEADERPADDINGBOTTOM : pHeaderPadding[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_HEADERBORDERALL : pAllHeaderBorderProperty = property; break;\n case CTF_PM_HEADERBORDERLEFT : pHeaderBorders[XML_LINE_LEFT] = property; break;\n case CTF_PM_HEADERBORDERRIGHT : pHeaderBorders[XML_LINE_RIGHT] = property; break;\n case CTF_PM_HEADERBORDERTOP : pHeaderBorders[XML_LINE_TOP] = property; break;\n case CTF_PM_HEADERBORDERBOTTOM : pHeaderBorders[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_HEADERBORDERWIDTHALL : pAllHeaderBorderWidthProperty = property; break;\n case CTF_PM_HEADERBORDERWIDTHLEFT : pHeaderBorderWidths[XML_LINE_LEFT] = property; break;\n case CTF_PM_HEADERBORDERWIDTHRIGHT : pHeaderBorderWidths[XML_LINE_RIGHT] = property; break;\n case CTF_PM_HEADERBORDERWIDTHTOP : pHeaderBorderWidths[XML_LINE_TOP] = property; break;\n case CTF_PM_HEADERBORDERWIDTHBOTTOM : pHeaderBorderWidths[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_FOOTERPADDINGALL : pAllFooterPaddingProperty = property; break;\n case CTF_PM_FOOTERPADDINGLEFT : pFooterPadding[XML_LINE_LEFT] = property; break;\n case CTF_PM_FOOTERPADDINGRIGHT : pFooterPadding[XML_LINE_RIGHT] = property; break;\n case CTF_PM_FOOTERPADDINGTOP : pFooterPadding[XML_LINE_TOP] = property; break;\n case CTF_PM_FOOTERPADDINGBOTTOM : pFooterPadding[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_FOOTERBORDERALL : pAllFooterBorderProperty = property; break;\n case CTF_PM_FOOTERBORDERLEFT : pFooterBorders[XML_LINE_LEFT] = property; break;\n case CTF_PM_FOOTERBORDERRIGHT : pFooterBorders[XML_LINE_RIGHT] = property; break;\n case CTF_PM_FOOTERBORDERTOP : pFooterBorders[XML_LINE_TOP] = property; break;\n case CTF_PM_FOOTERBORDERBOTTOM : pFooterBorders[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_FOOTERBORDERWIDTHALL : pAllFooterBorderWidthProperty = property; break;\n case CTF_PM_FOOTERBORDERWIDTHLEFT : pFooterBorderWidths[XML_LINE_LEFT] = property; break;\n case CTF_PM_FOOTERBORDERWIDTHRIGHT : pFooterBorderWidths[XML_LINE_RIGHT] = property; break;\n case CTF_PM_FOOTERBORDERWIDTHTOP : pFooterBorderWidths[XML_LINE_TOP] = property; break;\n case CTF_PM_FOOTERBORDERWIDTHBOTTOM : pFooterBorderWidths[XML_LINE_BOTTOM] = property; break;\n case CTF_PM_HEADERHEIGHT : pHeaderHeight = property; break;\n case CTF_PM_HEADERMINHEIGHT : pHeaderMinHeight = property; break;\n case CTF_PM_FOOTERHEIGHT : pFooterHeight = property; break;\n case CTF_PM_FOOTERMINHEIGHT : pFooterMinHeight = property; break;\n }\n }\n }\n\n for (sal_uInt16 i = 0; i < 4; i++)\n {\n if (pAllPaddingProperty && !pPadding[i])\n pNewPadding[i] = new XMLPropertyState(pAllPaddingProperty->mnIndex + 1 + i, pAllPaddingProperty->maValue);\n if (pAllBorderProperty && !pBorders[i])\n {\n pNewBorders[i] = new XMLPropertyState(pAllBorderProperty->mnIndex + 1 + i, pAllBorderProperty->maValue);\n pBorders[i] = pNewBorders[i];\n }\n if( !pBorderWidths[i] )\n pBorderWidths[i] = pAllBorderWidthProperty;\n else\n pBorderWidths[i]->mnIndex = -1;\n if( pBorders[i] )\n {\n table::BorderLine aBorderLine;\n pBorders[i]->maValue >>= aBorderLine;\n if( pBorderWidths[i] )\n {\n table::BorderLine aBorderLineWidth;\n pBorderWidths[i]->maValue >>= aBorderLineWidth;\n aBorderLine.OuterLineWidth = aBorderLineWidth.OuterLineWidth;\n aBorderLine.InnerLineWidth = aBorderLineWidth.InnerLineWidth;\n aBorderLine.LineDistance = aBorderLineWidth.LineDistance;\n pBorders[i]->maValue <<= aBorderLine;\n }\n }\n if (pAllHeaderPaddingProperty && !pHeaderPadding[i])\n pHeaderNewPadding[i] = new XMLPropertyState(pAllHeaderPaddingProperty->mnIndex + 1 + i, pAllHeaderPaddingProperty->maValue);\n if (pAllHeaderBorderProperty && !pHeaderBorders[i])\n pHeaderNewBorders[i] = new XMLPropertyState(pAllHeaderBorderProperty->mnIndex + 1 + i, pAllHeaderBorderProperty->maValue);\n if( !pHeaderBorderWidths[i] )\n pHeaderBorderWidths[i] = pAllHeaderBorderWidthProperty;\n else\n pHeaderBorderWidths[i]->mnIndex = -1;\n if( pHeaderBorders[i] )\n {\n table::BorderLine aBorderLine;\n pHeaderBorders[i]->maValue >>= aBorderLine;\n if( pHeaderBorderWidths[i] )\n {\n table::BorderLine aBorderLineWidth;\n pHeaderBorderWidths[i]->maValue >>= aBorderLineWidth;\n aBorderLine.OuterLineWidth = aBorderLineWidth.OuterLineWidth;\n aBorderLine.InnerLineWidth = aBorderLineWidth.InnerLineWidth;\n aBorderLine.LineDistance = aBorderLineWidth.LineDistance;\n pHeaderBorders[i]->maValue <<= aBorderLine;\n }\n }\n if (pAllFooterPaddingProperty && !pFooterPadding[i])\n pFooterNewPadding[i] = new XMLPropertyState(pAllFooterPaddingProperty->mnIndex + 1 + i, pAllFooterPaddingProperty->maValue);\n if (pAllFooterBorderProperty && !pFooterBorders[i])\n pFooterNewBorders[i] = new XMLPropertyState(pAllFooterBorderProperty->mnIndex + 1 + i, pAllFooterBorderProperty->maValue);\n if( !pFooterBorderWidths[i] )\n pFooterBorderWidths[i] = pAllFooterBorderWidthProperty;\n else\n pFooterBorderWidths[i]->mnIndex = -1;\n if( pFooterBorders[i] )\n {\n table::BorderLine aBorderLine;\n pFooterBorders[i]->maValue >>= aBorderLine;\n if( pFooterBorderWidths[i] )\n {\n table::BorderLine aBorderLineWidth;\n pFooterBorderWidths[i]->maValue >>= aBorderLineWidth;\n aBorderLine.OuterLineWidth = aBorderLineWidth.OuterLineWidth;\n aBorderLine.InnerLineWidth = aBorderLineWidth.InnerLineWidth;\n aBorderLine.LineDistance = aBorderLineWidth.LineDistance;\n pFooterBorders[i]->maValue <<= aBorderLine;\n }\n }\n }\n\n if (pHeaderHeight)\n {\n sal_Bool bValue(sal_False);\n uno::Any aAny;\n aAny.setValue( &bValue, ::getBooleanCppuType() );\n pHeaderDynamic = new XMLPropertyState(pHeaderHeight->mnIndex + 2, aAny);\n }\n if (pHeaderMinHeight)\n {\n sal_Bool bValue(sal_True);\n uno::Any aAny;\n aAny.setValue( &bValue, ::getBooleanCppuType() );\n pHeaderDynamic = new XMLPropertyState(pHeaderMinHeight->mnIndex + 1, aAny);\n }\n if (pFooterHeight)\n {\n sal_Bool bValue(sal_False);\n uno::Any aAny;\n aAny.setValue( &bValue, ::getBooleanCppuType() );\n pFooterDynamic = new XMLPropertyState(pFooterHeight->mnIndex + 2, aAny);\n }\n if (pFooterMinHeight)\n {\n sal_Bool bValue(sal_True);\n uno::Any aAny;\n aAny.setValue( &bValue, ::getBooleanCppuType() );\n pFooterDynamic = new XMLPropertyState(pFooterMinHeight->mnIndex + 1, aAny);\n }\n for (i = 0; i < 4; i++)\n {\n if (pNewPadding[i])\n {\n rProperties.push_back(*pNewPadding[i]);\n delete pNewPadding[i];\n }\n if (pNewBorders[i])\n {\n rProperties.push_back(*pNewBorders[i]);\n delete pNewBorders[i];\n }\n if (pHeaderNewPadding[i])\n {\n rProperties.push_back(*pHeaderNewPadding[i]);\n delete pHeaderNewPadding[i];\n }\n if (pHeaderNewBorders[i])\n {\n rProperties.push_back(*pHeaderNewBorders[i]);\n delete pHeaderNewBorders[i];\n }\n if (pFooterNewPadding[i])\n {\n rProperties.push_back(*pFooterNewPadding[i]);\n delete pFooterNewPadding[i];\n }\n if (pFooterNewBorders[i])\n {\n rProperties.push_back(*pFooterNewBorders[i]);\n delete pFooterNewBorders[i];\n }\n }\n if(pHeaderDynamic)\n {\n rProperties.push_back(*pHeaderDynamic);\n delete pHeaderDynamic;\n }\n if(pFooterDynamic)\n {\n rProperties.push_back(*pFooterDynamic);\n delete pFooterDynamic;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- MSP430ISelDAGToDAG.cpp - A dag to dag inst selector for MSP430 ----===\/\/\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\/\/ This file defines an instruction selector for the MSP430 target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"MSP430.h\"\n#include \"MSP430ISelLowering.h\"\n#include \"MSP430TargetMachine.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/CallingConv.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/SelectionDAGISel.h\"\n#include \"llvm\/Target\/TargetLowering.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include <queue>\n#include <set>\nusing namespace llvm;\n\n\/\/\/ MSP430DAGToDAGISel - MSP430 specific code to select MSP430 machine\n\/\/\/ instructions for SelectionDAG operations.\n\/\/\/\nnamespace {\n class MSP430DAGToDAGISel : public SelectionDAGISel {\n MSP430TargetLowering &Lowering;\n const MSP430Subtarget &Subtarget;\n\n public:\n MSP430DAGToDAGISel(MSP430TargetMachine &TM)\n : SelectionDAGISel(TM),\n Lowering(*TM.getTargetLowering()),\n Subtarget(*TM.getSubtargetImpl()) { }\n\n virtual void InstructionSelect();\n\n virtual const char *getPassName() const {\n return \"MSP430 DAG->DAG Pattern Instruction Selection\";\n }\n\n \/\/ Include the pieces autogenerated from the target description.\n #include \"MSP430GenDAGISel.inc\"\n\n private:\n SDNode *Select(SDValue Op);\n };\n} \/\/ end anonymous namespace\n\n\/\/\/ createMSP430ISelDag - This pass converts a legalized DAG into a\n\/\/\/ MSP430-specific DAG, ready for instruction scheduling.\n\/\/\/\nFunctionPass *llvm::createMSP430ISelDag(MSP430TargetMachine &TM) {\n return new MSP430DAGToDAGISel(TM);\n}\n\n\/\/\/ InstructionSelect - This callback is invoked by\n\/\/\/ SelectionDAGISel when it has created a SelectionDAG for us to codegen.\nvoid MSP430DAGToDAGISel::\nInstructionSelect() {\n DEBUG(BB->dump());\n\n \/\/ Select target instructions for the DAG.\n SelectRoot(*CurDAG);\n\n CurDAG->RemoveDeadNodes();\n}\n\nSDNode *MSP430DAGToDAGISel::Select(SDValue Op) {\n return SelectCode(Op);\n}\n<commit_msg>Cleanup<commit_after>\/\/===-- MSP430ISelDAGToDAG.cpp - A dag to dag inst selector for MSP430 ----===\/\/\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\/\/ This file defines an instruction selector for the MSP430 target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"MSP430.h\"\n#include \"MSP430ISelLowering.h\"\n#include \"MSP430TargetMachine.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/CallingConv.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/SelectionDAGISel.h\"\n#include \"llvm\/Target\/TargetLowering.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include <queue>\n#include <set>\nusing namespace llvm;\n\n\/\/\/ MSP430DAGToDAGISel - MSP430 specific code to select MSP430 machine\n\/\/\/ instructions for SelectionDAG operations.\n\/\/\/\nnamespace {\n class MSP430DAGToDAGISel : public SelectionDAGISel {\n MSP430TargetLowering &Lowering;\n const MSP430Subtarget &Subtarget;\n\n public:\n MSP430DAGToDAGISel(MSP430TargetMachine &TM)\n : SelectionDAGISel(TM),\n Lowering(*TM.getTargetLowering()),\n Subtarget(*TM.getSubtargetImpl()) { }\n\n virtual void InstructionSelect();\n\n virtual const char *getPassName() const {\n return \"MSP430 DAG->DAG Pattern Instruction Selection\";\n }\n\n \/\/ Include the pieces autogenerated from the target description.\n #include \"MSP430GenDAGISel.inc\"\n\n private:\n SDNode *Select(SDValue Op);\n };\n} \/\/ end anonymous namespace\n\n\/\/\/ createMSP430ISelDag - This pass converts a legalized DAG into a\n\/\/\/ MSP430-specific DAG, ready for instruction scheduling.\n\/\/\/\nFunctionPass *llvm::createMSP430ISelDag(MSP430TargetMachine &TM) {\n return new MSP430DAGToDAGISel(TM);\n}\n\n\/\/\/ InstructionSelect - This callback is invoked by\n\/\/\/ SelectionDAGISel when it has created a SelectionDAG for us to codegen.\nvoid MSP430DAGToDAGISel::InstructionSelect() {\n DEBUG(BB->dump());\n\n \/\/ Select target instructions for the DAG.\n SelectRoot(*CurDAG);\n\n CurDAG->RemoveDeadNodes();\n}\n\nSDNode *MSP430DAGToDAGISel::Select(SDValue Op) {\n return SelectCode(Op);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- SystemZLongBranch.cpp - Branch lengthening for SystemZ ------------===\/\/\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\/\/ This pass makes sure that all branches are in range. There are several ways\n\/\/ in which this could be done. One aggressive approach is to assume that all\n\/\/ branches are in range and successively replace those that turn out not\n\/\/ to be in range with a longer form (branch relaxation). A simple\n\/\/ implementation is to continually walk through the function relaxing\n\/\/ branches until no more changes are needed and a fixed point is reached.\n\/\/ However, in the pathological worst case, this implementation is\n\/\/ quadratic in the number of blocks; relaxing branch N can make branch N-1\n\/\/ go out of range, which in turn can make branch N-2 go out of range,\n\/\/ and so on.\n\/\/\n\/\/ An alternative approach is to assume that all branches must be\n\/\/ converted to their long forms, then reinstate the short forms of\n\/\/ branches that, even under this pessimistic assumption, turn out to be\n\/\/ in range (branch shortening). This too can be implemented as a function\n\/\/ walk that is repeated until a fixed point is reached. In general,\n\/\/ the result of shortening is not as good as that of relaxation, and\n\/\/ shortening is also quadratic in the worst case; shortening branch N\n\/\/ can bring branch N-1 in range of the short form, which in turn can do\n\/\/ the same for branch N-2, and so on. The main advantage of shortening\n\/\/ is that each walk through the function produces valid code, so it is\n\/\/ possible to stop at any point after the first walk. The quadraticness\n\/\/ could therefore be handled with a maximum pass count, although the\n\/\/ question then becomes: what maximum count should be used?\n\/\/\n\/\/ On SystemZ, long branches are only needed for functions bigger than 64k,\n\/\/ which are relatively rare to begin with, and the long branch sequences\n\/\/ are actually relatively cheap. It therefore doesn't seem worth spending\n\/\/ much compilation time on the problem. Instead, the approach we take is:\n\/\/\n\/\/ (1) Check whether all branches can be short (the usual case). Exit the\n\/\/ pass if so.\n\/\/ (2) If one branch needs to be long, work out the address that each block\n\/\/ would have if all branches need to be long, as for shortening above.\n\/\/ (3) Relax any branch that is out of range according to this pessimistic\n\/\/ assumption.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"systemz-long-branch\"\n\n#include \"SystemZTargetMachine.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n\nusing namespace llvm;\n\nSTATISTIC(LongBranches, \"Number of long branches.\");\n\nnamespace {\n typedef MachineBasicBlock::iterator Iter;\n\n \/\/ Represents positional information about a basic block.\n struct MBBInfo {\n \/\/ The address that we currently assume the block has, relative to\n \/\/ the start of the function. This is designed so that taking the\n \/\/ difference between two addresses gives a conservative upper bound\n \/\/ on the distance between them.\n uint64_t Address;\n\n \/\/ The size of the block in bytes, excluding terminators.\n \/\/ This value never changes.\n uint64_t Size;\n\n \/\/ The minimum alignment of the block, as a log2 value.\n \/\/ This value never changes.\n unsigned Alignment;\n\n \/\/ The number of terminators in this block. This value never changes.\n unsigned NumTerminators;\n\n MBBInfo()\n : Address(0), Size(0), Alignment(0), NumTerminators(0) {} \n };\n\n \/\/ Represents the state of a block terminator.\n struct TerminatorInfo {\n \/\/ If this terminator is a relaxable branch, this points to the branch\n \/\/ instruction, otherwise it is null.\n MachineInstr *Branch;\n\n \/\/ The current address of the terminator, in the same form as\n \/\/ for BlockInfo.\n uint64_t Address;\n\n \/\/ The current size of the terminator in bytes.\n uint64_t Size;\n\n \/\/ If Branch is nonnull, this is the number of the target block,\n \/\/ otherwise it is unused.\n unsigned TargetBlock;\n\n \/\/ If Branch is nonnull, this is the length of the longest relaxed form,\n \/\/ otherwise it is zero.\n unsigned ExtraRelaxSize;\n\n TerminatorInfo() : Branch(0), Size(0), TargetBlock(0), ExtraRelaxSize(0) {}\n };\n\n \/\/ Used to keep track of the current position while iterating over the blocks.\n struct BlockPosition {\n \/\/ The offset from the start of the function, in the same form\n \/\/ as BlockInfo.\n uint64_t Address;\n\n \/\/ The number of low bits in Address that are known to be the same\n \/\/ as the runtime address.\n unsigned KnownBits;\n\n BlockPosition(unsigned InitialAlignment)\n : Address(0), KnownBits(InitialAlignment) {}\n };\n\n class SystemZLongBranch : public MachineFunctionPass {\n public:\n static char ID;\n SystemZLongBranch(const SystemZTargetMachine &tm)\n : MachineFunctionPass(ID),\n TII(static_cast<const SystemZInstrInfo *>(tm.getInstrInfo())) {}\n\n virtual const char *getPassName() const {\n return \"SystemZ Long Branch\";\n }\n\n bool runOnMachineFunction(MachineFunction &F);\n\n private:\n void skipNonTerminators(BlockPosition &Position, MBBInfo &Block);\n void skipTerminator(BlockPosition &Position, TerminatorInfo &Terminator,\n bool AssumeRelaxed);\n TerminatorInfo describeTerminator(MachineInstr *MI);\n uint64_t initMBBInfo();\n bool mustRelaxBranch(const TerminatorInfo &Terminator);\n bool mustRelaxABranch();\n void setWorstCaseAddresses();\n void relaxBranch(TerminatorInfo &Terminator);\n void relaxBranches();\n\n const SystemZInstrInfo *TII;\n MachineFunction *MF;\n SmallVector<MBBInfo, 16> MBBs;\n SmallVector<TerminatorInfo, 16> Terminators;\n };\n\n char SystemZLongBranch::ID = 0;\n\n const uint64_t MaxBackwardRange = 0x10000;\n const uint64_t MaxForwardRange = 0xfffe;\n} \/\/ end of anonymous namespace\n\nFunctionPass *llvm::createSystemZLongBranchPass(SystemZTargetMachine &TM) {\n return new SystemZLongBranch(TM);\n}\n\n\/\/ Position describes the state immediately before Block. Update Block\n\/\/ accordingly and move Position to the end of the block's non-terminator\n\/\/ instructions.\nvoid SystemZLongBranch::skipNonTerminators(BlockPosition &Position,\n MBBInfo &Block) {\n if (Block.Alignment > Position.KnownBits) {\n \/\/ When calculating the address of Block, we need to conservatively\n \/\/ assume that Block had the worst possible misalignment.\n Position.Address += ((uint64_t(1) << Block.Alignment) -\n (uint64_t(1) << Position.KnownBits));\n Position.KnownBits = Block.Alignment;\n }\n\n \/\/ Align the addresses.\n uint64_t AlignMask = (uint64_t(1) << Block.Alignment) - 1;\n Position.Address = (Position.Address + AlignMask) & ~AlignMask;\n\n \/\/ Record the block's position.\n Block.Address = Position.Address;\n\n \/\/ Move past the non-terminators in the block.\n Position.Address += Block.Size;\n}\n\n\/\/ Position describes the state immediately before Terminator.\n\/\/ Update Terminator accordingly and move Position past it.\n\/\/ Assume that Terminator will be relaxed if AssumeRelaxed.\nvoid SystemZLongBranch::skipTerminator(BlockPosition &Position,\n TerminatorInfo &Terminator,\n bool AssumeRelaxed) {\n Terminator.Address = Position.Address;\n Position.Address += Terminator.Size;\n if (AssumeRelaxed)\n Position.Address += Terminator.ExtraRelaxSize;\n}\n\n\/\/ Return a description of terminator instruction MI.\nTerminatorInfo SystemZLongBranch::describeTerminator(MachineInstr *MI) {\n TerminatorInfo Terminator;\n Terminator.Size = TII->getInstSizeInBytes(MI);\n if (MI->isConditionalBranch() || MI->isUnconditionalBranch()) {\n Terminator.Branch = MI;\n switch (MI->getOpcode()) {\n case SystemZ::J:\n \/\/ Relaxes to JG, which is 2 bytes longer.\n Terminator.TargetBlock = MI->getOperand(0).getMBB()->getNumber();\n Terminator.ExtraRelaxSize = 2;\n break;\n case SystemZ::BRC:\n \/\/ Relaxes to BRCL, which is 2 bytes longer. Operand 0 is the\n \/\/ condition code mask.\n Terminator.TargetBlock = MI->getOperand(1).getMBB()->getNumber();\n Terminator.ExtraRelaxSize = 2;\n break;\n default:\n llvm_unreachable(\"Unrecognized branch instruction\");\n }\n }\n return Terminator;\n}\n\n\/\/ Fill MBBs and Terminators, setting the addresses on the assumption\n\/\/ that no branches need relaxation. Return the size of the function under\n\/\/ this assumption.\nuint64_t SystemZLongBranch::initMBBInfo() {\n MF->RenumberBlocks();\n unsigned NumBlocks = MF->size();\n\n MBBs.clear();\n MBBs.resize(NumBlocks);\n\n Terminators.clear();\n Terminators.reserve(NumBlocks);\n\n BlockPosition Position(MF->getAlignment());\n for (unsigned I = 0; I < NumBlocks; ++I) {\n MachineBasicBlock *MBB = MF->getBlockNumbered(I);\n MBBInfo &Block = MBBs[I];\n\n \/\/ Record the alignment, for quick access.\n Block.Alignment = MBB->getAlignment();\n\n \/\/ Calculate the size of the fixed part of the block.\n MachineBasicBlock::iterator MI = MBB->begin();\n MachineBasicBlock::iterator End = MBB->end();\n while (MI != End && !MI->isTerminator()) {\n Block.Size += TII->getInstSizeInBytes(MI);\n ++MI;\n }\n skipNonTerminators(Position, Block);\n\n \/\/ Add the terminators.\n while (MI != End) {\n if (!MI->isDebugValue()) {\n assert(MI->isTerminator() && \"Terminator followed by non-terminator\");\n Terminators.push_back(describeTerminator(MI));\n skipTerminator(Position, Terminators.back(), false);\n ++Block.NumTerminators;\n }\n ++MI;\n }\n }\n\n return Position.Address;\n}\n\n\/\/ Return true if, under current assumptions, Terminator needs to be relaxed.\nbool SystemZLongBranch::mustRelaxBranch(const TerminatorInfo &Terminator) {\n if (!Terminator.Branch)\n return false;\n\n const MBBInfo &Target = MBBs[Terminator.TargetBlock];\n if (Target.Address < Terminator.Address) {\n if (Terminator.Address - Target.Address <= MaxBackwardRange)\n return false;\n } else {\n if (Target.Address - Terminator.Address <= MaxForwardRange)\n return false;\n }\n\n return true;\n}\n\n\/\/ Return true if, under current assumptions, any terminator needs\n\/\/ to be relaxed.\nbool SystemZLongBranch::mustRelaxABranch() {\n for (SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin(),\n TE = Terminators.end(); TI != TE; ++TI)\n if (mustRelaxBranch(*TI))\n return true;\n return false;\n}\n\n\/\/ Set the address of each block on the assumption that all branches\n\/\/ must be long.\nvoid SystemZLongBranch::setWorstCaseAddresses() {\n SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();\n BlockPosition Position(MF->getAlignment());\n for (SmallVector<MBBInfo, 16>::iterator BI = MBBs.begin(), BE = MBBs.end();\n BI != BE; ++BI) {\n skipNonTerminators(Position, *BI);\n for (unsigned BTI = 0, BTE = BI->NumTerminators; BTI != BTE; ++BTI) {\n skipTerminator(Position, *TI, true);\n ++TI;\n }\n }\n}\n\n\/\/ Relax the branch described by Terminator.\nvoid SystemZLongBranch::relaxBranch(TerminatorInfo &Terminator) {\n MachineInstr *Branch = Terminator.Branch;\n switch (Branch->getOpcode()) {\n case SystemZ::J:\n Branch->setDesc(TII->get(SystemZ::JG));\n break;\n case SystemZ::BRC:\n Branch->setDesc(TII->get(SystemZ::BRCL));\n break;\n default:\n llvm_unreachable(\"Unrecognized branch\");\n }\n\n Terminator.Size += Terminator.ExtraRelaxSize;\n Terminator.ExtraRelaxSize = 0;\n Terminator.Branch = 0;\n\n ++LongBranches;\n}\n\n\/\/ Relax any branches that need to be relaxed, under current assumptions.\nvoid SystemZLongBranch::relaxBranches() {\n for (SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin(),\n TE = Terminators.end(); TI != TE; ++TI)\n if (mustRelaxBranch(*TI))\n relaxBranch(*TI);\n}\n\nbool SystemZLongBranch::runOnMachineFunction(MachineFunction &F) {\n MF = &F;\n uint64_t Size = initMBBInfo();\n if (Size <= MaxForwardRange || !mustRelaxABranch())\n return false;\n\n setWorstCaseAddresses();\n relaxBranches();\n return true;\n}\n<commit_msg>Fix indentation<commit_after>\/\/===-- SystemZLongBranch.cpp - Branch lengthening for SystemZ ------------===\/\/\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\/\/ This pass makes sure that all branches are in range. There are several ways\n\/\/ in which this could be done. One aggressive approach is to assume that all\n\/\/ branches are in range and successively replace those that turn out not\n\/\/ to be in range with a longer form (branch relaxation). A simple\n\/\/ implementation is to continually walk through the function relaxing\n\/\/ branches until no more changes are needed and a fixed point is reached.\n\/\/ However, in the pathological worst case, this implementation is\n\/\/ quadratic in the number of blocks; relaxing branch N can make branch N-1\n\/\/ go out of range, which in turn can make branch N-2 go out of range,\n\/\/ and so on.\n\/\/\n\/\/ An alternative approach is to assume that all branches must be\n\/\/ converted to their long forms, then reinstate the short forms of\n\/\/ branches that, even under this pessimistic assumption, turn out to be\n\/\/ in range (branch shortening). This too can be implemented as a function\n\/\/ walk that is repeated until a fixed point is reached. In general,\n\/\/ the result of shortening is not as good as that of relaxation, and\n\/\/ shortening is also quadratic in the worst case; shortening branch N\n\/\/ can bring branch N-1 in range of the short form, which in turn can do\n\/\/ the same for branch N-2, and so on. The main advantage of shortening\n\/\/ is that each walk through the function produces valid code, so it is\n\/\/ possible to stop at any point after the first walk. The quadraticness\n\/\/ could therefore be handled with a maximum pass count, although the\n\/\/ question then becomes: what maximum count should be used?\n\/\/\n\/\/ On SystemZ, long branches are only needed for functions bigger than 64k,\n\/\/ which are relatively rare to begin with, and the long branch sequences\n\/\/ are actually relatively cheap. It therefore doesn't seem worth spending\n\/\/ much compilation time on the problem. Instead, the approach we take is:\n\/\/\n\/\/ (1) Check whether all branches can be short (the usual case). Exit the\n\/\/ pass if so.\n\/\/ (2) If one branch needs to be long, work out the address that each block\n\/\/ would have if all branches need to be long, as for shortening above.\n\/\/ (3) Relax any branch that is out of range according to this pessimistic\n\/\/ assumption.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"systemz-long-branch\"\n\n#include \"SystemZTargetMachine.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n\nusing namespace llvm;\n\nSTATISTIC(LongBranches, \"Number of long branches.\");\n\nnamespace {\n typedef MachineBasicBlock::iterator Iter;\n\n \/\/ Represents positional information about a basic block.\n struct MBBInfo {\n \/\/ The address that we currently assume the block has, relative to\n \/\/ the start of the function. This is designed so that taking the\n \/\/ difference between two addresses gives a conservative upper bound\n \/\/ on the distance between them.\n uint64_t Address;\n\n \/\/ The size of the block in bytes, excluding terminators.\n \/\/ This value never changes.\n uint64_t Size;\n\n \/\/ The minimum alignment of the block, as a log2 value.\n \/\/ This value never changes.\n unsigned Alignment;\n\n \/\/ The number of terminators in this block. This value never changes.\n unsigned NumTerminators;\n\n MBBInfo()\n : Address(0), Size(0), Alignment(0), NumTerminators(0) {} \n };\n\n \/\/ Represents the state of a block terminator.\n struct TerminatorInfo {\n \/\/ If this terminator is a relaxable branch, this points to the branch\n \/\/ instruction, otherwise it is null.\n MachineInstr *Branch;\n\n \/\/ The current address of the terminator, in the same form as\n \/\/ for BlockInfo.\n uint64_t Address;\n\n \/\/ The current size of the terminator in bytes.\n uint64_t Size;\n\n \/\/ If Branch is nonnull, this is the number of the target block,\n \/\/ otherwise it is unused.\n unsigned TargetBlock;\n\n \/\/ If Branch is nonnull, this is the length of the longest relaxed form,\n \/\/ otherwise it is zero.\n unsigned ExtraRelaxSize;\n\n TerminatorInfo() : Branch(0), Size(0), TargetBlock(0), ExtraRelaxSize(0) {}\n };\n\n \/\/ Used to keep track of the current position while iterating over the blocks.\n struct BlockPosition {\n \/\/ The offset from the start of the function, in the same form\n \/\/ as BlockInfo.\n uint64_t Address;\n\n \/\/ The number of low bits in Address that are known to be the same\n \/\/ as the runtime address.\n unsigned KnownBits;\n\n BlockPosition(unsigned InitialAlignment)\n : Address(0), KnownBits(InitialAlignment) {}\n };\n\n class SystemZLongBranch : public MachineFunctionPass {\n public:\n static char ID;\n SystemZLongBranch(const SystemZTargetMachine &tm)\n : MachineFunctionPass(ID),\n TII(static_cast<const SystemZInstrInfo *>(tm.getInstrInfo())) {}\n\n virtual const char *getPassName() const {\n return \"SystemZ Long Branch\";\n }\n\n bool runOnMachineFunction(MachineFunction &F);\n\n private:\n void skipNonTerminators(BlockPosition &Position, MBBInfo &Block);\n void skipTerminator(BlockPosition &Position, TerminatorInfo &Terminator,\n bool AssumeRelaxed);\n TerminatorInfo describeTerminator(MachineInstr *MI);\n uint64_t initMBBInfo();\n bool mustRelaxBranch(const TerminatorInfo &Terminator);\n bool mustRelaxABranch();\n void setWorstCaseAddresses();\n void relaxBranch(TerminatorInfo &Terminator);\n void relaxBranches();\n\n const SystemZInstrInfo *TII;\n MachineFunction *MF;\n SmallVector<MBBInfo, 16> MBBs;\n SmallVector<TerminatorInfo, 16> Terminators;\n };\n\n char SystemZLongBranch::ID = 0;\n\n const uint64_t MaxBackwardRange = 0x10000;\n const uint64_t MaxForwardRange = 0xfffe;\n} \/\/ end of anonymous namespace\n\nFunctionPass *llvm::createSystemZLongBranchPass(SystemZTargetMachine &TM) {\n return new SystemZLongBranch(TM);\n}\n\n\/\/ Position describes the state immediately before Block. Update Block\n\/\/ accordingly and move Position to the end of the block's non-terminator\n\/\/ instructions.\nvoid SystemZLongBranch::skipNonTerminators(BlockPosition &Position,\n MBBInfo &Block) {\n if (Block.Alignment > Position.KnownBits) {\n \/\/ When calculating the address of Block, we need to conservatively\n \/\/ assume that Block had the worst possible misalignment.\n Position.Address += ((uint64_t(1) << Block.Alignment) -\n (uint64_t(1) << Position.KnownBits));\n Position.KnownBits = Block.Alignment;\n }\n\n \/\/ Align the addresses.\n uint64_t AlignMask = (uint64_t(1) << Block.Alignment) - 1;\n Position.Address = (Position.Address + AlignMask) & ~AlignMask;\n\n \/\/ Record the block's position.\n Block.Address = Position.Address;\n\n \/\/ Move past the non-terminators in the block.\n Position.Address += Block.Size;\n}\n\n\/\/ Position describes the state immediately before Terminator.\n\/\/ Update Terminator accordingly and move Position past it.\n\/\/ Assume that Terminator will be relaxed if AssumeRelaxed.\nvoid SystemZLongBranch::skipTerminator(BlockPosition &Position,\n TerminatorInfo &Terminator,\n bool AssumeRelaxed) {\n Terminator.Address = Position.Address;\n Position.Address += Terminator.Size;\n if (AssumeRelaxed)\n Position.Address += Terminator.ExtraRelaxSize;\n}\n\n\/\/ Return a description of terminator instruction MI.\nTerminatorInfo SystemZLongBranch::describeTerminator(MachineInstr *MI) {\n TerminatorInfo Terminator;\n Terminator.Size = TII->getInstSizeInBytes(MI);\n if (MI->isConditionalBranch() || MI->isUnconditionalBranch()) {\n Terminator.Branch = MI;\n switch (MI->getOpcode()) {\n case SystemZ::J:\n \/\/ Relaxes to JG, which is 2 bytes longer.\n Terminator.TargetBlock = MI->getOperand(0).getMBB()->getNumber();\n Terminator.ExtraRelaxSize = 2;\n break;\n case SystemZ::BRC:\n \/\/ Relaxes to BRCL, which is 2 bytes longer. Operand 0 is the\n \/\/ condition code mask.\n Terminator.TargetBlock = MI->getOperand(1).getMBB()->getNumber();\n Terminator.ExtraRelaxSize = 2;\n break;\n default:\n llvm_unreachable(\"Unrecognized branch instruction\");\n }\n }\n return Terminator;\n}\n\n\/\/ Fill MBBs and Terminators, setting the addresses on the assumption\n\/\/ that no branches need relaxation. Return the size of the function under\n\/\/ this assumption.\nuint64_t SystemZLongBranch::initMBBInfo() {\n MF->RenumberBlocks();\n unsigned NumBlocks = MF->size();\n\n MBBs.clear();\n MBBs.resize(NumBlocks);\n\n Terminators.clear();\n Terminators.reserve(NumBlocks);\n\n BlockPosition Position(MF->getAlignment());\n for (unsigned I = 0; I < NumBlocks; ++I) {\n MachineBasicBlock *MBB = MF->getBlockNumbered(I);\n MBBInfo &Block = MBBs[I];\n\n \/\/ Record the alignment, for quick access.\n Block.Alignment = MBB->getAlignment();\n\n \/\/ Calculate the size of the fixed part of the block.\n MachineBasicBlock::iterator MI = MBB->begin();\n MachineBasicBlock::iterator End = MBB->end();\n while (MI != End && !MI->isTerminator()) {\n Block.Size += TII->getInstSizeInBytes(MI);\n ++MI;\n }\n skipNonTerminators(Position, Block);\n\n \/\/ Add the terminators.\n while (MI != End) {\n if (!MI->isDebugValue()) {\n assert(MI->isTerminator() && \"Terminator followed by non-terminator\");\n Terminators.push_back(describeTerminator(MI));\n skipTerminator(Position, Terminators.back(), false);\n ++Block.NumTerminators;\n }\n ++MI;\n }\n }\n\n return Position.Address;\n}\n\n\/\/ Return true if, under current assumptions, Terminator needs to be relaxed.\nbool SystemZLongBranch::mustRelaxBranch(const TerminatorInfo &Terminator) {\n if (!Terminator.Branch)\n return false;\n\n const MBBInfo &Target = MBBs[Terminator.TargetBlock];\n if (Target.Address < Terminator.Address) {\n if (Terminator.Address - Target.Address <= MaxBackwardRange)\n return false;\n } else {\n if (Target.Address - Terminator.Address <= MaxForwardRange)\n return false;\n }\n\n return true;\n}\n\n\/\/ Return true if, under current assumptions, any terminator needs\n\/\/ to be relaxed.\nbool SystemZLongBranch::mustRelaxABranch() {\n for (SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin(),\n TE = Terminators.end(); TI != TE; ++TI)\n if (mustRelaxBranch(*TI))\n return true;\n return false;\n}\n\n\/\/ Set the address of each block on the assumption that all branches\n\/\/ must be long.\nvoid SystemZLongBranch::setWorstCaseAddresses() {\n SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();\n BlockPosition Position(MF->getAlignment());\n for (SmallVector<MBBInfo, 16>::iterator BI = MBBs.begin(), BE = MBBs.end();\n BI != BE; ++BI) {\n skipNonTerminators(Position, *BI);\n for (unsigned BTI = 0, BTE = BI->NumTerminators; BTI != BTE; ++BTI) {\n skipTerminator(Position, *TI, true);\n ++TI;\n }\n }\n}\n\n\/\/ Relax the branch described by Terminator.\nvoid SystemZLongBranch::relaxBranch(TerminatorInfo &Terminator) {\n MachineInstr *Branch = Terminator.Branch;\n switch (Branch->getOpcode()) {\n case SystemZ::J:\n Branch->setDesc(TII->get(SystemZ::JG));\n break;\n case SystemZ::BRC:\n Branch->setDesc(TII->get(SystemZ::BRCL));\n break;\n default:\n llvm_unreachable(\"Unrecognized branch\");\n }\n\n Terminator.Size += Terminator.ExtraRelaxSize;\n Terminator.ExtraRelaxSize = 0;\n Terminator.Branch = 0;\n\n ++LongBranches;\n}\n\n\/\/ Relax any branches that need to be relaxed, under current assumptions.\nvoid SystemZLongBranch::relaxBranches() {\n for (SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin(),\n TE = Terminators.end(); TI != TE; ++TI)\n if (mustRelaxBranch(*TI))\n relaxBranch(*TI);\n}\n\nbool SystemZLongBranch::runOnMachineFunction(MachineFunction &F) {\n MF = &F;\n uint64_t Size = initMBBInfo();\n if (Size <= MaxForwardRange || !mustRelaxABranch())\n return false;\n\n setWorstCaseAddresses();\n relaxBranches();\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ArgumentPromotion.cpp - Promote 'by reference' arguments ----------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass promotes \"by reference\" arguments to be \"by value\" arguments. In\n\/\/ practice, this means looking for internal functions that have pointer\n\/\/ arguments. If we can prove, through the use of alias analysis, that that an\n\/\/ argument is *only* loaded, then we can pass the value into the function\n\/\/ instead of the address of the value. This can cause recursive simplification\n\/\/ of code, and lead to the elimination of allocas, especially in C++ template\n\/\/ code like the STL.\n\/\/\n\/\/ Note that this transformation could also be done for arguments that are only\n\/\/ stored to (returning the value instead), but we do not currently handle that\n\/\/ case.\n\/\/\n\/\/ Note that we should be able to promote pointers to structures that are only\n\/\/ loaded from as well. The danger is creating way to many arguments, so this\n\/\/ transformation should be limited to 3 element structs or something.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"Support\/Debug.h\"\n#include \"Support\/DepthFirstIterator.h\"\n#include \"Support\/Statistic.h\"\n#include <set>\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumArgumentsPromoted(\"argpromotion\",\n \"Number of pointer arguments promoted\");\n Statistic<> NumArgumentsDead(\"argpromotion\",\n \"Number of dead pointer args eliminated\");\n\n \/\/\/ ArgPromotion - The 'by reference' to 'by value' argument promotion pass.\n \/\/\/\n class ArgPromotion : public Pass {\n \/\/ WorkList - The set of internal functions that we have yet to process. As\n \/\/ we eliminate arguments from a function, we push all callers into this set\n \/\/ so that the by reference argument can be bubbled out as far as possible.\n \/\/ This set contains only internal functions.\n std::set<Function*> WorkList;\n public:\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<AliasAnalysis>();\n AU.addRequired<TargetData>();\n }\n\n virtual bool run(Module &M);\n private:\n bool PromoteArguments(Function *F);\n bool isSafeToPromoteArgument(Argument *Arg) const; \n void DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);\n };\n\n RegisterOpt<ArgPromotion> X(\"argpromotion\",\n \"Promote 'by reference' arguments to scalars\");\n}\n\nPass *llvm::createArgumentPromotionPass() {\n return new ArgPromotion();\n}\n\nbool ArgPromotion::run(Module &M) {\n bool Changed = false;\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (I->hasInternalLinkage()) {\n WorkList.insert(I);\n\n \/\/ If there are any constant pointer refs pointing to this function,\n \/\/ eliminate them now if possible.\n ConstantPointerRef *CPR = 0;\n for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;\n ++UI)\n if ((CPR = dyn_cast<ConstantPointerRef>(*UI)))\n break; \/\/ Found one!\n if (CPR) {\n \/\/ See if we can transform all users to use the function directly.\n while (!CPR->use_empty()) {\n User *TheUser = CPR->use_back();\n if (!isa<Constant>(TheUser) && !isa<GlobalVariable>(TheUser)) {\n Changed = true;\n TheUser->replaceUsesOfWith(CPR, I);\n } else {\n \/\/ We won't be able to eliminate all users. :(\n WorkList.erase(I); \/\/ Minor efficiency win.\n break;\n }\n }\n\n \/\/ If we nuked all users of the CPR, kill the CPR now!\n if (CPR->use_empty()) {\n CPR->destroyConstant();\n Changed = true;\n }\n }\n }\n \n while (!WorkList.empty()) {\n Function *F = *WorkList.begin();\n WorkList.erase(WorkList.begin());\n\n if (PromoteArguments(F)) \/\/ Attempt to promote an argument.\n Changed = true; \/\/ Remember that we changed something.\n }\n \n return Changed;\n}\n\n\nbool ArgPromotion::PromoteArguments(Function *F) {\n assert(F->hasInternalLinkage() && \"We can only process internal functions!\");\n\n \/\/ First check: see if there are any pointer arguments! If not, quick exit.\n std::vector<Argument*> PointerArgs;\n for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)\n if (isa<PointerType>(I->getType()))\n PointerArgs.push_back(I);\n if (PointerArgs.empty()) return false;\n\n \/\/ Second check: make sure that all callers are direct callers. We can't\n \/\/ transform functions that have indirect callers.\n for (Value::use_iterator UI = F->use_begin(), E = F->use_end();\n UI != E; ++UI)\n \/\/ What about CPRs?\n if (!CallSite::get(*UI).getInstruction())\n return false; \/\/ Cannot promote an indirect call!\n\n \/\/ Check to see which arguments are promotable. If an argument is not\n \/\/ promotable, remove it from the PointerArgs vector.\n for (unsigned i = 0; i != PointerArgs.size(); ++i)\n if (!isSafeToPromoteArgument(PointerArgs[i])) {\n std::swap(PointerArgs[i--], PointerArgs.back());\n PointerArgs.pop_back();\n }\n\n \/\/ No promotable pointer arguments.\n if (PointerArgs.empty()) return false;\n\n \/\/ Okay, promote all of the arguments are rewrite the callees!\n DoPromotion(F, PointerArgs);\n return true;\n}\n\nbool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {\n \/\/ We can only promote this argument if all of the uses are loads...\n std::vector<LoadInst*> Loads;\n for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();\n UI != E; ++UI)\n if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {\n if (LI->isVolatile()) return false; \/\/ Don't hack volatile loads\n Loads.push_back(LI);\n } else\n return false;\n\n if (Loads.empty()) return true; \/\/ No users, dead argument.\n\n const Type *LoadTy = cast<PointerType>(Arg->getType())->getElementType();\n unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(LoadTy);\n\n \/\/ Okay, now we know that the argument is only used by load instructions.\n \/\/ Check to see if the pointer is guaranteed to not be modified from entry of\n \/\/ the function to each of the load instructions.\n Function &F = *Arg->getParent();\n\n \/\/ Because there could be several\/many load instructions, remember which\n \/\/ blocks we know to be transparent to the load.\n std::set<BasicBlock*> TranspBlocks;\n\n AliasAnalysis &AA = getAnalysis<AliasAnalysis>();\n\n for (unsigned i = 0, e = Loads.size(); i != e; ++i) {\n \/\/ Check to see if the load is invalidated from the start of the block to\n \/\/ the load itself.\n LoadInst *Load = Loads[i];\n BasicBlock *BB = Load->getParent();\n if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))\n return false; \/\/ Pointer is invalidated!\n\n \/\/ Now check every path from the entry block to the load for transparency.\n \/\/ To do this, we perform a depth first search on the inverse CFG from the\n \/\/ loading block.\n for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)\n for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),\n E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)\n if (AA.canBasicBlockModify(**I, Arg, LoadSize))\n return false;\n }\n\n \/\/ If the path from the entry of the function to each load is free of\n \/\/ instructions that potentially invalidate the load, we can make the\n \/\/ transformation!\n return true;\n}\n\n\nvoid ArgPromotion::DoPromotion(Function *F, std::vector<Argument*> &Args2Prom) {\n std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());\n \n \/\/ Start by computing a new prototype for the function, which is the same as\n \/\/ the old function, but has modified arguments.\n const FunctionType *FTy = F->getFunctionType();\n std::vector<const Type*> Params;\n\n for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)\n if (!ArgsToPromote.count(I)) {\n Params.push_back(I->getType());\n } else if (!I->use_empty()) {\n Params.push_back(cast<PointerType>(I->getType())->getElementType());\n ++NumArgumentsPromoted;\n } else {\n ++NumArgumentsDead;\n }\n\n const Type *RetTy = FTy->getReturnType();\n\n \/\/ Work around LLVM bug PR56: the CWriter cannot emit varargs functions which\n \/\/ have zero fixed arguments.\n bool ExtraArgHack = false;\n if (Params.empty() && FTy->isVarArg()) {\n ExtraArgHack = true;\n Params.push_back(Type::IntTy);\n }\n FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());\n \n \/\/ Create the new function body and insert it into the module...\n Function *NF = new Function(NFTy, F->getLinkage(), F->getName());\n F->getParent()->getFunctionList().insert(F, NF);\n \n \/\/ Loop over all of the callers of the function, transforming the call sites\n \/\/ to pass in the loaded pointers.\n \/\/\n std::vector<Value*> Args;\n while (!F->use_empty()) {\n CallSite CS = CallSite::get(F->use_back());\n Instruction *Call = CS.getInstruction();\n\n \/\/ Make sure the caller of this function is revisited.\n if (Call->getParent()->getParent()->hasInternalLinkage())\n WorkList.insert(Call->getParent()->getParent());\n \n \/\/ Loop over the operands, deleting dead ones...\n CallSite::arg_iterator AI = CS.arg_begin();\n for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)\n if (!ArgsToPromote.count(I))\n Args.push_back(*AI); \/\/ Unmodified argument\n else if (!I->use_empty()) {\n \/\/ Non-dead instruction\n Args.push_back(new LoadInst(*AI, (*AI)->getName()+\".val\", Call));\n }\n\n if (ExtraArgHack)\n Args.push_back(Constant::getNullValue(Type::IntTy));\n\n \/\/ Push any varargs arguments on the list\n for (; AI != CS.arg_end(); ++AI)\n Args.push_back(*AI);\n\n Instruction *New;\n if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {\n New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),\n Args, \"\", Call);\n } else {\n New = new CallInst(NF, Args, \"\", Call);\n }\n Args.clear();\n\n if (!Call->use_empty()) {\n Call->replaceAllUsesWith(New);\n std::string Name = Call->getName();\n Call->setName(\"\");\n New->setName(Name);\n }\n \n \/\/ Finally, remove the old call from the program, reducing the use-count of\n \/\/ F.\n Call->getParent()->getInstList().erase(Call);\n }\n\n \/\/ Since we have now created the new function, splice the body of the old\n \/\/ function right into the new function, leaving the old rotting hulk of the\n \/\/ function empty.\n NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());\n\n \/\/ Loop over the argument list, transfering uses of the old arguments over to\n \/\/ the new arguments, also transfering over the names as well.\n \/\/\n for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();\n I != E; ++I)\n if (!ArgsToPromote.count(I)) {\n \/\/ If this is an unmodified argument, move the name and users over to the\n \/\/ new version.\n I->replaceAllUsesWith(I2);\n I2->setName(I->getName());\n ++I2;\n } else if (!I->use_empty()) {\n \/\/ Otherwise, if we promoted this argument, then all users are load\n \/\/ instructions, and all loads should be using the new argument that we\n \/\/ added.\n DEBUG(std::cerr << \"*** Promoted argument '\" << I->getName()\n << \"' of function '\" << F->getName() << \"'\\n\");\n I2->setName(I->getName()+\".val\");\n while (!I->use_empty()) {\n LoadInst *LI = cast<LoadInst>(I->use_back());\n LI->replaceAllUsesWith(I2);\n LI->getParent()->getInstList().erase(LI);\n }\n ++I2;\n }\n\n \/\/ Now that the old function is dead, delete it.\n F->getParent()->getFunctionList().erase(F);\n}\n<commit_msg>Fix another minor bug, exposed by perlbmk<commit_after>\/\/===-- ArgumentPromotion.cpp - Promote 'by reference' arguments ----------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass promotes \"by reference\" arguments to be \"by value\" arguments. In\n\/\/ practice, this means looking for internal functions that have pointer\n\/\/ arguments. If we can prove, through the use of alias analysis, that that an\n\/\/ argument is *only* loaded, then we can pass the value into the function\n\/\/ instead of the address of the value. This can cause recursive simplification\n\/\/ of code, and lead to the elimination of allocas, especially in C++ template\n\/\/ code like the STL.\n\/\/\n\/\/ Note that this transformation could also be done for arguments that are only\n\/\/ stored to (returning the value instead), but we do not currently handle that\n\/\/ case.\n\/\/\n\/\/ Note that we should be able to promote pointers to structures that are only\n\/\/ loaded from as well. The danger is creating way to many arguments, so this\n\/\/ transformation should be limited to 3 element structs or something.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"Support\/Debug.h\"\n#include \"Support\/DepthFirstIterator.h\"\n#include \"Support\/Statistic.h\"\n#include <set>\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumArgumentsPromoted(\"argpromotion\",\n \"Number of pointer arguments promoted\");\n Statistic<> NumArgumentsDead(\"argpromotion\",\n \"Number of dead pointer args eliminated\");\n\n \/\/\/ ArgPromotion - The 'by reference' to 'by value' argument promotion pass.\n \/\/\/\n class ArgPromotion : public Pass {\n \/\/ WorkList - The set of internal functions that we have yet to process. As\n \/\/ we eliminate arguments from a function, we push all callers into this set\n \/\/ so that the by reference argument can be bubbled out as far as possible.\n \/\/ This set contains only internal functions.\n std::set<Function*> WorkList;\n public:\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<AliasAnalysis>();\n AU.addRequired<TargetData>();\n }\n\n virtual bool run(Module &M);\n private:\n bool PromoteArguments(Function *F);\n bool isSafeToPromoteArgument(Argument *Arg) const; \n void DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);\n };\n\n RegisterOpt<ArgPromotion> X(\"argpromotion\",\n \"Promote 'by reference' arguments to scalars\");\n}\n\nPass *llvm::createArgumentPromotionPass() {\n return new ArgPromotion();\n}\n\nbool ArgPromotion::run(Module &M) {\n bool Changed = false;\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (I->hasInternalLinkage()) {\n WorkList.insert(I);\n\n \/\/ If there are any constant pointer refs pointing to this function,\n \/\/ eliminate them now if possible.\n ConstantPointerRef *CPR = 0;\n for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;\n ++UI)\n if ((CPR = dyn_cast<ConstantPointerRef>(*UI)))\n break; \/\/ Found one!\n if (CPR) {\n \/\/ See if we can transform all users to use the function directly.\n while (!CPR->use_empty()) {\n User *TheUser = CPR->use_back();\n if (!isa<Constant>(TheUser) && !isa<GlobalVariable>(TheUser)) {\n Changed = true;\n TheUser->replaceUsesOfWith(CPR, I);\n } else {\n \/\/ We won't be able to eliminate all users. :(\n WorkList.erase(I); \/\/ Minor efficiency win.\n break;\n }\n }\n\n \/\/ If we nuked all users of the CPR, kill the CPR now!\n if (CPR->use_empty()) {\n CPR->destroyConstant();\n Changed = true;\n }\n }\n }\n \n while (!WorkList.empty()) {\n Function *F = *WorkList.begin();\n WorkList.erase(WorkList.begin());\n\n if (PromoteArguments(F)) \/\/ Attempt to promote an argument.\n Changed = true; \/\/ Remember that we changed something.\n }\n \n return Changed;\n}\n\n\nbool ArgPromotion::PromoteArguments(Function *F) {\n assert(F->hasInternalLinkage() && \"We can only process internal functions!\");\n\n \/\/ First check: see if there are any pointer arguments! If not, quick exit.\n std::vector<Argument*> PointerArgs;\n for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)\n if (isa<PointerType>(I->getType()))\n PointerArgs.push_back(I);\n if (PointerArgs.empty()) return false;\n\n \/\/ Second check: make sure that all callers are direct callers. We can't\n \/\/ transform functions that have indirect callers.\n for (Value::use_iterator UI = F->use_begin(), E = F->use_end();\n UI != E; ++UI) {\n CallSite CS = CallSite::get(*UI);\n if (Instruction *I = CS.getInstruction()) {\n \/\/ Ensure that this call site is CALLING the function, not passing it as\n \/\/ an argument.\n for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();\n AI != E; ++AI)\n if (*AI == F) return false; \/\/ Passing the function address in!\n } else {\n return false; \/\/ Cannot promote an indirect call!\n }\n }\n\n \/\/ Check to see which arguments are promotable. If an argument is not\n \/\/ promotable, remove it from the PointerArgs vector.\n for (unsigned i = 0; i != PointerArgs.size(); ++i)\n if (!isSafeToPromoteArgument(PointerArgs[i])) {\n std::swap(PointerArgs[i--], PointerArgs.back());\n PointerArgs.pop_back();\n }\n\n \/\/ No promotable pointer arguments.\n if (PointerArgs.empty()) return false;\n\n \/\/ Okay, promote all of the arguments are rewrite the callees!\n DoPromotion(F, PointerArgs);\n return true;\n}\n\nbool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {\n \/\/ We can only promote this argument if all of the uses are loads...\n std::vector<LoadInst*> Loads;\n for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();\n UI != E; ++UI)\n if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {\n if (LI->isVolatile()) return false; \/\/ Don't hack volatile loads\n Loads.push_back(LI);\n } else\n return false;\n\n if (Loads.empty()) return true; \/\/ No users, dead argument.\n\n const Type *LoadTy = cast<PointerType>(Arg->getType())->getElementType();\n unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(LoadTy);\n\n \/\/ Okay, now we know that the argument is only used by load instructions.\n \/\/ Check to see if the pointer is guaranteed to not be modified from entry of\n \/\/ the function to each of the load instructions.\n Function &F = *Arg->getParent();\n\n \/\/ Because there could be several\/many load instructions, remember which\n \/\/ blocks we know to be transparent to the load.\n std::set<BasicBlock*> TranspBlocks;\n\n AliasAnalysis &AA = getAnalysis<AliasAnalysis>();\n\n for (unsigned i = 0, e = Loads.size(); i != e; ++i) {\n \/\/ Check to see if the load is invalidated from the start of the block to\n \/\/ the load itself.\n LoadInst *Load = Loads[i];\n BasicBlock *BB = Load->getParent();\n if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))\n return false; \/\/ Pointer is invalidated!\n\n \/\/ Now check every path from the entry block to the load for transparency.\n \/\/ To do this, we perform a depth first search on the inverse CFG from the\n \/\/ loading block.\n for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)\n for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),\n E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)\n if (AA.canBasicBlockModify(**I, Arg, LoadSize))\n return false;\n }\n\n \/\/ If the path from the entry of the function to each load is free of\n \/\/ instructions that potentially invalidate the load, we can make the\n \/\/ transformation!\n return true;\n}\n\n\nvoid ArgPromotion::DoPromotion(Function *F, std::vector<Argument*> &Args2Prom) {\n std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());\n \n \/\/ Start by computing a new prototype for the function, which is the same as\n \/\/ the old function, but has modified arguments.\n const FunctionType *FTy = F->getFunctionType();\n std::vector<const Type*> Params;\n\n for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)\n if (!ArgsToPromote.count(I)) {\n Params.push_back(I->getType());\n } else if (!I->use_empty()) {\n Params.push_back(cast<PointerType>(I->getType())->getElementType());\n ++NumArgumentsPromoted;\n } else {\n ++NumArgumentsDead;\n }\n\n const Type *RetTy = FTy->getReturnType();\n\n \/\/ Work around LLVM bug PR56: the CWriter cannot emit varargs functions which\n \/\/ have zero fixed arguments.\n bool ExtraArgHack = false;\n if (Params.empty() && FTy->isVarArg()) {\n ExtraArgHack = true;\n Params.push_back(Type::IntTy);\n }\n FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());\n \n \/\/ Create the new function body and insert it into the module...\n Function *NF = new Function(NFTy, F->getLinkage(), F->getName());\n F->getParent()->getFunctionList().insert(F, NF);\n \n \/\/ Loop over all of the callers of the function, transforming the call sites\n \/\/ to pass in the loaded pointers.\n \/\/\n std::vector<Value*> Args;\n while (!F->use_empty()) {\n CallSite CS = CallSite::get(F->use_back());\n Instruction *Call = CS.getInstruction();\n\n \/\/ Make sure the caller of this function is revisited.\n if (Call->getParent()->getParent()->hasInternalLinkage())\n WorkList.insert(Call->getParent()->getParent());\n \n \/\/ Loop over the operands, deleting dead ones...\n CallSite::arg_iterator AI = CS.arg_begin();\n for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)\n if (!ArgsToPromote.count(I))\n Args.push_back(*AI); \/\/ Unmodified argument\n else if (!I->use_empty()) {\n \/\/ Non-dead instruction\n Args.push_back(new LoadInst(*AI, (*AI)->getName()+\".val\", Call));\n }\n\n if (ExtraArgHack)\n Args.push_back(Constant::getNullValue(Type::IntTy));\n\n \/\/ Push any varargs arguments on the list\n for (; AI != CS.arg_end(); ++AI)\n Args.push_back(*AI);\n\n Instruction *New;\n if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {\n New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),\n Args, \"\", Call);\n } else {\n New = new CallInst(NF, Args, \"\", Call);\n }\n Args.clear();\n\n if (!Call->use_empty()) {\n Call->replaceAllUsesWith(New);\n std::string Name = Call->getName();\n Call->setName(\"\");\n New->setName(Name);\n }\n \n \/\/ Finally, remove the old call from the program, reducing the use-count of\n \/\/ F.\n Call->getParent()->getInstList().erase(Call);\n }\n\n \/\/ Since we have now created the new function, splice the body of the old\n \/\/ function right into the new function, leaving the old rotting hulk of the\n \/\/ function empty.\n NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());\n\n \/\/ Loop over the argument list, transfering uses of the old arguments over to\n \/\/ the new arguments, also transfering over the names as well.\n \/\/\n for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();\n I != E; ++I)\n if (!ArgsToPromote.count(I)) {\n \/\/ If this is an unmodified argument, move the name and users over to the\n \/\/ new version.\n I->replaceAllUsesWith(I2);\n I2->setName(I->getName());\n ++I2;\n } else if (!I->use_empty()) {\n \/\/ Otherwise, if we promoted this argument, then all users are load\n \/\/ instructions, and all loads should be using the new argument that we\n \/\/ added.\n DEBUG(std::cerr << \"*** Promoted argument '\" << I->getName()\n << \"' of function '\" << F->getName() << \"'\\n\");\n I2->setName(I->getName()+\".val\");\n while (!I->use_empty()) {\n LoadInst *LI = cast<LoadInst>(I->use_back());\n LI->replaceAllUsesWith(I2);\n LI->getParent()->getInstList().erase(LI);\n }\n ++I2;\n }\n\n \/\/ Now that the old function is dead, delete it.\n F->getParent()->getFunctionList().erase(F);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"libcef\/browser\/content_browser_client.h\"\n#include \"libcef\/browser\/browser_context.h\"\n#include \"libcef\/browser\/browser_host_impl.h\"\n#include \"libcef\/browser\/browser_main.h\"\n#include \"libcef\/browser\/browser_message_filter.h\"\n#include \"libcef\/browser\/browser_settings.h\"\n#include \"libcef\/browser\/context.h\"\n#include \"libcef\/browser\/resource_dispatcher_host_delegate.h\"\n#include \"libcef\/browser\/thread_util.h\"\n#include \"libcef\/common\/cef_switches.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"content\/public\/browser\/access_token_store.h\"\n#include \"content\/public\/browser\/media_observer.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/resource_dispatcher_host.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nnamespace {\n\n\/\/ In-memory store for access tokens used by geolocation.\nclass CefAccessTokenStore : public content::AccessTokenStore {\n public:\n CefAccessTokenStore() {}\n\n virtual void LoadAccessTokens(\n const LoadAccessTokensCallbackType& callback) OVERRIDE {\n callback.Run(access_token_set_,\n _Context->browser_context()->GetRequestContext());\n }\n\n virtual void SaveAccessToken(\n const GURL& server_url, const string16& access_token) OVERRIDE {\n access_token_set_[server_url] = access_token;\n }\n\n private:\n AccessTokenSet access_token_set_;\n};\n\n} \/\/ namespace\n\n\nclass CefMediaObserver : public content::MediaObserver {\n public:\n CefMediaObserver() {}\n virtual ~CefMediaObserver() {}\n\n virtual void OnDeleteAudioStream(void* host, int stream_id) OVERRIDE {}\n\n virtual void OnSetAudioStreamPlaying(void* host, int stream_id,\n bool playing) OVERRIDE {}\n virtual void OnSetAudioStreamStatus(void* host, int stream_id,\n const std::string& status) OVERRIDE {}\n virtual void OnSetAudioStreamVolume(void* host, int stream_id,\n double volume) OVERRIDE {}\n virtual void OnMediaEvent(int render_process_id,\n const media::MediaLogEvent& event) OVERRIDE {}\n virtual void OnCaptureDevicesOpened(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevices& devices) OVERRIDE {}\n virtual void OnCaptureDevicesClosed(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevices& devices) OVERRIDE {}\n};\n\n\nCefContentBrowserClient::CefContentBrowserClient()\n : browser_main_parts_(NULL) {\n}\n\nCefContentBrowserClient::~CefContentBrowserClient() {\n}\n\ncontent::BrowserMainParts* CefContentBrowserClient::CreateBrowserMainParts(\n const content::MainFunctionParams& parameters) {\n browser_main_parts_ = new CefBrowserMainParts(parameters);\n return browser_main_parts_;\n}\n\nvoid CefContentBrowserClient::RenderProcessHostCreated(\n content::RenderProcessHost* host) {\n host->GetChannel()->AddFilter(new CefBrowserMessageFilter(host));\n}\n\nvoid CefContentBrowserClient::AppendExtraCommandLineSwitches(\n CommandLine* command_line, int child_process_id) {\n std::string process_type =\n command_line->GetSwitchValueASCII(switches::kProcessType);\n if (process_type == switches::kRendererProcess) {\n \/\/ Propagate the following switches to the renderer command line (along\n \/\/ with any associated values) if present in the browser command line.\n static const char* const kSwitchNames[] = {\n switches::kLogFile,\n switches::kLogSeverity,\n switches::kProductVersion,\n switches::kLocale,\n switches::kResourcesDirPath,\n switches::kLocalesDirPath,\n switches::kPackLoadingDisabled,\n };\n const CommandLine& browser_cmd = *CommandLine::ForCurrentProcess();\n command_line->CopySwitchesFrom(browser_cmd, kSwitchNames,\n arraysize(kSwitchNames));\n }\n}\n\ncontent::MediaObserver* CefContentBrowserClient::GetMediaObserver() {\n \/\/ TODO(cef): Return NULL once it's supported. See crbug.com\/116113.\n if (!media_observer_.get())\n media_observer_.reset(new CefMediaObserver());\n return media_observer_.get();\n}\n\ncontent::AccessTokenStore* CefContentBrowserClient::CreateAccessTokenStore() {\n return new CefAccessTokenStore;\n}\n\nvoid CefContentBrowserClient::ResourceDispatcherHostCreated() {\n resource_dispatcher_host_delegate_.reset(\n new CefResourceDispatcherHostDelegate());\n content::ResourceDispatcherHost::Get()->SetDelegate(\n resource_dispatcher_host_delegate_.get());\n}\n\nvoid CefContentBrowserClient::OverrideWebkitPrefs(\n content::RenderViewHost* rvh,\n const GURL& url,\n webkit_glue::WebPreferences* prefs) {\n CefRefPtr<CefBrowserHostImpl> browser =\n CefBrowserHostImpl::GetBrowserForHost(rvh);\n DCHECK(browser.get());\n\n \/\/ Populate WebPreferences based on CefBrowserSettings.\n BrowserToWebSettings(browser->settings(), *prefs);\n}\n\nstd::string CefContentBrowserClient::GetDefaultDownloadName() {\n return \"download\";\n}\n<commit_msg>Propagate logging command-line parameters to all processes (issue #717).<commit_after>\/\/ 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 \"libcef\/browser\/content_browser_client.h\"\n#include \"libcef\/browser\/browser_context.h\"\n#include \"libcef\/browser\/browser_host_impl.h\"\n#include \"libcef\/browser\/browser_main.h\"\n#include \"libcef\/browser\/browser_message_filter.h\"\n#include \"libcef\/browser\/browser_settings.h\"\n#include \"libcef\/browser\/context.h\"\n#include \"libcef\/browser\/resource_dispatcher_host_delegate.h\"\n#include \"libcef\/browser\/thread_util.h\"\n#include \"libcef\/common\/cef_switches.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"content\/public\/browser\/access_token_store.h\"\n#include \"content\/public\/browser\/media_observer.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/resource_dispatcher_host.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nnamespace {\n\n\/\/ In-memory store for access tokens used by geolocation.\nclass CefAccessTokenStore : public content::AccessTokenStore {\n public:\n CefAccessTokenStore() {}\n\n virtual void LoadAccessTokens(\n const LoadAccessTokensCallbackType& callback) OVERRIDE {\n callback.Run(access_token_set_,\n _Context->browser_context()->GetRequestContext());\n }\n\n virtual void SaveAccessToken(\n const GURL& server_url, const string16& access_token) OVERRIDE {\n access_token_set_[server_url] = access_token;\n }\n\n private:\n AccessTokenSet access_token_set_;\n};\n\n} \/\/ namespace\n\n\nclass CefMediaObserver : public content::MediaObserver {\n public:\n CefMediaObserver() {}\n virtual ~CefMediaObserver() {}\n\n virtual void OnDeleteAudioStream(void* host, int stream_id) OVERRIDE {}\n\n virtual void OnSetAudioStreamPlaying(void* host, int stream_id,\n bool playing) OVERRIDE {}\n virtual void OnSetAudioStreamStatus(void* host, int stream_id,\n const std::string& status) OVERRIDE {}\n virtual void OnSetAudioStreamVolume(void* host, int stream_id,\n double volume) OVERRIDE {}\n virtual void OnMediaEvent(int render_process_id,\n const media::MediaLogEvent& event) OVERRIDE {}\n virtual void OnCaptureDevicesOpened(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevices& devices) OVERRIDE {}\n virtual void OnCaptureDevicesClosed(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevices& devices) OVERRIDE {}\n};\n\n\nCefContentBrowserClient::CefContentBrowserClient()\n : browser_main_parts_(NULL) {\n}\n\nCefContentBrowserClient::~CefContentBrowserClient() {\n}\n\ncontent::BrowserMainParts* CefContentBrowserClient::CreateBrowserMainParts(\n const content::MainFunctionParams& parameters) {\n browser_main_parts_ = new CefBrowserMainParts(parameters);\n return browser_main_parts_;\n}\n\nvoid CefContentBrowserClient::RenderProcessHostCreated(\n content::RenderProcessHost* host) {\n host->GetChannel()->AddFilter(new CefBrowserMessageFilter(host));\n}\n\nvoid CefContentBrowserClient::AppendExtraCommandLineSwitches(\n CommandLine* command_line, int child_process_id) {\n const CommandLine& browser_cmd = *CommandLine::ForCurrentProcess();\n\n {\n \/\/ Propagate the following switches to all command lines (along with any\n \/\/ associated values) if present in the browser command line.\n static const char* const kSwitchNames[] = {\n switches::kLogFile,\n switches::kLogSeverity,\n };\n command_line->CopySwitchesFrom(browser_cmd, kSwitchNames,\n arraysize(kSwitchNames));\n }\n\n std::string process_type =\n command_line->GetSwitchValueASCII(switches::kProcessType);\n if (process_type == switches::kRendererProcess) {\n \/\/ Propagate the following switches to the renderer command line (along with\n \/\/ any associated values) if present in the browser command line.\n static const char* const kSwitchNames[] = {\n switches::kProductVersion,\n switches::kLocale,\n switches::kResourcesDirPath,\n switches::kLocalesDirPath,\n switches::kPackLoadingDisabled,\n };\n command_line->CopySwitchesFrom(browser_cmd, kSwitchNames,\n arraysize(kSwitchNames));\n }\n}\n\ncontent::MediaObserver* CefContentBrowserClient::GetMediaObserver() {\n \/\/ TODO(cef): Return NULL once it's supported. See crbug.com\/116113.\n if (!media_observer_.get())\n media_observer_.reset(new CefMediaObserver());\n return media_observer_.get();\n}\n\ncontent::AccessTokenStore* CefContentBrowserClient::CreateAccessTokenStore() {\n return new CefAccessTokenStore;\n}\n\nvoid CefContentBrowserClient::ResourceDispatcherHostCreated() {\n resource_dispatcher_host_delegate_.reset(\n new CefResourceDispatcherHostDelegate());\n content::ResourceDispatcherHost::Get()->SetDelegate(\n resource_dispatcher_host_delegate_.get());\n}\n\nvoid CefContentBrowserClient::OverrideWebkitPrefs(\n content::RenderViewHost* rvh,\n const GURL& url,\n webkit_glue::WebPreferences* prefs) {\n CefRefPtr<CefBrowserHostImpl> browser =\n CefBrowserHostImpl::GetBrowserForHost(rvh);\n DCHECK(browser.get());\n\n \/\/ Populate WebPreferences based on CefBrowserSettings.\n BrowserToWebSettings(browser->settings(), *prefs);\n}\n\nstd::string CefContentBrowserClient::GetDefaultDownloadName() {\n return \"download\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n kopetefileconfirmdialog.cpp\n\n Copyright (c) 2003-2004 by Olivier Goffart <ogoffart @ kde.org>\n\n Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\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 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <qtextedit.h>\n\n#include <klineedit.h>\n#include <kconfig.h>\n#include <klocale.h>\n#include <kfiledialog.h>\n#include <kpushbutton.h>\n#include <kmessagebox.h>\n\n\/\/#include \"kopetetransfermanager.h\"\n#include \"fileconfirmbase.h\"\n#include \"kopetefileconfirmdialog.h\"\n\n#include \"kopetemetacontact.h\"\n#include \"kopetecontact.h\"\n\nKopeteFileConfirmDialog::KopeteFileConfirmDialog(const Kopete::FileTransferInfo &info,const QString& description,QWidget *parent, const char *name )\n: KDialogBase( parent, name, false, i18n( \"A User Would Like to Send You a File\" ),\n\tKDialogBase::User1 | KDialogBase::User2, KDialogBase::User1, true, i18n( \"&Refuse\" ), i18n( \"&Accept\" ) ),\n\tm_info( info )\n{\n\tsetWFlags( WDestructiveClose );\n\tm_emited=false;\n\n\tm_view=new FileConfirmBase(this, \"FileConfirmView\");\n\tm_view->m_from->setText( info.contact()->metaContact()->displayName() + QString::fromLatin1( \" <\" ) +\n\t\t\tinfo.contact()->contactId() + QString::fromLatin1( \"> \" ) );\n\tm_view->m_size->setText( KGlobal::locale()->formatNumber( long( info.size() ) ) );\n\tm_view->m_description->setText( description );\n\tm_view->m_filename->setText( info.file() );\n\t\n\tKGlobal::config()->setGroup(\"File Transfer\");\n\tconst QString defaultPath=KGlobal::config()->readEntry(\"defaultPath\" , QDir::homeDirPath() );\n\tm_view->m_saveto->setText(defaultPath + QString::fromLatin1( \"\/\" ) + info.file() );\n\n\tsetMainWidget(m_view);\n\n\tconnect(m_view->cmdBrowse, SIGNAL(pressed()), this, SLOT(slotBrowsePressed()));\n}\n\nKopeteFileConfirmDialog::~KopeteFileConfirmDialog()\n{\n}\n\nvoid KopeteFileConfirmDialog::slotBrowsePressed()\n{\n\tQString saveFileName = KFileDialog::getSaveFileName( m_view->m_saveto->text(), QString::fromLatin1( \"*\" ), 0L , i18n( \"File Transfer\" ) );\n\tif ( !saveFileName.isNull())\n\t{\n\t\tm_view->m_saveto->setText(saveFileName);\n\t}\n}\n\nvoid KopeteFileConfirmDialog::slotUser2()\n{\n\tm_emited=true;\n\tKURL url(m_view->m_saveto->text());\n\tif(url.isValid() && url.isLocalFile() )\n\t{\n\t\tconst QString directory=url.directory();\n\t\tif(!directory.isEmpty())\n\t\t{\n\t\t\tKGlobal::config()->setGroup(\"File Transfer\");\n\t\t\tKGlobal::config()->writeEntry(\"defaultPath\" , directory );\n\t\t}\n\t\t\n\t\tif(QFile(m_view->m_saveto->text()).exists())\n\t\t{\n\t\t\tint ret=KMessageBox::warningContinueCancel(this, i18n(\"The file '%1' already exists.\\nDo you want to overwrite it ?\").arg(m_view->m_saveto->text()) ,\n\t\t\t\t\t i18n(\"Overwrite File\") , KStdGuiItem::save());\n\t\t\tif(ret==KMessageBox::Cancel)\n\t\t\t\treturn;\n\t\t}\n\t \n\t\temit accepted(m_info,m_view->m_saveto->text());\n\t\tclose();\n\t}\n\telse\n\t\tKMessageBox::queuedMessageBox (this, KMessageBox::Sorry, i18n(\"You must provide a valid local filename\") );\n}\n\nvoid KopeteFileConfirmDialog::slotUser1()\n{\n\tm_emited=true;\n\temit refused(m_info);\n\tclose();\n}\n\nvoid KopeteFileConfirmDialog::closeEvent( QCloseEvent *e)\n{\n\tif(!m_emited)\n\t{\n\t\tm_emited=true;\n\t\temit refused(m_info);\n\t}\n\tKDialogBase::closeEvent(e);\n}\n\n#include \"kopetefileconfirmdialog.moc\"\n\n<commit_msg>the file size is a whole number (port from 3.5 branch, revision 490969)<commit_after>\/*\n kopetefileconfirmdialog.cpp\n\n Copyright (c) 2003-2004 by Olivier Goffart <ogoffart @ kde.org>\n\n Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\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 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <qtextedit.h>\n\n#include <klineedit.h>\n#include <kconfig.h>\n#include <klocale.h>\n#include <kfiledialog.h>\n#include <kpushbutton.h>\n#include <kmessagebox.h>\n\n\/\/#include \"kopetetransfermanager.h\"\n#include \"fileconfirmbase.h\"\n#include \"kopetefileconfirmdialog.h\"\n\n#include \"kopetemetacontact.h\"\n#include \"kopetecontact.h\"\n\nKopeteFileConfirmDialog::KopeteFileConfirmDialog(const Kopete::FileTransferInfo &info,const QString& description,QWidget *parent, const char *name )\n: KDialogBase( parent, name, false, i18n( \"A User Would Like to Send You a File\" ),\n\tKDialogBase::User1 | KDialogBase::User2, KDialogBase::User1, true, i18n( \"&Refuse\" ), i18n( \"&Accept\" ) ),\n\tm_info( info )\n{\n\tsetWFlags( WDestructiveClose );\n\tm_emited=false;\n\n\tm_view=new FileConfirmBase(this, \"FileConfirmView\");\n\tm_view->m_from->setText( info.contact()->metaContact()->displayName() + QString::fromLatin1( \" <\" ) +\n\t\t\tinfo.contact()->contactId() + QString::fromLatin1( \"> \" ) );\n\tm_view->m_size->setText( KGlobal::locale()->formatNumber( long( info.size() ), 0 ) );\n\tm_view->m_description->setText( description );\n\tm_view->m_filename->setText( info.file() );\n\t\n\tKGlobal::config()->setGroup(\"File Transfer\");\n\tconst QString defaultPath=KGlobal::config()->readEntry(\"defaultPath\" , QDir::homeDirPath() );\n\tm_view->m_saveto->setText(defaultPath + QString::fromLatin1( \"\/\" ) + info.file() );\n\n\tsetMainWidget(m_view);\n\n\tconnect(m_view->cmdBrowse, SIGNAL(pressed()), this, SLOT(slotBrowsePressed()));\n}\n\nKopeteFileConfirmDialog::~KopeteFileConfirmDialog()\n{\n}\n\nvoid KopeteFileConfirmDialog::slotBrowsePressed()\n{\n\tQString saveFileName = KFileDialog::getSaveFileName( m_view->m_saveto->text(), QString::fromLatin1( \"*\" ), 0L , i18n( \"File Transfer\" ) );\n\tif ( !saveFileName.isNull())\n\t{\n\t\tm_view->m_saveto->setText(saveFileName);\n\t}\n}\n\nvoid KopeteFileConfirmDialog::slotUser2()\n{\n\tm_emited=true;\n\tKURL url(m_view->m_saveto->text());\n\tif(url.isValid() && url.isLocalFile() )\n\t{\n\t\tconst QString directory=url.directory();\n\t\tif(!directory.isEmpty())\n\t\t{\n\t\t\tKGlobal::config()->setGroup(\"File Transfer\");\n\t\t\tKGlobal::config()->writeEntry(\"defaultPath\" , directory );\n\t\t}\n\t\t\n\t\tif(QFile(m_view->m_saveto->text()).exists())\n\t\t{\n\t\t\tint ret=KMessageBox::warningContinueCancel(this, i18n(\"The file '%1' already exists.\\nDo you want to overwrite it ?\").arg(m_view->m_saveto->text()) ,\n\t\t\t\t\t i18n(\"Overwrite File\") , KStdGuiItem::save());\n\t\t\tif(ret==KMessageBox::Cancel)\n\t\t\t\treturn;\n\t\t}\n\t \n\t\temit accepted(m_info,m_view->m_saveto->text());\n\t\tclose();\n\t}\n\telse\n\t\tKMessageBox::queuedMessageBox (this, KMessageBox::Sorry, i18n(\"You must provide a valid local filename\") );\n}\n\nvoid KopeteFileConfirmDialog::slotUser1()\n{\n\tm_emited=true;\n\temit refused(m_info);\n\tclose();\n}\n\nvoid KopeteFileConfirmDialog::closeEvent( QCloseEvent *e)\n{\n\tif(!m_emited)\n\t{\n\t\tm_emited=true;\n\t\temit refused(m_info);\n\t}\n\tKDialogBase::closeEvent(e);\n}\n\n#include \"kopetefileconfirmdialog.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by everettjf on 2017\/8\/4.\n\/\/\n\n#include \"LoadCommandViewNode.h\"\n\n#include \"..\/node\/loadcmd\/LoadCommand_SEGMENT.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_DYLIB.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_DYLD_INFO.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_SYMTAB.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_DYSYMTAB.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_LOAD_DYLINKER.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_UUID.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_VERSION_MIN.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_SOURCE_VERSION.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_MAIN.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_ENCRYPTION_INFO.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_LINKEDIT_DATA.h\"\n\n\/*\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT_64)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_DYLIB, DYLIB)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_WEAK_DYLIB, DYLIB)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_REEXPORT_DYLIB, DYLIB)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO, DYLD_INFO)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO_ONLY, DYLD_INFO)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SYMTAB)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_DYSYMTAB)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_LOAD_DYLINKER)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_UUID)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_IPHONEOS, VERSION_MIN)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_MACOSX, VERSION_MIN)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_TVOS, VERSION_MIN)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_WATCHOS, VERSION_MIN)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SOURCE_VERSION)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_MAIN)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO_64)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_CODE_SIGNATURE, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_SEGMENT_SPLIT_INFO, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_FUNCTION_STARTS, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DATA_IN_CODE, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLIB_CODE_SIGN_DRS, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LINKER_OPTIMIZATION_HINT, LINKEDIT_DATA)\n *\/\n\n\nMOEX_NAMESPACE_BEGIN\n\nstd::string LoadCommandViewNode::GetDisplayName(){\n std::string charact = d_->GetShortCharacteristicDescription();\n if(charact.length() > 0){\n return boost::str(boost::format(\"%1%(%2%)\")%d_->GetLoadCommandTypeString()%charact);\n }else{\n return d_->GetLoadCommandTypeString();\n }\n}\n\n\n#define IMPL_LOADCOMMAND_VIEWNODE_BEGIN_CLASS(segment,classname) \\\nclass LoadCommandViewNode_##segment : public LoadCommandViewNode{ \\\npublic:\\\n void InitViewDatas()override{\\\n auto t = CreateTableViewDataPtr();\\\n auto b = CreateBinaryViewDataPtr();\\\n LoadCommand_##classname *cmd = static_cast<LoadCommand_##classname*>(d_.get());\n\n\n#define IMPL_LOADCOMMAND_VIEWNODE_BEGIN(segment) \\\nclass LoadCommandViewNode_##segment : public LoadCommandViewNode{ \\\npublic:\\\n void InitViewDatas()override{\\\n auto t = CreateTableViewDataPtr();\\\n auto b = CreateBinaryViewDataPtr();\\\n LoadCommand_##segment *cmd = static_cast<LoadCommand_##segment*>(d_.get());\n\n\n#define IMPL_LOADCOMMAND_VIEWNODE_END\\\n if(!t->IsEmpty()) AddViewData(t);\\\n if(!b->IsEmpty()) AddViewData(b);\\\n }\\\n};\n\n\n\n#define CASE_LOADCOMMAND_VIEWNODE(segment) \\\n case segment: { \\\n res = std::make_shared<LoadCommandViewNode_##segment>();\\\n break;\\\n }\n\n\nIMPL_LOADCOMMAND_VIEWNODE_BEGIN(LC_SEGMENT)\n\nIMPL_LOADCOMMAND_VIEWNODE_END\n\n\nLoadCommandViewNodePtr LoadCommandViewNodeFactory::Create(LoadCommandPtr d){\n LoadCommandViewNodePtr res;\n switch(d->GetCommand()){\n CASE_LOADCOMMAND_VIEWNODE(LC_SEGMENT)\n default:{\n res = std::make_shared<LoadCommandViewNode>();\n break;\n }\n }\n res->Init(d);\n return res;\n}\n\n\nMOEX_NAMESPACE_END<commit_msg>ready one<commit_after>\/\/\n\/\/ Created by everettjf on 2017\/8\/4.\n\/\/\n\n#include \"LoadCommandViewNode.h\"\n\n#include \"..\/node\/loadcmd\/LoadCommand_SEGMENT.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_DYLIB.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_DYLD_INFO.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_SYMTAB.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_DYSYMTAB.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_LOAD_DYLINKER.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_UUID.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_VERSION_MIN.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_SOURCE_VERSION.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_MAIN.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_ENCRYPTION_INFO.h\"\n#include \"..\/node\/loadcmd\/LoadCommand_LINKEDIT_DATA.h\"\n\n\/*\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT_64)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_DYLIB, DYLIB)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_WEAK_DYLIB, DYLIB)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_REEXPORT_DYLIB, DYLIB)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO, DYLD_INFO)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO_ONLY, DYLD_INFO)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SYMTAB)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_DYSYMTAB)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_LOAD_DYLINKER)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_UUID)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_IPHONEOS, VERSION_MIN)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_MACOSX, VERSION_MIN)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_TVOS, VERSION_MIN)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_WATCHOS, VERSION_MIN)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SOURCE_VERSION)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_MAIN)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO_64)\n\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_CODE_SIGNATURE, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_SEGMENT_SPLIT_INFO, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_FUNCTION_STARTS, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DATA_IN_CODE, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLIB_CODE_SIGN_DRS, LINKEDIT_DATA)\n DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LINKER_OPTIMIZATION_HINT, LINKEDIT_DATA)\n *\/\n\n\nMOEX_NAMESPACE_BEGIN\n\nstd::string LoadCommandViewNode::GetDisplayName(){\n std::string charact = d_->GetShortCharacteristicDescription();\n if(charact.length() > 0){\n return boost::str(boost::format(\"%1%(%2%)\")%d_->GetLoadCommandTypeString()%charact);\n }else{\n return d_->GetLoadCommandTypeString();\n }\n}\n\n\n#define IMPL_LOADCOMMAND_VIEWNODE_BEGIN_CLASS(segment,classname) \\\nclass LoadCommandViewNode_##segment : public LoadCommandViewNode{ \\\npublic:\\\n void InitViewDatas()override{\\\n using namespace moex::util;\\\n auto t = CreateTableViewDataPtr();\\\n auto b = CreateBinaryViewDataPtr();\\\n LoadCommand_##classname *c = static_cast<LoadCommand_##classname*>(d_.get());\\\n t->AddRow(c->GetRAW(&(c->cmd()->cmd)),c->cmd()->cmd,\"Command\",c->GetLoadCommandTypeString());\\\n t->AddRow(c->GetRAW(&(c->cmd()->cmdsize)),c->cmd()->cmdsize,\"Command Size\",AsString(c->cmd()->cmdsize));\\\n t->AddSeparator();\n\n\n#define IMPL_LOADCOMMAND_VIEWNODE_BEGIN(segment)\\\nclass LoadCommandViewNode_##segment : public LoadCommandViewNode{ \\\npublic:\\\n void InitViewDatas()override{\\\n using namespace moex::util;\\\n auto t = CreateTableViewDataPtr();\\\n auto b = CreateBinaryViewDataPtr();\\\n LoadCommand_##segment *c = static_cast<LoadCommand_##segment*>(d_.get());\\\n t->AddRow(c->GetRAW(&(c->cmd()->cmd)),c->cmd()->cmd,\"Command\",c->GetLoadCommandTypeString());\\\n t->AddRow(c->GetRAW(&(c->cmd()->cmdsize)),c->cmd()->cmdsize,\"Command Size\",AsString(c->cmd()->cmdsize));\\\n t->AddSeparator();\n\n\n#define IMPL_LOADCOMMAND_VIEWNODE_END\\\n if(!t->IsEmpty()) AddViewData(t);\\\n if(!b->IsEmpty()) AddViewData(b);\\\n }\\\n};\n\n\n\n#define CASE_LOADCOMMAND_VIEWNODE(segment) \\\n case segment: { \\\n res = std::make_shared<LoadCommandViewNode_##segment>();\\\n break;\\\n }\n\n\nIMPL_LOADCOMMAND_VIEWNODE_BEGIN(LC_SEGMENT)\n\nIMPL_LOADCOMMAND_VIEWNODE_END\n\n\nLoadCommandViewNodePtr LoadCommandViewNodeFactory::Create(LoadCommandPtr d){\n LoadCommandViewNodePtr res;\n switch(d->GetCommand()){\n CASE_LOADCOMMAND_VIEWNODE(LC_SEGMENT)\n default:{\n res = std::make_shared<LoadCommandViewNode>();\n break;\n }\n }\n res->Init(d);\n return res;\n}\n\n\nMOEX_NAMESPACE_END<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#define BTS_NET_PROTOCOL_VERSION 104 \/\/ protocol version to be used in testnet3\n\n\/** \n * Define this to enable debugging code in the p2p network interface.\n * This is code that would never be executed in normal operation, but is\n * used for automated testing (creating artificial net splits, \n * tracking where messages came from and when)\n *\/\n#define ENABLE_P2P_DEBUGGING_API 1\n\n\/**\n * 512 kb\n *\/\n#define MAX_MESSAGE_SIZE (512*1024) \n#define BTS_NET_DEFAULT_PEER_CONNECTION_RETRY_TIME (30) \/\/ seconds\n\n\/**\n * AFter trying all peers, how long to wait before we check to\n * see if there are peers we can try again.\n *\/\n#define BTS_PEER_DATABASE_RETRY_DELAY (15) \/\/ seconds\n\n#define BTS_NET_PEER_HANDSHAKE_INACTIVITY_TIMEOUT (5) \n\n#define BTS_NET_PEER_DISCONNECT_TIMEOUT (20) \n\n#define BTS_NETWORK_DEFAULT_P2P_PORT 8601\n#define BTS_NET_DEFAULT_DESIRED_CONNECTIONS 12 \n#define BTS_NET_DEFAULT_MAX_CONNECTIONS 200\n<commit_msg>reducing desired connection count to 8<commit_after>#pragma once\n\n#define BTS_NET_PROTOCOL_VERSION 104 \/\/ protocol version to be used in testnet3\n\n\/** \n * Define this to enable debugging code in the p2p network interface.\n * This is code that would never be executed in normal operation, but is\n * used for automated testing (creating artificial net splits, \n * tracking where messages came from and when)\n *\/\n#define ENABLE_P2P_DEBUGGING_API 1\n\n\/**\n * 512 kb\n *\/\n#define MAX_MESSAGE_SIZE (512*1024) \n#define BTS_NET_DEFAULT_PEER_CONNECTION_RETRY_TIME (30) \/\/ seconds\n\n\/**\n * AFter trying all peers, how long to wait before we check to\n * see if there are peers we can try again.\n *\/\n#define BTS_PEER_DATABASE_RETRY_DELAY (15) \/\/ seconds\n\n#define BTS_NET_PEER_HANDSHAKE_INACTIVITY_TIMEOUT (5) \n\n#define BTS_NET_PEER_DISCONNECT_TIMEOUT (20) \n\n#define BTS_NETWORK_DEFAULT_P2P_PORT 8701\n#define BTS_NET_DEFAULT_DESIRED_CONNECTIONS 8 \n#define BTS_NET_DEFAULT_MAX_CONNECTIONS 200\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file\n * @author Alexander Sherikov\n *\/\n\n#include <cmath> \/\/ sqrt\n\n#include \"WMG.h\"\n#include \"footstep.h\"\n\n\n\n\/**\n * @brief Returns index of the next SS.\n *\n * @param[in] start_ind start search from this index.\n * @param[in] type search for a footstep of certain type,\n * by default (FS_TYPE_AUTO) both left and right\n * are searched.\n *\n * @return index of the next SS.\n *\/\nint WMG::getNextSS(const int start_ind, const fs_type type)\n{\n int index = start_ind + 1;\n for (; index < (int) FS.size(); index++) \n {\n if (FS[index].type != FS_TYPE_DS)\n {\n if (type == FS_TYPE_AUTO)\n {\n break;\n }\n else\n {\n if (FS[index].type == type)\n {\n break;\n }\n }\n }\n }\n return (index);\n}\n\n\n\n\/**\n * @brief Returns index of the previous SS.\n *\n * @param[in] start_ind start search from this index.\n * @param[in] type search for a footstep of certain type,\n * by default (FS_TYPE_AUTO) both left and right\n * are searched.\n *\n * @return index of the previous SS.\n *\/\nint WMG::getPrevSS(const int start_ind, const fs_type type)\n{\n int index = start_ind - 1;\n for (; index >= 0; index--)\n {\n if (FS[index].type != FS_TYPE_DS)\n {\n if (type == FS_TYPE_AUTO)\n {\n break;\n }\n else\n {\n if (FS[index].type == type)\n {\n break;\n }\n }\n }\n }\n return (index);\n}\n\n\n\n\/**\n * @brief Determine position and orientation of feet in DS\n *\n * @param[in] support_number number of the support\n * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n *\/\nvoid WMG::getDSFeetPositions (\n const int support_number,\n double *left_foot_pos,\n double *right_foot_pos)\n{\n int left_ind, right_ind;\n\n left_ind = getNextSS (support_number);\n if (FS[left_ind].type == FS_TYPE_SS_L)\n {\n right_ind = getPrevSS (support_number);\n }\n else\n {\n right_ind = left_ind;\n left_ind = getPrevSS (support_number);\n }\n\n Matrix4d::Map(left_foot_pos) = FS[left_ind].posture->matrix();\n Matrix4d::Map(right_foot_pos) = FS[right_ind].posture->matrix();\n}\n\n\n\n\/**\n * @brief Determine position and orientation of feet (parabolic trajectory)\n *\n * @param[in] support_number number of the support\n * @param[in] theta a number between 0 and 1, a fraction of support time that have passed \n * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n *\/\nvoid WMG::getSSFeetPositions (\n const int support_number,\n const double theta,\n double *left_foot_pos,\n double *right_foot_pos)\n{\n double *swing_foot_pos, *ref_foot_pos;\n int next_swing_ind, prev_swing_ind;\n footstep& current_step = FS[support_number];\n\n\n if (current_step.type == FS_TYPE_SS_L)\n {\n ref_foot_pos = left_foot_pos;\n swing_foot_pos = right_foot_pos;\n\n prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_R);\n next_swing_ind = getNextSS (support_number, FS_TYPE_SS_R);\n }\n else\n {\n ref_foot_pos = right_foot_pos;\n swing_foot_pos = left_foot_pos;\n\n prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_L);\n next_swing_ind = getNextSS (support_number, FS_TYPE_SS_L);\n }\n\n Matrix4d::Map(ref_foot_pos) = current_step.posture->matrix();\n\n\n double dx = FS[next_swing_ind].x() - FS[prev_swing_ind].x();\n double dy = FS[next_swing_ind].y() - FS[prev_swing_ind].y();\n double l = sqrt(dx*dx + dy*dy);\n\n\n double x[3] = {0.0, l\/2, l};\n double b_coef = - (x[2]*x[2] \/*- x[0]*x[0]*\/)\/(x[2] \/*- x[0]*\/);\n double a = step_height \/ (x[1]*x[1] \/*- x[0]*x[0]*\/ + b_coef*(x[1] \/*- x[0]*\/));\n double b = a * b_coef;\n \/\/double c = - a*x[0]*x[0] - b*x[0];\n\n\n double dl = \/*(1-theta)*x[0] +*\/ theta * l;\n\n Matrix4d::Map(swing_foot_pos) = (\n (*FS[prev_swing_ind].posture)\n * Translation<double, 3>(theta * dx, theta * dy, a*dl*dl + b*dl)\n * AngleAxisd(FS[next_swing_ind].angle - FS[prev_swing_ind].angle, Vector3d::UnitZ())\n ).matrix();\n}\n\n\n\n\/**\n * @brief Determine position and orientation of feet (using cubic Bezier curves)\n *\n * @param[in] support_number number of the support\n * @param[in] theta a number between 0 and 1, a fraction of support time that have passed \n * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n *\/\nvoid WMG::getSSFeetPositionsBezier (\n const int support_number,\n const double theta,\n double *left_foot_pos,\n double *right_foot_pos)\n{\n double *swing_foot_pos, *ref_foot_pos;\n int next_swing_ind, prev_swing_ind;\n int inclination_sign = 0;\n footstep& current_step = FS[support_number];\n\n\n if (current_step.type == FS_TYPE_SS_L)\n {\n inclination_sign = -1;\n\n ref_foot_pos = left_foot_pos;\n swing_foot_pos = right_foot_pos;\n\n prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_R);\n next_swing_ind = getNextSS (support_number, FS_TYPE_SS_R);\n }\n else\n {\n inclination_sign = 1;\n\n ref_foot_pos = right_foot_pos;\n swing_foot_pos = left_foot_pos;\n\n prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_L);\n next_swing_ind = getNextSS (support_number, FS_TYPE_SS_L);\n }\n\n Matrix4d::Map(ref_foot_pos) = current_step.posture->matrix();\n\n\n\n Vector4d weighted_binomial_coef;\n \/\/ Note, that since we want to obtain a curve of a certain height (see below),\n \/\/ the weights have a rather limited impact. They may be useful in future, though.\n double w1 = 1.0;\n double w2 = 2.5;\n \/\/ first number is the weight\n weighted_binomial_coef(0) = 1 * (1-theta)*(1-theta)*(1-theta);\n weighted_binomial_coef(1) = w1 * 3*(1-theta)*(1-theta)*theta;\n weighted_binomial_coef(2) = w2 * 3*(1-theta)*theta*theta;\n weighted_binomial_coef(3) = 1 * theta*theta*theta;\n\n\n Matrix<double, 3, 4> control_points;\n control_points.col(0) = FS[prev_swing_ind].posture->translation();\n control_points.col(3) = FS[next_swing_ind].posture->translation(); \n\n \/\/ In order to reach step_height on z axis in the middle of trajectory, \n \/\/ z coordinates for these two points are derived as follows:\n \/\/ \n \/\/ S = sum of weighted binomial coefficients\n \/\/ 0.5^3 * w0*z0 + 3*0.5^3 * w1*z1 + 3*0.5^3 * w2*z2 + 0.5^3 * w3*z3 = step_height * S\n \/\/ =0 =0 \n \/\/ 3*0.5^3 * (w1*z1 + w2*z2) = step_height * S\n \/\/\n \/\/ lets take z1=z2=z, then:\n \/\/\n \/\/ z = step_height * S \/ (3*0.5^3 * (w1+w2))\n control_points.col(1) = control_points.col(0);\n control_points.col(1).y() += inclination_sign * step_height\/2;\n control_points.col(1).z() = step_height*weighted_binomial_coef.sum() \/ (3*0.5*0.5*0.5 * (w1+w2));\n control_points.col(2) = control_points.col(3);\n control_points.col(2).z() = control_points.col(1).z();\n\n\n Transform<double, 3> swing_posture =\n Translation<double,3>(\n control_points * weighted_binomial_coef \/ weighted_binomial_coef.sum())\n *\n Quaterniond (AngleAxisd (FS[prev_swing_ind].angle,Vector3d::UnitZ())).slerp (\n theta,\n Quaterniond (AngleAxisd (FS[next_swing_ind].angle,Vector3d::UnitZ())));\n\n Matrix4d::Map(swing_foot_pos) = swing_posture.matrix();\n}\n<commit_msg>Foot trajectory: changed parameters of Bezier curve.<commit_after>\/** \n * @file\n * @author Alexander Sherikov\n *\/\n\n#include <cmath> \/\/ sqrt\n\n#include \"WMG.h\"\n#include \"footstep.h\"\n\n\n\n\/**\n * @brief Returns index of the next SS.\n *\n * @param[in] start_ind start search from this index.\n * @param[in] type search for a footstep of certain type,\n * by default (FS_TYPE_AUTO) both left and right\n * are searched.\n *\n * @return index of the next SS.\n *\/\nint WMG::getNextSS(const int start_ind, const fs_type type)\n{\n int index = start_ind + 1;\n for (; index < (int) FS.size(); index++) \n {\n if (FS[index].type != FS_TYPE_DS)\n {\n if (type == FS_TYPE_AUTO)\n {\n break;\n }\n else\n {\n if (FS[index].type == type)\n {\n break;\n }\n }\n }\n }\n return (index);\n}\n\n\n\n\/**\n * @brief Returns index of the previous SS.\n *\n * @param[in] start_ind start search from this index.\n * @param[in] type search for a footstep of certain type,\n * by default (FS_TYPE_AUTO) both left and right\n * are searched.\n *\n * @return index of the previous SS.\n *\/\nint WMG::getPrevSS(const int start_ind, const fs_type type)\n{\n int index = start_ind - 1;\n for (; index >= 0; index--)\n {\n if (FS[index].type != FS_TYPE_DS)\n {\n if (type == FS_TYPE_AUTO)\n {\n break;\n }\n else\n {\n if (FS[index].type == type)\n {\n break;\n }\n }\n }\n }\n return (index);\n}\n\n\n\n\/**\n * @brief Determine position and orientation of feet in DS\n *\n * @param[in] support_number number of the support\n * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n *\/\nvoid WMG::getDSFeetPositions (\n const int support_number,\n double *left_foot_pos,\n double *right_foot_pos)\n{\n int left_ind, right_ind;\n\n left_ind = getNextSS (support_number);\n if (FS[left_ind].type == FS_TYPE_SS_L)\n {\n right_ind = getPrevSS (support_number);\n }\n else\n {\n right_ind = left_ind;\n left_ind = getPrevSS (support_number);\n }\n\n Matrix4d::Map(left_foot_pos) = FS[left_ind].posture->matrix();\n Matrix4d::Map(right_foot_pos) = FS[right_ind].posture->matrix();\n}\n\n\n\n\/**\n * @brief Determine position and orientation of feet (parabolic trajectory)\n *\n * @param[in] support_number number of the support\n * @param[in] theta a number between 0 and 1, a fraction of support time that have passed \n * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n *\/\nvoid WMG::getSSFeetPositions (\n const int support_number,\n const double theta,\n double *left_foot_pos,\n double *right_foot_pos)\n{\n double *swing_foot_pos, *ref_foot_pos;\n int next_swing_ind, prev_swing_ind;\n footstep& current_step = FS[support_number];\n\n\n if (current_step.type == FS_TYPE_SS_L)\n {\n ref_foot_pos = left_foot_pos;\n swing_foot_pos = right_foot_pos;\n\n prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_R);\n next_swing_ind = getNextSS (support_number, FS_TYPE_SS_R);\n }\n else\n {\n ref_foot_pos = right_foot_pos;\n swing_foot_pos = left_foot_pos;\n\n prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_L);\n next_swing_ind = getNextSS (support_number, FS_TYPE_SS_L);\n }\n\n Matrix4d::Map(ref_foot_pos) = current_step.posture->matrix();\n\n\n double dx = FS[next_swing_ind].x() - FS[prev_swing_ind].x();\n double dy = FS[next_swing_ind].y() - FS[prev_swing_ind].y();\n double l = sqrt(dx*dx + dy*dy);\n\n\n double x[3] = {0.0, l\/2, l};\n double b_coef = - (x[2]*x[2] \/*- x[0]*x[0]*\/)\/(x[2] \/*- x[0]*\/);\n double a = step_height \/ (x[1]*x[1] \/*- x[0]*x[0]*\/ + b_coef*(x[1] \/*- x[0]*\/));\n double b = a * b_coef;\n \/\/double c = - a*x[0]*x[0] - b*x[0];\n\n\n double dl = \/*(1-theta)*x[0] +*\/ theta * l;\n\n Matrix4d::Map(swing_foot_pos) = (\n (*FS[prev_swing_ind].posture)\n * Translation<double, 3>(theta * dx, theta * dy, a*dl*dl + b*dl)\n * AngleAxisd(FS[next_swing_ind].angle - FS[prev_swing_ind].angle, Vector3d::UnitZ())\n ).matrix();\n}\n\n\n\n\/**\n * @brief Determine position and orientation of feet (using cubic Bezier curves)\n *\n * @param[in] support_number number of the support\n * @param[in] theta a number between 0 and 1, a fraction of support time that have passed \n * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation\n *\/\nvoid WMG::getSSFeetPositionsBezier (\n const int support_number,\n const double theta,\n double *left_foot_pos,\n double *right_foot_pos)\n{\n double *swing_foot_pos, *ref_foot_pos;\n int next_swing_ind, prev_swing_ind;\n int inclination_sign = 0;\n footstep& current_step = FS[support_number];\n\n\n if (current_step.type == FS_TYPE_SS_L)\n {\n inclination_sign = -1;\n\n ref_foot_pos = left_foot_pos;\n swing_foot_pos = right_foot_pos;\n\n prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_R);\n next_swing_ind = getNextSS (support_number, FS_TYPE_SS_R);\n }\n else\n {\n inclination_sign = 1;\n\n ref_foot_pos = right_foot_pos;\n swing_foot_pos = left_foot_pos;\n\n prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_L);\n next_swing_ind = getNextSS (support_number, FS_TYPE_SS_L);\n }\n\n Matrix4d::Map(ref_foot_pos) = current_step.posture->matrix();\n\n\n\n Vector4d weighted_binomial_coef;\n \/\/ Note, that since we want to obtain a curve of a certain height (see below),\n \/\/ the weights have a rather limited impact. They may be useful in future, though.\n double w1 = 1.0;\n double w2 = 2.0;\n \/\/ first number is the weight\n weighted_binomial_coef(0) = 1 * (1-theta)*(1-theta)*(1-theta);\n weighted_binomial_coef(1) = w1 * 3*(1-theta)*(1-theta)*theta;\n weighted_binomial_coef(2) = w2 * 3*(1-theta)*theta*theta;\n weighted_binomial_coef(3) = 1 * theta*theta*theta;\n\n\n Matrix<double, 3, 4> control_points;\n control_points.col(0) = FS[prev_swing_ind].posture->translation();\n control_points.col(3) = FS[next_swing_ind].posture->translation(); \n\n \/\/ In order to reach step_height on z axis in the middle of trajectory, \n \/\/ z coordinates for these two points are derived as follows:\n \/\/ \n \/\/ S = sum of weighted binomial coefficients\n \/\/ 0.5^3 * w0*z0 + 3*0.5^3 * w1*z1 + 3*0.5^3 * w2*z2 + 0.5^3 * w3*z3 = step_height * S\n \/\/ =0 =0 \n \/\/ 3*0.5^3 * (w1*z1 + w2*z2) = step_height * S\n \/\/\n \/\/ lets take z1=z2=z, then:\n \/\/\n \/\/ z = step_height * S \/ (3*0.5^3 * (w1+w2))\n control_points.col(1) = control_points.col(0);\n control_points.col(1).y() += inclination_sign * step_height\/1.5;\n control_points.col(1).z() = step_height*weighted_binomial_coef.sum() \/ (3*0.5*0.5*0.5 * (w1+w2));\n control_points.col(2) = control_points.col(3);\n control_points.col(2).z() = control_points.col(1).z();\n\n\n Transform<double, 3> swing_posture =\n Translation<double,3>(\n control_points * weighted_binomial_coef \/ weighted_binomial_coef.sum())\n *\n Quaterniond (AngleAxisd (FS[prev_swing_ind].angle,Vector3d::UnitZ())).slerp (\n theta,\n Quaterniond (AngleAxisd (FS[next_swing_ind].angle,Vector3d::UnitZ())));\n\n Matrix4d::Map(swing_foot_pos) = swing_posture.matrix();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Jonathan Buchanan.\n\/\/ This file is part of Sunglasses, which is licensed under the MIT License.\n\/\/ See LICENSE.md for details.\n#include \"SunCamera.h\"\n#include <lua.hpp>\n#include <selene.h>\n\nSunCamera::SunCamera() {\n\n}\n\nSunCamera::SunCamera(GLfloat _FOV) {\n SunCamera();\n FOV = _FOV;\n}\n\nSunCamera::SunCamera(GLfloat _FOV, glm::vec3 _position) {\n SunCamera();\n FOV = _FOV;\n position = _position;\n}\n\nSunCamera::SunCamera(GLfloat _FOV, glm::vec3 _position, glm::vec3 _direction) {\n SunCamera();\n FOV = _FOV;\n position = _position;\n direction = _direction;\n}\n\nvoid SunCamera::init() {\n \/\/loadFile(\"..\/..\/Engine\/Scripts\/SunCamera.lua\");\n\tsetIgnoreTags(true);\n\taddAction(\"update\", &SunCamera::update);\n\taddAction(\"uniform\", &SunCamera::uniform);\n}\n\nvoid SunCamera::uniform(SunAction action) {\n\tpassPerFrameUniforms(action.getParameterPointer<SunShader>(\"shader\"));\n}\n\nvoid SunCamera::update(SunAction action) {\n\tdouble delta = ((SunWindowManager *)getService(\"window_manager\"))->getDelta();\n\n\tglm::vec2 mouse = ((SunCursorManager *)getService(\"cursor_manager\"))->getCursorPosition();\n static glm::vec2 oldMouse;\n glm::vec2 offset = glm::vec2(mouse.x - oldMouse.x, oldMouse.y - mouse.y);\n oldMouse = mouse;\n\n const float sensitivity = 0.1f;\n offset *= sensitivity;\n yaw += offset.x;\n pitch += offset.y;\n\n if (pitch > 89.0f)\n pitch = 89.0f;\n if (pitch < -89.0f)\n pitch = -89.0f;\n\n float speed = 5.0f;\n float finalSpeed = speed * delta;\n\tSunKeyboardManager *keyboard = (SunKeyboardManager *)getService(\"keyboard_manager\");\n if (keyboard->pollKey(GLFW_KEY_UP) == SunButtonStateDown)\n position += finalSpeed * direction;\n if (keyboard->pollKey(GLFW_KEY_DOWN) == SunButtonStateDown)\n position += finalSpeed * -direction;\n if (keyboard->pollKey(GLFW_KEY_RIGHT) == SunButtonStateDown)\n position += finalSpeed * glm::normalize(glm::cross(direction, cameraUp));\n if (keyboard->pollKey(GLFW_KEY_LEFT) == SunButtonStateDown)\n position += finalSpeed * -glm::normalize(glm::cross(direction, cameraUp));\n if (keyboard->pollKey(GLFW_KEY_SPACE) == SunButtonStateDown)\n position += finalSpeed * glm::vec3(0.0f, 1.0f, 0.0f);\n if (keyboard->pollKey(GLFW_KEY_LEFT_SHIFT) == SunButtonStateDown)\n position += finalSpeed * -glm::vec3(0.0f, 1.0f, 0.0f);\n\n direction.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw));\n direction.y = sin(glm::radians(pitch));\n direction.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));\n}\n\nglm::mat4 SunCamera::viewMatrix() {\n \/\/ Recalculate the camera's right and the camera's up\n cameraRight = glm::normalize(glm::cross(up, direction));\n cameraUp = glm::normalize(glm::cross(direction, cameraRight));\n\n \/\/ Create the view matrix for the camera's position and direction\n glm::mat4 matrix = glm::lookAt(position, position + direction, cameraUp);\n return matrix;\n}\n\nglm::mat4 SunCamera::projectionMatrix(GLfloat _aspectRatio) {\n \/\/ Create the projection matrix\n glm::mat4 matrix;\n\n \/\/ Check the type of projection\n matrix = glm::perspective(FOV, _aspectRatio, 0.01f, 100.0f);\n\n return matrix;\n}\n\nvoid SunCamera::passPerFrameUniforms(SunShader *_shader) {\n glUniform3f(_shader->getUniformLocation(\"viewPosition\"), position.x, position.y, position.z);\n\n \/\/ Pass the view and projection matrices to the shader\n GLint viewMatrixLocation = _shader->getUniformLocation(\"view\");\n glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(viewMatrix()));\n\n GLint projectionMatrixLocation = _shader->getUniformLocation(\"projection\");\n glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projectionMatrix(800.0f \/ 600.0f)));\n GLint FOVlocation = _shader->getUniformLocation(\"camera.FOV\");\n GLint nearPlaneLocation = _shader->getUniformLocation(\"camera.nearPlane\");\n GLint farPlaneLocation = _shader->getUniformLocation(\"camera.farPlane\");\n\n glUniform1f(FOVlocation, FOV);\n glUniform1f(nearPlaneLocation, 0.01f);\n glUniform1f(farPlaneLocation, 100.0f);\n}\n<commit_msg>Removed an include to selene<commit_after>\/\/ Copyright 2016 Jonathan Buchanan.\n\/\/ This file is part of Sunglasses, which is licensed under the MIT License.\n\/\/ See LICENSE.md for details.\n#include \"SunCamera.h\"\n#include <lua.hpp>\n\nSunCamera::SunCamera() {\n\n}\n\nSunCamera::SunCamera(GLfloat _FOV) {\n SunCamera();\n FOV = _FOV;\n}\n\nSunCamera::SunCamera(GLfloat _FOV, glm::vec3 _position) {\n SunCamera();\n FOV = _FOV;\n position = _position;\n}\n\nSunCamera::SunCamera(GLfloat _FOV, glm::vec3 _position, glm::vec3 _direction) {\n SunCamera();\n FOV = _FOV;\n position = _position;\n direction = _direction;\n}\n\nvoid SunCamera::init() {\n \/\/loadFile(\"..\/..\/Engine\/Scripts\/SunCamera.lua\");\n\tsetIgnoreTags(true);\n\taddAction(\"update\", &SunCamera::update);\n\taddAction(\"uniform\", &SunCamera::uniform);\n}\n\nvoid SunCamera::uniform(SunAction action) {\n\tpassPerFrameUniforms(action.getParameterPointer<SunShader>(\"shader\"));\n}\n\nvoid SunCamera::update(SunAction action) {\n\tdouble delta = ((SunWindowManager *)getService(\"window_manager\"))->getDelta();\n\n\tglm::vec2 mouse = ((SunCursorManager *)getService(\"cursor_manager\"))->getCursorPosition();\n static glm::vec2 oldMouse;\n glm::vec2 offset = glm::vec2(mouse.x - oldMouse.x, oldMouse.y - mouse.y);\n oldMouse = mouse;\n\n const float sensitivity = 0.1f;\n offset *= sensitivity;\n yaw += offset.x;\n pitch += offset.y;\n\n if (pitch > 89.0f)\n pitch = 89.0f;\n if (pitch < -89.0f)\n pitch = -89.0f;\n\n float speed = 5.0f;\n float finalSpeed = speed * delta;\n\tSunKeyboardManager *keyboard = (SunKeyboardManager *)getService(\"keyboard_manager\");\n if (keyboard->pollKey(GLFW_KEY_UP) == SunButtonStateDown)\n position += finalSpeed * direction;\n if (keyboard->pollKey(GLFW_KEY_DOWN) == SunButtonStateDown)\n position += finalSpeed * -direction;\n if (keyboard->pollKey(GLFW_KEY_RIGHT) == SunButtonStateDown)\n position += finalSpeed * glm::normalize(glm::cross(direction, cameraUp));\n if (keyboard->pollKey(GLFW_KEY_LEFT) == SunButtonStateDown)\n position += finalSpeed * -glm::normalize(glm::cross(direction, cameraUp));\n if (keyboard->pollKey(GLFW_KEY_SPACE) == SunButtonStateDown)\n position += finalSpeed * glm::vec3(0.0f, 1.0f, 0.0f);\n if (keyboard->pollKey(GLFW_KEY_LEFT_SHIFT) == SunButtonStateDown)\n position += finalSpeed * -glm::vec3(0.0f, 1.0f, 0.0f);\n\n direction.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw));\n direction.y = sin(glm::radians(pitch));\n direction.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));\n}\n\nglm::mat4 SunCamera::viewMatrix() {\n \/\/ Recalculate the camera's right and the camera's up\n cameraRight = glm::normalize(glm::cross(up, direction));\n cameraUp = glm::normalize(glm::cross(direction, cameraRight));\n\n \/\/ Create the view matrix for the camera's position and direction\n glm::mat4 matrix = glm::lookAt(position, position + direction, cameraUp);\n return matrix;\n}\n\nglm::mat4 SunCamera::projectionMatrix(GLfloat _aspectRatio) {\n \/\/ Create the projection matrix\n glm::mat4 matrix;\n\n \/\/ Check the type of projection\n matrix = glm::perspective(FOV, _aspectRatio, 0.01f, 100.0f);\n\n return matrix;\n}\n\nvoid SunCamera::passPerFrameUniforms(SunShader *_shader) {\n glUniform3f(_shader->getUniformLocation(\"viewPosition\"), position.x, position.y, position.z);\n\n \/\/ Pass the view and projection matrices to the shader\n GLint viewMatrixLocation = _shader->getUniformLocation(\"view\");\n glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(viewMatrix()));\n\n GLint projectionMatrixLocation = _shader->getUniformLocation(\"projection\");\n glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projectionMatrix(800.0f \/ 600.0f)));\n GLint FOVlocation = _shader->getUniformLocation(\"camera.FOV\");\n GLint nearPlaneLocation = _shader->getUniformLocation(\"camera.nearPlane\");\n GLint farPlaneLocation = _shader->getUniformLocation(\"camera.farPlane\");\n\n glUniform1f(FOVlocation, FOV);\n glUniform1f(nearPlaneLocation, 0.01f);\n glUniform1f(farPlaneLocation, 100.0f);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2012 GarageGames, LLC\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\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell 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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include <stdarg.h>\n\n#include \"core\/strings\/stringFunctions.h\"\n#include \"console\/console.h\"\n\n\n\/\/-------------------------------------- STATIC Declaration\nPlatformAssert *PlatformAssert::platformAssert = NULL;\n\n\/\/--------------------------------------\nPlatformAssert::PlatformAssert()\n{\n processing = false;\n ignoreAll = false;\n}\n\n\/\/--------------------------------------\nPlatformAssert::~PlatformAssert()\n{\n}\n\n\/\/--------------------------------------\nvoid PlatformAssert::create( PlatformAssert* newAssertClass )\n{\n if (!platformAssert)\n platformAssert = newAssertClass ? newAssertClass : new PlatformAssert;\n}\n\n\n\/\/--------------------------------------\nvoid PlatformAssert::destroy()\n{\n if (platformAssert)\n delete platformAssert;\n platformAssert = NULL;\n}\n\n\n\/\/--------------------------------------\nbool PlatformAssert::displayMessageBox(const char *title, const char *message, bool retry)\n{\n if (retry)\n return Platform::AlertRetry(title, message);\n\n Platform::AlertOK(title, message);\n return false;\n}\n\nstatic const char *typeName[] = { \"Unknown\", \"Fatal-ISV\", \"Fatal\", \"Warning\" };\n\/\/------------------------------------------------------------------------------\nstatic bool askToEnterDebugger(const char* message )\n{\n static bool haveAsked = false;\n static bool useDebugger = true;\n if(!haveAsked )\n {\n static char tempBuff[1024];\n dSprintf( tempBuff, 1024, \"Torque has encountered an assertion with message\\n\\n\"\n \"%s\\n\\n\"\n \"Would you like to use the debugger? If you cancel, you won't be asked\"\n \" again until you restart Torque.\", message);\n\n useDebugger = Platform::AlertOKCancel(\"Use debugger?\", tempBuff );\n haveAsked = true;\n }\n return useDebugger;\n}\n\n\/\/--------------------------------------\n\nbool PlatformAssert::process(Type assertType,\n const char *filename,\n U32 lineNumber,\n const char *message)\n{\n \/\/ If we're somehow recursing, just die.\n if(processing)\n Platform::debugBreak();\n \n processing = true;\n bool ret = false;\n \n \/\/ always dump to the Assert to the Console\n if (Con::isActive())\n {\n if (assertType == Warning)\n Con::warnf(ConsoleLogEntry::Assert, \"%s(%ld,0): {%s} - %s\", filename, lineNumber, typeName[assertType], message);\n else\n Con::errorf(ConsoleLogEntry::Assert, \"%s(%ld,0): {%s} - %s\", filename, lineNumber, typeName[assertType], message);\n }\n \n \/\/ if not a WARNING pop-up a dialog box\n if (assertType != Warning)\n {\n \/\/ used for processing navGraphs (an assert won't botch the whole build)\n if(Con::getBoolVariable(\"$FP::DisableAsserts\", false) == true)\n Platform::forceShutdown(1);\n \n char buffer[2048];\n dSprintf(buffer, 2048, \"%s: (%s @ %ld)\", typeName[assertType], filename, lineNumber);\n if( !ignoreAll )\n {\n \/\/ Display message box with Debug, Ignore, Ignore All, and Exit options\n switch( Platform::AlertAssert(buffer, message) )\n {\n case Platform::ALERT_ASSERT_DEBUG:\t\t\t\t\n ret = true;\n break;\n case Platform::ALERT_ASSERT_IGNORE:\n ret = false;\n break;\n case Platform::ALERT_ASSERT_IGNORE_ALL:\n ignoreAll = true;\n ret = false;\n break;\n default:\n case Platform::ALERT_ASSERT_EXIT:\n Platform::forceShutdown(1);\n break;\n }\n }\n }\n \n processing = false;\n \n return ret;\n}\n\nbool PlatformAssert::processingAssert()\n{\n return platformAssert ? platformAssert->processing : false;\n}\n\n\/\/--------------------------------------\nbool PlatformAssert::processAssert(Type assertType,\n const char *filename,\n U32 lineNumber,\n const char *message)\n{\n if (platformAssert)\n return platformAssert->process(assertType, filename, lineNumber, message);\n else \/\/ when platAssert NULL (during _start\/_exit) try direct output...\n dPrintf(\"\\n%s: (%s @ %ld) %s\\n\", typeName[assertType], filename, lineNumber, message);\n\n \/\/ this could also be platform-specific: OutputDebugString on PC, DebugStr on Mac.\n \/\/ Will raw printfs do the job? In the worst case, it's a break-pointable line of code.\n \/\/ would have preferred Con but due to race conditions, it might not be around...\n \/\/ Con::errorf(ConsoleLogEntry::Assert, \"%s: (%s @ %ld) %s\", typeName[assertType], filename, lineNumber, message);\n\n return true;\n}\n\n\/\/--------------------------------------\nconst char* avar(const char *message, ...)\n{\n static char buffer[4096];\n va_list args;\n va_start(args, message);\n dVsprintf(buffer, sizeof(buffer), message, args);\n return( buffer );\n}\n\n\/\/-----------------------------------------------------------------------------\n\nConsoleFunction( Assert, void, 3, 3, \"(condition, message) - Fatal Script Assertion\" )\n{\n \/\/ Process Assertion.\n AssertISV( dAtob(argv[1]), argv[2] );\n}\n<commit_msg>Remove dead function<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2012 GarageGames, LLC\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\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell 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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include <stdarg.h>\n\n#include \"core\/strings\/stringFunctions.h\"\n#include \"console\/console.h\"\n\n\n\/\/-------------------------------------- STATIC Declaration\nPlatformAssert *PlatformAssert::platformAssert = NULL;\n\n\/\/--------------------------------------\nPlatformAssert::PlatformAssert()\n{\n processing = false;\n ignoreAll = false;\n}\n\n\/\/--------------------------------------\nPlatformAssert::~PlatformAssert()\n{\n}\n\n\/\/--------------------------------------\nvoid PlatformAssert::create( PlatformAssert* newAssertClass )\n{\n if (!platformAssert)\n platformAssert = newAssertClass ? newAssertClass : new PlatformAssert;\n}\n\n\n\/\/--------------------------------------\nvoid PlatformAssert::destroy()\n{\n if (platformAssert)\n delete platformAssert;\n platformAssert = NULL;\n}\n\n\n\/\/--------------------------------------\nbool PlatformAssert::displayMessageBox(const char *title, const char *message, bool retry)\n{\n if (retry)\n return Platform::AlertRetry(title, message);\n\n Platform::AlertOK(title, message);\n return false;\n}\n\nstatic const char *typeName[] = { \"Unknown\", \"Fatal-ISV\", \"Fatal\", \"Warning\" };\n\n\/\/--------------------------------------\n\nbool PlatformAssert::process(Type assertType,\n const char *filename,\n U32 lineNumber,\n const char *message)\n{\n \/\/ If we're somehow recursing, just die.\n if(processing)\n Platform::debugBreak();\n \n processing = true;\n bool ret = false;\n \n \/\/ always dump to the Assert to the Console\n if (Con::isActive())\n {\n if (assertType == Warning)\n Con::warnf(ConsoleLogEntry::Assert, \"%s(%ld,0): {%s} - %s\", filename, lineNumber, typeName[assertType], message);\n else\n Con::errorf(ConsoleLogEntry::Assert, \"%s(%ld,0): {%s} - %s\", filename, lineNumber, typeName[assertType], message);\n }\n \n \/\/ if not a WARNING pop-up a dialog box\n if (assertType != Warning)\n {\n \/\/ used for processing navGraphs (an assert won't botch the whole build)\n if(Con::getBoolVariable(\"$FP::DisableAsserts\", false) == true)\n Platform::forceShutdown(1);\n \n char buffer[2048];\n dSprintf(buffer, 2048, \"%s: (%s @ %ld)\", typeName[assertType], filename, lineNumber);\n if( !ignoreAll )\n {\n \/\/ Display message box with Debug, Ignore, Ignore All, and Exit options\n switch( Platform::AlertAssert(buffer, message) )\n {\n case Platform::ALERT_ASSERT_DEBUG:\t\t\t\t\n ret = true;\n break;\n case Platform::ALERT_ASSERT_IGNORE:\n ret = false;\n break;\n case Platform::ALERT_ASSERT_IGNORE_ALL:\n ignoreAll = true;\n ret = false;\n break;\n default:\n case Platform::ALERT_ASSERT_EXIT:\n Platform::forceShutdown(1);\n break;\n }\n }\n }\n \n processing = false;\n \n return ret;\n}\n\nbool PlatformAssert::processingAssert()\n{\n return platformAssert ? platformAssert->processing : false;\n}\n\n\/\/--------------------------------------\nbool PlatformAssert::processAssert(Type assertType,\n const char *filename,\n U32 lineNumber,\n const char *message)\n{\n if (platformAssert)\n return platformAssert->process(assertType, filename, lineNumber, message);\n else \/\/ when platAssert NULL (during _start\/_exit) try direct output...\n dPrintf(\"\\n%s: (%s @ %ld) %s\\n\", typeName[assertType], filename, lineNumber, message);\n\n \/\/ this could also be platform-specific: OutputDebugString on PC, DebugStr on Mac.\n \/\/ Will raw printfs do the job? In the worst case, it's a break-pointable line of code.\n \/\/ would have preferred Con but due to race conditions, it might not be around...\n \/\/ Con::errorf(ConsoleLogEntry::Assert, \"%s: (%s @ %ld) %s\", typeName[assertType], filename, lineNumber, message);\n\n return true;\n}\n\n\/\/--------------------------------------\nconst char* avar(const char *message, ...)\n{\n static char buffer[4096];\n va_list args;\n va_start(args, message);\n dVsprintf(buffer, sizeof(buffer), message, args);\n return( buffer );\n}\n\n\/\/-----------------------------------------------------------------------------\n\nConsoleFunction( Assert, void, 3, 3, \"(condition, message) - Fatal Script Assertion\" )\n{\n \/\/ Process Assertion.\n AssertISV( dAtob(argv[1]), argv[2] );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2010 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: Korey Sewell\n *\n *\/\n\n#ifndef __CPU_INORDER_RESOURCE_SKED_HH__\n#define __CPU_INORDER_RESOURCE_SKED_HH__\n\n#include <vector>\n#include <list>\n\nclass ScheduleEntry {\n public:\n ScheduleEntry(int stage_num, int _priority, int res_num, int _cmd = 0,\n int _idx = 0) :\n stageNum(stage_num), resNum(res_num), cmd(_cmd),\n idx(_idx), priority(_priority)\n { }\n\n \/\/ Stage number to perform this service.\n int stageNum;\n\n \/\/ Resource ID to access\n int resNum;\n\n \/\/ See specific resource for meaning\n unsigned cmd;\n\n \/\/ See specific resource for meaning\n unsigned idx;\n\n \/\/ Some Resources May Need Priority\n int priority;\n};\n\nclass ResourceSked {\n public:\n typedef std::list<ScheduleEntry*>::iterator SkedIt;\n\n ResourceSked();\n\n void init();\n\n int size();\n bool empty();\n ScheduleEntry* top();\n void pop();\n void push(ScheduleEntry* sked_entry);\n void pushBefore(ScheduleEntry* sked_entry, int sked_cmd, int sked_cmd_idx);\n void print();\n\n private:\n SkedIt curSkedEntry;\n std::vector<std::list<ScheduleEntry*> > sked;\n\n SkedIt findIterByPriority(ScheduleEntry *sked_entry, int stage_num);\n SkedIt findIterByCommand(ScheduleEntry *sked_entry, int stage_num,\n int sked_cmd, int sked_cmd_idx = -1);\n};\n\n#endif \/\/__CPU_INORDER_RESOURCE_SKED_HH__\n<commit_msg>inorder: comments for resource sked class<commit_after>\/*\n * Copyright (c) 2010 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: Korey Sewell\n *\n *\/\n\n#ifndef __CPU_INORDER_RESOURCE_SKED_HH__\n#define __CPU_INORDER_RESOURCE_SKED_HH__\n\n#include <vector>\n#include <list>\n\n\/** ScheduleEntry class represents a single function that an instruction\n wants to do at any pipeline stage. For example, if an instruction\n needs to be decoded and do a branch prediction all in one stage\n then each of those tasks would need it's own ScheduleEntry.\n\n Each schedule entry corresponds to some resource that the instruction\n wants to interact with.\n\n The file pipeline_traits.cc shows how a typical instruction schedule is\n made up of these schedule entries.\n*\/\nclass ScheduleEntry {\n public:\n ScheduleEntry(int stage_num, int _priority, int res_num, int _cmd = 0,\n int _idx = 0) :\n stageNum(stage_num), resNum(res_num), cmd(_cmd),\n idx(_idx), priority(_priority)\n { }\n\n \/** Stage number to perform this service. *\/\n int stageNum;\n\n \/** Resource ID to access *\/\n int resNum;\n\n \/** See specific resource for meaning *\/\n unsigned cmd;\n\n \/** See specific resource for meaning *\/\n unsigned idx;\n\n \/** Some Resources May Need Priority *\/\n int priority;\n};\n\n\/** The ResourceSked maintains the complete schedule\n for an instruction. That schedule includes what\n resources an instruction wants to acquire at each\n pipeline stage and is represented by a collection\n of ScheduleEntry objects (described above) that\n must be executed in-order.\n\n In every pipeline stage, the InOrder model will\n process all entries on the resource schedule for\n that stage and then send the instruction to the next\n stage if and only if the instruction successfully\n completed each ScheduleEntry.\n*\/\nclass ResourceSked {\n public:\n typedef std::list<ScheduleEntry*>::iterator SkedIt;\n\n ResourceSked();\n\n \/** Initializee the current entry pointer to\n pipeline stage 0 and the 1st schedule entry\n *\/\n void init();\n\n \/** Goes through the remaining stages on the schedule\n and sums all the remaining entries left to be\n processed\n *\/\n int size();\n\n \/** Is the schedule empty? *\/\n bool empty();\n\n \/** What is the next task for this instruction schedule? *\/\n ScheduleEntry* top();\n\n \/** Top() Task is completed, remove it from schedule *\/\n void pop();\n\n \/** Add To Schedule based on stage num and priority of\n Schedule Entry\n *\/\n void push(ScheduleEntry* sked_entry);\n\n \/** Add Schedule Entry to be in front of another Entry *\/\n void pushBefore(ScheduleEntry* sked_entry, int sked_cmd, int sked_cmd_idx);\n\n \/** Print what's left on the instruction schedule *\/\n void print();\n\n private:\n \/** Current Schedule Entry Pointer *\/\n SkedIt curSkedEntry;\n\n \/** The Resource Schedule: Resized to Number of Stages in\n the constructor\n *\/\n std::vector<std::list<ScheduleEntry*> > sked;\n\n \/** Find a place to insert the instruction using the\n schedule entries priority\n *\/\n SkedIt findIterByPriority(ScheduleEntry *sked_entry, int stage_num);\n\n \/** Find a place to insert the instruction using a particular command\n to look for.\n *\/\n SkedIt findIterByCommand(ScheduleEntry *sked_entry, int stage_num,\n int sked_cmd, int sked_cmd_idx = -1);\n};\n\n#endif \/\/__CPU_INORDER_RESOURCE_SKED_HH__\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.7.32); FILE MERGED 2006\/01\/30 16:25:41 sb 1.7.32.3: #i53898# Made code warning-free. 2006\/01\/25 17:32:21 sb 1.7.32.2: RESYNC: (1.7-1.8); FILE MERGED 2005\/11\/16 13:10:34 pl 1.7.32.1: #i55991# removed warnings<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016, Nils Asmussen\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are\n * those of the authors and should not be interpreted as representing official\n * policies, either expressed or implied, of the FreeBSD Project.\n *\/\n\n#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__\n#define __CPU_DTU_ACCEL_SYSCALLSM_HH__\n\n#include \"cpu\/dtu-accel\/accelerator.hh\"\n#include \"sim\/system.hh\"\n\nclass SyscallSM\n{\n public:\n enum Operation\n {\n \/\/ sent by the DTU if the PF handler is not reachable\n PAGEFAULT = 0,\n\n \/\/ capability creations\n CREATE_SRV,\n CREATE_SESS,\n CREATE_RGATE,\n CREATE_SGATE,\n CREATE_MGATE,\n CREATE_MAP,\n CREATE_VPE,\n\n \/\/ capability operations\n ACTIVATE,\n VPE_CTRL,\n VPE_WAIT,\n DERIVE_MEM,\n OPEN_SESS,\n\n \/\/ capability exchange\n DELEGATE,\n OBTAIN,\n EXCHANGE,\n REVOKE,\n\n \/\/ forwarding\n FORWARD_MSG,\n FORWARD_MEM,\n FORWARD_REPLY,\n\n \/\/ misc\n NOOP,\n };\n\n enum VPEOp\n {\n VCTRL_INIT,\n VCTRL_START,\n VCTRL_YIELD,\n VCTRL_STOP,\n };\n\n enum State\n {\n SYSC_SEND,\n SYSC_WAIT,\n SYSC_FETCH,\n SYSC_READ_ADDR,\n SYSC_ACK,\n };\n\n explicit SyscallSM(DtuAccel *_accel)\n : accel(_accel), state(), stateChanged(), waitForReply(), fetched(),\n replyAddr(), syscallSize() {}\n\n std::string stateName() const;\n\n bool isWaiting() const { return state == SYSC_FETCH; }\n\n bool hasStateChanged() const { return stateChanged; }\n\n void retryFetch() { fetched = false; }\n\n void start(Addr size, bool wait = true, bool resume = false)\n {\n syscallSize = size;\n state = resume ? SYSC_FETCH : SYSC_SEND;\n fetched = false;\n waitForReply = wait;\n }\n\n PacketPtr tick();\n\n bool handleMemResp(PacketPtr pkt);\n\n private:\n\n DtuAccel *accel;\n State state;\n bool stateChanged;\n bool waitForReply;\n bool fetched;\n Addr replyAddr;\n Addr syscallSize;\n};\n\n#endif \/* __CPU_DTU_ACCEL_SYSCALLSM_HH__ *\/\n<commit_msg>DtuAccel: updated syscall table.<commit_after>\/*\n * Copyright (c) 2016, Nils Asmussen\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are\n * those of the authors and should not be interpreted as representing official\n * policies, either expressed or implied, of the FreeBSD Project.\n *\/\n\n#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__\n#define __CPU_DTU_ACCEL_SYSCALLSM_HH__\n\n#include \"cpu\/dtu-accel\/accelerator.hh\"\n#include \"sim\/system.hh\"\n\nclass SyscallSM\n{\n public:\n enum Operation\n {\n \/\/ sent by the DTU if the PF handler is not reachable\n PAGEFAULT = 0,\n\n \/\/ capability creations\n CREATE_SRV,\n CREATE_SESS,\n CREATE_RGATE,\n CREATE_SGATE,\n CREATE_MGATE,\n CREATE_MAP,\n CREATE_VPEGRP,\n CREATE_VPE,\n\n \/\/ capability operations\n ACTIVATE,\n VPE_CTRL,\n VPE_WAIT,\n DERIVE_MEM,\n OPEN_SESS,\n\n \/\/ capability exchange\n DELEGATE,\n OBTAIN,\n EXCHANGE,\n REVOKE,\n\n \/\/ forwarding\n FORWARD_MSG,\n FORWARD_MEM,\n FORWARD_REPLY,\n\n \/\/ misc\n NOOP,\n };\n\n enum VPEOp\n {\n VCTRL_INIT,\n VCTRL_START,\n VCTRL_YIELD,\n VCTRL_STOP,\n };\n\n enum State\n {\n SYSC_SEND,\n SYSC_WAIT,\n SYSC_FETCH,\n SYSC_READ_ADDR,\n SYSC_ACK,\n };\n\n explicit SyscallSM(DtuAccel *_accel)\n : accel(_accel), state(), stateChanged(), waitForReply(), fetched(),\n replyAddr(), syscallSize() {}\n\n std::string stateName() const;\n\n bool isWaiting() const { return state == SYSC_FETCH; }\n\n bool hasStateChanged() const { return stateChanged; }\n\n void retryFetch() { fetched = false; }\n\n void start(Addr size, bool wait = true, bool resume = false)\n {\n syscallSize = size;\n state = resume ? SYSC_FETCH : SYSC_SEND;\n fetched = false;\n waitForReply = wait;\n }\n\n PacketPtr tick();\n\n bool handleMemResp(PacketPtr pkt);\n\n private:\n\n DtuAccel *accel;\n State state;\n bool stateChanged;\n bool waitForReply;\n bool fetched;\n Addr replyAddr;\n Addr syscallSize;\n};\n\n#endif \/* __CPU_DTU_ACCEL_SYSCALLSM_HH__ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ofxLaserDacBase.cpp\n\/\/\n\/\/ Created by Seb Lee-Delisle on 07\/11\/2017.\n\/\/\n\/\/\n\n#include \"ofxLaserDacHelios.h\"\n\nusing namespace ofxLaser;\n\nDacHelios:: DacHelios() : heliosManager(DacHeliosManager::getInstance()) {\n\tpps = 30000;\n\tnewPPS = 30000;\n\t\n\tframeMode = true;\n\t\n\tconnected = false;\n newArmed = false; \/\/ as in the PPS system, this knows\n \/\/ if armed status has changed and sends\n \/\/ signal to DAC\n\tdeviceId = \"\";\n\tdacDevice = nullptr;\n\t\n}\nDacHelios:: ~DacHelios() {\n\tofLogNotice(\"DacHelios destructor\");\n\t\/\/stopThread();\n\tclose();\n\t\n\t\n}\n\nvoid DacHelios::close() {\n\t\n\tif(isThreadRunning()) {\n\t\twaitForThread(true); \/\/ also stops the thread\n\t\tif(lock()) {\n\t\t\tif(dacDevice!=nullptr) {\n\t\t\t\tdacDevice->SetClosed();\n\t\t\t\tdacDevice = nullptr;\n\t\t\t}\n\t\t\tunlock();\n\t\t}\n\t\tdelete dacDevice;\n\t}\n}\n\n\nvoid DacHelios::setup(string name) {\n\t\n\tdeviceName = name; \/\/ the parameter which shows the name\n\t\n\tofLogNotice(\"DacHelios::setup \"+name);\n\t\n\tconnectToDevice(deviceName);\n\n\tpointBufferDisplay.set(\"Point Buffer\", 0,0,1799);\n\tdisplayData.push_back(&deviceName);\n\tdisplayData.push_back(&pointBufferDisplay);\n\t\n\tstartThread();\n\n}\n\nconst vector<ofAbstractParameter*>& DacHelios :: getDisplayData() {\n\tif(lock()) {\n\t\n\t\t\/\/pointBufferDisplay += (response.status.buffer_fullness-pointBufferDisplay)*1;\n\t\t\n\t\t\/\/int pointssincelastmessage = (float)((ofGetElapsedTimeMicros()-lastMessageTimeMicros)*response.status.point_rate)\/1000000.0f;\n\t\t\n\t\t\/\/pointBufferDisplay = bufferedPoints.size();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\/\/latencyDisplay += (latencyMicros - latencyDisplay)*0.1;\n\t\t\/\/reconnectCount = prepareSendCount;\n\t\n\t\tunlock();\n\t}\n\t\n\treturn displayData;\n}\n\nbool DacHelios::connectToDevice(string name) {\n\t\n\tdacDevice = heliosManager.getDacDeviceForName(name);\n\tif(dacDevice!=nullptr) {\n\t\tdeviceId = deviceName = dacDevice->nameStr;\n\t\tif(dacDevice->isClosed()) { \/\/ not sure why it should be but hey\n\t\t\tofLogError(\"HeliosDac device is closed before it's used!\"+ name);\n\t\t\theliosManager.deleteDevice(dacDevice);\n\t\t\tconnected = false;\n\t\t\t\n\t\t\tdacDevice = nullptr;\n\t\t} else {\n\t\t\tconnected = true;\n\t\t}\n\t} else {\n\t\tconnected = false;\n\t}\n\n\treturn connected;\n\t\n}\n\nbool DacHelios:: sendFrame(const vector<Point>& points){\n\tif(!connected) return false;\n\t\/\/ get frame object\n\n\tDacHeliosFrame* frame = getFrame();\n\t\n\t\/\/ add all points into the frame object\n\tframeMode = true;\n\tfor(ofxLaser::Point p : points) {\n\t\tframe->addPoint(p);\n\t}\n\t\/\/ add the frame object to the frame channel\n\tframesChannel.send(frame);\n\t\n\treturn true;\n\t\n}\n\n\nbool DacHelios::sendPoints(const vector<Point>& points) {\n\t\n\tif(!connected) return false;\n\t\/\/ get frame object\n\n\tDacHeliosFrame* frame = getFrame();\n\t\n\t\/\/ add all points into the frame object\n\tframeMode = false;\n\tframe->addPoint(lastPoint);\n\tfor(ofxLaser::Point p : points) {\n\t\tframe->addPoint(p);\n\t\tlastPoint = p; \n\t}\n\t\/\/ add the frame object to the frame channel\n\tframesChannel.send(frame);\n\t\n\treturn true;\n};\n\nbool DacHelios::setPointsPerSecond(uint32_t newpps) {\n\tofLog(OF_LOG_NOTICE, \"setPointsPerSecond \" + ofToString(newpps));\n\twhile(!lock());\n\tnewPPS = newpps;\n\tunlock();\n\treturn true;\n\t\n\t\n};\n\nvoid DacHelios :: setActive(bool active){\n newArmed = active;\n \n}\nvoid DacHelios :: reset() {\n if(lock()) {\n resetFlag = true;\n unlock();\n }\n}\n\n\nvoid DacHelios :: threadedFunction(){\n\t\n\tDacHeliosFrame* currentFrame = nullptr;\n\tDacHeliosFrame* nextFrame = nullptr;\n\tDacHeliosFrame* newFrame = nullptr;\n\t\n\twhile(isThreadRunning()) {\n\t\n\t\tif(connected && (newPPS!=pps)) {\n\t\t\tpps = newPPS;\n\t\t\t\n\t\t}\n if(connected && (newArmed!=armed)) {\n if((dacDevice!=nullptr) && (dacDevice->SetShutter(newArmed)==HELIOS_SUCCESS)) {\n armed = newArmed;\n }\n }\n \n \n\t\tif(connected && isThreadRunning()) {\n \n\t\t\t\/\/ is there a new frame?\n\t\t\t\/\/ if so, store it\n\t\t\tbool dacReady = false;\n\t\t\tint status = 0;\n\t\t\t\t\n\t\t\twhile((!dacReady) && isThreadRunning()) {\n\t\t\t\t\/\/ if we're in frame mode or we don't have a next frame let's pull another frame off the buffer\n\t\t\t\t\/\/ (means that we only skip frames in frame mode)\n\t\t\t\tif( (frameMode || nextFrame==nullptr) &&\n\t\t\t\t\t (framesChannel.tryReceive(newFrame)) ) {\n\t\t\t\t\tif(nextFrame!=nullptr) {\n\t\t\t\t\t\tnextFrame = releaseFrame(nextFrame);\n\t\t\t\t\t}\n\t\t\t\t\tnextFrame = newFrame;\n\t\t\t\t}\n\t\t\t\tyield(); \n\t\t\t\tfloat time = ofGetElapsedTimef(); \n\t\t\t\tif(dacDevice!=nullptr) status = dacDevice->GetStatus();\n\t\t\t\t\n\t\t\t\tyield(); \n\t\t\t\tdacReady = (status == 1);\n\t\t\t\t\n\t\t\t\tif(!dacReady) {\n\n\t\t\t\t\tif(status<0) {\n\t\t\t\t\t\tofLog(OF_LOG_NOTICE, \"heliosDac.getStatus error: \"+ ofToString(status) +\" \" + ofToString(ofGetElapsedTimef()-time));\n\t\t\t\t\t}\n\t\t\t\t\tusleep(100);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tyield(); \n\t\t\t}\n\t\t\t\/\/ if we got to here then the dac is ready but we might not have a\n\t\t\t\/\/ currentFrame yet...\n\t\t\tif(nextFrame!=nullptr) {\n\t\t\t\tif(currentFrame!=nullptr) {\n\t\t\t\t\treleaseFrame(currentFrame);\n\t\t\t\t}\n\t\t\t\tcurrentFrame = nextFrame;\n\t\t\t\tnextFrame = nullptr;\n\t\t\t}\n\t\t\tif(currentFrame!=nullptr) {\n\t\t\t\tint result = 0;\n\t\t\t\tint attempts = 0; \n\t\t\t\tif(dacDevice!=nullptr) {\n\t\t\t\t\twhile((attempts<512) && (result!=HELIOS_SUCCESS)) {\n\t\t\t\t\t\tresult = dacDevice->SendFrame(pps, HELIOS_FLAGS_SINGLE_MODE, currentFrame->samples, currentFrame->numSamples);\n\t\t\t\t\t\tattempts++; \n\t\t\t\t\t\tyield(); \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ if we're not in frame mode then delete the points\n\t\t\t\tif((result == HELIOS_SUCCESS) && (!frameMode) ) {\n\t\t\t\t\tcurrentFrame=releaseFrame(currentFrame);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ofLog(OF_LOG_NOTICE, \"heliosDac.WriteFrame : \"+ ofToString(result));\n\t\t\t\tif(result <=-5000){ \/\/ then we have a USB connection error\n\t\t\t\t\tofLog(OF_LOG_NOTICE, \"heliosDac.WriteFrame failed. LIBUSB error : \"+ ofToString(result));\n\t\t\t\t\t\/\/if(result!=-5007) setConnected(false); \/\/ time out error\n\t\t\t\t} else if(result!=HELIOS_SUCCESS) {\n\t\t\t\t\tofLog(OF_LOG_NOTICE, \"heliosDac.WriteFrame failed. Error : \"+ ofToString(result));\n\t\t\t\t\t\/\/setConnected(false);\n\t\t\t\t} else {\n\t\t\t\t\t\/\/setConnected(true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ofLogError(\"DacHelios - run out of points!\");\n\t\t\t}\n\t\t} else {\n \n \n\t\t\t\/\/ TODO : handle reconnection better\n\t\t\t\/\/ try to reconnect!\n\t\t\t\n\t\t\tif(isThreadRunning()) {\n\t\t\t\tif(lock()) {\n\t\t\t\t\tif(connectToDevice(deviceName)) {\n\t\t\t\t\t\tsetConnected(true);\n\t\t\t\t\t\n\t\t\t\t\t\tunlock();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tunlock();\n\t\t\t\t\t\t\/\/ wait half a second and try again\n\t\t\t\t\t\tfor(size_t i = 0; (i<10)&&(isThreadRunning()); i++ ) {\n\t\t\t\t\t\t\tsleep(50);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tyield();\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n}\n\n\n\nvoid DacHelios :: setConnected(bool state) {\n\tif(connected!=state) {\n\t\t\n\t\twhile(!lock()){};\n\t\tconnected = state;\n\t\tif(!connected) {\n\t\t\t\/\/heliosManager.deviceDisconnected(deviceName);\n\t\t\tarmed = !newArmed;\n\t\t\theliosManager.deleteDevice(dacDevice);\n\t\t\tdacDevice = nullptr;\n\t\t}\n\t\tofLogNotice(\"Helios Dac changed connection state : \"+ofToString(connected));\n\t\tunlock();\n\t\t\n\t}\n}\n\n\nDacHeliosFrame* DacHelios :: getFrame() {\n\tDacHeliosFrame* returnframe;\n\t\n\tif(spareFrames.tryReceive(returnframe)) {\n\t\t\/\/ofLogNotice(\"DacHelios :: getFrame() - removed frame from channel\");\n\t\treturnframe->reset();\n\t\treturn returnframe;\n\t} else {\n\t\t\/\/ofLogNotice(\"DacHelios :: getFrame() - created new frame\");\n\t\treturnframe =new DacHeliosFrame();\n\t\treturn returnframe;\n\t}\n\t\t\n}\nDacHeliosFrame* DacHelios :: releaseFrame(DacHeliosFrame* frame){\n\t\/\/delete frame;\n\t\/\/\n\tspareFrames.send(frame);\n\t\/\/ofLogNotice(\"DacHelios :: releaseFrame() - added frame to channel \"+ofToString(frame->numSamples));\n\treturn nullptr;\n}\n\n<commit_msg>remove usleep (incompatible with windows)<commit_after>\/\/\n\/\/ ofxLaserDacBase.cpp\n\/\/\n\/\/ Created by Seb Lee-Delisle on 07\/11\/2017.\n\/\/\n\/\/\n\n#include \"ofxLaserDacHelios.h\"\n\nusing namespace ofxLaser;\n\nDacHelios:: DacHelios() : heliosManager(DacHeliosManager::getInstance()) {\n\tpps = 30000;\n\tnewPPS = 30000;\n\t\n\tframeMode = true;\n\t\n\tconnected = false;\n newArmed = false; \/\/ as in the PPS system, this knows\n \/\/ if armed status has changed and sends\n \/\/ signal to DAC\n\tdeviceId = \"\";\n\tdacDevice = nullptr;\n\t\n}\nDacHelios:: ~DacHelios() {\n\tofLogNotice(\"DacHelios destructor\");\n\t\/\/stopThread();\n\tclose();\n\t\n\t\n}\n\nvoid DacHelios::close() {\n\t\n\tif(isThreadRunning()) {\n\t\twaitForThread(true); \/\/ also stops the thread\n\t\tif(lock()) {\n\t\t\tif(dacDevice!=nullptr) {\n\t\t\t\tdacDevice->SetClosed();\n\t\t\t\tdacDevice = nullptr;\n\t\t\t}\n\t\t\tunlock();\n\t\t}\n\t\tdelete dacDevice;\n\t}\n}\n\n\nvoid DacHelios::setup(string name) {\n\t\n\tdeviceName = name; \/\/ the parameter which shows the name\n\t\n\tofLogNotice(\"DacHelios::setup \"+name);\n\t\n\tconnectToDevice(deviceName);\n\n\tpointBufferDisplay.set(\"Point Buffer\", 0,0,1799);\n\tdisplayData.push_back(&deviceName);\n\tdisplayData.push_back(&pointBufferDisplay);\n\t\n\tstartThread();\n\n}\n\nconst vector<ofAbstractParameter*>& DacHelios :: getDisplayData() {\n\tif(lock()) {\n\t\n\t\t\/\/pointBufferDisplay += (response.status.buffer_fullness-pointBufferDisplay)*1;\n\t\t\n\t\t\/\/int pointssincelastmessage = (float)((ofGetElapsedTimeMicros()-lastMessageTimeMicros)*response.status.point_rate)\/1000000.0f;\n\t\t\n\t\t\/\/pointBufferDisplay = bufferedPoints.size();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\/\/latencyDisplay += (latencyMicros - latencyDisplay)*0.1;\n\t\t\/\/reconnectCount = prepareSendCount;\n\t\n\t\tunlock();\n\t}\n\t\n\treturn displayData;\n}\n\nbool DacHelios::connectToDevice(string name) {\n\t\n\tdacDevice = heliosManager.getDacDeviceForName(name);\n\tif(dacDevice!=nullptr) {\n\t\tdeviceId = deviceName = dacDevice->nameStr;\n\t\tif(dacDevice->isClosed()) { \/\/ not sure why it should be but hey\n\t\t\tofLogError(\"HeliosDac device is closed before it's used!\"+ name);\n\t\t\theliosManager.deleteDevice(dacDevice);\n\t\t\tconnected = false;\n\t\t\t\n\t\t\tdacDevice = nullptr;\n\t\t} else {\n\t\t\tconnected = true;\n\t\t}\n\t} else {\n\t\tconnected = false;\n\t}\n\n\treturn connected;\n\t\n}\n\nbool DacHelios:: sendFrame(const vector<Point>& points){\n\tif(!connected) return false;\n\t\/\/ get frame object\n\n\tDacHeliosFrame* frame = getFrame();\n\t\n\t\/\/ add all points into the frame object\n\tframeMode = true;\n\tfor(ofxLaser::Point p : points) {\n\t\tframe->addPoint(p);\n\t}\n\t\/\/ add the frame object to the frame channel\n\tframesChannel.send(frame);\n\t\n\treturn true;\n\t\n}\n\n\nbool DacHelios::sendPoints(const vector<Point>& points) {\n\t\n\tif(!connected) return false;\n\t\/\/ get frame object\n\n\tDacHeliosFrame* frame = getFrame();\n\t\n\t\/\/ add all points into the frame object\n\tframeMode = false;\n\tframe->addPoint(lastPoint);\n\tfor(ofxLaser::Point p : points) {\n\t\tframe->addPoint(p);\n\t\tlastPoint = p; \n\t}\n\t\/\/ add the frame object to the frame channel\n\tframesChannel.send(frame);\n\t\n\treturn true;\n};\n\nbool DacHelios::setPointsPerSecond(uint32_t newpps) {\n\tofLog(OF_LOG_NOTICE, \"setPointsPerSecond \" + ofToString(newpps));\n\twhile(!lock());\n\tnewPPS = newpps;\n\tunlock();\n\treturn true;\n\t\n\t\n};\n\nvoid DacHelios :: setActive(bool active){\n newArmed = active;\n \n}\nvoid DacHelios :: reset() {\n if(lock()) {\n resetFlag = true;\n unlock();\n }\n}\n\n\nvoid DacHelios :: threadedFunction(){\n\t\n\tDacHeliosFrame* currentFrame = nullptr;\n\tDacHeliosFrame* nextFrame = nullptr;\n\tDacHeliosFrame* newFrame = nullptr;\n\t\n\twhile(isThreadRunning()) {\n\t\n\t\tif(connected && (newPPS!=pps)) {\n\t\t\tpps = newPPS;\n\t\t\t\n\t\t}\n if(connected && (newArmed!=armed)) {\n if((dacDevice!=nullptr) && (dacDevice->SetShutter(newArmed)==HELIOS_SUCCESS)) {\n armed = newArmed;\n }\n }\n \n \n\t\tif(connected && isThreadRunning()) {\n \n\t\t\t\/\/ is there a new frame?\n\t\t\t\/\/ if so, store it\n\t\t\tbool dacReady = false;\n\t\t\tint status = 0;\n\t\t\t\t\n\t\t\twhile((!dacReady) && isThreadRunning()) {\n\t\t\t\t\/\/ if we're in frame mode or we don't have a next frame let's pull another frame off the buffer\n\t\t\t\t\/\/ (means that we only skip frames in frame mode)\n\t\t\t\tif( (frameMode || nextFrame==nullptr) &&\n\t\t\t\t\t (framesChannel.tryReceive(newFrame)) ) {\n\t\t\t\t\tif(nextFrame!=nullptr) {\n\t\t\t\t\t\tnextFrame = releaseFrame(nextFrame);\n\t\t\t\t\t}\n\t\t\t\t\tnextFrame = newFrame;\n\t\t\t\t}\n\t\t\t\tyield(); \n\t\t\t\tfloat time = ofGetElapsedTimef(); \n\t\t\t\tif(dacDevice!=nullptr) status = dacDevice->GetStatus();\n\t\t\t\t\n\t\t\t\tyield(); \n\t\t\t\tdacReady = (status == 1);\n\t\t\t\t\n\t\t\t\tif(!dacReady) {\n\n\t\t\t\t\tif(status<0) {\n\t\t\t\t\t\tofLog(OF_LOG_NOTICE, \"heliosDac.getStatus error: \"+ ofToString(status) +\" \" + ofToString(ofGetElapsedTimef()-time));\n\t\t\t\t\t}\n\t\t\t\t\tyield();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tyield(); \n\t\t\t}\n\t\t\t\/\/ if we got to here then the dac is ready but we might not have a\n\t\t\t\/\/ currentFrame yet...\n\t\t\tif(nextFrame!=nullptr) {\n\t\t\t\tif(currentFrame!=nullptr) {\n\t\t\t\t\treleaseFrame(currentFrame);\n\t\t\t\t}\n\t\t\t\tcurrentFrame = nextFrame;\n\t\t\t\tnextFrame = nullptr;\n\t\t\t}\n\t\t\tif(currentFrame!=nullptr) {\n\t\t\t\tint result = 0;\n\t\t\t\tint attempts = 0; \n\t\t\t\tif(dacDevice!=nullptr) {\n\t\t\t\t\twhile((attempts<512) && (result!=HELIOS_SUCCESS)) {\n\t\t\t\t\t\tresult = dacDevice->SendFrame(pps, HELIOS_FLAGS_SINGLE_MODE, currentFrame->samples, currentFrame->numSamples);\n\t\t\t\t\t\tattempts++; \n\t\t\t\t\t\tyield(); \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ if we're not in frame mode then delete the points\n\t\t\t\tif((result == HELIOS_SUCCESS) && (!frameMode) ) {\n\t\t\t\t\tcurrentFrame=releaseFrame(currentFrame);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ofLog(OF_LOG_NOTICE, \"heliosDac.WriteFrame : \"+ ofToString(result));\n\t\t\t\tif(result <=-5000){ \/\/ then we have a USB connection error\n\t\t\t\t\tofLog(OF_LOG_NOTICE, \"heliosDac.WriteFrame failed. LIBUSB error : \"+ ofToString(result));\n\t\t\t\t\t\/\/if(result!=-5007) setConnected(false); \/\/ time out error\n\t\t\t\t} else if(result!=HELIOS_SUCCESS) {\n\t\t\t\t\tofLog(OF_LOG_NOTICE, \"heliosDac.WriteFrame failed. Error : \"+ ofToString(result));\n\t\t\t\t\t\/\/setConnected(false);\n\t\t\t\t} else {\n\t\t\t\t\t\/\/setConnected(true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ofLogError(\"DacHelios - run out of points!\");\n\t\t\t}\n\t\t} else {\n \n \n\t\t\t\/\/ TODO : handle reconnection better\n\t\t\t\/\/ try to reconnect!\n\t\t\t\n\t\t\tif(isThreadRunning()) {\n\t\t\t\tif(lock()) {\n\t\t\t\t\tif(connectToDevice(deviceName)) {\n\t\t\t\t\t\tsetConnected(true);\n\t\t\t\t\t\n\t\t\t\t\t\tunlock();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tunlock();\n\t\t\t\t\t\t\/\/ wait half a second and try again\n\t\t\t\t\t\tfor(size_t i = 0; (i<10)&&(isThreadRunning()); i++ ) {\n\t\t\t\t\t\t\tsleep(50);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tyield();\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n}\n\n\n\nvoid DacHelios :: setConnected(bool state) {\n\tif(connected!=state) {\n\t\t\n\t\twhile(!lock()){};\n\t\tconnected = state;\n\t\tif(!connected) {\n\t\t\t\/\/heliosManager.deviceDisconnected(deviceName);\n\t\t\tarmed = !newArmed;\n\t\t\theliosManager.deleteDevice(dacDevice);\n\t\t\tdacDevice = nullptr;\n\t\t}\n\t\tofLogNotice(\"Helios Dac changed connection state : \"+ofToString(connected));\n\t\tunlock();\n\t\t\n\t}\n}\n\n\nDacHeliosFrame* DacHelios :: getFrame() {\n\tDacHeliosFrame* returnframe;\n\t\n\tif(spareFrames.tryReceive(returnframe)) {\n\t\t\/\/ofLogNotice(\"DacHelios :: getFrame() - removed frame from channel\");\n\t\treturnframe->reset();\n\t\treturn returnframe;\n\t} else {\n\t\t\/\/ofLogNotice(\"DacHelios :: getFrame() - created new frame\");\n\t\treturnframe =new DacHeliosFrame();\n\t\treturn returnframe;\n\t}\n\t\t\n}\nDacHeliosFrame* DacHelios :: releaseFrame(DacHeliosFrame* frame){\n\t\/\/delete frame;\n\t\/\/\n\tspareFrames.send(frame);\n\t\/\/ofLogNotice(\"DacHelios :: releaseFrame() - added frame to channel \"+ofToString(frame->numSamples));\n\treturn nullptr;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Use the full path name to the shared library when registering it, not just \"libGPad\".<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Dawid Drozd aka Gelldur on 03.02.16.\n\/\/\n\n#include \"Provider.h\"\n\n#include <log.h>\n#include <Poco\/Delegate.h>\n#include <Poco\/Runnable.h>\n#include <Director.h>\n#include <exception\/Fail.h>\n#include <acme\/guard\/ChangeOnEnd.h>\n#include \"Application.h\"\n\n\/\/TODO make thread safe\nclass BackroundHelper : public Poco::Runnable\n{\npublic:\n\tstd::atomic<bool> isReady;\n\n\tBackroundHelper(std::shared_ptr<Provider>& provider)\n\t\t\t: isReady(false)\n\t\t\t, _provider(provider)\n\t{\n\t\tassert(_provider);\n\t\t_provider->setState(Provider::State::BEFORE_RUN);\n\t}\n\n\tvirtual void run() override\n\t{\n\t\tChangeOnEnd<std::atomic<bool>, bool> guard(isReady, true);\n\t\ttry\n\t\t{\n\t\t\trunTask();\n\t\t}\n\t\tcatch (std::exception& exception)\n\t\t{\n\t\t\tDLOG(\"Exception in background task!\\nWhat: %s\", exception.what());\n\t\t\tthrow;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tDLOG(\"Exception in background task!\");\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tvoid runTask()\n\t{\n\t\tif (_provider->isCanceled())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t_provider->setState(Provider::State::RUNNING);\n\t\ttry\n\t\t{\n\t\t\t_provider->onDoInBackground();\n\t\t\t_provider->setState(Provider::State::DONE);\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\t_provider->setState(Provider::State::ERROR);\n\t\t\tthrow;\n\t\t}\n\t}\n\nprivate:\n\tstd::shared_ptr<Provider> _provider;\n};\n\nProvider::Provider()\n\t\t: _state(State::IDLE)\n{\n}\n\nProvider::~Provider()\n{\n\tif (_runnable != nullptr)\n\t{\n\t\tFail(__FILE__, __func__, __LINE__).add(\"Provider is running and you try to release it durring this operation\")\n\t\t\t\t.report();\n\t}\n}\n\nvoid Provider::setReceiver(Receiver* receiver)\n{\n\t_receiver = receiver;\n}\n\nvoid Provider::onRequestData(std::shared_ptr<Provider>& thisProvider)\n{\n\tif (_runnable != nullptr)\n\t{\n\t\tELOG(\"Already queued\");\n\t\treturn;\n\t}\n\n\tassert(thisProvider.get() == this);\n\n\t_runnable = new BackroundHelper(thisProvider);\n\t_receiver->onStartLoading();\n\tDirector::getInstance().getApp()->getApiThreadPool().start(*_runnable);\n\tregisterCheck();\n}\n\nvoid Provider::cancel()\n{\n\tif (isReady())\n\t{\n\t\t\/\/Skip if doing nothing\n\t\treturn;\n\t}\n\tif (_state != State::CANCELED)\n\t{\n\t\tsetState(State::CANCELED);\n\t\tonCancel();\n\t}\n}\n\nvoid Provider::onCancel()\n{\n\t\/\/TODO implement\n\tDLOG(\"OnCancel\");\n\tif (_receiver != nullptr)\n\t{\n\t\t_receiver->onStopLoading();\n\t}\n}\n\nvoid Provider::onEvent(const void* sender, int& dummy)\n{\n\tif (_runnable == nullptr)\n\t{\n\t\tFail(__FILE__, __func__, __LINE__).report();\n\t}\n\tauto request = dynamic_cast<BackroundHelper*>(_runnable);\n assert(request != nullptr);\n\tif (request->isReady == false)\n\t{\n\t\tDLOG(\"WAITING!\");\n\t\treturn;\n\t}\n\tDLOG(\"Done request\");\n\n\tonPostExecute();\n\n\tif (_receiver != nullptr)\n\t{\n\t\tif (_state == State::ERROR)\n\t\t{\n\t\t\t_receiver->onStopLoading();\n\t\t\t\/\/TODO add catches?\n\t\t\tgetReceiver()->onError(this);\n\t\t}\n\t\telse if (_state == State::DONE)\n\t\t{\n\t\t\t_receiver->onStopLoading();\n\t\t\tgetReceiver()->onReceive(this);\n\t\t}\n\t\telse if (_state == State::CANCELED)\n\t\t{\n\t\t\tDLOG(\"Task canceled\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tFail(__FILE__, __func__, __LINE__).add(\"Wrong state:\").add(static_cast<int>(_state.load())).report();\n\t\t}\n\t}\n\telse\n\t{\n\t\tDLOG(\"%s:%s:%d\", __FILE__, __func__, __LINE__);\n\t\tWLOG(\"No one to notify!\");\n\t}\n\n\tunregisterCheck();\n\tsetState(State::IDLE);\n\n\tauto runnable = _runnable;\n\t_runnable = nullptr;\n\tdelete runnable;\n}\n\nvoid Provider::registerCheck()\n{\n\tDirector::getInstance().getApp()->getUILoop().uiTick += Poco::delegate(this, &Provider::onEvent);\n}\n\nvoid Provider::unregisterCheck()\n{\n\tDirector::getInstance().getApp()->getUILoop().uiTick -= Poco::delegate(this, &Provider::onEvent);\n}\n\nvoid Provider::setState(State state)\n{\n\tif (_state == State::CANCELED && state != State::IDLE)\n\t{\n\t\treturn;\n\t}\n\t_state = state;\n}\n\nbool Provider::isCanceled()\n{\n\treturn _state == State::CANCELED;\n}\n\nbool Provider::isReady()\n{\n\treturn _state == State::IDLE;\n}\n<commit_msg>Change log level<commit_after>\/\/\n\/\/ Created by Dawid Drozd aka Gelldur on 03.02.16.\n\/\/\n\n#include \"Provider.h\"\n\n#include <log.h>\n#include <Poco\/Delegate.h>\n#include <Poco\/Runnable.h>\n#include <Director.h>\n#include <exception\/Fail.h>\n#include <acme\/guard\/ChangeOnEnd.h>\n#include \"Application.h\"\n\n\/\/TODO make thread safe\nclass BackroundHelper : public Poco::Runnable\n{\npublic:\n\tstd::atomic<bool> isReady;\n\n\tBackroundHelper(std::shared_ptr<Provider>& provider)\n\t\t\t: isReady(false)\n\t\t\t, _provider(provider)\n\t{\n\t\tassert(_provider);\n\t\t_provider->setState(Provider::State::BEFORE_RUN);\n\t}\n\n\tvirtual void run() override\n\t{\n\t\tChangeOnEnd<std::atomic<bool>, bool> guard(isReady, true);\n\t\ttry\n\t\t{\n\t\t\trunTask();\n\t\t}\n\t\tcatch (std::exception& exception)\n\t\t{\n\t\t\tELOG(\"Exception in background task!\\nWhat: %s\", exception.what());\n\t\t\tthrow;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tELOG(\"Exception in background task!\");\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tvoid runTask()\n\t{\n\t\tif (_provider->isCanceled())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t_provider->setState(Provider::State::RUNNING);\n\t\ttry\n\t\t{\n\t\t\t_provider->onDoInBackground();\n\t\t\t_provider->setState(Provider::State::DONE);\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\t_provider->setState(Provider::State::ERROR);\n\t\t\tthrow;\n\t\t}\n\t}\n\nprivate:\n\tstd::shared_ptr<Provider> _provider;\n};\n\nProvider::Provider()\n\t\t: _state(State::IDLE)\n{\n}\n\nProvider::~Provider()\n{\n\tif (_runnable != nullptr)\n\t{\n\t\tFail(__FILE__, __func__, __LINE__).add(\"Provider is running and you try to release it durring this operation\")\n\t\t\t\t.report();\n\t}\n}\n\nvoid Provider::setReceiver(Receiver* receiver)\n{\n\t_receiver = receiver;\n}\n\nvoid Provider::onRequestData(std::shared_ptr<Provider>& thisProvider)\n{\n\tif (_runnable != nullptr)\n\t{\n\t\tELOG(\"Already queued\");\n\t\treturn;\n\t}\n\tassert(thisProvider.get() == this);\n\n\t_runnable = new BackroundHelper(thisProvider);\n\t_receiver->onStartLoading();\n\tDirector::getInstance().getApp()->getApiThreadPool().start(*_runnable);\n\tregisterCheck();\n}\n\nvoid Provider::cancel()\n{\n\tif (isReady())\n\t{\n\t\t\/\/Skip if doing nothing\n\t\treturn;\n\t}\n\tif (_state != State::CANCELED)\n\t{\n\t\tsetState(State::CANCELED);\n\t\tonCancel();\n\t}\n}\n\nvoid Provider::onCancel()\n{\n\t\/\/TODO implement\n\tDLOG(\"OnCancel\");\n\tif (_receiver != nullptr)\n\t{\n\t\t_receiver->onStopLoading();\n\t}\n}\n\nvoid Provider::onEvent(const void* sender, int& dummy)\n{\n\tif (_runnable == nullptr)\n\t{\n\t\tFail(__FILE__, __func__, __LINE__).report();\n\t}\n\tauto request = dynamic_cast<BackroundHelper*>(_runnable);\n assert(request != nullptr);\n\tif (request->isReady == false)\n\t{\n\t\tDLOG(\"WAITING!\");\n\t\treturn;\n\t}\n\tDLOG(\"Done request\");\n\n\tonPostExecute();\n\n\tif (_receiver != nullptr)\n\t{\n\t\tif (_state == State::ERROR)\n\t\t{\n\t\t\t_receiver->onStopLoading();\n\t\t\t\/\/TODO add catches?\n\t\t\tgetReceiver()->onError(this);\n\t\t}\n\t\telse if (_state == State::DONE)\n\t\t{\n\t\t\t_receiver->onStopLoading();\n\t\t\tgetReceiver()->onReceive(this);\n\t\t}\n\t\telse if (_state == State::CANCELED)\n\t\t{\n\t\t\tDLOG(\"Task canceled\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tFail(__FILE__, __func__, __LINE__).add(\"Wrong state:\").add(static_cast<int>(_state.load())).report();\n\t\t}\n\t}\n\telse\n\t{\n\t\tDLOG(\"%s:%s:%d\", __FILE__, __func__, __LINE__);\n\t\tWLOG(\"No one to notify!\");\n\t}\n\n\tunregisterCheck();\n\tsetState(State::IDLE);\n\n\tauto runnable = _runnable;\n\t_runnable = nullptr;\n\tdelete runnable;\n}\n\nvoid Provider::registerCheck()\n{\n\tDirector::getInstance().getApp()->getUILoop().uiTick += Poco::delegate(this, &Provider::onEvent);\n}\n\nvoid Provider::unregisterCheck()\n{\n\tDirector::getInstance().getApp()->getUILoop().uiTick -= Poco::delegate(this, &Provider::onEvent);\n}\n\nvoid Provider::setState(State state)\n{\n\tif (_state == State::CANCELED && state != State::IDLE)\n\t{\n\t\treturn;\n\t}\n\t_state = state;\n}\n\nbool Provider::isCanceled()\n{\n\treturn _state == State::CANCELED;\n}\n\nbool Provider::isReady()\n{\n\treturn _state == State::IDLE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dbusgateway.h\"\n\n#include <boost\/shared_ptr.hpp>\n#include \"logger.h\"\n#include \"types.h\"\n\nDbusGateway::DbusGateway(const Config& config_in, command::Channel* command_channel_in) : config(config_in), command_channel(command_channel_in), swlm(config) {\n int ret;\n dbus_error_init(&err);\n conn = dbus_bus_get(DBUS_BUS_SESSION, &err);\n if (dbus_error_is_set(&err)) {\n LOGGER_LOG(LVL_error, \"Dbus Connection Error: \" << err.message);\n dbus_error_free(&err);\n return;\n }\n\n ret = dbus_bus_request_name(conn, config_in.dbus.interface.c_str(), DBUS_NAME_FLAG_REPLACE_EXISTING, &err);\n if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {\n LOGGER_LOG(LVL_error, \"Cannot request Dbus name '\" << config_in.dbus.interface << \"' as primary owner\");\n return;\n }\n boost::thread(boost::bind(&DbusGateway::run, this));\n}\n\nDbusGateway::~DbusGateway() {\n dbus_bus_release_name(conn, config.dbus.interface.c_str(), NULL);\n dbus_connection_unref(conn);\n}\n\nvoid DbusGateway::processEvent(const boost::shared_ptr<event::BaseEvent>& event) {\n if (event->variant == \"DownloadComplete\") {\n event::DownloadComplete* download_complete_event = static_cast<event::DownloadComplete*>(event.get());\n swlm.downloadComplete(download_complete_event->download_complete.update_image, download_complete_event->download_complete.signature);\n fireDownloadCompleteEvent(download_complete_event->download_complete);\n } else if (event->variant == \"InstalledSoftwareNeeded\") {\n fireInstalledSoftwareNeededEvent();\n } else if (event->variant == \"UpdateAvailable\") {\n event::UpdateAvailable* update_vailable_event = static_cast<event::UpdateAvailable*>(event.get());\n fireUpdateAvailableEvent(update_vailable_event->update_vailable);\n }\n}\n\nvoid DbusGateway::fireInstalledSoftwareNeededEvent() {\n DBusMessage* msg;\n msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), \"InstalledSoftwareNeeded\");\n\n dbus_connection_send(conn, msg, NULL);\n\n dbus_message_unref(msg);\n}\n\nvoid DbusGateway::fireUpdateAvailableEvent(const data::UpdateAvailable& update_available) {\n DBusMessage* msg;\n DBusMessageIter iter;\n\n msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), \"UpdateAvailable\");\n\n dbus_message_iter_init_append(msg, &iter);\n\n DBusMessageIter sub_iter;\n dbus_message_iter_open_container(&iter, DBUS_TYPE_STRUCT, NULL, &sub_iter);\n const char* update_id = update_available.update_id.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_id);\n const char* description = update_available.description.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &description);\n const char* signature = update_available.signature.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &signature);\n unsigned long long size = update_available.size;\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_UINT64, &size);\n\n dbus_message_iter_close_container(&iter, &sub_iter);\n\n dbus_connection_send(conn, msg, NULL);\n\n dbus_message_unref(msg);\n}\n\nvoid DbusGateway::fireDownloadCompleteEvent(const data::DownloadComplete& download_complete) {\n DBusMessage* msg;\n DBusMessageIter iter;\n\n msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), \"DownloadComplete\");\n dbus_message_iter_init_append(msg, &iter);\n\n DBusMessageIter sub_iter;\n dbus_message_iter_open_container(&iter, DBUS_TYPE_STRUCT, NULL, &sub_iter);\n const char* update_id = download_complete.update_id.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_id);\n const char* update_image = download_complete.update_image.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_image);\n const char* signature = download_complete.signature.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &signature);\n dbus_message_iter_close_container(&iter, &sub_iter);\n\n dbus_connection_send(conn, msg, NULL);\n dbus_message_unref(msg);\n}\n\nvoid DbusGateway::run() {\n DBusMessage* msg;\n char* string_param;\n DBusMessageIter args;\n\n while (true) {\n dbus_connection_read_write(conn, 0);\n msg = dbus_connection_pop_message(conn);\n if (NULL == msg) {\n sleep(1);\n continue;\n }\n\n if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"initiateDownload\") ||\n dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"abortDownload\") ||\n dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"updateReport\")) {\n if (!dbus_message_iter_init(msg, &args) || DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) {\n LOGGER_LOG(LVL_error, \"dbus method initiateDownload called with wrong arguments\");\n dbus_message_unref(msg);\n continue;\n } else {\n dbus_message_iter_get_basic(&args, &string_param);\n }\n }\n if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"initiateDownload\")) {\n *command_channel << boost::shared_ptr<command::StartDownload>(new command::StartDownload(string_param));\n } else if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"abortDownload\")) {\n *command_channel << boost::shared_ptr<command::AbortDownload>(new command::AbortDownload(string_param));\n } else if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"updateReport\")) {\n data::UpdateReport update_report;\n update_report.update_id = string_param;\n if (dbus_message_iter_next(&args) && DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(&args)) {\n DBusMessageIter operation_result_args;\n int results_count = dbus_message_iter_get_element_count(&args);\n dbus_message_iter_recurse(&args, &operation_result_args);\n do {\n try {\n update_report.operation_results.push_back(getOperationResult(&operation_result_args));\n } catch (...) {\n LOGGER_LOG(LVL_error, \"dbus method 'updateReport' called with wrong arguments\");\n }\n dbus_message_iter_next(&operation_result_args);\n results_count--;\n } while (results_count);\n\n } else {\n LOGGER_LOG(LVL_error, \"dbus methid called with wrong argents\");\n dbus_message_unref(msg);\n continue;\n }\n *command_channel << boost::shared_ptr<command::SendUpdateReport>(new command::SendUpdateReport(update_report));\n }\n\n DBusMessage* reply = dbus_message_new_method_return(msg);\n dbus_connection_send(conn, reply, NULL);\n dbus_connection_flush(conn);\n\n dbus_message_unref(reply);\n dbus_message_unref(msg);\n }\n}\n\ndata::OperationResult DbusGateway::getOperationResult(DBusMessageIter* iter) {\n DBusMessageIter subiter, dict_iter, variant_iter;\n char* string_param;\n int int_param;\n data::OperationResult result;\n int params = dbus_message_iter_get_element_count(iter);\n dbus_message_iter_recurse(iter, &subiter);\n if (DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(iter)) {\n while (params) {\n dbus_message_iter_recurse(&subiter, &dict_iter);\n dbus_message_iter_get_basic(&dict_iter, &string_param);\n dbus_message_iter_next(&dict_iter);\n dbus_message_iter_recurse(&dict_iter, &variant_iter);\n if (std::string(string_param) == \"id\") {\n dbus_message_iter_get_basic(&variant_iter, &string_param);\n result.id = string_param;\n dbus_message_iter_next(&subiter);\n } else if (std::string(string_param) == \"result_code\") {\n dbus_message_iter_get_basic(&variant_iter, &int_param);\n result.result_code = (data::UpdateResultCode)int_param;\n dbus_message_iter_next(&subiter);\n } else if (std::string(string_param) == \"result_text\") {\n dbus_message_iter_get_basic(&variant_iter, &string_param);\n result.result_text = string_param;\n dbus_message_iter_next(&subiter);\n }\n params--;\n }\n }\n return result;\n}\n<commit_msg>Explicitly initialise libsbus in 'threads' mode<commit_after>#include \"dbusgateway.h\"\n\n#include <boost\/shared_ptr.hpp>\n#include \"logger.h\"\n#include \"types.h\"\n\nDbusGateway::DbusGateway(const Config& config_in, command::Channel* command_channel_in) : config(config_in), command_channel(command_channel_in), swlm(config) {\n dbus_threads_init_default();\n dbus_error_init(&err);\n conn = dbus_bus_get(DBUS_BUS_SESSION, &err);\n if (dbus_error_is_set(&err)) {\n LOGGER_LOG(LVL_error, \"Dbus Connection Error: \" << err.message);\n dbus_error_free(&err);\n return;\n }\n\n int ret = dbus_bus_request_name(conn, config_in.dbus.interface.c_str(), DBUS_NAME_FLAG_REPLACE_EXISTING, &err);\n if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {\n LOGGER_LOG(LVL_error, \"Cannot request Dbus name '\" << config_in.dbus.interface << \"' as primary owner\");\n return;\n }\n boost::thread(boost::bind(&DbusGateway::run, this));\n}\n\nDbusGateway::~DbusGateway() {\n dbus_bus_release_name(conn, config.dbus.interface.c_str(), NULL);\n dbus_connection_unref(conn);\n}\n\nvoid DbusGateway::processEvent(const boost::shared_ptr<event::BaseEvent>& event) {\n if (event->variant == \"DownloadComplete\") {\n event::DownloadComplete* download_complete_event = static_cast<event::DownloadComplete*>(event.get());\n swlm.downloadComplete(download_complete_event->download_complete.update_image, download_complete_event->download_complete.signature);\n fireDownloadCompleteEvent(download_complete_event->download_complete);\n } else if (event->variant == \"InstalledSoftwareNeeded\") {\n fireInstalledSoftwareNeededEvent();\n } else if (event->variant == \"UpdateAvailable\") {\n event::UpdateAvailable* update_vailable_event = static_cast<event::UpdateAvailable*>(event.get());\n fireUpdateAvailableEvent(update_vailable_event->update_vailable);\n }\n}\n\nvoid DbusGateway::fireInstalledSoftwareNeededEvent() {\n DBusMessage* msg;\n msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), \"InstalledSoftwareNeeded\");\n\n dbus_connection_send(conn, msg, NULL);\n\n dbus_message_unref(msg);\n}\n\nvoid DbusGateway::fireUpdateAvailableEvent(const data::UpdateAvailable& update_available) {\n DBusMessage* msg;\n DBusMessageIter iter;\n\n msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), \"UpdateAvailable\");\n\n dbus_message_iter_init_append(msg, &iter);\n\n DBusMessageIter sub_iter;\n dbus_message_iter_open_container(&iter, DBUS_TYPE_STRUCT, NULL, &sub_iter);\n const char* update_id = update_available.update_id.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_id);\n const char* description = update_available.description.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &description);\n const char* signature = update_available.signature.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &signature);\n unsigned long long size = update_available.size;\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_UINT64, &size);\n\n dbus_message_iter_close_container(&iter, &sub_iter);\n\n dbus_connection_send(conn, msg, NULL);\n\n dbus_message_unref(msg);\n}\n\nvoid DbusGateway::fireDownloadCompleteEvent(const data::DownloadComplete& download_complete) {\n DBusMessage* msg;\n DBusMessageIter iter;\n\n msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), \"DownloadComplete\");\n dbus_message_iter_init_append(msg, &iter);\n\n DBusMessageIter sub_iter;\n dbus_message_iter_open_container(&iter, DBUS_TYPE_STRUCT, NULL, &sub_iter);\n const char* update_id = download_complete.update_id.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_id);\n const char* update_image = download_complete.update_image.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_image);\n const char* signature = download_complete.signature.c_str();\n dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &signature);\n dbus_message_iter_close_container(&iter, &sub_iter);\n\n dbus_connection_send(conn, msg, NULL);\n dbus_message_unref(msg);\n}\n\nvoid DbusGateway::run() {\n DBusMessage* msg;\n char* string_param;\n DBusMessageIter args;\n\n while (true) {\n dbus_connection_read_write(conn, 0);\n msg = dbus_connection_pop_message(conn);\n if (NULL == msg) {\n sleep(1);\n continue;\n }\n\n if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"initiateDownload\") ||\n dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"abortDownload\") ||\n dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"updateReport\")) {\n if (!dbus_message_iter_init(msg, &args) || DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) {\n LOGGER_LOG(LVL_error, \"dbus method initiateDownload called with wrong arguments\");\n dbus_message_unref(msg);\n continue;\n } else {\n dbus_message_iter_get_basic(&args, &string_param);\n }\n }\n if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"initiateDownload\")) {\n *command_channel << boost::shared_ptr<command::StartDownload>(new command::StartDownload(string_param));\n } else if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"abortDownload\")) {\n *command_channel << boost::shared_ptr<command::AbortDownload>(new command::AbortDownload(string_param));\n } else if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), \"updateReport\")) {\n data::UpdateReport update_report;\n update_report.update_id = string_param;\n if (dbus_message_iter_next(&args) && DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(&args)) {\n DBusMessageIter operation_result_args;\n int results_count = dbus_message_iter_get_element_count(&args);\n dbus_message_iter_recurse(&args, &operation_result_args);\n do {\n try {\n update_report.operation_results.push_back(getOperationResult(&operation_result_args));\n } catch (...) {\n LOGGER_LOG(LVL_error, \"dbus method 'updateReport' called with wrong arguments\");\n }\n dbus_message_iter_next(&operation_result_args);\n results_count--;\n } while (results_count);\n\n } else {\n LOGGER_LOG(LVL_error, \"dbus methid called with wrong argents\");\n dbus_message_unref(msg);\n continue;\n }\n *command_channel << boost::shared_ptr<command::SendUpdateReport>(new command::SendUpdateReport(update_report));\n }\n\n DBusMessage* reply = dbus_message_new_method_return(msg);\n dbus_connection_send(conn, reply, NULL);\n dbus_connection_flush(conn);\n\n dbus_message_unref(reply);\n dbus_message_unref(msg);\n }\n}\n\ndata::OperationResult DbusGateway::getOperationResult(DBusMessageIter* iter) {\n DBusMessageIter subiter, dict_iter, variant_iter;\n char* string_param;\n int int_param;\n data::OperationResult result;\n int params = dbus_message_iter_get_element_count(iter);\n dbus_message_iter_recurse(iter, &subiter);\n if (DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(iter)) {\n while (params) {\n dbus_message_iter_recurse(&subiter, &dict_iter);\n dbus_message_iter_get_basic(&dict_iter, &string_param);\n dbus_message_iter_next(&dict_iter);\n dbus_message_iter_recurse(&dict_iter, &variant_iter);\n if (std::string(string_param) == \"id\") {\n dbus_message_iter_get_basic(&variant_iter, &string_param);\n result.id = string_param;\n dbus_message_iter_next(&subiter);\n } else if (std::string(string_param) == \"result_code\") {\n dbus_message_iter_get_basic(&variant_iter, &int_param);\n result.result_code = (data::UpdateResultCode)int_param;\n dbus_message_iter_next(&subiter);\n } else if (std::string(string_param) == \"result_text\") {\n dbus_message_iter_get_basic(&variant_iter, &string_param);\n result.result_text = string_param;\n dbus_message_iter_next(&subiter);\n }\n params--;\n }\n }\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Added default colors to the color values used in the *_dialog() functions.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n\/\/\/ \\file libuobject\/uvar.cc\n\n#include <libport\/format.hh>\n\n#include <libport\/debug.hh>\n#include <libport\/escape.hh>\n#include <libport\/lexical-cast.hh>\n\n#include <urbi\/uabstractclient.hh>\n#include <urbi\/ublend-type.hh>\n#include <urbi\/uexternal.hh>\n#include <urbi\/umessage.hh>\n#include <urbi\/uobject.hh>\n#include <urbi\/usyncclient.hh>\n\n#include <liburbi\/compatibility.hh>\n\n#include <libuobject\/remote-ucontext-impl.hh>\n\nnamespace urbi\n{\n namespace impl\n {\n\n GD_CATEGORY(LibUObject);\n\n \/\/! UVar initialization\n void\n RemoteUVarImpl::initialize(UVar* owner)\n {\n owner_ = owner;\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n client_ = ctx->client_;\n std::string name = owner_->get_name();\n ctx->varmap()[name].push_back(owner_);\n URBI_SEND_PIPED_COMMAND_C((*client_), \"if (!isdef(\" << name << \")) var \"\n << name);\n URBI_SEND_PIPED_COMMAND_C\n ((*client_),\n libport::format(\"external var %s from dummy\",\n owner_->get_name()));\n ctx->dataSent = true;\n }\n\n bool RemoteUVarImpl::setBypass(bool enable)\n {\n return !enable;\n }\n\n \/\/! UVar out value (read mode)\n ufloat&\n RemoteUVarImpl::out()\n {\n return const_cast<ufloat&>(get().val);\n }\n\n \/\/! UVar in value (write mode)\n ufloat&\n RemoteUVarImpl::in()\n {\n return const_cast<ufloat&>(get().val);\n }\n\n\n void\n RemoteUVarImpl::setProp(UProperty p, const UValue& v)\n {\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n URBI_SEND_PIPED_COMMAND_C((*client_), owner_->get_name() << \"->\"\n << urbi::name(p) << \" = \" << v);\n ctx->dataSent = true;\n }\n\n void\n RemoteUVarImpl::keepSynchronized()\n {\n \/\/FIXME: do something?\n }\n\n UValue\n RemoteUVarImpl::getProp(UProperty p)\n {\n UMessage* m = client_->syncGet(\"%s->%s\", owner_->get_name().c_str(),\n urbi::name(p));\n aver(m->value);\n UValue res = *m->value;\n delete m;\n return res;\n }\n\n \/*\n UBlendType\n UVar::blend()\n {\n echo(\"Properties not implemented in remote mode yet.\\n\");\n return UNORMAL;\n }\n *\/\n\n \/\/! UVar destructor.\n void\n RemoteUVarImpl::clean()\n {\n RemoteUContextImpl* ctx = dynamic_cast<RemoteUContextImpl*>(owner_->ctx_);\n ctx->varmap().clean(*owner_);\n }\n\n static\n std::string\n rtp_id()\n {\n \/\/ Compute once in some thread implementations, each thread has different\n \/\/ PID.\n static std::string res =\n libport::format(\"URTP_%s_%s\", getFilteredHostname(),\n#ifdef __UCLIBC__\n \"default\"\n#else\n getpid()\n#endif\n );\n return res;\n }\n\n std::string\n RemoteUContextImpl::makeRTPLink(const std::string& key)\n {\n \/* Setup RTP mode\n * We create two instances of the URTP UObject: one local to this\n * remote, and one plugged in the engine, and connect them together.\n *\/\n \/\/ Spawn a new local RTP instance\n std::string localRTP = rtp_id();\n RemoteUContextImpl::objects_type::iterator oi = objects.find(localRTP);\n if (oi == objects.end())\n return \"\";\n baseURBIStarter* bsa = oi->second->cloner;\n std::string linkName = localRTP + \"_\" + key;\n GD_SINFO_TRACE(\"Instanciating local RTP \" << linkName);\n linkName[linkName.find_first_of(\".\")] = '_';\n bsa->instanciate(this, linkName);\n \/\/ Call init\n localCall(linkName, \"init\");\n\n \/\/ Spawn a remote RTP instance and bind it.\n \/\/ Also destroy it when this remote disconnects\n std::string rLinkName = linkName + \"_l\";\n *client_\n << \"var \" << rLinkName <<\" = URTP.new|\\n\"\n << rLinkName << \".sourceContext = lobby.uid|\\n\"\n << \"disown({var t = Tag.new | t:at(Lobby.onDisconnect?(lobby))\\n\"\n << \"{\\n\"\n << \" wall(\\\" destroying lRTP...\\\")|\\n\"\n << \" try { \" << rLinkName << \".destroy} catch {}|\\n\"\n << \" t.stop\\n\"\n << \"}})|;\\n\";\n GD_SINFO_TRACE(\"fetching engine listen port...\");\n UMessage* mport =\n client_->syncGet(rLinkName +\".listen(\\\"0.0.0.0\\\", \\\"0\\\");\");\n if (!mport || mport->type != MESSAGE_DATA\n || mport->value->type != DATA_DOUBLE)\n {\n GD_SWARN(\"Failed to get remote RTP port, disabling RTP\");\n enableRTP = false;\n return \"\";\n }\n int port = int(mport->value->val);\n delete mport;\n GD_SINFO_TRACE(\"...ok: \" << port);\n \/\/ Invoke the connect method on our RTP instance. Having a reference\n \/\/ to URTP symbols would be painful, so pass through our\n \/\/ UGenericCallback mechanism.\n localCall(linkName, \"connect\", client_->getRemoteHost(), port);\n UObject* ob = getUObject(linkName);\n rtpLinks[key] = ob;\n \/\/ Monitor this RTP link.\n (*client_) << \"detach('external'.monitorRTP(\" << linkName << \",\"\n << rLinkName << \", closure() {'external'.failRTP}))|\"\n << std::endl;\n return linkName;\n }\n\n void\n RemoteUVarImpl::set(const UValue& v)\n {\n std::string fullname = owner_->get_name();\n size_t pos = fullname.rfind(\".\");\n assert(pos != std::string::npos);\n std::string owner = fullname.substr(0, pos);\n std::string name = fullname.substr(pos + 1);\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n libport::utime_t time = libport::utime();\n bool rtp = false;\n if (v.type == DATA_BINARY)\n {\n std::string localRTP = rtp_id();\n if (ctx->enableRTP && getUObject(localRTP)\n && owner_->get_rtp() != UVar::RTP_NO)\n {\n GD_SINFO_TRACE(\"Trying RTP mode using \" << localRTP);\n RemoteUContextImpl::RTPLinks::iterator i\n = ctx->rtpLinks.find(owner_->get_name());\n if (i == ctx->rtpLinks.end())\n {\n std::string linkName = ctx->makeRTPLink(owner_->get_name());\n if (linkName.empty())\n goto rtpfail;\n\n std::string rLinkName = linkName + \"_l\";\n (*ctx->client_)\n << rLinkName << \".receiveVar(\\\"\" << owner_->get_name()\n <<\"\\\")|\";\n i = ctx->rtpLinks.find(owner_->get_name());\n }\n ctx->localCall(i->second->__name, \"send\", v);\n rtp = true;\n }\n rtpfail:\n if (!rtp)\n {\n client_->startPack();\n (*client_) << owner << \".getSlot(\\\"\" << libport::escape(name) << \"\\\").update_timed(\";\n UBinary& b = *(v.binary);\n client_->sendBinary(b.common.data, b.common.size,\n b.getMessage());\n *client_ << \", \" << time << \")|\";\n client_->endPack();\n }\n }\n else\n {\n if (ctx->enableRTP && owner_->get_rtp())\n {\n RemoteUContextImpl::RTPLinks::iterator i\n = ctx->rtpLinks.find(\"_shared_\");\n if (i == ctx->rtpLinks.end())\n {\n std::string linkName = ctx->makeRTPLink(\"_shared_\");\n if (linkName.empty())\n goto rtpfail2;\n i = ctx->rtpLinks.find(\"_shared_\");\n }\n ctx->localCall(i->second->__name, \"sendGrouped\",\n owner_->get_name(), v);\n rtp = true;\n }\n rtpfail2:\n if (!rtp)\n {\n client_->startPack();\n (*client_) << owner << \".getSlot(\\\"\" << libport::escape(name) << \"\\\").update_timed(\";\n if (v.type == DATA_STRING)\n (*client_) << \"\\\"\" << libport::escape(*v.stringValue, '\"') << \"\\\"\";\n else\n *client_ << v ;\n *client_ << \", \" << time << \")|\";\n client_->endPack();\n }\n }\n \/\/ Loopback notification\n ctx->assignMessage(owner_->get_name(), v, time);\n if (!rtp)\n ctx->dataSent = true;\n }\n\n const UValue& RemoteUVarImpl::get() const\n {\n return value_;\n };\n\n \/\/! set own mode\n void\n RemoteUVarImpl::setOwned()\n {\n owner_->owned = true;\n }\n\n \/\/! Get Uvalue type\n UDataType\n RemoteUVarImpl::type() const\n {\n return get().type;\n }\n\n void\n RemoteUVarImpl::request()\n {\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n std::string name = owner_->get_name();\n \/\/build a getvalue message that will be parsed and returned by the server\n URBI_SEND_PIPED_COMMAND_C((*client_), externalModuleTag << \"<<\"\n <<'[' << UEM_ASSIGNVALUE << \",\"\n << '\"' << name << '\"' << ',' << name << ']');\n ctx->dataSent = true;\n }\n\n void\n RemoteUVarImpl::sync()\n {\n std::string tag(client_->fresh());\n std::string repeatChannel;\n if (client_->kernelMajor() < 2)\n repeatChannel = tag + \" << \";\n static boost::format\n fmt(\"{\\n\"\n \" if (isdef (%s) && !(%s))\\n\"\n \" {\\n\"\n \" %s %s\\n\"\n \" }\\n\"\n \" else\\n\"\n \" {\\n\"\n \" %s 1\/0\\n\"\n \" }\\n\"\n \"};\\n\");\n std::string name = owner_->get_name();\n std::string cmd = str(fmt\n % name\n % compatibility::isvoid(name.c_str(),\n client_->kernelMajor())\n % repeatChannel\n % name\n % repeatChannel);\n UMessage* m = client_->syncGetTag(\"%s\", tag.c_str(), 0, cmd.c_str());\n if (m->type == MESSAGE_DATA)\n value_ = *m->value;\n }\n\n time_t\n RemoteUVarImpl::timestamp() const\n {\n return timestamp_;\n }\n\n void\n RemoteUVarImpl::update(const UValue& v, time_t timestamp)\n {\n value_ = v;\n timestamp_ = timestamp;\n }\n\n void RemoteUVarImpl::unnotify()\n {\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n std::string name = owner_->get_name();\n size_t p = name.find_first_of(\".\");\n if (p == name.npos)\n throw std::runtime_error(\"Invalid argument to unnotify: \"+name);\n \/\/ Each UVar creation and each notifychange causes an 'external var'\n \/\/ message, so when the UVar dies, creation count is callbacks.size +1\n send(libport::format(\n \"UObject.unnotify(\\\"%s\\\", \\\"%s\\\", %s)|\",\n name.substr(0, p), name.substr(p+1, name.npos),\n callbacks_.size()+1));\n foreach(RemoteUGenericCallbackImpl* c, callbacks_)\n {\n UTable& t =\n dynamic_cast<RemoteUContextImpl*>(c->owner_->ctx_)\n ->tableByName(c->owner_->type);\n UTable::callbacks_type& ct = t[c->owner_->name];\n UTable::callbacks_type::iterator i =\n std::find(ct.begin(), ct.end(), c->owner_);\n if (i != ct.end())\n ct.erase(i);\n owner_->ctx_->addCleanup(c->owner_);\n owner_->ctx_->addCleanup(c);\n }\n callbacks_.clear();\n ctx->dataSent = true;\n };\n void RemoteUVarImpl::useRTP(bool enable)\n {\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n std::string name = owner_->get_name();\n size_t p = name.find_first_of(\".\");\n if (p == name.npos)\n throw std::runtime_error(\"Invalid argument to useRTP: \"+name);\n send(name.substr(0, p) + \".getSlot(\\\"\" + name.substr(p+1, name.npos)\n + \"\\\").rtp = \" + (enable?\"true;\":\"false;\"));\n ctx->dataSent = true;\n }\n }\n} \/\/namespace urbi\n<commit_msg>uobject remote: Stop updating UVars on which unnotify was called.<commit_after>\/*\n * Copyright (C) 2005-2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n\/\/\/ \\file libuobject\/uvar.cc\n\n#include <libport\/format.hh>\n\n#include <libport\/debug.hh>\n#include <libport\/escape.hh>\n#include <libport\/lexical-cast.hh>\n\n#include <urbi\/uabstractclient.hh>\n#include <urbi\/ublend-type.hh>\n#include <urbi\/uexternal.hh>\n#include <urbi\/umessage.hh>\n#include <urbi\/uobject.hh>\n#include <urbi\/usyncclient.hh>\n\n#include <liburbi\/compatibility.hh>\n\n#include <libuobject\/remote-ucontext-impl.hh>\n\nnamespace urbi\n{\n namespace impl\n {\n\n GD_CATEGORY(LibUObject);\n\n \/\/! UVar initialization\n void\n RemoteUVarImpl::initialize(UVar* owner)\n {\n owner_ = owner;\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n client_ = ctx->client_;\n std::string name = owner_->get_name();\n ctx->varmap()[name].push_back(owner_);\n URBI_SEND_PIPED_COMMAND_C((*client_), \"if (!isdef(\" << name << \")) var \"\n << name);\n URBI_SEND_PIPED_COMMAND_C\n ((*client_),\n libport::format(\"external var %s from dummy\",\n owner_->get_name()));\n ctx->dataSent = true;\n }\n\n bool RemoteUVarImpl::setBypass(bool enable)\n {\n return !enable;\n }\n\n \/\/! UVar out value (read mode)\n ufloat&\n RemoteUVarImpl::out()\n {\n return const_cast<ufloat&>(get().val);\n }\n\n \/\/! UVar in value (write mode)\n ufloat&\n RemoteUVarImpl::in()\n {\n return const_cast<ufloat&>(get().val);\n }\n\n\n void\n RemoteUVarImpl::setProp(UProperty p, const UValue& v)\n {\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n URBI_SEND_PIPED_COMMAND_C((*client_), owner_->get_name() << \"->\"\n << urbi::name(p) << \" = \" << v);\n ctx->dataSent = true;\n }\n\n void\n RemoteUVarImpl::keepSynchronized()\n {\n \/\/FIXME: do something?\n }\n\n UValue\n RemoteUVarImpl::getProp(UProperty p)\n {\n UMessage* m = client_->syncGet(\"%s->%s\", owner_->get_name().c_str(),\n urbi::name(p));\n aver(m->value);\n UValue res = *m->value;\n delete m;\n return res;\n }\n\n \/*\n UBlendType\n UVar::blend()\n {\n echo(\"Properties not implemented in remote mode yet.\\n\");\n return UNORMAL;\n }\n *\/\n\n \/\/! UVar destructor.\n void\n RemoteUVarImpl::clean()\n {\n RemoteUContextImpl* ctx = dynamic_cast<RemoteUContextImpl*>(owner_->ctx_);\n ctx->varmap().clean(*owner_);\n }\n\n static\n std::string\n rtp_id()\n {\n \/\/ Compute once in some thread implementations, each thread has different\n \/\/ PID.\n static std::string res =\n libport::format(\"URTP_%s_%s\", getFilteredHostname(),\n#ifdef __UCLIBC__\n \"default\"\n#else\n getpid()\n#endif\n );\n return res;\n }\n\n std::string\n RemoteUContextImpl::makeRTPLink(const std::string& key)\n {\n \/* Setup RTP mode\n * We create two instances of the URTP UObject: one local to this\n * remote, and one plugged in the engine, and connect them together.\n *\/\n \/\/ Spawn a new local RTP instance\n std::string localRTP = rtp_id();\n RemoteUContextImpl::objects_type::iterator oi = objects.find(localRTP);\n if (oi == objects.end())\n return \"\";\n baseURBIStarter* bsa = oi->second->cloner;\n std::string linkName = localRTP + \"_\" + key;\n GD_SINFO_TRACE(\"Instanciating local RTP \" << linkName);\n linkName[linkName.find_first_of(\".\")] = '_';\n bsa->instanciate(this, linkName);\n \/\/ Call init\n localCall(linkName, \"init\");\n\n \/\/ Spawn a remote RTP instance and bind it.\n \/\/ Also destroy it when this remote disconnects\n std::string rLinkName = linkName + \"_l\";\n *client_\n << \"var \" << rLinkName <<\" = URTP.new|\\n\"\n << rLinkName << \".sourceContext = lobby.uid|\\n\"\n << \"disown({var t = Tag.new | t:at(Lobby.onDisconnect?(lobby))\\n\"\n << \"{\\n\"\n << \" wall(\\\" destroying lRTP...\\\")|\\n\"\n << \" try { \" << rLinkName << \".destroy} catch {}|\\n\"\n << \" t.stop\\n\"\n << \"}})|;\\n\";\n GD_SINFO_TRACE(\"fetching engine listen port...\");\n UMessage* mport =\n client_->syncGet(rLinkName +\".listen(\\\"0.0.0.0\\\", \\\"0\\\");\");\n if (!mport || mport->type != MESSAGE_DATA\n || mport->value->type != DATA_DOUBLE)\n {\n GD_SWARN(\"Failed to get remote RTP port, disabling RTP\");\n enableRTP = false;\n return \"\";\n }\n int port = int(mport->value->val);\n delete mport;\n GD_SINFO_TRACE(\"...ok: \" << port);\n \/\/ Invoke the connect method on our RTP instance. Having a reference\n \/\/ to URTP symbols would be painful, so pass through our\n \/\/ UGenericCallback mechanism.\n localCall(linkName, \"connect\", client_->getRemoteHost(), port);\n UObject* ob = getUObject(linkName);\n rtpLinks[key] = ob;\n \/\/ Monitor this RTP link.\n (*client_) << \"detach('external'.monitorRTP(\" << linkName << \",\"\n << rLinkName << \", closure() {'external'.failRTP}))|\"\n << std::endl;\n return linkName;\n }\n\n void\n RemoteUVarImpl::set(const UValue& v)\n {\n std::string fullname = owner_->get_name();\n size_t pos = fullname.rfind(\".\");\n assert(pos != std::string::npos);\n std::string owner = fullname.substr(0, pos);\n std::string name = fullname.substr(pos + 1);\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n libport::utime_t time = libport::utime();\n bool rtp = false;\n if (v.type == DATA_BINARY)\n {\n std::string localRTP = rtp_id();\n if (ctx->enableRTP && getUObject(localRTP)\n && owner_->get_rtp() != UVar::RTP_NO)\n {\n GD_SINFO_TRACE(\"Trying RTP mode using \" << localRTP);\n RemoteUContextImpl::RTPLinks::iterator i\n = ctx->rtpLinks.find(owner_->get_name());\n if (i == ctx->rtpLinks.end())\n {\n std::string linkName = ctx->makeRTPLink(owner_->get_name());\n if (linkName.empty())\n goto rtpfail;\n\n std::string rLinkName = linkName + \"_l\";\n (*ctx->client_)\n << rLinkName << \".receiveVar(\\\"\" << owner_->get_name()\n <<\"\\\")|\";\n i = ctx->rtpLinks.find(owner_->get_name());\n }\n ctx->localCall(i->second->__name, \"send\", v);\n rtp = true;\n }\n rtpfail:\n if (!rtp)\n {\n client_->startPack();\n (*client_) << owner << \".getSlot(\\\"\" << libport::escape(name) << \"\\\").update_timed(\";\n UBinary& b = *(v.binary);\n client_->sendBinary(b.common.data, b.common.size,\n b.getMessage());\n *client_ << \", \" << time << \")|\";\n client_->endPack();\n }\n }\n else\n {\n if (ctx->enableRTP && owner_->get_rtp())\n {\n RemoteUContextImpl::RTPLinks::iterator i\n = ctx->rtpLinks.find(\"_shared_\");\n if (i == ctx->rtpLinks.end())\n {\n std::string linkName = ctx->makeRTPLink(\"_shared_\");\n if (linkName.empty())\n goto rtpfail2;\n i = ctx->rtpLinks.find(\"_shared_\");\n }\n ctx->localCall(i->second->__name, \"sendGrouped\",\n owner_->get_name(), v);\n rtp = true;\n }\n rtpfail2:\n if (!rtp)\n {\n client_->startPack();\n (*client_) << owner << \".getSlot(\\\"\" << libport::escape(name) << \"\\\").update_timed(\";\n if (v.type == DATA_STRING)\n (*client_) << \"\\\"\" << libport::escape(*v.stringValue, '\"') << \"\\\"\";\n else\n *client_ << v ;\n *client_ << \", \" << time << \")|\";\n client_->endPack();\n }\n }\n \/\/ Loopback notification\n ctx->assignMessage(owner_->get_name(), v, time);\n if (!rtp)\n ctx->dataSent = true;\n }\n\n const UValue& RemoteUVarImpl::get() const\n {\n return value_;\n };\n\n \/\/! set own mode\n void\n RemoteUVarImpl::setOwned()\n {\n owner_->owned = true;\n }\n\n \/\/! Get Uvalue type\n UDataType\n RemoteUVarImpl::type() const\n {\n return get().type;\n }\n\n void\n RemoteUVarImpl::request()\n {\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n std::string name = owner_->get_name();\n \/\/build a getvalue message that will be parsed and returned by the server\n URBI_SEND_PIPED_COMMAND_C((*client_), externalModuleTag << \"<<\"\n <<'[' << UEM_ASSIGNVALUE << \",\"\n << '\"' << name << '\"' << ',' << name << ']');\n ctx->dataSent = true;\n }\n\n void\n RemoteUVarImpl::sync()\n {\n std::string tag(client_->fresh());\n std::string repeatChannel;\n if (client_->kernelMajor() < 2)\n repeatChannel = tag + \" << \";\n static boost::format\n fmt(\"{\\n\"\n \" if (isdef (%s) && !(%s))\\n\"\n \" {\\n\"\n \" %s %s\\n\"\n \" }\\n\"\n \" else\\n\"\n \" {\\n\"\n \" %s 1\/0\\n\"\n \" }\\n\"\n \"};\\n\");\n std::string name = owner_->get_name();\n std::string cmd = str(fmt\n % name\n % compatibility::isvoid(name.c_str(),\n client_->kernelMajor())\n % repeatChannel\n % name\n % repeatChannel);\n UMessage* m = client_->syncGetTag(\"%s\", tag.c_str(), 0, cmd.c_str());\n if (m->type == MESSAGE_DATA)\n value_ = *m->value;\n }\n\n time_t\n RemoteUVarImpl::timestamp() const\n {\n return timestamp_;\n }\n\n void\n RemoteUVarImpl::update(const UValue& v, time_t timestamp)\n {\n value_ = v;\n timestamp_ = timestamp;\n }\n\n void RemoteUVarImpl::unnotify()\n {\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n std::string name = owner_->get_name();\n size_t p = name.find_first_of(\".\");\n if (p == name.npos)\n throw std::runtime_error(\"Invalid argument to unnotify: \"+name);\n \/\/ Each UVar creation and each notifychange causes an 'external var'\n \/\/ message, so when the UVar dies, creation count is callbacks.size +1\n send(libport::format(\n \"UObject.unnotify(\\\"%s\\\", \\\"%s\\\", %s)|\",\n name.substr(0, p), name.substr(p+1, name.npos),\n callbacks_.size()+1));\n foreach(RemoteUGenericCallbackImpl* c, callbacks_)\n {\n UTable& t =\n dynamic_cast<RemoteUContextImpl*>(c->owner_->ctx_)\n ->tableByName(c->owner_->type);\n UTable::callbacks_type& ct = t[c->owner_->name];\n UTable::callbacks_type::iterator i =\n std::find(ct.begin(), ct.end(), c->owner_);\n if (i != ct.end())\n ct.erase(i);\n owner_->ctx_->addCleanup(c->owner_);\n owner_->ctx_->addCleanup(c);\n }\n callbacks_.clear();\n ctx->dataSent = true;\n if (std::list<UVar*> *us = ctx->varmap().find0(name))\n us->remove(owner_);\n };\n void RemoteUVarImpl::useRTP(bool enable)\n {\n RemoteUContextImpl* ctx = static_cast<RemoteUContextImpl*>(owner_->ctx_);\n std::string name = owner_->get_name();\n size_t p = name.find_first_of(\".\");\n if (p == name.npos)\n throw std::runtime_error(\"Invalid argument to useRTP: \"+name);\n send(name.substr(0, p) + \".getSlot(\\\"\" + name.substr(p+1, name.npos)\n + \"\\\").rtp = \" + (enable?\"true;\":\"false;\"));\n ctx->dataSent = true;\n }\n }\n} \/\/namespace urbi\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2009-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 <ctime>\n#include <string>\n#include <cstdio>\n#include <boost\/limits.hpp>\n#include <boost\/version.hpp>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/time.hpp\"\n\n#ifndef _WIN32\n#include <unistd.h>\n#endif\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\t\/\/ used to cache the current time\n\t\t\/\/ every 100 ms. This is cheaper\n\t\t\/\/ than a system call and can be\n\t\t\/\/ used where more accurate time\n\t\t\/\/ is not necessary\n\t\tptime g_current_time;\n\t}\n\n\tTORRENT_EXPORT ptime const& time_now() { return aux::g_current_time; }\n\n\tchar const* time_now_string()\n\t{\n\/\/\t\ttime_t t = std::time(0);\n\/\/\t\ttm* timeinfo = std::localtime(&t);\n\/\/\t\tstatic char str[200];\n\/\/\t\tstd::strftime(str, 200, \"%b %d %X\", timeinfo);\n\/\/\t\treturn str;\n\n\t\tstatic const ptime start = time_now_hires();\n\t\tstatic char ret[200];\n\t\tint t = total_milliseconds(time_now_hires() - start);\n\t\tint h = t \/ 1000 \/ 60 \/ 60;\n\t\tt -= h * 60 * 60 * 1000;\n\t\tint m = t \/ 1000 \/ 60;\n\t\tt -= m * 60 * 1000;\n\t\tint s = t \/ 1000;\n\t\tt -= s * 1000;\n\t\tint ms = t;\n\t\tsnprintf(ret, sizeof(ret), \"%02d:%02d:%02d.%03d\", h, m, s, ms);\n\t\treturn ret;\n\t}\n\n\tstd::string log_time()\n\t{\n\t\tstatic const ptime start = time_now_hires();\n\t\tchar ret[200];\n\t\tsnprintf(ret, sizeof(ret), \"%\"PRId64, total_microseconds(time_now_hires() - start));\n\t\treturn ret;\n\t}\n}\n\n#if defined TORRENT_USE_BOOST_DATE_TIME\n\n#include <boost\/date_time\/microsec_time_clock.hpp>\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{ return boost::date_time::microsec_clock<ptime>::universal_time(); }\n\tptime min_time()\n\t{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }\n\tptime max_time()\n\t{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }\n\ttime_duration seconds(int s) { return boost::posix_time::seconds(s); }\n\ttime_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }\n\ttime_duration microsec(int s) { return boost::posix_time::microsec(s); }\n\ttime_duration minutes(int s) { return boost::posix_time::minutes(s); }\n\ttime_duration hours(int s) { return boost::posix_time::hours(s); }\n\n\tint total_seconds(time_duration td)\n\t{ return td.total_seconds(); }\n\tint total_milliseconds(time_duration td)\n\t{ return td.total_milliseconds(); }\n\tboost::int64_t total_microseconds(time_duration td)\n\t{ return td.total_microseconds(); }\n}\n\n#else \/\/ TORRENT_USE_BOOST_DATE_TIME\n\nnamespace libtorrent\n{\n\tptime min_time() { return ptime(0); }\n\tptime max_time() { return ptime((std::numeric_limits<boost::uint64_t>::max)()); }\n}\n\n#if defined TORRENT_USE_ABSOLUTE_TIME\n\n#include <mach\/mach_time.h>\n#include <boost\/cstdint.hpp>\n#include \"libtorrent\/assert.hpp\"\n\n\/\/ high precision timer for darwin intel and ppc\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{\n\t\tstatic mach_timebase_info_data_t timebase_info = {0,0};\n\t\tif (timebase_info.denom == 0)\n\t\t\tmach_timebase_info(&timebase_info);\n\t\tboost::uint64_t at = mach_absolute_time();\n\t\t\/\/ make sure we don't overflow\n\t\tTORRENT_ASSERT((at >= at \/ 1000 * timebase_info.numer \/ timebase_info.denom)\n\t\t\t|| (at < 0 && at < at \/ 1000 * timebase_info.numer \/ timebase_info.denom));\n\t\treturn ptime(at \/ 1000 * timebase_info.numer \/ timebase_info.denom);\n\t}\n}\n#elif defined TORRENT_USE_QUERY_PERFORMANCE_TIMER\n\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif\n#include <windows.h>\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\tboost::int64_t performance_counter_to_microseconds(boost::int64_t pc)\n\t\t{\n\t\t\tstatic LARGE_INTEGER performace_counter_frequency = {0,0};\n\t\t\tif (performace_counter_frequency.QuadPart == 0)\n\t\t\t\tQueryPerformanceFrequency(&performace_counter_frequency);\n\n#ifdef TORRENT_DEBUG\n\t\t\t\/\/ make sure we don't overflow\n\t\t\tboost::int64_t ret = (pc * 1000 \/ performace_counter_frequency.QuadPart) * 1000;\n\t\t\tTORRENT_ASSERT((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret));\n#endif\n\t\t\treturn (pc * 1000 \/ performace_counter_frequency.QuadPart) * 1000;\n\t\t}\n\n\t\tboost::int64_t microseconds_to_performance_counter(boost::int64_t ms)\n\t\t{\n\t\t\tstatic LARGE_INTEGER performace_counter_frequency = {0,0};\n\t\t\tif (performace_counter_frequency.QuadPart == 0)\n\t\t\t\tQueryPerformanceFrequency(&performace_counter_frequency);\n#ifdef TORRENT_DEBUG\n\t\t\t\/\/ make sure we don't overflow\n\t\t\tboost::int64_t ret = (ms \/ 1000) * performace_counter_frequency.QuadPart \/ 1000;\n\t\t\tTORRENT_ASSERT((ms >= 0 && ms <= ret)\n\t\t\t\t|| (ms < 0 && ms > ret));\n#endif\n\t\t\treturn (ms \/ 1000) * performace_counter_frequency.QuadPart \/ 1000;\n\t\t}\n\t}\n\n\tptime time_now_hires()\n\t{\n\t\tLARGE_INTEGER now;\n\t\tQueryPerformanceCounter(&now);\n\t\treturn ptime(now.QuadPart);\n\t}\n}\n\n#elif defined TORRENT_USE_CLOCK_GETTIME\n\n#include <time.h>\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{\n\t\ttimespec ts;\n\t\tclock_gettime(CLOCK_MONOTONIC, &ts);\n\t\treturn ptime(boost::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec \/ 1000);\n\t}\n}\n\n#elif defined TORRENT_USE_SYSTEM_TIME\n\n#include <kernel\/OS.h>\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{ return ptime(system_time()); }\n}\n\n#endif \/\/ TORRENT_USE_SYSTEM_TIME\n\n#endif \/\/ TORRENT_USE_BOOST_DATE_TIME\n\n<commit_msg>fix time_duration rounding on windows<commit_after>\/*\n\nCopyright (c) 2009-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 <ctime>\n#include <string>\n#include <cstdio>\n#include <boost\/limits.hpp>\n#include <boost\/version.hpp>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/time.hpp\"\n\n#ifndef _WIN32\n#include <unistd.h>\n#endif\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\t\/\/ used to cache the current time\n\t\t\/\/ every 100 ms. This is cheaper\n\t\t\/\/ than a system call and can be\n\t\t\/\/ used where more accurate time\n\t\t\/\/ is not necessary\n\t\tptime g_current_time;\n\t}\n\n\tTORRENT_EXPORT ptime const& time_now() { return aux::g_current_time; }\n\n\tchar const* time_now_string()\n\t{\n\/\/\t\ttime_t t = std::time(0);\n\/\/\t\ttm* timeinfo = std::localtime(&t);\n\/\/\t\tstatic char str[200];\n\/\/\t\tstd::strftime(str, 200, \"%b %d %X\", timeinfo);\n\/\/\t\treturn str;\n\n\t\tstatic const ptime start = time_now_hires();\n\t\tstatic char ret[200];\n\t\tint t = total_milliseconds(time_now_hires() - start);\n\t\tint h = t \/ 1000 \/ 60 \/ 60;\n\t\tt -= h * 60 * 60 * 1000;\n\t\tint m = t \/ 1000 \/ 60;\n\t\tt -= m * 60 * 1000;\n\t\tint s = t \/ 1000;\n\t\tt -= s * 1000;\n\t\tint ms = t;\n\t\tsnprintf(ret, sizeof(ret), \"%02d:%02d:%02d.%03d\", h, m, s, ms);\n\t\treturn ret;\n\t}\n\n\tstd::string log_time()\n\t{\n\t\tstatic const ptime start = time_now_hires();\n\t\tchar ret[200];\n\t\tsnprintf(ret, sizeof(ret), \"%\"PRId64, total_microseconds(time_now_hires() - start));\n\t\treturn ret;\n\t}\n}\n\n#if defined TORRENT_USE_BOOST_DATE_TIME\n\n#include <boost\/date_time\/microsec_time_clock.hpp>\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{ return boost::date_time::microsec_clock<ptime>::universal_time(); }\n\tptime min_time()\n\t{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }\n\tptime max_time()\n\t{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }\n\ttime_duration seconds(int s) { return boost::posix_time::seconds(s); }\n\ttime_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }\n\ttime_duration microsec(int s) { return boost::posix_time::microsec(s); }\n\ttime_duration minutes(int s) { return boost::posix_time::minutes(s); }\n\ttime_duration hours(int s) { return boost::posix_time::hours(s); }\n\n\tint total_seconds(time_duration td)\n\t{ return td.total_seconds(); }\n\tint total_milliseconds(time_duration td)\n\t{ return td.total_milliseconds(); }\n\tboost::int64_t total_microseconds(time_duration td)\n\t{ return td.total_microseconds(); }\n}\n\n#else \/\/ TORRENT_USE_BOOST_DATE_TIME\n\nnamespace libtorrent\n{\n\tptime min_time() { return ptime(0); }\n\tptime max_time() { return ptime((std::numeric_limits<boost::uint64_t>::max)()); }\n}\n\n#if defined TORRENT_USE_ABSOLUTE_TIME\n\n#include <mach\/mach_time.h>\n#include <boost\/cstdint.hpp>\n#include \"libtorrent\/assert.hpp\"\n\n\/\/ high precision timer for darwin intel and ppc\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{\n\t\tstatic mach_timebase_info_data_t timebase_info = {0,0};\n\t\tif (timebase_info.denom == 0)\n\t\t\tmach_timebase_info(&timebase_info);\n\t\tboost::uint64_t at = mach_absolute_time();\n\t\t\/\/ make sure we don't overflow\n\t\tTORRENT_ASSERT((at >= at \/ 1000 * timebase_info.numer \/ timebase_info.denom)\n\t\t\t|| (at < 0 && at < at \/ 1000 * timebase_info.numer \/ timebase_info.denom));\n\t\treturn ptime(at \/ 1000 * timebase_info.numer \/ timebase_info.denom);\n\t}\n}\n#elif defined TORRENT_USE_QUERY_PERFORMANCE_TIMER\n\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif\n#include <windows.h>\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\tboost::int64_t performance_counter_to_microseconds(boost::int64_t pc)\n\t\t{\n\t\t\tstatic LARGE_INTEGER performace_counter_frequency = {0,0};\n\t\t\tif (performace_counter_frequency.QuadPart == 0)\n\t\t\t\tQueryPerformanceFrequency(&performace_counter_frequency);\n\n#ifdef TORRENT_DEBUG\n\t\t\t\/\/ make sure we don't overflow\n\t\t\tboost::int64_t ret = (pc * 1000 \/ performace_counter_frequency.QuadPart) * 1000;\n\t\t\tTORRENT_ASSERT((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret));\n#endif\n\t\t\treturn ((pc * 1000 + performace_counter_frequency.QuadPart \/ 2) \/ performace_counter_frequency.QuadPart) * 1000;\n\t\t}\n\n\t\tboost::int64_t microseconds_to_performance_counter(boost::int64_t ms)\n\t\t{\n\t\t\tstatic LARGE_INTEGER performace_counter_frequency = {0,0};\n\t\t\tif (performace_counter_frequency.QuadPart == 0)\n\t\t\t\tQueryPerformanceFrequency(&performace_counter_frequency);\n#ifdef TORRENT_DEBUG\n\t\t\t\/\/ make sure we don't overflow\n\t\t\tboost::int64_t ret = (ms \/ 1000) * performace_counter_frequency.QuadPart \/ 1000;\n\t\t\tTORRENT_ASSERT((ms >= 0 && ms <= ret)\n\t\t\t\t|| (ms < 0 && ms > ret));\n#endif\n\t\t\treturn (ms \/ 1000) * performace_counter_frequency.QuadPart \/ 1000;\n\t\t}\n\t}\n\n\tptime time_now_hires()\n\t{\n\t\tLARGE_INTEGER now;\n\t\tQueryPerformanceCounter(&now);\n\t\treturn ptime(now.QuadPart);\n\t}\n}\n\n#elif defined TORRENT_USE_CLOCK_GETTIME\n\n#include <time.h>\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{\n\t\ttimespec ts;\n\t\tclock_gettime(CLOCK_MONOTONIC, &ts);\n\t\treturn ptime(boost::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec \/ 1000);\n\t}\n}\n\n#elif defined TORRENT_USE_SYSTEM_TIME\n\n#include <kernel\/OS.h>\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{ return ptime(system_time()); }\n}\n\n#endif \/\/ TORRENT_USE_SYSTEM_TIME\n\n#endif \/\/ TORRENT_USE_BOOST_DATE_TIME\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\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 \n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <osgProducer\/GraphicsContextImplementation>\n#include <osg\/TextureRectangle>\n#include <osg\/TextureCubeMap>\n#include <osg\/Notify>\n\nusing namespace osgProducer;\n\nnamespace osgProducer\n{\n struct MyWindowingSystemInterface : public osg::GraphicsContext::WindowingSystemInterface\n {\n virtual unsigned int getNumScreens(const osg::GraphicsContext::ScreenIdentifier& \/*screenIdentifier*\/) \n {\n return Producer::RenderSurface::getNumberOfScreens();\n }\n\n virtual void getScreenResolution(const osg::GraphicsContext::ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height)\n {\n osg::ref_ptr<Producer::RenderSurface> rs = new Producer::RenderSurface;\n rs->setHostName(screenIdentifier.hostName);\n rs->setDisplayNum(screenIdentifier.displayNum);\n rs->setScreenNum(screenIdentifier.screenNum);\n rs->getScreenSize(width, height);\n }\n\n\n virtual osg::GraphicsContext* createGraphicsContext(osg::GraphicsContext::Traits* traits)\n {\n return new GraphicsContextImplementation(traits);\n }\n };\n\n struct RegisterWindowingSystemInterfaceProxy\n {\n RegisterWindowingSystemInterfaceProxy()\n {\n osg::GraphicsContext::setWindowingSystemInterface(new MyWindowingSystemInterface);\n }\n \n ~RegisterWindowingSystemInterfaceProxy()\n {\n osg::GraphicsContext::setWindowingSystemInterface(0);\n }\n };\n \n RegisterWindowingSystemInterfaceProxy createWindowingSystemInterfaceProxy;\n};\n \n\n\nGraphicsContextImplementation::GraphicsContextImplementation(Traits* traits)\n{\n _traits = traits;\n\n _rs = new Producer::RenderSurface;\n _rs->setWindowName(traits->windowName);\n _rs->setWindowRectangle(traits->x, traits->y, traits->width, traits->height);\n _rs->useBorder(traits->windowDecoration);\n _rs->setDisplayNum(traits->displayNum);\n _rs->setScreenNum(traits->screenNum);\n \n\n \/\/ set the visual chooser\n Producer::VisualChooser* rs_vc = _rs->getVisualChooser();\n if (!rs_vc)\n {\n rs_vc = new Producer::VisualChooser;\n _rs->setVisualChooser(rs_vc);\n }\n \n rs_vc->setRedSize(_traits->red);\n rs_vc->setGreenSize(_traits->green);\n rs_vc->setBlueSize(_traits->blue);\n rs_vc->setAlphaSize(_traits->alpha);\n \n rs_vc->setDepthSize(_traits->depth);\n rs_vc->setStencilSize(_traits->stencil);\n \n if (_traits->doubleBuffer) rs_vc->useDoubleBuffer();\n\n rs_vc->addAttribute( Producer::VisualChooser::RGBA );\n\n \/\/ Always use UseGL\n rs_vc->addAttribute( Producer::VisualChooser::UseGL );\n \n if (traits->pbuffer)\n {\n _rs->setDrawableType(Producer::RenderSurface::DrawableType_PBuffer);\n\n if (traits->target)\n {\n\n _rs->setRenderToTextureOptions(traits->mipMapGeneration ? Producer::RenderSurface::RequestSpaceForMipMaps :\n Producer::RenderSurface::RenderToTextureOptions_Default);\n _rs->setRenderToTextureMipMapLevel(traits->level);\n _rs->setRenderToTextureMode(traits->alpha>0 ? Producer::RenderSurface::RenderToRGBATexture : \n Producer::RenderSurface::RenderToRGBTexture);\n\n switch(traits->target)\n {\n case(GL_TEXTURE_1D) : \n _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture1D);\n break;\n case(GL_TEXTURE_2D) : \n _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture2D);\n break;\n case(GL_TEXTURE_3D) :\n osg::notify(osg::NOTICE)<<\"PBuffer render to Texture3D not supported.\"<<std::endl;\n \/\/ not supported. \n \/\/ _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture3D);\n break;\n case(GL_TEXTURE_RECTANGLE) : \n osg::notify(osg::NOTICE)<<\"PBuffer render to TextureRectangle not supported.\"<<std::endl;\n \/\/ not supported.\n \/\/ _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureRectangle);\n break;\n case(GL_TEXTURE_CUBE_MAP_POSITIVE_X) : \n case(GL_TEXTURE_CUBE_MAP_NEGATIVE_X) : \n case(GL_TEXTURE_CUBE_MAP_POSITIVE_Y) : \n case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) : \n case(GL_TEXTURE_CUBE_MAP_POSITIVE_Z) : \n case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) : \n _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureCUBE);\n _rs->setRenderToTextureFace( Producer::RenderSurface::CubeMapFace(traits->target - GL_TEXTURE_CUBE_MAP_POSITIVE_X));\n break;\n }\n\n }\n \n }\n \n GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(traits->sharedContext);\n\n if (sharedContext)\n {\n \/\/ different graphics context so we have our own state.\n setState(new osg::State);\n \n if (sharedContext->getState())\n {\n getState()->setContextID( sharedContext->getState()->getContextID() );\n incrementContextIDUsageCount( sharedContext->getState()->getContextID() ); \n }\n else\n {\n getState()->setContextID( osg::GraphicsContext::createNewContextID() );\n }\n \n \/\/ but we share texture objects etc. so we also share the same contextID\n \/\/_rs->realize( 0, sharedContext->_rs->getGLContext() );\n \n }\n else\n {\n \n \/\/ need to do something here.... \n setState( new osg::State );\n getState()->setContextID( osg::GraphicsContext::createNewContextID() );\n\n \/\/_rs->realize();\n }\n \n \/\/ _rs->useConfigEventThread(false);\n\n _closeOnDestruction = true;\n}\n\nGraphicsContextImplementation::GraphicsContextImplementation(Producer::RenderSurface* rs)\n{\n _rs = rs;\n _closeOnDestruction = false;\n\n _traits = new osg::GraphicsContext::Traits;\n _traits->windowName = _rs->getWindowName();\n _traits->displayNum = _rs->getDisplayNum();\n _traits->screenNum = _rs->getScreenNum();\n}\n\nGraphicsContextImplementation::~GraphicsContextImplementation()\n{\n if (_closeOnDestruction) close();\n}\n\nbool GraphicsContextImplementation::realizeImplementation()\n{\n if (_rs.valid()) \n {\n GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(_traits->sharedContext);\n\n if (sharedContext)\n {\n _rs->realize( 0, sharedContext->_rs->getGLContext() );\n }\n else\n {\n osg::notify(osg::NOTICE)<<\"GraphicsContextImplementation::realize\"<<std::endl;\n\n _rs->realize();\n }\n return _rs->isRealized();\n }\n else\n {\n return false;\n }\n}\n\nbool GraphicsContextImplementation::makeCurrentImplementation()\n{\n if (!_rs)\n {\n osg::notify(osg::NOTICE)<<\"Error: GraphicsContextImplementation::makeCurrentImplementation() no RenderSurface.\"<<std::endl;\n return false;\n }\n\n if (!isRealized())\n {\n osg::notify(osg::NOTICE)<<\"Error: GraphicsContextImplementation::makeCurrentImplementation() not Realized.\"<<std::endl;\n return false;\n }\n\n\/\/ osg::notify(osg::INFO)<<\"GraphicsContextImplementation::makeCurrentImplementation()\"<<std::endl;\n\n _rs->setReadDrawable( 0 );\n\n \/\/ comment out right now, as Producer's setReadDrawable() is doing a call for us.\n \/\/ _rs->makeCurrent();\n \n return true;\n}\n\nbool GraphicsContextImplementation::makeContextCurrentImplementation(osg::GraphicsContext* readContext)\n{\n if (!_rs) return false;\n\n GraphicsContextImplementation* readContextImplemention = dynamic_cast<GraphicsContextImplementation*>(readContext);\n\n if (readContextImplemention)\n {\n _rs->setReadDrawable( readContextImplemention->getRenderSurface() );\n }\n else\n {\n _rs->setReadDrawable( 0 );\n }\n\n \/\/ comment out right now, as Producer's setReadDrawable() is doing a call for us.\n \/\/ _rs->makeCurrent();\n \n return true;\n}\n\nvoid GraphicsContextImplementation::closeImplementation()\n{\n if (!_rs) return;\n \n \/\/ close render surface by deleting it \n _rs = 0;\n}\n\nvoid GraphicsContextImplementation::bindPBufferToTextureImplementation(GLenum buffer)\n{\n if (!_rs) return;\n \n Producer::RenderSurface::BufferType bufferType = Producer::RenderSurface::FrontBuffer;\n switch(buffer)\n {\n case(GL_BACK): bufferType = Producer::RenderSurface::BackBuffer; break;\n case(GL_FRONT): bufferType = Producer::RenderSurface::FrontBuffer; break;\n default: bufferType = Producer::RenderSurface::FrontBuffer; break;\n }\n\n _rs->bindPBufferToTexture(bufferType);\n}\n\nvoid GraphicsContextImplementation::swapBuffersImplementation()\n{\n _rs->swapBuffers();\n}\n<commit_msg>Added releaseContextImplementation method<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\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 \n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <osgProducer\/GraphicsContextImplementation>\n#include <osg\/TextureRectangle>\n#include <osg\/TextureCubeMap>\n#include <osg\/Notify>\n\nusing namespace osgProducer;\n\nnamespace osgProducer\n{\n struct MyWindowingSystemInterface : public osg::GraphicsContext::WindowingSystemInterface\n {\n virtual unsigned int getNumScreens(const osg::GraphicsContext::ScreenIdentifier& \/*screenIdentifier*\/) \n {\n return Producer::RenderSurface::getNumberOfScreens();\n }\n\n virtual void getScreenResolution(const osg::GraphicsContext::ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height)\n {\n osg::ref_ptr<Producer::RenderSurface> rs = new Producer::RenderSurface;\n rs->setHostName(screenIdentifier.hostName);\n rs->setDisplayNum(screenIdentifier.displayNum);\n rs->setScreenNum(screenIdentifier.screenNum);\n rs->getScreenSize(width, height);\n }\n\n\n virtual osg::GraphicsContext* createGraphicsContext(osg::GraphicsContext::Traits* traits)\n {\n return new GraphicsContextImplementation(traits);\n }\n };\n\n struct RegisterWindowingSystemInterfaceProxy\n {\n RegisterWindowingSystemInterfaceProxy()\n {\n osg::GraphicsContext::setWindowingSystemInterface(new MyWindowingSystemInterface);\n }\n \n ~RegisterWindowingSystemInterfaceProxy()\n {\n osg::GraphicsContext::setWindowingSystemInterface(0);\n }\n };\n \n RegisterWindowingSystemInterfaceProxy createWindowingSystemInterfaceProxy;\n};\n \n\n\nGraphicsContextImplementation::GraphicsContextImplementation(Traits* traits)\n{\n _traits = traits;\n\n _rs = new Producer::RenderSurface;\n _rs->setWindowName(traits->windowName);\n _rs->setWindowRectangle(traits->x, traits->y, traits->width, traits->height);\n _rs->useBorder(traits->windowDecoration);\n _rs->setDisplayNum(traits->displayNum);\n _rs->setScreenNum(traits->screenNum);\n \n\n \/\/ set the visual chooser\n Producer::VisualChooser* rs_vc = _rs->getVisualChooser();\n if (!rs_vc)\n {\n rs_vc = new Producer::VisualChooser;\n _rs->setVisualChooser(rs_vc);\n }\n \n rs_vc->setRedSize(_traits->red);\n rs_vc->setGreenSize(_traits->green);\n rs_vc->setBlueSize(_traits->blue);\n rs_vc->setAlphaSize(_traits->alpha);\n \n rs_vc->setDepthSize(_traits->depth);\n rs_vc->setStencilSize(_traits->stencil);\n \n if (_traits->doubleBuffer) rs_vc->useDoubleBuffer();\n\n rs_vc->addAttribute( Producer::VisualChooser::RGBA );\n\n \/\/ Always use UseGL\n rs_vc->addAttribute( Producer::VisualChooser::UseGL );\n \n if (traits->pbuffer)\n {\n _rs->setDrawableType(Producer::RenderSurface::DrawableType_PBuffer);\n\n if (traits->target)\n {\n\n _rs->setRenderToTextureOptions(traits->mipMapGeneration ? Producer::RenderSurface::RequestSpaceForMipMaps :\n Producer::RenderSurface::RenderToTextureOptions_Default);\n _rs->setRenderToTextureMipMapLevel(traits->level);\n _rs->setRenderToTextureMode(traits->alpha>0 ? Producer::RenderSurface::RenderToRGBATexture : \n Producer::RenderSurface::RenderToRGBTexture);\n\n switch(traits->target)\n {\n case(GL_TEXTURE_1D) : \n _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture1D);\n break;\n case(GL_TEXTURE_2D) : \n _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture2D);\n break;\n case(GL_TEXTURE_3D) :\n osg::notify(osg::NOTICE)<<\"PBuffer render to Texture3D not supported.\"<<std::endl;\n \/\/ not supported. \n \/\/ _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture3D);\n break;\n case(GL_TEXTURE_RECTANGLE) : \n osg::notify(osg::NOTICE)<<\"PBuffer render to TextureRectangle not supported.\"<<std::endl;\n \/\/ not supported.\n \/\/ _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureRectangle);\n break;\n case(GL_TEXTURE_CUBE_MAP_POSITIVE_X) : \n case(GL_TEXTURE_CUBE_MAP_NEGATIVE_X) : \n case(GL_TEXTURE_CUBE_MAP_POSITIVE_Y) : \n case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) : \n case(GL_TEXTURE_CUBE_MAP_POSITIVE_Z) : \n case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) : \n _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureCUBE);\n _rs->setRenderToTextureFace( Producer::RenderSurface::CubeMapFace(traits->target - GL_TEXTURE_CUBE_MAP_POSITIVE_X));\n break;\n }\n\n }\n \n }\n \n GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(traits->sharedContext);\n\n if (sharedContext)\n {\n \/\/ different graphics context so we have our own state.\n setState(new osg::State);\n \n if (sharedContext->getState())\n {\n getState()->setContextID( sharedContext->getState()->getContextID() );\n incrementContextIDUsageCount( sharedContext->getState()->getContextID() ); \n }\n else\n {\n getState()->setContextID( osg::GraphicsContext::createNewContextID() );\n }\n \n \/\/ but we share texture objects etc. so we also share the same contextID\n \/\/_rs->realize( 0, sharedContext->_rs->getGLContext() );\n \n }\n else\n {\n \n \/\/ need to do something here.... \n setState( new osg::State );\n getState()->setContextID( osg::GraphicsContext::createNewContextID() );\n\n \/\/_rs->realize();\n }\n \n \/\/ _rs->useConfigEventThread(false);\n\n _closeOnDestruction = true;\n}\n\nGraphicsContextImplementation::GraphicsContextImplementation(Producer::RenderSurface* rs)\n{\n _rs = rs;\n _closeOnDestruction = false;\n\n _traits = new osg::GraphicsContext::Traits;\n _traits->windowName = _rs->getWindowName();\n _traits->displayNum = _rs->getDisplayNum();\n _traits->screenNum = _rs->getScreenNum();\n}\n\nGraphicsContextImplementation::~GraphicsContextImplementation()\n{\n if (_closeOnDestruction) close();\n}\n\nbool GraphicsContextImplementation::realizeImplementation()\n{\n if (_rs.valid()) \n {\n GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(_traits->sharedContext);\n\n if (sharedContext)\n {\n _rs->realize( 0, sharedContext->_rs->getGLContext() );\n }\n else\n {\n osg::notify(osg::NOTICE)<<\"GraphicsContextImplementation::realize\"<<std::endl;\n\n _rs->realize();\n }\n return _rs->isRealized();\n }\n else\n {\n return false;\n }\n}\n\nbool GraphicsContextImplementation::makeCurrentImplementation()\n{\n if (!_rs)\n {\n osg::notify(osg::NOTICE)<<\"Error: GraphicsContextImplementation::makeCurrentImplementation() no RenderSurface.\"<<std::endl;\n return false;\n }\n\n if (!isRealized())\n {\n osg::notify(osg::NOTICE)<<\"Error: GraphicsContextImplementation::makeCurrentImplementation() not Realized.\"<<std::endl;\n return false;\n }\n\n\/\/ osg::notify(osg::INFO)<<\"GraphicsContextImplementation::makeCurrentImplementation()\"<<std::endl;\n\n _rs->setReadDrawable( 0 );\n\n \/\/ comment out right now, as Producer's setReadDrawable() is doing a call for us.\n \/\/ _rs->makeCurrent();\n \n return true;\n}\n\nbool GraphicsContextImplementation::makeContextCurrentImplementation(osg::GraphicsContext* readContext)\n{\n if (!_rs) return false;\n\n GraphicsContextImplementation* readContextImplemention = dynamic_cast<GraphicsContextImplementation*>(readContext);\n\n if (readContextImplemention)\n {\n _rs->setReadDrawable( readContextImplemention->getRenderSurface() );\n }\n else\n {\n _rs->setReadDrawable( 0 );\n }\n\n \/\/ comment out right now, as Producer's setReadDrawable() is doing a call for us.\n \/\/ _rs->makeCurrent();\n \n return true;\n}\n\nbool GraphicsContextImplementation::makeCurrentImplementation()\n{\n osg::notify(osg::NOTICE)<<\"GraphicsContextImplementation::makeCurrentImplementation(): not implemented - release not supported under Producer.\"<<std::endl;\n return false;\n}\n\nvoid GraphicsContextImplementation::closeImplementation()\n{\n if (!_rs) return;\n \n \/\/ close render surface by deleting it \n _rs = 0;\n}\n\nvoid GraphicsContextImplementation::bindPBufferToTextureImplementation(GLenum buffer)\n{\n if (!_rs) return;\n \n Producer::RenderSurface::BufferType bufferType = Producer::RenderSurface::FrontBuffer;\n switch(buffer)\n {\n case(GL_BACK): bufferType = Producer::RenderSurface::BackBuffer; break;\n case(GL_FRONT): bufferType = Producer::RenderSurface::FrontBuffer; break;\n default: bufferType = Producer::RenderSurface::FrontBuffer; break;\n }\n\n _rs->bindPBufferToTexture(bufferType);\n}\n\nvoid GraphicsContextImplementation::swapBuffersImplementation()\n{\n _rs->swapBuffers();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n===========================================================================\n\nDaemon GPL Source Code\nCopyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.\n\nThis file is part of the Daemon GPL Source Code (Daemon Source Code).\n\nDaemon Source Code is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nDaemon Source Code is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon Source Code. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nIn addition, the Daemon Source Code is also subject to certain additional terms.\nYou should have received a copy of these additional terms immediately following the\nterms and conditions of the GNU General Public License which accompanied the Daemon\nSource Code. If not, please request a copy in writing from id Software at the address\nbelow.\n\nIf you have questions concerning this license or the applicable additional terms, you\nmay contact in writing id Software LLC, c\/o ZeniMax Media Inc., Suite 120, Rockville,\nMaryland 20850 USA.\n\n===========================================================================\n*\/\n\n#include \"server.h\"\n#include \"framework\/CvarSystem.h\"\n\n\/*\n===============================================================================\n\nOPERATOR CONSOLE ONLY COMMANDS\n\nThese commands can only be entered from stdin or by a remote operator datagram\n===============================================================================\n*\/\n\nclass MapCmd: public Cmd::StaticCmd {\n public:\n MapCmd(Str::StringRef name, Str::StringRef description, bool cheat):\n Cmd::StaticCmd(name, Cmd::SYSTEM, description), cheat(cheat) {\n }\n\n void Run(const Cmd::Args& args) const override {\n if (args.Argc() < 2) {\n PrintUsage(args, \"<mapname> (layoutname)\", \"loads a new map\");\n return;\n }\n\n const std::string& mapName = args.Argv(1);\n\n \/\/Make sure the map exists to avoid typos that would kill the game\n FS::GetAvailableMaps();\n const auto loadedPakInfo = FS::PakPath::LocateFile(Str::Format(\"maps\/%s.bsp\", mapName));\n if (!loadedPakInfo) {\n Print(\"Can't find map %s\", mapName);\n return;\n }\n\n \/\/Gets the layout list from the command but do not override if there is nothing\n std::string layouts = args.ConcatArgs(2);\n if (not layouts.empty()) {\n Cvar::SetValue(\"g_layouts\", layouts);\n }\n\n Cvar::SetValueForce(\"sv_cheats\", cheat ? \"1\" : \"0\");\n SV_SpawnServer(loadedPakInfo->name, mapName);\n }\n\n Cmd::CompletionResult Complete(int argNum, const Cmd::Args& args, Str::StringRef prefix) const override {\n if (argNum == 1) {\n Cmd::CompletionResult out;\n for (auto& map: FS::GetAvailableMaps()) {\n if (Str::IsPrefix(prefix, map))\n out.push_back({map, \"\"});\n }\n return out;\n } else if (argNum > 1) {\n return FS::HomePath::CompleteFilename(prefix, \"game\/layouts\/\" + args.Argv(1), \".dat\", false, true);\n }\n\n return {};\n }\n\n private:\n bool cheat;\n};\nstatic MapCmd MapCmdRegistration(\"map\", \"starts a new map\", false);\nstatic MapCmd DevmapCmdRegistration(\"devmap\", \"starts a new map with cheats enabled\", true);\n\nvoid MSG_PrioritiseEntitystateFields();\nvoid MSG_PrioritisePlayerStateFields();\n\nstatic void SV_FieldInfo_f()\n{\n\tMSG_PrioritiseEntitystateFields();\n\tMSG_PrioritisePlayerStateFields();\n}\n\n\/*\n================\nSV_MapRestart_f\n\nCompletely restarts a level, but doesn't send a new gamestate to the clients.\nThis allows fair starts with variable load times.\n================\n*\/\nstatic void SV_MapRestart_f()\n{\n\tint i;\n\tclient_t *client;\n\tbool denied;\n\tchar reason[ MAX_STRING_CHARS ];\n\tbool isBot;\n\n\t\/\/ make sure we aren't restarting twice in the same frame\n\tif ( com_frameTime == sv.serverId )\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ make sure server is running\n\tif ( !com_sv_running->integer )\n\t{\n\t\tLog::Notice( \"Server is not running.\\n\" );\n\t\treturn;\n\t}\n\n\t\/\/ check for changes in variables that can't just be restarted\n\t\/\/ check for maxclients change\n\tif ( sv_maxclients->modified )\n\t{\n\t\tchar mapname[ MAX_QPATH ];\n\t\tchar pakname[ MAX_OSPATH ];\n\n\t\tLog::Notice( \"sv_maxclients variable change — restarting.\\n\" );\n\t\t\/\/ restart the map the slow way\n\t\tQ_strncpyz( mapname, Cvar_VariableString( \"mapname\" ), sizeof( mapname ) );\n\t\tQ_strncpyz( pakname, Cvar_VariableString( \"pakname\" ), sizeof( pakname ) );\n\n\t\tSV_SpawnServer(pakname, mapname);\n\t\treturn;\n\t}\n\n\t\/\/ toggle the server bit so clients can detect that a\n\t\/\/ map_restart has happened\n\tsvs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT;\n\n\t\/\/ generate a new serverid\n\t\/\/ TTimo - don't update restartedserverId there, otherwise we won't deal correctly with multiple map_restart\n\tsv.serverId = com_frameTime;\n\tCvar_Set( \"sv_serverid\", va( \"%i\", sv.serverId ) );\n\n\t\/\/ reset all the VM data in place without changing memory allocation\n\t\/\/ note that we do NOT set sv.state = SS_LOADING, so configstrings that\n\t\/\/ had been changed from their default values will generate broadcast updates\n\tsv.state = serverState_t::SS_LOADING;\n\tsv.restarting = true;\n\n\tSV_RestartGameProgs();\n\n\t\/\/ run a few frames to allow everything to settle\n\tfor ( i = 0; i < GAME_INIT_FRAMES; i++ )\n\t{\n\t\tgvm.GameRunFrame( sv.time );\n\t\tsvs.time += FRAMETIME;\n\t\tsv.time += FRAMETIME;\n\t}\n\n\t\/\/ create a baseline for more efficient communications\n\t\/\/ Gordon: meh, this won't work here as the client doesn't know it has happened\n\/\/ SV_CreateBaseline ();\n\n\tsv.state = serverState_t::SS_GAME;\n\tsv.restarting = false;\n\n\t\/\/ connect and begin all the clients\n\tfor ( i = 0; i < sv_maxclients->integer; i++ )\n\t{\n\t\tclient = &svs.clients[ i ];\n\n\t\t\/\/ send the new gamestate to all connected clients\n\t\tif ( client->state < clientState_t::CS_CONNECTED )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tisBot = SV_IsBot(client);\n\n\t\t\/\/ add the map_restart command\n\t\tSV_AddServerCommand( client, \"map_restart\\n\" );\n\n\t\t\/\/ connect the client again, without the firstTime flag\n\t\tdenied = gvm.GameClientConnect( reason, sizeof( reason ), i, false, isBot );\n\n\t\tif ( denied )\n\t\t{\n\t\t\t\/\/ this generally shouldn't happen, because the client\n\t\t\t\/\/ was connected before the level change\n\t\t\tSV_DropClient( client, reason );\n\n\t\t\tif ( !isBot )\n\t\t\t{\n\t\t\t\tLog::Notice( \"SV_MapRestart_f: dropped client %i: denied!\\n\", i );\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tclient->state = clientState_t::CS_ACTIVE;\n\n\t\tSV_ClientEnterWorld( client, &client->lastUsercmd );\n\t}\n\n\t\/\/ run another frame to allow things to look at all the players\n\tgvm.GameRunFrame( sv.time );\n\tsvs.time += FRAMETIME;\n\tsv.time += FRAMETIME;\n}\n\nclass StatusCmd: public Cmd::StaticCmd\n{\npublic:\n\tStatusCmd():\n\t\tStaticCmd(\"status\", Cmd::SYSTEM, \"Shows a table with server and player information\")\n\t{}\n\n\tvoid Run(const Cmd::Args&) const override\n\t{\n\t\t\/\/ make sure server is running\n\t\tif ( !com_sv_running->integer )\n\t\t{\n\t\t\tLog::Notice( \"Server is not running.\\n\" );\n\t\t\treturn;\n\t\t}\n\n\t\tfloat cpu = ( svs.stats.latched_active + svs.stats.latched_idle );\n\n\t\tif ( cpu )\n\t\t{\n\t\t\tcpu = 100 * svs.stats.latched_active \/ cpu;\n\t\t}\n\n\t\tauto players = std::count_if(\n\t\t\tsvs.clients,\n\t\t\tsvs.clients+sv_maxclients->integer,\n\t\t\t[](const client_t& cl) {\n\t\t\t\treturn cl.state != clientState_t::CS_FREE;\n\t\t\t}\n\t\t);\n\n\t\tstd::string time_string;\n\t\tauto seconds = svs.time \/ 1000 % 60;\n\t\tauto minutes = svs.time \/ 1000 \/ 60 % 60;\n\t\tif ( auto hours = svs.time \/ 1000 \/ 60 \/ 60 \/ 60 )\n\t\t{\n\t\t\ttime_string = Str::Format(\"%02d:\", hours);\n\t\t}\n\t\ttime_string += Str::Format(\"%02d:%02d\", minutes, seconds);\n\n\t\tPrint(\n\t\t\t\"(begin server status)\\n\"\n\t\t\t\"hostname: %s\\n\"\n\t\t\t\"version: %s\\n\"\n\t\t\t\"protocol: %d\\n\"\n\t\t\t\"cpu: %.0f%%\\n\"\n\t\t\t\"time: %s\\n\"\n\t\t\t\"map: %s\\n\"\n\t\t\t\"players: %d \/ %d\\n\"\n\t\t\t\"num score connection address port name\\n\"\n\t\t\t\"--- ----- ---------- ---------------------- ------ ----\",\n\t\t\tsv_hostname->string,\n\t\t\tQ3_VERSION \" on \" Q3_ENGINE,\n\t\t\tPROTOCOL_VERSION,\n\t\t\tcpu,\n\t\t\ttime_string,\n\t\t\tsv_mapname->string,\n\t\t\tplayers,\n\t\t\tsv_maxclients->integer\n\t\t);\n\n\t\tfor ( int i = 0; i < sv_maxclients->integer; i++ )\n\t\t{\n\t\t\tconst client_t& cl = svs.clients[i];\n\t\t\tif ( cl.state == clientState_t::CS_FREE )\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstd::string connection;\n\n\t\t\tif ( cl.state == clientState_t::CS_CONNECTED )\n\t\t\t{\n\t\t\t\tconnection = \"CONNECTED\";\n\t\t\t}\n\t\t\telse if ( cl.state == clientState_t::CS_ZOMBIE )\n\t\t\t{\n\t\t\t\tconnection = \"ZOMBIE\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconnection = std::to_string(cl.ping);\n\t\t\t\tif ( connection.size() > 10 )\n\t\t\t\t{\n\t\t\t\t\tconnection = \"ERROR\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tOpaquePlayerState* ps = SV_GameClientNum( i );\n\n\t\t\tconst char *address = NET_AdrToString( cl.netchan.remoteAddress );\n\n\t\t\tPrint(\n\t\t\t\t\"%3i %5i %10s %-22s %-6i %s\",\n\t\t\t\ti,\n\t\t\t\tps->persistant[ PERS_SCORE ],\n\t\t\t\tconnection,\n\t\t\t\taddress,\n\t\t\t\tcl.netchan.qport,\n\t\t\t\tcl.name\n\t\t\t);\n\t\t}\n\n\t\tPrint( \"(end server status)\" );\n\t}\n};\nstatic StatusCmd StatusCmdRegistration;\n\n\n\/*\n==================\nSV_Heartbeat_f\n\nAlso called by SV_DropClient, SV_DirectConnect, and SV_SpawnServer\n==================\n*\/\nvoid SV_Heartbeat_f()\n{\n\tsvs.nextHeartbeatTime = -9999999;\n}\n\n\/*\n===========\nSV_Serverinfo_f\n\nExamine the serverinfo string\n===========\n*\/\nstatic void SV_Serverinfo_f()\n{\n\t\/\/ make sure server is running\n\tif ( !com_sv_running->integer )\n\t{\n\t\tLog::Notice( \"Server is not running.\\n\" );\n\t\treturn;\n\t}\n\n\tLog::Notice( \"Server info settings:\\n\" );\n\tInfo_Print( Cvar_InfoString( CVAR_SERVERINFO, false ) );\n}\n\n\/*\n===========\nSV_Systeminfo_f\n\nExamine the systeminfo string\n===========\n*\/\nstatic void SV_Systeminfo_f()\n{\n\t\/\/ make sure server is running\n\tif ( !com_sv_running->integer )\n\t{\n\t\tLog::Notice( \"Server is not running.\\n\" );\n\t\treturn;\n\t}\n\n\tLog::Notice( \"System info settings:\\n\" );\n\tInfo_Print( Cvar_InfoString( CVAR_SYSTEMINFO, false ) );\n}\n\nclass ListMapsCmd: public Cmd::StaticCmd\n{\npublic:\n\tListMapsCmd():\n\t\tStaticCmd(\"listmaps\", Cmd::SYSTEM, \"Lists all maps available to the server\")\n\t{}\n\n\tvoid Run(const Cmd::Args&) const override\n\t{\n\t\tauto maps = FS::GetAvailableMaps();\n\n\t\tPrint(\"Listing %d maps:\", maps.size());\n\n\t\tfor ( const auto& map: maps )\n\t\t{\n\t\t\tPrint(map.c_str());\n\t\t}\n\t}\n};\n\n#if BUILD_SERVER\nstatic ListMapsCmd ListMapsCmdRegistration;\n#endif\n\n\/*\n==================\nSV_AddOperatorCommands\n==================\n*\/\nvoid SV_AddOperatorCommands()\n{\n\tif ( com_sv_running->integer )\n\t{\n\t\t\/\/ These commands should only be available while the server is running.\n\t\tCmd_AddCommand( \"fieldinfo\", SV_FieldInfo_f );\n\t\tCmd_AddCommand( \"heartbeat\", SV_Heartbeat_f );\n\t\tCmd_AddCommand( \"map_restart\", SV_MapRestart_f );\n\t\tCmd_AddCommand( \"serverinfo\", SV_Serverinfo_f );\n\t\tCmd_AddCommand( \"systeminfo\", SV_Systeminfo_f );\n\t}\n}\n\n\/*\n==================\nSV_RemoveOperatorCommands\n==================\n*\/\nvoid SV_RemoveOperatorCommands()\n{\n\tCmd_RemoveCommand( \"fieldinfo\" );\n\tCmd_RemoveCommand( \"heartbeat\" );\n\tCmd_RemoveCommand( \"map_restart\" );\n\tCmd_RemoveCommand( \"serverinfo\" );\n\tCmd_RemoveCommand( \"status\" );\n\tCmd_RemoveCommand( \"systeminfo\" );\n}\n<commit_msg>[server] Do not truncate cpu stats from double to float<commit_after>\/*\n===========================================================================\n\nDaemon GPL Source Code\nCopyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.\n\nThis file is part of the Daemon GPL Source Code (Daemon Source Code).\n\nDaemon Source Code is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nDaemon Source Code is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon Source Code. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nIn addition, the Daemon Source Code is also subject to certain additional terms.\nYou should have received a copy of these additional terms immediately following the\nterms and conditions of the GNU General Public License which accompanied the Daemon\nSource Code. If not, please request a copy in writing from id Software at the address\nbelow.\n\nIf you have questions concerning this license or the applicable additional terms, you\nmay contact in writing id Software LLC, c\/o ZeniMax Media Inc., Suite 120, Rockville,\nMaryland 20850 USA.\n\n===========================================================================\n*\/\n\n#include \"server.h\"\n#include \"framework\/CvarSystem.h\"\n\n\/*\n===============================================================================\n\nOPERATOR CONSOLE ONLY COMMANDS\n\nThese commands can only be entered from stdin or by a remote operator datagram\n===============================================================================\n*\/\n\nclass MapCmd: public Cmd::StaticCmd {\n public:\n MapCmd(Str::StringRef name, Str::StringRef description, bool cheat):\n Cmd::StaticCmd(name, Cmd::SYSTEM, description), cheat(cheat) {\n }\n\n void Run(const Cmd::Args& args) const override {\n if (args.Argc() < 2) {\n PrintUsage(args, \"<mapname> (layoutname)\", \"loads a new map\");\n return;\n }\n\n const std::string& mapName = args.Argv(1);\n\n \/\/Make sure the map exists to avoid typos that would kill the game\n FS::GetAvailableMaps();\n const auto loadedPakInfo = FS::PakPath::LocateFile(Str::Format(\"maps\/%s.bsp\", mapName));\n if (!loadedPakInfo) {\n Print(\"Can't find map %s\", mapName);\n return;\n }\n\n \/\/Gets the layout list from the command but do not override if there is nothing\n std::string layouts = args.ConcatArgs(2);\n if (not layouts.empty()) {\n Cvar::SetValue(\"g_layouts\", layouts);\n }\n\n Cvar::SetValueForce(\"sv_cheats\", cheat ? \"1\" : \"0\");\n SV_SpawnServer(loadedPakInfo->name, mapName);\n }\n\n Cmd::CompletionResult Complete(int argNum, const Cmd::Args& args, Str::StringRef prefix) const override {\n if (argNum == 1) {\n Cmd::CompletionResult out;\n for (auto& map: FS::GetAvailableMaps()) {\n if (Str::IsPrefix(prefix, map))\n out.push_back({map, \"\"});\n }\n return out;\n } else if (argNum > 1) {\n return FS::HomePath::CompleteFilename(prefix, \"game\/layouts\/\" + args.Argv(1), \".dat\", false, true);\n }\n\n return {};\n }\n\n private:\n bool cheat;\n};\nstatic MapCmd MapCmdRegistration(\"map\", \"starts a new map\", false);\nstatic MapCmd DevmapCmdRegistration(\"devmap\", \"starts a new map with cheats enabled\", true);\n\nvoid MSG_PrioritiseEntitystateFields();\nvoid MSG_PrioritisePlayerStateFields();\n\nstatic void SV_FieldInfo_f()\n{\n\tMSG_PrioritiseEntitystateFields();\n\tMSG_PrioritisePlayerStateFields();\n}\n\n\/*\n================\nSV_MapRestart_f\n\nCompletely restarts a level, but doesn't send a new gamestate to the clients.\nThis allows fair starts with variable load times.\n================\n*\/\nstatic void SV_MapRestart_f()\n{\n\tint i;\n\tclient_t *client;\n\tbool denied;\n\tchar reason[ MAX_STRING_CHARS ];\n\tbool isBot;\n\n\t\/\/ make sure we aren't restarting twice in the same frame\n\tif ( com_frameTime == sv.serverId )\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ make sure server is running\n\tif ( !com_sv_running->integer )\n\t{\n\t\tLog::Notice( \"Server is not running.\\n\" );\n\t\treturn;\n\t}\n\n\t\/\/ check for changes in variables that can't just be restarted\n\t\/\/ check for maxclients change\n\tif ( sv_maxclients->modified )\n\t{\n\t\tchar mapname[ MAX_QPATH ];\n\t\tchar pakname[ MAX_OSPATH ];\n\n\t\tLog::Notice( \"sv_maxclients variable change — restarting.\\n\" );\n\t\t\/\/ restart the map the slow way\n\t\tQ_strncpyz( mapname, Cvar_VariableString( \"mapname\" ), sizeof( mapname ) );\n\t\tQ_strncpyz( pakname, Cvar_VariableString( \"pakname\" ), sizeof( pakname ) );\n\n\t\tSV_SpawnServer(pakname, mapname);\n\t\treturn;\n\t}\n\n\t\/\/ toggle the server bit so clients can detect that a\n\t\/\/ map_restart has happened\n\tsvs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT;\n\n\t\/\/ generate a new serverid\n\t\/\/ TTimo - don't update restartedserverId there, otherwise we won't deal correctly with multiple map_restart\n\tsv.serverId = com_frameTime;\n\tCvar_Set( \"sv_serverid\", va( \"%i\", sv.serverId ) );\n\n\t\/\/ reset all the VM data in place without changing memory allocation\n\t\/\/ note that we do NOT set sv.state = SS_LOADING, so configstrings that\n\t\/\/ had been changed from their default values will generate broadcast updates\n\tsv.state = serverState_t::SS_LOADING;\n\tsv.restarting = true;\n\n\tSV_RestartGameProgs();\n\n\t\/\/ run a few frames to allow everything to settle\n\tfor ( i = 0; i < GAME_INIT_FRAMES; i++ )\n\t{\n\t\tgvm.GameRunFrame( sv.time );\n\t\tsvs.time += FRAMETIME;\n\t\tsv.time += FRAMETIME;\n\t}\n\n\t\/\/ create a baseline for more efficient communications\n\t\/\/ Gordon: meh, this won't work here as the client doesn't know it has happened\n\/\/ SV_CreateBaseline ();\n\n\tsv.state = serverState_t::SS_GAME;\n\tsv.restarting = false;\n\n\t\/\/ connect and begin all the clients\n\tfor ( i = 0; i < sv_maxclients->integer; i++ )\n\t{\n\t\tclient = &svs.clients[ i ];\n\n\t\t\/\/ send the new gamestate to all connected clients\n\t\tif ( client->state < clientState_t::CS_CONNECTED )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tisBot = SV_IsBot(client);\n\n\t\t\/\/ add the map_restart command\n\t\tSV_AddServerCommand( client, \"map_restart\\n\" );\n\n\t\t\/\/ connect the client again, without the firstTime flag\n\t\tdenied = gvm.GameClientConnect( reason, sizeof( reason ), i, false, isBot );\n\n\t\tif ( denied )\n\t\t{\n\t\t\t\/\/ this generally shouldn't happen, because the client\n\t\t\t\/\/ was connected before the level change\n\t\t\tSV_DropClient( client, reason );\n\n\t\t\tif ( !isBot )\n\t\t\t{\n\t\t\t\tLog::Notice( \"SV_MapRestart_f: dropped client %i: denied!\\n\", i );\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tclient->state = clientState_t::CS_ACTIVE;\n\n\t\tSV_ClientEnterWorld( client, &client->lastUsercmd );\n\t}\n\n\t\/\/ run another frame to allow things to look at all the players\n\tgvm.GameRunFrame( sv.time );\n\tsvs.time += FRAMETIME;\n\tsv.time += FRAMETIME;\n}\n\nclass StatusCmd: public Cmd::StaticCmd\n{\npublic:\n\tStatusCmd():\n\t\tStaticCmd(\"status\", Cmd::SYSTEM, \"Shows a table with server and player information\")\n\t{}\n\n\tvoid Run(const Cmd::Args&) const override\n\t{\n\t\t\/\/ make sure server is running\n\t\tif ( !com_sv_running->integer )\n\t\t{\n\t\t\tLog::Notice( \"Server is not running.\\n\" );\n\t\t\treturn;\n\t\t}\n\n\t\tdouble cpu = ( svs.stats.latched_active + svs.stats.latched_idle );\n\n\t\tif ( cpu )\n\t\t{\n\t\t\tcpu = 100 * svs.stats.latched_active \/ cpu;\n\t\t}\n\n\t\tauto players = std::count_if(\n\t\t\tsvs.clients,\n\t\t\tsvs.clients+sv_maxclients->integer,\n\t\t\t[](const client_t& cl) {\n\t\t\t\treturn cl.state != clientState_t::CS_FREE;\n\t\t\t}\n\t\t);\n\n\t\tstd::string time_string;\n\t\tauto seconds = svs.time \/ 1000 % 60;\n\t\tauto minutes = svs.time \/ 1000 \/ 60 % 60;\n\t\tif ( auto hours = svs.time \/ 1000 \/ 60 \/ 60 \/ 60 )\n\t\t{\n\t\t\ttime_string = Str::Format(\"%02d:\", hours);\n\t\t}\n\t\ttime_string += Str::Format(\"%02d:%02d\", minutes, seconds);\n\n\t\tPrint(\n\t\t\t\"(begin server status)\\n\"\n\t\t\t\"hostname: %s\\n\"\n\t\t\t\"version: %s\\n\"\n\t\t\t\"protocol: %d\\n\"\n\t\t\t\"cpu: %.0f%%\\n\"\n\t\t\t\"time: %s\\n\"\n\t\t\t\"map: %s\\n\"\n\t\t\t\"players: %d \/ %d\\n\"\n\t\t\t\"num score connection address port name\\n\"\n\t\t\t\"--- ----- ---------- ---------------------- ------ ----\",\n\t\t\tsv_hostname->string,\n\t\t\tQ3_VERSION \" on \" Q3_ENGINE,\n\t\t\tPROTOCOL_VERSION,\n\t\t\tcpu,\n\t\t\ttime_string,\n\t\t\tsv_mapname->string,\n\t\t\tplayers,\n\t\t\tsv_maxclients->integer\n\t\t);\n\n\t\tfor ( int i = 0; i < sv_maxclients->integer; i++ )\n\t\t{\n\t\t\tconst client_t& cl = svs.clients[i];\n\t\t\tif ( cl.state == clientState_t::CS_FREE )\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstd::string connection;\n\n\t\t\tif ( cl.state == clientState_t::CS_CONNECTED )\n\t\t\t{\n\t\t\t\tconnection = \"CONNECTED\";\n\t\t\t}\n\t\t\telse if ( cl.state == clientState_t::CS_ZOMBIE )\n\t\t\t{\n\t\t\t\tconnection = \"ZOMBIE\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconnection = std::to_string(cl.ping);\n\t\t\t\tif ( connection.size() > 10 )\n\t\t\t\t{\n\t\t\t\t\tconnection = \"ERROR\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tOpaquePlayerState* ps = SV_GameClientNum( i );\n\n\t\t\tconst char *address = NET_AdrToString( cl.netchan.remoteAddress );\n\n\t\t\tPrint(\n\t\t\t\t\"%3i %5i %10s %-22s %-6i %s\",\n\t\t\t\ti,\n\t\t\t\tps->persistant[ PERS_SCORE ],\n\t\t\t\tconnection,\n\t\t\t\taddress,\n\t\t\t\tcl.netchan.qport,\n\t\t\t\tcl.name\n\t\t\t);\n\t\t}\n\n\t\tPrint( \"(end server status)\" );\n\t}\n};\nstatic StatusCmd StatusCmdRegistration;\n\n\n\/*\n==================\nSV_Heartbeat_f\n\nAlso called by SV_DropClient, SV_DirectConnect, and SV_SpawnServer\n==================\n*\/\nvoid SV_Heartbeat_f()\n{\n\tsvs.nextHeartbeatTime = -9999999;\n}\n\n\/*\n===========\nSV_Serverinfo_f\n\nExamine the serverinfo string\n===========\n*\/\nstatic void SV_Serverinfo_f()\n{\n\t\/\/ make sure server is running\n\tif ( !com_sv_running->integer )\n\t{\n\t\tLog::Notice( \"Server is not running.\\n\" );\n\t\treturn;\n\t}\n\n\tLog::Notice( \"Server info settings:\\n\" );\n\tInfo_Print( Cvar_InfoString( CVAR_SERVERINFO, false ) );\n}\n\n\/*\n===========\nSV_Systeminfo_f\n\nExamine the systeminfo string\n===========\n*\/\nstatic void SV_Systeminfo_f()\n{\n\t\/\/ make sure server is running\n\tif ( !com_sv_running->integer )\n\t{\n\t\tLog::Notice( \"Server is not running.\\n\" );\n\t\treturn;\n\t}\n\n\tLog::Notice( \"System info settings:\\n\" );\n\tInfo_Print( Cvar_InfoString( CVAR_SYSTEMINFO, false ) );\n}\n\nclass ListMapsCmd: public Cmd::StaticCmd\n{\npublic:\n\tListMapsCmd():\n\t\tStaticCmd(\"listmaps\", Cmd::SYSTEM, \"Lists all maps available to the server\")\n\t{}\n\n\tvoid Run(const Cmd::Args&) const override\n\t{\n\t\tauto maps = FS::GetAvailableMaps();\n\n\t\tPrint(\"Listing %d maps:\", maps.size());\n\n\t\tfor ( const auto& map: maps )\n\t\t{\n\t\t\tPrint(map.c_str());\n\t\t}\n\t}\n};\n\n#if BUILD_SERVER\nstatic ListMapsCmd ListMapsCmdRegistration;\n#endif\n\n\/*\n==================\nSV_AddOperatorCommands\n==================\n*\/\nvoid SV_AddOperatorCommands()\n{\n\tif ( com_sv_running->integer )\n\t{\n\t\t\/\/ These commands should only be available while the server is running.\n\t\tCmd_AddCommand( \"fieldinfo\", SV_FieldInfo_f );\n\t\tCmd_AddCommand( \"heartbeat\", SV_Heartbeat_f );\n\t\tCmd_AddCommand( \"map_restart\", SV_MapRestart_f );\n\t\tCmd_AddCommand( \"serverinfo\", SV_Serverinfo_f );\n\t\tCmd_AddCommand( \"systeminfo\", SV_Systeminfo_f );\n\t}\n}\n\n\/*\n==================\nSV_RemoveOperatorCommands\n==================\n*\/\nvoid SV_RemoveOperatorCommands()\n{\n\tCmd_RemoveCommand( \"fieldinfo\" );\n\tCmd_RemoveCommand( \"heartbeat\" );\n\tCmd_RemoveCommand( \"map_restart\" );\n\tCmd_RemoveCommand( \"serverinfo\" );\n\tCmd_RemoveCommand( \"status\" );\n\tCmd_RemoveCommand( \"systeminfo\" );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved\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 \"extension\/widget\/widget.h\"\n\n#include <list>\n#include <memory>\n#include <map>\n#include <vector>\n\n#include \"extension\/xwalk\/XW_Extension.h\"\n#include \"extension\/xwalk\/XW_Extension_EntryPoints.h\"\n#include \"extension\/xwalk\/XW_Extension_Permissions.h\"\n#include \"extension\/xwalk\/XW_Extension_Runtime.h\"\n#include \"extension\/xwalk\/XW_Extension_SyncMessage.h\"\n\n#include \"extension\/widget\/picojson.h\"\n#include \"common\/logger.h\"\n#include \"common\/app_db.h\"\n#include \"common\/application_data.h\"\n#include \"common\/locale_manager.h\"\n#include \"common\/string_utils.h\"\n\nXW_Extension g_xw_extension = 0;\nstd::string g_appid;\nstd::unique_ptr<wrt::ApplicationData> g_appdata;\nconst XW_CoreInterface* g_core = NULL;\nconst XW_MessagingInterface* g_messaging = NULL;\nconst XW_Internal_SyncMessagingInterface* g_sync_messaging = NULL;\nconst XW_Internal_EntryPointsInterface* g_entry_points = NULL;\nconst XW_Internal_RuntimeInterface* g_runtime = NULL;\nextern const char kSource_widget_api[];\n\ntypedef void (*CmdHandler)(const picojson::value& args, picojson::object* out);\n\nstatic void InitHandler(const picojson::value& args, picojson::object* out);\nstatic void KeyHandler(const picojson::value& args, picojson::object* out);\nstatic void GetItemHandler(const picojson::value& args,\n picojson::object* out);\nstatic void LengthHandler(const picojson::value& args,\n picojson::object* out);\nstatic void ClearHandler(const picojson::value& args,\n picojson::object* out);\nstatic void SetItemHandler(const picojson::value& args,\n picojson::object* out);\nstatic void RemoveHandler(const picojson::value& args,\n picojson::object* out);\n\nstd::map<std::string, CmdHandler> g_handler = {\n {\"init\", InitHandler},\n {\"key\", KeyHandler},\n {\"length\", LengthHandler},\n {\"clear\", ClearHandler},\n {\"getItem\", GetItemHandler},\n {\"setItem\", SetItemHandler},\n {\"removeItem\", RemoveHandler},\n};\n\n\nstatic void HandleMessage(XW_Instance instance,\n const char* message,\n bool sync);\n\nextern \"C\" int32_t XW_Initialize(XW_Extension extension,\n XW_GetInterface get_interface) {\n g_xw_extension = extension;\n g_core = reinterpret_cast<const XW_CoreInterface*>(\n get_interface(XW_CORE_INTERFACE));\n if (!g_core) {\n LOGGER(ERROR)\n << \"Can't initialize extension: error getting Core interface.\";\n return XW_ERROR;\n }\n\n g_messaging = reinterpret_cast<const XW_MessagingInterface*>(\n get_interface(XW_MESSAGING_INTERFACE));\n if (!g_messaging) {\n LOGGER(ERROR)\n << \"Can't initialize extension: error getting Messaging interface.\";\n return XW_ERROR;\n }\n\n g_sync_messaging =\n reinterpret_cast<const XW_Internal_SyncMessagingInterface*>(\n get_interface(XW_INTERNAL_SYNC_MESSAGING_INTERFACE));\n if (!g_sync_messaging) {\n LOGGER(ERROR)\n << \"Can't initialize extension: \"\n << \"error getting SyncMessaging interface.\";\n return XW_ERROR;\n }\n\n g_entry_points = reinterpret_cast<const XW_Internal_EntryPointsInterface*>(\n get_interface(XW_INTERNAL_ENTRY_POINTS_INTERFACE));\n if (!g_entry_points) {\n LOGGER(ERROR)\n << \"NOTE: Entry points interface not available in this version \"\n << \"of Crosswalk, ignoring entry point data for extensions.\\n\";\n return XW_ERROR;\n }\n\n g_runtime = reinterpret_cast<const XW_Internal_RuntimeInterface*>(\n get_interface(XW_INTERNAL_RUNTIME_INTERFACE));\n if (!g_runtime) {\n LOGGER(ERROR)\n << \"NOTE: runtime interface not available in this version \"\n << \"of Crosswalk, ignoring runtime variables for extensions.\\n\";\n return XW_ERROR;\n }\n\n std::vector<char> res(256, 0);\n g_runtime->GetRuntimeVariableString(extension, \"app_id\", &res[0], 256);\n g_appid = std::string(res.begin(), res.end());\n if (g_appid.at(0) == '\"') {\n g_appid = g_appid.substr(1, g_appid.size()-2);\n }\n\n g_core->RegisterInstanceCallbacks(\n g_xw_extension,\n [](XW_Instance \/*instance*\/){\n if (g_appdata.get() == NULL) {\n g_appdata.reset(new wrt::ApplicationData(g_appid));\n }\n wrt::Widget::GetInstance()->Initialize(g_appdata.get());\n },\n NULL);\n\n g_messaging->Register(g_xw_extension, [](XW_Instance instance,\n const char* message) {\n HandleMessage(instance, message, false);\n });\n g_sync_messaging->Register(g_xw_extension, [](XW_Instance instance,\n const char* message) {\n HandleMessage(instance, message, true);\n });\n\n g_core->SetExtensionName(g_xw_extension, \"Widget\");\n const char* entry_points[] = {\"widget\", NULL};\n g_entry_points->SetExtraJSEntryPoints(g_xw_extension, entry_points);\n g_core->SetJavaScriptAPI(g_xw_extension, kSource_widget_api);\n\n return XW_OK;\n}\n\nstatic void InitHandler(const picojson::value& \/*args*\/,\n picojson::object* out) {\n picojson::value result = picojson::value(picojson::object());\n picojson::object& obj = result.get<picojson::object>();\n\n auto widget_info = g_appdata->widget_info();\n if (widget_info.get() == NULL) {\n out->insert(std::make_pair(\"status\", picojson::value(\"error\")));\n return;\n }\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n\n wrt::LocaleManager locale_manager;\n if (!widget_info->default_locale().empty()) {\n locale_manager.SetDefaultLocale(widget_info->default_locale());\n }\n\n \/\/ TODO(sngn.lee): should be returned localized string\n obj[\"author\"] = picojson::value(widget_info->author());\n obj[\"description\"] = picojson::value(\n locale_manager.GetLocalizedString(widget_info->description_set()));\n obj[\"name\"] = picojson::value(\n locale_manager.GetLocalizedString(widget_info->name_set()));\n obj[\"shortName\"] = picojson::value(\n locale_manager.GetLocalizedString(widget_info->short_name_set()));\n obj[\"version\"] = picojson::value(widget_info->version());\n obj[\"id\"] = picojson::value(widget_info->id());\n obj[\"authorEmail\"] = picojson::value(widget_info->author_email());\n obj[\"authorHref\"] = picojson::value(widget_info->author_href());\n obj[\"height\"] = picojson::value(static_cast<double>(widget_info->height()));\n obj[\"width\"] = picojson::value(static_cast<double>(widget_info->width()));\n\n out->insert(std::make_pair(\"result\", result));\n}\n\nstatic void KeyHandler(const picojson::value& args, picojson::object* out) {\n int idx = static_cast<int>(args.get(\"idx\").get<double>());\n std::string key;\n if (!wrt::Widget::GetInstance()->Key(idx, &key)) {\n out->insert(std::make_pair(\"status\", picojson::value(\"error\")));\n return;\n }\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n out->insert(std::make_pair(\"result\", picojson::value(key)));\n}\n\nstatic void GetItemHandler(const picojson::value& args,\n picojson::object* out) {\n const std::string& key = args.get(\"key\").get<std::string>();\n std::string value;\n if (!wrt::Widget::GetInstance()->GetItem(key, &value)) {\n out->insert(std::make_pair(\"status\", picojson::value(\"error\")));\n return;\n }\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n out->insert(std::make_pair(\"result\", picojson::value(value)));\n}\n\nstatic void LengthHandler(const picojson::value& \/*args*\/,\n picojson::object* out) {\n int length = wrt::Widget::GetInstance()->Length();\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n out->insert(\n std::make_pair(\"result\", picojson::value(static_cast<double>(length))));\n}\n\nstatic void ClearHandler(const picojson::value& \/*args*\/,\n picojson::object* out) {\n wrt::Widget::GetInstance()->Clear();\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n}\n\nstatic void SetItemHandler(const picojson::value& args,\n picojson::object* out) {\n const std::string& key = args.get(\"key\").get<std::string>();\n const std::string& value = args.get(\"value\").get<std::string>();\n std::string oldvalue;\n if (wrt::Widget::GetInstance()->GetItem(key, &oldvalue)) {\n out->insert(std::make_pair(\"result\", picojson::value(oldvalue)));\n } else {\n out->insert(std::make_pair(\"result\", picojson::value()));\n }\n wrt::Widget::GetInstance()->SetItem(key, value);\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n}\n\nstatic void RemoveHandler(const picojson::value& args,\n picojson::object* out) {\n const std::string& key = args.get(\"key\").get<std::string>();\n std::string oldvalue;\n if (wrt::Widget::GetInstance()->GetItem(key, &oldvalue)) {\n out->insert(std::make_pair(\"result\", picojson::value(oldvalue)));\n } else {\n out->insert(std::make_pair(\"result\", picojson::value()));\n }\n wrt::Widget::GetInstance()->RemoveItem(key);\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n}\n\n\nstatic void HandleMessage(XW_Instance instance,\n const char* message,\n bool sync) {\n picojson::value value;\n std::string err;\n picojson::parse(value, message, message + strlen(message), &err);\n if (!err.empty()) {\n LOGGER(ERROR) << \"Ignoring message. \" << err;\n return;\n }\n\n if (!value.is<picojson::object>()) {\n LOGGER(ERROR) << \"Ignoring message. It is not an object.\";\n return;\n }\n\n std::string cmd = value.get(\"cmd\").to_str();\n \/\/ check for args in JSON message\n const picojson::value& args = value.get(\"args\");\n picojson::value result = picojson::value(picojson::object());\n\n auto handler = g_handler.find(cmd);\n if (handler != g_handler.end()) {\n handler->second(args, &result.get<picojson::object>());\n } else {\n result.get<picojson::object>().insert(\n std::make_pair(\"status\", picojson::value(\"error\")));\n }\n\n if (sync) {\n g_sync_messaging->SetSyncReply(instance, result.serialize().c_str());\n }\n}\n\nnamespace wrt {\n\nnamespace {\n const char* kDbInitedCheckKey = \"__WRT_DB_INITED__\";\n const char* kDBPublicSection = \"public\";\n const char* kDBPrivateSection = \"private\";\n} \/\/ namespace\n\n\nWidget* Widget::GetInstance() {\n static Widget instance;\n return &instance;\n}\n\nWidget::Widget() {\n}\nWidget::~Widget() {\n}\n\nvoid Widget::Initialize(const ApplicationData* appdata) {\n AppDB* db = AppDB::GetInstance();\n if (db->HasKey(kDBPrivateSection, kDbInitedCheckKey))\n return;\n if (appdata->widget_info() == NULL)\n return;\n\n auto preferences = appdata->widget_info()->preferences();\n auto it = preferences.begin();\n for ( ; it != preferences.end(); ++it) {\n db->Set(kDBPublicSection,\n (*it)->Name(),\n (*it)->Value());\n }\n db->Set(kDBPrivateSection, kDbInitedCheckKey, \"true\");\n}\n\nint Widget::Length() {\n AppDB* db = AppDB::GetInstance();\n std::list<std::string> list;\n db->GetKeys(kDBPublicSection, &list);\n return list.size();\n}\n\nbool Widget::Key(int idx, std::string* key) {\n AppDB* db = AppDB::GetInstance();\n std::list<std::string> list;\n db->GetKeys(kDBPublicSection, &list);\n\n auto it = list.begin();\n for ( ; it != list.end() && idx >= 0; ++it) {\n if (idx == 0) {\n *key = *it;\n return true;\n }\n idx--;\n }\n return false;\n}\n\nbool Widget::GetItem(const std::string& key, std::string* value) {\n AppDB* db = AppDB::GetInstance();\n if (!db->HasKey(kDBPublicSection, key))\n return false;\n *value = db->Get(kDBPublicSection, key);\n return true;\n}\n\nbool Widget::SetItem(const std::string& key, const std::string& value) {\n AppDB* db = AppDB::GetInstance();\n db->Set(kDBPublicSection, key, value);\n return true;\n}\n\nbool Widget::RemoveItem(const std::string& key) {\n AppDB* db = AppDB::GetInstance();\n if (!db->HasKey(kDBPublicSection, key))\n return false;\n db->Remove(kDBPublicSection, key);\n return true;\n}\n\nvoid Widget::Clear() {\n AppDB* db = AppDB::GetInstance();\n std::list<std::string> list;\n db->GetKeys(kDBPublicSection, &list);\n auto it = list.begin();\n for ( ; it != list.end(); ++it) {\n db->Remove(kDBPublicSection, *it);\n }\n}\n\n} \/\/ namespace wrt\n<commit_msg>Widget API : Bug fix - App id quote related bug - Missing LoadManifestData bug<commit_after>\/*\n * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved\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 \"extension\/widget\/widget.h\"\n\n#include <list>\n#include <memory>\n#include <map>\n#include <vector>\n\n#include \"extension\/xwalk\/XW_Extension.h\"\n#include \"extension\/xwalk\/XW_Extension_EntryPoints.h\"\n#include \"extension\/xwalk\/XW_Extension_Permissions.h\"\n#include \"extension\/xwalk\/XW_Extension_Runtime.h\"\n#include \"extension\/xwalk\/XW_Extension_SyncMessage.h\"\n\n#include \"extension\/widget\/picojson.h\"\n#include \"common\/logger.h\"\n#include \"common\/app_db.h\"\n#include \"common\/application_data.h\"\n#include \"common\/locale_manager.h\"\n#include \"common\/string_utils.h\"\n\nXW_Extension g_xw_extension = 0;\nstd::string g_appid;\nstd::unique_ptr<wrt::ApplicationData> g_appdata;\nconst XW_CoreInterface* g_core = NULL;\nconst XW_MessagingInterface* g_messaging = NULL;\nconst XW_Internal_SyncMessagingInterface* g_sync_messaging = NULL;\nconst XW_Internal_EntryPointsInterface* g_entry_points = NULL;\nconst XW_Internal_RuntimeInterface* g_runtime = NULL;\nextern const char kSource_widget_api[];\n\ntypedef void (*CmdHandler)(const picojson::value& args, picojson::object* out);\n\nstatic void InitHandler(const picojson::value& args, picojson::object* out);\nstatic void KeyHandler(const picojson::value& args, picojson::object* out);\nstatic void GetItemHandler(const picojson::value& args,\n picojson::object* out);\nstatic void LengthHandler(const picojson::value& args,\n picojson::object* out);\nstatic void ClearHandler(const picojson::value& args,\n picojson::object* out);\nstatic void SetItemHandler(const picojson::value& args,\n picojson::object* out);\nstatic void RemoveHandler(const picojson::value& args,\n picojson::object* out);\n\nstd::map<std::string, CmdHandler> g_handler = {\n {\"init\", InitHandler},\n {\"key\", KeyHandler},\n {\"length\", LengthHandler},\n {\"clear\", ClearHandler},\n {\"getItem\", GetItemHandler},\n {\"setItem\", SetItemHandler},\n {\"removeItem\", RemoveHandler},\n};\n\n\nstatic void HandleMessage(XW_Instance instance,\n const char* message,\n bool sync);\n\nextern \"C\" int32_t XW_Initialize(XW_Extension extension,\n XW_GetInterface get_interface) {\n g_xw_extension = extension;\n g_core = reinterpret_cast<const XW_CoreInterface*>(\n get_interface(XW_CORE_INTERFACE));\n if (!g_core) {\n LOGGER(ERROR)\n << \"Can't initialize extension: error getting Core interface.\";\n return XW_ERROR;\n }\n\n g_messaging = reinterpret_cast<const XW_MessagingInterface*>(\n get_interface(XW_MESSAGING_INTERFACE));\n if (!g_messaging) {\n LOGGER(ERROR)\n << \"Can't initialize extension: error getting Messaging interface.\";\n return XW_ERROR;\n }\n\n g_sync_messaging =\n reinterpret_cast<const XW_Internal_SyncMessagingInterface*>(\n get_interface(XW_INTERNAL_SYNC_MESSAGING_INTERFACE));\n if (!g_sync_messaging) {\n LOGGER(ERROR)\n << \"Can't initialize extension: \"\n << \"error getting SyncMessaging interface.\";\n return XW_ERROR;\n }\n\n g_entry_points = reinterpret_cast<const XW_Internal_EntryPointsInterface*>(\n get_interface(XW_INTERNAL_ENTRY_POINTS_INTERFACE));\n if (!g_entry_points) {\n LOGGER(ERROR)\n << \"NOTE: Entry points interface not available in this version \"\n << \"of Crosswalk, ignoring entry point data for extensions.\\n\";\n return XW_ERROR;\n }\n\n g_runtime = reinterpret_cast<const XW_Internal_RuntimeInterface*>(\n get_interface(XW_INTERNAL_RUNTIME_INTERFACE));\n if (!g_runtime) {\n LOGGER(ERROR)\n << \"NOTE: runtime interface not available in this version \"\n << \"of Crosswalk, ignoring runtime variables for extensions.\\n\";\n return XW_ERROR;\n }\n\n std::vector<char> res(256, 0);\n g_runtime->GetRuntimeVariableString(extension, \"app_id\", &res[0], 256);\n g_appid = std::string(res.begin(), res.end());\n if (g_appid.at(0) == '\"') {\n g_appid = g_appid.substr(1, strlen(g_appid.c_str())-2);\n }\n\n g_core->RegisterInstanceCallbacks(\n g_xw_extension,\n [](XW_Instance \/*instance*\/){\n if (g_appdata.get() == NULL) {\n g_appdata.reset(new wrt::ApplicationData(g_appid));\n g_appdata->LoadManifestData();\n }\n wrt::Widget::GetInstance()->Initialize(g_appdata.get());\n },\n NULL);\n\n g_messaging->Register(g_xw_extension, [](XW_Instance instance,\n const char* message) {\n HandleMessage(instance, message, false);\n });\n g_sync_messaging->Register(g_xw_extension, [](XW_Instance instance,\n const char* message) {\n HandleMessage(instance, message, true);\n });\n\n g_core->SetExtensionName(g_xw_extension, \"Widget\");\n const char* entry_points[] = {\"widget\", NULL};\n g_entry_points->SetExtraJSEntryPoints(g_xw_extension, entry_points);\n g_core->SetJavaScriptAPI(g_xw_extension, kSource_widget_api);\n\n return XW_OK;\n}\n\nstatic void InitHandler(const picojson::value& \/*args*\/,\n picojson::object* out) {\n picojson::value result = picojson::value(picojson::object());\n picojson::object& obj = result.get<picojson::object>();\n\n auto widget_info = g_appdata->widget_info();\n if (widget_info.get() == NULL) {\n out->insert(std::make_pair(\"status\", picojson::value(\"error\")));\n return;\n }\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n\n wrt::LocaleManager locale_manager;\n if (!widget_info->default_locale().empty()) {\n locale_manager.SetDefaultLocale(widget_info->default_locale());\n }\n\n \/\/ TODO(sngn.lee): should be returned localized string\n obj[\"author\"] = picojson::value(widget_info->author());\n obj[\"description\"] = picojson::value(\n locale_manager.GetLocalizedString(widget_info->description_set()));\n obj[\"name\"] = picojson::value(\n locale_manager.GetLocalizedString(widget_info->name_set()));\n obj[\"shortName\"] = picojson::value(\n locale_manager.GetLocalizedString(widget_info->short_name_set()));\n obj[\"version\"] = picojson::value(widget_info->version());\n obj[\"id\"] = picojson::value(widget_info->id());\n obj[\"authorEmail\"] = picojson::value(widget_info->author_email());\n obj[\"authorHref\"] = picojson::value(widget_info->author_href());\n obj[\"height\"] = picojson::value(static_cast<double>(widget_info->height()));\n obj[\"width\"] = picojson::value(static_cast<double>(widget_info->width()));\n\n out->insert(std::make_pair(\"result\", result));\n}\n\nstatic void KeyHandler(const picojson::value& args, picojson::object* out) {\n int idx = static_cast<int>(args.get(\"idx\").get<double>());\n std::string key;\n if (!wrt::Widget::GetInstance()->Key(idx, &key)) {\n out->insert(std::make_pair(\"status\", picojson::value(\"error\")));\n return;\n }\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n out->insert(std::make_pair(\"result\", picojson::value(key)));\n}\n\nstatic void GetItemHandler(const picojson::value& args,\n picojson::object* out) {\n const std::string& key = args.get(\"key\").get<std::string>();\n std::string value;\n if (!wrt::Widget::GetInstance()->GetItem(key, &value)) {\n out->insert(std::make_pair(\"status\", picojson::value(\"error\")));\n return;\n }\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n out->insert(std::make_pair(\"result\", picojson::value(value)));\n}\n\nstatic void LengthHandler(const picojson::value& \/*args*\/,\n picojson::object* out) {\n int length = wrt::Widget::GetInstance()->Length();\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n out->insert(\n std::make_pair(\"result\", picojson::value(static_cast<double>(length))));\n}\n\nstatic void ClearHandler(const picojson::value& \/*args*\/,\n picojson::object* out) {\n wrt::Widget::GetInstance()->Clear();\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n}\n\nstatic void SetItemHandler(const picojson::value& args,\n picojson::object* out) {\n const std::string& key = args.get(\"key\").get<std::string>();\n const std::string& value = args.get(\"value\").get<std::string>();\n std::string oldvalue;\n if (wrt::Widget::GetInstance()->GetItem(key, &oldvalue)) {\n out->insert(std::make_pair(\"result\", picojson::value(oldvalue)));\n } else {\n out->insert(std::make_pair(\"result\", picojson::value()));\n }\n wrt::Widget::GetInstance()->SetItem(key, value);\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n}\n\nstatic void RemoveHandler(const picojson::value& args,\n picojson::object* out) {\n const std::string& key = args.get(\"key\").get<std::string>();\n std::string oldvalue;\n if (wrt::Widget::GetInstance()->GetItem(key, &oldvalue)) {\n out->insert(std::make_pair(\"result\", picojson::value(oldvalue)));\n } else {\n out->insert(std::make_pair(\"result\", picojson::value()));\n }\n wrt::Widget::GetInstance()->RemoveItem(key);\n out->insert(std::make_pair(\"status\", picojson::value(\"success\")));\n}\n\n\nstatic void HandleMessage(XW_Instance instance,\n const char* message,\n bool sync) {\n picojson::value value;\n std::string err;\n picojson::parse(value, message, message + strlen(message), &err);\n if (!err.empty()) {\n LOGGER(ERROR) << \"Ignoring message. \" << err;\n return;\n }\n\n if (!value.is<picojson::object>()) {\n LOGGER(ERROR) << \"Ignoring message. It is not an object.\";\n return;\n }\n\n std::string cmd = value.get(\"cmd\").to_str();\n \/\/ check for args in JSON message\n const picojson::value& args = value.get(\"args\");\n picojson::value result = picojson::value(picojson::object());\n\n auto handler = g_handler.find(cmd);\n if (handler != g_handler.end()) {\n handler->second(args, &result.get<picojson::object>());\n } else {\n result.get<picojson::object>().insert(\n std::make_pair(\"status\", picojson::value(\"error\")));\n }\n\n if (sync) {\n g_sync_messaging->SetSyncReply(instance, result.serialize().c_str());\n }\n}\n\nnamespace wrt {\n\nnamespace {\n const char* kDbInitedCheckKey = \"__WRT_DB_INITED__\";\n const char* kDBPublicSection = \"public\";\n const char* kDBPrivateSection = \"private\";\n} \/\/ namespace\n\n\nWidget* Widget::GetInstance() {\n static Widget instance;\n return &instance;\n}\n\nWidget::Widget() {\n}\nWidget::~Widget() {\n}\n\nvoid Widget::Initialize(const ApplicationData* appdata) {\n AppDB* db = AppDB::GetInstance();\n if (db->HasKey(kDBPrivateSection, kDbInitedCheckKey))\n return;\n if (appdata->widget_info() == NULL)\n return;\n\n auto preferences = appdata->widget_info()->preferences();\n auto it = preferences.begin();\n for ( ; it != preferences.end(); ++it) {\n db->Set(kDBPublicSection,\n (*it)->Name(),\n (*it)->Value());\n }\n db->Set(kDBPrivateSection, kDbInitedCheckKey, \"true\");\n}\n\nint Widget::Length() {\n AppDB* db = AppDB::GetInstance();\n std::list<std::string> list;\n db->GetKeys(kDBPublicSection, &list);\n return list.size();\n}\n\nbool Widget::Key(int idx, std::string* key) {\n AppDB* db = AppDB::GetInstance();\n std::list<std::string> list;\n db->GetKeys(kDBPublicSection, &list);\n\n auto it = list.begin();\n for ( ; it != list.end() && idx >= 0; ++it) {\n if (idx == 0) {\n *key = *it;\n return true;\n }\n idx--;\n }\n return false;\n}\n\nbool Widget::GetItem(const std::string& key, std::string* value) {\n AppDB* db = AppDB::GetInstance();\n if (!db->HasKey(kDBPublicSection, key))\n return false;\n *value = db->Get(kDBPublicSection, key);\n return true;\n}\n\nbool Widget::SetItem(const std::string& key, const std::string& value) {\n AppDB* db = AppDB::GetInstance();\n db->Set(kDBPublicSection, key, value);\n return true;\n}\n\nbool Widget::RemoveItem(const std::string& key) {\n AppDB* db = AppDB::GetInstance();\n if (!db->HasKey(kDBPublicSection, key))\n return false;\n db->Remove(kDBPublicSection, key);\n return true;\n}\n\nvoid Widget::Clear() {\n AppDB* db = AppDB::GetInstance();\n std::list<std::string> list;\n db->GetKeys(kDBPublicSection, &list);\n auto it = list.begin();\n for ( ; it != list.end(); ++it) {\n db->Remove(kDBPublicSection, *it);\n }\n}\n\n} \/\/ namespace wrt\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_OPENCL_CODE_HPP\n#define STAN_MATH_OPENCL_KERNEL_GENERATOR_OPENCL_CODE_HPP\n#ifdef STAN_OPENCL\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/opencl\/matrix_cl_view.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/type_str.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/name_generator.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/operation_cl.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/as_operation_cl.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/common_return_scalar.hpp>\n#include <stan\/math\/prim\/functor\/for_each.hpp>\n#include <algorithm>\n#include <set>\n#include <string>\n#include <type_traits>\n#include <utility>\n\nnamespace stan {\nnamespace math {\n\n\/** \\addtogroup opencl_kernel_generator\n * @{\n *\/\n\/**\n * Represents output variable of custom code in kernel generator expressions.\n * @tparam T_code intantiation of `opencl_code_` class template this is output\n * of\n * @tparam T_scalar scalar type of the output variable\n *\/\ntemplate <typename T_code, typename T_scalar>\nclass opencl_code_output\n : public operation_cl<opencl_code_output<T_code, T_scalar>, T_scalar,\n T_code> {\n public:\n using Scalar = T_scalar;\n using base\n = operation_cl<opencl_code_output<T_code, T_scalar>, T_scalar, T_code>;\n using base::var_name_;\n const char* custom_var_name_;\n\n \/**\n * Constructor\n * @param code code object\n * @param custom_var_name variable name from the custom code\n *\/\n opencl_code_output(T_code code, const char* custom_var_name)\n : base(std::move(code)), custom_var_name_(custom_var_name) {}\n\n \/**\n * Creates a deep copy of this expression.\n * @return copy of \\c *this\n *\/\n inline auto deep_copy() const {\n auto&& code_copy = this->template get_arg<0>().deep_copy();\n return opencl_code_output<std::remove_reference_t<decltype(code_copy)>,\n T_scalar>(std::move(code_copy), custom_var_name_);\n }\n\n \/**\n * Generates kernel code for this operation.\n * @param row_index_name row index variable name\n * @param col_index_name column index variable name\n * @param view_handled whether whether caller already handled matrix view\n * @param var_name_condition variable name of the condition expression\n * @param var_name_else variable name of the then expression\n * @param var_name_then variable name of the else expression\n * @return part of kernel with code for this expression\n *\/\n inline kernel_parts generate(const std::string& row_index_name,\n const std::string& col_index_name,\n const bool view_handled,\n const std::string& dummy_var_name_code) const {\n kernel_parts res{};\n res.body = type_str<Scalar>() + \" \" + var_name_ + \" = \" + custom_var_name_\n + \";\\n\";\n return res;\n }\n\n \/**\n * Determine indices of extreme sub- and superdiagonals written.\n * @return pair of indices - bottom and top diagonal\n *\/\n inline std::pair<int, int> extreme_diagonals() const {\n return {-this->rows() + 1, this->cols() - 1};\n }\n};\n\nnamespace internal {\ntemplate <const char* Code, typename... T_arguments>\nclass opencl_code_impl\n : public operation_cl<opencl_code_impl<Code, T_arguments...>, double,\n T_arguments...> {\n public:\n \/\/ using Scalar = double;\n using base = operation_cl<opencl_code_impl<Code, T_arguments...>, double,\n T_arguments...>;\n using names_tuple\n = std::tuple<typename std::pair<const char*, T_arguments>::first_type...>;\n using base::var_name_;\n names_tuple names_;\n\n \/**\n * Constructor\n * @param condition condition expression\n * @param then then expression\n * @param els else expression\n *\/\n opencl_code_impl(names_tuple names, T_arguments&&... arguments)\n : base(std::forward<T_arguments>(arguments)...), names_(names) {}\n\n \/**\n * Generates kernel code for this (select) operation.\n * @param row_index_name row index variable name\n * @param col_index_name column index variable name\n * @param view_handled whether whether caller already handled matrix\n * view\n * @param var_name_condition variable name of the condition\n * expression\n * @param var_name_else variable name of the then expression\n * @param var_name_then variable name of the else expression\n * @return part of kernel with code for this expression\n *\/\n inline kernel_parts generate(\n const std::string& row_index_name, const std::string& col_index_name,\n const bool view_handled,\n std::tuple_element_t<\n 0, std::pair<const std::string&, T_arguments>>... var_names) const {\n return index_apply<sizeof...(T_arguments)>([this](auto... Is) {\n kernel_parts res{};\n std::array<std::string, sizeof...(T_arguments)> input_renames{\n (type_str<scalar_type_t<decltype(this->template get_arg<Is>())>>()\n + \" \" + std::get<Is>(names_) + \" = \"\n + this->template get_arg<Is>().var_name_ + \";\\n\")...};\n res.body = std::accumulate(input_renames.begin(), input_renames.end(),\n std::string())\n + Code;\n return res;\n });\n }\n};\n} \/\/ namespace internal\n\n\/**\n * Represents custom code in kernel generator expressions.\n * @tparam Code custom code\n * @tparam T_arguments types of argument expressions\n *\/\ntemplate <const char* Code, typename... T_arguments>\nclass opencl_code_ : public operation_cl_base {\n public:\n std::shared_ptr<internal::opencl_code_impl<Code, T_arguments...>> impl_;\n std::string& var_name_;\n using names_tuple\n = std::tuple<typename std::pair<const char*, T_arguments>::first_type...>;\n using Deriv = internal::opencl_code_impl<Code, T_arguments...>;\n\n \/**\n * Constructor\n * @param names tuple of names of the input variables (that hold values of\n * argument expressions)\n * @param arguments arguments to this operation\n *\/\n opencl_code_(const names_tuple& names, T_arguments&&... arguments)\n : impl_(\n std::make_shared<internal::opencl_code_impl<Code, T_arguments...>>(\n names, std::forward<T_arguments>(arguments)...)),\n var_name_(impl_->var_name_) {}\n\n \/**\n * Copy constructor.\n * @param other object to copy\n *\/\n opencl_code_(const opencl_code_<Code, T_arguments...>& other)\n : impl_(other.impl_), var_name_(impl_->var_name_) {}\n\n \/**\n * Generates kernel code for this and nested expressions.\n * @param[in,out] generated map from (pointer to) already generated local\n * operations to variable names\n * @param[in,out] generated_all map from (pointer to) already generated all\n * operations to variable names\n * @param name_gen name generator for this kernel\n * @param row_index_name row index variable name\n * @param col_index_name column index variable name\n * @param view_handled whether caller already handled matrix view\n * @return part of kernel with code for this and nested expressions\n *\/\n auto get_kernel_parts(std::map<const void*, const char*>& generated,\n std::map<const void*, const char*>& generated_all,\n name_generator& name_gen,\n const std::string& row_index_name,\n const std::string& col_index_name,\n bool view_handled) const {\n return impl_->get_kernel_parts(generated, generated_all, name_gen,\n row_index_name, col_index_name,\n view_handled);\n }\n\n \/**\n * Sets kernel arguments for nested expressions.\n * @param[in,out] generated map from (pointer to) already generated local\n * operations to variable names\n * @param[in,out] generated_all map from (pointer to) already generated all\n * operations to variable names\n * @param kernel kernel to set arguments on\n * @param[in,out] arg_num consecutive number of the first argument to set.\n * This is incremented for each argument set by this function.\n *\/\n auto set_args(std::map<const void*, const char*>& generated,\n std::map<const void*, const char*>& generated_all,\n cl::Kernel& kernel, int& arg_num) const {\n return impl_->set_args(generated, generated_all, kernel, arg_num);\n }\n\n \/**\n * Adds read event to any matrices used by nested expressions.\n * @param e the event to add\n *\/\n auto add_read_event(cl::Event& e) const { return impl_->add_read_event(e); }\n\n \/**\n * Adds all write events on any matrices used by nested expressions to a list.\n * @param[out] events List of all events.\n *\/\n auto get_write_events(std::vector<cl::Event>& events) const {\n return impl_->get_write_events(events);\n }\n\n \/**\n * Number of rows of a matrix that would be the result of evaluating this\n * expression. Some subclasses may need to override this.\n * @return number of rows\n *\/\n template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>\n auto rows() const {\n return impl_->rows();\n }\n template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>\n auto rows() const {\n return -1;\n }\n\n \/**\n * Number of columns of a matrix that would be the result of evaluating this\n * expression. Some subclasses may need to override this.\n * @return number of columns\n *\/\n template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>\n auto cols() const {\n return impl_->cols();\n }\n template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>\n auto cols() const {\n return -1;\n }\n\n \/**\n * Number of rows threads need to be launched for. For most expressions this\n * equals number of rows of the result.\n * @return number of rows\n *\/\n template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>\n auto thread_rows() const {\n return impl_->thread_rows();\n }\n template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>\n auto thread_rows() const {\n return -1;\n }\n\n \/**\n * Number of columns threads need to be launched for. For most expressions\n * this equals number of cols of the result.\n * @return number of columns\n *\/\n template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>\n auto thread_cols() const {\n return impl_->thread_cols();\n }\n template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>\n auto thread_cols() const {\n return -1;\n }\n\n \/**\n * Determine indices of extreme sub- and superdiagonals written.\n * @return pair of indices - bottom and top diagonal\n *\/\n auto extreme_diagonals() const { return impl_->extreme_diagonals(); }\n\n \/**\n * Collects data that is needed beside types to uniqly identify a kernel\n * generator expression.\n * @param[out] uids ids of unique matrix accesses\n * @param[in,out] id_map map from memory addresses to unique ids\n * @param[in,out] next_id neqt unique id to use\n *\/\n auto get_unique_matrix_accesses(std::vector<int>& uids,\n std::map<const void*, int>& id_map,\n int& next_id) const {\n return impl_->get_unique_matrix_accesses(uids, id_map, next_id);\n }\n\n \/**\n * Creates a deep copy of this expression.\n * @return copy of \\c *this\n *\/\n inline auto deep_copy() const {\n return index_apply<sizeof...(T_arguments)>([this](auto... Is) {\n auto args_copy\n = std::make_tuple(this->impl_->template get_arg<Is>().deep_copy()...);\n return opencl_code_<\n Code, std::remove_reference_t<decltype(std::get<Is>(args_copy))>...>(\n this->impl_->names_, std::move(std::get<Is>(args_copy))...);\n });\n }\n\n \/**\n * Get object representing output variable of ccustom code.\n * @param var_name name of the variable output object represents\n *\/\n template <typename T_scalar>\n inline auto output(const char* var_name) const {\n return opencl_code_output<opencl_code_<Code, T_arguments...>, T_scalar>(\n *this, var_name);\n }\n};\n\n\/**\n * Custom code in kernel generator expressions.\n * @tparam Code custom code\n * @tparam T_arguments types of argument expressions\n * @param names tuple of names of the input variables (that hold values of\n * argument expressions)\n * @param arguments arguments to this operation\n *\/\ntemplate <const char* Code, typename... T_arguments,\n require_all_kernel_expressions_t<T_arguments...>* = nullptr>\ninline opencl_code_<Code, as_operation_cl_t<T_arguments>...> opencl_code(\n std::tuple<typename std::pair<const char*, T_arguments>::first_type...>\n names,\n T_arguments&&... arguments) {\n return {names, as_operation_cl(std::forward<T_arguments>(arguments))...};\n}\n\n\/** @}*\/\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n#endif\n<commit_msg>fixed explicit constructors<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_OPENCL_CODE_HPP\n#define STAN_MATH_OPENCL_KERNEL_GENERATOR_OPENCL_CODE_HPP\n#ifdef STAN_OPENCL\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/opencl\/matrix_cl_view.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/type_str.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/name_generator.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/operation_cl.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/as_operation_cl.hpp>\n#include <stan\/math\/opencl\/kernel_generator\/common_return_scalar.hpp>\n#include <stan\/math\/prim\/functor\/for_each.hpp>\n#include <algorithm>\n#include <set>\n#include <string>\n#include <type_traits>\n#include <utility>\n\nnamespace stan {\nnamespace math {\n\n\/** \\addtogroup opencl_kernel_generator\n * @{\n *\/\n\/**\n * Represents output variable of custom code in kernel generator expressions.\n * @tparam T_code intantiation of `opencl_code_` class template this is output\n * of\n * @tparam T_scalar scalar type of the output variable\n *\/\ntemplate <typename T_code, typename T_scalar>\nclass opencl_code_output\n : public operation_cl<opencl_code_output<T_code, T_scalar>, T_scalar,\n T_code> {\n public:\n using Scalar = T_scalar;\n using base\n = operation_cl<opencl_code_output<T_code, T_scalar>, T_scalar, T_code>;\n using base::var_name_;\n const char* custom_var_name_;\n\n \/**\n * Constructor\n * @param code code object\n * @param custom_var_name variable name from the custom code\n *\/\n opencl_code_output(T_code code, const char* custom_var_name)\n : base(std::move(code)), custom_var_name_(custom_var_name) {}\n\n \/**\n * Creates a deep copy of this expression.\n * @return copy of \\c *this\n *\/\n inline auto deep_copy() const {\n auto&& code_copy = this->template get_arg<0>().deep_copy();\n return opencl_code_output<std::remove_reference_t<decltype(code_copy)>,\n T_scalar>(std::move(code_copy), custom_var_name_);\n }\n\n \/**\n * Generates kernel code for this operation.\n * @param row_index_name row index variable name\n * @param col_index_name column index variable name\n * @param view_handled whether whether caller already handled matrix view\n * @param var_name_condition variable name of the condition expression\n * @param var_name_else variable name of the then expression\n * @param var_name_then variable name of the else expression\n * @return part of kernel with code for this expression\n *\/\n inline kernel_parts generate(const std::string& row_index_name,\n const std::string& col_index_name,\n const bool view_handled,\n const std::string& dummy_var_name_code) const {\n kernel_parts res{};\n res.body = type_str<Scalar>() + \" \" + var_name_ + \" = \" + custom_var_name_\n + \";\\n\";\n return res;\n }\n\n \/**\n * Determine indices of extreme sub- and superdiagonals written.\n * @return pair of indices - bottom and top diagonal\n *\/\n inline std::pair<int, int> extreme_diagonals() const {\n return {-this->rows() + 1, this->cols() - 1};\n }\n};\n\nnamespace internal {\ntemplate <const char* Code, typename... T_arguments>\nclass opencl_code_impl\n : public operation_cl<opencl_code_impl<Code, T_arguments...>, double,\n T_arguments...> {\n public:\n \/\/ using Scalar = double;\n using base = operation_cl<opencl_code_impl<Code, T_arguments...>, double,\n T_arguments...>;\n using names_tuple\n = std::tuple<typename std::pair<const char*, T_arguments>::first_type...>;\n using base::var_name_;\n names_tuple names_;\n\n \/**\n * Constructor\n * @param condition condition expression\n * @param then then expression\n * @param els else expression\n *\/\n explicit opencl_code_impl(names_tuple names, T_arguments&&... arguments)\n : base(std::forward<T_arguments>(arguments)...), names_(names) {}\n\n \/**\n * Generates kernel code for this (select) operation.\n * @param row_index_name row index variable name\n * @param col_index_name column index variable name\n * @param view_handled whether whether caller already handled matrix\n * view\n * @param var_name_condition variable name of the condition\n * expression\n * @param var_name_else variable name of the then expression\n * @param var_name_then variable name of the else expression\n * @return part of kernel with code for this expression\n *\/\n inline kernel_parts generate(\n const std::string& row_index_name, const std::string& col_index_name,\n const bool view_handled,\n std::tuple_element_t<\n 0, std::pair<const std::string&, T_arguments>>... var_names) const {\n return index_apply<sizeof...(T_arguments)>([this](auto... Is) {\n kernel_parts res{};\n std::array<std::string, sizeof...(T_arguments)> input_renames{\n (type_str<scalar_type_t<decltype(this->template get_arg<Is>())>>()\n + \" \" + std::get<Is>(names_) + \" = \"\n + this->template get_arg<Is>().var_name_ + \";\\n\")...};\n res.body = std::accumulate(input_renames.begin(), input_renames.end(),\n std::string())\n + Code;\n return res;\n });\n }\n};\n} \/\/ namespace internal\n\n\/**\n * Represents custom code in kernel generator expressions.\n * @tparam Code custom code\n * @tparam T_arguments types of argument expressions\n *\/\ntemplate <const char* Code, typename... T_arguments>\nclass opencl_code_ : public operation_cl_base {\n public:\n std::shared_ptr<internal::opencl_code_impl<Code, T_arguments...>> impl_;\n std::string& var_name_;\n using names_tuple\n = std::tuple<typename std::pair<const char*, T_arguments>::first_type...>;\n using Deriv = internal::opencl_code_impl<Code, T_arguments...>;\n\n \/**\n * Constructor\n * @param names tuple of names of the input variables (that hold values of\n * argument expressions)\n * @param arguments arguments to this operation\n *\/\n explicit opencl_code_(const names_tuple& names, T_arguments&&... arguments)\n : impl_(\n std::make_shared<internal::opencl_code_impl<Code, T_arguments...>>(\n names, std::forward<T_arguments>(arguments)...)),\n var_name_(impl_->var_name_) {}\n\n \/**\n * Copy constructor.\n * @param other object to copy\n *\/\n opencl_code_(const opencl_code_<Code, T_arguments...>& other)\n : impl_(other.impl_), var_name_(impl_->var_name_) {}\n\n \/**\n * Generates kernel code for this and nested expressions.\n * @param[in,out] generated map from (pointer to) already generated local\n * operations to variable names\n * @param[in,out] generated_all map from (pointer to) already generated all\n * operations to variable names\n * @param name_gen name generator for this kernel\n * @param row_index_name row index variable name\n * @param col_index_name column index variable name\n * @param view_handled whether caller already handled matrix view\n * @return part of kernel with code for this and nested expressions\n *\/\n auto get_kernel_parts(std::map<const void*, const char*>& generated,\n std::map<const void*, const char*>& generated_all,\n name_generator& name_gen,\n const std::string& row_index_name,\n const std::string& col_index_name,\n bool view_handled) const {\n return impl_->get_kernel_parts(generated, generated_all, name_gen,\n row_index_name, col_index_name,\n view_handled);\n }\n\n \/**\n * Sets kernel arguments for nested expressions.\n * @param[in,out] generated map from (pointer to) already generated local\n * operations to variable names\n * @param[in,out] generated_all map from (pointer to) already generated all\n * operations to variable names\n * @param kernel kernel to set arguments on\n * @param[in,out] arg_num consecutive number of the first argument to set.\n * This is incremented for each argument set by this function.\n *\/\n auto set_args(std::map<const void*, const char*>& generated,\n std::map<const void*, const char*>& generated_all,\n cl::Kernel& kernel, int& arg_num) const {\n return impl_->set_args(generated, generated_all, kernel, arg_num);\n }\n\n \/**\n * Adds read event to any matrices used by nested expressions.\n * @param e the event to add\n *\/\n auto add_read_event(cl::Event& e) const { return impl_->add_read_event(e); }\n\n \/**\n * Adds all write events on any matrices used by nested expressions to a list.\n * @param[out] events List of all events.\n *\/\n auto get_write_events(std::vector<cl::Event>& events) const {\n return impl_->get_write_events(events);\n }\n\n \/**\n * Number of rows of a matrix that would be the result of evaluating this\n * expression. Some subclasses may need to override this.\n * @return number of rows\n *\/\n template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>\n auto rows() const {\n return impl_->rows();\n }\n template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>\n auto rows() const {\n return -1;\n }\n\n \/**\n * Number of columns of a matrix that would be the result of evaluating this\n * expression. Some subclasses may need to override this.\n * @return number of columns\n *\/\n template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>\n auto cols() const {\n return impl_->cols();\n }\n template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>\n auto cols() const {\n return -1;\n }\n\n \/**\n * Number of rows threads need to be launched for. For most expressions this\n * equals number of rows of the result.\n * @return number of rows\n *\/\n template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>\n auto thread_rows() const {\n return impl_->thread_rows();\n }\n template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>\n auto thread_rows() const {\n return -1;\n }\n\n \/**\n * Number of columns threads need to be launched for. For most expressions\n * this equals number of cols of the result.\n * @return number of columns\n *\/\n template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>\n auto thread_cols() const {\n return impl_->thread_cols();\n }\n template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>\n auto thread_cols() const {\n return -1;\n }\n\n \/**\n * Determine indices of extreme sub- and superdiagonals written.\n * @return pair of indices - bottom and top diagonal\n *\/\n auto extreme_diagonals() const { return impl_->extreme_diagonals(); }\n\n \/**\n * Collects data that is needed beside types to uniqly identify a kernel\n * generator expression.\n * @param[out] uids ids of unique matrix accesses\n * @param[in,out] id_map map from memory addresses to unique ids\n * @param[in,out] next_id neqt unique id to use\n *\/\n auto get_unique_matrix_accesses(std::vector<int>& uids,\n std::map<const void*, int>& id_map,\n int& next_id) const {\n return impl_->get_unique_matrix_accesses(uids, id_map, next_id);\n }\n\n \/**\n * Creates a deep copy of this expression.\n * @return copy of \\c *this\n *\/\n inline auto deep_copy() const {\n return index_apply<sizeof...(T_arguments)>([this](auto... Is) {\n auto args_copy\n = std::make_tuple(this->impl_->template get_arg<Is>().deep_copy()...);\n return opencl_code_<\n Code, std::remove_reference_t<decltype(std::get<Is>(args_copy))>...>(\n this->impl_->names_, std::move(std::get<Is>(args_copy))...);\n });\n }\n\n \/**\n * Get object representing output variable of ccustom code.\n * @param var_name name of the variable output object represents\n *\/\n template <typename T_scalar>\n inline auto output(const char* var_name) const {\n return opencl_code_output<opencl_code_<Code, T_arguments...>, T_scalar>(\n *this, var_name);\n }\n};\n\n\/**\n * Custom code in kernel generator expressions.\n * @tparam Code custom code\n * @tparam T_arguments types of argument expressions\n * @param names tuple of names of the input variables (that hold values of\n * argument expressions)\n * @param arguments arguments to this operation\n *\/\ntemplate <const char* Code, typename... T_arguments,\n require_all_kernel_expressions_t<T_arguments...>* = nullptr>\ninline auto opencl_code(\n std::tuple<typename std::pair<const char*, T_arguments>::first_type...>\n names,\n T_arguments&&... arguments) {\n return opencl_code_<Code, as_operation_cl_t<T_arguments>...>(\n names, as_operation_cl(std::forward<T_arguments>(arguments))...);\n}\n\n\/** @}*\/\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include <glog\/logging.h>\n#include \"paddle\/fluid\/inference\/api\/paddle_inference_api.h\"\n\nnamespace paddle {\n\nint PaddleDtypeSize(PaddleDType dtype) {\n switch (dtype) {\n case PaddleDType::FLOAT32:\n return sizeof(float);\n case PaddleDType::INT64:\n return sizeof(int64_t);\n default:\n assert(false);\n return -1;\n }\n}\n\nPaddleBuf::PaddleBuf(PaddleBuf&& other)\n : data_(other.data_),\n length_(other.length_),\n memory_owned_(other.memory_owned_) {\n other.memory_owned_ = false;\n other.data_ = nullptr;\n other.length_ = 0;\n}\n\nPaddleBuf::PaddleBuf(const PaddleBuf& other) { *this = other; }\n\nPaddleBuf& PaddleBuf::operator=(const PaddleBuf& other) {\n if (!other.memory_owned_) {\n data_ = other.data_;\n length_ = other.length_;\n memory_owned_ = other.memory_owned_;\n } else {\n Resize(other.length());\n memcpy(data_, other.data(), other.length());\n length_ = other.length();\n memory_owned_ = true;\n }\n return *this;\n}\n\nPaddleBuf& PaddleBuf::operator=(PaddleBuf&& other) {\n \/\/ only the buffer with external memory can be copied\n data_ = other.data_;\n length_ = other.length_;\n memory_owned_ = other.memory_owned_;\n other.data_ = nullptr;\n other.length_ = 0;\n other.memory_owned_ = false;\n return *this;\n}\n\nvoid PaddleBuf::Resize(size_t length) {\n \/\/ Only the owned memory can be reset, the external memory can't be changed.\n if (length_ == length) return;\n if (memory_owned_) {\n Free();\n }\n data_ = new char[length];\n length_ = length;\n memory_owned_ = true;\n}\n\nvoid PaddleBuf::Reset(void* data, size_t length) {\n Free();\n memory_owned_ = false;\n data_ = data;\n length_ = length;\n}\n\nvoid PaddleBuf::Free() {\n if (memory_owned_ && data_) {\n assert(length_ > 0);\n delete[] static_cast<char*>(data_);\n data_ = nullptr;\n length_ = 0;\n }\n}\n\n} \/\/ namespace paddle\n<commit_msg>Hotfix\/api predictor (#13383)<commit_after>\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/inference\/api\/paddle_inference_api.h\"\n#include \"paddle\/fluid\/platform\/enforce.h\"\n\nnamespace paddle {\n\nint PaddleDtypeSize(PaddleDType dtype) {\n switch (dtype) {\n case PaddleDType::FLOAT32:\n return sizeof(float);\n case PaddleDType::INT64:\n return sizeof(int64_t);\n default:\n assert(false);\n return -1;\n }\n}\n\nPaddleBuf::PaddleBuf(PaddleBuf&& other)\n : data_(other.data_),\n length_(other.length_),\n memory_owned_(other.memory_owned_) {\n other.memory_owned_ = false;\n other.data_ = nullptr;\n other.length_ = 0;\n}\n\nPaddleBuf::PaddleBuf(const PaddleBuf& other) { *this = other; }\n\nPaddleBuf& PaddleBuf::operator=(const PaddleBuf& other) {\n if (!other.memory_owned_) {\n data_ = other.data_;\n length_ = other.length_;\n memory_owned_ = other.memory_owned_;\n } else {\n Resize(other.length());\n memcpy(data_, other.data(), other.length());\n length_ = other.length();\n memory_owned_ = true;\n }\n return *this;\n}\n\nPaddleBuf& PaddleBuf::operator=(PaddleBuf&& other) {\n \/\/ only the buffer with external memory can be copied\n data_ = other.data_;\n length_ = other.length_;\n memory_owned_ = other.memory_owned_;\n other.data_ = nullptr;\n other.length_ = 0;\n other.memory_owned_ = false;\n return *this;\n}\n\nvoid PaddleBuf::Resize(size_t length) {\n \/\/ Only the owned memory can be reset, the external memory can't be changed.\n if (length_ >= length) return;\n if (memory_owned_) {\n Free();\n data_ = malloc(length);\n length_ = length;\n memory_owned_ = true;\n } else {\n PADDLE_THROW(\"The memory is allocated externally, can not Resized\");\n }\n}\n\nvoid PaddleBuf::Reset(void* data, size_t length) {\n Free();\n memory_owned_ = false;\n data_ = data;\n length_ = length;\n}\n\nvoid PaddleBuf::Free() {\n if (memory_owned_ && data_) {\n PADDLE_ENFORCE_GT(length_, 0);\n free(static_cast<char*>(data_));\n data_ = nullptr;\n length_ = 0;\n }\n}\n\n} \/\/ namespace paddle\n<|endoftext|>"} {"text":"<commit_before>#include \"FileDialog.h\"\n\n#ifdef SYSTEM_WINDOWS\n #include <windows.h>\n #include <shlobj.h>\n#endif\n#ifdef SYSTEM_LINUX\n #include <gtk\/gtk.h>\n #include <cstring>\n #include <malloc.h>\n#endif\n\n#include <iostream>\n#include <cassert>\n\nnamespace FileDialog\n{\n#ifdef SYSTEM_WINDOWS\n \/\/ Function that opens a dialoge window to choose a file\n bool openFilen( std::string const & filterList,\n std::string const & defaultPath,\n std::string & outPath )\n {\n OPENFILENAMEA ofn;\n char fileName[MAX_PATH] = \"\";\n ZeroMemory(&ofn, sizeof(ofn));\n\n ofn.lStructSize = sizeof(OPENFILENAME);\n ofn.hwndOwner = NULL;\n ofn.lpstrInitialDir = defaultPath.c_str();\n ofn.lpstrFilter = filter.c_str();\n ofn.lpstrFile = fileName;\n ofn.nMaxFile = MAX_PATH;\n ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; \n\t\tofn.lpstrDefExt = \"\";\n\n\t\tif(!GetOpenFileNameA(&ofn))\n\t\t\treturn false;\n\t\t\n\t\toutPath = fileName;\n\t\t\n return true;\n }\n\n\tstatic int CALLBACK browseFolderCallback( HWND hwnd, \n\t\t\t\t\t\t\t\t\t\t\t UINT uMsg, \n\t\t\t\t\t\t\t\t\t\t\t LPARAM lParam, \n\t\t\t\t\t\t\t\t\t\t\t LPARAM lpData )\n\t{\n\t\tif (uMsg == BFFM_INITIALIZED)\n\t\t{\n\t\t\tLPCTSTR path = reinterpret_cast<LPCTSTR>(lpData);\n\t\t\t::SendMessage(hwnd, BFFM_SETSELECTION, true, (LPARAM)path);\n\t\t}\n\t\treturn 0;\n\t}\n\n \/\/ Function to browse the folder with the DICOM Series\n bool openFolder( std::string const & defaultPath,\n std::string& outPath )\n {\n BROWSEINFO bi = { 0 };\n LPITEMIDLIST pidl;\n TCHAR szDisplay[MAX_PATH];\n\n LPVOID pvReserved = NULL;\n CoInitialize(pvReserved);\n\n bi.hwndOwner = NULL;\n bi.pszDisplayName = szDisplay;\n bi.lpszTitle = TEXT(\"Please choose a folder.\");\n bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;\n\t\tbi.lpfn = browseFolderCallback;\n\t\tif (defaultPath.empty())\n\t\t{\n\t\t\tbi.lParam = NULL;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbi.lParam = (LPARAM)(defaultPath.c_str());\n\t\t}\n\n pidl = SHBrowseForFolder(&bi);\n\n\t\tstd::string result;\n\t\tLPTSTR szPath = new TCHAR[MAX_PATH];\n\t\tif (!SHGetPathFromIDList(pidl, szPath))\n\t\t\treturn false;\n\n\t\tresult = std::string(szPath);\n\t\tdelete[] szPath;\n \n\t\tCoUninitialize();\n\n return true;\n }\n#endif\n\n#ifdef SYSTEM_LINUX\n static void WaitForCleanup(void)\n {\n while (gtk_events_pending())\n gtk_main_iteration();\n }\n\n static void AddTypeToFilterName( const char *typebuf, char *filterName, size_t bufsize )\n {\n const char SEP[] = \", \";\n\n size_t len = strlen(filterName);\n if ( len != 0 )\n {\n strncat( filterName, SEP, bufsize - len - 1 );\n len += strlen(SEP);\n }\n\n strncat( filterName, typebuf, bufsize - len - 1 );\n }\n\n static bool NFDi_IsFilterSegmentChar( char ch )\n {\n return (ch==','||ch==';'||ch=='\\0');\n }\n\n static void AddFiltersToDialog( GtkWidget *dialog, const char *filterList )\n {\n GtkFileFilter *filter;\n char typebuf[4096] = {0};\n const char *p_filterList = filterList;\n char *p_typebuf = typebuf;\n char filterName[4096] = {0};\n\n if ( !filterList || strlen(filterList) == 0 )\n return;\n\n filter = gtk_file_filter_new();\n while ( 1 )\n {\n\n if ( NFDi_IsFilterSegmentChar(*p_filterList) )\n {\n char typebufWildcard[4096];\n \/* add another type to the filter *\/\n assert( strlen(typebuf) > 0 );\n assert( strlen(typebuf) < 4096-1 );\n\n snprintf( typebufWildcard, 4096, \"*.%s\", typebuf );\n AddTypeToFilterName( typebuf, filterName, 4096 );\n\n gtk_file_filter_add_pattern( filter, typebufWildcard );\n\n p_typebuf = typebuf;\n memset( typebuf, 0, sizeof(char) * 4096 );\n }\n\n if ( *p_filterList == ';' || *p_filterList == '\\0' )\n {\n \/* end of filter -- add it to the dialog *\/\n\n gtk_file_filter_set_name( filter, filterName );\n gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(dialog), filter );\n\n filterName[0] = '\\0';\n\n if ( *p_filterList == '\\0' )\n break;\n\n filter = gtk_file_filter_new();\n }\n\n if ( !NFDi_IsFilterSegmentChar( *p_filterList ) )\n {\n *p_typebuf = *p_filterList;\n p_typebuf++;\n }\n\n p_filterList++;\n }\n\n \/* always append a wildcard option to the end*\/\n\n filter = gtk_file_filter_new();\n gtk_file_filter_set_name( filter, \"*.*\" );\n gtk_file_filter_add_pattern( filter, \"*\" );\n gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(dialog), filter );\n }\n\n static void SetDefaultPath( GtkWidget *dialog, const char *defaultPath )\n {\n if ( !defaultPath || strlen(defaultPath) == 0 )\n return;\n\n \/* GTK+ manual recommends not specifically setting the default path.\n We do it anyway in order to be consistent across platforms.\n If consistency with the native OS is preferred, this is the line\n to comment out. -ml *\/\n gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(dialog), defaultPath );\n }\n\n bool openFilen( std::string const & filterList,\n std::string const & defaultPath,\n std::string & outPath )\n {\n GtkWidget *dialog;\n bool result;\n\n if ( !gtk_init_check( NULL, NULL ) )\n {\n return false;\n }\n\n dialog = gtk_file_chooser_dialog_new( \"Open File\",\n NULL,\n GTK_FILE_CHOOSER_ACTION_OPEN,\n \"_Cancel\", GTK_RESPONSE_CANCEL,\n \"_Open\", GTK_RESPONSE_ACCEPT,\n NULL );\n\n \/* Build the filter list *\/\n AddFiltersToDialog(dialog, filterList.c_str() );\n\n \/* Set the default path *\/\n SetDefaultPath(dialog, defaultPath.c_str() );\n\n result = false;\n if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )\n {\n char *filename;\n\n filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) );\n\n {\n outPath = std::string( filename );\n if ( outPath.empty() )\n {\n g_free( filename );\n gtk_widget_destroy(dialog);\n return false;\n }\n }\n g_free( filename );\n\n result = true;\n }\n\n WaitForCleanup();\n gtk_widget_destroy(dialog);\n WaitForCleanup();\n\n return result;\n }\n\n bool openFolder( std::string const & defaultPath,\n std::string& outPath )\n {\n GtkWidget *dialog;\n bool result;\n\n if (!gtk_init_check(NULL, NULL))\n {\n return false;\n }\n\n dialog = gtk_file_chooser_dialog_new( \"Select folder\",\n NULL,\n GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,\n \"_Cancel\", GTK_RESPONSE_CANCEL,\n \"_Select\", GTK_RESPONSE_ACCEPT,\n NULL );\n gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dialog), TRUE );\n\n\n \/* Set the default path *\/\n SetDefaultPath( dialog, defaultPath.c_str() );\n\n result = false;\n if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )\n {\n char *filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) );\n\n {\n outPath = std::string( filename );\n if ( outPath.empty() )\n {\n g_free( filename );\n gtk_widget_destroy(dialog);\n return false;\n }\n }\n g_free(filename);\n\n result = true;\n }\n\n WaitForCleanup();\n gtk_widget_destroy(dialog);\n WaitForCleanup();\n\n return result;\n }\n#endif\n} \/\/ namespace FileDialog\n<commit_msg>#1 fixed minor bug in openFolder function<commit_after>#include \"FileDialog.h\"\n\n#ifdef SYSTEM_WINDOWS\n #include <windows.h>\n #include <shlobj.h>\n#endif\n#ifdef SYSTEM_LINUX\n #include <gtk\/gtk.h>\n #include <cstring>\n #include <malloc.h>\n#endif\n\n#include <iostream>\n#include <cassert>\n\nnamespace FileDialog\n{\n#ifdef SYSTEM_WINDOWS\n \/\/ Function that opens a dialoge window to choose a file\n bool openFile( std::string const & filterList,\n std::string const & defaultPath,\n std::string & outPath )\n {\n OPENFILENAMEA ofn;\n char fileName[MAX_PATH] = \"\";\n ZeroMemory(&ofn, sizeof(ofn));\n\n ofn.lStructSize = sizeof(OPENFILENAME);\n ofn.hwndOwner = NULL;\n ofn.lpstrInitialDir = defaultPath.c_str();\n ofn.lpstrFilter = filterList.c_str();\n ofn.lpstrFile = fileName;\n ofn.nMaxFile = MAX_PATH;\n ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; \n\t\tofn.lpstrDefExt = \"\";\n\n\t\tif(!GetOpenFileNameA(&ofn))\n\t\t\treturn false;\n\t\t\n\t\toutPath = fileName;\n\t\t\n return true;\n }\n\n\tstatic int CALLBACK browseFolderCallback( HWND hwnd, \n\t\t\t\t\t\t\t\t\t\t\t UINT uMsg, \n\t\t\t\t\t\t\t\t\t\t\t LPARAM lParam, \n\t\t\t\t\t\t\t\t\t\t\t LPARAM lpData )\n\t{\n\t\tif (uMsg == BFFM_INITIALIZED)\n\t\t{\n\t\t\tLPCTSTR path = reinterpret_cast<LPCTSTR>(lpData);\n\t\t\t::SendMessage(hwnd, BFFM_SETSELECTION, true, (LPARAM)path);\n\t\t}\n\t\treturn 0;\n\t}\n\n \/\/ Function to browse the folder with the DICOM Series\n bool openFolder( std::string const & defaultPath,\n std::string& outPath )\n {\n BROWSEINFO bi = { 0 };\n LPITEMIDLIST pidl;\n TCHAR szDisplay[MAX_PATH];\n\n LPVOID pvReserved = NULL;\n CoInitialize(pvReserved);\n\n bi.hwndOwner = NULL;\n bi.pszDisplayName = szDisplay;\n bi.lpszTitle = TEXT(\"Please choose a folder.\");\n bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;\n\t\tbi.lpfn = browseFolderCallback;\n\t\tif (defaultPath.empty())\n\t\t{\n\t\t\tbi.lParam = NULL;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbi.lParam = (LPARAM)(defaultPath.c_str());\n\t\t}\n\n pidl = SHBrowseForFolder(&bi);\n\n\t\tLPTSTR szPath = new TCHAR[MAX_PATH];\n\t\tif (!SHGetPathFromIDList(pidl, szPath))\n\t\t\treturn false;\n\n\t\toutPath = std::string(szPath);\n\t\tdelete[] szPath;\n \n\t\tCoUninitialize();\n\n return true;\n }\n#endif\n\n#ifdef SYSTEM_LINUX\n static void WaitForCleanup(void)\n {\n while (gtk_events_pending())\n gtk_main_iteration();\n }\n\n static void AddTypeToFilterName( const char *typebuf, char *filterName, size_t bufsize )\n {\n const char SEP[] = \", \";\n\n size_t len = strlen(filterName);\n if ( len != 0 )\n {\n strncat( filterName, SEP, bufsize - len - 1 );\n len += strlen(SEP);\n }\n\n strncat( filterName, typebuf, bufsize - len - 1 );\n }\n\n static bool NFDi_IsFilterSegmentChar( char ch )\n {\n return (ch==','||ch==';'||ch=='\\0');\n }\n\n static void AddFiltersToDialog( GtkWidget *dialog, const char *filterList )\n {\n GtkFileFilter *filter;\n char typebuf[4096] = {0};\n const char *p_filterList = filterList;\n char *p_typebuf = typebuf;\n char filterName[4096] = {0};\n\n if ( !filterList || strlen(filterList) == 0 )\n return;\n\n filter = gtk_file_filter_new();\n while ( 1 )\n {\n\n if ( NFDi_IsFilterSegmentChar(*p_filterList) )\n {\n char typebufWildcard[4096];\n \/* add another type to the filter *\/\n assert( strlen(typebuf) > 0 );\n assert( strlen(typebuf) < 4096-1 );\n\n snprintf( typebufWildcard, 4096, \"*.%s\", typebuf );\n AddTypeToFilterName( typebuf, filterName, 4096 );\n\n gtk_file_filter_add_pattern( filter, typebufWildcard );\n\n p_typebuf = typebuf;\n memset( typebuf, 0, sizeof(char) * 4096 );\n }\n\n if ( *p_filterList == ';' || *p_filterList == '\\0' )\n {\n \/* end of filter -- add it to the dialog *\/\n\n gtk_file_filter_set_name( filter, filterName );\n gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(dialog), filter );\n\n filterName[0] = '\\0';\n\n if ( *p_filterList == '\\0' )\n break;\n\n filter = gtk_file_filter_new();\n }\n\n if ( !NFDi_IsFilterSegmentChar( *p_filterList ) )\n {\n *p_typebuf = *p_filterList;\n p_typebuf++;\n }\n\n p_filterList++;\n }\n\n \/* always append a wildcard option to the end*\/\n\n filter = gtk_file_filter_new();\n gtk_file_filter_set_name( filter, \"*.*\" );\n gtk_file_filter_add_pattern( filter, \"*\" );\n gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(dialog), filter );\n }\n\n static void SetDefaultPath( GtkWidget *dialog, const char *defaultPath )\n {\n if ( !defaultPath || strlen(defaultPath) == 0 )\n return;\n\n \/* GTK+ manual recommends not specifically setting the default path.\n We do it anyway in order to be consistent across platforms.\n If consistency with the native OS is preferred, this is the line\n to comment out. -ml *\/\n gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(dialog), defaultPath );\n }\n\n bool openFilen( std::string const & filterList,\n std::string const & defaultPath,\n std::string & outPath )\n {\n GtkWidget *dialog;\n bool result;\n\n if ( !gtk_init_check( NULL, NULL ) )\n {\n return false;\n }\n\n dialog = gtk_file_chooser_dialog_new( \"Open File\",\n NULL,\n GTK_FILE_CHOOSER_ACTION_OPEN,\n \"_Cancel\", GTK_RESPONSE_CANCEL,\n \"_Open\", GTK_RESPONSE_ACCEPT,\n NULL );\n\n \/* Build the filter list *\/\n AddFiltersToDialog(dialog, filterList.c_str() );\n\n \/* Set the default path *\/\n SetDefaultPath(dialog, defaultPath.c_str() );\n\n result = false;\n if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )\n {\n char *filename;\n\n filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) );\n\n {\n outPath = std::string( filename );\n if ( outPath.empty() )\n {\n g_free( filename );\n gtk_widget_destroy(dialog);\n return false;\n }\n }\n g_free( filename );\n\n result = true;\n }\n\n WaitForCleanup();\n gtk_widget_destroy(dialog);\n WaitForCleanup();\n\n return result;\n }\n\n bool openFolder( std::string const & defaultPath,\n std::string& outPath )\n {\n GtkWidget *dialog;\n bool result;\n\n if (!gtk_init_check(NULL, NULL))\n {\n return false;\n }\n\n dialog = gtk_file_chooser_dialog_new( \"Select folder\",\n NULL,\n GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,\n \"_Cancel\", GTK_RESPONSE_CANCEL,\n \"_Select\", GTK_RESPONSE_ACCEPT,\n NULL );\n gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dialog), TRUE );\n\n\n \/* Set the default path *\/\n SetDefaultPath( dialog, defaultPath.c_str() );\n\n result = false;\n if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )\n {\n char *filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) );\n\n {\n outPath = std::string( filename );\n if ( outPath.empty() )\n {\n g_free( filename );\n gtk_widget_destroy(dialog);\n return false;\n }\n }\n g_free(filename);\n\n result = true;\n }\n\n WaitForCleanup();\n gtk_widget_destroy(dialog);\n WaitForCleanup();\n\n return result;\n }\n#endif\n} \/\/ namespace FileDialog\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2015-2017 The Bitcoin Unlimited developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"txdb.h\"\n\n#include \"chain.h\"\n#include \"chainparams.h\"\n#include \"hash.h\"\n#include \"main.h\"\n#include \"pow.h\"\n#include \"uint256.h\"\n#include \"ui_interface.h\"\n\n#include <stdint.h>\n\nusing namespace std;\n\nstatic const char DB_COIN = 'C';\nstatic const char DB_COINS = 'c';\nstatic const char DB_BLOCK_FILES = 'f';\nstatic const char DB_TXINDEX = 't';\nstatic const char DB_BLOCK_INDEX = 'b';\n\nstatic const char DB_BEST_BLOCK = 'B';\nstatic const char DB_FLAG = 'F';\nstatic const char DB_REINDEX_FLAG = 'R';\nstatic const char DB_LAST_BLOCK = 'l';\n\nnamespace {\n\nstruct CoinEntry {\n COutPoint* outpoint;\n char key;\n CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {}\n\n template<typename Stream>\n void Serialize(Stream &s) const {\n s << key;\n s << outpoint->hash;\n s << VARINT(outpoint->n);\n }\n\n template<typename Stream>\n void Unserialize(Stream& s) {\n s >> key;\n s >> outpoint->hash;\n s >> VARINT(outpoint->n);\n }\n};\n\n}\n\nCCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() \/ \"chainstate\", nCacheSize, fMemory, fWipe, true)\n{\n}\n\nbool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const {\n return db.Read(CoinEntry(&outpoint), coin);\n}\n\nbool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const {\n return db.Exists(CoinEntry(&outpoint));\n}\n\nuint256 CCoinsViewDB::GetBestBlock() const {\n LOCK(cs_utxo);\n uint256 hashBestChain;\n if (!db.Read(DB_BEST_BLOCK, hashBestChain))\n return uint256();\n return hashBestChain;\n}\n\nbool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage)\n{\n LOCK(cs_utxo);\n CDBBatch batch(db);\n size_t count = 0;\n size_t changed = 0;\n size_t nBatchSize = 0;\n size_t nBatchWrites = 0;\n for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();)\n {\n if (it->second.flags & CCoinsCacheEntry::DIRTY)\n {\n CoinEntry entry(&it->first);\n size_t nUsage = it->second.coin.DynamicMemoryUsage();\n if (it->second.coin.IsSpent())\n {\n batch.Erase(entry);\n\n \/\/ Update the usage of the child cache before deleting the entry in the child cache\n nChildCachedCoinsUsage -= nUsage;\n it = mapCoins.erase(it);\n }\n else\n {\n batch.Write(entry, it->second.coin);\n\n \/\/ Only delete valid coins from the cache when we're nearly syncd. During IBD, and also\n \/\/ if BlockOnly mode is turned on, these coins will be used, whereas, once the chain is\n \/\/ syncd we only need the coins that have come from accepting txns into the memory pool.\n bool fBlocksOnly = GetBoolArg(\"-blocksonly\", DEFAULT_BLOCKSONLY);\n if (IsChainNearlySyncd() && !fImporting && !fReindex && !fBlocksOnly)\n {\n \/\/ Update the usage of the child cache before deleting the entry in the child cache\n nChildCachedCoinsUsage -= nUsage;\n it = mapCoins.erase(it);\n }\n else\n {\n it->second.flags = 0;\n it++;\n }\n }\n changed++;\n\n \/\/ In order to prevent the spikes in memory usage that used to happen when we prepared large as \n \/\/ was possible, we instead break up the batches such that the performance gains for writing to \n \/\/ leveldb are still realized but the memory spikes are not seen.\n nBatchSize += nUsage;\n if (nBatchSize > nCoinCacheUsage * 0.01)\n {\n db.WriteBatch(batch);\n batch.Clear();\n nBatchSize = 0;\n nBatchWrites++;\n }\n }\n else\n it++;\n count++;\n }\n if (!hashBlock.IsNull())\n batch.Write(DB_BEST_BLOCK, hashBlock);\n\n bool ret = db.WriteBatch(batch);\n LogPrint(\"coindb\", \"Committing %u changed transactions (out of %u) to coin database with %u batch writes...\\n\", (unsigned int)changed, (unsigned int)count, (unsigned int)nBatchWrites);\n return ret;\n}\n\nsize_t CCoinsViewDB::EstimateSize() const\n{\n return db.EstimateSize(DB_COIN, (char)(DB_COIN+1));\n}\n\nCBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() \/ \"blocks\" \/ \"index\", nCacheSize, fMemory, fWipe) {\n}\n\nbool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {\n return Read(make_pair(DB_BLOCK_FILES, nFile), info);\n}\n\nbool CBlockTreeDB::WriteReindexing(bool fReindexing) {\n if (fReindexing)\n return Write(DB_REINDEX_FLAG, '1');\n else\n return Erase(DB_REINDEX_FLAG);\n}\n\nbool CBlockTreeDB::ReadReindexing(bool &fReindexing) {\n fReindexing = Exists(DB_REINDEX_FLAG);\n return true;\n}\n\nbool CBlockTreeDB::ReadLastBlockFile(int &nFile) {\n return Read(DB_LAST_BLOCK, nFile);\n}\n\nCCoinsViewCursor *CCoinsViewDB::Cursor() const\n{\n CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper*>(&db)->NewIterator(), GetBestBlock());\n \/* It seems that there are no \"const iterators\" for LevelDB. Since we\n only need read operations on it, use a const-cast to get around\n that restriction. *\/\n i->pcursor->Seek(DB_COIN);\n \/\/ Cache key of first record\n if (i->pcursor->Valid()) {\n CoinEntry entry(&i->keyTmp.second);\n i->pcursor->GetKey(entry);\n i->keyTmp.first = entry.key;\n } else {\n i->keyTmp.first = 0; \/\/ Make sure Valid() and GetKey() return false\n }\n return i;\n}\n\nbool CCoinsViewDBCursor::GetKey(COutPoint &key) const\n{\n \/\/ Return cached key\n if (keyTmp.first == DB_COIN) {\n key = keyTmp.second;\n return true;\n }\n return false;\n}\n\nbool CCoinsViewDBCursor::GetValue(Coin &coin) const\n{\n return pcursor->GetValue(coin);\n}\n\nunsigned int CCoinsViewDBCursor::GetValueSize() const\n{\n return pcursor->GetValueSize();\n}\n\nbool CCoinsViewDBCursor::Valid() const\n{\n return keyTmp.first == DB_COIN;\n}\n\nvoid CCoinsViewDBCursor::Next()\n{\n pcursor->Next();\n CoinEntry entry(&keyTmp.second);\n if (!pcursor->Valid() || !pcursor->GetKey(entry)) {\n keyTmp.first = 0; \/\/ Invalidate cached key after last record so that Valid() and GetKey() return false\n } else {\n keyTmp.first = entry.key;\n }\n}\n\nbool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {\n CDBBatch batch(*this);\n for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {\n batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);\n }\n batch.Write(DB_LAST_BLOCK, nLastFile);\n for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {\n batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));\n }\n return WriteBatch(batch, true);\n}\n\nbool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {\n return Read(make_pair(DB_TXINDEX, txid), pos);\n}\n\nbool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {\n CDBBatch batch(*this);\n for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)\n batch.Write(make_pair(DB_TXINDEX, it->first), it->second);\n return WriteBatch(batch);\n}\n\nbool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {\n return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');\n}\n\nbool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {\n char ch;\n if (!Read(std::make_pair(DB_FLAG, name), ch))\n return false;\n fValue = ch == '1';\n return true;\n}\n\nbool CBlockTreeDB::LoadBlockIndexGuts()\n{\n boost::scoped_ptr<CDBIterator> pcursor(NewIterator());\n\n pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));\n\n \/\/ Load mapBlockIndex\n while (pcursor->Valid()) {\n boost::this_thread::interruption_point();\n std::pair<char, uint256> key;\n if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {\n CDiskBlockIndex diskindex;\n if (pcursor->GetValue(diskindex)) {\n \/\/ Construct block index object\n CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());\n pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);\n pindexNew->nHeight = diskindex.nHeight;\n pindexNew->nFile = diskindex.nFile;\n pindexNew->nDataPos = diskindex.nDataPos;\n pindexNew->nUndoPos = diskindex.nUndoPos;\n pindexNew->nVersion = diskindex.nVersion;\n pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;\n pindexNew->nTime = diskindex.nTime;\n pindexNew->nBits = diskindex.nBits;\n pindexNew->nNonce = diskindex.nNonce;\n pindexNew->nStatus = diskindex.nStatus;\n pindexNew->nTx = diskindex.nTx;\n\n if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))\n return error(\"LoadBlockIndex(): CheckProofOfWork failed: %s\", pindexNew->ToString());\n\n pcursor->Next();\n } else {\n return error(\"LoadBlockIndex() : failed to read value\");\n }\n } else {\n break;\n }\n }\n\n return true;\n}\n\nnamespace {\n\n\/\/! Legacy class to deserialize pre-pertxout database entries without reindex.\nclass CCoins\n{\npublic:\n \/\/! whether transaction is a coinbase\n bool fCoinBase;\n\n \/\/! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped\n std::vector<CTxOut> vout;\n\n \/\/! at which height this transaction was included in the active block chain\n int nHeight;\n\n \/\/! empty constructor\n CCoins() : fCoinBase(false), vout(0), nHeight(0) { }\n\n template<typename Stream>\n void Unserialize(Stream &s) {\n unsigned int nCode = 0;\n \/\/ version\n int nVersionDummy;\n ::Unserialize(s, VARINT(nVersionDummy));\n \/\/ header code\n ::Unserialize(s, VARINT(nCode));\n fCoinBase = nCode & 1;\n std::vector<bool> vAvail(2, false);\n vAvail[0] = (nCode & 2) != 0;\n vAvail[1] = (nCode & 4) != 0;\n unsigned int nMaskCode = (nCode \/ 8) + ((nCode & 6) != 0 ? 0 : 1);\n \/\/ spentness bitmask\n while (nMaskCode > 0) {\n unsigned char chAvail = 0;\n ::Unserialize(s, chAvail);\n for (unsigned int p = 0; p < 8; p++) {\n bool f = (chAvail & (1 << p)) != 0;\n vAvail.push_back(f);\n }\n if (chAvail != 0)\n nMaskCode--;\n }\n \/\/ txouts themself\n vout.assign(vAvail.size(), CTxOut());\n for (unsigned int i = 0; i < vAvail.size(); i++) {\n if (vAvail[i])\n ::Unserialize(s, REF(CTxOutCompressor(vout[i])));\n }\n \/\/ coinbase height\n ::Unserialize(s, VARINT(nHeight));\n }\n};\n\n}\n\n\/** Upgrade the database from older formats.\n *\n * Currently implemented: from the per-tx utxo model (0.8..0.14.x) to per-txout.\n *\/\nbool CCoinsViewDB::Upgrade() {\n std::unique_ptr<CDBIterator> pcursor(db.NewIterator());\n pcursor->Seek(std::make_pair(DB_COINS, uint256()));\n if (!pcursor->Valid()) {\n return true;\n }\n\n LogPrintf(\"Upgrading database...\\n\");\n uiInterface.InitMessage(_(\"Upgrading database...this may take a while\"));\n size_t batch_size = 1 << 24;\n CDBBatch batch(db);\n while (pcursor->Valid()) {\n boost::this_thread::interruption_point();\n std::pair<unsigned char, uint256> key;\n if (pcursor->GetKey(key) && key.first == DB_COINS) {\n CCoins old_coins;\n if (!pcursor->GetValue(old_coins)) {\n return error(\"%s: cannot parse CCoins record\", __func__);\n }\n COutPoint outpoint(key.second, 0);\n for (size_t i = 0; i < old_coins.vout.size(); ++i) {\n if (!old_coins.vout[i].IsNull() && !old_coins.vout[i].scriptPubKey.IsUnspendable()) {\n Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight, old_coins.fCoinBase);\n outpoint.n = i;\n CoinEntry entry(&outpoint);\n batch.Write(entry, newcoin);\n }\n }\n batch.Erase(key);\n if (batch.SizeEstimate() > batch_size) {\n db.WriteBatch(batch);\n batch.Clear();\n }\n pcursor->Next();\n } else {\n break;\n }\n }\n db.WriteBatch(batch);\n return true;\n}\n<commit_msg>Force on-the-fly compaction during pertxout upgrade<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2015-2017 The Bitcoin Unlimited developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"txdb.h\"\n\n#include \"chain.h\"\n#include \"chainparams.h\"\n#include \"hash.h\"\n#include \"main.h\"\n#include \"pow.h\"\n#include \"uint256.h\"\n#include \"ui_interface.h\"\n\n#include <stdint.h>\n\nusing namespace std;\n\nstatic const char DB_COIN = 'C';\nstatic const char DB_COINS = 'c';\nstatic const char DB_BLOCK_FILES = 'f';\nstatic const char DB_TXINDEX = 't';\nstatic const char DB_BLOCK_INDEX = 'b';\n\nstatic const char DB_BEST_BLOCK = 'B';\nstatic const char DB_FLAG = 'F';\nstatic const char DB_REINDEX_FLAG = 'R';\nstatic const char DB_LAST_BLOCK = 'l';\n\nnamespace {\n\nstruct CoinEntry {\n COutPoint* outpoint;\n char key;\n CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {}\n\n template<typename Stream>\n void Serialize(Stream &s) const {\n s << key;\n s << outpoint->hash;\n s << VARINT(outpoint->n);\n }\n\n template<typename Stream>\n void Unserialize(Stream& s) {\n s >> key;\n s >> outpoint->hash;\n s >> VARINT(outpoint->n);\n }\n};\n\n}\n\nCCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() \/ \"chainstate\", nCacheSize, fMemory, fWipe, true)\n{\n}\n\nbool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const {\n return db.Read(CoinEntry(&outpoint), coin);\n}\n\nbool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const {\n return db.Exists(CoinEntry(&outpoint));\n}\n\nuint256 CCoinsViewDB::GetBestBlock() const {\n LOCK(cs_utxo);\n uint256 hashBestChain;\n if (!db.Read(DB_BEST_BLOCK, hashBestChain))\n return uint256();\n return hashBestChain;\n}\n\nbool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage)\n{\n LOCK(cs_utxo);\n CDBBatch batch(db);\n size_t count = 0;\n size_t changed = 0;\n size_t nBatchSize = 0;\n size_t nBatchWrites = 0;\n for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();)\n {\n if (it->second.flags & CCoinsCacheEntry::DIRTY)\n {\n CoinEntry entry(&it->first);\n size_t nUsage = it->second.coin.DynamicMemoryUsage();\n if (it->second.coin.IsSpent())\n {\n batch.Erase(entry);\n\n \/\/ Update the usage of the child cache before deleting the entry in the child cache\n nChildCachedCoinsUsage -= nUsage;\n it = mapCoins.erase(it);\n }\n else\n {\n batch.Write(entry, it->second.coin);\n\n \/\/ Only delete valid coins from the cache when we're nearly syncd. During IBD, and also\n \/\/ if BlockOnly mode is turned on, these coins will be used, whereas, once the chain is\n \/\/ syncd we only need the coins that have come from accepting txns into the memory pool.\n bool fBlocksOnly = GetBoolArg(\"-blocksonly\", DEFAULT_BLOCKSONLY);\n if (IsChainNearlySyncd() && !fImporting && !fReindex && !fBlocksOnly)\n {\n \/\/ Update the usage of the child cache before deleting the entry in the child cache\n nChildCachedCoinsUsage -= nUsage;\n it = mapCoins.erase(it);\n }\n else\n {\n it->second.flags = 0;\n it++;\n }\n }\n changed++;\n\n \/\/ In order to prevent the spikes in memory usage that used to happen when we prepared large as \n \/\/ was possible, we instead break up the batches such that the performance gains for writing to \n \/\/ leveldb are still realized but the memory spikes are not seen.\n nBatchSize += nUsage;\n if (nBatchSize > nCoinCacheUsage * 0.01)\n {\n db.WriteBatch(batch);\n batch.Clear();\n nBatchSize = 0;\n nBatchWrites++;\n }\n }\n else\n it++;\n count++;\n }\n if (!hashBlock.IsNull())\n batch.Write(DB_BEST_BLOCK, hashBlock);\n\n bool ret = db.WriteBatch(batch);\n LogPrint(\"coindb\", \"Committing %u changed transactions (out of %u) to coin database with %u batch writes...\\n\", (unsigned int)changed, (unsigned int)count, (unsigned int)nBatchWrites);\n return ret;\n}\n\nsize_t CCoinsViewDB::EstimateSize() const\n{\n return db.EstimateSize(DB_COIN, (char)(DB_COIN+1));\n}\n\nCBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() \/ \"blocks\" \/ \"index\", nCacheSize, fMemory, fWipe) {\n}\n\nbool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {\n return Read(make_pair(DB_BLOCK_FILES, nFile), info);\n}\n\nbool CBlockTreeDB::WriteReindexing(bool fReindexing) {\n if (fReindexing)\n return Write(DB_REINDEX_FLAG, '1');\n else\n return Erase(DB_REINDEX_FLAG);\n}\n\nbool CBlockTreeDB::ReadReindexing(bool &fReindexing) {\n fReindexing = Exists(DB_REINDEX_FLAG);\n return true;\n}\n\nbool CBlockTreeDB::ReadLastBlockFile(int &nFile) {\n return Read(DB_LAST_BLOCK, nFile);\n}\n\nCCoinsViewCursor *CCoinsViewDB::Cursor() const\n{\n CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper*>(&db)->NewIterator(), GetBestBlock());\n \/* It seems that there are no \"const iterators\" for LevelDB. Since we\n only need read operations on it, use a const-cast to get around\n that restriction. *\/\n i->pcursor->Seek(DB_COIN);\n \/\/ Cache key of first record\n if (i->pcursor->Valid()) {\n CoinEntry entry(&i->keyTmp.second);\n i->pcursor->GetKey(entry);\n i->keyTmp.first = entry.key;\n } else {\n i->keyTmp.first = 0; \/\/ Make sure Valid() and GetKey() return false\n }\n return i;\n}\n\nbool CCoinsViewDBCursor::GetKey(COutPoint &key) const\n{\n \/\/ Return cached key\n if (keyTmp.first == DB_COIN) {\n key = keyTmp.second;\n return true;\n }\n return false;\n}\n\nbool CCoinsViewDBCursor::GetValue(Coin &coin) const\n{\n return pcursor->GetValue(coin);\n}\n\nunsigned int CCoinsViewDBCursor::GetValueSize() const\n{\n return pcursor->GetValueSize();\n}\n\nbool CCoinsViewDBCursor::Valid() const\n{\n return keyTmp.first == DB_COIN;\n}\n\nvoid CCoinsViewDBCursor::Next()\n{\n pcursor->Next();\n CoinEntry entry(&keyTmp.second);\n if (!pcursor->Valid() || !pcursor->GetKey(entry)) {\n keyTmp.first = 0; \/\/ Invalidate cached key after last record so that Valid() and GetKey() return false\n } else {\n keyTmp.first = entry.key;\n }\n}\n\nbool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {\n CDBBatch batch(*this);\n for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {\n batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);\n }\n batch.Write(DB_LAST_BLOCK, nLastFile);\n for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {\n batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));\n }\n return WriteBatch(batch, true);\n}\n\nbool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {\n return Read(make_pair(DB_TXINDEX, txid), pos);\n}\n\nbool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {\n CDBBatch batch(*this);\n for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)\n batch.Write(make_pair(DB_TXINDEX, it->first), it->second);\n return WriteBatch(batch);\n}\n\nbool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {\n return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');\n}\n\nbool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {\n char ch;\n if (!Read(std::make_pair(DB_FLAG, name), ch))\n return false;\n fValue = ch == '1';\n return true;\n}\n\nbool CBlockTreeDB::LoadBlockIndexGuts()\n{\n boost::scoped_ptr<CDBIterator> pcursor(NewIterator());\n\n pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));\n\n \/\/ Load mapBlockIndex\n while (pcursor->Valid()) {\n boost::this_thread::interruption_point();\n std::pair<char, uint256> key;\n if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {\n CDiskBlockIndex diskindex;\n if (pcursor->GetValue(diskindex)) {\n \/\/ Construct block index object\n CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());\n pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);\n pindexNew->nHeight = diskindex.nHeight;\n pindexNew->nFile = diskindex.nFile;\n pindexNew->nDataPos = diskindex.nDataPos;\n pindexNew->nUndoPos = diskindex.nUndoPos;\n pindexNew->nVersion = diskindex.nVersion;\n pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;\n pindexNew->nTime = diskindex.nTime;\n pindexNew->nBits = diskindex.nBits;\n pindexNew->nNonce = diskindex.nNonce;\n pindexNew->nStatus = diskindex.nStatus;\n pindexNew->nTx = diskindex.nTx;\n\n if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))\n return error(\"LoadBlockIndex(): CheckProofOfWork failed: %s\", pindexNew->ToString());\n\n pcursor->Next();\n } else {\n return error(\"LoadBlockIndex() : failed to read value\");\n }\n } else {\n break;\n }\n }\n\n return true;\n}\n\nnamespace {\n\n\/\/! Legacy class to deserialize pre-pertxout database entries without reindex.\nclass CCoins\n{\npublic:\n \/\/! whether transaction is a coinbase\n bool fCoinBase;\n\n \/\/! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped\n std::vector<CTxOut> vout;\n\n \/\/! at which height this transaction was included in the active block chain\n int nHeight;\n\n \/\/! empty constructor\n CCoins() : fCoinBase(false), vout(0), nHeight(0) { }\n\n template<typename Stream>\n void Unserialize(Stream &s) {\n unsigned int nCode = 0;\n \/\/ version\n int nVersionDummy;\n ::Unserialize(s, VARINT(nVersionDummy));\n \/\/ header code\n ::Unserialize(s, VARINT(nCode));\n fCoinBase = nCode & 1;\n std::vector<bool> vAvail(2, false);\n vAvail[0] = (nCode & 2) != 0;\n vAvail[1] = (nCode & 4) != 0;\n unsigned int nMaskCode = (nCode \/ 8) + ((nCode & 6) != 0 ? 0 : 1);\n \/\/ spentness bitmask\n while (nMaskCode > 0) {\n unsigned char chAvail = 0;\n ::Unserialize(s, chAvail);\n for (unsigned int p = 0; p < 8; p++) {\n bool f = (chAvail & (1 << p)) != 0;\n vAvail.push_back(f);\n }\n if (chAvail != 0)\n nMaskCode--;\n }\n \/\/ txouts themself\n vout.assign(vAvail.size(), CTxOut());\n for (unsigned int i = 0; i < vAvail.size(); i++) {\n if (vAvail[i])\n ::Unserialize(s, REF(CTxOutCompressor(vout[i])));\n }\n \/\/ coinbase height\n ::Unserialize(s, VARINT(nHeight));\n }\n};\n\n}\n\n\/** Upgrade the database from older formats.\n *\n * Currently implemented: from the per-tx utxo model (0.8..0.14.x) to per-txout.\n *\/\nbool CCoinsViewDB::Upgrade() {\n std::unique_ptr<CDBIterator> pcursor(db.NewIterator());\n pcursor->Seek(std::make_pair(DB_COINS, uint256()));\n if (!pcursor->Valid()) {\n return true;\n }\n\n LogPrintf(\"Upgrading database...\\n\");\n uiInterface.InitMessage(_(\"Upgrading database...this may take a while\"));\n size_t batch_size = 1 << 24;\n CDBBatch batch(db);\n\n int reportDone = 0;\n std::pair<unsigned char, uint256> key;\n std::pair<unsigned char, uint256> prev_key = {DB_COINS, uint256()};\n while (pcursor->Valid()) {\n boost::this_thread::interruption_point();\n\n if (pcursor->GetKey(key) && key.first == DB_COINS) {\n CCoins old_coins;\n if (!pcursor->GetValue(old_coins)) {\n return error(\"%s: cannot parse CCoins record\", __func__);\n }\n COutPoint outpoint(key.second, 0);\n for (size_t i = 0; i < old_coins.vout.size(); ++i) {\n if (!old_coins.vout[i].IsNull() && !old_coins.vout[i].scriptPubKey.IsUnspendable()) {\n Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight, old_coins.fCoinBase);\n outpoint.n = i;\n CoinEntry entry(&outpoint);\n batch.Write(entry, newcoin);\n }\n }\n batch.Erase(key);\n if (batch.SizeEstimate() > batch_size) {\n db.WriteBatch(batch);\n batch.Clear();\n db.CompactRange(prev_key, key);\n prev_key = key;\n }\n pcursor->Next();\n } else {\n break;\n }\n }\n db.WriteBatch(batch);\n\n db.CompactRange({DB_COINS, uint256()}, key);\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, squirreldb. 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 <string>\n\n\/\/ db\nint CONF_db_file_size = 1; \/\/ file size in MB\n\n\/\/ sdk\nint CONF_sdk_thread_num = 4;\nint CONF_sdk_put_pending = 1;\n\n\/\/ server\nstd::string CONF_server_addr = \"st01-spi-session1.st01.baidu.com\";\n\/\/std::string CONF_server_addr = \"yq01-tera-dev1.yq01.baidu.com\";\nstd::string CONF_server_port = \"8221\";\n<commit_msg>localhost<commit_after>\/\/ Copyright (c) 2015, squirreldb. 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 <string>\n\n\/\/ db\nint CONF_db_file_size = 1; \/\/ file size in MB\n\n\/\/ sdk\nint CONF_sdk_thread_num = 4;\nint CONF_sdk_put_pending = 1;\n\n\/\/ server\nstd::string CONF_server_addr = \"localhost\";\nstd::string CONF_server_port = \"8221\";\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\nnamespace nano\n{\nenum class timer_state\n{\n\tstarted,\n\tstopped\n};\n\n\/** Timer utility with nesting support *\/\ntemplate <typename UNIT = std::chrono::milliseconds>\nclass timer\n{\npublic:\n\ttimer () = default;\n\n\ttimer (nano::timer_state state_a, std::string description_a = \"timer\") :\n\tdesc (description_a)\n\t{\n\t\tif (state_a == nano::timer_state::started)\n\t\t{\n\t\t\tstart ();\n\t\t}\n\t}\n\n\ttimer (std::string description_a) :\n\tdesc (description_a)\n\t{\n\t}\n\n\ttimer (std::string description_a, timer * parent_a) :\n\tdesc (description_a), parent (parent_a)\n\t{\n\t}\n\n\t\/** Do not output if measured time is below the time units threshold in \\p minimum_a *\/\n\ttimer & set_minimum (UNIT minimum_a)\n\t{\n\t\tminimum = minimum_a;\n\t\treturn *this;\n\t}\n\n\t\/**\n\t * Create a child timer without starting it.\n\t * Since the timing API needs to have low overhead, this function\n\t * does not check if a timer with the same name already exists.\n\t *\/\n\ttimer & child (std::string description_a = \"child timer\")\n\t{\n\t\tchildren.emplace_back (description_a, this);\n\t\treturn children.back ();\n\t}\n\n\t\/** Create and start a child timer *\/\n\ttimer & start_child (std::string description_a = \"child timer\")\n\t{\n\t\tauto & child_timer = child (description_a);\n\t\tchild_timer.start ();\n\t\treturn child_timer;\n\t}\n\n\t\/** Start the timer. This will assert if the timer is already started. *\/\n\tvoid start ()\n\t{\n\t\tassert (state == nano::timer_state::stopped);\n\t\tstate = nano::timer_state::started;\n\t\tbegin = std::chrono::high_resolution_clock::now ();\n\t}\n\n\t\/** Restarts the timer *\/\n\tvoid restart ()\n\t{\n\t\tstate = nano::timer_state::started;\n\t\tbegin = std::chrono::high_resolution_clock::now ();\n\t\tticks = UNIT::zero ();\n\t\tmeasurements = 0;\n\t}\n\n\t\/**\n\t * Stops the timer and increases the measurement count. A timer can be started and paused\n\t * multiple times (e.g. in a loop).\n\t * @return duration\n\t *\/\n\tUNIT pause ()\n\t{\n\t\t++measurements;\n\t\treturn stop ();\n\t}\n\n\t\/**\n\t * Stop timer\n\t * @return duration\n\t *\/\n\tUNIT stop ()\n\t{\n\t\tassert (state == nano::timer_state::started);\n\t\tstate = nano::timer_state::stopped;\n\n\t\tauto end = std::chrono::high_resolution_clock::now ();\n\t\tticks += std::chrono::duration_cast<UNIT> (end - begin);\n\t\treturn ticks;\n\t}\n\n\t\/**\n\t * Return current units.\n\t *\/\n\tUNIT value ()\n\t{\n\t\treturn ticks;\n\t}\n\n\t\/** Returns the duration in UNIT since the timer was last started. *\/\n\tUNIT since_start ()\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now ();\n\t\treturn std::chrono::duration_cast<UNIT> (end - begin);\n\t}\n\n\t\/** Returns true if the timer was last started longer than \\p duration_a units ago*\/\n\tbool after_deadline (UNIT duration_a)\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now ();\n\t\treturn std::chrono::duration_cast<UNIT> (end - begin) > duration_a;\n\t}\n\n\t\/** Returns true if the timer was last started shorter than \\p duration_a units ago*\/\n\tbool before_deadline (UNIT duration_a)\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now ();\n\t\treturn std::chrono::duration_cast<UNIT> (end - begin) < duration_a;\n\t}\n\n\t\/** Stop timer and write measurements to \\p output_a *\/\n\tvoid stop (std::string & output_a)\n\t{\n\t\tstd::ostringstream stream;\n\t\tstop (stream);\n\t\toutput_a = stream.str ();\n\t}\n\n\t\/** Stop timer and write measurements to \\p stream_a *\/\n\tvoid stop (std::ostream & stream_a)\n\t{\n\t\tstop ();\n\t\tprint (stream_a);\n\t}\n\n\t\/** Print measurements to the \\p stream_a *\/\n\tvoid print (std::ostream & stream_a)\n\t{\n\t\tif (ticks >= minimum)\n\t\t{\n\t\t\t\/\/ Print cumulative children first. Non-cumulative children prints directly.\n\t\t\tfor (auto & child : children)\n\t\t\t{\n\t\t\t\tif (child.measurements > 0)\n\t\t\t\t{\n\t\t\t\t\tchild.print (stream_a);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauto current_parent = parent;\n\t\t\twhile (current_parent)\n\t\t\t{\n\t\t\t\tstream_a << parent->desc << \".\";\n\t\t\t\tcurrent_parent = current_parent->parent;\n\t\t\t}\n\n\t\t\tstream_a << desc << \": \" << ticks.count () << ' ' << unit ();\n\t\t\tif (measurements > 0)\n\t\t\t{\n\t\t\t\tstream_a << \" (\" << measurements << \" measurements, \" << std::setprecision (2) << std::fixed << static_cast<double> (ticks.count ()) \/ static_cast<double> (measurements) << ' ' << unit () << \" avg)\";\n\t\t\t}\n\t\t\tstream_a << std::endl;\n\t\t}\n\t}\n\n\t\/** Returns the SI unit string *\/\n\tstd::string unit () const\n\t{\n\t\treturn typed_unit<UNIT> ();\n\t}\n\n\tnano::timer_state current_state () const\n\t{\n\t\treturn state;\n\t}\n\nprivate:\n\ttimer * parent{ nullptr };\n\tstd::vector<timer> children;\n\tnano::timer_state state{ nano::timer_state::stopped };\n\tstd::string desc;\n\tstd::chrono::time_point<std::chrono::high_resolution_clock> begin;\n\tUNIT ticks{ 0 };\n\tUNIT minimum{ UNIT::zero () };\n\tunsigned measurements{ 0 };\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::nanoseconds>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"nanoseconds\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::microseconds>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"microseconds\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::milliseconds>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"milliseconds\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::seconds>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"seconds\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::minutes>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"minutes\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::hours>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"hours\";\n\t}\n};\n\n\/**\n * The autotimer starts on construction, and stops and prints on destruction.\n *\/\ntemplate <typename UNIT = std::chrono::milliseconds>\nclass autotimer : public nano::timer<UNIT>\n{\npublic:\n\tautotimer (std::string description_a, std::ostream & stream_a = std::cout) :\n\tnano::timer<UNIT> (description_a), stream (stream_a)\n\t{\n\t\tnano::timer<UNIT>::start ();\n\t}\n\t~autotimer ()\n\t{\n\t\tnano::timer<UNIT>::stop (stream);\n\t}\n\nprivate:\n\tstd::ostream & stream;\n};\n}\n<commit_msg>Add missing headers in timer (#1673)<commit_after>#pragma once\n\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace nano\n{\nenum class timer_state\n{\n\tstarted,\n\tstopped\n};\n\n\/** Timer utility with nesting support *\/\ntemplate <typename UNIT = std::chrono::milliseconds>\nclass timer\n{\npublic:\n\ttimer () = default;\n\n\ttimer (nano::timer_state state_a, std::string description_a = \"timer\") :\n\tdesc (description_a)\n\t{\n\t\tif (state_a == nano::timer_state::started)\n\t\t{\n\t\t\tstart ();\n\t\t}\n\t}\n\n\ttimer (std::string description_a) :\n\tdesc (description_a)\n\t{\n\t}\n\n\ttimer (std::string description_a, timer * parent_a) :\n\tdesc (description_a), parent (parent_a)\n\t{\n\t}\n\n\t\/** Do not output if measured time is below the time units threshold in \\p minimum_a *\/\n\ttimer & set_minimum (UNIT minimum_a)\n\t{\n\t\tminimum = minimum_a;\n\t\treturn *this;\n\t}\n\n\t\/**\n\t * Create a child timer without starting it.\n\t * Since the timing API needs to have low overhead, this function\n\t * does not check if a timer with the same name already exists.\n\t *\/\n\ttimer & child (std::string description_a = \"child timer\")\n\t{\n\t\tchildren.emplace_back (description_a, this);\n\t\treturn children.back ();\n\t}\n\n\t\/** Create and start a child timer *\/\n\ttimer & start_child (std::string description_a = \"child timer\")\n\t{\n\t\tauto & child_timer = child (description_a);\n\t\tchild_timer.start ();\n\t\treturn child_timer;\n\t}\n\n\t\/** Start the timer. This will assert if the timer is already started. *\/\n\tvoid start ()\n\t{\n\t\tassert (state == nano::timer_state::stopped);\n\t\tstate = nano::timer_state::started;\n\t\tbegin = std::chrono::high_resolution_clock::now ();\n\t}\n\n\t\/** Restarts the timer *\/\n\tvoid restart ()\n\t{\n\t\tstate = nano::timer_state::started;\n\t\tbegin = std::chrono::high_resolution_clock::now ();\n\t\tticks = UNIT::zero ();\n\t\tmeasurements = 0;\n\t}\n\n\t\/**\n\t * Stops the timer and increases the measurement count. A timer can be started and paused\n\t * multiple times (e.g. in a loop).\n\t * @return duration\n\t *\/\n\tUNIT pause ()\n\t{\n\t\t++measurements;\n\t\treturn stop ();\n\t}\n\n\t\/**\n\t * Stop timer\n\t * @return duration\n\t *\/\n\tUNIT stop ()\n\t{\n\t\tassert (state == nano::timer_state::started);\n\t\tstate = nano::timer_state::stopped;\n\n\t\tauto end = std::chrono::high_resolution_clock::now ();\n\t\tticks += std::chrono::duration_cast<UNIT> (end - begin);\n\t\treturn ticks;\n\t}\n\n\t\/**\n\t * Return current units.\n\t *\/\n\tUNIT value ()\n\t{\n\t\treturn ticks;\n\t}\n\n\t\/** Returns the duration in UNIT since the timer was last started. *\/\n\tUNIT since_start ()\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now ();\n\t\treturn std::chrono::duration_cast<UNIT> (end - begin);\n\t}\n\n\t\/** Returns true if the timer was last started longer than \\p duration_a units ago*\/\n\tbool after_deadline (UNIT duration_a)\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now ();\n\t\treturn std::chrono::duration_cast<UNIT> (end - begin) > duration_a;\n\t}\n\n\t\/** Returns true if the timer was last started shorter than \\p duration_a units ago*\/\n\tbool before_deadline (UNIT duration_a)\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now ();\n\t\treturn std::chrono::duration_cast<UNIT> (end - begin) < duration_a;\n\t}\n\n\t\/** Stop timer and write measurements to \\p output_a *\/\n\tvoid stop (std::string & output_a)\n\t{\n\t\tstd::ostringstream stream;\n\t\tstop (stream);\n\t\toutput_a = stream.str ();\n\t}\n\n\t\/** Stop timer and write measurements to \\p stream_a *\/\n\tvoid stop (std::ostream & stream_a)\n\t{\n\t\tstop ();\n\t\tprint (stream_a);\n\t}\n\n\t\/** Print measurements to the \\p stream_a *\/\n\tvoid print (std::ostream & stream_a)\n\t{\n\t\tif (ticks >= minimum)\n\t\t{\n\t\t\t\/\/ Print cumulative children first. Non-cumulative children prints directly.\n\t\t\tfor (auto & child : children)\n\t\t\t{\n\t\t\t\tif (child.measurements > 0)\n\t\t\t\t{\n\t\t\t\t\tchild.print (stream_a);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauto current_parent = parent;\n\t\t\twhile (current_parent)\n\t\t\t{\n\t\t\t\tstream_a << parent->desc << \".\";\n\t\t\t\tcurrent_parent = current_parent->parent;\n\t\t\t}\n\n\t\t\tstream_a << desc << \": \" << ticks.count () << ' ' << unit ();\n\t\t\tif (measurements > 0)\n\t\t\t{\n\t\t\t\tstream_a << \" (\" << measurements << \" measurements, \" << std::setprecision (2) << std::fixed << static_cast<double> (ticks.count ()) \/ static_cast<double> (measurements) << ' ' << unit () << \" avg)\";\n\t\t\t}\n\t\t\tstream_a << std::endl;\n\t\t}\n\t}\n\n\t\/** Returns the SI unit string *\/\n\tstd::string unit () const\n\t{\n\t\treturn typed_unit<UNIT> ();\n\t}\n\n\tnano::timer_state current_state () const\n\t{\n\t\treturn state;\n\t}\n\nprivate:\n\ttimer * parent{ nullptr };\n\tstd::vector<timer> children;\n\tnano::timer_state state{ nano::timer_state::stopped };\n\tstd::string desc;\n\tstd::chrono::time_point<std::chrono::high_resolution_clock> begin;\n\tUNIT ticks{ 0 };\n\tUNIT minimum{ UNIT::zero () };\n\tunsigned measurements{ 0 };\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::nanoseconds>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"nanoseconds\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::microseconds>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"microseconds\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::milliseconds>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"milliseconds\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::seconds>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"seconds\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::minutes>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"minutes\";\n\t}\n\n\ttemplate <typename U, std::enable_if_t<std::is_same<U, std::chrono::hours>::value> * = nullptr>\n\tstd::string typed_unit () const\n\t{\n\t\treturn \"hours\";\n\t}\n};\n\n\/**\n * The autotimer starts on construction, and stops and prints on destruction.\n *\/\ntemplate <typename UNIT = std::chrono::milliseconds>\nclass autotimer : public nano::timer<UNIT>\n{\npublic:\n\tautotimer (std::string description_a, std::ostream & stream_a = std::cout) :\n\tnano::timer<UNIT> (description_a), stream (stream_a)\n\t{\n\t\tnano::timer<UNIT>::start ();\n\t}\n\t~autotimer ()\n\t{\n\t\tnano::timer<UNIT>::stop (stream);\n\t}\n\nprivate:\n\tstd::ostream & stream;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Parser.h\"\n\n#include <iostream>\n#include <stack>\n#include <algorithm>\n\n#include <llvm\/Config\/config.h>\n\n#include <clang\/AST\/ASTConsumer.h>\n#include <clang\/Basic\/TargetInfo.h>\n#include <clang\/Frontend\/InitHeaderSearch.h>\n#include <clang\/Frontend\/TextDiagnosticPrinter.h>\n#include <clang\/Lex\/HeaderSearch.h>\n#include <clang\/Lex\/Preprocessor.h>\n#include <clang\/Sema\/ParseAST.h>\n\n#include <clang\/Basic\/TargetInfo.h>\n#include <clang\/Basic\/Diagnostic.h>\n\n#include \"ClangUtils.h\"\n#include \"SrcGen.h\"\n\n\/\/ Temporary Hax:\n#include \"InitPP.cpp\"\n\nusing std::string;\n\nnamespace ccons {\n\nParser::Parser(const clang::LangOptions& options) :\n\t_options(options),\n\t_target(clang::TargetInfo::CreateTargetInfo(LLVM_HOSTTRIPLE))\n{\n}\n\nclang::ASTContext * Parser::getContext() const\n{\n\treturn _ast.get();\n}\n\nParser::InputType Parser::analyzeInput(const string& contextSource,\n const string& buffer,\n int& indentLevel,\n const clang::FunctionDecl*& FD)\n{\n\tclang::SourceManager sm;\n\tcreateMemoryBuffer(buffer, \"\", &sm);\n\tclang::FileManager fm;\n\tclang::HeaderSearch headers(fm);\n\tclang::InitHeaderSearch ihs(headers);\n\tihs.AddDefaultEnvVarPaths(_options);\n\tihs.AddDefaultSystemIncludePaths(_options);\n\tihs.Realize();\n\tProxyDiagnosticClient pdc(NULL);\n\tclang::Diagnostic diag(&pdc);\n\tclang::Preprocessor PP(diag, _options, *_target, sm, headers);\n\n\tInitializePreprocessor(PP);\n\n\tstd::stack<std::pair<clang::Token, clang::Token> > S; \/\/ Tok, PrevTok\n\n\tindentLevel = 0;\n\tPP.EnterMainSourceFile();\n\n\tclang::Token Tok, LastTok;\n\tbool TokWasDo = false;\n\tPP.Lex(Tok);\n\twhile (Tok.isNot(clang::tok::eof)) {\n\t\tif (Tok.is(clang::tok::l_square)) {\n\t\t\tS.push(std::make_pair(Tok, LastTok)); \/\/ [\n\t\t} else if (Tok.is(clang::tok::l_paren)) {\n\t\t\tS.push(std::make_pair(Tok, LastTok)); \/\/ (\n\t\t} else if (Tok.is(clang::tok::l_brace)) {\n\t\t\tS.push(std::make_pair(Tok, LastTok)); \/\/ {\n\t\t\tindentLevel++;\n\t\t} else if (Tok.is(clang::tok::r_square)) {\n\t\t\tif (S.empty() || S.top().first.isNot(clang::tok::l_square)) {\n\t\t\t\tstd::cout << \"Unmatched [\\n\";\n\t\t\t\treturn Incomplete;\n\t\t\t}\n\t\t\tTokWasDo = false;\n\t\t\tS.pop();\n\t\t} else if (Tok.is(clang::tok::r_paren)) {\n\t\t\tif (S.empty() || S.top().first.isNot(clang::tok::l_paren)) {\n\t\t\t\tstd::cout << \"Unmatched (\\n\";\n\t\t\t\treturn Incomplete;\n\t\t\t}\n\t\t\tTokWasDo = false;\n\t\t\tS.pop();\n\t\t} else if (Tok.is(clang::tok::r_brace)) {\n\t\t\tif (S.empty() || S.top().first.isNot(clang::tok::l_brace)) {\n\t\t\t\tstd::cout << \"Unmatched {\\n\";\n\t\t\t\treturn Incomplete;\n\t\t\t}\n\t\t\tTokWasDo = S.top().second.is(clang::tok::kw_do);\n\t\t\tS.pop();\n\t\t\tindentLevel--;\n\t\t}\n\t\tLastTok = Tok;\n\t\tPP.Lex(Tok);\n\t}\n\n\t\/\/ TODO: We need to properly account for indent-level for blocks that do not\n\t\/\/ have braces... such as:\n\t\/\/\n\t\/\/ if (X)\n\t\/\/ Y;\n\t\/\/\n\t\/\/ TODO: Do-while without braces doesn't work, e.g.:\n\t\/\/\n\t\/\/ do\n\t\/\/ foo();\n\t\/\/ while (bar());\n\t\/\/\n\t\/\/ Both of the above could be solved by some kind of rewriter-pass that would\n\t\/\/ insert implicit braces (or simply a more involved analysis).\n\n\t\/\/ TokWasDo is used for do { ... } while (...); loops\n\tif (LastTok.is(clang::tok::semi) || (LastTok.is(clang::tok::r_brace) && !TokWasDo)) {\n\t\tif (!S.empty()) return Incomplete;\n\t\t\/\/ FIXME: send diagnostics to \/dev\/null\n\t\tclang::TextDiagnosticPrinter tdp(llvm::errs(), false, true, false);\n\t\ttdp.SetLangOpts(_options);\n\t\tProxyDiagnosticClient pdc(NULL);\n\t\tclang::Diagnostic diag(&pdc);\n\t\tdiag.setSuppressSystemWarnings(true);\n\t\tstring src = contextSource + buffer;\n\t\tclang::SourceManager sm;\n\t\tstruct : public clang::ASTConsumer {\n\t\t\tunsigned pos;\n\t\t\tunsigned maxPos;\n\t\t\tclang::SourceManager *sm;\n\t\t\tclang::FunctionDecl *FD;\n\t\t\tvoid HandleTopLevelDecl(clang::Decl *D) {\n\t\t\t\tif (clang::FunctionDecl *FuD = dyn_cast<clang::FunctionDecl>(D)) {\n\t\t\t\t\tclang::SourceLocation Loc = FuD->getTypeSpecStartLoc();\n\t\t\t\t\tunsigned offset = sm->getFileOffset(sm->getInstantiationLoc(Loc));\n\t\t\t\t\tif (offset == pos) {\n\t\t\t\t\t\tthis->FD = FuD;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} consumer;\n\t\tconsumer.pos = contextSource.length();\n\t\tconsumer.maxPos = consumer.pos + buffer.length();\n\t\tconsumer.sm = &sm;\n\t\tconsumer.FD = NULL;\n\t\tparse(src, &sm, &diag, &consumer);\n\t\tif (!pdc.hadErrors() && consumer.FD) {\n\t\t\tFD = consumer.FD;\n\t\t\treturn TopLevel;\n\t\t}\n\t\treturn Stmt;\n\t}\n\n\treturn Incomplete;\n}\n\nvoid Parser::parse(const string& src,\n clang::SourceManager *sm,\n clang::Diagnostic *diag,\n clang::ASTConsumer *consumer)\n{\n\tcreateMemoryBuffer(src, \"Main\", sm);\n\tclang::HeaderSearch headers(_fm);\n\tclang::InitHeaderSearch ihs(headers);\n\tihs.AddDefaultEnvVarPaths(_options);\n\tihs.AddDefaultSystemIncludePaths(_options);\n\tihs.Realize();\n\n\t_pp.reset(new clang::Preprocessor(*diag, _options, *_target, *sm, headers));\n\n\tInitializePreprocessor(*_pp);\n\n\t_ast.reset(new clang::ASTContext(_options, *sm, *_target,\n\t\t_pp->getIdentifierTable(), _pp->getSelectorTable()));\n\tclang::ParseAST(*_pp, consumer, *_ast);\n}\n\nllvm::MemoryBuffer * Parser::createMemoryBuffer(const string& src,\n const char *name,\n clang::SourceManager *sm)\n{\n\tllvm::MemoryBuffer *mb =\n\t\tllvm::MemoryBuffer::getMemBufferCopy(&*src.begin(), &*src.end(), name);\n\tassert(mb && \"Error creating MemoryBuffer!\");\n\tsm->createMainFileIDForMemBuffer(mb);\n\tassert(!sm->getMainFileID().isInvalid() && \"Error creating MainFileID!\");\n\treturn mb;\n}\n\n} \/\/ namespace ccons\n<commit_msg>ignore diagnostics<commit_after>#include \"Parser.h\"\n\n#include <iostream>\n#include <stack>\n#include <algorithm>\n\n#include <llvm\/Config\/config.h>\n\n#include <clang\/AST\/ASTConsumer.h>\n#include <clang\/Basic\/TargetInfo.h>\n#include <clang\/Frontend\/InitHeaderSearch.h>\n#include <clang\/Lex\/HeaderSearch.h>\n#include <clang\/Lex\/Preprocessor.h>\n#include <clang\/Sema\/ParseAST.h>\n\n#include <clang\/Basic\/TargetInfo.h>\n#include <clang\/Basic\/Diagnostic.h>\n\n#include \"ClangUtils.h\"\n#include \"SrcGen.h\"\n\n\/\/ Temporary Hax:\n#include \"InitPP.cpp\"\n\nusing std::string;\n\nnamespace ccons {\n\nParser::Parser(const clang::LangOptions& options) :\n\t_options(options),\n\t_target(clang::TargetInfo::CreateTargetInfo(LLVM_HOSTTRIPLE))\n{\n}\n\nclang::ASTContext * Parser::getContext() const\n{\n\treturn _ast.get();\n}\n\nParser::InputType Parser::analyzeInput(const string& contextSource,\n const string& buffer,\n int& indentLevel,\n const clang::FunctionDecl*& FD)\n{\n\tclang::SourceManager sm;\n\tcreateMemoryBuffer(buffer, \"\", &sm);\n\tclang::FileManager fm;\n\tclang::HeaderSearch headers(fm);\n\tclang::InitHeaderSearch ihs(headers);\n\tihs.AddDefaultEnvVarPaths(_options);\n\tihs.AddDefaultSystemIncludePaths(_options);\n\tihs.Realize();\n\tProxyDiagnosticClient pdc(NULL);\n\tclang::Diagnostic diag(&pdc);\n\tclang::Preprocessor PP(diag, _options, *_target, sm, headers);\n\n\tInitializePreprocessor(PP);\n\n\tstd::stack<std::pair<clang::Token, clang::Token> > S; \/\/ Tok, PrevTok\n\n\tindentLevel = 0;\n\tPP.EnterMainSourceFile();\n\n\tclang::Token Tok, LastTok;\n\tbool TokWasDo = false;\n\tPP.Lex(Tok);\n\twhile (Tok.isNot(clang::tok::eof)) {\n\t\tif (Tok.is(clang::tok::l_square)) {\n\t\t\tS.push(std::make_pair(Tok, LastTok)); \/\/ [\n\t\t} else if (Tok.is(clang::tok::l_paren)) {\n\t\t\tS.push(std::make_pair(Tok, LastTok)); \/\/ (\n\t\t} else if (Tok.is(clang::tok::l_brace)) {\n\t\t\tS.push(std::make_pair(Tok, LastTok)); \/\/ {\n\t\t\tindentLevel++;\n\t\t} else if (Tok.is(clang::tok::r_square)) {\n\t\t\tif (S.empty() || S.top().first.isNot(clang::tok::l_square)) {\n\t\t\t\tstd::cout << \"Unmatched [\\n\";\n\t\t\t\treturn Incomplete;\n\t\t\t}\n\t\t\tTokWasDo = false;\n\t\t\tS.pop();\n\t\t} else if (Tok.is(clang::tok::r_paren)) {\n\t\t\tif (S.empty() || S.top().first.isNot(clang::tok::l_paren)) {\n\t\t\t\tstd::cout << \"Unmatched (\\n\";\n\t\t\t\treturn Incomplete;\n\t\t\t}\n\t\t\tTokWasDo = false;\n\t\t\tS.pop();\n\t\t} else if (Tok.is(clang::tok::r_brace)) {\n\t\t\tif (S.empty() || S.top().first.isNot(clang::tok::l_brace)) {\n\t\t\t\tstd::cout << \"Unmatched {\\n\";\n\t\t\t\treturn Incomplete;\n\t\t\t}\n\t\t\tTokWasDo = S.top().second.is(clang::tok::kw_do);\n\t\t\tS.pop();\n\t\t\tindentLevel--;\n\t\t}\n\t\tLastTok = Tok;\n\t\tPP.Lex(Tok);\n\t}\n\n\t\/\/ TODO: We need to properly account for indent-level for blocks that do not\n\t\/\/ have braces... such as:\n\t\/\/\n\t\/\/ if (X)\n\t\/\/ Y;\n\t\/\/\n\t\/\/ TODO: Do-while without braces doesn't work, e.g.:\n\t\/\/\n\t\/\/ do\n\t\/\/ foo();\n\t\/\/ while (bar());\n\t\/\/\n\t\/\/ Both of the above could be solved by some kind of rewriter-pass that would\n\t\/\/ insert implicit braces (or simply a more involved analysis).\n\n\t\/\/ TokWasDo is used for do { ... } while (...); loops\n\tif (LastTok.is(clang::tok::semi) || (LastTok.is(clang::tok::r_brace) && !TokWasDo)) {\n\t\tif (!S.empty()) return Incomplete;\n\t\tProxyDiagnosticClient pdc(NULL); \/\/ ignore diagnostics\n\t\tclang::Diagnostic diag(&pdc);\n\t\tdiag.setSuppressSystemWarnings(true);\n\t\tstring src = contextSource + buffer;\n\t\tclang::SourceManager sm;\n\t\tstruct : public clang::ASTConsumer {\n\t\t\tunsigned pos;\n\t\t\tunsigned maxPos;\n\t\t\tclang::SourceManager *sm;\n\t\t\tclang::FunctionDecl *FD;\n\t\t\tvoid HandleTopLevelDecl(clang::Decl *D) {\n\t\t\t\tif (clang::FunctionDecl *FuD = dyn_cast<clang::FunctionDecl>(D)) {\n\t\t\t\t\tclang::SourceLocation Loc = FuD->getTypeSpecStartLoc();\n\t\t\t\t\tunsigned offset = sm->getFileOffset(sm->getInstantiationLoc(Loc));\n\t\t\t\t\tif (offset == pos) {\n\t\t\t\t\t\tthis->FD = FuD;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} consumer;\n\t\tconsumer.pos = contextSource.length();\n\t\tconsumer.maxPos = consumer.pos + buffer.length();\n\t\tconsumer.sm = &sm;\n\t\tconsumer.FD = NULL;\n\t\tparse(src, &sm, &diag, &consumer);\n\t\tif (!pdc.hadErrors() && consumer.FD) {\n\t\t\tFD = consumer.FD;\n\t\t\treturn TopLevel;\n\t\t}\n\t\treturn Stmt;\n\t}\n\n\treturn Incomplete;\n}\n\nvoid Parser::parse(const string& src,\n clang::SourceManager *sm,\n clang::Diagnostic *diag,\n clang::ASTConsumer *consumer)\n{\n\tcreateMemoryBuffer(src, \"Main\", sm);\n\tclang::HeaderSearch headers(_fm);\n\tclang::InitHeaderSearch ihs(headers);\n\tihs.AddDefaultEnvVarPaths(_options);\n\tihs.AddDefaultSystemIncludePaths(_options);\n\tihs.Realize();\n\n\t_pp.reset(new clang::Preprocessor(*diag, _options, *_target, *sm, headers));\n\n\tInitializePreprocessor(*_pp);\n\n\t_ast.reset(new clang::ASTContext(_options, *sm, *_target,\n\t\t_pp->getIdentifierTable(), _pp->getSelectorTable()));\n\tclang::ParseAST(*_pp, consumer, *_ast);\n}\n\nllvm::MemoryBuffer * Parser::createMemoryBuffer(const string& src,\n const char *name,\n clang::SourceManager *sm)\n{\n\tllvm::MemoryBuffer *mb =\n\t\tllvm::MemoryBuffer::getMemBufferCopy(&*src.begin(), &*src.end(), name);\n\tassert(mb && \"Error creating MemoryBuffer!\");\n\tsm->createMainFileIDForMemBuffer(mb);\n\tassert(!sm->getMainFileID().isInvalid() && \"Error creating MainFileID!\");\n\treturn mb;\n}\n\n} \/\/ namespace ccons\n<|endoftext|>"} {"text":"<commit_before>#include \"Piezas.h\"\n#include <vector>\n\/** CLASS Piezas\n * Class for representing a Piezas vertical board, which is roughly based\n * on the game \"Connect Four\" where pieces are placed in a column and \n * fall to the bottom of the column, or on top of other pieces already in\n * that column. For an illustration of the board, see:\n * https:\/\/en.wikipedia.org\/wiki\/Connect_Four\n *\n * Board coordinates [row,col] should match with:\n * [2,0][2,1][2,2][2,3]\n * [1,0][1,1][1,2][1,3]\n * [0,0][0,1][0,2][0,3]\n * So that a piece dropped in column 2 should take [0,2] and the next one\n * dropped in column 2 should take [1,2].\n**\/\n\n\n\/**\n * Constructor sets an empty board (default 3 rows, 4 columns) and \n * specifies it is X's turn first\n**\/\nPiezas::Piezas();\n\n\/**\n * Resets each board location to the Blank Piece value, with a board of the\n * same size as previously specified\n**\/\nvoid Piezas::reset();\n\n\/**\n * Places a piece of the current turn on the board, returns what\n * piece is placed, and toggles which Piece's turn it is. dropPiece does \n * NOT allow to place a piece in a location where a column is full.\n * In that case, placePiece returns Piece Blank value \n * Out of bounds coordinates return the Piece Invalid value\n * Trying to drop a piece where it cannot be placed loses the player's turn\n**\/ \nPiece Piezas::dropPiece(int column);\n\n\/**\n * Returns what piece is at the provided coordinates, or Blank if there\n * are no pieces there, or Invalid if the coordinates are out of bounds\n**\/\nPiece Piezas::pieceAt(int row, int column);\n\n\/**\n * Returns which Piece has won, if there is a winner, Invalid if the game\n * is not over, or Blank if the board is filled and no one has won (\"tie\").\n * For a game to be over, all locations on the board must be filled with X's \n * and O's (i.e. no remaining Blank spaces). The winner is which player has\n * the most adjacent pieces in a single line. Lines can go either vertically\n * or horizontally. If both X's and O's have the same max number of pieces in a\n * line, it is a tie.\n**\/\nPiece Piezas::gameState();<commit_msg>added Piezas.cpp<commit_after>#include \"Piezas.h\"\n#include <vector>\n#include <iostream>\n\/** CLASS Piezas\n * Class for representing a Piezas vertical board, which is roughly based\n * on the game \"Connect Four\" where pieces are placed in a column and \n * fall to the bottom of the column, or on top of other pieces already in\n * that column. For an illustration of the board, see:\n * https:\/\/en.wikipedia.org\/wiki\/Connect_Four\n *\n * Board coordinates [row,col] should match with:\n * [2,0][2,1][2,2][2,3]\n * [1,0][1,1][1,2][1,3]\n * [0,0][0,1][0,2][0,3]\n * So that a piece dropped in column 2 should take [0,2] and the next one\n * dropped in column 2 should take [1,2].\n**\/\n\n\n\/**\n * Constructor sets an empty board (default 3 rows, 4 columns) and \n * specifies it is X's turn first\n**\/\nPiezas::Piezas()\n{\n\tboard.resize(BOARD_ROWS, std::vector<Piece>(BOARD_COLS, Blank));\n\tturn = X;\n\n}\/\/end of constructor\n\n\/**\n * Resets each board location to the Blank Piece value, with a board of the\n * same size as previously specified\n**\/\nvoid Piezas::reset()\n{\n\tfor(int i=0;i < BOARD_ROWS;i++)\n\t{\n\t\tfor(int j=0;j < BOARD_COLS;j++)\n\t\t{\n\t\t\tboard[i][j]=Blank;\n\t\t}\n\t}\n}\/\/end of reset\n\n\/**\n * Places a piece of the current turn on the board, returns what\n * piece is placed, and toggles which Piece's turn it is. dropPiece does \n * NOT allow to place a piece in a location where a column is full.\n * In that case, placePiece returns Piece Blank value \n * Out of bounds coordinates return the Piece Invalid value\n * Trying to drop a piece where it cannot be placed loses the player's turn\n**\/\nPiece Piezas::toggle_piece_turn()\n{\n\tif(turn == O)\n\t{\n\t\tturn = X;\n\t}\n\telse\n\t{\n\t\tturn = O;\n\t}\n\treturn turn;\n}\n\n\nPiece Piezas::dropPiece(int column)\n{\n\t\/\/invalid column\n\tif(column > BOARD_COLS-1)\n\t{\n\n\t\ttoggle_piece_turn();\n\t\treturn Invalid;\n\t}\n\t\/\/column full\n\telse if(board[0][column] != Blank)\n\t{\n\n\t\ttoggle_piece_turn();\n\t\treturn Blank;\n\t}\n\telse\n\t{\n\t\n\t\tPiece retval;\n\t\tfor(int i = BOARD_ROWS - 1;i >= 0; i--)\n\t\t{\n\t\t\tif(board[i][column] == Blank)\n\t\t\t{\n\t\t\t\tboard[i][column] = turn;\n\t\t\t\tretval = turn;\n\t\t\t\ttoggle_piece_turn();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\t\treturn retval;\n\n\t}\t\n}\/\/end of dropPiece\n\n\/**\n * Returns what piece is at the provided coordinates, or Blank if there\n * are no pieces there, or Invalid if the coordinates are out of bounds\n**\/\nPiece Piezas::pieceAt(int row, int column)\n{\n\tif(row < 0 || row > BOARD_ROWS-1 || column < 0 || column > BOARD_COLS-1)\n\t{\n\t\treturn Invalid;\t\n\t}\n\treturn board[row][column];\n}\n\n\/**\n * Returns which Piece has won, if there is a winner, Invalid if the game\n * is not over, or Blank if the board is filled and no one has won (\"tie\").\n * For a game to be over, all locations on the board must be filled with X's \n * and O's (i.e. no remaining Blank spaces). The winner is which player has\n * the most adjacent pieces in a single line. Lines can go either vertically\n * or horizontally. If both X's and O's have the same max number of pieces in a\n * line, it is a tie.\n**\/\nPiece Piezas::gameState()\n{\n\n int numx=0;\n int numo=0;\n int maxadjx=0; \n int maxadjo=0;\n\n\/\/check for Blank\n for(int i=0;i<BOARD_ROWS;i++)\n {\n\n for(int j=0;j<BOARD_COLS;j++) \n {\n\tif(board[i][j]==Blank) \n \t{\n return Invalid;\n \t}\n\n }\n\n }\n\n\/\/check within rows\n for(int i=0;i<BOARD_ROWS;i++)\n {\n for(int j=0;j<BOARD_COLS;j++)\n {\n if(board[i][j]==O)\n {\n numo++;\n if(numo>maxadjo)\n\t {\n maxadjo=numo;\n }\n numx=0;\n }\n else \n {\n numx++;\n if(numx>maxadjx)\n\t{\n maxadjx=numx;\n\t}\n numo=0;\n }\n }\n numx=0; \n numo=0;\n }\n numx=0; \n numo=0;\n\n\/\/check within cols\n for(int j=0;j<BOARD_COLS;j++)\n {\n for(int i=0;i<BOARD_ROWS;i++) \n {\n if(board[i][j]==O)\n {\n numo++;\n if(numo>maxadjo)\n\t{\n maxadjo=numo;\n\t}\n numx=0;\n }\n else \n {\n numx++;\n if(numx>maxadjx)\n\t{\n maxadjx=numx;\n\t}\n numo=0;\n }\n }\n\n numx=0; \n numo=0;\n }\n\n if(maxadjx < maxadjo)\n {\n return O; \/\/O winner\n }\n else if(maxadjo < maxadjx) \n {\n return X; \/\/X winner\n }\n else if(maxadjx == maxadjo )\n {\n return Blank; \/\/equal \n }\n return Blank;\n\n}\/\/end of gameState\n<|endoftext|>"} {"text":"<commit_before>#include \"GLWidget.h\"\n\n#include \"tiny_obj_loader.h\"\n\n#include <iostream>\n\n#include <glm\/gtx\/transform.hpp>\n#include <QApplication>\n\n\nGLWidget::GLWidget ( QWidget* parent, Qt::WindowFlags f ) : QOpenGLWidget ( parent, f )\n{\n\t\n\tsetFocusPolicy(Qt::ClickFocus);\n\t\n\tconnect(&time, &QTimer::timeout, [this]\n\t\t{\n\t\t\tthis->update();\n\t\t});\n\ttime.start(0);\n\t\n\tQSurfaceFormat format;\n\tformat.setMajorVersion(3);\n\tformat.setMinorVersion(3);\n\t\n\tformat.setSamples(8);\n\t\n\tsetFormat(format);\n\t\n}\n\nbool GLWidget::event (QEvent* event)\n{\n\n\tswitch(event->type())\n\t{\n\tcase QEvent::Type::MouseButtonPress:\n\t\t{\n\t\t\tauto mousePressEvent = static_cast<QMouseEvent*>(event);\n\t\t\tif(mousePressEvent->button() == Qt::LeftButton)\n\t\t\t{\n\t\t\t\tisMouseDown = true;\n\t\t\t\tlastMousePos = { mousePressEvent->x(), mousePressEvent->y() };\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase QEvent::Type::MouseButtonRelease:\n\t\t{\n\t\t\tauto mousePressEvent = static_cast<QMouseEvent*>(event);\n\t\t\tif(mousePressEvent->button() == Qt::LeftButton)\n\t\t\t{\n\t\t\t\tisMouseDown = false;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase QEvent::Type::MouseMove:\n\t\t{\n\t\t\tauto mousePressEvent = static_cast<QMouseEvent*>(event);\n\t\t\tif(isMouseDown)\n\t\t\t{\n\t\t\t\tglm::ivec2 currentMouse = { mousePressEvent->x(), mousePressEvent->y() };\n\t\t\t\t\n\t\t\t\tglm::ivec2 deltaMouse = currentMouse - lastMousePos;\n\t\t\t\t\n\t\t\t\tauto forVecIntX = glm::rotate((float)deltaMouse.x \/ 1000.f, glm::vec3{0.f, 0.f, 1.f}) * glm::vec4(forwardVector, 0.f);\n\t\t\t\tforwardVector = {forVecIntX.x, forVecIntX.y, forVecIntX.z};\n\t\t\t\t\n\t\t\t\tauto forVecIntY = glm::rotate(-(float)deltaMouse.y \/ 1000.f, glm::vec3{1.f, 0.f, 0.f}) * glm::vec4(forwardVector, 0.f);\n\t\t\t\tforwardVector = {forVecIntY.x, forVecIntY.y, forVecIntY.z};\n\t\t\t\t\n\t\t\t\tlastMousePos = currentMouse;\n\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tdefault: break;\n\t}\n\n\treturn QOpenGLWidget::event(event);\n}\n\n\nstd::array<float, 3> fromRGB(unsigned char r, unsigned char g, unsigned char b)\n{\n\treturn{ (float)r \/ 255.f, (float)g \/ 255.f, (float)b \/ 255.f };\n}\n\nvoid GLWidget::markForRegeneration()\n{\n\tneedsRegenerate = true;\n}\n\nvoid GLWidget::markForSave(const QString& saveDest)\n{\n\tneedsSave = true;\n\tsavePath = saveDest;\n}\n\n\n\n\nstd::array<float, 3> fromHex(uint32_t color)\n{\n return fromRGB(color >> 24, color << 8 >> 24, color << 16 >> 24);\n}\n\n\n\n\nvoid GLWidget::keyPressEvent ( QKeyEvent* event )\n{\n\tQWidget::keyPressEvent ( event );\n\t\t\n\tswitch(event->key())\n\t{\n\tcase Qt::Key_Q:\n\t\tvelocity.z += speed; break;\n\tcase Qt::Key_E:\n\t\tvelocity.z -= speed; break;\n\tcase Qt::Key_A:\n\t\tvelocity.x += speed; break;\n\tcase Qt::Key_D:\n\t\tvelocity.x -= speed; break;\n\tcase Qt::Key_W:\n\t\tvelocity.y += speed; break;\n\tcase Qt::Key_S:\n\t\tvelocity.y -= speed; break;\n\t}\n\t\n\t\n}\n\nvoid GLWidget::keyReleaseEvent ( QKeyEvent* event )\n{\n\tswitch(event->key())\n\t{\n\tcase Qt::Key_Q:\n\t\tvelocity.z -= speed; break;\n\tcase Qt::Key_E:\n\t\tvelocity.z += speed; break;\n\tcase Qt::Key_A:\n\t\tvelocity.x -= speed; break;\n\tcase Qt::Key_D:\n\t\tvelocity.x += speed; break;\n\tcase Qt::Key_W:\n\t\tvelocity.y -= speed; break;\n\tcase Qt::Key_S:\n\t\tvelocity.y += speed; break;\n\t}\n}\n\n\nvoid GLWidget::initializeGL()\n{\n\tQOpenGLWidget::initializeGL();\n\t\n\tinitializeOpenGLFunctions();\n\t\n\t\n\tstd::vector<tinyobj::shape_t> shapes;\n\tstd::vector<tinyobj::material_t> mats;\n\n\tstd::string error;\n\n\t\/\/ load model\n\ttinyobj::LoadObj(shapes, mats, error, \"thing.obj\");\n\n\tif (!shapes.size())\n\t{\n\t\tstd::cout << error << std::endl;\n\n\t\texit(-1);\n\t}\n\n\n\n\ttinyobj::mesh_t& mesh = shapes[0].mesh;\n\n\tnumElements = mesh.indices.size();\n\tnumVerts = mesh.positions.size() \/ 3;\n\n\t\/\/setup buffer\n\tglGenVertexArrays(1, &vertArray);\n\tglBindVertexArray(vertArray);\n\n\n\tglGenBuffers(1, &vertLocs);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertLocs);\n\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(float) * mesh.positions.size(), mesh.positions.data(), GL_STATIC_DRAW);\n\n\tglGenBuffers(1, &indicies);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicies);\n\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh.indices.size(), mesh.indices.data(), GL_STATIC_DRAW);\n\n\n\tstd::array<float, 3> colorsToChooseFrom[] =\n\t{\n\t\tfromHex(0xda253900),\n\t\tfromHex(0x377ac800),\n\t\tfromHex(0x5d3da300),\n\t\/\/\tfromHex(0xe3903100),\n\t\/\/\tfromHex(0x7dbe3200),\n\t\/\/\tfromHex(0x38579900),\n\t\/\/\tfromHex(0x89619e00)\n\t};\n\n\t\/\/ generate colors\n\tstd::vector<std::array<float, 3>> colorsData(mesh.positions.size() \/ 3);\n\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\n\tstd::uniform_int_distribution<> distr(0, 2);\n\n\tfor (std::array<float, 3>& color : colorsData)\n\t{\n\n\t\tcolor = colorsToChooseFrom[distr(gen)];\n\t}\n\n\tglGenBuffers(1, &colors);\n\tglBindBuffer(GL_ARRAY_BUFFER, colors);\n\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * colorsData.size(), colorsData.data(), GL_STATIC_DRAW);\n\n\t\/\/ load shader\n\tauto vertShader =\n\t\t\"#version 330 core\\n\"\n\t\t\"layout(location = 0) in vec3 vertLocationIn;\\n\"\n\t\t\"layout(location = 1) in vec3 vertColors;\\n\"\n\t\t\"uniform mat4 MVP;\\n\"\n\t\t\"\\n\"\n\t\t\"out vec3 color;\\n\"\n\t\t\"\\n\"\n\t\t\"void main()\\n\"\n\t\t\"{\\n\"\n\t\t\"\tgl_Position = MVP * vec4(vertLocationIn, 1.f);\\n\"\n\t\t\"\t\\n\"\n\t\t\"\tcolor = vertColors;\\n\"\n\t\t\"}\\n\";\n\n\tauto fragShader =\n\t\t\"#version 330 core\\n\"\n\t\t\"in vec3 color;\\n\"\n\t\t\"uniform int isRender = 0;\\n\"\n\t\t\"out vec3 fragColor;\\n\"\n\t\t\"void main()\\n\"\n\t\t\"{\\n\"\n\t\t\"\tfragColor = isRender != 0 ? vec3(.1f, .1f, .1f) : color;\\n\"\n\t\t\"}\\n\";\n\n\t\/\/ Create the shaders\n\tGLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);\n\tGLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);\n\n\tint32_t Result = GL_FALSE;\n\tint InfoLogLength;\n\n\tglShaderSource(vertexShader, 1, &vertShader, nullptr);\n\tglCompileShader(vertexShader);\n\n\t\/\/ Check Vertex Shader\n\tglGetShaderiv(vertexShader, GL_COMPILE_STATUS, &Result);\n\tglGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &InfoLogLength);\n\tif (InfoLogLength > 1) {\n\t\tauto VertexShaderErrorMessage = std::vector<char>(InfoLogLength + 1);\n\t\tglGetShaderInfoLog(vertexShader, InfoLogLength, nullptr, VertexShaderErrorMessage.data());\n\t\tstd::cout << VertexShaderErrorMessage.data();\n\t}\n\telse\n\t{\n\t\tstd::cout << \"\\tShader Successfully Compiled\";\n\t}\n\n\t\/\/ Compile Fragment Shader\n\tglShaderSource(fragmentShader, 1, &fragShader, nullptr);\n\tglCompileShader(fragmentShader);\n\n\t\/\/ Check Fragment Shader\n\tglGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &Result);\n\tglGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &InfoLogLength);\n\tif (InfoLogLength > 1) {\n\t\tauto FragmentShaderErrorMessage = std::vector<char>(InfoLogLength + 1);\n\t\tglGetShaderInfoLog(fragmentShader, InfoLogLength, nullptr, FragmentShaderErrorMessage.data());\n\t\tstd::cout << FragmentShaderErrorMessage.data();\n\t}\n\telse\n\t{\n\t\tstd::cout << \"\\tShader Successfully Compiled\";\n\t}\n\n\t\/\/ Link the program\n\tstd::cout << \"\\tLinking program \";\n\tprogram = glCreateProgram();\n\tglAttachShader(program, vertexShader);\n\tglAttachShader(program, fragmentShader);\n\tglLinkProgram(program);\n\n\t\/\/ Check the program\n\tglGetProgramiv(program, GL_LINK_STATUS, &Result);\n\tglGetProgramiv(program, GL_INFO_LOG_LENGTH, &InfoLogLength);\n\tif (InfoLogLength > 1) {\n\t\tauto ProgramErrorMessage = std::vector<char>(InfoLogLength + 1);\n\t\tglGetProgramInfoLog(program, InfoLogLength, nullptr, ProgramErrorMessage.data());\n\t\tstd::cout << ProgramErrorMessage.data();\n\t}\n\n\tglDeleteShader(vertexShader);\n\tglDeleteShader(fragmentShader);\n\n\tstd::cout << \"\\tSuccessfully Linked Program.\";\n\n\t\n\t\n}\n\nvoid GLWidget::paintGL()\n{\n\tQOpenGLWidget::paintGL();\n\n\tstd::chrono::time_point<std::chrono::system_clock> currentTickTime = std::chrono::system_clock::now();\n\t\n\tstd::chrono::duration<double> deltaDuration = currentTickTime - lastTickTime;\n\tfloat deltaTime = deltaDuration.count();\n\tlastTickTime = currentTickTime;\n\t\n\t\n\tdeltaTime = fabs(deltaTime);\n\t\n\t\/\/ apply velocity\n\tlocation += velocity.y * deltaTime * forwardVector;\n\tlocation += velocity.x * deltaTime * glm::cross(forwardVector, upVector);\n\t\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\t\n\tif(needsRegenerate) regenerate();\n\tneedsRegenerate = false;\n\t\n\tglBindVertexArray(vertArray);\n\n\t\n\t\/\/ render!\n\tglm::mat4 viewMat = glm::lookAt(location, location + forwardVector, upVector);\n\tglm::mat4 projectionMat = glm::perspective(50.f, 16.f \/ 10.f, .1f, 100.f);\n\n\tglm::mat4 MVPMat = projectionMat * viewMat;\n\n\tglm::vec4 a = MVPMat * glm::vec4(-62.8301315, 0.548247993, 51.5535278, 1);\n\n\tglUniformMatrix4fv(glGetUniformLocation(program, \"MVP\"), 1, GL_FALSE, &MVPMat[0][0]);\n\n\n\tglUseProgram(program);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertLocs);\n\tglEnableVertexAttribArray(0);\n\tglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), nullptr);\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, colors);\n\tglEnableVertexAttribArray(1);\n\tglVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), nullptr);\n\n\tglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n\tglUniform1i(glGetUniformLocation(program, \"isRender\"), GL_FALSE);\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicies);\n\tglDrawElements(GL_TRIANGLES, numElements, GL_UNSIGNED_INT, nullptr);\n\n\tglLineWidth(lineSize);\n\tglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\tglUniform1i(glGetUniformLocation(program, \"isRender\"), GL_TRUE);\n\n\tif(lineSize != -1.f)\t\n\t\tglDrawElements(GL_TRIANGLES, numElements, GL_UNSIGNED_INT, nullptr);\n\n\tglDisableVertexAttribArray(0);\n\tglDisableVertexAttribArray(1);\n\n\t\/\/std::vector<GLubyte> pixels(1920 * 1080 * 4);\n\t\/\/glReadPixels(0, 0, 1920, 1080, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());\n\n\t\/\/auto err = lodepng::encode(\"C:\\\\Users\\\\russe\\\\Documents\\\\Visual Studio 2015\\\\Projects\\\\WallPaperout.png\", pixels, 1920, 1080, LCT_RGBA);\n\t\/\/std::cout << lodepng_error_text(err) << std::endl;\n\n\tif(needsSave) save();\n\tneedsSave = false;\n}\n\nvoid GLWidget::regenerate()\n{\n\tstd::array<float, 3> colorsToChooseFrom[] =\n\t{\n\t\tfromHex(0xda253900),\n\t\tfromHex(0x377ac800),\n\t\tfromHex(0x5d3da300),\n\t\/\/\tfromHex(0xe3903100),\n\t\/\/\tfromHex(0x7dbe3200),\n\t\/\/\tfromHex(0x38579900),\n\t\/\/\tfromHex(0x89619e00)\n\t};\n\n\t\/\/ generate colors\n\tstd::vector<std::array<float, 3>> colorsData(numVerts);\n\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\n\tstd::uniform_int_distribution<> distr(0, 2);\n\n\tfor (std::array<float, 3>& color : colorsData)\n\t{\n\n\t\tcolor = colorsToChooseFrom[distr(gen)];\n\t}\n\n\tglBindBuffer(GL_ARRAY_BUFFER, colors);\n\tglBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float) * 3 * numVerts, colorsData.data());\n\t\n\t\n\t\n}\n\nvoid GLWidget::save()\n{\n\t\n}\n\n<commit_msg>Work on saving -- currently I get an OGL error.<commit_after>#include \"GLWidget.h\"\n\n#include \"tiny_obj_loader.h\"\n#include \"lodepng.h\"\n\n#include <iostream>\n#include <vector>\n\n#include <glm\/gtx\/transform.hpp>\n#include <QApplication>\n\n\nGLWidget::GLWidget ( QWidget* parent, Qt::WindowFlags f ) : QOpenGLWidget ( parent, f )\n{\n\t\n\tsetFocusPolicy(Qt::ClickFocus);\n\t\n\tconnect(&time, &QTimer::timeout, [this]\n\t\t{\n\t\t\tthis->update();\n\t\t});\n\ttime.start(0);\n\t\n\tQSurfaceFormat format;\n\tformat.setMajorVersion(3);\n\tformat.setMinorVersion(3);\n\t\n\tformat.setSamples(8);\n\t\n\tsetFormat(format);\n\t\n}\n\nbool GLWidget::event (QEvent* event)\n{\n\n\tswitch(event->type())\n\t{\n\tcase QEvent::Type::MouseButtonPress:\n\t\t{\n\t\t\tauto mousePressEvent = static_cast<QMouseEvent*>(event);\n\t\t\tif(mousePressEvent->button() == Qt::LeftButton)\n\t\t\t{\n\t\t\t\tisMouseDown = true;\n\t\t\t\tlastMousePos = { mousePressEvent->x(), mousePressEvent->y() };\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase QEvent::Type::MouseButtonRelease:\n\t\t{\n\t\t\tauto mousePressEvent = static_cast<QMouseEvent*>(event);\n\t\t\tif(mousePressEvent->button() == Qt::LeftButton)\n\t\t\t{\n\t\t\t\tisMouseDown = false;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase QEvent::Type::MouseMove:\n\t\t{\n\t\t\tauto mousePressEvent = static_cast<QMouseEvent*>(event);\n\t\t\tif(isMouseDown)\n\t\t\t{\n\t\t\t\tglm::ivec2 currentMouse = { mousePressEvent->x(), mousePressEvent->y() };\n\t\t\t\t\n\t\t\t\tglm::ivec2 deltaMouse = currentMouse - lastMousePos;\n\t\t\t\t\n\t\t\t\tauto forVecIntX = glm::rotate((float)deltaMouse.x \/ 1000.f, glm::vec3{0.f, 0.f, 1.f}) * glm::vec4(forwardVector, 0.f);\n\t\t\t\tforwardVector = {forVecIntX.x, forVecIntX.y, forVecIntX.z};\n\t\t\t\t\n\t\t\t\tauto forVecIntY = glm::rotate(-(float)deltaMouse.y \/ 1000.f, glm::vec3{1.f, 0.f, 0.f}) * glm::vec4(forwardVector, 0.f);\n\t\t\t\tforwardVector = {forVecIntY.x, forVecIntY.y, forVecIntY.z};\n\t\t\t\t\n\t\t\t\tlastMousePos = currentMouse;\n\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tdefault: break;\n\t}\n\n\treturn QOpenGLWidget::event(event);\n}\n\n\nstd::array<float, 3> fromRGB(unsigned char r, unsigned char g, unsigned char b)\n{\n\treturn{ (float)r \/ 255.f, (float)g \/ 255.f, (float)b \/ 255.f };\n}\n\nvoid GLWidget::markForRegeneration()\n{\n\tneedsRegenerate = true;\n}\n\nvoid GLWidget::markForSave(const QString& saveDest)\n{\n\tneedsSave = true;\n\tsavePath = saveDest;\n}\n\n\n\n\nstd::array<float, 3> fromHex(uint32_t color)\n{\n return fromRGB(color >> 24, color << 8 >> 24, color << 16 >> 24);\n}\n\n\n\n\nvoid GLWidget::keyPressEvent ( QKeyEvent* event )\n{\n\tQWidget::keyPressEvent ( event );\n\t\t\n\tswitch(event->key())\n\t{\n\tcase Qt::Key_Q:\n\t\tvelocity.z += speed; break;\n\tcase Qt::Key_E:\n\t\tvelocity.z -= speed; break;\n\tcase Qt::Key_A:\n\t\tvelocity.x += speed; break;\n\tcase Qt::Key_D:\n\t\tvelocity.x -= speed; break;\n\tcase Qt::Key_W:\n\t\tvelocity.y += speed; break;\n\tcase Qt::Key_S:\n\t\tvelocity.y -= speed; break;\n\t}\n\t\n\t\n}\n\nvoid GLWidget::keyReleaseEvent ( QKeyEvent* event )\n{\n\tswitch(event->key())\n\t{\n\tcase Qt::Key_Q:\n\t\tvelocity.z -= speed; break;\n\tcase Qt::Key_E:\n\t\tvelocity.z += speed; break;\n\tcase Qt::Key_A:\n\t\tvelocity.x -= speed; break;\n\tcase Qt::Key_D:\n\t\tvelocity.x += speed; break;\n\tcase Qt::Key_W:\n\t\tvelocity.y -= speed; break;\n\tcase Qt::Key_S:\n\t\tvelocity.y += speed; break;\n\t}\n}\n\n\nvoid GLWidget::initializeGL()\n{\n\tQOpenGLWidget::initializeGL();\n\t\n\tinitializeOpenGLFunctions();\n\t\n\t\n\tstd::vector<tinyobj::shape_t> shapes;\n\tstd::vector<tinyobj::material_t> mats;\n\n\tstd::string error;\n\n\t\/\/ load model\n\ttinyobj::LoadObj(shapes, mats, error, \"thing.obj\");\n\n\tif (!shapes.size())\n\t{\n\t\tstd::cout << error << std::endl;\n\n\t\texit(-1);\n\t}\n\n\n\n\ttinyobj::mesh_t& mesh = shapes[0].mesh;\n\n\tnumElements = mesh.indices.size();\n\tnumVerts = mesh.positions.size() \/ 3;\n\n\t\/\/setup buffer\n\tglGenVertexArrays(1, &vertArray);\n\tglBindVertexArray(vertArray);\n\n\n\tglGenBuffers(1, &vertLocs);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertLocs);\n\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(float) * mesh.positions.size(), mesh.positions.data(), GL_STATIC_DRAW);\n\n\tglGenBuffers(1, &indicies);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicies);\n\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh.indices.size(), mesh.indices.data(), GL_STATIC_DRAW);\n\n\n\n\tglGenBuffers(1, &colors);\n\tglBindBuffer(GL_ARRAY_BUFFER, colors);\n\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * mesh.positions.size(), 0, GL_STATIC_DRAW);\n\tregenerate();\n\n\t\/\/ load shader\n\tauto vertShader =\n\t\t\"#version 330 core\\n\"\n\t\t\"layout(location = 0) in vec3 vertLocationIn;\\n\"\n\t\t\"layout(location = 1) in vec3 vertColors;\\n\"\n\t\t\"uniform mat4 MVP;\\n\"\n\t\t\"\\n\"\n\t\t\"out vec3 color;\\n\"\n\t\t\"\\n\"\n\t\t\"void main()\\n\"\n\t\t\"{\\n\"\n\t\t\"\tgl_Position = MVP * vec4(vertLocationIn, 1.f);\\n\"\n\t\t\"\t\\n\"\n\t\t\"\tcolor = vertColors;\\n\"\n\t\t\"}\\n\";\n\n\tauto fragShader =\n\t\t\"#version 330 core\\n\"\n\t\t\"in vec3 color;\\n\"\n\t\t\"uniform int isRender = 0;\\n\"\n\t\t\"out vec3 fragColor;\\n\"\n\t\t\"void main()\\n\"\n\t\t\"{\\n\"\n\t\t\"\tfragColor = isRender != 0 ? vec3(.1f, .1f, .1f) : color;\\n\"\n\t\t\"}\\n\";\n\n\t\/\/ Create the shaders\n\tGLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);\n\tGLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);\n\n\tint32_t Result = GL_FALSE;\n\tint InfoLogLength;\n\n\tglShaderSource(vertexShader, 1, &vertShader, nullptr);\n\tglCompileShader(vertexShader);\n\n\t\/\/ Check Vertex Shader\n\tglGetShaderiv(vertexShader, GL_COMPILE_STATUS, &Result);\n\tglGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &InfoLogLength);\n\tif (InfoLogLength > 1) {\n\t\tauto VertexShaderErrorMessage = std::vector<char>(InfoLogLength + 1);\n\t\tglGetShaderInfoLog(vertexShader, InfoLogLength, nullptr, VertexShaderErrorMessage.data());\n\t\tstd::cout << VertexShaderErrorMessage.data();\n\t}\n\telse\n\t{\n\t\tstd::cout << \"\\tShader Successfully Compiled\";\n\t}\n\n\t\/\/ Compile Fragment Shader\n\tglShaderSource(fragmentShader, 1, &fragShader, nullptr);\n\tglCompileShader(fragmentShader);\n\n\t\/\/ Check Fragment Shader\n\tglGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &Result);\n\tglGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &InfoLogLength);\n\tif (InfoLogLength > 1) {\n\t\tauto FragmentShaderErrorMessage = std::vector<char>(InfoLogLength + 1);\n\t\tglGetShaderInfoLog(fragmentShader, InfoLogLength, nullptr, FragmentShaderErrorMessage.data());\n\t\tstd::cout << FragmentShaderErrorMessage.data();\n\t}\n\telse\n\t{\n\t\tstd::cout << \"\\tShader Successfully Compiled\";\n\t}\n\n\t\/\/ Link the program\n\tstd::cout << \"\\tLinking program \";\n\tprogram = glCreateProgram();\n\tglAttachShader(program, vertexShader);\n\tglAttachShader(program, fragmentShader);\n\tglLinkProgram(program);\n\n\t\/\/ Check the program\n\tglGetProgramiv(program, GL_LINK_STATUS, &Result);\n\tglGetProgramiv(program, GL_INFO_LOG_LENGTH, &InfoLogLength);\n\tif (InfoLogLength > 1) {\n\t\tauto ProgramErrorMessage = std::vector<char>(InfoLogLength + 1);\n\t\tglGetProgramInfoLog(program, InfoLogLength, nullptr, ProgramErrorMessage.data());\n\t\tstd::cout << ProgramErrorMessage.data();\n\t}\n\n\tglDeleteShader(vertexShader);\n\tglDeleteShader(fragmentShader);\n\n\tstd::cout << \"\\tSuccessfully Linked Program.\";\n\n\t\n\t\n}\n\nvoid GLWidget::paintGL()\n{\n\tQOpenGLWidget::paintGL();\n\n\tstd::chrono::time_point<std::chrono::system_clock> currentTickTime = std::chrono::system_clock::now();\n\t\n\tstd::chrono::duration<double> deltaDuration = currentTickTime - lastTickTime;\n\tfloat deltaTime = deltaDuration.count();\n\tlastTickTime = currentTickTime;\n\t\n\t\n\tdeltaTime = fabs(deltaTime);\n\t\n\t\/\/ apply velocity\n\tlocation += velocity.y * deltaTime * forwardVector;\n\tlocation += velocity.x * deltaTime * glm::cross(forwardVector, upVector);\n\t\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\t\n\tif(needsRegenerate) regenerate();\n\tneedsRegenerate = false;\n\t\n\tglBindVertexArray(vertArray);\n\n\t\n\t\/\/ render!\n\tglm::mat4 viewMat = glm::lookAt(location, location + forwardVector, upVector);\n\tglm::mat4 projectionMat = glm::perspective(50.f, 16.f \/ 10.f, .1f, 100.f);\n\n\tglm::mat4 MVPMat = projectionMat * viewMat;\n\n\tglm::vec4 a = MVPMat * glm::vec4(-62.8301315, 0.548247993, 51.5535278, 1);\n\n\tglUniformMatrix4fv(glGetUniformLocation(program, \"MVP\"), 1, GL_FALSE, &MVPMat[0][0]);\n\n\n\tglUseProgram(program);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertLocs);\n\tglEnableVertexAttribArray(0);\n\tglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), nullptr);\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, colors);\n\tglEnableVertexAttribArray(1);\n\tglVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), nullptr);\n\n\tglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n\tglUniform1i(glGetUniformLocation(program, \"isRender\"), GL_FALSE);\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicies);\n\tglDrawElements(GL_TRIANGLES, numElements, GL_UNSIGNED_INT, nullptr);\n\n\tglLineWidth(lineSize);\n\tglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\tglUniform1i(glGetUniformLocation(program, \"isRender\"), GL_TRUE);\n\n\tif(lineSize != -1.f)\t\n\t\tglDrawElements(GL_TRIANGLES, numElements, GL_UNSIGNED_INT, nullptr);\n\n\tglDisableVertexAttribArray(0);\n\tglDisableVertexAttribArray(1);\n\n\tif(needsSave) save();\n\tneedsSave = false;\n\t\n\t\n\/\/\tstd::cout << std::hex << glGetError() << std::endl;\n}\n\nvoid GLWidget::regenerate()\n{\n\tstd::array<float, 3> colorsToChooseFrom[] =\n\t{\n\t\tfromHex(0xda253900),\n\t\tfromHex(0x377ac800),\n\t\tfromHex(0x5d3da300),\n\t\/\/\tfromHex(0xe3903100),\n\t\/\/\tfromHex(0x7dbe3200),\n\t\/\/\tfromHex(0x38579900),\n\t\/\/\tfromHex(0x89619e00)\n\t};\n\n\t\/\/ generate colors\n\tstd::vector<std::array<float, 3>> colorsData(numVerts);\n\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\n\tstd::uniform_int_distribution<> distr(0, 2);\n\n\tfor (std::array<float, 3>& color : colorsData)\n\t{\n\n\t\tcolor = colorsToChooseFrom[distr(gen)];\n\t}\n\n\tglBindBuffer(GL_ARRAY_BUFFER, colors);\n\tglBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float) * 3 * numVerts, colorsData.data());\n\t\n\t\n\t\n}\n\nvoid GLWidget::save()\n{\n\tstd::vector<GLubyte> data(width() * height() * 4);\n\t\n\t\/\/glReadBuffer(GL_FRONT);\n\t\/\/glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, data.data());\n\t\n\t\/\/lodepng::encode(savePath.toStdString(), data.data(), width(), height(), LCT_RGBA, 8);\n\t\n\t\n\t\n\tstd::cout << glGetError() << std::endl;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************\nCopyright (C) 2013-2015 gregoire ANGERAND\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**********************************\/\n\n#include \"String.h\"\n#include \"Array.h\"\n#include <string>\n#include <iomanip>\n#include <cstring>\n\nnamespace n {\nnamespace core {\n\ntypedef String::CounterType SCType;\n\nN_FORCE_INLINE uint sizeForStrAlloc(uint s) {\n\tuint mod = s % sizeof(uint);\n\treturn s + (mod ? sizeof(uint) - mod : 0);\n}\n\nN_FORCE_INLINE char *allocStr(SCType **count, uint s) {\n\tif(!s) {\n\t\treturn 0;\n\t}\n\tuint allocSize = sizeForStrAlloc(s);\n\tbyte *cptr = (byte *)malloc(allocSize + sizeof(uint) + sizeof(SCType));\n\tif((uint)cptr % sizeof(SCType)) {\n\t\tfatal(\"Unaligned alloc (this should not happen\");\n\t}\n\t*count = new(cptr) SCType(1);\n\tnew(cptr + sizeof(SCType)) uint(allocSize);\n\n\treturn (char *)(cptr + sizeof(SCType) + sizeof(uint));\n}\n\n\nN_FORCE_INLINE void freeStr(SCType **count, char *) {\n\tif(!*count) {\n\t\treturn;\n\t}\n\t((SCType *)(*count))->~SCType();\n\tfree(*count);\n}\n\nN_FORCE_INLINE char *reallocStr(SCType **count, uint s) {\n\tif(!s) {\n\t\tfreeStr(count, 0);\n\t\t*count = 0;\n\t\treturn 0;\n\t}\n\tSCType *cptr = *count;\n\tif(!cptr) {\n\t\treturn allocStr(count, s);\n\t}\n\tuint allocated = *(uint *)(cptr + 1);\n\tuint optAllocSize = sizeForStrAlloc(s);\n\tif(s > allocated || allocated + 2 * sizeof(uint) < optAllocSize) {\n\t\tcptr = (SCType *)safeRealloc(cptr, optAllocSize + sizeof(uint) + sizeof(SCType));\n\t\t*(uint *)(cptr + 1) = optAllocSize;\n\t}\n\t*count = cptr;\n\treturn (char *)(cptr + sizeof(SCType) + sizeof(uint));\n}\n\nString::String() : length(0), count(0), data(0) {\n}\n\nString::String(const char *cst) : String() {\n\tif(cst) {\n\t\tdata = allocStr(&count, length = strlen(cst));\/\/(char *)malloc(length * sizeof(char));\n\t\tmemcpy(data, cst, length * sizeof(char));\n\t}\n}\n\nString::String(const char *cst, uint l) : length(l), count(0), data(0) {\n\tif(l) {\n\t\tdata = allocStr(&count, length);\/\/(char *)malloc(length * sizeof(char));\n\t\tif(cst) {\n\t\t\tmemcpy(data, cst, length * sizeof(char));\n\t\t} else {\n\t\t\t*data = '\\0';\n\t\t}\n\t}\n}\n\nString::String(const String &str) : length(str.length), count(str.count), data(str.data) {\n\tif(count) {\n\t\t++(*count);\n\t}\n}\n\nString::String(String &&str) : String() {\n\tswap(str);\n}\n\nString::~String() {\n\tif(data) {\n\t\tif(isUnique()) {\n\t\t\tfreeStr(&count, data);\n\t\t} else {\n\t\t\t--(*count);\n\t\t}\n\t}\n}\n\nString::String(const String &str, uint beg, uint len) : length(len), count(str.count), data(str.data + beg) {\n\tif(count) {\n\t\t++(*count);\n\t}\n}\n\nvoid String::replace(const String &oldS, const String &newS) {\n\toperator=(replaced(oldS, newS));\n}\n\nvoid String::replace(uint beg, uint len, const String &newS) {\n\tuint ol = length;\n\tif(newS.size() > len) {\n\t\tdetach(ol - len + newS.size());\n\t\tmemmove(data + beg + newS.size(), data + beg + len, (ol - beg - len) * sizeof(char));\n\t\tmemcpy(data + beg, newS.data, newS.length * sizeof(char));\n\t} else {\n\t\tmemmove(data + beg + newS.size(), data + beg + len, (ol - beg - len) * sizeof(char));\n\t\tmemcpy(data + beg, newS.data, newS.length * sizeof(char));\n\t\tdetach(ol - len + newS.size());\n\t}\n}\n\nString String::replaced(const String &oldS, const String &newS) const {\n\tArray<String> concat;\n\tuint index = find(oldS);\n\tif(index != (uint)-1) {\n\t\tuint from = 0;\n\t\tuint offset = oldS.size();\n\t\tdo {\n\t\t\tconcat += subString(from, index - from);\n\t\t\tconcat += newS;\n\t\t\tfrom = index + offset;\n\t\t\tindex = find(oldS, from);\n\t\t} while(index != (uint)-1);\n\t\tconcat += subString(from);\n\t} else {\n\t\treturn *this;\n\t}\n\treturn String(concat);\n}\n\nString String::replaced(uint beg, uint len, const String &newS) const {\n\treturn String(Array<String>(subString(0, beg), newS, subString(beg + len)));\n}\n\nvoid String::clear() {\n\tdetach(0);\n}\n\nuint String::size() const {\n\treturn length;\n}\n\nbool String::isEmpty() const {\n\treturn !length;\n}\n\nbool String::isNull() const {\n\treturn !data;\n}\n\nchar const *String::toChar() const {\n\tif(!data) {\n\t\treturn (char *)&null;\n\t}\n\tdetach(length + 1);\n\tlength--;\n\tdata[length] = '\\0';\n\treturn data;\n}\n\nuint String::find(char c, uint from) const {\n\tif(!(from < length)) {\n\t\treturn -1;\n\t}\n\tfor(uint i = from; i != length; i++) {\n\t\tif(data[i] == c) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\nuint String::find(const String &str, uint from) const {\n\tif(from + str.size() > length) {\n\t\treturn -1;\n\t}\n\tfor(uint i = from, l = length - str.length; i <= l; i++) {\n\t\tbool matched = true;\n\t\tfor(uint j = 0; j != str.length; j++) {\n\t\t\tif(data[i + j] != str.data[j]) {\n\t\t\t\tmatched = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(matched) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\nbool String::contains(char c) const {\n\treturn find(c) < length;\n}\n\nbool String::contains(const String &str) const {\n\treturn find(str) < length;\n}\n\nString String::subString(uint beg, uint len) const {\n\tif(!len) {\n\t\treturn String();\n\t}\n\treturn String(*this, beg, len);\n}\n\nString String::subString(uint beg) const {\n\treturn subString(beg, length - beg);\n}\n\nbool String::beginWith(const String &s) const {\n\tif(length < s.length) {\n\t\treturn false;\n\t}\n\tif(isNull()) {\n\t\treturn s.isEmpty();\n\t}\n\tif(s.isEmpty()) {\n\t\treturn true;\n\t}\n\tfor(uint i = 0; i != s.length; i++) {\n\t\tif(data[i] != s.data[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool String::endWith(const String &s) const {\n\tif(length < s.length) {\n\t\treturn false;\n\t}\n\tif(isNull()) {\n\t\treturn s.isEmpty();\n\t}\n\tif(s.isEmpty()) {\n\t\treturn true;\n\t}\n\tuint offset = length - s.length;\n\tfor(uint i = s.length - 1; i; i--) {\n\t\tif(data[offset + i] != s.data[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid String::detach() {\n\tdetach(length);\n}\n\nvoid String::swap(String &str) {\n\tuint l = str.length;\n\tchar *ch = str.data;\n\tSCType *c = str.count;\n\tstr.length = length;\n\tstr.data = data;\n\tstr.count = count;\n\tcount = c;\n\tdata = ch;\n\tlength = l;\n}\n\nArray<String> String::split(const String &str, bool empties) const {\n\tArray<String> arr;\n\tuint p = -1;\n\tuint from = 0;\n\twhile((p = find(str, from)) != (uint)-1) {\n\t\tarr.append(subString(from, p - from));\n\t\tfrom = p + str.size();\n\t}\n\tarr.append(subString(from));\n\treturn empties ? arr : arr.filtered([](const String &s) { return !s.isEmpty(); });\n}\n\nString String::toLower() const {\n\treturn mapped([](char c) -> char { return tolower(c); });\n}\n\nString String::toUpper() const {\n\treturn mapped([](char c) -> char { return toupper(c); });\n}\n\nstd::string String::toStdString() const {\n\treturn std::string(data, length);\n}\n\nString &String::operator+=(const String &s) {\n\tuint tl = length;\n\tuint ol = s.length;\n\tdetach(tl + ol);\n\tmemcpy(data + tl, s.data, ol * sizeof(char));\n\treturn *this;\n}\n\nString String::operator+(const String &s) const {\n\tif(isEmpty()) {\n\t\treturn s;\n\t}\n\tif(s.isEmpty()) {\n\t\treturn *this;\n\t}\n\tString str(0, length + s.length);\n\tmemcpy(str.data, data, length * sizeof(char));\n\tmemcpy(str.data + length, s.data, s.length * sizeof(char));\n\treturn str;\n}\n\nbool String::operator==(const String &str) const {\n\tif(str.length != length) {\n\t\treturn false;\n\t}\n\tif(count && count == str.count) {\n\t\treturn true;\n\t}\n\tfor(uint i = 0; i != length; i++) {\n\t\tif(data[i] != str.data[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool String::operator==(const char *str) const {\n\tfor(uint i = 0; i != length; i++) {\n\t\tif(data[i] != str[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool String::operator!=(const String &str) const {\n\treturn !operator==(str);\n}\n\nbool String::operator!=(const char *str) const {\n\treturn !operator==(str);\n}\n\nString &String::operator=(const String &s) {\n\tdetach(0);\n\tdata = s.data;\n\tcount = s.count;\n\tlength = s.length;\n\tif(count) {\n\t\t(*count)++;\n\t}\n\treturn *this;\n}\n\n\nString &String::operator=(String &&s) {\n\tswap(s);\n\treturn *this;\n}\n\nbool String::operator<(const String &s) const {\n\tif(data && s.data) {\n\t\tfor(uint i = 0, min = std::min(length, s.length); i != min; i++) {\n\t\t\tif(data[i] < s.data[i]) {\n\t\t\t\treturn true;\n\t\t\t} else if(data[i] > s.data[i]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn length < s.length;\n}\n\nbool String::operator>(const String &s) const {\n\tif(data && s.data) {\n\t\tfor(uint i = 0, min = std::min(length, s.length); i != min; i++) {\n\t\t\tif(data[i] > s.data[i]) {\n\t\t\t\treturn true;\n\t\t\t} else if(data[i] < s.data[i]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn length > s.length;\n}\n\nString::operator const char *() const {\n\treturn toChar();\n}\n\nString::const_iterator String::begin() const {\n\treturn data;\n}\n\nString::const_iterator String::end() const {\n\treturn data + length;\n}\n\nuint String::getHash() const {\n\treturn data ? hash(data, length) : hash(&null, 1);\n}\n\nvoid String::detach(uint s) const {\n\tif(s) {\n\t\tif(isUnique() && !isSharedSubset()) {\n\t\t\tdata = reallocStr(&count, s);\n\t\t} else {\n\t\t\t--(*count);\n\t\t\tchar *d = allocStr(&count, s);\n\t\t\tmemcpy(d, data, std::min(length, s) * sizeof(char));\n\t\t\tdata = d;\n\t\t}\n\t} else {\n\t\tif(isUnique()) {\n\t\t\tfreeStr(&count, data);\/\/free(data);\n\t\t}\n\t\tcount = 0;\n\t\tdata = 0;\n\t}\n\tlength = s;\n}\n\nbool String::isUnique() const {\n\treturn (!count || *count == 1);\n}\n\nbool String::isSharedSubset() const {\n\treturn count && (char *)(count + 1)\t!= data;\n}\n\nbool String::isShared() const {\n\treturn count && *count > 1;\n}\n\n}\n}\n\nstd::istream &operator>>(std::istream &s, n::core::String &str) {\n\tstd::string st;\n\ts>>st;\n\tstr = n::core::String(st.c_str());\n\treturn s;\n}\n\nstd::ostream &operator<<(std::ostream &s, const n::core::String &str) {\n\ts<<str.toStdString();\n\treturn s;\n}\n\n\n\n\n<commit_msg>Fixed String offsets.<commit_after>\/*******************************\nCopyright (C) 2013-2015 gregoire ANGERAND\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**********************************\/\n\n#include \"String.h\"\n#include \"Array.h\"\n#include <string>\n#include <iomanip>\n#include <cstring>\n\nnamespace n {\nnamespace core {\n\ntypedef String::CounterType SCType;\n\nN_FORCE_INLINE uint sizeForStrAlloc(uint s) {\n\tuint mod = s % sizeof(uint);\n\treturn s + (mod ? sizeof(uint) - mod : 0);\n}\n\nN_FORCE_INLINE char *allocStr(SCType **count, uint s) {\n\tif(!s) {\n\t\treturn 0;\n\t}\n\tuint allocSize = sizeForStrAlloc(s);\n\tbyte *cptr = (byte *)malloc(allocSize + sizeof(uint) + sizeof(SCType));\n\tif((uint)cptr % sizeof(SCType)) {\n\t\tfatal(\"Unaligned alloc (this should not happen\");\n\t}\n\t*count = new(cptr) SCType(1);\n\tnew(cptr + sizeof(SCType)) uint(allocSize);\n\treturn (char *)(cptr + sizeof(SCType) + sizeof(uint));\n}\n\nN_FORCE_INLINE void freeStr(SCType **count, char *) {\n\tif(!*count) {\n\t\treturn;\n\t}\n\t((SCType *)(*count))->~SCType();\n\tfree(*count);\n}\n\nN_FORCE_INLINE char *reallocStr(SCType **count, uint s) {\n\tif(!s) {\n\t\tfreeStr(count, 0);\n\t\t*count = 0;\n\t\treturn 0;\n\t}\n\tSCType *cptr = *count;\n\tif(!cptr) {\n\t\treturn allocStr(count, s);\n\t}\n\tuint allocated = *(uint *)(cptr + 1);\n\tuint optAllocSize = sizeForStrAlloc(s);\n\tif(s > allocated || allocated + 2 * sizeof(uint) < optAllocSize) {\n\t\tcptr = (SCType *)safeRealloc(cptr, optAllocSize + sizeof(uint) + sizeof(SCType));\n\t\t*(uint *)(cptr + 1) = optAllocSize;\n\t}\n\t*count = cptr;\n\treturn ((char *)cptr) + sizeof(SCType) + sizeof(uint);\n}\n\nString::String() : length(0), count(0), data(0) {\n}\n\nString::String(const char *cst) : String() {\n\tif(cst) {\n\t\tdata = allocStr(&count, length = strlen(cst));\/\/(char *)malloc(length * sizeof(char));\n\t\tmemcpy(data, cst, length * sizeof(char));\n\t}\n}\n\nString::String(const char *cst, uint l) : length(l), count(0), data(0) {\n\tif(l) {\n\t\tdata = allocStr(&count, length);\/\/(char *)malloc(length * sizeof(char));\n\t\tif(cst) {\n\t\t\tmemcpy(data, cst, length * sizeof(char));\n\t\t} else {\n\t\t\t*data = '\\0';\n\t\t}\n\t}\n}\n\nString::String(const String &str) : length(str.length), count(str.count), data(str.data) {\n\tif(count) {\n\t\t++(*count);\n\t}\n}\n\nString::String(String &&str) : String() {\n\tswap(str);\n}\n\nString::~String() {\n\tif(data) {\n\t\tif(isUnique()) {\n\t\t\tfreeStr(&count, data);\n\t\t} else {\n\t\t\t--(*count);\n\t\t}\n\t}\n}\n\nString::String(const String &str, uint beg, uint len) : length(len), count(str.count), data(str.data + beg) {\n\tif(count) {\n\t\t++(*count);\n\t}\n}\n\nvoid String::replace(const String &oldS, const String &newS) {\n\toperator=(replaced(oldS, newS));\n}\n\nvoid String::replace(uint beg, uint len, const String &newS) {\n\tuint ol = length;\n\tif(newS.size() > len) {\n\t\tdetach(ol - len + newS.size());\n\t\tmemmove(data + beg + newS.size(), data + beg + len, (ol - beg - len) * sizeof(char));\n\t\tmemcpy(data + beg, newS.data, newS.length * sizeof(char));\n\t} else {\n\t\tmemmove(data + beg + newS.size(), data + beg + len, (ol - beg - len) * sizeof(char));\n\t\tmemcpy(data + beg, newS.data, newS.length * sizeof(char));\n\t\tdetach(ol - len + newS.size());\n\t}\n}\n\nString String::replaced(const String &oldS, const String &newS) const {\n\tArray<String> concat;\n\tuint index = find(oldS);\n\tif(index != (uint)-1) {\n\t\tuint from = 0;\n\t\tuint offset = oldS.size();\n\t\tdo {\n\t\t\tconcat += subString(from, index - from);\n\t\t\tconcat += newS;\n\t\t\tfrom = index + offset;\n\t\t\tindex = find(oldS, from);\n\t\t} while(index != (uint)-1);\n\t\tconcat += subString(from);\n\t} else {\n\t\treturn *this;\n\t}\n\treturn String(concat);\n}\n\nString String::replaced(uint beg, uint len, const String &newS) const {\n\treturn String(Array<String>(subString(0, beg), newS, subString(beg + len)));\n}\n\nvoid String::clear() {\n\tdetach(0);\n}\n\nuint String::size() const {\n\treturn length;\n}\n\nbool String::isEmpty() const {\n\treturn !length;\n}\n\nbool String::isNull() const {\n\treturn !data;\n}\n\nchar const *String::toChar() const {\n\tif(!data) {\n\t\treturn (char *)&null;\n\t}\n\tdetach(length + 1);\n\tlength--;\n\tdata[length] = '\\0';\n\treturn data;\n}\n\nuint String::find(char c, uint from) const {\n\tif(!(from < length)) {\n\t\treturn -1;\n\t}\n\tfor(uint i = from; i != length; i++) {\n\t\tif(data[i] == c) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\nuint String::find(const String &str, uint from) const {\n\tif(from + str.size() > length) {\n\t\treturn -1;\n\t}\n\tfor(uint i = from, l = length - str.length; i <= l; i++) {\n\t\tbool matched = true;\n\t\tfor(uint j = 0; j != str.length; j++) {\n\t\t\tif(data[i + j] != str.data[j]) {\n\t\t\t\tmatched = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(matched) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\nbool String::contains(char c) const {\n\treturn find(c) < length;\n}\n\nbool String::contains(const String &str) const {\n\treturn find(str) < length;\n}\n\nString String::subString(uint beg, uint len) const {\n\tif(!len) {\n\t\treturn String();\n\t}\n\treturn String(*this, beg, len);\n}\n\nString String::subString(uint beg) const {\n\treturn subString(beg, length - beg);\n}\n\nbool String::beginWith(const String &s) const {\n\tif(length < s.length) {\n\t\treturn false;\n\t}\n\tif(isNull()) {\n\t\treturn s.isEmpty();\n\t}\n\tif(s.isEmpty()) {\n\t\treturn true;\n\t}\n\tfor(uint i = 0; i != s.length; i++) {\n\t\tif(data[i] != s.data[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool String::endWith(const String &s) const {\n\tif(length < s.length) {\n\t\treturn false;\n\t}\n\tif(isNull()) {\n\t\treturn s.isEmpty();\n\t}\n\tif(s.isEmpty()) {\n\t\treturn true;\n\t}\n\tuint offset = length - s.length;\n\tfor(uint i = s.length - 1; i; i--) {\n\t\tif(data[offset + i] != s.data[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid String::detach() {\n\tdetach(length);\n}\n\nvoid String::swap(String &str) {\n\tuint l = str.length;\n\tchar *ch = str.data;\n\tSCType *c = str.count;\n\tstr.length = length;\n\tstr.data = data;\n\tstr.count = count;\n\tcount = c;\n\tdata = ch;\n\tlength = l;\n}\n\nArray<String> String::split(const String &str, bool empties) const {\n\tArray<String> arr;\n\tuint p = -1;\n\tuint from = 0;\n\twhile((p = find(str, from)) != (uint)-1) {\n\t\tarr.append(subString(from, p - from));\n\t\tfrom = p + str.size();\n\t}\n\tarr.append(subString(from));\n\treturn empties ? arr : arr.filtered([](const String &s) { return !s.isEmpty(); });\n}\n\nString String::toLower() const {\n\treturn mapped([](char c) -> char { return tolower(c); });\n}\n\nString String::toUpper() const {\n\treturn mapped([](char c) -> char { return toupper(c); });\n}\n\nstd::string String::toStdString() const {\n\treturn std::string(data, length);\n}\n\nString &String::operator+=(const String &s) {\n\tuint tl = length;\n\tuint ol = s.length;\n\tdetach(tl + ol);\n\tmemcpy(data + tl, s.data, ol * sizeof(char));\n\treturn *this;\n}\n\nString String::operator+(const String &s) const {\n\tif(isEmpty()) {\n\t\treturn s;\n\t}\n\tif(s.isEmpty()) {\n\t\treturn *this;\n\t}\n\tString str(0, length + s.length);\n\tmemcpy(str.data, data, length * sizeof(char));\n\tmemcpy(str.data + length, s.data, s.length * sizeof(char));\n\treturn str;\n}\n\nbool String::operator==(const String &str) const {\n\tif(str.length != length) {\n\t\treturn false;\n\t}\n\tif(count && count == str.count) {\n\t\treturn true;\n\t}\n\tfor(uint i = 0; i != length; i++) {\n\t\tif(data[i] != str.data[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool String::operator==(const char *str) const {\n\tfor(uint i = 0; i != length; i++) {\n\t\tif(data[i] != str[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool String::operator!=(const String &str) const {\n\treturn !operator==(str);\n}\n\nbool String::operator!=(const char *str) const {\n\treturn !operator==(str);\n}\n\nString &String::operator=(const String &s) {\n\tdetach(0);\n\tdata = s.data;\n\tcount = s.count;\n\tlength = s.length;\n\tif(count) {\n\t\t(*count)++;\n\t}\n\treturn *this;\n}\n\n\nString &String::operator=(String &&s) {\n\tswap(s);\n\treturn *this;\n}\n\nbool String::operator<(const String &s) const {\n\tif(data && s.data) {\n\t\tfor(uint i = 0, min = std::min(length, s.length); i != min; i++) {\n\t\t\tif(data[i] < s.data[i]) {\n\t\t\t\treturn true;\n\t\t\t} else if(data[i] > s.data[i]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn length < s.length;\n}\n\nbool String::operator>(const String &s) const {\n\tif(data && s.data) {\n\t\tfor(uint i = 0, min = std::min(length, s.length); i != min; i++) {\n\t\t\tif(data[i] > s.data[i]) {\n\t\t\t\treturn true;\n\t\t\t} else if(data[i] < s.data[i]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn length > s.length;\n}\n\nString::operator const char *() const {\n\treturn toChar();\n}\n\nString::const_iterator String::begin() const {\n\treturn data;\n}\n\nString::const_iterator String::end() const {\n\treturn data + length;\n}\n\nuint String::getHash() const {\n\treturn data ? hash(data, length) : hash(&null, 1);\n}\n\nvoid String::detach(uint s) const {\n\tif(s) {\n\t\tif(isUnique()) {\n\t\t\tdata = reallocStr(&count, s);\n\t\t} else {\n\t\t\t--(*count);\n\t\t\tchar *d = allocStr(&count, s);\n\t\t\tmemcpy(d, data, std::min(length, s) * sizeof(char));\n\t\t\tdata = d;\n\t\t}\n\t} else {\n\t\tif(isUnique()) {\n\t\t\tfreeStr(&count, data);\/\/free(data);\n\t\t}\n\t\tcount = 0;\n\t\tdata = 0;\n\t}\n\tlength = s;\n}\n\nbool String::isUnique() const {\n\treturn (!count || *count <= 1);\n}\n\nbool String::isSharedSubset() const {\n\treturn count && ((char *)count) + sizeof(SCType) + sizeof(uint)\t!= data;\n}\n\nbool String::isShared() const {\n\treturn count && *count > 1;\n}\n\n}\n}\n\nstd::istream &operator>>(std::istream &s, n::core::String &str) {\n\tstd::string st;\n\ts>>st;\n\tstr = n::core::String(st.c_str());\n\treturn s;\n}\n\nstd::ostream &operator<<(std::ostream &s, const n::core::String &str) {\n\ts<<str.toStdString();\n\treturn s;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- AlphaTargetAsmInfo.cpp - Alpha asm properties -----------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by James M. Laskey and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains the declarations of the AlphaTargetAsmInfo properties.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AlphaTargetAsmInfo.h\"\n\nusing namespace llvm;\n\nAlphaTargetAsmInfo::AlphaTargetAsmInfo(const AlphaTargetMachine &TM) {\n AlignmentIsInBytes = false;\n PrivateGlobalPrefix = \"$\";\n JumpTableDirective = \".gprel32\";\n}\n<commit_msg>Set the jt section<commit_after>\/\/===-- AlphaTargetAsmInfo.cpp - Alpha asm properties -----------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by James M. Laskey and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains the declarations of the AlphaTargetAsmInfo properties.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AlphaTargetAsmInfo.h\"\n\nusing namespace llvm;\n\nAlphaTargetAsmInfo::AlphaTargetAsmInfo(const AlphaTargetMachine &TM) {\n AlignmentIsInBytes = false;\n PrivateGlobalPrefix = \"$\";\n JumpTableDirective = \".gprel32\";\n JumpTableDataSection = \"\\t.section .rodata\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef LF_POOL_ALLOC_POOL\n#define LF_POOL_ALLOC_POOL\n\n#include <cstdint>\n#include <atomic>\n#include <memory>\n#include <iostream>\n#include <cassert>\n\nnamespace lfpAlloc {\n\n template<typename T, uint16_t CellsPerAllocation, std::size_t NumCells>\n class Pool {\n public:\n static_assert(NumCells % CellsPerAllocation == 0,\n \"NumCells must be a multiple of CellsPerAllocation.\");\n\n Pool() : handle_(new Node_),\n head_(&handle_.load()->memBlock_[0]){}\n\n ~Pool() {\n Node_* node = handle_.load();\n while(node) {\n auto temp = node;\n node = node->next_;\n delete temp;\n }\n }\n\n T* allocate(){\n start:\n Cell_* currentHead;\n Cell_* currentNext;\n\n Node_* currentHandle;\n Node_* newNode;\n\n \/\/ Ran out of cells to allocate\n if (!head_.load()) {\n\n \/\/ Make a new node\n newNode = new Node_;\n\n \/\/ Point the current Head's next to the head of the new node\n do {\n currentHead = head_.load();\n newNode->memBlock_[NumCells-CellsPerAllocation].next_ = currentHead;\n } while(!head_.compare_exchange_strong(currentHead, &newNode->memBlock_[0]));\n\n \/\/ Add the node to the chain\n do {\n currentHandle = handle_.load();\n newNode->next_ = currentHandle;\n } while(!handle_.compare_exchange_strong(currentHandle, newNode));\n assert(head_.load());\n }\n\n \/\/ Allocate by making head = head.next\n do {\n currentHead = head_.load();\n currentNext = currentHead->next_.load();\n } while (!head_.compare_exchange_strong(currentHead, currentNext));\n return reinterpret_cast<T*>(currentHead);\n }\n\n void deallocate(void* p) {\n auto newHead = reinterpret_cast<Cell_*>(p);\n Cell_* currentHead;\n do {\n currentHead = head_.load();\n newHead->next_ = currentHead;\n } while (!head_.compare_exchange_strong(currentHead, newHead));\n }\n\n private:\n union Cell_{\n std::atomic<Cell_*> next_;\n uint8_t val[sizeof(T)];\n };\n\n struct Node_ {\n Node_() {\n for (uint16_t s=0; s < NumCells\/CellsPerAllocation; ++s) {\n memBlock_[s*CellsPerAllocation].next_\n .store(&memBlock_[(s+1)*CellsPerAllocation],\n std::memory_order_relaxed);\n }\n auto& last = memBlock_[NumCells-CellsPerAllocation];\n last.next_.store(nullptr, std::memory_order_relaxed);\n }\n Cell_ memBlock_[NumCells];\n Node_* next_ = nullptr;\n };\n\n std::atomic<Node_*> handle_;\n std::atomic<Cell_*> head_;\n };\n}\n\n#endif\n<commit_msg>Reserve first cell in new node for current request<commit_after>#ifndef LF_POOL_ALLOC_POOL\n#define LF_POOL_ALLOC_POOL\n\n#include <cstdint>\n#include <atomic>\n#include <memory>\n#include <iostream>\n#include <cassert>\n\nnamespace lfpAlloc {\n\n template<typename T, uint16_t CellsPerAllocation, std::size_t NumCells>\n class Pool {\n public:\n static_assert(NumCells % CellsPerAllocation == 0,\n \"NumCells must be a multiple of CellsPerAllocation.\");\n\n Pool() : handle_(new Node_),\n head_(&handle_.load()->memBlock_[0]){}\n\n ~Pool() {\n Node_* node = handle_.load();\n while(node) {\n auto temp = node;\n node = node->next_;\n delete temp;\n }\n }\n\n T* allocate(){\n Cell_* currentHead;\n Cell_* currentNext;\n\n Node_* currentHandle;\n Node_* newNode;\n\n \/\/ Out of cells to allocate\n if (!head_.load()) {\n\n \/\/ Make a new node\n newNode = new Node_;\n\n \/\/ Point the current Head's next to the head of the new node\n do {\n currentHead = head_.load();\n newNode->memBlock_[NumCells-CellsPerAllocation].next_ = currentHead;\n\n \/\/ The first block is reserved for the current request\n } while(!head_.compare_exchange_strong(currentHead, &newNode->memBlock_[1]));\n\n \/\/ Add the node to the chain\n do {\n currentHandle = handle_.load();\n newNode->next_ = currentHandle;\n } while(!handle_.compare_exchange_strong(currentHandle, newNode));\n\n return reinterpret_cast<T*>(&newNode->memBlock_[0]);\n }\n\n \/\/ Allocate by making head = head.next\n do {\n currentHead = head_.load();\n currentNext = currentHead->next_.load();\n } while (!head_.compare_exchange_strong(currentHead, currentNext));\n return reinterpret_cast<T*>(currentHead);\n }\n\n void deallocate(void* p) {\n auto newHead = reinterpret_cast<Cell_*>(p);\n Cell_* currentHead;\n do {\n currentHead = head_.load();\n newHead->next_ = currentHead;\n } while (!head_.compare_exchange_strong(currentHead, newHead));\n }\n\n private:\n union Cell_{\n std::atomic<Cell_*> next_;\n uint8_t val[sizeof(T)];\n };\n\n struct Node_ {\n Node_() {\n for (uint16_t s=0; s < NumCells\/CellsPerAllocation; ++s) {\n memBlock_[s*CellsPerAllocation].next_\n .store(&memBlock_[(s+1)*CellsPerAllocation],\n std::memory_order_relaxed);\n }\n auto& last = memBlock_[NumCells-CellsPerAllocation];\n last.next_.store(nullptr, std::memory_order_relaxed);\n }\n Cell_ memBlock_[NumCells];\n Node_* next_ = nullptr;\n };\n\n std::atomic<Node_*> handle_;\n std::atomic<Cell_*> head_;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ the window containing the plot and buttons for supported operations\n\n#include <QtSvg\/QtSvg>\n\n#include <QtGui\/QToolBar>\n#include <QtGui\/QPrinter>\n#include <QtGui\/QPixmap>\n#include <QtGui\/QPicture>\n#include <QtSvg\/QSvgGenerator>\n\n#include \"CQOptPopulation.h\"\n\n#include \"UI\/copasiui3window.h\"\n#include \"UI\/CQMessageBox.h\"\n#include \"UI\/qtUtilities.h\"\n#include \"qlayout\/CQZoomableView.h\"\n#include \"UI\/CColorScale.h\"\n#include \"resourcesUI\/CQIconResource.h\"\n#include \"optimization\/COptPopulationMethod.h\"\n#include \"optimization\/COptTask.h\"\n#include \"optimization\/COptProblem.h\"\n#include \"optimization\/COptItem.h\"\n\n#ifdef DEBUG_UI\n#include <QtCore\/QtDebug>\n#endif\n\n#include <qwt_plot.h>\n#include <qwt_scale_engine.h>\n\n#if QWT_VERSION > 0x060000\n#include <qwt_plot_renderer.h>\n#endif\n\n#if QWT_VERSION < 0x060000\n\/\/ taken from qwt examples\/bode\nclass PrintFilter: public QwtPlotPrintFilter\n{\npublic:\n PrintFilter() {};\n\n virtual QFont font(const QFont &f, Item, int) const\n {\n QFont f2 = f;\n f2.setPointSize((int)(f.pointSize() * 0.75));\n return f2;\n }\n};\n#endif\n\n\/\/-----------------------------------------------------------------------------\nCQOptPopulation::CQOptPopulation(COutputHandler * pHandler, CopasiUI3Window * pMainWindow):\n CWindowInterface(),\n mpHandler(pHandler),\n mpMainWindow(pMainWindow),\n mpWindowMenu(NULL),\n mpToolBar(NULL),\n mpaCloseWindow(NULL),\n mCounter(0),\n mDataInitialized(false),\n mGraphInitialized(false),\n initializing(false),\n mNumParameters(0)\n{\n this->resize(640, 480);\n this->setWindowTitle(\"Population Visualization\");\n\n#ifndef Darwin\n setWindowIcon(CQIconResource::icon(CQIconResource::copasi));\n#endif \/\/ not Darwin\n\n\n\n \/\/ set up the GUI - the toolbar\n\n mpGS = new QGraphicsScene(this);\n mpGV = new CQZoomableView(this);\n mpGV->setScene(mpGS);\n this->setCentralWidget(mpGV);\n\n mpGV->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);\n\n\n createActions();\n createMenus();\n createToolBar();\n\n \/\/setCentralWidget(mpPlot);\n\n initializing = true;\n initializing = false;\n\n\n addToMainWindow(mpMainWindow);\n\n connect(this, SIGNAL(updateSignal()), this, SLOT(update()));\n\n}\n\nvoid CQOptPopulation::createMenus()\n{\n QMenu *fileMenu = menuBar()->addMenu(\"&File\");\n\/\/ fileMenu->addAction(mpaSaveImage);\n\n QMenu *viewMenu = menuBar()->addMenu(\"&View\");\n\/\/ viewMenu->addAction(mpaShowAll);\n\/\/ viewMenu->addSeparator();\n static_cast<CQZoomableView*>(mpGV)->fillZoomMenu(viewMenu);\n\n \/\/ add a place holder menu, to be filled by the main window\n mpWindowMenu = menuBar()->addMenu(\"&Window\");\n}\nQMenu *CQOptPopulation::getWindowMenu() const\n{\n return mpWindowMenu;\n}\n\nvoid CQOptPopulation::createActions()\n{\n \/\/mpaToggleLogX = new QAction(\"Log &X\", this);\n \/\/mpaToggleLogX->setCheckable(true);\n \/\/mpaToggleLogX->setToolTip(\"Toggle x-axis logscale.\");\n \/\/connect(mpaToggleLogX, SIGNAL(toggled(bool)), this, SLOT(toggleLogX(bool)));\n\n mpaCloseWindow = new QAction(\"Close\", this);\n mpaCloseWindow->setObjectName(\"close\");\n mpaCloseWindow->setShortcut(Qt::CTRL + Qt::Key_W);\n connect(mpaCloseWindow, SIGNAL(triggered()), this, SLOT(slotCloseWindow()));\n}\n\nvoid CQOptPopulation::createToolBar()\n{\n mpToolBar = addToolBar(\"plot operations\");\n\n\/\/ mpToolBar->addAction(mpaPrint);\n\n\/\/ mpToolBar->addSeparator();\n\n mpToolBar->addAction(mpaCloseWindow);\n\n \/\/TODO button icons...\n static_cast<CQZoomableView*>(mpGV)->fillZoomTooBar(mpToolBar);\n\n setUnifiedTitleAndToolBarOnMac(true);\n}\n\nbool CQOptPopulation::initFromSpec()\n{\n return false;\n}\n\nvoid CQOptPopulation::setMethod(COptMethod* pMethod)\n{\n mpSourceMethod = pMethod;\n mpPopulationMethod = dynamic_cast<COptPopulationMethod*>(pMethod);\n\n if (mpPopulationMethod == NULL)\n {\n mGraphInitialized = false;\n mDataInitialized = false;\n }\n}\n\n\nvoid CQOptPopulation::saveToFile(const QString& fileName) const\n{\n}\n\n\n\nvoid CQOptPopulation::slotSaveData()\n{\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\nCQOptPopulation::~CQOptPopulation()\n{\n if (mpHandler)\n mpHandler->removeInterface(this);\n\n if (mpMainWindow != NULL)\n removeFromMainWindow(mpMainWindow);\n\n pdelete(mpToolBar);\n}\n\nbool CQOptPopulation::compile(CObjectInterface::ContainerList listOfContainer)\n{\n mObjects.clear();\n bool success = true;\n\n return success;\n};\n\n\nvoid CQOptPopulation::separate(const Activity & activity)\n{\n};\n\nvoid CQOptPopulation::finish()\n{\n};\n\nconst CObjectInterface::ObjectSet & CQOptPopulation::getObjects() const\n{\n\n return mObjects;\n}\n\n\nvoid CQOptPopulation::slotCloseWindow()\n{\n QWidget::close();\n}\n\nvoid CQOptPopulation::closeEvent(QCloseEvent *closeEvent)\n{\n mpMainWindow->removeWindow(this);\n mpHandler->removeInterface(this);\n}\n\n\nvoid CQOptPopulation::output(const Activity & activity)\n{\n if (activity != COutputInterface::Activity(0x08))\n return;\n\n if (!mDataInitialized)\n {\n if (!mpSourceMethod)\n return;\n \n CCopasiTask* pTask = dynamic_cast<CCopasiTask*>(mpSourceMethod->getObjectParent());\n\n if (!pTask)\n return;\n\n COptProblem* pProblem = dynamic_cast<COptProblem*>(pTask->getProblem());\n\n if (!pProblem)\n return;\n\n \/\/now that we have access to the problem we can retrieve the range information for the parameters.\n mNumParameters = pProblem->getOptItemList().size();\n mRangeMax.resize(mNumParameters);\n mRangeMin.resize(mNumParameters);\n mIsLog.resize(mNumParameters);\n\n unsigned C_INT32 i;\n\n for (i = 0; i < mNumParameters; ++i)\n {\n COptItem* pOI = pProblem->getOptItemList()[i];\n mRangeMax[i] = *pOI->getUpperBoundValue();\n mRangeMin[i] = *pOI->getLowerBoundValue();\n\n \/\/guess if log scaling should be used. This could also be retrieved from the method?\n if (mRangeMin[i] > 0.0 && mRangeMax[i] > 0.0 && mRangeMax[i] \/ mRangeMin[i] > 1000)\n mIsLog[i] = true;\n else\n mIsLog[i] = false;\n\n }\n\n mDataInitialized = true;\n }\n\n \/\/copy the data\n mPopulation = mpPopulationMethod->getPopulation();\n mObjectiveValues = mpPopulationMethod->getObjectiveValues();\n\n\n mCounter++;\n\n emit updateSignal();\n\n}\n\n\nvoid CQOptPopulation::update()\n{\n\n if (!mGraphInitialized)\n {\n mpGS->clear();\n\n QGraphicsRectItem* rect = mpGS->addRect(-0, -0, 1, 1);\n rect->setBrush(QColor(220, 220, 220));\n\n\n C_INT32 numProjections = (mNumParameters+1) \/ 2;\n mShiftX.resize(numProjections);\n mShiftY.resize(numProjections);\n mXIndex.resize(numProjections);\n mYIndex.resize(numProjections);\n mGraphicItems.resize(numProjections+1); \/\/extra space for the combined view\n\n \/\/if there's more than 2 parameters, create the combined view\n if (mNumParameters>2)\n {\n QGraphicsRectItem* rect = mpGS->addRect(-2.2, 0, 2.1, 2.1);\n rect->setBrush(QColor(230, 230, 250));\n \n mGraphicItems[numProjections].resize(mPopulation.size());\n unsigned C_INT32 i;\n for (i = 0; i < mPopulation.size(); ++i)\n {\n QGraphicsEllipseItem* ei = mpGS->addEllipse(-2.2,0, 0.05, 0.05);\n mGraphicItems[numProjections][i] = ei;\n ei->setBrush(QColor(10, 100, 10));\n ei->setPen(QPen(QColor(0, 0, 0)));\n }\n \n }\n\n C_INT32 j;\n for (j=0; j<numProjections; ++j)\n {\n mShiftX[j] = (j\/2)*1.1;\n mShiftY[j] = (j % 2)*1.1 ;\n mXIndex[j] = j*2;\n mYIndex[j] = (j*2+1) % mNumParameters;\n QGraphicsRectItem* rect = mpGS->addRect(mShiftX[j], mShiftY[j], 1, 1);\n rect->setBrush(QColor(240, 240, 240));\n\n mGraphicItems[j].resize(mPopulation.size());\n \n unsigned C_INT32 i;\n for (i = 0; i < mPopulation.size(); ++i)\n {\n \n QGraphicsEllipseItem* ei = mpGS->addEllipse(mShiftX[j], mShiftY[j], 0.05, 0.05);\n mGraphicItems[j][i] = ei;\n ei->setBrush(QColor(10, 100, 10));\n ei->setPen(QPen(QColor(0, 0, 0)));\n }\n }\n \n static_cast<CQZoomableView*>(mpGV)->slotFitOnScreen();\n mGraphInitialized = true;\n }\n\n \/\/--------------------------------\n \n unsigned C_INT32 i;\n\n \/\/Color scaling\n double tmp_min = 1e300;\n C_INT32 min_index = 0;\n CColorScaleAuto cs;\n cs.startAutomaticParameterCalculation();\n for (i = 0; i<mPopulation.size(); ++i)\n {\n cs.passValue(mObjectiveValues[i]);\n if (mObjectiveValues[i]<tmp_min)\n { tmp_min = mObjectiveValues[i]; min_index = i;}\n }\n cs.finishAutomaticParameterCalculation();\n \/\/std::cout << std::endl;\n\n \n for (i=0; i<mPopulation.size(); ++i)\n {\n \n \/\/first scale the parameters to a unit box\n bool isOnBorder = false;\n std::vector<double> scaled_values; scaled_values.resize(mNumParameters);\n double p0=0; double p1=0; C_INT32 count=0;\n C_INT32 j;\n for (j=0; j<mNumParameters; ++j)\n {\n if (mIsLog[j])\n scaled_values[j] = (log(mPopulation[i]->operator[](j))-log(mRangeMin[j]))\/(log(mRangeMax[j])-log(mRangeMin[j])) ;\n else\n scaled_values[j] = (mPopulation[i]->operator[](j)-mRangeMin[j])\/(mRangeMax[j]-mRangeMin[j]);\n\n if (scaled_values[j]<0.01 || scaled_values[j]>0.99)\n isOnBorder=true;\n \n if (j % 4 == 0)\n {p0 += scaled_values[j]; ++count;}\n if (j % 4 == 1)\n p1 += scaled_values[j];\n if (j % 4 == 2)\n p0 -= scaled_values[j];\n if (j % 4 == 3)\n p1 -= scaled_values[j];\n }\n \n \/\/now update the graph\n \n if (mNumParameters>2)\n {\n QGraphicsEllipseItem* gie = dynamic_cast<QGraphicsEllipseItem*>(mGraphicItems[mShiftX.size()][i]);\n if (gie)\n {\n gie->setX((p0\/count +1)*1.05 -0.025);\n gie->setY((p1\/count +1)*1.05 -0.025);\n gie->setBrush(cs.getColor(mObjectiveValues[i]));\n \/\/highlight parameters on the border of the allowed space\n if (i==min_index)\n gie->setPen(QPen(QColor(0,200,0,200), 0.01));\n else\n gie->setPen(isOnBorder ? QColor(200,0,0,200) : QColor(0,0,0,40));\n }\n }\n \n for (j=0; j<mShiftX.size(); ++j) \/\/loop over the different projections\n {\n QGraphicsEllipseItem* gie = dynamic_cast<QGraphicsEllipseItem*>(mGraphicItems[j][i]);\n if (gie)\n {\n gie->setX(scaled_values[mXIndex[j]]-0.025);\n gie->setY(scaled_values[mYIndex[j]]-0.025);\n gie->setBrush(cs.getColor(mObjectiveValues[i]));\n \/\/highlight parameters on the border of the allowed space\n if (i==min_index)\n gie->setPen(QPen(QColor(0,200,0,200), 0.01));\n else\n gie->setPen(isOnBorder ? QColor(200,0,0,200) : QColor(0,0,0,40));\n }\n }\n }\n \n}\n\n<commit_msg>- add close action to file menu - move the best member on top of the rest of the population<commit_after>\/\/ Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ the window containing the plot and buttons for supported operations\n\n#include <QtSvg\/QtSvg>\n\n#include <QtGui\/QToolBar>\n#include <QtGui\/QPrinter>\n#include <QtGui\/QPixmap>\n#include <QtGui\/QPicture>\n#include <QtSvg\/QSvgGenerator>\n\n#include \"CQOptPopulation.h\"\n\n#include \"UI\/copasiui3window.h\"\n#include \"UI\/CQMessageBox.h\"\n#include \"UI\/qtUtilities.h\"\n#include \"qlayout\/CQZoomableView.h\"\n#include \"UI\/CColorScale.h\"\n#include \"resourcesUI\/CQIconResource.h\"\n#include \"optimization\/COptPopulationMethod.h\"\n#include \"optimization\/COptTask.h\"\n#include \"optimization\/COptProblem.h\"\n#include \"optimization\/COptItem.h\"\n\n#ifdef DEBUG_UI\n#include <QtCore\/QtDebug>\n#endif\n\n#include <qwt_plot.h>\n#include <qwt_scale_engine.h>\n\n#if QWT_VERSION > 0x060000\n#include <qwt_plot_renderer.h>\n#endif\n\n#if QWT_VERSION < 0x060000\n\/\/ taken from qwt examples\/bode\nclass PrintFilter: public QwtPlotPrintFilter\n{\npublic:\n PrintFilter() {};\n\n virtual QFont font(const QFont &f, Item, int) const\n {\n QFont f2 = f;\n f2.setPointSize((int)(f.pointSize() * 0.75));\n return f2;\n }\n};\n#endif\n\n\/\/-----------------------------------------------------------------------------\nCQOptPopulation::CQOptPopulation(COutputHandler * pHandler, CopasiUI3Window * pMainWindow):\n CWindowInterface(),\n mpHandler(pHandler),\n mpMainWindow(pMainWindow),\n mpWindowMenu(NULL),\n mpToolBar(NULL),\n mpaCloseWindow(NULL),\n mCounter(0),\n mDataInitialized(false),\n mGraphInitialized(false),\n initializing(false),\n mNumParameters(0)\n{\n this->resize(640, 480);\n this->setWindowTitle(\"Population Visualization\");\n\n#ifndef Darwin\n setWindowIcon(CQIconResource::icon(CQIconResource::copasi));\n#endif \/\/ not Darwin\n\n\n\n \/\/ set up the GUI - the toolbar\n\n mpGS = new QGraphicsScene(this);\n mpGV = new CQZoomableView(this);\n mpGV->setScene(mpGS);\n this->setCentralWidget(mpGV);\n\n mpGV->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);\n\n\n createActions();\n createMenus();\n createToolBar();\n\n \/\/setCentralWidget(mpPlot);\n\n initializing = true;\n initializing = false;\n\n\n addToMainWindow(mpMainWindow);\n\n connect(this, SIGNAL(updateSignal()), this, SLOT(update()));\n\n}\n\nvoid CQOptPopulation::createMenus()\n{\n QMenu *fileMenu = menuBar()->addMenu(\"&File\");\n fileMenu->addAction(mpaCloseWindow);\n\/\/ fileMenu->addAction(mpaSaveImage);\n\n QMenu *viewMenu = menuBar()->addMenu(\"&View\");\n\/\/ viewMenu->addAction(mpaShowAll);\n\/\/ viewMenu->addSeparator();\n static_cast<CQZoomableView*>(mpGV)->fillZoomMenu(viewMenu);\n\n \/\/ add a place holder menu, to be filled by the main window\n mpWindowMenu = menuBar()->addMenu(\"&Window\");\n}\nQMenu *CQOptPopulation::getWindowMenu() const\n{\n return mpWindowMenu;\n}\n\nvoid CQOptPopulation::createActions()\n{\n \/\/mpaToggleLogX = new QAction(\"Log &X\", this);\n \/\/mpaToggleLogX->setCheckable(true);\n \/\/mpaToggleLogX->setToolTip(\"Toggle x-axis logscale.\");\n \/\/connect(mpaToggleLogX, SIGNAL(toggled(bool)), this, SLOT(toggleLogX(bool)));\n\n mpaCloseWindow = new QAction(\"Close\", this);\n mpaCloseWindow->setObjectName(\"close\");\n mpaCloseWindow->setShortcut(Qt::CTRL + Qt::Key_W);\n connect(mpaCloseWindow, SIGNAL(triggered()), this, SLOT(slotCloseWindow()));\n}\n\nvoid CQOptPopulation::createToolBar()\n{\n mpToolBar = addToolBar(\"plot operations\");\n\n\/\/ mpToolBar->addAction(mpaPrint);\n\n\/\/ mpToolBar->addSeparator();\n\n mpToolBar->addAction(mpaCloseWindow);\n\n \/\/TODO button icons...\n static_cast<CQZoomableView*>(mpGV)->fillZoomTooBar(mpToolBar);\n\n setUnifiedTitleAndToolBarOnMac(true);\n}\n\nbool CQOptPopulation::initFromSpec()\n{\n return false;\n}\n\nvoid CQOptPopulation::setMethod(COptMethod* pMethod)\n{\n mpSourceMethod = pMethod;\n mpPopulationMethod = dynamic_cast<COptPopulationMethod*>(pMethod);\n\n if (mpPopulationMethod == NULL)\n {\n mGraphInitialized = false;\n mDataInitialized = false;\n }\n}\n\n\nvoid CQOptPopulation::saveToFile(const QString& fileName) const\n{\n}\n\n\n\nvoid CQOptPopulation::slotSaveData()\n{\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\nCQOptPopulation::~CQOptPopulation()\n{\n if (mpHandler)\n mpHandler->removeInterface(this);\n\n if (mpMainWindow != NULL)\n removeFromMainWindow(mpMainWindow);\n\n pdelete(mpToolBar);\n}\n\nbool CQOptPopulation::compile(CObjectInterface::ContainerList listOfContainer)\n{\n mObjects.clear();\n bool success = true;\n\n return success;\n};\n\n\nvoid CQOptPopulation::separate(const Activity & activity)\n{\n};\n\nvoid CQOptPopulation::finish()\n{\n};\n\nconst CObjectInterface::ObjectSet & CQOptPopulation::getObjects() const\n{\n\n return mObjects;\n}\n\n\nvoid CQOptPopulation::slotCloseWindow()\n{\n QWidget::close();\n}\n\nvoid CQOptPopulation::closeEvent(QCloseEvent *closeEvent)\n{\n mpMainWindow->removeWindow(this);\n mpHandler->removeInterface(this);\n}\n\n\nvoid CQOptPopulation::output(const Activity & activity)\n{\n if (activity != COutputInterface::Activity(0x08))\n return;\n\n if (!mDataInitialized)\n {\n if (!mpSourceMethod)\n return;\n\n CCopasiTask* pTask = dynamic_cast<CCopasiTask*>(mpSourceMethod->getObjectParent());\n\n if (!pTask)\n return;\n\n COptProblem* pProblem = dynamic_cast<COptProblem*>(pTask->getProblem());\n\n if (!pProblem)\n return;\n\n \/\/now that we have access to the problem we can retrieve the range information for the parameters.\n mNumParameters = pProblem->getOptItemList().size();\n mRangeMax.resize(mNumParameters);\n mRangeMin.resize(mNumParameters);\n mIsLog.resize(mNumParameters);\n\n C_INT32 i;\n\n for (i = 0; i < mNumParameters; ++i)\n {\n COptItem* pOI = pProblem->getOptItemList()[i];\n mRangeMax[i] = *pOI->getUpperBoundValue();\n mRangeMin[i] = *pOI->getLowerBoundValue();\n\n \/\/guess if log scaling should be used. This could also be retrieved from the method?\n if (mRangeMin[i] > 0.0 && mRangeMax[i] > 0.0 && mRangeMax[i] \/ mRangeMin[i] > 1000)\n mIsLog[i] = true;\n else\n mIsLog[i] = false;\n\n }\n\n mDataInitialized = true;\n }\n\n \/\/copy the data\n mPopulation = mpPopulationMethod->getPopulation();\n mObjectiveValues = mpPopulationMethod->getObjectiveValues();\n\n\n mCounter++;\n\n emit updateSignal();\n\n}\n\n\nvoid CQOptPopulation::update()\n{\n\n if (!mGraphInitialized)\n {\n mpGS->clear();\n\n QGraphicsRectItem* rect = mpGS->addRect(-0, -0, 1, 1);\n rect->setBrush(QColor(220, 220, 220));\n\n\n C_INT32 numProjections = (mNumParameters + 1) \/ 2;\n mShiftX.resize(numProjections);\n mShiftY.resize(numProjections);\n mXIndex.resize(numProjections);\n mYIndex.resize(numProjections);\n mGraphicItems.resize(numProjections + 1); \/\/extra space for the combined view\n\n \/\/if there's more than 2 parameters, create the combined view\n if (mNumParameters > 2)\n {\n QGraphicsRectItem* rect = mpGS->addRect(-2.2, 0, 2.1, 2.1);\n rect->setBrush(QColor(230, 230, 250));\n\n mGraphicItems[numProjections].resize(mPopulation.size());\n unsigned C_INT32 i;\n\n for (i = 0; i < mPopulation.size(); ++i)\n {\n QGraphicsEllipseItem* ei = mpGS->addEllipse(-2.2, 0, 0.05, 0.05);\n mGraphicItems[numProjections][i] = ei;\n ei->setBrush(QColor(10, 100, 10));\n ei->setPen(QPen(QColor(0, 0, 0)));\n }\n\n }\n\n C_INT32 j;\n\n for (j = 0; j < numProjections; ++j)\n {\n mShiftX[j] = (j \/ 2) * 1.1;\n mShiftY[j] = (j % 2) * 1.1 ;\n mXIndex[j] = j * 2;\n mYIndex[j] = (j * 2 + 1) % mNumParameters;\n QGraphicsRectItem* rect = mpGS->addRect(mShiftX[j], mShiftY[j], 1, 1);\n rect->setBrush(QColor(240, 240, 240));\n\n mGraphicItems[j].resize(mPopulation.size());\n\n unsigned C_INT32 i;\n\n for (i = 0; i < mPopulation.size(); ++i)\n {\n\n QGraphicsEllipseItem* ei = mpGS->addEllipse(mShiftX[j], mShiftY[j], 0.05, 0.05);\n mGraphicItems[j][i] = ei;\n ei->setBrush(QColor(10, 100, 10));\n ei->setPen(QPen(QColor(0, 0, 0)));\n }\n }\n\n static_cast<CQZoomableView*>(mpGV)->slotFitOnScreen();\n\n mGraphInitialized = true;\n }\n\n \/\/--------------------------------\n\n unsigned C_INT32 i;\n\n \/\/Color scaling\n double tmp_min = 1e300;\n C_INT32 min_index = 0;\n CColorScaleAuto cs;\n cs.startAutomaticParameterCalculation();\n\n for (i = 0; i < mPopulation.size(); ++i)\n {\n cs.passValue(mObjectiveValues[i]);\n\n if (mObjectiveValues[i] < tmp_min)\n { tmp_min = mObjectiveValues[i]; min_index = i;}\n }\n\n cs.finishAutomaticParameterCalculation();\n \/\/std::cout << std::endl;\n\n\n for (i = 0; i < mPopulation.size(); ++i)\n {\n\n \/\/first scale the parameters to a unit box\n bool isOnBorder = false;\n std::vector<double> scaled_values; scaled_values.resize(mNumParameters);\n double p0 = 0; double p1 = 0; C_INT32 count = 0;\n C_INT32 j;\n\n for (j = 0; j < mNumParameters; ++j)\n {\n if (mIsLog[j])\n scaled_values[j] = (log(mPopulation[i]->operator[](j)) - log(mRangeMin[j])) \/ (log(mRangeMax[j]) - log(mRangeMin[j])) ;\n else\n scaled_values[j] = (mPopulation[i]->operator[](j) - mRangeMin[j]) \/ (mRangeMax[j] - mRangeMin[j]);\n\n if (scaled_values[j] < 0.01 || scaled_values[j] > 0.99)\n isOnBorder = true;\n\n if (j % 4 == 0)\n {p0 += scaled_values[j]; ++count;}\n\n if (j % 4 == 1)\n p1 += scaled_values[j];\n\n if (j % 4 == 2)\n p0 -= scaled_values[j];\n\n if (j % 4 == 3)\n p1 -= scaled_values[j];\n }\n\n \/\/now update the graph\n\n if (mNumParameters > 2)\n {\n QGraphicsEllipseItem* gie = dynamic_cast<QGraphicsEllipseItem*>(mGraphicItems[mShiftX.size()][i]);\n\n if (gie)\n {\n gie->setX((p0 \/ count + 1) * 1.05 - 0.025);\n gie->setY((p1 \/ count + 1) * 1.05 - 0.025);\n gie->setBrush(cs.getColor(mObjectiveValues[i]));\n\n \/\/highlight parameters on the border of the allowed space\n if (i == min_index)\n {\n gie->setPen(QPen(QColor(0, 200, 0, 200), 0.01));\n gie->setZValue(1.0);\n }\n else\n {\n gie->setPen(isOnBorder ? QColor(200, 0, 0, 200) : QColor(0, 0, 0, 40));\n gie->setZValue(0.0);\n }\n }\n }\n\n for (j = 0; j < mShiftX.size(); ++j) \/\/loop over the different projections\n {\n QGraphicsEllipseItem* gie = dynamic_cast<QGraphicsEllipseItem*>(mGraphicItems[j][i]);\n\n if (gie)\n {\n gie->setX(scaled_values[mXIndex[j]] - 0.025);\n gie->setY(scaled_values[mYIndex[j]] - 0.025);\n gie->setBrush(cs.getColor(mObjectiveValues[i]));\n\n \/\/highlight parameters on the border of the allowed space\n if (i == min_index)\n {\n gie->setPen(QPen(QColor(0, 200, 0, 200), 0.01));\n gie->setZValue(1.0);\n }\n else\n {\n gie->setPen(isOnBorder ? QColor(200, 0, 0, 200) : QColor(0, 0, 0, 40));\n gie->setZValue(0.0);\n }\n }\n }\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Zinge on 7\/4\/16.\n\/\/\n\/\/\n#include \"ee\/twitter\/TwitterBridge.hpp\"\n\n#include \"ee\/core\/MessageBridge.hpp\"\n#include \"ee\/core\/Utils.hpp\"\n#include <ee\/nlohmann\/json.hpp>\n\nnamespace ee {\nnamespace twitter {\nnamespace {\n\/\/ clang-format off\nconstexpr auto k__initialize = \"twitter_initialize\";\nconstexpr auto k__shareContent = \"twitter_shareContent\";\nconstexpr auto k__shareScreenShot = \"twitter_shareScreenShot\";\nconstexpr auto k__onSuccess = \"twitter_onSuccess\";\nconstexpr auto k__onFailure = \"twitter_onFailure\";\nconstexpr auto k__onCancel = \"twitter_onCancel\";\nconstexpr auto k__key = \"twitter_key\";\nconstexpr auto k__secret = \"twitter_secret\";\nconstexpr auto k__text = \"twitter_text\";\nconstexpr auto k__image = \"twitter_image\";\n\/\/ clang-format on\n} \/\/ namespace\n\nusing Self = Twitter;\n\nSelf::Twitter()\n : bridge_(MessageBridge::getInstance()) {\n bridge_.registerHandler(\n [this](const std::string& message) {\n onSuccess();\n return \"\";\n },\n k__onSuccess);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onFailure();\n return \"\";\n },\n k__onFailure);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onCancel();\n return \"\";\n },\n k__onCancel);\n}\n\nSelf::~Twitter() {\n bridge_.deregisterHandler(k__onSuccess);\n bridge_.deregisterHandler(k__onFailure);\n bridge_.deregisterHandler(k__onCancel);\n}\n\nvoid Self::initialize(const std::string& key, const std::string& secret) {\n nlohmann::json json;\n json[k__key] = key;\n json[k__secret] = secret;\n bridge_.call(k__initialize, json.dump());\n}\n\nvoid Self::setShareResultCallback(const ShareResultCallback& callback) {\n _callback = callback;\n}\n\nvoid Self::shareContent(const std::string& text) {\n _hadCallFailure = false;\n nlohmann::json json;\n json[k__text] = text;\n bridge_.call(k__shareContent, json.dump());\n}\n\nvoid Self::shareScreenShot(const std::string& text, const std::string& image) {\n _hadCallFailure = false;\n nlohmann::json json;\n json[k__text] = text;\n json[k__image] = image;\n bridge_.call(k__shareScreenShot, json.dump());\n}\n\nvoid Self::onSuccess() {\n if (_callback) {\n _hadCallFailure = false;\n _callback(true);\n }\n}\n\nvoid Self::onFailure() {\n if (_callback) {\n _hadCallFailure = true;\n _callback(false);\n }\n}\n\nvoid Self::onCancel() {\n if (_callback) {\n if (!_hadCallFailure) {\n _callback(false);\n }\n }\n}\n\n} \/\/ namespace twitter\n} \/\/ namespace ee\n<commit_msg>fix format<commit_after>\/\/\n\/\/ Created by Zinge on 7\/4\/16.\n\/\/\n\/\/\n#include \"ee\/twitter\/TwitterBridge.hpp\"\n\n#include <ee\/nlohmann\/json.hpp>\n\n#include \"ee\/core\/MessageBridge.hpp\"\n#include \"ee\/core\/Utils.hpp\"\n\nnamespace ee {\nnamespace twitter {\nnamespace {\n\/\/ clang-format off\nconstexpr auto k__initialize = \"twitter_initialize\";\nconstexpr auto k__shareContent = \"twitter_shareContent\";\nconstexpr auto k__shareScreenShot = \"twitter_shareScreenShot\";\nconstexpr auto k__onSuccess = \"twitter_onSuccess\";\nconstexpr auto k__onFailure = \"twitter_onFailure\";\nconstexpr auto k__onCancel = \"twitter_onCancel\";\nconstexpr auto k__key = \"twitter_key\";\nconstexpr auto k__secret = \"twitter_secret\";\nconstexpr auto k__text = \"twitter_text\";\nconstexpr auto k__image = \"twitter_image\";\n\/\/ clang-format on\n} \/\/ namespace\n\nusing Self = Twitter;\n\nSelf::Twitter()\n : bridge_(MessageBridge::getInstance()) {\n bridge_.registerHandler(\n [this](const std::string& message) {\n onSuccess();\n return \"\";\n },\n k__onSuccess);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onFailure();\n return \"\";\n },\n k__onFailure);\n bridge_.registerHandler(\n [this](const std::string& message) {\n onCancel();\n return \"\";\n },\n k__onCancel);\n}\n\nSelf::~Twitter() {\n bridge_.deregisterHandler(k__onSuccess);\n bridge_.deregisterHandler(k__onFailure);\n bridge_.deregisterHandler(k__onCancel);\n}\n\nvoid Self::initialize(const std::string& key, const std::string& secret) {\n nlohmann::json json;\n json[k__key] = key;\n json[k__secret] = secret;\n bridge_.call(k__initialize, json.dump());\n}\n\nvoid Self::setShareResultCallback(const ShareResultCallback& callback) {\n _callback = callback;\n}\n\nvoid Self::shareContent(const std::string& text) {\n _hadCallFailure = false;\n nlohmann::json json;\n json[k__text] = text;\n bridge_.call(k__shareContent, json.dump());\n}\n\nvoid Self::shareScreenShot(const std::string& text, const std::string& image) {\n _hadCallFailure = false;\n nlohmann::json json;\n json[k__text] = text;\n json[k__image] = image;\n bridge_.call(k__shareScreenShot, json.dump());\n}\n\nvoid Self::onSuccess() {\n if (_callback) {\n _hadCallFailure = false;\n _callback(true);\n }\n}\n\nvoid Self::onFailure() {\n if (_callback) {\n _hadCallFailure = true;\n _callback(false);\n }\n}\n\nvoid Self::onCancel() {\n if (_callback) {\n if (!_hadCallFailure) {\n _callback(false);\n }\n }\n}\n\n} \/\/ namespace twitter\n} \/\/ namespace ee\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This source file is part of Hect.\n\/\/\n\/\/ Copyright (c) 2015 Colin Hill\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\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell 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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"PhysFSFileSystem.h\"\n\n#include <cassert>\n#include <physfs.h>\n\n#include \"Hect\/Core\/Configuration.h\"\n#include \"Hect\/Core\/Exception.h\"\n#include \"Hect\/Core\/Format.h\"\n#include \"Hect\/Core\/Logging.h\"\n#include \"Hect\/Core\/Uncopyable.h\"\n#include \"Hect\/IO\/FileSystems\/PhysFSReadStream.h\"\n#include \"Hect\/IO\/FileSystems\/PhysFSWriteStream.h\"\n\n#ifdef HECT_WINDOWS_BUILD\n#include <Windows.h>\n#include <shlwapi.h>\n#include <shlobj.h>\n#else\n#include <unistd.h>\n#endif\n\nusing namespace hect;\n\nPhysFSFileSystem::PhysFSFileSystem(int argc, char* const argv[])\n{\n (void)argc;\n\n assert(!_initialized);\n if (!PHYSFS_init(argv[0]))\n {\n throw FatalError(format(\"Failed to initialize PhysFS: %s\", PHYSFS_getLastError()));\n }\n _initialized = true;\n}\n\nPhysFSFileSystem::~PhysFSFileSystem()\n{\n if (!PHYSFS_deinit())\n {\n throw FatalError(format(\"Failed to shutdown PhysFS: %s\", PHYSFS_getLastError()));\n }\n}\n\nPath PhysFSFileSystem::baseDirectory()\n{\n return convertPath(PHYSFS_getBaseDir());\n}\n\nPath PhysFSFileSystem::workingDirectory()\n{\n#ifdef HECT_WINDOWS_BUILD\n char path[2048];\n GetCurrentDirectory(2048, path);\n return convertPath(path);\n#else\n char* rawPath = get_current_dir_name();\n Path path(rawPath);\n free(rawPath);\n return path;\n#endif\n}\n\nPath PhysFSFileSystem::userDirectory()\n{\n return convertPath(PHYSFS_getUserDir());\n}\n\nPath PhysFSFileSystem::applicationDataDirectory()\n{\n#ifdef HECT_WINDOWS_BUILD\n TCHAR path[MAX_PATH];\n assert(SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, path)));\n return convertPath(path);\n#else\n return Path();\n#endif\n}\n\nvoid PhysFSFileSystem::setWriteDirectory(const Path& path)\n{\n if (!PHYSFS_setWriteDir(path.asString().c_str()))\n {\n throw IOError(format(\"Failed to set write directory to '%s': %s\", path.asString().c_str(), PHYSFS_getLastError()));\n }\n}\n\nvoid PhysFSFileSystem::mountArchive(const Path& path, const Path& mountPoint)\n{\n const char* pathString = path.asString().c_str();\n const char* mountPointString = mountPoint.asString().c_str();\n\n if (!PHYSFS_mount(pathString, mountPointString, 0))\n {\n throw IOError(format(\"Failed to mount archive '%s': %s\", pathString, PHYSFS_getLastError()));\n }\n\n if (mountPoint.empty())\n {\n HECT_INFO(format(\"Mounted archive '%s'\", pathString));\n }\n else\n {\n HECT_INFO(format(\"Mounted archive '%s' to '%s'\", pathString, mountPointString));\n }\n}\n\nstd::unique_ptr<ReadStream> PhysFSFileSystem::openFileForRead(const Path& path)\n{\n return std::unique_ptr<ReadStream>(new PhysFSReadStream(path));\n}\n\nstd::unique_ptr<WriteStream> PhysFSFileSystem::openFileForWrite(const Path& path)\n{\n return std::unique_ptr<WriteStream>(new PhysFSWriteStream(path));\n}\n\nvoid PhysFSFileSystem::createDirectory(const Path& path)\n{\n if (!PHYSFS_mkdir(path.asString().c_str()))\n {\n throw IOError(format(\"Failed to create directory: %s\", PHYSFS_getLastError()));\n }\n}\n\nstd::vector<Path> PhysFSFileSystem::filesInDirectory(const Path& path)\n{\n char** paths = PHYSFS_enumerateFiles(path.asString().c_str());\n\n std::vector<Path> resultingPaths;\n for (char** i = paths; *i != nullptr; ++i)\n {\n resultingPaths.push_back(path + *i);\n }\n\n PHYSFS_freeList(paths);\n\n return resultingPaths;\n}\n\nvoid PhysFSFileSystem::remove(const Path& path)\n{\n if (!PHYSFS_delete(path.asString().c_str()))\n {\n throw IOError(format(\"Failed to remove directory: %s\", PHYSFS_getLastError()));\n }\n}\n\nbool PhysFSFileSystem::exists(const Path& path)\n{\n return PHYSFS_exists(path.asString().c_str()) != 0;\n}\n\nTimeStamp PhysFSFileSystem::lastModified(const Path& path)\n{\n return PHYSFS_getLastModTime(path.asString().c_str());\n}\n\nPath PhysFSFileSystem::convertPath(const char* rawPath)\n{\n std::string delimiter(PHYSFS_getDirSeparator());\n std::string string(rawPath);\n\n size_t start = 0;\n while ((start = string.find(delimiter, start)) != std::string::npos)\n {\n string.replace(start, delimiter.length(), \"\/\");\n start += 1;\n }\n\n return Path(string);\n}\n\nbool PhysFSFileSystem::_initialized = false;\n<commit_msg>Fixed a forgotten include change needed for last commit<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This source file is part of Hect.\n\/\/\n\/\/ Copyright (c) 2015 Colin Hill\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\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell 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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"PhysFSFileSystem.h\"\n\n#include <cassert>\n#include <physfs.h>\n\n#include \"Hect\/Core\/Configuration.h\"\n#include \"Hect\/Core\/Exception.h\"\n#include \"Hect\/Core\/Format.h\"\n#include \"Hect\/Core\/Logging.h\"\n#include \"Hect\/Core\/Uncopyable.h\"\n#include \"Hect\/IO\/Internal\/PhysFSReadStream.h\"\n#include \"Hect\/IO\/Internal\/PhysFSWriteStream.h\"\n\n#ifdef HECT_WINDOWS_BUILD\n#include <Windows.h>\n#include <shlwapi.h>\n#include <shlobj.h>\n#else\n#include <unistd.h>\n#endif\n\nusing namespace hect;\n\nPhysFSFileSystem::PhysFSFileSystem(int argc, char* const argv[])\n{\n (void)argc;\n\n assert(!_initialized);\n if (!PHYSFS_init(argv[0]))\n {\n throw FatalError(format(\"Failed to initialize PhysFS: %s\", PHYSFS_getLastError()));\n }\n _initialized = true;\n}\n\nPhysFSFileSystem::~PhysFSFileSystem()\n{\n if (!PHYSFS_deinit())\n {\n throw FatalError(format(\"Failed to shutdown PhysFS: %s\", PHYSFS_getLastError()));\n }\n}\n\nPath PhysFSFileSystem::baseDirectory()\n{\n return convertPath(PHYSFS_getBaseDir());\n}\n\nPath PhysFSFileSystem::workingDirectory()\n{\n#ifdef HECT_WINDOWS_BUILD\n char path[2048];\n GetCurrentDirectory(2048, path);\n return convertPath(path);\n#else\n char* rawPath = get_current_dir_name();\n Path path(rawPath);\n free(rawPath);\n return path;\n#endif\n}\n\nPath PhysFSFileSystem::userDirectory()\n{\n return convertPath(PHYSFS_getUserDir());\n}\n\nPath PhysFSFileSystem::applicationDataDirectory()\n{\n#ifdef HECT_WINDOWS_BUILD\n TCHAR path[MAX_PATH];\n assert(SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, path)));\n return convertPath(path);\n#else\n return Path();\n#endif\n}\n\nvoid PhysFSFileSystem::setWriteDirectory(const Path& path)\n{\n if (!PHYSFS_setWriteDir(path.asString().c_str()))\n {\n throw IOError(format(\"Failed to set write directory to '%s': %s\", path.asString().c_str(), PHYSFS_getLastError()));\n }\n}\n\nvoid PhysFSFileSystem::mountArchive(const Path& path, const Path& mountPoint)\n{\n const char* pathString = path.asString().c_str();\n const char* mountPointString = mountPoint.asString().c_str();\n\n if (!PHYSFS_mount(pathString, mountPointString, 0))\n {\n throw IOError(format(\"Failed to mount archive '%s': %s\", pathString, PHYSFS_getLastError()));\n }\n\n if (mountPoint.empty())\n {\n HECT_INFO(format(\"Mounted archive '%s'\", pathString));\n }\n else\n {\n HECT_INFO(format(\"Mounted archive '%s' to '%s'\", pathString, mountPointString));\n }\n}\n\nstd::unique_ptr<ReadStream> PhysFSFileSystem::openFileForRead(const Path& path)\n{\n return std::unique_ptr<ReadStream>(new PhysFSReadStream(path));\n}\n\nstd::unique_ptr<WriteStream> PhysFSFileSystem::openFileForWrite(const Path& path)\n{\n return std::unique_ptr<WriteStream>(new PhysFSWriteStream(path));\n}\n\nvoid PhysFSFileSystem::createDirectory(const Path& path)\n{\n if (!PHYSFS_mkdir(path.asString().c_str()))\n {\n throw IOError(format(\"Failed to create directory: %s\", PHYSFS_getLastError()));\n }\n}\n\nstd::vector<Path> PhysFSFileSystem::filesInDirectory(const Path& path)\n{\n char** paths = PHYSFS_enumerateFiles(path.asString().c_str());\n\n std::vector<Path> resultingPaths;\n for (char** i = paths; *i != nullptr; ++i)\n {\n resultingPaths.push_back(path + *i);\n }\n\n PHYSFS_freeList(paths);\n\n return resultingPaths;\n}\n\nvoid PhysFSFileSystem::remove(const Path& path)\n{\n if (!PHYSFS_delete(path.asString().c_str()))\n {\n throw IOError(format(\"Failed to remove directory: %s\", PHYSFS_getLastError()));\n }\n}\n\nbool PhysFSFileSystem::exists(const Path& path)\n{\n return PHYSFS_exists(path.asString().c_str()) != 0;\n}\n\nTimeStamp PhysFSFileSystem::lastModified(const Path& path)\n{\n return PHYSFS_getLastModTime(path.asString().c_str());\n}\n\nPath PhysFSFileSystem::convertPath(const char* rawPath)\n{\n std::string delimiter(PHYSFS_getDirSeparator());\n std::string string(rawPath);\n\n size_t start = 0;\n while ((start = string.find(delimiter, start)) != std::string::npos)\n {\n string.replace(start, delimiter.length(), \"\/\");\n start += 1;\n }\n\n return Path(string);\n}\n\nbool PhysFSFileSystem::_initialized = false;\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Copyright (c) Kitware Inc.\n All rights reserved.\n\n=========================================================================*\/\n\/\/ .SECTION Thanks\n\/\/ This test was written by Charles Law and Philippe Pebay, Kitware 2012\n\n#include \"vtkHyperTreeGrid.h\"\n#include \"vtkHyperTreeGridAxisCut.h\"\n#include \"vtkHyperTreeGridFractalSource.h\"\n#include \"vtkHyperTreeGridGeometry.h\"\n\n#include \"vtkCamera.h\"\n#include \"vtkCellData.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkCutter.h\"\n#include \"vtkDataSetWriter.h\"\n#include \"vtkNew.h\"\n#include \"vtkPlane.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkPolyDataWriter.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkShrinkFilter.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkUnstructuredGridWriter.h\"\n#include \"vtkXMLUnstructuredGridWriter.h\"\n\nint TestHyperTreeGrid( int argc, char* argv[] )\n{\n \/\/ Initialize return value of test\n int testIntValue = 0;\n\n \/\/ Dimension of hyper trees\n int dim = 3;\n\n \/\/ Create hyper tree grid source\n vtkHyperTreeGridFractalSource* fractal = vtkHyperTreeGridFractalSource::New();\n fractal->SetMaximumLevel( 3 );\n fractal->DualOn();\n if ( dim == 3 )\n {\n fractal->SetGridSize( 3, 4, 2 );\n }\n else if ( dim == 2 )\n {\n fractal->SetGridSize( 3, 4, 1 );\n }\n else if ( dim == 1 )\n {\n fractal->SetGridSize( 3, 1, 1 );\n }\n else\n {\n return 1;\n }\n fractal->SetDimension( dim );\n fractal->SetAxisBranchFactor( 3 );\n fractal->Update();\n vtkHyperTreeGrid* htGrid = fractal->GetOutput();\n\n cerr << \"# Geometry\" << endl;\n vtkNew<vtkHyperTreeGridGeometry> geometry;\n geometry->SetInputConnection( fractal->GetOutputPort() );\n vtkNew<vtkPolyDataWriter> writer4;\n writer4->SetFileName( \".\/hyperTreeGridGeometry.vtk\" );\n writer4->SetInputConnection( geometry->GetOutputPort() );\n writer4->Write();\n\n cerr << \"# Contour\" << endl;\n vtkNew<vtkContourFilter> contour;\n contour->SetInputData( htGrid );\n contour->SetNumberOfContours( 2 );\n contour->SetValue( 0, 4. );\n contour->SetValue( 1, 18. );\n contour->SetInputArrayToProcess( 0, 0, 0,\n vtkDataObject::FIELD_ASSOCIATION_POINTS,\n \"Cell Value\" );\n vtkNew<vtkPolyDataWriter> writer0;\n writer0->SetFileName( \".\/hyperTreeGridContour.vtk\" );\n writer0->SetInputConnection( contour->GetOutputPort() );\n writer0->Write();\n\n cerr << \"# Shrink\" << endl;\n vtkNew<vtkShrinkFilter> shrink;\n shrink->SetInputData( htGrid );\n shrink->SetShrinkFactor( 1. );\n vtkNew<vtkUnstructuredGridWriter> writer1;\n writer1->SetFileName( \".\/hyperTreeGridShrink.vtk\" );\n writer1->SetInputConnection( shrink->GetOutputPort() );\n writer1->Write();\n\n \/\/ Axis-aligned cut works only in 3D for now\n if ( dim == 3 )\n {\n cerr << \"# HyperTreeGridAxisCut\" << endl;\n vtkNew<vtkHyperTreeGridAxisCut> axisCut;\n axisCut->SetInputConnection( fractal->GetOutputPort() );\n axisCut->SetPlaneNormalAxis( 2 );\n axisCut->SetPlanePosition( .1 );\n vtkNew<vtkPolyDataWriter> writer2;\n writer2->SetFileName( \".\/hyperTreeGridAxisCut.vtk\" );\n writer2->SetInputConnection( axisCut->GetOutputPort() );\n writer2->Write();\n }\n\n cerr << \"# Cut\" << endl;\n vtkNew<vtkCutter> cut;\n vtkNew<vtkPlane> plane;\n plane->SetOrigin( .5, .5, .15 );\n plane->SetNormal( 0, 0, 1 );\n cut->SetInputData( htGrid );\n cut->SetCutFunction( plane.GetPointer() );\n vtkNew<vtkPolyDataWriter> writer3;\n writer3->SetFileName( \".\/hyperTreeGridCut.vtk\" );\n writer3->SetInputConnection( cut->GetOutputPort() );\n writer3->Write();\n\n \/\/ Create mapper\n vtkNew<vtkPolyDataMapper> mapper;\n mapper->SetInputConnection( geometry->GetOutputPort() );\n vtkPolyData* pd = geometry->GetOutput();\n mapper->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() );\n \n \/\/ Create actor\n vtkNew<vtkActor> actor;\n actor->SetMapper( mapper.GetPointer() );\n\n \/\/ Create camera\n double bd[3];\n pd->GetBounds( bd );\n vtkNew<vtkCamera> camera;\n camera->SetClippingRange( 1., 100. );\n camera->SetFocalPoint( pd->GetCenter() );\n camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] );\n\n \/\/ Create a renderer, add actors to it\n vtkNew<vtkRenderer> renderer;\n renderer->SetActiveCamera( camera.GetPointer() );\n renderer->SetBackground( 1., 1., 1. );\n renderer->AddActor( actor.GetPointer() );\n\n \/\/ Create a renderWindow\n vtkNew<vtkRenderWindow> renWin;\n renWin->AddRenderer( renderer.GetPointer() );\n renWin->SetSize( 300, 300 );\n renWin->SetMultiSamples( 0 );\n\n \/\/ Create interactor\n vtkNew<vtkRenderWindowInteractor> iren;\n iren->SetRenderWindow( renWin.GetPointer() );\n\n \/\/ Render and test\n renWin->Render();\n \n int retVal = vtkRegressionTestImage( renWin.GetPointer() );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR )\n {\n iren->Start();\n }\n\n \/\/ Clean up\n \/\/htGrid->Delete();\n fractal->Delete();\n\n return testIntValue;\n}\n<commit_msg>A new test with plenty of options for thorough and convenient testing<commit_after>\/*=========================================================================\n\nCopyright (c) Kitware Inc.\nAll rights reserved.\n\n=========================================================================*\/\n\/\/ .SECTION Thanks\n\/\/ This test was written by Charles Law and Philippe Pebay, Kitware 2012\n\n#include \"vtkHyperTreeGrid.h\"\n#include \"vtkHyperTreeGridAxisCut.h\"\n#include \"vtkHyperTreeGridFractalSource.h\"\n#include \"vtkHyperTreeGridGeometry.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkCutter.h\"\n#include \"vtkDataSetWriter.h\"\n#include \"vtkNew.h\"\n#include \"vtkPlane.h\"\n#include \"vtkPolyDataWriter.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkShrinkFilter.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkUnstructuredGridWriter.h\"\n#include \"vtkXMLUnstructuredGridWriter.h\"\n\n#include \"vtksys\/CommandLineArguments.hxx\"\n\nint TestHyperTreeGrid( int argc, char* argv[] )\n{\n \/\/ Default parameters and options\n int dim = 3;\n int nX = 3;\n int nY = 4;\n int nZ = 2;\n bool skipAxisCut = false;\n bool skipContour = false;\n bool skipCut = false;\n bool skipGeometry = false;\n bool skipShrink = false;\n\n \/\/ Initialize command line argument parser\n vtksys::CommandLineArguments clArgs;\n clArgs.Initialize( argc, argv );\n clArgs.StoreUnusedArguments( false );\n\n \/\/ Parse command line parameters and options\n clArgs.AddArgument(\"--dimension\",\n vtksys::CommandLineArguments::SPACE_ARGUMENT,\n &dim, \"Dimension of hyper tree grid\");\n\n clArgs.AddArgument(\"--grid-size-X\",\n vtksys::CommandLineArguments::SPACE_ARGUMENT,\n &nX, \"Size of hyper tree grid in X direction\");\n\n clArgs.AddArgument(\"--grid-size-Y\",\n vtksys::CommandLineArguments::SPACE_ARGUMENT,\n &nY, \"Size of hyper tree grid in Y direction\");\n\n clArgs.AddArgument(\"--grid-size-Z\",\n vtksys::CommandLineArguments::SPACE_ARGUMENT,\n &nZ, \"Size of hyper tree grid in Z direction\");\n\n clArgs.AddArgument(\"--skip-Axis-Cut\",\n vtksys::CommandLineArguments::NO_ARGUMENT,\n &skipAxisCut, \"Skip axis cut filter\");\n\n clArgs.AddArgument(\"--skip-Contour\",\n vtksys::CommandLineArguments::NO_ARGUMENT,\n &skipAxisCut, \"Skip contour filter\");\n\n clArgs.AddArgument(\"--skip-Cut\",\n vtksys::CommandLineArguments::NO_ARGUMENT,\n &skipCut, \"Skip cut filter\");\n\n clArgs.AddArgument(\"--skip-Geometry\",\n vtksys::CommandLineArguments::NO_ARGUMENT,\n &skipGeometry, \"Skip geometry filter\");\n\n clArgs.AddArgument(\"--skip-Shrink\",\n vtksys::CommandLineArguments::NO_ARGUMENT,\n &skipShrink, \"Skip shrink filter\");\n\n \/\/ If incorrect arguments were provided, provide some help and terminate in error.\n if ( ! clArgs.Parse() )\n {\n cerr << \"Usage: \"\n << clArgs.GetHelp()\n << \"\\n\";\n }\n\n \/\/ Initialize return value of test\n int testIntValue = 0;\n\n \/\/ Create hyper tree grid source\n vtkHyperTreeGridFractalSource* fractal = vtkHyperTreeGridFractalSource::New();\n fractal->SetMaximumLevel( 3 );\n fractal->DualOn();\n if ( dim == 3 )\n {\n fractal->SetGridSize( nX, nY, nZ );\n }\n else if ( dim == 2 )\n {\n fractal->SetGridSize( nX, nY, 1 );\n }\n else if ( dim == 1 )\n {\n fractal->SetGridSize( nX, 1, 1 );\n }\n else\n {\n return 1;\n }\n fractal->SetDimension( dim );\n fractal->SetAxisBranchFactor( 3 );\n fractal->Update();\n vtkHyperTreeGrid* htGrid = fractal->GetOutput();\n\n if ( ! skipGeometry )\n {\n cerr << \"# Geometry\" << endl;\n vtkNew<vtkHyperTreeGridGeometry> geometry;\n geometry->SetInputConnection( fractal->GetOutputPort() );\n vtkNew<vtkPolyDataWriter> writer4;\n writer4->SetFileName( \".\/hyperTreeGridGeometry.vtk\" );\n writer4->SetInputConnection( geometry->GetOutputPort() );\n writer4->Write();\n }\n\n if ( ! skipContour )\n {\n cerr << \"# Contour\" << endl;\n vtkNew<vtkContourFilter> contour;\n contour->SetInputData( htGrid );\n contour->SetNumberOfContours( 2 );\n contour->SetValue( 0, 4. );\n contour->SetValue( 1, 18. );\n contour->SetInputArrayToProcess( 0, 0, 0,\n vtkDataObject::FIELD_ASSOCIATION_POINTS,\n \"Cell Value\" );\n vtkNew<vtkPolyDataWriter> writer0;\n writer0->SetFileName( \".\/hyperTreeGridContour.vtk\" );\n writer0->SetInputConnection( contour->GetOutputPort() );\n writer0->Write();\n }\n\n if ( ! skipShrink )\n {\n cerr << \"# Shrink\" << endl;\n vtkNew<vtkShrinkFilter> shrink;\n shrink->SetInputData( htGrid );\n shrink->SetShrinkFactor( 1. );\n vtkNew<vtkUnstructuredGridWriter> writer1;\n writer1->SetFileName( \".\/hyperTreeGridShrink.vtk\" );\n writer1->SetInputConnection( shrink->GetOutputPort() );\n writer1->Write();\n }\n\n if ( ! skipAxisCut )\n {\n \/\/ Axis-aligned cut works only in 3D for now\n if ( dim == 3 )\n {\n cerr << \"# HyperTreeGridAxisCut\" << endl;\n vtkNew<vtkHyperTreeGridAxisCut> axisCut;\n axisCut->SetInputConnection( fractal->GetOutputPort() );\n axisCut->SetPlaneNormalAxis( 2 );\n axisCut->SetPlanePosition( .1 );\n vtkNew<vtkPolyDataWriter> writer2;\n writer2->SetFileName( \".\/hyperTreeGridAxisCut.vtk\" );\n writer2->SetInputConnection( axisCut->GetOutputPort() );\n writer2->Write();\n }\n }\n\n if ( ! skipCut )\n {\n cerr << \"# Cut\" << endl;\n vtkNew<vtkCutter> cut;\n vtkNew<vtkPlane> plane;\n plane->SetOrigin( .5, .5, .15 );\n plane->SetNormal( 0, 0, 1 );\n cut->SetInputData( htGrid );\n cut->SetCutFunction( plane.GetPointer() );\n vtkNew<vtkPolyDataWriter> writer3;\n writer3->SetFileName( \".\/hyperTreeGridCut.vtk\" );\n writer3->SetInputConnection( cut->GetOutputPort() );\n writer3->Write();\n }\n\n \/\/ Clean up\n fractal->Delete();\n\n return testIntValue;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sceneLayer.h\"\n\nnamespace Tangram {\n\n short SceneLayer::s_layerCount = 0;\n\n SceneLayer::SceneLayer(const std::vector<SceneLayer*>&& _subLayers, const StyleParamMap&& _styleParamMap, const std::string _name, Filter* _filter) :\n m_subLayers(std::move(_subLayers)), m_styleParams(std::move(_styleParamMap)), m_name(_name), m_filter(_filter) {\n\n m_id = 1 << (s_layerCount++);\n\n }\n\n SceneLayer::~SceneLayer() {\n for(auto& subLayer : m_subLayers) {\n delete subLayer;\n }\n m_subLayers.clear();\n delete m_filter;\n }\n}\n\n<commit_msg>Fix SceneLayer ID value<commit_after>#include \"sceneLayer.h\"\n\nnamespace Tangram {\n\n short SceneLayer::s_layerCount = 0;\n\n SceneLayer::SceneLayer(const std::vector<SceneLayer*>&& _subLayers, const StyleParamMap&& _styleParamMap, const std::string _name, Filter* _filter) :\n m_subLayers(std::move(_subLayers)), m_styleParams(std::move(_styleParamMap)), m_name(_name), m_filter(_filter) {\n\n m_id = s_layerCount++;\n\n }\n\n SceneLayer::~SceneLayer() {\n for(auto& subLayer : m_subLayers) {\n delete subLayer;\n }\n m_subLayers.clear();\n delete m_filter;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)\r\n\/\/\r\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\r\n#include \"stdafx.h\"\r\n#include <vector>\r\n#include <boost\/bind.hpp>\r\n#include \"connection.h\"\r\n#include \"http_server\/request_handler.h\"\r\n#include \"plugin\/logger.h\"\r\n\r\n\/\/namespace {\r\n\/\/using namespace AIMPControlPlugin::PluginLogger;\r\n\/\/ModuleLoggerType& logger()\r\n\/\/ { return getLogManager().getModuleLogger<Http::Server>(); }\r\n\/\/}\r\n\r\nnamespace Http {\r\n\r\ntemplate <typename SocketT>\r\nConnection<SocketT>::Connection(boost::asio::io_service& io_service, RequestHandler& handler)\r\n :\r\n strand_(io_service),\r\n socket_(io_service),\r\n request_handler_(handler)\r\n{\r\n try {\r\n BOOST_LOG_SEV(logger(), info) << \"Creating connection to host \" << socket().remote_endpoint();\r\n } catch (boost::system::system_error&) {\r\n BOOST_LOG_SEV(logger(), info) << \"Creating connection.\";\r\n }\r\n}\r\n\r\ntemplate <typename SocketT>\r\nConnection<SocketT>::~Connection()\r\n{\r\n try {\r\n BOOST_LOG_SEV(logger(), info) << \"Destroying connection to host \" << socket().remote_endpoint();\r\n } catch (boost::system::system_error&) {\r\n BOOST_LOG_SEV(logger(), info) << \"Destroying connection.\";\r\n }\r\n}\r\n\r\ntemplate <typename SocketT>\r\nSocketT& Connection<SocketT>::socket()\r\n{\r\n return socket_;\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::start()\r\n{\r\n read_some_to_buffer();\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::read_some_to_buffer()\r\n{\r\n socket_.async_read_some(boost::asio::buffer(buffer_),\r\n strand_.wrap(boost::bind(&Connection<SocketT>::handle_read,\r\n shared_from_this(),\r\n boost::asio::placeholders::error,\r\n boost::asio::placeholders::bytes_transferred\r\n )\r\n )\r\n );\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::write_reply_content()\r\n{\r\n boost::asio::async_write(socket_,\r\n reply_.to_buffers(),\r\n strand_.wrap(boost::bind(&Connection<SocketT>::handle_write,\r\n shared_from_this(),\r\n boost::asio::placeholders::error\r\n )\r\n )\r\n );\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::handle_read(const boost::system::error_code& e,\r\n std::size_t bytes_transferred)\r\n{\r\n if (!e) {\r\n boost::tribool result;\r\n boost::tie(result, boost::tuples::ignore) = request_parser_.parse(request_,\r\n buffer_.data(),\r\n buffer_.data() + bytes_transferred\r\n );\r\n if (result) {\r\n ICometDelayedConnection_ptr comet_connection( new CometDelayedConnection<SocketT>( shared_from_this() ) );\r\n bool reply_immediately = request_handler_.handle_request(request_, reply_, comet_connection);\r\n if (reply_immediately) {\r\n write_reply_content();\r\n }\r\n } else if (!result) {\r\n reply_ = Reply::stock_reply(Reply::bad_request);\r\n write_reply_content();\r\n } else {\r\n read_some_to_buffer();\r\n }\r\n } else {\r\n \/\/ BOOST_LOG_SEV(logger(), debug) << \"Connection<SocketT>::handle_read(): failed to read data. Reason: \" << e.message();\r\n }\r\n\r\n \/\/ If an error occurs then no new asynchronous operations are started. This\r\n \/\/ means that all shared_ptr references to the connection object will\r\n \/\/ disappear and the object will be destroyed automatically after this\r\n \/\/ handler returns. The Connection class's destructor closes the socket.\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::handle_write(const boost::system::error_code& e)\r\n{\r\n if (!e) {\r\n \/\/ Initiate graceful connection closure.\r\n boost::system::error_code ignored_ec;\r\n socket_.shutdown(SocketT::shutdown_both, ignored_ec);\r\n }\r\n\r\n \/\/ No new asynchronous operations are started. This means that all shared_ptr\r\n \/\/ references to the connection object will disappear and the object will be\r\n \/\/ destroyed automatically after this handler returns. The Connection class's\r\n \/\/ destructor closes the socket.\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid CometDelayedConnection<SocketT>::sendResponse(DelayedResponseSender_ptr comet_http_response_sender)\r\n{\r\n BOOST_LOG_SEV(logger(), debug) << \"CometDelayedConnection::sendResponse to \" << connection_->socket().remote_endpoint();\r\n boost::asio::async_write( connection_->socket(),\r\n comet_http_response_sender->get_reply().to_buffers(),\r\n connection_->strand_.wrap(boost::bind(&CometDelayedConnection<SocketT>::handle_write,\r\n shared_from_this(),\r\n comet_http_response_sender,\r\n boost::asio::placeholders::error\r\n )\r\n )\r\n );\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid CometDelayedConnection<SocketT>::handle_write(DelayedResponseSender_ptr comet_http_response_sender, const boost::system::error_code& e)\r\n{\r\n if (!e) {\r\n BOOST_LOG_SEV(logger(), debug) << \"CometDelayedConnection::success sending response to \" << connection_->socket().remote_endpoint();\r\n \/\/ Initiate graceful connection closure.\r\n boost::system::error_code ignored_ec;\r\n connection_->socket().shutdown(SocketT::shutdown_both, ignored_ec);\r\n } else {\r\n BOOST_LOG_SEV(logger(), debug) << \"CometDelayedConnection::fail to send response to \"\r\n << connection_->socket_.remote_endpoint()\r\n << \". Reason: \" << e.message();\r\n }\r\n\r\n \/\/ No new asynchronous operations are started. This means that all shared_ptr\r\n \/\/ references to the CometDelayedConnection object will disappear and the object will be\r\n \/\/ destroyed automatically after this handler returns. The Connection class's\r\n \/\/ destructor closes the socket.\r\n}\r\n\r\n} \/\/ namespace Http\r\n<commit_msg>cosmetic<commit_after>\/\/ Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)\r\n\/\/\r\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\r\n#include \"stdafx.h\"\r\n#include <vector>\r\n#include <boost\/bind.hpp>\r\n#include \"connection.h\"\r\n#include \"http_server\/request_handler.h\"\r\n#include \"plugin\/logger.h\"\r\n\r\n\/\/namespace {\r\n\/\/using namespace AIMPControlPlugin::PluginLogger;\r\n\/\/ModuleLoggerType& logger()\r\n\/\/ { return getLogManager().getModuleLogger<Http::Server>(); }\r\n\/\/}\r\n\r\nnamespace Http {\r\n\r\ntemplate <typename SocketT>\r\nConnection<SocketT>::Connection(boost::asio::io_service& io_service, RequestHandler& handler)\r\n :\r\n strand_(io_service),\r\n socket_(io_service),\r\n request_handler_(handler)\r\n{\r\n try {\r\n BOOST_LOG_SEV(logger(), info) << \"Creating connection to host \" << socket().remote_endpoint();\r\n } catch (boost::system::system_error&) {\r\n BOOST_LOG_SEV(logger(), info) << \"Creating connection.\";\r\n }\r\n}\r\n\r\ntemplate <typename SocketT>\r\nConnection<SocketT>::~Connection()\r\n{\r\n try {\r\n BOOST_LOG_SEV(logger(), info) << \"Destroying connection to host \" << socket().remote_endpoint();\r\n } catch (boost::system::system_error&) {\r\n BOOST_LOG_SEV(logger(), info) << \"Destroying connection.\";\r\n }\r\n}\r\n\r\ntemplate <typename SocketT>\r\nSocketT& Connection<SocketT>::socket()\r\n{\r\n return socket_;\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::start()\r\n{\r\n read_some_to_buffer();\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::read_some_to_buffer()\r\n{\r\n socket_.async_read_some(boost::asio::buffer(buffer_),\r\n strand_.wrap(boost::bind(&Connection<SocketT>::handle_read,\r\n shared_from_this(),\r\n boost::asio::placeholders::error,\r\n boost::asio::placeholders::bytes_transferred\r\n )\r\n )\r\n );\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::write_reply_content()\r\n{\r\n boost::asio::async_write(socket_,\r\n reply_.to_buffers(),\r\n strand_.wrap(boost::bind(&Connection<SocketT>::handle_write,\r\n shared_from_this(),\r\n boost::asio::placeholders::error\r\n )\r\n )\r\n );\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::handle_read(const boost::system::error_code& e,\r\n std::size_t bytes_transferred)\r\n{\r\n if (!e) {\r\n boost::tribool result;\r\n boost::tie(result, boost::tuples::ignore) = request_parser_.parse(request_,\r\n buffer_.data(),\r\n buffer_.data() + bytes_transferred\r\n );\r\n if (result) {\r\n ICometDelayedConnection_ptr comet_connection( new CometDelayedConnection<SocketT>( shared_from_this() ) );\r\n bool reply_immediately = request_handler_.handle_request(request_, reply_, comet_connection);\r\n if (reply_immediately) {\r\n write_reply_content();\r\n }\r\n } else if (!result) {\r\n reply_ = Reply::stock_reply(Reply::bad_request);\r\n write_reply_content();\r\n } else {\r\n read_some_to_buffer();\r\n }\r\n } else {\r\n \/\/ BOOST_LOG_SEV(logger(), debug) << \"Connection<SocketT>::handle_read(): failed to read data. Reason: \" << e.message();\r\n }\r\n\r\n \/\/ If an error occurs then no new asynchronous operations are started. This\r\n \/\/ means that all shared_ptr references to the connection object will\r\n \/\/ disappear and the object will be destroyed automatically after this\r\n \/\/ handler returns. The Connection class's destructor closes the socket.\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid Connection<SocketT>::handle_write(const boost::system::error_code& e)\r\n{\r\n if (!e) {\r\n \/\/ Initiate graceful connection closure.\r\n boost::system::error_code ignored_ec;\r\n socket_.shutdown(SocketT::shutdown_both, ignored_ec);\r\n }\r\n\r\n \/\/ No new asynchronous operations are started. This means that all shared_ptr\r\n \/\/ references to the connection object will disappear and the object will be\r\n \/\/ destroyed automatically after this handler returns. The Connection class's\r\n \/\/ destructor closes the socket.\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid CometDelayedConnection<SocketT>::sendResponse(DelayedResponseSender_ptr comet_http_response_sender)\r\n{\r\n BOOST_LOG_SEV(logger(), debug) << \"CometDelayedConnection::sendResponse to \" << connection_->socket().remote_endpoint();\r\n boost::asio::async_write( connection_->socket(),\r\n comet_http_response_sender->get_reply().to_buffers(),\r\n connection_->strand_.wrap(boost::bind(&CometDelayedConnection<SocketT>::handle_write,\r\n shared_from_this(),\r\n comet_http_response_sender,\r\n boost::asio::placeholders::error\r\n )\r\n )\r\n );\r\n}\r\n\r\ntemplate <typename SocketT>\r\nvoid CometDelayedConnection<SocketT>::handle_write(DelayedResponseSender_ptr comet_http_response_sender, const boost::system::error_code& e)\r\n{\r\n if (!e) {\r\n BOOST_LOG_SEV(logger(), debug) << \"CometDelayedConnection::success sending response to \" << connection_->socket().remote_endpoint();\r\n \/\/ Initiate graceful connection closure.\r\n boost::system::error_code ignored_ec;\r\n connection_->socket().shutdown(SocketT::shutdown_both, ignored_ec);\r\n } else {\r\n BOOST_LOG_SEV(logger(), debug) << \"CometDelayedConnection::fail to send response to \"\r\n << connection_->socket_.remote_endpoint()\r\n << \". Reason: \" << e.message();\r\n }\r\n\r\n \/\/ No new asynchronous operations are started. This means that all shared_ptr\r\n \/\/ references to the CometDelayedConnection object will disappear and the object will be\r\n \/\/ destroyed automatically after this handler returns. The Connection class's\r\n \/\/ destructor closes the socket.\r\n}\r\n\r\n} \/\/ namespace Http\r\n<|endoftext|>"} {"text":"<commit_before>#include <allegro.h>\n#include \"allegro-joystick.h\"\n\nvoid AllegroJoystick::poll(){\n ::poll_joystick();\n}\n\nJoystickInput AllegroJoystick::readAll(){\n JoystickInput input;\n JOYSTICK_INFO * info = &joy[0];\n switch(info->num_buttons > 4 ? 4 : info->num_buttons){\n case 4: input.button4 = info->button[3].b;\n case 3: input.button3 = info->button[2].b;\n case 2: input.button2 = info->button[1].b;\n case 1: input.button1 = info->button[0].b;\n case 0: {\n break;\n }\n }\n\n for (int stick = 0; stick < info->num_sticks; stick++){\n if (info->stick[stick].num_axis > 0){\n int position = info->stick[stick].axis[0].pos;\n if (position < 0){\n input.left = true;\n } else if (position > 0){\n input.right = true;\n }\n }\n if (info->stick[stick].num_axis > 1){\n int position = info->stick[stick].axis[1].pos;\n if (position < 0){\n input.up = true;\n } else if (position > 0){\n input.down = true;\n }\n }\n }\n\n return input;\n}\n\nbool AllegroJoystick::pressed(){\n JoystickInput input = readAll();\n return input.up || input.down || input.left || input.right ||\n input.button1 || input.button2 || input.button3 || input.button4; \n}\n\nAllegroJoystick::~AllegroJoystick(){\n}\n\nAllegroJoystick::AllegroJoystick(){\n}\n<commit_msg>store current joystick in a local variable<commit_after>#include <allegro.h>\n#include \"allegro-joystick.h\"\n\nvoid AllegroJoystick::poll(){\n ::poll_joystick();\n}\n\nJoystickInput AllegroJoystick::readAll(){\n JoystickInput input;\n JOYSTICK_INFO * info = &joy[0];\n switch(info->num_buttons > 4 ? 4 : info->num_buttons){\n case 4: input.button4 = info->button[3].b;\n case 3: input.button3 = info->button[2].b;\n case 2: input.button2 = info->button[1].b;\n case 1: input.button1 = info->button[0].b;\n case 0: {\n break;\n }\n }\n\n for (int stick = 0; stick < info->num_sticks; stick++){\n JOYSTICK_STICK_INFO * this_stick = &info->stick[stick];\n if (this_stick->num_axis > 0){\n int position = this_stick->axis[0].pos;\n if (position < 0){\n input.left = true;\n } else if (position > 0){\n input.right = true;\n }\n }\n if (this_stick->num_axis > 1){\n int position = this_stick->axis[1].pos;\n if (position < 0){\n input.up = true;\n } else if (position > 0){\n input.down = true;\n }\n }\n }\n\n return input;\n}\n\nbool AllegroJoystick::pressed(){\n JoystickInput input = readAll();\n return input.up || input.down || input.left || input.right ||\n input.button1 || input.button2 || input.button3 || input.button4; \n}\n\nAllegroJoystick::~AllegroJoystick(){\n}\n\nAllegroJoystick::AllegroJoystick(){\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Facebook, Inc.\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#include <thrift\/lib\/cpp\/concurrency\/PosixThreadFactory.h>\n#include <thrift\/lib\/cpp\/concurrency\/Exception.h>\n#include <thrift\/lib\/cpp\/concurrency\/Mutex.h>\n#include <thrift\/lib\/cpp\/thrift_config.h>\n\n#if GOOGLE_PERFTOOLS_REGISTER_THREAD\n# include <google\/base\/Profiler.h>\n#endif\n\n#include <assert.h>\n#include <pthread.h>\n#include <sys\/resource.h>\n\n#include <iostream>\n\n#include <glog\/logging.h>\n\nnamespace apache { namespace thrift { namespace concurrency {\n\nusing std::shared_ptr;\nusing std::weak_ptr;\n\nconst PosixThreadFactory::POLICY PosixThreadFactory::kDefaultPolicy;\nconst PosixThreadFactory::PRIORITY PosixThreadFactory::kDefaultPriority;\nconst int PosixThreadFactory::kDefaultStackSizeMB;\n\n\/\/ global set to track the ids of live threads.\nstd::set<pthread_t> liveThreadIds;\nMutex liveThreadIdMutex;\n\nvoid addLiveThreadId(pthread_t tid) {\n Guard g(liveThreadIdMutex);\n liveThreadIds.insert(tid);\n}\n\nvoid removeLiveThreadId(pthread_t tid) {\n Guard g(liveThreadIdMutex);\n liveThreadIds.erase(tid);\n}\n\nvoid getLiveThreadIds(std::set<pthread_t>* tids) {\n Guard g(liveThreadIdMutex);\n for (std::set<pthread_t>::const_iterator it = liveThreadIds.begin();\n it != liveThreadIds.end(); ++it) {\n tids->insert(*it);\n }\n}\n\n\n\/\/ push our given name upstream into pthreads\nbool PthreadThread::updateName() {\n if (!pthread_ || name_.empty()) {\n return false;\n }\n return setPosixThreadName(pthread_, name_);\n}\n\nPthreadThread::PthreadThread(int policy, int priority, int stackSize,\n bool detached,\n shared_ptr<Runnable> runnable) :\n pthread_(pthread_t_init),\n state_(uninitialized),\n policy_(policy),\n priority_(priority),\n stackSize_(stackSize),\n detached_(detached) {\n\n this->Thread::runnable(runnable);\n}\n\nPthreadThread::~PthreadThread() {\n \/* Nothing references this thread, if is is not detached, do a join\n now, otherwise the thread-id and, possibly, other resources will\n be leaked. *\/\n if(!detached_) {\n try {\n join();\n } catch(...) {\n \/\/ We're really hosed.\n }\n }\n removeLiveThreadId(pthread_);\n}\n\nvoid PthreadThread::start() {\n Guard g(stateLock_);\n\n if (state_ != uninitialized) {\n return;\n }\n\n pthread_attr_t thread_attr;\n if (pthread_attr_init(&thread_attr) != 0) {\n throw SystemResourceException(\"pthread_attr_init failed\");\n }\n\n if(pthread_attr_setdetachstate(&thread_attr,\n detached_ ?\n PTHREAD_CREATE_DETACHED :\n PTHREAD_CREATE_JOINABLE) != 0) {\n throw SystemResourceException(\"pthread_attr_setdetachstate failed\");\n }\n\n \/\/ Set thread stack size\n if (pthread_attr_setstacksize(&thread_attr, MB * stackSize_) != 0) {\n throw SystemResourceException(\"pthread_attr_setstacksize failed\");\n }\n\n \/\/ Create reference\n shared_ptr<PthreadThread>* selfRef = new shared_ptr<PthreadThread>();\n *selfRef = self_.lock();\n\n state_ = starting;\n\n if (pthread_create(&pthread_, &thread_attr, threadMain, (void*)selfRef) != 0) {\n throw SystemResourceException(\"pthread_create failed\");\n }\n\n \/\/ Now that we have a thread, we can set the name we've been given, if any.\n updateName();\n addLiveThreadId(pthread_);\n}\n\nvoid PthreadThread::join() {\n Guard g(stateLock_);\n STATE join_state = state_;\n\n\n if (!detached_ && join_state != uninitialized) {\n void* ignore;\n \/* XXX\n If join fails it is most likely due to the fact\n that the last reference was the thread itself and cannot\n join. This results in leaked threads and will eventually\n cause the process to run out of thread resources.\n We're beyond the point of throwing an exception. Not clear how\n best to handle this. *\/\n int res = pthread_join(pthread_, &ignore);\n detached_ = (res == 0);\n if (res != 0) {\n LOG(ERROR) << \"PthreadThread::join(): fail with code \" << res;\n }\n } else {\n LOG(ERROR) << \"PthreadThread::join(): detached thread\";\n }\n}\n\nThread::id_t PthreadThread::getId() {\n#ifdef _MSC_VER\n return (Thread::id_t)pthread_getw32threadid_np(pthread_);\n#else\n return (Thread::id_t)pthread_;\n#endif\n}\n\nshared_ptr<Runnable> PthreadThread::runnable() const {\n return Thread::runnable();\n}\n\nvoid PthreadThread::runnable(shared_ptr<Runnable> value) {\n Thread::runnable(value);\n}\n\nvoid PthreadThread::weakRef(shared_ptr<PthreadThread> self) {\n assert(self.get() == this);\n self_ = weak_ptr<PthreadThread>(self);\n}\n\nbool PthreadThread::setName(const std::string& name) {\n Guard g(stateLock_);\n name_ = name;\n return updateName();\n}\n\nvoid* PthreadThread::threadMain(void* arg) {\n shared_ptr<PthreadThread> thread = *(shared_ptr<PthreadThread>*)arg;\n delete reinterpret_cast<shared_ptr<PthreadThread>*>(arg);\n\n if (thread == nullptr) {\n return (void*)0;\n }\n\n#if GOOGLE_PERFTOOLS_REGISTER_THREAD\n ProfilerRegisterThread();\n#endif\n \/\/ Using pthread_attr_setschedparam() at thread creation doesn't actually\n \/\/ change the new thread's priority for some reason... Other people on the\n \/\/ 'net also complain about it. The solution is to set priority inside the\n \/\/ new thread's threadMain.\n if (thread->policy_ == SCHED_FIFO || thread->policy_ == SCHED_RR) {\n struct sched_param sched_param;\n sched_param.sched_priority = thread->priority_;\n int err =\n pthread_setschedparam(pthread_self(), thread->policy_, &sched_param);\n if (err != 0) {\n VLOG(1) << \"pthread_setschedparam failed (are you root?) with error \" <<\n err, strerror(err);\n }\n } else if (thread->policy_ == SCHED_OTHER) {\n if (setpriority(PRIO_PROCESS, 0, thread->priority_) != 0) {\n VLOG(1) << \"setpriority failed (are you root?) with error \" <<\n errno, strerror(errno);\n }\n }\n\n thread->runnable()->run();\n\n return (void*)0;\n}\n\nint PosixThreadFactory::Impl::toPthreadPolicy(POLICY policy) {\n switch (policy) {\n case OTHER:\n return SCHED_OTHER;\n case FIFO:\n return SCHED_FIFO;\n case ROUND_ROBIN:\n return SCHED_RR;\n }\n return SCHED_OTHER;\n}\n\nint PosixThreadFactory::Impl::toPthreadPriority(\n POLICY policy, PRIORITY priority) {\n int pthread_policy = toPthreadPolicy(policy);\n int min_priority = 0;\n int max_priority = 0;\n if (pthread_policy == SCHED_FIFO || pthread_policy == SCHED_RR) {\n#ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MIN\n min_priority = sched_get_priority_min(pthread_policy);\n#endif\n#ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MAX\n max_priority = sched_get_priority_max(pthread_policy);\n#endif\n } else if (pthread_policy == SCHED_OTHER) {\n min_priority = 19;\n max_priority = -20;\n }\n int quanta = HIGHEST - LOWEST;\n float stepsperquanta = (float)(max_priority - min_priority) \/ quanta;\n\n if (priority <= HIGHEST) {\n return (int)(min_priority + stepsperquanta * priority);\n } else {\n \/\/ should never get here for priority increments.\n assert(false);\n return (int)(min_priority + stepsperquanta * NORMAL);\n }\n}\n\nPosixThreadFactory::Impl::Impl(\n POLICY policy, PRIORITY priority, int stackSize, DetachState detached) :\n policy_(policy),\n priority_(priority),\n stackSize_(stackSize),\n detached_(detached) {}\n\nshared_ptr<Thread> PosixThreadFactory::Impl::newThread(\n const shared_ptr<Runnable>& runnable,\n PosixThreadFactory::DetachState detachState) const {\n shared_ptr<PthreadThread> result = shared_ptr<PthreadThread>(\n new PthreadThread(toPthreadPolicy(policy_),\n toPthreadPriority(policy_, priority_), stackSize_,\n detachState == DETACHED, runnable));\n result->weakRef(result);\n runnable->thread(result);\n return result;\n}\n\nint PosixThreadFactory::Impl::getStackSize() const {\n return stackSize_;\n}\n\nvoid PosixThreadFactory::Impl::setStackSize(int value) {\n stackSize_ = value;\n}\n\nPosixThreadFactory::PRIORITY PosixThreadFactory::Impl::getPriority()\n const {\n return priority_;\n}\n\n\/**\n * Sets priority.\n *\n * XXX\n * Need to handle incremental priorities properly.\n *\/\nvoid PosixThreadFactory::Impl::setPriority(PRIORITY value) {\n priority_ = value;\n}\n\nPosixThreadFactory::DetachState PosixThreadFactory::Impl::getDetachState()\n const {\n return detached_;\n}\n\nvoid PosixThreadFactory::Impl::setDetachState(DetachState value) {\n detached_ = value;\n}\n\nThread::id_t PosixThreadFactory::Impl::getCurrentThreadId() const {\n#ifdef _MSC_VER\n return (Thread::id_t)pthread_getw32threadid_np(pthread_self());\n#else\n return (Thread::id_t)pthread_self();\n#endif\n}\n\n\nPosixThreadFactory::PosixThreadFactory(POLICY policy, PRIORITY priority,\n int stackSize, bool detached)\n : impl_(new PosixThreadFactory::Impl(policy, priority, stackSize,\n detached ? DETACHED : ATTACHED)) {\n}\n\nPosixThreadFactory::PosixThreadFactory(DetachState detached)\n : impl_(new PosixThreadFactory::Impl(kDefaultPolicy, kDefaultPriority,\n kDefaultStackSizeMB, detached)) {\n}\n\nshared_ptr<Thread> PosixThreadFactory::newThread(\n const shared_ptr<Runnable>& runnable) const {\n return impl_->newThread(runnable, impl_->getDetachState());\n}\n\nshared_ptr<Thread> PosixThreadFactory::newThread(\n const shared_ptr<Runnable>& runnable,\n DetachState detachState) const {\n return impl_->newThread(runnable, detachState);\n}\n\nint PosixThreadFactory::getStackSize() const { return impl_->getStackSize(); }\n\nvoid PosixThreadFactory::setStackSize(int value) { impl_->setStackSize(value); }\n\nPosixThreadFactory::PRIORITY PosixThreadFactory::getPriority() const { return impl_->getPriority(); }\n\nvoid PosixThreadFactory::setPriority(PosixThreadFactory::PRIORITY value) { impl_->setPriority(value); }\n\nbool PosixThreadFactory::isDetached() const {\n return impl_->getDetachState() == DETACHED;\n}\n\nvoid PosixThreadFactory::setDetached(bool value) {\n impl_->setDetachState(value ? DETACHED : ATTACHED);\n}\n\nvoid PosixThreadFactory::setDetached(DetachState value) {\n impl_->setDetachState(value);\n}\n\nThread::id_t PosixThreadFactory::getCurrentThreadId() const { return impl_->getCurrentThreadId(); }\n\n}}} \/\/ apache::thrift::concurrency\n<commit_msg>Don't you just love it when you forget to add a file to the diff?<commit_after>\/*\n * Copyright 2014 Facebook, Inc.\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#include <thrift\/lib\/cpp\/concurrency\/PosixThreadFactory.h>\n#include <thrift\/lib\/cpp\/concurrency\/Exception.h>\n#include <thrift\/lib\/cpp\/concurrency\/Mutex.h>\n#include <thrift\/lib\/cpp\/thrift_config.h>\n\n#if GOOGLE_PERFTOOLS_REGISTER_THREAD\n# include <google\/base\/Profiler.h>\n#endif\n\n#include <assert.h>\n#include <pthread.h>\n#include <sys\/resource.h>\n\n#include <iostream>\n\n#include <glog\/logging.h>\n\nnamespace apache { namespace thrift { namespace concurrency {\n\nusing std::shared_ptr;\nusing std::weak_ptr;\n\nconst PosixThreadFactory::POLICY PosixThreadFactory::kDefaultPolicy;\nconst PosixThreadFactory::PRIORITY PosixThreadFactory::kDefaultPriority;\nconst int PosixThreadFactory::kDefaultStackSizeMB;\n\n\/\/ global set to track the ids of live threads.\nstd::set<pthread_t> liveThreadIds;\nMutex liveThreadIdMutex;\n\nvoid addLiveThreadId(pthread_t tid) {\n Guard g(liveThreadIdMutex);\n liveThreadIds.insert(tid);\n}\n\nvoid removeLiveThreadId(pthread_t tid) {\n Guard g(liveThreadIdMutex);\n liveThreadIds.erase(tid);\n}\n\nvoid getLiveThreadIds(std::set<pthread_t>* tids) {\n Guard g(liveThreadIdMutex);\n for (std::set<pthread_t>::const_iterator it = liveThreadIds.begin();\n it != liveThreadIds.end(); ++it) {\n tids->insert(*it);\n }\n}\n\n\n\/\/ push our given name upstream into pthreads\nbool PthreadThread::updateName() {\n if (!pthread_ || name_.empty()) {\n return false;\n }\n return setPosixThreadName(pthread_, name_);\n}\n\nPthreadThread::PthreadThread(int policy, int priority, int stackSize,\n bool detached,\n shared_ptr<Runnable> runnable) :\n pthread_(pthread_zero),\n state_(uninitialized),\n policy_(policy),\n priority_(priority),\n stackSize_(stackSize),\n detached_(detached) {\n\n this->Thread::runnable(runnable);\n}\n\nPthreadThread::~PthreadThread() {\n \/* Nothing references this thread, if is is not detached, do a join\n now, otherwise the thread-id and, possibly, other resources will\n be leaked. *\/\n if(!detached_) {\n try {\n join();\n } catch(...) {\n \/\/ We're really hosed.\n }\n }\n removeLiveThreadId(pthread_);\n}\n\nvoid PthreadThread::start() {\n Guard g(stateLock_);\n\n if (state_ != uninitialized) {\n return;\n }\n\n pthread_attr_t thread_attr;\n if (pthread_attr_init(&thread_attr) != 0) {\n throw SystemResourceException(\"pthread_attr_init failed\");\n }\n\n if(pthread_attr_setdetachstate(&thread_attr,\n detached_ ?\n PTHREAD_CREATE_DETACHED :\n PTHREAD_CREATE_JOINABLE) != 0) {\n throw SystemResourceException(\"pthread_attr_setdetachstate failed\");\n }\n\n \/\/ Set thread stack size\n if (pthread_attr_setstacksize(&thread_attr, MB * stackSize_) != 0) {\n throw SystemResourceException(\"pthread_attr_setstacksize failed\");\n }\n\n \/\/ Create reference\n shared_ptr<PthreadThread>* selfRef = new shared_ptr<PthreadThread>();\n *selfRef = self_.lock();\n\n state_ = starting;\n\n if (pthread_create(&pthread_, &thread_attr, threadMain, (void*)selfRef) != 0) {\n throw SystemResourceException(\"pthread_create failed\");\n }\n\n \/\/ Now that we have a thread, we can set the name we've been given, if any.\n updateName();\n addLiveThreadId(pthread_);\n}\n\nvoid PthreadThread::join() {\n Guard g(stateLock_);\n STATE join_state = state_;\n\n\n if (!detached_ && join_state != uninitialized) {\n void* ignore;\n \/* XXX\n If join fails it is most likely due to the fact\n that the last reference was the thread itself and cannot\n join. This results in leaked threads and will eventually\n cause the process to run out of thread resources.\n We're beyond the point of throwing an exception. Not clear how\n best to handle this. *\/\n int res = pthread_join(pthread_, &ignore);\n detached_ = (res == 0);\n if (res != 0) {\n LOG(ERROR) << \"PthreadThread::join(): fail with code \" << res;\n }\n } else {\n LOG(ERROR) << \"PthreadThread::join(): detached thread\";\n }\n}\n\nThread::id_t PthreadThread::getId() {\n#ifdef _MSC_VER\n return (Thread::id_t)pthread_getw32threadid_np(pthread_);\n#else\n return (Thread::id_t)pthread_;\n#endif\n}\n\nshared_ptr<Runnable> PthreadThread::runnable() const {\n return Thread::runnable();\n}\n\nvoid PthreadThread::runnable(shared_ptr<Runnable> value) {\n Thread::runnable(value);\n}\n\nvoid PthreadThread::weakRef(shared_ptr<PthreadThread> self) {\n assert(self.get() == this);\n self_ = weak_ptr<PthreadThread>(self);\n}\n\nbool PthreadThread::setName(const std::string& name) {\n Guard g(stateLock_);\n name_ = name;\n return updateName();\n}\n\nvoid* PthreadThread::threadMain(void* arg) {\n shared_ptr<PthreadThread> thread = *(shared_ptr<PthreadThread>*)arg;\n delete reinterpret_cast<shared_ptr<PthreadThread>*>(arg);\n\n if (thread == nullptr) {\n return (void*)0;\n }\n\n#if GOOGLE_PERFTOOLS_REGISTER_THREAD\n ProfilerRegisterThread();\n#endif\n \/\/ Using pthread_attr_setschedparam() at thread creation doesn't actually\n \/\/ change the new thread's priority for some reason... Other people on the\n \/\/ 'net also complain about it. The solution is to set priority inside the\n \/\/ new thread's threadMain.\n if (thread->policy_ == SCHED_FIFO || thread->policy_ == SCHED_RR) {\n struct sched_param sched_param;\n sched_param.sched_priority = thread->priority_;\n int err =\n pthread_setschedparam(pthread_self(), thread->policy_, &sched_param);\n if (err != 0) {\n VLOG(1) << \"pthread_setschedparam failed (are you root?) with error \" <<\n err, strerror(err);\n }\n } else if (thread->policy_ == SCHED_OTHER) {\n if (setpriority(PRIO_PROCESS, 0, thread->priority_) != 0) {\n VLOG(1) << \"setpriority failed (are you root?) with error \" <<\n errno, strerror(errno);\n }\n }\n\n thread->runnable()->run();\n\n return (void*)0;\n}\n\nint PosixThreadFactory::Impl::toPthreadPolicy(POLICY policy) {\n switch (policy) {\n case OTHER:\n return SCHED_OTHER;\n case FIFO:\n return SCHED_FIFO;\n case ROUND_ROBIN:\n return SCHED_RR;\n }\n return SCHED_OTHER;\n}\n\nint PosixThreadFactory::Impl::toPthreadPriority(\n POLICY policy, PRIORITY priority) {\n int pthread_policy = toPthreadPolicy(policy);\n int min_priority = 0;\n int max_priority = 0;\n if (pthread_policy == SCHED_FIFO || pthread_policy == SCHED_RR) {\n#ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MIN\n min_priority = sched_get_priority_min(pthread_policy);\n#endif\n#ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MAX\n max_priority = sched_get_priority_max(pthread_policy);\n#endif\n } else if (pthread_policy == SCHED_OTHER) {\n min_priority = 19;\n max_priority = -20;\n }\n int quanta = HIGHEST - LOWEST;\n float stepsperquanta = (float)(max_priority - min_priority) \/ quanta;\n\n if (priority <= HIGHEST) {\n return (int)(min_priority + stepsperquanta * priority);\n } else {\n \/\/ should never get here for priority increments.\n assert(false);\n return (int)(min_priority + stepsperquanta * NORMAL);\n }\n}\n\nPosixThreadFactory::Impl::Impl(\n POLICY policy, PRIORITY priority, int stackSize, DetachState detached) :\n policy_(policy),\n priority_(priority),\n stackSize_(stackSize),\n detached_(detached) {}\n\nshared_ptr<Thread> PosixThreadFactory::Impl::newThread(\n const shared_ptr<Runnable>& runnable,\n PosixThreadFactory::DetachState detachState) const {\n shared_ptr<PthreadThread> result = shared_ptr<PthreadThread>(\n new PthreadThread(toPthreadPolicy(policy_),\n toPthreadPriority(policy_, priority_), stackSize_,\n detachState == DETACHED, runnable));\n result->weakRef(result);\n runnable->thread(result);\n return result;\n}\n\nint PosixThreadFactory::Impl::getStackSize() const {\n return stackSize_;\n}\n\nvoid PosixThreadFactory::Impl::setStackSize(int value) {\n stackSize_ = value;\n}\n\nPosixThreadFactory::PRIORITY PosixThreadFactory::Impl::getPriority()\n const {\n return priority_;\n}\n\n\/**\n * Sets priority.\n *\n * XXX\n * Need to handle incremental priorities properly.\n *\/\nvoid PosixThreadFactory::Impl::setPriority(PRIORITY value) {\n priority_ = value;\n}\n\nPosixThreadFactory::DetachState PosixThreadFactory::Impl::getDetachState()\n const {\n return detached_;\n}\n\nvoid PosixThreadFactory::Impl::setDetachState(DetachState value) {\n detached_ = value;\n}\n\nThread::id_t PosixThreadFactory::Impl::getCurrentThreadId() const {\n#ifdef _MSC_VER\n return (Thread::id_t)pthread_getw32threadid_np(pthread_self());\n#else\n return (Thread::id_t)pthread_self();\n#endif\n}\n\n\nPosixThreadFactory::PosixThreadFactory(POLICY policy, PRIORITY priority,\n int stackSize, bool detached)\n : impl_(new PosixThreadFactory::Impl(policy, priority, stackSize,\n detached ? DETACHED : ATTACHED)) {\n}\n\nPosixThreadFactory::PosixThreadFactory(DetachState detached)\n : impl_(new PosixThreadFactory::Impl(kDefaultPolicy, kDefaultPriority,\n kDefaultStackSizeMB, detached)) {\n}\n\nshared_ptr<Thread> PosixThreadFactory::newThread(\n const shared_ptr<Runnable>& runnable) const {\n return impl_->newThread(runnable, impl_->getDetachState());\n}\n\nshared_ptr<Thread> PosixThreadFactory::newThread(\n const shared_ptr<Runnable>& runnable,\n DetachState detachState) const {\n return impl_->newThread(runnable, detachState);\n}\n\nint PosixThreadFactory::getStackSize() const { return impl_->getStackSize(); }\n\nvoid PosixThreadFactory::setStackSize(int value) { impl_->setStackSize(value); }\n\nPosixThreadFactory::PRIORITY PosixThreadFactory::getPriority() const { return impl_->getPriority(); }\n\nvoid PosixThreadFactory::setPriority(PosixThreadFactory::PRIORITY value) { impl_->setPriority(value); }\n\nbool PosixThreadFactory::isDetached() const {\n return impl_->getDetachState() == DETACHED;\n}\n\nvoid PosixThreadFactory::setDetached(bool value) {\n impl_->setDetachState(value ? DETACHED : ATTACHED);\n}\n\nvoid PosixThreadFactory::setDetached(DetachState value) {\n impl_->setDetachState(value);\n}\n\nThread::id_t PosixThreadFactory::getCurrentThreadId() const { return impl_->getCurrentThreadId(); }\n\n}}} \/\/ apache::thrift::concurrency\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_READ_LOCAL_INTERACTION_HPP\n#define MJOLNIR_READ_LOCAL_INTERACTION_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/interaction\/BondLengthInteraction.hpp>\n#include <mjolnir\/interaction\/BondAngleInteraction.hpp>\n#include <mjolnir\/interaction\/DihedralAngleInteraction.hpp>\n#include <mjolnir\/util\/make_unique.hpp>\n#include <mjolnir\/util\/throw_exception.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/input\/read_local_potential.hpp>\n#include <memory>\n\nnamespace mjolnir\n{\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ individual local interaction. would be called from read_local_interaction\n\/\/ defined at the bottom of this file.\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_bond_length_interaction(const std::string& kind, const toml::value& local)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_bond_length_interaction(), 0);\n using real_type = typename traitsT::real_type;\n\n const auto potential = toml::find<std::string>(local, \"potential\");\n if(potential == \"Harmonic\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Harmonic.\");\n using potentialT = HarmonicPotential<real_type>;\n\n return make_unique<BondLengthInteraction<traitsT, potentialT>>(\n kind, read_local_potential<2, potentialT>(local));\n }\n else if(potential == \"Go1012Contact\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is 10-12 Go contact.\");\n using potentialT = Go1012ContactPotential<real_type>;\n\n return make_unique<BondLengthInteraction<traitsT, potentialT>>(\n kind, read_local_potential<2, potentialT>(local));\n }\n else if(potential == \"Gaussian\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Gaussian.\");\n using potentialT = GaussianPotential<real_type>;\n\n return make_unique<BondLengthInteraction<traitsT, potentialT>>(\n kind, read_local_potential<2, potentialT>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_bond_length_interaction: invalid potential\",\n toml::find<toml::value>(local, \"potential\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"Harmonic\\\" : well-known harmonic potential\",\n \"- \\\"Go1012Contact\\\": r^12 - r^10 type native contact potential\",\n \"- \\\"Gaussian\\\" : well-known gaussian potential\"\n }));\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_bond_angle_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::value& local)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_bond_angle_interaction(), 0);\n using real_type = typename traitsT::real_type;\n\n const auto potential = toml::find<std::string>(local, \"potential\");\n\n if(potential == \"Harmonic\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Harmonic.\");\n using potentialT = HarmonicPotential<real_type>;\n\n return make_unique<BondAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<3, potentialT>(local));\n }\n else if(potential == \"FlexibleLocalAngle\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Flexible Local Angle.\");\n using potentialT = FlexibleLocalAnglePotential<real_type>;\n\n return make_unique<BondAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<3, potentialT>(local));\n }\n else if(potential == \"Gaussian\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Gaussian.\");\n using potentialT = GaussianPotential<real_type>;\n\n return make_unique<BondAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<3, potentialT>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_bond_angle_interaction: invalid potential\",\n toml::find<toml::value>(local, \"potential\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"Harmonic\\\" : well-known harmonic potential\",\n \"- \\\"Gaussian\\\" : well-known gaussian potential\"\n \"- \\\"FlexibleLocalAngle\\\": table-based potential for C-alpha protein model\",\n }));\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_dihedral_angle_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::value& local)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_dihedral_angle_interaction(), 0);\n using real_type = typename traitsT::real_type;\n\n const auto potential = toml::find<std::string>(local, \"potential\");\n\n if(potential == \"Harmonic\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Harmonic.\");\n using potentialT = HarmonicPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n else if(potential == \"ClementiDihedral\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Clementi-Go's dihedral.\");\n using potentialT = ClementiDihedralPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n else if(potential == \"Gaussian\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Gaussian.\");\n using potentialT = GaussianPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n else if(potential == \"PeriodicGaussian\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is PeriodicGaussian.\");\n using potentialT = PeriodicGaussianPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n else if(potential == \"FlexibleLocalDihedral\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Flexible Local Dihedral.\");\n using potentialT = FlexibleLocalDihedralPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n \/\/ XXX generalization of this feature is too difficult (technically it's\n \/\/ not so difficult, but practically, it makes the code messy...).\n else if(potential == \"Gaussian+FlexibleLocalDihedral\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Gaussian + FlexibleLocalDihedral.\");\n using potential_1_T = GaussianPotential<real_type>;\n using potential_2_T = FlexibleLocalDihedralPotential<real_type>;\n using potentialT =\n SumLocalPotential<real_type, potential_1_T, potential_2_T>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(kind,\n read_local_potentials<4, real_type, potential_1_T, potential_2_T>(\n local, \"Gaussian\", \"FlexibleLocalDihedral\"));\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_dihedral_angle_interaction: invalid potential\",\n toml::find<toml::value>(local, \"potential\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"Harmonic\\\" : well-known harmonic potential\",\n \"- \\\"Gaussian\\\" : well-known gaussian potential\"\n \"- \\\"ClementiDihedral\\\" : potential used in the off-lattice Go protein model\"\n \"- \\\"FlexibleLocalDihedral\\\": table-based potential for C-alpha protein model\",\n }));\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ general read_local_interaction function\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_local_interaction(const toml::value& local)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_local_interaction(), 0);\n\n const auto interaction = toml::find<std::string>(local, \"interaction\");\n const auto kind = toml::find<std::string>(local, \"topology\");\n MJOLNIR_LOG_INFO(\"connection kind = \", kind);\n\n if(interaction == \"BondLength\")\n {\n MJOLNIR_LOG_NOTICE(\"Bond Length interaction found.\");\n return read_bond_length_interaction<traitsT>(kind, local);\n }\n else if(interaction == \"BondAngle\")\n {\n MJOLNIR_LOG_NOTICE(\"Bond Angle interaction found.\");\n return read_bond_angle_interaction<traitsT>(kind, local);\n }\n else if(interaction == \"DihedralAngle\")\n {\n MJOLNIR_LOG_NOTICE(\"Dihedral Angle interaction found.\");\n return read_dihedral_angle_interaction<traitsT>(kind, local);\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_local_interaction: invalid interaction\",\n toml::find<toml::value>(local, \"interaction\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"BondLength\\\" : 2-body well-known chemical bond interaction\",\n \"- \\\"BondAngle\\\" : 3-body well-known bond angle interaction\",\n \"- \\\"DihedralAngle\\\" : 4-body well-known dihedral angle interaction\",\n }));\n }\n}\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_LOCAL_INTERACTION\n<commit_msg>fix reading SumLocalPotential<commit_after>#ifndef MJOLNIR_READ_LOCAL_INTERACTION_HPP\n#define MJOLNIR_READ_LOCAL_INTERACTION_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/interaction\/BondLengthInteraction.hpp>\n#include <mjolnir\/interaction\/BondAngleInteraction.hpp>\n#include <mjolnir\/interaction\/DihedralAngleInteraction.hpp>\n#include <mjolnir\/util\/make_unique.hpp>\n#include <mjolnir\/util\/throw_exception.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/input\/read_local_potential.hpp>\n#include <memory>\n\nnamespace mjolnir\n{\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ individual local interaction. would be called from read_local_interaction\n\/\/ defined at the bottom of this file.\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_bond_length_interaction(const std::string& kind, const toml::value& local)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_bond_length_interaction(), 0);\n using real_type = typename traitsT::real_type;\n\n const auto potential = toml::find<std::string>(local, \"potential\");\n if(potential == \"Harmonic\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Harmonic.\");\n using potentialT = HarmonicPotential<real_type>;\n\n return make_unique<BondLengthInteraction<traitsT, potentialT>>(\n kind, read_local_potential<2, potentialT>(local));\n }\n else if(potential == \"Go1012Contact\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is 10-12 Go contact.\");\n using potentialT = Go1012ContactPotential<real_type>;\n\n return make_unique<BondLengthInteraction<traitsT, potentialT>>(\n kind, read_local_potential<2, potentialT>(local));\n }\n else if(potential == \"Gaussian\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Gaussian.\");\n using potentialT = GaussianPotential<real_type>;\n\n return make_unique<BondLengthInteraction<traitsT, potentialT>>(\n kind, read_local_potential<2, potentialT>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_bond_length_interaction: invalid potential\",\n toml::find<toml::value>(local, \"potential\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"Harmonic\\\" : well-known harmonic potential\",\n \"- \\\"Go1012Contact\\\": r^12 - r^10 type native contact potential\",\n \"- \\\"Gaussian\\\" : well-known gaussian potential\"\n }));\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_bond_angle_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::value& local)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_bond_angle_interaction(), 0);\n using real_type = typename traitsT::real_type;\n\n const auto potential = toml::find<std::string>(local, \"potential\");\n\n if(potential == \"Harmonic\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Harmonic.\");\n using potentialT = HarmonicPotential<real_type>;\n\n return make_unique<BondAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<3, potentialT>(local));\n }\n else if(potential == \"FlexibleLocalAngle\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Flexible Local Angle.\");\n using potentialT = FlexibleLocalAnglePotential<real_type>;\n\n return make_unique<BondAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<3, potentialT>(local));\n }\n else if(potential == \"Gaussian\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Gaussian.\");\n using potentialT = GaussianPotential<real_type>;\n\n return make_unique<BondAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<3, potentialT>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_bond_angle_interaction: invalid potential\",\n toml::find<toml::value>(local, \"potential\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"Harmonic\\\" : well-known harmonic potential\",\n \"- \\\"Gaussian\\\" : well-known gaussian potential\"\n \"- \\\"FlexibleLocalAngle\\\": table-based potential for C-alpha protein model\",\n }));\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_dihedral_angle_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::value& local)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_dihedral_angle_interaction(), 0);\n using real_type = typename traitsT::real_type;\n\n const auto potential = toml::find<std::string>(local, \"potential\");\n\n if(potential == \"Harmonic\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Harmonic.\");\n using potentialT = HarmonicPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n else if(potential == \"ClementiDihedral\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Clementi-Go's dihedral.\");\n using potentialT = ClementiDihedralPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n else if(potential == \"Gaussian\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Gaussian.\");\n using potentialT = GaussianPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n else if(potential == \"PeriodicGaussian\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is PeriodicGaussian.\");\n using potentialT = PeriodicGaussianPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n else if(potential == \"FlexibleLocalDihedral\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is Flexible Local Dihedral.\");\n using potentialT = FlexibleLocalDihedralPotential<real_type>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(\n kind, read_local_potential<4, potentialT>(local));\n }\n \/\/ XXX generalization of this feature is too difficult (technically it's\n \/\/ not so difficult, but practically, it makes the code messy...).\n else if(potential == \"PeriodicGaussian+FlexibleLocalDihedral\")\n {\n MJOLNIR_LOG_NOTICE(\"-- potential function is \"\n \"PeriodicGaussian + FlexibleLocalDihedral.\");\n using potential_1_T = PeriodicGaussianPotential<real_type>;\n using potential_2_T = FlexibleLocalDihedralPotential<real_type>;\n using potentialT =\n SumLocalPotential<real_type, potential_1_T, potential_2_T>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(kind,\n read_local_potentials<4, real_type, potential_1_T, potential_2_T>(\n local, \"PeriodicGaussian\", \"FlexibleLocalDihedral\"));\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_dihedral_angle_interaction: invalid potential\",\n toml::find<toml::value>(local, \"potential\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"Harmonic\\\" : well-known harmonic potential\",\n \"- \\\"Gaussian\\\" : well-known gaussian potential\"\n \"- \\\"ClementiDihedral\\\" : potential used in the off-lattice Go protein model\"\n \"- \\\"FlexibleLocalDihedral\\\": table-based potential for C-alpha protein model\",\n }));\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ general read_local_interaction function\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_local_interaction(const toml::value& local)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_SCOPE(read_local_interaction(), 0);\n\n const auto interaction = toml::find<std::string>(local, \"interaction\");\n const auto kind = toml::find<std::string>(local, \"topology\");\n MJOLNIR_LOG_INFO(\"connection kind = \", kind);\n\n if(interaction == \"BondLength\")\n {\n MJOLNIR_LOG_NOTICE(\"Bond Length interaction found.\");\n return read_bond_length_interaction<traitsT>(kind, local);\n }\n else if(interaction == \"BondAngle\")\n {\n MJOLNIR_LOG_NOTICE(\"Bond Angle interaction found.\");\n return read_bond_angle_interaction<traitsT>(kind, local);\n }\n else if(interaction == \"DihedralAngle\")\n {\n MJOLNIR_LOG_NOTICE(\"Dihedral Angle interaction found.\");\n return read_dihedral_angle_interaction<traitsT>(kind, local);\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_local_interaction: invalid interaction\",\n toml::find<toml::value>(local, \"interaction\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"BondLength\\\" : 2-body well-known chemical bond interaction\",\n \"- \\\"BondAngle\\\" : 3-body well-known bond angle interaction\",\n \"- \\\"DihedralAngle\\\" : 4-body well-known dihedral angle interaction\",\n }));\n }\n}\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_LOCAL_INTERACTION\n<|endoftext|>"} {"text":"<commit_before>#include <sirius.h>\n\nusing namespace sirius;\n\nvoid test_xc()\n{\n XC_functional Ex(\"XC_LDA_X\", 2);\n XC_functional Ec(\"XC_LDA_C_VWN\", 2);\n\n int npt = 5;\n double rho_up[] = {0, 0.1, 0.2, 0.5, 2.234};\n double rho_dn[] = {0, 0.0, 0.1, 1.5, 2.234};\n\n std::vector<double> vx_up(npt);\n std::vector<double> vx_dn(npt);\n std::vector<double> vc_up(npt);\n std::vector<double> vc_dn(npt);\n std::vector<double> ex(npt);\n std::vector<double> ec(npt);\n\n \/* compute XC potential and energy *\/\n Ex.get_lda(npt, rho_up, rho_dn, &vx_up[0], &vx_dn[0], &ex[0]);\n Ec.get_lda(npt, rho_up, rho_dn, &vc_up[0], &vc_dn[0], &ec[0]);\n for (int i = 0; i < npt; i++)\n {\n printf(\"%12.6f %12.6f %12.6f %12.6f %12.6f\\n\", rho_up[i], rho_dn[i], vx_up[i] + vc_up[i], vx_dn[i] + vc_dn[i], ex[i] + ec[i]);\n\n }\n}\n\nint main(int argn, char** argv)\n{\n sirius::initialize(1);\n test_xc();\n sirius::finalize();\n}\n<commit_msg>update xc test<commit_after>#include <sirius.h>\n\nusing namespace sirius;\n\nvoid test_xc()\n{\n XC_functional Ex(\"XC_LDA_X\", 2);\n XC_functional Ec(\"XC_LDA_C_VWN\", 2);\n\n int npt = 5;\n double rho_up[] = {0, 0.1, 0.2, 0.5, 2.234};\n double rho_dn[] = {0, 0.0, 0.1, 1.5, 2.234};\n\n std::vector<double> vx_up(npt);\n std::vector<double> vx_dn(npt);\n std::vector<double> vc_up(npt);\n std::vector<double> vc_dn(npt);\n std::vector<double> ex(npt);\n std::vector<double> ec(npt);\n\n \/* compute XC potential and energy *\/\n Ex.get_lda(npt, rho_up, rho_dn, &vx_up[0], &vx_dn[0], &ex[0]);\n Ec.get_lda(npt, rho_up, rho_dn, &vc_up[0], &vc_dn[0], &ec[0]);\n for (int i = 0; i < npt; i++)\n {\n printf(\"%12.6f %12.6f %12.6f %12.6f %12.6f\\n\", rho_up[i], rho_dn[i], vx_up[i] + vc_up[i], vx_dn[i] + vc_dn[i], ex[i] + ec[i]);\n\n }\n}\n\nvoid test_xc2()\n{\n \/\/XC_functional Ex(\"XC_GGA_X_PBE\", 1);\n \/\/XC_functional Ec(\"XC_GGA_C_PBE\", 1);\n \/\/XC_functional Ex(\"XC_LDA_X\", 1);\n \/\/XC_functional Ec(\"XC_LDA_C_PZ\", 1);\n XC_functional Ex(\"XC_GGA_X_PW91\", 1);\n XC_functional Ec(\"XC_GGA_C_PW91\", 1);\n \n std::vector<double> sigma(101);\n std::vector<double> vrho(101);\n std::vector<double> vsigma(101);\n std::vector<double> e(101);\n\n auto fout = fopen(\"xc_libxc.dat\", \"w+\");\n for (int i = 0; i <= 50; i++) {\n std::vector<double> rho(101, i * 0.2);\n for (int j = 0; j <= 100; j++) {\n sigma[j] = j * 0.1;\n }\n std::vector<double> result(101, 0);\n Ex.get_gga(101, rho.data(), sigma.data(), vrho.data(), vsigma.data(), e.data());\n \/\/Ex.get_lda(101, rho.data(), vrho.data(), e.data());\n for (int i = 0; i <= 100; i++) {\n result[i] += e[i];\n }\n Ec.get_gga(101, rho.data(), sigma.data(), vrho.data(), vsigma.data(), e.data());\n \/\/Ec.get_lda(101, rho.data(), vrho.data(), e.data());\n for (int i = 0; i <= 100; i++) {\n result[i] += e[i];\n }\n for (int i = 0; i <= 100; i++) {\n fprintf(fout, \"%18.10f\", result[i]);\n }\n fprintf(fout, \"\\n\");\n }\n fclose(fout);\n}\n\nint main(int argn, char** argv)\n{\n sirius::initialize(1);\n test_xc();\n test_xc2();\n sirius::finalize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*#include <catch.hpp>\n\n#include <pddlparse\/AST.h>\n#include <pddlparse\/Parse.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTEST_CASE(\"[parser] The Blocksworld domain is parsed correctly\", \"[parser]\")\n{\n\tconst pddl::Context::WarningCallback ignoreWarnings = [](const auto &, const auto &){};\n\n\tpddl::Tokenizer tokenizer;\n\ttokenizer.read(\"data\/blocksworld-domain.pddl\");\n\tpddl::Context context(std::move(tokenizer), ignoreWarnings);\n\n\tconst auto description = pddl::parseDescription(context);\n\n\tREQUIRE_NOTHROW(description.domain());\n\n\tconst auto &domain = description.domain();\n\n\t\/\/ Name\n\tCHECK(domain.name() == \"blocks\");\n\n\t\/\/ Requirements\n\tREQUIRE(domain.requirements().size() == 2u);\n\tCHECK(domain.requirements()[0].type() == Requirement::Type::STRIPS);\n\tCHECK(domain.requirements()[1].type() == Requirement::Type::Typing);\n\n\t\/\/ Types\n\tREQUIRE(domain.types().size() == 1u);\n\n\tconst auto &block = *domain.types()[0];\n\n\tCHECK(block.name() == \"block\");\n\tREQUIRE(block.parentTypes().size() == 0u);\n\n\t\/\/ Predicates\n\tREQUIRE(domain.predicates().size() == 5u);\n\n\tconst auto &on = *domain.predicates()[0];\n\n\tCHECK(on.name() == \"on\");\n\tREQUIRE(on.parameters().size() == 2u);\n\tCHECK(on.parameters()[0]->name() == \"x\");\n\tconst auto &onArgument0Type = on.parameters()[0]->type()->as<expressions::PrimitiveType>();\n\tCHECK(&onArgument0Type == &block);\n\tCHECK(on.parameters()[1]->name() == \"y\");\n\tconst auto &onArgument1Type = on.parameters()[1]->type()->as<expressions::PrimitiveType>();\n\tCHECK(&onArgument1Type == &block);\n\n\tconst auto &handempty = *domain.predicates()[3];\n\n\tCHECK(handempty.name() == \"handempty\");\n\tCHECK(handempty.parameters().empty());\n\n\t\/\/ Actions\n\tREQUIRE(domain.actions().size() == 4u);\n\n\tconst auto &pickUp = *domain.actions()[0];\n\n\tCHECK(pickUp.name() == \"pick-up\");\n\tREQUIRE(pickUp.parameters().size() == 1u);\n\tCHECK(pickUp.parameters()[0]->name() == \"x\");\n\tCHECK(pickUp.parameters()[0]->type() == &block);\n\n\tconst auto &pickUpPre = pickUp.precondition()->as<expressions::And>();\n\tREQUIRE(pickUpPre.arguments().size() == 3u);\n\tconst auto &pickUpPre0 = pickUpPre.arguments()[0]->as<expressions::Predicate>();\n\tCHECK(pickUpPre0.name() == \"clear\");\n\tREQUIRE(pickUpPre0.arguments().size() == 1u);\n\tconst auto &pickUpPre00 = pickUpPre0.arguments()[0]->as<expressions::Variable>();\n\tCHECK(pickUpPre00.name() == \"x\");\n\tCHECK(pickUpPre00.type() == &block);\n\tCHECK(&pickUpPre00 == pickUp.parameters()[0].get());\n\tconst auto &pickUpPre2 = pickUpPre.arguments()[2]->as<expressions::Predicate>();\n\tCHECK(pickUpPre2.name() == \"handempty\");\n\tCHECK(pickUpPre2.arguments().empty());\n\n\tconst auto &pickUpEff = pickUp.effect()->as<expressions::And>();\n\tREQUIRE(pickUpEff.arguments().size() == 4u);\n\tconst auto &pickUpEff0 = pickUpEff.arguments()[0]->as<expressions::Not>();\n\tconst auto &pickUpEff00 = pickUpEff0.argument()->as<expressions::Predicate>();\n\tCHECK(pickUpEff00.name() == \"ontable\");\n\tREQUIRE(pickUpEff00.arguments().size() == 1u);\n\tconst auto &pickUpEff000 = pickUpEff00.arguments()[0]->as<expressions::Variable>();\n\tCHECK(pickUpEff000.name() == \"x\");\n\tCHECK(pickUpEff000.type() == &block);\n}\n*\/\n<commit_msg>Removed unused test file.<commit_after><|endoftext|>"} {"text":"<commit_before>#include <QCoreApplication>\n#include \"GLApplicationController.h\"\n\n#include <typeinfo>\n#include \"GLPlatonicSolid.h\"\n#include \"Sphere.h\"\n\/\/#include \"Cylinder.h\"\n\/\/#include \"Cone.h\"\n\/\/#include \"Torus.h\"\n\nGLApplicationController::GLApplicationController(GLWindow* window, Drawable* drawableObject)\n\t: window(window), drawable(drawableObject), animating(false)\n{\n\tconnect(window->canvasWidget, SIGNAL(changed()),\n\t\tthis, SLOT(canvasWidgetChanged()));\n\tconnect(window->actionQuit, SIGNAL(triggered()),\n\t\tQCoreApplication::instance(), SLOT(quit()));\n\tconnect(window->xRotSlider, SIGNAL(valueChanged(int)),\n\t\tthis, SLOT(xRotSliderChanged(int)));\n\tconnect(window->yRotSlider, SIGNAL(valueChanged(int)),\n\t\tthis, SLOT(yRotSliderChanged(int)));\n\tconnect(window->zRotSlider, SIGNAL(valueChanged(int)),\n\t\tthis, SLOT(zRotSliderChanged(int)));\n\tconnect(window->animationCheckBox, SIGNAL(stateChanged(int)),\n\t\tthis, SLOT(animationCheckBoxChanged(int)));\n\n\tconnect(window->objectChooser, SIGNAL(currentIndexChanged(int)),\n\t\tthis, SLOT(objectChooserIndexChanged(int)));\n\tconnect(window->colourChooser, SIGNAL(currentIndexChanged(int)),\n\t\tthis, SLOT(colourChooserIndexChanged(int)));\n\n\tanimationTimer = new QTimer(this);\n\tconnect(animationTimer, SIGNAL(timeout()), this, SLOT(nextAnimationFrame()));\n\tanimationTimer->start(ANIMATION_FRAME_LENGTH);\n}\n\nvoid GLApplicationController::canvasWidgetChanged()\n{\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::xRotSliderChanged(int newValue)\n{\n\tdrawable->setXRotation( static_cast<float>(newValue) );\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::yRotSliderChanged(int newValue)\n{\n\tdrawable->setYRotation( static_cast<float>(newValue) );\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::zRotSliderChanged(int newValue)\n{\n\tdrawable->setZRotation( static_cast<float>(newValue) );\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::animationCheckBoxChanged(int newState)\n{\n\tanimating = (newState == Qt::Checked);\n}\n\nvoid GLApplicationController::objectChooserIndexChanged(int newIndex)\n{\n\t\/\/ We keep the drawable's current rendering method so\n\t\/\/ we can restore if it a new drawable is created\n\tRenderMethod oldRenderMethod = drawable->renderMethod();\n\n\tswitch (newIndex)\n\t{\n\tcase 0: \/\/ Sphere\n\t\tdrawable = new Sphere(0.25, 10, 10);\n\t\tbreak;\n\tcase 1: \/\/ Cylinder\n\t\t\/\/drawable = new Cylinder();\n\t\tbreak;\n\tcase 2: \/\/ Cone\n\t\t\/\/drawable = new Cone();\n\t\tbreak;\n\tcase 3: \/\/ Torus\n\t\t\/\/drawable = new Torus();\n\t\tbreak;\n\tdefault: \/\/ if default case, just do nothing and leave current object\n\t\treturn;\n\t}\n\t\/\/ Restore old render method and colouring\n\tdrawable->setRenderMethod(oldRenderMethod);\n\n\twindow->setDrawable(drawable);\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::colourChooserIndexChanged(int newIndex)\n{\n\t\/\/ TODO\n\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::nextAnimationFrame()\n{\n\tif (!animating) return;\n\n\tVector3 rotation = drawable->rotation();\n\tif (rotation.x < 0.0f || rotation.x > 360.0f) rotation.x = 0.0f;\n\telse rotation.x += 1.0f;\n\tif (rotation.y < 0.0f || rotation.y > 360.0f) rotation.y = 0.0f;\n\telse rotation.y += 1.0f;\n\tif (rotation.z < 0.0f || rotation.z > 360.0f) rotation.z = 0.0f;\n\telse rotation.z += 1.0f;\n\tdrawable->setRotation(rotation);\n\n\twindow->resetInterface();\n}\n<commit_msg>Combo box for colouring now changes the colouring<commit_after>#include <QCoreApplication>\n#include \"GLApplicationController.h\"\n\n#include <typeinfo>\n#include \"GLPlatonicSolid.h\"\n#include \"Sphere.h\"\n\/\/#include \"Cylinder.h\"\n\/\/#include \"Cone.h\"\n\/\/#include \"Torus.h\"\n\nGLApplicationController::GLApplicationController(GLWindow* window, Drawable* drawableObject)\n\t: window(window), drawable(drawableObject), animating(false)\n{\n\tconnect(window->canvasWidget, SIGNAL(changed()),\n\t\tthis, SLOT(canvasWidgetChanged()));\n\tconnect(window->actionQuit, SIGNAL(triggered()),\n\t\tQCoreApplication::instance(), SLOT(quit()));\n\tconnect(window->xRotSlider, SIGNAL(valueChanged(int)),\n\t\tthis, SLOT(xRotSliderChanged(int)));\n\tconnect(window->yRotSlider, SIGNAL(valueChanged(int)),\n\t\tthis, SLOT(yRotSliderChanged(int)));\n\tconnect(window->zRotSlider, SIGNAL(valueChanged(int)),\n\t\tthis, SLOT(zRotSliderChanged(int)));\n\tconnect(window->animationCheckBox, SIGNAL(stateChanged(int)),\n\t\tthis, SLOT(animationCheckBoxChanged(int)));\n\n\tconnect(window->objectChooser, SIGNAL(currentIndexChanged(int)),\n\t\tthis, SLOT(objectChooserIndexChanged(int)));\n\tconnect(window->colourChooser, SIGNAL(currentIndexChanged(int)),\n\t\tthis, SLOT(colourChooserIndexChanged(int)));\n\n\tanimationTimer = new QTimer(this);\n\tconnect(animationTimer, SIGNAL(timeout()), this, SLOT(nextAnimationFrame()));\n\tanimationTimer->start(ANIMATION_FRAME_LENGTH);\n}\n\nvoid GLApplicationController::canvasWidgetChanged()\n{\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::xRotSliderChanged(int newValue)\n{\n\tdrawable->setXRotation( static_cast<float>(newValue) );\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::yRotSliderChanged(int newValue)\n{\n\tdrawable->setYRotation( static_cast<float>(newValue) );\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::zRotSliderChanged(int newValue)\n{\n\tdrawable->setZRotation( static_cast<float>(newValue) );\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::animationCheckBoxChanged(int newState)\n{\n\tanimating = (newState == Qt::Checked);\n}\n\nvoid GLApplicationController::objectChooserIndexChanged(int newIndex)\n{\n\t\/\/ We keep the drawable's current rendering method so\n\t\/\/ we can restore if it a new drawable is created\n\tRenderMethod oldRenderMethod = drawable->renderMethod();\n\n\tswitch (newIndex)\n\t{\n\tcase 0: \/\/ Sphere\n\t\tdrawable = new Sphere(0.25, 10, 10);\n\t\tbreak;\n\tcase 1: \/\/ Cylinder\n\t\t\/\/drawable = new Cylinder();\n\t\tbreak;\n\tcase 2: \/\/ Cone\n\t\t\/\/drawable = new Cone();\n\t\tbreak;\n\tcase 3: \/\/ Torus\n\t\t\/\/drawable = new Torus();\n\t\tbreak;\n\tdefault: \/\/ if default case, just do nothing and leave current object\n\t\treturn;\n\t}\n\t\/\/ Restore old render method and colouring (if instance is a mesh)\n\tdrawable->setRenderMethod(oldRenderMethod);\n\tMesh* meshObject = dynamic_cast<Mesh*>(drawable);\n\tif (meshObject)\n\t\tmeshObject->setColouring( static_cast<Mesh::Colouring>(newIndex) );\n\n\twindow->setDrawable(drawable);\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::colourChooserIndexChanged(int newIndex)\n{\n\t\/\/ If object is an instance of mesh, assign new colouring\n\tMesh* meshObject = dynamic_cast<Mesh*>(drawable);\n\tif (meshObject)\n\t\tmeshObject->setColouring( static_cast<Mesh::Colouring>(newIndex) );\n\n\twindow->resetInterface();\n}\n\nvoid GLApplicationController::nextAnimationFrame()\n{\n\tif (!animating) return;\n\n\tVector3 rotation = drawable->rotation();\n\tif (rotation.x < 0.0f || rotation.x > 360.0f) rotation.x = 0.0f;\n\telse rotation.x += 1.0f;\n\tif (rotation.y < 0.0f || rotation.y > 360.0f) rotation.y = 0.0f;\n\telse rotation.y += 1.0f;\n\tif (rotation.z < 0.0f || rotation.z > 360.0f) rotation.z = 0.0f;\n\telse rotation.z += 1.0f;\n\tdrawable->setRotation(rotation);\n\n\twindow->resetInterface();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2022 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\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 *\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\n * distribution.\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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"ChunkedIstream.hxx\"\n#include \"FacadeIstream.hxx\"\n#include \"Bucket.hxx\"\n#include \"New.hxx\"\n#include \"UnusedPtr.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/DestructObserver.hxx\"\n#include \"util\/HexFormat.hxx\"\n#include \"util\/SpanCast.hxx\"\n\n#include <algorithm>\n\n#include <assert.h>\n#include <string.h>\n\nusing std::string_view_literals::operator\"\"sv;\n\nclass ChunkedIstream final : public FacadeIstream, DestructAnchor {\n\t\/**\n\t * This flag is true while writing the buffer inside _Read().\n\t * OnData() will check it, and refuse to accept more data from the\n\t * input. This avoids writing the buffer recursively.\n\t *\/\n\tbool writing_buffer = false;\n\n\tchar buffer[7];\n\tsize_t buffer_sent = sizeof(buffer);\n\n\tsize_t missing_from_current_chunk = 0;\n\npublic:\n\tChunkedIstream(struct pool &p, UnusedIstreamPtr &&_input) noexcept\n\t\t:FacadeIstream(p, std::move(_input)) {}\n\n\t\/* virtual methods from class Istream *\/\n\n\tvoid _Read() noexcept override;\n\tvoid _FillBucketList(IstreamBucketList &list) override;\n\tsize_t _ConsumeBucketList(size_t nbytes) noexcept override;\n\n\t\/* virtual methods from class IstreamHandler *\/\n\n\tbool OnIstreamReady() noexcept override {\n\t\treturn InvokeReady();\n\t}\n\n\tsize_t OnData(const void *data, size_t length) noexcept override;\n\tvoid OnEof() noexcept override;\n\tvoid OnError(std::exception_ptr ep) noexcept override;\n\nprivate:\n\tbool IsBufferEmpty() const noexcept {\n\t\tassert(buffer_sent <= sizeof(buffer));\n\n\t\treturn buffer_sent == sizeof(buffer);\n\t}\n\n\t\/** set the buffer length and return a pointer to the first byte *\/\n\tchar *SetBuffer(size_t length) noexcept {\n\t\tassert(IsBufferEmpty());\n\t\tassert(length <= sizeof(buffer));\n\n\t\tbuffer_sent = sizeof(buffer) - length;\n\t\treturn buffer + buffer_sent;\n\t}\n\n\t\/** append data to the buffer *\/\n\tvoid AppendToBuffer(const void *data, size_t length) noexcept;\n\n\tvoid StartChunk(size_t length) noexcept;\n\n\tConstBuffer<void> ReadBuffer() noexcept {\n\t\treturn { buffer + buffer_sent, sizeof(buffer) - buffer_sent };\n\t}\n\n\tsize_t ConsumeBuffer(size_t nbytes) noexcept {\n\t\tsize_t size = ReadBuffer().size;\n\t\tif (size > nbytes)\n\t\t\tsize = nbytes;\n\n\t\tif (size > 0) {\n\t\t\tbuffer_sent += size;\n\t\t\tConsumed(size);\n\t\t}\n\n\t\treturn size;\n\t}\n\n\t\/**\n\t * Returns true if the buffer is consumed.\n\t *\/\n\tbool SendBuffer() noexcept;\n\n\t\/**\n\t * Wrapper for SendBuffer() that sets and clears the\n\t * #writing_buffer flag. This requires acquiring a pool reference\n\t * to do that safely.\n\t *\n\t * @return true if the buffer is consumed.\n\t *\/\n\tbool SendBuffer2() noexcept;\n\n\tsize_t Feed(const char *data, size_t length) noexcept;\n};\n\nvoid\nChunkedIstream::AppendToBuffer(const void *data, size_t length) noexcept\n{\n\tassert(data != nullptr);\n\tassert(length > 0);\n\tassert(length <= buffer_sent);\n\n\tconst auto old = ReadBuffer();\n\n#ifndef NDEBUG\n\t\/* simulate a buffer reset; if we don't do this, an assertion in\n\t SetBuffer() fails (which is invalid for this special case) *\/\n\tbuffer_sent = sizeof(buffer);\n#endif\n\n\tauto dest = SetBuffer(old.size + length);\n\tmemmove(dest, old.data, old.size);\n\tdest += old.size;\n\n\tmemcpy(dest, data, length);\n}\n\nvoid\nChunkedIstream::StartChunk(size_t length) noexcept\n{\n\tassert(length > 0);\n\tassert(IsBufferEmpty());\n\tassert(missing_from_current_chunk == 0);\n\n\tif (length > 0x8000)\n\t\t\/* maximum chunk size is 32kB for now *\/\n\t\tlength = 0x8000;\n\n\tmissing_from_current_chunk = length;\n\n\tchar *p = SetBuffer(6);\n\tp = HexFormatUint16Fixed(p, (uint16_t)length);\n\t*p++ = '\\r';\n\t*p++ = '\\n';\n}\n\nbool\nChunkedIstream::SendBuffer() noexcept\n{\n\tauto r = ReadBuffer();\n\tif (r.empty())\n\t\treturn true;\n\n\tsize_t nbytes = InvokeData(r.data, r.size);\n\tif (nbytes > 0)\n\t\tbuffer_sent += nbytes;\n\n\treturn nbytes == r.size;\n}\n\nbool\nChunkedIstream::SendBuffer2() noexcept\n{\n\tconst DestructObserver destructed(*this);\n\n\tassert(!writing_buffer);\n\twriting_buffer = true;\n\n\tconst bool result = SendBuffer();\n\tif (!destructed)\n\t\twriting_buffer = false;\n\treturn result;\n}\n\ninline size_t\nChunkedIstream::Feed(const char *data, size_t length) noexcept\n{\n\tconst DestructObserver destructed(*this);\n\n\tsize_t total = 0, rest, nbytes;\n\n\tassert(input.IsDefined());\n\n\tdo {\n\t\tassert(!writing_buffer);\n\n\t\tif (IsBufferEmpty() && missing_from_current_chunk == 0)\n\t\t\tStartChunk(length - total);\n\n\t\tif (!SendBuffer())\n\t\t\treturn destructed ? 0 : total;\n\n\t\tassert(IsBufferEmpty());\n\n\t\tif (missing_from_current_chunk == 0) {\n\t\t\t\/* we have just written the previous chunk trailer;\n\t\t\t re-start this loop to start a new chunk *\/\n\t\t\tnbytes = rest = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\trest = length - total;\n\t\tif (rest > missing_from_current_chunk)\n\t\t\trest = missing_from_current_chunk;\n\n\t\tnbytes = InvokeData(data + total, rest);\n\t\tif (nbytes == 0)\n\t\t\treturn destructed ? 0 : total;\n\n\t\ttotal += nbytes;\n\n\t\tmissing_from_current_chunk -= nbytes;\n\t\tif (missing_from_current_chunk == 0) {\n\t\t\t\/* a chunk ends with \"\\r\\n\" *\/\n\t\t\tchar *p = SetBuffer(2);\n\t\t\tp[0] = '\\r';\n\t\t\tp[1] = '\\n';\n\t\t}\n\t} while ((!IsBufferEmpty() || total < length) && nbytes == rest);\n\n\treturn total;\n}\n\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nChunkedIstream::OnData(const void *data, size_t length) noexcept\n{\n\tif (writing_buffer)\n\t\t\/* this is a recursive call from _Read(): bail out *\/\n\t\treturn 0;\n\n\treturn Feed((const char*)data, length);\n}\n\nvoid\nChunkedIstream::OnEof() noexcept\n{\n\tassert(input.IsDefined());\n\tassert(missing_from_current_chunk == 0);\n\n\tinput.Clear();\n\n\t\/* write EOF chunk (length 0) *\/\n\n\tAppendToBuffer(\"0\\r\\n\\r\\n\", 5);\n\n\t\/* flush the buffer *\/\n\n\tif (SendBuffer())\n\t\tDestroyEof();\n}\n\nvoid\nChunkedIstream::OnError(std::exception_ptr ep) noexcept\n{\n\tassert(input.IsDefined());\n\n\tinput.Clear();\n\tDestroyError(ep);\n}\n\n\/*\n * istream implementation\n *\n *\/\n\nvoid\nChunkedIstream::_Read() noexcept\n{\n\tif (!SendBuffer2())\n\t\treturn;\n\n\tif (!input.IsDefined()) {\n\t\tDestroyEof();\n\t\treturn;\n\t}\n\n\tif (IsBufferEmpty() && missing_from_current_chunk == 0) {\n\t\toff_t available = input.GetAvailable(true);\n\t\tif (available > 0) {\n\t\t\tStartChunk(available);\n\t\t\tif (!SendBuffer2())\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\tinput.Read();\n}\n\nvoid\nChunkedIstream::_FillBucketList(IstreamBucketList &list)\n{\n\tif (!input.IsDefined()) {\n\t\t\/\/ TODO: generate EOF chunk\n\t\tlist.SetMore();\n\t\treturn;\n\t}\n\n\tauto b = ReadBuffer();\n\tif (b.empty() && missing_from_current_chunk == 0) {\n\t\toff_t available = input.GetAvailable(true);\n\t\tif (available > 0) {\n\t\t\tStartChunk(available);\n\t\t\tb = ReadBuffer();\n\t\t}\n\t}\n\n\tif (!b.empty())\n\t\tlist.Push(b);\n\n\tif (missing_from_current_chunk > 0) {\n\t\tassert(input.IsDefined());\n\n\t\tIstreamBucketList sub;\n\t\ttry {\n\t\t\tinput.FillBucketList(sub);\n\t\t} catch (...) {\n\t\t\tDestroy();\n\t\t\tthrow;\n\t\t}\n\n\t\tsize_t nbytes = list.SpliceBuffersFrom(std::move(sub),\n\t\t\t\t\t\t missing_from_current_chunk);\n\t\tif (nbytes >= missing_from_current_chunk)\n\t\t\tlist.Push(AsBytes(\"\\r\\n\"sv));\n\t}\n\n\tlist.SetMore();\n}\n\nsize_t\nChunkedIstream::_ConsumeBucketList(size_t nbytes) noexcept\n{\n\tsize_t total = 0;\n\n\tsize_t size = ConsumeBuffer(nbytes);\n\tnbytes -= size;\n\ttotal += size;\n\n\tsize = std::min(nbytes, missing_from_current_chunk);\n\tif (size > 0) {\n\t\tassert(input.IsDefined());\n\n\t\tsize = input.ConsumeBucketList(size);\n\t\tConsumed(size);\n\t\tnbytes -= size;\n\t\ttotal += size;\n\n\t\tmissing_from_current_chunk -= size;\n\t\tif (missing_from_current_chunk == 0) {\n\t\t\t\/* a chunk ends with \"\\r\\n\" *\/\n\t\t\tchar *p = SetBuffer(2);\n\t\t\tp[0] = '\\r';\n\t\t\tp[1] = '\\n';\n\n\t\t\tsize = ConsumeBuffer(nbytes);\n\t\t\tnbytes -= size;\n\t\t\ttotal += size;\n\t\t}\n\n\t\tif (nbytes > 0)\n\t\t\t\/* if data still remains, then our input must\n\t\t\t have reached end-of-file *\/\n\t\t\tCloseInput();\n\t}\n\n\treturn total;\n}\n\n\/*\n * constructor\n *\n *\/\n\nUnusedIstreamPtr\nistream_chunked_new(struct pool &pool, UnusedIstreamPtr input) noexcept\n{\n\treturn NewIstreamPtr<ChunkedIstream>(pool, std::move(input));\n}\n<commit_msg>istream\/chunked: use std::array and std::span<commit_after>\/*\n * Copyright 2007-2022 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\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 *\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\n * distribution.\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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"ChunkedIstream.hxx\"\n#include \"FacadeIstream.hxx\"\n#include \"Bucket.hxx\"\n#include \"New.hxx\"\n#include \"UnusedPtr.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/DestructObserver.hxx\"\n#include \"util\/HexFormat.hxx\"\n#include \"util\/SpanCast.hxx\"\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n\n#include <string.h>\n\nusing std::string_view_literals::operator\"\"sv;\n\nclass ChunkedIstream final : public FacadeIstream, DestructAnchor {\n\t\/**\n\t * This flag is true while writing the buffer inside _Read().\n\t * OnData() will check it, and refuse to accept more data from the\n\t * input. This avoids writing the buffer recursively.\n\t *\/\n\tbool writing_buffer = false;\n\n\tstd::array<char, 7> buffer;\n\tsize_t buffer_sent = buffer.size();\n\n\tsize_t missing_from_current_chunk = 0;\n\npublic:\n\tChunkedIstream(struct pool &p, UnusedIstreamPtr &&_input) noexcept\n\t\t:FacadeIstream(p, std::move(_input)) {}\n\n\t\/* virtual methods from class Istream *\/\n\n\tvoid _Read() noexcept override;\n\tvoid _FillBucketList(IstreamBucketList &list) override;\n\tsize_t _ConsumeBucketList(size_t nbytes) noexcept override;\n\n\t\/* virtual methods from class IstreamHandler *\/\n\n\tbool OnIstreamReady() noexcept override {\n\t\treturn InvokeReady();\n\t}\n\n\tsize_t OnData(const void *data, size_t length) noexcept override;\n\tvoid OnEof() noexcept override;\n\tvoid OnError(std::exception_ptr ep) noexcept override;\n\nprivate:\n\tbool IsBufferEmpty() const noexcept {\n\t\tassert(buffer_sent <= buffer.size());\n\n\t\treturn buffer_sent == buffer.size();\n\t}\n\n\t\/** set the buffer length and return a pointer to the first byte *\/\n\tchar *SetBuffer(size_t length) noexcept {\n\t\tassert(IsBufferEmpty());\n\t\tassert(length <= buffer.size());\n\n\t\tbuffer_sent = buffer.size() - length;\n\t\treturn buffer.data() + buffer_sent;\n\t}\n\n\t\/** append data to the buffer *\/\n\tvoid AppendToBuffer(std::string_view src) noexcept;\n\n\tvoid StartChunk(size_t length) noexcept;\n\n\tstd::span<const char> ReadBuffer() noexcept {\n\t\treturn std::span{buffer}.subspan(buffer_sent);\n\t}\n\n\tsize_t ConsumeBuffer(size_t nbytes) noexcept {\n\t\tsize_t size = ReadBuffer().size();\n\t\tif (size > nbytes)\n\t\t\tsize = nbytes;\n\n\t\tif (size > 0) {\n\t\t\tbuffer_sent += size;\n\t\t\tConsumed(size);\n\t\t}\n\n\t\treturn size;\n\t}\n\n\t\/**\n\t * Returns true if the buffer is consumed.\n\t *\/\n\tbool SendBuffer() noexcept;\n\n\t\/**\n\t * Wrapper for SendBuffer() that sets and clears the\n\t * #writing_buffer flag. This requires acquiring a pool reference\n\t * to do that safely.\n\t *\n\t * @return true if the buffer is consumed.\n\t *\/\n\tbool SendBuffer2() noexcept;\n\n\tsize_t Feed(const char *data, size_t length) noexcept;\n};\n\nvoid\nChunkedIstream::AppendToBuffer(std::string_view src) noexcept\n{\n\tassert(!src.empty());\n\tassert(src.size() <= buffer_sent);\n\n\tconst auto old = ReadBuffer();\n\n#ifndef NDEBUG\n\t\/* simulate a buffer reset; if we don't do this, an assertion in\n\t SetBuffer() fails (which is invalid for this special case) *\/\n\tbuffer_sent = buffer.size();\n#endif\n\n\tauto dest = SetBuffer(old.size() + src.size());\n\tdest = std::copy(old.begin(), old.end(), dest);\n\tstd::copy(src.begin(), src.end(), dest);\n}\n\nvoid\nChunkedIstream::StartChunk(size_t length) noexcept\n{\n\tassert(length > 0);\n\tassert(IsBufferEmpty());\n\tassert(missing_from_current_chunk == 0);\n\n\tif (length > 0x8000)\n\t\t\/* maximum chunk size is 32kB for now *\/\n\t\tlength = 0x8000;\n\n\tmissing_from_current_chunk = length;\n\n\tchar *p = (char *)SetBuffer(6);\n\tp = HexFormatUint16Fixed(p, (uint16_t)length);\n\t*p++ = '\\r';\n\t*p++ = '\\n';\n}\n\nbool\nChunkedIstream::SendBuffer() noexcept\n{\n\tauto r = ReadBuffer();\n\tif (r.empty())\n\t\treturn true;\n\n\tsize_t nbytes = InvokeData(r.data(), r.size());\n\tif (nbytes > 0)\n\t\tbuffer_sent += nbytes;\n\n\treturn nbytes == r.size();\n}\n\nbool\nChunkedIstream::SendBuffer2() noexcept\n{\n\tconst DestructObserver destructed(*this);\n\n\tassert(!writing_buffer);\n\twriting_buffer = true;\n\n\tconst bool result = SendBuffer();\n\tif (!destructed)\n\t\twriting_buffer = false;\n\treturn result;\n}\n\ninline size_t\nChunkedIstream::Feed(const char *data, size_t length) noexcept\n{\n\tconst DestructObserver destructed(*this);\n\n\tsize_t total = 0, rest, nbytes;\n\n\tassert(input.IsDefined());\n\n\tdo {\n\t\tassert(!writing_buffer);\n\n\t\tif (IsBufferEmpty() && missing_from_current_chunk == 0)\n\t\t\tStartChunk(length - total);\n\n\t\tif (!SendBuffer())\n\t\t\treturn destructed ? 0 : total;\n\n\t\tassert(IsBufferEmpty());\n\n\t\tif (missing_from_current_chunk == 0) {\n\t\t\t\/* we have just written the previous chunk trailer;\n\t\t\t re-start this loop to start a new chunk *\/\n\t\t\tnbytes = rest = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\trest = length - total;\n\t\tif (rest > missing_from_current_chunk)\n\t\t\trest = missing_from_current_chunk;\n\n\t\tnbytes = InvokeData(data + total, rest);\n\t\tif (nbytes == 0)\n\t\t\treturn destructed ? 0 : total;\n\n\t\ttotal += nbytes;\n\n\t\tmissing_from_current_chunk -= nbytes;\n\t\tif (missing_from_current_chunk == 0) {\n\t\t\t\/* a chunk ends with \"\\r\\n\" *\/\n\t\t\tchar *p = SetBuffer(2);\n\t\t\tp[0] = '\\r';\n\t\t\tp[1] = '\\n';\n\t\t}\n\t} while ((!IsBufferEmpty() || total < length) && nbytes == rest);\n\n\treturn total;\n}\n\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nChunkedIstream::OnData(const void *data, size_t length) noexcept\n{\n\tif (writing_buffer)\n\t\t\/* this is a recursive call from _Read(): bail out *\/\n\t\treturn 0;\n\n\treturn Feed((const char*)data, length);\n}\n\nvoid\nChunkedIstream::OnEof() noexcept\n{\n\tassert(input.IsDefined());\n\tassert(missing_from_current_chunk == 0);\n\n\tinput.Clear();\n\n\t\/* write EOF chunk (length 0) *\/\n\n\tAppendToBuffer(\"0\\r\\n\\r\\n\"sv);\n\n\t\/* flush the buffer *\/\n\n\tif (SendBuffer())\n\t\tDestroyEof();\n}\n\nvoid\nChunkedIstream::OnError(std::exception_ptr ep) noexcept\n{\n\tassert(input.IsDefined());\n\n\tinput.Clear();\n\tDestroyError(ep);\n}\n\n\/*\n * istream implementation\n *\n *\/\n\nvoid\nChunkedIstream::_Read() noexcept\n{\n\tif (!SendBuffer2())\n\t\treturn;\n\n\tif (!input.IsDefined()) {\n\t\tDestroyEof();\n\t\treturn;\n\t}\n\n\tif (IsBufferEmpty() && missing_from_current_chunk == 0) {\n\t\toff_t available = input.GetAvailable(true);\n\t\tif (available > 0) {\n\t\t\tStartChunk(available);\n\t\t\tif (!SendBuffer2())\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\tinput.Read();\n}\n\nvoid\nChunkedIstream::_FillBucketList(IstreamBucketList &list)\n{\n\tif (!input.IsDefined()) {\n\t\t\/\/ TODO: generate EOF chunk\n\t\tlist.SetMore();\n\t\treturn;\n\t}\n\n\tauto b = ReadBuffer();\n\tif (b.empty() && missing_from_current_chunk == 0) {\n\t\toff_t available = input.GetAvailable(true);\n\t\tif (available > 0) {\n\t\t\tStartChunk(available);\n\t\t\tb = ReadBuffer();\n\t\t}\n\t}\n\n\tif (!b.empty())\n\t\tlist.Push(std::as_bytes(b));\n\n\tif (missing_from_current_chunk > 0) {\n\t\tassert(input.IsDefined());\n\n\t\tIstreamBucketList sub;\n\t\ttry {\n\t\t\tinput.FillBucketList(sub);\n\t\t} catch (...) {\n\t\t\tDestroy();\n\t\t\tthrow;\n\t\t}\n\n\t\tsize_t nbytes = list.SpliceBuffersFrom(std::move(sub),\n\t\t\t\t\t\t missing_from_current_chunk);\n\t\tif (nbytes >= missing_from_current_chunk)\n\t\t\tlist.Push(AsBytes(\"\\r\\n\"sv));\n\t}\n\n\tlist.SetMore();\n}\n\nsize_t\nChunkedIstream::_ConsumeBucketList(size_t nbytes) noexcept\n{\n\tsize_t total = 0;\n\n\tsize_t size = ConsumeBuffer(nbytes);\n\tnbytes -= size;\n\ttotal += size;\n\n\tsize = std::min(nbytes, missing_from_current_chunk);\n\tif (size > 0) {\n\t\tassert(input.IsDefined());\n\n\t\tsize = input.ConsumeBucketList(size);\n\t\tConsumed(size);\n\t\tnbytes -= size;\n\t\ttotal += size;\n\n\t\tmissing_from_current_chunk -= size;\n\t\tif (missing_from_current_chunk == 0) {\n\t\t\t\/* a chunk ends with \"\\r\\n\" *\/\n\t\t\tchar *p = SetBuffer(2);\n\t\t\tp[0] = '\\r';\n\t\t\tp[1] = '\\n';\n\n\t\t\tsize = ConsumeBuffer(nbytes);\n\t\t\tnbytes -= size;\n\t\t\ttotal += size;\n\t\t}\n\n\t\tif (nbytes > 0)\n\t\t\t\/* if data still remains, then our input must\n\t\t\t have reached end-of-file *\/\n\t\t\tCloseInput();\n\t}\n\n\treturn total;\n}\n\n\/*\n * constructor\n *\n *\/\n\nUnusedIstreamPtr\nistream_chunked_new(struct pool &pool, UnusedIstreamPtr input) noexcept\n{\n\treturn NewIstreamPtr<ChunkedIstream>(pool, std::move(input));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * word.cpp\n *\/\n\n#include \"word.h\"\n\nWord::Word()\n{\n value = \"\";\n frequency = 0;\n}\n\nWord::Word(std::string val)\n{\n std::string text;\n std::remove_copy_if(val.begin(), val.end(), std::back_inserter(text),std::ptr_fun<int,int>(&std::ispunct));\n\n value = text;\n frequency = 1;\n}\n\nWord::~Word(){}\n\nWord::Word(const Word& w)\n{\n value = w.value;\n frequency = w.frequency;\n}\n\nstd::string Word::getVal()\n{\n return value;\n}\n\nint Word::getFrequency()\n{\n return frequency;\n}\n\nvoid Word::setVal(std::string newValue)\n{\n value = newValue;\n}\n\nvoid Word::setFrequency(int newFrequency)\n{\n frequency = newFrequency;\n}\n\nvoid Word::incrementFrequency()\n{\n frequency++;\n}\n\nbool Word::operator==(const Word& w)\n{\n return (w.value == this->value);\n}\n\nstd::ostream& operator<<(std::ostream& os, const Word& w)\n{\n os<<w.value<<\" | \"<<w.frequency;\n return os;\n}\n<commit_msg>added to lower in word constructor & clean up<commit_after>\/*\n * word.cpp\n *\/\n\n#include \"word.h\"\n#include <locale>\n\nWord::Word()\n{\n value = \"\";\n frequency = 0;\n}\n\nWord::Word(std::string val)\n{\n std::string text;\n\n \/\/remove punctuation\n std::remove_copy_if(val.begin(), val.end(), std::back_inserter(text),std::ptr_fun<int,int>(&std::ispunct));\n\n \/\/to lower case\n std::locale loc;\n for (std::string::size_type i=0; i<text.length(); ++i) {\n text[i] = std::tolower(text[i],loc);\n }\n value = text;\n frequency = 1;\n}\n\nWord::~Word(){}\n\nWord::Word(const Word& w)\n{\n value = w.value;\n frequency = w.frequency;\n}\n\nstd::string Word::getVal()\n{\n return value;\n}\n\nint Word::getFrequency()\n{\n return frequency;\n}\n\nvoid Word::setVal(std::string newValue)\n{\n value = newValue;\n}\n\nvoid Word::setFrequency(int newFrequency)\n{\n frequency = newFrequency;\n}\n\nvoid Word::incrementFrequency()\n{\n frequency++;\n}\n\nbool Word::operator==(const Word& w)\n{\n return (w.value == this->value);\n}\n\nstd::ostream& operator<<(std::ostream& os, const Word& w)\n{\n os<<w.value<<\" | \"<<w.frequency;\n return os;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"AsyncServer.h\"\n\n\/\/ #include <jemalloc\/jemalloc.h>\n#include <macgyver\/AsyncTaskGroup.h>\n#include <macgyver\/AnsiEscapeCodes.h>\n#include <macgyver\/Exception.h>\n#include <spine\/HTTP.h>\n#include <spine\/Options.h>\n#include <spine\/Reactor.h>\n#include <spine\/SmartMet.h>\n#include <spine\/Convenience.h>\n#include <sys\/types.h>\n#include <sys\/select.h>\n#include <atomic>\n#include <csignal>\n#include <iostream>\n#include <memory>\n#include <new>\n#include <thread>\n\n\/\/ libdw from elfutils-devel provides more details than libbfd\n#define BACKWARD_HAS_DW 1\n#include \"backward.h\"\n\nstd::unique_ptr<SmartMet::Server::Server> server;\nstd::unique_ptr<SmartMet::Spine::Reactor> reactor;\nstd::unique_ptr<Fmi::AsyncTaskGroup> tasks;\n\nstd::atomic<int> last_signal(0);\n\n\/\/ Allowed core dump signals. Note that we choose to ignore SIGBUS though due to\n\/\/ NFS problems, and SIGQUIT since we want to allow quitting via keyboard\n\nstd::vector<int> core_signals{SIGILL, SIGABRT, SIGFPE, SIGSYS, SIGSEGV, SIGXCPU, SIGXFSZ};\n\nvoid crash_signal_handler(int sig)\n{\n std::cout << \"---------------------------------------------------------\\n\";\n std::cout << SmartMet::Spine::log_time_str() << \" THE SYSTEM IS GOING DOWN (signal=\" << sig << \")\\n\";\n std::cout << \"---------------------------------------------------------\\n\";\n auto requests = reactor->getActiveRequests();\n for (auto it = requests.begin(); it != requests.end(); ++it)\n {\n std::cout << it->second.request.getURI() << \"\\n\";\n std::cout << \"---------------------------------------------------------\\n\";\n }\n signal(sig, SIG_DFL);\n raise(sig);\n}\n\nvoid signal_handler(int sig)\n{\n last_signal = sig;\n}\n\/\/ Block all signals except profiling\nvoid block_signals()\n{\n sigset_t signal_set;\n sigfillset(&signal_set);\n\n \/\/ Enable debugging\n sigdelset(&signal_set, SIGPROF);\n\n \/\/ Enable core dumps from fatal errors\n for (auto sig : core_signals)\n sigdelset(&signal_set, sig);\n\n pthread_sigmask(SIG_BLOCK, &signal_set, nullptr);\n}\n\nvoid set_new_handler(const std::string& name)\n{\n if (name == \"default\") \/\/ system default may change in C++20\n ;\n else if (name == \"bad_alloc\")\n std::set_new_handler([] { throw std::bad_alloc(); });\n else if (name == \"terminate\")\n std::set_new_handler([] { std::terminate(); });\n else\n throw Fmi::Exception(BCP, \"Unknown new_handler\").addParameter(\"name\", name);\n}\n\nint main(int argc, char* argv[])\n{\n try\n {\n \/\/ Parse options\n\n SmartMet::Spine::Options options;\n if (!options.parse(argc, argv))\n exit(1);\n\n \/\/ Use the system locale or autocomplete may not work properly (iconv requirement)\n std::setlocale(LC_ALL, \"\");\n\n \/\/ Set new_handler\n set_new_handler(options.new_handler);\n\n const auto signals_init =\n [] ()\n {\n \/\/ Block signals before starting new threads\n\n block_signals();\n\n \/\/ Set special SIGTERM, SIGBUS and SIGWINCH handlers\n\n struct sigaction action; \/\/ NOLINT(cppcoreguidelines-pro-type-member-init)\n action.sa_handler = signal_handler; \/\/ NOLINT(cppcoreguidelines-pro-type-union-access)\n sigemptyset(&action.sa_mask);\n action.sa_flags = 0;\n sigaction(SIGBUS, &action, nullptr);\n sigaction(SIGTERM, &action, nullptr);\n sigaction(SIGWINCH, &action, nullptr);\n\n \/\/ We also want to record other common non-core dumping signals\n sigaction(SIGHUP, &action, nullptr);\n sigaction(SIGINT, &action, nullptr);\n\n struct sigaction action2; \/\/ NOLINT(cppcoreguidelines-pro-type-member-init)\n action2.sa_handler = crash_signal_handler; \/\/ NOLINT(cppcoreguidelines-pro-type-union-access)\n sigemptyset(&action2.sa_mask);\n action2.sa_flags = 0;\n sigaction(SIGSEGV, &action2, nullptr);\n\n };\n\n std::unique_ptr<backward::SignalHandling> sh;\n if (options.stacktrace)\n sh.reset(new backward::SignalHandling(core_signals));\n\n reactor.reset(new SmartMet::Spine::Reactor(options));\n\n server.reset(new SmartMet::Server::AsyncServer(options, *reactor));\n\n tasks.reset(new Fmi::AsyncTaskGroup);\n tasks->on_task_error([] (const std::string&) { throw; });\n tasks->stop_on_error(true);\n\n tasks->add(\n \"SmartMet::Spine::Reactor::init\",\n [signals_init] ()\n {\n signals_init();\n reactor->init();\n });\n\n tasks->add(\n \"Run SmartMet::Server::AsyncServer\",\n [signals_init] ()\n {\n signals_init();\n std::this_thread::sleep_for(std::chrono::seconds(3));\n std::cout << ANSI_BG_GREEN << ANSI_BOLD_ON << ANSI_FG_WHITE << \"Launched Synapse server\"\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT << std::endl;\n server->run();\n });\n\n \/\/ Sleep until a signal comes, and then either handle it or exit\n\n double sigint_cnt = 0;\n\n while (true)\n {\n struct timeval tv;\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n errno = 0;\n if (select(0, nullptr, nullptr, nullptr, &tv) >= 0) {\n tasks->handle_finished();\n \/\/ FIXME: handle case when all tasks have ended\n } else if (errno != EINTR) {\n std::cout << ANSI_BG_RED << ANSI_BOLD_ON << ANSI_FG_WHITE\n << \"Unexpected error code from select(): \"\n << strerror(errno)\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n }\n\n int sig = last_signal;\n if (sig != 0) {\n std::cout << \"\\n\"\n << ANSI_BG_RED << ANSI_BOLD_ON << ANSI_FG_WHITE << \"Signal '\"\n << strsignal(sig) << \"' (\" << sig << \") received \";\n\n if (sig == SIGBUS || sig == SIGWINCH)\n {\n std::cout << \" - ignoring it!\"\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n last_signal = 0;\n }\n else if (sig == SIGTERM)\n {\n std::cout << \" - shutting down!\"\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n\n tasks->stop();\n server->shutdownServer();\n tasks->wait();\n\n \/\/ Save heap profile if it has been enabled\n \/\/ mallctl(\"prof.dump\", nullptr, nullptr, nullptr, 0);\n return 0;\n }\n else if (sig == SIGINT)\n {\n\t last_signal = 0;\n Fmi::AsyncTask shutdown_timer(\"Shutdown timer\",\n\t\t\t\t\t [&sigint_cnt]()\n\t\t\t\t\t {\n\t\t\t\t\t\t for (int i = 0; i < 1200; i++)\n\t\t\t\t\t\t {\n\t\t\t\t\t\t boost::this_thread::sleep_for(boost::chrono::milliseconds(50));\n\t\t\t\t\t\t if (last_signal == SIGINT || last_signal == SIGTERM) {\n\t\t\t\t\t\t\t last_signal = 0;\n\t\t\t\t\t\t\t sigint_cnt++;\n if (sigint_cnt > 5) {\n\t\t\t\t\t\t\t std::cout << \"*** Too many SIGINT or SIGTERM signals after first SIGINT. Commiting suicide\" << std::endl;\n\t\t\t\t\t\t\t abort();\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t } else {\n\t\t\t\t\t\t\t sigint_cnt = std::max(0.0, sigint_cnt - 0.05);\n\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t\t\t\t std::cout << \"*** Timed out waiting for server to shut down after SIGINT\" << std::endl;\n abort();\n\t\t\t\t\t });\n std::cout << \" - shutting down!\"\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n\n tasks->stop();\n server->shutdownServer();\n tasks->wait();\n\t\tshutdown_timer.cancel();\n\n \/\/ Save heap profile if it has been enabled\n \/\/ mallctl(\"prof.dump\", nullptr, nullptr, nullptr, 0);\n return 0;\n }\n else\n {\n std::cout << \" - exiting!\" << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n break;\n }\n }\n }\n\n return 666;\n }\n catch (...)\n {\n Fmi::Exception exception(BCP, \"Operation failed!\", nullptr);\n exception.printError();\n\n return -1;\n }\n}\n<commit_msg>smartmetd.cpp: initialization task erro handling update<commit_after>#include \"AsyncServer.h\"\n\n\/\/ #include <jemalloc\/jemalloc.h>\n#include <macgyver\/AsyncTaskGroup.h>\n#include <macgyver\/AnsiEscapeCodes.h>\n#include <macgyver\/Exception.h>\n#include <spine\/HTTP.h>\n#include <spine\/Options.h>\n#include <spine\/Reactor.h>\n#include <spine\/SmartMet.h>\n#include <spine\/Convenience.h>\n#include <sys\/types.h>\n#include <sys\/select.h>\n#include <atomic>\n#include <csignal>\n#include <iostream>\n#include <memory>\n#include <new>\n#include <thread>\n\n\/\/ libdw from elfutils-devel provides more details than libbfd\n#define BACKWARD_HAS_DW 1\n#include \"backward.h\"\n\nstd::unique_ptr<SmartMet::Server::Server> server;\nstd::unique_ptr<SmartMet::Spine::Reactor> reactor;\nstd::unique_ptr<Fmi::AsyncTaskGroup> tasks;\n\nstd::atomic<int> last_signal(0);\n\n\/\/ Allowed core dump signals. Note that we choose to ignore SIGBUS though due to\n\/\/ NFS problems, and SIGQUIT since we want to allow quitting via keyboard\n\nstd::vector<int> core_signals{SIGILL, SIGABRT, SIGFPE, SIGSYS, SIGSEGV, SIGXCPU, SIGXFSZ};\n\nvoid crash_signal_handler(int sig)\n{\n std::cout << \"---------------------------------------------------------\\n\";\n std::cout << SmartMet::Spine::log_time_str() << \" THE SYSTEM IS GOING DOWN (signal=\" << sig << \")\\n\";\n std::cout << \"---------------------------------------------------------\\n\";\n auto requests = reactor->getActiveRequests();\n for (auto it = requests.begin(); it != requests.end(); ++it)\n {\n std::cout << it->second.request.getURI() << \"\\n\";\n std::cout << \"---------------------------------------------------------\\n\";\n }\n signal(sig, SIG_DFL);\n raise(sig);\n}\n\nvoid signal_handler(int sig)\n{\n last_signal = sig;\n}\n\/\/ Block all signals except profiling\nvoid block_signals()\n{\n sigset_t signal_set;\n sigfillset(&signal_set);\n\n \/\/ Enable debugging\n sigdelset(&signal_set, SIGPROF);\n\n \/\/ Enable core dumps from fatal errors\n for (auto sig : core_signals)\n sigdelset(&signal_set, sig);\n\n pthread_sigmask(SIG_BLOCK, &signal_set, nullptr);\n}\n\nvoid set_new_handler(const std::string& name)\n{\n if (name == \"default\") \/\/ system default may change in C++20\n ;\n else if (name == \"bad_alloc\")\n std::set_new_handler([] { throw std::bad_alloc(); });\n else if (name == \"terminate\")\n std::set_new_handler([] { std::terminate(); });\n else\n throw Fmi::Exception(BCP, \"Unknown new_handler\").addParameter(\"name\", name);\n}\n\nint main(int argc, char* argv[])\n{\n try\n {\n \/\/ Parse options\n\n SmartMet::Spine::Options options;\n if (!options.parse(argc, argv))\n exit(1);\n\n \/\/ Use the system locale or autocomplete may not work properly (iconv requirement)\n std::setlocale(LC_ALL, \"\");\n\n \/\/ Set new_handler\n set_new_handler(options.new_handler);\n\n const auto signals_init =\n [] ()\n {\n \/\/ Block signals before starting new threads\n\n block_signals();\n\n \/\/ Set special SIGTERM, SIGBUS and SIGWINCH handlers\n\n struct sigaction action; \/\/ NOLINT(cppcoreguidelines-pro-type-member-init)\n action.sa_handler = signal_handler; \/\/ NOLINT(cppcoreguidelines-pro-type-union-access)\n sigemptyset(&action.sa_mask);\n action.sa_flags = 0;\n sigaction(SIGBUS, &action, nullptr);\n sigaction(SIGTERM, &action, nullptr);\n sigaction(SIGWINCH, &action, nullptr);\n\n \/\/ We also want to record other common non-core dumping signals\n sigaction(SIGHUP, &action, nullptr);\n sigaction(SIGINT, &action, nullptr);\n\n struct sigaction action2; \/\/ NOLINT(cppcoreguidelines-pro-type-member-init)\n action2.sa_handler = crash_signal_handler; \/\/ NOLINT(cppcoreguidelines-pro-type-union-access)\n sigemptyset(&action2.sa_mask);\n action2.sa_flags = 0;\n sigaction(SIGSEGV, &action2, nullptr);\n\n };\n\n std::unique_ptr<backward::SignalHandling> sh;\n if (options.stacktrace)\n sh.reset(new backward::SignalHandling(core_signals));\n\n reactor.reset(new SmartMet::Spine::Reactor(options));\n\n server.reset(new SmartMet::Server::AsyncServer(options, *reactor));\n\n tasks.reset(new Fmi::AsyncTaskGroup);\n\n tasks->on_task_error(\n [] (const std::string&)\n {\n if (server)\n {\n server->shutdownServer();\n }\n else\n {\n throw;\n }\n });\n\n tasks->stop_on_error(true);\n\n tasks->add(\n \"SmartMet::Spine::Reactor::init\",\n [signals_init] ()\n {\n signals_init();\n reactor->init();\n });\n\n tasks->add(\n \"Run SmartMet::Server::AsyncServer\",\n [signals_init] ()\n {\n signals_init();\n std::this_thread::sleep_for(std::chrono::seconds(3));\n std::cout << ANSI_BG_GREEN << ANSI_BOLD_ON << ANSI_FG_WHITE << \"Launched Synapse server\"\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT << std::endl;\n server->run();\n });\n\n \/\/ Sleep until a signal comes, and then either handle it or exit\n\n double sigint_cnt = 0;\n\n while (true)\n {\n struct timeval tv;\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n errno = 0;\n if (select(0, nullptr, nullptr, nullptr, &tv) >= 0) {\n tasks->handle_finished();\n \/\/ FIXME: handle case when all tasks have ended\n } else if (errno != EINTR) {\n std::cout << ANSI_BG_RED << ANSI_BOLD_ON << ANSI_FG_WHITE\n << \"Unexpected error code from select(): \"\n << strerror(errno)\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n }\n\n int sig = last_signal;\n if (sig != 0) {\n std::cout << \"\\n\"\n << ANSI_BG_RED << ANSI_BOLD_ON << ANSI_FG_WHITE << \"Signal '\"\n << strsignal(sig) << \"' (\" << sig << \") received \";\n\n if (sig == SIGBUS || sig == SIGWINCH)\n {\n std::cout << \" - ignoring it!\"\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n last_signal = 0;\n }\n else if (sig == SIGTERM)\n {\n std::cout << \" - shutting down!\"\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n\n tasks->stop();\n server->shutdownServer();\n tasks->wait();\n\n \/\/ Save heap profile if it has been enabled\n \/\/ mallctl(\"prof.dump\", nullptr, nullptr, nullptr, 0);\n return 0;\n }\n else if (sig == SIGINT)\n {\n\t last_signal = 0;\n Fmi::AsyncTask shutdown_timer(\"Shutdown timer\",\n\t\t\t\t\t [&sigint_cnt]()\n\t\t\t\t\t {\n\t\t\t\t\t\t for (int i = 0; i < 1200; i++)\n\t\t\t\t\t\t {\n\t\t\t\t\t\t boost::this_thread::sleep_for(boost::chrono::milliseconds(50));\n\t\t\t\t\t\t if (last_signal == SIGINT || last_signal == SIGTERM) {\n\t\t\t\t\t\t\t last_signal = 0;\n\t\t\t\t\t\t\t sigint_cnt++;\n if (sigint_cnt > 5) {\n\t\t\t\t\t\t\t std::cout << \"*** Too many SIGINT or SIGTERM signals after first SIGINT. Commiting suicide\" << std::endl;\n\t\t\t\t\t\t\t abort();\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t } else {\n\t\t\t\t\t\t\t sigint_cnt = std::max(0.0, sigint_cnt - 0.05);\n\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t\t\t\t std::cout << \"*** Timed out waiting for server to shut down after SIGINT\" << std::endl;\n abort();\n\t\t\t\t\t });\n std::cout << \" - shutting down!\"\n << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n\n tasks->stop();\n server->shutdownServer();\n tasks->wait();\n\t\tshutdown_timer.cancel();\n\n \/\/ Save heap profile if it has been enabled\n \/\/ mallctl(\"prof.dump\", nullptr, nullptr, nullptr, 0);\n return 0;\n }\n else\n {\n std::cout << \" - exiting!\" << ANSI_FG_DEFAULT << ANSI_BOLD_OFF << ANSI_BG_DEFAULT\n << std::endl;\n break;\n }\n }\n }\n\n return 666;\n }\n catch (...)\n {\n Fmi::Exception exception(BCP, \"Operation failed!\", nullptr);\n exception.printError();\n\n return -1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#define SOFA_COMPONENT_ENGINE_VALUESFROMINDICES_CPP\n#include <SofaEngine\/ValuesFromIndices.inl>\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/defaulttype\/Vec3Types.h>\n#include <sofa\/defaulttype\/RigidTypes.h>\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace engine\n{\n\nSOFA_DECL_CLASS(ValuesFromIndices)\n\nint ValuesFromIndicesClass = core::RegisterObject(\"Find the values given a list of indices\")\n .add< ValuesFromIndices<std::string> >()\n .add< ValuesFromIndices<int> >()\n .add< ValuesFromIndices<unsigned int> >()\n .add< ValuesFromIndices< helper::fixed_array<unsigned int, 2> > >()\n .add< ValuesFromIndices< helper::fixed_array<unsigned int, 3> > >()\n .add< ValuesFromIndices< helper::fixed_array<unsigned int, 4> > >()\n .add< ValuesFromIndices< helper::fixed_array<unsigned int, 8> > >()\n#ifndef SOFA_FLOAT\n .add< ValuesFromIndices<double> >()\n .add< ValuesFromIndices<defaulttype::Vec2d> >()\n .add< ValuesFromIndices<defaulttype::Vec3d> >()\n\t\t.add< ValuesFromIndices<defaulttype::Vec4d> >()\n\t\t.add< ValuesFromIndices<defaulttype::Vec6d> >()\n .add< ValuesFromIndices<defaulttype::Rigid2dTypes::Coord> >()\n\/\/.add< ValuesFromIndices<defaulttype::Rigid2dTypes::Deriv> >() WARNING: removed because «duplicate instanciation» (changes on RigidDeriv)\n .add< ValuesFromIndices<defaulttype::Rigid3dTypes::Coord> >()\n .add< ValuesFromIndices<defaulttype::Rigid3dTypes::Deriv> >()\n#endif \/\/SOFA_FLOAT\n#ifndef SOFA_DOUBLE\n .add< ValuesFromIndices<float> >()\n .add< ValuesFromIndices<defaulttype::Vec2f> >()\n .add< ValuesFromIndices<defaulttype::Vec3f> >()\n\t\t.add< ValuesFromIndices<defaulttype::Vec4f> >()\n\t\t.add< ValuesFromIndices<defaulttype::Vec6f> >()\n .add< ValuesFromIndices<defaulttype::Rigid2fTypes::Coord> >()\n\/\/.add< ValuesFromIndices<defaulttype::Rigid2fTypes::Deriv> >() WARNING: removed because «duplicate instanciation» (changes on RigidDeriv)\n .add< ValuesFromIndices<defaulttype::Rigid3fTypes::Coord> >()\n .add< ValuesFromIndices<defaulttype::Rigid3fTypes::Deriv> >()\n#endif \/\/SOFA_DOUBLE\n ;\n\ntemplate class SOFA_ENGINE_API ValuesFromIndices<std::string>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<int>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<unsigned int>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices< helper::fixed_array<unsigned int, 2> >;\ntemplate class SOFA_ENGINE_API ValuesFromIndices< helper::fixed_array<unsigned int, 3> >;\ntemplate class SOFA_ENGINE_API ValuesFromIndices< helper::fixed_array<unsigned int, 4> >;\ntemplate class SOFA_ENGINE_API ValuesFromIndices< helper::fixed_array<unsigned int, 8> >;\n#ifndef SOFA_FLOAT\ntemplate class SOFA_ENGINE_API ValuesFromIndices<double>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec2d>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec3d>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec4d>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec6d>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid2dTypes::Coord>;\n\/\/template class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid2dTypes::Deriv>; WARNING: removed because «duplicate instanciation» (???)\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid3dTypes::Coord>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid3dTypes::Deriv>;\n#endif \/\/SOFA_FLOAT\n#ifndef SOFA_DOUBLE\ntemplate class SOFA_ENGINE_API ValuesFromIndices<float>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec2f>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec3f>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec4f>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec6f>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid2fTypes::Coord>;\n\/\/template class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid2fTypes::Deriv>; WARNING: removed because «duplicate instanciation» (???)\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid3fTypes::Coord>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid3fTypes::Deriv>;\n#endif \/\/SOFA_DOUBLE\n\n} \/\/ namespace constraint\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n<commit_msg>SofaEngine\/ValuesFromIndices: uncomment some instanciations<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#define SOFA_COMPONENT_ENGINE_VALUESFROMINDICES_CPP\n#include <SofaEngine\/ValuesFromIndices.inl>\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/defaulttype\/Vec3Types.h>\n#include <sofa\/defaulttype\/RigidTypes.h>\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace engine\n{\n\nSOFA_DECL_CLASS(ValuesFromIndices)\n\nint ValuesFromIndicesClass = core::RegisterObject(\"Find the values given a list of indices\")\n .add< ValuesFromIndices<std::string> >()\n .add< ValuesFromIndices<int> >()\n .add< ValuesFromIndices<unsigned int> >()\n .add< ValuesFromIndices< helper::fixed_array<unsigned int, 2> > >()\n .add< ValuesFromIndices< helper::fixed_array<unsigned int, 3> > >()\n .add< ValuesFromIndices< helper::fixed_array<unsigned int, 4> > >()\n .add< ValuesFromIndices< helper::fixed_array<unsigned int, 8> > >()\n#ifndef SOFA_FLOAT\n .add< ValuesFromIndices<double> >()\n .add< ValuesFromIndices<defaulttype::Vec2d> >()\n .add< ValuesFromIndices<defaulttype::Vec3d> >()\n\t\t.add< ValuesFromIndices<defaulttype::Vec4d> >()\n\t\t.add< ValuesFromIndices<defaulttype::Vec6d> >()\n .add< ValuesFromIndices<defaulttype::Rigid2dTypes::Coord> >()\n .add< ValuesFromIndices<defaulttype::Rigid2dTypes::Deriv> >()\n .add< ValuesFromIndices<defaulttype::Rigid3dTypes::Coord> >()\n .add< ValuesFromIndices<defaulttype::Rigid3dTypes::Deriv> >()\n#endif \/\/SOFA_FLOAT\n#ifndef SOFA_DOUBLE\n .add< ValuesFromIndices<float> >()\n .add< ValuesFromIndices<defaulttype::Vec2f> >()\n .add< ValuesFromIndices<defaulttype::Vec3f> >()\n\t\t.add< ValuesFromIndices<defaulttype::Vec4f> >()\n\t\t.add< ValuesFromIndices<defaulttype::Vec6f> >()\n .add< ValuesFromIndices<defaulttype::Rigid2fTypes::Coord> >()\n .add< ValuesFromIndices<defaulttype::Rigid2fTypes::Deriv> >()\n .add< ValuesFromIndices<defaulttype::Rigid3fTypes::Coord> >()\n .add< ValuesFromIndices<defaulttype::Rigid3fTypes::Deriv> >()\n#endif \/\/SOFA_DOUBLE\n ;\n\ntemplate class SOFA_ENGINE_API ValuesFromIndices<std::string>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<int>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<unsigned int>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices< helper::fixed_array<unsigned int, 2> >;\ntemplate class SOFA_ENGINE_API ValuesFromIndices< helper::fixed_array<unsigned int, 3> >;\ntemplate class SOFA_ENGINE_API ValuesFromIndices< helper::fixed_array<unsigned int, 4> >;\ntemplate class SOFA_ENGINE_API ValuesFromIndices< helper::fixed_array<unsigned int, 8> >;\n#ifndef SOFA_FLOAT\ntemplate class SOFA_ENGINE_API ValuesFromIndices<double>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec2d>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec3d>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec4d>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec6d>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid2dTypes::Coord>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid2dTypes::Deriv>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid3dTypes::Coord>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid3dTypes::Deriv>;\n#endif \/\/SOFA_FLOAT\n#ifndef SOFA_DOUBLE\ntemplate class SOFA_ENGINE_API ValuesFromIndices<float>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec2f>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec3f>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec4f>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Vec6f>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid2fTypes::Coord>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid2fTypes::Deriv>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid3fTypes::Coord>;\ntemplate class SOFA_ENGINE_API ValuesFromIndices<defaulttype::Rigid3fTypes::Deriv>;\n#endif \/\/SOFA_DOUBLE\n\n} \/\/ namespace constraint\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Framework *\n* *\n* Authors: The SOFA Team (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\n#include <SofaOpenglVisual\/OglColorMap.h>\n\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/core\/visual\/VisualParams.h>\n\n#ifdef SOFA_HAVE_GLEW\n#include <sofa\/helper\/gl\/GLSLShader.h>\n#endif \/\/ SOFA_HAVE_GLEW\n\n#include <string>\n#include <iostream>\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace visualmodel\n{\n\nSOFA_DECL_CLASS(OglColorMap)\n\nint OglColorMapClass = core::RegisterObject(\"Provides color palette and support for conversion of numbers to colors.\")\n .add< OglColorMap >()\n .addAlias(\"ColorMap\")\n ;\n\nOglColorMap::OglColorMap()\n: f_paletteSize(initData(&f_paletteSize, (unsigned int)256, \"paletteSize\", \"How many colors to use\"))\n, f_colorScheme(initData(&f_colorScheme, \"colorScheme\", \"Color scheme to use\"))\n, f_showLegend(initData(&f_showLegend, false, \"showLegend\", \"Activate rendering of color scale legend on the side\"))\n, f_legendOffset(initData(&f_legendOffset, defaulttype::Vec2f(10.0f,5.0f),\"legendOffset\", \"Draw the legend on screen with an x,y offset\"))\n, f_legendTitle(initData(&f_legendTitle,\"legendTitle\", \"Add a title to the legend\"))\n, d_min(initData(&d_min,0.0f,\"min\",\"min value for drawing the legend without the need to actually use the range with getEvaluator method wich sets the min\"))\n, d_max(initData(&d_max,0.0f,\"max\",\"max value for drawing the legend without the need to actually use the range with getEvaluator method wich sets the max\"))\n, d_legendRangeScale(initData(&d_legendRangeScale,1.f,\"legendRangeScale\",\"to change the unit of the min\/max value of the legend\"))\n, texture(0)\n{\n f_colorScheme.beginEdit()->setNames(19,\n \"Red to Blue\", \/\/ HSV space\n \"Blue to Red\", \/\/ HSV space\n \"HSV\", \/\/ HSV space\n \"Red\", \/\/ RGB space\n \"Green\", \/\/ RGB space\n \"Blue\", \/\/ RGB space\n\t\t\"Yellow to Cyan\",\/\/ HSV space\n\t\t\"Cyan to Yellow\",\/\/ HSV space\n\t\t\"Red to Yellow\",\/\/ RGB space\n\t\t\"Yellow to Red\",\/\/ RGB space\n\t\t\"Yellow to Green\",\/\/ RGB space\n\t\t\"Green to Yellow\",\/\/ RGB space\n\t\t\"Green to Cyan\",\/\/ RGB space\n\t\t\"Cyan to Green\",\/\/ RGB space\n\t\t\"Cyan to Blue\",\/\/ RGB space\n\t\t\"Blue to Cyan\",\/\/ RGB space\n\t\t\"BlueInv\",\/\/ HSV space\n\t\t\"GreenInv\",\/\/ HSV space\n\t\t\"RedInv\",\/\/ HSV space\n \"Custom\"\/\/ TODO: Custom colors\n );\n f_colorScheme.beginEdit()->setSelectedItem(\"HSV\");\n f_colorScheme.endEdit();\n\n}\n\nOglColorMap::~OglColorMap() {\n \/\/ Some components may use OglColorMap internally, in which case an OpenGL\n \/\/ context might not exist. That's why this 'if' is here, to avoid calling\n \/\/ an OpenGL function in a destructor unless strictly necessary.\n if (texture != 0)\n glDeleteTextures(1, &texture);\n}\n\n\/\/ For backward compatibility only\n\/\/ TODO: remove this later\n\/\/void OglColorMap::initOld(const std::string &data)\n\/\/{\n\/\/ if (data == \"\") {\n\/\/ entries.insert(entries.end(), DefaultOglColorMapEntries, DefaultOglColorMapEntries+NDefaultOglColorMapEntries);\n\/\/ return;\n\/\/ }\n\/\/\n\/\/ std::istringstream is(data);\n\/\/ is >> *this;\n\/\/\n\/\/ return;\n\/\/}\n\nvoid OglColorMap::init()\n{\n reinit();\n}\n\n\nvoid OglColorMap::reinit()\n{\n m_colorMap.setPaletteSize(f_paletteSize.getValue());\n m_colorMap.setColorScheme(f_colorScheme.getValue().getSelectedItem());\n m_colorMap.reinit();\n }\n\nOglColorMap* OglColorMap::getDefault()\n{\n static OglColorMap::SPtr defaultOglColorMap;\n if (defaultOglColorMap == NULL) {\n defaultOglColorMap = sofa::core::objectmodel::New< OglColorMap >();\n std::string tmp(\"\");\n \/\/defaultOglColorMap->initOld(tmp); \/\/ TODO: replace initOld() with init()\n defaultOglColorMap->init();\n }\n return defaultOglColorMap.get();\n}\n\nvoid OglColorMap::drawVisual(const core::visual::VisualParams* vparams)\n{\n if( !vparams->displayFlags().getShowVisual() ) return;\n\n if (!f_showLegend.getValue()) return;\n\n \/\/ Prepare texture for legend\n \/\/ crashes on mac in batch mode (no GL context)\n if (vparams->isSupported(core::visual::API_OpenGL)\n && !texture)\n {\n glGenTextures(1, &texture);\n glBindTexture(GL_TEXTURE_1D, texture);\n \/\/glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n \/\/glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\n int width = getNbColors();\n unsigned char *data = new unsigned char[ width * 3 ];\n\n for (int i=0; i<width; i++) {\n Color c = getColor(i);\n data[i*3+0] = (unsigned char)(c[0]*255);\n data[i*3+1] = (unsigned char)(c[1]*255);\n data[i*3+2] = (unsigned char)(c[2]*255);\n }\n\n glBindTexture(GL_TEXTURE_1D, texture);\n\n glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, width, 0, GL_RGB, GL_UNSIGNED_BYTE,\n data);\n\n delete[] data;\n }\n\n\n\n \/\/\n \/\/ Draw legend\n \/\/\n \/\/ TODO: move the code to DrawTool\n\n\n const std::string& legendTitle = f_legendTitle.getValue();\n int yoffset = legendTitle.empty() ? 0 : 25;\n\n\n GLint viewport[4];\n glGetIntegerv(GL_VIEWPORT,viewport);\n const int vWidth = viewport[2];\n const int vHeight = viewport[3];\n\n glPushAttrib(GL_ENABLE_BIT);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_LIGHTING);\n glDisable(GL_BLEND);\n\n \/\/ disable clipping planes\n\tfor(int i = 0; i < GL_MAX_CLIP_PLANES; ++i)\n\t\tglDisable(GL_CLIP_PLANE0+i);\n\n \/\/ Setup orthogonal projection\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n glOrtho(0.0, vWidth, vHeight, 0.0, -1.0, 1.0);\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n#ifdef SOFA_HAVE_GLEW\n for(int i = 0; i < 8; ++i)\n {\n glActiveTexture(GL_TEXTURE0 + i);\n glDisable(GL_TEXTURE_2D);\n }\n\n glActiveTexture(GL_TEXTURE0);\n glEnable(GL_TEXTURE_1D);\n glBindTexture(GL_TEXTURE_1D, texture);\n\n \/\/glBlendFunc(GL_ONE, GL_ONE);\n glColor3f(1.0f, 1.0f, 1.0f);\n\n GLhandleARB currentShader = sofa::helper::gl::GLSLShader::GetActiveShaderProgram();\n sofa::helper::gl::GLSLShader::SetActiveShaderProgram(0);\n#endif \/\/ SOFA_HAVE_GLEW\n\n glBegin(GL_QUADS);\n\n glTexCoord1f(1.0);\n glVertex3f(20.0f+f_legendOffset.getValue().x(), yoffset+20.0f+f_legendOffset.getValue().y(), 0.0f);\n\n glTexCoord1f(1.0);\n glVertex3f(10.0f+f_legendOffset.getValue().x(), yoffset+20.0f+f_legendOffset.getValue().y(), 0.0f);\n\n glTexCoord1f(0.0);\n glVertex3f(10.0f+f_legendOffset.getValue().x(), yoffset+120.0f+f_legendOffset.getValue().y(), 0.0f);\n\n glTexCoord1f(0.0);\n glVertex3f(20.0f+f_legendOffset.getValue().x(), yoffset+120.0f+f_legendOffset.getValue().y(), 0.0f);\n\n glEnd();\n\n glDisable(GL_TEXTURE_1D);\n\n \/\/ Restore projection matrix\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n\n \/\/ Restore model view matrix\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n\n \/\/ Maximum & minimum\n std::ostringstream smin, smax;\n smin << d_min.getValue() * d_legendRangeScale.getValue();\n smax << d_max.getValue() * d_legendRangeScale.getValue();\n\n \/\/ Adjust the text color according to the background luminance\n GLfloat bgcol[4];\n glGetFloatv(GL_COLOR_CLEAR_VALUE,bgcol);\n\n Color textcolor(1.0f, 1.0f, 1.0f, 1.0f);\n sofa::defaulttype::Vec3f luminanceMatrix(0.212f, 0.715f, 0.072f);\n float backgroundLuminance = sofa::defaulttype::Vec3f(bgcol[0], bgcol[1], bgcol[2]) * luminanceMatrix;\n if(backgroundLuminance > 0.5f)\n textcolor = Color(0.0f, 0.0f, 0.0f, 1.0f);\n\n if( !legendTitle.empty() )\n {\n vparams->drawTool()->writeOverlayText((int)f_legendOffset.getValue().x(), \/\/ x\n (int)f_legendOffset.getValue().y(), \/\/ y\n 11u, \/\/ size\n textcolor,\n legendTitle.c_str());\n }\n\n\n\n vparams->drawTool()->writeOverlayText((int)f_legendOffset.getValue().x(), \/\/ x\n yoffset + (int)f_legendOffset.getValue().y(), \/\/ y\n 12u, \/\/ size\n textcolor,\n smax.str().c_str());\n\n vparams->drawTool()->writeOverlayText((int)f_legendOffset.getValue().x(), \/\/ x\n yoffset + 120 + (int)f_legendOffset.getValue().y(), \/\/ y\n 12u, \/\/ size\n textcolor,\n smin.str().c_str());\n\n#ifdef SOFA_HAVE_GLEW\n sofa::helper::gl::GLSLShader::SetActiveShaderProgram(currentShader);\n#endif \/\/ SOFA_HAVE_GLEW\n\n \/\/ Restore state\n glPopAttrib();\n}\n\n\n} \/\/ namespace visualmodel\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n<commit_msg>[SofaOpenglVisual] fixing OglColorMap<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Framework *\n* *\n* Authors: The SOFA Team (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\n#include <SofaOpenglVisual\/OglColorMap.h>\n\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/core\/visual\/VisualParams.h>\n\n#ifdef SOFA_HAVE_GLEW\n#include <sofa\/helper\/gl\/GLSLShader.h>\n#endif \/\/ SOFA_HAVE_GLEW\n\n#include <string>\n#include <iostream>\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace visualmodel\n{\n\nSOFA_DECL_CLASS(OglColorMap)\n\nint OglColorMapClass = core::RegisterObject(\"Provides color palette and support for conversion of numbers to colors.\")\n .add< OglColorMap >()\n .addAlias(\"ColorMap\")\n ;\n\nOglColorMap::OglColorMap()\n: f_paletteSize(initData(&f_paletteSize, (unsigned int)256, \"paletteSize\", \"How many colors to use\"))\n, f_colorScheme(initData(&f_colorScheme, \"colorScheme\", \"Color scheme to use\"))\n, f_showLegend(initData(&f_showLegend, false, \"showLegend\", \"Activate rendering of color scale legend on the side\"))\n, f_legendOffset(initData(&f_legendOffset, defaulttype::Vec2f(10.0f,5.0f),\"legendOffset\", \"Draw the legend on screen with an x,y offset\"))\n, f_legendTitle(initData(&f_legendTitle,\"legendTitle\", \"Add a title to the legend\"))\n, d_min(initData(&d_min,0.0f,\"min\",\"min value for drawing the legend without the need to actually use the range with getEvaluator method wich sets the min\"))\n, d_max(initData(&d_max,0.0f,\"max\",\"max value for drawing the legend without the need to actually use the range with getEvaluator method wich sets the max\"))\n, d_legendRangeScale(initData(&d_legendRangeScale,1.f,\"legendRangeScale\",\"to change the unit of the min\/max value of the legend\"))\n, texture(0)\n{\n f_colorScheme.beginEdit()->setNames(19,\n \"Red to Blue\", \/\/ HSV space\n \"Blue to Red\", \/\/ HSV space\n \"HSV\", \/\/ HSV space\n \"Red\", \/\/ RGB space\n \"Green\", \/\/ RGB space\n \"Blue\", \/\/ RGB space\n\t\t\"Yellow to Cyan\",\/\/ HSV space\n\t\t\"Cyan to Yellow\",\/\/ HSV space\n\t\t\"Red to Yellow\",\/\/ RGB space\n\t\t\"Yellow to Red\",\/\/ RGB space\n\t\t\"Yellow to Green\",\/\/ RGB space\n\t\t\"Green to Yellow\",\/\/ RGB space\n\t\t\"Green to Cyan\",\/\/ RGB space\n\t\t\"Cyan to Green\",\/\/ RGB space\n\t\t\"Cyan to Blue\",\/\/ RGB space\n\t\t\"Blue to Cyan\",\/\/ RGB space\n\t\t\"BlueInv\",\/\/ HSV space\n\t\t\"GreenInv\",\/\/ HSV space\n\t\t\"RedInv\",\/\/ HSV space\n \"Custom\"\/\/ TODO: Custom colors\n );\n f_colorScheme.beginEdit()->setSelectedItem(\"HSV\");\n f_colorScheme.endEdit();\n\n}\n\nOglColorMap::~OglColorMap() {\n \/\/ Some components may use OglColorMap internally, in which case an OpenGL\n \/\/ context might not exist. That's why this 'if' is here, to avoid calling\n \/\/ an OpenGL function in a destructor unless strictly necessary.\n if (texture != 0)\n glDeleteTextures(1, &texture);\n}\n\n\/\/ For backward compatibility only\n\/\/ TODO: remove this later\n\/\/void OglColorMap::initOld(const std::string &data)\n\/\/{\n\/\/ if (data == \"\") {\n\/\/ entries.insert(entries.end(), DefaultOglColorMapEntries, DefaultOglColorMapEntries+NDefaultOglColorMapEntries);\n\/\/ return;\n\/\/ }\n\/\/\n\/\/ std::istringstream is(data);\n\/\/ is >> *this;\n\/\/\n\/\/ return;\n\/\/}\n\nvoid OglColorMap::init()\n{\n reinit();\n}\n\n\nvoid OglColorMap::reinit()\n{\n m_colorMap.setPaletteSize(f_paletteSize.getValue());\n m_colorMap.setColorScheme(f_colorScheme.getValue().getSelectedItem());\n m_colorMap.reinit();\n }\n\nOglColorMap* OglColorMap::getDefault()\n{\n static OglColorMap::SPtr defaultOglColorMap;\n if (defaultOglColorMap == NULL) {\n defaultOglColorMap = sofa::core::objectmodel::New< OglColorMap >();\n std::string tmp(\"\");\n \/\/defaultOglColorMap->initOld(tmp); \/\/ TODO: replace initOld() with init()\n defaultOglColorMap->init();\n }\n return defaultOglColorMap.get();\n}\n\nvoid OglColorMap::drawVisual(const core::visual::VisualParams* vparams)\n{\n if( !vparams->displayFlags().getShowVisual() ) return;\n\n if (!f_showLegend.getValue()) return;\n\n \/\/ Prepare texture for legend\n \/\/ crashes on mac in batch mode (no GL context)\n if (vparams->isSupported(core::visual::API_OpenGL)\n && !texture)\n {\n glGenTextures(1, &texture);\n glBindTexture(GL_TEXTURE_1D, texture);\n \/\/glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n \/\/glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\n int width = getNbColors();\n unsigned char *data = new unsigned char[ width * 3 ];\n\n for (int i=0; i<width; i++) {\n Color c = getColor(i);\n data[i*3+0] = (unsigned char)(c[0]*255);\n data[i*3+1] = (unsigned char)(c[1]*255);\n data[i*3+2] = (unsigned char)(c[2]*255);\n }\n\n glBindTexture(GL_TEXTURE_1D, texture);\n\n glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, width, 0, GL_RGB, GL_UNSIGNED_BYTE,\n data);\n\n delete[] data;\n }\n\n\n\n \/\/\n \/\/ Draw legend\n \/\/\n \/\/ TODO: move the code to DrawTool\n\n\n const std::string& legendTitle = f_legendTitle.getValue();\n int yoffset = legendTitle.empty() ? 0 : 25;\n\n\n GLint viewport[4];\n glGetIntegerv(GL_VIEWPORT,viewport);\n const int vWidth = viewport[2];\n const int vHeight = viewport[3];\n\n glPushAttrib(GL_ENABLE_BIT);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_LIGHTING);\n glDisable(GL_BLEND);\n\n \/\/ disable clipping planes\n\tfor(int i = 0; i < GL_MAX_CLIP_PLANES; ++i)\n\t\tglDisable(GL_CLIP_PLANE0+i);\n\n \/\/ Setup orthogonal projection\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n glOrtho(0.0, vWidth, vHeight, 0.0, -1.0, 1.0);\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n#ifdef SOFA_HAVE_GLEW\n for(int i = 0; i < 8; ++i)\n {\n glActiveTexture(GL_TEXTURE0 + i);\n glDisable(GL_TEXTURE_2D);\n }\n\n glActiveTexture(GL_TEXTURE0);\n glEnable(GL_TEXTURE_1D);\n glBindTexture(GL_TEXTURE_1D, texture);\n\n \/\/glBlendFunc(GL_ONE, GL_ONE);\n glColor3f(1.0f, 1.0f, 1.0f);\n\n GLhandleARB currentShader = sofa::helper::gl::GLSLShader::GetActiveShaderProgram();\n sofa::helper::gl::GLSLShader::SetActiveShaderProgram(0);\n#endif \/\/ SOFA_HAVE_GLEW\n\n glBegin(GL_QUADS);\n\n glTexCoord1f(1.0);\n glVertex3f(20.0f+f_legendOffset.getValue().x(), yoffset+20.0f+f_legendOffset.getValue().y(), 0.0f);\n\n glTexCoord1f(1.0);\n glVertex3f(10.0f+f_legendOffset.getValue().x(), yoffset+20.0f+f_legendOffset.getValue().y(), 0.0f);\n\n glTexCoord1f(0.0);\n glVertex3f(10.0f+f_legendOffset.getValue().x(), yoffset+120.0f+f_legendOffset.getValue().y(), 0.0f);\n\n glTexCoord1f(0.0);\n glVertex3f(20.0f+f_legendOffset.getValue().x(), yoffset+120.0f+f_legendOffset.getValue().y(), 0.0f);\n\n glEnd();\n\n glDisable(GL_TEXTURE_1D);\n\n \/\/ Restore model view matrix\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n\n \/\/ Restore projection matrix\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n\n\n \/\/ Maximum & minimum\n std::ostringstream smin, smax;\n smin << d_min.getValue() * d_legendRangeScale.getValue();\n smax << d_max.getValue() * d_legendRangeScale.getValue();\n\n \/\/ Adjust the text color according to the background luminance\n GLfloat bgcol[4];\n glGetFloatv(GL_COLOR_CLEAR_VALUE,bgcol);\n\n Color textcolor(1.0f, 1.0f, 1.0f, 1.0f);\n sofa::defaulttype::Vec3f luminanceMatrix(0.212f, 0.715f, 0.072f);\n float backgroundLuminance = sofa::defaulttype::Vec3f(bgcol[0], bgcol[1], bgcol[2]) * luminanceMatrix;\n if(backgroundLuminance > 0.5f)\n textcolor = Color(0.0f, 0.0f, 0.0f, 1.0f);\n\n if( !legendTitle.empty() )\n {\n vparams->drawTool()->writeOverlayText((int)f_legendOffset.getValue().x(), \/\/ x\n (int)f_legendOffset.getValue().y(), \/\/ y\n 11u, \/\/ size\n textcolor,\n legendTitle.c_str());\n }\n\n\n\n vparams->drawTool()->writeOverlayText((int)f_legendOffset.getValue().x(), \/\/ x\n yoffset + (int)f_legendOffset.getValue().y(), \/\/ y\n 12u, \/\/ size\n textcolor,\n smax.str().c_str());\n\n vparams->drawTool()->writeOverlayText((int)f_legendOffset.getValue().x(), \/\/ x\n yoffset + 120 + (int)f_legendOffset.getValue().y(), \/\/ y\n 12u, \/\/ size\n textcolor,\n smin.str().c_str());\n\n#ifdef SOFA_HAVE_GLEW\n sofa::helper::gl::GLSLShader::SetActiveShaderProgram(currentShader);\n#endif \/\/ SOFA_HAVE_GLEW\n\n \/\/ Restore state\n glPopAttrib();\n}\n\n\n} \/\/ namespace visualmodel\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n<|endoftext|>"} {"text":"<commit_before>\/\/! Copyright (c) 2013 ASMlover. 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 ofconditions and the following disclaimer.\n\/\/!\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 materialsprovided with the\n\/\/! distribution.\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 HOLDER 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#include <stdio.h>\n\n\nint \nmain(int argc, char* argv[])\n{\n return 0;\n}\n<commit_msg>add test for AppendFile in windows platform<commit_after>\/\/! Copyright (c) 2013 ASMlover. 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 ofconditions and the following disclaimer.\n\/\/!\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 materialsprovided with the\n\/\/! distribution.\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 HOLDER 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#include <stdio.h>\n#include <string.h>\n#include \"append_file.h\"\n\n\n#define LOOP_TIMES (100000)\n\n\nint \nmain(int argc, char* argv[])\n{\n char* s = \"Hello, world! This is AppendFile testing ...\\n\";\n size_t n = strlen(s);\n DWORD beg, end;\n int counter;\n\n FILE* fp = fopen(\"test1.txt\", \"a+\");\n counter = 0;\n beg = GetTickCount();\n while (counter++ < LOOP_TIMES) \n _fwrite_nolock(s, sizeof(char), n, fp);\n end = GetTickCount();\n fprintf(stdout, \"stream io used: %lu\\n\", end - beg);\n fclose(fp);\n\n\n AppendFile f;\n f.Open(\"test2.txt\");\n counter = 0;\n beg = GetTickCount();\n while (counter++ < LOOP_TIMES) \n f.Write(s, n);\n end = GetTickCount();\n fprintf(stdout, \"AppendFile used: %lu\\n\", end - beg);\n f.Close();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>rework to begin supporting #else and #elif<commit_after><|endoftext|>"} {"text":"<commit_before>\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2013, OpenCV Foundation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"test_precomp.hpp\"\n#include \"npy_blob.hpp\"\n#include <opencv2\/dnn\/shape_utils.hpp>\n\nnamespace opencv_test\n{\n\nusing namespace std;\nusing namespace testing;\nusing namespace cv;\nusing namespace cv::dnn;\n\ntemplate<typename TStr>\nstatic std::string _tf(TStr filename, bool inTorchDir = true)\n{\n String path = \"dnn\/\";\n if (inTorchDir)\n path += \"torch\/\";\n path += filename;\n return findDataFile(path, false);\n}\n\nTEST(Torch_Importer, simple_read)\n{\n Net net;\n ASSERT_NO_THROW(net = readNetFromTorch(_tf(\"net_simple_net.txt\"), false));\n ASSERT_FALSE(net.empty());\n}\n\nstatic void runTorchNet(String prefix, int targetId = DNN_TARGET_CPU, String outLayerName = \"\",\n bool check2ndBlob = false, bool isBinary = false)\n{\n String suffix = (isBinary) ? \".dat\" : \".txt\";\n\n Net net = readNetFromTorch(_tf(prefix + \"_net\" + suffix), isBinary);\n ASSERT_FALSE(net.empty());\n\n net.setPreferableBackend(DNN_BACKEND_DEFAULT);\n net.setPreferableTarget(targetId);\n\n Mat inp, outRef;\n ASSERT_NO_THROW( inp = readTorchBlob(_tf(prefix + \"_input\" + suffix), isBinary) );\n ASSERT_NO_THROW( outRef = readTorchBlob(_tf(prefix + \"_output\" + suffix), isBinary) );\n\n if (outLayerName.empty())\n outLayerName = net.getLayerNames().back();\n\n net.setInput(inp, \"0\");\n std::vector<Mat> outBlobs;\n net.forward(outBlobs, outLayerName);\n normAssert(outRef, outBlobs[0]);\n\n if (check2ndBlob)\n {\n Mat out2 = outBlobs[1];\n Mat ref2 = readTorchBlob(_tf(prefix + \"_output_2\" + suffix), isBinary);\n normAssert(out2, ref2);\n }\n}\n\ntypedef testing::TestWithParam<DNNTarget> Test_Torch_layers;\n\nTEST_P(Test_Torch_layers, run_convolution)\n{\n runTorchNet(\"net_conv\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, run_pool_max)\n{\n runTorchNet(\"net_pool_max\", GetParam(), \"\", true);\n}\n\nTEST_P(Test_Torch_layers, run_pool_ave)\n{\n runTorchNet(\"net_pool_ave\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, run_reshape)\n{\n int targetId = GetParam();\n runTorchNet(\"net_reshape\", targetId);\n runTorchNet(\"net_reshape_batch\", targetId);\n runTorchNet(\"net_reshape_single_sample\", targetId);\n runTorchNet(\"net_reshape_channels\", targetId, \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, run_linear)\n{\n runTorchNet(\"net_linear_2d\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, run_concat)\n{\n int targetId = GetParam();\n runTorchNet(\"net_concat\", targetId, \"l5_torchMerge\");\n runTorchNet(\"net_depth_concat\", targetId, \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, run_deconv)\n{\n runTorchNet(\"net_deconv\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, run_batch_norm)\n{\n runTorchNet(\"net_batch_norm\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_prelu)\n{\n runTorchNet(\"net_prelu\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, net_cadd_table)\n{\n runTorchNet(\"net_cadd_table\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, net_softmax)\n{\n int targetId = GetParam();\n runTorchNet(\"net_softmax\", targetId);\n runTorchNet(\"net_softmax_spatial\", targetId);\n}\n\nTEST_P(Test_Torch_layers, net_logsoftmax)\n{\n runTorchNet(\"net_logsoftmax\");\n runTorchNet(\"net_logsoftmax_spatial\");\n}\n\nTEST_P(Test_Torch_layers, net_lp_pooling)\n{\n int targetId = GetParam();\n runTorchNet(\"net_lp_pooling_square\", targetId, \"\", false, true);\n runTorchNet(\"net_lp_pooling_power\", targetId, \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_conv_gemm_lrn)\n{\n runTorchNet(\"net_conv_gemm_lrn\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_inception_block)\n{\n runTorchNet(\"net_inception_block\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_normalize)\n{\n runTorchNet(\"net_normalize\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_padding)\n{\n int targetId = GetParam();\n runTorchNet(\"net_padding\", targetId, \"\", false, true);\n runTorchNet(\"net_spatial_zero_padding\", targetId, \"\", false, true);\n runTorchNet(\"net_spatial_reflection_padding\", targetId, \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_non_spatial)\n{\n runTorchNet(\"net_non_spatial\", GetParam(), \"\", false, true);\n}\n\nINSTANTIATE_TEST_CASE_P(\/**\/, Test_Torch_layers, availableDnnTargets());\n\ntypedef testing::TestWithParam<DNNTarget> Test_Torch_nets;\n\nTEST_P(Test_Torch_nets, OpenFace_accuracy)\n{\n const string model = findDataFile(\"dnn\/openface_nn4.small2.v1.t7\", false);\n Net net = readNetFromTorch(model);\n\n net.setPreferableTarget(GetParam());\n\n Mat sample = imread(findDataFile(\"cv\/shared\/lena.png\", false));\n Mat sampleF32(sample.size(), CV_32FC3);\n sample.convertTo(sampleF32, sampleF32.type());\n sampleF32 \/= 255;\n resize(sampleF32, sampleF32, Size(96, 96), 0, 0, INTER_NEAREST);\n\n Mat inputBlob = blobFromImage(sampleF32);\n\n net.setInput(inputBlob);\n Mat out = net.forward();\n\n Mat outRef = readTorchBlob(_tf(\"net_openface_output.dat\"), true);\n normAssert(out, outRef);\n}\n\nTEST_P(Test_Torch_nets, ENet_accuracy)\n{\n Net net;\n {\n const string model = findDataFile(\"dnn\/Enet-model-best.net\", false);\n net = readNetFromTorch(model, true);\n ASSERT_TRUE(!net.empty());\n }\n\n net.setPreferableTarget(GetParam());\n\n Mat sample = imread(_tf(\"street.png\", false));\n Mat inputBlob = blobFromImage(sample, 1.\/255);\n\n net.setInput(inputBlob, \"\");\n Mat out = net.forward();\n Mat ref = blobFromNPY(_tf(\"torch_enet_prob.npy\", false));\n \/\/ Due to numerical instability in Pooling-Unpooling layers (indexes jittering)\n \/\/ thresholds for ENet must be changed. Accuracy of resuults was checked on\n \/\/ Cityscapes dataset and difference in mIOU with Torch is 10E-4%\n normAssert(ref, out, \"\", 0.00044, 0.44);\n\n const int N = 3;\n for (int i = 0; i < N; i++)\n {\n net.setInput(inputBlob, \"\");\n Mat out = net.forward();\n normAssert(ref, out, \"\", 0.00044, 0.44);\n }\n}\n\n\/\/ Check accuracy of style transfer models from https:\/\/github.com\/jcjohnson\/fast-neural-style\n\/\/ th fast_neural_style.lua \\\n\/\/ -input_image ~\/opencv_extra\/testdata\/dnn\/googlenet_1.png \\\n\/\/ -output_image lena.png \\\n\/\/ -median_filter 0 \\\n\/\/ -image_size 0 \\\n\/\/ -model models\/eccv16\/starry_night.t7\n\/\/ th fast_neural_style.lua \\\n\/\/ -input_image ~\/opencv_extra\/testdata\/dnn\/googlenet_1.png \\\n\/\/ -output_image lena.png \\\n\/\/ -median_filter 0 \\\n\/\/ -image_size 0 \\\n\/\/ -model models\/instance_norm\/feathers.t7\nTEST_P(Test_Torch_nets, FastNeuralStyle_accuracy)\n{\n std::string models[] = {\"dnn\/fast_neural_style_eccv16_starry_night.t7\",\n \"dnn\/fast_neural_style_instance_norm_feathers.t7\"};\n std::string targets[] = {\"dnn\/lena_starry_night.png\", \"dnn\/lena_feathers.png\"};\n\n for (int i = 0; i < 2; ++i)\n {\n const string model = findDataFile(models[i], false);\n Net net = readNetFromTorch(model);\n\n net.setPreferableTarget(GetParam());\n\n Mat img = imread(findDataFile(\"dnn\/googlenet_1.png\", false));\n Mat inputBlob = blobFromImage(img, 1.0, Size(), Scalar(103.939, 116.779, 123.68), false);\n\n net.setInput(inputBlob);\n Mat out = net.forward();\n\n \/\/ Deprocessing.\n getPlane(out, 0, 0) += 103.939;\n getPlane(out, 0, 1) += 116.779;\n getPlane(out, 0, 2) += 123.68;\n out = cv::min(cv::max(0, out), 255);\n\n Mat ref = imread(findDataFile(targets[i]));\n Mat refBlob = blobFromImage(ref, 1.0, Size(), Scalar(), false);\n\n normAssert(out, refBlob, \"\", 0.5, 1.1);\n }\n}\n\nINSTANTIATE_TEST_CASE_P(\/**\/, Test_Torch_nets, availableDnnTargets());\n\n\/\/ TODO: fix OpenCL and add to the rest of tests\nTEST(Torch_Importer, run_paralel)\n{\n runTorchNet(\"net_parallel\", DNN_TARGET_CPU, \"l5_torchMerge\");\n}\n\nTEST(Torch_Importer, DISABLED_run_paralel)\n{\n runTorchNet(\"net_parallel\", DNN_TARGET_OPENCL, \"l5_torchMerge\");\n}\n\n}\n<commit_msg>Update Torch testdata<commit_after>\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2013, OpenCV Foundation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"test_precomp.hpp\"\n#include \"npy_blob.hpp\"\n#include <opencv2\/dnn\/shape_utils.hpp>\n\nnamespace opencv_test\n{\n\nusing namespace std;\nusing namespace testing;\nusing namespace cv;\nusing namespace cv::dnn;\n\ntemplate<typename TStr>\nstatic std::string _tf(TStr filename, bool inTorchDir = true)\n{\n String path = \"dnn\/\";\n if (inTorchDir)\n path += \"torch\/\";\n path += filename;\n return findDataFile(path, false);\n}\n\nTEST(Torch_Importer, simple_read)\n{\n Net net;\n ASSERT_NO_THROW(net = readNetFromTorch(_tf(\"net_simple_net.txt\"), false));\n ASSERT_FALSE(net.empty());\n}\n\nstatic void runTorchNet(String prefix, int targetId = DNN_TARGET_CPU, String outLayerName = \"\",\n bool check2ndBlob = false, bool isBinary = false)\n{\n String suffix = (isBinary) ? \".dat\" : \".txt\";\n\n Net net = readNetFromTorch(_tf(prefix + \"_net\" + suffix), isBinary);\n ASSERT_FALSE(net.empty());\n\n net.setPreferableBackend(DNN_BACKEND_DEFAULT);\n net.setPreferableTarget(targetId);\n\n Mat inp, outRef;\n ASSERT_NO_THROW( inp = readTorchBlob(_tf(prefix + \"_input\" + suffix), isBinary) );\n ASSERT_NO_THROW( outRef = readTorchBlob(_tf(prefix + \"_output\" + suffix), isBinary) );\n\n if (outLayerName.empty())\n outLayerName = net.getLayerNames().back();\n\n net.setInput(inp, \"0\");\n std::vector<Mat> outBlobs;\n net.forward(outBlobs, outLayerName);\n normAssert(outRef, outBlobs[0]);\n\n if (check2ndBlob)\n {\n Mat out2 = outBlobs[1];\n Mat ref2 = readTorchBlob(_tf(prefix + \"_output_2\" + suffix), isBinary);\n normAssert(out2, ref2);\n }\n}\n\ntypedef testing::TestWithParam<DNNTarget> Test_Torch_layers;\n\nTEST_P(Test_Torch_layers, run_convolution)\n{\n runTorchNet(\"net_conv\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, run_pool_max)\n{\n runTorchNet(\"net_pool_max\", GetParam(), \"\", true);\n}\n\nTEST_P(Test_Torch_layers, run_pool_ave)\n{\n runTorchNet(\"net_pool_ave\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, run_reshape)\n{\n int targetId = GetParam();\n runTorchNet(\"net_reshape\", targetId);\n runTorchNet(\"net_reshape_batch\", targetId);\n runTorchNet(\"net_reshape_single_sample\", targetId);\n runTorchNet(\"net_reshape_channels\", targetId, \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, run_linear)\n{\n runTorchNet(\"net_linear_2d\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, run_concat)\n{\n int targetId = GetParam();\n runTorchNet(\"net_concat\", targetId, \"l5_torchMerge\");\n runTorchNet(\"net_depth_concat\", targetId, \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, run_deconv)\n{\n runTorchNet(\"net_deconv\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, run_batch_norm)\n{\n runTorchNet(\"net_batch_norm\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_prelu)\n{\n runTorchNet(\"net_prelu\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, net_cadd_table)\n{\n runTorchNet(\"net_cadd_table\", GetParam());\n}\n\nTEST_P(Test_Torch_layers, net_softmax)\n{\n int targetId = GetParam();\n runTorchNet(\"net_softmax\", targetId);\n runTorchNet(\"net_softmax_spatial\", targetId);\n}\n\nTEST_P(Test_Torch_layers, net_logsoftmax)\n{\n runTorchNet(\"net_logsoftmax\");\n runTorchNet(\"net_logsoftmax_spatial\");\n}\n\nTEST_P(Test_Torch_layers, net_lp_pooling)\n{\n int targetId = GetParam();\n runTorchNet(\"net_lp_pooling_square\", targetId, \"\", false, true);\n runTorchNet(\"net_lp_pooling_power\", targetId, \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_conv_gemm_lrn)\n{\n runTorchNet(\"net_conv_gemm_lrn\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_inception_block)\n{\n runTorchNet(\"net_inception_block\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_normalize)\n{\n runTorchNet(\"net_normalize\", GetParam(), \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_padding)\n{\n int targetId = GetParam();\n runTorchNet(\"net_padding\", targetId, \"\", false, true);\n runTorchNet(\"net_spatial_zero_padding\", targetId, \"\", false, true);\n runTorchNet(\"net_spatial_reflection_padding\", targetId, \"\", false, true);\n}\n\nTEST_P(Test_Torch_layers, net_non_spatial)\n{\n runTorchNet(\"net_non_spatial\", GetParam(), \"\", false, true);\n}\n\nINSTANTIATE_TEST_CASE_P(\/**\/, Test_Torch_layers, availableDnnTargets());\n\ntypedef testing::TestWithParam<DNNTarget> Test_Torch_nets;\n\nTEST_P(Test_Torch_nets, OpenFace_accuracy)\n{\n const string model = findDataFile(\"dnn\/openface_nn4.small2.v1.t7\", false);\n Net net = readNetFromTorch(model);\n\n net.setPreferableTarget(GetParam());\n\n Mat sample = imread(findDataFile(\"cv\/shared\/lena.png\", false));\n Mat sampleF32(sample.size(), CV_32FC3);\n sample.convertTo(sampleF32, sampleF32.type());\n sampleF32 \/= 255;\n resize(sampleF32, sampleF32, Size(96, 96), 0, 0, INTER_NEAREST);\n\n Mat inputBlob = blobFromImage(sampleF32);\n\n net.setInput(inputBlob);\n Mat out = net.forward();\n\n Mat outRef = readTorchBlob(_tf(\"net_openface_output.dat\"), true);\n normAssert(out, outRef);\n}\n\nTEST_P(Test_Torch_nets, ENet_accuracy)\n{\n Net net;\n {\n const string model = findDataFile(\"dnn\/Enet-model-best.net\", false);\n net = readNetFromTorch(model, true);\n ASSERT_TRUE(!net.empty());\n }\n\n net.setPreferableTarget(GetParam());\n\n Mat sample = imread(_tf(\"street.png\", false));\n Mat inputBlob = blobFromImage(sample, 1.\/255);\n\n net.setInput(inputBlob, \"\");\n Mat out = net.forward();\n Mat ref = blobFromNPY(_tf(\"torch_enet_prob.npy\", false));\n \/\/ Due to numerical instability in Pooling-Unpooling layers (indexes jittering)\n \/\/ thresholds for ENet must be changed. Accuracy of resuults was checked on\n \/\/ Cityscapes dataset and difference in mIOU with Torch is 10E-4%\n normAssert(ref, out, \"\", 0.00044, 0.44);\n\n const int N = 3;\n for (int i = 0; i < N; i++)\n {\n net.setInput(inputBlob, \"\");\n Mat out = net.forward();\n normAssert(ref, out, \"\", 0.00044, 0.44);\n }\n}\n\n\/\/ Check accuracy of style transfer models from https:\/\/github.com\/jcjohnson\/fast-neural-style\n\/\/ th fast_neural_style.lua \\\n\/\/ -input_image ~\/opencv_extra\/testdata\/dnn\/googlenet_1.png \\\n\/\/ -output_image lena.png \\\n\/\/ -median_filter 0 \\\n\/\/ -image_size 0 \\\n\/\/ -model models\/eccv16\/starry_night.t7\n\/\/ th fast_neural_style.lua \\\n\/\/ -input_image ~\/opencv_extra\/testdata\/dnn\/googlenet_1.png \\\n\/\/ -output_image lena.png \\\n\/\/ -median_filter 0 \\\n\/\/ -image_size 0 \\\n\/\/ -model models\/instance_norm\/feathers.t7\nTEST_P(Test_Torch_nets, FastNeuralStyle_accuracy)\n{\n std::string models[] = {\"dnn\/fast_neural_style_eccv16_starry_night.t7\",\n \"dnn\/fast_neural_style_instance_norm_feathers.t7\"};\n std::string targets[] = {\"dnn\/lena_starry_night.png\", \"dnn\/lena_feathers.png\"};\n\n for (int i = 0; i < 2; ++i)\n {\n const string model = findDataFile(models[i], false);\n Net net = readNetFromTorch(model);\n\n net.setPreferableTarget(GetParam());\n\n Mat img = imread(findDataFile(\"dnn\/googlenet_1.png\", false));\n Mat inputBlob = blobFromImage(img, 1.0, Size(), Scalar(103.939, 116.779, 123.68), false);\n\n net.setInput(inputBlob);\n Mat out = net.forward();\n\n \/\/ Deprocessing.\n getPlane(out, 0, 0) += 103.939;\n getPlane(out, 0, 1) += 116.779;\n getPlane(out, 0, 2) += 123.68;\n out = cv::min(cv::max(0, out), 255);\n\n Mat ref = imread(findDataFile(targets[i]));\n Mat refBlob = blobFromImage(ref, 1.0, Size(), Scalar(), false);\n\n normAssert(out, refBlob, \"\", 0.5, 1.1);\n }\n}\n\nINSTANTIATE_TEST_CASE_P(\/**\/, Test_Torch_nets, availableDnnTargets());\n\n\/\/ TODO: fix OpenCL and add to the rest of tests\nTEST(Torch_Importer, run_paralel)\n{\n runTorchNet(\"net_parallel\", DNN_TARGET_CPU, \"l5_torchMerge\");\n}\n\nTEST(Torch_Importer, DISABLED_run_paralel)\n{\n runTorchNet(\"net_parallel\", DNN_TARGET_OPENCL, \"l5_torchMerge\");\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\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: dx_textlayout.cxx,v $\n * $Revision: 1.3 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <ctype.h> \/\/ don't ask. msdev breaks otherwise...\n#include <canvas\/debug.hxx>\n#include <canvas\/verbosetrace.hxx>\n\n#include <basegfx\/matrix\/b2dhommatrix.hxx>\n#include <basegfx\/numeric\/ftools.hxx>\n#include \"dx_bitmap.hxx\"\n#include \"dx_textlayout.hxx\"\n#include \"dx_spritecanvas.hxx\"\n#include \"dx_textlayout_drawhelper.hxx\"\n\n\nusing namespace ::com::sun::star;\n\nnamespace dxcanvas\n{\n TextLayout::TextLayout( const rendering::StringContext& aText,\n sal_Int8 nDirection,\n sal_Int64 \/*nRandomSeed*\/,\n const CanvasFont::ImplRef& rFont ) :\n TextLayout_Base( m_aMutex ),\n maText( aText ),\n maLogicalAdvancements(),\n mpFont( rFont ),\n mnTextDirection( nDirection )\n {\n }\n\n TextLayout::~TextLayout()\n {\n }\n\n void SAL_CALL TextLayout::disposing()\n {\n mpFont.reset();\n }\n\n \/\/ XTextLayout\n uno::Sequence< uno::Reference< rendering::XPolyPolygon2D > > SAL_CALL TextLayout::queryTextShapes( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Sequence< uno::Reference< rendering::XPolyPolygon2D > >();\n }\n\n uno::Sequence< geometry::RealRectangle2D > SAL_CALL TextLayout::queryInkMeasures( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Sequence< geometry::RealRectangle2D >();\n }\n\n uno::Sequence< geometry::RealRectangle2D > SAL_CALL TextLayout::queryMeasures( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Sequence< geometry::RealRectangle2D >();\n }\n\n uno::Sequence< double > SAL_CALL TextLayout::queryLogicalAdvancements( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return maLogicalAdvancements;\n }\n\n void SAL_CALL TextLayout::applyLogicalAdvancements( const uno::Sequence< double >& aAdvancements ) throw (lang::IllegalArgumentException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n if( aAdvancements.getLength() != maText.Length )\n {\n OSL_TRACE( \"TextLayout::applyLogicalAdvancements(): mismatching number of advancements\" );\n throw lang::IllegalArgumentException();\n }\n\n maLogicalAdvancements = aAdvancements;\n }\n\n geometry::RealRectangle2D SAL_CALL TextLayout::queryTextBounds( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n uno::Reference< rendering::XGraphicDevice > xGraphicDevice;\n ::dxcanvas::TextLayoutDrawHelper aDrawHelper(xGraphicDevice);\n\n \/\/ render text\n const geometry::RealRectangle2D aBounds(\n aDrawHelper.queryTextBounds(\n maText,\n maLogicalAdvancements,\n mpFont.getRef(),\n mpFont->getFontMatrix()));\n\n return aBounds;\n }\n\n double SAL_CALL TextLayout::justify( double \/*nSize*\/ ) throw (lang::IllegalArgumentException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return 0.0;\n }\n\n double SAL_CALL TextLayout::combinedJustify( const uno::Sequence< uno::Reference< rendering::XTextLayout > >& \/*aNextLayouts*\/,\n double \/*nSize*\/ ) throw (lang::IllegalArgumentException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return 0.0;\n }\n\n rendering::TextHit SAL_CALL TextLayout::getTextHit( const geometry::RealPoint2D& \/*aHitPoint*\/ ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return rendering::TextHit();\n }\n\n rendering::Caret SAL_CALL TextLayout::getCaret( sal_Int32 \/*nInsertionIndex*\/,\n sal_Bool \/*bExcludeLigatures*\/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return rendering::Caret();\n }\n\n sal_Int32 SAL_CALL TextLayout::getNextInsertionIndex( sal_Int32 \/*nStartIndex*\/,\n sal_Int32 \/*nCaretAdvancement*\/,\n sal_Bool \/*bExcludeLigatures*\/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return 0;\n }\n\n uno::Reference< rendering::XPolyPolygon2D > SAL_CALL TextLayout::queryVisualHighlighting( sal_Int32 \/*nStartIndex*\/,\n sal_Int32 \/*nEndIndex*\/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Reference< rendering::XPolyPolygon2D >();\n }\n\n uno::Reference< rendering::XPolyPolygon2D > SAL_CALL TextLayout::queryLogicalHighlighting( sal_Int32 \/*nStartIndex*\/,\n sal_Int32 \/*nEndIndex*\/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Reference< rendering::XPolyPolygon2D >();\n }\n\n double SAL_CALL TextLayout::getBaselineOffset( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return 0.0;\n }\n\n sal_Int8 SAL_CALL TextLayout::getMainTextDirection( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return mnTextDirection;\n }\n\n uno::Reference< rendering::XCanvasFont > SAL_CALL TextLayout::getFont( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return mpFont.getRef();\n }\n\n rendering::StringContext SAL_CALL TextLayout::getText( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return maText;\n }\n\n namespace\n {\n \/\/ TODO(P2): Check whether this gets inlined. If not, make functor\n \/\/ out of it\n inline Gdiplus::PointF gdiPlusPointFromDx( const double& dx )\n {\n return Gdiplus::PointF( static_cast<Gdiplus::REAL>(dx),\n 0.0f );\n }\n }\n\n bool TextLayout::draw( const DXBitmapSharedPtr &rBitmap,\n const rendering::ViewState& rViewState,\n const rendering::RenderState& rRenderState,\n const ::basegfx::B2ISize& rOutputOffset,\n const uno::Reference< rendering::XGraphicDevice >& xGraphicDevice ) const\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n ::dxcanvas::TextLayoutDrawHelper aDrawHelper(xGraphicDevice);\n\n \/\/ render text\n aDrawHelper.drawText(rBitmap,\n rViewState,\n rRenderState,\n rOutputOffset,\n maText,\n maLogicalAdvancements,\n mpFont.getRef(),\n mpFont->getFontMatrix());\n\n return true;\n }\n\n\n#define SERVICE_NAME \"com.sun.star.rendering.TextLayout\"\n#define IMPLEMENTATION_NAME \"DXCanvas::TextLayout\"\n\n ::rtl::OUString SAL_CALL TextLayout::getImplementationName() throw( uno::RuntimeException )\n {\n return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) );\n }\n\n sal_Bool SAL_CALL TextLayout::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException )\n {\n return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );\n }\n\n uno::Sequence< ::rtl::OUString > SAL_CALL TextLayout::getSupportedServiceNames() throw( uno::RuntimeException )\n {\n uno::Sequence< ::rtl::OUString > aRet(1);\n aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );\n\n return aRet;\n }\n}\n<commit_msg>INTEGRATION: CWS canvas05 (1.2.2); FILE MERGED 2008\/04\/21 07:30:20 thb 1.2.2.2: RESYNC: (1.2-1.3); FILE MERGED 2008\/01\/22 00:25:24 thb 1.2.2.1: #i81092# Making gdiplus and dx canvas more independent<commit_after>\/*************************************************************************\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: dx_textlayout.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 * <http:\/\/www.openoffice.org\/license.html>\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_canvas.hxx\"\n\n#include <ctype.h> \/\/ don't ask. msdev breaks otherwise...\n#include <canvas\/debug.hxx>\n#include <canvas\/verbosetrace.hxx>\n\n#include <basegfx\/matrix\/b2dhommatrix.hxx>\n#include <basegfx\/numeric\/ftools.hxx>\n#include \"dx_bitmap.hxx\"\n#include \"dx_textlayout.hxx\"\n#include \"dx_spritecanvas.hxx\"\n#include \"dx_textlayout_drawhelper.hxx\"\n\n\nusing namespace ::com::sun::star;\n\nnamespace dxcanvas\n{\n TextLayout::TextLayout( const rendering::StringContext& aText,\n sal_Int8 nDirection,\n sal_Int64 \/*nRandomSeed*\/,\n const CanvasFont::ImplRef& rFont ) :\n TextLayout_Base( m_aMutex ),\n maText( aText ),\n maLogicalAdvancements(),\n mpFont( rFont ),\n mnTextDirection( nDirection )\n {\n }\n\n TextLayout::~TextLayout()\n {\n }\n\n void SAL_CALL TextLayout::disposing()\n {\n mpFont.reset();\n }\n\n \/\/ XTextLayout\n uno::Sequence< uno::Reference< rendering::XPolyPolygon2D > > SAL_CALL TextLayout::queryTextShapes( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Sequence< uno::Reference< rendering::XPolyPolygon2D > >();\n }\n\n uno::Sequence< geometry::RealRectangle2D > SAL_CALL TextLayout::queryInkMeasures( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Sequence< geometry::RealRectangle2D >();\n }\n\n uno::Sequence< geometry::RealRectangle2D > SAL_CALL TextLayout::queryMeasures( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Sequence< geometry::RealRectangle2D >();\n }\n\n uno::Sequence< double > SAL_CALL TextLayout::queryLogicalAdvancements( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return maLogicalAdvancements;\n }\n\n void SAL_CALL TextLayout::applyLogicalAdvancements( const uno::Sequence< double >& aAdvancements ) throw (lang::IllegalArgumentException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n if( aAdvancements.getLength() != maText.Length )\n {\n OSL_TRACE( \"TextLayout::applyLogicalAdvancements(): mismatching number of advancements\" );\n throw lang::IllegalArgumentException();\n }\n\n maLogicalAdvancements = aAdvancements;\n }\n\n geometry::RealRectangle2D SAL_CALL TextLayout::queryTextBounds( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n uno::Reference< rendering::XGraphicDevice > xGraphicDevice;\n ::dxcanvas::TextLayoutDrawHelper aDrawHelper(xGraphicDevice);\n\n \/\/ render text\n const geometry::RealRectangle2D aBounds(\n aDrawHelper.queryTextBounds(\n maText,\n maLogicalAdvancements,\n mpFont.getRef(),\n mpFont->getFontMatrix()));\n\n return aBounds;\n }\n\n double SAL_CALL TextLayout::justify( double \/*nSize*\/ ) throw (lang::IllegalArgumentException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return 0.0;\n }\n\n double SAL_CALL TextLayout::combinedJustify( const uno::Sequence< uno::Reference< rendering::XTextLayout > >& \/*aNextLayouts*\/,\n double \/*nSize*\/ ) throw (lang::IllegalArgumentException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return 0.0;\n }\n\n rendering::TextHit SAL_CALL TextLayout::getTextHit( const geometry::RealPoint2D& \/*aHitPoint*\/ ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return rendering::TextHit();\n }\n\n rendering::Caret SAL_CALL TextLayout::getCaret( sal_Int32 \/*nInsertionIndex*\/,\n sal_Bool \/*bExcludeLigatures*\/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return rendering::Caret();\n }\n\n sal_Int32 SAL_CALL TextLayout::getNextInsertionIndex( sal_Int32 \/*nStartIndex*\/,\n sal_Int32 \/*nCaretAdvancement*\/,\n sal_Bool \/*bExcludeLigatures*\/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return 0;\n }\n\n uno::Reference< rendering::XPolyPolygon2D > SAL_CALL TextLayout::queryVisualHighlighting( sal_Int32 \/*nStartIndex*\/,\n sal_Int32 \/*nEndIndex*\/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Reference< rendering::XPolyPolygon2D >();\n }\n\n uno::Reference< rendering::XPolyPolygon2D > SAL_CALL TextLayout::queryLogicalHighlighting( sal_Int32 \/*nStartIndex*\/,\n sal_Int32 \/*nEndIndex*\/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return uno::Reference< rendering::XPolyPolygon2D >();\n }\n\n double SAL_CALL TextLayout::getBaselineOffset( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ TODO\n return 0.0;\n }\n\n sal_Int8 SAL_CALL TextLayout::getMainTextDirection( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return mnTextDirection;\n }\n\n uno::Reference< rendering::XCanvasFont > SAL_CALL TextLayout::getFont( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return mpFont.getRef();\n }\n\n rendering::StringContext SAL_CALL TextLayout::getText( ) throw (uno::RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return maText;\n }\n\n namespace\n {\n \/\/ TODO(P2): Check whether this gets inlined. If not, make functor\n \/\/ out of it\n inline Gdiplus::PointF gdiPlusPointFromDx( const double& dx )\n {\n return Gdiplus::PointF( static_cast<Gdiplus::REAL>(dx),\n 0.0f );\n }\n }\n\n bool TextLayout::draw( const GraphicsSharedPtr& rGraphics,\n const rendering::ViewState& rViewState,\n const rendering::RenderState& rRenderState,\n const ::basegfx::B2ISize& rOutputOffset,\n const uno::Reference< rendering::XGraphicDevice >& xGraphicDevice,\n bool bAlphaSurface ) const\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n ::dxcanvas::TextLayoutDrawHelper aDrawHelper(xGraphicDevice);\n\n \/\/ render text\n aDrawHelper.drawText(\n rGraphics,\n rViewState,\n rRenderState,\n rOutputOffset,\n maText,\n maLogicalAdvancements,\n mpFont.getRef(),\n mpFont->getFontMatrix(),\n bAlphaSurface);\n\n return true;\n }\n\n\n#define SERVICE_NAME \"com.sun.star.rendering.TextLayout\"\n#define IMPLEMENTATION_NAME \"DXCanvas::TextLayout\"\n\n ::rtl::OUString SAL_CALL TextLayout::getImplementationName() throw( uno::RuntimeException )\n {\n return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) );\n }\n\n sal_Bool SAL_CALL TextLayout::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException )\n {\n return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );\n }\n\n uno::Sequence< ::rtl::OUString > SAL_CALL TextLayout::getSupportedServiceNames() throw( uno::RuntimeException )\n {\n uno::Sequence< ::rtl::OUString > aRet(1);\n aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );\n\n return aRet;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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 * @file\n **\/\n\n#include <limits>\n#include <unordered_map>\n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/util\/util.h\"\n#include \"modules\/planning\/common\/path_obstacle.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/common\/speed\/st_boundary.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing common::VehicleConfigHelper;\n\nnamespace {\nconst double kStBoundaryDeltaS = 0.2;\n}\n\nconst std::unordered_map<ObjectDecisionType::ObjectTagCase, int,\n PathObstacle::ObjectTagCaseHash>\n PathObstacle::s_longitudinal_decision_safety_sorter_ = {\n {ObjectDecisionType::kIgnore, 0},\n {ObjectDecisionType::kOvertake, 100},\n {ObjectDecisionType::kFollow, 300},\n {ObjectDecisionType::kYield, 400},\n {ObjectDecisionType::kStop, 500}};\n\nconst std::unordered_map<ObjectDecisionType::ObjectTagCase, int,\n PathObstacle::ObjectTagCaseHash>\n PathObstacle::s_lateral_decision_safety_sorter_ = {\n {ObjectDecisionType::kIgnore, 0}, {ObjectDecisionType::kNudge, 100}};\n\nconst std::string& PathObstacle::Id() const { return id_; }\n\nPathObstacle::PathObstacle(const Obstacle* obstacle) : obstacle_(obstacle) {\n CHECK_NOTNULL(obstacle);\n id_ = obstacle_->Id();\n}\n\nbool PathObstacle::Init(const ReferenceLine& reference_line) {\n if (!reference_line.GetSLBoundary(obstacle_->PerceptionBoundingBox(),\n &perception_sl_boundary_)) {\n AERROR << \"Failed to get sl boundary for obstacle: \" << id_;\n return false;\n }\n BuildStBoundary(reference_line);\n return true;\n}\n\nvoid PathObstacle::BuildStBoundary(const ReferenceLine& reference_line) {\n if (obstacle_->IsStatic() ||\n obstacle_->Trajectory().trajectory_point().empty()) {\n std::vector<STPoint> points;\n points.emplace_back(perception_sl_boundary_.start_s(), 0.0);\n points.emplace_back(perception_sl_boundary_.start_s(), FLAGS_st_max_t);\n points.emplace_back(perception_sl_boundary_.end_s(), FLAGS_st_max_t);\n points.emplace_back(perception_sl_boundary_.end_s(), 0.0);\n st_boundary_ = StBoundary(points);\n } else {\n if (BuildTrajectoryStBoundary(reference_line, &st_boundary_)) {\n ADEBUG << \"Found st_boundary for obstacle \" << id_;\n } else {\n ADEBUG << \"No st_boundary for obstacle \" << id_;\n }\n }\n}\n\nbool PathObstacle::BuildTrajectoryStBoundary(\n const ReferenceLine& reference_line, StBoundary* const st_boundary) {\n const auto& object_id = obstacle_->Id();\n const auto& perception = obstacle_->Perception();\n const double object_width = perception.width();\n const double object_length = perception.length();\n const auto& trajectory_points = obstacle_->Trajectory().trajectory_point();\n if (trajectory_points.empty()) {\n AWARN << \"object \" << object_id << \" has no trajectory points\";\n return false;\n }\n const auto& adc_param =\n VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n const double adc_length = adc_param.length();\n const double adc_half_length = adc_length \/ 2.0;\n const double adc_width = adc_param.width();\n common::math::Box2d min_box({0, 0}, 1.0, 1.0, 1.0);\n common::math::Box2d max_box({0, 0}, 1.0, 1.0, 1.0);\n const double s_step = kStBoundaryDeltaS;\n std::vector<common::math::Vec2d> polygon_points;\n for (int i = 1; i < trajectory_points.size(); ++i) {\n const auto& first_traj_point = trajectory_points[i - 1];\n const auto& second_traj_point = trajectory_points[i - 1];\n const auto& first_point = first_traj_point.path_point();\n const auto& second_point = second_traj_point.path_point();\n double total_length =\n object_length + common::util::Distance2D(first_point, second_point);\n common::math::Vec2d center((first_point.x() + second_point.x()) \/ 2.0,\n (first_point.y() + second_point.y()) \/ 2.0);\n common::math::Box2d object_moving_box(center, first_point.theta(),\n total_length, object_width);\n SLBoundary object_boundary;\n if (!reference_line.GetSLBoundary(object_moving_box, &object_boundary)) {\n AERROR << \"failed to calculate boundary\";\n return false;\n }\n const double object_s_diff =\n object_boundary.end_s() - object_boundary.start_s();\n if (object_boundary.end_s() < 0) {\n \/\/ skip if behind adc\n continue;\n }\n const double delta_t =\n second_traj_point.relative_time() - first_traj_point.relative_time();\n for (double s = std::max(object_boundary.start_s() - adc_half_length, 0.0);\n s <\n std::min(object_boundary.end_s() + adc_half_length, FLAGS_st_max_s);\n s += s_step) {\n auto adc_trajectory_point = reference_line.GetReferencePoint(s);\n common::math::Box2d tmp_adc_box(adc_trajectory_point,\n adc_trajectory_point.heading(),\n adc_length, adc_width);\n if (tmp_adc_box.HasOverlap(object_moving_box)) {\n double mean_t = first_traj_point.relative_time();\n if (object_s_diff > common::math::kMathEpsilon) {\n mean_t = (first_traj_point.relative_time() +\n std::fabs((s - object_boundary.start_s()) \/ object_s_diff) *\n delta_t);\n }\n polygon_points.emplace_back(mean_t, s);\n }\n }\n }\n if (polygon_points.size() < 3) {\n ADEBUG << \"object \" << object_id << \" has no st overlap\";\n return false;\n }\n common::math::Polygon2d::ComputeConvexHull(polygon_points, st_boundary);\n return true;\n}\n\nconst StBoundary& PathObstacle::st_boundary() const { return st_boundary_; }\n\nbool PathObstacle::IsLateralDecision(const ObjectDecisionType& decision) {\n return decision.has_ignore() || decision.has_nudge();\n}\n\nbool PathObstacle::IsLongitudinalDecision(const ObjectDecisionType& decision) {\n return decision.has_ignore() || decision.has_stop() || decision.has_yield() ||\n decision.has_follow() || decision.has_overtake();\n}\n\nObjectDecisionType PathObstacle::MergeLongitudinalDecision(\n const ObjectDecisionType& lhs, const ObjectDecisionType& rhs) {\n if (lhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n return rhs;\n }\n if (rhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n return lhs;\n }\n auto lhs_iter =\n s_longitudinal_decision_safety_sorter_.find(lhs.object_tag_case());\n DCHECK(lhs_iter != s_longitudinal_decision_safety_sorter_.end())\n << \"decision : \" << lhs.ShortDebugString()\n << \" not found in safety sorter\";\n auto rhs_iter =\n s_longitudinal_decision_safety_sorter_.find(rhs.object_tag_case());\n DCHECK(rhs_iter != s_longitudinal_decision_safety_sorter_.end())\n << \"decision : \" << rhs.ShortDebugString()\n << \" not found in safety sorter\";\n if (lhs_iter->second < rhs_iter->second) {\n return rhs;\n } else if (lhs_iter->second > rhs_iter->second) {\n return lhs;\n } else {\n if (lhs.has_ignore()) {\n return rhs;\n } else if (lhs.has_stop()) {\n return lhs.stop().distance_s() < rhs.stop().distance_s() ? lhs : rhs;\n } else if (lhs.has_yield()) {\n return lhs.yield().distance_s() < rhs.yield().distance_s() ? lhs : rhs;\n } else if (lhs.has_follow()) {\n return lhs.follow().distance_s() < rhs.follow().distance_s() ? lhs : rhs;\n } else if (lhs.has_overtake()) {\n return lhs.overtake().distance_s() > rhs.overtake().distance_s() ? lhs\n : rhs;\n } else {\n DCHECK(false) << \"Unknown decision\";\n }\n }\n}\n\nconst ObjectDecisionType& PathObstacle::LongitudinalDecision() const {\n return longitudinal_decision_;\n}\n\nconst ObjectDecisionType& PathObstacle::LateralDecision() const {\n return lateral_decision_;\n}\n\nbool PathObstacle::IsIgnore() const {\n return longitudinal_decision_.has_ignore() && lateral_decision_.has_ignore();\n}\n\nObjectDecisionType PathObstacle::MergeLateralDecision(\n const ObjectDecisionType& lhs, const ObjectDecisionType& rhs) {\n if (lhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n return rhs;\n }\n if (rhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n return lhs;\n }\n auto lhs_iter = s_lateral_decision_safety_sorter_.find(lhs.object_tag_case());\n DCHECK(lhs_iter != s_lateral_decision_safety_sorter_.end())\n << \"decision : \" << lhs.ShortDebugString()\n << \" not found in safety sorter\";\n auto rhs_iter = s_lateral_decision_safety_sorter_.find(rhs.object_tag_case());\n DCHECK(rhs_iter != s_lateral_decision_safety_sorter_.end())\n << \"decision : \" << rhs.ShortDebugString()\n << \" not found in safety sorter\";\n if (lhs_iter->second < rhs_iter->second) {\n return rhs;\n } else if (lhs_iter->second > rhs_iter->second) {\n return lhs;\n } else {\n if (lhs.has_ignore()) {\n return rhs;\n } else if (lhs.has_nudge()) {\n DCHECK(lhs.nudge().type() == rhs.nudge().type())\n << \"could not merge left nudge and right nudge\";\n return std::fabs(lhs.nudge().distance_l()) >\n std::fabs(rhs.nudge().distance_l())\n ? lhs\n : rhs;\n }\n }\n DCHECK(false) << \"Does not have rule to merge decision: \"\n << lhs.ShortDebugString()\n << \" and decision: \" << rhs.ShortDebugString();\n}\n\nbool PathObstacle::HasLateralDecision() const {\n return lateral_decision_.object_tag_case() !=\n ObjectDecisionType::OBJECT_TAG_NOT_SET;\n}\n\nbool PathObstacle::HasLongitudinalDecision() const {\n return longitudinal_decision_.object_tag_case() !=\n ObjectDecisionType::OBJECT_TAG_NOT_SET;\n}\n\nconst Obstacle* PathObstacle::obstacle() const { return obstacle_; }\n\nvoid PathObstacle::AddLongitudinalDecision(const std::string& decider_tag,\n const ObjectDecisionType& decision) {\n DCHECK(IsLongitudinalDecision(decision))\n << \"Decision: \" << decision.ShortDebugString()\n << \" is not a longitudinal decision\";\n longitudinal_decision_ =\n MergeLongitudinalDecision(longitudinal_decision_, decision);\n ADEBUG << decider_tag << \" added obstacle \" << Id()\n << \" a longitudinal decision: \" << decision.ShortDebugString()\n << \". The merged decision is: \"\n << longitudinal_decision_.ShortDebugString();\n decisions_.push_back(decision);\n decider_tags_.push_back(decider_tag);\n}\n\nvoid PathObstacle::AddLateralDecision(const std::string& decider_tag,\n const ObjectDecisionType& decision) {\n DCHECK(IsLateralDecision(decision))\n << \"Decision: \" << decision.ShortDebugString()\n << \" is not a lateral decision\";\n lateral_decision_ = MergeLateralDecision(lateral_decision_, decision);\n ADEBUG << decider_tag << \" added obstacle \" << Id()\n << \" a lateral decision: \" << decision.ShortDebugString()\n << \". The merged decision is: \"\n << lateral_decision_.ShortDebugString();\n decisions_.push_back(decision);\n decider_tags_.push_back(decider_tag);\n}\n\nconst std::string PathObstacle::DebugString() const {\n std::stringstream ss;\n ss << \"PathObstacle id: \" << id_;\n for (std::size_t i = 0; i < decisions_.size(); ++i) {\n ss << \" decision: \" << decisions_[i].DebugString() << \", made by \"\n << decider_tags_[i];\n }\n if (lateral_decision_.object_tag_case() !=\n ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n ss << \"lateral decision: \" << lateral_decision_.ShortDebugString();\n }\n if (longitudinal_decision_.object_tag_case() !=\n ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n ss << \"longitutional decision: \"\n << longitudinal_decision_.ShortDebugString();\n }\n return ss.str();\n}\n\nconst SLBoundary& PathObstacle::perception_sl_boundary() const {\n return perception_sl_boundary_;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: temporariy disable StBoundary in path_obstacle<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\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 * @file\n **\/\n\n#include <limits>\n#include <unordered_map>\n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/util\/util.h\"\n#include \"modules\/planning\/common\/path_obstacle.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/common\/speed\/st_boundary.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing common::VehicleConfigHelper;\n\nnamespace {\nconst double kStBoundaryDeltaS = 0.2;\n}\n\nconst std::unordered_map<ObjectDecisionType::ObjectTagCase, int,\n PathObstacle::ObjectTagCaseHash>\n PathObstacle::s_longitudinal_decision_safety_sorter_ = {\n {ObjectDecisionType::kIgnore, 0},\n {ObjectDecisionType::kOvertake, 100},\n {ObjectDecisionType::kFollow, 300},\n {ObjectDecisionType::kYield, 400},\n {ObjectDecisionType::kStop, 500}};\n\nconst std::unordered_map<ObjectDecisionType::ObjectTagCase, int,\n PathObstacle::ObjectTagCaseHash>\n PathObstacle::s_lateral_decision_safety_sorter_ = {\n {ObjectDecisionType::kIgnore, 0}, {ObjectDecisionType::kNudge, 100}};\n\nconst std::string& PathObstacle::Id() const { return id_; }\n\nPathObstacle::PathObstacle(const Obstacle* obstacle) : obstacle_(obstacle) {\n CHECK_NOTNULL(obstacle);\n id_ = obstacle_->Id();\n}\n\nbool PathObstacle::Init(const ReferenceLine& reference_line) {\n if (!reference_line.GetSLBoundary(obstacle_->PerceptionBoundingBox(),\n &perception_sl_boundary_)) {\n AERROR << \"Failed to get sl boundary for obstacle: \" << id_;\n return false;\n }\n \/\/ BuildStBoundary(reference_line);\n return true;\n}\n\nvoid PathObstacle::BuildStBoundary(const ReferenceLine& reference_line) {\n if (obstacle_->IsStatic() ||\n obstacle_->Trajectory().trajectory_point().empty()) {\n std::vector<STPoint> points;\n points.emplace_back(perception_sl_boundary_.start_s(), 0.0);\n points.emplace_back(perception_sl_boundary_.start_s(), FLAGS_st_max_t);\n points.emplace_back(perception_sl_boundary_.end_s(), FLAGS_st_max_t);\n points.emplace_back(perception_sl_boundary_.end_s(), 0.0);\n st_boundary_ = StBoundary(points);\n } else {\n if (BuildTrajectoryStBoundary(reference_line, &st_boundary_)) {\n ADEBUG << \"Found st_boundary for obstacle \" << id_;\n } else {\n ADEBUG << \"No st_boundary for obstacle \" << id_;\n }\n }\n}\n\nbool PathObstacle::BuildTrajectoryStBoundary(\n const ReferenceLine& reference_line, StBoundary* const st_boundary) {\n const auto& object_id = obstacle_->Id();\n const auto& perception = obstacle_->Perception();\n const double object_width = perception.width();\n const double object_length = perception.length();\n const auto& trajectory_points = obstacle_->Trajectory().trajectory_point();\n if (trajectory_points.empty()) {\n AWARN << \"object \" << object_id << \" has no trajectory points\";\n return false;\n }\n const auto& adc_param =\n VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n const double adc_length = adc_param.length();\n const double adc_half_length = adc_length \/ 2.0;\n const double adc_width = adc_param.width();\n common::math::Box2d min_box({0, 0}, 1.0, 1.0, 1.0);\n common::math::Box2d max_box({0, 0}, 1.0, 1.0, 1.0);\n const double s_step = kStBoundaryDeltaS;\n std::vector<common::math::Vec2d> polygon_points;\n for (int i = 1; i < trajectory_points.size(); ++i) {\n const auto& first_traj_point = trajectory_points[i - 1];\n const auto& second_traj_point = trajectory_points[i - 1];\n const auto& first_point = first_traj_point.path_point();\n const auto& second_point = second_traj_point.path_point();\n double total_length =\n object_length + common::util::Distance2D(first_point, second_point);\n common::math::Vec2d center((first_point.x() + second_point.x()) \/ 2.0,\n (first_point.y() + second_point.y()) \/ 2.0);\n common::math::Box2d object_moving_box(center, first_point.theta(),\n total_length, object_width);\n SLBoundary object_boundary;\n if (!reference_line.GetSLBoundary(object_moving_box, &object_boundary)) {\n AERROR << \"failed to calculate boundary\";\n return false;\n }\n const double object_s_diff =\n object_boundary.end_s() - object_boundary.start_s();\n if (object_boundary.end_s() < 0) {\n \/\/ skip if behind adc\n continue;\n }\n const double delta_t =\n second_traj_point.relative_time() - first_traj_point.relative_time();\n for (double s = std::max(object_boundary.start_s() - adc_half_length, 0.0);\n s <\n std::min(object_boundary.end_s() + adc_half_length, FLAGS_st_max_s);\n s += s_step) {\n auto adc_trajectory_point = reference_line.GetReferencePoint(s);\n common::math::Box2d tmp_adc_box(adc_trajectory_point,\n adc_trajectory_point.heading(),\n adc_length, adc_width);\n if (tmp_adc_box.HasOverlap(object_moving_box)) {\n double mean_t = first_traj_point.relative_time();\n if (object_s_diff > common::math::kMathEpsilon) {\n mean_t = (first_traj_point.relative_time() +\n std::fabs((s - object_boundary.start_s()) \/ object_s_diff) *\n delta_t);\n }\n polygon_points.emplace_back(mean_t, s);\n }\n }\n }\n if (polygon_points.size() < 3) {\n ADEBUG << \"object \" << object_id << \" has no st overlap\";\n return false;\n }\n common::math::Polygon2d::ComputeConvexHull(polygon_points, st_boundary);\n return true;\n}\n\nconst StBoundary& PathObstacle::st_boundary() const { return st_boundary_; }\n\nbool PathObstacle::IsLateralDecision(const ObjectDecisionType& decision) {\n return decision.has_ignore() || decision.has_nudge();\n}\n\nbool PathObstacle::IsLongitudinalDecision(const ObjectDecisionType& decision) {\n return decision.has_ignore() || decision.has_stop() || decision.has_yield() ||\n decision.has_follow() || decision.has_overtake();\n}\n\nObjectDecisionType PathObstacle::MergeLongitudinalDecision(\n const ObjectDecisionType& lhs, const ObjectDecisionType& rhs) {\n if (lhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n return rhs;\n }\n if (rhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n return lhs;\n }\n auto lhs_iter =\n s_longitudinal_decision_safety_sorter_.find(lhs.object_tag_case());\n DCHECK(lhs_iter != s_longitudinal_decision_safety_sorter_.end())\n << \"decision : \" << lhs.ShortDebugString()\n << \" not found in safety sorter\";\n auto rhs_iter =\n s_longitudinal_decision_safety_sorter_.find(rhs.object_tag_case());\n DCHECK(rhs_iter != s_longitudinal_decision_safety_sorter_.end())\n << \"decision : \" << rhs.ShortDebugString()\n << \" not found in safety sorter\";\n if (lhs_iter->second < rhs_iter->second) {\n return rhs;\n } else if (lhs_iter->second > rhs_iter->second) {\n return lhs;\n } else {\n if (lhs.has_ignore()) {\n return rhs;\n } else if (lhs.has_stop()) {\n return lhs.stop().distance_s() < rhs.stop().distance_s() ? lhs : rhs;\n } else if (lhs.has_yield()) {\n return lhs.yield().distance_s() < rhs.yield().distance_s() ? lhs : rhs;\n } else if (lhs.has_follow()) {\n return lhs.follow().distance_s() < rhs.follow().distance_s() ? lhs : rhs;\n } else if (lhs.has_overtake()) {\n return lhs.overtake().distance_s() > rhs.overtake().distance_s() ? lhs\n : rhs;\n } else {\n DCHECK(false) << \"Unknown decision\";\n }\n }\n}\n\nconst ObjectDecisionType& PathObstacle::LongitudinalDecision() const {\n return longitudinal_decision_;\n}\n\nconst ObjectDecisionType& PathObstacle::LateralDecision() const {\n return lateral_decision_;\n}\n\nbool PathObstacle::IsIgnore() const {\n return longitudinal_decision_.has_ignore() && lateral_decision_.has_ignore();\n}\n\nObjectDecisionType PathObstacle::MergeLateralDecision(\n const ObjectDecisionType& lhs, const ObjectDecisionType& rhs) {\n if (lhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n return rhs;\n }\n if (rhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n return lhs;\n }\n auto lhs_iter = s_lateral_decision_safety_sorter_.find(lhs.object_tag_case());\n DCHECK(lhs_iter != s_lateral_decision_safety_sorter_.end())\n << \"decision : \" << lhs.ShortDebugString()\n << \" not found in safety sorter\";\n auto rhs_iter = s_lateral_decision_safety_sorter_.find(rhs.object_tag_case());\n DCHECK(rhs_iter != s_lateral_decision_safety_sorter_.end())\n << \"decision : \" << rhs.ShortDebugString()\n << \" not found in safety sorter\";\n if (lhs_iter->second < rhs_iter->second) {\n return rhs;\n } else if (lhs_iter->second > rhs_iter->second) {\n return lhs;\n } else {\n if (lhs.has_ignore()) {\n return rhs;\n } else if (lhs.has_nudge()) {\n DCHECK(lhs.nudge().type() == rhs.nudge().type())\n << \"could not merge left nudge and right nudge\";\n return std::fabs(lhs.nudge().distance_l()) >\n std::fabs(rhs.nudge().distance_l())\n ? lhs\n : rhs;\n }\n }\n DCHECK(false) << \"Does not have rule to merge decision: \"\n << lhs.ShortDebugString()\n << \" and decision: \" << rhs.ShortDebugString();\n}\n\nbool PathObstacle::HasLateralDecision() const {\n return lateral_decision_.object_tag_case() !=\n ObjectDecisionType::OBJECT_TAG_NOT_SET;\n}\n\nbool PathObstacle::HasLongitudinalDecision() const {\n return longitudinal_decision_.object_tag_case() !=\n ObjectDecisionType::OBJECT_TAG_NOT_SET;\n}\n\nconst Obstacle* PathObstacle::obstacle() const { return obstacle_; }\n\nvoid PathObstacle::AddLongitudinalDecision(const std::string& decider_tag,\n const ObjectDecisionType& decision) {\n DCHECK(IsLongitudinalDecision(decision))\n << \"Decision: \" << decision.ShortDebugString()\n << \" is not a longitudinal decision\";\n longitudinal_decision_ =\n MergeLongitudinalDecision(longitudinal_decision_, decision);\n ADEBUG << decider_tag << \" added obstacle \" << Id()\n << \" a longitudinal decision: \" << decision.ShortDebugString()\n << \". The merged decision is: \"\n << longitudinal_decision_.ShortDebugString();\n decisions_.push_back(decision);\n decider_tags_.push_back(decider_tag);\n}\n\nvoid PathObstacle::AddLateralDecision(const std::string& decider_tag,\n const ObjectDecisionType& decision) {\n DCHECK(IsLateralDecision(decision))\n << \"Decision: \" << decision.ShortDebugString()\n << \" is not a lateral decision\";\n lateral_decision_ = MergeLateralDecision(lateral_decision_, decision);\n ADEBUG << decider_tag << \" added obstacle \" << Id()\n << \" a lateral decision: \" << decision.ShortDebugString()\n << \". The merged decision is: \"\n << lateral_decision_.ShortDebugString();\n decisions_.push_back(decision);\n decider_tags_.push_back(decider_tag);\n}\n\nconst std::string PathObstacle::DebugString() const {\n std::stringstream ss;\n ss << \"PathObstacle id: \" << id_;\n for (std::size_t i = 0; i < decisions_.size(); ++i) {\n ss << \" decision: \" << decisions_[i].DebugString() << \", made by \"\n << decider_tags_[i];\n }\n if (lateral_decision_.object_tag_case() !=\n ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n ss << \"lateral decision: \" << lateral_decision_.ShortDebugString();\n }\n if (longitudinal_decision_.object_tag_case() !=\n ObjectDecisionType::OBJECT_TAG_NOT_SET) {\n ss << \"longitutional decision: \"\n << longitudinal_decision_.ShortDebugString();\n }\n return ss.str();\n}\n\nconst SLBoundary& PathObstacle::perception_sl_boundary() const {\n return perception_sl_boundary_;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2019 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#define CAF_SUITE ipv6_endpoint\n\n#include \"caf\/ipv6_endpoint.hpp\"\n\n#include \"caf\/test\/unit_test.hpp\"\n\n#include <cassert>\n#include <vector>\n\n#include \"caf\/actor_system.hpp\"\n#include \"caf\/actor_system_config.hpp\"\n#include \"caf\/binary_deserializer.hpp\"\n#include \"caf\/byte.hpp\"\n#include \"caf\/ipv6_address.hpp\"\n#include \"caf\/serializer_impl.hpp\"\n#include \"caf\/span.hpp\"\n\nusing namespace caf;\n\nnamespace {\n\nipv6_endpoint operator\"\" _ep(const char* str, size_t) {\n union {\n std::array<uint8_t, 16> xs_bytes;\n std::array<uint16_t, 8> xs;\n };\n union {\n std::array<uint8_t, 16> ys_bytes;\n std::array<uint16_t, 8> ys;\n };\n memset(xs_bytes.data(), 0, xs_bytes.size());\n memset(ys_bytes.data(), 0, xs_bytes.size());\n assert(*str == '[');\n ++str;\n char* next = nullptr;\n auto pull = [&] {\n auto x = static_cast<uint16_t>(strtol(str, &next, 16));\n return detail::to_network_order(x);\n };\n size_t n = 0;\n do {\n xs[n++] = pull();\n assert(next != nullptr);\n str = next + 1;\n } while (*str != ':' && *str != ']');\n if (*str == ':') {\n ++str;\n do {\n ys[0] = pull();\n std::rotate(ys.begin(), ys.begin() + 1, ys.end());\n assert(next != nullptr);\n str = next + 1;\n } while (*next != ']');\n }\n assert(*next == ']');\n assert(*str == ':');\n ++str;\n auto port = static_cast<uint16_t>(strtol(str, nullptr, 10));\n std::array<uint8_t, 16> bytes;\n for (size_t i = 0; i < 16; ++i)\n bytes[i] = xs_bytes[i] | ys_bytes[i];\n return ipv6_endpoint{ipv6_address{bytes}, port};\n}\n\nstruct fixture {\n actor_system_config cfg;\n actor_system sys{cfg};\n\n template <class T>\n T roundtrip(T x) {\n using container_type = std::vector<byte>;\n container_type buf;\n serializer_impl<container_type> sink(sys, buf);\n if (auto err = sink(x))\n CAF_FAIL(\"serialization failed: \" << sys.render(err));\n binary_deserializer source(sys, make_span(buf));\n T y;\n if (auto err = source(y))\n CAF_FAIL(\"deserialization failed: \" << sys.render(err));\n return y;\n }\n};\n\n#define CHECK_TO_STRING(addr) CAF_CHECK_EQUAL(addr, to_string(addr##_ep))\n\n#define CHECK_COMPARISON(addr1, addr2) \\\n CAF_CHECK_GREATER(addr2##_ep, addr1##_ep); \\\n CAF_CHECK_GREATER_OR_EQUAL(addr2##_ep, addr1##_ep); \\\n CAF_CHECK_GREATER_OR_EQUAL(addr1##_ep, addr1##_ep); \\\n CAF_CHECK_GREATER_OR_EQUAL(addr2##_ep, addr2##_ep); \\\n CAF_CHECK_EQUAL(addr1##_ep, addr1##_ep); \\\n CAF_CHECK_EQUAL(addr2##_ep, addr2##_ep); \\\n CAF_CHECK_LESS_OR_EQUAL(addr1##_ep, addr2##_ep); \\\n CAF_CHECK_LESS_OR_EQUAL(addr1##_ep, addr1##_ep); \\\n CAF_CHECK_LESS_OR_EQUAL(addr2##_ep, addr2##_ep); \\\n CAF_CHECK_NOT_EQUAL(addr1##_ep, addr2##_ep); \\\n CAF_CHECK_NOT_EQUAL(addr2##_ep, addr1##_ep);\n\n#define CHECK_SERIALIZATION(addr) \\\n CAF_CHECK_EQUAL(addr##_ep, roundtrip(addr##_ep))\n\n} \/\/ namespace\n\nCAF_TEST_FIXTURE_SCOPE(comparison_scope, fixture)\n\nCAF_TEST(constructing assigning and hash_code) {\n const uint16_t port = 8888;\n ipv6_address::array_type bytes{0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1};\n auto addr = ipv6_address{bytes};\n ipv6_endpoint ep1(addr, port);\n CAF_CHECK_EQUAL(ep1.address(), addr);\n CAF_CHECK_EQUAL(ep1.port(), port);\n ipv6_endpoint ep2;\n ep2.address(addr);\n ep2.port(port);\n CAF_CHECK_EQUAL(ep2.address(), addr);\n CAF_CHECK_EQUAL(ep2.port(), port);\n CAF_CHECK_EQUAL(ep1, ep2);\n CAF_CHECK_EQUAL(ep1.hash_code(), ep2.hash_code());\n}\n\nCAF_TEST(to_string) {\n CHECK_TO_STRING(\"[::1]:8888\");\n CHECK_TO_STRING(\"[4e::d00:0:ed00:0:1]:1234\");\n CHECK_TO_STRING(\"[::1]:1111\");\n CHECK_TO_STRING(\"[4432::33:1]:8732\");\n CHECK_TO_STRING(\"[::2]:8888\");\n CHECK_TO_STRING(\"[4f::d00:12:ed00:0:1]:1234\");\n CHECK_TO_STRING(\"[4f::1]:2222\");\n CHECK_TO_STRING(\"[4432:8d::33:1]:8732\");\n CHECK_TO_STRING(\"[4e::d00:0:ed00:0:1]:5678\");\n CHECK_TO_STRING(\"[::1]:2221\");\n CHECK_TO_STRING(\"[::1]:2222\");\n CHECK_TO_STRING(\"[4432::33:1]:872\");\n CHECK_TO_STRING(\"[4432::33:1]:999\");\n}\n\nCAF_TEST(comparison) {\n CHECK_COMPARISON(\"[::1]:8888\", \"[::2]:8888\");\n CHECK_COMPARISON(\"[4e::d00:0:ed00:0:1]:1234\", \"[4f::d00:12:ed00:0:1]:1234\");\n CHECK_COMPARISON(\"[::1]:1111\", \"[4f::1]:2222\");\n CHECK_COMPARISON(\"[4432::33:1]:8732\", \"[4432:8d::33:1]:8732\");\n CHECK_COMPARISON(\"[::1]:1111\", \"[::1]:8888\");\n CHECK_COMPARISON(\"[4e::d00:0:ed00:0:1]:1234\", \"[4e::d00:0:ed00:0:1]:5678\");\n CHECK_COMPARISON(\"[::1]:2221\", \"[::1]:2222\");\n CHECK_COMPARISON(\"[4432::33:1]:872\", \"[4432::33:1]:999\");\n}\n\nCAF_TEST(serialization) {\n CHECK_SERIALIZATION(\"[::1]:8888\");\n CHECK_SERIALIZATION(\"[4e::d00:0:ed00:0:1]:1234\");\n CHECK_SERIALIZATION(\"[::1]:1111\");\n CHECK_SERIALIZATION(\"[4432::33:1]:8732\");\n CHECK_SERIALIZATION(\"[::2]:8888\");\n CHECK_SERIALIZATION(\"[4f::d00:12:ed00:0:1]:1234\");\n CHECK_SERIALIZATION(\"[4f::1]:2222\");\n CHECK_SERIALIZATION(\"[4432:8d::33:1]:8732\");\n CHECK_SERIALIZATION(\"[4e::d00:0:ed00:0:1]:5678\");\n CHECK_SERIALIZATION(\"[::1]:2221\");\n CHECK_SERIALIZATION(\"[::1]:2222\");\n CHECK_SERIALIZATION(\"[4432::33:1]:872\");\n CHECK_SERIALIZATION(\"[4432::33:1]:999\");\n}\n\nCAF_TEST_FIXTURE_SCOPE_END()<commit_msg>Add newline<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2019 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#define CAF_SUITE ipv6_endpoint\n\n#include \"caf\/ipv6_endpoint.hpp\"\n\n#include \"caf\/test\/unit_test.hpp\"\n\n#include <cassert>\n#include <vector>\n\n#include \"caf\/actor_system.hpp\"\n#include \"caf\/actor_system_config.hpp\"\n#include \"caf\/binary_deserializer.hpp\"\n#include \"caf\/byte.hpp\"\n#include \"caf\/ipv6_address.hpp\"\n#include \"caf\/serializer_impl.hpp\"\n#include \"caf\/span.hpp\"\n\nusing namespace caf;\n\nnamespace {\n\nipv6_endpoint operator\"\" _ep(const char* str, size_t) {\n union {\n std::array<uint8_t, 16> xs_bytes;\n std::array<uint16_t, 8> xs;\n };\n union {\n std::array<uint8_t, 16> ys_bytes;\n std::array<uint16_t, 8> ys;\n };\n memset(xs_bytes.data(), 0, xs_bytes.size());\n memset(ys_bytes.data(), 0, xs_bytes.size());\n assert(*str == '[');\n ++str;\n char* next = nullptr;\n auto pull = [&] {\n auto x = static_cast<uint16_t>(strtol(str, &next, 16));\n return detail::to_network_order(x);\n };\n size_t n = 0;\n do {\n xs[n++] = pull();\n assert(next != nullptr);\n str = next + 1;\n } while (*str != ':' && *str != ']');\n if (*str == ':') {\n ++str;\n do {\n ys[0] = pull();\n std::rotate(ys.begin(), ys.begin() + 1, ys.end());\n assert(next != nullptr);\n str = next + 1;\n } while (*next != ']');\n }\n assert(*next == ']');\n assert(*str == ':');\n ++str;\n auto port = static_cast<uint16_t>(strtol(str, nullptr, 10));\n std::array<uint8_t, 16> bytes;\n for (size_t i = 0; i < 16; ++i)\n bytes[i] = xs_bytes[i] | ys_bytes[i];\n return ipv6_endpoint{ipv6_address{bytes}, port};\n}\n\nstruct fixture {\n actor_system_config cfg;\n actor_system sys{cfg};\n\n template <class T>\n T roundtrip(T x) {\n using container_type = std::vector<byte>;\n container_type buf;\n serializer_impl<container_type> sink(sys, buf);\n if (auto err = sink(x))\n CAF_FAIL(\"serialization failed: \" << sys.render(err));\n binary_deserializer source(sys, make_span(buf));\n T y;\n if (auto err = source(y))\n CAF_FAIL(\"deserialization failed: \" << sys.render(err));\n return y;\n }\n};\n\n#define CHECK_TO_STRING(addr) CAF_CHECK_EQUAL(addr, to_string(addr##_ep))\n\n#define CHECK_COMPARISON(addr1, addr2) \\\n CAF_CHECK_GREATER(addr2##_ep, addr1##_ep); \\\n CAF_CHECK_GREATER_OR_EQUAL(addr2##_ep, addr1##_ep); \\\n CAF_CHECK_GREATER_OR_EQUAL(addr1##_ep, addr1##_ep); \\\n CAF_CHECK_GREATER_OR_EQUAL(addr2##_ep, addr2##_ep); \\\n CAF_CHECK_EQUAL(addr1##_ep, addr1##_ep); \\\n CAF_CHECK_EQUAL(addr2##_ep, addr2##_ep); \\\n CAF_CHECK_LESS_OR_EQUAL(addr1##_ep, addr2##_ep); \\\n CAF_CHECK_LESS_OR_EQUAL(addr1##_ep, addr1##_ep); \\\n CAF_CHECK_LESS_OR_EQUAL(addr2##_ep, addr2##_ep); \\\n CAF_CHECK_NOT_EQUAL(addr1##_ep, addr2##_ep); \\\n CAF_CHECK_NOT_EQUAL(addr2##_ep, addr1##_ep);\n\n#define CHECK_SERIALIZATION(addr) \\\n CAF_CHECK_EQUAL(addr##_ep, roundtrip(addr##_ep))\n\n} \/\/ namespace\n\nCAF_TEST_FIXTURE_SCOPE(comparison_scope, fixture)\n\nCAF_TEST(constructing assigning and hash_code) {\n const uint16_t port = 8888;\n ipv6_address::array_type bytes{0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1};\n auto addr = ipv6_address{bytes};\n ipv6_endpoint ep1(addr, port);\n CAF_CHECK_EQUAL(ep1.address(), addr);\n CAF_CHECK_EQUAL(ep1.port(), port);\n ipv6_endpoint ep2;\n ep2.address(addr);\n ep2.port(port);\n CAF_CHECK_EQUAL(ep2.address(), addr);\n CAF_CHECK_EQUAL(ep2.port(), port);\n CAF_CHECK_EQUAL(ep1, ep2);\n CAF_CHECK_EQUAL(ep1.hash_code(), ep2.hash_code());\n}\n\nCAF_TEST(to_string) {\n CHECK_TO_STRING(\"[::1]:8888\");\n CHECK_TO_STRING(\"[4e::d00:0:ed00:0:1]:1234\");\n CHECK_TO_STRING(\"[::1]:1111\");\n CHECK_TO_STRING(\"[4432::33:1]:8732\");\n CHECK_TO_STRING(\"[::2]:8888\");\n CHECK_TO_STRING(\"[4f::d00:12:ed00:0:1]:1234\");\n CHECK_TO_STRING(\"[4f::1]:2222\");\n CHECK_TO_STRING(\"[4432:8d::33:1]:8732\");\n CHECK_TO_STRING(\"[4e::d00:0:ed00:0:1]:5678\");\n CHECK_TO_STRING(\"[::1]:2221\");\n CHECK_TO_STRING(\"[::1]:2222\");\n CHECK_TO_STRING(\"[4432::33:1]:872\");\n CHECK_TO_STRING(\"[4432::33:1]:999\");\n}\n\nCAF_TEST(comparison) {\n CHECK_COMPARISON(\"[::1]:8888\", \"[::2]:8888\");\n CHECK_COMPARISON(\"[4e::d00:0:ed00:0:1]:1234\", \"[4f::d00:12:ed00:0:1]:1234\");\n CHECK_COMPARISON(\"[::1]:1111\", \"[4f::1]:2222\");\n CHECK_COMPARISON(\"[4432::33:1]:8732\", \"[4432:8d::33:1]:8732\");\n CHECK_COMPARISON(\"[::1]:1111\", \"[::1]:8888\");\n CHECK_COMPARISON(\"[4e::d00:0:ed00:0:1]:1234\", \"[4e::d00:0:ed00:0:1]:5678\");\n CHECK_COMPARISON(\"[::1]:2221\", \"[::1]:2222\");\n CHECK_COMPARISON(\"[4432::33:1]:872\", \"[4432::33:1]:999\");\n}\n\nCAF_TEST(serialization) {\n CHECK_SERIALIZATION(\"[::1]:8888\");\n CHECK_SERIALIZATION(\"[4e::d00:0:ed00:0:1]:1234\");\n CHECK_SERIALIZATION(\"[::1]:1111\");\n CHECK_SERIALIZATION(\"[4432::33:1]:8732\");\n CHECK_SERIALIZATION(\"[::2]:8888\");\n CHECK_SERIALIZATION(\"[4f::d00:12:ed00:0:1]:1234\");\n CHECK_SERIALIZATION(\"[4f::1]:2222\");\n CHECK_SERIALIZATION(\"[4432:8d::33:1]:8732\");\n CHECK_SERIALIZATION(\"[4e::d00:0:ed00:0:1]:5678\");\n CHECK_SERIALIZATION(\"[::1]:2221\");\n CHECK_SERIALIZATION(\"[::1]:2222\");\n CHECK_SERIALIZATION(\"[4432::33:1]:872\");\n CHECK_SERIALIZATION(\"[4432::33:1]:999\");\n}\n\nCAF_TEST_FIXTURE_SCOPE_END()\n<|endoftext|>"} {"text":"<commit_before>\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n * Gearmand client and server library.\n *\n * Copyright (C) 2011-2013 Data Differential, http:\/\/datadifferential.com\/\n * Copyright (C) 2008 Brian Aker, Eric Day\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:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * 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 *\/\n\n#pragma once\n\n#include \"libgearman\/allocator.hpp\" \n#include \"libgearman\/server_options.hpp\"\n#include \"libgearman\/interface\/packet.hpp\"\n#include \"libgearman\/interface\/error.hpp\"\n#include \"libgearman\/vector.h\" \n#include \"libgearman\/assert.hpp\" \n#include \"libgearman\/ssl.h\"\n\nenum universal_options_t\n{\n GEARMAN_UNIVERSAL_NON_BLOCKING,\n GEARMAN_UNIVERSAL_DONT_TRACK_PACKETS,\n GEARMAN_UNIVERSAL_IDENTIFY,\n GEARMAN_UNIVERSAL_MAX\n};\n\n\/**\n @todo this is only used by the server and should be made private.\n *\/\ntypedef struct gearman_connection_st gearman_connection_st;\ntypedef gearman_return_t (gearman_event_watch_fn)(gearman_connection_st *con,\n short events, void *context);\n\nstruct gearman_universal_st : public error_st\n{\n struct Options {\n bool dont_track_packets;\n bool non_blocking;\n bool no_new_data;\n bool _ssl;\n\n Options() :\n dont_track_packets(false),\n non_blocking(false),\n no_new_data(false),\n _ssl(false)\n { }\n } options;\n gearman_verbose_t verbose;\n uint32_t con_count;\n uint32_t packet_count;\n uint32_t pfds_size;\n uint32_t sending;\n int timeout; \/\/ Connection timeout.\n gearman_connection_st *con_list;\n gearman_server_options_st *server_options_list;\n gearman_packet_st *packet_list;\n struct pollfd *pfds;\n gearman_log_fn *log_fn;\n void *log_context;\n gearman_allocator_t allocator;\n struct gearman_vector_st *_identifier;\n struct gearman_vector_st *_namespace;\n SSL_CTX* _ctx_ssl;\n struct error_st _error;\n int wakeup_fd[2];\n\n bool ssl() const\n {\n return options._ssl;\n }\n\n void ssl(bool ssl_)\n {\n options._ssl= ssl_;\n }\n\n private:\n void close_wakeup();\n\n public:\n bool wakeup(bool);\n bool has_wakeup() const\n {\n return wakeup_fd[0] != INVALID_SOCKET;\n }\n\n bool is_non_blocking() const\n {\n return options.non_blocking;\n }\n\n void non_blocking(bool arg_)\n {\n options.non_blocking= arg_;\n }\n\n const char *error() const\n {\n if (_error.error() == NULL)\n {\n if (_error.error_code() != GEARMAN_SUCCESS)\n {\n return gearman_strerror(_error.error_code());\n }\n\n return NULL;\n }\n\n return _error.error();\n }\n\n gearman_return_t error_code() const\n {\n return _error.error_code();\n }\n\n gearman_return_t error_code(const gearman_return_t rc)\n {\n return _error.error_code(rc);\n }\n\n int last_errno() const\n {\n return _error.system_error();\n }\n\n void last_errno(const int last_errno_)\n {\n _error.system_error(last_errno_);\n }\n\n bool has_connections() const\n {\n return con_count;\n }\n\n void reset_error()\n {\n _error.clear();\n }\n\n gearman_return_t option(const universal_options_t& option_, bool value);\n\n gearman_universal_st(const universal_options_t *options_= NULL) :\n verbose(GEARMAN_VERBOSE_NEVER),\n con_count(0),\n packet_count(0),\n pfds_size(0),\n sending(0),\n timeout(-1),\n con_list(NULL),\n server_options_list(NULL),\n packet_list(NULL),\n pfds(NULL),\n log_fn(NULL),\n log_context(NULL),\n allocator(gearman_default_allocator()),\n _identifier(NULL),\n _namespace(NULL),\n _ctx_ssl(NULL)\n {\n wakeup_fd[0]= INVALID_SOCKET;\n wakeup_fd[1]= INVALID_SOCKET;\n\n if (options_)\n {\n while (*options_ != GEARMAN_UNIVERSAL_MAX)\n {\n \/**\n @note Check for bad value, refactor gearman_add_options().\n *\/\n (void)option(*options_, true);\n options_++;\n }\n }\n }\n\n const char* ssl_ca_file() const\n {\n if (getenv(\"GEARMAND_CA_CERTIFICATE\"))\n {\n return getenv(\"GEARMAND_CA_CERTIFICATE\");\n }\n\n return GEARMAND_CA_CERTIFICATE;\n }\n\n const char* ssl_certificate() const\n {\n if (getenv(\"GEARMAN_CLIENT_PEM\"))\n {\n return getenv(\"GEARMAN_CLIENT_PEM\");\n }\n\n return GEARMAN_CLIENT_PEM;\n }\n\n const char* ssl_key() const\n {\n if (getenv(\"GEARMAN_CLIENT_KEY\"))\n {\n return getenv(\"GEARMAN_CLIENT_KEY\");\n }\n\n return GEARMAN_CLIENT_KEY;\n }\n\nprivate:\n bool init_ssl();\n\npublic:\n SSL_CTX* ctx_ssl() \n {\n if (ssl())\n {\n if (_ctx_ssl == NULL)\n {\n if (init_ssl() == false)\n {\n abort();\n }\n }\n assert(_ctx_ssl);\n\n return _ctx_ssl;\n }\n\n return NULL;\n }\n\n ~gearman_universal_st();\n\n void identifier(const char *identifier_, const size_t identifier_size_);\n bool has_identifier() const\n {\n return _identifier;\n }\n\n void flush();\n void reset();\n};\n\nstatic inline bool gearman_universal_is_non_blocking(gearman_universal_st &self)\n{\n return self.is_non_blocking();\n}\n\nstatic inline const char *gearman_universal_error(const gearman_universal_st &self)\n{\n return self.error();\n}\n\nstatic inline gearman_return_t gearman_universal_error_code(const gearman_universal_st &self)\n{\n return self.error_code();\n}\n\nstatic inline int gearman_universal_errno(const gearman_universal_st &self)\n{\n return self.last_errno();\n}\n\nstatic inline void universal_reset_error(gearman_universal_st &self)\n{\n self.reset_error();\n}\n<commit_msg>gearman_universal_st refactoring<commit_after>\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n * Gearmand client and server library.\n *\n * Copyright (C) 2011-2013 Data Differential, http:\/\/datadifferential.com\/\n * Copyright (C) 2008 Brian Aker, Eric Day\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:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * 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 *\/\n\n#pragma once\n\n#include \"libgearman\/allocator.hpp\" \n#include \"libgearman\/server_options.hpp\"\n#include \"libgearman\/interface\/packet.hpp\"\n#include \"libgearman\/interface\/error.hpp\"\n#include \"libgearman\/vector.h\" \n#include \"libgearman\/assert.hpp\" \n#include \"libgearman\/ssl.h\"\n\nenum universal_options_t\n{\n GEARMAN_UNIVERSAL_NON_BLOCKING,\n GEARMAN_UNIVERSAL_DONT_TRACK_PACKETS,\n GEARMAN_UNIVERSAL_IDENTIFY,\n GEARMAN_UNIVERSAL_MAX\n};\n\n\/**\n @todo this is only used by the server and should be made private.\n *\/\ntypedef struct gearman_connection_st gearman_connection_st;\ntypedef gearman_return_t (gearman_event_watch_fn)(gearman_connection_st *con,\n short events, void *context);\n\nstruct gearman_universal_st : public error_st\n{\n struct Options {\n bool dont_track_packets;\n bool non_blocking;\n bool no_new_data;\n bool _ssl;\n\n Options() :\n dont_track_packets{false},\n non_blocking{false},\n no_new_data{false},\n _ssl{false}\n { }\n } options;\n gearman_verbose_t verbose;\n uint32_t con_count;\n uint32_t packet_count;\n uint32_t pfds_size;\n uint32_t sending;\n int timeout; \/\/ Connection timeout.\n gearman_connection_st *con_list;\n gearman_server_options_st *server_options_list;\n gearman_packet_st *packet_list;\n struct pollfd *pfds;\n gearman_log_fn *log_fn;\n void *log_context;\n gearman_allocator_t allocator;\n struct gearman_vector_st *_identifier;\n struct gearman_vector_st *_namespace;\n SSL_CTX* _ctx_ssl;\n struct error_st _error;\n int wakeup_fd[2];\n\n bool ssl() const\n {\n return options._ssl;\n }\n\n void ssl(bool ssl_)\n {\n options._ssl= ssl_;\n }\n\n private:\n void close_wakeup();\n\n public:\n bool wakeup(bool);\n bool has_wakeup() const\n {\n return wakeup_fd[0] != INVALID_SOCKET;\n }\n\n bool is_non_blocking() const\n {\n return options.non_blocking;\n }\n\n void non_blocking(bool arg_)\n {\n options.non_blocking= arg_;\n }\n\n const char *error() const\n {\n if (_error.error() == nullptr)\n {\n if (_error.error_code() != GEARMAN_SUCCESS)\n {\n return gearman_strerror(_error.error_code());\n }\n\n return nullptr;\n }\n\n return _error.error();\n }\n\n gearman_return_t error_code() const\n {\n return _error.error_code();\n }\n\n gearman_return_t error_code(const gearman_return_t rc)\n {\n return _error.error_code(rc);\n }\n\n int last_errno() const\n {\n return _error.system_error();\n }\n\n void last_errno(const int last_errno_)\n {\n _error.system_error(last_errno_);\n }\n\n bool has_connections() const\n {\n return con_count;\n }\n\n void reset_error()\n {\n _error.clear();\n }\n\n gearman_return_t option(const universal_options_t& option_, bool value);\n\n gearman_universal_st(const universal_options_t *options_= nullptr) :\n verbose(GEARMAN_VERBOSE_NEVER),\n con_count(0),\n packet_count(0),\n pfds_size(0),\n sending(0),\n timeout{-1},\n con_list(nullptr),\n server_options_list(nullptr),\n packet_list(nullptr),\n pfds(nullptr),\n log_fn(nullptr),\n log_context(nullptr),\n allocator(gearman_default_allocator()),\n _identifier(nullptr),\n _namespace(nullptr),\n _ctx_ssl(nullptr)\n {\n wakeup_fd[0]= INVALID_SOCKET;\n wakeup_fd[1]= INVALID_SOCKET;\n\n if (options_)\n {\n while (*options_ != GEARMAN_UNIVERSAL_MAX)\n {\n \/**\n @note Check for bad value, refactor gearman_add_options().\n *\/\n (void)option(*options_, true);\n options_++;\n }\n }\n }\n\n const char* ssl_ca_file() const\n {\n if (getenv(\"GEARMAND_CA_CERTIFICATE\"))\n {\n return getenv(\"GEARMAND_CA_CERTIFICATE\");\n }\n\n return GEARMAND_CA_CERTIFICATE;\n }\n\n const char* ssl_certificate() const\n {\n if (getenv(\"GEARMAN_CLIENT_PEM\"))\n {\n return getenv(\"GEARMAN_CLIENT_PEM\");\n }\n\n return GEARMAN_CLIENT_PEM;\n }\n\n const char* ssl_key() const\n {\n if (getenv(\"GEARMAN_CLIENT_KEY\"))\n {\n return getenv(\"GEARMAN_CLIENT_KEY\");\n }\n\n return GEARMAN_CLIENT_KEY;\n }\n\nprivate:\n bool init_ssl();\n\npublic:\n SSL_CTX* ctx_ssl() \n {\n if (ssl())\n {\n if (!_ctx_ssl)\n {\n if (init_ssl() == false)\n {\n abort();\n }\n }\n assert(_ctx_ssl);\n\n return _ctx_ssl;\n }\n\n return nullptr;\n }\n\n ~gearman_universal_st();\n\n void identifier(const char *identifier_, const size_t identifier_size_);\n bool has_identifier() const\n {\n return _identifier;\n }\n\n void flush();\n void reset();\n};\n\nstatic inline bool gearman_universal_is_non_blocking(gearman_universal_st &self)\n{\n return self.is_non_blocking();\n}\n\nstatic inline const char *gearman_universal_error(const gearman_universal_st &self)\n{\n return self.error();\n}\n\nstatic inline gearman_return_t gearman_universal_error_code(const gearman_universal_st &self)\n{\n return self.error_code();\n}\n\nstatic inline int gearman_universal_errno(const gearman_universal_st &self)\n{\n return self.last_errno();\n}\n\nstatic inline void universal_reset_error(gearman_universal_st &self)\n{\n self.reset_error();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010-2011 Dmitry Marakasov\n *\n * This file is part of glosm.\n *\n * glosm 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 3 of the License, or\n * (at your option) any later version.\n *\n * glosm 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 glosm. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <glosm\/TileManager.hh>\n\n#include <glosm\/Viewer.hh>\n#include <glosm\/Geometry.hh>\n#include <glosm\/GeometryDatasource.hh>\n#include <glosm\/Tile.hh>\n#include <glosm\/Exception.hh>\n\n#include <glosm\/util\/gl.h>\n\n#include <cassert>\n\nTileManager::TileId::TileId(int lev, int xx, int yy) : level(lev), x(xx), y(yy) {\n}\n\nbool TileManager::TileId::operator<(const TileId& other) const {\n\tif (level < other.level) return true;\n\tif (level > other.level) return false;\n\tif (x < other.x) return true;\n\tif (x > other.x) return false;\n\treturn y < other.y;\n}\n\nTileManager::TileManager(const Projection projection): projection_(projection) {\n\tint errn;\n\n\tif ((errn = pthread_mutex_init(&tiles_mutex_, 0)) != 0)\n\t\tthrow SystemError(errn) << \"pthread_mutex_init failed\";\n\n\tif ((errn = pthread_mutex_init(&queue_mutex_, 0)) != 0) {\n\t\tpthread_mutex_destroy(&tiles_mutex_);\n\t\tthrow SystemError(errn) << \"pthread_mutex_init failed\";\n\t}\n\n\tif ((errn = pthread_cond_init(&queue_cond_, 0)) != 0) {\n\t\tpthread_mutex_destroy(&tiles_mutex_);\n\t\tpthread_mutex_destroy(&queue_mutex_);\n\t\tthrow SystemError(errn) << \"pthread_cond_init failed\";\n\t}\n\n\tif ((errn = pthread_create(&loading_thread_, NULL, LoadingThreadFuncWrapper, (void*)this)) != 0) {\n\t\tpthread_mutex_destroy(&tiles_mutex_);\n\t\tpthread_mutex_destroy(&queue_mutex_);\n\t\tpthread_cond_destroy(&queue_cond_);\n\t\tthrow SystemError(errn) << \"pthread_create failed\";\n\t}\n\n\ttarget_level_ = 0;\n\tgeneration_ = 0;\n\tthread_die_flag_ = false;\n}\n\nTileManager::~TileManager() {\n\tthread_die_flag_ = true;\n\tpthread_cond_signal(&queue_cond_);\n\n\tpthread_join(loading_thread_, NULL);\n\n\tpthread_cond_destroy(&queue_cond_);\n\tpthread_mutex_destroy(&queue_mutex_);\n\tpthread_mutex_destroy(&tiles_mutex_);\n\n\tfor (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ++i)\n\t\tdelete i->second.tile;\n}\n\nint TileManager::LoadTile(const TileId& id, const BBoxi& bbox, int flags) {\n\tint ret = 0;\n\tif (flags & SYNC) {\n\t\tTile* tile = SpawnTile(bbox);\n\t\t\/* TODO: we may call tile->BindBuffers here *\/\n\t\ttiles_.insert(std::make_pair(id, TileData(tile, generation_)));\n\t} else {\n\t\tbool added = false;\n\t\tpthread_mutex_lock(&queue_mutex_);\n\t\t\/* don't needlessly enqueue more tiles that we can process in a frame time*\/\n\t\t\/* TODO: this should be user-settable, as we don't necessarily do GC\/loading\n\t\t * every frame *\/\n\t\tif (loading_.find(id) == loading_.end() && queue_.size() < 2) {\n\t\t\tadded = true;\n\t\t\tqueue_.push_back(TileTask(id, bbox));\n\t\t}\n\t\tret = queue_.size();\n\t\tpthread_mutex_unlock(&queue_mutex_);\n\t\tif (added)\n\t\t\tpthread_cond_signal(&queue_cond_);\n\t}\n\n\treturn ret;\n}\n\n\/*\n * recursive quadtree processing\n *\/\n\nbool TileManager::LoadTiles(const BBoxi& bbox, int flags, int level, int x, int y) {\n\tif (level == target_level_) {\n\t\tTilesMap::iterator thistile = tiles_.find(TileId(level, x, y));\n\n\t\tif (thistile != tiles_.end()) {\n\t\t\tthistile->second.generation = generation_;\n\t\t\treturn true; \/* tile already loaded *\/\n\t\t}\n\n\t\tBBoxi bbox = BBoxi::ForGeoTile(level, x, y);\n\n\t\tLoadTile(TileId(level, x, y), BBoxi::ForGeoTile(level, x, y), flags);\n\n\t\t\/* no deeper recursion *\/\n\t\treturn true;\n\t}\n\n\t\/* children *\/\n\tfor (int d = 0; d < 4; ++d) {\n\t\tint xx = x * 2 + d % 2;\n\t\tint yy = y * 2 + d \/ 2;\n\t\tif (BBoxi::ForGeoTile(level + 1, xx, yy).Intersects(bbox)) {\n\t\t\tif (!LoadTiles(bbox, flags, level + 1, xx, yy))\n\t\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\/*\n * loading queue - related\n *\/\n\nvoid TileManager::LoadingThreadFunc() {\n\tpthread_mutex_lock(&queue_mutex_);\n\twhile (!thread_die_flag_) {\n\t\t\/* found nothing, sleep *\/\n\t\tif (queue_.empty()) {\n\t\t\tpthread_cond_wait(&queue_cond_, &queue_mutex_);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/* take a task from the queue *\/\n\t\tTileTask task = queue_.front();\n\t\tqueue_.pop_front();\n\n\t\t\/* mark it as loading *\/\n\t\tstd::pair<LoadingSet::iterator, bool> pair = loading_.insert(task.id);\n\t\tassert(pair.second);\n\n\t\tpthread_mutex_unlock(&queue_mutex_);\n\n\t\t\/* load tile *\/\n\t\tTile* tile = SpawnTile(task.bbox);\n\n\t\tpthread_mutex_lock(&tiles_mutex_);\n\t\ttiles_.insert(std::make_pair(task.id, TileData(tile, generation_)));\n\t\tpthread_mutex_unlock(&tiles_mutex_);\n\n\t\tpthread_mutex_lock(&queue_mutex_);\n\t\tloading_.erase(pair.first);\n\t}\n\tpthread_mutex_unlock(&queue_mutex_);\n}\n\nvoid* TileManager::LoadingThreadFuncWrapper(void* arg) {\n\tstatic_cast<TileManager*>(arg)->LoadingThreadFunc();\n\treturn NULL;\n}\n\n\/*\n * protected interface\n *\/\n\nvoid TileManager::Render(const Viewer& viewer) {\n\tpthread_mutex_lock(&tiles_mutex_);\n\n\t\/* and render them *\/\n\tfor (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ++i) {\n\t\tif (i->second.generation != generation_)\n\t\t\tcontinue;\n\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglPushMatrix();\n\n\t\t\/* prepare modelview matrix for the tile: position\n\t\t * it in the right place given that viewer is always\n\t\t * at (0, 0, 0) *\/\n\t\tVector3f offset = projection_.Project(i->second.tile->GetReference(), Vector2i(viewer.GetPos(projection_))) +\n\t\t\t\tprojection_.Project(Vector2i(viewer.GetPos(projection_)), viewer.GetPos(projection_));\n\n\t\tglTranslatef(offset.x, offset.y, offset.z);\n\n\t\t\/* same for rotation *\/\n\t\tVector3i ref = i->second.tile->GetReference();\n\t\tVector3i pos = viewer.GetPos(projection_);\n\n\t\t\/* normal at tile's reference point *\/\n\t\tVector3d refnormal = (\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, ref.y, std::numeric_limits<osmint_t>::max()), pos) -\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, ref.y, 0), pos)\n\t\t\t).Normalized();\n\n\t\t\/* normal at reference point projected to equator *\/\n\t\tVector3d refeqnormal = (\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, 0, std::numeric_limits<osmint_t>::max()), pos) -\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, 0, 0), pos)\n\t\t\t).Normalized();\n\n\t\t\/* normal at north pole *\/\n\t\tVector3d polenormal = (\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, 900000000, std::numeric_limits<osmint_t>::max()), pos) -\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, 900000000, 0), pos)\n\t\t\t).Normalized();\n\n\t\t\/* XXX: IsValid() check basically detects\n\t\t * MercatorProjection and does no rotation for it.\n\t\t * While is's ok for now, this may need more generic\n\t\t * approach in future *\/\n\t\tif (polenormal.IsValid()) {\n\t\t\tVector3d side = refnormal.CrossProduct(polenormal).Normalized();\n\n\t\t\tglRotatef((double)((osmlong_t)ref.y - (osmlong_t)pos.y) \/ 10000000.0, side.x, side.y, side.z);\n\t\t\tglRotatef((double)((osmlong_t)ref.x - (osmlong_t)pos.x) \/ 10000000.0, polenormal.x, polenormal.y, polenormal.z);\n\t\t}\n\n\t\ti->second.tile->Render();\n\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglPopMatrix();\n\t}\n\n\tpthread_mutex_unlock(&tiles_mutex_);\n}\n\n\/*\n * public interface\n *\/\n\nvoid TileManager::SetTargetLevel(int level) {\n\ttarget_level_ = level;\n}\n\nvoid TileManager::RequestVisible(const BBoxi& bbox, int flags) {\n\tif (!flags & SYNC) {\n\t\tpthread_mutex_lock(&queue_mutex_);\n\t\tqueue_.clear();\n\t\tpthread_mutex_unlock(&queue_mutex_);\n\t}\n\n\tpthread_mutex_lock(&tiles_mutex_);\n\tif (flags & BLOB)\n\t\tLoadTile(TileId(0, 0, 0), bbox, flags);\n\telse\n\t\tLoadTiles(bbox, flags);\n\tpthread_mutex_unlock(&tiles_mutex_);\n}\n\nvoid TileManager::GarbageCollect() {\n\t\/* TODO: may put deletable tiles into list and delete after\n\t * unlocking mutex for less contention *\/\n\tpthread_mutex_lock(&tiles_mutex_);\n\tfor (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ) {\n\t\tif (i->second.generation != generation_) {\n\t\t\tdelete i->second.tile;\n\t\t\tTilesMap::iterator tmp = i++;\n\t\t\ttiles_.erase(tmp);\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n\tgeneration_++;\n\tpthread_mutex_unlock(&tiles_mutex_);\n}\n<commit_msg>Fix uninitialized variable usage<commit_after>\/*\n * Copyright (C) 2010-2011 Dmitry Marakasov\n *\n * This file is part of glosm.\n *\n * glosm 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 3 of the License, or\n * (at your option) any later version.\n *\n * glosm 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 glosm. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <glosm\/TileManager.hh>\n\n#include <glosm\/Viewer.hh>\n#include <glosm\/Geometry.hh>\n#include <glosm\/GeometryDatasource.hh>\n#include <glosm\/Tile.hh>\n#include <glosm\/Exception.hh>\n\n#include <glosm\/util\/gl.h>\n\n#include <cassert>\n\nTileManager::TileId::TileId(int lev, int xx, int yy) : level(lev), x(xx), y(yy) {\n}\n\nbool TileManager::TileId::operator<(const TileId& other) const {\n\tif (level < other.level) return true;\n\tif (level > other.level) return false;\n\tif (x < other.x) return true;\n\tif (x > other.x) return false;\n\treturn y < other.y;\n}\n\nTileManager::TileManager(const Projection projection): projection_(projection) {\n\ttarget_level_ = 0;\n\tgeneration_ = 0;\n\tthread_die_flag_ = false;\n\n\tint errn;\n\n\tif ((errn = pthread_mutex_init(&tiles_mutex_, 0)) != 0)\n\t\tthrow SystemError(errn) << \"pthread_mutex_init failed\";\n\n\tif ((errn = pthread_mutex_init(&queue_mutex_, 0)) != 0) {\n\t\tpthread_mutex_destroy(&tiles_mutex_);\n\t\tthrow SystemError(errn) << \"pthread_mutex_init failed\";\n\t}\n\n\tif ((errn = pthread_cond_init(&queue_cond_, 0)) != 0) {\n\t\tpthread_mutex_destroy(&tiles_mutex_);\n\t\tpthread_mutex_destroy(&queue_mutex_);\n\t\tthrow SystemError(errn) << \"pthread_cond_init failed\";\n\t}\n\n\tif ((errn = pthread_create(&loading_thread_, NULL, LoadingThreadFuncWrapper, (void*)this)) != 0) {\n\t\tpthread_mutex_destroy(&tiles_mutex_);\n\t\tpthread_mutex_destroy(&queue_mutex_);\n\t\tpthread_cond_destroy(&queue_cond_);\n\t\tthrow SystemError(errn) << \"pthread_create failed\";\n\t}\n}\n\nTileManager::~TileManager() {\n\tthread_die_flag_ = true;\n\tpthread_cond_signal(&queue_cond_);\n\n\t\/* TODO: check exit code *\/\n\tpthread_join(loading_thread_, NULL);\n\n\tpthread_cond_destroy(&queue_cond_);\n\tpthread_mutex_destroy(&queue_mutex_);\n\tpthread_mutex_destroy(&tiles_mutex_);\n\n\tfor (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ++i)\n\t\tdelete i->second.tile;\n}\n\nint TileManager::LoadTile(const TileId& id, const BBoxi& bbox, int flags) {\n\tint ret = 0;\n\tif (flags & SYNC) {\n\t\tTile* tile = SpawnTile(bbox);\n\t\t\/* TODO: we may call tile->BindBuffers here *\/\n\t\ttiles_.insert(std::make_pair(id, TileData(tile, generation_)));\n\t} else {\n\t\tbool added = false;\n\t\tpthread_mutex_lock(&queue_mutex_);\n\t\t\/* don't needlessly enqueue more tiles that we can process in a frame time*\/\n\t\t\/* TODO: this should be user-settable, as we don't necessarily do GC\/loading\n\t\t * every frame *\/\n\t\tif (loading_.find(id) == loading_.end() && queue_.size() < 2) {\n\t\t\tadded = true;\n\t\t\tqueue_.push_back(TileTask(id, bbox));\n\t\t}\n\t\tret = queue_.size();\n\t\tpthread_mutex_unlock(&queue_mutex_);\n\t\tif (added)\n\t\t\tpthread_cond_signal(&queue_cond_);\n\t}\n\n\treturn ret;\n}\n\n\/*\n * recursive quadtree processing\n *\/\n\nbool TileManager::LoadTiles(const BBoxi& bbox, int flags, int level, int x, int y) {\n\tif (level == target_level_) {\n\t\tTilesMap::iterator thistile = tiles_.find(TileId(level, x, y));\n\n\t\tif (thistile != tiles_.end()) {\n\t\t\tthistile->second.generation = generation_;\n\t\t\treturn true; \/* tile already loaded *\/\n\t\t}\n\n\t\tBBoxi bbox = BBoxi::ForGeoTile(level, x, y);\n\n\t\tLoadTile(TileId(level, x, y), BBoxi::ForGeoTile(level, x, y), flags);\n\n\t\t\/* no deeper recursion *\/\n\t\treturn true;\n\t}\n\n\t\/* children *\/\n\tfor (int d = 0; d < 4; ++d) {\n\t\tint xx = x * 2 + d % 2;\n\t\tint yy = y * 2 + d \/ 2;\n\t\tif (BBoxi::ForGeoTile(level + 1, xx, yy).Intersects(bbox)) {\n\t\t\tif (!LoadTiles(bbox, flags, level + 1, xx, yy))\n\t\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\/*\n * loading queue - related\n *\/\n\nvoid TileManager::LoadingThreadFunc() {\n\tpthread_mutex_lock(&queue_mutex_);\n\twhile (!thread_die_flag_) {\n\t\t\/* found nothing, sleep *\/\n\t\tif (queue_.empty()) {\n\t\t\tpthread_cond_wait(&queue_cond_, &queue_mutex_);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/* take a task from the queue *\/\n\t\tTileTask task = queue_.front();\n\t\tqueue_.pop_front();\n\n\t\t\/* mark it as loading *\/\n\t\tstd::pair<LoadingSet::iterator, bool> pair = loading_.insert(task.id);\n\t\tassert(pair.second);\n\n\t\tpthread_mutex_unlock(&queue_mutex_);\n\n\t\t\/* load tile *\/\n\t\tTile* tile = SpawnTile(task.bbox);\n\n\t\tpthread_mutex_lock(&tiles_mutex_);\n\t\ttiles_.insert(std::make_pair(task.id, TileData(tile, generation_)));\n\t\tpthread_mutex_unlock(&tiles_mutex_);\n\n\t\tpthread_mutex_lock(&queue_mutex_);\n\t\tloading_.erase(pair.first);\n\t}\n\tpthread_mutex_unlock(&queue_mutex_);\n}\n\nvoid* TileManager::LoadingThreadFuncWrapper(void* arg) {\n\tstatic_cast<TileManager*>(arg)->LoadingThreadFunc();\n\treturn NULL;\n}\n\n\/*\n * protected interface\n *\/\n\nvoid TileManager::Render(const Viewer& viewer) {\n\tpthread_mutex_lock(&tiles_mutex_);\n\n\t\/* and render them *\/\n\tfor (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ++i) {\n\t\tif (i->second.generation != generation_)\n\t\t\tcontinue;\n\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglPushMatrix();\n\n\t\t\/* prepare modelview matrix for the tile: position\n\t\t * it in the right place given that viewer is always\n\t\t * at (0, 0, 0) *\/\n\t\tVector3f offset = projection_.Project(i->second.tile->GetReference(), Vector2i(viewer.GetPos(projection_))) +\n\t\t\t\tprojection_.Project(Vector2i(viewer.GetPos(projection_)), viewer.GetPos(projection_));\n\n\t\tglTranslatef(offset.x, offset.y, offset.z);\n\n\t\t\/* same for rotation *\/\n\t\tVector3i ref = i->second.tile->GetReference();\n\t\tVector3i pos = viewer.GetPos(projection_);\n\n\t\t\/* normal at tile's reference point *\/\n\t\tVector3d refnormal = (\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, ref.y, std::numeric_limits<osmint_t>::max()), pos) -\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, ref.y, 0), pos)\n\t\t\t).Normalized();\n\n\t\t\/* normal at reference point projected to equator *\/\n\t\tVector3d refeqnormal = (\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, 0, std::numeric_limits<osmint_t>::max()), pos) -\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, 0, 0), pos)\n\t\t\t).Normalized();\n\n\t\t\/* normal at north pole *\/\n\t\tVector3d polenormal = (\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, 900000000, std::numeric_limits<osmint_t>::max()), pos) -\n\t\t\t\t(Vector3d)projection_.Project(Vector3i(ref.x, 900000000, 0), pos)\n\t\t\t).Normalized();\n\n\t\t\/* XXX: IsValid() check basically detects\n\t\t * MercatorProjection and does no rotation for it.\n\t\t * While is's ok for now, this may need more generic\n\t\t * approach in future *\/\n\t\tif (polenormal.IsValid()) {\n\t\t\tVector3d side = refnormal.CrossProduct(polenormal).Normalized();\n\n\t\t\tglRotatef((double)((osmlong_t)ref.y - (osmlong_t)pos.y) \/ 10000000.0, side.x, side.y, side.z);\n\t\t\tglRotatef((double)((osmlong_t)ref.x - (osmlong_t)pos.x) \/ 10000000.0, polenormal.x, polenormal.y, polenormal.z);\n\t\t}\n\n\t\ti->second.tile->Render();\n\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglPopMatrix();\n\t}\n\n\tpthread_mutex_unlock(&tiles_mutex_);\n}\n\n\/*\n * public interface\n *\/\n\nvoid TileManager::SetTargetLevel(int level) {\n\ttarget_level_ = level;\n}\n\nvoid TileManager::RequestVisible(const BBoxi& bbox, int flags) {\n\tif (!flags & SYNC) {\n\t\tpthread_mutex_lock(&queue_mutex_);\n\t\tqueue_.clear();\n\t\tpthread_mutex_unlock(&queue_mutex_);\n\t}\n\n\tpthread_mutex_lock(&tiles_mutex_);\n\tif (flags & BLOB)\n\t\tLoadTile(TileId(0, 0, 0), bbox, flags);\n\telse\n\t\tLoadTiles(bbox, flags);\n\tpthread_mutex_unlock(&tiles_mutex_);\n}\n\nvoid TileManager::GarbageCollect() {\n\t\/* TODO: may put deletable tiles into list and delete after\n\t * unlocking mutex for less contention *\/\n\tpthread_mutex_lock(&tiles_mutex_);\n\tfor (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ) {\n\t\tif (i->second.generation != generation_) {\n\t\t\tdelete i->second.tile;\n\t\t\tTilesMap::iterator tmp = i++;\n\t\t\ttiles_.erase(tmp);\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n\tgeneration_++;\n\tpthread_mutex_unlock(&tiles_mutex_);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 neurodata (http:\/\/neurodata.io\/)\n * Written by Disa Mhembere (disa@jhu.edu)\n *\n * This file is part of knor\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 CURRENT_KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"util.hpp\"\n#include <cassert>\n\nusing namespace knor::base;\n\nvoid test_hclust_floor() {\n assert(get_hclust_floor(1) == 1);\n assert(get_hclust_floor(2) == 2);\n assert(get_hclust_floor(3) == 2);\n assert(get_hclust_floor(4) == 4);\n assert(get_hclust_floor(5) == 4);\n assert(get_hclust_floor(6) == 4);\n assert(get_hclust_floor(7) == 4);\n assert(get_hclust_floor(8) == 8);\n assert(get_hclust_floor(9) == 8);\n assert(get_hclust_floor(10) == 8);\n assert(get_hclust_floor(15) == 8);\n assert(get_hclust_floor(16) == 16);\n assert(get_hclust_floor(20) == 16);\n assert(get_hclust_floor(27) == 16);\n assert(get_hclust_floor(31) == 16);\n assert(get_hclust_floor(32) == 32);\n printf(\"hclust_floor test OK ...\\n\");\n}\n\nvoid test_hclust_ceil() {\n assert(get_hclust_ceil(1) == 1);\n assert(get_hclust_ceil(2) == 2);\n assert(get_hclust_ceil(3) == 4);\n assert(get_hclust_ceil(4) == 4);\n assert(get_hclust_ceil(5) == 8);\n assert(get_hclust_ceil(6) == 8);\n assert(get_hclust_ceil(7) == 8);\n assert(get_hclust_ceil(8) == 8);\n assert(get_hclust_ceil(9) == 16);\n assert(get_hclust_ceil(10) == 16);\n assert(get_hclust_ceil(15) == 16);\n assert(get_hclust_ceil(16) == 16);\n assert(get_hclust_ceil(20) == 32);\n assert(get_hclust_ceil(27) == 32);\n assert(get_hclust_ceil(31) == 32);\n assert(get_hclust_ceil(32) == 32);\n assert(get_hclust_ceil(33) == 64);\n assert(get_hclust_ceil(63) == 64);\n\n printf(\"hclust_ceil test OK ...\\n\");\n}\n\nint main() {\n test_hclust_floor();\n test_hclust_ceil();\n printf(\"Successful util test!\\n\");\n}\n<commit_msg>test get_max_hnodes<commit_after>\/*\n * Copyright 2016 neurodata (http:\/\/neurodata.io\/)\n * Written by Disa Mhembere (disa@jhu.edu)\n *\n * This file is part of knor\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 CURRENT_KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"util.hpp\"\n#include <cassert>\n\nusing namespace knor::base;\n\nvoid test_hclust_floor() {\n assert(get_hclust_floor(1) == 1);\n assert(get_hclust_floor(2) == 2);\n assert(get_hclust_floor(3) == 2);\n assert(get_hclust_floor(4) == 4);\n assert(get_hclust_floor(5) == 4);\n assert(get_hclust_floor(6) == 4);\n assert(get_hclust_floor(7) == 4);\n assert(get_hclust_floor(8) == 8);\n assert(get_hclust_floor(9) == 8);\n assert(get_hclust_floor(10) == 8);\n assert(get_hclust_floor(15) == 8);\n assert(get_hclust_floor(16) == 16);\n assert(get_hclust_floor(20) == 16);\n assert(get_hclust_floor(27) == 16);\n assert(get_hclust_floor(31) == 16);\n assert(get_hclust_floor(32) == 32);\n printf(\"hclust_floor test OK ...\\n\");\n}\n\nvoid test_get_max_hnodes() {\n assert(get_max_hnodes(4) == 7);\n assert(get_max_hnodes(8) == 15);\n assert(get_max_hnodes(16) == 31);\n assert(get_max_hnodes(32) == 63);\n assert(get_max_hnodes(64) == 127);\n assert(get_max_hnodes(128) == 255);\n printf(\"test_get_max_hnodes test OK ...\\n\");\n}\n\nvoid test_hclust_ceil() {\n assert(get_hclust_ceil(1) == 1);\n assert(get_hclust_ceil(2) == 2);\n assert(get_hclust_ceil(3) == 4);\n assert(get_hclust_ceil(4) == 4);\n assert(get_hclust_ceil(5) == 8);\n assert(get_hclust_ceil(6) == 8);\n assert(get_hclust_ceil(7) == 8);\n assert(get_hclust_ceil(8) == 8);\n assert(get_hclust_ceil(9) == 16);\n assert(get_hclust_ceil(10) == 16);\n assert(get_hclust_ceil(15) == 16);\n assert(get_hclust_ceil(16) == 16);\n assert(get_hclust_ceil(20) == 32);\n assert(get_hclust_ceil(27) == 32);\n assert(get_hclust_ceil(31) == 32);\n assert(get_hclust_ceil(32) == 32);\n assert(get_hclust_ceil(33) == 64);\n assert(get_hclust_ceil(63) == 64);\n\n printf(\"hclust_ceil test OK ...\\n\");\n}\n\nint main() {\n test_hclust_floor();\n test_hclust_ceil();\n test_get_max_hnodes();\n printf(\"Successful util test!\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n kopetemessagemanager.cpp - Manages all chats\n\n Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>\n Copyright (c) 2002 by Daniel Stone <dstone@kde.org>\n Copyright (c) 2002 by Martijn Klingens <klingens@kde.org>\n Copyright (c) 2002-2003 by Olivier Goffart <ogoffart@tiscalinet.be>\n Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>\n\n Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\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 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <kdebug.h>\n#include <klocale.h>\n#include <knotifyclient.h>\n#include <qapplication.h>\n#include <kglobal.h>\n#include <qregexp.h>\n\n#include \"kopeteaccount.h\"\n#include \"kopetemessagemanager.h\"\n#include \"kopetemessagemanagerfactory.h\"\n#include \"kopeteprefs.h\"\n#include \"kopetemetacontact.h\"\n#include \"kopetecommandhandler.h\"\n#include \"kopeteview.h\"\n\nstruct KMMPrivate\n{\n\tKopeteContactPtrList mContactList;\n\tconst KopeteContact *mUser;\n\tQMap<const KopeteContact *, KopeteOnlineStatus> contactStatus;\n\tKopeteProtocol *mProtocol;\n\tint mId;\n\tbool isEmpty;\n\tbool mCanBeDeleted;\n\tQDateTime awayTime;\n\tQString displayName;\n\tKopeteView *view;\n};\n\nKopeteMessageManager::KopeteMessageManager( const KopeteContact *user,\n\tKopeteContactPtrList others, KopeteProtocol *protocol, int id, const char *name )\n: QObject( user->account(), name )\n{\n\td = new KMMPrivate;\n\td->mUser = user;\n\td->mProtocol = protocol;\n\td->mId = id;\n\td->isEmpty= others.isEmpty();\n\td->mCanBeDeleted = true;\n\td->view=0L;\n\n\tfor( KopeteContact *c = others.first(); c; c = others.next() )\n\t{\n\t\taddContact(c,true);\n\t}\n\n\tconnect( user, SIGNAL( onlineStatusChanged( KopeteContact *, const KopeteOnlineStatus &, const KopeteOnlineStatus & ) ), this,\n\t\tSLOT( slotStatusChanged( KopeteContact *, const KopeteOnlineStatus &, const KopeteOnlineStatus & ) ) );\n\n\/\/\tkdDebug(14010) << k_funcinfo << endl;\n}\n\nKopeteMessageManager::~KopeteMessageManager()\n{\n\/\/\tkdDebug(14010) << k_funcinfo << endl;\n\n\tfor( KopeteContact *c = d->mContactList.first(); c; c = d->mContactList.next() )\n\t\tc->setConversations( c->conversations() - 1 );\n\n\tif (!d) return;\n\td->mCanBeDeleted = false; \/\/prevent double deletion\n\tKopeteMessageManagerFactory::factory()->removeSession( this );\n\temit(closing( this ) );\n\tdelete d;\n}\n\nvoid KopeteMessageManager::slotStatusChanged( KopeteContact *c, const KopeteOnlineStatus &status, const KopeteOnlineStatus &oldStatus )\n{\n\tif(!KopetePrefs::prefs()->notifyAway())\n\t\treturn;\n\tif( status.status() == KopeteOnlineStatus::Away )\n\t{\n\t\td->awayTime = QDateTime::currentDateTime();\n\t\tKopeteMessage msg(c, d->mContactList, i18n(\"%1 has been marked as away.\")\n\t\t\t.arg( QString::fromLatin1(\"\/me\") ), KopeteMessage::Outbound, KopeteMessage::PlainText);\n\t\tsendMessage( msg );\n\t}\n\telse if( oldStatus.status() == KopeteOnlineStatus::Away && status.status() == KopeteOnlineStatus::Online )\n\t{\n\t\tKopeteMessage msg(c, d->mContactList, i18n(\"%1 is no longer marked as away. Gone since %1\")\n\t\t\t.arg( QString::fromLatin1(\"\/me\") ).arg(KGlobal::locale()->formatDateTime(d->awayTime, true)), KopeteMessage::Outbound, KopeteMessage::PlainText);\n\t\tsendMessage( msg );\n\t}\n}\n\nvoid KopeteMessageManager::setContactOnlineStatus( const KopeteContact *contact, const KopeteOnlineStatus &status )\n{\n\td->contactStatus[ contact ] = status;\n}\n\nconst KopeteOnlineStatus KopeteMessageManager::contactOnlineStatus( const KopeteContact *contact ) const\n{\n\tif( d->contactStatus.contains( contact ) )\n\t\treturn d->contactStatus[ contact ];\n\n\treturn contact->onlineStatus();\n}\n\nconst QString KopeteMessageManager::displayName()\n{\n\tif( d->displayName.isNull() )\n\t{\n\t\tconnect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) );\n\t\tslotUpdateDisplayName();\n\t}\n\n\treturn d->displayName;\n}\n\nvoid KopeteMessageManager::setDisplayName( const QString &newName )\n{\n\/\/\tkdDebug(14010) << k_funcinfo << endl;\n\tdisconnect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) );\n\n\td->displayName = newName;\n\n\temit( displayNameChanged() );\n}\n\nvoid KopeteMessageManager::slotUpdateDisplayName()\n{\n\/\/\tkdDebug(14010) << k_funcinfo << endl;\n\n\tQString nextDisplayName;\n\n\tKopeteContact *c = d->mContactList.first();\n\tif( c->metaContact() )\n\t\td->displayName = c->metaContact()->displayName();\n\telse\n\t\td->displayName = c->displayName();\n\n\t\/\/If we have only 1 contact, add the status of him\n\tif( d->mContactList.count() == 1 )\n\t{\n\t\td->displayName.append( QString::fromLatin1( \" (%1)\").arg( c->onlineStatus().description() ) );\n\t}\n\telse\n\t{\n\t\twhile( ( c = d->mContactList.next() ) )\n\t\t{\n\t\t\tif( c->metaContact() )\n\t\t\t\tnextDisplayName = c->metaContact()->displayName();\n\t\t\telse\n\t\t\t\tnextDisplayName = c->displayName();\n\t\t\td->displayName.append( QString::fromLatin1( \", \" ) ).append( nextDisplayName );\n\t\t}\n\t}\n\n\temit( displayNameChanged() );\n}\n\nconst KopeteContactPtrList& KopeteMessageManager::members() const\n{\n\treturn d->mContactList;\n}\n\nconst KopeteContact* KopeteMessageManager::user() const\n{\n\treturn d->mUser;\n}\n\nKopeteProtocol* KopeteMessageManager::protocol() const\n{\n\treturn d->mProtocol;\n}\n\nint KopeteMessageManager::mmId() const\n{\n\treturn d->mId;\n}\n\nvoid KopeteMessageManager::setMMId( int id )\n{\n\td->mId = id;\n}\n\nvoid KopeteMessageManager::sendMessage(KopeteMessage &message)\n{\n\tmessage.setManager(this);\n\tKopeteMessage sentMessage = message;\n\tif( !KopeteCommandHandler::commandHandler()->processMessage( message, this ) )\n\t{\n\t\temit messageSent(sentMessage, this);\n\t\tif ( !account()->isAway() || KopetePrefs::prefs()->soundIfAway() )\n\t\t\tKNotifyClient::event( QString::fromLatin1( \"kopete_outgoing\"), i18n(\"Outgoing Message Sent\") );\n\t}\n\telse\n\t\temit( messageSuccess() );\n}\n\nvoid KopeteMessageManager::messageSucceeded()\n{\n\temit( messageSuccess() );\n}\n\nvoid KopeteMessageManager::appendMessage( KopeteMessage &msg )\n{\n\/\/\tkdDebug(14010) << k_funcinfo << endl;\n\tmsg.setManager(this);\n\n\tif( msg.direction() == KopeteMessage::Inbound )\n\t{\n\t\tif( KopetePrefs::prefs()->highlightEnabled() && msg.plainBody().contains( QRegExp(QString::fromLatin1(\"\\\\b(%1)\\\\b\").arg(user()->displayName()),false) ) )\n\t\t\tmsg.setImportance( KopeteMessage::Highlight );\n\n\t\temit( messageReceived( msg, this ) );\n\t}\n\n\temit messageAppended( msg, this );\n}\n\nvoid KopeteMessageManager::addContact( const KopeteContact *c, bool supress )\n{\n\tif ( d->mContactList.contains(c) )\n\t{\n\t\tkdDebug(14010) << k_funcinfo << \"Contact already exists\" <<endl;\n\t\temit contactAdded(c, supress);\n\t}\n\telse\n\t{\n\t\tif(d->mContactList.count()==1 && d->isEmpty)\n\t\t{\n\t\t\tKopeteContact *old=d->mContactList.first();\n\t\t\td->mContactList.remove(old);\n\t\t\td->mContactList.append(c);\n\t\t\t\/\/disconnect (old, SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\t\tdisconnect (old, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged()));\n\t\t\tif(old->metaContact())\n\t\t\t\tdisconnect (old->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\t\temit contactAdded(c, supress);\n\t\t\temit contactRemoved(old, QString::null);\n\t\t}\n\t\telse\n\t\t{\n\t\t\td->mContactList.append(c);\n\t\t\temit contactAdded(c, supress);\n\t\t}\n\t\tc->setConversations( c->conversations() + 1 );\n\t\t\/\/connect (c, SIGNAL(displayNameChanged(const QString &,const QString &)), this, SIGNAL(contactChanged()));\n\t\tconnect (c, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged()));\n\t\tif(c->metaContact())\n\t\t\tconnect (c->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\tconnect (c, SIGNAL(contactDestroyed(KopeteContact*)) , this , SLOT(slotContactDestroyed(KopeteContact*)));\n\t}\n\td->isEmpty=false;\n\tslotUpdateDisplayName();\n}\n\nvoid KopeteMessageManager::removeContact( const KopeteContact *c, const QString& raison )\n{\n\tif(!c || !d->mContactList.contains(c))\n\t\treturn;\n\n\tif(d->mContactList.count()==1)\n\t{\n\t\tkdDebug(14010) << k_funcinfo << \"Contact not removed. Keep always one contact\" <<endl;\n\t\td->isEmpty=true;\n\t}\n\telse\n\t{\n\t\td->mContactList.remove( c );\n\t\t\/\/disconnect (c, SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\tdisconnect (c, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged()));\n\t\tif(c->metaContact())\n\t\t\tdisconnect (c->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\tc->setConversations( c->conversations() - 1 );\n\t}\n\temit contactRemoved(c, raison);\n\tslotUpdateDisplayName();\n}\n\nvoid KopeteMessageManager::receivedTypingMsg( const KopeteContact *c , bool t )\n{\n\temit(remoteTyping( c, t ));\n}\n\nvoid KopeteMessageManager::receivedTypingMsg( const QString &contactId , bool t )\n{\n\tfor( KopeteContact *it = d->mContactList.first(); it; it = d->mContactList.next() )\n\t{\n\t\tif( it->contactId() == contactId )\n\t\t{\n\t\t\treceivedTypingMsg( it, t );\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid KopeteMessageManager::typing ( bool t )\n{\n\temit typingMsg(t);\n}\n\nvoid KopeteMessageManager::setCanBeDeleted ( bool b )\n{\n\td->mCanBeDeleted = b;\n\tif(b && !d->view)\n\t\tdeleteLater();\n}\n\nKopeteView* KopeteMessageManager::view(bool canCreate , KopeteMessage::MessageType type )\n{\n\tif(!d->view && canCreate)\n\t{\n\t\td->view=KopeteMessageManagerFactory::factory()->createView( this , type );\n\t\tconnect( d->view->mainWidget(), SIGNAL( closing( KopeteView * ) ), this, SLOT( slotViewDestroyed( ) ) );\n\t}\n\treturn d->view;\n}\n\nvoid KopeteMessageManager::slotViewDestroyed()\n{\n\td->view=0L;\n\tif(d->mCanBeDeleted)\n\t\tdeleteLater();\n}\n\nKopeteAccount *KopeteMessageManager::account() const\n{\n\treturn user()->account();\n}\n\nvoid KopeteMessageManager::slotContactDestroyed(KopeteContact* c)\n{\n\tif(!c || !d->mContactList.contains(c))\n\t\treturn;\n\n\tif(d->mContactList.count()==1)\n\t{\n\t\tdeleteLater(); \/\/the contact has been deleted, it is better to delete this\n\t}\n\telse\n\t{\n\t\td->mContactList.remove( c );\n\t\temit contactRemoved(c , QString::null);\n\t}\n}\n\n#include \"kopetemessagemanager.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n<commit_msg>wow, forget a connection<commit_after>\/*\n kopetemessagemanager.cpp - Manages all chats\n\n Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>\n Copyright (c) 2002 by Daniel Stone <dstone@kde.org>\n Copyright (c) 2002 by Martijn Klingens <klingens@kde.org>\n Copyright (c) 2002-2003 by Olivier Goffart <ogoffart@tiscalinet.be>\n Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>\n\n Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\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 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <kdebug.h>\n#include <klocale.h>\n#include <knotifyclient.h>\n#include <qapplication.h>\n#include <kglobal.h>\n#include <qregexp.h>\n\n#include \"kopeteaccount.h\"\n#include \"kopetemessagemanager.h\"\n#include \"kopetemessagemanagerfactory.h\"\n#include \"kopeteprefs.h\"\n#include \"kopetemetacontact.h\"\n#include \"kopetecommandhandler.h\"\n#include \"kopeteview.h\"\n\nstruct KMMPrivate\n{\n\tKopeteContactPtrList mContactList;\n\tconst KopeteContact *mUser;\n\tQMap<const KopeteContact *, KopeteOnlineStatus> contactStatus;\n\tKopeteProtocol *mProtocol;\n\tint mId;\n\tbool isEmpty;\n\tbool mCanBeDeleted;\n\tQDateTime awayTime;\n\tQString displayName;\n\tKopeteView *view;\n};\n\nKopeteMessageManager::KopeteMessageManager( const KopeteContact *user,\n\tKopeteContactPtrList others, KopeteProtocol *protocol, int id, const char *name )\n: QObject( user->account(), name )\n{\n\td = new KMMPrivate;\n\td->mUser = user;\n\td->mProtocol = protocol;\n\td->mId = id;\n\td->isEmpty= others.isEmpty();\n\td->mCanBeDeleted = true;\n\td->view=0L;\n\n\tfor( KopeteContact *c = others.first(); c; c = others.next() )\n\t{\n\t\taddContact(c,true);\n\t}\n\n\tconnect( user, SIGNAL( onlineStatusChanged( KopeteContact *, const KopeteOnlineStatus &, const KopeteOnlineStatus & ) ), this,\n\t\tSLOT( slotStatusChanged( KopeteContact *, const KopeteOnlineStatus &, const KopeteOnlineStatus & ) ) );\n\n\tconnect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) );\n}\n\nKopeteMessageManager::~KopeteMessageManager()\n{\n\tfor( KopeteContact *c = d->mContactList.first(); c; c = d->mContactList.next() )\n\t\tc->setConversations( c->conversations() - 1 );\n\n\tif (!d) return;\n\td->mCanBeDeleted = false; \/\/prevent double deletion\n\tKopeteMessageManagerFactory::factory()->removeSession( this );\n\temit(closing( this ) );\n\tdelete d;\n}\n\nvoid KopeteMessageManager::slotStatusChanged( KopeteContact *c, const KopeteOnlineStatus &status, const KopeteOnlineStatus &oldStatus )\n{\n\tif(!KopetePrefs::prefs()->notifyAway())\n\t\treturn;\n\tif( status.status() == KopeteOnlineStatus::Away )\n\t{\n\t\td->awayTime = QDateTime::currentDateTime();\n\t\tKopeteMessage msg(c, d->mContactList, i18n(\"%1 has been marked as away.\")\n\t\t\t.arg( QString::fromLatin1(\"\/me\") ), KopeteMessage::Outbound, KopeteMessage::PlainText);\n\t\tsendMessage( msg );\n\t}\n\telse if( oldStatus.status() == KopeteOnlineStatus::Away && status.status() == KopeteOnlineStatus::Online )\n\t{\n\t\tKopeteMessage msg(c, d->mContactList, i18n(\"%1 is no longer marked as away. Gone since %1\")\n\t\t\t.arg( QString::fromLatin1(\"\/me\") ).arg(KGlobal::locale()->formatDateTime(d->awayTime, true)), KopeteMessage::Outbound, KopeteMessage::PlainText);\n\t\tsendMessage( msg );\n\t}\n}\n\nvoid KopeteMessageManager::setContactOnlineStatus( const KopeteContact *contact, const KopeteOnlineStatus &status )\n{\n\td->contactStatus[ contact ] = status;\n}\n\nconst KopeteOnlineStatus KopeteMessageManager::contactOnlineStatus( const KopeteContact *contact ) const\n{\n\tif( d->contactStatus.contains( contact ) )\n\t\treturn d->contactStatus[ contact ];\n\n\treturn contact->onlineStatus();\n}\n\nconst QString KopeteMessageManager::displayName()\n{\n\tif( d->displayName.isNull() )\n\t{\n\t\tconnect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) );\n\t\tslotUpdateDisplayName();\n\t}\n\n\treturn d->displayName;\n}\n\nvoid KopeteMessageManager::setDisplayName( const QString &newName )\n{\n\tdisconnect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) );\n\n\td->displayName = newName;\n\n\temit( displayNameChanged() );\n}\n\nvoid KopeteMessageManager::slotUpdateDisplayName()\n{\n\tQString nextDisplayName;\n\n\tKopeteContact *c = d->mContactList.first();\n\tif( c->metaContact() )\n\t\td->displayName = c->metaContact()->displayName();\n\telse\n\t\td->displayName = c->displayName();\n\n\t\/\/If we have only 1 contact, add the status of him\n\tif( d->mContactList.count() == 1 )\n\t{\n\t\td->displayName.append( QString::fromLatin1( \" (%1)\").arg( c->onlineStatus().description() ) );\n\t}\n\telse\n\t{\n\t\twhile( ( c = d->mContactList.next() ) )\n\t\t{\n\t\t\tif( c->metaContact() )\n\t\t\t\tnextDisplayName = c->metaContact()->displayName();\n\t\t\telse\n\t\t\t\tnextDisplayName = c->displayName();\n\t\t\td->displayName.append( QString::fromLatin1( \", \" ) ).append( nextDisplayName );\n\t\t}\n\t}\n\n\temit( displayNameChanged() );\n}\n\nconst KopeteContactPtrList& KopeteMessageManager::members() const\n{\n\treturn d->mContactList;\n}\n\nconst KopeteContact* KopeteMessageManager::user() const\n{\n\treturn d->mUser;\n}\n\nKopeteProtocol* KopeteMessageManager::protocol() const\n{\n\treturn d->mProtocol;\n}\n\nint KopeteMessageManager::mmId() const\n{\n\treturn d->mId;\n}\n\nvoid KopeteMessageManager::setMMId( int id )\n{\n\td->mId = id;\n}\n\nvoid KopeteMessageManager::sendMessage(KopeteMessage &message)\n{\n\tmessage.setManager(this);\n\tKopeteMessage sentMessage = message;\n\tif( !KopeteCommandHandler::commandHandler()->processMessage( message, this ) )\n\t{\n\t\temit messageSent(sentMessage, this);\n\t\tif ( !account()->isAway() || KopetePrefs::prefs()->soundIfAway() )\n\t\t\tKNotifyClient::event( QString::fromLatin1( \"kopete_outgoing\"), i18n(\"Outgoing Message Sent\") );\n\t}\n\telse\n\t\temit( messageSuccess() );\n}\n\nvoid KopeteMessageManager::messageSucceeded()\n{\n\temit( messageSuccess() );\n}\n\nvoid KopeteMessageManager::appendMessage( KopeteMessage &msg )\n{\n\tmsg.setManager(this);\n\n\tif( msg.direction() == KopeteMessage::Inbound )\n\t{\n\t\tif( KopetePrefs::prefs()->highlightEnabled() && msg.plainBody().contains( QRegExp(QString::fromLatin1(\"\\\\b(%1)\\\\b\").arg(user()->displayName()),false) ) )\n\t\t\tmsg.setImportance( KopeteMessage::Highlight );\n\n\t\temit( messageReceived( msg, this ) );\n\t}\n\n\temit messageAppended( msg, this );\n}\n\nvoid KopeteMessageManager::addContact( const KopeteContact *c, bool supress )\n{\n\tif ( d->mContactList.contains(c) )\n\t{\n\t\tkdDebug(14010) << k_funcinfo << \"Contact already exists\" <<endl;\n\t\temit contactAdded(c, supress);\n\t}\n\telse\n\t{\n\t\tif(d->mContactList.count()==1 && d->isEmpty)\n\t\t{\n\t\t\tKopeteContact *old=d->mContactList.first();\n\t\t\td->mContactList.remove(old);\n\t\t\td->mContactList.append(c);\n\t\t\t\/\/disconnect (old, SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\t\tdisconnect (old, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged()));\n\t\t\tif(old->metaContact())\n\t\t\t\tdisconnect (old->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\t\temit contactAdded(c, supress);\n\t\t\temit contactRemoved(old, QString::null);\n\t\t}\n\t\telse\n\t\t{\n\t\t\td->mContactList.append(c);\n\t\t\temit contactAdded(c, supress);\n\t\t}\n\t\tc->setConversations( c->conversations() + 1 );\n\t\t\/\/connect (c, SIGNAL(displayNameChanged(const QString &,const QString &)), this, SIGNAL(contactChanged()));\n\t\tconnect (c, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged()));\n\t\tif(c->metaContact())\n\t\t\tconnect (c->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\tconnect (c, SIGNAL(contactDestroyed(KopeteContact*)) , this , SLOT(slotContactDestroyed(KopeteContact*)));\n\t}\n\td->isEmpty=false;\n\tslotUpdateDisplayName();\n}\n\nvoid KopeteMessageManager::removeContact( const KopeteContact *c, const QString& raison )\n{\n\tif(!c || !d->mContactList.contains(c))\n\t\treturn;\n\n\tif(d->mContactList.count()==1)\n\t{\n\t\tkdDebug(14010) << k_funcinfo << \"Contact not removed. Keep always one contact\" <<endl;\n\t\td->isEmpty=true;\n\t}\n\telse\n\t{\n\t\td->mContactList.remove( c );\n\t\t\/\/disconnect (c, SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\tdisconnect (c, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged()));\n\t\tif(c->metaContact())\n\t\t\tdisconnect (c->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged()));\n\t\tdisconnect (c, SIGNAL(contactDestroyed(KopeteContact*)) , this , SLOT(slotContactDestroyed(KopeteContact*)));\n\t\tc->setConversations( c->conversations() - 1 );\n\t}\n\temit contactRemoved(c, raison);\n\tslotUpdateDisplayName();\n}\n\nvoid KopeteMessageManager::receivedTypingMsg( const KopeteContact *c , bool t )\n{\n\temit(remoteTyping( c, t ));\n}\n\nvoid KopeteMessageManager::receivedTypingMsg( const QString &contactId , bool t )\n{\n\tfor( KopeteContact *it = d->mContactList.first(); it; it = d->mContactList.next() )\n\t{\n\t\tif( it->contactId() == contactId )\n\t\t{\n\t\t\treceivedTypingMsg( it, t );\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid KopeteMessageManager::typing ( bool t )\n{\n\temit typingMsg(t);\n}\n\nvoid KopeteMessageManager::setCanBeDeleted ( bool b )\n{\n\td->mCanBeDeleted = b;\n\tif(b && !d->view)\n\t\tdeleteLater();\n}\n\nKopeteView* KopeteMessageManager::view(bool canCreate , KopeteMessage::MessageType type )\n{\n\tif(!d->view && canCreate)\n\t{\n\t\td->view=KopeteMessageManagerFactory::factory()->createView( this , type );\n\t\tconnect( d->view->mainWidget(), SIGNAL( closing( KopeteView * ) ), this, SLOT( slotViewDestroyed( ) ) );\n\t}\n\treturn d->view;\n}\n\nvoid KopeteMessageManager::slotViewDestroyed()\n{\n\td->view=0L;\n\tif(d->mCanBeDeleted)\n\t\tdeleteLater();\n}\n\nKopeteAccount *KopeteMessageManager::account() const\n{\n\treturn user()->account();\n}\n\nvoid KopeteMessageManager::slotContactDestroyed(KopeteContact* c)\n{\n\tif(!c || !d->mContactList.contains(c))\n\t\treturn;\n\n\tif(d->mContactList.count()==1)\n\t{\n\t\tdeleteLater(); \/\/the contact has been deleted, it is better to delete this\n\t}\n\telse\n\t{\n\t\td->mContactList.remove( c );\n\t\temit contactRemoved(c , QString::null);\n\t}\n}\n\n#include \"kopetemessagemanager.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*-mode: c++; indent-tabs-mode: nil; -*-\n\n#include <iostream>\n#include <fstream>\n\n#include <sys\/types.h> \/\/ opendir\n#include <dirent.h> \/\/ opendir, readdir\n\n#include <sys\/types.h> \/\/ stat\n#include <sys\/stat.h> \/\/ stat\n#include <unistd.h> \/\/ stat\n\n#include <limits.h> \/\/ realpath\n#include <stdlib.h> \/\/ realpath\n\n#include <string.h> \/\/ strerror_r\n#include <errno.h> \/\/ errno\n\n#include <set>\n#include <vector>\n#include <map>\n#include <limits.h> \/\/ PATH_MAX http:\/\/stackoverflow.com\/a\/9449307\/257924\n#include <regex>\n\nbool realPathToString(const std::string & inPath, std::string & realPath, bool verbose)\n{\n realPath.resize(PATH_MAX);\n \/\/ Get the realPath for duplicate detection.\n const char * tmp = realpath(inPath.c_str(), &(realPath[0]));\n \/\/ Warn about bad links:\n if (!tmp) {\n char strbuf[1024];\n const char * errstring = strerror_r(errno, strbuf, sizeof(strbuf));\n if (verbose) {\n std::cerr << \"WARNING: Failed resolve: \" << inPath << \" : \" << errstring << std::endl;\n }\n realPath = \"\";\n return false;\n }\n realPath.resize(strlen(&(realPath[0])));\n return true;\n}\n\nnamespace VerboseNS {\n\n enum VerbosityLevel {\n E_NONE = 0\n , E_VERBOSE = 1 << 0\n , E_DEBUG = 1 << 1\n };\n\n class VerbosityTracker\n {\n public:\n\n VerbosityTracker() : _verbosity(E_NONE) {}\n\n bool isAtVerbosity(int level) { return (_verbosity & level) != 0; }\n\n void setVerbosity(int value)\n {\n _verbosity = value;\n }\n\n#define DEFINE_SET_VERBOSITY_METHOD(TYPE) \\\n TYPE & setVerbosity(int value) \\\n { \\\n _verbosity.setVerbosity(value); \\\n return *this; \\\n }\n\n\n private:\n int _verbosity;\n };\n\n};\n\nclass UniqueFileVisitor\n{\npublic:\n virtual bool visit(const std::string & absPath) = 0;\n};\n\nclass UniqueFileScanner\n{\npublic:\n UniqueFileScanner()\n : _visitor(NULL)\n {}\n\n\n UniqueFileScanner & setVisitor(UniqueFileVisitor * visitor)\n {\n _visitor = visitor;\n return *this;\n }\n\n DEFINE_SET_VERBOSITY_METHOD(UniqueFileScanner);\n\n bool scan(const std::string & inDir)\n {\n DIR * dirfp = opendir(inDir.c_str());\n\n if (!dirfp) {\n std::cerr << \"ERROR: Failed to open directory: \" << inDir << std::endl;\n return false;\n }\n\n struct dirent *result = nullptr;\n struct stat statbuf;\n std::string absPath;\n std::string realPath;\n errno = 0;\n while ((result = readdir(dirfp)) != nullptr) {\n std::string basename = result->d_name;\n\n \/\/ Skip directories we obviously should not traverse into:\n if (basename == \".\" || basename == \"..\" || basename == \".git\")\n continue;\n\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << std::endl;\n }\n\n \/\/ Fully-qualify the directory entry in preparation for calling stat:\n absPath = inDir;\n absPath += \"\/\";\n absPath += basename;\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << \"absPath \" << absPath << std::endl;\n }\n\n \/\/ Identify the type of file it is:\n int status = stat(absPath.c_str(), &statbuf);\n if (status == 0) { \/\/ stat succeeded\n\n \/\/ Get the realPath for duplicate detection.\n if (!realPathToString(absPath, realPath, _verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)))\n continue;\n\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << \"realPath \" << realPath << std::endl;\n }\n\n \/\/ Avoid parsing the same file or directory twice (can happen via symbolic links):\n SetT::iterator iter = _seen.find(realPath);\n if(iter != _seen.end()) {\n if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {\n std::cout << \"Skipping previously processed file or directory: \" << realPath << std::endl;\n }\n continue;\n }\n _seen.insert(realPath);\n\n if ( S_ISDIR(statbuf.st_mode) ) {\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << \"directory absPath \" << absPath << std::endl;\n }\n \/\/ recurse:\n if (!scan(absPath)) {\n return false;\n }\n } else if ( S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode) ) {\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << \"parsable absPath \" << absPath << std::endl;\n }\n if (!_visitor->visit(absPath))\n return false;\n } else {\n if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {\n std::cout << \"Skipping non-regular file: \" << absPath << std::endl;\n }\n continue;\n }\n } else { \/\/ stat failed\n if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {\n std::cerr << \"WARNING: Failed to stat: \" << absPath << std::endl;\n }\n continue;\n }\n\n }\n\n if (errno) {\n std::cerr << \"ERROR: Failed to read from directory: \" << inDir << \" : \" << strerror(errno) << std::endl;\n return false;\n }\n\n closedir(dirfp);\n return true;\n }\n\nprivate:\n typedef std::set<std::string> SetT;\n SetT _seen;\n UniqueFileVisitor * _visitor; \/\/ not owned by this object.\n VerboseNS::VerbosityTracker _verbosity;\n};\n\nclass OrgIDParser : public UniqueFileVisitor\n{\n std::regex _id_regexp{\n \"\\n\"\n \"\\\\s*:PROPERTIES:\\\\s*\\n\"\n \"\\\\s*:ID:\\\\s*([a-z0-9-]+)\",\n std::regex_constants::icase};\n\n\npublic:\n OrgIDParser() {}\n\n virtual bool visit(const std::string & absPath)\n {\n\n \/\/ Only work on Org-mode files:\n static const char * orgExtension = \".org\";\n std::size_t pos;\n if ( (pos = absPath.rfind(orgExtension)) != std::string::npos ) {\n if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {\n std::cout << \"Processing \" << absPath << std::endl;\n }\n\n \/\/ Parse the file:\n return parse(absPath);\n\n }\n return true;\n }\n\n bool parse(const std::string & absPath)\n {\n std::ifstream stream(absPath.c_str(), std::ifstream::binary);\n if (!stream) {\n std::cerr << \"ERROR: Failed to open: \" << absPath << std::endl;\n return false;\n }\n\n \/\/ Get length of file:\n stream.seekg (0, stream.end);\n std::streampos length = stream.tellg();\n stream.seekg (0, stream.beg);\n\n \/\/ Allocate memory:\n std::string buffer(length, 0);\n\n \/\/ Read data as a block:\n stream.read(&(buffer[0]), length);\n\n stream.close();\n\n auto ids_begin = std::sregex_iterator(buffer.begin(), buffer.end(), _id_regexp);\n auto ids_end = std::sregex_iterator();\n\n for (std::sregex_iterator i = ids_begin; i != ids_end; ++i) {\n std::smatch match = *i;\n std::string id = match.str(1);\n\n IdSetT & ids = _map[absPath]; \/\/ Create a IdSetT if one does not exist\n if (ids.find(id) != ids.end()) {\n std::cerr << \"ERROR: Duplicate ID value \" << id << \" at position \" << match.position(1) << \" in file \" << absPath << std::endl;\n return false;\n }\n ids.insert(id);\n\n }\n\n return true;\n }\n\n bool writeIdAlistFile(const std::string & alistPath)\n {\n std::ofstream stream(alistPath.c_str());\n if (!stream) {\n std::cerr << \"ERROR: Cannot open \" << alistPath << \" for writing.\" << std::endl;\n return false;\n }\n\n bool first = true;\n stream << \"(\";\n for (FileToIdSetT::iterator cur = _map.begin(); cur != _map.end(); ++cur)\n {\n const std::string & absPath = cur->first;\n\n if (!first) {\n stream << std::endl << \" \";\n }\n\n stream << \"(\\\"\" << absPath << \"\\\"\";\n IdSetT & ids = cur->second;\n\n for (IdSetT::iterator cur = ids.begin(); cur != ids.end(); ++cur)\n {\n stream << \" \\\"\" << *cur << \"\\\"\";\n }\n\n stream << \")\";\n\n first = false;\n }\n stream << \")\" << std::endl;\n\n return true;\n }\n\n\n\n DEFINE_SET_VERBOSITY_METHOD(OrgIDParser);\n\nprivate:\n VerboseNS::VerbosityTracker _verbosity;\n typedef std::set<std::string> IdSetT;\n typedef std::map<std::string, IdSetT > FileToIdSetT;\n FileToIdSetT _map;\n};\n\nint main(int argc, char *argv[], char *const envp[])\n{\n int verbosity = VerboseNS::E_NONE;\n bool readingDirectories = false;\n typedef std::vector<std::string> DirectoryListT;\n DirectoryListT directories;\n std::string idAlistPath;\n for (int i = 1; i < argc; i++)\n {\n std::string arg = argv[i];\n if (arg.empty()) break;\n if (readingDirectories) {\n \/\/ Get the realPath for things like \".\":\n std::string realPath;\n if (!realPathToString(arg, realPath, true))\n continue;\n directories.push_back(realPath);\n } else {\n if (arg == \"--\") {\n readingDirectories = true;\n } else if (arg == \"-verbose\") {\n verbosity |= VerboseNS::E_VERBOSE;\n } else if (arg == \"-debug\") {\n verbosity |= VerboseNS::E_DEBUG;\n } else if (arg == \"-o\") {\n if (i + 1 >= argc) {\n std::cerr << \"ERROR: -o requires a value.\" << std::endl;\n return 1;\n }\n idAlistPath = argv[++i];\n } else if (arg == \"-h\" || arg == \"--help\") {\n std::cerr << \"USAGE: \" << argv[0] << \" -o OUTPUT-ALIST-FILE [ -verbose ] [ -debug ] [ -h ] -- DIR-1 DIR-2 ... DIR-N\" << std::endl;\n return 0;\n } else {\n std::cerr << \"ERROR: Unrecognized option \" << arg << std::endl;\n return 1;\n }\n }\n }\n\n if (directories.empty()) {\n std::cerr << \"ERROR: No directories specified.\" << std::endl;\n return 1;\n }\n\n if (idAlistPath.empty()) {\n std::cerr << \"ERROR: No alistfile specified.\" << std::endl;\n return 1;\n }\n\n \/\/ OrgIDParser will house the results:\n OrgIDParser parser;\n parser.setVerbosity(verbosity);\n\n \/\/ UniqueFileScanner scans for files and removes duplicates, visiting each\n \/\/ with the parser:\n UniqueFileScanner scanner;\n scanner\n .setVerbosity(verbosity)\n .setVisitor(&parser);\n for (DirectoryListT::iterator cur = directories.begin(); cur != directories.end(); ++cur)\n {\n int success = scanner.scan(*cur);\n if (!success) {\n return 1;\n }\n }\n\n \/\/ Write out the alist file:\n parser.writeIdAlistFile(idAlistPath);\n\n return 0;\n} \/\/ end main\n\n<commit_msg>org-id-scanner.cpp: Reset errno after a failed stat<commit_after>\/\/ -*-mode: c++; indent-tabs-mode: nil; -*-\n\n#include <iostream>\n#include <fstream>\n\n#include <sys\/types.h> \/\/ opendir\n#include <dirent.h> \/\/ opendir, readdir\n\n#include <sys\/types.h> \/\/ stat\n#include <sys\/stat.h> \/\/ stat\n#include <unistd.h> \/\/ stat\n\n#include <limits.h> \/\/ realpath\n#include <stdlib.h> \/\/ realpath\n\n#include <string.h> \/\/ strerror_r\n#include <errno.h> \/\/ errno\n\n#include <set>\n#include <vector>\n#include <map>\n#include <limits.h> \/\/ PATH_MAX http:\/\/stackoverflow.com\/a\/9449307\/257924\n#include <regex>\n\nbool realPathToString(const std::string & inPath, std::string & realPath, bool verbose)\n{\n realPath.resize(PATH_MAX);\n \/\/ Get the realPath for duplicate detection.\n const char * tmp = realpath(inPath.c_str(), &(realPath[0]));\n \/\/ Warn about bad links:\n if (!tmp) {\n char strbuf[1024];\n const char * errstring = strerror_r(errno, strbuf, sizeof(strbuf));\n if (verbose) {\n std::cerr << \"WARNING: Failed resolve: \" << inPath << \" : \" << errstring << std::endl;\n }\n realPath = \"\";\n return false;\n }\n realPath.resize(strlen(&(realPath[0])));\n return true;\n}\n\nnamespace VerboseNS {\n\n enum VerbosityLevel {\n E_NONE = 0\n , E_VERBOSE = 1 << 0\n , E_DEBUG = 1 << 1\n };\n\n class VerbosityTracker\n {\n public:\n\n VerbosityTracker() : _verbosity(E_NONE) {}\n\n bool isAtVerbosity(int level) { return (_verbosity & level) != 0; }\n\n void setVerbosity(int value)\n {\n _verbosity = value;\n }\n\n#define DEFINE_SET_VERBOSITY_METHOD(TYPE) \\\n TYPE & setVerbosity(int value) \\\n { \\\n _verbosity.setVerbosity(value); \\\n return *this; \\\n }\n\n\n private:\n int _verbosity;\n };\n\n};\n\nclass UniqueFileVisitor\n{\npublic:\n virtual bool visit(const std::string & absPath) = 0;\n};\n\nclass UniqueFileScanner\n{\npublic:\n UniqueFileScanner()\n : _visitor(NULL)\n {}\n\n\n UniqueFileScanner & setVisitor(UniqueFileVisitor * visitor)\n {\n _visitor = visitor;\n return *this;\n }\n\n DEFINE_SET_VERBOSITY_METHOD(UniqueFileScanner);\n\n bool scan(const std::string & inDir)\n {\n DIR * dirfp = opendir(inDir.c_str());\n\n if (!dirfp) {\n std::cerr << \"ERROR: Failed to open directory: \" << inDir << std::endl;\n return false;\n }\n\n struct dirent *result = nullptr;\n struct stat statbuf;\n std::string absPath;\n std::string realPath;\n errno = 0;\n while ((result = readdir(dirfp)) != nullptr) {\n std::string basename = result->d_name;\n\n \/\/ Skip directories we obviously should not traverse into:\n if (basename == \".\" || basename == \"..\" || basename == \".git\")\n continue;\n\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << std::endl;\n }\n\n \/\/ Fully-qualify the directory entry in preparation for calling stat:\n absPath = inDir;\n absPath += \"\/\";\n absPath += basename;\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << \"absPath \" << absPath << std::endl;\n }\n\n \/\/ Identify the type of file it is:\n int status = stat(absPath.c_str(), &statbuf);\n if (status == 0) { \/\/ stat succeeded\n\n \/\/ Get the realPath for duplicate detection.\n if (!realPathToString(absPath, realPath, _verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)))\n continue;\n\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << \"realPath \" << realPath << std::endl;\n }\n\n \/\/ Avoid parsing the same file or directory twice (can happen via symbolic links):\n SetT::iterator iter = _seen.find(realPath);\n if(iter != _seen.end()) {\n if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {\n std::cout << \"Skipping previously processed file or directory: \" << realPath << std::endl;\n }\n continue;\n }\n _seen.insert(realPath);\n\n if ( S_ISDIR(statbuf.st_mode) ) {\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << \"directory absPath \" << absPath << std::endl;\n }\n \/\/ recurse:\n if (!scan(absPath)) {\n return false;\n }\n } else if ( S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode) ) {\n if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {\n std::cout << \"parsable absPath \" << absPath << std::endl;\n }\n if (!_visitor->visit(absPath))\n return false;\n } else {\n if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {\n std::cout << \"Skipping non-regular file: \" << absPath << std::endl;\n }\n continue;\n }\n } else { \/\/ stat failed\n if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {\n std::cerr << \"WARNING: Failed to stat: \" << absPath << std::endl;\n errno = 0; \/\/ reset errno so we do not fail after the loop\n }\n continue;\n }\n\n }\n\n if (errno) {\n std::cerr << \"ERROR: Failed to read from directory: \" << inDir << \" : \" << strerror(errno) << std::endl;\n return false;\n }\n\n closedir(dirfp);\n return true;\n }\n\nprivate:\n typedef std::set<std::string> SetT;\n SetT _seen;\n UniqueFileVisitor * _visitor; \/\/ not owned by this object.\n VerboseNS::VerbosityTracker _verbosity;\n};\n\nclass OrgIDParser : public UniqueFileVisitor\n{\n std::regex _id_regexp{\n \"\\n\"\n \"\\\\s*:PROPERTIES:\\\\s*\\n\"\n \"\\\\s*:ID:\\\\s*([a-z0-9-]+)\",\n std::regex_constants::icase};\n\n\npublic:\n OrgIDParser() {}\n\n virtual bool visit(const std::string & absPath)\n {\n\n \/\/ Only work on Org-mode files:\n static const char * orgExtension = \".org\";\n std::size_t pos;\n if ( (pos = absPath.rfind(orgExtension)) != std::string::npos ) {\n if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {\n std::cout << \"Processing \" << absPath << std::endl;\n }\n\n \/\/ Parse the file:\n return parse(absPath);\n\n }\n return true;\n }\n\n bool parse(const std::string & absPath)\n {\n std::ifstream stream(absPath.c_str(), std::ifstream::binary);\n if (!stream) {\n std::cerr << \"ERROR: Failed to open: \" << absPath << std::endl;\n return false;\n }\n\n \/\/ Get length of file:\n stream.seekg (0, stream.end);\n std::streampos length = stream.tellg();\n stream.seekg (0, stream.beg);\n\n \/\/ Allocate memory:\n std::string buffer(length, 0);\n\n \/\/ Read data as a block:\n stream.read(&(buffer[0]), length);\n\n stream.close();\n\n auto ids_begin = std::sregex_iterator(buffer.begin(), buffer.end(), _id_regexp);\n auto ids_end = std::sregex_iterator();\n\n for (std::sregex_iterator i = ids_begin; i != ids_end; ++i) {\n std::smatch match = *i;\n std::string id = match.str(1);\n\n IdSetT & ids = _map[absPath]; \/\/ Create a IdSetT if one does not exist\n if (ids.find(id) != ids.end()) {\n std::cerr << \"ERROR: Duplicate ID value \" << id << \" at position \" << match.position(1) << \" in file \" << absPath << std::endl;\n return false;\n }\n ids.insert(id);\n\n }\n\n return true;\n }\n\n bool writeIdAlistFile(const std::string & alistPath)\n {\n std::ofstream stream(alistPath.c_str());\n if (!stream) {\n std::cerr << \"ERROR: Cannot open \" << alistPath << \" for writing.\" << std::endl;\n return false;\n }\n\n bool first = true;\n stream << \"(\";\n for (FileToIdSetT::iterator cur = _map.begin(); cur != _map.end(); ++cur)\n {\n const std::string & absPath = cur->first;\n\n if (!first) {\n stream << std::endl << \" \";\n }\n\n stream << \"(\\\"\" << absPath << \"\\\"\";\n IdSetT & ids = cur->second;\n\n for (IdSetT::iterator cur = ids.begin(); cur != ids.end(); ++cur)\n {\n stream << \" \\\"\" << *cur << \"\\\"\";\n }\n\n stream << \")\";\n\n first = false;\n }\n stream << \")\" << std::endl;\n\n return true;\n }\n\n\n\n DEFINE_SET_VERBOSITY_METHOD(OrgIDParser);\n\nprivate:\n VerboseNS::VerbosityTracker _verbosity;\n typedef std::set<std::string> IdSetT;\n typedef std::map<std::string, IdSetT > FileToIdSetT;\n FileToIdSetT _map;\n};\n\nint main(int argc, char *argv[], char *const envp[])\n{\n int verbosity = VerboseNS::E_NONE;\n bool readingDirectories = false;\n typedef std::vector<std::string> DirectoryListT;\n DirectoryListT directories;\n std::string idAlistPath;\n for (int i = 1; i < argc; i++)\n {\n std::string arg = argv[i];\n if (arg.empty()) break;\n if (readingDirectories) {\n \/\/ Get the realPath for things like \".\":\n std::string realPath;\n if (!realPathToString(arg, realPath, true))\n continue;\n directories.push_back(realPath);\n } else {\n if (arg == \"--\") {\n readingDirectories = true;\n } else if (arg == \"-verbose\") {\n verbosity |= VerboseNS::E_VERBOSE;\n } else if (arg == \"-debug\") {\n verbosity |= VerboseNS::E_DEBUG;\n } else if (arg == \"-o\") {\n if (i + 1 >= argc) {\n std::cerr << \"ERROR: -o requires a value.\" << std::endl;\n return 1;\n }\n idAlistPath = argv[++i];\n } else if (arg == \"-h\" || arg == \"--help\") {\n std::cerr << \"USAGE: \" << argv[0] << \" -o OUTPUT-ALIST-FILE [ -verbose ] [ -debug ] [ -h ] -- DIR-1 DIR-2 ... DIR-N\" << std::endl;\n return 0;\n } else {\n std::cerr << \"ERROR: Unrecognized option \" << arg << std::endl;\n return 1;\n }\n }\n }\n\n if (directories.empty()) {\n std::cerr << \"ERROR: No directories specified.\" << std::endl;\n return 1;\n }\n\n if (idAlistPath.empty()) {\n std::cerr << \"ERROR: No alistfile specified.\" << std::endl;\n return 1;\n }\n\n \/\/ OrgIDParser will house the results:\n OrgIDParser parser;\n parser.setVerbosity(verbosity);\n\n \/\/ UniqueFileScanner scans for files and removes duplicates, visiting each\n \/\/ with the parser:\n UniqueFileScanner scanner;\n scanner\n .setVerbosity(verbosity)\n .setVisitor(&parser);\n for (DirectoryListT::iterator cur = directories.begin(); cur != directories.end(); ++cur)\n {\n int success = scanner.scan(*cur);\n if (!success) {\n return 1;\n }\n }\n\n \/\/ Write out the alist file:\n parser.writeIdAlistFile(idAlistPath);\n\n return 0;\n} \/\/ end main\n\n<|endoftext|>"} {"text":"<commit_before>#include \"network_epoll.hpp\"\n\n#include \"unistd.h\"\n#include <sys\/epoll.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/mman.h>\n#include <sys\/ioctl.h>\n#include <sys\/epoll.h>\n#include <sys\/socket.h>\n#include <sys\/eventfd.h>\n#include <netinet\/in.h>\n#include <string.h>\n#include <assert.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#define MAX_EVENTS 16\n\n#ifdef USE_EDGE_TRIGGERED_EPOLL\n#define MODE EPOLLET\n#define READ while\n#else\n#define MODE 0\n#define READ if\n#endif\n\nstatic void errno_exit(const char *s)\n{\n\tstd::ostringstream os;\n\tos << s << \" error \" << errno << \", \" << strerror(errno);\n\tthrow std::runtime_error(os.str());\n}\n\nNetworkThread::NetworkThread(Canvas& canvas, uint16_t port)\n : canvas(canvas)\n{\n\tint fd_max;\n\t{\n\t\tstd::ifstream fd_max_stream(\"\/proc\/sys\/fs\/file-max\");\n\t\tif (!(fd_max_stream >> fd_max)) {\n\t\t\tthrow std::runtime_error(\"Can not read \/proc\/sys\/fs\/file-max\");\n\t\t}\n\t}\n\tstate = new uint64_t[fd_max + 1];\n\n\tepollfd = epoll_create1(0);\n\tif (epollfd == -1)\n\t\terrno_exit(\"epoll_create1\");\n\n\tevfd = eventfd(0, SOCK_NONBLOCK);\n\tstruct epoll_event evee = { .events = EPOLLIN, .data = { .fd = evfd } };\n\tepoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &evee);\n\n\tstruct sockaddr_in6 destAddr = {};\n\tdestAddr.sin6_family = AF_INET6;\n\tdestAddr.sin6_port = htons(port);\n\tserverfd = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);\n\n\tint one = 1;\n\tsetsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);\n\n\tif (serverfd == -1)\n\t\terrno_exit(\"socket\");\n\n\tint err;\n\n\terr = bind(serverfd, (sockaddr*)&destAddr, sizeof(destAddr));\n\tif (err < 0)\n\t\terrno_exit(\"bind\");\n\n\terr = listen(serverfd, 1);\n\tif (err < 0)\n\t\terrno_exit(\"listen\");\n\n\tstruct epoll_event serveree = { .events = EPOLLIN | MODE, .data = { .fd = serverfd } };\n\tepoll_ctl(epollfd, EPOLL_CTL_ADD, serverfd, &serveree);\n\n\tthread = std::thread(&NetworkThread::work, this);\n}\n\nNetworkThread::~NetworkThread()\n{\n\tuint64_t one = 1;\n\twrite(evfd, &one, sizeof one);\n\tthread.join();\n\tuint64_t devnull;\n\tread(evfd, &devnull, sizeof devnull);\n\tdelete[] state;\n}\n\nvoid NetworkThread::work()\n{\n\tconst unsigned xmax = canvas.width, ymax = canvas.height;\n\n\tfor (;;) {\n\t\tstruct epoll_event event[MAX_EVENTS];\n\t\tint eventCnt = epoll_wait(epollfd, event, MAX_EVENTS, -1);\n\t\tfor (int i = 0; i < eventCnt; i++) {\n\t\t\tint fd = event[i].data.fd;\n\n\t\t\tif (fd == evfd) {\n\t\t\t\treturn;\n\t\t\t} else if (fd == serverfd) {\n\t\t\t\tint clientfd;\n\t\t\t\tREAD ((clientfd = accept4(serverfd, nullptr, nullptr, SOCK_NONBLOCK)) >= 0) {\n\t\t\t\t\tstate[clientfd] = 0;\n\t\t\t\t\tstruct epoll_event ee = { .events = EPOLLIN | MODE, .data = { .fd = clientfd } };\n\t\t\t\t\tepoll_ctl(epollfd, EPOLL_CTL_ADD, clientfd, &ee);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tchar buf[32768];\n\t\t\t\tint size;\n\t\t\t\tREAD ((size = read(fd, &buf, sizeof buf - 1)) > 0) {\n\t\t\t\t\tbuf[size] = '\\0';\n\t\t\t\t\tchar* c = buf;\n\t\t\t\t\tuint64_t ss = state[fd];\n\t\t\t\t\tunsigned col = (ss >> 0) & 0xFFFFFFFF;\n\t\t\t\t\tunsigned x = (ss >> 32) & 0x1FFF;\n\t\t\t\t\tunsigned y = (ss >> 45) & 0x1FFF;\n\t\t\t\t\tunsigned comb = (ss >> 58) & 0x3F;\n\t\t\t\t\tunsigned s = comb \/ 9;\n\t\t\t\t\tunsigned dc = comb % 9;\n\t\t\t\t\tswitch (s) {\n\t\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\t case 0:\n\t\t\t\t\t\t\t\tif (*c == 'P') c++; else { s = 0; break; }\n\t\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\t\tif (*c == 'X') c++; else { s = 1; break; }\n\t\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\t\tif (*c == ' ') c++; else { s = 2; break; }\n\t\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\t\twhile (*c >= '0' && *c <= '9' && dc < 4) {\n\t\t\t\t\t\t\t\t\tx = 10 * x + (*c - '0');\n\t\t\t\t\t\t\t\t\tif (x >= xmax)\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (dc && *c == ' ') { dc = 0; c++; } else { s = 3; break; }\n\t\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\t\twhile (*c >= '0' && *c <= '9' && dc < 4) {\n\t\t\t\t\t\t\t\t\ty = 10 * y + (*c - '0');\n\t\t\t\t\t\t\t\t\tif (y >= ymax)\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (dc && *c == ' ') { dc = 0; c++; } else { s = 4; break; }\n\t\t\t\t\t\t\tcase 5:\n\t\t\t\t\t\t\t\ts = 5;\n\t\t\t\t\t\t\t\twhile (dc < 8) {\n\t\t\t\t\t\t\t\t\tif (*c >= '0' && *c <= '9') {\n\t\t\t\t\t\t\t\t\t\tcol = (col << 4) | (*c - '0');\n\t\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\t} else if (*c >= 'a' && *c <= 'f') {\n\t\t\t\t\t\t\t\t\t\tcol = (col << 4) | (*c - 'a' + 0xA);\n\t\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\t} else if (*c >= 'A' && *c <= 'F') {\n\t\t\t\t\t\t\t\t\t\tcol = (col << 4) | (*c - 'A' + 0xA);\n\t\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (*c == '\\r') {\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\ts = 6;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 6:\n\t\t\t\t\t\t\t\tif (*c == '\\n' && (dc == 6 || dc == 8)) {\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\tif (dc == 6) {\n\t\t\t\t\t\t\t\t\t\tcol <<= 8;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcanvas.data[y * canvas.width + x] = col;\n\t\t\t\t\t\t\t\t\ts = x = y = col = dc = 0;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\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\tif (c == buf + size) {\n\t\t\t\t\t\tstate[fd] = ((col & 0xFFFFFFFFL) << 0) | ((x & 0x1FFFL) << 32) | ((y & 0x1FFFL) << 45) | (((s * 9 + dc) & 0x3FL) << 58);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (size == 0) {\n\t\t\t\t\tclose(fd);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Check return value of epoll_ctl<commit_after>#include \"network_epoll.hpp\"\n\n#include \"unistd.h\"\n#include <sys\/epoll.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/mman.h>\n#include <sys\/ioctl.h>\n#include <sys\/epoll.h>\n#include <sys\/socket.h>\n#include <sys\/eventfd.h>\n#include <netinet\/in.h>\n#include <string.h>\n#include <assert.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#define MAX_EVENTS 16\n\n#ifdef USE_EDGE_TRIGGERED_EPOLL\n#define MODE EPOLLET\n#define READ while\n#else\n#define MODE 0\n#define READ if\n#endif\n\nstatic void errno_exit(const char *s)\n{\n\tstd::ostringstream os;\n\tos << s << \" error \" << errno << \", \" << strerror(errno);\n\tthrow std::runtime_error(os.str());\n}\n\nNetworkThread::NetworkThread(Canvas& canvas, uint16_t port)\n : canvas(canvas)\n{\n\tint fd_max;\n\t{\n\t\tstd::ifstream fd_max_stream(\"\/proc\/sys\/fs\/file-max\");\n\t\tif (!(fd_max_stream >> fd_max)) {\n\t\t\tthrow std::runtime_error(\"Can not read \/proc\/sys\/fs\/file-max\");\n\t\t}\n\t}\n\tstate = new uint64_t[fd_max + 1];\n\n\tepollfd = epoll_create1(0);\n\tif (epollfd == -1)\n\t\terrno_exit(\"epoll_create1\");\n\n\tevfd = eventfd(0, SOCK_NONBLOCK);\n\tstruct epoll_event evee = { .events = EPOLLIN, .data = { .fd = evfd } };\n\tepoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &evee);\n\n\tstruct sockaddr_in6 destAddr = {};\n\tdestAddr.sin6_family = AF_INET6;\n\tdestAddr.sin6_port = htons(port);\n\tserverfd = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);\n\n\tint one = 1;\n\tsetsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);\n\n\tif (serverfd == -1)\n\t\terrno_exit(\"socket\");\n\n\tint err;\n\n\terr = bind(serverfd, (sockaddr*)&destAddr, sizeof(destAddr));\n\tif (err < 0)\n\t\terrno_exit(\"bind\");\n\n\terr = listen(serverfd, 1);\n\tif (err < 0)\n\t\terrno_exit(\"listen\");\n\n\tstruct epoll_event serveree = { .events = EPOLLIN | MODE, .data = { .fd = serverfd } };\n\terr = epoll_ctl(epollfd, EPOLL_CTL_ADD, serverfd, &serveree);\n\tif (err < 0)\n\t\terrno_exit(\"epoll_ctl add server\");\n\n\tthread = std::thread(&NetworkThread::work, this);\n}\n\nNetworkThread::~NetworkThread()\n{\n\tuint64_t one = 1;\n\twrite(evfd, &one, sizeof one);\n\tthread.join();\n\tuint64_t devnull;\n\tread(evfd, &devnull, sizeof devnull);\n\tdelete[] state;\n}\n\nvoid NetworkThread::work()\n{\n\tconst unsigned xmax = canvas.width, ymax = canvas.height;\n\n\tfor (;;) {\n\t\tstruct epoll_event event[MAX_EVENTS];\n\t\tint eventCnt = epoll_wait(epollfd, event, MAX_EVENTS, -1);\n\t\tfor (int i = 0; i < eventCnt; i++) {\n\t\t\tint fd = event[i].data.fd;\n\n\t\t\tif (fd == evfd) {\n\t\t\t\treturn;\n\t\t\t} else if (fd == serverfd) {\n\t\t\t\tint clientfd;\n\t\t\t\tREAD ((clientfd = accept4(serverfd, nullptr, nullptr, SOCK_NONBLOCK)) >= 0) {\n\t\t\t\t\tstate[clientfd] = 0;\n\t\t\t\t\tstruct epoll_event ee = { .events = EPOLLIN | MODE, .data = { .fd = clientfd } };\n\t\t\t\t\tint err = epoll_ctl(epollfd, EPOLL_CTL_ADD, clientfd, &ee);\n\t\t\t\t\tif (err < 0)\n\t\t\t\t\t\terrno_exit(\"epoll_ctl add client\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tchar buf[32768];\n\t\t\t\tint size;\n\t\t\t\tREAD ((size = read(fd, &buf, sizeof buf - 1)) > 0) {\n\t\t\t\t\tbuf[size] = '\\0';\n\t\t\t\t\tchar* c = buf;\n\t\t\t\t\tuint64_t ss = state[fd];\n\t\t\t\t\tunsigned col = (ss >> 0) & 0xFFFFFFFF;\n\t\t\t\t\tunsigned x = (ss >> 32) & 0x1FFF;\n\t\t\t\t\tunsigned y = (ss >> 45) & 0x1FFF;\n\t\t\t\t\tunsigned comb = (ss >> 58) & 0x3F;\n\t\t\t\t\tunsigned s = comb \/ 9;\n\t\t\t\t\tunsigned dc = comb % 9;\n\t\t\t\t\tswitch (s) {\n\t\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\t case 0:\n\t\t\t\t\t\t\t\tif (*c == 'P') c++; else { s = 0; break; }\n\t\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\t\tif (*c == 'X') c++; else { s = 1; break; }\n\t\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\t\tif (*c == ' ') c++; else { s = 2; break; }\n\t\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\t\twhile (*c >= '0' && *c <= '9' && dc < 4) {\n\t\t\t\t\t\t\t\t\tx = 10 * x + (*c - '0');\n\t\t\t\t\t\t\t\t\tif (x >= xmax)\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (dc && *c == ' ') { dc = 0; c++; } else { s = 3; break; }\n\t\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\t\twhile (*c >= '0' && *c <= '9' && dc < 4) {\n\t\t\t\t\t\t\t\t\ty = 10 * y + (*c - '0');\n\t\t\t\t\t\t\t\t\tif (y >= ymax)\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (dc && *c == ' ') { dc = 0; c++; } else { s = 4; break; }\n\t\t\t\t\t\t\tcase 5:\n\t\t\t\t\t\t\t\ts = 5;\n\t\t\t\t\t\t\t\twhile (dc < 8) {\n\t\t\t\t\t\t\t\t\tif (*c >= '0' && *c <= '9') {\n\t\t\t\t\t\t\t\t\t\tcol = (col << 4) | (*c - '0');\n\t\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\t} else if (*c >= 'a' && *c <= 'f') {\n\t\t\t\t\t\t\t\t\t\tcol = (col << 4) | (*c - 'a' + 0xA);\n\t\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\t} else if (*c >= 'A' && *c <= 'F') {\n\t\t\t\t\t\t\t\t\t\tcol = (col << 4) | (*c - 'A' + 0xA);\n\t\t\t\t\t\t\t\t\t\tdc++;\n\t\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (*c == '\\r') {\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\ts = 6;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 6:\n\t\t\t\t\t\t\t\tif (*c == '\\n' && (dc == 6 || dc == 8)) {\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\tif (dc == 6) {\n\t\t\t\t\t\t\t\t\t\tcol <<= 8;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcanvas.data[y * canvas.width + x] = col;\n\t\t\t\t\t\t\t\t\ts = x = y = col = dc = 0;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\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\tif (c == buf + size) {\n\t\t\t\t\t\tstate[fd] = ((col & 0xFFFFFFFFL) << 0) | ((x & 0x1FFFL) << 32) | ((y & 0x1FFFL) << 45) | (((s * 9 + dc) & 0x3FL) << 58);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (size == 0) {\n\t\t\t\t\tclose(fd);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#if defined(LINUX)\n#include \"user\/wqlinux.hh\"\n#elif defined(XV6_KERNEL)\n#include \"wqkernel.hh\"\n#else\n#include \"wquser.hh\"\n#endif\n#include \"percpu.hh\"\n\n#define NSLOTS (1 << WQSHIFT)\n\nclass wq {\npublic:\n wq();\n int push(work *w, int tcpuid);\n int trywork();\n void dump();\n\n static void* operator new(unsigned long);\n\nprivate:\n work *steal(int c);\n work *pop(int c);\n void inclen(int c);\n void declen(int c);\n\n struct wqueue {\n work *w[NSLOTS];\n volatile int head __mpalign__;\n volatile int tail;\n wqlock_t lock;\n };\n\n struct stat {\n u64 push;\n u64 full;\n u64 pop;\n u64 steal;\n };\n\n percpu<wqueue> q_;\n percpu<stat> stat_;\n\n#if defined(XV6_USER)\n uwq_ipcbuf* ipc_;\n#endif\n};\n\nstatic wq *wq_;\n\nsize_t\nwq_size(void)\n{\n return sizeof(wq);\n}\n\nint\nwq_push(work *w)\n{\n return wq_->push(w, mycpuid());\n}\n\nint\nwq_pushto(work *w, int tcpuid)\n{\n return wq_->push(w, tcpuid);\n}\n\nint\nwq_trywork(void)\n{\n return wq_->trywork();\n}\n\nvoid\nwq_dump(void)\n{\n return wq_->dump();\n}\n\nvoid\ninitwq(void)\n{\n wq_ = new wq();\n wqarch_init();\n}\n\n\/\/\n\/\/ wq\n\/\/\nvoid*\nwq::operator new(unsigned long nbytes)\n{\n assert(nbytes == sizeof(wq));\n return allocwq(nbytes);\n}\n\nwq::wq(void)\n{\n int i;\n\n for (i = 0; i < NCPU; i++)\n wqlock_init(&q_[i].lock);\n\n#if defined(XV6_USER)\n ipc_ = allocipc();\n assert(wq_maxworkers <= NWORKERS);\n ipc_->maxworkers = wq_maxworkers;\n#endif\n}\n\nvoid\nwq::dump(void)\n{\n int i;\n for (i = 0; i < NCPU; i++)\n xprintf(\"push %lu full %lu pop %lu steal %lu\\n\",\n stat_[i].push, stat_[i].full,\n stat_[i].pop, stat_[i].steal);\n}\n\ninline void\nwq::inclen(int c)\n{\n#if defined(XV6_USER)\n __sync_fetch_and_add(&ipc_->len[c].v_, 1);\n#endif\n}\n\ninline void\nwq::declen(int c)\n{\n#if defined(XV6_USER)\n __sync_fetch_and_sub(&ipc_->len[c].v_, 1);\n#endif\n}\n\nint\nwq::push(work *w, int tcpuid)\n{\n int i;\n\n acquire(&q_[tcpuid].lock);\n i = q_[tcpuid].head;\n if ((i - q_[tcpuid].tail) == NSLOTS) {\n stat_[tcpuid].full++;\n release(&q_[tcpuid].lock);\n return -1;\n }\n i = i & (NSLOTS-1);\n q_[tcpuid].w[i] = w;\n barrier();\n q_[tcpuid].head++;\n inclen(tcpuid);\n stat_[tcpuid].push++;\n release(&q_[tcpuid].lock);\n return 0;\n}\n\ninline work*\nwq::pop(int c)\n{\n struct wqueue *q = &q_[c];\n work *w;\n int i;\n\n i = q->head;\n if ((i - q->tail) == 0)\n return 0;\n \n wqlock_acquire(&q->lock);\n i = q->head;\n if ((i - q->tail) == 0) {\n wqlock_release(&q->lock);\n return 0;\n }\n i = (i-1) & (NSLOTS-1);\n w = q->w[i];\n q->head--;\n declen(c);\n wqlock_release(&q->lock);\n\n stat_->pop++;\n return w;\n}\n\ninline work*\nwq::steal(int c)\n{\n struct wqueue *q = &q_[c];\n work *w;\n int i;\n\n if (wqlock_tryacquire(&q->lock) == 0)\n return 0;\n i = q->tail;\n if ((i - q->head) == 0) {\n wqlock_release(&q->lock);\n return 0;\n }\n i = i & (NSLOTS-1);\n w = q->w[i];\n q->tail++;\n declen(c);\n wqlock_release(&q->lock);\n\n stat_->steal++;\n return w;\n}\n\nint\nwq::trywork(void)\n{\n work *w;\n u64 i, k;\n\n \/\/ A \"random\" victim CPU\n k = rdtsc();\n\n w = pop(mycpuid());\n if (w != nullptr) {\n w->run();\n return 1;\n }\n\n for (i = 0; i < NCPU; i++) {\n u64 j = (i+k) % NCPU;\n\n if (j == mycpuid())\n continue;\n \n w = steal(j);\n if (w != nullptr) {\n w->run();\n return 1;\n }\n }\n\n return 0;\n}\n\n\/\/\n\/\/ cwork\n\/\/\nvoid\ncwork::run(void)\n{\n void (*fn)(void*, void*, void*, void*, void*) = \n (void(*)(void*,void*,void*,void*,void*))rip;\n fn(arg0, arg1, arg2, arg3, arg4);\n delete this;\n}\n\nvoid*\ncwork::operator new(unsigned long nbytes)\n{\n assert(nbytes == sizeof(cwork));\n return xallocwork(sizeof(cwork));\n}\n\nvoid*\ncwork::operator new(unsigned long nbytes, cwork* buf)\n{\n assert(nbytes == sizeof(cwork));\n return buf;\n}\n\nvoid\ncwork::operator delete(void *p)\n{\n xfreework(p, sizeof(cwork));\n}\n<commit_msg>flag to avoid stealing in the workqueue code, needed to ensure the exec-cleanup and wait-cleanup handlers run on the right core (disabled by default).<commit_after>#if defined(LINUX)\n#include \"user\/wqlinux.hh\"\n#elif defined(XV6_KERNEL)\n#include \"wqkernel.hh\"\n#else\n#include \"wquser.hh\"\n#endif\n#include \"percpu.hh\"\n\n#define NSLOTS (1 << WQSHIFT)\n\nenum { wq_steal_others = 1 };\n\nclass wq {\npublic:\n wq();\n int push(work *w, int tcpuid);\n int trywork();\n void dump();\n\n static void* operator new(unsigned long);\n\nprivate:\n work *steal(int c);\n work *pop(int c);\n void inclen(int c);\n void declen(int c);\n\n struct wqueue {\n work *w[NSLOTS];\n volatile int head __mpalign__;\n volatile int tail;\n wqlock_t lock;\n };\n\n struct stat {\n u64 push;\n u64 full;\n u64 pop;\n u64 steal;\n };\n\n percpu<wqueue> q_;\n percpu<stat> stat_;\n\n#if defined(XV6_USER)\n uwq_ipcbuf* ipc_;\n#endif\n};\n\nstatic wq *wq_;\n\nsize_t\nwq_size(void)\n{\n return sizeof(wq);\n}\n\nint\nwq_push(work *w)\n{\n return wq_->push(w, mycpuid());\n}\n\nint\nwq_pushto(work *w, int tcpuid)\n{\n return wq_->push(w, tcpuid);\n}\n\nint\nwq_trywork(void)\n{\n return wq_->trywork();\n}\n\nvoid\nwq_dump(void)\n{\n return wq_->dump();\n}\n\nvoid\ninitwq(void)\n{\n wq_ = new wq();\n wqarch_init();\n}\n\n\/\/\n\/\/ wq\n\/\/\nvoid*\nwq::operator new(unsigned long nbytes)\n{\n assert(nbytes == sizeof(wq));\n return allocwq(nbytes);\n}\n\nwq::wq(void)\n{\n int i;\n\n for (i = 0; i < NCPU; i++)\n wqlock_init(&q_[i].lock);\n\n#if defined(XV6_USER)\n ipc_ = allocipc();\n assert(wq_maxworkers <= NWORKERS);\n ipc_->maxworkers = wq_maxworkers;\n#endif\n}\n\nvoid\nwq::dump(void)\n{\n int i;\n for (i = 0; i < NCPU; i++)\n xprintf(\"push %lu full %lu pop %lu steal %lu\\n\",\n stat_[i].push, stat_[i].full,\n stat_[i].pop, stat_[i].steal);\n}\n\ninline void\nwq::inclen(int c)\n{\n#if defined(XV6_USER)\n __sync_fetch_and_add(&ipc_->len[c].v_, 1);\n#endif\n}\n\ninline void\nwq::declen(int c)\n{\n#if defined(XV6_USER)\n __sync_fetch_and_sub(&ipc_->len[c].v_, 1);\n#endif\n}\n\nint\nwq::push(work *w, int tcpuid)\n{\n int i;\n\n acquire(&q_[tcpuid].lock);\n i = q_[tcpuid].head;\n if ((i - q_[tcpuid].tail) == NSLOTS) {\n stat_[tcpuid].full++;\n release(&q_[tcpuid].lock);\n return -1;\n }\n i = i & (NSLOTS-1);\n q_[tcpuid].w[i] = w;\n barrier();\n q_[tcpuid].head++;\n inclen(tcpuid);\n stat_[tcpuid].push++;\n release(&q_[tcpuid].lock);\n return 0;\n}\n\ninline work*\nwq::pop(int c)\n{\n struct wqueue *q = &q_[c];\n work *w;\n int i;\n\n i = q->head;\n if ((i - q->tail) == 0)\n return 0;\n \n wqlock_acquire(&q->lock);\n i = q->head;\n if ((i - q->tail) == 0) {\n wqlock_release(&q->lock);\n return 0;\n }\n i = (i-1) & (NSLOTS-1);\n w = q->w[i];\n q->head--;\n declen(c);\n wqlock_release(&q->lock);\n\n stat_->pop++;\n return w;\n}\n\ninline work*\nwq::steal(int c)\n{\n if (!wq_steal_others && (c != mycpuid()))\n return 0;\n\n struct wqueue *q = &q_[c];\n work *w;\n int i;\n\n if (wqlock_tryacquire(&q->lock) == 0)\n return 0;\n i = q->tail;\n if ((i - q->head) == 0) {\n wqlock_release(&q->lock);\n return 0;\n }\n i = i & (NSLOTS-1);\n w = q->w[i];\n q->tail++;\n declen(c);\n wqlock_release(&q->lock);\n\n stat_->steal++;\n return w;\n}\n\nint\nwq::trywork(void)\n{\n work *w;\n u64 i, k;\n\n \/\/ A \"random\" victim CPU\n k = rdtsc();\n\n w = pop(mycpuid());\n if (w != nullptr) {\n w->run();\n return 1;\n }\n\n for (i = 0; i < NCPU; i++) {\n u64 j = (i+k) % NCPU;\n\n if (j == mycpuid())\n continue;\n \n w = steal(j);\n if (w != nullptr) {\n w->run();\n return 1;\n }\n }\n\n return 0;\n}\n\n\/\/\n\/\/ cwork\n\/\/\nvoid\ncwork::run(void)\n{\n void (*fn)(void*, void*, void*, void*, void*) = \n (void(*)(void*,void*,void*,void*,void*))rip;\n fn(arg0, arg1, arg2, arg3, arg4);\n delete this;\n}\n\nvoid*\ncwork::operator new(unsigned long nbytes)\n{\n assert(nbytes == sizeof(cwork));\n return xallocwork(sizeof(cwork));\n}\n\nvoid*\ncwork::operator new(unsigned long nbytes, cwork* buf)\n{\n assert(nbytes == sizeof(cwork));\n return buf;\n}\n\nvoid\ncwork::operator delete(void *p)\n{\n xfreework(p, sizeof(cwork));\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Delete Worker.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/data\/buffer_chain.hpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_DATA_BUFFER_CHAIN_HEADER\n#define C7A_DATA_BUFFER_CHAIN_HEADER\n\n#include <deque>\n#include <condition_variable>\n#include <mutex> \/\/mutex, unique_lock\n\n#include <c7a\/data\/binary_buffer.hpp>\n#include <c7a\/data\/emitter_target.hpp>\n\nnamespace c7a {\nnamespace data {\n\n\/\/! Elements of a singly linked list, holding a immuteable buffer\nstruct BufferChainElement {\n BufferChainElement(BinaryBuffer b, size_t element_count, size_t offset = 0)\n : buffer(b),\n element_count(element_count),\n offset_of_first(offset) {\n \/\/TODO(ts, sl) implement offset logic\n assert(offset_of_first == 0); \/\/no support for offset right now\n }\n\n \/\/! BinaryBuffer holds the data\n BinaryBuffer buffer;\n\n \/\/! prefixsum of number of elements of previous BufferChainElements and\n \/\/! this BufferChainElement\n size_t element_count;\n\n \/\/! offset to the first element in the BinaryBuffer\n \/\/! The cut-off element before that offset is not included in the element_count\n size_t offset_of_first;\n};\n\nusing BufferChainIterator = std::deque<BufferChainElement>::const_iterator;\n\n\/\/! A Buffer chain holds multiple immuteable buffers.\n\/\/! Append in O(1), Delete in O(num_buffers)\nstruct BufferChain : public EmitterTarget {\n BufferChain() : closed_(false) { }\n\n \/\/! Appends a BinaryBufferBuffer's content to the chain\n \/\/! This method is thread-safe and runs in O(1)\n \/\/! \\Param b buffer to append\n void Append(BinaryBufferBuilder& b) {\n std::unique_lock<std::mutex> lock(append_mutex_);\n elements_.emplace_back(BufferChainElement(BinaryBuffer(b), size() + b.elements()));\n b.Detach();\n lock.unlock();\n NotifyWaitingThreads();\n }\n\n \/\/! Waits until beeing notified\n void Wait() {\n std::unique_lock<std::mutex> lock(mutex_);\n condition_variable_.wait(lock);\n }\n\n \/\/! Waits until beeing notified and closed == true\n void WaitUntilClosed() {\n std::unique_lock<std::mutex> lock(mutex_);\n condition_variable_.wait(lock, [=]() { return this->closed_; });\n }\n\n \/\/! Call buffers' destructors and deconstructs the chain\n void Delete() {\n std::unique_lock<std::mutex> lock(append_mutex_);\n for (auto& elem : elements_)\n elem.buffer.Delete();\n }\n\n \/\/! Returns the number of elements in this BufferChain at the current\n \/\/! state.\n size_t size() {\n if (elements_.empty())\n return 0;\n return elements_.back().element_count;\n }\n\n BufferChainIterator Begin() {\n return elements_.begin();\n }\n\n BufferChainIterator End() {\n \/\/TODO(ts) this should point to the last element in the buffer\n return elements_.end();\n }\n\n void Close() {\n closed_ = true;\n NotifyWaitingThreads();\n }\n\n bool IsClosed() { return closed_; }\n\n std::deque<BufferChainElement> elements_;\n\nprivate:\n std::mutex mutex_;\n std::mutex append_mutex_;\n std::condition_variable condition_variable_;\n bool closed_;\n\n void NotifyWaitingThreads() {\n std::unique_lock<std::mutex> lock(mutex_);\n condition_variable_.notify_all();\n }\n};\n\n} \/\/ namespace data\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_DATA_BUFFER_CHAIN_HEADER\n\n\/******************************************************************************\/\n<commit_msg>remove false comment<commit_after>\/*******************************************************************************\n * c7a\/data\/buffer_chain.hpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_DATA_BUFFER_CHAIN_HEADER\n#define C7A_DATA_BUFFER_CHAIN_HEADER\n\n#include <deque>\n#include <condition_variable>\n#include <mutex> \/\/mutex, unique_lock\n\n#include <c7a\/data\/binary_buffer.hpp>\n#include <c7a\/data\/emitter_target.hpp>\n\nnamespace c7a {\nnamespace data {\n\n\/\/! Elements of a singly linked list, holding a immuteable buffer\nstruct BufferChainElement {\n BufferChainElement(BinaryBuffer b, size_t element_count, size_t offset = 0)\n : buffer(b),\n element_count(element_count),\n offset_of_first(offset) {\n \/\/TODO(ts, sl) implement offset logic\n assert(offset_of_first == 0); \/\/no support for offset right now\n }\n\n \/\/! BinaryBuffer holds the data\n BinaryBuffer buffer;\n\n \/\/! prefixsum of number of elements of previous BufferChainElements and\n \/\/! this BufferChainElement\n size_t element_count;\n\n \/\/! offset to the first element in the BinaryBuffer\n \/\/! The cut-off element before that offset is not included in the element_count\n size_t offset_of_first;\n};\n\nusing BufferChainIterator = std::deque<BufferChainElement>::const_iterator;\n\n\/\/! A Buffer chain holds multiple immuteable buffers.\n\/\/! Append in O(1), Delete in O(num_buffers)\nstruct BufferChain : public EmitterTarget {\n BufferChain() : closed_(false) { }\n\n \/\/! Appends a BinaryBufferBuffer's content to the chain\n \/\/! This method is thread-safe and runs in O(1)\n \/\/! \\Param b buffer to append\n void Append(BinaryBufferBuilder& b) {\n std::unique_lock<std::mutex> lock(append_mutex_);\n elements_.emplace_back(BufferChainElement(BinaryBuffer(b), size() + b.elements()));\n b.Detach();\n lock.unlock();\n NotifyWaitingThreads();\n }\n\n \/\/! Waits until beeing notified\n void Wait() {\n std::unique_lock<std::mutex> lock(mutex_);\n condition_variable_.wait(lock);\n }\n\n \/\/! Waits until beeing notified and closed == true\n void WaitUntilClosed() {\n std::unique_lock<std::mutex> lock(mutex_);\n condition_variable_.wait(lock, [=]() { return this->closed_; });\n }\n\n \/\/! Call buffers' destructors and deconstructs the chain\n void Delete() {\n std::unique_lock<std::mutex> lock(append_mutex_);\n for (auto& elem : elements_)\n elem.buffer.Delete();\n }\n\n \/\/! Returns the number of elements in this BufferChain at the current\n \/\/! state.\n size_t size() {\n if (elements_.empty())\n return 0;\n return elements_.back().element_count;\n }\n\n BufferChainIterator Begin() {\n return elements_.begin();\n }\n\n BufferChainIterator End() {\n return elements_.end();\n }\n\n void Close() {\n closed_ = true;\n NotifyWaitingThreads();\n }\n\n bool IsClosed() { return closed_; }\n\n std::deque<BufferChainElement> elements_;\n\nprivate:\n std::mutex mutex_;\n std::mutex append_mutex_;\n std::condition_variable condition_variable_;\n bool closed_;\n\n void NotifyWaitingThreads() {\n std::unique_lock<std::mutex> lock(mutex_);\n condition_variable_.notify_all();\n }\n};\n\n} \/\/ namespace data\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_DATA_BUFFER_CHAIN_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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\/browser\/browser_about_handler.h\"\n\n#include <algorithm>\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/net\/url_fixer_upper.h\"\n#include \"chrome\/browser\/ui\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n\nnamespace {\n\n\/\/ Add paths here to be included in chrome:\/\/chrome-urls (about:about).\n\/\/ These paths will also be suggested by BuiltinProvider.\nconst char* const kPaths[] = {\n chrome::kChromeUIAppCacheInternalsHost,\n chrome::kChromeUIBlobInternalsHost,\n chrome::kChromeUICacheHost,\n chrome::kChromeUIChromeURLsHost,\n chrome::kChromeUICrashesHost,\n chrome::kChromeUICreditsHost,\n chrome::kChromeUIDNSHost,\n chrome::kChromeUIGpuInternalsHost,\n chrome::kChromeUIHistoryHost,\n chrome::kChromeUIIPCHost,\n chrome::kChromeUIMediaInternalsHost,\n chrome::kChromeUIMemoryHost,\n chrome::kChromeUINetInternalsHost,\n chrome::kChromeUINetworkViewCacheHost,\n chrome::kChromeUINewTabHost,\n chrome::kChromeUIOmniboxHost,\n chrome::kChromeUIPredictorsHost,\n chrome::kChromeUIProfilerHost,\n chrome::kChromeUIQuotaInternalsHost,\n chrome::kChromeUIStatsHost,\n chrome::kChromeUISyncInternalsHost,\n chrome::kChromeUITermsHost,\n chrome::kChromeUIVersionHost,\n#if defined(OS_ANDROID)\n chrome::kChromeUIWelcomeHost,\n#else\n chrome::kChromeUIBookmarksHost,\n chrome::kChromeUIDownloadsHost,\n \/\/ TODO(dfalcantara): Enable after http:\/\/crbug.com\/143146 is fixed.\n chrome::kChromeUIFlagsHost,\n chrome::kChromeUIFlashHost,\n chrome::kChromeUIInspectHost,\n chrome::kChromeUIPluginsHost,\n chrome::kChromeUISettingsHost,\n chrome::kChromeUITracingHost,\n#endif\n#if defined(OS_WIN)\n chrome::kChromeUIConflictsHost,\n#endif\n#if defined(OS_LINUX) || defined(OS_OPENBSD)\n chrome::kChromeUILinuxProxyConfigHost,\n chrome::kChromeUISandboxHost,\n#endif\n#if defined(OS_CHROMEOS)\n chrome::kChromeUIChooseMobileNetworkHost,\n chrome::kChromeUICryptohomeHost,\n chrome::kChromeUIDiagnosticsHost,\n chrome::kChromeUIDiscardsHost,\n chrome::kChromeUIDriveInternalsHost,\n chrome::kChromeUIImageBurnerHost,\n chrome::kChromeUIKeyboardOverlayHost,\n chrome::kChromeUILoginHost,\n chrome::kChromeUINetworkHost,\n chrome::kChromeUIOobeHost,\n chrome::kChromeUIOSCreditsHost,\n chrome::kChromeUIProxySettingsHost,\n chrome::kChromeUISystemInfoHost,\n chrome::kChromeUITaskManagerHost,\n chrome::kChromeUIWallpaperHost,\n#endif\n#if !defined(DISABLE_NACL)\n chrome::kChromeUINaClHost,\n#endif\n#if defined(ENABLE_CONFIGURATION_POLICY)\n chrome::kChromeUIPolicyHost,\n#endif\n#if defined(ENABLE_EXTENSIONS)\n chrome::kChromeUIExtensionsHost,\n#endif\n#if defined(ENABLE_PRINTING)\n chrome::kChromeUIPrintHost,\n#endif\n};\n\n} \/\/ namespace\n\nbool WillHandleBrowserAboutURL(GURL* url,\n content::BrowserContext* browser_context) {\n \/\/ TODO(msw): Eliminate \"about:*\" constants and literals from code and tests,\n \/\/ then hopefully we can remove this forced fixup.\n *url = URLFixerUpper::FixupURL(url->possibly_invalid_spec(), std::string());\n\n \/\/ Check that about: URLs are fixed up to chrome: by URLFixerUpper::FixupURL.\n DCHECK((*url == GURL(chrome::kAboutBlankURL)) ||\n !url->SchemeIs(chrome::kAboutScheme));\n\n \/\/ Only handle chrome:\/\/foo\/, URLFixerUpper::FixupURL translates about:foo.\n if (!url->SchemeIs(chrome::kChromeUIScheme))\n return false;\n\n std::string host(url->host());\n std::string path;\n \/\/ Replace about with chrome-urls.\n if (host == chrome::kChromeUIAboutHost)\n host = chrome::kChromeUIChromeURLsHost;\n \/\/ Replace cache with view-http-cache.\n if (host == chrome::kChromeUICacheHost) {\n host = chrome::kChromeUINetworkViewCacheHost;\n \/\/ Replace gpu with gpu-internals.\n } else if (host == chrome::kChromeUIGpuHost) {\n host = chrome::kChromeUIGpuInternalsHost;\n \/\/ Replace sync with sync-internals (for legacy reasons).\n } else if (host == chrome::kChromeUISyncHost) {\n host = chrome::kChromeUISyncInternalsHost;\n \/\/ Redirect chrome:\/\/extensions.\n } else if (host == chrome::kChromeUIExtensionsHost) {\n host = chrome::kChromeUIUberHost;\n path = chrome::kChromeUIExtensionsHost + url->path();\n \/\/ Redirect chrome:\/\/settings\/extensions.\n \/\/ TODO(csilv): Remove this URL after M22 (legacy URL).\n } else if (host == chrome::kChromeUISettingsHost &&\n url->path() == std::string(\"\/\") + chrome::kExtensionsSubPage) {\n host = chrome::kChromeUIUberHost;\n path = chrome::kChromeUIExtensionsHost;\n \/\/ Redirect chrome:\/\/history.\n } else if (host == chrome::kChromeUIHistoryHost) {\n host = chrome::kChromeUIUberHost;\n path = chrome::kChromeUIHistoryHost + url->path();\n \/\/ Redirect chrome:\/\/settings\n } else if (host == chrome::kChromeUISettingsHost) {\n host = chrome::kChromeUIUberHost;\n path = chrome::kChromeUISettingsHost + url->path();\n }\n GURL::Replacements replacements;\n replacements.SetHostStr(host);\n if (!path.empty())\n replacements.SetPathStr(path);\n *url = url->ReplaceComponents(replacements);\n\n \/\/ Having re-written the URL, make the chrome: handler process it.\n return false;\n}\n\nbool HandleNonNavigationAboutURL(const GURL& url) {\n std::string host(url.host());\n\n \/\/ chrome:\/\/ipc\/ is currently buggy, so we disable it for official builds.\n#if !defined(OFFICIAL_BUILD)\n\n#if (defined(OS_MACOSX) || defined(OS_WIN)) && defined(IPC_MESSAGE_LOG_ENABLED)\n if (LowerCaseEqualsASCII(url.spec(), chrome::kChromeUIIPCURL)) {\n \/\/ Run the dialog. This will re-use the existing one if it's already up.\n chrome::ShowAboutIPCDialog();\n return true;\n }\n#endif\n\n#endif \/\/ OFFICIAL_BUILD\n\n return false;\n}\n\nstd::vector<std::string> ChromePaths() {\n std::vector<std::string> paths(kPaths, kPaths + arraysize(kPaths));\n std::sort(paths.begin(), paths.end());\n return paths;\n}\n<commit_msg>Revert r158555 \"[Android] Exclude unsupported URLs from chrome:\/\/chrome-urls.\"<commit_after>\/\/ 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\/browser\/browser_about_handler.h\"\n\n#include <algorithm>\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/net\/url_fixer_upper.h\"\n#include \"chrome\/browser\/ui\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n\nnamespace {\n\n\/\/ Add paths here to be included in chrome:\/\/chrome-urls (about:about).\n\/\/ These paths will also be suggested by BuiltinProvider.\nconst char* const kPaths[] = {\n chrome::kChromeUIAppCacheInternalsHost,\n chrome::kChromeUIBlobInternalsHost,\n chrome::kChromeUIBookmarksHost,\n chrome::kChromeUICacheHost,\n chrome::kChromeUIChromeURLsHost,\n chrome::kChromeUICrashesHost,\n chrome::kChromeUICreditsHost,\n chrome::kChromeUIDNSHost,\n chrome::kChromeUIDownloadsHost,\n chrome::kChromeUIExtensionsHost,\n chrome::kChromeUIFlagsHost,\n chrome::kChromeUIFlashHost,\n chrome::kChromeUIGpuInternalsHost,\n chrome::kChromeUIHistoryHost,\n chrome::kChromeUIIPCHost,\n chrome::kChromeUIInspectHost,\n chrome::kChromeUIMediaInternalsHost,\n chrome::kChromeUIMemoryHost,\n chrome::kChromeUINaClHost,\n chrome::kChromeUINetInternalsHost,\n chrome::kChromeUINetworkViewCacheHost,\n chrome::kChromeUINewTabHost,\n chrome::kChromeUIOmniboxHost,\n chrome::kChromeUIPluginsHost,\n chrome::kChromeUIPolicyHost,\n chrome::kChromeUIPredictorsHost,\n chrome::kChromeUIProfilerHost,\n chrome::kChromeUIQuotaInternalsHost,\n chrome::kChromeUISettingsHost,\n chrome::kChromeUIStatsHost,\n chrome::kChromeUISyncInternalsHost,\n#if defined(OS_CHROMEOS)\n chrome::kChromeUITaskManagerHost,\n#endif\n chrome::kChromeUITermsHost,\n chrome::kChromeUITracingHost,\n chrome::kChromeUIVersionHost,\n#if defined(OS_WIN)\n chrome::kChromeUIConflictsHost,\n#endif\n#if defined(OS_LINUX) || defined(OS_OPENBSD)\n chrome::kChromeUILinuxProxyConfigHost,\n chrome::kChromeUISandboxHost,\n#endif\n#if defined(OS_CHROMEOS)\n chrome::kChromeUIChooseMobileNetworkHost,\n chrome::kChromeUICryptohomeHost,\n chrome::kChromeUIDiagnosticsHost,\n chrome::kChromeUIDiscardsHost,\n chrome::kChromeUIDriveInternalsHost,\n chrome::kChromeUIImageBurnerHost,\n chrome::kChromeUIKeyboardOverlayHost,\n chrome::kChromeUILoginHost,\n chrome::kChromeUINetworkHost,\n chrome::kChromeUIOobeHost,\n chrome::kChromeUIOSCreditsHost,\n chrome::kChromeUIProxySettingsHost,\n chrome::kChromeUISystemInfoHost,\n chrome::kChromeUIWallpaperHost,\n#endif\n#if defined(ENABLE_PRINTING)\n chrome::kChromeUIPrintHost,\n#endif\n};\n\n} \/\/ namespace\n\nbool WillHandleBrowserAboutURL(GURL* url,\n content::BrowserContext* browser_context) {\n \/\/ TODO(msw): Eliminate \"about:*\" constants and literals from code and tests,\n \/\/ then hopefully we can remove this forced fixup.\n *url = URLFixerUpper::FixupURL(url->possibly_invalid_spec(), std::string());\n\n \/\/ Check that about: URLs are fixed up to chrome: by URLFixerUpper::FixupURL.\n DCHECK((*url == GURL(chrome::kAboutBlankURL)) ||\n !url->SchemeIs(chrome::kAboutScheme));\n\n \/\/ Only handle chrome:\/\/foo\/, URLFixerUpper::FixupURL translates about:foo.\n if (!url->SchemeIs(chrome::kChromeUIScheme))\n return false;\n\n std::string host(url->host());\n std::string path;\n \/\/ Replace about with chrome-urls.\n if (host == chrome::kChromeUIAboutHost)\n host = chrome::kChromeUIChromeURLsHost;\n \/\/ Replace cache with view-http-cache.\n if (host == chrome::kChromeUICacheHost) {\n host = chrome::kChromeUINetworkViewCacheHost;\n \/\/ Replace gpu with gpu-internals.\n } else if (host == chrome::kChromeUIGpuHost) {\n host = chrome::kChromeUIGpuInternalsHost;\n \/\/ Replace sync with sync-internals (for legacy reasons).\n } else if (host == chrome::kChromeUISyncHost) {\n host = chrome::kChromeUISyncInternalsHost;\n \/\/ Redirect chrome:\/\/extensions.\n } else if (host == chrome::kChromeUIExtensionsHost) {\n host = chrome::kChromeUIUberHost;\n path = chrome::kChromeUIExtensionsHost + url->path();\n \/\/ Redirect chrome:\/\/settings\/extensions.\n \/\/ TODO(csilv): Remove this URL after M22 (legacy URL).\n } else if (host == chrome::kChromeUISettingsHost &&\n url->path() == std::string(\"\/\") + chrome::kExtensionsSubPage) {\n host = chrome::kChromeUIUberHost;\n path = chrome::kChromeUIExtensionsHost;\n \/\/ Redirect chrome:\/\/history.\n } else if (host == chrome::kChromeUIHistoryHost) {\n host = chrome::kChromeUIUberHost;\n path = chrome::kChromeUIHistoryHost + url->path();\n \/\/ Redirect chrome:\/\/settings\n } else if (host == chrome::kChromeUISettingsHost) {\n host = chrome::kChromeUIUberHost;\n path = chrome::kChromeUISettingsHost + url->path();\n }\n GURL::Replacements replacements;\n replacements.SetHostStr(host);\n if (!path.empty())\n replacements.SetPathStr(path);\n *url = url->ReplaceComponents(replacements);\n\n \/\/ Having re-written the URL, make the chrome: handler process it.\n return false;\n}\n\nbool HandleNonNavigationAboutURL(const GURL& url) {\n std::string host(url.host());\n\n \/\/ chrome:\/\/ipc\/ is currently buggy, so we disable it for official builds.\n#if !defined(OFFICIAL_BUILD)\n\n#if (defined(OS_MACOSX) || defined(OS_WIN)) && defined(IPC_MESSAGE_LOG_ENABLED)\n if (LowerCaseEqualsASCII(url.spec(), chrome::kChromeUIIPCURL)) {\n \/\/ Run the dialog. This will re-use the existing one if it's already up.\n chrome::ShowAboutIPCDialog();\n return true;\n }\n#endif\n\n#endif \/\/ OFFICIAL_BUILD\n\n return false;\n}\n\nstd::vector<std::string> ChromePaths() {\n std::vector<std::string> paths(kPaths, kPaths + arraysize(kPaths));\n std::sort(paths.begin(), paths.end());\n return paths;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 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\/common\/notification_registrar.h\"\n\n#include <algorithm>\n\n#include \"base\/logging.h\"\n#include \"chrome\/common\/notification_service.h\"\n\nstruct NotificationRegistrar::Record {\n bool operator==(const Record& other) const;\n\n NotificationObserver* observer;\n NotificationType type;\n NotificationSource source;\n};\n\nbool NotificationRegistrar::Record::operator==(const Record& other) const {\n return observer == other.observer &&\n type == other.type &&\n source == other.source;\n}\n\nNotificationRegistrar::NotificationRegistrar() {\n}\n\nNotificationRegistrar::~NotificationRegistrar() {\n RemoveAll();\n}\n\nvoid NotificationRegistrar::Add(NotificationObserver* observer,\n NotificationType type,\n const NotificationSource& source) {\n Record record = { observer, type, source };\n DCHECK(std::find(registered_.begin(), registered_.end(), record) ==\n registered_.end()) << \"Duplicate registration.\";\n registered_.push_back(record);\n\n NotificationService::current()->AddObserver(observer, type, source);\n}\n\nvoid NotificationRegistrar::Remove(NotificationObserver* observer,\n NotificationType type,\n const NotificationSource& source) {\n Record record = { observer, type, source };\n RecordVector::iterator found = std::find(\n registered_.begin(), registered_.end(), record);\n if (found == registered_.end()) {\n NOTREACHED();\n return;\n }\n registered_.erase(found);\n\n \/\/ This can be NULL if our owner outlives the NotificationService, e.g. if our\n \/\/ owner is a Singleton.\n NotificationService* service = NotificationService::current();\n if (service)\n service->RemoveObserver(observer, type, source);\n}\n\nvoid NotificationRegistrar::RemoveAll() {\n \/\/ Early-exit if no registrations, to avoid calling\n \/\/ NotificationService::current. If we've constructed an object with a\n \/\/ NotificationRegistrar member, but haven't actually used the notification\n \/\/ service, and we reach prgram exit, then calling current() below could try\n \/\/ to initialize the service's lazy TLS pointer during exit, which throws\n \/\/ wrenches at things.\n if (registered_.empty())\n return;\n\n \/\/ This can be NULL if our owner outlives the NotificationService, e.g. if our\n \/\/ owner is a Singleton.\n NotificationService* service = NotificationService::current();\n if (service) {\n for (size_t i = 0; i < registered_.size(); i++) {\n service->RemoveObserver(registered_[i].observer,\n registered_[i].type,\n registered_[i].source);\n }\n }\n registered_.clear();\n}\n\nbool NotificationRegistrar::IsEmpty() const {\n return registered_.empty();\n}\n<commit_msg>Add more logging on a NOTREACHED() in hopes of getting more data about why we're hitting it.<commit_after>\/\/ Copyright (c) 2006-2008 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\/common\/notification_registrar.h\"\n\n#include <algorithm>\n\n#include \"base\/logging.h\"\n#include \"chrome\/common\/notification_service.h\"\n\nstruct NotificationRegistrar::Record {\n bool operator==(const Record& other) const;\n\n NotificationObserver* observer;\n NotificationType type;\n NotificationSource source;\n};\n\nbool NotificationRegistrar::Record::operator==(const Record& other) const {\n return observer == other.observer &&\n type == other.type &&\n source == other.source;\n}\n\nNotificationRegistrar::NotificationRegistrar() {\n}\n\nNotificationRegistrar::~NotificationRegistrar() {\n RemoveAll();\n}\n\nvoid NotificationRegistrar::Add(NotificationObserver* observer,\n NotificationType type,\n const NotificationSource& source) {\n Record record = { observer, type, source };\n DCHECK(std::find(registered_.begin(), registered_.end(), record) ==\n registered_.end()) << \"Duplicate registration.\";\n registered_.push_back(record);\n\n NotificationService::current()->AddObserver(observer, type, source);\n}\n\nvoid NotificationRegistrar::Remove(NotificationObserver* observer,\n NotificationType type,\n const NotificationSource& source) {\n Record record = { observer, type, source };\n RecordVector::iterator found = std::find(\n registered_.begin(), registered_.end(), record);\n if (found == registered_.end()) {\n NOTREACHED() << \"Trying to remove unregistered observer of type \" <<\n type.value << \" from list of size \" << registered_.size() << \".\";\n return;\n }\n registered_.erase(found);\n\n \/\/ This can be NULL if our owner outlives the NotificationService, e.g. if our\n \/\/ owner is a Singleton.\n NotificationService* service = NotificationService::current();\n if (service)\n service->RemoveObserver(observer, type, source);\n}\n\nvoid NotificationRegistrar::RemoveAll() {\n \/\/ Early-exit if no registrations, to avoid calling\n \/\/ NotificationService::current. If we've constructed an object with a\n \/\/ NotificationRegistrar member, but haven't actually used the notification\n \/\/ service, and we reach prgram exit, then calling current() below could try\n \/\/ to initialize the service's lazy TLS pointer during exit, which throws\n \/\/ wrenches at things.\n if (registered_.empty())\n return;\n\n \/\/ This can be NULL if our owner outlives the NotificationService, e.g. if our\n \/\/ owner is a Singleton.\n NotificationService* service = NotificationService::current();\n if (service) {\n for (size_t i = 0; i < registered_.size(); i++) {\n service->RemoveObserver(registered_[i].observer,\n registered_[i].type,\n registered_[i].source);\n }\n }\n registered_.clear();\n}\n\nbool NotificationRegistrar::IsEmpty() const {\n return registered_.empty();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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\/common\/pepper_plugin_registry.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/native_library.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_split.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"remoting\/client\/plugin\/pepper_entrypoints.h\"\n\nnamespace {\n\nconst char* kPDFPluginName = \"Chrome PDF Viewer\";\nconst char* kPDFPluginMimeType = \"application\/pdf\";\nconst char* kPDFPluginExtension = \"pdf\";\nconst char* kPDFPluginDescription = \"Portable Document Format\";\n\nconst char* kNaClPluginName = \"Chrome NaCl\";\nconst char* kNaClPluginMimeType = \"application\/x-nacl\";\nconst char* kNaClPluginExtension = \"nexe\";\nconst char* kNaClPluginDescription = \"Native Client Executable\";\n\n#if defined(ENABLE_REMOTING)\nconst char* kRemotingPluginMimeType = \"pepper-application\/x-chromoting\";\n#endif\n\n\/\/ Appends the known built-in plugins to the given vector. Some built-in\n\/\/ plugins are \"internal\" which means they are compiled into the Chrome binary,\n\/\/ and some are extra shared libraries distributed with the browser (these are\n\/\/ not marked internal, aside from being automatically registered, they're just\n\/\/ regular plugins).\nvoid ComputeBuiltInPlugins(std::vector<PepperPluginInfo>* plugins) {\n \/\/ PDF.\n \/\/\n \/\/ Once we're sandboxed, we can't know if the PDF plugin is available or not;\n \/\/ but (on Linux) this function is always called once before we're sandboxed.\n \/\/ So the first time through test if the file is available and then skip the\n \/\/ check on subsequent calls if yes.\n static bool skip_pdf_file_check = false;\n FilePath path;\n if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path)) {\n if (skip_pdf_file_check || file_util::PathExists(path)) {\n PepperPluginInfo pdf;\n pdf.path = path;\n pdf.name = kPDFPluginName;\n pdf.mime_types.push_back(kPDFPluginMimeType);\n pdf.file_extensions = kPDFPluginExtension;\n pdf.type_descriptions = kPDFPluginDescription;\n plugins->push_back(pdf);\n\n skip_pdf_file_check = true;\n }\n }\n\n \/\/ Native client.\n \/\/\n \/\/ Verify that we enable nacl on the command line. The name of the switch\n \/\/ varies between the browser and renderer process.\n if (PathService::Get(chrome::FILE_NACL_PLUGIN, &path) &&\n file_util::PathExists(path)) {\n PepperPluginInfo nacl;\n nacl.path = path;\n nacl.name = kNaClPluginName;\n nacl.mime_types.push_back(kNaClPluginMimeType);\n\n \/\/ TODO(bbudge) Remove this mime type after NaCl tree has been updated.\n const char* kNaClPluginOldMimeType = \"application\/x-ppapi-nacl-srpc\";\n nacl.mime_types.push_back(kNaClPluginOldMimeType);\n\n nacl.file_extensions = kNaClPluginExtension;\n nacl.type_descriptions = kNaClPluginDescription;\n plugins->push_back(nacl);\n }\n\n \/\/ Remoting.\n#if defined(ENABLE_REMOTING)\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableRemoting)) {\n PepperPluginInfo info;\n info.is_internal = true;\n info.path = FilePath(FILE_PATH_LITERAL(\"internal-chromoting\"));\n info.mime_types.push_back(kRemotingPluginMimeType);\n info.internal_entry_points.get_interface = remoting::PPP_GetInterface;\n info.internal_entry_points.initialize_module =\n remoting::PPP_InitializeModule;\n info.internal_entry_points.shutdown_module = remoting::PPP_ShutdownModule;\n\n plugins->push_back(info);\n }\n#endif\n}\n\n\/\/ Appends any plugins from the command line to the given vector.\nvoid ComputePluginsFromCommandLine(std::vector<PepperPluginInfo>* plugins) {\n const std::string value =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kRegisterPepperPlugins);\n if (value.empty())\n return;\n\n bool out_of_process =\n CommandLine::ForCurrentProcess()->HasSwitch(switches::kPpapiOutOfProcess);\n\n \/\/ FORMAT:\n \/\/ command-line = <plugin-entry> + *( LWS + \",\" + LWS + <plugin-entry> )\n \/\/ plugin-entry = <file-path> + [\"#\" + <name> + [\"#\" + <description>]] +\n \/\/ *1( LWS + \";\" + LWS + <mime-type> )\n\n std::vector<std::string> modules;\n base::SplitString(value, ',', &modules);\n for (size_t i = 0; i < modules.size(); ++i) {\n std::vector<std::string> parts;\n base::SplitString(modules[i], ';', &parts);\n if (parts.size() < 2) {\n DLOG(ERROR) << \"Required mime-type not found\";\n continue;\n }\n\n std::vector<std::string> name_parts;\n base::SplitString(parts[0], '#', &name_parts);\n\n PepperPluginInfo plugin;\n plugin.is_out_of_process = out_of_process;\n#if defined(OS_WIN)\n \/\/ This means we can't provide plugins from non-ASCII paths, but\n \/\/ since this switch is only for development I don't think that's\n \/\/ too awful.\n plugin.path = FilePath(ASCIIToUTF16(name_parts[0]));\n#else\n plugin.path = FilePath(name_parts[0]);\n#endif\n if (name_parts.size() > 1)\n plugin.name = name_parts[1];\n if (name_parts.size() > 2) {\n plugin.description = name_parts[2];\n plugin.type_descriptions = name_parts[2];\n }\n for (size_t j = 1; j < parts.size(); ++j)\n plugin.mime_types.push_back(parts[j]);\n\n plugins->push_back(plugin);\n }\n}\n\n} \/\/ namespace\n\nconst char* PepperPluginRegistry::kPDFPluginName = ::kPDFPluginName;\n\nPepperPluginInfo::PepperPluginInfo()\n : is_internal(false),\n is_out_of_process(false) {\n}\n\nPepperPluginInfo::~PepperPluginInfo() {}\n\n\/\/ static\nPepperPluginRegistry* PepperPluginRegistry::GetInstance() {\n static PepperPluginRegistry* registry = NULL;\n \/\/ This object leaks. It is a temporary hack to work around a crash.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=63234\n if (!registry)\n registry = new PepperPluginRegistry;\n return registry;\n}\n\n\/\/ static\nvoid PepperPluginRegistry::ComputeList(std::vector<PepperPluginInfo>* plugins) {\n ComputeBuiltInPlugins(plugins);\n ComputePluginsFromCommandLine(plugins);\n}\n\n\/\/ static\nvoid PepperPluginRegistry::PreloadModules() {\n std::vector<PepperPluginInfo> plugins;\n ComputeList(&plugins);\n for (size_t i = 0; i < plugins.size(); ++i) {\n if (!plugins[i].is_internal && !plugins[i].is_out_of_process) {\n base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path);\n LOG_IF(WARNING, !library) << \"Unable to load plugin \"\n << plugins[i].path.value();\n }\n }\n}\n\nconst PepperPluginInfo* PepperPluginRegistry::GetInfoForPlugin(\n const FilePath& path) const {\n for (size_t i = 0; i < plugin_list_.size(); ++i) {\n if (path == plugin_list_[i].path)\n return &plugin_list_[i];\n }\n return NULL;\n}\n\nwebkit::ppapi::PluginModule* PepperPluginRegistry::GetLiveModule(\n const FilePath& path) {\n NonOwningModuleMap::iterator it = live_modules_.find(path);\n if (it == live_modules_.end())\n return NULL;\n return it->second;\n}\n\nvoid PepperPluginRegistry::AddLiveModule(const FilePath& path,\n webkit::ppapi::PluginModule* module) {\n DCHECK(live_modules_.find(path) == live_modules_.end());\n live_modules_[path] = module;\n}\n\nvoid PepperPluginRegistry::PluginModuleDestroyed(\n webkit::ppapi::PluginModule* destroyed_module) {\n \/\/ Modules aren't destroyed very often and there are normally at most a\n \/\/ couple of them. So for now we just do a brute-force search.\n for (NonOwningModuleMap::iterator i = live_modules_.begin();\n i != live_modules_.end(); ++i) {\n if (i->second == destroyed_module) {\n live_modules_.erase(i);\n return;\n }\n }\n NOTREACHED(); \/\/ Should have always found the module above.\n}\n\nPepperPluginRegistry::~PepperPluginRegistry() {\n \/\/ Explicitly clear all preloaded modules first. This will cause callbacks\n \/\/ to erase these modules from the live_modules_ list, and we don't want\n \/\/ that to happen implicitly out-of-order.\n preloaded_modules_.clear();\n\n DCHECK(live_modules_.empty());\n}\n\nPepperPluginRegistry::PepperPluginRegistry() {\n ComputeList(&plugin_list_);\n\n \/\/ Note that in each case, AddLiveModule must be called before completing\n \/\/ initialization. If we bail out (in the continue clauses) before saving\n \/\/ the initialized module, it will still try to unregister itself in its\n \/\/ destructor.\n for (size_t i = 0; i < plugin_list_.size(); i++) {\n const PepperPluginInfo& current = plugin_list_[i];\n if (current.is_out_of_process)\n continue; \/\/ Out of process plugins need no special pre-initialization.\n\n scoped_refptr<webkit::ppapi::PluginModule> module =\n new webkit::ppapi::PluginModule(current.name, this);\n AddLiveModule(current.path, module);\n if (current.is_internal) {\n if (!module->InitAsInternalPlugin(current.internal_entry_points)) {\n DLOG(ERROR) << \"Failed to load pepper module: \" << current.path.value();\n continue;\n }\n } else {\n \/\/ Preload all external plugins we're not running out of process.\n module = new webkit::ppapi::PluginModule(current.name, this);\n AddLiveModule(current.path, module);\n if (!module->InitAsLibrary(current.path)) {\n DLOG(ERROR) << \"Failed to load pepper module: \" << current.path.value();\n continue;\n }\n }\n preloaded_modules_[current.path] = module;\n }\n}\n<commit_msg>Remove double-initialization for plugin modules.<commit_after>\/\/ Copyright (c) 2011 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\/common\/pepper_plugin_registry.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/native_library.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_split.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"remoting\/client\/plugin\/pepper_entrypoints.h\"\n\nnamespace {\n\nconst char* kPDFPluginName = \"Chrome PDF Viewer\";\nconst char* kPDFPluginMimeType = \"application\/pdf\";\nconst char* kPDFPluginExtension = \"pdf\";\nconst char* kPDFPluginDescription = \"Portable Document Format\";\n\nconst char* kNaClPluginName = \"Chrome NaCl\";\nconst char* kNaClPluginMimeType = \"application\/x-nacl\";\nconst char* kNaClPluginExtension = \"nexe\";\nconst char* kNaClPluginDescription = \"Native Client Executable\";\n\n#if defined(ENABLE_REMOTING)\nconst char* kRemotingPluginMimeType = \"pepper-application\/x-chromoting\";\n#endif\n\n\/\/ Appends the known built-in plugins to the given vector. Some built-in\n\/\/ plugins are \"internal\" which means they are compiled into the Chrome binary,\n\/\/ and some are extra shared libraries distributed with the browser (these are\n\/\/ not marked internal, aside from being automatically registered, they're just\n\/\/ regular plugins).\nvoid ComputeBuiltInPlugins(std::vector<PepperPluginInfo>* plugins) {\n \/\/ PDF.\n \/\/\n \/\/ Once we're sandboxed, we can't know if the PDF plugin is available or not;\n \/\/ but (on Linux) this function is always called once before we're sandboxed.\n \/\/ So the first time through test if the file is available and then skip the\n \/\/ check on subsequent calls if yes.\n static bool skip_pdf_file_check = false;\n FilePath path;\n if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path)) {\n if (skip_pdf_file_check || file_util::PathExists(path)) {\n PepperPluginInfo pdf;\n pdf.path = path;\n pdf.name = kPDFPluginName;\n pdf.mime_types.push_back(kPDFPluginMimeType);\n pdf.file_extensions = kPDFPluginExtension;\n pdf.type_descriptions = kPDFPluginDescription;\n plugins->push_back(pdf);\n\n skip_pdf_file_check = true;\n }\n }\n\n \/\/ Native client.\n \/\/\n \/\/ Verify that we enable nacl on the command line. The name of the switch\n \/\/ varies between the browser and renderer process.\n if (PathService::Get(chrome::FILE_NACL_PLUGIN, &path) &&\n file_util::PathExists(path)) {\n PepperPluginInfo nacl;\n nacl.path = path;\n nacl.name = kNaClPluginName;\n nacl.mime_types.push_back(kNaClPluginMimeType);\n\n \/\/ TODO(bbudge) Remove this mime type after NaCl tree has been updated.\n const char* kNaClPluginOldMimeType = \"application\/x-ppapi-nacl-srpc\";\n nacl.mime_types.push_back(kNaClPluginOldMimeType);\n\n nacl.file_extensions = kNaClPluginExtension;\n nacl.type_descriptions = kNaClPluginDescription;\n plugins->push_back(nacl);\n }\n\n \/\/ Remoting.\n#if defined(ENABLE_REMOTING)\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableRemoting)) {\n PepperPluginInfo info;\n info.is_internal = true;\n info.path = FilePath(FILE_PATH_LITERAL(\"internal-chromoting\"));\n info.mime_types.push_back(kRemotingPluginMimeType);\n info.internal_entry_points.get_interface = remoting::PPP_GetInterface;\n info.internal_entry_points.initialize_module =\n remoting::PPP_InitializeModule;\n info.internal_entry_points.shutdown_module = remoting::PPP_ShutdownModule;\n\n plugins->push_back(info);\n }\n#endif\n}\n\n\/\/ Appends any plugins from the command line to the given vector.\nvoid ComputePluginsFromCommandLine(std::vector<PepperPluginInfo>* plugins) {\n const std::string value =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kRegisterPepperPlugins);\n if (value.empty())\n return;\n\n bool out_of_process =\n CommandLine::ForCurrentProcess()->HasSwitch(switches::kPpapiOutOfProcess);\n\n \/\/ FORMAT:\n \/\/ command-line = <plugin-entry> + *( LWS + \",\" + LWS + <plugin-entry> )\n \/\/ plugin-entry = <file-path> + [\"#\" + <name> + [\"#\" + <description>]] +\n \/\/ *1( LWS + \";\" + LWS + <mime-type> )\n\n std::vector<std::string> modules;\n base::SplitString(value, ',', &modules);\n for (size_t i = 0; i < modules.size(); ++i) {\n std::vector<std::string> parts;\n base::SplitString(modules[i], ';', &parts);\n if (parts.size() < 2) {\n DLOG(ERROR) << \"Required mime-type not found\";\n continue;\n }\n\n std::vector<std::string> name_parts;\n base::SplitString(parts[0], '#', &name_parts);\n\n PepperPluginInfo plugin;\n plugin.is_out_of_process = out_of_process;\n#if defined(OS_WIN)\n \/\/ This means we can't provide plugins from non-ASCII paths, but\n \/\/ since this switch is only for development I don't think that's\n \/\/ too awful.\n plugin.path = FilePath(ASCIIToUTF16(name_parts[0]));\n#else\n plugin.path = FilePath(name_parts[0]);\n#endif\n if (name_parts.size() > 1)\n plugin.name = name_parts[1];\n if (name_parts.size() > 2) {\n plugin.description = name_parts[2];\n plugin.type_descriptions = name_parts[2];\n }\n for (size_t j = 1; j < parts.size(); ++j)\n plugin.mime_types.push_back(parts[j]);\n\n plugins->push_back(plugin);\n }\n}\n\n} \/\/ namespace\n\nconst char* PepperPluginRegistry::kPDFPluginName = ::kPDFPluginName;\n\nPepperPluginInfo::PepperPluginInfo()\n : is_internal(false),\n is_out_of_process(false) {\n}\n\nPepperPluginInfo::~PepperPluginInfo() {}\n\n\/\/ static\nPepperPluginRegistry* PepperPluginRegistry::GetInstance() {\n static PepperPluginRegistry* registry = NULL;\n \/\/ This object leaks. It is a temporary hack to work around a crash.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=63234\n if (!registry)\n registry = new PepperPluginRegistry;\n return registry;\n}\n\n\/\/ static\nvoid PepperPluginRegistry::ComputeList(std::vector<PepperPluginInfo>* plugins) {\n ComputeBuiltInPlugins(plugins);\n ComputePluginsFromCommandLine(plugins);\n}\n\n\/\/ static\nvoid PepperPluginRegistry::PreloadModules() {\n std::vector<PepperPluginInfo> plugins;\n ComputeList(&plugins);\n for (size_t i = 0; i < plugins.size(); ++i) {\n if (!plugins[i].is_internal && !plugins[i].is_out_of_process) {\n base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path);\n LOG_IF(WARNING, !library) << \"Unable to load plugin \"\n << plugins[i].path.value();\n }\n }\n}\n\nconst PepperPluginInfo* PepperPluginRegistry::GetInfoForPlugin(\n const FilePath& path) const {\n for (size_t i = 0; i < plugin_list_.size(); ++i) {\n if (path == plugin_list_[i].path)\n return &plugin_list_[i];\n }\n return NULL;\n}\n\nwebkit::ppapi::PluginModule* PepperPluginRegistry::GetLiveModule(\n const FilePath& path) {\n NonOwningModuleMap::iterator it = live_modules_.find(path);\n if (it == live_modules_.end())\n return NULL;\n return it->second;\n}\n\nvoid PepperPluginRegistry::AddLiveModule(const FilePath& path,\n webkit::ppapi::PluginModule* module) {\n DCHECK(live_modules_.find(path) == live_modules_.end());\n live_modules_[path] = module;\n}\n\nvoid PepperPluginRegistry::PluginModuleDestroyed(\n webkit::ppapi::PluginModule* destroyed_module) {\n \/\/ Modules aren't destroyed very often and there are normally at most a\n \/\/ couple of them. So for now we just do a brute-force search.\n for (NonOwningModuleMap::iterator i = live_modules_.begin();\n i != live_modules_.end(); ++i) {\n if (i->second == destroyed_module) {\n live_modules_.erase(i);\n return;\n }\n }\n NOTREACHED(); \/\/ Should have always found the module above.\n}\n\nPepperPluginRegistry::~PepperPluginRegistry() {\n \/\/ Explicitly clear all preloaded modules first. This will cause callbacks\n \/\/ to erase these modules from the live_modules_ list, and we don't want\n \/\/ that to happen implicitly out-of-order.\n preloaded_modules_.clear();\n\n DCHECK(live_modules_.empty());\n}\n\nPepperPluginRegistry::PepperPluginRegistry() {\n ComputeList(&plugin_list_);\n\n \/\/ Note that in each case, AddLiveModule must be called before completing\n \/\/ initialization. If we bail out (in the continue clauses) before saving\n \/\/ the initialized module, it will still try to unregister itself in its\n \/\/ destructor.\n for (size_t i = 0; i < plugin_list_.size(); i++) {\n const PepperPluginInfo& current = plugin_list_[i];\n if (current.is_out_of_process)\n continue; \/\/ Out of process plugins need no special pre-initialization.\n\n scoped_refptr<webkit::ppapi::PluginModule> module =\n new webkit::ppapi::PluginModule(current.name, this);\n AddLiveModule(current.path, module);\n if (current.is_internal) {\n if (!module->InitAsInternalPlugin(current.internal_entry_points)) {\n DLOG(ERROR) << \"Failed to load pepper module: \" << current.path.value();\n continue;\n }\n } else {\n \/\/ Preload all external plugins we're not running out of process.\n if (!module->InitAsLibrary(current.path)) {\n DLOG(ERROR) << \"Failed to load pepper module: \" << current.path.value();\n continue;\n }\n }\n preloaded_modules_[current.path] = module;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"temp_scaffolding_stubs.h\"\n\n#include \"build\/build_config.h\"\n\n#include <vector>\n\n#include \"base\/gfx\/rect.h\"\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/automation\/automation_provider.h\"\n#include \"chrome\/browser\/download\/download_request_dialog_delegate.h\"\n#include \"chrome\/browser\/download\/download_request_manager.h\"\n#include \"chrome\/browser\/first_run.h\"\n#include \"chrome\/browser\/hung_renderer_dialog.h\"\n#include \"chrome\/browser\/memory_details.h\"\n#include \"chrome\/browser\/options_window.h\"\n#include \"chrome\/browser\/rlz\/rlz.h\"\n#include \"chrome\/browser\/shell_integration.h\"\n#include \"chrome\/common\/process_watcher.h\"\n\n#if defined(OS_MACOSX)\n#include \"chrome\/browser\/download\/download_item_model.h\"\n#include \"chrome\/browser\/download\/download_shelf.h\"\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n#include \"views\/controls\/menu\/chrome_menu.h\"\n#endif\n\nclass TabContents;\n\n\/\/--------------------------------------------------------------------------\n\nvoid AutomationProvider::GetActiveWindow(int* handle) { NOTIMPLEMENTED(); }\n\nvoid AutomationProvider::ActivateWindow(int handle) { NOTIMPLEMENTED(); }\n\nvoid AutomationProvider::SetWindowVisible(int handle, bool visible,\n bool* result) { NOTIMPLEMENTED(); }\n\nvoid AutomationProvider::GetFocusedViewID(int handle, int* view_id) {\n NOTIMPLEMENTED();\n}\n\n#if defined(OS_MACOSX)\nvoid AutomationProvider::GetAutocompleteEditForBrowser(\n int browser_handle,\n bool* success,\n int* autocomplete_edit_handle) {\n *success = false;\n NOTIMPLEMENTED();\n}\n#endif\n\nvoid AutomationProvider::GetBrowserForWindow(int window_handle,\n bool* success,\n int* browser_handle) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::GetSecurityState(int handle, bool* success,\n SecurityStyle* security_style,\n int* ssl_cert_status,\n int* mixed_content_status) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::GetPageType(int handle, bool* success,\n NavigationEntry::PageType* page_type) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::ActionOnSSLBlockingPage(int handle, bool proceed,\n IPC::Message* reply_message) {\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::PrintNow(int tab_handle,\n IPC::Message* reply_message) {\n NOTIMPLEMENTED();\n}\n\n#if defined(OS_MACOSX)\nvoid AutomationProvider::GetAutocompleteEditText(int autocomplete_edit_handle,\n bool* success,\n std::wstring* text) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::SetAutocompleteEditText(int autocomplete_edit_handle,\n const std::wstring& text,\n bool* success) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::AutocompleteEditGetMatches(\n int autocomplete_edit_handle,\n bool* success,\n std::vector<AutocompleteMatchData>* matches) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::AutocompleteEditIsQueryInProgress(\n int autocomplete_edit_handle,\n bool* success,\n bool* query_in_progress) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::OnMessageFromExternalHost(\n int handle, const std::string& message, const std::string& origin,\n const std::string& target) {\n NOTIMPLEMENTED();\n}\n#endif \/\/ defined(OS_MACOSX)\n\n\/\/--------------------------------------------------------------------------\n\n#if defined(OS_LINUX)\nbool ShellIntegration::SetAsDefaultBrowser() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=11972\n return true;\n}\n\nbool ShellIntegration::IsDefaultBrowser() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=11972\n return true;\n}\n#endif\n\n\/\/--------------------------------------------------------------------------\n\n\n\/\/ static\nbool FirstRun::ProcessMasterPreferences(const FilePath& user_data_dir,\n const FilePath& master_prefs_path,\n int* preference_details,\n std::vector<std::wstring>* new_tabs) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=11971\n \/\/ Pretend we processed them correctly.\n return true;\n}\n\n\/\/ static\nint FirstRun::ImportNow(Profile* profile, const CommandLine& cmdline) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=11971\n return 0;\n}\n\nbool FirstRun::CreateChromeDesktopShortcut() {\n NOTIMPLEMENTED();\n return false;\n}\n\nbool FirstRun::CreateChromeQuickLaunchShortcut() {\n NOTIMPLEMENTED();\n return false;\n}\n\n\/\/ static\nbool Upgrade::IsBrowserAlreadyRunning() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=9295\n return false;\n}\n\n\/\/ static\nbool Upgrade::RelaunchChromeBrowser(const CommandLine& command_line) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=9295\n return true;\n}\n\n\/\/ static\nbool Upgrade::SwapNewChromeExeIfPresent() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=9295\n return true;\n}\n\n\/\/--------------------------------------------------------------------------\n\nvoid InstallJankometer(const CommandLine&) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8077\n}\n\nvoid UninstallJankometer() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8077\n}\n\n\/\/--------------------------------------------------------------------------\n\nvoid RLZTracker::CleanupRlz() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8152\n}\n\nbool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8152\n return false;\n}\n\nbool RLZTracker::RecordProductEvent(Product product, AccessPoint point,\n Event event) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8152\n return false;\n}\n\n\/\/--------------------------------------------------------------------------\n\n#if defined(OS_MACOSX)\n\nclass DownloadShelfMac : public DownloadShelf {\n public:\n explicit DownloadShelfMac(TabContents* tab_contents)\n : DownloadShelf(tab_contents) { }\n virtual void AddDownload(BaseDownloadItemModel* download_model) { }\n virtual bool IsShowing() const { return false; }\n virtual bool IsClosing() const { return false; }\n};\n\n\/\/ static\nDownloadShelf* DownloadShelf::Create(TabContents* tab_contents) {\n return new DownloadShelfMac(tab_contents);\n}\n\n#endif\n\n\/\/--------------------------------------------------------------------------\n\nvoid RunRepostFormWarningDialog(NavigationController*) {\n}\n\nLoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,\n URLRequest* request,\n MessageLoop* ui_loop) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\n\/\/--------------------------------------------------------------------------\n\nMemoryDetails::MemoryDetails() {\n NOTIMPLEMENTED();\n}\n\nvoid MemoryDetails::StartFetch() {\n NOTIMPLEMENTED();\n}\n\n#if defined(OS_MACOSX)\nInfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nInfoBar* AlertInfoBarDelegate::CreateInfoBar() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nInfoBar* LinkInfoBarDelegate::CreateInfoBar() {\n NOTIMPLEMENTED();\n return NULL;\n}\n#endif\n\nDownloadRequestDialogDelegate* DownloadRequestDialogDelegate::Create(\n TabContents* tab,\n DownloadRequestManager::TabDownloadState* host) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\n#if !defined(TOOLKIT_VIEWS)\nnamespace download_util {\n\nvoid DragDownload(const DownloadItem* download, SkBitmap* icon) {\n NOTIMPLEMENTED();\n}\n\n} \/\/ namespace download_util\n#endif\n\n#if defined(OS_MACOSX)\nvoid HungRendererDialog::HideForTabContents(TabContents*) {\n NOTIMPLEMENTED();\n}\n\nvoid HungRendererDialog::ShowForTabContents(TabContents*) {\n NOTIMPLEMENTED();\n}\n#endif\n\n#if !defined(TOOLKIT_VIEWS)\nvoid BrowserList::AllBrowsersClosed() {\n \/\/ TODO(port): Close any dependent windows if necessary when the last browser\n \/\/ window is closed.\n}\n#endif\n\n\/\/--------------------------------------------------------------------------\n\n#if defined(OS_MACOSX)\nvoid ShowOptionsWindow(OptionsPage page,\n OptionsGroup highlight_group,\n Profile* profile) {\n NOTIMPLEMENTED();\n}\n#endif\n\n#if !defined(TOOLKIT_VIEWS)\nbool DockInfo::GetNewWindowBounds(gfx::Rect* new_window_bounds,\n bool* maximize_new_window) const {\n NOTIMPLEMENTED();\n return true;\n}\n#endif\n\n\/\/------------------------------------------------------------------------------\n\n#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\nnamespace views {\n\nMenuItemView::MenuItemView(MenuDelegate* delegate) {\n}\n\nMenuItemView::~MenuItemView() {\n}\n\nMenuItemView* MenuItemView::AppendMenuItemInternal(int item_id,\n const std::wstring& label,\n const SkBitmap& icon,\n Type type) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid MenuItemView::RunMenuAt(gfx::NativeView parent,\n const gfx::Rect& bounds,\n AnchorPosition anchor,\n bool has_mnemonics) {\n NOTIMPLEMENTED();\n}\n\nvoid MenuItemView::RunMenuForDropAt(gfx::NativeView parent,\n const gfx::Rect& bounds,\n AnchorPosition anchor) {\n NOTIMPLEMENTED();\n}\n\n\/\/ Hides and cancels the menu. This does nothing if the menu is not open.\nvoid MenuItemView::Cancel() {\n NOTIMPLEMENTED();\n}\n\nSubmenuView* MenuItemView::CreateSubmenu() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid MenuItemView::SetSelected(bool selected) {\n NOTIMPLEMENTED();\n}\n\nvoid MenuItemView::SetIcon(const SkBitmap& icon, int item_id) {\n NOTIMPLEMENTED();\n}\n\nvoid MenuItemView::SetIcon(const SkBitmap& icon) {\n NOTIMPLEMENTED();\n}\n\nvoid MenuItemView::Paint(gfx::Canvas* canvas) {\n NOTIMPLEMENTED();\n}\n\ngfx::Size MenuItemView::GetPreferredSize() {\n NOTIMPLEMENTED();\n return gfx::Size();\n}\n\nMenuController* MenuItemView::GetMenuController() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nMenuDelegate* MenuItemView::GetDelegate() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nMenuItemView* MenuItemView::GetRootMenuItem() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nwchar_t MenuItemView::GetMnemonic() {\n return 'a';\n}\n\n} \/\/ namespace views\n\n#endif\n<commit_msg>Hopefully fix the Linux build again. Review URL: http:\/\/codereview.chromium.org\/115850<commit_after>\/\/ 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 \"temp_scaffolding_stubs.h\"\n\n#include \"build\/build_config.h\"\n\n#include <vector>\n\n#include \"base\/gfx\/rect.h\"\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/automation\/automation_provider.h\"\n#include \"chrome\/browser\/download\/download_request_dialog_delegate.h\"\n#include \"chrome\/browser\/download\/download_request_manager.h\"\n#include \"chrome\/browser\/first_run.h\"\n#include \"chrome\/browser\/hung_renderer_dialog.h\"\n#include \"chrome\/browser\/memory_details.h\"\n#include \"chrome\/browser\/options_window.h\"\n#include \"chrome\/browser\/rlz\/rlz.h\"\n#include \"chrome\/browser\/shell_integration.h\"\n#include \"chrome\/common\/process_watcher.h\"\n\n#if defined(OS_MACOSX)\n#include \"chrome\/browser\/download\/download_item_model.h\"\n#include \"chrome\/browser\/download\/download_shelf.h\"\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n#include \"views\/controls\/menu\/chrome_menu.h\"\n#endif\n\nclass TabContents;\n\n\/\/--------------------------------------------------------------------------\n\nvoid AutomationProvider::GetActiveWindow(int* handle) { NOTIMPLEMENTED(); }\n\nvoid AutomationProvider::ActivateWindow(int handle) { NOTIMPLEMENTED(); }\n\nvoid AutomationProvider::SetWindowVisible(int handle, bool visible,\n bool* result) { NOTIMPLEMENTED(); }\n\nvoid AutomationProvider::GetFocusedViewID(int handle, int* view_id) {\n NOTIMPLEMENTED();\n}\n\n#if defined(OS_MACOSX)\nvoid AutomationProvider::GetAutocompleteEditForBrowser(\n int browser_handle,\n bool* success,\n int* autocomplete_edit_handle) {\n *success = false;\n NOTIMPLEMENTED();\n}\n#endif\n\nvoid AutomationProvider::GetBrowserForWindow(int window_handle,\n bool* success,\n int* browser_handle) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::GetSecurityState(int handle, bool* success,\n SecurityStyle* security_style,\n int* ssl_cert_status,\n int* mixed_content_status) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::GetPageType(int handle, bool* success,\n NavigationEntry::PageType* page_type) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::ActionOnSSLBlockingPage(int handle, bool proceed,\n IPC::Message* reply_message) {\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::PrintNow(int tab_handle,\n IPC::Message* reply_message) {\n NOTIMPLEMENTED();\n}\n\n#if defined(OS_MACOSX)\nvoid AutomationProvider::GetAutocompleteEditText(int autocomplete_edit_handle,\n bool* success,\n std::wstring* text) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::SetAutocompleteEditText(int autocomplete_edit_handle,\n const std::wstring& text,\n bool* success) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::AutocompleteEditGetMatches(\n int autocomplete_edit_handle,\n bool* success,\n std::vector<AutocompleteMatchData>* matches) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::AutocompleteEditIsQueryInProgress(\n int autocomplete_edit_handle,\n bool* success,\n bool* query_in_progress) {\n *success = false;\n NOTIMPLEMENTED();\n}\n\nvoid AutomationProvider::OnMessageFromExternalHost(\n int handle, const std::string& message, const std::string& origin,\n const std::string& target) {\n NOTIMPLEMENTED();\n}\n#endif \/\/ defined(OS_MACOSX)\n\n\/\/--------------------------------------------------------------------------\n\n#if defined(OS_LINUX)\nbool ShellIntegration::SetAsDefaultBrowser() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=11972\n return true;\n}\n\nbool ShellIntegration::IsDefaultBrowser() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=11972\n return true;\n}\n#endif\n\n\/\/--------------------------------------------------------------------------\n\n\n\/\/ static\nbool FirstRun::ProcessMasterPreferences(const FilePath& user_data_dir,\n const FilePath& master_prefs_path,\n int* preference_details,\n std::vector<std::wstring>* new_tabs) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=11971\n \/\/ Pretend we processed them correctly.\n return true;\n}\n\n\/\/ static\nint FirstRun::ImportNow(Profile* profile, const CommandLine& cmdline) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=11971\n return 0;\n}\n\nbool FirstRun::CreateChromeDesktopShortcut() {\n NOTIMPLEMENTED();\n return false;\n}\n\nbool FirstRun::CreateChromeQuickLaunchShortcut() {\n NOTIMPLEMENTED();\n return false;\n}\n\n\/\/ static\nbool Upgrade::IsBrowserAlreadyRunning() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=9295\n return false;\n}\n\n\/\/ static\nbool Upgrade::RelaunchChromeBrowser(const CommandLine& command_line) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=9295\n return true;\n}\n\n\/\/ static\nbool Upgrade::SwapNewChromeExeIfPresent() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=9295\n return true;\n}\n\n\/\/--------------------------------------------------------------------------\n\nvoid InstallJankometer(const CommandLine&) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8077\n}\n\nvoid UninstallJankometer() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8077\n}\n\n\/\/--------------------------------------------------------------------------\n\nvoid RLZTracker::CleanupRlz() {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8152\n}\n\nbool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8152\n return false;\n}\n\nbool RLZTracker::RecordProductEvent(Product product, AccessPoint point,\n Event event) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=8152\n return false;\n}\n\n\/\/--------------------------------------------------------------------------\n\n#if defined(OS_MACOSX)\n\nclass DownloadShelfMac : public DownloadShelf {\n public:\n explicit DownloadShelfMac(TabContents* tab_contents)\n : DownloadShelf(tab_contents) { }\n virtual void AddDownload(BaseDownloadItemModel* download_model) { }\n virtual bool IsShowing() const { return false; }\n virtual bool IsClosing() const { return false; }\n};\n\n\/\/ static\nDownloadShelf* DownloadShelf::Create(TabContents* tab_contents) {\n return new DownloadShelfMac(tab_contents);\n}\n\n#endif\n\n\/\/--------------------------------------------------------------------------\n\nvoid RunRepostFormWarningDialog(NavigationController*) {\n}\n\nLoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,\n URLRequest* request,\n MessageLoop* ui_loop) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\n\/\/--------------------------------------------------------------------------\n\nMemoryDetails::MemoryDetails() {\n NOTIMPLEMENTED();\n}\n\nvoid MemoryDetails::StartFetch() {\n NOTIMPLEMENTED();\n}\n\n#if defined(OS_MACOSX)\nInfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nInfoBar* AlertInfoBarDelegate::CreateInfoBar() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nInfoBar* LinkInfoBarDelegate::CreateInfoBar() {\n NOTIMPLEMENTED();\n return NULL;\n}\n#endif\n\nDownloadRequestDialogDelegate* DownloadRequestDialogDelegate::Create(\n TabContents* tab,\n DownloadRequestManager::TabDownloadState* host) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\n#if !defined(TOOLKIT_VIEWS)\nnamespace download_util {\n\nvoid DragDownload(const DownloadItem* download, SkBitmap* icon) {\n NOTIMPLEMENTED();\n}\n\n} \/\/ namespace download_util\n#endif\n\n#if defined(OS_MACOSX)\nvoid HungRendererDialog::HideForTabContents(TabContents*) {\n NOTIMPLEMENTED();\n}\n\nvoid HungRendererDialog::ShowForTabContents(TabContents*) {\n NOTIMPLEMENTED();\n}\n#endif\n\n#if !defined(TOOLKIT_VIEWS)\nvoid BrowserList::AllBrowsersClosed() {\n \/\/ TODO(port): Close any dependent windows if necessary when the last browser\n \/\/ window is closed.\n}\n#endif\n\n\/\/--------------------------------------------------------------------------\n\n#if defined(OS_MACOSX)\nvoid ShowOptionsWindow(OptionsPage page,\n OptionsGroup highlight_group,\n Profile* profile) {\n NOTIMPLEMENTED();\n}\n#endif\n\n#if defined(OS_MACOSX)\nbool DockInfo::GetNewWindowBounds(gfx::Rect* new_window_bounds,\n bool* maximize_new_window) const {\n NOTIMPLEMENTED();\n return true;\n}\n#endif\n\n\/\/------------------------------------------------------------------------------\n\n#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\nnamespace views {\n\nMenuItemView::MenuItemView(MenuDelegate* delegate) {\n}\n\nMenuItemView::~MenuItemView() {\n}\n\nMenuItemView* MenuItemView::AppendMenuItemInternal(int item_id,\n const std::wstring& label,\n const SkBitmap& icon,\n Type type) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid MenuItemView::RunMenuAt(gfx::NativeView parent,\n const gfx::Rect& bounds,\n AnchorPosition anchor,\n bool has_mnemonics) {\n NOTIMPLEMENTED();\n}\n\nvoid MenuItemView::RunMenuForDropAt(gfx::NativeView parent,\n const gfx::Rect& bounds,\n AnchorPosition anchor) {\n NOTIMPLEMENTED();\n}\n\n\/\/ Hides and cancels the menu. This does nothing if the menu is not open.\nvoid MenuItemView::Cancel() {\n NOTIMPLEMENTED();\n}\n\nSubmenuView* MenuItemView::CreateSubmenu() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid MenuItemView::SetSelected(bool selected) {\n NOTIMPLEMENTED();\n}\n\nvoid MenuItemView::SetIcon(const SkBitmap& icon, int item_id) {\n NOTIMPLEMENTED();\n}\n\nvoid MenuItemView::SetIcon(const SkBitmap& icon) {\n NOTIMPLEMENTED();\n}\n\nvoid MenuItemView::Paint(gfx::Canvas* canvas) {\n NOTIMPLEMENTED();\n}\n\ngfx::Size MenuItemView::GetPreferredSize() {\n NOTIMPLEMENTED();\n return gfx::Size();\n}\n\nMenuController* MenuItemView::GetMenuController() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nMenuDelegate* MenuItemView::GetDelegate() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nMenuItemView* MenuItemView::GetRootMenuItem() {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nwchar_t MenuItemView::GetMnemonic() {\n return 'a';\n}\n\n} \/\/ namespace views\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file dcs\/testbed\/base_application.hpp\n *\n * \\brief Base class for applications.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr\/>\n *\n * Copyright (C) 2012 Marco Guazzone (marco.guazzone@gmail.com)\n * [Distributed Computing System (DCS) Group,\n * Computer Science Institute,\n * Department of Science and Technological Innovation,\n * University of Piemonte Orientale,\n * Alessandria (Italy)]\n *\n * This file is part of dcsxx-testbed (below referred to as \"this program\").\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\n * by the Free Software Foundation, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef DCS_TESTBED_BASE_APPLICATION_HPP\n#define DCS_TESTBED_BASE_APPLICATION_HPP\n\n\n#include <boost\/function.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <cstddef>\n#include <dcs\/testbed\/application_performance_category.hpp>\n#include <dcs\/testbed\/base_sensor.hpp>\n#include <dcs\/testbed\/base_virtual_machine.hpp>\n\n\nnamespace dcs { namespace testbed {\n\ntemplate <typename TraitsT>\nclass base_application\n{\n\tpublic: typedef TraitsT traits_type;\n\tpublic: typedef base_virtual_machine<traits_type> vm_type;\n\tpublic: typedef ::boost::shared_ptr<vm_type> vm_pointer;\n\tpublic: typedef base_sensor<traits_type> sensor_type;\n\tpublic: typedef ::boost::shared_ptr<sensor_type> sensor_pointer;\n\tpublic: typedef typename traits_type::real_type real_type;\n\tpublic: typedef ::boost::function<bool (real_type x)> slo_checker_type;\n\n\n\tpublic: virtual ~base_application()\n\t{\n\t}\n\n\tpublic: ::std::size_t num_vms() const\n\t{\n\t\treturn do_num_vms();\n\t}\n\n\tpublic: ::std::vector<vm_pointer> vms() const\n\t{\n\t\treturn do_vms();\n\t}\n\n\tpublic: void register_sensor(application_performance_category cat, sensor_pointer const& p_sens)\n\t{\n\t\tdo_register_sensor(cat, p_sens);\n\t}\n\n\tpublic: void deregister_sensor(application_performance_category cat)\n\t{\n\t\tdo_deregister_sensor(cat);\n\t}\n\n\tpublic: sensor_pointer sensor(application_performance_category cat)\n\t{\n\t\treturn do_sensor(cat);\n\t}\n\n\tpublic: sensor_pointer sensor(application_performance_category cat) const\n\t{\n\t\treturn do_sensor(cat);\n\t}\n\n\tpublic: template <typename FuncT>\n\t\t\tvoid slo(application_performance_category cat, FuncT checker)\n\t{\n\t\tdo_slo(cat, slo_checker_type(checker));\n\t}\n\n\tpublic: bool slo(application_performance_category cat, real_type val)\n\t{\n\t\treturn do_slo(cat, val);\n\t}\n\n\tprivate: virtual ::std::size_t do_num_vms() const = 0;\n\n\tprivate: virtual ::std::vector<vm_pointer> do_vms() const = 0;\n\n\tprivate: virtual void do_register_sensor(application_performance_category cat, sensor_pointer const& p_sens) = 0;\n\n\tprivate: virtual void do_deregister_sensor(application_performance_category cat) = 0;\n\n\tprivate: virtual sensor_pointer do_sensor(application_performance_category cat) = 0;\n\n\tprivate: virtual sensor_pointer do_sensor(application_performance_category cat) const = 0;\n\n\tprivate: virtual void do_slo(application_performance_category cat, slo_checker_type const& checker) = 0;\n\n\tprivate: virtual bool do_slo(application_performance_category cat, real_type val) const = 0;\n}; \/\/ base_application\n\n}} \/\/ Namespace dcs::testbed\n\n#endif \/\/ DCS_TESTBED_BASE_APPLICATION_HPP\n<commit_msg>(new:major) Added id management and name getter\/setter<commit_after>\/**\n * \\file dcs\/testbed\/base_application.hpp\n *\n * \\brief Base class for applications.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr\/>\n *\n * Copyright (C) 2012 Marco Guazzone (marco.guazzone@gmail.com)\n * [Distributed Computing System (DCS) Group,\n * Computer Science Institute,\n * Department of Science and Technological Innovation,\n * University of Piemonte Orientale,\n * Alessandria (Italy)]\n *\n * This file is part of dcsxx-testbed (below referred to as \"this program\").\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\n * by the Free Software Foundation, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef DCS_TESTBED_BASE_APPLICATION_HPP\n#define DCS_TESTBED_BASE_APPLICATION_HPP\n\n\n#include <boost\/function.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <cstddef>\n#include <dcs\/testbed\/application_performance_category.hpp>\n#include <dcs\/testbed\/base_sensor.hpp>\n#include <dcs\/testbed\/base_virtual_machine.hpp>\n#include <string>\n\n\nnamespace dcs { namespace testbed {\n\ntemplate <typename TraitsT>\nclass base_application\n{\n\tpublic: typedef TraitsT traits_type;\n\tpublic: typedef base_virtual_machine<traits_type> vm_type;\n\tpublic: typedef ::boost::shared_ptr<vm_type> vm_pointer;\n\/\/\tpublic: typedef typename vm_type::identifier_type vm_identifier_type;\n\tpublic: typedef base_sensor<traits_type> sensor_type;\n\tpublic: typedef ::boost::shared_ptr<sensor_type> sensor_pointer;\n\tpublic: typedef typename traits_type::real_type real_type;\n\tpublic: typedef ::boost::function<bool (real_type x)> slo_checker_type;\n\tpublic: typedef unsigned long identifier_type;\n\n\n\tprivate: static identifier_type next_id_;\n\n\n\tpublic: static identifier_type make_id()\n\t{\n\t\treturn next_id_++;\n\t}\n\n\n\tpublic: base_application()\n\t: id_(make_id())\n\t{\n\t}\n\n\tpublic: virtual ~base_application()\n\t{\n\t}\n\n\tpublic: identifier_type id() const\n\t{\n\t\treturn id_;\n\t}\n\n\tpublic: void name(::std::string const& val)\n\t{\n\t\tname_ = val;\n\t}\n\n\tpublic: ::std::string name() const\n\t{\n\t\treturn name_;\n\t}\n\n\tpublic: ::std::size_t num_vms() const\n\t{\n\t\treturn do_num_vms();\n\t}\n\n\tpublic: ::std::vector<vm_pointer> vms() const\n\t{\n\t\treturn do_vms();\n\t}\n\n\/\/\tpublic: vm_pointer vm(vm_identifier_type id) const\n\/\/\t{\n\/\/\t\treturn do_vm(id);\n\/\/\t}\n\n\tpublic: void register_sensor(application_performance_category cat, sensor_pointer const& p_sens)\n\t{\n\t\tdo_register_sensor(cat, p_sens);\n\t}\n\n\tpublic: void deregister_sensor(application_performance_category cat)\n\t{\n\t\tdo_deregister_sensor(cat);\n\t}\n\n\tpublic: sensor_pointer sensor(application_performance_category cat)\n\t{\n\t\treturn do_sensor(cat);\n\t}\n\n\tpublic: sensor_pointer sensor(application_performance_category cat) const\n\t{\n\t\treturn do_sensor(cat);\n\t}\n\n\tpublic: template <typename FuncT>\n\t\t\tvoid slo(application_performance_category cat, FuncT checker)\n\t{\n\t\tdo_slo(cat, slo_checker_type(checker));\n\t}\n\n\tpublic: bool slo(application_performance_category cat, real_type val)\n\t{\n\t\treturn do_slo(cat, val);\n\t}\n\n\tprivate: virtual ::std::size_t do_num_vms() const = 0;\n\n\tprivate: virtual ::std::vector<vm_pointer> do_vms() const = 0;\n\n\tprivate: virtual void do_register_sensor(application_performance_category cat, sensor_pointer const& p_sens) = 0;\n\n\tprivate: virtual void do_deregister_sensor(application_performance_category cat) = 0;\n\n\tprivate: virtual sensor_pointer do_sensor(application_performance_category cat) = 0;\n\n\tprivate: virtual sensor_pointer do_sensor(application_performance_category cat) const = 0;\n\n\tprivate: virtual void do_slo(application_performance_category cat, slo_checker_type const& checker) = 0;\n\n\tprivate: virtual bool do_slo(application_performance_category cat, real_type val) const = 0;\n\n\n\tprivate: identifier_type id_; \/\/\/< The unique identifier\n\tprivate: ::std::string name_; \/\/\/< The mnemonic name of this application\n}; \/\/ base_application\n\ntemplate <typename T>\ntypename base_application<T>::identifier_type base_application<T>::next_id_ = 0;\n\n}} \/\/ Namespace dcs::testbed\n\n#endif \/\/ DCS_TESTBED_BASE_APPLICATION_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"refinedepth.h\"\n\nusing caffe::Blob;\nusing caffe::Net;\n\nconst int feature_num = 5; \/\/ y cr cb r c\nconst int w_ = 640;\nconst int h_ = 480;\n\nRefineDepth::RefineDepth()\n{\n int gpu_id = 0;\n#ifdef CPU_ONLY\n printf(\"Setting up Caffe in CPU mode\\n\");\n caffe::Caffe::set_mode(caffe::Caffe::CPU);\n#else\n caffe::Caffe::SetDevice(gpu_id);\n caffe::Caffe::set_mode(caffe::Caffe::GPU);\n#endif\n char* drv_path_env = getenv(\"DRV\");\n string drv_path_ = string(drv_path_env) + \"\/supplements\/refine_depth\/\";\n string proto_file;\n proto_file = drv_path_ + \"refine_depth.prototxt\";\n\n if (!boost::filesystem::is_regular_file(proto_file))\n cerr << \"Proto file \" << proto_file << \" not exist.\" << endl;\n net_.reset(new Net<float>(proto_file, caffe::TEST));\n setParams();\n}\n\nvoid RefineDepth::refineDepth(Mat rgb_in, Mat depth_in, Mat &depth_out)\n{\n vector<float> depth_values_in;\n\n vector<vector<float> > features_in;\n vector<vector<float> > features_out;\n\n depth_values_in.resize(w_ * h_);\n features_in.resize(feature_num);\n features_out.resize(feature_num);\n\n for (size_t e = 0; e < feature_num; ++e) {\n features_in[e].resize(w_ * h_);\n features_out[e].resize(w_ * h_);\n }\n\n CHECK_EQ(rgb_in.size(), Size(w_, h_));\n CHECK_EQ(depth_in.size(), Size(w_, h_));\n\n cv::Mat yCrCb;\n cv::cvtColor(rgb_in, yCrCb, CV_BGR2YCrCb);\n\n for (size_t r = 0; r < h_; ++r) {\n for (size_t c = 0; c < w_; ++c) {\n float depth_val = depth_in.at<float>(r, c);\n if (depth_val == 0) {\n \/\/ In place where depth is not known, put its features to features_out\n features_out[0][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[0];\n features_out[1][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[1];\n features_out[2][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[2];\n features_out[3][r * w_ + c] = r;\n features_out[4][r * w_ + c] = c;\n }\n else {\n features_in[0][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[0];\n features_in[1][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[1];\n features_in[2][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[2];\n features_in[3][r * w_ + c] = r;\n features_in[4][r * w_ + c] = c;\n\n depth_values_in[r * w_ + c] = depth_val;\n }\n }\n }\n\n depth_out = Mat(h_, w_, CV_32FC1, Scalar(0.0));\n\n Mat depth_filled(h_, w_, CV_32FC1, Scalar(0.0));\n forward(depth_values_in, features_in, features_out, depth_filled);\n\n for (size_t r = 0; r < h_; ++r) {\n for (size_t c = 0; c < w_; ++c) {\n float depth_val = depth_in.at<float>(r, c);\n if (depth_val == 0) {\n depth_out.at<float>(r, c) = depth_filled.at<float>(r, c);\n }\n else {\n depth_out.at<float>(r, c) = depth_val;\n }\n }\n }\n namedWindow(\"Refined\", WINDOW_NORMAL);\n imshow(\"Refined\", depth_out);\n waitKey();\n}\n\nvoid RefineDepth::forward(vector<float> depth_in, vector<vector<float> > features_in,\n vector<vector<float> > features_out, Mat &depth_out)\n{\n wrapInputLayer(depth_in, features_in, features_out);\n net_->Forward();\n getOutput(depth_out);\n}\n\nvoid RefineDepth::setParams()\n{\n const vector<boost::shared_ptr<Blob<float> > >& net_params = net_->params();\n boost::shared_ptr<Blob<float> > out_seg1 = net_params[0];\n float* out_seg1_data = out_seg1->mutable_cpu_data();\n \/\/ dim of out_seg1 param: 1 X 1 X 1 X 1\n out_seg1_data[0] = 1.0;\n\n boost::shared_ptr<Blob<float> > out_seg2 = net_params[2];\n float* out_seg2_data = out_seg2->mutable_cpu_data();\n \/\/ dim of out_seg1 param: 1 X 1 X 1 X 1\n out_seg2_data[0] = 1.0;\n\n boost::shared_ptr<Blob<float> > sp_out_seg1 = net_params[4];\n float* sp_out_seg1_data = sp_out_seg1->mutable_cpu_data();\n \/\/ dim of sp_out_seg1 param: 1 X 2 X 1 X 1\n sp_out_seg1_data[0] = 1.0; \/\/ This value only need be larger\n sp_out_seg1_data[1] = 0.0; \/\/ than this value\n}\n\nvoid RefineDepth::wrapInputLayer(vector<float> depth_in, vector<vector<float> > features_in,\n vector<vector<float> > features_out)\n{\n \/\/ Input depth shape: num_pixel\n \/\/ Net shape: 1 1 1 num_pixel\n Blob<float>* input_unary = net_->input_blobs()[0];\n float* unary_data = input_unary->mutable_cpu_data();\n\n for (size_t e = 0; e < depth_in.size(); ++e) {\n *unary_data = depth_in[e];\n ++unary_data;\n }\n\n \/\/ Input in_features shape : feature_num_ num_pixel\n \/\/ Net shape : 1 feature_num_ 1 num_pixel\n Blob<float>* input_in_features = net_->input_blobs()[1];\n float* in_features_data = input_in_features->mutable_cpu_data();\n\n vector<float> in_features_c; \/\/ collection of data in in_features\n int sz = w_ * h_;\n for (size_t c = 0; c < feature_num; ++c) {\n for (size_t e = 0; e < sz; ++e) {\n in_features_c.push_back(features_in[c][e]);\n }\n }\n for (size_t e = 0; e < in_features_c.size(); ++e) {\n *in_features_data = in_features_c[e];\n ++in_features_data;\n }\n\n \/\/ Input out_features shape: feature_num_ num_pixel\n \/\/ Net shape : 1 feature_num_ 1 num_pixel\n Blob<float>* input_out_features = net_->input_blobs()[2];\n float* out_features_data = input_out_features->mutable_cpu_data();\n\n vector<float> out_features_c; \/\/ collection of data in out_features\n for (size_t c = 0; c < feature_num; ++c) {\n for (size_t e = 0; e < sz; ++e) {\n out_features_c.push_back(features_out[c][e]);\n }\n }\n for (size_t e = 0; e < out_features_c.size(); ++e) {\n *out_features_data = out_features_c[e];\n ++out_features_data;\n }\n\n \/\/ Scales1 1 feature_num_ 1 1\n Blob<float>* input_scales1 = net_->input_blobs()[3];\n float* scales1_data = input_scales1->mutable_cpu_data();\n \/\/ Scales2 1 feature_num_ 1 1\n Blob<float>* input_scales2 = net_->input_blobs()[4];\n float* scales2_data = input_scales2->mutable_cpu_data();\n\n float s1[] = {0.06, 0.2, 0.2, 0.02, 0.02};\n float s2[] = {0.09, 0.3, 0.3, 0.03, 0.03};\n vector<float> scales1(s1, s1 + sizeof(s1) \/ sizeof(float));\n for (size_t e = 0; e < feature_num; ++e) {\n *scales1_data = scales1[e];\n ++scales1_data;\n }\n vector<float> scales2(s2, s2 + sizeof(s2) \/ sizeof(float));\n for (size_t e = 0; e < feature_num; ++e) {\n *scales2_data = scales2[e];\n ++scales2_data;\n }\n}\n\nvoid RefineDepth::getOutput(Mat &depth_out)\n{\n int num_elements = 1;\n const string out_depth_name = \"out_depth1\";\n const boost::shared_ptr<Blob<float> > out_depth_blob =\n net_->blob_by_name(out_depth_name.c_str());\n\n num_elements = 1;\n for (int i = 0; i < out_depth_blob->num_axes(); ++i) {\n const int elements_in_dim = out_depth_blob->shape(i);\n num_elements *= elements_in_dim;\n }\n\n vector<float> temp_depth;\n for (int n = 0; n < num_elements; ++n) {\n const float* out_depth_blob_data = out_depth_blob->cpu_data() + n;\n temp_depth.push_back(*out_depth_blob_data);\n }\n\n for (int i = 0; i < temp_depth.size(); ++i) {\n int r = i \/ w_;\n int c = i % w_;\n depth_out.at<float>(r, c) = float(temp_depth[i]);\n }\n}\n\n<commit_msg>refine the algorithm<commit_after>#include \"refinedepth.h\"\n\nusing caffe::Blob;\nusing caffe::Net;\n\nconst int feature_num = 5; \/\/ y cr cb r c\nconst int w_ = 640;\nconst int h_ = 480;\n\nRefineDepth::RefineDepth()\n{\n int gpu_id = 0;\n#ifdef CPU_ONLY\n printf(\"Setting up Caffe in CPU mode\\n\");\n caffe::Caffe::set_mode(caffe::Caffe::CPU);\n#else\n caffe::Caffe::SetDevice(gpu_id);\n caffe::Caffe::set_mode(caffe::Caffe::GPU);\n#endif\n char* drv_path_env = getenv(\"DRV\");\n string drv_path_ = string(drv_path_env) + \"\/supplements\/refine_depth\/\";\n string proto_file;\n proto_file = drv_path_ + \"refine_depth.prototxt\";\n\n if (!boost::filesystem::is_regular_file(proto_file))\n cerr << \"Proto file \" << proto_file << \" not exist.\" << endl;\n net_.reset(new Net<float>(proto_file, caffe::TEST));\n setParams();\n}\n\nvoid RefineDepth::refineDepth(Mat rgb_in, Mat depth_in, Mat &depth_out)\n{\n vector<float> depth_values_in;\n\n vector<vector<float> > features_in;\n vector<vector<float> > features_out;\n\n depth_values_in.resize(w_ * h_);\n features_in.resize(feature_num);\n features_out.resize(feature_num);\n\n for (size_t e = 0; e < feature_num; ++e) {\n features_in[e].resize(w_ * h_);\n features_out[e].resize(w_ * h_);\n }\n\n CHECK_EQ(rgb_in.size(), Size(w_, h_));\n CHECK_EQ(depth_in.size(), Size(w_, h_));\n\n cv::Mat yCrCb;\n cv::cvtColor(rgb_in, yCrCb, CV_BGR2YCrCb);\n\n for (size_t r = 0; r < h_; ++r) {\n for (size_t c = 0; c < w_; ++c) {\n float depth_val = depth_in.at<float>(r, c);\n if (depth_val == 0) {\n \/\/ In place where depth is not known, put its features to features_out\n features_out[0][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[0];\n features_out[1][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[1];\n features_out[2][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[2];\n features_out[3][r * w_ + c] = r;\n features_out[4][r * w_ + c] = c;\n }\n else {\n features_in[0][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[0];\n features_in[1][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[1];\n features_in[2][r * w_ + c] = yCrCb.at<Vec3b>(r, c)[2];\n features_in[3][r * w_ + c] = r;\n features_in[4][r * w_ + c] = c;\n\n depth_values_in[r * w_ + c] = depth_val;\n }\n }\n }\n\n depth_out = Mat(h_, w_, CV_32FC1, Scalar(0.0));\n\n Mat depth_filled(h_, w_, CV_32FC1, Scalar(0.0));\n forward(depth_values_in, features_in, features_out, depth_filled);\n\n for (size_t r = 0; r < h_; ++r) {\n for (size_t c = 0; c < w_; ++c) {\n float depth_val = depth_in.at<float>(r, c);\n if (depth_val == 0) {\n depth_out.at<float>(r, c) = depth_filled.at<float>(r, c);\n }\n else {\n depth_out.at<float>(r, c) = depth_val;\n }\n }\n }\n namedWindow(\"Refined\", WINDOW_NORMAL);\n imshow(\"Refined\", depth_out);\n waitKey(10);\n}\n\nvoid RefineDepth::forward(vector<float> depth_in, vector<vector<float> > features_in,\n vector<vector<float> > features_out, Mat &depth_out)\n{\n wrapInputLayer(depth_in, features_in, features_out);\n net_->Forward();\n getOutput(depth_out);\n}\n\nvoid RefineDepth::setParams()\n{\n const vector<boost::shared_ptr<Blob<float> > >& net_params = net_->params();\n boost::shared_ptr<Blob<float> > out_seg1 = net_params[0];\n float* out_seg1_data = out_seg1->mutable_cpu_data();\n \/\/ dim of out_seg1 param: 1 X 1 X 1 X 1\n out_seg1_data[0] = 1.0;\n\n boost::shared_ptr<Blob<float> > out_seg2 = net_params[2];\n float* out_seg2_data = out_seg2->mutable_cpu_data();\n \/\/ dim of out_seg1 param: 1 X 1 X 1 X 1\n out_seg2_data[0] = 1.0;\n\n boost::shared_ptr<Blob<float> > sp_out_seg1 = net_params[4];\n float* sp_out_seg1_data = sp_out_seg1->mutable_cpu_data();\n \/\/ dim of sp_out_seg1 param: 1 X 2 X 1 X 1\n sp_out_seg1_data[0] = 1.0; \/\/ This value only need be larger\n sp_out_seg1_data[1] = 0.0; \/\/ than this value\n}\n\nvoid RefineDepth::wrapInputLayer(vector<float> depth_in, vector<vector<float> > features_in,\n vector<vector<float> > features_out)\n{\n \/\/ Input depth shape: num_pixel\n \/\/ Net shape: 1 1 1 num_pixel\n Blob<float>* input_unary = net_->input_blobs()[0];\n float* unary_data = input_unary->mutable_cpu_data();\n\n for (size_t e = 0; e < depth_in.size(); ++e) {\n *unary_data = depth_in[e];\n ++unary_data;\n }\n\n \/\/ Input in_features shape : feature_num_ num_pixel\n \/\/ Net shape : 1 feature_num_ 1 num_pixel\n Blob<float>* input_in_features = net_->input_blobs()[1];\n float* in_features_data = input_in_features->mutable_cpu_data();\n\n vector<float> in_features_c; \/\/ collection of data in in_features\n int sz = w_ * h_;\n for (size_t c = 0; c < feature_num; ++c) {\n for (size_t e = 0; e < sz; ++e) {\n in_features_c.push_back(features_in[c][e]);\n }\n }\n for (size_t e = 0; e < in_features_c.size(); ++e) {\n *in_features_data = in_features_c[e];\n ++in_features_data;\n }\n\n \/\/ Input out_features shape: feature_num_ num_pixel\n \/\/ Net shape : 1 feature_num_ 1 num_pixel\n Blob<float>* input_out_features = net_->input_blobs()[2];\n float* out_features_data = input_out_features->mutable_cpu_data();\n\n vector<float> out_features_c; \/\/ collection of data in out_features\n for (size_t c = 0; c < feature_num; ++c) {\n for (size_t e = 0; e < sz; ++e) {\n out_features_c.push_back(features_out[c][e]);\n }\n }\n for (size_t e = 0; e < out_features_c.size(); ++e) {\n *out_features_data = out_features_c[e];\n ++out_features_data;\n }\n\n \/\/ Scales1 1 feature_num_ 1 1\n Blob<float>* input_scales1 = net_->input_blobs()[3];\n float* scales1_data = input_scales1->mutable_cpu_data();\n \/\/ Scales2 1 feature_num_ 1 1\n Blob<float>* input_scales2 = net_->input_blobs()[4];\n float* scales2_data = input_scales2->mutable_cpu_data();\n\n float s1[] = {0.06, 0.2, 0.2, 0.02, 0.02};\n float s2[] = {0.09, 0.3, 0.3, 0.03, 0.03};\n vector<float> scales1(s1, s1 + sizeof(s1) \/ sizeof(float));\n for (size_t e = 0; e < feature_num; ++e) {\n *scales1_data = scales1[e];\n ++scales1_data;\n }\n vector<float> scales2(s2, s2 + sizeof(s2) \/ sizeof(float));\n for (size_t e = 0; e < feature_num; ++e) {\n *scales2_data = scales2[e];\n ++scales2_data;\n }\n}\n\nvoid RefineDepth::getOutput(Mat &depth_out)\n{\n int num_elements = 1;\n const string out_depth_name = \"out_depth1\";\n const boost::shared_ptr<Blob<float> > out_depth_blob =\n net_->blob_by_name(out_depth_name.c_str());\n\n num_elements = 1;\n for (int i = 0; i < out_depth_blob->num_axes(); ++i) {\n const int elements_in_dim = out_depth_blob->shape(i);\n num_elements *= elements_in_dim;\n }\n\n vector<float> temp_depth;\n for (int n = 0; n < num_elements; ++n) {\n const float* out_depth_blob_data = out_depth_blob->cpu_data() + n;\n temp_depth.push_back(*out_depth_blob_data);\n }\n\n for (int i = 0; i < temp_depth.size(); ++i) {\n int r = i \/ w_;\n int c = i % w_;\n depth_out.at<float>(r, c) = float(temp_depth[i]);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"generator\/feature_merger.hpp\"\n#include \"generator\/generate_info.hpp\"\n#include \"generator\/popular_places_section_builder.hpp\"\n\n#include \"search\/utils.hpp\"\n\n#include \"indexer\/classificator.hpp\"\n#include \"indexer\/scales.hpp\"\n\n#include \"coding\/pointd_to_pointu.hpp\"\n\n#include \"geometry\/polygon.hpp\"\n#include \"geometry\/region2d.hpp\"\n#include \"geometry\/tree4d.hpp\"\n\n#include \"base\/logging.hpp\"\n\n#include <algorithm>\n#include <cstdint>\n#include <map>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include \"defines.hpp\"\n\nnamespace\n{\nclass WaterBoundaryChecker\n{\n uint32_t m_boundaryType;\n\n struct RegionTraits\n {\n m2::RectD const & LimitRect(m2::RegionD const & r) const { return r.GetRect(); }\n };\n m4::Tree<m2::RegionD, RegionTraits> m_tree;\n\n size_t m_totalFeatures = 0;\n size_t m_totalBorders = 0;\n size_t m_skippedBorders = 0;\n size_t m_selectedPolygons = 0;\n\npublic:\n WaterBoundaryChecker(feature::GenerateInfo const & info)\n {\n m_boundaryType = classif().GetTypeByPath({\"boundary\", \"administrative\"});\n LoadWaterGeometry(\n info.GetIntermediateFileName(WORLD_COASTS_FILE_NAME, RAW_GEOM_FILE_EXTENSION));\n }\n\n ~WaterBoundaryChecker()\n {\n LOG_SHORT(LINFO, (\"Features checked:\", m_totalFeatures, \"borders checked:\", m_totalBorders,\n \"borders skipped:\", m_skippedBorders, \"selected polygons:\", m_selectedPolygons));\n }\n\n void LoadWaterGeometry(std::string const & rawGeometryFileName)\n {\n LOG_SHORT(LINFO, (\"Loading water geometry:\", rawGeometryFileName));\n FileReader reader(rawGeometryFileName);\n ReaderSource<FileReader> file(reader);\n\n size_t total = 0;\n while (true)\n {\n uint64_t numGeometries = 0;\n file.Read(&numGeometries, sizeof(numGeometries));\n\n if (numGeometries == 0)\n break;\n\n ++total;\n\n for (size_t i = 0; i < numGeometries; ++i)\n {\n uint64_t numPoints = 0;\n file.Read(&numPoints, sizeof(numPoints));\n\n std::vector<m2::PointD> points(numPoints);\n file.Read(points.data(), sizeof(m2::PointD) * numPoints);\n m_tree.Add(m2::RegionD(move(points)));\n }\n }\n LOG_SHORT(LINFO, (\"Load\", total, \"water geometries\"));\n }\n\n bool IsBoundaries(FeatureBuilder1 const & fb)\n {\n ++m_totalFeatures;\n\n if (fb.FindType(m_boundaryType, 2) == ftype::GetEmptyValue())\n return false;\n\n ++m_totalBorders;\n\n return true;\n }\n\n enum class ProcessState\n {\n Initial,\n Water,\n Earth\n };\n\n void ProcessBoundary(FeatureBuilder1 const & boundary, std::vector<FeatureBuilder1> & parts)\n {\n auto const & line = boundary.GetGeometry().front();\n\n double constexpr kExtension = 0.01;\n ProcessState state = ProcessState::Initial;\n\n FeatureBuilder1::PointSeq points;\n\n for (size_t i = 0; i < line.size(); ++i)\n {\n m2::PointD const & p = line[i];\n m2::RectD r(p.x - kExtension, p.y - kExtension, p.x + kExtension, p.y + kExtension);\n size_t hits = 0;\n m_tree.ForEachInRect(r, [&](m2::RegionD const & rgn)\n {\n ++m_selectedPolygons;\n hits += rgn.Contains(p) ? 1 : 0;\n });\n\n bool inWater = (hits & 0x01) == 1;\n\n switch (state)\n {\n case ProcessState::Initial:\n {\n if (inWater)\n {\n state = ProcessState::Water;\n }\n else\n {\n points.push_back(p);\n state = ProcessState::Earth;\n }\n break;\n }\n case ProcessState::Water:\n {\n if (inWater)\n {\n \/\/ do nothing\n }\n else\n {\n points.push_back(p);\n state = ProcessState::Earth;\n }\n break;\n }\n case ProcessState::Earth:\n {\n if (inWater)\n {\n if (points.size() > 1)\n {\n parts.push_back(boundary);\n parts.back().ResetGeometry();\n for (auto const & pt : points)\n parts.back().AddPoint(pt);\n }\n points.clear();\n state = ProcessState::Water;\n }\n else\n {\n points.push_back(p);\n }\n break;\n }\n }\n }\n\n if (points.size() > 1)\n {\n parts.push_back(boundary);\n parts.back().ResetGeometry();\n for (auto const & pt : points)\n parts.back().AddPoint(pt);\n }\n\n if (parts.empty())\n m_skippedBorders++;\n }\n};\n} \/\/ namespace\n\n\/\/\/ Process FeatureBuilder1 for world map. Main functions:\n\/\/\/ - check for visibility in world map\n\/\/\/ - merge linear features\ntemplate <class FeatureOutT>\nclass WorldMapGenerator\n{\n class EmitterImpl : public FeatureEmitterIFace\n {\n FeatureOutT m_output;\n std::map<uint32_t, size_t> m_mapTypes;\n\n public:\n explicit EmitterImpl(feature::GenerateInfo const & info)\n : m_output(info.GetTmpFileName(WORLD_FILE_NAME))\n {\n LOG_SHORT(LINFO, (\"Output World file:\", info.GetTmpFileName(WORLD_FILE_NAME)));\n }\n\n ~EmitterImpl() override\n {\n Classificator const & c = classif();\n \n std::stringstream ss;\n ss << std::endl;\n for (auto const & p : m_mapTypes)\n ss << c.GetReadableObjectName(p.first) << \" : \" << p.second << std::endl;\n LOG_SHORT(LINFO, (\"World types:\", ss.str()));\n }\n\n \/\/\/ This function is called after merging linear features.\n void operator()(FeatureBuilder1 const & fb) override\n {\n \/\/ do additional check for suitable size of feature\n if (NeedPushToWorld(fb) &&\n scales::IsGoodForLevel(scales::GetUpperWorldScale(), fb.GetLimitRect()))\n PushSure(fb);\n }\n\n void CalcStatistics(FeatureBuilder1 const & fb)\n {\n for (uint32_t type : fb.GetTypes())\n ++m_mapTypes[type];\n }\n\n bool NeedPushToWorld(FeatureBuilder1 const & fb) const\n {\n \/\/ GetMinFeatureDrawScale also checks suitable size for AREA features\n return (scales::GetUpperWorldScale() >= fb.GetMinFeatureDrawScale());\n }\n\n void PushSure(FeatureBuilder1 const & fb) { m_output(fb); }\n };\n\n EmitterImpl m_worldBucket;\n FeatureTypesProcessor m_typesCorrector;\n FeatureMergeProcessor m_merger;\n WaterBoundaryChecker m_boundaryChecker;\n generator::PopularPlaces m_popularPlaces;\n\npublic:\n explicit WorldMapGenerator(feature::GenerateInfo const & info)\n : m_worldBucket(info),\n m_merger(POINT_COORD_BITS - (scales::GetUpperScale() - scales::GetUpperWorldScale()) \/ 2),\n m_boundaryChecker(info)\n {\n \/\/ Do not strip last types for given tags,\n \/\/ for example, do not cut 'admin_level' in 'boundary-administrative-XXX'.\n char const * arr1[][3] = {{\"boundary\", \"administrative\", \"2\"},\n {\"boundary\", \"administrative\", \"3\"},\n {\"boundary\", \"administrative\", \"4\"}};\n\n for (size_t i = 0; i < ARRAY_SIZE(arr1); ++i)\n m_typesCorrector.SetDontNormalizeType(arr1[i]);\n\n char const * arr2[] = {\"boundary\", \"administrative\", \"4\", \"state\"};\n m_typesCorrector.SetDontNormalizeType(arr2);\n\n if (!info.m_popularPlacesFilename.empty())\n generator::LoadPopularPlaces(info.m_popularPlacesFilename, m_popularPlaces);\n else\n LOG(LWARNING, (\"popular_places_data option not set. Popular atractions will not be added to World.mwm\"));\n }\n\n void operator()(FeatureBuilder1 fb)\n {\n auto const isPopularAttraction = IsPopularAttraction(fb);\n auto const isInternationalAirport =\n fb.HasType(classif().GetTypeByPath({\"aeroway\", \"aerodrome\", \"international\"}));\n auto const forcePushToWorld = isPopularAttraction || isInternationalAirport;\n\n if (!m_worldBucket.NeedPushToWorld(fb) && !forcePushToWorld)\n return;\n\n m_worldBucket.CalcStatistics(fb);\n\n if (!m_boundaryChecker.IsBoundaries(fb))\n {\n \/\/ Save original feature iff we need to force push it before PushFeature(fb) modifies fb.\n auto originalFeature = forcePushToWorld ? fb : FeatureBuilder1();\n\n if (PushFeature(fb) || !forcePushToWorld)\n return;\n\n \/\/ We push GEOM_POINT with all the same tags, names and center instead of GEOM_WAY\/GEOM_AREA\n \/\/ because we do not need geometry for invisible features (just search index and placepage\n \/\/ data) and want to avoid size checks applied to areas.\n if (originalFeature.GetGeomType() != feature::GEOM_POINT)\n originalFeature.SetCenter(originalFeature.GetGeometryCenter());\n\n m_worldBucket.PushSure(originalFeature);\n return;\n }\n\n std::vector<FeatureBuilder1> boundaryParts;\n m_boundaryChecker.ProcessBoundary(fb, boundaryParts);\n for (auto & f : boundaryParts)\n PushFeature(f);\n }\n\n bool PushFeature(FeatureBuilder1 & fb)\n {\n switch (fb.GetGeomType())\n {\n case feature::GEOM_LINE:\n {\n MergedFeatureBuilder1 * p = m_typesCorrector(fb);\n if (p)\n m_merger(p);\n return false;\n }\n case feature::GEOM_AREA:\n {\n \/\/ This constant is set according to size statistics.\n \/\/ Added approx 4Mb of data to the World.mwm\n auto const & geometry = fb.GetOuterGeometry();\n if (GetPolygonArea(geometry.begin(), geometry.end()) < 0.01)\n return false;\n }\n default:\n break;\n }\n\n if (feature::PreprocessForWorldMap(fb))\n {\n m_worldBucket.PushSure(fb);\n return true;\n }\n\n return false;\n }\n\n void DoMerge() { m_merger.DoMerge(m_worldBucket); }\n\nprivate:\n bool IsPopularAttraction(FeatureBuilder1 const & fb) const\n {\n if (fb.GetName().empty())\n return false;\n\n auto const attractionTypes =\n search::GetCategoryTypes(\"attractions\", \"en\", GetDefaultCategories());\n ASSERT(is_sorted(attractionTypes.begin(), attractionTypes.end()), ());\n auto const & featureTypes = fb.GetTypes();\n if (!std::any_of(featureTypes.begin(), featureTypes.end(), [&attractionTypes](uint32_t t) {\n return binary_search(attractionTypes.begin(), attractionTypes.end(), t);\n }))\n {\n return false;\n }\n\n auto const it = m_popularPlaces.find(fb.GetMostGenericOsmId());\n if (it == m_popularPlaces.end())\n return false;\n\n \/\/ todo(@t.yan): adjust\n uint8_t const kPopularityThreshold = 40;\n if (it->second < kPopularityThreshold)\n return false;\n\n \/\/ todo(@t.yan): maybe check place has wikipedia link.\n return true;\n }\n};\n\ntemplate <class FeatureOut>\nclass SimpleCountryMapGenerator\n{\npublic:\n SimpleCountryMapGenerator(feature::GenerateInfo const & info) : m_bucket(info) {}\n\n void operator()(FeatureBuilder1 & fb)\n {\n m_bucket(fb);\n }\n\n FeatureOut & Parent() { return m_bucket; }\n\nprivate:\n FeatureOut m_bucket;\n};\n\ntemplate <class FeatureOut>\nclass CountryMapGenerator : public SimpleCountryMapGenerator<FeatureOut>\n{\npublic:\n CountryMapGenerator(feature::GenerateInfo const & info) :\n SimpleCountryMapGenerator<FeatureOut>(info) {}\n\n void operator()(FeatureBuilder1 fb)\n {\n if (feature::PreprocessForCountryMap(fb))\n SimpleCountryMapGenerator<FeatureOut>::operator()(fb);\n }\n};\n<commit_msg>[generator][search] Adjust kPopularityThreshold for new data<commit_after>#pragma once\n\n#include \"generator\/feature_merger.hpp\"\n#include \"generator\/generate_info.hpp\"\n#include \"generator\/popular_places_section_builder.hpp\"\n\n#include \"search\/utils.hpp\"\n\n#include \"indexer\/classificator.hpp\"\n#include \"indexer\/scales.hpp\"\n\n#include \"coding\/pointd_to_pointu.hpp\"\n\n#include \"geometry\/polygon.hpp\"\n#include \"geometry\/region2d.hpp\"\n#include \"geometry\/tree4d.hpp\"\n\n#include \"base\/logging.hpp\"\n\n#include <algorithm>\n#include <cstdint>\n#include <map>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include \"defines.hpp\"\n\nnamespace\n{\nclass WaterBoundaryChecker\n{\n uint32_t m_boundaryType;\n\n struct RegionTraits\n {\n m2::RectD const & LimitRect(m2::RegionD const & r) const { return r.GetRect(); }\n };\n m4::Tree<m2::RegionD, RegionTraits> m_tree;\n\n size_t m_totalFeatures = 0;\n size_t m_totalBorders = 0;\n size_t m_skippedBorders = 0;\n size_t m_selectedPolygons = 0;\n\npublic:\n WaterBoundaryChecker(feature::GenerateInfo const & info)\n {\n m_boundaryType = classif().GetTypeByPath({\"boundary\", \"administrative\"});\n LoadWaterGeometry(\n info.GetIntermediateFileName(WORLD_COASTS_FILE_NAME, RAW_GEOM_FILE_EXTENSION));\n }\n\n ~WaterBoundaryChecker()\n {\n LOG_SHORT(LINFO, (\"Features checked:\", m_totalFeatures, \"borders checked:\", m_totalBorders,\n \"borders skipped:\", m_skippedBorders, \"selected polygons:\", m_selectedPolygons));\n }\n\n void LoadWaterGeometry(std::string const & rawGeometryFileName)\n {\n LOG_SHORT(LINFO, (\"Loading water geometry:\", rawGeometryFileName));\n FileReader reader(rawGeometryFileName);\n ReaderSource<FileReader> file(reader);\n\n size_t total = 0;\n while (true)\n {\n uint64_t numGeometries = 0;\n file.Read(&numGeometries, sizeof(numGeometries));\n\n if (numGeometries == 0)\n break;\n\n ++total;\n\n for (size_t i = 0; i < numGeometries; ++i)\n {\n uint64_t numPoints = 0;\n file.Read(&numPoints, sizeof(numPoints));\n\n std::vector<m2::PointD> points(numPoints);\n file.Read(points.data(), sizeof(m2::PointD) * numPoints);\n m_tree.Add(m2::RegionD(move(points)));\n }\n }\n LOG_SHORT(LINFO, (\"Load\", total, \"water geometries\"));\n }\n\n bool IsBoundaries(FeatureBuilder1 const & fb)\n {\n ++m_totalFeatures;\n\n if (fb.FindType(m_boundaryType, 2) == ftype::GetEmptyValue())\n return false;\n\n ++m_totalBorders;\n\n return true;\n }\n\n enum class ProcessState\n {\n Initial,\n Water,\n Earth\n };\n\n void ProcessBoundary(FeatureBuilder1 const & boundary, std::vector<FeatureBuilder1> & parts)\n {\n auto const & line = boundary.GetGeometry().front();\n\n double constexpr kExtension = 0.01;\n ProcessState state = ProcessState::Initial;\n\n FeatureBuilder1::PointSeq points;\n\n for (size_t i = 0; i < line.size(); ++i)\n {\n m2::PointD const & p = line[i];\n m2::RectD r(p.x - kExtension, p.y - kExtension, p.x + kExtension, p.y + kExtension);\n size_t hits = 0;\n m_tree.ForEachInRect(r, [&](m2::RegionD const & rgn)\n {\n ++m_selectedPolygons;\n hits += rgn.Contains(p) ? 1 : 0;\n });\n\n bool inWater = (hits & 0x01) == 1;\n\n switch (state)\n {\n case ProcessState::Initial:\n {\n if (inWater)\n {\n state = ProcessState::Water;\n }\n else\n {\n points.push_back(p);\n state = ProcessState::Earth;\n }\n break;\n }\n case ProcessState::Water:\n {\n if (inWater)\n {\n \/\/ do nothing\n }\n else\n {\n points.push_back(p);\n state = ProcessState::Earth;\n }\n break;\n }\n case ProcessState::Earth:\n {\n if (inWater)\n {\n if (points.size() > 1)\n {\n parts.push_back(boundary);\n parts.back().ResetGeometry();\n for (auto const & pt : points)\n parts.back().AddPoint(pt);\n }\n points.clear();\n state = ProcessState::Water;\n }\n else\n {\n points.push_back(p);\n }\n break;\n }\n }\n }\n\n if (points.size() > 1)\n {\n parts.push_back(boundary);\n parts.back().ResetGeometry();\n for (auto const & pt : points)\n parts.back().AddPoint(pt);\n }\n\n if (parts.empty())\n m_skippedBorders++;\n }\n};\n} \/\/ namespace\n\n\/\/\/ Process FeatureBuilder1 for world map. Main functions:\n\/\/\/ - check for visibility in world map\n\/\/\/ - merge linear features\ntemplate <class FeatureOutT>\nclass WorldMapGenerator\n{\n class EmitterImpl : public FeatureEmitterIFace\n {\n FeatureOutT m_output;\n std::map<uint32_t, size_t> m_mapTypes;\n\n public:\n explicit EmitterImpl(feature::GenerateInfo const & info)\n : m_output(info.GetTmpFileName(WORLD_FILE_NAME))\n {\n LOG_SHORT(LINFO, (\"Output World file:\", info.GetTmpFileName(WORLD_FILE_NAME)));\n }\n\n ~EmitterImpl() override\n {\n Classificator const & c = classif();\n \n std::stringstream ss;\n ss << std::endl;\n for (auto const & p : m_mapTypes)\n ss << c.GetReadableObjectName(p.first) << \" : \" << p.second << std::endl;\n LOG_SHORT(LINFO, (\"World types:\", ss.str()));\n }\n\n \/\/\/ This function is called after merging linear features.\n void operator()(FeatureBuilder1 const & fb) override\n {\n \/\/ do additional check for suitable size of feature\n if (NeedPushToWorld(fb) &&\n scales::IsGoodForLevel(scales::GetUpperWorldScale(), fb.GetLimitRect()))\n PushSure(fb);\n }\n\n void CalcStatistics(FeatureBuilder1 const & fb)\n {\n for (uint32_t type : fb.GetTypes())\n ++m_mapTypes[type];\n }\n\n bool NeedPushToWorld(FeatureBuilder1 const & fb) const\n {\n \/\/ GetMinFeatureDrawScale also checks suitable size for AREA features\n return (scales::GetUpperWorldScale() >= fb.GetMinFeatureDrawScale());\n }\n\n void PushSure(FeatureBuilder1 const & fb) { m_output(fb); }\n };\n\n EmitterImpl m_worldBucket;\n FeatureTypesProcessor m_typesCorrector;\n FeatureMergeProcessor m_merger;\n WaterBoundaryChecker m_boundaryChecker;\n generator::PopularPlaces m_popularPlaces;\n\npublic:\n explicit WorldMapGenerator(feature::GenerateInfo const & info)\n : m_worldBucket(info),\n m_merger(POINT_COORD_BITS - (scales::GetUpperScale() - scales::GetUpperWorldScale()) \/ 2),\n m_boundaryChecker(info)\n {\n \/\/ Do not strip last types for given tags,\n \/\/ for example, do not cut 'admin_level' in 'boundary-administrative-XXX'.\n char const * arr1[][3] = {{\"boundary\", \"administrative\", \"2\"},\n {\"boundary\", \"administrative\", \"3\"},\n {\"boundary\", \"administrative\", \"4\"}};\n\n for (size_t i = 0; i < ARRAY_SIZE(arr1); ++i)\n m_typesCorrector.SetDontNormalizeType(arr1[i]);\n\n char const * arr2[] = {\"boundary\", \"administrative\", \"4\", \"state\"};\n m_typesCorrector.SetDontNormalizeType(arr2);\n\n if (!info.m_popularPlacesFilename.empty())\n generator::LoadPopularPlaces(info.m_popularPlacesFilename, m_popularPlaces);\n else\n LOG(LWARNING, (\"popular_places_data option not set. Popular atractions will not be added to World.mwm\"));\n }\n\n void operator()(FeatureBuilder1 fb)\n {\n auto const isPopularAttraction = IsPopularAttraction(fb);\n auto const isInternationalAirport =\n fb.HasType(classif().GetTypeByPath({\"aeroway\", \"aerodrome\", \"international\"}));\n auto const forcePushToWorld = isPopularAttraction || isInternationalAirport;\n\n if (!m_worldBucket.NeedPushToWorld(fb) && !forcePushToWorld)\n return;\n\n m_worldBucket.CalcStatistics(fb);\n\n if (!m_boundaryChecker.IsBoundaries(fb))\n {\n \/\/ Save original feature iff we need to force push it before PushFeature(fb) modifies fb.\n auto originalFeature = forcePushToWorld ? fb : FeatureBuilder1();\n\n if (PushFeature(fb) || !forcePushToWorld)\n return;\n\n \/\/ We push GEOM_POINT with all the same tags, names and center instead of GEOM_WAY\/GEOM_AREA\n \/\/ because we do not need geometry for invisible features (just search index and placepage\n \/\/ data) and want to avoid size checks applied to areas.\n if (originalFeature.GetGeomType() != feature::GEOM_POINT)\n originalFeature.SetCenter(originalFeature.GetGeometryCenter());\n\n m_worldBucket.PushSure(originalFeature);\n return;\n }\n\n std::vector<FeatureBuilder1> boundaryParts;\n m_boundaryChecker.ProcessBoundary(fb, boundaryParts);\n for (auto & f : boundaryParts)\n PushFeature(f);\n }\n\n bool PushFeature(FeatureBuilder1 & fb)\n {\n switch (fb.GetGeomType())\n {\n case feature::GEOM_LINE:\n {\n MergedFeatureBuilder1 * p = m_typesCorrector(fb);\n if (p)\n m_merger(p);\n return false;\n }\n case feature::GEOM_AREA:\n {\n \/\/ This constant is set according to size statistics.\n \/\/ Added approx 4Mb of data to the World.mwm\n auto const & geometry = fb.GetOuterGeometry();\n if (GetPolygonArea(geometry.begin(), geometry.end()) < 0.01)\n return false;\n }\n default:\n break;\n }\n\n if (feature::PreprocessForWorldMap(fb))\n {\n m_worldBucket.PushSure(fb);\n return true;\n }\n\n return false;\n }\n\n void DoMerge() { m_merger.DoMerge(m_worldBucket); }\n\nprivate:\n bool IsPopularAttraction(FeatureBuilder1 const & fb) const\n {\n if (fb.GetName().empty())\n return false;\n\n auto const attractionTypes =\n search::GetCategoryTypes(\"attractions\", \"en\", GetDefaultCategories());\n ASSERT(is_sorted(attractionTypes.begin(), attractionTypes.end()), ());\n auto const & featureTypes = fb.GetTypes();\n if (!std::any_of(featureTypes.begin(), featureTypes.end(), [&attractionTypes](uint32_t t) {\n return binary_search(attractionTypes.begin(), attractionTypes.end(), t);\n }))\n {\n return false;\n }\n\n auto const it = m_popularPlaces.find(fb.GetMostGenericOsmId());\n if (it == m_popularPlaces.end())\n return false;\n\n \/\/ todo(@t.yan): adjust\n uint8_t const kPopularityThreshold = 20;\n if (it->second < kPopularityThreshold)\n return false;\n\n \/\/ todo(@t.yan): maybe check place has wikipedia link.\n return true;\n }\n};\n\ntemplate <class FeatureOut>\nclass SimpleCountryMapGenerator\n{\npublic:\n SimpleCountryMapGenerator(feature::GenerateInfo const & info) : m_bucket(info) {}\n\n void operator()(FeatureBuilder1 & fb)\n {\n m_bucket(fb);\n }\n\n FeatureOut & Parent() { return m_bucket; }\n\nprivate:\n FeatureOut m_bucket;\n};\n\ntemplate <class FeatureOut>\nclass CountryMapGenerator : public SimpleCountryMapGenerator<FeatureOut>\n{\npublic:\n CountryMapGenerator(feature::GenerateInfo const & info) :\n SimpleCountryMapGenerator<FeatureOut>(info) {}\n\n void operator()(FeatureBuilder1 fb)\n {\n if (feature::PreprocessForCountryMap(fb))\n SimpleCountryMapGenerator<FeatureOut>::operator()(fb);\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2014 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 <Nazara\/Utility\/Debug.hpp>\n\ntemplate<typename T>\nNzBoxf NzComputeVerticesAABB(const T* vertices, unsigned int vertexCount)\n{\n\tNzBoxf aabb;\n\tif (vertexCount > 0)\n\t{\n\t\taabb.Set(vertices->position.x, vertices->position.y, vertices->position.z, 0.f, 0.f, 0.f);\n\t\tvertices++;\n\n\t\tfor (unsigned int i = 1; i < vertexCount; ++i)\n\t\t{\n\t\t\taabb.ExtendTo(vertices->position);\n\t\t\tvertices++;\n\t\t}\n\t}\n\telse\n\t\taabb.MakeZero();\n\n\treturn aabb;\n}\n\ntemplate<typename T>\nvoid NzTransformVertices(T* vertices, unsigned int vertexCount, const NzMatrix4f& matrix)\n{\n\tif (matrix.IsIdentity())\n\t\treturn;\n\n\tNzVector3f scale = matrix.GetScale();\n\n\tfor (unsigned int i = 0; i < vertexCount; ++i)\n\t{\n\t\tvertices->normal = matrix.Transform(vertices->normal, 0.f) \/ scale;\n\t\tvertices->position = matrix.Transform(vertices->position);\n\t\tvertices->tangent = matrix.Transform(vertices->tangent, 0.f) \/ scale;\n\t\tvertices++;\n\t}\n}\n\n#include <Nazara\/Utility\/DebugOff.hpp>\n<commit_msg>Removed Identity test in TransformVertices<commit_after>\/\/ Copyright (C) 2014 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 <Nazara\/Utility\/Debug.hpp>\n\ntemplate<typename T>\nNzBoxf NzComputeVerticesAABB(const T* vertices, unsigned int vertexCount)\n{\n\tNzBoxf aabb;\n\tif (vertexCount > 0)\n\t{\n\t\taabb.Set(vertices->position.x, vertices->position.y, vertices->position.z, 0.f, 0.f, 0.f);\n\t\tvertices++;\n\n\t\tfor (unsigned int i = 1; i < vertexCount; ++i)\n\t\t{\n\t\t\taabb.ExtendTo(vertices->position);\n\t\t\tvertices++;\n\t\t}\n\t}\n\telse\n\t\taabb.MakeZero();\n\n\treturn aabb;\n}\n\ntemplate<typename T>\nvoid NzTransformVertices(T* vertices, unsigned int vertexCount, const NzMatrix4f& matrix)\n{\n\tNzVector3f scale = matrix.GetScale();\n\n\tfor (unsigned int i = 0; i < vertexCount; ++i)\n\t{\n\t\tvertices->normal = matrix.Transform(vertices->normal, 0.f) \/ scale;\n\t\tvertices->position = matrix.Transform(vertices->position);\n\t\tvertices->tangent = matrix.Transform(vertices->tangent, 0.f) \/ scale;\n\t\tvertices++;\n\t}\n}\n\n#include <Nazara\/Utility\/DebugOff.hpp>\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ ParameterGraph.hpp\n\/\/\/ Shaun Harker\n\/\/\/ 2015-05-24\n\n#ifndef DSGRN_PARAMETERGRAPH_HPP\n#define DSGRN_PARAMETERGRAPH_HPP\n\n#ifndef INLINE_IF_HEADER_ONLY\n#define INLINE_IF_HEADER_ONLY\n#endif\n\n#include \"ParameterGraph.h\"\n\nINLINE_IF_HEADER_ONLY ParameterGraph::\nParameterGraph ( void ) {\n data_ . reset ( new ParameterGraph_ );\n}\n\nINLINE_IF_HEADER_ONLY ParameterGraph::\nParameterGraph ( Network const& network, std::string const& path ) {\n assign ( network, path );\n}\n\nINLINE_IF_HEADER_ONLY void ParameterGraph::\nassign ( Network const& network, std::string const& path ) {\n data_ . reset ( new ParameterGraph_ );\n data_ -> network_ = network;\n data_ -> reorderings_ = 1;\n data_ -> fixedordersize_ = 1;\n \/\/ Load the network files one by one.\n uint64_t D = data_ -> network_ . size ();\n for ( uint64_t d = 0; d < D; ++ d ) {\n uint64_t n = data_ -> network_ . inputs ( d ) . size ();\n uint64_t m = data_ -> network_ . outputs ( d ) . size ();\n data_ -> order_place_values_ . push_back ( _factorial ( m ) );\n data_ -> reorderings_ *= data_ -> order_place_values_ . back ();\n std::vector<std::vector<uint64_t>> const& logic_struct = data_ -> network_ . logic ( d );\n std::stringstream ss;\n ss << path << \"\/\" << n << \"_\" << m;\n for ( auto const& p : logic_struct ) ss << \"_\" << p.size();\n if ( data_ -> network_ . essential ( d ) ) ss << \"_E\";\n ss << \".dat\";\n \/\/std::cout << \"Acquiring logic data in \" << ss.str() << \"\\n\";\n std::vector<std::string> hex_codes;\n std::ifstream infile ( ss.str() );\n if ( not infile . good () ) {\n throw std::runtime_error ( \"Error: Could not find logic resource \" + ss.str() + \".\\n\");\n }\n std::string line;\n while ( std::getline ( infile, line ) ) hex_codes . push_back ( line );\n infile . close ();\n data_ -> factors_ . push_back ( hex_codes );\n data_ -> logic_place_values_ . push_back ( hex_codes . size () );\n data_ -> fixedordersize_ *= hex_codes . size ();\n \/\/std::cout << d << \": \" << hex_codes . size () << \" factorial(\" << m << \")=\" << _factorial ( m ) << \"\\n\";\n }\n data_ -> size_ = data_ -> fixedordersize_ * data_ -> reorderings_;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\nsize ( void ) const {\n return data_ -> size_;\n}\n\nINLINE_IF_HEADER_ONLY Parameter ParameterGraph::\nparameter ( uint64_t index ) const {\n \/\/std::cout << data_ -> \"ParameterGraph::parameter( \" << index << \" )\\n\";\n if ( index >= size () ) {\n throw std::runtime_error ( \"ParameterGraph::parameter Index out of bounds\");\n }\n uint64_t logic_index = index % data_ -> fixedordersize_;\n uint64_t order_index = index \/ data_ -> fixedordersize_;\n \/\/std::cout << \"Logic index = \" << logic_index << \"\\n\";\n \/\/std::cout << \"Order index = \" << order_index << \"\\n\";\n\n uint64_t D = data_ -> network_ . size ();\n std::vector<uint64_t> logic_indices;\n for ( uint64_t d = 0; d < D; ++ d ) {\n uint64_t i = logic_index % data_ -> logic_place_values_ [ d ];\n logic_index \/= data_ -> logic_place_values_ [ d ];\n logic_indices . push_back ( i );\n }\n std::vector<uint64_t> order_indices;\n for ( uint64_t d = 0; d < D; ++ d ) {\n uint64_t i = order_index % data_ -> order_place_values_ [ d ];\n order_index \/= data_ -> order_place_values_ [ d ];\n order_indices . push_back ( i );\n }\n std::vector<LogicParameter> logic;\n std::vector<OrderParameter> order;\n for ( uint64_t d = 0; d < D; ++ d ) {\n uint64_t n = data_ -> network_ . inputs ( d ) . size ();\n uint64_t m = data_ -> network_ . outputs ( d ) . size ();\n std::string hex_code = data_ -> factors_ [ d ] [ logic_indices[d] ];\n LogicParameter logic_param ( n, m, hex_code );\n OrderParameter order_param ( m, order_indices[d] );\n logic . push_back ( logic_param );\n order . push_back ( order_param );\n }\n Parameter result ( logic, order, data_ -> network_ );\n return result;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\nindex ( Parameter const& p ) const {\n\/\/ throw std::runtime_error ( \"Feature not implemented\" ); \/\/ TODO\n\n std::vector<LogicParameter> logic = p . logic ( );\n std::vector<OrderParameter> order = p . order ( );\n\n \/\/\/ Construct Logic indices\n std::vector<uint64_t> logic_indices;\n uint64_t D = data_ -> network_ . size ();\n for ( uint64_t d = 0; d< D; ++d ) {\n std::string hexcode = logic [ d ] . hex ( );\n \/\/\/ If factors_ was a different container, we could use find instead\n \/\/\/ find the hex code within factors_ for the appropriate node\n uint64_t hexsize = data_ -> factors_ [ d ] . size ( );\n for ( uint64_t i = 0; i < hexsize; ++i ) {\n if ( hexcode == data_ -> factors_ [ d ] [ i ] ) {\n logic_indices . push_back ( i );\n }\n }\n }\n \/\/ debug\n std::cout << \"\\nLogic indices:\\n\";\n for ( uint64_t d = 0; d< D; ++d ) std::cout << logic_indices[d] << \" \";\n std::cout << \"\\n\";\n \/\/ end debug\n\n \/\/\/ Construct Order indices\n std::vector<uint64_t> order_indices;\n for ( uint64_t d = 0; d < D; ++ d ) {\n order_indices . push_back ( order[d].index() );\n }\n \/\/ debug\n std::cout << \"\\nOrder indices:\\n\";\n for ( uint64_t d = 0; d< D; ++d ) std::cout << order_indices[d] << \" \";\n std::cout << \"\\n\";\n \/\/ end debug\n\n \/\/ Debug\n std::cout << \"\\n\\n\";\n std::cout << \"Logic_place_values : \";\n for ( uint64_t d = 0; d< D; ++d ) std::cout << data_ -> logic_place_values_[d] << \" \";\n std::cout << \"\\n\";\n std::cout << \"Order_place_values : \";\n for ( uint64_t d = 0; d< D; ++d ) std::cout << data_ -> order_place_values_[d] << \" \";\n std::cout << \"\\n\";\n std::cout << \"Fixed order size : \" << data_ -> fixedordersize_;\n std::cout << \"\\n\\n\";\n \/\/ end debug\n\n\n \/\/\/ Find logic_index and order_index, in general\n \/\/\/ notation :\n \/\/\/ Logic_place_values : lpv\n \/\/\/ logics_indices : lis\n \/\/\/\n \/\/\/ For the logic index L :\n \/\/\/ A[n] = m_n * lpv[n] + lis[n] for n > 1, and m_n are unknown integers.\n \/\/\/ L = m_0 * lpv[0] + lis[0] for n = 0\n \/\/\/ with\n \/\/\/ A[n] = floor( A[n-1] \/ lpv[n-1] ) and A[0] = L\n \/\/\/\n \n\n\n\n\n\n\n\n\n\/\/\/ BELOW WAS INCOMPLETE TEST FOR 2 NODES NETWORKS\n \/\/ \/\/\/ Return : m * Q + R\n \/\/ auto getInteger = []( const uint64_t &m, const uint64_t &Q, const uint64_t &R ) -> uint64_t {\n \/\/ return m * Q + R;\n \/\/ };\n \/\/\n \/\/ typedef std::vector<uint64_t> Interval;\n \/\/\n \/\/ \/\/\/ Return interval of the form : [ m*n*k+m*a, m*n*k+m*a+m )\n \/\/ auto getInterval = [](uint64_t &k, uint64_t &m, uint64_t &n, uint64_t &a ) -> Interval {\n \/\/ return Interval { m*n*k+m*a,m*n*k+m*a+m };\n \/\/ };\n \/\/\n \/\/ auto insideInterval = [](uint64_t &n, Interval &interval) -> bool {\n \/\/ return n>=interval[0] && n<=interval[1];\n \/\/ };\n \/\/\n \/\/ \/\/ List all the subintervals for logic_index and store the potential good values for logic index\n \/\/ std::cout << \"\\n\\nList of all subintervals for logic index\\n\";\n \/\/ std::vector<Interval> intervals; \/\/ needed just for debug\n \/\/ std::vector<uint64_t> logicindexvalues;\n \/\/ for ( uint64_t R = 0; R<data_->reorderings_; ++R ) {\n \/\/ Interval interval = getInterval( R,\n \/\/ data_ -> logic_place_values_[0],\n \/\/ data_ -> logic_place_values_[1],\n \/\/ logic_indices[1] );\n \/\/ std::cout << \"[ \" << interval[0] << \", \" << interval[1] << \" ]\\n\";\n \/\/ intervals . push_back ( interval );\n \/\/ \/\/\/ check for good values inside the interval\n \/\/ uint64_t myvalue = getInteger(data_ -> logic_place_values_[0],\n \/\/ R*data_ -> logic_place_values_[1]+logic_indices[1],\n \/\/ logic_indices[0]);\n \/\/ std::cout << \"value=\" << myvalue << \" \";\n \/\/ if ( insideInterval(myvalue,interval) ) {\n \/\/ std::cout << \"is good\\n\";\n \/\/ logicindexvalues . push_back ( myvalue );\n \/\/ } else {\n \/\/ std::cout << \"is bad\\n\";\n \/\/ }\n \/\/ }\n \/\/ \/\/ List all the subintervals for order_index and store the potential good values for order index\n\n\/\/\/ END INCOMPLETE TEST 2 NODES NETWORK\n\n\n return 0;\n\n}\n\nINLINE_IF_HEADER_ONLY std::vector<uint64_t> ParameterGraph::\nadjacencies ( uint64_t index ) const {\n throw std::runtime_error ( \"Feature not implemented\" ); \/\/TODO\n}\n\nINLINE_IF_HEADER_ONLY Network const ParameterGraph::\nnetwork ( void ) const {\n return data_ -> network_;\n}\n\nINLINE_IF_HEADER_ONLY std::ostream& operator << ( std::ostream& stream, ParameterGraph const& pg ) {\n stream << \"(ParameterGraph: \"<< pg.size() << \" parameters, \"\n << pg.network().size() << \" nodes)\";\n return stream;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\nfixedordersize ( void ) const {\n return data_ -> fixedordersize_;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\nreorderings ( void ) const {\n return data_ -> reorderings_;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\n_factorial ( uint64_t m ) const {\n static const std::vector<uint64_t> table =\n { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};\n if ( m < 10 ) return table [ m ]; else return m * _factorial ( m - 1 );\n}\n\n\n#endif\n<commit_msg>[WIP] debug index method for 2 nodes network<commit_after>\/\/\/ ParameterGraph.hpp\n\/\/\/ Shaun Harker\n\/\/\/ 2015-05-24\n\n#ifndef DSGRN_PARAMETERGRAPH_HPP\n#define DSGRN_PARAMETERGRAPH_HPP\n\n#ifndef INLINE_IF_HEADER_ONLY\n#define INLINE_IF_HEADER_ONLY\n#endif\n\n#include \"ParameterGraph.h\"\n\nINLINE_IF_HEADER_ONLY ParameterGraph::\nParameterGraph ( void ) {\n data_ . reset ( new ParameterGraph_ );\n}\n\nINLINE_IF_HEADER_ONLY ParameterGraph::\nParameterGraph ( Network const& network, std::string const& path ) {\n assign ( network, path );\n}\n\nINLINE_IF_HEADER_ONLY void ParameterGraph::\nassign ( Network const& network, std::string const& path ) {\n data_ . reset ( new ParameterGraph_ );\n data_ -> network_ = network;\n data_ -> reorderings_ = 1;\n data_ -> fixedordersize_ = 1;\n \/\/ Load the network files one by one.\n uint64_t D = data_ -> network_ . size ();\n for ( uint64_t d = 0; d < D; ++ d ) {\n uint64_t n = data_ -> network_ . inputs ( d ) . size ();\n uint64_t m = data_ -> network_ . outputs ( d ) . size ();\n data_ -> order_place_values_ . push_back ( _factorial ( m ) );\n data_ -> reorderings_ *= data_ -> order_place_values_ . back ();\n std::vector<std::vector<uint64_t>> const& logic_struct = data_ -> network_ . logic ( d );\n std::stringstream ss;\n ss << path << \"\/\" << n << \"_\" << m;\n for ( auto const& p : logic_struct ) ss << \"_\" << p.size();\n if ( data_ -> network_ . essential ( d ) ) ss << \"_E\";\n ss << \".dat\";\n \/\/std::cout << \"Acquiring logic data in \" << ss.str() << \"\\n\";\n std::vector<std::string> hex_codes;\n std::ifstream infile ( ss.str() );\n if ( not infile . good () ) {\n throw std::runtime_error ( \"Error: Could not find logic resource \" + ss.str() + \".\\n\");\n }\n std::string line;\n while ( std::getline ( infile, line ) ) hex_codes . push_back ( line );\n infile . close ();\n data_ -> factors_ . push_back ( hex_codes );\n data_ -> logic_place_values_ . push_back ( hex_codes . size () );\n data_ -> fixedordersize_ *= hex_codes . size ();\n \/\/std::cout << d << \": \" << hex_codes . size () << \" factorial(\" << m << \")=\" << _factorial ( m ) << \"\\n\";\n }\n data_ -> size_ = data_ -> fixedordersize_ * data_ -> reorderings_;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\nsize ( void ) const {\n return data_ -> size_;\n}\n\nINLINE_IF_HEADER_ONLY Parameter ParameterGraph::\nparameter ( uint64_t index ) const {\n \/\/std::cout << data_ -> \"ParameterGraph::parameter( \" << index << \" )\\n\";\n if ( index >= size () ) {\n throw std::runtime_error ( \"ParameterGraph::parameter Index out of bounds\");\n }\n uint64_t logic_index = index % data_ -> fixedordersize_;\n uint64_t order_index = index \/ data_ -> fixedordersize_;\n \/\/std::cout << \"Logic index = \" << logic_index << \"\\n\";\n \/\/std::cout << \"Order index = \" << order_index << \"\\n\";\n\n uint64_t D = data_ -> network_ . size ();\n std::vector<uint64_t> logic_indices;\n for ( uint64_t d = 0; d < D; ++ d ) {\n uint64_t i = logic_index % data_ -> logic_place_values_ [ d ];\n logic_index \/= data_ -> logic_place_values_ [ d ];\n logic_indices . push_back ( i );\n }\n std::vector<uint64_t> order_indices;\n for ( uint64_t d = 0; d < D; ++ d ) {\n uint64_t i = order_index % data_ -> order_place_values_ [ d ];\n order_index \/= data_ -> order_place_values_ [ d ];\n order_indices . push_back ( i );\n }\n std::vector<LogicParameter> logic;\n std::vector<OrderParameter> order;\n for ( uint64_t d = 0; d < D; ++ d ) {\n uint64_t n = data_ -> network_ . inputs ( d ) . size ();\n uint64_t m = data_ -> network_ . outputs ( d ) . size ();\n std::string hex_code = data_ -> factors_ [ d ] [ logic_indices[d] ];\n LogicParameter logic_param ( n, m, hex_code );\n OrderParameter order_param ( m, order_indices[d] );\n logic . push_back ( logic_param );\n order . push_back ( order_param );\n }\n Parameter result ( logic, order, data_ -> network_ );\n return result;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\nindex ( Parameter const& p ) const {\n\/\/ throw std::runtime_error ( \"Feature not implemented\" ); \/\/ TODO\n\n std::vector<LogicParameter> logic = p . logic ( );\n std::vector<OrderParameter> order = p . order ( );\n\n \/\/\/ Construct Logic indices\n std::vector<uint64_t> logic_indices;\n uint64_t D = data_ -> network_ . size ();\n for ( uint64_t d = 0; d< D; ++d ) {\n std::string hexcode = logic [ d ] . hex ( );\n \/\/\/ If factors_ was a different container, we could use find instead\n \/\/\/ find the hex code within factors_ for the appropriate node\n uint64_t hexsize = data_ -> factors_ [ d ] . size ( );\n for ( uint64_t i = 0; i < hexsize; ++i ) {\n if ( hexcode == data_ -> factors_ [ d ] [ i ] ) {\n logic_indices . push_back ( i );\n }\n }\n }\n \/\/ debug\n std::cout << \"\\nLogic indices:\\n\";\n for ( uint64_t d = 0; d< D; ++d ) std::cout << logic_indices[d] << \" \";\n std::cout << \"\\n\";\n \/\/ end debug\n\n \/\/\/ Construct Order indices\n std::vector<uint64_t> order_indices;\n for ( uint64_t d = 0; d < D; ++ d ) {\n order_indices . push_back ( order[d].index() );\n }\n \/\/ debug\n std::cout << \"\\nOrder indices:\\n\";\n for ( uint64_t d = 0; d< D; ++d ) std::cout << order_indices[d] << \" \";\n std::cout << \"\\n\";\n \/\/ end debug\n\n \/\/ Debug\n std::cout << \"\\n\\n\";\n std::cout << \"Logic_place_values : \";\n for ( uint64_t d = 0; d< D; ++d ) std::cout << data_ -> logic_place_values_[d] << \" \";\n std::cout << \"\\n\";\n std::cout << \"Order_place_values : \";\n for ( uint64_t d = 0; d< D; ++d ) std::cout << data_ -> order_place_values_[d] << \" \";\n std::cout << \"\\n\";\n std::cout << \"Fixed order size : \" << data_ -> fixedordersize_;\n std::cout << \"\\n\";\n std::cout << \"reorderings : \" << data_ -> reorderings_;\n std::cout << \"\\n\\n\";\n \/\/ end debug\n\n\n \/\/\/ Find logic_index and order_index, in general\n \/\/\/ notation :\n \/\/\/ Logic_place_values : lpv\n \/\/\/ logics_indices : lis\n \/\/\/\n \/\/\/ For the logic index L :\n \/\/\/ A[n] = m_n * lpv[n] + lis[n] ,m_n are unknown integers.\n \/\/\/ L = m_0 * lpv[0] + lis[0] for n = 0\n \/\/\/ with\n \/\/\/ A[n] = floor( A[n-1] \/ lpv[n-1] ) and A[0] = L\n \/\/\/\n \/\/\/ By using the floor function at the step n, we have :\n \/\/\/\n \/\/\/ lpv[n-1]*( m_n * lpv[n] + lis[n] ) <= A[n-1] < lpv[n-1]*( m_n * lpv[n] + lis[n] + 1 )\n \/\/\/\n \/\/\/ so A[n-1] is a set of intervals of the form\n \/\/\/ I_{n-1} = [ a_{n-1}, b_{n-1} ) for various m_n (positive integers)\n \/\/\/ with\n \/\/\/ a_{n-1} = lpv[n-1]*( m_n * lpv[n] + lis[n] )\n \/\/\/ b_{n-1} = lpv[n-1]*( m_n * lpv[n] + lis[n] + 1 ) = a_{n-1} + lpv[n-1]\n \/\/\/\n \/\/\/\n\n \/\/\/ and according to the step n-1\n \/\/\/\n \/\/\/ A[n-1] = m_{n-1} * lpv[n-1] + lis[n-1]\n \/\/\/\n \/\/\/ Find all m_{n-1} such that A[n-1] is in the set I_{n-1}\n \/\/\/ (hmmmm no)\n \/\/\/ ...\n\n\n \/\/\/=========================\n \/\/\/ Using only A[0] and A[1]\n\n \/\/\/ A[0] = m_0 * lpv[0] + lis[0] : GOAL : Find m_0\n\n \/\/\/ A[1] = m_1 * lpv[1] + lis[1]\n \/\/\/ lpv[0]*( m_1 * lpv[1] + lis[1] ) <= A[0] < lpv[0]*( m_1 * lpv[1] + lis[1] + 1 )\n \/\/\/\n \/\/\/ Find the set of intervals {I_1}\n\n\n\/\/\/ BELOW WAS INCOMPLETE TEST FOR 2 NODES NETWORKS\n \/\/\/ Return : m * Q + R\n auto getInteger = []( const uint64_t &m, const uint64_t &Q, const uint64_t &R ) -> uint64_t {\n return m * Q + R;\n };\n\n typedef std::vector<uint64_t> Interval;\n\n \/\/\/ Return interval of the form : [ m*n*k+m*a, m*n*k+m*a+m )\n auto getInterval = [](uint64_t &k, uint64_t &m, uint64_t &n, uint64_t &a ) -> Interval {\n return Interval { m*n*k+m*a,m*n*k+m*a+m };\n };\n\n auto insideInterval = [](uint64_t &n, Interval &interval) -> bool {\n return n>=interval[0] && n<=interval[1];\n };\n\n \/\/ List all the subintervals for logic_index and store the potential good values for logic index\n std::cout << \"\\n\\nList of all subintervals for logic index\\n\";\n std::vector<Interval> intervals; \/\/ needed just for debug\n std::vector<uint64_t> logicindexvalues;\n for ( uint64_t R = 0; R<data_->reorderings_; ++R ) {\n Interval interval = getInterval( R,\n data_ -> logic_place_values_[0],\n data_ -> logic_place_values_[1],\n logic_indices[1] );\n std::cout << \"[ \" << interval[0] << \", \" << interval[1] << \" ]\\n\";\n \/\/ intervals . push_back ( interval );\n \/\/\/ check for good values inside the interval\n uint64_t myvalue = getInteger(data_ -> logic_place_values_[0],\n R*data_ -> logic_place_values_[1]+logic_indices[1],\n logic_indices[0]);\n std::cout << \"value=\" << myvalue << \" \";\n if ( insideInterval(myvalue,interval) ) {\n std::cout << \"is good\\n\";\n logicindexvalues . push_back ( myvalue );\n } else {\n std::cout << \"is bad\\n\";\n }\n }\n \/\/ List all the subintervals for order_index and store the potential good values for order index\n std::vector<uint64_t> orderindexvalues;\n for ( uint64_t R = 0; R<data_->reorderings_; ++R ) {\n Interval interval = getInterval( R,\n data_ -> order_place_values_[0],\n data_ -> order_place_values_[1],\n order_indices[1] );\n std::cout << \"[ \" << interval[0] << \", \" << interval[1] << \" ]\\n\";\n \/\/ intervals . push_back ( interval );\n \/\/\/ check for good values inside the interval\n uint64_t myvalue = getInteger(data_ -> order_place_values_[0],\n R*data_ -> order_place_values_[1]+order_indices[1],\n order_indices[0]);\n std::cout << \"value=\" << myvalue << \" \";\n if ( insideInterval(myvalue,interval) ) {\n std::cout << \"is good\\n\";\n orderindexvalues . push_back ( myvalue );\n } else {\n std::cout << \"is bad\\n\";\n }\n }\n\n \/\/ Find which pair of logicindexvalues and orderindexvalues is correct\n for ( uint64_t L : logicindexvalues ) {\n for ( uint64_t O : orderindexvalues ) {\n uint64_t myindex = O * data_ -> fixedordersize_ + L;\n\n if ( myindex < size() ) {\n std::cout << \"Found a good pair (L,O)=( \" << L << \", \" << O << \" ) with index : \" << myindex << \"\\n\";\n }\n\n }\n }\n\n\n\n\/\/\/ END INCOMPLETE TEST 2 NODES NETWORK\n\n\n return 0;\n\n}\n\nINLINE_IF_HEADER_ONLY std::vector<uint64_t> ParameterGraph::\nadjacencies ( uint64_t index ) const {\n throw std::runtime_error ( \"Feature not implemented\" ); \/\/TODO\n}\n\nINLINE_IF_HEADER_ONLY Network const ParameterGraph::\nnetwork ( void ) const {\n return data_ -> network_;\n}\n\nINLINE_IF_HEADER_ONLY std::ostream& operator << ( std::ostream& stream, ParameterGraph const& pg ) {\n stream << \"(ParameterGraph: \"<< pg.size() << \" parameters, \"\n << pg.network().size() << \" nodes)\";\n return stream;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\nfixedordersize ( void ) const {\n return data_ -> fixedordersize_;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\nreorderings ( void ) const {\n return data_ -> reorderings_;\n}\n\nINLINE_IF_HEADER_ONLY uint64_t ParameterGraph::\n_factorial ( uint64_t m ) const {\n static const std::vector<uint64_t> table =\n { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};\n if ( m < 10 ) return table [ m ]; else return m * _factorial ( m - 1 );\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2009 Adenilson Cavalcanti <savagobr@yahoo.com>\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; by version 2 of the License or (at your\n * choice) 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#include \"gcalresource.h\"\n#include \"settings.h\"\n#include \"settingsadaptor.h\"\n\n#include <QtDBus\/QDBusConnection>\n#include <QDate>\n#include <kabc\/addressee.h>\n#include <kabc\/phonenumber.h>\n#include <kabc\/key.h>\n#include <kabc\/errorhandler.h>\n#include <kcal\/event.h>\n#include <kdatetime.h>\n#include <qstring.h>\n#include <KWindowSystem>\n#include <akonadi\/changerecorder.h>\n#include <akonadi\/itemfetchscope.h>\n#include <KUrl>\n\nextern \"C\" {\n#include <gcalendar.h>\n#include <gcal_status.h>\n}\n\nusing namespace Akonadi;\n\nGCalResource::GCalResource( const QString &id )\n\t: ResourceBase(id)\n{\n\tnew SettingsAdaptor( Settings::self() );\n\tQDBusConnection::sessionBus().registerObject(\n\t\tQLatin1String( \"\/Settings\" ), Settings::self(),\n\t\tQDBusConnection::ExportAdaptors );\n\n\tchangeRecorder()->itemFetchScope().fetchFullPayload();\n\n if (!(gcal = gcal_new(GCALENDAR)))\n\t\texit(1);\n gcal_set_store_xml(gcal, 1);\n all_events.length = 0;\n all_events.entries = NULL;\n}\n\nGCalResource::~GCalResource()\n{\n gcal_cleanup_events(&all_events);\n pending.clear();\n deleted.clear();\n}\n\nvoid GCalResource::retrieveTimestamp(QString ×tamp)\n{\n\ttimestamp = Settings::self()->timestamp();\n}\n\nvoid GCalResource::saveTimestamp(QString ×tamp)\n{\n Settings::self()->setTimestamp(timestamp);\n Settings::self()->writeConfig();\n}\n\n\nvoid GCalResource::retrieveCollections()\n{\n if(!authenticated) {\n\t\tkError() << \"No authentication for Google Calendar available\";\n const QString message = i18nc(\"@info: status\",\n\t\t\t\t\t \"Not yet authenticated for \"\n\t\t\t\t\t \"use of Google Calendar\");\n\n emit error(message);\n\n emit status(Broken, message);\n return;\n }\n\n Collection c;\n c.setParent(Collection::root());\n c.setRemoteId(\"google-calendar\");\n c.setName(name());\n\n QStringList mimeTypes;\n mimeTypes << \"text\/calendar\";\n c.setContentMimeTypes(mimeTypes);\n\n Collection::List list;\n list << c;\n collectionsRetrieved(list);\n}\n\nvoid GCalResource::retrieveItems( const Akonadi::Collection &collection )\n{\n Q_UNUSED(collection);\n Item::List items;\n int result;\n\tgcal_event_t event;\n\tQString timestamp;\n\tQByteArray t_byte;\n\n\tkError() << \"\\n............. retrieveItems ...........\\n\";\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google calendar available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t \"Not yet authenticated for\"\n\t\t\t\t\t \" use of Google calendar\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\t\/* Query by updated *\/\n\tretrieveTimestamp(timestamp);\n\tt_byte = timestamp.toLocal8Bit();\n\tif (t_byte.length() > TIMESTAMP_SIZE) {\n\t\t\/\/TODO: implement getUpdated\n\t\t\/\/result = getUpdated(t_byte.data());\n\t\treturn;\n\t}\n\tkError() << \"First retrieve\";\n\n\tif ((result = gcal_get_events(gcal, &all_events)))\n\t\texit(1);\n\n\t\/* GCalendar returns last updated entry as first element *\/\n\tevent = gcal_event_element(&all_events, 0);\n\tif (!event) {\n\t\tkError() << \"Failed to retrieve last updated event.\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t \"Failed getting last updated\"\n\t\t\t\t\t \" event\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\t\treturn;\n\n\t}\n\n\ttimestamp = gcal_event_get_updated(event);\n\tsaveTimestamp(timestamp);\n\n\t\/* Each google entry has a unique ID and edit_url *\/\n\tfor (size_t i = 0; i < all_events.length; ++i) {\n\t\tItem item(QLatin1String(\"text\/calendar\"));\n\t\tKCal::Event kevent;\n\t\tQString temp;\n\t\tevent = gcal_event_element(&all_events, i);\n\n\t\ttemp = gcal_event_get_title(event);\n\t\tkevent.setSummary(temp);\n\n\t\ttemp = gcal_event_get_where(event);\n\t\tkevent.setLocation(temp);\n\n\t\ttemp = gcal_event_get_status(event);\n\t\tKCal::Incidence::Status status;\n\t\tif (gcal_event_is_deleted(event))\n\t\t\tstatus = KCal::Incidence::StatusCanceled;\n\t\telse\n\t\t\tstatus = KCal::Incidence::StatusConfirmed;\n\t\tkevent.setStatus(status);\n\n\t\ttemp = gcal_event_get_content(event);\n\t\tkevent.setDescription(temp);\n\n\t\t\/* TODO: there must exit an easier way *\/\n\t\tQDate start, end;\n\t\ttemp = gcal_event_get_start(event);\n\t\tstart.fromString(temp, Qt::ISODate);\n\t\ttemp = gcal_event_get_end(event);\n\t\tend.fromString(temp, Qt::ISODate);\n\t\tKDateTime time_start(start), time_end(end);\n\t\tkevent.setDtStart(time_start);\n\t\tkevent.setDtEnd(time_end);\n\n\t}\n}\n\nbool GCalResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )\n{\n\tQ_UNUSED(parts);\n\tQ_UNUSED(item);\n\treturn true;\n}\n\nvoid GCalResource::aboutToQuit()\n{\n\t\/\/ TODO: any cleanup you need to do while there is still an active\n\t\/\/ event loop. The resource will terminate after this method returns\n}\n\nvoid GCalResource::doSetOnline(bool online)\n{\n\tQ_UNUSED(online);\n}\n\nint GCalResource::getUpdated(char *timestamp)\n{\n\tQ_UNUSED(timestamp);\n\n\treturn -1;\n}\n\nvoid GCalResource::configure( WId windowId )\n{\n\tQ_UNUSED(windowId);\n\n}\n\nvoid GCalResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )\n{\n\tQ_UNUSED(collection);\n\tQ_UNUSED(item);\n}\n\nvoid GCalResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts )\n{\n\tQ_UNUSED(parts);\n\tQ_UNUSED(item);\n}\n\nvoid GCalResource::itemRemoved( const Akonadi::Item &item )\n{\n\tQ_UNUSED(item);\n}\n\nAKONADI_RESOURCE_MAIN( GCalResource )\n\n#include \"gcalresource.moc\"\n<commit_msg>Removing unused function call.<commit_after>\/* Copyright (C) 2009 Adenilson Cavalcanti <savagobr@yahoo.com>\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; by version 2 of the License or (at your\n * choice) 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#include \"gcalresource.h\"\n#include \"settings.h\"\n#include \"settingsadaptor.h\"\n\n#include <QtDBus\/QDBusConnection>\n#include <QDate>\n#include <kabc\/addressee.h>\n#include <kabc\/phonenumber.h>\n#include <kabc\/key.h>\n#include <kabc\/errorhandler.h>\n#include <kcal\/event.h>\n#include <kdatetime.h>\n#include <qstring.h>\n#include <KWindowSystem>\n#include <akonadi\/changerecorder.h>\n#include <akonadi\/itemfetchscope.h>\n#include <KUrl>\n\nextern \"C\" {\n#include <gcalendar.h>\n#include <gcal_status.h>\n}\n\nusing namespace Akonadi;\n\nGCalResource::GCalResource( const QString &id )\n\t: ResourceBase(id)\n{\n\tnew SettingsAdaptor( Settings::self() );\n\tQDBusConnection::sessionBus().registerObject(\n\t\tQLatin1String( \"\/Settings\" ), Settings::self(),\n\t\tQDBusConnection::ExportAdaptors );\n\n\tchangeRecorder()->itemFetchScope().fetchFullPayload();\n\n if (!(gcal = gcal_new(GCALENDAR)))\n\t\texit(1);\n gcal_set_store_xml(gcal, 1);\n all_events.length = 0;\n all_events.entries = NULL;\n}\n\nGCalResource::~GCalResource()\n{\n gcal_cleanup_events(&all_events);\n pending.clear();\n deleted.clear();\n}\n\nvoid GCalResource::retrieveTimestamp(QString ×tamp)\n{\n\ttimestamp = Settings::self()->timestamp();\n}\n\nvoid GCalResource::saveTimestamp(QString ×tamp)\n{\n Settings::self()->setTimestamp(timestamp);\n Settings::self()->writeConfig();\n}\n\n\nvoid GCalResource::retrieveCollections()\n{\n if(!authenticated) {\n\t\tkError() << \"No authentication for Google Calendar available\";\n const QString message = i18nc(\"@info: status\",\n\t\t\t\t\t \"Not yet authenticated for \"\n\t\t\t\t\t \"use of Google Calendar\");\n\n emit error(message);\n\n emit status(Broken, message);\n return;\n }\n\n Collection c;\n c.setParent(Collection::root());\n c.setRemoteId(\"google-calendar\");\n c.setName(name());\n\n QStringList mimeTypes;\n mimeTypes << \"text\/calendar\";\n c.setContentMimeTypes(mimeTypes);\n\n Collection::List list;\n list << c;\n collectionsRetrieved(list);\n}\n\nvoid GCalResource::retrieveItems( const Akonadi::Collection &collection )\n{\n Q_UNUSED(collection);\n Item::List items;\n int result;\n\tgcal_event_t event;\n\tQString timestamp;\n\tQByteArray t_byte;\n\n\tkError() << \"\\n............. retrieveItems ...........\\n\";\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google calendar available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t \"Not yet authenticated for\"\n\t\t\t\t\t \" use of Google calendar\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\t\/* Query by updated *\/\n\tretrieveTimestamp(timestamp);\n\tt_byte = timestamp.toLocal8Bit();\n\tif (t_byte.length() > TIMESTAMP_SIZE) {\n\t\t\/\/TODO: implement getUpdated\n\t\t\/\/result = getUpdated(t_byte.data());\n\t\treturn;\n\t}\n\tkError() << \"First retrieve\";\n\n\tif ((result = gcal_get_events(gcal, &all_events)))\n\t\texit(1);\n\n\t\/* GCalendar returns last updated entry as first element *\/\n\tevent = gcal_event_element(&all_events, 0);\n\tif (!event) {\n\t\tkError() << \"Failed to retrieve last updated event.\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t \"Failed getting last updated\"\n\t\t\t\t\t \" event\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\t\treturn;\n\n\t}\n\n\ttimestamp = gcal_event_get_updated(event);\n\tsaveTimestamp(timestamp);\n\n\t\/* Each google entry has a unique ID and edit_url *\/\n\tfor (size_t i = 0; i < all_events.length; ++i) {\n\t\tItem item(QLatin1String(\"text\/calendar\"));\n\t\tKCal::Event kevent;\n\t\tQString temp;\n\t\tevent = gcal_event_element(&all_events, i);\n\n\t\ttemp = gcal_event_get_title(event);\n\t\tkevent.setSummary(temp);\n\n\t\ttemp = gcal_event_get_where(event);\n\t\tkevent.setLocation(temp);\n\n\t\tKCal::Incidence::Status status;\n\t\tif (gcal_event_is_deleted(event))\n\t\t\tstatus = KCal::Incidence::StatusCanceled;\n\t\telse\n\t\t\tstatus = KCal::Incidence::StatusConfirmed;\n\t\tkevent.setStatus(status);\n\n\t\ttemp = gcal_event_get_content(event);\n\t\tkevent.setDescription(temp);\n\n\t\t\/* TODO: there must exit an easier way *\/\n\t\tQDate start, end;\n\t\ttemp = gcal_event_get_start(event);\n\t\tstart.fromString(temp, Qt::ISODate);\n\t\ttemp = gcal_event_get_end(event);\n\t\tend.fromString(temp, Qt::ISODate);\n\t\tKDateTime time_start(start), time_end(end);\n\t\tkevent.setDtStart(time_start);\n\t\tkevent.setDtEnd(time_end);\n\n\t}\n}\n\nbool GCalResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )\n{\n\tQ_UNUSED(parts);\n\tQ_UNUSED(item);\n\treturn true;\n}\n\nvoid GCalResource::aboutToQuit()\n{\n\t\/\/ TODO: any cleanup you need to do while there is still an active\n\t\/\/ event loop. The resource will terminate after this method returns\n}\n\nvoid GCalResource::doSetOnline(bool online)\n{\n\tQ_UNUSED(online);\n}\n\nint GCalResource::getUpdated(char *timestamp)\n{\n\tQ_UNUSED(timestamp);\n\n\treturn -1;\n}\n\nvoid GCalResource::configure( WId windowId )\n{\n\tQ_UNUSED(windowId);\n\n}\n\nvoid GCalResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )\n{\n\tQ_UNUSED(collection);\n\tQ_UNUSED(item);\n}\n\nvoid GCalResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts )\n{\n\tQ_UNUSED(parts);\n\tQ_UNUSED(item);\n}\n\nvoid GCalResource::itemRemoved( const Akonadi::Item &item )\n{\n\tQ_UNUSED(item);\n}\n\nAKONADI_RESOURCE_MAIN( GCalResource )\n\n#include \"gcalresource.moc\"\n<|endoftext|>"} {"text":"<commit_before>#ifndef CLAMMBON_SORT_GENETIC_HPP\n#define CLAMMBON_SORT_GENETIC_HPP\n\n#include <algorithm>\n#include <iomanip> \/\/ std::setwのみ\n#include <random>\n#include <boost\/range\/algorithm.hpp>\n\nint constexpr PARENT_NUM = 10;\nint constexpr CHILDREN_NUM = 100;\n\nclass genetic\n{\nprivate:\n typedef std::vector<std::vector<std::vector<std::vector<direction_type<uint64_t>>>>> compared_type;\n \n\tstruct children_t { std::vector<int> children_gene; unsigned int assessment;};\/\/子供の遺伝子と評価値\n\tstd::vector<children_t> children_;\/\/子供の遺伝子と評価値の配列\n \n question_raw_data *data_;\n compared_type *comp_;\n\n \/\/ std::mt19937_64ほど高級なもの要る?\n mutable std::mt19937 mt_;\n \n void shuffle(std::vector<int>& arr) const\n {\n std::uniform_int_distribution<int> distribution(0, arr.size()-1);\n\n for(int i = 0; i < arr.size(); ++i)\n {\n int j = distribution(mt_);\n std::swap(arr[i], arr[j]);\n }\n }\n\n void shuffle_all()\n {\n for(auto it = children_.begin(); it != children_.end(); ++it)\n {\n shuffle(it->children_gene);\n }\n }\n\n unsigned int assess(std::vector<int> const& arr) const\n {\n auto const sepx = data_->split_num.first;\n auto const sepy = data_->split_num.second;\n\n unsigned int ass = 0;\n for(int i = 0; i < arr.size(); ++i)\n {\n if(i + 1 < arr.size())\n {\n if(arr[i] == arr[i + 1])\n {\n std::cout << \"!!!\" << arr[i] << arr[i + 1] << std::endl;\n }\n ass += (*comp_)[arr[i] \/ sepx][arr[i] % sepx][arr[i + 1] \/ sepx][arr[i + 1] % sepx].right;\n }\n if(i + sepy < arr.size())\n {\n if(arr[i] == arr[i + sepy])\n {\n std::cout << \"???\" << arr[i] << arr[i + sepy] << std::endl;\n }\n ass += (*comp_)[arr[i] \/ sepx][arr[i] % sepx][arr[i + sepy] \/ sepx][arr[i + sepy] % sepx].right;\n }\n }\n return ass;\n }\n\n void assess_all()\n {\n for(auto it = children_.begin(); it != children_.end(); ++it)\n {\n \/\/for(int i = 0; i < split_total; ++i)\n \/\/{\n \/\/ std::cout << it->children_gene[i] << \" - \";\n \/\/}\n it->assessment = assess(it->children_gene);\n\t\t \/\/std::cout << \" \" << it->assessment << std::endl;\n }\n }\n\n std::vector<std::vector<int>> select_parent(std::vector<int>& top10)\n {\n top10.assign(PARENT_NUM, 0);\n\n std::vector<int> childred_copy;\n childred_copy.reserve(children_.size());\n\n boost::transform(\n children_, std::back_inserter(childred_copy),\n [](children_t const& base){ return base.assessment; }\n );\n boost::sort(childred_copy);\n \/\/boost::for_each(childred_copy, [](int const base){ std::cout << base << std::endl; });\n\n for(int i=0; i<top10.size(); ++i)\n {\n for(int j=0; j<CHILDREN_NUM; ++j)\n {\n if(childred_copy.at(i) == children_[j].assessment)\n {\n top10[i] = j;\n }\n }\n }\n\n auto const split_total = data_->split_num.first * data_->split_num.second;\n std::vector<std::vector<int>> parent_gene(PARENT_NUM, std::vector<int>(split_total, 0));\n\n \/\/親遺伝子配列にいいやつTop10を突っ込む\n for(int i=0; i<top10.size(); ++i)\n {\n for(int j=0; j<split_total; ++j)\n {\n parent_gene[i][j] = children_[top10[i]].children_gene[j];\n }\n }\n\n std::cout << \"番号 \" << \"評価\" << std::endl;\n for(auto const& elem : top10)\n {\n std::cout << elem << \" \" << children_[elem].assessment << std::endl;\n }\n\n return parent_gene;\n }\n\n void cross_over(std::vector<std::vector<int>> const& parent_gene)\n {\n auto const split_width = data_->split_num.first;\n auto const split_height = data_->split_num.second;\n auto const split_total = split_width * split_height;\n\n std::uniform_int_distribution<int> parent_dist(0, PARENT_NUM - 1);\n std::uniform_int_distribution<int> mutate_dist(0, 4 - 1);\n std::uniform_int_distribution<int> split_dist(0, split_total - 1);\n\n for(int i=0; i<CHILDREN_NUM; i+=2)\n {\n auto const& pra1 = parent_gene[parent_dist(mt_)];\n auto const& pra2 = parent_gene[parent_dist(mt_)];\n auto & child1 = children_[i ].children_gene;\n auto & child2 = children_[i+1].children_gene;\n \n \/\/std::cout << \"par1 \";\n \/\/boost::for_each(pra1, [](int const elem){ std::cout << elem << \"*\"; });\n \/\/std::cout << std::endl;\n \/\/\n \/\/std::cout << \"par2 \";\n \/\/boost::for_each(pra2, [](int const elem){ std::cout << elem << \"*\"; });\n \/\/std::cout << std::endl;\n\n child1.assign(child1.size(), -1);\n child2.assign(child2.size(), -1);\n\n int select_gene = split_dist(mt_);\n \/\/std::cout << \" s\" << select_gene;\n while(child1[select_gene] != pra1[select_gene])\n {\n\t\t\t child1[select_gene] = pra1[select_gene];\n\t\t\t child2[select_gene] = pra2[select_gene];\n\n for(int i=0; i<split_total; ++i)\n {\n if(child2[select_gene] == pra1[i])\n {\n select_gene = i;\n }\n }\n \/\/std::cout << \" s\" << select_gene;\n }\n\n for(int i=0; i<split_total; ++i)\n {\n if(child1[i] == -1)\n {\n\t\t\t\t child1[i] = pra2[i];\n\t\t\t\t child2[i] = pra1[i];\n }\n }\n\n for(int n = parent_dist(mt_); n < 10; ++n) \/\/このループ数をいじらないと収束しなかったりすぐに収束してしまったり\n {\n if(mutate_dist(mt_) == 0) \/\/ここの確率で突然変異率を変化させる\n {\n int rand1 = split_dist(mt_);\n int rand2 = split_dist(mt_);\n std::swap(child1[rand1], child1[rand2]);\n \/\/std::cout << \"rand1\" << std::endl;\n }\n if(mutate_dist(mt_) == 0) \/\/ここの確率で突然変異率を変化させる\n {\n int rand1 = split_dist(mt_);\n int rand2 = split_dist(mt_);\n std::swap(child2[rand1], child2[rand2]);\n\t\t\t\t \/\/std::cout << \"rand2\" << std::endl;\n }\n }\n \n \/\/std::cout << std::endl;\n \/\/std::cout << \"chi1 \";\n \/\/boost::for_each(child1, [](int const elem){ std::cout << elem << \"+\"; });\n \/\/\n \/\/std::cout << std::endl;\n \/\/std::cout << \"chi2 \";\n \/\/boost::for_each(child2, [](int const elem){ std::cout << elem << \"+\"; });\n \/\/\n \/\/std::cout << std::endl;\n }\n }\n\npublic:\n \/\/ 泣きのポインタ渡し\n genetic(question_raw_data *data, compared_type *comp)\n : data_(data), comp_(comp)\n {\n \/\/メルセンヌ・ツイスタの初期化\n std::random_device rd;\n std::vector<std::uint_least64_t> random_seed(10);\n boost::generate(random_seed, std::ref(rd));\n mt_.seed(std::seed_seq(random_seed.cbegin(), random_seed.cend()));\n }\n virtual ~genetic() = default;\n\n int sort()\n {\n auto const split_total = data_->split_num.first * data_->split_num.second;\n\n \/\/ children_の初期化\n {\n \/\/連番リスト(0~split_total-1)の作製\n std::vector<int> tmp_vector;\n tmp_vector.reserve(split_total); \n for(int i = 0; i < split_total; ++i) tmp_vector.push_back(i);\n\n \/\/連番リストでchildren_を初期化\n children_.assign(CHILDREN_NUM, {tmp_vector, 0});\n }\n\n shuffle_all();\n assess_all();\n \n int top;\n std::vector<int> top10(PARENT_NUM);\n std::vector<int> toppers(1000);\n for(int i = 0; i < toppers.size(); ++i)\n {\n for(int j = 0; j < 10000; ++j)\n {\n auto const parent_gene = select_parent(top10);\n top = children_.at(top10[0]).assessment;\n\n cross_over(parent_gene);\n assess_all();\n \n\t\t\t std::cout << \"最上位遺伝子\";\n\t\t\t for (int i = 0; i < split_total; i++)\n {\n\t\t\t\t std::cout << std::setw(3) << parent_gene[0][i]; \/\/unspecified(std::setw)\n\t\t\t }\n \n std::cout << \"番号\" << top10[0] << std::endl;\n\n int const base = top10[0]; \/\/ VCのための苦肉の策\n if(\n std::all_of(\n top10.begin(), top10.end(),\n [base](int const elem){ return base == elem; }\n \/\/[base = top10[0]](int const elem){ return base == elem; }\n )\n )\n {\n \/\/Top10の遺伝子がすべて同じものになったら収束したと判断する\n break;\n }\n std::cout << \"世代=\" << j << \"ループ\" << i << std::endl;\n\n }\n toppers[i] = top;\n\n shuffle_all();\n }\n\n \n\t int toptop = std::numeric_limits<int>::max();\n\t int topnum = 0;\n\t for(auto const elem : toppers)\n {\n if(elem < toptop)\n {\n toptop = elem;\n topnum = 0;\n }\n else if(elem == toptop)\n {\n ++topnum;\n }\n\t\t std::cout << elem << std::endl;\n }\n\t std::cout << \"最適値\" << toptop << \"数\" << topnum << std::endl;\n }\n\n};\n\n#endif\n<commit_msg>g++\/clangに対応<commit_after>#ifndef CLAMMBON_SORT_GENETIC_HPP\n#define CLAMMBON_SORT_GENETIC_HPP\n\n#include <iostream>\n#include <algorithm>\n#include <functional>\n#include <iomanip> \/\/ std::setwのみ\n#include <random>\n#include <boost\/range\/algorithm.hpp>\n\nint constexpr PARENT_NUM = 10;\nint constexpr CHILDREN_NUM = 100;\n\nclass genetic\n{\nprivate:\n typedef std::vector<std::vector<std::vector<std::vector<direction_type<uint64_t>>>>> compared_type;\n \n\tstruct children_t { std::vector<int> children_gene; unsigned int assessment;};\/\/子供の遺伝子と評価値\n\tstd::vector<children_t> children_;\/\/子供の遺伝子と評価値の配列\n \n question_raw_data *data_;\n compared_type *comp_;\n\n \/\/ std::mt19937_64ほど高級なもの要る?\n mutable std::mt19937 mt_;\n \n void shuffle(std::vector<int>& arr) const\n {\n std::uniform_int_distribution<int> distribution(0, arr.size()-1);\n\n for(int i = 0; i < arr.size(); ++i)\n {\n int j = distribution(mt_);\n std::swap(arr[i], arr[j]);\n }\n }\n\n void shuffle_all()\n {\n for(auto it = children_.begin(); it != children_.end(); ++it)\n {\n shuffle(it->children_gene);\n }\n }\n\n unsigned int assess(std::vector<int> const& arr) const\n {\n auto const sepx = data_->split_num.first;\n auto const sepy = data_->split_num.second;\n\n unsigned int ass = 0;\n for(int i = 0; i < arr.size(); ++i)\n {\n if(i + 1 < arr.size())\n {\n if(arr[i] == arr[i + 1])\n {\n std::cout << \"!!!\" << arr[i] << arr[i + 1] << std::endl;\n }\n ass += (*comp_)[arr[i] \/ sepx][arr[i] % sepx][arr[i + 1] \/ sepx][arr[i + 1] % sepx].right;\n }\n if(i + sepy < arr.size())\n {\n if(arr[i] == arr[i + sepy])\n {\n std::cout << \"???\" << arr[i] << arr[i + sepy] << std::endl;\n }\n ass += (*comp_)[arr[i] \/ sepx][arr[i] % sepx][arr[i + sepy] \/ sepx][arr[i + sepy] % sepx].right;\n }\n }\n return ass;\n }\n\n void assess_all()\n {\n for(auto it = children_.begin(); it != children_.end(); ++it)\n {\n \/\/for(int i = 0; i < split_total; ++i)\n \/\/{\n \/\/ std::cout << it->children_gene[i] << \" - \";\n \/\/}\n it->assessment = assess(it->children_gene);\n\t\t \/\/std::cout << \" \" << it->assessment << std::endl;\n }\n }\n\n std::vector<std::vector<int>> select_parent(std::vector<int>& top10)\n {\n top10.assign(PARENT_NUM, 0);\n\n std::vector<int> childred_copy;\n childred_copy.reserve(children_.size());\n\n boost::transform(\n children_, std::back_inserter(childred_copy),\n [](children_t const& base){ return base.assessment; }\n );\n boost::sort(childred_copy);\n \/\/boost::for_each(childred_copy, [](int const base){ std::cout << base << std::endl; });\n\n for(int i=0; i<top10.size(); ++i)\n {\n for(int j=0; j<CHILDREN_NUM; ++j)\n {\n if(childred_copy.at(i) == children_[j].assessment)\n {\n top10[i] = j;\n }\n }\n }\n\n auto const split_total = data_->split_num.first * data_->split_num.second;\n std::vector<std::vector<int>> parent_gene(PARENT_NUM, std::vector<int>(split_total, 0));\n\n \/\/親遺伝子配列にいいやつTop10を突っ込む\n for(int i=0; i<top10.size(); ++i)\n {\n for(int j=0; j<split_total; ++j)\n {\n parent_gene[i][j] = children_[top10[i]].children_gene[j];\n }\n }\n\n std::cout << \"番号 \" << \"評価\" << std::endl;\n for(auto const& elem : top10)\n {\n std::cout << elem << \" \" << children_[elem].assessment << std::endl;\n }\n\n return parent_gene;\n }\n\n void cross_over(std::vector<std::vector<int>> const& parent_gene)\n {\n auto const split_width = data_->split_num.first;\n auto const split_height = data_->split_num.second;\n auto const split_total = split_width * split_height;\n\n std::uniform_int_distribution<int> parent_dist(0, PARENT_NUM - 1);\n std::uniform_int_distribution<int> mutate_dist(0, 4 - 1);\n std::uniform_int_distribution<int> split_dist(0, split_total - 1);\n\n for(int i=0; i<CHILDREN_NUM; i+=2)\n {\n auto const& pra1 = parent_gene[parent_dist(mt_)];\n auto const& pra2 = parent_gene[parent_dist(mt_)];\n auto & child1 = children_[i ].children_gene;\n auto & child2 = children_[i+1].children_gene;\n \n \/\/std::cout << \"par1 \";\n \/\/boost::for_each(pra1, [](int const elem){ std::cout << elem << \"*\"; });\n \/\/std::cout << std::endl;\n \/\/\n \/\/std::cout << \"par2 \";\n \/\/boost::for_each(pra2, [](int const elem){ std::cout << elem << \"*\"; });\n \/\/std::cout << std::endl;\n\n child1.assign(child1.size(), -1);\n child2.assign(child2.size(), -1);\n\n int select_gene = split_dist(mt_);\n \/\/std::cout << \" s\" << select_gene;\n while(child1[select_gene] != pra1[select_gene])\n {\n\t\t\t child1[select_gene] = pra1[select_gene];\n\t\t\t child2[select_gene] = pra2[select_gene];\n\n for(int i=0; i<split_total; ++i)\n {\n if(child2[select_gene] == pra1[i])\n {\n select_gene = i;\n }\n }\n \/\/std::cout << \" s\" << select_gene;\n }\n\n for(int i=0; i<split_total; ++i)\n {\n if(child1[i] == -1)\n {\n\t\t\t\t child1[i] = pra2[i];\n\t\t\t\t child2[i] = pra1[i];\n }\n }\n\n for(int n = parent_dist(mt_); n < 10; ++n) \/\/このループ数をいじらないと収束しなかったりすぐに収束してしまったり\n {\n if(mutate_dist(mt_) == 0) \/\/ここの確率で突然変異率を変化させる\n {\n int rand1 = split_dist(mt_);\n int rand2 = split_dist(mt_);\n std::swap(child1[rand1], child1[rand2]);\n \/\/std::cout << \"rand1\" << std::endl;\n }\n if(mutate_dist(mt_) == 0) \/\/ここの確率で突然変異率を変化させる\n {\n int rand1 = split_dist(mt_);\n int rand2 = split_dist(mt_);\n std::swap(child2[rand1], child2[rand2]);\n\t\t\t\t \/\/std::cout << \"rand2\" << std::endl;\n }\n }\n \n \/\/std::cout << std::endl;\n \/\/std::cout << \"chi1 \";\n \/\/boost::for_each(child1, [](int const elem){ std::cout << elem << \"+\"; });\n \/\/\n \/\/std::cout << std::endl;\n \/\/std::cout << \"chi2 \";\n \/\/boost::for_each(child2, [](int const elem){ std::cout << elem << \"+\"; });\n \/\/\n \/\/std::cout << std::endl;\n }\n }\n\npublic:\n \/\/ 泣きのポインタ渡し\n genetic(question_raw_data *data, compared_type *comp)\n : data_(data), comp_(comp)\n {\n \/\/メルセンヌ・ツイスタの初期化\n std::random_device rd;\n std::vector<std::uint_least64_t> random_seed(10);\n boost::generate(random_seed, std::ref(rd));\n\n std::seed_seq seed(random_seed.cbegin(), random_seed.cend());\n mt_.seed(seed);\n }\n virtual ~genetic() = default;\n\n int sort()\n {\n auto const split_total = data_->split_num.first * data_->split_num.second;\n\n \/\/ children_の初期化\n {\n \/\/連番リスト(0~split_total-1)の作製\n std::vector<int> tmp_vector;\n tmp_vector.reserve(split_total); \n for(int i = 0; i < split_total; ++i) tmp_vector.push_back(i);\n\n \/\/連番リストでchildren_を初期化\n children_.assign(CHILDREN_NUM, {tmp_vector, 0});\n }\n\n shuffle_all();\n assess_all();\n \n int top;\n std::vector<int> top10(PARENT_NUM);\n std::vector<int> toppers(1000);\n for(int i = 0; i < toppers.size(); ++i)\n {\n for(int j = 0; j < 10000; ++j)\n {\n auto const parent_gene = select_parent(top10);\n top = children_.at(top10[0]).assessment;\n\n cross_over(parent_gene);\n assess_all();\n \n\t\t\t std::cout << \"最上位遺伝子\";\n\t\t\t for (int i = 0; i < split_total; i++)\n {\n\t\t\t\t std::cout << std::setw(3) << parent_gene[0][i]; \/\/unspecified(std::setw)\n\t\t\t }\n \n std::cout << \"番号\" << top10[0] << std::endl;\n\n int const base = top10[0]; \/\/ VCのための苦肉の策\n if(\n std::all_of(\n top10.begin(), top10.end(),\n [base](int const elem){ return base == elem; }\n \/\/[base = top10[0]](int const elem){ return base == elem; }\n )\n )\n {\n \/\/Top10の遺伝子がすべて同じものになったら収束したと判断する\n break;\n }\n std::cout << \"世代=\" << j << \"ループ\" << i << std::endl;\n\n }\n toppers[i] = top;\n\n shuffle_all();\n }\n\n \n\t int toptop = std::numeric_limits<int>::max();\n\t int topnum = 0;\n\t for(auto const elem : toppers)\n {\n if(elem < toptop)\n {\n toptop = elem;\n topnum = 0;\n }\n else if(elem == toptop)\n {\n ++topnum;\n }\n\t\t std::cout << elem << std::endl;\n }\n\t std::cout << \"最適値\" << toptop << \"数\" << topnum << std::endl;\n }\n\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief SortedIntrusiveList template class header\n *\n * \\author Copyright (C) 2015 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2015-12-20\n *\/\n\n#ifndef ESTD_SORTEDINTRUSIVELIST_HPP_\n#define ESTD_SORTEDINTRUSIVELIST_HPP_\n\n#include \"estd\/IntrusiveList.hpp\"\n\n#include <algorithm>\n\nnamespace estd\n{\n\n\/**\n * \\brief SortedIntrusiveList class is an IntrusiveList with sorted elements\n *\n * This class tries to provide an interface similar to std::list.\n *\n * \\note The elements are sorted as long as the user does not modify the contents.\n *\n * \\tparam Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in\n * ascending order\n * \\tparam T is the type that has the IntrusiveListNode variable\n * \\tparam NodePointer is a pointer-to-member to IntrusiveListNode variable in \\a T\n * \\tparam U is the type that will be stored on the list; it can be different from \\a T, but must be implicitly\n * convertible to \\a T (so usually a type derived from \\a T); default - \\a T; using different type than \\a T can be used\n * to break circular dependencies, because \\a T must be fully defined to instantiate this class, but it is enough to\n * forward declare \\a U - it only needs to be fully defined to use member functions\n *\/\n\ntemplate<typename Compare, typename T, IntrusiveListNode T::* NodePointer, typename U = T>\nclass SortedIntrusiveList\n{\npublic:\n\n\t\/\/\/ unsorted intrusive list used internally\n\tusing UnsortedIntrusiveList = IntrusiveList<T, NodePointer, U>;\n\n\t\/\/\/ const iterator of elements on the list\n\tusing const_iterator = typename UnsortedIntrusiveList::const_iterator;\n\n\t\/\/\/ const reverse iterator of elements on the list\n\tusing const_reverse_iterator = typename UnsortedIntrusiveList::const_reverse_iterator;\n\n\t\/\/\/ const pointer to value linked in the list\n\tusing const_pointer = typename UnsortedIntrusiveList::const_pointer;\n\n\t\/\/\/ const reference to value linked in the list\n\tusing const_reference = typename UnsortedIntrusiveList::const_reference;\n\n\t\/\/\/ iterator of elements on the list\n\tusing iterator = typename UnsortedIntrusiveList::iterator;\n\n\t\/\/\/ reverse iterator of elements on the list\n\tusing reverse_iterator = typename UnsortedIntrusiveList::reverse_iterator;\n\n\t\/\/\/ pointer to value linked in the list\n\tusing pointer = typename UnsortedIntrusiveList::pointer;\n\n\t\/\/\/ reference to value linked in the list\n\tusing reference = typename UnsortedIntrusiveList::reference;\n\n\t\/\/\/ value linked in the list\n\tusing value_type = typename UnsortedIntrusiveList::value_type;\n\n\t\/**\n\t * \\brief SortedIntrusiveList's constructor\n\t *\n\t * \\param [in] compare is a reference to Compare object used to copy-construct internal comparison functor\n\t *\/\n\n\tconstexpr SortedIntrusiveList(const Compare& compare = Compare{}) :\n\t\t\timplementation_{compare}\n\t{\n\n\t}\n\n\t\/**\n\t * \\return reference to last element on the list\n\t *\/\n\n\treference back()\n\t{\n\t\treturn implementation_.intrusiveList.back();\n\t}\n\n\t\/**\n\t * \\return const reference to last element on the list\n\t *\/\n\n\tconst_reference back() const\n\t{\n\t\treturn implementation_.intrusiveList.back();\n\t}\n\n\t\/**\n\t * \\return iterator of first element on the list\n\t *\/\n\n\titerator begin()\n\t{\n\t\treturn implementation_.intrusiveList.begin();\n\t}\n\n\t\/**\n\t * \\return const iterator of first element on the list\n\t *\/\n\n\tconst_iterator begin() const\n\t{\n\t\treturn implementation_.intrusiveList.begin();\n\t}\n\n\t\/**\n\t * \\return const iterator of first element on the list\n\t *\/\n\n\tconst_iterator cbegin() const\n\t{\n\t\treturn implementation_.intrusiveList.cbegin();\n\t}\n\n\t\/**\n\t * \\return const iterator of \"one past the last\" element on the list\n\t *\/\n\n\tconst_iterator cend() const\n\t{\n\t\treturn implementation_.intrusiveList.cend();\n\t}\n\n\t\/**\n\t * \\brief Unlinks all elements from the list.\n\t *\/\n\n\tvoid clear()\n\t{\n\t\timplementation_.intrusiveList.clear();\n\t}\n\n\t\/**\n\t * \\return true is the list is empty, false otherwise\n\t *\/\n\n\tbool empty() const\n\t{\n\t\treturn implementation_.intrusiveList.empty();\n\t}\n\n\t\/**\n\t * \\return iterator of \"one past the last\" element on the list\n\t *\/\n\n\titerator end()\n\t{\n\t\treturn implementation_.intrusiveList.end();\n\t}\n\n\t\/**\n\t * \\return const iterator of \"one past the last\" element on the list\n\t *\/\n\n\tconst_iterator end() const\n\t{\n\t\treturn implementation_.intrusiveList.end();\n\t}\n\n\t\/**\n\t * \\return reference to first element on the list\n\t *\/\n\n\treference front()\n\t{\n\t\treturn implementation_.intrusiveList.front();\n\t}\n\n\t\/**\n\t * \\return const reference to first element on the list\n\t *\/\n\n\tconst_reference front() const\n\t{\n\t\treturn implementation_.intrusiveList.front();\n\t}\n\n\t\/**\n\t * \\brief Links the element in the list, keeping it sorted.\n\t *\n\t * \\param [in] newElement is a reference to the element that will be linked in the list\n\t *\n\t * \\return iterator of \\a newElement\n\t *\/\n\n\titerator insert(reference newElement)\n\t{\n\t\treturn UnsortedIntrusiveList::insert(implementation_.findInsertPosition(newElement), newElement);\n\t}\n\n\t\/**\n\t * \\brief Unlinks the last element from the list.\n\t *\/\n\n\tvoid pop_back()\n\t{\n\t\timplementation_.intrusiveList.pop_back();\n\t}\n\n\t\/**\n\t * \\brief Unlinks the first element from the list.\n\t *\/\n\n\tvoid pop_front()\n\t{\n\t\timplementation_.intrusiveList.pop_front();\n\t}\n\n\t\/**\n\t * \\brief Transfers the element from another list to this one, keeping it sorted.\n\t *\n\t * \\param [in] splicedElement is an iterator of the element that will be spliced from another list to this one\n\t *\/\n\n\tvoid splice(const iterator splicedElement)\n\t{\n\t\tUnsortedIntrusiveList::splice(implementation_.findInsertPosition(*splicedElement), splicedElement);\n\t}\n\n\t\/**\n\t * \\brief Swaps contents with another list.\n\t *\n\t * \\param [in] other is a reference to SortedIntrusiveList with which contents of this list will be swapped\n\t *\/\n\n\tvoid swap(SortedIntrusiveList& other)\n\t{\n\t\tstd::swap(implementation_, other.implementation_);\n\t}\n\n\t\/**\n\t * \\brief Unlinks the element at \\a position from the list.\n\t *\n\t * \\note No instance of the list is needed for this operation.\n\t *\n\t * \\param [in] position is an iterator of the element that will be unlinked from the list\n\t *\n\t * \\return iterator of the element that was following the element which was unlinked\n\t *\/\n\n\tstatic iterator erase(const iterator position)\n\t{\n\t\treturn UnsortedIntrusiveList::erase(position);\n\t}\n\nprivate:\n\n\t\/\/\/ Implementation struct is used primarily for \"Empty Base Optimization\" with \\a Compare type\n\tstruct Implementation : public Compare\n\t{\n\t\t\/**\n\t\t * \\brief Implementation's constructor\n\t\t *\n\t\t * \\param [in] comparee is a reference to Compare object used to copy-construct internal comparison functor\n\t\t *\/\n\n\t\tconstexpr Implementation(const Compare& comparee) :\n\t\t\t\tCompare{comparee},\n\t\t\t\tintrusiveList{}\n\t\t{\n\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Finds insert position that satisfies sorting criteria.\n\t\t *\n\t\t * \\param [in] newElement is a const reference to new element that is going to be inserted\/spliced\n\t\t *\n\t\t * \\return iterator for which Compare's function call operator of dereferenced value and \\a newElement returns\n\t\t * true.\n\t\t *\/\n\n\t\titerator findInsertPosition(const_reference newElement)\n\t\t{\n\t\t\treturn std::find_if(intrusiveList.begin(), intrusiveList.end(),\n\t\t\t\t\t[this, &newElement](const_reference& element) -> bool\n\t\t\t\t\t{\n\t\t\t\t\t\treturn this->Compare::operator()(element, newElement);\n\t\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\t\/\/\/ internal unsorted IntrusiveList\n\t\tUnsortedIntrusiveList intrusiveList;\n\t};\n\n\t\/\/\/ internal Implementation object - unsorted IntrusiveList and Compare instance\n\tImplementation implementation_;\n};\n\n\/**\n * \\brief Swaps contents of two lists.\n *\n * \\tparam Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in\n * ascending order\n * \\tparam T is the type that has the IntrusiveListNode variable\n * \\tparam NodePointer is a pointer-to-member to IntrusiveListNode variable in \\a T\n * \\tparam U is the type that will be stored on the list; it can be different from \\a T, but must be implicitly\n * convertible to \\a T (so usually a type derived from \\a T); default - \\a T;\n *\n * \\param [in] left is a reference to SortedIntrusiveList with which contents of \\a right will be swapped\n * \\param [in] right is a reference to SortedIntrusiveList with which contents of \\a left will be swapped\n *\/\n\ntemplate<typename Compare, typename T, IntrusiveListNode T::* NodePointer, typename U = T>\ninline void swap(SortedIntrusiveList<Compare, T, NodePointer, U>& left,\n\t\tSortedIntrusiveList<Compare, T, NodePointer, U>& right)\n{\n\tleft.swap(right);\n}\n\n}\t\/\/ namespace estd\n\n#endif\t\/\/ ESTD_SORTEDINTRUSIVELIST_HPP_\n<commit_msg>SortedIntrusiveList: fix swap() function<commit_after>\/**\n * \\file\n * \\brief SortedIntrusiveList template class header\n *\n * \\author Copyright (C) 2015 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2015-12-23\n *\/\n\n#ifndef ESTD_SORTEDINTRUSIVELIST_HPP_\n#define ESTD_SORTEDINTRUSIVELIST_HPP_\n\n#include \"estd\/IntrusiveList.hpp\"\n\n#include <algorithm>\n\nnamespace estd\n{\n\n\/**\n * \\brief SortedIntrusiveList class is an IntrusiveList with sorted elements\n *\n * This class tries to provide an interface similar to std::list.\n *\n * \\note The elements are sorted as long as the user does not modify the contents.\n *\n * \\tparam Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in\n * ascending order\n * \\tparam T is the type that has the IntrusiveListNode variable\n * \\tparam NodePointer is a pointer-to-member to IntrusiveListNode variable in \\a T\n * \\tparam U is the type that will be stored on the list; it can be different from \\a T, but must be implicitly\n * convertible to \\a T (so usually a type derived from \\a T); default - \\a T; using different type than \\a T can be used\n * to break circular dependencies, because \\a T must be fully defined to instantiate this class, but it is enough to\n * forward declare \\a U - it only needs to be fully defined to use member functions\n *\/\n\ntemplate<typename Compare, typename T, IntrusiveListNode T::* NodePointer, typename U = T>\nclass SortedIntrusiveList\n{\npublic:\n\n\t\/\/\/ unsorted intrusive list used internally\n\tusing UnsortedIntrusiveList = IntrusiveList<T, NodePointer, U>;\n\n\t\/\/\/ const iterator of elements on the list\n\tusing const_iterator = typename UnsortedIntrusiveList::const_iterator;\n\n\t\/\/\/ const reverse iterator of elements on the list\n\tusing const_reverse_iterator = typename UnsortedIntrusiveList::const_reverse_iterator;\n\n\t\/\/\/ const pointer to value linked in the list\n\tusing const_pointer = typename UnsortedIntrusiveList::const_pointer;\n\n\t\/\/\/ const reference to value linked in the list\n\tusing const_reference = typename UnsortedIntrusiveList::const_reference;\n\n\t\/\/\/ iterator of elements on the list\n\tusing iterator = typename UnsortedIntrusiveList::iterator;\n\n\t\/\/\/ reverse iterator of elements on the list\n\tusing reverse_iterator = typename UnsortedIntrusiveList::reverse_iterator;\n\n\t\/\/\/ pointer to value linked in the list\n\tusing pointer = typename UnsortedIntrusiveList::pointer;\n\n\t\/\/\/ reference to value linked in the list\n\tusing reference = typename UnsortedIntrusiveList::reference;\n\n\t\/\/\/ value linked in the list\n\tusing value_type = typename UnsortedIntrusiveList::value_type;\n\n\t\/**\n\t * \\brief SortedIntrusiveList's constructor\n\t *\n\t * \\param [in] compare is a reference to Compare object used to copy-construct internal comparison functor\n\t *\/\n\n\tconstexpr SortedIntrusiveList(const Compare& compare = Compare{}) :\n\t\t\timplementation_{compare}\n\t{\n\n\t}\n\n\t\/**\n\t * \\return reference to last element on the list\n\t *\/\n\n\treference back()\n\t{\n\t\treturn implementation_.intrusiveList.back();\n\t}\n\n\t\/**\n\t * \\return const reference to last element on the list\n\t *\/\n\n\tconst_reference back() const\n\t{\n\t\treturn implementation_.intrusiveList.back();\n\t}\n\n\t\/**\n\t * \\return iterator of first element on the list\n\t *\/\n\n\titerator begin()\n\t{\n\t\treturn implementation_.intrusiveList.begin();\n\t}\n\n\t\/**\n\t * \\return const iterator of first element on the list\n\t *\/\n\n\tconst_iterator begin() const\n\t{\n\t\treturn implementation_.intrusiveList.begin();\n\t}\n\n\t\/**\n\t * \\return const iterator of first element on the list\n\t *\/\n\n\tconst_iterator cbegin() const\n\t{\n\t\treturn implementation_.intrusiveList.cbegin();\n\t}\n\n\t\/**\n\t * \\return const iterator of \"one past the last\" element on the list\n\t *\/\n\n\tconst_iterator cend() const\n\t{\n\t\treturn implementation_.intrusiveList.cend();\n\t}\n\n\t\/**\n\t * \\brief Unlinks all elements from the list.\n\t *\/\n\n\tvoid clear()\n\t{\n\t\timplementation_.intrusiveList.clear();\n\t}\n\n\t\/**\n\t * \\return true is the list is empty, false otherwise\n\t *\/\n\n\tbool empty() const\n\t{\n\t\treturn implementation_.intrusiveList.empty();\n\t}\n\n\t\/**\n\t * \\return iterator of \"one past the last\" element on the list\n\t *\/\n\n\titerator end()\n\t{\n\t\treturn implementation_.intrusiveList.end();\n\t}\n\n\t\/**\n\t * \\return const iterator of \"one past the last\" element on the list\n\t *\/\n\n\tconst_iterator end() const\n\t{\n\t\treturn implementation_.intrusiveList.end();\n\t}\n\n\t\/**\n\t * \\return reference to first element on the list\n\t *\/\n\n\treference front()\n\t{\n\t\treturn implementation_.intrusiveList.front();\n\t}\n\n\t\/**\n\t * \\return const reference to first element on the list\n\t *\/\n\n\tconst_reference front() const\n\t{\n\t\treturn implementation_.intrusiveList.front();\n\t}\n\n\t\/**\n\t * \\brief Links the element in the list, keeping it sorted.\n\t *\n\t * \\param [in] newElement is a reference to the element that will be linked in the list\n\t *\n\t * \\return iterator of \\a newElement\n\t *\/\n\n\titerator insert(reference newElement)\n\t{\n\t\treturn UnsortedIntrusiveList::insert(implementation_.findInsertPosition(newElement), newElement);\n\t}\n\n\t\/**\n\t * \\brief Unlinks the last element from the list.\n\t *\/\n\n\tvoid pop_back()\n\t{\n\t\timplementation_.intrusiveList.pop_back();\n\t}\n\n\t\/**\n\t * \\brief Unlinks the first element from the list.\n\t *\/\n\n\tvoid pop_front()\n\t{\n\t\timplementation_.intrusiveList.pop_front();\n\t}\n\n\t\/**\n\t * \\brief Transfers the element from another list to this one, keeping it sorted.\n\t *\n\t * \\param [in] splicedElement is an iterator of the element that will be spliced from another list to this one\n\t *\/\n\n\tvoid splice(const iterator splicedElement)\n\t{\n\t\tUnsortedIntrusiveList::splice(implementation_.findInsertPosition(*splicedElement), splicedElement);\n\t}\n\n\t\/**\n\t * \\brief Swaps contents with another list.\n\t *\n\t * \\param [in] other is a reference to SortedIntrusiveList with which contents of this list will be swapped\n\t *\/\n\n\tvoid swap(SortedIntrusiveList& other)\n\t{\n\t\timplementation_.swap(other.implementation_);\n\t}\n\n\t\/**\n\t * \\brief Unlinks the element at \\a position from the list.\n\t *\n\t * \\note No instance of the list is needed for this operation.\n\t *\n\t * \\param [in] position is an iterator of the element that will be unlinked from the list\n\t *\n\t * \\return iterator of the element that was following the element which was unlinked\n\t *\/\n\n\tstatic iterator erase(const iterator position)\n\t{\n\t\treturn UnsortedIntrusiveList::erase(position);\n\t}\n\nprivate:\n\n\t\/\/\/ Implementation struct is used primarily for \"Empty Base Optimization\" with \\a Compare type\n\tstruct Implementation : public Compare\n\t{\n\t\t\/**\n\t\t * \\brief Implementation's constructor\n\t\t *\n\t\t * \\param [in] comparee is a reference to Compare object used to copy-construct internal comparison functor\n\t\t *\/\n\n\t\tconstexpr Implementation(const Compare& comparee) :\n\t\t\t\tCompare{comparee},\n\t\t\t\tintrusiveList{}\n\t\t{\n\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Finds insert position that satisfies sorting criteria.\n\t\t *\n\t\t * \\param [in] newElement is a const reference to new element that is going to be inserted\/spliced\n\t\t *\n\t\t * \\return iterator for which Compare's function call operator of dereferenced value and \\a newElement returns\n\t\t * true.\n\t\t *\/\n\n\t\titerator findInsertPosition(const_reference newElement)\n\t\t{\n\t\t\treturn std::find_if(intrusiveList.begin(), intrusiveList.end(),\n\t\t\t\t\t[this, &newElement](const_reference& element) -> bool\n\t\t\t\t\t{\n\t\t\t\t\t\treturn this->Compare::operator()(element, newElement);\n\t\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Swaps contents with another instance.\n\t\t *\n\t\t * \\param [in] other is a reference to Implementation with which contents of this instance will be swapped\n\t\t *\/\n\n\t\tvoid swap(Implementation& other)\n\t\t{\n\t\t\tintrusiveList.swap(other.intrusiveList);\n\t\t\tusing std::swap;\n\t\t\tswap(static_cast<Compare&>(*this), static_cast<Compare&>(other));\n\t\t}\n\n\t\t\/\/\/ internal unsorted IntrusiveList\n\t\tUnsortedIntrusiveList intrusiveList;\n\t};\n\n\t\/\/\/ internal Implementation object - unsorted IntrusiveList and Compare instance\n\tImplementation implementation_;\n};\n\n\/**\n * \\brief Swaps contents of two lists.\n *\n * \\tparam Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in\n * ascending order\n * \\tparam T is the type that has the IntrusiveListNode variable\n * \\tparam NodePointer is a pointer-to-member to IntrusiveListNode variable in \\a T\n * \\tparam U is the type that will be stored on the list; it can be different from \\a T, but must be implicitly\n * convertible to \\a T (so usually a type derived from \\a T); default - \\a T;\n *\n * \\param [in] left is a reference to SortedIntrusiveList with which contents of \\a right will be swapped\n * \\param [in] right is a reference to SortedIntrusiveList with which contents of \\a left will be swapped\n *\/\n\ntemplate<typename Compare, typename T, IntrusiveListNode T::* NodePointer, typename U = T>\ninline void swap(SortedIntrusiveList<Compare, T, NodePointer, U>& left,\n\t\tSortedIntrusiveList<Compare, T, NodePointer, U>& right)\n{\n\tleft.swap(right);\n}\n\n}\t\/\/ namespace estd\n\n#endif\t\/\/ ESTD_SORTEDINTRUSIVELIST_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Open Source Robotics 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#ifndef __IGN_TRANSPORT_PACKET_HH_INCLUDED__\n#define __IGN_TRANSPORT_PACKET_HH_INCLUDED__\n\n#include <uuid\/uuid.h>\n#include <cstdint>\n#include <string>\n#include <vector>\n\nnamespace ignition\n{\n namespace transport\n {\n \/\/\/ \\brief Length of a GUID.\n #define GUID_STR_LEN (sizeof(uuid_t) * 2) + 4 + 1\n\n \/\/ This is the version of Gazebo transport we implement\n static const int Version = 1;\n\n \/\/ Message types\n static const int AdvType = 0;\n static const int SubType = 1;\n static const int AdvSvcType = 2;\n static const int SubSvcType = 3;\n static const int PubType = 4;\n static const int ReqType = 5;\n static const int RepType = 6;\n static const int RepErrorType = 7;\n\n \/\/\/ \\brief Used for debugging the message type received\/send.\n static const std::vector<std::string> MsgTypesStr =\n {\n \"ADVERTISE\", \"SUBSCRIBE\", \"ADV_SRV\", \"SUB_SVC\",\n \"PUB\", \"REQ\", \"SRV_REP_OK\", \"SRV_REP_ERROR\"\n };\n\n \/\/\/ \\brief Get the string representation of the GUID.\n \/\/\/ \\param[in] _uuid UUID to be converted to string.\n \/\/\/ \\return A string representation of the GUID.\n std::string GetGuidStr(const uuid_t &_uuid);\n\n class Header\n {\n \/\/\/ \\brief Constructor.\n public: Header();\n\n \/\/\/ \\brief Constructor.\n \/\/\/ \\param[in] _version Version of the transport library.\n \/\/\/ \\param[in] _guid Global identifier. Every process has a unique guid.\n \/\/\/ \\param[in] _topic Topic\n \/\/\/ \\param[in] _type Message type (ADVERTISE, SUBSCRIPTION, ...)\n \/\/\/ \\param[in] _flags Optional flags included in the header.\n public: Header(const uint16_t _version,\n const uuid_t &_guid,\n const std::string &_topic,\n const uint8_t _type,\n const uint16_t _flags);\n\n \/\/\/ \\brief Get the transport library version.\n \/\/\/ \\return Transport library version.\n public: uint16_t GetVersion() const;\n\n \/\/\/ \\brief Get the guid.\n \/\/\/ \\return A unique global identifier for every process.\n public: uuid_t& GetGuid();\n\n \/\/\/ \\brief Get the topic length.\n \/\/\/ \\return Topic length in bytes.\n public: uint16_t GetTopicLength() const;\n\n \/\/\/ \\brief Get the topic.\n \/\/\/ \\return Topic name.\n public: std::string GetTopic() const;\n\n \/\/\/ \\brief Get the message type.\n \/\/\/ \\return Message type (ADVERTISE, SUBSCRIPTION, ...)\n public: uint8_t GetType() const;\n\n \/\/\/ \\brief Get the message flags.\n \/\/\/ \\return Message flags used for compression or other optional features.\n public: uint16_t GetFlags() const;\n\n \/\/\/ \\brief Set the transport library version.\n \/\/\/ \\param[in] Transport library version.\n public: void SetVersion(const uint16_t _version);\n\n \/\/\/ \\brief Set the guid.\n \/\/\/ \\param[in] _guid A unique global identifier for every process.\n public: void SetGuid(const uuid_t &_guid);\n\n \/\/\/ \\brief Set the topic.\n \/\/\/ \\param[in] _topic Topic name.\n public: void SetTopic(const std::string &_topic);\n\n \/\/\/ \\brief Set the message type.\n \/\/\/ \\param[in] _type Message type (ADVERTISE, SUBSCRIPTION, ...)\n public: void SetType(const uint8_t _type);\n\n \/\/\/ \\brief Set the message flags.\n \/\/\/ \\param[in] _flags Used for enable optional features.\n public: void SetFlags(const uint16_t _flags);\n\n \/\/\/ \\brief Get the header length.\n \/\/\/ \\return The header length in bytes.\n public: int GetHeaderLength();\n\n \/\/\/ \\brief Print the header.\n public: void Print();\n\n \/\/\/ \\brief Serialize the header. The caller has ownership of the\n \/\/\/ buffer and is responsible for its [de]allocation.\n \/\/\/ \\param[out] _buffer Destination buffer in which the header\n \/\/\/ will be serialized.\n \/\/\/ \\return Number of bytes serialized.\n public: size_t Pack(char *_buffer);\n\n \/\/\/ \\brief Unserialize the header.\n \/\/\/ \\param[in] _buffer Input buffer with the data to be unserialized.\n public: size_t Unpack(const char *_buffer);\n\n\n \/\/\/ \\brief Calculate the header length.\n private: void UpdateHeaderLength();\n\n \/\/\/ \\brief Version of the transport library.\n private: uint16_t version;\n\n \/\/\/ \\brief Global identifier. Every process has a unique guid.\n private: uuid_t guid;\n\n \/\/\/ \\brief Topic length in bytes.\n private: uint16_t topicLength;\n\n \/\/\/ \\brief Topic.\n private:std::string topic;\n\n \/\/\/ \\brief Message type (ADVERTISE, SUBSCRIPTION, ...).\n private: uint8_t type;\n\n \/\/\/ \\brief Optional flags that you want to include in the header.\n private: uint16_t flags;\n\n \/\/\/ \\brief Header length.\n private: int headerLength;\n };\n\n class AdvMsg\n {\n \/\/\/ \\brief Constructor.\n public: AdvMsg();\n\n \/\/\/ \\brief Constructor.\n \/\/\/ \\param[in] _header Message header\n \/\/\/ \\param[in] _address ZeroMQ address (e.g., \"tcp:\/\/10.0.0.1:6000\").\n public: AdvMsg(const Header &_header, const std::string &_address);\n\n \/\/\/ \\brief Get the message header.\n \/\/\/ \\return Reference to the message header.\n public: Header& GetHeader();\n\n \/\/\/ \\brief Get the address length.\n \/\/\/ \\brief Return the ZMQ address length (num of bytes).\n public: uint16_t GetAddressLength() const;\n\n \/\/\/ \\brief Get the ZMQ address.\n \/\/\/ \\return Return the ZMQ address.\n public: std::string GetAddress() const;\n\n \/\/\/ \\brief Set the header of the message.\n \/\/\/ \\param[in] _header Message header.\n public: void SetHeader(const Header &_header);\n\n \/\/\/ \\brief Set the ZMQ address.\n \/\/\/ \\param[in] _address ZMQ address to be contained in the message.\n public: void SetAddress(const std::string &_address);\n\n \/\/\/ \\brief Get the total length of the message.\n \/\/\/ \\return Return the length of the message in bytes.\n public: size_t GetMsgLength();\n\n \/\/\/ \\brief Print the message.\n public: void PrintBody();\n\n \/\/\/ \\brief Serialize the AdvMsg.\n \/\/\/ \\param[out] _buffer Buffer where the message will be serialized.\n \/\/\/ \\return The length of the serialized message in bytes.\n public: size_t Pack(char *_buffer);\n\n \/\/\/ \\brief Unserialize a stream of bytes into a AdvMsg.\n \/\/\/ \\param[out] _buffer Unpack the body from the buffer.\n \/\/\/ \\return The number of bytes from the body.\n public: size_t UnpackBody(char *_buffer);\n\n \/\/\/ \\brief Update the ADV message length.\n private: void UpdateMsgLength();\n\n \/\/\/ \\brief Message header\n private: Header header;\n\n \/\/\/ \\brief Length of the address contained in this message (bytes).\n private: uint16_t addressLength;\n\n \/\/\/ \\brief ZMQ valid address (e.g., \"tcp:\/\/10.0.0.1:6000\").\n private: std::string address;\n\n \/\/\/ \\brief Length of the message in bytes.\n private: int msgLength;\n };\n }\n}\n\n#endif\n<commit_msg>[include\/ignition\/transport\/Packet.hh] Adding doxygen to the classes Packet and AdvMsg.<commit_after>\/*\n * Copyright (C) 2014 Open Source Robotics 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#ifndef __IGN_TRANSPORT_PACKET_HH_INCLUDED__\n#define __IGN_TRANSPORT_PACKET_HH_INCLUDED__\n\n#include <uuid\/uuid.h>\n#include <cstdint>\n#include <string>\n#include <vector>\n\nnamespace ignition\n{\n namespace transport\n {\n \/\/\/ \\brief Length of a GUID.\n #define GUID_STR_LEN (sizeof(uuid_t) * 2) + 4 + 1\n\n \/\/ This is the version of Gazebo transport we implement\n static const int Version = 1;\n\n \/\/ Message types\n static const int AdvType = 0;\n static const int SubType = 1;\n static const int AdvSvcType = 2;\n static const int SubSvcType = 3;\n static const int PubType = 4;\n static const int ReqType = 5;\n static const int RepType = 6;\n static const int RepErrorType = 7;\n\n \/\/\/ \\brief Used for debugging the message type received\/send.\n static const std::vector<std::string> MsgTypesStr =\n {\n \"ADVERTISE\", \"SUBSCRIBE\", \"ADV_SRV\", \"SUB_SVC\",\n \"PUB\", \"REQ\", \"SRV_REP_OK\", \"SRV_REP_ERROR\"\n };\n\n \/\/\/ \\brief Get the string representation of the GUID.\n \/\/\/ \\param[in] _uuid UUID to be converted to string.\n \/\/\/ \\return A string representation of the GUID.\n std::string GetGuidStr(const uuid_t &_uuid);\n\n \/\/\/ \\class Header Packet.hh\n \/\/\/ \\brief Header included in each discovery message containing the version\n \/\/\/ of the discovery protocol, the UUID of the sender node, the topic\n \/\/\/ contained in the message, the type of message (ADV, SUB, ... ) and\n \/\/\/ optional flags.\n class Header\n {\n \/\/\/ \\brief Constructor.\n public: Header();\n\n \/\/\/ \\brief Constructor.\n \/\/\/ \\param[in] _version Version of the transport library.\n \/\/\/ \\param[in] _guid Global identifier. Every process has a unique guid.\n \/\/\/ \\param[in] _topic Topic\n \/\/\/ \\param[in] _type Message type (ADVERTISE, SUBSCRIPTION, ...)\n \/\/\/ \\param[in] _flags Optional flags included in the header.\n public: Header(const uint16_t _version,\n const uuid_t &_guid,\n const std::string &_topic,\n const uint8_t _type,\n const uint16_t _flags);\n\n \/\/\/ \\brief Get the transport library version.\n \/\/\/ \\return Transport library version.\n public: uint16_t GetVersion() const;\n\n \/\/\/ \\brief Get the guid.\n \/\/\/ \\return A unique global identifier for every process.\n public: uuid_t& GetGuid();\n\n \/\/\/ \\brief Get the topic length.\n \/\/\/ \\return Topic length in bytes.\n public: uint16_t GetTopicLength() const;\n\n \/\/\/ \\brief Get the topic.\n \/\/\/ \\return Topic name.\n public: std::string GetTopic() const;\n\n \/\/\/ \\brief Get the message type.\n \/\/\/ \\return Message type (ADVERTISE, SUBSCRIPTION, ...)\n public: uint8_t GetType() const;\n\n \/\/\/ \\brief Get the message flags.\n \/\/\/ \\return Message flags used for compression or other optional features.\n public: uint16_t GetFlags() const;\n\n \/\/\/ \\brief Set the transport library version.\n \/\/\/ \\param[in] Transport library version.\n public: void SetVersion(const uint16_t _version);\n\n \/\/\/ \\brief Set the guid.\n \/\/\/ \\param[in] _guid A unique global identifier for every process.\n public: void SetGuid(const uuid_t &_guid);\n\n \/\/\/ \\brief Set the topic.\n \/\/\/ \\param[in] _topic Topic name.\n public: void SetTopic(const std::string &_topic);\n\n \/\/\/ \\brief Set the message type.\n \/\/\/ \\param[in] _type Message type (ADVERTISE, SUBSCRIPTION, ...)\n public: void SetType(const uint8_t _type);\n\n \/\/\/ \\brief Set the message flags.\n \/\/\/ \\param[in] _flags Used for enable optional features.\n public: void SetFlags(const uint16_t _flags);\n\n \/\/\/ \\brief Get the header length.\n \/\/\/ \\return The header length in bytes.\n public: int GetHeaderLength();\n\n \/\/\/ \\brief Print the header.\n public: void Print();\n\n \/\/\/ \\brief Serialize the header. The caller has ownership of the\n \/\/\/ buffer and is responsible for its [de]allocation.\n \/\/\/ \\param[out] _buffer Destination buffer in which the header\n \/\/\/ will be serialized.\n \/\/\/ \\return Number of bytes serialized.\n public: size_t Pack(char *_buffer);\n\n \/\/\/ \\brief Unserialize the header.\n \/\/\/ \\param[in] _buffer Input buffer with the data to be unserialized.\n public: size_t Unpack(const char *_buffer);\n\n\n \/\/\/ \\brief Calculate the header length.\n private: void UpdateHeaderLength();\n\n \/\/\/ \\brief Version of the transport library.\n private: uint16_t version;\n\n \/\/\/ \\brief Global identifier. Every process has a unique guid.\n private: uuid_t guid;\n\n \/\/\/ \\brief Topic length in bytes.\n private: uint16_t topicLength;\n\n \/\/\/ \\brief Topic.\n private:std::string topic;\n\n \/\/\/ \\brief Message type (ADVERTISE, SUBSCRIPTION, ...).\n private: uint8_t type;\n\n \/\/\/ \\brief Optional flags that you want to include in the header.\n private: uint16_t flags;\n\n \/\/\/ \\brief Header length.\n private: int headerLength;\n };\n\n \/\/\/ \\class AdvMsg Packet.hh\n \/\/\/ \\brief Advertise message used in the discovery protocol to broadcast\n \/\/\/ information about the node advertising a topic. The information sent\n \/\/\/ is the ZeroMQ end point addressy where the node will be receiving\n \/\/\/ subscription requests.\n class AdvMsg\n {\n \/\/\/ \\brief Constructor.\n public: AdvMsg();\n\n \/\/\/ \\brief Constructor.\n \/\/\/ \\param[in] _header Message header\n \/\/\/ \\param[in] _address ZeroMQ address (e.g., \"tcp:\/\/10.0.0.1:6000\").\n public: AdvMsg(const Header &_header, const std::string &_address);\n\n \/\/\/ \\brief Get the message header.\n \/\/\/ \\return Reference to the message header.\n public: Header& GetHeader();\n\n \/\/\/ \\brief Get the address length.\n \/\/\/ \\brief Return the ZMQ address length (num of bytes).\n public: uint16_t GetAddressLength() const;\n\n \/\/\/ \\brief Get the ZMQ address.\n \/\/\/ \\return Return the ZMQ address.\n public: std::string GetAddress() const;\n\n \/\/\/ \\brief Set the header of the message.\n \/\/\/ \\param[in] _header Message header.\n public: void SetHeader(const Header &_header);\n\n \/\/\/ \\brief Set the ZMQ address.\n \/\/\/ \\param[in] _address ZMQ address to be contained in the message.\n public: void SetAddress(const std::string &_address);\n\n \/\/\/ \\brief Get the total length of the message.\n \/\/\/ \\return Return the length of the message in bytes.\n public: size_t GetMsgLength();\n\n \/\/\/ \\brief Print the message.\n public: void PrintBody();\n\n \/\/\/ \\brief Serialize the AdvMsg.\n \/\/\/ \\param[out] _buffer Buffer where the message will be serialized.\n \/\/\/ \\return The length of the serialized message in bytes.\n public: size_t Pack(char *_buffer);\n\n \/\/\/ \\brief Unserialize a stream of bytes into a AdvMsg.\n \/\/\/ \\param[out] _buffer Unpack the body from the buffer.\n \/\/\/ \\return The number of bytes from the body.\n public: size_t UnpackBody(char *_buffer);\n\n \/\/\/ \\brief Update the ADV message length.\n private: void UpdateMsgLength();\n\n \/\/\/ \\brief Message header\n private: Header header;\n\n \/\/\/ \\brief Length of the address contained in this message (bytes).\n private: uint16_t addressLength;\n\n \/\/\/ \\brief ZMQ valid address (e.g., \"tcp:\/\/10.0.0.1:6000\").\n private: std::string address;\n\n \/\/\/ \\brief Length of the message in bytes.\n private: int msgLength;\n };\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/======================================================================\r\n\/\/-----------------------------------------------------------------------\r\n\/**\r\n * @file\t\tiutest_constant.hpp\r\n * @brief\t\tiris unit test 定数 定義 ファイル\r\n *\r\n * @author\t\tt.shirayanagi\r\n * @par\t\t\tcopyright\r\n * Copyright (C) 2011-2016, Takazumi Shirayanagi\\n\r\n * This software is released under the new BSD License,\r\n * see LICENSE\r\n*\/\r\n\/\/-----------------------------------------------------------------------\r\n\/\/======================================================================\r\n#ifndef INCG_IRIS_IUTEST_CONSTANT_HPP_37DDDC13_3259_42E0_A648_47B064DED4BA_\r\n#define INCG_IRIS_IUTEST_CONSTANT_HPP_37DDDC13_3259_42E0_A648_47B064DED4BA_\r\n\r\n\/\/======================================================================\r\n\/\/ include\r\n\r\nnamespace iutest {\r\nnamespace detail\r\n{\r\n\r\nnamespace helper\r\n{\r\n\r\nnamespace\r\n{\r\n\r\n\/**\r\n * @brief\t文字列定数\r\n*\/\r\ntemplate<typename DMY>\r\nstruct kStringsT\r\n{\r\n\tstatic const char* const DefaultXmlReportFileName;\t\/\/!< デフォルト xml 出力ファイル名\r\n\tstatic const char* const UnknownFile;\t\t\t\t\/\/!< unknown file\r\n\tstatic const char* const Null;\t\t\t\t\t\t\/\/!< NULL\r\n};\r\n\r\n#if IUTEST_HAS_LIB && IUTEST_HAS_EXTERN_TEMPLATE\r\n\r\nIUTEST_PRAGMA_EXTERN_TEMPLATE_WARN_DISABLE_BEGIN()\r\n\r\nextern template struct kStringsT<void>;\r\n\r\nIUTEST_PRAGMA_EXTERN_TEMPLATE_WARN_DISABLE_END()\r\n\r\n#else\r\n\r\ntemplate<typename DMY>\r\nconst char* const kStringsT<DMY>::DefaultXmlReportFileName = \"test_detail.xml\";\r\ntemplate<typename DMY>\r\nconst char* const kStringsT<DMY>::UnknownFile = \"unknown file\";\r\ntemplate<typename DMY>\r\nconst char* const kStringsT<DMY>::Null = \"(null)\";\r\n\r\ntemplate struct kStringsT<void>;\r\n\r\n#endif\r\n\r\n}\r\n}\t\/\/ end of namespace helper\r\n\r\n\/** @internal *\/\r\ntypedef helper::kStringsT<void> kStrings;\r\n\r\n\/**\r\n * @brief\t定数群\r\n*\/\r\nstruct kValues\r\n{\r\n#if defined(IUTEST_NO_INCLASS_MEMBER_INITIALIZATION)\r\n\tenum\r\n\t{\r\n\t\tMaxPrintContainerCount = 32\r\n\t\t, PrintArrayThreshold = 16\r\n\t\t, PrintArrayChunksize = PrintArrayThreshold\/2\r\n\t};\r\n#else\r\n\tstatic const size_t MaxPrintContainerCount = 32;\r\n\tstatic const size_t PrintArrayThreshold = 18;\r\n\tstatic const size_t PrintArrayChunksize = PrintArrayThreshold\/2;\r\n#endif\r\n};\r\n\r\n}\t\/\/ end of namespace detail\r\n}\t\/\/ end of namespace iutest\r\n\r\n#endif \/\/ INCG_IRIS_IUTEST_CONSTANT_HPP_37DDDC13_3259_42E0_A648_47B064DED4BA_\r\n<commit_msg>update r1054 fix cpplint<commit_after>\/\/======================================================================\r\n\/\/-----------------------------------------------------------------------\r\n\/**\r\n * @file\t\tiutest_constant.hpp\r\n * @brief\t\tiris unit test 定数 定義 ファイル\r\n *\r\n * @author\t\tt.shirayanagi\r\n * @par\t\t\tcopyright\r\n * Copyright (C) 2011-2016, Takazumi Shirayanagi\\n\r\n * This software is released under the new BSD License,\r\n * see LICENSE\r\n*\/\r\n\/\/-----------------------------------------------------------------------\r\n\/\/======================================================================\r\n#ifndef INCG_IRIS_IUTEST_CONSTANT_HPP_37DDDC13_3259_42E0_A648_47B064DED4BA_\r\n#define INCG_IRIS_IUTEST_CONSTANT_HPP_37DDDC13_3259_42E0_A648_47B064DED4BA_\r\n\r\n\/\/======================================================================\r\n\/\/ include\r\n\r\nnamespace iutest {\r\nnamespace detail\r\n{\r\n\r\nnamespace helper\r\n{\r\n\r\nnamespace\r\n{\r\n\r\n\/**\r\n * @brief\t文字列定数\r\n*\/\r\ntemplate<typename DMY>\r\nstruct kStringsT\r\n{\r\n\tstatic const char* const DefaultXmlReportFileName;\t\/\/!< デフォルト xml 出力ファイル名\r\n\tstatic const char* const UnknownFile;\t\t\t\t\/\/!< unknown file\r\n\tstatic const char* const Null;\t\t\t\t\t\t\/\/!< NULL\r\n};\r\n\r\n#if IUTEST_HAS_LIB && IUTEST_HAS_EXTERN_TEMPLATE\r\n\r\nIUTEST_PRAGMA_EXTERN_TEMPLATE_WARN_DISABLE_BEGIN()\r\n\r\nextern template struct kStringsT<void>;\r\n\r\nIUTEST_PRAGMA_EXTERN_TEMPLATE_WARN_DISABLE_END()\r\n\r\n#else\r\n\r\ntemplate<typename DMY>\r\nconst char* const kStringsT<DMY>::DefaultXmlReportFileName = \"test_detail.xml\";\r\ntemplate<typename DMY>\r\nconst char* const kStringsT<DMY>::UnknownFile = \"unknown file\";\r\ntemplate<typename DMY>\r\nconst char* const kStringsT<DMY>::Null = \"(null)\";\r\n\r\ntemplate struct kStringsT<void>;\r\n\r\n#endif\r\n\r\n}\t\/\/ namespace\r\n}\t\/\/ end of namespace helper\r\n\r\n\/** @internal *\/\r\ntypedef helper::kStringsT<void> kStrings;\r\n\r\n\/**\r\n * @brief\t定数群\r\n*\/\r\nstruct kValues\r\n{\r\n#if defined(IUTEST_NO_INCLASS_MEMBER_INITIALIZATION)\r\n\tenum\r\n\t{\r\n\t\tMaxPrintContainerCount = 32\r\n\t\t, PrintArrayThreshold = 16\r\n\t\t, PrintArrayChunksize = PrintArrayThreshold\/2\r\n\t};\r\n#else\r\n\tstatic const size_t MaxPrintContainerCount = 32;\r\n\tstatic const size_t PrintArrayThreshold = 18;\r\n\tstatic const size_t PrintArrayChunksize = PrintArrayThreshold\/2;\r\n#endif\r\n};\r\n\r\n}\t\/\/ end of namespace detail\r\n}\t\/\/ end of namespace iutest\r\n\r\n#endif \/\/ INCG_IRIS_IUTEST_CONSTANT_HPP_37DDDC13_3259_42E0_A648_47B064DED4BA_\r\n<|endoftext|>"} {"text":"<commit_before>#ifndef KGR_INCLUDE_KANGARU_OPERATOR_SERVICE\n#define KGR_INCLUDE_KANGARU_OPERATOR_SERVICE\n\n#include \"container.hpp\"\n#include \"operator.hpp\"\n\nnamespace kgr {\n\ntemplate<typename Predicate = All>\nstruct ForkService {\n\texplicit ForkService(in_place_t, Container& container) : _container{container.fork<Predicate>()} {}\n\t\n\tinline Container forward() {\n\t\treturn std::move(_container);\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer _container;\n};\n\ntemplate<template<typename> class Map>\nstruct InvokerService {\n\texplicit InvokerService(in_place_t, Container& container) : _container{container} {}\n\t\n\tInvoker<Map> forward() {\n\t\treturn Invoker<Map>{_container};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer& _container;\n};\n\ntemplate<template<typename> class Map, typename Predicate = All>\nstruct ForkedInvokerService {\n\texplicit ForkedInvokerService(in_place_t, Container& container) : _container{container.fork<Predicate>()} {}\n\t\n\tForkedInvoker<Map> forward() {\n\t\treturn ForkedInvoker<Map>{std::move(_container)};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer _container;\n};\n\ntemplate<typename T>\nstruct GeneratorService {\n\texplicit GeneratorService(in_place_t, Container& container) : _container{container} {}\n\t\n\tGenerator<T> forward() {\n\t\treturn Generator<T>{_container};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer& _container;\n};\n\ntemplate<typename T, typename Predicate = All>\nstruct ForkedGeneratorService {\n\texplicit ForkedGeneratorService(in_place_t, Container& container) : _container{container.fork<Predicate>()} {}\n\t\n\tForkedGenerator<T> forward() {\n\t\treturn ForkedGenerator<T>{std::move(_container)};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer _container;\n};\n\ntemplate<typename T>\nstruct LazyService {\n\texplicit LazyService(in_place_t, Container& container) : _container{container} {}\n\t\n\tLazy<T> forward() {\n\t\treturn Lazy<T>{_container};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer& _container;\n};\n\ntemplate<typename T, typename Predicate = All>\nstruct ForkedLazyService {\n\texplicit ForkedLazyService(in_place_t, Container& container) : _container{container.fork<Predicate>()} {}\n\t\n\tForkedLazy<T> forward() {\n\t\treturn ForkedLazy<T>{std::move(_container)};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer _container;\n};\n\n} \/\/ namespace kgr\n\n#endif \/\/ KGR_INCLUDE_KANGARU_OPERATOR_SERVICE\n<commit_msg>added DefaultForkService to mimic the old behaviour<commit_after>#ifndef KGR_INCLUDE_KANGARU_OPERATOR_SERVICE\n#define KGR_INCLUDE_KANGARU_OPERATOR_SERVICE\n\n#include \"container.hpp\"\n#include \"operator.hpp\"\n\nnamespace kgr {\n\ntemplate<typename Predicate>\nstruct ForkService {\n\texplicit ForkService(in_place_t, Container& container) : _container{container.fork<Predicate>()} {}\n\t\n\tinline Container forward() {\n\t\treturn std::move(_container);\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer _container;\n};\n\nusing DefaultForkService = ForkService<All>;\n\ntemplate<template<typename> class Map>\nstruct InvokerService {\n\texplicit InvokerService(in_place_t, Container& container) : _container{container} {}\n\t\n\tInvoker<Map> forward() {\n\t\treturn Invoker<Map>{_container};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer& _container;\n};\n\ntemplate<template<typename> class Map, typename Predicate = All>\nstruct ForkedInvokerService {\n\texplicit ForkedInvokerService(in_place_t, Container& container) : _container{container.fork<Predicate>()} {}\n\t\n\tForkedInvoker<Map> forward() {\n\t\treturn ForkedInvoker<Map>{std::move(_container)};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer _container;\n};\n\ntemplate<typename T>\nstruct GeneratorService {\n\texplicit GeneratorService(in_place_t, Container& container) : _container{container} {}\n\t\n\tGenerator<T> forward() {\n\t\treturn Generator<T>{_container};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer& _container;\n};\n\ntemplate<typename T, typename Predicate = All>\nstruct ForkedGeneratorService {\n\texplicit ForkedGeneratorService(in_place_t, Container& container) : _container{container.fork<Predicate>()} {}\n\t\n\tForkedGenerator<T> forward() {\n\t\treturn ForkedGenerator<T>{std::move(_container)};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer _container;\n};\n\ntemplate<typename T>\nstruct LazyService {\n\texplicit LazyService(in_place_t, Container& container) : _container{container} {}\n\t\n\tLazy<T> forward() {\n\t\treturn Lazy<T>{_container};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer& _container;\n};\n\ntemplate<typename T, typename Predicate = All>\nstruct ForkedLazyService {\n\texplicit ForkedLazyService(in_place_t, Container& container) : _container{container.fork<Predicate>()} {}\n\t\n\tForkedLazy<T> forward() {\n\t\treturn ForkedLazy<T>{std::move(_container)};\n\t}\n\t\n\tstatic auto construct(Inject<ContainerService> cs) -> decltype(inject(cs.forward())) {\n\t\treturn inject(cs.forward());\n\t}\n\t\nprivate:\n\tContainer _container;\n};\n\n} \/\/ namespace kgr\n\n#endif \/\/ KGR_INCLUDE_KANGARU_OPERATOR_SERVICE\n<|endoftext|>"} {"text":"<commit_before>#ifdef NN_ACCEL_GPU\n#ifndef NVBLAS_TPP\n#define NVBLAS_TPP\n\n#include <nvblas.h>\n\nnamespace nnlib\n{\n\ntemplate <>\nvoid Math<float>::mAdd_mm(size_t M, size_t N, size_t K, const float *A, size_t lda, const float *B, size_t ldb, float *C, size_t ldc, float alpha, float beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tsgemm(\"N\", \"N\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<double>::mAdd_mm(size_t M, size_t N, size_t K, const double *A, size_t lda, const double *B, size_t ldb, double *C, size_t ldc, double alpha, double beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tdgemm(\"N\", \"N\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<float>::mAdd_mtm(size_t M, size_t N, size_t K, const float *A, size_t lda, const float *B, size_t ldb, float *C, size_t ldc, float alpha, float beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tsgemm(\"N\", \"T\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<double>::mAdd_mtm(size_t M, size_t N, size_t K, const double *A, size_t lda, const double *B, size_t ldb, double *C, size_t ldc, double alpha, double beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tdgemm(\"N\", \"T\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<float>::mAdd_mmt(size_t M, size_t N, size_t K, const float *A, size_t lda, const float *B, size_t ldb, float *C, size_t ldc, float alpha, float beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tsgemm(\"T\", \"N\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<float>::mAdd_mmt(size_t M, size_t N, size_t K, const double *A, size_t lda, const double *B, size_t ldb, double *C, size_t ldc, double alpha, double beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tsgemm(\"T\", \"N\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\n}\n\n#endif\n#endif\n<commit_msg>Fixed a problem with nvblas.<commit_after>#ifdef NN_ACCEL_GPU\n#ifndef NVBLAS_TPP\n#define NVBLAS_TPP\n\n#include <nvblas.h>\n\nnamespace nnlib\n{\n\ntemplate <>\nvoid Math<float>::mAdd_mm(size_t M, size_t N, size_t K, const float *A, size_t lda, const float *B, size_t ldb, float *C, size_t ldc, float alpha, float beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tsgemm(\"N\", \"N\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<double>::mAdd_mm(size_t M, size_t N, size_t K, const double *A, size_t lda, const double *B, size_t ldb, double *C, size_t ldc, double alpha, double beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tdgemm(\"N\", \"N\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<float>::mAdd_mtm(size_t M, size_t N, size_t K, const float *A, size_t lda, const float *B, size_t ldb, float *C, size_t ldc, float alpha, float beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tsgemm(\"N\", \"T\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<double>::mAdd_mtm(size_t M, size_t N, size_t K, const double *A, size_t lda, const double *B, size_t ldb, double *C, size_t ldc, double alpha, double beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tdgemm(\"N\", \"T\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<float>::mAdd_mmt(size_t M, size_t N, size_t K, const float *A, size_t lda, const float *B, size_t ldb, float *C, size_t ldc, float alpha, float beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tsgemm(\"T\", \"N\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\ntemplate <>\nvoid Math<double>::mAdd_mmt(size_t M, size_t N, size_t K, const double *A, size_t lda, const double *B, size_t ldb, double *C, size_t ldc, double alpha, double beta)\n{\n\tint m = (int) M, n = (int) N, k = (int) K, a = (int) lda, b = (int) ldb, c = (int) ldc;\n\tdgemm(\"T\", \"N\", &n, &m, &k, &alpha, B, &b, A, &a, &beta, C, &c);\n}\n\n}\n\n#endif\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <memory>\n#include <functional>\n\nnamespace th\n{\ntemplate<typename BaseType>\nclass PolymorphicWrapper\n{\n public:\n template<typename DerivedType>\n PolymorphicWrapper(DerivedType&& derived)\n {\n using DecayedType = typename std::decay<DerivedType>::type;\n static_assert(std::is_base_of<BaseType, DecayedType>::value, \"Can only be constructed from types that inherit BaseType\");\n \n mCopyFunction = [] (const std::unique_ptr<BaseType>& derivedToCopy)\n {\n const auto originalPtr = static_cast<DecayedType*>(derivedToCopy.get());\n return std::unique_ptr<BaseType>(new DecayedType(*originalPtr)); \/\/uses the normal copy mechanics of the DecayedType class\n };\n\n mValue.reset(new DecayedType(derived));\n }\n\n PolymorphicWrapper(const PolymorphicWrapper& other)\n {\n mCopyFunction = other.mCopyFunction;\n mValue = mCopyFunction(other.mValue); \/\/uses stored lambda to copy\n }\n\n PolymorphicWrapper(PolymorphicWrapper&& other)\n {\n mCopyFunction = other.mCopyFunction;\n mValue = std::move(other.mValue);\n }\n\n PolymorphicWrapper& operator=(const PolymorphicWrapper& other)\n {\n mCopyFunction = other.mCopyFunction;\n mValue = mCopyFunction(other.mValue); \/\/uses stored lambda to copy\n return *this;\n }\n\n PolymorphicWrapper& operator=(PolymorphicWrapper&& other)\n {\n mCopyFunction = other.mCopyFunction;\n mValue = std::move(other.mValue);\n return *this;\n }\n\n const BaseType& operator*() const\n {\n return *mValue;\n }\n\n BaseType& operator*()\n {\n return *mValue;\n }\n\n const BaseType* operator->() const\n {\n return mValue.get();\n }\n\n BaseType* operator->()\n {\n return mValue.get();\n }\n\n private:\n std::function<std::unique_ptr<BaseType>(const std::unique_ptr<BaseType>&)> mCopyFunction;\n std::unique_ptr<BaseType> mValue;\n};\n}\n<commit_msg>Now uses std::forward<commit_after>#pragma once\n#include <memory>\n#include <functional>\n\nnamespace th\n{\ntemplate<typename BaseType>\nclass PolymorphicWrapper\n{\n public:\n template<typename DerivedType>\n PolymorphicWrapper(DerivedType&& derived)\n {\n using DecayedType = typename std::decay<DerivedType>::type;\n static_assert(std::is_base_of<BaseType, DecayedType>::value, \"Can only be constructed from types that inherit BaseType\");\n \n mCopyFunction = [] (const std::unique_ptr<BaseType>& derivedToCopy)\n {\n const auto originalPtr = static_cast<DecayedType*>(derivedToCopy.get());\n return std::unique_ptr<BaseType>(new DecayedType(*originalPtr)); \/\/uses the normal copy mechanics of the DecayedType class\n };\n\n mValue.reset(new DecayedType(std::forward<DerivedType>(derived)));\n }\n\n PolymorphicWrapper(const PolymorphicWrapper& other)\n {\n mCopyFunction = other.mCopyFunction;\n mValue = mCopyFunction(other.mValue); \/\/uses stored lambda to copy\n }\n\n PolymorphicWrapper(PolymorphicWrapper&& other)\n {\n mCopyFunction = std::move(other.mCopyFunction);\n mValue = std::move(other.mValue);\n }\n\n PolymorphicWrapper& operator=(const PolymorphicWrapper& other)\n {\n mCopyFunction = other.mCopyFunction;\n mValue = mCopyFunction(other.mValue); \/\/uses stored lambda to copy\n return *this;\n }\n\n PolymorphicWrapper& operator=(PolymorphicWrapper&& other)\n {\n mCopyFunction = other.mCopyFunction;\n mValue = std::move(other.mValue);\n return *this;\n }\n\n const BaseType& operator*() const\n {\n return *mValue;\n }\n\n BaseType& operator*()\n {\n return *mValue;\n }\n\n const BaseType* operator->() const\n {\n return mValue.get();\n }\n\n BaseType* operator->()\n {\n return mValue.get();\n }\n\n private:\n std::function<std::unique_ptr<BaseType>(const std::unique_ptr<BaseType>&)> mCopyFunction;\n std::unique_ptr<BaseType> mValue;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"model.h\"\n#include \"modelwidget.h\"\n#include \"figurepainter.h\"\n#include \"recognition.h\"\n#include \"layouting.h\"\n#include <QPainter>\n#include <QMouseEvent>\n#include <QDebug>\n#include <QTimer>\n#include <iostream>\n\nUi::ModelWidget::ModelWidget(QWidget *parent) :\n QWidget(parent), trackIsCancelled(false), _gridStep(0) {\n setFocusPolicy(Qt::FocusPolicy::StrongFocus);\n}\n\nvoid drawTrack(QPainter &painter, FigurePainter &fpainter, const Track &track) {\n for (size_t i = 0; i + 1 < track.size(); i++) {\n painter.drawLine(fpainter.scale(track[i]), fpainter.scale(track[i + 1]));\n }\n}\n\nint Ui::ModelWidget::gridStep() {\n return _gridStep;\n}\n\nvoid Ui::ModelWidget::setGridStep(int newGridStep) {\n if (newGridStep < 0) {\n throw std::runtime_error(\"Grid step should be >= 0\");\n }\n _gridStep = newGridStep;\n}\n\nvoid Ui::ModelWidget::setModel(Model model) {\n commitedModel = std::move(model);\n previousModels.clear();\n redoModels.clear();\n emit canUndoChanged();\n emit canRedoChanged();\n}\nModel &Ui::ModelWidget::getModel() {\n return commitedModel;\n}\n\nbool Ui::ModelWidget::canUndo() {\n return !previousModels.empty();\n}\n\nvoid Ui::ModelWidget::undo() {\n if (!canUndo()) {\n throw std::runtime_error(\"Cannot undo\");\n }\n redoModels.push_front(std::move(commitedModel));\n commitedModel = std::move(previousModels.back());\n previousModels.pop_back();\n if (!canUndo()) {\n emit canUndoChanged();\n }\n emit canRedoChanged();\n repaint();\n}\n\nbool Ui::ModelWidget::canRedo() {\n return !redoModels.empty();\n}\n\nvoid Ui::ModelWidget::redo() {\n if (!canRedo()) {\n throw std::runtime_error(\"Cannot redo\");\n }\n previousModels.push_back(std::move(commitedModel));\n commitedModel = std::move(redoModels.front());\n redoModels.pop_front();\n if (!canRedo()) {\n canRedoChanged();\n }\n canUndoChanged();\n repaint();\n}\n\ndouble roundUpToMultiple(double x, double multiple) {\n return ceil(x \/ multiple) * multiple;\n}\n\nvoid Ui::ModelWidget::paintEvent(QPaintEvent *) {\n QPainter painter(this);\n painter.fillRect(QRect(QPoint(), size()), Qt::white);\n\n painter.setPen(Qt::black);\n\n FigurePainter fpainter(painter);\n if (gridStep() > 0) {\n int step = gridStep();\n \/\/ Calculating visible area\n Point p1 = fpainter.unscale(QPointF(0, 0));\n Point p2 = fpainter.unscale(QPointF(width(), height()));\n if (p1.x > p2.x) { std::swap(p1.x, p2.x); }\n if (p1.y > p2.y) { std::swap(p1.y, p2.y); }\n\n \/\/ Finding starting point for the grid\n p1.x = roundUpToMultiple(p1.x, step);\n p1.y = roundUpToMultiple(p1.y, step);\n\n \/\/ Drawing\n QPen pen(QColor(192, 192, 192, 255));\n pen.setStyle(Qt::DashLine);\n painter.setPen(pen);\n for (int x = p1.x; x <= p2.x; x += step) {\n painter.drawLine(fpainter.scale(Point(x, p1.y)), fpainter.scale(Point(x, p2.y)));\n }\n for (int y = p1.y; y <= p2.y; y += step) {\n painter.drawLine(fpainter.scale(Point(p1.x, y)), fpainter.scale(Point(p2.x, y)));\n }\n }\n\n Model modelToDraw = commitedModel;\n PFigure modified = recognize(lastTrack, modelToDraw);\n for (PFigure fig : modelToDraw) {\n if (fig == modified) {\n painter.setPen(Qt::magenta);\n } else if (fig == modelToDraw.selectedFigure) {\n painter.setPen(Qt::blue);\n } else {\n painter.setPen(Qt::black);\n }\n fig->visit(fpainter);\n }\n\n QPen pen(QColor(255, 0, 0, 16));\n pen.setWidth(3);\n painter.setPen(pen);\n drawTrack(painter, fpainter, lastTrack);\n for (const Track &track : visibleTracks) {\n drawTrack(painter, fpainter, track);\n }\n}\n\nvoid Ui::ModelWidget::mousePressEvent(QMouseEvent *event) {\n lastTrack = Track();\n trackIsCancelled = false;\n lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n repaint();\n}\nvoid Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) {\n lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n repaint();\n}\nvoid Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) {\n if (trackIsCancelled) {\n return;\n }\n lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n Model previousModel = commitedModel;\n PFigure modifiedFigure = recognize(lastTrack, commitedModel);\n if (_gridStep > 0 && modifiedFigure) {\n GridAlignLayouter layouter(_gridStep);\n layouter.updateLayout(commitedModel, modifiedFigure);\n }\n\n visibleTracks.push_back(lastTrack);\n auto iterator = --visibleTracks.end();\n QTimer *timer = new QTimer(this);\n\n connect(timer, &QTimer::timeout, [this, iterator, timer]() {\n visibleTracks.erase(iterator);\n delete timer;\n repaint();\n });\n timer->setInterval(1500);\n timer->setSingleShot(true);\n timer->start();\n\n lastTrack = Track();\n if (modifiedFigure) {\n previousModels.push_back(previousModel);\n redoModels.clear();\n emit canUndoChanged();\n emit canRedoChanged();\n }\n repaint();\n}\nvoid Ui::ModelWidget::keyReleaseEvent(QKeyEvent *event) {\n if (event->key() == Qt::Key_Escape) {\n lastTrack = Track();\n trackIsCancelled = true;\n repaint();\n }\n if (event->key() == Qt::Key_Delete) {\n if (commitedModel.selectedFigure) {\n previousModels.push_back(commitedModel);\n redoModels.clear();\n for (auto it = commitedModel.begin(); it != commitedModel.end(); it++) {\n if (*it == commitedModel.selectedFigure) {\n commitedModel.removeFigure(it);\n break;\n }\n }\n emit canUndoChanged();\n emit canRedoChanged();\n repaint();\n }\n }\n}\n<commit_msg>modelwidget.paint: now it does not copy model if there is no active track to recognize<commit_after>#include \"model.h\"\n#include \"modelwidget.h\"\n#include \"figurepainter.h\"\n#include \"recognition.h\"\n#include \"layouting.h\"\n#include <QPainter>\n#include <QMouseEvent>\n#include <QDebug>\n#include <QTimer>\n#include <iostream>\n\nUi::ModelWidget::ModelWidget(QWidget *parent) :\n QWidget(parent), trackIsCancelled(false), _gridStep(0) {\n setFocusPolicy(Qt::FocusPolicy::StrongFocus);\n}\n\nvoid drawTrack(QPainter &painter, FigurePainter &fpainter, const Track &track) {\n for (size_t i = 0; i + 1 < track.size(); i++) {\n painter.drawLine(fpainter.scale(track[i]), fpainter.scale(track[i + 1]));\n }\n}\n\nint Ui::ModelWidget::gridStep() {\n return _gridStep;\n}\n\nvoid Ui::ModelWidget::setGridStep(int newGridStep) {\n if (newGridStep < 0) {\n throw std::runtime_error(\"Grid step should be >= 0\");\n }\n _gridStep = newGridStep;\n}\n\nvoid Ui::ModelWidget::setModel(Model model) {\n commitedModel = std::move(model);\n previousModels.clear();\n redoModels.clear();\n emit canUndoChanged();\n emit canRedoChanged();\n}\nModel &Ui::ModelWidget::getModel() {\n return commitedModel;\n}\n\nbool Ui::ModelWidget::canUndo() {\n return !previousModels.empty();\n}\n\nvoid Ui::ModelWidget::undo() {\n if (!canUndo()) {\n throw std::runtime_error(\"Cannot undo\");\n }\n redoModels.push_front(std::move(commitedModel));\n commitedModel = std::move(previousModels.back());\n previousModels.pop_back();\n if (!canUndo()) {\n emit canUndoChanged();\n }\n emit canRedoChanged();\n repaint();\n}\n\nbool Ui::ModelWidget::canRedo() {\n return !redoModels.empty();\n}\n\nvoid Ui::ModelWidget::redo() {\n if (!canRedo()) {\n throw std::runtime_error(\"Cannot redo\");\n }\n previousModels.push_back(std::move(commitedModel));\n commitedModel = std::move(redoModels.front());\n redoModels.pop_front();\n if (!canRedo()) {\n canRedoChanged();\n }\n canUndoChanged();\n repaint();\n}\n\ndouble roundUpToMultiple(double x, double multiple) {\n return ceil(x \/ multiple) * multiple;\n}\n\nvoid Ui::ModelWidget::paintEvent(QPaintEvent *) {\n QPainter painter(this);\n painter.fillRect(QRect(QPoint(), size()), Qt::white);\n\n painter.setPen(Qt::black);\n\n FigurePainter fpainter(painter);\n if (gridStep() > 0) {\n int step = gridStep();\n \/\/ Calculating visible area\n Point p1 = fpainter.unscale(QPointF(0, 0));\n Point p2 = fpainter.unscale(QPointF(width(), height()));\n if (p1.x > p2.x) { std::swap(p1.x, p2.x); }\n if (p1.y > p2.y) { std::swap(p1.y, p2.y); }\n\n \/\/ Finding starting point for the grid\n p1.x = roundUpToMultiple(p1.x, step);\n p1.y = roundUpToMultiple(p1.y, step);\n\n \/\/ Drawing\n QPen pen(QColor(192, 192, 192, 255));\n pen.setStyle(Qt::DashLine);\n painter.setPen(pen);\n for (int x = p1.x; x <= p2.x; x += step) {\n painter.drawLine(fpainter.scale(Point(x, p1.y)), fpainter.scale(Point(x, p2.y)));\n }\n for (int y = p1.y; y <= p2.y; y += step) {\n painter.drawLine(fpainter.scale(Point(p1.x, y)), fpainter.scale(Point(p2.x, y)));\n }\n }\n\n Model copiedModel;\n Model &modelToDraw = lastTrack.empty() ? commitedModel : (copiedModel = commitedModel);\n PFigure modified = recognize(lastTrack, modelToDraw);\n for (PFigure fig : modelToDraw) {\n if (fig == modified) {\n painter.setPen(Qt::magenta);\n } else if (fig == modelToDraw.selectedFigure) {\n painter.setPen(Qt::blue);\n } else {\n painter.setPen(Qt::black);\n }\n fig->visit(fpainter);\n }\n\n QPen pen(QColor(255, 0, 0, 16));\n pen.setWidth(3);\n painter.setPen(pen);\n drawTrack(painter, fpainter, lastTrack);\n for (const Track &track : visibleTracks) {\n drawTrack(painter, fpainter, track);\n }\n}\n\nvoid Ui::ModelWidget::mousePressEvent(QMouseEvent *event) {\n lastTrack = Track();\n trackIsCancelled = false;\n lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n repaint();\n}\nvoid Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) {\n lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n repaint();\n}\nvoid Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) {\n if (trackIsCancelled) {\n return;\n }\n lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n Model previousModel = commitedModel;\n PFigure modifiedFigure = recognize(lastTrack, commitedModel);\n if (_gridStep > 0 && modifiedFigure) {\n GridAlignLayouter layouter(_gridStep);\n layouter.updateLayout(commitedModel, modifiedFigure);\n }\n\n visibleTracks.push_back(lastTrack);\n auto iterator = --visibleTracks.end();\n QTimer *timer = new QTimer(this);\n\n connect(timer, &QTimer::timeout, [this, iterator, timer]() {\n visibleTracks.erase(iterator);\n delete timer;\n repaint();\n });\n timer->setInterval(1500);\n timer->setSingleShot(true);\n timer->start();\n\n lastTrack = Track();\n if (modifiedFigure) {\n previousModels.push_back(previousModel);\n redoModels.clear();\n emit canUndoChanged();\n emit canRedoChanged();\n }\n repaint();\n}\nvoid Ui::ModelWidget::keyReleaseEvent(QKeyEvent *event) {\n if (event->key() == Qt::Key_Escape) {\n lastTrack = Track();\n trackIsCancelled = true;\n repaint();\n }\n if (event->key() == Qt::Key_Delete) {\n if (commitedModel.selectedFigure) {\n previousModels.push_back(commitedModel);\n redoModels.clear();\n for (auto it = commitedModel.begin(); it != commitedModel.end(); it++) {\n if (*it == commitedModel.selectedFigure) {\n commitedModel.removeFigure(it);\n break;\n }\n }\n emit canUndoChanged();\n emit canRedoChanged();\n repaint();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: %cling %s \"args(42)\" -Xclang -verify 2>&1 | FileCheck %s\n\n\/\/CHECK-NOT: {{.*error|warning|note:.*}}\n\nextern \"C\" int printf(const char* fmt, ...);\nvoid args(int I, const char* S = \"ArgString\") {\n printf(\"I=%d\\n\", I); \/\/ CHECK: I=42\n printf(\"S=%s\\n\", S); \/\/ CHECK: S=ArgString\n}\n\/\/ expected-no-diagnostics\n<commit_msg>We cannot pass in a 'proper' source location, thus we cannot use -verify.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: %cling %s \"args(42)\" 2>&1 | FileCheck %s\n\n\/\/CHECK-NOT: {{.*error|note:.*}}\n\/\/CHECK: warning: function 'args' cannot be called with no arguments.\nextern \"C\" int printf(const char* fmt, ...);\nvoid args(int I, const char* S = \"ArgString\") {\n printf(\"I=%d\\n\", I); \/\/ CHECK: I=42\n printf(\"S=%s\\n\", S); \/\/ CHECK: S=ArgString\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"codeccomparisonwindow.h\"\n#include \"ui_codeccomparisonwindow.h\"\n\nCodecComparisonWindow::CodecComparisonWindow(QWidget *parent)\n : QMainWindow(parent), ui(new Ui::CodecComparisonWindow) {\n ui->setupUi(this);\n\n initCodecs();\n initVlc();\n connectSlots();\n\n \/\/ prints probe output to standard output\n \/\/probeProcess.setProcessChannelMode(QProcess::ForwardedChannels);\n\n ui->frameTypes->setReadOnly(true);\n ui->tabWidget->setCurrentIndex(0);\n}\n\nCodecComparisonWindow::~CodecComparisonWindow() { delete ui; }\n\nvoid CodecComparisonWindow::closeEvent(QCloseEvent *event) {\n (void)event; \/\/ silence annoying warning\n streamingProcess.kill();\n probeProcess.kill();\n\n streamingProcess.waitForFinished();\n probeProcess.waitForFinished();\n}\n\nvoid CodecComparisonWindow::readOutput() {\n while (probeProcess.canReadLine()) {\n QString output = probeProcess.readLine();\n\n if (output.startsWith(\"pict_type=\")) {\n typesOfFrames.enqueue(output.toUtf8().constData()[10]);\n if (typesOfFrames.size() > 16)\n typesOfFrames.dequeue();\n\n QString currentFrameTypes;\n\n QListIterator<char> i(typesOfFrames);\n\n while (i.hasNext()) {\n currentFrameTypes.append(i.next());\n }\n\n ui->frameTypes->setText(currentFrameTypes);\n }\n }\n}\n\nQString CodecComparisonWindow::buildStreamingCommand(\n QString inputParameters, QString inputLocation,\n QVector<QString> outputPrameters, QVector<QString> outputLocations) {\n QStringList list;\n list << FFMPEG;\n list << inputParameters;\n list << \"-i \" << inputLocation;\n for (int i = 0;\n i < outputPrameters.length() && i < outputLocations.length(); i++) {\n list << outputPrameters[i] << outputLocations[i];\n }\n\n QString command = list.join(\" \");\n qDebug() << \"Produced the following encoding command:\\n\"\n << command.toUtf8().constData();\n return command;\n}\n\nQString CodecComparisonWindow::buildProbeCommand(QString location) {\n QStringList list;\n list << FFPROBE;\n list << location;\n list << \"-show_frames\";\n\n QString command = list.join(\" \");\n qDebug() << \"Produced the following probe command:\\n\"\n << command.toUtf8().constData();\n return command;\n}\n\nvoid CodecComparisonWindow::broadcast() {\n if (inputLocation.isEmpty()) {\n qDebug() << \"Input location is missing! Not starting player.\";\n return;\n }\n if (inputParameters.isEmpty()) {\n qDebug() << \"Input parameters are missing! Not starting player.\";\n return;\n }\n QString streamingParameters =\n codecManagers.at(ui->tabWidget->currentIndex())\n ->getStreamingParameters();\n if (streamingParameters.isEmpty()) {\n qDebug() << \"Encoding parameters are missing! Not starting player.\";\n return;\n }\n\n typesOfFrames.clear();\n ui->frameTypes->setText(\"\");\n\n qDebug() << \"Stopping the players...\";\n vlcPlayerRaw->stop();\n vlcPlayerEncoded->stop();\n\n qDebug() << \"Killing current encoding and probe processes...\";\n streamingProcess.kill();\n probeProcess.kill();\n\n streamingProcess.waitForFinished();\n probeProcess.waitForFinished();\n\n qDebug() << \"Starting the encoding process...\";\n QString streamingCommand = buildStreamingCommand(\n inputParameters, inputLocation,\n {\"-c:v copy -f nut -an\", streamingParameters},\n {RAW_VIDEO_PROTOCOL + \":\/\/\" + RAW_VIDEO_HOST + \":\" + RAW_VIDEO_PORT,\n ENCODED_VIDEO_PROTOCOL + \":\/\/\" + ENCODED_VIDEO_HOST + \":\" +\n ENCODED_VIDEO_PORT, VIDEO_PROBE_PROTOCOL + \":\/\/\" + VIDEO_PROBE_HOST + \":\" + VIDEO_PROBE_PORT});\n streamingProcess.start(streamingCommand);\n\n qDebug() << \"Starting the probe process...\";\n QString probeCommand =\n buildProbeCommand(VIDEO_PROBE_PROTOCOL + \":\/\/\" + VIDEO_PROBE_HOST +\n \":\" + VIDEO_PROBE_PORT);\n probeProcess.start(probeCommand);\n\n qDebug() << \"Starting the players...\";\n vlcPlayerRaw->setTime(0);\n vlcPlayerEncoded->setTime(0);\n vlcPlayerRaw->play();\n vlcPlayerEncoded->play();\n}\n\nvoid CodecComparisonWindow::on_actionOpenFile_triggered() {\n QString filePath = QFileDialog::getOpenFileName(\n this, tr(\"Open file\"), QDir::homePath(), tr(\"Multimedia files (*)\"),\n Q_NULLPTR, QFileDialog::DontUseNativeDialog);\n if (!filePath.isEmpty()) {\n inputParameters = \"-re\";\n inputLocation = \"\\\"\" + filePath + \"\\\"\";\n settingsChanged();\n }\n}\n\nvoid CodecComparisonWindow::on_actionOpenCamera_triggered() {\n#ifdef Q_OS_WIN\n inputParameters = \"-f dshow\";\n inputLocation = \"video=\\\"Lenovo EasyCamera\\\"\";\n settingsChanged();\n#else\n inputParameters = \"-f v4l2\";\n inputLocation = \"\/dev\/video0\";\n settingsChanged();\n#endif\n}\n\nvoid CodecComparisonWindow::initCodecs() {\n codecManagers.push_back(new MJPEGManager());\n codecManagers.push_back(new H261Manager());\n codecManagers.push_back(new MPEG1Manager());\n codecManagers.push_back(new MPEG2Manager());\n codecManagers.push_back(new H264Manager());\n codecManagers.push_back(new H265Manager());\n}\n\nvoid CodecComparisonWindow::initVlc() {\n vlcInstance = new VlcInstance(VlcCommon::args(), NULL);\n \/\/ vlcInstance->setLogLevel(Vlc::DisabledLevel);\n\n \/\/ Initialise raw video display\n vlcPlayerRaw = new VlcMediaPlayer(vlcInstance);\n vlcPlayerRaw->setVideoWidget(ui->rawVideo);\n vlcPlayerRaw->audio()->setMute(true);\n ui->rawVideo->setMediaPlayer(vlcPlayerRaw);\n vlcMediaRaw = new VlcMedia(RAW_VIDEO_PROTOCOL + \":\/\/@\" + RAW_VIDEO_HOST +\n \":\" + RAW_VIDEO_PORT,\n false, vlcInstance);\n vlcPlayerRaw->openOnly(vlcMediaRaw);\n\n \/\/ Initialise encoded video display\n vlcPlayerEncoded = new VlcMediaPlayer(vlcInstance);\n vlcPlayerEncoded->setVideoWidget(ui->encodedVideo);\n vlcPlayerEncoded->audio()->setMute(true);\n ui->encodedVideo->setMediaPlayer(vlcPlayerEncoded);\n vlcMediaEncoded =\n new VlcMedia(ENCODED_VIDEO_PROTOCOL + \":\/\/@\" + ENCODED_VIDEO_HOST +\n \":\" + ENCODED_VIDEO_PORT,\n false, vlcInstance);\n vlcPlayerEncoded->openOnly(vlcMediaEncoded);\n}\n\nvoid CodecComparisonWindow::connectSlots() {\n\n connect(this, &CodecComparisonWindow::settingsChanged, this,\n &CodecComparisonWindow::broadcast);\n connect(ui->tabWidget, &QTabWidget::currentChanged, this,\n &CodecComparisonWindow::broadcast);\n\n \/\/ Provide debug info for raw player\n connect(vlcPlayerRaw, &VlcMediaPlayer::stopped,\n []() { qDebug() << \"vlcPlayerRaw stopped\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::playing,\n []() { qDebug() << \"vlcPlayerRaw playing\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::paused,\n []() { qDebug() << \"vlcPlayerRaw paused\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::end,\n []() { qDebug() << \"vlcPlayerRaw end\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::error,\n []() { qDebug() << \"vlcPlayerRaw error\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::opening,\n []() { qDebug() << \"vlcPlayerRaw opening\"; });\n\n \/\/ Provide debug info for encoded player\n connect(vlcPlayerEncoded, &VlcMediaPlayer::stopped,\n []() { qDebug() << \"vlcPlayerEncoded stopped\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::playing,\n []() { qDebug() << \"vlcPlayerEncoded playing\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::paused,\n []() { qDebug() << \"vlcPlayerEncoded paused\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::end,\n []() { qDebug() << \"vlcPlayerEncoded end\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::error,\n []() { qDebug() << \"vlcPlayerEncoded error\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::opening,\n []() { qDebug() << \"vlcPlayerEncoded opening\"; });\n\n connect(&probeProcess, &QProcess::readyRead, this,\n &CodecComparisonWindow::readOutput);\n}\n<commit_msg>fixed frame types<commit_after>#include \"codeccomparisonwindow.h\"\n#include \"ui_codeccomparisonwindow.h\"\n\nCodecComparisonWindow::CodecComparisonWindow(QWidget *parent)\n : QMainWindow(parent), ui(new Ui::CodecComparisonWindow) {\n ui->setupUi(this);\n\n initCodecs();\n initVlc();\n connectSlots();\n\n \/\/ prints probe output to standard output\n \/\/probeProcess.setProcessChannelMode(QProcess::ForwardedChannels);\n\n ui->frameTypes->setReadOnly(true);\n ui->tabWidget->setCurrentIndex(0);\n}\n\nCodecComparisonWindow::~CodecComparisonWindow() { delete ui; }\n\nvoid CodecComparisonWindow::closeEvent(QCloseEvent *event) {\n (void)event; \/\/ silence annoying warning\n streamingProcess.kill();\n probeProcess.kill();\n\n streamingProcess.waitForFinished();\n probeProcess.waitForFinished();\n}\n\nvoid CodecComparisonWindow::readOutput() {\n while (probeProcess.canReadLine()) {\n QString output = probeProcess.readLine();\n\n if (output.startsWith(\"pict_type=\")) {\n typesOfFrames.enqueue(output.toUtf8().constData()[10]);\n if (typesOfFrames.size() > 16)\n typesOfFrames.dequeue();\n\n QString currentFrameTypes;\n\n QListIterator<char> i(typesOfFrames);\n\n while (i.hasNext()) {\n currentFrameTypes.append(i.next());\n }\n\n ui->frameTypes->setText(currentFrameTypes);\n }\n }\n}\n\nQString CodecComparisonWindow::buildStreamingCommand(\n QString inputParameters, QString inputLocation,\n QVector<QString> outputPrameters, QVector<QString> outputLocations) {\n QStringList list;\n list << FFMPEG;\n list << inputParameters;\n list << \"-i \" << inputLocation;\n for (int i = 0;\n i < outputPrameters.length() && i < outputLocations.length(); i++) {\n list << outputPrameters[i] << outputLocations[i];\n }\n\n QString command = list.join(\" \");\n qDebug() << \"Produced the following encoding command:\\n\"\n << command.toUtf8().constData();\n return command;\n}\n\nQString CodecComparisonWindow::buildProbeCommand(QString location) {\n QStringList list;\n list << FFPROBE;\n list << location;\n list << \"-show_frames\";\n\n QString command = list.join(\" \");\n qDebug() << \"Produced the following probe command:\\n\"\n << command.toUtf8().constData();\n return command;\n}\n\nvoid CodecComparisonWindow::broadcast() {\n if (inputLocation.isEmpty()) {\n qDebug() << \"Input location is missing! Not starting player.\";\n return;\n }\n if (inputParameters.isEmpty()) {\n qDebug() << \"Input parameters are missing! Not starting player.\";\n return;\n }\n QString streamingParameters =\n codecManagers.at(ui->tabWidget->currentIndex())\n ->getStreamingParameters();\n if (streamingParameters.isEmpty()) {\n qDebug() << \"Encoding parameters are missing! Not starting player.\";\n return;\n }\n\n typesOfFrames.clear();\n ui->frameTypes->setText(\"\");\n\n qDebug() << \"Stopping the players...\";\n vlcPlayerRaw->stop();\n vlcPlayerEncoded->stop();\n\n qDebug() << \"Killing current encoding and probe processes...\";\n streamingProcess.kill();\n probeProcess.kill();\n\n streamingProcess.waitForFinished();\n probeProcess.waitForFinished();\n\n qDebug() << \"Starting the encoding process...\";\n QString streamingCommand = buildStreamingCommand(\n inputParameters, inputLocation,\n {\"-c:v copy -f nut -an\", streamingParameters, streamingParameters},\n {RAW_VIDEO_PROTOCOL + \":\/\/\" + RAW_VIDEO_HOST + \":\" + RAW_VIDEO_PORT,\n ENCODED_VIDEO_PROTOCOL + \":\/\/\" + ENCODED_VIDEO_HOST + \":\" + ENCODED_VIDEO_PORT,\n VIDEO_PROBE_PROTOCOL + \":\/\/\" + VIDEO_PROBE_HOST + \":\" + VIDEO_PROBE_PORT});\n streamingProcess.start(streamingCommand);\n\n qDebug() << \"Starting the probe process...\";\n QString probeCommand =\n buildProbeCommand(VIDEO_PROBE_PROTOCOL + \":\/\/\" + VIDEO_PROBE_HOST +\n \":\" + VIDEO_PROBE_PORT);\n probeProcess.start(probeCommand);\n\n qDebug() << \"Starting the players...\";\n vlcPlayerRaw->setTime(0);\n vlcPlayerEncoded->setTime(0);\n vlcPlayerRaw->play();\n vlcPlayerEncoded->play();\n}\n\nvoid CodecComparisonWindow::on_actionOpenFile_triggered() {\n QString filePath = QFileDialog::getOpenFileName(\n this, tr(\"Open file\"), QDir::homePath(), tr(\"Multimedia files (*)\"),\n Q_NULLPTR, QFileDialog::DontUseNativeDialog);\n if (!filePath.isEmpty()) {\n inputParameters = \"-re\";\n inputLocation = \"\\\"\" + filePath + \"\\\"\";\n settingsChanged();\n }\n}\n\nvoid CodecComparisonWindow::on_actionOpenCamera_triggered() {\n#ifdef Q_OS_WIN\n inputParameters = \"-f dshow\";\n inputLocation = \"video=\\\"Lenovo EasyCamera\\\"\";\n settingsChanged();\n#else\n inputParameters = \"-f v4l2\";\n inputLocation = \"\/dev\/video0\";\n settingsChanged();\n#endif\n}\n\nvoid CodecComparisonWindow::initCodecs() {\n codecManagers.push_back(new MJPEGManager());\n codecManagers.push_back(new H261Manager());\n codecManagers.push_back(new MPEG1Manager());\n codecManagers.push_back(new MPEG2Manager());\n codecManagers.push_back(new H264Manager());\n codecManagers.push_back(new H265Manager());\n}\n\nvoid CodecComparisonWindow::initVlc() {\n vlcInstance = new VlcInstance(VlcCommon::args(), NULL);\n \/\/ vlcInstance->setLogLevel(Vlc::DisabledLevel);\n\n \/\/ Initialise raw video display\n vlcPlayerRaw = new VlcMediaPlayer(vlcInstance);\n vlcPlayerRaw->setVideoWidget(ui->rawVideo);\n vlcPlayerRaw->audio()->setMute(true);\n ui->rawVideo->setMediaPlayer(vlcPlayerRaw);\n vlcMediaRaw = new VlcMedia(RAW_VIDEO_PROTOCOL + \":\/\/@\" + RAW_VIDEO_HOST +\n \":\" + RAW_VIDEO_PORT,\n false, vlcInstance);\n vlcPlayerRaw->openOnly(vlcMediaRaw);\n\n \/\/ Initialise encoded video display\n vlcPlayerEncoded = new VlcMediaPlayer(vlcInstance);\n vlcPlayerEncoded->setVideoWidget(ui->encodedVideo);\n vlcPlayerEncoded->audio()->setMute(true);\n ui->encodedVideo->setMediaPlayer(vlcPlayerEncoded);\n vlcMediaEncoded =\n new VlcMedia(ENCODED_VIDEO_PROTOCOL + \":\/\/@\" + ENCODED_VIDEO_HOST +\n \":\" + ENCODED_VIDEO_PORT,\n false, vlcInstance);\n vlcPlayerEncoded->openOnly(vlcMediaEncoded);\n}\n\nvoid CodecComparisonWindow::connectSlots() {\n\n connect(this, &CodecComparisonWindow::settingsChanged, this,\n &CodecComparisonWindow::broadcast);\n connect(ui->tabWidget, &QTabWidget::currentChanged, this,\n &CodecComparisonWindow::broadcast);\n\n \/\/ Provide debug info for raw player\n connect(vlcPlayerRaw, &VlcMediaPlayer::stopped,\n []() { qDebug() << \"vlcPlayerRaw stopped\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::playing,\n []() { qDebug() << \"vlcPlayerRaw playing\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::paused,\n []() { qDebug() << \"vlcPlayerRaw paused\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::end,\n []() { qDebug() << \"vlcPlayerRaw end\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::error,\n []() { qDebug() << \"vlcPlayerRaw error\"; });\n connect(vlcPlayerRaw, &VlcMediaPlayer::opening,\n []() { qDebug() << \"vlcPlayerRaw opening\"; });\n\n \/\/ Provide debug info for encoded player\n connect(vlcPlayerEncoded, &VlcMediaPlayer::stopped,\n []() { qDebug() << \"vlcPlayerEncoded stopped\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::playing,\n []() { qDebug() << \"vlcPlayerEncoded playing\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::paused,\n []() { qDebug() << \"vlcPlayerEncoded paused\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::end,\n []() { qDebug() << \"vlcPlayerEncoded end\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::error,\n []() { qDebug() << \"vlcPlayerEncoded error\"; });\n connect(vlcPlayerEncoded, &VlcMediaPlayer::opening,\n []() { qDebug() << \"vlcPlayerEncoded opening\"; });\n\n connect(&probeProcess, &QProcess::readyRead, this,\n &CodecComparisonWindow::readOutput);\n}\n<|endoftext|>"} {"text":"<commit_before>\n#ifndef Entity_HH_\n#define Entity_HH_\n\n#include <map>\n\n#include \"Core\/Input.hh\"\n#include \"Core\/Timer.hh\"\n#include \"Utils\/SmartPointer.hh\"\n#include \"OpenGL\/Shader.hh\"\n#include \"Utils\/Barcode.h\"\n#include \"Utils\/PubSub.hpp\"\n#include \"glm\/glm.hpp\"\n#include <Components\/Component.hh>\n\nclass AScene;\nclass EntityManager;\nclass Entity;\n\nclass EntityData : public PubSub\n{\nprivate:\n\tstatic size_t \t\t\t\t\t_currentId;\n\tEntity _handle;\npublic:\n\tenum\tGetFlags\n\t{\n\t\tONLY_THIS_FLAGS,\n\t\tTHIS_FLAGS,\n\t\tNOT_THIS_FLAGS\n\t};\n\n\tenum\tEntityFlags\n\t{\n\t\tHAS_MOVED = 1,\n\t\tACTIVE = 2,\n\n\t};\n\n\ttypedef std::vector<SmartPointer<Component::Base> >\tt_ComponentsList;\n\n\tEntity &getHandle();\n\tvoid setHandle(Entity &handle);\n\nprivate:\n\tAScene *_scene;\n\tsize_t \t\t\t\t_flags;\n\n\tglm::mat4 \t\t\t_localTransform;\n\tglm::mat4 \t\t\t_globalTransform;\n\n\tglm::vec3 _localRotation;\n\tglm::vec3 _localScale;\n\tglm::vec3 _localTranslation;\n\n\tglm::vec3 _globalRotation;\n\tglm::vec3 _globalScale;\n\tglm::vec3 _globalTranslation;\n\n\tt_ComponentsList\t_components;\n\n\tBarcode _code;\npublic:\n\tEntityData(AScene *scene);\n\tvirtual ~EntityData();\n\n\tAScene *getScene() const;\n\tvoid translate(const glm::vec3 &v);\n\tvoid setTranslation(const glm::vec3 &v);\n\tglm::vec3 const &getTranslation() const;\n\tvoid rotate(const glm::vec3 &v);\n\tvoid setRotation(const glm::vec3 &v);\n\tglm::vec3 const &getRotation() const;\n\tvoid scale(const glm::vec3 &v);\n\tvoid setScale(const glm::vec3 &v);\n\tglm::vec3 const &getScale() const;\n\n\n\tglm::mat4 const \t\t&getLocalTransform();\n\t\/\/ TO DELETE\n\tglm::mat4 \t\t\t&setLocalTransform(); \/\/ <-- \/\/\n\n\tglm::mat4 const\t\t\t&getGlobalTransform() const;\n\t\/\/ TO DELETE\n\tvoid \t\t\t\t\tcomputeGlobalTransform(glm::mat4 const &fatherTransform); \/\/ <-- \/\/\n\tvoid computeGlobalTransform(const Entity &parent);\n\n\tsize_t \t\t\t\t\tgetFlags() const;\n\tvoid \t\t\t\t\tsetFlags(size_t flags);\n\tvoid \t\t\t\t\taddFlags(size_t flags);\n\tvoid \t\t\t\t\tremoveFlags(size_t flags);\n\n\tBarcode &getCode();\n\tvoid reset();\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\n\t\/\/\n\t\/\/ COMPONENTS OPERATIONS\n\t\/\/\n\t\/\/\n\t\/\/\n\tbool hasComponent(unsigned int componentId) const;\n\n\ttemplate <typename T>\n\tbool hasComponent() const\n\t{\n\t\treturn _code.isSet<T>();\n\t}\n\n\ttemplate <typename T, typename... Args>\n\tSmartPointer<T> addComponent(Args ...args)\n\t{\n\t\t\/\/ get the component type ID\n\t\tunsigned int id = T::getTypeId();\n\n\t\tauto a = _code.isEmpty();\n\n\t\t\/\/ if entity already have component, return it\n\t\tif (hasComponent(id))\n\t\t{\n\t\t\treturn static_cast<SmartPointer<T> >(_components[id]);\n\t\t}\n\t\t\/\/ else if entity components array is to small, resize it\n\t\telse if (_components.size() <= id)\n\t\t{\n\t\t\t_components.resize(id + 1);\n\t\t}\n\t\t\/\/ if component has never been created, create one\n\t\tif (!_components[id].get())\n\t\t{\n\t\t\t_components[id] = new T();\n\t\t\tassert(_components[id].get() != nullptr && \"Memory error : Component creation failed.\");\n\t\t\t_components[id]->setEntity(getHandle());\n\t\t}\n\t\t\/\/init component\n\t\tstatic_cast<SmartPointer<T> >(_components[id])->init(args...);\n\t\t_code.add(id);\n\t\tbroadCast(std::string(\"componentAdded\" + std::to_string(id)), _handle);\n\t\treturn static_cast<SmartPointer<T> >(_components[id]);\n\t}\n\n\ttemplate <typename T>\n\tSmartPointer<T> getComponent() const\n\t{\n\t\tunsigned int id = T::getTypeId();\n\t\tif (!hasComponent(id))\n\t\t\treturn nullptr;\n\t\treturn static_cast<SmartPointer<T> >(_components[id]);\n\t}\n\n\ttemplate <typename T>\n\tvoid removeComponent()\n\t{\n\t\tunsigned int id = T::getTypeId();\n\t\tif (!hasComponent(id))\n\t\t\treturn;\n\t\t_code.remove(id);\n\/\/\t\t_components[id]\t= nullptr;\n\t\t_components[id].get()->reset();\n\t\tbroadCast(std::string(\"componentRemoved\" + std::to_string(id)), _handle);\n\t\t\/\/ component remove -> signal to system\n\t}\n\n\ttemplate <class Archive>\n\tvoid save(Archive &ar) const\n\t{\n\t\tunsigned int cptNumber = 0;\n\t\tfor (auto &e : _components)\n\t\t{\n\t\t\tif (!e.get())\n\t\t\t\tcontinue;\n\t\t\t++cptNumber;\n\t\t}\n\t\tar(cereal::make_nvp(\"component_number\", cptNumber));\n\t\tfor (auto &e : _components)\n\t\t{\n\t\t\tif (!e.get())\n\t\t\t\tcontinue;\n\/\/\t\t\tar(*e.get());\n\t\t\te->serialize(ar);\n\t\t}\n\t}\n\n\ttemplate <class Archive>\n\tvoid load(Archive &ar) const\n\t{\n\t\tunsigned int cptNumber = 0;\n\t\tar(cptNumber);\n\t\tfor (unsigned int i = 0; i < cptNumber; ++i)\n\t\t{\n\t\t\tstd::size_t type = 0;\n\t\t\tunsigned int typeId;\n\t\t\tar(type);\n\t\t\tunsigned int position;\n\t\t\tComponent::Base *cpt = _scene->createFromType(type, ar, _handle, typeId);\n\t\t\tcpt->setEntity(_handle);\n\t\t\tif (_handle.get()->_components.size() <= typeId)\n\t\t\t\t_handle.get()->_components.resize(typeId + 1);\n\t\t\t_handle.get()->_components[typeId] = SmartPointer<Component::Base>(cpt);\n\t\t\t_handle.get()->_code.add(typeId);\n\t\t\tbroadCast(std::string(\"componentAdded\" + std::to_string(typeId)), _handle);\n\t\t}\n\t\tstd::cout << \"lol\" << std::endl;\n\t}\n\n};\n\n#endif<commit_msg>Flags and transformations added to Entity serialization #37 # 38<commit_after>\n#ifndef Entity_HH_\n#define Entity_HH_\n\n#include <map>\n\n#include \"Core\/Input.hh\"\n#include \"Core\/Timer.hh\"\n#include \"Utils\/SmartPointer.hh\"\n#include \"OpenGL\/Shader.hh\"\n#include \"Utils\/Barcode.h\"\n#include \"Utils\/PubSub.hpp\"\n#include \"glm\/glm.hpp\"\n#include <Components\/Component.hh>\n#include <Utils\/GlmSerialization.hpp>\n\nclass AScene;\nclass EntityManager;\nclass Entity;\n\nclass EntityData : public PubSub\n{\nprivate:\n\tstatic size_t \t\t\t\t\t_currentId;\n\tEntity _handle;\npublic:\n\tenum\tGetFlags\n\t{\n\t\tONLY_THIS_FLAGS,\n\t\tTHIS_FLAGS,\n\t\tNOT_THIS_FLAGS\n\t};\n\n\tenum\tEntityFlags\n\t{\n\t\tHAS_MOVED = 1,\n\t\tACTIVE = 2,\n\n\t};\n\n\ttypedef std::vector<SmartPointer<Component::Base> >\tt_ComponentsList;\n\n\tEntity &getHandle();\n\tvoid setHandle(Entity &handle);\n\nprivate:\n\tAScene *_scene;\n\tsize_t \t\t\t\t_flags;\n\n\tglm::mat4 \t\t\t_localTransform;\n\tglm::mat4 \t\t\t_globalTransform;\n\n\tglm::vec3 _localRotation;\n\tglm::vec3 _localScale;\n\tglm::vec3 _localTranslation;\n\n\tglm::vec3 _globalRotation;\n\tglm::vec3 _globalScale;\n\tglm::vec3 _globalTranslation;\n\n\tt_ComponentsList\t_components;\n\n\tBarcode _code;\npublic:\n\tEntityData(AScene *scene);\n\tvirtual ~EntityData();\n\n\tAScene *getScene() const;\n\tvoid translate(const glm::vec3 &v);\n\tvoid setTranslation(const glm::vec3 &v);\n\tglm::vec3 const &getTranslation() const;\n\tvoid rotate(const glm::vec3 &v);\n\tvoid setRotation(const glm::vec3 &v);\n\tglm::vec3 const &getRotation() const;\n\tvoid scale(const glm::vec3 &v);\n\tvoid setScale(const glm::vec3 &v);\n\tglm::vec3 const &getScale() const;\n\n\n\tglm::mat4 const \t\t&getLocalTransform();\n\t\/\/ TO DELETE\n\tglm::mat4 \t\t\t&setLocalTransform(); \/\/ <-- \/\/\n\n\tglm::mat4 const\t\t\t&getGlobalTransform() const;\n\t\/\/ TO DELETE\n\tvoid \t\t\t\t\tcomputeGlobalTransform(glm::mat4 const &fatherTransform); \/\/ <-- \/\/\n\tvoid computeGlobalTransform(const Entity &parent);\n\n\tsize_t \t\t\t\t\tgetFlags() const;\n\tvoid \t\t\t\t\tsetFlags(size_t flags);\n\tvoid \t\t\t\t\taddFlags(size_t flags);\n\tvoid \t\t\t\t\tremoveFlags(size_t flags);\n\n\tBarcode &getCode();\n\tvoid reset();\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\n\t\/\/\n\t\/\/ COMPONENTS OPERATIONS\n\t\/\/\n\t\/\/\n\t\/\/\n\tbool hasComponent(unsigned int componentId) const;\n\n\ttemplate <typename T>\n\tbool hasComponent() const\n\t{\n\t\treturn _code.isSet<T>();\n\t}\n\n\ttemplate <typename T, typename... Args>\n\tSmartPointer<T> addComponent(Args ...args)\n\t{\n\t\t\/\/ get the component type ID\n\t\tunsigned int id = T::getTypeId();\n\n\t\tauto a = _code.isEmpty();\n\n\t\t\/\/ if entity already have component, return it\n\t\tif (hasComponent(id))\n\t\t{\n\t\t\treturn static_cast<SmartPointer<T> >(_components[id]);\n\t\t}\n\t\t\/\/ else if entity components array is to small, resize it\n\t\telse if (_components.size() <= id)\n\t\t{\n\t\t\t_components.resize(id + 1);\n\t\t}\n\t\t\/\/ if component has never been created, create one\n\t\tif (!_components[id].get())\n\t\t{\n\t\t\t_components[id] = new T();\n\t\t\tassert(_components[id].get() != nullptr && \"Memory error : Component creation failed.\");\n\t\t\t_components[id]->setEntity(getHandle());\n\t\t}\n\t\t\/\/init component\n\t\tstatic_cast<SmartPointer<T> >(_components[id])->init(args...);\n\t\t_code.add(id);\n\t\tbroadCast(std::string(\"componentAdded\" + std::to_string(id)), _handle);\n\t\treturn static_cast<SmartPointer<T> >(_components[id]);\n\t}\n\n\ttemplate <typename T>\n\tSmartPointer<T> getComponent() const\n\t{\n\t\tunsigned int id = T::getTypeId();\n\t\tif (!hasComponent(id))\n\t\t\treturn nullptr;\n\t\treturn static_cast<SmartPointer<T> >(_components[id]);\n\t}\n\n\ttemplate <typename T>\n\tvoid removeComponent()\n\t{\n\t\tunsigned int id = T::getTypeId();\n\t\tif (!hasComponent(id))\n\t\t\treturn;\n\t\t_code.remove(id);\n\/\/\t\t_components[id]\t= nullptr;\n\t\t_components[id].get()->reset();\n\t\tbroadCast(std::string(\"componentRemoved\" + std::to_string(id)), _handle);\n\t\t\/\/ component remove -> signal to system\n\t}\n\n\ttemplate <class Archive>\n\tvoid save(Archive &ar) const\n\t{\n\t\t\/\/ Save Entity informations\n\t\tar(cereal::make_nvp(\"flags\", _flags),\n\t\t\tcereal::make_nvp(\"localTransform\", _localTransform),\n\t\t\tcereal::make_nvp(\"globalTransform\", _globalTransform));\n\n\t\t\/\/ Save Entity Components\n\t\tunsigned int cptNumber = 0;\n\t\tfor (auto &e : _components)\n\t\t{\n\t\t\tif (!e.get())\n\t\t\t\tcontinue;\n\t\t\t++cptNumber;\n\t\t}\n\t\tar(cereal::make_nvp(\"component_number\", cptNumber));\n\t\tfor (auto &e : _components)\n\t\t{\n\t\t\tif (!e.get())\n\t\t\t\tcontinue;\n\/\/\t\t\tar(*e.get());\n\t\t\te->serialize(ar);\n\t\t}\n\t}\n\n\ttemplate <class Archive>\n\tvoid load(Archive &ar)\n\t{\n\t\t\/\/ load Entity informations\n\t\tar(_flags, _localTransform, _globalTransform);\n\t\tunsigned int cptNumber = 0;\n\t\tar(cptNumber);\n\t\tfor (unsigned int i = 0; i < cptNumber; ++i)\n\t\t{\n\t\t\tstd::size_t type = 0;\n\t\t\tunsigned int typeId;\n\t\t\tar(type);\n\t\t\tunsigned int position;\n\t\t\tComponent::Base *cpt = _scene->createFromType(type, ar, _handle, typeId);\n\t\t\tcpt->setEntity(_handle);\n\t\t\tif (_components.size() <= typeId)\n\t\t\t\t_components.resize(typeId + 1);\n\t\t\t_components[typeId] = SmartPointer<Component::Base>(cpt);\n\t\t\t_code.add(typeId);\n\t\t\tbroadCast(std::string(\"componentAdded\" + std::to_string(typeId)), _handle);\n\t\t}\n\t\tstd::cout << \"lol\" << std::endl;\n\t}\n\n};\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"webkit\/plugins\/ppapi\/ppb_url_request_info_impl.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/http\/http_util.h\"\n#include \"ppapi\/c\/pp_var.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebData.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebHTTPBody.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURL.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURLRequest.h\"\n#include \"webkit\/plugins\/ppapi\/common.h\"\n#include \"webkit\/plugins\/ppapi\/plugin_module.h\"\n#include \"webkit\/plugins\/ppapi\/ppb_file_ref_impl.h\"\n#include \"webkit\/plugins\/ppapi\/string.h\"\n#include \"webkit\/plugins\/ppapi\/var.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nusing WebKit::WebData;\nusing WebKit::WebHTTPBody;\nusing WebKit::WebString;\nusing WebKit::WebFrame;\nusing WebKit::WebURL;\nusing WebKit::WebURLRequest;\n\nnamespace webkit {\nnamespace ppapi {\n\nnamespace {\n\n\/\/ If any of these request headers are specified, they will not be sent.\n\/\/ TODO(darin): Add more based on security considerations?\nconst char* const kIgnoredRequestHeaders[] = {\n \"content-length\"\n};\n\nPP_Bool IsIgnoredRequestHeader(const std::string& name) {\n for (size_t i = 0; i < arraysize(kIgnoredRequestHeaders); ++i) {\n if (LowerCaseEqualsASCII(name, kIgnoredRequestHeaders[i]))\n return PP_TRUE;\n }\n return PP_FALSE;\n}\n\nPP_Resource Create(PP_Module module_id) {\n PluginModule* module = ResourceTracker::Get()->GetModule(module_id);\n if (!module)\n return 0;\n\n PPB_URLRequestInfo_Impl* request = new PPB_URLRequestInfo_Impl(module);\n\n return request->GetReference();\n}\n\nPP_Bool IsURLRequestInfo(PP_Resource resource) {\n return BoolToPPBool(!!Resource::GetAs<PPB_URLRequestInfo_Impl>(resource));\n}\n\nPP_Bool SetProperty(PP_Resource request_id,\n PP_URLRequestProperty property,\n PP_Var var) {\n scoped_refptr<PPB_URLRequestInfo_Impl> request(\n Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));\n if (!request)\n return PP_FALSE;\n\n if (var.type == PP_VARTYPE_BOOL) {\n return BoolToPPBool(\n request->SetBooleanProperty(property,\n PPBoolToBool(var.value.as_bool)));\n }\n\n if (var.type == PP_VARTYPE_STRING) {\n scoped_refptr<StringVar> string(StringVar::FromPPVar(var));\n if (string) {\n return BoolToPPBool(request->SetStringProperty(property,\n string->value()));\n }\n }\n\n return PP_FALSE;\n}\n\nPP_Bool AppendDataToBody(PP_Resource request_id,\n const char* data,\n uint32_t len) {\n scoped_refptr<PPB_URLRequestInfo_Impl> request(\n Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));\n if (!request)\n return PP_FALSE;\n\n return BoolToPPBool(request->AppendDataToBody(std::string(data, len)));\n}\n\nPP_Bool AppendFileToBody(PP_Resource request_id,\n PP_Resource file_ref_id,\n int64_t start_offset,\n int64_t number_of_bytes,\n PP_Time expected_last_modified_time) {\n scoped_refptr<PPB_URLRequestInfo_Impl> request(\n Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));\n if (!request)\n return PP_FALSE;\n\n scoped_refptr<PPB_FileRef_Impl> file_ref(\n Resource::GetAs<PPB_FileRef_Impl>(file_ref_id));\n if (!file_ref)\n return PP_FALSE;\n\n return BoolToPPBool(request->AppendFileToBody(file_ref,\n start_offset,\n number_of_bytes,\n expected_last_modified_time));\n}\n\nconst PPB_URLRequestInfo ppb_urlrequestinfo = {\n &Create,\n &IsURLRequestInfo,\n &SetProperty,\n &AppendDataToBody,\n &AppendFileToBody\n};\n\n} \/\/ namespace\n\nstruct PPB_URLRequestInfo_Impl::BodyItem {\n BodyItem(const std::string& data)\n : data(data),\n start_offset(0),\n number_of_bytes(-1),\n expected_last_modified_time(0.0) {\n }\n\n BodyItem(PPB_FileRef_Impl* file_ref,\n int64_t start_offset,\n int64_t number_of_bytes,\n PP_Time expected_last_modified_time)\n : file_ref(file_ref),\n start_offset(start_offset),\n number_of_bytes(number_of_bytes),\n expected_last_modified_time(expected_last_modified_time) {\n }\n\n std::string data;\n scoped_refptr<PPB_FileRef_Impl> file_ref;\n int64_t start_offset;\n int64_t number_of_bytes;\n PP_Time expected_last_modified_time;\n};\n\nPPB_URLRequestInfo_Impl::PPB_URLRequestInfo_Impl(PluginModule* module)\n : Resource(module),\n stream_to_file_(false),\n follow_redirects_(true),\n record_download_progress_(false),\n record_upload_progress_(false) {\n}\n\nPPB_URLRequestInfo_Impl::~PPB_URLRequestInfo_Impl() {\n}\n\n\/\/ static\nconst PPB_URLRequestInfo* PPB_URLRequestInfo_Impl::GetInterface() {\n return &ppb_urlrequestinfo;\n}\n\nPPB_URLRequestInfo_Impl* PPB_URLRequestInfo_Impl::AsPPB_URLRequestInfo_Impl() {\n return this;\n}\n\nbool PPB_URLRequestInfo_Impl::SetBooleanProperty(PP_URLRequestProperty property,\n bool value) {\n switch (property) {\n case PP_URLREQUESTPROPERTY_STREAMTOFILE:\n stream_to_file_ = value;\n return true;\n case PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS:\n follow_redirects_ = value;\n return true;\n case PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS:\n record_download_progress_ = value;\n return true;\n case PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS:\n record_upload_progress_ = value;\n return true;\n default:\n \/\/NOTIMPLEMENTED(); \/\/ TODO(darin): Implement me!\n return false;\n }\n}\n\nbool PPB_URLRequestInfo_Impl::SetStringProperty(PP_URLRequestProperty property,\n const std::string& value) {\n \/\/ TODO(darin): Validate input. Perhaps at a different layer?\n switch (property) {\n case PP_URLREQUESTPROPERTY_URL:\n url_ = value; \/\/ NOTE: This may be a relative URL.\n return true;\n case PP_URLREQUESTPROPERTY_METHOD:\n method_ = value;\n return true;\n case PP_URLREQUESTPROPERTY_HEADERS:\n headers_ = value;\n return true;\n default:\n return false;\n }\n}\n\nbool PPB_URLRequestInfo_Impl::AppendDataToBody(const std::string& data) {\n if (!data.empty())\n body_.push_back(BodyItem(data));\n return true;\n}\n\nbool PPB_URLRequestInfo_Impl::AppendFileToBody(\n PPB_FileRef_Impl* file_ref,\n int64_t start_offset,\n int64_t number_of_bytes,\n PP_Time expected_last_modified_time) {\n \/\/ Ignore a call to append nothing.\n if (number_of_bytes == 0)\n return true;\n\n \/\/ Check for bad values. (-1 means read until end of file.)\n if (start_offset < 0 || number_of_bytes < -1)\n return false;\n\n body_.push_back(BodyItem(file_ref,\n start_offset,\n number_of_bytes,\n expected_last_modified_time));\n return true;\n}\n\nWebURLRequest PPB_URLRequestInfo_Impl::ToWebURLRequest(WebFrame* frame) const {\n WebURLRequest web_request;\n web_request.initialize();\n web_request.setURL(frame->document().completeURL(WebString::fromUTF8(url_)));\n web_request.setDownloadToFile(stream_to_file_);\n\n if (!method_.empty())\n web_request.setHTTPMethod(WebString::fromUTF8(method_));\n\n if (!headers_.empty()) {\n net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(), \"\\n\");\n while (it.GetNext()) {\n if (!IsIgnoredRequestHeader(it.name())) {\n web_request.addHTTPHeaderField(\n WebString::fromUTF8(it.name()),\n WebString::fromUTF8(it.values()));\n }\n }\n }\n\n if (!body_.empty()) {\n WebHTTPBody http_body;\n http_body.initialize();\n for (size_t i = 0; i < body_.size(); ++i) {\n if (body_[i].file_ref) {\n http_body.appendFileRange(\n webkit_glue::FilePathToWebString(\n body_[i].file_ref->GetSystemPath()),\n body_[i].start_offset,\n body_[i].number_of_bytes,\n body_[i].expected_last_modified_time);\n } else {\n DCHECK(!body_[i].data.empty());\n http_body.appendData(WebData(body_[i].data));\n }\n }\n web_request.setHTTPBody(http_body);\n }\n\n frame->setReferrerForRequest(web_request, WebURL()); \/\/ Use default.\n return web_request;\n}\n\n} \/\/ namespace ppapi\n} \/\/ namespace webkit\n\n<commit_msg>Restrict HTTP headers by checking in URLRequestInfo::SetProperty. BUG=47354 TEST=none Review URL: http:\/\/codereview.chromium.org\/5138010<commit_after>\/\/ Copyright (c) 2010 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 \"webkit\/plugins\/ppapi\/ppb_url_request_info_impl.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/http\/http_util.h\"\n#include \"ppapi\/c\/pp_var.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebData.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebHTTPBody.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURL.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURLRequest.h\"\n#include \"webkit\/plugins\/ppapi\/common.h\"\n#include \"webkit\/plugins\/ppapi\/plugin_module.h\"\n#include \"webkit\/plugins\/ppapi\/ppb_file_ref_impl.h\"\n#include \"webkit\/plugins\/ppapi\/string.h\"\n#include \"webkit\/plugins\/ppapi\/var.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nusing WebKit::WebData;\nusing WebKit::WebHTTPBody;\nusing WebKit::WebString;\nusing WebKit::WebFrame;\nusing WebKit::WebURL;\nusing WebKit::WebURLRequest;\n\nnamespace webkit {\nnamespace ppapi {\n\nnamespace {\n\n\/\/ A header string containing any of the following fields will cause\n\/\/ an error. The list comes from the XMLHttpRequest standard.\n\/\/ http:\/\/www.w3.org\/TR\/XMLHttpRequest\/#the-setrequestheader-method\nconst char* const kForbiddenHeaderFields[] = {\n \"accept-charset\",\n \"accept-encoding\",\n \"connection\",\n \"content-length\",\n \"cookie\",\n \"cookie2\",\n \"content-transfer-encoding\",\n \"date\",\n \"expect\",\n \"host\",\n \"keep-alive\",\n \"origin\",\n \"referer\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"user-agent\",\n \"via\",\n};\n\nbool IsValidHeaderField(const std::string& name) {\n for (size_t i = 0; i < arraysize(kForbiddenHeaderFields); ++i) {\n if (LowerCaseEqualsASCII(name, kForbiddenHeaderFields[i]))\n return false;\n }\n if (StartsWithASCII(name, \"proxy-\", false))\n return false;\n if (StartsWithASCII(name, \"sec-\", false))\n return false;\n\n return true;\n}\n\nbool AreValidHeaders(const std::string& headers) {\n net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), \"\\n\");\n while (it.GetNext()) {\n if (!IsValidHeaderField(it.name()))\n return false;\n }\n return true;\n}\n\nPP_Resource Create(PP_Module module_id) {\n PluginModule* module = ResourceTracker::Get()->GetModule(module_id);\n if (!module)\n return 0;\n\n PPB_URLRequestInfo_Impl* request = new PPB_URLRequestInfo_Impl(module);\n\n return request->GetReference();\n}\n\nPP_Bool IsURLRequestInfo(PP_Resource resource) {\n return BoolToPPBool(!!Resource::GetAs<PPB_URLRequestInfo_Impl>(resource));\n}\n\nPP_Bool SetProperty(PP_Resource request_id,\n PP_URLRequestProperty property,\n PP_Var var) {\n scoped_refptr<PPB_URLRequestInfo_Impl> request(\n Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));\n if (!request)\n return PP_FALSE;\n\n if (var.type == PP_VARTYPE_BOOL) {\n return BoolToPPBool(\n request->SetBooleanProperty(property,\n PPBoolToBool(var.value.as_bool)));\n }\n\n if (var.type == PP_VARTYPE_STRING) {\n scoped_refptr<StringVar> string(StringVar::FromPPVar(var));\n if (string) {\n return BoolToPPBool(request->SetStringProperty(property,\n string->value()));\n }\n }\n\n return PP_FALSE;\n}\n\nPP_Bool AppendDataToBody(PP_Resource request_id,\n const char* data,\n uint32_t len) {\n scoped_refptr<PPB_URLRequestInfo_Impl> request(\n Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));\n if (!request)\n return PP_FALSE;\n\n return BoolToPPBool(request->AppendDataToBody(std::string(data, len)));\n}\n\nPP_Bool AppendFileToBody(PP_Resource request_id,\n PP_Resource file_ref_id,\n int64_t start_offset,\n int64_t number_of_bytes,\n PP_Time expected_last_modified_time) {\n scoped_refptr<PPB_URLRequestInfo_Impl> request(\n Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));\n if (!request)\n return PP_FALSE;\n\n scoped_refptr<PPB_FileRef_Impl> file_ref(\n Resource::GetAs<PPB_FileRef_Impl>(file_ref_id));\n if (!file_ref)\n return PP_FALSE;\n\n return BoolToPPBool(request->AppendFileToBody(file_ref,\n start_offset,\n number_of_bytes,\n expected_last_modified_time));\n}\n\nconst PPB_URLRequestInfo ppb_urlrequestinfo = {\n &Create,\n &IsURLRequestInfo,\n &SetProperty,\n &AppendDataToBody,\n &AppendFileToBody\n};\n\n} \/\/ namespace\n\nstruct PPB_URLRequestInfo_Impl::BodyItem {\n BodyItem(const std::string& data)\n : data(data),\n start_offset(0),\n number_of_bytes(-1),\n expected_last_modified_time(0.0) {\n }\n\n BodyItem(PPB_FileRef_Impl* file_ref,\n int64_t start_offset,\n int64_t number_of_bytes,\n PP_Time expected_last_modified_time)\n : file_ref(file_ref),\n start_offset(start_offset),\n number_of_bytes(number_of_bytes),\n expected_last_modified_time(expected_last_modified_time) {\n }\n\n std::string data;\n scoped_refptr<PPB_FileRef_Impl> file_ref;\n int64_t start_offset;\n int64_t number_of_bytes;\n PP_Time expected_last_modified_time;\n};\n\nPPB_URLRequestInfo_Impl::PPB_URLRequestInfo_Impl(PluginModule* module)\n : Resource(module),\n stream_to_file_(false),\n follow_redirects_(true),\n record_download_progress_(false),\n record_upload_progress_(false) {\n}\n\nPPB_URLRequestInfo_Impl::~PPB_URLRequestInfo_Impl() {\n}\n\n\/\/ static\nconst PPB_URLRequestInfo* PPB_URLRequestInfo_Impl::GetInterface() {\n return &ppb_urlrequestinfo;\n}\n\nPPB_URLRequestInfo_Impl* PPB_URLRequestInfo_Impl::AsPPB_URLRequestInfo_Impl() {\n return this;\n}\n\nbool PPB_URLRequestInfo_Impl::SetBooleanProperty(PP_URLRequestProperty property,\n bool value) {\n switch (property) {\n case PP_URLREQUESTPROPERTY_STREAMTOFILE:\n stream_to_file_ = value;\n return true;\n case PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS:\n follow_redirects_ = value;\n return true;\n case PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS:\n record_download_progress_ = value;\n return true;\n case PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS:\n record_upload_progress_ = value;\n return true;\n default:\n return false;\n }\n}\n\nbool PPB_URLRequestInfo_Impl::SetStringProperty(PP_URLRequestProperty property,\n const std::string& value) {\n \/\/ TODO(darin): Validate input. Perhaps at a different layer?\n switch (property) {\n case PP_URLREQUESTPROPERTY_URL:\n url_ = value; \/\/ NOTE: This may be a relative URL.\n return true;\n case PP_URLREQUESTPROPERTY_METHOD:\n method_ = value;\n return true;\n case PP_URLREQUESTPROPERTY_HEADERS:\n if (!AreValidHeaders(value))\n return false;\n headers_ = value;\n return true;\n default:\n return false;\n }\n}\n\nbool PPB_URLRequestInfo_Impl::AppendDataToBody(const std::string& data) {\n if (!data.empty())\n body_.push_back(BodyItem(data));\n return true;\n}\n\nbool PPB_URLRequestInfo_Impl::AppendFileToBody(\n PPB_FileRef_Impl* file_ref,\n int64_t start_offset,\n int64_t number_of_bytes,\n PP_Time expected_last_modified_time) {\n \/\/ Ignore a call to append nothing.\n if (number_of_bytes == 0)\n return true;\n\n \/\/ Check for bad values. (-1 means read until end of file.)\n if (start_offset < 0 || number_of_bytes < -1)\n return false;\n\n body_.push_back(BodyItem(file_ref,\n start_offset,\n number_of_bytes,\n expected_last_modified_time));\n return true;\n}\n\nWebURLRequest PPB_URLRequestInfo_Impl::ToWebURLRequest(WebFrame* frame) const {\n WebURLRequest web_request;\n web_request.initialize();\n web_request.setURL(frame->document().completeURL(WebString::fromUTF8(url_)));\n web_request.setDownloadToFile(stream_to_file_);\n\n if (!method_.empty())\n web_request.setHTTPMethod(WebString::fromUTF8(method_));\n\n if (!headers_.empty()) {\n net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(), \"\\n\");\n while (it.GetNext()) {\n web_request.addHTTPHeaderField(\n WebString::fromUTF8(it.name()),\n WebString::fromUTF8(it.values()));\n }\n }\n\n if (!body_.empty()) {\n WebHTTPBody http_body;\n http_body.initialize();\n for (size_t i = 0; i < body_.size(); ++i) {\n if (body_[i].file_ref) {\n http_body.appendFileRange(\n webkit_glue::FilePathToWebString(\n body_[i].file_ref->GetSystemPath()),\n body_[i].start_offset,\n body_[i].number_of_bytes,\n body_[i].expected_last_modified_time);\n } else {\n DCHECK(!body_[i].data.empty());\n http_body.appendData(WebData(body_[i].data));\n }\n }\n web_request.setHTTPBody(http_body);\n }\n\n frame->setReferrerForRequest(web_request, WebURL()); \/\/ Use default.\n return web_request;\n}\n\n} \/\/ namespace ppapi\n} \/\/ namespace webkit\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef _CONNECT_H\n#define _CONNECT_H\n\n#include <vector>\n#include <memory>\n#include <functional>\n\n#define emit\n#define slots\n#define signals public\n#define connect(sender, signal, slot) ((sender)->signal.bind(slot))\n\ntemplate<typename... Args>\nclass Slot\n{\npublic:\n using OnFunc = std::function<void(Args...)>;\n\n Slot(const OnFunc& func)\n : m_func(func)\n {\n \/\/ Do nothing\n }\n\n void exec(Args... args)\n {\n m_func(args...);\n }\n\nprivate:\n OnFunc m_func = nullptr;\n};\n\ntemplate<typename... Args>\nclass Signal\n{\npublic:\n using SlotPtr = std::shared_ptr<Slot<Args...>>; \n using OnFunc = std::function<void(Args...)>;\n\n void bind(const OnFunc& func)\n {\n m_slotVec.push_back(SlotPtr(new Slot<Args...>(func)));\n }\n\n void operator()(Args... args)\n {\n for (auto& iter : m_slotVec)\n {\n iter->exec(args...);\n }\n }\n\nprivate:\n std::vector<SlotPtr> m_slotVec;\n};\n\n#endif\n<commit_msg>Update connect<commit_after>#ifndef _CONNECT_H\n#define _CONNECT_H\n\n#include <vector>\n#include <memory>\n#include <functional>\n\n#define emit\n#define slots\n#define signals public\n#define connect(sender, signal, slot) ((sender)->signal.bind(slot))\n\ntemplate<typename... Args>\nclass Slot\n{\npublic:\n using OnFunc = std::function<void(Args&&...)>;\n\n Slot(const OnFunc& func)\n : m_func(func)\n {\n \/\/ Do nothing\n }\n\n void exec(Args&&... args)\n {\n m_func(std::forward<Args>(args)...);\n }\n\nprivate:\n OnFunc m_func = nullptr;\n};\n\ntemplate<typename... Args>\nclass Signal\n{\npublic:\n using SlotPtr = std::shared_ptr<Slot<Args&&...>>; \n using OnFunc = std::function<void(Args&&...)>;\n\n void bind(const OnFunc& func)\n {\n m_slotVec.push_back(SlotPtr(new Slot<Args&&...>(func)));\n }\n\n void operator()(Args&&... args)\n {\n for (auto& iter : m_slotVec)\n {\n iter->exec(std::forward<Args>(args)...);\n }\n }\n\nprivate:\n std::vector<SlotPtr> m_slotVec;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ MaxPoolLayer.cpp\n\/\/ abs\n\/\/\n\/\/ Created by jiangxiaotang on 15\/10\/2016.\n\/\/ Copyright © 2016 jiangxiaotang. All rights reserved.\n\/\/\n\n#include \"MaxPoolLayer.hpp\"\n#include <fstream>\n#include \"LayerFactoryRegistor.hpp\"\n\nnamespace ALCNN {\n MaxPoolLayer::MaxPoolLayer(int stride, int width, int height, int depth):ILayer(width*height*depth, width*height*depth\/stride\/stride, 0, 0, width*height*depth\/stride\/stride, 1)\n {\n ALASSERT(stride>=2);\n ALASSERT(width>0);\n ALASSERT(height>0);\n ALASSERT(depth>0);\n ALASSERT(width%stride==0);\n ALASSERT(height%stride==0);\n mInput.iExpand = 0;\n mInput.iHeight = height;\n mInput.iWidth = width;\n mInput.iDepth = depth;\n \n mOutput.iDepth = depth;\n mOutput.iExpand = 0;\n mOutput.iWidth = width\/stride;\n mOutput.iHeight = height\/stride;\n mStride = stride;\n }\n MaxPoolLayer::~ MaxPoolLayer()\n {\n }\n \n void MaxPoolLayer::vForward(const ALFloatMatrix* before, ALFloatMatrix* after, const ALFloatMatrix* parameters, ALFloatMatrix* cache) const\n {\n ALLEARNAUTOTIME;\n ALASSERT(NULL!=after);\n ALASSERT(NULL!=before);\n ALASSERT(before->height() == after->height());\n ALASSERT(before->width() == mInput.getTotalWidth());\n ALASSERT(after->width() == mOutput.getTotalWidth());\n auto batchSize = after->height();\n ALAUTOSTORAGE(srcLines, ALFLOAT*, mStride);\n auto h = mOutput.iHeight;\n auto w = mOutput.iWidth;\n for (int z=0; z<batchSize; ++z)\n {\n for (int p=0; p<mInput.iDepth; ++p)\n {\n auto output_p = after->vGetAddr(z)+p*mOutput.iWidth*mOutput.iHeight;\n auto input_p = before->vGetAddr(z)+p*mInput.iWidth*mInput.iHeight;\n auto cache_p = cache->vGetAddr(z)+p*mOutput.iWidth*mOutput.iHeight;\n\n for (int i=0; i<h; ++i)\n {\n auto dst = output_p + mOutput.iWidth*i;\n auto cache_dst = cache_p + mOutput.iWidth*i;\n for (int k=0; k<mStride; ++k)\n {\n srcLines[k] = input_p + (mStride*i+k)*mInput.iWidth;\n }\n for (int j=0; j<w; ++j)\n {\n ALFLOAT maxNumber = srcLines[0][0];\n size_t maxX = 0;\n size_t maxY = 0;\n for (int x=0; x<mStride; ++x)\n {\n for (int y=0; y<mStride; ++y)\n {\n auto s = srcLines[x][y+mStride*j];\n if (maxNumber < s)\n {\n maxNumber = s;\n maxX = x;\n maxY = y;\n }\n }\n }\n dst[j] = maxNumber;\n cache_dst[j] = maxX + mStride*maxY;\n }\n }\n }\n }\n }\n void MaxPoolLayer::vBackward(const ALFloatMatrix* after_diff, const ALFloatMatrix* after, const ALFloatMatrix* parameters, const ALFloatMatrix* before, ALFloatMatrix* before_diff, ALFloatMatrix* parameters_diff, ALFloatMatrix* cache) const\n {\n ALLEARNAUTOTIME;\n ALASSERT(NULL!=after_diff);\n ALASSERT(NULL!=after);\n ALASSERT(after->height() == after_diff->height());\n ALASSERT(before_diff->width() == mInput.getTotalWidth());\n ALASSERT(after_diff->width() == mOutput.getTotalWidth());\n auto batchSize = after_diff->height();\n ALFloatMatrix::zero(before_diff);\n auto h = mOutput.iHeight;\n auto w = mOutput.iWidth;\n for (int z=0; z<batchSize; ++z)\n {\n for (int p=0; p<mInput.iDepth; ++p)\n {\n auto output_p = after_diff->vGetAddr(z)+p*mOutput.iWidth*mOutput.iHeight;\n auto input_diff_p = before_diff->vGetAddr(z)+p*mInput.iWidth*mInput.iHeight;\n auto cache_p = cache->vGetAddr(z)+p*mOutput.iWidth*mOutput.iHeight;\n\n for (int i=0; i<h; ++i)\n {\n auto dst = output_p + i*mOutput.iWidth;\n auto cache_dst = cache_p + mOutput.iWidth*i;\n for (int j=0; j<w; ++j)\n {\n auto mask = (size_t)(cache_dst[j]);\n auto maxX = mask % mStride;\n auto maxY = (mask - maxX)\/mStride;\n *(input_diff_p+(mStride*i+maxY)*mInput.iWidth + mStride*j+maxX) = dst[j];\n }\n }\n }\n }\n }\n static auto gCreateFunction = [](const LayerParameters& p) {\n return new MaxPoolLayer(p.get(\"stride\"), p.mMatrixInfo.iWidth, p.mMatrixInfo.iHeight, p.mMatrixInfo.iDepth);\n };\n \n static LayerFactoryRegister __reg(gCreateFunction, \"MaxPool\");\n\n}\n<commit_msg>Revert MaxPoolLayer opt for bug<commit_after>\/\/\n\/\/ MaxPoolLayer.cpp\n\/\/ abs\n\/\/\n\/\/ Created by jiangxiaotang on 15\/10\/2016.\n\/\/ Copyright © 2016 jiangxiaotang. All rights reserved.\n\/\/\n\n#include \"MaxPoolLayer.hpp\"\n#include <fstream>\n#include \"LayerFactoryRegistor.hpp\"\n\nnamespace ALCNN {\n MaxPoolLayer::MaxPoolLayer(int stride, int width, int height, int depth):ILayer(width*height*depth, width*height*depth\/stride\/stride, 0, 0, 0, 0)\n {\n ALASSERT(stride>=2);\n ALASSERT(width>0);\n ALASSERT(height>0);\n ALASSERT(depth>0);\n ALASSERT(width%stride==0);\n ALASSERT(height%stride==0);\n mInput.iExpand = 0;\n mInput.iHeight = height;\n mInput.iWidth = width;\n mInput.iDepth = depth;\n \n mOutput.iDepth = depth;\n mOutput.iExpand = 0;\n mOutput.iWidth = width\/stride;\n mOutput.iHeight = height\/stride;\n mStride = stride;\n }\n MaxPoolLayer::~ MaxPoolLayer()\n {\n }\n \n void MaxPoolLayer::vForward(const ALFloatMatrix* before, ALFloatMatrix* after, const ALFloatMatrix* parameters, ALFloatMatrix* cache) const\n {\n ALLEARNAUTOTIME;\n ALASSERT(NULL!=after);\n ALASSERT(NULL!=before);\n ALASSERT(before->height() == after->height());\n ALASSERT(before->width() == mInput.getTotalWidth());\n ALASSERT(after->width() == mOutput.getTotalWidth());\n auto batchSize = after->height();\n ALAUTOSTORAGE(srcLines, ALFLOAT*, mStride);\n for (int z=0; z<batchSize; ++z)\n {\n for (int p=0; p<mInput.iDepth; ++p)\n {\n ALSp<ALFloatMatrix> input = ALFloatMatrix::createRefMatrix(before->vGetAddr(z)+p*mInput.iWidth*mInput.iHeight, mInput.iWidth, mInput.iHeight);\n ALSp<ALFloatMatrix> output = ALFloatMatrix::createRefMatrix(after->vGetAddr(z)+p*mOutput.iWidth*mOutput.iHeight, mOutput.iWidth, mOutput.iHeight);\n auto h = mOutput.iHeight;\n auto w = mOutput.iWidth;\n for (int i=0; i<h; ++i)\n {\n auto dst = output->vGetAddr(i);\n for (int k=0; k<mStride; ++k)\n {\n srcLines[k] = input->vGetAddr(mStride*i+k);\n }\n for (int j=0; j<w; ++j)\n {\n ALFLOAT maxNumber = srcLines[0][0];\n for (int x=0; x<mStride; ++x)\n {\n for (int y=0; y<mStride; ++y)\n {\n auto s = srcLines[x][y+mStride*j];\n if (maxNumber < s)\n {\n maxNumber = s;\n }\n }\n }\n dst[j] = maxNumber;\n }\n }\n }\n }\n }\n void MaxPoolLayer::vBackward(const ALFloatMatrix* after_diff, const ALFloatMatrix* after, const ALFloatMatrix* parameters, const ALFloatMatrix* before, ALFloatMatrix* before_diff, ALFloatMatrix* parameters_diff, ALFloatMatrix* cache) const\n {\n ALLEARNAUTOTIME;\n ALASSERT(NULL!=after_diff);\n ALASSERT(NULL!=after);\n ALASSERT(after->height() == after_diff->height());\n ALASSERT(before_diff->width() == mInput.getTotalWidth());\n ALASSERT(after_diff->width() == mOutput.getTotalWidth());\n auto batchSize = after_diff->height();\n ALAUTOSTORAGE(srcLines, ALFLOAT*, mStride);\n ALAUTOSTORAGE(srcDiffLines, ALFLOAT*, mStride);\n ALFloatMatrix::zero(before_diff);\n for (int z=0; z<batchSize; ++z)\n {\n for (int p=0; p<mInput.iDepth; ++p)\n {\n ALSp<ALFloatMatrix> input = ALFloatMatrix::createRefMatrix(before->vGetAddr(z)+p*mInput.iWidth*mInput.iHeight, mInput.iWidth, mInput.iHeight);\n ALSp<ALFloatMatrix> input_diff = ALFloatMatrix::createRefMatrix(before_diff->vGetAddr(z)+p*mInput.iWidth*mInput.iHeight, mInput.iWidth, mInput.iHeight);\n ALSp<ALFloatMatrix> output = ALFloatMatrix::createRefMatrix(after_diff->vGetAddr(z)+p*mOutput.iWidth*mOutput.iHeight, mOutput.iWidth, mOutput.iHeight);\n auto h = mOutput.iHeight;\n auto w = mOutput.iWidth;\n for (int i=0; i<h; ++i)\n {\n auto dst = output->vGetAddr(i);\n for (int k=0; k<mStride; ++k)\n {\n srcLines[k] = input->vGetAddr(mStride*i+k);\n srcDiffLines[k] = input_diff->vGetAddr(mStride*i+k);\n }\n for (int j=0; j<w; ++j)\n {\n ALFLOAT maxNumber = srcLines[0][0];\n int maxX = 0;\n int maxY = 0;\n for (int x=0; x<mStride; ++x)\n {\n for (int y=0; y<mStride; ++y)\n {\n auto s = srcLines[x][y+mStride*j];\n if (maxNumber < s)\n {\n maxNumber = s;\n maxX = x;\n maxY = y;\n }\n }\n }\n srcDiffLines[maxX][maxY+mStride*j] = dst[j];\n }\n }\n }\n }\n }\n static auto gCreateFunction = [](const LayerParameters& p) {\n return new MaxPoolLayer(p.get(\"stride\"), p.mMatrixInfo.iWidth, p.mMatrixInfo.iHeight, p.mMatrixInfo.iDepth);\n };\n \n static LayerFactoryRegister __reg(gCreateFunction, \"MaxPool\");\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Jan de Visser on 2021-10-07.\n\/\/\n\n#include <gtest\/gtest.h>\n#include <lexer\/Tokenizer.h>\n#include <lexer\/test\/LexerTest.h>\n\nnamespace Obelix {\n\nclass KeywordTest : public ::LexerTest {\nprotected:\n unsigned int prepareWithBig()\n {\n initialize();\n add_scanner<Obelix::KeywordScanner>(Token(200, \"Big\"));\n return 200;\n }\n\n void prepareWithBigBad(unsigned int* big, unsigned int* bad)\n {\n initialize();\n add_scanner<Obelix::KeywordScanner>(Token(200, \"Big\"), Token(201, \"Bad\"));\n *big = 200;\n *bad = 201;\n }\n\n unsigned int prepareWithAbc()\n {\n return 205;\n }\n\n void tokenizeBig(const char* s, int total_count, int big_count)\n {\n auto code = prepareWithBig();\n tokenize(s);\n EXPECT_EQ(tokens.size(), total_count);\n for (auto& token : tokens) {\n debug(lexer, \"{}\", token.to_string());\n }\n EXPECT_EQ(tokens_by_code[(Obelix::TokenCode)code].size(), big_count);\n }\n\n void tokenizeBigBad(const char* s, int total_count, int big_count, int bad_count)\n {\n initialize();\n unsigned int big, bad;\n prepareWithBigBad(&big, &bad);\n tokenize(s);\n debug(lexer, \"{}\", tokens[0].to_string());\n EXPECT_EQ(tokens.size(), total_count);\n EXPECT_EQ(tokens_by_code[(Obelix::TokenCode)big].size(), big_count);\n EXPECT_EQ(tokens_by_code[(Obelix::TokenCode)bad].size(), bad_count);\n }\n\n bool debugOn() override {\n return false;\n }\n\n};\n\nTEST_F(KeywordTest, Keyword)\n{\n tokenizeBig(\"Big\", 2, 1);\n}\n\nTEST_F(KeywordTest, KeywordSpace)\n{\n tokenizeBig(\"Big \", 3, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 1);\n}\n\nTEST_F(KeywordTest, KeywordIsPrefix)\n{\n tokenizeBig(\"Bigger\", 3, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 1);\n}\n\nTEST_F(KeywordTest, KeywordAndIdentifiers)\n{\n tokenizeBig(\"Hello Big World\", 6, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 2);\n}\n\nTEST_F(KeywordTest, TwoKeywords)\n{\n tokenizeBig(\"Hello Big Big Beautiful World\", 10, 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 3);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 4);\n}\n\nTEST_F(KeywordTest, keyword_two_keywords_separated)\n{\n tokenizeBig(\"Hello Big Beautiful Big World\", 10, 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 3);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 4);\n}\n\nTEST_F(KeywordTest, keyword_big_bad_big)\n{\n tokenizeBigBad(\"Hello Big World\", 6, 1, 0);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 2);\n}\n\nTEST_F(KeywordTest, keyword_big_bad_bad)\n{\n tokenizeBigBad(\"Hello Bad World\", 6, 0, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 2);\n}\n\nTEST_F(KeywordTest, keyword_big_bad_big_bad)\n{\n tokenizeBigBad(\"Hello Big Bad World\", 8, 1, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 3);\n}\n\nTEST_F(KeywordTest, keyword_big_bad_bad_big)\n{\n tokenizeBigBad(\"Hello Bad Big World\", 8, 1, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 3);\n}\n\nTEST_F(KeywordTest, keyword_abc)\n{\n initialize();\n add_scanner<Obelix::KeywordScanner>(\n Token(TokenCode::Keyword0, \"abb\"),\n Token(TokenCode::Keyword1, \"aca\"),\n Token(TokenCode::Keyword2, \"aba\"),\n Token(TokenCode::Keyword3, \"aaa\"),\n Token(TokenCode::Keyword4, \"aab\"),\n Token(TokenCode::Keyword5, \"abc\"),\n Token(TokenCode::Keyword6, \"aac\"),\n Token(TokenCode::Keyword7, \"acc\"),\n Token(TokenCode::Keyword8, \"acb\"));\n\n tokenize(\"yyz abc ams\");\n EXPECT_EQ(tokens.size(), 6);\n EXPECT_EQ(tokens_by_code[TokenCode::Keyword5].size(), 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 2);\n}\n\nTEST_F(KeywordTest, keyword_for_format)\n{\n \/\/ Logger::get_logger().enable(\"lexer\");\n initialize();\n add_scanner<Obelix::KeywordScanner>(\n Token(TokenCode::Keyword0, \"for\"),\n Token(TokenCode::Keyword1, \"format\"),\n Token(TokenCode::Keyword2, \"font\"),\n TokenCode::GreaterEqualThan,\n Token(TokenCode::Keyword4, \"aab\"),\n Token(TokenCode::Keyword5, \"abc\"),\n Token(TokenCode::Keyword6, \"aac\"),\n Token(TokenCode::Keyword7, \"acc\"),\n Token(TokenCode::Keyword8, \"acb\"));\n\n tokenize(\"xxx for format font fo formatting >=xxx\");\n EXPECT_EQ(tokens.size(), 15);\n EXPECT_EQ(tokens_by_code[TokenCode::Keyword0].size(), 1);\n EXPECT_EQ(tokens_by_code[TokenCode::Keyword1].size(), 1);\n EXPECT_EQ(tokens_by_code[TokenCode::Keyword2].size(), 1);\n EXPECT_EQ(tokens_by_code[TokenCode::GreaterEqualThan].size(), 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 4);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 6);\n}\n\n}<commit_msg>Fix test<commit_after>\/\/\n\/\/ Created by Jan de Visser on 2021-10-07.\n\/\/\n\n#include <gtest\/gtest.h>\n#include <lexer\/Tokenizer.h>\n#include <lexer\/test\/LexerTest.h>\n\nnamespace Obelix {\n\nclass KeywordTest : public ::LexerTest {\nprotected:\n unsigned int prepareWithBig()\n {\n initialize();\n add_scanner<Obelix::KeywordScanner>(Token(200, \"Big\"));\n return 200;\n }\n\n void prepareWithBigBad(unsigned int* big, unsigned int* bad)\n {\n initialize();\n add_scanner<Obelix::KeywordScanner>(Token(200, \"Big\"), Token(201, \"Bad\"));\n *big = 200;\n *bad = 201;\n }\n\n unsigned int prepareWithAbc()\n {\n return 205;\n }\n\n void tokenizeBig(const char* s, int total_count, int big_count)\n {\n auto code = prepareWithBig();\n tokenize(s);\n EXPECT_EQ(tokens.size(), total_count);\n for (auto& token : tokens) {\n debug(lexer, \"{}\", token.to_string());\n }\n EXPECT_EQ(tokens_by_code[(Obelix::TokenCode)code].size(), big_count);\n }\n\n void tokenizeBigBad(const char* s, int total_count, int big_count, int bad_count)\n {\n initialize();\n unsigned int big, bad;\n prepareWithBigBad(&big, &bad);\n tokenize(s);\n debug(lexer, \"{}\", tokens[0].to_string());\n EXPECT_EQ(tokens.size(), total_count);\n EXPECT_EQ(tokens_by_code[(Obelix::TokenCode)big].size(), big_count);\n EXPECT_EQ(tokens_by_code[(Obelix::TokenCode)bad].size(), bad_count);\n }\n\n bool debugOn() override {\n return false;\n }\n\n};\n\nTEST_F(KeywordTest, Keyword)\n{\n tokenizeBig(\"Big\", 2, 1);\n}\n\nTEST_F(KeywordTest, KeywordSpace)\n{\n tokenizeBig(\"Big \", 3, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 1);\n}\n\nTEST_F(KeywordTest, KeywordIsPrefix)\n{\n tokenizeBig(\"Bigger\", 2, 0);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 1);\n}\n\nTEST_F(KeywordTest, KeywordAndIdentifiers)\n{\n tokenizeBig(\"Hello Big World\", 6, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 2);\n}\n\nTEST_F(KeywordTest, TwoKeywords)\n{\n tokenizeBig(\"Hello Big Big Beautiful World\", 10, 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 3);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 4);\n}\n\nTEST_F(KeywordTest, keyword_two_keywords_separated)\n{\n tokenizeBig(\"Hello Big Beautiful Big World\", 10, 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 3);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 4);\n}\n\nTEST_F(KeywordTest, keyword_big_bad_big)\n{\n tokenizeBigBad(\"Hello Big World\", 6, 1, 0);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 2);\n}\n\nTEST_F(KeywordTest, keyword_big_bad_bad)\n{\n tokenizeBigBad(\"Hello Bad World\", 6, 0, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 2);\n}\n\nTEST_F(KeywordTest, keyword_big_bad_big_bad)\n{\n tokenizeBigBad(\"Hello Big Bad World\", 8, 1, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 3);\n}\n\nTEST_F(KeywordTest, keyword_big_bad_bad_big)\n{\n tokenizeBigBad(\"Hello Bad Big World\", 8, 1, 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 3);\n}\n\nTEST_F(KeywordTest, keyword_abc)\n{\n initialize();\n add_scanner<Obelix::KeywordScanner>(\n Token(TokenCode::Keyword0, \"abb\"),\n Token(TokenCode::Keyword1, \"aca\"),\n Token(TokenCode::Keyword2, \"aba\"),\n Token(TokenCode::Keyword3, \"aaa\"),\n Token(TokenCode::Keyword4, \"aab\"),\n Token(TokenCode::Keyword5, \"abc\"),\n Token(TokenCode::Keyword6, \"aac\"),\n Token(TokenCode::Keyword7, \"acc\"),\n Token(TokenCode::Keyword8, \"acb\"));\n\n tokenize(\"yyz abc ams\");\n EXPECT_EQ(tokens.size(), 6);\n EXPECT_EQ(tokens_by_code[TokenCode::Keyword5].size(), 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 2);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 2);\n}\n\nTEST_F(KeywordTest, keyword_for_format)\n{\n \/\/ Logger::get_logger().enable(\"lexer\");\n initialize();\n add_scanner<Obelix::KeywordScanner>(\n Token(TokenCode::Keyword0, \"for\"),\n Token(TokenCode::Keyword1, \"format\"),\n Token(TokenCode::Keyword2, \"font\"),\n TokenCode::GreaterEqualThan,\n Token(TokenCode::Keyword4, \"aab\"),\n Token(TokenCode::Keyword5, \"abc\"),\n Token(TokenCode::Keyword6, \"aac\"),\n Token(TokenCode::Keyword7, \"acc\"),\n Token(TokenCode::Keyword8, \"acb\"));\n\n tokenize(\"xxx for format font fo formatting >=xxx\");\n EXPECT_EQ(tokens.size(), 15);\n EXPECT_EQ(tokens_by_code[TokenCode::Keyword0].size(), 1);\n EXPECT_EQ(tokens_by_code[TokenCode::Keyword1].size(), 1);\n EXPECT_EQ(tokens_by_code[TokenCode::Keyword2].size(), 1);\n EXPECT_EQ(tokens_by_code[TokenCode::GreaterEqualThan].size(), 1);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Identifier].size(), 4);\n EXPECT_EQ(tokens_by_code[Obelix::TokenCode::Whitespace].size(), 6);\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).\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 \"fastrtps\/subscriber\/Subscriber.h\"\n\n#include \"rmw\/error_handling.h\"\n#include \"rmw\/rmw.h\"\n\n#include \"rmw_fastrtps_cpp\/custom_client_info.hpp\"\n#include \"rmw_fastrtps_cpp\/custom_service_info.hpp\"\n#include \"rmw_fastrtps_cpp\/custom_subscriber_info.hpp\"\n#include \"types\/custom_wait_set_info.hpp\"\n#include \"types\/guard_condition.hpp\"\n\n\/\/ helper function for wait\nbool\ncheck_wait_set_for_data(\n const rmw_subscriptions_t * subscriptions,\n const rmw_guard_conditions_t * guard_conditions,\n const rmw_services_t * services,\n const rmw_clients_t * clients)\n{\n if (subscriptions) {\n for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {\n void * data = subscriptions->subscribers[i];\n auto custom_subscriber_info = static_cast<CustomSubscriberInfo *>(data);\n \/\/ Short circuiting out of this function is possible\n if (custom_subscriber_info && custom_subscriber_info->listener_->hasData()) {\n return true;\n }\n }\n }\n\n if (clients) {\n for (size_t i = 0; i < clients->client_count; ++i) {\n void * data = clients->clients[i];\n CustomClientInfo * custom_client_info = static_cast<CustomClientInfo *>(data);\n if (custom_client_info && custom_client_info->listener_->hasData()) {\n return true;\n }\n }\n }\n\n if (services) {\n for (size_t i = 0; i < services->service_count; ++i) {\n void * data = services->services[i];\n CustomServiceInfo * custom_service_info = static_cast<CustomServiceInfo *>(data);\n if (custom_service_info && custom_service_info->listener_->hasData()) {\n return true;\n }\n }\n }\n\n if (guard_conditions) {\n for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {\n void * data = guard_conditions->guard_conditions[i];\n auto guard_condition = static_cast<GuardCondition *>(data);\n if (guard_condition && guard_condition->hasTriggered()) {\n return true;\n }\n }\n }\n return false;\n}\n\nextern \"C\"\n{\nrmw_ret_t\nrmw_wait(\n rmw_subscriptions_t * subscriptions,\n rmw_guard_conditions_t * guard_conditions,\n rmw_services_t * services,\n rmw_clients_t * clients,\n rmw_wait_set_t * wait_set,\n const rmw_time_t * wait_timeout)\n{\n if (!wait_set) {\n RMW_SET_ERROR_MSG(\"wait set handle is null\");\n return RMW_RET_ERROR;\n }\n CustomWaitsetInfo * wait_set_info = static_cast<CustomWaitsetInfo *>(wait_set->data);\n if (!wait_set_info) {\n RMW_SET_ERROR_MSG(\"Waitset info struct is null\");\n return RMW_RET_ERROR;\n }\n std::mutex * conditionMutex = &wait_set_info->condition_mutex;\n std::condition_variable * conditionVariable = &wait_set_info->condition;\n if (!conditionMutex) {\n RMW_SET_ERROR_MSG(\"Mutex for wait set was null\");\n return RMW_RET_ERROR;\n }\n if (!conditionVariable) {\n RMW_SET_ERROR_MSG(\"Condition variable for wait set was null\");\n return RMW_RET_ERROR;\n }\n\n if (subscriptions) {\n for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {\n void * data = subscriptions->subscribers[i];\n auto custom_subscriber_info = static_cast<CustomSubscriberInfo *>(data);\n custom_subscriber_info->listener_->attachCondition(conditionMutex, conditionVariable);\n }\n }\n\n if (clients) {\n for (size_t i = 0; i < clients->client_count; ++i) {\n void * data = clients->clients[i];\n CustomClientInfo * custom_client_info = static_cast<CustomClientInfo *>(data);\n custom_client_info->listener_->attachCondition(conditionMutex, conditionVariable);\n }\n }\n\n if (services) {\n for (size_t i = 0; i < services->service_count; ++i) {\n void * data = services->services[i];\n auto custom_service_info = static_cast<CustomServiceInfo *>(data);\n custom_service_info->listener_->attachCondition(conditionMutex, conditionVariable);\n }\n }\n\n if (guard_conditions) {\n for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {\n void * data = guard_conditions->guard_conditions[i];\n auto guard_condition = static_cast<GuardCondition *>(data);\n guard_condition->attachCondition(conditionMutex, conditionVariable);\n }\n }\n\n \/\/ This mutex prevents any of the listeners\n \/\/ to change the internal state and notify the condition\n \/\/ between the call to hasData() \/ hasTriggered() and wait()\n \/\/ otherwise the decision to wait might be incorrect\n std::unique_lock<std::mutex> lock(*conditionMutex);\n\n \/\/ First check variables.\n \/\/ If wait_timeout is null, wait indefinitely (so we have to wait)\n \/\/ If wait_timeout is not null and either of its fields are nonzero, we have to wait\n bool hasToWait = (wait_timeout && (wait_timeout->sec > 0 || wait_timeout->nsec > 0)) ||\n !wait_timeout;\n\n if (subscriptions) {\n for (size_t i = 0; hasToWait && i < subscriptions->subscriber_count; ++i) {\n void * data = subscriptions->subscribers[i];\n auto custom_subscriber_info = static_cast<CustomSubscriberInfo *>(data);\n if (custom_subscriber_info->listener_->hasData()) {\n hasToWait = false;\n }\n }\n }\n\n if (clients) {\n for (size_t i = 0; hasToWait && i < clients->client_count; ++i) {\n void * data = clients->clients[i];\n CustomClientInfo * custom_client_info = static_cast<CustomClientInfo *>(data);\n if (custom_client_info->listener_->hasData()) {\n hasToWait = false;\n }\n }\n }\n\n if (services) {\n for (size_t i = 0; hasToWait && i < services->service_count; ++i) {\n void * data = services->services[i];\n auto custom_service_info = static_cast<CustomServiceInfo *>(data);\n if (custom_service_info->listener_->hasData()) {\n hasToWait = false;\n }\n }\n }\n\n if (guard_conditions) {\n for (size_t i = 0; hasToWait && i < guard_conditions->guard_condition_count; ++i) {\n void * data = guard_conditions->guard_conditions[i];\n auto guard_condition = static_cast<GuardCondition *>(data);\n if (guard_condition->hasTriggered()) {\n hasToWait = false;\n }\n }\n }\n\n bool timeout = false;\n\n if (hasToWait) {\n if (!wait_timeout) {\n conditionVariable->wait(lock);\n } else {\n auto predicate = [subscriptions, guard_conditions, services, clients]() {\n return check_wait_set_for_data(subscriptions, guard_conditions, services, clients);\n };\n auto n = std::chrono::duration_cast<std::chrono::nanoseconds>(\n std::chrono::seconds(wait_timeout->sec));\n n += std::chrono::nanoseconds(wait_timeout->nsec);\n timeout = !conditionVariable->wait_for(lock, n, predicate);\n }\n }\n\n \/\/ Unlock the condition variable mutex to prevent deadlocks that can occur if\n \/\/ a listener triggers while the condition variable is being detached.\n \/\/ Listeners will no longer be prevented from changing their internal state,\n \/\/ but that should not cause issues (if a listener has data \/ has triggered\n \/\/ after we check, it will be caught on the next call to this function).\n lock.unlock();\n\n \/\/ Even if this was a non-blocking wait, signal a timeout if there's no data.\n \/\/ This makes the return behavior consistent with rcl expectations for zero timeout value.\n \/\/ Do this before detaching the listeners because the data gets cleared for guard conditions.\n bool hasData = check_wait_set_for_data(subscriptions, guard_conditions, services, clients);\n if (!hasData && wait_timeout && wait_timeout->sec == 0 && wait_timeout->nsec == 0) {\n timeout = true;\n }\n\n if (subscriptions) {\n for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {\n void * data = subscriptions->subscribers[i];\n auto custom_subscriber_info = static_cast<CustomSubscriberInfo *>(data);\n custom_subscriber_info->listener_->detachCondition();\n if (!custom_subscriber_info->listener_->hasData()) {\n subscriptions->subscribers[i] = 0;\n }\n }\n }\n\n if (clients) {\n for (size_t i = 0; i < clients->client_count; ++i) {\n void * data = clients->clients[i];\n CustomClientInfo * custom_client_info = static_cast<CustomClientInfo *>(data);\n custom_client_info->listener_->detachCondition();\n if (!custom_client_info->listener_->hasData()) {\n clients->clients[i] = 0;\n }\n }\n }\n\n if (services) {\n for (size_t i = 0; i < services->service_count; ++i) {\n void * data = services->services[i];\n auto custom_service_info = static_cast<CustomServiceInfo *>(data);\n custom_service_info->listener_->detachCondition();\n if (!custom_service_info->listener_->hasData()) {\n services->services[i] = 0;\n }\n }\n }\n\n if (guard_conditions) {\n for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {\n void * data = guard_conditions->guard_conditions[i];\n auto guard_condition = static_cast<GuardCondition *>(data);\n guard_condition->detachCondition();\n if (!guard_condition->getHasTriggered()) {\n guard_conditions->guard_conditions[i] = 0;\n }\n }\n }\n\n return timeout ? RMW_RET_TIMEOUT : RMW_RET_OK;\n}\n} \/\/ extern \"C\"\n<commit_msg>use existing check_wait_set_for_data to avoid duplicated code (#185)<commit_after>\/\/ Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).\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 \"fastrtps\/subscriber\/Subscriber.h\"\n\n#include \"rmw\/error_handling.h\"\n#include \"rmw\/rmw.h\"\n\n#include \"rmw_fastrtps_cpp\/custom_client_info.hpp\"\n#include \"rmw_fastrtps_cpp\/custom_service_info.hpp\"\n#include \"rmw_fastrtps_cpp\/custom_subscriber_info.hpp\"\n#include \"types\/custom_wait_set_info.hpp\"\n#include \"types\/guard_condition.hpp\"\n\n\/\/ helper function for wait\nbool\ncheck_wait_set_for_data(\n const rmw_subscriptions_t * subscriptions,\n const rmw_guard_conditions_t * guard_conditions,\n const rmw_services_t * services,\n const rmw_clients_t * clients)\n{\n if (subscriptions) {\n for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {\n void * data = subscriptions->subscribers[i];\n auto custom_subscriber_info = static_cast<CustomSubscriberInfo *>(data);\n \/\/ Short circuiting out of this function is possible\n if (custom_subscriber_info && custom_subscriber_info->listener_->hasData()) {\n return true;\n }\n }\n }\n\n if (clients) {\n for (size_t i = 0; i < clients->client_count; ++i) {\n void * data = clients->clients[i];\n CustomClientInfo * custom_client_info = static_cast<CustomClientInfo *>(data);\n if (custom_client_info && custom_client_info->listener_->hasData()) {\n return true;\n }\n }\n }\n\n if (services) {\n for (size_t i = 0; i < services->service_count; ++i) {\n void * data = services->services[i];\n CustomServiceInfo * custom_service_info = static_cast<CustomServiceInfo *>(data);\n if (custom_service_info && custom_service_info->listener_->hasData()) {\n return true;\n }\n }\n }\n\n if (guard_conditions) {\n for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {\n void * data = guard_conditions->guard_conditions[i];\n auto guard_condition = static_cast<GuardCondition *>(data);\n if (guard_condition && guard_condition->hasTriggered()) {\n return true;\n }\n }\n }\n return false;\n}\n\nextern \"C\"\n{\nrmw_ret_t\nrmw_wait(\n rmw_subscriptions_t * subscriptions,\n rmw_guard_conditions_t * guard_conditions,\n rmw_services_t * services,\n rmw_clients_t * clients,\n rmw_wait_set_t * wait_set,\n const rmw_time_t * wait_timeout)\n{\n if (!wait_set) {\n RMW_SET_ERROR_MSG(\"wait set handle is null\");\n return RMW_RET_ERROR;\n }\n CustomWaitsetInfo * wait_set_info = static_cast<CustomWaitsetInfo *>(wait_set->data);\n if (!wait_set_info) {\n RMW_SET_ERROR_MSG(\"Waitset info struct is null\");\n return RMW_RET_ERROR;\n }\n std::mutex * conditionMutex = &wait_set_info->condition_mutex;\n std::condition_variable * conditionVariable = &wait_set_info->condition;\n if (!conditionMutex) {\n RMW_SET_ERROR_MSG(\"Mutex for wait set was null\");\n return RMW_RET_ERROR;\n }\n if (!conditionVariable) {\n RMW_SET_ERROR_MSG(\"Condition variable for wait set was null\");\n return RMW_RET_ERROR;\n }\n\n if (subscriptions) {\n for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {\n void * data = subscriptions->subscribers[i];\n auto custom_subscriber_info = static_cast<CustomSubscriberInfo *>(data);\n custom_subscriber_info->listener_->attachCondition(conditionMutex, conditionVariable);\n }\n }\n\n if (clients) {\n for (size_t i = 0; i < clients->client_count; ++i) {\n void * data = clients->clients[i];\n CustomClientInfo * custom_client_info = static_cast<CustomClientInfo *>(data);\n custom_client_info->listener_->attachCondition(conditionMutex, conditionVariable);\n }\n }\n\n if (services) {\n for (size_t i = 0; i < services->service_count; ++i) {\n void * data = services->services[i];\n auto custom_service_info = static_cast<CustomServiceInfo *>(data);\n custom_service_info->listener_->attachCondition(conditionMutex, conditionVariable);\n }\n }\n\n if (guard_conditions) {\n for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {\n void * data = guard_conditions->guard_conditions[i];\n auto guard_condition = static_cast<GuardCondition *>(data);\n guard_condition->attachCondition(conditionMutex, conditionVariable);\n }\n }\n\n \/\/ This mutex prevents any of the listeners\n \/\/ to change the internal state and notify the condition\n \/\/ between the call to hasData() \/ hasTriggered() and wait()\n \/\/ otherwise the decision to wait might be incorrect\n std::unique_lock<std::mutex> lock(*conditionMutex);\n\n \/\/ First check variables.\n \/\/ If wait_timeout is null, wait indefinitely (so we have to wait)\n \/\/ If wait_timeout is not null and either of its fields are nonzero, we have to wait\n bool hasToWait = (wait_timeout && (wait_timeout->sec > 0 || wait_timeout->nsec > 0)) ||\n !wait_timeout;\n hasToWait &= !check_wait_set_for_data(subscriptions, guard_conditions, services, clients);\n\n bool timeout = false;\n\n if (hasToWait) {\n if (!wait_timeout) {\n conditionVariable->wait(lock);\n } else {\n auto predicate = [subscriptions, guard_conditions, services, clients]() {\n return check_wait_set_for_data(subscriptions, guard_conditions, services, clients);\n };\n auto n = std::chrono::duration_cast<std::chrono::nanoseconds>(\n std::chrono::seconds(wait_timeout->sec));\n n += std::chrono::nanoseconds(wait_timeout->nsec);\n timeout = !conditionVariable->wait_for(lock, n, predicate);\n }\n }\n\n \/\/ Unlock the condition variable mutex to prevent deadlocks that can occur if\n \/\/ a listener triggers while the condition variable is being detached.\n \/\/ Listeners will no longer be prevented from changing their internal state,\n \/\/ but that should not cause issues (if a listener has data \/ has triggered\n \/\/ after we check, it will be caught on the next call to this function).\n lock.unlock();\n\n \/\/ Even if this was a non-blocking wait, signal a timeout if there's no data.\n \/\/ This makes the return behavior consistent with rcl expectations for zero timeout value.\n \/\/ Do this before detaching the listeners because the data gets cleared for guard conditions.\n bool hasData = check_wait_set_for_data(subscriptions, guard_conditions, services, clients);\n if (!hasData && wait_timeout && wait_timeout->sec == 0 && wait_timeout->nsec == 0) {\n timeout = true;\n }\n\n if (subscriptions) {\n for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {\n void * data = subscriptions->subscribers[i];\n auto custom_subscriber_info = static_cast<CustomSubscriberInfo *>(data);\n custom_subscriber_info->listener_->detachCondition();\n if (!custom_subscriber_info->listener_->hasData()) {\n subscriptions->subscribers[i] = 0;\n }\n }\n }\n\n if (clients) {\n for (size_t i = 0; i < clients->client_count; ++i) {\n void * data = clients->clients[i];\n CustomClientInfo * custom_client_info = static_cast<CustomClientInfo *>(data);\n custom_client_info->listener_->detachCondition();\n if (!custom_client_info->listener_->hasData()) {\n clients->clients[i] = 0;\n }\n }\n }\n\n if (services) {\n for (size_t i = 0; i < services->service_count; ++i) {\n void * data = services->services[i];\n auto custom_service_info = static_cast<CustomServiceInfo *>(data);\n custom_service_info->listener_->detachCondition();\n if (!custom_service_info->listener_->hasData()) {\n services->services[i] = 0;\n }\n }\n }\n\n if (guard_conditions) {\n for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {\n void * data = guard_conditions->guard_conditions[i];\n auto guard_condition = static_cast<GuardCondition *>(data);\n guard_condition->detachCondition();\n if (!guard_condition->getHasTriggered()) {\n guard_conditions->guard_conditions[i] = 0;\n }\n }\n }\n\n return timeout ? RMW_RET_TIMEOUT : RMW_RET_OK;\n}\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_BROADCAST_SCATTERER_HPP\n#define CAF_BROADCAST_SCATTERER_HPP\n\n#include \"caf\/buffered_scatterer.hpp\"\n#include \"caf\/outbound_path.hpp\"\n\n#include \"caf\/detail\/algorithms.hpp\"\n#include \"caf\/detail\/path_state.hpp\"\n#include \"caf\/detail\/select_all.hpp\"\n\nnamespace caf {\n\ntemplate <class T, class Filter = unit_t, class Select = detail::select_all>\nclass broadcast_scatterer : public buffered_scatterer<T> {\npublic:\n \/\/ -- member types -----------------------------------------------------------\n\n \/\/\/ Base type.\n using super = buffered_scatterer<T>;\n\n \/\/\/ Type of `paths_`.\n using typename super::map_type;\n\n \/\/\/ Enables or disables output per path.\n using filter_type = Filter;\n\n \/\/\/ Function object for evaluating filters.\n using select_type = Select;\n\n \/\/\/ Container for caching `T`s per path with active filter.\n using path_state = detail::path_state<Filter, T>;\n\n \/\/\/ Maps slot IDs to caches.\n using state_map_type = detail::unordered_flat_map<stream_slot, path_state>;\n\n \/\/ -- constructors, destructors, and assignment operators --------------------\n\n broadcast_scatterer(scheduled_actor* selfptr) : super(selfptr) {\n \/\/ nop\n }\n\n \/\/ -- properties -------------------------------------------------------------\n\n \/\/\/ Sets the filter for `slot` to `filter`. Inserts a new element if `slot`\n \/\/\/ is a new path.\n void set_filter(stream_slot slot, filter_type filter) {\n CAF_LOG_TRACE(CAF_ARG(slot) << CAF_ARG(filter));\n state_map_[slot].filter = std::move(filter);\n }\n\n \/\/\/ Returns the filter for `slot`. Inserts a new element if `slot` is a new\n \/\/\/ path.\n filter_type& filter(stream_slot slot) {\n CAF_LOG_TRACE(CAF_ARG(slot));\n return state_map_[slot].filter;\n }\n\n \/\/\/ Returns the broadcast states for all paths.\n state_map_type& states() {\n return state_map_;\n }\n\n \/\/\/ Returns the broadcast states for all paths.\n const state_map_type& states() const {\n return state_map_;\n }\n\n \/\/\/ Returns the selector for filtering outgoing data.\n select_type& selector() {\n return select_;\n }\n\n \/\/\/ Returns the selector for filtering outgoing data.\n const select_type& selector() const {\n return select_;\n }\n\n \/\/ -- overridden functions ---------------------------------------------------\n\n typename super::path_ptr add_path(stream_slots slots,\n strong_actor_ptr target) override {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(target));\n \/\/ Make sure we have state for the slot.\n state_map_.emplace(slots.sender, path_state{});\n \/\/ Append to `paths_`.\n auto index = this->paths_.size();\n auto result = super::add_path(slots, target);\n if (result == nullptr)\n return nullptr;\n \/\/ Make sure state_map_ and paths_ are always equally sorted, otherwise\n \/\/ we'll run into UB when calling `zip_foreach`.\n CAF_ASSERT(index == this->paths_.size() - 1);\n CAF_ASSERT(result->slots == slots);\n CAF_ASSERT(this->paths_.container().back().first == slots.sender);\n CAF_ASSERT(this->paths_.container().back().second.get() == result);\n auto& ys = state_map_.container();\n if (ys[index].first != slots.sender) {\n auto i = state_map_.find(slots.sender);\n CAF_ASSERT(i != ys.end());\n CAF_ASSERT(std::distance(ys.begin(), i) > static_cast<ptrdiff_t>(index));\n using std::swap;\n swap(ys[index], *i);\n }\n return result;\n }\n\n void emit_batches() override {\n CAF_LOG_TRACE(CAF_ARG2(\"buffered\", this->buffered())\n << CAF_ARG2(\"paths\", this->paths_.size()));\n emit_batches_impl(false);\n }\n\n void force_emit_batches() override {\n CAF_LOG_TRACE(CAF_ARG2(\"buffered\", this->buffered())\n << CAF_ARG2(\"paths\", this->paths_.size()));\n emit_batches_impl(true);\n }\n\nprotected:\n void about_to_erase(outbound_path* ptr, bool silent,\n error* reason) override {\n CAF_LOG_DEBUG(\"remove cache:\" << CAF_ARG2(\"slot\", ptr->slots.sender));\n state_map_.erase(ptr->slots.sender);\n super::about_to_erase(ptr, silent, reason);\n }\n\nprivate:\n void emit_batches_impl(bool force_underfull) {\n CAF_ASSERT(this->paths_.size() <= state_map_.size());\n if (this->paths_.empty())\n return;\n \/\/ Calculate the chunk size, i.e., how many more items we can put to our\n \/\/ caches at the most.\n struct get_credit {\n inline size_t operator()(typename map_type::value_type& x) {\n return static_cast<size_t>(x.second->open_credit);\n }\n };\n struct get_cache_size {\n inline size_t operator()(typename state_map_type::value_type& x) {\n return x.second.buf.size();\n }\n };\n auto f = [](size_t x, size_t credit, size_t cache_size) {\n auto y = credit > cache_size ? credit - cache_size : 0u;\n return x < y ? x : y;\n };\n auto chunk_size = detail::zip_fold(\n f, std::numeric_limits<size_t>::max(),\n detail::make_container_view<get_credit>(this->paths_.container()),\n detail::make_container_view<get_cache_size>(state_map_.container()));\n auto chunk = this->get_chunk(chunk_size);\n if (chunk.empty()) {\n auto g = [&](typename map_type::value_type& x,\n typename state_map_type::value_type& y) {\n x.second->emit_batches(this->self_, y.second.buf, force_underfull);\n };\n detail::zip_foreach(g, this->paths_.container(), state_map_.container());\n } else {\n auto g = [&](typename map_type::value_type& x,\n typename state_map_type::value_type& y) {\n \/\/ TODO: replace with `if constexpr` when switching to C++17\n auto& st = y.second;\n if (std::is_same<select_type, detail::select_all>::value) {\n st.buf.insert(st.buf.end(), chunk.begin(), chunk.end());\n } else {\n for (auto& piece : chunk)\n if (select_(st.filter, piece))\n st.buf.emplace_back(piece);\n }\n x.second->emit_batches(this->self_, st.buf, force_underfull);\n };\n detail::zip_foreach(g, this->paths_.container(), state_map_.container());\n }\n }\n\n state_map_type state_map_;\n select_type select_;\n};\n\n} \/\/ namespace caf\n\n#endif \/\/ CAF_BROADCAST_SCATTERER_HPP\n<commit_msg>Add convenience algorithms for filters<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_BROADCAST_SCATTERER_HPP\n#define CAF_BROADCAST_SCATTERER_HPP\n\n#include <algorithm>\n\n#include \"caf\/buffered_scatterer.hpp\"\n#include \"caf\/outbound_path.hpp\"\n\n#include \"caf\/detail\/algorithms.hpp\"\n#include \"caf\/detail\/path_state.hpp\"\n#include \"caf\/detail\/select_all.hpp\"\n\nnamespace caf {\n\ntemplate <class T, class Filter = unit_t, class Select = detail::select_all>\nclass broadcast_scatterer : public buffered_scatterer<T> {\npublic:\n \/\/ -- member types -----------------------------------------------------------\n\n \/\/\/ Base type.\n using super = buffered_scatterer<T>;\n\n \/\/\/ Type of `paths_`.\n using typename super::map_type;\n\n \/\/\/ Enables or disables output per path.\n using filter_type = Filter;\n\n \/\/\/ Function object for evaluating filters.\n using select_type = Select;\n\n \/\/\/ Container for caching `T`s per path with active filter.\n using path_state = detail::path_state<Filter, T>;\n\n \/\/\/ Maps slot IDs to caches.\n using state_map_type = detail::unordered_flat_map<stream_slot, path_state>;\n\n \/\/ -- constructors, destructors, and assignment operators --------------------\n\n broadcast_scatterer(scheduled_actor* selfptr) : super(selfptr) {\n \/\/ nop\n }\n\n \/\/ -- properties -------------------------------------------------------------\n\n \/\/\/ Sets the filter for `slot` to `filter`. Inserts a new element if `slot`\n \/\/\/ is a new path.\n void set_filter(stream_slot slot, filter_type filter) {\n CAF_LOG_TRACE(CAF_ARG(slot) << CAF_ARG(filter));\n state_map_[slot].filter = std::move(filter);\n }\n\n \/\/\/ Returns the filter for `slot`. Inserts a new element if `slot` is a new\n \/\/\/ path.\n filter_type& filter(stream_slot slot) {\n CAF_LOG_TRACE(CAF_ARG(slot));\n return state_map_[slot].filter;\n }\n\n \/\/\/ Returns whether all filters satisfy the predicate as if applying\n \/\/\/ `std::all_of`.\n template <class UnaryPredicate>\n bool all_filters(UnaryPredicate predicate) {\n return std::all_of(state_map_.begin(), state_map_.end(),\n [&](const typename state_map_type::value_type& kvp) {\n return predicate(kvp.second);\n });\n }\n\n \/\/\/ Returns whether any filter satisfies the predicate as if applying\n \/\/\/ `std::any_of`.\n template <class UnaryPredicate>\n bool any_filter(UnaryPredicate predicate) {\n return std::any_of(state_map_.begin(), state_map_.end(),\n [&](const typename state_map_type::value_type& kvp) {\n return predicate(kvp.second);\n });\n }\n\n \/\/\/ Returns whether no filter satisfies the predicate as if applying\n \/\/\/ `std::none_of`.\n template <class UnaryPredicate>\n bool no_filter(UnaryPredicate predicate) {\n return std::none_of(state_map_.begin(), state_map_.end(),\n [&](const typename state_map_type::value_type& kvp) {\n return predicate(kvp.second);\n });\n }\n\n \/\/\/ Returns the broadcast states for all paths.\n state_map_type& states() {\n return state_map_;\n }\n\n \/\/\/ Returns the broadcast states for all paths.\n const state_map_type& states() const {\n return state_map_;\n }\n\n \/\/\/ Returns the selector for filtering outgoing data.\n select_type& selector() {\n return select_;\n }\n\n \/\/\/ Returns the selector for filtering outgoing data.\n const select_type& selector() const {\n return select_;\n }\n\n \/\/ -- overridden functions ---------------------------------------------------\n\n typename super::path_ptr add_path(stream_slots slots,\n strong_actor_ptr target) override {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(target));\n \/\/ Make sure we have state for the slot.\n state_map_.emplace(slots.sender, path_state{});\n \/\/ Append to `paths_`.\n auto index = this->paths_.size();\n auto result = super::add_path(slots, target);\n if (result == nullptr)\n return nullptr;\n \/\/ Make sure state_map_ and paths_ are always equally sorted, otherwise\n \/\/ we'll run into UB when calling `zip_foreach`.\n CAF_ASSERT(index == this->paths_.size() - 1);\n CAF_ASSERT(result->slots == slots);\n CAF_ASSERT(this->paths_.container().back().first == slots.sender);\n CAF_ASSERT(this->paths_.container().back().second.get() == result);\n auto& ys = state_map_.container();\n if (ys[index].first != slots.sender) {\n auto i = state_map_.find(slots.sender);\n CAF_ASSERT(i != ys.end());\n CAF_ASSERT(std::distance(ys.begin(), i) > static_cast<ptrdiff_t>(index));\n using std::swap;\n swap(ys[index], *i);\n }\n return result;\n }\n\n void emit_batches() override {\n CAF_LOG_TRACE(CAF_ARG2(\"buffered\", this->buffered())\n << CAF_ARG2(\"paths\", this->paths_.size()));\n emit_batches_impl(false);\n }\n\n void force_emit_batches() override {\n CAF_LOG_TRACE(CAF_ARG2(\"buffered\", this->buffered())\n << CAF_ARG2(\"paths\", this->paths_.size()));\n emit_batches_impl(true);\n }\n\nprotected:\n void about_to_erase(outbound_path* ptr, bool silent,\n error* reason) override {\n CAF_LOG_DEBUG(\"remove cache:\" << CAF_ARG2(\"slot\", ptr->slots.sender));\n state_map_.erase(ptr->slots.sender);\n super::about_to_erase(ptr, silent, reason);\n }\n\nprivate:\n void emit_batches_impl(bool force_underfull) {\n CAF_ASSERT(this->paths_.size() <= state_map_.size());\n if (this->paths_.empty())\n return;\n \/\/ Calculate the chunk size, i.e., how many more items we can put to our\n \/\/ caches at the most.\n struct get_credit {\n inline size_t operator()(typename map_type::value_type& x) {\n return static_cast<size_t>(x.second->open_credit);\n }\n };\n struct get_cache_size {\n inline size_t operator()(typename state_map_type::value_type& x) {\n return x.second.buf.size();\n }\n };\n auto f = [](size_t x, size_t credit, size_t cache_size) {\n auto y = credit > cache_size ? credit - cache_size : 0u;\n return x < y ? x : y;\n };\n auto chunk_size = detail::zip_fold(\n f, std::numeric_limits<size_t>::max(),\n detail::make_container_view<get_credit>(this->paths_.container()),\n detail::make_container_view<get_cache_size>(state_map_.container()));\n auto chunk = this->get_chunk(chunk_size);\n if (chunk.empty()) {\n auto g = [&](typename map_type::value_type& x,\n typename state_map_type::value_type& y) {\n x.second->emit_batches(this->self_, y.second.buf, force_underfull);\n };\n detail::zip_foreach(g, this->paths_.container(), state_map_.container());\n } else {\n auto g = [&](typename map_type::value_type& x,\n typename state_map_type::value_type& y) {\n \/\/ TODO: replace with `if constexpr` when switching to C++17\n auto& st = y.second;\n if (std::is_same<select_type, detail::select_all>::value) {\n st.buf.insert(st.buf.end(), chunk.begin(), chunk.end());\n } else {\n for (auto& piece : chunk)\n if (select_(st.filter, piece))\n st.buf.emplace_back(piece);\n }\n x.second->emit_batches(this->self_, st.buf, force_underfull);\n };\n detail::zip_foreach(g, this->paths_.container(), state_map_.container());\n }\n }\n\n state_map_type state_map_;\n select_type select_;\n};\n\n} \/\/ namespace caf\n\n#endif \/\/ CAF_BROADCAST_SCATTERER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (C) 2008-2013 The Communi Project\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; 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. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"treedelegate.h\"\n#include \"treerole.h\"\n#include <QStyleOptionViewItem>\n#include <QLineEdit>\n#include <QPalette>\n#include <QPainter>\n\nTreeDelegate::TreeDelegate(QObject* parent) : QStyledItemDelegate(parent)\n{\n}\n\nQSize TreeDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const\n{\n QSize size = QStyledItemDelegate::sizeHint(option, index);\n static int height = 0;\n if (!height) {\n QLineEdit lineEdit;\n lineEdit.setStyleSheet(\"QLineEdit { border: 1px solid transparent; }\");\n height = lineEdit.sizeHint().height();\n }\n size.setHeight(height);\n return size;\n}\n\nvoid TreeDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const\n{\n if (!index.parent().isValid()) {\n const bool selected = option.state & QStyle::State_Selected;\n const_cast<QStyleOptionViewItem&>(option).state &= ~(QStyle::State_Selected | QStyle::State_MouseOver);\n\n QColor c1 = option.palette.color(QPalette::Light);\n QColor c2 = option.palette.color(QPalette::Button);\n if (selected)\n qSwap(c1, c2);\n\n QLinearGradient gradient(option.rect.topLeft(), option.rect.bottomLeft());\n gradient.setColorAt(0.0, c1);\n gradient.setColorAt(1.0, c2);\n painter->fillRect(option.rect, gradient);\n\n QVector<QLine> lines;\n if (index.row() > 0)\n lines += QLine(option.rect.topLeft(), option.rect.topRight());\n lines += QLine(option.rect.bottomLeft(), option.rect.bottomRight());\n QPen oldPen = painter->pen();\n painter->setPen(option.palette.color(QPalette::Dark));\n painter->drawLines(lines);\n painter->setPen(oldPen);\n }\n\n if (index.parent().isValid() && index.column() == 1) {\n QRect rect;\n rect.setWidth(option.rect.width() - 2);\n const int ascent = option.fontMetrics.ascent();\n rect.setHeight(ascent + qMax(option.rect.height() % 2, ascent % 2));\n rect.moveCenter(option.rect.center());\n\n QColor color = index.data(Qt::BackgroundRole).value<QColor>();\n if (!color.isValid())\n color = option.palette.color(QPalette::Button);\n\n painter->save();\n painter->setPen(Qt::NoPen);\n painter->setBrush(color);\n painter->setRenderHint(QPainter::Antialiasing);\n painter->drawRoundedRect(rect, 40, 80, Qt::RelativeSize);\n painter->restore();\n }\n\n QStyledItemDelegate::paint(painter, option, index);\n\n if (index.parent().isValid() && index.column() == 1) {\n int badge = index.data(TreeRole::Badge).toInt();\n if (badge > 0) {\n painter->save();\n QFont font;\n if (font.pointSize() != -1)\n font.setPointSizeF(0.8 * font.pointSizeF());\n painter->setFont(font);\n\n QString txt;\n if (badge > 999)\n txt = QLatin1String(\"...\");\n else\n txt = QFontMetrics(font).elidedText(QString::number(badge), Qt::ElideRight, option.rect.width());\n\n painter->setPen(option.palette.color(QPalette::ButtonText));\n painter->drawText(option.rect, Qt::AlignCenter, txt);\n painter->restore();\n }\n }\n}\n\nvoid TreeDelegate::initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const\n{\n QStyledItemDelegate::initStyleOption(option, index);\n if (index.parent().isValid() && index.column() == 1) {\n QStyleOptionViewItemV4* v4 = qstyleoption_cast<QStyleOptionViewItemV4*>(option);\n if (v4)\n v4->backgroundBrush = Qt::transparent;\n }\n}\n<commit_msg>Fix badge background<commit_after>\/*\n* Copyright (C) 2008-2013 The Communi Project\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; 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. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"treedelegate.h\"\n#include \"treerole.h\"\n#include <QStyleOptionViewItem>\n#include <QLineEdit>\n#include <QPalette>\n#include <QPainter>\n\nTreeDelegate::TreeDelegate(QObject* parent) : QStyledItemDelegate(parent)\n{\n}\n\nQSize TreeDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const\n{\n QSize size = QStyledItemDelegate::sizeHint(option, index);\n static int height = 0;\n if (!height) {\n QLineEdit lineEdit;\n lineEdit.setStyleSheet(\"QLineEdit { border: 1px solid transparent; }\");\n height = lineEdit.sizeHint().height();\n }\n size.setHeight(height);\n return size;\n}\n\nvoid TreeDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const\n{\n int badge = 0;\n\n if (!index.parent().isValid()) {\n const bool selected = option.state & QStyle::State_Selected;\n const_cast<QStyleOptionViewItem&>(option).state &= ~(QStyle::State_Selected | QStyle::State_MouseOver);\n\n QColor c1 = option.palette.color(QPalette::Light);\n QColor c2 = option.palette.color(QPalette::Button);\n if (selected)\n qSwap(c1, c2);\n\n QLinearGradient gradient(option.rect.topLeft(), option.rect.bottomLeft());\n gradient.setColorAt(0.0, c1);\n gradient.setColorAt(1.0, c2);\n painter->fillRect(option.rect, gradient);\n\n QVector<QLine> lines;\n if (index.row() > 0)\n lines += QLine(option.rect.topLeft(), option.rect.topRight());\n lines += QLine(option.rect.bottomLeft(), option.rect.bottomRight());\n QPen oldPen = painter->pen();\n painter->setPen(option.palette.color(QPalette::Dark));\n painter->drawLines(lines);\n painter->setPen(oldPen);\n } else if (index.column() == 1) {\n badge = index.data(TreeRole::Badge).toInt();\n }\n\n if (badge > 0) {\n QRect rect;\n rect.setWidth(option.rect.width() - 2);\n const int ascent = option.fontMetrics.ascent();\n rect.setHeight(ascent + qMax(option.rect.height() % 2, ascent % 2));\n rect.moveCenter(option.rect.center());\n\n QColor color = index.data(Qt::BackgroundRole).value<QColor>();\n if (!color.isValid())\n color = option.palette.color(QPalette::Button);\n\n painter->save();\n painter->setPen(Qt::NoPen);\n painter->setBrush(color);\n painter->setRenderHint(QPainter::Antialiasing);\n painter->drawRoundedRect(rect, 40, 80, Qt::RelativeSize);\n painter->restore();\n }\n\n QStyledItemDelegate::paint(painter, option, index);\n\n if (badge > 0) {\n painter->save();\n QFont font;\n if (font.pointSize() != -1)\n font.setPointSizeF(0.8 * font.pointSizeF());\n painter->setFont(font);\n\n QString txt;\n if (badge > 999)\n txt = QLatin1String(\"...\");\n else\n txt = QFontMetrics(font).elidedText(QString::number(badge), Qt::ElideRight, option.rect.width());\n\n painter->setPen(option.palette.color(QPalette::ButtonText));\n painter->drawText(option.rect, Qt::AlignCenter, txt);\n painter->restore();\n }\n}\n\nvoid TreeDelegate::initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const\n{\n QStyledItemDelegate::initStyleOption(option, index);\n if (index.parent().isValid() && index.column() == 1) {\n QStyleOptionViewItemV4* v4 = qstyleoption_cast<QStyleOptionViewItemV4*>(option);\n if (v4)\n v4->backgroundBrush = Qt::transparent;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=============================================================================\n\tCopyright (c) 2012-2013 Richard Otis\n\n Distributed under the Boost Software License, Version 1.0. (See accompanying\n file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n=============================================================================*\/\n\n\/\/ Model for magnetic ordering according to Inden-Hillert-Jarl (IHJ)\n\/\/ Reference: Inden, 1976. Hillert and Jarl, 1978.\n\/\/ Handling for anti-ferromagnetic (AFM) states done according to Hertzman and Sundman, 1982.\n\/\/ Implementation follows from a review of the IHJ model by W. Xiong et al., 2012.\n\/\/ Note: This is the IHJ model, not Xiong's model.\n\n#include \"libgibbs\/include\/libgibbs_pch.hpp\"\n#include \"libgibbs\/include\/models.hpp\"\n#include \"libgibbs\/include\/optimizer\/opt_Gibbs.hpp\"\n#include <string>\n#include <sstream>\n#include <set>\n#include <limits>\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/composite_key.hpp>\n#include <boost\/multi_index\/member.hpp>\n#include <boost\/multi_index\/ordered_index.hpp>\n#include <boost\/tuple\/tuple.hpp>\n\nusing boost::spirit::utree;\ntypedef boost::spirit::utree_type utree_type;\nusing boost::multi_index_container;\nusing namespace boost::multi_index;\n\n\/\/ Apply op with root_tree as left hand side and new_tree as right hand side\nutree a_o (const utree &root_tree, const utree &new_tree, const std::string &op) {\n\tutree temp_tree;\n\ttemp_tree.push_back(op);\n\ttemp_tree.push_back(root_tree);\n\ttemp_tree.push_back(new_tree);\n\treturn temp_tree;\n}\n\/\/ Apply op with root_tree as left hand side\nutree a_o (const utree &root_tree, const std::string &op) {\n\tutree temp_tree;\n\ttemp_tree.push_back(op);\n\ttemp_tree.push_back(root_tree);\n\treturn temp_tree;\n}\n\nutree max_magnetic_entropy(const utree &beta);\nutree magnetic_polynomial(const utree &tc_tree, const double &p, const double &afm_factor);\nutree get_afm_factor(const utree &tree, const double &afm_factor);\n\nIHJMagneticModel::IHJMagneticModel(\n\t\tconst std::string &phasename,\n\t\tconst sublattice_set &subl_set,\n\t\tconst parameter_set ¶m_set,\n\t\tconst double &afm_factor,\n\t\tconst double &sro_enthalpy_order_fraction\n\t\t) : EnergyModel(phasename, subl_set, param_set) {\n\tif (afm_factor == 0 || sro_enthalpy_order_fraction == 0) {\n\t\t\/\/ There is no magnetic contribution\n\t\tmodel_ast = utree(0);\n\t\treturn;\n\t}\n\tsublattice_set_view ssv;\n\tparameter_set_view psv;\n\tparameter_set_view psv_subview_tc, psv_subview_bm;\n\tutree Curie_temperature, mean_magnetic_moment;\n\tstd::string scantype;\n\tboost::multi_index::index<sublattice_set,phases>::type::iterator ic0,ic1;\n\tboost::multi_index::index<parameter_set_view,type_index>::type::iterator it0, it1;\n\tboost::multi_index::index<parameter_set,phase_index>::type::iterator pa_start,pa_end;\n\n\t\/\/ Get all the sublattices for this phase\n\tboost::tuples::tie(ic0,ic1)=get<phases>(subl_set).equal_range(phasename);\n\t\/\/ Construct a view from the iterators\n\twhile (ic0 != ic1) {\n\t\tssv.insert(&*ic0);\n\t\t++ic0;\n\t}\n\t\/\/ Get all the parameters for this phase\n\tboost::tuples::tie(pa_start,pa_end)=get<phase_index>(param_set).equal_range(phasename);\n\t\/\/ Construct a view from the iterators\n\twhile (pa_start != pa_end) {\n\t\tpsv.insert(&*pa_start);\n\t\t++pa_start;\n\t}\n\n\t\/\/ build subview to the parameter \"TC\"\n\tscantype = \"TC\";\n\tboost::tuples::tie(it0,it1)=get<type_index>(psv).equal_range(scantype);\n\n\t\/\/ Construct a subview from the view\n\twhile (it0 != it1) {\n\t\tpsv_subview_tc.insert(*it0);\n\t\t++it0;\n\t}\n\tCurie_temperature = permute_site_fractions(ssv, sublattice_set_view(), psv_subview_tc, (int)0);\n\tCurie_temperature = a_o(Curie_temperature,\n\t\t\tpermute_site_fractions_with_interactions(ssv, sublattice_set_view(), psv_subview_tc, (int)0),\n\t\t\t\"+\"\n\t);\n\tCurie_temperature = simplify_utree(Curie_temperature);\n\tstd::cout << \"Curie_temperature: \" << Curie_temperature << std::endl;\n\tif (is_zero_tree(Curie_temperature)) {\n\t\t\/\/ Transition temperature is always zero, no magnetic contribution\n\t\tmodel_ast = utree(0);\n\t\treturn;\n\t}\n\n\t\/\/ Now find parameters of type \"BMAGN\"\n\tscantype = \"BMAGN\";\n\tboost::tuples::tie(it0,it1)=get<type_index>(psv).equal_range(scantype);\n\n\t\/\/ Construct a subview from the view\n\twhile (it0 != it1) {\n\t\tpsv_subview_bm.insert(*it0);\n\t\t++it0;\n\t}\n\tmean_magnetic_moment = permute_site_fractions(ssv, sublattice_set_view(), psv_subview_bm, (int)0);\n\tmean_magnetic_moment = a_o(mean_magnetic_moment,\n\t\t\t\tpermute_site_fractions_with_interactions(ssv, sublattice_set_view(), psv_subview_bm, (int)0),\n\t\t\t\t\"+\"\n\t\t);\n\tmean_magnetic_moment = simplify_utree(mean_magnetic_moment);\n\tif (is_zero_tree(mean_magnetic_moment)) {\n\t\t\/\/ Mean magnetic moment is always zero, no magnetic contribution\n\t\tmodel_ast = utree(0);\n\t\treturn;\n\t}\n\telse {\n\t\t\/\/ Apply AFM factor\n\t\tmean_magnetic_moment = a_o(get_afm_factor(mean_magnetic_moment, afm_factor), mean_magnetic_moment, \"*\");\n\t}\n\n\tmodel_ast = a_o(\"T\", max_magnetic_entropy(mean_magnetic_moment), \"*\");\n\tmodel_ast = a_o(model_ast, magnetic_polynomial(Curie_temperature, sro_enthalpy_order_fraction, afm_factor), \"*\");\n\n\n\tnormalize_utree(model_ast, ssv);\n}\n\nutree magnetic_polynomial(const utree &tc_tree, const double &p, const double &afm_factor) {\n\t\/\/ These are constant factors from the heat capacity integration\n\tdouble A = (518.0\/1125.0) + ((11692.0\/15975.0)*((1.0\/p) - 1.0));\n\tdouble B = 79.0\/(140*p);\n\tdouble C = (474.0\/497.0)*((1.0\/p)-1.0);\n\tutree ret_tree, tau, subcritical_tree, supercritical_tree;\n\n\ttau = a_o(\"T\", tc_tree, \"\/\");\n\t\/\/ If tau < 0, apply the anti-ferromagnetic (AFM) factor\n\ttau = a_o(get_afm_factor(tau, afm_factor), tau, \"*\");\n\n\t\/\/ TODO: This is a mess. Using the utree visitation interface might make this better.\n\n\t\/\/ First calculate the polynomial for 0 < tau < 1\n\tutree taum1 = a_o(B, a_o(tau, -1, \"**\"), \"*\");\n\tutree tau3 = a_o(1.0\/6.0, a_o(tau, 3, \"**\"), \"*\");\n\tutree tau9 = a_o(1.0\/135.0, a_o(tau, 9, \"**\"), \"*\");\n\tutree tau15 = a_o(1.0\/600.0, a_o(tau, 15, \"**\"), \"*\");\n\tutree total_taus = a_o(C, a_o(a_o(tau3, tau9, \"+\"), tau15, \"+\"), \"*\");\n\n\ttotal_taus = a_o(taum1, total_taus, \"+\");\n\ttotal_taus = a_o(-1.0\/A, total_taus, \"*\");\n\tsubcritical_tree = a_o(1.0, total_taus, \"-\");\n\n\n\t\/\/ Now calculate the polynomial for tau >= 1\n\tutree taum5 = a_o(1.0\/10.0, a_o(tau, -5, \"**\"), \"*\");\n\tutree taum15 = a_o(1.0\/315.0, a_o(tau, -15, \"**\"), \"*\");\n\tutree taum25 = a_o(1.0\/1500.0, a_o(tau, -25, \"**\"), \"*\");\n\ttotal_taus = a_o(a_o(taum5, taum15, \"+\"), taum25, \"+\");\n\tsupercritical_tree = a_o(-1.0\/A, total_taus, \"*\");\n\n\tret_tree.push_back(\"@\");\n\tret_tree.push_back(tau);\n\tret_tree.push_back(-std::numeric_limits<double>::max());\n\tret_tree.push_back(1);\n\tret_tree.push_back(subcritical_tree);\n\tret_tree.push_back(\"@\");\n\tret_tree.push_back(tau);\n\tret_tree.push_back(1);\n\tret_tree.push_back(std::numeric_limits<double>::max());\n\tret_tree.push_back(supercritical_tree);\n\n\treturn ret_tree;\n}\n\nutree max_magnetic_entropy(const utree &beta) {\n\t\/\/ beta is the mean magnetic moment\n\t\/\/ The return value is the maximum magnetic entropy of an element undergoing the FM disordering transition\n\tutree ret_tree;\n\tret_tree = a_o(SI_GAS_CONSTANT, a_o(a_o(beta, 1.0, \"+\"), \"LN\"), \"*\"); \/\/ R*ln(beta + 1)\n\n\treturn ret_tree;\n}\n\n\/\/ Calculate the anti-ferromagnetic (AFM) factor\nutree get_afm_factor(const utree &tree, const double &afm_factor) {\n\tutree afm_factor_tree;\n\tafm_factor_tree.push_back(\"@\");\n\tafm_factor_tree.push_back(tree);\n\tafm_factor_tree.push_back(-std::numeric_limits<double>::max());\n\tafm_factor_tree.push_back(0);\n\tafm_factor_tree.push_back(1.0\/afm_factor);\n\tafm_factor_tree.push_back(\"@\");\n\tafm_factor_tree.push_back(tree);\n\tafm_factor_tree.push_back(0);\n\tafm_factor_tree.push_back(std::numeric_limits<double>::max());\n\tafm_factor_tree.push_back(1);\n\treturn afm_factor_tree;\n}\n<commit_msg>Fix how AFM factor is applied to TC<commit_after>\/*=============================================================================\n\tCopyright (c) 2012-2013 Richard Otis\n\n Distributed under the Boost Software License, Version 1.0. (See accompanying\n file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n=============================================================================*\/\n\n\/\/ Model for magnetic ordering according to Inden-Hillert-Jarl (IHJ)\n\/\/ Reference: Inden, 1976. Hillert and Jarl, 1978.\n\/\/ Handling for anti-ferromagnetic (AFM) states done according to Hertzman and Sundman, 1982.\n\/\/ Implementation follows from a review of the IHJ model by W. Xiong et al., 2012.\n\/\/ Note: This is the IHJ model, not Xiong's model.\n\n#include \"libgibbs\/include\/libgibbs_pch.hpp\"\n#include \"libgibbs\/include\/models.hpp\"\n#include \"libgibbs\/include\/optimizer\/opt_Gibbs.hpp\"\n#include <string>\n#include <sstream>\n#include <set>\n#include <limits>\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/composite_key.hpp>\n#include <boost\/multi_index\/member.hpp>\n#include <boost\/multi_index\/ordered_index.hpp>\n#include <boost\/tuple\/tuple.hpp>\n\nusing boost::spirit::utree;\ntypedef boost::spirit::utree_type utree_type;\nusing boost::multi_index_container;\nusing namespace boost::multi_index;\n\n\/\/ Apply op with root_tree as left hand side and new_tree as right hand side\nutree a_o (const utree &root_tree, const utree &new_tree, const std::string &op) {\n\tutree temp_tree;\n\ttemp_tree.push_back(op);\n\ttemp_tree.push_back(root_tree);\n\ttemp_tree.push_back(new_tree);\n\treturn temp_tree;\n}\n\/\/ Apply op with root_tree as left hand side\nutree a_o (const utree &root_tree, const std::string &op) {\n\tutree temp_tree;\n\ttemp_tree.push_back(op);\n\ttemp_tree.push_back(root_tree);\n\treturn temp_tree;\n}\n\nutree max_magnetic_entropy(const utree &beta);\nutree magnetic_polynomial(const utree &tc_tree, const double &p, const double &afm_factor);\nutree get_afm_factor(const utree &tree, const double &afm_factor);\n\nIHJMagneticModel::IHJMagneticModel(\n\t\tconst std::string &phasename,\n\t\tconst sublattice_set &subl_set,\n\t\tconst parameter_set ¶m_set,\n\t\tconst double &afm_factor,\n\t\tconst double &sro_enthalpy_order_fraction\n\t\t) : EnergyModel(phasename, subl_set, param_set) {\n\tif (afm_factor == 0 || sro_enthalpy_order_fraction == 0) {\n\t\t\/\/ There is no magnetic contribution\n\t\tmodel_ast = utree(0);\n\t\treturn;\n\t}\n\tsublattice_set_view ssv;\n\tparameter_set_view psv;\n\tparameter_set_view psv_subview_tc, psv_subview_bm;\n\tutree Curie_temperature, mean_magnetic_moment;\n\tstd::string scantype;\n\tboost::multi_index::index<sublattice_set,phases>::type::iterator ic0,ic1;\n\tboost::multi_index::index<parameter_set_view,type_index>::type::iterator it0, it1;\n\tboost::multi_index::index<parameter_set,phase_index>::type::iterator pa_start,pa_end;\n\n\t\/\/ Get all the sublattices for this phase\n\tboost::tuples::tie(ic0,ic1)=get<phases>(subl_set).equal_range(phasename);\n\t\/\/ Construct a view from the iterators\n\twhile (ic0 != ic1) {\n\t\tssv.insert(&*ic0);\n\t\t++ic0;\n\t}\n\t\/\/ Get all the parameters for this phase\n\tboost::tuples::tie(pa_start,pa_end)=get<phase_index>(param_set).equal_range(phasename);\n\t\/\/ Construct a view from the iterators\n\twhile (pa_start != pa_end) {\n\t\tpsv.insert(&*pa_start);\n\t\t++pa_start;\n\t}\n\n\t\/\/ build subview to the parameter \"TC\"\n\tscantype = \"TC\";\n\tboost::tuples::tie(it0,it1)=get<type_index>(psv).equal_range(scantype);\n\n\t\/\/ Construct a subview from the view\n\twhile (it0 != it1) {\n\t\tpsv_subview_tc.insert(*it0);\n\t\t++it0;\n\t}\n\tCurie_temperature = permute_site_fractions(ssv, sublattice_set_view(), psv_subview_tc, (int)0);\n\tCurie_temperature = a_o(Curie_temperature,\n\t\t\tpermute_site_fractions_with_interactions(ssv, sublattice_set_view(), psv_subview_tc, (int)0),\n\t\t\t\"+\"\n\t);\n\tCurie_temperature = simplify_utree(Curie_temperature);\n\tif (is_zero_tree(Curie_temperature)) {\n\t\t\/\/ Transition temperature is always zero, no magnetic contribution\n\t\tmodel_ast = utree(0);\n\t\treturn;\n\t}\n\t\/\/ Apply AFM factor to TC\n\tCurie_temperature = a_o(get_afm_factor(Curie_temperature, afm_factor), Curie_temperature, \"*\");\n\n\t\/\/ Now find parameters of type \"BMAGN\"\n\tscantype = \"BMAGN\";\n\tboost::tuples::tie(it0,it1)=get<type_index>(psv).equal_range(scantype);\n\n\t\/\/ Construct a subview from the view\n\twhile (it0 != it1) {\n\t\tpsv_subview_bm.insert(*it0);\n\t\t++it0;\n\t}\n\tmean_magnetic_moment = permute_site_fractions(ssv, sublattice_set_view(), psv_subview_bm, (int)0);\n\tmean_magnetic_moment = a_o(mean_magnetic_moment,\n\t\t\t\tpermute_site_fractions_with_interactions(ssv, sublattice_set_view(), psv_subview_bm, (int)0),\n\t\t\t\t\"+\"\n\t\t);\n\tmean_magnetic_moment = simplify_utree(mean_magnetic_moment);\n\tif (is_zero_tree(mean_magnetic_moment)) {\n\t\t\/\/ Mean magnetic moment is always zero, no magnetic contribution\n\t\tmodel_ast = utree(0);\n\t\treturn;\n\t}\n\telse {\n\t\t\/\/ Apply AFM factor\n\t\tmean_magnetic_moment = a_o(get_afm_factor(mean_magnetic_moment, afm_factor), mean_magnetic_moment, \"*\");\n\t}\n\tmodel_ast = a_o(\"T\", max_magnetic_entropy(mean_magnetic_moment), \"*\");\n\tmodel_ast = a_o(model_ast, magnetic_polynomial(Curie_temperature, sro_enthalpy_order_fraction, afm_factor), \"*\");\n\n\n\tnormalize_utree(model_ast, ssv);\n}\n\nutree magnetic_polynomial(const utree &tc_tree, const double &p, const double &afm_factor) {\n\t\/\/ These are constant factors from the heat capacity integration\n\tdouble A = (518.0\/1125.0) + ((11692.0\/15975.0)*((1.0\/p) - 1.0));\n\tdouble B = 79.0\/(140*p);\n\tdouble C = (474.0\/497.0)*((1.0\/p)-1.0);\n\tutree ret_tree, tau, subcritical_tree, supercritical_tree;\n\n\ttau = a_o(\"T\", tc_tree, \"\/\");\n\n\t\/\/ TODO: This is a mess. Using the utree visitation interface might make this better.\n\n\t\/\/ First calculate the polynomial for 0 < tau < 1\n\tutree taum1 = a_o(B, a_o(tau, -1.0, \"**\"), \"*\");\n\tutree tau3 = a_o(1.0\/6.0, a_o(tau, 3.0, \"**\"), \"*\");\n\tutree tau9 = a_o(1.0\/135.0, a_o(tau, 9.0, \"**\"), \"*\");\n\tutree tau15 = a_o(1.0\/600.0, a_o(tau, 15.0, \"**\"), \"*\");\n\tutree total_taus = a_o(C, a_o(a_o(tau3, tau9, \"+\"), tau15, \"+\"), \"*\");\n\n\ttotal_taus = a_o(taum1, total_taus, \"+\");\n\ttotal_taus = a_o(-1.0\/A, total_taus, \"*\");\n\tsubcritical_tree = a_o(1.0, total_taus, \"-\");\n\n\n\t\/\/ Now calculate the polynomial for tau >= 1\n\tutree taum5 = a_o(1.0\/10.0, a_o(tau, -5.0, \"**\"), \"*\");\n\tutree taum15 = a_o(1.0\/315.0, a_o(tau, -15.0, \"**\"), \"*\");\n\tutree taum25 = a_o(1.0\/1500.0, a_o(tau, -25.0, \"**\"), \"*\");\n\ttotal_taus = a_o(a_o(taum5, taum15, \"+\"), taum25, \"+\");\n\tsupercritical_tree = a_o(-1.0\/A, total_taus, \"*\");\n\n\tret_tree.push_back(\"@\");\n\tret_tree.push_back(tau);\n\tret_tree.push_back(-std::numeric_limits<double>::max());\n\tret_tree.push_back(1);\n\tret_tree.push_back(subcritical_tree);\n\tret_tree.push_back(\"@\");\n\tret_tree.push_back(tau);\n\tret_tree.push_back(1);\n\tret_tree.push_back(std::numeric_limits<double>::max());\n\tret_tree.push_back(supercritical_tree);\n\n\treturn ret_tree;\n}\n\nutree max_magnetic_entropy(const utree &beta) {\n\t\/\/ beta is the mean magnetic moment\n\t\/\/ The return value is the maximum magnetic entropy of an element undergoing the FM disordering transition\n\tutree ret_tree;\n\tret_tree = a_o(SI_GAS_CONSTANT, a_o(a_o(beta, 1.0, \"+\"), \"LN\"), \"*\"); \/\/ R*ln(beta + 1)\n\n\treturn ret_tree;\n}\n\n\/\/ Calculate the anti-ferromagnetic (AFM) factor\nutree get_afm_factor(const utree &tree, const double &afm_factor) {\n\tutree afm_factor_tree;\n\tafm_factor_tree.push_back(\"@\");\n\tafm_factor_tree.push_back(tree);\n\tafm_factor_tree.push_back(-std::numeric_limits<double>::max());\n\tafm_factor_tree.push_back(0);\n\tafm_factor_tree.push_back(1.0\/afm_factor);\n\tafm_factor_tree.push_back(\"@\");\n\tafm_factor_tree.push_back(tree);\n\tafm_factor_tree.push_back(0);\n\tafm_factor_tree.push_back(std::numeric_limits<double>::max());\n\tafm_factor_tree.push_back(1);\n\treturn afm_factor_tree;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <bts\/blockchain\/account_record.hpp>\n#include <bts\/blockchain\/chain_interface.hpp>\n\nnamespace bts { namespace blockchain {\n\n share_type account_record::delegate_pay_balance()const\n {\n FC_ASSERT( is_delegate() );\n return delegate_info->pay_balance;\n }\n\n bool account_record::is_delegate()const\n {\n return delegate_info.valid();\n }\n\n int64_t account_record::net_votes()const\n {\n FC_ASSERT( is_delegate() );\n return delegate_info->votes_for;\n }\n\n void account_record::adjust_votes_for( const share_type delta )\n {\n FC_ASSERT( is_delegate() );\n delegate_info->votes_for += delta;\n }\n\n bool account_record::is_retracted()const\n {\n return active_key() == public_key_type();\n }\n\n address account_record::active_address()const\n {\n return address( active_key() );\n }\n\n void account_record::set_active_key( const time_point_sec now, const public_key_type& new_key )\n { try {\n FC_ASSERT( now != fc::time_point_sec() );\n active_key_history[ now ] = new_key;\n } FC_CAPTURE_AND_RETHROW( (now)(new_key) ) }\n\n public_key_type account_record::active_key()const\n {\n FC_ASSERT( !active_key_history.empty() );\n return active_key_history.rbegin()->second;\n }\n\n uint8_t account_record::delegate_pay_rate()const\n {\n if( !is_delegate() )\n return -1;\n\n return delegate_info->pay_rate;\n }\n\n void account_record::set_signing_key( uint32_t block_num, const public_key_type& signing_key )\n {\n FC_ASSERT( is_delegate() );\n delegate_info->signing_key_history[ block_num ] = signing_key;\n }\n\n public_key_type account_record::signing_key()const\n {\n FC_ASSERT( is_delegate() );\n FC_ASSERT( !delegate_info->signing_key_history.empty() );\n return delegate_info->signing_key_history.crbegin()->second;\n }\n\n address account_record::signing_address()const\n {\n return address( signing_key() );\n }\n\n void account_record::sanity_check( const chain_interface& db )const\n { try {\n FC_ASSERT( id > 0 );\n FC_ASSERT( !name.empty() );\n FC_ASSERT( !active_key_history.empty() );\n if( delegate_info.valid() )\n {\n FC_ASSERT( delegate_info->votes_for >= 0 );\n FC_ASSERT( delegate_info->pay_rate <= 100 );\n FC_ASSERT( !delegate_info->signing_key_history.empty() );\n FC_ASSERT( delegate_info->pay_balance >= 0 );\n }\n } FC_CAPTURE_AND_RETHROW( (*this) ) }\n\n oaccount_record account_record::lookup( const chain_interface& db, const account_id_type id )\n { try {\n return db.account_lookup_by_id( id );\n } FC_CAPTURE_AND_RETHROW( (id) ) }\n\n oaccount_record account_record::lookup( const chain_interface& db, const string& name )\n { try {\n return db.account_lookup_by_name( name );\n } FC_CAPTURE_AND_RETHROW( (name) ) }\n\n oaccount_record account_record::lookup( const chain_interface& db, const address& addr )\n { try {\n return db.account_lookup_by_address( addr );\n } FC_CAPTURE_AND_RETHROW( (addr) ) }\n\n void account_record::store( chain_interface& db, const account_id_type id, const account_record& record )\n { try {\n const oaccount_record prev_record = db.lookup<account_record>( id );\n if( prev_record.valid() )\n {\n if( prev_record->name != record.name )\n db.account_erase_from_name_map( prev_record->name );\n\n if( prev_record->owner_address() != record.owner_address() )\n db.account_erase_from_address_map( prev_record->owner_address() );\n\n if( fc::ripemd160::hash( prev_record->active_key_history ) != fc::ripemd160::hash( record.active_key_history ) )\n {\n for( const auto& item : prev_record->active_key_history )\n {\n const public_key_type& active_key = item.second;\n db.account_erase_from_address_map( address( active_key ) );\n }\n }\n\n if( prev_record->is_delegate() )\n {\n if( !record.is_delegate() || fc::ripemd160::hash( prev_record->delegate_info->signing_key_history )\n != fc::ripemd160::hash( record.delegate_info->signing_key_history ) )\n {\n for( const auto& item : prev_record->delegate_info->signing_key_history )\n {\n const public_key_type& signing_key = item.second;\n db.account_erase_from_address_map( address( signing_key ) );\n }\n }\n\n if( !prev_record->is_retracted() )\n {\n if( record.is_retracted() || !record.is_delegate() || prev_record->net_votes() != record.net_votes() )\n db.account_erase_from_vote_set( vote_del( prev_record->net_votes(), prev_record->id ) );\n }\n }\n }\n\n db.account_insert_into_id_map( id, record );\n db.account_insert_into_name_map( record.name, id );\n db.account_insert_into_address_map( record.owner_address(), id );\n\n for( const auto& item : record.active_key_history )\n {\n const public_key_type& active_key = item.second;\n if( active_key != public_key_type() ) db.account_insert_into_address_map( address( active_key ), id );\n }\n\n if( record.is_delegate() )\n {\n for( const auto& item : record.delegate_info->signing_key_history )\n {\n const public_key_type& signing_key = item.second;\n if( signing_key != public_key_type() ) db.account_insert_into_address_map( address( signing_key ), id );\n }\n\n if( !record.is_retracted() )\n db.account_insert_into_vote_set( vote_del( record.net_votes(), id ) );\n }\n } FC_CAPTURE_AND_RETHROW( (id)(record) ) }\n\n void account_record::remove( chain_interface& db, const account_id_type id )\n { try {\n const oaccount_record prev_record = db.lookup<account_record>( id );\n if( prev_record.valid() )\n {\n db.account_erase_from_id_map( id );\n db.account_erase_from_name_map( prev_record->name );\n db.account_erase_from_address_map( prev_record->owner_address() );\n\n for( const auto& item : prev_record->active_key_history )\n {\n const public_key_type& active_key = item.second;\n db.account_erase_from_address_map( address( active_key ) );\n }\n\n if( prev_record->is_delegate() )\n {\n for( const auto& item : prev_record->delegate_info->signing_key_history )\n {\n const public_key_type& signing_key = item.second;\n db.account_erase_from_address_map( address( signing_key ) );\n }\n\n if( !prev_record->is_retracted() )\n db.account_erase_from_vote_set( vote_del( prev_record->net_votes(), prev_record->id ) );\n }\n }\n } FC_CAPTURE_AND_RETHROW( (id) ) }\n\n} } \/\/ bts::blockchain\n<commit_msg>Simplify account_record indexing<commit_after>#include <bts\/blockchain\/account_record.hpp>\n#include <bts\/blockchain\/chain_interface.hpp>\n\nnamespace bts { namespace blockchain {\n\n share_type account_record::delegate_pay_balance()const\n {\n FC_ASSERT( is_delegate() );\n return delegate_info->pay_balance;\n }\n\n bool account_record::is_delegate()const\n {\n return delegate_info.valid();\n }\n\n int64_t account_record::net_votes()const\n {\n FC_ASSERT( is_delegate() );\n return delegate_info->votes_for;\n }\n\n void account_record::adjust_votes_for( const share_type delta )\n {\n FC_ASSERT( is_delegate() );\n delegate_info->votes_for += delta;\n }\n\n bool account_record::is_retracted()const\n {\n return active_key() == public_key_type();\n }\n\n address account_record::active_address()const\n {\n return address( active_key() );\n }\n\n void account_record::set_active_key( const time_point_sec now, const public_key_type& new_key )\n { try {\n FC_ASSERT( now != fc::time_point_sec() );\n active_key_history[ now ] = new_key;\n } FC_CAPTURE_AND_RETHROW( (now)(new_key) ) }\n\n public_key_type account_record::active_key()const\n {\n FC_ASSERT( !active_key_history.empty() );\n return active_key_history.rbegin()->second;\n }\n\n uint8_t account_record::delegate_pay_rate()const\n {\n if( !is_delegate() )\n return -1;\n\n return delegate_info->pay_rate;\n }\n\n void account_record::set_signing_key( uint32_t block_num, const public_key_type& signing_key )\n {\n FC_ASSERT( is_delegate() );\n delegate_info->signing_key_history[ block_num ] = signing_key;\n }\n\n public_key_type account_record::signing_key()const\n {\n FC_ASSERT( is_delegate() );\n FC_ASSERT( !delegate_info->signing_key_history.empty() );\n return delegate_info->signing_key_history.crbegin()->second;\n }\n\n address account_record::signing_address()const\n {\n return address( signing_key() );\n }\n\n void account_record::sanity_check( const chain_interface& db )const\n { try {\n FC_ASSERT( id > 0 );\n FC_ASSERT( !name.empty() );\n FC_ASSERT( !active_key_history.empty() );\n if( delegate_info.valid() )\n {\n FC_ASSERT( delegate_info->votes_for >= 0 );\n FC_ASSERT( delegate_info->pay_rate <= 100 );\n FC_ASSERT( !delegate_info->signing_key_history.empty() );\n FC_ASSERT( delegate_info->pay_balance >= 0 );\n }\n } FC_CAPTURE_AND_RETHROW( (*this) ) }\n\n oaccount_record account_record::lookup( const chain_interface& db, const account_id_type id )\n { try {\n return db.account_lookup_by_id( id );\n } FC_CAPTURE_AND_RETHROW( (id) ) }\n\n oaccount_record account_record::lookup( const chain_interface& db, const string& name )\n { try {\n return db.account_lookup_by_name( name );\n } FC_CAPTURE_AND_RETHROW( (name) ) }\n\n oaccount_record account_record::lookup( const chain_interface& db, const address& addr )\n { try {\n return db.account_lookup_by_address( addr );\n } FC_CAPTURE_AND_RETHROW( (addr) ) }\n\n void account_record::store( chain_interface& db, const account_id_type id, const account_record& record )\n { try {\n const oaccount_record prev_record = db.lookup<account_record>( id );\n if( prev_record.valid() )\n {\n if( prev_record->name != record.name )\n db.account_erase_from_name_map( prev_record->name );\n\n if( prev_record->owner_address() != record.owner_address() )\n db.account_erase_from_address_map( prev_record->owner_address() );\n\n if( prev_record->active_key() != record.active_key() )\n {\n for( const auto& item : prev_record->active_key_history )\n {\n const public_key_type& active_key = item.second;\n db.account_erase_from_address_map( address( active_key ) );\n }\n }\n\n if( prev_record->is_delegate() )\n {\n if( !record.is_delegate() || prev_record->signing_key() != record.signing_key() )\n {\n for( const auto& item : prev_record->delegate_info->signing_key_history )\n {\n const public_key_type& signing_key = item.second;\n db.account_erase_from_address_map( address( signing_key ) );\n }\n }\n\n if( !prev_record->is_retracted() )\n {\n if( record.is_retracted() || !record.is_delegate() || prev_record->net_votes() != record.net_votes() )\n db.account_erase_from_vote_set( vote_del( prev_record->net_votes(), prev_record->id ) );\n }\n }\n }\n\n db.account_insert_into_id_map( id, record );\n db.account_insert_into_name_map( record.name, id );\n db.account_insert_into_address_map( record.owner_address(), id );\n\n for( const auto& item : record.active_key_history )\n {\n const public_key_type& active_key = item.second;\n if( active_key != public_key_type() ) db.account_insert_into_address_map( address( active_key ), id );\n }\n\n if( record.is_delegate() )\n {\n for( const auto& item : record.delegate_info->signing_key_history )\n {\n const public_key_type& signing_key = item.second;\n if( signing_key != public_key_type() ) db.account_insert_into_address_map( address( signing_key ), id );\n }\n\n if( !record.is_retracted() )\n db.account_insert_into_vote_set( vote_del( record.net_votes(), id ) );\n }\n } FC_CAPTURE_AND_RETHROW( (id)(record) ) }\n\n void account_record::remove( chain_interface& db, const account_id_type id )\n { try {\n const oaccount_record prev_record = db.lookup<account_record>( id );\n if( prev_record.valid() )\n {\n db.account_erase_from_id_map( id );\n db.account_erase_from_name_map( prev_record->name );\n db.account_erase_from_address_map( prev_record->owner_address() );\n\n for( const auto& item : prev_record->active_key_history )\n {\n const public_key_type& active_key = item.second;\n db.account_erase_from_address_map( address( active_key ) );\n }\n\n if( prev_record->is_delegate() )\n {\n for( const auto& item : prev_record->delegate_info->signing_key_history )\n {\n const public_key_type& signing_key = item.second;\n db.account_erase_from_address_map( address( signing_key ) );\n }\n\n if( !prev_record->is_retracted() )\n db.account_erase_from_vote_set( vote_del( prev_record->net_votes(), prev_record->id ) );\n }\n }\n } FC_CAPTURE_AND_RETHROW( (id) ) }\n\n} } \/\/ bts::blockchain\n<|endoftext|>"} {"text":"<commit_before>#ifndef LIB_DATA_HPP__\n#define LIB_DATA_HPP__\n\n#include <lib\/include\/types.hpp>\n#include <lib\/include\/compconfig.hpp>\n#include <map>\n#include <vector>\n\nnamespace lib\n{\n\tclass DataValue;\n\ttypedef LIB_API std::map<str, DataValue> DataMap;\n\tenum class LIB_API DataType : u8\n\t{\n\t\tT_Empty,\n\t\tT_s8,\n\t\tT_u8,\n\t\tT_s16,\n\t\tT_u16,\n\t\tT_s32,\n\t\tT_u32,\n\t\tT_f64,\n\t\tT_string,\n\t\tT_Tree\n\t};\n\n\tclass LIB_API DataValue\n\t{\n\tpublic:\n\t\texplicit inline DataValue() : m_dtype{ DataType::T_Empty }, f64_{ 0 } {}\n\t\texplicit inline DataValue(const s8 value_) : m_dtype{ DataType::T_s8 }, s8_{ value_ } {}\n\t\texplicit inline DataValue(const u8 value_) : m_dtype{ DataType::T_u8 }, u8_{ value_ } {}\n\t\texplicit inline DataValue(const s16 value_) : m_dtype{ DataType::T_s16 }, s16_{ value_ } {}\n\t\texplicit inline DataValue(const u16 value_) : m_dtype{ DataType::T_u16 }, u16_{ value_ } {}\n\t\texplicit inline DataValue(const s32 value_) : m_dtype{ DataType::T_s32 }, s32_{ value_ } {}\n\t\texplicit inline DataValue(const u32 value_) : m_dtype{ DataType::T_u32 }, u32_{ value_ } {}\n\t\texplicit inline DataValue(const f64 value_) : m_dtype{ DataType::T_f64 }, f64_{ value_ } {}\n\t\texplicit inline DataValue(const str &value_) : m_dtype{ DataType::T_string }, ptr_{ new str(value_) } {}\n\t\texplicit inline DataValue(const DataMap &value_) : m_dtype{ DataType::T_Tree }, ptr_{ new DataMap(value_) } {}\n\n\t\texplicit inline DataValue(const DataValue &value_): m_dtype{ value_.m_dtype }\n\t\t{\n\t\t\tswitch (m_dtype)\n\t\t\t{\n\t\t\t\tcase DataType::T_s8:\n\t\t\t\tcase DataType::T_u8:\n\t\t\t\tcase DataType::T_s16:\n\t\t\t\tcase DataType::T_u16:\n\t\t\t\tcase DataType::T_s32:\n\t\t\t\tcase DataType::T_u32:\n\t\t\t\tcase DataType::T_f64:\n\t\t\t\t\tf64_ = value_.f64_;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::T_string:\n\t\t\t\t\tptr_ = new str(value_.getString());\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::T_Tree:\n\t\t\t\t\tptr_ = new DataMap(*value_.getMap());\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::T_Empty:\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tinline DataValue(DataValue &&other)\n\t\t{\n\t\t\tstd::swap(m_dtype, other.m_dtype);\n\t\t\tf64_ = other.f64_;\n\t\t}\n\t\t\n\t\t~DataValue();\n\n\t\tbool operator==(const s8 value_) const;\n\t\tbool operator==(const u8 value_) const;\n\t\tbool operator==(const s16 value_) const;\n\t\tbool operator==(const u16 value_) const;\n\t\tbool operator==(const s32 value_) const;\n\t\tbool operator==(const u32 value_) const;\n\t\tbool operator==(const f64 value_) const;\n\t\tbool operator==(const str &value_) const;\n\t\tbool operator==(const DataMap &value_) const;\n\t\tbool operator==(const DataValue &other) const;\n\t\tDataValue &operator=(DataValue &&other);\n\n\t\tconst s8 gets8() const;\n\t\tconst u8 getu8() const;\n\t\tconst s16 gets16() const;\n\t\tconst u16 getu16() const;\n\t\tconst s32 gets32() const;\n\t\tconst u32 getu32() const;\n\t\tconst f64 getf64() const;\n\t\tconst str getString() const;\n\t\tconst DataMap *getMap() const;\n\t\tDataMap *getMap();\n\n\t\tfriend std::ostream &operator<<(std::ostream &output, const DataValue &this_);\n\t\t\n\t\ttemplate <typename T> inline const T get() const;\n\t\ttemplate <> inline const s8 get() const { return gets8(); }\n\t\ttemplate <> inline const u8 get() const { return getu8(); }\n\t\ttemplate <> inline const s16 get() const { return gets16(); }\n\t\ttemplate <> inline const u16 get() const { return getu16(); }\n\t\ttemplate <> inline const s32 get() const { return gets32(); }\n\t\ttemplate <> inline const u32 get() const { return getu32(); }\n\t\ttemplate <> inline const f64 get() const { return getf64(); }\n\n\t\tinline const bool iss8() const { return m_dtype == DataType::T_s8; }\n\t\tinline const bool isu8() const { return m_dtype == DataType::T_s8; }\n\t\tinline const bool iss16() const { return m_dtype == DataType::T_s16; }\n\t\tinline const bool isu16() const { return m_dtype == DataType::T_u16; }\n\t\tinline const bool iss32() const { return m_dtype == DataType::T_s32; }\n\t\tinline const bool isu32() const { return m_dtype == DataType::T_u32; }\n\t\tinline const bool isf64() const { return m_dtype == DataType::T_f64; }\n\t\tinline const bool isstring() const { return m_dtype == DataType::T_string; }\n\t\tinline const bool ismap() const { return m_dtype == DataType::T_Tree; }\n\n\t\ttemplate <typename T>\n\t\tconst bool is() const;\n\n\t\ttemplate <> inline const bool is<s8>() const { return iss8(); }\n\t\ttemplate <> inline const bool is<u8>() const { return isu8(); }\n\t\ttemplate <> inline const bool is<s16>() const { return iss16(); }\n\t\ttemplate <> inline const bool is<u16>() const { return isu16(); }\n\t\ttemplate <> inline const bool is<s32>() const { return iss32(); }\n\t\ttemplate <> inline const bool is<u32>() const { return isu32(); }\n\t\ttemplate <> inline const bool is<f64>() const { return isf64(); }\n\n\t\tstatic DataMap fromStringVector(const std::vector<str> &data, u32 &count);\n\n\tprivate:\n\t\tunion\n\t\t{\n\t\t\ts8 s8_;\n\t\t\tu8 u8_;\n\t\t\ts16 s16_;\n\t\t\tu16 u16_;\n\t\t\ts32 s32_;\n\t\t\tu32 u32_;\n\t\t\tf64 f64_;\n\t\t\tvoid *ptr_;\n\t\t};\n\t\tDataType m_dtype{ DataType::T_Empty };\n\t};\n}\n\n#endif\n<commit_msg>Added assignment operator<commit_after>#ifndef LIB_DATA_HPP__\n#define LIB_DATA_HPP__\n\n#include <lib\/include\/types.hpp>\n#include <lib\/include\/compconfig.hpp>\n#include <map>\n#include <vector>\n\nnamespace lib\n{\n\tclass DataValue;\n\ttypedef LIB_API std::map<str, DataValue> DataMap;\n\tenum class LIB_API DataType : u8\n\t{\n\t\tT_Empty,\n\t\tT_s8,\n\t\tT_u8,\n\t\tT_s16,\n\t\tT_u16,\n\t\tT_s32,\n\t\tT_u32,\n\t\tT_f64,\n\t\tT_string,\n\t\tT_Tree\n\t};\n\n\tclass LIB_API DataValue\n\t{\n\tpublic:\n\t\texplicit inline DataValue() : m_dtype{ DataType::T_Empty }, f64_{ 0 } {}\n\t\texplicit inline DataValue(const s8 value_) : m_dtype{ DataType::T_s8 }, s8_{ value_ } {}\n\t\texplicit inline DataValue(const u8 value_) : m_dtype{ DataType::T_u8 }, u8_{ value_ } {}\n\t\texplicit inline DataValue(const s16 value_) : m_dtype{ DataType::T_s16 }, s16_{ value_ } {}\n\t\texplicit inline DataValue(const u16 value_) : m_dtype{ DataType::T_u16 }, u16_{ value_ } {}\n\t\texplicit inline DataValue(const s32 value_) : m_dtype{ DataType::T_s32 }, s32_{ value_ } {}\n\t\texplicit inline DataValue(const u32 value_) : m_dtype{ DataType::T_u32 }, u32_{ value_ } {}\n\t\texplicit inline DataValue(const f64 value_) : m_dtype{ DataType::T_f64 }, f64_{ value_ } {}\n\t\texplicit inline DataValue(const str &value_) : m_dtype{ DataType::T_string }, ptr_{ new str(value_) } {}\n\t\texplicit inline DataValue(const DataMap &value_) : m_dtype{ DataType::T_Tree }, ptr_{ new DataMap(value_) } {}\n\n\t\texplicit inline DataValue(const DataValue &value_): m_dtype{ value_.m_dtype }\n\t\t{\n\t\t\tswitch (m_dtype)\n\t\t\t{\n\t\t\t\tcase DataType::T_s8:\n\t\t\t\tcase DataType::T_u8:\n\t\t\t\tcase DataType::T_s16:\n\t\t\t\tcase DataType::T_u16:\n\t\t\t\tcase DataType::T_s32:\n\t\t\t\tcase DataType::T_u32:\n\t\t\t\tcase DataType::T_f64:\n\t\t\t\t\tf64_ = value_.f64_;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::T_string:\n\t\t\t\t\tptr_ = new str(value_.getString());\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::T_Tree:\n\t\t\t\t\tptr_ = new DataMap(*value_.getMap());\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::T_Empty:\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tinline DataValue(DataValue &&other)\n\t\t{\n\t\t\tstd::swap(m_dtype, other.m_dtype);\n\t\t\tf64_ = other.f64_;\n\t\t}\n\n\t\tinline DataValue &operator=(const DataValue &rh)\n\t\t{\n\t\t\tDataValue temp{ rh };\n\t\t\tstd::swap(*this, temp);\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\t~DataValue();\n\n\t\tbool operator==(const s8 value_) const;\n\t\tbool operator==(const u8 value_) const;\n\t\tbool operator==(const s16 value_) const;\n\t\tbool operator==(const u16 value_) const;\n\t\tbool operator==(const s32 value_) const;\n\t\tbool operator==(const u32 value_) const;\n\t\tbool operator==(const f64 value_) const;\n\t\tbool operator==(const str &value_) const;\n\t\tbool operator==(const DataMap &value_) const;\n\t\tbool operator==(const DataValue &other) const;\n\t\tDataValue &operator=(DataValue &&other);\n\n\t\tconst s8 gets8() const;\n\t\tconst u8 getu8() const;\n\t\tconst s16 gets16() const;\n\t\tconst u16 getu16() const;\n\t\tconst s32 gets32() const;\n\t\tconst u32 getu32() const;\n\t\tconst f64 getf64() const;\n\t\tconst str getString() const;\n\t\tconst DataMap *getMap() const;\n\t\tDataMap *getMap();\n\n\t\tfriend std::ostream &operator<<(std::ostream &output, const DataValue &this_);\n\t\t\n\t\ttemplate <typename T> inline const T get() const;\n\t\ttemplate <> inline const s8 get() const { return gets8(); }\n\t\ttemplate <> inline const u8 get() const { return getu8(); }\n\t\ttemplate <> inline const s16 get() const { return gets16(); }\n\t\ttemplate <> inline const u16 get() const { return getu16(); }\n\t\ttemplate <> inline const s32 get() const { return gets32(); }\n\t\ttemplate <> inline const u32 get() const { return getu32(); }\n\t\ttemplate <> inline const f64 get() const { return getf64(); }\n\n\t\tinline const bool iss8() const { return m_dtype == DataType::T_s8; }\n\t\tinline const bool isu8() const { return m_dtype == DataType::T_s8; }\n\t\tinline const bool iss16() const { return m_dtype == DataType::T_s16; }\n\t\tinline const bool isu16() const { return m_dtype == DataType::T_u16; }\n\t\tinline const bool iss32() const { return m_dtype == DataType::T_s32; }\n\t\tinline const bool isu32() const { return m_dtype == DataType::T_u32; }\n\t\tinline const bool isf64() const { return m_dtype == DataType::T_f64; }\n\t\tinline const bool isstring() const { return m_dtype == DataType::T_string; }\n\t\tinline const bool ismap() const { return m_dtype == DataType::T_Tree; }\n\n\t\ttemplate <typename T>\n\t\tconst bool is() const;\n\n\t\ttemplate <> inline const bool is<s8>() const { return iss8(); }\n\t\ttemplate <> inline const bool is<u8>() const { return isu8(); }\n\t\ttemplate <> inline const bool is<s16>() const { return iss16(); }\n\t\ttemplate <> inline const bool is<u16>() const { return isu16(); }\n\t\ttemplate <> inline const bool is<s32>() const { return iss32(); }\n\t\ttemplate <> inline const bool is<u32>() const { return isu32(); }\n\t\ttemplate <> inline const bool is<f64>() const { return isf64(); }\n\n\t\tstatic DataMap fromStringVector(const std::vector<str> &data, u32 &count);\n\n\tprivate:\n\t\tunion\n\t\t{\n\t\t\ts8 s8_;\n\t\t\tu8 u8_;\n\t\t\ts16 s16_;\n\t\t\tu16 u16_;\n\t\t\ts32 s32_;\n\t\t\tu32 u32_;\n\t\t\tf64 f64_;\n\t\t\tvoid *ptr_;\n\t\t};\n\t\tDataType m_dtype{ DataType::T_Empty };\n\t};\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Pelagicore AB\n * All rights reserved.\n *\/\n#include <iostream>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <signal.h>\n#include \"dbusgateway.h\"\n#include \"debug.h\"\n\nDBusGateway::DBusGateway(ControllerAbstractInterface *controllerInterface,\n SystemcallAbstractInterface *systemcallInterface,\n ProxyType type,\n const std::string &gatewayDir,\n const std::string &name):\n Gateway(controllerInterface),\n m_systemcallInterface(systemcallInterface),\n m_type(type),\n m_pid(-1),\n m_infp(-1),\n m_outfp(-1),\n m_hasBeenConfigured(false)\n{\n if (m_type == SessionProxy) {\n m_socket = gatewayDir\n + std::string(\"\/sess_\")\n + name\n + std::string(\".sock\");\n } else {\n m_socket = gatewayDir\n + std::string(\"\/sys_\")\n + name\n + std::string(\".sock\");\n }\n}\n\nDBusGateway::~DBusGateway()\n{\n}\n\nstd::string DBusGateway::id()\n{\n return \"dbus-proxy\";\n}\n\nbool DBusGateway::setConfig(const std::string &config)\n{\n m_config = config;\n\n if(m_config.length() > 1) {\n m_hasBeenConfigured = true;\n return true;\n }\n\n return false;\n}\n\nbool DBusGateway::activate()\n{\n if(!m_hasBeenConfigured) {\n log_error (\"'Activate' called on non-configured gateway %s\",\n id().c_str());\n return false;\n }\n\n \/\/ set DBUS ENV\n std::string variable = \"DBUS_\";\n if (m_type == SessionProxy) {\n variable += \"SESSION\";\n } else {\n variable += \"SYSTEM\";\n }\n variable += \"_BUS_ADDRESS\";\n\n std::string value = \"unix:path=\/gateways\/\";\n value += socketName();\n m_controllerInterface->setEnvironmentVariable(variable, value);\n\n \/\/ Open pipe\n std::string command = \"dbus-proxy \";\n command += m_socket + \" \" + typeString();\n m_pid = m_systemcallInterface->makePopenCall(command,\n &m_infp,\n &m_outfp);\n if(m_pid == -1) {\n log_error (\"Failed to launch %s\", command.c_str());\n return false;\n }\n\n size_t count = sizeof(char) * m_config.length();\n\n ssize_t written = write(m_infp,\n m_config.c_str(),\n count);\n\n \/\/ writing didn't work at all\n if(written == -1) {\n log_error (\"Failed to write to STDIN of dbus-proxy!\");\n return false;\n }\n\n \/\/ writing has written exact amout of bytes\n if(written == (ssize_t)count) {\n return true;\n }\n\n \/\/ something went wrong during the write\n log_error (\"Failed to write to STDIN of dbus-proxy!\");\n\n return false;\n}\n\nbool DBusGateway::teardown() {\n\n bool success = true;\n\n if(m_pid != -1) {\n if(!m_systemcallInterface->makePcloseCall(m_pid, m_infp, m_outfp)) {\n log_error(\"makePcloseCall() returned error\\n\");\n success = false;\n }\n }\n\n if(unlink(m_socket.c_str()) == -1) {\n log_error(\"Could not remove %s\\n\", m_socket.c_str());\n success = false;\n }\n\n return success;\n}\n\nconst char *DBusGateway::typeString()\n{\n if (m_type == SessionProxy) {\n return \"session\";\n } else {\n return \"system\";\n }\n}\n\nconst char *DBusGateway::socketName()\n{\n \/\/ Return the filename after stripping directory info\n std::string socket(m_socket.c_str());\n return socket.substr(socket.rfind('\/') + 1).c_str();\n}\n\nstd::string DBusGateway::environment()\n{\n return \"\";\n}\n<commit_msg>Output error when not being able to close connection to dbus-proxy<commit_after>\/*\n * Copyright (C) 2014 Pelagicore AB\n * All rights reserved.\n *\/\n#include <iostream>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <signal.h>\n#include \"dbusgateway.h\"\n#include \"debug.h\"\n\nDBusGateway::DBusGateway(ControllerAbstractInterface *controllerInterface,\n SystemcallAbstractInterface *systemcallInterface,\n ProxyType type,\n const std::string &gatewayDir,\n const std::string &name):\n Gateway(controllerInterface),\n m_systemcallInterface(systemcallInterface),\n m_type(type),\n m_pid(-1),\n m_infp(-1),\n m_outfp(-1),\n m_hasBeenConfigured(false)\n{\n if (m_type == SessionProxy) {\n m_socket = gatewayDir\n + std::string(\"\/sess_\")\n + name\n + std::string(\".sock\");\n } else {\n m_socket = gatewayDir\n + std::string(\"\/sys_\")\n + name\n + std::string(\".sock\");\n }\n}\n\nDBusGateway::~DBusGateway()\n{\n}\n\nstd::string DBusGateway::id()\n{\n return \"dbus-proxy\";\n}\n\nbool DBusGateway::setConfig(const std::string &config)\n{\n m_config = config;\n\n if(m_config.length() > 1) {\n m_hasBeenConfigured = true;\n return true;\n }\n\n return false;\n}\n\nbool DBusGateway::activate()\n{\n if(!m_hasBeenConfigured) {\n log_error (\"'Activate' called on non-configured gateway %s\",\n id().c_str());\n return false;\n }\n\n \/\/ set DBUS ENV\n std::string variable = \"DBUS_\";\n if (m_type == SessionProxy) {\n variable += \"SESSION\";\n } else {\n variable += \"SYSTEM\";\n }\n variable += \"_BUS_ADDRESS\";\n\n std::string value = \"unix:path=\/gateways\/\";\n value += socketName();\n m_controllerInterface->setEnvironmentVariable(variable, value);\n\n \/\/ Open pipe\n std::string command = \"dbus-proxy \";\n command += m_socket + \" \" + typeString();\n m_pid = m_systemcallInterface->makePopenCall(command,\n &m_infp,\n &m_outfp);\n if(m_pid == -1) {\n log_error (\"Failed to launch %s\", command.c_str());\n return false;\n }\n\n size_t count = sizeof(char) * m_config.length();\n\n ssize_t written = write(m_infp,\n m_config.c_str(),\n count);\n\n \/\/ writing didn't work at all\n if(written == -1) {\n log_error (\"Failed to write to STDIN of dbus-proxy!\");\n return false;\n }\n\n \/\/ writing has written exact amout of bytes\n if(written == (ssize_t)count) {\n return true;\n }\n\n \/\/ something went wrong during the write\n log_error (\"Failed to write to STDIN of dbus-proxy!\");\n\n return false;\n}\n\nbool DBusGateway::teardown() {\n\n bool success = true;\n\n if(m_pid != -1) {\n if(!m_systemcallInterface->makePcloseCall(m_pid, m_infp, m_outfp)) {\n log_error(\"makePcloseCall() returned error\\n\");\n success = false;\n }\n } else {\n log_error(\"Failed to close connection to dbus-proxy!\");\n success = false;\n }\n\n if(unlink(m_socket.c_str()) == -1) {\n log_error(\"Could not remove %s\\n\", m_socket.c_str());\n success = false;\n }\n\n return success;\n}\n\nconst char *DBusGateway::typeString()\n{\n if (m_type == SessionProxy) {\n return \"session\";\n } else {\n return \"system\";\n }\n}\n\nconst char *DBusGateway::socketName()\n{\n \/\/ Return the filename after stripping directory info\n std::string socket(m_socket.c_str());\n return socket.substr(socket.rfind('\/') + 1).c_str();\n}\n\nstd::string DBusGateway::environment()\n{\n return \"\";\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Runtime\/World\/CPathFindRegion.hpp\"\n\n#include \"Runtime\/World\/CPathFindArea.hpp\"\n\nnamespace urde {\n\nCPFNode::CPFNode(CMemoryInStream& in) {\n x0_position.readBig(in);\n xc_normal.readBig(in);\n}\n\nCPFLink::CPFLink(CMemoryInStream& in) {\n x0_node = in.readUint32Big();\n x4_region = in.readUint32Big();\n x8_2dWidth = in.readFloatBig();\n xc_oo2dWidth = in.readFloatBig();\n}\n\nCPFRegion::CPFRegion(CMemoryInStream& in) {\n x0_numNodes = in.readUint32Big();\n x4_startNode = reinterpret_cast<CPFNode*>(in.readUint32Big());\n x8_numLinks = in.readUint32Big();\n xc_startLink = reinterpret_cast<CPFLink*>(in.readUint32Big());\n x10_flags = in.readUint32Big();\n x14_height = in.readFloatBig();\n x18_normal.readBig(in);\n x24_regionIdx = in.readUint32Big();\n x28_centroid.readBig(in);\n x34_aabb.readBoundingBoxBig(in);\n x4c_regionData = reinterpret_cast<CPFRegionData*>(in.readUint32Big());\n}\n\nconst CPFLink* CPFRegion::GetPathLink() const { return &xc_startLink[x4c_regionData->GetPathLink()]; }\n\nvoid CPFRegion::Fixup(CPFArea& area, u32& maxRegionNodes) {\n if (x0_numNodes)\n x4_startNode = &area.x140_nodes[reinterpret_cast<uintptr_t>(x4_startNode)];\n else\n x4_startNode = nullptr;\n if (x8_numLinks)\n xc_startLink = &area.x148_links[reinterpret_cast<uintptr_t>(xc_startLink)];\n else\n xc_startLink = nullptr;\n x4c_regionData = &area.x178_regionDatas[x24_regionIdx];\n if (x0_numNodes > maxRegionNodes)\n maxRegionNodes = x0_numNodes;\n}\n\nbool CPFRegion::IsPointInside(const zeus::CVector3f& point) const {\n if (!x34_aabb.pointInside(point))\n return false;\n u32 i;\n for (i = 0; i < x0_numNodes; ++i) {\n CPFNode& node = x4_startNode[i];\n if ((point - node.GetPos()).dot(node.GetNormal()) < 0.f)\n break;\n }\n if (i != x0_numNodes)\n return false;\n zeus::CVector3f nodeToPoint = point - x4_startNode->GetPos();\n return nodeToPoint.dot(x18_normal) >= 0.f &&\n (nodeToPoint - x14_height * zeus::skUp).dot(x18_normal) <= 0.f;\n}\n\nfloat CPFRegion::PointHeight(const zeus::CVector3f& point) const {\n return (point - x4_startNode->GetPos()).dot(x18_normal);\n}\n\nbool CPFRegion::FindClosestPointOnPolygon(const std::vector<zeus::CVector3f>& polyPoints, const zeus::CVector3f& normal,\n const zeus::CVector3f& point, bool excludePolyPoints) const {\n bool found = false;\n size_t i;\n for (i = 0; i < polyPoints.size(); ++i) {\n const zeus::CVector3f& p0 = polyPoints[i];\n const zeus::CVector3f& p1 = polyPoints[(i + 1) % polyPoints.size()];\n if ((p1 - p0).cross(normal).dot(point - p0) < 0.f)\n break;\n }\n\n if (i == polyPoints.size()) {\n float distToPoly = (polyPoints.front() - point).dot(normal);\n float distToPolySq = distToPoly * distToPoly;\n if (distToPolySq < x4c_regionData->GetBestPointDistanceSquared()) {\n found = true;\n x4c_regionData->SetBestPointDistanceSquared(distToPolySq);\n x4c_regionData->SetBestPoint(normal * distToPoly + point);\n }\n } else {\n bool projected = false;\n for (i = 0; i < polyPoints.size(); ++i) {\n const zeus::CVector3f& p0 = polyPoints[i];\n const zeus::CVector3f& p1 = polyPoints[(i + 1) % polyPoints.size()];\n zeus::CVector3f p0ToP1 = p1 - p0;\n zeus::CVector3f p1ToPoint = point - p1;\n zeus::CVector3f sum = p1ToPoint + p0ToP1;\n if (p0ToP1.cross(normal).dot(p1ToPoint) < 0.f && p0ToP1.dot(p1ToPoint) <= 0.f && sum.dot(p0ToP1) >= 0.f) {\n projected = true;\n p0ToP1.normalize();\n sum -= p0ToP1.dot(sum) * p0ToP1;\n float distSq = sum.magSquared();\n if (distSq < x4c_regionData->GetBestPointDistanceSquared()) {\n found = true;\n x4c_regionData->SetBestPointDistanceSquared(distSq);\n x4c_regionData->SetBestPoint(point - sum);\n }\n break;\n }\n }\n\n if (!projected && !excludePolyPoints) {\n for (i = 0; i < polyPoints.size(); ++i) {\n const zeus::CVector3f& p0 = polyPoints[i];\n float distSq = (point - p0).magSquared();\n if (distSq < x4c_regionData->GetBestPointDistanceSquared()) {\n found = true;\n x4c_regionData->SetBestPointDistanceSquared(distSq);\n x4c_regionData->SetBestPoint(p0);\n }\n }\n }\n }\n return found;\n}\n\nbool CPFRegion::FindBestPoint(std::vector<zeus::CVector3f>& polyPoints, const zeus::CVector3f& point, u32 flags,\n float paddingSq) const {\n bool found = false;\n bool isFlyer = (flags & 0x2) != 0;\n x4c_regionData->SetBestPointDistanceSquared(paddingSq);\n if (!isFlyer) {\n for (u32 i = 0; i < x0_numNodes; ++i) {\n CPFNode& node = x4_startNode[i];\n CPFNode& nextNode = x4_startNode[(i + 1) % x0_numNodes];\n polyPoints.clear();\n polyPoints.push_back(node.GetPos());\n polyPoints.push_back(node.GetPos());\n polyPoints.back().z() += x14_height;\n polyPoints.push_back(nextNode.GetPos());\n polyPoints.back().z() += x14_height;\n polyPoints.push_back(nextNode.GetPos());\n found |= FindClosestPointOnPolygon(polyPoints, node.GetNormal(), point, true);\n }\n }\n\n polyPoints.clear();\n for (u32 i = 0; i < x0_numNodes; ++i) {\n CPFNode& node = x4_startNode[i];\n polyPoints.push_back(node.GetPos());\n }\n found |= FindClosestPointOnPolygon(polyPoints, x18_normal, point, false);\n\n if (!isFlyer) {\n polyPoints.clear();\n for (int i = int(x0_numNodes) - 1; i >= 0; --i) {\n CPFNode& node = x4_startNode[i];\n polyPoints.push_back(node.GetPos());\n polyPoints.back().z() += x14_height;\n }\n found |= FindClosestPointOnPolygon(polyPoints, -x18_normal, point, false);\n }\n\n return found;\n}\n\nvoid CPFRegion::SetLinkTo(u32 idx) {\n if (x8_numLinks <= 0) {\n return;\n }\n\n for (u32 i = 0; i < x8_numLinks; ++i) {\n if (xc_startLink[i].GetRegion() == idx) {\n Data()->SetPathLink(i);\n return;\n }\n }\n}\n\nvoid CPFRegion::DropToGround(zeus::CVector3f& point) const {\n point.z() -= (point - x4_startNode->GetPos()).dot(x18_normal) \/ x18_normal.z();\n}\n\nzeus::CVector3f CPFRegion::GetLinkMidPoint(const CPFLink& link) const {\n const CPFNode& node = x4_startNode[link.GetNode()];\n const CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes];\n return (node.GetPos() + nextNode.GetPos()) * 0.5f;\n}\n\nzeus::CVector3f CPFRegion::FitThroughLink2d(const zeus::CVector3f& p1, const CPFLink& link, const zeus::CVector3f& p2,\n float chRadius) const {\n CPFNode& node = x4_startNode[link.GetNode()];\n CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes];\n zeus::CVector3f nodeDelta = nextNode.GetPos() - node.GetPos();\n float t = 0.5f;\n if (chRadius < 0.5f * link.Get2dWidth()) {\n zeus::CVector2f delta2d = nodeDelta.toVec2f();\n delta2d *= link.GetOO2dWidth();\n zeus::CVector3f nodeToP1 = p1 - node.GetPos();\n float f27 = nodeToP1.dot(node.GetNormal());\n float f31 = delta2d.dot(nodeToP1.toVec2f());\n zeus::CVector3f nodeToP2 = p2 - node.GetPos();\n float f26 = -nodeToP2.dot(node.GetNormal());\n float f1b = delta2d.dot(nodeToP2.toVec2f());\n float f3 = f27 + f26;\n if (f3 > FLT_EPSILON)\n t = zeus::clamp(chRadius, 1.f \/ f3 * (f26 * f31 + f27 * f1b), link.Get2dWidth() - chRadius) * link.GetOO2dWidth();\n }\n return nodeDelta * t + node.GetPos();\n}\n\nzeus::CVector3f CPFRegion::FitThroughLink3d(const zeus::CVector3f& p1, const CPFLink& link, float regionHeight,\n const zeus::CVector3f& p2, float chRadius, float chHalfHeight) const {\n CPFNode& node = x4_startNode[link.GetNode()];\n CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes];\n zeus::CVector3f nodeDelta = nextNode.GetPos() - node.GetPos();\n float f25 = (p1 - node.GetPos()).dot(node.GetNormal());\n float f24 = (node.GetPos() - p2).dot(node.GetNormal());\n float f23 = f25 + f24;\n#if 0\n if (chRadius < 0.5f * link.Get2dWidth()) {\n zeus::CVector2f delta2d(nodeDelta.x, nodeDelta.y);\n delta2d *= link.GetOO2dWidth();\n zeus::CVector3f nodeToP1 = p1 - node.GetPos();\n float f29 = delta2d.dot(zeus::CVector2f(nodeToP1.y, nodeToP1.y));\n zeus::CVector3f nodeToP2 = p2 - node.GetPos();\n float f1b = delta2d.dot(zeus::CVector2f(nodeToP2.y, nodeToP2.y));\n if (f23 > FLT_EPSILON) {\n zeus::clamp(chRadius, 1.f \/ f23 * f24 * f29 + f25 * f1b, link.Get2dWidth() - chRadius) *\n link.GetOO2dWidth();\n }\n }\n#endif\n zeus::CVector3f midPoint = nodeDelta * 0.5f + node.GetPos();\n float z;\n if (chHalfHeight < 0.5f * regionHeight) {\n float minZ = chHalfHeight + midPoint.z();\n z = 0.5f * (p1.z() + p2.z());\n if (f23 > FLT_EPSILON)\n z = (f24 * p1.z() + f25 * p2.z()) \/ f23;\n z = zeus::clamp(minZ, z, regionHeight + midPoint.z() - chHalfHeight);\n } else {\n z = (p1.z() + p2.z()) * 0.5f;\n }\n return {midPoint.x(), midPoint.y(), z};\n}\n\nbool CPFRegion::IsPointInsidePaddedAABox(const zeus::CVector3f& point, float padding) const {\n return point.x() >= x34_aabb.min.x() - padding && point.x() <= x34_aabb.max.x() + padding &&\n point.y() >= x34_aabb.min.y() - padding && point.y() <= x34_aabb.max.y() + padding &&\n point.z() >= x34_aabb.min.z() - padding && point.z() <= x34_aabb.max.z() + padding;\n}\n\n} \/\/ namespace urde\n<commit_msg>CPathFindRegion: Brace statements where applicable<commit_after>#include \"Runtime\/World\/CPathFindRegion.hpp\"\n\n#include \"Runtime\/World\/CPathFindArea.hpp\"\n\nnamespace urde {\n\nCPFNode::CPFNode(CMemoryInStream& in) {\n x0_position.readBig(in);\n xc_normal.readBig(in);\n}\n\nCPFLink::CPFLink(CMemoryInStream& in) {\n x0_node = in.readUint32Big();\n x4_region = in.readUint32Big();\n x8_2dWidth = in.readFloatBig();\n xc_oo2dWidth = in.readFloatBig();\n}\n\nCPFRegion::CPFRegion(CMemoryInStream& in) {\n x0_numNodes = in.readUint32Big();\n x4_startNode = reinterpret_cast<CPFNode*>(in.readUint32Big());\n x8_numLinks = in.readUint32Big();\n xc_startLink = reinterpret_cast<CPFLink*>(in.readUint32Big());\n x10_flags = in.readUint32Big();\n x14_height = in.readFloatBig();\n x18_normal.readBig(in);\n x24_regionIdx = in.readUint32Big();\n x28_centroid.readBig(in);\n x34_aabb.readBoundingBoxBig(in);\n x4c_regionData = reinterpret_cast<CPFRegionData*>(in.readUint32Big());\n}\n\nconst CPFLink* CPFRegion::GetPathLink() const { return &xc_startLink[x4c_regionData->GetPathLink()]; }\n\nvoid CPFRegion::Fixup(CPFArea& area, u32& maxRegionNodes) {\n if (x0_numNodes != 0) {\n x4_startNode = &area.x140_nodes[reinterpret_cast<uintptr_t>(x4_startNode)];\n } else {\n x4_startNode = nullptr;\n }\n\n if (x8_numLinks != 0) {\n xc_startLink = &area.x148_links[reinterpret_cast<uintptr_t>(xc_startLink)];\n } else {\n xc_startLink = nullptr;\n }\n\n x4c_regionData = &area.x178_regionDatas[x24_regionIdx];\n if (x0_numNodes > maxRegionNodes) {\n maxRegionNodes = x0_numNodes;\n }\n}\n\nbool CPFRegion::IsPointInside(const zeus::CVector3f& point) const {\n if (!x34_aabb.pointInside(point)) {\n return false;\n }\n\n u32 i;\n for (i = 0; i < x0_numNodes; ++i) {\n const CPFNode& node = x4_startNode[i];\n if ((point - node.GetPos()).dot(node.GetNormal()) < 0.f) {\n break;\n }\n }\n\n if (i != x0_numNodes) {\n return false;\n }\n\n const zeus::CVector3f nodeToPoint = point - x4_startNode->GetPos();\n return nodeToPoint.dot(x18_normal) >= 0.f && (nodeToPoint - x14_height * zeus::skUp).dot(x18_normal) <= 0.f;\n}\n\nfloat CPFRegion::PointHeight(const zeus::CVector3f& point) const {\n return (point - x4_startNode->GetPos()).dot(x18_normal);\n}\n\nbool CPFRegion::FindClosestPointOnPolygon(const std::vector<zeus::CVector3f>& polyPoints, const zeus::CVector3f& normal,\n const zeus::CVector3f& point, bool excludePolyPoints) const {\n bool found = false;\n size_t i;\n for (i = 0; i < polyPoints.size(); ++i) {\n const zeus::CVector3f& p0 = polyPoints[i];\n const zeus::CVector3f& p1 = polyPoints[(i + 1) % polyPoints.size()];\n if ((p1 - p0).cross(normal).dot(point - p0) < 0.f) {\n break;\n }\n }\n\n if (i == polyPoints.size()) {\n const float distToPoly = (polyPoints.front() - point).dot(normal);\n const float distToPolySq = distToPoly * distToPoly;\n if (distToPolySq < x4c_regionData->GetBestPointDistanceSquared()) {\n found = true;\n x4c_regionData->SetBestPointDistanceSquared(distToPolySq);\n x4c_regionData->SetBestPoint(normal * distToPoly + point);\n }\n } else {\n bool projected = false;\n for (i = 0; i < polyPoints.size(); ++i) {\n const zeus::CVector3f& p0 = polyPoints[i];\n const zeus::CVector3f& p1 = polyPoints[(i + 1) % polyPoints.size()];\n zeus::CVector3f p0ToP1 = p1 - p0;\n zeus::CVector3f p1ToPoint = point - p1;\n zeus::CVector3f sum = p1ToPoint + p0ToP1;\n\n if (p0ToP1.cross(normal).dot(p1ToPoint) < 0.f && p0ToP1.dot(p1ToPoint) <= 0.f && sum.dot(p0ToP1) >= 0.f) {\n projected = true;\n p0ToP1.normalize();\n sum -= p0ToP1.dot(sum) * p0ToP1;\n const float distSq = sum.magSquared();\n if (distSq < x4c_regionData->GetBestPointDistanceSquared()) {\n found = true;\n x4c_regionData->SetBestPointDistanceSquared(distSq);\n x4c_regionData->SetBestPoint(point - sum);\n }\n break;\n }\n }\n\n if (!projected && !excludePolyPoints) {\n for (i = 0; i < polyPoints.size(); ++i) {\n const zeus::CVector3f& p0 = polyPoints[i];\n const float distSq = (point - p0).magSquared();\n if (distSq < x4c_regionData->GetBestPointDistanceSquared()) {\n found = true;\n x4c_regionData->SetBestPointDistanceSquared(distSq);\n x4c_regionData->SetBestPoint(p0);\n }\n }\n }\n }\n return found;\n}\n\nbool CPFRegion::FindBestPoint(std::vector<zeus::CVector3f>& polyPoints, const zeus::CVector3f& point, u32 flags,\n float paddingSq) const {\n bool found = false;\n const bool isFlyer = (flags & 0x2) != 0;\n\n x4c_regionData->SetBestPointDistanceSquared(paddingSq);\n\n if (!isFlyer) {\n for (u32 i = 0; i < x0_numNodes; ++i) {\n const CPFNode& node = x4_startNode[i];\n const CPFNode& nextNode = x4_startNode[(i + 1) % x0_numNodes];\n polyPoints.clear();\n polyPoints.push_back(node.GetPos());\n polyPoints.push_back(node.GetPos());\n polyPoints.back().z() += x14_height;\n polyPoints.push_back(nextNode.GetPos());\n polyPoints.back().z() += x14_height;\n polyPoints.push_back(nextNode.GetPos());\n found |= FindClosestPointOnPolygon(polyPoints, node.GetNormal(), point, true);\n }\n }\n\n polyPoints.clear();\n for (u32 i = 0; i < x0_numNodes; ++i) {\n const CPFNode& node = x4_startNode[i];\n polyPoints.push_back(node.GetPos());\n }\n found |= FindClosestPointOnPolygon(polyPoints, x18_normal, point, false);\n\n if (!isFlyer) {\n polyPoints.clear();\n for (int i = int(x0_numNodes) - 1; i >= 0; --i) {\n const CPFNode& node = x4_startNode[i];\n polyPoints.push_back(node.GetPos());\n polyPoints.back().z() += x14_height;\n }\n found |= FindClosestPointOnPolygon(polyPoints, -x18_normal, point, false);\n }\n\n return found;\n}\n\nvoid CPFRegion::SetLinkTo(u32 idx) {\n if (x8_numLinks <= 0) {\n return;\n }\n\n for (u32 i = 0; i < x8_numLinks; ++i) {\n if (xc_startLink[i].GetRegion() == idx) {\n Data()->SetPathLink(i);\n return;\n }\n }\n}\n\nvoid CPFRegion::DropToGround(zeus::CVector3f& point) const {\n point.z() -= (point - x4_startNode->GetPos()).dot(x18_normal) \/ x18_normal.z();\n}\n\nzeus::CVector3f CPFRegion::GetLinkMidPoint(const CPFLink& link) const {\n const CPFNode& node = x4_startNode[link.GetNode()];\n const CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes];\n return (node.GetPos() + nextNode.GetPos()) * 0.5f;\n}\n\nzeus::CVector3f CPFRegion::FitThroughLink2d(const zeus::CVector3f& p1, const CPFLink& link, const zeus::CVector3f& p2,\n float chRadius) const {\n const CPFNode& node = x4_startNode[link.GetNode()];\n const CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes];\n const zeus::CVector3f nodeDelta = nextNode.GetPos() - node.GetPos();\n float t = 0.5f;\n\n if (chRadius < 0.5f * link.Get2dWidth()) {\n zeus::CVector2f delta2d = nodeDelta.toVec2f();\n delta2d *= link.GetOO2dWidth();\n const zeus::CVector3f nodeToP1 = p1 - node.GetPos();\n const float f27 = nodeToP1.dot(node.GetNormal());\n const float f31 = delta2d.dot(nodeToP1.toVec2f());\n const zeus::CVector3f nodeToP2 = p2 - node.GetPos();\n const float f26 = -nodeToP2.dot(node.GetNormal());\n const float f1b = delta2d.dot(nodeToP2.toVec2f());\n const float f3 = f27 + f26;\n if (f3 > FLT_EPSILON) {\n t = zeus::clamp(chRadius, 1.f \/ f3 * (f26 * f31 + f27 * f1b), link.Get2dWidth() - chRadius) * link.GetOO2dWidth();\n }\n }\n return nodeDelta * t + node.GetPos();\n}\n\nzeus::CVector3f CPFRegion::FitThroughLink3d(const zeus::CVector3f& p1, const CPFLink& link, float regionHeight,\n const zeus::CVector3f& p2, float chRadius, float chHalfHeight) const {\n const CPFNode& node = x4_startNode[link.GetNode()];\n const CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes];\n const zeus::CVector3f nodeDelta = nextNode.GetPos() - node.GetPos();\n const float f25 = (p1 - node.GetPos()).dot(node.GetNormal());\n const float f24 = (node.GetPos() - p2).dot(node.GetNormal());\n const float f23 = f25 + f24;\n\n#if 0\n if (chRadius < 0.5f * link.Get2dWidth()) {\n zeus::CVector2f delta2d(nodeDelta.x, nodeDelta.y);\n delta2d *= link.GetOO2dWidth();\n const zeus::CVector3f nodeToP1 = p1 - node.GetPos();\n const float f29 = delta2d.dot(zeus::CVector2f(nodeToP1.y, nodeToP1.y));\n const zeus::CVector3f nodeToP2 = p2 - node.GetPos();\n const float f1b = delta2d.dot(zeus::CVector2f(nodeToP2.y, nodeToP2.y));\n if (f23 > FLT_EPSILON) {\n zeus::clamp(chRadius, 1.f \/ f23 * f24 * f29 + f25 * f1b, link.Get2dWidth() - chRadius) * link.GetOO2dWidth();\n }\n }\n#endif\n\n const zeus::CVector3f midPoint = nodeDelta * 0.5f + node.GetPos();\n float z;\n if (chHalfHeight < 0.5f * regionHeight) {\n const float minZ = chHalfHeight + midPoint.z();\n z = 0.5f * (p1.z() + p2.z());\n if (f23 > FLT_EPSILON) {\n z = (f24 * p1.z() + f25 * p2.z()) \/ f23;\n }\n z = zeus::clamp(minZ, z, regionHeight + midPoint.z() - chHalfHeight);\n } else {\n z = (p1.z() + p2.z()) * 0.5f;\n }\n return {midPoint.x(), midPoint.y(), z};\n}\n\nbool CPFRegion::IsPointInsidePaddedAABox(const zeus::CVector3f& point, float padding) const {\n return point.x() >= x34_aabb.min.x() - padding && point.x() <= x34_aabb.max.x() + padding &&\n point.y() >= x34_aabb.min.y() - padding && point.y() <= x34_aabb.max.y() + padding &&\n point.z() >= x34_aabb.min.z() - padding && point.z() <= x34_aabb.max.z() + padding;\n}\n\n} \/\/ namespace urde\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <getopt.h>\n#include <math.h>\n\n#include \"Scorer.h\"\n#include \"Timer.h\"\n#include \"Util.h\"\n\n#include \"ScorerFactory.h\"\n\nusing namespace std;\n\nScorer* scorer;\nint bootstrap = 0;\nvoid evaluate(const string& candFile);\nvoid addStats(vector<int>& stats1, const vector<int>& stats2);\nfloat average(const vector<float>& list);\nfloat stdDeviation(const vector<float>& list, float avg);\nstring int2string(int n);\n\nbool moreFiles = false;\nbool moreScorers = false;\n\nvoid usage()\n{\n cerr<<\"usage: evaluator [options] --reference ref1[,ref2[,ref3...]] --candidate cand1[,cand2[,cand3...]] \"<<endl;\n cerr<<\"[--sctype|-s] the scorer type (default BLEU)\"<<endl;\n cerr<<\"[--scconfig|-c] configuration string passed to scorer\"<<endl;\n cerr<<\"\\tThis is of the form NAME1:VAL1,NAME2:VAL2 etc \"<<endl;\n cerr<<\"[--reference|-R] comma separated list of reference files\"<<endl;\n cerr<<\"[--candidate|-C] comma separated list of candidate files\"<<endl;\n cerr<<\"[--bootstrap|-b] number of booststraped samples (default 0 - no bootstraping)\"<<endl;\n cerr<<\"[--rseed|-r] the random seed for bootstraping (defaults to system clock)\"<<endl;\n cerr<<\"[--help|-h] print this message and exit\"<<endl;\n cerr<<endl;\n cerr<<\"Evaluator is able to compute more metrics at once. To do this,\"<<endl;\n cerr<<\"separate scorers with semicolon (note that comma is used to separate\"<<endl;\n cerr<<\"scorers in the interpolated scorer).\"<<endl;\n cerr<<endl;\n cerr<<\"If you specify only one metric and one candidate file, only the final score\"<<endl;\n cerr<<\"will be printed to stdout. Otherwise each line will contain metric name\"<<endl;\n cerr<<\"and\/or filename and the final score. Since most of the metrics prints some\"<<endl;\n cerr<<\"debuging info, consider redirecting stderr to \/dev\/null.\"<<endl;\n exit(1);\n}\n\nstatic struct option long_options[] = {\n {\"sctype\",required_argument,0,'s'},\n {\"scconfig\",required_argument,0,'c'},\n {\"reference\",required_argument,0,'R'},\n {\"candidate\",required_argument,0,'C'},\n {\"bootstrap\",required_argument,0,'b'},\n {\"rseed\",required_argument,0,'r'},\n {\"help\",no_argument,0,'h'},\n {0, 0, 0, 0}\n};\nint option_index;\n\nint main(int argc, char** argv)\n{\n ResetUserTime();\n\n \/\/defaults\n string scorerType(\"BLEU\");\n string scorerConfig(\"\");\n string reference(\"\");\n string candidate(\"\");\n\n int seed = 0;\n bool hasSeed = false;\n\n int c;\n while ((c=getopt_long (argc,argv, \"s:c:R:C:b:r:h\", long_options, &option_index)) != -1) {\n switch(c) {\n case 's':\n scorerType = string(optarg);\n break;\n case 'c':\n scorerConfig = string(optarg);\n break;\n case 'R':\n reference = string(optarg);\n break;\n case 'C':\n candidate = string(optarg);\n break;\n case 'b':\n bootstrap = atoi(optarg);\n break;\n case 'r':\n seed = strtol(optarg, NULL, 10);\n hasSeed = true;\n break;\n default:\n usage();\n }\n }\n\n if (bootstrap)\n {\n if (hasSeed) {\n cerr << \"Seeding random numbers with \" << seed << endl;\n srandom(seed);\n } else {\n cerr << \"Seeding random numbers with system clock \" << endl;\n srandom(time(NULL));\n }\n }\n\n try {\n vector<string> refFiles;\n vector<string> candFiles;\n vector<string> scorerTypes;\n\n \n\n if (reference.length() == 0) throw runtime_error(\"You have to specify at least one reference file.\");\n split(reference,',',refFiles);\n\n if (candidate.length() == 0) throw runtime_error(\"You have to specify at least one candidate file.\");\n split(candidate,',',candFiles);\n\n if (scorerType.length() == 0) throw runtime_error(\"You have to specify at least one scorer.\");\n split(scorerType,';',scorerTypes);\n \n if (candFiles.size() > 1) moreFiles = true;\n if (scorerTypes.size() > 1) moreScorers = true;\n \n for (vector<string>::const_iterator fileIt = candFiles.begin(); fileIt != candFiles.end(); ++fileIt)\n {\n for (vector<string>::const_iterator scorerIt = scorerTypes.begin(); scorerIt != scorerTypes.end(); ++scorerIt)\n {\n scorer = ScorerFactory::getScorer(*scorerIt,scorerConfig);\n scorer->setReferenceFiles(refFiles);\n evaluate(*fileIt);\n delete scorer;\n }\n }\n\n return EXIT_SUCCESS;\n } catch (const exception& e) {\n cerr << \"Exception: \" << e.what() << endl;\n return EXIT_FAILURE;\n }\n\n}\n\nvoid evaluate(const string& candFile)\n{\n ifstream cand(candFile.c_str());\n if (!cand.good()) throw runtime_error(\"Error opening candidate file\");\n\n vector<ScoreStats> entries;\n\n \/\/ Loading sentences and preparing statistics\n ScoreStats scoreentry;\n string line;\n while (getline(cand, line))\n {\n scorer->prepareStats(entries.size(), line, scoreentry);\n entries.push_back(scoreentry);\n }\n\n int n = entries.size();\n if (bootstrap)\n {\n vector<float> scores;\n for (int i = 0; i < bootstrap; ++i)\n {\n \/\/ TODO: Use smart pointer for exceptional-safety.\n ScoreData* scoredata = new ScoreData(*scorer);\n for (int j = 0; j < n; ++j)\n {\n int randomIndex = random() % n;\n string str_j = int2string(j);\n scoredata->add(entries[randomIndex], str_j);\n }\n scorer->setScoreData(scoredata);\n candidates_t candidates(n, 0);\n float score = scorer->score(candidates);\n scores.push_back(score);\n delete scoredata;\n }\n\n float avg = average(scores);\n float dev = stdDeviation(scores, avg);\n\n if (moreFiles) cout << candFile << \"\\t\";\n if (moreScorers) cout << scorer->getName() << \"\\t\";\n\n cout.setf(ios::fixed,ios::floatfield);\n cout.precision(4);\n cout << avg << \" [+-\" << dev << \"]\"<< endl;\n }\n else\n {\n \/\/ TODO: Use smart pointer for exceptional-safety.\n ScoreData* scoredata = new ScoreData(*scorer);\n for (int sid = 0; sid < n; ++sid)\n {\n string str_sid = int2string(sid);\n scoredata->add(entries[sid], str_sid);\n }\n scorer->setScoreData(scoredata);\n candidates_t candidates(n, 0);\n float score = scorer->score(candidates);\n delete scoredata;\n \n if (moreFiles) cout << candFile << \"\\t\";\n if (moreScorers) cout << scorer->getName() << \"\\t\";\n \n cout.setf(ios::fixed,ios::floatfield);\n cout.precision(4);\n cout << score << endl;\n }\n}\n\nstring int2string(int n)\n{\n stringstream ss;\n ss << n;\n return ss.str();\n}\n\nfloat average(const vector<float>& list)\n{\n float sum = 0;\n for (vector<float>::const_iterator it = list.begin(); it != list.end(); ++it)\n sum += *it;\n\n return sum \/ list.size();\n}\n\nfloat stdDeviation(const vector<float>& list, float avg)\n{\n vector<float> tmp;\n for (vector<float>::const_iterator it = list.begin(); it != list.end(); ++it)\n tmp.push_back(pow(*it - avg, 2));\n\n return sqrt(average(tmp));\n}\n<commit_msg>mert\/evaluator should now compute confidence interval correctly<commit_after>#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <getopt.h>\n#include <math.h>\n\n#include \"Scorer.h\"\n#include \"Timer.h\"\n#include \"Util.h\"\n\n#include \"ScorerFactory.h\"\n\nusing namespace std;\n\nScorer* scorer;\nint bootstrap = 0;\nvoid evaluate(const string& candFile);\nvoid addStats(vector<int>& stats1, const vector<int>& stats2);\nfloat average(const vector<float>& list);\nfloat stdDeviation(const vector<float>& list, float avg);\nstring int2string(int n);\n\nbool moreFiles = false;\nbool moreScorers = false;\n\nfloat alpha = 0.05;\n\nvoid usage()\n{\n cerr<<\"usage: evaluator [options] --reference ref1[,ref2[,ref3...]] --candidate cand1[,cand2[,cand3...]] \"<<endl;\n cerr<<\"[--sctype|-s] the scorer type (default BLEU)\"<<endl;\n cerr<<\"[--scconfig|-c] configuration string passed to scorer\"<<endl;\n cerr<<\"\\tThis is of the form NAME1:VAL1,NAME2:VAL2 etc \"<<endl;\n cerr<<\"[--reference|-R] comma separated list of reference files\"<<endl;\n cerr<<\"[--candidate|-C] comma separated list of candidate files\"<<endl;\n cerr<<\"[--bootstrap|-b] number of booststraped samples (default 0 - no bootstraping)\"<<endl;\n cerr<<\"[--rseed|-r] the random seed for bootstraping (defaults to system clock)\"<<endl;\n cerr<<\"[--help|-h] print this message and exit\"<<endl;\n cerr<<endl;\n cerr<<\"Evaluator is able to compute more metrics at once. To do this,\"<<endl;\n cerr<<\"separate scorers with semicolon (note that comma is used to separate\"<<endl;\n cerr<<\"scorers in the interpolated scorer).\"<<endl;\n cerr<<endl;\n cerr<<\"If you specify only one metric and one candidate file, only the final score\"<<endl;\n cerr<<\"will be printed to stdout. Otherwise each line will contain metric name\"<<endl;\n cerr<<\"and\/or filename and the final score. Since most of the metrics prints some\"<<endl;\n cerr<<\"debuging info, consider redirecting stderr to \/dev\/null.\"<<endl;\n exit(1);\n}\n\nstatic struct option long_options[] = {\n {\"sctype\",required_argument,0,'s'},\n {\"scconfig\",required_argument,0,'c'},\n {\"reference\",required_argument,0,'R'},\n {\"candidate\",required_argument,0,'C'},\n {\"bootstrap\",required_argument,0,'b'},\n {\"rseed\",required_argument,0,'r'},\n {\"help\",no_argument,0,'h'},\n {0, 0, 0, 0}\n};\nint option_index;\n\nint main(int argc, char** argv)\n{\n ResetUserTime();\n\n \/\/defaults\n string scorerType(\"BLEU\");\n string scorerConfig(\"\");\n string reference(\"\");\n string candidate(\"\");\n\n int seed = 0;\n bool hasSeed = false;\n\n int c;\n while ((c=getopt_long (argc,argv, \"s:c:R:C:b:r:h\", long_options, &option_index)) != -1) {\n switch(c) {\n case 's':\n scorerType = string(optarg);\n break;\n case 'c':\n scorerConfig = string(optarg);\n break;\n case 'R':\n reference = string(optarg);\n break;\n case 'C':\n candidate = string(optarg);\n break;\n case 'b':\n bootstrap = atoi(optarg);\n break;\n case 'r':\n seed = strtol(optarg, NULL, 10);\n hasSeed = true;\n break;\n default:\n usage();\n }\n }\n\n if (bootstrap)\n {\n if (hasSeed) {\n cerr << \"Seeding random numbers with \" << seed << endl;\n srandom(seed);\n } else {\n cerr << \"Seeding random numbers with system clock \" << endl;\n srandom(time(NULL));\n }\n }\n\n try {\n vector<string> refFiles;\n vector<string> candFiles;\n vector<string> scorerTypes;\n\n \n\n if (reference.length() == 0) throw runtime_error(\"You have to specify at least one reference file.\");\n split(reference,',',refFiles);\n\n if (candidate.length() == 0) throw runtime_error(\"You have to specify at least one candidate file.\");\n split(candidate,',',candFiles);\n\n if (scorerType.length() == 0) throw runtime_error(\"You have to specify at least one scorer.\");\n split(scorerType,';',scorerTypes);\n \n if (candFiles.size() > 1) moreFiles = true;\n if (scorerTypes.size() > 1) moreScorers = true;\n \n for (vector<string>::const_iterator fileIt = candFiles.begin(); fileIt != candFiles.end(); ++fileIt)\n {\n for (vector<string>::const_iterator scorerIt = scorerTypes.begin(); scorerIt != scorerTypes.end(); ++scorerIt)\n {\n scorer = ScorerFactory::getScorer(*scorerIt,scorerConfig);\n scorer->setReferenceFiles(refFiles);\n evaluate(*fileIt);\n delete scorer;\n }\n }\n\n return EXIT_SUCCESS;\n } catch (const exception& e) {\n cerr << \"Exception: \" << e.what() << endl;\n return EXIT_FAILURE;\n }\n\n}\n\nvoid evaluate(const string& candFile)\n{\n ifstream cand(candFile.c_str());\n if (!cand.good()) throw runtime_error(\"Error opening candidate file\");\n\n vector<ScoreStats> entries;\n\n \/\/ Loading sentences and preparing statistics\n ScoreStats scoreentry;\n string line;\n while (getline(cand, line))\n {\n scorer->prepareStats(entries.size(), line, scoreentry);\n entries.push_back(scoreentry);\n }\n\n int n = entries.size();\n if (bootstrap)\n {\n vector<float> scores;\n for (int i = 0; i < bootstrap; ++i)\n {\n \/\/ TODO: Use smart pointer for exceptional-safety.\n ScoreData* scoredata = new ScoreData(*scorer);\n for (int j = 0; j < n; ++j)\n {\n int randomIndex = random() % n;\n string str_j = int2string(j);\n scoredata->add(entries[randomIndex], str_j);\n }\n scorer->setScoreData(scoredata);\n candidates_t candidates(n, 0);\n float score = scorer->score(candidates);\n scores.push_back(score);\n delete scoredata;\n } \n\n float avg = average(scores);\n \n sort(scores.begin(), scores.end());\n \n int lbIdx = scores.size() * (alpha \/ 2);\n int rbIdx = scores.size() * (1 - alpha \/ 2);\n\n float lb = scores[lbIdx];\n float rb = scores[rbIdx];\n\n if (moreFiles) cout << candFile << \"\\t\";\n if (moreScorers) cout << scorer->getName() << \"\\t\";\n\n cout.setf(ios::fixed,ios::floatfield);\n cout.precision(4);\n cout << avg << \"\\t[\" << lb << \",\" << rb << \"]\"<< endl;\n }\n else\n {\n \/\/ TODO: Use smart pointer for exceptional-safety.\n ScoreData* scoredata = new ScoreData(*scorer);\n for (int sid = 0; sid < n; ++sid)\n {\n string str_sid = int2string(sid);\n scoredata->add(entries[sid], str_sid);\n }\n scorer->setScoreData(scoredata);\n candidates_t candidates(n, 0);\n float score = scorer->score(candidates);\n delete scoredata;\n \n if (moreFiles) cout << candFile << \"\\t\";\n if (moreScorers) cout << scorer->getName() << \"\\t\";\n \n cout.setf(ios::fixed,ios::floatfield);\n cout.precision(4);\n cout << score << endl;\n }\n}\n\nstring int2string(int n)\n{\n stringstream ss;\n ss << n;\n return ss.str();\n}\n\nfloat average(const vector<float>& list)\n{\n float sum = 0;\n for (vector<float>::const_iterator it = list.begin(); it != list.end(); ++it)\n sum += *it;\n\n return sum \/ list.size();\n}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n filename: BitmapImage.cpp\n created: Wed Feb 16 2011\n author: Paul D Turner <paul@cegui.org.uk>\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/BitmapImage.h\"\n#include \"CEGUI\/GeometryBuffer.h\"\n#include \"CEGUI\/Texture.h\"\n#include \"CEGUI\/Vertex.h\"\n#include \"CEGUI\/ColourRect.h\"\n#include \"CEGUI\/XMLAttributes.h\"\n#include \"CEGUI\/System.h\" \/\/ this being here is a bit nasty IMO\n#include \"CEGUI\/CoordConverter.h\"\n\n#include <glm\/glm.hpp>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\nconst String ImageTypeAttribute( \"type\" );\nconst String ImageNameAttribute( \"name\" );\nconst String ImageTextureAttribute( \"texture\" );\nconst String ImageXPosAttribute( \"xPos\" );\nconst String ImageYPosAttribute( \"yPos\" );\nconst String ImageWidthAttribute( \"width\" );\nconst String ImageHeightAttribute( \"height\" );\nconst String ImageXOffsetAttribute( \"xOffset\" );\nconst String ImageYOffsetAttribute( \"yOffset\" );\nconst String ImageAutoScaledAttribute( \"autoScaled\" );\nconst String ImageNativeHorzResAttribute( \"nativeHorzRes\" );\nconst String ImageNativeVertResAttribute( \"nativeVertRes\" );\n\n\/\/----------------------------------------------------------------------------\/\/\nBitmapImage::BitmapImage(const String& name) :\n Image(name),\n d_texture(0)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nBitmapImage::BitmapImage(const XMLAttributes& attributes) :\n Image(attributes.getValueAsString(ImageNameAttribute),\n Vector2f(static_cast<float>(attributes.getValueAsInteger(ImageXOffsetAttribute, 0)),\n static_cast<float>(attributes.getValueAsInteger(ImageYOffsetAttribute, 0))),\n Rectf(Vector2f(static_cast<float>(attributes.getValueAsInteger(ImageXPosAttribute, 0)),\n static_cast<float>(attributes.getValueAsInteger(ImageYPosAttribute, 0))),\n Sizef(static_cast<float>(attributes.getValueAsInteger(ImageWidthAttribute, 0)),\n static_cast<float>(attributes.getValueAsInteger(ImageHeightAttribute, 0))) ),\n PropertyHelper<AutoScaledMode>::fromString(attributes.getValueAsString(ImageAutoScaledAttribute)),\n Sizef(static_cast<float>(attributes.getValueAsInteger(ImageNativeHorzResAttribute, 640)),\n static_cast<float>(attributes.getValueAsInteger(ImageNativeVertResAttribute, 480))) ),\n d_texture(&System::getSingleton().getRenderer()->getTexture(\n attributes.getValueAsString(ImageTextureAttribute)))\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nBitmapImage::BitmapImage(const String& name, Texture* texture,\n const Rectf& pixel_area, const Vector2f& pixel_offset,\n const AutoScaledMode autoscaled, const Sizef& native_res) :\n Image(name,\n pixel_offset,\n pixel_area,\n autoscaled,\n native_res),\n d_texture(texture)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid BitmapImage::setTexture(Texture* texture)\n{\n d_texture = texture;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid BitmapImage::render(std::vector<GeometryBuffer*>& geometry_buffers,\n const ImageRenderSettings& render_settings) const\n{\n const QuadSplitMode quad_split_mode(TopLeftToBottomRight);\n\n Rectf dest(render_settings.d_destArea);\n \/\/ apply rendering offset to the destination Rect\n dest.offset(d_scaledOffset);\n\n const CEGUI::Rectf*const& clip_area = render_settings.d_clipArea;\n \/\/ get the rect area that we will actually draw to (i.e. perform clipping)\n Rectf final_rect(clip_area ? dest.getIntersection(*clip_area) : dest );\n\n \/\/ check if rect was totally clipped\n if ((final_rect.getWidth() == 0) || (final_rect.getHeight() == 0))\n return;\n\n \/\/ Obtain correct scale values from the texture\n const Vector2f& texel_scale = d_texture->getTexelScaling();\n const Vector2f tex_per_pix(d_imageArea.getWidth() \/ dest.getWidth(), d_imageArea.getHeight() \/ dest.getHeight());\n\n \/\/ calculate final, clipped, texture co-ordinates\n const Rectf tex_rect((d_imageArea + ((final_rect - dest) * tex_per_pix)) * texel_scale);\n\n \/\/ URGENT FIXME: Shouldn't this be in the hands of the user?\n final_rect.d_min.d_x = CoordConverter::alignToPixels(final_rect.d_min.d_x);\n final_rect.d_min.d_y = CoordConverter::alignToPixels(final_rect.d_min.d_y);\n final_rect.d_max.d_x = CoordConverter::alignToPixels(final_rect.d_max.d_x);\n final_rect.d_max.d_y = CoordConverter::alignToPixels(final_rect.d_max.d_y);\n\n TexturedColouredVertex vbuffer[6];\n const CEGUI::ColourRect& colours = render_settings.d_multiplyColours;\n\n \/\/ vertex 0\n vbuffer[0].position = glm::vec3(final_rect.left(), final_rect.top(), 0.0f);\n vbuffer[0].colour_val = colours.d_top_left;\n vbuffer[0].tex_coords = glm::vec2(tex_rect.left(), tex_rect.top());\n\n \/\/ vertex 1\n vbuffer[1].position = glm::vec3(final_rect.left(), final_rect.bottom(), 0.0f);\n vbuffer[1].colour_val = colours.d_bottom_left;\n vbuffer[1].tex_coords = glm::vec2(tex_rect.left(), tex_rect.bottom());\n\n \/\/ vertex 2\n vbuffer[2].position.x = final_rect.right();\n vbuffer[2].position.z = 0.0f;\n vbuffer[2].colour_val = colours.d_bottom_right;\n vbuffer[2].tex_coords.x = tex_rect.right();\n\n \/\/ top-left to bottom-right diagonal\n if (quad_split_mode == TopLeftToBottomRight)\n {\n vbuffer[2].position.y = final_rect.bottom();\n vbuffer[2].tex_coords.y = tex_rect.bottom();\n }\n \/\/ bottom-left to top-right diagonal\n else\n {\n vbuffer[2].position.y = final_rect.top();\n vbuffer[2].tex_coords.y = tex_rect.top();\n }\n\n \/\/ vertex 3\n vbuffer[3].position = glm::vec3(final_rect.right(), final_rect.top(), 0.0f);\n vbuffer[3].colour_val = colours.d_top_right;\n vbuffer[3].tex_coords = glm::vec2(tex_rect.right(), tex_rect.top());\n\n \/\/ vertex 4\n vbuffer[4].position.x = final_rect.left();\n vbuffer[4].position.z = 0.0f;\n vbuffer[4].colour_val = colours.d_top_left;\n vbuffer[4].tex_coords.x = tex_rect.left();\n\n \/\/ top-left to bottom-right diagonal\n if (quad_split_mode == TopLeftToBottomRight)\n {\n vbuffer[4].position.y = final_rect.top();\n vbuffer[4].tex_coords.y = tex_rect.top();\n }\n \/\/ bottom-left to top-right diagonal\n else\n {\n vbuffer[4].position.y = final_rect.bottom();\n vbuffer[4].tex_coords.y = tex_rect.bottom();\n }\n\n \/\/ vertex 5\n vbuffer[5].position = glm::vec3(final_rect.right(), final_rect.bottom(), 0.0f);\n vbuffer[5].colour_val = colours.d_bottom_right;\n vbuffer[5].tex_coords = glm::vec2(tex_rect.right(), tex_rect.bottom());\n\n CEGUI::GeometryBuffer& buffer = System::getSingleton().getRenderer()->createGeometryBufferTextured();\n geometry_buffers.push_back(&buffer);\n\n buffer.setClippingActive(render_settings.d_clippingEnabled);\n if(render_settings.d_clippingEnabled)\n buffer.setClippingRegion(*render_settings.d_clipArea);\n buffer.setTexture(d_texture);\n buffer.appendGeometry(vbuffer, 6);\n}\n\n\n\n\n\/\/----------------------------------------------------------------------------\/\/\nconst Texture* BitmapImage::getTexture() const\n{\n return d_texture;\n}\n\n} \/\/ End of CEGUI namespace section\n\n<commit_msg>MOD: Formatting<commit_after>\/***********************************************************************\n filename: BitmapImage.cpp\n created: Wed Feb 16 2011\n author: Paul D Turner <paul@cegui.org.uk>\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/BitmapImage.h\"\n#include \"CEGUI\/GeometryBuffer.h\"\n#include \"CEGUI\/Texture.h\"\n#include \"CEGUI\/Vertex.h\"\n#include \"CEGUI\/ColourRect.h\"\n#include \"CEGUI\/XMLAttributes.h\"\n#include \"CEGUI\/System.h\" \/\/ this being here is a bit nasty IMO\n#include \"CEGUI\/CoordConverter.h\"\n\n#include <glm\/glm.hpp>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\nconst String ImageTypeAttribute( \"type\" );\nconst String ImageNameAttribute( \"name\" );\nconst String ImageTextureAttribute( \"texture\" );\nconst String ImageXPosAttribute( \"xPos\" );\nconst String ImageYPosAttribute( \"yPos\" );\nconst String ImageWidthAttribute( \"width\" );\nconst String ImageHeightAttribute( \"height\" );\nconst String ImageXOffsetAttribute( \"xOffset\" );\nconst String ImageYOffsetAttribute( \"yOffset\" );\nconst String ImageAutoScaledAttribute( \"autoScaled\" );\nconst String ImageNativeHorzResAttribute( \"nativeHorzRes\" );\nconst String ImageNativeVertResAttribute( \"nativeVertRes\" );\n\n\/\/----------------------------------------------------------------------------\/\/\nBitmapImage::BitmapImage(const String& name) :\n Image(name),\n d_texture(0)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nBitmapImage::BitmapImage(const XMLAttributes& attributes) :\n Image(attributes.getValueAsString(ImageNameAttribute),\n Vector2f(static_cast<float>(attributes.getValueAsInteger(ImageXOffsetAttribute, 0)),\n static_cast<float>(attributes.getValueAsInteger(ImageYOffsetAttribute, 0))),\n Rectf(Vector2f(static_cast<float>(attributes.getValueAsInteger(ImageXPosAttribute, 0)),\n static_cast<float>(attributes.getValueAsInteger(ImageYPosAttribute, 0))),\n Sizef(static_cast<float>(attributes.getValueAsInteger(ImageWidthAttribute, 0)),\n static_cast<float>(attributes.getValueAsInteger(ImageHeightAttribute, 0)))),\n PropertyHelper<AutoScaledMode>::fromString(attributes.getValueAsString(ImageAutoScaledAttribute)),\n Sizef(static_cast<float>(attributes.getValueAsInteger(ImageNativeHorzResAttribute, 640)),\n static_cast<float>(attributes.getValueAsInteger(ImageNativeVertResAttribute, 480)))),\n d_texture(&System::getSingleton().getRenderer()->getTexture(\n attributes.getValueAsString(ImageTextureAttribute)))\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nBitmapImage::BitmapImage(const String& name, Texture* texture,\n const Rectf& pixel_area, const Vector2f& pixel_offset,\n const AutoScaledMode autoscaled, const Sizef& native_res) :\n Image(name,\n pixel_offset,\n pixel_area,\n autoscaled,\n native_res),\n d_texture(texture)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid BitmapImage::setTexture(Texture* texture)\n{\n d_texture = texture;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid BitmapImage::render(std::vector<GeometryBuffer*>& geometry_buffers,\n const ImageRenderSettings& render_settings) const\n{\n const QuadSplitMode quad_split_mode(TopLeftToBottomRight);\n\n Rectf dest(render_settings.d_destArea);\n \/\/ apply rendering offset to the destination Rect\n dest.offset(d_scaledOffset);\n\n const CEGUI::Rectf*const& clip_area = render_settings.d_clipArea;\n \/\/ get the rect area that we will actually draw to (i.e. perform clipping)\n Rectf final_rect(clip_area ? dest.getIntersection(*clip_area) : dest );\n\n \/\/ check if rect was totally clipped\n if ((final_rect.getWidth() == 0) || (final_rect.getHeight() == 0))\n return;\n\n \/\/ Obtain correct scale values from the texture\n const Vector2f& texel_scale = d_texture->getTexelScaling();\n const Vector2f tex_per_pix(d_imageArea.getWidth() \/ dest.getWidth(), d_imageArea.getHeight() \/ dest.getHeight());\n\n \/\/ calculate final, clipped, texture co-ordinates\n const Rectf tex_rect((d_imageArea + ((final_rect - dest) * tex_per_pix)) * texel_scale);\n\n \/\/ URGENT FIXME: Shouldn't this be in the hands of the user?\n final_rect.d_min.d_x = CoordConverter::alignToPixels(final_rect.d_min.d_x);\n final_rect.d_min.d_y = CoordConverter::alignToPixels(final_rect.d_min.d_y);\n final_rect.d_max.d_x = CoordConverter::alignToPixels(final_rect.d_max.d_x);\n final_rect.d_max.d_y = CoordConverter::alignToPixels(final_rect.d_max.d_y);\n\n TexturedColouredVertex vbuffer[6];\n const CEGUI::ColourRect& colours = render_settings.d_multiplyColours;\n\n \/\/ vertex 0\n vbuffer[0].position = glm::vec3(final_rect.left(), final_rect.top(), 0.0f);\n vbuffer[0].colour_val = colours.d_top_left;\n vbuffer[0].tex_coords = glm::vec2(tex_rect.left(), tex_rect.top());\n\n \/\/ vertex 1\n vbuffer[1].position = glm::vec3(final_rect.left(), final_rect.bottom(), 0.0f);\n vbuffer[1].colour_val = colours.d_bottom_left;\n vbuffer[1].tex_coords = glm::vec2(tex_rect.left(), tex_rect.bottom());\n\n \/\/ vertex 2\n vbuffer[2].position.x = final_rect.right();\n vbuffer[2].position.z = 0.0f;\n vbuffer[2].colour_val = colours.d_bottom_right;\n vbuffer[2].tex_coords.x = tex_rect.right();\n\n \/\/ top-left to bottom-right diagonal\n if (quad_split_mode == TopLeftToBottomRight)\n {\n vbuffer[2].position.y = final_rect.bottom();\n vbuffer[2].tex_coords.y = tex_rect.bottom();\n }\n \/\/ bottom-left to top-right diagonal\n else\n {\n vbuffer[2].position.y = final_rect.top();\n vbuffer[2].tex_coords.y = tex_rect.top();\n }\n\n \/\/ vertex 3\n vbuffer[3].position = glm::vec3(final_rect.right(), final_rect.top(), 0.0f);\n vbuffer[3].colour_val = colours.d_top_right;\n vbuffer[3].tex_coords = glm::vec2(tex_rect.right(), tex_rect.top());\n\n \/\/ vertex 4\n vbuffer[4].position.x = final_rect.left();\n vbuffer[4].position.z = 0.0f;\n vbuffer[4].colour_val = colours.d_top_left;\n vbuffer[4].tex_coords.x = tex_rect.left();\n\n \/\/ top-left to bottom-right diagonal\n if (quad_split_mode == TopLeftToBottomRight)\n {\n vbuffer[4].position.y = final_rect.top();\n vbuffer[4].tex_coords.y = tex_rect.top();\n }\n \/\/ bottom-left to top-right diagonal\n else\n {\n vbuffer[4].position.y = final_rect.bottom();\n vbuffer[4].tex_coords.y = tex_rect.bottom();\n }\n\n \/\/ vertex 5\n vbuffer[5].position = glm::vec3(final_rect.right(), final_rect.bottom(), 0.0f);\n vbuffer[5].colour_val = colours.d_bottom_right;\n vbuffer[5].tex_coords = glm::vec2(tex_rect.right(), tex_rect.bottom());\n\n CEGUI::GeometryBuffer& buffer = System::getSingleton().getRenderer()->createGeometryBufferTextured();\n geometry_buffers.push_back(&buffer);\n\n buffer.setClippingActive(render_settings.d_clippingEnabled);\n if(render_settings.d_clippingEnabled)\n buffer.setClippingRegion(*render_settings.d_clipArea);\n buffer.setTexture(d_texture);\n buffer.appendGeometry(vbuffer, 6);\n}\n\n\n\n\n\/\/----------------------------------------------------------------------------\/\/\nconst Texture* BitmapImage::getTexture() const\n{\n return d_texture;\n}\n\n} \/\/ End of CEGUI namespace section\n\n<|endoftext|>"} {"text":"<commit_before>#include \"net\/RawSocket.h\"\n#include \"common\/RhodesApp.h\"\n\n#include <algorithm>\n\n#if !defined(OS_WINDOWS) && !defined(OS_WINCE)\n#include <arpa\/inet.h>\n#endif\n\n#if !defined(OS_WINCE)\n#include <common\/stat.h>\n\n#ifdef EAGAIN\n#undef EAGAIN\n#endif\n#define EAGAIN EWOULDBLOCK\n\n#else\n\n#include \"CompatWince.h\"\n\n#if defined(OS_WINDOWS) || defined(OS_WINCE)\ntypedef unsigned __int16 uint16_t;\n\n# ifndef S_ISDIR\n# define S_ISDIR(m) ((_S_IFDIR & m) == _S_IFDIR)\n# endif\n\n# ifndef S_ISREG\n# define S_ISREG(m) ((_S_IFREG & m) == _S_IFREG)\n# endif\n\n# ifndef EAGAIN\n# define EAGAIN WSAEWOULDBLOCK\n# endif\n#endif\n\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"RawSocket\"\n\nnamespace rho\n{\nnamespace net\n{\n\nbool RawSocket::init()\n{\n RAWTRACE(\"Init raw socket\");\n m_isInit = create();\n return m_isInit;\n}\n\nbool RawSocket::create()\n{\n RAWTRACE(\"Start create raw socket\");\n cleanup();\n\n int iResult;\n addrinfo *addrInfo = NULL, hints;\n\n memset( &hints, 0, sizeof(hints) );\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_protocol = IPPROTO_TCP;\n\n RAWTRACE(\"Get host adress\");\n\n \/\/ Resolve the server address and port\n iResult = getaddrinfo(m_hostName.c_str(), m_hostPort.c_str(), &hints, &addrInfo);\n\n if (iResult != 0) {\n RAWTRACE2(\"Unable to get addres info for host %s, port %s\", m_hostName.c_str(), m_hostPort.c_str());\n return false;\n }\n\n RAWTRACE(\"Create socket\");\n \/\/ Create a SOCKET for connecting to server\n m_clientSocket = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);\n\n if (m_clientSocket == INVALID_SOCKET) {\n RAWTRACE2(\"Socket can`t create for host %s, port %s\", m_hostName.c_str(), m_hostPort.c_str());\n freeaddrinfo(addrInfo);\n return false;\n }\n\n \/\/ Connect to server.\n RAWTRACE(\"Connect to server\");\n iResult = connect(m_clientSocket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen);\n\n if (iResult == SOCKET_ERROR) {\n RAWTRACE2(\"Can`t connect to host %s, port %s \", m_hostName.c_str(), m_hostPort.c_str());\n cleanup();\n return false;\n }\n\n freeaddrinfo(addrInfo);\n\n RAWTRACE(\"End of socket creating\");\n\n return true;\n}\n\nbool RawSocket::send(const String& sendData)\n{\n int iResult = 0;\n\n \/\/ Send an initial buffer\n iResult = ::send(m_clientSocket, sendData.c_str(), (int) sendData.size(), 0);\n\n if (iResult == SOCKET_ERROR) \n {\n RAWTRACE2(\"Data not send for host %s, port %s\", m_hostName.c_str(), m_hostPort.c_str());\n cleanup();\n return false;\n }\n\n return true;\n}\n\nvoid RawSocket::cleanup()\n{\n m_isInit = false;\n closesocket(m_clientSocket);\n m_clientSocket = INVALID_SOCKET;\n}\n\n} \/\/ namespace net\n} \/\/ namespace rho\n\n#endif<commit_msg>fix raw socket<commit_after>#include \"net\/RawSocket.h\"\n#include \"common\/RhodesApp.h\"\n\n#include <algorithm>\n\n#if !defined(OS_WINDOWS) && !defined(OS_WINCE)\n#include <arpa\/inet.h>\n#endif\n\n#if !defined(OS_WINCE)\n#include <common\/stat.h>\n\n#ifdef EAGAIN\n#undef EAGAIN\n#endif\n#define EAGAIN EWOULDBLOCK\n\n#else\n\n#include \"CompatWince.h\"\n\n#if defined(OS_WINDOWS) || defined(OS_WINCE)\ntypedef unsigned __int16 uint16_t;\n\n# ifndef S_ISDIR\n# define S_ISDIR(m) ((_S_IFDIR & m) == _S_IFDIR)\n# endif\n\n# ifndef S_ISREG\n# define S_ISREG(m) ((_S_IFREG & m) == _S_IFREG)\n# endif\n\n# ifndef EAGAIN\n# define EAGAIN WSAEWOULDBLOCK\n# endif\n#endif\n\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"RawSocket\"\n\nnamespace rho\n{\nnamespace net\n{\n\nbool RawSocket::init()\n{\n \/\/RAWTRACE(\"Init raw socket\");\n m_isInit = create();\n return m_isInit;\n}\n\nbool RawSocket::create()\n{\n \/\/RAWTRACE(\"Start create raw socket\");\n cleanup();\n\n int iResult;\n addrinfo *addrInfo = NULL, hints;\n\n memset( &hints, 0, sizeof(hints) );\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_protocol = IPPROTO_TCP;\n\n \/\/RAWTRACE(\"Get host adress\");\n\n \/\/ Resolve the server address and port\n iResult = getaddrinfo(m_hostName.c_str(), m_hostPort.c_str(), &hints, &addrInfo);\n\n if (iResult != 0) {\n \/\/RAWTRACE2(\"Unable to get addres info for host %s, port %s\", m_hostName.c_str(), m_hostPort.c_str());\n return false;\n }\n\n \/\/RAWTRACE(\"Create socket\");\n \/\/ Create a SOCKET for connecting to server\n m_clientSocket = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);\n\n if (m_clientSocket == INVALID_SOCKET) {\n \/\/RAWTRACE2(\"Socket can`t create for host %s, port %s\", m_hostName.c_str(), m_hostPort.c_str());\n freeaddrinfo(addrInfo);\n return false;\n }\n\n \/\/ Connect to server.\n \/\/RAWTRACE(\"Connect to server\");\n iResult = connect(m_clientSocket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen);\n\n if (iResult == SOCKET_ERROR) {\n \/\/RAWTRACE2(\"Can`t connect to host %s, port %s \", m_hostName.c_str(), m_hostPort.c_str());\n cleanup();\n return false;\n }\n\n freeaddrinfo(addrInfo);\n\n \/\/RAWTRACE(\"End of socket creating\");\n\n return true;\n}\n\nbool RawSocket::send(const String& sendData)\n{\n int iResult = 0;\n\n \/\/ Send an initial buffer\n iResult = ::send(m_clientSocket, sendData.c_str(), (int) sendData.size(), 0);\n\n if (iResult == SOCKET_ERROR) \n {\n \/\/RAWTRACE2(\"Data not send for host %s, port %s\", m_hostName.c_str(), m_hostPort.c_str());\n cleanup();\n return false;\n }\n\n return true;\n}\n\nvoid RawSocket::cleanup()\n{\n m_isInit = false;\n closesocket(m_clientSocket);\n m_clientSocket = INVALID_SOCKET;\n}\n\n} \/\/ namespace net\n} \/\/ namespace rho\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ File: oapicimpl.hpp\n\/\/\n\/\/ Desc: OpenCVR API - OpenCVR API.\n\/\/\n\/\/ Copyright (c) 2014-2018 opencvr.com. All rights reserved.\n\/\/------------------------------------------------------------------------------\n#ifndef __VSC_OAPIC_IMPL_H_\n#define __VSC_OAPIC_IMPL_H_\n\nOAPIClient::OAPIClient(XRef<XSocket> pSocket)\n:m_pSocket(pSocket)\n{\n\n}\nOAPIClient::~OAPIClient()\n{\n\n}\n\nBOOL OAPIClient::DeviceListRequest(oapi::DeviceList &list)\n{\n\tOAPIHeader header;\n\theader.cmd = htonl(OAPI_CMD_GET_DEVICE_REQ);\n\theader.length = 0;\n\n\tm_pSocket->Send((void *)&header, sizeof(header));\n\n\ts32 nRet = m_pSocket->Recv((void *)&header, sizeof(header));\n\tif (nRet == sizeof(header))\n\t{\n\t\theader.length = ntohl(header.length);\n\t\tchar *pRecv = new char[header.length + 1];\n\t\ts32 nRetBody = m_pSocket->Recv((void *)pRecv, header.length);\n\t\tif (nRetBody == header.length)\n\t\t{\n\t\t\tstd::cerr << pRecv << '\\n';\n\t\t\tautojsoncxx::ParsingResult result;\n\t\t\tif (!autojsoncxx::from_json_string(pRecv, list, result)) \n\t\t\t{\n\t\t\t \/\/std::cerr << result << '\\n';\n\t\t\t \/\/return FALSE;\n\t\t\t}\n\t\t\tdelete pRecv;\n\t\t\t\n\t\t}else\n\t\t{\n\t\t\tdelete pRecv;\n\t\t\treturn FALSE;\n\t\t}\n\t}else\n\t{\n\t\treturn FALSE;\n\t}\n}\n\n#endif<commit_msg>add parse<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ File: oapicimpl.hpp\n\/\/\n\/\/ Desc: OpenCVR API - OpenCVR API.\n\/\/\n\/\/ Copyright (c) 2014-2018 opencvr.com. All rights reserved.\n\/\/------------------------------------------------------------------------------\n#ifndef __VSC_OAPIC_IMPL_H_\n#define __VSC_OAPIC_IMPL_H_\n\nOAPIClient::OAPIClient(XRef<XSocket> pSocket)\n:m_pSocket(pSocket)\n{\n\n}\nOAPIClient::~OAPIClient()\n{\n\n}\n\n\n\/* Setup connect with server *\/\nBOOL OAPIClient::Setup(std::string strUser, std::string strPasswd)\n{\n\t\/\/TODO\n\treturn TRUE;\n}\n\nBOOL OAPIClient::SendDeviceListRequest()\n{\n\tOAPIHeader header;\n\theader.cmd = htonl(OAPI_CMD_DEVICE_LIST_REQ);\n\theader.length = 0;\n\n\tm_pSocket->Send((void *)&header, sizeof(header));\n\n\treturn TRUE;\n\n}\n\nBOOL OAPIClient::StartLiveview(int nId)\n{\n\tOAPIHeader header;\n\n\toapi::LiveView liveview;\n\tliveview.nId = nId;\n\t\n\tstd::string strJson = autojsoncxx::to_pretty_json_string(liveview);\n\ts32 nJsonLen = strJson.length();\n\tif (nJsonLen <= 0)\n\t{\n\t\treturn FALSE;\n\t}\n\theader.cmd = htonl(OAPI_CMD_START_LIVE);\n\theader.length = htonl(nJsonLen + 1);;\n\t\n\tm_pSocket->Send((void *)&header, sizeof(header));\n\tm_pSocket->Send((void *)strJson.c_str(), nJsonLen + 1);\n\treturn TRUE;\n\n}\n\nBOOL OAPIClient::StopLiveview(int nId)\n{\n\tOAPIHeader header;\n\n\toapi::LiveView liveview;\n\tliveview.nId = nId;\n\t\n\tstd::string strJson = autojsoncxx::to_pretty_json_string(liveview);\n\ts32 nJsonLen = strJson.length();\n\tif (nJsonLen <= 0)\n\t{\n\t\treturn FALSE;\n\t}\n\theader.cmd = htonl(OAPI_CMD_STOP_LIVE);\n\theader.length = htonl(nJsonLen + 1);\n\t\n\tm_pSocket->Send((void *)&header, sizeof(header));\n\tm_pSocket->Send((void *)strJson.c_str(), nJsonLen + 1);\n\treturn TRUE;\n\n}\nBOOL OAPIClient::ParseDeviceList(char *pRecv, int len, oapi::DeviceList &list)\n{\n\tautojsoncxx::ParsingResult result;\n\tif (!autojsoncxx::from_json_string(pRecv, list, result)) \n\t{\n\t std::cerr << result << '\\n';\n\t return FALSE;\n\t}\n\treturn TRUE;\n}\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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\/browser\/extensions\/extension_protocols.h\"\n\n#include <algorithm>\n\n#include \"app\/resource_bundle.h\"\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/extensions\/extension_file_util.h\"\n#include \"chrome\/common\/extensions\/extension_resource.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"googleurl\/src\/url_util.h\"\n#include \"grit\/bookmark_manager_resources_map.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/url_request\/url_request_error_job.h\"\n#include \"net\/url_request\/url_request_file_job.h\"\n#include \"net\/url_request\/url_request_simple_job.h\"\n\nnamespace {\n\nclass URLRequestResourceBundleJob : public URLRequestSimpleJob {\n public:\n explicit URLRequestResourceBundleJob(URLRequest* request,\n const FilePath& filename, int resource_id)\n : URLRequestSimpleJob(request),\n filename_(filename),\n resource_id_(resource_id) { }\n\n \/\/ URLRequestSimpleJob method.\n virtual bool GetData(std::string* mime_type,\n std::string* charset,\n std::string* data) const {\n const ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n *data = rb.GetRawDataResource(resource_id_).as_string();\n bool result = net::GetMimeTypeFromFile(filename_, mime_type);\n if (StartsWithASCII(*mime_type, \"text\/\", false)) {\n \/\/ All of our HTML files should be UTF-8 and for other resource types\n \/\/ (like images), charset doesn't matter.\n DCHECK(IsStringUTF8(*data));\n *charset = \"utf-8\";\n }\n return result;\n }\n\n private:\n virtual ~URLRequestResourceBundleJob() { }\n\n \/\/ We need the filename of the resource to determine the mime type.\n FilePath filename_;\n\n \/\/ The resource bundle id to load.\n int resource_id_;\n};\n\n\/\/ Returns true if an chrome-extension:\/\/ resource should be allowed to load.\nbool AllowExtensionResourceLoad(URLRequest* request,\n ChromeURLRequestContext* context,\n const std::string& scheme) {\n const ResourceDispatcherHostRequestInfo* info =\n ResourceDispatcherHost::InfoForRequest(request);\n\n GURL origin_url(info->frame_origin());\n\n \/\/ chrome:\/\/ URLs are always allowed to load chrome-extension:\/\/ resources.\n \/\/ The app launcher in the NTP uses this feature, as does dev tools.\n if (origin_url.SchemeIs(chrome::kChromeUIScheme))\n return true;\n\n \/\/ Disallow loading of packaged resources for hosted apps. We don't allow\n \/\/ hybrid hosted\/packaged apps.\n if (context->ExtensionHasWebExtent(request->url().host()))\n return false;\n\n \/\/ chrome-extension:\/\/ pages can load resources from extensions and packaged\n \/\/ apps. This is allowed for legacy reasons.\n if (origin_url.SchemeIs(chrome::kExtensionScheme))\n return true;\n\n \/\/ Extension resources should only be loadable from web pages which the\n \/\/ extension has host permissions to (and therefore could be running script\n \/\/ in, which might need access to the extension resources).\n ExtensionExtent host_permissions =\n context->GetEffectiveHostPermissionsForExtension(request->url().host());\n if (!origin_url.is_empty() && !host_permissions.ContainsURL(origin_url))\n return false;\n\n \/\/ Don't allow toplevel navigations to extension resources in incognito mode.\n \/\/ This is because an extension must run in a single process, and an\n \/\/ incognito tab prevents that.\n if (context->is_off_the_record() &&\n info->resource_type() == ResourceType::MAIN_FRAME) {\n return false;\n }\n\n \/\/ Otherwise, the resource load is allowed.\n return true;\n}\n\n} \/\/ namespace\n\n\/\/ Factory registered with URLRequest to create URLRequestJobs for extension:\/\/\n\/\/ URLs.\nstatic URLRequestJob* CreateExtensionURLRequestJob(URLRequest* request,\n const std::string& scheme) {\n ChromeURLRequestContext* context =\n static_cast<ChromeURLRequestContext*>(request->context());\n\n \/\/ TODO(mpcomplete): better error code.\n if (!AllowExtensionResourceLoad(request, context, scheme))\n return new URLRequestErrorJob(request, net::ERR_ADDRESS_UNREACHABLE);\n\n \/\/ chrome-extension:\/\/extension-id\/resource\/path.js\n const std::string& extension_id = request->url().host();\n FilePath directory_path = context->GetPathForExtension(extension_id);\n if (directory_path.value().empty()) {\n LOG(WARNING) << \"Failed to GetPathForExtension: \" << extension_id;\n return NULL;\n }\n\n FilePath resources_path;\n if (PathService::Get(chrome::DIR_RESOURCES, &resources_path) &&\n directory_path.DirName() == resources_path) {\n FilePath relative_path = directory_path.BaseName().Append(\n extension_file_util::ExtensionURLToRelativeFilePath(request->url()));\n#if defined(OS_WIN)\n relative_path = relative_path.NormalizeWindowsPathSeparators();\n#endif\n\n \/\/ TODO(tc): Make a map of FilePath -> resource ids so we don't have to\n \/\/ covert to FilePaths all the time. This will be more useful as we add\n \/\/ more resources.\n for (size_t i = 0; i < kBookmarkManagerResourcesSize; ++i) {\n FilePath bm_resource_path =\n FilePath().AppendASCII(kBookmarkManagerResources[i].name);\n#if defined(OS_WIN)\n bm_resource_path = bm_resource_path.NormalizeWindowsPathSeparators();\n#endif\n if (relative_path == bm_resource_path) {\n return new URLRequestResourceBundleJob(request, relative_path,\n kBookmarkManagerResources[i].value);\n }\n }\n }\n \/\/ TODO(tc): Move all of these files into resources.pak so we don't break\n \/\/ when updating on Linux.\n ExtensionResource resource(extension_id, directory_path,\n extension_file_util::ExtensionURLToRelativeFilePath(request->url()));\n\n return new URLRequestFileJob(request,\n resource.GetFilePathOnAnyThreadHack());\n}\n\n\/\/ Factory registered with URLRequest to create URLRequestJobs for\n\/\/ chrome-user-script:\/ URLs.\nstatic URLRequestJob* CreateUserScriptURLRequestJob(URLRequest* request,\n const std::string& scheme) {\n ChromeURLRequestContext* context =\n static_cast<ChromeURLRequestContext*>(request->context());\n\n \/\/ chrome-user-script:\/user-script-name.user.js\n FilePath directory_path = context->user_script_dir_path();\n\n ExtensionResource resource(request->url().host(), directory_path,\n extension_file_util::ExtensionURLToRelativeFilePath(request->url()));\n\n return new URLRequestFileJob(request, resource.GetFilePath());\n}\n\nvoid RegisterExtensionProtocols() {\n URLRequest::RegisterProtocolFactory(chrome::kExtensionScheme,\n &CreateExtensionURLRequestJob);\n URLRequest::RegisterProtocolFactory(chrome::kUserScriptScheme,\n &CreateUserScriptURLRequestJob);\n}\n<commit_msg>Fixes a bug in revision 55103 that prevents extensions from loading their own resources in some rare cases when the origin is \"null\". <commit_after>\/\/ Copyright (c) 2010 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\/browser\/extensions\/extension_protocols.h\"\n\n#include <algorithm>\n\n#include \"app\/resource_bundle.h\"\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/extensions\/extension_file_util.h\"\n#include \"chrome\/common\/extensions\/extension_resource.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"googleurl\/src\/url_util.h\"\n#include \"grit\/bookmark_manager_resources_map.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/url_request\/url_request_error_job.h\"\n#include \"net\/url_request\/url_request_file_job.h\"\n#include \"net\/url_request\/url_request_simple_job.h\"\n\nnamespace {\n\nclass URLRequestResourceBundleJob : public URLRequestSimpleJob {\n public:\n explicit URLRequestResourceBundleJob(URLRequest* request,\n const FilePath& filename, int resource_id)\n : URLRequestSimpleJob(request),\n filename_(filename),\n resource_id_(resource_id) { }\n\n \/\/ URLRequestSimpleJob method.\n virtual bool GetData(std::string* mime_type,\n std::string* charset,\n std::string* data) const {\n const ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n *data = rb.GetRawDataResource(resource_id_).as_string();\n bool result = net::GetMimeTypeFromFile(filename_, mime_type);\n if (StartsWithASCII(*mime_type, \"text\/\", false)) {\n \/\/ All of our HTML files should be UTF-8 and for other resource types\n \/\/ (like images), charset doesn't matter.\n DCHECK(IsStringUTF8(*data));\n *charset = \"utf-8\";\n }\n return result;\n }\n\n private:\n virtual ~URLRequestResourceBundleJob() { }\n\n \/\/ We need the filename of the resource to determine the mime type.\n FilePath filename_;\n\n \/\/ The resource bundle id to load.\n int resource_id_;\n};\n\n\/\/ Returns true if an chrome-extension:\/\/ resource should be allowed to load.\nbool AllowExtensionResourceLoad(URLRequest* request,\n ChromeURLRequestContext* context,\n const std::string& scheme) {\n const ResourceDispatcherHostRequestInfo* info =\n ResourceDispatcherHost::InfoForRequest(request);\n\n GURL origin_url(info->frame_origin());\n\n \/\/ chrome:\/\/ URLs are always allowed to load chrome-extension:\/\/ resources.\n \/\/ The app launcher in the NTP uses this feature, as does dev tools.\n if (origin_url.SchemeIs(chrome::kChromeUIScheme))\n return true;\n\n \/\/ Disallow loading of packaged resources for hosted apps. We don't allow\n \/\/ hybrid hosted\/packaged apps.\n if (context->ExtensionHasWebExtent(request->url().host()))\n return false;\n\n \/\/ chrome-extension:\/\/ pages can load resources from extensions and packaged\n \/\/ apps. This is allowed for legacy reasons.\n if (origin_url.SchemeIs(chrome::kExtensionScheme))\n return true;\n\n \/\/ Allow extenion's options pages to access resources media resources.\n \/\/ This will have an origin of \"null\".\n if (LowerCaseEqualsASCII(info->frame_origin(), \"null\"))\n return true;\n\n \/\/ Extension resources should only be loadable from web pages which the\n \/\/ extension has host permissions to (and therefore could be running script\n \/\/ in, which might need access to the extension resources).\n ExtensionExtent host_permissions =\n context->GetEffectiveHostPermissionsForExtension(request->url().host());\n if (!origin_url.is_empty() && !host_permissions.ContainsURL(origin_url))\n return false;\n\n \/\/ Don't allow toplevel navigations to extension resources in incognito mode.\n \/\/ This is because an extension must run in a single process, and an\n \/\/ incognito tab prevents that.\n if (context->is_off_the_record() &&\n info->resource_type() == ResourceType::MAIN_FRAME) {\n return false;\n }\n\n \/\/ Otherwise, the resource load is allowed.\n return true;\n}\n\n} \/\/ namespace\n\n\/\/ Factory registered with URLRequest to create URLRequestJobs for extension:\/\/\n\/\/ URLs.\nstatic URLRequestJob* CreateExtensionURLRequestJob(URLRequest* request,\n const std::string& scheme) {\n ChromeURLRequestContext* context =\n static_cast<ChromeURLRequestContext*>(request->context());\n\n \/\/ TODO(mpcomplete): better error code.\n if (!AllowExtensionResourceLoad(request, context, scheme))\n return new URLRequestErrorJob(request, net::ERR_ADDRESS_UNREACHABLE);\n\n \/\/ chrome-extension:\/\/extension-id\/resource\/path.js\n const std::string& extension_id = request->url().host();\n FilePath directory_path = context->GetPathForExtension(extension_id);\n if (directory_path.value().empty()) {\n LOG(WARNING) << \"Failed to GetPathForExtension: \" << extension_id;\n return NULL;\n }\n\n FilePath resources_path;\n if (PathService::Get(chrome::DIR_RESOURCES, &resources_path) &&\n directory_path.DirName() == resources_path) {\n FilePath relative_path = directory_path.BaseName().Append(\n extension_file_util::ExtensionURLToRelativeFilePath(request->url()));\n#if defined(OS_WIN)\n relative_path = relative_path.NormalizeWindowsPathSeparators();\n#endif\n\n \/\/ TODO(tc): Make a map of FilePath -> resource ids so we don't have to\n \/\/ covert to FilePaths all the time. This will be more useful as we add\n \/\/ more resources.\n for (size_t i = 0; i < kBookmarkManagerResourcesSize; ++i) {\n FilePath bm_resource_path =\n FilePath().AppendASCII(kBookmarkManagerResources[i].name);\n#if defined(OS_WIN)\n bm_resource_path = bm_resource_path.NormalizeWindowsPathSeparators();\n#endif\n if (relative_path == bm_resource_path) {\n return new URLRequestResourceBundleJob(request, relative_path,\n kBookmarkManagerResources[i].value);\n }\n }\n }\n \/\/ TODO(tc): Move all of these files into resources.pak so we don't break\n \/\/ when updating on Linux.\n ExtensionResource resource(extension_id, directory_path,\n extension_file_util::ExtensionURLToRelativeFilePath(request->url()));\n\n return new URLRequestFileJob(request,\n resource.GetFilePathOnAnyThreadHack());\n}\n\n\/\/ Factory registered with URLRequest to create URLRequestJobs for\n\/\/ chrome-user-script:\/ URLs.\nstatic URLRequestJob* CreateUserScriptURLRequestJob(URLRequest* request,\n const std::string& scheme) {\n ChromeURLRequestContext* context =\n static_cast<ChromeURLRequestContext*>(request->context());\n\n \/\/ chrome-user-script:\/user-script-name.user.js\n FilePath directory_path = context->user_script_dir_path();\n\n ExtensionResource resource(request->url().host(), directory_path,\n extension_file_util::ExtensionURLToRelativeFilePath(request->url()));\n\n return new URLRequestFileJob(request, resource.GetFilePath());\n}\n\nvoid RegisterExtensionProtocols() {\n URLRequest::RegisterProtocolFactory(chrome::kExtensionScheme,\n &CreateExtensionURLRequestJob);\n URLRequest::RegisterProtocolFactory(chrome::kUserScriptScheme,\n &CreateUserScriptURLRequestJob);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"base\/gfx\/png_encoder.h\"\n#include \"chrome\/browser\/browser_theme_provider.h\"\n#include \"chrome\/browser\/dom_ui\/dom_ui_theme_source.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/testing_profile.h\"\n#include \"grit\/theme_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ A mock ThemeSource (so we can override SendResponse to get at its data).\nclass MockThemeSource : public DOMUIThemeSource {\n public:\n explicit MockThemeSource(Profile* profile) : DOMUIThemeSource(profile) { }\n\n virtual void SendResponse(int request_id, RefCountedBytes* data) {\n result_data_size_ = data ? data->data.size() : 0;\n result_request_id_ = request_id;\n }\n\n int result_request_id_;\n int result_data_size_;\n};\n\n\/\/ A mock profile\nclass MockProfile : public TestingProfile {\n public:\n ThemeProvider* GetThemeProvider() { return new BrowserThemeProvider(); }\n};\n\n\nTEST(DOMUISources, ThemeSourceMimeTypes) {\n MockProfile* profile = new MockProfile();\n DOMUIThemeSource* theme_source = new DOMUIThemeSource(profile);\n\n EXPECT_EQ(theme_source->GetMimeType(\"css\/newtab.css\"), \"text\/css\");\n EXPECT_EQ(theme_source->GetMimeType(\"css\/newtab.css?foo\"), \"text\/css\");\n EXPECT_EQ(theme_source->GetMimeType(\"WRONGURL\"), \"image\/png\");\n}\n\nTEST(DOMUISources, ThemeSourceImages) {\n MockProfile* profile = new MockProfile();\n MockThemeSource* theme_source = new MockThemeSource(profile);\n\n \/\/ Our test data. Rather than comparing the data itself, we just compare\n \/\/ its size.\n ThemeProvider* tp = profile->GetThemeProvider();\n SkBitmap* image = tp->GetBitmapNamed(IDR_THEME_FRAME);\n std::vector<unsigned char> png_bytes;\n PNGEncoder::EncodeBGRASkBitmap(*image, false, &png_bytes);\n\n theme_source->StartDataRequest(\"theme_frame\", 1);\n EXPECT_EQ(theme_source->result_request_id_, 1);\n EXPECT_EQ(theme_source->result_data_size_, png_bytes.size());\n\n theme_source->StartDataRequest(\"theme_toolbar\", 2);\n EXPECT_EQ(theme_source->result_request_id_, 2);\n EXPECT_NE(theme_source->result_data_size_, png_bytes.size());\n}\n\nTEST(DOMUISources, ThemeSourceCSS) {\n MockProfile* profile = new MockProfile();\n MockThemeSource* theme_source = new MockThemeSource(profile);\n\n \/\/ Generating the test data for the NTP CSS would just involve copying the\n \/\/ method, or being super brittle and hard-coding the result (requiring\n \/\/ an update to the unittest every time the CSS template changes), so we\n \/\/ just check for a successful request and data that is non-null.\n theme_source->StartDataRequest(\"css\/newtab.css\", 1);\n EXPECT_EQ(theme_source->result_request_id_, 1);\n EXPECT_NE(theme_source->result_data_size_, 0);\n\n theme_source->StartDataRequest(\"css\/newtab.css?pie\", 3);\n EXPECT_EQ(theme_source->result_request_id_, 3);\n EXPECT_NE(theme_source->result_data_size_, 0);\n\n \/\/ Check that we send NULL back when we can't find what we're looking for.\n theme_source->StartDataRequest(\"css\/WRONGURL\", 7);\n EXPECT_EQ(theme_source->result_request_id_, 7);\n EXPECT_EQ(theme_source->result_data_size_, 0);\n}\n<commit_msg>Fix mac builder. int comparison.<commit_after>\/\/ 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 \"base\/gfx\/png_encoder.h\"\n#include \"chrome\/browser\/browser_theme_provider.h\"\n#include \"chrome\/browser\/dom_ui\/dom_ui_theme_source.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/testing_profile.h\"\n#include \"grit\/theme_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ A mock ThemeSource (so we can override SendResponse to get at its data).\nclass MockThemeSource : public DOMUIThemeSource {\n public:\n explicit MockThemeSource(Profile* profile) : DOMUIThemeSource(profile) { }\n\n virtual void SendResponse(int request_id, RefCountedBytes* data) {\n result_data_size_ = data ? data->data.size() : 0;\n result_request_id_ = request_id;\n }\n\n int result_request_id_;\n unsigned int result_data_size_;\n};\n\n\/\/ A mock profile\nclass MockProfile : public TestingProfile {\n public:\n ThemeProvider* GetThemeProvider() { return new BrowserThemeProvider(); }\n};\n\n\nTEST(DOMUISources, ThemeSourceMimeTypes) {\n MockProfile* profile = new MockProfile();\n DOMUIThemeSource* theme_source = new DOMUIThemeSource(profile);\n\n EXPECT_EQ(theme_source->GetMimeType(\"css\/newtab.css\"), \"text\/css\");\n EXPECT_EQ(theme_source->GetMimeType(\"css\/newtab.css?foo\"), \"text\/css\");\n EXPECT_EQ(theme_source->GetMimeType(\"WRONGURL\"), \"image\/png\");\n}\n\nTEST(DOMUISources, ThemeSourceImages) {\n MockProfile* profile = new MockProfile();\n MockThemeSource* theme_source = new MockThemeSource(profile);\n\n \/\/ Our test data. Rather than comparing the data itself, we just compare\n \/\/ its size.\n ThemeProvider* tp = profile->GetThemeProvider();\n SkBitmap* image = tp->GetBitmapNamed(IDR_THEME_FRAME);\n std::vector<unsigned char> png_bytes;\n PNGEncoder::EncodeBGRASkBitmap(*image, false, &png_bytes);\n\n theme_source->StartDataRequest(\"theme_frame\", 1);\n EXPECT_EQ(theme_source->result_request_id_, 1);\n EXPECT_EQ(theme_source->result_data_size_, png_bytes.size());\n\n theme_source->StartDataRequest(\"theme_toolbar\", 2);\n EXPECT_EQ(theme_source->result_request_id_, 2);\n EXPECT_NE(theme_source->result_data_size_, png_bytes.size());\n}\n\nTEST(DOMUISources, ThemeSourceCSS) {\n MockProfile* profile = new MockProfile();\n MockThemeSource* theme_source = new MockThemeSource(profile);\n\n \/\/ Generating the test data for the NTP CSS would just involve copying the\n \/\/ method, or being super brittle and hard-coding the result (requiring\n \/\/ an update to the unittest every time the CSS template changes), so we\n \/\/ just check for a successful request and data that is non-null.\n theme_source->StartDataRequest(\"css\/newtab.css\", 1);\n EXPECT_EQ(theme_source->result_request_id_, 1);\n EXPECT_NE(theme_source->result_data_size_, 0);\n\n theme_source->StartDataRequest(\"css\/newtab.css?pie\", 3);\n EXPECT_EQ(theme_source->result_request_id_, 3);\n EXPECT_NE(theme_source->result_data_size_, 0);\n\n \/\/ Check that we send NULL back when we can't find what we're looking for.\n theme_source->StartDataRequest(\"css\/WRONGURL\", 7);\n EXPECT_EQ(theme_source->result_request_id_, 7);\n EXPECT_EQ(theme_source->result_data_size_, 0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"base\/command_line.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_WindowOpen) {\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ResultCatcher catcher;\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"window_open\").AppendASCII(\"spanning\")));\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nvoid WaitForTabsAndPopups(Browser* browser, int num_tabs, int num_popups) {\n \/\/ We start with one tab and one browser already open.\n ++num_tabs;\n size_t num_browsers = static_cast<size_t>(num_popups) + 1;\n\n while (true) {\n if (BrowserList::GetBrowserCount(browser->profile()) < num_browsers ||\n browser->tab_count() < num_tabs) {\n MessageLoopForUI::current()->RunAllPending();\n continue;\n }\n\n ASSERT_EQ(num_browsers, BrowserList::GetBrowserCount(browser->profile()));\n ASSERT_EQ(num_tabs, browser->tab_count());\n\n for (BrowserList::const_iterator iter = BrowserList::begin();\n iter != BrowserList::end(); ++iter) {\n if (*iter == browser)\n continue;\n\n \/\/ Check for TYPE_POPUP or TYPE_APP_POPUP\/PANEL.\n ASSERT_TRUE((*iter)->type() & Browser::TYPE_POPUP);\n }\n\n break;\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupBlockingExtension) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"window_open\").AppendASCII(\"popup_blocking\")\n .AppendASCII(\"extension\")));\n\n WaitForTabsAndPopups(browser(), 5, 3);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupBlockingHostedApp) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"window_open\").AppendASCII(\"popup_blocking\")\n .AppendASCII(\"hosted_app\")));\n\n \/\/ The app being tested owns the domain a.com . The test URLs we navigate\n \/\/ to below must be within that domain, so that they fall within the app's\n \/\/ web extent.\n GURL::Replacements replace_host;\n std::string a_dot_com = \"a.com\";\n replace_host.SetHostStr(a_dot_com);\n\n const std::string popup_app_contents_path(\n \"files\/extensions\/api_test\/window_open\/popup_blocking\/hosted_app\/\");\n\n GURL open_tab =\n test_server()->GetURL(popup_app_contents_path + \"open_tab.html\")\n .ReplaceComponents(replace_host);\n GURL open_popup =\n test_server()->GetURL(popup_app_contents_path + \"open_popup.html\")\n .ReplaceComponents(replace_host);\n\n browser()->OpenURL(open_tab, GURL(), NEW_FOREGROUND_TAB,\n PageTransition::TYPED);\n browser()->OpenURL(open_popup, GURL(), NEW_FOREGROUND_TAB,\n PageTransition::TYPED);\n\n WaitForTabsAndPopups(browser(), 3, 1);\n}\n<commit_msg>Disable ExtensionApiTest.WindowOpen on mac because it never works.<commit_after>\/\/ Copyright (c) 2010 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 \"base\/command_line.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\n\/\/ crbug.com\/60156\n#if defined(OS_MACOSX)\n\/\/ On mac, this test basically never succeeds.\n#define FLAKY_WindowOpen DISABLED_WindowOpen\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_WindowOpen) {\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ResultCatcher catcher;\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"window_open\").AppendASCII(\"spanning\")));\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nvoid WaitForTabsAndPopups(Browser* browser, int num_tabs, int num_popups) {\n \/\/ We start with one tab and one browser already open.\n ++num_tabs;\n size_t num_browsers = static_cast<size_t>(num_popups) + 1;\n\n while (true) {\n if (BrowserList::GetBrowserCount(browser->profile()) < num_browsers ||\n browser->tab_count() < num_tabs) {\n MessageLoopForUI::current()->RunAllPending();\n continue;\n }\n\n ASSERT_EQ(num_browsers, BrowserList::GetBrowserCount(browser->profile()));\n ASSERT_EQ(num_tabs, browser->tab_count());\n\n for (BrowserList::const_iterator iter = BrowserList::begin();\n iter != BrowserList::end(); ++iter) {\n if (*iter == browser)\n continue;\n\n \/\/ Check for TYPE_POPUP or TYPE_APP_POPUP\/PANEL.\n ASSERT_TRUE((*iter)->type() & Browser::TYPE_POPUP);\n }\n\n break;\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupBlockingExtension) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"window_open\").AppendASCII(\"popup_blocking\")\n .AppendASCII(\"extension\")));\n\n WaitForTabsAndPopups(browser(), 5, 3);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupBlockingHostedApp) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"window_open\").AppendASCII(\"popup_blocking\")\n .AppendASCII(\"hosted_app\")));\n\n \/\/ The app being tested owns the domain a.com . The test URLs we navigate\n \/\/ to below must be within that domain, so that they fall within the app's\n \/\/ web extent.\n GURL::Replacements replace_host;\n std::string a_dot_com = \"a.com\";\n replace_host.SetHostStr(a_dot_com);\n\n const std::string popup_app_contents_path(\n \"files\/extensions\/api_test\/window_open\/popup_blocking\/hosted_app\/\");\n\n GURL open_tab =\n test_server()->GetURL(popup_app_contents_path + \"open_tab.html\")\n .ReplaceComponents(replace_host);\n GURL open_popup =\n test_server()->GetURL(popup_app_contents_path + \"open_popup.html\")\n .ReplaceComponents(replace_host);\n\n browser()->OpenURL(open_tab, GURL(), NEW_FOREGROUND_TAB,\n PageTransition::TYPED);\n browser()->OpenURL(open_popup, GURL(), NEW_FOREGROUND_TAB,\n PageTransition::TYPED);\n\n WaitForTabsAndPopups(browser(), 3, 1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 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\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/find_in_page_controller.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nclass FindInPageControllerTest : public UITest {\n public:\n FindInPageControllerTest() {\n show_window_ = true;\n }\n};\n\nconst std::wstring kFramePage = L\"files\/find_in_page\/frames.html\";\nconst std::wstring kUserSelectPage = L\"files\/find_in_page\/user-select.html\";\nconst std::wstring kCrashPage = L\"files\/find_in_page\/crash_1341577.html\";\nconst std::wstring kTooFewMatchesPage = L\"files\/find_in_page\/bug_1155639.html\";\n\n\/\/ This test loads a page with frames and starts FindInPage requests\nTEST_F(FindInPageControllerTest, FindInPageFrames) {\n TestServer server(L\"chrome\/test\/data\");\n\n \/\/ First we navigate to our frames page.\n GURL url = server.TestServerPageW(kFramePage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ Try incremental search (mimicking user typing in).\n EXPECT_EQ(18, tab->FindInPage(L\"g\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(11, tab->FindInPage(L\"go\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(04, tab->FindInPage(L\"goo\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(03, tab->FindInPage(L\"goog\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(02, tab->FindInPage(L\"googl\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(01, tab->FindInPage(L\"google\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(00, tab->FindInPage(L\"google!\", FWD, IGNORE_CASE, false));\n\n \/\/ Negative test (no matches should be found).\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n\n \/\/ 'horse' only exists in the three right frames.\n EXPECT_EQ(3, tab->FindInPage(L\"horse\", FWD, IGNORE_CASE, false));\n\n \/\/ 'cat' only exists in the first frame.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching again, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching backwards, ignoring case, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"CAT\", BACK, IGNORE_CASE, false));\n\n \/\/ Try case sensitive, should NOT find it.\n EXPECT_EQ(0, tab->FindInPage(L\"CAT\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try again case sensitive, but this time with right case.\n EXPECT_EQ(1, tab->FindInPage(L\"dog\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try non-Latin characters ('Hreggvidur' with 'eth' for 'd' in left frame).\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n}\n\n\/\/ Load a page with no selectable text and make sure we don't crash.\nTEST_F(FindInPageControllerTest, FindUnSelectableText) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kUserSelectPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_EQ(0, tab->FindInPage(L\"text\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n}\n\n\/\/ Try to reproduce the crash seen in issue 1341577.\nTEST_F(FindInPageControllerTest, FindCrash_Issue1341577) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kCrashPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This would crash the tab. These must be the first two find requests issued\n \/\/ against the frame, otherwise an active frame pointer is set and it wont\n \/\/ produce the crash.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, false));\n \/\/ FindNext returns -1 for match count because it doesn't bother with\n \/\/ recounting the number of matches. We don't care about the match count\n \/\/ anyway in this case, we just want to make sure it doesn't crash.\n EXPECT_EQ(-1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, true));\n\n \/\/ This should work fine.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D24\\u0D46\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"nostring\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ Test to make sure Find does the right thing when restarting from a timeout.\n\/\/ We used to have a problem where we'd stop finding matches when all of the\n\/\/ following conditions were true:\n\/\/ 1) The page has a lot of text to search.\n\/\/ 2) The page contains more than one match.\n\/\/ 3) It takes longer than the time-slice given to each Find operation (100\n\/\/ ms) to find one or more of those matches (so Find times out and has to try\n\/\/ again from where it left off).\nTEST_F(FindInPageControllerTest, FindEnoughMatches_Issue1155639) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kTooFewMatchesPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This string appears 5 times at the bottom of a long page. If Find restarts\n \/\/ properly after a timeout, it will find 5 matches, not just 1.\n EXPECT_EQ(5, tab->FindInPage(L\"008.xml\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ The find window should not change its location just because we open and close\n\/\/ a new tab.\nTEST_F(FindInPageControllerTest, FindMovesOnTabClose_Issue1343052) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kFramePage);\n scoped_ptr<TabProxy> tabA(GetActiveTab());\n ASSERT_TRUE(tabA->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get() != NULL);\n\n \/\/ Toggle the bookmark bar state.\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), true));\n\n \/\/ Open the Find window and wait for it to animate.\n EXPECT_TRUE(tabA->OpenFindInPage());\n EXPECT_TRUE(WaitForFindWindowFullyVisible(tabA.get()));\n\n \/\/ Find its location.\n int x = -1, y = -1;\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab B).\n EXPECT_TRUE(browser->AppendTab(url));\n scoped_ptr<TabProxy> tabB(GetActiveTab());\n\n \/\/ Close tab B.\n EXPECT_TRUE(tabB->Close(true));\n\n \/\/ See if the Find window has moved.\n int new_x = -1, new_y = -1;\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n\n \/\/ Now reset the bookmarks bar state and try the same again.\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), false));\n\n \/\/ Bookmark bar has moved, reset our coordinates.\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab C).\n EXPECT_TRUE(browser->AppendTab(url));\n scoped_ptr<TabProxy> tabC(GetActiveTab());\n\n \/\/ Close it.\n EXPECT_TRUE(tabC->Close(true));\n\n \/\/ See if the Find window has moved.\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n}\n<commit_msg>Add some trace statements in an attempt to find the reason why a Find test is flaky. This will be removed once I get a run that hangs again.<commit_after>\/\/ Copyright (c) 2006-2008 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\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/find_in_page_controller.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nclass FindInPageControllerTest : public UITest {\n public:\n FindInPageControllerTest() {\n show_window_ = true;\n }\n};\n\nconst std::wstring kFramePage = L\"files\/find_in_page\/frames.html\";\nconst std::wstring kUserSelectPage = L\"files\/find_in_page\/user-select.html\";\nconst std::wstring kCrashPage = L\"files\/find_in_page\/crash_1341577.html\";\nconst std::wstring kTooFewMatchesPage = L\"files\/find_in_page\/bug_1155639.html\";\n\n\/\/ This test loads a page with frames and starts FindInPage requests\nTEST_F(FindInPageControllerTest, FindInPageFrames) {\n TestServer server(L\"chrome\/test\/data\");\n\n \/\/ First we navigate to our frames page.\n GURL url = server.TestServerPageW(kFramePage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ Try incremental search (mimicking user typing in).\n EXPECT_EQ(18, tab->FindInPage(L\"g\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(11, tab->FindInPage(L\"go\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(04, tab->FindInPage(L\"goo\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(03, tab->FindInPage(L\"goog\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(02, tab->FindInPage(L\"googl\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(01, tab->FindInPage(L\"google\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(00, tab->FindInPage(L\"google!\", FWD, IGNORE_CASE, false));\n\n \/\/ Negative test (no matches should be found).\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n\n \/\/ 'horse' only exists in the three right frames.\n EXPECT_EQ(3, tab->FindInPage(L\"horse\", FWD, IGNORE_CASE, false));\n\n \/\/ 'cat' only exists in the first frame.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching again, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching backwards, ignoring case, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"CAT\", BACK, IGNORE_CASE, false));\n\n \/\/ Try case sensitive, should NOT find it.\n EXPECT_EQ(0, tab->FindInPage(L\"CAT\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try again case sensitive, but this time with right case.\n EXPECT_EQ(1, tab->FindInPage(L\"dog\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try non-Latin characters ('Hreggvidur' with 'eth' for 'd' in left frame).\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n}\n\n\/\/ Load a page with no selectable text and make sure we don't crash.\nTEST_F(FindInPageControllerTest, FindUnSelectableText) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kUserSelectPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_EQ(0, tab->FindInPage(L\"text\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n}\n\n\/\/ Try to reproduce the crash seen in issue 1341577.\nTEST_F(FindInPageControllerTest, FindCrash_Issue1341577) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kCrashPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This would crash the tab. These must be the first two find requests issued\n \/\/ against the frame, otherwise an active frame pointer is set and it wont\n \/\/ produce the crash.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, false));\n \/\/ FindNext returns -1 for match count because it doesn't bother with\n \/\/ recounting the number of matches. We don't care about the match count\n \/\/ anyway in this case, we just want to make sure it doesn't crash.\n EXPECT_EQ(-1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, true));\n\n \/\/ This should work fine.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D24\\u0D46\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"nostring\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ Test to make sure Find does the right thing when restarting from a timeout.\n\/\/ We used to have a problem where we'd stop finding matches when all of the\n\/\/ following conditions were true:\n\/\/ 1) The page has a lot of text to search.\n\/\/ 2) The page contains more than one match.\n\/\/ 3) It takes longer than the time-slice given to each Find operation (100\n\/\/ ms) to find one or more of those matches (so Find times out and has to try\n\/\/ again from where it left off).\nTEST_F(FindInPageControllerTest, FindEnoughMatches_Issue1155639) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kTooFewMatchesPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This string appears 5 times at the bottom of a long page. If Find restarts\n \/\/ properly after a timeout, it will find 5 matches, not just 1.\n EXPECT_EQ(5, tab->FindInPage(L\"008.xml\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ The find window should not change its location just because we open and close\n\/\/ a new tab.\nTEST_F(FindInPageControllerTest, FindMovesOnTabClose_Issue1343052) {\n fprintf(stderr, \"Starting FindMovesOnTabClose_Issue1343052\\n\");\n TestServer server(L\"chrome\/test\/data\");\n\n fprintf(stderr, \"TestServerPageW\\n\");\n GURL url = server.TestServerPageW(kFramePage);\n fprintf(stderr, \"GetActiveTab A\\n\");\n scoped_ptr<TabProxy> tabA(GetActiveTab());\n fprintf(stderr, \"Navigate A\\n\");\n ASSERT_TRUE(tabA->NavigateToURL(url));\n fprintf(stderr, \"WaitUntilTabCount(1) for A\\n\");\n WaitUntilTabCount(1);\n\n fprintf(stderr, \"GetBrowserWindow(0)\\n\");\n scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get() != NULL);\n\n \/\/ Toggle the bookmark bar state.\n fprintf(stderr, \"ApplyAccelerator bookmark bar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkVisibility\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), true));\n\n \/\/ Open the Find window and wait for it to animate.\n fprintf(stderr, \"OpenFindInPage in A\\n\");\n EXPECT_TRUE(tabA->OpenFindInPage());\n fprintf(stderr, \"WaitForWindowFullyVisible in A\\n\");\n EXPECT_TRUE(WaitForFindWindowFullyVisible(tabA.get()));\n\n \/\/ Find its location.\n int x = -1, y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab B).\n fprintf(stderr, \"AppendTab B\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab B\\n\");\n scoped_ptr<TabProxy> tabB(GetActiveTab());\n\n \/\/ Close tab B.\n fprintf(stderr, \"Tab Close B\\n\");\n EXPECT_TRUE(tabB->Close(true));\n\n \/\/ See if the Find window has moved.\n int new_x = -1, new_y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n\n \/\/ Now reset the bookmarks bar state and try the same again.\n fprintf(stderr, \"ApplyAccelerator BookmarksBar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkBarVisibilityChange\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), false));\n\n \/\/ Bookmark bar has moved, reset our coordinates.\n fprintf(stderr, \"GetFindWindowLocation again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab C).\n fprintf(stderr, \"Append tab C\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab C\\n\");\n scoped_ptr<TabProxy> tabC(GetActiveTab());\n\n \/\/ Close it.\n fprintf(stderr, \"Close tab C\\n\");\n EXPECT_TRUE(tabC->Close(true));\n\n \/\/ See if the Find window has moved.\n fprintf(stderr, \"GetFindWindowLocation yet again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n fprintf(stderr, \"Done!\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 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\/\/ Tests the MetricsService stat recording to make sure that the numbers are\n\/\/ what we expect.\n\n#include <string>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/platform_thread.h\"\n#include \"base\/process_util.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n\nclass MetricsServiceTest : public UITest {\n public:\n MetricsServiceTest() : UITest() {\n \/\/ We need to show the window so web content type tabs load.\n show_window_ = true;\n }\n\n \/\/ Open a few tabs of random content\n void OpenTabs() {\n scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);\n ASSERT_TRUE(window.get());\n\n FilePath page1_path;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page1_path));\n page1_path = page1_path.AppendASCII(\"title2.html\");\n ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page1_path)));\n\n FilePath page2_path;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page2_path));\n page2_path = page2_path.AppendASCII(\"iframe.html\");\n ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page2_path)));\n }\n\n \/\/ Get a PrefService whose contents correspond to the Local State file\n \/\/ that was saved by the app as it closed. The caller takes ownership of the\n \/\/ returned PrefService object.\n PrefService* GetLocalState() {\n FilePath local_state_path = user_data_dir()\n .Append(chrome::kLocalStateFilename);\n\n return new PrefService(local_state_path);\n }\n};\n\nTEST_F(MetricsServiceTest, CloseRenderersNormally) {\n OpenTabs();\n QuitBrowser();\n\n scoped_ptr<PrefService> local_state(GetLocalState());\n local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);\n local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);\n local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);\n local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);\n EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));\n EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));\n EXPECT_EQ(3, local_state->GetInteger(prefs::kStabilityPageLoadCount));\n EXPECT_EQ(0, local_state->GetInteger(prefs::kStabilityRendererCrashCount));\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/32048\n#define CrashRenderers FLAKY_CrashRenders\n#endif\nTEST_F(MetricsServiceTest, CrashRenderers) {\n \/\/ This doesn't make sense to test in single process mode.\n if (in_process_renderer_)\n return;\n\n OpenTabs();\n\n {\n \/\/ Limit the lifetime of various automation proxies used here. We must\n \/\/ destroy them before calling QuitBrowser.\n\n scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);\n ASSERT_TRUE(window.get());\n\n \/\/ Kill the process for one of the tabs.\n scoped_refptr<TabProxy> tab(window->GetTab(1));\n ASSERT_TRUE(tab.get());\n\n\/\/ Only windows implements the crash service for now.\n#if defined(OS_WIN)\n expected_crashes_ = 1;\n#endif\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"about:crash\")));\n }\n\n \/\/ Give the browser a chance to notice the crashed tab.\n PlatformThread::Sleep(1000);\n\n QuitBrowser();\n\n scoped_ptr<PrefService> local_state(GetLocalState());\n local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);\n local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);\n local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);\n local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);\n EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));\n EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));\n EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));\n EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityRendererCrashCount));\n}\n<commit_msg>Linux: Fix test crash expectations for MetricsServiceTest.CrashRenderers.<commit_after>\/\/ Copyright (c) 2006-2008 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\/\/ Tests the MetricsService stat recording to make sure that the numbers are\n\/\/ what we expect.\n\n#include <string>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/platform_thread.h\"\n#include \"base\/process_util.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n\nclass MetricsServiceTest : public UITest {\n public:\n MetricsServiceTest() : UITest() {\n \/\/ We need to show the window so web content type tabs load.\n show_window_ = true;\n }\n\n \/\/ Open a few tabs of random content\n void OpenTabs() {\n scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);\n ASSERT_TRUE(window.get());\n\n FilePath page1_path;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page1_path));\n page1_path = page1_path.AppendASCII(\"title2.html\");\n ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page1_path)));\n\n FilePath page2_path;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page2_path));\n page2_path = page2_path.AppendASCII(\"iframe.html\");\n ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page2_path)));\n }\n\n \/\/ Get a PrefService whose contents correspond to the Local State file\n \/\/ that was saved by the app as it closed. The caller takes ownership of the\n \/\/ returned PrefService object.\n PrefService* GetLocalState() {\n FilePath local_state_path = user_data_dir()\n .Append(chrome::kLocalStateFilename);\n\n return new PrefService(local_state_path);\n }\n};\n\nTEST_F(MetricsServiceTest, CloseRenderersNormally) {\n OpenTabs();\n QuitBrowser();\n\n scoped_ptr<PrefService> local_state(GetLocalState());\n local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);\n local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);\n local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);\n local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);\n EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));\n EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));\n EXPECT_EQ(3, local_state->GetInteger(prefs::kStabilityPageLoadCount));\n EXPECT_EQ(0, local_state->GetInteger(prefs::kStabilityRendererCrashCount));\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/32048\n#define CrashRenderers FLAKY_CrashRenders\n#endif\nTEST_F(MetricsServiceTest, CrashRenderers) {\n \/\/ This doesn't make sense to test in single process mode.\n if (in_process_renderer_)\n return;\n\n OpenTabs();\n\n {\n \/\/ Limit the lifetime of various automation proxies used here. We must\n \/\/ destroy them before calling QuitBrowser.\n\n scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);\n ASSERT_TRUE(window.get());\n\n \/\/ Kill the process for one of the tabs.\n scoped_refptr<TabProxy> tab(window->GetTab(1));\n ASSERT_TRUE(tab.get());\n\n\/\/ We should get a crash dump on Windows.\n\/\/ Also on Linux with Breakpad enabled.\n#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD)\n expected_crashes_ = 1;\n#endif\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"about:crash\")));\n }\n\n \/\/ Give the browser a chance to notice the crashed tab.\n PlatformThread::Sleep(1000);\n\n QuitBrowser();\n\n scoped_ptr<PrefService> local_state(GetLocalState());\n local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);\n local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);\n local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);\n local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);\n EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));\n EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));\n EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));\n EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityRendererCrashCount));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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\/browser\/ssl_client_certificate_selector.h\"\n\n#include <gtk\/gtk.h>\n\n#include <string>\n#include <vector>\n\n#include \"app\/gtk_signal.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/i18n\/time_formatting.h\"\n#include \"base\/logging.h\"\n#include \"base\/nss_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/certificate_viewer.h\"\n#include \"chrome\/browser\/gtk\/constrained_window_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/gtk\/owned_widget_gtk.h\"\n#include \"chrome\/browser\/ssl\/ssl_client_auth_handler.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/net\/x509_certificate_model.h\"\n#include \"gfx\/native_widget_types.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/x509_certificate.h\"\n\nnamespace {\n\nenum {\n RESPONSE_SHOW_CERT_INFO = 1,\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SSLClientCertificateSelector\n\nclass SSLClientCertificateSelector : public ConstrainedDialogDelegate {\n public:\n explicit SSLClientCertificateSelector(\n TabContents* parent,\n net::SSLCertRequestInfo* cert_request_info,\n SSLClientAuthHandler* delegate);\n ~SSLClientCertificateSelector();\n\n void Show();\n\n \/\/ ConstrainedDialogDelegate implementation:\n virtual GtkWidget* GetWidgetRoot() { return root_widget_.get(); }\n virtual void DeleteDelegate() { delete this; }\n\n private:\n void PopulateCerts();\n\n net::X509Certificate* GetSelectedCert();\n\n static std::string FormatComboBoxText(\n net::X509Certificate::OSCertHandle cert,\n const std::string& nickname);\n static std::string FormatDetailsText(\n net::X509Certificate::OSCertHandle cert);\n\n CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnComboBoxChanged);\n CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnViewClicked);\n CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnCancelClicked);\n CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnOkClicked);\n CHROMEGTK_CALLBACK_1(SSLClientCertificateSelector, void, OnPromptShown,\n GtkWidget*);\n\n scoped_refptr<net::SSLCertRequestInfo> cert_request_info_;\n\n std::vector<std::string> details_strings_;\n\n GtkWidget* cert_combo_box_;\n GtkTextBuffer* cert_details_buffer_;\n\n scoped_refptr<SSLClientAuthHandler> delegate_;\n\n OwnedWidgetGtk root_widget_;\n \/\/ Hold on to the select button to focus it.\n GtkWidget* select_button_;\n\n TabContents* parent_;\n ConstrainedWindow* window_;\n\n DISALLOW_COPY_AND_ASSIGN(SSLClientCertificateSelector);\n};\n\nSSLClientCertificateSelector::SSLClientCertificateSelector(\n TabContents* parent,\n net::SSLCertRequestInfo* cert_request_info,\n SSLClientAuthHandler* delegate)\n : cert_request_info_(cert_request_info),\n delegate_(delegate),\n parent_(parent),\n window_(NULL) {\n root_widget_.Own(gtk_vbox_new(FALSE, gtk_util::kControlSpacing));\n\n GtkWidget* site_vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_box_pack_start(GTK_BOX(root_widget_.get()), site_vbox,\n FALSE, FALSE, 0);\n\n GtkWidget* site_description_label = gtk_util::CreateBoldLabel(\n l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_SITE_DESCRIPTION_LABEL));\n gtk_box_pack_start(GTK_BOX(site_vbox), site_description_label,\n FALSE, FALSE, 0);\n\n GtkWidget* site_label = gtk_label_new(\n cert_request_info->host_and_port.c_str());\n gtk_util::LeftAlignMisc(site_label);\n gtk_box_pack_start(GTK_BOX(site_vbox), site_label, FALSE, FALSE, 0);\n\n GtkWidget* selector_vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_box_pack_start(GTK_BOX(root_widget_.get()), selector_vbox,\n TRUE, TRUE, 0);\n\n GtkWidget* choose_description_label = gtk_util::CreateBoldLabel(\n l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CHOOSE_DESCRIPTION_LABEL));\n gtk_box_pack_start(GTK_BOX(selector_vbox), choose_description_label,\n FALSE, FALSE, 0);\n\n\n cert_combo_box_ = gtk_combo_box_new_text();\n g_signal_connect(cert_combo_box_, \"changed\",\n G_CALLBACK(OnComboBoxChangedThunk), this);\n gtk_box_pack_start(GTK_BOX(selector_vbox), cert_combo_box_,\n FALSE, FALSE, 0);\n\n GtkWidget* details_label = gtk_label_new(l10n_util::GetStringUTF8(\n IDS_CERT_SELECTOR_DETAILS_DESCRIPTION_LABEL).c_str());\n gtk_util::LeftAlignMisc(details_label);\n gtk_box_pack_start(GTK_BOX(selector_vbox), details_label, FALSE, FALSE, 0);\n\n \/\/ TODO(mattm): fix text view coloring (should have grey background).\n GtkWidget* cert_details_view = gtk_text_view_new();\n gtk_text_view_set_editable(GTK_TEXT_VIEW(cert_details_view), FALSE);\n gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(cert_details_view), GTK_WRAP_WORD);\n cert_details_buffer_ = gtk_text_view_get_buffer(\n GTK_TEXT_VIEW(cert_details_view));\n \/\/ We put the details in a frame instead of a scrolled window so that the\n \/\/ entirety will be visible without requiring scrolling or expanding the\n \/\/ dialog. This does however mean the dialog will grow itself if you switch\n \/\/ to different cert that has longer details text.\n GtkWidget* details_frame = gtk_frame_new(NULL);\n gtk_frame_set_shadow_type(GTK_FRAME(details_frame), GTK_SHADOW_ETCHED_IN);\n gtk_container_add(GTK_CONTAINER(details_frame), cert_details_view);\n gtk_box_pack_start(GTK_BOX(selector_vbox), details_frame, TRUE, TRUE, 0);\n\n \/\/ And then create a set of buttons like a GtkDialog would.\n GtkWidget* button_box = gtk_hbutton_box_new();\n gtk_button_box_set_layout(GTK_BUTTON_BOX(button_box), GTK_BUTTONBOX_END);\n gtk_box_set_spacing(GTK_BOX(button_box), gtk_util::kControlSpacing);\n gtk_box_pack_end(GTK_BOX(root_widget_.get()), button_box, FALSE, FALSE, 0);\n\n GtkWidget* view_button = gtk_button_new_with_mnemonic(\n l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str());\n gtk_box_pack_start(GTK_BOX(button_box), view_button, FALSE, FALSE, 0);\n g_signal_connect(view_button, \"clicked\",\n G_CALLBACK(OnViewClickedThunk), this);\n\n GtkWidget* cancel_button = gtk_button_new_from_stock(GTK_STOCK_CANCEL);\n gtk_box_pack_end(GTK_BOX(button_box), cancel_button, FALSE, FALSE, 0);\n g_signal_connect(cancel_button, \"clicked\",\n G_CALLBACK(OnCancelClickedThunk), this);\n\n GtkWidget* select_button = gtk_button_new_from_stock(GTK_STOCK_OK);\n gtk_box_pack_end(GTK_BOX(button_box), select_button, FALSE, FALSE, 0);\n g_signal_connect(select_button, \"clicked\",\n G_CALLBACK(OnOkClickedThunk), this);\n\n \/\/ When we are attached to a window, focus the select button.\n select_button_ = select_button;\n g_signal_connect(root_widget_.get(), \"hierarchy-changed\",\n G_CALLBACK(OnPromptShownThunk), this);\n PopulateCerts();\n\n gtk_widget_show_all(root_widget_.get());\n}\n\nSSLClientCertificateSelector::~SSLClientCertificateSelector() {\n root_widget_.Destroy();\n}\n\nvoid SSLClientCertificateSelector::Show() {\n DCHECK(!window_);\n window_ = parent_->CreateConstrainedDialog(this);\n}\n\nvoid SSLClientCertificateSelector::PopulateCerts() {\n std::vector<std::string> nicknames;\n x509_certificate_model::GetNicknameStringsFromCertList(\n cert_request_info_->client_certs,\n l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CERT_EXPIRED),\n l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CERT_NOT_YET_VALID),\n &nicknames);\n\n DCHECK_EQ(nicknames.size(),\n cert_request_info_->client_certs.size());\n\n for (size_t i = 0; i < cert_request_info_->client_certs.size(); ++i) {\n net::X509Certificate::OSCertHandle cert =\n cert_request_info_->client_certs[i]->os_cert_handle();\n\n details_strings_.push_back(FormatDetailsText(cert));\n\n gtk_combo_box_append_text(\n GTK_COMBO_BOX(cert_combo_box_),\n FormatComboBoxText(cert, nicknames[i]).c_str());\n }\n\n \/\/ Auto-select the first cert.\n gtk_combo_box_set_active(GTK_COMBO_BOX(cert_combo_box_), 0);\n}\n\nnet::X509Certificate* SSLClientCertificateSelector::GetSelectedCert() {\n int selected = gtk_combo_box_get_active(GTK_COMBO_BOX(cert_combo_box_));\n if (selected >= 0 &&\n selected < static_cast<int>(\n cert_request_info_->client_certs.size()))\n return cert_request_info_->client_certs[selected];\n return NULL;\n}\n\n\/\/ static\nstd::string SSLClientCertificateSelector::FormatComboBoxText(\n net::X509Certificate::OSCertHandle cert, const std::string& nickname) {\n std::string rv(nickname);\n rv += \" [\";\n rv += x509_certificate_model::GetSerialNumberHexified(cert, \"\");\n rv += ']';\n return rv;\n}\n\n\/\/ static\nstd::string SSLClientCertificateSelector::FormatDetailsText(\n net::X509Certificate::OSCertHandle cert) {\n std::string rv;\n\n rv += l10n_util::GetStringFUTF8(\n IDS_CERT_SUBJECTNAME_FORMAT,\n UTF8ToUTF16(x509_certificate_model::GetSubjectName(cert)));;\n\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(\n IDS_CERT_SERIAL_NUMBER_FORMAT,\n UTF8ToUTF16(\n x509_certificate_model::GetSerialNumberHexified(cert, \"\")));\n\n base::Time issued, expires;\n if (x509_certificate_model::GetTimes(cert, &issued, &expires)) {\n string16 issued_str = WideToUTF16(\n base::TimeFormatShortDateAndTime(issued));\n string16 expires_str = WideToUTF16(\n base::TimeFormatShortDateAndTime(expires));\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(IDS_CERT_VALIDITY_RANGE_FORMAT,\n issued_str, expires_str);\n }\n\n std::vector<std::string> usages;\n x509_certificate_model::GetUsageStrings(cert, &usages);\n if (usages.size()) {\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(IDS_CERT_X509_EXTENDED_KEY_USAGE_FORMAT,\n UTF8ToUTF16(JoinString(usages, ',')));\n }\n\n std::string key_usage_str = x509_certificate_model::GetKeyUsageString(cert);\n if (!key_usage_str.empty()) {\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(IDS_CERT_X509_KEY_USAGE_FORMAT,\n UTF8ToUTF16(key_usage_str));\n }\n\n std::vector<std::string> email_addresses;\n x509_certificate_model::GetEmailAddresses(cert, &email_addresses);\n if (email_addresses.size()) {\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(\n IDS_CERT_EMAIL_ADDRESSES_FORMAT,\n UTF8ToUTF16(JoinString(email_addresses, ',')));\n }\n\n rv += '\\n';\n rv += l10n_util::GetStringFUTF8(\n IDS_CERT_ISSUERNAME_FORMAT,\n UTF8ToUTF16(x509_certificate_model::GetIssuerName(cert)));\n\n string16 token(UTF8ToUTF16(x509_certificate_model::GetTokenName(cert)));\n if (!token.empty()) {\n rv += '\\n';\n rv += l10n_util::GetStringFUTF8(IDS_CERT_TOKEN_FORMAT, token);\n }\n\n return rv;\n}\n\nvoid SSLClientCertificateSelector::OnComboBoxChanged(GtkWidget* combo_box) {\n int selected = gtk_combo_box_get_active(\n GTK_COMBO_BOX(cert_combo_box_));\n if (selected < 0)\n return;\n gtk_text_buffer_set_text(cert_details_buffer_,\n details_strings_[selected].c_str(),\n details_strings_[selected].size());\n}\n\nvoid SSLClientCertificateSelector::OnViewClicked(GtkWidget* button) {\n net::X509Certificate* cert = GetSelectedCert();\n if (cert) {\n GtkWidget* toplevel = gtk_widget_get_toplevel(root_widget_.get());\n ShowCertificateViewer(GTK_WINDOW(toplevel), cert);\n }\n}\n\nvoid SSLClientCertificateSelector::OnCancelClicked(GtkWidget* button) {\n delegate_->CertificateSelected(NULL);\n DCHECK(window_);\n window_->CloseConstrainedWindow();\n}\n\nvoid SSLClientCertificateSelector::OnOkClicked(GtkWidget* button) {\n net::X509Certificate* cert = GetSelectedCert();\n delegate_->CertificateSelected(cert);\n DCHECK(window_);\n window_->CloseConstrainedWindow();\n}\n\nvoid SSLClientCertificateSelector::OnPromptShown(GtkWidget* widget,\n GtkWidget* previous_toplevel) {\n if (!root_widget_.get() ||\n !GTK_WIDGET_TOPLEVEL(gtk_widget_get_toplevel(root_widget_.get())))\n return;\n GTK_WIDGET_SET_FLAGS(select_button_, GTK_CAN_DEFAULT);\n gtk_widget_grab_default(select_button_);\n gtk_widget_grab_focus(select_button_);\n}\n\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SSLClientAuthHandler platform specific implementation:\n\nnamespace browser {\n\nvoid ShowSSLClientCertificateSelector(\n TabContents* parent,\n net::SSLCertRequestInfo* cert_request_info,\n SSLClientAuthHandler* delegate) {\n (new SSLClientCertificateSelector(parent,\n cert_request_info,\n delegate))->Show();\n}\n\n} \/\/ namespace browser\n<commit_msg>Linux: Fix client certificate selection dialog handling of esc key.<commit_after>\/\/ Copyright (c) 2010 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\/browser\/ssl_client_certificate_selector.h\"\n\n#include <gtk\/gtk.h>\n\n#include <string>\n#include <vector>\n\n#include \"app\/gtk_signal.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/i18n\/time_formatting.h\"\n#include \"base\/logging.h\"\n#include \"base\/nss_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/certificate_viewer.h\"\n#include \"chrome\/browser\/gtk\/constrained_window_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/gtk\/owned_widget_gtk.h\"\n#include \"chrome\/browser\/ssl\/ssl_client_auth_handler.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/net\/x509_certificate_model.h\"\n#include \"gfx\/native_widget_types.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/x509_certificate.h\"\n\nnamespace {\n\nenum {\n RESPONSE_SHOW_CERT_INFO = 1,\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SSLClientCertificateSelector\n\nclass SSLClientCertificateSelector : public ConstrainedDialogDelegate {\n public:\n explicit SSLClientCertificateSelector(\n TabContents* parent,\n net::SSLCertRequestInfo* cert_request_info,\n SSLClientAuthHandler* delegate);\n ~SSLClientCertificateSelector();\n\n void Show();\n\n \/\/ ConstrainedDialogDelegate implementation:\n virtual GtkWidget* GetWidgetRoot() { return root_widget_.get(); }\n virtual void DeleteDelegate();\n\n private:\n void PopulateCerts();\n\n net::X509Certificate* GetSelectedCert();\n\n static std::string FormatComboBoxText(\n net::X509Certificate::OSCertHandle cert,\n const std::string& nickname);\n static std::string FormatDetailsText(\n net::X509Certificate::OSCertHandle cert);\n\n CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnComboBoxChanged);\n CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnViewClicked);\n CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnCancelClicked);\n CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnOkClicked);\n CHROMEGTK_CALLBACK_1(SSLClientCertificateSelector, void, OnPromptShown,\n GtkWidget*);\n\n scoped_refptr<net::SSLCertRequestInfo> cert_request_info_;\n\n std::vector<std::string> details_strings_;\n\n GtkWidget* cert_combo_box_;\n GtkTextBuffer* cert_details_buffer_;\n\n scoped_refptr<SSLClientAuthHandler> delegate_;\n\n OwnedWidgetGtk root_widget_;\n \/\/ Hold on to the select button to focus it.\n GtkWidget* select_button_;\n\n TabContents* parent_;\n ConstrainedWindow* window_;\n\n DISALLOW_COPY_AND_ASSIGN(SSLClientCertificateSelector);\n};\n\nSSLClientCertificateSelector::SSLClientCertificateSelector(\n TabContents* parent,\n net::SSLCertRequestInfo* cert_request_info,\n SSLClientAuthHandler* delegate)\n : cert_request_info_(cert_request_info),\n delegate_(delegate),\n parent_(parent),\n window_(NULL) {\n root_widget_.Own(gtk_vbox_new(FALSE, gtk_util::kControlSpacing));\n\n GtkWidget* site_vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_box_pack_start(GTK_BOX(root_widget_.get()), site_vbox,\n FALSE, FALSE, 0);\n\n GtkWidget* site_description_label = gtk_util::CreateBoldLabel(\n l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_SITE_DESCRIPTION_LABEL));\n gtk_box_pack_start(GTK_BOX(site_vbox), site_description_label,\n FALSE, FALSE, 0);\n\n GtkWidget* site_label = gtk_label_new(\n cert_request_info->host_and_port.c_str());\n gtk_util::LeftAlignMisc(site_label);\n gtk_box_pack_start(GTK_BOX(site_vbox), site_label, FALSE, FALSE, 0);\n\n GtkWidget* selector_vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_box_pack_start(GTK_BOX(root_widget_.get()), selector_vbox,\n TRUE, TRUE, 0);\n\n GtkWidget* choose_description_label = gtk_util::CreateBoldLabel(\n l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CHOOSE_DESCRIPTION_LABEL));\n gtk_box_pack_start(GTK_BOX(selector_vbox), choose_description_label,\n FALSE, FALSE, 0);\n\n\n cert_combo_box_ = gtk_combo_box_new_text();\n g_signal_connect(cert_combo_box_, \"changed\",\n G_CALLBACK(OnComboBoxChangedThunk), this);\n gtk_box_pack_start(GTK_BOX(selector_vbox), cert_combo_box_,\n FALSE, FALSE, 0);\n\n GtkWidget* details_label = gtk_label_new(l10n_util::GetStringUTF8(\n IDS_CERT_SELECTOR_DETAILS_DESCRIPTION_LABEL).c_str());\n gtk_util::LeftAlignMisc(details_label);\n gtk_box_pack_start(GTK_BOX(selector_vbox), details_label, FALSE, FALSE, 0);\n\n \/\/ TODO(mattm): fix text view coloring (should have grey background).\n GtkWidget* cert_details_view = gtk_text_view_new();\n gtk_text_view_set_editable(GTK_TEXT_VIEW(cert_details_view), FALSE);\n gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(cert_details_view), GTK_WRAP_WORD);\n cert_details_buffer_ = gtk_text_view_get_buffer(\n GTK_TEXT_VIEW(cert_details_view));\n \/\/ We put the details in a frame instead of a scrolled window so that the\n \/\/ entirety will be visible without requiring scrolling or expanding the\n \/\/ dialog. This does however mean the dialog will grow itself if you switch\n \/\/ to different cert that has longer details text.\n GtkWidget* details_frame = gtk_frame_new(NULL);\n gtk_frame_set_shadow_type(GTK_FRAME(details_frame), GTK_SHADOW_ETCHED_IN);\n gtk_container_add(GTK_CONTAINER(details_frame), cert_details_view);\n gtk_box_pack_start(GTK_BOX(selector_vbox), details_frame, TRUE, TRUE, 0);\n\n \/\/ And then create a set of buttons like a GtkDialog would.\n GtkWidget* button_box = gtk_hbutton_box_new();\n gtk_button_box_set_layout(GTK_BUTTON_BOX(button_box), GTK_BUTTONBOX_END);\n gtk_box_set_spacing(GTK_BOX(button_box), gtk_util::kControlSpacing);\n gtk_box_pack_end(GTK_BOX(root_widget_.get()), button_box, FALSE, FALSE, 0);\n\n GtkWidget* view_button = gtk_button_new_with_mnemonic(\n l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str());\n gtk_box_pack_start(GTK_BOX(button_box), view_button, FALSE, FALSE, 0);\n g_signal_connect(view_button, \"clicked\",\n G_CALLBACK(OnViewClickedThunk), this);\n\n GtkWidget* cancel_button = gtk_button_new_from_stock(GTK_STOCK_CANCEL);\n gtk_box_pack_end(GTK_BOX(button_box), cancel_button, FALSE, FALSE, 0);\n g_signal_connect(cancel_button, \"clicked\",\n G_CALLBACK(OnCancelClickedThunk), this);\n\n GtkWidget* select_button = gtk_button_new_from_stock(GTK_STOCK_OK);\n gtk_box_pack_end(GTK_BOX(button_box), select_button, FALSE, FALSE, 0);\n g_signal_connect(select_button, \"clicked\",\n G_CALLBACK(OnOkClickedThunk), this);\n\n \/\/ When we are attached to a window, focus the select button.\n select_button_ = select_button;\n g_signal_connect(root_widget_.get(), \"hierarchy-changed\",\n G_CALLBACK(OnPromptShownThunk), this);\n PopulateCerts();\n\n gtk_widget_show_all(root_widget_.get());\n}\n\nSSLClientCertificateSelector::~SSLClientCertificateSelector() {\n root_widget_.Destroy();\n}\n\nvoid SSLClientCertificateSelector::Show() {\n DCHECK(!window_);\n window_ = parent_->CreateConstrainedDialog(this);\n}\n\nvoid SSLClientCertificateSelector::DeleteDelegate() {\n if (delegate_) {\n \/\/ The dialog was closed by escape key.\n delegate_->CertificateSelected(NULL);\n }\n delete this;\n}\n\nvoid SSLClientCertificateSelector::PopulateCerts() {\n std::vector<std::string> nicknames;\n x509_certificate_model::GetNicknameStringsFromCertList(\n cert_request_info_->client_certs,\n l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CERT_EXPIRED),\n l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CERT_NOT_YET_VALID),\n &nicknames);\n\n DCHECK_EQ(nicknames.size(),\n cert_request_info_->client_certs.size());\n\n for (size_t i = 0; i < cert_request_info_->client_certs.size(); ++i) {\n net::X509Certificate::OSCertHandle cert =\n cert_request_info_->client_certs[i]->os_cert_handle();\n\n details_strings_.push_back(FormatDetailsText(cert));\n\n gtk_combo_box_append_text(\n GTK_COMBO_BOX(cert_combo_box_),\n FormatComboBoxText(cert, nicknames[i]).c_str());\n }\n\n \/\/ Auto-select the first cert.\n gtk_combo_box_set_active(GTK_COMBO_BOX(cert_combo_box_), 0);\n}\n\nnet::X509Certificate* SSLClientCertificateSelector::GetSelectedCert() {\n int selected = gtk_combo_box_get_active(GTK_COMBO_BOX(cert_combo_box_));\n if (selected >= 0 &&\n selected < static_cast<int>(\n cert_request_info_->client_certs.size()))\n return cert_request_info_->client_certs[selected];\n return NULL;\n}\n\n\/\/ static\nstd::string SSLClientCertificateSelector::FormatComboBoxText(\n net::X509Certificate::OSCertHandle cert, const std::string& nickname) {\n std::string rv(nickname);\n rv += \" [\";\n rv += x509_certificate_model::GetSerialNumberHexified(cert, \"\");\n rv += ']';\n return rv;\n}\n\n\/\/ static\nstd::string SSLClientCertificateSelector::FormatDetailsText(\n net::X509Certificate::OSCertHandle cert) {\n std::string rv;\n\n rv += l10n_util::GetStringFUTF8(\n IDS_CERT_SUBJECTNAME_FORMAT,\n UTF8ToUTF16(x509_certificate_model::GetSubjectName(cert)));;\n\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(\n IDS_CERT_SERIAL_NUMBER_FORMAT,\n UTF8ToUTF16(\n x509_certificate_model::GetSerialNumberHexified(cert, \"\")));\n\n base::Time issued, expires;\n if (x509_certificate_model::GetTimes(cert, &issued, &expires)) {\n string16 issued_str = WideToUTF16(\n base::TimeFormatShortDateAndTime(issued));\n string16 expires_str = WideToUTF16(\n base::TimeFormatShortDateAndTime(expires));\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(IDS_CERT_VALIDITY_RANGE_FORMAT,\n issued_str, expires_str);\n }\n\n std::vector<std::string> usages;\n x509_certificate_model::GetUsageStrings(cert, &usages);\n if (usages.size()) {\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(IDS_CERT_X509_EXTENDED_KEY_USAGE_FORMAT,\n UTF8ToUTF16(JoinString(usages, ',')));\n }\n\n std::string key_usage_str = x509_certificate_model::GetKeyUsageString(cert);\n if (!key_usage_str.empty()) {\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(IDS_CERT_X509_KEY_USAGE_FORMAT,\n UTF8ToUTF16(key_usage_str));\n }\n\n std::vector<std::string> email_addresses;\n x509_certificate_model::GetEmailAddresses(cert, &email_addresses);\n if (email_addresses.size()) {\n rv += \"\\n \";\n rv += l10n_util::GetStringFUTF8(\n IDS_CERT_EMAIL_ADDRESSES_FORMAT,\n UTF8ToUTF16(JoinString(email_addresses, ',')));\n }\n\n rv += '\\n';\n rv += l10n_util::GetStringFUTF8(\n IDS_CERT_ISSUERNAME_FORMAT,\n UTF8ToUTF16(x509_certificate_model::GetIssuerName(cert)));\n\n string16 token(UTF8ToUTF16(x509_certificate_model::GetTokenName(cert)));\n if (!token.empty()) {\n rv += '\\n';\n rv += l10n_util::GetStringFUTF8(IDS_CERT_TOKEN_FORMAT, token);\n }\n\n return rv;\n}\n\nvoid SSLClientCertificateSelector::OnComboBoxChanged(GtkWidget* combo_box) {\n int selected = gtk_combo_box_get_active(\n GTK_COMBO_BOX(cert_combo_box_));\n if (selected < 0)\n return;\n gtk_text_buffer_set_text(cert_details_buffer_,\n details_strings_[selected].c_str(),\n details_strings_[selected].size());\n}\n\nvoid SSLClientCertificateSelector::OnViewClicked(GtkWidget* button) {\n net::X509Certificate* cert = GetSelectedCert();\n if (cert) {\n GtkWidget* toplevel = gtk_widget_get_toplevel(root_widget_.get());\n ShowCertificateViewer(GTK_WINDOW(toplevel), cert);\n }\n}\n\nvoid SSLClientCertificateSelector::OnCancelClicked(GtkWidget* button) {\n delegate_->CertificateSelected(NULL);\n delegate_ = NULL;\n DCHECK(window_);\n window_->CloseConstrainedWindow();\n}\n\nvoid SSLClientCertificateSelector::OnOkClicked(GtkWidget* button) {\n net::X509Certificate* cert = GetSelectedCert();\n delegate_->CertificateSelected(cert);\n delegate_ = NULL;\n DCHECK(window_);\n window_->CloseConstrainedWindow();\n}\n\nvoid SSLClientCertificateSelector::OnPromptShown(GtkWidget* widget,\n GtkWidget* previous_toplevel) {\n if (!root_widget_.get() ||\n !GTK_WIDGET_TOPLEVEL(gtk_widget_get_toplevel(root_widget_.get())))\n return;\n GTK_WIDGET_SET_FLAGS(select_button_, GTK_CAN_DEFAULT);\n gtk_widget_grab_default(select_button_);\n gtk_widget_grab_focus(select_button_);\n}\n\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SSLClientAuthHandler platform specific implementation:\n\nnamespace browser {\n\nvoid ShowSSLClientCertificateSelector(\n TabContents* parent,\n net::SSLCertRequestInfo* cert_request_info,\n SSLClientAuthHandler* delegate) {\n (new SSLClientCertificateSelector(parent,\n cert_request_info,\n delegate))->Show();\n}\n\n} \/\/ namespace browser\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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\/browser\/metrics\/proto\/study.pb.h\"\n#include \"chrome\/browser\/metrics\/variations_service.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ Converts |time| to chrome_variations::Study proto format.\nint64 TimeToProtoTime(const base::Time& time) {\n return (time - base::Time::UnixEpoch()).InSeconds();\n}\n\n} \/\/ namespace\n\n\nTEST(VariationsServiceTest, CheckStudyChannel) {\n const chrome::VersionInfo::Channel channels[] = {\n chrome::VersionInfo::CHANNEL_CANARY,\n chrome::VersionInfo::CHANNEL_DEV,\n chrome::VersionInfo::CHANNEL_BETA,\n chrome::VersionInfo::CHANNEL_STABLE,\n };\n const chrome_variations::Study_Channel study_channels[] = {\n chrome_variations::Study_Channel_CANARY,\n chrome_variations::Study_Channel_DEV,\n chrome_variations::Study_Channel_BETA,\n chrome_variations::Study_Channel_STABLE,\n };\n ASSERT_EQ(arraysize(channels), arraysize(study_channels));\n bool channel_added[arraysize(channels)] = { 0 };\n\n chrome_variations::Study study;\n\n \/\/ Check in the forwarded order. The loop cond is <= arraysize(study_channels)\n \/\/ instead of < so that the result of adding the last channel gets checked.\n for (size_t i = 0; i <= arraysize(study_channels); ++i) {\n for (size_t j = 0; j < arraysize(channels); ++j) {\n const bool expected = channel_added[j] || study.channel_size() == 0;\n const bool result = VariationsService::CheckStudyChannel(study,\n channels[j]);\n EXPECT_EQ(expected, result) << \"Case \" << i << \",\" << j << \" failed!\";\n }\n\n if (i < arraysize(study_channels))\n {\n study.add_channel(study_channels[i]);\n channel_added[i] = true;\n }\n }\n\n \/\/ Do the same check in the reverse order.\n study.clear_channel();\n memset(&channel_added, 0, sizeof(channel_added));\n for (size_t i = 0; i <= arraysize(study_channels); ++i) {\n for (size_t j = 0; j < arraysize(channels); ++j) {\n const bool expected = channel_added[j] || study.channel_size() == 0;\n const bool result = VariationsService::CheckStudyChannel(study,\n channels[j]);\n EXPECT_EQ(expected, result) << \"Case \" << i << \",\" << j << \" failed!\";\n }\n\n if (i < arraysize(study_channels))\n {\n const int index = arraysize(study_channels) - i - 1;\n study.add_channel(study_channels[index]);\n channel_added[index] = true;\n }\n }\n}\n\nTEST(VariationsServiceTest, CheckStudyVersion) {\n const struct {\n const char* min_version;\n const char* version;\n bool expected_result;\n } min_test_cases[] = {\n { \"1.2.2\", \"1.2.3\", true },\n { \"1.2.3\", \"1.2.3\", true },\n { \"1.2.4\", \"1.2.3\", false },\n { \"1.3.2\", \"1.2.3\", false },\n { \"2.1.2\", \"1.2.3\", false },\n { \"0.3.4\", \"1.2.3\", true },\n };\n\n const struct {\n const char* max_version;\n const char* version;\n bool expected_result;\n } max_test_cases[] = {\n { \"1.2.2\", \"1.2.3\", false },\n { \"1.2.3\", \"1.2.3\", true },\n { \"1.2.4\", \"1.2.3\", true },\n { \"2.1.1\", \"1.2.3\", true },\n { \"2.1.1\", \"2.3.4\", false },\n };\n\n chrome_variations::Study study;\n\n \/\/ Min\/max version not set should result in true.\n EXPECT_TRUE(VariationsService::CheckStudyVersion(study, \"1.2.3\"));\n\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(min_test_cases); ++i) {\n study.set_min_version(min_test_cases[i].min_version);\n const bool result =\n VariationsService::CheckStudyVersion(study, min_test_cases[i].version);\n EXPECT_EQ(min_test_cases[i].expected_result, result) <<\n \"Case \" << i << \" failed!\";\n }\n study.clear_min_version();\n\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(max_test_cases); ++i) {\n study.set_max_version(max_test_cases[i].max_version);\n const bool result =\n VariationsService::CheckStudyVersion(study, max_test_cases[i].version);\n EXPECT_EQ(max_test_cases[i].expected_result, result) <<\n \"Case \" << i << \" failed!\";\n }\n\n \/\/ Check intersection semantics.\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(min_test_cases); ++i) {\n for (size_t j = 0; j < ARRAYSIZE_UNSAFE(max_test_cases); ++j) {\n study.set_min_version(min_test_cases[i].min_version);\n study.set_max_version(max_test_cases[j].max_version);\n\n if (!min_test_cases[i].expected_result) {\n const bool result =\n VariationsService::CheckStudyVersion(study,\n min_test_cases[i].version);\n EXPECT_FALSE(result) << \"Case \" << i << \",\" << j << \" failed!\";\n }\n\n if (!max_test_cases[j].expected_result) {\n const bool result =\n VariationsService::CheckStudyVersion(study,\n max_test_cases[j].version);\n EXPECT_FALSE(result) << \"Case \" << i << \",\" << j << \" failed!\";\n }\n }\n }\n}\n\n\/\/ The current client logic does not handle version number strings containing\n\/\/ wildcards. Check that any such values received from the server result in the\n\/\/ study being disqualified.\nTEST(VariationsServiceTest, CheckStudyVersionWildcards) {\n chrome_variations::Study study;\n\n study.set_min_version(\"1.0.*\");\n EXPECT_FALSE(VariationsService::CheckStudyVersion(study, \"1.2.3\"));\n\n study.clear_min_version();\n study.set_max_version(\"2.0.*\");\n EXPECT_FALSE(VariationsService::CheckStudyVersion(study, \"1.2.3\"));\n}\n\nTEST(VariationsServiceTest, CheckStudyDate) {\n const base::Time now = base::Time::Now();\n const base::TimeDelta delta = base::TimeDelta::FromHours(1);\n const struct {\n const base::Time start_date;\n bool expected_result;\n } start_test_cases[] = {\n { now - delta, true },\n { now, true },\n { now + delta, false },\n };\n const struct {\n const base::Time expiry_date;\n bool expected_result;\n } expiry_test_cases[] = {\n { now - delta, false },\n { now, false },\n { now + delta, true },\n };\n\n chrome_variations::Study study;\n\n \/\/ Start\/expiry date not set should result in true.\n EXPECT_TRUE(VariationsService::CheckStudyDate(study, now));\n\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(start_test_cases); ++i) {\n study.set_start_date(TimeToProtoTime(start_test_cases[i].start_date));\n const bool result = VariationsService::CheckStudyDate(study, now);\n EXPECT_EQ(start_test_cases[i].expected_result, result)\n << \"Case \" << i << \" failed!\";\n }\n study.clear_start_date();\n\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(expiry_test_cases); ++i) {\n study.set_expiry_date(TimeToProtoTime(expiry_test_cases[i].expiry_date));\n const bool result = VariationsService::CheckStudyDate(study, now);\n EXPECT_EQ(expiry_test_cases[i].expected_result, result)\n << \"Case \" << i << \" failed!\";\n }\n\n \/\/ Check intersection semantics.\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(start_test_cases); ++i) {\n for (size_t j = 0; j < ARRAYSIZE_UNSAFE(expiry_test_cases); ++j) {\n study.set_start_date(TimeToProtoTime(start_test_cases[i].start_date));\n study.set_expiry_date(TimeToProtoTime(expiry_test_cases[j].expiry_date));\n const bool expected = start_test_cases[i].expected_result &&\n expiry_test_cases[j].expected_result;\n const bool result = VariationsService::CheckStudyDate(study, now);\n EXPECT_EQ(expected, result) << \"Case \" << i << \",\" << j << \" failed!\";\n }\n }\n}\n<commit_msg>revert 135858: This depends on the previous revet<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ 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\/browser\/pepper_broker_infobar_delegate.h\"\n\n#include \"base\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/api\/infobars\/infobar_service.h\"\n#include \"chrome\/browser\/content_settings\/host_content_settings_map.h\"\n#include \"chrome\/browser\/content_settings\/tab_specific_content_settings.h\"\n#include \"chrome\/browser\/plugins\/plugin_finder.h\"\n#include \"chrome\/browser\/plugins\/plugin_metadata.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"content\/public\/browser\/page_navigator.h\"\n#include \"content\/public\/browser\/plugin_service.h\"\n#include \"content\/public\/browser\/user_metrics.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/referrer.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"net\/base\/net_util.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/plugins\/webplugininfo.h\"\n\n\/\/ The URL for the \"learn more\" article about the PPAPI broker.\nconst char kPpapiBrokerLearnMoreUrl[] =\n \"https:\/\/support.google.com\/chrome\/?p=ib_pepper_broker\";\n\nusing content::OpenURLParams;\nusing content::Referrer;\nusing content::WebContents;\n\n\/\/ static\nvoid PepperBrokerInfoBarDelegate::Create(\n WebContents* web_contents,\n const GURL& url,\n const base::FilePath& plugin_path,\n const base::Callback<void(bool)>& callback) {\n Profile* profile =\n Profile::FromBrowserContext(web_contents->GetBrowserContext());\n \/\/ TODO(wad): Add ephemeral device ID support for broker in guest mode.\n if (profile->IsGuestSession()) {\n callback.Run(false);\n return;\n }\n\n TabSpecificContentSettings* tab_content_settings =\n TabSpecificContentSettings::FromWebContents(web_contents);\n HostContentSettingsMap* content_settings =\n profile->GetHostContentSettingsMap();\n ContentSetting setting =\n content_settings->GetContentSetting(url, url,\n CONTENT_SETTINGS_TYPE_PPAPI_BROKER,\n std::string());\n switch (setting) {\n case CONTENT_SETTING_ALLOW: {\n content::RecordAction(\n content::UserMetricsAction(\"PPAPI.BrokerSettingAllow\"));\n tab_content_settings->SetPepperBrokerAllowed(true);\n callback.Run(true);\n break;\n }\n case CONTENT_SETTING_BLOCK: {\n content::RecordAction(\n content::UserMetricsAction(\"PPAPI.BrokerSettingDeny\"));\n tab_content_settings->SetPepperBrokerAllowed(false);\n callback.Run(false);\n break;\n }\n case CONTENT_SETTING_ASK: {\n content::RecordAction(\n content::UserMetricsAction(\"PPAPI.BrokerInfobarDisplayed\"));\n\n InfoBarService* infobar_service =\n InfoBarService::FromWebContents(web_contents);\n std::string languages =\n profile->GetPrefs()->GetString(prefs::kAcceptLanguages);\n infobar_service->AddInfoBar(scoped_ptr<InfoBarDelegate>(\n new PepperBrokerInfoBarDelegate(\n infobar_service, url, plugin_path, languages, content_settings,\n tab_content_settings, callback)));\n break;\n }\n default:\n NOTREACHED();\n }\n}\n\nstring16 PepperBrokerInfoBarDelegate::GetMessageText() const {\n content::PluginService* plugin_service =\n content::PluginService::GetInstance();\n webkit::WebPluginInfo plugin;\n bool success = plugin_service->GetPluginInfoByPath(plugin_path_, &plugin);\n DCHECK(success);\n scoped_ptr<PluginMetadata> plugin_metadata(\n PluginFinder::GetInstance()->GetPluginMetadata(plugin));\n return l10n_util::GetStringFUTF16(IDS_PEPPER_BROKER_MESSAGE,\n plugin_metadata->name(),\n net::FormatUrl(url_.GetOrigin(),\n languages_));\n}\n\nint PepperBrokerInfoBarDelegate::GetButtons() const {\n return BUTTON_OK | BUTTON_CANCEL;\n}\n\nstring16 PepperBrokerInfoBarDelegate::GetButtonLabel(\n InfoBarButton button) const {\n switch (button) {\n case BUTTON_OK:\n return l10n_util::GetStringUTF16(IDS_PEPPER_BROKER_ALLOW_BUTTON);\n case BUTTON_CANCEL:\n return l10n_util::GetStringUTF16(IDS_PEPPER_BROKER_DENY_BUTTON);\n default:\n NOTREACHED();\n return string16();\n }\n}\n\nbool PepperBrokerInfoBarDelegate::Accept() {\n DispatchCallback(true);\n return true;\n}\n\nbool PepperBrokerInfoBarDelegate::Cancel() {\n DispatchCallback(false);\n return true;\n}\n\nstring16 PepperBrokerInfoBarDelegate::GetLinkText() const {\n return l10n_util::GetStringUTF16(IDS_LEARN_MORE);\n}\n\nbool PepperBrokerInfoBarDelegate::LinkClicked(\n WindowOpenDisposition disposition) {\n OpenURLParams params(\n GURL(kPpapiBrokerLearnMoreUrl), Referrer(),\n (disposition == CURRENT_TAB) ? NEW_FOREGROUND_TAB : disposition,\n content::PAGE_TRANSITION_LINK,\n false);\n owner()->GetWebContents()->OpenURL(params);\n return false;\n}\n\ngfx::Image* PepperBrokerInfoBarDelegate::GetIcon() const {\n return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(\n IDR_INFOBAR_PLUGIN_INSTALL);\n}\n\nPepperBrokerInfoBarDelegate::PepperBrokerInfoBarDelegate(\n InfoBarService* infobar_service,\n const GURL& url,\n const base::FilePath& plugin_path,\n const std::string& languages,\n HostContentSettingsMap* content_settings,\n TabSpecificContentSettings* tab_content_settings,\n const base::Callback<void(bool)>& callback)\n : ConfirmInfoBarDelegate(infobar_service),\n url_(url),\n plugin_path_(plugin_path),\n languages_(languages),\n content_settings_(content_settings),\n tab_content_settings_(tab_content_settings),\n callback_(callback) {\n}\n\nPepperBrokerInfoBarDelegate::~PepperBrokerInfoBarDelegate() {\n if (!callback_.is_null())\n callback_.Run(false);\n}\n\nvoid PepperBrokerInfoBarDelegate::DispatchCallback(bool result) {\n content::RecordAction(result ?\n content::UserMetricsAction(\"PPAPI.BrokerInfobarClickedAllow\") :\n content::UserMetricsAction(\"PPAPI.BrokerInfobarClickedDeny\"));\n callback_.Run(result);\n callback_ = base::Callback<void(bool)>();\n content_settings_->SetContentSetting(\n ContentSettingsPattern::FromURLNoWildcard(url_),\n ContentSettingsPattern::Wildcard(),\n CONTENT_SETTINGS_TYPE_PPAPI_BROKER,\n std::string(), result ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK);\n tab_content_settings_->SetPepperBrokerAllowed(result);\n}\n<commit_msg>Disabled plugin broker infobar on Chrome OS for Netflix since this plugins can only come installed by the OS.<commit_after>\/\/ 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\/browser\/pepper_broker_infobar_delegate.h\"\n\n#include \"base\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/api\/infobars\/infobar_service.h\"\n#include \"chrome\/browser\/content_settings\/host_content_settings_map.h\"\n#include \"chrome\/browser\/content_settings\/tab_specific_content_settings.h\"\n#include \"chrome\/browser\/plugins\/plugin_finder.h\"\n#include \"chrome\/browser\/plugins\/plugin_metadata.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"content\/public\/browser\/page_navigator.h\"\n#include \"content\/public\/browser\/plugin_service.h\"\n#include \"content\/public\/browser\/user_metrics.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/referrer.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"net\/base\/net_util.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/plugins\/webplugininfo.h\"\n\n\/\/ The URL for the \"learn more\" article about the PPAPI broker.\nconst char kPpapiBrokerLearnMoreUrl[] =\n \"https:\/\/support.google.com\/chrome\/?p=ib_pepper_broker\";\n\n#if defined(OS_CHROMEOS)\nconst char kNetflixPluginFileName[] = \"libnetflixplugin2.so\";\n#endif\n\nusing content::OpenURLParams;\nusing content::Referrer;\nusing content::WebContents;\n\n\/\/ static\nvoid PepperBrokerInfoBarDelegate::Create(\n WebContents* web_contents,\n const GURL& url,\n const base::FilePath& plugin_path,\n const base::Callback<void(bool)>& callback) {\n Profile* profile =\n Profile::FromBrowserContext(web_contents->GetBrowserContext());\n \/\/ TODO(wad): Add ephemeral device ID support for broker in guest mode.\n if (profile->IsGuestSession()) {\n callback.Run(false);\n return;\n }\n\n TabSpecificContentSettings* tab_content_settings =\n TabSpecificContentSettings::FromWebContents(web_contents);\n\n#if defined(OS_CHROMEOS)\n \/\/ On ChromeOS, we're ok with granting broker access to Netflix plugin, since\n \/\/ it can only come installed with the OS.\n if (plugin_path.BaseName().value() ==\n FILE_PATH_LITERAL(kNetflixPluginFileName)) {\n tab_content_settings->SetPepperBrokerAllowed(true);\n callback.Run(true);\n return;\n }\n#endif\n\n HostContentSettingsMap* content_settings =\n profile->GetHostContentSettingsMap();\n ContentSetting setting =\n content_settings->GetContentSetting(url, url,\n CONTENT_SETTINGS_TYPE_PPAPI_BROKER,\n std::string());\n switch (setting) {\n case CONTENT_SETTING_ALLOW: {\n content::RecordAction(\n content::UserMetricsAction(\"PPAPI.BrokerSettingAllow\"));\n tab_content_settings->SetPepperBrokerAllowed(true);\n callback.Run(true);\n break;\n }\n case CONTENT_SETTING_BLOCK: {\n content::RecordAction(\n content::UserMetricsAction(\"PPAPI.BrokerSettingDeny\"));\n tab_content_settings->SetPepperBrokerAllowed(false);\n callback.Run(false);\n break;\n }\n case CONTENT_SETTING_ASK: {\n content::RecordAction(\n content::UserMetricsAction(\"PPAPI.BrokerInfobarDisplayed\"));\n\n InfoBarService* infobar_service =\n InfoBarService::FromWebContents(web_contents);\n std::string languages =\n profile->GetPrefs()->GetString(prefs::kAcceptLanguages);\n infobar_service->AddInfoBar(scoped_ptr<InfoBarDelegate>(\n new PepperBrokerInfoBarDelegate(\n infobar_service, url, plugin_path, languages, content_settings,\n tab_content_settings, callback)));\n break;\n }\n default:\n NOTREACHED();\n }\n}\n\nstring16 PepperBrokerInfoBarDelegate::GetMessageText() const {\n content::PluginService* plugin_service =\n content::PluginService::GetInstance();\n webkit::WebPluginInfo plugin;\n bool success = plugin_service->GetPluginInfoByPath(plugin_path_, &plugin);\n DCHECK(success);\n scoped_ptr<PluginMetadata> plugin_metadata(\n PluginFinder::GetInstance()->GetPluginMetadata(plugin));\n return l10n_util::GetStringFUTF16(IDS_PEPPER_BROKER_MESSAGE,\n plugin_metadata->name(),\n net::FormatUrl(url_.GetOrigin(),\n languages_));\n}\n\nint PepperBrokerInfoBarDelegate::GetButtons() const {\n return BUTTON_OK | BUTTON_CANCEL;\n}\n\nstring16 PepperBrokerInfoBarDelegate::GetButtonLabel(\n InfoBarButton button) const {\n switch (button) {\n case BUTTON_OK:\n return l10n_util::GetStringUTF16(IDS_PEPPER_BROKER_ALLOW_BUTTON);\n case BUTTON_CANCEL:\n return l10n_util::GetStringUTF16(IDS_PEPPER_BROKER_DENY_BUTTON);\n default:\n NOTREACHED();\n return string16();\n }\n}\n\nbool PepperBrokerInfoBarDelegate::Accept() {\n DispatchCallback(true);\n return true;\n}\n\nbool PepperBrokerInfoBarDelegate::Cancel() {\n DispatchCallback(false);\n return true;\n}\n\nstring16 PepperBrokerInfoBarDelegate::GetLinkText() const {\n return l10n_util::GetStringUTF16(IDS_LEARN_MORE);\n}\n\nbool PepperBrokerInfoBarDelegate::LinkClicked(\n WindowOpenDisposition disposition) {\n OpenURLParams params(\n GURL(kPpapiBrokerLearnMoreUrl), Referrer(),\n (disposition == CURRENT_TAB) ? NEW_FOREGROUND_TAB : disposition,\n content::PAGE_TRANSITION_LINK,\n false);\n owner()->GetWebContents()->OpenURL(params);\n return false;\n}\n\ngfx::Image* PepperBrokerInfoBarDelegate::GetIcon() const {\n return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(\n IDR_INFOBAR_PLUGIN_INSTALL);\n}\n\nPepperBrokerInfoBarDelegate::PepperBrokerInfoBarDelegate(\n InfoBarService* infobar_service,\n const GURL& url,\n const base::FilePath& plugin_path,\n const std::string& languages,\n HostContentSettingsMap* content_settings,\n TabSpecificContentSettings* tab_content_settings,\n const base::Callback<void(bool)>& callback)\n : ConfirmInfoBarDelegate(infobar_service),\n url_(url),\n plugin_path_(plugin_path),\n languages_(languages),\n content_settings_(content_settings),\n tab_content_settings_(tab_content_settings),\n callback_(callback) {\n}\n\nPepperBrokerInfoBarDelegate::~PepperBrokerInfoBarDelegate() {\n if (!callback_.is_null())\n callback_.Run(false);\n}\n\nvoid PepperBrokerInfoBarDelegate::DispatchCallback(bool result) {\n content::RecordAction(result ?\n content::UserMetricsAction(\"PPAPI.BrokerInfobarClickedAllow\") :\n content::UserMetricsAction(\"PPAPI.BrokerInfobarClickedDeny\"));\n callback_.Run(result);\n callback_ = base::Callback<void(bool)>();\n content_settings_->SetContentSetting(\n ContentSettingsPattern::FromURLNoWildcard(url_),\n ContentSettingsPattern::Wildcard(),\n CONTENT_SETTINGS_TYPE_PPAPI_BROKER,\n std::string(), result ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK);\n tab_content_settings_->SetPepperBrokerAllowed(result);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ [WriteFile Name=FeatureLayerShapefile, Category=Layers]\n\/\/ [Legal]\n\/\/ Copyright 2017 Esri.\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\/\/ 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\/\/ [Legal]\n\n#include \"FeatureLayerShapefile.h\"\n\n#include \"Map.h\"\n#include \"MapQuickView.h\"\n#include \"Basemap.h\"\n#include \"ShapefileFeatureTable.h\"\n#include \"FeatureLayer.h\"\n\n#include <QQmlProperty>\n\n\nusing namespace Esri::ArcGISRuntime;\n\nFeatureLayerShapefile::FeatureLayerShapefile(QQuickItem* parent \/* = nullptr *\/):\n QQuickItem(parent)\n{\n}\n\nvoid FeatureLayerShapefile::init()\n{\n \/\/ Register the map view for QML\n qmlRegisterType<MapQuickView>(\"Esri.Samples\", 1, 0, \"MapView\");\n qmlRegisterType<FeatureLayerShapefile>(\"Esri.Samples\", 1, 0, \"FeatureLayerShapefileSample\");\n}\n\nvoid FeatureLayerShapefile::componentComplete()\n{\n QQuickItem::componentComplete();\n\n QString dataPath = QQmlProperty::read(this, \"dataPath\").toString();\n\n \/\/ find QML MapView component\n m_mapView = findChild<MapQuickView*>(\"mapView\");\n\n \/\/ Create a map using the topographic basemap\n m_map = new Map(Basemap::streetsVector(this), this);\n\n \/\/ Set map to map view\n m_mapView->setMap(m_map);\n\n \/\/ Create and add the shapefile to the map\n createAndAddShapefileLayer(dataPath + \"Public_Art.shp\");\n}\nvoid FeatureLayerShapefile::createAndAddShapefileLayer(QUrl const &file)\n{\n\n QString dataPath = file.toLocalFile();\n\n \/\/ Create the ShapefileFeatureTable\n ShapefileFeatureTable* featureTable = new ShapefileFeatureTable(dataPath, this);\n\n \/\/ Create the feature layer from the ShapefileFeatureTable\n FeatureLayer* layer = new FeatureLayer(featureTable, this);\n\n connect(layer, &FeatureLayer::doneLoading, this, [this, layer](Error loadError)\n {\n if (!loadError.isEmpty())\n return;\n\n \/\/ If the layer was loaded successfully, set the map extent to the full extent of the layer\n m_mapView->setViewpointCenter(layer->fullExtent().center(), 80000);\n });\n\n \/\/ Add the shapefile layer to the map\n m_map->operationalLayers()->clear();\n m_map->operationalLayers()->append(layer);\n}\n<commit_msg>Changed \"QUrl const &file\" to \"const QUrl& file\"<commit_after>\/\/ [WriteFile Name=FeatureLayerShapefile, Category=Layers]\n\/\/ [Legal]\n\/\/ Copyright 2017 Esri.\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\/\/ 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\/\/ [Legal]\n\n#include \"FeatureLayerShapefile.h\"\n\n#include \"Map.h\"\n#include \"MapQuickView.h\"\n#include \"Basemap.h\"\n#include \"ShapefileFeatureTable.h\"\n#include \"FeatureLayer.h\"\n\n#include <QQmlProperty>\n\n\nusing namespace Esri::ArcGISRuntime;\n\nFeatureLayerShapefile::FeatureLayerShapefile(QQuickItem* parent \/* = nullptr *\/):\n QQuickItem(parent)\n{\n}\n\nvoid FeatureLayerShapefile::init()\n{\n \/\/ Register the map view for QML\n qmlRegisterType<MapQuickView>(\"Esri.Samples\", 1, 0, \"MapView\");\n qmlRegisterType<FeatureLayerShapefile>(\"Esri.Samples\", 1, 0, \"FeatureLayerShapefileSample\");\n}\n\nvoid FeatureLayerShapefile::componentComplete()\n{\n QQuickItem::componentComplete();\n\n QString dataPath = QQmlProperty::read(this, \"dataPath\").toString();\n\n \/\/ find QML MapView component\n m_mapView = findChild<MapQuickView*>(\"mapView\");\n\n \/\/ Create a map using the topographic basemap\n m_map = new Map(Basemap::streetsVector(this), this);\n\n \/\/ Set map to map view\n m_mapView->setMap(m_map);\n\n \/\/ Create and add the shapefile to the map\n createAndAddShapefileLayer(dataPath + \"Public_Art.shp\");\n}\nvoid FeatureLayerShapefile::createAndAddShapefileLayer(const QUrl& file)\n{\n\n QString dataPath = file.toLocalFile();\n\n \/\/ Create the ShapefileFeatureTable\n ShapefileFeatureTable* featureTable = new ShapefileFeatureTable(dataPath, this);\n\n \/\/ Create the feature layer from the ShapefileFeatureTable\n FeatureLayer* layer = new FeatureLayer(featureTable, this);\n\n connect(layer, &FeatureLayer::doneLoading, this, [this, layer](Error loadError)\n {\n if (!loadError.isEmpty())\n return;\n\n \/\/ If the layer was loaded successfully, set the map extent to the full extent of the layer\n m_mapView->setViewpointCenter(layer->fullExtent().center(), 80000);\n });\n\n \/\/ Add the shapefile layer to the map\n m_map->operationalLayers()->clear();\n m_map->operationalLayers()->append(layer);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ [WriteFile Name=FeatureLayerExtrusion, Category=Scenes]\n\/\/ [Legal]\n\/\/ Copyright 2017 Esri.\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\/\/ 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\/\/ [Legal]\n\n#include \"FeatureLayerExtrusion.h\"\n\n#include \"FeatureLayer.h\"\n#include \"ServiceFeatureTable.h\"\n#include \"ArcGISTiledElevationSource.h\"\n#include \"Scene.h\"\n#include \"SceneQuickView.h\"\n#include \"Point.h\"\n#include \"SimpleLineSymbol.h\"\n#include \"SimpleFillSymbol.h\"\n#include \"SimpleRenderer.h\"\n#include \"RendererSceneProperties.h\"\n\nusing namespace Esri::ArcGISRuntime;\n\nFeatureLayerExtrusion::FeatureLayerExtrusion(QQuickItem* parent \/* = nullptr *\/):\n QQuickItem(parent)\n{\n}\n\nvoid FeatureLayerExtrusion::init()\n{\n \/\/ Register classes for QML\n qmlRegisterType<SceneQuickView>(\"Esri.Samples\", 1, 0, \"SceneView\");\n qmlRegisterType<FeatureLayerExtrusion>(\"Esri.Samples\", 1, 0, \"FeatureLayerExtrusionSample\");\n}\n\nvoid FeatureLayerExtrusion::componentComplete()\n{\n QQuickItem::componentComplete();\n\n \/\/ Create the feature service to use\n m_featureTable = new ServiceFeatureTable(QUrl(\"https:\/\/sampleserver6.arcgisonline.com\/arcgis\/rest\/services\/Census\/MapServer\/3\"), this);\n\n \/\/ add the service feature table to a feature layer\n m_featureLayer = new FeatureLayer(m_featureTable, this);\n\n \/\/ set the feature layer to render dynamically to allow extrusion\n m_featureLayer->setRenderingMode(FeatureRenderingMode::Dynamic);\n\n \/\/ define line and fill symbols for a simple renderer\n m_lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(\"Black\"), 1.0f, this);\n m_fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle::Solid, QColor(\"Blue\"), m_lineSymbol, this);\n m_renderer = new SimpleRenderer(m_fillSymbol, this);\n\n \/\/ set renderer extrusion mode to absolute to prevent clipping\n RendererSceneProperties props = m_renderer->sceneProperties();\n props.setExtrusionMode(ExtrusionMode::AbsoluteHeight);\n props.setExtrusionExpression(\"[POP2007] \/ 10\");\n m_renderer->setSceneProperties(props);\n\n \/\/ set the simple renderer to the feature layer\n m_featureLayer->setRenderer(m_renderer);\n\n \/\/ Create a scene and give it to the SceneView\n m_sceneView = findChild<SceneQuickView*>(\"sceneView\");\n Scene* scene = new Scene(Basemap::imagery(this), this);\n Surface* surface = new Surface(this);\n surface->elevationSources()->append(\n new ArcGISTiledElevationSource(\n QUrl(\"https:\/\/elevation3d.arcgis.com\/arcgis\/rest\/services\/WorldElevation3D\/Terrain3D\/ImageServer\"),\n this));\n scene->setBaseSurface(surface);\n scene->operationalLayers()->append(m_featureLayer);\n\n \/\/ set initial viewpoint\n const double distance = 12940924;\n const Point lookAtPoint = Point(-99.659448, 20.513652, distance, SpatialReference::wgs84());\n const Camera camera(lookAtPoint, 0, 15, 0);\n const Viewpoint initialVp(lookAtPoint, distance, camera);\n scene->setInitialViewpoint(initialVp);\n\n \/\/ apply initial extrusion\n totalPopulation();\n\n m_sceneView->setArcGISScene(scene);\n}\n\nvoid FeatureLayerExtrusion::popDensity()\n{\n \/\/ multiply population density by 5000 to make data legible\n RendererSceneProperties props = m_renderer->sceneProperties();\n props.setExtrusionExpression(\"([POP07_SQMI] * 5000) + 10000\");\n m_renderer->setSceneProperties(props);\n}\n\nvoid FeatureLayerExtrusion::totalPopulation()\n{\n \/\/ divide total population by 10 to make data legible\n RendererSceneProperties props = m_renderer->sceneProperties();\n props.setExtrusionExpression(\"[POP2007] \/ 10\");\n m_renderer->setSceneProperties(props);\n}\n\n\n\n<commit_msg>Update FeatureLayerExtrusion.cpp<commit_after>\/\/ [WriteFile Name=FeatureLayerExtrusion, Category=Scenes]\n\/\/ [Legal]\n\/\/ Copyright 2017 Esri.\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\/\/ 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\/\/ [Legal]\n\n#include \"FeatureLayerExtrusion.h\"\n\n#include \"FeatureLayer.h\"\n#include \"ServiceFeatureTable.h\"\n#include \"ArcGISTiledElevationSource.h\"\n#include \"Scene.h\"\n#include \"SceneQuickView.h\"\n#include \"Point.h\"\n#include \"SimpleLineSymbol.h\"\n#include \"SimpleFillSymbol.h\"\n#include \"SimpleRenderer.h\"\n#include \"RendererSceneProperties.h\"\n\nusing namespace Esri::ArcGISRuntime;\n\nFeatureLayerExtrusion::FeatureLayerExtrusion(QQuickItem* parent \/* = nullptr *\/):\n QQuickItem(parent)\n{\n}\n\nvoid FeatureLayerExtrusion::init()\n{\n \/\/ Register classes for QML\n qmlRegisterType<SceneQuickView>(\"Esri.Samples\", 1, 0, \"SceneView\");\n qmlRegisterType<FeatureLayerExtrusion>(\"Esri.Samples\", 1, 0, \"FeatureLayerExtrusionSample\");\n}\n\nvoid FeatureLayerExtrusion::componentComplete()\n{\n QQuickItem::componentComplete();\n\n \/\/ Create the feature service to use\n m_featureTable = new ServiceFeatureTable(QUrl(\"https:\/\/sampleserver6.arcgisonline.com\/arcgis\/rest\/services\/Census\/MapServer\/3\"), this);\n\n \/\/ add the service feature table to a feature layer\n m_featureLayer = new FeatureLayer(m_featureTable, this);\n\n \/\/ set the feature layer to render dynamically to allow extrusion\n m_featureLayer->setRenderingMode(FeatureRenderingMode::Dynamic);\n\n \/\/ define line and fill symbols for a simple renderer\n m_lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(\"Black\"), 1.0f, this);\n m_fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle::Solid, QColor(\"Blue\"), m_lineSymbol, this);\n m_renderer = new SimpleRenderer(m_fillSymbol, this);\n\n \/\/ set renderer extrusion mode to absolute to prevent clipping\n RendererSceneProperties props = m_renderer->sceneProperties();\n props.setExtrusionMode(ExtrusionMode::AbsoluteHeight);\n props.setExtrusionExpression(\"[POP2007] \/ 10\");\n m_renderer->setSceneProperties(props);\n\n \/\/ set the simple renderer to the feature layer\n m_featureLayer->setRenderer(m_renderer);\n\n \/\/ Create a scene and give it to the SceneView\n m_sceneView = findChild<SceneQuickView*>(\"sceneView\");\n Scene* scene = new Scene(Basemap::imagery(this), this);\n Surface* surface = new Surface(this);\n surface->elevationSources()->append(\n new ArcGISTiledElevationSource(\n QUrl(\"https:\/\/elevation3d.arcgis.com\/arcgis\/rest\/services\/WorldElevation3D\/Terrain3D\/ImageServer\"),\n this));\n scene->setBaseSurface(surface);\n scene->operationalLayers()->append(m_featureLayer);\n\n \/\/ set initial viewpoint\n const double distance = 12940924;\n const Point lookAtPoint(-99.659448, 20.513652, distance, SpatialReference::wgs84());\n const Camera camera(lookAtPoint, 0, 15, 0);\n const Viewpoint initialVp(lookAtPoint, distance, camera);\n scene->setInitialViewpoint(initialVp);\n\n \/\/ apply initial extrusion\n totalPopulation();\n\n m_sceneView->setArcGISScene(scene);\n}\n\nvoid FeatureLayerExtrusion::popDensity()\n{\n \/\/ multiply population density by 5000 to make data legible\n RendererSceneProperties props = m_renderer->sceneProperties();\n props.setExtrusionExpression(\"([POP07_SQMI] * 5000) + 10000\");\n m_renderer->setSceneProperties(props);\n}\n\nvoid FeatureLayerExtrusion::totalPopulation()\n{\n \/\/ divide total population by 10 to make data legible\n RendererSceneProperties props = m_renderer->sceneProperties();\n props.setExtrusionExpression(\"[POP2007] \/ 10\");\n m_renderer->setSceneProperties(props);\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_CONSTRAINTSET_PERSISTENTUNILATERALINTERACTIONCONSTRAINT_INL\n#define SOFA_COMPONENT_CONSTRAINTSET_PERSISTENTUNILATERALINTERACTIONCONSTRAINT_INL\n\n#include \"PersistentUnilateralInteractionConstraint.h\"\n\n#include <sofa\/component\/constraintset\/UnilateralInteractionConstraint.inl>\n\n#include <sofa\/helper\/rmath.h>\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace constraintset\n{\n\ntemplate< class DataTypes >\nvoid PersistentUnilateralConstraintResolutionWithFriction< DataTypes >::init(int line, double** w, double* force)\n{\n _W[0] = w[line\t\t][line\t\t];\n _W[1] = w[line\t\t][line + 1\t];\n _W[2] = w[line\t\t][line + 2\t];\n _W[3] = w[line + 1\t][line + 1\t];\n _W[4] = w[line + 1\t][line + 2\t];\n _W[5] = w[line + 2\t][line + 2\t];\n\n \/\/\/@TODO OPTIMIZATION\n force[line\t\t] = _f[0];\n force[line + 1\t] = _f[1];\n force[line + 2\t] = _f[2];\n}\n\ntemplate< class DataTypes >\nvoid PersistentUnilateralConstraintResolutionWithFriction< DataTypes >::resolution(int line, double** \/*w*\/, double* d, double* force, double * \/*dfree*\/)\n{\n double f[2];\n double normFt;\n\n f[0] = force[line]; f[1] = force[line+1];\n force[line] -= d[line] \/ _W[0];\n\n if(force[line] < 0)\n {\n force[line]=0; force[line+1]=0; force[line+2]=0;\n\n \/\/\/@TODO OPTIMIZATION\n if (m_constraint)\n m_constraint->setContactState(line, NONE);\n\n return;\n }\n\n d[line+1] += _W[1] * (force[line]-f[0]);\n d[line+2] += _W[2] * (force[line]-f[0]);\n force[line+1] -= 2*d[line+1] \/ (_W[3] +_W[5]) ;\n force[line+2] -= 2*d[line+2] \/ (_W[3] +_W[5]) ;\n\n normFt = sqrt(force[line+1]*force[line+1] + force[line+2]*force[line+2]);\n\n if(normFt > _mu*force[line])\n {\n force[line+1] *= _mu*force[line]\/normFt;\n force[line+2] *= _mu*force[line]\/normFt;\n\n \/\/\/@TODO OPTIMIZATION\n if (m_constraint)\n {\n m_constraint->setContactState(line, SLIDING);\n m_constraint->setContactForce(line, Deriv(force[line], force[line+1], force[line+2]));\n }\n }\n else\n {\n \/\/\/@TODO OPTIMIZATION\n if (m_constraint)\n {\n m_constraint->setContactState(line, STICKY);\n m_constraint->setContactForce(line, Deriv(force[line], force[line+1], force[line+2]));\n }\n }\n}\n\ntemplate< class DataTypes >\nvoid PersistentUnilateralConstraintResolutionWithFriction< DataTypes >::store(int line, double* force, bool \/*convergence*\/)\n{\n if(_active)\n {\n *_active = (force[line] != 0);\n\n \/\/ Won't be used in the haptic thread\n _active = NULL;\n }\n}\n\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::addContact(double mu, Deriv norm, Coord P, Coord Q, Real contactDistance, int m1, int m2, Coord Pfree, Coord Qfree, long id, PersistentID localid, bool isPersistent)\n{\n \/\/ Compute dt and delta\n const Real delta = dot(P-Q, norm) - contactDistance;\n const Real deltaFree = dot(Pfree-Qfree, norm) - contactDistance;\n\n if (this->f_printLog.getValue())\n {\n std::cout << \"delta : \" << delta << \" - deltaFree : \" << deltaFree << std::endl;\n std::cout << \"P : \" << P << \" - PFree : \" << Pfree << std::endl;\n std::cout << \"Q : \" << Q << \" - QFree : \" << Qfree << std::endl;\n }\n\n unsigned int lastContactIndex = this->contacts.size();\n this->contacts.resize(lastContactIndex + 1);\n\n typename Inherited::Contact& c = this->contacts[lastContactIndex];\n\n c.P\t\t\t\t= P;\n c.Q\t\t\t\t= Q;\n c.Pfree\t\t\t= Pfree;\n c.Qfree\t\t\t= Qfree;\n c.m1\t\t\t= m1;\n c.m2\t\t\t= m2;\n c.norm\t\t\t= norm;\n c.delta\t\t\t= delta;\n c.mu\t\t\t= mu;\n c.contactId\t\t= id;\n c.localId\t\t= localid;\n c.t\t\t\t\t= Deriv(norm.z(), norm.x(), norm.y());\n c.s\t\t\t\t= cross(norm, c.t);\n c.s\t\t\t\t= c.s \/ c.s.norm();\n c.t\t\t\t\t= cross((-norm), c.s);\n\n const Deriv PPfree = Pfree - P;\n const Deriv QQfree = Qfree - Q;\n const Real REF_DIST = PPfree.norm() + QQfree.norm();\n\n if (isPersistent)\n {\n\n std::cout << \"Persistent contact: \\nP : \" << P << \" - PFree : \" << Pfree << std::endl;\n std::cout << \"Q : \" << Q << \" - QFree : \" << Qfree << std::endl;\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(Pfree - Qfree, c.t);\n c.dfree_s\t= dot(Pfree - Qfree, c.s);\n\n return;\n }\n\n if (helper::rabs(delta) < 0.00001 * REF_DIST)\n {\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(PPfree, c.t) - dot(QQfree, c.t);\n c.dfree_s\t= dot(PPfree, c.s) - dot(QQfree, c.s);\n\n return;\n }\n\n if (helper::rabs(delta - deltaFree) > 0.001 * delta)\n {\n const Real dt = delta \/ (delta - deltaFree);\n\n if (dt > 0.0 && dt < 1.0)\n {\n const sofa::defaulttype::Vector3 Qt = Q * (1-dt) + Qfree * dt;\n const sofa::defaulttype::Vector3 Pt = P * (1-dt) + Pfree * dt;\n\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(Pfree-Pt, c.t) - dot(Qfree-Qt, c.t);\n c.dfree_s\t= dot(Pfree-Pt, c.s) - dot(Qfree-Qt, c.s);\n }\n else\n {\n if (deltaFree < 0.0)\n {\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(PPfree, c.t) - dot(QQfree, c.t);\n c.dfree_s\t= dot(PPfree, c.s) - dot(QQfree, c.s);\n }\n else\n {\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= 0;\n c.dfree_s\t= 0;\n }\n }\n }\n else\n {\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(PPfree, c.t) - dot(QQfree, c.t);\n c.dfree_s\t= dot(PPfree, c.s) - dot(QQfree, c.s);\n }\n}\n\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::getConstraintResolution(std::vector<core::behavior::ConstraintResolution*>& resTab, unsigned int& offset)\n{\n if (this->contactsStatus)\n delete[] this->contactsStatus;\n\n this->contactsStatus = new bool[this->contacts.size()];\n memset(this->contactsStatus, 0, sizeof(bool)*this->contacts.size());\n\n for(unsigned int i=0; i<this->contacts.size(); i++)\n {\n Contact& c = this->contacts[i];\n if(c.mu > 0.0)\n {\n PersistentUnilateralConstraintResolutionWithFriction<DataTypes> *cRes = new PersistentUnilateralConstraintResolutionWithFriction<DataTypes>(c.mu, &this->contactsStatus[i]);\n cRes->setConstraint(this);\n cRes->setInitForce(getInitForce(c.contactId));\n resTab[offset] = cRes;\n offset += 3;\n }\n else\n resTab[offset++] = new UnilateralConstraintResolution();\n }\n}\n\n\ntemplate<class DataTypes>\nbool PersistentUnilateralInteractionConstraint<DataTypes>::isSticked(int _contactId)\n{\n typename sofa::helper::vector< Contact >::iterator it = this->contacts.begin();\n typename sofa::helper::vector< Contact >::iterator itEnd = this->contacts.end();\n\n while (it != itEnd)\n {\n if (it->contactId == _contactId)\n break;\n\n ++it;\n }\n\n if (it != itEnd)\n return (contactStates[it->id] == PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::STICKY);\n else\n return false;\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::setContactState(int id, ContactState s)\n{\n if (contactStates.find(id) != contactStates.end())\n {\n contactStates[id] = s;\n }\n else\n {\n contactStates.insert(std::make_pair(id, s));\n }\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::clearContactStates()\n{\n contactStates.clear();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::setContactForce(int id, Deriv f)\n{\n if (contactForces.find(id) != contactForces.end())\n {\n contactForces[id] = f;\n }\n else\n {\n contactForces.insert(std::make_pair(id, f));\n }\n}\n\ntemplate<class DataTypes>\ntypename PersistentUnilateralInteractionConstraint<DataTypes>::Deriv PersistentUnilateralInteractionConstraint<DataTypes>::getContactForce(int _contactId)\n{\n typename sofa::helper::vector< Contact >::iterator it = this->contacts.begin();\n typename sofa::helper::vector< Contact >::iterator itEnd = this->contacts.end();\n\n while (it != itEnd)\n {\n if (it->contactId == _contactId)\n break;\n\n ++it;\n }\n\n if (it != itEnd)\n {\n if (contactForces.find(it->id) != contactForces.end())\n {\n return contactForces[it->id];\n }\n }\n\n return Deriv();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::clearContactForces()\n{\n contactForces.clear();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::setInitForce(int id, Deriv f)\n{\n if (initForces.find(id) != initForces.end())\n {\n initForces[id] = f;\n }\n else\n {\n initForces.insert(std::make_pair(id, f));\n }\n}\n\ntemplate<class DataTypes>\ntypename PersistentUnilateralInteractionConstraint<DataTypes>::Deriv PersistentUnilateralInteractionConstraint<DataTypes>::getInitForce(int id)\n{\n if (initForces.find(id) != initForces.end())\n {\n return initForces[id];\n }\n\n return Deriv();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::clearInitForces()\n{\n initForces.clear();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::debugContactStates()\n{\n std::cout << \"-------------->debugContactStates\\n\";\n\n typename std::map< int, ContactState >::iterator it = contactStates.begin();\n typename std::map< int, ContactState >::iterator itEnd = contactStates.end();\n\n std::string s;\n\n while (it != itEnd)\n {\n switch (it->second)\n {\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::NONE :\n s = \"NONE\";\n break;\n\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::SLIDING :\n s = \"SLIDING\";\n break;\n\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::STICKY :\n s = \"STICKY\";\n break;\n }\n\n std::cout << it->first << \" : \" << s << std::endl;\n ++it;\n }\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::draw()\n{\n if (!this->getContext()->getShowInteractionForceFields()) return;\n\n glDisable(GL_LIGHTING);\n\n for (unsigned int i=0; i< this->contacts.size(); i++)\n {\n const Contact& c = this->contacts[i];\n\n glLineWidth(5);\n glBegin(GL_LINES);\n\n switch (contactStates[c.id])\n {\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::NONE :\n glColor4f(1,0,0,1);\n break;\n\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::SLIDING :\n glColor4f(0,0,1,1);\n break;\n\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::STICKY :\n glColor4f(0,1,0,1);\n break;\n }\n\n helper::gl::glVertexT(c.P);\n helper::gl::glVertexT(c.Q);\n\n glEnd();\n\n glLineWidth(1);\n glBegin(GL_LINES);\n\n glColor4f(1,1,1,1);\n helper::gl::glVertexT(c.Pfree);\n helper::gl::glVertexT(c.Qfree);\n\n glEnd();\n\n glLineWidth(1);\n }\n}\n\n} \/\/ namespace constraintset\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif \/\/ SOFA_COMPONENT_CONSTRAINTSET_PERSISTENTUNILATERALINTERACTIONCONSTRAINT_INL\n<commit_msg>r9767\/sofa-dev : FIX : Bug in Haptics Thread trying to access a potentially deleted UnilateralInteractionConstraint.<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_CONSTRAINTSET_PERSISTENTUNILATERALINTERACTIONCONSTRAINT_INL\n#define SOFA_COMPONENT_CONSTRAINTSET_PERSISTENTUNILATERALINTERACTIONCONSTRAINT_INL\n\n#include \"PersistentUnilateralInteractionConstraint.h\"\n\n#include <sofa\/component\/constraintset\/UnilateralInteractionConstraint.inl>\n\n#include <sofa\/helper\/rmath.h>\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace constraintset\n{\n\ntemplate< class DataTypes >\nvoid PersistentUnilateralConstraintResolutionWithFriction< DataTypes >::init(int line, double** w, double* force)\n{\n _W[0] = w[line\t\t][line\t\t];\n _W[1] = w[line\t\t][line + 1\t];\n _W[2] = w[line\t\t][line + 2\t];\n _W[3] = w[line + 1\t][line + 1\t];\n _W[4] = w[line + 1\t][line + 2\t];\n _W[5] = w[line + 2\t][line + 2\t];\n\n \/\/\/@TODO OPTIMIZATION\n force[line\t\t] = _f[0];\n force[line + 1\t] = _f[1];\n force[line + 2\t] = _f[2];\n}\n\ntemplate< class DataTypes >\nvoid PersistentUnilateralConstraintResolutionWithFriction< DataTypes >::resolution(int line, double** \/*w*\/, double* d, double* force, double * \/*dfree*\/)\n{\n double f[2];\n double normFt;\n\n f[0] = force[line]; f[1] = force[line+1];\n force[line] -= d[line] \/ _W[0];\n\n if(force[line] < 0)\n {\n force[line]=0; force[line+1]=0; force[line+2]=0;\n\n \/\/\/@TODO OPTIMIZATION\n if (m_constraint)\n m_constraint->setContactState(line, NONE);\n\n return;\n }\n\n d[line+1] += _W[1] * (force[line]-f[0]);\n d[line+2] += _W[2] * (force[line]-f[0]);\n force[line+1] -= 2*d[line+1] \/ (_W[3] +_W[5]) ;\n force[line+2] -= 2*d[line+2] \/ (_W[3] +_W[5]) ;\n\n normFt = sqrt(force[line+1]*force[line+1] + force[line+2]*force[line+2]);\n\n if(normFt > _mu*force[line])\n {\n force[line+1] *= _mu*force[line]\/normFt;\n force[line+2] *= _mu*force[line]\/normFt;\n\n \/\/\/@TODO OPTIMIZATION\n if (m_constraint)\n {\n m_constraint->setContactState(line, SLIDING);\n m_constraint->setContactForce(line, Deriv(force[line], force[line+1], force[line+2]));\n }\n }\n else\n {\n \/\/\/@TODO OPTIMIZATION\n if (m_constraint)\n {\n m_constraint->setContactState(line, STICKY);\n m_constraint->setContactForce(line, Deriv(force[line], force[line+1], force[line+2]));\n }\n }\n}\n\ntemplate< class DataTypes >\nvoid PersistentUnilateralConstraintResolutionWithFriction< DataTypes >::store(int line, double* force, bool \/*convergence*\/)\n{\n m_constraint = 0;\n\n if(_active)\n {\n *_active = (force[line] != 0);\n\n \/\/ Won't be used in the haptic thread\n _active = NULL;\n }\n}\n\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::addContact(double mu, Deriv norm, Coord P, Coord Q, Real contactDistance, int m1, int m2, Coord Pfree, Coord Qfree, long id, PersistentID localid, bool isPersistent)\n{\n \/\/ Compute dt and delta\n const Real delta = dot(P-Q, norm) - contactDistance;\n const Real deltaFree = dot(Pfree-Qfree, norm) - contactDistance;\n\n if (this->f_printLog.getValue())\n {\n std::cout << \"delta : \" << delta << \" - deltaFree : \" << deltaFree << std::endl;\n std::cout << \"P : \" << P << \" - PFree : \" << Pfree << std::endl;\n std::cout << \"Q : \" << Q << \" - QFree : \" << Qfree << std::endl;\n }\n\n unsigned int lastContactIndex = this->contacts.size();\n this->contacts.resize(lastContactIndex + 1);\n\n typename Inherited::Contact& c = this->contacts[lastContactIndex];\n\n c.P\t\t\t\t= P;\n c.Q\t\t\t\t= Q;\n c.Pfree\t\t\t= Pfree;\n c.Qfree\t\t\t= Qfree;\n c.m1\t\t\t= m1;\n c.m2\t\t\t= m2;\n c.norm\t\t\t= norm;\n c.delta\t\t\t= delta;\n c.mu\t\t\t= mu;\n c.contactId\t\t= id;\n c.localId\t\t= localid;\n c.t\t\t\t\t= Deriv(norm.z(), norm.x(), norm.y());\n c.s\t\t\t\t= cross(norm, c.t);\n c.s\t\t\t\t= c.s \/ c.s.norm();\n c.t\t\t\t\t= cross((-norm), c.s);\n\n const Deriv PPfree = Pfree - P;\n const Deriv QQfree = Qfree - Q;\n const Real REF_DIST = PPfree.norm() + QQfree.norm();\n\n if (isPersistent)\n {\n\n std::cout << \"Persistent contact: \\nP : \" << P << \" - PFree : \" << Pfree << std::endl;\n std::cout << \"Q : \" << Q << \" - QFree : \" << Qfree << std::endl;\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(Pfree - Qfree, c.t);\n c.dfree_s\t= dot(Pfree - Qfree, c.s);\n\n return;\n }\n\n if (helper::rabs(delta) < 0.00001 * REF_DIST)\n {\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(PPfree, c.t) - dot(QQfree, c.t);\n c.dfree_s\t= dot(PPfree, c.s) - dot(QQfree, c.s);\n\n return;\n }\n\n if (helper::rabs(delta - deltaFree) > 0.001 * delta)\n {\n const Real dt = delta \/ (delta - deltaFree);\n\n if (dt > 0.0 && dt < 1.0)\n {\n const sofa::defaulttype::Vector3 Qt = Q * (1-dt) + Qfree * dt;\n const sofa::defaulttype::Vector3 Pt = P * (1-dt) + Pfree * dt;\n\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(Pfree-Pt, c.t) - dot(Qfree-Qt, c.t);\n c.dfree_s\t= dot(Pfree-Pt, c.s) - dot(Qfree-Qt, c.s);\n }\n else\n {\n if (deltaFree < 0.0)\n {\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(PPfree, c.t) - dot(QQfree, c.t);\n c.dfree_s\t= dot(PPfree, c.s) - dot(QQfree, c.s);\n }\n else\n {\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= 0;\n c.dfree_s\t= 0;\n }\n }\n }\n else\n {\n c.dfree\t\t= deltaFree;\n c.dfree_t\t= dot(PPfree, c.t) - dot(QQfree, c.t);\n c.dfree_s\t= dot(PPfree, c.s) - dot(QQfree, c.s);\n }\n}\n\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::getConstraintResolution(std::vector<core::behavior::ConstraintResolution*>& resTab, unsigned int& offset)\n{\n if (this->contactsStatus)\n delete[] this->contactsStatus;\n\n this->contactsStatus = new bool[this->contacts.size()];\n memset(this->contactsStatus, 0, sizeof(bool)*this->contacts.size());\n\n for(unsigned int i=0; i<this->contacts.size(); i++)\n {\n Contact& c = this->contacts[i];\n if(c.mu > 0.0)\n {\n PersistentUnilateralConstraintResolutionWithFriction<DataTypes> *cRes = new PersistentUnilateralConstraintResolutionWithFriction<DataTypes>(c.mu, &this->contactsStatus[i]);\n cRes->setConstraint(this);\n cRes->setInitForce(getInitForce(c.contactId));\n resTab[offset] = cRes;\n offset += 3;\n }\n else\n resTab[offset++] = new UnilateralConstraintResolution();\n }\n}\n\n\ntemplate<class DataTypes>\nbool PersistentUnilateralInteractionConstraint<DataTypes>::isSticked(int _contactId)\n{\n typename sofa::helper::vector< Contact >::iterator it = this->contacts.begin();\n typename sofa::helper::vector< Contact >::iterator itEnd = this->contacts.end();\n\n while (it != itEnd)\n {\n if (it->contactId == _contactId)\n break;\n\n ++it;\n }\n\n if (it != itEnd)\n return (contactStates[it->id] == PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::STICKY);\n else\n return false;\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::setContactState(int id, ContactState s)\n{\n if (contactStates.find(id) != contactStates.end())\n {\n contactStates[id] = s;\n }\n else\n {\n contactStates.insert(std::make_pair(id, s));\n }\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::clearContactStates()\n{\n contactStates.clear();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::setContactForce(int id, Deriv f)\n{\n if (contactForces.find(id) != contactForces.end())\n {\n contactForces[id] = f;\n }\n else\n {\n contactForces.insert(std::make_pair(id, f));\n }\n}\n\ntemplate<class DataTypes>\ntypename PersistentUnilateralInteractionConstraint<DataTypes>::Deriv PersistentUnilateralInteractionConstraint<DataTypes>::getContactForce(int _contactId)\n{\n typename sofa::helper::vector< Contact >::iterator it = this->contacts.begin();\n typename sofa::helper::vector< Contact >::iterator itEnd = this->contacts.end();\n\n while (it != itEnd)\n {\n if (it->contactId == _contactId)\n break;\n\n ++it;\n }\n\n if (it != itEnd)\n {\n if (contactForces.find(it->id) != contactForces.end())\n {\n return contactForces[it->id];\n }\n }\n\n return Deriv();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::clearContactForces()\n{\n contactForces.clear();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::setInitForce(int id, Deriv f)\n{\n if (initForces.find(id) != initForces.end())\n {\n initForces[id] = f;\n }\n else\n {\n initForces.insert(std::make_pair(id, f));\n }\n}\n\ntemplate<class DataTypes>\ntypename PersistentUnilateralInteractionConstraint<DataTypes>::Deriv PersistentUnilateralInteractionConstraint<DataTypes>::getInitForce(int id)\n{\n if (initForces.find(id) != initForces.end())\n {\n return initForces[id];\n }\n\n return Deriv();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::clearInitForces()\n{\n initForces.clear();\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::debugContactStates()\n{\n std::cout << \"-------------->debugContactStates\\n\";\n\n typename std::map< int, ContactState >::iterator it = contactStates.begin();\n typename std::map< int, ContactState >::iterator itEnd = contactStates.end();\n\n std::string s;\n\n while (it != itEnd)\n {\n switch (it->second)\n {\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::NONE :\n s = \"NONE\";\n break;\n\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::SLIDING :\n s = \"SLIDING\";\n break;\n\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::STICKY :\n s = \"STICKY\";\n break;\n }\n\n std::cout << it->first << \" : \" << s << std::endl;\n ++it;\n }\n}\n\ntemplate<class DataTypes>\nvoid PersistentUnilateralInteractionConstraint<DataTypes>::draw()\n{\n if (!this->getContext()->getShowInteractionForceFields()) return;\n\n glDisable(GL_LIGHTING);\n\n for (unsigned int i=0; i< this->contacts.size(); i++)\n {\n const Contact& c = this->contacts[i];\n\n glLineWidth(5);\n glBegin(GL_LINES);\n\n switch (contactStates[c.id])\n {\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::NONE :\n glColor4f(1,0,0,1);\n break;\n\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::SLIDING :\n glColor4f(0,0,1,1);\n break;\n\n case PersistentUnilateralConstraintResolutionWithFriction<DataTypes>::STICKY :\n glColor4f(0,1,0,1);\n break;\n }\n\n helper::gl::glVertexT(c.P);\n helper::gl::glVertexT(c.Q);\n\n glEnd();\n\n glLineWidth(1);\n glBegin(GL_LINES);\n\n glColor4f(1,1,1,1);\n helper::gl::glVertexT(c.Pfree);\n helper::gl::glVertexT(c.Qfree);\n\n glEnd();\n\n glLineWidth(1);\n }\n}\n\n} \/\/ namespace constraintset\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif \/\/ SOFA_COMPONENT_CONSTRAINTSET_PERSISTENTUNILATERALINTERACTIONCONSTRAINT_INL\n<|endoftext|>"} {"text":"<commit_before>\/\/ Polygon.cpp\n\n#include \"Polygon.h\"\n#include \"Triangle.h\"\n#include \"IndexTriangle.h\"\n#include \"LineSegment.h\"\n#include \"Surface.h\"\n#include \"AffineTransform.h\"\n#include \"Graph.h\"\n#include \"Exception.h\"\n#include \"ListFunctions.h\"\n\nusing namespace _3DMath;\n\nPolygon::Polygon( void )\n{\n\tvertexArray = new VectorArray();\n\tindexTriangleList = new IndexTriangleList();\n}\n\n\/*virtual*\/ Polygon::~Polygon( void )\n{\n\tdelete vertexArray;\n\tdelete indexTriangleList;\n}\n\nvoid Polygon::Transform( const AffineTransform& transform )\n{\n\ttransform.Transform( *vertexArray );\n}\n\nbool Polygon::GetPlane( Plane& plane ) const\n{\n\tif( vertexArray->size() < 3 )\n\t\treturn false;\n\n\tVector center;\n\tGetCenter( center );\n\n\tVector normal;\n\tnormal.Set( 0.0, 0.0, 0.0 );\n\t\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t{\n\t\t\/\/ This is the Newel method.\n\t\tint j = ( i + 1 ) % vertexArray->size();\n\t\tconst Vector& pointA = ( *vertexArray )[i];\n\t\tconst Vector& pointB = ( *vertexArray )[j];\n\t\tnormal.x += ( pointA.y - pointB.y ) * ( pointA.z + pointB.z );\n\t\tnormal.y += ( pointA.z - pointB.z ) * ( pointA.x + pointB.x );\n\t\tnormal.z += ( pointA.x - pointB.x ) * ( pointA.y + pointB.y );\n\t}\n\n\tplane.SetCenterAndNormal( center, normal );\n\treturn true;\n}\n\nvoid Polygon::GetCenter( Vector& center ) const\n{\n\tcenter.Set( 0.0, 0.0, 0.0 );\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\tcenter.Add( ( *vertexArray )[i] );\n\tcenter.Scale( 1.0 \/ double( vertexArray->size() ) );\n}\n\nbool Polygon::GetTriangleAverageCenter( Vector& center ) const\n{\n\tif( indexTriangleList->size() == 0 )\n\t\treturn false;\n\n\tcenter.Set( 0.0, 0.0, 0.0 );\n\n\tfor( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->cend(); iter++ )\n\t{\n\t\tconst IndexTriangle& indexTriangle = *iter;\n\n\t\tTriangle triangle;\n\t\tindexTriangle.GetTriangle( triangle, vertexArray );\n\n\t\tVector triangleCenter;\n\t\ttriangle.GetCenter( triangleCenter );\n\n\t\tcenter.Add( triangleCenter );\n\t}\n\n\tcenter.Scale( 1.0 \/ double( indexTriangleList->size() ) );\n\treturn true;\n}\n\n\/\/ This assumes that we're properly tessellated.\nbool Polygon::ContainsPoint( const Vector& point, double eps \/*= EPSILON*\/ ) const\n{\n\tfor( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->cend(); iter++ )\n\t{\n\t\tconst IndexTriangle& indexTriangle = *iter;\n\n\t\tTriangle triangle;\n\t\tindexTriangle.GetTriangle( triangle, vertexArray );\n\n\t\tif( triangle.ContainsPoint( point, eps ) )\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n\/\/ Add extraneous points to the polygon until no edge is greater than the given minimum distance.\n\/\/ Of course, since the geometry of the polygon doesn't change, the visible edge-lengths remain the same.\n\/\/ Note that this may invalidate a current tessellation of the polygon.\nvoid Polygon::IncreaseDensity( double minDistance )\n{\n\tint i;\n\n\tdo\n\t{\t\n\t\tfor( i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\t{\n\t\t\tint j = ( i + 1 ) % vertexArray->size();\n\t\t\tLineSegment lineSegment;\n\t\t\tlineSegment.vertex[0] = ( *vertexArray )[i];\n\t\t\tlineSegment.vertex[1] = ( *vertexArray )[j];\n\t\t\tif( lineSegment.Length() > minDistance )\n\t\t\t{\n\t\t\t\tVector midPoint;\n\t\t\t\tlineSegment.Lerp( 0.5, midPoint );\n\t\t\t\tvertexArray->insert( vertexArray->begin() + j, midPoint );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\t\n\t}\n\twhile( i < ( signed )vertexArray->size() );\n}\n\n\/\/ Here we remove any extraneous vertices. These are those that\n\/\/ are co-linear with respect to their immediate adjacencies.\n\/\/ Note that this may invalidate a current tessellation of the polygon.\nvoid Polygon::MinimizeDensity( void )\n{\n\twhile( true )\n\t{\n\t\tint i;\n\t\tfor( i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\t{\n\t\t\tTriangle triangle;\n\t\t\tfor( int j = 0; j < 3; j++ )\n\t\t\t\ttriangle.vertex[j] = ( *vertexArray )[ ( i + j ) % vertexArray->size() ];\n\n\t\t\tif( triangle.Area() < EPSILON )\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif( i == ( signed )vertexArray->size() )\n\t\t\tbreak;\n\n\t\tvertexArray->erase( vertexArray->begin() + ( i + 1 ) % vertexArray->size() );\n\t}\n}\n\nvoid Polygon::GetCopy( Polygon& polygon ) const\n{\n\tpolygon.vertexArray->clear();\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\tpolygon.vertexArray->push_back( ( *vertexArray )[i] );\n\n\tpolygon.indexTriangleList->clear();\n}\n\nbool Polygon::SplitAgainstSurface( const Surface* surface, PolygonList& polygonList, double minDistance, double maxDistance, double eps \/*= EPSILON*\/ ) const\n{\n\tPolygon* polygon = new Polygon();\n\tGetCopy( *polygon );\n\n\tPolygonList polygonQueue;\n\tpolygonQueue.push_back( polygon );\n\n\twhile( polygonQueue.size() > 0 )\n\t{\n\t\tPolygonList::iterator iter = polygonQueue.begin();\n\t\tpolygon = *iter;\n\t\tpolygonQueue.erase( iter );\n\n\t\tPolygon* polygonA = nullptr;\n\t\tPolygon* polygonB = nullptr;\n\n\t\tif( !polygon->SplitInTwoAgainstSurface( surface, polygonA, polygonB, minDistance, maxDistance, eps ) )\n\t\t\tpolygonList.push_back( polygon );\n\t\telse\n\t\t{\n\t\t\tdelete polygon;\n\t\t\tpolygonQueue.push_back( polygonA );\n\t\t\tpolygonQueue.push_back( polygonB );\n\t\t}\n\t}\n\n\tif( polygonQueue.size() > 1 )\n\t\treturn true;\n\n\tFreeList< Polygon >( polygonList );\n\treturn false;\n}\n\nbool Polygon::SplitInTwoAgainstSurface( const Surface* surface, Polygon*& polygonA, Polygon*& polygonB, double minDistance, double maxDistance, double eps )\n{\n\tpolygonA = nullptr;\n\tpolygonB = nullptr;\n\n\tIncreaseDensity( minDistance );\n\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t{\n\t\tint j = ( i + 1 ) % vertexArray->size();\n\n\t\tLineSegment lineSegment;\n\t\tlineSegment.vertex[0] = ( *vertexArray )[i];\n\t\tlineSegment.vertex[1] = ( *vertexArray )[j];\n\n\t\tSurface::Side side[2];\n\t\tside[0] = surface->GetSide( lineSegment.vertex[0], eps );\n\t\tside[1] = surface->GetSide( lineSegment.vertex[1], eps );\n\n\t\tif( ( side[0] == Surface::INSIDE && side[1] == Surface::OUTSIDE ) ||\n\t\t\t( side[1] == Surface::INSIDE && side[0] == Surface::OUTSIDE ) )\n\t\t{\n\t\t\tSurfacePoint* surfacePoint = surface->FindSingleIntersection( lineSegment );\n\t\t\tif( !surfacePoint )\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t{\n\t\t\t\tVector point;\n\t\t\t\tsurfacePoint->GetLocation( point );\n\t\t\t\tvertexArray->insert( vertexArray->begin() + j, point );\n\t\t\t\tdelete surfacePoint;\n\t\t\t}\n\t\t}\n\t}\n\n\tif( !Tessellate() )\n\t\treturn false;\n\n\tstd::vector< int > intersectionArray;\n\tint insideCount = 0;\n\tint outsideCount = 0;\n\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t{\n\t\tSurface::Side side = surface->GetSide( ( *vertexArray )[i] );\n\t\tswitch( side )\n\t\t{\n\t\t\tcase Surface::NEITHER_SIDE:\n\t\t\t{\n\t\t\t\tint j = ( i > 0 ) ? ( i - 1 ) : ( ( signed )vertexArray->size() - 1 );\n\t\t\t\tint k = ( i + 1 ) % vertexArray->size();\n\n\t\t\t\tif( ( surface->GetSide( ( *vertexArray )[j] ) == Surface::INSIDE && surface->GetSide( ( *vertexArray )[k] ) == Surface::OUTSIDE ) ||\n\t\t\t\t\t( surface->GetSide( ( *vertexArray )[k] ) == Surface::INSIDE && surface->GetSide( ( *vertexArray )[j] ) == Surface::OUTSIDE ) )\n\t\t\t\t{\n\t\t\t\t\tintersectionArray.push_back(i);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase Surface::INSIDE:\n\t\t\t{\n\t\t\t\tinsideCount++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase Surface::OUTSIDE:\n\t\t\t{\n\t\t\t\toutsideCount++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif( insideCount == 0 || outsideCount == 0 )\n\t\treturn false;\n\n\t_3DMath::Plane plane;\n\tif( !GetPlane( plane ) )\n\t\treturn false;\n\n\tfor( int i = 0; i < ( signed )intersectionArray.size(); i++ )\n\t{\n\t\tfor( int j = i + 1; j < ( signed )intersectionArray.size(); j++ )\n\t\t{\n\t\t\tVector pointA = ( *vertexArray )[ intersectionArray[i] ];\n\t\t\tVector pointB = ( *vertexArray )[ intersectionArray[j] ];\n\n\t\t\tVectorArray surfacePointArray;\n\t\t\tbool pathFound = false;\n\n\t\t\tdouble distance = pointA.Distance( pointB );\n\t\t\tif( distance < eps )\n\t\t\t{\n\t\t\t\tsurfacePointArray.push_back( pointA );\n\t\t\t\tpathFound = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tSurfacePoint* surfacePointA = surface->GetNearestSurfacePoint( pointA );\n\t\t\t\tSurfacePoint* surfacePointB = surface->GetNearestSurfacePoint( pointB );\n\t\t\t\tSurfacePoint* surfacePointC = nullptr;\n\n\t\t\t\tpathFound = surface->FindDirectPath( surfacePointA, surfacePointB, surfacePointArray, maxDistance, &plane );\n\t\t\t\tif( !pathFound )\n\t\t\t\t{\n\t\t\t\t\t\/\/ This is a bit of a hack.\n\t\t\t\t\tVector center;\n\t\t\t\t\tGetCenter( center );\n\n\t\t\t\t\tsurfacePointC = surface->GetNearestSurfacePoint( center );\n\t\t\t\t\tpathFound = surface->FindDirectPath( surfacePointA, surfacePointC, surfacePointArray, maxDistance, &plane );\n\t\t\t\t\tif( pathFound )\n\t\t\t\t\t{\n\t\t\t\t\t\tsurfacePointArray.pop_back();\n\t\t\t\t\t\tpathFound = surface->FindDirectPath( surfacePointC, surfacePointB, surfacePointArray, maxDistance, &plane );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdelete surfacePointA;\n\t\t\t\tdelete surfacePointB;\n\t\t\t\tdelete surfacePointC;\n\n\t\t\t\tif( surfacePointArray.size() == 0 )\n\t\t\t\t\tpathFound = false;\n\t\t\t}\n\n\t\t\t\/\/ Does the path along the surface and in the plane of the polygon\n\t\t\t\/\/ stay within the polygon's area through the whole path?\n\t\t\tif( pathFound )\n\t\t\t{\n\t\t\t\tfor( int k = 0; k < ( signed )surfacePointArray.size(); i++ )\n\t\t\t\t{\n\t\t\t\t\tif( !ContainsPoint( surfacePointArray[k] ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tpathFound = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif( pathFound )\n\t\t\t\t{\n\t\t\t\t\tfor( int k = 0; k < ( signed )surfacePointArray.size() - 1; i++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tLineSegment lineSegment;\n\t\t\t\t\t\tlineSegment.vertex[0] = surfacePointArray[k];\n\t\t\t\t\t\tlineSegment.vertex[1] = surfacePointArray[ k + 1 ];\n\n\t\t\t\t\t\tVectorList intersectionList;\n\t\t\t\t\t\tif( GetIntersectionPoints( lineSegment, intersectionList ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpathFound = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Finally, if we get here, we're ready to split the polygon in two.\n\t\t\tif( pathFound )\n\t\t\t{\n\t\t\t\tpolygonA = new Polygon();\n\t\t\t\tpolygonB = new Polygon();\n\n\t\t\t\tint k = ( intersectionArray[i] + 1 ) % vertexArray->size();\n\t\t\t\twhile( k != intersectionArray[j] )\n\t\t\t\t{\n\t\t\t\t\tpolygonA->vertexArray->push_back( ( *vertexArray )[k] );\n\t\t\t\t\tk = ( k + 1 ) % vertexArray->size();\n\t\t\t\t}\n\n\t\t\t\tk = ( intersectionArray[j] + 1 ) % vertexArray->size();\n\t\t\t\twhile( k != intersectionArray[i] )\n\t\t\t\t{\n\t\t\t\t\tpolygonB->vertexArray->push_back( ( *vertexArray )[k] );\n\t\t\t\t\tk = ( k + 1 ) % vertexArray->size();\n\t\t\t\t}\n\n\t\t\t\tfor( int k = 0; k < ( signed )surfacePointArray.size(); k++ )\n\t\t\t\t{\n\t\t\t\t\tint l = signed( surfacePointArray.size() ) - 1 - k;\n\t\t\t\t\tpolygonA->vertexArray->push_back( surfacePointArray[l] );\n\t\t\t\t\tpolygonB->vertexArray->push_back( surfacePointArray[k] );\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool Polygon::GetIntersectionPoints( const LineSegment& lineSegment, VectorList& intersectionList ) const\n{\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t{\n\t\tint j = ( i + 1 ) % vertexArray->size();\n\n\t\tLineSegment edge;\n\t\tedge.vertex[0] = ( *vertexArray )[i];\n\t\tedge.vertex[1] = ( *vertexArray )[j];\n\n\t\tVector intersectionPoint;\n\t\tif( edge.IntersectsWith( lineSegment, &intersectionPoint ) )\n\t\t\tintersectionList.push_back( intersectionPoint );\n\t}\n\n\treturn( intersectionList.size() > 0 ? true : false );\n}\n\ndouble Polygon::GetArea( void ) const\n{\n\tdouble totalArea = 0.0;\n\n\tfor( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->end(); iter++ )\n\t{\n\t\tconst IndexTriangle& indexTriangle = *iter;\n\t\tTriangle triangle;\n\t\tindexTriangle.GetTriangle( triangle, vertexArray );\n\t\ttotalArea += triangle.Area();\n\t}\n\n\treturn totalArea;\n}\n\nbool Polygon::Tessellate( void ) const\n{\n\tPlane plane;\n\tif( !GetPlane( plane ) )\n\t\treturn false;\n\n\tindexTriangleList->clear();\n\n\tstd::vector< int > indexArray;\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\tindexArray.push_back(i);\n\n\twhile( indexArray.size() > 2 )\n\t{\n\t\tint i;\n\t\tfor( i = 0; i < ( signed )indexArray.size(); i++ )\n\t\t{\n\t\t\tIndexTriangle indexTriangle(\n\t\t\t\t\tindexArray[i],\n\t\t\t\t\tindexArray[ ( i + 1 ) % indexArray.size() ],\n\t\t\t\t\tindexArray[ ( i + 2 ) % indexArray.size() ] );\n\n\t\t\tTriangle triangle;\n\t\t\tindexTriangle.GetTriangle( triangle, vertexArray );\n\n\t\t\tVector edge[2];\n\t\t\tedge[0].Subtract( triangle.vertex[1], triangle.vertex[0] );\n\t\t\tedge[1].Subtract( triangle.vertex[2], triangle.vertex[1] );\n\n\t\t\tVector cross;\n\t\t\tcross.Cross( edge[0], edge[1] );\n\t\t\tdouble dot = cross.Dot( plane.normal );\n\t\t\tif( dot < 0.0 )\n\t\t\t\tcontinue;\n\n\t\t\tint j;\n\t\t\tfor( j = 0; j < ( signed )indexArray.size(); j++ )\n\t\t\t{\n\t\t\t\tif( j == i || j == ( i + 1 ) % indexArray.size() || j == ( i + 2 ) % indexArray.size() )\n\t\t\t\t\tcontinue;\n\t\t\t\tif( triangle.ContainsPoint( ( *vertexArray )[ indexArray[j] ] ) )\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif( j < ( signed )indexArray.size() )\n\t\t\t\tcontinue;\n\n\t\t\tindexTriangleList->push_back( indexTriangle );\n\t\t\tindexArray.erase( indexArray.begin() + ( i + 1 ) % indexArray.size() );\n\t\t\tbreak;\n\t\t}\n\n\t\tif( i == ( signed )indexArray.size() )\n\t\t\treturn false;\t\t\/\/ Avoid an infinite loop.\n\t}\n\n\treturn true;\n}\n\n\/\/ Polygon.cpp<commit_msg>only check appropriate intersection pairs<commit_after>\/\/ Polygon.cpp\n\n#include \"Polygon.h\"\n#include \"Triangle.h\"\n#include \"IndexTriangle.h\"\n#include \"LineSegment.h\"\n#include \"Surface.h\"\n#include \"AffineTransform.h\"\n#include \"Graph.h\"\n#include \"Exception.h\"\n#include \"ListFunctions.h\"\n\nusing namespace _3DMath;\n\nPolygon::Polygon( void )\n{\n\tvertexArray = new VectorArray();\n\tindexTriangleList = new IndexTriangleList();\n}\n\n\/*virtual*\/ Polygon::~Polygon( void )\n{\n\tdelete vertexArray;\n\tdelete indexTriangleList;\n}\n\nvoid Polygon::Transform( const AffineTransform& transform )\n{\n\ttransform.Transform( *vertexArray );\n}\n\nbool Polygon::GetPlane( Plane& plane ) const\n{\n\tif( vertexArray->size() < 3 )\n\t\treturn false;\n\n\tVector center;\n\tGetCenter( center );\n\n\tVector normal;\n\tnormal.Set( 0.0, 0.0, 0.0 );\n\t\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t{\n\t\t\/\/ This is the Newel method.\n\t\tint j = ( i + 1 ) % vertexArray->size();\n\t\tconst Vector& pointA = ( *vertexArray )[i];\n\t\tconst Vector& pointB = ( *vertexArray )[j];\n\t\tnormal.x += ( pointA.y - pointB.y ) * ( pointA.z + pointB.z );\n\t\tnormal.y += ( pointA.z - pointB.z ) * ( pointA.x + pointB.x );\n\t\tnormal.z += ( pointA.x - pointB.x ) * ( pointA.y + pointB.y );\n\t}\n\n\tplane.SetCenterAndNormal( center, normal );\n\treturn true;\n}\n\nvoid Polygon::GetCenter( Vector& center ) const\n{\n\tcenter.Set( 0.0, 0.0, 0.0 );\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\tcenter.Add( ( *vertexArray )[i] );\n\tcenter.Scale( 1.0 \/ double( vertexArray->size() ) );\n}\n\nbool Polygon::GetTriangleAverageCenter( Vector& center ) const\n{\n\tif( indexTriangleList->size() == 0 )\n\t\treturn false;\n\n\tcenter.Set( 0.0, 0.0, 0.0 );\n\n\tfor( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->cend(); iter++ )\n\t{\n\t\tconst IndexTriangle& indexTriangle = *iter;\n\n\t\tTriangle triangle;\n\t\tindexTriangle.GetTriangle( triangle, vertexArray );\n\n\t\tVector triangleCenter;\n\t\ttriangle.GetCenter( triangleCenter );\n\n\t\tcenter.Add( triangleCenter );\n\t}\n\n\tcenter.Scale( 1.0 \/ double( indexTriangleList->size() ) );\n\treturn true;\n}\n\n\/\/ This assumes that we're properly tessellated.\nbool Polygon::ContainsPoint( const Vector& point, double eps \/*= EPSILON*\/ ) const\n{\n\tfor( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->cend(); iter++ )\n\t{\n\t\tconst IndexTriangle& indexTriangle = *iter;\n\n\t\tTriangle triangle;\n\t\tindexTriangle.GetTriangle( triangle, vertexArray );\n\n\t\tif( triangle.ContainsPoint( point, eps ) )\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n\/\/ Add extraneous points to the polygon until no edge is greater than the given minimum distance.\n\/\/ Of course, since the geometry of the polygon doesn't change, the visible edge-lengths remain the same.\n\/\/ Note that this may invalidate a current tessellation of the polygon.\nvoid Polygon::IncreaseDensity( double minDistance )\n{\n\tint i;\n\n\tdo\n\t{\t\n\t\tfor( i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\t{\n\t\t\tint j = ( i + 1 ) % vertexArray->size();\n\t\t\tLineSegment lineSegment;\n\t\t\tlineSegment.vertex[0] = ( *vertexArray )[i];\n\t\t\tlineSegment.vertex[1] = ( *vertexArray )[j];\n\t\t\tif( lineSegment.Length() > minDistance )\n\t\t\t{\n\t\t\t\tVector midPoint;\n\t\t\t\tlineSegment.Lerp( 0.5, midPoint );\n\t\t\t\tvertexArray->insert( vertexArray->begin() + j, midPoint );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\t\n\t}\n\twhile( i < ( signed )vertexArray->size() );\n}\n\n\/\/ Here we remove any extraneous vertices. These are those that\n\/\/ are co-linear with respect to their immediate adjacencies.\n\/\/ Note that this may invalidate a current tessellation of the polygon.\nvoid Polygon::MinimizeDensity( void )\n{\n\twhile( true )\n\t{\n\t\tint i;\n\t\tfor( i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\t{\n\t\t\tTriangle triangle;\n\t\t\tfor( int j = 0; j < 3; j++ )\n\t\t\t\ttriangle.vertex[j] = ( *vertexArray )[ ( i + j ) % vertexArray->size() ];\n\n\t\t\tif( triangle.Area() < EPSILON )\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif( i == ( signed )vertexArray->size() )\n\t\t\tbreak;\n\n\t\tvertexArray->erase( vertexArray->begin() + ( i + 1 ) % vertexArray->size() );\n\t}\n}\n\nvoid Polygon::GetCopy( Polygon& polygon ) const\n{\n\tpolygon.vertexArray->clear();\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\tpolygon.vertexArray->push_back( ( *vertexArray )[i] );\n\n\tpolygon.indexTriangleList->clear();\n}\n\nbool Polygon::SplitAgainstSurface( const Surface* surface, PolygonList& polygonList, double minDistance, double maxDistance, double eps \/*= EPSILON*\/ ) const\n{\n\tPolygon* polygon = new Polygon();\n\tGetCopy( *polygon );\n\n\tPolygonList polygonQueue;\n\tpolygonQueue.push_back( polygon );\n\n\twhile( polygonQueue.size() > 0 )\n\t{\n\t\tPolygonList::iterator iter = polygonQueue.begin();\n\t\tpolygon = *iter;\n\t\tpolygonQueue.erase( iter );\n\n\t\tPolygon* polygonA = nullptr;\n\t\tPolygon* polygonB = nullptr;\n\n\t\tif( !polygon->SplitInTwoAgainstSurface( surface, polygonA, polygonB, minDistance, maxDistance, eps ) )\n\t\t\tpolygonList.push_back( polygon );\n\t\telse\n\t\t{\n\t\t\tdelete polygon;\n\t\t\tpolygonQueue.push_back( polygonA );\n\t\t\tpolygonQueue.push_back( polygonB );\n\t\t}\n\t}\n\n\tif( polygonQueue.size() > 1 )\n\t\treturn true;\n\n\tFreeList< Polygon >( polygonList );\n\treturn false;\n}\n\nbool Polygon::SplitInTwoAgainstSurface( const Surface* surface, Polygon*& polygonA, Polygon*& polygonB, double minDistance, double maxDistance, double eps )\n{\n\tpolygonA = nullptr;\n\tpolygonB = nullptr;\n\n\tIncreaseDensity( minDistance );\n\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t{\n\t\tint j = ( i + 1 ) % vertexArray->size();\n\n\t\tLineSegment lineSegment;\n\t\tlineSegment.vertex[0] = ( *vertexArray )[i];\n\t\tlineSegment.vertex[1] = ( *vertexArray )[j];\n\n\t\tSurface::Side side[2];\n\t\tside[0] = surface->GetSide( lineSegment.vertex[0], eps );\n\t\tside[1] = surface->GetSide( lineSegment.vertex[1], eps );\n\n\t\tif( ( side[0] == Surface::INSIDE && side[1] == Surface::OUTSIDE ) ||\n\t\t\t( side[1] == Surface::INSIDE && side[0] == Surface::OUTSIDE ) )\n\t\t{\n\t\t\tSurfacePoint* surfacePoint = surface->FindSingleIntersection( lineSegment );\n\t\t\tif( !surfacePoint )\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t{\n\t\t\t\tVector point;\n\t\t\t\tsurfacePoint->GetLocation( point );\n\t\t\t\tvertexArray->insert( vertexArray->begin() + j, point );\n\t\t\t\tdelete surfacePoint;\n\t\t\t}\n\t\t}\n\t}\n\n\tif( !Tessellate() )\n\t\treturn false;\n\n\tstd::vector< int > intersectionArray;\n\tint insideCount = 0;\n\tint outsideCount = 0;\n\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t{\n\t\tSurface::Side side = surface->GetSide( ( *vertexArray )[i] );\n\t\tswitch( side )\n\t\t{\n\t\t\tcase Surface::NEITHER_SIDE:\n\t\t\t{\n\t\t\t\tint j = ( i > 0 ) ? ( i - 1 ) : ( ( signed )vertexArray->size() - 1 );\n\t\t\t\tint k = ( i + 1 ) % vertexArray->size();\n\n\t\t\t\tif( ( surface->GetSide( ( *vertexArray )[j] ) == Surface::INSIDE && surface->GetSide( ( *vertexArray )[k] ) == Surface::OUTSIDE ) ||\n\t\t\t\t\t( surface->GetSide( ( *vertexArray )[k] ) == Surface::INSIDE && surface->GetSide( ( *vertexArray )[j] ) == Surface::OUTSIDE ) )\n\t\t\t\t{\n\t\t\t\t\tintersectionArray.push_back(i);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase Surface::INSIDE:\n\t\t\t{\n\t\t\t\tinsideCount++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase Surface::OUTSIDE:\n\t\t\t{\n\t\t\t\toutsideCount++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif( insideCount == 0 || outsideCount == 0 )\n\t\treturn false;\n\n\t_3DMath::Plane plane;\n\tif( !GetPlane( plane ) )\n\t\treturn false;\n\n\tfor( int i = 0; i < ( signed )intersectionArray.size(); i++ )\n\t{\n\t\tint j = ( i + 1 ) % intersectionArray.size();\n\n\t\tVector pointA = ( *vertexArray )[ intersectionArray[i] ];\n\t\tVector pointB = ( *vertexArray )[ intersectionArray[j] ];\n\n\t\tVectorArray surfacePointArray;\n\t\tbool pathFound = false;\n\n\t\tdouble distance = pointA.Distance( pointB );\n\t\tif( distance < eps )\n\t\t{\n\t\t\tsurfacePointArray.push_back( pointA );\n\t\t\tpathFound = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSurfacePoint* surfacePointA = surface->GetNearestSurfacePoint( pointA );\n\t\t\tSurfacePoint* surfacePointB = surface->GetNearestSurfacePoint( pointB );\n\t\t\tSurfacePoint* surfacePointC = nullptr;\n\n\t\t\tpathFound = surface->FindDirectPath( surfacePointA, surfacePointB, surfacePointArray, maxDistance, &plane );\n\t\t\tif( !pathFound )\n\t\t\t{\n\t\t\t\t\/\/ This is a bit of a hack.\n\t\t\t\tVector center;\n\t\t\t\tGetCenter( center );\n\n\t\t\t\tsurfacePointC = surface->GetNearestSurfacePoint( center );\n\t\t\t\tpathFound = surface->FindDirectPath( surfacePointA, surfacePointC, surfacePointArray, maxDistance, &plane );\n\t\t\t\tif( pathFound )\n\t\t\t\t{\n\t\t\t\t\tsurfacePointArray.pop_back();\n\t\t\t\t\tpathFound = surface->FindDirectPath( surfacePointC, surfacePointB, surfacePointArray, maxDistance, &plane );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdelete surfacePointA;\n\t\t\tdelete surfacePointB;\n\t\t\tdelete surfacePointC;\n\n\t\t\tif( surfacePointArray.size() == 0 )\n\t\t\t\tpathFound = false;\n\t\t}\n\n\t\t\/\/ Does the path along the surface and in the plane of the polygon\n\t\t\/\/ stay within the polygon's area through the whole path?\n\t\tif( pathFound )\n\t\t{\n\t\t\tfor( int k = 0; k < ( signed )surfacePointArray.size(); i++ )\n\t\t\t{\n\t\t\t\tif( !ContainsPoint( surfacePointArray[k] ) )\n\t\t\t\t{\n\t\t\t\t\tpathFound = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( pathFound )\n\t\t\t{\n\t\t\t\tfor( int k = 0; k < ( signed )surfacePointArray.size() - 1; i++ )\n\t\t\t\t{\n\t\t\t\t\tLineSegment lineSegment;\n\t\t\t\t\tlineSegment.vertex[0] = surfacePointArray[k];\n\t\t\t\t\tlineSegment.vertex[1] = surfacePointArray[ k + 1 ];\n\n\t\t\t\t\tVectorList intersectionList;\n\t\t\t\t\tif( GetIntersectionPoints( lineSegment, intersectionList ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tpathFound = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Finally, if we get here, we're ready to split the polygon in two.\n\t\tif( pathFound )\n\t\t{\n\t\t\tpolygonA = new Polygon();\n\t\t\tpolygonB = new Polygon();\n\n\t\t\tint k = ( intersectionArray[i] + 1 ) % vertexArray->size();\n\t\t\twhile( k != intersectionArray[j] )\n\t\t\t{\n\t\t\t\tpolygonA->vertexArray->push_back( ( *vertexArray )[k] );\n\t\t\t\tk = ( k + 1 ) % vertexArray->size();\n\t\t\t}\n\n\t\t\tk = ( intersectionArray[j] + 1 ) % vertexArray->size();\n\t\t\twhile( k != intersectionArray[i] )\n\t\t\t{\n\t\t\t\tpolygonB->vertexArray->push_back( ( *vertexArray )[k] );\n\t\t\t\tk = ( k + 1 ) % vertexArray->size();\n\t\t\t}\n\n\t\t\tfor( int k = 0; k < ( signed )surfacePointArray.size(); k++ )\n\t\t\t{\n\t\t\t\tint l = signed( surfacePointArray.size() ) - 1 - k;\n\t\t\t\tpolygonA->vertexArray->push_back( surfacePointArray[l] );\n\t\t\t\tpolygonB->vertexArray->push_back( surfacePointArray[k] );\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool Polygon::GetIntersectionPoints( const LineSegment& lineSegment, VectorList& intersectionList ) const\n{\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t{\n\t\tint j = ( i + 1 ) % vertexArray->size();\n\n\t\tLineSegment edge;\n\t\tedge.vertex[0] = ( *vertexArray )[i];\n\t\tedge.vertex[1] = ( *vertexArray )[j];\n\n\t\tVector intersectionPoint;\n\t\tif( edge.IntersectsWith( lineSegment, &intersectionPoint ) )\n\t\t\tintersectionList.push_back( intersectionPoint );\n\t}\n\n\treturn( intersectionList.size() > 0 ? true : false );\n}\n\ndouble Polygon::GetArea( void ) const\n{\n\tdouble totalArea = 0.0;\n\n\tfor( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->end(); iter++ )\n\t{\n\t\tconst IndexTriangle& indexTriangle = *iter;\n\t\tTriangle triangle;\n\t\tindexTriangle.GetTriangle( triangle, vertexArray );\n\t\ttotalArea += triangle.Area();\n\t}\n\n\treturn totalArea;\n}\n\nbool Polygon::Tessellate( void ) const\n{\n\tPlane plane;\n\tif( !GetPlane( plane ) )\n\t\treturn false;\n\n\tindexTriangleList->clear();\n\n\tstd::vector< int > indexArray;\n\tfor( int i = 0; i < ( signed )vertexArray->size(); i++ )\n\t\tindexArray.push_back(i);\n\n\twhile( indexArray.size() > 2 )\n\t{\n\t\tint i;\n\t\tfor( i = 0; i < ( signed )indexArray.size(); i++ )\n\t\t{\n\t\t\tIndexTriangle indexTriangle(\n\t\t\t\t\tindexArray[i],\n\t\t\t\t\tindexArray[ ( i + 1 ) % indexArray.size() ],\n\t\t\t\t\tindexArray[ ( i + 2 ) % indexArray.size() ] );\n\n\t\t\tTriangle triangle;\n\t\t\tindexTriangle.GetTriangle( triangle, vertexArray );\n\n\t\t\tVector edge[2];\n\t\t\tedge[0].Subtract( triangle.vertex[1], triangle.vertex[0] );\n\t\t\tedge[1].Subtract( triangle.vertex[2], triangle.vertex[1] );\n\n\t\t\tVector cross;\n\t\t\tcross.Cross( edge[0], edge[1] );\n\t\t\tdouble dot = cross.Dot( plane.normal );\n\t\t\tif( dot < 0.0 )\n\t\t\t\tcontinue;\n\n\t\t\tint j;\n\t\t\tfor( j = 0; j < ( signed )indexArray.size(); j++ )\n\t\t\t{\n\t\t\t\tif( j == i || j == ( i + 1 ) % indexArray.size() || j == ( i + 2 ) % indexArray.size() )\n\t\t\t\t\tcontinue;\n\t\t\t\tif( triangle.ContainsPoint( ( *vertexArray )[ indexArray[j] ] ) )\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif( j < ( signed )indexArray.size() )\n\t\t\t\tcontinue;\n\n\t\t\tindexTriangleList->push_back( indexTriangle );\n\t\t\tindexArray.erase( indexArray.begin() + ( i + 1 ) % indexArray.size() );\n\t\t\tbreak;\n\t\t}\n\n\t\tif( i == ( signed )indexArray.size() )\n\t\t\treturn false;\t\t\/\/ Avoid an infinite loop.\n\t}\n\n\treturn true;\n}\n\n\/\/ Polygon.cpp<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"IncrementalParser.h\"\n#include \"ASTNodeEraser.h\"\n\n#include \"ASTDumper.h\"\n#include \"ChainedConsumer.h\"\n#include \"DeclExtractor.h\"\n#include \"DynamicLookup.h\"\n#include \"ValuePrinterSynthesizer.h\"\n#include \"cling\/Interpreter\/CIFactory.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclGroup.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/CodeGen\/ModuleBuilder.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Serialization\/ASTWriter.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_os_ostream.h\"\n\n#include <ctime>\n#include <iostream>\n#include <stdio.h>\n#include <sstream>\n\nusing namespace clang;\n\nnamespace cling {\n IncrementalParser::IncrementalParser(Interpreter* interp,\n int argc, const char* const *argv,\n const char* llvmdir):\n m_Interpreter(interp),\n m_DynamicLookupEnabled(false),\n m_Consumer(0),\n m_SyntaxOnly(false)\n {\n CompilerInstance* CI\n = CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer(\"\", \"CLING\"),\n argc, argv, llvmdir);\n assert(CI && \"CompilerInstance is (null)!\");\n m_CI.reset(CI);\n m_SyntaxOnly\n = CI->getFrontendOpts().ProgramAction == clang::frontend::ParseSyntaxOnly;\n\n CreateSLocOffsetGenerator();\n\n m_Consumer = dyn_cast<ChainedConsumer>(&CI->getASTConsumer());\n assert(m_Consumer && \"Expected ChainedConsumer!\");\n \/\/ Add consumers to the ChainedConsumer, which owns them\n EvaluateTSynthesizer* ES = new EvaluateTSynthesizer(interp);\n m_Consumer->Add(ChainedConsumer::kEvaluateTSynthesizer, ES);\n\n DeclExtractor* DE = new DeclExtractor();\n m_Consumer->Add(ChainedConsumer::kDeclExtractor, DE);\n\n ValuePrinterSynthesizer* VPS = new ValuePrinterSynthesizer(interp);\n m_Consumer->Add(ChainedConsumer::kValuePrinterSynthesizer, VPS);\n m_Consumer->Add(ChainedConsumer::kASTDumper, new ASTDumper());\n if (!m_SyntaxOnly) {\n CodeGenerator* CG = CreateLLVMCodeGen(CI->getDiagnostics(),\n \"cling input\",\n CI->getCodeGenOpts(),\n *m_Interpreter->getLLVMContext()\n );\n assert(CG && \"No CodeGen?!\");\n m_Consumer->Add(ChainedConsumer::kCodeGenerator, CG);\n }\n m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema(),\n false \/*skipFuncBodies*\/));\n CI->getPreprocessor().EnterMainSourceFile();\n \/\/ Initialize the parser after we have entered the main source file.\n m_Parser->Initialize();\n \/\/ Perform initialization that occurs after the parser has been initialized\n \/\/ but before it parses anything. Initializes the consumers too.\n CI->getSema().Initialize();\n }\n\n void IncrementalParser::beginTransaction() {\n Transaction* NewCurT = new Transaction();\n Transaction* OldCurT = m_Consumer->getTransaction();\n m_Consumer->setTransaction(NewCurT);\n \/\/ If we are in the middle of transaction and we see another begin \n \/\/ transaction - it must be nested transaction.\n if (OldCurT && !OldCurT->isCompleted()) {\n OldCurT->addNestedTransaction(NewCurT);\n return;\n }\n\n m_Transactions.push_back(NewCurT);\n }\n\n void IncrementalParser::endTransaction() const {\n Transaction* CurT = m_Consumer->getTransaction();\n CurT->setCompleted();\n const DiagnosticsEngine& Diags = getCI()->getSema().getDiagnostics();\n\n \/\/TODO: Make the enum orable.\n if (Diags.getNumWarnings() > 0)\n CurT->setIssuedDiags(Transaction::kWarnings);\n\n if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())\n CurT->setIssuedDiags(Transaction::kErrors);\n\n \n if (CurT->isNestedTransaction()) {\n assert(!CurT->getParent()->isCompleted() \n && \"Parent transaction completed!?\");\n CurT = m_Consumer->getTransaction()->getParent();\n }\n }\n\n void IncrementalParser::commitTransaction(const Transaction* T) const {\n assert(T->isCompleted() && \"Transaction not ended!?\");\n const Transaction* OldT = m_Consumer->getTransaction();\n m_Consumer->setTransaction(T);\n commitCurrentTransaction();\n m_Consumer->setTransaction(OldT);\n }\n\n void IncrementalParser::commitCurrentTransaction() const {\n Transaction* CurT = m_Consumer->getTransaction();\n assert(CurT->isCompleted() && \"Transaction not ended!?\");\n\n \/\/ Check for errors...\n if (CurT->getIssuedDiags() == Transaction::kErrors) {\n rollbackTransaction(CurT);\n return;\n }\n\n \/\/ We are sure it's safe to pipe it through\n for (Transaction::const_iterator I = CurT->decls_begin(), \n E = CurT->decls_end(); I != E; ++I) {\n \/\/ if an error was seen somewhere in the consumer chain rollback \n if (!m_Consumer->HandleTopLevelDecl(*I)) {\n rollbackTransaction(CurT);\n return;\n } \n }\n\n \/\/ Pull all template instantiations in that came from the consumers.\n getCI()->getSema().PerformPendingInstantiations();\n\n m_Consumer->HandleTranslationUnit(getCI()->getASTContext());\n CurT->setState(Transaction::kCommitted);\n }\n\n void IncrementalParser::rollbackTransaction(Transaction* T) const {\n ASTNodeEraser NodeEraser(&getCI()->getSema());\n\n for (Transaction::const_reverse_iterator I = T->rdecls_begin(),\n E = T->rdecls_end(); I != E; ++I) {\n const DeclGroupRef& DGR = (*I);\n\n for (DeclGroupRef::const_iterator\n Di = DGR.end() - 1, E = DGR.begin() - 1; Di != E; --Di) {\n DeclContext* DC = (*Di)->getDeclContext();\n assert(DC == (*Di)->getLexicalDeclContext() && \\\n \"Cannot handle that yet\");\n\n \/\/ Get rid of the declaration. If the declaration has name we should\n \/\/ heal the lookup tables as well\n bool Successful = NodeEraser.RevertDecl(*Di);\n assert(Successful && \"Cannot handle that yet!\");\n }\n }\n\n T->setState(Transaction::kRolledBack);\n }\n \n\n \/\/ Each input line is contained in separate memory buffer. The SourceManager\n \/\/ assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry\n \/\/ for the MemoryBuffer's FileID. That in turn is problem because invalid\n \/\/ SourceLocations are given to the diagnostics. Thus the diagnostics cannot\n \/\/ order the overloads, for example\n \/\/\n \/\/ Our work-around is creating a virtual file, which doesn't exist on the disk\n \/\/ with enormous size (no allocation is done). That file has valid FileEntry\n \/\/ and so on... We use it for generating valid SourceLocations with valid\n \/\/ offsets so that it doesn't cause any troubles to the diagnostics.\n \/\/\n \/\/ +---------------------+\n \/\/ | Main memory buffer |\n \/\/ +---------------------+\n \/\/ | Virtual file SLoc |\n \/\/ | address space |<-----------------+\n \/\/ | ... |<------------+ |\n \/\/ | ... | | |\n \/\/ | ... |<----+ | |\n \/\/ | ... | | | |\n \/\/ +~~~~~~~~~~~~~~~~~~~~~+ | | |\n \/\/ | input_line_1 | ....+.......+..--+\n \/\/ +---------------------+ | |\n \/\/ | input_line_2 | ....+.....--+\n \/\/ +---------------------+ |\n \/\/ | ... | |\n \/\/ +---------------------+ |\n \/\/ | input_line_N | ..--+\n \/\/ +---------------------+\n \/\/\n void IncrementalParser::CreateSLocOffsetGenerator() {\n SourceManager& SM = getCI()->getSourceManager();\n FileManager& FM = SM.getFileManager();\n const FileEntry* FE\n = FM.getVirtualFile(\"Interactrive\/InputLineIncluder\", 1U << 15U, time(0));\n m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);\n\n assert(!m_VirtualFileID.isInvalid() && \"No VirtualFileID created?\");\n }\n\n IncrementalParser::~IncrementalParser() {\n if (GetCodeGenerator()) {\n GetCodeGenerator()->ReleaseModule();\n }\n }\n\n void IncrementalParser::Initialize() {\n CompilationOptions CO;\n CO.DeclarationExtraction = 0;\n CO.ValuePrinting = 0;\n }\n\n IncrementalParser::EParseResult\n IncrementalParser::Compile(llvm::StringRef input,\n const CompilationOptions& Opts) {\n\n m_Consumer->pushCompilationOpts(Opts);\n EParseResult Result = Compile(input);\n m_Consumer->popCompilationOpts();\n\n return Result;\n }\n\n void IncrementalParser::Parse(llvm::StringRef input,\n llvm::SmallVector<DeclGroupRef, 4>& DGRs) {\n\n beginTransaction();\n Parse(input);\n endTransaction();\n const Transaction* T = m_Consumer->getTransaction();\n DGRs.append(T->decls_begin(), T->decls_end());\n }\n\n IncrementalParser::EParseResult\n IncrementalParser::Compile(llvm::StringRef input) {\n \/\/ Just in case when Parse is called, we want to complete the transaction\n \/\/ coming from parse and then start new one.\n \/\/m_Consumer->HandleTranslationUnit(getCI()->getASTContext());\n\n \/\/ Reset the module builder to clean up global initializers, c'tors, d'tors:\n if (GetCodeGenerator()) {\n GetCodeGenerator()->Initialize(getCI()->getASTContext());\n }\n\n beginTransaction();\n EParseResult Result = Parse(input);\n endTransaction();\n\n \/\/ Check for errors coming from our custom consumers.\n DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();\n DClient.BeginSourceFile(getCI()->getLangOpts(),\n &getCI()->getPreprocessor());\n commitCurrentTransaction();\n\n DClient.EndSourceFile();\n m_CI->getDiagnostics().Reset();\n\n if (!m_SyntaxOnly) {\n m_Interpreter->runStaticInitializersOnce();\n }\n\n return Result;\n }\n\n \/\/ Add the input to the memory buffer, parse it, and add it to the AST.\n IncrementalParser::EParseResult\n IncrementalParser::Parse(llvm::StringRef input) {\n if (input.empty()) return IncrementalParser::kSuccess;\n\n Preprocessor& PP = m_CI->getPreprocessor();\n DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();\n\n if (!PP.getCurrentLexer()) {\n PP.EnterSourceFile(m_CI->getSourceManager().getMainFileID(),\n 0, SourceLocation());\n }\n PP.enableIncrementalProcessing();\n\n DClient.BeginSourceFile(m_CI->getLangOpts(), &PP);\n\n std::ostringstream source_name;\n source_name << \"input_line_\" << (m_MemoryBuffer.size() + 1);\n llvm::MemoryBuffer* MB\n = llvm::MemoryBuffer::getMemBufferCopy(input, source_name.str());\n m_MemoryBuffer.push_back(MB);\n SourceManager& SM = getCI()->getSourceManager();\n\n \/\/ Create SourceLocation, which will allow clang to order the overload\n \/\/ candidates for example\n SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID);\n NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffer.size() + 1);\n\n \/\/ Create FileID for the current buffer\n FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffer.back(),\n \/*LoadedID*\/0,\n \/*LoadedOffset*\/0, NewLoc);\n\n PP.EnterSourceFile(FID, 0, NewLoc);\n\n Parser::DeclGroupPtrTy ADecl;\n\n while (!m_Parser->ParseTopLevelDecl(ADecl)) {\n \/\/ If we got a null return and something *was* parsed, ignore it. This\n \/\/ is due to a top-level semicolon, an action override, or a parse error\n \/\/ skipping something.\n if (ADecl)\n m_Consumer->HandleTopLevelDecl(ADecl.getAsVal<DeclGroupRef>());\n };\n\n \/\/ Process any TopLevelDecls generated by #pragma weak.\n for (llvm::SmallVector<Decl*,2>::iterator\n I = getCI()->getSema().WeakTopLevelDecls().begin(),\n E = getCI()->getSema().WeakTopLevelDecls().end(); I != E; ++I) {\n m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));\n }\n\n getCI()->getSema().PerformPendingInstantiations();\n\n DClient.EndSourceFile();\n\n PP.enableIncrementalProcessing(false);\n\n DiagnosticsEngine& Diag = getCI()->getSema().getDiagnostics();\n if (Diag.hasErrorOccurred())\n return IncrementalParser::kFailed;\n else if (Diag.getNumWarnings())\n return IncrementalParser::kSuccessWithWarnings;\n\n return IncrementalParser::kSuccess;\n }\n\n void IncrementalParser::enableDynamicLookup(bool value) {\n m_DynamicLookupEnabled = value;\n Sema& S = m_CI->getSema();\n if (isDynamicLookupEnabled()) {\n assert(!S.ExternalSource && \"Already set Sema ExternalSource\");\n S.ExternalSource = new DynamicIDHandler(&S);\n }\n else {\n delete S.ExternalSource;\n S.ExternalSource = 0;\n }\n }\n\n CodeGenerator* IncrementalParser::GetCodeGenerator() const {\n return\n (CodeGenerator*)m_Consumer->getConsumer(ChainedConsumer::kCodeGenerator);\n }\n\n} \/\/ namespace cling\n<commit_msg>Take care of the leaking transactions in m_Transactions<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"IncrementalParser.h\"\n#include \"ASTNodeEraser.h\"\n\n#include \"ASTDumper.h\"\n#include \"ChainedConsumer.h\"\n#include \"DeclExtractor.h\"\n#include \"DynamicLookup.h\"\n#include \"ValuePrinterSynthesizer.h\"\n#include \"cling\/Interpreter\/CIFactory.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclGroup.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/CodeGen\/ModuleBuilder.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Serialization\/ASTWriter.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_os_ostream.h\"\n\n#include <ctime>\n#include <iostream>\n#include <stdio.h>\n#include <sstream>\n\nusing namespace clang;\n\nnamespace cling {\n IncrementalParser::IncrementalParser(Interpreter* interp,\n int argc, const char* const *argv,\n const char* llvmdir):\n m_Interpreter(interp),\n m_DynamicLookupEnabled(false),\n m_Consumer(0),\n m_SyntaxOnly(false)\n {\n CompilerInstance* CI\n = CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer(\"\", \"CLING\"),\n argc, argv, llvmdir);\n assert(CI && \"CompilerInstance is (null)!\");\n m_CI.reset(CI);\n m_SyntaxOnly\n = CI->getFrontendOpts().ProgramAction == clang::frontend::ParseSyntaxOnly;\n\n CreateSLocOffsetGenerator();\n\n m_Consumer = dyn_cast<ChainedConsumer>(&CI->getASTConsumer());\n assert(m_Consumer && \"Expected ChainedConsumer!\");\n \/\/ Add consumers to the ChainedConsumer, which owns them\n EvaluateTSynthesizer* ES = new EvaluateTSynthesizer(interp);\n m_Consumer->Add(ChainedConsumer::kEvaluateTSynthesizer, ES);\n\n DeclExtractor* DE = new DeclExtractor();\n m_Consumer->Add(ChainedConsumer::kDeclExtractor, DE);\n\n ValuePrinterSynthesizer* VPS = new ValuePrinterSynthesizer(interp);\n m_Consumer->Add(ChainedConsumer::kValuePrinterSynthesizer, VPS);\n m_Consumer->Add(ChainedConsumer::kASTDumper, new ASTDumper());\n if (!m_SyntaxOnly) {\n CodeGenerator* CG = CreateLLVMCodeGen(CI->getDiagnostics(),\n \"cling input\",\n CI->getCodeGenOpts(),\n *m_Interpreter->getLLVMContext()\n );\n assert(CG && \"No CodeGen?!\");\n m_Consumer->Add(ChainedConsumer::kCodeGenerator, CG);\n }\n m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema(),\n false \/*skipFuncBodies*\/));\n CI->getPreprocessor().EnterMainSourceFile();\n \/\/ Initialize the parser after we have entered the main source file.\n m_Parser->Initialize();\n \/\/ Perform initialization that occurs after the parser has been initialized\n \/\/ but before it parses anything. Initializes the consumers too.\n CI->getSema().Initialize();\n }\n\n void IncrementalParser::beginTransaction() {\n Transaction* NewCurT = new Transaction();\n Transaction* OldCurT = m_Consumer->getTransaction();\n m_Consumer->setTransaction(NewCurT);\n \/\/ If we are in the middle of transaction and we see another begin \n \/\/ transaction - it must be nested transaction.\n if (OldCurT && !OldCurT->isCompleted()) {\n OldCurT->addNestedTransaction(NewCurT);\n return;\n }\n\n m_Transactions.push_back(NewCurT);\n }\n\n void IncrementalParser::endTransaction() const {\n Transaction* CurT = m_Consumer->getTransaction();\n CurT->setCompleted();\n const DiagnosticsEngine& Diags = getCI()->getSema().getDiagnostics();\n\n \/\/TODO: Make the enum orable.\n if (Diags.getNumWarnings() > 0)\n CurT->setIssuedDiags(Transaction::kWarnings);\n\n if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())\n CurT->setIssuedDiags(Transaction::kErrors);\n\n \n if (CurT->isNestedTransaction()) {\n assert(!CurT->getParent()->isCompleted() \n && \"Parent transaction completed!?\");\n CurT = m_Consumer->getTransaction()->getParent();\n }\n }\n\n void IncrementalParser::commitTransaction(const Transaction* T) const {\n assert(T->isCompleted() && \"Transaction not ended!?\");\n const Transaction* OldT = m_Consumer->getTransaction();\n m_Consumer->setTransaction(T);\n commitCurrentTransaction();\n m_Consumer->setTransaction(OldT);\n }\n\n void IncrementalParser::commitCurrentTransaction() const {\n Transaction* CurT = m_Consumer->getTransaction();\n assert(CurT->isCompleted() && \"Transaction not ended!?\");\n\n \/\/ Check for errors...\n if (CurT->getIssuedDiags() == Transaction::kErrors) {\n rollbackTransaction(CurT);\n return;\n }\n\n \/\/ We are sure it's safe to pipe it through\n for (Transaction::const_iterator I = CurT->decls_begin(), \n E = CurT->decls_end(); I != E; ++I) {\n \/\/ if an error was seen somewhere in the consumer chain rollback \n if (!m_Consumer->HandleTopLevelDecl(*I)) {\n rollbackTransaction(CurT);\n return;\n } \n }\n\n \/\/ Pull all template instantiations in that came from the consumers.\n getCI()->getSema().PerformPendingInstantiations();\n\n m_Consumer->HandleTranslationUnit(getCI()->getASTContext());\n CurT->setState(Transaction::kCommitted);\n }\n\n void IncrementalParser::rollbackTransaction(Transaction* T) const {\n ASTNodeEraser NodeEraser(&getCI()->getSema());\n\n for (Transaction::const_reverse_iterator I = T->rdecls_begin(),\n E = T->rdecls_end(); I != E; ++I) {\n const DeclGroupRef& DGR = (*I);\n\n for (DeclGroupRef::const_iterator\n Di = DGR.end() - 1, E = DGR.begin() - 1; Di != E; --Di) {\n DeclContext* DC = (*Di)->getDeclContext();\n assert(DC == (*Di)->getLexicalDeclContext() && \\\n \"Cannot handle that yet\");\n\n \/\/ Get rid of the declaration. If the declaration has name we should\n \/\/ heal the lookup tables as well\n bool Successful = NodeEraser.RevertDecl(*Di);\n assert(Successful && \"Cannot handle that yet!\");\n }\n }\n\n T->setState(Transaction::kRolledBack);\n }\n \n\n \/\/ Each input line is contained in separate memory buffer. The SourceManager\n \/\/ assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry\n \/\/ for the MemoryBuffer's FileID. That in turn is problem because invalid\n \/\/ SourceLocations are given to the diagnostics. Thus the diagnostics cannot\n \/\/ order the overloads, for example\n \/\/\n \/\/ Our work-around is creating a virtual file, which doesn't exist on the disk\n \/\/ with enormous size (no allocation is done). That file has valid FileEntry\n \/\/ and so on... We use it for generating valid SourceLocations with valid\n \/\/ offsets so that it doesn't cause any troubles to the diagnostics.\n \/\/\n \/\/ +---------------------+\n \/\/ | Main memory buffer |\n \/\/ +---------------------+\n \/\/ | Virtual file SLoc |\n \/\/ | address space |<-----------------+\n \/\/ | ... |<------------+ |\n \/\/ | ... | | |\n \/\/ | ... |<----+ | |\n \/\/ | ... | | | |\n \/\/ +~~~~~~~~~~~~~~~~~~~~~+ | | |\n \/\/ | input_line_1 | ....+.......+..--+\n \/\/ +---------------------+ | |\n \/\/ | input_line_2 | ....+.....--+\n \/\/ +---------------------+ |\n \/\/ | ... | |\n \/\/ +---------------------+ |\n \/\/ | input_line_N | ..--+\n \/\/ +---------------------+\n \/\/\n void IncrementalParser::CreateSLocOffsetGenerator() {\n SourceManager& SM = getCI()->getSourceManager();\n FileManager& FM = SM.getFileManager();\n const FileEntry* FE\n = FM.getVirtualFile(\"Interactrive\/InputLineIncluder\", 1U << 15U, time(0));\n m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);\n\n assert(!m_VirtualFileID.isInvalid() && \"No VirtualFileID created?\");\n }\n\n IncrementalParser::~IncrementalParser() {\n if (GetCodeGenerator()) {\n GetCodeGenerator()->ReleaseModule();\n }\n for (unsigned i = 0; i < m_Transactions.size(); ++i)\n delete m_Transactions[i];\n }\n\n void IncrementalParser::Initialize() {\n CompilationOptions CO;\n CO.DeclarationExtraction = 0;\n CO.ValuePrinting = 0;\n }\n\n IncrementalParser::EParseResult\n IncrementalParser::Compile(llvm::StringRef input,\n const CompilationOptions& Opts) {\n\n m_Consumer->pushCompilationOpts(Opts);\n EParseResult Result = Compile(input);\n m_Consumer->popCompilationOpts();\n\n return Result;\n }\n\n void IncrementalParser::Parse(llvm::StringRef input,\n llvm::SmallVector<DeclGroupRef, 4>& DGRs) {\n\n beginTransaction();\n Parse(input);\n endTransaction();\n const Transaction* T = m_Consumer->getTransaction();\n DGRs.append(T->decls_begin(), T->decls_end());\n }\n\n IncrementalParser::EParseResult\n IncrementalParser::Compile(llvm::StringRef input) {\n \/\/ Just in case when Parse is called, we want to complete the transaction\n \/\/ coming from parse and then start new one.\n \/\/m_Consumer->HandleTranslationUnit(getCI()->getASTContext());\n\n \/\/ Reset the module builder to clean up global initializers, c'tors, d'tors:\n if (GetCodeGenerator()) {\n GetCodeGenerator()->Initialize(getCI()->getASTContext());\n }\n\n beginTransaction();\n EParseResult Result = Parse(input);\n endTransaction();\n\n \/\/ Check for errors coming from our custom consumers.\n DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();\n DClient.BeginSourceFile(getCI()->getLangOpts(),\n &getCI()->getPreprocessor());\n commitCurrentTransaction();\n\n DClient.EndSourceFile();\n m_CI->getDiagnostics().Reset();\n\n if (!m_SyntaxOnly) {\n m_Interpreter->runStaticInitializersOnce();\n }\n\n return Result;\n }\n\n \/\/ Add the input to the memory buffer, parse it, and add it to the AST.\n IncrementalParser::EParseResult\n IncrementalParser::Parse(llvm::StringRef input) {\n if (input.empty()) return IncrementalParser::kSuccess;\n\n Preprocessor& PP = m_CI->getPreprocessor();\n DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();\n\n if (!PP.getCurrentLexer()) {\n PP.EnterSourceFile(m_CI->getSourceManager().getMainFileID(),\n 0, SourceLocation());\n }\n PP.enableIncrementalProcessing();\n\n DClient.BeginSourceFile(m_CI->getLangOpts(), &PP);\n\n std::ostringstream source_name;\n source_name << \"input_line_\" << (m_MemoryBuffer.size() + 1);\n llvm::MemoryBuffer* MB\n = llvm::MemoryBuffer::getMemBufferCopy(input, source_name.str());\n m_MemoryBuffer.push_back(MB);\n SourceManager& SM = getCI()->getSourceManager();\n\n \/\/ Create SourceLocation, which will allow clang to order the overload\n \/\/ candidates for example\n SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID);\n NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffer.size() + 1);\n\n \/\/ Create FileID for the current buffer\n FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffer.back(),\n \/*LoadedID*\/0,\n \/*LoadedOffset*\/0, NewLoc);\n\n PP.EnterSourceFile(FID, 0, NewLoc);\n\n Parser::DeclGroupPtrTy ADecl;\n\n while (!m_Parser->ParseTopLevelDecl(ADecl)) {\n \/\/ If we got a null return and something *was* parsed, ignore it. This\n \/\/ is due to a top-level semicolon, an action override, or a parse error\n \/\/ skipping something.\n if (ADecl)\n m_Consumer->HandleTopLevelDecl(ADecl.getAsVal<DeclGroupRef>());\n };\n\n \/\/ Process any TopLevelDecls generated by #pragma weak.\n for (llvm::SmallVector<Decl*,2>::iterator\n I = getCI()->getSema().WeakTopLevelDecls().begin(),\n E = getCI()->getSema().WeakTopLevelDecls().end(); I != E; ++I) {\n m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));\n }\n\n getCI()->getSema().PerformPendingInstantiations();\n\n DClient.EndSourceFile();\n\n PP.enableIncrementalProcessing(false);\n\n DiagnosticsEngine& Diag = getCI()->getSema().getDiagnostics();\n if (Diag.hasErrorOccurred())\n return IncrementalParser::kFailed;\n else if (Diag.getNumWarnings())\n return IncrementalParser::kSuccessWithWarnings;\n\n return IncrementalParser::kSuccess;\n }\n\n void IncrementalParser::enableDynamicLookup(bool value) {\n m_DynamicLookupEnabled = value;\n Sema& S = m_CI->getSema();\n if (isDynamicLookupEnabled()) {\n assert(!S.ExternalSource && \"Already set Sema ExternalSource\");\n S.ExternalSource = new DynamicIDHandler(&S);\n }\n else {\n delete S.ExternalSource;\n S.ExternalSource = 0;\n }\n }\n\n CodeGenerator* IncrementalParser::GetCodeGenerator() const {\n return\n (CodeGenerator*)m_Consumer->getConsumer(ChainedConsumer::kCodeGenerator);\n }\n\n} \/\/ namespace cling\n<|endoftext|>"} {"text":"<commit_before>\/* * This file is part of meego-keyboard *\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n * Contact: Nokia Corporation (directui@nokia.com)\n *\n * If you have questions regarding the use of this file, please contact\n * Nokia at directui@nokia.com.\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\n#include \"mimtoolbar.h\"\n#include \"layoutsmanager.h\"\n#include \"mhardwarekeyboard.h\"\n#include \"mvirtualkeyboardstyle.h\"\n#include \"mtoolbarbutton.h\"\n#include \"mtoolbarlabel.h\"\n\n#include <mtoolbardata.h>\n#include <mtoolbaritem.h>\n#include <mtoolbarrow.h>\n#include <mtoolbarlayout.h>\n\n#include <MNamespace>\n#include <MButton>\n#include <QKeySequence>\n#include <QGraphicsLinearLayout>\n#include <QDebug>\n#include <MSceneManager>\n#include <mplainwindow.h>\n#include <mreactionmap.h>\n#include <MScalableImage>\n\nnamespace\n{\n const QString ObjectNameToolbar(\"MImToolbar\");\n const QString ObjectNameToolbarLeft(\"VirtualKeyboardToolbarLeft\");\n const QString ObjectNameToolbarRight(\"VirtualKeyboardToolbarRight\");\n const QString NameToolbarCopyPasteButton(\"VirtualKeyboardCopyPasteButton\");\n};\n\nMImToolbar::MImToolbar(QGraphicsWidget *parent)\n : MStylableWidget(parent),\n textSelected(false),\n copyPasteItem(new MToolbarItem(NameToolbarCopyPasteButton, MInputMethod::ItemButton)),\n leftBar(true, this),\n rightBar(true, this),\n shiftState(ModifierClearState),\n fnState(ModifierClearState)\n{\n leftBar.setObjectName(ObjectNameToolbarLeft);\n rightBar.setObjectName(ObjectNameToolbarRight);\n setObjectName(ObjectNameToolbar);\n\n setupLayout();\n\n connect(this, SIGNAL(visibleChanged()), this, SLOT(updateVisibility()));\n connect(MTheme::instance(), SIGNAL(themeChangeCompleted()),\n this, SLOT(updateFromStyle()));\n}\n\nMImToolbar::~MImToolbar()\n{\n}\n\nvoid MImToolbar::setupLayout()\n{\n QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout(Qt::Vertical, this);\n mainLayout->setContentsMargins(0, 0, 0, 0);\n\n QGraphicsLinearLayout *rowLayout = new QGraphicsLinearLayout(Qt::Horizontal, mainLayout);\n\n setupRowLayout(rowLayout, &leftBar, &rightBar);\n mainLayout->insertItem(0, rowLayout);\n\n resize(geometry().width(), layout()->preferredHeight());\n}\n\nQRegion MImToolbar::region() const\n{\n QRegion region;\n\n if (isVisible()) {\n if (currentToolbar && currentToolbar->isCustom()) {\n region = QRegion(mapRectToScene(rect()).toRect());\n } else if (rightBar.isVisible()) {\n region = QRegion(mapRectToScene(rightBar.geometry()).toRect());\n }\n }\n return region;\n}\n\nvoid MImToolbar::handleButtonClick(MToolbarItem *item)\n{\n if (!item || item->type() != MInputMethod::ItemButton)\n return;\n\n foreach(QSharedPointer<const MToolbarItemAction> action, item->actions()) {\n switch (action->type()) {\n case MInputMethod::ActionSendKeySequence:\n sendKeySequence(action->keys());\n break;\n case MInputMethod::ActionSendString:\n sendStringRequest(action->text());\n break;\n case MInputMethod::ActionSendCommand:\n \/\/TODO:not support yet\n break;\n case MInputMethod::ActionCopy:\n emit copyPasteRequest(InputMethodCopy);\n break;\n case MInputMethod::ActionPaste:\n emit copyPasteRequest(InputMethodPaste);\n break;\n case MInputMethod::ActionShowGroup:\n showGroup(action->group());\n break;\n case MInputMethod::ActionHideGroup:\n hideGroup(action->group());\n break;\n case MInputMethod::ActionClose:\n emit closeKeyboardRequest();\n break;\n case MInputMethod::ActionUndefined:\n case MInputMethod::ActionCopyPaste:\n break;\n }\n }\n}\n\nvoid MImToolbar::setSelectionStatus(bool selection)\n{\n if (textSelected != selection) {\n textSelected = selection;\n if (isVisible())\n updateVisibility();\n }\n}\n\nvoid MImToolbar::updateVisibility()\n{\n if (currentToolbar) {\n foreach (const QSharedPointer<MToolbarItem> item, currentToolbar->items())\n {\n if ((item->showOn() == MInputMethod::VisibleAlways)\n || (textSelected && item->showOn() == MInputMethod::VisibleWhenSelectingText)\n || (!textSelected && item->hideOn() == MInputMethod::VisibleWhenSelectingText)) {\n item->setVisible(true);\n }\n\n if ((!textSelected && item->showOn() == MInputMethod::VisibleWhenSelectingText)\n || (textSelected && item->hideOn() == MInputMethod::VisibleWhenSelectingText)) {\n item->setVisible(false);\n }\n }\n }\n arrangeWidgets();\n}\n\nvoid MImToolbar::updateFromStyle()\n{\n prepareGeometryChange(); \/\/ notify scene about changes in bounding rect\n}\n\nvoid MImToolbar::loadCustomWidgets()\n{\n if (!currentToolbar) {\n return;\n }\n\n const M::Orientation orientation = MPlainWindow::instance()->sceneManager()->orientation();\n QSharedPointer<const MToolbarLayout> layout = currentToolbar->layout(orientation);\n QGraphicsLinearLayout *mainLayout = static_cast<QGraphicsLinearLayout*>(this->layout());\n\n if (!mainLayout) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n QList<QSharedPointer<const MToolbarRow> > rows = layout->rows();\n\n \/\/create additional rows if necessary\n for (int n = 0; n < rows.count() - 1; ++n) {\n QSharedPointer<const MToolbarRow> row = rows[n];\n QGraphicsLinearLayout *rowLayout = new QGraphicsLinearLayout(Qt::Horizontal, mainLayout);\n WidgetBar *leftWidget = new WidgetBar(true, this);\n WidgetBar *rightWidget = new WidgetBar(true, this);\n\n leftWidget->setObjectName(ObjectNameToolbarLeft);\n rightWidget->setObjectName(ObjectNameToolbarRight);\n setupRowLayout(rowLayout, leftWidget, rightWidget);\n mainLayout->insertItem(n, rowLayout);\n\n foreach (QSharedPointer<MToolbarItem> item , row->items()) {\n createAndAppendWidget(item, leftWidget, rightWidget);\n }\n }\n\n \/\/add custom items to bottom row\n QSharedPointer<const MToolbarRow> row = rows.last();\n foreach (QSharedPointer<MToolbarItem> item, row->items()) {\n createAndAppendWidget(item, &leftBar, &rightBar);\n }\n\n mainLayout->invalidate();\n}\n\nvoid MImToolbar::createAndAppendWidget(QSharedPointer<MToolbarItem> item,\n WidgetBar *leftWidget,\n WidgetBar *rightWidget)\n{\n MWidget *widget = 0;\n WidgetBar *sidebar = 0;\n\n if (item->alignment() == Qt::AlignLeft) {\n sidebar = leftWidget;\n } else {\n sidebar = rightWidget;\n }\n if (item->type() == MInputMethod::ItemButton) {\n widget = new MToolbarButton(item, sidebar);\n\n connect(widget, SIGNAL(clicked(MToolbarItem*)),\n this, SLOT(handleButtonClick(MToolbarItem*)));\n } else {\n widget = new MToolbarLabel(item, sidebar);\n }\n customWidgets.append(widget);\n sidebar->append(widget, item->isVisible());\n if (sidebar->count() == 1) {\n sidebar->show();\n }\n}\n\nvoid MImToolbar::setupRowLayout(QGraphicsLinearLayout *rowLayout,\n WidgetBar *leftWidget,\n WidgetBar *rightWidget)\n{\n rowLayout->setContentsMargins(0, 0, 0, 0);\n\n \/\/ Empty button bars are hidden.\n leftWidget->hide();\n rightWidget->hide();\n \/\/ Add the left and right side WidgetBar widgets with a stretch item in between.\n rowLayout->addItem(leftWidget);\n rowLayout->addStretch();\n rowLayout->addItem(rightWidget);\n\n rowLayout->setAlignment(leftWidget, Qt::AlignBottom);\n rowLayout->setAlignment(rightWidget, Qt::AlignBottom);\n}\n\nvoid MImToolbar::unloadCustomWidgets()\n{\n QGraphicsLinearLayout *mainLayout = static_cast<QGraphicsLinearLayout*>(layout());\n QList<QGraphicsLinearLayout*> rows;\n\n if (!mainLayout) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n \/\/delete all dynamically created rows\n for (int n = 0; n < mainLayout->count() - 1; ++n) {\n QGraphicsLinearLayout *rowLayout = dynamic_cast<QGraphicsLinearLayout*>(mainLayout->itemAt(n));\n\n if (rowLayout) {\n WidgetBar *leftBar = dynamic_cast<WidgetBar*>(rowLayout->itemAt(0));\n WidgetBar *rightBar = dynamic_cast<WidgetBar*>(rowLayout->itemAt(1));\n\n delete leftBar;\n delete rightBar;\n rows << rowLayout;\n }\n }\n\n qDeleteAll(rows);\n qDeleteAll(customWidgets);\n customWidgets.clear();\n leftBar.cleanup();\n rightBar.cleanup();\n}\n\nvoid MImToolbar::arrangeWidgets()\n{\n if (!layout()) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n if (isVisible()) {\n for (int n = 0; n < layout()->count(); ++n) {\n QGraphicsLayout *rowLayout = dynamic_cast<QGraphicsLayout*>(layout()->itemAt(n));\n if (rowLayout) {\n rowLayout->invalidate();\n rowLayout->activate();\n }\n }\n\n layout()->invalidate();\n layout()->activate();\n resize(geometry().width(), layout()->preferredHeight());\n }\n\n emit regionUpdated();\n}\n\nvoid MImToolbar::showGroup(const QString &group)\n{\n bool changed = false;\n\n if (!currentToolbar) {\n return;\n }\n\n foreach (const QSharedPointer<MToolbarItem> item, currentToolbar->items())\n {\n if (item->group() == group && !(item->isVisible())) {\n item->setVisible(true);\n changed = true;\n }\n }\n\n if (changed) {\n arrangeWidgets();\n }\n}\n\nvoid MImToolbar::hideGroup(const QString &group)\n{\n bool changed = false;\n\n if (!currentToolbar) {\n return;\n }\n\n foreach (const QSharedPointer<MToolbarItem> item, currentToolbar->items())\n {\n if (item->group() == group && item->isVisible()) {\n item->setVisible(false);\n changed = true;\n }\n }\n\n if (changed) {\n arrangeWidgets();\n }\n}\n\nvoid MImToolbar::sendKeySequence(const QString &keys)\n{\n const QKeySequence keysequence(keys);\n \/\/translate the keys string to QKeyEvent by QKeySequence\n if (!keysequence.isEmpty()) {\n for (uint i = 0; i < keysequence.count(); i++) {\n int key = keysequence[i];\n Qt::KeyboardModifiers modify = keyModifiers(key);\n key -= modify;\n QString text;\n if (modify == Qt::NoModifier || modify == Qt::ShiftModifier)\n text = QString(key);\n \/\/send both KeyPress and KeyRelease\n QKeyEvent press(QEvent::KeyPress, key, modify, text);\n emit sendKeyEventRequest(press);\n QKeyEvent release(QEvent::KeyRelease, key, modify, text);\n emit sendKeyEventRequest(release);\n }\n }\n}\n\nQt::KeyboardModifiers MImToolbar::keyModifiers(int key) const\n{\n Qt::KeyboardModifiers modify = Qt::NoModifier;\n if (key & Qt::CTRL)\n modify |= Qt::ControlModifier;\n if (key & Qt::ALT)\n modify |= Qt::AltModifier;\n if (key & Qt::SHIFT)\n modify |= Qt::ShiftModifier;\n if (key & Qt::META)\n modify |= Qt::MetaModifier;\n return modify;\n}\n\nvoid MImToolbar::setShapedMode(bool shaped)\n{\n if (shaped) {\n style().setModeShapedToolbar();\n } else {\n style().setModeFullToolbar();\n }\n rightBar.setShapedMode(shaped);\n}\n\nvoid MImToolbar::showToolbarWidget(QSharedPointer<const MToolbarData> toolbar)\n{\n if (toolbar == currentToolbar) {\n return;\n }\n unloadCustomWidgets();\n\n const bool oldToolbarCustom(currentToolbar ? currentToolbar->isCustom() : false);\n currentToolbar = toolbar;\n loadCustomWidgets();\n\n setShapedMode(!toolbar->isCustom());\n\n if (isVisible())\n updateVisibility();\n\n if (oldToolbarCustom != toolbar->isCustom()) {\n emit typeChanged(!toolbar->isCustom());\n }\n}\n\nvoid MImToolbar::hideToolbarWidget()\n{\n currentToolbar.clear();\n unloadCustomWidgets();\n arrangeWidgets();\n setShapedMode(true);\n}\n\nvoid MImToolbar::removeItem(MWidget *widget)\n{\n leftBar.remove(widget);\n rightBar.remove(widget);\n\n if (leftBar.count() == 0) {\n leftBar.hide();\n }\n if (rightBar.count() == 0) {\n rightBar.hide();\n }\n\n if (!layout()) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n layout()->invalidate();\n layout()->activate();\n}\n\nvoid MImToolbar::paintReactionMap(MReactionMap *reactionMap, QGraphicsView *view)\n{\n if (!layout()) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n layout()->activate();\n\n \/\/ Draw the whole toolbar background as inactive when custom toolbar is used.\n const bool paintWholeToolbar = currentToolbar && currentToolbar->isCustom();\n\n if (paintWholeToolbar) {\n reactionMap->setTransform(this, view);\n reactionMap->setInactiveDrawingValue();\n reactionMap->fillRectangle(boundingRect());\n }\n\n \/\/ Draw all widgets geometries.\n reactionMap->setReactiveDrawingValue();\n\n for (int n = 0; n < layout()->count(); ++n) {\n QGraphicsLinearLayout *row = dynamic_cast<QGraphicsLinearLayout*>(layout()->itemAt(n));\n\n if (!row) {\n continue;\n }\n\n row->activate();\n\n for (int j = 0; j < row->count(); ++j) {\n WidgetBar *sidebar = dynamic_cast<WidgetBar *>(row->itemAt(j));\n if (!sidebar || !sidebar->isVisible()) {\n continue;\n }\n\n \/\/ Buttons sometimes require this.\n sidebar->layout()->activate();\n\n if (!paintWholeToolbar) {\n reactionMap->setTransform(sidebar, view);\n reactionMap->setInactiveDrawingValue();\n reactionMap->fillRectangle(sidebar->boundingRect());\n }\n\n reactionMap->setReactiveDrawingValue();\n\n for (int i = 0; i < sidebar->count(); ++i) {\n QGraphicsWidget *widget = sidebar->widgetAt(i);\n\n if (widget && widget->isVisible()\n && !qobject_cast<MToolbarLabel*>(widget)) {\n\n reactionMap->setTransform(widget, view);\n reactionMap->fillRectangle(widget->boundingRect());\n }\n \/\/ Otherwise leave as inactive.\n }\n }\n }\n}\n\nvoid MImToolbar::finalizeOrientationChange()\n{\n \/\/use brute force: destroy everything and construct it again\n unloadCustomWidgets();\n loadCustomWidgets();\n\n if (isVisible()) {\n blockSignals(true);\n arrangeWidgets();\n blockSignals(false);\n }\n}\n\nQRectF MImToolbar::boundingRect() const\n{\n return QRectF(-style()->marginLeft(), -style()->marginTop(),\n size().width() + style()->marginLeft() + style()->marginRight(),\n size().height() + style()->marginTop() + style()->marginBottom());\n}\n\n<commit_msg>Changes: coding style fixes<commit_after>\/* * This file is part of meego-keyboard *\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n * Contact: Nokia Corporation (directui@nokia.com)\n *\n * If you have questions regarding the use of this file, please contact\n * Nokia at directui@nokia.com.\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\n#include \"mimtoolbar.h\"\n#include \"layoutsmanager.h\"\n#include \"mhardwarekeyboard.h\"\n#include \"mvirtualkeyboardstyle.h\"\n#include \"mtoolbarbutton.h\"\n#include \"mtoolbarlabel.h\"\n\n#include <mtoolbardata.h>\n#include <mtoolbaritem.h>\n#include <mtoolbarrow.h>\n#include <mtoolbarlayout.h>\n\n#include <MNamespace>\n#include <MButton>\n#include <QKeySequence>\n#include <QGraphicsLinearLayout>\n#include <QDebug>\n#include <MSceneManager>\n#include <mplainwindow.h>\n#include <mreactionmap.h>\n#include <MScalableImage>\n\nnamespace\n{\n const QString ObjectNameToolbar(\"MImToolbar\");\n const QString ObjectNameToolbarLeft(\"VirtualKeyboardToolbarLeft\");\n const QString ObjectNameToolbarRight(\"VirtualKeyboardToolbarRight\");\n const QString NameToolbarCopyPasteButton(\"VirtualKeyboardCopyPasteButton\");\n};\n\nMImToolbar::MImToolbar(QGraphicsWidget *parent)\n : MStylableWidget(parent),\n textSelected(false),\n copyPasteItem(new MToolbarItem(NameToolbarCopyPasteButton, MInputMethod::ItemButton)),\n leftBar(true, this),\n rightBar(true, this),\n shiftState(ModifierClearState),\n fnState(ModifierClearState)\n{\n leftBar.setObjectName(ObjectNameToolbarLeft);\n rightBar.setObjectName(ObjectNameToolbarRight);\n setObjectName(ObjectNameToolbar);\n\n setupLayout();\n\n connect(this, SIGNAL(visibleChanged()), this, SLOT(updateVisibility()));\n connect(MTheme::instance(), SIGNAL(themeChangeCompleted()),\n this, SLOT(updateFromStyle()));\n}\n\nMImToolbar::~MImToolbar()\n{\n}\n\nvoid MImToolbar::setupLayout()\n{\n QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout(Qt::Vertical, this);\n mainLayout->setContentsMargins(0, 0, 0, 0);\n\n QGraphicsLinearLayout *rowLayout = new QGraphicsLinearLayout(Qt::Horizontal, mainLayout);\n\n setupRowLayout(rowLayout, &leftBar, &rightBar);\n mainLayout->insertItem(0, rowLayout);\n\n resize(geometry().width(), layout()->preferredHeight());\n}\n\nQRegion MImToolbar::region() const\n{\n QRegion region;\n\n if (isVisible()) {\n if (currentToolbar && currentToolbar->isCustom()) {\n region = QRegion(mapRectToScene(rect()).toRect());\n } else if (rightBar.isVisible()) {\n region = QRegion(mapRectToScene(rightBar.geometry()).toRect());\n }\n }\n return region;\n}\n\nvoid MImToolbar::handleButtonClick(MToolbarItem *item)\n{\n if (!item || item->type() != MInputMethod::ItemButton)\n return;\n\n foreach(QSharedPointer<const MToolbarItemAction> action, item->actions()) {\n switch (action->type()) {\n case MInputMethod::ActionSendKeySequence:\n sendKeySequence(action->keys());\n break;\n case MInputMethod::ActionSendString:\n sendStringRequest(action->text());\n break;\n case MInputMethod::ActionSendCommand:\n \/\/TODO:not support yet\n break;\n case MInputMethod::ActionCopy:\n emit copyPasteRequest(InputMethodCopy);\n break;\n case MInputMethod::ActionPaste:\n emit copyPasteRequest(InputMethodPaste);\n break;\n case MInputMethod::ActionShowGroup:\n showGroup(action->group());\n break;\n case MInputMethod::ActionHideGroup:\n hideGroup(action->group());\n break;\n case MInputMethod::ActionClose:\n emit closeKeyboardRequest();\n break;\n case MInputMethod::ActionUndefined:\n case MInputMethod::ActionCopyPaste:\n break;\n }\n }\n}\n\nvoid MImToolbar::setSelectionStatus(bool selection)\n{\n if (textSelected != selection) {\n textSelected = selection;\n if (isVisible())\n updateVisibility();\n }\n}\n\nvoid MImToolbar::updateVisibility()\n{\n if (currentToolbar) {\n foreach (const QSharedPointer<MToolbarItem> item, currentToolbar->items()) {\n if ((item->showOn() == MInputMethod::VisibleAlways)\n || (textSelected && item->showOn() == MInputMethod::VisibleWhenSelectingText)\n || (!textSelected && item->hideOn() == MInputMethod::VisibleWhenSelectingText)) {\n item->setVisible(true);\n }\n\n if ((!textSelected && item->showOn() == MInputMethod::VisibleWhenSelectingText)\n || (textSelected && item->hideOn() == MInputMethod::VisibleWhenSelectingText)) {\n item->setVisible(false);\n }\n }\n }\n arrangeWidgets();\n}\n\nvoid MImToolbar::updateFromStyle()\n{\n prepareGeometryChange(); \/\/ notify scene about changes in bounding rect\n}\n\nvoid MImToolbar::loadCustomWidgets()\n{\n if (!currentToolbar) {\n return;\n }\n\n const M::Orientation orientation = MPlainWindow::instance()->sceneManager()->orientation();\n QSharedPointer<const MToolbarLayout> layout = currentToolbar->layout(orientation);\n QGraphicsLinearLayout *mainLayout = static_cast<QGraphicsLinearLayout*>(this->layout());\n\n if (!mainLayout) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n QList<QSharedPointer<const MToolbarRow> > rows = layout->rows();\n\n \/\/create additional rows if necessary\n for (int n = 0; n < rows.count() - 1; ++n) {\n QSharedPointer<const MToolbarRow> row = rows[n];\n QGraphicsLinearLayout *rowLayout = new QGraphicsLinearLayout(Qt::Horizontal, mainLayout);\n WidgetBar *leftWidget = new WidgetBar(true, this);\n WidgetBar *rightWidget = new WidgetBar(true, this);\n\n leftWidget->setObjectName(ObjectNameToolbarLeft);\n rightWidget->setObjectName(ObjectNameToolbarRight);\n setupRowLayout(rowLayout, leftWidget, rightWidget);\n mainLayout->insertItem(n, rowLayout);\n\n foreach (QSharedPointer<MToolbarItem> item , row->items()) {\n createAndAppendWidget(item, leftWidget, rightWidget);\n }\n }\n\n \/\/add custom items to bottom row\n QSharedPointer<const MToolbarRow> row = rows.last();\n foreach (QSharedPointer<MToolbarItem> item, row->items()) {\n createAndAppendWidget(item, &leftBar, &rightBar);\n }\n\n mainLayout->invalidate();\n}\n\nvoid MImToolbar::createAndAppendWidget(QSharedPointer<MToolbarItem> item,\n WidgetBar *leftWidget,\n WidgetBar *rightWidget)\n{\n MWidget *widget = 0;\n WidgetBar *sidebar = 0;\n\n if (item->alignment() == Qt::AlignLeft) {\n sidebar = leftWidget;\n } else {\n sidebar = rightWidget;\n }\n if (item->type() == MInputMethod::ItemButton) {\n widget = new MToolbarButton(item, sidebar);\n\n connect(widget, SIGNAL(clicked(MToolbarItem*)),\n this, SLOT(handleButtonClick(MToolbarItem*)));\n } else {\n widget = new MToolbarLabel(item, sidebar);\n }\n customWidgets.append(widget);\n sidebar->append(widget, item->isVisible());\n if (sidebar->count() == 1) {\n sidebar->show();\n }\n}\n\nvoid MImToolbar::setupRowLayout(QGraphicsLinearLayout *rowLayout,\n WidgetBar *leftWidget,\n WidgetBar *rightWidget)\n{\n rowLayout->setContentsMargins(0, 0, 0, 0);\n\n \/\/ Empty button bars are hidden.\n leftWidget->hide();\n rightWidget->hide();\n \/\/ Add the left and right side WidgetBar widgets with a stretch item in between.\n rowLayout->addItem(leftWidget);\n rowLayout->addStretch();\n rowLayout->addItem(rightWidget);\n\n rowLayout->setAlignment(leftWidget, Qt::AlignBottom);\n rowLayout->setAlignment(rightWidget, Qt::AlignBottom);\n}\n\nvoid MImToolbar::unloadCustomWidgets()\n{\n QGraphicsLinearLayout *mainLayout = static_cast<QGraphicsLinearLayout*>(layout());\n QList<QGraphicsLinearLayout*> rows;\n\n if (!mainLayout) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n \/\/delete all dynamically created rows\n for (int n = 0; n < mainLayout->count() - 1; ++n) {\n QGraphicsLinearLayout *rowLayout = dynamic_cast<QGraphicsLinearLayout*>(mainLayout->itemAt(n));\n\n if (rowLayout) {\n WidgetBar *leftBar = dynamic_cast<WidgetBar*>(rowLayout->itemAt(0));\n WidgetBar *rightBar = dynamic_cast<WidgetBar*>(rowLayout->itemAt(1));\n\n delete leftBar;\n delete rightBar;\n rows << rowLayout;\n }\n }\n\n qDeleteAll(rows);\n qDeleteAll(customWidgets);\n customWidgets.clear();\n leftBar.cleanup();\n rightBar.cleanup();\n}\n\nvoid MImToolbar::arrangeWidgets()\n{\n if (!layout()) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n if (isVisible()) {\n for (int n = 0; n < layout()->count(); ++n) {\n QGraphicsLayout *rowLayout = dynamic_cast<QGraphicsLayout*>(layout()->itemAt(n));\n if (rowLayout) {\n rowLayout->invalidate();\n rowLayout->activate();\n }\n }\n\n layout()->invalidate();\n layout()->activate();\n resize(geometry().width(), layout()->preferredHeight());\n }\n\n emit regionUpdated();\n}\n\nvoid MImToolbar::showGroup(const QString &group)\n{\n bool changed = false;\n\n if (!currentToolbar) {\n return;\n }\n\n foreach (const QSharedPointer<MToolbarItem> item, currentToolbar->items()) {\n if (item->group() == group && !(item->isVisible())) {\n item->setVisible(true);\n changed = true;\n }\n }\n\n if (changed) {\n arrangeWidgets();\n }\n}\n\nvoid MImToolbar::hideGroup(const QString &group)\n{\n bool changed = false;\n\n if (!currentToolbar) {\n return;\n }\n\n foreach (const QSharedPointer<MToolbarItem> item, currentToolbar->items()) {\n if (item->group() == group && item->isVisible()) {\n item->setVisible(false);\n changed = true;\n }\n }\n\n if (changed) {\n arrangeWidgets();\n }\n}\n\nvoid MImToolbar::sendKeySequence(const QString &keys)\n{\n const QKeySequence keysequence(keys);\n \/\/translate the keys string to QKeyEvent by QKeySequence\n if (!keysequence.isEmpty()) {\n for (uint i = 0; i < keysequence.count(); i++) {\n int key = keysequence[i];\n Qt::KeyboardModifiers modify = keyModifiers(key);\n key -= modify;\n QString text;\n if (modify == Qt::NoModifier || modify == Qt::ShiftModifier)\n text = QString(key);\n \/\/send both KeyPress and KeyRelease\n QKeyEvent press(QEvent::KeyPress, key, modify, text);\n emit sendKeyEventRequest(press);\n QKeyEvent release(QEvent::KeyRelease, key, modify, text);\n emit sendKeyEventRequest(release);\n }\n }\n}\n\nQt::KeyboardModifiers MImToolbar::keyModifiers(int key) const\n{\n Qt::KeyboardModifiers modify = Qt::NoModifier;\n if (key & Qt::CTRL)\n modify |= Qt::ControlModifier;\n if (key & Qt::ALT)\n modify |= Qt::AltModifier;\n if (key & Qt::SHIFT)\n modify |= Qt::ShiftModifier;\n if (key & Qt::META)\n modify |= Qt::MetaModifier;\n return modify;\n}\n\nvoid MImToolbar::setShapedMode(bool shaped)\n{\n if (shaped) {\n style().setModeShapedToolbar();\n } else {\n style().setModeFullToolbar();\n }\n rightBar.setShapedMode(shaped);\n}\n\nvoid MImToolbar::showToolbarWidget(QSharedPointer<const MToolbarData> toolbar)\n{\n if (toolbar == currentToolbar) {\n return;\n }\n unloadCustomWidgets();\n\n const bool oldToolbarCustom(currentToolbar ? currentToolbar->isCustom() : false);\n currentToolbar = toolbar;\n loadCustomWidgets();\n\n setShapedMode(!toolbar->isCustom());\n\n if (isVisible())\n updateVisibility();\n\n if (oldToolbarCustom != toolbar->isCustom()) {\n emit typeChanged(!toolbar->isCustom());\n }\n}\n\nvoid MImToolbar::hideToolbarWidget()\n{\n currentToolbar.clear();\n unloadCustomWidgets();\n arrangeWidgets();\n setShapedMode(true);\n}\n\nvoid MImToolbar::removeItem(MWidget *widget)\n{\n leftBar.remove(widget);\n rightBar.remove(widget);\n\n if (leftBar.count() == 0) {\n leftBar.hide();\n }\n if (rightBar.count() == 0) {\n rightBar.hide();\n }\n\n if (!layout()) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n layout()->invalidate();\n layout()->activate();\n}\n\nvoid MImToolbar::paintReactionMap(MReactionMap *reactionMap, QGraphicsView *view)\n{\n if (!layout()) {\n qCritical() << __PRETTY_FUNCTION__ << \"Layout does not exist\";\n }\n\n layout()->activate();\n\n \/\/ Draw the whole toolbar background as inactive when custom toolbar is used.\n const bool paintWholeToolbar = currentToolbar && currentToolbar->isCustom();\n\n if (paintWholeToolbar) {\n reactionMap->setTransform(this, view);\n reactionMap->setInactiveDrawingValue();\n reactionMap->fillRectangle(boundingRect());\n }\n\n \/\/ Draw all widgets geometries.\n reactionMap->setReactiveDrawingValue();\n\n for (int n = 0; n < layout()->count(); ++n) {\n QGraphicsLinearLayout *row = dynamic_cast<QGraphicsLinearLayout*>(layout()->itemAt(n));\n\n if (!row) {\n continue;\n }\n\n row->activate();\n\n for (int j = 0; j < row->count(); ++j) {\n WidgetBar *sidebar = dynamic_cast<WidgetBar *>(row->itemAt(j));\n if (!sidebar || !sidebar->isVisible()) {\n continue;\n }\n\n \/\/ Buttons sometimes require this.\n sidebar->layout()->activate();\n\n if (!paintWholeToolbar) {\n reactionMap->setTransform(sidebar, view);\n reactionMap->setInactiveDrawingValue();\n reactionMap->fillRectangle(sidebar->boundingRect());\n }\n\n reactionMap->setReactiveDrawingValue();\n\n for (int i = 0; i < sidebar->count(); ++i) {\n QGraphicsWidget *widget = sidebar->widgetAt(i);\n\n if (widget && widget->isVisible()\n && !qobject_cast<MToolbarLabel*>(widget)) {\n\n reactionMap->setTransform(widget, view);\n reactionMap->fillRectangle(widget->boundingRect());\n }\n \/\/ Otherwise leave as inactive.\n }\n }\n }\n}\n\nvoid MImToolbar::finalizeOrientationChange()\n{\n \/\/use brute force: destroy everything and construct it again\n unloadCustomWidgets();\n loadCustomWidgets();\n\n if (isVisible()) {\n blockSignals(true);\n arrangeWidgets();\n blockSignals(false);\n }\n}\n\nQRectF MImToolbar::boundingRect() const\n{\n return QRectF(-style()->marginLeft(), -style()->marginTop(),\n size().width() + style()->marginLeft() + style()->marginRight(),\n size().height() + style()->marginTop() + style()->marginBottom());\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013-2015 Daniel Nicoletti <dantti12@gmail.com>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"engine_p.h\"\n\n#include \"common.h\"\n#include \"request_p.h\"\n#include \"application.h\"\n#include \"response_p.h\"\n#include \"context_p.h\"\n\n#include <QUrl>\n#include <QSettings>\n#include <QDir>\n#include <QtCore\/QByteArray>\n#include <QDebug>\n\nusing namespace Cutelyst;\n\nEngine::Engine(const QVariantMap &opts, QObject *parent) :\n QObject(parent),\n d_ptr(new EnginePrivate)\n{\n Q_D(Engine);\n\n \/\/ Debug messages should be disabled by default\n QLoggingCategory::setFilterRules(QLatin1String(\"cutelyst.*.debug=false\"));\n\n \/\/ Load application configuration\n if (qEnvironmentVariableIsSet(\"CUTELYST_CONFIG\")) {\n const QByteArray config = qgetenv(\"CUTELYST_CONFIG\");\n qCDebug(CUTELYST_CORE) << \"Reading config file:\" << config;\n QSettings settings(QString::fromLatin1(config), QSettings::IniFormat);\n Q_FOREACH (const QString &group, settings.childGroups()) {\n settings.beginGroup(group);\n Q_FOREACH (const QString &key, settings.childKeys()) {\n d->config[group].insert(key, settings.value(key));\n }\n settings.endGroup();\n }\n qCDebug(CUTELYST_CORE) << \"Configuration:\" << d->config;\n }\n\n d->opts = opts;\n}\n\nEngine::~Engine()\n{\n delete d_ptr;\n}\n\nvoid Engine::finalizeCookies(Context *c)\n{\n Response *res = c->response();\n Headers &headers = res->headers();\n Q_FOREACH (const QNetworkCookie &cookie, res->cookies()) {\n headers.pushHeader(QStringLiteral(\"Set-Cookie\"), QString::fromLatin1(cookie.toRawForm()));\n }\n}\n\nbool Engine::finalizeHeaders(Context *c)\n{\n Response *response = c->response();\n\n \/\/ Check if we already finalized headers\n if (response->d_ptr->finalizedHeaders) {\n return true;\n }\n\n \/\/ Fix missing content length\n if (!response->contentLength() && response->hasBody()) {\n QIODevice *body = response->bodyDevice();\n if (body) {\n response->setContentLength(body->size());\n } else {\n response->setContentLength(response->body().size());\n }\n }\n\n const QString protocol = c->request()->protocol();\n if (protocol == QLatin1String(\"HTTP\/1.1\")) {\n if (!response->contentLength()) {\n quint16 status = response->status();\n \/\/ if status is not 1xx or 204 NoContent or 304 NotModified\n if (!(status >= 100 && status <= 199) && status != 204 && status != 304) {\n qCDebug(CUTELYST_ENGINE, \"Using chunked transfer-encoding to send unknown length body\");\n response->setHeader(QStringLiteral(\"Transfer-Encoding\"), QStringLiteral(\"chunked\"));\n response->d_ptr->chunked = true;\n }\n } else if (response->header(QStringLiteral(\"Transfer-Encoding\")) == QLatin1String(\"chunked\")) {\n qCDebug(CUTELYST_ENGINE, \"Chunked transfer-encoding set for response\");\n response->d_ptr->chunked = true;\n }\n }\n\n \/\/ Handle redirects\n const QUrl &location = response->location();\n if (!location.isEmpty()) {\n qCDebug(CUTELYST_ENGINE, \"Redirecting to \\\"%s\\\"\", location.toEncoded().constData());\n response->headers().setHeader(QStringLiteral(\"Location\"), QString::fromLatin1(location.toEncoded()));\n }\n\n finalizeCookies(c);\n\n \/\/ Done\n response->d_ptr->finalizedHeaders = true;\n return true;\n}\n\nvoid Engine::finalizeBody(Context *c)\n{\n Response *response = c->response();\n void *engineData = c->engineData();\n\n if (!response->d_ptr->chunked) {\n QIODevice *body = response->bodyDevice();\n\n if (body) {\n body->seek(0);\n char block[64 * 1024];\n while (!body->atEnd()) {\n qint64 in = body->read(block, sizeof(block));\n if (in <= 0)\n break;\n\n if (write(c, block, in, engineData) != in) {\n qCWarning(CUTELYST_ENGINE) << \"Failed to write body\";\n break;\n }\n }\n } else {\n const QByteArray bodyByteArray = response->body();\n if (!bodyByteArray.isNull()) {\n write(c, bodyByteArray.constData(), bodyByteArray.size(), engineData);\n }\n }\n } else if (!response->d_ptr->chunked_done) {\n \/\/ Write the final '0' chunk\n doWrite(c, \"0\\r\\n\\r\\n\", 5, engineData);\n }\n}\n\nvoid Engine::finalizeError(Context *c)\n{\n Response *res = c->response();\n\n res->setContentType(QStringLiteral(\"text\/html; charset=utf-8\"));\n\n QByteArray body;\n\n \/\/ Trick IE. Old versions of IE would display their own error page instead\n \/\/ of ours if we'd give it less than 512 bytes.\n body.reserve(512);\n\n body.append(c->errors().join(QLatin1Char('\\n')).toUtf8());\n\n res->body() = body;\n\n \/\/ Return 500\n res->setStatus(Response::InternalServerError);\n}\n\nApplication *Engine::app() const\n{\n Q_D(const Engine);\n Q_ASSERT(d->app);\n return d->app;\n}\n\nbool Engine::initApplication(Application *app, bool postFork)\n{\n Q_D(Engine);\n d->app = app;\n\n \/\/ To make easier for engines to clean up\n \/\/ the app must be a child of it\n app->setParent(this);\n\n if (!app->setup(this)) {\n qCCritical(CUTELYST_ENGINE) << \"Failed to setup application\";\n return false;\n }\n\n if (!init()) {\n qCCritical(CUTELYST_ENGINE) << \"Failed to setup engine\";\n return false;\n }\n\n if (postFork) {\n return postForkApplication();\n }\n\n return true;\n}\n\nbool Engine::postForkApplication()\n{\n Q_D(Engine);\n\n if (!d->app) {\n qCCritical(CUTELYST_ENGINE) << \"Failed to postForkApplication on a null application\";\n return false;\n }\n return d->app->enginePostFork();\n}\n\nquint64 Engine::time()\n{\n return QDateTime::currentMSecsSinceEpoch();\n}\n\nqint64 Engine::write(Context *c, const char *data, qint64 len, void *engineData)\n{\n Response *response = c->response();\n if (!response->d_ptr->chunked) {\n return doWrite(c, data, len, engineData);\n } else if (!response->d_ptr->chunked_done) {\n const QByteArray chunkSize = QByteArray::number(len, 16).toUpper();\n QByteArray chunk;\n chunk.reserve(len + chunkSize.size() + 4);\n chunk.append(chunkSize).append(\"\\r\\n\", 2)\n .append(data, len).append(\"\\r\\n\", 2);\n\n qint64 retWrite = doWrite(c, chunk.data(), chunk.size(), engineData);\n\n \/\/ Flag if we wrote an empty chunk\n if (!len) {\n response->d_ptr->chunked_done = true;\n }\n\n return retWrite == chunk.size() ? len : -1;\n }\n return -1;\n}\n\nQByteArray Engine::statusCode(quint16 status)\n{\n switch (status) {\n case Response::OK:\n return QByteArrayLiteral(\"200 OK\");\n case Response::Found:\n return QByteArrayLiteral(\"302 Found\");\n case Response::NotFound:\n return QByteArrayLiteral(\"404 Not Found\");\n case Response::InternalServerError:\n return QByteArrayLiteral(\"500 Internal Server Error\");\n case Response::MovedPermanently:\n return QByteArrayLiteral(\"301 Moved Permanently\");\n case Response::NotModified:\n return QByteArrayLiteral(\"304 Not Modified\");\n case Response::SeeOther:\n return QByteArrayLiteral(\"303 See Other\");\n case Response::Forbidden:\n return QByteArrayLiteral(\"403 Forbidden\");\n case Response::TemporaryRedirect:\n return QByteArrayLiteral(\"307 Temporary Redirect\");\n case Response::Unauthorized:\n return QByteArrayLiteral(\"401 Unauthorized\");\n case Response::BadRequest:\n return QByteArrayLiteral(\"400 Bad Request\");\n case Response::MethodNotAllowed:\n return QByteArrayLiteral(\"405 Method Not Allowed\");\n case Response::RequestTimeout:\n return QByteArrayLiteral(\"408 Request Timeout\");\n case Response::Continue:\n return QByteArrayLiteral(\"100 Continue\");\n case Response::SwitchingProtocols:\n return QByteArrayLiteral(\"101 Switching Protocols\");\n case Response::Created:\n return QByteArrayLiteral(\"201 Created\");\n case Response::Accepted:\n return QByteArrayLiteral(\"202 Accepted\");\n case Response::NonAuthoritativeInformation:\n return QByteArrayLiteral(\"203 Non-Authoritative Information\");\n case Response::NoContent:\n return QByteArrayLiteral(\"204 No Content\");\n case Response::ResetContent:\n return QByteArrayLiteral(\"205 Reset Content\");\n case Response::PartialContent:\n return QByteArrayLiteral(\"206 Partial Content\");\n case Response::MultipleChoices:\n return QByteArrayLiteral(\"300 Multiple Choices\");\n case Response::UseProxy:\n return QByteArrayLiteral(\"305 Use Proxy\");\n case Response::PaymentRequired:\n return QByteArrayLiteral(\"402 Payment Required\");\n case Response::NotAcceptable:\n return QByteArrayLiteral(\"406 Not Acceptable\");\n case Response::ProxyAuthenticationRequired:\n return QByteArrayLiteral(\"407 Proxy Authentication Required\");\n case Response::Conflict:\n return QByteArrayLiteral(\"409 Conflict\");\n case Response::Gone:\n return QByteArrayLiteral(\"410 Gone\");\n case Response::LengthRequired:\n return QByteArrayLiteral(\"411 Length Required\");\n case Response::PreconditionFailed:\n return QByteArrayLiteral(\"412 Precondition Failed\");\n case Response::RequestEntityTooLarge:\n return QByteArrayLiteral(\"413 Request Entity Too Large\");\n case Response::RequestURITooLong:\n return QByteArrayLiteral(\"414 Request-URI Too Long\");\n case Response::UnsupportedMediaType:\n return QByteArrayLiteral(\"415 Unsupported Media Type\");\n case Response::RequestedRangeNotSatisfiable:\n return QByteArrayLiteral(\"416 Requested Range Not Satisfiable\");\n case Response::ExpectationFailed:\n return QByteArrayLiteral(\"417 Expectation Failed\");\n case Response::NotImplemented:\n return QByteArrayLiteral(\"501 Not Implemented\");\n case Response::BadGateway:\n return QByteArrayLiteral(\"502 Bad Gateway\");\n case Response::ServiceUnavailable:\n return QByteArrayLiteral(\"503 Service Unavailable\");\n case Response::GatewayTimeout:\n return QByteArrayLiteral(\"504 Gateway Timeout\");\n case Response::HTTPVersionNotSupported:\n return QByteArrayLiteral(\"505 HTTP Version Not Supported\");\n case Response::BandwidthLimitExceeded:\n return QByteArrayLiteral(\"509 Bandwidth Limit Exceeded\");\n default:\n return QByteArray::number(status);\n }\n}\n\nQVariantMap Engine::opts() const\n{\n Q_D(const Engine);\n return d->opts;\n}\n\nQVariantMap Engine::config(const QString &entity) const\n{\n Q_D(const Engine);\n return d->config.value(entity);\n}\n\nvoid Engine::finalize(Context *c)\n{\n if (c->error()) {\n finalizeError(c);\n }\n\n if (!c->response()->d_ptr->finalizedHeaders) {\n finalizeHeaders(c);\n }\n\n finalizeBody(c);\n}\n\nstatic const QByteArray cutelyst_header_order (\n \/\/ General headers\n \"Cache-Control\\n\"\n \"Connection\\n\"\n \"Date\\n\"\n \"Pragma\\n\"\n \"Trailer\\n\"\n \"Transfer-Encoding\\n\"\n \"Upgrade\\n\"\n \"Via\\n\"\n \"Warning\\n\"\n \/\/ Request headers\n \"Accept\\n\"\n \"Accept-Charset\\n\"\n \"Accept-Encoding\\n\"\n \"Accept-Language\\n\"\n \"Authorization\\n\"\n \"Expect\\n\"\n \"From\\n\"\n \"Host\\n\"\n \"If-Match\\n\"\n \"If-Modified-Since\\n\"\n \"If-None-Match\\n\"\n \"If-Range\\n\"\n \"If-Unmodified-Since\\n\"\n \"Max-Forwards\\n\"\n \"Proxy-Authorization\\n\"\n \"Range\\n\"\n \"Referer\\n\"\n \"TE\\n\"\n \"User-Agent\\n\"\n \/\/ Response headers\n \"Accept-Ranges\\n\"\n \"Age\\n\"\n \"ETag\\n\"\n \"Location\\n\"\n \"Proxy-Authenticate\\n\"\n \"Retry-After\\n\"\n \"Server\\n\"\n \"Vary\\n\"\n \"WWW-Authenticate\\n\"\n \/\/ Entity headers\n \"Allow\\n\"\n \"Content-Encoding\\n\"\n \"Content-Language\\n\"\n \"Content-Length\\n\"\n \"Content-Location\\n\"\n \"Content-MD5\\n\"\n \"Content-Range\\n\"\n \"Content-Type\\n\"\n \"Expires\\n\"\n \"Last-Modified\"\n );\n\nbool httpGoodPracticeWeightSort(const HeaderValuePair &pair1, const HeaderValuePair &pair2)\n{\n int index1 = pair1.weight;\n int index2 = pair2.weight;\n\n if (index1 != -1 && index2 != -1) {\n \/\/ Both items are in the headerOrder list\n return index1 < index2;\n } else if (index1 == -1 && index2 == -1) {\n \/\/ Noone of them are int the headerOrder list\n return false;\n }\n\n \/\/ if the pair1 is in the header list it should go first\n return index1 != -1;\n}\n\nQList<HeaderValuePair> Engine::headersForResponse(const Headers &headers)\n{\n QList<HeaderValuePair> ret;\n\n auto it = headers.constBegin();\n while (it != headers.constEnd()) {\n HeaderValuePair pair;\n pair.key = camelCaseHeader(it.key());\n pair.value = it.value();\n pair.weight = cutelyst_header_order.indexOf(pair.key.toLatin1());\n\n ret.append(pair);\n ++it;\n }\n\n \/\/ Sort base on the \"good practices\" of HTTP RCF\n qSort(ret.begin(), ret.end(), &httpGoodPracticeWeightSort);\n\n return ret;\n}\n\nvoid Engine::processRequest(const QString &method,\n const QString &path,\n const QByteArray &query,\n const QString &protocol,\n bool isSecure,\n const QString &serverAddress,\n const QString &remoteAddress,\n quint16 remotePort,\n const QString &remoteUser,\n const Headers &headers,\n quint64 startOfRequest,\n QIODevice *body,\n void *requestPtr)\n{\n Q_D(Engine);\n\n auto prv = new RequestPrivate(this,\n method,\n path,\n query,\n protocol,\n isSecure,\n serverAddress,\n remoteAddress,\n remotePort,\n remoteUser,\n headers,\n startOfRequest,\n body,\n requestPtr);\n\n auto request = new Request(prv);\n d->app->handleRequest(request);\n delete request;\n}\n\n#include \"moc_engine.cpp\"\n<commit_msg>Automatically set chunked transfer only for QIODevice bodies of unknown size<commit_after>\/*\n * Copyright (C) 2013-2015 Daniel Nicoletti <dantti12@gmail.com>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"engine_p.h\"\n\n#include \"common.h\"\n#include \"request_p.h\"\n#include \"application.h\"\n#include \"response_p.h\"\n#include \"context_p.h\"\n\n#include <QUrl>\n#include <QSettings>\n#include <QDir>\n#include <QtCore\/QByteArray>\n#include <QDebug>\n\nusing namespace Cutelyst;\n\nEngine::Engine(const QVariantMap &opts, QObject *parent) :\n QObject(parent),\n d_ptr(new EnginePrivate)\n{\n Q_D(Engine);\n\n \/\/ Debug messages should be disabled by default\n QLoggingCategory::setFilterRules(QLatin1String(\"cutelyst.*.debug=false\"));\n\n \/\/ Load application configuration\n if (qEnvironmentVariableIsSet(\"CUTELYST_CONFIG\")) {\n const QByteArray config = qgetenv(\"CUTELYST_CONFIG\");\n qCDebug(CUTELYST_CORE) << \"Reading config file:\" << config;\n QSettings settings(QString::fromLatin1(config), QSettings::IniFormat);\n Q_FOREACH (const QString &group, settings.childGroups()) {\n settings.beginGroup(group);\n Q_FOREACH (const QString &key, settings.childKeys()) {\n d->config[group].insert(key, settings.value(key));\n }\n settings.endGroup();\n }\n qCDebug(CUTELYST_CORE) << \"Configuration:\" << d->config;\n }\n\n d->opts = opts;\n}\n\nEngine::~Engine()\n{\n delete d_ptr;\n}\n\nvoid Engine::finalizeCookies(Context *c)\n{\n Response *res = c->response();\n Headers &headers = res->headers();\n Q_FOREACH (const QNetworkCookie &cookie, res->cookies()) {\n headers.pushHeader(QStringLiteral(\"Set-Cookie\"), QString::fromLatin1(cookie.toRawForm()));\n }\n}\n\nbool Engine::finalizeHeaders(Context *c)\n{\n Response *response = c->response();\n\n \/\/ Check if we already finalized headers\n if (response->d_ptr->finalizedHeaders) {\n return true;\n }\n\n \/\/ Fix missing content length\n if (!response->contentLength() && response->hasBody()) {\n QIODevice *body = response->bodyDevice();\n if (!body) {\n response->setContentLength(response->body().size());\n } else {\n qint64 size = body->size();\n if (size >= 0) {\n response->setContentLength(body->size());\n } else if (c->request()->protocol() == QLatin1String(\"HTTP\/1.1\")) {\n quint16 status = response->status();\n \/\/ if status is not 1xx or 204 NoContent or 304 NotModified\n if (!(status >= 100 && status <= 199) && status != 204 && status != 304) {\n qCDebug(CUTELYST_ENGINE, \"Using chunked transfer-encoding to send unknown length body\");\n response->setHeader(QStringLiteral(\"Transfer-Encoding\"), QStringLiteral(\"chunked\"));\n response->d_ptr->chunked = true;\n }\n }\n }\n } else if (response->header(QStringLiteral(\"Transfer-Encoding\")) == QLatin1String(\"chunked\")) {\n qCDebug(CUTELYST_ENGINE, \"Chunked transfer-encoding set for response\");\n response->d_ptr->chunked = true;\n }\n\n \/\/ Handle redirects\n const QUrl &location = response->location();\n if (!location.isEmpty()) {\n qCDebug(CUTELYST_ENGINE, \"Redirecting to \\\"%s\\\"\", location.toEncoded().constData());\n response->headers().setHeader(QStringLiteral(\"Location\"), QString::fromLatin1(location.toEncoded()));\n }\n\n finalizeCookies(c);\n\n \/\/ Done\n response->d_ptr->finalizedHeaders = true;\n return true;\n}\n\nvoid Engine::finalizeBody(Context *c)\n{\n Response *response = c->response();\n void *engineData = c->engineData();\n\n if (!response->d_ptr->chunked) {\n QIODevice *body = response->bodyDevice();\n\n if (body) {\n body->seek(0);\n char block[64 * 1024];\n while (!body->atEnd()) {\n qint64 in = body->read(block, sizeof(block));\n if (in <= 0)\n break;\n\n if (write(c, block, in, engineData) != in) {\n qCWarning(CUTELYST_ENGINE) << \"Failed to write body\";\n break;\n }\n }\n } else {\n const QByteArray bodyByteArray = response->body();\n if (!bodyByteArray.isNull()) {\n write(c, bodyByteArray.constData(), bodyByteArray.size(), engineData);\n }\n }\n } else if (!response->d_ptr->chunked_done) {\n \/\/ Write the final '0' chunk\n doWrite(c, \"0\\r\\n\\r\\n\", 5, engineData);\n }\n}\n\nvoid Engine::finalizeError(Context *c)\n{\n Response *res = c->response();\n\n res->setContentType(QStringLiteral(\"text\/html; charset=utf-8\"));\n\n QByteArray body;\n\n \/\/ Trick IE. Old versions of IE would display their own error page instead\n \/\/ of ours if we'd give it less than 512 bytes.\n body.reserve(512);\n\n body.append(c->errors().join(QLatin1Char('\\n')).toUtf8());\n\n res->body() = body;\n\n \/\/ Return 500\n res->setStatus(Response::InternalServerError);\n}\n\nApplication *Engine::app() const\n{\n Q_D(const Engine);\n Q_ASSERT(d->app);\n return d->app;\n}\n\nbool Engine::initApplication(Application *app, bool postFork)\n{\n Q_D(Engine);\n d->app = app;\n\n \/\/ To make easier for engines to clean up\n \/\/ the app must be a child of it\n app->setParent(this);\n\n if (!app->setup(this)) {\n qCCritical(CUTELYST_ENGINE) << \"Failed to setup application\";\n return false;\n }\n\n if (!init()) {\n qCCritical(CUTELYST_ENGINE) << \"Failed to setup engine\";\n return false;\n }\n\n if (postFork) {\n return postForkApplication();\n }\n\n return true;\n}\n\nbool Engine::postForkApplication()\n{\n Q_D(Engine);\n\n if (!d->app) {\n qCCritical(CUTELYST_ENGINE) << \"Failed to postForkApplication on a null application\";\n return false;\n }\n return d->app->enginePostFork();\n}\n\nquint64 Engine::time()\n{\n return QDateTime::currentMSecsSinceEpoch();\n}\n\nqint64 Engine::write(Context *c, const char *data, qint64 len, void *engineData)\n{\n Response *response = c->response();\n if (!response->d_ptr->chunked) {\n return doWrite(c, data, len, engineData);\n } else if (!response->d_ptr->chunked_done) {\n const QByteArray chunkSize = QByteArray::number(len, 16).toUpper();\n QByteArray chunk;\n chunk.reserve(len + chunkSize.size() + 4);\n chunk.append(chunkSize).append(\"\\r\\n\", 2)\n .append(data, len).append(\"\\r\\n\", 2);\n\n qint64 retWrite = doWrite(c, chunk.data(), chunk.size(), engineData);\n\n \/\/ Flag if we wrote an empty chunk\n if (!len) {\n response->d_ptr->chunked_done = true;\n }\n\n return retWrite == chunk.size() ? len : -1;\n }\n return -1;\n}\n\nQByteArray Engine::statusCode(quint16 status)\n{\n switch (status) {\n case Response::OK:\n return QByteArrayLiteral(\"200 OK\");\n case Response::Found:\n return QByteArrayLiteral(\"302 Found\");\n case Response::NotFound:\n return QByteArrayLiteral(\"404 Not Found\");\n case Response::InternalServerError:\n return QByteArrayLiteral(\"500 Internal Server Error\");\n case Response::MovedPermanently:\n return QByteArrayLiteral(\"301 Moved Permanently\");\n case Response::NotModified:\n return QByteArrayLiteral(\"304 Not Modified\");\n case Response::SeeOther:\n return QByteArrayLiteral(\"303 See Other\");\n case Response::Forbidden:\n return QByteArrayLiteral(\"403 Forbidden\");\n case Response::TemporaryRedirect:\n return QByteArrayLiteral(\"307 Temporary Redirect\");\n case Response::Unauthorized:\n return QByteArrayLiteral(\"401 Unauthorized\");\n case Response::BadRequest:\n return QByteArrayLiteral(\"400 Bad Request\");\n case Response::MethodNotAllowed:\n return QByteArrayLiteral(\"405 Method Not Allowed\");\n case Response::RequestTimeout:\n return QByteArrayLiteral(\"408 Request Timeout\");\n case Response::Continue:\n return QByteArrayLiteral(\"100 Continue\");\n case Response::SwitchingProtocols:\n return QByteArrayLiteral(\"101 Switching Protocols\");\n case Response::Created:\n return QByteArrayLiteral(\"201 Created\");\n case Response::Accepted:\n return QByteArrayLiteral(\"202 Accepted\");\n case Response::NonAuthoritativeInformation:\n return QByteArrayLiteral(\"203 Non-Authoritative Information\");\n case Response::NoContent:\n return QByteArrayLiteral(\"204 No Content\");\n case Response::ResetContent:\n return QByteArrayLiteral(\"205 Reset Content\");\n case Response::PartialContent:\n return QByteArrayLiteral(\"206 Partial Content\");\n case Response::MultipleChoices:\n return QByteArrayLiteral(\"300 Multiple Choices\");\n case Response::UseProxy:\n return QByteArrayLiteral(\"305 Use Proxy\");\n case Response::PaymentRequired:\n return QByteArrayLiteral(\"402 Payment Required\");\n case Response::NotAcceptable:\n return QByteArrayLiteral(\"406 Not Acceptable\");\n case Response::ProxyAuthenticationRequired:\n return QByteArrayLiteral(\"407 Proxy Authentication Required\");\n case Response::Conflict:\n return QByteArrayLiteral(\"409 Conflict\");\n case Response::Gone:\n return QByteArrayLiteral(\"410 Gone\");\n case Response::LengthRequired:\n return QByteArrayLiteral(\"411 Length Required\");\n case Response::PreconditionFailed:\n return QByteArrayLiteral(\"412 Precondition Failed\");\n case Response::RequestEntityTooLarge:\n return QByteArrayLiteral(\"413 Request Entity Too Large\");\n case Response::RequestURITooLong:\n return QByteArrayLiteral(\"414 Request-URI Too Long\");\n case Response::UnsupportedMediaType:\n return QByteArrayLiteral(\"415 Unsupported Media Type\");\n case Response::RequestedRangeNotSatisfiable:\n return QByteArrayLiteral(\"416 Requested Range Not Satisfiable\");\n case Response::ExpectationFailed:\n return QByteArrayLiteral(\"417 Expectation Failed\");\n case Response::NotImplemented:\n return QByteArrayLiteral(\"501 Not Implemented\");\n case Response::BadGateway:\n return QByteArrayLiteral(\"502 Bad Gateway\");\n case Response::ServiceUnavailable:\n return QByteArrayLiteral(\"503 Service Unavailable\");\n case Response::GatewayTimeout:\n return QByteArrayLiteral(\"504 Gateway Timeout\");\n case Response::HTTPVersionNotSupported:\n return QByteArrayLiteral(\"505 HTTP Version Not Supported\");\n case Response::BandwidthLimitExceeded:\n return QByteArrayLiteral(\"509 Bandwidth Limit Exceeded\");\n default:\n return QByteArray::number(status);\n }\n}\n\nQVariantMap Engine::opts() const\n{\n Q_D(const Engine);\n return d->opts;\n}\n\nQVariantMap Engine::config(const QString &entity) const\n{\n Q_D(const Engine);\n return d->config.value(entity);\n}\n\nvoid Engine::finalize(Context *c)\n{\n if (c->error()) {\n finalizeError(c);\n }\n\n if (!c->response()->d_ptr->finalizedHeaders) {\n finalizeHeaders(c);\n }\n\n finalizeBody(c);\n}\n\nstatic const QByteArray cutelyst_header_order (\n \/\/ General headers\n \"Cache-Control\\n\"\n \"Connection\\n\"\n \"Date\\n\"\n \"Pragma\\n\"\n \"Trailer\\n\"\n \"Transfer-Encoding\\n\"\n \"Upgrade\\n\"\n \"Via\\n\"\n \"Warning\\n\"\n \/\/ Request headers\n \"Accept\\n\"\n \"Accept-Charset\\n\"\n \"Accept-Encoding\\n\"\n \"Accept-Language\\n\"\n \"Authorization\\n\"\n \"Expect\\n\"\n \"From\\n\"\n \"Host\\n\"\n \"If-Match\\n\"\n \"If-Modified-Since\\n\"\n \"If-None-Match\\n\"\n \"If-Range\\n\"\n \"If-Unmodified-Since\\n\"\n \"Max-Forwards\\n\"\n \"Proxy-Authorization\\n\"\n \"Range\\n\"\n \"Referer\\n\"\n \"TE\\n\"\n \"User-Agent\\n\"\n \/\/ Response headers\n \"Accept-Ranges\\n\"\n \"Age\\n\"\n \"ETag\\n\"\n \"Location\\n\"\n \"Proxy-Authenticate\\n\"\n \"Retry-After\\n\"\n \"Server\\n\"\n \"Vary\\n\"\n \"WWW-Authenticate\\n\"\n \/\/ Entity headers\n \"Allow\\n\"\n \"Content-Encoding\\n\"\n \"Content-Language\\n\"\n \"Content-Length\\n\"\n \"Content-Location\\n\"\n \"Content-MD5\\n\"\n \"Content-Range\\n\"\n \"Content-Type\\n\"\n \"Expires\\n\"\n \"Last-Modified\"\n );\n\nbool httpGoodPracticeWeightSort(const HeaderValuePair &pair1, const HeaderValuePair &pair2)\n{\n int index1 = pair1.weight;\n int index2 = pair2.weight;\n\n if (index1 != -1 && index2 != -1) {\n \/\/ Both items are in the headerOrder list\n return index1 < index2;\n } else if (index1 == -1 && index2 == -1) {\n \/\/ Noone of them are int the headerOrder list\n return false;\n }\n\n \/\/ if the pair1 is in the header list it should go first\n return index1 != -1;\n}\n\nQList<HeaderValuePair> Engine::headersForResponse(const Headers &headers)\n{\n QList<HeaderValuePair> ret;\n\n auto it = headers.constBegin();\n while (it != headers.constEnd()) {\n HeaderValuePair pair;\n pair.key = camelCaseHeader(it.key());\n pair.value = it.value();\n pair.weight = cutelyst_header_order.indexOf(pair.key.toLatin1());\n\n ret.append(pair);\n ++it;\n }\n\n \/\/ Sort base on the \"good practices\" of HTTP RCF\n qSort(ret.begin(), ret.end(), &httpGoodPracticeWeightSort);\n\n return ret;\n}\n\nvoid Engine::processRequest(const QString &method,\n const QString &path,\n const QByteArray &query,\n const QString &protocol,\n bool isSecure,\n const QString &serverAddress,\n const QString &remoteAddress,\n quint16 remotePort,\n const QString &remoteUser,\n const Headers &headers,\n quint64 startOfRequest,\n QIODevice *body,\n void *requestPtr)\n{\n Q_D(Engine);\n\n auto prv = new RequestPrivate(this,\n method,\n path,\n query,\n protocol,\n isSecure,\n serverAddress,\n remoteAddress,\n remotePort,\n remoteUser,\n headers,\n startOfRequest,\n body,\n requestPtr);\n\n auto request = new Request(prv);\n d->app->handleRequest(request);\n delete request;\n}\n\n#include \"moc_engine.cpp\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005, 2006, 2009 Apple 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 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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"config.h\"\n\n#ifdef SKIP_STATIC_CONSTRUCTORS_ON_GCC\n#define WEBCORE_QUALIFIEDNAME_HIDE_GLOBALS 1\n#else\n#define QNAME_DEFAULT_CONSTRUCTOR\n#endif\n\n#include \"HTMLNames.h\"\n#include \"SVGNames.h\"\n#include \"XLinkNames.h\"\n#include \"XMLNSNames.h\"\n#include \"XMLNames.h\"\n#include \"core\/dom\/QualifiedName.h\"\n#include \"wtf\/Assertions.h\"\n#include \"wtf\/HashSet.h\"\n#include \"wtf\/StaticConstructors.h\"\n\nnamespace WebCore {\n\nstatic const int staticQualifiedNamesCount = HTMLNames::HTMLTagsCount + HTMLNames::HTMLAttrsCount\n + SVGNames::SVGTagsCount + SVGNames::SVGAttrsCount\n + XLinkNames::XLinkAttrsCount\n + XMLNSNames::XMLNSAttrsCount\n + XMLNames::XMLAttrsCount;\n\nstruct QualifiedNameHashTraits : public HashTraits<QualifiedName::QualifiedNameImpl*> {\n static const int minimumTableSize = WTF::HashTableCapacityForSize<staticQualifiedNamesCount>::value;\n};\n\ntypedef HashSet<QualifiedName::QualifiedNameImpl*, QualifiedNameHash, QualifiedNameHashTraits> QNameSet;\n\nstruct QNameComponentsTranslator {\n static unsigned hash(const QualifiedNameComponents& components)\n {\n return hashComponents(components);\n }\n static bool equal(QualifiedName::QualifiedNameImpl* name, const QualifiedNameComponents& c)\n {\n return c.m_prefix == name->m_prefix.impl() && c.m_localName == name->m_localName.impl() && c.m_namespace == name->m_namespace.impl();\n }\n static void translate(QualifiedName::QualifiedNameImpl*& location, const QualifiedNameComponents& components, unsigned)\n {\n location = QualifiedName::QualifiedNameImpl::create(components.m_prefix, components.m_localName, components.m_namespace).leakRef();\n }\n};\n\nstatic QNameSet* gNameCache;\n\nQualifiedName::QualifiedName(const AtomicString& p, const AtomicString& l, const AtomicString& n)\n{\n if (!gNameCache)\n gNameCache = new QNameSet;\n QualifiedNameComponents components = { p.impl(), l.impl(), n.isEmpty() ? nullAtom.impl() : n.impl() };\n QNameSet::AddResult addResult = gNameCache->add<QNameComponentsTranslator>(components);\n m_impl = *addResult.iterator;\n if (!addResult.isNewEntry)\n m_impl->ref();\n}\n\nQualifiedName::~QualifiedName()\n{\n deref();\n}\n\nvoid QualifiedName::deref()\n{\n#ifdef QNAME_DEFAULT_CONSTRUCTOR\n if (!m_impl)\n return;\n#endif\n ASSERT(!isHashTableDeletedValue());\n m_impl->deref();\n}\n\nQualifiedName::QualifiedNameImpl::~QualifiedNameImpl()\n{\n gNameCache->remove(this);\n}\n\nString QualifiedName::toString() const\n{\n String local = localName();\n if (hasPrefix())\n return prefix().string() + \":\" + local;\n return local;\n}\n\n\/\/ Global init routines\nDEFINE_GLOBAL(QualifiedName, anyName, nullAtom, starAtom, starAtom)\n\nvoid QualifiedName::init()\n{\n ASSERT(starAtom.impl());\n new ((void*)&anyName) QualifiedName(nullAtom, starAtom, starAtom);\n}\n\nconst QualifiedName& nullQName()\n{\n DEFINE_STATIC_LOCAL(QualifiedName, nullName, (nullAtom, nullAtom, nullAtom));\n return nullName;\n}\n\nconst AtomicString& QualifiedName::localNameUpper() const\n{\n if (!m_impl->m_localNameUpper)\n m_impl->m_localNameUpper = m_impl->m_localName.upper();\n return m_impl->m_localNameUpper;\n}\n\nunsigned QualifiedName::QualifiedNameImpl::computeHash() const\n{\n QualifiedNameComponents components = { m_prefix.impl(), m_localName.impl(), m_namespace.impl() };\n return hashComponents(components);\n}\n\nvoid createQualifiedName(void* targetAddress, StringImpl* name, const AtomicString& nameNamespace)\n{\n new (targetAddress) QualifiedName(nullAtom, AtomicString(name), nameNamespace);\n}\n\nvoid createQualifiedName(void* targetAddress, StringImpl* name)\n{\n new (targetAddress) QualifiedName(nullAtom, AtomicString(name), nullAtom);\n}\n\n}\n<commit_msg>ASSERT that QualifiedNames are only ever created\/destroyed on the main thread<commit_after>\/*\n * Copyright (C) 2005, 2006, 2009 Apple 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 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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"config.h\"\n\n#ifdef SKIP_STATIC_CONSTRUCTORS_ON_GCC\n#define WEBCORE_QUALIFIEDNAME_HIDE_GLOBALS 1\n#else\n#define QNAME_DEFAULT_CONSTRUCTOR\n#endif\n\n#include \"HTMLNames.h\"\n#include \"SVGNames.h\"\n#include \"XLinkNames.h\"\n#include \"XMLNSNames.h\"\n#include \"XMLNames.h\"\n#include \"core\/dom\/QualifiedName.h\"\n#include \"wtf\/Assertions.h\"\n#include \"wtf\/HashSet.h\"\n#include \"wtf\/MainThread.h\"\n#include \"wtf\/StaticConstructors.h\"\n\nnamespace WebCore {\n\nstatic const int staticQualifiedNamesCount = HTMLNames::HTMLTagsCount + HTMLNames::HTMLAttrsCount\n + SVGNames::SVGTagsCount + SVGNames::SVGAttrsCount\n + XLinkNames::XLinkAttrsCount\n + XMLNSNames::XMLNSAttrsCount\n + XMLNames::XMLAttrsCount;\n\nstruct QualifiedNameHashTraits : public HashTraits<QualifiedName::QualifiedNameImpl*> {\n static const int minimumTableSize = WTF::HashTableCapacityForSize<staticQualifiedNamesCount>::value;\n};\n\ntypedef HashSet<QualifiedName::QualifiedNameImpl*, QualifiedNameHash, QualifiedNameHashTraits> QualifiedNameCache;\n\nstatic QualifiedNameCache& qualifiedNameCache()\n{\n \/\/ This code is lockless and thus assumes it all runs on one thread!\n ASSERT(isMainThread());\n static QualifiedNameCache* gNameCache = new QualifiedNameCache;\n return *gNameCache;\n}\n\nstruct QNameComponentsTranslator {\n static unsigned hash(const QualifiedNameComponents& components)\n {\n return hashComponents(components);\n }\n static bool equal(QualifiedName::QualifiedNameImpl* name, const QualifiedNameComponents& c)\n {\n return c.m_prefix == name->m_prefix.impl() && c.m_localName == name->m_localName.impl() && c.m_namespace == name->m_namespace.impl();\n }\n static void translate(QualifiedName::QualifiedNameImpl*& location, const QualifiedNameComponents& components, unsigned)\n {\n location = QualifiedName::QualifiedNameImpl::create(components.m_prefix, components.m_localName, components.m_namespace).leakRef();\n }\n};\n\nQualifiedName::QualifiedName(const AtomicString& p, const AtomicString& l, const AtomicString& n)\n{\n QualifiedNameComponents components = { p.impl(), l.impl(), n.isEmpty() ? nullAtom.impl() : n.impl() };\n QualifiedNameCache::AddResult addResult = qualifiedNameCache().add<QNameComponentsTranslator>(components);\n m_impl = *addResult.iterator;\n if (!addResult.isNewEntry)\n m_impl->ref();\n}\n\nQualifiedName::~QualifiedName()\n{\n deref();\n}\n\nvoid QualifiedName::deref()\n{\n#ifdef QNAME_DEFAULT_CONSTRUCTOR\n if (!m_impl)\n return;\n#endif\n ASSERT(!isHashTableDeletedValue());\n m_impl->deref();\n}\n\nQualifiedName::QualifiedNameImpl::~QualifiedNameImpl()\n{\n qualifiedNameCache().remove(this);\n}\n\nString QualifiedName::toString() const\n{\n String local = localName();\n if (hasPrefix())\n return prefix().string() + \":\" + local;\n return local;\n}\n\n\/\/ Global init routines\nDEFINE_GLOBAL(QualifiedName, anyName, nullAtom, starAtom, starAtom)\n\nvoid QualifiedName::init()\n{\n ASSERT(starAtom.impl());\n new ((void*)&anyName) QualifiedName(nullAtom, starAtom, starAtom);\n}\n\nconst QualifiedName& nullQName()\n{\n DEFINE_STATIC_LOCAL(QualifiedName, nullName, (nullAtom, nullAtom, nullAtom));\n return nullName;\n}\n\nconst AtomicString& QualifiedName::localNameUpper() const\n{\n if (!m_impl->m_localNameUpper)\n m_impl->m_localNameUpper = m_impl->m_localName.upper();\n return m_impl->m_localNameUpper;\n}\n\nunsigned QualifiedName::QualifiedNameImpl::computeHash() const\n{\n QualifiedNameComponents components = { m_prefix.impl(), m_localName.impl(), m_namespace.impl() };\n return hashComponents(components);\n}\n\nvoid createQualifiedName(void* targetAddress, StringImpl* name, const AtomicString& nameNamespace)\n{\n new (targetAddress) QualifiedName(nullAtom, AtomicString(name), nameNamespace);\n}\n\nvoid createQualifiedName(void* targetAddress, StringImpl* name)\n{\n new (targetAddress) QualifiedName(nullAtom, AtomicString(name), nullAtom);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***\nCopyright (C) 2013 Aniket Deole <aniket.deole@gmail.com>\nThis program is free software: you can redistribute it and\/or modify it\nunder the terms of the GNU Lesser General Public License version 2.1, as published\nby the Free Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranties of\nMERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR\nPURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along\nwith this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n***\/\n#include <iostream>\n#include \"notepaneview.hh\"\n\/*\n * This files contains C Code as I was not able to find a good C++ gtkmm e\n * equivalent wrapper for webkit. Open to suggestions :)\n *\/\n\nNotePaneView::NotePaneView (bool homogeneous, int spacing, Gtk::PackOptions options, int padding) {\n\tset_orientation (Gtk::ORIENTATION_VERTICAL);\n\n\tnoteTitle = Gtk::manage (new Gtk::Entry ());\n\tnoteTitle->set_text (\"NoteTitle\");\n\tnoteTitle->set_has_frame (false);\n\tnoteTitle->set_editable (true);\n\t\n\taddCss (noteTitle, \"noteTitle\", \".noteTitle {\\n color:#000;\\n font: OpenSans light 18; padding-top:10px;padding-bottom:10px; \"\n\t\t\t\t\t\t\t\t\"padding-left:14px; background-image:none; background-color:white;\\n}\\n\"\n\t\t\t\t\t\t\t\t\".noteTitle:selected { background-color: #34393D; color:white ; }\");\n\n\tGtk::EventBox* ev = Gtk::manage (new Gtk::EventBox ());\n\n\tGtk::Box* noteTitleAndSaveButtonBox = Gtk::manage (new Gtk::Box ());\n\n\tsaveButton = Gtk::manage (new Gtk::Button (\" Save Note \"));\n\n \tsaveButton->signal_clicked().connect(\n sigc::mem_fun(*this, &NotePaneView::saveNote) );\n\n\tnoteTitleAndSaveButtonBox->pack_start (*noteTitle, true, true, 0);\n\tnoteTitleAndSaveButtonBox->pack_end (*saveButton, false, false, 0);\n\n\tev->add (*noteTitleAndSaveButtonBox);\n\n\taddCss (ev, \"ev\", \".ev { background-image:none; background-color:white;\\n}\\n\");\n\n\n\tpack_start (*ev, false, false, 0);\n\n\tGtk::Separator* sepBot = Gtk::manage (new Gtk::Separator (Gtk::ORIENTATION_HORIZONTAL));\n\tpack_start (*sepBot, false, false, 0);\n\n\n\n\twebviewWrapper = Gtk::manage (new Gtk::ScrolledWindow ());\n\n\twebview = WEBKIT_WEB_VIEW(webkit_web_view_new());\n\t\n\tGtkScrolledWindow* webviewWrapper_c = webviewWrapper->gobj ();\n\tgtk_container_add (GTK_CONTAINER (webviewWrapper_c), GTK_WIDGET (webview));\n\n\twebkit_web_view_set_editable(webview, true);\n \n\twebkit_web_view_load_string (webview, \"No Notes :(\", \"text\/html\", NULL, NULL);\n\n\tWebKitWebSettings* wkws = webkit_web_view_get_settings ( webview);\n\tg_object_set (G_OBJECT(wkws), \"default-font-size\", 10, NULL);\t\n\tg_object_set (G_OBJECT(wkws), \"enable-offline-web-application-cache\", true, NULL);\t\n\tg_object_set (G_OBJECT(wkws), \"tab-key-cycles-through-elements\", false, NULL);\t\n\n\n\twebviewWrapper->set_policy (Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);\n\tpack_start (*webviewWrapper);\n\n\tshow_all ();\n}\n\nNotePaneView::~NotePaneView () {}\n\n\nvoid NotePaneView::setDatabaseManager (DatabaseManager* d) {\n dbm = d;\n}\n\nvoid NotePaneView::setNote (NoteData n) {\n\tsetWebViewContent (n.getBody ());\n\tsetNoteTitleEntryText (n.getTitle ());\n\tnd = n;\n}\n\nvoid NotePaneView::setNoteTitleEntryText (std::string content) {\n\tnoteTitle->set_text (content);\n}\n\nvoid NotePaneView::setWebViewContent (std::string content) {\n\twebkit_web_view_load_string (webview, content.c_str (), \"text\/html\", NULL, NULL);\n}\n\nvoid NotePaneView::newNote () {\n\twebkit_web_view_load_string (webview, \"\", \"text\/html\", NULL, NULL);\n}\n\nvoid NotePaneView::disableButtons () {\n\tsaveButton->set_sensitive (false);\n}\n\nvoid NotePaneView::enableButtons () {\n\tsaveButton->set_sensitive (true);\n}\n\nstd::string\nreplaceSingleQuote( std::string const& original )\n{\n std::string results(\n original.size() \n + std::count( original.begin(), original.end(), '\\''),\n '\\'' );\n std::string::iterator dest = results.begin();\n for ( std::string::const_iterator current = original.begin();\n current != original.end();\n ++ current ) {\n if ( *current == '\\'' ) {\n ++ dest;\n }\n *dest = *current;\n ++ dest;\n }\n return results;\n}\n\ntemplate <typename T>\nstd::string NumberToString(T pNumber)\n{\n std::ostringstream oOStrStream;\n oOStrStream << pNumber;\n return oOStrStream.str();\n}\n\nvoid NotePaneView::saveNote () {\n\n std::string body = \"\";\n\twebkit_web_view_execute_script (webview, \"document.title=document.documentElement.innerHTML;\");\n\tbody.append (webkit_web_frame_get_title ((webkit_web_view_get_main_frame (webview))));\n\tbody = replaceSingleQuote (body);\n\n\tstd::string title = replaceSingleQuote (noteTitle->get_text ());\n\tstd::cout << \"saved: \" << \"update notes set title = '\" + title + \"', body = '\" + body + \"' where id = \" + NumberToString (nd.getPrimaryKey ()) \t<< std::endl;\n \tdbm->exec (\"update notes set title = '\" + title + \"', body = '\" + body + \"', modified_time = strftime('%s','now') where id = \" + NumberToString (nd.getPrimaryKey ()), NULL, this);\n\n \tapp->nlpv->fetchNotesForNotebook (app->lpv->getSelectedNotebookId ());\n}<commit_msg>Styled the save button to a white background.<commit_after>\/***\nCopyright (C) 2013 Aniket Deole <aniket.deole@gmail.com>\nThis program is free software: you can redistribute it and\/or modify it\nunder the terms of the GNU Lesser General Public License version 2.1, as published\nby the Free Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranties of\nMERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR\nPURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along\nwith this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n***\/\n#include <iostream>\n#include \"notepaneview.hh\"\n\/*\n * This files contains C Code as I was not able to find a good C++ gtkmm e\n * equivalent wrapper for webkit. Open to suggestions :)\n *\/\n\nNotePaneView::NotePaneView (bool homogeneous, int spacing, Gtk::PackOptions options, int padding) {\n\tset_orientation (Gtk::ORIENTATION_VERTICAL);\n\n\tnoteTitle = Gtk::manage (new Gtk::Entry ());\n\tnoteTitle->set_text (\"NoteTitle\");\n\tnoteTitle->set_has_frame (false);\n\tnoteTitle->set_editable (true);\n\t\n\taddCss (noteTitle, \"noteTitle\", \".noteTitle {\\n color:#000;\\n font: OpenSans light 18; padding-top:10px;padding-bottom:10px; \"\n\t\t\t\t\t\t\t\t\"padding-left:14px; background-image:none; background-color:white;\\n}\\n\"\n\t\t\t\t\t\t\t\t\".noteTitle:selected { background-color: #34393D; color:white ; }\");\n\n\tGtk::EventBox* ev = Gtk::manage (new Gtk::EventBox ());\n\n\tGtk::Box* noteTitleAndSaveButtonBox = Gtk::manage (new Gtk::Box ());\n\n\n\tGtk::Separator* sepVert = Gtk::manage (new Gtk::Separator (Gtk::ORIENTATION_VERTICAL));\n\n\tsaveButton = Gtk::manage (new Gtk::Button (\" Save Note \"));\n\taddCss (saveButton, \"saveButton\", \".saveButton { background-image:none; background-color:white;\"\n\t\t\"border-radius: 0px; border: 0px solid; -unico-inner-stroke-width: 0px;\t-unico-outer-stroke-width: 0px;-GtkButton-inner-border: 0;\\n}\\n\");\n\n \tsaveButton->signal_clicked().connect(\n sigc::mem_fun(*this, &NotePaneView::saveNote) );\n\n\tnoteTitleAndSaveButtonBox->pack_start (*noteTitle, true, true, 0);\n\tnoteTitleAndSaveButtonBox->pack_start (*sepVert, false, false, 0);\n\tnoteTitleAndSaveButtonBox->pack_end (*saveButton, false, false, 0);\n\n\tev->add (*noteTitleAndSaveButtonBox);\n\n\taddCss (ev, \"ev\", \".ev { background-image:none; background-color:white;\\n}\\n\");\n\n\n\tpack_start (*ev, false, false, 0);\n\n\tGtk::Separator* sepBot = Gtk::manage (new Gtk::Separator (Gtk::ORIENTATION_HORIZONTAL));\n\tpack_start (*sepBot, false, false, 0);\n\n\n\n\twebviewWrapper = Gtk::manage (new Gtk::ScrolledWindow ());\n\n\twebview = WEBKIT_WEB_VIEW(webkit_web_view_new());\n\t\n\tGtkScrolledWindow* webviewWrapper_c = webviewWrapper->gobj ();\n\tgtk_container_add (GTK_CONTAINER (webviewWrapper_c), GTK_WIDGET (webview));\n\n\twebkit_web_view_set_editable(webview, true);\n \n\twebkit_web_view_load_string (webview, \"No Notes :(\", \"text\/html\", NULL, NULL);\n\n\tWebKitWebSettings* wkws = webkit_web_view_get_settings ( webview);\n\tg_object_set (G_OBJECT(wkws), \"default-font-size\", 10, NULL);\t\n\tg_object_set (G_OBJECT(wkws), \"enable-offline-web-application-cache\", true, NULL);\t\n\tg_object_set (G_OBJECT(wkws), \"tab-key-cycles-through-elements\", false, NULL);\t\n\n\n\twebviewWrapper->set_policy (Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);\n\tpack_start (*webviewWrapper);\n\n\tshow_all ();\n}\n\nNotePaneView::~NotePaneView () {}\n\n\nvoid NotePaneView::setDatabaseManager (DatabaseManager* d) {\n dbm = d;\n}\n\nvoid NotePaneView::setNote (NoteData n) {\n\tsetWebViewContent (n.getBody ());\n\tsetNoteTitleEntryText (n.getTitle ());\n\tnd = n;\n}\n\nvoid NotePaneView::setNoteTitleEntryText (std::string content) {\n\tnoteTitle->set_text (content);\n}\n\nvoid NotePaneView::setWebViewContent (std::string content) {\n\twebkit_web_view_load_string (webview, content.c_str (), \"text\/html\", NULL, NULL);\n}\n\nvoid NotePaneView::newNote () {\n\twebkit_web_view_load_string (webview, \"\", \"text\/html\", NULL, NULL);\n}\n\nvoid NotePaneView::disableButtons () {\n\tsaveButton->set_sensitive (false);\n}\n\nvoid NotePaneView::enableButtons () {\n\tsaveButton->set_sensitive (true);\n}\n\nstd::string\nreplaceSingleQuote( std::string const& original )\n{\n std::string results(\n original.size() \n + std::count( original.begin(), original.end(), '\\''),\n '\\'' );\n std::string::iterator dest = results.begin();\n for ( std::string::const_iterator current = original.begin();\n current != original.end();\n ++ current ) {\n if ( *current == '\\'' ) {\n ++ dest;\n }\n *dest = *current;\n ++ dest;\n }\n return results;\n}\n\ntemplate <typename T>\nstd::string NumberToString(T pNumber)\n{\n std::ostringstream oOStrStream;\n oOStrStream << pNumber;\n return oOStrStream.str();\n}\n\nvoid NotePaneView::saveNote () {\n\n std::string body = \"\";\n\twebkit_web_view_execute_script (webview, \"document.title=document.documentElement.innerHTML;\");\n\tbody.append (webkit_web_frame_get_title ((webkit_web_view_get_main_frame (webview))));\n\tbody = replaceSingleQuote (body);\n\n\tstd::string title = replaceSingleQuote (noteTitle->get_text ());\n\tstd::cout << \"saved: \" << \"update notes set title = '\" + title + \"', body = '\" + body + \"' where id = \" + NumberToString (nd.getPrimaryKey ()) \t<< std::endl;\n \tdbm->exec (\"update notes set title = '\" + title + \"', body = '\" + body + \"', modified_time = strftime('%s','now') where id = \" + NumberToString (nd.getPrimaryKey ()), NULL, this);\n\n \tapp->nlpv->fetchNotesForNotebook (app->lpv->getSelectedNotebookId ());\n}<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"content\/renderer\/pepper\/pepper_websocket_host.h\"\n\n#include <string>\n\n#include \"content\/public\/renderer\/renderer_ppapi_host.h\"\n#include \"net\/base\/net_util.h\"\n#include \"ppapi\/c\/pp_errors.h\"\n#include \"ppapi\/c\/ppb_websocket.h\"\n#include \"ppapi\/host\/dispatch_host_message.h\"\n#include \"ppapi\/host\/host_message_context.h\"\n#include \"ppapi\/host\/ppapi_host.h\"\n#include \"ppapi\/proxy\/ppapi_messages.h\"\n#include \"third_party\/WebKit\/public\/platform\/WebString.h\"\n#include \"third_party\/WebKit\/public\/platform\/WebURL.h\"\n#include \"third_party\/WebKit\/public\/web\/WebArrayBuffer.h\"\n#include \"third_party\/WebKit\/public\/web\/WebDocument.h\"\n#include \"third_party\/WebKit\/public\/web\/WebElement.h\"\n#include \"third_party\/WebKit\/public\/web\/WebPluginContainer.h\"\n#include \"third_party\/WebKit\/public\/web\/WebSocket.h\"\n\nusing blink::WebArrayBuffer;\nusing blink::WebDocument;\nusing blink::WebString;\nusing blink::WebSocket;\nusing blink::WebURL;\n\nnamespace content {\n\n#define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name) \\\n COMPILE_ASSERT( \\\n static_cast<int>(WebSocket::webkit_name) == static_cast<int>(np_name), \\\n mismatching_enums)\n\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeNormalClosure,\n PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeGoingAway,\n PP_WEBSOCKETSTATUSCODE_GOING_AWAY);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeProtocolError,\n PP_WEBSOCKETSTATUSCODE_PROTOCOL_ERROR);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeUnsupportedData,\n PP_WEBSOCKETSTATUSCODE_UNSUPPORTED_DATA);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeNoStatusRcvd,\n PP_WEBSOCKETSTATUSCODE_NO_STATUS_RECEIVED);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeAbnormalClosure,\n PP_WEBSOCKETSTATUSCODE_ABNORMAL_CLOSURE);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeInvalidFramePayloadData,\n PP_WEBSOCKETSTATUSCODE_INVALID_FRAME_PAYLOAD_DATA);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodePolicyViolation,\n PP_WEBSOCKETSTATUSCODE_POLICY_VIOLATION);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeMessageTooBig,\n PP_WEBSOCKETSTATUSCODE_MESSAGE_TOO_BIG);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeMandatoryExt,\n PP_WEBSOCKETSTATUSCODE_MANDATORY_EXTENSION);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeInternalError,\n PP_WEBSOCKETSTATUSCODE_INTERNAL_SERVER_ERROR);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeTLSHandshake,\n PP_WEBSOCKETSTATUSCODE_TLS_HANDSHAKE);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeMinimumUserDefined,\n PP_WEBSOCKETSTATUSCODE_USER_REGISTERED_MIN);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeMaximumUserDefined,\n PP_WEBSOCKETSTATUSCODE_USER_PRIVATE_MAX);\n\nPepperWebSocketHost::PepperWebSocketHost(RendererPpapiHost* host,\n PP_Instance instance,\n PP_Resource resource)\n : ResourceHost(host->GetPpapiHost(), instance, resource),\n renderer_ppapi_host_(host),\n connecting_(false),\n initiating_close_(false),\n accepting_close_(false),\n error_was_received_(false) {}\n\nPepperWebSocketHost::~PepperWebSocketHost() {\n if (websocket_)\n websocket_->disconnect();\n}\n\nint32_t PepperWebSocketHost::OnResourceMessageReceived(\n const IPC::Message& msg,\n ppapi::host::HostMessageContext* context) {\n PPAPI_BEGIN_MESSAGE_MAP(PepperWebSocketHost, msg)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Connect,\n OnHostMsgConnect)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Close,\n OnHostMsgClose)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_SendText,\n OnHostMsgSendText)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_SendBinary,\n OnHostMsgSendBinary)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Fail,\n OnHostMsgFail)\n PPAPI_END_MESSAGE_MAP()\n return PP_ERROR_FAILED;\n}\n\nvoid PepperWebSocketHost::didConnect() {\n std::string protocol;\n if (websocket_)\n protocol = websocket_->subprotocol().utf8();\n connecting_ = false;\n connect_reply_.params.set_result(PP_OK);\n host()->SendReply(connect_reply_,\n PpapiPluginMsg_WebSocket_ConnectReply(url_, protocol));\n}\n\nvoid PepperWebSocketHost::didReceiveMessage(const blink::WebString& message) {\n \/\/ Dispose packets after receiving an error.\n if (error_was_received_)\n return;\n\n \/\/ Send an IPC to transport received data.\n std::string string_message = message.utf8();\n host()->SendUnsolicitedReply(\n pp_resource(), PpapiPluginMsg_WebSocket_ReceiveTextReply(string_message));\n}\n\nvoid PepperWebSocketHost::didReceiveArrayBuffer(\n const blink::WebArrayBuffer& binaryData) {\n \/\/ Dispose packets after receiving an error.\n if (error_was_received_)\n return;\n\n \/\/ Send an IPC to transport received data.\n uint8_t* data = static_cast<uint8_t*>(binaryData.data());\n std::vector<uint8_t> array_message(data, data + binaryData.byteLength());\n host()->SendUnsolicitedReply(\n pp_resource(),\n PpapiPluginMsg_WebSocket_ReceiveBinaryReply(array_message));\n}\n\nvoid PepperWebSocketHost::didReceiveMessageError() {\n \/\/ Records the error, then stops receiving any frames after this error.\n \/\/ The error must be notified after all queued messages are read.\n error_was_received_ = true;\n\n \/\/ Send an IPC to report the error. After this IPC, ReceiveTextReply and\n \/\/ ReceiveBinaryReply IPC are not sent anymore because |error_was_received_|\n \/\/ blocks.\n host()->SendUnsolicitedReply(pp_resource(),\n PpapiPluginMsg_WebSocket_ErrorReply());\n}\n\nvoid PepperWebSocketHost::didUpdateBufferedAmount(\n unsigned long buffered_amount) {\n \/\/ Send an IPC to update buffered amount.\n host()->SendUnsolicitedReply(\n pp_resource(),\n PpapiPluginMsg_WebSocket_BufferedAmountReply(buffered_amount));\n}\n\nvoid PepperWebSocketHost::didStartClosingHandshake() {\n accepting_close_ = true;\n\n \/\/ Send an IPC to notice that server starts closing handshake.\n host()->SendUnsolicitedReply(\n pp_resource(),\n PpapiPluginMsg_WebSocket_StateReply(PP_WEBSOCKETREADYSTATE_CLOSING));\n}\n\nvoid PepperWebSocketHost::didClose(unsigned long unhandled_buffered_amount,\n ClosingHandshakeCompletionStatus status,\n unsigned short code,\n const blink::WebString& reason) {\n if (connecting_) {\n connecting_ = false;\n connect_reply_.params.set_result(PP_ERROR_FAILED);\n host()->SendReply(\n connect_reply_,\n PpapiPluginMsg_WebSocket_ConnectReply(url_, std::string()));\n }\n\n \/\/ Set close_was_clean_.\n bool was_clean = (initiating_close_ || accepting_close_) &&\n !unhandled_buffered_amount &&\n status == WebSocketClient::ClosingHandshakeComplete;\n\n if (initiating_close_) {\n initiating_close_ = false;\n close_reply_.params.set_result(PP_OK);\n host()->SendReply(\n close_reply_,\n PpapiPluginMsg_WebSocket_CloseReply(\n unhandled_buffered_amount, was_clean, code, reason.utf8()));\n } else {\n accepting_close_ = false;\n host()->SendUnsolicitedReply(\n pp_resource(),\n PpapiPluginMsg_WebSocket_ClosedReply(\n unhandled_buffered_amount, was_clean, code, reason.utf8()));\n }\n\n \/\/ Disconnect.\n if (websocket_) {\n websocket_->disconnect();\n websocket_.reset();\n }\n}\n\nint32_t PepperWebSocketHost::OnHostMsgConnect(\n ppapi::host::HostMessageContext* context,\n const std::string& url,\n const std::vector<std::string>& protocols) {\n \/\/ Validate url and convert it to WebURL.\n GURL gurl(url);\n url_ = gurl.spec();\n if (!gurl.is_valid())\n return PP_ERROR_BADARGUMENT;\n if (!gurl.SchemeIs(\"ws\") && !gurl.SchemeIs(\"wss\"))\n return PP_ERROR_BADARGUMENT;\n if (gurl.has_ref())\n return PP_ERROR_BADARGUMENT;\n if (!net::IsPortAllowedByDefault(gurl.IntPort()))\n return PP_ERROR_BADARGUMENT;\n WebURL web_url(gurl);\n\n \/\/ Validate protocols.\n std::string protocol_string;\n for (std::vector<std::string>::const_iterator vector_it = protocols.begin();\n vector_it != protocols.end();\n ++vector_it) {\n\n \/\/ Check containing characters.\n for (std::string::const_iterator string_it = vector_it->begin();\n string_it != vector_it->end();\n ++string_it) {\n uint8_t character = *string_it;\n \/\/ WebSocket specification says \"(Subprotocol string must consist of)\n \/\/ characters in the range U+0021 to U+007E not including separator\n \/\/ characters as defined in [RFC2616].\"\n const uint8_t minimumProtocolCharacter = '!'; \/\/ U+0021.\n const uint8_t maximumProtocolCharacter = '~'; \/\/ U+007E.\n if (character < minimumProtocolCharacter ||\n character > maximumProtocolCharacter || character == '\"' ||\n character == '(' || character == ')' || character == ',' ||\n character == '\/' ||\n (character >= ':' && character <= '@') || \/\/ U+003A - U+0040\n (character >= '[' && character <= ']') || \/\/ U+005B - u+005D\n character == '{' ||\n character == '}')\n return PP_ERROR_BADARGUMENT;\n }\n \/\/ Join protocols with the comma separator.\n if (vector_it != protocols.begin())\n protocol_string.append(\",\");\n protocol_string.append(*vector_it);\n }\n\n \/\/ Convert protocols to WebString.\n WebString web_protocols = WebString::fromUTF8(protocol_string);\n\n \/\/ Create blink::WebSocket object and connect.\n blink::WebPluginContainer* container =\n renderer_ppapi_host_->GetContainerForInstance(pp_instance());\n if (!container)\n return PP_ERROR_BADARGUMENT;\n \/\/ TODO(toyoshim) Remove following WebDocument object copy.\n WebDocument document = container->element().document();\n websocket_.reset(WebSocket::create(document, this));\n DCHECK(websocket_.get());\n if (!websocket_)\n return PP_ERROR_NOTSUPPORTED;\n\n \/\/ Set receiving binary object type.\n websocket_->setBinaryType(WebSocket::BinaryTypeArrayBuffer);\n websocket_->connect(web_url, web_protocols);\n\n connect_reply_ = context->MakeReplyMessageContext();\n connecting_ = true;\n return PP_OK_COMPLETIONPENDING;\n}\n\nint32_t PepperWebSocketHost::OnHostMsgClose(\n ppapi::host::HostMessageContext* context,\n int32_t code,\n const std::string& reason) {\n if (!websocket_)\n return PP_ERROR_FAILED;\n close_reply_ = context->MakeReplyMessageContext();\n initiating_close_ = true;\n\n blink::WebSocket::CloseEventCode event_code =\n static_cast<blink::WebSocket::CloseEventCode>(code);\n if (code == PP_WEBSOCKETSTATUSCODE_NOT_SPECIFIED) {\n \/\/ PP_WEBSOCKETSTATUSCODE_NOT_SPECIFIED and CloseEventCodeNotSpecified are\n \/\/ assigned to different values. A conversion is needed if\n \/\/ PP_WEBSOCKETSTATUSCODE_NOT_SPECIFIED is specified.\n event_code = blink::WebSocket::CloseEventCodeNotSpecified;\n }\n\n WebString web_reason = WebString::fromUTF8(reason);\n websocket_->close(event_code, web_reason);\n return PP_OK_COMPLETIONPENDING;\n}\n\nint32_t PepperWebSocketHost::OnHostMsgSendText(\n ppapi::host::HostMessageContext* context,\n const std::string& message) {\n if (websocket_) {\n WebString web_message = WebString::fromUTF8(message);\n websocket_->sendText(web_message);\n }\n return PP_OK;\n}\n\nint32_t PepperWebSocketHost::OnHostMsgSendBinary(\n ppapi::host::HostMessageContext* context,\n const std::vector<uint8_t>& message) {\n if (websocket_.get() && !message.empty()) {\n WebArrayBuffer web_message = WebArrayBuffer::create(message.size(), 1);\n memcpy(web_message.data(), &message.front(), message.size());\n websocket_->sendArrayBuffer(web_message);\n }\n return PP_OK;\n}\n\nint32_t PepperWebSocketHost::OnHostMsgFail(\n ppapi::host::HostMessageContext* context,\n const std::string& message) {\n if (websocket_)\n websocket_->fail(WebString::fromUTF8(message));\n return PP_OK;\n}\n\n} \/\/ namespace content\n<commit_msg>Change pepper websocket port check to use EffectiveIntPort.<commit_after>\/\/ 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 \"content\/renderer\/pepper\/pepper_websocket_host.h\"\n\n#include <string>\n\n#include \"content\/public\/renderer\/renderer_ppapi_host.h\"\n#include \"net\/base\/net_util.h\"\n#include \"ppapi\/c\/pp_errors.h\"\n#include \"ppapi\/c\/ppb_websocket.h\"\n#include \"ppapi\/host\/dispatch_host_message.h\"\n#include \"ppapi\/host\/host_message_context.h\"\n#include \"ppapi\/host\/ppapi_host.h\"\n#include \"ppapi\/proxy\/ppapi_messages.h\"\n#include \"third_party\/WebKit\/public\/platform\/WebString.h\"\n#include \"third_party\/WebKit\/public\/platform\/WebURL.h\"\n#include \"third_party\/WebKit\/public\/web\/WebArrayBuffer.h\"\n#include \"third_party\/WebKit\/public\/web\/WebDocument.h\"\n#include \"third_party\/WebKit\/public\/web\/WebElement.h\"\n#include \"third_party\/WebKit\/public\/web\/WebPluginContainer.h\"\n#include \"third_party\/WebKit\/public\/web\/WebSocket.h\"\n\nusing blink::WebArrayBuffer;\nusing blink::WebDocument;\nusing blink::WebString;\nusing blink::WebSocket;\nusing blink::WebURL;\n\nnamespace content {\n\n#define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name) \\\n COMPILE_ASSERT( \\\n static_cast<int>(WebSocket::webkit_name) == static_cast<int>(np_name), \\\n mismatching_enums)\n\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeNormalClosure,\n PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeGoingAway,\n PP_WEBSOCKETSTATUSCODE_GOING_AWAY);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeProtocolError,\n PP_WEBSOCKETSTATUSCODE_PROTOCOL_ERROR);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeUnsupportedData,\n PP_WEBSOCKETSTATUSCODE_UNSUPPORTED_DATA);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeNoStatusRcvd,\n PP_WEBSOCKETSTATUSCODE_NO_STATUS_RECEIVED);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeAbnormalClosure,\n PP_WEBSOCKETSTATUSCODE_ABNORMAL_CLOSURE);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeInvalidFramePayloadData,\n PP_WEBSOCKETSTATUSCODE_INVALID_FRAME_PAYLOAD_DATA);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodePolicyViolation,\n PP_WEBSOCKETSTATUSCODE_POLICY_VIOLATION);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeMessageTooBig,\n PP_WEBSOCKETSTATUSCODE_MESSAGE_TOO_BIG);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeMandatoryExt,\n PP_WEBSOCKETSTATUSCODE_MANDATORY_EXTENSION);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeInternalError,\n PP_WEBSOCKETSTATUSCODE_INTERNAL_SERVER_ERROR);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeTLSHandshake,\n PP_WEBSOCKETSTATUSCODE_TLS_HANDSHAKE);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeMinimumUserDefined,\n PP_WEBSOCKETSTATUSCODE_USER_REGISTERED_MIN);\nCOMPILE_ASSERT_MATCHING_ENUM(CloseEventCodeMaximumUserDefined,\n PP_WEBSOCKETSTATUSCODE_USER_PRIVATE_MAX);\n\nPepperWebSocketHost::PepperWebSocketHost(RendererPpapiHost* host,\n PP_Instance instance,\n PP_Resource resource)\n : ResourceHost(host->GetPpapiHost(), instance, resource),\n renderer_ppapi_host_(host),\n connecting_(false),\n initiating_close_(false),\n accepting_close_(false),\n error_was_received_(false) {}\n\nPepperWebSocketHost::~PepperWebSocketHost() {\n if (websocket_)\n websocket_->disconnect();\n}\n\nint32_t PepperWebSocketHost::OnResourceMessageReceived(\n const IPC::Message& msg,\n ppapi::host::HostMessageContext* context) {\n PPAPI_BEGIN_MESSAGE_MAP(PepperWebSocketHost, msg)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Connect,\n OnHostMsgConnect)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Close,\n OnHostMsgClose)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_SendText,\n OnHostMsgSendText)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_SendBinary,\n OnHostMsgSendBinary)\n PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Fail,\n OnHostMsgFail)\n PPAPI_END_MESSAGE_MAP()\n return PP_ERROR_FAILED;\n}\n\nvoid PepperWebSocketHost::didConnect() {\n std::string protocol;\n if (websocket_)\n protocol = websocket_->subprotocol().utf8();\n connecting_ = false;\n connect_reply_.params.set_result(PP_OK);\n host()->SendReply(connect_reply_,\n PpapiPluginMsg_WebSocket_ConnectReply(url_, protocol));\n}\n\nvoid PepperWebSocketHost::didReceiveMessage(const blink::WebString& message) {\n \/\/ Dispose packets after receiving an error.\n if (error_was_received_)\n return;\n\n \/\/ Send an IPC to transport received data.\n std::string string_message = message.utf8();\n host()->SendUnsolicitedReply(\n pp_resource(), PpapiPluginMsg_WebSocket_ReceiveTextReply(string_message));\n}\n\nvoid PepperWebSocketHost::didReceiveArrayBuffer(\n const blink::WebArrayBuffer& binaryData) {\n \/\/ Dispose packets after receiving an error.\n if (error_was_received_)\n return;\n\n \/\/ Send an IPC to transport received data.\n uint8_t* data = static_cast<uint8_t*>(binaryData.data());\n std::vector<uint8_t> array_message(data, data + binaryData.byteLength());\n host()->SendUnsolicitedReply(\n pp_resource(),\n PpapiPluginMsg_WebSocket_ReceiveBinaryReply(array_message));\n}\n\nvoid PepperWebSocketHost::didReceiveMessageError() {\n \/\/ Records the error, then stops receiving any frames after this error.\n \/\/ The error must be notified after all queued messages are read.\n error_was_received_ = true;\n\n \/\/ Send an IPC to report the error. After this IPC, ReceiveTextReply and\n \/\/ ReceiveBinaryReply IPC are not sent anymore because |error_was_received_|\n \/\/ blocks.\n host()->SendUnsolicitedReply(pp_resource(),\n PpapiPluginMsg_WebSocket_ErrorReply());\n}\n\nvoid PepperWebSocketHost::didUpdateBufferedAmount(\n unsigned long buffered_amount) {\n \/\/ Send an IPC to update buffered amount.\n host()->SendUnsolicitedReply(\n pp_resource(),\n PpapiPluginMsg_WebSocket_BufferedAmountReply(buffered_amount));\n}\n\nvoid PepperWebSocketHost::didStartClosingHandshake() {\n accepting_close_ = true;\n\n \/\/ Send an IPC to notice that server starts closing handshake.\n host()->SendUnsolicitedReply(\n pp_resource(),\n PpapiPluginMsg_WebSocket_StateReply(PP_WEBSOCKETREADYSTATE_CLOSING));\n}\n\nvoid PepperWebSocketHost::didClose(unsigned long unhandled_buffered_amount,\n ClosingHandshakeCompletionStatus status,\n unsigned short code,\n const blink::WebString& reason) {\n if (connecting_) {\n connecting_ = false;\n connect_reply_.params.set_result(PP_ERROR_FAILED);\n host()->SendReply(\n connect_reply_,\n PpapiPluginMsg_WebSocket_ConnectReply(url_, std::string()));\n }\n\n \/\/ Set close_was_clean_.\n bool was_clean = (initiating_close_ || accepting_close_) &&\n !unhandled_buffered_amount &&\n status == WebSocketClient::ClosingHandshakeComplete;\n\n if (initiating_close_) {\n initiating_close_ = false;\n close_reply_.params.set_result(PP_OK);\n host()->SendReply(\n close_reply_,\n PpapiPluginMsg_WebSocket_CloseReply(\n unhandled_buffered_amount, was_clean, code, reason.utf8()));\n } else {\n accepting_close_ = false;\n host()->SendUnsolicitedReply(\n pp_resource(),\n PpapiPluginMsg_WebSocket_ClosedReply(\n unhandled_buffered_amount, was_clean, code, reason.utf8()));\n }\n\n \/\/ Disconnect.\n if (websocket_) {\n websocket_->disconnect();\n websocket_.reset();\n }\n}\n\nint32_t PepperWebSocketHost::OnHostMsgConnect(\n ppapi::host::HostMessageContext* context,\n const std::string& url,\n const std::vector<std::string>& protocols) {\n \/\/ Validate url and convert it to WebURL.\n GURL gurl(url);\n url_ = gurl.spec();\n if (!gurl.is_valid())\n return PP_ERROR_BADARGUMENT;\n if (!gurl.SchemeIs(\"ws\") && !gurl.SchemeIs(\"wss\"))\n return PP_ERROR_BADARGUMENT;\n if (gurl.has_ref())\n return PP_ERROR_BADARGUMENT;\n if (!net::IsPortAllowedByDefault(gurl.EffectiveIntPort()))\n return PP_ERROR_BADARGUMENT;\n WebURL web_url(gurl);\n\n \/\/ Validate protocols.\n std::string protocol_string;\n for (std::vector<std::string>::const_iterator vector_it = protocols.begin();\n vector_it != protocols.end();\n ++vector_it) {\n\n \/\/ Check containing characters.\n for (std::string::const_iterator string_it = vector_it->begin();\n string_it != vector_it->end();\n ++string_it) {\n uint8_t character = *string_it;\n \/\/ WebSocket specification says \"(Subprotocol string must consist of)\n \/\/ characters in the range U+0021 to U+007E not including separator\n \/\/ characters as defined in [RFC2616].\"\n const uint8_t minimumProtocolCharacter = '!'; \/\/ U+0021.\n const uint8_t maximumProtocolCharacter = '~'; \/\/ U+007E.\n if (character < minimumProtocolCharacter ||\n character > maximumProtocolCharacter || character == '\"' ||\n character == '(' || character == ')' || character == ',' ||\n character == '\/' ||\n (character >= ':' && character <= '@') || \/\/ U+003A - U+0040\n (character >= '[' && character <= ']') || \/\/ U+005B - u+005D\n character == '{' ||\n character == '}')\n return PP_ERROR_BADARGUMENT;\n }\n \/\/ Join protocols with the comma separator.\n if (vector_it != protocols.begin())\n protocol_string.append(\",\");\n protocol_string.append(*vector_it);\n }\n\n \/\/ Convert protocols to WebString.\n WebString web_protocols = WebString::fromUTF8(protocol_string);\n\n \/\/ Create blink::WebSocket object and connect.\n blink::WebPluginContainer* container =\n renderer_ppapi_host_->GetContainerForInstance(pp_instance());\n if (!container)\n return PP_ERROR_BADARGUMENT;\n \/\/ TODO(toyoshim) Remove following WebDocument object copy.\n WebDocument document = container->element().document();\n websocket_.reset(WebSocket::create(document, this));\n DCHECK(websocket_.get());\n if (!websocket_)\n return PP_ERROR_NOTSUPPORTED;\n\n \/\/ Set receiving binary object type.\n websocket_->setBinaryType(WebSocket::BinaryTypeArrayBuffer);\n websocket_->connect(web_url, web_protocols);\n\n connect_reply_ = context->MakeReplyMessageContext();\n connecting_ = true;\n return PP_OK_COMPLETIONPENDING;\n}\n\nint32_t PepperWebSocketHost::OnHostMsgClose(\n ppapi::host::HostMessageContext* context,\n int32_t code,\n const std::string& reason) {\n if (!websocket_)\n return PP_ERROR_FAILED;\n close_reply_ = context->MakeReplyMessageContext();\n initiating_close_ = true;\n\n blink::WebSocket::CloseEventCode event_code =\n static_cast<blink::WebSocket::CloseEventCode>(code);\n if (code == PP_WEBSOCKETSTATUSCODE_NOT_SPECIFIED) {\n \/\/ PP_WEBSOCKETSTATUSCODE_NOT_SPECIFIED and CloseEventCodeNotSpecified are\n \/\/ assigned to different values. A conversion is needed if\n \/\/ PP_WEBSOCKETSTATUSCODE_NOT_SPECIFIED is specified.\n event_code = blink::WebSocket::CloseEventCodeNotSpecified;\n }\n\n WebString web_reason = WebString::fromUTF8(reason);\n websocket_->close(event_code, web_reason);\n return PP_OK_COMPLETIONPENDING;\n}\n\nint32_t PepperWebSocketHost::OnHostMsgSendText(\n ppapi::host::HostMessageContext* context,\n const std::string& message) {\n if (websocket_) {\n WebString web_message = WebString::fromUTF8(message);\n websocket_->sendText(web_message);\n }\n return PP_OK;\n}\n\nint32_t PepperWebSocketHost::OnHostMsgSendBinary(\n ppapi::host::HostMessageContext* context,\n const std::vector<uint8_t>& message) {\n if (websocket_.get() && !message.empty()) {\n WebArrayBuffer web_message = WebArrayBuffer::create(message.size(), 1);\n memcpy(web_message.data(), &message.front(), message.size());\n websocket_->sendArrayBuffer(web_message);\n }\n return PP_OK;\n}\n\nint32_t PepperWebSocketHost::OnHostMsgFail(\n ppapi::host::HostMessageContext* context,\n const std::string& message) {\n if (websocket_)\n websocket_->fail(WebString::fromUTF8(message));\n return PP_OK;\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"<commit_before>\/** Manages the event handling functions in the superloop\n *\n * StageManager.cpp\n * Created 1-28-18 By: Smitty\n *\n * A longer description.\n *\/\n\n#include \"StageManager.hpp\"\n\n\n\n\/** \n * @brief StageManager constructor\n *\/\nStageManager::StageManager(void)\n{\n timerList = new Timer[TIMER_NUM];\n timerList[0].limit = LED_1_POLL;\n timerList[1].limit = LED_2_POLL;\n \n\n \/\/initializing the variables in the Timer array\n for(int i = 0; i < TIMER_NUM; i++) \n {\n \/\/creating the individual mask for each timer\n timerList[i].TFmask = 1 << i;\n timerList[i].count = 0;\n }\n}\n\n\n\/** \n * @brief Handles the multiple timers running off of a single 1ms timer from main\n * @note Might have to be fleshed out more\n * @retval uint32_t with each bit coresponding to which timers went off\n *\/\nuint32_t StageManager::processTimers(Stage currentStage)\n{\n \/\/Goes through the array of timers to increment their count and store which ones popped\n for (int i = 0; i < TIMER_NUM; i++)\n {\n timerList[i].count++;\n if(timerList[i].count >= timerList[i].limit)\n {\n \/\/store which timer popped\n timerTF |= timerList[i].TFmask;\n\n \/\/resetting the count of the timer that just popped\n timerList[i].count = 0;\n }\n\n }\n\n return timerTF;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processCan(Stage currentStage)\n{\n \/\/do CAN stuff\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processCooling(Stage currentStage)\n{\n \/\/do Cooling stuff\n return 0;\n}\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processDash(Stage currentStage)\n{\n \/\/do Dash processing\n\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processGlcd(Stage currentStage)\n{\n \/\/glcd view display updating\n\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processImd(Stage currentStage)\n{ \n return 0;\n}\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processOrion(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processPedal(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processSdCard(Stage currentStage)\n{\n return 0;\n}\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processUnitek(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processBatlog(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processPrecharge(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processReadyToDrive(Stage currentStage)\n{\n return 0;\n}\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processLaunch(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processShutdown(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note Entry condition: EVOS finishes subsystem testing\n * Exit condition: Driver requests Precharging\n * @param &localEventFlags: \n * @param urgencyLevel: \n * @retval \n *\/\nStageManager::Stage StageManager::processEventsStandby(uint32_t &localEventFlags, Priority urgencyLevel)\n{\n Stage currentStage = Stage::STAGE_STANDBY;\n\n switch(urgencyLevel)\n {\n case PRIORITY_CRITICAL:\n\n if(localEventFlags && EF_SHUTDOWN)\n {\n processShutdown(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_SHUTDOWN;\n }\n\n\n if(localEventFlags && EF_IMD)\n {\n processImd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_IMD;\n }\n\n break;\n\n \n case PRIORITY_HIGH:\n \n if(localEventFlags && EF_CAN)\n {\n processCan(currentStage); \n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_CAN;\n }\n\n\n if(localEventFlags && EF_UNITEK)\n {\n processUnitek(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_UNITEK;\n }\n\n\n if(localEventFlags && EF_ORION)\n {\n processOrion(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_ORION;\n }\n \n break;\n\n\n case PRIORITY_MEDIUM:\n\n if(localEventFlags && EF_COOLING)\n {\n processCooling(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_COOLING;\n }\n\n\n if(localEventFlags && EF_BATLOG)\n {\n processBatlog(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_BATLOG;\n }\n\n\n if(localEventFlags && EF_DASH)\n {\n processDash(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_DASH;\n }\n\n break;\n\n\n case PRIORITY_LOW:\n\n if(localEventFlags && TF_GLCD)\n {\n processGlcd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_GLCD;\n }\n\n\n if(localEventFlags && TF_SDCARD)\n {\n processSdCard(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_SDCARD;\n }\n\n break;\n\n } \/\/End switch\n\n return currentStage;\n}\n\n\n\/** \n * @brief \n * @note Entry condition: Driver requests Precharging\n * Exit condition: Precharge done signal recieved from Unitek\n * @param &localEventFlags: \n * @param urgencyLevel: \n * @retval \n *\/\nStageManager::Stage StageManager::processEventsPrecharge(uint32_t &localEventFlags, Priority urgencyLevel)\n{\n Stage currentStage = Stage::STAGE_PRECHARGE;\n\n switch(urgencyLevel)\n {\n case PRIORITY_CRITICAL:\n \/\/code here\n if(localEventFlags && EF_SHUTDOWN)\n {\n processShutdown(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_SHUTDOWN;\n }\n\n\n if(localEventFlags && EF_IMD)\n {\n processImd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_IMD;\n }\n\n break;\n\n \n case PRIORITY_HIGH:\n \/\/code here\n if(localEventFlags && EF_CAN)\n {\n processCan(currentStage); \n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_CAN;\n }\n\n\n if(localEventFlags && EF_UNITEK)\n {\n processUnitek(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_UNITEK;\n }\n\n\n if(localEventFlags && EF_ORION)\n {\n processOrion(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_ORION;\n }\n \n break;\n\n\n case PRIORITY_MEDIUM:\n \/\/code here\n\n if(localEventFlags && EF_COOLING)\n {\n processCooling(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_COOLING;\n }\n\n\n if(localEventFlags && EF_BATLOG)\n {\n processBatlog(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_BATLOG;\n }\n\n\n if(localEventFlags && EF_DASH)\n {\n processDash(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_DASH;\n }\n\n break;\n\n\n case PRIORITY_LOW:\n \/\/code here\n if(localEventFlags && TF_SDCARD)\n {\n processSdCard(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_SDCARD;\n }\n\n\n if(localEventFlags && TF_GLCD)\n {\n processGlcd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_GLCD;\n }\n\n break;\n\n } \/\/End switch\n\n return currentStage;\n}\n\n\n\/** \n * @brief \n * @note Entry condition: Precharge done signal recieved from Unitek\n * Exit condition: Driver requests ready to drive\n * @param &localEventFlags: \n * @param urgencyLevel: \n * @retval \n *\/\nStageManager::Stage StageManager::processEventsEnergized(uint32_t &localEventFlags, Priority urgencyLevel)\n{\n Stage currentStage = Stage::STAGE_ENERGIZED;\n\n switch(urgencyLevel)\n {\n case PRIORITY_CRITICAL:\n \/\/code here\n if(localEventFlags && EF_SHUTDOWN)\n {\n processShutdown(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_SHUTDOWN;\n }\n\n\n if(localEventFlags && EF_IMD)\n {\n processImd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_IMD;\n }\n\n break;\n\n \n case PRIORITY_HIGH:\n \/\/code here\n if(localEventFlags && EF_CAN)\n {\n processCan(currentStage); \n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_CAN;\n }\n\n\n if(localEventFlags && EF_UNITEK)\n {\n processUnitek(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_UNITEK;\n }\n\n\n if(localEventFlags && EF_ORION)\n {\n processOrion(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_ORION;\n }\n \n break;\n\n\n case PRIORITY_MEDIUM:\n \/\/code here\n\n if(localEventFlags && EF_COOLING)\n {\n processCooling(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_COOLING;\n }\n\n\n if(localEventFlags && EF_BATLOG)\n {\n processBatlog(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_BATLOG;\n }\n\n\n if(localEventFlags && EF_DASH)\n {\n processDash(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_DASH;\n }\n\n break;\n\n\n case PRIORITY_LOW:\n \/\/code here\n if(localEventFlags && TF_GLCD)\n {\n processGlcd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_GLCD;\n }\n\n\n if(localEventFlags && TF_SDCARD)\n {\n processSdCard(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_SDCARD;\n }\n\n break;\n\n } \/\/End switch\n\n return currentStage;\n}\n\n\n\/** \n * @brief \n * @note Entry condition: Driver requests ready to drive\n * Exit condition: Driver requests standby\n * @param &localEventFlags: \n * @param urgencyLevel: \n * @retval \n *\/\nStageManager::Stage StageManager::processEventsDriving(uint32_t &localEventFlags, Priority urgencyLevel)\n{\n Stage currentStage = Stage::STAGE_STANDBY;\n\n switch(urgencyLevel)\n {\n case PRIORITY_CRITICAL:\n \/\/code here\n if(localEventFlags && EF_SHUTDOWN)\n {\n processShutdown(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_SHUTDOWN;\n }\n\n\n if(localEventFlags && EF_IMD)\n {\n processImd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_IMD;\n }\n\n break;\n\n \n case PRIORITY_HIGH:\n \/\/code here\n if(localEventFlags && EF_CAN)\n {\n processCan(currentStage); \n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_CAN;\n }\n\n\n if(localEventFlags && EF_UNITEK)\n {\n processUnitek(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_UNITEK;\n }\n\n\n if(localEventFlags && EF_ORION)\n {\n processOrion(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_ORION;\n }\n \n break;\n\n\n case PRIORITY_MEDIUM:\n \/\/code here\n\n if(localEventFlags && EF_COOLING)\n {\n processCooling(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_COOLING;\n }\n\n\n if(localEventFlags && EF_BATLOG)\n {\n processBatlog(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_BATLOG;\n }\n\n\n if(localEventFlags && EF_DASH)\n {\n processDash(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_DASH;\n }\n\n break;\n\n\n case PRIORITY_LOW:\n \/\/code here\n if(localEventFlags && TF_GLCD)\n {\n processGlcd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_GLCD;\n }\n\n\n if(localEventFlags && TF_SDCARD)\n {\n processSdCard(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_SDCARD;\n }\n\n break;\n\n } \/\/End switch\n\n return currentStage;\n}<commit_msg>#25 processPedal function skeleton<commit_after>\/** Manages the event handling functions in the superloop\n *\n * StageManager.cpp\n * Created 1-28-18 By: Smitty\n *\n * A longer description.\n *\/\n\n#include \"StageManager.hpp\"\n\n\n\n\/** \n * @brief StageManager constructor\n *\/\nStageManager::StageManager(void)\n{\n timerList = new Timer[TIMER_NUM];\n timerList[0].limit = LED_1_POLL;\n timerList[1].limit = LED_2_POLL;\n \n\n \/\/initializing the variables in the Timer array\n for(int i = 0; i < TIMER_NUM; i++) \n {\n \/\/creating the individual mask for each timer\n timerList[i].TFmask = 1 << i;\n timerList[i].count = 0;\n }\n}\n\n\n\/** \n * @brief Handles the multiple timers running off of a single 1ms timer from main\n * @note Might have to be fleshed out more\n * @retval uint32_t with each bit coresponding to which timers went off\n *\/\nuint32_t StageManager::processTimers(Stage currentStage)\n{\n \/\/Goes through the array of timers to increment their count and store which ones popped\n for (int i = 0; i < TIMER_NUM; i++)\n {\n timerList[i].count++;\n if(timerList[i].count >= timerList[i].limit)\n {\n \/\/store which timer popped\n timerTF |= timerList[i].TFmask;\n\n \/\/resetting the count of the timer that just popped\n timerList[i].count = 0;\n }\n\n }\n\n return timerTF;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processCan(Stage currentStage)\n{\n \/\/do CAN stuff\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processCooling(Stage currentStage)\n{\n \/\/do Cooling stuff\n return 0;\n}\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processDash(Stage currentStage)\n{\n \/\/do Dash processing\n\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processGlcd(Stage currentStage)\n{\n \/\/glcd view display updating\n\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processImd(Stage currentStage)\n{ \n return 0;\n}\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processOrion(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processPedal(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processSdCard(Stage currentStage)\n{\n return 0;\n}\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processUnitek(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processBatlog(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processPrecharge(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processReadyToDrive(Stage currentStage)\n{\n return 0;\n}\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processLaunch(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note \n * @retval \n *\/\nuint32_t StageManager::processShutdown(Stage currentStage)\n{\n return 0;\n}\n\n\n\/** \n * @brief \n * @note Entry condition: EVOS finishes subsystem testing\n * Exit condition: Driver requests Precharging\n * @param &localEventFlags: \n * @param urgencyLevel: \n * @retval \n *\/\nStageManager::Stage StageManager::processEventsStandby(uint32_t &localEventFlags, Priority urgencyLevel)\n{\n Stage currentStage = Stage::STAGE_STANDBY;\n\n switch(urgencyLevel)\n {\n case PRIORITY_CRITICAL:\n\n if(localEventFlags && EF_SHUTDOWN)\n {\n processShutdown(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_SHUTDOWN;\n }\n\n\n if(localEventFlags && EF_IMD)\n {\n processImd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_IMD;\n }\n\n break;\n\n \n case PRIORITY_HIGH:\n \n if(localEventFlags && EF_CAN)\n {\n processCan(currentStage); \n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_CAN;\n }\n\n\n if(localEventFlags && EF_UNITEK)\n {\n processUnitek(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_UNITEK;\n }\n\n\n if(localEventFlags && EF_ORION)\n {\n processOrion(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_ORION;\n }\n \n break;\n\n\n case PRIORITY_MEDIUM:\n\n if(localEventFlags && EF_COOLING)\n {\n processCooling(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_COOLING;\n }\n\n\n if(localEventFlags && EF_BATLOG)\n {\n processBatlog(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_BATLOG;\n }\n\n\n if(localEventFlags && EF_DASH)\n {\n processDash(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_DASH;\n }\n\n break;\n\n\n case PRIORITY_LOW:\n\n if(localEventFlags && TF_GLCD)\n {\n processGlcd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_GLCD;\n }\n\n\n if(localEventFlags && TF_SDCARD)\n {\n processSdCard(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_SDCARD;\n }\n\n break;\n\n } \/\/End switch\n\n return currentStage;\n}\n\n\n\/** \n * @brief \n * @note Entry condition: Driver requests Precharging\n * Exit condition: Precharge done signal recieved from Unitek\n * @param &localEventFlags: \n * @param urgencyLevel: \n * @retval \n *\/\nStageManager::Stage StageManager::processEventsPrecharge(uint32_t &localEventFlags, Priority urgencyLevel)\n{\n Stage currentStage = Stage::STAGE_PRECHARGE;\n\n switch(urgencyLevel)\n {\n case PRIORITY_CRITICAL:\n \/\/code here\n if(localEventFlags && EF_SHUTDOWN)\n {\n processShutdown(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_SHUTDOWN;\n }\n\n\n if(localEventFlags && EF_IMD)\n {\n processImd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_IMD;\n }\n\n break;\n\n \n case PRIORITY_HIGH:\n \/\/code here\n if(localEventFlags && EF_CAN)\n {\n processCan(currentStage); \n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_CAN;\n }\n\n\n if(localEventFlags && EF_UNITEK)\n {\n processUnitek(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_UNITEK;\n }\n\n\n if(localEventFlags && EF_ORION)\n {\n processOrion(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_ORION;\n }\n \n break;\n\n\n case PRIORITY_MEDIUM:\n \/\/code here\n\n if(localEventFlags && EF_COOLING)\n {\n processCooling(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_COOLING;\n }\n\n\n if(localEventFlags && EF_BATLOG)\n {\n processBatlog(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_BATLOG;\n }\n\n\n if(localEventFlags && EF_DASH)\n {\n processDash(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_DASH;\n }\n\n break;\n\n\n case PRIORITY_LOW:\n \/\/code here\n if(localEventFlags && TF_SDCARD)\n {\n processSdCard(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_SDCARD;\n }\n\n\n if(localEventFlags && TF_GLCD)\n {\n processGlcd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_GLCD;\n }\n\n break;\n\n } \/\/End switch\n\n return currentStage;\n}\n\n\n\/** \n * @brief \n * @note Entry condition: Precharge done signal recieved from Unitek\n * Exit condition: Driver requests ready to drive\n * @param &localEventFlags: \n * @param urgencyLevel: \n * @retval \n *\/\nStageManager::Stage StageManager::processEventsEnergized(uint32_t &localEventFlags, Priority urgencyLevel)\n{\n Stage currentStage = Stage::STAGE_ENERGIZED;\n\n switch(urgencyLevel)\n {\n case PRIORITY_CRITICAL:\n \/\/code here\n if(localEventFlags && EF_SHUTDOWN)\n {\n processShutdown(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_SHUTDOWN;\n }\n\n\n if(localEventFlags && EF_IMD)\n {\n processImd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_IMD;\n }\n\n break;\n\n \n case PRIORITY_HIGH:\n \/\/code here\n if(localEventFlags && EF_CAN)\n {\n processCan(currentStage); \n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_CAN;\n }\n\n\n if(localEventFlags && EF_UNITEK)\n {\n processUnitek(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_UNITEK;\n }\n\n\n if(localEventFlags && EF_ORION)\n {\n processOrion(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_ORION;\n }\n \n break;\n\n\n case PRIORITY_MEDIUM:\n \/\/code here\n\n if(localEventFlags && EF_COOLING)\n {\n processCooling(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_COOLING;\n }\n\n\n if(localEventFlags && EF_BATLOG)\n {\n processBatlog(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_BATLOG;\n }\n\n\n if(localEventFlags && EF_DASH)\n {\n processDash(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_DASH;\n }\n\n break;\n\n\n case PRIORITY_LOW:\n \/\/code here\n if(localEventFlags && TF_GLCD)\n {\n processGlcd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_GLCD;\n }\n\n\n if(localEventFlags && TF_SDCARD)\n {\n processSdCard(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~TF_SDCARD;\n }\n\n break;\n\n } \/\/End switch\n\n return currentStage;\n}\n\n\n\/** \n * @brief \n * @note Entry condition: Driver requests ready to drive\n * Exit condition: Driver requests standby\n * @param &localEventFlags: \n * @param urgencyLevel: \n * @retval \n *\/\nStageManager::Stage StageManager::processEventsDriving(uint32_t &localEventFlags, Priority urgencyLevel)\n{\n Stage currentStage = Stage::STAGE_STANDBY;\n\n switch(urgencyLevel)\n {\n case PRIORITY_CRITICAL:\n \/\/code here\n if(localEventFlags && EF_SHUTDOWN)\n {\n processShutdown(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_SHUTDOWN;\n }\n\n\n if(localEventFlags && EF_IMD)\n {\n processImd(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_IMD;\n }\n\n break;\n\n \n case PRIORITY_HIGH:\n \/\/code here\n if(localEventFlags && EF_CAN)\n {\n processCan(currentStage); \n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_CAN;\n }\n\n\n if(localEventFlags && EF_UNITEK)\n {\n processUnitek(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_UNITEK;\n }\n\n\n if(localEventFlags && EF_ORION)\n {\n processOrion(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_ORION;\n }\n \n break;\n\n\n case PRIORITY_MEDIUM:\n \/\/code here\n\n if(localEventFlags && EF_COOLING)\n {\n processCooling(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_COOLING;\n }\n\n\n if(localEventFlags && EF_BATLOG)\n {\n processBatlog(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_BATLOG;\n }\n\n\n if(localEventFlags && EF_DASH)\n {\n processDash(currentStage);\n \n \/\/clearing the EF so we don't trigger this again\n localEventFlags &= ~EF_DASH;\n }\n\n break;\n\n\n case PRIORITY_LOW:\n \/\/code here\n if(localEventFlags && TF_PEDAL)\n {\n processPedal(currentStage);\n\n \/\/clearing the Flag so we don't trigger this again\n localEventFlags &= ~TF_PEDAL;\n }\n\n\n if(localEventFlags && TF_GLCD)\n {\n processGlcd(currentStage);\n \n \/\/clearing the Flag so we don't trigger this again\n localEventFlags &= ~TF_GLCD;\n }\n\n\n if(localEventFlags && TF_SDCARD)\n {\n processSdCard(currentStage);\n \n \/\/clearing the Flag so we don't trigger this again\n localEventFlags &= ~TF_SDCARD;\n }\n\n break;\n\n } \/\/End switch\n\n return currentStage;\n}<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n#ifndef mitkCLVoxeFeatures_cpp\n#define mitkCLVoxeFeatures_cpp\n\n#include \"time.h\"\n#include <sstream>\n#include <fstream>\n\n#include <mitkIOUtil.h>\n#include <mitkImageAccessByItk.h>\n#include <mitkImageCast.h>\n#include \"mitkCommandLineParser.h\"\n\n#include <mitkGIFCooccurenceMatrix.h>\n#include <mitkGIFGrayLevelRunLength.h>\n\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include <itkLaplacianRecursiveGaussianImageFilter.h>\n#include \"itkHessianRecursiveGaussianImageFilter.h\"\n#include \"itkUnaryFunctorImageFilter.h\"\n#include \"vnl\/algo\/vnl_symmetric_eigensystem.h\"\n#include <itkSubtractImageFilter.h>\n\nstatic vector<double> splitDouble(string str, char delimiter) {\n vector<double> internal;\n stringstream ss(str); \/\/ Turn the string into a stream.\n string tok;\n double val;\n while(getline(ss, tok, delimiter)) {\n stringstream s2(tok);\n s2 >> val;\n internal.push_back(val);\n }\n\n return internal;\n}\n\nnamespace Functor\n{\n template <class TInput, class TOutput>\n class MatrixFirstEigenvalue\n {\n public:\n MatrixFirstEigenvalue() {}\n virtual ~MatrixFirstEigenvalue() {}\n\n int order;\n\n inline TOutput operator ()(const TInput& input)\n {\n double a,b,c;\n if (input[0] < 0.01 && input[1] < 0.01 &&input[2] < 0.01 &&input[3] < 0.01 &&input[4] < 0.01 &&input[5] < 0.01)\n return 0;\n vnl_symmetric_eigensystem_compute_eigenvals(input[0], input[1],input[2],input[3],input[4],input[5],a,b,c);\n switch (order)\n {\n case 0: return a;\n case 1: return b;\n case 2: return c;\n default: return a;\n }\n }\n bool operator !=(const MatrixFirstEigenvalue) const\n {\n return false;\n }\n bool operator ==(const MatrixFirstEigenvalue& other) const\n {\n return !(*this != other);\n }\n };\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\n GaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;\n\n typename GaussFilterType::Pointer gaussianFilter = GaussFilterType::New();\n gaussianFilter->SetInput( itkImage );\n gaussianFilter->SetVariance(variance);\n gaussianFilter->Update();\n mitk::CastToMitkImage(gaussianFilter->GetOutput(), output);\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\n DifferenceOfGaussFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;\n typedef itk::SubtractImageFilter<ImageType, ImageType, ImageType> SubFilterType;\n\n typename GaussFilterType::Pointer gaussianFilter1 = GaussFilterType::New();\n gaussianFilter1->SetInput( itkImage );\n gaussianFilter1->SetVariance(variance);\n gaussianFilter1->Update();\n typename GaussFilterType::Pointer gaussianFilter2 = GaussFilterType::New();\n gaussianFilter2->SetInput( itkImage );\n gaussianFilter2->SetVariance(variance*0.66*0.66);\n gaussianFilter2->Update();\n typename SubFilterType::Pointer subFilter = SubFilterType::New();\n subFilter->SetInput1(gaussianFilter1->GetOutput());\n subFilter->SetInput2(gaussianFilter2->GetOutput());\n subFilter->Update();\n mitk::CastToMitkImage(subFilter->GetOutput(), output);\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\n LaplacianOfGaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;\n typedef itk::LaplacianRecursiveGaussianImageFilter<ImageType, ImageType> LaplacianFilter;\n\n typename GaussFilterType::Pointer gaussianFilter = GaussFilterType::New();\n gaussianFilter->SetInput( itkImage );\n gaussianFilter->SetVariance(variance);\n gaussianFilter->Update();\n typename LaplacianFilter::Pointer laplaceFilter = LaplacianFilter::New();\n laplaceFilter->SetInput(gaussianFilter->GetOutput());\n laplaceFilter->Update();\n mitk::CastToMitkImage(laplaceFilter->GetOutput(), output);\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\n HessianOfGaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, std::vector<mitk::Image::Pointer> &out)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::Image<double, VImageDimension> FloatImageType;\n typedef itk::HessianRecursiveGaussianImageFilter <ImageType> HessianFilterType;\n typedef typename HessianFilterType::OutputImageType VectorImageType;\n typedef Functor::MatrixFirstEigenvalue<VectorImageType::PixelType, double> DeterminantFunctorType;\n typedef itk::UnaryFunctorImageFilter<VectorImageType, FloatImageType, DeterminantFunctorType> DetFilterType;\n\n typename HessianFilterType::Pointer hessianFilter = HessianFilterType::New();\n hessianFilter->SetInput(itkImage);\n hessianFilter->SetSigma(std::sqrt(variance));\n for (int i = 0; i < VImageDimension; ++i)\n {\n typename DetFilterType::Pointer detFilter = DetFilterType::New();\n detFilter->SetInput(hessianFilter->GetOutput());\n detFilter->GetFunctor().order = i;\n detFilter->Update();\n mitk::CastToMitkImage(detFilter->GetOutput(), out[i]);\n }\n}\n\nint main(int argc, char* argv[])\n{\n mitkCommandLineParser parser;\n parser.setArgumentPrefix(\"--\", \"-\");\n \/\/ required params\n parser.addArgument(\"image\", \"i\", mitkCommandLineParser::InputImage, \"Input Image\", \"Path to the input VTK polydata\", us::Any(), false);\n parser.addArgument(\"output\", \"o\", mitkCommandLineParser::OutputFile, \"Output text file\", \"Target file. The output statistic is appended to this file.\", us::Any(), false);\n\n parser.addArgument(\"gaussian\",\"g\",mitkCommandLineParser::String, \"Gaussian Filtering of the input images\", \"Gaussian Filter. Followed by the used variances seperated by ';' \",us::Any());\n parser.addArgument(\"difference-of-gaussian\",\"dog\",mitkCommandLineParser::String, \"Difference of Gaussian Filtering of the input images\", \"Difference of Gaussian Filter. Followed by the used variances seperated by ';' \",us::Any());\n parser.addArgument(\"laplace-of-gauss\",\"log\",mitkCommandLineParser::String, \"Laplacian of Gaussian Filtering\", \"Laplacian of Gaussian Filter. Followed by the used variances seperated by ';' \",us::Any());\n parser.addArgument(\"hessian-of-gauss\",\"hog\",mitkCommandLineParser::String, \"Hessian of Gaussian Filtering\", \"Hessian of Gaussian Filter. Followed by the used variances seperated by ';' \",us::Any());\n \/\/ Miniapp Infos\n parser.setCategory(\"Classification Tools\");\n parser.setTitle(\"Global Image Feature calculator\");\n parser.setDescription(\"Calculates different global statistics for a given segmentation \/ image combination\");\n parser.setContributor(\"MBI\");\n\n map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);\n\n if (parsedArgs.size()==0)\n {\n return EXIT_FAILURE;\n }\n if ( parsedArgs.count(\"help\") || parsedArgs.count(\"h\"))\n {\n return EXIT_SUCCESS;\n }\n bool useCooc = parsedArgs.count(\"cooccurence\");\n\n mitk::Image::Pointer image = mitk::IOUtil::LoadImage(parsedArgs[\"image\"].ToString());\n std::string filename=parsedArgs[\"output\"].ToString();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ CAlculate Gaussian Features\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n MITK_INFO << \"Check for Gaussian...\";\n if (parsedArgs.count(\"gaussian\"))\n {\n MITK_INFO << \"Calculate Gaussian... \" << parsedArgs[\"gaussian\"].ToString();\n auto ranges = splitDouble(parsedArgs[\"gaussian\"].ToString(),';');\n\n for (int i = 0; i < ranges.size(); ++i)\n {\n mitk::Image::Pointer output;\n AccessByItk_2(image, GaussianFilter, ranges[i], output);\n std::string name = filename + \"-gaussian-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(output, name);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ CAlculate Difference of Gaussian Features\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n MITK_INFO << \"Check for DoG...\";\n if (parsedArgs.count(\"difference-of-gaussian\"))\n {\n MITK_INFO << \"Calculate Difference of Gaussian... \" << parsedArgs[\"difference-of-gaussian\"].ToString();\n auto ranges = splitDouble(parsedArgs[\"difference-of-gaussian\"].ToString(),';');\n\n for (int i = 0; i < ranges.size(); ++i)\n {\n mitk::Image::Pointer output;\n AccessByItk_2(image, DifferenceOfGaussFilter, ranges[i], output);\n std::string name = filename + \"-dog-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(output, name);\n }\n }\n\n MITK_INFO << \"Check for LoG...\";\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ CAlculate Laplacian Of Gauss Features\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (parsedArgs.count(\"laplace-of-gauss\"))\n {\n MITK_INFO << \"Calculate LoG... \" << parsedArgs[\"laplace-of-gauss\"].ToString();\n auto ranges = splitDouble(parsedArgs[\"laplace-of-gauss\"].ToString(),';');\n\n for (int i = 0; i < ranges.size(); ++i)\n {\n mitk::Image::Pointer output;\n AccessByItk_2(image, LaplacianOfGaussianFilter, ranges[i], output);\n std::string name = filename + \"-log-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(output, name);\n }\n }\n\n MITK_INFO << \"Check for HoG...\";\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ CAlculate Hessian Of Gauss Features\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (parsedArgs.count(\"hessian-of-gauss\"))\n {\n MITK_INFO << \"Calculate HoG... \" << parsedArgs[\"hessian-of-gauss\"].ToString();\n auto ranges = splitDouble(parsedArgs[\"hessian-of-gauss\"].ToString(),';');\n\n for (int i = 0; i < ranges.size(); ++i)\n {\n std::vector<mitk::Image::Pointer> outs;\n outs.push_back(mitk::Image::New());\n outs.push_back(mitk::Image::New());\n outs.push_back(mitk::Image::New());\n AccessByItk_2(image, HessianOfGaussianFilter, ranges[i], outs);\n std::string name = filename + \"-hog0-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(outs[0], name);\n name = filename + \"-hog1-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(outs[1], name);\n name = filename + \"-hog2-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(outs[2], name);\n }\n }\n\n return 0;\n}\n\n#endif<commit_msg>COMP: Fixed missing typename<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n#ifndef mitkCLVoxeFeatures_cpp\n#define mitkCLVoxeFeatures_cpp\n\n#include \"time.h\"\n#include <sstream>\n#include <fstream>\n\n#include <mitkIOUtil.h>\n#include <mitkImageAccessByItk.h>\n#include <mitkImageCast.h>\n#include \"mitkCommandLineParser.h\"\n\n#include <mitkGIFCooccurenceMatrix.h>\n#include <mitkGIFGrayLevelRunLength.h>\n\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include <itkLaplacianRecursiveGaussianImageFilter.h>\n#include \"itkHessianRecursiveGaussianImageFilter.h\"\n#include \"itkUnaryFunctorImageFilter.h\"\n#include \"vnl\/algo\/vnl_symmetric_eigensystem.h\"\n#include <itkSubtractImageFilter.h>\n\nstatic vector<double> splitDouble(string str, char delimiter) {\n vector<double> internal;\n stringstream ss(str); \/\/ Turn the string into a stream.\n string tok;\n double val;\n while(getline(ss, tok, delimiter)) {\n stringstream s2(tok);\n s2 >> val;\n internal.push_back(val);\n }\n\n return internal;\n}\n\nnamespace Functor\n{\n template <class TInput, class TOutput>\n class MatrixFirstEigenvalue\n {\n public:\n MatrixFirstEigenvalue() {}\n virtual ~MatrixFirstEigenvalue() {}\n\n int order;\n\n inline TOutput operator ()(const TInput& input)\n {\n double a,b,c;\n if (input[0] < 0.01 && input[1] < 0.01 &&input[2] < 0.01 &&input[3] < 0.01 &&input[4] < 0.01 &&input[5] < 0.01)\n return 0;\n vnl_symmetric_eigensystem_compute_eigenvals(input[0], input[1],input[2],input[3],input[4],input[5],a,b,c);\n switch (order)\n {\n case 0: return a;\n case 1: return b;\n case 2: return c;\n default: return a;\n }\n }\n bool operator !=(const MatrixFirstEigenvalue) const\n {\n return false;\n }\n bool operator ==(const MatrixFirstEigenvalue& other) const\n {\n return !(*this != other);\n }\n };\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\n GaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;\n\n typename GaussFilterType::Pointer gaussianFilter = GaussFilterType::New();\n gaussianFilter->SetInput( itkImage );\n gaussianFilter->SetVariance(variance);\n gaussianFilter->Update();\n mitk::CastToMitkImage(gaussianFilter->GetOutput(), output);\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\n DifferenceOfGaussFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;\n typedef itk::SubtractImageFilter<ImageType, ImageType, ImageType> SubFilterType;\n\n typename GaussFilterType::Pointer gaussianFilter1 = GaussFilterType::New();\n gaussianFilter1->SetInput( itkImage );\n gaussianFilter1->SetVariance(variance);\n gaussianFilter1->Update();\n typename GaussFilterType::Pointer gaussianFilter2 = GaussFilterType::New();\n gaussianFilter2->SetInput( itkImage );\n gaussianFilter2->SetVariance(variance*0.66*0.66);\n gaussianFilter2->Update();\n typename SubFilterType::Pointer subFilter = SubFilterType::New();\n subFilter->SetInput1(gaussianFilter1->GetOutput());\n subFilter->SetInput2(gaussianFilter2->GetOutput());\n subFilter->Update();\n mitk::CastToMitkImage(subFilter->GetOutput(), output);\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\n LaplacianOfGaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;\n typedef itk::LaplacianRecursiveGaussianImageFilter<ImageType, ImageType> LaplacianFilter;\n\n typename GaussFilterType::Pointer gaussianFilter = GaussFilterType::New();\n gaussianFilter->SetInput( itkImage );\n gaussianFilter->SetVariance(variance);\n gaussianFilter->Update();\n typename LaplacianFilter::Pointer laplaceFilter = LaplacianFilter::New();\n laplaceFilter->SetInput(gaussianFilter->GetOutput());\n laplaceFilter->Update();\n mitk::CastToMitkImage(laplaceFilter->GetOutput(), output);\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\n HessianOfGaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, std::vector<mitk::Image::Pointer> &out)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::Image<double, VImageDimension> FloatImageType;\n typedef itk::HessianRecursiveGaussianImageFilter <ImageType> HessianFilterType;\n typedef typename HessianFilterType::OutputImageType VectorImageType;\n typedef Functor::MatrixFirstEigenvalue<typename VectorImageType::PixelType, double> DeterminantFunctorType;\n typedef itk::UnaryFunctorImageFilter<VectorImageType, FloatImageType, DeterminantFunctorType> DetFilterType;\n\n typename HessianFilterType::Pointer hessianFilter = HessianFilterType::New();\n hessianFilter->SetInput(itkImage);\n hessianFilter->SetSigma(std::sqrt(variance));\n for (int i = 0; i < VImageDimension; ++i)\n {\n typename DetFilterType::Pointer detFilter = DetFilterType::New();\n detFilter->SetInput(hessianFilter->GetOutput());\n detFilter->GetFunctor().order = i;\n detFilter->Update();\n mitk::CastToMitkImage(detFilter->GetOutput(), out[i]);\n }\n}\n\nint main(int argc, char* argv[])\n{\n mitkCommandLineParser parser;\n parser.setArgumentPrefix(\"--\", \"-\");\n \/\/ required params\n parser.addArgument(\"image\", \"i\", mitkCommandLineParser::InputImage, \"Input Image\", \"Path to the input VTK polydata\", us::Any(), false);\n parser.addArgument(\"output\", \"o\", mitkCommandLineParser::OutputFile, \"Output text file\", \"Target file. The output statistic is appended to this file.\", us::Any(), false);\n\n parser.addArgument(\"gaussian\",\"g\",mitkCommandLineParser::String, \"Gaussian Filtering of the input images\", \"Gaussian Filter. Followed by the used variances seperated by ';' \",us::Any());\n parser.addArgument(\"difference-of-gaussian\",\"dog\",mitkCommandLineParser::String, \"Difference of Gaussian Filtering of the input images\", \"Difference of Gaussian Filter. Followed by the used variances seperated by ';' \",us::Any());\n parser.addArgument(\"laplace-of-gauss\",\"log\",mitkCommandLineParser::String, \"Laplacian of Gaussian Filtering\", \"Laplacian of Gaussian Filter. Followed by the used variances seperated by ';' \",us::Any());\n parser.addArgument(\"hessian-of-gauss\",\"hog\",mitkCommandLineParser::String, \"Hessian of Gaussian Filtering\", \"Hessian of Gaussian Filter. Followed by the used variances seperated by ';' \",us::Any());\n \/\/ Miniapp Infos\n parser.setCategory(\"Classification Tools\");\n parser.setTitle(\"Global Image Feature calculator\");\n parser.setDescription(\"Calculates different global statistics for a given segmentation \/ image combination\");\n parser.setContributor(\"MBI\");\n\n map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);\n\n if (parsedArgs.size()==0)\n {\n return EXIT_FAILURE;\n }\n if ( parsedArgs.count(\"help\") || parsedArgs.count(\"h\"))\n {\n return EXIT_SUCCESS;\n }\n bool useCooc = parsedArgs.count(\"cooccurence\");\n\n mitk::Image::Pointer image = mitk::IOUtil::LoadImage(parsedArgs[\"image\"].ToString());\n std::string filename=parsedArgs[\"output\"].ToString();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ CAlculate Gaussian Features\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n MITK_INFO << \"Check for Gaussian...\";\n if (parsedArgs.count(\"gaussian\"))\n {\n MITK_INFO << \"Calculate Gaussian... \" << parsedArgs[\"gaussian\"].ToString();\n auto ranges = splitDouble(parsedArgs[\"gaussian\"].ToString(),';');\n\n for (int i = 0; i < ranges.size(); ++i)\n {\n mitk::Image::Pointer output;\n AccessByItk_2(image, GaussianFilter, ranges[i], output);\n std::string name = filename + \"-gaussian-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(output, name);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ CAlculate Difference of Gaussian Features\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n MITK_INFO << \"Check for DoG...\";\n if (parsedArgs.count(\"difference-of-gaussian\"))\n {\n MITK_INFO << \"Calculate Difference of Gaussian... \" << parsedArgs[\"difference-of-gaussian\"].ToString();\n auto ranges = splitDouble(parsedArgs[\"difference-of-gaussian\"].ToString(),';');\n\n for (int i = 0; i < ranges.size(); ++i)\n {\n mitk::Image::Pointer output;\n AccessByItk_2(image, DifferenceOfGaussFilter, ranges[i], output);\n std::string name = filename + \"-dog-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(output, name);\n }\n }\n\n MITK_INFO << \"Check for LoG...\";\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ CAlculate Laplacian Of Gauss Features\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (parsedArgs.count(\"laplace-of-gauss\"))\n {\n MITK_INFO << \"Calculate LoG... \" << parsedArgs[\"laplace-of-gauss\"].ToString();\n auto ranges = splitDouble(parsedArgs[\"laplace-of-gauss\"].ToString(),';');\n\n for (int i = 0; i < ranges.size(); ++i)\n {\n mitk::Image::Pointer output;\n AccessByItk_2(image, LaplacianOfGaussianFilter, ranges[i], output);\n std::string name = filename + \"-log-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(output, name);\n }\n }\n\n MITK_INFO << \"Check for HoG...\";\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ CAlculate Hessian Of Gauss Features\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (parsedArgs.count(\"hessian-of-gauss\"))\n {\n MITK_INFO << \"Calculate HoG... \" << parsedArgs[\"hessian-of-gauss\"].ToString();\n auto ranges = splitDouble(parsedArgs[\"hessian-of-gauss\"].ToString(),';');\n\n for (int i = 0; i < ranges.size(); ++i)\n {\n std::vector<mitk::Image::Pointer> outs;\n outs.push_back(mitk::Image::New());\n outs.push_back(mitk::Image::New());\n outs.push_back(mitk::Image::New());\n AccessByItk_2(image, HessianOfGaussianFilter, ranges[i], outs);\n std::string name = filename + \"-hog0-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(outs[0], name);\n name = filename + \"-hog1-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(outs[1], name);\n name = filename + \"-hog2-\" + us::any_value_to_string(ranges[i])+\".nrrd\";\n mitk::IOUtil::SaveImage(outs[2], name);\n }\n }\n\n return 0;\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>void AnalysisTrainFromStandardToMuonAODLocal(char* filein= \"AliAODs.root\", \n char* fileout= \"AliMuonAOD.root\", \n\t\t\t\t char* dirChain= \".\",\n\t\t\t\t char* dirData= \".\"){\n \n\/\/ Macro to produce a MUON-AOD, i.e. a replica of the standard AOD, containing only events\n\/\/ where at least one muon is present\n\/\/ \n\/\/ - The input files are the ESD (used only for tag creation) and the standard AOD.\n\/\/ Tags files are created from all the ESD\/AOD files placed in the directory dirData \n\/\/ and in its subdirectories.\n\/\/ - The selection of the muon events is based on the AOD tags.\n\/\/ - The content of the MUON-AOD can be defined by the user with some settings as\n\/\/ SetNeedsTracksBranchReplication(), SetNeedsVerticesBranchReplication() \n\/\/ (defined in STEER\/AliAODHandler.h)...\n\n\n gSystem->Load(\"libTree.so\");\n gSystem->Load(\"libGeom.so\");\n gSystem->Load(\"libVMC.so\");\n gSystem->Load(\"libPhysics.so\");\n\n \/\/ Load par files \n SetupPar(\"STEERBase\");\n SetupPar(\"ESD\");\n SetupPar(\"AOD\");\n SetupPar(\"ANALYSIS\");\n SetupPar(\"ANALYSISalice\");\n SetupPar(\"PWG3base\"); \n SetupPar(\"PWG3muon\"); \n \n \/\/ Create ESD tag files \n printf(\"Creating ESD Tags\\n\");\n AliESDTagCreator *tesd = new AliESDTagCreator();\n tesd->SetStorage(0); \n tesd->ReadLocalCollection(dirData); \n \n \/\/ Create AOD tag files \n printf(\"Creating AOD Tags\\n\");\n AliAODTagCreator *t = new AliAODTagCreator();\n t->SetStorage(0);\n t->ReadLocalCollection(dirData); \n \n AliTagAnalysis *TagAna = new AliTagAnalysis(\"AOD\"); \n \n \/\/ Define tag cuts to select only events with muons\n printf(\"Defining Tags cuts to select events containing at least one muon\\n\");\n AliRunTagCuts *runCuts = new AliRunTagCuts();\n AliLHCTagCuts *lhcCuts = new AliLHCTagCuts();\n AliDetectorTagCuts *detCuts = new AliDetectorTagCuts();\n AliEventTagCuts *evCuts = new AliEventTagCuts();\n evCuts->SetNMuonRange(1,10);\n \n \/\/ Create the chain of interesting events\n TChain* chain = 0x0;\n TagAna->ChainLocalTags(dirChain);\n chain = TagAna->QueryTags(runCuts,lhcCuts,detCuts,evCuts);\n\n \/\/ Define aod input handler\n AliAODInputHandler* aodInputHandler = new AliAODInputHandler();\n \n \/\/ Define aod output handler\n AliAODHandler* aodOutputHandler = new AliAODHandler();\n\n \/\/ Create non standard AOD\n aodOutputHandler->SetCreateNonStandardAOD(); \n \n \/\/ Select the branches to be written in the MUON-AOD\n aodOutputHandler->SetNeedsHeaderReplication();\n aodOutputHandler->SetNeedsTracksBranchReplication();\n aodOutputHandler->SetNeedsVerticesBranchReplication();\n \/\/aodOutputHandler->SetNeedsV0sBranchReplication();\n \/\/aodOutputHandler->SetNeedsTrackletsBranchReplication(); \n \/\/aodOutputHandler->SetNeedsPMDClustersBranchReplication();\n \/\/aodOutputHandler->SetNeedsJetsBranchReplication();\n \/\/aodOutputHandler->SetNeedsFMDClustersBranchReplication();\n \/\/aodOutputHandler->SetNeedsCaloClustersBranchReplication();\n \n aodOutputHandler->SetOutputFileName(fileout);\n\n \/\/ Define the analysis manager\n AliAnalysisManager *mgr = new AliAnalysisManager(\"AOD Manager\", \"AOD Manager\");\n mgr->SetInputEventHandler(aodInputHandler);\n mgr->SetOutputEventHandler(aodOutputHandler);\n \/\/mgr->SetDebugLevel(10);\n \n AliAnalysisTaskFromStandardToMuonAOD *aodfilter = new AliAnalysisTaskFromStandardToMuonAOD(\"AOD Filter\");\n mgr->AddTask(aodfilter);\n \n \/\/ Create containers for input\/output\n AliAnalysisDataContainer *cinput1 = mgr->CreateContainer(\"cchain\",TChain::Class(), \n\t\t\t\t\t\t\t AliAnalysisManager::kInputContainer);\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"tree\", TTree::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer, \"default\");\n\n mgr->ConnectInput(aodfilter,0,cinput1);\n mgr->ConnectOutput(aodfilter,0,coutput1);\n \n \/\/ Run the analysis \n printf(\"CHAIN HAS %d ENTRIES\\n\",(Int_t)chain->GetEntries());\n mgr->InitAnalysis();\n mgr->PrintStatus();\n mgr->StartAnalysis(\"local\",chain);\n}\n\n\nInt_t setupPar(const char* pararchivename) {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Setup PAR File\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (pararchivename) {\n char processline[1024];\n sprintf(processline,\".! tar xvzf %s.par\",pararchivename);\n gROOT->ProcessLine(processline);\n const char* ocwd = gSystem->WorkingDirectory();\n gSystem->ChangeDirectory(pararchivename);\n\n \/\/ check for BUILD.sh and execute\n if (!gSystem->AccessPathName(\"PROOF-INF\/BUILD.sh\")) {\n printf(\"*******************************\\n\");\n printf(\"*** Building PAR archive ***\\n\");\n printf(\"*******************************\\n\");\n\n if (gSystem->Exec(\"PROOF-INF\/BUILD.sh\")) {\n Error(\"runAnalysis\",\"Cannot Build the PAR Archive! - Abort!\");\n return -1;\n }\n }\n \/\/ check for SETUP.C and execute\n if (!gSystem->AccessPathName(\"PROOF-INF\/SETUP.C\")) {\n printf(\"*******************************\\n\");\n printf(\"*** Setup PAR archive ***\\n\");\n printf(\"*******************************\\n\");\n gROOT->Macro(\"PROOF-INF\/SETUP.C\");\n }\n\n gSystem->ChangeDirectory(\"..\/\");\n }\n\n return 1;\n}\n\n\/\/______________________________________________________________________________\nvoid SetupPar(char* pararchivename)\n{\n if (pararchivename) {\n\tchar processline[1024];\n\tsprintf(processline,\".! tar xvzf %s.par\",pararchivename);\n\tgROOT->ProcessLine(processline);\n\tTString ocwd = gSystem->WorkingDirectory();\n\tgSystem->ChangeDirectory(pararchivename);\n\t\n\t\/\/ check for BUILD.sh and execute\n\tif (!gSystem->AccessPathName(\"PROOF-INF\/BUILD.sh\")) {\n\t printf(\"*******************************\\n\");\n\t printf(\"*** Building PAR archive ***\\n\");\n\t printf(\"*******************************\\n\");\n\t \n\t if (gSystem->Exec(\"PROOF-INF\/BUILD.sh\")) {\n\t\tError(\"runProcess\",\"Cannot Build the PAR Archive! - Abort!\");\n\t\treturn -1;\n\t }\n\t}\n\t\/\/ check for SETUP.C and execute\n\tif (!gSystem->AccessPathName(\"PROOF-INF\/SETUP.C\")) {\n\t printf(\"*******************************\\n\");\n\t printf(\"*** Setup PAR archive ***\\n\");\n\t printf(\"*******************************\\n\");\n\t gROOT->Macro(\"PROOF-INF\/SETUP.C\");\n\t}\n\t\n\tgSystem->ChangeDirectory(ocwd.Data());\n printf(\"Current dir: %s\\n\", ocwd.Data());\n } \n}\n<commit_msg>Removing dependence on ESD files and new possibility for selecting muon multiplicity in the forward region (Enrico, Roberta)<commit_after>void AnalysisTrainFromStandardToMuonAODLocal(char* filein= \"AliAODs.root\", \n char* fileout= \"AliMuonAOD.root\", \n\t\t\t\t char* dirChain= \".\",\n\t\t\t\t char* dirData= \".\",\n\t\t\t\t\t Int_t nev=123456789){\n \n\/\/ Macro to produce a MUON-AOD, i.e. a replica of the standard AOD, containing only events\n\/\/ where at least one muon is present\n\/\/ \n\/\/ - The input files are the standard AOD and the AOD.tag.root files \n\/\/ - The AOD.tag file can be:\n\/\/ 1) the one previously created together with the AOD file (i.e. from\n\/\/ AnalysisTrainMuonLocal.C)\n\/\/ 2) created on the fly with this macro\n\/\/ - The selection of the muon events is based on the AOD tags\n\/\/ - The content of the MUON-AOD can be defined by the user with some settings as\n\/\/ SetNeedsTracksBranchReplication(), SetNeedsVerticesBranchReplication() \n\/\/ (defined in STEER\/AliAODHandler.h)...\n\n\n gSystem->Load(\"libTree.so\");\n gSystem->Load(\"libGeom.so\");\n gSystem->Load(\"libVMC.so\");\n gSystem->Load(\"libPhysics.so\");\n gSystem->Load(\"libSTEER.so\"); \/\/ for aliroot based analysis\n gSystem->Load(\"libPWG3muon.so\"); \/\/ for aliroot based analysis\n\n \/\/ Load par files, if the analysis is par based\n \/\/ SetupPar(\"STEERBase\");\n \/\/ SetupPar(\"ESD\");\n \/\/ SetupPar(\"AOD\");\n \/\/ SetupPar(\"ANALYSIS\");\n \/\/ SetupPar(\"ANALYSISalice\");\n \/\/ SetupPar(\"PWG3muon\"); \n \n \/\/ Uncomment the following lines if the AOD tag file has to be created on the fly\t \n \/\/ printf(\"Creating AOD Tags on the fly\\n\");\n \/\/ AliAODTagCreator *t = new AliAODTagCreator();\n \/\/ t->SetStorage(0);\n \/\/ t->ReadLocalCollection(dirData); \n \n AliTagAnalysis *TagAna = new AliTagAnalysis(\"AOD\"); \n \n \/\/ Define tag cuts to select events containing at least one muon in the dimuon spectrometer\n printf(\"Defining Tags cuts to select events containing at least one muon in the dimuon spectrometer\\n\");\n AliRunTagCuts *runCuts = new AliRunTagCuts();\n AliLHCTagCuts *lhcCuts = new AliLHCTagCuts();\n AliDetectorTagCuts *detCuts = new AliDetectorTagCuts();\n AliEventTagCuts *evCuts = new AliEventTagCuts();\n evCuts->SetNFWMuonRange(1,10);\n \n \/\/ Create the chain of interesting events\n TChain* chain = 0x0;\n TagAna->ChainLocalTags(dirChain);\n TagAna->SetType(\"AOD\");\n chain = TagAna->QueryTags(runCuts,lhcCuts,detCuts,evCuts);\n Info(\"AnalysisTrainFromStandardToMuonAOD\",Form(\"CHAIN HAS %d ENTRIES\",(Int_t)chain->GetEntries()));\n\n \/\/ Define aod input handler\n AliAODInputHandler* aodInputHandler = new AliAODInputHandler();\n \n \/\/ Define aod output handler\n AliAODHandler* aodOutputHandler = new AliAODHandler();\n\n \/\/ Create non standard AOD\n aodOutputHandler->SetCreateNonStandardAOD(); \n \n \/\/ Select the branches to be replicated in the MUON-AOD\n aodOutputHandler->SetNeedsHeaderReplication();\n aodOutputHandler->SetNeedsTracksBranchReplication();\n aodOutputHandler->SetNeedsVerticesBranchReplication();\n aodOutputHandler->SetNeedsV0sBranchReplication();\n aodOutputHandler->SetNeedsTrackletsBranchReplication(); \n aodOutputHandler->SetNeedsPMDClustersBranchReplication();\n aodOutputHandler->SetNeedsJetsBranchReplication();\n aodOutputHandler->SetNeedsFMDClustersBranchReplication();\n aodOutputHandler->SetNeedsCaloClustersBranchReplication();\n \n aodOutputHandler->SetOutputFileName(fileout);\n\n \/\/ Define the analysis manager\n AliAnalysisManager *mgr = new AliAnalysisManager(\"AOD Manager\", \"AOD Manager\");\n mgr->SetInputEventHandler(aodInputHandler);\n mgr->SetOutputEventHandler(aodOutputHandler);\n \/\/mgr->SetDebugLevel(10);\n \n AliAnalysisTaskFromStandardToMuonAOD *aodfilter = new AliAnalysisTaskFromStandardToMuonAOD(\"AOD Filter\");\n mgr->AddTask(aodfilter);\n \n \/\/ Create containers for input\/output\n AliAnalysisDataContainer *cinput1 = mgr->CreateContainer(\"cchain\",TChain::Class(), \n\t\t\t\t\t\t\t AliAnalysisManager::kInputContainer);\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"tree\", TTree::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer, \"default\");\n\t\t\t\t\t\t\t \n mgr->ConnectInput(aodfilter,0,cinput1);\n mgr->ConnectOutput(aodfilter,0,coutput1);\n \n \/\/ Run the analysis \n printf(\"CHAIN HAS %d ENTRIES\\n\",(Int_t)chain->GetEntries());\n mgr->InitAnalysis();\n mgr->PrintStatus();\n mgr->StartAnalysis(\"local\",chain,nev);\n}\n\n\nInt_t setupPar(const char* pararchivename) {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Setup PAR File\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (pararchivename) {\n char processline[1024];\n sprintf(processline,\".! tar xvzf %s.par\",pararchivename);\n gROOT->ProcessLine(processline);\n const char* ocwd = gSystem->WorkingDirectory();\n gSystem->ChangeDirectory(pararchivename);\n\n \/\/ check for BUILD.sh and execute\n if (!gSystem->AccessPathName(\"PROOF-INF\/BUILD.sh\")) {\n printf(\"*******************************\\n\");\n printf(\"*** Building PAR archive ***\\n\");\n printf(\"*******************************\\n\");\n\n if (gSystem->Exec(\"PROOF-INF\/BUILD.sh\")) {\n Error(\"runAnalysis\",\"Cannot Build the PAR Archive! - Abort!\");\n return -1;\n }\n }\n \/\/ check for SETUP.C and execute\n if (!gSystem->AccessPathName(\"PROOF-INF\/SETUP.C\")) {\n printf(\"*******************************\\n\");\n printf(\"*** Setup PAR archive ***\\n\");\n printf(\"*******************************\\n\");\n gROOT->Macro(\"PROOF-INF\/SETUP.C\");\n }\n\n gSystem->ChangeDirectory(\"..\/\");\n }\n\n return 1;\n}\n\n\/\/______________________________________________________________________________\nvoid SetupPar(char* pararchivename)\n{\n if (pararchivename) {\n\tchar processline[1024];\n\tsprintf(processline,\".! tar xvzf %s.par\",pararchivename);\n\tgROOT->ProcessLine(processline);\n\tTString ocwd = gSystem->WorkingDirectory();\n\tgSystem->ChangeDirectory(pararchivename);\n\t\n\t\/\/ check for BUILD.sh and execute\n\tif (!gSystem->AccessPathName(\"PROOF-INF\/BUILD.sh\")) {\n\t printf(\"*******************************\\n\");\n\t printf(\"*** Building PAR archive ***\\n\");\n\t printf(\"*******************************\\n\");\n\t \n\t if (gSystem->Exec(\"PROOF-INF\/BUILD.sh\")) {\n\t\tError(\"runProcess\",\"Cannot Build the PAR Archive! - Abort!\");\n\t\treturn -1;\n\t }\n\t}\n\t\/\/ check for SETUP.C and execute\n\tif (!gSystem->AccessPathName(\"PROOF-INF\/SETUP.C\")) {\n\t printf(\"*******************************\\n\");\n\t printf(\"*** Setup PAR archive ***\\n\");\n\t printf(\"*******************************\\n\");\n\t gROOT->Macro(\"PROOF-INF\/SETUP.C\");\n\t}\n\t\n\tgSystem->ChangeDirectory(ocwd.Data());\n printf(\"Current dir: %s\\n\", ocwd.Data());\n } \n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--------------------------------------------------------------------------------*- C++ -*-===\/\/\n\/\/ _\n\/\/ | |\n\/\/ __| | __ ___ ___ ___\n\/\/ \/ _` |\/ _` \\ \\ \/\\ \/ \/ '_ |\n\/\/ | (_| | (_| |\\ V V \/| | | |\n\/\/ \\__,_|\\__,_| \\_\/\\_\/ |_| |_| - Compiler Toolchain\n\/\/\n\/\/\n\/\/ This file is distributed under the MIT License (MIT).\n\/\/ See LICENSE.txt for details.\n\/\/\n\/\/===------------------------------------------------------------------------------------------===\/\/\n\n#include \"IcoChainSizes.h\"\n\n#include \"dawn\/AST\/LocationType.h\"\n#include \"dawn\/Support\/HashCombine.h\"\n\n#include <assert.h>\n#include <unordered_set>\n\nnamespace dawn {\n\nusing connection_t = std::tuple<ast::LocationType, ast::LocationType>;\n\nusing grid_location_t = std::tuple<int, int, int>;\n\n\/******************************************************************************\n * We encode the grid as follows:\n *\n * \\|{-1, 1} \\|{0, 1} \\|\n * -*-------------------------*-------------------------*-\n * |\\ {-1, 1, 0} |\\ {0, 1, 0} |\\\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ {-1, 0, 1} | \\ {0, 0, 1} |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\{-1, 0, 1} | \\{0, 0, 1} |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * |{-1, 0, 2} \\ |{0, 0, 2} \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | {-1, 0, 0} \\ | {0, 0, 0} \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * \\|{-1, 0} \\|{0, 0} \\|\n * -*-------------------------*-------------------------*-\n * |\\ {-1, 0, 0} |\\ {0, 0, 0} |\\\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ {-1, -1, 1} | \\ {0, -1, 1} |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\{-1, -1, 1} | \\{0, -1, 1} |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * |{-1, -1, 2} \\ |{0, -1, 2} \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | {-1, -1, 0} \\ | {0, -1, 0} \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * \\|{-1, -1} \\|{0, -1} \\|\n * -*-------------------------*-------------------------*-\n * |\\ {-1, -1, 0} |\\ {0, -1, 0} |\\\n *\n *\n * Which is described by this general pattern:\n *\n * |\\\n * | \\\n * | \\\n * | \\ {x, y, 1}\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\{x, y, 1}\n * | \\\n * | \\\n * | \\\n * |{x, y, 2} \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | {x, y, 0} \\\n * | \\\n * | \\\n * |{x, y} \\\n * *-------------------------\n * {x, y, 0}\n *\n * Note: Each location type uses a separate _id-space_.\n * {x, y, 0} can both mean an edge or cell. It's up to the user to ensure\n * they know what location type is meant.\n * To make the implementation easier, vertices are encoded also\n * as `std::tuple<int, int, int>` ({x, y, 0}).\n *\/\n\nstatic std::array<grid_location_t, 6> get_vertex_to_edge(const grid_location_t& vertex) {\n const auto [x, y, _] = vertex;\n return {{\n {x, y, 0},\n {x, y, 2},\n {x - 1, y, 0},\n {x - 1, y, 1},\n {x, y - 1, 1},\n {x, y - 1, 2},\n }};\n}\n\nstatic std::array<grid_location_t, 6> get_vertex_to_cell(const grid_location_t& vertex) {\n const auto [x, y, _] = vertex;\n return {{\n {x, y, 0},\n {x - 1, y, 0},\n {x - 1, y, 1},\n {x, y - 1, 0},\n {x, y - 1, 1},\n {x - 1, y - 1, 1},\n }};\n}\n\nstatic std::array<grid_location_t, 2> get_edge_to_vertex(const grid_location_t& edge) {\n const auto [x, y, e] = edge;\n if(e == 0) {\n return {{{x, y, 0}, {x + 1, y, 0}}};\n } else if(e == 1) {\n return {{{x + 1, y, 0}, {x, y + 1, 0}}};\n } else if(e == 2) {\n return {{{x, y, 0}, {x, y + 1, 0}}};\n } else {\n throw std::runtime_error(\"Invalid edge type\");\n }\n}\n\nstatic std::array<grid_location_t, 2> get_edge_to_cell(const grid_location_t& edge) {\n const auto [x, y, e] = edge;\n if(e == 0) {\n return {{{x, y, 0}, {x, y - 1, 1}}};\n } else if(e == 1) {\n return {{{x, y, 0}, {x, y, 1}}};\n } else if(e == 2) {\n return {{{x, y, 0}, {x - 1, y, 1}}};\n } else {\n throw std::runtime_error(\"Invalid edge type\");\n }\n}\n\nstatic std::array<grid_location_t, 3> get_cell_to_vertex(const grid_location_t& cell) {\n const auto [x, y, c] = cell;\n if(c == 0) {\n return {{{x, y, 0}, {x + 1, y, 0}, {x, y + 1, 0}}};\n } else if(c == 1) {\n return {{{x + 1, y + 1, 0}, {x + 1, y, 0}, {x, y + 1, 0}}};\n } else {\n throw std::runtime_error(\"Invalid cell type\");\n }\n}\n\nstatic std::array<grid_location_t, 3> get_cell_to_edge(const grid_location_t& cell) {\n const auto [x, y, c] = cell;\n if(c == 0) {\n return {{{x, y, 0}, {x, y, 1}, {x, y, 2}}};\n } else if(c == 1) {\n return {{{x, y, 1}, {x + 1, y, 2}, {x, y + 1, 0}}};\n } else {\n throw std::runtime_error(\"Invalid cell type\");\n }\n}\n\nint ICOChainSize(const ast::NeighborChain& chain) {\n\n assert(1 < chain.size());\n\n auto previous_location_type = chain[0];\n std::unordered_set<grid_location_t> previous_locations{{0, 0, 0}};\n\n for(ast::NeighborChain::size_type i = 1; i < chain.size(); ++i) {\n\n const auto current_location_type = chain[i];\n std::unordered_set<grid_location_t> current_locations;\n\n assert(previous_location_type != current_location_type);\n const connection_t connection{previous_location_type, current_location_type};\n\n \/\/ Vertices -> Edges\n if(connection == connection_t{ast::LocationType::Vertices, ast::LocationType::Edges}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_vertex_to_edge(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Vertices -> Cells\n } else if(connection == connection_t{ast::LocationType::Vertices, ast::LocationType::Cells}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_vertex_to_cell(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Edges -> Vertices\n } else if(connection == connection_t{ast::LocationType::Edges, ast::LocationType::Vertices}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_edge_to_vertex(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Edges -> Cells\n } else if(connection == connection_t{ast::LocationType::Edges, ast::LocationType::Cells}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_edge_to_cell(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Cells -> Vertices\n } else if(connection == connection_t{ast::LocationType::Cells, ast::LocationType::Vertices}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_cell_to_vertex(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Cells -> Edges\n } else if(connection == connection_t{ast::LocationType::Cells, ast::LocationType::Edges}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_cell_to_edge(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n } else {\n assert(false);\n }\n\n previous_locations = std::move(current_locations);\n previous_location_type = current_location_type;\n }\n\n if(chain.front() == chain.back()) {\n \/\/ we don't include the starting location\n return previous_locations.size() - 1;\n } else {\n return previous_locations.size();\n }\n}\n} \/\/ namespace dawn<commit_msg>Fix include in IcoChainSizes.cpp (#1060)<commit_after>\/\/===--------------------------------------------------------------------------------*- C++ -*-===\/\/\n\/\/ _\n\/\/ | |\n\/\/ __| | __ ___ ___ ___\n\/\/ \/ _` |\/ _` \\ \\ \/\\ \/ \/ '_ |\n\/\/ | (_| | (_| |\\ V V \/| | | |\n\/\/ \\__,_|\\__,_| \\_\/\\_\/ |_| |_| - Compiler Toolchain\n\/\/\n\/\/\n\/\/ This file is distributed under the MIT License (MIT).\n\/\/ See LICENSE.txt for details.\n\/\/\n\/\/===------------------------------------------------------------------------------------------===\/\/\n\n#include \"IcoChainSizes.h\"\n\n#include \"dawn\/AST\/LocationType.h\"\n#include \"dawn\/Support\/HashCombine.h\"\n\n#include <stdexcept>\n#include <assert.h>\n#include <unordered_set>\n\nnamespace dawn {\n\nusing connection_t = std::tuple<ast::LocationType, ast::LocationType>;\n\nusing grid_location_t = std::tuple<int, int, int>;\n\n\/******************************************************************************\n * We encode the grid as follows:\n *\n * \\|{-1, 1} \\|{0, 1} \\|\n * -*-------------------------*-------------------------*-\n * |\\ {-1, 1, 0} |\\ {0, 1, 0} |\\\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ {-1, 0, 1} | \\ {0, 0, 1} |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\{-1, 0, 1} | \\{0, 0, 1} |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * |{-1, 0, 2} \\ |{0, 0, 2} \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | {-1, 0, 0} \\ | {0, 0, 0} \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * \\|{-1, 0} \\|{0, 0} \\|\n * -*-------------------------*-------------------------*-\n * |\\ {-1, 0, 0} |\\ {0, 0, 0} |\\\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ {-1, -1, 1} | \\ {0, -1, 1} |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\{-1, -1, 1} | \\{0, -1, 1} |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * |{-1, -1, 2} \\ |{0, -1, 2} \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * | {-1, -1, 0} \\ | {0, -1, 0} \\ |\n * | \\ | \\ |\n * | \\ | \\ |\n * \\|{-1, -1} \\|{0, -1} \\|\n * -*-------------------------*-------------------------*-\n * |\\ {-1, -1, 0} |\\ {0, -1, 0} |\\\n *\n *\n * Which is described by this general pattern:\n *\n * |\\\n * | \\\n * | \\\n * | \\ {x, y, 1}\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\{x, y, 1}\n * | \\\n * | \\\n * | \\\n * |{x, y, 2} \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | \\\n * | {x, y, 0} \\\n * | \\\n * | \\\n * |{x, y} \\\n * *-------------------------\n * {x, y, 0}\n *\n * Note: Each location type uses a separate _id-space_.\n * {x, y, 0} can both mean an edge or cell. It's up to the user to ensure\n * they know what location type is meant.\n * To make the implementation easier, vertices are encoded also\n * as `std::tuple<int, int, int>` ({x, y, 0}).\n *\/\n\nstatic std::array<grid_location_t, 6> get_vertex_to_edge(const grid_location_t& vertex) {\n const auto [x, y, _] = vertex;\n return {{\n {x, y, 0},\n {x, y, 2},\n {x - 1, y, 0},\n {x - 1, y, 1},\n {x, y - 1, 1},\n {x, y - 1, 2},\n }};\n}\n\nstatic std::array<grid_location_t, 6> get_vertex_to_cell(const grid_location_t& vertex) {\n const auto [x, y, _] = vertex;\n return {{\n {x, y, 0},\n {x - 1, y, 0},\n {x - 1, y, 1},\n {x, y - 1, 0},\n {x, y - 1, 1},\n {x - 1, y - 1, 1},\n }};\n}\n\nstatic std::array<grid_location_t, 2> get_edge_to_vertex(const grid_location_t& edge) {\n const auto [x, y, e] = edge;\n if(e == 0) {\n return {{{x, y, 0}, {x + 1, y, 0}}};\n } else if(e == 1) {\n return {{{x + 1, y, 0}, {x, y + 1, 0}}};\n } else if(e == 2) {\n return {{{x, y, 0}, {x, y + 1, 0}}};\n } else {\n throw std::runtime_error(\"Invalid edge type\");\n }\n}\n\nstatic std::array<grid_location_t, 2> get_edge_to_cell(const grid_location_t& edge) {\n const auto [x, y, e] = edge;\n if(e == 0) {\n return {{{x, y, 0}, {x, y - 1, 1}}};\n } else if(e == 1) {\n return {{{x, y, 0}, {x, y, 1}}};\n } else if(e == 2) {\n return {{{x, y, 0}, {x - 1, y, 1}}};\n } else {\n throw std::runtime_error(\"Invalid edge type\");\n }\n}\n\nstatic std::array<grid_location_t, 3> get_cell_to_vertex(const grid_location_t& cell) {\n const auto [x, y, c] = cell;\n if(c == 0) {\n return {{{x, y, 0}, {x + 1, y, 0}, {x, y + 1, 0}}};\n } else if(c == 1) {\n return {{{x + 1, y + 1, 0}, {x + 1, y, 0}, {x, y + 1, 0}}};\n } else {\n throw std::runtime_error(\"Invalid cell type\");\n }\n}\n\nstatic std::array<grid_location_t, 3> get_cell_to_edge(const grid_location_t& cell) {\n const auto [x, y, c] = cell;\n if(c == 0) {\n return {{{x, y, 0}, {x, y, 1}, {x, y, 2}}};\n } else if(c == 1) {\n return {{{x, y, 1}, {x + 1, y, 2}, {x, y + 1, 0}}};\n } else {\n throw std::runtime_error(\"Invalid cell type\");\n }\n}\n\nint ICOChainSize(const ast::NeighborChain& chain) {\n\n assert(1 < chain.size());\n\n auto previous_location_type = chain[0];\n std::unordered_set<grid_location_t> previous_locations{{0, 0, 0}};\n\n for(ast::NeighborChain::size_type i = 1; i < chain.size(); ++i) {\n\n const auto current_location_type = chain[i];\n std::unordered_set<grid_location_t> current_locations;\n\n assert(previous_location_type != current_location_type);\n const connection_t connection{previous_location_type, current_location_type};\n\n \/\/ Vertices -> Edges\n if(connection == connection_t{ast::LocationType::Vertices, ast::LocationType::Edges}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_vertex_to_edge(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Vertices -> Cells\n } else if(connection == connection_t{ast::LocationType::Vertices, ast::LocationType::Cells}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_vertex_to_cell(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Edges -> Vertices\n } else if(connection == connection_t{ast::LocationType::Edges, ast::LocationType::Vertices}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_edge_to_vertex(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Edges -> Cells\n } else if(connection == connection_t{ast::LocationType::Edges, ast::LocationType::Cells}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_edge_to_cell(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Cells -> Vertices\n } else if(connection == connection_t{ast::LocationType::Cells, ast::LocationType::Vertices}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_cell_to_vertex(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n \/\/ Cells -> Edges\n } else if(connection == connection_t{ast::LocationType::Cells, ast::LocationType::Edges}) {\n for(const auto& previous_location : previous_locations) {\n const auto neighbors = get_cell_to_edge(previous_location);\n current_locations.insert(neighbors.cbegin(), neighbors.cend());\n }\n } else {\n assert(false);\n }\n\n previous_locations = std::move(current_locations);\n previous_location_type = current_location_type;\n }\n\n if(chain.front() == chain.back()) {\n \/\/ we don't include the starting location\n return previous_locations.size() - 1;\n } else {\n return previous_locations.size();\n }\n}\n} \/\/ namespace dawn\n<|endoftext|>"} {"text":"<commit_before>#include \"ui_root.h\"\n#include \"ui_widget.h\"\n#include \"halley\/core\/api\/audio_api.h\"\n#include \"ui_painter.h\"\n#include \"halley\/audio\/audio_position.h\"\n#include \"halley\/audio\/audio_clip.h\"\n#include \"halley\/maths\/random.h\"\n\nusing namespace Halley;\n\nUIRoot* UIRoot::getRoot()\n{\n\treturn this;\n}\n\nconst UIRoot* UIRoot::getRoot() const\n{\n\treturn this;\n}\n\nconst String& UIRoot::getId() const\n{\n\treturn id;\n}\n\nUIRoot::UIRoot(AudioAPI* audio, Rect4f rect)\n\t: id(\"root\")\n\t, dummyInput(std::make_shared<InputButtonBase>(4))\n\t, uiRect(rect)\n\t, audio(audio)\n\t, mouseRemap([](Vector2f p) { return p; })\n{\n\n}\n\nvoid UIRoot::setRect(Rect4f rect, Vector2f overscan)\n{\n\tuiRect = Rect4f(rect.getTopLeft() + overscan, rect.getBottomRight() - overscan);\n\tthis->overscan = overscan;\n}\n\nRect4f UIRoot::getRect() const\n{\n\treturn uiRect;\n}\n\nvoid UIRoot::update(Time t, UIInputType activeInputType, spInputDevice mouse, spInputDevice manual)\n{\n\tauto joystickType = manual->getJoystickType();\n\tbool first = true;\n\n\tdo {\n\t\t\/\/ Spawn & Update input\n\t\taddNewChildren(activeInputType);\n\t\tif (activeInputType == UIInputType::Mouse) {\n\t\t\tupdateMouse(mouse);\n\t\t}\n\t\tupdateInput(manual);\n\n\t\t\/\/ Update children\n\t\tfor (auto& c: getChildren()) {\n\t\t\tc->doUpdate(first ? UIWidgetUpdateType::First : UIWidgetUpdateType::Full, t, activeInputType, joystickType);\n\t\t}\n\t\tfirst = false;\n\t\tremoveDeadChildren();\n\n\t\t\/\/ Layout all widgets\n\t\trunLayout();\n\n\t\t\/\/ Update again, to reflect what happened >_>\n\t\tfor (auto& c: getChildren()) {\n\t\t\tc->doUpdate(UIWidgetUpdateType::Partial, 0, activeInputType, joystickType);\n\t\t}\n\n\t\t\/\/ For subsequent iterations, make sure t = 0\n\t\tt = 0;\n\t} while (isWaitingToSpawnChildren());\n}\n\nvoid UIRoot::updateMouse(spInputDevice mouse)\n{\n\t\/\/ Check where we should be mouse overing.\n\t\/\/ If the mouse hasn't moved, keep the last one.\n\tstd::shared_ptr<UIWidget> underMouse;\n\tVector2f mousePos = mouseRemap(mouse->getPosition() + uiRect.getTopLeft() - overscan);\n\tif (true || (mousePos - lastMousePos).squaredLength() > 0.01f) {\n\t\t\/\/ Go through all root-level widgets and find the actual widget under the mouse\n\t\tunderMouse = getWidgetUnderMouse(mousePos);\n\t\tlastMousePos = mousePos;\n\t} else {\n\t\tunderMouse = currentMouseOver.lock();\n\t}\n\n\t\/\/ Click\n\tif (mouse->isButtonPressed(0)) {\n\t\tmouseHeld = true;\n\t\tsetFocus(underMouse);\n\t\tif (underMouse) {\n\t\t\tmouse->clearButtonPress(0);\n\t\t\tunderMouse->pressMouse(mousePos, 0);\n\t\t}\n\t}\n\n\t\/\/ Release click\n\tauto focus = currentFocus.lock();\n\tif (mouse->isButtonReleased(0)) {\n\t\tmouseHeld = false;\n\t\tif (focus) {\n\t\t\tfocus->releaseMouse(mousePos, 0);\n\t\t\tmouse->clearButtonRelease(0);\n\t\t}\n\t}\n\n\t\/\/ Mouse wheel\n\tint wheelDelta = mouse->getWheelMove();\n\tif (wheelDelta != 0 && underMouse) {\n\t\tunderMouse->sendEvent(UIEvent(UIEventType::MouseWheel, \"mouse\", wheelDelta));\n\t}\n\n\t\/\/ If the mouse is held, but it's over a different component from the focused one, don't mouse over anything\n\tauto activeMouseOver = underMouse;\n\tif (mouseHeld && focus) {\n\t\tif (focus != underMouse) {\n\t\t\tactiveMouseOver.reset();\n\t\t}\n\t\tfocus->onMouseOver(mousePos);\n\t} else if (activeMouseOver) {\n\t\tactiveMouseOver->onMouseOver(mousePos);\n\t}\n\tupdateMouseOver(activeMouseOver);\n}\n\nvoid UIRoot::updateInputTree(const spInputDevice& input, UIWidget& widget, std::vector<UIWidget*>& inputTargets, UIInput::Priority& bestPriority, bool accepting)\n{\n\tif (!widget.isActive()) {\n\t\treturn;\n\t}\n\n\tif (!widget.isEnabled()) {\n\t\taccepting = false;\n\t}\n\n\tfor (auto& c: widget.getChildren()) {\n\t\t\/\/ Depth-first\n\t\tupdateInputTree(input, *c, inputTargets, bestPriority, accepting);\n\t}\n\n\tif (widget.inputButtons) {\n\t\twidget.inputResults.reset();\n\t\tif (accepting) {\n\t\t\tauto priority = widget.getInputPriority();\n\n\t\t\tif (int(priority) > int(bestPriority)) {\n\t\t\t\tbestPriority = priority;\n\t\t\t\tinputTargets.clear();\n\t\t\t}\n\t\t\tif (priority == bestPriority) {\n\t\t\t\tinputTargets.push_back(&widget);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid UIRoot::updateInput(spInputDevice input)\n{\n\tauto& cs = getChildren();\n\tstd::vector<UIWidget*> inputTargets;\n\tUIInput::Priority bestPriority = UIInput::Priority::Lowest;\n\n\tbool accepting = true;\n\tfor (int i = int(cs.size()); --i >= 0; ) {\n\t\tauto& c = *cs[i];\n\t\tupdateInputTree(input, c, inputTargets, bestPriority, accepting);\n\t\t\t\t\n\t\tif (c.isMouseBlocker()) {\n\t\t\taccepting = false;\n\t\t}\n\t}\n\n\tfor (auto& target: inputTargets) {\n\t\tauto& b = *target->inputButtons;\n\t\tauto& results = target->inputResults;\n\t\tresults.reset();\n\t\tif (b.accept != -1) {\n\t\t\tresults.setButton(UIInput::Button::Accept, input->isButtonPressed(b.accept), input->isButtonReleased(b.accept), input->isButtonDown(b.accept));\n\t\t}\n\t\tif (b.cancel != -1) {\n\t\t\tresults.setButton(UIInput::Button::Cancel, input->isButtonPressed(b.cancel), input->isButtonReleased(b.cancel), input->isButtonDown(b.cancel));\n\t\t}\n\t\tif (b.prev != -1) {\n\t\t\tresults.setButton(UIInput::Button::Prev, input->isButtonPressed(b.prev), input->isButtonReleased(b.prev), input->isButtonDown(b.prev));\n\t\t}\n\t\tif (b.next != -1) {\n\t\t\tresults.setButton(UIInput::Button::Next, input->isButtonPressed(b.next), input->isButtonReleased(b.next), input->isButtonDown(b.next));\n\t\t}\n\t\tif (b.hold != -1) {\n\t\t\tresults.setButton(UIInput::Button::Hold, input->isButtonPressed(b.hold), input->isButtonReleased(b.hold), input->isButtonDown(b.hold));\n\t\t}\n\t\tresults.setAxis(UIInput::Axis::X, (b.xAxis != -1 ? input->getAxis(b.xAxis) : 0) + (b.xAxisAlt != -1 ? input->getAxis(b.xAxisAlt) : 0));\n\t\tresults.setAxis(UIInput::Axis::Y, (b.yAxis != -1 ? input->getAxis(b.yAxis) : 0) + (b.yAxisAlt != -1 ? input->getAxis(b.yAxisAlt) : 0));\n\t\tresults.setAxisRepeat(UIInput::Axis::X, (b.xAxis != -1 ? input->getAxisRepeat(b.xAxis) : 0) + (b.xAxisAlt != -1 ? input->getAxisRepeat(b.xAxisAlt) : 0));\n\t\tresults.setAxisRepeat(UIInput::Axis::Y, (b.yAxis != -1 ? input->getAxisRepeat(b.yAxis) : 0) + (b.yAxisAlt != -1 ? input->getAxisRepeat(b.yAxisAlt) : 0));\n\t}\n}\n\nvoid UIRoot::mouseOverNext(bool forward)\n{\n\tauto widgets = collectWidgets();\n\n\tif (widgets.empty()) {\n\t\treturn;\n\t}\n\n\tsize_t nextIdx = 0;\n\tauto current = currentMouseOver.lock();\n\tif (current) {\n\t\tauto i = std::find(widgets.begin(), widgets.end(), current);\n\t\tif (i != widgets.end()) {\n\t\t\tnextIdx = ((i - widgets.begin()) + widgets.size() + (forward ? 1 : -1)) % widgets.size();\n\t\t}\n\t}\n\n\tupdateMouseOver(widgets[nextIdx]);\n}\n\nvoid UIRoot::runLayout()\n{\n\tfor (auto& c: getChildren()) {\n\t\tc->layout();\n\t}\n}\n\nvoid UIRoot::setFocus(std::shared_ptr<UIWidget> focus)\n{\n\tauto curFocus = currentFocus.lock();\n\tif (curFocus != focus) {\n\t\tif (curFocus) {\n\t\t\tcurFocus->setFocused(false);\n\t\t}\n\n\t\tcurrentFocus = focus;\n\t\tif (focus) {\n\t\t\tfocus->setFocused(true);\n\t\t}\n\t}\n}\n\nvoid UIRoot::updateMouseOver(const std::shared_ptr<UIWidget>& underMouse)\n{\n\tauto curMouseOver = currentMouseOver.lock();\n\tif (curMouseOver != underMouse) {\n\t\tif (curMouseOver) {\n\t\t\tcurMouseOver->setMouseOver(false);\n\t\t}\n\t\tif (underMouse) {\n\t\t\tunderMouse->setMouseOver(true);\n\t\t}\n\t\tcurrentMouseOver = underMouse;\n\t}\n}\n\n\nstd::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse(Vector2f mousePos, bool includeDisabled) const\n{\n\tauto& cs = getChildren();\n\tfor (int i = int(cs.size()); --i >= 0; ) {\n\t\tauto& curRootWidget = cs[i];\n\t\tauto widget = getWidgetUnderMouse(curRootWidget, mousePos, includeDisabled);\n\t\tif (widget) {\n\t\t\treturn widget;\n\t\t} else {\n\t\t\tif (curRootWidget->isMouseBlocker()) {\n\t\t\t\treturn {};\n\t\t\t}\n\t\t}\n\t}\n\treturn {};\n}\n\nstd::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse(const std::shared_ptr<UIWidget>& start, Vector2f mousePos, bool includeDisabled) const\n{\n\tif (!start->isActive() || (!includeDisabled && !start->isEnabled())) {\n\t\treturn {};\n\t}\n\n\t\/\/ Depth first\n\tfor (auto& c: start->getChildren()) {\n\t\tauto result = getWidgetUnderMouse(c, mousePos, includeDisabled);\n\t\tif (result) {\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tauto rect = start->getMouseRect();\n\tif (start->canInteractWithMouse() && rect.contains(mousePos)) {\n\t\treturn start;\n\t} else {\n\t\treturn {};\n\t}\n}\n\nvoid UIRoot::setUIMouseRemapping(std::function<Vector2f(Vector2f)> remapFunction) {\n\tExpects(remapFunction);\n\tmouseRemap = remapFunction;\n}\n\nvoid UIRoot::unsetUIMouseRemapping() {\n\tmouseRemap = [](Vector2f p) { return p; };\n}\n\nstd::vector<std::shared_ptr<UIWidget>> UIRoot::collectWidgets()\n{\n\tstd::vector<std::shared_ptr<UIWidget>> output;\n\tif (getChildren().empty()) {\n\t\treturn {};\n\t}\n\tcollectWidgets(getChildren().back(), output);\n\treturn output;\n}\n\nvoid UIRoot::collectWidgets(const std::shared_ptr<UIWidget>& start, std::vector<std::shared_ptr<UIWidget>>& output)\n{\n\tfor (auto& c: start->getChildren()) {\n\t\tcollectWidgets(c, output);\n\t}\n\n\tif (start->canInteractWithMouse()) {\n\t\toutput.push_back(start);\n\t}\n}\n\nvoid UIRoot::draw(SpritePainter& painter, int mask, int layer)\n{\n\tUIPainter p(painter, mask, layer);\n\n\tfor (auto& c: getChildren()) {\n\t\tc->doDraw(p);\n\t}\n}\n\nMaybe<AudioHandle> UIRoot::playSound(const String& eventName)\n{\n\tif (audio && !eventName.isEmpty()) {\n\t\treturn audio->postEvent(eventName, AudioPosition::makeUI(0.0f));\n\t}\n\n\treturn {};\n}\n\nvoid UIRoot::sendEvent(UIEvent&&) const\n{\n\t\/\/ Unhandled event\n}\n\nbool UIRoot::hasModalUI() const\n{\n\tfor (auto& c: getChildren()) {\n\t\tif (c->isModal()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool UIRoot::isMouseOverUI() const\n{\n\treturn static_cast<bool>(currentMouseOver.lock());\n}\n\nstd::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse() const\n{\n\treturn currentMouseOver.lock();\n}\n\nstd::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouseIncludingDisabled() const\n{\n\treturn getWidgetUnderMouse(lastMousePos, true);\n}\n\nUIWidget* UIRoot::getCurrentFocus() const\n{\n\treturn currentFocus.lock().get();\n}\n<commit_msg>UI doesn't count as modal if it's inactive.<commit_after>#include \"ui_root.h\"\n#include \"ui_widget.h\"\n#include \"halley\/core\/api\/audio_api.h\"\n#include \"ui_painter.h\"\n#include \"halley\/audio\/audio_position.h\"\n#include \"halley\/audio\/audio_clip.h\"\n#include \"halley\/maths\/random.h\"\n\nusing namespace Halley;\n\nUIRoot* UIRoot::getRoot()\n{\n\treturn this;\n}\n\nconst UIRoot* UIRoot::getRoot() const\n{\n\treturn this;\n}\n\nconst String& UIRoot::getId() const\n{\n\treturn id;\n}\n\nUIRoot::UIRoot(AudioAPI* audio, Rect4f rect)\n\t: id(\"root\")\n\t, dummyInput(std::make_shared<InputButtonBase>(4))\n\t, uiRect(rect)\n\t, audio(audio)\n\t, mouseRemap([](Vector2f p) { return p; })\n{\n\n}\n\nvoid UIRoot::setRect(Rect4f rect, Vector2f overscan)\n{\n\tuiRect = Rect4f(rect.getTopLeft() + overscan, rect.getBottomRight() - overscan);\n\tthis->overscan = overscan;\n}\n\nRect4f UIRoot::getRect() const\n{\n\treturn uiRect;\n}\n\nvoid UIRoot::update(Time t, UIInputType activeInputType, spInputDevice mouse, spInputDevice manual)\n{\n\tauto joystickType = manual->getJoystickType();\n\tbool first = true;\n\n\tdo {\n\t\t\/\/ Spawn & Update input\n\t\taddNewChildren(activeInputType);\n\t\tif (activeInputType == UIInputType::Mouse) {\n\t\t\tupdateMouse(mouse);\n\t\t}\n\t\tupdateInput(manual);\n\n\t\t\/\/ Update children\n\t\tfor (auto& c: getChildren()) {\n\t\t\tc->doUpdate(first ? UIWidgetUpdateType::First : UIWidgetUpdateType::Full, t, activeInputType, joystickType);\n\t\t}\n\t\tfirst = false;\n\t\tremoveDeadChildren();\n\n\t\t\/\/ Layout all widgets\n\t\trunLayout();\n\n\t\t\/\/ Update again, to reflect what happened >_>\n\t\tfor (auto& c: getChildren()) {\n\t\t\tc->doUpdate(UIWidgetUpdateType::Partial, 0, activeInputType, joystickType);\n\t\t}\n\n\t\t\/\/ For subsequent iterations, make sure t = 0\n\t\tt = 0;\n\t} while (isWaitingToSpawnChildren());\n}\n\nvoid UIRoot::updateMouse(spInputDevice mouse)\n{\n\t\/\/ Check where we should be mouse overing.\n\t\/\/ If the mouse hasn't moved, keep the last one.\n\tstd::shared_ptr<UIWidget> underMouse;\n\tVector2f mousePos = mouseRemap(mouse->getPosition() + uiRect.getTopLeft() - overscan);\n\tif (true || (mousePos - lastMousePos).squaredLength() > 0.01f) {\n\t\t\/\/ Go through all root-level widgets and find the actual widget under the mouse\n\t\tunderMouse = getWidgetUnderMouse(mousePos);\n\t\tlastMousePos = mousePos;\n\t} else {\n\t\tunderMouse = currentMouseOver.lock();\n\t}\n\n\t\/\/ Click\n\tif (mouse->isButtonPressed(0)) {\n\t\tmouseHeld = true;\n\t\tsetFocus(underMouse);\n\t\tif (underMouse) {\n\t\t\tmouse->clearButtonPress(0);\n\t\t\tunderMouse->pressMouse(mousePos, 0);\n\t\t}\n\t}\n\n\t\/\/ Release click\n\tauto focus = currentFocus.lock();\n\tif (mouse->isButtonReleased(0)) {\n\t\tmouseHeld = false;\n\t\tif (focus) {\n\t\t\tfocus->releaseMouse(mousePos, 0);\n\t\t\tmouse->clearButtonRelease(0);\n\t\t}\n\t}\n\n\t\/\/ Mouse wheel\n\tint wheelDelta = mouse->getWheelMove();\n\tif (wheelDelta != 0 && underMouse) {\n\t\tunderMouse->sendEvent(UIEvent(UIEventType::MouseWheel, \"mouse\", wheelDelta));\n\t}\n\n\t\/\/ If the mouse is held, but it's over a different component from the focused one, don't mouse over anything\n\tauto activeMouseOver = underMouse;\n\tif (mouseHeld && focus) {\n\t\tif (focus != underMouse) {\n\t\t\tactiveMouseOver.reset();\n\t\t}\n\t\tfocus->onMouseOver(mousePos);\n\t} else if (activeMouseOver) {\n\t\tactiveMouseOver->onMouseOver(mousePos);\n\t}\n\tupdateMouseOver(activeMouseOver);\n}\n\nvoid UIRoot::updateInputTree(const spInputDevice& input, UIWidget& widget, std::vector<UIWidget*>& inputTargets, UIInput::Priority& bestPriority, bool accepting)\n{\n\tif (!widget.isActive()) {\n\t\treturn;\n\t}\n\n\tif (!widget.isEnabled()) {\n\t\taccepting = false;\n\t}\n\n\tfor (auto& c: widget.getChildren()) {\n\t\t\/\/ Depth-first\n\t\tupdateInputTree(input, *c, inputTargets, bestPriority, accepting);\n\t}\n\n\tif (widget.inputButtons) {\n\t\twidget.inputResults.reset();\n\t\tif (accepting) {\n\t\t\tauto priority = widget.getInputPriority();\n\n\t\t\tif (int(priority) > int(bestPriority)) {\n\t\t\t\tbestPriority = priority;\n\t\t\t\tinputTargets.clear();\n\t\t\t}\n\t\t\tif (priority == bestPriority) {\n\t\t\t\tinputTargets.push_back(&widget);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid UIRoot::updateInput(spInputDevice input)\n{\n\tauto& cs = getChildren();\n\tstd::vector<UIWidget*> inputTargets;\n\tUIInput::Priority bestPriority = UIInput::Priority::Lowest;\n\n\tbool accepting = true;\n\tfor (int i = int(cs.size()); --i >= 0; ) {\n\t\tauto& c = *cs[i];\n\t\tupdateInputTree(input, c, inputTargets, bestPriority, accepting);\n\t\t\t\t\n\t\tif (c.isMouseBlocker()) {\n\t\t\taccepting = false;\n\t\t}\n\t}\n\n\tfor (auto& target: inputTargets) {\n\t\tauto& b = *target->inputButtons;\n\t\tauto& results = target->inputResults;\n\t\tresults.reset();\n\t\tif (b.accept != -1) {\n\t\t\tresults.setButton(UIInput::Button::Accept, input->isButtonPressed(b.accept), input->isButtonReleased(b.accept), input->isButtonDown(b.accept));\n\t\t}\n\t\tif (b.cancel != -1) {\n\t\t\tresults.setButton(UIInput::Button::Cancel, input->isButtonPressed(b.cancel), input->isButtonReleased(b.cancel), input->isButtonDown(b.cancel));\n\t\t}\n\t\tif (b.prev != -1) {\n\t\t\tresults.setButton(UIInput::Button::Prev, input->isButtonPressed(b.prev), input->isButtonReleased(b.prev), input->isButtonDown(b.prev));\n\t\t}\n\t\tif (b.next != -1) {\n\t\t\tresults.setButton(UIInput::Button::Next, input->isButtonPressed(b.next), input->isButtonReleased(b.next), input->isButtonDown(b.next));\n\t\t}\n\t\tif (b.hold != -1) {\n\t\t\tresults.setButton(UIInput::Button::Hold, input->isButtonPressed(b.hold), input->isButtonReleased(b.hold), input->isButtonDown(b.hold));\n\t\t}\n\t\tresults.setAxis(UIInput::Axis::X, (b.xAxis != -1 ? input->getAxis(b.xAxis) : 0) + (b.xAxisAlt != -1 ? input->getAxis(b.xAxisAlt) : 0));\n\t\tresults.setAxis(UIInput::Axis::Y, (b.yAxis != -1 ? input->getAxis(b.yAxis) : 0) + (b.yAxisAlt != -1 ? input->getAxis(b.yAxisAlt) : 0));\n\t\tresults.setAxisRepeat(UIInput::Axis::X, (b.xAxis != -1 ? input->getAxisRepeat(b.xAxis) : 0) + (b.xAxisAlt != -1 ? input->getAxisRepeat(b.xAxisAlt) : 0));\n\t\tresults.setAxisRepeat(UIInput::Axis::Y, (b.yAxis != -1 ? input->getAxisRepeat(b.yAxis) : 0) + (b.yAxisAlt != -1 ? input->getAxisRepeat(b.yAxisAlt) : 0));\n\t}\n}\n\nvoid UIRoot::mouseOverNext(bool forward)\n{\n\tauto widgets = collectWidgets();\n\n\tif (widgets.empty()) {\n\t\treturn;\n\t}\n\n\tsize_t nextIdx = 0;\n\tauto current = currentMouseOver.lock();\n\tif (current) {\n\t\tauto i = std::find(widgets.begin(), widgets.end(), current);\n\t\tif (i != widgets.end()) {\n\t\t\tnextIdx = ((i - widgets.begin()) + widgets.size() + (forward ? 1 : -1)) % widgets.size();\n\t\t}\n\t}\n\n\tupdateMouseOver(widgets[nextIdx]);\n}\n\nvoid UIRoot::runLayout()\n{\n\tfor (auto& c: getChildren()) {\n\t\tc->layout();\n\t}\n}\n\nvoid UIRoot::setFocus(std::shared_ptr<UIWidget> focus)\n{\n\tauto curFocus = currentFocus.lock();\n\tif (curFocus != focus) {\n\t\tif (curFocus) {\n\t\t\tcurFocus->setFocused(false);\n\t\t}\n\n\t\tcurrentFocus = focus;\n\t\tif (focus) {\n\t\t\tfocus->setFocused(true);\n\t\t}\n\t}\n}\n\nvoid UIRoot::updateMouseOver(const std::shared_ptr<UIWidget>& underMouse)\n{\n\tauto curMouseOver = currentMouseOver.lock();\n\tif (curMouseOver != underMouse) {\n\t\tif (curMouseOver) {\n\t\t\tcurMouseOver->setMouseOver(false);\n\t\t}\n\t\tif (underMouse) {\n\t\t\tunderMouse->setMouseOver(true);\n\t\t}\n\t\tcurrentMouseOver = underMouse;\n\t}\n}\n\n\nstd::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse(Vector2f mousePos, bool includeDisabled) const\n{\n\tauto& cs = getChildren();\n\tfor (int i = int(cs.size()); --i >= 0; ) {\n\t\tauto& curRootWidget = cs[i];\n\t\tauto widget = getWidgetUnderMouse(curRootWidget, mousePos, includeDisabled);\n\t\tif (widget) {\n\t\t\treturn widget;\n\t\t} else {\n\t\t\tif (curRootWidget->isMouseBlocker()) {\n\t\t\t\treturn {};\n\t\t\t}\n\t\t}\n\t}\n\treturn {};\n}\n\nstd::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse(const std::shared_ptr<UIWidget>& start, Vector2f mousePos, bool includeDisabled) const\n{\n\tif (!start->isActive() || (!includeDisabled && !start->isEnabled())) {\n\t\treturn {};\n\t}\n\n\t\/\/ Depth first\n\tfor (auto& c: start->getChildren()) {\n\t\tauto result = getWidgetUnderMouse(c, mousePos, includeDisabled);\n\t\tif (result) {\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tauto rect = start->getMouseRect();\n\tif (start->canInteractWithMouse() && rect.contains(mousePos)) {\n\t\treturn start;\n\t} else {\n\t\treturn {};\n\t}\n}\n\nvoid UIRoot::setUIMouseRemapping(std::function<Vector2f(Vector2f)> remapFunction) {\n\tExpects(remapFunction);\n\tmouseRemap = remapFunction;\n}\n\nvoid UIRoot::unsetUIMouseRemapping() {\n\tmouseRemap = [](Vector2f p) { return p; };\n}\n\nstd::vector<std::shared_ptr<UIWidget>> UIRoot::collectWidgets()\n{\n\tstd::vector<std::shared_ptr<UIWidget>> output;\n\tif (getChildren().empty()) {\n\t\treturn {};\n\t}\n\tcollectWidgets(getChildren().back(), output);\n\treturn output;\n}\n\nvoid UIRoot::collectWidgets(const std::shared_ptr<UIWidget>& start, std::vector<std::shared_ptr<UIWidget>>& output)\n{\n\tfor (auto& c: start->getChildren()) {\n\t\tcollectWidgets(c, output);\n\t}\n\n\tif (start->canInteractWithMouse()) {\n\t\toutput.push_back(start);\n\t}\n}\n\nvoid UIRoot::draw(SpritePainter& painter, int mask, int layer)\n{\n\tUIPainter p(painter, mask, layer);\n\n\tfor (auto& c: getChildren()) {\n\t\tc->doDraw(p);\n\t}\n}\n\nMaybe<AudioHandle> UIRoot::playSound(const String& eventName)\n{\n\tif (audio && !eventName.isEmpty()) {\n\t\treturn audio->postEvent(eventName, AudioPosition::makeUI(0.0f));\n\t}\n\n\treturn {};\n}\n\nvoid UIRoot::sendEvent(UIEvent&&) const\n{\n\t\/\/ Unhandled event\n}\n\nbool UIRoot::hasModalUI() const\n{\n\tfor (auto& c: getChildren()) {\n\t\tif (c->isActive() && c->isModal()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool UIRoot::isMouseOverUI() const\n{\n\treturn static_cast<bool>(currentMouseOver.lock());\n}\n\nstd::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse() const\n{\n\treturn currentMouseOver.lock();\n}\n\nstd::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouseIncludingDisabled() const\n{\n\treturn getWidgetUnderMouse(lastMousePos, true);\n}\n\nUIWidget* UIRoot::getCurrentFocus() const\n{\n\treturn currentFocus.lock().get();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tdate: 20 05 2015\n*\/\n\n\/\/4 x 4 matrix exp \n\n#include <bits\/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst ll mod = 1e9 + 7;\n\nll start[4][4] = {{1, 1, 1, 1}, {1, 0, 0, 0},\n\t\t\t\t\t{0, 1, 0, 0}, {0, 0, 1, 0}};\n\nll tmp[4][4];\n\nvoid mul(ll A[4][4], ll B[4][4]) {\n\tll cell;\n\tfor (ll i = 0; i < 4; ++i) {\n\t\tfor (ll j = 0; j < 4; ++j) {\n\t\t\tcell = 0;\n\t\t\tfor (ll a = 0; a < 4; ++a) {\n\t\t\t\tcell += (A[i][a]*B[a][j])%mod;\n\t\t\t\tcell %= mod;\n\t\t\t}\n\t\t\ttmp[i][j] = cell;\n\t\t}\n\t}\n\tmemcpy(A, tmp, 16*sizeof(ll));\n}\n\nvoid power(ll T[4][4], ll n) {\n\tif (n == 0 || n == 1) return;\n\tpower(T, n\/2);\n\tmul(T, T);\n\tif (n%2) mul(T, start);\n}\n\nll tetra(ll n) {\n\tif (n <= 2) return 0;\n\tif (n == 3) return 1;\n\t\n\tll T[4][4];\n\tmemcpy(T, start, 16*sizeof(ll));\n\tpower(T, n - 3);\n\n\treturn T[0][0];\n}\n\nll sum(ll m) {\n\treturn (3*tetra(0) + 2*tetra(1) + tetra(2) - tetra(4) +\n\t\t\t\ttetra(m + 4) - 2*tetra(m + 1) - tetra(m + 2) + mod)%mod; \n}\n\nint main() {\n\tios::sync_with_stdio(0);\n\t\n\tll t; cin >> t;\n\twhile (t--) {\n\t\tll n, m; cin >> n >> m;\n\t\tcout << ((((sum(m) - sum(n - 1) + mod) % mod) * 333333336) % mod) << \"\\n\";\n\t}\n\n\treturn 0;\n}\n<commit_msg>Update TETRAHRD.cxx<commit_after>\/*\n\tdate: 20 05 2015\n*\/\n\n\/\/4 x 4 matrix exponentitation \n\n#include <bits\/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst ll mod = 1e9 + 7;\n\nll start[4][4] = {{1, 1, 1, 1}, {1, 0, 0, 0},\n\t\t\t\t\t{0, 1, 0, 0}, {0, 0, 1, 0}};\n\nll tmp[4][4];\n\nvoid mul(ll A[4][4], ll B[4][4]) {\n\tll cell;\n\tfor (ll i = 0; i < 4; ++i) {\n\t\tfor (ll j = 0; j < 4; ++j) {\n\t\t\tcell = 0;\n\t\t\tfor (ll a = 0; a < 4; ++a) {\n\t\t\t\tcell += (A[i][a]*B[a][j])%mod;\n\t\t\t\tcell %= mod;\n\t\t\t}\n\t\t\ttmp[i][j] = cell;\n\t\t}\n\t}\n\tmemcpy(A, tmp, 16*sizeof(ll));\n}\n\nvoid power(ll T[4][4], ll n) {\n\tif (n == 0 || n == 1) return;\n\tpower(T, n\/2);\n\tmul(T, T);\n\tif (n%2) mul(T, start);\n}\n\nll tetra(ll n) {\n\tif (n <= 2) return 0;\n\tif (n == 3) return 1;\n\t\n\tll T[4][4];\n\tmemcpy(T, start, 16*sizeof(ll));\n\tpower(T, n - 3);\n\n\treturn T[0][0];\n}\n\nll sum(ll m) {\n\treturn (3*tetra(0) + 2*tetra(1) + tetra(2) - tetra(4) +\n\t\t\t\ttetra(m + 4) - 2*tetra(m + 1) - tetra(m + 2) + mod)%mod; \n}\n\nint main() {\n\tios::sync_with_stdio(0);\n\t\n\tll t; cin >> t;\n\twhile (t--) {\n\t\tll n, m; cin >> n >> m;\n\t\tcout << ((((sum(m) - sum(n - 1) + mod) % mod) * 333333336) % mod) << \"\\n\";\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstring>\n\n#include <sampgdk\/a_players.h>\n#include <sampgdk\/a_samp.h>\n#include <sampgdk\/core.h>\n#include <sampgdk\/plugin.h>\n\nstatic ThisPlugin helloworld;\n\nvoid SAMPGDK_CALL Timer(int \/*timerid*\/, void *\/*param*\/) {\n\tServerLog::Printf(\"timer!\");\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {\n\tSetGameModeText(\"Hello, World!\");\n\n\tAddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);\n\n\tServerLog::Printf(\"------------------------------------------\\n\");\n\tServerLog::Printf(\" HelloWorld gamemode got loaded. \\n\");\n\tServerLog::Printf(\"------------------------------------------\\n\");\n\n\tSetTimer(1000, true, Timer, 0);\n\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {\n\tSendClientMessage(playerid, 0xFFFFFFFF, \"Welcome to the HelloWorld server!\");\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {\n\tSetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\tSetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\tSetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f, CAMERA_CUT);\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {\n\tif (std::strcmp(cmdtext, \"\/hello\") == 0) {\n\t\tchar name[MAX_PLAYER_NAME];\n\t\tGetPlayerName(playerid, name, MAX_PLAYER_NAME);\n\t\tchar message[128];\n\t\tstd::sprintf(message, \"Hello, %s!\", name);\n\t\tSendClientMessage(playerid, 0x00FF00FF, message);\n\t\treturn true;\n\t}\n\tif (std::strcmp(cmdtext, \"\/pos\") == 0) {\n\t\tfloat x, y, z;\n\t\tGetPlayerPos(playerid, &x, &y, &z);\n\t\tchar message[128];\n\t\tstd::sprintf(message, \"You are at (%f, %f, %f)\", x, y, z);\n\t\tSendClientMessage(playerid, 0xFFFFFFFF, message);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n\treturn SUPPORTS_VERSION | SUPPORTS_PROCESS_TICK;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n\thelloworld.Load(ppData);\n\treturn true;\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload() {\n\thelloworld.Unload();\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {\n\thelloworld.ProcessTimers();\n}\n<commit_msg>Fix MSVC compile warning<commit_after>#include <cstdio>\n#include <cstring>\n\n#include <sampgdk\/a_players.h>\n#include <sampgdk\/a_samp.h>\n#include <sampgdk\/core.h>\n#include <sampgdk\/plugin.h>\n\nstatic ThisPlugin helloworld;\n\nvoid SAMPGDK_CALL Timer(int \/*timerid*\/, void* \/*param*\/) {\n\tServerLog::Printf(\"timer!\");\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {\n\tSetGameModeText(\"Hello, World!\");\n\n\tAddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);\n\n\tServerLog::Printf(\"------------------------------------------\\n\");\n\tServerLog::Printf(\" HelloWorld gamemode got loaded. \\n\");\n\tServerLog::Printf(\"------------------------------------------\\n\");\n\n\tSetTimer(1000, true, Timer, 0);\n\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {\n\tSendClientMessage(playerid, 0xFFFFFFFF, \"Welcome to the HelloWorld server!\");\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {\n\tSetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\tSetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\tSetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f, CAMERA_CUT);\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {\n\tif (std::strcmp(cmdtext, \"\/hello\") == 0) {\n\t\tchar name[MAX_PLAYER_NAME];\n\t\tGetPlayerName(playerid, name, MAX_PLAYER_NAME);\n\t\tchar message[128];\n\t\tstd::sprintf(message, \"Hello, %s!\", name);\n\t\tSendClientMessage(playerid, 0x00FF00FF, message);\n\t\treturn true;\n\t}\n\tif (std::strcmp(cmdtext, \"\/pos\") == 0) {\n\t\tfloat x, y, z;\n\t\tGetPlayerPos(playerid, &x, &y, &z);\n\t\tchar message[128];\n\t\tstd::sprintf(message, \"You are at (%f, %f, %f)\", x, y, z);\n\t\tSendClientMessage(playerid, 0xFFFFFFFF, message);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n\treturn SUPPORTS_VERSION | SUPPORTS_PROCESS_TICK;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n\thelloworld.Load(ppData);\n\treturn true;\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload() {\n\thelloworld.Unload();\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {\n\thelloworld.ProcessTimers();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Streams.cpp\n *****************************************************************************\n * Copyright (C) 2014 - VideoLAN and VLC authors\n *\n * This program 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 * 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 Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"Streams.hpp\"\n#include \"http\/HTTPConnection.hpp\"\n#include \"http\/HTTPConnectionManager.h\"\n#include \"playlist\/BaseRepresentation.h\"\n#include \"playlist\/SegmentChunk.hpp\"\n#include \"plumbing\/SourceStream.hpp\"\n#include \"plumbing\/CommandsQueue.hpp\"\n#include \"tools\/Debug.hpp\"\n#include <vlc_demux.h>\n\nusing namespace adaptive;\nusing namespace adaptive::http;\n\nAbstractStream::AbstractStream(demux_t * demux_)\n{\n p_realdemux = demux_;\n format = StreamFormat::UNSUPPORTED;\n currentChunk = NULL;\n eof = false;\n dead = false;\n disabled = false;\n discontinuity = false;\n segmentTracker = NULL;\n demuxersource = NULL;\n commandsqueue = NULL;\n demuxer = NULL;\n fakeesout = NULL;\n vlc_mutex_init(&lock);\n}\n\nbool AbstractStream::init(const StreamFormat &format_, SegmentTracker *tracker, HTTPConnectionManager *conn)\n{\n \/* Don't even try if not supported or already init *\/\n if((unsigned)format_ == StreamFormat::UNSUPPORTED || demuxersource)\n return false;\n\n demuxersource = new (std::nothrow) ChunksSourceStream( VLC_OBJECT(p_realdemux), this );\n if(demuxersource)\n {\n CommandsFactory *factory = new (std::nothrow) CommandsFactory();\n if(factory)\n {\n commandsqueue = new (std::nothrow) CommandsQueue(factory);\n if(commandsqueue)\n {\n fakeesout = new (std::nothrow) FakeESOut(p_realdemux->out, commandsqueue);\n if(fakeesout)\n {\n \/* All successfull *\/\n fakeesout->setExtraInfoProvider( this );\n format = format_;\n segmentTracker = tracker;\n segmentTracker->registerListener(this);\n connManager = conn;\n return true;\n }\n delete commandsqueue;\n commandsqueue = NULL;\n }\n else\n {\n delete factory;\n }\n }\n delete demuxersource;\n }\n\n return false;\n}\n\nAbstractStream::~AbstractStream()\n{\n delete currentChunk;\n delete segmentTracker;\n\n delete demuxer;\n delete demuxersource;\n delete fakeesout;\n delete commandsqueue;\n\n vlc_mutex_destroy(&lock);\n}\n\nvoid AbstractStream::prepareFormatChange()\n{\n if(demuxer)\n {\n \/* Enqueue Del Commands for all current ES *\/\n demuxer->drain();\n \/* Enqueue Del Commands for all current ES *\/\n fakeesout->scheduleAllForDeletion();\n fakeesout->schedulePCRReset();\n commandsqueue->Commit();\n \/* ignoring demuxer's own Del commands *\/\n commandsqueue->setDrop(true);\n delete demuxer;\n commandsqueue->setDrop(false);\n demuxer = NULL;\n }\n}\n\nvoid AbstractStream::setLanguage(const std::string &lang)\n{\n language = lang;\n}\n\nvoid AbstractStream::setDescription(const std::string &desc)\n{\n description = desc;\n}\n\nbool AbstractStream::isDead() const\n{\n return dead;\n}\n\nmtime_t AbstractStream::getPCR() const\n{\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n mtime_t pcr = (dead || disabled) ? VLC_TS_INVALID : commandsqueue->getPCR();\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return pcr;\n}\n\nmtime_t AbstractStream::getMinAheadTime() const\n{\n if(!segmentTracker)\n return 0;\n return segmentTracker->getMinAheadTime();\n}\n\nmtime_t AbstractStream::getFirstDTS() const\n{\n mtime_t dts;\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n if(dead || disabled)\n {\n dts = VLC_TS_INVALID;\n }\n else\n {\n dts = commandsqueue->getFirstDTS();\n if(dts == VLC_TS_INVALID)\n dts = commandsqueue->getPCR();\n }\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return dts;\n}\n\nint AbstractStream::esCount() const\n{\n return fakeesout->esCount();\n}\n\nbool AbstractStream::seekAble() const\n{\n return (demuxer &&\n !fakeesout->restarting() &&\n !discontinuity &&\n !commandsqueue->isFlushing() );\n}\n\nbool AbstractStream::isSelected() const\n{\n return fakeesout->hasSelectedEs();\n}\n\nbool AbstractStream::reactivate(mtime_t basetime)\n{\n if(setPosition(basetime, false))\n {\n disabled = false;\n return true;\n }\n else\n {\n eof = true; \/* can't reactivate *\/\n return false;\n }\n}\n\nbool AbstractStream::startDemux()\n{\n if(demuxer)\n return false;\n\n demuxersource->Reset();\n demuxer = createDemux(format);\n if(!demuxer)\n msg_Err(p_realdemux, \"Failed to create demuxer\");\n\n return !!demuxer;\n}\n\nbool AbstractStream::restartDemux()\n{\n if(!demuxer)\n {\n return startDemux();\n }\n else if(demuxer->reinitsOnSeek())\n {\n \/* Push all ES as recycling candidates *\/\n fakeesout->recycleAll();\n \/* Restart with ignoring pushes to queue *\/\n return demuxer->restart(commandsqueue);\n }\n commandsqueue->Commit();\n return true;\n}\n\nbool AbstractStream::isDisabled() const\n{\n return disabled;\n}\n\nbool AbstractStream::drain()\n{\n return fakeesout->drain();\n}\n\nAbstractStream::buffering_status AbstractStream::bufferize(mtime_t nz_deadline,\n unsigned i_min_buffering, unsigned i_extra_buffering)\n{\n vlc_mutex_lock(&lock);\n\n \/* Ensure it is configured *\/\n if(!segmentTracker || !connManager || dead)\n {\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_end;\n }\n\n \/* Disable streams that are not selected (alternate streams) *\/\n if(esCount() && !isSelected() && !fakeesout->restarting())\n {\n disabled = true;\n segmentTracker->reset();\n commandsqueue->Abort(false);\n msg_Dbg(p_realdemux, \"deactivating stream %s\", format.str().c_str());\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_end;\n }\n\n if(commandsqueue->isFlushing())\n {\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_suspended;\n }\n\n if(!demuxer)\n {\n format = segmentTracker->getCurrentFormat();\n if(!startDemux())\n {\n \/* If demux fails because of probing failure \/ wrong format*\/\n if(discontinuity)\n {\n msg_Dbg( p_realdemux, \"Flushing on format change\" );\n prepareFormatChange();\n discontinuity = false;\n commandsqueue->setFlush();\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_ongoing;\n }\n dead = true; \/* Prevent further retries *\/\n commandsqueue->setEOF();\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_end;\n }\n setTimeOffset();\n }\n\n const int64_t i_total_buffering = i_min_buffering + i_extra_buffering;\n\n mtime_t i_demuxed = commandsqueue->getDemuxedAmount();\n if(i_demuxed < i_total_buffering) \/* not already demuxed *\/\n {\n if(!segmentTracker->segmentsListReady()) \/* Live Streams *\/\n {\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_suspended;\n }\n\n nz_deadline = commandsqueue->getBufferingLevel() +\n (i_total_buffering - commandsqueue->getDemuxedAmount()) \/ (CLOCK_FREQ\/4);\n\n \/* need to read, demuxer still buffering, ... *\/\n vlc_mutex_unlock(&lock);\n int i_ret = demuxer->demux(nz_deadline);\n vlc_mutex_lock(&lock);\n if(i_ret != VLC_DEMUXER_SUCCESS)\n {\n if(discontinuity)\n {\n msg_Dbg( p_realdemux, \"Flushing on discontinuity\" );\n prepareFormatChange();\n discontinuity = false;\n commandsqueue->setFlush();\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_ongoing;\n }\n commandsqueue->setEOF();\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_end;\n }\n i_demuxed = commandsqueue->getDemuxedAmount();\n }\n vlc_mutex_unlock(&lock);\n\n if(i_demuxed < i_total_buffering) \/* need to read more *\/\n {\n if(i_demuxed < i_min_buffering)\n return AbstractStream::buffering_lessthanmin; \/* high prio *\/\n return AbstractStream::buffering_ongoing;\n }\n return AbstractStream::buffering_full;\n}\n\nAbstractStream::status AbstractStream::dequeue(mtime_t nz_deadline, mtime_t *pi_pcr)\n{\n vlc_mutex_locker locker(&lock);\n\n *pi_pcr = nz_deadline;\n\n if (disabled || dead)\n return AbstractStream::status_eof;\n\n if(commandsqueue->isFlushing())\n {\n *pi_pcr = commandsqueue->Process(p_realdemux->out, VLC_TS_0 + nz_deadline);\n if(!commandsqueue->isEmpty())\n return AbstractStream::status_demuxed;\n\n if(!commandsqueue->isEOF())\n {\n commandsqueue->Abort(true); \/* reset buffering level and flags *\/\n return AbstractStream::status_discontinuity;\n }\n }\n\n if(commandsqueue->isEOF())\n {\n *pi_pcr = nz_deadline;\n return AbstractStream::status_eof;\n }\n\n AdvDebug(msg_Dbg(p_realdemux, \"Stream %s pcr %ld dts %ld deadline %ld buflevel %ld\",\n description.c_str(), commandsqueue->getPCR(), commandsqueue->getFirstDTS(),\n nz_deadline, commandsqueue->getBufferingLevel()));\n\n if(nz_deadline + VLC_TS_0 <= commandsqueue->getBufferingLevel()) \/* demuxed *\/\n {\n *pi_pcr = commandsqueue->Process( p_realdemux->out, VLC_TS_0 + nz_deadline );\n return AbstractStream::status_demuxed;\n }\n\n return AbstractStream::status_buffering;\n}\n\nblock_t * AbstractStream::readNextBlock()\n{\n if (currentChunk == NULL && !eof)\n currentChunk = segmentTracker->getNextChunk(!fakeesout->restarting(), connManager);\n\n if(discontinuity)\n {\n msg_Info(p_realdemux, \"Encountered discontinuity\");\n \/* Force stream\/demuxer to end for this call *\/\n return NULL;\n }\n\n if(currentChunk == NULL)\n {\n eof = true;\n return NULL;\n }\n\n const bool b_segment_head_chunk = (currentChunk->getBytesRead() == 0);\n\n block_t *block = currentChunk->readBlock();\n if(block == NULL)\n {\n delete currentChunk;\n currentChunk = NULL;\n return NULL;\n }\n\n if (currentChunk->isEmpty())\n {\n delete currentChunk;\n currentChunk = NULL;\n }\n\n block = checkBlock(block, b_segment_head_chunk);\n\n return block;\n}\n\nbool AbstractStream::setPosition(mtime_t time, bool tryonly)\n{\n if(!seekAble())\n return false;\n\n bool ret = segmentTracker->setPositionByTime(time, demuxer->reinitsOnSeek(), tryonly);\n if(!tryonly && ret)\n {\n if(demuxer->reinitsOnSeek())\n {\n if(currentChunk)\n delete currentChunk;\n currentChunk = NULL;\n\n if( !restartDemux() )\n dead = true;\n\n setTimeOffset();\n }\n else commandsqueue->Abort( true );\n\n es_out_Control(p_realdemux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,\n VLC_TS_0 + time);\n }\n return ret;\n}\n\nmtime_t AbstractStream::getPlaybackTime() const\n{\n return segmentTracker->getPlaybackTime();\n}\n\nvoid AbstractStream::runUpdates()\n{\n if(!isDisabled())\n segmentTracker->updateSelected();\n}\n\nvoid AbstractStream::fillExtraFMTInfo( es_format_t *p_fmt ) const\n{\n if(!p_fmt->psz_language && !language.empty())\n p_fmt->psz_language = strdup(language.c_str());\n if(!p_fmt->psz_description && !description.empty())\n p_fmt->psz_description = strdup(description.c_str());\n}\n\nvoid AbstractStream::setTimeOffset()\n{\n \/* Check if we need to set an offset as the demuxer\n * will start from zero from seek point *\/\n if(demuxer && demuxer->alwaysStartsFromZero())\n fakeesout->setTimestampOffset(segmentTracker->getPlaybackTime());\n else\n fakeesout->setTimestampOffset(0);\n}\n\nvoid AbstractStream::trackerEvent(const SegmentTrackerEvent &event)\n{\n switch(event.type)\n {\n case SegmentTrackerEvent::DISCONTINUITY:\n discontinuity = true;\n break;\n\n case SegmentTrackerEvent::FORMATCHANGE:\n \/* Check if our current demux is still valid *\/\n if(*event.u.format.f != format)\n {\n \/* Format has changed between segments, we need to drain and change demux *\/\n msg_Info(p_realdemux, \"Changing stream format %s -> %s\",\n format.str().c_str(), event.u.format.f->str().c_str());\n format = *event.u.format.f;\n\n \/* This is an implict discontinuity *\/\n discontinuity = true;\n }\n break;\n\n case SegmentTrackerEvent::SWITCHING:\n default:\n break;\n }\n}\n<commit_msg>demux: adaptive: don't show err for unsupported demuxers<commit_after>\/*\n * Streams.cpp\n *****************************************************************************\n * Copyright (C) 2014 - VideoLAN and VLC authors\n *\n * This program 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 * 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 Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"Streams.hpp\"\n#include \"http\/HTTPConnection.hpp\"\n#include \"http\/HTTPConnectionManager.h\"\n#include \"playlist\/BaseRepresentation.h\"\n#include \"playlist\/SegmentChunk.hpp\"\n#include \"plumbing\/SourceStream.hpp\"\n#include \"plumbing\/CommandsQueue.hpp\"\n#include \"tools\/Debug.hpp\"\n#include <vlc_demux.h>\n\nusing namespace adaptive;\nusing namespace adaptive::http;\n\nAbstractStream::AbstractStream(demux_t * demux_)\n{\n p_realdemux = demux_;\n format = StreamFormat::UNSUPPORTED;\n currentChunk = NULL;\n eof = false;\n dead = false;\n disabled = false;\n discontinuity = false;\n segmentTracker = NULL;\n demuxersource = NULL;\n commandsqueue = NULL;\n demuxer = NULL;\n fakeesout = NULL;\n vlc_mutex_init(&lock);\n}\n\nbool AbstractStream::init(const StreamFormat &format_, SegmentTracker *tracker, HTTPConnectionManager *conn)\n{\n \/* Don't even try if not supported or already init *\/\n if((unsigned)format_ == StreamFormat::UNSUPPORTED || demuxersource)\n return false;\n\n demuxersource = new (std::nothrow) ChunksSourceStream( VLC_OBJECT(p_realdemux), this );\n if(demuxersource)\n {\n CommandsFactory *factory = new (std::nothrow) CommandsFactory();\n if(factory)\n {\n commandsqueue = new (std::nothrow) CommandsQueue(factory);\n if(commandsqueue)\n {\n fakeesout = new (std::nothrow) FakeESOut(p_realdemux->out, commandsqueue);\n if(fakeesout)\n {\n \/* All successfull *\/\n fakeesout->setExtraInfoProvider( this );\n format = format_;\n segmentTracker = tracker;\n segmentTracker->registerListener(this);\n connManager = conn;\n return true;\n }\n delete commandsqueue;\n commandsqueue = NULL;\n }\n else\n {\n delete factory;\n }\n }\n delete demuxersource;\n }\n\n return false;\n}\n\nAbstractStream::~AbstractStream()\n{\n delete currentChunk;\n delete segmentTracker;\n\n delete demuxer;\n delete demuxersource;\n delete fakeesout;\n delete commandsqueue;\n\n vlc_mutex_destroy(&lock);\n}\n\nvoid AbstractStream::prepareFormatChange()\n{\n if(demuxer)\n {\n \/* Enqueue Del Commands for all current ES *\/\n demuxer->drain();\n \/* Enqueue Del Commands for all current ES *\/\n fakeesout->scheduleAllForDeletion();\n fakeesout->schedulePCRReset();\n commandsqueue->Commit();\n \/* ignoring demuxer's own Del commands *\/\n commandsqueue->setDrop(true);\n delete demuxer;\n commandsqueue->setDrop(false);\n demuxer = NULL;\n }\n}\n\nvoid AbstractStream::setLanguage(const std::string &lang)\n{\n language = lang;\n}\n\nvoid AbstractStream::setDescription(const std::string &desc)\n{\n description = desc;\n}\n\nbool AbstractStream::isDead() const\n{\n return dead;\n}\n\nmtime_t AbstractStream::getPCR() const\n{\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n mtime_t pcr = (dead || disabled) ? VLC_TS_INVALID : commandsqueue->getPCR();\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return pcr;\n}\n\nmtime_t AbstractStream::getMinAheadTime() const\n{\n if(!segmentTracker)\n return 0;\n return segmentTracker->getMinAheadTime();\n}\n\nmtime_t AbstractStream::getFirstDTS() const\n{\n mtime_t dts;\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n if(dead || disabled)\n {\n dts = VLC_TS_INVALID;\n }\n else\n {\n dts = commandsqueue->getFirstDTS();\n if(dts == VLC_TS_INVALID)\n dts = commandsqueue->getPCR();\n }\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return dts;\n}\n\nint AbstractStream::esCount() const\n{\n return fakeesout->esCount();\n}\n\nbool AbstractStream::seekAble() const\n{\n return (demuxer &&\n !fakeesout->restarting() &&\n !discontinuity &&\n !commandsqueue->isFlushing() );\n}\n\nbool AbstractStream::isSelected() const\n{\n return fakeesout->hasSelectedEs();\n}\n\nbool AbstractStream::reactivate(mtime_t basetime)\n{\n if(setPosition(basetime, false))\n {\n disabled = false;\n return true;\n }\n else\n {\n eof = true; \/* can't reactivate *\/\n return false;\n }\n}\n\nbool AbstractStream::startDemux()\n{\n if(demuxer)\n return false;\n\n demuxersource->Reset();\n demuxer = createDemux(format);\n if(!demuxer && format != StreamFormat())\n msg_Err(p_realdemux, \"Failed to create demuxer\");\n\n return !!demuxer;\n}\n\nbool AbstractStream::restartDemux()\n{\n if(!demuxer)\n {\n return startDemux();\n }\n else if(demuxer->reinitsOnSeek())\n {\n \/* Push all ES as recycling candidates *\/\n fakeesout->recycleAll();\n \/* Restart with ignoring pushes to queue *\/\n return demuxer->restart(commandsqueue);\n }\n commandsqueue->Commit();\n return true;\n}\n\nbool AbstractStream::isDisabled() const\n{\n return disabled;\n}\n\nbool AbstractStream::drain()\n{\n return fakeesout->drain();\n}\n\nAbstractStream::buffering_status AbstractStream::bufferize(mtime_t nz_deadline,\n unsigned i_min_buffering, unsigned i_extra_buffering)\n{\n vlc_mutex_lock(&lock);\n\n \/* Ensure it is configured *\/\n if(!segmentTracker || !connManager || dead)\n {\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_end;\n }\n\n \/* Disable streams that are not selected (alternate streams) *\/\n if(esCount() && !isSelected() && !fakeesout->restarting())\n {\n disabled = true;\n segmentTracker->reset();\n commandsqueue->Abort(false);\n msg_Dbg(p_realdemux, \"deactivating stream %s\", format.str().c_str());\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_end;\n }\n\n if(commandsqueue->isFlushing())\n {\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_suspended;\n }\n\n if(!demuxer)\n {\n format = segmentTracker->getCurrentFormat();\n if(!startDemux())\n {\n \/* If demux fails because of probing failure \/ wrong format*\/\n if(discontinuity)\n {\n msg_Dbg( p_realdemux, \"Flushing on format change\" );\n prepareFormatChange();\n discontinuity = false;\n commandsqueue->setFlush();\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_ongoing;\n }\n dead = true; \/* Prevent further retries *\/\n commandsqueue->setEOF();\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_end;\n }\n setTimeOffset();\n }\n\n const int64_t i_total_buffering = i_min_buffering + i_extra_buffering;\n\n mtime_t i_demuxed = commandsqueue->getDemuxedAmount();\n if(i_demuxed < i_total_buffering) \/* not already demuxed *\/\n {\n if(!segmentTracker->segmentsListReady()) \/* Live Streams *\/\n {\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_suspended;\n }\n\n nz_deadline = commandsqueue->getBufferingLevel() +\n (i_total_buffering - commandsqueue->getDemuxedAmount()) \/ (CLOCK_FREQ\/4);\n\n \/* need to read, demuxer still buffering, ... *\/\n vlc_mutex_unlock(&lock);\n int i_ret = demuxer->demux(nz_deadline);\n vlc_mutex_lock(&lock);\n if(i_ret != VLC_DEMUXER_SUCCESS)\n {\n if(discontinuity)\n {\n msg_Dbg( p_realdemux, \"Flushing on discontinuity\" );\n prepareFormatChange();\n discontinuity = false;\n commandsqueue->setFlush();\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_ongoing;\n }\n commandsqueue->setEOF();\n vlc_mutex_unlock(&lock);\n return AbstractStream::buffering_end;\n }\n i_demuxed = commandsqueue->getDemuxedAmount();\n }\n vlc_mutex_unlock(&lock);\n\n if(i_demuxed < i_total_buffering) \/* need to read more *\/\n {\n if(i_demuxed < i_min_buffering)\n return AbstractStream::buffering_lessthanmin; \/* high prio *\/\n return AbstractStream::buffering_ongoing;\n }\n return AbstractStream::buffering_full;\n}\n\nAbstractStream::status AbstractStream::dequeue(mtime_t nz_deadline, mtime_t *pi_pcr)\n{\n vlc_mutex_locker locker(&lock);\n\n *pi_pcr = nz_deadline;\n\n if (disabled || dead)\n return AbstractStream::status_eof;\n\n if(commandsqueue->isFlushing())\n {\n *pi_pcr = commandsqueue->Process(p_realdemux->out, VLC_TS_0 + nz_deadline);\n if(!commandsqueue->isEmpty())\n return AbstractStream::status_demuxed;\n\n if(!commandsqueue->isEOF())\n {\n commandsqueue->Abort(true); \/* reset buffering level and flags *\/\n return AbstractStream::status_discontinuity;\n }\n }\n\n if(commandsqueue->isEOF())\n {\n *pi_pcr = nz_deadline;\n return AbstractStream::status_eof;\n }\n\n AdvDebug(msg_Dbg(p_realdemux, \"Stream %s pcr %ld dts %ld deadline %ld buflevel %ld\",\n description.c_str(), commandsqueue->getPCR(), commandsqueue->getFirstDTS(),\n nz_deadline, commandsqueue->getBufferingLevel()));\n\n if(nz_deadline + VLC_TS_0 <= commandsqueue->getBufferingLevel()) \/* demuxed *\/\n {\n *pi_pcr = commandsqueue->Process( p_realdemux->out, VLC_TS_0 + nz_deadline );\n return AbstractStream::status_demuxed;\n }\n\n return AbstractStream::status_buffering;\n}\n\nblock_t * AbstractStream::readNextBlock()\n{\n if (currentChunk == NULL && !eof)\n currentChunk = segmentTracker->getNextChunk(!fakeesout->restarting(), connManager);\n\n if(discontinuity)\n {\n msg_Info(p_realdemux, \"Encountered discontinuity\");\n \/* Force stream\/demuxer to end for this call *\/\n return NULL;\n }\n\n if(currentChunk == NULL)\n {\n eof = true;\n return NULL;\n }\n\n const bool b_segment_head_chunk = (currentChunk->getBytesRead() == 0);\n\n block_t *block = currentChunk->readBlock();\n if(block == NULL)\n {\n delete currentChunk;\n currentChunk = NULL;\n return NULL;\n }\n\n if (currentChunk->isEmpty())\n {\n delete currentChunk;\n currentChunk = NULL;\n }\n\n block = checkBlock(block, b_segment_head_chunk);\n\n return block;\n}\n\nbool AbstractStream::setPosition(mtime_t time, bool tryonly)\n{\n if(!seekAble())\n return false;\n\n bool ret = segmentTracker->setPositionByTime(time, demuxer->reinitsOnSeek(), tryonly);\n if(!tryonly && ret)\n {\n if(demuxer->reinitsOnSeek())\n {\n if(currentChunk)\n delete currentChunk;\n currentChunk = NULL;\n\n if( !restartDemux() )\n dead = true;\n\n setTimeOffset();\n }\n else commandsqueue->Abort( true );\n\n es_out_Control(p_realdemux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,\n VLC_TS_0 + time);\n }\n return ret;\n}\n\nmtime_t AbstractStream::getPlaybackTime() const\n{\n return segmentTracker->getPlaybackTime();\n}\n\nvoid AbstractStream::runUpdates()\n{\n if(!isDisabled())\n segmentTracker->updateSelected();\n}\n\nvoid AbstractStream::fillExtraFMTInfo( es_format_t *p_fmt ) const\n{\n if(!p_fmt->psz_language && !language.empty())\n p_fmt->psz_language = strdup(language.c_str());\n if(!p_fmt->psz_description && !description.empty())\n p_fmt->psz_description = strdup(description.c_str());\n}\n\nvoid AbstractStream::setTimeOffset()\n{\n \/* Check if we need to set an offset as the demuxer\n * will start from zero from seek point *\/\n if(demuxer && demuxer->alwaysStartsFromZero())\n fakeesout->setTimestampOffset(segmentTracker->getPlaybackTime());\n else\n fakeesout->setTimestampOffset(0);\n}\n\nvoid AbstractStream::trackerEvent(const SegmentTrackerEvent &event)\n{\n switch(event.type)\n {\n case SegmentTrackerEvent::DISCONTINUITY:\n discontinuity = true;\n break;\n\n case SegmentTrackerEvent::FORMATCHANGE:\n \/* Check if our current demux is still valid *\/\n if(*event.u.format.f != format)\n {\n \/* Format has changed between segments, we need to drain and change demux *\/\n msg_Info(p_realdemux, \"Changing stream format %s -> %s\",\n format.str().c_str(), event.u.format.f->str().c_str());\n format = *event.u.format.f;\n\n \/* This is an implict discontinuity *\/\n discontinuity = true;\n }\n break;\n\n case SegmentTrackerEvent::SWITCHING:\n default:\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/Mancala AI\n\/\/Copyright Matthew Chandler 2012\n\n#include <iostream>\n#include <vector>\n\n\/\/board:\n\/\/2 rows of 6 bowls\n\/\/2 larger bowls for scoring (stores)\n\/\/\n\/\/Rules\n\/\/play is CCW\n\/\/ending in player's own store yields extra turn\n\/\/ending in empty bowl earns that piece and all those in the bowl across from it\n\/\/game ends when a player has no legal moves left\n\/\/\n\/\/good heuristics:\n\/\/score - opponent's score\n\/\/possibly good:\n\/\/number of availible moves\n\/\/seeds in play\n\/\/seed distribution (large piles waiting to be collected? seed ratio between sides)\n\/\/possibilty of extra turns\n\/\/if we wanted to, we could use a genetic algorithm for determining the importance of each of these\n\/\/\n\/\/representation\n\/\/circular array?\n\/\/ 11 10 9 8 7 6\n\/\/ 0 1 2 3 4 5\n\/\/ p1 store, p2 store\n\/\/From there, we would need logic to add to player's own store and skip the opponents.\n\/\/if we abstract out the actual array indexes, we can use 2 starting pointers to easily flip the board\n\/\/With that in mind, it might be better to use a Digraph, so we can have a truly circular setup\n\/\/each node could have a next, prev, and across pointer, and one that points to the stores for the ends (NULL otherwise)\n\/\/\n\/\/\n\/\/\n\/\/If we wanted to get really fancy, we could do 3D graphics with particle physics for the seeds.\n\nstruct Bowl\n{\npublic:\n Bowl(const int Count = 0, const int Next = 0, const int Across = 0):\n count(Count), next(Next), across(Across)\n {}\n\n int count;\n int next, across;\n};\n\nclass Board\n{\npublic:\n Board(const int Num_bowls = 6, const int Num_seeds = 4):\n num_bowls(Num_bowls), num_seeds(Num_seeds)\n {\n bowls.resize(2 * num_bowls + 2);\n p1_start = 0;\n p1_store = num_bowls;\n p2_start = num_bowls + 1;\n p2_store = 2 * num_bowls + 1;\n\n for(size_t i = 0; i < bowls.size(); ++i)\n {\n if(i < bowls.size() - 1)\n bowls[i].next = i + 1;\n else\n bowls[i].next = 0;\n\n if(i != (size_t)num_bowls && i != 2 * (size_t)num_bowls + 1)\n {\n bowls[i].across = 2 * num_bowls - i;\n bowls[i].count = num_seeds;\n }\n }\n }\n \/\/perform a move\n \/\/returns true if the move earns an extra turn\n bool move(int bowl)\n {\n if(bowl < 0 || bowl >= num_bowls)\n return false;\n bowl += p1_start;\n int seeds = bowls[bowl].count;\n if(seeds == 0)\n return false;\n bowls[bowl].count = 0;\n \/\/make the move\n for(int i = 0; i < seeds; ++i)\n {\n bowl = bowls[bowl].next;\n if(bowl == p2_store)\n bowl = bowls[bowl].next;\n bowls[bowl].count += 1;\n }\n \/\/extra turn if we land in our own store\n if(bowl == p1_store)\n return true;\n\n \/\/if we land in an empty bowl, we get the last seed sown and all the seeds from the bowl across\n if(bowls[bowl].count == 1 && bowls[bowls[bowl].across].count > 0)\n {\n bowls[p1_store].count += 1 + bowls[bowls[bowl].across].count;\n bowls[bowls[bowl].across].count = 0;\n bowls[bowl].count = 0;\n }\n return false;\n }\n\n \/\/swap sides of the board\n void swapsides()\n {\n std::swap(p1_start, p2_start);\n std::swap(p1_store, p2_store);\n }\n\n \/\/heuristics to evaluate the board status\n int evaluate() const\n {\n \/\/simple\n return bowls[p1_store].count - bowls[p2_store].count;\n }\n\n void crapprint() const \/\/delete me!\n {\n std::cout<<bowls[p2_store].count<<std::endl;\n for(int i = p1_start; i < p1_start + 6; ++i)\n std::cout<<bowls[i].count<<\"\\t\"<<bowls[bowls[i].across].count<<std::endl;\n std::cout<<bowls[p1_store].count<<std::endl;\n }\n\n\n int num_bowls, num_seeds;\n std::vector<Bowl> bowls;\n int p1_start, p2_start;\n int p1_store, p2_store;\n};\n\nint choosemove(Board b) \/\/purposely doing pass by value here\n{\n int best = 0;\n int best_i = 0;\n \/\/loop over available moves\n for(int i =0; i < 6; ++i)\n {\n if(b.bowls[b.p1_start + 1].count <= 0)\n continue;\n Board sub_b = b;\n sub_b.move(i);\n if(sub_b.evaluate() > best)\n {\n best = sub_b.evaluate();\n best_i = i;\n }\n }\n return best_i;\n}\n\nint main()\n{\n return 0;\n}\n<commit_msg>improved crapprint<commit_after>\/\/Mancala AI\n\/\/Copyright Matthew Chandler 2012\n\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <limits>\n\n\/\/board:\n\/\/2 rows of 6 bowls\n\/\/2 larger bowls for scoring (stores)\n\/\/\n\/\/Rules\n\/\/play is CCW\n\/\/ending in player's own store yields extra turn\n\/\/ending in empty bowl earns that piece and all those in the bowl across from it\n\/\/game ends when a player has no legal moves left\n\/\/\n\/\/good heuristics:\n\/\/score - opponent's score\n\/\/possibly good:\n\/\/number of availible moves\n\/\/seeds in play\n\/\/seed distribution (large piles waiting to be collected? seed ratio between sides)\n\/\/possibilty of extra turns\n\/\/if we wanted to, we could use a genetic algorithm for determining the importance of each of these\n\/\/\n\/\/representation\n\/\/circular array?\n\/\/ 11 10 9 8 7 6\n\/\/ 0 1 2 3 4 5\n\/\/ p1 store, p2 store\n\/\/From there, we would need logic to add to player's own store and skip the opponents.\n\/\/if we abstract out the actual array indexes, we can use 2 starting pointers to easily flip the board\n\/\/With that in mind, it might be better to use a Digraph, so we can have a truly circular setup\n\/\/each node could have a next, prev, and across pointer, and one that points to the stores for the ends (NULL otherwise)\n\/\/\n\/\/\n\/\/\n\/\/If we wanted to get really fancy, we could do 3D graphics with particle physics for the seeds.\n\nstruct Bowl\n{\npublic:\n Bowl(const int Count = 0, const int Next = 0, const int Across = 0):\n count(Count), next(Next), across(Across)\n {}\n\n int count;\n int next, across;\n};\n\nclass Board\n{\npublic:\n Board(const int Num_bowls = 6, const int Num_seeds = 4):\n num_bowls(Num_bowls), num_seeds(Num_seeds)\n {\n bowls.resize(2 * num_bowls + 2);\n p1_start = 0;\n p1_store = num_bowls;\n p2_start = num_bowls + 1;\n p2_store = 2 * num_bowls + 1;\n\n for(size_t i = 0; i < bowls.size(); ++i)\n {\n if(i < bowls.size() - 1)\n bowls[i].next = i + 1;\n else\n bowls[i].next = 0;\n\n if(i != (size_t)num_bowls && i != 2 * (size_t)num_bowls + 1)\n {\n bowls[i].across = 2 * num_bowls - i;\n bowls[i].count = num_seeds;\n }\n }\n }\n \/\/perform a move\n \/\/returns true if the move earns an extra turn\n bool move(int bowl)\n {\n if(bowl < 0 || bowl >= num_bowls)\n return false;\n bowl += p1_start;\n int seeds = bowls[bowl].count;\n if(seeds == 0)\n return false;\n bowls[bowl].count = 0;\n \/\/make the move\n for(int i = 0; i < seeds; ++i)\n {\n bowl = bowls[bowl].next;\n if(bowl == p2_store)\n bowl = bowls[bowl].next;\n bowls[bowl].count += 1;\n }\n \/\/extra turn if we land in our own store\n if(bowl == p1_store)\n return true;\n\n \/\/if we land in an empty bowl, we get the last seed sown and all the seeds from the bowl across\n if(bowls[bowl].count == 1 && bowls[bowls[bowl].across].count > 0)\n {\n bowls[p1_store].count += 1 + bowls[bowls[bowl].across].count;\n bowls[bowls[bowl].across].count = 0;\n bowls[bowl].count = 0;\n }\n return false;\n }\n\n \/\/swap sides of the board\n void swapsides()\n {\n std::swap(p1_start, p2_start);\n std::swap(p1_store, p2_store);\n }\n\n \/\/heuristics to evaluate the board status\n int evaluate() const\n {\n \/\/simple\n return bowls[p1_store].count - bowls[p2_store].count;\n }\n\n void crapprint() const \/\/delete me!\n {\n std::cout<<\" \";\n for(int i = p1_start; i < p1_start + 6; ++i)\n std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[bowls[i].across].count<<\" \";\n std::cout<<std::endl;\n std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[p2_store].count<<std::setw(3*7)<<\" \"<<std::setw(2)<<bowls[p1_store].count<<std::endl;\n std::cout<<\" \";\n for(int i = p1_start; i < p1_start + 6; ++i)\n std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[i].count<<\" \";\n std::cout<<std::endl;\n std::cout<<\" \";\n for(int i = 0; i < 6 ; ++i)\n std::cout<<std::setw(2)<<std::setfill(' ')<<i<<\" \";\n std::cout<<std::endl;\n }\n\n int num_bowls, num_seeds;\n std::vector<Bowl> bowls;\n int p1_start, p2_start;\n int p1_store, p2_store;\n};\n\nint choosemove(Board b) \/\/purposely doing pass by value here\n{\n int best = 0;\n int best_i = 0;\n \/\/loop over available moves\n for(int i =0; i < 6; ++i)\n {\n if(b.bowls[b.p1_start + 1].count <= 0)\n continue;\n Board sub_b = b;\n sub_b.move(i);\n if(sub_b.evaluate() > best)\n {\n best = sub_b.evaluate();\n best_i = i;\n }\n }\n return best_i;\n}\n\nint main()\n{\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <plugin.hpp>\n#include <output.hpp>\n#include <core.hpp>\n#include <debug.hpp>\n#include <view.hpp>\n#include <view-transform.hpp>\n#include <render-manager.hpp>\n#include <workspace-stream.hpp>\n#include <workspace-manager.hpp>\n#include <signal-definitions.hpp>\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <animation.hpp>\n\n#include <cmath>\n#include <utility>\n#include <animation.hpp>\n\n#include \"vswipe-processing.hpp\"\n\nclass vswipe : public wf::plugin_interface_t\n{\n private:\n struct {\n \/* When the workspace is set to (-1, -1), means no such workspace *\/\n wf::workspace_stream_t prev, curr, next;\n } streams;\n\n enum swipe_direction_t\n {\n HORIZONTAL = 0,\n VERTICAL,\n UNKNOWN,\n };\n\n struct {\n bool swiping = false;\n swipe_direction_t direction;\n\n wf_pointf initial_deltas;\n\n double delta_sum = 0.0;\n double gap = 0.0;\n\n double delta_prev = 0.0;\n double delta_last = 0.0;\n\n int vx = 0;\n int vy = 0;\n int vw = 0;\n int vh = 0;\n } state;\n\n wf::render_hook_t renderer;\n\n wf_duration duration;\n wf_transition transition;\n\n wf_option animation_duration;\n wf_option background_color;\n wf_option enable_horizontal;\n wf_option enable_vertical;\n wf_option ignore_cancel;\n wf_option fingers;\n wf_option gap;\n wf_option threshold;\n wf_option delta_threshold;\n wf_option speed_factor;\n wf_option speed_cap;\n\n public:\n\n void init(wayfire_config *config)\n {\n grab_interface->name = \"vswipe\";\n grab_interface->capabilities = wf::CAPABILITY_MANAGE_COMPOSITOR;\n grab_interface->callbacks.cancel = [=] () { finalize_and_exit(); };\n\n auto section = config->get_section(\"vswipe\");\n\n animation_duration = section->get_option(\"duration\", \"180\");\n duration = wf_duration(animation_duration);\n\n enable_horizontal = section->get_option(\"enable_horizontal\", \"1\");\n enable_vertical = section->get_option(\"enable_vertical\", \"1\");\n ignore_cancel = section->get_option(\"ignore_cancel\", \"1\");\n fingers = section->get_option(\"fingers\", \"4\");\n gap = section->get_option(\"gap\", \"32\");\n threshold = section->get_option(\"threshold\", \"0.35\");\n delta_threshold = section->get_option(\"delta_threshold\", \"24\");\n speed_factor = section->get_option(\"speed_factor\", \"256\");\n speed_cap = section->get_option(\"speed_cap\", \"0.05\");\n wf::get_core().connect_signal(\"pointer-swipe-begin\", &on_swipe_begin);\n wf::get_core().connect_signal(\"pointer-swipe-update\", &on_swipe_update);\n wf::get_core().connect_signal(\"pointer-swipe-end\", &on_swipe_end);\n\n background_color = section->get_option(\"background\", \"0 0 0 1\");\n\n renderer = [=] (const wf_framebuffer& buffer) { render(buffer); };\n }\n\n \/**\n * Get the translation matrix for a workspace at the given offset.\n * Depends on the swipe direction\n *\/\n glm::mat4 get_translation(double offset)\n {\n switch (state.direction)\n {\n case UNKNOWN:\n return glm::mat4(1.0);\n case HORIZONTAL:\n return glm::translate(glm::mat4(1.0),\n glm::vec3(offset, 0.0, 0.0));\n case VERTICAL:\n return glm::translate(glm::mat4(1.0),\n glm::vec3(0.0, -offset, 0.0));\n }\n\n assert(false); \/\/ not reached\n }\n\n void render(const wf_framebuffer &fb)\n {\n if (!duration.running() && !state.swiping)\n finalize_and_exit();\n\n if (duration.running())\n state.delta_sum = duration.progress(transition);\n\n update_stream(streams.prev);\n update_stream(streams.curr);\n update_stream(streams.next);\n\n OpenGL::render_begin(fb);\n OpenGL::clear(background_color->as_cached_color());\n fb.scissor(fb.framebuffer_box_from_geometry_box(fb.geometry));\n\n gl_geometry out_geometry = {\n .x1 = -1,\n .y1 = 1,\n .x2 = 1,\n .y2 = -1,\n };\n\n auto swipe = get_translation(state.delta_sum * 2);\n if (streams.prev.ws.x >= 0)\n {\n auto prev = get_translation(-2.0 - state.gap * 2.0);\n OpenGL::render_transformed_texture(streams.prev.buffer.tex,\n out_geometry, {}, fb.transform * prev * swipe);\n }\n\n OpenGL::render_transformed_texture(streams.curr.buffer.tex,\n out_geometry, {}, fb.transform * swipe);\n\n if (streams.next.ws.x >= 0)\n {\n auto next = get_translation(2.0 + state.gap * 2.0);\n OpenGL::render_transformed_texture(streams.next.buffer.tex,\n out_geometry, {}, fb.transform * next * swipe);\n }\n\n GL_CALL(glUseProgram(0));\n OpenGL::render_end();\n }\n\n inline void update_stream(wf::workspace_stream_t& s)\n {\n if (s.ws.x < 0 || s.ws.y < 0)\n return;\n\n if (!s.running)\n output->render->workspace_stream_start(s);\n else\n output->render->workspace_stream_update(s);\n }\n\n wf::signal_callback_t on_swipe_begin = [=] (wf::signal_data_t *data)\n {\n if (!enable_horizontal->as_cached_int() && !enable_vertical->as_cached_int())\n return;\n\n if (output->is_plugin_active(grab_interface->name))\n return;\n\n auto ev = static_cast<wf::swipe_begin_signal*> (data)->ev;\n if (static_cast<int>(ev->fingers) != fingers->as_cached_int())\n return;\n\n \/\/ Plugins are per output, swipes are global, so we need to handle\n \/\/ the swipe only when the cursor is on *our* (plugin instance's) output\n if (!(output->get_relative_geometry() & output->get_cursor_position()))\n return;\n\n state.swiping = true;\n state.direction = UNKNOWN;\n state.initial_deltas = {0.0, 0.0};\n state.delta_sum = 0;\n state.delta_last = 0;\n state.delta_prev = 0;\n\n state.gap = gap->as_cached_double() \/ output->get_screen_size().width;\n\n \/\/ We switch the actual workspace before the finishing animation,\n \/\/ so the rendering of the animation cannot dynamically query current\n \/\/ workspace again, so it's stored here\n auto grid = output->workspace->get_workspace_grid_size();\n auto ws = output->workspace->get_current_workspace();\n state.vw = grid.width;\n state.vh = grid.height;\n state.vx = ws.x;\n state.vy = ws.y;\n\n \/* Invalid in the beginning, because we want a few swipe events to\n * determine whether swipe is horizontal or vertical *\/\n streams.prev.ws = {-1, -1};\n streams.next.ws = {-1, -1};\n streams.curr.ws = wf_point {ws.x, ws.y};\n };\n\n void start_swipe(swipe_direction_t direction)\n {\n assert(direction != UNKNOWN);\n state.direction = direction;\n\n wf::get_core().focus_output(output);\n\n if (!output->activate_plugin(grab_interface))\n return;\n\n grab_interface->grab();\n output->render->set_renderer(renderer);\n output->render->damage_whole();\n\n auto ws = output->workspace->get_current_workspace();\n auto grid = output->workspace->get_workspace_grid_size();\n\n if (direction == HORIZONTAL)\n {\n if (ws.x > 0)\n streams.prev.ws = wf_point{ws.x - 1, ws.y};\n if (ws.x < grid.width - 1)\n streams.next.ws = wf_point{ws.x + 1, ws.y};\n } else \/\/if (direction == VERTICAL)\n {\n if (ws.y > 0)\n streams.prev.ws = wf_point{ws.x, ws.y - 1};\n if (ws.y < grid.height - 1)\n streams.next.ws = wf_point{ws.x, ws.y + 1};\n }\n }\n\n wf::signal_callback_t on_swipe_update = [=] (wf::signal_data_t *data)\n {\n if (!state.swiping)\n return;\n\n auto ev = static_cast<wf::swipe_update_signal*> (data)->ev;\n\n if (state.direction == UNKNOWN)\n {\n auto grid = output->workspace->get_workspace_grid_size();\n\n \/\/ XXX: how to determine this??\n static constexpr double initial_direction_threshold = 0.05;\n state.initial_deltas.x +=\n std::abs(ev->dx) \/ speed_factor->as_double();\n state.initial_deltas.y +=\n std::abs(ev->dy) \/ speed_factor->as_double();\n\n bool horizontal =\n state.initial_deltas.x > initial_direction_threshold;\n bool vertical =\n state.initial_deltas.y > initial_direction_threshold;\n\n horizontal &= state.initial_deltas.x > state.initial_deltas.y;\n vertical &= state.initial_deltas.y > state.initial_deltas.x;\n\n if (horizontal && grid.width > 1 && enable_horizontal->as_cached_int())\n {\n start_swipe(HORIZONTAL);\n }\n else if (vertical && grid.height > 1 && enable_vertical->as_cached_int())\n {\n start_swipe(VERTICAL);\n }\n\n if (state.direction == UNKNOWN)\n return;\n }\n\n const double cap = speed_cap->as_cached_double();\n const double fac = speed_factor->as_cached_double();\n\n state.delta_prev = state.delta_last;\n if (state.direction == HORIZONTAL)\n {\n state.delta_sum += vswipe_process_delta(ev->dx, state.delta_sum,\n state.vx, state.vw, cap, fac);\n state.delta_last = ev->dx;\n } else\n {\n state.delta_sum += vswipe_process_delta(ev->dy, state.delta_sum,\n state.vy, state.vh, cap, fac);\n state.delta_last = ev->dy;\n }\n\n output->render->damage_whole();\n };\n\n wf::signal_callback_t on_swipe_end = [=] (wf::signal_data_t *data)\n {\n if (!state.swiping)\n return;\n\n state.swiping = false;\n\n auto ev = static_cast<wf::swipe_end_signal*>(data)->ev;\n\n const double move_threshold =\n clamp(threshold->as_cached_double(), 0.0, 1.0);\n const double fast_threshold =\n clamp(delta_threshold->as_cached_double(), 0.0, 1000.0);\n\n int target_delta = 0;\n wf_point target_workspace = {state.vx, state.vy};\n\n if (!ev->cancelled || ignore_cancel->as_int())\n {\n switch (state.direction)\n {\n case UNKNOWN:\n target_delta = 0;\n break;\n case HORIZONTAL:\n target_delta = vswipe_finish_target(state.delta_sum,\n state.vx, state.vw, state.delta_prev + state.delta_last,\n move_threshold, fast_threshold);\n target_workspace.x -= target_delta;\n break;\n case VERTICAL:\n target_delta = vswipe_finish_target(state.delta_sum,\n state.vy, state.vh, state.delta_prev + state.delta_last,\n move_threshold, fast_threshold);\n target_workspace.y -= target_delta;\n break;\n }\n }\n\n transition = {state.delta_sum, target_delta + state.gap * target_delta};\n\n output->workspace->set_workspace(target_workspace);\n output->render->set_redraw_always();\n duration.start();\n };\n\n void finalize_and_exit()\n {\n state.swiping = false;\n grab_interface->ungrab();\n output->deactivate_plugin(grab_interface);\n\n if (streams.prev.running)\n output->render->workspace_stream_stop(streams.prev);\n output->render->workspace_stream_stop(streams.curr);\n if (streams.next.running)\n output->render->workspace_stream_stop(streams.next);\n\n output->render->set_renderer(nullptr);\n output->render->set_redraw_always(false);\n }\n\n void fini()\n {\n if (state.swiping)\n finalize_and_exit();\n\n OpenGL::render_begin();\n streams.prev.buffer.release();\n streams.curr.buffer.release();\n streams.next.buffer.release();\n OpenGL::render_end();\n }\n};\n\nDECLARE_WAYFIRE_PLUGIN(vswipe);\n<commit_msg>vswipe: fix remaining issues<commit_after>#include <plugin.hpp>\n#include <output.hpp>\n#include <core.hpp>\n#include <debug.hpp>\n#include <view.hpp>\n#include <view-transform.hpp>\n#include <render-manager.hpp>\n#include <workspace-stream.hpp>\n#include <workspace-manager.hpp>\n#include <signal-definitions.hpp>\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <animation.hpp>\n\n#include <cmath>\n#include <utility>\n#include <animation.hpp>\n\n#include \"vswipe-processing.hpp\"\n\nclass vswipe : public wf::plugin_interface_t\n{\n private:\n struct {\n \/* When the workspace is set to (-1, -1), means no such workspace *\/\n wf::workspace_stream_t prev, curr, next;\n } streams;\n\n enum swipe_direction_t\n {\n HORIZONTAL = 0,\n VERTICAL,\n UNKNOWN,\n };\n\n struct {\n bool swiping = false;\n bool animating = false;\n swipe_direction_t direction;\n\n wf_pointf initial_deltas;\n\n double delta_sum = 0.0;\n double gap = 0.0;\n\n double delta_prev = 0.0;\n double delta_last = 0.0;\n\n int vx = 0;\n int vy = 0;\n int vw = 0;\n int vh = 0;\n } state;\n\n wf::render_hook_t renderer;\n\n wf_duration duration;\n wf_transition transition;\n\n wf_option animation_duration;\n wf_option background_color;\n wf_option enable_horizontal;\n wf_option enable_vertical;\n wf_option ignore_cancel;\n wf_option fingers;\n wf_option gap;\n wf_option threshold;\n wf_option delta_threshold;\n wf_option speed_factor;\n wf_option speed_cap;\n\n public:\n\n void init(wayfire_config *config)\n {\n grab_interface->name = \"vswipe\";\n grab_interface->capabilities = wf::CAPABILITY_MANAGE_COMPOSITOR;\n grab_interface->callbacks.cancel = [=] () { finalize_and_exit(); };\n\n auto section = config->get_section(\"vswipe\");\n\n animation_duration = section->get_option(\"duration\", \"180\");\n duration = wf_duration(animation_duration);\n\n enable_horizontal = section->get_option(\"enable_horizontal\", \"1\");\n enable_vertical = section->get_option(\"enable_vertical\", \"1\");\n ignore_cancel = section->get_option(\"ignore_cancel\", \"1\");\n fingers = section->get_option(\"fingers\", \"4\");\n gap = section->get_option(\"gap\", \"32\");\n threshold = section->get_option(\"threshold\", \"0.35\");\n delta_threshold = section->get_option(\"delta_threshold\", \"24\");\n speed_factor = section->get_option(\"speed_factor\", \"256\");\n speed_cap = section->get_option(\"speed_cap\", \"0.05\");\n wf::get_core().connect_signal(\"pointer-swipe-begin\", &on_swipe_begin);\n wf::get_core().connect_signal(\"pointer-swipe-update\", &on_swipe_update);\n wf::get_core().connect_signal(\"pointer-swipe-end\", &on_swipe_end);\n\n background_color = section->get_option(\"background\", \"0 0 0 1\");\n\n renderer = [=] (const wf_framebuffer& buffer) { render(buffer); };\n }\n\n \/**\n * Get the translation matrix for a workspace at the given offset.\n * Depends on the swipe direction\n *\/\n glm::mat4 get_translation(double offset)\n {\n switch (state.direction)\n {\n case UNKNOWN:\n return glm::mat4(1.0);\n case HORIZONTAL:\n return glm::translate(glm::mat4(1.0),\n glm::vec3(offset, 0.0, 0.0));\n case VERTICAL:\n return glm::translate(glm::mat4(1.0),\n glm::vec3(0.0, -offset, 0.0));\n }\n\n assert(false); \/\/ not reached\n }\n\n void render(const wf_framebuffer &fb)\n {\n if (!duration.running() && !state.swiping)\n finalize_and_exit();\n\n if (duration.running())\n state.delta_sum = duration.progress(transition);\n\n update_stream(streams.prev);\n update_stream(streams.curr);\n update_stream(streams.next);\n\n OpenGL::render_begin(fb);\n OpenGL::clear(background_color->as_cached_color());\n fb.scissor(fb.framebuffer_box_from_geometry_box(fb.geometry));\n\n gl_geometry out_geometry = {\n .x1 = -1,\n .y1 = 1,\n .x2 = 1,\n .y2 = -1,\n };\n\n auto swipe = get_translation(state.delta_sum * 2);\n if (streams.prev.ws.x >= 0)\n {\n auto prev = get_translation(-2.0 - state.gap * 2.0);\n OpenGL::render_transformed_texture(streams.prev.buffer.tex,\n out_geometry, {}, fb.transform * prev * swipe);\n }\n\n OpenGL::render_transformed_texture(streams.curr.buffer.tex,\n out_geometry, {}, fb.transform * swipe);\n\n if (streams.next.ws.x >= 0)\n {\n auto next = get_translation(2.0 + state.gap * 2.0);\n OpenGL::render_transformed_texture(streams.next.buffer.tex,\n out_geometry, {}, fb.transform * next * swipe);\n }\n\n GL_CALL(glUseProgram(0));\n OpenGL::render_end();\n }\n\n inline void update_stream(wf::workspace_stream_t& s)\n {\n if (s.ws.x < 0 || s.ws.y < 0)\n return;\n\n if (!s.running)\n output->render->workspace_stream_start(s);\n else\n output->render->workspace_stream_update(s);\n }\n\n wf::signal_callback_t on_swipe_begin = [=] (wf::signal_data_t *data)\n {\n if (!enable_horizontal->as_cached_int() && !enable_vertical->as_cached_int())\n return;\n\n if (output->is_plugin_active(grab_interface->name))\n return;\n\n auto ev = static_cast<wf::swipe_begin_signal*> (data)->ev;\n if (static_cast<int>(ev->fingers) != fingers->as_cached_int())\n return;\n\n \/\/ Plugins are per output, swipes are global, so we need to handle\n \/\/ the swipe only when the cursor is on *our* (plugin instance's) output\n if (!(output->get_relative_geometry() & output->get_cursor_position()))\n return;\n\n state.swiping = true;\n state.direction = UNKNOWN;\n state.initial_deltas = {0.0, 0.0};\n state.delta_sum = 0;\n state.delta_last = 0;\n state.delta_prev = 0;\n\n state.gap = gap->as_cached_double() \/ output->get_screen_size().width;\n\n \/\/ We switch the actual workspace before the finishing animation,\n \/\/ so the rendering of the animation cannot dynamically query current\n \/\/ workspace again, so it's stored here\n auto grid = output->workspace->get_workspace_grid_size();\n auto ws = output->workspace->get_current_workspace();\n state.vw = grid.width;\n state.vh = grid.height;\n state.vx = ws.x;\n state.vy = ws.y;\n\n \/* Invalid in the beginning, because we want a few swipe events to\n * determine whether swipe is horizontal or vertical *\/\n streams.prev.ws = {-1, -1};\n streams.next.ws = {-1, -1};\n streams.curr.ws = wf_point {ws.x, ws.y};\n };\n\n void start_swipe(swipe_direction_t direction)\n {\n assert(direction != UNKNOWN);\n state.direction = direction;\n\n wf::get_core().focus_output(output);\n\n if (!output->activate_plugin(grab_interface))\n return;\n\n grab_interface->grab();\n output->render->set_renderer(renderer);\n output->render->damage_whole();\n\n auto ws = output->workspace->get_current_workspace();\n auto grid = output->workspace->get_workspace_grid_size();\n\n if (direction == HORIZONTAL)\n {\n if (ws.x > 0)\n streams.prev.ws = wf_point{ws.x - 1, ws.y};\n if (ws.x < grid.width - 1)\n streams.next.ws = wf_point{ws.x + 1, ws.y};\n } else \/\/if (direction == VERTICAL)\n {\n if (ws.y > 0)\n streams.prev.ws = wf_point{ws.x, ws.y - 1};\n if (ws.y < grid.height - 1)\n streams.next.ws = wf_point{ws.x, ws.y + 1};\n }\n }\n\n wf::signal_callback_t on_swipe_update = [=] (wf::signal_data_t *data)\n {\n if (!state.swiping)\n return;\n\n auto ev = static_cast<wf::swipe_update_signal*> (data)->ev;\n\n if (state.direction == UNKNOWN)\n {\n auto grid = output->workspace->get_workspace_grid_size();\n\n \/\/ XXX: how to determine this??\n static constexpr double initial_direction_threshold = 0.05;\n state.initial_deltas.x +=\n std::abs(ev->dx) \/ speed_factor->as_double();\n state.initial_deltas.y +=\n std::abs(ev->dy) \/ speed_factor->as_double();\n\n bool horizontal =\n state.initial_deltas.x > initial_direction_threshold;\n bool vertical =\n state.initial_deltas.y > initial_direction_threshold;\n\n horizontal &= state.initial_deltas.x > state.initial_deltas.y;\n vertical &= state.initial_deltas.y > state.initial_deltas.x;\n\n if (horizontal && grid.width > 1 && enable_horizontal->as_cached_int())\n {\n start_swipe(HORIZONTAL);\n }\n else if (vertical && grid.height > 1 && enable_vertical->as_cached_int())\n {\n start_swipe(VERTICAL);\n }\n\n if (state.direction == UNKNOWN)\n return;\n }\n\n const double cap = speed_cap->as_cached_double();\n const double fac = speed_factor->as_cached_double();\n\n state.delta_prev = state.delta_last;\n if (state.direction == HORIZONTAL)\n {\n state.delta_sum += vswipe_process_delta(ev->dx, state.delta_sum,\n state.vx, state.vw, cap, fac);\n state.delta_last = ev->dx;\n } else\n {\n state.delta_sum += vswipe_process_delta(ev->dy, state.delta_sum,\n state.vy, state.vh, cap, fac);\n state.delta_last = ev->dy;\n }\n\n output->render->damage_whole();\n };\n\n wf::signal_callback_t on_swipe_end = [=] (wf::signal_data_t *data)\n {\n if (!state.swiping)\n return;\n\n state.swiping = false;\n\n auto ev = static_cast<wf::swipe_end_signal*>(data)->ev;\n\n const double move_threshold =\n clamp(threshold->as_cached_double(), 0.0, 1.0);\n const double fast_threshold =\n clamp(delta_threshold->as_cached_double(), 0.0, 1000.0);\n\n int target_delta = 0;\n wf_point target_workspace = {state.vx, state.vy};\n\n if (!ev->cancelled || ignore_cancel->as_int())\n {\n switch (state.direction)\n {\n case UNKNOWN:\n target_delta = 0;\n break;\n case HORIZONTAL:\n target_delta = vswipe_finish_target(state.delta_sum,\n state.vx, state.vw, state.delta_prev + state.delta_last,\n move_threshold, fast_threshold);\n target_workspace.x -= target_delta;\n break;\n case VERTICAL:\n target_delta = vswipe_finish_target(state.delta_sum,\n state.vy, state.vh, state.delta_prev + state.delta_last,\n move_threshold, fast_threshold);\n target_workspace.y -= target_delta;\n break;\n }\n }\n\n transition = {state.delta_sum, target_delta + state.gap * target_delta};\n\n output->workspace->set_workspace(target_workspace);\n state.animating = true;\n output->render->set_redraw_always();\n duration.start();\n };\n\n void finalize_and_exit()\n {\n state.swiping = false;\n grab_interface->ungrab();\n output->deactivate_plugin(grab_interface);\n\n if (streams.prev.running)\n output->render->workspace_stream_stop(streams.prev);\n output->render->workspace_stream_stop(streams.curr);\n if (streams.next.running)\n output->render->workspace_stream_stop(streams.next);\n\n output->render->set_renderer(nullptr);\n\n if (state.animating)\n {\n output->render->set_redraw_always(false);\n state.animating = false;\n }\n }\n\n void fini()\n {\n if (state.swiping)\n finalize_and_exit();\n\n OpenGL::render_begin();\n streams.prev.buffer.release();\n streams.curr.buffer.release();\n streams.next.buffer.release();\n OpenGL::render_end();\n\n wf::get_core().disconnect_signal(\"pointer-swipe-begin\", &on_swipe_begin);\n wf::get_core().disconnect_signal(\"pointer-swipe-update\", &on_swipe_update);\n wf::get_core().disconnect_signal(\"pointer-swipe-end\", &on_swipe_end);\n }\n};\n\nDECLARE_WAYFIRE_PLUGIN(vswipe);\n<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Ash Berlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/class.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/native_object_base.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include <new>\n\n#include \"sqlite3.h\"\n\nusing namespace flusspferd;\n\n\/\/ Put everything in an anon-namespace so typeid wont clash ever.\nnamespace {\n\nvoid raise_sqlite_error(sqlite3* db);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Classes\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass sqlite3 : public native_object_base {\npublic:\n struct class_info : public flusspferd::class_info {\n static char const *full_name() { return \"SQLite3\"; }\n typedef boost::mpl::bool_<true> constructible;\n static char const *constructor_name() { return \"SQLite3\"; }\n static void augment_constructor(object &ctor);\n static object create_prototype();\n };\n\n sqlite3(object const &obj, call_context &x);\n ~sqlite3();\n\nprotected:\n \/\/void trace(tracer &);\n\nprivate: \/\/ JS methods\n ::sqlite3 *db;\n\n void close();\n object cursor(call_context &x);\n};\n\nclass sqlite3_cursor : public native_object_base {\npublic:\n struct class_info : public flusspferd::class_info {\n static char const *full_name() { return \"SQLite3.Cursor\"; }\n typedef boost::mpl::bool_<true> constructible;\n static char const* constructor_name() { return \"Cursor\"; }\n };\n\n sqlite3_cursor(object const &obj, call_context &x);\n sqlite3_cursor(object const &obj, sqlite3_stmt *sth);\n ~sqlite3_cursor();\n\nprivate: \/\/ JS methods\n sqlite3_stmt *sth;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ import hook\nextern \"C\" value flusspferd_load(object container)\n{\n return load_class<sqlite3>(container);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Set version properties on constructor object\nvoid sqlite3::class_info::augment_constructor(object &ctor)\n{\n \/\/ Set static properties on the constructor\n ctor.define_property(\"version\", SQLITE_VERSION_NUMBER, \n object::read_only_property | object::permanent_property);\n ctor.define_property(\"versionStr\", string(SQLITE_VERSION), \n object::read_only_property | object::permanent_property);\n\n load_class<sqlite3_cursor>(ctor);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nobject sqlite3::class_info::create_prototype()\n{\n object proto = create_object();\n\n create_native_method(proto, \"cursor\", 1);\n create_native_method(proto, \"close\", 0);\n return proto; \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsqlite3::sqlite3(object const &obj, call_context &x)\n : native_object_base(obj), \n db(NULL)\n{\n if (x.arg.size() == 0)\n throw exception (\"SQLite3 requires more than 0 arguments\");\n\n string dsn = x.arg[0];\n\n \/\/ TODO: pull arguments from 2nd\/options argument\n if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {\n if (db)\n raise_sqlite_error(db);\n else\n throw std::bad_alloc(); \/\/ out of memory. better way to signal this?\n }\n\n \/\/register_native_method(\"cursor\", &sqlite3::cursor);\n register_native_method(\"close\", &sqlite3::close);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsqlite3::~sqlite3()\n{\n close();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::close()\n{\n if (db)\n sqlite3_close(db);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nobject sqlite3::cursor(call_context &x) {\n local_root_scope scope;\n if (!db)\n throw exception(\"SQLite3.cursor called on closed dbh\");\n\n if (x.arg.size() < 1)\n throw exception (\"cursor requires more than 0 arguments\");\n\n string sql = x.arg[0].to_string();\n size_t n_bytes = sql.length() * 2;\n sqlite3_stmt *sth;\n char16_t *tail; \/\/ uncompiled part of the sql (when multiple stmts)\n if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)\n {\n raise_sqlite_error(db);\n }\n object cursor = create_native_object<sqlite3_cursor>(object(), sth);\n\n \/\/ TODO: remove tail and set it seperately\n cursor.define_property(\"sql\", sql);\n\n return cursor;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ 'Private' constructor that is called from sqlite3::cursor\nsqlite3_cursor::sqlite3_cursor(object const &obj, sqlite3_stmt *_sth)\n : native_object_base(obj),\n sth(_sth)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ 'Public' JS exposed constructor, dies cos its created without a sth.\nsqlite3_cursor::sqlite3_cursor(object const &obj, call_context &)\n : native_object_base(obj)\n{\n throw exception(\"Use sqlite3.cursor to create cursors\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsqlite3_cursor::~sqlite3_cursor()\n{\n}\n\n\n\/\/ Helper function\nvoid raise_sqlite_error(::sqlite3* db)\n{\n std::string s = \"SQLite3 Error: \";\n s += sqlite3_errmsg(db);\n throw exception(s);\n}\n\n}\n\n<commit_msg>Plugins\/sqlite3: When using call_context, return type must be void<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Ash Berlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/class.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/native_object_base.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include <new>\n\n#include \"sqlite3.h\"\n\nusing namespace flusspferd;\n\n\/\/ Put everything in an anon-namespace so typeid wont clash ever.\nnamespace {\n\nvoid raise_sqlite_error(sqlite3* db);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Classes\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass sqlite3 : public native_object_base {\npublic:\n struct class_info : public flusspferd::class_info {\n static char const *full_name() { return \"SQLite3\"; }\n typedef boost::mpl::bool_<true> constructible;\n static char const *constructor_name() { return \"SQLite3\"; }\n static void augment_constructor(object &ctor);\n static object create_prototype();\n };\n\n sqlite3(object const &obj, call_context &x);\n ~sqlite3();\n\nprotected:\n \/\/void trace(tracer &);\n\nprivate: \/\/ JS methods\n ::sqlite3 *db;\n\n void close();\n void cursor(call_context &x);\n};\n\nclass sqlite3_cursor : public native_object_base {\npublic:\n struct class_info : public flusspferd::class_info {\n static char const *full_name() { return \"SQLite3.Cursor\"; }\n typedef boost::mpl::bool_<true> constructible;\n static char const* constructor_name() { return \"Cursor\"; }\n };\n\n sqlite3_cursor(object const &obj, call_context &x);\n sqlite3_cursor(object const &obj, sqlite3_stmt *sth);\n ~sqlite3_cursor();\n\nprivate: \/\/ JS methods\n sqlite3_stmt *sth;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ import hook\nextern \"C\" value flusspferd_load(object container)\n{\n return load_class<sqlite3>(container);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Set version properties on constructor object\nvoid sqlite3::class_info::augment_constructor(object &ctor)\n{\n \/\/ Set static properties on the constructor\n ctor.define_property(\"version\", SQLITE_VERSION_NUMBER, \n object::read_only_property | object::permanent_property);\n ctor.define_property(\"versionStr\", string(SQLITE_VERSION), \n object::read_only_property | object::permanent_property);\n\n load_class<sqlite3_cursor>(ctor);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nobject sqlite3::class_info::create_prototype()\n{\n object proto = create_object();\n\n create_native_method(proto, \"cursor\", 1);\n create_native_method(proto, \"close\", 0);\n return proto; \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsqlite3::sqlite3(object const &obj, call_context &x)\n : native_object_base(obj), \n db(NULL)\n{\n if (x.arg.size() == 0)\n throw exception (\"SQLite3 requires more than 0 arguments\");\n\n string dsn = x.arg[0];\n\n \/\/ TODO: pull arguments from 2nd\/options argument\n if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {\n if (db)\n raise_sqlite_error(db);\n else\n throw std::bad_alloc(); \/\/ out of memory. better way to signal this?\n }\n\n register_native_method(\"cursor\", &sqlite3::cursor);\n register_native_method(\"close\", &sqlite3::close);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsqlite3::~sqlite3()\n{\n close();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::close()\n{\n if (db) {\n sqlite3_close(db);\n db = NULL;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::cursor(call_context &x) {\n local_root_scope scope;\n if (!db)\n throw exception(\"SQLite3.cursor called on closed dbh\");\n\n if (x.arg.size() < 1)\n throw exception (\"cursor requires more than 0 arguments\");\n\n string sql = x.arg[0].to_string();\n size_t n_bytes = sql.length() * 2;\n sqlite3_stmt *sth;\n char16_t *tail; \/\/ uncompiled part of the sql (when multiple stmts)\n if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)\n {\n raise_sqlite_error(db);\n }\n object cursor = create_native_object<sqlite3_cursor>(object(), sth);\n\n \/\/ TODO: remove tail and set it seperately\n cursor.define_property(\"sql\", sql);\n\n x.result = cursor;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ 'Private' constructor that is called from sqlite3::cursor\nsqlite3_cursor::sqlite3_cursor(object const &obj, sqlite3_stmt *_sth)\n : native_object_base(obj),\n sth(_sth)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ 'Public' JS exposed constructor, dies cos its created without a sth.\nsqlite3_cursor::sqlite3_cursor(object const &obj, call_context &)\n : native_object_base(obj)\n{\n throw exception(\"Use sqlite3.cursor to create cursors\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsqlite3_cursor::~sqlite3_cursor()\n{\n}\n\n\n\/\/ Helper function\nvoid raise_sqlite_error(::sqlite3* db)\n{\n std::string s = \"SQLite3 Error: \";\n s += sqlite3_errmsg(db);\n throw exception(s);\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: embeddedobjectcontainer.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2005-07-12 12:27:16 $\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#ifndef _COMPHELPER_OBJECTCONTAINER_HXX_\n#define _COMPHELPER_OBJECTCONTAINER_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_\n#include <com\/sun\/star\/embed\/XEmbeddedObject.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#endif\n#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_\n#include <com\/sun\/star\/io\/XInputStrem.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n#include <rtl\/ustring.hxx>\n\nnamespace comphelper\n{\n\nstruct EmbedImpl;\nclass COMPHELPER_DLLPUBLIC EmbeddedObjectContainer\n{\n EmbedImpl* pImpl;\n\npublic:\n \/\/ add an embedded object to the container storage\n sal_Bool StoreEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString&, sal_Bool );\n\n \/\/ add an embedded object that has been imported from the container storage - should only be called by filters!\n void AddEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, const ::rtl::OUString& );\n\n EmbeddedObjectContainer();\n EmbeddedObjectContainer( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& );\n ~EmbeddedObjectContainer();\n\n void SwitchPersistence( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& );\n sal_Bool CommitImageSubStorage();\n void ReleaseImageSubStorage();\n\n ::rtl::OUString CreateUniqueObjectName();\n\n \/\/ get a list of object names that have been added so far\n com::sun::star::uno::Sequence < ::rtl::OUString > GetObjectNames();\n\n \/\/ check for existence of objects at all\n sal_Bool HasEmbeddedObjects();\n\n \/\/ check existence of an object - either by identity or by name\n sal_Bool HasEmbeddedObject( const ::rtl::OUString& );\n sal_Bool HasEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >& );\n\n \/\/ get the object name of an object - this is the persist name if the object has persistence\n ::rtl::OUString GetEmbeddedObjectName( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >& );\n\n \/\/ retrieve an embedded object by name that either has been added already or is available in the container storage\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject > GetEmbeddedObject( const ::rtl::OUString& );\n\n \/\/ create an object from a ClassId\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >\n CreateEmbeddedObject( const com::sun::star::uno::Sequence < sal_Int8 >&, ::rtl::OUString& );\n\n \/\/ insert an embedded object into the container - objects persistant representation will be added to the storage\n sal_Bool InsertEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString& );\n\n \/\/ load an embedded object from a MediaDescriptor and insert it into the container\n \/\/ a new object will be created from the new content and returned\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >\n InsertEmbeddedObject( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, ::rtl::OUString& );\n\n \/\/ create an embedded link based on a MediaDescriptor and insert it into the container\n \/\/ a new object will be created from the new content and returned\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >\n InsertEmbeddedLink( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, ::rtl::OUString& );\n\n \/\/ create an object from a stream that contains its persistent representation and insert it as usual (usually called from clipboard)\n \/\/ a new object will be created from the new content and returned\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >\n InsertEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >&, ::rtl::OUString& );\n\n \/\/ copy an embedded object into the storage\n sal_Bool CopyEmbeddedObject( EmbeddedObjectContainer& rSrc, const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString& );\n\n \/\/ copy an embedded object into the storage, open the new copy and return it\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject > CopyAndGetEmbeddedObject( EmbeddedObjectContainer& rSrc, const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >& xObj, \/* TODO const ::rtl::OUString& aOrigName,*\/ ::rtl::OUString& rName );\n\n \/\/ move an embedded object from one container to another one\n sal_Bool MoveEmbeddedObject( EmbeddedObjectContainer& rSrc, const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString& );\n\n \/\/ remove an embedded object from the container and from the storage; if object can't be closed\n sal_Bool RemoveEmbeddedObject( const ::rtl::OUString& rName, sal_Bool bClose=sal_True );\n sal_Bool RemoveEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, sal_Bool bClose=sal_True );\n\n \/\/ move an embedded object to another container (keep the persistent name)\n sal_Bool MoveEmbeddedObject( const ::rtl::OUString& rName, EmbeddedObjectContainer& );\n\n \/\/ get the stored graphical representation for the object\n com::sun::star::uno::Reference < com::sun::star::io::XInputStream > GetGraphicStream( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString* pMediaType=0 );\n\n \/\/ get the stored graphical representation by the object name\n com::sun::star::uno::Reference < com::sun::star::io::XInputStream > GetGraphicStream( const ::rtl::OUString& aName, ::rtl::OUString* pMediaType=0 );\n\n \/\/ add a graphical representation for an object\n sal_Bool InsertGraphicStream( const com::sun::star::uno::Reference < com::sun::star::io::XInputStream >& rStream, const ::rtl::OUString& rObjectName, const ::rtl::OUString& rMediaType );\n\n \/\/ remove a graphical representation for an object\n sal_Bool RemoveGraphicStream( const ::rtl::OUString& rObjectName );\n\n \/\/ copy the graphical representation from different container\n sal_Bool TryToCopyGraphReplacement( EmbeddedObjectContainer& rSrc,\n const ::rtl::OUString& aOrigName,\n const ::rtl::OUString& aTargetName );\n\n void CloseEmbeddedObjects();\n};\n\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.7.22); FILE MERGED 2005\/09\/05 15:23:40 rt 1.7.22.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: embeddedobjectcontainer.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:29:57 $\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 _COMPHELPER_OBJECTCONTAINER_HXX_\n#define _COMPHELPER_OBJECTCONTAINER_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_\n#include <com\/sun\/star\/embed\/XEmbeddedObject.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#endif\n#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_\n#include <com\/sun\/star\/io\/XInputStrem.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n#include <rtl\/ustring.hxx>\n\nnamespace comphelper\n{\n\nstruct EmbedImpl;\nclass COMPHELPER_DLLPUBLIC EmbeddedObjectContainer\n{\n EmbedImpl* pImpl;\n\npublic:\n \/\/ add an embedded object to the container storage\n sal_Bool StoreEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString&, sal_Bool );\n\n \/\/ add an embedded object that has been imported from the container storage - should only be called by filters!\n void AddEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, const ::rtl::OUString& );\n\n EmbeddedObjectContainer();\n EmbeddedObjectContainer( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& );\n ~EmbeddedObjectContainer();\n\n void SwitchPersistence( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& );\n sal_Bool CommitImageSubStorage();\n void ReleaseImageSubStorage();\n\n ::rtl::OUString CreateUniqueObjectName();\n\n \/\/ get a list of object names that have been added so far\n com::sun::star::uno::Sequence < ::rtl::OUString > GetObjectNames();\n\n \/\/ check for existence of objects at all\n sal_Bool HasEmbeddedObjects();\n\n \/\/ check existence of an object - either by identity or by name\n sal_Bool HasEmbeddedObject( const ::rtl::OUString& );\n sal_Bool HasEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >& );\n\n \/\/ get the object name of an object - this is the persist name if the object has persistence\n ::rtl::OUString GetEmbeddedObjectName( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >& );\n\n \/\/ retrieve an embedded object by name that either has been added already or is available in the container storage\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject > GetEmbeddedObject( const ::rtl::OUString& );\n\n \/\/ create an object from a ClassId\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >\n CreateEmbeddedObject( const com::sun::star::uno::Sequence < sal_Int8 >&, ::rtl::OUString& );\n\n \/\/ insert an embedded object into the container - objects persistant representation will be added to the storage\n sal_Bool InsertEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString& );\n\n \/\/ load an embedded object from a MediaDescriptor and insert it into the container\n \/\/ a new object will be created from the new content and returned\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >\n InsertEmbeddedObject( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, ::rtl::OUString& );\n\n \/\/ create an embedded link based on a MediaDescriptor and insert it into the container\n \/\/ a new object will be created from the new content and returned\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >\n InsertEmbeddedLink( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, ::rtl::OUString& );\n\n \/\/ create an object from a stream that contains its persistent representation and insert it as usual (usually called from clipboard)\n \/\/ a new object will be created from the new content and returned\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >\n InsertEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >&, ::rtl::OUString& );\n\n \/\/ copy an embedded object into the storage\n sal_Bool CopyEmbeddedObject( EmbeddedObjectContainer& rSrc, const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString& );\n\n \/\/ copy an embedded object into the storage, open the new copy and return it\n ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject > CopyAndGetEmbeddedObject( EmbeddedObjectContainer& rSrc, const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >& xObj, \/* TODO const ::rtl::OUString& aOrigName,*\/ ::rtl::OUString& rName );\n\n \/\/ move an embedded object from one container to another one\n sal_Bool MoveEmbeddedObject( EmbeddedObjectContainer& rSrc, const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString& );\n\n \/\/ remove an embedded object from the container and from the storage; if object can't be closed\n sal_Bool RemoveEmbeddedObject( const ::rtl::OUString& rName, sal_Bool bClose=sal_True );\n sal_Bool RemoveEmbeddedObject( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, sal_Bool bClose=sal_True );\n\n \/\/ move an embedded object to another container (keep the persistent name)\n sal_Bool MoveEmbeddedObject( const ::rtl::OUString& rName, EmbeddedObjectContainer& );\n\n \/\/ get the stored graphical representation for the object\n com::sun::star::uno::Reference < com::sun::star::io::XInputStream > GetGraphicStream( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XEmbeddedObject >&, ::rtl::OUString* pMediaType=0 );\n\n \/\/ get the stored graphical representation by the object name\n com::sun::star::uno::Reference < com::sun::star::io::XInputStream > GetGraphicStream( const ::rtl::OUString& aName, ::rtl::OUString* pMediaType=0 );\n\n \/\/ add a graphical representation for an object\n sal_Bool InsertGraphicStream( const com::sun::star::uno::Reference < com::sun::star::io::XInputStream >& rStream, const ::rtl::OUString& rObjectName, const ::rtl::OUString& rMediaType );\n\n \/\/ remove a graphical representation for an object\n sal_Bool RemoveGraphicStream( const ::rtl::OUString& rObjectName );\n\n \/\/ copy the graphical representation from different container\n sal_Bool TryToCopyGraphReplacement( EmbeddedObjectContainer& rSrc,\n const ::rtl::OUString& aOrigName,\n const ::rtl::OUString& aTargetName );\n\n void CloseEmbeddedObjects();\n};\n\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: implementationreference.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-11-26 21:08:05 $\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 _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX\n#define _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_\n#include <com\/sun\/star\/uno\/XInterface.hpp>\n#endif\n\nnamespace comphelper\n{\n\n \/** Holds a uno::Reference alongside a C++ implementation pointer\n\n This template is useful to accomplish the following task: the\n client needs an implementation pointer to an object providing\n UNO interfaces. It is unsafe to simply store a C++ pointer,\n because of the automatic UNO lifetime control. It is\n inconvenient to always cast the UNO interface to the C++\n implementation, and what's more, it's mostly unclear to the\n casual code reader.\n\n Thus, this template nicely encapsulate the stated intention,\n by holding a uno::Reference internally, and providing simple\n C++ pointer semantics to the outside. As a differentiator to\n ::rtl::Reference, this template features a getRef() method,\n giving you friction-less access to the internal UNO interface,\n without extra querying.\n\n By the way, the pointer semantic of this template include\n transitive constness. That means, if this template's instance\n is const (e.g. because it is a member of a class which is\n accessed in a const method), the pointer returned is also\n const.\n\n As this template is geared towards fast, internal pointer\n access, validity of the UNO reference is _not_ checked for\n every pointer access. The client of this template is\n responsible to check that, whereever necessary, via the is()\n method.\n\n @tpl CppType\n The C++ type this class should mimick a pointer to (not the\n pointer type itself!).\n\n @tpl UnoType\n The UNO interface type of the object (a uno::Reference to this\n type is held internally).\n\n @tpl XIfType\n An unambiguous derivative of UnoType. This is defaulted to\n the second template parameter (UnoType), which should normally\n just work, since one typically has only single inheritance in\n UNO.<p>\n Alternatively, when using the\n ImplementationReference::createFromQuery() method to create an\n instance, this type can serve a different need: if the\n provided CppType only derives from XInterface (generally\n speaking, derives from a UNO interface above UnoType in the\n class hierarchy), then the default XIfType constitutes a\n possibly invalid downcast to UnoType. Setting XIfType equal to\n CppTypes's most derived UNO interface type then solves this\n problem (which is not as arcane as it seems to be. Just\n imagine you're providing a C++ abstract interface, which must\n provide UNO reference semantics. Naturally, you will derive\n this C++ interface only from XInterface, to reduce the number\n of ambiguous classes. Even more naturally, it is reasonable to\n have UnoType be something different from XInterface, governed\n by the usage of the C++ interface)\n\n @sample ImplementationReference< MyCppType, XMyInterface >\n\n @sample ImplementationReference< MyAbstractCppType, XMyInterface, XInterface >\n for an abstract C++ class\n\n @see ::rtl::Reference\n\n *\/\n template < class CppType,\n class UnoType,\n class XIfType=UnoType > class ImplementationReference\n {\n public:\n\n typedef UnoType UnoInterfaceType;\n typedef CppType ImplementationType;\n typedef XIfType UnambiguousXInterfaceType;\n\n \/** Default-construct an ImplementationReference\n\n Uno reference will be invalid, implementation pointer will\n be NULL.\n *\/\n ImplementationReference() :\n mxRef(),\n mpImpl( NULL )\n {\n }\n\n \/** Create an ImplementationReference from C++ pointer.\n\n This constructor does not perform an explicit\n QueryInterface on the provided implementation object, but\n constructs the UNO reference directly from the given\n pointer. This is the fastest, and most often the best way\n to create an ImplementationReference. If the conversion\n between the implementation object and the required UNO\n interface is ambiguous, provide the third template\n parameter with a type that can be unambiguously upcasted\n to the UNO interface (the second template parameter).\n\n There are cases, however, where performing a\n QueryInterface is the better, albeit slower choice. In\n these cases, createFromQuery() should be used.\n\n @param pImpl\n Pointer to the C++ implementation type\n\n @see createFromQuery()\n *\/\n explicit ImplementationReference( ImplementationType* pImpl ) :\n mxRef( static_cast<UnambiguousXInterfaceType*>(pImpl) ),\n mpImpl( pImpl )\n {\n }\n\n struct CreateFromQuery { };\n \/** Create an ImplementationReference from C++ pointer\n\n @param pImpl\n The pointer to the C++ implementation type, which is\n queried for the template-parameterized UNO type.\n\n @param dummy\n Dummy parameter, to distinguish this contructor from the\n default unary one (which does not perform a\n QueryInterface)\n *\/\n ImplementationReference( ImplementationType* pImpl, CreateFromQuery dummy ) :\n mxRef( static_cast<UnambiguousXInterfaceType*>(pImpl),\n ::com::sun::star::uno::UNO_QUERY ),\n mpImpl( pImpl )\n {\n }\n\n \/** Factory method to create an ImplementationReference from\n C++ pointer.\n\n This is a static version of the constructor which creates\n an instance of an implementation type which is explicitely\n queried for the ImplementationReference's\n template-parameterized UNO type.\n\n @sample\n mpRef = mpRef.createFromQuery( new ImplementationType );\n *\/\n static ImplementationReference createFromQuery( ImplementationType* pImpl )\n {\n return ImplementationReference( pImpl, CreateFromQuery() );\n }\n\n \/** Query whether the pointer is still valid.\n\n Hands off also from the implementation pointer if this\n returns false!\n *\/\n bool is() const { return mxRef.is(); }\n\n \/** Get a pointer to the implementation object\n\n Compatibility method to get an auto_ptr-compatible\n interface\n *\/\n ImplementationType* get() { return mpImpl; }\n const ImplementationType* get() const { return mpImpl; }\n\n \/** Release all references\n\n Compatibility method to get an auto_ptr-compatible\n interface\n *\/\n void reset() { dispose(); }\n\n \/** Release all references\n\n This method releases the UNO interface reference, and\n clears the C++ pointer to NULL.\n *\/\n void dispose() { mxRef = NULL; mpImpl=NULL; }\n\n ImplementationType* operator->() { return mpImpl; }\n const ImplementationType* operator->() const { return mpImpl; }\n\n ImplementationType& operator*() { return *mpImpl; }\n const ImplementationType& operator*() const { return *mpImpl; }\n\n \/\/\/ Access to the underlying UNO reference, without extra querying\n ::com::sun::star::uno::Reference< UnoInterfaceType > getRef() { return mxRef; }\n\n \/\/\/ Access to the underlying UNO reference, without extra querying\n const ::com::sun::star::uno::Reference< UnoInterfaceType >& getRef() const { return mxRef; }\n\n \/\/ default destructor, copy constructor and assignment will do\n \/\/ ~ImplementationReference();\n \/\/ ImplementationReference( const ImplementationReference& );\n \/\/ ImplementationReference& operator= ( const ImplementationReference& );\n\n \/** Comparison operator\n\n Object identity is defined to be identity of the\n implementation pointers. This is in general invalid when\n comparing pointers to UNO objects (ambiguous class\n hierarchies, optimizations in the bridges, etc.), but okay\n for raw C++ pointers (which is what's compared herein).\n *\/\n bool operator==( const ImplementationReference& rhs ) const\n {\n return mpImpl == rhs.mpImpl;\n }\n\n \/** less-than operator\n\n Object order is defined to be the ordering of the\n implementation pointers. This is in general invalid when\n comparing pointers to UNO objects (ambiguous class\n hierarchies, optimizations in the bridges, etc.), but okay\n for raw C++ pointers (which is what's used herein).\n\n This ordering complies with STL's strict weak ordering\n concept.\n *\/\n bool operator<( const ImplementationReference& rhs ) const\n {\n return mpImpl < rhs.mpImpl;\n }\n\n private:\n\n \/\/ the interface, hard reference to prevent object from vanishing\n ::com::sun::star::uno::Reference< UnoInterfaceType > mxRef;\n\n \/\/ the c++ object, for our internal stuff\n ImplementationType* mpImpl;\n\n };\n\n}\n\n#endif \/\/ _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.84); FILE MERGED 2005\/09\/05 15:23:42 rt 1.3.84.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: implementationreference.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:31:51 $\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 _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX\n#define _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_\n#include <com\/sun\/star\/uno\/XInterface.hpp>\n#endif\n\nnamespace comphelper\n{\n\n \/** Holds a uno::Reference alongside a C++ implementation pointer\n\n This template is useful to accomplish the following task: the\n client needs an implementation pointer to an object providing\n UNO interfaces. It is unsafe to simply store a C++ pointer,\n because of the automatic UNO lifetime control. It is\n inconvenient to always cast the UNO interface to the C++\n implementation, and what's more, it's mostly unclear to the\n casual code reader.\n\n Thus, this template nicely encapsulate the stated intention,\n by holding a uno::Reference internally, and providing simple\n C++ pointer semantics to the outside. As a differentiator to\n ::rtl::Reference, this template features a getRef() method,\n giving you friction-less access to the internal UNO interface,\n without extra querying.\n\n By the way, the pointer semantic of this template include\n transitive constness. That means, if this template's instance\n is const (e.g. because it is a member of a class which is\n accessed in a const method), the pointer returned is also\n const.\n\n As this template is geared towards fast, internal pointer\n access, validity of the UNO reference is _not_ checked for\n every pointer access. The client of this template is\n responsible to check that, whereever necessary, via the is()\n method.\n\n @tpl CppType\n The C++ type this class should mimick a pointer to (not the\n pointer type itself!).\n\n @tpl UnoType\n The UNO interface type of the object (a uno::Reference to this\n type is held internally).\n\n @tpl XIfType\n An unambiguous derivative of UnoType. This is defaulted to\n the second template parameter (UnoType), which should normally\n just work, since one typically has only single inheritance in\n UNO.<p>\n Alternatively, when using the\n ImplementationReference::createFromQuery() method to create an\n instance, this type can serve a different need: if the\n provided CppType only derives from XInterface (generally\n speaking, derives from a UNO interface above UnoType in the\n class hierarchy), then the default XIfType constitutes a\n possibly invalid downcast to UnoType. Setting XIfType equal to\n CppTypes's most derived UNO interface type then solves this\n problem (which is not as arcane as it seems to be. Just\n imagine you're providing a C++ abstract interface, which must\n provide UNO reference semantics. Naturally, you will derive\n this C++ interface only from XInterface, to reduce the number\n of ambiguous classes. Even more naturally, it is reasonable to\n have UnoType be something different from XInterface, governed\n by the usage of the C++ interface)\n\n @sample ImplementationReference< MyCppType, XMyInterface >\n\n @sample ImplementationReference< MyAbstractCppType, XMyInterface, XInterface >\n for an abstract C++ class\n\n @see ::rtl::Reference\n\n *\/\n template < class CppType,\n class UnoType,\n class XIfType=UnoType > class ImplementationReference\n {\n public:\n\n typedef UnoType UnoInterfaceType;\n typedef CppType ImplementationType;\n typedef XIfType UnambiguousXInterfaceType;\n\n \/** Default-construct an ImplementationReference\n\n Uno reference will be invalid, implementation pointer will\n be NULL.\n *\/\n ImplementationReference() :\n mxRef(),\n mpImpl( NULL )\n {\n }\n\n \/** Create an ImplementationReference from C++ pointer.\n\n This constructor does not perform an explicit\n QueryInterface on the provided implementation object, but\n constructs the UNO reference directly from the given\n pointer. This is the fastest, and most often the best way\n to create an ImplementationReference. If the conversion\n between the implementation object and the required UNO\n interface is ambiguous, provide the third template\n parameter with a type that can be unambiguously upcasted\n to the UNO interface (the second template parameter).\n\n There are cases, however, where performing a\n QueryInterface is the better, albeit slower choice. In\n these cases, createFromQuery() should be used.\n\n @param pImpl\n Pointer to the C++ implementation type\n\n @see createFromQuery()\n *\/\n explicit ImplementationReference( ImplementationType* pImpl ) :\n mxRef( static_cast<UnambiguousXInterfaceType*>(pImpl) ),\n mpImpl( pImpl )\n {\n }\n\n struct CreateFromQuery { };\n \/** Create an ImplementationReference from C++ pointer\n\n @param pImpl\n The pointer to the C++ implementation type, which is\n queried for the template-parameterized UNO type.\n\n @param dummy\n Dummy parameter, to distinguish this contructor from the\n default unary one (which does not perform a\n QueryInterface)\n *\/\n ImplementationReference( ImplementationType* pImpl, CreateFromQuery dummy ) :\n mxRef( static_cast<UnambiguousXInterfaceType*>(pImpl),\n ::com::sun::star::uno::UNO_QUERY ),\n mpImpl( pImpl )\n {\n }\n\n \/** Factory method to create an ImplementationReference from\n C++ pointer.\n\n This is a static version of the constructor which creates\n an instance of an implementation type which is explicitely\n queried for the ImplementationReference's\n template-parameterized UNO type.\n\n @sample\n mpRef = mpRef.createFromQuery( new ImplementationType );\n *\/\n static ImplementationReference createFromQuery( ImplementationType* pImpl )\n {\n return ImplementationReference( pImpl, CreateFromQuery() );\n }\n\n \/** Query whether the pointer is still valid.\n\n Hands off also from the implementation pointer if this\n returns false!\n *\/\n bool is() const { return mxRef.is(); }\n\n \/** Get a pointer to the implementation object\n\n Compatibility method to get an auto_ptr-compatible\n interface\n *\/\n ImplementationType* get() { return mpImpl; }\n const ImplementationType* get() const { return mpImpl; }\n\n \/** Release all references\n\n Compatibility method to get an auto_ptr-compatible\n interface\n *\/\n void reset() { dispose(); }\n\n \/** Release all references\n\n This method releases the UNO interface reference, and\n clears the C++ pointer to NULL.\n *\/\n void dispose() { mxRef = NULL; mpImpl=NULL; }\n\n ImplementationType* operator->() { return mpImpl; }\n const ImplementationType* operator->() const { return mpImpl; }\n\n ImplementationType& operator*() { return *mpImpl; }\n const ImplementationType& operator*() const { return *mpImpl; }\n\n \/\/\/ Access to the underlying UNO reference, without extra querying\n ::com::sun::star::uno::Reference< UnoInterfaceType > getRef() { return mxRef; }\n\n \/\/\/ Access to the underlying UNO reference, without extra querying\n const ::com::sun::star::uno::Reference< UnoInterfaceType >& getRef() const { return mxRef; }\n\n \/\/ default destructor, copy constructor and assignment will do\n \/\/ ~ImplementationReference();\n \/\/ ImplementationReference( const ImplementationReference& );\n \/\/ ImplementationReference& operator= ( const ImplementationReference& );\n\n \/** Comparison operator\n\n Object identity is defined to be identity of the\n implementation pointers. This is in general invalid when\n comparing pointers to UNO objects (ambiguous class\n hierarchies, optimizations in the bridges, etc.), but okay\n for raw C++ pointers (which is what's compared herein).\n *\/\n bool operator==( const ImplementationReference& rhs ) const\n {\n return mpImpl == rhs.mpImpl;\n }\n\n \/** less-than operator\n\n Object order is defined to be the ordering of the\n implementation pointers. This is in general invalid when\n comparing pointers to UNO objects (ambiguous class\n hierarchies, optimizations in the bridges, etc.), but okay\n for raw C++ pointers (which is what's used herein).\n\n This ordering complies with STL's strict weak ordering\n concept.\n *\/\n bool operator<( const ImplementationReference& rhs ) const\n {\n return mpImpl < rhs.mpImpl;\n }\n\n private:\n\n \/\/ the interface, hard reference to prevent object from vanishing\n ::com::sun::star::uno::Reference< UnoInterfaceType > mxRef;\n\n \/\/ the c++ object, for our internal stuff\n ImplementationType* mpImpl;\n\n };\n\n}\n\n#endif \/\/ _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: accessiblekeybindinghelper.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2003-04-24 17:27:32 $\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\/\/ includes --------------------------------------------------------------\n\n#ifndef COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX\n#include <comphelper\/accessiblekeybindinghelper.hxx>\n#endif\n\n\n\/\/..............................................................................\nnamespace comphelper\n{\n\/\/..............................................................................\n\n using namespace ::com::sun::star; \/\/ MT 04\/2003: was ::drafts::com::sun::star - otherwise to many changes\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::accessibility;\n\n \/\/==============================================================================\n \/\/ OAccessibleKeyBindingHelper\n \/\/==============================================================================\n\n OAccessibleKeyBindingHelper::OAccessibleKeyBindingHelper()\n {\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n OAccessibleKeyBindingHelper::OAccessibleKeyBindingHelper( const OAccessibleKeyBindingHelper& rHelper )\n :m_aKeyBindings( rHelper.m_aKeyBindings )\n {\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n OAccessibleKeyBindingHelper::~OAccessibleKeyBindingHelper()\n {\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n void OAccessibleKeyBindingHelper::AddKeyBinding( const Sequence< awt::KeyStroke >& rKeyBinding ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n m_aKeyBindings.push_back( rKeyBinding );\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n void OAccessibleKeyBindingHelper::AddKeyBinding( const awt::KeyStroke& rKeyStroke ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n Sequence< awt::KeyStroke > aSeq(1);\n aSeq[0] = rKeyStroke;\n m_aKeyBindings.push_back( aSeq );\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XAccessibleKeyBinding\n \/\/ -----------------------------------------------------------------------------\n\n sal_Int32 OAccessibleKeyBindingHelper::getAccessibleKeyBindingCount() throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return m_aKeyBindings.size();\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n Sequence< awt::KeyStroke > OAccessibleKeyBindingHelper::getAccessibleKeyBinding( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n if ( nIndex < 0 || nIndex >= (sal_Int32)m_aKeyBindings.size() )\n throw IndexOutOfBoundsException();\n\n return m_aKeyBindings[nIndex];\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n\/\/..............................................................................\n} \/\/ namespace comphelper\n\/\/..............................................................................\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.264); FILE MERGED 2005\/09\/05 15:23:58 rt 1.2.264.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accessiblekeybindinghelper.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:47:20 $\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\/\/ includes --------------------------------------------------------------\n\n#ifndef COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX\n#include <comphelper\/accessiblekeybindinghelper.hxx>\n#endif\n\n\n\/\/..............................................................................\nnamespace comphelper\n{\n\/\/..............................................................................\n\n using namespace ::com::sun::star; \/\/ MT 04\/2003: was ::drafts::com::sun::star - otherwise to many changes\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::accessibility;\n\n \/\/==============================================================================\n \/\/ OAccessibleKeyBindingHelper\n \/\/==============================================================================\n\n OAccessibleKeyBindingHelper::OAccessibleKeyBindingHelper()\n {\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n OAccessibleKeyBindingHelper::OAccessibleKeyBindingHelper( const OAccessibleKeyBindingHelper& rHelper )\n :m_aKeyBindings( rHelper.m_aKeyBindings )\n {\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n OAccessibleKeyBindingHelper::~OAccessibleKeyBindingHelper()\n {\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n void OAccessibleKeyBindingHelper::AddKeyBinding( const Sequence< awt::KeyStroke >& rKeyBinding ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n m_aKeyBindings.push_back( rKeyBinding );\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n void OAccessibleKeyBindingHelper::AddKeyBinding( const awt::KeyStroke& rKeyStroke ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n Sequence< awt::KeyStroke > aSeq(1);\n aSeq[0] = rKeyStroke;\n m_aKeyBindings.push_back( aSeq );\n }\n\n \/\/ -----------------------------------------------------------------------------\n \/\/ XAccessibleKeyBinding\n \/\/ -----------------------------------------------------------------------------\n\n sal_Int32 OAccessibleKeyBindingHelper::getAccessibleKeyBindingCount() throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return m_aKeyBindings.size();\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n Sequence< awt::KeyStroke > OAccessibleKeyBindingHelper::getAccessibleKeyBinding( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n if ( nIndex < 0 || nIndex >= (sal_Int32)m_aKeyBindings.size() )\n throw IndexOutOfBoundsException();\n\n return m_aKeyBindings[nIndex];\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n\/\/..............................................................................\n} \/\/ namespace comphelper\n\/\/..............................................................................\n<|endoftext|>"} {"text":"<commit_before>\/* The MIT License\n *\n * Copyright (c) 2010 OTClient, https:\/\/github.com\/edubart\/otclient\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\n\n#include <prerequisites.h>\n#include <core\/resources.h>\n#include <core\/platform.h>\n\n#include <physfs.h>\n\nResources g_resources;\n\nvoid Resources::init(const char *argv0)\n{\n PHYSFS_init(argv0);\n\n \/\/ try to find data directory\n std::list<std::string> searchPaths;\n std::string dir;\n std::string baseDir = PHYSFS_getBaseDir();\n\n std::list<std::string> possibleDirs;\n possibleDirs.push_back(\"data\");\n possibleDirs.push_back(baseDir + \"data\");\n possibleDirs.push_back(baseDir + \"..\/data\");\n possibleDirs.push_back(baseDir + \"..\/share\/data\");\n possibleDirs.push_back(\"\");\n\n foreach(dir, possibleDirs)\n if(g_resources.addToSearchPath(dir))\n break;\n\n \/\/ setup write directory\n dir = Platform::getAppUserDir();\n if(g_resources.setWriteDir(dir))\n g_resources.addToSearchPath(dir);\n else\n logError(\"ERROR: could not setup write directory\");\n}\n\nvoid Resources::terminate()\n{\n PHYSFS_deinit();\n}\n\nbool Resources::setWriteDir(const std::string& path)\n{\n if(!PHYSFS_setWriteDir(path.c_str()))\n return false;\n return true;\n}\n\nbool Resources::addToSearchPath(const std::string& path, bool insertInFront \/*= true*\/)\n{\n if(!PHYSFS_addToSearchPath(path.c_str(), insertInFront ? 0 : 1))\n return false;\n return true;\n}\n\nvoid Resources::addPackagesToSearchPath(const std::string &packagesDirectory, const std::string &packageExtension, bool append)\n{\n auto files = listDirectoryFiles(resolvePath(packagesDirectory));\n foreach(const std::string& file, files) {\n if(boost::ends_with(file, packageExtension))\n addToSearchPath(packagesDirectory + \"\/\" + file, !append);\n }\n}\n\nbool Resources::fileExists(const std::string& fileName)\n{\n return (PHYSFS_exists(resolvePath(fileName).c_str()) && !PHYSFS_isDirectory(resolvePath(fileName).c_str()));\n}\n\nbool Resources::directoryExists(const std::string& directoryName)\n{\n return (PHYSFS_exists(resolvePath(directoryName).c_str()) && PHYSFS_isDirectory(resolvePath(directoryName).c_str()));\n}\n\nbool Resources::loadFile(const std::string& fileName, std::iostream& out)\n{\n out.clear(std::ios::goodbit);\n PHYSFS_file *file = PHYSFS_openRead(resolvePath(fileName).c_str());\n if(!file) {\n flogError(\"ERROR: Failed to load file \\\"%s\\\": %s\", fileName.c_str() % PHYSFS_getLastError());\n out.clear(std::ios::failbit);\n return false;\n } else {\n int fileSize = PHYSFS_fileLength(file);\n if(fileSize > 0) {\n char *buffer = new char[fileSize];\n PHYSFS_read(file, (void*)buffer, 1, fileSize);\n out.write(buffer, fileSize);\n delete buffer;\n } else\n out.clear(std::ios::eofbit);\n PHYSFS_close(file);\n out.seekg(0, std::ios::beg);\n return true;\n }\n}\n\nbool Resources::saveFile(const std::string &fileName, const uchar *data, uint size)\n{\n PHYSFS_file *file = PHYSFS_openWrite(resolvePath(fileName).c_str());\n if(!file) {\n flogError(\"ERROR: Failed to save file \\\"%s\\\": %s\", fileName.c_str() % PHYSFS_getLastError());\n return false;\n }\n\n PHYSFS_write(file, (void*)data, size, 1);\n PHYSFS_close(file);\n return true;\n}\n\nbool Resources::saveFile(const std::string &fileName, std::istream& in)\n{\n std::streampos oldPos = in.tellg();\n in.seekg(0, std::ios::end);\n std::streampos size = in.tellg();\n in.seekg(0, std::ios::beg);\n char *buffer = new char[size];\n in.read(buffer, size);\n bool ret = saveFile(fileName, (const uchar*)buffer, size);\n delete[] buffer;\n in.seekg(oldPos, std::ios::beg);\n return ret;\n}\n\nbool Resources::deleteFile(const std::string& fileName)\n{\n return PHYSFS_delete(resolvePath(fileName).c_str()) != 0;\n}\n\nstd::list<std::string> Resources::listDirectoryFiles(const std::string& directoryPath)\n{\n std::list<std::string> files;\n char **rc = PHYSFS_enumerateFiles(resolvePath(directoryPath).c_str());\n\n for(char **i = rc; *i != NULL; i++)\n files.push_back(*i);\n\n PHYSFS_freeList(rc);\n return files;\n}\n\n\nvoid Resources::pushCurrentPath(const std::string ¤tPath)\n{\n m_currentPaths.push(currentPath);\n}\n\nvoid Resources::popCurrentPath()\n{\n m_currentPaths.pop();\n}\n\nstd::string Resources::resolvePath(const std::string& path)\n{\n std::string fullPath;\n if(boost::starts_with(path, \"\/\"))\n fullPath = path.substr(1);\n else {\n if(m_currentPaths.size() > 0) {\n std::string currentPath = m_currentPaths.top();\n if(currentPath.length() > 0)\n fullPath += currentPath + \"\/\";\n }\n fullPath += path;\n }\n return fullPath;\n}\n\n<commit_msg>rework on resources system<commit_after>\/* The MIT License\n *\n * Copyright (c) 2010 OTClient, https:\/\/github.com\/edubart\/otclient\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\n\n#include <prerequisites.h>\n#include <core\/resources.h>\n#include <core\/platform.h>\n\n#include <physfs.h>\n\nResources g_resources;\n\nvoid Resources::init(const char *argv0)\n{\n PHYSFS_init(argv0);\n\n \/\/ try to find data directory\n std::list<std::string> searchPaths;\n std::string dir;\n std::string baseDir = PHYSFS_getBaseDir();\n\n std::list<std::string> possibleDirs;\n possibleDirs.push_back(\"data\");\n possibleDirs.push_back(baseDir + \"data\");\n possibleDirs.push_back(baseDir + \"..\/data\");\n possibleDirs.push_back(baseDir + \"..\/share\/otclient\/data\");\n possibleDirs.push_back(\"\");\n\n bool found = false;\n foreach(dir, possibleDirs) {\n if(g_resources.addToSearchPath(dir)) {\n flogInfo(\"Using data directory: %s\", dir.c_str());\n found = true;\n break;\n }\n }\n if(!found)\n logFatal(\"ERROR: could not find data directory\");\n\n \/\/ setup write directory\n dir = Platform::getAppUserDir();\n if(g_resources.setWriteDir(dir))\n g_resources.addToSearchPath(dir);\n else\n logError(\"ERROR: could not setup write directory\");\n}\n\nvoid Resources::terminate()\n{\n PHYSFS_deinit();\n}\n\nbool Resources::setWriteDir(const std::string& path)\n{\n if(!PHYSFS_setWriteDir(path.c_str()))\n return false;\n return true;\n}\n\nbool Resources::addToSearchPath(const std::string& path, bool insertInFront \/*= true*\/)\n{\n if(!PHYSFS_addToSearchPath(path.c_str(), insertInFront ? 0 : 1))\n return false;\n return true;\n}\n\nvoid Resources::addPackagesToSearchPath(const std::string &packagesDirectory, const std::string &packageExtension, bool append)\n{\n auto files = listDirectoryFiles(resolvePath(packagesDirectory));\n foreach(const std::string& file, files) {\n if(boost::ends_with(file, packageExtension))\n addToSearchPath(packagesDirectory + \"\/\" + file, !append);\n }\n}\n\nbool Resources::fileExists(const std::string& fileName)\n{\n return (PHYSFS_exists(resolvePath(fileName).c_str()) && !PHYSFS_isDirectory(resolvePath(fileName).c_str()));\n}\n\nbool Resources::directoryExists(const std::string& directoryName)\n{\n return (PHYSFS_exists(resolvePath(directoryName).c_str()) && PHYSFS_isDirectory(resolvePath(directoryName).c_str()));\n}\n\nbool Resources::loadFile(const std::string& fileName, std::iostream& out)\n{\n out.clear(std::ios::goodbit);\n PHYSFS_file *file = PHYSFS_openRead(resolvePath(fileName).c_str());\n if(!file) {\n flogError(\"ERROR: Failed to load file \\\"%s\\\": %s\", fileName.c_str() % PHYSFS_getLastError());\n out.clear(std::ios::failbit);\n return false;\n } else {\n int fileSize = PHYSFS_fileLength(file);\n if(fileSize > 0) {\n char *buffer = new char[fileSize];\n PHYSFS_read(file, (void*)buffer, 1, fileSize);\n out.write(buffer, fileSize);\n delete buffer;\n } else\n out.clear(std::ios::eofbit);\n PHYSFS_close(file);\n out.seekg(0, std::ios::beg);\n return true;\n }\n}\n\nbool Resources::saveFile(const std::string &fileName, const uchar *data, uint size)\n{\n PHYSFS_file *file = PHYSFS_openWrite(resolvePath(fileName).c_str());\n if(!file) {\n flogError(\"ERROR: Failed to save file \\\"%s\\\": %s\", fileName.c_str() % PHYSFS_getLastError());\n return false;\n }\n\n PHYSFS_write(file, (void*)data, size, 1);\n PHYSFS_close(file);\n return true;\n}\n\nbool Resources::saveFile(const std::string &fileName, std::istream& in)\n{\n std::streampos oldPos = in.tellg();\n in.seekg(0, std::ios::end);\n std::streampos size = in.tellg();\n in.seekg(0, std::ios::beg);\n char *buffer = new char[size];\n in.read(buffer, size);\n bool ret = saveFile(fileName, (const uchar*)buffer, size);\n delete[] buffer;\n in.seekg(oldPos, std::ios::beg);\n return ret;\n}\n\nbool Resources::deleteFile(const std::string& fileName)\n{\n return PHYSFS_delete(resolvePath(fileName).c_str()) != 0;\n}\n\nstd::list<std::string> Resources::listDirectoryFiles(const std::string& directoryPath)\n{\n std::list<std::string> files;\n char **rc = PHYSFS_enumerateFiles(resolvePath(directoryPath).c_str());\n\n for(char **i = rc; *i != NULL; i++)\n files.push_back(*i);\n\n PHYSFS_freeList(rc);\n return files;\n}\n\n\nvoid Resources::pushCurrentPath(const std::string ¤tPath)\n{\n m_currentPaths.push(currentPath);\n}\n\nvoid Resources::popCurrentPath()\n{\n m_currentPaths.pop();\n}\n\nstd::string Resources::resolvePath(const std::string& path)\n{\n std::string fullPath;\n if(boost::starts_with(path, \"\/\"))\n fullPath = path.substr(1);\n else {\n if(m_currentPaths.size() > 0) {\n std::string currentPath = m_currentPaths.top();\n if(currentPath.length() > 0)\n fullPath += currentPath + \"\/\";\n }\n fullPath += path;\n }\n return fullPath;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"IMPCacher.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Metadata.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n\n#include \"LLVMCompat.h\"\n\nGNUstep::IMPCacher::IMPCacher(LLVMContext &C, Pass *owner) : Context(C),\n Owner(owner) {\n\n PtrTy = Type::getInt8PtrTy(Context);\n IntTy = (sizeof(int) == 4 ) ? Type::getInt32Ty(C) : Type::getInt64Ty(C);\n IdTy = PointerType::getUnqual(PtrTy);\n Value *AlreadyCachedFlagValue = MDString::get(C, \"IMPCached\");\n AlreadyCachedFlag = CreateMDNode(C, AlreadyCachedFlagValue);\n IMPCacheFlagKind = Context.getMDKindID(\"IMPCache\");\n}\n\nvoid GNUstep::IMPCacher::CacheLookup(Instruction *lookup, Value *slot, Value\n *version, bool isSuperMessage) {\n\n \/\/ If this IMP is already cached, don't cache it again.\n if (lookup->getMetadata(IMPCacheFlagKind)) { return; }\n\n lookup->setMetadata(IMPCacheFlagKind, AlreadyCachedFlag);\n\n BasicBlock *beforeLookupBB = lookup->getParent();\n BasicBlock *lookupBB = SplitBlock(beforeLookupBB, lookup, Owner);\n BasicBlock::iterator iter = lookup;\n iter++;\n BasicBlock *afterLookupBB = SplitBlock(iter->getParent(), iter, Owner);\n\n removeTerminator(beforeLookupBB);\n\n IRBuilder<> B = IRBuilder<>(beforeLookupBB);\n \/\/ Load the slot and check that neither it nor the version is 0.\n Value *slotValue = B.CreateLoad(slot);\n Value *versionValue = B.CreateLoad(version);\n Value *receiverPtr = lookup->getOperand(0);\n Value *receiver = receiverPtr;\n if (!isSuperMessage) {\n receiver = B.CreateLoad(receiverPtr);\n }\n\n Value *isCacheEmpty = \n B.CreateICmpEQ(versionValue, Constant::getNullValue(IntTy));\n Value *receiverNotNil =\n B.CreateICmpNE(receiver, Constant::getNullValue(receiver->getType()));\n isCacheEmpty = B.CreateAnd(isCacheEmpty, receiverNotNil);\n \n BasicBlock *cacheLookupBB = BasicBlock::Create(Context, \"cache_check\",\n lookupBB->getParent());\n\n B.CreateCondBr(isCacheEmpty, lookupBB, cacheLookupBB);\n\n \/\/ Check the cache node is current\n B.SetInsertPoint(cacheLookupBB);\n Value *slotVersion = B.CreateStructGEP(slotValue, 3);\n \/\/ Note: Volatile load because the slot version might have changed in\n \/\/ another thread.\n slotVersion = B.CreateLoad(slotVersion, true, \"slot_version\");\n Value *slotCachedFor = B.CreateStructGEP(slotValue, 1);\n slotCachedFor = B.CreateLoad(slotCachedFor, true, \"slot_owner\");\n Value *cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));\n Value *isVersionCorrect = B.CreateICmpEQ(slotVersion, versionValue);\n Value *isOwnerCorrect = B.CreateICmpEQ(slotCachedFor, cls);\n Value *isSlotValid = B.CreateAnd(isVersionCorrect, isOwnerCorrect);\n \/\/ If this slot is still valid, skip the lookup.\n B.CreateCondBr(isSlotValid, afterLookupBB, lookupBB);\n\n \/\/ Replace the looked up slot with the loaded one\n B.SetInsertPoint(afterLookupBB, afterLookupBB->begin());\n \/\/ Not volatile, so a redundant load elimination pass can do some phi\n \/\/ magic with this later.\n lookup->replaceAllUsesWith(B.CreateLoad(slot));\n\n \/\/ Perform the real lookup and cache the result\n removeTerminator(lookupBB);\n B.SetInsertPoint(lookupBB);\n Value * newReceiver = receiver;\n if (!isSuperMessage) {\n newReceiver = B.CreateLoad(receiverPtr);\n }\n BasicBlock *storeCacheBB = BasicBlock::Create(Context, \"cache_store\",\n lookupBB->getParent());\n\n \/\/ Don't store the cached lookup if we are doing forwarding tricks.\n B.CreateBr(storeCacheBB);\n \/*\n B.CreateCondBr(B.CreateICmpEQ(receiver, newReceiver), storeCacheBB,\n afterLookupBB);\n *\/\n B.SetInsertPoint(storeCacheBB);\n\n \/\/ Store it even if the version is 0, because we always check that the\n \/\/ version is not 0 at the start and an occasional redundant store is\n \/\/ probably better than a branch every time.\n B.CreateStore(lookup, slot);\n \/\/B.CreateStore(B.CreateLoad(B.CreateStructGEP(lookup, 3)), version);\n cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));\n B.CreateStore(cls, B.CreateStructGEP(lookup, 1));\n B.CreateBr(afterLookupBB);\n}\n\n\nvoid GNUstep::IMPCacher::SpeculativelyInline(Instruction *call, Function\n *function) {\n BasicBlock *beforeCallBB = call->getParent();\n BasicBlock *callBB = SplitBlock(beforeCallBB, call, Owner);\n BasicBlock *inlineBB = BasicBlock::Create(Context, \"inline\",\n callBB->getParent());\n\n\n BasicBlock::iterator iter = call;\n iter++;\n\n BasicBlock *afterCallBB = SplitBlock(iter->getParent(), iter, Owner);\n\n removeTerminator(beforeCallBB);\n\n \/\/ Put a branch before the call, testing whether the callee really is the\n \/\/ function\n IRBuilder<> B = IRBuilder<>(beforeCallBB);\n Value *callee = isa<CallInst>(call) ? cast<CallInst>(call)->getCalledValue()\n : cast<InvokeInst>(call)->getCalledValue();\n\n const FunctionType *FTy = function->getFunctionType();\n const FunctionType *calleeTy = cast<FunctionType>(\n cast<PointerType>(callee->getType())->getElementType());\n if (calleeTy != FTy) {\n callee = B.CreateBitCast(callee, function->getType());\n }\n\n Value *isInlineValid = B.CreateICmpEQ(callee, function);\n B.CreateCondBr(isInlineValid, inlineBB, callBB);\n\n \/\/ In the inline BB, add a copy of the call, but this time calling the real\n \/\/ version.\n Instruction *inlineCall = call->clone();\n Value *inlineResult= inlineCall;\n inlineBB->getInstList().push_back(inlineCall);\n\n B.SetInsertPoint(inlineBB);\n\n if (calleeTy != FTy) {\n for (unsigned i=0 ; i<FTy->getNumParams() ; i++) {\n const Type *callType = calleeTy->getParamType(i);\n const Type *argType = FTy->getParamType(i);\n if (callType != argType) {\n inlineCall->setOperand(i, new\n BitCastInst(inlineCall->getOperand(i), argType, \"\", inlineCall));\n }\n }\n if (FTy->getReturnType() != calleeTy->getReturnType()) {\n if (FTy->getReturnType() == Type::getVoidTy(Context)) {\n inlineResult = Constant::getNullValue(calleeTy->getReturnType());\n } else {\n inlineResult = \n new BitCastInst(inlineCall, calleeTy->getReturnType(), \"\", inlineBB);\n }\n }\n }\n\n B.CreateBr(afterCallBB);\n\n \/\/ Unify the return values\n if (call->getType() != Type::getVoidTy(Context)) {\n PHINode *phi = CreatePHI(call->getType(), 2, \"\", afterCallBB->begin());\n call->replaceAllUsesWith(phi);\n phi->addIncoming(call, callBB);\n phi->addIncoming(inlineResult, inlineBB);\n }\n\n \/\/ Really do the real inlining\n InlineFunctionInfo IFI(0, 0);\n if (CallInst *c = dyn_cast<CallInst>(inlineCall)) {\n c->setCalledFunction(function);\n InlineFunction(c, IFI);\n } else if (InvokeInst *c = dyn_cast<InvokeInst>(inlineCall)) {\n c->setCalledFunction(function);\n InlineFunction(c, IFI);\n }\n}\n\n\/\/ Cleanly removes a terminator instruction.\nvoid GNUstep::removeTerminator(BasicBlock *BB) {\n TerminatorInst *BBTerm = BB->getTerminator();\n\n \/\/ Remove the BB as a predecessor from all of successors\n for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {\n BBTerm->getSuccessor(i)->removePredecessor(BB);\n }\n\n BBTerm->replaceAllUsesWith(UndefValue::get(BBTerm->getType()));\n \/\/ Remove the terminator instruction itself.\n BBTerm->eraseFromParent();\n}\n<commit_msg>Ooops. Accidentally left the bit that actually did the optimisation commented out.<commit_after>#include \"IMPCacher.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Metadata.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n\n#include \"LLVMCompat.h\"\n\nGNUstep::IMPCacher::IMPCacher(LLVMContext &C, Pass *owner) : Context(C),\n Owner(owner) {\n\n PtrTy = Type::getInt8PtrTy(Context);\n IntTy = (sizeof(int) == 4 ) ? Type::getInt32Ty(C) : Type::getInt64Ty(C);\n IdTy = PointerType::getUnqual(PtrTy);\n Value *AlreadyCachedFlagValue = MDString::get(C, \"IMPCached\");\n AlreadyCachedFlag = CreateMDNode(C, AlreadyCachedFlagValue);\n IMPCacheFlagKind = Context.getMDKindID(\"IMPCache\");\n}\n\nvoid GNUstep::IMPCacher::CacheLookup(Instruction *lookup, Value *slot, Value\n *version, bool isSuperMessage) {\n\n \/\/ If this IMP is already cached, don't cache it again.\n if (lookup->getMetadata(IMPCacheFlagKind)) { return; }\n\n lookup->setMetadata(IMPCacheFlagKind, AlreadyCachedFlag);\n\n BasicBlock *beforeLookupBB = lookup->getParent();\n BasicBlock *lookupBB = SplitBlock(beforeLookupBB, lookup, Owner);\n BasicBlock::iterator iter = lookup;\n iter++;\n BasicBlock *afterLookupBB = SplitBlock(iter->getParent(), iter, Owner);\n\n removeTerminator(beforeLookupBB);\n\n IRBuilder<> B = IRBuilder<>(beforeLookupBB);\n \/\/ Load the slot and check that neither it nor the version is 0.\n Value *slotValue = B.CreateLoad(slot);\n Value *versionValue = B.CreateLoad(version);\n Value *receiverPtr = lookup->getOperand(0);\n Value *receiver = receiverPtr;\n if (!isSuperMessage) {\n receiver = B.CreateLoad(receiverPtr);\n }\n\n Value *isCacheEmpty = \n B.CreateICmpEQ(versionValue, Constant::getNullValue(IntTy));\n Value *receiverNotNil =\n B.CreateICmpNE(receiver, Constant::getNullValue(receiver->getType()));\n isCacheEmpty = B.CreateAnd(isCacheEmpty, receiverNotNil);\n \n BasicBlock *cacheLookupBB = BasicBlock::Create(Context, \"cache_check\",\n lookupBB->getParent());\n\n B.CreateCondBr(isCacheEmpty, lookupBB, cacheLookupBB);\n\n \/\/ Check the cache node is current\n B.SetInsertPoint(cacheLookupBB);\n Value *slotVersion = B.CreateStructGEP(slotValue, 3);\n \/\/ Note: Volatile load because the slot version might have changed in\n \/\/ another thread.\n slotVersion = B.CreateLoad(slotVersion, true, \"slot_version\");\n Value *slotCachedFor = B.CreateStructGEP(slotValue, 1);\n slotCachedFor = B.CreateLoad(slotCachedFor, true, \"slot_owner\");\n Value *cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));\n Value *isVersionCorrect = B.CreateICmpEQ(slotVersion, versionValue);\n Value *isOwnerCorrect = B.CreateICmpEQ(slotCachedFor, cls);\n Value *isSlotValid = B.CreateAnd(isVersionCorrect, isOwnerCorrect);\n \/\/ If this slot is still valid, skip the lookup.\n B.CreateCondBr(isSlotValid, afterLookupBB, lookupBB);\n\n \/\/ Replace the looked up slot with the loaded one\n B.SetInsertPoint(afterLookupBB, afterLookupBB->begin());\n \/\/ Not volatile, so a redundant load elimination pass can do some phi\n \/\/ magic with this later.\n lookup->replaceAllUsesWith(B.CreateLoad(slot));\n\n \/\/ Perform the real lookup and cache the result\n removeTerminator(lookupBB);\n B.SetInsertPoint(lookupBB);\n Value * newReceiver = receiver;\n if (!isSuperMessage) {\n newReceiver = B.CreateLoad(receiverPtr);\n }\n BasicBlock *storeCacheBB = BasicBlock::Create(Context, \"cache_store\",\n lookupBB->getParent());\n\n \/\/ Don't store the cached lookup if we are doing forwarding tricks.\n B.CreateCondBr(B.CreateICmpEQ(receiver, newReceiver), storeCacheBB,\n afterLookupBB);\n B.SetInsertPoint(storeCacheBB);\n\n \/\/ Store it even if the version is 0, because we always check that the\n \/\/ version is not 0 at the start and an occasional redundant store is\n \/\/ probably better than a branch every time.\n B.CreateStore(lookup, slot);\n B.CreateStore(B.CreateLoad(B.CreateStructGEP(lookup, 3)), version);\n cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));\n B.CreateStore(cls, B.CreateStructGEP(lookup, 1));\n B.CreateBr(afterLookupBB);\n}\n\n\nvoid GNUstep::IMPCacher::SpeculativelyInline(Instruction *call, Function\n *function) {\n BasicBlock *beforeCallBB = call->getParent();\n BasicBlock *callBB = SplitBlock(beforeCallBB, call, Owner);\n BasicBlock *inlineBB = BasicBlock::Create(Context, \"inline\",\n callBB->getParent());\n\n\n BasicBlock::iterator iter = call;\n iter++;\n\n BasicBlock *afterCallBB = SplitBlock(iter->getParent(), iter, Owner);\n\n removeTerminator(beforeCallBB);\n\n \/\/ Put a branch before the call, testing whether the callee really is the\n \/\/ function\n IRBuilder<> B = IRBuilder<>(beforeCallBB);\n Value *callee = isa<CallInst>(call) ? cast<CallInst>(call)->getCalledValue()\n : cast<InvokeInst>(call)->getCalledValue();\n\n const FunctionType *FTy = function->getFunctionType();\n const FunctionType *calleeTy = cast<FunctionType>(\n cast<PointerType>(callee->getType())->getElementType());\n if (calleeTy != FTy) {\n callee = B.CreateBitCast(callee, function->getType());\n }\n\n Value *isInlineValid = B.CreateICmpEQ(callee, function);\n B.CreateCondBr(isInlineValid, inlineBB, callBB);\n\n \/\/ In the inline BB, add a copy of the call, but this time calling the real\n \/\/ version.\n Instruction *inlineCall = call->clone();\n Value *inlineResult= inlineCall;\n inlineBB->getInstList().push_back(inlineCall);\n\n B.SetInsertPoint(inlineBB);\n\n if (calleeTy != FTy) {\n for (unsigned i=0 ; i<FTy->getNumParams() ; i++) {\n const Type *callType = calleeTy->getParamType(i);\n const Type *argType = FTy->getParamType(i);\n if (callType != argType) {\n inlineCall->setOperand(i, new\n BitCastInst(inlineCall->getOperand(i), argType, \"\", inlineCall));\n }\n }\n if (FTy->getReturnType() != calleeTy->getReturnType()) {\n if (FTy->getReturnType() == Type::getVoidTy(Context)) {\n inlineResult = Constant::getNullValue(calleeTy->getReturnType());\n } else {\n inlineResult = \n new BitCastInst(inlineCall, calleeTy->getReturnType(), \"\", inlineBB);\n }\n }\n }\n\n B.CreateBr(afterCallBB);\n\n \/\/ Unify the return values\n if (call->getType() != Type::getVoidTy(Context)) {\n PHINode *phi = CreatePHI(call->getType(), 2, \"\", afterCallBB->begin());\n call->replaceAllUsesWith(phi);\n phi->addIncoming(call, callBB);\n phi->addIncoming(inlineResult, inlineBB);\n }\n\n \/\/ Really do the real inlining\n InlineFunctionInfo IFI(0, 0);\n if (CallInst *c = dyn_cast<CallInst>(inlineCall)) {\n c->setCalledFunction(function);\n InlineFunction(c, IFI);\n } else if (InvokeInst *c = dyn_cast<InvokeInst>(inlineCall)) {\n c->setCalledFunction(function);\n InlineFunction(c, IFI);\n }\n}\n\n\/\/ Cleanly removes a terminator instruction.\nvoid GNUstep::removeTerminator(BasicBlock *BB) {\n TerminatorInst *BBTerm = BB->getTerminator();\n\n \/\/ Remove the BB as a predecessor from all of successors\n for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {\n BBTerm->getSuccessor(i)->removePredecessor(BB);\n }\n\n BBTerm->replaceAllUsesWith(UndefValue::get(BBTerm->getType()));\n \/\/ Remove the terminator instruction itself.\n BBTerm->eraseFromParent();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2006-2008 The FLWOR 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#include \"functions\/sequences.h\"\n#include \"functions\/sequences_impl.h\"\n\n#include \"runtime\/sequences\/sequences.h\"\n#include \"runtime\/sequences\/SequencesImpl.h\"\n#include \"system\/globalenv.h\"\n\n#include \"compiler\/expression\/expr.h\"\n\n#include \"compiler\/semantic_annotations\/annotation_keys.h\"\n#include \"compiler\/semantic_annotations\/tsv_annotation.h\"\n\n#include \"types\/typeops.h\"\n\nnamespace zorba {\n\nxqtref_t\nop_concatenate::return_type(const std::vector<xqtref_t>& arg_types) const \n{\n int sz = arg_types.size ();\n if (sz == 0)\n return GENV_TYPESYSTEM.EMPTY_TYPE;\n else {\n xqtref_t t = arg_types [0];\n TypeConstants::quantifier_t q = TypeConstants::QUANT_STAR;\n for (int i = 1; i < sz; i++) {\n t = TypeOps::union_type (*t, *arg_types [i]);\n TypeConstants::quantifier_t pq = TypeOps::quantifier (*t);\n if (pq == TypeConstants::QUANT_ONE || pq == TypeConstants::QUANT_PLUS)\n q = TypeConstants::QUANT_PLUS;\n }\n return GENV_TYPESYSTEM.create_type_x_quant (*t, q);\n }\n}\n\nvoid\nop_concatenate::compute_annotation (\n AnnotationHolder *parent,\n std::vector<AnnotationHolder *> &kids,\n Annotations::Key k) const \n{\n switch (k) {\n case Annotations::IGNORES_SORTED_NODES:\n case Annotations::IGNORES_DUP_NODES:\n for (std::vector<AnnotationHolder *>::iterator i = kids.begin (); i < kids.end (); i++)\n TSVAnnotationValue::update_annotation ((*i), k, parent->get_annotation (k));\n break;\n default: break;\n }\n}\n\nfunction* fn_sum::specialize(\n static_context* sctx,\n const std::vector<xqtref_t>& argTypes) const\n{\n RootTypeManager& rtm = GENV_TYPESYSTEM;\n\n xqtref_t argType = argTypes[0];\n\n if (TypeOps::is_subtype(*argType, *rtm.UNTYPED_ATOMIC_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_double\", get_arity());\n }\n else if (TypeOps::is_subtype(*argType, *rtm.DOUBLE_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_double\", get_arity());\n }\n else if (TypeOps::is_subtype(*argType, *rtm.FLOAT_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_foat\", get_arity());\n }\n else if (TypeOps::is_subtype(*argType, *rtm.INTEGER_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_integer\", get_arity());\n }\n else if (TypeOps::is_subtype(*argType, *rtm.DECIMAL_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_decimal\", get_arity());\n }\n else\n {\n return NULL;\n }\n}\n\nxqtref_t fn_exactly_one_noraise::return_type(\n const std::vector<xqtref_t>& arg_types) const\n{\n if (theRaiseError)\n return TypeOps::prime_type(*arg_types[0]);\n else\n return function::return_type(arg_types);\n}\n\n\nPlanIter_t\nfn_exactly_one_noraise::codegen(CompilerCB* aCb,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& aAnn) const\n{\n return new FnExactlyOneIterator(aSctx,\n aLoc,\n aArgs,\n theRaiseError,\n testFlag(FunctionConsts::DoDistinct));\n}\n\nPlanIter_t\nfn_union::codegen (\n CompilerCB* \/*cb*\/,\n static_context* sctx,\n const QueryLoc& loc,\n std::vector<PlanIter_t>& argv,\n AnnotationHolder &ann) const\n{\n return new FnConcatIterator(sctx, loc, argv, false);\n}\n\nPlanIter_t fn_intersect::codegen(\n CompilerCB* \/*cb*\/,\n static_context* sctx,\n const QueryLoc& loc, \n std::vector<PlanIter_t>& argv,\n AnnotationHolder &ann) const\n{\n#if 0 \/\/ we can't access PRODUCES_* from the inputs, must rethink\n bool distinct = ann.get_annotation (Annotations::IGNORES_DUP_NODES) != TSVAnnotationValue::TRUE_VAL;\n bool sort = ann.get_annotation (Annotations::IGNORES_SORTED_NODES) != TSVAnnotationValue::TRUE_VAL;\n\n std::vector<PlanIter_t> inputs;\n for (std::vector<PlanIter_t>::iterator i = argv.begin ();\n i != argv.end (); i++)\n inputs.push_back (new NodeSortIterator (loc, *i, true, distinct, false));\n return new SortSemiJoinIterator(loc, inputs);\n#endif\n\n return new HashSemiJoinIterator(sctx, loc, argv);\n}\n\n\nPlanIter_t\nfn_except::codegen(\n CompilerCB* \/*cb*\/,\n static_context* sctx,\n const QueryLoc& loc,\n std::vector<PlanIter_t>& argv,\n AnnotationHolder& ann) const\n{\n \/\/ TODO: use SortAntiJoinIterator when available (trac ticket 254)\n return new HashSemiJoinIterator(sctx, loc, argv, true);\n}\n\nvoid\nfn_subsequence::compute_annotation(\n AnnotationHolder* parent,\n std::vector<AnnotationHolder *>& kids,\n Annotations::Key k) const\n{\n switch (k) {\n case Annotations::IGNORES_SORTED_NODES:\n case Annotations::IGNORES_DUP_NODES:\n \/\/ don't use single_seq_fun default propagation rule\n return;\n default: single_seq_opt_function::compute_annotation (parent, kids, k);\n }\n}\n\n\nPlanIter_t\nfn_subsequence::codegen(\n CompilerCB* \/*cb*\/,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& aAnn) const\n{\n fo_expr& subseqExpr = static_cast<fo_expr&>(aAnn);\n\n const relpath_expr* pathExpr =\n dynamic_cast<const relpath_expr*>(subseqExpr[0].getp());\n\n const const_expr* posExpr =\n dynamic_cast<const const_expr*>(subseqExpr[1].getp());\n\n const const_expr* lenExpr = NULL;\n if (subseqExpr.size() > 2)\n lenExpr = dynamic_cast<const const_expr*>(subseqExpr[2].getp());\n\n if (posExpr != NULL && lenExpr != NULL && pathExpr != NULL)\n {\n xqp_double pos1 = posExpr->get_val()->getDoubleValue().round();\n long pos2 = static_cast<long>(pos1.getNumber());\n\n xqp_double len1 = lenExpr->get_val()->getDoubleValue().round();\n long len2 = static_cast<long>(pos1.getNumber());\n\n ulong numSteps = pathExpr->numSteps();\n\n if (pos2 > 0 && len2 == 1 && numSteps == 2)\n {\n AxisIteratorHelper* input = dynamic_cast<AxisIteratorHelper*>(aArgs[0].getp());\n assert(input != NULL);\n\n if (input->setTargetPos(pos2-1))\n return aArgs[0];\n }\n }\n\n return new FnSubsequenceIterator(aSctx, aLoc, aArgs);\n}\n\nxqtref_t\nfn_zero_or_one::return_type(const std::vector<xqtref_t>& arg_types) const\n{\n xqtref_t srcType = arg_types[0];\n\n return srcType->get_manager()->\n create_type(*TypeOps::prime_type(*srcType), TypeConstants::QUANT_QUESTION);\n}\n\nPlanIter_t\nfn_zero_or_one::codegen(\n CompilerCB* \/*cb*\/,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& aAnn) const\n{\n return new FnZeroOrOneIterator(aSctx,\n aLoc,\n aArgs,\n testFlag(FunctionConsts::DoDistinct));\n}\n\nPlanIter_t\nfn_distinct_values::codegen(CompilerCB* \/* cb *\/,\n static_context* sctx,\n const QueryLoc& loc,\n std::vector<PlanIter_t>& argv,\n AnnotationHolder &\/*ann*\/) const\n{\n return new FnDistinctValuesIterator(sctx, loc, argv);\n}\n\nPlanIter_t\nfn_max::codegen(\n CompilerCB* \/*cb*\/,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& \/*aAnn*\/) const\n{\n return new FnMinMaxIterator(aSctx, aLoc, aArgs, FnMinMaxIterator::MAX);\n}\n\nPlanIter_t\nfn_min::codegen(\n CompilerCB* \/*cb*\/,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& \/*ann*\/) const\n{\n return new FnMinMaxIterator(aSctx, aLoc, aArgs, FnMinMaxIterator::MIN);\n}\n\nvoid\npopulate_context_sequences_impl(static_context* sctx)\n{\n DECL(sctx, fn_exactly_one,\n (createQName(XQUERY_FN_NS,\"fn\",\"exactly-one\"),\n GENV_TYPESYSTEM.ITEM_TYPE_STAR, \n GENV_TYPESYSTEM.ITEM_TYPE_ONE));\n\n DECL(sctx, fn_exactly_one_noraise,\n (createQName(XQUERY_FN_NS,\"fn\",\":exactly-one-noraise\"),\n GENV_TYPESYSTEM.ITEM_TYPE_STAR,\n GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE));\n\n DECL(sctx, fn_union,\n (createQName(XQUERY_FN_NS,\"fn\",\":union\"),\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR, GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR));\n\n DECL(sctx, fn_intersect,\n (createQName(XQUERY_FN_NS,\"fn\",\":intersect\"),\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR, GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR));\n\n DECL(sctx, fn_except,\n (createQName(XQUERY_FN_NS,\"fn\",\":except\"),\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR, GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR));\n\n DECL(sctx, fn_distinct_values,\n (createQName(XQUERY_FN_NS,\"fn\",\"distinct-values\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR));\n\n DECL(sctx, fn_distinct_values,\n (createQName(XQUERY_FN_NS,\"fn\",\"distinct-values\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR,\n GENV_TYPESYSTEM.STRING_TYPE_ONE,\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR));\n DECL(sctx, fn_max,\n (createQName(XQUERY_FN_NS,\"fn\",\"max\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR, \n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_QUESTION));\n \n DECL(sctx, fn_max,\n (createQName(XQUERY_FN_NS,\"fn\",\"max\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR,\n GENV_TYPESYSTEM.STRING_TYPE_ONE,\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_QUESTION));\n\n DECL(sctx, fn_min,\n (createQName(XQUERY_FN_NS,\"fn\",\"min\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR, \n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_QUESTION));\n\n DECL(sctx, fn_min,\n (createQName(XQUERY_FN_NS,\"fn\",\"min\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR, \n GENV_TYPESYSTEM.STRING_TYPE_ONE, \n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_QUESTION));\n\n}\n\n} \/* namespace zorba *\/\n<commit_msg>Added fn:id and fn:idref codegen.<commit_after>\/*\n * Copyright 2006-2008 The FLWOR 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#include \"functions\/sequences.h\"\n#include \"functions\/sequences_impl.h\"\n\n#include \"runtime\/sequences\/sequences.h\"\n#include \"runtime\/sequences\/SequencesImpl.h\"\n#include \"system\/globalenv.h\"\n\n#include \"compiler\/expression\/expr.h\"\n\n#include \"compiler\/semantic_annotations\/annotation_keys.h\"\n#include \"compiler\/semantic_annotations\/tsv_annotation.h\"\n\n#include \"types\/typeops.h\"\n\nnamespace zorba {\n\nxqtref_t\nop_concatenate::return_type(const std::vector<xqtref_t>& arg_types) const \n{\n int sz = arg_types.size ();\n if (sz == 0)\n return GENV_TYPESYSTEM.EMPTY_TYPE;\n else {\n xqtref_t t = arg_types [0];\n TypeConstants::quantifier_t q = TypeConstants::QUANT_STAR;\n for (int i = 1; i < sz; i++) {\n t = TypeOps::union_type (*t, *arg_types [i]);\n TypeConstants::quantifier_t pq = TypeOps::quantifier (*t);\n if (pq == TypeConstants::QUANT_ONE || pq == TypeConstants::QUANT_PLUS)\n q = TypeConstants::QUANT_PLUS;\n }\n return GENV_TYPESYSTEM.create_type_x_quant (*t, q);\n }\n}\n\nvoid\nop_concatenate::compute_annotation (\n AnnotationHolder *parent,\n std::vector<AnnotationHolder *> &kids,\n Annotations::Key k) const \n{\n switch (k) {\n case Annotations::IGNORES_SORTED_NODES:\n case Annotations::IGNORES_DUP_NODES:\n for (std::vector<AnnotationHolder *>::iterator i = kids.begin (); i < kids.end (); i++)\n TSVAnnotationValue::update_annotation ((*i), k, parent->get_annotation (k));\n break;\n default: break;\n }\n}\n\nfunction* fn_sum::specialize(\n static_context* sctx,\n const std::vector<xqtref_t>& argTypes) const\n{\n RootTypeManager& rtm = GENV_TYPESYSTEM;\n\n xqtref_t argType = argTypes[0];\n\n if (TypeOps::is_subtype(*argType, *rtm.UNTYPED_ATOMIC_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_double\", get_arity());\n }\n else if (TypeOps::is_subtype(*argType, *rtm.DOUBLE_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_double\", get_arity());\n }\n else if (TypeOps::is_subtype(*argType, *rtm.FLOAT_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_foat\", get_arity());\n }\n else if (TypeOps::is_subtype(*argType, *rtm.INTEGER_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_integer\", get_arity());\n }\n else if (TypeOps::is_subtype(*argType, *rtm.DECIMAL_TYPE_STAR))\n {\n return sctx->lookup_builtin_fn(\"sum_decimal\", get_arity());\n }\n else\n {\n return NULL;\n }\n}\n\nxqtref_t fn_exactly_one_noraise::return_type(\n const std::vector<xqtref_t>& arg_types) const\n{\n if (theRaiseError)\n return TypeOps::prime_type(*arg_types[0]);\n else\n return function::return_type(arg_types);\n}\n\n\nPlanIter_t\nfn_exactly_one_noraise::codegen(CompilerCB* aCb,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& aAnn) const\n{\n return new FnExactlyOneIterator(aSctx,\n aLoc,\n aArgs,\n theRaiseError,\n testFlag(FunctionConsts::DoDistinct));\n}\n\nPlanIter_t\nfn_union::codegen (\n CompilerCB* \/*cb*\/,\n static_context* sctx,\n const QueryLoc& loc,\n std::vector<PlanIter_t>& argv,\n AnnotationHolder &ann) const\n{\n return new FnConcatIterator(sctx, loc, argv, false);\n}\n\nPlanIter_t fn_intersect::codegen(\n CompilerCB* \/*cb*\/,\n static_context* sctx,\n const QueryLoc& loc, \n std::vector<PlanIter_t>& argv,\n AnnotationHolder &ann) const\n{\n#if 0 \/\/ we can't access PRODUCES_* from the inputs, must rethink\n bool distinct = ann.get_annotation (Annotations::IGNORES_DUP_NODES) != TSVAnnotationValue::TRUE_VAL;\n bool sort = ann.get_annotation (Annotations::IGNORES_SORTED_NODES) != TSVAnnotationValue::TRUE_VAL;\n\n std::vector<PlanIter_t> inputs;\n for (std::vector<PlanIter_t>::iterator i = argv.begin ();\n i != argv.end (); i++)\n inputs.push_back (new NodeSortIterator (loc, *i, true, distinct, false));\n return new SortSemiJoinIterator(loc, inputs);\n#endif\n\n return new HashSemiJoinIterator(sctx, loc, argv);\n}\n\n\nPlanIter_t\nfn_except::codegen(\n CompilerCB* \/*cb*\/,\n static_context* sctx,\n const QueryLoc& loc,\n std::vector<PlanIter_t>& argv,\n AnnotationHolder& ann) const\n{\n \/\/ TODO: use SortAntiJoinIterator when available (trac ticket 254)\n return new HashSemiJoinIterator(sctx, loc, argv, true);\n}\n\nvoid\nfn_subsequence::compute_annotation(\n AnnotationHolder* parent,\n std::vector<AnnotationHolder *>& kids,\n Annotations::Key k) const\n{\n switch (k) {\n case Annotations::IGNORES_SORTED_NODES:\n case Annotations::IGNORES_DUP_NODES:\n \/\/ don't use single_seq_fun default propagation rule\n return;\n default: single_seq_opt_function::compute_annotation (parent, kids, k);\n }\n}\n\n\nPlanIter_t\nfn_subsequence::codegen(\n CompilerCB* \/*cb*\/,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& aAnn) const\n{\n fo_expr& subseqExpr = static_cast<fo_expr&>(aAnn);\n\n const relpath_expr* pathExpr =\n dynamic_cast<const relpath_expr*>(subseqExpr[0].getp());\n\n const const_expr* posExpr =\n dynamic_cast<const const_expr*>(subseqExpr[1].getp());\n\n const const_expr* lenExpr = NULL;\n if (subseqExpr.size() > 2)\n lenExpr = dynamic_cast<const const_expr*>(subseqExpr[2].getp());\n\n if (posExpr != NULL && lenExpr != NULL && pathExpr != NULL)\n {\n xqp_double pos1 = posExpr->get_val()->getDoubleValue().round();\n long pos2 = static_cast<long>(pos1.getNumber());\n\n xqp_double len1 = lenExpr->get_val()->getDoubleValue().round();\n long len2 = static_cast<long>(pos1.getNumber());\n\n ulong numSteps = pathExpr->numSteps();\n\n if (pos2 > 0 && len2 == 1 && numSteps == 2)\n {\n AxisIteratorHelper* input = dynamic_cast<AxisIteratorHelper*>(aArgs[0].getp());\n assert(input != NULL);\n\n if (input->setTargetPos(pos2-1))\n return aArgs[0];\n }\n }\n\n return new FnSubsequenceIterator(aSctx, aLoc, aArgs);\n}\n\nxqtref_t\nfn_zero_or_one::return_type(const std::vector<xqtref_t>& arg_types) const\n{\n xqtref_t srcType = arg_types[0];\n\n return srcType->get_manager()->\n create_type(*TypeOps::prime_type(*srcType), TypeConstants::QUANT_QUESTION);\n}\n\nPlanIter_t\nfn_zero_or_one::codegen(\n CompilerCB* \/*cb*\/,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& aAnn) const\n{\n return new FnZeroOrOneIterator(aSctx,\n aLoc,\n aArgs,\n testFlag(FunctionConsts::DoDistinct));\n}\n\nPlanIter_t\nfn_distinct_values::codegen(CompilerCB* \/* cb *\/,\n static_context* sctx,\n const QueryLoc& loc,\n std::vector<PlanIter_t>& argv,\n AnnotationHolder &\/*ann*\/) const\n{\n return new FnDistinctValuesIterator(sctx, loc, argv);\n}\n\nPlanIter_t\nfn_max::codegen(\n CompilerCB* \/*cb*\/,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& \/*aAnn*\/) const\n{\n return new FnMinMaxIterator(aSctx, aLoc, aArgs, FnMinMaxIterator::MAX);\n}\n\nPlanIter_t\nfn_min::codegen(\n CompilerCB* \/*cb*\/,\n static_context* aSctx,\n const QueryLoc& aLoc,\n std::vector<PlanIter_t>& aArgs,\n AnnotationHolder& \/*ann*\/) const\n{\n return new FnMinMaxIterator(aSctx, aLoc, aArgs, FnMinMaxIterator::MIN);\n}\n\n\/\/15.5.2 fn:id\ntypedef function_impl<FnIdIterator> fn_id;\n\n\n\/\/15.5.3 fn:idref\ntypedef function_impl<FnIdRefIterator> fn_id_ref;\n\nvoid\npopulate_context_sequences_impl(static_context* sctx)\n{\n DECL(sctx, fn_exactly_one,\n (createQName(XQUERY_FN_NS,\"fn\",\"exactly-one\"),\n GENV_TYPESYSTEM.ITEM_TYPE_STAR, \n GENV_TYPESYSTEM.ITEM_TYPE_ONE));\n\n DECL(sctx, fn_exactly_one_noraise,\n (createQName(XQUERY_FN_NS,\"fn\",\":exactly-one-noraise\"),\n GENV_TYPESYSTEM.ITEM_TYPE_STAR,\n GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE));\n\n DECL(sctx, fn_union,\n (createQName(XQUERY_FN_NS,\"fn\",\":union\"),\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR, GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR));\n\n DECL(sctx, fn_intersect,\n (createQName(XQUERY_FN_NS,\"fn\",\":intersect\"),\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR, GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR));\n\n DECL(sctx, fn_except,\n (createQName(XQUERY_FN_NS,\"fn\",\":except\"),\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR, GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR));\n\n DECL(sctx, fn_distinct_values,\n (createQName(XQUERY_FN_NS,\"fn\",\"distinct-values\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR));\n\n DECL(sctx, fn_distinct_values,\n (createQName(XQUERY_FN_NS,\"fn\",\"distinct-values\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR,\n GENV_TYPESYSTEM.STRING_TYPE_ONE,\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR));\n DECL(sctx, fn_max,\n (createQName(XQUERY_FN_NS,\"fn\",\"max\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR, \n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_QUESTION));\n \n DECL(sctx, fn_max,\n (createQName(XQUERY_FN_NS,\"fn\",\"max\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR,\n GENV_TYPESYSTEM.STRING_TYPE_ONE,\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_QUESTION));\n\n DECL(sctx, fn_min,\n (createQName(XQUERY_FN_NS,\"fn\",\"min\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR, \n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_QUESTION));\n\n DECL(sctx, fn_min,\n (createQName(XQUERY_FN_NS,\"fn\",\"min\"),\n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR, \n GENV_TYPESYSTEM.STRING_TYPE_ONE, \n GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_QUESTION));\n\n DECL(sctx, fn_id,\n (createQName(XQUERY_FN_NS,\"fn\",\"id\"),\n GENV_TYPESYSTEM.STRING_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_ONE,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR)\n );\n\n DECL(sctx, fn_id_ref,\n (createQName(XQUERY_FN_NS,\"fn\",\"idref\"),\n GENV_TYPESYSTEM.STRING_TYPE_STAR,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_ONE,\n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR));\n\n}\n\n} \/* namespace zorba *\/\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015-2018 Egor Yusov\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* 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 OF ANY PROPRIETARY RIGHTS.\n*\n* In no event and under no legal theory, whether in tort (including negligence),\n* contract, or otherwise, unless required by applicable law (such as deliberate\n* and grossly negligent acts) or agreed to in writing, shall any Contributor be\n* liable for any damages, including any direct, indirect, special, incidental,\n* or consequential damages of any character arising as a result of this License or\n* out of the use or inability to use the software (including but not limited to damages\n* for loss of goodwill, work stoppage, computer failure or malfunction, or any and\n* all other commercial damages or losses), even if such Contributor has been advised\n* of the possibility of such damages.\n*\/\n\n#include \"AndroidFileSystem.h\"\n#include \"EngineFactoryOpenGL.h\"\n#include \"SampleApp.h\"\n#include \"RenderDeviceGLES.h\"\n#include \"AntTweakBar.h\"\n\nnamespace Diligent\n{\n\nclass SampleAppAndroid final : public SampleApp\n{\npublic:\n SampleAppAndroid()\n {\n m_DeviceType = DeviceType::OpenGLES;\n }\n\n virtual void Initialize()override final\n {\n GetEngineFactoryOpenGL()->InitAndroidFileSystem(app_->activity, native_activity_class_name_.c_str());\n AndroidFileSystem::Init(app_->activity, native_activity_class_name_.c_str());\n SampleApp::Initialize();\n InitializeDiligentEngine(app_->window);\n m_RenderDeviceGLES = RefCntAutoPtr<IRenderDeviceGLES>(m_pDevice, IID_RenderDeviceGLES);\n m_TheSample->SetUIScale(3);\n InitializeSample();\n }\n\n virtual int Resume(ANativeWindow* window)override final\n {\n return m_RenderDeviceGLES->Resume(window);\n }\n\n virtual void TermDisplay()override final\n {\n \/\/ Tear down the EGL context currently associated with the display.\n m_RenderDeviceGLES->Suspend();\n }\n\n virtual void TrimMemory()override final\n {\n LOGI( \"Trimming memory\" );\n m_RenderDeviceGLES->Invalidate();\n }\n\n virtual int32_t HandleInput( AInputEvent* event )override final\n {\n if( AInputEvent_getType( event ) == AINPUT_EVENT_TYPE_MOTION )\n {\n ndk_helper::GESTURE_STATE doubleTapState = doubletap_detector_.Detect( event );\n ndk_helper::GESTURE_STATE dragState = drag_detector_.Detect( event );\n ndk_helper::GESTURE_STATE pinchState = pinch_detector_.Detect( event );\n\n \/\/Double tap detector has a priority over other detectors\n if( doubleTapState == ndk_helper::GESTURE_STATE_ACTION )\n {\n \/\/Detect double tap\n \/\/tap_camera_.Reset( true );\n }\n else\n {\n \/\/Handle drag state\n if( dragState & ndk_helper::GESTURE_STATE_START )\n {\n \/\/Otherwise, start dragging\n ndk_helper::Vec2 v;\n drag_detector_.GetPointer( v );\n float fX = 0, fY = 0;\n v.Value(fX, fY);\n TwMouseMotion((short)fX, (short)fY);\n int Handled = TwMouseButton( TW_MOUSE_PRESSED, TW_MOUSE_LEFT );\n if (!Handled)\n {\n m_TheSample->GetInputController().BeginDrag(fX, fY);\n }\n }\n else if( dragState & ndk_helper::GESTURE_STATE_MOVE )\n {\n ndk_helper::Vec2 v;\n drag_detector_.GetPointer( v );\n float fX = 0, fY = 0;\n v.Value(fX, fY);\n int Handled = TwMouseMotion((short)fX, (short)fY);\n m_TheSample->GetInputController().DragMove(fX, fY);\n }\n else if( dragState & ndk_helper::GESTURE_STATE_END )\n {\n int Handled = TwMouseButton(TW_MOUSE_RELEASED, TW_MOUSE_LEFT);\n m_TheSample->GetInputController().EndDrag();\n }\n\n \/\/Handle pinch state\n if( pinchState & ndk_helper::GESTURE_STATE_START )\n {\n \/\/Start new pinch\n ndk_helper::Vec2 v1;\n ndk_helper::Vec2 v2;\n pinch_detector_.GetPointers( v1, v2 );\n float fX1 = 0, fY1 = 0, fX2 = 0, fY2 = 0;\n v1.Value(fX1, fY1);\n v2.Value(fX2, fY2);\n m_TheSample->GetInputController().StartPinch(fX1, fY1, fX2, fY2);\n \/\/tap_camera_.BeginPinch( v1, v2 );\n }\n else if( pinchState & ndk_helper::GESTURE_STATE_MOVE )\n {\n \/\/Multi touch\n \/\/Start new pinch\n ndk_helper::Vec2 v1;\n ndk_helper::Vec2 v2;\n pinch_detector_.GetPointers( v1, v2 );\n float fX1 = 0, fY1 = 0, fX2 = 0, fY2 = 0;\n v1.Value(fX1, fY1);\n v2.Value(fX2, fY2);\n m_TheSample->GetInputController().PinchMove(fX1, fY1, fX2, fY2);\n \/\/tap_camera_.Pinch( v1, v2 );\n }\n else if( pinchState & ndk_helper::GESTURE_STATE_END )\n {\n m_TheSample->GetInputController().EndPinch();\n }\n }\n return 1;\n }\n return 0;\n }\n\nprivate:\n RefCntAutoPtr<IRenderDeviceGLES> m_RenderDeviceGLES;\n};\n\nNativeAppBase* CreateApplication()\n{\n return new SampleAppAndroid;\n}\n\n}\n\n<commit_msg>Sample app android: enabled event handling by ImGui<commit_after>\/* Copyright 2015-2018 Egor Yusov\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* 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 OF ANY PROPRIETARY RIGHTS.\n*\n* In no event and under no legal theory, whether in tort (including negligence),\n* contract, or otherwise, unless required by applicable law (such as deliberate\n* and grossly negligent acts) or agreed to in writing, shall any Contributor be\n* liable for any damages, including any direct, indirect, special, incidental,\n* or consequential damages of any character arising as a result of this License or\n* out of the use or inability to use the software (including but not limited to damages\n* for loss of goodwill, work stoppage, computer failure or malfunction, or any and\n* all other commercial damages or losses), even if such Contributor has been advised\n* of the possibility of such damages.\n*\/\n\n#include \"AndroidFileSystem.h\"\n#include \"EngineFactoryOpenGL.h\"\n#include \"SampleApp.h\"\n#include \"RenderDeviceGLES.h\"\n#include \"ImGuiImplAndroid.h\"\n\nnamespace Diligent\n{\n\nclass SampleAppAndroid final : public SampleApp\n{\npublic:\n SampleAppAndroid()\n {\n m_DeviceType = DeviceType::OpenGLES;\n }\n\n virtual void Initialize()override final\n {\n GetEngineFactoryOpenGL()->InitAndroidFileSystem(app_->activity, native_activity_class_name_.c_str());\n AndroidFileSystem::Init(app_->activity, native_activity_class_name_.c_str());\n SampleApp::Initialize();\n InitializeDiligentEngine(app_->window);\n const auto& SCDesc = m_pSwapChain->GetDesc();\n m_pImGui.reset(new ImGuiImplAndroid(m_pDevice, SCDesc.ColorBufferFormat, SCDesc.DepthBufferFormat, SCDesc.Width, SCDesc.Height));\n m_RenderDeviceGLES = RefCntAutoPtr<IRenderDeviceGLES>(m_pDevice, IID_RenderDeviceGLES);\n InitializeSample();\n }\n\n virtual int Resume(ANativeWindow* window)override final\n {\n return m_RenderDeviceGLES->Resume(window);\n }\n\n virtual void TermDisplay()override final\n {\n \/\/ Tear down the EGL context currently associated with the display.\n m_RenderDeviceGLES->Suspend();\n }\n\n virtual void TrimMemory()override final\n {\n LOGI( \"Trimming memory\" );\n m_RenderDeviceGLES->Invalidate();\n }\n\n virtual int32_t HandleInput( AInputEvent* event )override final\n {\n if( AInputEvent_getType( event ) == AINPUT_EVENT_TYPE_MOTION )\n {\n ndk_helper::GESTURE_STATE doubleTapState = doubletap_detector_.Detect( event );\n ndk_helper::GESTURE_STATE dragState = drag_detector_.Detect( event );\n ndk_helper::GESTURE_STATE pinchState = pinch_detector_.Detect( event );\n\n \/\/Double tap detector has a priority over other detectors\n if( doubleTapState == ndk_helper::GESTURE_STATE_ACTION )\n {\n \/\/Detect double tap\n \/\/tap_camera_.Reset( true );\n }\n else\n {\n \/\/Handle drag state\n if( dragState & ndk_helper::GESTURE_STATE_START )\n {\n \/\/Otherwise, start dragging\n ndk_helper::Vec2 v;\n drag_detector_.GetPointer( v );\n float fX = 0, fY = 0;\n v.Value(fX, fY);\n auto Handled = static_cast<ImGuiImplAndroid*>(m_pImGui.get())->BeginDrag(fX, fY);\n if (!Handled)\n {\n m_TheSample->GetInputController().BeginDrag(fX, fY);\n }\n }\n else if( dragState & ndk_helper::GESTURE_STATE_MOVE )\n {\n ndk_helper::Vec2 v;\n drag_detector_.GetPointer( v );\n float fX = 0, fY = 0;\n v.Value(fX, fY);\n auto Handled = static_cast<ImGuiImplAndroid*>(m_pImGui.get())->DragMove(fX, fY);\n if (!Handled)\n {\n m_TheSample->GetInputController().DragMove(fX, fY);\n }\n }\n else if( dragState & ndk_helper::GESTURE_STATE_END )\n {\n static_cast<ImGuiImplAndroid*>(m_pImGui.get())->EndDrag();\n m_TheSample->GetInputController().EndDrag();\n }\n\n \/\/Handle pinch state\n if( pinchState & ndk_helper::GESTURE_STATE_START )\n {\n \/\/Start new pinch\n ndk_helper::Vec2 v1;\n ndk_helper::Vec2 v2;\n pinch_detector_.GetPointers( v1, v2 );\n float fX1 = 0, fY1 = 0, fX2 = 0, fY2 = 0;\n v1.Value(fX1, fY1);\n v2.Value(fX2, fY2);\n m_TheSample->GetInputController().StartPinch(fX1, fY1, fX2, fY2);\n \/\/tap_camera_.BeginPinch( v1, v2 );\n }\n else if( pinchState & ndk_helper::GESTURE_STATE_MOVE )\n {\n \/\/Multi touch\n \/\/Start new pinch\n ndk_helper::Vec2 v1;\n ndk_helper::Vec2 v2;\n pinch_detector_.GetPointers( v1, v2 );\n float fX1 = 0, fY1 = 0, fX2 = 0, fY2 = 0;\n v1.Value(fX1, fY1);\n v2.Value(fX2, fY2);\n m_TheSample->GetInputController().PinchMove(fX1, fY1, fX2, fY2);\n \/\/tap_camera_.Pinch( v1, v2 );\n }\n else if( pinchState & ndk_helper::GESTURE_STATE_END )\n {\n m_TheSample->GetInputController().EndPinch();\n }\n }\n return 1;\n }\n return 0;\n }\n\nprivate:\n RefCntAutoPtr<IRenderDeviceGLES> m_RenderDeviceGLES;\n};\n\nNativeAppBase* CreateApplication()\n{\n return new SampleAppAndroid;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- DriverUtils.cpp ----------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains utility functions for the driver. Because there\n\/\/ are so many small functions, we created this separate file to make\n\/\/ Driver.cpp less cluttered.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Driver.h\"\n#include \"Error.h\"\n#include \"Memory.h\"\n#include \"lld\/Config\/Version.h\"\n#include \"lld\/Core\/Reproduce.h\"\n#include \"llvm\/ADT\/Optional.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Option\/Option.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Process.h\"\n\nusing namespace llvm;\nusing namespace llvm::sys;\n\nusing namespace lld;\nusing namespace lld::elf;\n\n\/\/ Create OptTable\n\n\/\/ Create prefix string literals used in Options.td\n#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;\n#include \"Options.inc\"\n#undef PREFIX\n\n\/\/ Create table mapping all options defined in Options.td\nstatic const opt::OptTable::Info OptInfo[] = {\n#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10) \\\n {X1, X2, X9, X10, OPT_##ID, opt::Option::KIND##Class, \\\n X8, X7, OPT_##GROUP, OPT_##ALIAS, X6},\n#include \"Options.inc\"\n#undef OPTION\n};\n\nELFOptTable::ELFOptTable() : OptTable(OptInfo) {}\n\n\/\/ Parse -color-diagnostics={auto,always,never} or -no-color-diagnostics.\nstatic bool getColorDiagnostics(opt::InputArgList &Args) {\n bool Default = (ErrorOS == &errs() && Process::StandardErrHasColors());\n\n auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,\n OPT_no_color_diagnostics);\n if (!Arg)\n return Default;\n if (Arg->getOption().getID() == OPT_color_diagnostics)\n return true;\n if (Arg->getOption().getID() == OPT_no_color_diagnostics)\n return false;\n\n StringRef S = Arg->getValue();\n if (S == \"auto\")\n return Default;\n if (S == \"always\")\n return true;\n if (S != \"never\")\n error(\"unknown option: -color-diagnostics=\" + S);\n return false;\n}\n\nstatic cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {\n if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {\n StringRef S = Arg->getValue();\n if (S != \"windows\" && S != \"posix\")\n error(\"invalid response file quoting: \" + S);\n if (S == \"windows\")\n return cl::TokenizeWindowsCommandLine;\n return cl::TokenizeGNUCommandLine;\n }\n if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)\n return cl::TokenizeWindowsCommandLine;\n return cl::TokenizeGNUCommandLine;\n}\n\n\/\/ Parses a given list of options.\nopt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {\n \/\/ Make InputArgList from string vectors.\n unsigned MissingIndex;\n unsigned MissingCount;\n SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());\n\n \/\/ We need to get the quoting style for response files before parsing all\n \/\/ options so we parse here before and ignore all the options but\n \/\/ --rsp-quoting.\n opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);\n\n \/\/ Expand response files (arguments in the form of @<filename>)\n \/\/ and then parse the argument again.\n cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);\n Args = this->ParseArgs(Vec, MissingIndex, MissingCount);\n\n \/\/ Interpret -color-diagnostics early so that error messages\n \/\/ for unknown flags are colored.\n Config->ColorDiagnostics = getColorDiagnostics(Args);\n if (MissingCount)\n error(Twine(Args.getArgString(MissingIndex)) + \": missing argument\");\n\n for (auto *Arg : Args.filtered(OPT_UNKNOWN))\n error(\"unknown argument: \" + Arg->getSpelling());\n return Args;\n}\n\nvoid elf::printHelp(const char *Argv0) {\n ELFOptTable Table;\n Table.PrintHelp(outs(), Argv0, \"lld\", false);\n outs() << \"\\n\";\n\n \/\/ Scripts generated by Libtool versions up to at least 2.4.6 (the most\n \/\/ recent version as of March 2017) expect \/supported targets:.* elf\/ in\n \/\/ a message for the -help option. If it doesn't match, the scripts\n \/\/ assume that the linker doesn't support very basic features such as\n \/\/ shared libraries. Therefore, we need to print out at least \"elf\".\n \/\/ Here, we print out all the targets that we support.\n outs() << Argv0 << \": supported targets: \"\n << \"elf32-i386 elf32-iamcu elf32-littlearm elf32-powerpc \"\n << \"elf32-tradbigmips elf32-tradlittlemips elf32-x86-64 \"\n << \"elf64-amdgpu elf64-littleaarch64 elf64-powerpc \"\n << \"elf64-tradbigmips elf64-tradlittlemips elf64-x86-64\\n\";\n}\n\n\/\/ Reconstructs command line arguments so that so that you can re-run\n\/\/ the same command with the same inputs. This is for --reproduce.\nstd::string elf::createResponseFile(const opt::InputArgList &Args) {\n SmallString<0> Data;\n raw_svector_ostream OS(Data);\n\n \/\/ Copy the command line to the output while rewriting paths.\n for (auto *Arg : Args) {\n switch (Arg->getOption().getID()) {\n case OPT_reproduce:\n break;\n case OPT_INPUT:\n OS << quote(rewritePath(Arg->getValue())) << \"\\n\";\n break;\n case OPT_o:\n \/\/ If -o path contains directories, \"lld @response.txt\" will likely\n \/\/ fail because the archive we are creating doesn't contain empty\n \/\/ directories for the output path (-o doesn't create directories).\n \/\/ Strip directories to prevent the issue.\n OS << \"-o \" << quote(sys::path::filename(Arg->getValue())) << \"\\n\";\n break;\n case OPT_L:\n case OPT_dynamic_list:\n case OPT_rpath:\n case OPT_alias_script_T:\n case OPT_script:\n case OPT_version_script:\n OS << Arg->getSpelling() << \" \" << quote(rewritePath(Arg->getValue()))\n << \"\\n\";\n break;\n default:\n OS << toString(Arg) << \"\\n\";\n }\n }\n return Data.str();\n}\n\n\/\/ Find a file by concatenating given paths. If a resulting path\n\/\/ starts with \"=\", the character is replaced with a --sysroot value.\nstatic Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {\n SmallString<128> S;\n if (Path1.startswith(\"=\"))\n path::append(S, Config->Sysroot, Path1.substr(1), Path2);\n else\n path::append(S, Path1, Path2);\n\n if (fs::exists(S))\n return S.str().str();\n return None;\n}\n\nOptional<std::string> elf::findFromSearchPaths(StringRef Path) {\n for (StringRef Dir : Config->SearchPaths)\n if (Optional<std::string> S = findFile(Dir, Path))\n return S;\n return None;\n}\n\n\/\/ This is for -lfoo. We'll look for libfoo.so or libfoo.a from\n\/\/ search paths.\nOptional<std::string> elf::searchLibrary(StringRef Name) {\n if (Name.startswith(\":\"))\n return findFromSearchPaths(Name.substr(1));\n\n for (StringRef Dir : Config->SearchPaths) {\n if (!Config->Static)\n if (Optional<std::string> S = findFile(Dir, \"lib\" + Name + \".so\"))\n return S;\n if (Optional<std::string> S = findFile(Dir, \"lib\" + Name + \".a\"))\n return S;\n }\n return None;\n}\n<commit_msg>Refine comment.<commit_after>\/\/===- DriverUtils.cpp ----------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains utility functions for the driver. Because there\n\/\/ are so many small functions, we created this separate file to make\n\/\/ Driver.cpp less cluttered.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Driver.h\"\n#include \"Error.h\"\n#include \"Memory.h\"\n#include \"lld\/Config\/Version.h\"\n#include \"lld\/Core\/Reproduce.h\"\n#include \"llvm\/ADT\/Optional.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Option\/Option.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Process.h\"\n\nusing namespace llvm;\nusing namespace llvm::sys;\n\nusing namespace lld;\nusing namespace lld::elf;\n\n\/\/ Create OptTable\n\n\/\/ Create prefix string literals used in Options.td\n#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;\n#include \"Options.inc\"\n#undef PREFIX\n\n\/\/ Create table mapping all options defined in Options.td\nstatic const opt::OptTable::Info OptInfo[] = {\n#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10) \\\n {X1, X2, X9, X10, OPT_##ID, opt::Option::KIND##Class, \\\n X8, X7, OPT_##GROUP, OPT_##ALIAS, X6},\n#include \"Options.inc\"\n#undef OPTION\n};\n\nELFOptTable::ELFOptTable() : OptTable(OptInfo) {}\n\n\/\/ Parse -color-diagnostics={auto,always,never} or -no-color-diagnostics.\nstatic bool getColorDiagnostics(opt::InputArgList &Args) {\n bool Default = (ErrorOS == &errs() && Process::StandardErrHasColors());\n\n auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,\n OPT_no_color_diagnostics);\n if (!Arg)\n return Default;\n if (Arg->getOption().getID() == OPT_color_diagnostics)\n return true;\n if (Arg->getOption().getID() == OPT_no_color_diagnostics)\n return false;\n\n StringRef S = Arg->getValue();\n if (S == \"auto\")\n return Default;\n if (S == \"always\")\n return true;\n if (S != \"never\")\n error(\"unknown option: -color-diagnostics=\" + S);\n return false;\n}\n\nstatic cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {\n if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {\n StringRef S = Arg->getValue();\n if (S != \"windows\" && S != \"posix\")\n error(\"invalid response file quoting: \" + S);\n if (S == \"windows\")\n return cl::TokenizeWindowsCommandLine;\n return cl::TokenizeGNUCommandLine;\n }\n if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)\n return cl::TokenizeWindowsCommandLine;\n return cl::TokenizeGNUCommandLine;\n}\n\n\/\/ Parses a given list of options.\nopt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {\n \/\/ Make InputArgList from string vectors.\n unsigned MissingIndex;\n unsigned MissingCount;\n SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());\n\n \/\/ We need to get the quoting style for response files before parsing all\n \/\/ options so we parse here before and ignore all the options but\n \/\/ --rsp-quoting.\n opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);\n\n \/\/ Expand response files (arguments in the form of @<filename>)\n \/\/ and then parse the argument again.\n cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);\n Args = this->ParseArgs(Vec, MissingIndex, MissingCount);\n\n \/\/ Interpret -color-diagnostics early so that error messages\n \/\/ for unknown flags are colored.\n Config->ColorDiagnostics = getColorDiagnostics(Args);\n if (MissingCount)\n error(Twine(Args.getArgString(MissingIndex)) + \": missing argument\");\n\n for (auto *Arg : Args.filtered(OPT_UNKNOWN))\n error(\"unknown argument: \" + Arg->getSpelling());\n return Args;\n}\n\nvoid elf::printHelp(const char *Argv0) {\n ELFOptTable Table;\n Table.PrintHelp(outs(), Argv0, \"lld\", false);\n outs() << \"\\n\";\n\n \/\/ Scripts generated by Libtool versions up to at least 2.4.6 (the most\n \/\/ recent version as of March 2017) expect \/: supported targets:.* elf\/\n \/\/ in a message for the -help option. If it doesn't match, the scripts\n \/\/ assume that the linker doesn't support very basic features such as\n \/\/ shared libraries. Therefore, we need to print out at least \"elf\".\n \/\/ Here, we print out all the targets that we support.\n outs() << Argv0 << \": supported targets: \"\n << \"elf32-i386 elf32-iamcu elf32-littlearm elf32-powerpc \"\n << \"elf32-tradbigmips elf32-tradlittlemips elf32-x86-64 \"\n << \"elf64-amdgpu elf64-littleaarch64 elf64-powerpc \"\n << \"elf64-tradbigmips elf64-tradlittlemips elf64-x86-64\\n\";\n}\n\n\/\/ Reconstructs command line arguments so that so that you can re-run\n\/\/ the same command with the same inputs. This is for --reproduce.\nstd::string elf::createResponseFile(const opt::InputArgList &Args) {\n SmallString<0> Data;\n raw_svector_ostream OS(Data);\n\n \/\/ Copy the command line to the output while rewriting paths.\n for (auto *Arg : Args) {\n switch (Arg->getOption().getID()) {\n case OPT_reproduce:\n break;\n case OPT_INPUT:\n OS << quote(rewritePath(Arg->getValue())) << \"\\n\";\n break;\n case OPT_o:\n \/\/ If -o path contains directories, \"lld @response.txt\" will likely\n \/\/ fail because the archive we are creating doesn't contain empty\n \/\/ directories for the output path (-o doesn't create directories).\n \/\/ Strip directories to prevent the issue.\n OS << \"-o \" << quote(sys::path::filename(Arg->getValue())) << \"\\n\";\n break;\n case OPT_L:\n case OPT_dynamic_list:\n case OPT_rpath:\n case OPT_alias_script_T:\n case OPT_script:\n case OPT_version_script:\n OS << Arg->getSpelling() << \" \" << quote(rewritePath(Arg->getValue()))\n << \"\\n\";\n break;\n default:\n OS << toString(Arg) << \"\\n\";\n }\n }\n return Data.str();\n}\n\n\/\/ Find a file by concatenating given paths. If a resulting path\n\/\/ starts with \"=\", the character is replaced with a --sysroot value.\nstatic Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {\n SmallString<128> S;\n if (Path1.startswith(\"=\"))\n path::append(S, Config->Sysroot, Path1.substr(1), Path2);\n else\n path::append(S, Path1, Path2);\n\n if (fs::exists(S))\n return S.str().str();\n return None;\n}\n\nOptional<std::string> elf::findFromSearchPaths(StringRef Path) {\n for (StringRef Dir : Config->SearchPaths)\n if (Optional<std::string> S = findFile(Dir, Path))\n return S;\n return None;\n}\n\n\/\/ This is for -lfoo. We'll look for libfoo.so or libfoo.a from\n\/\/ search paths.\nOptional<std::string> elf::searchLibrary(StringRef Name) {\n if (Name.startswith(\":\"))\n return findFromSearchPaths(Name.substr(1));\n\n for (StringRef Dir : Config->SearchPaths) {\n if (!Config->Static)\n if (Optional<std::string> S = findFile(Dir, \"lib\" + Name + \".so\"))\n return S;\n if (Optional<std::string> S = findFile(Dir, \"lib\" + Name + \".a\"))\n return S;\n }\n return None;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008-2010 Kent State University\n\/\/ Copyright (c) 2011-2012 Texas S&M University\n\/\/\n\/\/ This file is distributed under the MIT License. See the accompanying file\n\/\/ LICENSE.txt or http:\/\/www.opensource.org\/licenses\/mit-license.php for terms\n\/\/ and conditions.\n\n#ifndef ORIGIN_ITERATOR_STRIDE_HPP\n#define ORIGIN_ITERATOR_STRIDE_HPP\n\n#include <origin\/iterator\/facade.hpp>\n\nnamespace origin\n{\n template <typename I, typename S>\n class stride_iterator;\n\n\n \/\/ An alias for the facade used by the stride iterator.\n template <typename I, typename S>\n using Stride_iterator_facade = iterator_facade<stride_iterator<I, S>, I>;\n\n\n \/\/ Stride iterator\n \/\/\n \/\/ The stride iterator adaptor wraps an underlying iterator in such a way\n \/\/ that advancing a single stride (or step) will cause the underlying iterator\n \/\/ to advance a specified number of steps. \n \/\/\n \/\/ The step function for a stride iterator must return a value greater than 0.\n \/\/ S step of 0 will not result in bounded ranges. Also note that that\n \/\/ reversing a stride iterator can be achieved using a reverse iterator\n \/\/ adaptor.\n \/\/\n \/\/ Note: The bidirectional iterator operations are unchecked, meaning it\n \/\/ is possible to access elements that are before the first element of\n \/\/ the initial iterator value. Ensuring that these operations are checked\n \/\/ would require the addition of an extra iterator (the first iterator) and\n \/\/ checking those operations.\n \/\/\n \/\/ Invariants:\n \/\/ this->step() > 0\n template<typename I, typename Step = constant_function<Difference_type<I>>>\n class stride_iterator : public Stride_iterator_facade<I, Step>\n {\n static_assert(Iterator<I>(), \"\");\n static_assert(Function<Step>(), \"\");\n public:\n using Base = Stride_iterator_facade<I, Step>;\n\n stride_iterator(I first, I last, Step step = {})\n : data{first, last, step}\n { \n assert(step() > 0);\n }\n\n stride_iterator(I last, Step step = {})\n : stride_iterator(last, last, step)\n { }\n\n\n \/\/ Returns the underlying iterator\n I base() const { return first(); }\n \n \/\/ Returns the advance action.\n Step step_func() const { return inc(); }\n\n \/\/ Returns the step or stride for the iterator.\n constexpr Difference_type<I> step() const { return inc()(); }\n \n \n \/\/ Readable\n Iterator_reference<I> operator*() const;\n using Base::operator[];\n\n \/\/ Incrementable\n stride_iterator& operator++();\n using Base::operator++;\n \n \/\/ Decrementable\n stride_iterator& operator--();\n using Base::operator--;\n\n \/\/ Advance\n stride_iterator& operator+=(Difference_type<I> n);\n stride_iterator& operator-=(Difference_type<I> n);\n\n private:\n I& first() { return std::get<0>(data); }\n const I& first() const { return std::get<0>(data); }\n \n I& last() { return std::get<1>(data); }\n const I& last() const { return std::get<1>(data); }\n\n const Step& inc() const { return std::get<2>(data); }\n \n private:\n std::tuple<I, I, Step> data;\n };\n\n\n template <typename I, typename S>\n inline Iterator_reference<I> \n stride_iterator<I, S>::operator*() const \n { \n assert(first() != last());\n return *first(); \n }\n\n\n template <typename I, typename S>\n inline auto \n stride_iterator<I, S>::operator++() -> stride_iterator&\n { \n assert(first() != last());\n first() = bounded_next(first(), step(), last());\n return *this; \n }\n\n template <typename I, typename S>\n inline auto \n stride_iterator<I, S>::operator--() -> stride_iterator&\n { \n first() = prev(first(), step());\n return *this; \n }\n\n template <typename I, typename S>\n inline auto \n stride_iterator<I, S>::operator+=(Difference_type<I> n)\n -> stride_iterator&\n {\n assert(first() != last());\n first() = bounded_next(first(), step() * n, last());\n return *this;\n }\n\n template <typename I, typename S>\n inline auto \n stride_iterator<I, S>::operator-=(Difference_type<I> n) \n -> stride_iterator&\n { \n first() *= prev(first(), step * n);\n return *this; \n }\n\n\n \/\/ Equality_comparable\n \/\/\n \/\/ Two stride iterators are equal if they refer to the same object and have\n \/\/ the same step function.\n template <typename I, typename S>\n inline bool \n operator==(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() == b.base();\n }\n\n template <typename I, typename S>\n inline bool \n operator!=(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return !(a == b);\n }\n \n\n \/\/ Totally_ordered\n \/\/\n \/\/ The ordering of stride iterators is defined by the ordering of the \n \/\/ underlying iterator. The order is undefined if the iterators have different\n \/\/ step functions.\n template <typename I, typename S>\n inline bool \n operator<(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() < b.base();\n }\n\n template <typename I, typename S>\n inline bool \n operator>(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() > b.base();\n }\n\n template <typename I, typename S>\n inline bool \n operator<=(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() <= b.base();\n }\n\n template <typename I, typename S>\n inline bool \n operator>=(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() >= b.base();\n }\n \n\n \/\/ Difference\n \/\/\n \/\/ The difference between two stride iterators is undefined if a and b have\n \/\/ different step functions.\n template <typename I, typename S>\n inline Difference_type<I> \n operator-(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n {\n return (a.base() - b.base()) \/ a.stride();\n }\n\n\n\n \/\/ Make stride iterator\n \/\/\n \/\/ Construct a stride iterator with some predetermined stride or step. There\n \/\/ are four overloads of this function:\n \/\/\n \/\/ make_stride_iterator(first, last, n) ~> i\n \/\/ make_stride_iterator(last, n) ~> i\n \/\/ make_stride_iterator(first, last, step) ~> i\n \/\/ make_stride_iterator(last, step) ~> i\n \/\/\n \/\/ The first two overloads construct stride iterators using a constant step n\n \/\/ where n is the difference type of first and last. These are the most\n \/\/ commonly used overloads.\n \/\/\n \/\/ The last two overloads construct stride iterators whose step function is\n \/\/ given explicitly. These can be used to construct iteratos functions with\n \/\/ dynamic strides or whose strides are constant expressions. For example:\n \/\/\n \/\/ auto i = make_stride_iterator(f, l, literal(2));\n \/\/\n \/\/ This creates a stride iterator whose stride is the literal value 2 (i.e.,\n \/\/ a constant expression).\n \n template <typename I>\n inline auto make_stride_iterator(I first, I last, Difference_type<I> n)\n -> Requires<Iterator<I>(), stride_iterator<I>>\n {\n using F = constant_function<Difference_type<I>>;\n return {first, last, F{n}};\n }\n\n template <typename I>\n inline auto make_stride_iterator(I last, Difference_type<I> n)\n -> Requires<Iterator<I>(), stride_iterator<I>>\n {\n using F = constant_function<Difference_type<I>>;\n return {last, F{n}};\n }\n\n template <typename I, typename Step>\n inline auto make_stride_iterator(I first, I last, Step step) \n -> Requires<Iterator<I>() && Function<Step>(), stride_iterator<I, Step>>\n {\n return {first, last, step};\n }\n\n template <typename I, typename Step>\n inline auto make_stride_iterator(I last, Step step)\n -> Requires<Iterator<I>() && Function<Step>(), stride_iterator<I, Step>>\n {\n return {last, step};\n }\n\n} \/\/ namespace origin\n\n#endif\n<commit_msg>Small doc fix.<commit_after>\/\/ Copyright (c) 2008-2010 Kent State University\n\/\/ Copyright (c) 2011-2012 Texas S&M University\n\/\/\n\/\/ This file is distributed under the MIT License. See the accompanying file\n\/\/ LICENSE.txt or http:\/\/www.opensource.org\/licenses\/mit-license.php for terms\n\/\/ and conditions.\n\n#ifndef ORIGIN_ITERATOR_STRIDE_HPP\n#define ORIGIN_ITERATOR_STRIDE_HPP\n\n#include <origin\/iterator\/facade.hpp>\n\nnamespace origin\n{\n template <typename I, typename S>\n class stride_iterator;\n\n\n \/\/ An alias for the facade used by the stride iterator.\n template <typename I, typename S>\n using Stride_iterator_facade = iterator_facade<stride_iterator<I, S>, I>;\n\n\n \/\/ Stride iterator\n \/\/\n \/\/ The stride iterator adaptor wraps an underlying iterator in such a way\n \/\/ that advancing a single stride (or step) will cause the underlying iterator\n \/\/ to advance a specified number of steps. \n \/\/\n \/\/ The step function for a stride iterator must return a value greater than 0.\n \/\/ S step of 0 will not result in bounded ranges. Also note that that\n \/\/ reversing a stride iterator can be achieved using a reverse iterator\n \/\/ adaptor.\n \/\/\n \/\/ Note: The bidirectional iterator operations are unchecked, meaning it\n \/\/ is possible to access elements that are before the first element of\n \/\/ the initial iterator value. Ensuring that these operations are checked\n \/\/ would require the addition of an extra iterator (the first iterator) and\n \/\/ checking those operations.\n \/\/\n \/\/ Invariants:\n \/\/ this->step() > 0\n template<typename I, typename Step = constant_function<Difference_type<I>>>\n class stride_iterator : public Stride_iterator_facade<I, Step>\n {\n static_assert(Iterator<I>(), \"\");\n static_assert(Function<Step>(), \"\");\n public:\n using Base = Stride_iterator_facade<I, Step>;\n\n stride_iterator(I first, I last, Step step = {})\n : data{first, last, step}\n { \n assert(step() > 0);\n }\n\n stride_iterator(I last, Step step = {})\n : stride_iterator(last, last, step)\n { }\n\n\n \/\/ Returns the underlying iterator\n I base() const { return first(); }\n \n \/\/ Returns the advance action.\n Step step_func() const { return inc(); }\n\n \/\/ Returns the step or stride for the iterator.\n constexpr Difference_type<I> step() const { return inc()(); }\n \n \n \/\/ Readable\n Iterator_reference<I> operator*() const;\n using Base::operator[];\n\n \/\/ Incrementable\n stride_iterator& operator++();\n using Base::operator++;\n \n \/\/ Decrementable\n stride_iterator& operator--();\n using Base::operator--;\n\n \/\/ Advance\n stride_iterator& operator+=(Difference_type<I> n);\n stride_iterator& operator-=(Difference_type<I> n);\n\n private:\n I& first() { return std::get<0>(data); }\n const I& first() const { return std::get<0>(data); }\n \n I& last() { return std::get<1>(data); }\n const I& last() const { return std::get<1>(data); }\n\n const Step& inc() const { return std::get<2>(data); }\n \n private:\n std::tuple<I, I, Step> data;\n };\n\n\n template <typename I, typename S>\n inline Iterator_reference<I> \n stride_iterator<I, S>::operator*() const \n { \n assert(first() != last());\n return *first(); \n }\n\n\n template <typename I, typename S>\n inline auto \n stride_iterator<I, S>::operator++() -> stride_iterator&\n { \n assert(first() != last());\n first() = bounded_next(first(), step(), last());\n return *this; \n }\n\n template <typename I, typename S>\n inline auto \n stride_iterator<I, S>::operator--() -> stride_iterator&\n { \n first() = prev(first(), step());\n return *this; \n }\n\n template <typename I, typename S>\n inline auto \n stride_iterator<I, S>::operator+=(Difference_type<I> n)\n -> stride_iterator&\n {\n assert(first() != last());\n first() = bounded_next(first(), step() * n, last());\n return *this;\n }\n\n template <typename I, typename S>\n inline auto \n stride_iterator<I, S>::operator-=(Difference_type<I> n) \n -> stride_iterator&\n { \n first() *= prev(first(), step * n);\n return *this; \n }\n\n\n \/\/ Equality_comparable\n \/\/\n \/\/ Two stride iterators are equal if they refer to the same object and have\n \/\/ the same step function.\n template <typename I, typename S>\n inline bool \n operator==(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() == b.base();\n }\n\n template <typename I, typename S>\n inline bool \n operator!=(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return !(a == b);\n }\n \n\n \/\/ Totally_ordered\n \/\/\n \/\/ The ordering of stride iterators is defined by the ordering of the \n \/\/ underlying iterator. The order is undefined if the iterators have different\n \/\/ step functions.\n template <typename I, typename S>\n inline bool \n operator<(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() < b.base();\n }\n\n template <typename I, typename S>\n inline bool \n operator>(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() > b.base();\n }\n\n template <typename I, typename S>\n inline bool \n operator<=(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() <= b.base();\n }\n\n template <typename I, typename S>\n inline bool \n operator>=(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n { \n return a.base() >= b.base();\n }\n \n\n \/\/ Difference\n \/\/\n \/\/ The difference between two stride iterators is undefined if a and b have\n \/\/ different step functions.\n template <typename I, typename S>\n inline Difference_type<I> \n operator-(const stride_iterator<I, S>& a, const stride_iterator<I, S>& b)\n {\n return (a.base() - b.base()) \/ a.stride();\n }\n\n\n\n \/\/ Make stride iterator \n \/\/\n \/\/ Construct a stride iterator with some predetermined stride or step. There\n \/\/ are four overloads of this function:\n \/\/\n \/\/ make_stride_iterator(first, last, n) ~> i\n \/\/ make_stride_iterator(last, n) ~> i\n \/\/ make_stride_iterator(first, last, step) ~> i\n \/\/ make_stride_iterator(last, step) ~> i\n \/\/\n \/\/ The first two overloads construct stride iterators using a constant step n\n \/\/ where n is the difference type of first and last. These are the most\n \/\/ commonly used overloads.\n \/\/\n \/\/ The last two overloads construct stride iterators whose step function is\n \/\/ given explicitly. These can be used to construct iteratos functions with\n \/\/ dynamic strides or whose strides are constant expressions. For example:\n \/\/\n \/\/ auto i = make_stride_iterator(f, l, integral_constant<int, 2>{});\n \/\/\n \/\/ This creates a stride iterator whose stride is the literal value 2 (i.e.,\n \/\/ a constant expression).\n \n template <typename I>\n inline auto make_stride_iterator(I first, I last, Difference_type<I> n)\n -> Requires<Iterator<I>(), stride_iterator<I>>\n {\n using F = constant_function<Difference_type<I>>;\n return {first, last, F{n}};\n }\n\n template <typename I>\n inline auto make_stride_iterator(I last, Difference_type<I> n)\n -> Requires<Iterator<I>(), stride_iterator<I>>\n {\n using F = constant_function<Difference_type<I>>;\n return {last, F{n}};\n }\n\n template <typename I, typename Step>\n inline auto make_stride_iterator(I first, I last, Step step) \n -> Requires<Iterator<I>() && Function<Step>(), stride_iterator<I, Step>>\n {\n return {first, last, step};\n }\n\n template <typename I, typename Step>\n inline auto make_stride_iterator(I last, Step step)\n -> Requires<Iterator<I>() && Function<Step>(), stride_iterator<I, Step>>\n {\n return {last, step};\n }\n\n} \/\/ namespace origin\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Picasso - a vector graphics library\n * \n * Copyright (C) 2014 Zhang Ji Peng\n * Contact: onecoolx@gmail.com\n *\/\n\n#include \"common.h\"\n\n#include \"gfx_math.h\"\n#include \"gfx_gradient_adapter.h\"\n#include \"gfx_line_generator.h\"\n\nnamespace gfx {\n\n\/\/ gradient functions\n\n\/\/ gradient_x\nclass gradient_x\n{\npublic:\n void init(scalar, scalar, scalar) { }\n static int calculate(int x, int, int) { return x; }\n};\n\n\/\/ gradient_conic\nclass gradient_conic\n{\npublic:\n void init(scalar, scalar, scalar) { }\n static int calculate(int x, int y, int d)\n {\n return uround(Fabs(Atan2(INT_TO_SCALAR(y), INT_TO_SCALAR(x))) * INT_TO_SCALAR(d) * _1divPI);\n }\n};\n\nclass gradient_conic_vg\n{\npublic:\n void init(scalar, scalar, scalar) { }\n static int calculate(int x, int y, int d)\n {\n scalar a = Atan2(INT_TO_SCALAR(y), INT_TO_SCALAR(x));\n if (a < 0) a = _2PI + a;\n return round(a * INT_TO_SCALAR(d) * _1div2PI);\n }\n};\n\n\n\/\/ gradient_radial\nclass gradient_radial\n{\npublic:\n void init(scalar, scalar, scalar) { }\n static int calculate(int x, int y, int d)\n {\n return (int)fast_sqrt(x*x + y*y);\n }\n};\n\n\/\/ gradient_radial_focus\nclass gradient_radial_focus\n{\npublic:\n gradient_radial_focus()\n : m_r(100 * gradient_subpixel_scale)\n , m_fx(0)\n , m_fy(0)\n {\n update_values();\n }\n\n void init(scalar r, scalar fx, scalar fy)\n {\n m_r = iround(r * gradient_subpixel_scale);\n m_fx = iround(fx * gradient_subpixel_scale);\n m_fy = iround(fy * gradient_subpixel_scale);\n update_values();\n }\n\n int calculate(int x, int y, int) const\n {\n scalar dx = INT_TO_SCALAR(x - m_fx);\n scalar dy = INT_TO_SCALAR(y - m_fy);\n scalar d2 = dx * m_fy - dy * m_fx;\n scalar d3 = m_r2 * (dx * dx + dy * dy) - d2 * d2;\n return iround((dx * m_fx + dy * m_fy + Sqrt(Fabs(d3))) * m_mul);\n }\n\nprivate:\n void update_values(void)\n {\n \/\/ Calculate the invariant values. In case the focal center\n \/\/ lies exactly on the gradient circle the divisor degenerates\n \/\/ into zero. In this case we just move the focal center by\n \/\/ one subpixel unit possibly in the direction to the origin (0,0)\n \/\/ and calculate the values again.\n \n m_r2 = INT_TO_SCALAR(m_r) * INT_TO_SCALAR(m_r);\n m_fx2 = INT_TO_SCALAR(m_fx) * INT_TO_SCALAR(m_fx);\n m_fy2 = INT_TO_SCALAR(m_fy) * INT_TO_SCALAR(m_fy);\n scalar d = (m_r2 - (m_fx2 + m_fy2));\n if (d == INT_TO_SCALAR(0)) {\n if (m_fx) {\n if (m_fx < 0)\n ++m_fx;\n else\n --m_fx;\n }\n\n if (m_fy) {\n if (m_fy < 0)\n ++m_fy;\n else\n --m_fy;\n }\n\n m_fx2 = INT_TO_SCALAR(m_fx) * INT_TO_SCALAR(m_fx);\n m_fy2 = INT_TO_SCALAR(m_fy) * INT_TO_SCALAR(m_fy);\n d = (m_r2 - (m_fx2 + m_fy2));\n }\n m_mul = m_r \/ d;\n }\n\nprivate:\n int m_r;\n int m_fx;\n int m_fy;\n scalar m_r2;\n scalar m_fx2;\n scalar m_fy2;\n scalar m_mul;\n};\n\n\/\/ gradient adaptors\n\n\/\/ gradient once adaptor\ntemplate <typename GradientFunc>\nclass gradient_pad_adaptor\n{\npublic:\n gradient_pad_adaptor(const GradientFunc& gradient)\n : m_gradient(&gradient)\n {\n }\n\n int calculate(int x, int y, int d) const\n {\n int ret = m_gradient->calculate(x, y, d);\n if (ret < 0) ret = 0;\n if (ret > d) ret = d;\n return ret;\n }\n\nprivate:\n const GradientFunc* m_gradient;\n};\n\n\/\/ gradient repeat adaptor\ntemplate <typename GradientFunc>\nclass gradient_repeat_adaptor\n{\npublic:\n gradient_repeat_adaptor(const GradientFunc& gradient)\n : m_gradient(&gradient)\n {\n }\n\n int calculate(int x, int y, int d) const\n {\n int ret = m_gradient->calculate(x, y, d) % d;\n if (ret < 0) ret += d;\n return ret;\n }\n\nprivate:\n const GradientFunc* m_gradient;\n};\n\n\/\/ gradient reflect adaptor\ntemplate <typename GradientFunc>\nclass gradient_reflect_adaptor\n{\npublic:\n gradient_reflect_adaptor(const GradientFunc& gradient)\n : m_gradient(&gradient)\n {\n }\n\n int calculate(int x, int y, int d) const\n {\n int d2 = d << 1;\n int ret = m_gradient->calculate(x, y, d) % d2;\n if (ret < 0) ret += d2;\n if (ret >= d) ret = d2 - ret;\n return ret;\n }\n\nprivate:\n const GradientFunc* m_gradient;\n};\n\n\n\/\/ gradient wrapper implements\ntemplate <typename GradientFunc, typename Adaptor>\nclass gfx_gradient : public gfx_gradient_wrapper\n{\npublic:\n gfx_gradient()\n : m_gradient()\n , m_adaptor(m_gradient) \n { \n }\n\n virtual void init(scalar r, scalar x, scalar y)\n {\n m_gradient.init(r, x, y);\n }\n\n virtual int calculate(int x, int y, int d) const \n {\n return m_adaptor.calculate(x, y, d);\n }\n\nprivate:\n GradientFunc m_gradient;\n Adaptor m_adaptor;\n};\n\n\/\/ gfx gradient table\n\n\/\/ rgba8 color interpolator\nstruct color_interpolator\n{\npublic:\n typedef rgba8 color_type;\n\n color_interpolator(const color_type& c1, const color_type& c2, unsigned len)\n : r(c1.r, c2.r, len)\n , g(c1.g, c2.g, len)\n , b(c1.b, c2.b, len)\n , a(c1.a, c2.a, len)\n {\n }\n\n void operator ++ ()\n {\n ++r; ++g; ++b; ++a;\n }\n\n color_type color(void) const\n {\n return color_type(r.y(), g.y(), b.y(), a.y());\n }\n\nprivate:\n gfx_dda_line_interpolator<14> r;\n gfx_dda_line_interpolator<14> g;\n gfx_dda_line_interpolator<14> b;\n gfx_dda_line_interpolator<14> a;\n};\n\nvoid gfx_gradient_table::build_table(void)\n{\n quick_sort(m_color_profile, offset_less);\n m_color_profile.cut_at(remove_duplicates(m_color_profile, offset_equal));\n\n if (m_color_profile.size() >= 2) {\n unsigned int i;\n unsigned int start = uround(m_color_profile[0].offset * color_table_size);\n unsigned int end = 0;\n color_type c = m_color_profile[0].color;\n\n for (i = 0; i < start; i++) {\n m_color_table[i] = c;\n }\n\n for (i = 1; i < m_color_profile.size(); i++) {\n end = uround(m_color_profile[i].offset * color_table_size);\n color_interpolator ci(m_color_profile[i-1].color, \n m_color_profile[i].color, end - start + 1);\n while (start < end) {\n m_color_table[start] = ci.color();\n ++ci;\n ++start;\n }\n }\n\n c = m_color_profile.last().color;\n\n for (; end < m_color_table.size(); end++) {\n m_color_table[end] = c;\n }\n }\n}\n\n\/\/ gfx gradient adapter\nvoid gfx_gradient_adapter::init_linear(int spread, scalar x1, scalar y1, scalar x2, scalar y2)\n{\n if (!m_wrapper) {\n switch (spread) {\n case SPREAD_PAD:\n m_wrapper = new gfx_gradient<gradient_x, gradient_pad_adaptor<gradient_x> >;\n break;\n case SPREAD_REPEAT:\n m_wrapper = new gfx_gradient<gradient_x, gradient_repeat_adaptor<gradient_x> >;\n break;\n case SPREAD_REFLECT:\n m_wrapper = new gfx_gradient<gradient_x, gradient_reflect_adaptor<gradient_x> >;\n break;\n };\n\n if (!m_wrapper)\n return;\n \n scalar len = calc_distance(x1, y1, x2, y2);\n\n gfx_trans_affine mtx;\n if (len) {\n if (x2 < x1)\n mtx.rotate(PI - Asin((y2 - y1) \/ len));\n else\n mtx.rotate(Asin((y2 - y1) \/ len));\n } else\n len = FLT_TO_SCALAR(2.0f); \/\/ len can not be zero\n\n mtx.translate(x1, y1);\n\n m_start = FLT_TO_SCALAR(0.0f);\n m_length = len;\n m_matrix = mtx;\n }\n}\n\nvoid gfx_gradient_adapter::init_radial(int spread, scalar x1, scalar y1, scalar radius1, \n scalar x2, scalar y2, scalar radius2)\n{\n if (!m_wrapper) {\n if ((x1 == x2) && (y1 == y2)) {\n switch (spread) {\n case SPREAD_PAD:\n m_wrapper = new gfx_gradient<gradient_radial, \n gradient_pad_adaptor<gradient_radial> >;\n break;\n case SPREAD_REPEAT:\n m_wrapper = new gfx_gradient<gradient_radial, \n gradient_repeat_adaptor<gradient_radial> >;\n break;\n case SPREAD_REFLECT:\n m_wrapper = new gfx_gradient<gradient_radial, \n gradient_reflect_adaptor<gradient_radial> >;\n break;\n }\n } else {\n switch (spread) {\n case SPREAD_PAD:\n m_wrapper = new gfx_gradient<gradient_radial_focus, \n gradient_pad_adaptor<gradient_radial_focus> >;\n break;\n case SPREAD_REPEAT:\n m_wrapper = new gfx_gradient<gradient_radial_focus, \n gradient_repeat_adaptor<gradient_radial_focus> >;\n break;\n case SPREAD_REFLECT:\n m_wrapper = new gfx_gradient<gradient_radial_focus, \n gradient_reflect_adaptor<gradient_radial_focus> >;\n break;\n }\n\n }\n\n if (!m_wrapper)\n return;\n\n scalar len = Fabs(radius2);\n scalar fx = x1 - x2;\n scalar fy = y1 - y2;\n\n m_wrapper->init(len, fx, fy);\n\n if (!len) \n len = FLT_TO_SCALAR(2.0f); \/\/ len can not be zero\n\n gfx_trans_affine mtx;\n mtx.translate(x1 - fx, y1 - fy);\n\n\n m_start = Fabs(radius1);\n m_length = len;\n m_matrix = mtx;\n }\n}\n\nvoid gfx_gradient_adapter::init_conic(int spread, scalar x, scalar y, scalar angle)\n{\n if (!m_wrapper) {\n if (spread == SPREAD_REFLECT) {\n m_wrapper = new gfx_gradient<gradient_conic, gradient_reflect_adaptor<gradient_conic> >;\n } else {\n m_wrapper = new gfx_gradient<gradient_conic_vg, gradient_pad_adaptor<gradient_conic_vg> >;\n }\n\n if (!m_wrapper) \n return;\n\n gfx_trans_affine mtx;\n mtx.translate(x, y);\n mtx.translate(-x, -y);\n mtx.rotate(angle);\n mtx.translate(x, y);\n\n m_start = INT_TO_SCALAR(0);\n m_length = INT_TO_SCALAR(128);\n m_matrix = mtx;\n }\n}\n\n}\n<commit_msg>fix win32 gyp build<commit_after>\/* Picasso - a vector graphics library\n * \n * Copyright (C) 2014 Zhang Ji Peng\n * Contact: onecoolx@gmail.com\n *\/\n\n#include \"common.h\"\n\n#include \"gfx_math.h\"\n#include \"gfx_gradient_adapter.h\"\n#include \"gfx_line_generator.h\"\n\nnamespace gfx {\n\n\/\/ gradient functions\n\n\/\/ gradient_x\nclass gradient_x\n{\npublic:\n void init(scalar, scalar, scalar) { }\n static int calculate(int x, int, int) { return x; }\n};\n\n\/\/ gradient_conic\nclass gradient_conic\n{\npublic:\n void init(scalar, scalar, scalar) { }\n static int calculate(int x, int y, int d)\n {\n return uround(Fabs(Atan2(INT_TO_SCALAR(y), INT_TO_SCALAR(x))) * INT_TO_SCALAR(d) * _1divPI);\n }\n};\n\nclass gradient_conic_vg\n{\npublic:\n void init(scalar, scalar, scalar) { }\n static int calculate(int x, int y, int d)\n {\n scalar a = Atan2(INT_TO_SCALAR(y), INT_TO_SCALAR(x));\n if (a < 0) a = _2PI + a;\n return iround(a * INT_TO_SCALAR(d) * _1div2PI);\n }\n};\n\n\n\/\/ gradient_radial\nclass gradient_radial\n{\npublic:\n void init(scalar, scalar, scalar) { }\n static int calculate(int x, int y, int d)\n {\n return (int)fast_sqrt(x*x + y*y);\n }\n};\n\n\/\/ gradient_radial_focus\nclass gradient_radial_focus\n{\npublic:\n gradient_radial_focus()\n : m_r(100 * gradient_subpixel_scale)\n , m_fx(0)\n , m_fy(0)\n {\n update_values();\n }\n\n void init(scalar r, scalar fx, scalar fy)\n {\n m_r = iround(r * gradient_subpixel_scale);\n m_fx = iround(fx * gradient_subpixel_scale);\n m_fy = iround(fy * gradient_subpixel_scale);\n update_values();\n }\n\n int calculate(int x, int y, int) const\n {\n scalar dx = INT_TO_SCALAR(x - m_fx);\n scalar dy = INT_TO_SCALAR(y - m_fy);\n scalar d2 = dx * m_fy - dy * m_fx;\n scalar d3 = m_r2 * (dx * dx + dy * dy) - d2 * d2;\n return iround((dx * m_fx + dy * m_fy + Sqrt(Fabs(d3))) * m_mul);\n }\n\nprivate:\n void update_values(void)\n {\n \/\/ Calculate the invariant values. In case the focal center\n \/\/ lies exactly on the gradient circle the divisor degenerates\n \/\/ into zero. In this case we just move the focal center by\n \/\/ one subpixel unit possibly in the direction to the origin (0,0)\n \/\/ and calculate the values again.\n \n m_r2 = INT_TO_SCALAR(m_r) * INT_TO_SCALAR(m_r);\n m_fx2 = INT_TO_SCALAR(m_fx) * INT_TO_SCALAR(m_fx);\n m_fy2 = INT_TO_SCALAR(m_fy) * INT_TO_SCALAR(m_fy);\n scalar d = (m_r2 - (m_fx2 + m_fy2));\n if (d == INT_TO_SCALAR(0)) {\n if (m_fx) {\n if (m_fx < 0)\n ++m_fx;\n else\n --m_fx;\n }\n\n if (m_fy) {\n if (m_fy < 0)\n ++m_fy;\n else\n --m_fy;\n }\n\n m_fx2 = INT_TO_SCALAR(m_fx) * INT_TO_SCALAR(m_fx);\n m_fy2 = INT_TO_SCALAR(m_fy) * INT_TO_SCALAR(m_fy);\n d = (m_r2 - (m_fx2 + m_fy2));\n }\n m_mul = m_r \/ d;\n }\n\nprivate:\n int m_r;\n int m_fx;\n int m_fy;\n scalar m_r2;\n scalar m_fx2;\n scalar m_fy2;\n scalar m_mul;\n};\n\n\/\/ gradient adaptors\n\n\/\/ gradient once adaptor\ntemplate <typename GradientFunc>\nclass gradient_pad_adaptor\n{\npublic:\n gradient_pad_adaptor(const GradientFunc& gradient)\n : m_gradient(&gradient)\n {\n }\n\n int calculate(int x, int y, int d) const\n {\n int ret = m_gradient->calculate(x, y, d);\n if (ret < 0) ret = 0;\n if (ret > d) ret = d;\n return ret;\n }\n\nprivate:\n const GradientFunc* m_gradient;\n};\n\n\/\/ gradient repeat adaptor\ntemplate <typename GradientFunc>\nclass gradient_repeat_adaptor\n{\npublic:\n gradient_repeat_adaptor(const GradientFunc& gradient)\n : m_gradient(&gradient)\n {\n }\n\n int calculate(int x, int y, int d) const\n {\n int ret = m_gradient->calculate(x, y, d) % d;\n if (ret < 0) ret += d;\n return ret;\n }\n\nprivate:\n const GradientFunc* m_gradient;\n};\n\n\/\/ gradient reflect adaptor\ntemplate <typename GradientFunc>\nclass gradient_reflect_adaptor\n{\npublic:\n gradient_reflect_adaptor(const GradientFunc& gradient)\n : m_gradient(&gradient)\n {\n }\n\n int calculate(int x, int y, int d) const\n {\n int d2 = d << 1;\n int ret = m_gradient->calculate(x, y, d) % d2;\n if (ret < 0) ret += d2;\n if (ret >= d) ret = d2 - ret;\n return ret;\n }\n\nprivate:\n const GradientFunc* m_gradient;\n};\n\n\n\/\/ gradient wrapper implements\ntemplate <typename GradientFunc, typename Adaptor>\nclass gfx_gradient : public gfx_gradient_wrapper\n{\npublic:\n gfx_gradient()\n : m_gradient()\n , m_adaptor(m_gradient) \n { \n }\n\n virtual void init(scalar r, scalar x, scalar y)\n {\n m_gradient.init(r, x, y);\n }\n\n virtual int calculate(int x, int y, int d) const \n {\n return m_adaptor.calculate(x, y, d);\n }\n\nprivate:\n GradientFunc m_gradient;\n Adaptor m_adaptor;\n};\n\n\/\/ gfx gradient table\n\n\/\/ rgba8 color interpolator\nstruct color_interpolator\n{\npublic:\n typedef rgba8 color_type;\n\n color_interpolator(const color_type& c1, const color_type& c2, unsigned len)\n : r(c1.r, c2.r, len)\n , g(c1.g, c2.g, len)\n , b(c1.b, c2.b, len)\n , a(c1.a, c2.a, len)\n {\n }\n\n void operator ++ ()\n {\n ++r; ++g; ++b; ++a;\n }\n\n color_type color(void) const\n {\n return color_type(r.y(), g.y(), b.y(), a.y());\n }\n\nprivate:\n gfx_dda_line_interpolator<14> r;\n gfx_dda_line_interpolator<14> g;\n gfx_dda_line_interpolator<14> b;\n gfx_dda_line_interpolator<14> a;\n};\n\nvoid gfx_gradient_table::build_table(void)\n{\n quick_sort(m_color_profile, offset_less);\n m_color_profile.cut_at(remove_duplicates(m_color_profile, offset_equal));\n\n if (m_color_profile.size() >= 2) {\n unsigned int i;\n unsigned int start = uround(m_color_profile[0].offset * color_table_size);\n unsigned int end = 0;\n color_type c = m_color_profile[0].color;\n\n for (i = 0; i < start; i++) {\n m_color_table[i] = c;\n }\n\n for (i = 1; i < m_color_profile.size(); i++) {\n end = uround(m_color_profile[i].offset * color_table_size);\n color_interpolator ci(m_color_profile[i-1].color, \n m_color_profile[i].color, end - start + 1);\n while (start < end) {\n m_color_table[start] = ci.color();\n ++ci;\n ++start;\n }\n }\n\n c = m_color_profile.last().color;\n\n for (; end < m_color_table.size(); end++) {\n m_color_table[end] = c;\n }\n }\n}\n\n\/\/ gfx gradient adapter\nvoid gfx_gradient_adapter::init_linear(int spread, scalar x1, scalar y1, scalar x2, scalar y2)\n{\n if (!m_wrapper) {\n switch (spread) {\n case SPREAD_PAD:\n m_wrapper = new gfx_gradient<gradient_x, gradient_pad_adaptor<gradient_x> >;\n break;\n case SPREAD_REPEAT:\n m_wrapper = new gfx_gradient<gradient_x, gradient_repeat_adaptor<gradient_x> >;\n break;\n case SPREAD_REFLECT:\n m_wrapper = new gfx_gradient<gradient_x, gradient_reflect_adaptor<gradient_x> >;\n break;\n };\n\n if (!m_wrapper)\n return;\n \n scalar len = calc_distance(x1, y1, x2, y2);\n\n gfx_trans_affine mtx;\n if (len) {\n if (x2 < x1)\n mtx.rotate(PI - Asin((y2 - y1) \/ len));\n else\n mtx.rotate(Asin((y2 - y1) \/ len));\n } else\n len = FLT_TO_SCALAR(2.0f); \/\/ len can not be zero\n\n mtx.translate(x1, y1);\n\n m_start = FLT_TO_SCALAR(0.0f);\n m_length = len;\n m_matrix = mtx;\n }\n}\n\nvoid gfx_gradient_adapter::init_radial(int spread, scalar x1, scalar y1, scalar radius1, \n scalar x2, scalar y2, scalar radius2)\n{\n if (!m_wrapper) {\n if ((x1 == x2) && (y1 == y2)) {\n switch (spread) {\n case SPREAD_PAD:\n m_wrapper = new gfx_gradient<gradient_radial, \n gradient_pad_adaptor<gradient_radial> >;\n break;\n case SPREAD_REPEAT:\n m_wrapper = new gfx_gradient<gradient_radial, \n gradient_repeat_adaptor<gradient_radial> >;\n break;\n case SPREAD_REFLECT:\n m_wrapper = new gfx_gradient<gradient_radial, \n gradient_reflect_adaptor<gradient_radial> >;\n break;\n }\n } else {\n switch (spread) {\n case SPREAD_PAD:\n m_wrapper = new gfx_gradient<gradient_radial_focus, \n gradient_pad_adaptor<gradient_radial_focus> >;\n break;\n case SPREAD_REPEAT:\n m_wrapper = new gfx_gradient<gradient_radial_focus, \n gradient_repeat_adaptor<gradient_radial_focus> >;\n break;\n case SPREAD_REFLECT:\n m_wrapper = new gfx_gradient<gradient_radial_focus, \n gradient_reflect_adaptor<gradient_radial_focus> >;\n break;\n }\n\n }\n\n if (!m_wrapper)\n return;\n\n scalar len = Fabs(radius2);\n scalar fx = x1 - x2;\n scalar fy = y1 - y2;\n\n m_wrapper->init(len, fx, fy);\n\n if (!len) \n len = FLT_TO_SCALAR(2.0f); \/\/ len can not be zero\n\n gfx_trans_affine mtx;\n mtx.translate(x1 - fx, y1 - fy);\n\n\n m_start = Fabs(radius1);\n m_length = len;\n m_matrix = mtx;\n }\n}\n\nvoid gfx_gradient_adapter::init_conic(int spread, scalar x, scalar y, scalar angle)\n{\n if (!m_wrapper) {\n if (spread == SPREAD_REFLECT) {\n m_wrapper = new gfx_gradient<gradient_conic, gradient_reflect_adaptor<gradient_conic> >;\n } else {\n m_wrapper = new gfx_gradient<gradient_conic_vg, gradient_pad_adaptor<gradient_conic_vg> >;\n }\n\n if (!m_wrapper) \n return;\n\n gfx_trans_affine mtx;\n mtx.translate(x, y);\n mtx.translate(-x, -y);\n mtx.rotate(angle);\n mtx.translate(x, y);\n\n m_start = INT_TO_SCALAR(0);\n m_length = INT_TO_SCALAR(128);\n m_matrix = mtx;\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"csv_exporter.h\"\r\n\r\n\/*\r\n *\r\n * Class doc can be found in csv_exporter.h\r\n *\/\r\nCSV_Exporter::CSV_Exporter()\r\n{\r\n \/* EMPTY - NO NEED *\/\r\n}\r\n\r\n\/**\r\n * @brief This method will generate the CSV file (Targeting google calendar import)\r\n * it will create a full Semester calendar based on the users input (@param cal)\r\n * and the @calSched wich holdes all the courses in \"this\" semester.\r\n * @param calSched - Holdes all the Courses and there info\r\n * @param cal - The Calendar dialog witch holdes the starting date and the eand date.\r\n * @return - True if *all* went well, false if something on the way went wrong.\r\n *\/\r\nbool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *cal, calendarExam *exams)\r\n{\r\n if ((cal == NULL) || (calSched == NULL)) \/\/pointers checking!\r\n return false;\r\n\r\n if (calSched->getCourses().isEmpty())\r\n return false;\r\n\r\n qDebug() << Q_FUNC_INFO << \"Getting path for csv file from user...\";\r\n\r\n QString filePath = getFileFath();\r\n if(filePath == NULL) \/\/User canceled from the file explorer popup\r\n {\r\n qDebug() << Q_FUNC_INFO << \"CSV : User pressed Cancel... returning false\";\r\n return false;\r\n }\r\n qDebug() << Q_FUNC_INFO << \"CSV : User Chose: \" << filePath;\r\n qDebug() << Q_FUNC_INFO << \"CSV : Atempting to export the Schedule...\";\r\n\r\n QFile file(filePath);\r\n if(!file.open(QIODevice::ReadWrite | QIODevice::Truncate)) \/\/Incase unable to open the file (binary mode - \\n will not be converted on \"Windows\")\r\n {\r\n QMessageBox msgBox;\r\n msgBox.setIcon(QMessageBox::Critical);\r\n msgBox.setText(QObject::tr(\"Unable to open or create the file.\\nExporting Failed\"));\r\n msgBox.exec();\r\n qCritical() << Q_FUNC_INFO << \"unable to open\/create the file... maybe permissions error.\";\r\n return false;\r\n }\r\n\r\n QTextStream out(&file); \/\/The output streem.\r\n out.setCodec(\"UTF-8\"); \/\/Unicode 8\r\n\r\n out << CSV_CALENDAR_HEADER << \"\\n\"; \/\/ macro in header file\r\n\r\n for (calendarCourse *coursePtr: (calSched->getCourses())) \/\/main loop - running though all courses\r\n {\r\n \/\/ Getting course info - store in vars for easy access\r\n int day = coursePtr->getDay();\r\n int startH = coursePtr->getHourBegin();\r\n int startM = coursePtr->getMinutesBegin();\r\n int endH = coursePtr->getHourEnd();\r\n int endM = coursePtr->getMinutesEnd();\r\n QString lecturer = coursePtr->getLecturer();\r\n QString type = coursePtr->getType();\r\n QString name = coursePtr->getName();\r\n QString room = coursePtr->getRoom();\r\n\r\n QDate currentDate = cal->getStartDate(); \/\/ currentDate will iterate throuh the semester\r\n int firstDayOfSemester = currentDate.dayOfWeek(); \/\/Returns the weekday (1 = Monday to 7 = Sunday) for this date.\r\n\r\n changeDayNumberFromQtToNormal(&firstDayOfSemester); \/\/Get sync with our day numbers.\r\n\r\n \/*\r\n * these 6 lines will get the right day for the starting poin in a\r\n * semester for eatch course.\r\n *\/\r\n if(day > firstDayOfSemester)\r\n currentDate = currentDate.addDays(day-firstDayOfSemester); \/\/add the gap\r\n else if(day < firstDayOfSemester)\r\n currentDate = currentDate.addDays(6); \/\/move a week nius one day\r\n else\/\/ ==\r\n currentDate = currentDate; \/\/just for clearaty\r\n\r\n \/*\r\n * secondary loop - We have course info and starting day.\r\n * evrey loop enterence we add the course and moving one week forward.\r\n *\/\r\n for(;currentDate <= cal->getEndDate(); currentDate = currentDate.addDays(7))\r\n {\r\n QString line = makeLine(name, ¤tDate, startH, startM, endH, endM, lecturer, room, type);\r\n if(line != NULL)\r\n out << line << char(0x0A);\r\n else\r\n qWarning() << Q_FUNC_INFO << \"CSV : Got A NULL in Line! in function: \" << Q_FUNC_INFO;\r\n }\r\n out.flush();\r\n }\r\n\r\n if(cal->isExams()) \/\/Export Exams as well\r\n {\r\n qDebug() << \"Exporting Exams!\";\r\n for(calendarExamCourse* exam:exams->getExams())\r\n {\r\n QTime startH = exam->getFirstHourbegin();\r\n QTime endH = startH.addSecs(60*60*3);\/\/add 3 hours\r\n QString type = \"מבחן א\";\r\n QString name = exam->getName();\r\n QDate date = exam->getFirstDate();\r\n QString line = makeLine(name, &date, startH.hour(), startH.minute(), endH.hour(), endH.minute(), \"\", \"\", type);\r\n if(line != NULL)\r\n out << line << char(0x0A);\r\n else\r\n qWarning() << Q_FUNC_INFO << \"CSV : Got A NULL in Line! in function: \" << Q_FUNC_INFO;\r\n \/\/===============\r\n \/\/ Second Date\r\n \/\/===============\r\n startH = exam->getSecondHourbegin();\r\n endH = startH.addSecs(60*60*3);\/\/add 3 hours\r\n date = exam->getSecondDate();\r\n type = \"מבחן ב\";\r\n line = makeLine(name, &date, startH.hour(), startH.minute(), endH.hour(), endH.minute(), \"\", \"\", type);\r\n if(line != NULL)\r\n out << line << char(0x0A);\r\n else\r\n qWarning() << Q_FUNC_INFO << \"CSV : Got A NULL in Line! in function: \" << Q_FUNC_INFO;\r\n }\r\n out.flush();\r\n }\r\n\r\n file.close();\r\n qDebug() << Q_FUNC_INFO << \"CSV : Exported Successfully\";\r\n return true;\r\n\r\n}\r\n\r\n\/**\r\n * @brief Get the file path according to user via a file explorer dialog\r\n * @return - QString: the file path.\r\n *\/\r\nQString CSV_Exporter::getFileFath()\r\n{\r\n QString fileName = QFileDialog::getSaveFileName(NULL,\r\n QObject::tr(\"JceManager Save Schedule Dialog\"), \"\",\r\n QObject::tr(\"CSV Files (*.csv);;All Files (*)\"));\r\n if (fileName == \"\")\r\n return NULL;\r\n\r\n \/\/IMPORTENT! ADD CSV EXTENTION\r\n if(!fileName.contains(\".csv\") && !fileName.contains(\".CSV\"))\r\n fileName.append(\".csv\");\r\n return fileName;\r\n}\r\n\r\n\r\n\/**\r\n * @brief Returning a CSV formated ling in QString.\r\n * @param name\r\n * @param date\r\n * @param startH\r\n * @param startM - Not used at the moment.\r\n * @param endH\r\n * @param endM\r\n * @param lecturer\r\n * @param room\r\n * @param type\r\n * @return a CSV formated ling in QString.\r\n *\/\r\nQString CSV_Exporter::makeLine(QString name, QDate *date, int startH, int startM, int endH, int endM, QString lecturer, QString room, QString type)\r\n{\r\n \/\/Creating a CSV text line for Google Calendar\/iCal\/Outlook\r\n\r\n QString CSV_line = \"\";\r\n QString subject = \"\\\"\";\r\n subject.append(name);\r\n subject.append(\" - \");\r\n subject.append(type);\r\n subject.append(\"\\\"\");\r\n\r\n\r\n QString dateStr = date->toString(\"MM\/dd\/yyyy\");\r\n\r\n\r\n QString start;\r\n start.append(QString::number(startH));\r\n if(startM != 0)\r\n {\r\n start.append(\":\");\r\n start.append(QString::number(startM));\r\n }\r\n else\r\n start.append(\":00\");\r\n start.append(\":00\");\r\n\r\n QString end;\r\n end.append(QString::number(endH));\r\n if(endM != 0)\r\n {\r\n end.append(\":\");\r\n end.append(QString::number(endM));\r\n }\r\n else\r\n end.append(\":00\");\r\n end.append(\":00\");\r\n\r\n QString description = \"\\\"מרצה \";\r\n\r\n if (lecturer == LECTURER_DEFAULT_STRING)\r\n description.append(\"טרם נקבע מרצה או מתרגל\");\r\n else if(lecturer == \"\")\r\n description = \"\";\r\n else\r\n description.append(lecturer);\r\n\r\n description.append(\"\\n\");\r\n\r\n if (room == ROOM_DEFAULT_STRING)\r\n description.append(\"טרם נקבע מיקום\");\r\n else\r\n {\r\n description.append(\" ב\");\r\n description.append(room);\r\n }\r\n\r\n if(room == \"\")\r\n description = \"\\\"\\Good Luck!\\n\";\r\n\r\n description.append(\"\\n Created with JCE Manager.\\\"\");\r\n\r\n \/\/Create the Fucking Line\r\n \/\/Header: Subject,Start Date,Start Time,End Date,End Time,Description,Location\r\n CSV_line.append(subject);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(dateStr);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(start);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(dateStr);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(end);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(description);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(\"\\\"JCE Jerusalem\\\"\");\r\n\r\n return CSV_line;\r\n}\r\n\r\n\/**\r\n * @brief The QDate.dayOfWeek() returns an integer as follows (Sunday = 7, monday = 1... Friday = 5)\r\n * This method will make that return integer more uderstandble and easy to use with the Calander classes of\r\n * JCE Manager. so Sunday = 1, Monday = 2 and so on...\r\n *\r\n * @param QtDay - A Qt dayOfWeek integer pointer. it will cange his value.\r\n *\/\r\nvoid CSV_Exporter::changeDayNumberFromQtToNormal(int *QtDay)\r\n{\r\n switch(*QtDay){\r\n case 7:\r\n *QtDay = SUNDAY;\r\n break;\r\n case 1:\r\n *QtDay = MONDAY;\r\n break;\r\n case 2:\r\n *QtDay = TUESDAY;\r\n break;\r\n case 3:\r\n *QtDay = WENDSDAY;\r\n break;\r\n case 4:\r\n *QtDay = THURSDAY;\r\n break;\r\n case 5:\r\n *QtDay = FRIDAY;\r\n break;\r\n default:\r\n *QtDay = 7;\r\n break;\r\n }\r\n return; \/\/Done.\r\n}\r\n\r\n<commit_msg>Changed the type of exams in exporter<commit_after>#include \"csv_exporter.h\"\r\n\r\n\/*\r\n *\r\n * Class doc can be found in csv_exporter.h\r\n *\/\r\nCSV_Exporter::CSV_Exporter()\r\n{\r\n \/* EMPTY - NO NEED *\/\r\n}\r\n\r\n\/**\r\n * @brief This method will generate the CSV file (Targeting google calendar import)\r\n * it will create a full Semester calendar based on the users input (@param cal)\r\n * and the @calSched wich holdes all the courses in \"this\" semester.\r\n * @param calSched - Holdes all the Courses and there info\r\n * @param cal - The Calendar dialog witch holdes the starting date and the eand date.\r\n * @return - True if *all* went well, false if something on the way went wrong.\r\n *\/\r\nbool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *cal, calendarExam *exams)\r\n{\r\n if ((cal == NULL) || (calSched == NULL)) \/\/pointers checking!\r\n return false;\r\n\r\n if (calSched->getCourses().isEmpty())\r\n return false;\r\n\r\n qDebug() << Q_FUNC_INFO << \"Getting path for csv file from user...\";\r\n\r\n QString filePath = getFileFath();\r\n if(filePath == NULL) \/\/User canceled from the file explorer popup\r\n {\r\n qDebug() << Q_FUNC_INFO << \"CSV : User pressed Cancel... returning false\";\r\n return false;\r\n }\r\n qDebug() << Q_FUNC_INFO << \"CSV : User Chose: \" << filePath;\r\n qDebug() << Q_FUNC_INFO << \"CSV : Atempting to export the Schedule...\";\r\n\r\n QFile file(filePath);\r\n if(!file.open(QIODevice::ReadWrite | QIODevice::Truncate)) \/\/Incase unable to open the file (binary mode - \\n will not be converted on \"Windows\")\r\n {\r\n QMessageBox msgBox;\r\n msgBox.setIcon(QMessageBox::Critical);\r\n msgBox.setText(QObject::tr(\"Unable to open or create the file.\\nExporting Failed\"));\r\n msgBox.exec();\r\n qCritical() << Q_FUNC_INFO << \"unable to open\/create the file... maybe permissions error.\";\r\n return false;\r\n }\r\n\r\n QTextStream out(&file); \/\/The output streem.\r\n out.setCodec(\"UTF-8\"); \/\/Unicode 8\r\n\r\n out << CSV_CALENDAR_HEADER << \"\\n\"; \/\/ macro in header file\r\n\r\n for (calendarCourse *coursePtr: (calSched->getCourses())) \/\/main loop - running though all courses\r\n {\r\n \/\/ Getting course info - store in vars for easy access\r\n int day = coursePtr->getDay();\r\n int startH = coursePtr->getHourBegin();\r\n int startM = coursePtr->getMinutesBegin();\r\n int endH = coursePtr->getHourEnd();\r\n int endM = coursePtr->getMinutesEnd();\r\n QString lecturer = coursePtr->getLecturer();\r\n QString type = coursePtr->getType();\r\n QString name = coursePtr->getName();\r\n QString room = coursePtr->getRoom();\r\n\r\n QDate currentDate = cal->getStartDate(); \/\/ currentDate will iterate throuh the semester\r\n int firstDayOfSemester = currentDate.dayOfWeek(); \/\/Returns the weekday (1 = Monday to 7 = Sunday) for this date.\r\n\r\n changeDayNumberFromQtToNormal(&firstDayOfSemester); \/\/Get sync with our day numbers.\r\n\r\n \/*\r\n * these 6 lines will get the right day for the starting poin in a\r\n * semester for eatch course.\r\n *\/\r\n if(day > firstDayOfSemester)\r\n currentDate = currentDate.addDays(day-firstDayOfSemester); \/\/add the gap\r\n else if(day < firstDayOfSemester)\r\n currentDate = currentDate.addDays(6); \/\/move a week nius one day\r\n else\/\/ ==\r\n currentDate = currentDate; \/\/just for clearaty\r\n\r\n \/*\r\n * secondary loop - We have course info and starting day.\r\n * evrey loop enterence we add the course and moving one week forward.\r\n *\/\r\n for(;currentDate <= cal->getEndDate(); currentDate = currentDate.addDays(7))\r\n {\r\n QString line = makeLine(name, ¤tDate, startH, startM, endH, endM, lecturer, room, type);\r\n if(line != NULL)\r\n out << line << char(0x0A);\r\n else\r\n qWarning() << Q_FUNC_INFO << \"CSV : Got A NULL in Line! in function: \" << Q_FUNC_INFO;\r\n }\r\n out.flush();\r\n }\r\n\r\n if(cal->isExams()) \/\/Export Exams as well\r\n {\r\n qDebug() << \"Exporting Exams!\";\r\n for(calendarExamCourse* exam:exams->getExams())\r\n {\r\n QTime startH = exam->getFirstHourbegin();\r\n QTime endH = startH.addSecs(60*60*3);\/\/add 3 hours\r\n QString type = \"מועד א\";\r\n QString name = exam->getName();\r\n QDate date = exam->getFirstDate();\r\n QString line = makeLine(name, &date, startH.hour(), startH.minute(), endH.hour(), endH.minute(), \"\", \"\", type);\r\n if(line != NULL)\r\n out << line << char(0x0A);\r\n else\r\n qWarning() << Q_FUNC_INFO << \"CSV : Got A NULL in Line! in function: \" << Q_FUNC_INFO;\r\n \/\/===============\r\n \/\/ Second Date\r\n \/\/===============\r\n startH = exam->getSecondHourbegin();\r\n endH = startH.addSecs(60*60*3);\/\/add 3 hours\r\n date = exam->getSecondDate();\r\n type = \"מועד ב\";\r\n line = makeLine(name, &date, startH.hour(), startH.minute(), endH.hour(), endH.minute(), \"\", \"\", type);\r\n if(line != NULL)\r\n out << line << char(0x0A);\r\n else\r\n qWarning() << Q_FUNC_INFO << \"CSV : Got A NULL in Line! in function: \" << Q_FUNC_INFO;\r\n }\r\n out.flush();\r\n }\r\n\r\n file.close();\r\n qDebug() << Q_FUNC_INFO << \"CSV : Exported Successfully\";\r\n return true;\r\n\r\n}\r\n\r\n\/**\r\n * @brief Get the file path according to user via a file explorer dialog\r\n * @return - QString: the file path.\r\n *\/\r\nQString CSV_Exporter::getFileFath()\r\n{\r\n QString fileName = QFileDialog::getSaveFileName(NULL,\r\n QObject::tr(\"JceManager Save Schedule Dialog\"), \"\",\r\n QObject::tr(\"CSV Files (*.csv);;All Files (*)\"));\r\n if (fileName == \"\")\r\n return NULL;\r\n\r\n \/\/IMPORTENT! ADD CSV EXTENTION\r\n if(!fileName.contains(\".csv\") && !fileName.contains(\".CSV\"))\r\n fileName.append(\".csv\");\r\n return fileName;\r\n}\r\n\r\n\r\n\/**\r\n * @brief Returning a CSV formated ling in QString.\r\n * @param name\r\n * @param date\r\n * @param startH\r\n * @param startM\r\n * @param endH\r\n * @param endM\r\n * @param lecturer\r\n * @param room\r\n * @param type\r\n * @return a CSV formated ling in QString.\r\n *\/\r\nQString CSV_Exporter::makeLine(QString name, QDate *date, int startH, int startM, int endH, int endM, QString lecturer, QString room, QString type)\r\n{\r\n \/\/Creating a CSV text line for Google Calendar\/iCal\/Outlook\r\n\r\n QString CSV_line = \"\";\r\n QString subject = \"\\\"\";\r\n subject.append(name);\r\n subject.append(\" - \");\r\n subject.append(type);\r\n subject.append(\"\\\"\");\r\n\r\n\r\n QString dateStr = date->toString(\"MM\/dd\/yyyy\");\r\n\r\n\r\n QString start;\r\n start.append(QString::number(startH));\r\n if(startM != 0)\r\n {\r\n start.append(\":\");\r\n start.append(QString::number(startM));\r\n }\r\n else\r\n start.append(\":00\");\r\n start.append(\":00\");\r\n\r\n QString end;\r\n end.append(QString::number(endH));\r\n if(endM != 0)\r\n {\r\n end.append(\":\");\r\n end.append(QString::number(endM));\r\n }\r\n else\r\n end.append(\":00\");\r\n end.append(\":00\");\r\n\r\n QString description = \"\\\"מרצה \";\r\n\r\n if (lecturer == LECTURER_DEFAULT_STRING)\r\n description.append(\"טרם נקבע מרצה או מתרגל\");\r\n else if(lecturer == \"\")\r\n description = \"\";\r\n else\r\n description.append(lecturer);\r\n\r\n description.append(\"\\n\");\r\n\r\n if (room == ROOM_DEFAULT_STRING)\r\n description.append(\"טרם נקבע מיקום\");\r\n else\r\n {\r\n description.append(\" ב\");\r\n description.append(room);\r\n }\r\n\r\n if(room == \"\")\r\n description = \"\\\"\\Good Luck!\\n\";\r\n\r\n description.append(\"\\n Created with JCE Manager.\\\"\");\r\n\r\n \/\/Create the Fucking Line\r\n \/\/Header: Subject,Start Date,Start Time,End Date,End Time,Description,Location\r\n CSV_line.append(subject);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(dateStr);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(start);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(dateStr);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(end);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(description);\r\n CSV_line.append(\",\");\r\n\r\n CSV_line.append(\"\\\"JCE Jerusalem\\\"\");\r\n\r\n return CSV_line;\r\n}\r\n\r\n\/**\r\n * @brief The QDate.dayOfWeek() returns an integer as follows (Sunday = 7, monday = 1... Friday = 5)\r\n * This method will make that return integer more uderstandble and easy to use with the Calander classes of\r\n * JCE Manager. so Sunday = 1, Monday = 2 and so on...\r\n *\r\n * @param QtDay - A Qt dayOfWeek integer pointer. it will cange his value.\r\n *\/\r\nvoid CSV_Exporter::changeDayNumberFromQtToNormal(int *QtDay)\r\n{\r\n switch(*QtDay){\r\n case 7:\r\n *QtDay = SUNDAY;\r\n break;\r\n case 1:\r\n *QtDay = MONDAY;\r\n break;\r\n case 2:\r\n *QtDay = TUESDAY;\r\n break;\r\n case 3:\r\n *QtDay = WENDSDAY;\r\n break;\r\n case 4:\r\n *QtDay = THURSDAY;\r\n break;\r\n case 5:\r\n *QtDay = FRIDAY;\r\n break;\r\n default:\r\n *QtDay = 7;\r\n break;\r\n }\r\n return; \/\/Done.\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include \"joedb\/Readonly_Journal.h\"\n#include \"joedb\/Generic_File.h\"\n#include \"joedb\/Exception.h\"\n\n#include <vector>\n#include <sstream>\n\nconst uint32_t joedb::Readonly_Journal::version_number = 0x00000004;\nconst uint32_t joedb::Readonly_Journal::compatible_version = 0x00000004;\nconst int64_t joedb::Readonly_Journal::header_size = 41;\n\n#define FORMAT_EXCEPTION(x)\\\n do {if (!ignore_errors) throw Exception(x);} while(false)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\njoedb::Readonly_Journal::Readonly_Journal\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Generic_File &file,\n bool ignore_errors\n):\n file(file),\n checkpoint_index(0),\n checkpoint_position(0),\n table_of_last_operation(0),\n record_of_last_operation(0),\n field_of_last_update(0)\n{\n \/\/\n \/\/ Check the format of an existing joedb file\n \/\/\n if (file.get_mode() != Open_Mode::create_new)\n {\n \/\/\n \/\/ First, check for initial \"joedb\"\n \/\/\n if (file.read<uint8_t>() != 'j' ||\n file.read<uint8_t>() != 'o' ||\n file.read<uint8_t>() != 'e' ||\n file.read<uint8_t>() != 'd' ||\n file.read<uint8_t>() != 'b')\n {\n FORMAT_EXCEPTION(\"File does not start by 'joedb'\");\n }\n else\n {\n \/\/\n \/\/ Check version number\n \/\/\n const uint32_t version = file.read<uint32_t>();\n if (version < compatible_version || version > version_number)\n FORMAT_EXCEPTION(\"Unsupported format version\");\n\n \/\/\n \/\/ Find the most recent checkpoint\n \/\/\n int64_t pos[4];\n for (int i = 0; i < 4; i++)\n pos[i] = file.read<int64_t>();\n\n if (pos[0] != pos[1] || pos[2] != pos[3])\n FORMAT_EXCEPTION(\"Checkpoint mismatch\");\n\n checkpoint_position = 0;\n\n for (unsigned i = 0; i < 2; i++)\n if (pos[2 * i] == pos[2 * i + 1] && pos[2 * i] > checkpoint_position)\n {\n if (int64_t(size_t(pos[2 * i])) != pos[2 * i])\n throw Exception(\"size_t is too small for this file\");\n checkpoint_position = pos[2 * i];\n checkpoint_index = i;\n }\n\n if (checkpoint_position < header_size)\n FORMAT_EXCEPTION(\"Checkpoint too small\");\n\n \/\/\n \/\/ Compare to file size (if available)\n \/\/\n int64_t file_size = file.get_size();\n\n if (file_size > 0 && file_size != checkpoint_position)\n FORMAT_EXCEPTION(\"Checkpoint different from file size\");\n\n if (ignore_errors)\n checkpoint_position = file_size;\n }\n }\n}\n\n#undef FORMAT_EXCEPTION\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::replay_log(Writable &writable)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n rewind();\n play_until_checkpoint(writable);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::rewind()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n file.set_position(header_size);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::seek(int64_t position)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n file.set_position(position);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::play_until(Writable &writable, int64_t end)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n while(file.get_position() < end)\n one_step(writable);\n file.set_position(file.get_position()); \/\/ get ready for writing\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool joedb::Readonly_Journal::at_end_of_file() const\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n return file.get_position() >= checkpoint_position;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::one_step(Writable &writable)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n switch(file.read<operation_t>())\n {\n case operation_t::end_of_file:\n if (file.get_position() != checkpoint_position)\n throw Exception(\"Unexpected end of file\");\n break;\n\n case operation_t::create_table:\n {\n std::string name = safe_read_string();\n writable.create_table(name);\n }\n break;\n\n case operation_t::drop_table:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n writable.drop_table(table_id);\n }\n break;\n\n case operation_t::rename_table:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n std::string name = safe_read_string();\n writable.rename_table(table_id, name);\n }\n break;\n\n case operation_t::add_field:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n std::string name = safe_read_string();\n Type type = read_type();\n writable.add_field(table_id, name, type);\n }\n break;\n\n case operation_t::drop_field:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Field_Id field_id = file.compact_read<Field_Id>();\n writable.drop_field(table_id, field_id);\n }\n break;\n\n case operation_t::rename_field:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Field_Id field_id = file.compact_read<Field_Id>();\n std::string name = safe_read_string();\n writable.rename_field(table_id, field_id, name);\n }\n break;\n\n case operation_t::insert_into:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Record_Id record_id = file.compact_read<Record_Id>();\n writable.insert_into(table_id, record_id);\n table_of_last_operation = table_id;\n record_of_last_operation = record_id;\n }\n break;\n\n case operation_t::insert_vector:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Record_Id record_id = file.compact_read<Record_Id>();\n Record_Id size = file.compact_read<Record_Id>();\n writable.insert_vector(table_id, record_id, size);\n table_of_last_operation = table_id;\n record_of_last_operation = record_id;\n }\n break;\n\n case operation_t::append:\n writable.insert_into(table_of_last_operation,\n ++record_of_last_operation);\n break;\n\n case operation_t::delete_from:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Record_Id record_id = file.compact_read<Record_Id>();\n writable.delete_from(table_id, record_id);\n }\n break;\n\n #define TYPE_MACRO(cpp_type, return_type, type_id, read_method, W)\\\n case operation_t::update_##type_id:\\\n table_of_last_operation = file.compact_read<Table_Id>();\\\n record_of_last_operation = file.compact_read<Record_Id>();\\\n field_of_last_update = file.compact_read<Field_Id>();\\\n goto lbl_perform_update_##type_id;\\\n\\\n case operation_t::update_last_##type_id:\\\n field_of_last_update = file.compact_read<Field_Id>();\\\n goto lbl_perform_update_##type_id;\\\n\\\n case operation_t::update_next_##type_id:\\\n record_of_last_operation++;\\\n goto lbl_perform_update_##type_id;\\\n\\\n lbl_perform_update_##type_id:\\\n {\\\n cpp_type value = read_method();\\\n writable.update_##type_id\\\n (\\\n table_of_last_operation,\\\n record_of_last_operation,\\\n field_of_last_update,\\\n value\\\n );\\\n }\\\n break;\\\n\\\n case operation_t::update_vector_##type_id:\\\n {\\\n table_of_last_operation = file.compact_read<Table_Id>();\\\n record_of_last_operation = file.compact_read<Record_Id>();\\\n field_of_last_update = file.compact_read<Field_Id>();\\\n Record_Id size = file.compact_read<Record_Id>();\\\n if (int64_t(size) > checkpoint_position || size < 0)\\\n throw Exception(\"update_vector too big\");\\\n std::vector<cpp_type> buffer(size);\\\n for (size_t i = 0; i < size; i++)\\\n buffer[i] = read_method();\\\n writable.update_vector_##type_id\\\n (\\\n table_of_last_operation,\\\n record_of_last_operation,\\\n field_of_last_update,\\\n size,\\\n &buffer[0]\\\n );\\\n }\\\n break;\n #include \"joedb\/TYPE_MACRO.h\"\n #undef TYPE_MACRO\n\n case operation_t::custom:\n {\n std::string name = safe_read_string();\n writable.custom(name);\n }\n break;\n\n case operation_t::comment:\n {\n std::string comment = safe_read_string();\n writable.comment(comment);\n }\n break;\n\n case operation_t::timestamp:\n {\n int64_t timestamp = file.read<int64_t>();\n writable.timestamp(timestamp);\n }\n break;\n\n case operation_t::valid_data:\n writable.valid_data();\n break;\n\n default:\n {\n std::ostringstream error;\n error << \"Unexpected operation: file.get_position() = \";\n error << file.get_position();\n throw Exception(error.str());\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\njoedb::Type joedb::Readonly_Journal::read_type()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n Type::Type_Id type_id = Type::Type_Id(file.read<Type_Id_Storage>());\n if (type_id == Type::Type_Id::reference)\n return Type::reference(file.compact_read<Table_Id>());\n else\n return Type(type_id);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string joedb::Readonly_Journal::safe_read_string()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n return file.safe_read_string(size_t(checkpoint_position));\n}\n<commit_msg>replace ugly macro by lambda<commit_after>#include \"joedb\/Readonly_Journal.h\"\n#include \"joedb\/Generic_File.h\"\n#include \"joedb\/Exception.h\"\n\n#include <vector>\n#include <sstream>\n\nconst uint32_t joedb::Readonly_Journal::version_number = 0x00000004;\nconst uint32_t joedb::Readonly_Journal::compatible_version = 0x00000004;\nconst int64_t joedb::Readonly_Journal::header_size = 41;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\njoedb::Readonly_Journal::Readonly_Journal\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Generic_File &file,\n bool ignore_errors\n):\n file(file),\n checkpoint_index(0),\n checkpoint_position(0),\n table_of_last_operation(0),\n record_of_last_operation(0),\n field_of_last_update(0)\n{\n auto format_exception = [ignore_errors](const char *message)\n {\n if (!ignore_errors)\n throw Exception(message);\n };\n\n \/\/\n \/\/ Check the format of an existing joedb file\n \/\/\n if (file.get_mode() != Open_Mode::create_new)\n {\n \/\/\n \/\/ First, check for initial \"joedb\"\n \/\/\n if (file.read<uint8_t>() != 'j' ||\n file.read<uint8_t>() != 'o' ||\n file.read<uint8_t>() != 'e' ||\n file.read<uint8_t>() != 'd' ||\n file.read<uint8_t>() != 'b')\n {\n format_exception(\"File does not start by 'joedb'\");\n }\n else\n {\n \/\/\n \/\/ Check version number\n \/\/\n const uint32_t version = file.read<uint32_t>();\n if (version < compatible_version || version > version_number)\n format_exception(\"Unsupported format version\");\n\n \/\/\n \/\/ Find the most recent checkpoint\n \/\/\n int64_t pos[4];\n for (int i = 0; i < 4; i++)\n pos[i] = file.read<int64_t>();\n\n if (pos[0] != pos[1] || pos[2] != pos[3])\n format_exception(\"Checkpoint mismatch\");\n\n checkpoint_position = 0;\n\n for (unsigned i = 0; i < 2; i++)\n if (pos[2 * i] == pos[2 * i + 1] && pos[2 * i] > checkpoint_position)\n {\n if (int64_t(size_t(pos[2 * i])) != pos[2 * i])\n throw Exception(\"size_t is too small for this file\");\n checkpoint_position = pos[2 * i];\n checkpoint_index = i;\n }\n\n if (checkpoint_position < header_size)\n format_exception(\"Checkpoint too small\");\n\n \/\/\n \/\/ Compare to file size (if available)\n \/\/\n int64_t file_size = file.get_size();\n\n if (file_size > 0 && file_size != checkpoint_position)\n format_exception(\"Checkpoint different from file size\");\n\n if (ignore_errors)\n checkpoint_position = file_size;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::replay_log(Writable &writable)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n rewind();\n play_until_checkpoint(writable);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::rewind()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n file.set_position(header_size);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::seek(int64_t position)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n file.set_position(position);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::play_until(Writable &writable, int64_t end)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n while(file.get_position() < end)\n one_step(writable);\n file.set_position(file.get_position()); \/\/ get ready for writing\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool joedb::Readonly_Journal::at_end_of_file() const\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n return file.get_position() >= checkpoint_position;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Readonly_Journal::one_step(Writable &writable)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n switch(file.read<operation_t>())\n {\n case operation_t::end_of_file:\n if (file.get_position() != checkpoint_position)\n throw Exception(\"Unexpected end of file\");\n break;\n\n case operation_t::create_table:\n {\n std::string name = safe_read_string();\n writable.create_table(name);\n }\n break;\n\n case operation_t::drop_table:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n writable.drop_table(table_id);\n }\n break;\n\n case operation_t::rename_table:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n std::string name = safe_read_string();\n writable.rename_table(table_id, name);\n }\n break;\n\n case operation_t::add_field:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n std::string name = safe_read_string();\n Type type = read_type();\n writable.add_field(table_id, name, type);\n }\n break;\n\n case operation_t::drop_field:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Field_Id field_id = file.compact_read<Field_Id>();\n writable.drop_field(table_id, field_id);\n }\n break;\n\n case operation_t::rename_field:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Field_Id field_id = file.compact_read<Field_Id>();\n std::string name = safe_read_string();\n writable.rename_field(table_id, field_id, name);\n }\n break;\n\n case operation_t::insert_into:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Record_Id record_id = file.compact_read<Record_Id>();\n writable.insert_into(table_id, record_id);\n table_of_last_operation = table_id;\n record_of_last_operation = record_id;\n }\n break;\n\n case operation_t::insert_vector:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Record_Id record_id = file.compact_read<Record_Id>();\n Record_Id size = file.compact_read<Record_Id>();\n writable.insert_vector(table_id, record_id, size);\n table_of_last_operation = table_id;\n record_of_last_operation = record_id;\n }\n break;\n\n case operation_t::append:\n writable.insert_into(table_of_last_operation,\n ++record_of_last_operation);\n break;\n\n case operation_t::delete_from:\n {\n Table_Id table_id = file.compact_read<Table_Id>();\n Record_Id record_id = file.compact_read<Record_Id>();\n writable.delete_from(table_id, record_id);\n }\n break;\n\n #define TYPE_MACRO(cpp_type, return_type, type_id, read_method, W)\\\n case operation_t::update_##type_id:\\\n table_of_last_operation = file.compact_read<Table_Id>();\\\n record_of_last_operation = file.compact_read<Record_Id>();\\\n field_of_last_update = file.compact_read<Field_Id>();\\\n goto lbl_perform_update_##type_id;\\\n\\\n case operation_t::update_last_##type_id:\\\n field_of_last_update = file.compact_read<Field_Id>();\\\n goto lbl_perform_update_##type_id;\\\n\\\n case operation_t::update_next_##type_id:\\\n record_of_last_operation++;\\\n goto lbl_perform_update_##type_id;\\\n\\\n lbl_perform_update_##type_id:\\\n {\\\n cpp_type value = read_method();\\\n writable.update_##type_id\\\n (\\\n table_of_last_operation,\\\n record_of_last_operation,\\\n field_of_last_update,\\\n value\\\n );\\\n }\\\n break;\\\n\\\n case operation_t::update_vector_##type_id:\\\n {\\\n table_of_last_operation = file.compact_read<Table_Id>();\\\n record_of_last_operation = file.compact_read<Record_Id>();\\\n field_of_last_update = file.compact_read<Field_Id>();\\\n Record_Id size = file.compact_read<Record_Id>();\\\n if (int64_t(size) > checkpoint_position || size < 0)\\\n throw Exception(\"update_vector too big\");\\\n std::vector<cpp_type> buffer(size);\\\n for (size_t i = 0; i < size; i++)\\\n buffer[i] = read_method();\\\n writable.update_vector_##type_id\\\n (\\\n table_of_last_operation,\\\n record_of_last_operation,\\\n field_of_last_update,\\\n size,\\\n &buffer[0]\\\n );\\\n }\\\n break;\n #include \"joedb\/TYPE_MACRO.h\"\n #undef TYPE_MACRO\n\n case operation_t::custom:\n {\n std::string name = safe_read_string();\n writable.custom(name);\n }\n break;\n\n case operation_t::comment:\n {\n std::string comment = safe_read_string();\n writable.comment(comment);\n }\n break;\n\n case operation_t::timestamp:\n {\n int64_t timestamp = file.read<int64_t>();\n writable.timestamp(timestamp);\n }\n break;\n\n case operation_t::valid_data:\n writable.valid_data();\n break;\n\n default:\n {\n std::ostringstream error;\n error << \"Unexpected operation: file.get_position() = \";\n error << file.get_position();\n throw Exception(error.str());\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\njoedb::Type joedb::Readonly_Journal::read_type()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n Type::Type_Id type_id = Type::Type_Id(file.read<Type_Id_Storage>());\n if (type_id == Type::Type_Id::reference)\n return Type::reference(file.compact_read<Table_Id>());\n else\n return Type(type_id);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string joedb::Readonly_Journal::safe_read_string()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n return file.safe_read_string(size_t(checkpoint_position));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. 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,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"kudu\/master\/master_runner.h\"\n\n#include <iostream>\n#include <string>\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include \"kudu\/gutil\/strings\/substitute.h\"\n#include \"kudu\/master\/master.h\"\n#include \"kudu\/util\/flags.h\"\n#include \"kudu\/util\/monotime.h\"\n#include \"kudu\/util\/version_info.h\"\n\nusing kudu::master::Master;\nusing std::string;\n\nDECLARE_bool(evict_failed_followers);\n\nnamespace kudu {\nnamespace master {\n\nvoid SetMasterFlagDefaults() {\n \/\/ Reset some default values before parsing gflags.\n CHECK_NE(\"\", google::SetCommandLineOptionWithMode(\"rpc_bind_addresses\",\n strings::Substitute(\n \"0.0.0.0:$0\",\n Master::kDefaultPort).c_str(),\n google::FlagSettingMode::SET_FLAGS_DEFAULT));\n CHECK_NE(\"\", google::SetCommandLineOptionWithMode(\"webserver_port\",\n std::to_string(\n Master::kDefaultWebPort).c_str(),\n google::FlagSettingMode::SET_FLAGS_DEFAULT));\n\n \/\/ Setting the default value of the 'force_block_cache_capacity' flag to\n \/\/ 'false' makes the corresponding group validator enforce proper settings\n \/\/ for the memory limit and the cfile cache capacity.\n CHECK_NE(\"\", SetCommandLineOptionWithMode(\"force_block_cache_capacity\",\n \"false\",\n gflags::SET_FLAGS_DEFAULT));\n\n \/\/ A multi-node Master leader should not evict failed Master followers\n \/\/ because there is no-one to assign replacement servers in order to maintain\n \/\/ the desired replication factor. (It's not turtles all the way down!)\n CHECK_NE(\"\", SetCommandLineOptionWithMode(\"evict_failed_followers\",\n \"false\",\n gflags::SET_FLAGS_DEFAULT));\n \/\/ SET_FLAGS_DEFAULT won't reset the flag value if it has previously been\n \/\/ set, instead it will only change the default. Because we want to ensure\n \/\/ evict_failed_followers is always false, we explicitly set the flag.\n FLAGS_evict_failed_followers = false;\n}\n\nStatus RunMasterServer() {\n string nondefault_flags = GetNonDefaultFlags();\n LOG(INFO) << \"Master server non-default flags:\\n\"\n << nondefault_flags << '\\n'\n << \"Master server version:\\n\"\n << VersionInfo::GetAllVersionInfo();\n\n Master server({});\n RETURN_NOT_OK(server.Init());\n RETURN_NOT_OK(server.Start());\n\n while (true) {\n SleepFor(MonoDelta::FromSeconds(60));\n }\n}\n\n} \/\/ namespace master\n} \/\/ namespace kudu\n<commit_msg>[master] Replace hive_metastore_sasl_enabled validator<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. 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,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"kudu\/master\/master_runner.h\"\n\n#include <iostream>\n#include <string>\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include \"kudu\/gutil\/strings\/substitute.h\"\n#include \"kudu\/master\/master.h\"\n#include \"kudu\/util\/flags.h\"\n#include \"kudu\/util\/monotime.h\"\n#include \"kudu\/util\/version_info.h\"\n\nusing kudu::master::Master;\nusing std::string;\n\nDECLARE_bool(evict_failed_followers);\n\nDECLARE_bool(hive_metastore_sasl_enabled);\nDECLARE_string(keytab_file);\n\nnamespace kudu {\nnamespace master {\n\n\/\/ Validates that if the HMS is configured with SASL enabled, the server has a\n\/\/ keytab available. This doesn't use a GROUP_FLAG_VALIDATOR because this check\n\/\/ only needs to be run on a server. E.g. tools that run with the HMS don't need\n\/\/ to pass in a keytab.\nstatic Status ValidateHiveMetastoreSaslEnabled() {\n if (FLAGS_hive_metastore_sasl_enabled &&\n FLAGS_keytab_file.empty()) {\n return Status::ConfigurationError(\"When the Hive Metastore has SASL enabled \"\n \"(--hive_metastore_sasl_enabled), Kudu must be \"\n \"configured with a keytab (--keytab_file).\");\n }\n return Status::OK();\n}\n\nvoid SetMasterFlagDefaults() {\n \/\/ Reset some default values before parsing gflags.\n CHECK_NE(\"\", google::SetCommandLineOptionWithMode(\"rpc_bind_addresses\",\n strings::Substitute(\n \"0.0.0.0:$0\",\n Master::kDefaultPort).c_str(),\n google::FlagSettingMode::SET_FLAGS_DEFAULT));\n CHECK_NE(\"\", google::SetCommandLineOptionWithMode(\"webserver_port\",\n std::to_string(\n Master::kDefaultWebPort).c_str(),\n google::FlagSettingMode::SET_FLAGS_DEFAULT));\n\n \/\/ Setting the default value of the 'force_block_cache_capacity' flag to\n \/\/ 'false' makes the corresponding group validator enforce proper settings\n \/\/ for the memory limit and the cfile cache capacity.\n CHECK_NE(\"\", SetCommandLineOptionWithMode(\"force_block_cache_capacity\",\n \"false\",\n gflags::SET_FLAGS_DEFAULT));\n\n \/\/ A multi-node Master leader should not evict failed Master followers\n \/\/ because there is no-one to assign replacement servers in order to maintain\n \/\/ the desired replication factor. (It's not turtles all the way down!)\n CHECK_NE(\"\", SetCommandLineOptionWithMode(\"evict_failed_followers\",\n \"false\",\n gflags::SET_FLAGS_DEFAULT));\n \/\/ SET_FLAGS_DEFAULT won't reset the flag value if it has previously been\n \/\/ set, instead it will only change the default. Because we want to ensure\n \/\/ evict_failed_followers is always false, we explicitly set the flag.\n FLAGS_evict_failed_followers = false;\n}\n\nStatus RunMasterServer() {\n string nondefault_flags = GetNonDefaultFlags();\n LOG(INFO) << \"Master server non-default flags:\\n\"\n << nondefault_flags << '\\n'\n << \"Master server version:\\n\"\n << VersionInfo::GetAllVersionInfo();\n\n RETURN_NOT_OK(ValidateHiveMetastoreSaslEnabled());\n\n Master server({});\n RETURN_NOT_OK(server.Init());\n RETURN_NOT_OK(server.Start());\n\n while (true) {\n SleepFor(MonoDelta::FromSeconds(60));\n }\n}\n\n} \/\/ namespace master\n} \/\/ namespace kudu\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of the Qt Build Suite\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 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\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file.\n** Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\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\n#include \"oldsourceproject.h\"\n\n#include <buildgraph\/buildgraph.h>\n#include <buildgraph\/executor.h>\n#include <language\/loader.h>\n#include <tools\/runenvironment.h>\n#include <tools\/fileinfo.h>\n#include <tools\/persistence.h>\n#include <tools\/logger.h>\n#include <tools\/scannerpluginmanager.h>\n#include <tools\/scripttools.h>\n#include <tools\/platform.h>\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QProcess>\n#include <QtCore\/QSettings>\n#include <QtCore\/QScopedPointer>\n#include <QtCore\/QDebug>\n#include <QtCore\/QDir>\n#include <QtCore\/QElapsedTimer>\n\nnamespace qbs {\n\nSourceProject::SourceProject(qbs::Settings::Ptr settings)\n : m_settings(settings)\n{\n}\n\nvoid SourceProject::setSearchPaths(const QStringList &searchPaths)\n{\n m_searchPaths = searchPaths;\n}\n\nvoid SourceProject::loadPlugins(const QStringList &pluginPaths)\n{\n static bool alreadyCalled = false;\n if (alreadyCalled) {\n qbsWarning(\"qbs::SourceProject::loadPlugins was called more than once.\");\n }\n\n alreadyCalled = true;\n\n foreach (const QString &pluginPath, pluginPaths)\n QCoreApplication::addLibraryPath(pluginPath);\n\n qbs::ScannerPluginManager::instance()->loadPlugins(pluginPaths);\n}\n\nvoid SourceProject::loadProject(QFutureInterface<bool> &futureInterface, QString projectFileName, QList<QVariantMap> buildConfigs)\n{\n QHash<QString, qbs::Platform::Ptr > platforms = Platform::platforms();\n if (platforms.isEmpty()) {\n qbsFatal(\"no platforms configured. maybe you want to run 'qbs platforms probe' first.\");\n futureInterface.reportResult(false);\n return;\n }\n if (buildConfigs.isEmpty()) {\n qbsFatal(\"SourceProject::loadProject: no build configuration given.\");\n futureInterface.reportResult(false);\n return;\n }\n QList<qbs::Configuration::Ptr> configurations;\n foreach (QVariantMap buildCfg, buildConfigs) {\n if (!buildCfg.value(\"platform\").isValid()) {\n if (!m_settings->value(\"defaults\/platform\").isValid()) {\n qbsFatal(\"SourceProject::loadProject: no platform given and no default set.\");\n continue;\n }\n buildCfg.insert(\"platform\", m_settings->value(\"defaults\/platform\").toString());\n }\n Platform::Ptr platform = platforms.value(buildCfg.value(\"platform\").toString());\n if (platform.isNull()) {\n qbsFatal(\"SourceProject::loadProject: unknown platform: %s\", qPrintable(buildCfg.value(\"platform\").toString()));\n continue;\n }\n foreach (const QString &key, platform->settings.allKeys()) {\n buildCfg.insert(QString(key).replace('\/','.'),\n platform->settings.value(key));\n }\n\n if (!buildCfg.value(\"buildVariant\").isValid()) {\n qbsFatal(\"SourceProject::loadProject: property 'buildVariant' missing in build configuration.\");\n continue;\n }\n qbs::Configuration::Ptr configure(new qbs::Configuration);\n configurations.append(configure);\n\n foreach (const QString &property, buildCfg.keys()) {\n QStringList nameElements = property.split('.');\n if (nameElements.count() == 1)\n nameElements.prepend(\"qbs\");\n QVariantMap configValue = configure->value();\n qbs::setConfigProperty(configValue, nameElements, buildCfg.value(property));\n configure->setValue(configValue);\n }\n }\n\n qbs::Loader loader;\n loader.setSearchPaths(m_searchPaths);\n m_buildGraph = QSharedPointer<qbs::BuildGraph>(new qbs::BuildGraph);\n m_buildGraph->setOutputDirectoryRoot(QDir::currentPath());\n const QString buildDirectoryRoot = m_buildGraph->buildDirectoryRoot();\n\n try {\n foreach (const qbs::Configuration::Ptr &configure, configurations) {\n qbs::BuildProject::Ptr bProject;\n const qbs::FileTime projectFileTimeStamp = qbs::FileInfo(projectFileName).lastModified();\n bProject = qbs::BuildProject::load(m_buildGraph.data(), projectFileTimeStamp, configure, m_searchPaths);\n if (!bProject) {\n QElapsedTimer timer;\n timer.start();\n if (!loader.hasLoaded())\n loader.loadProject(projectFileName);\n qbs::ResolvedProject::Ptr rProject = loader.resolveProject(buildDirectoryRoot, configure, futureInterface);\n if (rProject->products.isEmpty())\n throw qbs::Error(QString(\"'%1' does not contain products.\").arg(projectFileName));\n qDebug() << \"loading project took: \" << timer.elapsed() << \"ms\";\n timer.start();\n bProject = m_buildGraph->resolveProject(rProject, futureInterface);\n qDebug() << \"build graph took: \" << timer.elapsed() << \"ms\";\n }\n\n m_buildProjects.append(bProject);\n\n printf(\"for %s:\\n\", qPrintable(bProject->resolvedProject()->id));\n foreach (qbs::ResolvedProduct::Ptr p, bProject->resolvedProject()->products) {\n printf(\" - [%s] %s as %s\\n\"\n ,qPrintable(p->fileTags.join(\", \"))\n ,qPrintable(p->name)\n ,qPrintable(p->project->id)\n );\n }\n printf(\"\\n\");\n }\n\n } catch (qbs::Error &e) {\n m_errors.append(e);\n futureInterface.reportResult(false);\n return;\n }\n\n futureInterface.reportResult(true);\n}\n\nQList<BuildProject::Ptr> SourceProject::buildProjects() const\n{\n return m_buildProjects;\n}\n\nQList<Error> SourceProject::errors() const\n{\n return m_errors;\n}\n\n} \/\/ namespace qbs\n\n<commit_msg>support submodule syntax in platform config files<commit_after>\/**************************************************************************\n**\n** This file is part of the Qt Build Suite\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 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\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file.\n** Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\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\n#include \"oldsourceproject.h\"\n\n#include <buildgraph\/buildgraph.h>\n#include <buildgraph\/executor.h>\n#include <language\/loader.h>\n#include <tools\/runenvironment.h>\n#include <tools\/fileinfo.h>\n#include <tools\/persistence.h>\n#include <tools\/logger.h>\n#include <tools\/scannerpluginmanager.h>\n#include <tools\/scripttools.h>\n#include <tools\/platform.h>\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QProcess>\n#include <QtCore\/QSettings>\n#include <QtCore\/QScopedPointer>\n#include <QtCore\/QDebug>\n#include <QtCore\/QDir>\n#include <QtCore\/QElapsedTimer>\n\nnamespace qbs {\n\nSourceProject::SourceProject(qbs::Settings::Ptr settings)\n : m_settings(settings)\n{\n}\n\nvoid SourceProject::setSearchPaths(const QStringList &searchPaths)\n{\n m_searchPaths = searchPaths;\n}\n\nvoid SourceProject::loadPlugins(const QStringList &pluginPaths)\n{\n static bool alreadyCalled = false;\n if (alreadyCalled) {\n qbsWarning(\"qbs::SourceProject::loadPlugins was called more than once.\");\n }\n\n alreadyCalled = true;\n\n foreach (const QString &pluginPath, pluginPaths)\n QCoreApplication::addLibraryPath(pluginPath);\n\n qbs::ScannerPluginManager::instance()->loadPlugins(pluginPaths);\n}\n\nvoid SourceProject::loadProject(QFutureInterface<bool> &futureInterface, QString projectFileName, QList<QVariantMap> buildConfigs)\n{\n QHash<QString, qbs::Platform::Ptr > platforms = Platform::platforms();\n if (platforms.isEmpty()) {\n qbsFatal(\"no platforms configured. maybe you want to run 'qbs platforms probe' first.\");\n futureInterface.reportResult(false);\n return;\n }\n if (buildConfigs.isEmpty()) {\n qbsFatal(\"SourceProject::loadProject: no build configuration given.\");\n futureInterface.reportResult(false);\n return;\n }\n QList<qbs::Configuration::Ptr> configurations;\n foreach (QVariantMap buildCfg, buildConfigs) {\n if (!buildCfg.value(\"platform\").isValid()) {\n if (!m_settings->value(\"defaults\/platform\").isValid()) {\n qbsFatal(\"SourceProject::loadProject: no platform given and no default set.\");\n continue;\n }\n buildCfg.insert(\"platform\", m_settings->value(\"defaults\/platform\").toString());\n }\n Platform::Ptr platform = platforms.value(buildCfg.value(\"platform\").toString());\n if (platform.isNull()) {\n qbsFatal(\"SourceProject::loadProject: unknown platform: %s\", qPrintable(buildCfg.value(\"platform\").toString()));\n continue;\n }\n foreach (const QString &key, platform->settings.allKeys()) {\n QString fixedKey = key;\n int idx = fixedKey.lastIndexOf(QChar('\/'));\n if (idx > 0)\n fixedKey[idx] = QChar('.');\n buildCfg.insert(fixedKey, platform->settings.value(key));\n }\n\n if (!buildCfg.value(\"buildVariant\").isValid()) {\n qbsFatal(\"SourceProject::loadProject: property 'buildVariant' missing in build configuration.\");\n continue;\n }\n qbs::Configuration::Ptr configure(new qbs::Configuration);\n configurations.append(configure);\n\n foreach (const QString &property, buildCfg.keys()) {\n QStringList nameElements = property.split('.');\n if (nameElements.count() == 1)\n nameElements.prepend(\"qbs\");\n QVariantMap configValue = configure->value();\n qbs::setConfigProperty(configValue, nameElements, buildCfg.value(property));\n configure->setValue(configValue);\n }\n }\n\n qbs::Loader loader;\n loader.setSearchPaths(m_searchPaths);\n m_buildGraph = QSharedPointer<qbs::BuildGraph>(new qbs::BuildGraph);\n m_buildGraph->setOutputDirectoryRoot(QDir::currentPath());\n const QString buildDirectoryRoot = m_buildGraph->buildDirectoryRoot();\n\n try {\n foreach (const qbs::Configuration::Ptr &configure, configurations) {\n qbs::BuildProject::Ptr bProject;\n const qbs::FileTime projectFileTimeStamp = qbs::FileInfo(projectFileName).lastModified();\n bProject = qbs::BuildProject::load(m_buildGraph.data(), projectFileTimeStamp, configure, m_searchPaths);\n if (!bProject) {\n QElapsedTimer timer;\n timer.start();\n if (!loader.hasLoaded())\n loader.loadProject(projectFileName);\n qbs::ResolvedProject::Ptr rProject = loader.resolveProject(buildDirectoryRoot, configure, futureInterface);\n if (rProject->products.isEmpty())\n throw qbs::Error(QString(\"'%1' does not contain products.\").arg(projectFileName));\n qDebug() << \"loading project took: \" << timer.elapsed() << \"ms\";\n timer.start();\n bProject = m_buildGraph->resolveProject(rProject, futureInterface);\n qDebug() << \"build graph took: \" << timer.elapsed() << \"ms\";\n }\n\n m_buildProjects.append(bProject);\n\n printf(\"for %s:\\n\", qPrintable(bProject->resolvedProject()->id));\n foreach (qbs::ResolvedProduct::Ptr p, bProject->resolvedProject()->products) {\n printf(\" - [%s] %s as %s\\n\"\n ,qPrintable(p->fileTags.join(\", \"))\n ,qPrintable(p->name)\n ,qPrintable(p->project->id)\n );\n }\n printf(\"\\n\");\n }\n\n } catch (qbs::Error &e) {\n m_errors.append(e);\n futureInterface.reportResult(false);\n return;\n }\n\n futureInterface.reportResult(true);\n}\n\nQList<BuildProject::Ptr> SourceProject::buildProjects() const\n{\n return m_buildProjects;\n}\n\nQList<Error> SourceProject::errors() const\n{\n return m_errors;\n}\n\n} \/\/ namespace qbs\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n* BigInt Encoding\/Decoding\n* (C) 1999-2010,2012 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/bigint.h>\n#include <botan\/divide.h>\n#include <botan\/charset.h>\n#include <botan\/hex.h>\n\nnamespace Botan {\n\nstd::string BigInt::to_dec_string() const\n {\n BigInt copy = *this;\n copy.set_sign(Positive);\n\n BigInt remainder;\n std::vector<uint8_t> digits;\n\n while(copy > 0)\n {\n divide(copy, 10, copy, remainder);\n digits.push_back(static_cast<uint8_t>(remainder.word_at(0)));\n }\n\n std::string s;\n\n for(auto i = digits.rbegin(); i != digits.rend(); ++i)\n {\n s.push_back(Charset::digit2char(*i));\n }\n\n return s;\n }\n\nstd::string BigInt::to_hex_string() const\n {\n return hex_encode(BigInt::encode(*this));\n }\n\n\/*\n* Encode a BigInt\n*\/\nvoid BigInt::encode(uint8_t output[], const BigInt& n, Base base)\n {\n if(base == Binary)\n {\n n.binary_encode(output);\n }\n else if(base == Hexadecimal)\n {\n secure_vector<uint8_t> binary(n.encoded_size(Binary));\n n.binary_encode(binary.data());\n\n hex_encode(cast_uint8_ptr_to_char(output),\n binary.data(), binary.size());\n }\n else if(base == Decimal)\n {\n BigInt copy = n;\n BigInt remainder;\n copy.set_sign(Positive);\n const size_t output_size = n.encoded_size(Decimal);\n for(size_t j = 0; j != output_size; ++j)\n {\n divide(copy, 10, copy, remainder);\n output[output_size - 1 - j] =\n Charset::digit2char(static_cast<uint8_t>(remainder.word_at(0)));\n if(copy.is_zero())\n break;\n }\n }\n else\n throw Invalid_Argument(\"Unknown BigInt encoding method\");\n }\n\n\/*\n* Encode a BigInt\n*\/\nstd::vector<uint8_t> BigInt::encode(const BigInt& n, Base base)\n {\n if(base == Binary)\n return BigInt::encode(n);\n\n std::vector<uint8_t> output(n.encoded_size(base));\n encode(output.data(), n, base);\n for(size_t j = 0; j != output.size(); ++j)\n if(output[j] == 0)\n output[j] = '0';\n\n return output;\n }\n\n\/*\n* Encode a BigInt\n*\/\nsecure_vector<uint8_t> BigInt::encode_locked(const BigInt& n, Base base)\n {\n if(base == Binary)\n return BigInt::encode_locked(n);\n\n secure_vector<uint8_t> output(n.encoded_size(base));\n encode(output.data(), n, base);\n for(size_t j = 0; j != output.size(); ++j)\n if(output[j] == 0)\n output[j] = '0';\n\n return output;\n }\n\n\/*\n* Encode a BigInt, with leading 0s if needed\n*\/\nsecure_vector<uint8_t> BigInt::encode_1363(const BigInt& n, size_t bytes)\n {\n secure_vector<uint8_t> output(bytes);\n BigInt::encode_1363(output.data(), output.size(), n);\n return output;\n }\n\n\/\/static\nvoid BigInt::encode_1363(uint8_t output[], size_t bytes, const BigInt& n)\n {\n const size_t n_bytes = n.bytes();\n if(n_bytes > bytes)\n throw Encoding_Error(\"encode_1363: n is too large to encode properly\");\n\n const size_t leading_0s = bytes - n_bytes;\n encode(&output[leading_0s], n, Binary);\n }\n\n\/*\n* Encode two BigInt, with leading 0s if needed, and concatenate\n*\/\nsecure_vector<uint8_t> BigInt::encode_fixed_length_int_pair(const BigInt& n1, const BigInt& n2, size_t bytes)\n {\n secure_vector<uint8_t> output(2 * bytes);\n BigInt::encode_1363(output.data(), bytes, n1);\n BigInt::encode_1363(output.data() + bytes, bytes, n2);\n return output;\n }\n\n\/*\n* Decode a BigInt\n*\/\nBigInt BigInt::decode(const uint8_t buf[], size_t length, Base base)\n {\n BigInt r;\n if(base == Binary)\n r.binary_decode(buf, length);\n else if(base == Hexadecimal)\n {\n secure_vector<uint8_t> binary;\n\n if(length % 2)\n {\n \/\/ Handle lack of leading 0\n const char buf0_with_leading_0[2] =\n { '0', static_cast<char>(buf[0]) };\n\n binary = hex_decode_locked(buf0_with_leading_0, 2);\n\n binary += hex_decode_locked(cast_uint8_ptr_to_char(&buf[1]),\n length - 1,\n false);\n }\n else\n binary = hex_decode_locked(cast_uint8_ptr_to_char(buf),\n length, false);\n\n r.binary_decode(binary.data(), binary.size());\n }\n else if(base == Decimal)\n {\n for(size_t i = 0; i != length; ++i)\n {\n if(Charset::is_space(buf[i]))\n continue;\n\n if(!Charset::is_digit(buf[i]))\n throw Invalid_Argument(\"BigInt::decode: \"\n \"Invalid character in decimal input\");\n\n const uint8_t x = Charset::char2digit(buf[i]);\n\n if(x >= 10)\n throw Invalid_Argument(\"BigInt: Invalid decimal string\");\n\n r *= 10;\n r += x;\n }\n }\n else\n throw Invalid_Argument(\"Unknown BigInt decoding method\");\n return r;\n }\n\n}\n<commit_msg>Fix BigInt::to_{dec,hex}_string for zero<commit_after>\/*\n* BigInt Encoding\/Decoding\n* (C) 1999-2010,2012 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/bigint.h>\n#include <botan\/divide.h>\n#include <botan\/charset.h>\n#include <botan\/hex.h>\n\nnamespace Botan {\n\nstd::string BigInt::to_dec_string() const\n {\n BigInt copy = *this;\n copy.set_sign(Positive);\n\n BigInt remainder;\n std::vector<uint8_t> digits;\n\n while(copy > 0)\n {\n divide(copy, 10, copy, remainder);\n digits.push_back(static_cast<uint8_t>(remainder.word_at(0)));\n }\n\n std::string s;\n\n for(auto i = digits.rbegin(); i != digits.rend(); ++i)\n {\n s.push_back(Charset::digit2char(*i));\n }\n\n if(s.empty())\n s += \"0\";\n\n return s;\n }\n\nstd::string BigInt::to_hex_string() const\n {\n const std::vector<uint8_t> bits = BigInt::encode(*this);\n if(bits.empty())\n return \"00\";\n else\n return hex_encode(bits);\n }\n\n\/*\n* Encode a BigInt\n*\/\nvoid BigInt::encode(uint8_t output[], const BigInt& n, Base base)\n {\n if(base == Binary)\n {\n n.binary_encode(output);\n }\n else if(base == Hexadecimal)\n {\n secure_vector<uint8_t> binary(n.encoded_size(Binary));\n n.binary_encode(binary.data());\n\n hex_encode(cast_uint8_ptr_to_char(output),\n binary.data(), binary.size());\n }\n else if(base == Decimal)\n {\n BigInt copy = n;\n BigInt remainder;\n copy.set_sign(Positive);\n const size_t output_size = n.encoded_size(Decimal);\n for(size_t j = 0; j != output_size; ++j)\n {\n divide(copy, 10, copy, remainder);\n output[output_size - 1 - j] =\n Charset::digit2char(static_cast<uint8_t>(remainder.word_at(0)));\n if(copy.is_zero())\n break;\n }\n }\n else\n throw Invalid_Argument(\"Unknown BigInt encoding method\");\n }\n\n\/*\n* Encode a BigInt\n*\/\nstd::vector<uint8_t> BigInt::encode(const BigInt& n, Base base)\n {\n if(base == Binary)\n return BigInt::encode(n);\n\n std::vector<uint8_t> output(n.encoded_size(base));\n encode(output.data(), n, base);\n for(size_t j = 0; j != output.size(); ++j)\n if(output[j] == 0)\n output[j] = '0';\n\n return output;\n }\n\n\/*\n* Encode a BigInt\n*\/\nsecure_vector<uint8_t> BigInt::encode_locked(const BigInt& n, Base base)\n {\n if(base == Binary)\n return BigInt::encode_locked(n);\n\n secure_vector<uint8_t> output(n.encoded_size(base));\n encode(output.data(), n, base);\n for(size_t j = 0; j != output.size(); ++j)\n if(output[j] == 0)\n output[j] = '0';\n\n return output;\n }\n\n\/*\n* Encode a BigInt, with leading 0s if needed\n*\/\nsecure_vector<uint8_t> BigInt::encode_1363(const BigInt& n, size_t bytes)\n {\n secure_vector<uint8_t> output(bytes);\n BigInt::encode_1363(output.data(), output.size(), n);\n return output;\n }\n\n\/\/static\nvoid BigInt::encode_1363(uint8_t output[], size_t bytes, const BigInt& n)\n {\n const size_t n_bytes = n.bytes();\n if(n_bytes > bytes)\n throw Encoding_Error(\"encode_1363: n is too large to encode properly\");\n\n const size_t leading_0s = bytes - n_bytes;\n encode(&output[leading_0s], n, Binary);\n }\n\n\/*\n* Encode two BigInt, with leading 0s if needed, and concatenate\n*\/\nsecure_vector<uint8_t> BigInt::encode_fixed_length_int_pair(const BigInt& n1, const BigInt& n2, size_t bytes)\n {\n secure_vector<uint8_t> output(2 * bytes);\n BigInt::encode_1363(output.data(), bytes, n1);\n BigInt::encode_1363(output.data() + bytes, bytes, n2);\n return output;\n }\n\n\/*\n* Decode a BigInt\n*\/\nBigInt BigInt::decode(const uint8_t buf[], size_t length, Base base)\n {\n BigInt r;\n if(base == Binary)\n r.binary_decode(buf, length);\n else if(base == Hexadecimal)\n {\n secure_vector<uint8_t> binary;\n\n if(length % 2)\n {\n \/\/ Handle lack of leading 0\n const char buf0_with_leading_0[2] =\n { '0', static_cast<char>(buf[0]) };\n\n binary = hex_decode_locked(buf0_with_leading_0, 2);\n\n binary += hex_decode_locked(cast_uint8_ptr_to_char(&buf[1]),\n length - 1,\n false);\n }\n else\n binary = hex_decode_locked(cast_uint8_ptr_to_char(buf),\n length, false);\n\n r.binary_decode(binary.data(), binary.size());\n }\n else if(base == Decimal)\n {\n for(size_t i = 0; i != length; ++i)\n {\n if(Charset::is_space(buf[i]))\n continue;\n\n if(!Charset::is_digit(buf[i]))\n throw Invalid_Argument(\"BigInt::decode: \"\n \"Invalid character in decimal input\");\n\n const uint8_t x = Charset::char2digit(buf[i]);\n\n if(x >= 10)\n throw Invalid_Argument(\"BigInt: Invalid decimal string\");\n\n r *= 10;\n r += x;\n }\n }\n else\n throw Invalid_Argument(\"Unknown BigInt decoding method\");\n return r;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Hugh Perkins 2015 hughperkins at gmail\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License, \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <stdexcept>\n\n#include \"util\/FileHelper.h\"\n#include \"util\/stringhelper.h\"\n#include \"ManifestLoaderv1.h\"\n#include \"util\/JpegHelper.h\"\n\n#include \"DeepCLDllExport.h\"\n\nusing namespace std;\n\n#undef STATIC\n#undef VIRTUAL\n#define STATIC\n#define VIRTUAL\n\nPUBLIC STATIC bool ManifestLoaderv1::isFormatFor(std::string imagesFilepath) {\n cout << \"ManifestLoaderv1 checking format for \" << imagesFilepath << endl;\n string sigString = \"# format=deepcl-jpeg-list-v1 \";\n char *headerBytes = FileHelper::readBinaryChunk(imagesFilepath, 0, sigString.length() + 1);\n headerBytes[sigString.length()] = 0;\n bool matched = string(headerBytes) == sigString;\n cout << \"matched: \" << matched << endl;\n return matched;\n}\nPUBLIC ManifestLoaderv1::ManifestLoaderv1(std::string imagesFilepath) {\n init(imagesFilepath);\n}\nPRIVATE void ManifestLoaderv1::init(std::string imagesFilepath) {\n this->imagesFilepath = imagesFilepath;\n \/\/ by reading the number of lines in the manifest, we can get the number of examples, *p_N\n \/\/ number of planes is .... 1\n \/\/ imageSize is ...\n\n if(!isFormatFor(imagesFilepath) ) {\n throw runtime_error(\"file \" + imagesFilepath + \" is not a deepcl-jpeg-list-v1 manifest file\");\n }\n\n ifstream infile(imagesFilepath);\n char lineChars[1024];\n infile.getline(lineChars, 1024); \/\/ skip first, header, line\n string firstLine = string(lineChars);\n\/\/ cout << \"firstline: [\" << firstLine << \"]\" << endl;\n vector<string> splitLine = split(firstLine, \" \");\n N = readIntValue(splitLine, \"N\");\n planes = readIntValue(splitLine, \"planes\");\n size = readIntValue(splitLine, \"width\");\n int imageSizeRepeated = readIntValue(splitLine, \"height\");\n if(size != imageSizeRepeated) {\n throw runtime_error(\"file \" + imagesFilepath + \" contains non-square images. Not handled for now.\");\n }\n \/\/ now we should load into memory, since the file is not fixed-size records, and cannot be loaded partially easily\n\n files = new string[N];\n labels = 0;\n\n int n = 0;\n hasLabels = false;\n while(infile) {\n infile.getline(lineChars, 1024);\n if(!infile) {\n break;\n }\n string line = string(lineChars);\n if(line == \"\") {\n continue;\n }\n vector<string> splitLine = split(line, \" \");\n if((int)splitLine.size() == 0) {\n continue;\n }\n if(n == 0) {\n int lineSize = (int)splitLine.size();\n if(lineSize == 2) {\n hasLabels = true;\n labels = new int[N];\n }\n }\n if(!hasLabels && (int)splitLine.size() != 1) { \n throw runtime_error(\"Error reading \" + imagesFilepath + \". Following line not parseable:\\n\" + line);\n }\n if(hasLabels && (int)splitLine.size() != 2) { \n throw runtime_error(\"Error reading \" + imagesFilepath + \". Following line not parseable:\\n\" + line);\n }\n string jpegFile = splitLine[0];\n #ifdef _WIN32\n if(jpegFile[1] != ':' && jpegFile[0] != '\\\\') { \/\/ I guess this means its a relative path?\n vector<string> splitManifestPath = split(imagesFilepath, \"\\\\\");\n string dirPath = replace(imagesFilepath, splitManifestPath[splitManifestPath.size()-1], \"\");\n jpegFile = dirPath + jpegFile;\n }\n #else\n if(jpegFile[0] != '\/') { \/\/ this is a bit hacky, but at least handles linux and mac for now...\n vector<string> splitManifestPath = split(imagesFilepath, \"\/\");\n string dirPath = replace(imagesFilepath, splitManifestPath[splitManifestPath.size()-1], \"\");\n jpegFile = dirPath + jpegFile;\n }\n #endif\n files[n] = jpegFile;\n if(hasLabels) {\n int label = atoi(splitLine[1]);\n labels[n] = label;\n }\n\/\/ cout << \"file \" << jpegFile << \" label=\" << label << endl;\n n++;\n }\n infile.close();\n if(n != N) {\n throw runtime_error(\"Error: number of images declared in manifest \" + toString(N) + \" doesnt match number actually in manifest \" + to_string(n));\n }\n\n cout << \"manifest \" << imagesFilepath << \" read. N=\" << N << \" planes=\" << planes << \" size=\" << size << \" labels? \" << hasLabels << endl;\n}\nPUBLIC VIRTUAL std::string ManifestLoaderv1::getType() {\n return \"ManifestLoaderv1\";\n}\nPUBLIC VIRTUAL int ManifestLoaderv1::getImageCubeSize() {\n return planes * size * size;\n}\nPUBLIC VIRTUAL int ManifestLoaderv1::getN() {\n return N;\n}\nPUBLIC VIRTUAL int ManifestLoaderv1::getPlanes() {\n return planes;\n}\nPUBLIC VIRTUAL int ManifestLoaderv1::getImageSize() {\n return size;\n}\nint ManifestLoaderv1::readIntValue(std::vector< std::string > splitLine, std::string key) {\n for(int i = 0; i < (int)splitLine.size(); i++) {\n vector<string> splitPair = split(splitLine[i], \"=\");\n if((int)splitPair.size() == 2) {\n if(splitPair[0] == key) {\n return atoi(splitPair[1]);\n }\n }\n }\n throw runtime_error(\"Key \" + key + \" not found in file header\");\n}\nPUBLIC VIRTUAL void ManifestLoaderv1::load(unsigned char *data, int *labels, int startRecord, int numRecords) {\n int imageCubeSize = planes * size * size;\n\/\/ cout << \"ManifestLoaderv1, loading \" << numRecords << \" jpegs\" << endl;\n for(int localN = 0; localN < numRecords; localN++) {\n int globalN = localN + startRecord;\n if(globalN >= N) {\n return;\n }\n JpegHelper::read(files[globalN], planes, size, size, data + localN * imageCubeSize);\n if(labels != 0) {\n if(!hasLabels) {\n throw runtime_error(\"ManifestLoaderv1: labels reqested in load() method, but none found in file\");\n }\n labels[localN] = this->labels[globalN];\n }\n }\n}\n\n<commit_msg>another tostring<commit_after>\/\/ Copyright Hugh Perkins 2015 hughperkins at gmail\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License, \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <stdexcept>\n\n#include \"util\/FileHelper.h\"\n#include \"util\/stringhelper.h\"\n#include \"ManifestLoaderv1.h\"\n#include \"util\/JpegHelper.h\"\n\n#include \"DeepCLDllExport.h\"\n\nusing namespace std;\n\n#undef STATIC\n#undef VIRTUAL\n#define STATIC\n#define VIRTUAL\n\nPUBLIC STATIC bool ManifestLoaderv1::isFormatFor(std::string imagesFilepath) {\n cout << \"ManifestLoaderv1 checking format for \" << imagesFilepath << endl;\n string sigString = \"# format=deepcl-jpeg-list-v1 \";\n char *headerBytes = FileHelper::readBinaryChunk(imagesFilepath, 0, sigString.length() + 1);\n headerBytes[sigString.length()] = 0;\n bool matched = string(headerBytes) == sigString;\n cout << \"matched: \" << matched << endl;\n return matched;\n}\nPUBLIC ManifestLoaderv1::ManifestLoaderv1(std::string imagesFilepath) {\n init(imagesFilepath);\n}\nPRIVATE void ManifestLoaderv1::init(std::string imagesFilepath) {\n this->imagesFilepath = imagesFilepath;\n \/\/ by reading the number of lines in the manifest, we can get the number of examples, *p_N\n \/\/ number of planes is .... 1\n \/\/ imageSize is ...\n\n if(!isFormatFor(imagesFilepath) ) {\n throw runtime_error(\"file \" + imagesFilepath + \" is not a deepcl-jpeg-list-v1 manifest file\");\n }\n\n ifstream infile(imagesFilepath);\n char lineChars[1024];\n infile.getline(lineChars, 1024); \/\/ skip first, header, line\n string firstLine = string(lineChars);\n\/\/ cout << \"firstline: [\" << firstLine << \"]\" << endl;\n vector<string> splitLine = split(firstLine, \" \");\n N = readIntValue(splitLine, \"N\");\n planes = readIntValue(splitLine, \"planes\");\n size = readIntValue(splitLine, \"width\");\n int imageSizeRepeated = readIntValue(splitLine, \"height\");\n if(size != imageSizeRepeated) {\n throw runtime_error(\"file \" + imagesFilepath + \" contains non-square images. Not handled for now.\");\n }\n \/\/ now we should load into memory, since the file is not fixed-size records, and cannot be loaded partially easily\n\n files = new string[N];\n labels = 0;\n\n int n = 0;\n hasLabels = false;\n while(infile) {\n infile.getline(lineChars, 1024);\n if(!infile) {\n break;\n }\n string line = string(lineChars);\n if(line == \"\") {\n continue;\n }\n vector<string> splitLine = split(line, \" \");\n if((int)splitLine.size() == 0) {\n continue;\n }\n if(n == 0) {\n int lineSize = (int)splitLine.size();\n if(lineSize == 2) {\n hasLabels = true;\n labels = new int[N];\n }\n }\n if(!hasLabels && (int)splitLine.size() != 1) { \n throw runtime_error(\"Error reading \" + imagesFilepath + \". Following line not parseable:\\n\" + line);\n }\n if(hasLabels && (int)splitLine.size() != 2) { \n throw runtime_error(\"Error reading \" + imagesFilepath + \". Following line not parseable:\\n\" + line);\n }\n string jpegFile = splitLine[0];\n #ifdef _WIN32\n if(jpegFile[1] != ':' && jpegFile[0] != '\\\\') { \/\/ I guess this means its a relative path?\n vector<string> splitManifestPath = split(imagesFilepath, \"\\\\\");\n string dirPath = replace(imagesFilepath, splitManifestPath[splitManifestPath.size()-1], \"\");\n jpegFile = dirPath + jpegFile;\n }\n #else\n if(jpegFile[0] != '\/') { \/\/ this is a bit hacky, but at least handles linux and mac for now...\n vector<string> splitManifestPath = split(imagesFilepath, \"\/\");\n string dirPath = replace(imagesFilepath, splitManifestPath[splitManifestPath.size()-1], \"\");\n jpegFile = dirPath + jpegFile;\n }\n #endif\n files[n] = jpegFile;\n if(hasLabels) {\n int label = atoi(splitLine[1]);\n labels[n] = label;\n }\n\/\/ cout << \"file \" << jpegFile << \" label=\" << label << endl;\n n++;\n }\n infile.close();\n if(n != N) {\n throw runtime_error(\"Error: number of images declared in manifest \" + toString(N) + \" doesnt match number actually in manifest \" + toString(n));\n }\n\n cout << \"manifest \" << imagesFilepath << \" read. N=\" << N << \" planes=\" << planes << \" size=\" << size << \" labels? \" << hasLabels << endl;\n}\nPUBLIC VIRTUAL std::string ManifestLoaderv1::getType() {\n return \"ManifestLoaderv1\";\n}\nPUBLIC VIRTUAL int ManifestLoaderv1::getImageCubeSize() {\n return planes * size * size;\n}\nPUBLIC VIRTUAL int ManifestLoaderv1::getN() {\n return N;\n}\nPUBLIC VIRTUAL int ManifestLoaderv1::getPlanes() {\n return planes;\n}\nPUBLIC VIRTUAL int ManifestLoaderv1::getImageSize() {\n return size;\n}\nint ManifestLoaderv1::readIntValue(std::vector< std::string > splitLine, std::string key) {\n for(int i = 0; i < (int)splitLine.size(); i++) {\n vector<string> splitPair = split(splitLine[i], \"=\");\n if((int)splitPair.size() == 2) {\n if(splitPair[0] == key) {\n return atoi(splitPair[1]);\n }\n }\n }\n throw runtime_error(\"Key \" + key + \" not found in file header\");\n}\nPUBLIC VIRTUAL void ManifestLoaderv1::load(unsigned char *data, int *labels, int startRecord, int numRecords) {\n int imageCubeSize = planes * size * size;\n\/\/ cout << \"ManifestLoaderv1, loading \" << numRecords << \" jpegs\" << endl;\n for(int localN = 0; localN < numRecords; localN++) {\n int globalN = localN + startRecord;\n if(globalN >= N) {\n return;\n }\n JpegHelper::read(files[globalN], planes, size, size, data + localN * imageCubeSize);\n if(labels != 0) {\n if(!hasLabels) {\n throw runtime_error(\"ManifestLoaderv1: labels reqested in load() method, but none found in file\");\n }\n labels[localN] = this->labels[globalN];\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"content\/browser\/renderer_host\/gesture_event_filter.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host_impl.h\"\n#include \"content\/browser\/renderer_host\/tap_suppression_controller.h\"\n#include \"content\/public\/common\/content_switches.h\"\n\nusing WebKit::WebGestureEvent;\nusing WebKit::WebInputEvent;\n\nnamespace content {\nnamespace {\n\n\/\/ Default maximum time between the GestureRecognizer generating a\n\/\/ GestureTapDown and when it is forwarded to the renderer.\nstatic const int kTapDownDeferralTimeMs = 150;\n\n\/\/ Default debouncing interval duration: if a scroll is in progress, non-scroll\n\/\/ events during this interval are deferred to either its end or discarded on\n\/\/ receipt of another GestureScrollUpdate.\nstatic const int kDebouncingIntervalTimeMs = 30;\n\n\/\/ Sets |*value| to |switchKey| if it exists or sets it to |defaultValue|.\nstatic void GetParamHelper(int* value,\n int defaultValue,\n const char switchKey[]) {\n if (*value < 0) {\n *value = defaultValue;\n CommandLine* command_line = CommandLine::ForCurrentProcess();\n std::string command_line_param =\n command_line->GetSwitchValueASCII(switchKey);\n if (!command_line_param.empty()) {\n int v;\n if (base::StringToInt(command_line_param, &v))\n *value = v;\n }\n DCHECK_GE(*value, 0);\n }\n}\n\nstatic int GetTapDownDeferralTimeMs() {\n static int tap_down_deferral_time_window = -1;\n GetParamHelper(&tap_down_deferral_time_window,\n kTapDownDeferralTimeMs,\n switches::kTapDownDeferralTimeMs);\n return tap_down_deferral_time_window;\n}\n} \/\/ namespace\n\nGestureEventFilter::GestureEventFilter(RenderWidgetHostImpl* rwhv)\n : render_widget_host_(rwhv),\n fling_in_progress_(false),\n scrolling_in_progress_(false),\n tap_suppression_controller_(new TapSuppressionController(rwhv)),\n maximum_tap_gap_time_ms_(GetTapDownDeferralTimeMs()),\n debounce_interval_time_ms_(kDebouncingIntervalTimeMs) {\n}\n\nGestureEventFilter::~GestureEventFilter() { }\n\nbool GestureEventFilter::ShouldDiscardFlingCancelEvent(\n const WebKit::WebGestureEvent& gesture_event) {\n if (coalesced_gesture_events_.empty() && fling_in_progress_)\n return false;\n GestureEventQueue::reverse_iterator it =\n coalesced_gesture_events_.rbegin();\n while (it != coalesced_gesture_events_.rend()) {\n if (it->type == WebInputEvent::GestureFlingStart)\n return false;\n if (it->type == WebInputEvent::GestureFlingCancel)\n return true;\n it++;\n }\n return true;\n}\n\nbool GestureEventFilter::ShouldForwardForBounceReduction(\n const WebGestureEvent& gesture_event) {\n switch (gesture_event.type) {\n case WebInputEvent::GestureScrollUpdate:\n if (!scrolling_in_progress_) {\n debounce_deferring_timer_.Start(FROM_HERE,\n base::TimeDelta::FromMilliseconds(debounce_interval_time_ms_),\n this,\n &GestureEventFilter::SendScrollEndingEventsNow);\n } else {\n \/\/ Extend the bounce interval.\n debounce_deferring_timer_.Reset();\n }\n scrolling_in_progress_ = true;\n debouncing_deferral_queue_.clear();\n return true;\n case WebInputEvent::GesturePinchBegin:\n \/\/ TODO(rjkroege): Debounce pinch (http:\/\/crbug.com\/147647)\n scrolling_in_progress_ = false;\n return true;\n default:\n if (scrolling_in_progress_) {\n debouncing_deferral_queue_.push_back(gesture_event);\n return false;\n }\n return true;\n }\n\n NOTREACHED();\n return false;\n}\n\n\/\/ NOTE: The filters are applied successively. This simplifies the change.\nbool GestureEventFilter::ShouldForward(const WebGestureEvent& gesture_event) {\n if (debounce_interval_time_ms_ == 0 ||\n ShouldForwardForBounceReduction(gesture_event))\n return ShouldForwardForTapDeferral(gesture_event);\n return false;\n}\n\n\/\/ TODO(rjkroege): separate touchpad and touchscreen events.\nbool GestureEventFilter::ShouldForwardForTapDeferral(\n const WebGestureEvent& gesture_event) {\n switch (gesture_event.type) {\n case WebInputEvent::GestureFlingCancel:\n if (!ShouldDiscardFlingCancelEvent(gesture_event)) {\n coalesced_gesture_events_.push_back(gesture_event);\n fling_in_progress_ = false;\n return ShouldHandleEventNow();\n }\n return false;\n case WebInputEvent::GestureFlingStart:\n fling_in_progress_ = true;\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n case WebInputEvent::GestureTapDown:\n \/\/ GestureTapDown is always paired with either a Tap or TapCancel, so\n \/\/ it should be impossible to have more than one outstanding at a time.\n DCHECK_EQ(deferred_tap_down_event_.type, WebInputEvent::Undefined);\n deferred_tap_down_event_ = gesture_event;\n send_gtd_timer_.Start(FROM_HERE,\n base::TimeDelta::FromMilliseconds(maximum_tap_gap_time_ms_),\n this,\n &GestureEventFilter::SendGestureTapDownNow);\n return false;\n case WebInputEvent::GestureTapCancel:\n if (deferred_tap_down_event_.type == WebInputEvent::Undefined) {\n \/\/ The TapDown has already been put in the queue, must send the\n \/\/ corresponding TapCancel as well.\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n }\n \/\/ Cancelling a deferred TapDown, just drop them on the floor.\n send_gtd_timer_.Stop();\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n return false;\n case WebInputEvent::GestureTap:\n send_gtd_timer_.Stop();\n if (deferred_tap_down_event_.type != WebInputEvent::Undefined) {\n coalesced_gesture_events_.push_back(deferred_tap_down_event_);\n if (ShouldHandleEventNow())\n render_widget_host_->ForwardGestureEventImmediately(\n deferred_tap_down_event_);\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n coalesced_gesture_events_.push_back(gesture_event);\n return false;\n }\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n case WebInputEvent::GestureScrollBegin:\n case WebInputEvent::GesturePinchBegin:\n send_gtd_timer_.Stop();\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n case WebInputEvent::GestureScrollUpdate:\n MergeOrInsertScrollEvent(gesture_event);\n return ShouldHandleEventNow();\n default:\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n }\n\n NOTREACHED();\n return false;\n}\n\nvoid GestureEventFilter::Reset() {\n fling_in_progress_ = false;\n scrolling_in_progress_ = false;\n coalesced_gesture_events_.clear();\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n debouncing_deferral_queue_.clear();\n send_gtd_timer_.Stop();\n debounce_deferring_timer_.Stop();\n \/\/ TODO(rjkroege): Reset the tap suppression controller.\n}\n\nvoid GestureEventFilter::ProcessGestureAck(bool processed, int type) {\n DCHECK_EQ(coalesced_gesture_events_.front().type, type);\n coalesced_gesture_events_.pop_front();\n if (!coalesced_gesture_events_.empty()) {\n WebGestureEvent next_gesture_event = coalesced_gesture_events_.front();\n render_widget_host_->ForwardGestureEventImmediately(next_gesture_event);\n }\n}\n\nTapSuppressionController* GestureEventFilter::GetTapSuppressionController() {\n return tap_suppression_controller_.get();\n}\n\nvoid GestureEventFilter::FlingHasBeenHalted() {\n fling_in_progress_ = false;\n}\n\nbool GestureEventFilter::ShouldHandleEventNow() {\n return coalesced_gesture_events_.size() == 1;\n}\n\nvoid GestureEventFilter::SendGestureTapDownNow() {\n \/\/ We must not have already sent the deferred TapDown (if we did, we would\n \/\/ have stopped the timer, which prevents this task from running - even if\n \/\/ it's time had already elapsed).\n DCHECK_EQ(deferred_tap_down_event_.type, WebInputEvent::GestureTapDown);\n coalesced_gesture_events_.push_back(deferred_tap_down_event_);\n if (ShouldHandleEventNow()) {\n render_widget_host_->ForwardGestureEventImmediately(\n deferred_tap_down_event_);\n }\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n}\n\nvoid GestureEventFilter::SendScrollEndingEventsNow() {\n scrolling_in_progress_ = false;\n for (GestureEventQueue::iterator it =\n debouncing_deferral_queue_.begin();\n it != debouncing_deferral_queue_.end(); it++) {\n if (ShouldForwardForTapDeferral(*it)) {\n render_widget_host_->ForwardGestureEventImmediately(*it);\n }\n }\n debouncing_deferral_queue_.clear();\n}\n\nvoid GestureEventFilter::MergeOrInsertScrollEvent(\n const WebGestureEvent& gesture_event) {\n WebGestureEvent* last_gesture_event = coalesced_gesture_events_.empty() ? 0 :\n &coalesced_gesture_events_.back();\n if (coalesced_gesture_events_.size() > 1 &&\n last_gesture_event->type == gesture_event.type &&\n last_gesture_event->modifiers == gesture_event.modifiers) {\n last_gesture_event->data.scrollUpdate.deltaX +=\n gesture_event.data.scrollUpdate.deltaX;\n last_gesture_event->data.scrollUpdate.deltaY +=\n gesture_event.data.scrollUpdate.deltaY;\n DLOG_IF(WARNING,\n gesture_event.timeStampSeconds <=\n last_gesture_event->timeStampSeconds)\n << \"Event time not monotonic?\\n\";\n DCHECK(last_gesture_event->type == WebInputEvent::GestureScrollUpdate);\n last_gesture_event->timeStampSeconds = gesture_event.timeStampSeconds;\n } else {\n coalesced_gesture_events_.push_back(gesture_event);\n }\n}\n\n} \/\/ namespace content\n<commit_msg>Send pinch events to webkit without putting them into the deboucing deferral queue<commit_after>\/\/ 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 \"content\/browser\/renderer_host\/gesture_event_filter.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host_impl.h\"\n#include \"content\/browser\/renderer_host\/tap_suppression_controller.h\"\n#include \"content\/public\/common\/content_switches.h\"\n\nusing WebKit::WebGestureEvent;\nusing WebKit::WebInputEvent;\n\nnamespace content {\nnamespace {\n\n\/\/ Default maximum time between the GestureRecognizer generating a\n\/\/ GestureTapDown and when it is forwarded to the renderer.\nstatic const int kTapDownDeferralTimeMs = 150;\n\n\/\/ Default debouncing interval duration: if a scroll is in progress, non-scroll\n\/\/ events during this interval are deferred to either its end or discarded on\n\/\/ receipt of another GestureScrollUpdate.\nstatic const int kDebouncingIntervalTimeMs = 30;\n\n\/\/ Sets |*value| to |switchKey| if it exists or sets it to |defaultValue|.\nstatic void GetParamHelper(int* value,\n int defaultValue,\n const char switchKey[]) {\n if (*value < 0) {\n *value = defaultValue;\n CommandLine* command_line = CommandLine::ForCurrentProcess();\n std::string command_line_param =\n command_line->GetSwitchValueASCII(switchKey);\n if (!command_line_param.empty()) {\n int v;\n if (base::StringToInt(command_line_param, &v))\n *value = v;\n }\n DCHECK_GE(*value, 0);\n }\n}\n\nstatic int GetTapDownDeferralTimeMs() {\n static int tap_down_deferral_time_window = -1;\n GetParamHelper(&tap_down_deferral_time_window,\n kTapDownDeferralTimeMs,\n switches::kTapDownDeferralTimeMs);\n return tap_down_deferral_time_window;\n}\n} \/\/ namespace\n\nGestureEventFilter::GestureEventFilter(RenderWidgetHostImpl* rwhv)\n : render_widget_host_(rwhv),\n fling_in_progress_(false),\n scrolling_in_progress_(false),\n tap_suppression_controller_(new TapSuppressionController(rwhv)),\n maximum_tap_gap_time_ms_(GetTapDownDeferralTimeMs()),\n debounce_interval_time_ms_(kDebouncingIntervalTimeMs) {\n}\n\nGestureEventFilter::~GestureEventFilter() { }\n\nbool GestureEventFilter::ShouldDiscardFlingCancelEvent(\n const WebKit::WebGestureEvent& gesture_event) {\n if (coalesced_gesture_events_.empty() && fling_in_progress_)\n return false;\n GestureEventQueue::reverse_iterator it =\n coalesced_gesture_events_.rbegin();\n while (it != coalesced_gesture_events_.rend()) {\n if (it->type == WebInputEvent::GestureFlingStart)\n return false;\n if (it->type == WebInputEvent::GestureFlingCancel)\n return true;\n it++;\n }\n return true;\n}\n\nbool GestureEventFilter::ShouldForwardForBounceReduction(\n const WebGestureEvent& gesture_event) {\n switch (gesture_event.type) {\n case WebInputEvent::GestureScrollUpdate:\n if (!scrolling_in_progress_) {\n debounce_deferring_timer_.Start(FROM_HERE,\n base::TimeDelta::FromMilliseconds(debounce_interval_time_ms_),\n this,\n &GestureEventFilter::SendScrollEndingEventsNow);\n } else {\n \/\/ Extend the bounce interval.\n debounce_deferring_timer_.Reset();\n }\n scrolling_in_progress_ = true;\n debouncing_deferral_queue_.clear();\n return true;\n case WebInputEvent::GesturePinchBegin:\n case WebInputEvent::GesturePinchEnd:\n case WebInputEvent::GesturePinchUpdate:\n \/\/ TODO(rjkroege): Debounce pinch (http:\/\/crbug.com\/147647)\n return true;\n default:\n if (scrolling_in_progress_) {\n debouncing_deferral_queue_.push_back(gesture_event);\n return false;\n }\n return true;\n }\n\n NOTREACHED();\n return false;\n}\n\n\/\/ NOTE: The filters are applied successively. This simplifies the change.\nbool GestureEventFilter::ShouldForward(const WebGestureEvent& gesture_event) {\n if (debounce_interval_time_ms_ == 0 ||\n ShouldForwardForBounceReduction(gesture_event))\n return ShouldForwardForTapDeferral(gesture_event);\n return false;\n}\n\n\/\/ TODO(rjkroege): separate touchpad and touchscreen events.\nbool GestureEventFilter::ShouldForwardForTapDeferral(\n const WebGestureEvent& gesture_event) {\n switch (gesture_event.type) {\n case WebInputEvent::GestureFlingCancel:\n if (!ShouldDiscardFlingCancelEvent(gesture_event)) {\n coalesced_gesture_events_.push_back(gesture_event);\n fling_in_progress_ = false;\n return ShouldHandleEventNow();\n }\n return false;\n case WebInputEvent::GestureFlingStart:\n fling_in_progress_ = true;\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n case WebInputEvent::GestureTapDown:\n \/\/ GestureTapDown is always paired with either a Tap or TapCancel, so\n \/\/ it should be impossible to have more than one outstanding at a time.\n DCHECK_EQ(deferred_tap_down_event_.type, WebInputEvent::Undefined);\n deferred_tap_down_event_ = gesture_event;\n send_gtd_timer_.Start(FROM_HERE,\n base::TimeDelta::FromMilliseconds(maximum_tap_gap_time_ms_),\n this,\n &GestureEventFilter::SendGestureTapDownNow);\n return false;\n case WebInputEvent::GestureTapCancel:\n if (deferred_tap_down_event_.type == WebInputEvent::Undefined) {\n \/\/ The TapDown has already been put in the queue, must send the\n \/\/ corresponding TapCancel as well.\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n }\n \/\/ Cancelling a deferred TapDown, just drop them on the floor.\n send_gtd_timer_.Stop();\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n return false;\n case WebInputEvent::GestureTap:\n send_gtd_timer_.Stop();\n if (deferred_tap_down_event_.type != WebInputEvent::Undefined) {\n coalesced_gesture_events_.push_back(deferred_tap_down_event_);\n if (ShouldHandleEventNow())\n render_widget_host_->ForwardGestureEventImmediately(\n deferred_tap_down_event_);\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n coalesced_gesture_events_.push_back(gesture_event);\n return false;\n }\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n case WebInputEvent::GestureScrollBegin:\n case WebInputEvent::GesturePinchBegin:\n send_gtd_timer_.Stop();\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n case WebInputEvent::GestureScrollUpdate:\n MergeOrInsertScrollEvent(gesture_event);\n return ShouldHandleEventNow();\n default:\n coalesced_gesture_events_.push_back(gesture_event);\n return ShouldHandleEventNow();\n }\n\n NOTREACHED();\n return false;\n}\n\nvoid GestureEventFilter::Reset() {\n fling_in_progress_ = false;\n scrolling_in_progress_ = false;\n coalesced_gesture_events_.clear();\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n debouncing_deferral_queue_.clear();\n send_gtd_timer_.Stop();\n debounce_deferring_timer_.Stop();\n \/\/ TODO(rjkroege): Reset the tap suppression controller.\n}\n\nvoid GestureEventFilter::ProcessGestureAck(bool processed, int type) {\n DCHECK_EQ(coalesced_gesture_events_.front().type, type);\n coalesced_gesture_events_.pop_front();\n if (!coalesced_gesture_events_.empty()) {\n WebGestureEvent next_gesture_event = coalesced_gesture_events_.front();\n render_widget_host_->ForwardGestureEventImmediately(next_gesture_event);\n }\n}\n\nTapSuppressionController* GestureEventFilter::GetTapSuppressionController() {\n return tap_suppression_controller_.get();\n}\n\nvoid GestureEventFilter::FlingHasBeenHalted() {\n fling_in_progress_ = false;\n}\n\nbool GestureEventFilter::ShouldHandleEventNow() {\n return coalesced_gesture_events_.size() == 1;\n}\n\nvoid GestureEventFilter::SendGestureTapDownNow() {\n \/\/ We must not have already sent the deferred TapDown (if we did, we would\n \/\/ have stopped the timer, which prevents this task from running - even if\n \/\/ it's time had already elapsed).\n DCHECK_EQ(deferred_tap_down_event_.type, WebInputEvent::GestureTapDown);\n coalesced_gesture_events_.push_back(deferred_tap_down_event_);\n if (ShouldHandleEventNow()) {\n render_widget_host_->ForwardGestureEventImmediately(\n deferred_tap_down_event_);\n }\n deferred_tap_down_event_.type = WebInputEvent::Undefined;\n}\n\nvoid GestureEventFilter::SendScrollEndingEventsNow() {\n scrolling_in_progress_ = false;\n for (GestureEventQueue::iterator it =\n debouncing_deferral_queue_.begin();\n it != debouncing_deferral_queue_.end(); it++) {\n if (ShouldForwardForTapDeferral(*it)) {\n render_widget_host_->ForwardGestureEventImmediately(*it);\n }\n }\n debouncing_deferral_queue_.clear();\n}\n\nvoid GestureEventFilter::MergeOrInsertScrollEvent(\n const WebGestureEvent& gesture_event) {\n WebGestureEvent* last_gesture_event = coalesced_gesture_events_.empty() ? 0 :\n &coalesced_gesture_events_.back();\n if (coalesced_gesture_events_.size() > 1 &&\n last_gesture_event->type == gesture_event.type &&\n last_gesture_event->modifiers == gesture_event.modifiers) {\n last_gesture_event->data.scrollUpdate.deltaX +=\n gesture_event.data.scrollUpdate.deltaX;\n last_gesture_event->data.scrollUpdate.deltaY +=\n gesture_event.data.scrollUpdate.deltaY;\n DLOG_IF(WARNING,\n gesture_event.timeStampSeconds <=\n last_gesture_event->timeStampSeconds)\n << \"Event time not monotonic?\\n\";\n DCHECK(last_gesture_event->type == WebInputEvent::GestureScrollUpdate);\n last_gesture_event->timeStampSeconds = gesture_event.timeStampSeconds;\n } else {\n coalesced_gesture_events_.push_back(gesture_event);\n }\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"content\/browser\/tab_contents\/tab_contents_view_win.h\"\n\n#include \"base\/bind.h\"\n#include \"content\/browser\/renderer_host\/render_view_host_factory.h\"\n#include \"content\/browser\/renderer_host\/render_view_host_impl.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host_view_win.h\"\n#include \"content\/browser\/tab_contents\/interstitial_page_impl.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/browser\/tab_contents\/web_contents_drag_win.h\"\n#include \"content\/browser\/tab_contents\/web_drag_dest_win.h\"\n#include \"content\/public\/browser\/web_contents_delegate.h\"\n#include \"content\/public\/browser\/web_contents_view_win_delegate.h\"\n#include \"ui\/gfx\/screen.h\"\n\nusing content::RenderViewHost;\nusing content::RenderWidgetHostView;\nusing content::WebContents;\nusing content::WebContentsViewWinDelegate;\n\nnamespace {\n\n\/\/ We need to have a parent window for the compositing code to work correctly.\n\/\/\n\/\/ A tab will not have a parent HWND whenever it is not active in its\n\/\/ host window - for example at creation time and when it's in the\n\/\/ background, so we provide a default widget to host them.\n\/\/\n\/\/ It may be tempting to use GetDesktopWindow() instead, but this is\n\/\/ problematic as the shell sends messages to children of the desktop\n\/\/ window that interact poorly with us.\n\/\/\n\/\/ See: http:\/\/crbug.com\/16476\nclass TempParent : public ui::WindowImpl {\n public:\n static TempParent* Get() {\n static TempParent* g_temp_parent;\n if (!g_temp_parent) {\n g_temp_parent = new TempParent();\n\n g_temp_parent->set_window_style(WS_POPUP);\n g_temp_parent->set_window_ex_style(WS_EX_TOOLWINDOW);\n g_temp_parent->Init(GetDesktopWindow(), gfx::Rect());\n EnableWindow(g_temp_parent->hwnd(), FALSE);\n }\n return g_temp_parent;\n }\n\n private:\n BEGIN_MSG_MAP_EX(TabContentsViewWin)\n END_MSG_MAP()\n};\n\n} \/\/ namespace namespace\n\nTabContentsViewWin::TabContentsViewWin(WebContents* web_contents,\n WebContentsViewWinDelegate* delegate)\n : tab_contents_(static_cast<TabContents*>(web_contents)),\n view_(NULL),\n delegate_(delegate),\n close_tab_after_drag_ends_(false) {\n}\n\nTabContentsViewWin::~TabContentsViewWin() {\n if (IsWindow(hwnd()))\n DestroyWindow(hwnd());\n}\n\nvoid TabContentsViewWin::CreateView(const gfx::Size& initial_size) {\n initial_size_ = initial_size;\n\n set_window_style(WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);\n\n Init(TempParent::Get()->hwnd(), gfx::Rect(initial_size_));\n\n \/\/ Remove the root view drop target so we can register our own.\n RevokeDragDrop(GetNativeView());\n drag_dest_ = new WebDragDest(hwnd(), tab_contents_);\n if (delegate_.get()) {\n content::WebDragDestDelegate* delegate = delegate_->GetDragDestDelegate();\n if (delegate)\n drag_dest_->set_delegate(delegate);\n }\n}\n\nRenderWidgetHostView* TabContentsViewWin::CreateViewForWidget(\n content::RenderWidgetHost* render_widget_host) {\n if (render_widget_host->GetView()) {\n \/\/ During testing, the view will already be set up in most cases to the\n \/\/ test view, so we don't want to clobber it with a real one. To verify that\n \/\/ this actually is happening (and somebody isn't accidentally creating the\n \/\/ view twice), we check for the RVH Factory, which will be set when we're\n \/\/ making special ones (which go along with the special views).\n DCHECK(RenderViewHostFactory::has_factory());\n return render_widget_host->GetView();\n }\n\n view_ = static_cast<RenderWidgetHostViewWin*>(\n RenderWidgetHostView::CreateViewForWidget(render_widget_host));\n view_->CreateWnd(GetNativeView());\n view_->ShowWindow(SW_SHOW);\n view_->SetSize(initial_size_);\n return view_;\n}\n\ngfx::NativeView TabContentsViewWin::GetNativeView() const {\n return hwnd();\n}\n\ngfx::NativeView TabContentsViewWin::GetContentNativeView() const {\n RenderWidgetHostView* rwhv = tab_contents_->GetRenderWidgetHostView();\n return rwhv ? rwhv->GetNativeView() : NULL;\n}\n\ngfx::NativeWindow TabContentsViewWin::GetTopLevelNativeWindow() const {\n return GetParent(GetNativeView());\n}\n\nvoid TabContentsViewWin::GetContainerBounds(gfx::Rect *out) const {\n \/\/ Copied from NativeWidgetWin::GetClientAreaScreenBounds().\n RECT r;\n GetClientRect(hwnd(), &r);\n POINT point = { r.left, r.top };\n ClientToScreen(hwnd(), &point);\n *out = gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top);\n}\n\nvoid TabContentsViewWin::SetPageTitle(const string16& title) {\n \/\/ It's possible to get this after the hwnd has been destroyed.\n if (GetNativeView())\n ::SetWindowText(GetNativeView(), title.c_str());\n}\n\nvoid TabContentsViewWin::OnTabCrashed(base::TerminationStatus status,\n int error_code) {\n \/\/ TODO(avi): No other TCV implementation does anything in this callback. Can\n \/\/ this be moved elsewhere so that |OnTabCrashed| can be removed everywhere?\n view_ = NULL;\n}\n\nvoid TabContentsViewWin::SizeContents(const gfx::Size& size) {\n gfx::Rect bounds;\n GetContainerBounds(&bounds);\n if (bounds.size() != size) {\n SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(),\n SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);\n } else {\n \/\/ Our size matches what we want but the renderers size may not match.\n \/\/ Pretend we were resized so that the renderers size is updated too.\n if (tab_contents_->GetInterstitialPage())\n tab_contents_->GetInterstitialPage()->SetSize(size);\n RenderWidgetHostView* rwhv = tab_contents_->GetRenderWidgetHostView();\n if (rwhv)\n rwhv->SetSize(size);\n }\n}\n\nvoid TabContentsViewWin::RenderViewCreated(RenderViewHost* host) {\n}\n\nvoid TabContentsViewWin::Focus() {\n if (tab_contents_->GetInterstitialPage()) {\n tab_contents_->GetInterstitialPage()->Focus();\n return;\n }\n\n if (delegate_.get() && delegate_->Focus())\n return;\n\n RenderWidgetHostView* rwhv = tab_contents_->GetRenderWidgetHostView();\n if (rwhv)\n rwhv->Focus();\n}\n\nvoid TabContentsViewWin::SetInitialFocus() {\n if (tab_contents_->FocusLocationBarByDefault())\n tab_contents_->SetFocusToLocationBar(false);\n else\n Focus();\n}\n\nvoid TabContentsViewWin::StoreFocus() {\n if (delegate_.get())\n delegate_->StoreFocus();\n}\n\nvoid TabContentsViewWin::RestoreFocus() {\n if (delegate_.get())\n delegate_->RestoreFocus();\n}\n\nbool TabContentsViewWin::IsDoingDrag() const {\n return drag_handler_.get() != NULL;\n}\n\nvoid TabContentsViewWin::CancelDragAndCloseTab() {\n DCHECK(IsDoingDrag());\n \/\/ We can't close the tab while we're in the drag and\n \/\/ |drag_handler_->CancelDrag()| is async. Instead, set a flag to cancel\n \/\/ the drag and when the drag nested message loop ends, close the tab.\n drag_handler_->CancelDrag();\n close_tab_after_drag_ends_ = true;\n}\n\nbool TabContentsViewWin::IsEventTracking() const {\n return false;\n}\n\nvoid TabContentsViewWin::CloseTabAfterEventTracking() {\n}\n\nvoid TabContentsViewWin::GetViewBounds(gfx::Rect* out) const {\n RECT r;\n GetWindowRect(hwnd(), &r);\n *out = gfx::Rect(r);\n}\n\nvoid TabContentsViewWin::CreateNewWindow(\n int route_id,\n const ViewHostMsg_CreateWindow_Params& params) {\n tab_contents_view_helper_.CreateNewWindow(tab_contents_, route_id, params);\n}\n\nvoid TabContentsViewWin::CreateNewWidget(int route_id,\n WebKit::WebPopupType popup_type) {\n tab_contents_view_helper_.CreateNewWidget(tab_contents_,\n route_id,\n false,\n popup_type);\n}\n\nvoid TabContentsViewWin::CreateNewFullscreenWidget(int route_id) {\n tab_contents_view_helper_.CreateNewWidget(tab_contents_,\n route_id,\n true,\n WebKit::WebPopupTypeNone);\n}\n\nvoid TabContentsViewWin::ShowCreatedWindow(int route_id,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n tab_contents_view_helper_.ShowCreatedWindow(\n tab_contents_, route_id, disposition, initial_pos, user_gesture);\n}\n\nvoid TabContentsViewWin::ShowCreatedWidget(int route_id,\n const gfx::Rect& initial_pos) {\n tab_contents_view_helper_.ShowCreatedWidget(tab_contents_,\n route_id,\n false,\n initial_pos);\n}\n\nvoid TabContentsViewWin::ShowCreatedFullscreenWidget(int route_id) {\n tab_contents_view_helper_.ShowCreatedWidget(tab_contents_,\n route_id,\n true,\n gfx::Rect());\n}\n\nvoid TabContentsViewWin::ShowContextMenu(\n const content::ContextMenuParams& params) {\n \/\/ Allow WebContentsDelegates to handle the context menu operation first.\n if (tab_contents_->GetDelegate() &&\n tab_contents_->GetDelegate()->HandleContextMenu(params)) {\n return;\n }\n\n if (delegate_.get())\n delegate_->ShowContextMenu(params);\n}\n\nvoid TabContentsViewWin::ShowPopupMenu(const gfx::Rect& bounds,\n int item_height,\n double item_font_size,\n int selected_item,\n const std::vector<WebMenuItem>& items,\n bool right_aligned) {\n \/\/ External popup menus are only used on Mac.\n NOTIMPLEMENTED();\n}\n\nvoid TabContentsViewWin::StartDragging(const WebDropData& drop_data,\n WebKit::WebDragOperationsMask operations,\n const SkBitmap& image,\n const gfx::Point& image_offset) {\n drag_handler_ = new WebContentsDragWin(\n GetNativeView(),\n tab_contents_,\n drag_dest_,\n base::Bind(&TabContentsViewWin::EndDragging, base::Unretained(this)));\n drag_handler_->StartDragging(drop_data, operations, image, image_offset);\n}\n\nvoid TabContentsViewWin::UpdateDragCursor(WebKit::WebDragOperation operation) {\n drag_dest_->set_drag_cursor(operation);\n}\n\nvoid TabContentsViewWin::GotFocus() {\n if (tab_contents_->GetDelegate())\n tab_contents_->GetDelegate()->WebContentsFocused(tab_contents_);\n}\n\nvoid TabContentsViewWin::TakeFocus(bool reverse) {\n if (tab_contents_->GetDelegate() &&\n !tab_contents_->GetDelegate()->TakeFocus(reverse) &&\n delegate_.get()) {\n delegate_->TakeFocus(reverse);\n }\n}\n\nvoid TabContentsViewWin::EndDragging() {\n drag_handler_ = NULL;\n if (close_tab_after_drag_ends_) {\n close_tab_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(0),\n this, &TabContentsViewWin::CloseTab);\n }\n tab_contents_->SystemDragEnded();\n}\n\nvoid TabContentsViewWin::CloseTab() {\n RenderViewHost* rvh = tab_contents_->GetRenderViewHost();\n rvh->GetDelegate()->Close(rvh);\n}\n\nLRESULT TabContentsViewWin::OnDestroy(\n UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n if (drag_dest_.get()) {\n RevokeDragDrop(GetNativeView());\n drag_dest_ = NULL;\n }\n return 0;\n}\n\nLRESULT TabContentsViewWin::OnWindowPosChanged(\n UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n WINDOWPOS* window_pos = reinterpret_cast<WINDOWPOS*>(lparam);\n if (window_pos->flags & SWP_NOSIZE)\n return 0;\n\n gfx::Size size(window_pos->cx, window_pos->cy);\n if (tab_contents_->GetInterstitialPage())\n tab_contents_->GetInterstitialPage()->SetSize(size);\n RenderWidgetHostView* rwhv = tab_contents_->GetRenderWidgetHostView();\n if (rwhv)\n rwhv->SetSize(size);\n\n if (delegate_.get())\n delegate_->SizeChanged(size);\n\n return 0;\n}\n\nLRESULT TabContentsViewWin::OnMouseDown(\n UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n \/\/ Make sure this TabContents is activated when it is clicked on.\n if (tab_contents_->GetDelegate())\n tab_contents_->GetDelegate()->ActivateContents(tab_contents_);\n return 0;\n}\n\nLRESULT TabContentsViewWin::OnMouseMove(\n UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n \/\/ Let our delegate know that the mouse moved (useful for resetting status\n \/\/ bubble state).\n if (tab_contents_->GetDelegate()) {\n tab_contents_->GetDelegate()->ContentsMouseEvent(\n tab_contents_, gfx::Screen::GetCursorScreenPoint(), true);\n }\n return 0;\n}\n\nLRESULT TabContentsViewWin::OnReflectedMessage(\n UINT msg, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n MSG* message = reinterpret_cast<MSG*>(lparam);\n switch (message->message) {\n case WM_MOUSEWHEEL:\n \/\/ This message is reflected from the view() to this window.\n if (GET_KEYSTATE_WPARAM(message->wParam) & MK_CONTROL) {\n tab_contents_->GetDelegate()->ContentsZoomChange(\n GET_WHEEL_DELTA_WPARAM(message->wParam) > 0);\n return 1;\n }\n break;\n }\n return 0;\n}\n<commit_msg>Fix repainting not happening when switching tabs after resizing the browser. I didn't copy this behavior from TCVViews to TCVWin.<commit_after>\/\/ 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 \"content\/browser\/tab_contents\/tab_contents_view_win.h\"\n\n#include \"base\/bind.h\"\n#include \"content\/browser\/renderer_host\/render_view_host_factory.h\"\n#include \"content\/browser\/renderer_host\/render_view_host_impl.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host_view_win.h\"\n#include \"content\/browser\/tab_contents\/interstitial_page_impl.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/browser\/tab_contents\/web_contents_drag_win.h\"\n#include \"content\/browser\/tab_contents\/web_drag_dest_win.h\"\n#include \"content\/public\/browser\/web_contents_delegate.h\"\n#include \"content\/public\/browser\/web_contents_view_win_delegate.h\"\n#include \"ui\/gfx\/screen.h\"\n\nusing content::RenderViewHost;\nusing content::RenderWidgetHostView;\nusing content::WebContents;\nusing content::WebContentsViewWinDelegate;\n\nnamespace {\n\n\/\/ We need to have a parent window for the compositing code to work correctly.\n\/\/\n\/\/ A tab will not have a parent HWND whenever it is not active in its\n\/\/ host window - for example at creation time and when it's in the\n\/\/ background, so we provide a default widget to host them.\n\/\/\n\/\/ It may be tempting to use GetDesktopWindow() instead, but this is\n\/\/ problematic as the shell sends messages to children of the desktop\n\/\/ window that interact poorly with us.\n\/\/\n\/\/ See: http:\/\/crbug.com\/16476\nclass TempParent : public ui::WindowImpl {\n public:\n static TempParent* Get() {\n static TempParent* g_temp_parent;\n if (!g_temp_parent) {\n g_temp_parent = new TempParent();\n\n g_temp_parent->set_window_style(WS_POPUP);\n g_temp_parent->set_window_ex_style(WS_EX_TOOLWINDOW);\n g_temp_parent->Init(GetDesktopWindow(), gfx::Rect());\n EnableWindow(g_temp_parent->hwnd(), FALSE);\n }\n return g_temp_parent;\n }\n\n private:\n BEGIN_MSG_MAP_EX(TabContentsViewWin)\n END_MSG_MAP()\n};\n\n} \/\/ namespace namespace\n\nTabContentsViewWin::TabContentsViewWin(WebContents* web_contents,\n WebContentsViewWinDelegate* delegate)\n : tab_contents_(static_cast<TabContents*>(web_contents)),\n view_(NULL),\n delegate_(delegate),\n close_tab_after_drag_ends_(false) {\n}\n\nTabContentsViewWin::~TabContentsViewWin() {\n if (IsWindow(hwnd()))\n DestroyWindow(hwnd());\n}\n\nvoid TabContentsViewWin::CreateView(const gfx::Size& initial_size) {\n initial_size_ = initial_size;\n\n set_window_style(WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);\n\n Init(TempParent::Get()->hwnd(), gfx::Rect(initial_size_));\n\n \/\/ Remove the root view drop target so we can register our own.\n RevokeDragDrop(GetNativeView());\n drag_dest_ = new WebDragDest(hwnd(), tab_contents_);\n if (delegate_.get()) {\n content::WebDragDestDelegate* delegate = delegate_->GetDragDestDelegate();\n if (delegate)\n drag_dest_->set_delegate(delegate);\n }\n}\n\nRenderWidgetHostView* TabContentsViewWin::CreateViewForWidget(\n content::RenderWidgetHost* render_widget_host) {\n if (render_widget_host->GetView()) {\n \/\/ During testing, the view will already be set up in most cases to the\n \/\/ test view, so we don't want to clobber it with a real one. To verify that\n \/\/ this actually is happening (and somebody isn't accidentally creating the\n \/\/ view twice), we check for the RVH Factory, which will be set when we're\n \/\/ making special ones (which go along with the special views).\n DCHECK(RenderViewHostFactory::has_factory());\n return render_widget_host->GetView();\n }\n\n view_ = static_cast<RenderWidgetHostViewWin*>(\n RenderWidgetHostView::CreateViewForWidget(render_widget_host));\n view_->CreateWnd(GetNativeView());\n view_->ShowWindow(SW_SHOW);\n view_->SetSize(initial_size_);\n return view_;\n}\n\ngfx::NativeView TabContentsViewWin::GetNativeView() const {\n return hwnd();\n}\n\ngfx::NativeView TabContentsViewWin::GetContentNativeView() const {\n RenderWidgetHostView* rwhv = tab_contents_->GetRenderWidgetHostView();\n return rwhv ? rwhv->GetNativeView() : NULL;\n}\n\ngfx::NativeWindow TabContentsViewWin::GetTopLevelNativeWindow() const {\n return GetParent(GetNativeView());\n}\n\nvoid TabContentsViewWin::GetContainerBounds(gfx::Rect *out) const {\n \/\/ Copied from NativeWidgetWin::GetClientAreaScreenBounds().\n RECT r;\n GetClientRect(hwnd(), &r);\n POINT point = { r.left, r.top };\n ClientToScreen(hwnd(), &point);\n *out = gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top);\n}\n\nvoid TabContentsViewWin::SetPageTitle(const string16& title) {\n \/\/ It's possible to get this after the hwnd has been destroyed.\n if (GetNativeView())\n ::SetWindowText(GetNativeView(), title.c_str());\n}\n\nvoid TabContentsViewWin::OnTabCrashed(base::TerminationStatus status,\n int error_code) {\n \/\/ TODO(avi): No other TCV implementation does anything in this callback. Can\n \/\/ this be moved elsewhere so that |OnTabCrashed| can be removed everywhere?\n view_ = NULL;\n}\n\nvoid TabContentsViewWin::SizeContents(const gfx::Size& size) {\n gfx::Rect bounds;\n GetContainerBounds(&bounds);\n if (bounds.size() != size) {\n SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(),\n SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);\n } else {\n \/\/ Our size matches what we want but the renderers size may not match.\n \/\/ Pretend we were resized so that the renderers size is updated too.\n if (tab_contents_->GetInterstitialPage())\n tab_contents_->GetInterstitialPage()->SetSize(size);\n RenderWidgetHostView* rwhv = tab_contents_->GetRenderWidgetHostView();\n if (rwhv)\n rwhv->SetSize(size);\n }\n}\n\nvoid TabContentsViewWin::RenderViewCreated(RenderViewHost* host) {\n}\n\nvoid TabContentsViewWin::Focus() {\n if (tab_contents_->GetInterstitialPage()) {\n tab_contents_->GetInterstitialPage()->Focus();\n return;\n }\n\n if (delegate_.get() && delegate_->Focus())\n return;\n\n RenderWidgetHostView* rwhv = tab_contents_->GetRenderWidgetHostView();\n if (rwhv)\n rwhv->Focus();\n}\n\nvoid TabContentsViewWin::SetInitialFocus() {\n if (tab_contents_->FocusLocationBarByDefault())\n tab_contents_->SetFocusToLocationBar(false);\n else\n Focus();\n}\n\nvoid TabContentsViewWin::StoreFocus() {\n if (delegate_.get())\n delegate_->StoreFocus();\n}\n\nvoid TabContentsViewWin::RestoreFocus() {\n if (delegate_.get())\n delegate_->RestoreFocus();\n}\n\nbool TabContentsViewWin::IsDoingDrag() const {\n return drag_handler_.get() != NULL;\n}\n\nvoid TabContentsViewWin::CancelDragAndCloseTab() {\n DCHECK(IsDoingDrag());\n \/\/ We can't close the tab while we're in the drag and\n \/\/ |drag_handler_->CancelDrag()| is async. Instead, set a flag to cancel\n \/\/ the drag and when the drag nested message loop ends, close the tab.\n drag_handler_->CancelDrag();\n close_tab_after_drag_ends_ = true;\n}\n\nbool TabContentsViewWin::IsEventTracking() const {\n return false;\n}\n\nvoid TabContentsViewWin::CloseTabAfterEventTracking() {\n}\n\nvoid TabContentsViewWin::GetViewBounds(gfx::Rect* out) const {\n RECT r;\n GetWindowRect(hwnd(), &r);\n *out = gfx::Rect(r);\n}\n\nvoid TabContentsViewWin::CreateNewWindow(\n int route_id,\n const ViewHostMsg_CreateWindow_Params& params) {\n tab_contents_view_helper_.CreateNewWindow(tab_contents_, route_id, params);\n}\n\nvoid TabContentsViewWin::CreateNewWidget(int route_id,\n WebKit::WebPopupType popup_type) {\n tab_contents_view_helper_.CreateNewWidget(tab_contents_,\n route_id,\n false,\n popup_type);\n}\n\nvoid TabContentsViewWin::CreateNewFullscreenWidget(int route_id) {\n tab_contents_view_helper_.CreateNewWidget(tab_contents_,\n route_id,\n true,\n WebKit::WebPopupTypeNone);\n}\n\nvoid TabContentsViewWin::ShowCreatedWindow(int route_id,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n tab_contents_view_helper_.ShowCreatedWindow(\n tab_contents_, route_id, disposition, initial_pos, user_gesture);\n}\n\nvoid TabContentsViewWin::ShowCreatedWidget(int route_id,\n const gfx::Rect& initial_pos) {\n tab_contents_view_helper_.ShowCreatedWidget(tab_contents_,\n route_id,\n false,\n initial_pos);\n}\n\nvoid TabContentsViewWin::ShowCreatedFullscreenWidget(int route_id) {\n tab_contents_view_helper_.ShowCreatedWidget(tab_contents_,\n route_id,\n true,\n gfx::Rect());\n}\n\nvoid TabContentsViewWin::ShowContextMenu(\n const content::ContextMenuParams& params) {\n \/\/ Allow WebContentsDelegates to handle the context menu operation first.\n if (tab_contents_->GetDelegate() &&\n tab_contents_->GetDelegate()->HandleContextMenu(params)) {\n return;\n }\n\n if (delegate_.get())\n delegate_->ShowContextMenu(params);\n}\n\nvoid TabContentsViewWin::ShowPopupMenu(const gfx::Rect& bounds,\n int item_height,\n double item_font_size,\n int selected_item,\n const std::vector<WebMenuItem>& items,\n bool right_aligned) {\n \/\/ External popup menus are only used on Mac.\n NOTIMPLEMENTED();\n}\n\nvoid TabContentsViewWin::StartDragging(const WebDropData& drop_data,\n WebKit::WebDragOperationsMask operations,\n const SkBitmap& image,\n const gfx::Point& image_offset) {\n drag_handler_ = new WebContentsDragWin(\n GetNativeView(),\n tab_contents_,\n drag_dest_,\n base::Bind(&TabContentsViewWin::EndDragging, base::Unretained(this)));\n drag_handler_->StartDragging(drop_data, operations, image, image_offset);\n}\n\nvoid TabContentsViewWin::UpdateDragCursor(WebKit::WebDragOperation operation) {\n drag_dest_->set_drag_cursor(operation);\n}\n\nvoid TabContentsViewWin::GotFocus() {\n if (tab_contents_->GetDelegate())\n tab_contents_->GetDelegate()->WebContentsFocused(tab_contents_);\n}\n\nvoid TabContentsViewWin::TakeFocus(bool reverse) {\n if (tab_contents_->GetDelegate() &&\n !tab_contents_->GetDelegate()->TakeFocus(reverse) &&\n delegate_.get()) {\n delegate_->TakeFocus(reverse);\n }\n}\n\nvoid TabContentsViewWin::EndDragging() {\n drag_handler_ = NULL;\n if (close_tab_after_drag_ends_) {\n close_tab_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(0),\n this, &TabContentsViewWin::CloseTab);\n }\n tab_contents_->SystemDragEnded();\n}\n\nvoid TabContentsViewWin::CloseTab() {\n RenderViewHost* rvh = tab_contents_->GetRenderViewHost();\n rvh->GetDelegate()->Close(rvh);\n}\n\nLRESULT TabContentsViewWin::OnDestroy(\n UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n if (drag_dest_.get()) {\n RevokeDragDrop(GetNativeView());\n drag_dest_ = NULL;\n }\n return 0;\n}\n\nLRESULT TabContentsViewWin::OnWindowPosChanged(\n UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n WINDOWPOS* window_pos = reinterpret_cast<WINDOWPOS*>(lparam);\n if (window_pos->flags & SWP_HIDEWINDOW) {\n tab_contents_->HideContents();\n return 0;\n }\n\n \/\/ The TabContents was shown by a means other than the user selecting a\n \/\/ Tab, e.g. the window was minimized then restored.\n if (window_pos->flags & SWP_SHOWWINDOW)\n tab_contents_->ShowContents();\n\n \/\/ Unless we were specifically told not to size, cause the renderer to be\n \/\/ sized to the new bounds, which forces a repaint. Not required for the\n \/\/ simple minimize-restore case described above, for example, since the\n \/\/ size hasn't changed.\n if (window_pos->flags & SWP_NOSIZE)\n return 0;\n\n gfx::Size size(window_pos->cx, window_pos->cy);\n if (tab_contents_->GetInterstitialPage())\n tab_contents_->GetInterstitialPage()->SetSize(size);\n RenderWidgetHostView* rwhv = tab_contents_->GetRenderWidgetHostView();\n if (rwhv)\n rwhv->SetSize(size);\n\n if (delegate_.get())\n delegate_->SizeChanged(size);\n\n return 0;\n}\n\nLRESULT TabContentsViewWin::OnMouseDown(\n UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n \/\/ Make sure this TabContents is activated when it is clicked on.\n if (tab_contents_->GetDelegate())\n tab_contents_->GetDelegate()->ActivateContents(tab_contents_);\n return 0;\n}\n\nLRESULT TabContentsViewWin::OnMouseMove(\n UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n \/\/ Let our delegate know that the mouse moved (useful for resetting status\n \/\/ bubble state).\n if (tab_contents_->GetDelegate()) {\n tab_contents_->GetDelegate()->ContentsMouseEvent(\n tab_contents_, gfx::Screen::GetCursorScreenPoint(), true);\n }\n return 0;\n}\n\nLRESULT TabContentsViewWin::OnReflectedMessage(\n UINT msg, WPARAM wparam, LPARAM lparam, BOOL& handled) {\n MSG* message = reinterpret_cast<MSG*>(lparam);\n switch (message->message) {\n case WM_MOUSEWHEEL:\n \/\/ This message is reflected from the view() to this window.\n if (GET_KEYSTATE_WPARAM(message->wParam) & MK_CONTROL) {\n tab_contents_->GetDelegate()->ContentsZoomChange(\n GET_WHEEL_DELTA_WPARAM(message->wParam) > 0);\n return 1;\n }\n break;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <inttypes.h>\n\n#include \"mutex.hpp\"\n#include \"task.hpp\"\n#include \"EiTOSConfig.hpp\"\n#include \"port\/port.hpp\"\n\nuint8_t MutexUsed = 0;\nuint8_t MutexTaken[MAX_MUTEX] = {false};\n\nmutex::mutex() {\n MutexUsed++;\n this->nr = MutexUsed;\n}\n\nvoid mutex::give() {\n if ( MutexTaken[this->nr] == false )\n return;\n MutexTaken[this->nr] = false;\n for (uint8_t i = 0; i < TaskQueue.size(); i++) {\n if ( TaskQueue[i].blockingMutexNr == this->nr ) {\n TaskStruct_t taskRemoved = TaskQueue[i];\n taskRemoved.blockingMutexNr = 0;\n TaskQueue.remove(i);\n TaskQueue.push(taskRemoved);\n }\n }\n TriggerSysTick();\n}\n\nvoid mutex::take() {\n MutexTaken[this->nr] = true;\n TaskStruct_t task = TaskQueue.front();\n TaskQueue.pop();\n task.blockingMutexNr = this->nr;\n TaskQueue.push(task);\n TriggerSysTick();\n}\n\nbool mutex::take(uint32_t timeout) {\n}\n<commit_msg>extracting task operating functions in mutex struct<commit_after>#include <inttypes.h>\n\n#include \"mutex.hpp\"\n#include \"task.hpp\"\n#include \"EiTOSConfig.hpp\"\n#include \"port\/port.hpp\"\n\nuint8_t MutexUsed = 0;\nuint8_t MutexTaken[MAX_MUTEX] = {false};\n\nmutex::mutex() {\n MutexUsed++;\n this->nr = MutexUsed;\n}\n\nstatic inline void unlockTasksByMutex(uint8_t mutexNr) {\n for (uint8_t i = 0; i < TaskQueue.size(); i++) {\n if ( TaskQueue[i].blockingMutexNr == mutexNr ) {\n TaskStruct_t taskRemoved = TaskQueue[i];\n taskRemoved.blockingMutexNr = 0;\n TaskQueue.remove(i);\n TaskQueue.push(taskRemoved);\n }\n }\n}\n\nvoid mutex::give() {\n if ( MutexTaken[this->nr] == false )\n return;\n MutexTaken[this->nr] = false;\n unlockTasksByMutex(this->nr);\n TriggerSysTick();\n}\n\nstatic inline void lockTaskByMutex(uint8_t mutexNr) {\n TaskStruct_t task = TaskQueue.front();\n TaskQueue.pop();\n task.blockingMutexNr = mutexNr;\n TaskQueue.push(task);\n}\n\nvoid mutex::take() {\n MutexTaken[this->nr] = true;\n lockTaskByMutex(this->nr);\n TriggerSysTick();\n}\n\nbool mutex::take(uint32_t timeout) {\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n* Copyright 2014 Steven T Sell (ssell@ocularinteractive.com)\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#include \"Utilities\/UIDGenerator.hpp\"\n\n\/\/------------------------------------------------------------------------------------------\n\nnamespace Ocular\n{\n namespace Utils\n {\n \/\/----------------------------------------------------------------------------------\n \/\/ CONSTRUCTORS\n \/\/----------------------------------------------------------------------------------\n\n UIDGenerator::UIDGenerator()\n {\n m_UID = 0;\n }\n\n UIDGenerator::~UIDGenerator()\n {\n \n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PUBLIC METHODS\n \/\/----------------------------------------------------------------------------------\n\n unsigned UIDGenerator::next()\n {\n m_Mutex.lock();\n m_UID++;\n m_Mutex.unlock();\n\n return m_UID;\n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PROTECTED METHODS\n \/\/----------------------------------------------------------------------------------\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PRIVATE METHODS\n \/\/----------------------------------------------------------------------------------\n \n }\n}<commit_msg>UIDGenerator should actually be thread-safe now<commit_after>\/**\n* Copyright 2014 Steven T Sell (ssell@ocularinteractive.com)\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#include \"Utilities\/UIDGenerator.hpp\"\n\n\/\/------------------------------------------------------------------------------------------\n\nnamespace Ocular\n{\n namespace Utils\n {\n \/\/----------------------------------------------------------------------------------\n \/\/ CONSTRUCTORS\n \/\/----------------------------------------------------------------------------------\n\n UIDGenerator::UIDGenerator()\n {\n m_UID = 0;\n }\n\n UIDGenerator::~UIDGenerator()\n {\n \n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PUBLIC METHODS\n \/\/----------------------------------------------------------------------------------\n\n unsigned UIDGenerator::next()\n {\n int returnID;\n\n m_Mutex.lock();\n returnID = ++m_UID;\n m_Mutex.unlock();\n\n return returnID;\n }\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PROTECTED METHODS\n \/\/----------------------------------------------------------------------------------\n\n \/\/----------------------------------------------------------------------------------\n \/\/ PRIVATE METHODS\n \/\/----------------------------------------------------------------------------------\n \n }\n}<|endoftext|>"} {"text":"<commit_before>#include \"Fb2File.h\"\n#include \"..\/DesktopEditor\/xml\/include\/xmlutils.h\"\n#include \"..\/DesktopEditor\/common\/Base64.h\"\n#include \"..\/DesktopEditor\/common\/File.h\"\n\n#include <vector>\n#include <map>\n\n\/\/ Тэг author\nstruct author\n{\n std::wstring first_name;\n std::wstring middle_name;\n std::wstring last_name;\n std::wstring nickname;\n std::vector<std::wstring> home_page;\n std::vector<std::wstring> email;\n};\n\nclass CFb2File_Private\n{\npublic:\n XmlUtils::CXmlLiteReader m_oLightReader; \/\/ SAX Reader\n std::wstring m_sFile; \/\/ Имя файла\n std::wstring m_sDstFolder; \/\/ Путь к результату\n \/\/ Контент файла\n std::vector<std::wstring> m_arGenres; \/\/ Жанры\n std::vector<author> m_arAuthors; \/\/ Авторы\n std::vector<author> m_arTranslator; \/\/ Переводчики\n\n std::wstring m_sBookTitle; \/\/ Название\n std::wstring m_sLang; \/\/ Язык после перевода\n\n std::wstring* m_pAnnotation; \/\/ Аннотация\n std::wstring* m_pKeywords; \/\/ Ключевые слова\n std::pair<std::wstring, std::wstring>* m_pDate; \/\/ Дата\n std::wstring* m_pCoverpage; \/\/ Обложка\n std::wstring* m_pSrcLang; \/\/ Язык до перевода\n\n std::map<std::wstring, std::wstring> m_mXmlns; \/\/ Ссылки\n std::map<std::wstring, std::wstring> m_mSequence; \/\/ Серии книг\n std::map<std::wstring, std::wstring> m_mImage; \/\/ Картинки\n\npublic:\n CFb2File_Private()\n {\n m_pAnnotation = NULL;\n m_pKeywords = NULL;\n m_pDate = NULL;\n m_pCoverpage = NULL;\n m_pSrcLang = NULL;\n }\n\n ~CFb2File_Private()\n {\n m_oLightReader.Clear();\n m_arGenres.clear();\n m_arAuthors.clear();\n m_arTranslator.clear();\n m_mXmlns.clear();\n m_mSequence.clear();\n m_mImage.clear();\n RELEASEARRAYOBJECTS(m_pAnnotation);\n RELEASEARRAYOBJECTS(m_pKeywords);\n RELEASEARRAYOBJECTS(m_pDate);\n RELEASEARRAYOBJECTS(m_pCoverpage);\n RELEASEARRAYOBJECTS(m_pSrcLang);\n }\n\n \/\/ Читает и проверят соответствует ли текущий раздел ожиданиям\n bool isSection(const std::wstring& sName)\n {\n if(!m_oLightReader.ReadNextNode())\n return false;\n if(m_oLightReader.GetName() != sName)\n return false;\n return true;\n }\n\n \/\/ Читает поля автора\n bool readAuthor(std::vector<author>& arAuthor)\n {\n author oAuthor;\n int nDepth = m_oLightReader.GetDepth();\n while(m_oLightReader.ReadNextSiblingNode(nDepth))\n {\n std::wstring sName = m_oLightReader.GetName();\n std::wstring sRes;\n if(sName == L\"first-name\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.first_name = sRes;\n }\n else if(sName == L\"middle-name\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.middle_name = sRes;\n }\n else if(sName == L\"last-name\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.last_name = sRes;\n }\n else if(sName == L\"nickname\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.nickname = sRes;\n }\n else if(sName == L\"home-page\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.home_page.push_back(sRes);\n }\n else if(sName == L\"email\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.email.push_back(sRes);\n }\n else\n return false;\n }\n arAuthor.push_back(oAuthor);\n return true;\n }\n\n \/\/ Возвращает содержание узла\n std::wstring content()\n {\n std::wstring sRes = L\"\";\n if(m_oLightReader.ReadNextSiblingNode2(m_oLightReader.GetDepth()))\n sRes = m_oLightReader.GetText();\n return sRes;\n }\n\n std::string contentA(std::wstring is)\n {\n std::string sRes = \"\";\n if(m_oLightReader.ReadNextSiblingNode2(m_oLightReader.GetDepth()))\n sRes = m_oLightReader.GetTextA();\n return sRes;\n }\n};\n\nCFb2File::CFb2File()\n{\n m_internal = new CFb2File_Private();\n}\n\nCFb2File::~CFb2File()\n{\n RELEASEOBJECT(m_internal);\n}\n\n\/\/ Проверяет, соответствует ли fb2 файл формату\nbool CFb2File::IsFb2File(const std::wstring& sFile)\n{\n if (!m_internal->m_oLightReader.FromFile(sFile))\n return false;\n\n \/\/ Читаем FictionBook\n if(!m_internal->isSection(L\"FictionBook\"))\n return false;\n while(m_internal->m_oLightReader.MoveToNextAttribute())\n m_internal->m_mXmlns.insert(std::make_pair(m_internal->m_oLightReader.GetName(), m_internal->m_oLightReader.GetText()));\n m_internal->m_sFile = sFile;\n return true;\n}\n\n\/\/ Выставление временной (рабочей) папки\nvoid CFb2File::SetImpDirectory(const std::wstring& sFolder)\n{\n m_internal->m_sDstFolder = sFolder;\n}\n\n\/\/ Проверяет, соответствует ли fb2 файл формату\n\/\/ sPath - путь к сохраненному файлу, sDirectory - путь к сохраненным картинкам\nint CFb2File::Convert (const std::wstring& sPath, const std::wstring& sDirectory)\n{\n \/\/ Читаем description\n if(!m_internal->isSection(L\"description\"))\n return false;\n\n \/\/ Читаем наполнение description\n \/\/ Читаем title-info\n if(!m_internal->isSection(L\"title-info\"))\n return false;\n\n \/\/ Читаем наполнение title-info\n \/\/ Читаем genre (один или более)\n if(!m_internal->isSection(L\"genre\"))\n return false;\n do\n {\n std::wstring sGenre;\n sGenre = m_internal->content();\n if(sGenre == L\"\")\n return false;\n m_internal->m_arGenres.push_back(sGenre);\n } while(m_internal->isSection(L\"genre\"));\n\n \/\/ Читаем author (один или более)\n do\n {\n if(!m_internal->readAuthor(m_internal->m_arAuthors))\n return false;\n } while(m_internal->isSection(L\"author\"));\n\n \/\/ Читаем book-title\n if(m_internal->m_oLightReader.GetName() != L\"book-title\")\n return false;\n std::wstring sBookTitle;\n sBookTitle = m_internal->content();\n if(sBookTitle == L\"\")\n return false;\n m_internal->m_sBookTitle = sBookTitle;\n\n \/\/ Читаем все до lang\n while(!m_internal->isSection(L\"lang\"))\n {\n if(m_internal->m_oLightReader.GetDepth() == 0)\n return false;\n std::wstring sRes;\n std::wstring sName = m_internal->m_oLightReader.GetName();\n\n \/\/ Читаем annotation (ноль или один)\n if(sName == L\"annotation\")\n {\n \/\/ Содержит форматированный текст - НЕ РЕАЛИЗОВАНО\n if(m_internal->m_pAnnotation)\n return false;\n m_internal->m_pAnnotation = new std::wstring[1];\n *m_internal->m_pAnnotation = L\"\";\n int nDepth = m_internal->m_oLightReader.GetDepth();\n while(m_internal->m_oLightReader.ReadNextSiblingNode(nDepth))\n {\n *m_internal->m_pAnnotation += m_internal->content();\n }\n }\n \/\/ Читаем keywords (ноль или один)\n else if(sName == L\"keywords\")\n {\n if(m_internal->m_pKeywords)\n return false;\n m_internal->m_pKeywords = new std::wstring[1];\n sRes = m_internal->content();\n if(sRes == L\"\")\n return false;\n *m_internal->m_pKeywords = sRes;\n }\n \/\/ Читаем date (ноль или один)\n else if(sName == L\"date\")\n {\n if(m_internal->m_pDate)\n return false;\n m_internal->m_pDate = new std::pair<std::wstring, std::wstring>[1];\n std::wstring sDate = L\"\";\n if(m_internal->m_oLightReader.MoveToNextAttribute())\n {\n sDate = m_internal->m_oLightReader.GetText();\n m_internal->m_oLightReader.MoveToElement();\n }\n sRes = m_internal->content();\n if(sRes == L\"\")\n return false;\n *m_internal->m_pDate = make_pair(sDate, sRes);\n }\n \/\/ Читаем coverpage (ноль или один)\n else if(sName == L\"coverpage\")\n {\n if(m_internal->m_pCoverpage)\n return false;\n m_internal->m_pCoverpage = new std::wstring[1];\n if(!m_internal->m_oLightReader.ReadNextSiblingNode(m_internal->m_oLightReader.GetDepth()))\n return false;\n if(!m_internal->m_oLightReader.MoveToNextAttribute())\n return false;\n sRes = m_internal->m_oLightReader.GetText();\n if(sRes == L\"\")\n return false;\n m_internal->m_oLightReader.MoveToElement();\n *m_internal->m_pCoverpage = sRes;\n }\n }\n\n \/\/ Читаем lang\n if(m_internal->m_oLightReader.GetName() != L\"lang\")\n return false;\n std::wstring sLang;\n sLang = m_internal->content();\n if(sLang == L\"\")\n return false;\n m_internal->m_sLang = sLang;\n\n \/\/ Читаем все до document-info\n while(!m_internal->isSection(L\"document-info\"))\n {\n if(m_internal->m_oLightReader.GetDepth() == 0)\n return false;\n std::wstring sRes;\n std::wstring sName = m_internal->m_oLightReader.GetName();\n\n \/\/ Читаем src-lang (ноль или один)\n if(sName == L\"src-lang\")\n {\n if(m_internal->m_pSrcLang)\n return false;\n m_internal->m_pSrcLang = new std::wstring[1];\n sRes = m_internal->content();\n if(sRes == L\"\")\n return false;\n *m_internal->m_pSrcLang = sRes;\n }\n \/\/ Читаем translator (любое)\n else if(sName == L\"translator\")\n {\n if(!m_internal->readAuthor(m_internal->m_arTranslator))\n return false;\n }\n \/\/ Читаем sequence (любое)\n else if(sName == L\"sequence\")\n {\n if(!m_internal->m_oLightReader.MoveToNextAttribute())\n return false;\n std::wstring sSName = m_internal->m_oLightReader.GetText();\n if(!m_internal->m_oLightReader.MoveToNextAttribute())\n return false;\n std::wstring sSNumber = m_internal->m_oLightReader.GetText();\n m_internal->m_mSequence.insert(std::make_pair(sSName, sSNumber));\n }\n }\n\n \/\/ ПРОЧИТАН разде title-info\n\n \/\/ ПРОПУСКАЕМ body\n\n while(m_internal->m_oLightReader.ReadNextNode())\n {\n \/\/ Читает картинки\n if(m_internal->m_oLightReader.GetName() == L\"binary\")\n {\n std::wstring sId;\n std::wstring sContentType;\n\n \/\/ Читает id\n if(!m_internal->m_oLightReader.MoveToNextAttribute())\n return false;\n sId = m_internal->m_oLightReader.GetText();\n\n \/\/ Читает content-type\n if(!m_internal->m_oLightReader.MoveToNextAttribute())\n return false;\n sContentType = m_internal->m_oLightReader.GetText();\n\n m_internal->m_mImage.insert(std::make_pair(sId, sContentType));\n m_internal->m_oLightReader.MoveToElement();\n\n \/\/ Пишет картинку в файл\n NSFile::CFileBinary oImageWriter;\n if (!oImageWriter.CreateFileW(sDirectory + sId))\n return false;\n std::string sBase64 = m_internal->contentA(sId);\n int nSrcLen = (int)sBase64.length();\n int nDecodeLen = NSBase64::Base64DecodeGetRequiredLength(nSrcLen);\n BYTE* pImageData = new BYTE[nDecodeLen];\n if (TRUE == NSBase64::Base64Decode(sBase64.c_str(), nSrcLen, pImageData, &nDecodeLen))\n oImageWriter.WriteFile(pImageData, (DWORD)nDecodeLen);\n RELEASEARRAYOBJECTS(pImageData);\n oImageWriter.CloseFile();\n }\n }\n return TRUE;\n}\n<commit_msg>read src-title-info<commit_after>#include \"Fb2File.h\"\n#include \"..\/DesktopEditor\/xml\/include\/xmlutils.h\"\n#include \"..\/DesktopEditor\/common\/Base64.h\"\n#include \"..\/DesktopEditor\/common\/File.h\"\n\n#include <vector>\n#include <map>\n\n\/\/ Информация об авторе книги. Тэг author, translator\nstruct SAuthor\n{\n std::wstring first_name;\n std::wstring middle_name;\n std::wstring last_name;\n std::wstring nickname;\n std::vector<std::wstring> home_page;\n std::vector<std::wstring> email;\n};\n\n\/\/ Описание информации о произведении. Тэг title-info, src-title-info\nstruct STitleInfo\n{\n std::vector<std::wstring> m_arGenres; \/\/ Жанры\n std::vector<SAuthor> m_arAuthors; \/\/ Авторы\n std::vector<SAuthor> m_arTranslator; \/\/ Переводчики\n\n std::wstring m_sBookTitle; \/\/ Название\n std::wstring m_sLang; \/\/ Язык после перевода\n\n std::wstring* m_pAnnotation; \/\/ Аннотация\n std::wstring* m_pKeywords; \/\/ Ключевые слова\n std::pair<std::wstring, std::wstring>* m_pDate; \/\/ Дата\n std::wstring* m_pCoverpage; \/\/ Обложка\n std::wstring* m_pSrcLang; \/\/ Язык до перевода\n\n std::map<std::wstring, std::wstring> m_mSequence; \/\/ Серии книг\n\n STitleInfo()\n {\n m_pAnnotation = NULL;\n m_pKeywords = NULL;\n m_pDate = NULL;\n m_pCoverpage = NULL;\n m_pSrcLang = NULL;\n }\n\n ~STitleInfo()\n {\n m_arGenres.clear();\n m_arAuthors.clear();\n m_arTranslator.clear();\n\n m_mSequence.clear();\n\n RELEASEARRAYOBJECTS(m_pAnnotation);\n RELEASEARRAYOBJECTS(m_pKeywords);\n RELEASEARRAYOBJECTS(m_pDate);\n RELEASEARRAYOBJECTS(m_pCoverpage);\n RELEASEARRAYOBJECTS(m_pSrcLang);\n }\n};\n\nclass CFb2File_Private\n{\npublic:\n XmlUtils::CXmlLiteReader m_oLightReader; \/\/ SAX Reader\n std::wstring m_sFile; \/\/ Имя файла\n std::wstring m_sDstFolder; \/\/ Путь к результату\n\n STitleInfo m_oTitleInfo; \/\/ Данные о книге\n\n STitleInfo* m_pSrcTitleInfo; \/\/ Данные об исходнике книги\n \/*\n std::vector<std::wstring> m_arGenres; \/\/ Жанры\n std::vector<SAuthor> m_arAuthors; \/\/ Авторы\n std::vector<SAuthor> m_arTranslator; \/\/ Переводчики\n\n std::wstring m_sBookTitle; \/\/ Название\n std::wstring m_sLang; \/\/ Язык после перевода\n\n std::wstring* m_pAnnotation; \/\/ Аннотация\n std::wstring* m_pKeywords; \/\/ Ключевые слова\n std::pair<std::wstring, std::wstring>* m_pDate; \/\/ Дата\n std::wstring* m_pCoverpage; \/\/ Обложка\n std::wstring* m_pSrcLang; \/\/ Язык до перевода\n\n std::map<std::wstring, std::wstring> m_mSequence; \/\/ Серии книг\n *\/\n std::map<std::wstring, std::wstring> m_mXmlns; \/\/ Ссылки\n std::map<std::wstring, std::wstring> m_mImage; \/\/ Картинки\n\npublic:\n CFb2File_Private()\n {\n m_pSrcTitleInfo = NULL;\n }\n\n ~CFb2File_Private()\n {\n m_oLightReader.Clear();\n m_mXmlns.clear();\n m_mImage.clear();\n if(m_pSrcTitleInfo)\n delete m_pSrcTitleInfo;\n }\n\n \/\/ Читает и проверят соответствует ли текущий раздел ожиданиям\n bool isSection(const std::wstring& sName)\n {\n if(!m_oLightReader.ReadNextNode())\n return false;\n if(m_oLightReader.GetName() != sName)\n return false;\n return true;\n }\n\n \/\/ Читает поля автора\n bool readAuthor(std::vector<SAuthor>& arAuthor)\n {\n SAuthor oAuthor;\n int nDepth = m_oLightReader.GetDepth();\n while(m_oLightReader.ReadNextSiblingNode(nDepth))\n {\n std::wstring sName = m_oLightReader.GetName();\n std::wstring sRes;\n if(sName == L\"first-name\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.first_name = sRes;\n }\n else if(sName == L\"middle-name\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.middle_name = sRes;\n }\n else if(sName == L\"last-name\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.last_name = sRes;\n }\n else if(sName == L\"nickname\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.nickname = sRes;\n }\n else if(sName == L\"home-page\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.home_page.push_back(sRes);\n }\n else if(sName == L\"email\")\n {\n sRes = content();\n if(sRes == L\"\")\n return false;\n oAuthor.email.push_back(sRes);\n }\n else\n return false;\n }\n arAuthor.push_back(oAuthor);\n return true;\n }\n\n bool getTitleInfo(STitleInfo& oTitleInfo)\n {\n \/\/ Читаем genre (один или более)\n if(!isSection(L\"genre\"))\n return false;\n do\n {\n std::wstring sGenre;\n sGenre = content();\n if(sGenre == L\"\")\n return false;\n oTitleInfo.m_arGenres.push_back(sGenre);\n } while(isSection(L\"genre\"));\n\n \/\/ Читаем author (один или более)\n do\n {\n if(!readAuthor(oTitleInfo.m_arAuthors))\n return false;\n } while(isSection(L\"author\"));\n\n \/\/ Читаем book-title\n if(m_oLightReader.GetName() != L\"book-title\")\n return false;\n std::wstring sBookTitle;\n sBookTitle = content();\n if(sBookTitle == L\"\")\n return false;\n oTitleInfo.m_sBookTitle = sBookTitle;\n\n \/\/ Читаем все до lang\n while(!isSection(L\"lang\"))\n {\n if(m_oLightReader.GetDepth() == 0)\n return false;\n std::wstring sRes;\n std::wstring sName = m_oLightReader.GetName();\n\n \/\/ Читаем annotation (ноль или один)\n if(sName == L\"annotation\")\n {\n \/\/ Содержит форматированный текст - НЕ РЕАЛИЗОВАНО\n if(oTitleInfo.m_pAnnotation)\n return false;\n oTitleInfo.m_pAnnotation = new std::wstring[1];\n *oTitleInfo.m_pAnnotation = L\"\";\n int nDepth = m_oLightReader.GetDepth();\n while(m_oLightReader.ReadNextSiblingNode(nDepth))\n {\n *oTitleInfo.m_pAnnotation += content();\n }\n }\n \/\/ Читаем keywords (ноль или один)\n else if(sName == L\"keywords\")\n {\n if(oTitleInfo.m_pKeywords)\n return false;\n oTitleInfo.m_pKeywords = new std::wstring[1];\n sRes = content();\n if(sRes == L\"\")\n return false;\n *oTitleInfo.m_pKeywords = sRes;\n }\n \/\/ Читаем date (ноль или один)\n else if(sName == L\"date\")\n {\n if(oTitleInfo.m_pDate)\n return false;\n oTitleInfo.m_pDate = new std::pair<std::wstring, std::wstring>[1];\n std::wstring sDate = L\"\";\n if(m_oLightReader.MoveToNextAttribute())\n {\n sDate = m_oLightReader.GetText();\n m_oLightReader.MoveToElement();\n }\n sRes = content();\n if(sRes == L\"\")\n return false;\n *oTitleInfo.m_pDate = make_pair(sDate, sRes);\n }\n \/\/ Читаем coverpage (ноль или один)\n else if(sName == L\"coverpage\")\n {\n if(oTitleInfo.m_pCoverpage)\n return false;\n oTitleInfo.m_pCoverpage = new std::wstring[1];\n if(!m_oLightReader.ReadNextSiblingNode(m_oLightReader.GetDepth()))\n return false;\n if(!m_oLightReader.MoveToNextAttribute())\n return false;\n sRes = m_oLightReader.GetText();\n if(sRes == L\"\")\n return false;\n m_oLightReader.MoveToElement();\n *oTitleInfo.m_pCoverpage = sRes;\n }\n }\n\n \/\/ Читаем lang\n if(m_oLightReader.GetName() != L\"lang\")\n return false;\n std::wstring sLang;\n sLang = content();\n if(sLang == L\"\")\n return false;\n oTitleInfo.m_sLang = sLang;\n\n \/\/ Читаем все до document-info\n while(!isSection(L\"document-info\"))\n {\n if(m_oLightReader.GetDepth() == 0)\n return false;\n std::wstring sRes;\n std::wstring sName = m_oLightReader.GetName();\n\n \/\/ Читаем src-lang (ноль или один)\n if(sName == L\"src-lang\")\n {\n if(oTitleInfo.m_pSrcLang)\n return false;\n oTitleInfo.m_pSrcLang = new std::wstring[1];\n sRes = content();\n if(sRes == L\"\")\n return false;\n *oTitleInfo.m_pSrcLang = sRes;\n }\n \/\/ Читаем translator (любое)\n else if(sName == L\"translator\")\n {\n if(!readAuthor(oTitleInfo.m_arTranslator))\n return false;\n }\n \/\/ Читаем sequence (любое)\n else if(sName == L\"sequence\")\n {\n if(!m_oLightReader.MoveToNextAttribute())\n return false;\n std::wstring sSName = m_oLightReader.GetText();\n if(!m_oLightReader.MoveToNextAttribute())\n return false;\n std::wstring sSNumber = m_oLightReader.GetText();\n oTitleInfo.m_mSequence.insert(std::make_pair(sSName, sSNumber));\n }\n else if(sName == L\"src-title-info\")\n {\n break;\n }\n }\n return true;\n }\n\n \/\/ Возвращает содержание узла\n std::wstring content()\n {\n std::wstring sRes = L\"\";\n if(m_oLightReader.ReadNextSiblingNode2(m_oLightReader.GetDepth()))\n sRes = m_oLightReader.GetText();\n return sRes;\n }\n\n std::string contentA(std::wstring is)\n {\n std::string sRes = \"\";\n if(m_oLightReader.ReadNextSiblingNode2(m_oLightReader.GetDepth()))\n sRes = m_oLightReader.GetTextA();\n return sRes;\n }\n};\n\nCFb2File::CFb2File()\n{\n m_internal = new CFb2File_Private();\n}\n\nCFb2File::~CFb2File()\n{\n RELEASEOBJECT(m_internal);\n}\n\n\/\/ Проверяет, соответствует ли fb2 файл формату\nbool CFb2File::IsFb2File(const std::wstring& sFile)\n{\n if (!m_internal->m_oLightReader.FromFile(sFile))\n return false;\n\n \/\/ Читаем FictionBook\n if(!m_internal->isSection(L\"FictionBook\"))\n return false;\n while(m_internal->m_oLightReader.MoveToNextAttribute())\n m_internal->m_mXmlns.insert(std::make_pair(m_internal->m_oLightReader.GetName(), m_internal->m_oLightReader.GetText()));\n m_internal->m_sFile = sFile;\n return true;\n}\n\n\/\/ Выставление временной (рабочей) папки\nvoid CFb2File::SetImpDirectory(const std::wstring& sFolder)\n{\n m_internal->m_sDstFolder = sFolder;\n}\n\n\/\/ Проверяет, соответствует ли fb2 файл формату\n\/\/ sPath - путь к сохраненному файлу, sDirectory - путь к сохраненным картинкам\nint CFb2File::Convert (const std::wstring& sPath, const std::wstring& sDirectory)\n{\n \/\/ Читаем description\n if(!m_internal->isSection(L\"description\"))\n return false;\n\n \/\/ Читаем наполнение description\n \/\/ Читаем title-info\n if(!m_internal->isSection(L\"title-info\"))\n return false;\n\n \/\/ Читаем наполнение title-info\n if(!m_internal->getTitleInfo(m_internal->m_oTitleInfo))\n return false;\n\n if(m_internal->m_oLightReader.GetName() == L\"src-title-info\")\n {\n m_internal->m_pSrcTitleInfo = new STitleInfo();\n if(!m_internal->getTitleInfo(*m_internal->m_pSrcTitleInfo))\n return false;\n }\n\n \/\/ ПРОПУСКАЕМ body\n\n while(m_internal->m_oLightReader.ReadNextNode())\n {\n \/\/ Читает картинки\n if(m_internal->m_oLightReader.GetName() == L\"binary\")\n {\n std::wstring sId;\n std::wstring sContentType;\n\n \/\/ Читает id\n if(!m_internal->m_oLightReader.MoveToNextAttribute())\n return false;\n sId = m_internal->m_oLightReader.GetText();\n\n \/\/ Читает content-type\n if(!m_internal->m_oLightReader.MoveToNextAttribute())\n return false;\n sContentType = m_internal->m_oLightReader.GetText();\n\n m_internal->m_mImage.insert(std::make_pair(sId, sContentType));\n m_internal->m_oLightReader.MoveToElement();\n\n \/\/ Пишет картинку в файл\n NSFile::CFileBinary oImageWriter;\n if (!oImageWriter.CreateFileW(sDirectory + sId))\n return false;\n std::string sBase64 = m_internal->contentA(sId);\n int nSrcLen = (int)sBase64.length();\n int nDecodeLen = NSBase64::Base64DecodeGetRequiredLength(nSrcLen);\n BYTE* pImageData = new BYTE[nDecodeLen];\n if (TRUE == NSBase64::Base64Decode(sBase64.c_str(), nSrcLen, pImageData, &nDecodeLen))\n oImageWriter.WriteFile(pImageData, (DWORD)nDecodeLen);\n RELEASEARRAYOBJECTS(pImageData);\n oImageWriter.CloseFile();\n }\n }\n return TRUE;\n}\n<|endoftext|>"} {"text":"<commit_before>AliAnalysisTaskTrigChEff *AddTaskMTRchamberEfficiency(Bool_t useGhosts = kFALSE) \n{\n \/\/\n \/\/ Task for the determination of the MUON trigger chamber efficiency\n \/\/\n \/\/ stocco@subatech.in2p3.fr\n \/\/\n\n\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTask\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ Create the task\n AliAnalysisTaskTrigChEff* taskTrigChEff = new AliAnalysisTaskTrigChEff(\"TriggerChamberEfficiency\");\n taskTrigChEff->SetUseGhostTracks(useGhosts);\n \/\/ Add to the manager\n mgr->AddTask(taskTrigChEff);\n\n \/\/\n \/\/ Create containers for input\/output\n AliAnalysisDataContainer *cOutputTrigChEff = mgr->CreateContainer(\"triggerChamberEff\", TList::Class(), AliAnalysisManager::kOutputContainer, \"MUON.TriggerEfficiencyMap.root\");\n\n \/\/ Attach input\n mgr->ConnectInput(taskTrigChEff,0,mgr->GetCommonInputContainer());\n \/\/ Attach output\n mgr->ConnectOutput(taskTrigChEff,0,cOutputTrigChEff);\n \n return taskTrigChEff;\n}\n<commit_msg>changes by Diego<commit_after>AliAnalysisTaskTrigChEff *AddTaskMTRchamberEfficiency(Bool_t useGhosts = kFALSE) \n{\n \/\/\n \/\/ Task for the determination of the MUON trigger chamber efficiency\n \/\/\n \/\/ stocco@subatech.in2p3.fr\n \/\/\n\n\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskMTRchamberEfficiency\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AliAnalysisTaskTrigChEff\", \"This task requires an input event handler\");\n return NULL;\n }\n\n \/\/ Create the task\n AliAnalysisTaskTrigChEff* taskTrigChEff = new AliAnalysisTaskTrigChEff(\"TriggerChamberEfficiency\");\n taskTrigChEff->SetUseGhostTracks(useGhosts);\n \/\/ Add to the manager\n mgr->AddTask(taskTrigChEff);\n\n \/\/\n \/\/ Create containers for input\/output\n AliAnalysisDataContainer *cOutputTrigChEff = mgr->CreateContainer(\"triggerChamberEff\", TList::Class(), AliAnalysisManager::kOutputContainer, \"MUON.TriggerEfficiencyMap.root\");\n\n \/\/ Attach input\n mgr->ConnectInput(taskTrigChEff,0,mgr->GetCommonInputContainer());\n \/\/ Attach output\n mgr->ConnectOutput(taskTrigChEff,1,cOutputTrigChEff);\n \n return taskTrigChEff;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\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\/\/\/ \\file\n\/\/\/ Tests for the Mesh class.\n\n#include \"gtest\/gtest.h\"\n\n#include \"SurgSim\/DataStructures\/MeshVertex.h\"\n#include \"SurgSim\/DataStructures\/UnitTests\/MockObjects.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n\nusing SurgSim::Math::Vector3d;\n\n\/\/\/ Vertex\ntypedef SurgSim::DataStructures::MeshVertex<MockVertexData> MockVertex;\n\nTEST(MeshVertexTest, InitTest)\n{\n\tVector3d position(0.0, 0.0, 0.0);\n\tMockVertexData data(0, Vector3d(1.0, 0.0, 0.0));\n\tASSERT_NO_THROW({MockVertex vertex(position, data);});\n}\n\nTEST(MeshVertexTest, VertexTest)\n{\n\tVector3d position(1.0, 2.0, 3.0);\n\tMockVertexData data(2, Vector3d(1.0, 0.0, 0.0));\n\tMockVertex vertex(position, data);\n\n\tEXPECT_EQ(position, vertex.position);\n\tEXPECT_EQ(data, vertex.data);\n\n\t{\n\t\tconst MockVertexData& data = vertex.data;\n\t\tEXPECT_EQ(2, data.getId());\n\t\tEXPECT_EQ(Vector3d(1.0, 0.0, 0.0), data.getNormal());\n\t}\n}<commit_msg>Tests for MeshVertex with no data (void template parameter).<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\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\/\/\/ \\file\n\/\/\/ Tests for the Mesh class.\n\n#include \"gtest\/gtest.h\"\n\n#include \"SurgSim\/DataStructures\/MeshVertex.h\"\n#include \"SurgSim\/DataStructures\/UnitTests\/MockObjects.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n\nusing SurgSim::DataStructures::MeshVertex;\nusing SurgSim::Math::Vector3d;\n\n\/\/\/ Vertex with ID and normal data\ntypedef SurgSim::DataStructures::MeshVertex<MockVertexData> MockVertex;\n\/\/\/ Vertex with no data\ntypedef SurgSim::DataStructures::MeshVertex<void> MockVertexNoData;\n\nTEST(MeshVertexTest, InitTest)\n{\n\tVector3d position(0.0, 0.0, 0.0);\n\tMockVertexData data(0, Vector3d(1.0, 0.0, 0.0));\n\tASSERT_NO_THROW({MockVertex vertex(position, data);});\n\n\t\/\/\/ Check that we can also create a vertex with no data\n\tASSERT_NO_THROW({MockVertexNoData vertex(position);});\n}\n\nTEST(MeshVertexTest, VertexTest)\n{\n\tVector3d position(1.0, 2.0, 3.0);\n\tMockVertexData data(2, Vector3d(1.0, 0.0, 0.0));\n\tMockVertex vertex(position, data);\n\n\tEXPECT_EQ(position, vertex.position);\n\tEXPECT_EQ(data, vertex.data);\n\n\t{\n\t\tconst MockVertexData& data = vertex.data;\n\t\tEXPECT_EQ(2, data.getId());\n\t\tEXPECT_EQ(Vector3d(1.0, 0.0, 0.0), data.getNormal());\n\t}\n}\n\nTEST(MeshVertexTest, VertexNoDataTest)\n{\n\tVector3d position(1.0, 2.0, 3.0);\n\tMockVertexNoData vertex(position);\n\n\tEXPECT_EQ(position, vertex.position);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include <CommDbConnPref.h> \/\/ connection prefs (iap)\n\n#include \"push\/FSocket.h\"\n#include \"base\/SymbianLog.h\"\n#include \"base\/util\/stringUtils.h\"\n#include \"base\/util\/symbianUtils.h\"\n\nStringBuffer FSocket::lIP;\n\n\n\n\nFSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port) \n{\n return FSocket::NewL(peer, port);\n}\n\n\nFSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)\n{\n FSocket* self = FSocket::NewLC(peer, port);\n CleanupStack::Pop( self );\n return self;\n}\n\nFSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)\n{\n FSocket* self = new ( ELeave ) FSocket();\n CleanupStack::PushL( self );\n self->ConstructL(peer, port);\n return self;\n}\n\n\nvoid FSocket::ConstructL(const StringBuffer& peer, int32_t port) \n{\n LOG.debug(\"FSocket::ConstructL\");\n StringBuffer errorMsg;\n \n RBuf serverName;\n serverName.Assign(stringBufferToNewBuf(peer));\n \n \/\/ Create the socket session\n iSocketSession.Connect();\n\n \/\/ Open the Client Socket tcp\/ip\n TInt res = iSocket.Open(iSocketSession, KAfInet, KSockStream, KProtocolInetTcp);\n if (res != KErrNone) {\n iStatus = -1;\n errorMsg = \"Error opening socket\";\n goto error;\n }\n\n \/\/ --- Resolve the host address ---\n LOG.debug(\"resolve IP address...\");\n RHostResolver resolver;\n res = resolver.Open(iSocketSession, KAfInet, KProtocolInetTcp);\n if (res != KErrNone) {\n iStatus = -2;\n errorMsg = \"Host resolver open failed\";\n goto error;\n }\n \n TNameEntry hostAddress;\n resolver.GetByName(serverName, hostAddress, iStatus);\n User::WaitForRequest(iStatus);\n resolver.Close();\n if (iStatus != KErrNone) {\n errorMsg = \"DNS lookup failed\";\n goto error;\n }\n\n \/\/ Set the socket server address\/port\n TInetAddr address = hostAddress().iAddr;\n address.SetPort(port);\n \n \/\/ --- Connect to host ---\n LOG.debug(\"connect...\");\n iSocket.Connect(address, iStatus);\n User::WaitForRequest(iStatus);\n if (iStatus != KErrNone) {\n errorMsg = \"Failed to connect to Server\";\n goto error;\n }\n \n return;\n \n \nerror:\n LOG.error(errorMsg.c_str()); \/\/ msgBox?\n iSocketSession.Close();\n return;\n}\n\n\n\nFSocket::FSocket() \n{\n iStatus = 0;\n}\n\nFSocket::~FSocket() \n{\n close();\n}\n\n\n\nint32_t FSocket::writeBuffer(const int8_t* const buffer, int32_t len) \n{\n \/\/ This doesn't copy the buffer in memory.\n TPtr8 data((TUint8*)buffer, len);\n \n \/\/ Sends data to the remote host.\n iSocket.Write(data, iStatus);\n User::WaitForRequest(iStatus);\n \n if (iStatus == KErrNone) {\n return len;\n }\n else {\n LOG.error(\"FSocket: error writing on socket (status = %d)\", iStatus.Int());\n return -1;\n }\n}\n\n\nint32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen) \n{\n RBuf8 data;\n data.CreateL(maxLen);\n \n \/\/ Receives data from a remote host and completes when data is available.\n do {\n TSockXfrLength len;\n iSocket.RecvOneOrMore(data, 0, iStatus, len);\n User::WaitForRequest(iStatus);\n LOG.debug(\"received %d bytes...\", data.Length());\n } while (iStatus == KErrNone);\n \/\/\n \/\/ TODO: status error codes?\n \/\/\n \n if (iStatus == KErrNone) {\n const char* ret = buf8ToNewChar(data);\n buffer = (int8_t*)ret;\n return data.Length();\n }\n else {\n LOG.error(\"FSocket: error reading on socket (status = %d)\", iStatus.Int());\n buffer = NULL;\n return -1;\n }\n}\n\n\nvoid FSocket::close() \n{\n LOG.debug(\"FSocket::close\");\n \/\/iSocket.CancelAll();\n iSocket.Close();\n iSocketSession.Close();\n}\n\n\n\n\nconst StringBuffer& FSocket::address() const {\n return lAddress;\n}\n\nconst StringBuffer& FSocket::peerAddress() const {\n return pAddress;\n}\n\nconst StringBuffer& FSocket::localIP() {\n return lIP;\n}\n\n\n\nvoid FSocket::startConnection()\n{\n RConnection connection;\n RSocketServ socketServ;\n User::LeaveIfError(socketServ.Connect());\n \n \/\/ Use the default IAP without prompting the user\n TUint32 UidAP=0;\n TCommDbConnPref prefs;\n prefs.SetDialogPreference (ECommDbDialogPrefDoNotPrompt);\n prefs.SetDirection (ECommDbConnectionDirectionUnknown);\n prefs.SetIapId (UidAP);\n\n User::LeaveIfError (connection.Open (socketServ, KAfInet));\n User::LeaveIfError (connection.Start (prefs));\n\n \/\/ use this to search for a particular IAP to use\n \/\/ withouth prompting the user\n#if defined(PREDEFINED_IAP)\n CCommsDatabase* commDb = CCommsDatabase::NewL(EDatabaseTypeIAP);\n CleanupStack::PushL(commDb);\n CApSelect* select = CApSelect::NewLC(*commDb,KEApIspTypeAll,EApBearerTypeAll,KEApSortUidAscending);\n TBuf<256> accessPoint;\n TInt UidAP= 0;\n TBool ok = select->MoveToFirst();\n for (TInt32 i = 0; ok&&(i<select->Count()); i++)\n {\n if ( select->Name ()==_L(PREDEFINED_IAP))\n {\n UidAP = select->Uid ();\n TCommDbConnPref prefs;\n prefs.SetDialogPreference (ECommDbDialogPrefDoNotPrompt);\n prefs.SetDirection (ECommDbConnectionDirectionUnknown);\n prefs.SetIapId (UidAP);\n\n User::LeaveIfError (iConnection.Open (iSocketSession, KAfInet));\n User::LeaveIfError (iConnection.Start (prefs));\n\n }\n else\n {\n ok = select->MoveNext ();\n }\n }\n#else\n \/\/ use this if you want prompt user for IAP\n TCommDbConnPref pref;\n pref.SetDirection(ECommDbConnectionDirectionUnknown);\n \n connection.Open(socketServ, KAfInet);\n connection.Start(pref);\n#endif\n \n socketServ.Close();\n}\n\n\n\n\n\n\n<commit_msg>moved local variable declarations at the beginning of the method, for compiler errors<commit_after>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include <CommDbConnPref.h> \/\/ connection prefs (iap)\n\n#include \"push\/FSocket.h\"\n#include \"base\/SymbianLog.h\"\n#include \"base\/util\/stringUtils.h\"\n#include \"base\/util\/symbianUtils.h\"\n\nStringBuffer FSocket::lIP;\n\n\n\n\nFSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port) \n{\n return FSocket::NewL(peer, port);\n}\n\n\nFSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)\n{\n FSocket* self = FSocket::NewLC(peer, port);\n CleanupStack::Pop( self );\n return self;\n}\n\nFSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)\n{\n FSocket* self = new ( ELeave ) FSocket();\n CleanupStack::PushL( self );\n self->ConstructL(peer, port);\n return self;\n}\n\n\nvoid FSocket::ConstructL(const StringBuffer& peer, int32_t port) \n{\n LOG.debug(\"FSocket::ConstructL\");\n \n StringBuffer errorMsg;\n RHostResolver resolver; \n RBuf serverName;\n TNameEntry hostAddress;\n TInetAddr address;\n \n serverName.Assign(stringBufferToNewBuf(peer));\n \n \/\/ Create the socket session\n iSocketSession.Connect();\n\n \/\/ Open the Client Socket tcp\/ip\n TInt res = iSocket.Open(iSocketSession, KAfInet, KSockStream, KProtocolInetTcp);\n if (res != KErrNone) {\n iStatus = -1;\n errorMsg = \"Error opening socket\";\n goto error;\n }\n\n \/\/ --- Resolve the host address ---\n LOG.debug(\"resolve IP address...\");\n res = resolver.Open(iSocketSession, KAfInet, KProtocolInetTcp);\n if (res != KErrNone) {\n iStatus = -2;\n errorMsg = \"Host resolver open failed\";\n goto error;\n }\n \n resolver.GetByName(serverName, hostAddress, iStatus);\n User::WaitForRequest(iStatus);\n resolver.Close();\n if (iStatus != KErrNone) {\n errorMsg = \"DNS lookup failed\";\n goto error;\n }\n\n \/\/ Set the socket server address\/port\n address = hostAddress().iAddr;\n address.SetPort(port);\n \n \/\/ --- Connect to host ---\n LOG.debug(\"connect...\");\n iSocket.Connect(address, iStatus);\n User::WaitForRequest(iStatus);\n if (iStatus != KErrNone) {\n errorMsg = \"Failed to connect to Server\";\n goto error;\n }\n \n return;\n \n \nerror:\n LOG.error(errorMsg.c_str()); \/\/ msgBox?\n iSocketSession.Close();\n return;\n}\n\n\n\nFSocket::FSocket() \n{\n iStatus = 0;\n}\n\nFSocket::~FSocket() \n{\n close();\n}\n\n\n\nint32_t FSocket::writeBuffer(const int8_t* const buffer, int32_t len) \n{\n \/\/ This doesn't copy the buffer in memory.\n TPtr8 data((TUint8*)buffer, len);\n \n \/\/ Sends data to the remote host.\n iSocket.Write(data, iStatus);\n User::WaitForRequest(iStatus);\n \n if (iStatus == KErrNone) {\n return len;\n }\n else {\n LOG.error(\"FSocket: error writing on socket (status = %d)\", iStatus.Int());\n return -1;\n }\n}\n\n\nint32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen) \n{\n RBuf8 data;\n data.CreateL(maxLen);\n \n \/\/ Receives data from a remote host and completes when data is available.\n do {\n TSockXfrLength len;\n iSocket.RecvOneOrMore(data, 0, iStatus, len);\n User::WaitForRequest(iStatus);\n LOG.debug(\"received %d bytes...\", data.Length());\n } while (iStatus == KErrNone);\n \/\/\n \/\/ TODO: status error codes?\n \/\/\n \n if (iStatus == KErrNone) {\n const char* ret = buf8ToNewChar(data);\n buffer = (int8_t*)ret;\n return data.Length();\n }\n else {\n LOG.error(\"FSocket: error reading on socket (status = %d)\", iStatus.Int());\n buffer = NULL;\n return -1;\n }\n}\n\n\nvoid FSocket::close() \n{\n LOG.debug(\"FSocket::close\");\n \/\/iSocket.CancelAll();\n iSocket.Close();\n iSocketSession.Close();\n}\n\n\n\n\nconst StringBuffer& FSocket::address() const {\n return lAddress;\n}\n\nconst StringBuffer& FSocket::peerAddress() const {\n return pAddress;\n}\n\nconst StringBuffer& FSocket::localIP() {\n return lIP;\n}\n\n\n\nvoid FSocket::startConnection()\n{\n RConnection connection;\n RSocketServ socketServ;\n User::LeaveIfError(socketServ.Connect());\n \n \/\/ Use the default IAP without prompting the user\n TUint32 UidAP=0;\n TCommDbConnPref prefs;\n prefs.SetDialogPreference (ECommDbDialogPrefDoNotPrompt);\n prefs.SetDirection (ECommDbConnectionDirectionUnknown);\n prefs.SetIapId (UidAP);\n\n User::LeaveIfError (connection.Open (socketServ, KAfInet));\n User::LeaveIfError (connection.Start (prefs));\n\n \/\/ use this to search for a particular IAP to use\n \/\/ withouth prompting the user\n#if defined(PREDEFINED_IAP)\n CCommsDatabase* commDb = CCommsDatabase::NewL(EDatabaseTypeIAP);\n CleanupStack::PushL(commDb);\n CApSelect* select = CApSelect::NewLC(*commDb,KEApIspTypeAll,EApBearerTypeAll,KEApSortUidAscending);\n TBuf<256> accessPoint;\n TInt UidAP= 0;\n TBool ok = select->MoveToFirst();\n for (TInt32 i = 0; ok&&(i<select->Count()); i++)\n {\n if ( select->Name ()==_L(PREDEFINED_IAP))\n {\n UidAP = select->Uid ();\n TCommDbConnPref prefs;\n prefs.SetDialogPreference (ECommDbDialogPrefDoNotPrompt);\n prefs.SetDirection (ECommDbConnectionDirectionUnknown);\n prefs.SetIapId (UidAP);\n\n User::LeaveIfError (iConnection.Open (iSocketSession, KAfInet));\n User::LeaveIfError (iConnection.Start (prefs));\n\n }\n else\n {\n ok = select->MoveNext ();\n }\n }\n#else\n \/\/ use this if you want prompt user for IAP\n TCommDbConnPref pref;\n pref.SetDirection(ECommDbConnectionDirectionUnknown);\n \n connection.Open(socketServ, KAfInet);\n connection.Start(pref);\n#endif\n \n socketServ.Close();\n}\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module:\n Language: C++\n Date:\n Version:\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n\/\/ This file has been generated by BuildHeaderTest.tcl\n\/\/ Test to include each header file for Insight\n\n#include \"itkAntiAliasBinaryImageFilter.txx\"\n#include \"itkBalloonForce3DFilter.txx\"\n#include \"itkBalloonForceFilter.txx\"\n#include \"itkBinaryMask3DMeshSource.txx\"\n#include \"itkBinaryMinMaxCurvatureFlowFunction.txx\"\n#include \"itkBinaryMinMaxCurvatureFlowImageFilter.txx\"\n#include \"itkClassifierBase.txx\"\n#include \"itkConnectedRegionsMeshFilter.txx\"\n#include \"itkCurvatureFlowFunction.txx\"\n#include \"itkCurvatureFlowImageFilter.txx\"\n#include \"itkDeformableMesh3DFilter.txx\"\n#include \"itkDeformableMeshFilter.txx\"\n#include \"itkDemonsRegistrationFilter.txx\"\n#include \"itkDemonsRegistrationFunction.txx\"\n#include \"itkExtensionVelocitiesImageFilter.txx\"\n#include \"itkFEMRegistrationFilter.txx\"\n#include \"itkFastMarchingExtensionImageFilter.txx\"\n#include \"itkFastMarchingImageFilter.txx\"\n\/\/#include \"itkFEMRegistrationFilter.txx\"\n#include \"itkGeodesicActiveContourImageFilter.txx\"\n#include \"itkGibbsPriorFilter.txx\"\n#include \"itkGradientVectorFlowImageFilter.txx\"\n#include \"itkHistogramMatchingImageFilter.txx\"\n#include \"itkHybridFilter.txx\"\n#include \"itkImageClassifierBase.txx\"\n#include \"itkImageGaussianModelEstimator.txx\"\n#include \"itkImageKmeansModelEstimator.txx\"\n#include \"itkImageModelEstimatorBase.txx\"\n#include \"itkImageMomentsCalculator.txx\"\n#include \"itkImageRegistrationMethod.txx\"\n#include \"itkImageToImageMetric.txx\"\n#include \"itkKLMRegionGrowImageFilter.txx\"\n#include \"itkKalmanLinearEstimator.h\"\n#include \"itkLaplacianSegmentationLevelSetFunction.txx\"\n#include \"itkLaplacianSegmentationLevelSetImageFilter.txx\"\n#include \"itkLevelSetImageFilter.txx\"\n#include \"itkLevelSetNeighborhoodExtractor.txx\"\n#include \"itkLevelSetVelocityNeighborhoodExtractor.txx\"\n#include \"itkMRASlabIdentifier.txx\"\n#include \"itkMRFImageFilter.txx\"\n#include \"itkMRIBiasFieldCorrectionFilter.txx\"\n#include \"itkMeanSquaresImageToImageMetric.txx\"\n#include \"itkMeanSquaresPointSetToImageMetric.txx\"\n#include \"itkMinMaxCurvatureFlowFunction.txx\"\n#include \"itkMinMaxCurvatureFlowImageFilter.txx\"\n#include \"itkMultiResolutionImageRegistrationMethod.txx\"\n#include \"itkMultiResolutionPDEDeformableRegistration.txx\"\n#include \"itkMultiResolutionPyramidImageFilter.txx\"\n#include \"itkMutualInformationImageToImageMetric.txx\"\n#include \"itkNormalizedCorrelationImageToImageMetric.txx\"\n#include \"itkNormalizedCorrelationPointSetToImageMetric.txx\"\n#include \"itkOtsuThresholdImageCalculator.txx\"\n#include \"itkPDEDeformableRegistrationFilter.txx\"\n#include \"itkPDEDeformableRegistrationFunction.h\"\n#include \"itkPatternIntensityImageToImageMetric.txx\"\n#include \"itkPatternIntensityPointSetToImageMetric.txx\"\n#include \"itkRGBGibbsPriorFilter.txx\"\n#include \"itkRecursiveMultiResolutionPyramidImageFilter.txx\"\n#include \"itkRegionGrowImageFilter.txx\"\n#include \"itkRegistrationMethod.txx\"\n#include \"itkReinitializeLevelSetImageFilter.txx\"\n#include \"itkSegmentationLevelSetImageFilter.txx\"\n#include \"itkShapeDetectionLevelSetFilter.txx\"\n#include \"itkSimpleFuzzyConnectednessImageFilterBase.txx\"\n#include \"itkSimpleFuzzyConnectednessRGBImageFilter.txx\"\n#include \"itkSimpleFuzzyConnectednessScalarImageFilter.txx\"\n#include \"itkSphereMeshSource.txx\"\n#include \"itkSphereSource.txx\"\n#include \"itkThresholdSegmentationLevelSetFunction.txx\"\n#include \"itkThresholdSegmentationLevelSetImageFilter.txx\"\n#include \"itkVectorFuzzyConnectednessImageFilter.txx\"\n#include \"itkVoronoiDiagram2D.txx\"\n#include \"itkVoronoiDiagram2DGenerator.txx\"\n#include \"itkVoronoiSegmentationImageFilter.txx\"\n#include \"itkVoronoiSegmentationImageFilterBase.txx\"\n#include \"itkVoronoiSegmentationRGBImageFilter.txx\"\n#include \"itkWatershedBoundary.txx\"\n#include \"itkWatershedBoundaryResolver.txx\"\n#include \"itkWatershedEquivalenceRelabeler.txx\"\n#include \"itkWatershedEquivalencyTable.txx\"\n#include \"itkWatershedImageFilter.txx\"\n#include \"itkWatershedMiniPipelineProgressCommand.h\"\n#include \"itkWatershedOneWayEquivalencyTable.txx\"\n#include \"itkWatershedRelabeler.txx\"\n#include \"itkWatershedSegmentTable.txx\"\n#include \"itkWatershedSegmentTree.txx\"\n#include \"itkWatershedSegmentTreeGenerator.txx\"\n#include \"itkWatershedSegmenter.txx\"\n\nint main ( int argc, char* argv )\n{\n \n return 0;\n}\n\n<commit_msg>ENH: Updated to latest headers<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module:\n Language: C++\n Date:\n Version:\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n\/\/ This file has been generated by BuildHeaderTest.tcl\n\/\/ Test to include each header file for Insight\n\n#include \"itkAntiAliasBinaryImageFilter.txx\"\n#include \"itkBalloonForce3DFilter.txx\"\n#include \"itkBalloonForceFilter.txx\"\n#include \"itkBinaryMask3DMeshSource.txx\"\n#include \"itkBinaryMinMaxCurvatureFlowFunction.txx\"\n#include \"itkBinaryMinMaxCurvatureFlowImageFilter.txx\"\n#include \"itkClassifierBase.txx\"\n#include \"itkConnectedRegionsMeshFilter.txx\"\n#include \"itkCurvatureFlowFunction.txx\"\n#include \"itkCurvatureFlowImageFilter.txx\"\n#include \"itkDeformableMesh3DFilter.txx\"\n#include \"itkDeformableMeshFilter.txx\"\n#include \"itkDemonsRegistrationFilter.txx\"\n#include \"itkDemonsRegistrationFunction.txx\"\n#include \"itkExtensionVelocitiesImageFilter.txx\"\n#include \"itkFEMRegistrationFilter.txx\"\n#include \"itkFastMarchingExtensionImageFilter.txx\"\n#include \"itkFastMarchingImageFilter.txx\"\n#include \"itkGeodesicActiveContourImageFilter.txx\"\n#include \"itkGibbsPriorFilter.txx\"\n#include \"itkGradientVectorFlowImageFilter.txx\"\n#include \"itkHistogramMatchingImageFilter.txx\"\n#include \"itkHybridFilter.txx\"\n#include \"itkImageClassifierBase.txx\"\n#include \"itkImageGaussianModelEstimator.txx\"\n#include \"itkImageKmeansModelEstimator.txx\"\n#include \"itkImageModelEstimatorBase.txx\"\n#include \"itkImageMomentsCalculator.txx\"\n#include \"itkImageRegistrationMethod.txx\"\n#include \"itkImageToImageMetric.txx\"\n#include \"itkKLMRegionGrowImageFilter.txx\"\n#include \"itkKalmanLinearEstimator.h\"\n#include \"itkLaplacianSegmentationLevelSetFunction.txx\"\n#include \"itkLaplacianSegmentationLevelSetImageFilter.txx\"\n#include \"itkLevelSetImageFilter.txx\"\n#include \"itkLevelSetNeighborhoodExtractor.txx\"\n#include \"itkLevelSetVelocityNeighborhoodExtractor.txx\"\n#include \"itkMRASlabIdentifier.txx\"\n#include \"itkMRFImageFilter.txx\"\n#include \"itkMRIBiasFieldCorrectionFilter.txx\"\n#include \"itkMeanSquaresImageToImageMetric.txx\"\n#include \"itkMeanSquaresPointSetToImageMetric.txx\"\n#include \"itkMinMaxCurvatureFlowFunction.txx\"\n#include \"itkMinMaxCurvatureFlowImageFilter.txx\"\n#include \"itkMultiResolutionImageRegistrationMethod.txx\"\n#include \"itkMultiResolutionPDEDeformableRegistration.txx\"\n#include \"itkMultiResolutionPyramidImageFilter.txx\"\n#include \"itkMutualInformationImageToImageMetric.txx\"\n#include \"itkNormalizedCorrelationImageToImageMetric.txx\"\n#include \"itkNormalizedCorrelationPointSetToImageMetric.txx\"\n#include \"itkOtsuThresholdImageCalculator.txx\"\n#include \"itkPDEDeformableRegistrationFilter.txx\"\n#include \"itkPDEDeformableRegistrationFunction.h\"\n#include \"itkPatternIntensityImageToImageMetric.txx\"\n#include \"itkPatternIntensityPointSetToImageMetric.txx\"\n#include \"itkRGBGibbsPriorFilter.txx\"\n#include \"itkRecursiveMultiResolutionPyramidImageFilter.txx\"\n#include \"itkRegionGrowImageFilter.txx\"\n#include \"itkRegistrationMethod.txx\"\n#include \"itkReinitializeLevelSetImageFilter.txx\"\n#include \"itkSegmentationLevelSetImageFilter.txx\"\n#include \"itkShapeDetectionLevelSetFilter.txx\"\n#include \"itkSimpleFuzzyConnectednessImageFilterBase.txx\"\n#include \"itkSimpleFuzzyConnectednessRGBImageFilter.txx\"\n#include \"itkSimpleFuzzyConnectednessScalarImageFilter.txx\"\n#include \"itkSphereMeshSource.txx\"\n#include \"itkSphereSource.txx\"\n#include \"itkThresholdSegmentationLevelSetFunction.txx\"\n#include \"itkThresholdSegmentationLevelSetImageFilter.txx\"\n#include \"itkVectorFuzzyConnectednessImageFilter.txx\"\n#include \"itkVoronoiDiagram2D.txx\"\n#include \"itkVoronoiDiagram2DGenerator.txx\"\n#include \"itkVoronoiSegmentationImageFilter.txx\"\n#include \"itkVoronoiSegmentationImageFilterBase.txx\"\n#include \"itkVoronoiSegmentationRGBImageFilter.txx\"\n#include \"itkWatershedBoundary.txx\"\n#include \"itkWatershedBoundaryResolver.txx\"\n#include \"itkWatershedEquivalenceRelabeler.txx\"\n#include \"itkWatershedEquivalencyTable.txx\"\n#include \"itkWatershedImageFilter.txx\"\n#include \"itkWatershedMiniPipelineProgressCommand.h\"\n#include \"itkWatershedOneWayEquivalencyTable.txx\"\n#include \"itkWatershedRelabeler.txx\"\n#include \"itkWatershedSegmentTable.txx\"\n#include \"itkWatershedSegmentTree.txx\"\n#include \"itkWatershedSegmentTreeGenerator.txx\"\n#include \"itkWatershedSegmenter.txx\"\n\nint main ( int argc, char* argv )\n{\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkGeometricalQuadEdgeTest1.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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\n#include \"itkGeometricalQuadEdge.h\"\n#include <iostream>\n\nclass itkGeometricalQuadEdgeTest1Helper\n{\npublic:\n typedef unsigned int PointIdentifier;\n typedef unsigned int FaceIdentifier;\n typedef float PointData;\n typedef std::string FaceData;\n\n typedef itk::GeometricalQuadEdge<\n PointIdentifier, FaceIdentifier, \n PointData, FaceData, true > PrimalQuadEdgeType;\n\n\n typedef itk::GeometricalQuadEdge<\n PointIdentifier, FaceIdentifier, \n PointData, FaceData, false > DualQuadEdgeType;\n\n \n static PrimalQuadEdgeType * MakeQuadEdges()\n {\n PrimalQuadEdgeType * e1 = new PrimalQuadEdgeType();\n DualQuadEdgeType * e2 = new DualQuadEdgeType();\n PrimalQuadEdgeType * e3 = new PrimalQuadEdgeType();\n DualQuadEdgeType * e4 = new DualQuadEdgeType();\n \n e1->SetRot( e2 );\n e2->SetRot( e3 );\n e3->SetRot( e4 );\n e4->SetRot( e1 );\n \n e1->SetOnext( e1 );\n e2->SetOnext( e4 );\n e3->SetOnext( e3 );\n e4->SetOnext( e4 );\n\n return e1;\n }\n};\n\n\nint itkGeometricalQuadEdgeTest1( int , char* [] )\n{\n\n typedef itkGeometricalQuadEdgeTest1Helper HelperType;\n\n typedef HelperType::PrimalQuadEdgeType PrimalQuadEdgeType;\n typedef HelperType::DualQuadEdgeType DualQuadEdgeType;\n\n\n { \/\/ Define a local scope for testing constructors\n\n DualQuadEdgeType dummyQuadEdge1; \/\/ test constructor\n PrimalQuadEdgeType dummyQuadEdge2; \/\/ test constructor\n\n dummyQuadEdge1.SetRot( &dummyQuadEdge2 ); \/\/ Test SetRot()\n }\n\n PrimalQuadEdgeType * e1 = HelperType::MakeQuadEdges();\n \n return EXIT_SUCCESS;\n}\n\n<commit_msg>ENH: Replacing typedef for the DualType trying to solve link problem in the SGIs.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkGeometricalQuadEdgeTest1.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\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\n#include \"itkGeometricalQuadEdge.h\"\n#include <iostream>\n\nclass itkGeometricalQuadEdgeTest1Helper\n{\npublic:\n typedef unsigned int PointIdentifier;\n typedef unsigned int FaceIdentifier;\n typedef float PointData;\n typedef std::string FaceData;\n\n typedef itk::GeometricalQuadEdge<\n PointIdentifier, FaceIdentifier, \n PointData, FaceData, true > PrimalQuadEdgeType;\n\n\n typedef PrimalQuadEdgeType::DualType DualQuadEdgeType;\n\n \n static PrimalQuadEdgeType * MakeQuadEdges()\n {\n PrimalQuadEdgeType * e1 = new PrimalQuadEdgeType();\n DualQuadEdgeType * e2 = new DualQuadEdgeType();\n PrimalQuadEdgeType * e3 = new PrimalQuadEdgeType();\n DualQuadEdgeType * e4 = new DualQuadEdgeType();\n \n e1->SetRot( e2 );\n e2->SetRot( e3 );\n e3->SetRot( e4 );\n e4->SetRot( e1 );\n \n e1->SetOnext( e1 );\n e2->SetOnext( e4 );\n e3->SetOnext( e3 );\n e4->SetOnext( e4 );\n\n return e1;\n }\n};\n\n\nint itkGeometricalQuadEdgeTest1( int , char* [] )\n{\n\n typedef itkGeometricalQuadEdgeTest1Helper HelperType;\n\n typedef HelperType::PrimalQuadEdgeType PrimalQuadEdgeType;\n typedef HelperType::DualQuadEdgeType DualQuadEdgeType;\n\n\n { \/\/ Define a local scope for testing constructors\n\n DualQuadEdgeType dummyQuadEdge1; \/\/ test constructor\n PrimalQuadEdgeType dummyQuadEdge2; \/\/ test constructor\n\n dummyQuadEdge1.SetRot( &dummyQuadEdge2 ); \/\/ Test SetRot()\n }\n\n PrimalQuadEdgeType * e1 = HelperType::MakeQuadEdges();\n \n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n return 0; \/\/ 不返回的话也不会报错,那么加上这个返回值的原因是?\n}\n<commit_msg>main函数返回值,对程序运行的影响<commit_after>#include <iostream>\n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n return 0; \/\/ 不返回的话也不会报错\n\/\/ return -1; \/\/ 甚至返回-1运行的时候也没有任何区别,那么加上这个返回值的原因是?\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2007 Apple Inc. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its 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 APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"WebKitInitializer.h\"\n\n\/\/ Needed to get SetDllDirectory\n#define _WIN32_WINNT 0x0502\n\n#include <shlwapi.h>\n#include <tchar.h>\n#include <windows.h>\n\nstatic TCHAR* getStringValue(HKEY key, LPCTSTR valueName)\n{\n DWORD type = 0;\n DWORD bufferSize = 0;\n if (RegQueryValueEx(key, valueName, 0, &type, 0, &bufferSize) != ERROR_SUCCESS || type != REG_SZ)\n return 0;\n\n TCHAR* buffer = new TCHAR[bufferSize \/ sizeof(TCHAR)];\n if (RegQueryValueEx(key, 0, 0, &type, reinterpret_cast<LPBYTE>(buffer), &bufferSize) != ERROR_SUCCESS) {\n delete [] buffer;\n return 0;\n }\n\n return buffer;\n}\n\nstatic LPOLESTR getWebViewCLSID()\n{\n \/\/ FIXME <rdar:\/\/5505062>: Once WebKit switches to truly version-independent\n \/\/ ProgIDs, this should just become \"WebKit.WebView\".\n LPCTSTR webViewProgID = TEXT(\"WebKit.WebView.3\");\n\n CLSID clsid = CLSID_NULL;\n HRESULT hr = CLSIDFromProgID(webViewProgID, &clsid);\n if (FAILED(hr)) {\n _ftprintf(stderr, TEXT(\"Failed to get CLSID for %s\\n\"), webViewProgID);\n return 0;\n }\n\n LPOLESTR clsidString = 0;\n if (FAILED(StringFromCLSID(clsid, &clsidString))) {\n _ftprintf(stderr, TEXT(\"Failed to get string representation of CLSID for WebView\\n\"));\n return 0;\n }\n\n return clsidString;\n}\n\nstatic TCHAR* getInstalledWebKitDirectory()\n{\n LPCTSTR keyPrefix = TEXT(\"SOFTWARE\\\\Classes\\\\CLSID\\\\\");\n LPCTSTR keySuffix = TEXT(\"\\\\InprocServer32\");\n\n LPOLESTR clsid = getWebViewCLSID();\n if (!clsid)\n return 0;\n\n size_t keyBufferLength = _tcslen(keyPrefix) + _tcslen(clsid) + _tcslen(keySuffix) + 1;\n TCHAR* keyString = new TCHAR[keyBufferLength];\n\n int ret = _sntprintf_s(keyString, keyBufferLength, keyBufferLength - 1, TEXT(\"%s%s%s\"), keyPrefix, clsid, keySuffix);\n CoTaskMemFree(clsid);\n if (ret == -1) {\n _ftprintf(stderr, TEXT(\"Failed to construct InprocServer32 key\\n\"));\n return 0;\n }\n\n HKEY serverKey = 0;\n LONG error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyString, 0, KEY_READ, &serverKey);\n delete [] keyString;\n if (error != ERROR_SUCCESS) {\n _ftprintf(stderr, TEXT(\"Failed to open registry key %s\\n\"), keyString);\n return 0;\n }\n\n TCHAR* webKitPath = getStringValue(serverKey, 0);\n RegCloseKey(serverKey);\n if (!webKitPath) {\n _ftprintf(stderr, TEXT(\"Couldn't retrieve value for registry key %s\\n\"), keyString);\n return 0;\n }\n\n TCHAR* startOfFileName = PathFindFileName(webKitPath);\n if (startOfFileName == webKitPath) {\n _ftprintf(stderr, TEXT(\"Couldn't find filename from path %s\\n\"), webKitPath);\n delete [] webKitPath;\n return 0;\n }\n\n *startOfFileName = '\\0';\n return webKitPath;\n}\n\nbool initializeWebKit()\n{\n static bool haveInitialized;\n static bool success;\n if (haveInitialized)\n return success;\n haveInitialized = true;\n\n#ifdef NDEBUG\n LPCTSTR webKitDLL = TEXT(\"WebKit.dll\");\n#else\n LPCTSTR webKitDLL = TEXT(\"WebKit_debug.dll\");\n#endif\n\n HMODULE webKitModule = LoadLibrary(webKitDLL);\n if (!webKitModule) {\n _ftprintf(stderr, TEXT(\"LoadLibrary(%s) failed\\n\"), webKitDLL);\n return false;\n }\n\n FARPROC dllRegisterServer = GetProcAddress(webKitModule, \"DllRegisterServer\");\n if (!dllRegisterServer) {\n _ftprintf(stderr, TEXT(\"GetProcAddress(webKitModule, \\\"DllRegisterServer\\\") failed\\n\"));\n return false;\n }\n\n dllRegisterServer();\n\n TCHAR* directory = getInstalledWebKitDirectory();\n if (!directory) {\n _ftprintf(stderr, TEXT(\"Couldn't determine installed WebKit directory\\n\"));\n return false;\n }\n\n SetDllDirectory(directory);\n delete [] directory;\n\n success = true;\n return success;\n}\n<commit_msg>Touch it again so it rebuilds<commit_after>\/*\n * Copyright (C) 2007 Apple Inc. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its 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 APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"WebKitInitializer.h\"\n\n\/\/ Needed to get SetDllDirectory\n#define _WIN32_WINNT 0x0502\n\n#include <shlwapi.h>\n#include <tchar.h>\n#include <windows.h>\n\nstatic TCHAR* getStringValue(HKEY key, LPCTSTR valueName)\n{\n DWORD type = 0;\n DWORD bufferSize = 0;\n if (RegQueryValueEx(key, valueName, 0, &type, 0, &bufferSize) != ERROR_SUCCESS || type != REG_SZ)\n return 0;\n\n TCHAR* buffer = new TCHAR[bufferSize \/ sizeof(TCHAR)];\n if (RegQueryValueEx(key, 0, 0, &type, reinterpret_cast<LPBYTE>(buffer), &bufferSize) != ERROR_SUCCESS) {\n delete [] buffer;\n return 0;\n }\n\n return buffer;\n}\n\nstatic LPOLESTR getWebViewCLSID()\n{\n \/\/ FIXME <rdar:\/\/5505062>: Once WebKit switches to truly version-independent\n \/\/ ProgIDs, this should just become \"WebKit.WebView\".\n LPCTSTR webViewProgID = TEXT(\"WebKit.WebView.3\");\n\n CLSID clsid = CLSID_NULL;\n HRESULT hr = CLSIDFromProgID(webViewProgID, &clsid);\n if (FAILED(hr)) {\n _ftprintf(stderr, TEXT(\"Failed to get CLSID for %s\\n\"), webViewProgID);\n return 0;\n }\n\n LPOLESTR clsidString = 0;\n if (FAILED(StringFromCLSID(clsid, &clsidString))) {\n _ftprintf(stderr, TEXT(\"Failed to get string representation of CLSID for WebView\\n\"));\n return 0;\n }\n\n return clsidString;\n}\n\nstatic TCHAR* getInstalledWebKitDirectory()\n{\n LPCTSTR keyPrefix = TEXT(\"SOFTWARE\\\\Classes\\\\CLSID\\\\\");\n LPCTSTR keySuffix = TEXT(\"\\\\InprocServer32\");\n\n LPOLESTR clsid = getWebViewCLSID();\n if (!clsid)\n return 0;\n\n size_t keyBufferLength = _tcslen(keyPrefix) + _tcslen(clsid) + _tcslen(keySuffix) + 1;\n TCHAR* keyString = new TCHAR[keyBufferLength];\n\n int ret = _sntprintf_s(keyString, keyBufferLength, keyBufferLength - 1, TEXT(\"%s%s%s\"), keyPrefix, clsid, keySuffix);\n CoTaskMemFree(clsid);\n if (ret == -1) {\n _ftprintf(stderr, TEXT(\"Failed to construct InprocServer32 key\\n\"));\n return 0;\n }\n\n HKEY serverKey = 0;\n LONG error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyString, 0, KEY_READ, &serverKey);\n delete [] keyString;\n if (error != ERROR_SUCCESS) {\n _ftprintf(stderr, TEXT(\"Failed to open registry key %s\\n\"), keyString);\n return 0;\n }\n\n TCHAR* webKitPath = getStringValue(serverKey, 0);\n RegCloseKey(serverKey);\n if (!webKitPath) {\n _ftprintf(stderr, TEXT(\"Couldn't retrieve value for registry key %s\\n\"), keyString);\n return 0;\n }\n\n TCHAR* startOfFileName = PathFindFileName(webKitPath);\n if (startOfFileName == webKitPath) {\n _ftprintf(stderr, TEXT(\"Couldn't find filename from path %s\\n\"), webKitPath);\n delete [] webKitPath;\n return 0;\n }\n\n *startOfFileName = '\\0';\n return webKitPath;\n}\n\nbool initializeWebKit()\n{\n static bool haveInitialized;\n static bool success;\n if (haveInitialized)\n return success;\n\n haveInitialized = true;\n\n#ifdef NDEBUG\n LPCTSTR webKitDLL = TEXT(\"WebKit.dll\");\n#else\n LPCTSTR webKitDLL = TEXT(\"WebKit_debug.dll\");\n#endif\n\n HMODULE webKitModule = LoadLibrary(webKitDLL);\n if (!webKitModule) {\n _ftprintf(stderr, TEXT(\"LoadLibrary(%s) failed\\n\"), webKitDLL);\n return false;\n }\n\n FARPROC dllRegisterServer = GetProcAddress(webKitModule, \"DllRegisterServer\");\n if (!dllRegisterServer) {\n _ftprintf(stderr, TEXT(\"GetProcAddress(webKitModule, \\\"DllRegisterServer\\\") failed\\n\"));\n return false;\n }\n\n dllRegisterServer();\n\n TCHAR* directory = getInstalledWebKitDirectory();\n if (!directory) {\n _ftprintf(stderr, TEXT(\"Couldn't determine installed WebKit directory\\n\"));\n return false;\n }\n\n SetDllDirectory(directory);\n delete [] directory;\n\n success = true;\n return success;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved\n *\/\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Characters\/String.h\"\n#include \"Stroika\/Foundation\/Characters\/ToString.h\"\n#include \"Stroika\/Foundation\/Containers\/Collection.h\"\n#include \"Stroika\/Foundation\/Containers\/SortedCollection.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n\/\/ Not generally included, but you can include these if you want to select a particular backend implementation\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Collection_Array.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Collection_LinkedList.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Collection_stdforward_list.h\"\n\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n\n#include \"Collection.h\"\n\nusing namespace std;\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\n\nusing Characters::CompareOptions;\n\nnamespace {\n void SimplestCollectionTest_ ()\n {\n \/*\n * A Collection is the simplest form of Stroika container. You can add things, and remove them, and iterate over them.\n * View the class declaration, with all the methods well documented, must with examples of usage.\n *\/\n Collection<int> c;\n c.Add (3);\n c += 13;\n for ([[maybe_unused]] int i : c) {\n Lambda_Arg_Unused_BWA (i); \/\/ warning C4189: 'i': local variable is initialized but not referenced\n Assert (i == 3 or i == 13);\n }\n Assert (c.size () == 2);\n }\n}\n\nnamespace {\n void UseParticularConcreteRepresentation_ ()\n {\n {\n Collection<int> c{3, 5, 19, 3040, 34, 1, 33, 33, 4, 19};\n\n \/\/ Unclear what the performance characteristics of this will be - with a linked list - O(1), but with array, O(N) worst case.\n c += 4;\n\n \/\/ 'c' will now operate identically (same API) - but use a differnt backend datastructure for storage,\n \/\/ always showing O(1) worst case addition time\n c = Concrete::Collection_stdforward_list<int>{c};\n c += 4;\n }\n {\n using Characters::String;\n Collection<String> fruits;\n fruits += L\"apple\";\n fruits += L\"bananas\";\n fruits += L\"cherries\";\n fruits += L\"APPLE\";\n \/\/ Print (to debugger\/tracelog) the fruits - but now they could come out in any order\n DbgTrace (L\"fruits=%s\", Characters::ToString (fruits).c_str ());\n Assert (fruits.size () == 4); \/\/ they are all there\n\n \/\/ Like changing the backend. But this still respects all the rules of a Collection (no order specified) -\n \/\/ except now it will happen to be ordered (using the default compare function)\n fruits = SortedCollection<String>{fruits};\n DbgTrace (L\"sorted fruits=%s\", Characters::ToString (fruits).c_str ());\n Assert (fruits.size () == 4); \/\/ only one apple or the other (case squished)\n \/\/ note they must now be in alphabetic order\n Assert (fruits.SequenceEquals (initializer_list<String>{L\"APPLE\", L\"apple\", L\"bananas\", L\"cherries\"}));\n\n \/\/ But, we can do the same thing with a compare function that sorts case insensitively\n fruits = SortedCollection<String>{String::LessComparer{CompareOptions::eCaseInsensitive}, fruits};\n DbgTrace (L\"sorted case insensitve fruits=%s\", Characters::ToString (fruits).c_str ());\n Assert (fruits.SequenceEquals (initializer_list<String>{L\"apple\", L\"APPLE\", L\"bananas\", L\"cherries\"}) or\n fruits.SequenceEquals (initializer_list<String>{L\"APPLE\", L\"apple\", L\"bananas\", L\"cherries\"}));\n }\n }\n}\n\nnamespace {\n void InterfaceWithSTLContainers_ ()\n {\n vector<int> aVector{1, 3, 5, 7, 9, 11};\n Collection<int> c{aVector};\n\n \/\/ CANNOT guarantee the ordering is the same, as Collection guarantees it keeps all the same elements,\n \/\/ but does not guarantee maintaining order.\n Assert (c.SetEquals (aVector));\n Assert (c.SequnceEquals (aVector) or not c.SequnceEquals (aVector));\n\n vector<int> v2 = c.As<vector<int>> ();\n \/\/ V will contain all the same elements as aVector, but maybe not in the same order.\n \/\/ it will be in the order the 'c' collection happened to produce\n }\n}\n\nnamespace {\n void PrintTheContentsOfAContainerToTheTraceLog_ ()\n {\n \/*\n * Use DbgTrace and Characters::ToString () to echo objects to a tracelog file (and\/or debugger output under windows)\n *\/\n Debug::TraceContextBumper ctx{L\"PrintTheContentsOfAContainerToTheTraceLog_\"};\n Collection<int> tmp{1, 3, 5, 7, 9};\n DbgTrace (L\"tmp=%s\", Characters::ToString (tmp).c_str ());\n }\n}\n\nnamespace {\n void StoreOtherSortsOfElements_ ()\n {\n Debug::TraceContextBumper ctx{L\"StoreOtherSortsOfElements_\"};\n using Characters::String;\n Collection<String> fruits;\n fruits += L\"apple\";\n fruits += L\"bananas\";\n fruits += L\"cherries\";\n DbgTrace (L\"fruits=%s\", Characters::ToString (fruits).c_str ());\n }\n}\n\nnamespace {\n void UseLinqLikeFunctionalAPIs_ ()\n {\n Debug::TraceContextBumper ctx{L\"PrintTheContentsOfAContainerToTheTraceLog_\"};\n \/*\n * See the Iterable<> template in Iterable.h - for a ton more of this functional style linq-like operations\n * you can do on any Stroika container.\n *\/\n {\n Collection<int> tmp{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n auto whereTestResult = tmp.Where ([] (int i) { return i % 2 == 1; });\n DbgTrace (L\"tmp=%s\", Characters::ToString (whereTestResult).c_str ());\n }\n {\n Collection<int> tmp{1, 2, 3, 4, 5, 1, 2, 3, 4, 5};\n auto d = tmp.Distinct ();\n DbgTrace (L\"d=%s\", Characters::ToString (d).c_str ());\n Assert (d.SetEquals (initializer_list<int>{1, 2, 3, 4, 5}));\n }\n {\n using Characters::String;\n Collection<String> fruits;\n fruits += L\"apple\";\n fruits += L\"APPLE\";\n fruits += L\"bananas\";\n fruits += L\"cherries\";\n DbgTrace (L\"fruits=%s\", Characters::ToString (fruits.Distinct (String::EqualsComparer{CompareOptions::eCaseInsensitive})).c_str ());\n Assert (fruits.Distinct (String::EqualsComparer{CompareOptions::eCaseInsensitive}).size () == 3); \/\/ only one apple or the other (case squished)\n }\n }\n}\n\nnamespace {\n void CollectionOfThingsWithNoOpEqualsAndNotDefaultConstructibleEtc_ ()\n {\n struct MyFunnyObject_ {\n MyFunnyObject_ () = delete; \/\/ no need to be default constructible\n MyFunnyObject_ (int \/*n*\/)\n {\n \/\/ need some constructor to test\n }\n MyFunnyObject_ (const MyFunnyObject_&) = default; \/\/ OK, but you do need to be copyable\n };\n Collection<MyFunnyObject_> myObjects;\n myObjects.Add (MyFunnyObject_{3});\n myObjects += MyFunnyObject_{4}; \/\/ use whatever add syntax you want\n\n \/\/ THIS WONT WORK, because no operator== defined\n \/\/ myObjects.Remove (MyFunnyObject_{3});\n \/\/ but this will remove the first object found\n Assert (myObjects.size () == 2);\n myObjects.Remove (MyFunnyObject_{3}, [] (const MyFunnyObject_&, const MyFunnyObject_&) { return true; });\n Assert (myObjects.size () == 1);\n }\n}\n\nnamespace {\n void IteratorsAndSafeUpdateIteration_ ()\n {\n using Characters::String;\n Collection<String> fruits;\n fruits += L\"apple\";\n fruits += L\"APPLE\";\n fruits += L\"bananas\";\n fruits += L\"cherries\";\n\n {\n Iterator<String> i = fruits.FindFirstThat ([] (String i) { return i == L\"apple\"; });\n Assert (i != fruits.end ());\n Assert (fruits.size () == 4);\n }\n for (Iterator<String> i = fruits.begin (); i != fruits.end (); ++i) {\n if (String::EqualsComparer{CompareOptions::eCaseInsensitive}(*i, L\"apple\")) {\n fruits.Remove (i);\n \/\/ with STL containers, it would be illegal to reference i again, as in i++.\n \/\/ However, with Stroika iterators, they are smart about doing the right thing,\n \/\/ when they point to a deleted item, and this code will work as expected.\n }\n }\n Assert (fruits.size () == 2);\n }\n}\n\nvoid Samples::Containers::Collection::RunDemo ()\n{\n SimplestCollectionTest_ ();\n UseParticularConcreteRepresentation_ ();\n InterfaceWithSTLContainers_ ();\n PrintTheContentsOfAContainerToTheTraceLog_ ();\n StoreOtherSortsOfElements_ ();\n UseLinqLikeFunctionalAPIs_ ();\n CollectionOfThingsWithNoOpEqualsAndNotDefaultConstructibleEtc_ ();\n IteratorsAndSafeUpdateIteration_ ();\n}\n<commit_msg>react to name change<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved\n *\/\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Characters\/String.h\"\n#include \"Stroika\/Foundation\/Characters\/ToString.h\"\n#include \"Stroika\/Foundation\/Containers\/Collection.h\"\n#include \"Stroika\/Foundation\/Containers\/SortedCollection.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n\/\/ Not generally included, but you can include these if you want to select a particular backend implementation\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Collection_Array.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Collection_LinkedList.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Collection_stdforward_list.h\"\n\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n\n#include \"Collection.h\"\n\nusing namespace std;\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\n\nusing Characters::CompareOptions;\n\nnamespace {\n void SimplestCollectionTest_ ()\n {\n \/*\n * A Collection is the simplest form of Stroika container. You can add things, and remove them, and iterate over them.\n * View the class declaration, with all the methods well documented, must with examples of usage.\n *\/\n Collection<int> c;\n c.Add (3);\n c += 13;\n for ([[maybe_unused]] int i : c) {\n Lambda_Arg_Unused_BWA (i); \/\/ warning C4189: 'i': local variable is initialized but not referenced\n Assert (i == 3 or i == 13);\n }\n Assert (c.size () == 2);\n }\n}\n\nnamespace {\n void UseParticularConcreteRepresentation_ ()\n {\n {\n Collection<int> c{3, 5, 19, 3040, 34, 1, 33, 33, 4, 19};\n\n \/\/ Unclear what the performance characteristics of this will be - with a linked list - O(1), but with array, O(N) worst case.\n c += 4;\n\n \/\/ 'c' will now operate identically (same API) - but use a differnt backend datastructure for storage,\n \/\/ always showing O(1) worst case addition time\n c = Concrete::Collection_stdforward_list<int>{c};\n c += 4;\n }\n {\n using Characters::String;\n Collection<String> fruits;\n fruits += L\"apple\";\n fruits += L\"bananas\";\n fruits += L\"cherries\";\n fruits += L\"APPLE\";\n \/\/ Print (to debugger\/tracelog) the fruits - but now they could come out in any order\n DbgTrace (L\"fruits=%s\", Characters::ToString (fruits).c_str ());\n Assert (fruits.size () == 4); \/\/ they are all there\n\n \/\/ Like changing the backend. But this still respects all the rules of a Collection (no order specified) -\n \/\/ except now it will happen to be ordered (using the default compare function)\n fruits = SortedCollection<String>{fruits};\n DbgTrace (L\"sorted fruits=%s\", Characters::ToString (fruits).c_str ());\n Assert (fruits.size () == 4); \/\/ only one apple or the other (case squished)\n \/\/ note they must now be in alphabetic order\n Assert (fruits.SequenceEquals (initializer_list<String>{L\"APPLE\", L\"apple\", L\"bananas\", L\"cherries\"}));\n\n \/\/ But, we can do the same thing with a compare function that sorts case insensitively\n fruits = SortedCollection<String>{String::LessComparer{CompareOptions::eCaseInsensitive}, fruits};\n DbgTrace (L\"sorted case insensitve fruits=%s\", Characters::ToString (fruits).c_str ());\n Assert (fruits.SequenceEquals (initializer_list<String>{L\"apple\", L\"APPLE\", L\"bananas\", L\"cherries\"}) or\n fruits.SequenceEquals (initializer_list<String>{L\"APPLE\", L\"apple\", L\"bananas\", L\"cherries\"}));\n }\n }\n}\n\nnamespace {\n void InterfaceWithSTLContainers_ ()\n {\n vector<int> aVector{1, 3, 5, 7, 9, 11};\n Collection<int> c{aVector};\n\n \/\/ CANNOT guarantee the ordering is the same, as Collection guarantees it keeps all the same elements,\n \/\/ but does not guarantee maintaining order.\n Assert (c.SetEquals (aVector));\n Assert (c.SequenceEquals (aVector) or not c.SequenceEquals (aVector));\n\n vector<int> v2 = c.As<vector<int>> ();\n \/\/ V will contain all the same elements as aVector, but maybe not in the same order.\n \/\/ it will be in the order the 'c' collection happened to produce\n }\n}\n\nnamespace {\n void PrintTheContentsOfAContainerToTheTraceLog_ ()\n {\n \/*\n * Use DbgTrace and Characters::ToString () to echo objects to a tracelog file (and\/or debugger output under windows)\n *\/\n Debug::TraceContextBumper ctx{L\"PrintTheContentsOfAContainerToTheTraceLog_\"};\n Collection<int> tmp{1, 3, 5, 7, 9};\n DbgTrace (L\"tmp=%s\", Characters::ToString (tmp).c_str ());\n }\n}\n\nnamespace {\n void StoreOtherSortsOfElements_ ()\n {\n Debug::TraceContextBumper ctx{L\"StoreOtherSortsOfElements_\"};\n using Characters::String;\n Collection<String> fruits;\n fruits += L\"apple\";\n fruits += L\"bananas\";\n fruits += L\"cherries\";\n DbgTrace (L\"fruits=%s\", Characters::ToString (fruits).c_str ());\n }\n}\n\nnamespace {\n void UseLinqLikeFunctionalAPIs_ ()\n {\n Debug::TraceContextBumper ctx{L\"PrintTheContentsOfAContainerToTheTraceLog_\"};\n \/*\n * See the Iterable<> template in Iterable.h - for a ton more of this functional style linq-like operations\n * you can do on any Stroika container.\n *\/\n {\n Collection<int> tmp{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n auto whereTestResult = tmp.Where ([] (int i) { return i % 2 == 1; });\n DbgTrace (L\"tmp=%s\", Characters::ToString (whereTestResult).c_str ());\n }\n {\n Collection<int> tmp{1, 2, 3, 4, 5, 1, 2, 3, 4, 5};\n auto d = tmp.Distinct ();\n DbgTrace (L\"d=%s\", Characters::ToString (d).c_str ());\n Assert (d.SetEquals (initializer_list<int>{1, 2, 3, 4, 5}));\n }\n {\n using Characters::String;\n Collection<String> fruits;\n fruits += L\"apple\";\n fruits += L\"APPLE\";\n fruits += L\"bananas\";\n fruits += L\"cherries\";\n DbgTrace (L\"fruits=%s\", Characters::ToString (fruits.Distinct (String::EqualsComparer{CompareOptions::eCaseInsensitive})).c_str ());\n Assert (fruits.Distinct (String::EqualsComparer{CompareOptions::eCaseInsensitive}).size () == 3); \/\/ only one apple or the other (case squished)\n }\n }\n}\n\nnamespace {\n void CollectionOfThingsWithNoOpEqualsAndNotDefaultConstructibleEtc_ ()\n {\n struct MyFunnyObject_ {\n MyFunnyObject_ () = delete; \/\/ no need to be default constructible\n MyFunnyObject_ (int \/*n*\/)\n {\n \/\/ need some constructor to test\n }\n MyFunnyObject_ (const MyFunnyObject_&) = default; \/\/ OK, but you do need to be copyable\n };\n Collection<MyFunnyObject_> myObjects;\n myObjects.Add (MyFunnyObject_{3});\n myObjects += MyFunnyObject_{4}; \/\/ use whatever add syntax you want\n\n \/\/ THIS WONT WORK, because no operator== defined\n \/\/ myObjects.Remove (MyFunnyObject_{3});\n \/\/ but this will remove the first object found\n Assert (myObjects.size () == 2);\n myObjects.Remove (MyFunnyObject_{3}, [] (const MyFunnyObject_&, const MyFunnyObject_&) { return true; });\n Assert (myObjects.size () == 1);\n }\n}\n\nnamespace {\n void IteratorsAndSafeUpdateIteration_ ()\n {\n using Characters::String;\n Collection<String> fruits;\n fruits += L\"apple\";\n fruits += L\"APPLE\";\n fruits += L\"bananas\";\n fruits += L\"cherries\";\n\n {\n Iterator<String> i = fruits.FindFirstThat ([] (String i) { return i == L\"apple\"; });\n Assert (i != fruits.end ());\n Assert (fruits.size () == 4);\n }\n for (Iterator<String> i = fruits.begin (); i != fruits.end (); ++i) {\n if (String::EqualsComparer{CompareOptions::eCaseInsensitive}(*i, L\"apple\")) {\n fruits.Remove (i);\n \/\/ with STL containers, it would be illegal to reference i again, as in i++.\n \/\/ However, with Stroika iterators, they are smart about doing the right thing,\n \/\/ when they point to a deleted item, and this code will work as expected.\n }\n }\n Assert (fruits.size () == 2);\n }\n}\n\nvoid Samples::Containers::Collection::RunDemo ()\n{\n SimplestCollectionTest_ ();\n UseParticularConcreteRepresentation_ ();\n InterfaceWithSTLContainers_ ();\n PrintTheContentsOfAContainerToTheTraceLog_ ();\n StoreOtherSortsOfElements_ ();\n UseLinqLikeFunctionalAPIs_ ();\n CollectionOfThingsWithNoOpEqualsAndNotDefaultConstructibleEtc_ ();\n IteratorsAndSafeUpdateIteration_ ();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file lars_test.cpp\n *\n * Test for LARS\n *\/\n\n\/\/ Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need\n\/\/ to use FPC_WEAK, and it's not at all intuitive how to do that.\n\n\n#include <armadillo>\n#include <mlpack\/methods\/lars\/lars.hpp>\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(LARSTest);\n\nvoid GenerateProblem(arma::mat& X, arma::vec& y, size_t nPoints, size_t nDims)\n{\n X = arma::randn(nPoints, nDims);\n arma::vec beta = arma::randn(nDims, 1);\n y = X * beta;\n}\n\n\nvoid VerifyCorrectness(arma::vec beta, arma::vec errCorr, double lambda)\n{\n size_t nDims = beta.n_elem;\n const double tol = 1e-12;\n for(size_t j = 0; j < nDims; j++)\n {\n if (beta(j) == 0)\n {\n \/\/ make sure that errCorr(j) <= lambda\n BOOST_REQUIRE_SMALL(std::max(errCorr(j) - lambda, 0.0), tol);\n }\n else if (beta(j) < 0)\n {\n \/\/ make sure that errCorr(j) == lambda\n BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);\n }\n else\n { \/\/ beta(j) > 0\n \/\/ make sure that errCorr(j) == -lambda\n BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);\n }\n }\n}\n\n\nvoid LassoTest(size_t nPoints, size_t nDims, bool elasticNet, bool useCholesky)\n{\n arma::mat X;\n arma::vec y;\n\n for(size_t i = 0; i < 100; i++)\n {\n GenerateProblem(X, y, nPoints, nDims);\n\n \/\/ Armadillo's median is broken, so...\n arma::vec sortedAbsCorr = sort(abs(trans(X) * y));\n double lambda1 = sortedAbsCorr(nDims\/2);\n double lambda2;\n if (elasticNet)\n lambda2 = lambda1 \/ 2;\n else\n lambda2 = 0;\n\n\n LARS lars(useCholesky, lambda1, lambda2);\n lars.DoLARS(X, y);\n\n arma::vec betaOpt;\n lars.Solution(betaOpt);\n arma::vec errCorr = (arma::trans(X) * X + lambda2 *\n arma::eye(nDims, nDims)) * betaOpt - arma::trans(X) * y;\n\n VerifyCorrectness(betaOpt, errCorr, lambda1);\n }\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestLassoCholesky)\n{\n LassoTest(100, 10, true, false);\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestLassoGram)\n{\n LassoTest(100, 10, false, false);\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestElasticNetCholesky)\n{\n LassoTest(100, 10, true, true);\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestElasticNetGram)\n{\n LassoTest(100, 10, true, false);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n<commit_msg>fixed a bug in how we were checking the optimality conditions for the LASSO. holy shit, an error in the test case itself!<commit_after>\/**\n * @file lars_test.cpp\n *\n * Test for LARS\n *\/\n\n\/\/ Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need\n\/\/ to use FPC_WEAK, and it's not at all intuitive how to do that.\n\n\n#include <armadillo>\n#include <mlpack\/methods\/lars\/lars.hpp>\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(LARSTest);\n\nvoid GenerateProblem(arma::mat& X, arma::vec& y, size_t nPoints, size_t nDims)\n{\n X = arma::randn(nPoints, nDims);\n arma::vec beta = arma::randn(nDims, 1);\n y = X * beta;\n}\n\n\nvoid VerifyCorrectness(arma::vec beta, arma::vec errCorr, double lambda)\n{\n size_t nDims = beta.n_elem;\n const double tol = 1e-12;\n for(size_t j = 0; j < nDims; j++)\n {\n if (beta(j) == 0)\n {\n \/\/ make sure that |errCorr(j)| <= lambda\n BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);\n }\n else if (beta(j) < 0)\n {\n \/\/ make sure that errCorr(j) == lambda\n BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);\n }\n else\n { \/\/ beta(j) > 0\n \/\/ make sure that errCorr(j) == -lambda\n BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);\n }\n }\n}\n\n\nvoid LassoTest(size_t nPoints, size_t nDims, bool elasticNet, bool useCholesky)\n{\n arma::mat X;\n arma::vec y;\n\n for(size_t i = 0; i < 100; i++)\n {\n GenerateProblem(X, y, nPoints, nDims);\n\n \/\/ Armadillo's median is broken, so...\n arma::vec sortedAbsCorr = sort(abs(trans(X) * y));\n double lambda1 = sortedAbsCorr(nDims\/2);\n double lambda2;\n if (elasticNet)\n lambda2 = lambda1 \/ 2;\n else\n lambda2 = 0;\n\n\n LARS lars(useCholesky, lambda1, lambda2);\n lars.DoLARS(X, y);\n\n arma::vec betaOpt;\n lars.Solution(betaOpt);\n arma::vec errCorr = (arma::trans(X) * X + lambda2 *\n arma::eye(nDims, nDims)) * betaOpt - arma::trans(X) * y;\n\n VerifyCorrectness(betaOpt, errCorr, lambda1);\n }\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestLassoCholesky)\n{\n LassoTest(100, 10, true, false);\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestLassoGram)\n{\n LassoTest(100, 10, false, false);\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestElasticNetCholesky)\n{\n LassoTest(100, 10, true, true);\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestElasticNetGram)\n{\n LassoTest(100, 10, true, false);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n<|endoftext|>"} {"text":"<commit_before>\n#include \"..\/Flare.h\"\n#include \"..\/Game\/FlareWorld.h\"\n#include \"..\/Game\/FlareGame.h\"\n#include \"..\/Game\/FlareSimulatedSector.h\"\n#include \"..\/Spacecrafts\/FlareSimulatedSpacecraft.h\"\n\n#include \"FlarePeople.h\"\n\n\n#define LOCTEXT_NAMESPACE \"FlarePeopleInfo\"\n\n\n\/*----------------------------------------------------\n\tConstructor\n----------------------------------------------------*\/\n\nUFlarePeople::UFlarePeople(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n}\n\n\/*----------------------------------------------------\n Save\n----------------------------------------------------*\/\n\n\nvoid UFlarePeople::Load(UFlareSimulatedSector* ParentSector, const FFlarePeopleSave& Data)\n{\n\tGame = ParentSector->GetGame();\n\n\tPeopleData = Data;\n\tParent = ParentSector;\n}\n\nFFlarePeopleSave* UFlarePeople::Save()\n{\n\treturn &PeopleData;\n}\n\n\/*----------------------------------------------------\n Gameplay\n----------------------------------------------------*\/\n\nstatic uint32 BIRTH_POINT_TRESHOLD = 7120;\nstatic uint32 DEATH_POINT_TRESHOLD = 29200;\nstatic uint32 MONETARY_CREATION = 1000;\n\nvoid UFlarePeople::Simulate()\n{\n\tif(PeopleData.Population == 0)\n\t{\n\t\treturn;\n\t}\n\n\tFLOGV(\"Simulate people for sector %s. Population=%u\", *Parent->GetSectorName().ToString(), PeopleData.Population)\t\t\t\n\n\tSimulateResourcePurchase();\n\n\tfloat Happiness = GetHappiness();\n\n\t\/\/ Death of old age : 1 death for 80 years per inhabitant = 1 death per 29200 inhabitant days\n\t\/\/ Sickness increase with hunger and sadness\n\t\/\/\t- 4 times normal sickness if happiness is 0\n\t\/\/ - normal sickness if happiness is 1.5\n\t\/\/ - half sickness if happiness 2\n\t\/\/ Formula : sickness = 0.5 + (happiness -2)^2\n\t\/\/\n\t\/\/ Hunger is add to population death point\n\t\/\/\n\tfloat Sickness = 0.5 + FMath::Square(Happiness - 2);\n\tPeopleData.DeathPoint += (PeopleData.Population + PeopleData.HungerPoint * 2) * Sickness;\n\tKillPeople(PeopleData.DeathPoint \/ DEATH_POINT_TRESHOLD);\n\tPeopleData.DeathPoint = PeopleData.DeathPoint % DEATH_POINT_TRESHOLD;\n\n\t\/\/ Births : 1 birth for 20 years per inhabitant = 1 birth per 7120 inhabitant days\n\t\/\/ Fertility increase with happiness :\n\t\/\/\t - no fertility if hapinness is less of 50%\n\t\/\/ - normal fertility at 100 % happiness\n\t\/\/ - triple fertility at 200%\n\t\/\/ Formula : fertility = 2 * happiness -1\n\tfloat Fertility = FMath::Max(2 * Happiness -1, 0.0f);\n\n\tPeopleData.BirthPoint += PeopleData.Population * Fertility;\n\tGiveBirth(PeopleData.BirthPoint \/ BIRTH_POINT_TRESHOLD);\n\tPeopleData.BirthPoint = PeopleData.BirthPoint % BIRTH_POINT_TRESHOLD;\n\n\n\t\/\/ Eat\n\t\/\/ Each inhabitant eat 1 kg of food a day as vital food.\n\t\/\/ TODO dynamic consumtion\n\t\/\/ If an inhabitant don't heat, happiness decrease heavily and hunger is increase\n\t\/\/ If some inhabitant heat, the hunger deaseapear and some happiness is gain\n\tuint32 FoodConsumption = PeopleData.Population;\n\tuint32 EatenFood = FMath::Min(FoodConsumption, PeopleData.FoodStock);\n\t\/\/ Reduce stock\n\tPeopleData.FoodStock -= EatenFood;\n\tIncreaseHappiness(EatenFood \/ 10);\n\n\t\/\/ Reduce hunger (100% if everybody eat)\n\tfloat FeedPeopleRatio = (float) EatenFood \/ (float) FoodConsumption;\n\n\tPeopleData.HungerPoint *= 1 - FeedPeopleRatio;\n\n\n\t\/\/ Add hunger (0 if everybody eat)\n\tuint32 Hunger = FoodConsumption - EatenFood;\n\tPeopleData.HungerPoint += Hunger + PeopleData.HungerPoint \/ 10;\n\tDecreaseHappiness(Hunger * 10);\n\n\n\n\tFLOGV(\" - happiness: %f\", Happiness);\n\tFLOGV(\" - Sickness: %f\", Sickness);\n\tFLOGV(\" - Fertility: %f\", Fertility);\n\n\tFLOGV(\" - Food: %u\", PeopleData.FoodStock);\n\tFLOGV(\" - FoodConsumption: %u\", FoodConsumption);\n\tFLOGV(\" - EatenFood: %u\", EatenFood);\n\tFLOGV(\" - FeedPeopleRatio: %f\", FeedPeopleRatio);\n\tFLOGV(\" - Delta Hunger: %u\", Hunger);\n\tFLOGV(\" - Hunger: %u\", PeopleData.HungerPoint);\n\n\tFLOGV(\" - Money: %u\", PeopleData.Money);\n\tFLOGV(\" - Dept: %u\", PeopleData.Dept);\n}\n\nvoid UFlarePeople::SimulateResourcePurchase()\n{\n\tFFlareResourceDescription* Food = Game->GetResourceCatalog()->Get(\"food\");\n\tFFlareResourceDescription* Fuel = Game->GetResourceCatalog()->Get(\"fuel\");\n\tFFlareResourceDescription* Tools = Game->GetResourceCatalog()->Get(\"tools\");\n\tFFlareResourceDescription* Tech = Game->GetResourceCatalog()->Get(\"tech\");\n\n\t\/\/ Buy at food for 15 days\n\tuint32 FoodToHave = PeopleData.Population * 15; \/\/ In kg\n\tif(FoodToHave > PeopleData.FoodStock)\n\t{\n\t\tuint32 FoodToBuy = FoodToHave - PeopleData.FoodStock;\n\t\tFLOGV(\" FoodToBuy: %u\", FoodToBuy);\n\t\tuint32 BoughtFood = BuyResourcesInSector(Food, FoodToBuy \/ 1000); \/\/ In Tons\n\t\tFLOGV(\" BoughtFood: %u\", BoughtFood);\n\t\tPeopleData.FoodStock += BoughtFood * 1000; \/\/ In kg\n\t}\n\n\t\/\/ Todo stock\n\tuint32 BoughtFuel = BuyResourcesInSector(Fuel, PeopleData.Population \/ 1000); \/\/ In Tons\n\tuint32 BoughtTools = BuyResourcesInSector(Tools, PeopleData.Population \/ 1000); \/\/ In Tons\n\tuint32 BoughtTech = BuyResourcesInSector(Tech, PeopleData.Population \/ 1000); \/\/ In Tons\n\n\tPeopleData.HappinessPoint += BoughtFuel + BoughtTools + BoughtTech;\n\n}\n\nuint32 UFlarePeople::BuyResourcesInSector(FFlareResourceDescription* Resource, uint32 Quantity)\n{\n\t\/\/ Find companies selling the ressource\n\n\tTArray<UFlareSimulatedSpacecraft*> SellingStations;\n\tTArray<UFlareCompany*> SellingCompanies;\n\n\tfor (int32 SpacecraftIndex = 0; SpacecraftIndex < Parent->GetSectorStations().Num(); SpacecraftIndex++)\n\t{\n\t\tUFlareSimulatedSpacecraft* Station = Parent->GetSectorStations()[SpacecraftIndex];\n\n\t\tif(!Station->HasCapability(EFlareSpacecraftCapability::Consumer))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tSellingStations.Add(Station);\n\t\tSellingCompanies.AddUnique(Station->GetCompany());\n\t}\n\n\t\/\/ Limit quantity to buy with money\n\tuint32 ResourceToBuy = FMath::Min(Quantity, PeopleData.Money \/ Parent->GetResourcePrice(Resource));\n\n\twhile(ResourceToBuy > 0 && SellingCompanies.Num() > 0)\n\t{\n\t\tuint32 ReputationSum = 0;\n\t\tuint32 InitialResourceToBuy = ResourceToBuy;\n\n\t\t\/\/ Compute company reputation sum to share market part\n\t\tfor (int32 CompanyIndex = 0; CompanyIndex < SellingCompanies.Num(); CompanyIndex++)\n\t\t{\n\t\t\tFFlareCompanyReputationSave* Reputation = GetCompanyReputation(SellingCompanies[CompanyIndex]);\n\n\t\t\tReputationSum += Reputation->Reputation;\n\t\t}\n\n\t\tfor (int32 CompanyIndex = SellingCompanies.Num()-1; CompanyIndex >= 0; CompanyIndex--)\n\t\t{\n\t\t\tFFlareCompanyReputationSave* Reputation = GetCompanyReputation(SellingCompanies[CompanyIndex]);\n\n\t\t\tuint32 PartToBuy = (InitialResourceToBuy * Reputation->Reputation) \/ ReputationSum;\n\n\t\t\tuint32 BoughtQuantity = BuyInStationForCompany(Resource, PartToBuy, SellingCompanies[CompanyIndex], SellingStations);\n\t\t\tResourceToBuy -= BoughtQuantity;\n\t\t\tif(PartToBuy == 0 || BoughtQuantity < PartToBuy)\n\t\t\t{\n\t\t\t\tSellingCompanies.RemoveAt(CompanyIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Quantity - ResourceToBuy;\n}\n\nuint32 UFlarePeople::BuyInStationForCompany(FFlareResourceDescription* Resource, uint32 Quantity, UFlareCompany* Company, TArray<UFlareSimulatedSpacecraft*>& Stations)\n{\n\tuint32 RemainingQuantity = Quantity;\n\n\n\n\tfor (int32 StationIndex = 0; StationIndex < Stations.Num(); StationIndex++)\n\t{\n\t\tUFlareSimulatedSpacecraft* Station = Stations[StationIndex];\n\n\t\tif(Station->GetCompany() != Company)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tuint32 TakenQuantity = Station->GetCargoBay()->TakeResources(Resource, RemainingQuantity);\n\t\tRemainingQuantity -= TakenQuantity;\n\t\tuint32 Price = Parent->GetResourcePrice(Resource) * TakenQuantity;\n\t\tPeopleData.Money -= Price;\n\t\tCompany->GiveMoney(Price);\n\t}\n\n\treturn Quantity - RemainingQuantity;\n}\n\nvoid UFlarePeople::GiveBirth(uint32 BirthCount)\n{\n\tif(BirthCount == 0)\n\t{\n\t\treturn;\n\t}\n\n\tFLOGV(\"Give birth %u people for sector %s\", BirthCount, *Parent->GetSectorName().ToString());\n\n\t\/\/ Increase population\n\tPeopleData.Population += BirthCount;\n\n\t\/\/ Money creation\n\tPeopleData.Money += BirthCount * MONETARY_CREATION;\n\n\tIncreaseHappiness(BirthCount * 100 * 2);\n\tPeopleData.HappinessPoint += BirthCount * 100 * 2; \/\/ Birth happiness bonus\n}\n\nvoid UFlarePeople::KillPeople(uint32 KillCount)\n{\n\n\tuint32 PeopleToKill = FMath::Min(KillCount, PeopleData.Population);\n\tif(PeopleToKill == 0)\n\t{\n\t\treturn;\n\t}\n\n\tFLOGV(\"Kill %u people for sector %s\", KillCount, *Parent->GetSectorName().ToString());\n\n\n\tfloat KillRatio = (float) PeopleToKill \/ (float)PeopleData.Population;\n\t\/\/ Decrease population\n\tPeopleData.Population -= KillCount;\n\n\t\/\/ Money destruction\n\tPeopleData.Dept += KillCount * MONETARY_CREATION;\n\n\tDecreaseHappiness(KillCount * 100 * 2); \/\/ Death happiness malus\n\n\t\/\/Cancel dead hunger\n\tPeopleData.HungerPoint = (1 - KillRatio) * PeopleData.HungerPoint;\n\n\tif(PeopleToKill == 0)\n\t{\n\t\tResetPeople();\n\t}\n}\n\nvoid UFlarePeople::IncreaseHappiness(uint32 HappinessPoints)\n{\n\t\/\/ Max happiness is 2 so Happiness max is 200 x population\n\t\/\/ Gain happiness is boost when sad and difficult when happy\n\t\/\/ - Normal gain for 1 as happiness\n\t\/\/ - 4 times gain for 0 as happiness\n\t\/\/ - No gain for 2 as happiness\n\t\/\/ Formula: gain = (happiness - 2) ^ 2\n\tfloat Happiness = GetHappiness();\n\tfloat Gain = FMath::Square(Happiness - 2);\n\tPeopleData.HappinessPoint += HappinessPoints * Gain;\n\tPeopleData.HappinessPoint = FMath::Min(PeopleData.HappinessPoint, PeopleData.Population * 200);\n}\n\nvoid UFlarePeople::DecreaseHappiness(uint32 SadnessPoints)\n{\n\t\/\/ Same as for increase but gain are inverted\n\tfloat Happiness = GetHappiness();\n\tfloat Gain = FMath::Square(Happiness);\n\tPeopleData.HappinessPoint -= SadnessPoints * Gain;\n\tPeopleData.HappinessPoint = FMath::Max(PeopleData.HappinessPoint, (uint32) 0);\n}\n\nvoid UFlarePeople::SetHappiness(float Happiness)\n{\n\tPeopleData.HappinessPoint = PeopleData.Population * 100 * Happiness;\n}\n\nvoid UFlarePeople::Pay(uint32 Amount)\n{\n\tFLOGV(\"Pay to people for sector %s Amount=%u\", *Parent->GetSectorName().ToString(), Amount)\n\n\tuint32 Repayment = 0;\n\tif(PeopleData.Dept > 0)\n\t{\n\t\tRepayment = FMath::Min(PeopleData.Dept, Amount \/ 10);\n\t\tPeopleData.Dept -= Repayment;\n\t}\n\tPeopleData.Money += Amount - Repayment;\n}\n\nvoid UFlarePeople::ResetPeople()\n{\n\tPeopleData.Population = 0;\n\tPeopleData.BirthPoint = 0;\n\tPeopleData.DeathPoint = 0;\n\tPeopleData.FoodStock = 0;\n\tPeopleData.HappinessPoint = 0;\n\tPeopleData.HungerPoint = 0;\n\n\t\/\/ Don't reset money to avoid moyen lost\n\n}\n\n\/*----------------------------------------------------\n\tGetters\n----------------------------------------------------*\/\n\nfloat UFlarePeople::GetHappiness()\n{\n\tif(PeopleData.Population == 0)\n\t{\n\t\treturn 0;\n\t}\n\treturn (float) PeopleData.HappinessPoint \/ (100 * (float) PeopleData.Population);\n}\n\nFFlareCompanyReputationSave* UFlarePeople::GetCompanyReputation(UFlareCompany* Company)\n{\n\tfor(int ReputationIndex = 0; ReputationIndex < PeopleData.CompanyReputations.Num(); ReputationIndex++)\n\t{\n\t\tif(PeopleData.CompanyReputations[ReputationIndex].CompanyIdentifier == Company->GetIdentifier())\n\t\t{\n\t\t\treturn &PeopleData.CompanyReputations[ReputationIndex];\n\t\t}\n\t}\n\n\t\/\/Init Reputation\n\tFFlareCompanyReputationSave NewReputation;\n\tNewReputation.CompanyIdentifier = Company->GetIdentifier();\n\tNewReputation.Reputation = 1000 * PeopleData.Population;\n\tPeopleData.CompanyReputations.Add(NewReputation);\n\n\treturn GetCompanyReputation(Company);\n}\n\n#undef LOCTEXT_NAMESPACE\n<commit_msg>People buy the resources 105% of the market price to give margin to final reseller<commit_after>\n#include \"..\/Flare.h\"\n#include \"..\/Game\/FlareWorld.h\"\n#include \"..\/Game\/FlareGame.h\"\n#include \"..\/Game\/FlareSimulatedSector.h\"\n#include \"..\/Spacecrafts\/FlareSimulatedSpacecraft.h\"\n\n#include \"FlarePeople.h\"\n\n\n#define LOCTEXT_NAMESPACE \"FlarePeopleInfo\"\n\n\n\/*----------------------------------------------------\n\tConstructor\n----------------------------------------------------*\/\n\nUFlarePeople::UFlarePeople(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n}\n\n\/*----------------------------------------------------\n Save\n----------------------------------------------------*\/\n\n\nvoid UFlarePeople::Load(UFlareSimulatedSector* ParentSector, const FFlarePeopleSave& Data)\n{\n\tGame = ParentSector->GetGame();\n\n\tPeopleData = Data;\n\tParent = ParentSector;\n}\n\nFFlarePeopleSave* UFlarePeople::Save()\n{\n\treturn &PeopleData;\n}\n\n\/*----------------------------------------------------\n Gameplay\n----------------------------------------------------*\/\n\nstatic uint32 BIRTH_POINT_TRESHOLD = 7120;\nstatic uint32 DEATH_POINT_TRESHOLD = 29200;\nstatic uint32 MONETARY_CREATION = 1000;\n\nvoid UFlarePeople::Simulate()\n{\n\tif(PeopleData.Population == 0)\n\t{\n\t\treturn;\n\t}\n\n\tFLOGV(\"Simulate people for sector %s. Population=%u\", *Parent->GetSectorName().ToString(), PeopleData.Population)\t\t\t\n\n\tSimulateResourcePurchase();\n\n\tfloat Happiness = GetHappiness();\n\n\t\/\/ Death of old age : 1 death for 80 years per inhabitant = 1 death per 29200 inhabitant days\n\t\/\/ Sickness increase with hunger and sadness\n\t\/\/\t- 4 times normal sickness if happiness is 0\n\t\/\/ - normal sickness if happiness is 1.5\n\t\/\/ - half sickness if happiness 2\n\t\/\/ Formula : sickness = 0.5 + (happiness -2)^2\n\t\/\/\n\t\/\/ Hunger is add to population death point\n\t\/\/\n\tfloat Sickness = 0.5 + FMath::Square(Happiness - 2);\n\tPeopleData.DeathPoint += (PeopleData.Population + PeopleData.HungerPoint * 2) * Sickness;\n\tKillPeople(PeopleData.DeathPoint \/ DEATH_POINT_TRESHOLD);\n\tPeopleData.DeathPoint = PeopleData.DeathPoint % DEATH_POINT_TRESHOLD;\n\n\t\/\/ Births : 1 birth for 20 years per inhabitant = 1 birth per 7120 inhabitant days\n\t\/\/ Fertility increase with happiness :\n\t\/\/\t - no fertility if hapinness is less of 50%\n\t\/\/ - normal fertility at 100 % happiness\n\t\/\/ - triple fertility at 200%\n\t\/\/ Formula : fertility = 2 * happiness -1\n\tfloat Fertility = FMath::Max(2 * Happiness -1, 0.0f);\n\n\tPeopleData.BirthPoint += PeopleData.Population * Fertility;\n\tGiveBirth(PeopleData.BirthPoint \/ BIRTH_POINT_TRESHOLD);\n\tPeopleData.BirthPoint = PeopleData.BirthPoint % BIRTH_POINT_TRESHOLD;\n\n\n\t\/\/ Eat\n\t\/\/ Each inhabitant eat 1 kg of food a day as vital food.\n\t\/\/ TODO dynamic consumtion\n\t\/\/ If an inhabitant don't heat, happiness decrease heavily and hunger is increase\n\t\/\/ If some inhabitant heat, the hunger deaseapear and some happiness is gain\n\tuint32 FoodConsumption = PeopleData.Population;\n\tuint32 EatenFood = FMath::Min(FoodConsumption, PeopleData.FoodStock);\n\t\/\/ Reduce stock\n\tPeopleData.FoodStock -= EatenFood;\n\tIncreaseHappiness(EatenFood \/ 10);\n\n\t\/\/ Reduce hunger (100% if everybody eat)\n\tfloat FeedPeopleRatio = (float) EatenFood \/ (float) FoodConsumption;\n\n\tPeopleData.HungerPoint *= 1 - FeedPeopleRatio;\n\n\n\t\/\/ Add hunger (0 if everybody eat)\n\tuint32 Hunger = FoodConsumption - EatenFood;\n\tPeopleData.HungerPoint += Hunger + PeopleData.HungerPoint \/ 10;\n\tDecreaseHappiness(Hunger * 10);\n\n\n\n\tFLOGV(\" - happiness: %f\", Happiness);\n\tFLOGV(\" - Sickness: %f\", Sickness);\n\tFLOGV(\" - Fertility: %f\", Fertility);\n\n\tFLOGV(\" - Food: %u\", PeopleData.FoodStock);\n\tFLOGV(\" - FoodConsumption: %u\", FoodConsumption);\n\tFLOGV(\" - EatenFood: %u\", EatenFood);\n\tFLOGV(\" - FeedPeopleRatio: %f\", FeedPeopleRatio);\n\tFLOGV(\" - Delta Hunger: %u\", Hunger);\n\tFLOGV(\" - Hunger: %u\", PeopleData.HungerPoint);\n\n\tFLOGV(\" - Money: %u\", PeopleData.Money);\n\tFLOGV(\" - Dept: %u\", PeopleData.Dept);\n}\n\nvoid UFlarePeople::SimulateResourcePurchase()\n{\n\tFFlareResourceDescription* Food = Game->GetResourceCatalog()->Get(\"food\");\n\tFFlareResourceDescription* Fuel = Game->GetResourceCatalog()->Get(\"fuel\");\n\tFFlareResourceDescription* Tools = Game->GetResourceCatalog()->Get(\"tools\");\n\tFFlareResourceDescription* Tech = Game->GetResourceCatalog()->Get(\"tech\");\n\n\t\/\/ Buy at food for 15 days\n\tuint32 FoodToHave = PeopleData.Population * 15; \/\/ In kg\n\tif(FoodToHave > PeopleData.FoodStock)\n\t{\n\t\tuint32 FoodToBuy = FoodToHave - PeopleData.FoodStock;\n\t\tFLOGV(\" FoodToBuy: %u\", FoodToBuy);\n\t\tuint32 BoughtFood = BuyResourcesInSector(Food, FoodToBuy \/ 1000); \/\/ In Tons\n\t\tFLOGV(\" BoughtFood: %u\", BoughtFood);\n\t\tPeopleData.FoodStock += BoughtFood * 1000; \/\/ In kg\n\t}\n\n\t\/\/ Todo stock\n\tuint32 BoughtFuel = BuyResourcesInSector(Fuel, PeopleData.Population \/ 1000); \/\/ In Tons\n\tuint32 BoughtTools = BuyResourcesInSector(Tools, PeopleData.Population \/ 1000); \/\/ In Tons\n\tuint32 BoughtTech = BuyResourcesInSector(Tech, PeopleData.Population \/ 1000); \/\/ In Tons\n\n\tPeopleData.HappinessPoint += BoughtFuel + BoughtTools + BoughtTech;\n\n}\n\nuint32 UFlarePeople::BuyResourcesInSector(FFlareResourceDescription* Resource, uint32 Quantity)\n{\n\t\/\/ Find companies selling the ressource\n\n\tTArray<UFlareSimulatedSpacecraft*> SellingStations;\n\tTArray<UFlareCompany*> SellingCompanies;\n\n\tfor (int32 SpacecraftIndex = 0; SpacecraftIndex < Parent->GetSectorStations().Num(); SpacecraftIndex++)\n\t{\n\t\tUFlareSimulatedSpacecraft* Station = Parent->GetSectorStations()[SpacecraftIndex];\n\n\t\tif(!Station->HasCapability(EFlareSpacecraftCapability::Consumer))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tSellingStations.Add(Station);\n\t\tSellingCompanies.AddUnique(Station->GetCompany());\n\t}\n\n\t\/\/ Limit quantity to buy with money\n\tuint32 ResourceToBuy = FMath::Min(Quantity, PeopleData.Money \/ (uint32) (Parent->GetResourcePrice(Resource)*1.05));\n\n\twhile(ResourceToBuy > 0 && SellingCompanies.Num() > 0)\n\t{\n\t\tuint32 ReputationSum = 0;\n\t\tuint32 InitialResourceToBuy = ResourceToBuy;\n\n\t\t\/\/ Compute company reputation sum to share market part\n\t\tfor (int32 CompanyIndex = 0; CompanyIndex < SellingCompanies.Num(); CompanyIndex++)\n\t\t{\n\t\t\tFFlareCompanyReputationSave* Reputation = GetCompanyReputation(SellingCompanies[CompanyIndex]);\n\n\t\t\tReputationSum += Reputation->Reputation;\n\t\t}\n\n\t\tfor (int32 CompanyIndex = SellingCompanies.Num()-1; CompanyIndex >= 0; CompanyIndex--)\n\t\t{\n\t\t\tFFlareCompanyReputationSave* Reputation = GetCompanyReputation(SellingCompanies[CompanyIndex]);\n\n\t\t\tuint32 PartToBuy = (InitialResourceToBuy * Reputation->Reputation) \/ ReputationSum;\n\n\t\t\tuint32 BoughtQuantity = BuyInStationForCompany(Resource, PartToBuy, SellingCompanies[CompanyIndex], SellingStations);\n\t\t\tResourceToBuy -= BoughtQuantity;\n\t\t\tif(PartToBuy == 0 || BoughtQuantity < PartToBuy)\n\t\t\t{\n\t\t\t\tSellingCompanies.RemoveAt(CompanyIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Quantity - ResourceToBuy;\n}\n\nuint32 UFlarePeople::BuyInStationForCompany(FFlareResourceDescription* Resource, uint32 Quantity, UFlareCompany* Company, TArray<UFlareSimulatedSpacecraft*>& Stations)\n{\n\tuint32 RemainingQuantity = Quantity;\n\n\n\n\tfor (int32 StationIndex = 0; StationIndex < Stations.Num(); StationIndex++)\n\t{\n\t\tUFlareSimulatedSpacecraft* Station = Stations[StationIndex];\n\n\t\tif(Station->GetCompany() != Company)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tuint32 TakenQuantity = Station->GetCargoBay()->TakeResources(Resource, RemainingQuantity);\n\t\tRemainingQuantity -= TakenQuantity;\n\t\tuint32 Price = (uint32) (Parent->GetResourcePrice(Resource)*1.05) * TakenQuantity;\n\t\tPeopleData.Money -= Price;\n\t\tCompany->GiveMoney(Price);\n\t}\n\n\treturn Quantity - RemainingQuantity;\n}\n\nvoid UFlarePeople::GiveBirth(uint32 BirthCount)\n{\n\tif(BirthCount == 0)\n\t{\n\t\treturn;\n\t}\n\n\tFLOGV(\"Give birth %u people for sector %s\", BirthCount, *Parent->GetSectorName().ToString());\n\n\t\/\/ Increase population\n\tPeopleData.Population += BirthCount;\n\n\t\/\/ Money creation\n\tPeopleData.Money += BirthCount * MONETARY_CREATION;\n\n\tIncreaseHappiness(BirthCount * 100 * 2);\n\tPeopleData.HappinessPoint += BirthCount * 100 * 2; \/\/ Birth happiness bonus\n}\n\nvoid UFlarePeople::KillPeople(uint32 KillCount)\n{\n\n\tuint32 PeopleToKill = FMath::Min(KillCount, PeopleData.Population);\n\tif(PeopleToKill == 0)\n\t{\n\t\treturn;\n\t}\n\n\tFLOGV(\"Kill %u people for sector %s\", KillCount, *Parent->GetSectorName().ToString());\n\n\n\tfloat KillRatio = (float) PeopleToKill \/ (float)PeopleData.Population;\n\t\/\/ Decrease population\n\tPeopleData.Population -= KillCount;\n\n\t\/\/ Money destruction\n\tPeopleData.Dept += KillCount * MONETARY_CREATION;\n\n\tDecreaseHappiness(KillCount * 100 * 2); \/\/ Death happiness malus\n\n\t\/\/Cancel dead hunger\n\tPeopleData.HungerPoint = (1 - KillRatio) * PeopleData.HungerPoint;\n\n\tif(PeopleToKill == 0)\n\t{\n\t\tResetPeople();\n\t}\n}\n\nvoid UFlarePeople::IncreaseHappiness(uint32 HappinessPoints)\n{\n\t\/\/ Max happiness is 2 so Happiness max is 200 x population\n\t\/\/ Gain happiness is boost when sad and difficult when happy\n\t\/\/ - Normal gain for 1 as happiness\n\t\/\/ - 4 times gain for 0 as happiness\n\t\/\/ - No gain for 2 as happiness\n\t\/\/ Formula: gain = (happiness - 2) ^ 2\n\tfloat Happiness = GetHappiness();\n\tfloat Gain = FMath::Square(Happiness - 2);\n\tPeopleData.HappinessPoint += HappinessPoints * Gain;\n\tPeopleData.HappinessPoint = FMath::Min(PeopleData.HappinessPoint, PeopleData.Population * 200);\n}\n\nvoid UFlarePeople::DecreaseHappiness(uint32 SadnessPoints)\n{\n\t\/\/ Same as for increase but gain are inverted\n\tfloat Happiness = GetHappiness();\n\tfloat Gain = FMath::Square(Happiness);\n\tPeopleData.HappinessPoint -= SadnessPoints * Gain;\n\tPeopleData.HappinessPoint = FMath::Max(PeopleData.HappinessPoint, (uint32) 0);\n}\n\nvoid UFlarePeople::SetHappiness(float Happiness)\n{\n\tPeopleData.HappinessPoint = PeopleData.Population * 100 * Happiness;\n}\n\nvoid UFlarePeople::Pay(uint32 Amount)\n{\n\tFLOGV(\"Pay to people for sector %s Amount=%u\", *Parent->GetSectorName().ToString(), Amount)\n\n\tuint32 Repayment = 0;\n\tif(PeopleData.Dept > 0)\n\t{\n\t\tRepayment = FMath::Min(PeopleData.Dept, Amount \/ 10);\n\t\tPeopleData.Dept -= Repayment;\n\t}\n\tPeopleData.Money += Amount - Repayment;\n}\n\nvoid UFlarePeople::ResetPeople()\n{\n\tPeopleData.Population = 0;\n\tPeopleData.BirthPoint = 0;\n\tPeopleData.DeathPoint = 0;\n\tPeopleData.FoodStock = 0;\n\tPeopleData.HappinessPoint = 0;\n\tPeopleData.HungerPoint = 0;\n\n\t\/\/ Don't reset money to avoid moyen lost\n\n}\n\n\/*----------------------------------------------------\n\tGetters\n----------------------------------------------------*\/\n\nfloat UFlarePeople::GetHappiness()\n{\n\tif(PeopleData.Population == 0)\n\t{\n\t\treturn 0;\n\t}\n\treturn (float) PeopleData.HappinessPoint \/ (100 * (float) PeopleData.Population);\n}\n\nFFlareCompanyReputationSave* UFlarePeople::GetCompanyReputation(UFlareCompany* Company)\n{\n\tfor(int ReputationIndex = 0; ReputationIndex < PeopleData.CompanyReputations.Num(); ReputationIndex++)\n\t{\n\t\tif(PeopleData.CompanyReputations[ReputationIndex].CompanyIdentifier == Company->GetIdentifier())\n\t\t{\n\t\t\treturn &PeopleData.CompanyReputations[ReputationIndex];\n\t\t}\n\t}\n\n\t\/\/Init Reputation\n\tFFlareCompanyReputationSave NewReputation;\n\tNewReputation.CompanyIdentifier = Company->GetIdentifier();\n\tNewReputation.Reputation = 1000 * PeopleData.Population;\n\tPeopleData.CompanyReputations.Add(NewReputation);\n\n\treturn GetCompanyReputation(Company);\n}\n\n#undef LOCTEXT_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/atoms\/base\/Link.cc\n *\n * Copyright (C) 2008-2010 OpenCog Foundation\n * Copyright (C) 2002-2007 Novamente LLC\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <stdio.h>\n\n#include <opencog\/util\/exceptions.h>\n#include <opencog\/util\/Logger.h>\n\n#include <opencog\/atoms\/base\/ClassServer.h>\n#include <opencog\/atoms\/base\/Node.h>\n#include <opencog\/atomspace\/AtomTable.h>\n\n#include <boost\/range\/algorithm.hpp>\n\n#include \"Link.h\"\n\n\/\/#define DPRINTF printf\n#define DPRINTF(...)\n\nusing namespace opencog;\n\nvoid Link::resort(void)\n{\n \/\/ Caution: this comparison function MUST BE EXACTLY THE SAME as\n \/\/ the one in AtomTable.cc, used for Unordered links. Changing\n \/\/ this without changing the other one will break things!\n std::sort(_outgoing.begin(), _outgoing.end(), handle_less());\n}\n\nvoid Link::init(const HandleSeq& outgoingVector)\n{\n if (not classserver().isA(_type, LINK)) {\n throw InvalidParamException(TRACE_INFO,\n \"Link ctor: Atom type is not a Link: '%d' %s.\",\n _type, classserver().getTypeName(_type).c_str());\n }\n\n _outgoing = outgoingVector;\n \/\/ If the link is unordered, it will be normalized by sorting the\n \/\/ elements in the outgoing list.\n if (classserver().isA(_type, UNORDERED_LINK)) {\n resort();\n }\n}\n\nLink::~Link()\n{\n DPRINTF(\"Deleting link:\\n%s\\n\", this->toString().c_str());\n}\n\nstd::string Link::toShortString(const std::string& indent) const\n{\n std::stringstream answer;\n std::string more_indent = indent + \" \";\n\n answer << indent << \"(\" << classserver().getTypeName(_type);\n if (not getTruthValue()->isDefaultTV())\n answer << \" \" << getTruthValue()->toString();\n answer << \"\\n\";\n\n \/\/ Here the target string is made. If a target is a node, its name is\n \/\/ concatenated. If it's a link, all its properties are concatenated.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer << h->toShortString(more_indent);\n else\n answer << more_indent << \"Undefined Atom!\\n\";\n }\n\n answer << indent << \") ; [\" << _uuid << \"]\";\n\n if (_atomTable)\n answer << \"[\" << _atomTable->get_uuid() << \"]\\n\";\n else\n answer << \"[NULL]\\n\";\n\n return answer.str();\n}\n\nstd::string Link::toString(const std::string& indent) const\n{\n std::string answer = indent;\n std::string more_indent = indent + \" \";\n\n answer += \"(\" + classserver().getTypeName(_type);\n\n \/\/ Print the TV and AV only if its not the default.\n if (not getAttentionValue()->isDefaultAV())\n answer += \" (av \" +\n std::to_string(getAttentionValue()->getSTI()) + \" \" +\n std::to_string(getAttentionValue()->getLTI()) + \" \" +\n std::to_string(getAttentionValue()->getVLTI()) + \")\";\n\n if (not getTruthValue()->isDefaultTV())\n answer += \" \" + getTruthValue()->toString();\n\n answer += \"\\n\";\n \/\/ Here, the outset string is made. If a target is a node,\n \/\/ its name is concatenated. If it's a link, then recurse.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer += h->toString(more_indent);\n else\n answer += more_indent + \"Undefined Atom!\\n\";\n }\n\n answer += indent + \") ; [\" +\n std::to_string(_uuid) + \"][\" +\n std::to_string(_atomTable? _atomTable->get_uuid() : -1) +\n \"]\\n\";\n\n return answer;\n}\n\n\/\/ Content-based comparison.\nbool Link::operator==(const Atom& other) const\n{\n \/\/ Rule out obvious mis-matches, based on the hash.\n if (get_hash() != other.get_hash()) return false;\n if (getType() != other.getType()) return false;\n\n Arity sz = getArity();\n if (sz != other.getArity()) return false;\n\n const HandleSeq& rhs = other.getOutgoingSet();\n for (Arity i = 0; i < sz; i++)\n {\n if (_outgoing[i] != rhs[i])\n return false;\n }\n return true;\n}\n\n\/\/ Content-based ordering.\nbool Link::operator<(const Atom& other) const\n{\n if (get_hash() < other.get_hash()) return true;\n if (other.get_hash() < get_hash()) return false;\n\n \/\/ We get to here only if the hashes are equal.\n \/\/ Compare the contents directly, for this\n \/\/ (hopefully rare) case.\n if (getType() == other.getType()) {\n const HandleSeq& outgoing = getOutgoingSet();\n const HandleSeq& other_outgoing = other.getOutgoingSet();\n Arity arity = outgoing.size();\n Arity other_arity = other_outgoing.size();\n if (arity == other_arity) {\n Arity i = 0;\n while (i < arity) {\n Handle ll = outgoing[i];\n Handle rl = other_outgoing[i];\n if (ll == rl)\n i++;\n else\n return ll->operator<(*rl.atom_ptr());\n }\n return false;\n } else\n return arity < other_arity;\n } else\n return getType() < other.getType();\n}\n\n\/\/\/ Returns a Merkle tree hash -- that is, the hash of this link\n\/\/\/ chains the hash values of the child atoms, as well.\nContentHash Link::compute_hash() const\n{\n\t\/\/ djb hash\n\tContentHash hsh = 5381;\n\thsh += (hsh <<5) + getType();\n\n\tfor (const Handle& h: _outgoing)\n\t{\n\t\thsh += (hsh <<5) + h->get_hash(); \/\/ recursive!\n\t}\n\n\t\/\/ Links will always have the MSB set.\n\tContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);\n\thsh |= mask;\n\n\tif (Handle::INVALID_HASH == hsh) hsh -= 1;\n\t_content_hash = hsh;\n\treturn _content_hash;\n}\n<commit_msg>Bug-fix the content-compare for links.<commit_after>\/*\n * opencog\/atoms\/base\/Link.cc\n *\n * Copyright (C) 2008-2010 OpenCog Foundation\n * Copyright (C) 2002-2007 Novamente LLC\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <stdio.h>\n\n#include <opencog\/util\/exceptions.h>\n#include <opencog\/util\/Logger.h>\n\n#include <opencog\/atoms\/base\/ClassServer.h>\n#include <opencog\/atoms\/base\/Node.h>\n#include <opencog\/atomspace\/AtomTable.h>\n\n#include <boost\/range\/algorithm.hpp>\n\n#include \"Link.h\"\n\n\/\/#define DPRINTF printf\n#define DPRINTF(...)\n\nusing namespace opencog;\n\nvoid Link::resort(void)\n{\n \/\/ Caution: this comparison function MUST BE EXACTLY THE SAME as\n \/\/ the one in AtomTable.cc, used for Unordered links. Changing\n \/\/ this without changing the other one will break things!\n std::sort(_outgoing.begin(), _outgoing.end(), handle_less());\n}\n\nvoid Link::init(const HandleSeq& outgoingVector)\n{\n if (not classserver().isA(_type, LINK)) {\n throw InvalidParamException(TRACE_INFO,\n \"Link ctor: Atom type is not a Link: '%d' %s.\",\n _type, classserver().getTypeName(_type).c_str());\n }\n\n _outgoing = outgoingVector;\n \/\/ If the link is unordered, it will be normalized by sorting the\n \/\/ elements in the outgoing list.\n if (classserver().isA(_type, UNORDERED_LINK)) {\n resort();\n }\n}\n\nLink::~Link()\n{\n DPRINTF(\"Deleting link:\\n%s\\n\", this->toString().c_str());\n}\n\nstd::string Link::toShortString(const std::string& indent) const\n{\n std::stringstream answer;\n std::string more_indent = indent + \" \";\n\n answer << indent << \"(\" << classserver().getTypeName(_type);\n if (not getTruthValue()->isDefaultTV())\n answer << \" \" << getTruthValue()->toString();\n answer << \"\\n\";\n\n \/\/ Here the target string is made. If a target is a node, its name is\n \/\/ concatenated. If it's a link, all its properties are concatenated.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer << h->toShortString(more_indent);\n else\n answer << more_indent << \"Undefined Atom!\\n\";\n }\n\n answer << indent << \") ; [\" << _uuid << \"]\";\n\n if (_atomTable)\n answer << \"[\" << _atomTable->get_uuid() << \"]\\n\";\n else\n answer << \"[NULL]\\n\";\n\n return answer.str();\n}\n\nstd::string Link::toString(const std::string& indent) const\n{\n std::string answer = indent;\n std::string more_indent = indent + \" \";\n\n answer += \"(\" + classserver().getTypeName(_type);\n\n \/\/ Print the TV and AV only if its not the default.\n if (not getAttentionValue()->isDefaultAV())\n answer += \" (av \" +\n std::to_string(getAttentionValue()->getSTI()) + \" \" +\n std::to_string(getAttentionValue()->getLTI()) + \" \" +\n std::to_string(getAttentionValue()->getVLTI()) + \")\";\n\n if (not getTruthValue()->isDefaultTV())\n answer += \" \" + getTruthValue()->toString();\n\n answer += \"\\n\";\n \/\/ Here, the outset string is made. If a target is a node,\n \/\/ its name is concatenated. If it's a link, then recurse.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer += h->toString(more_indent);\n else\n answer += more_indent + \"Undefined Atom!\\n\";\n }\n\n answer += indent + \") ; [\" +\n std::to_string(_uuid) + \"][\" +\n std::to_string(_atomTable? _atomTable->get_uuid() : -1) +\n \"]\\n\";\n\n return answer;\n}\n\n\/\/ Content-based comparison.\nbool Link::operator==(const Atom& other) const\n{\n \/\/ If other points to this, then have equality.\n if (this == &other) return true;\n\n \/\/ Rule out obvious mis-matches, based on the hash.\n if (get_hash() != other.get_hash()) return false;\n if (getType() != other.getType()) return false;\n\n Arity sz = getArity();\n if (sz != other.getArity()) return false;\n\n \/\/ Perform a content-compare on the outgoing set.\n const HandleSeq& rhs = other.getOutgoingSet();\n for (Arity i = 0; i < sz; i++)\n {\n if (*((AtomPtr)_outgoing[i]) != *((AtomPtr)rhs[i]))\n return false;\n }\n return true;\n}\n\n\/\/ Content-based ordering.\nbool Link::operator<(const Atom& other) const\n{\n if (get_hash() < other.get_hash()) return true;\n if (other.get_hash() < get_hash()) return false;\n\n \/\/ We get to here only if the hashes are equal.\n \/\/ Compare the contents directly, for this\n \/\/ (hopefully rare) case.\n if (getType() == other.getType()) {\n const HandleSeq& outgoing = getOutgoingSet();\n const HandleSeq& other_outgoing = other.getOutgoingSet();\n Arity arity = outgoing.size();\n Arity other_arity = other_outgoing.size();\n if (arity == other_arity) {\n Arity i = 0;\n while (i < arity) {\n Handle ll = outgoing[i];\n Handle rl = other_outgoing[i];\n if (ll == rl)\n i++;\n else\n return ll->operator<(*rl.atom_ptr());\n }\n return false;\n } else\n return arity < other_arity;\n } else\n return getType() < other.getType();\n}\n\n\/\/\/ Returns a Merkle tree hash -- that is, the hash of this link\n\/\/\/ chains the hash values of the child atoms, as well.\nContentHash Link::compute_hash() const\n{\n\t\/\/ djb hash\n\tContentHash hsh = 5381;\n\thsh += (hsh <<5) + getType();\n\n\tfor (const Handle& h: _outgoing)\n\t{\n\t\thsh += (hsh <<5) + h->get_hash(); \/\/ recursive!\n\t}\n\n\t\/\/ Links will always have the MSB set.\n\tContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);\n\thsh |= mask;\n\n\tif (Handle::INVALID_HASH == hsh) hsh -= 1;\n\t_content_hash = hsh;\n\treturn _content_hash;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"UnrealCVPrivate.h\"\n#include \"ObjectPainter.h\"\n#include \"StaticMeshResources.h\"\n#include \"UE4CVServer.h\"\n#include \"SceneViewport.h\"\n\nstatic TMap<uint8, uint8> DecodeColorValue; \/\/ Convert Encoded Color to Display Color, for numerical issue\n\n\/\/ Do Gamma correction\nvoid BuildDecodeColorValue(float InvGamma)\n{\n\tDecodeColorValue.Empty();\n\tfor (int32 DisplayIter = 0; DisplayIter < 256; DisplayIter++) \/\/ if use uint8, this loop will go forever\n\t{\n\t\tint32 EncodeVal = FMath::FloorToInt(FMath::Pow((float)DisplayIter \/ 255.0, InvGamma) * 255.0);\n\t\tcheck(EncodeVal >= 0);\n\t\tcheck(EncodeVal <= 255);\n\t\tif (!DecodeColorValue.Find(EncodeVal))\n\t\t{\n\t\t\tDecodeColorValue.Emplace(EncodeVal, DisplayIter);\n\t\t}\n\t}\n\tcheck(DecodeColorValue.Num() < 256); \/\/ Not all of them can find a correspondence due to numerical issue\n}\n\nbool GetDisplayValue(uint8 InEncodedValue, uint8& OutDisplayValue, float InvGamma)\n{\n\tstatic float CachedInvGamma;\n\tif (DecodeColorValue.Num() == 0 || CachedInvGamma != InvGamma)\n\t{\n\t\tBuildDecodeColorValue(InvGamma);\n\t\tCachedInvGamma = InvGamma;\n\t}\n\n\tif (DecodeColorValue.Find(InEncodedValue))\n\t{\n\t\tOutDisplayValue = DecodeColorValue[InEncodedValue];\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\n\nFObjectPainter& FObjectPainter::Get()\n{\n\tstatic FObjectPainter Singleton(NULL);\n\treturn Singleton;\n}\n\nFObjectPainter::FObjectPainter(ULevel* InLevel)\n{\n\tthis->Level = InLevel;\n}\n\nFExecStatus FObjectPainter::SetActorColor(FString ObjectName, FColor Color)\n{\n\tauto ObjectsMapping = GetObjectsMapping();\n\tif (ObjectsMapping.Contains(ObjectName))\n\t{\n\t\tAActor* Actor = ObjectsMapping[ObjectName];\n\t\tif (PaintObject(Actor, Color))\n\t\t{\n\t\t\tObjectsColorMapping.Emplace(ObjectName, Color);\n\t\t\treturn FExecStatus::OK();\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn FExecStatus::Error(FString::Printf(TEXT(\"Failed to paint object %s\"), *ObjectName));\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn FExecStatus::Error(FString::Printf(TEXT(\"Object %s not exist\"), *ObjectName));\n\t}\n}\n\nFExecStatus FObjectPainter::GetActorColor(FString ObjectName)\n{\n\tif (ObjectsColorMapping.Contains(ObjectName))\n\t{\n\t\tFColor ObjectColor = ObjectsColorMapping[ObjectName]; \/\/ Make sure the object exist\n\t\tFString Message = ObjectColor.ToString();\n\t\t\/\/ FString Message = \"%.3f %.3f %.3f %.3f\";\n\t\treturn FExecStatus::OK(Message);\n\t}\n\telse\n\t{\n\t\treturn FExecStatus::Error(FString::Printf(TEXT(\"Object %s not exist\"), *ObjectName));\n\t}\n}\n\nFExecStatus FObjectPainter::GetObjectList()\n{\n\tTArray<FString> Keys;\n\tGetObjectsMapping().GetKeys(Keys);\n\tFString Message = \"\";\n\tfor (auto ObjectName : Keys)\n\t{\n\t\tMessage += ObjectName + \" \";\n\t}\n\tMessage = Message.LeftChop(1);\n\treturn FExecStatus::OK(Message);\n}\n\nTMap<FString, AActor*>& FObjectPainter::GetObjectsMapping()\n{\n\tstatic TMap<FString, AActor*> ObjectsMapping;\n\tif (!this->Level) return ObjectsMapping;\n\tcheck(Level);\n\tif (ObjectsMapping.Num() == 0)\n\t{\n\t\tfor (AActor* Actor : Level->Actors)\n\t\t{\n\t\t\tif (Actor && Actor->IsA(AStaticMeshActor::StaticClass())) \/\/ Only StaticMeshActor is interesting\n\t\t\t{\n\t\t\t\tFString ActorLabel = Actor->GetActorLabel();\n\t\t\t\tObjectsMapping.Emplace(ActorLabel, Actor);\n\t\t\t}\n\t\t}\n\t}\n\treturn ObjectsMapping;\n}\n\nbool FObjectPainter::PaintRandomColors()\n{\n\tFSceneViewport* SceneViewport = FUE4CVServer::Get().GetPawn()->GetWorld()->GetGameViewport()->GetGameViewport();\n\tfloat Gamma = SceneViewport->GetDisplayGamma();\n\tcheck(Gamma != 0);\n\tif (Gamma == 0) Gamma = 1;\n\tfloat InvGamma = 1 \/ Gamma;\n\tBuildDecodeColorValue(InvGamma);\n\t\/\/ Iterate over all actors\n\t\/\/ ULevel* Level = GetLevel();\n\n\t\/\/ Get a random color\n\tcheck(Level);\n\tfor (auto Actor : Level->Actors)\n\t{\n\t\tif (Actor && Actor->IsA(AStaticMeshActor::StaticClass())) \/\/ Only StaticMeshActor is interesting\n\t\t{\n\t\t\tFString ActorLabel = Actor->GetActorLabel();\n\t\t\t\/\/ FString ActorLabel = Actor->GetHumanReadableName();\n\t\t\t\/\/ FColor NewColor = FColor(FMath::RandRange(0, 255), FMath::RandRange(0, 255), FMath::RandRange(0, 255), 255);\n\t\t\t\/\/ FColor NewColor = FColor(1, 1, 1, 255);\n\t\t\tFColor NewColor;\n\t\t\tTArray<uint8> ValidVals;\n\t\t\tDecodeColorValue.GenerateKeyArray(ValidVals);\n\n\t\t\tNewColor.R = ValidVals[FMath::RandRange(0, ValidVals.Num()-1)];\n\t\t\tNewColor.G = ValidVals[FMath::RandRange(0, ValidVals.Num()-1)];\n\t\t\tNewColor.B = ValidVals[FMath::RandRange(0, ValidVals.Num()-1)];\n\t\t\tNewColor.A = 255;\n\t\t\t\/\/ FColor NewColor = FColor(128, 128, 128, 255);\n\n\t\t\tObjectsColorMapping.Emplace(ActorLabel, NewColor);\n\t\t\t\/\/ if (Actor->GetActorLabel() == FString(\"SM_Door43\"))\n\t\t\t{\n\t\t\t\tcheck(PaintObject(Actor, NewColor));\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Paint actor using floodfill.\n\t\/\/ return FExecStatus::OK();\n\treturn true;\n}\n\n\/** DisplayColor is the color that the screen will show\n\tIf DisplayColor.R = 128, the display will show 0.5 voltage\n\tTo achieve this, UnrealEngine will do gamma correction.\n\tThe value on image will be 187.\n\thttps:\/\/en.wikipedia.org\/wiki\/Gamma_correction#Methods_to_perform_display_gamma_correction_in_computing\n*\/\nbool FObjectPainter::PaintObject(AActor* Actor, const FColor& Color, bool IsColorGammaEncoded)\n{\n\tif (!Actor) return false;\n\n\tFColor NewColor;\n\tif (IsColorGammaEncoded)\n\t{\n\t\tFSceneViewport* SceneViewport = FUE4CVServer::Get().GetPawn()->GetWorld()->GetGameViewport()->GetGameViewport();\n\t\tfloat Gamma = SceneViewport->GetDisplayGamma();\n\t\tcheck(Gamma != 0);\n\t\tif (Gamma == 0) Gamma = 1;\n\t\tfloat InvGamma = 1 \/ Gamma;\n\n\t\tbool Converted = true;\n\t\tConverted &= GetDisplayValue(Color.R, NewColor.R, InvGamma);\n\t\tConverted &= GetDisplayValue(Color.G, NewColor.G, InvGamma);\n\t\tConverted &= GetDisplayValue(Color.B, NewColor.B, InvGamma);\n\t\tif (!Converted)\n\t\t{\n\t\t\tUE_LOG(LogTemp, Error, TEXT(\"Can not convert encoded color %d %d %d\"), Color.R, Color.G, Color.B);\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ See UnrealEngine\/Engine\/Shaders\/GammaCorrection.usf\n\t\t\/* This is the real calculation, but due to numerical issue, we need to use table lookup\n\t\tNewColor.R = FMath::RoundToInt(FMath::Pow(Color.R \/ 255.0, Gamma) * 255.0);\n\t\tNewColor.G = FMath::RoundToInt(FMath::Pow(Color.G \/ 255.0, Gamma) * 255.0);\n\t\tNewColor.B = FMath::RoundToInt(FMath::Pow(Color.B \/ 255.0, Gamma) * 255.0);\n\t\t*\/\n\t}\n\telse\n\t{\n\t\tNewColor = Color;\n\t}\n\n\tTArray<UMeshComponent*> PaintableComponents;\n\t\/\/ TInlineComponentArray<UMeshComponent*> MeshComponents;\n\t\/\/ Actor->GetComponents<UMeshComponent>(MeshComponents);\n\tActor->GetComponents<UMeshComponent>(PaintableComponents);\n\n\n\tfor (auto MeshComponent : PaintableComponents)\n\t{\n\t\tif (UStaticMeshComponent* StaticMeshComponent = Cast<UStaticMeshComponent>(MeshComponent))\n\t\t{\n\t\t\tif (UStaticMesh* StaticMesh = StaticMeshComponent->StaticMesh)\n\t\t\t{\n\t\t\t\tuint32 PaintingMeshLODIndex = 0;\n\t\t\t\tuint32 NumLODLevel = StaticMeshComponent->StaticMesh->RenderData->LODResources.Num();\n\t\t\t\tcheck(NumLODLevel == 1);\n\t\t\t\tFStaticMeshLODResources& LODModel = StaticMeshComponent->StaticMesh->RenderData->LODResources[PaintingMeshLODIndex];\n\t\t\t\tFStaticMeshComponentLODInfo* InstanceMeshLODInfo = NULL;\n\n\t\t\t\t\/\/ PaintingMeshLODIndex + 1 is the minimum requirement, enlarge if not satisfied\n\t\t\t\tStaticMeshComponent->SetLODDataCount(PaintingMeshLODIndex + 1, StaticMeshComponent->LODData.Num());\n\t\t\t\tInstanceMeshLODInfo = &StaticMeshComponent->LODData[PaintingMeshLODIndex];\n\n\t\t\t\t\/\/ Setup OverrideVertexColors\n\t\t\t\t\/\/ if (!InstanceMeshLODInfo->OverrideVertexColors) \/\/ TODO: Check this\n\t\t\t\t{\n\t\t\t\t\tInstanceMeshLODInfo->OverrideVertexColors = new FColorVertexBuffer;\n\n\t\t\t\t\tFColor FillColor = FColor(255, 255, 255, 255);\n\t\t\t\t\tInstanceMeshLODInfo->OverrideVertexColors->InitFromSingleColor(FColor::White, LODModel.GetNumVertices());\n\t\t\t\t}\n\n\t\t\t\tuint32 NumVertices = LODModel.GetNumVertices();\n\t\t\t\tcheck(InstanceMeshLODInfo->OverrideVertexColors);\n\t\t\t\tcheck(NumVertices <= InstanceMeshLODInfo->OverrideVertexColors->GetNumVertices());\n\t\t\t\t\/\/ StaticMeshComponent->CachePaintedDataIfNecessary();\n\n\t\t\t\tfor (uint32 ColorIndex = 0; ColorIndex < NumVertices; ++ColorIndex)\n\t\t\t\t{\n\t\t\t\t\t\/\/ FColor NewColor = FColor(FMath::RandRange(0, 255), FMath::RandRange(0, 255), FMath::RandRange(0, 255), 255);\n\t\t\t\t\t\/\/ LODModel.ColorVertexBuffer.VertexColor(ColorIndex) = NewColor; \/\/ This is vertex level\n\t\t\t\t\t\/\/ Need to initialize the vertex buffer first\n\t\t\t\t\tuint32 NumOverrideVertexColors = InstanceMeshLODInfo->OverrideVertexColors->GetNumVertices();\n\t\t\t\t\tuint32 NumPaintedVertices = InstanceMeshLODInfo->PaintedVertices.Num();\n\t\t\t\t\t\/\/ check(NumOverrideVertexColors == NumPaintedVertices);\n\t\t\t\t\tInstanceMeshLODInfo->OverrideVertexColors->VertexColor(ColorIndex) = NewColor;\n\t\t\t\t\t\/\/ InstanceMeshLODInfo->PaintedVertices[ColorIndex].Color = NewColor;\n\t\t\t\t}\n\t\t\t\tBeginInitResource(InstanceMeshLODInfo->OverrideVertexColors);\n\t\t\t\tStaticMeshComponent->MarkRenderStateDirty();\n\t\t\t\t\/\/ BeginUpdateResourceRHI(InstanceMeshLODInfo->OverrideVertexColors);\n\n\n\t\t\t\t\/*\n\t\t\t\t\/\/ TODO: Need to check other LOD levels\n\t\t\t\t\/\/ Use flood fill to paint mesh vertices\n\t\t\t\tUE_LOG(LogTemp, Warning, TEXT(\"%s:%s has %d vertices\"), *Actor->GetActorLabel(), *StaticMeshComponent->GetName(), NumVertices);\n\n\t\t\t\tif (LODModel.ColorVertexBuffer.GetNumVertices() == 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Mesh doesn't have a color vertex buffer yet! We'll create one now.\n\t\t\t\t\tLODModel.ColorVertexBuffer.InitFromSingleColor(FColor(255, 255, 255, 255), LODModel.GetNumVertices());\n\t\t\t\t}\n\n\t\t\t\t*\/\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid FObjectPainter::SetLevel(ULevel* InLevel)\n{\n\tLevel = InLevel;\n}\n<commit_msg>Add color map.<commit_after>#include \"UnrealCVPrivate.h\"\n#include \"ObjectPainter.h\"\n#include \"StaticMeshResources.h\"\n#include \"UE4CVServer.h\"\n#include \"SceneViewport.h\"\n\nstatic TMap<uint8, uint8> DecodeColorValue; \/\/ Convert Encoded Color to Display Color, for numerical issue\n\n\/\/ Do Gamma correction\nvoid BuildDecodeColorValue(float InvGamma)\n{\n\tDecodeColorValue.Empty();\n\tfor (int32 DisplayIter = 0; DisplayIter < 256; DisplayIter++) \/\/ if use uint8, this loop will go forever\n\t{\n\t\tint32 EncodeVal = FMath::FloorToInt(FMath::Pow((float)DisplayIter \/ 255.0, InvGamma) * 255.0);\n\t\tcheck(EncodeVal >= 0);\n\t\tcheck(EncodeVal <= 255);\n\t\tif (!DecodeColorValue.Find(EncodeVal))\n\t\t{\n\t\t\tDecodeColorValue.Emplace(EncodeVal, DisplayIter);\n\t\t}\n\t}\n\tcheck(DecodeColorValue.Num() < 256); \/\/ Not all of them can find a correspondence due to numerical issue\n}\n\nbool GetDisplayValue(uint8 InEncodedValue, uint8& OutDisplayValue, float InvGamma)\n{\n\tstatic float CachedInvGamma;\n\tif (DecodeColorValue.Num() == 0 || CachedInvGamma != InvGamma)\n\t{\n\t\tBuildDecodeColorValue(InvGamma);\n\t\tCachedInvGamma = InvGamma;\n\t}\n\n\tif (DecodeColorValue.Find(InEncodedValue))\n\t{\n\t\tOutDisplayValue = DecodeColorValue[InEncodedValue];\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\nint32 GetChannelValue(uint32 Index)\n{\n\tstatic int32 Values[256] = { 0 };\n\tstatic bool Init = false;\n\tif (!Init)\n\t{\n\t\tfloat Step = 256;\n\t\tuint32 Iter = 0;\n\t\tValues[0] = 0;\n\t\twhile (Step >= 1)\n\t\t{\n\t\t\tfor (uint32 Value = Step-1; Value <= 256; Value += Step * 2)\n\t\t\t{\n\t\t\t\tIter++;\n\t\t\t\tValues[Iter] = Value;\n\t\t\t}\n\t\t\tStep \/= 2;\n\t\t}\n\t\tInit = true;\n\t}\n\tif (Index >= 0 && Index <= 255)\n\t{\n\t\treturn Values[Index];\n\t}\n\telse\n\t{\n\t\tUE_LOG(LogTemp, Error, TEXT(\"Invalid channel index\"));\n\t\tcheck(false);\n\t\treturn -1;\n\t}\n}\n\nvoid GetColors(int32 MaxVal, bool Fix1, bool Fix2, bool Fix3, TArray<FColor>& ColorMap)\n{\n\tfor (int32 I = 0; I <= (Fix1 ? 0 : MaxVal-1); I++)\n\t{\n\t\tfor (int32 J = 0; J <= (Fix2 ? 0 : MaxVal-1); J++)\n\t\t{\n\t\t\tfor (int32 K = 0; K <= (Fix3 ? 0 : MaxVal-1); K++)\n\t\t\t{\n\t\t\t\tuint8 R = GetChannelValue(Fix1 ? MaxVal : I);\n\t\t\t\tuint8 G = GetChannelValue(Fix2 ? MaxVal : J);\n\t\t\t\tuint8 B = GetChannelValue(Fix3 ? MaxVal : K);\n\t\t\t\tFColor Color(R, G, B, 255);\n\t\t\t\tColorMap.Add(Color);\n\t\t\t}\n\t\t}\n\t}\n}\n\nFColor GetColorFromColorMap(int32 ObjectIndex)\n{\n\tstatic TArray<FColor> ColorMap;\n\tif (ColorMap.Num() == 0)\n\t{\n\t\tfor (int32 MaxChannelIndex = 0; MaxChannelIndex < 10; MaxChannelIndex++) \/\/ Get color map for 1000 objects\n\t\t{\n\t\t\t\/\/ GetColors(MaxChannelIndex, false, false, false, ColorMap);\n\t\t\tGetColors(MaxChannelIndex, false, false, true , ColorMap);\n\t\t\tGetColors(MaxChannelIndex, false, true , false, ColorMap);\n\t\t\tGetColors(MaxChannelIndex, false, true , true , ColorMap);\n\t\t\tGetColors(MaxChannelIndex, true , false, false, ColorMap);\n\t\t\tGetColors(MaxChannelIndex, true , false, true , ColorMap);\n\t\t\tGetColors(MaxChannelIndex, true , true , false, ColorMap);\n\t\t\tGetColors(MaxChannelIndex, true , true , true , ColorMap);\n\t\t}\n\t}\n\tcheck(ColorMap.Num() == 1000);\n\tcheck(ObjectIndex >= 0 && ObjectIndex <= 1000);\n\treturn ColorMap[ObjectIndex];\n}\n\nFObjectPainter& FObjectPainter::Get()\n{\n\tstatic FObjectPainter Singleton(NULL);\n\treturn Singleton;\n}\n\nFObjectPainter::FObjectPainter(ULevel* InLevel)\n{\n\tthis->Level = InLevel;\n}\n\nFExecStatus FObjectPainter::SetActorColor(FString ObjectName, FColor Color)\n{\n\tauto ObjectsMapping = GetObjectsMapping();\n\tif (ObjectsMapping.Contains(ObjectName))\n\t{\n\t\tAActor* Actor = ObjectsMapping[ObjectName];\n\t\tif (PaintObject(Actor, Color))\n\t\t{\n\t\t\tObjectsColorMapping.Emplace(ObjectName, Color);\n\t\t\treturn FExecStatus::OK();\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn FExecStatus::Error(FString::Printf(TEXT(\"Failed to paint object %s\"), *ObjectName));\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn FExecStatus::Error(FString::Printf(TEXT(\"Object %s not exist\"), *ObjectName));\n\t}\n}\n\nFExecStatus FObjectPainter::GetActorColor(FString ObjectName)\n{\n\tif (ObjectsColorMapping.Contains(ObjectName))\n\t{\n\t\tFColor ObjectColor = ObjectsColorMapping[ObjectName]; \/\/ Make sure the object exist\n\t\tFString Message = ObjectColor.ToString();\n\t\t\/\/ FString Message = \"%.3f %.3f %.3f %.3f\";\n\t\treturn FExecStatus::OK(Message);\n\t}\n\telse\n\t{\n\t\treturn FExecStatus::Error(FString::Printf(TEXT(\"Object %s not exist\"), *ObjectName));\n\t}\n}\n\nFExecStatus FObjectPainter::GetObjectList()\n{\n\tTArray<FString> Keys;\n\tGetObjectsMapping().GetKeys(Keys);\n\tFString Message = \"\";\n\tfor (auto ObjectName : Keys)\n\t{\n\t\tMessage += ObjectName + \" \";\n\t}\n\tMessage = Message.LeftChop(1);\n\treturn FExecStatus::OK(Message);\n}\n\nTMap<FString, AActor*>& FObjectPainter::GetObjectsMapping()\n{\n\tstatic TMap<FString, AActor*> ObjectsMapping;\n\tif (!this->Level) return ObjectsMapping;\n\tcheck(Level);\n\tif (ObjectsMapping.Num() == 0)\n\t{\n\t\tfor (AActor* Actor : Level->Actors)\n\t\t{\n\t\t\tif (Actor && Actor->IsA(AStaticMeshActor::StaticClass())) \/\/ Only StaticMeshActor is interesting\n\t\t\t{\n\t\t\t\tFString ActorLabel = Actor->GetActorLabel();\n\t\t\t\tObjectsMapping.Emplace(ActorLabel, Actor);\n\t\t\t}\n\t\t}\n\t}\n\treturn ObjectsMapping;\n}\n\nbool FObjectPainter::PaintRandomColors()\n{\n\tFSceneViewport* SceneViewport = FUE4CVServer::Get().GetPawn()->GetWorld()->GetGameViewport()->GetGameViewport();\n\tfloat Gamma = SceneViewport->GetDisplayGamma();\n\tcheck(Gamma != 0);\n\tif (Gamma == 0) Gamma = 1;\n\tfloat InvGamma = 1 \/ Gamma;\n\tBuildDecodeColorValue(InvGamma);\n\t\/\/ Iterate over all actors\n\t\/\/ ULevel* Level = GetLevel();\n\n\t\/\/ Get a random color\n\tcheck(Level);\n\tuint32 ObjectIndex = 0;\n\tfor (auto Actor : Level->Actors)\n\t{\n\t\tif (Actor && Actor->IsA(AStaticMeshActor::StaticClass())) \/\/ Only StaticMeshActor is interesting\n\t\t{\n\t\t\tFString ActorLabel = Actor->GetActorLabel();\n\t\t\t\/\/ FString ActorLabel = Actor->GetHumanReadableName();\n\t\t\t\/\/ FColor NewColor = FColor(FMath::RandRange(0, 255), FMath::RandRange(0, 255), FMath::RandRange(0, 255), 255);\n\t\t\t\/\/ FColor NewColor = FColor(1, 1, 1, 255);\n\t\t\t\/*\n\t\t\tFColor NewColor;\n\t\t\tTArray<uint8> ValidVals;\n\t\t\tDecodeColorValue.GenerateKeyArray(ValidVals);\n\n\t\t\tNewColor.R = ValidVals[FMath::RandRange(0, ValidVals.Num()-1)];\n\t\t\tNewColor.G = ValidVals[FMath::RandRange(0, ValidVals.Num()-1)];\n\t\t\tNewColor.B = ValidVals[FMath::RandRange(0, ValidVals.Num()-1)];\n\t\t\tNewColor.A = 255;\n\t\t\t*\/\n\t\t\t\/\/ FColor NewColor = FColor(128, 128, 128, 255);\n\t\t\t\/\/ FColor NewColor = FColor::MakeRandomColor();\n\t\t\tFColor NewColor = GetColorFromColorMap(ObjectIndex);\n\n\t\t\tObjectsColorMapping.Emplace(ActorLabel, NewColor);\n\t\t\tcheck(PaintObject(Actor, NewColor));\n\t\t\tObjectIndex++;\n\t\t}\n\t}\n\n\t\/\/ Paint actor using floodfill.\n\t\/\/ return FExecStatus::OK();\n\treturn true;\n}\n\n\/** DisplayColor is the color that the screen will show\n\tIf DisplayColor.R = 128, the display will show 0.5 voltage\n\tTo achieve this, UnrealEngine will do gamma correction.\n\tThe value on image will be 187.\n\thttps:\/\/en.wikipedia.org\/wiki\/Gamma_correction#Methods_to_perform_display_gamma_correction_in_computing\n*\/\nbool FObjectPainter::PaintObject(AActor* Actor, const FColor& Color, bool IsColorGammaEncoded)\n{\n\tif (!Actor) return false;\n\n\tFColor NewColor;\n\tif (IsColorGammaEncoded)\n\t{\n\t\t\/*\n\t\tFSceneViewport* SceneViewport = FUE4CVServer::Get().GetPawn()->GetWorld()->GetGameViewport()->GetGameViewport();\n\t\tfloat Gamma = SceneViewport->GetDisplayGamma();\n\t\tcheck(Gamma != 0);\n\t\tif (Gamma == 0) Gamma = 1;\n\t\tfloat InvGamma = 1 \/ Gamma;\n\n\t\tbool Converted = true;\n\t\tConverted &= GetDisplayValue(Color.R, NewColor.R, InvGamma);\n\t\tConverted &= GetDisplayValue(Color.G, NewColor.G, InvGamma);\n\t\tConverted &= GetDisplayValue(Color.B, NewColor.B, InvGamma);\n\t\tif (!Converted)\n\t\t{\n\t\t\tUE_LOG(LogTemp, Error, TEXT(\"Can not convert encoded color %d %d %d\"), Color.R, Color.G, Color.B);\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ See UnrealEngine\/Engine\/Shaders\/GammaCorrection.usf\n\t\t\/\/ This is the real calculation, but due to numerical issue, we need to use table lookup\n\t\t\/\/ NewColor.R = FMath::RoundToInt(FMath::Pow(Color.R \/ 255.0, Gamma) * 255.0);\n\t\t\/\/ NewColor.G = FMath::RoundToInt(FMath::Pow(Color.G \/ 255.0, Gamma) * 255.0);\n\t\t\/\/ NewColor.B = FMath::RoundToInt(FMath::Pow(Color.B \/ 255.0, Gamma) * 255.0);\n\t\t*\/\n\t\tFLinearColor LinearColor = FLinearColor::FromPow22Color(Color);\n\t\tNewColor = LinearColor.ToFColor(false);\n\t\t\/\/ NewColor = LinearColor.ToFColor(true); \/\/ this is incorrect, not sRGB, just pow22\n\t}\n\telse\n\t{\n\t\tNewColor = Color;\n\t}\n\n\tTArray<UMeshComponent*> PaintableComponents;\n\t\/\/ TInlineComponentArray<UMeshComponent*> MeshComponents;\n\t\/\/ Actor->GetComponents<UMeshComponent>(MeshComponents);\n\tActor->GetComponents<UMeshComponent>(PaintableComponents);\n\n\n\tfor (auto MeshComponent : PaintableComponents)\n\t{\n\t\tif (UStaticMeshComponent* StaticMeshComponent = Cast<UStaticMeshComponent>(MeshComponent))\n\t\t{\n\t\t\tif (UStaticMesh* StaticMesh = StaticMeshComponent->StaticMesh)\n\t\t\t{\n\t\t\t\tuint32 PaintingMeshLODIndex = 0;\n\t\t\t\tuint32 NumLODLevel = StaticMeshComponent->StaticMesh->RenderData->LODResources.Num();\n\t\t\t\tcheck(NumLODLevel == 1);\n\t\t\t\tFStaticMeshLODResources& LODModel = StaticMeshComponent->StaticMesh->RenderData->LODResources[PaintingMeshLODIndex];\n\t\t\t\tFStaticMeshComponentLODInfo* InstanceMeshLODInfo = NULL;\n\n\t\t\t\t\/\/ PaintingMeshLODIndex + 1 is the minimum requirement, enlarge if not satisfied\n\t\t\t\tStaticMeshComponent->SetLODDataCount(PaintingMeshLODIndex + 1, StaticMeshComponent->LODData.Num());\n\t\t\t\tInstanceMeshLODInfo = &StaticMeshComponent->LODData[PaintingMeshLODIndex];\n\n\t\t\t\t\/\/ Setup OverrideVertexColors\n\t\t\t\t\/\/ if (!InstanceMeshLODInfo->OverrideVertexColors) \/\/ TODO: Check this\n\t\t\t\t{\n\t\t\t\t\tInstanceMeshLODInfo->OverrideVertexColors = new FColorVertexBuffer;\n\n\t\t\t\t\tFColor FillColor = FColor(255, 255, 255, 255);\n\t\t\t\t\tInstanceMeshLODInfo->OverrideVertexColors->InitFromSingleColor(FColor::White, LODModel.GetNumVertices());\n\t\t\t\t}\n\n\t\t\t\tuint32 NumVertices = LODModel.GetNumVertices();\n\t\t\t\tcheck(InstanceMeshLODInfo->OverrideVertexColors);\n\t\t\t\tcheck(NumVertices <= InstanceMeshLODInfo->OverrideVertexColors->GetNumVertices());\n\t\t\t\t\/\/ StaticMeshComponent->CachePaintedDataIfNecessary();\n\n\t\t\t\tfor (uint32 ColorIndex = 0; ColorIndex < NumVertices; ++ColorIndex)\n\t\t\t\t{\n\t\t\t\t\t\/\/ FColor NewColor = FColor(FMath::RandRange(0, 255), FMath::RandRange(0, 255), FMath::RandRange(0, 255), 255);\n\t\t\t\t\t\/\/ LODModel.ColorVertexBuffer.VertexColor(ColorIndex) = NewColor; \/\/ This is vertex level\n\t\t\t\t\t\/\/ Need to initialize the vertex buffer first\n\t\t\t\t\tuint32 NumOverrideVertexColors = InstanceMeshLODInfo->OverrideVertexColors->GetNumVertices();\n\t\t\t\t\tuint32 NumPaintedVertices = InstanceMeshLODInfo->PaintedVertices.Num();\n\t\t\t\t\t\/\/ check(NumOverrideVertexColors == NumPaintedVertices);\n\t\t\t\t\tInstanceMeshLODInfo->OverrideVertexColors->VertexColor(ColorIndex) = NewColor;\n\t\t\t\t\t\/\/ InstanceMeshLODInfo->PaintedVertices[ColorIndex].Color = NewColor;\n\t\t\t\t}\n\t\t\t\tBeginInitResource(InstanceMeshLODInfo->OverrideVertexColors);\n\t\t\t\tStaticMeshComponent->MarkRenderStateDirty();\n\t\t\t\t\/\/ BeginUpdateResourceRHI(InstanceMeshLODInfo->OverrideVertexColors);\n\n\n\t\t\t\t\/*\n\t\t\t\t\/\/ TODO: Need to check other LOD levels\n\t\t\t\t\/\/ Use flood fill to paint mesh vertices\n\t\t\t\tUE_LOG(LogTemp, Warning, TEXT(\"%s:%s has %d vertices\"), *Actor->GetActorLabel(), *StaticMeshComponent->GetName(), NumVertices);\n\n\t\t\t\tif (LODModel.ColorVertexBuffer.GetNumVertices() == 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Mesh doesn't have a color vertex buffer yet! We'll create one now.\n\t\t\t\t\tLODModel.ColorVertexBuffer.InitFromSingleColor(FColor(255, 255, 255, 255), LODModel.GetNumVertices());\n\t\t\t\t}\n\n\t\t\t\t*\/\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid FObjectPainter::SetLevel(ULevel* InLevel)\n{\n\tLevel = InLevel;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 <windows.h>\n#include <shlwapi.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/environment.h\"\n#include \"base\/file_util.h\"\n#include \"base\/trace_event.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/breakpad_win.h\"\n#include \"chrome\/app\/client_util.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/google_update_constants.h\"\n#include \"chrome\/installer\/util\/util_constants.h\"\n\nnamespace {\n\/\/ The entry point signature of chrome.dll.\ntypedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);\n\ntypedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();\n\n\/\/ Not generic, we only handle strings up to 128 chars.\nbool ReadRegistryStr(HKEY key, const wchar_t* name, std::wstring* value) {\n BYTE out[128 * sizeof(wchar_t)];\n DWORD size = sizeof(out);\n DWORD type = 0;\n if (ERROR_SUCCESS != ::RegQueryValueExW(key, name, NULL, &type, out, &size))\n return false;\n if (type != REG_SZ)\n return false;\n value->assign(reinterpret_cast<wchar_t*>(out));\n return true;\n}\n\n\/\/ Gets chrome version according to the load path. |exe_path| must be the\n\/\/ backslash terminated directory of the current chrome.exe.\nbool GetVersion(const wchar_t* exe_path, const wchar_t* key_path,\n std::wstring* version) {\n HKEY reg_root = InstallUtil::IsPerUserInstall(exe_path) ? HKEY_CURRENT_USER :\n HKEY_LOCAL_MACHINE;\n HKEY key;\n if (::RegOpenKeyEx(reg_root, key_path, 0, KEY_READ, &key) != ERROR_SUCCESS)\n return false;\n\n \/\/ If 'new_chrome.exe' is present it means chrome was auto-updated while\n \/\/ running. We need to consult the opv value so we can load the old dll.\n \/\/ TODO(cpu) : This is solving the same problem as the environment variable\n \/\/ so one of them will eventually be deprecated.\n std::wstring new_chrome_exe(exe_path);\n new_chrome_exe.append(installer_util::kChromeNewExe);\n if (::PathFileExistsW(new_chrome_exe.c_str()) &&\n ReadRegistryStr(key, google_update::kRegOldVersionField, version)) {\n ::RegCloseKey(key);\n return true;\n }\n\n bool ret = ReadRegistryStr(key, google_update::kRegVersionField, version);\n ::RegCloseKey(key);\n return ret;\n}\n\n\/\/ Gets the path of the current exe with a trailing backslash.\nstd::wstring GetExecutablePath() {\n wchar_t path[MAX_PATH];\n ::GetModuleFileNameW(NULL, path, MAX_PATH);\n if (!::PathRemoveFileSpecW(path))\n return std::wstring();\n std::wstring exe_path(path);\n return exe_path.append(L\"\\\\\");\n}\n\n\/\/ Not generic, we only handle strings up to 128 chars.\nbool EnvQueryStr(const wchar_t* key_name, std::wstring* value) {\n wchar_t out[128];\n DWORD count = sizeof(out)\/sizeof(out[0]);\n DWORD rv = ::GetEnvironmentVariableW(key_name, out, count);\n if ((rv == 0) || (rv >= count))\n return false;\n *value = out;\n return true;\n}\n\n\/\/ Expects that |dir| has a trailing backslash. |dir| is modified so it\n\/\/ contains the full path that was tried. Caller must check for the return\n\/\/ value not being null to dermine if this path contains a valid dll.\nHMODULE LoadChromeWithDirectory(std::wstring* dir) {\n ::SetCurrentDirectoryW(dir->c_str());\n const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();\n#ifdef _WIN64\n if ((cmd_line.GetSwitchValueASCII(switches::kProcessType) ==\n switches::kNaClBrokerProcess) ||\n (cmd_line.GetSwitchValueASCII(switches::kProcessType) ==\n switches::kNaClLoaderProcess)) {\n \/\/ Load the 64-bit DLL when running in a 64-bit process.\n dir->append(installer_util::kChromeNaCl64Dll);\n } else {\n \/\/ Only NaCl broker and loader can be launched as Win64 processes.\n NOTREACHED();\n return NULL;\n }\n#else\n dir->append(installer_util::kChromeDll);\n#endif\n\n#ifdef NDEBUG\n \/\/ Experimental pre-reading optimization\n \/\/ The idea is to pre read significant portion of chrome.dll in advance\n \/\/ so that subsequent hard page faults are avoided.\n if (!cmd_line.HasSwitch(switches::kProcessType)) {\n \/\/ The kernel brings in 8 pages for the code section at a time and 4 pages\n \/\/ for other sections. We can skip over these pages to avoid a soft page\n \/\/ fault which may not occur during code execution. However skipping 4K at\n \/\/ a time still has better performance over 32K and 16K according to data.\n \/\/ TODO(ananta)\n \/\/ Investigate this and tune.\n const size_t kStepSize = 4 * 1024;\n\n DWORD pre_read_size = 0;\n DWORD pre_read_step_size = kStepSize;\n DWORD pre_read = 1;\n\n HKEY key = NULL;\n if (::RegOpenKeyEx(HKEY_CURRENT_USER, L\"Software\\\\Google\\\\ChromeFrame\",\n 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) {\n DWORD unused = sizeof(pre_read_size);\n RegQueryValueEx(key, L\"PreReadSize\", NULL, NULL,\n reinterpret_cast<LPBYTE>(&pre_read_size), &unused);\n RegQueryValueEx(key, L\"PreReadStepSize\", NULL, NULL,\n reinterpret_cast<LPBYTE>(&pre_read_step_size), &unused);\n RegQueryValueEx(key, L\"PreRead\", NULL, NULL,\n reinterpret_cast<LPBYTE>(&pre_read), &unused);\n RegCloseKey(key);\n key = NULL;\n }\n if (pre_read) {\n TRACE_EVENT_BEGIN(\"PreReadImage\", 0, \"\");\n file_util::PreReadImage(dir->c_str(), pre_read_size, pre_read_step_size);\n TRACE_EVENT_END(\"PreReadImage\", 0, \"\");\n }\n }\n#endif \/\/ NDEBUG\n\n return ::LoadLibraryExW(dir->c_str(), NULL,\n LOAD_WITH_ALTERED_SEARCH_PATH);\n}\n\n\/\/ Set did_run \"dr\" in omaha's client state for this product.\nbool SetDidRunState(const wchar_t* guid, const wchar_t* value) {\n std::wstring key_path(google_update::kRegPathClientState);\n key_path.append(L\"\\\\\").append(guid);\n HKEY reg_key;\n if (::RegCreateKeyExW(HKEY_CURRENT_USER, key_path.c_str(), 0, NULL,\n REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL,\n ®_key, NULL) == ERROR_SUCCESS) {\n \/\/ Note that the length here must be in bytes and must account for the\n \/\/ terminating null char.\n ::RegSetValueExW(reg_key, google_update::kRegDidRunField, 0, REG_SZ,\n reinterpret_cast<const BYTE *>(value),\n (::lstrlenW(value) + 1) * sizeof(wchar_t));\n ::RegCloseKey(reg_key);\n return true;\n }\n return false;\n}\n\nbool RecordDidRun(const wchar_t* guid) {\n return SetDidRunState(guid, L\"1\");\n}\n\nbool ClearDidRun(const wchar_t* guid) {\n return SetDidRunState(guid, L\"0\");\n}\n\n}\n\/\/=============================================================================\n\nMainDllLoader::MainDllLoader() : dll_(NULL) {\n}\n\nMainDllLoader::~MainDllLoader() {\n#ifdef PURIFY\n \/\/ We should never unload the dll. There is only risk and no gain from\n \/\/ doing so. The singleton dtors have been already run by AtExitManager.\n ::FreeLibrary(dll_);\n#endif\n}\n\n\/\/ Loading chrome is an interesting afair. First we try loading from the current\n\/\/ directory to support run-what-you-compile and other development scenarios.\n\/\/ If that fails then we look at the 'CHROME_VERSION' env variable to determine\n\/\/ if we should stick with an older dll version even if a new one is available\n\/\/ to support upgrade-in-place scenarios, and if that fails we finally we look\n\/\/ at the registry which should point us to the latest version.\nHMODULE MainDllLoader::Load(std::wstring* version, std::wstring* file) {\n std::wstring dir(GetExecutablePath());\n *file = dir;\n HMODULE dll = LoadChromeWithDirectory(file);\n if (dll)\n return dll;\n\n if (!EnvQueryStr(\n BrowserDistribution::GetDistribution()->GetEnvVersionKey().c_str(),\n version)) {\n std::wstring reg_path(GetRegistryPath());\n \/\/ Look into the registry to find the latest version.\n if (!GetVersion(dir.c_str(), reg_path.c_str(), version))\n return NULL;\n }\n\n *file = dir;\n file->append(*version).append(L\"\\\\\");\n return LoadChromeWithDirectory(file);\n}\n\n\/\/ Launching is a matter of loading the right dll, setting the CHROME_VERSION\n\/\/ environment variable and just calling the entry point. Derived classes can\n\/\/ add custom code in the OnBeforeLaunch callback.\nint MainDllLoader::Launch(HINSTANCE instance,\n sandbox::SandboxInterfaceInfo* sbox_info) {\n std::wstring version;\n std::wstring file;\n dll_ = Load(&version, &file);\n if (!dll_)\n return ResultCodes::MISSING_DATA;\n\n scoped_ptr<base::Environment> env(base::Environment::Create());\n env->SetVar(WideToUTF8(\n BrowserDistribution::GetDistribution()->GetEnvVersionKey()).c_str(),\n WideToUTF8(version));\n\n InitCrashReporterWithDllPath(file);\n OnBeforeLaunch(version);\n\n DLL_MAIN entry_point =\n reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, \"ChromeMain\"));\n if (!entry_point)\n return ResultCodes::BAD_PROCESS_TYPE;\n\n int rc = entry_point(instance, sbox_info, ::GetCommandLineW());\n return OnBeforeExit(rc);\n}\n\nvoid MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {\n RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =\n reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(\n ::GetProcAddress(dll_,\n \"RelaunchChromeBrowserWithNewCommandLineIfNeeded\"));\n if (!relaunch_function) {\n LOG(ERROR) << \"Could not find exported function \"\n << \"RelaunchChromeBrowserWithNewCommandLineIfNeeded\";\n } else {\n relaunch_function();\n }\n}\n\n\/\/=============================================================================\n\nclass ChromeDllLoader : public MainDllLoader {\n public:\n virtual std::wstring GetRegistryPath() {\n std::wstring key(google_update::kRegPathClients);\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n key.append(L\"\\\\\").append(dist->GetAppGuid());\n return key;\n }\n\n virtual void OnBeforeLaunch(const std::wstring& version) {\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n RecordDidRun(dist->GetAppGuid().c_str());\n }\n\n virtual int OnBeforeExit(int return_code) {\n \/\/ NORMAL_EXIT_CANCEL is used for experiments when the user cancels\n \/\/ so we need to reset the did_run signal so omaha does not count\n \/\/ this run as active usage.\n if (ResultCodes::NORMAL_EXIT_CANCEL == return_code) {\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n ClearDidRun(dist->GetAppGuid().c_str());\n }\n return return_code;\n }\n};\n\n\/\/=============================================================================\n\nclass ChromiumDllLoader : public MainDllLoader {\n public:\n virtual std::wstring GetRegistryPath() {\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n return dist->GetVersionKey();\n }\n};\n\nMainDllLoader* MakeMainDllLoader() {\n#if defined(GOOGLE_CHROME_BUILD)\n return new ChromeDllLoader();\n#else\n return new ChromiumDllLoader();\n#endif\n}\n<commit_msg>Use Environment::GetVar instead of the obscure EnvQueryStr function.<commit_after>\/\/ Copyright (c) 2010 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 <windows.h>\n#include <shlwapi.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/environment.h\"\n#include \"base\/file_util.h\"\n#include \"base\/trace_event.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/breakpad_win.h\"\n#include \"chrome\/app\/client_util.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/google_update_constants.h\"\n#include \"chrome\/installer\/util\/util_constants.h\"\n\nnamespace {\n\/\/ The entry point signature of chrome.dll.\ntypedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);\n\ntypedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();\n\n\/\/ Not generic, we only handle strings up to 128 chars.\nbool ReadRegistryStr(HKEY key, const wchar_t* name, std::wstring* value) {\n BYTE out[128 * sizeof(wchar_t)];\n DWORD size = sizeof(out);\n DWORD type = 0;\n if (ERROR_SUCCESS != ::RegQueryValueExW(key, name, NULL, &type, out, &size))\n return false;\n if (type != REG_SZ)\n return false;\n value->assign(reinterpret_cast<wchar_t*>(out));\n return true;\n}\n\n\/\/ Gets chrome version according to the load path. |exe_path| must be the\n\/\/ backslash terminated directory of the current chrome.exe.\nbool GetVersion(const wchar_t* exe_path, const wchar_t* key_path,\n std::wstring* version) {\n HKEY reg_root = InstallUtil::IsPerUserInstall(exe_path) ? HKEY_CURRENT_USER :\n HKEY_LOCAL_MACHINE;\n HKEY key;\n if (::RegOpenKeyEx(reg_root, key_path, 0, KEY_READ, &key) != ERROR_SUCCESS)\n return false;\n\n \/\/ If 'new_chrome.exe' is present it means chrome was auto-updated while\n \/\/ running. We need to consult the opv value so we can load the old dll.\n \/\/ TODO(cpu) : This is solving the same problem as the environment variable\n \/\/ so one of them will eventually be deprecated.\n std::wstring new_chrome_exe(exe_path);\n new_chrome_exe.append(installer_util::kChromeNewExe);\n if (::PathFileExistsW(new_chrome_exe.c_str()) &&\n ReadRegistryStr(key, google_update::kRegOldVersionField, version)) {\n ::RegCloseKey(key);\n return true;\n }\n\n bool ret = ReadRegistryStr(key, google_update::kRegVersionField, version);\n ::RegCloseKey(key);\n return ret;\n}\n\n\/\/ Gets the path of the current exe with a trailing backslash.\nstd::wstring GetExecutablePath() {\n wchar_t path[MAX_PATH];\n ::GetModuleFileNameW(NULL, path, MAX_PATH);\n if (!::PathRemoveFileSpecW(path))\n return std::wstring();\n std::wstring exe_path(path);\n return exe_path.append(L\"\\\\\");\n}\n\n\/\/ Expects that |dir| has a trailing backslash. |dir| is modified so it\n\/\/ contains the full path that was tried. Caller must check for the return\n\/\/ value not being null to dermine if this path contains a valid dll.\nHMODULE LoadChromeWithDirectory(std::wstring* dir) {\n ::SetCurrentDirectoryW(dir->c_str());\n const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();\n#ifdef _WIN64\n if ((cmd_line.GetSwitchValueASCII(switches::kProcessType) ==\n switches::kNaClBrokerProcess) ||\n (cmd_line.GetSwitchValueASCII(switches::kProcessType) ==\n switches::kNaClLoaderProcess)) {\n \/\/ Load the 64-bit DLL when running in a 64-bit process.\n dir->append(installer_util::kChromeNaCl64Dll);\n } else {\n \/\/ Only NaCl broker and loader can be launched as Win64 processes.\n NOTREACHED();\n return NULL;\n }\n#else\n dir->append(installer_util::kChromeDll);\n#endif\n\n#ifdef NDEBUG\n \/\/ Experimental pre-reading optimization\n \/\/ The idea is to pre read significant portion of chrome.dll in advance\n \/\/ so that subsequent hard page faults are avoided.\n if (!cmd_line.HasSwitch(switches::kProcessType)) {\n \/\/ The kernel brings in 8 pages for the code section at a time and 4 pages\n \/\/ for other sections. We can skip over these pages to avoid a soft page\n \/\/ fault which may not occur during code execution. However skipping 4K at\n \/\/ a time still has better performance over 32K and 16K according to data.\n \/\/ TODO(ananta)\n \/\/ Investigate this and tune.\n const size_t kStepSize = 4 * 1024;\n\n DWORD pre_read_size = 0;\n DWORD pre_read_step_size = kStepSize;\n DWORD pre_read = 1;\n\n HKEY key = NULL;\n if (::RegOpenKeyEx(HKEY_CURRENT_USER, L\"Software\\\\Google\\\\ChromeFrame\",\n 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) {\n DWORD unused = sizeof(pre_read_size);\n RegQueryValueEx(key, L\"PreReadSize\", NULL, NULL,\n reinterpret_cast<LPBYTE>(&pre_read_size), &unused);\n RegQueryValueEx(key, L\"PreReadStepSize\", NULL, NULL,\n reinterpret_cast<LPBYTE>(&pre_read_step_size), &unused);\n RegQueryValueEx(key, L\"PreRead\", NULL, NULL,\n reinterpret_cast<LPBYTE>(&pre_read), &unused);\n RegCloseKey(key);\n key = NULL;\n }\n if (pre_read) {\n TRACE_EVENT_BEGIN(\"PreReadImage\", 0, \"\");\n file_util::PreReadImage(dir->c_str(), pre_read_size, pre_read_step_size);\n TRACE_EVENT_END(\"PreReadImage\", 0, \"\");\n }\n }\n#endif \/\/ NDEBUG\n\n return ::LoadLibraryExW(dir->c_str(), NULL,\n LOAD_WITH_ALTERED_SEARCH_PATH);\n}\n\n\/\/ Set did_run \"dr\" in omaha's client state for this product.\nbool SetDidRunState(const wchar_t* guid, const wchar_t* value) {\n std::wstring key_path(google_update::kRegPathClientState);\n key_path.append(L\"\\\\\").append(guid);\n HKEY reg_key;\n if (::RegCreateKeyExW(HKEY_CURRENT_USER, key_path.c_str(), 0, NULL,\n REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL,\n ®_key, NULL) == ERROR_SUCCESS) {\n \/\/ Note that the length here must be in bytes and must account for the\n \/\/ terminating null char.\n ::RegSetValueExW(reg_key, google_update::kRegDidRunField, 0, REG_SZ,\n reinterpret_cast<const BYTE *>(value),\n (::lstrlenW(value) + 1) * sizeof(wchar_t));\n ::RegCloseKey(reg_key);\n return true;\n }\n return false;\n}\n\nbool RecordDidRun(const wchar_t* guid) {\n return SetDidRunState(guid, L\"1\");\n}\n\nbool ClearDidRun(const wchar_t* guid) {\n return SetDidRunState(guid, L\"0\");\n}\n\n}\n\/\/=============================================================================\n\nMainDllLoader::MainDllLoader() : dll_(NULL) {\n}\n\nMainDllLoader::~MainDllLoader() {\n#ifdef PURIFY\n \/\/ We should never unload the dll. There is only risk and no gain from\n \/\/ doing so. The singleton dtors have been already run by AtExitManager.\n ::FreeLibrary(dll_);\n#endif\n}\n\n\/\/ Loading chrome is an interesting afair. First we try loading from the current\n\/\/ directory to support run-what-you-compile and other development scenarios.\n\/\/ If that fails then we look at the 'CHROME_VERSION' env variable to determine\n\/\/ if we should stick with an older dll version even if a new one is available\n\/\/ to support upgrade-in-place scenarios, and if that fails we finally we look\n\/\/ at the registry which should point us to the latest version.\nHMODULE MainDllLoader::Load(std::wstring* version, std::wstring* file) {\n std::wstring dir(GetExecutablePath());\n *file = dir;\n HMODULE dll = LoadChromeWithDirectory(file);\n if (dll)\n return dll;\n\n scoped_ptr<base::Environment> env(base::Environment::Create());\n\n std::string version_value;\n if (!env->GetVar(WideToUTF8(\n BrowserDistribution::GetDistribution()->GetEnvVersionKey()).c_str(),\n &version_value)) {\n std::wstring reg_path(GetRegistryPath());\n\n *version = UTF8ToWide(version_value);\n \/\/ Look into the registry to find the latest version.\n if (!GetVersion(dir.c_str(), reg_path.c_str(), version))\n return NULL;\n }\n\n *file = dir;\n file->append(*version).append(L\"\\\\\");\n return LoadChromeWithDirectory(file);\n}\n\n\/\/ Launching is a matter of loading the right dll, setting the CHROME_VERSION\n\/\/ environment variable and just calling the entry point. Derived classes can\n\/\/ add custom code in the OnBeforeLaunch callback.\nint MainDllLoader::Launch(HINSTANCE instance,\n sandbox::SandboxInterfaceInfo* sbox_info) {\n std::wstring version;\n std::wstring file;\n dll_ = Load(&version, &file);\n if (!dll_)\n return ResultCodes::MISSING_DATA;\n\n scoped_ptr<base::Environment> env(base::Environment::Create());\n env->SetVar(WideToUTF8(\n BrowserDistribution::GetDistribution()->GetEnvVersionKey()).c_str(),\n WideToUTF8(version));\n\n InitCrashReporterWithDllPath(file);\n OnBeforeLaunch(version);\n\n DLL_MAIN entry_point =\n reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, \"ChromeMain\"));\n if (!entry_point)\n return ResultCodes::BAD_PROCESS_TYPE;\n\n int rc = entry_point(instance, sbox_info, ::GetCommandLineW());\n return OnBeforeExit(rc);\n}\n\nvoid MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {\n RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =\n reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(\n ::GetProcAddress(dll_,\n \"RelaunchChromeBrowserWithNewCommandLineIfNeeded\"));\n if (!relaunch_function) {\n LOG(ERROR) << \"Could not find exported function \"\n << \"RelaunchChromeBrowserWithNewCommandLineIfNeeded\";\n } else {\n relaunch_function();\n }\n}\n\n\/\/=============================================================================\n\nclass ChromeDllLoader : public MainDllLoader {\n public:\n virtual std::wstring GetRegistryPath() {\n std::wstring key(google_update::kRegPathClients);\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n key.append(L\"\\\\\").append(dist->GetAppGuid());\n return key;\n }\n\n virtual void OnBeforeLaunch(const std::wstring& version) {\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n RecordDidRun(dist->GetAppGuid().c_str());\n }\n\n virtual int OnBeforeExit(int return_code) {\n \/\/ NORMAL_EXIT_CANCEL is used for experiments when the user cancels\n \/\/ so we need to reset the did_run signal so omaha does not count\n \/\/ this run as active usage.\n if (ResultCodes::NORMAL_EXIT_CANCEL == return_code) {\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n ClearDidRun(dist->GetAppGuid().c_str());\n }\n return return_code;\n }\n};\n\n\/\/=============================================================================\n\nclass ChromiumDllLoader : public MainDllLoader {\n public:\n virtual std::wstring GetRegistryPath() {\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n return dist->GetVersionKey();\n }\n};\n\nMainDllLoader* MakeMainDllLoader() {\n#if defined(GOOGLE_CHROME_BUILD)\n return new ChromeDllLoader();\n#else\n return new ChromiumDllLoader();\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>File missing from previous recommit.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"sncc_disparitywise_calculator.h\"\n\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <iostream>\n#include <omp.h>\n\n#include \"disparitywise_calculator.h\"\n\nsncc_disparitywise_calculator::sncc_disparitywise_calculator(const cv::Mat& pbase, const cv::Mat& pmatch)\n{\n\tlong long start = cv::getCPUTickCount();\n\tcv::Size box_size(3,3);\n\n\tcv::Mat_<float> base_float_org;\n\tpbase.convertTo(base_float_org, CV_32F);\n\tcv::copyMakeBorder(base_float_org, base_float, 1,1,1,1, cv::BORDER_DEFAULT);\n\tcv::Mat base_square;\n\tcv::pow(base_float_org, 2, base_square);\n\tcv::boxFilter(base_float_org, mu_base, -1, box_size);\n\tcv::Mat mu_base_sq;\n\tcv::pow(mu_base, 2, mu_base_sq);\n\tcv::Mat sq_base_box;\n\tcv::boxFilter(base_square, sq_base_box, -1, box_size);\n\tcv::sqrt(sq_base_box - mu_base_sq, sigma_base_inv);\n\tcv::pow(sigma_base_inv, -1, sigma_base_inv);\n\n\tcv::Mat match_float_org;\n\tpmatch.convertTo(match_float_org, CV_32F);\n\tcv::copyMakeBorder(match_float_org, match_float, 1,1,1,1, cv::BORDER_DEFAULT);\n\tcv::Mat match_square;\n\tcv::pow(match_float_org, 2, match_square);\n\tcv::boxFilter(match_float_org, mu_match, -1, box_size);\n\tcv::Mat mu_match_sq;\n\tcv::pow(mu_match, 2, mu_match_sq);\n\tcv::Mat sq_match_box;\n\tcv::boxFilter(match_square, sq_match_box, -1, box_size);\n\tcv::sqrt(sq_match_box - mu_match_sq, sigma_match_inv);\n\tcv::pow(sigma_match_inv, -1, sigma_match_inv);\n\n\tint threads = omp_get_max_threads();\n\t\/\/int threads = 1;\n\tfor(int i = 0; i < threads; ++i)\n\t\ttemp.emplace_back(base_float.size());\n\n\tstd::cout << \"init: \" << cv::getCPUTickCount() - start << std::endl;\n}\n\nvoid preparation_kernel(float* temp, const float* base, const float* match, int cols, int rows, int row_stride)\n{\n\tfor(int y = 0; y < rows; ++y)\n\t{\n\t\tconst float* base_d_ptr = base + y*row_stride;\n\t\tconst float* match_d_ptr = match + y*row_stride;\n\t\tfor(int x = 0; x < cols; ++x)\n\t\t\t*temp++ = *base_d_ptr++ * *match_d_ptr++;\n\t}\n}\n\nvoid sncc_kernel(float* result, const float* temp, const float* mu_base, const float* mu_match, const float* sigma_base_inv, const float* sigma_match_inv, int rows, int cols, int row_stride)\n{\n\tconst float norm_factor = 1.0\/9.0f;\n\tfloat* result_ptr = result;\n\n\tstd::vector<float> box_temp(cols);\n\tstd::vector<float> boxcol_temp(cols+2);\n\tfor(int y = 0; y < rows; ++y)\n\t{\n\t\tconst float *temp_1 = temp + (y+0)*(cols+2);\n\t\tconst float *temp_2 = temp + (y+1)*(cols+2);\n\t\tconst float *temp_3 = temp + (y+2)*(cols+2);\n\t\tfor(int x = 0; x < cols; ++x)\n\t\t{\n\t\t\tboxcol_temp[x] = *temp_1++ + *temp_2++ + *temp_3++;\n\t\t}\n\n\t\t\/*for(int x = 0; x < cols; ++x)\n\t\t{\n\t\t\tfloat sum = 0.0f;\n\t\t\tfor(int dy = 0; dy < 3; ++dy)\n\t\t\t{\n\t\t\t\tconst float *temp_ptr = temp + (y+dy)*(cols+2)+x;\n\t\t\t\tfor(int dx = 0; dx < 3; ++dx)\n\t\t\t\t\tsum += *temp_ptr++;\n\t\t\t}\n\t\t\tsum *= norm_factor;\n\t\t\tbox_temp[x] = sum;\n\t\t}*\/\n\t\tconst float* boxcol_temp_ptr = boxcol_temp.data();\n\t\tfor(int x = 0; x < cols; ++x)\n\t\t{\n\t\t\tfloat sum = 0.0f;\n\t\t\t\/*for(int dy = 0; dy < 3; ++dy)\n\t\t\t{\n\t\t\t\tconst float *temp_ptr = temp + (y+dy)*(cols+2)+x;\n\t\t\t\tfor(int dx = 0; dx < 3; ++dx)\n\t\t\t\t\tsum += *temp_ptr++;\n\t\t\t}*\/\n\t\t\tfor(int dx = 0; dx < 3; ++dx)\n\t\t\t\tsum += *(boxcol_temp_ptr + dx);\n\t\t\tboxcol_temp_ptr++;\n\n\t\t\tsum *= norm_factor;\n\t\t\tbox_temp[x] = sum;\n\t\t}\n\n\t\tint y_offset = y*row_stride;\n\t\t\/\/float* result_ptr = result + y_offset;\n\t\tconst float* mu_base_ptr = mu_base + y_offset;\n\t\tconst float* mu_match_ptr = mu_match + y_offset;\n\t\tconst float* sigma_base_inv_ptr = sigma_base_inv + y_offset;\n\t\tconst float* sigma_match_inv_ptr = sigma_match_inv + y_offset;\n\t\tconst float *box_ptr = box_temp.data();\n\n\t\tfor(int x = 0; x < cols; ++x)\n\t\t{\n\t\t\t\/*float sum = 0.0f;\n\t\t\tfor(int dy = 0; dy < 3; ++dy)\n\t\t\t{\n\t\t\t\tconst float *temp_ptr = temp + (y+dy)*(cols+2)+x;\n\t\t\t\tfor(int dx = 0; dx < 3; ++dx)\n\t\t\t\t\tsum += *temp_ptr++;\n\t\t\t}\n\t\t\tsum *= norm_factor;*\/\n\n\t\t\t*result_ptr++ = 1.0f - (*box_ptr++ - *mu_base_ptr++ * *mu_match_ptr++) * *sigma_base_inv_ptr++ * *sigma_match_inv_ptr++;\n\t\t}\n\t}\n}\n\ncv::Mat_<float> sncc_disparitywise_calculator::operator()(int d)\n{\n\tconst int offset_base = calculate_base_offset(d);\n\tconst int offset_match = calculate_match_offset(d);\n\tconst int row_length = calculate_row_length(base_float, d) - 2;\n\tconst int rows = base_float.rows - 2;\n\n\t\/\/cv::Mat_<float> result = prepare_result(cv::Size(row_length, rows), d, 100.0f);\n\tcv::Mat_<float> result(cv::Size(row_length, rows), 100.0f);\n\n\tint thread_idx = omp_get_thread_num();\n\tpreparation_kernel(temp[thread_idx][0], base_float.ptr<float>() + offset_base, match_float.ptr<float>() + offset_match, row_length+2, rows+2, base_float.cols);\n\t\/\/sncc_kernel(result[0] + offset_base, temp[thread_idx][0], mu_base[0] + offset_base, mu_match[0] + offset_match, sigma_base_inv[0] + offset_base, sigma_match_inv[0] + offset_match, rows, row_length, base_float.cols - 2);\n\tsncc_kernel(result[0], temp[thread_idx][0], mu_base[0] + offset_base, mu_match[0] + offset_match, sigma_base_inv[0] + offset_base, sigma_match_inv[0] + offset_match, rows, row_length, base_float.cols - 2);\n\n\treturn result;\n}\n\n<commit_msg>performance opt of sncc<commit_after>#include \"sncc_disparitywise_calculator.h\"\n\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <iostream>\n#include <omp.h>\n\n#include \"disparitywise_calculator.h\"\n\nsncc_disparitywise_calculator::sncc_disparitywise_calculator(const cv::Mat& pbase, const cv::Mat& pmatch)\n{\n\tlong long start = cv::getCPUTickCount();\n\tcv::Size box_size(3,3);\n\n\tcv::Mat_<float> base_float_org;\n\tpbase.convertTo(base_float_org, CV_32F);\n\tcv::copyMakeBorder(base_float_org, base_float, 1,1,1,1, cv::BORDER_DEFAULT);\n\tcv::Mat base_square;\n\tcv::pow(base_float_org, 2, base_square);\n\tcv::boxFilter(base_float_org, mu_base, -1, box_size);\n\tcv::Mat mu_base_sq;\n\tcv::pow(mu_base, 2, mu_base_sq);\n\tcv::Mat sq_base_box;\n\tcv::boxFilter(base_square, sq_base_box, -1, box_size);\n\tcv::sqrt(sq_base_box - mu_base_sq, sigma_base_inv);\n\tcv::pow(sigma_base_inv, -1, sigma_base_inv);\n\n\tcv::Mat match_float_org;\n\tpmatch.convertTo(match_float_org, CV_32F);\n\tcv::copyMakeBorder(match_float_org, match_float, 1,1,1,1, cv::BORDER_DEFAULT);\n\tcv::Mat match_square;\n\tcv::pow(match_float_org, 2, match_square);\n\tcv::boxFilter(match_float_org, mu_match, -1, box_size);\n\tcv::Mat mu_match_sq;\n\tcv::pow(mu_match, 2, mu_match_sq);\n\tcv::Mat sq_match_box;\n\tcv::boxFilter(match_square, sq_match_box, -1, box_size);\n\tcv::sqrt(sq_match_box - mu_match_sq, sigma_match_inv);\n\tcv::pow(sigma_match_inv, -1, sigma_match_inv);\n\n\tint threads = omp_get_max_threads();\n\t\/\/int threads = 1;\n\tfor(int i = 0; i < threads; ++i)\n\t\ttemp.emplace_back(base_float.size());\n\n\tstd::cout << \"init: \" << cv::getCPUTickCount() - start << std::endl;\n}\n\nvoid preparation_kernel(float* temp, const float* base, const float* match, int cols, int rows, int row_stride)\n{\n\tfor(int y = 0; y < rows; ++y)\n\t{\n\t\tconst float* base_d_ptr = base + y*row_stride;\n\t\tconst float* match_d_ptr = match + y*row_stride;\n\t\tfor(int x = 0; x < cols; ++x)\n\t\t\t*temp++ = *base_d_ptr++ * *match_d_ptr++;\n\t}\n}\n\ninline void prepare_line(float *temp, const float* base, const float* match, int cols)\n{\n\tfor(int x = 0; x < cols; ++x)\n\t\t*temp++ = *base++ * *match++;\n}\n\nvoid sncc_kernel(float* result, const float* mu_base, const float* mu_match, const float* sigma_base_inv, const float* sigma_match_inv, int rows, int cols, int row_stride, const float* base, const float *match)\n{\n\tconst float norm_factor = 1.0\/9.0f;\n\tfloat* result_ptr = result;\n\n\tstd::vector<std::vector<float>> coltemp(3, std::vector<float>(cols+2));\n\t\/\/std::array<std::vector<float>,3> coltemp(std::vector<float>(cols+2));\n\tfor(int i = 0; i < 2; ++i)\n\t\tprepare_line(coltemp[i].data(), base + i*(row_stride+2), match + i*(row_stride+2), cols+2);\n\tint replace_idx = 2;\n\n\tstd::vector<float> box_temp(cols);\n\tstd::vector<float> boxcol_temp(cols+2);\n\tfor(int y = 0; y < rows; ++y)\n\t{\n\t\tprepare_line(coltemp[replace_idx].data(), base+(y+2)*(row_stride+2), match+(y+2)*(row_stride+2), cols+2);\n\t\treplace_idx = (replace_idx+1) %3;\n\n\t\tconst float *temp_1 = coltemp[0].data();\n\t\tconst float *temp_2 = coltemp[1].data();\n\t\tconst float *temp_3 = coltemp[2].data();\n\n\t\tfor(int x = 0; x < cols+2; ++x)\n\t\t{\n\t\t\tboxcol_temp[x] = *temp_1++ + *temp_2++ + *temp_3++;\n\t\t}\n\n\t\tconst float* boxcol_temp_ptr = boxcol_temp.data();\n\t\tfor(int x = 0; x < cols; ++x)\n\t\t{\n\t\t\tfloat sum = 0.0f;\n\t\t\tfor(int dx = 0; dx < 3; ++dx)\n\t\t\t\tsum += *(boxcol_temp_ptr + dx);\n\t\t\tboxcol_temp_ptr++;\n\n\t\t\tsum *= norm_factor;\n\t\t\tbox_temp[x] = sum;\n\t\t}\n\n\t\tint y_offset = y*row_stride;\n\t\tconst float* mu_base_ptr = mu_base + y_offset;\n\t\tconst float* mu_match_ptr = mu_match + y_offset;\n\t\tconst float* sigma_base_inv_ptr = sigma_base_inv + y_offset;\n\t\tconst float* sigma_match_inv_ptr = sigma_match_inv + y_offset;\n\t\tconst float *box_ptr = box_temp.data();\n\n\t\tfor(int x = 0; x < cols; ++x)\n\t\t{\n\t\t\t*result_ptr++ = 1.0f - (*box_ptr++ - *mu_base_ptr++ * *mu_match_ptr++) * *sigma_base_inv_ptr++ * *sigma_match_inv_ptr++;\n\t\t}\n\t}\n}\n\ncv::Mat_<float> sncc_disparitywise_calculator::operator()(int d)\n{\n\tconst int offset_base = calculate_base_offset(d);\n\tconst int offset_match = calculate_match_offset(d);\n\tconst int row_length = calculate_row_length(base_float, d) - 2;\n\tconst int rows = base_float.rows - 2;\n\n\t\/\/cv::Mat_<float> result = prepare_result(cv::Size(row_length, rows), d, 100.0f);\n\tcv::Mat_<float> result(cv::Size(row_length, rows), 100.0f);\n\n\tint thread_idx = omp_get_thread_num();\n\t\/\/preparation_kernel(temp[thread_idx][0], base_float.ptr<float>() + offset_base, match_float.ptr<float>() + offset_match, row_length+2, rows+2, base_float.cols);\n\t\/\/sncc_kernel(result[0] + offset_base, temp[thread_idx][0], mu_base[0] + offset_base, mu_match[0] + offset_match, sigma_base_inv[0] + offset_base, sigma_match_inv[0] + offset_match, rows, row_length, base_float.cols - 2);\n\t\/\/sncc_kernel(result[0], temp[thread_idx][0], mu_base[0] + offset_base, mu_match[0] + offset_match, sigma_base_inv[0] + offset_base, sigma_match_inv[0] + offset_match, rows, row_length, base_float.cols - 2);\n\tsncc_kernel(result[0], mu_base[0] + offset_base, mu_match[0] + offset_match, sigma_base_inv[0] + offset_base, sigma_match_inv[0] + offset_match, rows, row_length, base_float.cols - 2, base_float.ptr<float>() + offset_base, match_float.ptr<float>() + offset_match);\n\n\treturn result;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Provide initialization of member variable<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"addscientist.h\"\n#include \"ui_addscientist.h\"\n#include \"scientist.h\"\n#include \"listservices.h\"\n#include <string>\n#include <cstdlib>\n\nusing namespace std;\n\naddScientist::addScientist(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::addScientist)\n{\n ui->setupUi(this);\n ui ->genderSelectBox ->addItem(\"Gender\");\n ui ->genderSelectBox ->addItem(\"---\");\n ui ->genderSelectBox ->addItem(\"Male\");\n ui ->genderSelectBox ->addItem(\"Female\");\n ui ->genderSelectBox ->addItem(\"Other\");\n\n}\n\naddScientist::~addScientist()\n{\n delete ui;\n}\n\n\nvoid addScientist::on_addScientistButton_clicked()\n{\n \/\/this boolean is true only when the entry is fully legal\n bool isLegalScientist = false;\n\n \/\/set all errors to empty every time the button is clicked.\n ui ->birthYearLabel ->setText(\"\");\n ui ->deathYearLabel ->setText(\"\");\n ui ->firstNameLabel ->setText(\"\");\n ui ->lastNameLabel ->setText(\"\");\n ui ->genderLabel ->setText(\"\");\n ui ->nationalityLabel ->setText(\"\");\n\n \/\/this runs if no required fields are empty.\n\n bool hasFirstName = getFirstName();\n bool hasLastName = getLastName();\n bool hasGender = getGender();\n bool hasNationality = getNationality();\n bool hasBirthYear; getBirthYear();\n bool hasDeathYear; \/\/ = _deathYear = (ui -> deathYearBox -> text()).toInt();\n bool hasAwardYear; \/\/ =_awardYear =(ui ->turingAwardBox -> text()).toInt();\n\n \/\/if it's all legal, add the scientist to the database. Maybe open a little popup.\n\n if(isLegalScientist)\n {\n Scientist newScientist(0, _firstName, _lastName, 'm', _nationality, _birthYear, _deathYear, _awardYear);\n _connection.addScientistToDatabase(newScientist);\n }\n\n}\n\n\/\/NOT NEEDED!!\nbool addScientist::checkForEmpty()\n{\n bool hasContent = true;\n if((ui ->firstNameBox->text()).isEmpty())\n {\n ui -> firstNameLabel ->setText(\"<span style='color: red'>First name required<\/span>\");\n hasContent = false;\n }\n if((ui ->lastNameBox->text()).isEmpty())\n {\n ui -> lastNameLabel ->setText(\"<span style='color: red'>Last name required<\/span>\");\n hasContent = false;\n }\n if((ui ->nationalityBox->text()).isEmpty())\n {\n ui -> nationalityLabel ->setText(\"<span style='color: red'>Nationality required<\/span>\");\n hasContent = false;\n }\n if((ui ->birthYearBox ->text()).isEmpty())\n {\n ui ->birthYearLabel ->setText(\"<span style='color: red'>Birth year required<\/span>\");\n hasContent = false;\n }\n if(ui->genderSelectBox ->currentText() == \"Gender\" || ui->genderSelectBox ->currentText() == \"---\")\n {\n ui ->genderLabel ->setText(\"<span style='color: red'>Gender required<\/span>\");\n hasContent = false;\n }\n \/\/hasContent is true if and only if all required fields have entries.\n return hasContent;\n}\n\nbool addScientist::getGender()\n{\n if(ui->genderLabel->selectedText() == \"Male\")\n {\n _gender = 'm';\n return true;\n }\n else if(ui ->genderLabel->selectedText() == \"Female\")\n {\n _gender = 'f';\n return true;\n }\n else if(ui ->genderLabel ->selectedText() == \"Other\")\n {\n _gender = 'o';\n return true;\n }\n else\n {\n ui -> genderLabel ->setText(\"<span style=' color: red'>Gender required<\/span>\");\n return false;\n }\n}\n\n\/\/The integer this function returns indicates whether the name is legal, and if not, what the problem is.\nbool addScientist::getFirstName()\n{\n\n string potentialName = ui ->firstNameBox ->text().toStdString();\n\n bool hasOnlyChar = true;\n bool hasContent = true;\n\n \/\/Checks that there is something in the field\n if((ui ->firstNameBox->text()).isEmpty())\n {\n hasContent = false;\n }\n\n \/\/check that it has only characters\n for(unsigned int i = 0; i < potentialName.size(); i++)\n {\n if(isalpha(potentialName[i]))\n {\n \/\/do nothing\n }\n else\n {\n hasOnlyChar = false;\n }\n }\n\n \/\/Throws errors if any are needed\n if(!hasContent)\n {\n ui ->firstNameLabel ->setText(\"<span style='color: red'>First name required<\/span>\");\n\n }\n else if(!hasOnlyChar)\n {\n ui ->firstNameLabel ->setText(\"<span style='color: red'>Name can only contain latin characters<\/span>\");\n }\n else if(potentialName.size() < 3 || potentialName.size() > 16)\n {\n ui -> firstNameLabel ->setText(\"<span style=' color: red'>Name must be between 2 and 16 characters<\/span>\");\n }\n else\n {\n \/\/If there are no problems, the first name is legal.\n _firstName = potentialName;\n }\n\n return (hasContent && hasOnlyChar && !(potentialName.size() < 3 || potentialName.size() > 16));\n}\n\nbool addScientist::getLastName()\n{\n\n string potentialName = ui ->lastNameBox ->text().toStdString();\n\n bool hasOnlyChar = true;\n bool hasContent = true;\n\n \/\/Checks that there is something in the field\n if((ui ->lastNameBox->text()).isEmpty())\n {\n hasContent = false;\n }\n\n \/\/check that it has only characters\n for(unsigned int i = 0; i < potentialName.size(); i++)\n {\n if(isalpha(potentialName[i]))\n {\n \/\/do nothing\n }\n else\n {\n hasOnlyChar = false;\n }\n }\n\n \/\/Throws errors if any are needed\n if(!hasContent)\n {\n ui ->lastNameLabel ->setText(\"<span style='color: red'>Last name required<\/span>\");\n }\n else if(!hasOnlyChar)\n {\n ui ->lastNameLabel ->setText(\"<span style='color: red'>Name can only contain latin characters<\/span>\");\n }\n else if(potentialName.size() < 3 || potentialName.size() > 16)\n {\n ui -> lastNameLabel ->setText(\"<span style=' color: red'>Name must be between 2 and 16 characters<\/span>\");\n }\n else\n {\n \/\/If there are no problems, the last name is legal.\n _lastName = potentialName;\n }\n\n return (hasContent && hasOnlyChar && !(potentialName.size() < 3 || potentialName.size() > 16));\n}\n\nbool addScientist::getNationality()\n{\n\n string potentialNationality = ui ->nationalityBox ->text().toStdString();\n\n bool hasOnlyChar = true;\n bool hasContent = true;\n\n \/\/Checks that there is something in the field\n if((ui ->nationalityBox->text()).isEmpty())\n {\n hasContent = false;\n }\n\n \/\/check that it has only characters\n for(unsigned int i = 0; i < potentialNationality.size(); i++)\n {\n if(isalpha(potentialNationality[i]))\n {\n \/\/do nothing\n }\n else\n {\n hasOnlyChar = false;\n }\n }\n\n \/\/Throws errors if any are needed\n if(!hasContent)\n {\n ui ->nationalityLabel ->setText(\"<span style='color: red'>Nationality required<\/span>\");\n\n }\n else if(!hasOnlyChar)\n {\n ui ->nationalityLabel ->setText(\"<span style='color: red'>Nationality can only contain latin characters<\/span>\");\n }\n else if(potentialNationality.size() < 5 || potentialNationality.size() > 21)\n {\n ui ->nationalityLabel ->setText(\"<span style=' color: red'>Nationality be between 4 and 20 characters<\/span>\");\n }\n else\n {\n \/\/If there are no problems, the first name is legal.\n _nationality = potentialNationality;\n }\n\n return (hasContent && hasOnlyChar && !(potentialNationality.size() < 5 || potentialNationality.size() > 21));\n}\n\nbool addScientist::getBirthYear()\n{\n int potentialBirthYear = ui ->birthYearBox ->text().toInt();\n string potentialBirthYearString =(ui ->birthYearBox ->text()).toStdString();\n\n bool hasContent = true;\n bool hasOnlyNumbers = true;\n bool isInRange = true;\n\n \/\/Checks that there is something in the field\n if((ui ->birthYearBox->text()).isEmpty())\n {\n hasContent = false;\n }\n\n \/\/checks that it has only numbers\n for(unsigned int i = 0; i < potentialBirthYearString.size();i++)\n {\n if(!isdigit(potentialBirthYearString[0]))\n {\n hasOnlyNumbers = false;\n }\n }\n\n \/\/checks that it is in range\n if(potentialBirthYear <1791 || potentialBirthYear > 2016)\n {\n isInRange = false;\n }\n\n \/\/throws errors when necessary\n if(!hasContent)\n {\n ui ->birthYearLabel ->setText(\"<span style='color: red'>Birth year required<\/span>\");\n\n }\n else if(!hasOnlyNumbers)\n {\n ui ->birthYearLabel ->setText(\"<span style='color: red'>Birth year can only contain numbers<\/span>\");\n }\n else if(!isInRange)\n {\n ui ->birthYearLabel ->setText(\"<span style=' color: red'>No computer scientists born in this year <\/span>\");\n }\n else\n {\n \/\/If there are no problems, the birth year is legal.\n _birthYear = potentialBirthYear;\n }\n\n\n return(hasContent && hasOnlyNumbers && isInRange);\n\n}\n\nbool addScientist::getDeathYear()\n{\n int potentialDeathYear = ui ->deathYearBox ->text().toInt();\n string potentialDeathYearString =(ui ->deathYearBox ->text()).toStdString();\n\n bool hasOnlyNumbers = true;\n bool isInRange = true;\n\n \/\/Checks that there is something in the field\n if((ui ->deathYearBox->text()).isEmpty())\n {\n _deathYear = 0;\n return true;\n }\n\n \/\/checks that it has only numbers\n for(unsigned int i = 0; i < potentialDeathYearString.size();i++)\n {\n if(!isdigit(potentialDeathYearString[0]))\n {\n hasOnlyNumbers = false;\n }\n }\n \/\/checks that it is in range\n if(potentialDeathYear <_birthYear || potentialDeathYear > 2016)\n {\n isInRange = false;\n }\n\n \/\/throws errors when necessary\n\n if(!hasOnlyNumbers)\n {\n ui ->deathYearLabel ->setText(\"<span style='color: red'>Death year can only contain numbers<\/span>\");\n }\n else if(!isInRange)\n {\n ui ->deathYearLabel ->setText(\"<span style=' color: red'>Not legal death year<\/span>\");\n }\n else\n {\n \/\/If there are no problems, the birth year is legal.\n _deathYear = potentialDeathYear;\n }\n\n return(hasOnlyNumbers && isInRange);\n\n}\n<commit_msg>add checks and all that<commit_after>#include \"addscientist.h\"\n#include \"ui_addscientist.h\"\n#include \"scientist.h\"\n#include \"listservices.h\"\n#include <string>\n#include <cstdlib>\n\nusing namespace std;\n\naddScientist::addScientist(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::addScientist)\n{\n ui->setupUi(this);\n ui ->genderSelectBox ->addItem(\"Gender\");\n ui ->genderSelectBox ->addItem(\"---\");\n ui ->genderSelectBox ->addItem(\"Male\");\n ui ->genderSelectBox ->addItem(\"Female\");\n ui ->genderSelectBox ->addItem(\"Other\");\n\n}\n\naddScientist::~addScientist()\n{\n delete ui;\n}\n\n\nvoid addScientist::on_addScientistButton_clicked()\n{\n \/\/this boolean is true only when the entry is fully legal\n bool isLegalScientist = false;\n\n \/\/set all errors to empty every time the button is clicked.\n ui ->birthYearLabel ->setText(\"\");\n ui ->deathYearLabel ->setText(\"\");\n ui ->firstNameLabel ->setText(\"\");\n ui ->lastNameLabel ->setText(\"\");\n ui ->genderLabel ->setText(\"\");\n ui ->nationalityLabel ->setText(\"\");\n\n \/\/this runs if no required fields are empty.\n\n bool hasFirstName = getFirstName();\n bool hasLastName = getLastName();\n bool hasGender = getGender();\n bool hasNationality = getNationality();\n bool hasBirthYear = getBirthYear();\n bool hasDeathYear = getDeathYear();\n bool hasAwardYear; \/\/ =_awardYear =(ui ->turingAwardBox -> text()).toInt();\n\n \/\/if it's all legal, add the scientist to the database. Maybe open a little popup.\n\n\n\n isLegalScientist = (hasFirstName && hasLastName && hasGender && hasNationality && hasBirthYear);\n\n\n if(isLegalScientist)\n {\n Scientist newScientist(0, _firstName, _lastName, 'm', _nationality, _birthYear, _deathYear, _awardYear);\n _connection.addScientistToDatabase(newScientist);\n\n ui -> firstNameLabel -> setText(\"GREAT SUCCESS\");\n }\n\n}\n\n\/\/NOT NEEDED!!\nbool addScientist::checkForEmpty()\n{\n bool hasContent = true;\n if((ui ->firstNameBox->text()).isEmpty())\n {\n ui -> firstNameLabel ->setText(\"<span style='color: red'>First name required<\/span>\");\n hasContent = false;\n }\n if((ui ->lastNameBox->text()).isEmpty())\n {\n ui -> lastNameLabel ->setText(\"<span style='color: red'>Last name required<\/span>\");\n hasContent = false;\n }\n if((ui ->nationalityBox->text()).isEmpty())\n {\n ui -> nationalityLabel ->setText(\"<span style='color: red'>Nationality required<\/span>\");\n hasContent = false;\n }\n if((ui ->birthYearBox ->text()).isEmpty())\n {\n ui ->birthYearLabel ->setText(\"<span style='color: red'>Birth year required<\/span>\");\n hasContent = false;\n }\n if(ui->genderSelectBox ->currentIndex() == 0 || ui->genderSelectBox ->currentIndex() == 1)\n {\n ui ->genderLabel ->setText(\"<span style='color: red'>Gender required<\/span>\");\n hasContent = false;\n }\n \/\/hasContent is true if and only if all required fields have entries.\n return hasContent;\n}\n\nbool addScientist::getGender()\n{\n if((ui->genderSelectBox->currentIndex()) == 2)\n {\n _gender = 'm';\n return true;\n }\n else if((ui ->genderSelectBox->currentIndex()) == 3)\n {\n _gender = 'f';\n return true;\n }\n else if((ui ->genderSelectBox ->currentIndex()) == 4)\n {\n _gender = 'o';\n return true;\n }\n else\n {\n ui -> genderLabel ->setText(\"<span style=' color: red'>Gender required<\/span>\");\n return false;\n }\n}\n\n\/\/The integer this function returns indicates whether the name is legal, and if not, what the problem is.\nbool addScientist::getFirstName()\n{\n\n string potentialName = ui ->firstNameBox ->text().toStdString();\n\n bool hasOnlyChar = true;\n bool hasContent = true;\n\n \/\/Checks that there is something in the field\n if((ui ->firstNameBox->text()).isEmpty())\n {\n hasContent = false;\n }\n\n \/\/check that it has only characters\n for(unsigned int i = 0; i < potentialName.size(); i++)\n {\n if(isalpha(potentialName[i]))\n {\n \/\/do nothing\n }\n else\n {\n hasOnlyChar = false;\n }\n }\n\n \/\/Throws errors if any are needed\n if(!hasContent)\n {\n ui ->firstNameLabel ->setText(\"<span style='color: red'>First name required<\/span>\");\n\n }\n else if(!hasOnlyChar)\n {\n ui ->firstNameLabel ->setText(\"<span style='color: red'>Name can only contain latin characters<\/span>\");\n }\n else if(potentialName.size() < 3 || potentialName.size() > 16)\n {\n ui -> firstNameLabel ->setText(\"<span style=' color: red'>Name must be between 2 and 16 characters<\/span>\");\n }\n else\n {\n \/\/If there are no problems, the first name is legal.\n _firstName = potentialName;\n }\n\n return (hasContent && hasOnlyChar && !(potentialName.size() < 3 || potentialName.size() > 16));\n}\n\nbool addScientist::getLastName()\n{\n\n string potentialName = ui ->lastNameBox ->text().toStdString();\n\n bool hasOnlyChar = true;\n bool hasContent = true;\n\n \/\/Checks that there is something in the field\n if((ui ->lastNameBox->text()).isEmpty())\n {\n hasContent = false;\n }\n\n \/\/check that it has only characters\n for(unsigned int i = 0; i < potentialName.size(); i++)\n {\n if(isalpha(potentialName[i]))\n {\n \/\/do nothing\n }\n else\n {\n hasOnlyChar = false;\n }\n }\n\n \/\/Throws errors if any are needed\n if(!hasContent)\n {\n ui ->lastNameLabel ->setText(\"<span style='color: red'>Last name required<\/span>\");\n }\n else if(!hasOnlyChar)\n {\n ui ->lastNameLabel ->setText(\"<span style='color: red'>Name can only contain latin characters<\/span>\");\n }\n else if(potentialName.size() < 3 || potentialName.size() > 16)\n {\n ui -> lastNameLabel ->setText(\"<span style=' color: red'>Name must be between 2 and 16 characters<\/span>\");\n }\n else\n {\n \/\/If there are no problems, the last name is legal.\n _lastName = potentialName;\n }\n\n return (hasContent && hasOnlyChar && !(potentialName.size() < 3 || potentialName.size() > 16));\n}\n\nbool addScientist::getNationality()\n{\n\n string potentialNationality = ui ->nationalityBox ->text().toStdString();\n\n bool hasOnlyChar = true;\n bool hasContent = true;\n\n \/\/Checks that there is something in the field\n if((ui ->nationalityBox->text()).isEmpty())\n {\n hasContent = false;\n }\n\n \/\/check that it has only characters\n for(unsigned int i = 0; i < potentialNationality.size(); i++)\n {\n if(isalpha(potentialNationality[i]))\n {\n \/\/do nothing\n }\n else\n {\n hasOnlyChar = false;\n }\n }\n\n \/\/Throws errors if any are needed\n if(!hasContent)\n {\n ui ->nationalityLabel ->setText(\"<span style='color: red'>Nationality required<\/span>\");\n\n }\n else if(!hasOnlyChar)\n {\n ui ->nationalityLabel ->setText(\"<span style='color: red'>Nationality can only contain latin characters<\/span>\");\n }\n else if(potentialNationality.size() < 5 || potentialNationality.size() > 21)\n {\n ui ->nationalityLabel ->setText(\"<span style=' color: red'>Nationality be between 4 and 20 characters<\/span>\");\n }\n else\n {\n \/\/If there are no problems, the first name is legal.\n _nationality = potentialNationality;\n }\n\n return (hasContent && hasOnlyChar && !(potentialNationality.size() < 5 || potentialNationality.size() > 21));\n}\n\nbool addScientist::getBirthYear()\n{\n int potentialBirthYear = ui ->birthYearBox ->text().toInt();\n string potentialBirthYearString =(ui ->birthYearBox ->text()).toStdString();\n\n bool hasContent = true;\n bool hasOnlyNumbers = true;\n bool isInRange = true;\n\n \/\/Checks that there is something in the field\n if((ui ->birthYearBox->text()).isEmpty())\n {\n hasContent = false;\n }\n\n \/\/checks that it has only numbers\n for(unsigned int i = 0; i < potentialBirthYearString.size();i++)\n {\n if(!isdigit(potentialBirthYearString[0]))\n {\n hasOnlyNumbers = false;\n }\n }\n\n \/\/checks that it is in range\n if(potentialBirthYear <1791 || potentialBirthYear > 2016)\n {\n isInRange = false;\n }\n\n \/\/throws errors when necessary\n if(!hasContent)\n {\n ui ->birthYearLabel ->setText(\"<span style='color: red'>Birth year required<\/span>\");\n\n }\n else if(!hasOnlyNumbers)\n {\n ui ->birthYearLabel ->setText(\"<span style='color: red'>Birth year can only contain numbers<\/span>\");\n }\n else if(!isInRange)\n {\n ui ->birthYearLabel ->setText(\"<span style=' color: red'>No computer scientists born in this year <\/span>\");\n }\n else\n {\n \/\/If there are no problems, the birth year is legal.\n _birthYear = potentialBirthYear;\n }\n\n\n return(hasContent && hasOnlyNumbers && isInRange);\n\n}\n\nbool addScientist::getDeathYear()\n{\n int potentialDeathYear = ui ->deathYearBox ->text().toInt();\n string potentialDeathYearString =(ui ->deathYearBox ->text()).toStdString();\n\n bool hasOnlyNumbers = true;\n bool isInRange = true;\n\n \/\/Checks that there is something in the field\n if((ui ->deathYearBox->text()).isEmpty())\n {\n _deathYear = 0;\n return true;\n }\n\n \/\/checks that it has only numbers\n for(unsigned int i = 0; i < potentialDeathYearString.size();i++)\n {\n if(!isdigit(potentialDeathYearString[0]))\n {\n hasOnlyNumbers = false;\n }\n }\n \/\/checks that it is in range\n if(potentialDeathYear <_birthYear || potentialDeathYear > 2016)\n {\n isInRange = false;\n }\n\n \/\/throws errors when necessary\n\n if(!hasOnlyNumbers)\n {\n ui ->deathYearLabel ->setText(\"<span style='color: red'>Death year can only contain numbers<\/span>\");\n }\n else if(!isInRange)\n {\n ui ->deathYearLabel ->setText(\"<span style=' color: red'>Not legal death year<\/span>\");\n }\n else\n {\n \/\/If there are no problems, the birth year is legal.\n _deathYear = potentialDeathYear;\n }\n\n return(hasOnlyNumbers && isInRange);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\/**************************************************************************\n * This file is property of and copyright by the ALICE HLT Project *\n * ALICE Experiment at CERN, All rights reserved. *\n * *\n * Primary Authors: Artur Szostak <artursz@iafrica.com> *\n * for The ALICE HLT Project. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/\/ @file AliHLTTrigger.h\n\/\/\/ @author Artur Szostak <artursz@iafrica.com>\n\/\/\/ @date 12 Aug 2008\n\/\/\/ @brief Implementation of the AliHLTTrigger base component class.\n\/\/\/\n\/\/\/ The AliHLTTrigger class is the base class from which all HLT trigger components\n\/\/\/ should be derived.\n\n#include \"AliHLTTrigger.h\"\n#include \"AliHLTTriggerDecision.h\"\n#include \"AliHLTReadoutList.h\"\n#include \"AliHLTTriggerDomain.h\"\n#include \"AliHLTDomainEntry.h\"\n#include \"AliHLTCTPData.h\"\n\nClassImp(AliHLTTrigger)\n\n\nAliHLTTrigger::AliHLTTrigger() :\n\tAliHLTProcessor(),\n\tfEventData(NULL),\n\tfTriggerData(NULL),\n\tfDecisionMade(false),\n\tfClearInfo(true),\n\tfTriggerEventResult(0),\n\tfDescription(),\n\tfReadoutList(),\n\tfTriggerDomain()\n{\n \/\/ Default constructor sets pointers to NULL.\n}\n\n\nAliHLTTrigger::~AliHLTTrigger()\n{\n \/\/ Default destructor.\n}\n\n\nvoid AliHLTTrigger::GetInputDataTypes(AliHLTComponentDataTypeList& list) const\n{\n \/\/ Returns the kAliHLTAnyDataType type as input.\n list.push_back(kAliHLTAnyDataType);\n}\n\n\nvoid AliHLTTrigger::GetOutputDataTypes(AliHLTComponentDataTypeList& list) const\n{\n \/\/ Returns the kAliHLTDataTypeTriggerDecision type as output.\n list.push_back(kAliHLTDataTypeTriggerDecision);\n}\n\n\nvoid AliHLTTrigger::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)\n{\n \/\/ Returns output data size estimate.\n \/\/ See header file for more details.\n\n \/\/ Matthias 2009-07-03 this is presumably to small as the streamed object might be\n \/\/ bigger. This is actually the case in root v5-24-00\n \/\/ Just take 2x the size of the object\n constBase = 2*sizeof(AliHLTTriggerDecision);\n inputMultiplier = 1;\n}\n\n\nint AliHLTTrigger::DoEvent(const AliHLTComponentEventData& evtData, AliHLTComponentTriggerData& trigData)\n{\n \/\/ Sets the pointers to the evtData and trigData, then calls the DoTrigger to\n \/\/ execute the actual trigger algorithm.\n\n fEventData = &evtData;\n fTriggerData = &trigData;\n fDecisionMade = false;\n fTriggerEventResult = 0;\n \/\/ Reset the description, readout list and trigger domain used by TriggerEvent\n \/\/ if requested to do so.\n if (fClearInfo)\n {\n fDescription = \"\";\n fReadoutList.Clear();\n fTriggerDomain.Clear();\n }\n \n int result = DoTrigger();\n if (result != 0) return result;\n \n \/\/ Fill in a default decision of false if none was made.\n if (not fDecisionMade)\n {\n TriggerEvent(false);\n }\n\n \/\/ Cleanup\n fEventData = NULL;\n fTriggerData = NULL;\n return fTriggerEventResult;\n}\n\n\nint AliHLTTrigger::TriggerEvent(bool value)\n{\n \/\/ Sets the trigger decision for the current event.\n \/\/ See header file for more details.\n \n if (fTriggerEventResult != 0) return fTriggerEventResult; \/\/ Do not do anything if a previous call failed.\n AliHLTTriggerDecision triggerResult(value, GetTriggerName(), fTriggerDomain, fDescription);\n \/\/ Append the readout list if it contains anything.\n triggerResult.TriggerDomain().Add(fReadoutList);\n return TriggerEvent(&triggerResult, kAliHLTDataTypeTObject|kAliHLTDataOriginOut);\n}\n\n\nint AliHLTTrigger::TriggerEvent(\n AliHLTTriggerDecision* result, const AliHLTComponentDataType& type,\n AliHLTUInt32_t spec\n )\n{\n \/\/ Sets a custom trigger decision for the current event.\n \/\/ See header file for more details.\n \n AliHLTReadoutList readoutlist = result->ReadoutList();\n \/\/ mask the readout list according to the CTP trigger\n \/\/ if the classes have been initialized (mask non-zero)\n if (CTPData() != NULL and CTPData()->Mask() != 0x0) {\n AliHLTEventDDL eventDDL = CTPData()->ReadoutList(*GetTriggerData());\n AliHLTReadoutList ctpreadout(eventDDL);\n ctpreadout.Enable(AliHLTReadoutList::kHLT);\n readoutlist.AndEq(ctpreadout);\n result->ReadoutList(readoutlist); \/\/ override the readout list with the masked one.\n }\n \n if (fTriggerEventResult != 0) return fTriggerEventResult; \/\/ Do not do anything if a previous call failed.\n fTriggerEventResult = PushBack(result, type, spec);\n if (fTriggerEventResult == 0) {\n fTriggerEventResult = PushBack(readoutlist.Buffer(), readoutlist.BufferSize(), kAliHLTDataTypeReadoutList);\n }\n \n if (fTriggerEventResult == 0) fDecisionMade = true;\n return fTriggerEventResult;\n}\n\n\nvoid AliHLTTrigger::GetInputDataTypes(AliHLTComponentDataTypeList& list)\n{\n \/\/ Calls the const version of this method.\n \n \/\/ Assign to const temporary variable to make sure we call the constant version\n \/\/ of the GetOutputDataTypes method.\n const AliHLTTrigger* t = this;\n t->GetInputDataTypes(list);\n}\n\n\nint AliHLTTrigger::GetOutputDataTypes(AliHLTComponentDataTypeList& list)\n{\n \/\/ Calls the const version of this method.\n \n \/\/ Assign to const temporary variable to make sure we call the constant version\n \/\/ of the GetOutputDataTypes method.\n const AliHLTTrigger* t = this;\n t->GetOutputDataTypes(list);\n list.push_back(kAliHLTDataTypeReadoutList);\n return list.size();\n}\n\nint AliHLTTrigger::CreateEventDoneReadoutFilter(const AliHLTTriggerDomain& domain, unsigned type)\n{\n \/\/ add a readout filter to the EventDoneData\n int iResult=0;\n unsigned nofEntries=0;\n switch (type) {\n \/* readout filter *\/\n case 3:\n \/* monitoring filter *\/\n case 4:\n nofEntries=domain.GetNofEntries();\n break;\n \/* monitoring event command *\/\n case 5:\n break;\n default:\n HLTError(\"unknown event done data command code 0x%08x\", type);\n return -EINVAL;\n }\n\n \/\/ we need:\n \/\/ 1 word for the filter command: readout filter, monitoring filter, monitoring event\n \/\/ 1 word for the readout filter size\n \/\/ 4*n words for the filter list\n if ((iResult=ReserveEventDoneData((nofEntries*4 + 2) * sizeof(AliHLTUInt32_t)))<0) return iResult;\n AliHLTUInt32_t eddbuffer[4];\n\n \/\/ add the specific command\n eddbuffer[0]=type;\n if ((iResult=PushEventDoneData(eddbuffer[0]))<0) return iResult;\n\n \/\/ find the valid entries\n unsigned block=0;\n vector<const AliHLTDomainEntry*> entries;\n for (block=0; block<nofEntries; block++) {\n \/\/ skip all DAQ readout entries as they are handled by the readout list\n \/\/ 2009-12-03: this turned out to cause a bug, since all blocks with data type\n \/\/ id 'any' will also match this condition. In fact, it is not necessary to\n \/\/ filter the entries, disable this condition. Code can be cleaned up later\n \/\/ if this schema has been established and tested\n \/\/ https:\/\/savannah.cern.ch\/bugs\/index.php?60082\n \/\/if (domain[block]==AliHLTDomainEntry(kAliHLTDataTypeDAQRDOUT)) continue;\n if (domain[block].Exclusive()) {\n \/\/ 2009-12-03 comment out that warning for the moment\n \/\/ there are suddenly exclusive entries in the list\n \/\/ https:\/\/savannah.cern.ch\/bugs\/index.php?60083\n \/\/HLTWarning(\"exclusive trigger domain entries are currently not handled, skipping entry %s\", domain[block].AsString().Data());\n continue;\n }\n entries.push_back(&(domain[block]));\n }\n\n \/\/ add the number of blocks if not monitoring event command\n if (type!=5) {\n eddbuffer[0]=entries.size();\n if ((iResult=PushEventDoneData(eddbuffer[0]))<0) return iResult;\n }\n\n for (vector<const AliHLTDomainEntry*>::iterator entry=entries.begin();\n entry!=entries.end(); entry++) {\n (*entry)->AsBinary(eddbuffer);\n for (int n=0; n<4; n++)\n if ((iResult=PushEventDoneData(eddbuffer[n]))<0) return iResult;\n }\n return iResult;\n}\n<commit_msg>Improving handling of error state.<commit_after>\/\/ $Id$\n\/**************************************************************************\n * This file is property of and copyright by the ALICE HLT Project *\n * ALICE Experiment at CERN, All rights reserved. *\n * *\n * Primary Authors: Artur Szostak <artursz@iafrica.com> *\n * for The ALICE HLT Project. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/\/ @file AliHLTTrigger.h\n\/\/\/ @author Artur Szostak <artursz@iafrica.com>\n\/\/\/ @date 12 Aug 2008\n\/\/\/ @brief Implementation of the AliHLTTrigger base component class.\n\/\/\/\n\/\/\/ The AliHLTTrigger class is the base class from which all HLT trigger components\n\/\/\/ should be derived.\n\n#include \"AliHLTTrigger.h\"\n#include \"AliHLTTriggerDecision.h\"\n#include \"AliHLTReadoutList.h\"\n#include \"AliHLTTriggerDomain.h\"\n#include \"AliHLTDomainEntry.h\"\n#include \"AliHLTCTPData.h\"\n\nClassImp(AliHLTTrigger)\n\n\nAliHLTTrigger::AliHLTTrigger() :\n\tAliHLTProcessor(),\n\tfEventData(NULL),\n\tfTriggerData(NULL),\n\tfDecisionMade(false),\n\tfClearInfo(true),\n\tfTriggerEventResult(0),\n\tfDescription(),\n\tfReadoutList(),\n\tfTriggerDomain()\n{\n \/\/ Default constructor sets pointers to NULL.\n}\n\n\nAliHLTTrigger::~AliHLTTrigger()\n{\n \/\/ Default destructor.\n}\n\n\nvoid AliHLTTrigger::GetInputDataTypes(AliHLTComponentDataTypeList& list) const\n{\n \/\/ Returns the kAliHLTAnyDataType type as input.\n list.push_back(kAliHLTAnyDataType);\n}\n\n\nvoid AliHLTTrigger::GetOutputDataTypes(AliHLTComponentDataTypeList& list) const\n{\n \/\/ Returns the kAliHLTDataTypeTriggerDecision type as output.\n list.push_back(kAliHLTDataTypeTriggerDecision);\n}\n\n\nvoid AliHLTTrigger::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)\n{\n \/\/ Returns output data size estimate.\n \/\/ See header file for more details.\n\n \/\/ Matthias 2009-07-03 this is presumably to small as the streamed object might be\n \/\/ bigger. This is actually the case in root v5-24-00\n \/\/ Just take 2x the size of the object\n constBase = 2*sizeof(AliHLTTriggerDecision);\n inputMultiplier = 1;\n}\n\n\nint AliHLTTrigger::DoEvent(const AliHLTComponentEventData& evtData, AliHLTComponentTriggerData& trigData)\n{\n \/\/ Sets the pointers to the evtData and trigData, then calls the DoTrigger to\n \/\/ execute the actual trigger algorithm.\n\n fEventData = &evtData;\n fTriggerData = &trigData;\n fDecisionMade = false;\n fTriggerEventResult = 0;\n \/\/ Reset the description, readout list and trigger domain used by TriggerEvent\n \/\/ if requested to do so.\n if (fClearInfo)\n {\n fDescription = \"\";\n fReadoutList.Clear();\n fTriggerDomain.Clear();\n }\n \n int result = DoTrigger();\n if (result != 0) return result;\n \n \/\/ Fill in a default decision of false if none was made.\n if (not fDecisionMade)\n {\n TriggerEvent(false);\n }\n\n \/\/ Cleanup\n fEventData = NULL;\n fTriggerData = NULL;\n return fTriggerEventResult;\n}\n\n\nint AliHLTTrigger::TriggerEvent(bool value)\n{\n \/\/ Sets the trigger decision for the current event.\n \/\/ See header file for more details.\n \n if (fTriggerEventResult != 0) return fTriggerEventResult; \/\/ Do not do anything if a previous call failed.\n AliHLTTriggerDecision triggerResult(value, GetTriggerName(), fTriggerDomain, fDescription);\n \/\/ Append the readout list if it contains anything.\n triggerResult.TriggerDomain().Add(fReadoutList);\n return TriggerEvent(&triggerResult, kAliHLTDataTypeTObject|kAliHLTDataOriginOut);\n}\n\n\nint AliHLTTrigger::TriggerEvent(\n AliHLTTriggerDecision* result, const AliHLTComponentDataType& type,\n AliHLTUInt32_t spec\n )\n{\n \/\/ Sets a custom trigger decision for the current event.\n \/\/ See header file for more details.\n \n if (fTriggerEventResult != 0) return fTriggerEventResult; \/\/ Do not do anything if a previous call failed.\n \n AliHLTReadoutList readoutlist = result->ReadoutList();\n \/\/ mask the readout list according to the CTP trigger\n \/\/ if the classes have been initialized (mask non-zero)\n if (CTPData() != NULL and CTPData()->Mask() != 0x0) {\n AliHLTEventDDL eventDDL = CTPData()->ReadoutList(*GetTriggerData());\n AliHLTReadoutList ctpreadout(eventDDL);\n ctpreadout.Enable(AliHLTReadoutList::kHLT);\n readoutlist.AndEq(ctpreadout);\n result->ReadoutList(readoutlist); \/\/ override the readout list with the masked one.\n }\n \n fTriggerEventResult = PushBack(result, type, spec);\n if (fTriggerEventResult == 0) {\n fTriggerEventResult = PushBack(readoutlist.Buffer(), readoutlist.BufferSize(), kAliHLTDataTypeReadoutList);\n }\n \n if (fTriggerEventResult == 0) fDecisionMade = true;\n return fTriggerEventResult;\n}\n\n\nvoid AliHLTTrigger::GetInputDataTypes(AliHLTComponentDataTypeList& list)\n{\n \/\/ Calls the const version of this method.\n \n \/\/ Assign to const temporary variable to make sure we call the constant version\n \/\/ of the GetOutputDataTypes method.\n const AliHLTTrigger* t = this;\n t->GetInputDataTypes(list);\n}\n\n\nint AliHLTTrigger::GetOutputDataTypes(AliHLTComponentDataTypeList& list)\n{\n \/\/ Calls the const version of this method.\n \n \/\/ Assign to const temporary variable to make sure we call the constant version\n \/\/ of the GetOutputDataTypes method.\n const AliHLTTrigger* t = this;\n t->GetOutputDataTypes(list);\n list.push_back(kAliHLTDataTypeReadoutList);\n return list.size();\n}\n\nint AliHLTTrigger::CreateEventDoneReadoutFilter(const AliHLTTriggerDomain& domain, unsigned type)\n{\n \/\/ add a readout filter to the EventDoneData\n int iResult=0;\n unsigned nofEntries=0;\n switch (type) {\n \/* readout filter *\/\n case 3:\n \/* monitoring filter *\/\n case 4:\n nofEntries=domain.GetNofEntries();\n break;\n \/* monitoring event command *\/\n case 5:\n break;\n default:\n HLTError(\"unknown event done data command code 0x%08x\", type);\n return -EINVAL;\n }\n\n \/\/ we need:\n \/\/ 1 word for the filter command: readout filter, monitoring filter, monitoring event\n \/\/ 1 word for the readout filter size\n \/\/ 4*n words for the filter list\n if ((iResult=ReserveEventDoneData((nofEntries*4 + 2) * sizeof(AliHLTUInt32_t)))<0) return iResult;\n AliHLTUInt32_t eddbuffer[4];\n\n \/\/ add the specific command\n eddbuffer[0]=type;\n if ((iResult=PushEventDoneData(eddbuffer[0]))<0) return iResult;\n\n \/\/ find the valid entries\n unsigned block=0;\n vector<const AliHLTDomainEntry*> entries;\n for (block=0; block<nofEntries; block++) {\n \/\/ skip all DAQ readout entries as they are handled by the readout list\n \/\/ 2009-12-03: this turned out to cause a bug, since all blocks with data type\n \/\/ id 'any' will also match this condition. In fact, it is not necessary to\n \/\/ filter the entries, disable this condition. Code can be cleaned up later\n \/\/ if this schema has been established and tested\n \/\/ https:\/\/savannah.cern.ch\/bugs\/index.php?60082\n \/\/if (domain[block]==AliHLTDomainEntry(kAliHLTDataTypeDAQRDOUT)) continue;\n if (domain[block].Exclusive()) {\n \/\/ 2009-12-03 comment out that warning for the moment\n \/\/ there are suddenly exclusive entries in the list\n \/\/ https:\/\/savannah.cern.ch\/bugs\/index.php?60083\n \/\/HLTWarning(\"exclusive trigger domain entries are currently not handled, skipping entry %s\", domain[block].AsString().Data());\n continue;\n }\n entries.push_back(&(domain[block]));\n }\n\n \/\/ add the number of blocks if not monitoring event command\n if (type!=5) {\n eddbuffer[0]=entries.size();\n if ((iResult=PushEventDoneData(eddbuffer[0]))<0) return iResult;\n }\n\n for (vector<const AliHLTDomainEntry*>::iterator entry=entries.begin();\n entry!=entries.end(); entry++) {\n (*entry)->AsBinary(eddbuffer);\n for (int n=0; n<4; n++)\n if ((iResult=PushEventDoneData(eddbuffer[n]))<0) return iResult;\n }\n return iResult;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the HamFramework for Siv3D.\n\/\/\n\/\/\tCopyright (C) 2014-2016 Hamukun\n\/\/\tCopyright (C) 2014-2016 Ryo Suzuki\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# pragma once\n\/\/# include \"..\/Siv3D.hpp\"\n# include <Siv3D.hpp>\n\nnamespace ham\n{\n\tenum class TransitionState\n\t{\n\t\tNone,\n\t\tFadeIn,\n\t\tActive,\n\t\tFadeOut,\n\t\tFadeInOut,\n\t};\n\n\ttemplate<class State, class Data> class LayerManager;\n\n\ttemplate<class State, class Data> \n\tclass LayerBase : public std::enable_shared_from_this<LayerBase<State, Data>>, s3d::Uncopyable\n\t{\n\tpublic:\t\n\n\t\tusing Manager_t = LayerManager<State, Data>;\n\n\t\tusing State_t = State;\n\n\t\tusing Data_t = Data;\n\n\t\tvirtual ~LayerBase() = default;\n\n\t\tvoid setData(Manager_t* pManager, const std::shared_ptr<Data>& data)\n\t\t{\n\t\t\tm_manager = pManager;\n\n\t\t\tm_data = data;\n\t\t}\n\n\t\tvoid setTransitionValue(int transitionTimeMillisec)\n\t\t{\n\t\t\tm_transitionTimeMillisec = transitionTimeMillisec;\n\n\t\t\tm_transitionState = TransitionState::FadeIn;\n\n\t\t\tm_stopwatch.restart();\n\t\t}\n\n\t\ts3d::Stopwatch& getStopwatch()\n\t\t{\n\t\t\treturn m_stopwatch;\n\t\t}\n\n\t\tint32 getTransitionTimeMillisec() const\n\t\t{\n\t\t\treturn m_transitionTimeMillisec;\n\t\t}\n\n\t\tvoid setTransitionState(const TransitionState& transitionState)\n\t\t{\n\t\t\tm_transitionState = transitionState;\n\t\t}\n\n\t\tconst TransitionState& getTransitionState() const\n\t\t{\n\t\t\treturn m_transitionState;\n\t\t}\n\n\t\tbool isDestroyed() const\n\t\t{\n\t\t\treturn m_isDestroyed;\n\t\t}\n\n\t\tvoid setDestroyed(bool isDestroyed)\n\t\t{\n\t\t\tm_isDestroyed = isDestroyed;\n\t\t}\n\n\t\tvirtual void init() {}\n\n\t\tvirtual bool input() { return false; }\n\n\t\tvirtual bool inputFadeIn(double) { return false; }\n\n\t\tvirtual bool inputFadeOut(double) { return false; }\n\n\t\tvirtual void updateFadeIn(double) {}\n\n\t\tvirtual void update() = 0;\n\n\t\tvirtual void updateFadeOut(double) {}\n\n\t\tvirtual void draw() const = 0;\n\n\t\tvirtual void drawFadeIn(double) const\n\t\t{\n\t\t\tdraw();\n\t\t}\n\n\t\tvirtual void drawFadeOut(double) const \n\t\t{\n\t\t\tdraw();\n\t\t}\n\n\tprotected:\n\n\t\tstd::shared_ptr<Data> m_data;\n\n\t\tbool pushLayer(const State& state, int transitionTimeMillisec = 200)\n\t\t{\n\t\t\treturn m_manager->pushLayer(state, transitionTimeMillisec);\n\t\t}\n\n\t\tbool popThisLayer()\n\t\t{\n\t\t\treturn m_manager->popLayer(shared_from_this());\n\t\t}\n\n\tprivate:\n\n\t\tManager_t* m_manager = nullptr;\n\n\t\ts3d::Stopwatch m_stopwatch;\n\n\t\tint32 m_transitionTimeMillisec = 0;\n\n\t\tTransitionState m_transitionState = TransitionState::None;\n\n\t\tbool m_isDestroyed = false;\n\t};\n\n\ttemplate<class State, class Data> class LayerManager\n\t{\n\tprivate:\n\n\t\tusing Layer_t = std::shared_ptr<LayerBase<State, Data>>;\n\n\t\tusing FactoryFunction_t = std::function<Layer_t()>;\n\n\t\tstd::unordered_map<State, FactoryFunction_t> m_factories;\n\n\t\tstd::shared_ptr<Data> m_data;\n\n\t\tArray<Layer_t> m_layers;\n\n\t\tArray<Layer_t> m_tLayers;\n\n\t\ts3d::Optional<State> m_first;\n\n\t\tbool m_error = false;\n\n\t\ttemplate<class Type>\n\t\tstd::shared_ptr<Type> MakeShared() const\n\t\t{\n\t\t\treturn std::make_shared<Data>();\n\t\t}\n\n\t\ttemplate<>\n\t\tstd::shared_ptr<void> MakeShared() const\n\t\t{\n\t\t\treturn std::shared_ptr<void>(nullptr);\n\t\t}\n\n\tpublic:\n\n\t\tusing Layer = LayerBase<State, Data>;\n\n\t\tLayerManager()\n\t\t\t: m_data(MakeShared<Data>())\n\t\t{\n\n\t\t}\n\n\t\tLayerManager(const std::shared_ptr<Data>& data)\n\t\t\t: m_data(data)\n\t\t{\n\n\t\t}\n\n\t\ttemplate<class Layer> bool add(const State& state)\n\t\t{\n\t\t\tif (m_factories.find(state) != m_factories.end())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tm_factories.emplace(state, [&]()\n\t\t\t{\n\t\t\t\tauto m = std::make_shared<Layer>();\n\n\t\t\t\tm->setData(this, m_data);\n\n\t\t\t\treturn m;\n\t\t\t});\n\n\t\t\tif (!m_first)\n\t\t\t{\n\t\t\t\tm_first = state;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool init(const State& state)\n\t\t{\n\t\t\tif (m_layers.size() != 0)\n\t\t\t{\n\t\t\t\tm_layers.clear();\n\t\t\t}\n\n\t\t\tauto it = m_factories.find(state);\n\n\t\t\tif (it == m_factories.end())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tauto newLayer = it->second();\n\n\t\t\tnewLayer->init();\n\n\t\t\tm_layers.push_back(newLayer);\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool input()\n\t\t{\n\t\t\tfor (auto i = m_layers.rbegin(); i != m_layers.rend(); ++i)\n\t\t\t{\n\t\t\t\tauto& layer = *i;\n\n\t\t\t\tconst auto state = layer->getTransitionState();\n\n\t\t\t\tif (state == TransitionState::FadeIn || state == TransitionState::Active)\n\t\t\t\t{\n\t\t\t\t\tif (layer->input())\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\n\t\t\t}\n\n\t\t\tif (m_tLayers.size() > 0)\n\t\t\t{\n\t\t\t\tm_layers.insert(m_layers.end(), m_tLayers.begin(), m_tLayers.end());\n\n\t\t\t\tm_tLayers.clear();\n\t\t\t}\t\t\t\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool update()\n\t\t{\n\t\t\tif (m_layers.size() == 0 && !init(m_first.value()))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfor (auto& layer : m_layers)\n\t\t\t{\n\t\t\t\tconst int32 elapsed = layer->getStopwatch().ms();\n\n\t\t\t\tswitch (layer->getTransitionState())\n\t\t\t\t{\n\t\t\t\tcase TransitionState::FadeIn:\n\t\t\t\t\tlayer->updateFadeIn(static_cast<double>(elapsed) \/ layer->getTransitionTimeMillisec());\n\t\t\t\t\tif (elapsed > layer->getTransitionTimeMillisec())\n\t\t\t\t\t{\n\t\t\t\t\t\tlayer->getStopwatch().reset();\n\t\t\t\t\t\tlayer->setTransitionState(TransitionState::Active);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TransitionState::Active:\n\t\t\t\t\tlayer->update();\n\t\t\t\t\tbreak;\n\t\t\t\tcase TransitionState::FadeOut:\n\t\t\t\t\tlayer->updateFadeOut(static_cast<double>(elapsed) \/ layer->getTransitionTimeMillisec());\n\t\t\t\t\tif (elapsed > layer->getTransitionTimeMillisec())\n\t\t\t\t\t{\n\t\t\t\t\t\tlayer->setDestroyed(true);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tErase_if(m_layers, [&](const Layer_t& layer)\n\t\t\t{\n\t\t\t\treturn layer->isDestroyed();\n\t\t\t});\n\n\t\t\tif (m_tLayers.size() > 0)\n\t\t\t{\n\t\t\t\tm_layers.insert(m_layers.end(), m_tLayers.begin(), m_tLayers.end());\n\n\t\t\t\tm_tLayers.clear();\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid draw() const\n\t\t{\n\t\t\tfor (const auto& layer : m_layers)\n\t\t\t{\n\t\t\t\tconst int32 elapsed = layer->getStopwatch().ms();\n\n\t\t\t\tswitch (layer->getTransitionState())\n\t\t\t\t{\n\t\t\t\tcase TransitionState::FadeIn:\n\t\t\t\t\tlayer->drawFadeIn(static_cast<double>(elapsed) \/ layer->getTransitionTimeMillisec());\n\t\t\t\t\tbreak;\n\t\t\t\tcase TransitionState::Active:\n\t\t\t\t\tlayer->draw();\n\t\t\t\t\tbreak;\n\t\t\t\tcase TransitionState::FadeOut:\n\t\t\t\t\tlayer->drawFadeOut(static_cast<double>(elapsed) \/ layer->getTransitionTimeMillisec());\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbool inputAndUpdateAndDraw()\n\t\t{\n\t\t\tif (!input())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!update())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tdraw();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tstd::shared_ptr<Data> get()\n\t\t{\n\t\t\treturn m_data;\n\t\t}\n\n\t\tbool pushLayer(const State& state, int transitionTimeMillisec = 200)\n\t\t{\n\t\t\tif (m_factories.find(state) == m_factories.end())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tauto newLayer = m_factories[state]();\n\n\t\t\tnewLayer->setTransitionValue(transitionTimeMillisec);\n\n\t\t\tm_tLayers.push_back(newLayer);\n\n\t\t\tnewLayer->init();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool popLayer(const std::shared_ptr<Layer>& layer)\n\t\t{\n\t\t\tauto it = std::find(m_layers.begin(), m_layers.end(), layer);\n\n\t\t\tif (it == m_layers.end())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t(*it)->setTransitionState(TransitionState::FadeOut);\n\t\t\t(*it)->getStopwatch().restart();\n\n\t\t\treturn true;\n\t\t}\n\t};\n}\n<commit_msg>fix update draw = 0 to {}<commit_after>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the HamFramework for Siv3D.\n\/\/\n\/\/\tCopyright (C) 2014-2016 Hamukun\n\/\/\tCopyright (C) 2014-2016 Ryo Suzuki\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# pragma once\n\/\/# include \"..\/Siv3D.hpp\"\n# include <Siv3D.hpp>\n\nnamespace ham\n{\n\tenum class TransitionState\n\t{\n\t\tNone,\n\t\tFadeIn,\n\t\tActive,\n\t\tFadeOut,\n\t\tFadeInOut,\n\t};\n\n\ttemplate<class State, class Data> class LayerManager;\n\n\ttemplate<class State, class Data> \n\tclass LayerBase : public std::enable_shared_from_this<LayerBase<State, Data>>, s3d::Uncopyable\n\t{\n\tpublic:\t\n\n\t\tusing Manager_t = LayerManager<State, Data>;\n\n\t\tusing State_t = State;\n\n\t\tusing Data_t = Data;\n\n\t\tvirtual ~LayerBase() = default;\n\n\t\tvoid setData(Manager_t* pManager, const std::shared_ptr<Data>& data)\n\t\t{\n\t\t\tm_manager = pManager;\n\n\t\t\tm_data = data;\n\t\t}\n\n\t\tvoid setTransitionValue(int transitionTimeMillisec)\n\t\t{\n\t\t\tm_transitionTimeMillisec = transitionTimeMillisec;\n\n\t\t\tm_transitionState = TransitionState::FadeIn;\n\n\t\t\tm_stopwatch.restart();\n\t\t}\n\n\t\ts3d::Stopwatch& getStopwatch()\n\t\t{\n\t\t\treturn m_stopwatch;\n\t\t}\n\n\t\tint32 getTransitionTimeMillisec() const\n\t\t{\n\t\t\treturn m_transitionTimeMillisec;\n\t\t}\n\n\t\tvoid setTransitionState(const TransitionState& transitionState)\n\t\t{\n\t\t\tm_transitionState = transitionState;\n\t\t}\n\n\t\tconst TransitionState& getTransitionState() const\n\t\t{\n\t\t\treturn m_transitionState;\n\t\t}\n\n\t\tbool isDestroyed() const\n\t\t{\n\t\t\treturn m_isDestroyed;\n\t\t}\n\n\t\tvoid setDestroyed(bool isDestroyed)\n\t\t{\n\t\t\tm_isDestroyed = isDestroyed;\n\t\t}\n\n\t\tvirtual void init() {}\n\n\t\tvirtual bool input() { return false; }\n\n\t\tvirtual bool inputFadeIn(double) { return false; }\n\n\t\tvirtual bool inputFadeOut(double) { return false; }\n\n\t\tvirtual void updateFadeIn(double) {}\n\n\t\tvirtual void update() {};\n\n\t\tvirtual void updateFadeOut(double) {}\n\n\t\tvirtual void draw() const {};\n\n\t\tvirtual void drawFadeIn(double) const\n\t\t{\n\t\t\tdraw();\n\t\t}\n\n\t\tvirtual void drawFadeOut(double) const \n\t\t{\n\t\t\tdraw();\n\t\t}\n\n\tprotected:\n\n\t\tstd::shared_ptr<Data> m_data;\n\n\t\tbool pushLayer(const State& state, int transitionTimeMillisec = 200)\n\t\t{\n\t\t\treturn m_manager->pushLayer(state, transitionTimeMillisec);\n\t\t}\n\n\t\tbool popThisLayer()\n\t\t{\n\t\t\treturn m_manager->popLayer(shared_from_this());\n\t\t}\n\n\tprivate:\n\n\t\tManager_t* m_manager = nullptr;\n\n\t\ts3d::Stopwatch m_stopwatch;\n\n\t\tint32 m_transitionTimeMillisec = 0;\n\n\t\tTransitionState m_transitionState = TransitionState::None;\n\n\t\tbool m_isDestroyed = false;\n\t};\n\n\ttemplate<class State, class Data> class LayerManager\n\t{\n\tprivate:\n\n\t\tusing Layer_t = std::shared_ptr<LayerBase<State, Data>>;\n\n\t\tusing FactoryFunction_t = std::function<Layer_t()>;\n\n\t\tstd::unordered_map<State, FactoryFunction_t> m_factories;\n\n\t\tstd::shared_ptr<Data> m_data;\n\n\t\tArray<Layer_t> m_layers;\n\n\t\tArray<Layer_t> m_tLayers;\n\n\t\ts3d::Optional<State> m_first;\n\n\t\tbool m_error = false;\n\n\t\ttemplate<class Type>\n\t\tstd::shared_ptr<Type> MakeShared() const\n\t\t{\n\t\t\treturn std::make_shared<Data>();\n\t\t}\n\n\t\ttemplate<>\n\t\tstd::shared_ptr<void> MakeShared() const\n\t\t{\n\t\t\treturn std::shared_ptr<void>(nullptr);\n\t\t}\n\n\tpublic:\n\n\t\tusing Layer = LayerBase<State, Data>;\n\n\t\tLayerManager()\n\t\t\t: m_data(MakeShared<Data>())\n\t\t{\n\n\t\t}\n\n\t\tLayerManager(const std::shared_ptr<Data>& data)\n\t\t\t: m_data(data)\n\t\t{\n\n\t\t}\n\n\t\ttemplate<class Layer> bool add(const State& state)\n\t\t{\n\t\t\tif (m_factories.find(state) != m_factories.end())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tm_factories.emplace(state, [&]()\n\t\t\t{\n\t\t\t\tauto m = std::make_shared<Layer>();\n\n\t\t\t\tm->setData(this, m_data);\n\n\t\t\t\treturn m;\n\t\t\t});\n\n\t\t\tif (!m_first)\n\t\t\t{\n\t\t\t\tm_first = state;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool init(const State& state)\n\t\t{\n\t\t\tif (m_layers.size() != 0)\n\t\t\t{\n\t\t\t\tm_layers.clear();\n\t\t\t}\n\n\t\t\tauto it = m_factories.find(state);\n\n\t\t\tif (it == m_factories.end())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tauto newLayer = it->second();\n\n\t\t\tnewLayer->init();\n\n\t\t\tm_layers.push_back(newLayer);\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool input()\n\t\t{\n\t\t\tfor (auto i = m_layers.rbegin(); i != m_layers.rend(); ++i)\n\t\t\t{\n\t\t\t\tauto& layer = *i;\n\n\t\t\t\tconst auto state = layer->getTransitionState();\n\n\t\t\t\tif (state == TransitionState::FadeIn || state == TransitionState::Active)\n\t\t\t\t{\n\t\t\t\t\tif (layer->input())\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\n\t\t\t}\n\n\t\t\tif (m_tLayers.size() > 0)\n\t\t\t{\n\t\t\t\tm_layers.insert(m_layers.end(), m_tLayers.begin(), m_tLayers.end());\n\n\t\t\t\tm_tLayers.clear();\n\t\t\t}\t\t\t\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool update()\n\t\t{\n\t\t\tif (m_layers.size() == 0 && !init(m_first.value()))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfor (auto& layer : m_layers)\n\t\t\t{\n\t\t\t\tconst int32 elapsed = layer->getStopwatch().ms();\n\n\t\t\t\tswitch (layer->getTransitionState())\n\t\t\t\t{\n\t\t\t\tcase TransitionState::FadeIn:\n\t\t\t\t\tlayer->updateFadeIn(static_cast<double>(elapsed) \/ layer->getTransitionTimeMillisec());\n\t\t\t\t\tif (elapsed > layer->getTransitionTimeMillisec())\n\t\t\t\t\t{\n\t\t\t\t\t\tlayer->getStopwatch().reset();\n\t\t\t\t\t\tlayer->setTransitionState(TransitionState::Active);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TransitionState::Active:\n\t\t\t\t\tlayer->update();\n\t\t\t\t\tbreak;\n\t\t\t\tcase TransitionState::FadeOut:\n\t\t\t\t\tlayer->updateFadeOut(static_cast<double>(elapsed) \/ layer->getTransitionTimeMillisec());\n\t\t\t\t\tif (elapsed > layer->getTransitionTimeMillisec())\n\t\t\t\t\t{\n\t\t\t\t\t\tlayer->setDestroyed(true);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tErase_if(m_layers, [&](const Layer_t& layer)\n\t\t\t{\n\t\t\t\treturn layer->isDestroyed();\n\t\t\t});\n\n\t\t\tif (m_tLayers.size() > 0)\n\t\t\t{\n\t\t\t\tm_layers.insert(m_layers.end(), m_tLayers.begin(), m_tLayers.end());\n\n\t\t\t\tm_tLayers.clear();\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid draw() const\n\t\t{\n\t\t\tfor (const auto& layer : m_layers)\n\t\t\t{\n\t\t\t\tconst int32 elapsed = layer->getStopwatch().ms();\n\n\t\t\t\tswitch (layer->getTransitionState())\n\t\t\t\t{\n\t\t\t\tcase TransitionState::FadeIn:\n\t\t\t\t\tlayer->drawFadeIn(static_cast<double>(elapsed) \/ layer->getTransitionTimeMillisec());\n\t\t\t\t\tbreak;\n\t\t\t\tcase TransitionState::Active:\n\t\t\t\t\tlayer->draw();\n\t\t\t\t\tbreak;\n\t\t\t\tcase TransitionState::FadeOut:\n\t\t\t\t\tlayer->drawFadeOut(static_cast<double>(elapsed) \/ layer->getTransitionTimeMillisec());\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbool inputAndUpdateAndDraw()\n\t\t{\n\t\t\tif (!input())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!update())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tdraw();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tstd::shared_ptr<Data> get()\n\t\t{\n\t\t\treturn m_data;\n\t\t}\n\n\t\tbool pushLayer(const State& state, int transitionTimeMillisec = 200)\n\t\t{\n\t\t\tif (m_factories.find(state) == m_factories.end())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tauto newLayer = m_factories[state]();\n\n\t\t\tnewLayer->setTransitionValue(transitionTimeMillisec);\n\n\t\t\tm_tLayers.push_back(newLayer);\n\n\t\t\tnewLayer->init();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool popLayer(const std::shared_ptr<Layer>& layer)\n\t\t{\n\t\t\tauto it = std::find(m_layers.begin(), m_layers.end(), layer);\n\n\t\t\tif (it == m_layers.end())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t(*it)->setTransitionState(TransitionState::FadeOut);\n\t\t\t(*it)->getStopwatch().restart();\n\n\t\t\treturn true;\n\t\t}\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>#include <core\/mat4.h>\n#include \"core\/draw.h\"\n#include \"core\/random.h\"\n#include \"core\/shufflebag.h\"\n#include \"core\/mat4.h\"\n#include \"core\/axisangle.h\"\n#include \"core\/aabb.h\"\n#include \"core\/texturetypes.h\"\n#include \"core\/vfs.h\"\n#include \"core\/vfs_imagegenerator.h\"\n#include \"core\/vfs_path.h\"\n#include \"core\/os.h\"\n#include \"core\/range.h\"\n#include \"core\/camera.h\"\n#include \"core\/stringutils.h\"\n#include \"core\/stdutils.h\"\n#include \"core\/proto.h\"\n#include \"core\/log.h\"\n\n#include \"core\/path.h\"\n\n#include <render\/init.h>\n#include <render\/debuggl.h>\n#include <render\/materialshader.h>\n#include <render\/compiledmesh.h>\n#include <render\/texturecache.h>\n#include \"render\/shaderattribute3d.h\"\n#include \"render\/texture.h\"\n#include \"render\/world.h\"\n#include \"render\/viewport.h\"\n#include \"render\/materialshadercache.h\"\n#include \"render\/defaultfiles.h\"\n\n\n\n#include \"window\/imguilibrary.h\"\n#include \"window\/timer.h\"\n#include \"window\/imgui_ext.h\"\n#include \"window\/fpscontroller.h\"\n#include \"window\/sdllibrary.h\"\n#include \"window\/sdlwindow.h\"\n#include \"window\/sdlglcontext.h\"\n#include \"window\/filesystem.h\"\n#include \"window\/engine.h\"\n\n#include \"imgui\/imgui.h\"\n#include <SDL.h>\n#include <iostream>\n#include <memory>\n\n#include \"painter\/canvas.h\"\n\n\n#define IMGUI_DEFINE_MATH_OPERATORS\n#include \"imgui\/imgui_internal.h\"\n#include \"window\/imgui_ext.h\"\n\nLOG_SPECIFY_DEFAULT_LOGGER(\"painter\")\n\nint\nmain(int argc, char** argv)\n{\n Engine engine;\n\n if(engine.Setup() == false)\n {\n return -1;\n }\n\n\n int window_width = 1280;\n int window_height = 720;\n\n if(!engine.CreateWindow(\"Painter\", window_width, window_height, true))\n {\n return -1;\n }\n\n \/\/ ViewportHandler viewport_handler;\n \/\/ viewport_handler.SetSize(window_width, window_height);\n\n\n bool running = true;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ main loop\n CanvasConfig cc;\n Canvas canvas;\n BezierPath2 path (point2f(0,0));\n int index = -1;\n\n while(running)\n {\n SDL_Event e;\n while(SDL_PollEvent(&e) != 0)\n {\n engine.imgui->ProcessEvents(&e);\n\n if(engine.HandleResize(e, &window_width, &window_height))\n {\n \/\/ viewport_handler.SetSize(window_width, window_height);\n }\n\n switch(e.type)\n {\n case SDL_QUIT:\n running = false;\n break;\n default:\n \/\/ ignore other events\n break;\n }\n }\n\n engine.imgui->StartNewFrame();\n\n if(ImGui::BeginMainMenuBar())\n {\n if(ImGui::BeginMenu(\"File\"))\n {\n if(ImGui::MenuItem(\"Exit\", \"Ctrl+Q\"))\n {\n running = false;\n }\n ImGui::EndMenu();\n }\n }\n ImGui::EndMainMenuBar();\n\n ImGui::SetNextWindowSize(ImVec2{300, 300}, ImGuiCond_FirstUseEver);\n if(ImGui::Begin(\"painter\"))\n {\n \/\/ win->Run(&style_data);\n canvas.Begin(cc);\n canvas.ShowGrid(cc);\n\n if(ImGui::IsMouseReleased(0)) { index = -1; }\n auto handle = [&canvas, &index](const ImVec2& p, int id, float size)\n {\n ImDrawList* draw_list = ImGui::GetWindowDrawList();\n const auto sp = canvas.WorldToScreen(p);\n const auto me = ImGui::GetMousePos();\n const auto hover = vec2f::FromTo(C(me),C(sp)).GetLengthSquared() < size*size;\n if(index==-1 && hover && ImGui::IsMouseDown(0))\n {\n index = id;\n }\n const auto red = IM_COL32(hover || index==id ? 200 : 100, 0, 0, 255);\n draw_list->AddCircleFilled(sp, size, red);\n if(index==id)\n {\n \/\/ capture current drag item...\n if(ImGui::IsMouseDragging())\n {\n const auto d = ImGui::GetMouseDragDelta();\n ImGui::ResetMouseDragDelta();\n \/\/ todo: handle scale\/zoom\n return std::make_pair(true, vec2f(d.x, d.y));\n }\n }\n return std::make_pair(false, vec2f(0,0));\n };\n\n int i = 0;\n for(auto& p: path.points)\n {\n i += 1;\n auto r = handle(C(p), i, 10);\n if(r.first)\n {\n p += r.second;\n }\n }\n\n canvas.ShowRuler(cc);\n canvas.End(cc);\n }\n ImGui::End();\n\n \/\/ ImGui::ShowMetricsWindow();\n\n engine.init->ClearScreen(Color::Wheat);\n engine.imgui->Render();\n\n SDL_GL_SwapWindow(engine.window->window);\n }\n\n return 0;\n}\n\n<commit_msg>scaling is taken into acount when moving now<commit_after>#include <core\/mat4.h>\n#include \"core\/draw.h\"\n#include \"core\/random.h\"\n#include \"core\/shufflebag.h\"\n#include \"core\/mat4.h\"\n#include \"core\/axisangle.h\"\n#include \"core\/aabb.h\"\n#include \"core\/texturetypes.h\"\n#include \"core\/vfs.h\"\n#include \"core\/vfs_imagegenerator.h\"\n#include \"core\/vfs_path.h\"\n#include \"core\/os.h\"\n#include \"core\/range.h\"\n#include \"core\/camera.h\"\n#include \"core\/stringutils.h\"\n#include \"core\/stdutils.h\"\n#include \"core\/proto.h\"\n#include \"core\/log.h\"\n\n#include \"core\/path.h\"\n\n#include <render\/init.h>\n#include <render\/debuggl.h>\n#include <render\/materialshader.h>\n#include <render\/compiledmesh.h>\n#include <render\/texturecache.h>\n#include \"render\/shaderattribute3d.h\"\n#include \"render\/texture.h\"\n#include \"render\/world.h\"\n#include \"render\/viewport.h\"\n#include \"render\/materialshadercache.h\"\n#include \"render\/defaultfiles.h\"\n\n\n\n#include \"window\/imguilibrary.h\"\n#include \"window\/timer.h\"\n#include \"window\/imgui_ext.h\"\n#include \"window\/fpscontroller.h\"\n#include \"window\/sdllibrary.h\"\n#include \"window\/sdlwindow.h\"\n#include \"window\/sdlglcontext.h\"\n#include \"window\/filesystem.h\"\n#include \"window\/engine.h\"\n\n#include \"imgui\/imgui.h\"\n#include <SDL.h>\n#include <iostream>\n#include <memory>\n\n#include \"painter\/canvas.h\"\n\n\n#define IMGUI_DEFINE_MATH_OPERATORS\n#include \"imgui\/imgui_internal.h\"\n#include \"window\/imgui_ext.h\"\n\nLOG_SPECIFY_DEFAULT_LOGGER(\"painter\")\n\nint\nmain(int argc, char** argv)\n{\n Engine engine;\n\n if(engine.Setup() == false)\n {\n return -1;\n }\n\n\n int window_width = 1280;\n int window_height = 720;\n\n if(!engine.CreateWindow(\"Painter\", window_width, window_height, true))\n {\n return -1;\n }\n\n \/\/ ViewportHandler viewport_handler;\n \/\/ viewport_handler.SetSize(window_width, window_height);\n\n\n bool running = true;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ main loop\n CanvasConfig cc;\n Canvas canvas;\n BezierPath2 path (point2f(0,0));\n int index = -1;\n\n while(running)\n {\n SDL_Event e;\n while(SDL_PollEvent(&e) != 0)\n {\n engine.imgui->ProcessEvents(&e);\n\n if(engine.HandleResize(e, &window_width, &window_height))\n {\n \/\/ viewport_handler.SetSize(window_width, window_height);\n }\n\n switch(e.type)\n {\n case SDL_QUIT:\n running = false;\n break;\n default:\n \/\/ ignore other events\n break;\n }\n }\n\n engine.imgui->StartNewFrame();\n\n if(ImGui::BeginMainMenuBar())\n {\n if(ImGui::BeginMenu(\"File\"))\n {\n if(ImGui::MenuItem(\"Exit\", \"Ctrl+Q\"))\n {\n running = false;\n }\n ImGui::EndMenu();\n }\n }\n ImGui::EndMainMenuBar();\n\n ImGui::SetNextWindowSize(ImVec2{300, 300}, ImGuiCond_FirstUseEver);\n if(ImGui::Begin(\"painter\"))\n {\n \/\/ win->Run(&style_data);\n canvas.Begin(cc);\n canvas.ShowGrid(cc);\n\n if(ImGui::IsMouseReleased(0)) { index = -1; }\n auto handle = [&canvas, &index](const ImVec2& p, int id, ImU32 color)\n {\n const auto size = 5.0f;\n ImDrawList* draw_list = ImGui::GetWindowDrawList();\n const auto sp = canvas.WorldToScreen(p);\n const auto me = ImGui::GetMousePos();\n const auto hover = vec2f::FromTo(C(me),C(sp)).GetLengthSquared() < size*size;\n if(index==-1 && hover && ImGui::IsMouseDown(0))\n {\n index = id;\n }\n draw_list->AddCircleFilled(sp, size, color);\n if(index==id)\n {\n \/\/ capture current drag item...\n if(ImGui::IsMouseDragging())\n {\n const auto d = ImGui::GetMouseDragDelta();\n ImGui::ResetMouseDragDelta();\n \/\/ todo: handle scale\/zoom\n return std::make_pair(true, vec2f(d.x, d.y) \/ canvas.view.scale );\n }\n }\n return std::make_pair(false, vec2f(0,0));\n };\n\n int i = 0;\n for(auto& p: path.points)\n {\n i += 1;\n auto r = handle(C(p), i, IM_COL32(200, 100, 20, 200));\n if(r.first)\n {\n p += r.second;\n }\n }\n\n canvas.ShowRuler(cc);\n canvas.End(cc);\n }\n ImGui::End();\n\n \/\/ ImGui::ShowMetricsWindow();\n\n engine.init->ClearScreen(Color::Wheat);\n engine.imgui->Render();\n\n SDL_GL_SwapWindow(engine.window->window);\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/ Implemenatation of the K-Means Clustering Algorithm\n\/\/ See http:\/\/en.wikipedia.org\/wiki\/K-means_clustering and references therein.\n\/\/\n\/\/ This particular implementation is the so called Soft K-means algorithm.\n\/\/ It has been modified to work on the cylindrical topology in eta-phi space.\n\/\/\n\/\/ Author: Andreas Morsch (CERN)\n\/\/ andreas.morsch@cern.ch\n \n#include \"AliKMeansClustering.h\"\n#include <TMath.h>\n#include <TRandom.h>\n\nClassImp(AliKMeansClustering)\n\nDouble_t AliKMeansClustering::fBeta = 10.;\n \nvoid AliKMeansClustering::SoftKMeans(Int_t k, Int_t n, Double_t* x, Double_t* y, Double_t* mx, Double_t* my , Double_t* rk )\n{\n \/\/\n \/\/ The soft K-means algorithm\n \/\/\n Int_t i,j;\n \/\/\n \/\/ (1) Initialisation of the k means\n\n for (i = 0; i < k; i++) {\n\tmx[i] = 2. * TMath::Pi() * gRandom->Rndm();\n\tmy[i] = -1. + 2. * gRandom->Rndm();\n }\n\n \/\/\n \/\/ (2a) The responsibilities\n Double_t** r = new Double_t*[n]; \/\/ responsibilities\n for (j = 0; j < n; j++) {r[j] = new Double_t[k];}\n \/\/\n \/\/ (2b) Normalisation\n Double_t* nr = new Double_t[n];\n\n \/\/ (3) Iterations\n Int_t nit = 0;\n \n while(1) {\n\tnit++;\n \/\/\n \/\/ Assignment step\n \/\/\n for (j = 0; j < n; j++) {\n\tnr[j] = 0.;\n\tfor (i = 0; i < k; i++) {\n\t r[j][i] = TMath::Exp(- fBeta * d(mx[i], my[i], x[j], y[j]));\n\t nr[j] += r[j][i];\n\t} \/\/ mean i\n } \/\/ data point j\n\t\n for (j = 0; j < n; j++) {\n\tfor (i = 0; i < k; i++) {\n\t r[j][i] \/= nr[j];\n\t} \/\/ mean i\n } \/\/ data point j\n \n\t\/\/\n\t\/\/ Update step\n Double_t di = 0;\n \n for (i = 0; i < k; i++) {\n\t Double_t oldx = mx[i];\n\t Double_t oldy = my[i];\n\t \n\t mx[i] = x[0];\n\t my[i] = y[0];\n\t rk[i] = r[0][i];\n\t\n\tfor (j = 1; j < n; j++) {\n\t Double_t xx = x[j];\n\/\/\n\/\/ Here we have to take into acount the cylinder topology where phi is defined mod 2xpi\n\/\/ If two coordinates are separated by more than pi in phi one has to be shifted by +\/- 2 pi\n\n\t Double_t dx = mx[i] - x[j];\n\t if (dx > TMath::Pi()) xx += 2. * TMath::Pi();\n\t if (dx < -TMath::Pi()) xx -= 2. * TMath::Pi();\n\t mx[i] = mx[i] * rk[i] + r[j][i] * xx;\n\t my[i] = my[i] * rk[i] + r[j][i] * y[j];\n\t rk[i] += r[j][i];\n\t mx[i] \/= rk[i];\n\t my[i] \/= rk[i];\t \n\t if (mx[i] > 2. * TMath::Pi()) mx[i] -= 2. * TMath::Pi();\n\t if (mx[i] < 0. ) mx[i] += 2. * TMath::Pi();\n\t} \/\/ Data\n\tdi += d(mx[i], my[i], oldx, oldy);\n } \/\/ means \n\t\/\/\n\t\/\/ ending condition\n if (di < 1.e-8 || nit > 1000) break;\n } \/\/ while\n\n\/\/ Clean-up \n delete[] nr;\n for (j = 0; j < n; j++) delete[] r[j];\n delete[] r;\n}\n\nDouble_t AliKMeansClustering::d(Double_t mx, Double_t my, Double_t x, Double_t y)\n{\n \/\/\n \/\/ Distance definition \n \/\/ Quasi - Euclidian on the eta-phi cylinder\n \n Double_t dx = TMath::Abs(mx-x);\n if (dx > TMath::Pi()) dx = 2. * TMath::Pi() - dx;\n \n return (dx * dx + (my - y) * (my - y));\n}\n<commit_msg>Correction in the distance definition.<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/ Implemenatation of the K-Means Clustering Algorithm\n\/\/ See http:\/\/en.wikipedia.org\/wiki\/K-means_clustering and references therein.\n\/\/\n\/\/ This particular implementation is the so called Soft K-means algorithm.\n\/\/ It has been modified to work on the cylindrical topology in eta-phi space.\n\/\/\n\/\/ Author: Andreas Morsch (CERN)\n\/\/ andreas.morsch@cern.ch\n \n#include \"AliKMeansClustering.h\"\n#include <TMath.h>\n#include <TRandom.h>\n\nClassImp(AliKMeansClustering)\n\nDouble_t AliKMeansClustering::fBeta = 10.;\n \nvoid AliKMeansClustering::SoftKMeans(Int_t k, Int_t n, Double_t* x, Double_t* y, Double_t* mx, Double_t* my , Double_t* rk )\n{\n \/\/\n \/\/ The soft K-means algorithm\n \/\/\n Int_t i,j;\n \/\/\n \/\/ (1) Initialisation of the k means\n\n for (i = 0; i < k; i++) {\n\tmx[i] = 2. * TMath::Pi() * gRandom->Rndm();\n\tmy[i] = -1. + 2. * gRandom->Rndm();\n }\n\n \/\/\n \/\/ (2a) The responsibilities\n Double_t** r = new Double_t*[n]; \/\/ responsibilities\n for (j = 0; j < n; j++) {r[j] = new Double_t[k];}\n \/\/\n \/\/ (2b) Normalisation\n Double_t* nr = new Double_t[n];\n\n \/\/ (3) Iterations\n Int_t nit = 0;\n \n while(1) {\n\tnit++;\n \/\/\n \/\/ Assignment step\n \/\/\n for (j = 0; j < n; j++) {\n\tnr[j] = 0.;\n\tfor (i = 0; i < k; i++) {\n\t r[j][i] = TMath::Exp(- fBeta * d(mx[i], my[i], x[j], y[j]));\n\t nr[j] += r[j][i];\n\t} \/\/ mean i\n } \/\/ data point j\n\t\n for (j = 0; j < n; j++) {\n\tfor (i = 0; i < k; i++) {\n\t r[j][i] \/= nr[j];\n\t} \/\/ mean i\n } \/\/ data point j\n \n\t\/\/\n\t\/\/ Update step\n Double_t di = 0;\n \n for (i = 0; i < k; i++) {\n\t Double_t oldx = mx[i];\n\t Double_t oldy = my[i];\n\t \n\t mx[i] = x[0];\n\t my[i] = y[0];\n\t rk[i] = r[0][i];\n\t\n\tfor (j = 1; j < n; j++) {\n\t Double_t xx = x[j];\n\/\/\n\/\/ Here we have to take into acount the cylinder topology where phi is defined mod 2xpi\n\/\/ If two coordinates are separated by more than pi in phi one has to be shifted by +\/- 2 pi\n\n\t Double_t dx = mx[i] - x[j];\n\t if (dx > TMath::Pi()) xx += 2. * TMath::Pi();\n\t if (dx < -TMath::Pi()) xx -= 2. * TMath::Pi();\n\t mx[i] = mx[i] * rk[i] + r[j][i] * xx;\n\t my[i] = my[i] * rk[i] + r[j][i] * y[j];\n\t rk[i] += r[j][i];\n\t mx[i] \/= rk[i];\n\t my[i] \/= rk[i];\t \n\t if (mx[i] > 2. * TMath::Pi()) mx[i] -= 2. * TMath::Pi();\n\t if (mx[i] < 0. ) mx[i] += 2. * TMath::Pi();\n\t} \/\/ Data\n\tdi += d(mx[i], my[i], oldx, oldy);\n } \/\/ means \n\t\/\/\n\t\/\/ ending condition\n if (di < 1.e-8 || nit > 1000) break;\n } \/\/ while\n\n\/\/ Clean-up \n delete[] nr;\n for (j = 0; j < n; j++) delete[] r[j];\n delete[] r;\n}\n\nDouble_t AliKMeansClustering::d(Double_t mx, Double_t my, Double_t x, Double_t y)\n{\n \/\/\n \/\/ Distance definition \n \/\/ Quasi - Euclidian on the eta-phi cylinder\n \n Double_t dx = TMath::Abs(mx-x);\n if (dx > TMath::Pi()) dx = 2. * TMath::Pi() - dx;\n \n return (0.5*(dx * dx + (my - y) * (my - y)));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#include \"posix-stack.hh\"\n#include \"net.hh\"\n#include \"packet.hh\"\n#include \"api.hh\"\n\nnamespace net {\n\nclass posix_connected_socket_impl final : public connected_socket_impl {\n pollable_fd _fd;\nprivate:\n explicit posix_connected_socket_impl(pollable_fd fd) : _fd(std::move(fd)) {}\npublic:\n virtual input_stream<char> input() override { return input_stream<char>(posix_data_source(_fd)); }\n virtual output_stream<char> output() override { return output_stream<char>(posix_data_sink(_fd), 8192); }\n friend class posix_server_socket_impl;\n friend class posix_ap_server_socket_impl;\n};\n\nfuture<connected_socket, socket_address>\nposix_server_socket_impl::accept() {\n return _lfd.accept().then([this] (pollable_fd fd, socket_address sa) {\n static unsigned balance = 0;\n auto cpu = balance++ % smp::count;\n\n if (cpu == engine.cpu_id()) {\n std::unique_ptr<connected_socket_impl> csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future<connected_socket, socket_address>(\n connected_socket(std::move(csi)), sa);\n } else {\n smp::submit_to(cpu, [this, fd = std::move(fd.get_file_desc()), sa] () mutable {\n posix_ap_server_socket_impl::move_connected_socket(_sa, pollable_fd(std::move(fd)), sa);\n });\n return accept();\n }\n });\n}\n\nfuture<connected_socket, socket_address> posix_ap_server_socket_impl::accept() {\n auto conni = conn_q.find(_sa.as_posix_sockaddr_in());\n if (conni != conn_q.end()) {\n connection c = std::move(conni->second);\n conn_q.erase(conni);\n std::unique_ptr<connected_socket_impl> csi(new posix_connected_socket_impl(std::move(c.fd)));\n return make_ready_future<connected_socket, socket_address>(connected_socket(std::move(csi)), std::move(c.addr));\n } else {\n auto i = sockets.emplace(std::piecewise_construct, std::make_tuple(_sa.as_posix_sockaddr_in()), std::make_tuple());\n assert(i.second);\n return i.first->second.get_future();\n }\n}\n\nvoid posix_ap_server_socket_impl::move_connected_socket(socket_address sa, pollable_fd fd, socket_address addr) {\n auto i = sockets.find(sa.as_posix_sockaddr_in());\n if (i != sockets.end()) {\n std::unique_ptr<connected_socket_impl> csi(new posix_connected_socket_impl(std::move(fd)));\n i->second.set_value(connected_socket(std::move(csi)), std::move(addr));\n sockets.erase(i);\n } else {\n conn_q.emplace(std::piecewise_construct, std::make_tuple(sa.as_posix_sockaddr_in()), std::make_tuple(std::move(fd), std::move(addr)));\n }\n}\n\ndata_source posix_data_source(pollable_fd& fd) {\n return data_source(std::make_unique<posix_data_source_impl>(fd));\n}\n\nfuture<temporary_buffer<char>>\nposix_data_source_impl::get() {\n return _fd.read_some(_buf.get_write(), _buf_size).then([this] (size_t size) {\n _buf.trim(size);\n auto ret = std::move(_buf);\n _buf = temporary_buffer<char>(_buf_size);\n return make_ready_future<temporary_buffer<char>>(std::move(ret));\n });\n}\n\ndata_sink posix_data_sink(pollable_fd& fd) {\n return data_sink(std::make_unique<posix_data_sink_impl>(fd));\n}\n\nstd::vector<struct iovec> to_iovec(const packet& p) {\n std::vector<struct iovec> v;\n v.reserve(p.nr_frags());\n for (auto&& f : p.fragments()) {\n v.push_back({.iov_base = f.base, .iov_len = f.size});\n }\n return v;\n}\n\nstd::vector<iovec> to_iovec(std::vector<temporary_buffer<char>>& buf_vec) {\n std::vector<iovec> v;\n v.reserve(buf_vec.size());\n for (auto& buf : buf_vec) {\n v.push_back({.iov_base = buf.get_write(), .iov_len = buf.size()});\n }\n return v;\n}\n\nfuture<>\nposix_data_sink_impl::put(temporary_buffer<char> buf) {\n return _fd.write_all(buf.get(), buf.size()).then([d = buf.release()] {});\n}\n\nfuture<>\nposix_data_sink_impl::put(packet p) {\n _p = std::move(p);\n return _fd.write_all(_p).then([this] { _p.reset(); });\n}\n\nserver_socket\nposix_network_stack::listen(socket_address sa, listen_options opt) {\n return server_socket(std::make_unique<posix_server_socket_impl>(sa, engine.posix_listen(sa, opt)));\n}\n\nfuture<connected_socket>\nposix_network_stack::connect(socket_address sa) {\n return make_ready_future<connected_socket>(connected_socket(nullptr));\n}\n\nthread_local std::unordered_map<::sockaddr_in, promise<connected_socket, socket_address>> posix_ap_server_socket_impl::sockets;\nthread_local std::unordered_multimap<::sockaddr_in, posix_ap_server_socket_impl::connection> posix_ap_server_socket_impl::conn_q;\n\nserver_socket\nposix_ap_network_stack::listen(socket_address sa, listen_options opt) {\n return server_socket(std::make_unique<posix_ap_server_socket_impl>(sa));\n}\n\nfuture<connected_socket>\nposix_ap_network_stack::connect(socket_address sa) {\n return make_ready_future<connected_socket>(connected_socket(nullptr));\n}\n\nstruct cmsg_with_pktinfo {\n struct cmsghdrcmh;\n struct in_pktinfo pktinfo;\n};\n\nclass posix_udp_channel : public udp_channel_impl {\nprivate:\n static constexpr int MAX_DATAGRAM_SIZE = 65507;\n struct recv_ctx {\n struct msghdr _hdr;\n struct iovec _iov;\n socket_address _src_addr;\n char* _buffer;\n cmsg_with_pktinfo _cmsg;\n\n recv_ctx() {\n memset(&_hdr, 0, sizeof(_hdr));\n _hdr.msg_iov = &_iov;\n _hdr.msg_iovlen = 1;\n _hdr.msg_name = &_src_addr.u.sa;\n _hdr.msg_namelen = sizeof(_src_addr.u.sas);\n memset(&_cmsg, 0, sizeof(_cmsg));\n _hdr.msg_control = &_cmsg;\n _hdr.msg_controllen = sizeof(_cmsg);\n }\n\n void prepare() {\n _buffer = new char[MAX_DATAGRAM_SIZE];\n _iov.iov_base = _buffer;\n _iov.iov_len = MAX_DATAGRAM_SIZE;\n }\n };\n struct send_ctx {\n struct msghdr _hdr;\n std::vector<struct iovec> _iovecs;\n socket_address _dst;\n packet _p;\n\n send_ctx() {\n memset(&_hdr, 0, sizeof(_hdr));\n _hdr.msg_name = &_dst.u.sa;\n _hdr.msg_namelen = sizeof(_dst.u.sas);\n }\n\n void prepare(ipv4_addr dst, packet p) {\n _dst = make_ipv4_address(dst);\n _p = std::move(p);\n _iovecs = std::move(to_iovec(_p));\n _hdr.msg_iov = _iovecs.data();\n _hdr.msg_iovlen = _iovecs.size();\n }\n };\n std::unique_ptr<pollable_fd> _fd;\n ipv4_addr _address;\n recv_ctx _recv;\n send_ctx _send;\n bool _closed;\npublic:\n posix_udp_channel(ipv4_addr bind_address)\n : _closed(false) {\n auto sa = make_ipv4_address(bind_address);\n file_desc fd = file_desc::socket(sa.u.sa.sa_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n fd.setsockopt(SOL_IP, IP_PKTINFO, true);\n fd.bind(sa.u.sa, sizeof(sa.u.sas));\n _address = ipv4_addr(fd.get_address());\n _fd = std::make_unique<pollable_fd>(std::move(fd));\n }\n virtual ~posix_udp_channel() {};\n virtual future<udp_datagram> receive() override;\n virtual future<> send(ipv4_addr dst, const char *msg);\n virtual future<> send(ipv4_addr dst, packet p);\n virtual void close() override {\n _closed = true;\n _fd.reset();\n }\n virtual bool is_closed() const override { return _closed; }\n};\n\nfuture<> posix_udp_channel::send(ipv4_addr dst, const char *message) {\n auto len = strlen(message);\n return _fd->sendto(make_ipv4_address(dst), message, len)\n .then([len] (size_t size) { assert(size == len); });\n}\n\nfuture<> posix_udp_channel::send(ipv4_addr dst, packet p) {\n auto len = p.len();\n _send.prepare(dst, std::move(p));\n return _fd->sendmsg(&_send._hdr)\n .then([len] (size_t size) { assert(size == len); });\n}\n\nudp_channel\nposix_network_stack::make_udp_channel(ipv4_addr addr) {\n return udp_channel(std::make_unique<posix_udp_channel>(addr));\n}\n\nclass posix_datagram : public udp_datagram_impl {\nprivate:\n ipv4_addr _src;\n ipv4_addr _dst;\n packet _p;\npublic:\n posix_datagram(ipv4_addr src, ipv4_addr dst, packet p) : _src(src), _dst(dst), _p(std::move(p)) {}\n virtual ipv4_addr get_src() override { return _src; }\n virtual ipv4_addr get_dst() override { return _dst; }\n virtual uint16_t get_dst_port() override { return _dst.port; }\n virtual packet& get_data() override { return _p; }\n};\n\nfuture<udp_datagram>\nposix_udp_channel::receive() {\n _recv.prepare();\n return _fd->recvmsg(&_recv._hdr).then([this] (size_t size) {\n auto dst = ipv4_addr(_recv._cmsg.pktinfo.ipi_addr.s_addr, _address.port);\n return make_ready_future<udp_datagram>(udp_datagram(std::make_unique<posix_datagram>(\n _recv._src_addr, dst, packet(fragment{_recv._buffer, size}, [buf = _recv._buffer] { delete[] buf; }))));\n });\n}\n\nnetwork_stack_registrator nsr_posix{\"posix\",\n boost::program_options::options_description(),\n [](boost::program_options::variables_map ops) {\n return smp::main_thread() ? posix_network_stack::create(ops) : posix_ap_network_stack::create(ops);\n },\n true\n};\n\n}\n<commit_msg>Implement TCP client on posix-stack<commit_after>\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#include \"posix-stack.hh\"\n#include \"net.hh\"\n#include \"packet.hh\"\n#include \"api.hh\"\n\nnamespace net {\n\nclass posix_connected_socket_impl final : public connected_socket_impl {\n pollable_fd _fd;\nprivate:\n explicit posix_connected_socket_impl(pollable_fd fd) : _fd(std::move(fd)) {}\npublic:\n virtual input_stream<char> input() override { return input_stream<char>(posix_data_source(_fd)); }\n virtual output_stream<char> output() override { return output_stream<char>(posix_data_sink(_fd), 8192); }\n friend class posix_server_socket_impl;\n friend class posix_ap_server_socket_impl;\n friend class posix_network_stack;\n friend class posix_ap_network_stack;\n};\n\nfuture<connected_socket, socket_address>\nposix_server_socket_impl::accept() {\n return _lfd.accept().then([this] (pollable_fd fd, socket_address sa) {\n static unsigned balance = 0;\n auto cpu = balance++ % smp::count;\n\n if (cpu == engine.cpu_id()) {\n std::unique_ptr<connected_socket_impl> csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future<connected_socket, socket_address>(\n connected_socket(std::move(csi)), sa);\n } else {\n smp::submit_to(cpu, [this, fd = std::move(fd.get_file_desc()), sa] () mutable {\n posix_ap_server_socket_impl::move_connected_socket(_sa, pollable_fd(std::move(fd)), sa);\n });\n return accept();\n }\n });\n}\n\nfuture<connected_socket, socket_address> posix_ap_server_socket_impl::accept() {\n auto conni = conn_q.find(_sa.as_posix_sockaddr_in());\n if (conni != conn_q.end()) {\n connection c = std::move(conni->second);\n conn_q.erase(conni);\n std::unique_ptr<connected_socket_impl> csi(new posix_connected_socket_impl(std::move(c.fd)));\n return make_ready_future<connected_socket, socket_address>(connected_socket(std::move(csi)), std::move(c.addr));\n } else {\n auto i = sockets.emplace(std::piecewise_construct, std::make_tuple(_sa.as_posix_sockaddr_in()), std::make_tuple());\n assert(i.second);\n return i.first->second.get_future();\n }\n}\n\nvoid posix_ap_server_socket_impl::move_connected_socket(socket_address sa, pollable_fd fd, socket_address addr) {\n auto i = sockets.find(sa.as_posix_sockaddr_in());\n if (i != sockets.end()) {\n std::unique_ptr<connected_socket_impl> csi(new posix_connected_socket_impl(std::move(fd)));\n i->second.set_value(connected_socket(std::move(csi)), std::move(addr));\n sockets.erase(i);\n } else {\n conn_q.emplace(std::piecewise_construct, std::make_tuple(sa.as_posix_sockaddr_in()), std::make_tuple(std::move(fd), std::move(addr)));\n }\n}\n\ndata_source posix_data_source(pollable_fd& fd) {\n return data_source(std::make_unique<posix_data_source_impl>(fd));\n}\n\nfuture<temporary_buffer<char>>\nposix_data_source_impl::get() {\n return _fd.read_some(_buf.get_write(), _buf_size).then([this] (size_t size) {\n _buf.trim(size);\n auto ret = std::move(_buf);\n _buf = temporary_buffer<char>(_buf_size);\n return make_ready_future<temporary_buffer<char>>(std::move(ret));\n });\n}\n\ndata_sink posix_data_sink(pollable_fd& fd) {\n return data_sink(std::make_unique<posix_data_sink_impl>(fd));\n}\n\nstd::vector<struct iovec> to_iovec(const packet& p) {\n std::vector<struct iovec> v;\n v.reserve(p.nr_frags());\n for (auto&& f : p.fragments()) {\n v.push_back({.iov_base = f.base, .iov_len = f.size});\n }\n return v;\n}\n\nstd::vector<iovec> to_iovec(std::vector<temporary_buffer<char>>& buf_vec) {\n std::vector<iovec> v;\n v.reserve(buf_vec.size());\n for (auto& buf : buf_vec) {\n v.push_back({.iov_base = buf.get_write(), .iov_len = buf.size()});\n }\n return v;\n}\n\nfuture<>\nposix_data_sink_impl::put(temporary_buffer<char> buf) {\n return _fd.write_all(buf.get(), buf.size()).then([d = buf.release()] {});\n}\n\nfuture<>\nposix_data_sink_impl::put(packet p) {\n _p = std::move(p);\n return _fd.write_all(_p).then([this] { _p.reset(); });\n}\n\nserver_socket\nposix_network_stack::listen(socket_address sa, listen_options opt) {\n return server_socket(std::make_unique<posix_server_socket_impl>(sa, engine.posix_listen(sa, opt)));\n}\n\nfuture<connected_socket>\nposix_network_stack::connect(socket_address sa) {\n return engine.posix_connect(sa).then([] (pollable_fd fd) {\n std::unique_ptr<connected_socket_impl> csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future<connected_socket>(connected_socket(std::move(csi)));\n });\n}\n\nthread_local std::unordered_map<::sockaddr_in, promise<connected_socket, socket_address>> posix_ap_server_socket_impl::sockets;\nthread_local std::unordered_multimap<::sockaddr_in, posix_ap_server_socket_impl::connection> posix_ap_server_socket_impl::conn_q;\n\nserver_socket\nposix_ap_network_stack::listen(socket_address sa, listen_options opt) {\n return server_socket(std::make_unique<posix_ap_server_socket_impl>(sa));\n}\n\nfuture<connected_socket>\nposix_ap_network_stack::connect(socket_address sa) {\n return engine.posix_connect(sa).then([] (pollable_fd fd) {\n std::unique_ptr<connected_socket_impl> csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future<connected_socket>(connected_socket(std::move(csi)));\n });\n}\n\nstruct cmsg_with_pktinfo {\n struct cmsghdrcmh;\n struct in_pktinfo pktinfo;\n};\n\nclass posix_udp_channel : public udp_channel_impl {\nprivate:\n static constexpr int MAX_DATAGRAM_SIZE = 65507;\n struct recv_ctx {\n struct msghdr _hdr;\n struct iovec _iov;\n socket_address _src_addr;\n char* _buffer;\n cmsg_with_pktinfo _cmsg;\n\n recv_ctx() {\n memset(&_hdr, 0, sizeof(_hdr));\n _hdr.msg_iov = &_iov;\n _hdr.msg_iovlen = 1;\n _hdr.msg_name = &_src_addr.u.sa;\n _hdr.msg_namelen = sizeof(_src_addr.u.sas);\n memset(&_cmsg, 0, sizeof(_cmsg));\n _hdr.msg_control = &_cmsg;\n _hdr.msg_controllen = sizeof(_cmsg);\n }\n\n void prepare() {\n _buffer = new char[MAX_DATAGRAM_SIZE];\n _iov.iov_base = _buffer;\n _iov.iov_len = MAX_DATAGRAM_SIZE;\n }\n };\n struct send_ctx {\n struct msghdr _hdr;\n std::vector<struct iovec> _iovecs;\n socket_address _dst;\n packet _p;\n\n send_ctx() {\n memset(&_hdr, 0, sizeof(_hdr));\n _hdr.msg_name = &_dst.u.sa;\n _hdr.msg_namelen = sizeof(_dst.u.sas);\n }\n\n void prepare(ipv4_addr dst, packet p) {\n _dst = make_ipv4_address(dst);\n _p = std::move(p);\n _iovecs = std::move(to_iovec(_p));\n _hdr.msg_iov = _iovecs.data();\n _hdr.msg_iovlen = _iovecs.size();\n }\n };\n std::unique_ptr<pollable_fd> _fd;\n ipv4_addr _address;\n recv_ctx _recv;\n send_ctx _send;\n bool _closed;\npublic:\n posix_udp_channel(ipv4_addr bind_address)\n : _closed(false) {\n auto sa = make_ipv4_address(bind_address);\n file_desc fd = file_desc::socket(sa.u.sa.sa_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n fd.setsockopt(SOL_IP, IP_PKTINFO, true);\n fd.bind(sa.u.sa, sizeof(sa.u.sas));\n _address = ipv4_addr(fd.get_address());\n _fd = std::make_unique<pollable_fd>(std::move(fd));\n }\n virtual ~posix_udp_channel() {};\n virtual future<udp_datagram> receive() override;\n virtual future<> send(ipv4_addr dst, const char *msg);\n virtual future<> send(ipv4_addr dst, packet p);\n virtual void close() override {\n _closed = true;\n _fd.reset();\n }\n virtual bool is_closed() const override { return _closed; }\n};\n\nfuture<> posix_udp_channel::send(ipv4_addr dst, const char *message) {\n auto len = strlen(message);\n return _fd->sendto(make_ipv4_address(dst), message, len)\n .then([len] (size_t size) { assert(size == len); });\n}\n\nfuture<> posix_udp_channel::send(ipv4_addr dst, packet p) {\n auto len = p.len();\n _send.prepare(dst, std::move(p));\n return _fd->sendmsg(&_send._hdr)\n .then([len] (size_t size) { assert(size == len); });\n}\n\nudp_channel\nposix_network_stack::make_udp_channel(ipv4_addr addr) {\n return udp_channel(std::make_unique<posix_udp_channel>(addr));\n}\n\nclass posix_datagram : public udp_datagram_impl {\nprivate:\n ipv4_addr _src;\n ipv4_addr _dst;\n packet _p;\npublic:\n posix_datagram(ipv4_addr src, ipv4_addr dst, packet p) : _src(src), _dst(dst), _p(std::move(p)) {}\n virtual ipv4_addr get_src() override { return _src; }\n virtual ipv4_addr get_dst() override { return _dst; }\n virtual uint16_t get_dst_port() override { return _dst.port; }\n virtual packet& get_data() override { return _p; }\n};\n\nfuture<udp_datagram>\nposix_udp_channel::receive() {\n _recv.prepare();\n return _fd->recvmsg(&_recv._hdr).then([this] (size_t size) {\n auto dst = ipv4_addr(_recv._cmsg.pktinfo.ipi_addr.s_addr, _address.port);\n return make_ready_future<udp_datagram>(udp_datagram(std::make_unique<posix_datagram>(\n _recv._src_addr, dst, packet(fragment{_recv._buffer, size}, [buf = _recv._buffer] { delete[] buf; }))));\n });\n}\n\nnetwork_stack_registrator nsr_posix{\"posix\",\n boost::program_options::options_description(),\n [](boost::program_options::variables_map ops) {\n return smp::main_thread() ? posix_network_stack::create(ops) : posix_ap_network_stack::create(ops);\n },\n true\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \".\/JPetSinogram.h\"\n#include <boost\/numeric\/ublas\/matrix.hpp>\nusing namespace boost::numeric::ublas;\n\nJPetSinogram::JPetSinogram() { }\n\nJPetSinogram::~JPetSinogram() { }\n\nlong long JPetSinogram::forwardProjection(float s, float theta, matrix<int> emissionMatrix) {\n long long sum = 0;\n if(theta == 0) {\n for(unsigned int i = 0; i < emissionMatrix.size2(); i++) {\n sum += emissionMatrix(s, i);\n }\n } else if(theta == 90) {\n for(unsigned int i = 0; i < emissionMatrix.size1(); i++) {\n sum += emissionMatrix(i, s);\n }\n }\n\n return sum;\n}\n<commit_msg>Add 45theta case<commit_after>#include \".\/JPetSinogram.h\"\n#include <boost\/numeric\/ublas\/matrix.hpp>\nusing namespace boost::numeric::ublas;\n\nJPetSinogram::JPetSinogram() { }\n\nJPetSinogram::~JPetSinogram() { }\n\nlong long JPetSinogram::forwardProjection(float s, float theta, matrix<int> emissionMatrix) {\n long long sum = 0;\n if(theta == 0) {\n for(unsigned int i = 0; i < emissionMatrix.size2(); i++) {\n sum += emissionMatrix(s, i);\n }\n } else if(theta == 90) {\n for(unsigned int i = 0; i < emissionMatrix.size1(); i++) {\n sum += emissionMatrix(i, s);\n }\n } else if(theta == 45) {\n unsigned int j = (emissionMatrix.size2() - 1) - s < 0 ? 0 : (emissionMatrix.size2() - 1) - s;\n unsigned int i = (emissionMatrix.size2() - 1) - s < 0 ? - ((emissionMatrix.size2() - 1 - s)) : 0;\/\/ select row, start from upper right corner\n for(; j < emissionMatrix.size2(); j++) { \/\/-1 bcs matrix start from 0\n if(i < emissionMatrix.size1()) {\n sum += emissionMatrix(i, j);\n i++;\n }\n else { } \/\/ exception\n }\n\n }\n\n return sum;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgeotiledmaprectangleobjectinfo_p.h\"\n\n#include \"qgeotiledmapdata.h\"\n#include \"qgeotiledmapdata_p.h\"\n\n#include \"qgeomaprectangleobject_p.h\"\n\nQTM_BEGIN_NAMESPACE\n\nQGeoTiledMapRectangleObjectInfo::QGeoTiledMapRectangleObjectInfo(const QGeoMapObjectPrivate *mapObjectPrivate)\n : QGeoTiledMapObjectInfo(mapObjectPrivate),\n rectangleItem1(0),\n rectangleItem2(0)\n{\n rectangle = static_cast<const QGeoMapRectangleObjectPrivate*>(mapObjectPrivate);\n}\n\nQGeoTiledMapRectangleObjectInfo::~QGeoTiledMapRectangleObjectInfo() {}\n\nvoid QGeoTiledMapRectangleObjectInfo::objectUpdate()\n{\n QPoint topLeft = mapData->q_ptr->coordinateToWorldPixel(rectangle->bounds.topLeft());\n QPoint bottomRight = mapData->q_ptr->coordinateToWorldPixel(rectangle->bounds.bottomRight());\n\n bounds = QRectF(topLeft, bottomRight);\n\n QRectF bounds1 = bounds;\n QRectF bounds2;\n\n if (bounds1.right() < bounds1.left()) {\n bounds1.setRight(bounds1.right() + mapData->maxZoomSize.width());\n bounds2 = bounds1.translated(-mapData->maxZoomSize.width(), 0);\n }\n\n if (!rectangleItem1)\n rectangleItem1 = new QGraphicsRectItem();\n\n if (bounds2.isValid()) {\n if (!rectangleItem2)\n rectangleItem2 = new QGraphicsRectItem(rectangleItem1);\n } else {\n if (rectangleItem2) {\n delete rectangleItem2;\n rectangleItem2 = 0;\n }\n }\n\n rectangleItem1->setRect(bounds1);\n if (rectangleItem2)\n rectangleItem2->setRect(bounds2);\n\n rectangleItem1->setBrush(rectangle->brush);\n if (rectangleItem2)\n rectangleItem2->setBrush(rectangle->brush);\n\n mapUpdate();\n\n graphicsItem1 = rectangleItem1;\n graphicsItem2 = rectangleItem2;\n}\n\nvoid QGeoTiledMapRectangleObjectInfo::mapUpdate()\n{\n if (rectangleItem1) {\n QPen pen = rectangle->pen;\n pen.setWidthF(pen.widthF() * mapData->zoomFactor);\n rectangleItem1->setPen(pen);\n if (rectangleItem2)\n rectangleItem2->setPen(pen);\n }\n}\n\nQTM_END_NAMESPACE\n\n\n<commit_msg>Using a derivative of the polyline\/gon\/circle path->points algorithm for rectangles now. Works much better across the dateline and with denormalized rectangles.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgeotiledmaprectangleobjectinfo_p.h\"\n\n#include \"qgeotiledmapdata.h\"\n#include \"qgeotiledmapdata_p.h\"\n\n#include \"qgeomaprectangleobject_p.h\"\n\nQTM_BEGIN_NAMESPACE\n\nQGeoTiledMapRectangleObjectInfo::QGeoTiledMapRectangleObjectInfo(const QGeoMapObjectPrivate *mapObjectPrivate)\n : QGeoTiledMapObjectInfo(mapObjectPrivate),\n rectangleItem1(0),\n rectangleItem2(0)\n{\n rectangle = static_cast<const QGeoMapRectangleObjectPrivate*>(mapObjectPrivate);\n}\n\nQGeoTiledMapRectangleObjectInfo::~QGeoTiledMapRectangleObjectInfo() {}\n\nvoid QGeoTiledMapRectangleObjectInfo::objectUpdate()\n{\n#if 1\n QGeoCoordinate coord1 = rectangle->bounds.topLeft();\n QGeoCoordinate coord2 = rectangle->bounds.bottomRight();\n\n const qreal lng1 = coord1.longitude();\n const qreal lng2 = coord2.longitude();\n\n \/\/ is the dateline crossed = different sign AND gap is large enough\n const bool crossesDateline = lng1 * lng2 < 0 && abs(lng1 - lng2) > 180;\n\n \/\/ calculate base points\n QPointF point1 = mapData->q_ptr->coordinateToWorldPixel(coord1);\n QPointF point2 = mapData->q_ptr->coordinateToWorldPixel(coord2);\n\n QRectF bounds1 = QRectF(point1, point2).normalized();\n QRectF bounds2;\n\n \/\/ if the dateline is crossed, draw \"around\" the map over the chosen pole\n if (crossesDateline) {\n \/\/ is the shortest route east = dateline crossed XOR longitude is east by simple comparison\n const bool goesEast = crossesDateline != (lng2 > lng1);\n \/\/ direction = positive if east, negative otherwise\n const qreal dir = goesEast ? 1 : -1;\n\n int width = mapData->maxZoomSize.width();\n\n \/\/ lastPoint on the other side\n QPointF point1_ = point1 - QPointF(width*dir, 0);\n\n \/\/ point on this side\n QPointF point2_ = point2 + QPointF(width*dir, 0);\n\n bounds1 = QRectF(point1_, point2).normalized();\n bounds2 = QRectF(point1, point2_).normalized();\n }\n\n#else\n \/\/ Old code, to be removed.\n QPoint topLeft = mapData->q_ptr->coordinateToWorldPixel(rectangle->bounds.topLeft());\n QPoint bottomRight = mapData->q_ptr->coordinateToWorldPixel(rectangle->bounds.bottomRight());\n\n bounds = QRectF(topLeft, bottomRight);\n\n QRectF bounds1 = bounds;\n QRectF bounds2;\n\n if (bounds1.right() < bounds1.left()) {\n bounds1.setRight(bounds1.right() + mapData->maxZoomSize.width());\n bounds2 = bounds1.translated(-mapData->maxZoomSize.width(), 0);\n }\n#endif\n\n if (!rectangleItem1)\n rectangleItem1 = new QGraphicsRectItem();\n\n if (bounds2.isValid()) {\n if (!rectangleItem2)\n rectangleItem2 = new QGraphicsRectItem(rectangleItem1);\n } else {\n if (rectangleItem2) {\n delete rectangleItem2;\n rectangleItem2 = 0;\n }\n }\n\n rectangleItem1->setRect(bounds1);\n if (rectangleItem2)\n rectangleItem2->setRect(bounds2);\n\n rectangleItem1->setBrush(rectangle->brush);\n if (rectangleItem2)\n rectangleItem2->setBrush(rectangle->brush);\n\n mapUpdate();\n\n graphicsItem1 = rectangleItem1;\n graphicsItem2 = rectangleItem2;\n}\n\nvoid QGeoTiledMapRectangleObjectInfo::mapUpdate()\n{\n if (rectangleItem1) {\n QPen pen = rectangle->pen;\n pen.setWidthF(pen.widthF() * mapData->zoomFactor);\n rectangleItem1->setPen(pen);\n if (rectangleItem2)\n rectangleItem2->setPen(pen);\n }\n}\n\nQTM_END_NAMESPACE\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include \"ccspec\/core.h\"\n#include \"ccspec\/expectation.h\"\n#include \"ccspec\/matchers.h\"\n\nnamespace spec {\nnamespace expectation {\n\nusing std::string;\nusing ccspec::core::describe;\nusing ccspec::core::it;\nusing ccspec::expect;\nusing ccspec::expectation::Mismatch;\nusing ccspec::matchers::BeComparedTo;\nusing ccspec::matchers::Eq;\nusing ccspec::matchers::be;\nusing ccspec::matchers::eq;\n\nauto mismatch_spec = describe(\"Mismatch\", [] {\n describe(\"#what\", [] {\n it(\"says '$x should equal $y' for Eq matcher\", [] {\n Mismatch<int, Eq<int>> mismatch(42, eq(43));\n expect(string(mismatch.what())).to(eq(\"42 should equal 43\"));\n });\n\n it(\"says '$x should be <= $y' for BeComparedTo matcher with <=\", [] {\n Mismatch<int, BeComparedTo<int>> mismatch(42, be <= 41);\n expect(string(mismatch.what())).to(eq(\"42 should be <= 41\"));\n });\n });\n});\n\n} \/\/ namespace expectation\n} \/\/ namespace spec\n\n<commit_msg>Remove trailing newline in mismatch_spec.cc<commit_after>#include <string>\n\n#include \"ccspec\/core.h\"\n#include \"ccspec\/expectation.h\"\n#include \"ccspec\/matchers.h\"\n\nnamespace spec {\nnamespace expectation {\n\nusing std::string;\nusing ccspec::core::describe;\nusing ccspec::core::it;\nusing ccspec::expect;\nusing ccspec::expectation::Mismatch;\nusing ccspec::matchers::BeComparedTo;\nusing ccspec::matchers::Eq;\nusing ccspec::matchers::be;\nusing ccspec::matchers::eq;\n\nauto mismatch_spec = describe(\"Mismatch\", [] {\n describe(\"#what\", [] {\n it(\"says '$x should equal $y' for Eq matcher\", [] {\n Mismatch<int, Eq<int>> mismatch(42, eq(43));\n expect(string(mismatch.what())).to(eq(\"42 should equal 43\"));\n });\n\n it(\"says '$x should be <= $y' for BeComparedTo matcher with <=\", [] {\n Mismatch<int, BeComparedTo<int>> mismatch(42, be <= 41);\n expect(string(mismatch.what())).to(eq(\"42 should be <= 41\"));\n });\n });\n});\n\n} \/\/ namespace expectation\n} \/\/ namespace spec\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include <ostream>\n\n#include \"paddle\/fluid\/framework\/data_type.h\"\n#include \"paddle\/fluid\/framework\/framework.pb.h\"\n#include \"paddle\/fluid\/framework\/lod_tensor.h\"\n#include \"paddle\/fluid\/framework\/op_registry.h\"\n\n#include <future>\n#include \"paddle\/fluid\/operators\/detail\/grpc_client.h\"\n\nnamespace paddle {\nnamespace operators {\nstatic bool NeedSend(const framework::Scope& scope,\n const std::string& varname) {\n auto* var = scope.FindVar(varname);\n PADDLE_ENFORCE_NOT_NULL(var, \"Can not find variable '%s' in the send side.\",\n varname);\n if (var->IsType<framework::LoDTensor>()) {\n return var->Get<framework::LoDTensor>().IsInitialized();\n } else if (var->IsType<framework::SelectedRows>()) {\n return var->Get<framework::SelectedRows>().rows().size() > 0UL;\n } else {\n PADDLE_THROW(\n \"Variable type in send side should be in \"\n \"[LodTensor, SelectedRows]\");\n }\n return false;\n}\n\nclass SendOp : public framework::OperatorBase {\n public:\n SendOp(const std::string& type, const framework::VariableNameMap& inputs,\n const framework::VariableNameMap& outputs,\n const framework::AttributeMap& attrs)\n : OperatorBase(type, inputs, outputs, attrs) {}\n\n void RunImpl(const framework::Scope& scope,\n const platform::Place& place) const override {\n auto ins = Inputs(\"X\");\n auto outs = Outputs(\"Out\");\n std::vector<std::string> epmap = Attr<std::vector<std::string>>(\"epmap\");\n std::vector<std::string> endpoints =\n Attr<std::vector<std::string>>(\"endpoints\");\n\n platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();\n auto& ctx = *pool.Get(place);\n\n auto client_var_name = Output(\"RPCClient\");\n PADDLE_ENFORCE_NOT_NULL(scope.FindVar(client_var_name),\n \"Can not find variable '%s' in the scope.\",\n client_var_name);\n auto* client_var = scope.FindVar(client_var_name);\n detail::RPCClient* rpc_client = client_var->GetMutable<detail::RPCClient>();\n\n ctx.Wait(); \/\/ wait before sending\n for (size_t i = 0; i < ins.size(); i++) {\n if (NeedSend(scope, ins[i])) {\n VLOG(3) << \"sending \" << ins[i] << \" to \" << epmap[i];\n rpc_client->AsyncSendVariable(epmap[i], ctx, scope, ins[i]);\n } else {\n VLOG(3) << \"don't send no-initialied variable: \" << ins[i];\n }\n }\n PADDLE_ENFORCE(rpc_client->Wait());\n\n for (auto& ep : endpoints) {\n VLOG(3) << \"batch barrier, ep: \" << ep;\n rpc_client->AsyncSendBatchBarrier(ep);\n }\n PADDLE_ENFORCE(rpc_client->Wait());\n\n if (outs.size() > 0) {\n for (size_t i = 0; i < outs.size(); i++) {\n VLOG(3) << \"getting \" << outs[i] << \" from \" << epmap[i];\n rpc_client->AsyncGetVariable(epmap[i], ctx, scope, outs[i]);\n }\n PADDLE_ENFORCE(rpc_client->Wait());\n \/\/ tell pservers that current trainer have called fetch\n for (auto& ep : endpoints) {\n VLOG(3) << \"send fetch barrier, ep: \" << ep;\n rpc_client->AsyncSendFetchBarrier(ep);\n }\n PADDLE_ENFORCE(rpc_client->Wait());\n }\n }\n};\n\nclass SendOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n SendOpMaker(OpProto* proto, OpAttrChecker* op_checker)\n : OpProtoAndCheckerMaker(proto, op_checker) {\n AddInput(\"X\", \"(Tensor) Input tensor to be sent\").AsDuplicable();\n AddOutput(\"Out\", \"(Tensor) Output tensor to be received from server\")\n .AsDuplicable();\n AddOutput(\"RPCClient\",\n \"(RPCClient) The RPC client object which is\"\n \"initialized at most once.\");\n AddComment(R\"DOC(\nSend operator\n\nThis operator will send tensor to recv_op at the parameter server.\n)DOC\");\n \/\/ TODO(typhoonzero): remove this attr generate de-duplicated vector from\n \/\/ epmap when initializing.\n AddAttr<std::vector<std::string>>(\"endpoints\",\n \"(string vector, default 127.0.0.1:6164)\"\n \"Server endpoints to send variables to.\")\n .SetDefault({});\n AddAttr<std::vector<std::string>>(\"epmap\",\n \"(string vector, default 127.0.0.1:6164)\"\n \"Server endpoints in the order of input \"\n \"variables for mapping\")\n .SetDefault({});\n }\n};\n\nclass SendOpVarTypeInference : public framework::VarTypeInference {\n public:\n void operator()(const framework::OpDesc& op_desc,\n framework::BlockDesc* block) const override {\n auto out_var_name = op_desc.Output(\"RPCClient\").front();\n auto& out_var = block->FindRecursiveOrCreateVar(out_var_name);\n auto var_type = framework::proto::VarType::RAW;\n out_var.SetType(var_type);\n }\n};\n\nclass SendOpShapeInference : public framework::InferShapeBase {\n public:\n void operator()(framework::InferShapeContext* ctx) const override {}\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(send, ops::SendOp, paddle::framework::EmptyGradOpMaker,\n ops::SendOpMaker, ops::SendOpVarTypeInference,\n ops::SendOpShapeInference);\n<commit_msg>updates<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include <ostream>\n\n#include \"paddle\/fluid\/framework\/data_type.h\"\n#include \"paddle\/fluid\/framework\/framework.pb.h\"\n#include \"paddle\/fluid\/framework\/lod_tensor.h\"\n#include \"paddle\/fluid\/framework\/op_registry.h\"\n\n#include <future>\n#include \"paddle\/fluid\/operators\/detail\/grpc_client.h\"\n\nnamespace paddle {\nnamespace operators {\nstatic bool NeedSend(const framework::Scope& scope,\n const std::string& varname) {\n auto* var = scope.FindVar(varname);\n PADDLE_ENFORCE_NOT_NULL(var, \"Can not find variable '%s' in the send side.\",\n varname);\n if (var->IsType<framework::LoDTensor>()) {\n return var->Get<framework::LoDTensor>().IsInitialized();\n } else if (var->IsType<framework::SelectedRows>()) {\n return var->Get<framework::SelectedRows>().rows().size() > 0UL;\n } else {\n PADDLE_THROW(\n \"Variable type in send side should be in \"\n \"[LodTensor, SelectedRows]\");\n }\n return false;\n}\n\nclass SendOp : public framework::OperatorBase {\n public:\n SendOp(const std::string& type, const framework::VariableNameMap& inputs,\n const framework::VariableNameMap& outputs,\n const framework::AttributeMap& attrs)\n : OperatorBase(type, inputs, outputs, attrs) {}\n\n void RunImpl(const framework::Scope& scope,\n const platform::Place& place) const override {\n auto ins = Inputs(\"X\");\n auto outs = Outputs(\"Out\");\n std::vector<std::string> epmap = Attr<std::vector<std::string>>(\"epmap\");\n std::vector<std::string> endpoints =\n Attr<std::vector<std::string>>(\"endpoints\");\n\n platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();\n auto& ctx = *pool.Get(place);\n\n auto client_var_name = Output(\"RPCClient\");\n PADDLE_ENFORCE_NOT_NULL(scope.FindVar(client_var_name),\n \"Can not find variable '%s' in the scope.\",\n client_var_name);\n auto* client_var = scope.FindVar(client_var_name);\n detail::RPCClient* rpc_client = client_var->GetMutable<detail::RPCClient>();\n\n for (size_t i = 0; i < ins.size(); i++) {\n if (NeedSend(scope, ins[i])) {\n VLOG(3) << \"sending \" << ins[i] << \" to \" << epmap[i];\n rpc_client->AsyncSendVariable(epmap[i], ctx, scope, ins[i]);\n } else {\n VLOG(3) << \"don't send no-initialied variable: \" << ins[i];\n }\n }\n PADDLE_ENFORCE(rpc_client->Wait());\n\n for (auto& ep : endpoints) {\n VLOG(3) << \"batch barrier, ep: \" << ep;\n rpc_client->AsyncSendBatchBarrier(ep);\n }\n PADDLE_ENFORCE(rpc_client->Wait());\n\n if (outs.size() > 0) {\n for (size_t i = 0; i < outs.size(); i++) {\n VLOG(3) << \"getting \" << outs[i] << \" from \" << epmap[i];\n rpc_client->AsyncGetVariable(epmap[i], ctx, scope, outs[i]);\n }\n PADDLE_ENFORCE(rpc_client->Wait());\n \/\/ tell pservers that current trainer have called fetch\n for (auto& ep : endpoints) {\n VLOG(3) << \"send fetch barrier, ep: \" << ep;\n rpc_client->AsyncSendFetchBarrier(ep);\n }\n PADDLE_ENFORCE(rpc_client->Wait());\n }\n }\n};\n\nclass SendOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n SendOpMaker(OpProto* proto, OpAttrChecker* op_checker)\n : OpProtoAndCheckerMaker(proto, op_checker) {\n AddInput(\"X\", \"(Tensor) Input tensor to be sent\").AsDuplicable();\n AddOutput(\"Out\", \"(Tensor) Output tensor to be received from server\")\n .AsDuplicable();\n AddOutput(\"RPCClient\",\n \"(RPCClient) The RPC client object which is\"\n \"initialized at most once.\");\n AddComment(R\"DOC(\nSend operator\n\nThis operator will send tensor to recv_op at the parameter server.\n)DOC\");\n \/\/ TODO(typhoonzero): remove this attr generate de-duplicated vector from\n \/\/ epmap when initializing.\n AddAttr<std::vector<std::string>>(\"endpoints\",\n \"(string vector, default 127.0.0.1:6164)\"\n \"Server endpoints to send variables to.\")\n .SetDefault({});\n AddAttr<std::vector<std::string>>(\"epmap\",\n \"(string vector, default 127.0.0.1:6164)\"\n \"Server endpoints in the order of input \"\n \"variables for mapping\")\n .SetDefault({});\n }\n};\n\nclass SendOpVarTypeInference : public framework::VarTypeInference {\n public:\n void operator()(const framework::OpDesc& op_desc,\n framework::BlockDesc* block) const override {\n auto out_var_name = op_desc.Output(\"RPCClient\").front();\n auto& out_var = block->FindRecursiveOrCreateVar(out_var_name);\n auto var_type = framework::proto::VarType::RAW;\n out_var.SetType(var_type);\n }\n};\n\nclass SendOpShapeInference : public framework::InferShapeBase {\n public:\n void operator()(framework::InferShapeContext* ctx) const override {}\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(send, ops::SendOp, paddle::framework::EmptyGradOpMaker,\n ops::SendOpMaker, ops::SendOpVarTypeInference,\n ops::SendOpShapeInference);\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 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 \"net\/disk_cache\/cache_util.h\"\n\n#include <errno.h>\n#include <sys\/statvfs.h>\n#include <unistd.h>\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n\nnamespace disk_cache {\n\nint64 GetFreeDiskSpace(const std::wstring& path) {\n struct statvfs stats;\n if (statvfs(WideToUTF8(path).c_str(), &stats) != 0) {\n return -1;\n }\n return static_cast<int64>(stats.f_bavail) * stats.f_frsize;\n}\n\nint64 GetSystemMemory() {\n#if defined(OS_LINUX)\n \/\/ _SC_PHYS_PAGES is not part of POSIX and not available on OS X\n long pages = sysconf(_SC_PHYS_PAGES);\n if (pages == -1) {\n return -1;\n }\n long page_size = sysconf(_SC_PAGE_SIZE);\n if (page_size == -1) {\n return -1;\n }\n int64 result = static_cast<int64>(pages) * page_size;\n DCHECK(result > 0);\n return result;\n#else\n \/\/ TODO(pinkerton): figure this out for mac\n NOTIMPLEMENTED();\n return -1;\n#endif\n}\n\nbool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {\n \/\/ Just use the version from base.\n return file_util::Move(from_path.c_str(), to_path.c_str());\n}\n\nvoid DeleteCache(const std::wstring& path, bool remove_folder) {\n if (remove_folder) {\n file_util::Delete(path, false);\n } else {\n std::wstring name(path);\n \/\/ TODO(rvargas): Fix this after file_util::delete is fixed.\n \/\/ file_util::AppendToPath(&name, L\"*\");\n file_util::Delete(name, true);\n }\n}\n\nbool DeleteCacheFile(const std::wstring& name) {\n return file_util::Delete(name, false);\n}\n\nvoid WaitForPendingIO(int* num_pending_io) {\n if (*num_pending_io) {\n NOTIMPLEMENTED();\n }\n}\n\n} \/\/ namespace disk_cache\n\n<commit_msg>Mac\/mach implementation of disk_cache::GetSystemMemory(). Patch by Kelly Norton <knorton@google.com>.<commit_after>\/\/ Copyright (c) 2006-2008 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 \"net\/disk_cache\/cache_util.h\"\n\n#include <errno.h>\n#include <sys\/statvfs.h>\n#include <unistd.h>\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n\n#if defined(OS_MACOSX)\n#include <mach\/mach_host.h>\n#include <mach\/mach_init.h>\n#endif\n\nnamespace disk_cache {\n\nint64 GetFreeDiskSpace(const std::wstring& path) {\n struct statvfs stats;\n if (statvfs(WideToUTF8(path).c_str(), &stats) != 0) {\n return -1;\n }\n return static_cast<int64>(stats.f_bavail) * stats.f_frsize;\n}\n\nint64 GetSystemMemory() {\n#if defined(OS_LINUX)\n \/\/ _SC_PHYS_PAGES is not part of POSIX and not available on OS X\n long pages = sysconf(_SC_PHYS_PAGES);\n if (pages == -1) {\n return -1;\n }\n long page_size = sysconf(_SC_PAGE_SIZE);\n if (page_size == -1) {\n return -1;\n }\n int64 result = static_cast<int64>(pages) * page_size;\n DCHECK(result > 0);\n return result;\n#elif defined(OS_MACOSX)\n struct host_basic_info hostinfo;\n mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;\n int result = host_info(mach_host_self(),\n HOST_BASIC_INFO,\n reinterpret_cast<host_info_t>(&hostinfo),\n &count);\n DCHECK_EQ(HOST_BASIC_INFO_COUNT, count);\n return (result == KERN_SUCCESS) ? hostinfo.max_mem : -1;\n#else\n NOTIMPLEMENTED();\n return -1;\n#endif\n}\n\nbool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {\n \/\/ Just use the version from base.\n return file_util::Move(from_path.c_str(), to_path.c_str());\n}\n\nvoid DeleteCache(const std::wstring& path, bool remove_folder) {\n if (remove_folder) {\n file_util::Delete(path, false);\n } else {\n std::wstring name(path);\n \/\/ TODO(rvargas): Fix this after file_util::delete is fixed.\n \/\/ file_util::AppendToPath(&name, L\"*\");\n file_util::Delete(name, true);\n }\n}\n\nbool DeleteCacheFile(const std::wstring& name) {\n return file_util::Delete(name, false);\n}\n\nvoid WaitForPendingIO(int* num_pending_io) {\n if (*num_pending_io) {\n NOTIMPLEMENTED();\n }\n}\n\n} \/\/ namespace disk_cache\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: interact.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 07:58: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\n#include \"interact.hxx\"\n\n#include \"com\/sun\/star\/java\/JavaDisabledException.hpp\"\n#include \"com\/sun\/star\/java\/JavaVMCreationFailureException.hpp\"\n#include \"com\/sun\/star\/task\/XInteractionAbort.hpp\"\n#include \"com\/sun\/star\/task\/XInteractionRetry.hpp\"\n#include \"com\/sun\/star\/task\/XInteractionContinuation.hpp\"\n#include \"cppuhelper\/implbase1.hxx\"\n#include \"osl\/mutex.hxx\"\n\nnamespace css = com::sun::star;\n\nusing stoc_javavm::InteractionRequest;\n\nnamespace {\n\nclass AbortContinuation:\n public cppu::WeakImplHelper1< css::task::XInteractionAbort >\n{\npublic:\n inline AbortContinuation() {}\n\n virtual inline void SAL_CALL select() throw (css::uno::RuntimeException) {}\n\nprivate:\n AbortContinuation(AbortContinuation &); \/\/ not implemented\n void operator =(AbortContinuation); \/\/ not implemented\n\n virtual inline ~AbortContinuation() {}\n};\n\n}\n\nclass InteractionRequest::RetryContinuation:\n public cppu::WeakImplHelper1< css::task::XInteractionRetry >\n{\npublic:\n inline RetryContinuation(): m_bSelected(false) {}\n\n virtual void SAL_CALL select() throw (css::uno::RuntimeException);\n\n bool isSelected() const;\n\nprivate:\n RetryContinuation(RetryContinuation &); \/\/ not implemented\n void operator =(RetryContinuation); \/\/ not implemented\n\n virtual inline ~RetryContinuation() {}\n\n mutable osl::Mutex m_aMutex;\n bool m_bSelected;\n};\n\nvoid SAL_CALL InteractionRequest::RetryContinuation::select()\n throw (css::uno::RuntimeException)\n{\n osl::MutexGuard aGuard(m_aMutex);\n m_bSelected = true;\n}\n\nbool InteractionRequest::RetryContinuation::isSelected() const\n{\n osl::MutexGuard aGuard(m_aMutex);\n return m_bSelected;\n}\n\nInteractionRequest::InteractionRequest(css::uno::Any const & rRequest):\n m_aRequest(rRequest)\n{\n m_aContinuations.realloc(2);\n m_xRetryContinuation = new RetryContinuation;\n m_aContinuations[0] = new AbortContinuation;\n m_aContinuations[1] = m_xRetryContinuation.get();\n}\n\ncss::uno::Any SAL_CALL InteractionRequest::getRequest()\n throw (css::uno::RuntimeException)\n{\n return m_aRequest;\n}\n\ncss::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >\nSAL_CALL InteractionRequest::getContinuations()\n throw (css::uno::RuntimeException)\n{\n return m_aContinuations;\n}\n\nbool InteractionRequest::retry() const\n{\n return m_xRetryContinuation.is() && m_xRetryContinuation->isSelected();\n}\n\nInteractionRequest::~InteractionRequest()\n{}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.8.36); FILE MERGED 2006\/09\/01 17:41:12 kaib 1.8.36.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: interact.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 17:30: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_stoc.hxx\"\n\n#include \"interact.hxx\"\n\n#include \"com\/sun\/star\/java\/JavaDisabledException.hpp\"\n#include \"com\/sun\/star\/java\/JavaVMCreationFailureException.hpp\"\n#include \"com\/sun\/star\/task\/XInteractionAbort.hpp\"\n#include \"com\/sun\/star\/task\/XInteractionRetry.hpp\"\n#include \"com\/sun\/star\/task\/XInteractionContinuation.hpp\"\n#include \"cppuhelper\/implbase1.hxx\"\n#include \"osl\/mutex.hxx\"\n\nnamespace css = com::sun::star;\n\nusing stoc_javavm::InteractionRequest;\n\nnamespace {\n\nclass AbortContinuation:\n public cppu::WeakImplHelper1< css::task::XInteractionAbort >\n{\npublic:\n inline AbortContinuation() {}\n\n virtual inline void SAL_CALL select() throw (css::uno::RuntimeException) {}\n\nprivate:\n AbortContinuation(AbortContinuation &); \/\/ not implemented\n void operator =(AbortContinuation); \/\/ not implemented\n\n virtual inline ~AbortContinuation() {}\n};\n\n}\n\nclass InteractionRequest::RetryContinuation:\n public cppu::WeakImplHelper1< css::task::XInteractionRetry >\n{\npublic:\n inline RetryContinuation(): m_bSelected(false) {}\n\n virtual void SAL_CALL select() throw (css::uno::RuntimeException);\n\n bool isSelected() const;\n\nprivate:\n RetryContinuation(RetryContinuation &); \/\/ not implemented\n void operator =(RetryContinuation); \/\/ not implemented\n\n virtual inline ~RetryContinuation() {}\n\n mutable osl::Mutex m_aMutex;\n bool m_bSelected;\n};\n\nvoid SAL_CALL InteractionRequest::RetryContinuation::select()\n throw (css::uno::RuntimeException)\n{\n osl::MutexGuard aGuard(m_aMutex);\n m_bSelected = true;\n}\n\nbool InteractionRequest::RetryContinuation::isSelected() const\n{\n osl::MutexGuard aGuard(m_aMutex);\n return m_bSelected;\n}\n\nInteractionRequest::InteractionRequest(css::uno::Any const & rRequest):\n m_aRequest(rRequest)\n{\n m_aContinuations.realloc(2);\n m_xRetryContinuation = new RetryContinuation;\n m_aContinuations[0] = new AbortContinuation;\n m_aContinuations[1] = m_xRetryContinuation.get();\n}\n\ncss::uno::Any SAL_CALL InteractionRequest::getRequest()\n throw (css::uno::RuntimeException)\n{\n return m_aRequest;\n}\n\ncss::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >\nSAL_CALL InteractionRequest::getContinuations()\n throw (css::uno::RuntimeException)\n{\n return m_aContinuations;\n}\n\nbool InteractionRequest::retry() const\n{\n return m_xRetryContinuation.is() && m_xRetryContinuation->isSelected();\n}\n\nInteractionRequest::~InteractionRequest()\n{}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: testjavavm.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 17:43:05 $\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_stoc.hxx\"\n\n\n#include <jni.h>\n\n\/\/#include <iostream>\n#include <stdio.h>\n#include <sal\/main.h>\n#include <rtl\/process.h>\n\n#include <cppuhelper\/servicefactory.hxx>\n#include <cppuhelper\/weak.hxx>\n#include <cppuhelper\/bootstrap.hxx>\n\n#include <com\/sun\/star\/registry\/XSimpleRegistry.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/lang\/XMultiComponentFactory.hpp>\n#include <com\/sun\/star\/java\/XJavaVM.hpp>\n#include <com\/sun\/star\/registry\/XImplementationRegistration.hpp>\n#include <com\/sun\/star\/java\/XJavaThreadRegister_11.hpp>\n\n\/\/#include <cppuhelper\/implbase1.hxx>\n\nusing namespace std;\nusing namespace rtl;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\n\/\/using namespace com::sun::star::reflection;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::registry;\nusing namespace com::sun::star::java;\n\n\nsal_Bool testJavaVM(const Reference< XMultiServiceFactory > & xMgr )\n{\n\n OUString sVMService( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.java.JavaVirtualMachine\"));\n Reference<XInterface> xXInt= xMgr->createInstance(sVMService);\n if( ! xXInt.is())\n return sal_False;\n Reference<XJavaVM> xVM( xXInt, UNO_QUERY);\n if( ! xVM.is())\n return sal_False;\n Reference<XJavaThreadRegister_11> xreg11(xVM, UNO_QUERY);\n if( ! xreg11.is())\n return sal_False;\n\n\n sal_Int8 arId[16];\n rtl_getGlobalProcessId((sal_uInt8*) arId);\n Any anyVM = xVM->getJavaVM( Sequence<sal_Int8>(arId, 16));\n if ( ! anyVM.hasValue())\n {\n OSL_ENSURE(0,\"could not get Java VM\");\n return sal_False;\n }\n\n sal_Bool b= xreg11->isThreadAttached();\n xreg11->registerThread();\n b= xreg11->isThreadAttached();\n xreg11->revokeThread();\n b= xreg11->isThreadAttached();\n\n\n b= xVM->isVMEnabled();\n b= xVM->isVMStarted();\n\n\n b= xVM->isVMEnabled();\n b= xVM->isVMStarted();\n\n\n JavaVM* _jvm= *(JavaVM**) anyVM.getValue();\n JNIEnv *p_env;\n if( _jvm->AttachCurrentThread((void**) &p_env, 0))\n return sal_False;\n\n\/\/ jclass aJProg = p_env->FindClass(\"TestJavaVM\");\n\/\/ if( p_env->ExceptionOccurred()){\n\/\/ p_env->ExceptionDescribe();\n\/\/ p_env->ExceptionClear();\n\/\/ }\n\/\/\n\/\/ jmethodID mid= p_env->GetStaticMethodID( aJProg,\"main\", \"([Ljava\/lang\/String;)V\");\n\n jclass cls = p_env->FindClass( \"TestJavaVM\");\n if (cls == 0) {\n OSL_TRACE( \"Can't find Prog class\\n\");\n exit(1);\n }\n\n\/\/ jmethodID methid = p_env->GetStaticMethodID( cls, \"main\", \"([Ljava\/lang\/String;)V\");\n\/\/ if (methid == 0) {\n\/\/ OSL_TRACE(\"Can't find Prog.main\\n\");\n\/\/ exit(1);\n\/\/ }\n\n\/\/ jstring jstr = p_env->NewStringUTF(\" from C!\");\n\/\/ if (jstr == 0) {\n\/\/ OSL_TRACE(\"Out of memory\\n\");\n\/\/ exit(1);\n\/\/ }\n\/\/ jobjectArray args = p_env->NewObjectArray( 1,\n\/\/ p_env->FindClass(\"java\/lang\/String\"), jstr);\n\/\/ if (args == 0) {\n\/\/ OSL_TRACE( \"Out of memory\\n\");\n\/\/ exit(1);\n\/\/ }\n\/\/ p_env->CallStaticVoidMethod( cls, methid, args);\n\n\n jmethodID id = p_env->GetStaticMethodID( cls, \"getInt\", \"()I\");\n if( id)\n {\n jint _i= p_env->CallStaticIntMethod(cls, id);\n }\n\n if( p_env->ExceptionOccurred()){\n p_env->ExceptionDescribe();\n p_env->ExceptionClear();\n }\n\n\n _jvm->DetachCurrentThread();\n return sal_True;\n}\n\nSAL_IMPLEMENT_MAIN()\n{\n Reference<XSimpleRegistry> xreg= createSimpleRegistry();\n xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM(\"applicat.rdb\")),\n sal_False, sal_False );\n\n Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg);\n Reference<XMultiComponentFactory> fac= context->getServiceManager();\n Reference<XMultiServiceFactory> xMgr( fac, UNO_QUERY);\n\n sal_Bool bSucc = sal_False;\n try\n {\n OUString sImplReg(RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.registry.ImplementationRegistration\"));\n Reference<com::sun::star::registry::XImplementationRegistration> xImplReg(\n xMgr->createInstance( sImplReg ), UNO_QUERY );\n OSL_ENSURE( xImplReg.is(), \"### no impl reg!\" );\n\n\n OUString sLibLoader( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.loader.SharedLibrary\"));\n OUString sJenLib(\n RTL_CONSTASCII_USTRINGPARAM( \"javavm.uno\" SAL_DLLEXTENSION ) );\n xImplReg->registerImplementation(\n sLibLoader, sJenLib, Reference< XSimpleRegistry >() );\n\n bSucc = testJavaVM( xMgr );\n }\n catch (Exception & rExc)\n {\n OSL_ENSURE( sal_False, \"### exception occured!\" );\n OString aMsg( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_TRACE( \"### exception occured: \" );\n OSL_TRACE( aMsg.getStr() );\n OSL_TRACE( \"\\n\" );\n }\n\n Reference< XComponent > xCompContext( context, UNO_QUERY );\n xCompContext->dispose();\n printf(\"javavm %s\", bSucc ? \"succeeded\" : \"failed\");\n\/\/ cout << \"javavm \" << (bSucc ? \"succeeded\" : \"failed\") << \" !\" << endl;\n return (bSucc ? 0 : -1);\n}\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.8.56); FILE MERGED 2008\/03\/31 07:26:15 rt 1.8.56.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: testjavavm.cxx,v $\n * $Revision: 1.9 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_stoc.hxx\"\n\n\n#include <jni.h>\n\n\/\/#include <iostream>\n#include <stdio.h>\n#include <sal\/main.h>\n#include <rtl\/process.h>\n\n#include <cppuhelper\/servicefactory.hxx>\n#include <cppuhelper\/weak.hxx>\n#include <cppuhelper\/bootstrap.hxx>\n\n#include <com\/sun\/star\/registry\/XSimpleRegistry.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/lang\/XMultiComponentFactory.hpp>\n#include <com\/sun\/star\/java\/XJavaVM.hpp>\n#include <com\/sun\/star\/registry\/XImplementationRegistration.hpp>\n#include <com\/sun\/star\/java\/XJavaThreadRegister_11.hpp>\n\n\/\/#include <cppuhelper\/implbase1.hxx>\n\nusing namespace std;\nusing namespace rtl;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\n\/\/using namespace com::sun::star::reflection;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::registry;\nusing namespace com::sun::star::java;\n\n\nsal_Bool testJavaVM(const Reference< XMultiServiceFactory > & xMgr )\n{\n\n OUString sVMService( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.java.JavaVirtualMachine\"));\n Reference<XInterface> xXInt= xMgr->createInstance(sVMService);\n if( ! xXInt.is())\n return sal_False;\n Reference<XJavaVM> xVM( xXInt, UNO_QUERY);\n if( ! xVM.is())\n return sal_False;\n Reference<XJavaThreadRegister_11> xreg11(xVM, UNO_QUERY);\n if( ! xreg11.is())\n return sal_False;\n\n\n sal_Int8 arId[16];\n rtl_getGlobalProcessId((sal_uInt8*) arId);\n Any anyVM = xVM->getJavaVM( Sequence<sal_Int8>(arId, 16));\n if ( ! anyVM.hasValue())\n {\n OSL_ENSURE(0,\"could not get Java VM\");\n return sal_False;\n }\n\n sal_Bool b= xreg11->isThreadAttached();\n xreg11->registerThread();\n b= xreg11->isThreadAttached();\n xreg11->revokeThread();\n b= xreg11->isThreadAttached();\n\n\n b= xVM->isVMEnabled();\n b= xVM->isVMStarted();\n\n\n b= xVM->isVMEnabled();\n b= xVM->isVMStarted();\n\n\n JavaVM* _jvm= *(JavaVM**) anyVM.getValue();\n JNIEnv *p_env;\n if( _jvm->AttachCurrentThread((void**) &p_env, 0))\n return sal_False;\n\n\/\/ jclass aJProg = p_env->FindClass(\"TestJavaVM\");\n\/\/ if( p_env->ExceptionOccurred()){\n\/\/ p_env->ExceptionDescribe();\n\/\/ p_env->ExceptionClear();\n\/\/ }\n\/\/\n\/\/ jmethodID mid= p_env->GetStaticMethodID( aJProg,\"main\", \"([Ljava\/lang\/String;)V\");\n\n jclass cls = p_env->FindClass( \"TestJavaVM\");\n if (cls == 0) {\n OSL_TRACE( \"Can't find Prog class\\n\");\n exit(1);\n }\n\n\/\/ jmethodID methid = p_env->GetStaticMethodID( cls, \"main\", \"([Ljava\/lang\/String;)V\");\n\/\/ if (methid == 0) {\n\/\/ OSL_TRACE(\"Can't find Prog.main\\n\");\n\/\/ exit(1);\n\/\/ }\n\n\/\/ jstring jstr = p_env->NewStringUTF(\" from C!\");\n\/\/ if (jstr == 0) {\n\/\/ OSL_TRACE(\"Out of memory\\n\");\n\/\/ exit(1);\n\/\/ }\n\/\/ jobjectArray args = p_env->NewObjectArray( 1,\n\/\/ p_env->FindClass(\"java\/lang\/String\"), jstr);\n\/\/ if (args == 0) {\n\/\/ OSL_TRACE( \"Out of memory\\n\");\n\/\/ exit(1);\n\/\/ }\n\/\/ p_env->CallStaticVoidMethod( cls, methid, args);\n\n\n jmethodID id = p_env->GetStaticMethodID( cls, \"getInt\", \"()I\");\n if( id)\n {\n jint _i= p_env->CallStaticIntMethod(cls, id);\n }\n\n if( p_env->ExceptionOccurred()){\n p_env->ExceptionDescribe();\n p_env->ExceptionClear();\n }\n\n\n _jvm->DetachCurrentThread();\n return sal_True;\n}\n\nSAL_IMPLEMENT_MAIN()\n{\n Reference<XSimpleRegistry> xreg= createSimpleRegistry();\n xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM(\"applicat.rdb\")),\n sal_False, sal_False );\n\n Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg);\n Reference<XMultiComponentFactory> fac= context->getServiceManager();\n Reference<XMultiServiceFactory> xMgr( fac, UNO_QUERY);\n\n sal_Bool bSucc = sal_False;\n try\n {\n OUString sImplReg(RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.registry.ImplementationRegistration\"));\n Reference<com::sun::star::registry::XImplementationRegistration> xImplReg(\n xMgr->createInstance( sImplReg ), UNO_QUERY );\n OSL_ENSURE( xImplReg.is(), \"### no impl reg!\" );\n\n\n OUString sLibLoader( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.loader.SharedLibrary\"));\n OUString sJenLib(\n RTL_CONSTASCII_USTRINGPARAM( \"javavm.uno\" SAL_DLLEXTENSION ) );\n xImplReg->registerImplementation(\n sLibLoader, sJenLib, Reference< XSimpleRegistry >() );\n\n bSucc = testJavaVM( xMgr );\n }\n catch (Exception & rExc)\n {\n OSL_ENSURE( sal_False, \"### exception occured!\" );\n OString aMsg( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_TRACE( \"### exception occured: \" );\n OSL_TRACE( aMsg.getStr() );\n OSL_TRACE( \"\\n\" );\n }\n\n Reference< XComponent > xCompContext( context, UNO_QUERY );\n xCompContext->dispose();\n printf(\"javavm %s\", bSucc ? \"succeeded\" : \"failed\");\n\/\/ cout << \"javavm \" << (bSucc ? \"succeeded\" : \"failed\") << \" !\" << endl;\n return (bSucc ? 0 : -1);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* This pass is meant to show how one uses the Knowledge Construction Engine\n * (KCE). It's pretty simple. Running this pass requires a lot more work and\n * I'm...heh....working on that. \n * - Joshua Scoggins (8\/12\/2012)\n *\/\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Analysis\/LoopInfo.h\"\n#include \"llvm\/Analysis\/RegionInfo.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/DenseSet.h\"\n#include \"KnowledgeConstructionEngine.h\"\n#include \"LLVMWrapper.h\"\n#include \"JSEdgeRemoval.h\"\n#include \"PassDependencies.h\"\nextern \"C\" {\n #include \"clips.h\"\n}\n\nusing namespace llvm;\nchar nilObject[41] = \"(nil of ConstantPointerNull (Pointer 0))\";\nnamespace {\n struct KnowledgeConstruction : public FunctionPass {\n static char ID;\n public:\n KnowledgeConstruction() : FunctionPass(ID) {\n \/\/InitializeRuntimeAnalyzer();\n }\n virtual void getAnalysisUsage(AnalysisUsage &Info) const {\n Info.addRequired<LoopInfo>();\n Info.addRequired<RegionInfo>();\n }\n virtual bool runOnFunction(Function& fn) {\n\t\t\treturn false;\n \/\/do not actually wavefront schedule if we only have one block\n\t\t\t\/*\n if(fn.size() > 1) {\n char* funcName = (char*)fn.getName().data();\n DenseMap<PointerAddress, std::string> translation;\n std::pair<PointerAddress, std::string> pair(0,\"nil\");\n translation.insert(pair);\n FunctionNamer namer (translation);\n Reset();\n MakeInstance(nilObject);\n ModifyFunctionContents(fn, namer);\n LoopInfo &li = getAnalysis<LoopInfo>();\n RouteLoopInfo(li, funcName, namer);\n RegionInfo &ri = getAnalysis<RegionInfo>();\n llvm::Region* top = ri.getTopLevelRegion();\n Route(top, funcName, namer);\n Run(-1L);\n return true;\n } else {\n return false;\n }\n\t\t\t*\/\n }\n };\n}\nchar KnowledgeConstruction::ID = 0;\nINITIALIZE_PASS_BEGIN(KnowledgeConstruction, \"knowledge\", \"Knowledge constructor\", false, false)\nINITIALIZE_PASS_END(KnowledgeConstruction, \"knowledge\", \"Knowledge constructor\", false, false)\n\/\/for opt\nstatic RegisterPass<KnowledgeConstruction> X(\"knowledge\", \"Knowledge constructor\", false, false);\n<commit_msg>Commented out the global nilObject<commit_after>\/* This pass is meant to show how one uses the Knowledge Construction Engine\n * (KCE). It's pretty simple. Running this pass requires a lot more work and\n * I'm...heh....working on that. \n * - Joshua Scoggins (8\/12\/2012)\n *\/\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Analysis\/LoopInfo.h\"\n#include \"llvm\/Analysis\/RegionInfo.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/DenseSet.h\"\n#include \"KnowledgeConstructionEngine.h\"\n#include \"LLVMWrapper.h\"\n#include \"JSEdgeRemoval.h\"\n#include \"PassDependencies.h\"\nextern \"C\" {\n #include \"clips.h\"\n}\n\nusing namespace llvm;\n\/\/char nilObject[41] = \"(nil of ConstantPointerNull (Pointer 0))\";\nnamespace {\n struct KnowledgeConstruction : public FunctionPass {\n static char ID;\n public:\n KnowledgeConstruction() : FunctionPass(ID) {\n \/\/InitializeRuntimeAnalyzer();\n }\n virtual void getAnalysisUsage(AnalysisUsage &Info) const {\n Info.addRequired<LoopInfo>();\n Info.addRequired<RegionInfo>();\n }\n virtual bool runOnFunction(Function& fn) {\n\t\t\treturn false;\n \/\/do not actually wavefront schedule if we only have one block\n\t\t\t\/*\n if(fn.size() > 1) {\n char* funcName = (char*)fn.getName().data();\n DenseMap<PointerAddress, std::string> translation;\n std::pair<PointerAddress, std::string> pair(0,\"nil\");\n translation.insert(pair);\n FunctionNamer namer (translation);\n Reset();\n MakeInstance(nilObject);\n ModifyFunctionContents(fn, namer);\n LoopInfo &li = getAnalysis<LoopInfo>();\n RouteLoopInfo(li, funcName, namer);\n RegionInfo &ri = getAnalysis<RegionInfo>();\n llvm::Region* top = ri.getTopLevelRegion();\n Route(top, funcName, namer);\n Run(-1L);\n return true;\n } else {\n return false;\n }\n\t\t\t*\/\n }\n };\n}\nchar KnowledgeConstruction::ID = 0;\nINITIALIZE_PASS_BEGIN(KnowledgeConstruction, \"knowledge\", \"Knowledge constructor\", false, false)\nINITIALIZE_PASS_END(KnowledgeConstruction, \"knowledge\", \"Knowledge constructor\", false, false)\n\/\/for opt\nstatic RegisterPass<KnowledgeConstruction> X(\"knowledge\", \"Knowledge constructor\", false, false);\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, Willow Garage, Inc.\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 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 * $Id: pointimage_msgto_pcd.cpp 33238 2010-03-11 00:46:58Z rusu $\n *\n *\/\n\n\/\/ ROS core\n#include <boost\/thread\/mutex.hpp>\n\/\/ PCL includes\n#include <pcl\/common\/io.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/point_types.h>\n#include <pcl\/range_image\/range_image_planar.h>\n#include <pcl\/common\/common_headers.h>\n\n#include <pcl_visualization\/pcl_visualizer.h>\n#include \"pcl_visualization\/range_image_visualizer.h\"\n\nusing namespace std;\nusing namespace pcl;\nusing namespace pcl_visualization;\ntypedef PointXYZ PointType;\n\nfloat angular_resolution = 0.5f, \/\/ Resolution of the range image\n noise_level = 0.0f, \/\/ Distance in which the z-buffer averages instead of taking the minimum\n min_range = 0.0f; \/\/ Minimum range for the range image creation\nint border_size = 0; \/\/ Additional border around the range image\nRangeImage::CoordinateFrame coordinate_frame = RangeImage::CAMERA_FRAME;\nint source = 0; \/\/ Default: Use PointCloud2\n\nvoid \nprintUsage (const char* progName)\n{\n cout << \"\\n\\nUsage: \"<<progName<<\" [options] input:=<yourInput>\\n\\n\"\n << \"Options:\\n\"\n << \"-------------------------------------------\\n\"\n << \"-c <int> source coordinate frame (default \"<<coordinate_frame<<\")\\n\"\n << \"-s source used to create the range image: \"\n << \"0 PointCloud2 (default), 1 depth image, 2 disparity image .\\n\"\n << \"-r <float> angular resolution in degrees (default \"<<angular_resolution<<\")\\n\"\n << \"-h this help\\n\"\n << \"\\n\\n\";\n}\n\nsensor_msgs::PointCloud2ConstPtr cloud_msg, old_cloud_msg;\nsensor_msgs::ImageConstPtr depth_image_msg, old_depth_image_msg;\nstereo_msgs::DisparityImageConstPtr disparity_image_msg, old_disparity_image_msg;\nsensor_msgs::CameraInfoConstPtr camera_info_msg;\nboost::mutex m;\n\nvoid\ndisparity_image_msg_cb (const stereo_msgs::DisparityImageConstPtr& msg)\n{\n m.lock ();\n disparity_image_msg = msg;\n m.unlock ();\n}\n\nvoid\ndepth_image_msg_cb (const sensor_msgs::ImageConstPtr& msg)\n{\n m.lock ();\n \/\/std::cout << \"Received depth image of size \"<<msg->width<<\"x\"<<msg->height<<\".\\n\";\n depth_image_msg = msg;\n m.unlock ();\n}\n\nvoid\ncloud_msg_cb (const sensor_msgs::PointCloud2ConstPtr& msg)\n{\n m.lock ();\n cloud_msg = msg;\n m.unlock ();\n}\n\nvoid\ncamera_info_msg_cb (const sensor_msgs::CameraInfoConstPtr& msg)\n{\n m.lock ();\n \/\/std::cout << \"Received camera info: \" << \"width=\"<<msg->width<<\", height=\"<<msg->height<<\", \"\n \/\/<< \"center_x=\"<<msg->P[2]<<\", center_y=\"<<msg->P[6]<<\", \"\n \/\/<<\"fl_x=\"<<msg->P[0]<<\", fl_y=\"<<msg->P[5]<<\".\\n\";\n camera_info_msg = msg;\n m.unlock ();\n}\n\nint\nmain (int argc, char** argv)\n{\n \/\/ Read command line arguments.\n for (char c; (c = getopt (argc, argv, \"s:hc:r:\")) != -1; ) \n {\n switch (c) \n {\n case 'c':\n coordinate_frame = RangeImage::CoordinateFrame (strtol (optarg, NULL, 0));\n break;\n case 'r':\n {\n angular_resolution = strtod (optarg, NULL);\n cout << PVARN(angular_resolution);\n break;\n }\n case 's':\n {\n source = strtol (optarg, NULL, 0);\n if (source < 0 || source > 2)\n {\n cout << \"Source \"<<source<<\" is unknown.\\n\";\n exit (0);\n }\n cout << \"Receiving \"<<(source==0 ? \"point clouds\" : (source==1 ? \"depth images\" : \"disparity images\"))<<\".\\n\";\n break;\n }\n case 'h':\n default:\n printUsage (argv[0]);\n exit (0);\n }\n }\n angular_resolution = deg2rad (angular_resolution);\n \n ros::init (argc, argv, \"tutorial_range_image_live_viewer\");\n ros::NodeHandle node_handle;\n ros::Subscriber subscriber, subscriber2;\n \n if (node_handle.resolveName(\"input\")==\"\/input\")\n std::cerr << \"Did you forget input:=<your topic>?\\n\";\n \n if (source == 0)\n subscriber = node_handle.subscribe (\"input\", 1, cloud_msg_cb);\n else if (source == 1)\n {\n if (node_handle.resolveName(\"input2\")==\"\/input2\")\n std::cerr << \"Did you forget input2:=<your camera_info_topic>?\\n\";\n subscriber = node_handle.subscribe (\"input\", 1, depth_image_msg_cb);\n subscriber2 = node_handle.subscribe (\"input2\", 1, camera_info_msg_cb);\n }\n else if (source == 2)\n subscriber = node_handle.subscribe (\"input\", 1, disparity_image_msg_cb);\n \n PCLVisualizer viewer (argc, argv, \"Live viewer - point cloud\");\n RangeImageVisualizer range_image_widget(\"Live viewer - range image\");\n \n RangeImagePlanar* range_image_planar;\n RangeImage* range_image;\n if (source==0)\n range_image = new RangeImage;\n else\n {\n range_image_planar = new RangeImagePlanar;\n range_image = range_image_planar;\n }\n \n while (node_handle.ok ())\n {\n usleep (10000);\n viewer.spinOnce (10);\n RangeImageVisualizer::spinOnce ();\n ros::spinOnce ();\n \n if (source==0)\n {\n \/\/ If no new message received: continue\n if (!cloud_msg || cloud_msg == old_cloud_msg)\n continue;\n old_cloud_msg = cloud_msg;\n \n Eigen::Affine3f sensor_pose(Eigen::Affine3f::Identity());\n PointCloud<PointWithViewpoint> far_ranges;\n RangeImage::extractFarRanges(*cloud_msg, far_ranges);\n if (pcl::getFieldIndex(*cloud_msg, \"vp_x\")>=0)\n {\n PointCloud<PointWithViewpoint> tmp_pc;\n fromROSMsg(*cloud_msg, tmp_pc);\n Eigen::Vector3f average_viewpoint = RangeImage::getAverageViewPoint(tmp_pc);\n sensor_pose = Eigen::Translation3f(average_viewpoint) * sensor_pose;\n }\n PointCloud<PointType> point_cloud;\n fromROSMsg(*cloud_msg, point_cloud);\n range_image->createFromPointCloud(point_cloud, angular_resolution, deg2rad(360.0f), deg2rad(180.0f),\n sensor_pose, coordinate_frame, noise_level, min_range, border_size);\n }\n else if (source==1)\n {\n \/\/ If no new message received: continue\n if (!depth_image_msg || depth_image_msg == old_depth_image_msg || !camera_info_msg)\n continue;\n old_depth_image_msg = depth_image_msg;\n range_image_planar->setDepthImage(reinterpret_cast<const float*> (&depth_image_msg->data[0]),\n depth_image_msg->width, depth_image_msg->height,\n camera_info_msg->P[2], camera_info_msg->P[6],\n camera_info_msg->P[0], camera_info_msg->P[5], angular_resolution);\n }\n else if (source==2)\n {\n \/\/ If no new message received: continue\n if (!disparity_image_msg || disparity_image_msg == old_disparity_image_msg)\n continue;\n old_disparity_image_msg = disparity_image_msg;\n range_image_planar->setDisparityImage(reinterpret_cast<const float*> (&disparity_image_msg->image.data[0]),\n disparity_image_msg->image.width, disparity_image_msg->image.height,\n disparity_image_msg->f, disparity_image_msg->T, angular_resolution);\n }\n\n range_image_widget.setRangeImage (*range_image);\n viewer.removePointCloud (\"range image cloud\");\n pcl_visualization::PointCloudColorHandlerCustom<pcl::PointWithRange> color_handler_cloud(*range_image,\n 200, 200, 200);\n viewer.addPointCloud (*range_image, color_handler_cloud, \"range image cloud\");\n }\n}\n<commit_msg>removed <commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 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 \"apps\/ui\/views\/app_window_frame_view.h\"\n\n#include \"apps\/ui\/native_app_window.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"extensions\/common\/draggable_region.h\"\n#include \"grit\/theme_resources.h\"\n#include \"grit\/ui_strings.h\" \/\/ Accessibility names\n#include \"third_party\/skia\/include\/core\/SkPaint.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/path.h\"\n#include \"ui\/views\/controls\/button\/image_button.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/views_delegate.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/widget\/widget_delegate.h\"\n\n#if defined(USE_AURA)\n#include \"ui\/aura\/env.h\"\n#include \"ui\/aura\/window.h\"\n#endif\n\nnamespace {\n\/\/ Height of the chrome-style caption, in pixels.\nconst int kCaptionHeight = 25;\n} \/\/ namespace\n\nnamespace apps {\n\nconst char AppWindowFrameView::kViewClassName[] =\n \"browser\/ui\/views\/extensions\/AppWindowFrameView\";\n\nAppWindowFrameView::AppWindowFrameView(NativeAppWindow* window)\n : window_(window),\n frame_(NULL),\n close_button_(NULL),\n maximize_button_(NULL),\n restore_button_(NULL),\n minimize_button_(NULL),\n resize_inside_bounds_size_(0),\n resize_outside_bounds_size_(0),\n resize_area_corner_size_(0) {}\n\nAppWindowFrameView::~AppWindowFrameView() {}\n\nvoid AppWindowFrameView::Init(views::Widget* frame,\n int resize_inside_bounds_size,\n int resize_outside_bounds_size,\n int resize_outside_scale_for_touch,\n int resize_area_corner_size) {\n frame_ = frame;\n resize_inside_bounds_size_ = resize_inside_bounds_size;\n resize_outside_bounds_size_ = resize_outside_bounds_size;\n resize_area_corner_size_ = resize_area_corner_size;\n\n if (!window_->IsFrameless()) {\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n close_button_ = new views::ImageButton(this);\n close_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE).ToImageSkia());\n close_button_->SetImage(\n views::CustomButton::STATE_HOVERED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE_H).ToImageSkia());\n close_button_->SetImage(\n views::CustomButton::STATE_PRESSED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE_P).ToImageSkia());\n close_button_->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));\n AddChildView(close_button_);\n maximize_button_ = new views::ImageButton(this);\n maximize_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MAXIMIZE).ToImageSkia());\n maximize_button_->SetImage(\n views::CustomButton::STATE_HOVERED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MAXIMIZE_H).ToImageSkia());\n maximize_button_->SetImage(\n views::CustomButton::STATE_PRESSED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MAXIMIZE_P).ToImageSkia());\n maximize_button_->SetImage(\n views::CustomButton::STATE_DISABLED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MAXIMIZE_D).ToImageSkia());\n maximize_button_->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_APP_ACCNAME_MAXIMIZE));\n AddChildView(maximize_button_);\n restore_button_ = new views::ImageButton(this);\n restore_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_RESTORE).ToImageSkia());\n restore_button_->SetImage(\n views::CustomButton::STATE_HOVERED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_RESTORE_H).ToImageSkia());\n restore_button_->SetImage(\n views::CustomButton::STATE_PRESSED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_RESTORE_P).ToImageSkia());\n restore_button_->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_APP_ACCNAME_RESTORE));\n AddChildView(restore_button_);\n minimize_button_ = new views::ImageButton(this);\n minimize_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MINIMIZE).ToImageSkia());\n minimize_button_->SetImage(\n views::CustomButton::STATE_HOVERED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MINIMIZE_H).ToImageSkia());\n minimize_button_->SetImage(\n views::CustomButton::STATE_PRESSED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MINIMIZE_P).ToImageSkia());\n minimize_button_->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_APP_ACCNAME_MINIMIZE));\n AddChildView(minimize_button_);\n }\n\n#if defined(USE_AURA)\n aura::Window* window = frame->GetNativeWindow();\n \/\/ Ensure we get resize cursors just inside our bounds as well.\n \/\/ TODO(jeremya): do we need to update these when in fullscreen\/maximized?\n window->set_hit_test_bounds_override_inner(\n gfx::Insets(resize_inside_bounds_size_,\n resize_inside_bounds_size_,\n resize_inside_bounds_size_,\n resize_inside_bounds_size_));\n#endif\n}\n\n\/\/ views::NonClientFrameView implementation.\n\ngfx::Rect AppWindowFrameView::GetBoundsForClientView() const {\n if (window_->IsFrameless() || frame_->IsFullscreen())\n return bounds();\n return gfx::Rect(\n 0, kCaptionHeight, width(), std::max(0, height() - kCaptionHeight));\n}\n\ngfx::Rect AppWindowFrameView::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n if (window_->IsFrameless()) {\n gfx::Rect window_bounds = client_bounds;\n \/\/ Enforce minimum size (1, 1) in case that client_bounds is passed with\n \/\/ empty size. This could occur when the frameless window is being\n \/\/ initialized.\n if (window_bounds.IsEmpty()) {\n window_bounds.set_width(1);\n window_bounds.set_height(1);\n }\n return window_bounds;\n }\n\n int closeButtonOffsetX = (kCaptionHeight - close_button_->height()) \/ 2;\n int header_width = close_button_->width() + closeButtonOffsetX * 2;\n return gfx::Rect(client_bounds.x(),\n std::max(0, client_bounds.y() - kCaptionHeight),\n std::max(header_width, client_bounds.width()),\n client_bounds.height() + kCaptionHeight);\n}\n\nint AppWindowFrameView::NonClientHitTest(const gfx::Point& point) {\n if (frame_->IsFullscreen())\n return HTCLIENT;\n\n gfx::Rect expanded_bounds = bounds();\n if (resize_outside_bounds_size_)\n expanded_bounds.Inset(gfx::Insets(-resize_outside_bounds_size_,\n -resize_outside_bounds_size_,\n -resize_outside_bounds_size_,\n -resize_outside_bounds_size_));\n \/\/ Points outside the (possibly expanded) bounds can be discarded.\n if (!expanded_bounds.Contains(point))\n return HTNOWHERE;\n\n \/\/ Check the frame first, as we allow a small area overlapping the contents\n \/\/ to be used for resize handles.\n bool can_ever_resize = frame_->widget_delegate()\n ? frame_->widget_delegate()->CanResize()\n : false;\n \/\/ Don't allow overlapping resize handles when the window is maximized or\n \/\/ fullscreen, as it can't be resized in those states.\n int resize_border = (frame_->IsMaximized() || frame_->IsFullscreen())\n ? 0\n : resize_inside_bounds_size_;\n int frame_component = GetHTComponentForFrame(point,\n resize_border,\n resize_border,\n resize_area_corner_size_,\n resize_area_corner_size_,\n can_ever_resize);\n if (frame_component != HTNOWHERE)\n return frame_component;\n\n \/\/ Check for possible draggable region in the client area for the frameless\n \/\/ window.\n if (window_->IsFrameless()) {\n SkRegion* draggable_region = window_->GetDraggableRegion();\n if (draggable_region && draggable_region->contains(point.x(), point.y()))\n return HTCAPTION;\n }\n\n int client_component = frame_->client_view()->NonClientHitTest(point);\n if (client_component != HTNOWHERE)\n return client_component;\n\n \/\/ Then see if the point is within any of the window controls.\n if (close_button_ && close_button_->visible() &&\n close_button_->GetMirroredBounds().Contains(point)) {\n return HTCLOSE;\n }\n if ((maximize_button_ && maximize_button_->visible() &&\n maximize_button_->GetMirroredBounds().Contains(point)) ||\n (restore_button_ && restore_button_->visible() &&\n restore_button_->GetMirroredBounds().Contains(point))) {\n return HTMAXBUTTON;\n }\n if (minimize_button_ && minimize_button_->visible() &&\n minimize_button_->GetMirroredBounds().Contains(point)) {\n return HTMINBUTTON;\n }\n\n \/\/ Caption is a safe default.\n return HTCAPTION;\n}\n\nvoid AppWindowFrameView::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n \/\/ We got nothing to say about no window mask.\n}\n\n\/\/ views::View implementation.\n\ngfx::Size AppWindowFrameView::GetPreferredSize() {\n gfx::Size pref = frame_->client_view()->GetPreferredSize();\n gfx::Rect bounds(0, 0, pref.width(), pref.height());\n return frame_->non_client_view()\n ->GetWindowBoundsForClientBounds(bounds)\n .size();\n}\n\nvoid AppWindowFrameView::Layout() {\n if (window_->IsFrameless())\n return;\n gfx::Size close_size = close_button_->GetPreferredSize();\n const int kButtonOffsetY = 0;\n const int kButtonSpacing = 1;\n const int kRightMargin = 3;\n\n close_button_->SetBounds(width() - kRightMargin - close_size.width(),\n kButtonOffsetY,\n close_size.width(),\n close_size.height());\n\n bool can_ever_resize = frame_->widget_delegate()\n ? frame_->widget_delegate()->CanResize()\n : false;\n maximize_button_->SetEnabled(can_ever_resize);\n gfx::Size maximize_size = maximize_button_->GetPreferredSize();\n maximize_button_->SetBounds(\n close_button_->x() - kButtonSpacing - maximize_size.width(),\n kButtonOffsetY,\n maximize_size.width(),\n maximize_size.height());\n gfx::Size restore_size = restore_button_->GetPreferredSize();\n restore_button_->SetBounds(\n close_button_->x() - kButtonSpacing - restore_size.width(),\n kButtonOffsetY,\n restore_size.width(),\n restore_size.height());\n\n bool maximized = frame_->IsMaximized();\n maximize_button_->SetVisible(!maximized);\n restore_button_->SetVisible(maximized);\n if (maximized)\n maximize_button_->SetState(views::CustomButton::STATE_NORMAL);\n else\n restore_button_->SetState(views::CustomButton::STATE_NORMAL);\n\n gfx::Size minimize_size = minimize_button_->GetPreferredSize();\n minimize_button_->SetBounds(\n maximize_button_->x() - kButtonSpacing - minimize_size.width(),\n kButtonOffsetY,\n minimize_size.width(),\n minimize_size.height());\n}\n\nvoid AppWindowFrameView::OnPaint(gfx::Canvas* canvas) {\n if (window_->IsFrameless())\n return;\n\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n if (ShouldPaintAsActive()) {\n close_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE).ToImageSkia());\n } else {\n close_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE_U).ToImageSkia());\n }\n\n \/\/ TODO(jeremya): different look for inactive?\n SkPaint paint;\n paint.setAntiAlias(false);\n paint.setStyle(SkPaint::kFill_Style);\n paint.setColor(SK_ColorWHITE);\n gfx::Path path;\n path.moveTo(0, 0);\n path.lineTo(width(), 0);\n path.lineTo(width(), kCaptionHeight);\n path.lineTo(0, kCaptionHeight);\n path.close();\n canvas->DrawPath(path, paint);\n}\n\nconst char* AppWindowFrameView::GetClassName() const { return kViewClassName; }\n\ngfx::Size AppWindowFrameView::GetMinimumSize() {\n gfx::Size min_size = frame_->client_view()->GetMinimumSize();\n if (window_->IsFrameless())\n return min_size;\n\n \/\/ Ensure we can display the top of the caption area.\n gfx::Rect client_bounds = GetBoundsForClientView();\n min_size.Enlarge(0, client_bounds.y());\n \/\/ Ensure we have enough space for the window icon and buttons. We allow\n \/\/ the title string to collapse to zero width.\n int closeButtonOffsetX = (kCaptionHeight - close_button_->height()) \/ 2;\n int header_width = close_button_->width() + closeButtonOffsetX * 2;\n if (header_width > min_size.width())\n min_size.set_width(header_width);\n return min_size;\n}\n\ngfx::Size AppWindowFrameView::GetMaximumSize() {\n gfx::Size max_size = frame_->client_view()->GetMaximumSize();\n\n \/\/ Add to the client maximum size the height of any title bar and borders.\n gfx::Size client_size = GetBoundsForClientView().size();\n if (max_size.width())\n max_size.Enlarge(width() - client_size.width(), 0);\n if (max_size.height())\n max_size.Enlarge(0, height() - client_size.height());\n\n return max_size;\n}\n\n\/\/ views::ButtonListener implementation.\n\nvoid AppWindowFrameView::ButtonPressed(views::Button* sender,\n const ui::Event& event) {\n DCHECK(!window_->IsFrameless());\n if (sender == close_button_)\n frame_->Close();\n else if (sender == maximize_button_)\n frame_->Maximize();\n else if (sender == restore_button_)\n frame_->Restore();\n else if (sender == minimize_button_)\n frame_->Minimize();\n}\n\n} \/\/ namespace apps\n<commit_msg>Fix the \"Minimize\" button of app windows remaining hovered after restore.<commit_after>\/\/ Copyright 2014 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 \"apps\/ui\/views\/app_window_frame_view.h\"\n\n#include \"apps\/ui\/native_app_window.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"extensions\/common\/draggable_region.h\"\n#include \"grit\/theme_resources.h\"\n#include \"grit\/ui_strings.h\" \/\/ Accessibility names\n#include \"third_party\/skia\/include\/core\/SkPaint.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/path.h\"\n#include \"ui\/views\/controls\/button\/image_button.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/views_delegate.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/widget\/widget_delegate.h\"\n\n#if defined(USE_AURA)\n#include \"ui\/aura\/env.h\"\n#include \"ui\/aura\/window.h\"\n#endif\n\nnamespace {\n\/\/ Height of the chrome-style caption, in pixels.\nconst int kCaptionHeight = 25;\n} \/\/ namespace\n\nnamespace apps {\n\nconst char AppWindowFrameView::kViewClassName[] =\n \"browser\/ui\/views\/extensions\/AppWindowFrameView\";\n\nAppWindowFrameView::AppWindowFrameView(NativeAppWindow* window)\n : window_(window),\n frame_(NULL),\n close_button_(NULL),\n maximize_button_(NULL),\n restore_button_(NULL),\n minimize_button_(NULL),\n resize_inside_bounds_size_(0),\n resize_outside_bounds_size_(0),\n resize_area_corner_size_(0) {}\n\nAppWindowFrameView::~AppWindowFrameView() {}\n\nvoid AppWindowFrameView::Init(views::Widget* frame,\n int resize_inside_bounds_size,\n int resize_outside_bounds_size,\n int resize_outside_scale_for_touch,\n int resize_area_corner_size) {\n frame_ = frame;\n resize_inside_bounds_size_ = resize_inside_bounds_size;\n resize_outside_bounds_size_ = resize_outside_bounds_size;\n resize_area_corner_size_ = resize_area_corner_size;\n\n if (!window_->IsFrameless()) {\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n close_button_ = new views::ImageButton(this);\n close_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE).ToImageSkia());\n close_button_->SetImage(\n views::CustomButton::STATE_HOVERED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE_H).ToImageSkia());\n close_button_->SetImage(\n views::CustomButton::STATE_PRESSED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE_P).ToImageSkia());\n close_button_->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));\n AddChildView(close_button_);\n maximize_button_ = new views::ImageButton(this);\n maximize_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MAXIMIZE).ToImageSkia());\n maximize_button_->SetImage(\n views::CustomButton::STATE_HOVERED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MAXIMIZE_H).ToImageSkia());\n maximize_button_->SetImage(\n views::CustomButton::STATE_PRESSED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MAXIMIZE_P).ToImageSkia());\n maximize_button_->SetImage(\n views::CustomButton::STATE_DISABLED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MAXIMIZE_D).ToImageSkia());\n maximize_button_->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_APP_ACCNAME_MAXIMIZE));\n AddChildView(maximize_button_);\n restore_button_ = new views::ImageButton(this);\n restore_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_RESTORE).ToImageSkia());\n restore_button_->SetImage(\n views::CustomButton::STATE_HOVERED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_RESTORE_H).ToImageSkia());\n restore_button_->SetImage(\n views::CustomButton::STATE_PRESSED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_RESTORE_P).ToImageSkia());\n restore_button_->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_APP_ACCNAME_RESTORE));\n AddChildView(restore_button_);\n minimize_button_ = new views::ImageButton(this);\n minimize_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MINIMIZE).ToImageSkia());\n minimize_button_->SetImage(\n views::CustomButton::STATE_HOVERED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MINIMIZE_H).ToImageSkia());\n minimize_button_->SetImage(\n views::CustomButton::STATE_PRESSED,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_MINIMIZE_P).ToImageSkia());\n minimize_button_->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_APP_ACCNAME_MINIMIZE));\n AddChildView(minimize_button_);\n }\n\n#if defined(USE_AURA)\n aura::Window* window = frame->GetNativeWindow();\n \/\/ Ensure we get resize cursors just inside our bounds as well.\n \/\/ TODO(jeremya): do we need to update these when in fullscreen\/maximized?\n window->set_hit_test_bounds_override_inner(\n gfx::Insets(resize_inside_bounds_size_,\n resize_inside_bounds_size_,\n resize_inside_bounds_size_,\n resize_inside_bounds_size_));\n#endif\n}\n\n\/\/ views::NonClientFrameView implementation.\n\ngfx::Rect AppWindowFrameView::GetBoundsForClientView() const {\n if (window_->IsFrameless() || frame_->IsFullscreen())\n return bounds();\n return gfx::Rect(\n 0, kCaptionHeight, width(), std::max(0, height() - kCaptionHeight));\n}\n\ngfx::Rect AppWindowFrameView::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n if (window_->IsFrameless()) {\n gfx::Rect window_bounds = client_bounds;\n \/\/ Enforce minimum size (1, 1) in case that client_bounds is passed with\n \/\/ empty size. This could occur when the frameless window is being\n \/\/ initialized.\n if (window_bounds.IsEmpty()) {\n window_bounds.set_width(1);\n window_bounds.set_height(1);\n }\n return window_bounds;\n }\n\n int closeButtonOffsetX = (kCaptionHeight - close_button_->height()) \/ 2;\n int header_width = close_button_->width() + closeButtonOffsetX * 2;\n return gfx::Rect(client_bounds.x(),\n std::max(0, client_bounds.y() - kCaptionHeight),\n std::max(header_width, client_bounds.width()),\n client_bounds.height() + kCaptionHeight);\n}\n\nint AppWindowFrameView::NonClientHitTest(const gfx::Point& point) {\n if (frame_->IsFullscreen())\n return HTCLIENT;\n\n gfx::Rect expanded_bounds = bounds();\n if (resize_outside_bounds_size_)\n expanded_bounds.Inset(gfx::Insets(-resize_outside_bounds_size_,\n -resize_outside_bounds_size_,\n -resize_outside_bounds_size_,\n -resize_outside_bounds_size_));\n \/\/ Points outside the (possibly expanded) bounds can be discarded.\n if (!expanded_bounds.Contains(point))\n return HTNOWHERE;\n\n \/\/ Check the frame first, as we allow a small area overlapping the contents\n \/\/ to be used for resize handles.\n bool can_ever_resize = frame_->widget_delegate()\n ? frame_->widget_delegate()->CanResize()\n : false;\n \/\/ Don't allow overlapping resize handles when the window is maximized or\n \/\/ fullscreen, as it can't be resized in those states.\n int resize_border = (frame_->IsMaximized() || frame_->IsFullscreen())\n ? 0\n : resize_inside_bounds_size_;\n int frame_component = GetHTComponentForFrame(point,\n resize_border,\n resize_border,\n resize_area_corner_size_,\n resize_area_corner_size_,\n can_ever_resize);\n if (frame_component != HTNOWHERE)\n return frame_component;\n\n \/\/ Check for possible draggable region in the client area for the frameless\n \/\/ window.\n if (window_->IsFrameless()) {\n SkRegion* draggable_region = window_->GetDraggableRegion();\n if (draggable_region && draggable_region->contains(point.x(), point.y()))\n return HTCAPTION;\n }\n\n int client_component = frame_->client_view()->NonClientHitTest(point);\n if (client_component != HTNOWHERE)\n return client_component;\n\n \/\/ Then see if the point is within any of the window controls.\n if (close_button_ && close_button_->visible() &&\n close_button_->GetMirroredBounds().Contains(point)) {\n return HTCLOSE;\n }\n if ((maximize_button_ && maximize_button_->visible() &&\n maximize_button_->GetMirroredBounds().Contains(point)) ||\n (restore_button_ && restore_button_->visible() &&\n restore_button_->GetMirroredBounds().Contains(point))) {\n return HTMAXBUTTON;\n }\n if (minimize_button_ && minimize_button_->visible() &&\n minimize_button_->GetMirroredBounds().Contains(point)) {\n return HTMINBUTTON;\n }\n\n \/\/ Caption is a safe default.\n return HTCAPTION;\n}\n\nvoid AppWindowFrameView::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n \/\/ We got nothing to say about no window mask.\n}\n\n\/\/ views::View implementation.\n\ngfx::Size AppWindowFrameView::GetPreferredSize() {\n gfx::Size pref = frame_->client_view()->GetPreferredSize();\n gfx::Rect bounds(0, 0, pref.width(), pref.height());\n return frame_->non_client_view()\n ->GetWindowBoundsForClientBounds(bounds)\n .size();\n}\n\nvoid AppWindowFrameView::Layout() {\n if (window_->IsFrameless())\n return;\n gfx::Size close_size = close_button_->GetPreferredSize();\n const int kButtonOffsetY = 0;\n const int kButtonSpacing = 1;\n const int kRightMargin = 3;\n\n close_button_->SetBounds(width() - kRightMargin - close_size.width(),\n kButtonOffsetY,\n close_size.width(),\n close_size.height());\n\n bool can_ever_resize = frame_->widget_delegate()\n ? frame_->widget_delegate()->CanResize()\n : false;\n maximize_button_->SetEnabled(can_ever_resize);\n gfx::Size maximize_size = maximize_button_->GetPreferredSize();\n maximize_button_->SetBounds(\n close_button_->x() - kButtonSpacing - maximize_size.width(),\n kButtonOffsetY,\n maximize_size.width(),\n maximize_size.height());\n gfx::Size restore_size = restore_button_->GetPreferredSize();\n restore_button_->SetBounds(\n close_button_->x() - kButtonSpacing - restore_size.width(),\n kButtonOffsetY,\n restore_size.width(),\n restore_size.height());\n\n bool maximized = frame_->IsMaximized();\n maximize_button_->SetVisible(!maximized);\n restore_button_->SetVisible(maximized);\n if (maximized)\n maximize_button_->SetState(views::CustomButton::STATE_NORMAL);\n else\n restore_button_->SetState(views::CustomButton::STATE_NORMAL);\n\n gfx::Size minimize_size = minimize_button_->GetPreferredSize();\n minimize_button_->SetState(views::CustomButton::STATE_NORMAL);\n minimize_button_->SetBounds(\n maximize_button_->x() - kButtonSpacing - minimize_size.width(),\n kButtonOffsetY,\n minimize_size.width(),\n minimize_size.height());\n}\n\nvoid AppWindowFrameView::OnPaint(gfx::Canvas* canvas) {\n if (window_->IsFrameless())\n return;\n\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n if (ShouldPaintAsActive()) {\n close_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE).ToImageSkia());\n } else {\n close_button_->SetImage(\n views::CustomButton::STATE_NORMAL,\n rb.GetNativeImageNamed(IDR_APP_WINDOW_CLOSE_U).ToImageSkia());\n }\n\n \/\/ TODO(jeremya): different look for inactive?\n SkPaint paint;\n paint.setAntiAlias(false);\n paint.setStyle(SkPaint::kFill_Style);\n paint.setColor(SK_ColorWHITE);\n gfx::Path path;\n path.moveTo(0, 0);\n path.lineTo(width(), 0);\n path.lineTo(width(), kCaptionHeight);\n path.lineTo(0, kCaptionHeight);\n path.close();\n canvas->DrawPath(path, paint);\n}\n\nconst char* AppWindowFrameView::GetClassName() const { return kViewClassName; }\n\ngfx::Size AppWindowFrameView::GetMinimumSize() {\n gfx::Size min_size = frame_->client_view()->GetMinimumSize();\n if (window_->IsFrameless())\n return min_size;\n\n \/\/ Ensure we can display the top of the caption area.\n gfx::Rect client_bounds = GetBoundsForClientView();\n min_size.Enlarge(0, client_bounds.y());\n \/\/ Ensure we have enough space for the window icon and buttons. We allow\n \/\/ the title string to collapse to zero width.\n int closeButtonOffsetX = (kCaptionHeight - close_button_->height()) \/ 2;\n int header_width = close_button_->width() + closeButtonOffsetX * 2;\n if (header_width > min_size.width())\n min_size.set_width(header_width);\n return min_size;\n}\n\ngfx::Size AppWindowFrameView::GetMaximumSize() {\n gfx::Size max_size = frame_->client_view()->GetMaximumSize();\n\n \/\/ Add to the client maximum size the height of any title bar and borders.\n gfx::Size client_size = GetBoundsForClientView().size();\n if (max_size.width())\n max_size.Enlarge(width() - client_size.width(), 0);\n if (max_size.height())\n max_size.Enlarge(0, height() - client_size.height());\n\n return max_size;\n}\n\n\/\/ views::ButtonListener implementation.\n\nvoid AppWindowFrameView::ButtonPressed(views::Button* sender,\n const ui::Event& event) {\n DCHECK(!window_->IsFrameless());\n if (sender == close_button_)\n frame_->Close();\n else if (sender == maximize_button_)\n frame_->Maximize();\n else if (sender == restore_button_)\n frame_->Restore();\n else if (sender == minimize_button_)\n frame_->Minimize();\n}\n\n} \/\/ namespace apps\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n\nint main(){\n \/\/ open a file in read mode.\n ifstream infile; \n\n}\n<commit_msg>adding pass runner skeleton<commit_after>#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\/\/ vector with permutations of passorder\nvector<string> passOrder;\n\nvoid runOptimizationPasses(){\n\n for( int i = 0; i < passOrder.size() ; ++i ) {\n system(NULL);\n }\n}\n\n\/\/ print operator for vector<string>\nvoid operator<<(ostream& os, vector<string> V){\n for( vector<string>::iterator it = V.begin(); it != V.end() ; ++it ) {\n os << *it << endl;\n }\n}\n\nint main(){\n \/\/ open a file in read mode.\n ifstream infile; \n infile.open(\"events.1\");\n\n string opt_order;\n while(getline(infile,opt_order)) {\n passOrder.push_back(opt_order);\n }\n\n \/\/ this will potentially print the contents of events.1 file\n#ifdef VERBOSE\n cout << passOrder;\n#endif\n\n runOptimizationPasses();\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"common\/SignalVector.hpp\"\n\n#include <QAbstractTableModel>\n#include <QMimeData>\n#include <QStandardItem>\n#include <boost\/optional.hpp>\n\n#include <pajlada\/signals\/signalholder.hpp>\n\nnamespace chatterino {\n\ntemplate <typename TVectorItem>\nclass SignalVectorModel : public QAbstractTableModel,\n pajlada::Signals::SignalHolder\n{\npublic:\n SignalVectorModel(int columnCount, QObject *parent = nullptr)\n : QAbstractTableModel(parent)\n , columnCount_(columnCount)\n {\n for (int i = 0; i < columnCount; i++)\n {\n this->headerData_.emplace_back();\n }\n }\n\n void initialize(SignalVector<TVectorItem> *vec)\n {\n this->vector_ = vec;\n\n auto insert = [this](const SignalVectorItemEvent<TVectorItem> &args) {\n if (args.caller == this)\n {\n return;\n }\n \/\/ get row index\n int index = this->getModelIndexFromVectorIndex(args.index);\n assert(index >= 0 && index <= this->rows_.size());\n\n \/\/ get row items\n std::vector<QStandardItem *> row = this->createRow();\n this->getRowFromItem(args.item, row);\n\n \/\/ insert row\n index = this->beforeInsert(args.item, row, index);\n\n this->beginInsertRows(QModelIndex(), index, index);\n this->rows_.insert(this->rows_.begin() + index,\n Row(row, args.item));\n this->endInsertRows();\n };\n\n int i = 0;\n for (const TVectorItem &item : vec->raw())\n {\n SignalVectorItemEvent<TVectorItem> args{item, i++, 0};\n\n insert(args);\n }\n\n this->managedConnect(vec->itemInserted, insert);\n\n this->managedConnect(vec->itemRemoved, [this](auto args) {\n if (args.caller == this)\n {\n return;\n }\n\n int row = this->getModelIndexFromVectorIndex(args.index);\n assert(row >= 0 && row <= this->rows_.size());\n\n \/\/ remove row\n std::vector<QStandardItem *> items = this->rows_[row].items;\n\n this->beginRemoveRows(QModelIndex(), row, row);\n this->rows_.erase(this->rows_.begin() + row);\n this->endRemoveRows();\n\n this->afterRemoved(args.item, items, row);\n\n for (QStandardItem *item : items)\n {\n delete item;\n }\n });\n\n this->afterInit();\n }\n\n SignalVectorModel<TVectorItem> *initialized(SignalVector<TVectorItem> *vec)\n {\n this->initialize(vec);\n return this;\n }\n\n virtual ~SignalVectorModel()\n {\n for (Row &row : this->rows_)\n {\n for (QStandardItem *item : row.items)\n {\n delete item;\n }\n }\n }\n\n int rowCount(const QModelIndex &parent) const override\n {\n (void)parent;\n\n return this->rows_.size();\n }\n\n int columnCount(const QModelIndex &parent) const override\n {\n (void)parent;\n\n return this->columnCount_;\n }\n\n QVariant data(const QModelIndex &index, int role) const override\n {\n int row = index.row(), column = index.column();\n if (row < 0 || column < 0 || row >= this->rows_.size() ||\n column >= this->columnCount_)\n {\n return QVariant();\n }\n\n return rows_[row].items[column]->data(role);\n }\n\n bool setData(const QModelIndex &index, const QVariant &value,\n int role) override\n {\n int row = index.row(), column = index.column();\n if (row < 0 || column < 0 || row >= this->rows_.size() ||\n column >= this->columnCount_)\n {\n return false;\n }\n\n Row &rowItem = this->rows_[row];\n\n assert(this->columnCount_ == rowItem.items.size());\n\n auto &cell = rowItem.items[column];\n\n cell->setData(value, role);\n\n if (rowItem.isCustomRow)\n {\n this->customRowSetData(rowItem.items, column, value, role, row);\n }\n else\n {\n int vecRow = this->getVectorIndexFromModelIndex(row);\n this->vector_->removeAt(vecRow, this);\n\n assert(this->rows_[row].original);\n TVectorItem item = this->getItemFromRow(\n this->rows_[row].items, this->rows_[row].original.get());\n this->vector_->insert(item, vecRow, this);\n }\n\n return true;\n }\n\n QVariant headerData(int section, Qt::Orientation orientation,\n int role) const override\n {\n if (orientation != Qt::Horizontal)\n {\n return QVariant();\n }\n\n auto it = this->headerData_[section].find(role);\n if (it == this->headerData_[section].end())\n {\n return QVariant();\n }\n else\n {\n return it.value();\n }\n }\n\n bool setHeaderData(int section, Qt::Orientation orientation,\n const QVariant &value,\n int role = Qt::DisplayRole) override\n {\n if (orientation != Qt::Horizontal)\n {\n return false;\n }\n\n this->headerData_[section][role] = value;\n\n emit this->headerDataChanged(Qt::Horizontal, section, section);\n return true;\n }\n\n Qt::ItemFlags flags(const QModelIndex &index) const override\n {\n int row = index.row(), column = index.column();\n\n if (row < 0 || column < 0 || row >= this->rows_.size() ||\n column >= this->columnCount_)\n {\n return Qt::NoItemFlags;\n }\n\n assert(row >= 0 && row < this->rows_.size() && column >= 0 &&\n column < this->columnCount_);\n\n const auto &rowItem = this->rows_[row];\n\n assert(this->columnCount_ == rowItem.items.size());\n\n return rowItem.items[column]->flags();\n }\n\n QStandardItem *getItem(int row, int column)\n {\n assert(row >= 0 && row < this->rows_.size() && column >= 0 &&\n column < this->columnCount_);\n\n const auto &rowItem = this->rows_[row];\n\n assert(this->columnCount_ == rowItem.items.size());\n\n return rowItem.items[column];\n }\n\n void deleteRow(int row)\n {\n int signalVectorRow = this->getVectorIndexFromModelIndex(row);\n this->vector_->removeAt(signalVectorRow);\n }\n\n bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count,\n const QModelIndex &destinationParent,\n int destinationChild) override\n {\n if (count != 1)\n {\n return false;\n }\n\n assert(sourceRow >= 0 && sourceRow < this->rows_.size());\n\n int signalVectorRow = this->getVectorIndexFromModelIndex(sourceRow);\n this->beginMoveRows(sourceParent, sourceRow, sourceRow,\n destinationParent, destinationChild);\n\n TVectorItem item =\n this->getItemFromRow(this->rows_[sourceRow].items,\n this->rows_[sourceRow].original.get());\n this->vector_->removeAt(signalVectorRow);\n this->vector_->insert(\n item, this->getVectorIndexFromModelIndex(destinationChild));\n\n this->endMoveRows();\n\n return true;\n }\n\n bool removeRows(int row, int count, const QModelIndex &parent) override\n {\n (void)parent;\n\n if (count != 1)\n {\n return false;\n }\n\n assert(row >= 0 && row < this->rows_.size());\n\n int signalVectorRow = this->getVectorIndexFromModelIndex(row);\n this->vector_->removeAt(signalVectorRow);\n\n return true;\n }\n\n QStringList mimeTypes() const override\n {\n return {\"chatterino_row_id\"};\n }\n\n QMimeData *mimeData(const QModelIndexList &list) const override\n {\n if (list.length() == 1)\n {\n return nullptr;\n }\n\n \/\/ Check if all indices are in the same row -> single row selected\n for (auto &&x : list)\n {\n if (x.row() != list.first().row())\n return nullptr;\n }\n\n auto data = new QMimeData;\n data->setData(\"chatterino_row_id\", QByteArray::number(list[0].row()));\n return data;\n }\n\n bool dropMimeData(const QMimeData *data, Qt::DropAction action, int \/*row*\/,\n int \/*column*\/, const QModelIndex &parent) override\n {\n if (data->hasFormat(\"chatterino_row_id\") &&\n action & (Qt::DropAction::MoveAction | Qt::DropAction::CopyAction))\n {\n int from = data->data(\"chatterino_row_id\").toInt();\n int to = parent.row();\n\n int vectorFrom = this->getVectorIndexFromModelIndex(from);\n int vectorTo = this->getVectorIndexFromModelIndex(to);\n\n if (vectorFrom < 0 || vectorFrom > this->vector_->raw().size() ||\n vectorTo < 0 || vectorTo > this->vector_->raw().size())\n {\n return false;\n }\n\n if (from != to)\n {\n this->moveRow(this->index(from, to), from, parent, to);\n }\n\n \/\/ We return false since we remove items ourselves.\n return false;\n }\n\n return false;\n }\n\n Qt::DropActions supportedDropActions() const override\n {\n return this->vector_->isSorted()\n ? Qt::DropActions()\n : Qt::DropAction::CopyAction | Qt::DropAction::MoveAction;\n }\n\nprotected:\n virtual void afterInit()\n {\n }\n\n \/\/ turn a vector item into a model row\n virtual TVectorItem getItemFromRow(std::vector<QStandardItem *> &row,\n const TVectorItem &original) = 0;\n\n \/\/ turns a row in the model into a vector item\n virtual void getRowFromItem(const TVectorItem &item,\n std::vector<QStandardItem *> &row) = 0;\n\n virtual int beforeInsert(const TVectorItem &item,\n std::vector<QStandardItem *> &row,\n int proposedIndex)\n {\n (void)item, (void)row;\n\n return proposedIndex;\n }\n\n virtual void afterRemoved(const TVectorItem &item,\n std::vector<QStandardItem *> &row, int index)\n {\n (void)item, (void)row, (void)index;\n }\n\n virtual void customRowSetData(const std::vector<QStandardItem *> &row,\n int column, const QVariant &value, int role,\n int rowIndex)\n {\n (void)row, (void)column, (void)value, (void)role, (void)rowIndex;\n }\n\n void insertCustomRow(std::vector<QStandardItem *> row, int index)\n {\n assert(index >= 0 && index <= this->rows_.size());\n\n this->beginInsertRows(QModelIndex(), index, index);\n this->rows_.insert(this->rows_.begin() + index,\n Row(std::move(row), true));\n this->endInsertRows();\n }\n\n void removeCustomRow(int index)\n {\n assert(index >= 0 && index <= this->rows_.size());\n assert(this->rows_[index].isCustomRow);\n\n this->beginRemoveRows(QModelIndex(), index, index);\n this->rows_.erase(this->rows_.begin() + index);\n this->endRemoveRows();\n }\n\n std::vector<QStandardItem *> createRow()\n {\n std::vector<QStandardItem *> row;\n for (int i = 0; i < this->columnCount_; i++)\n {\n row.push_back(new QStandardItem());\n }\n return row;\n }\n\n struct Row {\n std::vector<QStandardItem *> items;\n boost::optional<TVectorItem> original;\n bool isCustomRow;\n\n Row(std::vector<QStandardItem *> _items, bool _isCustomRow = false)\n : items(std::move(_items))\n , isCustomRow(_isCustomRow)\n {\n }\n\n Row(std::vector<QStandardItem *> _items, const TVectorItem &_original,\n bool _isCustomRow = false)\n : items(std::move(_items))\n , original(_original)\n , isCustomRow(_isCustomRow)\n {\n }\n };\n\nprivate:\n std::vector<QMap<int, QVariant>> headerData_;\n SignalVector<TVectorItem> *vector_;\n std::vector<Row> rows_;\n\n const int columnCount_;\n\n \/\/ returns the related index of the SignalVector\n int getVectorIndexFromModelIndex(int index)\n {\n int i = 0;\n\n for (auto &row : this->rows_)\n {\n if (row.isCustomRow)\n {\n index--;\n continue;\n }\n\n if (i == index)\n {\n return i;\n }\n i++;\n }\n\n return i;\n }\n\n \/\/ returns the related index of the model\n int getModelIndexFromVectorIndex(int index)\n {\n int i = 0;\n\n for (auto &row : this->rows_)\n {\n if (row.isCustomRow)\n {\n index++;\n }\n\n if (i == index)\n {\n return i;\n }\n i++;\n }\n\n return i;\n }\n};\n\n} \/\/ namespace chatterino\n<commit_msg>Refactor parts of SignalVectorModel (#3342)<commit_after>#pragma once\n\n#include \"common\/SignalVector.hpp\"\n\n#include <QAbstractTableModel>\n#include <QMimeData>\n#include <QStandardItem>\n#include <boost\/optional.hpp>\n\n#include <pajlada\/signals\/signalholder.hpp>\n\nnamespace chatterino {\n\ntemplate <typename TVectorItem>\nclass SignalVectorModel : public QAbstractTableModel,\n pajlada::Signals::SignalHolder\n{\npublic:\n SignalVectorModel(int columnCount, QObject *parent = nullptr)\n : QAbstractTableModel(parent)\n , columnCount_(columnCount)\n {\n for (int i = 0; i < columnCount; i++)\n {\n this->headerData_.emplace_back();\n }\n }\n\n void initialize(SignalVector<TVectorItem> *vec)\n {\n this->vector_ = vec;\n\n auto insert = [this](const SignalVectorItemEvent<TVectorItem> &args) {\n if (args.caller == this)\n {\n return;\n }\n \/\/ get row index\n int index = this->getModelIndexFromVectorIndex(args.index);\n assert(index >= 0 && index <= this->rows_.size());\n\n \/\/ get row items\n std::vector<QStandardItem *> row = this->createRow();\n this->getRowFromItem(args.item, row);\n\n \/\/ insert row\n index = this->beforeInsert(args.item, row, index);\n\n this->beginInsertRows(QModelIndex(), index, index);\n this->rows_.insert(this->rows_.begin() + index,\n Row(row, args.item));\n this->endInsertRows();\n };\n\n int i = 0;\n for (const TVectorItem &item : vec->raw())\n {\n SignalVectorItemEvent<TVectorItem> args{item, i++, 0};\n\n insert(args);\n }\n\n this->managedConnect(vec->itemInserted, insert);\n\n this->managedConnect(vec->itemRemoved, [this](auto args) {\n if (args.caller == this)\n {\n return;\n }\n\n int row = this->getModelIndexFromVectorIndex(args.index);\n assert(row >= 0 && row <= this->rows_.size());\n\n \/\/ remove row\n std::vector<QStandardItem *> items = this->rows_[row].items;\n\n this->beginRemoveRows(QModelIndex(), row, row);\n this->rows_.erase(this->rows_.begin() + row);\n this->endRemoveRows();\n\n this->afterRemoved(args.item, items, row);\n\n for (QStandardItem *item : items)\n {\n delete item;\n }\n });\n\n this->afterInit();\n }\n\n SignalVectorModel<TVectorItem> *initialized(SignalVector<TVectorItem> *vec)\n {\n this->initialize(vec);\n return this;\n }\n\n virtual ~SignalVectorModel()\n {\n for (Row &row : this->rows_)\n {\n for (QStandardItem *item : row.items)\n {\n delete item;\n }\n }\n }\n\n int rowCount(const QModelIndex &parent) const override\n {\n (void)parent;\n\n return this->rows_.size();\n }\n\n int columnCount(const QModelIndex &parent) const override\n {\n (void)parent;\n\n return this->columnCount_;\n }\n\n QVariant data(const QModelIndex &index, int role) const override\n {\n int row = index.row(), column = index.column();\n if (row < 0 || column < 0 || row >= this->rows_.size() ||\n column >= this->columnCount_)\n {\n return QVariant();\n }\n\n return rows_[row].items[column]->data(role);\n }\n\n bool setData(const QModelIndex &index, const QVariant &value,\n int role) override\n {\n int row = index.row(), column = index.column();\n if (row < 0 || column < 0 || row >= this->rows_.size() ||\n column >= this->columnCount_)\n {\n return false;\n }\n\n Row &rowItem = this->rows_[row];\n\n assert(this->columnCount_ == rowItem.items.size());\n\n auto &cell = rowItem.items[column];\n\n cell->setData(value, role);\n\n if (rowItem.isCustomRow)\n {\n this->customRowSetData(rowItem.items, column, value, role, row);\n }\n else\n {\n int vecRow = this->getVectorIndexFromModelIndex(row);\n this->vector_->removeAt(vecRow, this);\n\n assert(this->rows_[row].original);\n TVectorItem item = this->getItemFromRow(\n this->rows_[row].items, this->rows_[row].original.get());\n this->vector_->insert(item, vecRow, this);\n }\n\n return true;\n }\n\n QVariant headerData(int section, Qt::Orientation orientation,\n int role) const override\n {\n if (orientation != Qt::Horizontal)\n {\n return QVariant();\n }\n\n auto it = this->headerData_[section].find(role);\n if (it == this->headerData_[section].end())\n {\n return QVariant();\n }\n else\n {\n return it.value();\n }\n }\n\n bool setHeaderData(int section, Qt::Orientation orientation,\n const QVariant &value,\n int role = Qt::DisplayRole) override\n {\n if (orientation != Qt::Horizontal)\n {\n return false;\n }\n\n this->headerData_[section][role] = value;\n\n emit this->headerDataChanged(Qt::Horizontal, section, section);\n return true;\n }\n\n Qt::ItemFlags flags(const QModelIndex &index) const override\n {\n int row = index.row(), column = index.column();\n\n if (row < 0 || column < 0 || row >= this->rows_.size() ||\n column >= this->columnCount_)\n {\n return Qt::NoItemFlags;\n }\n\n assert(row >= 0 && row < this->rows_.size() && column >= 0 &&\n column < this->columnCount_);\n\n const auto &rowItem = this->rows_[row];\n\n assert(this->columnCount_ == rowItem.items.size());\n\n return rowItem.items[column]->flags();\n }\n\n QStandardItem *getItem(int row, int column)\n {\n assert(row >= 0 && row < this->rows_.size() && column >= 0 &&\n column < this->columnCount_);\n\n const auto &rowItem = this->rows_[row];\n\n assert(this->columnCount_ == rowItem.items.size());\n\n return rowItem.items[column];\n }\n\n void deleteRow(int row)\n {\n int signalVectorRow = this->getVectorIndexFromModelIndex(row);\n this->vector_->removeAt(signalVectorRow);\n }\n\n bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count,\n const QModelIndex &destinationParent,\n int destinationChild) override\n {\n if (count != 1)\n {\n return false;\n }\n\n assert(sourceRow >= 0 && sourceRow < this->rows_.size());\n\n int signalVectorRow = this->getVectorIndexFromModelIndex(sourceRow);\n this->beginMoveRows(sourceParent, sourceRow, sourceRow,\n destinationParent, destinationChild);\n\n TVectorItem item =\n this->getItemFromRow(this->rows_[sourceRow].items,\n this->rows_[sourceRow].original.get());\n this->vector_->removeAt(signalVectorRow);\n this->vector_->insert(\n item, this->getVectorIndexFromModelIndex(destinationChild));\n\n this->endMoveRows();\n\n return true;\n }\n\n bool removeRows(int row, int count, const QModelIndex &parent) override\n {\n (void)parent;\n\n if (count != 1)\n {\n return false;\n }\n\n assert(row >= 0 && row < this->rows_.size());\n\n int signalVectorRow = this->getVectorIndexFromModelIndex(row);\n this->vector_->removeAt(signalVectorRow);\n\n return true;\n }\n\n QStringList mimeTypes() const override\n {\n return {\"chatterino_row_id\"};\n }\n\n QMimeData *mimeData(const QModelIndexList &list) const override\n {\n if (list.length() == 1)\n {\n return nullptr;\n }\n\n \/\/ Check if all indices are in the same row -> single row selected\n for (auto &&x : list)\n {\n if (x.row() != list.first().row())\n return nullptr;\n }\n\n auto data = new QMimeData;\n data->setData(\"chatterino_row_id\", QByteArray::number(list[0].row()));\n return data;\n }\n\n bool dropMimeData(const QMimeData *data, Qt::DropAction action, int \/*row*\/,\n int \/*column*\/, const QModelIndex &parent) override\n {\n if (data->hasFormat(\"chatterino_row_id\") &&\n action & (Qt::DropAction::MoveAction | Qt::DropAction::CopyAction))\n {\n int from = data->data(\"chatterino_row_id\").toInt();\n int to = parent.row();\n\n int vectorFrom = this->getVectorIndexFromModelIndex(from);\n int vectorTo = this->getVectorIndexFromModelIndex(to);\n\n if (vectorFrom < 0 || vectorFrom > this->vector_->raw().size() ||\n vectorTo < 0 || vectorTo > this->vector_->raw().size())\n {\n return false;\n }\n\n if (from != to)\n {\n this->moveRow(this->index(from, to), from, parent, to);\n }\n\n \/\/ We return false since we remove items ourselves.\n return false;\n }\n\n return false;\n }\n\n Qt::DropActions supportedDropActions() const override\n {\n return this->vector_->isSorted()\n ? Qt::DropActions()\n : Qt::DropAction::CopyAction | Qt::DropAction::MoveAction;\n }\n\nprotected:\n virtual void afterInit()\n {\n }\n\n \/\/ turn a vector item into a model row\n virtual TVectorItem getItemFromRow(std::vector<QStandardItem *> &row,\n const TVectorItem &original) = 0;\n\n \/\/ turns a row in the model into a vector item\n virtual void getRowFromItem(const TVectorItem &item,\n std::vector<QStandardItem *> &row) = 0;\n\n virtual int beforeInsert(const TVectorItem &item,\n std::vector<QStandardItem *> &row,\n int proposedIndex)\n {\n (void)item, (void)row;\n\n return proposedIndex;\n }\n\n virtual void afterRemoved(const TVectorItem &item,\n std::vector<QStandardItem *> &row, int index)\n {\n (void)item, (void)row, (void)index;\n }\n\n virtual void customRowSetData(const std::vector<QStandardItem *> &row,\n int column, const QVariant &value, int role,\n int rowIndex)\n {\n (void)row, (void)column, (void)value, (void)role, (void)rowIndex;\n }\n\n void insertCustomRow(std::vector<QStandardItem *> row, int index)\n {\n assert(index >= 0 && index <= this->rows_.size());\n\n this->beginInsertRows(QModelIndex(), index, index);\n this->rows_.insert(this->rows_.begin() + index,\n Row(std::move(row), true));\n this->endInsertRows();\n }\n\n void removeCustomRow(int index)\n {\n assert(index >= 0 && index <= this->rows_.size());\n assert(this->rows_[index].isCustomRow);\n\n this->beginRemoveRows(QModelIndex(), index, index);\n this->rows_.erase(this->rows_.begin() + index);\n this->endRemoveRows();\n }\n\n std::vector<QStandardItem *> createRow()\n {\n std::vector<QStandardItem *> row;\n for (int i = 0; i < this->columnCount_; i++)\n {\n row.push_back(new QStandardItem());\n }\n return row;\n }\n\n struct Row {\n std::vector<QStandardItem *> items;\n boost::optional<TVectorItem> original;\n bool isCustomRow;\n\n Row(std::vector<QStandardItem *> _items, bool _isCustomRow = false)\n : items(std::move(_items))\n , isCustomRow(_isCustomRow)\n {\n }\n\n Row(std::vector<QStandardItem *> _items, const TVectorItem &_original,\n bool _isCustomRow = false)\n : items(std::move(_items))\n , original(_original)\n , isCustomRow(_isCustomRow)\n {\n }\n };\n\n const std::vector<Row> &rows() const\n {\n return this->rows_;\n }\n\nprivate:\n std::vector<QMap<int, QVariant>> headerData_;\n SignalVector<TVectorItem> *vector_;\n std::vector<Row> rows_;\n\n const int columnCount_;\n\n \/\/ returns the related index of the SignalVector\n int getVectorIndexFromModelIndex(int index)\n {\n int i = 0;\n\n for (auto &row : this->rows_)\n {\n if (row.isCustomRow)\n {\n index--;\n continue;\n }\n\n if (i == index)\n {\n return i;\n }\n i++;\n }\n\n return i;\n }\n\npublic:\n \/\/ returns the related index of the model\n int getModelIndexFromVectorIndex(int vectorIndex) const\n {\n int modelIndex = 0;\n\n for (auto &row : this->rows())\n {\n if (row.isCustomRow)\n {\n vectorIndex++;\n }\n\n if (modelIndex == vectorIndex)\n {\n return modelIndex;\n }\n\n modelIndex++;\n }\n\n return modelIndex;\n }\n};\n\n} \/\/ namespace chatterino\n<|endoftext|>"} {"text":"<commit_before>#include \"packagerplugin.h\"\n\n#include <QFileInfo>\n\nPackagerPlugin::PackagerPlugin(QObject *parent) :\n PackagerInterface(parent)\n{\n}\n\nQ_EXPORT_PLUGIN2(PackagerPlugin, PackagerPlugin)\n\nPackagerPlugin::~PackagerPlugin()\n{\n}\n\nQString PackagerPlugin::name() const\n{\n return \"PackagerPlugin\";\n}\n\nQString PackagerPlugin::version() const\n{\n return \"1.0\";\n}\n\nvoid PackagerPlugin::setDefaultParameters()\n{\n\n}\n\nbool PackagerPlugin::pack(const QString &path, const QString &name)\n{\n QFile *file = new QFile(name);\n if (!file->open(QIODevice::WriteOnly)) {\n return false;\n }\n\n int size = 1048576;\n for (int i = 0; i < 20; i++) {\n char *data = new char[size];\n memset(data,'-',size);\n file->seek(i*size);\n file->writeData(reinterpret_cast<const char*>(data), size);\n delete[] data;\n }\n\n file->close();\n\n return true;\n}\n\nbool PackagerPlugin::unpack(const QString &name, const QString &path)\n{\n int size = 1048576;\n for (int i = 0; i < 5; i++) {\n QString filename = path + \"\/\" + \"output_\" + QString::number(i);\n QFile *file = new QFile(filename);\n if (file->open(QIODevice::WriteOnly)) {\n char *data = new char[size];\n memset(data,'-',size);\n file->writeData(reinterpret_cast<const char*>(data), size);\n delete[] data;\n }\n file->close();\n }\n\n return true;\n}\n<commit_msg>fix file write error<commit_after>#include \"packagerplugin.h\"\n\n#include <QFileInfo>\n\nPackagerPlugin::PackagerPlugin(QObject *parent) :\n PackagerInterface(parent)\n{\n}\n\nQ_EXPORT_PLUGIN2(PackagerPlugin, PackagerPlugin)\n\nPackagerPlugin::~PackagerPlugin()\n{\n}\n\nQString PackagerPlugin::name() const\n{\n return \"PackagerPlugin\";\n}\n\nQString PackagerPlugin::version() const\n{\n return \"1.0\";\n}\n\nvoid PackagerPlugin::setDefaultParameters()\n{\n\n}\n\nbool PackagerPlugin::pack(const QString &path, const QString &name)\n{\n QFile *file = new QFile(name);\n if (!file->open(QIODevice::WriteOnly)) {\n return false;\n }\n\n int size = 1048576;\n for (int i = 0; i < 20; i++) {\n char *data = new char[size];\n memset(data,'-',size);\n file->seek(i*size);\n file->write(reinterpret_cast<const char*>(data), size);\n delete[] data;\n }\n\n file->close();\n\n return true;\n}\n\nbool PackagerPlugin::unpack(const QString &name, const QString &path)\n{\n int size = 1048576;\n for (int i = 0; i < 5; i++) {\n QString filename = path + \"\/\" + \"output_\" + QString::number(i);\n QFile *file = new QFile(filename);\n if (file->open(QIODevice::WriteOnly)) {\n char *data = new char[size];\n memset(data,'-',size);\n file->write(reinterpret_cast<const char*>(data), size);\n delete[] data;\n }\n file->close();\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Natron\n\/\/\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012.\n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Image.h\"\n\n#include \"Engine\/Lut.h\"\n\nRectI Natron::Bitmap::minimalNonMarkedBbox(const RectI& roi) const\n{\n \/*if we rendered everything we just append\n a NULL box to indicate we rendered it all.*\/\n\/\/ if(!memchr(_map.get(),0,_rod.area())){\n\/\/ ret.push_back(RectI());\n\/\/ return ret;\n\/\/ }\n \n RectI bbox = roi;\n \/\/find bottom\n for (int i = bbox.bottom(); i < bbox.top();++i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width()];\n if(!memchr(buf, 0, _rod.width())){\n bbox.set_bottom(bbox.bottom()+1);\n } else {\n break;\n }\n }\n\n \/\/find top (will do zero iteration if the bbox is already empty)\n for (int i = bbox.top()-1; i >= bbox.bottom();--i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width()];\n if (!memchr(buf, 0, _rod.width())) {\n bbox.set_top(bbox.top()-1);\n } else {\n break;\n }\n }\n\n \/\/ avoid making bbox.width() iterations for nothing\n if (bbox.isNull()) {\n return bbox;\n }\n\n \/\/find left\n for (int j = bbox.left(); j < bbox.right(); ++j) {\n bool shouldStop = false;\n for (int i = bbox.bottom(); i < bbox.top(); ++i) {\n if (!_map[(i-_rod.bottom())*_rod.width() + (j-_rod.left())]) {\n shouldStop = true;\n break;\n }\n }\n if (!shouldStop) {\n bbox.set_left(bbox.left()+1);\n } else {\n break;\n }\n }\n\n \/\/find right\n for (int j = bbox.right()-1; j >= bbox.left(); --j) {\n bool shouldStop = false;\n for (int i = bbox.bottom(); i < bbox.top(); ++i) {\n if (!_map[(i-_rod.bottom())*_rod.width() + (j-_rod.left())]) {\n shouldStop = true;\n break;\n }\n }\n if (!shouldStop) {\n bbox.set_right(bbox.right()-1);\n } else {\n break;\n }\n }\n return bbox;\n}\n\nstd::list<RectI> Natron::Bitmap::minimalNonMarkedRects(const RectI& roi) const\n{\n std::list<RectI> ret;\n\n RectI bboxM = minimalNonMarkedBbox(roi);\n\/\/#define NATRON_BITMAP_DISABLE_OPTIMIZATION\n#ifdef NATRON_BITMAP_DISABLE_OPTIMIZATION\n if (!bboxM.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxM);\n }\n#else\n if (bboxM.isNull()) {\n return ret; \/\/ return an empty rectangle list\n }\n\n \/\/ optimization by Fred, Jan 31, 2014\n \/\/\n \/\/ Now that we have the smallest enclosing bounding box,\n \/\/ let's try to find rectangles for the bottom, the top,\n \/\/ the left and the right part.\n \/\/ This happens quite often, for example when zooming out\n \/\/ (in this case the area to compute is formed of A, B, C and D,\n \/\/ and X is already rendered), or when panning (in this case the area\n \/\/ is just two rectangles, e.g. A and C, and the rectangles B, D and\n \/\/ X are already rendered).\n \/\/ The rectangles A, B, C and D from the following drawing are just\n \/\/ zeroes, and X contains zeroes and ones.\n \/\/\n \/\/ BBBBBBBBBBBBBB\n \/\/ BBBBBBBBBBBBBB\n \/\/ CXXXXXXXXXXDDD\n \/\/ CXXXXXXXXXXDDD\n \/\/ CXXXXXXXXXXDDD\n \/\/ CXXXXXXXXXXDDD\n \/\/ AAAAAAAAAAAAAA\n\n \/\/ First, find if there's an \"A\" rectangle, and push it to the result\n \/\/find bottom\n RectI bboxX = bboxM;\n RectI bboxA = bboxX;\n bboxA.set_top(bboxX.bottom());\n for (int i = bboxX.bottom(); i < bboxX.top();++i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width()];\n if (!memchr(buf, 1, _rod.width())) {\n bboxX.set_bottom(bboxX.bottom()+1);\n bboxA.set_top(bboxX.bottom());\n } else {\n break;\n }\n }\n if (!bboxA.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxA);\n }\n\n \/\/ Now, find the \"B\" rectangle\n \/\/find top\n RectI bboxB = bboxX;\n bboxB.set_bottom(bboxX.top());\n for (int i = bboxX.top()-1; i >= bboxX.bottom();--i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width()];\n if (!memchr(buf, 1, _rod.width())) {\n bboxX.set_top(bboxX.top()-1);\n bboxB.set_bottom(bboxX.top());\n } else {\n break;\n }\n }\n if (!bboxB.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxB);\n }\n\n \/\/find left\n RectI bboxC = bboxX;\n bboxC.set_right(bboxX.left());\n for (int j = bboxX.left(); j < bboxX.right(); ++j) {\n bool shouldStop = false;\n for (int i = bboxX.bottom(); i < bboxX.top(); ++i) {\n if (_map[(i-_rod.bottom())*_rod.width()+(j-_rod.left())]) {\n shouldStop = true;\n break;\n }\n }\n if (!shouldStop) {\n bboxX.set_left(bboxX.left()+1);\n bboxC.set_right(bboxX.left());\n } else {\n break;\n }\n }\n if (!bboxC.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxC);\n }\n\n \/\/find right\n RectI bboxD = bboxX;\n bboxD.set_left(bboxX.right());\n for (int j = bboxX.right()-1; j >= bboxX.left(); --j) {\n bool shouldStop = false;\n for (int i = bboxX.bottom(); i < bboxX.top(); ++i) {\n if (_map[(i-_rod.bottom())*_rod.width()+(j-_rod.left())]) {\n shouldStop = true;\n break;\n }\n }\n if (!shouldStop) {\n bboxX.set_right(bboxX.right()-1);\n bboxD.set_left(bboxX.right());\n } else {\n break;\n }\n }\n\n assert(bboxA.bottom() == bboxM.bottom());\n assert(bboxA.left() == bboxM.left());\n assert(bboxA.right() == bboxM.right());\n assert(bboxA.top() == bboxX.bottom());\n\n assert(bboxB.top() == bboxM.top());\n assert(bboxB.left() == bboxM.left());\n assert(bboxB.right() == bboxM.right());\n assert(bboxB.bottom() == bboxX.top());\n\n assert(bboxC.top() == bboxX.top());\n assert(bboxC.left() == bboxM.left());\n assert(bboxC.right() == bboxX.left());\n assert(bboxC.bottom() == bboxX.bottom());\n\n assert(bboxD.top() == bboxX.top());\n assert(bboxD.left() == bboxX.right());\n assert(bboxD.right() == bboxM.right());\n assert(bboxD.bottom() == bboxX.bottom());\n\n \/\/ get the bounding box of what's left (the X rectangle in the drawing above)\n bboxX = minimalNonMarkedBbox(bboxX);\n if (!bboxX.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxX);\n }\n\n#endif \/\/ NATRON_BITMAP_DISABLE_OPTIMIZATION\n qDebug() << \"render \" << ret.size() << \" rectangles\";\n for (std::list<RectI>::const_iterator it = ret.begin(); it != ret.end(); ++it) {\n qDebug() << \"rect: \" << it->x1 << ',' << it->x2 << ',' << it->y1 << ',' << it->y2;\n }\n return ret;\n}\n\nvoid Natron::Bitmap::markForRendered(const RectI& roi){\n for (int i = roi.bottom(); i < roi.top();++i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width() + (roi.left() - _rod.left())];\n memset(buf, 1, roi.width());\n }\n}\n\nvoid Natron::Image::copy(const Natron::Image& other){\n \n RectI intersection;\n this->_params._rod.intersect(other._params._rod, &intersection);\n \n if (intersection.isNull()) {\n return;\n }\n \n const float* src = other.pixelAt(0, 0);\n float* dst = pixelAt(0, 0);\n memcpy(dst, src, intersection.area());\n}\n\nnamespace Natron{\n void debugImage(Natron::Image* img,const QString& filename){\n const RectI& rod = img->getRoD();\n QImage output(rod.width(),rod.height(),QImage::Format_ARGB32);\n const Natron::Color::Lut* lut = Natron::Color::LutManager::sRGBLut();\n lut->to_byte_packed(output.bits(), img->pixelAt(0, 0), rod, rod, rod,\n Natron::Color::PACKING_RGBA,Natron::Color::PACKING_BGRA, true,false);\n U64 hashKey = img->getHashKey();\n QString hashKeyStr = QString::number(hashKey);\n QString realFileName = filename.isEmpty() ? QString(hashKeyStr+\".png\") : filename;\n output.save(realFileName);\n }\n \n}\n\n<commit_msg>Image: fix the last bug (!) in the optimized Bitmap::minimalNonMarkedRects()<commit_after>\/\/ Natron\n\/\/\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012.\n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Image.h\"\n\n#include \"Engine\/Lut.h\"\n\nRectI Natron::Bitmap::minimalNonMarkedBbox(const RectI& roi) const\n{\n \/*if we rendered everything we just append\n a NULL box to indicate we rendered it all.*\/\n\/\/ if(!memchr(_map.get(),0,_rod.area())){\n\/\/ ret.push_back(RectI());\n\/\/ return ret;\n\/\/ }\n \n RectI bbox = roi;\n \/\/find bottom\n for (int i = bbox.bottom(); i < bbox.top();++i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width()];\n if(!memchr(buf, 0, _rod.width())){\n bbox.set_bottom(bbox.bottom()+1);\n } else {\n break;\n }\n }\n\n \/\/find top (will do zero iteration if the bbox is already empty)\n for (int i = bbox.top()-1; i >= bbox.bottom();--i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width()];\n if (!memchr(buf, 0, _rod.width())) {\n bbox.set_top(bbox.top()-1);\n } else {\n break;\n }\n }\n\n \/\/ avoid making bbox.width() iterations for nothing\n if (bbox.isNull()) {\n return bbox;\n }\n\n \/\/find left\n for (int j = bbox.left(); j < bbox.right(); ++j) {\n bool shouldStop = false;\n for (int i = bbox.bottom(); i < bbox.top(); ++i) {\n if (!_map[(i-_rod.bottom())*_rod.width() + (j-_rod.left())]) {\n shouldStop = true;\n break;\n }\n }\n if (!shouldStop) {\n bbox.set_left(bbox.left()+1);\n } else {\n break;\n }\n }\n\n \/\/find right\n for (int j = bbox.right()-1; j >= bbox.left(); --j) {\n bool shouldStop = false;\n for (int i = bbox.bottom(); i < bbox.top(); ++i) {\n if (!_map[(i-_rod.bottom())*_rod.width() + (j-_rod.left())]) {\n shouldStop = true;\n break;\n }\n }\n if (!shouldStop) {\n bbox.set_right(bbox.right()-1);\n } else {\n break;\n }\n }\n return bbox;\n}\n\nstd::list<RectI> Natron::Bitmap::minimalNonMarkedRects(const RectI& roi) const\n{\n std::list<RectI> ret;\n\n RectI bboxM = minimalNonMarkedBbox(roi);\n\/\/#define NATRON_BITMAP_DISABLE_OPTIMIZATION\n#ifdef NATRON_BITMAP_DISABLE_OPTIMIZATION\n if (!bboxM.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxM);\n }\n#else\n if (bboxM.isNull()) {\n return ret; \/\/ return an empty rectangle list\n }\n\n \/\/ optimization by Fred, Jan 31, 2014\n \/\/\n \/\/ Now that we have the smallest enclosing bounding box,\n \/\/ let's try to find rectangles for the bottom, the top,\n \/\/ the left and the right part.\n \/\/ This happens quite often, for example when zooming out\n \/\/ (in this case the area to compute is formed of A, B, C and D,\n \/\/ and X is already rendered), or when panning (in this case the area\n \/\/ is just two rectangles, e.g. A and C, and the rectangles B, D and\n \/\/ X are already rendered).\n \/\/ The rectangles A, B, C and D from the following drawing are just\n \/\/ zeroes, and X contains zeroes and ones.\n \/\/\n \/\/ BBBBBBBBBBBBBB\n \/\/ BBBBBBBBBBBBBB\n \/\/ CXXXXXXXXXXDDD\n \/\/ CXXXXXXXXXXDDD\n \/\/ CXXXXXXXXXXDDD\n \/\/ CXXXXXXXXXXDDD\n \/\/ AAAAAAAAAAAAAA\n\n \/\/ First, find if there's an \"A\" rectangle, and push it to the result\n \/\/find bottom\n RectI bboxX = bboxM;\n RectI bboxA = bboxX;\n bboxA.set_top(bboxX.bottom());\n for (int i = bboxX.bottom(); i < bboxX.top();++i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width()];\n if (!memchr(buf, 1, _rod.width())) {\n bboxX.set_bottom(bboxX.bottom()+1);\n bboxA.set_top(bboxX.bottom());\n } else {\n break;\n }\n }\n if (!bboxA.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxA);\n }\n\n \/\/ Now, find the \"B\" rectangle\n \/\/find top\n RectI bboxB = bboxX;\n bboxB.set_bottom(bboxX.top());\n for (int i = bboxX.top()-1; i >= bboxX.bottom();--i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width()];\n if (!memchr(buf, 1, _rod.width())) {\n bboxX.set_top(bboxX.top()-1);\n bboxB.set_bottom(bboxX.top());\n } else {\n break;\n }\n }\n if (!bboxB.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxB);\n }\n\n \/\/find left\n RectI bboxC = bboxX;\n bboxC.set_right(bboxX.left());\n for (int j = bboxX.left(); j < bboxX.right(); ++j) {\n bool shouldStop = false;\n for (int i = bboxX.bottom(); i < bboxX.top(); ++i) {\n if (_map[(i-_rod.bottom())*_rod.width()+(j-_rod.left())]) {\n shouldStop = true;\n break;\n }\n }\n if (!shouldStop) {\n bboxX.set_left(bboxX.left()+1);\n bboxC.set_right(bboxX.left());\n } else {\n break;\n }\n }\n if (!bboxC.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxC);\n }\n\n \/\/find right\n RectI bboxD = bboxX;\n bboxD.set_left(bboxX.right());\n for (int j = bboxX.right()-1; j >= bboxX.left(); --j) {\n bool shouldStop = false;\n for (int i = bboxX.bottom(); i < bboxX.top(); ++i) {\n if (_map[(i-_rod.bottom())*_rod.width()+(j-_rod.left())]) {\n shouldStop = true;\n break;\n }\n }\n if (!shouldStop) {\n bboxX.set_right(bboxX.right()-1);\n bboxD.set_left(bboxX.right());\n } else {\n break;\n }\n }\n if (!bboxD.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxD);\n }\n\n assert(bboxA.bottom() == bboxM.bottom());\n assert(bboxA.left() == bboxM.left());\n assert(bboxA.right() == bboxM.right());\n assert(bboxA.top() == bboxX.bottom());\n\n assert(bboxB.top() == bboxM.top());\n assert(bboxB.left() == bboxM.left());\n assert(bboxB.right() == bboxM.right());\n assert(bboxB.bottom() == bboxX.top());\n\n assert(bboxC.top() == bboxX.top());\n assert(bboxC.left() == bboxM.left());\n assert(bboxC.right() == bboxX.left());\n assert(bboxC.bottom() == bboxX.bottom());\n\n assert(bboxD.top() == bboxX.top());\n assert(bboxD.left() == bboxX.right());\n assert(bboxD.right() == bboxM.right());\n assert(bboxD.bottom() == bboxX.bottom());\n\n \/\/ get the bounding box of what's left (the X rectangle in the drawing above)\n bboxX = minimalNonMarkedBbox(bboxX);\n if (!bboxX.isNull()) { \/\/ empty boxes should not be pushed\n ret.push_back(bboxX);\n }\n\n#endif \/\/ NATRON_BITMAP_DISABLE_OPTIMIZATION\n qDebug() << \"render \" << ret.size() << \" rectangles\";\n for (std::list<RectI>::const_iterator it = ret.begin(); it != ret.end(); ++it) {\n qDebug() << \"rect: \" << it->x1 << ',' << it->x2 << ',' << it->y1 << ',' << it->y2;\n }\n return ret;\n}\n\nvoid Natron::Bitmap::markForRendered(const RectI& roi){\n for (int i = roi.bottom(); i < roi.top();++i) {\n char* buf = &_map[(i-_rod.bottom())*_rod.width() + (roi.left() - _rod.left())];\n memset(buf, 1, roi.width());\n }\n}\n\nvoid Natron::Image::copy(const Natron::Image& other){\n \n RectI intersection;\n this->_params._rod.intersect(other._params._rod, &intersection);\n \n if (intersection.isNull()) {\n return;\n }\n \n const float* src = other.pixelAt(0, 0);\n float* dst = pixelAt(0, 0);\n memcpy(dst, src, intersection.area());\n}\n\nnamespace Natron{\n void debugImage(Natron::Image* img,const QString& filename){\n const RectI& rod = img->getRoD();\n QImage output(rod.width(),rod.height(),QImage::Format_ARGB32);\n const Natron::Color::Lut* lut = Natron::Color::LutManager::sRGBLut();\n lut->to_byte_packed(output.bits(), img->pixelAt(0, 0), rod, rod, rod,\n Natron::Color::PACKING_RGBA,Natron::Color::PACKING_BGRA, true,false);\n U64 hashKey = img->getHashKey();\n QString hashKeyStr = QString::number(hashKey);\n QString realFileName = filename.isEmpty() ? QString(hashKeyStr+\".png\") : filename;\n output.save(realFileName);\n }\n \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\n Module: FGAtmosphere.cpp\n Author: Jon Berndt\n Implementation of 1959 Standard Atmosphere added by Tony Peden \n Date started: 11\/24\/98\n Purpose: Models the atmosphere\n Called by: FGSimExec\n\n ------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) -------------\n\n This program is free software; you can redistribute it and\/or modify it under\n the terms of the GNU General Public License as published by the Free Software\n Foundation; either version 2 of the License, or (at your option) any later\n version.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n details.\n\n You should have received a copy of the GNU General Public License along with\n this program; if not, write to the Free Software Foundation, Inc., 59 Temple\n Place - Suite 330, Boston, MA 02111-1307, USA.\n\n Further information about the GNU General Public License can also be found on\n the world wide web at http:\/\/www.gnu.org.\n\nFUNCTIONAL DESCRIPTION\n--------------------------------------------------------------------------------\nModels the atmosphere. The equation used below was determined by a third order\ncurve fit using Excel. The data is from the ICAO atmosphere model.\n\nHISTORY\n--------------------------------------------------------------------------------\n11\/24\/98 JSB Created\n07\/23\/99 TP Added implementation of 1959 Standard Atmosphere\n Moved calculation of Mach number to FGTranslation\n********************************************************************************\nCOMMENTS, REFERENCES, and NOTES\n********************************************************************************\n[1] Anderson, John D. \"Introduction to Flight, Third Edition\", McGraw-Hill,\n 1989, ISBN 0-07-001641-0\n\n********************************************************************************\nINCLUDES\n*******************************************************************************\/\n\n#include \"FGAtmosphere.h\"\n#include \"FGState.h\"\n#include \"FGFDMExec.h\"\n#include \"FGFCS.h\"\n#include \"FGAircraft.h\"\n#include \"FGTranslation.h\"\n#include \"FGRotation.h\"\n#include \"FGPosition.h\"\n#include \"FGAuxiliary.h\"\n#include \"FGOutput.h\"\n#include \"FGDefs.h\"\n\n\/*******************************************************************************\n************************************ CODE **************************************\n*******************************************************************************\/\n\n\nFGAtmosphere::FGAtmosphere(FGFDMExec* fdmex) : FGModel(fdmex)\n{\n Name = \"FGAtmosphere\";\n h = 0;\n Calculate(h);\n SLtemperature = temperature;\n SLpressure = pressure;\n SLdensity = density;\n SLsoundspeed = sqrt(SHRATIO*Reng*temperature);\n useExternal=false;\n}\n\n\nFGAtmosphere::~FGAtmosphere()\n{\n}\n\n\nbool FGAtmosphere::Run(void)\n{\n if (!FGModel::Run()) { \/\/ if false then execute this Run()\n if (!useExternal) {\n h = State->Geth();\n Calculate(h);\n } else {\n density = exDensity;\n pressure = exPressure;\n temperature = exTemperature;\n }\n soundspeed = sqrt(SHRATIO*Reng*temperature);\n State->Seta(soundspeed);\n } else { \/\/ skip Run() execution this time\n }\n return false;\n}\n\nvoid FGAtmosphere::Calculate(float altitude)\n{\n \/\/see reference [1]\n\n\n float slope,reftemp,refpress,refdens;\n int i=0;\n float htab[]={0,36089,82020,154198,173882,259183,295272,344484}; \/\/ft.\n\/\/ cout << \"Atmosphere: h=\" << altitude << \" rho= \" << density << endl;\n if (altitude <= htab[0]) {\n altitude=0;\n } else if (altitude >= htab[7]){\n i = 7;\n altitude = htab[7];\n } else {\n while (htab[i+1] < altitude) {\n i++;\n }\n }\n\n switch(i) {\n case 0: \/\/ sea level\n slope = -0.0035662; \/\/ R\/ft.\n reftemp = 518.688; \/\/ R\n refpress = 2116.17; \/\/ psf\n refdens = 0.0023765; \/\/ slugs\/cubic ft.\n break;\n case 1: \/\/ 36089 ft.\n slope = 0;\n reftemp = 389.988;\n refpress = 474.1;\n refdens = 0.0007078;\n break;\n case 2: \/\/ 82020 ft.\n slope = 0.00164594;\n reftemp = 389.988;\n refpress = 52.7838;\n refdens = 7.8849E-5;\n break;\n case 3: \/\/ 154198 ft.\n slope = 0;\n reftemp = 508.788;\n refpress = 2.62274;\n refdens = 3.01379E-6;\n break;\n case 4: \/\/ 173882 ft.\n slope = -0.00246891;\n reftemp = 508.788;\n refpress = 1.28428;\n refdens = 1.47035e-06;\n break;\n case 5: \/\/ 259183 ft.\n slope = 0;\n reftemp = 298.188;\n refpress = 0.0222008;\n refdens = 4.33396e-08;\n break;\n case 6: \/\/ 295272 ft.\n slope = 0.00219459;\n reftemp = 298.188;\n refpress = 0.00215742;\n refdens = 4.21368e-09;\n break;\n case 7: \/\/ 344484 ft.\n slope = 0;\n reftemp = 406.188;\n refpress = 0.000153755;\n refdens = 2.20384e-10;\n break;\n }\n\n\n if (slope == 0) {\n temperature = reftemp;\n pressure = refpress*exp(-GRAVITY\/(reftemp*Reng)*(altitude-htab[i]));\n density = refdens*exp(-GRAVITY\/(reftemp*Reng)*(altitude-htab[i]));\n } else {\n temperature = reftemp+slope*(altitude-htab[i]);\n pressure = refpress*pow(temperature\/reftemp,-GRAVITY\/(slope*Reng));\n density = refdens*pow(temperature\/reftemp,-(GRAVITY\/(slope*Reng)+1));\n }\n\n cout << \"Atmosphere: h=\" << altitude << \" rho= \" << density << endl;\n\n}\n\n<commit_msg>Removed output statement<commit_after>\/*******************************************************************************\n\n Module: FGAtmosphere.cpp\n Author: Jon Berndt\n Implementation of 1959 Standard Atmosphere added by Tony Peden \n Date started: 11\/24\/98\n Purpose: Models the atmosphere\n Called by: FGSimExec\n\n ------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) -------------\n\n This program is free software; you can redistribute it and\/or modify it under\n the terms of the GNU General Public License as published by the Free Software\n Foundation; either version 2 of the License, or (at your option) any later\n version.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n details.\n\n You should have received a copy of the GNU General Public License along with\n this program; if not, write to the Free Software Foundation, Inc., 59 Temple\n Place - Suite 330, Boston, MA 02111-1307, USA.\n\n Further information about the GNU General Public License can also be found on\n the world wide web at http:\/\/www.gnu.org.\n\nFUNCTIONAL DESCRIPTION\n--------------------------------------------------------------------------------\nModels the atmosphere. The equation used below was determined by a third order\ncurve fit using Excel. The data is from the ICAO atmosphere model.\n\nHISTORY\n--------------------------------------------------------------------------------\n11\/24\/98 JSB Created\n07\/23\/99 TP Added implementation of 1959 Standard Atmosphere\n Moved calculation of Mach number to FGTranslation\n********************************************************************************\nCOMMENTS, REFERENCES, and NOTES\n********************************************************************************\n[1] Anderson, John D. \"Introduction to Flight, Third Edition\", McGraw-Hill,\n 1989, ISBN 0-07-001641-0\n\n********************************************************************************\nINCLUDES\n*******************************************************************************\/\n\n#include \"FGAtmosphere.h\"\n#include \"FGState.h\"\n#include \"FGFDMExec.h\"\n#include \"FGFCS.h\"\n#include \"FGAircraft.h\"\n#include \"FGTranslation.h\"\n#include \"FGRotation.h\"\n#include \"FGPosition.h\"\n#include \"FGAuxiliary.h\"\n#include \"FGOutput.h\"\n#include \"FGDefs.h\"\n\n\/*******************************************************************************\n************************************ CODE **************************************\n*******************************************************************************\/\n\n\nFGAtmosphere::FGAtmosphere(FGFDMExec* fdmex) : FGModel(fdmex)\n{\n Name = \"FGAtmosphere\";\n h = 0;\n Calculate(h);\n SLtemperature = temperature;\n SLpressure = pressure;\n SLdensity = density;\n SLsoundspeed = sqrt(SHRATIO*Reng*temperature);\n useExternal=false;\n}\n\n\nFGAtmosphere::~FGAtmosphere()\n{\n}\n\n\nbool FGAtmosphere::Run(void)\n{\n if (!FGModel::Run()) { \/\/ if false then execute this Run()\n if (!useExternal) {\n h = State->Geth();\n Calculate(h);\n } else {\n density = exDensity;\n pressure = exPressure;\n temperature = exTemperature;\n }\n soundspeed = sqrt(SHRATIO*Reng*temperature);\n State->Seta(soundspeed);\n } else { \/\/ skip Run() execution this time\n }\n return false;\n}\n\nvoid FGAtmosphere::Calculate(float altitude)\n{\n \/\/see reference [1]\n\n\n float slope,reftemp,refpress,refdens;\n int i=0;\n float htab[]={0,36089,82020,154198,173882,259183,295272,344484}; \/\/ft.\n\/\/ cout << \"Atmosphere: h=\" << altitude << \" rho= \" << density << endl;\n if (altitude <= htab[0]) {\n altitude=0;\n } else if (altitude >= htab[7]){\n i = 7;\n altitude = htab[7];\n } else {\n while (htab[i+1] < altitude) {\n i++;\n }\n }\n\n switch(i) {\n case 0: \/\/ sea level\n slope = -0.0035662; \/\/ R\/ft.\n reftemp = 518.688; \/\/ R\n refpress = 2116.17; \/\/ psf\n refdens = 0.0023765; \/\/ slugs\/cubic ft.\n break;\n case 1: \/\/ 36089 ft.\n slope = 0;\n reftemp = 389.988;\n refpress = 474.1;\n refdens = 0.0007078;\n break;\n case 2: \/\/ 82020 ft.\n slope = 0.00164594;\n reftemp = 389.988;\n refpress = 52.7838;\n refdens = 7.8849E-5;\n break;\n case 3: \/\/ 154198 ft.\n slope = 0;\n reftemp = 508.788;\n refpress = 2.62274;\n refdens = 3.01379E-6;\n break;\n case 4: \/\/ 173882 ft.\n slope = -0.00246891;\n reftemp = 508.788;\n refpress = 1.28428;\n refdens = 1.47035e-06;\n break;\n case 5: \/\/ 259183 ft.\n slope = 0;\n reftemp = 298.188;\n refpress = 0.0222008;\n refdens = 4.33396e-08;\n break;\n case 6: \/\/ 295272 ft.\n slope = 0.00219459;\n reftemp = 298.188;\n refpress = 0.00215742;\n refdens = 4.21368e-09;\n break;\n case 7: \/\/ 344484 ft.\n slope = 0;\n reftemp = 406.188;\n refpress = 0.000153755;\n refdens = 2.20384e-10;\n break;\n }\n\n\n if (slope == 0) {\n temperature = reftemp;\n pressure = refpress*exp(-GRAVITY\/(reftemp*Reng)*(altitude-htab[i]));\n density = refdens*exp(-GRAVITY\/(reftemp*Reng)*(altitude-htab[i]));\n } else {\n temperature = reftemp+slope*(altitude-htab[i]);\n pressure = refpress*pow(temperature\/reftemp,-GRAVITY\/(slope*Reng));\n density = refdens*pow(temperature\/reftemp,-(GRAVITY\/(slope*Reng)+1));\n }\n\n \/\/cout << \"Atmosphere: h=\" << altitude << \" rho= \" << density << endl;\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n *\n * Condor ClassAd library\n * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI, and Rajesh Raman.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of version 2.1 of the GNU Lesser General\n * Public License 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, MA 02111-1307\n * USA\n *\n *********************************************************************\/\n\n#include \"common.h\"\n#include \"exprTree.h\"\n\nusing namespace std;\n\nBEGIN_NAMESPACE( classad )\n\nExprList::\nExprList()\n{\n\tnodeKind = EXPR_LIST_NODE;\n}\n\n\nExprList::\n~ExprList()\n{\n\tClear( );\n}\n\n\nvoid ExprList::\nClear ()\n{\n\tvector<ExprTree*>::iterator itr;\n\tfor( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {\n\t\tdelete *itr;\n\t}\n\texprList.clear( );\n}\n\n\t\nExprList *ExprList::\nCopy( ) const\n{\n\tExprList *newList = new ExprList;\n\tExprTree *newTree;\n\n\tif (newList == 0) return 0;\n\tnewList->parentScope = parentScope;\n\n\tvector<ExprTree*>::const_iterator itr;\n\tfor( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {\n\t\tif( !( newTree = (*itr)->Copy( ) ) ) {\n\t\t\tdelete newList;\n\t\t\tCondorErrno = ERR_MEM_ALLOC_FAILED;\n\t\t\tCondorErrMsg = \"\";\n\t\t\treturn((ExprList*)NULL);\n\t\t}\n\t\tnewList->exprList.push_back( newTree );\n\t}\n\treturn newList;\n}\n\n\nvoid ExprList::\n_SetParentScope( const ClassAd *parent )\n{\n\tvector<ExprTree*>::iterator\titr;\n\tfor( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {\n\t\t(*itr)->SetParentScope( parent );\n\t}\n}\n\n\nExprList *ExprList::\nMakeExprList( const vector<ExprTree*> &exprs )\n{\n\tvector<ExprTree*>::const_iterator itr;\n\tExprList *el = new ExprList;\n\tif( !el ) {\n\t\tCondorErrno = ERR_MEM_ALLOC_FAILED;\n\t\tCondorErrMsg = \"\";\n\t\treturn( NULL );\n\t}\n\tfor( itr=exprs.begin( ) ; itr!=exprs.end( ); itr++ ) {\t\n\t\tel->exprList.push_back( *itr );\n\t}\n\treturn( el );\n}\n\nvoid ExprList::\nGetComponents( vector<ExprTree*> &exprs ) const\n{\n\tvector<ExprTree*>::const_iterator itr;\n\texprs.clear( );\n\tfor( itr=exprList.begin( ); itr!=exprList.end( ); itr++ ) {\n\t\texprs.push_back( *itr );\n\t}\n}\n\n\nbool ExprList::\n_Evaluate (EvalState &, Value &val) const\n{\n\tval.SetListValue (this);\n\treturn( true );\n}\n\nbool ExprList::\n_Evaluate( EvalState &, Value &val, ExprTree *&sig ) const\n{\n\tval.SetListValue( this );\n\treturn( ( sig = Copy( ) ) );\n}\n\nbool ExprList::\n_Flatten( EvalState &state, Value &, ExprTree *&tree, int* ) const\n{\n\tvector<ExprTree*>::const_iterator\titr;\n\tExprTree\t*expr, *nexpr;\n\tValue\t\ttempVal;\n\tExprList\t*newList;\n\n\tif( ( newList = new ExprList( ) ) == NULL ) return false;\n\n\tfor( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {\n\t\texpr = *itr;\n\t\t\/\/ flatten the constituent expression\n\t\tif( !expr->Flatten( state, tempVal, nexpr ) ) {\n\t\t\tdelete newList;\n\t\t\ttree = NULL;\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ if only a value was obtained, convert to an expression\n\t\tif( !nexpr ) {\n\t\t\tnexpr = Literal::MakeLiteral( tempVal );\n\t\t\tif( !nexpr ) {\n\t\t\t\tCondorErrno = ERR_MEM_ALLOC_FAILED;\n\t\t\t\tCondorErrMsg = \"\";\n\t\t\t\tdelete newList;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\/\/ add the new expression to the flattened list\n\t\tnewList->exprList.push_back( nexpr );\n\t}\n\n\ttree = newList;\n\n\treturn true;\n}\n\n\n\/\/ Iterator implementation\nExprListIterator::\nExprListIterator( )\n{\n\tl = NULL;\n}\n\n\nExprListIterator::\nExprListIterator( const ExprList* l )\n{\n\tInitialize( l );\n}\n\n\nExprListIterator::\n~ExprListIterator( )\n{\n}\n\n\nvoid ExprListIterator::\nInitialize( const ExprList *el )\n{\n\t\/\/ initialize eval state\n\tl = el;\n\tstate.cache.clear( );\n\tstate.curAd = (ClassAd*)l->parentScope;\n\tstate.SetRootScope( );\n\n\t\/\/ initialize list iterator\n\titr = l->exprList.begin( );\n}\n\n\nvoid ExprListIterator::\nToFirst( )\n{\n\tif( l ) itr = l->exprList.begin( );\n}\n\n\nvoid ExprListIterator::\nToAfterLast( )\n{\n\tif( l ) itr = l->exprList.end( );\n}\n\n\nbool ExprListIterator::\nToNth( int n ) \n{\n\tif( l && n >= 0 && l->exprList.size( ) > (unsigned)n ) {\n\t\titr = l->exprList.begin( ) + n;\n\t\treturn( true );\n\t}\n\titr = l->exprList.begin( );\n\treturn( false );\n}\n\n\nconst ExprTree* ExprListIterator::\nNextExpr( )\n{\n\tif( l && itr != l->exprList.end( ) ) {\n\t\titr++;\n\t\treturn( itr==l->exprList.end() ? NULL : *itr );\n\t}\n\treturn( NULL );\n}\n\n\nconst ExprTree* ExprListIterator::\nCurrentExpr( ) const\n{\n\treturn( l && itr != l->exprList.end( ) ? *itr : NULL );\n}\n\n\nconst ExprTree* ExprListIterator::\nPrevExpr( )\n{\n\tif( l && itr != l->exprList.begin( ) ) {\n\t\titr++;\n\t\treturn( *itr );\n\t}\n\treturn( NULL );\n}\n\n\nbool ExprListIterator::\nGetValue( Value& val, const ExprTree *tree, EvalState *es )\n{\n\tValue\t\t\t\tcv;\n\tEvalState\t\t\t*currentState;\n EvalCache::iterator\titr;\n\n\tif( !tree ) return false;\n\n\t\/\/ if called from user code, es == NULL so we use &state instead\n\tcurrentState = es ? es : &state;\n\n\t\/\/ lookup in cache\n\titr = currentState->cache.find( tree );\n\n\t\/\/ if found, return cached value\n\tif( itr != currentState->cache.end( ) ) {\n\t\tval.CopyFrom( itr->second );\n\t\treturn true;\n\t} \n\n\t\/\/ temporarily cache value as undef, so any circular refs in\n \/\/ Evaluate() will eval to undef rather than loop\n\n\tcv.SetUndefinedValue( );\n\n\tcurrentState->cache[ tree ] = cv;\n\t\n\tconst ClassAd *tmpScope = es->curAd;\n\tes->curAd = (ClassAd*) tree->GetParentScope();\n\ttree->Evaluate( *currentState, val );\n\tes->curAd = (ClassAd*) tmpScope;\n\n\t\/\/ replace temporary cached value (above) with actual evaluation\n\tcurrentState->cache[ tree ] = val;\n\n\treturn true;\n}\n\n\nbool ExprListIterator::\nNextValue( Value& val, EvalState *es )\n{\n\treturn GetValue( val, NextExpr( ), es );\n}\n\n\nbool ExprListIterator::\nCurrentValue( Value& val, EvalState *es )\n{\n\treturn GetValue( val, CurrentExpr( ), es );\n}\n\n\nbool ExprListIterator::\nPrevValue( Value& val, EvalState *es )\n{\n\treturn GetValue( val, PrevExpr( ), es );\n}\n\n\nbool ExprListIterator::\nGetValue( Value& val, ExprTree*& sig, const ExprTree *tree, EvalState *es ) \n{\n\tValue\t\t\t\tcv;\n\tEvalState\t\t\t*currentState;\n EvalCache::iterator\titr;\n\n\tif( !tree ) return false;\n\n\t\/\/ if called from user code, es == NULL so we use &state instead\n\tcurrentState = es ? es : &state;\n\n\t\/\/ lookup in cache\n\titr = currentState->cache.find( tree );\n\n\t\/\/ if found, return cached value\n\tif( itr != currentState->cache.end( ) ) {\n\t\tval.CopyFrom( itr->second );\n\t\treturn true;\n\t} \n\n\t\/\/ temporarily cache value as undef, so any circular refs in\n \/\/ Evaluate() will eval to undef rather than loop\n\n\tcv.SetUndefinedValue( );\n\tcurrentState->cache[ tree ] = cv;\n\n\tconst ClassAd *tmpScope = es->curAd;\n\tes->curAd = (ClassAd*) tree->GetParentScope();\n\ttree->Evaluate( *currentState, val, sig );\n\tes->curAd = (ClassAd*) tmpScope;\n\n\t\/\/ replace temporary cached value (above) with actual evaluation\n\tcurrentState->cache[ tree ] = val;\n\n\treturn true;\n}\n\n\nbool ExprListIterator::\nNextValue( Value& val, ExprTree*& sig, EvalState *es )\n{\n\treturn GetValue( val, sig, NextExpr( ), es );\n}\n\n\nbool ExprListIterator::\nCurrentValue( Value& val, ExprTree*& sig, EvalState *es )\n{\n\treturn GetValue( val, sig, CurrentExpr( ), es );\n}\n\n\nbool ExprListIterator::\nPrevValue( Value& val, ExprTree*& sig, EvalState *es )\n{\n\treturn GetValue( val, sig, PrevExpr( ), es );\n}\n\n\nbool ExprListIterator::\nIsAtFirst( ) const\n{\n\treturn( l && itr == l->exprList.begin( ) );\n}\n\n\nbool ExprListIterator::\nIsAfterLast( ) const\n{\n\treturn( l && itr == l->exprList.end( ) );\n}\n\nEND_NAMESPACE \/\/ classad\n<commit_msg>Fixed NULL pointer de-reference.<commit_after>\/*********************************************************************\n *\n * Condor ClassAd library\n * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI, and Rajesh Raman.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of version 2.1 of the GNU Lesser General\n * Public License 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, MA 02111-1307\n * USA\n *\n *********************************************************************\/\n\n#include \"common.h\"\n#include \"exprTree.h\"\n\nusing namespace std;\n\nBEGIN_NAMESPACE( classad )\n\nExprList::\nExprList()\n{\n\tnodeKind = EXPR_LIST_NODE;\n}\n\n\nExprList::\n~ExprList()\n{\n\tClear( );\n}\n\n\nvoid ExprList::\nClear ()\n{\n\tvector<ExprTree*>::iterator itr;\n\tfor( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {\n\t\tdelete *itr;\n\t}\n\texprList.clear( );\n}\n\n\t\nExprList *ExprList::\nCopy( ) const\n{\n\tExprList *newList = new ExprList;\n\tExprTree *newTree;\n\n\tif (newList == 0) return 0;\n\tnewList->parentScope = parentScope;\n\n\n\tvector<ExprTree*>::const_iterator itr;\n\tfor( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {\n\t\tif( !( newTree = (*itr)->Copy( ) ) ) {\n\t\t\tdelete newList;\n\t\t\tCondorErrno = ERR_MEM_ALLOC_FAILED;\n\t\t\tCondorErrMsg = \"\";\n\t\t\treturn((ExprList*)NULL);\n\t\t}\n\t\tnewList->exprList.push_back( newTree );\n\t}\n\treturn newList;\n}\n\n\nvoid ExprList::\n_SetParentScope( const ClassAd *parent )\n{\n\tvector<ExprTree*>::iterator\titr;\n\tfor( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {\n\t\t(*itr)->SetParentScope( parent );\n\t}\n}\n\n\nExprList *ExprList::\nMakeExprList( const vector<ExprTree*> &exprs )\n{\n\tvector<ExprTree*>::const_iterator itr;\n\tExprList *el = new ExprList;\n\tif( !el ) {\n\t\tCondorErrno = ERR_MEM_ALLOC_FAILED;\n\t\tCondorErrMsg = \"\";\n\t\treturn( NULL );\n\t}\n\tfor( itr=exprs.begin( ) ; itr!=exprs.end( ); itr++ ) {\t\n\t\tel->exprList.push_back( *itr );\n\t}\n\treturn( el );\n}\n\nvoid ExprList::\nGetComponents( vector<ExprTree*> &exprs ) const\n{\n\tvector<ExprTree*>::const_iterator itr;\n\texprs.clear( );\n\tfor( itr=exprList.begin( ); itr!=exprList.end( ); itr++ ) {\n\t\texprs.push_back( *itr );\n\t}\n}\n\n\nbool ExprList::\n_Evaluate (EvalState &, Value &val) const\n{\n\tval.SetListValue (this);\n\treturn( true );\n}\n\nbool ExprList::\n_Evaluate( EvalState &, Value &val, ExprTree *&sig ) const\n{\n\tval.SetListValue( this );\n\treturn( ( sig = Copy( ) ) );\n}\n\nbool ExprList::\n_Flatten( EvalState &state, Value &, ExprTree *&tree, int* ) const\n{\n\tvector<ExprTree*>::const_iterator\titr;\n\tExprTree\t*expr, *nexpr;\n\tValue\t\ttempVal;\n\tExprList\t*newList;\n\n\tif( ( newList = new ExprList( ) ) == NULL ) return false;\n\n\tfor( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {\n\t\texpr = *itr;\n\t\t\/\/ flatten the constituent expression\n\t\tif( !expr->Flatten( state, tempVal, nexpr ) ) {\n\t\t\tdelete newList;\n\t\t\ttree = NULL;\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ if only a value was obtained, convert to an expression\n\t\tif( !nexpr ) {\n\t\t\tnexpr = Literal::MakeLiteral( tempVal );\n\t\t\tif( !nexpr ) {\n\t\t\t\tCondorErrno = ERR_MEM_ALLOC_FAILED;\n\t\t\t\tCondorErrMsg = \"\";\n\t\t\t\tdelete newList;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\/\/ add the new expression to the flattened list\n\t\tnewList->exprList.push_back( nexpr );\n\t}\n\n\ttree = newList;\n\n\treturn true;\n}\n\n\n\/\/ Iterator implementation\nExprListIterator::\nExprListIterator( )\n{\n\tl = NULL;\n}\n\n\nExprListIterator::\nExprListIterator( const ExprList* l )\n{\n\tInitialize( l );\n}\n\n\nExprListIterator::\n~ExprListIterator( )\n{\n}\n\n\nvoid ExprListIterator::\nInitialize( const ExprList *el )\n{\n\t\/\/ initialize eval state\n\tl = el;\n\tstate.cache.clear( );\n\tstate.curAd = (ClassAd*)l->parentScope;\n\tstate.SetRootScope( );\n\n\t\/\/ initialize list iterator\n\titr = l->exprList.begin( );\n}\n\n\nvoid ExprListIterator::\nToFirst( )\n{\n\tif( l ) itr = l->exprList.begin( );\n}\n\n\nvoid ExprListIterator::\nToAfterLast( )\n{\n\tif( l ) itr = l->exprList.end( );\n}\n\n\nbool ExprListIterator::\nToNth( int n ) \n{\n\tif( l && n >= 0 && l->exprList.size( ) > (unsigned)n ) {\n\t\titr = l->exprList.begin( ) + n;\n\t\treturn( true );\n\t}\n\titr = l->exprList.begin( );\n\treturn( false );\n}\n\n\nconst ExprTree* ExprListIterator::\nNextExpr( )\n{\n\tif( l && itr != l->exprList.end( ) ) {\n\t\titr++;\n\t\treturn( itr==l->exprList.end() ? NULL : *itr );\n\t}\n\treturn( NULL );\n}\n\n\nconst ExprTree* ExprListIterator::\nCurrentExpr( ) const\n{\n\treturn( l && itr != l->exprList.end( ) ? *itr : NULL );\n}\n\n\nconst ExprTree* ExprListIterator::\nPrevExpr( )\n{\n\tif( l && itr != l->exprList.begin( ) ) {\n\t\titr++;\n\t\treturn( *itr );\n\t}\n\treturn( NULL );\n}\n\n\nbool ExprListIterator::\nGetValue( Value& val, const ExprTree *tree, EvalState *es )\n{\n\tValue\t\t\t\tcv;\n\tEvalState\t\t\t*currentState;\n EvalCache::iterator\titr;\n\n\tif( !tree ) return false;\n\n\t\/\/ if called from user code, es == NULL so we use &state instead\n\tcurrentState = es ? es : &state;\n\n\t\/\/ lookup in cache\n\titr = currentState->cache.find( tree );\n\n\t\/\/ if found, return cached value\n\tif( itr != currentState->cache.end( ) ) {\n\t\tval.CopyFrom( itr->second );\n\t\treturn true;\n\t} \n\n\t\/\/ temporarily cache value as undef, so any circular refs in\n \/\/ Evaluate() will eval to undef rather than loop\n\n\tcv.SetUndefinedValue( );\n\n\tcurrentState->cache[ tree ] = cv;\n\t\n\tconst ClassAd *tmpScope = currentState->curAd;\n\tcurrentState->curAd = (ClassAd*) tree->GetParentScope();\n\ttree->Evaluate( *currentState, val );\n\tcurrentState->curAd = (ClassAd*) tmpScope;\n\n\t\/\/ replace temporary cached value (above) with actual evaluation\n\tcurrentState->cache[ tree ] = val;\n\n\treturn true;\n}\n\n\nbool ExprListIterator::\nNextValue( Value& val, EvalState *es )\n{\n\treturn GetValue( val, NextExpr( ), es );\n}\n\n\nbool ExprListIterator::\nCurrentValue( Value& val, EvalState *es )\n{\n\treturn GetValue( val, CurrentExpr( ), es );\n}\n\n\nbool ExprListIterator::\nPrevValue( Value& val, EvalState *es )\n{\n\treturn GetValue( val, PrevExpr( ), es );\n}\n\n\nbool ExprListIterator::\nGetValue( Value& val, ExprTree*& sig, const ExprTree *tree, EvalState *es ) \n{\n\tValue\t\t\t\tcv;\n\tEvalState\t\t\t*currentState;\n EvalCache::iterator\titr;\n\n\tif( !tree ) return false;\n\n\t\/\/ if called from user code, es == NULL so we use &state instead\n\tcurrentState = es ? es : &state;\n\n\t\/\/ lookup in cache\n\titr = currentState->cache.find( tree );\n\n\t\/\/ if found, return cached value\n\tif( itr != currentState->cache.end( ) ) {\n\t\tval.CopyFrom( itr->second );\n\t\treturn true;\n\t} \n\n\t\/\/ temporarily cache value as undef, so any circular refs in\n \/\/ Evaluate() will eval to undef rather than loop\n\n\tcv.SetUndefinedValue( );\n\tcurrentState->cache[ tree ] = cv;\n\n\tconst ClassAd *tmpScope = currentState->curAd;\n\tcurrentState->curAd = (ClassAd*) tree->GetParentScope();\n\ttree->Evaluate( *currentState, val, sig );\n\tcurrentState->curAd = (ClassAd*) tmpScope;\n\n\t\/\/ replace temporary cached value (above) with actual evaluation\n\tcurrentState->cache[ tree ] = val;\n\n\treturn true;\n}\n\n\nbool ExprListIterator::\nNextValue( Value& val, ExprTree*& sig, EvalState *es )\n{\n\treturn GetValue( val, sig, NextExpr( ), es );\n}\n\n\nbool ExprListIterator::\nCurrentValue( Value& val, ExprTree*& sig, EvalState *es )\n{\n\treturn GetValue( val, sig, CurrentExpr( ), es );\n}\n\n\nbool ExprListIterator::\nPrevValue( Value& val, ExprTree*& sig, EvalState *es )\n{\n\treturn GetValue( val, sig, PrevExpr( ), es );\n}\n\n\nbool ExprListIterator::\nIsAtFirst( ) const\n{\n\treturn( l && itr == l->exprList.begin( ) );\n}\n\n\nbool ExprListIterator::\nIsAfterLast( ) const\n{\n\treturn( l && itr == l->exprList.end( ) );\n}\n\nEND_NAMESPACE \/\/ classad\n<|endoftext|>"} {"text":"<commit_before>#include \"PackAnimation.h\"\n#include \"PackNodeFactory.h\"\n#include \"PackAnchor.h\"\n#include \"PackClipbox.h\"\n#include \"Utility.h\"\n#include \"typedef.h\"\n\n#include \"AnimToLuaString.h\"\n#include \"AnimFromLua.h\"\n\n#include \"AnimToBin.h\"\n#include \"AnimFromBin.h\"\n\n#include <ee\/Sprite.h>\n#include <ee\/SymbolFile.h>\n#include <ee\/ImageSprite.h>\n#include <ee\/SymbolFile.h>\n\n#include <sprite2\/SymType.h>\n#include <sprite2\/RenderColor.h>\n#include <sprite2\/RenderShader.h>\n#include <sprite2\/RenderCamera.h>\n#include <sprite2\/RenderFilter.h>\n#include <gum\/trans_color.h>\n\nnamespace erespacker\n{\n\nPackAnimation::PackAnimation(int id)\n\t: IPackNode(id)\n{\n}\n\nvoid PackAnimation::PackToLuaString(ebuilder::CodeGenerator& gen, \n\t\t\t\t\t\t\t\t\tconst ee::TexturePacker& tp,\n\t\t\t\t\t\t\t\t\tfloat scale) const\n{\n\tAnimToLuaString::Pack(this, gen);\n}\n\nvoid PackAnimation::UnpackFromLua(lua_State* L, const std::vector<ee::Image*>& images)\n{\n\tAnimFromLua::Unpack(L, this);\n}\n\nint PackAnimation::SizeOfPackToBin() const\n{\n\treturn AnimToBin::Size(this);\n}\n\nvoid PackAnimation::PackToBin(uint8_t** ptr, \n\t\t\t\t\t\t\t const ee::TexturePacker& tp,\n\t\t\t\t\t\t\t float scale) const\n{\n\tAnimToBin::Pack(this, ptr);\n}\n\nint PackAnimation::SizeOfUnpackFromBin() const\n{\n\treturn AnimFromBin::Size(this);\n}\n\nvoid PackAnimation::UnpackFromBin(uint8_t** ptr, const std::vector<ee::Image*>& images)\n{\n\tAnimFromBin::Unpack(ptr, this);\n}\n\nbool PackAnimation::CreateFramePart(const ee::Sprite* spr, Frame& frame)\n{\t\n\tconst IPackNode* node = PackNodeFactory::Instance()->Create(spr);\n\n\tPackAnimation::Part part;\n\tstd::string name = \"\";\n\tif (Utility::IsNameValid(spr->GetName())) {\n\t\tname = spr->GetName();\n\t}\n\n\tbool force_mat = false;\n\tbool new_comp = AddComponent(node, name, part.comp_idx, force_mat);\n\tPackAnimation::LoadSprTrans(spr, part.t, force_mat);\n\n\tframe.parts.push_back(part);\n\n\treturn new_comp;\n}\n\nvoid PackAnimation::CreateClipboxFramePart(const PackClipbox* cb, Frame& frame)\n{\n\tPackAnimation::Part part;\n\n\tbool force_mat;\n\tAddComponent(cb, \"\", part.comp_idx, force_mat);\n\n\tpart.t.mat[0] = part.t.mat[3] = 1024;\n\tpart.t.mat[1] = part.t.mat[2] = 0;\n\tpart.t.mat[4] = static_cast<int>(cb->x * SCALE);\n\tpart.t.mat[5] =-static_cast<int>(cb->y * SCALE);\n\n\tframe.parts.push_back(part);\n}\n\nvoid PackAnimation::Clear()\n{\n\texport_name.clear();\n\tcomponents.clear();\n\tactions.clear();\n\tframes.clear();\n}\n\nbool PackAnimation::AddComponent(const IPackNode* node, const std::string& name, int& comp_idx, bool& force_mat)\n{\n\tbool new_comp = false;\n\tbool is_anchor = false;\n\tif (const PackAnchor* anchor = dynamic_cast<const PackAnchor*>(node)) {\n\t\tis_anchor = true;\n\t\tfor (int i = 0, n = components.size(); i < n; ++i) {\n\t\t\tif (dynamic_cast<const PackAnchor*>(components[i].node) && components[i].name == name) {\n\t\t\t\tcomp_idx = i;\n\t\t\t\tforce_mat = true;\n\t\t\t\treturn new_comp;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (int i = 0, n = components.size(); i < n; ++i) {\n\t\t\tif (components[i].node == node && components[i].name == name) {\n\t\t\t\tcomp_idx = i;\n\t\t\t\tforce_mat = true;\n\t\t\t\treturn new_comp;\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0, n = components.size(); i < n; ++i) {\n\t\t\tif (components[i].node->GetFilepath() == node->GetFilepath() \n\t\t\t\t&& components[i].name == name\n\t\t\t\t&& !name.empty()) \n\t\t\t{\n\t\t\t\tint type = ee::SymbolFile::Instance()->Type(node->GetFilepath());\n\t\t\t\tswitch (type)\n\t\t\t\t{\n\t\t\t\tcase s2::SYM_IMAGE: case s2::SYM_COMPLEX: case s2::SYM_ANIMATION: case s2::SYM_TEXTBOX: case s2::SYM_MASK: case s2::SYM_PARTICLE3D:\n\t\t\t\t\tcomp_idx = i;\n\t\t\t\t\tforce_mat = true;\n\t\t\t\t\treturn new_comp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tComponent comp;\n\tcomp.node = node;\n\tcomp.name = name;\n\tcomponents.push_back(comp);\n\tcomp_idx = components.size() - 1;\n\n\tnew_comp = true;\n\n\tif (is_anchor) {\n\t\tforce_mat = true;\n\t} else if (ee::SymbolFile::Instance()->Type(node->GetFilepath()) == s2::SYM_IMAGE) {\n\t\tforce_mat = false;\n\t} else {\n\t\tforce_mat = !name.empty();\n\t}\n\n\treturn new_comp;\n}\n\nvoid PackAnimation::LoadSprTrans(const ee::Sprite* spr, SpriteTrans& trans, bool force_mat)\n{\n\tLoadSprMat(spr, trans, force_mat);\n\tLoadSprColor(spr, trans);\n\ttrans.blend = static_cast<int>(spr->GetShader().GetBlend());\n\tif (spr->GetShader().GetFilter()) {\n\t\ttrans.filter = static_cast<int>(spr->GetShader().GetFilter()->GetMode());\n\t} else {\n\t\ttrans.filter = s2::FM_NULL;\n\t}\n\ttrans.camera = static_cast<int>(spr->GetCamera().mode);\n}\n\nvoid PackAnimation::LoadSprMat(const ee::Sprite* spr, SpriteTrans& trans, bool force)\n{\n\tif (!force) {\n\t\treturn;\n\t}\n\n\tfloat mat[6];\n\n\t\/\/ | 1 ky | | sx | | c s | | 1 |\n\t\/\/ | kx 1 | | sy | | -s c | | 1 |\n\t\/\/ | 1 | | 1 | | 1 | | x y 1 |\n\t\/\/ skew scale rotate move\n\n\tmat[1] = mat[2] = mat[4] = mat[5] = 0;\n\tmat[0] = mat[3] = 1;\n\n\tsm::vec2 center = spr->GetCenter();\n\n\tfloat sx = spr->GetScale().x,\n\t\t sy = spr->GetScale().y;\n\tfloat c = cos(-spr->GetAngle()),\n\t\t s = sin(-spr->GetAngle());\n\tfloat kx = -spr->GetShear().x,\n\t\t ky = -spr->GetShear().y;\n\tmat[0] = sx*c - ky*sy*s;\n\tmat[1] = sx*s + ky*sy*c;\n\tmat[2] = kx*sx*c - sy*s;\n\tmat[3] = kx*sx*s + sy*c;\n\tmat[4] = center.x\/* * m_scale*\/;\n\tmat[5] = center.y\/* * m_scale*\/;\n\n\tfor (size_t i = 0; i < 4; ++i) {\n\t\ttrans.mat[i] = static_cast<int>(floor(mat[i] * 1024 + 0.5f));\n\t}\n\tfor (size_t i = 4; i < 6; ++i) {\n\t\ttrans.mat[i] = static_cast<int>(floor(mat[i] * 16 + 0.5f));\n\t}\n\t\/\/ flip y\n\ttrans.mat[5] = -trans.mat[5];\n}\n\nvoid PackAnimation::LoadSprColor(const ee::Sprite* spr, SpriteTrans& trans)\n{\n\tconst s2::RenderColor& rc = spr->GetColor();\n\n\ttrans.color = gum::color2int(rc.mul, gum::ARGB);\n\ttrans.additive = gum::color2int(rc.add, gum::ARGB);\n\n\ttrans.rmap = rc.rmap.ToRGBA();\n\ttrans.gmap = rc.gmap.ToRGBA();\n\ttrans.bmap = rc.bmap.ToRGBA();\t\n}\n\nbool PackAnimation::IsMatrixIdentity(const int* mat)\n{\n\treturn mat[0] == 1024 && mat[3] == 1024 \n\t\t&& mat[1] == 0 && mat[2] == 0 && mat[4] == 0 && mat[5] == 0;\n}\n\n}<commit_msg>Revert \"[FIXED] pack img\"<commit_after>#include \"PackAnimation.h\"\n#include \"PackNodeFactory.h\"\n#include \"PackAnchor.h\"\n#include \"PackClipbox.h\"\n#include \"Utility.h\"\n#include \"typedef.h\"\n\n#include \"AnimToLuaString.h\"\n#include \"AnimFromLua.h\"\n\n#include \"AnimToBin.h\"\n#include \"AnimFromBin.h\"\n\n#include <ee\/Sprite.h>\n#include <ee\/SymbolFile.h>\n#include <ee\/ImageSprite.h>\n#include <ee\/SymbolFile.h>\n\n#include <sprite2\/SymType.h>\n#include <sprite2\/RenderColor.h>\n#include <sprite2\/RenderShader.h>\n#include <sprite2\/RenderCamera.h>\n#include <sprite2\/RenderFilter.h>\n#include <gum\/trans_color.h>\n\nnamespace erespacker\n{\n\nPackAnimation::PackAnimation(int id)\n\t: IPackNode(id)\n{\n}\n\nvoid PackAnimation::PackToLuaString(ebuilder::CodeGenerator& gen, \n\t\t\t\t\t\t\t\t\tconst ee::TexturePacker& tp,\n\t\t\t\t\t\t\t\t\tfloat scale) const\n{\n\tAnimToLuaString::Pack(this, gen);\n}\n\nvoid PackAnimation::UnpackFromLua(lua_State* L, const std::vector<ee::Image*>& images)\n{\n\tAnimFromLua::Unpack(L, this);\n}\n\nint PackAnimation::SizeOfPackToBin() const\n{\n\treturn AnimToBin::Size(this);\n}\n\nvoid PackAnimation::PackToBin(uint8_t** ptr, \n\t\t\t\t\t\t\t const ee::TexturePacker& tp,\n\t\t\t\t\t\t\t float scale) const\n{\n\tAnimToBin::Pack(this, ptr);\n}\n\nint PackAnimation::SizeOfUnpackFromBin() const\n{\n\treturn AnimFromBin::Size(this);\n}\n\nvoid PackAnimation::UnpackFromBin(uint8_t** ptr, const std::vector<ee::Image*>& images)\n{\n\tAnimFromBin::Unpack(ptr, this);\n}\n\nbool PackAnimation::CreateFramePart(const ee::Sprite* spr, Frame& frame)\n{\t\n\tconst IPackNode* node = PackNodeFactory::Instance()->Create(spr);\n\n\tPackAnimation::Part part;\n\tstd::string name = \"\";\n\tif (Utility::IsNameValid(spr->GetName())) {\n\t\tname = spr->GetName();\n\t}\n\n\tbool force_mat = false;\n\tbool new_comp = AddComponent(node, name, part.comp_idx, force_mat);\n\tPackAnimation::LoadSprTrans(spr, part.t, force_mat);\n\n\tframe.parts.push_back(part);\n\n\treturn new_comp;\n}\n\nvoid PackAnimation::CreateClipboxFramePart(const PackClipbox* cb, Frame& frame)\n{\n\tPackAnimation::Part part;\n\n\tbool force_mat;\n\tAddComponent(cb, \"\", part.comp_idx, force_mat);\n\n\tpart.t.mat[0] = part.t.mat[3] = 1024;\n\tpart.t.mat[1] = part.t.mat[2] = 0;\n\tpart.t.mat[4] = static_cast<int>(cb->x * SCALE);\n\tpart.t.mat[5] =-static_cast<int>(cb->y * SCALE);\n\n\tframe.parts.push_back(part);\n}\n\nvoid PackAnimation::Clear()\n{\n\texport_name.clear();\n\tcomponents.clear();\n\tactions.clear();\n\tframes.clear();\n}\n\nbool PackAnimation::AddComponent(const IPackNode* node, const std::string& name, int& comp_idx, bool& force_mat)\n{\n\tbool new_comp = false;\n\tbool is_anchor = false;\n\tif (const PackAnchor* anchor = dynamic_cast<const PackAnchor*>(node)) {\n\t\tis_anchor = true;\n\t\tfor (int i = 0, n = components.size(); i < n; ++i) {\n\t\t\tif (dynamic_cast<const PackAnchor*>(components[i].node) && components[i].name == name) {\n\t\t\t\tcomp_idx = i;\n\t\t\t\tforce_mat = true;\n\t\t\t\treturn new_comp;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (int i = 0, n = components.size(); i < n; ++i) {\n\t\t\tif (components[i].node == node && components[i].name == name) {\n\t\t\t\tcomp_idx = i;\n\t\t\t\tforce_mat = true;\n\t\t\t\treturn new_comp;\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0, n = components.size(); i < n; ++i) {\n\t\t\tif (components[i].node->GetFilepath() == node->GetFilepath() \n\t\t\t\t&& components[i].name == name\n\t\t\t\t&& !name.empty()) \n\t\t\t{\n\t\t\t\tint type = ee::SymbolFile::Instance()->Type(node->GetFilepath());\n\t\t\t\tswitch (type)\n\t\t\t\t{\n\t\t\t\tcase s2::SYM_IMAGE:\n\t\t\t\t\tcomp_idx = i;\n\t\t\t\t\tforce_mat = false;\n\t\t\t\t\treturn new_comp;\n\t\t\t\tcase s2::SYM_COMPLEX: case s2::SYM_ANIMATION: case s2::SYM_TEXTBOX: case s2::SYM_MASK: case s2::SYM_PARTICLE3D:\n\t\t\t\t\tcomp_idx = i;\n\t\t\t\t\tforce_mat = true;\n\t\t\t\t\treturn new_comp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tComponent comp;\n\tcomp.node = node;\n\tcomp.name = name;\n\tcomponents.push_back(comp);\n\tcomp_idx = components.size() - 1;\n\n\tnew_comp = true;\n\n\tif (is_anchor) {\n\t\tforce_mat = true;\n\t} else if (ee::SymbolFile::Instance()->Type(node->GetFilepath()) == s2::SYM_IMAGE) {\n\t\tforce_mat = false;\n\t} else {\n\t\tforce_mat = !name.empty();\n\t}\n\n\treturn new_comp;\n}\n\nvoid PackAnimation::LoadSprTrans(const ee::Sprite* spr, SpriteTrans& trans, bool force_mat)\n{\n\tLoadSprMat(spr, trans, force_mat);\n\tLoadSprColor(spr, trans);\n\ttrans.blend = static_cast<int>(spr->GetShader().GetBlend());\n\tif (spr->GetShader().GetFilter()) {\n\t\ttrans.filter = static_cast<int>(spr->GetShader().GetFilter()->GetMode());\n\t} else {\n\t\ttrans.filter = s2::FM_NULL;\n\t}\n\ttrans.camera = static_cast<int>(spr->GetCamera().mode);\n}\n\nvoid PackAnimation::LoadSprMat(const ee::Sprite* spr, SpriteTrans& trans, bool force)\n{\n\tif (!force && dynamic_cast<const ee::ImageSprite*>(spr)) {\n\t\treturn;\n\t}\n\n\tfloat mat[6];\n\n\t\/\/ | 1 ky | | sx | | c s | | 1 |\n\t\/\/ | kx 1 | | sy | | -s c | | 1 |\n\t\/\/ | 1 | | 1 | | 1 | | x y 1 |\n\t\/\/ skew scale rotate move\n\n\tmat[1] = mat[2] = mat[4] = mat[5] = 0;\n\tmat[0] = mat[3] = 1;\n\n\tsm::vec2 center = spr->GetCenter();\n\n\tfloat sx = spr->GetScale().x,\n\t\t sy = spr->GetScale().y;\n\tfloat c = cos(-spr->GetAngle()),\n\t\t s = sin(-spr->GetAngle());\n\tfloat kx = -spr->GetShear().x,\n\t\t ky = -spr->GetShear().y;\n\tmat[0] = sx*c - ky*sy*s;\n\tmat[1] = sx*s + ky*sy*c;\n\tmat[2] = kx*sx*c - sy*s;\n\tmat[3] = kx*sx*s + sy*c;\n\tmat[4] = center.x\/* * m_scale*\/;\n\tmat[5] = center.y\/* * m_scale*\/;\n\n\tfor (size_t i = 0; i < 4; ++i) {\n\t\ttrans.mat[i] = static_cast<int>(floor(mat[i] * 1024 + 0.5f));\n\t}\n\tfor (size_t i = 4; i < 6; ++i) {\n\t\ttrans.mat[i] = static_cast<int>(floor(mat[i] * 16 + 0.5f));\n\t}\n\t\/\/ flip y\n\ttrans.mat[5] = -trans.mat[5];\n}\n\nvoid PackAnimation::LoadSprColor(const ee::Sprite* spr, SpriteTrans& trans)\n{\n\tconst s2::RenderColor& rc = spr->GetColor();\n\n\ttrans.color = gum::color2int(rc.mul, gum::ARGB);\n\ttrans.additive = gum::color2int(rc.add, gum::ARGB);\n\n\ttrans.rmap = rc.rmap.ToRGBA();\n\ttrans.gmap = rc.gmap.ToRGBA();\n\ttrans.bmap = rc.bmap.ToRGBA();\t\n}\n\nbool PackAnimation::IsMatrixIdentity(const int* mat)\n{\n\treturn mat[0] == 1024 && mat[3] == 1024 \n\t\t&& mat[1] == 0 && mat[2] == 0 && mat[4] == 0 && mat[5] == 0;\n}\n\n}<|endoftext|>"} {"text":"<commit_before>#ifndef CONTAINERS_OBJECT_BUFFER_HPP_\n#define CONTAINERS_OBJECT_BUFFER_HPP_\n\n#include \"errors.hpp\"\n\ntemplate <class T>\nclass object_buffer_t {\npublic:\n \/\/ TODO: this object makes no guarantees that its parent still exists when it is destroyed\n \/\/ is that ok?\n class destruction_sentinel_t {\n public:\n explicit destruction_sentinel_t(object_buffer_t<T> *_parent) : parent(_parent) { }\n\n ~destruction_sentinel_t() {\n if (parent->has()) {\n parent->reset();\n }\n }\n private:\n object_buffer_t<T> *parent;\n\n DISABLE_COPYING(destruction_sentinel_t);\n };\n\n object_buffer_t() : instantiated(false) { }\n ~object_buffer_t() {\n if (instantiated) { reset(); }\n }\n\n#define OBJECT_BUFFER_CREATE_INTERNAL(...) do { \\\n rassert(!instantiated); \\\n instantiated = true; \\\n return new (&object_data[0]) T(__VA_ARGS__); \\\n } while (0)\n\n \/\/ 9 arguments ought to be enough for anybody\n T * create()\n { OBJECT_BUFFER_CREATE_INTERNAL(); }\n\n template <class arg1_t>\n T * create(const arg1_t &arg1)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1); }\n\n template <class arg1_t, class arg2_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2); }\n\n template <class arg1_t, class arg2_t, class arg3_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t, class arg6_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5, const arg6_t &arg6)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5, arg6); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t, class arg6_t, class arg7_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5, const arg6_t &arg6, const arg7_t &arg7)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5, arg6, arg7); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t, class arg6_t, class arg7_t, class arg8_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5, const arg6_t &arg6, const arg7_t &arg7, const arg8_t &arg8)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t, class arg6_t, class arg7_t, class arg8_t, class arg9_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5, const arg6_t &arg6, const arg7_t &arg7, const arg8_t &arg8, const arg9_t &arg9)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); }\n\n T * get() {\n rassert(instantiated);\n return reinterpret_cast<T *>(&object_data[0]);\n }\n\n const T * get() const {\n rassert(instantiated);\n return reinterpret_cast<const T *>(&object_data[0]);\n }\n\n void reset() {\n rassert(instantiated);\n get()->~T();\n instantiated = false;\n }\n\n bool has() const {\n return instantiated;\n }\n\nprivate:\n bool instantiated;\n uint8_t object_data[sizeof(T)];\n\n DISABLE_COPYING(object_buffer_t);\n};\n\n#endif \/\/ CONTAINERS_OBJECT_BUFFER_HPP_\n<commit_msg>Made the object_buffer_t have a higher probability of good alignment.<commit_after>#ifndef CONTAINERS_OBJECT_BUFFER_HPP_\n#define CONTAINERS_OBJECT_BUFFER_HPP_\n\n#include \"errors.hpp\"\n\ntemplate <class T>\nclass object_buffer_t {\npublic:\n class destruction_sentinel_t {\n public:\n explicit destruction_sentinel_t(object_buffer_t<T> *_parent) : parent(_parent) { }\n\n ~destruction_sentinel_t() {\n if (parent->has()) {\n parent->reset();\n }\n }\n private:\n object_buffer_t<T> *parent;\n\n DISABLE_COPYING(destruction_sentinel_t);\n };\n\n object_buffer_t() : instantiated(false) { }\n ~object_buffer_t() {\n if (instantiated) { reset(); }\n }\n\n#define OBJECT_BUFFER_CREATE_INTERNAL(...) do { \\\n rassert(!instantiated); \\\n instantiated = true; \\\n return new (&object_data[0]) T(__VA_ARGS__); \\\n } while (0)\n\n \/\/ 9 arguments ought to be enough for anybody\n T * create()\n { OBJECT_BUFFER_CREATE_INTERNAL(); }\n\n template <class arg1_t>\n T * create(const arg1_t &arg1)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1); }\n\n template <class arg1_t, class arg2_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2); }\n\n template <class arg1_t, class arg2_t, class arg3_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t, class arg6_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5, const arg6_t &arg6)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5, arg6); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t, class arg6_t, class arg7_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5, const arg6_t &arg6, const arg7_t &arg7)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5, arg6, arg7); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t, class arg6_t, class arg7_t, class arg8_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5, const arg6_t &arg6, const arg7_t &arg7, const arg8_t &arg8)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }\n\n template <class arg1_t, class arg2_t, class arg3_t, class arg4_t, class arg5_t, class arg6_t, class arg7_t, class arg8_t, class arg9_t>\n T * create(const arg1_t &arg1, const arg2_t &arg2, const arg3_t &arg3, const arg4_t &arg4, const arg5_t &arg5, const arg6_t &arg6, const arg7_t &arg7, const arg8_t &arg8, const arg9_t &arg9)\n { OBJECT_BUFFER_CREATE_INTERNAL(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); }\n\n T * get() {\n rassert(instantiated);\n return reinterpret_cast<T *>(&object_data[0]);\n }\n\n const T * get() const {\n rassert(instantiated);\n return reinterpret_cast<const T *>(&object_data[0]);\n }\n\n void reset() {\n rassert(instantiated);\n get()->~T();\n instantiated = false;\n }\n\n bool has() const {\n return instantiated;\n }\n\nprivate:\n \/\/ We're going more for a high probability of good alignment than\n \/\/ proof of good alignment.\n uint8_t object_data[sizeof(T)];\n bool instantiated;\n\n DISABLE_COPYING(object_buffer_t);\n};\n\n#endif \/\/ CONTAINERS_OBJECT_BUFFER_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"input_manager.hpp\"\n\n#include \"input_mapping.hpp\"\n\n#include \"..\/asset\/asset_manager.hpp\"\n#include \"..\/utils\/template_utils.hpp\"\n\n#include <glm\/glm.hpp>\n#include <sf2\/sf2.hpp>\n\n#include <SDL2\/SDL_gesture.h>\n\n#ifdef EMSCRIPTEN\n\t#include <emscripten\/html5.h>\n#endif\n\n\nnamespace lux {\nnamespace input {\n\n\tusing namespace unit_literals;\n\n\tclass Input_manager::Gamepad {\n\t\tpublic:\n\t\t\tGamepad(Input_source src_id, SDL_GameController*, Input_mapper& mapper);\n\t\t\t~Gamepad();\n\n\t\t\tvoid force_feedback(float force);\n\n\t\t\tauto button_pressed(Pad_button b)const noexcept -> bool;\n\t\t\tauto button_released(Pad_button b)const noexcept -> bool;\n\n\t\t\tauto button_down(Pad_button b)const noexcept -> bool;\n\t\t\tauto button_up(Pad_button b)const noexcept -> bool;\n\t\t\tauto trigger(Pad_button b)const noexcept -> float;\n\n\t\t\tvoid update(Time dt);\n\n\t\t\tauto axis(Pad_stick stick) -> glm::vec2;\n\n\t\t\tauto id()const noexcept {return _id;}\n\n\t\tprivate:\n\t\t\tInput_source _src_id;\n\t\t\tint _id;\n\t\t\tSDL_GameController* _sdl_controller;\n\t\t\tSDL_Haptic* _haptic;\n\t\t\tInput_mapper& _mapper;\n\n\t\t\tuint8_t _button_state[pad_button_count] {};\n\t\t\tfloat _button_value[pad_button_count] {};\n\t\t\tglm::vec2 _stick_state[pad_stick_count] {};\n\n\t\t\tfloat _stick_dead_zone=0.2, _stick_max=32767;\n\n\t\t\tfloat _current_force = 0.f;\n\t\t\tTime _force_reset_timer {0.f};\n\t};\n\n\tnamespace {\n\t\tinline auto from_sdl_keycode(SDL_Keycode key) {\n\t\t\treturn static_cast<Key>(key);\n\t\t}\n\n\t\tinline auto to_sdl_pad_button(Pad_button b) {\n\t\t\treturn static_cast<SDL_GameControllerButton>(b);\n\t\t}\n\t\tinline bool is_trigger(Pad_button b) {\n\t\t\treturn b==Pad_button::left_trigger || b==Pad_button::right_trigger;\n\t\t}\n\n\t\tinline auto to_sdl_axis_x(Pad_stick s) {\n\t\t\tswitch(s) {\n\t\t\t\tcase Pad_stick::left: return SDL_CONTROLLER_AXIS_LEFTX;\n\t\t\t\tcase Pad_stick::right: return SDL_CONTROLLER_AXIS_RIGHTX;\n\t\t\t\tdefault: return SDL_CONTROLLER_AXIS_INVALID;\n\t\t\t}\n\t\t}\n\t\tinline auto to_sdl_axis_y(Pad_stick s) {\n\t\t\tswitch(s) {\n\t\t\t\tcase Pad_stick::left: return SDL_CONTROLLER_AXIS_LEFTY;\n\t\t\t\tcase Pad_stick::right: return SDL_CONTROLLER_AXIS_RIGHTY;\n\t\t\t\tdefault: return SDL_CONTROLLER_AXIS_INVALID;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tInput_manager::Input_manager(util::Message_bus& bus,\n\t asset::Asset_manager& assets)\n\t : _mailbox(bus),\n\t _screen_to_world_coords(&util::identity<glm::vec2>),\n\t _mapper(std::make_unique<Input_mapper>(bus, assets)) {\n\n\t\tSDL_JoystickEventState(SDL_ENABLE);\n\t\tSDL_GameControllerEventState(SDL_ENABLE);\n\n\t\tSDL_RecordGesture(-1);\n\n\t\t_mailbox.subscribe<Force_feedback, 4>(8, [&](auto& m) {\n\t\t\tauto handle = [&](Force_feedback fb) {\n\t\t\t\tif(m.src>0 && m.src-1<static_cast<int>(this->_gamepads.size())) {\n\t\t\t\t\tauto& pad = this->_gamepads.at(m.src-1);\n\t\t\t\t\tif(pad)\n\t\t\t\t\t\tpad->force_feedback(m.force);\n\t\t\t\t}\n\n\t#ifdef EMSCRIPTEN\n\t\t\t\tif(m.src==0 && m.force>0.5)\n\t\t\t\t\temscripten_vibrate(200);\n\t#endif\n\t\t\t};\n\n\t\t\tif(m.src>=0)\n\t\t\t\thandle(m);\n\n\t\t\telse {\n\t\t\t\tfor(auto i=0u; i<this->_gamepads.size()+1; i++) {\n\t\t\t\t\tm.src = i;\n\t\t\t\t\thandle(m);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tInput_manager::~Input_manager()noexcept {\n\t}\n\n\tvoid Input_manager::update(Time dt) {\n\t\tfor(auto& gp : _gamepads)\n\t\t\tgp->update(dt);\n\n\t\t_mailbox.update_subscriptions();\n\t}\n\n\n\tvoid Input_manager::handle_event(SDL_Event& event) {\n\t\tswitch(event.type) {\n\t\t\tcase SDL_TEXTINPUT:\n\t\t\t\t_mailbox.send<Char_input>(event.text.text);\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_KEYDOWN:\n\t\t\t\tif(event.key.repeat==0)\n\t\t\t\t\t_mapper->on_key_pressed(from_sdl_keycode(event.key.keysym.sym));\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_KEYUP:\n\t\t\t\tif(event.key.repeat==0)\n\t\t\t\t\t_mapper->on_key_released(from_sdl_keycode(event.key.keysym.sym));\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_MOUSEMOTION: {\n\t\t\t\tauto idx = 0;\n\t\t\t\tauto screen_pos = glm::vec2{event.motion.x, event.motion.y};\n\t\t\t\tauto world_pos = _screen_to_world_coords(screen_pos);\n\t\t\t\tauto world_diff = world_pos - _pointer_world_pos[idx];\n\n\t\t\t\t_pointer_screen_pos[idx] = screen_pos;\n\t\t\t\t_pointer_world_pos[idx] = world_pos;\n\n\t\t\t\t_mapper->on_mouse_pos_change(world_diff, world_pos);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase SDL_MOUSEBUTTONDOWN:\n\t\t\t\t_mapper->on_mouse_button_pressed(event.button.button);\n\t\t\t\t_pointer_active[0] = true;\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_MOUSEBUTTONUP:\n\t\t\t\t_mapper->on_mouse_button_released(event.button.button, event.button.clicks);\n\t\t\t\t_pointer_active[0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_FINGERMOTION:\n\t\t\tcase SDL_FINGERUP:\n\t\t\tcase SDL_FINGERDOWN: {\n\t\t\t\tint idx = 0;\n\t\t\t\tfor(;idx<_max_pointers; idx++) {\n\t\t\t\t\tif(_pointer_finger_id[idx] == event.tfinger.fingerId)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(idx>=_max_pointers) {\n\t\t\t\t\tfor(idx=0; idx<_max_pointers; idx++) {\n\t\t\t\t\t\tif(!_pointer_active[idx])\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(idx<_max_pointers) {\n\t\t\t\t\tauto screen_pos = glm::vec2{event.tfinger.x, event.tfinger.y};\n\t\t\t\t\tif(screen_pos.x<=1.0f && screen_pos.y<=1.0f) {\n\t\t\t\t\t\tscreen_pos *= glm::vec2{_viewport.z,_viewport.w};\n\t\t\t\t\t\tscreen_pos += glm::vec2{_viewport.x,_viewport.y};\n\t\t\t\t\t}\n\n\t\t\t\t\tauto world_pos = _screen_to_world_coords(screen_pos);\n\t\t\t\t\tauto world_diff = world_pos - _pointer_world_pos[idx];\n\n\t\t\t\t\t_pointer_finger_id[idx] = event.tfinger.fingerId;\n\t\t\t\t\t_pointer_screen_pos[idx] = screen_pos;\n\t\t\t\t\t_pointer_world_pos[idx] = world_pos;\n\t\t\t\t\t_pointer_active[idx] = event.type!=SDL_FINGERUP;\n\n\t\t\t\t\tif(idx==0) { \/\/< mouse emulation\n\t\t\t\t\t\t_mapper->on_mouse_pos_change(world_diff, world_pos);\n\n\t\t\t\t\t\tif(event.tfinger.type==SDL_FINGERDOWN)\n\t\t\t\t\t\t\t_mapper->on_mouse_button_pressed(1, event.tfinger.pressure);\n\t\t\t\t\t\telse if(event.tfinger.type==SDL_FINGERUP)\n\t\t\t\t\t\t\t_mapper->on_mouse_button_released(1, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase SDL_MOUSEWHEEL:\n\t\t\t\t_mapper->on_mouse_wheel_change({event.wheel.x,event.wheel.y});\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_CONTROLLERDEVICEADDED:\n\t\t\t\t_add_gamepad(event.cdevice.which);\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_CONTROLLERDEVICEREMOVED:\n\t\t\t\t_remove_gamepad(event.cdevice.which);\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_CONTROLLERDEVICEREMAPPED:\n\t\t\t\tbreak; \/\/ ignored for now\n\t\t}\n\t}\n\tvoid Input_manager::_add_gamepad(int joystick_id) {\n\t\tif(joystick_id==-1)\n\t\t\tjoystick_id = SDL_NumJoysticks()-1;\n\n\t\tif (SDL_IsGameController(joystick_id)) {\n\t\t\tSDL_GameController* controller = SDL_GameControllerOpen(joystick_id);\n\t\t\tif (controller) {\n\t\t\t\t_gamepads.emplace_back(std::make_unique<Gamepad>(\n\t\t\t\t\t\t_gamepads.size()+1,\n\t\t\t\t\t\tcontroller,\n\t\t\t\t\t\t*_mapper ));\n\t\t\t\t_mailbox.send<Source_added>(Input_source(_gamepads.size()));\n\n\t\t\t} else {\n\t\t\t\tstd::cerr<<\"Could not open gamecontroller \"<<joystick_id<<\": \"<<SDL_GetError()<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Input_manager::_remove_gamepad(int instance_id) {\n\t\tauto e = std::find_if(_gamepads.begin(), _gamepads.end(),\n\t\t\t\t\t [instance_id](auto& c) {\n\t\t\treturn c->id()==instance_id;\n\t\t});\n\n\t\tif(e!=_gamepads.end()) {\n\t\t\tauto idx = std::distance(_gamepads.begin(), e);\n\t\t\t_mailbox.send<Source_removed>(Input_source(idx));\n\t\t\te->reset();\n\t\t}\n\t}\n\n\tvoid Input_manager::enable_context(Context_id id) {\n\t\t_mapper->enable_context(id);\n\t}\n\n\n\t\/\/ Gamepad impl\n\tInput_manager::Gamepad::Gamepad(Input_source src_id,\n\t SDL_GameController* c,\n\t Input_mapper& mapper)\n\t : _src_id(src_id),\n\t _id(SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(c))),\n\t _sdl_controller(c),\n\t _mapper(mapper) {\n\n\t\tauto name = SDL_GameControllerName(_sdl_controller);\n\n\t\t_haptic = SDL_HapticOpenFromJoystick(SDL_GameControllerGetJoystick(_sdl_controller));\n\t\tif(!_haptic)\n\t\t\tWARN(\"Warning: Controller '\"<<name<<\n\t\t\t\t\t \"'' does not support haptics: \"<< SDL_GetError());\n\n\t\telse {\n\t\t\tif( SDL_HapticRumbleInit(_haptic) < 0 ) {\n\t\t\t\t_haptic = nullptr;\n\t\t\t\tWARN(\"Warning: Unable to initialize rumble for '\"<<name<<\n\t\t\t\t\t\t \"': \"<<SDL_GetError());\n\t\t\t}\n\t\t}\n\n\t\tINFO(\"Detected gamepad '\"<<name<<\"'\");\n\t}\n\tInput_manager::Gamepad::~Gamepad() {\n\t\tif(_haptic)\n\t\t\tSDL_HapticClose(_haptic);\n\n\t\tSDL_GameControllerClose(_sdl_controller);\n\t}\n\n\tvoid Input_manager::Gamepad::force_feedback(float force) {\n\t\tif(force > _current_force) {\n\t\t\t_force_reset_timer = 200_ms;\n\t\t\t_current_force = force;\n\t\t}\n\n\t\tif(_haptic)\n\t\t\tSDL_HapticRumblePlay(_haptic, glm::clamp(_current_force,0.f,1.f), 200);\n\t}\n\n\tauto Input_manager::Gamepad::button_pressed(Pad_button b)const noexcept -> bool {\n\t\treturn _button_state[static_cast<int8_t>(b)]==1;\n\t}\n\tauto Input_manager::Gamepad::button_released(Pad_button b)const noexcept -> bool {\n\t\treturn _button_state[static_cast<int8_t>(b)]==3;\n\t}\n\n\tauto Input_manager::Gamepad::trigger(Pad_button b)const noexcept -> float {\n\t\tauto state = [&](auto t) {\n\t\t\treturn glm::abs(SDL_GameControllerGetAxis(_sdl_controller,t)) \/ _stick_max;\n\t\t};\n\n\t\tif(b==Pad_button::left_trigger)\n\t\t\treturn state(SDL_CONTROLLER_AXIS_TRIGGERLEFT);\n\n\t\telse if(b==Pad_button::right_trigger)\n\t\t\treturn state(SDL_CONTROLLER_AXIS_TRIGGERRIGHT);\n\n\t\telse\n\t\t\treturn 0;\n\t}\n\n\tauto Input_manager::Gamepad::button_down(Pad_button button)const noexcept -> bool {\n\t\tif(!is_trigger(button))\n\t\t\treturn SDL_GameControllerGetButton(_sdl_controller, to_sdl_pad_button(button))!=0;\n\n\t\telse\n\t\t\treturn trigger(button) > _stick_dead_zone;\n\t}\n\tauto Input_manager::Gamepad::button_up(Pad_button b)const noexcept -> bool {\n\t\treturn !button_down(b);\n\t}\n\n\tvoid Input_manager::Gamepad::update(Time dt) {\n\t\tif(_force_reset_timer>0_s) {\n\t\t\t_force_reset_timer-=dt;\n\t\t\tif(_force_reset_timer<0_s)\n\t\t\t\t_current_force = 0.f;\n\t\t}\n\n\t\tfor(auto i : util::range(pad_button_count)) {\n\t\t\tauto button = static_cast<Pad_button>(i);\n\t\t\tbool down = button_down(button);\n\n\t\t\tswitch(_button_state[i]) {\n\t\t\t\tcase 0: \/\/ up\n\t\t\t\t\t_button_state[i] = down ? 1 : 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1: \/\/ pressed\n\t\t\t\t\t_button_state[i] = down ? 2 : 3;\n\t\t\t\t\tif(is_trigger(button))\n\t\t\t\t\t\t_mapper.on_pad_button_pressed(_src_id, button,\n\t\t\t\t\t\t trigger(button));\n\t\t\t\t\telse\n\t\t\t\t\t\t_mapper.on_pad_button_pressed(_src_id, button, 1.f);\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2: \/\/ down\n\t\t\t\t\t_button_state[i] = down ? 2 : 3;\n\t\t\t\t\t{\n\t\t\t\t\t\tauto value = trigger(button);\n\t\t\t\t\t\tif(std::abs(_button_value[i]-value)>0.1) {\n\t\t\t\t\t\t\t_mapper.on_pad_button_changed(_src_id,button,value);\n\t\t\t\t\t\t\t_button_value[i] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3: \/\/ released\n\t\t\t\t\t_button_state[i] = down ? 1 : 0;\n\t\t\t\t\t_mapper.on_pad_button_released(_src_id, button);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tfor(auto i : util::range(pad_stick_count)) {\n\t\t\tauto stick = static_cast<Pad_stick>(i);\n\n\t\t\tauto state = axis(stick);\n\t\t\tif(state!=_stick_state[i]) {\n\t\t\t\t_mapper.on_pad_stick_change(_src_id, stick, state-_stick_state[i], state);\n\t\t\t\t_stick_state[i] = state;\n\t\t\t}\n\t\t}\n\t}\n\n\tauto Input_manager::Gamepad::axis(Pad_stick s) -> glm::vec2 {\n\t\tglm::vec2 v {\n\t\t\tSDL_GameControllerGetAxis(_sdl_controller, to_sdl_axis_x(s)) \/ _stick_max,\n\t\t\tSDL_GameControllerGetAxis(_sdl_controller, to_sdl_axis_y(s)) \/ _stick_max,\n\t\t};\n\n\t\tauto dz = _stick_dead_zone;\n\t\tauto length = glm::length(v);\n\n\t\tif(length<dz)\n\t\t\treturn glm::vec2{0,0};\n\n\t\treturn v\/length * ((length-dz)\/(1-dz));\n\t}\n\n}\n}\n<commit_msg>fixed mouse drag<commit_after>#include \"input_manager.hpp\"\n\n#include \"input_mapping.hpp\"\n\n#include \"..\/asset\/asset_manager.hpp\"\n#include \"..\/utils\/template_utils.hpp\"\n\n#include <glm\/glm.hpp>\n#include <sf2\/sf2.hpp>\n\n#include <SDL2\/SDL_gesture.h>\n\n#ifdef EMSCRIPTEN\n\t#include <emscripten\/html5.h>\n#endif\n\n\nnamespace lux {\nnamespace input {\n\n\tusing namespace unit_literals;\n\n\tclass Input_manager::Gamepad {\n\t\tpublic:\n\t\t\tGamepad(Input_source src_id, SDL_GameController*, Input_mapper& mapper);\n\t\t\t~Gamepad();\n\n\t\t\tvoid force_feedback(float force);\n\n\t\t\tauto button_pressed(Pad_button b)const noexcept -> bool;\n\t\t\tauto button_released(Pad_button b)const noexcept -> bool;\n\n\t\t\tauto button_down(Pad_button b)const noexcept -> bool;\n\t\t\tauto button_up(Pad_button b)const noexcept -> bool;\n\t\t\tauto trigger(Pad_button b)const noexcept -> float;\n\n\t\t\tvoid update(Time dt);\n\n\t\t\tauto axis(Pad_stick stick) -> glm::vec2;\n\n\t\t\tauto id()const noexcept {return _id;}\n\n\t\tprivate:\n\t\t\tInput_source _src_id;\n\t\t\tint _id;\n\t\t\tSDL_GameController* _sdl_controller;\n\t\t\tSDL_Haptic* _haptic;\n\t\t\tInput_mapper& _mapper;\n\n\t\t\tuint8_t _button_state[pad_button_count] {};\n\t\t\tfloat _button_value[pad_button_count] {};\n\t\t\tglm::vec2 _stick_state[pad_stick_count] {};\n\n\t\t\tfloat _stick_dead_zone=0.2, _stick_max=32767;\n\n\t\t\tfloat _current_force = 0.f;\n\t\t\tTime _force_reset_timer {0.f};\n\t};\n\n\tnamespace {\n\t\tinline auto from_sdl_keycode(SDL_Keycode key) {\n\t\t\treturn static_cast<Key>(key);\n\t\t}\n\n\t\tinline auto to_sdl_pad_button(Pad_button b) {\n\t\t\treturn static_cast<SDL_GameControllerButton>(b);\n\t\t}\n\t\tinline bool is_trigger(Pad_button b) {\n\t\t\treturn b==Pad_button::left_trigger || b==Pad_button::right_trigger;\n\t\t}\n\n\t\tinline auto to_sdl_axis_x(Pad_stick s) {\n\t\t\tswitch(s) {\n\t\t\t\tcase Pad_stick::left: return SDL_CONTROLLER_AXIS_LEFTX;\n\t\t\t\tcase Pad_stick::right: return SDL_CONTROLLER_AXIS_RIGHTX;\n\t\t\t\tdefault: return SDL_CONTROLLER_AXIS_INVALID;\n\t\t\t}\n\t\t}\n\t\tinline auto to_sdl_axis_y(Pad_stick s) {\n\t\t\tswitch(s) {\n\t\t\t\tcase Pad_stick::left: return SDL_CONTROLLER_AXIS_LEFTY;\n\t\t\t\tcase Pad_stick::right: return SDL_CONTROLLER_AXIS_RIGHTY;\n\t\t\t\tdefault: return SDL_CONTROLLER_AXIS_INVALID;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tInput_manager::Input_manager(util::Message_bus& bus,\n\t asset::Asset_manager& assets)\n\t : _mailbox(bus),\n\t _screen_to_world_coords(&util::identity<glm::vec2>),\n\t _mapper(std::make_unique<Input_mapper>(bus, assets)) {\n\n\t\tSDL_JoystickEventState(SDL_ENABLE);\n\t\tSDL_GameControllerEventState(SDL_ENABLE);\n\n\t\tSDL_RecordGesture(-1);\n\n\t\t_mailbox.subscribe<Force_feedback, 4>(8, [&](auto& m) {\n\t\t\tauto handle = [&](Force_feedback fb) {\n\t\t\t\tif(m.src>0 && m.src-1<static_cast<int>(this->_gamepads.size())) {\n\t\t\t\t\tauto& pad = this->_gamepads.at(m.src-1);\n\t\t\t\t\tif(pad)\n\t\t\t\t\t\tpad->force_feedback(m.force);\n\t\t\t\t}\n\n\t#ifdef EMSCRIPTEN\n\t\t\t\tif(m.src==0 && m.force>0.5)\n\t\t\t\t\temscripten_vibrate(200);\n\t#endif\n\t\t\t};\n\n\t\t\tif(m.src>=0)\n\t\t\t\thandle(m);\n\n\t\t\telse {\n\t\t\t\tfor(auto i=0u; i<this->_gamepads.size()+1; i++) {\n\t\t\t\t\tm.src = i;\n\t\t\t\t\thandle(m);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tInput_manager::~Input_manager()noexcept {\n\t}\n\n\tvoid Input_manager::update(Time dt) {\n\t\tfor(auto& gp : _gamepads)\n\t\t\tgp->update(dt);\n\n\t\t_mailbox.update_subscriptions();\n\t}\n\n\n\tvoid Input_manager::handle_event(SDL_Event& event) {\n\t\tswitch(event.type) {\n\t\t\tcase SDL_TEXTINPUT:\n\t\t\t\t_mailbox.send<Char_input>(event.text.text);\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_KEYDOWN:\n\t\t\t\tif(event.key.repeat==0)\n\t\t\t\t\t_mapper->on_key_pressed(from_sdl_keycode(event.key.keysym.sym));\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_KEYUP:\n\t\t\t\tif(event.key.repeat==0)\n\t\t\t\t\t_mapper->on_key_released(from_sdl_keycode(event.key.keysym.sym));\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_MOUSEMOTION: {\n\t\t\t\tauto idx = 0;\n\t\t\t\tauto screen_pos = glm::vec2{event.motion.x, event.motion.y};\n\t\t\t\tauto world_pos = _screen_to_world_coords(screen_pos);\n\t\t\t\tauto screen_diff = screen_pos - _pointer_screen_pos[idx];\n\n\t\t\t\t_pointer_screen_pos[idx] = screen_pos;\n\t\t\t\t_pointer_world_pos[idx] = world_pos;\n\n\t\t\t\t_mapper->on_mouse_pos_change(screen_diff, screen_pos);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase SDL_MOUSEBUTTONDOWN:\n\t\t\t\t_mapper->on_mouse_button_pressed(event.button.button);\n\t\t\t\t_pointer_active[0] = true;\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_MOUSEBUTTONUP:\n\t\t\t\t_mapper->on_mouse_button_released(event.button.button, event.button.clicks);\n\t\t\t\t_pointer_active[0] = false;\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_FINGERMOTION:\n\t\t\tcase SDL_FINGERUP:\n\t\t\tcase SDL_FINGERDOWN: {\n\t\t\t\tint idx = 0;\n\t\t\t\tfor(;idx<_max_pointers; idx++) {\n\t\t\t\t\tif(_pointer_finger_id[idx] == event.tfinger.fingerId)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(idx>=_max_pointers) {\n\t\t\t\t\tfor(idx=0; idx<_max_pointers; idx++) {\n\t\t\t\t\t\tif(!_pointer_active[idx])\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(idx<_max_pointers) {\n\t\t\t\t\tauto screen_pos = glm::vec2{event.tfinger.x, event.tfinger.y};\n\t\t\t\t\tif(screen_pos.x<=1.0f && screen_pos.y<=1.0f) {\n\t\t\t\t\t\tscreen_pos *= glm::vec2{_viewport.z,_viewport.w};\n\t\t\t\t\t\tscreen_pos += glm::vec2{_viewport.x,_viewport.y};\n\t\t\t\t\t}\n\n\t\t\t\t\tauto world_pos = _screen_to_world_coords(screen_pos);\n\t\t\t\t\tauto screen_diff = screen_pos - _pointer_screen_pos[idx];\n\n\t\t\t\t\t_pointer_finger_id[idx] = event.tfinger.fingerId;\n\t\t\t\t\t_pointer_screen_pos[idx] = screen_pos;\n\t\t\t\t\t_pointer_world_pos[idx] = world_pos;\n\t\t\t\t\t_pointer_active[idx] = event.type!=SDL_FINGERUP;\n\n\t\t\t\t\tif(idx==0) { \/\/< mouse emulation\n\t\t\t\t\t\t_mapper->on_mouse_pos_change(screen_diff, screen_pos);\n\n\t\t\t\t\t\tif(event.tfinger.type==SDL_FINGERDOWN)\n\t\t\t\t\t\t\t_mapper->on_mouse_button_pressed(1, event.tfinger.pressure);\n\t\t\t\t\t\telse if(event.tfinger.type==SDL_FINGERUP)\n\t\t\t\t\t\t\t_mapper->on_mouse_button_released(1, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase SDL_MOUSEWHEEL:\n\t\t\t\t_mapper->on_mouse_wheel_change({event.wheel.x,event.wheel.y});\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_CONTROLLERDEVICEADDED:\n\t\t\t\t_add_gamepad(event.cdevice.which);\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_CONTROLLERDEVICEREMOVED:\n\t\t\t\t_remove_gamepad(event.cdevice.which);\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_CONTROLLERDEVICEREMAPPED:\n\t\t\t\tbreak; \/\/ ignored for now\n\t\t}\n\t}\n\tvoid Input_manager::_add_gamepad(int joystick_id) {\n\t\tif(joystick_id==-1)\n\t\t\tjoystick_id = SDL_NumJoysticks()-1;\n\n\t\tif (SDL_IsGameController(joystick_id)) {\n\t\t\tSDL_GameController* controller = SDL_GameControllerOpen(joystick_id);\n\t\t\tif (controller) {\n\t\t\t\t_gamepads.emplace_back(std::make_unique<Gamepad>(\n\t\t\t\t\t\t_gamepads.size()+1,\n\t\t\t\t\t\tcontroller,\n\t\t\t\t\t\t*_mapper ));\n\t\t\t\t_mailbox.send<Source_added>(Input_source(_gamepads.size()));\n\n\t\t\t} else {\n\t\t\t\tstd::cerr<<\"Could not open gamecontroller \"<<joystick_id<<\": \"<<SDL_GetError()<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Input_manager::_remove_gamepad(int instance_id) {\n\t\tauto e = std::find_if(_gamepads.begin(), _gamepads.end(),\n\t\t\t\t\t [instance_id](auto& c) {\n\t\t\treturn c->id()==instance_id;\n\t\t});\n\n\t\tif(e!=_gamepads.end()) {\n\t\t\tauto idx = std::distance(_gamepads.begin(), e);\n\t\t\t_mailbox.send<Source_removed>(Input_source(idx));\n\t\t\te->reset();\n\t\t}\n\t}\n\n\tvoid Input_manager::enable_context(Context_id id) {\n\t\t_mapper->enable_context(id);\n\t}\n\n\n\t\/\/ Gamepad impl\n\tInput_manager::Gamepad::Gamepad(Input_source src_id,\n\t SDL_GameController* c,\n\t Input_mapper& mapper)\n\t : _src_id(src_id),\n\t _id(SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(c))),\n\t _sdl_controller(c),\n\t _mapper(mapper) {\n\n\t\tauto name = SDL_GameControllerName(_sdl_controller);\n\n\t\t_haptic = SDL_HapticOpenFromJoystick(SDL_GameControllerGetJoystick(_sdl_controller));\n\t\tif(!_haptic)\n\t\t\tWARN(\"Warning: Controller '\"<<name<<\n\t\t\t\t\t \"'' does not support haptics: \"<< SDL_GetError());\n\n\t\telse {\n\t\t\tif( SDL_HapticRumbleInit(_haptic) < 0 ) {\n\t\t\t\t_haptic = nullptr;\n\t\t\t\tWARN(\"Warning: Unable to initialize rumble for '\"<<name<<\n\t\t\t\t\t\t \"': \"<<SDL_GetError());\n\t\t\t}\n\t\t}\n\n\t\tINFO(\"Detected gamepad '\"<<name<<\"'\");\n\t}\n\tInput_manager::Gamepad::~Gamepad() {\n\t\tif(_haptic)\n\t\t\tSDL_HapticClose(_haptic);\n\n\t\tSDL_GameControllerClose(_sdl_controller);\n\t}\n\n\tvoid Input_manager::Gamepad::force_feedback(float force) {\n\t\tif(force > _current_force) {\n\t\t\t_force_reset_timer = 200_ms;\n\t\t\t_current_force = force;\n\t\t}\n\n\t\tif(_haptic)\n\t\t\tSDL_HapticRumblePlay(_haptic, glm::clamp(_current_force,0.f,1.f), 200);\n\t}\n\n\tauto Input_manager::Gamepad::button_pressed(Pad_button b)const noexcept -> bool {\n\t\treturn _button_state[static_cast<int8_t>(b)]==1;\n\t}\n\tauto Input_manager::Gamepad::button_released(Pad_button b)const noexcept -> bool {\n\t\treturn _button_state[static_cast<int8_t>(b)]==3;\n\t}\n\n\tauto Input_manager::Gamepad::trigger(Pad_button b)const noexcept -> float {\n\t\tauto state = [&](auto t) {\n\t\t\treturn glm::abs(SDL_GameControllerGetAxis(_sdl_controller,t)) \/ _stick_max;\n\t\t};\n\n\t\tif(b==Pad_button::left_trigger)\n\t\t\treturn state(SDL_CONTROLLER_AXIS_TRIGGERLEFT);\n\n\t\telse if(b==Pad_button::right_trigger)\n\t\t\treturn state(SDL_CONTROLLER_AXIS_TRIGGERRIGHT);\n\n\t\telse\n\t\t\treturn 0;\n\t}\n\n\tauto Input_manager::Gamepad::button_down(Pad_button button)const noexcept -> bool {\n\t\tif(!is_trigger(button))\n\t\t\treturn SDL_GameControllerGetButton(_sdl_controller, to_sdl_pad_button(button))!=0;\n\n\t\telse\n\t\t\treturn trigger(button) > _stick_dead_zone;\n\t}\n\tauto Input_manager::Gamepad::button_up(Pad_button b)const noexcept -> bool {\n\t\treturn !button_down(b);\n\t}\n\n\tvoid Input_manager::Gamepad::update(Time dt) {\n\t\tif(_force_reset_timer>0_s) {\n\t\t\t_force_reset_timer-=dt;\n\t\t\tif(_force_reset_timer<0_s)\n\t\t\t\t_current_force = 0.f;\n\t\t}\n\n\t\tfor(auto i : util::range(pad_button_count)) {\n\t\t\tauto button = static_cast<Pad_button>(i);\n\t\t\tbool down = button_down(button);\n\n\t\t\tswitch(_button_state[i]) {\n\t\t\t\tcase 0: \/\/ up\n\t\t\t\t\t_button_state[i] = down ? 1 : 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1: \/\/ pressed\n\t\t\t\t\t_button_state[i] = down ? 2 : 3;\n\t\t\t\t\tif(is_trigger(button))\n\t\t\t\t\t\t_mapper.on_pad_button_pressed(_src_id, button,\n\t\t\t\t\t\t trigger(button));\n\t\t\t\t\telse\n\t\t\t\t\t\t_mapper.on_pad_button_pressed(_src_id, button, 1.f);\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2: \/\/ down\n\t\t\t\t\t_button_state[i] = down ? 2 : 3;\n\t\t\t\t\t{\n\t\t\t\t\t\tauto value = trigger(button);\n\t\t\t\t\t\tif(std::abs(_button_value[i]-value)>0.1) {\n\t\t\t\t\t\t\t_mapper.on_pad_button_changed(_src_id,button,value);\n\t\t\t\t\t\t\t_button_value[i] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3: \/\/ released\n\t\t\t\t\t_button_state[i] = down ? 1 : 0;\n\t\t\t\t\t_mapper.on_pad_button_released(_src_id, button);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tfor(auto i : util::range(pad_stick_count)) {\n\t\t\tauto stick = static_cast<Pad_stick>(i);\n\n\t\t\tauto state = axis(stick);\n\t\t\tif(state!=_stick_state[i]) {\n\t\t\t\t_mapper.on_pad_stick_change(_src_id, stick, state-_stick_state[i], state);\n\t\t\t\t_stick_state[i] = state;\n\t\t\t}\n\t\t}\n\t}\n\n\tauto Input_manager::Gamepad::axis(Pad_stick s) -> glm::vec2 {\n\t\tglm::vec2 v {\n\t\t\tSDL_GameControllerGetAxis(_sdl_controller, to_sdl_axis_x(s)) \/ _stick_max,\n\t\t\tSDL_GameControllerGetAxis(_sdl_controller, to_sdl_axis_y(s)) \/ _stick_max,\n\t\t};\n\n\t\tauto dz = _stick_dead_zone;\n\t\tauto length = glm::length(v);\n\n\t\tif(length<dz)\n\t\t\treturn glm::vec2{0,0};\n\n\t\treturn v\/length * ((length-dz)\/(1-dz));\n\t}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp\n *\n * Created on: Feb 25, 2017\n * Author: fpregernik\n *\/\n\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <csignal>\n#include <thread>\n#include <chrono>\nusing namespace std;\n\n#include \"inc\/cxxopts.hpp\"\n#include \"radar_simulator.hpp\"\n\nRadarSimulator rsim;\n\nstd::chrono::seconds sleepDuration(1);\n\nvoid signalHandler(int signum) {\n cout << \"INTR=\" << signum << endl;\n rsim.disable();\n cout << \"DISABLE_SIM\" << endl;\n\n exit(signum);\n}\n\nint main(int argc, char* argv[]) {\n\n \/\/ register signal SIGINT and signal handler\n signal(SIGINT, signalHandler);\n\n \/\/ ensure simulator is not running\n rsim.disable();\n\n \/\/ setup CLI option handling\n cxxopts::Options options(argv[0], \" - example command line options\");\n options.add_option(\"\", \"ct\", \"clear-target\", \"Clear target map\", cxxopts::value<bool>(), \"\");\n options.add_option(\"\", \"cc\", \"clear-clutter\", \"Clear clutter map\", cxxopts::value<bool>(), \"\");\n options.add_option(\"\", \"ltf\", \"load-target-file\", \"Load target file\", cxxopts::value<string>(), \"FILE\");\n options.add_option(\"\", \"lcf\", \"load-clutter-file\", \"Load target file\", cxxopts::value<string>(), \"FILE\");\n options.add_option(\"\", \"r\", \"run\", \"Start simulation\", cxxopts::value<bool>(), \"\");\n options.add_option(\"\", \"c\", \"cal\", \"Calibrate\", cxxopts::value<bool>(), \"\");\n options.add_option(\"\", \"h\", \"help\", \"Print help\", cxxopts::value<bool>(), \"\");\n\n try {\n options.parse(argc, argv);\n } catch (const cxxopts::OptionException& e) {\n cout << \"error parsing options: \" << e.what() << endl;\n exit(1);\n }\n\n if (options.count(\"help\")) {\n cout << options.help( { \"\" }) << endl;\n exit(0);\n }\n\n if (options.count(\"ct\")) {\n rsim.clearTargetMap();\n cout << \"CLR_MT_MAP\" << endl;\n }\n\n if (options.count(\"ct\")) {\n rsim.clearClutterMap();\n cout << \"CLR_CL_MAP\" << endl;\n }\n\n if (options.count(\"ltf\")) {\n auto& ff = options[\"ltf\"].as<string>();\n\n ifstream mtFile(ff, ios_base::in | ios_base::binary);\n if (!mtFile || !mtFile.is_open()) {\n cerr << \"ERR=Unable to open file \" << ff << endl;\n exit(2);\n }\n rsim.initTargetMap(mtFile);\n\n cout << \"INIT_MT_FILE\" << endl;\n }\n\n if (options.count(\"lcf\")) {\n auto& ff = options[\"lcf\"].as<string>();\n\n ifstream clFile(ff, ios_base::in | ios_base::binary);\n if (!clFile || !clFile.is_open()) {\n cerr << \"ERR=Unable to open file \" << ff << endl;\n exit(3);\n }\n rsim.initClutterMap(clFile);\n\n cout << \"INIT_CL_FILE\" << endl;\n }\n\n \/\/ get status\n auto status = rsim.getStatus();\n\n if (options.count(\"r\")) {\n\n rsim.enable();\n cout << \"ENABLE_SIM\" << endl;\n\n auto startTime = chrono::steady_clock::now();\n auto lastStatTime = startTime;\n chrono::milliseconds timeSinceEpoch = chrono::duration_cast < chrono::milliseconds > (startTime.time_since_epoch());\n\n cout << \"SIM_EN=\" << status.enabled << endl;\n cout << \"SIM_CAL=\" << status.calibrated << endl;\n cout << \"SIM_ARP_US=\" << dec << status.arpUs << endl;\n cout << \"SIM_ACP_CNT=\" << dec << status.acpCnt << endl;\n cout << \"SIM_TRIG_US=\" << dec << status.trigUs << endl;\n cout << \"SIM_MT_FIFO_CNT=\" << dec << status.targetFifoCnt << endl;\n cout << \"SIM_CL_FIFO_CNT=\" << dec << status.clutterFifoCnt << endl;\n cout << \"SIM_ACP_IDX=\" << dec << status.simAcpIdx << \"\/\" << timeSinceEpoch.count() << endl;\n cout << \"SIM_CURR_ACP=\" << dec << status.currAcpIdx << \"\/\" << timeSinceEpoch.count() << endl;\n\n \/\/ notify caller of progress\n while (!rsim.isScenarioFinished()) {\n\n status = rsim.getStatus();\n\n auto secSinceFullStat = chrono::duration_cast < chrono::seconds > (chrono::steady_clock::now() - lastStatTime);\n if (secSinceFullStat.count() > 5 \/* [s] *\/) {\n lastStatTime = chrono::steady_clock::now();\n cout << \"SIM_EN=\" << status.enabled << endl;\n cout << \"SIM_CAL=\" << status.calibrated << endl;\n cout << \"SIM_ARP_US=\" << dec << status.arpUs << endl;\n cout << \"SIM_ACP_CNT=\" << dec << status.acpCnt << endl;\n cout << \"SIM_TRIG_US=\" << dec << status.trigUs << endl;\n cout << \"SIM_MT_FIFO_CNT=\" << dec << status.targetFifoCnt << endl;\n cout << \"SIM_CL_FIFO_CNT=\" << dec << status.clutterFifoCnt << endl;\n }\n\n chrono::milliseconds timeSinceEpoch = chrono::duration_cast < chrono::milliseconds > (chrono::steady_clock::now().time_since_epoch());\n cout << \"SIM_ACP_IDX=\" << dec << status.simAcpIdx << \"\/\" << timeSinceEpoch.count() << endl;\n cout << \"SIM_CURR_ACP=\" << dec << status.currAcpIdx << \"\/\" << timeSinceEpoch.count() << endl;\n\n \/\/ check if we can load more moving target data\n if (options.count(\"ltf\")) {\n auto& ff = options[\"ltf\"].as<string>();\n ifstream mtFile(ff, ios_base::in | ios_base::binary);\n if (!mtFile || !mtFile.is_open()) {\n cerr << \"Unable to open file: \" << ff << endl;\n exit(2);\n }\n rsim.loadNextTargetMaps(mtFile);\n }\n\n this_thread::sleep_for(sleepDuration);\n }\n\n \/\/ disable simulator\n rsim.disable();\n cout << \"END_SIM\" << endl;\n\n } else if (options.count(\"c\")) {\n\n \/\/ perform calibration\n cout << \"CAL_BEGIN\" << endl;\n\n do {\n\n status = rsim.getStatus();\n\n cout << \"SIM_ARP_US=\" << dec << status.arpUs << endl;\n cout << \"SIM_ACP_CNT=\" << dec << status.acpCnt << endl;\n cout << \"SIM_TRIG_US=\" << dec << status.trigUs << endl;\n cout << \"SIM_CAL=\" << status.calibrated << endl;\n\n this_thread::sleep_for(sleepDuration);\n\n } while (status.calibrated != 1);\n\n cout << \"CAL_COMPLETE\" << endl;\n\n }\n\n return 0;\n}\n\n<commit_msg>Remove unused code<commit_after>\/*\n * main.cpp\n *\n * Created on: Feb 25, 2017\n * Author: fpregernik\n *\/\n\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <csignal>\n#include <thread>\n#include <chrono>\nusing namespace std;\n\n#include \"inc\/cxxopts.hpp\"\n#include \"radar_simulator.hpp\"\n\nRadarSimulator rsim;\n\nstd::chrono::seconds sleepDuration(1);\n\nvoid signalHandler(int signum) {\n cout << \"INTR=\" << signum << endl;\n rsim.disable();\n cout << \"DISABLE_SIM\" << endl;\n\n exit(signum);\n}\n\nint main(int argc, char* argv[]) {\n\n \/\/ register signal SIGINT and signal handler\n signal(SIGINT, signalHandler);\n\n \/\/ ensure simulator is not running\n rsim.disable();\n\n \/\/ setup CLI option handling\n cxxopts::Options options(argv[0], \" - example command line options\");\n options.add_option(\"\", \"ct\", \"clear-target\", \"Clear target map\", cxxopts::value<bool>(), \"\");\n options.add_option(\"\", \"cc\", \"clear-clutter\", \"Clear clutter map\", cxxopts::value<bool>(), \"\");\n options.add_option(\"\", \"ltf\", \"load-target-file\", \"Load target file\", cxxopts::value<string>(), \"FILE\");\n options.add_option(\"\", \"lcf\", \"load-clutter-file\", \"Load target file\", cxxopts::value<string>(), \"FILE\");\n options.add_option(\"\", \"r\", \"run\", \"Start simulation\", cxxopts::value<bool>(), \"\");\n options.add_option(\"\", \"c\", \"cal\", \"Calibrate\", cxxopts::value<bool>(), \"\");\n options.add_option(\"\", \"h\", \"help\", \"Print help\", cxxopts::value<bool>(), \"\");\n\n try {\n options.parse(argc, argv);\n } catch (const cxxopts::OptionException& e) {\n cout << \"error parsing options: \" << e.what() << endl;\n exit(1);\n }\n\n if (options.count(\"help\")) {\n cout << options.help( { \"\" }) << endl;\n exit(0);\n }\n\n if (options.count(\"ct\")) {\n rsim.clearTargetMap();\n cout << \"CLR_MT_MAP\" << endl;\n }\n\n if (options.count(\"ct\")) {\n rsim.clearClutterMap();\n cout << \"CLR_CL_MAP\" << endl;\n }\n\n if (options.count(\"ltf\")) {\n auto& ff = options[\"ltf\"].as<string>();\n\n ifstream mtFile(ff, ios_base::in | ios_base::binary);\n if (!mtFile || !mtFile.is_open()) {\n cerr << \"ERR=Unable to open file \" << ff << endl;\n exit(2);\n }\n rsim.initTargetMap(mtFile);\n\n cout << \"INIT_MT_FILE\" << endl;\n }\n\n if (options.count(\"lcf\")) {\n auto& ff = options[\"lcf\"].as<string>();\n\n ifstream clFile(ff, ios_base::in | ios_base::binary);\n if (!clFile || !clFile.is_open()) {\n cerr << \"ERR=Unable to open file \" << ff << endl;\n exit(3);\n }\n rsim.initClutterMap(clFile);\n\n cout << \"INIT_CL_FILE\" << endl;\n }\n\n \/\/ get status\n auto status = rsim.getStatus();\n\n if (options.count(\"r\")) {\n\n rsim.enable();\n cout << \"ENABLE_SIM\" << endl;\n\n auto startTime = chrono::steady_clock::now();\n auto lastStatTime = startTime;\n chrono::milliseconds timeSinceEpoch = chrono::duration_cast < chrono::milliseconds > (startTime.time_since_epoch());\n\n cout << \"SIM_EN=\" << status.enabled << endl;\n cout << \"SIM_CAL=\" << status.calibrated << endl;\n cout << \"SIM_ARP_US=\" << dec << status.arpUs << endl;\n cout << \"SIM_ACP_CNT=\" << dec << status.acpCnt << endl;\n cout << \"SIM_TRIG_US=\" << dec << status.trigUs << endl;\n cout << \"SIM_MT_FIFO_CNT=\" << dec << status.targetFifoCnt << endl;\n cout << \"SIM_CL_FIFO_CNT=\" << dec << status.clutterFifoCnt << endl;\n cout << \"SIM_ACP_IDX=\" << dec << status.simAcpIdx << \"\/\" << timeSinceEpoch.count() << endl;\n cout << \"SIM_CURR_ACP=\" << dec << status.currAcpIdx << \"\/\" << timeSinceEpoch.count() << endl;\n\n \/\/ notify caller of progress\n while (!rsim.isScenarioFinished()) {\n\n status = rsim.getStatus();\n\n auto secSinceFullStat = chrono::duration_cast < chrono::seconds > (chrono::steady_clock::now() - lastStatTime);\n if (secSinceFullStat.count() > 5 \/* [s] *\/) {\n lastStatTime = chrono::steady_clock::now();\n cout << \"SIM_EN=\" << status.enabled << endl;\n cout << \"SIM_CAL=\" << status.calibrated << endl;\n cout << \"SIM_ARP_US=\" << dec << status.arpUs << endl;\n cout << \"SIM_ACP_CNT=\" << dec << status.acpCnt << endl;\n cout << \"SIM_TRIG_US=\" << dec << status.trigUs << endl;\n cout << \"SIM_MT_FIFO_CNT=\" << dec << status.targetFifoCnt << endl;\n cout << \"SIM_CL_FIFO_CNT=\" << dec << status.clutterFifoCnt << endl;\n }\n\n chrono::milliseconds timeSinceEpoch = chrono::duration_cast < chrono::milliseconds > (chrono::steady_clock::now().time_since_epoch());\n cout << \"SIM_ACP_IDX=\" << dec << status.simAcpIdx << \"\/\" << timeSinceEpoch.count() << endl;\n\n \/\/ NOT IMPLEMENTED\n \/\/ cout << \"SIM_CURR_ACP=\" << dec << status.currAcpIdx << \"\/\" << timeSinceEpoch.count() << endl;\n\n \/\/ check if we can load more moving target data\n if (options.count(\"ltf\")) {\n auto& ff = options[\"ltf\"].as<string>();\n ifstream mtFile(ff, ios_base::in | ios_base::binary);\n if (!mtFile || !mtFile.is_open()) {\n cerr << \"Unable to open file: \" << ff << endl;\n exit(2);\n }\n rsim.loadNextTargetMaps(mtFile);\n }\n\n this_thread::sleep_for(sleepDuration);\n }\n\n \/\/ disable simulator\n rsim.disable();\n cout << \"END_SIM\" << endl;\n\n } else if (options.count(\"c\")) {\n\n \/\/ perform calibration\n cout << \"CAL_BEGIN\" << endl;\n\n do {\n\n status = rsim.getStatus();\n\n cout << \"SIM_ARP_US=\" << dec << status.arpUs << endl;\n cout << \"SIM_ACP_CNT=\" << dec << status.acpCnt << endl;\n cout << \"SIM_TRIG_US=\" << dec << status.trigUs << endl;\n cout << \"SIM_CAL=\" << status.calibrated << endl;\n\n this_thread::sleep_for(sleepDuration);\n\n } while (status.calibrated != 1);\n\n cout << \"CAL_COMPLETE\" << endl;\n\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\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: Os2Transferable.hxx,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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _DTRANS_OS2_TRANSFERABLE_HXX_\n#define _DTRANS_OS2_TRANSFERABLE_HXX_\n\n#include <com\/sun\/star\/datatransfer\/XTransferable.hpp>\n\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HDL_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n#include <cppuhelper\/implbase1.hxx>\n#include <osl\/thread.h>\n\n#include <errno.h>\n\n#include <uclip.h>\n\n#define CHAR_POINTER(THE_OUSTRING) ::rtl::OUStringToOString (THE_OUSTRING, RTL_TEXTENCODING_UTF8).pData->buffer\n\n#if OSL_DEBUG_LEVEL>1\nextern \"C\" int debug_printf(const char *f, ...);\n#else\n#define debug_printf( ...) { 1; }\n#endif\n\n#define CPPUTYPE_SEQSALINT8 getCppuType( (const Sequence< sal_Int8 >*) 0 )\n#define CPPUTYPE_DEFAULT CPPUTYPE_SEQSALINT8\n\n#ifdef OOO_VENDOR\nusing namespace com::sun::star::uno;\nHBITMAP OOoBmpToOS2Handle( Any &aAnyB);\nint OS2HandleToOOoBmp( HBITMAP hbm, Sequence< sal_Int8 >* winDIBStream);\n#else\n#define OOoBmpToOS2Handle(a) 0\n#define OS2HandleToOOoBmp(a,b) 0\n#endif\n\nnamespace os2 {\n\n class Os2Transferable : public ::cppu::WeakImplHelper1 <\n ::com::sun::star::datatransfer::XTransferable >\n {\n HAB hAB;\n ::rtl::OUString clipText;\n ::com::sun::star::datatransfer::DataFlavor aFlavor;\n ::osl::Mutex m_aMutex;\n ::com::sun::star::uno::Reference< XInterface > m_xCreator;\n\n public:\n Os2Transferable( const ::com::sun::star::uno::Reference< XInterface >& xCreator);\n virtual ~Os2Transferable();\n\n \/*\n * XTransferable\n *\/\n\n virtual ::com::sun::star::uno::Any SAL_CALL getTransferData( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )\n throw(::com::sun::star::datatransfer::UnsupportedFlavorException,\n ::com::sun::star::io::IOException,\n ::com::sun::star::uno::RuntimeException\n );\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::datatransfer::DataFlavor > SAL_CALL getTransferDataFlavors( )\n throw(::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL isDataFlavorSupported( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )\n throw(::com::sun::star::uno::RuntimeException);\n };\n\n} \/\/ namespace\n\n#endif\n\n<commit_msg>INTEGRATION: CWS os2port03 (1.3.8); FILE MERGED 2008\/07\/17 05:27:53 obr 1.3.8.2: RESYNC: (1.3-1.4); FILE MERGED 2008\/01\/14 16:27:33 ydario 1.3.8.1: remove old os2 directory Issue number:i85203 Submitted by:ydario<commit_after>\/*************************************************************************\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: Os2Transferable.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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _DTRANS_OS2_TRANSFERABLE_HXX_\n#define _DTRANS_OS2_TRANSFERABLE_HXX_\n\n#include <com\/sun\/star\/datatransfer\/XTransferable.hpp>\n\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HDL_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n#include <cppuhelper\/implbase1.hxx>\n#include <osl\/thread.h>\n\n#include <errno.h>\n\n#include <uclip.h>\n\n#define CHAR_POINTER(THE_OUSTRING) ::rtl::OUStringToOString (THE_OUSTRING, RTL_TEXTENCODING_UTF8).pData->buffer\n\n#if OSL_DEBUG_LEVEL>1\n\/\/extern \"C\" int debug_printf(const char *f, ...);\n#define debug_printf( ...) { 1; }\n#else\n#define debug_printf( ...) { 1; }\n#endif\n\n#define CPPUTYPE_SEQSALINT8 getCppuType( (const Sequence< sal_Int8 >*) 0 )\n#define CPPUTYPE_DEFAULT CPPUTYPE_SEQSALINT8\n\n#ifdef OOO_VENDOR\nusing namespace com::sun::star::uno;\nHBITMAP OOoBmpToOS2Handle( Any &aAnyB);\nint OS2HandleToOOoBmp( HBITMAP hbm, Sequence< sal_Int8 >* winDIBStream);\n#else\n#define OOoBmpToOS2Handle(a) 0\n#define OS2HandleToOOoBmp(a,b) 0\n#endif\n\nnamespace os2 {\n\n class Os2Transferable : public ::cppu::WeakImplHelper1 <\n ::com::sun::star::datatransfer::XTransferable >\n {\n HAB hAB;\n ::rtl::OUString clipText;\n ::com::sun::star::datatransfer::DataFlavor aFlavor;\n ::osl::Mutex m_aMutex;\n ::com::sun::star::uno::Reference< XInterface > m_xCreator;\n\n public:\n Os2Transferable( const ::com::sun::star::uno::Reference< XInterface >& xCreator);\n virtual ~Os2Transferable();\n\n \/*\n * XTransferable\n *\/\n\n virtual ::com::sun::star::uno::Any SAL_CALL getTransferData( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )\n throw(::com::sun::star::datatransfer::UnsupportedFlavorException,\n ::com::sun::star::io::IOException,\n ::com::sun::star::uno::RuntimeException\n );\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::datatransfer::DataFlavor > SAL_CALL getTransferDataFlavors( )\n throw(::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL isDataFlavorSupported( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )\n throw(::com::sun::star::uno::RuntimeException);\n };\n\n} \/\/ namespace\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DataFmtTransl.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 06:04:48 $\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\n#ifndef _DATAFMTTRANSL_HXX_\n#define _DATAFMTTRANSL_HXX_\n\n\/\/-----------------------------------------------\n\/\/ includes\n\/\/-----------------------------------------------\n\n#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_\n#include <cppuhelper\/servicefactory.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_DATATRANSFER_XDATAFORMATTRANSLATOR_HPP_\n#include <com\/sun\/star\/datatransfer\/XDataFormatTranslator.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_\n#include <com\/sun\/star\/datatransfer\/XTransferable.hpp>\n#endif\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#if defined _MSC_VER\n#pragma warning(push,1)\n#endif\n#include <windows.h>\n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n\n\/\/-----------------------------------------------\n\/\/ declaration\n\/\/-----------------------------------------------\n\nclass CFormatEtc;\n\nclass CDataFormatTranslator\n{\npublic:\n CDataFormatTranslator( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aServiceManager );\n\n CFormatEtc getFormatEtcFromDataFlavor( const com::sun::star::datatransfer::DataFlavor& aDataFlavor ) const;\n com::sun::star::datatransfer::DataFlavor getDataFlavorFromFormatEtc(\n const FORMATETC& aFormatEtc, LCID lcid = GetThreadLocale( ) ) const;\n\n CFormatEtc SAL_CALL getFormatEtcForClipformat( CLIPFORMAT cf ) const;\n CFormatEtc SAL_CALL getFormatEtcForClipformatName( const rtl::OUString& aClipFmtName ) const;\n rtl::OUString SAL_CALL getClipboardFormatName( CLIPFORMAT aClipformat ) const;\n\n sal_Bool SAL_CALL isHTMLFormat( CLIPFORMAT cf ) const;\n sal_Bool SAL_CALL isTextHtmlFormat( CLIPFORMAT cf ) const;\n sal_Bool SAL_CALL isOemOrAnsiTextFormat( CLIPFORMAT cf ) const;\n sal_Bool SAL_CALL isUnicodeTextFormat( CLIPFORMAT cf ) const;\n sal_Bool SAL_CALL isTextFormat( CLIPFORMAT cf ) const;\n\nprivate:\n rtl::OUString SAL_CALL getTextCharsetFromLCID( LCID lcid, CLIPFORMAT aClipformat ) const;\n\nprivate:\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_SrvMgr;\n com::sun::star::uno::Reference< com::sun::star::datatransfer::XDataFormatTranslator > m_XDataFormatTranslator;\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.9.76); FILE MERGED 2008\/04\/01 15:13:35 thb 1.9.76.3: #i85898# Stripping all external header guards 2008\/04\/01 12:28:33 thb 1.9.76.2: #i85898# Stripping all external header guards 2008\/03\/31 13:09:02 rt 1.9.76.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: DataFmtTransl.hxx,v $\n * $Revision: 1.10 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#ifndef _DATAFMTTRANSL_HXX_\n#define _DATAFMTTRANSL_HXX_\n\n\/\/-----------------------------------------------\n\/\/ includes\n\/\/-----------------------------------------------\n\n#include <cppuhelper\/servicefactory.hxx>\n#include <com\/sun\/star\/datatransfer\/XDataFormatTranslator.hpp>\n#include <com\/sun\/star\/datatransfer\/XTransferable.hpp>\n#include <sal\/types.h>\n#include <rtl\/ustring.hxx>\n\n#if defined _MSC_VER\n#pragma warning(push,1)\n#endif\n#include <windows.h>\n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n\n\/\/-----------------------------------------------\n\/\/ declaration\n\/\/-----------------------------------------------\n\nclass CFormatEtc;\n\nclass CDataFormatTranslator\n{\npublic:\n CDataFormatTranslator( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aServiceManager );\n\n CFormatEtc getFormatEtcFromDataFlavor( const com::sun::star::datatransfer::DataFlavor& aDataFlavor ) const;\n com::sun::star::datatransfer::DataFlavor getDataFlavorFromFormatEtc(\n const FORMATETC& aFormatEtc, LCID lcid = GetThreadLocale( ) ) const;\n\n CFormatEtc SAL_CALL getFormatEtcForClipformat( CLIPFORMAT cf ) const;\n CFormatEtc SAL_CALL getFormatEtcForClipformatName( const rtl::OUString& aClipFmtName ) const;\n rtl::OUString SAL_CALL getClipboardFormatName( CLIPFORMAT aClipformat ) const;\n\n sal_Bool SAL_CALL isHTMLFormat( CLIPFORMAT cf ) const;\n sal_Bool SAL_CALL isTextHtmlFormat( CLIPFORMAT cf ) const;\n sal_Bool SAL_CALL isOemOrAnsiTextFormat( CLIPFORMAT cf ) const;\n sal_Bool SAL_CALL isUnicodeTextFormat( CLIPFORMAT cf ) const;\n sal_Bool SAL_CALL isTextFormat( CLIPFORMAT cf ) const;\n\nprivate:\n rtl::OUString SAL_CALL getTextCharsetFromLCID( LCID lcid, CLIPFORMAT aClipformat ) const;\n\nprivate:\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_SrvMgr;\n com::sun::star::uno::Reference< com::sun::star::datatransfer::XDataFormatTranslator > m_XDataFormatTranslator;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_SPACE_CONTINUOUSLAGRANGE_PDELAB_HH\n#define DUNE_GDT_SPACE_CONTINUOUSLAGRANGE_PDELAB_HH\n\n#include <memory>\n\n#include <dune\/common\/typetraits.hh>\n#include <dune\/common\/fvector.hh>\n\n#include <dune\/geometry\/genericgeometry\/topologytypes.hh>\n\n#include <dune\/grid\/common\/capabilities.hh>\n\n#if HAVE_DUNE_PDELAB\n#include <dune\/pdelab\/finiteelementmap\/pkfem.hh>\n#include <dune\/pdelab\/finiteelementmap\/qkfem.hh>\n#include <dune\/pdelab\/gridfunctionspace\/gridfunctionspace.hh>\n#endif \/\/ HAVE_DUNE_PDELAB\n\n#include \"..\/..\/mapper\/pdelab.hh\"\n#include \"..\/..\/basefunctionset\/pdelab.hh\"\n\n#include \"..\/interface.hh\"\n#include \"..\/continuouslagrange.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace ContinuousLagrangeSpace {\n\n#if HAVE_DUNE_PDELAB\n\n\n\/\/ forward, to be used in the traits and to allow for specialization\ntemplate <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>\nclass PdelabWrapper\n{\n static_assert((Dune::AlwaysFalse<GridViewImp>::value), \"Untested for this combination of dimensions!\");\n};\n\n\n\/**\n * \\brief Traits class for ContinuousLagrangeSpace::PdelabWrapper.\n *\/\ntemplate <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>\nclass PdelabWrapperTraits\n{\npublic:\n typedef PdelabWrapper<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;\n typedef GridViewImp GridViewType;\n static const int polOrder = polynomialOrder;\n static_assert(polOrder >= 1, \"Wrong polOrder given!\");\n\nprivate:\n typedef typename GridViewType::ctype DomainFieldType;\n\npublic:\n static const unsigned int dimDomain = GridViewType::dimension;\n typedef RangeFieldImp RangeFieldType;\n static const unsigned int dimRange = rangeDim;\n static const unsigned int dimRangeCols = rangeDimCols;\n\nprivate:\n template <class G, bool single_geom, bool is_simplex, bool is_cube>\n struct FeMap\n {\n static_assert(Dune::AlwaysFalse<G>::value,\n \"This space is only implemented for either fully simplicial or fully cubic grids!\");\n };\n template <class G>\n struct FeMap<G, true, true, false>\n {\n typedef PDELab::PkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type;\n };\n template <class G>\n struct FeMap<G, true, false, true>\n {\n typedef PDELab::QkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type;\n };\n typedef typename GridViewType::Grid GridType;\n static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v;\n static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId\n == GenericGeometry::SimplexTopology<dimDomain>::type::id);\n static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId\n == GenericGeometry::CubeTopology<dimDomain>::type::id);\n typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType;\n\npublic:\n typedef PDELab::GridFunctionSpace<GridViewType, FEMapType> BackendType;\n typedef Mapper::PdelabPkQk<BackendType> MapperType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n typedef BaseFunctionSet::PdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange,\n dimRangeCols> BaseFunctionSetType;\n\nprivate:\n friend class PdelabWrapper<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>;\n}; \/\/ class SpaceWrappedFemContinuousLagrangeTraits\n\n\ntemplate <class GridViewImp, int polynomialOrder, class RangeFieldImp>\nclass PdelabWrapper<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>\n : public ContinuousLagrangeSpaceBase<PdelabWrapperTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>,\n GridViewImp::dimension, RangeFieldImp, 1, 1>\n{\n typedef ContinuousLagrangeSpaceBase<PdelabWrapperTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>,\n GridViewImp::dimension, RangeFieldImp, 1, 1> BaseType;\n typedef PdelabWrapper<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;\n\npublic:\n typedef PdelabWrapperTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;\n\n typedef typename Traits::GridViewType GridViewType;\n static const int polOrder = Traits::polOrder;\n typedef typename GridViewType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridViewType::dimension;\n typedef FieldVector<DomainFieldType, dimDomain> DomainType;\n typedef typename Traits::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = Traits::dimRange;\n static const unsigned int dimRangeCols = Traits::dimRangeCols;\n\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::MapperType MapperType;\n typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;\n\nprivate:\n typedef typename Traits::FEMapType FEMapType;\n\npublic:\n typedef typename BaseType::IntersectionType IntersectionType;\n typedef typename BaseType::EntityType EntityType;\n typedef typename BaseType::PatternType PatternType;\n typedef typename BaseType::BoundaryInfoType BoundaryInfoType;\n\n PdelabWrapper(const std::shared_ptr<const GridViewType>& gV)\n : gridView_(gV)\n , fe_map_(std::make_shared<FEMapType>(*(gridView_)))\n , backend_(std::make_shared<BackendType>(const_cast<GridViewType&>(*gridView_), *fe_map_))\n , mapper_(std::make_shared<MapperType>(*backend_))\n {\n }\n\n PdelabWrapper(const ThisType& other)\n : gridView_(other.gridView_)\n , fe_map_(other.fe_map_)\n , backend_(other.backend_)\n , mapper_(other.mapper_)\n {\n }\n\n ThisType& operator=(const ThisType& other)\n {\n if (this != &other) {\n gridView_ = other.gridView_;\n fe_map_ = other.fe_map_;\n backend_ = other.backend_;\n mapper_ = other.mapper_;\n }\n return *this;\n }\n\n ~PdelabWrapper()\n {\n }\n\n const std::shared_ptr<const GridViewType>& grid_view() const\n {\n return gridView_;\n }\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n bool continuous() const\n {\n return true;\n }\n\n const MapperType& mapper() const\n {\n return *mapper_;\n }\n\n BaseFunctionSetType base_function_set(const EntityType& entity) const\n {\n return BaseFunctionSetType(*backend_, entity, polOrder);\n }\n\n using BaseType::compute_pattern;\n\n template <class LocalGridViewType, class T>\n PatternType compute_pattern(const LocalGridViewType& localgridView, const SpaceInterface<T>& otherSpace) const\n {\n return BaseType::compute_volume_pattern(localgridView, otherSpace);\n }\n\n using BaseType::local_constraints;\n\nprivate:\n std::shared_ptr<const GridViewType> gridView_;\n std::shared_ptr<const FEMapType> fe_map_;\n std::shared_ptr<const BackendType> backend_;\n std::shared_ptr<const MapperType> mapper_;\n}; \/\/ class PdelabWrapper< ..., 1 >\n\n\n#else \/\/ HAVE_DUNE_PDELAB\n\n\ntemplate <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>\nclass PdelabWrapper\n{\n static_assert((Dune::AlwaysFalse<GridViewImp>::value), \"You are missing dune-pdelab!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_PDELAB\n\n} \/\/ namespace ContinuousLagrangeSpace\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_SPACE_CONTINUOUSLAGRANGE_PDELAB_HH\n<commit_msg>[space.continuouslagrange.pdelab] minor cleanup<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_SPACE_CONTINUOUSLAGRANGE_PDELAB_HH\n#define DUNE_GDT_SPACE_CONTINUOUSLAGRANGE_PDELAB_HH\n\n#include <memory>\n\n#include <dune\/common\/typetraits.hh>\n#include <dune\/common\/fvector.hh>\n\n#include <dune\/geometry\/genericgeometry\/topologytypes.hh>\n\n#include <dune\/grid\/common\/capabilities.hh>\n\n#if HAVE_DUNE_PDELAB\n#include <dune\/pdelab\/finiteelementmap\/pkfem.hh>\n#include <dune\/pdelab\/finiteelementmap\/qkfem.hh>\n#include <dune\/pdelab\/gridfunctionspace\/gridfunctionspace.hh>\n#endif \/\/ HAVE_DUNE_PDELAB\n\n#include \"..\/..\/mapper\/pdelab.hh\"\n#include \"..\/..\/basefunctionset\/pdelab.hh\"\n\n#include \"..\/continuouslagrange.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace ContinuousLagrangeSpace {\n\n#if HAVE_DUNE_PDELAB\n\n\n\/\/ forward, to be used in the traits and to allow for specialization\ntemplate <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>\nclass PdelabWrapper\n{\n static_assert((Dune::AlwaysFalse<GridViewImp>::value), \"Untested for this combination of dimensions!\");\n};\n\n\n\/**\n * \\brief Traits class for ContinuousLagrangeSpace::PdelabWrapper.\n *\/\ntemplate <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>\nclass PdelabWrapperTraits\n{\npublic:\n typedef PdelabWrapper<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;\n typedef GridViewImp GridViewType;\n static const int polOrder = polynomialOrder;\n static_assert(polOrder >= 1, \"Wrong polOrder given!\");\n\nprivate:\n typedef typename GridViewType::ctype DomainFieldType;\n\npublic:\n static const unsigned int dimDomain = GridViewType::dimension;\n typedef RangeFieldImp RangeFieldType;\n static const unsigned int dimRange = rangeDim;\n static const unsigned int dimRangeCols = rangeDimCols;\n\nprivate:\n template <class G, bool single_geom, bool is_simplex, bool is_cube>\n struct FeMap\n {\n static_assert(Dune::AlwaysFalse<G>::value,\n \"This space is only implemented for either fully simplicial or fully cubic grids!\");\n };\n template <class G>\n struct FeMap<G, true, true, false>\n {\n typedef PDELab::PkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type;\n };\n template <class G>\n struct FeMap<G, true, false, true>\n {\n typedef PDELab::QkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type;\n };\n typedef typename GridViewType::Grid GridType;\n static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v;\n static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId\n == GenericGeometry::SimplexTopology<dimDomain>::type::id);\n static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId\n == GenericGeometry::CubeTopology<dimDomain>::type::id);\n typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType;\n\npublic:\n typedef PDELab::GridFunctionSpace<GridViewType, FEMapType> BackendType;\n typedef Mapper::PdelabPkQk<BackendType> MapperType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n typedef BaseFunctionSet::PdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange,\n dimRangeCols> BaseFunctionSetType;\n\nprivate:\n friend class PdelabWrapper<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>;\n}; \/\/ class SpaceWrappedFemContinuousLagrangeTraits\n\n\ntemplate <class GridViewImp, int polynomialOrder, class RangeFieldImp>\nclass PdelabWrapper<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>\n : public ContinuousLagrangeSpaceBase<PdelabWrapperTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>,\n GridViewImp::dimension, RangeFieldImp, 1, 1>\n{\n typedef ContinuousLagrangeSpaceBase<PdelabWrapperTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>,\n GridViewImp::dimension, RangeFieldImp, 1, 1> BaseType;\n typedef PdelabWrapper<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;\n\npublic:\n typedef PdelabWrapperTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;\n\n typedef typename Traits::GridViewType GridViewType;\n static const int polOrder = Traits::polOrder;\n typedef typename GridViewType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridViewType::dimension;\n typedef FieldVector<DomainFieldType, dimDomain> DomainType;\n typedef typename Traits::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = Traits::dimRange;\n static const unsigned int dimRangeCols = Traits::dimRangeCols;\n\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::MapperType MapperType;\n typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;\n\nprivate:\n typedef typename Traits::FEMapType FEMapType;\n\npublic:\n typedef typename BaseType::IntersectionType IntersectionType;\n typedef typename BaseType::EntityType EntityType;\n typedef typename BaseType::PatternType PatternType;\n typedef typename BaseType::BoundaryInfoType BoundaryInfoType;\n\n PdelabWrapper(const std::shared_ptr<const GridViewType>& gV)\n : gridView_(gV)\n , fe_map_(std::make_shared<FEMapType>(*(gridView_)))\n , backend_(std::make_shared<BackendType>(const_cast<GridViewType&>(*gridView_), *fe_map_))\n , mapper_(std::make_shared<MapperType>(*backend_))\n {\n }\n\n PdelabWrapper(const ThisType& other)\n : gridView_(other.gridView_)\n , fe_map_(other.fe_map_)\n , backend_(other.backend_)\n , mapper_(other.mapper_)\n {\n }\n\n ThisType& operator=(const ThisType& other)\n {\n if (this != &other) {\n gridView_ = other.gridView_;\n fe_map_ = other.fe_map_;\n backend_ = other.backend_;\n mapper_ = other.mapper_;\n }\n return *this;\n }\n\n ~PdelabWrapper()\n {\n }\n\n const std::shared_ptr<const GridViewType>& grid_view() const\n {\n return gridView_;\n }\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n bool continuous() const\n {\n return true;\n }\n\n const MapperType& mapper() const\n {\n return *mapper_;\n }\n\n BaseFunctionSetType base_function_set(const EntityType& entity) const\n {\n return BaseFunctionSetType(*backend_, entity, polOrder);\n }\n\nprivate:\n std::shared_ptr<const GridViewType> gridView_;\n std::shared_ptr<const FEMapType> fe_map_;\n std::shared_ptr<const BackendType> backend_;\n std::shared_ptr<const MapperType> mapper_;\n}; \/\/ class PdelabWrapper< ..., 1 >\n\n\n#else \/\/ HAVE_DUNE_PDELAB\n\n\ntemplate <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>\nclass PdelabWrapper\n{\n static_assert((Dune::AlwaysFalse<GridViewImp>::value), \"You are missing dune-pdelab!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_PDELAB\n\n} \/\/ namespace ContinuousLagrangeSpace\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_SPACE_CONTINUOUSLAGRANGE_PDELAB_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\n**\n** Author(s):\n** - Cedric GESTES <gestes@aldebaran-robotics.com>\n**\n** Copyright (C) 2013 Aldebaran Robotics\n*\/\n\n#include \"pyservicedirectory.hpp\"\n#include <qimessaging\/servicedirectory.hpp>\n#include <boost\/python.hpp>\n#include \"pyfuture.hpp\"\n\nqiLogCategory(\"qimpy\");\n\nnamespace qi {\n namespace py {\n\n class PyServiceDirectory : public qi::ServiceDirectory\n {\n public:\n \/\/return a future, or None (and throw in case of error)\n boost::python::object listen(const std::string &url, bool _async=false) {\n if (_async)\n return boost::python::object(toPyFuture(ServiceDirectory::listen(url)));\n else {\n qi::Future<void> fut = ServiceDirectory::listen(url);\n fut.value(); \/\/throw on error\n return boost::python::object();\n }\n }\n\n \/\/override because python do not know qi::Url\n std::vector<std::string> endpoints() const {\n std::vector<std::string> ret;\n std::vector<qi::Url> eps = ServiceDirectory::endpoints();\n for (unsigned int i = 0; i < eps.size(); ++i) {\n ret.push_back(eps.at(i).str());\n }\n return ret;\n }\n\n };\n\n void export_pyservicedirectory() {\n boost::python::class_<PyServiceDirectory>(\"ServiceDirectory\")\n .def(\"listen\", &PyServiceDirectory::listen, (boost::python::arg(\"url\"), boost::python::arg(\"_async\") = false))\n .def(\"setIdentity\", &PyServiceDirectory::setIdentity)\n .def(\"close\", &PyServiceDirectory::close)\n .def(\"endpoints\", &PyServiceDirectory::endpoints);\n }\n\n }\n}\n<commit_msg>python: servicedirectory: fix endpoints()<commit_after>\/*\n**\n** Author(s):\n** - Cedric GESTES <gestes@aldebaran-robotics.com>\n**\n** Copyright (C) 2013 Aldebaran Robotics\n*\/\n\n#include \"pyservicedirectory.hpp\"\n#include <qimessaging\/servicedirectory.hpp>\n#include <boost\/python.hpp>\n#include \"pyfuture.hpp\"\n\nqiLogCategory(\"qimpy\");\n\nnamespace qi {\n namespace py {\n\n class PyServiceDirectory : public qi::ServiceDirectory\n {\n public:\n \/\/return a future, or None (and throw in case of error)\n boost::python::object listen(const std::string &url, bool _async=false) {\n if (_async)\n return boost::python::object(toPyFuture(ServiceDirectory::listen(url)));\n else {\n qi::Future<void> fut = ServiceDirectory::listen(url);\n \/\/TODO: unlock GIL here?\n fut.value(); \/\/throw on error\n return boost::python::object();\n }\n }\n\n \/\/override because python do not know qi::Url\n boost::python::list endpoints() const {\n boost::python::list ret;\n std::vector<qi::Url> eps = ServiceDirectory::endpoints();\n for (unsigned int i = 0; i < eps.size(); ++i) {\n ret.append(eps.at(i).str());\n }\n return ret;\n }\n\n };\n\n void export_pyservicedirectory() {\n boost::python::class_<PyServiceDirectory>(\"ServiceDirectory\")\n .def(\"listen\", &PyServiceDirectory::listen, (boost::python::arg(\"url\"), boost::python::arg(\"_async\") = false))\n .def(\"setIdentity\", &PyServiceDirectory::setIdentity)\n .def(\"close\", &PyServiceDirectory::close)\n .def(\"endpoints\", &PyServiceDirectory::endpoints);\n }\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ServerPAMAuth.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n#include \"ServerPAMAuth.hpp\"\n\n#include <sys\/wait.h>\n\n#include <core\/Error.hpp>\n#include <core\/system\/System.hpp>\n#include <core\/system\/ProcessArgs.hpp>\n\n#include <core\/http\/Request.hpp>\n#include <core\/http\/Response.hpp>\n#include <core\/http\/URL.hpp>\n#include <core\/http\/AsyncUriHandler.hpp>\n#include <core\/text\/TemplateFilter.hpp>\n\n#include <server\/util\/system\/Crypto.hpp>\n#include <server\/util\/system\/System.hpp>\n\n#include <server\/auth\/ServerValidateUser.hpp>\n#include <server\/auth\/ServerSecureUriHandler.hpp>\n#include <server\/auth\/ServerAuthHandler.hpp>\n#include <server\/auth\/ServerSecureCookie.hpp>\n\n#include <server\/ServerOptions.hpp>\n#include <server\/ServerUriHandlers.hpp>\n\n\nnamespace server {\nnamespace pam_auth {\n\nnamespace {\n\n\n\/\/ TODO: don't re-assume priv on ubuntu\n\n\/\/ TODO: comments on intentionally failing forward in child\n\n\/\/ TODO: make sure inputs into pam helper are bounded\n\/\/ TODO: block tty case in pam helper\n\n\/\/ TODO: make sure it works on redhat\n\n\/\/ TODO: then can change hat permanently\n\n\n\/\/ Handles error logging and EINTR retrying. Only for use with\n\/\/ functions that return -1 on error and set errno.\nint posixcall(boost::function<ssize_t()> func, const ErrorLocation& location)\n{\n while (true)\n {\n int result;\n if ((result = func()) == -1)\n {\n if (errno == EINTR)\n continue;\n LOG_ERROR(systemError(errno, location));\n return result;\n }\n return result;\n }\n}\n\n\nbool pamLogin(const std::string& username, const std::string& password)\n{\n \/\/ get path to pam helper\n FilePath pamHelperPath(server::options().authPamHelperPath());\n if (!pamHelperPath.exists())\n {\n LOG_ERROR_MESSAGE(\"PAM helper binary does not exist at \" +\n pamHelperPath.absolutePath());\n return false;\n }\n\n \/\/ create pipes\n const int READ = 0;\n const int WRITE = 1;\n int fdInput[2];\n if (posixcall(boost::bind(::pipe, fdInput), ERROR_LOCATION) == -1)\n return false;\n int fdOutput[2];\n if (posixcall(boost::bind(::pipe, fdOutput), ERROR_LOCATION) == -1)\n return false;\n\n \/\/ fork\n pid_t pid = posixcall(::fork, ERROR_LOCATION);\n if (pid == -1)\n return false;\n\n \/\/ child\n else if (pid == 0)\n {\n \/\/ RedHat 5 returns PAM_SYSTEM_ERR from pam_authenticate if we're\n \/\/ running with geteuid != getuid (as is the case when we temporarily\n \/\/ drop privileges). So restore privilliges in the child\n if (util::system::realUserIsRoot())\n {\n Error error = util::system::restorePriv();\n if (error)\n LOG_ERROR(error);\n }\n\n \/\/ close unused pipes\n posixcall(boost::bind(::close, fdInput[WRITE]), ERROR_LOCATION);\n posixcall(boost::bind(::close, fdOutput[READ]), ERROR_LOCATION);\n\n \/\/ clear the child signal mask\n Error error = core::system::clearSignalMask();\n if (error)\n LOG_ERROR(error);\n\n \/\/ wire standard streams\n posixcall(boost::bind(::dup2, fdInput[READ], STDIN_FILENO),\n ERROR_LOCATION);\n posixcall(boost::bind(::dup2, fdOutput[WRITE], STDOUT_FILENO),\n ERROR_LOCATION);\n\n \/\/ close all open file descriptors other than std streams\n error = core::system::closeNonStdFileDescriptors();\n if (error)\n LOG_ERROR(error);\n\n \/\/ build username args (on heap so they stay around after exec)\n \/\/ and execute pam helper\n using core::system::ProcessArgs;\n std::vector<std::string> args;\n args.push_back(pamHelperPath.absolutePath());\n args.push_back(username);\n ProcessArgs* pProcessArgs = new ProcessArgs(args);\n ::execv(pamHelperPath.absolutePath().c_str(), pProcessArgs->args()) ;\n\n \/\/ in the normal case control should never return from execv (it starts\n \/\/ anew at main of the process pointed to by path). therefore, if we get\n \/\/ here then there was an error\n LOG_ERROR(systemError(errno, ERROR_LOCATION)) ;\n ::exit(EXIT_FAILURE) ;\n }\n\n \/\/ parent\n else\n {\n \/\/ close unused pipes\n posixcall(boost::bind(::close, fdInput[READ]), ERROR_LOCATION);\n posixcall(boost::bind(::close, fdOutput[WRITE]), ERROR_LOCATION);\n\n \/\/ write the password to standard input then close the pipe\n std::string input = password ;\n std::size_t written = posixcall(boost::bind(::write,\n fdInput[WRITE],\n input.c_str(),\n input.length()),\n ERROR_LOCATION);\n posixcall(boost::bind(::close, fdInput[WRITE]), ERROR_LOCATION);\n\n \/\/ check for correct bytes written\n if (written != static_cast<std::size_t>(input.length()))\n {\n \/\/ first close stdout pipe\n posixcall(boost::bind(::close, fdOutput[READ]), ERROR_LOCATION);\n\n \/\/ log error and return false\n LOG_ERROR_MESSAGE(\"Error writing to pam helper stdin\");\n return false;\n }\n\n \/\/ read the response from standard output\n char buf;\n size_t bytesRead = posixcall(boost::bind(::read, fdOutput[READ], &buf, 1),\n ERROR_LOCATION);\n posixcall(boost::bind(::close, fdOutput[READ]), ERROR_LOCATION);\n\n \/\/ return true if bytes were read\n return bytesRead > 0;\n }\n\n return false;\n}\n\n\n\nconst char * const kUserId = \"user-id\";\n\n\/\/ It's important that URIs be in the root directory, so the cookie\n\/\/ gets set\/unset at the correct scope!\nconst char * const kDoSignIn = \"\/auth-do-sign-in\";\nconst char * const kPublicKey = \"\/auth-public-key\";\n\nconst char * const kAppUri = \"appUri\";\n\nconst char * const kErrorParam = \"error\";\nconst char * const kErrorDisplay = \"errorDisplay\";\nconst char * const kErrorMessage = \"errorMessage\";\n\n\nstd::string applicationURL(const http::Request& request,\n const std::string& path = std::string())\n{\n return http::URL::uncomplete(\n request.uri(),\n path);\n}\n\nstd::string applicationSignInURL(const http::Request& request,\n const std::string& appUri,\n const std::string& errorMessage=std::string())\n{\n \/\/ build fields\n http::Fields fields ;\n if (appUri != \"\/\")\n fields.push_back(std::make_pair(kAppUri, appUri));\n if (!errorMessage.empty())\n fields.push_back(std::make_pair(kErrorParam, errorMessage));\n\n \/\/ build query string\n std::string queryString ;\n if (!fields.empty())\n http::util::buildQueryString(fields, &queryString);\n\n \/\/ generate url\n std::string signInURL = applicationURL(request, auth::handler::kSignIn);\n if (!queryString.empty())\n signInURL += (\"?\" + queryString);\n return signInURL;\n}\n\nstd::string getUserIdentifier(const core::http::Request& request)\n{\n return auth::secure_cookie::readSecureCookie(request, kUserId);\n}\n\nstd::string userIdentifierToLocalUsername(const std::string& userIdentifier)\n{\n return userIdentifier;\n}\n\nbool mainPageFilter(const http::Request& request,\n http::Response* pResponse)\n{\n \/\/ check for user identity, if we have one then allow the request to proceed\n std::string userIdentifier = getUserIdentifier(request);\n if (userIdentifier.empty())\n {\n \/\/ otherwise redirect to sign-in\n pResponse->setMovedTemporarily(request, applicationSignInURL(request, request.uri()));\n return false;\n }\n else\n {\n return true;\n }\n}\n\nvoid signInThenContinue(const core::http::Request& request,\n core::http::Response* pResponse)\n{\n pResponse->setMovedTemporarily(request, applicationSignInURL(request, request.uri()));\n}\n\nvoid refreshCredentialsThenContinue(\n boost::shared_ptr<core::http::AsyncConnection> pConnection)\n{\n \/\/ no silent refresh possible so delegate to sign-in and continue\n signInThenContinue(pConnection->request(),\n &(pConnection->response()));\n\n \/\/ write response\n pConnection->writeResponse();\n}\n\nvoid signIn(const http::Request& request,\n http::Response* pResponse)\n{\n auth::secure_cookie::remove(request, kUserId, \"\", pResponse);\n\n std::map<std::string,std::string> variables;\n variables[\"action\"] = applicationURL(request, kDoSignIn);\n variables[\"publicKeyUrl\"] = applicationURL(request, kPublicKey);\n\n \/\/ setup template variables\n std::string error = request.queryParamValue(kErrorParam);\n variables[kErrorMessage] = error;\n variables[kErrorDisplay] = error.empty() ? \"none\" : \"block\";\n\n variables[kAppUri] = request.queryParamValue(kAppUri);\n\n \/\/ get the path to the JS file\n Options& options = server::options();\n FilePath wwwPath(options.wwwLocalPath());\n FilePath signInPath = wwwPath.complete(\"templates\/encrypted-sign-in.htm\");\n\n text::TemplateFilter filter(variables);\n\n pResponse->setFile(signInPath, request, filter);\n pResponse->setContentType(\"text\/html\");\n}\n\nvoid publicKey(const http::Request&,\n http::Response* pResponse)\n{\n std::string exp, mod;\n util::system::crypto::rsaPublicKey(&exp, &mod);\n pResponse->setNoCacheHeaders();\n pResponse->setBody(exp + \":\" + mod);\n pResponse->setContentType(\"text\/plain\");\n}\n\nvoid doSignIn(const http::Request& request,\n http::Response* pResponse)\n{\n std::string appUri = request.formFieldValue(kAppUri);\n if (appUri.empty())\n appUri = \"\/\";\n\n std::string encryptedValue = request.formFieldValue(\"v\");\n bool persist = request.formFieldValue(\"persist\") == \"1\";\n std::string plainText;\n Error error = util::system::crypto::rsaPrivateDecrypt(encryptedValue,\n &plainText);\n if (error)\n {\n LOG_ERROR(error);\n pResponse->setMovedTemporarily(\n request,\n applicationSignInURL(request,\n appUri,\n \"Temporary server error,\"\n \" please try again\"));\n return;\n }\n\n size_t splitAt = plainText.find('\\n');\n if (splitAt < 0)\n {\n LOG_ERROR_MESSAGE(\"Didn't find newline in plaintext\");\n pResponse->setMovedTemporarily(\n request,\n applicationSignInURL(request,\n appUri,\n \"Temporary server error,\"\n \" please try again\"));\n return;\n }\n\n std::string username = plainText.substr(0, splitAt);\n std::string password = plainText.substr(splitAt + 1, plainText.size());\n\n if ( pamLogin(username, password) &&\n server::auth::validateUser(username))\n {\n if (appUri.size() > 0 && appUri[0] != '\/')\n appUri = \"\/\" + appUri;\n\n boost::optional<boost::gregorian::days> expiry;\n if (persist)\n expiry = boost::gregorian::days(3652);\n else\n expiry = boost::none;\n\n auth::secure_cookie::set(kUserId,\n username,\n request,\n boost::posix_time::time_duration(24*3652,\n 0,\n 0,\n 0),\n expiry,\n std::string(),\n pResponse);\n pResponse->setMovedTemporarily(request, appUri);\n }\n else\n {\n pResponse->setMovedTemporarily(\n request,\n applicationSignInURL(request,\n appUri,\n \"Incorrect or invalid username\/password\"));\n }\n}\n\nvoid signOut(const std::string&,\n const http::Request& request,\n http::Response* pResponse)\n{\n auth::secure_cookie::remove(request, kUserId, \"\", pResponse);\n pResponse->setMovedTemporarily(request, auth::handler::kSignIn);\n}\n\n} \/\/ anonymous namespace\n\nError initialize()\n{\n \/\/ register ourselves as the auth handler\n server::auth::handler::Handler pamHandler;\n pamHandler.getUserIdentifier = getUserIdentifier;\n pamHandler.userIdentifierToLocalUsername = userIdentifierToLocalUsername;\n pamHandler.mainPageFilter = mainPageFilter;\n pamHandler.signInThenContinue = signInThenContinue;\n pamHandler.refreshCredentialsThenContinue = refreshCredentialsThenContinue;\n pamHandler.signIn = signIn;\n pamHandler.signOut = signOut;\n auth::handler::registerHandler(pamHandler);\n\n \/\/ add pam-specific auth handlers\n uri_handlers::addBlocking(kDoSignIn, doSignIn);\n uri_handlers::addBlocking(kPublicKey, publicKey);\n\n \/\/ initialize crypto\n return util::system::crypto::rsaInit();\n}\n\n\n} \/\/ namespace pam_auth\n} \/\/ namespace server\n<commit_msg>add TODO to pam helper<commit_after>\/*\n * ServerPAMAuth.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n#include \"ServerPAMAuth.hpp\"\n\n#include <sys\/wait.h>\n\n#include <core\/Error.hpp>\n#include <core\/system\/System.hpp>\n#include <core\/system\/ProcessArgs.hpp>\n\n#include <core\/http\/Request.hpp>\n#include <core\/http\/Response.hpp>\n#include <core\/http\/URL.hpp>\n#include <core\/http\/AsyncUriHandler.hpp>\n#include <core\/text\/TemplateFilter.hpp>\n\n#include <server\/util\/system\/Crypto.hpp>\n#include <server\/util\/system\/System.hpp>\n\n#include <server\/auth\/ServerValidateUser.hpp>\n#include <server\/auth\/ServerSecureUriHandler.hpp>\n#include <server\/auth\/ServerAuthHandler.hpp>\n#include <server\/auth\/ServerSecureCookie.hpp>\n\n#include <server\/ServerOptions.hpp>\n#include <server\/ServerUriHandlers.hpp>\n\n\nnamespace server {\nnamespace pam_auth {\n\nnamespace {\n\n\/\/ TODO: verify that we never leak a file descriptor\n\n\/\/ TODO: don't re-assume priv on ubuntu\n\n\/\/ TODO: comments on intentionally failing forward in child\n\n\/\/ TODO: make sure inputs into pam helper are bounded\n\/\/ TODO: block tty case in pam helper\n\n\/\/ TODO: make sure it works on redhat\n\n\/\/ TODO: then can change hat permanently\n\n\n\/\/ Handles error logging and EINTR retrying. Only for use with\n\/\/ functions that return -1 on error and set errno.\nint posixcall(boost::function<ssize_t()> func, const ErrorLocation& location)\n{\n while (true)\n {\n int result;\n if ((result = func()) == -1)\n {\n if (errno == EINTR)\n continue;\n LOG_ERROR(systemError(errno, location));\n return result;\n }\n return result;\n }\n}\n\n\nbool pamLogin(const std::string& username, const std::string& password)\n{\n \/\/ get path to pam helper\n FilePath pamHelperPath(server::options().authPamHelperPath());\n if (!pamHelperPath.exists())\n {\n LOG_ERROR_MESSAGE(\"PAM helper binary does not exist at \" +\n pamHelperPath.absolutePath());\n return false;\n }\n\n \/\/ create pipes\n const int READ = 0;\n const int WRITE = 1;\n int fdInput[2];\n if (posixcall(boost::bind(::pipe, fdInput), ERROR_LOCATION) == -1)\n return false;\n int fdOutput[2];\n if (posixcall(boost::bind(::pipe, fdOutput), ERROR_LOCATION) == -1)\n return false;\n\n \/\/ fork\n pid_t pid = posixcall(::fork, ERROR_LOCATION);\n if (pid == -1)\n return false;\n\n \/\/ child\n else if (pid == 0)\n {\n \/\/ RedHat 5 returns PAM_SYSTEM_ERR from pam_authenticate if we're\n \/\/ running with geteuid != getuid (as is the case when we temporarily\n \/\/ drop privileges). So restore privilliges in the child\n if (util::system::realUserIsRoot())\n {\n Error error = util::system::restorePriv();\n if (error)\n LOG_ERROR(error);\n }\n\n \/\/ close unused pipes\n posixcall(boost::bind(::close, fdInput[WRITE]), ERROR_LOCATION);\n posixcall(boost::bind(::close, fdOutput[READ]), ERROR_LOCATION);\n\n \/\/ clear the child signal mask\n Error error = core::system::clearSignalMask();\n if (error)\n LOG_ERROR(error);\n\n \/\/ wire standard streams\n posixcall(boost::bind(::dup2, fdInput[READ], STDIN_FILENO),\n ERROR_LOCATION);\n posixcall(boost::bind(::dup2, fdOutput[WRITE], STDOUT_FILENO),\n ERROR_LOCATION);\n\n \/\/ close all open file descriptors other than std streams\n error = core::system::closeNonStdFileDescriptors();\n if (error)\n LOG_ERROR(error);\n\n \/\/ build username args (on heap so they stay around after exec)\n \/\/ and execute pam helper\n using core::system::ProcessArgs;\n std::vector<std::string> args;\n args.push_back(pamHelperPath.absolutePath());\n args.push_back(username);\n ProcessArgs* pProcessArgs = new ProcessArgs(args);\n ::execv(pamHelperPath.absolutePath().c_str(), pProcessArgs->args()) ;\n\n \/\/ in the normal case control should never return from execv (it starts\n \/\/ anew at main of the process pointed to by path). therefore, if we get\n \/\/ here then there was an error\n LOG_ERROR(systemError(errno, ERROR_LOCATION)) ;\n ::exit(EXIT_FAILURE) ;\n }\n\n \/\/ parent\n else\n {\n \/\/ close unused pipes\n posixcall(boost::bind(::close, fdInput[READ]), ERROR_LOCATION);\n posixcall(boost::bind(::close, fdOutput[WRITE]), ERROR_LOCATION);\n\n \/\/ write the password to standard input then close the pipe\n std::string input = password ;\n std::size_t written = posixcall(boost::bind(::write,\n fdInput[WRITE],\n input.c_str(),\n input.length()),\n ERROR_LOCATION);\n posixcall(boost::bind(::close, fdInput[WRITE]), ERROR_LOCATION);\n\n \/\/ check for correct bytes written\n if (written != static_cast<std::size_t>(input.length()))\n {\n \/\/ first close stdout pipe\n posixcall(boost::bind(::close, fdOutput[READ]), ERROR_LOCATION);\n\n \/\/ log error and return false\n LOG_ERROR_MESSAGE(\"Error writing to pam helper stdin\");\n return false;\n }\n\n \/\/ read the response from standard output\n char buf;\n size_t bytesRead = posixcall(boost::bind(::read, fdOutput[READ], &buf, 1),\n ERROR_LOCATION);\n posixcall(boost::bind(::close, fdOutput[READ]), ERROR_LOCATION);\n\n \/\/ return true if bytes were read\n return bytesRead > 0;\n }\n\n return false;\n}\n\n\n\nconst char * const kUserId = \"user-id\";\n\n\/\/ It's important that URIs be in the root directory, so the cookie\n\/\/ gets set\/unset at the correct scope!\nconst char * const kDoSignIn = \"\/auth-do-sign-in\";\nconst char * const kPublicKey = \"\/auth-public-key\";\n\nconst char * const kAppUri = \"appUri\";\n\nconst char * const kErrorParam = \"error\";\nconst char * const kErrorDisplay = \"errorDisplay\";\nconst char * const kErrorMessage = \"errorMessage\";\n\n\nstd::string applicationURL(const http::Request& request,\n const std::string& path = std::string())\n{\n return http::URL::uncomplete(\n request.uri(),\n path);\n}\n\nstd::string applicationSignInURL(const http::Request& request,\n const std::string& appUri,\n const std::string& errorMessage=std::string())\n{\n \/\/ build fields\n http::Fields fields ;\n if (appUri != \"\/\")\n fields.push_back(std::make_pair(kAppUri, appUri));\n if (!errorMessage.empty())\n fields.push_back(std::make_pair(kErrorParam, errorMessage));\n\n \/\/ build query string\n std::string queryString ;\n if (!fields.empty())\n http::util::buildQueryString(fields, &queryString);\n\n \/\/ generate url\n std::string signInURL = applicationURL(request, auth::handler::kSignIn);\n if (!queryString.empty())\n signInURL += (\"?\" + queryString);\n return signInURL;\n}\n\nstd::string getUserIdentifier(const core::http::Request& request)\n{\n return auth::secure_cookie::readSecureCookie(request, kUserId);\n}\n\nstd::string userIdentifierToLocalUsername(const std::string& userIdentifier)\n{\n return userIdentifier;\n}\n\nbool mainPageFilter(const http::Request& request,\n http::Response* pResponse)\n{\n \/\/ check for user identity, if we have one then allow the request to proceed\n std::string userIdentifier = getUserIdentifier(request);\n if (userIdentifier.empty())\n {\n \/\/ otherwise redirect to sign-in\n pResponse->setMovedTemporarily(request, applicationSignInURL(request, request.uri()));\n return false;\n }\n else\n {\n return true;\n }\n}\n\nvoid signInThenContinue(const core::http::Request& request,\n core::http::Response* pResponse)\n{\n pResponse->setMovedTemporarily(request, applicationSignInURL(request, request.uri()));\n}\n\nvoid refreshCredentialsThenContinue(\n boost::shared_ptr<core::http::AsyncConnection> pConnection)\n{\n \/\/ no silent refresh possible so delegate to sign-in and continue\n signInThenContinue(pConnection->request(),\n &(pConnection->response()));\n\n \/\/ write response\n pConnection->writeResponse();\n}\n\nvoid signIn(const http::Request& request,\n http::Response* pResponse)\n{\n auth::secure_cookie::remove(request, kUserId, \"\", pResponse);\n\n std::map<std::string,std::string> variables;\n variables[\"action\"] = applicationURL(request, kDoSignIn);\n variables[\"publicKeyUrl\"] = applicationURL(request, kPublicKey);\n\n \/\/ setup template variables\n std::string error = request.queryParamValue(kErrorParam);\n variables[kErrorMessage] = error;\n variables[kErrorDisplay] = error.empty() ? \"none\" : \"block\";\n\n variables[kAppUri] = request.queryParamValue(kAppUri);\n\n \/\/ get the path to the JS file\n Options& options = server::options();\n FilePath wwwPath(options.wwwLocalPath());\n FilePath signInPath = wwwPath.complete(\"templates\/encrypted-sign-in.htm\");\n\n text::TemplateFilter filter(variables);\n\n pResponse->setFile(signInPath, request, filter);\n pResponse->setContentType(\"text\/html\");\n}\n\nvoid publicKey(const http::Request&,\n http::Response* pResponse)\n{\n std::string exp, mod;\n util::system::crypto::rsaPublicKey(&exp, &mod);\n pResponse->setNoCacheHeaders();\n pResponse->setBody(exp + \":\" + mod);\n pResponse->setContentType(\"text\/plain\");\n}\n\nvoid doSignIn(const http::Request& request,\n http::Response* pResponse)\n{\n std::string appUri = request.formFieldValue(kAppUri);\n if (appUri.empty())\n appUri = \"\/\";\n\n std::string encryptedValue = request.formFieldValue(\"v\");\n bool persist = request.formFieldValue(\"persist\") == \"1\";\n std::string plainText;\n Error error = util::system::crypto::rsaPrivateDecrypt(encryptedValue,\n &plainText);\n if (error)\n {\n LOG_ERROR(error);\n pResponse->setMovedTemporarily(\n request,\n applicationSignInURL(request,\n appUri,\n \"Temporary server error,\"\n \" please try again\"));\n return;\n }\n\n size_t splitAt = plainText.find('\\n');\n if (splitAt < 0)\n {\n LOG_ERROR_MESSAGE(\"Didn't find newline in plaintext\");\n pResponse->setMovedTemporarily(\n request,\n applicationSignInURL(request,\n appUri,\n \"Temporary server error,\"\n \" please try again\"));\n return;\n }\n\n std::string username = plainText.substr(0, splitAt);\n std::string password = plainText.substr(splitAt + 1, plainText.size());\n\n if ( pamLogin(username, password) &&\n server::auth::validateUser(username))\n {\n if (appUri.size() > 0 && appUri[0] != '\/')\n appUri = \"\/\" + appUri;\n\n boost::optional<boost::gregorian::days> expiry;\n if (persist)\n expiry = boost::gregorian::days(3652);\n else\n expiry = boost::none;\n\n auth::secure_cookie::set(kUserId,\n username,\n request,\n boost::posix_time::time_duration(24*3652,\n 0,\n 0,\n 0),\n expiry,\n std::string(),\n pResponse);\n pResponse->setMovedTemporarily(request, appUri);\n }\n else\n {\n pResponse->setMovedTemporarily(\n request,\n applicationSignInURL(request,\n appUri,\n \"Incorrect or invalid username\/password\"));\n }\n}\n\nvoid signOut(const std::string&,\n const http::Request& request,\n http::Response* pResponse)\n{\n auth::secure_cookie::remove(request, kUserId, \"\", pResponse);\n pResponse->setMovedTemporarily(request, auth::handler::kSignIn);\n}\n\n} \/\/ anonymous namespace\n\nError initialize()\n{\n \/\/ register ourselves as the auth handler\n server::auth::handler::Handler pamHandler;\n pamHandler.getUserIdentifier = getUserIdentifier;\n pamHandler.userIdentifierToLocalUsername = userIdentifierToLocalUsername;\n pamHandler.mainPageFilter = mainPageFilter;\n pamHandler.signInThenContinue = signInThenContinue;\n pamHandler.refreshCredentialsThenContinue = refreshCredentialsThenContinue;\n pamHandler.signIn = signIn;\n pamHandler.signOut = signOut;\n auth::handler::registerHandler(pamHandler);\n\n \/\/ add pam-specific auth handlers\n uri_handlers::addBlocking(kDoSignIn, doSignIn);\n uri_handlers::addBlocking(kPublicKey, publicKey);\n\n \/\/ initialize crypto\n return util::system::crypto::rsaInit();\n}\n\n\n} \/\/ namespace pam_auth\n} \/\/ namespace server\n<|endoftext|>"} {"text":"<commit_before>#include <cppunit\/Exception.h>\n#include <cppunit\/extensions\/TypeInfoHelper.h>\n#include \"DefaultProtector.h\"\n\n\nCPPUNIT_NS_BEGIN\n\n\nbool \nDefaultProtector::protect( const Functor &functor,\n const ProtectorContext &context )\n{\n try\n {\n return functor();\n }\n catch ( Exception &failure )\n {\n reportFailure( context, failure );\n }\n catch ( std::exception &e )\n {\n std::string shortDescription( \"uncaught exception of type \" );\n#if CPPUNIT_USE_TYPEINFO_NAME\n shortDescription += TypeInfoHelper::getClassName( typeid(e) );\n#else\n shortDescription += \"std::exception (or derived).\"\n#endif\n Message message( shortDescription, e.what() );\n reportError( context, message );\n }\n catch ( ... )\n {\n reportError( context,\n Message( \"uncaught exception of unknown type\") );\n }\n \n return false;\n}\n\n\nCPPUNIT_NS_END\n<commit_msg>missing semicolon when CPPUNIT_USE_TYPEINFO_NAME not used<commit_after>#include <cppunit\/Exception.h>\n#include <cppunit\/extensions\/TypeInfoHelper.h>\n#include \"DefaultProtector.h\"\n\n\nCPPUNIT_NS_BEGIN\n\n\nbool \nDefaultProtector::protect( const Functor &functor,\n const ProtectorContext &context )\n{\n try\n {\n return functor();\n }\n catch ( Exception &failure )\n {\n reportFailure( context, failure );\n }\n catch ( std::exception &e )\n {\n std::string shortDescription( \"uncaught exception of type \" );\n#if CPPUNIT_USE_TYPEINFO_NAME\n shortDescription += TypeInfoHelper::getClassName( typeid(e) );\n#else\n shortDescription += \"std::exception (or derived).\";\n#endif\n Message message( shortDescription, e.what() );\n reportError( context, message );\n }\n catch ( ... )\n {\n reportError( context,\n Message( \"uncaught exception of unknown type\") );\n }\n \n return false;\n}\n\n\nCPPUNIT_NS_END\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\/*\n * Main authors:\n * Vincent Barichard <Vincent.Barichard@univ-angers.fr>\n *\n * Copyright:\n * Vincent Barichard, 2013\n *\n * Last modified:\n * $Date$ by $Author$\n * $Revision$\n *\n * This file is part of Quacode:\n * http:\/\/quacode.barichard.com\n *\n * This file is based on gecode\/search\/path.hh\n * and is under the same license as given below:\n *\n * Main authors:\n * Christian Schulte <schulte@gecode.org>\n *\n * Copyright:\n * Christian Schulte, 2009\n *\n * This file is part of Gecode, the generic constraint\n * development environment:\n * http:\/\/www.gecode.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#ifndef __GECODE_SEARCH_SEQUENTIAL_QDFS_HH__\n#define __GECODE_SEARCH_SEQUENTIAL_QDFS_HH__\n\n#include <gecode\/search.hh>\n#include <gecode\/search\/support.hh>\n#include <gecode\/search\/worker.hh>\n\n#include <quacode\/search\/sequential\/qpath.hh>\n\nnamespace Gecode { namespace Search { namespace Sequential {\n\n \/\/\/ Depth-first search engine implementation\n class QDFS : public Worker {\n private:\n \/\/\/ Search options\n Options opt;\n \/\/\/ Current path ins search tree\n QPath path;\n \/\/\/ Current space being explored\n Space* cur;\n \/\/\/ Distance until next clone\n unsigned int d;\n public:\n \/\/\/ Initialize for space \\a s with options \\a o\n QDFS(Space* s, const Options& o);\n \/\/\/ %Search for next solution\n Space* next(void);\n \/\/\/ Return statistics\n Statistics statistics(void) const;\n \/\/\/ Reset engine to restart at space \\a s\n void reset(Space* s);\n \/\/\/ Return no-goods\n NoGoods& nogoods(void);\n \/\/\/ Destructor\n ~QDFS(void);\n };\n\n forceinline \n QDFS::QDFS(Space* s, const Options& o)\n : opt(o), path(static_cast<int>(opt.nogoods_limit)), d(0) {\n if ((s == NULL) || (s->status(*this) == SS_FAILED)) {\n fail++;\n cur = NULL;\n if (!opt.clone)\n delete s;\n } else {\n cur = snapshot(s,opt);\n dynamic_cast<QSpaceInfo*>(cur)->strategyInit();\n }\n }\n\n forceinline void\n QDFS::reset(Space* s) {\n delete cur;\n path.reset();\n d = 0;\n if ((s == NULL) || (s->status(*this) == SS_FAILED)) {\n cur = NULL;\n } else {\n cur = s;\n dynamic_cast<QSpaceInfo*>(cur)->strategyReset();\n }\n Worker::reset();\n }\n\n forceinline NoGoods&\n QDFS::nogoods(void) {\n return path;\n }\n\n forceinline Space*\n QDFS::next(void) {\n Space * solvedSpace = NULL;\n TQuantifier bckQuant = EXISTS;\n start();\n while (true) {\n while (cur) {\n if (stop(opt))\n return NULL;\n node++;\n\n SpaceStatus curStatus = cur->status(*this);\n \/\/ If no more propagators in space then all is succes below.\n \/\/ We deal with that case as any other success.\n \/\/ If it remains only Watch Propagators, then it is a success!\n if ((!cur->failed()) && (cur->propagators() == dynamic_cast<QSpaceInfo*>(cur)->watchConstraints())) curStatus = SS_SOLVED;\n\n switch (curStatus) {\n case SS_FAILED:\n dynamic_cast<QSpaceInfo*>(cur)->scenarioFailed();\n \/\/ On devra dépiler jusqu'au dernier existentiel\n bckQuant = EXISTS;\n fail++;\n delete cur;\n cur = NULL;\n break;\n case SS_SOLVED:\n dynamic_cast<QSpaceInfo*>(cur)->scenarioSuccess();\n \/\/ We will must go back to the last universal variable\n bckQuant = FORALL;\n \/\/ Deletes all pending branchers\n {\n const Choice* ch = cur->choice();\n if (ch) delete ch;\n }\n solvedSpace = cur;\n cur = NULL;\n break;\n case SS_BRANCH:\n {\n Space* c;\n if ((d == 0) || (d >= opt.c_d)) {\n c = cur->clone();\n d = 1;\n } else {\n c = NULL;\n d++;\n }\n const Choice* ch = path.push(*this,cur,c);\n cur->commit(*ch,0);\n cur->print(*ch,0,UNUSED_STREAM);\n break;\n }\n default:\n GECODE_NEVER;\n }\n }\n do {\n if (!path.next(bckQuant))\n {\n cur = NULL;\n if (solvedSpace)\n {\n dynamic_cast<QSpaceInfo*>(cur)->strategySuccess();\n return solvedSpace;\n } else {\n dynamic_cast<QSpaceInfo*>(cur)->strategyFailed();\n return NULL;\n }\n }\n cur = path.recompute(d,opt.a_d,*this);\n } while (cur == NULL);\n if (solvedSpace)\n {\n delete solvedSpace;\n solvedSpace = NULL;\n }\n }\n GECODE_NEVER;\n return NULL;\n }\n\n forceinline Statistics\n QDFS::statistics(void) const {\n return *this;\n }\n\n forceinline \n QDFS::~QDFS(void) {\n delete cur;\n path.reset();\n }\n\n}}}\n\n#endif\n<commit_msg>Bug fix in search<commit_after>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\/*\n * Main authors:\n * Vincent Barichard <Vincent.Barichard@univ-angers.fr>\n *\n * Copyright:\n * Vincent Barichard, 2013\n *\n * Last modified:\n * $Date$ by $Author$\n * $Revision$\n *\n * This file is part of Quacode:\n * http:\/\/quacode.barichard.com\n *\n * This file is based on gecode\/search\/path.hh\n * and is under the same license as given below:\n *\n * Main authors:\n * Christian Schulte <schulte@gecode.org>\n *\n * Copyright:\n * Christian Schulte, 2009\n *\n * This file is part of Gecode, the generic constraint\n * development environment:\n * http:\/\/www.gecode.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#ifndef __GECODE_SEARCH_SEQUENTIAL_QDFS_HH__\n#define __GECODE_SEARCH_SEQUENTIAL_QDFS_HH__\n\n#include <gecode\/search.hh>\n#include <gecode\/search\/support.hh>\n#include <gecode\/search\/worker.hh>\n\n#include <quacode\/search\/sequential\/qpath.hh>\n\nnamespace Gecode { namespace Search { namespace Sequential {\n\n \/\/\/ Depth-first search engine implementation\n class QDFS : public Worker {\n private:\n \/\/\/ Search options\n Options opt;\n \/\/\/ Current path ins search tree\n QPath path;\n \/\/\/ Current space being explored\n Space* cur;\n \/\/\/ Distance until next clone\n unsigned int d;\n public:\n \/\/\/ Initialize for space \\a s with options \\a o\n QDFS(Space* s, const Options& o);\n \/\/\/ %Search for next solution\n Space* next(void);\n \/\/\/ Return statistics\n Statistics statistics(void) const;\n \/\/\/ Reset engine to restart at space \\a s\n void reset(Space* s);\n \/\/\/ Return no-goods\n NoGoods& nogoods(void);\n \/\/\/ Destructor\n ~QDFS(void);\n };\n\n forceinline \n QDFS::QDFS(Space* s, const Options& o)\n : opt(o), path(static_cast<int>(opt.nogoods_limit)), d(0) {\n if ((s == NULL) || (s->status(*this) == SS_FAILED)) {\n fail++;\n cur = NULL;\n if (!opt.clone)\n delete s;\n } else {\n cur = snapshot(s,opt);\n dynamic_cast<QSpaceInfo*>(cur)->strategyInit();\n }\n }\n\n forceinline void\n QDFS::reset(Space* s) {\n delete cur;\n path.reset();\n d = 0;\n if ((s == NULL) || (s->status(*this) == SS_FAILED)) {\n cur = NULL;\n } else {\n cur = s;\n dynamic_cast<QSpaceInfo*>(cur)->strategyReset();\n }\n Worker::reset();\n }\n\n forceinline NoGoods&\n QDFS::nogoods(void) {\n return path;\n }\n\n forceinline Space*\n QDFS::next(void) {\n Space * solvedSpace = NULL;\n Space * failedSpace = NULL;\n TQuantifier bckQuant = EXISTS;\n start();\n while (true) {\n while (cur) {\n if (stop(opt))\n return NULL;\n node++;\n\n SpaceStatus curStatus = cur->status(*this);\n \/\/ If no more propagators in space then all is succes below.\n \/\/ We deal with that case as any other success.\n \/\/ If it remains only Watch Propagators, then it is a success!\n if ((!cur->failed()) && (cur->propagators() == dynamic_cast<QSpaceInfo*>(cur)->watchConstraints())) curStatus = SS_SOLVED;\n\n switch (curStatus) {\n case SS_FAILED:\n dynamic_cast<QSpaceInfo*>(cur)->scenarioFailed();\n \/\/ On devra dépiler jusqu'au dernier existentiel\n bckQuant = EXISTS;\n fail++;\n failedSpace = cur;\n cur = NULL;\n break;\n case SS_SOLVED:\n dynamic_cast<QSpaceInfo*>(cur)->scenarioSuccess();\n \/\/ We will must go back to the last universal variable\n bckQuant = FORALL;\n \/\/ Deletes all pending branchers\n {\n const Choice* ch = cur->choice();\n if (ch) delete ch;\n }\n solvedSpace = cur;\n cur = NULL;\n break;\n case SS_BRANCH:\n {\n Space* c;\n if ((d == 0) || (d >= opt.c_d)) {\n c = cur->clone();\n d = 1;\n } else {\n c = NULL;\n d++;\n }\n const Choice* ch = path.push(*this,cur,c);\n cur->commit(*ch,0);\n cur->print(*ch,0,UNUSED_STREAM);\n break;\n }\n default:\n GECODE_NEVER;\n }\n }\n do {\n if (!path.next(bckQuant))\n {\n cur = NULL;\n if (solvedSpace)\n {\n dynamic_cast<QSpaceInfo*>(solvedSpace)->strategySuccess();\n return solvedSpace;\n } else {\n dynamic_cast<QSpaceInfo*>(failedSpace)->strategyFailed();\n delete failedSpace;\n return NULL;\n }\n }\n cur = path.recompute(d,opt.a_d,*this);\n } while (cur == NULL);\n if (solvedSpace)\n {\n delete solvedSpace;\n solvedSpace = NULL;\n }\n if (failedSpace)\n {\n delete failedSpace;\n failedSpace = NULL;\n }\n }\n GECODE_NEVER;\n return NULL;\n }\n\n forceinline Statistics\n QDFS::statistics(void) const {\n return *this;\n }\n\n forceinline \n QDFS::~QDFS(void) {\n delete cur;\n path.reset();\n }\n\n}}}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <quic\/server\/QuicServer.h>\n\nnamespace quic {\n\nQuicServer::EventBaseBackendDetails QuicServer::getEventBaseBackendDetails() {\n EventBaseBackendDetails ret;\n ret.factory = &folly::EventBase::getDefaultBackend;\n return ret;\n}\n\n} \/\/ namespace quic\n<commit_msg>Precise event_base timer on Windows<commit_after>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <folly\/io\/async\/EventBase.h>\n#include <folly\/io\/async\/EventBaseBackendBase.h>\n#include <quic\/server\/QuicServer.h>\n\nnamespace quic {\n\n#if _WIN32\n#include <mmsystem.h>\n#include <timeapi.h>\n#pragma comment(lib, \"winmm.lib\")\n\nstruct GetBetterWindowsTimers {\n GetBetterWindowsTimers() {\n CHECK_EQ(timeBeginPeriod(1), TIMERR_NOERROR);\n }\n ~GetBetterWindowsTimers() {\n timeEndPeriod(1);\n }\n};\n\nGetBetterWindowsTimers timerGetter;\n\nclass WindowsEventBaseBackend : public folly::EventBaseBackendBase {\n public:\n WindowsEventBaseBackend();\n explicit WindowsEventBaseBackend(event_base* evb);\n ~WindowsEventBaseBackend() override;\n\n event_base* getEventBase() override {\n return evb_;\n }\n\n int eb_event_base_loop(int flags) override;\n int eb_event_base_loopbreak() override;\n\n int eb_event_add(Event& event, const struct timeval* timeout) override;\n int eb_event_del(EventBaseBackendBase::Event& event) override;\n\n bool eb_event_active(Event& event, int res) override;\n\n private:\n event_base* evb_;\n};\n\nWindowsEventBaseBackend::WindowsEventBaseBackend() {\n evb_ = event_base_new();\n}\n\nWindowsEventBaseBackend::WindowsEventBaseBackend(event_base* evb) : evb_(evb) {\n if (UNLIKELY(evb_ == nullptr)) {\n LOG(ERROR) << \"EventBase(): Pass nullptr as event base.\";\n throw std::invalid_argument(\"EventBase(): event base cannot be nullptr\");\n }\n}\n\nint WindowsEventBaseBackend::eb_event_base_loop(int flags) {\n return event_base_loop(evb_, flags);\n}\n\nint WindowsEventBaseBackend::eb_event_base_loopbreak() {\n return event_base_loopbreak(evb_);\n}\n\nint WindowsEventBaseBackend::eb_event_add(\n Event& event,\n const struct timeval* timeout) {\n return event_add(event.getEvent(), timeout);\n}\n\nint WindowsEventBaseBackend::eb_event_del(EventBaseBackendBase::Event& event) {\n return event_del(event.getEvent());\n}\n\nbool WindowsEventBaseBackend::eb_event_active(Event& event, int res) {\n event_active(event.getEvent(), res, 1);\n return true;\n}\n\nWindowsEventBaseBackend::~WindowsEventBaseBackend() {\n event_base_free(evb_);\n}\n\nstatic std::unique_ptr<folly::EventBaseBackendBase>\ngetWindowsEventBaseBackend() {\n auto config = event_config_new();\n event_config_set_flag(config, EVENT_BASE_FLAG_PRECISE_TIMER);\n auto evb = event_base_new_with_config(config);\n event_config_free(config);\n std::unique_ptr<folly::EventBaseBackendBase> backend =\n std::make_unique<WindowsEventBaseBackend>(evb);\n return backend;\n}\n\n#endif\n\nQuicServer::EventBaseBackendDetails QuicServer::getEventBaseBackendDetails() {\n EventBaseBackendDetails ret;\n#if _WIN32\n ret.factory = &getWindowsEventBaseBackend;\n#else\n ret.factory = &folly::EventBase::getDefaultBackend;\n#endif\n return ret;\n}\n\n} \/\/ namespace quic\n<|endoftext|>"} {"text":"<commit_before>#include \"Game.h\"\n#include \"Player.h\"\n#include \"GameStateManager.h\"\n#include \"Server.h\"\n#include \"Socket.h\"\n#include \"ClientCommand.h\"\n\n#include <thread>\n\nGame::Game() \n{\n\t_commands = make_shared<std::queue<ClientCommand>>();\n\t_players = make_shared<vector<shared_ptr<Player>>>();\n\t_factory = make_shared<CardFactory>();\n\t_buildingCards = make_shared<CardStack<BuildingCard>>();\n\t_characterCards = make_shared<CardStack<CharacterCard>>();\n\t_characterMap = make_shared<std::map<Game::Character, std::string>>();\n\t_orderQueue = make_shared<std::queue<Character>>();\n\n\t_gold = GOLD_AMOUNT;\n}\n\nGame::~Game() \n{\n}\n\nvoid Game::Init() \n{\n\t\/\/ Start server\n\tthread server{ Server::Start, shared_from_this() };\n\tserver.detach();\n\n\t\/\/ Load cards from file\n\t_factory->CreateCharacterCardsFromFile(\"assets\/cards\/charactercards.csv\", shared_from_this());\n\t_factory->CreateBuildingCardsFromFile(\"assets\/cards\/buildingcards.csv\", shared_from_this());\n\n\t\/\/ Create statemanager\n\t_stateManager = make_shared<GameStateManager>(shared_from_this());\n\n\t\/\/ Start running\n\t_running = true;\n\tSetGameStart(true);\n}\n\nvoid Game::Cleanup() \n{\n\n}\n\nvoid Game::Start()\n{\n\t\/\/ Start game\n\twhile (_running) {\n\t\tHandleEvents(shared_from_this());\n\t\tUpdate(shared_from_this());\n\t}\n}\n\nvoid Game::Stop() \n{\n\t_running = false;\n}\n\nvoid Game::HandleEvents(shared_ptr<Game> &game)\n{\n\t_stateManager->HandleEvents(game);\n}\n\nvoid Game::Update(shared_ptr<Game> &game)\n{\n\t_stateManager->Update(game);\n}\n\nvoid Game::AddCommand(ClientCommand command)\n{\n\t_commands->push(command);\n}\n\nbool Game::HasNextCommand(shared_ptr<Player> &player) {\n\tbool has = false;\n\n\tif (_commands->size() > 0) {\n\t\tClientCommand command = _commands->front();\n\t\tif (command.get_client() == player->GetClient())\n\t\t\thas = true;\n\t}\n\treturn has;\n}\n\nClientCommand Game::GetNextCommand(shared_ptr<Player> &player)\n{\n\twhile (_commands->front().get_client() != player->GetClient())\n\t\t_commands->pop();\n\tClientCommand command = _commands->front();\n\t_commands->pop();\n\treturn command;\n}\n\nvoid Game::AddPlayer(shared_ptr<Socket> &client)\n{\n\t_players->push_back(make_unique<Player>(client, shared_from_this()));\n}\n\nint Game::GetPlayerCount() \n{\n\treturn _players->size();\n}\n\nvoid Game::AddBuildingCard(BuildingCard card)\n{\n\t_buildingCards->AddCard(card);\n}\n\nvoid Game::AddCharacterCard(CharacterCard card)\n{\n\t_characterCards->AddCard(card);\n}\n\nvoid Game::AddGold(int amount)\n{\n\t_gold += amount;\n\tif (_gold > GOLD_AMOUNT)\n\t\t_gold = GOLD_AMOUNT;\n}\n\nint Game::RemoveGold(int amount)\n{\n\tif ((_gold -= amount) < 0) {\n\t\treturn -1;\n\t}\n\telse {\n\t\treturn amount;\n\t}\n}\n\nvoid Game::KillCharacter(Character character)\n{\n\t_flagForKill = character;\n}\n\nvoid Game::StealFrom(Character character)\n{\n\t_flagForSteal = character;\n}\n\nshared_ptr<Player> Game::GetOpponent(shared_ptr<Player> &player)\n{\n\t\/\/ Determine opponent\n\tshared_ptr<Player> opponent;\n\tif (GetPlayers()->front() == player)\n\t\topponent = GetPlayers()->back();\n\telse\n\t\topponent = GetPlayers()->front();\n\treturn opponent;\n}\n\nvoid Game::GenerateOrder()\n{\n\t_orderQueue->push(ASSASSIN);\n\t_orderQueue->push(THIEF);\n\t_orderQueue->push(WIZARD);\n\t_orderQueue->push(KING);\n\t_orderQueue->push(BISHOP);\n\t_orderQueue->push(MERCHANT);\n\t_orderQueue->push(ARCHITECT);\n\t_orderQueue->push(WARLORD);\n}\n\nvoid Game::GenerateMap()\n{\n\t_characterMap->insert(std::make_pair(ASSASSIN, \"Assassin\"));\n\t_characterMap->insert(std::make_pair(THIEF, \"Thief\"));\n\t_characterMap->insert(std::make_pair(WIZARD, \"Wizard\"));\n\t_characterMap->insert(std::make_pair(KING, \"King\"));\n\t_characterMap->insert(std::make_pair(BISHOP, \"Bishop\"));\n\t_characterMap->insert(std::make_pair(MERCHANT, \"Merchant\"));\n\t_characterMap->insert(std::make_pair(ARCHITECT, \"Architect\"));\n\t_characterMap->insert(std::make_pair(WARLORD, \"Warlord\"));\n}\n\nvoid Game::ResetRound(bool isStart)\n{\n\tif (isStart) {\n\t\tshared_ptr<CardStack<BuildingCard>> bCards = _factory->GetBuildingCards();\n\t\t_buildingCards->Clear();\n\t\tfor (size_t i = 0, blen = bCards->Size(); i < blen; ++i)\n\t\t\t_buildingCards->AddCard(bCards->ShowCardByIndex(i));\n\t}\n\n\tshared_ptr<CardStack<CharacterCard>> cCards = _factory->GetCharacterCards();\n\n\t_characterCards->Clear();\n\n\tfor (size_t i = 0, clen = cCards->Size(); i < clen; ++i)\n\t\t_characterCards->AddCard(cCards->ShowCardByIndex(i));\n\n\tfor (size_t i = 0, plen = _players->size(); i < plen; ++i) {\n\t\t_players->at(i)->GetCharacterCards()->Clear();\n\t}\n\n\t_flagForKill = LAST_CHARACTER;\n\t_flagForSteal = LAST_CHARACTER;\n\n\tGenerateOrder();\n}\n<commit_msg>CommandQueue fix<commit_after>#include \"Game.h\"\n#include \"Player.h\"\n#include \"GameStateManager.h\"\n#include \"Server.h\"\n#include \"Socket.h\"\n#include \"ClientCommand.h\"\n\n#include <thread>\n\nGame::Game() \n{\n\t_commands = make_shared<std::queue<ClientCommand>>();\n\t_players = make_shared<vector<shared_ptr<Player>>>();\n\t_factory = make_shared<CardFactory>();\n\t_buildingCards = make_shared<CardStack<BuildingCard>>();\n\t_characterCards = make_shared<CardStack<CharacterCard>>();\n\t_characterMap = make_shared<std::map<Game::Character, std::string>>();\n\t_orderQueue = make_shared<std::queue<Character>>();\n\n\t_gold = GOLD_AMOUNT;\n}\n\nGame::~Game() \n{\n}\n\nvoid Game::Init() \n{\n\t\/\/ Start server\n\tthread server{ Server::Start, shared_from_this() };\n\tserver.detach();\n\n\t\/\/ Load cards from file\n\t_factory->CreateCharacterCardsFromFile(\"assets\/cards\/charactercards.csv\", shared_from_this());\n\t_factory->CreateBuildingCardsFromFile(\"assets\/cards\/buildingcards.csv\", shared_from_this());\n\n\t\/\/ Create statemanager\n\t_stateManager = make_shared<GameStateManager>(shared_from_this());\n\n\t\/\/ Start running\n\t_running = true;\n\tSetGameStart(true);\n}\n\nvoid Game::Cleanup() \n{\n\n}\n\nvoid Game::Start()\n{\n\t\/\/ Start game\n\twhile (_running) {\n\t\tHandleEvents(shared_from_this());\n\t\tUpdate(shared_from_this());\n\t}\n}\n\nvoid Game::Stop() \n{\n\t_running = false;\n}\n\nvoid Game::HandleEvents(shared_ptr<Game> &game)\n{\n\t_stateManager->HandleEvents(game);\n}\n\nvoid Game::Update(shared_ptr<Game> &game)\n{\n\t_stateManager->Update(game);\n}\n\nvoid Game::AddCommand(ClientCommand command)\n{\n\t_commands->push(command);\n}\n\nbool Game::HasNextCommand(shared_ptr<Player> &player) {\n\tbool has = false;\n\n\twhile (_commands->size() > 1) {\n\t\tif (_commands->front().get_client() != player->GetClient())\n\t\t\t_commands->pop();\n\t}\n\tif (!_commands->empty()) {\n\t\tif (_commands->front().get_client() != player->GetClient())\n\t\t\t_commands->pop();\n\t\telse\n\t\t\thas = true;\n\t}\n\n\treturn has;\n}\n\nClientCommand Game::GetNextCommand(shared_ptr<Player> &player)\n{\n\twhile (_commands->front().get_client() != player->GetClient())\n\t\t_commands->pop();\n\tClientCommand command = _commands->front();\n\t_commands->pop();\n\treturn command;\n}\n\nvoid Game::AddPlayer(shared_ptr<Socket> &client)\n{\n\t_players->push_back(make_unique<Player>(client, shared_from_this()));\n}\n\nint Game::GetPlayerCount() \n{\n\treturn _players->size();\n}\n\nvoid Game::AddBuildingCard(BuildingCard card)\n{\n\t_buildingCards->AddCard(card);\n}\n\nvoid Game::AddCharacterCard(CharacterCard card)\n{\n\t_characterCards->AddCard(card);\n}\n\nvoid Game::AddGold(int amount)\n{\n\t_gold += amount;\n\tif (_gold > GOLD_AMOUNT)\n\t\t_gold = GOLD_AMOUNT;\n}\n\nint Game::RemoveGold(int amount)\n{\n\tif ((_gold -= amount) < 0) {\n\t\treturn -1;\n\t}\n\telse {\n\t\treturn amount;\n\t}\n}\n\nvoid Game::KillCharacter(Character character)\n{\n\t_flagForKill = character;\n}\n\nvoid Game::StealFrom(Character character)\n{\n\t_flagForSteal = character;\n}\n\nshared_ptr<Player> Game::GetOpponent(shared_ptr<Player> &player)\n{\n\t\/\/ Determine opponent\n\tshared_ptr<Player> opponent;\n\tif (GetPlayers()->front() == player)\n\t\topponent = GetPlayers()->back();\n\telse\n\t\topponent = GetPlayers()->front();\n\treturn opponent;\n}\n\nvoid Game::GenerateOrder()\n{\n\t_orderQueue->push(ASSASSIN);\n\t_orderQueue->push(THIEF);\n\t_orderQueue->push(WIZARD);\n\t_orderQueue->push(KING);\n\t_orderQueue->push(BISHOP);\n\t_orderQueue->push(MERCHANT);\n\t_orderQueue->push(ARCHITECT);\n\t_orderQueue->push(WARLORD);\n}\n\nvoid Game::GenerateMap()\n{\n\t_characterMap->insert(std::make_pair(ASSASSIN, \"Assassin\"));\n\t_characterMap->insert(std::make_pair(THIEF, \"Thief\"));\n\t_characterMap->insert(std::make_pair(WIZARD, \"Wizard\"));\n\t_characterMap->insert(std::make_pair(KING, \"King\"));\n\t_characterMap->insert(std::make_pair(BISHOP, \"Bishop\"));\n\t_characterMap->insert(std::make_pair(MERCHANT, \"Merchant\"));\n\t_characterMap->insert(std::make_pair(ARCHITECT, \"Architect\"));\n\t_characterMap->insert(std::make_pair(WARLORD, \"Warlord\"));\n}\n\nvoid Game::ResetRound(bool isStart)\n{\n\tif (isStart) {\n\t\tshared_ptr<CardStack<BuildingCard>> bCards = _factory->GetBuildingCards();\n\t\t_buildingCards->Clear();\n\t\tfor (size_t i = 0, blen = bCards->Size(); i < blen; ++i)\n\t\t\t_buildingCards->AddCard(bCards->ShowCardByIndex(i));\n\t}\n\n\tshared_ptr<CardStack<CharacterCard>> cCards = _factory->GetCharacterCards();\n\n\t_characterCards->Clear();\n\n\tfor (size_t i = 0, clen = cCards->Size(); i < clen; ++i)\n\t\t_characterCards->AddCard(cCards->ShowCardByIndex(i));\n\n\tfor (size_t i = 0, plen = _players->size(); i < plen; ++i) {\n\t\t_players->at(i)->GetCharacterCards()->Clear();\n\t}\n\n\t_flagForKill = LAST_CHARACTER;\n\t_flagForSteal = LAST_CHARACTER;\n\n\tGenerateOrder();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"views\/gamelist\/IGameListView.h\"\n#include \"Window.h\"\n#include \"guis\/GuiMetaDataEd.h\"\n#include \"guis\/GuiMenu.h\"\n#include \"guis\/GuiGamelistOptions.h\"\n#include \"views\/ViewController.h\"\n#include \"Settings.h\"\n#include \"Log.h\"\n#include \"Sound.h\"\n\nbool IGameListView::input(InputConfig* config, Input input)\n{\n\t\/\/ select to open GuiGamelistOptions\n\tif(config->isMappedTo(\"select\", input) && input.value)\n\t{\n\t\tSound::getFromTheme(mTheme, getName(), \"menuOpen\")->play();\n\t\tmWindow->pushGui(new GuiGamelistOptions(mWindow, this->mRoot->getSystem()));\n\t\treturn true;\n\n\t\/\/ Ctrl-R to reload a view when debugging\n\t}else if(Settings::getInstance()->getBool(\"Debug\") && config->getDeviceId() == DEVICE_KEYBOARD && \n\t\t(SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) && input.id == SDLK_r && input.value != 0)\n\t{\n\t\tLOG(LogDebug) << \"reloading view\";\n\t\tViewController::get()->reloadGameListView(this, true);\n\t\treturn true;\n\t}\n\n\treturn GuiComponent::input(config, input);\n}\n\nvoid IGameListView::setTheme(const std::shared_ptr<ThemeData>& theme)\n{\n\tmTheme = theme;\n\tonThemeChanged(theme);\n}\n\nHelpStyle IGameListView::getHelpStyle()\n{\n\tHelpStyle style;\n\tstyle.applyTheme(mTheme, getName());\n\treturn style;\n}\n\nvoid IGameListView::render(const Eigen::Affine3f& parentTrans)\n{\n\tEigen::Affine3f trans = parentTrans * getTransform();\n\tRenderer::pushClipRect(Eigen::Vector2i(trans.translation()[0],trans.translation()[1]), Eigen::Vector2i(Renderer::getScreenWidth(), Renderer::getScreenHeight()));\n\trenderChildren(trans);\n\tRenderer::popClipRect();\n}\n<commit_msg>fix #151 zoom launch transition by extracting scale factor from transform<commit_after>#include \"views\/gamelist\/IGameListView.h\"\n#include \"Window.h\"\n#include \"guis\/GuiMetaDataEd.h\"\n#include \"guis\/GuiMenu.h\"\n#include \"guis\/GuiGamelistOptions.h\"\n#include \"views\/ViewController.h\"\n#include \"Settings.h\"\n#include \"Log.h\"\n#include \"Sound.h\"\n\nbool IGameListView::input(InputConfig* config, Input input)\n{\n\t\/\/ select to open GuiGamelistOptions\n\tif(config->isMappedTo(\"select\", input) && input.value)\n\t{\n\t\tSound::getFromTheme(mTheme, getName(), \"menuOpen\")->play();\n\t\tmWindow->pushGui(new GuiGamelistOptions(mWindow, this->mRoot->getSystem()));\n\t\treturn true;\n\n\t\/\/ Ctrl-R to reload a view when debugging\n\t}else if(Settings::getInstance()->getBool(\"Debug\") && config->getDeviceId() == DEVICE_KEYBOARD && \n\t\t(SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) && input.id == SDLK_r && input.value != 0)\n\t{\n\t\tLOG(LogDebug) << \"reloading view\";\n\t\tViewController::get()->reloadGameListView(this, true);\n\t\treturn true;\n\t}\n\n\treturn GuiComponent::input(config, input);\n}\n\nvoid IGameListView::setTheme(const std::shared_ptr<ThemeData>& theme)\n{\n\tmTheme = theme;\n\tonThemeChanged(theme);\n}\n\nHelpStyle IGameListView::getHelpStyle()\n{\n\tHelpStyle style;\n\tstyle.applyTheme(mTheme, getName());\n\treturn style;\n}\n\nvoid IGameListView::render(const Eigen::Affine3f& parentTrans)\n{\n\tEigen::Affine3f trans = parentTrans * getTransform();\n\n\tfloat scaleX = trans.linear()(0,0);\n\tfloat scaleY = trans.linear()(1,1);\n\n\tEigen::Vector2i pos(trans.translation()[0], trans.translation()[1]);\n\tEigen::Vector2i size(mSize.x() * scaleX, mSize.y() * scaleY);\n\n\tRenderer::pushClipRect(pos, size);\n\trenderChildren(trans);\n\tRenderer::popClipRect();\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"numerics\/unbounded_arrays.hpp\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace principia {\nnamespace numerics {\n\nclass UnboundedArraysTest : public ::testing::Test {\n protected:\n UnboundedArraysTest()\n : v3_({10, 31, -47}),\n v4_({-3, -3, 1, 4}),\n l4_({ 1,\n 2, 3,\n 5, 8, 13,\n 21, 34, 55, 89}) {}\n\n UnboundedVector<double> v3_;\n UnboundedVector<double> v4_;\n UnboundedLowerTriangularMatrix<double> l4_;\n};\n\nTEST_F(UnboundedArraysTest, Assignment) {\n UnboundedVector<double> u2({1, 2});\n UnboundedVector<double> v2 = {{1, 2}};\n UnboundedVector<double> w2(2);\n w2 = {{1, 2}};\n EXPECT_EQ(u2, v2);\n EXPECT_EQ(u2, w2);\n\n UnboundedLowerTriangularMatrix<double> l3({1,\n 2, 3,\n 4, 5, 6});\n UnboundedLowerTriangularMatrix<double> m3 = {{1,\n 2, 3,\n 4, 5, 6}};\n UnboundedLowerTriangularMatrix<double> n3 = {{0,\n 0, 0,\n 0, 0, 0}};\n UnboundedLowerTriangularMatrix<double> o3(3);\n EXPECT_EQ(o3, n3);\n n3 = {{1,\n 2, 3,\n 4, 5, 6}};\n EXPECT_EQ(l3, m3);\n EXPECT_EQ(l3, n3);\n}\n\nTEST_F(UnboundedArraysTest, VectorIndexing) {\n EXPECT_EQ(31, v3_[1]);\n v3_[2] = -666;\n EXPECT_EQ(-666, v3_[2]);\n}\n\nTEST_F(UnboundedArraysTest, LowerTriangularMatrixIndexing) {\n EXPECT_EQ(10, l4_.dimension());\n EXPECT_EQ(1, l4_[0][0]);\n EXPECT_EQ(2, l4_[1][0]);\n EXPECT_EQ(3, l4_[1][1]);\n EXPECT_EQ(5, l4_[2][0]);\n EXPECT_EQ(8, l4_[2][1]);\n EXPECT_EQ(13, l4_[2][2]);\n EXPECT_EQ(21, l4_[3][0]);\n EXPECT_EQ(34, l4_[3][1]);\n EXPECT_EQ(55, l4_[3][2]);\n EXPECT_EQ(89, l4_[3][3]);\n l4_[3][1] = -666;\n EXPECT_EQ(-666, l4_[3][1]);\n}\n\nTEST_F(UnboundedArraysTest, Extend) {\n UnboundedVector<double> u2({1, 2});\n UnboundedVector<double> u4({1, 2, 3, 4});\n u2.Extend({3, 4});\n EXPECT_EQ(u2, u4);\n\n UnboundedLowerTriangularMatrix<double> l3({1,\n 2, 3,\n 4, 5, 6});\n UnboundedLowerTriangularMatrix<double> l4({1,\n 2, 3,\n 4, 5, 6,\n 7, 8, 9, 10});\n l3.Extend({7, 8, 9, 10});\n EXPECT_EQ(l3, l4);\n}\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<commit_msg>Readying for review.<commit_after>\n#include \"numerics\/unbounded_arrays.hpp\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace principia {\nnamespace numerics {\n\nclass UnboundedArraysTest : public ::testing::Test {\n protected:\n UnboundedArraysTest()\n : v3_({10, 31, -47}),\n v4_({-3, -3, 1, 4}),\n l4_({1, 2, 3, 5, 8, 13, 21, 34, 55, 89}) {}\n\n UnboundedVector<double> v3_;\n UnboundedVector<double> v4_;\n UnboundedLowerTriangularMatrix<double> l4_;\n};\n\nTEST_F(UnboundedArraysTest, Assignment) {\n UnboundedVector<double> u2({1, 2});\n UnboundedVector<double> v2 = {{1, 2}};\n UnboundedVector<double> w2(2);\n w2 = {{1, 2}};\n EXPECT_EQ(u2, v2);\n EXPECT_EQ(u2, w2);\n\n UnboundedLowerTriangularMatrix<double> l3({1, 2, 3, 4, 5, 6});\n UnboundedLowerTriangularMatrix<double> m3 = {{1, 2, 3, 4, 5, 6}};\n UnboundedLowerTriangularMatrix<double> n3 = {{0, 0, 0, 0, 0, 0}};\n UnboundedLowerTriangularMatrix<double> o3(3);\n EXPECT_EQ(o3, n3);\n n3 = {{1, 2, 3, 4, 5, 6}};\n EXPECT_EQ(l3, m3);\n EXPECT_EQ(l3, n3);\n}\n\nTEST_F(UnboundedArraysTest, VectorIndexing) {\n EXPECT_EQ(31, v3_[1]);\n v3_[2] = -666;\n EXPECT_EQ(-666, v3_[2]);\n}\n\nTEST_F(UnboundedArraysTest, LowerTriangularMatrixIndexing) {\n EXPECT_EQ(10, l4_.dimension());\n EXPECT_EQ(1, l4_[0][0]);\n EXPECT_EQ(2, l4_[1][0]);\n EXPECT_EQ(3, l4_[1][1]);\n EXPECT_EQ(5, l4_[2][0]);\n EXPECT_EQ(8, l4_[2][1]);\n EXPECT_EQ(13, l4_[2][2]);\n EXPECT_EQ(21, l4_[3][0]);\n EXPECT_EQ(34, l4_[3][1]);\n EXPECT_EQ(55, l4_[3][2]);\n EXPECT_EQ(89, l4_[3][3]);\n l4_[3][1] = -666;\n EXPECT_EQ(-666, l4_[3][1]);\n}\n\nTEST_F(UnboundedArraysTest, Extend) {\n UnboundedVector<double> u2({1, 2});\n UnboundedVector<double> u4({1, 2, 3, 4});\n u2.Extend({3, 4});\n EXPECT_EQ(u2, u4);\n\n UnboundedLowerTriangularMatrix<double> l3({1, 2, 3, 4, 5, 6});\n UnboundedLowerTriangularMatrix<double> l4({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});\n l3.Extend({7, 8, 9, 10});\n EXPECT_EQ(l3, l4);\n}\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License 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. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n#include \"grins_config.h\"\n\n#include \"reacting_low_mach_navier_stokes_base.C\"\n#include \"reacting_low_mach_navier_stokes.C\"\n\n#ifdef GRINS_HAVE_CANTERA\n\n#include \"grins\/cantera_mixture.h\"\n#include \"grins\/cantera_evaluator.h\"\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::CanteraMixture,GRINS::CanteraEvaluator>;\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::CanteraMixture,GRINS::CanteraEvaluator>;\n\n#endif \/\/ GRINS_HAVE_CANTERA\n\n\n\n#ifdef GRINS_HAVE_ANTIOCH\n\n#include \"grins\/antioch_mixture_averaged_transport_mixture.h\"\n#include \"grins\/antioch_mixture_averaged_transport_evaluator.h\"\n\n#include \"grins\/antioch_constant_transport_mixture.h\"\n#include \"grins\/antioch_constant_transport_evaluator.h\"\n\n\/* -------------------- ReactingLowMachNavierStokes -------------------- *\/\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::AntiochMixtureAveragedTransportMixture<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::SutherlandViscosity<libMesh::Real>,\n Antioch::EuckenThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real> >,\n Antioch::ConstantLewisDiffusivity<libMesh::Real> >,\n GRINS::AntiochMixtureAveragedTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::SutherlandViscosity<libMesh::Real>,\n Antioch::EuckenThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real> >,\n Antioch::ConstantLewisDiffusivity<libMesh::Real> > >;\n\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::AntiochMixtureAveragedTransportMixture<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::BlottnerViscosity<libMesh::Real>,\n Antioch::EuckenThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real> >,\n Antioch::ConstantLewisDiffusivity<libMesh::Real> >,\n GRINS::AntiochMixtureAveragedTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::BlottnerViscosity<libMesh::Real>,\n Antioch::EuckenThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real> >,\n Antioch::ConstantLewisDiffusivity<libMesh::Real> > >;\n\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::AntiochMixtureAveragedTransportMixture<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::KineticsTheoryViscosity<libMesh::Real,Antioch::GSLSpliner>,\n Antioch::KineticsTheoryThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real>,libMesh::Real>,\n Antioch::MolecularBinaryDiffusion<libMesh::Real,Antioch::GSLSpliner> >,\n GRINS::AntiochMixtureAveragedTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::KineticsTheoryViscosity<libMesh::Real,Antioch::GSLSpliner>,\n Antioch::KineticsTheoryThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real>,libMesh::Real>,\n Antioch::MolecularBinaryDiffusion<libMesh::Real,Antioch::GSLSpliner> > >;\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::AntiochMixtureAveragedTransportMixture<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::SutherlandViscosity<libMesh::Real>,\n Antioch::EuckenThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real> >,\n Antioch::ConstantLewisDiffusivity<libMesh::Real> >,\n GRINS::AntiochMixtureAveragedTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::SutherlandViscosity<libMesh::Real>,\n Antioch::EuckenThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real> >,\n Antioch::ConstantLewisDiffusivity<libMesh::Real> > >;\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::AntiochMixtureAveragedTransportMixture<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::BlottnerViscosity<libMesh::Real>,\n Antioch::EuckenThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real> >,\n Antioch::ConstantLewisDiffusivity<libMesh::Real> >,\n GRINS::AntiochMixtureAveragedTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::BlottnerViscosity<libMesh::Real>,\n Antioch::EuckenThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real> >,\n Antioch::ConstantLewisDiffusivity<libMesh::Real> > >;\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::AntiochMixtureAveragedTransportMixture<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::KineticsTheoryViscosity<libMesh::Real,Antioch::GSLSpliner>,\n Antioch::KineticsTheoryThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real>,libMesh::Real>,\n Antioch::MolecularBinaryDiffusion<libMesh::Real,Antioch::GSLSpliner> >,\n GRINS::AntiochMixtureAveragedTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>,\n Antioch::KineticsTheoryViscosity<libMesh::Real,Antioch::GSLSpliner>,\n Antioch::KineticsTheoryThermalConductivity<Antioch::StatMechThermodynamics<libMesh::Real>,libMesh::Real>,\n Antioch::MolecularBinaryDiffusion<libMesh::Real,Antioch::GSLSpliner> > >;\n\n\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::AntiochConstantTransportMixture<GRINS::ConstantConductivity>,\n GRINS::AntiochConstantTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>, GRINS::ConstantConductivity> >;\n\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::AntiochConstantTransportMixture<GRINS::ConstantPrandtlConductivity>,\n GRINS::AntiochConstantTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>, GRINS::ConstantPrandtlConductivity> >;\n\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::AntiochConstantTransportMixture<GRINS::ConstantConductivity>,\n GRINS::AntiochConstantTransportEvaluator<Antioch::CEAEvaluator<libMesh::Real>, GRINS::ConstantConductivity> >;\n\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::AntiochConstantTransportMixture<GRINS::ConstantPrandtlConductivity>,\n GRINS::AntiochConstantTransportEvaluator<Antioch::CEAEvaluator<libMesh::Real>, GRINS::ConstantPrandtlConductivity> >;\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::AntiochConstantTransportMixture<GRINS::ConstantConductivity>,\n GRINS::AntiochConstantTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>, GRINS::ConstantConductivity> >;\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::AntiochConstantTransportMixture<GRINS::ConstantPrandtlConductivity>,\n GRINS::AntiochConstantTransportEvaluator<Antioch::StatMechThermodynamics<libMesh::Real>, GRINS::ConstantPrandtlConductivity> >;\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::AntiochConstantTransportMixture<GRINS::ConstantConductivity>,\n GRINS::AntiochConstantTransportEvaluator<Antioch::CEAEvaluator<libMesh::Real>, GRINS::ConstantConductivity> >;\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::AntiochConstantTransportMixture<GRINS::ConstantPrandtlConductivity>,\n GRINS::AntiochConstantTransportEvaluator<Antioch::CEAEvaluator<libMesh::Real>, GRINS::ConstantPrandtlConductivity> >;\n\n#endif \/\/GRINS_HAVE_ANTIOCH\n<commit_msg>Use instantiation macro<commit_after>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License 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. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n#include \"grins_config.h\"\n\n#include \"reacting_low_mach_navier_stokes_base.C\"\n#include \"reacting_low_mach_navier_stokes.C\"\n\n#ifdef GRINS_HAVE_CANTERA\n\n#include \"grins\/cantera_mixture.h\"\n#include \"grins\/cantera_evaluator.h\"\n\ntemplate class GRINS::ReactingLowMachNavierStokesBase<GRINS::CanteraMixture,GRINS::CanteraEvaluator>;\ntemplate class GRINS::ReactingLowMachNavierStokes<GRINS::CanteraMixture,GRINS::CanteraEvaluator>;\n\n#endif \/\/ GRINS_HAVE_CANTERA\n\n\n\n#ifdef GRINS_HAVE_ANTIOCH\n\n#include \"grins\/reacting_low_mach_navier_stokes_macro.h\"\n\nINSTANTIATE_REACTING_LOW_MACH_SUBCLASS(ReactingLowMachNavierStokesBase);\nINSTANTIATE_REACTING_LOW_MACH_SUBCLASS(ReactingLowMachNavierStokes);\n\n#endif \/\/GRINS_HAVE_ANTIOCH\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"subcomponentmanager.h\"\n#include \"metainfo.h\"\n\n#include <QDir>\n#include <QMetaType>\n#include <QUrl>\n#include <QDeclarativeEngine>\n#include <private\/qdeclarativemetatype_p.h>\n#include <QFileSystemWatcher>\n#include <private\/qdeclarativedom_p.h>\n\nenum { debug = false };\n\nQT_BEGIN_NAMESPACE\n\n\/\/ Allow usage of QFileInfo in hash \/ qSort\n\nstatic bool operator<(const QFileInfo &file1, const QFileInfo &file2)\n{\n return file1.filePath() < file2.filePath();\n}\n\nstatic uint qHash(const QFileInfo &fileInfo)\n{\n return qHash(fileInfo.filePath());\n}\n\nQT_END_NAMESPACE\n\nnamespace QmlDesigner {\n\nnamespace Internal {\n\nstatic const QString QMLFILEPATTERN = QString(QLatin1String(\"*.qml\"));\n\n\nclass SubComponentManagerPrivate : QObject {\n Q_OBJECT\npublic:\n SubComponentManagerPrivate(MetaInfo metaInfo, SubComponentManager *q);\n\n void addImport(int pos, const QDeclarativeDomImport &import);\n void removeImport(int pos);\n void parseDirectories();\n\npublic slots:\n void parseDirectory(const QString &dirPath);\n void parseFile(const QString &filePath);\n\npublic:\n QList<QFileInfo> watchedFiles(const QDir &dirInfo);\n void unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier);\n void registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier, const QDeclarativeDomDocument &document);\n\n SubComponentManager *m_q;\n\n MetaInfo m_metaInfo;\n QDeclarativeEngine m_engine;\n\n QFileSystemWatcher m_watcher;\n\n QMultiHash<QFileInfo,QString> m_dirToQualifier;\n\n QUrl m_filePath;\n\n QList<QDeclarativeDomImport> m_imports;\n};\n\nSubComponentManagerPrivate::SubComponentManagerPrivate(MetaInfo metaInfo, SubComponentManager *q) :\n m_q(q),\n m_metaInfo(metaInfo)\n{\n connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));\n connect(&m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(parseFile(QString)));\n}\n\nvoid SubComponentManagerPrivate::addImport(int pos, const QDeclarativeDomImport &import)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << pos << import.uri();\n\n if (import.type() == QDeclarativeDomImport::File) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());\n if (dirInfo.exists() && dirInfo.isDir()) {\n m_watcher.addPath(dirInfo.filePath());\n m_dirToQualifier.insertMulti(dirInfo, import.qualifier());\n }\n } else {\n \/\/ TODO: QDeclarativeDomImport::Library\n }\n\n m_imports.insert(pos, import);\n}\n\nvoid SubComponentManagerPrivate::removeImport(int pos)\n{\n const QDeclarativeDomImport import = m_imports.takeAt(pos);\n\n if (import.type() == QDeclarativeDomImport::File) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());\n\n m_dirToQualifier.remove(dirInfo, import.qualifier());\n\n if (!m_dirToQualifier.contains(dirInfo))\n m_watcher.removePath(dirInfo.filePath());\n\n foreach (const QFileInfo &monitoredFile, watchedFiles(dirInfo.filePath())) {\n if (!m_dirToQualifier.contains(dirInfo))\n m_watcher.removePath(monitoredFile.filePath());\n unregisterQmlFile(monitoredFile, import.qualifier());\n }\n } else {\n \/\/ TODO: QDeclarativeDomImport::Library\n }\n}\n\nvoid SubComponentManagerPrivate::parseDirectories()\n{\n if (!m_filePath.isEmpty()) {\n const QString file = m_filePath.toLocalFile();\n QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());\n if (dirInfo.exists() && dirInfo.isDir())\n parseDirectory(dirInfo.filePath());\n }\n\n foreach (const QDeclarativeDomImport &import, m_imports) {\n if (import.type() == QDeclarativeDomImport::File) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());\n if (dirInfo.exists() && dirInfo.isDir()) {\n parseDirectory(dirInfo.filePath());\n }\n }\n }\n}\n\nvoid SubComponentManagerPrivate::parseDirectory(const QString &dirPath)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << dirPath;\n\n QDir dir(dirPath);\n\n dir.setNameFilters(QStringList(QMLFILEPATTERN));\n dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);\n\n QList<QFileInfo> monitoredList = watchedFiles(dir);\n QList<QFileInfo> newList;\n foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {\n if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {\n \/\/ do not parse main file\n continue;\n }\n if (!qmlFile.fileName().at(0).isUpper()) {\n \/\/ Qml sub components must be upper case\n continue;\n }\n newList << qmlFile;\n }\n\n qSort(monitoredList);\n qSort(newList);\n\n if (debug)\n qDebug() << \"monitored list \" << monitoredList.size() << \"new list \" << newList.size();\n QList<QFileInfo>::const_iterator oldIter = monitoredList.constBegin();\n QList<QFileInfo>::const_iterator newIter = newList.constBegin();\n\n while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {\n const QFileInfo oldFileInfo = *oldIter;\n const QFileInfo newFileInfo = *newIter;\n if (oldFileInfo == newFileInfo) {\n ++oldIter;\n ++newIter;\n continue;\n }\n if (oldFileInfo < newFileInfo) {\n foreach (const QString &qualifier, m_dirToQualifier.value(dirPath))\n unregisterQmlFile(oldFileInfo, qualifier);\n m_watcher.removePath(oldFileInfo.filePath());\n ++oldIter;\n continue;\n }\n \/\/ oldFileInfo > newFileInfo\n parseFile(newFileInfo.filePath());\n m_watcher.addPath(oldFileInfo.filePath());\n ++newIter;\n }\n\n while (oldIter != monitoredList.constEnd()) {\n foreach (const QString &qualifier, m_dirToQualifier.value(dirPath))\n unregisterQmlFile(*oldIter, qualifier);\n m_watcher.removePath(oldIter->filePath());\n ++oldIter;\n }\n\n while (newIter != newList.constEnd()) {\n parseFile(newIter->filePath());\n if (debug)\n qDebug() << \"m_watcher.addPath(\" << newIter->filePath() << ')';\n m_watcher.addPath(newIter->filePath());\n ++newIter;\n }\n}\n\nvoid SubComponentManagerPrivate::parseFile(const QString &filePath)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << filePath;\n\n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QDeclarativeDomDocument document;\n if (!document.load(&m_engine, file.readAll(), QUrl::fromLocalFile(filePath))) {\n \/\/ TODO: Put the errors somewhere?\n qWarning() << \"Could not load qml file \" << filePath;\n return;\n }\n\n QFileInfo dir = QFileInfo(filePath).absolutePath();\n foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {\n registerQmlFile(filePath, qualifier, document);\n }\n}\n\nQList<QFileInfo> SubComponentManagerPrivate::watchedFiles(const QDir &dirInfo)\n{\n QList<QFileInfo> files;\n\n const QString dirPath = dirInfo.absolutePath();\n foreach (const QString &monitoredFile, m_watcher.files()) {\n QFileInfo fileInfo(monitoredFile);\n if (fileInfo.dir().absolutePath() == dirPath) {\n files.append(fileInfo);\n }\n }\n return files;\n}\n\nvoid SubComponentManagerPrivate::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)\n{\n QString componentName = fileInfo.baseName();\n if (!qualifier.isEmpty())\n componentName = qualifier + '\/' + componentName;\n\n if (m_metaInfo.hasNodeMetaInfo(componentName)) {\n NodeMetaInfo nodeInfo = m_metaInfo.nodeMetaInfo(componentName);\n m_metaInfo.removeNodeInfo(nodeInfo);\n }\n}\n\nvoid SubComponentManagerPrivate::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier, const QDeclarativeDomDocument &document)\n{\n QString componentName = fileInfo.baseName();\n if (!qualifier.isEmpty())\n componentName = qualifier + '\/' + componentName;\n\n if (debug)\n qDebug() << \"SubComponentManager\" << __FUNCTION__ << componentName;\n\n if (m_metaInfo.hasNodeMetaInfo(componentName)) {\n NodeMetaInfo nodeInfo = m_metaInfo.nodeMetaInfo(componentName);\n m_metaInfo.removeNodeInfo(nodeInfo);\n }\n\n const QDeclarativeDomObject rootObject = document.rootObject();\n\n const QString baseType = document.rootObject().objectType();\n Q_ASSERT_X(!baseType.isEmpty(), Q_FUNC_INFO, \"Type of root object cannot be empty\");\n\n NodeMetaInfo nodeInfo(m_metaInfo);\n nodeInfo.setTypeName(componentName);\n nodeInfo.setQmlFile(fileInfo.filePath());\n\n \/\/ Add file components to the library\n nodeInfo.setCategory(tr(\"Qml Component\"));\n nodeInfo.setIsVisibleToItemLibrary(true);\n\n m_metaInfo.addItemLibraryInfo(nodeInfo, componentName);\n m_metaInfo.addNodeInfo(nodeInfo, baseType);\n\n foreach (const QDeclarativeDomDynamicProperty &dynamicProperty, document.rootObject().dynamicProperties()) {\n Q_ASSERT(!dynamicProperty.propertyName().isEmpty());\n Q_ASSERT(!dynamicProperty.propertyTypeName().isEmpty());\n\n PropertyMetaInfo propertyMetaInfo;\n propertyMetaInfo.setName(dynamicProperty.propertyName());\n propertyMetaInfo.setType(dynamicProperty.propertyTypeName());\n propertyMetaInfo.setValid(true);\n propertyMetaInfo.setReadable(true);\n propertyMetaInfo.setWritable(true);\n\n QDeclarativeDomProperty defaultValue = dynamicProperty.defaultValue();\n if (defaultValue.value().isLiteral()) {\n QVariant defaultValueVariant(defaultValue.value().toLiteral().literal());\n defaultValueVariant.convert((QVariant::Type) dynamicProperty.propertyType());\n propertyMetaInfo.setDefaultValue(nodeInfo, defaultValueVariant);\n }\n\n nodeInfo.addProperty(propertyMetaInfo);\n }\n}\n\n} \/\/ namespace Internal\n\n\/*!\n \\class SubComponentManager\n\n Detects & monitors (potential) component files in a list of directories, and registers\n these in the metatype system.\n*\/\n\nSubComponentManager::SubComponentManager(MetaInfo metaInfo, QObject *parent) :\n QObject(parent),\n m_d(new Internal::SubComponentManagerPrivate(metaInfo, this))\n{\n}\n\nSubComponentManager::~SubComponentManager()\n{\n delete m_d;\n}\n\nQStringList SubComponentManager::directories() const\n{\n return m_d->m_watcher.directories();\n}\n\nQStringList SubComponentManager::qmlFiles() const\n{\n return m_d->m_watcher.files();\n}\n\nstatic bool importEqual(const QDeclarativeDomImport &import1, const QDeclarativeDomImport &import2)\n{\n return import1.type() == import2.type()\n && import1.uri() == import2.uri()\n && import1.version() == import2.version()\n && import1.qualifier() == import2.qualifier();\n}\n\nvoid SubComponentManager::update(const QUrl &filePath, const QByteArray &data)\n{\n QDeclarativeEngine engine;\n QDeclarativeDomDocument document;\n\n QList<QDeclarativeDomImport> imports;\n if (document.load(&engine, data, filePath))\n imports = document.imports();\n\n update(filePath, imports);\n}\n\nvoid SubComponentManager::update(const QUrl &filePath, const QList<QDeclarativeDomImport> &imports)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << filePath << imports.size();\n\n QFileInfo oldDir, newDir;\n\n if (!m_d->m_filePath.isEmpty()) {\n const QString file = m_d->m_filePath.toLocalFile();\n oldDir = QFileInfo(QFileInfo(file).path());\n }\n if (!filePath.isEmpty()) {\n const QString file = filePath.toLocalFile();\n newDir = QFileInfo(QFileInfo(file).path());\n }\n\n m_d->m_filePath = filePath;\n\n \/\/\n \/\/ (implicit) import of local directory\n \/\/\n if (oldDir != newDir) {\n if (!oldDir.filePath().isEmpty()) {\n m_d->m_dirToQualifier.remove(oldDir, QString());\n if (!m_d->m_dirToQualifier.contains(oldDir))\n m_d->m_watcher.removePath(oldDir.filePath());\n }\n\n if (!newDir.filePath().isEmpty()) {\n m_d->m_watcher.addPath(newDir.filePath());\n m_d->m_dirToQualifier.insertMulti(newDir, QString());\n }\n }\n\n \/\/\n \/\/ Imports\n \/\/\n\n \/\/ skip first list items until the lists differ\n int i = 0;\n while (i < qMin(imports.size(), m_d->m_imports.size())) {\n if (!importEqual(imports.at(i), m_d->m_imports.at(i)))\n break;\n ++i;\n }\n\n for (int ii = m_d->m_imports.size() - 1; ii >= i; --ii)\n m_d->removeImport(ii);\n\n for (int ii = i; ii < imports.size(); ++ii) {\n m_d->addImport(ii, imports.at(ii));\n }\n\n m_d->parseDirectories();\n}\n\n} \/\/ namespace QmlDesigner\n\n#include \"subcomponentmanager.moc\"\n<commit_msg>QmlDesigner.MetaInfo: renamed subcomponents group<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"subcomponentmanager.h\"\n#include \"metainfo.h\"\n\n#include <QDir>\n#include <QMetaType>\n#include <QUrl>\n#include <QDeclarativeEngine>\n#include <private\/qdeclarativemetatype_p.h>\n#include <QFileSystemWatcher>\n#include <private\/qdeclarativedom_p.h>\n\nenum { debug = false };\n\nQT_BEGIN_NAMESPACE\n\n\/\/ Allow usage of QFileInfo in hash \/ qSort\n\nstatic bool operator<(const QFileInfo &file1, const QFileInfo &file2)\n{\n return file1.filePath() < file2.filePath();\n}\n\nstatic uint qHash(const QFileInfo &fileInfo)\n{\n return qHash(fileInfo.filePath());\n}\n\nQT_END_NAMESPACE\n\nnamespace QmlDesigner {\n\nnamespace Internal {\n\nstatic const QString QMLFILEPATTERN = QString(QLatin1String(\"*.qml\"));\n\n\nclass SubComponentManagerPrivate : QObject {\n Q_OBJECT\npublic:\n SubComponentManagerPrivate(MetaInfo metaInfo, SubComponentManager *q);\n\n void addImport(int pos, const QDeclarativeDomImport &import);\n void removeImport(int pos);\n void parseDirectories();\n\npublic slots:\n void parseDirectory(const QString &dirPath);\n void parseFile(const QString &filePath);\n\npublic:\n QList<QFileInfo> watchedFiles(const QDir &dirInfo);\n void unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier);\n void registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier, const QDeclarativeDomDocument &document);\n\n SubComponentManager *m_q;\n\n MetaInfo m_metaInfo;\n QDeclarativeEngine m_engine;\n\n QFileSystemWatcher m_watcher;\n\n QMultiHash<QFileInfo,QString> m_dirToQualifier;\n\n QUrl m_filePath;\n\n QList<QDeclarativeDomImport> m_imports;\n};\n\nSubComponentManagerPrivate::SubComponentManagerPrivate(MetaInfo metaInfo, SubComponentManager *q) :\n m_q(q),\n m_metaInfo(metaInfo)\n{\n connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));\n connect(&m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(parseFile(QString)));\n}\n\nvoid SubComponentManagerPrivate::addImport(int pos, const QDeclarativeDomImport &import)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << pos << import.uri();\n\n if (import.type() == QDeclarativeDomImport::File) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());\n if (dirInfo.exists() && dirInfo.isDir()) {\n m_watcher.addPath(dirInfo.filePath());\n m_dirToQualifier.insertMulti(dirInfo, import.qualifier());\n }\n } else {\n \/\/ TODO: QDeclarativeDomImport::Library\n }\n\n m_imports.insert(pos, import);\n}\n\nvoid SubComponentManagerPrivate::removeImport(int pos)\n{\n const QDeclarativeDomImport import = m_imports.takeAt(pos);\n\n if (import.type() == QDeclarativeDomImport::File) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());\n\n m_dirToQualifier.remove(dirInfo, import.qualifier());\n\n if (!m_dirToQualifier.contains(dirInfo))\n m_watcher.removePath(dirInfo.filePath());\n\n foreach (const QFileInfo &monitoredFile, watchedFiles(dirInfo.filePath())) {\n if (!m_dirToQualifier.contains(dirInfo))\n m_watcher.removePath(monitoredFile.filePath());\n unregisterQmlFile(monitoredFile, import.qualifier());\n }\n } else {\n \/\/ TODO: QDeclarativeDomImport::Library\n }\n}\n\nvoid SubComponentManagerPrivate::parseDirectories()\n{\n if (!m_filePath.isEmpty()) {\n const QString file = m_filePath.toLocalFile();\n QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());\n if (dirInfo.exists() && dirInfo.isDir())\n parseDirectory(dirInfo.filePath());\n }\n\n foreach (const QDeclarativeDomImport &import, m_imports) {\n if (import.type() == QDeclarativeDomImport::File) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());\n if (dirInfo.exists() && dirInfo.isDir()) {\n parseDirectory(dirInfo.filePath());\n }\n }\n }\n}\n\nvoid SubComponentManagerPrivate::parseDirectory(const QString &dirPath)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << dirPath;\n\n QDir dir(dirPath);\n\n dir.setNameFilters(QStringList(QMLFILEPATTERN));\n dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);\n\n QList<QFileInfo> monitoredList = watchedFiles(dir);\n QList<QFileInfo> newList;\n foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {\n if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {\n \/\/ do not parse main file\n continue;\n }\n if (!qmlFile.fileName().at(0).isUpper()) {\n \/\/ Qml sub components must be upper case\n continue;\n }\n newList << qmlFile;\n }\n\n qSort(monitoredList);\n qSort(newList);\n\n if (debug)\n qDebug() << \"monitored list \" << monitoredList.size() << \"new list \" << newList.size();\n QList<QFileInfo>::const_iterator oldIter = monitoredList.constBegin();\n QList<QFileInfo>::const_iterator newIter = newList.constBegin();\n\n while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {\n const QFileInfo oldFileInfo = *oldIter;\n const QFileInfo newFileInfo = *newIter;\n if (oldFileInfo == newFileInfo) {\n ++oldIter;\n ++newIter;\n continue;\n }\n if (oldFileInfo < newFileInfo) {\n foreach (const QString &qualifier, m_dirToQualifier.value(dirPath))\n unregisterQmlFile(oldFileInfo, qualifier);\n m_watcher.removePath(oldFileInfo.filePath());\n ++oldIter;\n continue;\n }\n \/\/ oldFileInfo > newFileInfo\n parseFile(newFileInfo.filePath());\n m_watcher.addPath(oldFileInfo.filePath());\n ++newIter;\n }\n\n while (oldIter != monitoredList.constEnd()) {\n foreach (const QString &qualifier, m_dirToQualifier.value(dirPath))\n unregisterQmlFile(*oldIter, qualifier);\n m_watcher.removePath(oldIter->filePath());\n ++oldIter;\n }\n\n while (newIter != newList.constEnd()) {\n parseFile(newIter->filePath());\n if (debug)\n qDebug() << \"m_watcher.addPath(\" << newIter->filePath() << ')';\n m_watcher.addPath(newIter->filePath());\n ++newIter;\n }\n}\n\nvoid SubComponentManagerPrivate::parseFile(const QString &filePath)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << filePath;\n\n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QDeclarativeDomDocument document;\n if (!document.load(&m_engine, file.readAll(), QUrl::fromLocalFile(filePath))) {\n \/\/ TODO: Put the errors somewhere?\n qWarning() << \"Could not load qml file \" << filePath;\n return;\n }\n\n QFileInfo dir = QFileInfo(filePath).absolutePath();\n foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {\n registerQmlFile(filePath, qualifier, document);\n }\n}\n\nQList<QFileInfo> SubComponentManagerPrivate::watchedFiles(const QDir &dirInfo)\n{\n QList<QFileInfo> files;\n\n const QString dirPath = dirInfo.absolutePath();\n foreach (const QString &monitoredFile, m_watcher.files()) {\n QFileInfo fileInfo(monitoredFile);\n if (fileInfo.dir().absolutePath() == dirPath) {\n files.append(fileInfo);\n }\n }\n return files;\n}\n\nvoid SubComponentManagerPrivate::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)\n{\n QString componentName = fileInfo.baseName();\n if (!qualifier.isEmpty())\n componentName = qualifier + '\/' + componentName;\n\n if (m_metaInfo.hasNodeMetaInfo(componentName)) {\n NodeMetaInfo nodeInfo = m_metaInfo.nodeMetaInfo(componentName);\n m_metaInfo.removeNodeInfo(nodeInfo);\n }\n}\n\nvoid SubComponentManagerPrivate::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier, const QDeclarativeDomDocument &document)\n{\n QString componentName = fileInfo.baseName();\n if (!qualifier.isEmpty())\n componentName = qualifier + '\/' + componentName;\n\n if (debug)\n qDebug() << \"SubComponentManager\" << __FUNCTION__ << componentName;\n\n if (m_metaInfo.hasNodeMetaInfo(componentName)) {\n NodeMetaInfo nodeInfo = m_metaInfo.nodeMetaInfo(componentName);\n m_metaInfo.removeNodeInfo(nodeInfo);\n }\n\n const QDeclarativeDomObject rootObject = document.rootObject();\n\n const QString baseType = document.rootObject().objectType();\n Q_ASSERT_X(!baseType.isEmpty(), Q_FUNC_INFO, \"Type of root object cannot be empty\");\n\n NodeMetaInfo nodeInfo(m_metaInfo);\n nodeInfo.setTypeName(componentName);\n nodeInfo.setQmlFile(fileInfo.filePath());\n\n \/\/ Add file components to the library\n nodeInfo.setCategory(tr(\"Qml Components\"));\n nodeInfo.setIsVisibleToItemLibrary(true);\n\n m_metaInfo.addItemLibraryInfo(nodeInfo, componentName);\n m_metaInfo.addNodeInfo(nodeInfo, baseType);\n\n foreach (const QDeclarativeDomDynamicProperty &dynamicProperty, document.rootObject().dynamicProperties()) {\n Q_ASSERT(!dynamicProperty.propertyName().isEmpty());\n Q_ASSERT(!dynamicProperty.propertyTypeName().isEmpty());\n\n PropertyMetaInfo propertyMetaInfo;\n propertyMetaInfo.setName(dynamicProperty.propertyName());\n propertyMetaInfo.setType(dynamicProperty.propertyTypeName());\n propertyMetaInfo.setValid(true);\n propertyMetaInfo.setReadable(true);\n propertyMetaInfo.setWritable(true);\n\n QDeclarativeDomProperty defaultValue = dynamicProperty.defaultValue();\n if (defaultValue.value().isLiteral()) {\n QVariant defaultValueVariant(defaultValue.value().toLiteral().literal());\n defaultValueVariant.convert((QVariant::Type) dynamicProperty.propertyType());\n propertyMetaInfo.setDefaultValue(nodeInfo, defaultValueVariant);\n }\n\n nodeInfo.addProperty(propertyMetaInfo);\n }\n}\n\n} \/\/ namespace Internal\n\n\/*!\n \\class SubComponentManager\n\n Detects & monitors (potential) component files in a list of directories, and registers\n these in the metatype system.\n*\/\n\nSubComponentManager::SubComponentManager(MetaInfo metaInfo, QObject *parent) :\n QObject(parent),\n m_d(new Internal::SubComponentManagerPrivate(metaInfo, this))\n{\n}\n\nSubComponentManager::~SubComponentManager()\n{\n delete m_d;\n}\n\nQStringList SubComponentManager::directories() const\n{\n return m_d->m_watcher.directories();\n}\n\nQStringList SubComponentManager::qmlFiles() const\n{\n return m_d->m_watcher.files();\n}\n\nstatic bool importEqual(const QDeclarativeDomImport &import1, const QDeclarativeDomImport &import2)\n{\n return import1.type() == import2.type()\n && import1.uri() == import2.uri()\n && import1.version() == import2.version()\n && import1.qualifier() == import2.qualifier();\n}\n\nvoid SubComponentManager::update(const QUrl &filePath, const QByteArray &data)\n{\n QDeclarativeEngine engine;\n QDeclarativeDomDocument document;\n\n QList<QDeclarativeDomImport> imports;\n if (document.load(&engine, data, filePath))\n imports = document.imports();\n\n update(filePath, imports);\n}\n\nvoid SubComponentManager::update(const QUrl &filePath, const QList<QDeclarativeDomImport> &imports)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << filePath << imports.size();\n\n QFileInfo oldDir, newDir;\n\n if (!m_d->m_filePath.isEmpty()) {\n const QString file = m_d->m_filePath.toLocalFile();\n oldDir = QFileInfo(QFileInfo(file).path());\n }\n if (!filePath.isEmpty()) {\n const QString file = filePath.toLocalFile();\n newDir = QFileInfo(QFileInfo(file).path());\n }\n\n m_d->m_filePath = filePath;\n\n \/\/\n \/\/ (implicit) import of local directory\n \/\/\n if (oldDir != newDir) {\n if (!oldDir.filePath().isEmpty()) {\n m_d->m_dirToQualifier.remove(oldDir, QString());\n if (!m_d->m_dirToQualifier.contains(oldDir))\n m_d->m_watcher.removePath(oldDir.filePath());\n }\n\n if (!newDir.filePath().isEmpty()) {\n m_d->m_watcher.addPath(newDir.filePath());\n m_d->m_dirToQualifier.insertMulti(newDir, QString());\n }\n }\n\n \/\/\n \/\/ Imports\n \/\/\n\n \/\/ skip first list items until the lists differ\n int i = 0;\n while (i < qMin(imports.size(), m_d->m_imports.size())) {\n if (!importEqual(imports.at(i), m_d->m_imports.at(i)))\n break;\n ++i;\n }\n\n for (int ii = m_d->m_imports.size() - 1; ii >= i; --ii)\n m_d->removeImport(ii);\n\n for (int ii = i; ii < imports.size(); ++ii) {\n m_d->addImport(ii, imports.at(ii));\n }\n\n m_d->parseDirectories();\n}\n\n} \/\/ namespace QmlDesigner\n\n#include \"subcomponentmanager.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ ROS Libraries\n#include <ros\/ros.h>\n#include <sensor_msgs\/Joy.h>\n#include <geometry_msgs\/Twist.h>\n\/\/ Standard Libraries\n#include <stdlib.h>\n#include <math.h>\n\nfloat linear_x_button=0;\nfloat angular_z_button=0;\nfloat linear_x_stick=0;\nfloat angular_z_stick=0;\n\n\/\/ Defines\n#define Joystick_Stick_Left_Right msg->axes[4]\n#define Joystick_Stick_Up_Down msg->axes[5]\n#define Joystick_Button_Left_Right msg->axes[0]\n#define Joystick_Button_Up_Down msg->axes[1]\n\n\/\/ Callback Functions\nvoid Joy_Callback (const sensor_msgs::Joy::ConstPtr& msg)\n{\n\/\/ for (unsigned i = 0; i < msg->axes.size(); ++i) {\n\/\/ ROS_INFO(\"Axis %d is now at position %f\", i, msg->axes[i]);\n\/\/ }\n\n \/\/ Test if joystick buttons are pressed?\n if (Joystick_Button_Left_Right>0) {\n angular_z_button=Joystick_Button_Left_Right;\n }\n if (Joystick_Button_Left_Right<0) {\n angular_z_button=Joystick_Button_Left_Right;\n }\n if (Joystick_Button_Up_Down>0) {\n linear_x_button=Joystick_Button_Up_Down\/5;\n }\n if (Joystick_Button_Up_Down<0) {\n linear_x_button=Joystick_Button_Up_Down\/5;\n }\n if (Joystick_Button_Up_Down==0) {\n linear_x_button=Joystick_Button_Up_Down;\n }\n if (Joystick_Button_Left_Right==0) {\n angular_z_button=Joystick_Button_Left_Right;\n }\n\n \/\/ Test if joystick stick is pressed?\n if (Joystick_Stick_Left_Right>0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n }\n if (Joystick_Stick_Left_Right<0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n }\n if (Joystick_Stick_Up_Down>0) {\n linear_x_stick=Joystick_Stick_Up_Down\/5;\n }\n if (Joystick_Stick_Up_Down<0) {\n linear_x_stick=Joystick_Stick_Up_Down\/5;\n }\n if (Joystick_Stick_Up_Down==0) {\n linear_x_stick=Joystick_Stick_Up_Down;\n }\n if (Joystick_Stick_Left_Right==0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n }\n\n\n}\n\nvoid onExit( void )\n{\n \/\/ Run cleanup code here!\n ROS_INFO(\"joystick_teleop: Exit node\");\n}\n\nint main(int argc, char **argv)\n{\n atexit(onExit);\n ros::init(argc, argv, \"joystick_teleop\");\n ros::NodeHandle n;\n ros::Subscriber sub = n.subscribe(\"joy\", 100, Joy_Callback);\n ros::Publisher cmd_vel_pub = n.advertise<geometry_msgs::Twist>(\"\/cmd_vel\", 1);\n ros::Rate loop_rate(20); \/\/Sets the loop to publish at a rate of 10Hz\n geometry_msgs::Twist cmd_vel_msg; \/\/Declares the message to be sent\n while (n.ok()){ \n\n if ((cmd_vel_msg.linear.x != linear_x_button) || (cmd_vel_msg.angular.z != angular_z_button)){\n cmd_vel_msg.linear.x=linear_x_button;\n cmd_vel_msg.angular.z=angular_z_button;\n cmd_vel_pub.publish(cmd_vel_msg);\n ROS_INFO(\"linear.x = %f angular.z = %f\",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);\n }\n if ((cmd_vel_msg.linear.x != linear_x_stick) || (cmd_vel_msg.angular.z != angular_z_stick)){\n cmd_vel_msg.linear.x=linear_x_stick;\n cmd_vel_msg.angular.z=angular_z_stick;\n cmd_vel_pub.publish(cmd_vel_msg);\n ROS_INFO(\"linear.x = %f angular.z = %f\",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);\n }\n\n ros::spinOnce();\n loop_rate.sleep();\n }\/\/end.mainloop\n return 0;\n}\/\/end.main\n\n<commit_msg>UPDATE joystick_teleop_node.cpp: Node is now continously sending cmd_vel messages if button or stick is pressed<commit_after>\/\/ ROS Libraries\n#include <ros\/ros.h>\n#include <sensor_msgs\/Joy.h>\n#include <geometry_msgs\/Twist.h>\n\/\/ Standard Libraries\n#include <stdlib.h>\n#include <math.h>\n\nfloat linear_x_button=0;\nfloat angular_z_button=0;\nfloat linear_x_stick=0;\nfloat angular_z_stick=0;\n\nbool stick_used=false;\nbool button_used=false;\n\n\/\/ Defines\n#define Joystick_Stick_Left_Right msg->axes[4]\n#define Joystick_Stick_Up_Down msg->axes[5]\n#define Joystick_Button_Left_Right msg->axes[0]\n#define Joystick_Button_Up_Down msg->axes[1]\n\n\/\/ Callback Functions\nvoid Joy_Callback (const sensor_msgs::Joy::ConstPtr& msg)\n{\n\/\/ for (unsigned i = 0; i < msg->axes.size(); ++i) {\n\/\/ ROS_INFO(\"Axis %d is now at position %f\", i, msg->axes[i]);\n\/\/ }\n\n \/\/ Test if joystick buttons are pressed?\n if (Joystick_Button_Left_Right>0) {\n angular_z_button=Joystick_Button_Left_Right;\n button_used = true;\n }\n if (Joystick_Button_Left_Right<0) {\n angular_z_button=Joystick_Button_Left_Right;\n button_used = true;\n }\n if (Joystick_Button_Up_Down>0) {\n linear_x_button=Joystick_Button_Up_Down\/5;\n button_used = true;\n }\n if (Joystick_Button_Up_Down<0) {\n linear_x_button=Joystick_Button_Up_Down\/5;\n button_used = true;\n }\n if (Joystick_Button_Up_Down==0) {\n linear_x_button=Joystick_Button_Up_Down;\n button_used = true;\n }\n if (Joystick_Button_Left_Right==0) {\n angular_z_button=Joystick_Button_Left_Right;\n button_used = true;\n }\n if ((Joystick_Button_Left_Right==0) && (Joystick_Button_Up_Down==0))\n {\n button_used=false;\n }\n\n \/\/ Test if joystick stick is pressed?\n if (Joystick_Stick_Left_Right>0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n stick_used = true;\n }\n if (Joystick_Stick_Left_Right<0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n stick_used = true;\n }\n if (Joystick_Stick_Up_Down>0) {\n linear_x_stick=Joystick_Stick_Up_Down\/5;\n stick_used = true;\n }\n if (Joystick_Stick_Up_Down<0) {\n linear_x_stick=Joystick_Stick_Up_Down\/5;\n stick_used = true;\n }\n if (Joystick_Stick_Up_Down==0) {\n linear_x_stick=Joystick_Stick_Up_Down;\n stick_used = true;\n }\n if (Joystick_Stick_Left_Right==0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n stick_used = true;\n }\n if ((Joystick_Stick_Left_Right==0) && (Joystick_Stick_Up_Down==0))\n {\n stick_used=false;\n }\n\n\n}\n\nvoid onExit( void )\n{\n \/\/ Run cleanup code here!\n ROS_INFO(\"joystick_teleop: Exit node\");\n}\n\nint main(int argc, char **argv)\n{\n atexit(onExit);\n ros::init(argc, argv, \"joystick_teleop\");\n ros::NodeHandle n;\n ros::Subscriber sub = n.subscribe(\"joy\", 100, Joy_Callback);\n ros::Publisher cmd_vel_pub = n.advertise<geometry_msgs::Twist>(\"\/cmd_vel\", 1);\n ros::Rate loop_rate(20); \/\/Sets the loop to publish at a rate of 10Hz\n geometry_msgs::Twist cmd_vel_msg; \/\/Declares the message to be sent\n bool publish_cmd_vel=false;\n\n while (ros::ok()){\n\n if (button_used==true && stick_used==false){\n cmd_vel_msg.linear.x=linear_x_button;\n cmd_vel_msg.angular.z=angular_z_button;\n cmd_vel_pub.publish(cmd_vel_msg);\n ROS_INFO(\"linear.x = %f angular.z = %f\",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);\n publish_cmd_vel = true;\n }\n if (stick_used==true && button_used==false){\n cmd_vel_msg.linear.x=linear_x_stick;\n cmd_vel_msg.angular.z=angular_z_stick;\n cmd_vel_pub.publish(cmd_vel_msg);\n ROS_INFO(\"linear.x = %f angular.z = %f\",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);\n publish_cmd_vel = true;\n }\n \/\/ If nor button or stick is pressed, send null-message to cmd_vel once\n if ((stick_used==false && button_used==false) && publish_cmd_vel==true){\n cmd_vel_msg.linear.x=0;\n cmd_vel_msg.angular.z =0;\n cmd_vel_pub.publish(cmd_vel_msg);\n ROS_INFO(\"linear.x = %f angular.z = %f\",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);\n publish_cmd_vel = false;\n }\n\n ros::spinOnce();\n loop_rate.sleep();\n }\/\/end.mainloop\n return 0;\n}\/\/end.main\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_MATRIX\n#define MFEM_MATRIX\n\n#include \"..\/general\/array.hpp\"\n#include \"..\/general\/globals.hpp\"\n#include \"operator.hpp\"\n\nnamespace mfem\n{\n\n\/\/ Abstract data types matrix, inverse matrix\n\nclass MatrixInverse;\n\n\/\/\/ Abstract data type matrix\nclass Matrix : public Operator\n{\n friend class MatrixInverse;\npublic:\n \/\/\/\/ Defines matrix diagonal policy upon elimination of rows and\/or columns.\n enum DiagonalPolicy\n {\n DIAG_ZERO, \/\/\/< Set the diagonal value to zero\n DIAG_ONE, \/\/\/< Set the diagonal value to one\n DIAG_KEEP \/\/\/< Keep the diagonal value\n };\n\n \/\/\/ Creates a square matrix of size s.\n explicit Matrix(int s) : Operator(s) { }\n\n \/\/\/ Creates a matrix of the given height and width.\n explicit Matrix(int h, int w) : Operator(h, w) { }\n\n \/\/\/ Returns whether this matrix instanse is a square matrix.\n bool IsSquare() const { return (height==width); };\n\n \/\/\/ Returns reference to a_{ij}.\n virtual double &Elem(int i, int j) = 0;\n\n \/\/\/ Returns constant reference to a_{ij}.\n virtual const double &Elem(int i, int j) const = 0;\n\n \/\/\/ Returns a pointer to (an approximation) of the matrix inverse.\n virtual MatrixInverse *Inverse() const = 0;\n\n \/\/\/ Finalizes the matrix initialization.\n virtual void Finalize(int) { }\n\n \/\/\/ Prints matrix to stream out.\n virtual void Print (std::ostream & out = mfem::out, int width_ = 4) const;\n\n \/\/\/ Destroys matrix.\n virtual ~Matrix() { }\n};\n\n\n\/\/\/ Abstract data type for matrix inverse\nclass MatrixInverse : public Solver\n{\npublic:\n MatrixInverse() { }\n\n \/\/\/ Creates approximation of the inverse of square matrix\n MatrixInverse(const Matrix &mat)\n : Solver(mat.height, mat.width) { }\n};\n\n\/\/\/ Abstract data type for sparse matrices\nclass AbstractSparseMatrix : public Matrix\n{\npublic:\n \/\/\/ Creates a square matrix of the given size.\n explicit AbstractSparseMatrix(int s = 0) : Matrix(s) { }\n\n \/\/\/ Creates a matrix of the given height and width.\n explicit AbstractSparseMatrix(int h, int w) : Matrix(h, w) { }\n\n \/\/\/ Returns the number of non-zeros in a matrix\n virtual int NumNonZeroElems() const = 0;\n\n \/\/\/ Gets the columns indexes and values for row *row*.\n \/** Returns:\n - 0 if @a cols and @a srow are copies of the values in the matrix.\n - 1 if @a cols and @a srow are views of the values in the matrix. *\/\n virtual int GetRow(const int row, Array<int> &cols, Vector &srow) const = 0;\n\n \/** @brief If the matrix is square, this method will place 1 on the diagonal\n (i,i) if row i has \"almost\" zero l1-norm.\n\n If entry (i,i) does not belong to the sparsity pattern of A, then an\n error will occur. *\/\n virtual void EliminateZeroRows(const double threshold = 1e-12) = 0;\n\n \/\/\/ Matrix-Vector Multiplication y = A*x\n virtual void Mult(const Vector &x, Vector &y) const = 0;\n \/\/\/ Matrix-Vector Multiplication y = y + val*A*x\n virtual void AddMult(const Vector &x, Vector &y,\n const double val = 1.) const = 0;\n \/\/\/ MatrixTranspose-Vector Multiplication y = A'*x\n virtual void MultTranspose(const Vector &x, Vector &y) const = 0;\n \/\/\/ MatrixTranspose-Vector Multiplication y = y + val*A'*x\n virtual void AddMultTranspose(const Vector &x, Vector &y,\n const double val = 1.) const = 0;\n\n \/\/\/ Destroys AbstractSparseMatrix.\n virtual ~AbstractSparseMatrix() { }\n};\n\n}\n\n#endif\n<commit_msg>DOC: fix typo in doxygen documentation<commit_after>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_MATRIX\n#define MFEM_MATRIX\n\n#include \"..\/general\/array.hpp\"\n#include \"..\/general\/globals.hpp\"\n#include \"operator.hpp\"\n\nnamespace mfem\n{\n\n\/\/ Abstract data types matrix, inverse matrix\n\nclass MatrixInverse;\n\n\/\/\/ Abstract data type matrix\nclass Matrix : public Operator\n{\n friend class MatrixInverse;\npublic:\n \/\/\/\/ Defines matrix diagonal policy upon elimination of rows and\/or columns.\n enum DiagonalPolicy\n {\n DIAG_ZERO, \/\/\/< Set the diagonal value to zero\n DIAG_ONE, \/\/\/< Set the diagonal value to one\n DIAG_KEEP \/\/\/< Keep the diagonal value\n };\n\n \/\/\/ Creates a square matrix of size s.\n explicit Matrix(int s) : Operator(s) { }\n\n \/\/\/ Creates a matrix of the given height and width.\n explicit Matrix(int h, int w) : Operator(h, w) { }\n\n \/\/\/ Returns whether this matrix instance is a square matrix.\n bool IsSquare() const { return (height==width); };\n\n \/\/\/ Returns reference to a_{ij}.\n virtual double &Elem(int i, int j) = 0;\n\n \/\/\/ Returns constant reference to a_{ij}.\n virtual const double &Elem(int i, int j) const = 0;\n\n \/\/\/ Returns a pointer to (an approximation) of the matrix inverse.\n virtual MatrixInverse *Inverse() const = 0;\n\n \/\/\/ Finalizes the matrix initialization.\n virtual void Finalize(int) { }\n\n \/\/\/ Prints matrix to stream out.\n virtual void Print (std::ostream & out = mfem::out, int width_ = 4) const;\n\n \/\/\/ Destroys matrix.\n virtual ~Matrix() { }\n};\n\n\n\/\/\/ Abstract data type for matrix inverse\nclass MatrixInverse : public Solver\n{\npublic:\n MatrixInverse() { }\n\n \/\/\/ Creates approximation of the inverse of square matrix\n MatrixInverse(const Matrix &mat)\n : Solver(mat.height, mat.width) { }\n};\n\n\/\/\/ Abstract data type for sparse matrices\nclass AbstractSparseMatrix : public Matrix\n{\npublic:\n \/\/\/ Creates a square matrix of the given size.\n explicit AbstractSparseMatrix(int s = 0) : Matrix(s) { }\n\n \/\/\/ Creates a matrix of the given height and width.\n explicit AbstractSparseMatrix(int h, int w) : Matrix(h, w) { }\n\n \/\/\/ Returns the number of non-zeros in a matrix\n virtual int NumNonZeroElems() const = 0;\n\n \/\/\/ Gets the columns indexes and values for row *row*.\n \/** Returns:\n - 0 if @a cols and @a srow are copies of the values in the matrix.\n - 1 if @a cols and @a srow are views of the values in the matrix. *\/\n virtual int GetRow(const int row, Array<int> &cols, Vector &srow) const = 0;\n\n \/** @brief If the matrix is square, this method will place 1 on the diagonal\n (i,i) if row i has \"almost\" zero l1-norm.\n\n If entry (i,i) does not belong to the sparsity pattern of A, then an\n error will occur. *\/\n virtual void EliminateZeroRows(const double threshold = 1e-12) = 0;\n\n \/\/\/ Matrix-Vector Multiplication y = A*x\n virtual void Mult(const Vector &x, Vector &y) const = 0;\n \/\/\/ Matrix-Vector Multiplication y = y + val*A*x\n virtual void AddMult(const Vector &x, Vector &y,\n const double val = 1.) const = 0;\n \/\/\/ MatrixTranspose-Vector Multiplication y = A'*x\n virtual void MultTranspose(const Vector &x, Vector &y) const = 0;\n \/\/\/ MatrixTranspose-Vector Multiplication y = y + val*A'*x\n virtual void AddMultTranspose(const Vector &x, Vector &y,\n const double val = 1.) const = 0;\n\n \/\/\/ Destroys AbstractSparseMatrix.\n virtual ~AbstractSparseMatrix() { }\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n *\tManjeet Dahiya\n *\n * Source:\n *\thttp:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\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 *\/\n\n#include <iostream>\n\n#include \"QXmppMessage.h\"\n#include \"QXmppRosterManager.h\"\n\n#include \"xmppClient.h\"\n\nxmppClient::xmppClient(QObject *parent)\n : QXmppClient(parent)\n{\n bool check = connect(this, SIGNAL(connected()),\n SLOT(clientConnected()));\n Q_ASSERT(check);\n\n check = connect(&this->rosterManager(), SIGNAL(rosterReceived()),\n SLOT(rosterReceived()));\n Q_ASSERT(check);\n\n \/\/\/ Then QXmppRoster::presenceChanged() is emitted whenever presence of someone\n \/\/\/ in roster changes\n check = connect(&this->rosterManager(),\n SIGNAL(presenceChanged(const QString&, const QString&)),\n SLOT(presenceChanged(const QString&, const QString&)));\n Q_ASSERT(check);\n}\n\nxmppClient::~xmppClient()\n{\n\n}\n\nvoid xmppClient::clientConnected()\n{\n std::cout<<\"example_2_rosterHandling:: CONNECTED\"<<std::endl;\n}\n\nvoid xmppClient::rosterReceived()\n{\n std::cout<<\"example_2_rosterHandling:: Roster Received\"<<std::endl;\n QStringList list = rosterManager().getRosterBareJids();\n for(int i = 0; i < list.size(); ++i)\n {\n std::cout<<\"Roster Received:: \"<<qPrintable(list.at(i))<<std::endl;\n }\n}\n\nvoid xmppClient::presenceChanged(const QString& bareJid,\n const QString& resource)\n{\n std::cout<<\"Presence changed:: \"<< qPrintable(bareJid)\n << qPrintable(resource)<<std::endl;\n}\n<commit_msg>display name also<commit_after>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n *\tManjeet Dahiya\n *\n * Source:\n *\thttp:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\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 *\/\n\n#include <iostream>\n\n#include \"QXmppMessage.h\"\n#include \"QXmppRosterManager.h\"\n\n#include \"xmppClient.h\"\n\nxmppClient::xmppClient(QObject *parent)\n : QXmppClient(parent)\n{\n bool check = connect(this, SIGNAL(connected()),\n SLOT(clientConnected()));\n Q_ASSERT(check);\n\n check = connect(&this->rosterManager(), SIGNAL(rosterReceived()),\n SLOT(rosterReceived()));\n Q_ASSERT(check);\n\n \/\/\/ Then QXmppRoster::presenceChanged() is emitted whenever presence of someone\n \/\/\/ in roster changes\n check = connect(&this->rosterManager(),\n SIGNAL(presenceChanged(const QString&, const QString&)),\n SLOT(presenceChanged(const QString&, const QString&)));\n Q_ASSERT(check);\n}\n\nxmppClient::~xmppClient()\n{\n\n}\n\nvoid xmppClient::clientConnected()\n{\n std::cout<<\"example_2_rosterHandling:: CONNECTED\"<<std::endl;\n}\n\nvoid xmppClient::rosterReceived()\n{\n std::cout<<\"example_2_rosterHandling:: Roster Received\"<<std::endl;\n QStringList list = rosterManager().getRosterBareJids();\n QString rosterEntry = \"Roster Received:: %1 [%2]\";\n for(int i = 0; i < list.size(); ++i)\n {\n QString bareJid = list.at(i);\n QString name = rosterManager().getRosterEntry(bareJid).name();\n if(name.isEmpty())\n name = \"-\";\n std::cout << qPrintable(rosterEntry.arg(bareJid).arg(name)) << std::endl;\n }\n}\n\nvoid xmppClient::presenceChanged(const QString& bareJid,\n const QString& resource)\n{\n std::cout<<\"Presence changed:: \"<< qPrintable(bareJid)\n << qPrintable(resource)<<std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 Samsung Electronics Co., Ltd.\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\/\/ INTERNAL INCLUDES\n\n#include \"vertical-layout.h\"\n#include \"emoji-strings.h\"\n\n\/\/ EXTERNAL INCLUDES\n#include <dali-toolkit\/dali-toolkit.h>\n#include <dali\/public-api\/text-abstraction\/text-abstraction.h>\n#include <iostream>\n\nusing namespace Dali;\nusing namespace Dali::Toolkit;\nusing namespace EmojiStrings;\n\n \/\/ TODO Need to expose Text::RENDER.....\nconst int ATLAS_RENDERER = 0;\n\n\/\/ This example shows how to create and display Hello World! using a simple TextActor\n\/\/\nclass EmojiExample : public ConnectionTracker\n{\npublic:\n\n typedef uint32_t SizeType;\n\n EmojiExample( Application& application )\n : mApplication( application )\n {\n std::cout << \"EmoticonController::EmoticonController\" << std::endl;\n\n \/\/ Connect to the Application's Init signal\n mApplication.InitSignal().Connect( this, &EmojiExample::Create );\n }\n\n ~EmojiExample()\n {\n \/\/ Nothing to do here;\n }\n\n \/\/ The Init signal is received once (only) during the Application lifetime\n void Create( Application& application )\n {\n\n mLayout = VerticalLayout::New();\n mLayout.SetParentOrigin( ParentOrigin::TOP_LEFT );\n mLayout.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n Stage stage = Stage::GetCurrent();\n stage.Add( mLayout );\n stage.KeyEventSignal().Connect(this, &EmojiExample::OnKeyEvent);\n\n for( unsigned int index = 0u; index < NUMBER_OF_EMOJIS; ++index )\n {\n const Emoji& emoji = EMOJIS[index];\n const std::string text = emoji.mUTF8 + \" \" + emoji.mDescription;\n TextLabel label = TextLabel::New();\n label.SetParentOrigin( ParentOrigin::TOP_CENTER );\n label.SetAnchorPoint( AnchorPoint::TOP_CENTER );\n label.SetProperty( TextLabel::Property::MULTI_LINE, true );\n label.SetProperty( TextLabel::Property::RENDERING_BACKEND, 0 );\n label.SetProperty( TextLabel::Property::TEXT, text );\n mLayout.AddLabel( label );\n mLayout.TouchedSignal().Connect( this, &EmojiExample::OnTouchEvent );\n }\n\n const Vector2& size = stage.GetSize();\n const float height = mLayout.GetHeightForWidth( size.width );\n mLayout.SetSize( Size( size.width, height ) );\n mLayout.TouchedSignal().Connect( this, &EmojiExample::OnTouchEvent );\n\n }\n\n bool OnTouchEvent( Actor actor, const TouchEvent& event )\n {\n if( 1u == event.GetPointCount() )\n {\n const TouchPoint::State state = event.GetPoint(0u).state;\n\n \/\/ Clamp to integer values; this is to reduce flicking due to pixel misalignment\n const float localPoint = static_cast<float>( static_cast<int>( event.GetPoint( 0 ).local.y ) );\n\n if( TouchPoint::Down == state )\n {\n mLastPoint = localPoint;\n mAnimation = Animation::New( 0.25f );\n }\n else if( TouchPoint::Motion == state )\n {\n if( mAnimation )\n {\n mAnimation.MoveBy( mLayout, Vector3( 0.f, localPoint - mLastPoint, 0.f ), AlphaFunctions::Linear );\n mAnimation.Play();\n mLastPoint = localPoint;\n }\n }\n }\n\n return true;\n }\n\n \/**\n * Main key event handler\n *\/\n void OnKeyEvent(const KeyEvent& event)\n {\n if(event.state == KeyEvent::Down)\n {\n if( IsKey( event, DALI_KEY_ESCAPE) || IsKey( event, DALI_KEY_BACK ) )\n {\n mApplication.Quit();\n }\n }\n }\n\n\nprivate:\n Application& mApplication;\n VerticalLayout mLayout;\n Animation mAnimation;\n float mLastPoint;\n};\n\nvoid RunTest( Application& application )\n{\n EmojiExample test( application );\n\n application.MainLoop();\n}\n\n\/\/ Entry point for Linux & SLP applications\n\/\/\nint main( int argc, char **argv )\n{\n Application application = Application::New( &argc, &argv );\n\n RunTest( application );\n\n return 0;\n}\n<commit_msg>Text renderer not using default backend in emoji example<commit_after>\/*\n * Copyright (c) 2015 Samsung Electronics Co., Ltd.\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\/\/ INTERNAL INCLUDES\n\n#include \"vertical-layout.h\"\n#include \"emoji-strings.h\"\n\n\/\/ EXTERNAL INCLUDES\n#include <dali-toolkit\/dali-toolkit.h>\n#include <dali\/public-api\/text-abstraction\/text-abstraction.h>\n#include <iostream>\n\nusing namespace Dali;\nusing namespace Dali::Toolkit;\nusing namespace EmojiStrings;\n\n \/\/ TODO Need to expose Text::RENDER.....\nconst int ATLAS_RENDERER = 0;\n\n\/\/ This example shows how to create and display Hello World! using a simple TextActor\n\/\/\nclass EmojiExample : public ConnectionTracker\n{\npublic:\n\n typedef uint32_t SizeType;\n\n EmojiExample( Application& application )\n : mApplication( application )\n {\n std::cout << \"EmoticonController::EmoticonController\" << std::endl;\n\n \/\/ Connect to the Application's Init signal\n mApplication.InitSignal().Connect( this, &EmojiExample::Create );\n }\n\n ~EmojiExample()\n {\n \/\/ Nothing to do here;\n }\n\n \/\/ The Init signal is received once (only) during the Application lifetime\n void Create( Application& application )\n {\n\n mLayout = VerticalLayout::New();\n mLayout.SetParentOrigin( ParentOrigin::TOP_LEFT );\n mLayout.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n Stage stage = Stage::GetCurrent();\n stage.Add( mLayout );\n stage.KeyEventSignal().Connect(this, &EmojiExample::OnKeyEvent);\n\n for( unsigned int index = 0u; index < NUMBER_OF_EMOJIS; ++index )\n {\n const Emoji& emoji = EMOJIS[index];\n const std::string text = emoji.mUTF8 + \" \" + emoji.mDescription;\n TextLabel label = TextLabel::New();\n label.SetParentOrigin( ParentOrigin::TOP_CENTER );\n label.SetAnchorPoint( AnchorPoint::TOP_CENTER );\n label.SetProperty( TextLabel::Property::MULTI_LINE, true );\n label.SetProperty( TextLabel::Property::TEXT, text );\n mLayout.AddLabel( label );\n mLayout.TouchedSignal().Connect( this, &EmojiExample::OnTouchEvent );\n }\n\n const Vector2& size = stage.GetSize();\n const float height = mLayout.GetHeightForWidth( size.width );\n mLayout.SetSize( Size( size.width, height ) );\n mLayout.TouchedSignal().Connect( this, &EmojiExample::OnTouchEvent );\n\n }\n\n bool OnTouchEvent( Actor actor, const TouchEvent& event )\n {\n if( 1u == event.GetPointCount() )\n {\n const TouchPoint::State state = event.GetPoint(0u).state;\n\n \/\/ Clamp to integer values; this is to reduce flicking due to pixel misalignment\n const float localPoint = static_cast<float>( static_cast<int>( event.GetPoint( 0 ).local.y ) );\n\n if( TouchPoint::Down == state )\n {\n mLastPoint = localPoint;\n mAnimation = Animation::New( 0.25f );\n }\n else if( TouchPoint::Motion == state )\n {\n if( mAnimation )\n {\n mAnimation.MoveBy( mLayout, Vector3( 0.f, localPoint - mLastPoint, 0.f ), AlphaFunctions::Linear );\n mAnimation.Play();\n mLastPoint = localPoint;\n }\n }\n }\n\n return true;\n }\n\n \/**\n * Main key event handler\n *\/\n void OnKeyEvent(const KeyEvent& event)\n {\n if(event.state == KeyEvent::Down)\n {\n if( IsKey( event, DALI_KEY_ESCAPE) || IsKey( event, DALI_KEY_BACK ) )\n {\n mApplication.Quit();\n }\n }\n }\n\n\nprivate:\n Application& mApplication;\n VerticalLayout mLayout;\n Animation mAnimation;\n float mLastPoint;\n};\n\nvoid RunTest( Application& application )\n{\n EmojiExample test( application );\n\n application.MainLoop();\n}\n\n\/\/ Entry point for Linux & SLP applications\n\/\/\nint main( int argc, char **argv )\n{\n Application application = Application::New( &argc, &argv );\n\n RunTest( application );\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ =============================================================================\n\/\/\n\/\/ Copyright (c) 2014 Brannon Dorsey <http:\/\/brannondorsey.com>\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\/\/ =============================================================================\n\n\n#include \"EditorSettings.h\"\n\nnamespace of {\nnamespace Sketch {\n\n\nEditorSettings::EditorSettings(const std::string& path):\n _path(path)\n{\n load();\n cout<<getProjectDir()<<endl;\n}\n\nbool EditorSettings::load()\n{\n return _data.open(_path);\n}\n\nbool EditorSettings::save()\n{\n return _data.save(_path);\n}\n\nconst Json::Value& EditorSettings::getData() const\n{\n return _data;\n}\n\nint EditorSettings::getPort() const\n{\n return _data[\"port\"].asInt();\n}\n \nstd::string EditorSettings::getProjectDir() const\n{\n return _data[\"projectDir\"].asString();\n}\n\nstd::string EditorSettings::getSketchDir() const\n{\n return _data[\"sketchDir\"].asString();\n}\n\nstd::string EditorSettings::getAddonsDir() const\n{\n return _data[\"addonsDir\"].asString();\n}\n\nstd::string EditorSettings::getOpenFrameworksDir() const\n{\n return _data[\"openFrameworksDir\"].asString();\n}\n\nstd::string EditorSettings::getOpenFrameworksVersion() const\n{\n return _data[\"openFrameworksVersion\"].asString();\n}\n \nstd::string EditorSettings::getProjectSettingsFilename() const\n{\n return _data[\"projectSettingsFilename\"].asString();\n}\n \nstd::string EditorSettings::getProjectExtension() const\n{\n return _data[\"projectExtension\"].asString();\n}\n\nstd::string EditorSettings::getClassExtension() const\n{\n return _data[\"classExtension\"].asString();\n}\n\n} } \/\/ namespace of::Sketch\n<commit_msg>Cleanup.<commit_after>\/\/ =============================================================================\n\/\/\n\/\/ Copyright (c) 2014 Brannon Dorsey <http:\/\/brannondorsey.com>\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\/\/ =============================================================================\n\n\n#include \"EditorSettings.h\"\n\nnamespace of {\nnamespace Sketch {\n\n\nEditorSettings::EditorSettings(const std::string& path):\n _path(path)\n{\n load();\n ofLogVerbose(\"EditorSettings::EditorSettings\") << \"Project Directory: \" << getProjectDir();\n}\n\nbool EditorSettings::load()\n{\n return _data.open(_path);\n}\n\nbool EditorSettings::save()\n{\n return _data.save(_path);\n}\n\nconst Json::Value& EditorSettings::getData() const\n{\n return _data;\n}\n\nint EditorSettings::getPort() const\n{\n return _data[\"port\"].asInt();\n}\n \nstd::string EditorSettings::getProjectDir() const\n{\n return _data[\"projectDir\"].asString();\n}\n\nstd::string EditorSettings::getSketchDir() const\n{\n return _data[\"sketchDir\"].asString();\n}\n\nstd::string EditorSettings::getAddonsDir() const\n{\n return _data[\"addonsDir\"].asString();\n}\n\nstd::string EditorSettings::getOpenFrameworksDir() const\n{\n return _data[\"openFrameworksDir\"].asString();\n}\n\nstd::string EditorSettings::getOpenFrameworksVersion() const\n{\n return _data[\"openFrameworksVersion\"].asString();\n}\n \nstd::string EditorSettings::getProjectSettingsFilename() const\n{\n return _data[\"projectSettingsFilename\"].asString();\n}\n \nstd::string EditorSettings::getProjectExtension() const\n{\n return _data[\"projectExtension\"].asString();\n}\n\nstd::string EditorSettings::getClassExtension() const\n{\n return _data[\"classExtension\"].asString();\n}\n\n} } \/\/ namespace of::Sketch\n<|endoftext|>"} {"text":"<commit_before>#include \"barcode\\PerkAttribMenu.hpp\"\r\n\r\nPerkAttribMenu::PerkAttribMenu()\r\n{\r\n\r\n}\r\n\r\nPerkAttribMenu::~PerkAttribMenu()\r\n{\r\n}\r\nvoid PerkAttribMenu::render(bool & thing, Hydra::Renderer::Batch * renderBatch, float delta)\r\n{\r\n\tImGui::SetNextWindowSize(ImVec2(500, 1000), ImGuiCond_Once);\r\n\tImGui::Begin(\"Attributes\", &thing, ImGuiWindowFlags_MenuBar);\r\n\r\n\t\/\/Whatever you choose in the editor will be added\/multiplied by\r\n\t\/\/whatever values the player already has\r\n\tImGui::Checkbox(\"Glow on\/off\", &Bullet.glow);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Glow Intensity:\"); ImGui::SameLine(); ImGui::DragFloat(\" \", &Bullet.glowIntensity);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Bullet Size:\"); ImGui::SameLine(); ImGui::DragFloat(\"\", &Bullet.bulletSize);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Bullet Damage:\"); ImGui::SameLine(); ImGui::DragFloat(\" \",&Bullet.dmg);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Weapon Recoil:\"); ImGui::SameLine(); ImGui::DragFloat(\" \", &Bullet.recoil);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Mag Ammo:\"); ImGui::SameLine(); ImGui::DragInt(\" \", &Bullet.currentMagAmmo);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Shot Spread:\"); ImGui::SameLine(); ImGui::DragFloat(\" \", &Bullet.bulletSpread);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Shot RPM:\"); ImGui::SameLine(); ImGui::DragFloat(\" \", &Bullet.roundsPerMinute);\r\n\tImGui::Separator();\r\n\tImGui::ColorPicker4(\"Bullet Color:\",(float*)&Bullet.bulletColor,ImGuiColorEditFlags_RGB);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Perk Description:\");\r\n\tImGui::InputText(\" \", Bullet.perkDescription, 128);\r\n\tImGui::Separator();\r\n\t\/\/ImGui::RadioButton(\"Multiplier\", &Bullet.multi); ImGui::SameLine(); ImGui::RadioButton(\"Adder\", &Bullet.add);\r\n\tImGui::Checkbox(\"Multiplier\", &Bullet.Multiplier), ImGui::SameLine(); ImGui::Checkbox(\"Adder\", &Bullet.Adder);\r\n\r\n\tif (ImGui::Button(\"Export\", ImVec2(200, 75)))\r\n\t{\r\n\t\topenPopup = true;\r\n\t}\r\n\r\n\tif (openPopup)\r\n\t{\r\n\t\tImGui::OpenPopup(\"Exporter\");\r\n\t\tif (ImGui::BeginPopup(\"Exporter\"))\r\n\t\t{\r\n\t\t\tImGui::Text(\"Write the name of your Perk:\");\r\n\t\t\tImGui::InputText(\" \", Bullet.perkName, 128);\r\n\r\n\t\t\tif (ImGui::Button(\"Done\", ImVec2(200, 75)))\r\n\t\t\t{\r\n\t\t\t\twriteToFile(Bullet.perkName);\r\n\t\t\t\topenPopup = false;\r\n\t\t\t}\r\n\t\t\tImGui::SameLine();\r\n\t\t\tif (ImGui::Button(\"Exit\", ImVec2(50, 75)))\r\n\t\t\t{\r\n\t\t\t\topenPopup = false;\r\n\t\t\t}\r\n\t\t\tImGui::EndPopup();\r\n\t\t}\r\n\t}\r\n\t\t\r\n\r\n\tImGui::End();\r\n}\r\n\r\nvoid PerkAttribMenu::updateBullet(BulletInfo& bullet)\r\n{\r\n\tbullet = Bullet;\r\n}\r\n\r\nvoid PerkAttribMenu::writeToFile(const char* fileName)\r\n{\r\n\t\/\/file << Bullet.bulletSize;\r\n\t\/\/file << Bullet.dmg;\r\n\t\/\/file << Bullet.recoil;\r\n\t\/\/file << Bullet.currentMagAmmo;\r\n\t\/\/file << Bullet.bulletSpread;\r\n\t\/\/file << Bullet.roundsPerMinute;\r\n\t\/\/file << Bullet.bulletColor[0];\r\n\t\/\/file << Bullet.bulletColor[1];\r\n\t\/\/file << Bullet.bulletColor[2];\r\n\t\/\/file.write(reinterpret_cast<char *>(&Bullet.perkDescription), sizeof(char));\r\n\t\/\/binary\r\n\t\/\/file << Bullet.perkDescription;\r\n\t\r\n\t\r\n\tstd::string name = fileName;\r\n\tstd::string filepath = \"C:\/Users\/destroyer\/Documents\/GitHub\/Hydra\/assets\/perks\/\" + name + \".PERK\";\r\n\tstd::ofstream file;\r\n\tfile.open(filepath, std::ios::binary);\r\n\t\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletSize), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.dmg), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.recoil), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.currentMagAmmo), sizeof(int));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletSpread), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.roundsPerMinute), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletColor[0]), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletColor[1]), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletColor[2]), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.Adder), sizeof(bool));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.Multiplier), sizeof(bool));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.glow), sizeof(bool));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.glowIntensity), sizeof(float));\r\n\r\n\tstd::string description = Bullet.perkDescription;\r\n\tint size = description.size();\r\n\r\n\tfile.write(reinterpret_cast<char*>(&size), sizeof(int));\r\n\tfile.write(description.data(), size);\r\n\r\n\tfile.close();\r\n}\r\n\r\n\r\n\r\n\r\n<commit_msg>Stuff<commit_after>#include \"barcode\\PerkAttribMenu.hpp\"\r\n\r\nPerkAttribMenu::PerkAttribMenu()\r\n{\r\n\r\n}\r\n\r\nPerkAttribMenu::~PerkAttribMenu()\r\n{\r\n}\r\nvoid PerkAttribMenu::render(bool & thing, Hydra::Renderer::Batch * renderBatch, float delta)\r\n{\r\n\tImGui::SetNextWindowSize(ImVec2(500, 1000), ImGuiCond_Once);\r\n\tImGui::Begin(\"Attributes\", &thing, ImGuiWindowFlags_MenuBar);\r\n\r\n\t\/\/Whatever you choose in the editor will be added\/multiplied by\r\n\t\/\/whatever values the player already has\r\n\tImGui::Checkbox(\"Glow on\/off\", &Bullet.glow);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Glow Intensity:\"); ImGui::SameLine(); ImGui::DragFloat(\" \", &Bullet.glowIntensity, 0.01f);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Bullet Size:\"); ImGui::SameLine(); ImGui::DragFloat(\"\", &Bullet.bulletSize);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Bullet Damage:\"); ImGui::SameLine(); ImGui::DragFloat(\" \",&Bullet.dmg);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Weapon Recoil:\"); ImGui::SameLine(); ImGui::DragFloat(\" \", &Bullet.recoil);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Mag Ammo:\"); ImGui::SameLine(); ImGui::DragInt(\" \", &Bullet.currentMagAmmo);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Shot Spread:\"); ImGui::SameLine(); ImGui::DragFloat(\" \", &Bullet.bulletSpread);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Shot RPM:\"); ImGui::SameLine(); ImGui::DragFloat(\" \", &Bullet.roundsPerMinute);\r\n\tImGui::Separator();\r\n\tImGui::ColorPicker4(\"Bullet Color:\",(float*)&Bullet.bulletColor,ImGuiColorEditFlags_RGB);\r\n\tImGui::Separator();\r\n\tImGui::Text(\"Perk Description:\");\r\n\tImGui::InputText(\" \", Bullet.perkDescription, 128);\r\n\tImGui::Separator();\r\n\t\/\/ImGui::RadioButton(\"Multiplier\", &Bullet.multi); ImGui::SameLine(); ImGui::RadioButton(\"Adder\", &Bullet.add);\r\n\tImGui::Checkbox(\"Multiplier\", &Bullet.Multiplier), ImGui::SameLine(); ImGui::Checkbox(\"Adder\", &Bullet.Adder);\r\n\r\n\tif (ImGui::Button(\"Export\", ImVec2(200, 75)))\r\n\t{\r\n\t\topenPopup = true;\r\n\t}\r\n\r\n\tif (openPopup)\r\n\t{\r\n\t\tImGui::OpenPopup(\"Exporter\");\r\n\t\tif (ImGui::BeginPopup(\"Exporter\"))\r\n\t\t{\r\n\t\t\tImGui::Text(\"Write the name of your Perk:\");\r\n\t\t\tImGui::InputText(\" \", Bullet.perkName, 128);\r\n\r\n\t\t\tif (ImGui::Button(\"Done\", ImVec2(200, 75)))\r\n\t\t\t{\r\n\t\t\t\twriteToFile(Bullet.perkName);\r\n\t\t\t\topenPopup = false;\r\n\t\t\t}\r\n\t\t\tImGui::SameLine();\r\n\t\t\tif (ImGui::Button(\"Exit\", ImVec2(50, 75)))\r\n\t\t\t{\r\n\t\t\t\topenPopup = false;\r\n\t\t\t}\r\n\t\t\tImGui::EndPopup();\r\n\t\t}\r\n\t}\r\n\t\t\r\n\r\n\tImGui::End();\r\n}\r\n\r\nvoid PerkAttribMenu::updateBullet(BulletInfo& bullet)\r\n{\r\n\tbullet = Bullet;\r\n}\r\n\r\nvoid PerkAttribMenu::writeToFile(const char* fileName)\r\n{\r\n\t\/\/file << Bullet.bulletSize;\r\n\t\/\/file << Bullet.dmg;\r\n\t\/\/file << Bullet.recoil;\r\n\t\/\/file << Bullet.currentMagAmmo;\r\n\t\/\/file << Bullet.bulletSpread;\r\n\t\/\/file << Bullet.roundsPerMinute;\r\n\t\/\/file << Bullet.bulletColor[0];\r\n\t\/\/file << Bullet.bulletColor[1];\r\n\t\/\/file << Bullet.bulletColor[2];\r\n\t\/\/file.write(reinterpret_cast<char *>(&Bullet.perkDescription), sizeof(char));\r\n\t\/\/binary\r\n\t\/\/file << Bullet.perkDescription;\r\n\t\r\n\t\r\n\tstd::string name = fileName;\r\n\tstd::string filepath = \"C:\/Users\/destroyer\/Documents\/GitHub\/Hydra\/assets\/perks\/\" + name + \".PERK\";\r\n\tstd::ofstream file;\r\n\tfile.open(filepath, std::ios::binary);\r\n\t\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletSize), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.dmg), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.recoil), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.currentMagAmmo), sizeof(int));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletSpread), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.roundsPerMinute), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletColor[0]), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletColor[1]), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.bulletColor[2]), sizeof(float));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.Adder), sizeof(bool));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.Multiplier), sizeof(bool));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.glow), sizeof(bool));\r\n\tfile.write(reinterpret_cast<char *>(&Bullet.glowIntensity), sizeof(float));\r\n\r\n\tstd::string description = Bullet.perkDescription;\r\n\tint size = description.size();\r\n\r\n\tfile.write(reinterpret_cast<char*>(&size), sizeof(int));\r\n\tfile.write(description.data(), size);\r\n\r\n\tfile.close();\r\n}\r\n\r\n\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\n\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <iostream>\n#include \"shape_featureset.hpp\"\n\ntemplate <typename filterT>\nshape_featureset<filterT>::shape_featureset(const filterT& filter, \n const std::string& shape_file,\n const std::set<std::string>& attribute_names,\n std::string const& encoding,\n long file_length )\n : filter_(filter),\n shape_type_(shape_io::shape_null),\n shape_(shape_file),\n query_ext_(),\n tr_(new transcoder(encoding)),\n file_length_(file_length),\n count_(0)\n{\n shape_.shp().skip(100);\n \/\/attributes\n typename std::set<std::string>::const_iterator pos=attribute_names.begin();\n while (pos!=attribute_names.end())\n {\n bool found_name = false;\n for (int i=0;i<shape_.dbf().num_fields();++i)\n {\n if (shape_.dbf().descriptor(i).name_ == *pos)\n {\n attr_ids_.push_back(i);\n found_name = true;\n break;\n }\n }\n if (!found_name)\n {\n std::ostringstream s;\n\n s << \"Shapefile Plugin: Error: no attribute by the name of '\" << *pos << \"'\"\n << \", available attributes are:\";\n for (int i=0;i<shape_.dbf().num_fields();++i)\n {\n s << \" '\" << shape_.dbf().descriptor(i).name_ << \"'\";\n }\n \n throw mapnik::datasource_exception( s.str() );\n }\n ++pos;\n }\n}\n\n\ntemplate <typename filterT>\nfeature_ptr shape_featureset<filterT>::next()\n{\n using mapnik::point_impl;\n std::streampos pos=shape_.shp().pos();\n \n if (!shape_.shp().is_eof())\n {\n shape_.move_to(pos);\n int type=shape_.type();\n feature_ptr feature(new Feature(shape_.id_));\n if (type == shape_io::shape_point)\n {\n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n ++count_;\n }\n else if (type == shape_io::shape_pointm)\n {\n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n shape_.shp().skip(8); \/\/m\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n ++count_;\n }\n else if (type == shape_io::shape_pointz)\n {\n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n \/\/ skip z\n shape_.shp().skip(8);\n\n \/\/skip m if exists\n if ( shape_.reclength_ == 8 + 36) \n {\n shape_.shp().skip(8);\n }\n geometry2d * point=new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n ++count_;\n }\n else\n {\n while (!filter_.pass(shape_.current_extent()))\n { \n if (!shape_.shp().is_eof())\n {\n std::streampos pos = shape_.shp().pos();\n if (shape_.type() != shape_io::shape_null)\n {\n pos += std::streampos(2 * shape_.reclength_ - 36);\n }\n shape_.move_to(pos); \n }\n else\n {\n return feature_ptr();\n }\n }\n \n switch (type)\n {\n case shape_io::shape_multipoint:\n {\n int num_points = shape_.shp().read_ndr_integer();\n for (int i=0; i< num_points;++i)\n { \n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n }\n ++count_;\n break;\n }\n case shape_io::shape_multipointm:\n {\n int num_points = shape_.shp().read_ndr_integer();\n for (int i=0; i< num_points;++i)\n { \n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n }\n \n \/\/ skip m \n shape_.shp().skip(2*8 + 8*num_points);\n ++count_;\n break;\n }\n case shape_io::shape_multipointz:\n {\n unsigned num_points = shape_.shp().read_ndr_integer();\n for (unsigned i=0; i< num_points;++i)\n { \n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n }\n \n \/\/ skip z\n shape_.shp().skip(2*8 + 8*num_points);\n \n \/\/ check if we have measure data \n \n if ( shape_.reclength_ == num_points * 16 + 36) \n {\n \/\/ skip m \n shape_.shp().skip(2*8 + 8*num_points);\n }\n ++count_;\n break;\n }\n case shape_io::shape_polyline:\n {\n geometry2d * line = shape_.read_polyline();\n feature->add_geometry(line);\n ++count_;\n break;\n }\n case shape_io::shape_polylinem:\n {\n geometry2d * line = shape_.read_polylinem();\n feature->add_geometry(line);\n ++count_;\n break;\n }\n case shape_io::shape_polylinez:\n {\n geometry2d * line = shape_.read_polylinez();\n feature->add_geometry(line);\n ++count_;\n break;\n }\n case shape_io::shape_polygon:\n { \n geometry2d * poly = shape_.read_polygon();\n feature->add_geometry(poly);\n ++count_;\n break;\n }\n case shape_io::shape_polygonm:\n { \n geometry2d * poly = shape_.read_polygonm();\n feature->add_geometry(poly);\n ++count_;\n break;\n }\n case shape_io::shape_polygonz:\n {\n geometry2d * poly = shape_.read_polygonz();\n feature->add_geometry(poly);\n ++count_;\n break;\n }\n \n }\n }\n if (attr_ids_.size())\n {\n shape_.dbf().move_to(shape_.id_);\n std::vector<int>::const_iterator pos=attr_ids_.begin();\n std::vector<int>::const_iterator end=attr_ids_.end();\n \n while (pos!=end)\n {\n try \n {\n shape_.dbf().add_attribute(*pos,*tr_,*feature);\/\/TODO optimize!!!\n }\n catch (...)\n {\n std::clog << \"error processing attributes \" << std::endl;\n }\n ++pos;\n }\n }\n return feature;\n }\n else\n {\n#ifdef MAPNIK_DEBUG\n std::clog<<\" total shapes read=\"<<count_<<\"\\n\";\n#endif\n return feature_ptr();\n }\n}\n\ntemplate <typename filterT>\nshape_featureset<filterT>::~shape_featureset() {}\n\ntemplate class shape_featureset<mapnik::filter_in_box>;\ntemplate class shape_featureset<mapnik::filter_at_point>;\n\n \n<commit_msg>shape: switch back to previous end of file method - closes #647<commit_after>\n\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <iostream>\n#include \"shape_featureset.hpp\"\n\ntemplate <typename filterT>\nshape_featureset<filterT>::shape_featureset(const filterT& filter, \n const std::string& shape_file,\n const std::set<std::string>& attribute_names,\n std::string const& encoding,\n long file_length )\n : filter_(filter),\n shape_type_(shape_io::shape_null),\n shape_(shape_file),\n query_ext_(),\n tr_(new transcoder(encoding)),\n file_length_(file_length),\n count_(0)\n{\n shape_.shp().skip(100);\n \/\/attributes\n typename std::set<std::string>::const_iterator pos=attribute_names.begin();\n while (pos!=attribute_names.end())\n {\n bool found_name = false;\n for (int i=0;i<shape_.dbf().num_fields();++i)\n {\n if (shape_.dbf().descriptor(i).name_ == *pos)\n {\n attr_ids_.push_back(i);\n found_name = true;\n break;\n }\n }\n if (!found_name)\n {\n std::ostringstream s;\n\n s << \"Shapefile Plugin: Error: no attribute by the name of '\" << *pos << \"'\"\n << \", available attributes are:\";\n for (int i=0;i<shape_.dbf().num_fields();++i)\n {\n s << \" '\" << shape_.dbf().descriptor(i).name_ << \"'\";\n }\n \n throw mapnik::datasource_exception( s.str() );\n }\n ++pos;\n }\n}\n\n\ntemplate <typename filterT>\nfeature_ptr shape_featureset<filterT>::next()\n{\n using mapnik::point_impl;\n std::streampos pos=shape_.shp().pos();\n \n if (pos < std::streampos(file_length_ * 2))\n {\n shape_.move_to(pos);\n int type=shape_.type();\n feature_ptr feature(new Feature(shape_.id_));\n if (type == shape_io::shape_point)\n {\n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n ++count_;\n }\n else if (type == shape_io::shape_pointm)\n {\n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n shape_.shp().skip(8); \/\/m\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n ++count_;\n }\n else if (type == shape_io::shape_pointz)\n {\n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n \/\/ skip z\n shape_.shp().skip(8);\n\n \/\/skip m if exists\n if ( shape_.reclength_ == 8 + 36) \n {\n shape_.shp().skip(8);\n }\n geometry2d * point=new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n ++count_;\n }\n else\n {\n while (!filter_.pass(shape_.current_extent()))\n { \n if (!shape_.shp().is_eof())\n {\n std::streampos pos = shape_.shp().pos();\n if (shape_.type() != shape_io::shape_null)\n {\n pos += std::streampos(2 * shape_.reclength_ - 36);\n }\n shape_.move_to(pos); \n }\n else\n {\n return feature_ptr();\n }\n }\n \n switch (type)\n {\n case shape_io::shape_multipoint:\n {\n int num_points = shape_.shp().read_ndr_integer();\n for (int i=0; i< num_points;++i)\n { \n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n }\n ++count_;\n break;\n }\n case shape_io::shape_multipointm:\n {\n int num_points = shape_.shp().read_ndr_integer();\n for (int i=0; i< num_points;++i)\n { \n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n }\n \n \/\/ skip m \n shape_.shp().skip(2*8 + 8*num_points);\n ++count_;\n break;\n }\n case shape_io::shape_multipointz:\n {\n unsigned num_points = shape_.shp().read_ndr_integer();\n for (unsigned i=0; i< num_points;++i)\n { \n double x=shape_.shp().read_double();\n double y=shape_.shp().read_double();\n geometry2d * point = new point_impl;\n point->move_to(x,y);\n feature->add_geometry(point);\n }\n \n \/\/ skip z\n shape_.shp().skip(2*8 + 8*num_points);\n \n \/\/ check if we have measure data \n \n if ( shape_.reclength_ == num_points * 16 + 36) \n {\n \/\/ skip m \n shape_.shp().skip(2*8 + 8*num_points);\n }\n ++count_;\n break;\n }\n case shape_io::shape_polyline:\n {\n geometry2d * line = shape_.read_polyline();\n feature->add_geometry(line);\n ++count_;\n break;\n }\n case shape_io::shape_polylinem:\n {\n geometry2d * line = shape_.read_polylinem();\n feature->add_geometry(line);\n ++count_;\n break;\n }\n case shape_io::shape_polylinez:\n {\n geometry2d * line = shape_.read_polylinez();\n feature->add_geometry(line);\n ++count_;\n break;\n }\n case shape_io::shape_polygon:\n { \n geometry2d * poly = shape_.read_polygon();\n feature->add_geometry(poly);\n ++count_;\n break;\n }\n case shape_io::shape_polygonm:\n { \n geometry2d * poly = shape_.read_polygonm();\n feature->add_geometry(poly);\n ++count_;\n break;\n }\n case shape_io::shape_polygonz:\n {\n geometry2d * poly = shape_.read_polygonz();\n feature->add_geometry(poly);\n ++count_;\n break;\n }\n \n }\n }\n if (attr_ids_.size())\n {\n shape_.dbf().move_to(shape_.id_);\n std::vector<int>::const_iterator pos=attr_ids_.begin();\n std::vector<int>::const_iterator end=attr_ids_.end();\n \n while (pos!=end)\n {\n try \n {\n shape_.dbf().add_attribute(*pos,*tr_,*feature);\/\/TODO optimize!!!\n }\n catch (...)\n {\n std::clog << \"error processing attributes \" << std::endl;\n }\n ++pos;\n }\n }\n return feature;\n }\n else\n {\n#ifdef MAPNIK_DEBUG\n std::clog<<\" total shapes read=\"<<count_<<\"\\n\";\n#endif\n return feature_ptr();\n }\n}\n\ntemplate <typename filterT>\nshape_featureset<filterT>::~shape_featureset() {}\n\ntemplate class shape_featureset<mapnik::filter_in_box>;\ntemplate class shape_featureset<mapnik::filter_at_point>;\n\n \n<|endoftext|>"} {"text":"<commit_before>#include \"dynet\/tensor-eigen.h\"\n#include \"dynet\/nodes-dropout.h\"\n\n#include \"dynet\/nodes-impl-macros.h\"\n\nusing namespace std;\n\nnamespace dynet {\n\n\/\/ ************* Dropout *************\n\n#ifndef __CUDACC__\n\nstring Dropout::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"dropout(\" << arg_names[0] << \",p=\" << p << ')';\n return s.str();\n}\n\nDim Dropout::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(xs.size() == 1, \"Failed input count check in Dropout\")\n return xs[0];\n}\n\nsize_t Dropout::aux_storage_size() const {\n return dim.size() * sizeof(float);\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid Dropout::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n Tensor m(fx.d, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n TensorTools::randomize_bernoulli(m, (1.f-p), 1.f \/ (1.f-p));\n tvec(fx).device(*dev.edevice) = tvec(*xs[0]) * tvec(m);\n}\n\ntemplate<class MyDevice>\nvoid Dropout::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n Tensor m(fx.d, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n tvec(dEdxi).device(*dev.edevice) += tvec(dEdf) * tvec(m);\n}\nDYNET_NODE_INST_DEV_IMPL(Dropout)\n\n\/\/ ************* DropoutDim *************\n\n#ifndef __CUDACC__\n\nstring DropoutDim::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"dropout_dim(\" << arg_names[0] << \",p=\" << p << ')';\n return s.str();\n}\n\nDim DropoutDim::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(xs.size() == 1, \"Failed input count check in DropoutDim\")\n DYNET_ARG_CHECK(xs[0].nd < 4, \"DropoutDim only supports tensor up to order 3 + batch dimension, got tensor of order\"<<xs[0].nd)\n DYNET_ARG_CHECK(xs[0].nd > dimension, \"In DropoutDim : tried to drop along dimension \"<<dimension<<\" on tensor of order\"<<xs[0].nd)\n return xs[0];\n}\n\nsize_t DropoutDim::aux_storage_size() const {\n return (dim.size() \/ dim[dimension]) * sizeof(float);\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid DropoutDim::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n Dim mask_dim(dim);\n mask_dim.d[dimension]=1;\n Tensor m(mask_dim, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n TensorTools::randomize_bernoulli(m, (1.f-p), 1.f \/ (1.f-p));\n Eigen::array<ptrdiff_t, 4> bcast = {1, 1, 1, 1}; bcast[dimension] = xs[0]->d[dimension];\n tb<3>(fx).device(*dev.edevice) = tb<3>(*xs[0]) * tb<3>(m).broadcast(bcast);\n}\n\ntemplate<class MyDevice>\nvoid DropoutDim::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n Dim mask_dim(dim);\n mask_dim.d[dimension]=1;\n Tensor m(mask_dim, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n Eigen::array<ptrdiff_t, 4> bcast = {1, 1, 1, 1}; bcast[dimension] = dEdf.d[dimension];\n tb<3>(dEdxi).device(*dev.edevice) += tb<3>(dEdf) * tb<3>(m).broadcast(bcast);\n}\nDYNET_NODE_INST_DEV_IMPL(DropoutDim)\n\n\/\/ ************* DropoutBatch *************\n\n#ifndef __CUDACC__\n\nstring DropoutBatch::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"dropout_batch(\" << arg_names[0] << \",p=\" << p << ')';\n return s.str();\n}\n\nDim DropoutBatch::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(xs.size() == 1, \"Failed input count check in DropoutBatch\")\n return xs[0];\n}\n\nsize_t DropoutBatch::aux_storage_size() const {\n return dim.batch_elems() * sizeof(float);\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid DropoutBatch::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n Dim mask_dim({1},xs[0]->d.batch_elems());\n Tensor m(mask_dim, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n TensorTools::randomize_bernoulli(m, (1.f-p), 1.f \/ (1.f-p));\n Eigen::array<ptrdiff_t, 2> bcast = {xs[0]->d.batch_size(), 1};\n tbvec(fx).device(*dev.edevice) = tbvec(*xs[0]) * tbvec(m).broadcast(bcast);\n}\n\ntemplate<class MyDevice>\nvoid DropoutBatch::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n Dim mask_dim({1},xs[0]->d.batch_elems());\n Tensor m(mask_dim, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n Eigen::array<ptrdiff_t, 2> bcast = {xs[0]->d.batch_size(), 1};\n tbvec(dEdxi).device(*dev.edevice) += tbvec(dEdf) * tbvec(m).broadcast(bcast);\n}\nDYNET_NODE_INST_DEV_IMPL(DropoutBatch)\n\n\/\/ ************* BlockDropout *************\n\n#ifndef __CUDACC__\n\nstring BlockDropout::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"block_dropout(\" << arg_names[0] << \",dropout_probability=\" << dropout_probability << ')';\n return s.str();\n}\n\nDim BlockDropout::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(xs.size() == 1, \"Failed input count check in BlockDropout\")\n return xs[0];\n}\n\nsize_t BlockDropout::aux_storage_size() const {\n \/\/ we just need to remember whether this entire block is turned on (1.0) or off (0.0)\n return 1 * sizeof(float);\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid BlockDropout::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n bernoulli_distribution distribution(1.0 - dropout_probability);\n float block_multiplier = distribution(*rndeng)? 1.0 : 0.0;\n block_multiplier =\n dropout_probability == 1.0? 0.0 : block_multiplier \/ (1.0 - dropout_probability);\n if (dropout_probability > 1.0 || dropout_probability < 0.0)\n DYNET_INVALID_ARG(\"Dropout probability must be in the range [0, 1]\");\n *(static_cast<float*>(aux_mem)) = block_multiplier;\n tvec(fx).device(*dev.edevice) = tvec(*xs[0]) * block_multiplier;\n}\n\ntemplate<class MyDevice>\nvoid BlockDropout::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n float block_multiplier = *(static_cast<float*>(aux_mem));\n tvec(dEdxi).device(*dev.edevice) += tvec(dEdf) * block_multiplier;\n}\nDYNET_NODE_INST_DEV_IMPL(BlockDropout)\n\n}\n<commit_msg>Fix block dropout on GPU<commit_after>#include \"dynet\/tensor-eigen.h\"\n#include \"dynet\/nodes-dropout.h\"\n\n#include \"dynet\/nodes-impl-macros.h\"\n\nusing namespace std;\n\nnamespace dynet {\n\n\/\/ ************* Dropout *************\n\n#ifndef __CUDACC__\n\nstring Dropout::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"dropout(\" << arg_names[0] << \",p=\" << p << ')';\n return s.str();\n}\n\nDim Dropout::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(xs.size() == 1, \"Failed input count check in Dropout\")\n return xs[0];\n}\n\nsize_t Dropout::aux_storage_size() const {\n return dim.size() * sizeof(float);\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid Dropout::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n Tensor m(fx.d, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n TensorTools::randomize_bernoulli(m, (1.f-p), 1.f \/ (1.f-p));\n tvec(fx).device(*dev.edevice) = tvec(*xs[0]) * tvec(m);\n}\n\ntemplate<class MyDevice>\nvoid Dropout::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n Tensor m(fx.d, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n tvec(dEdxi).device(*dev.edevice) += tvec(dEdf) * tvec(m);\n}\nDYNET_NODE_INST_DEV_IMPL(Dropout)\n\n\/\/ ************* DropoutDim *************\n\n#ifndef __CUDACC__\n\nstring DropoutDim::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"dropout_dim(\" << arg_names[0] << \",p=\" << p << ')';\n return s.str();\n}\n\nDim DropoutDim::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(xs.size() == 1, \"Failed input count check in DropoutDim\")\n DYNET_ARG_CHECK(xs[0].nd < 4, \"DropoutDim only supports tensor up to order 3 + batch dimension, got tensor of order\"<<xs[0].nd)\n DYNET_ARG_CHECK(xs[0].nd > dimension, \"In DropoutDim : tried to drop along dimension \"<<dimension<<\" on tensor of order\"<<xs[0].nd)\n return xs[0];\n}\n\nsize_t DropoutDim::aux_storage_size() const {\n return (dim.size() \/ dim[dimension]) * sizeof(float);\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid DropoutDim::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n Dim mask_dim(dim);\n mask_dim.d[dimension]=1;\n Tensor m(mask_dim, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n TensorTools::randomize_bernoulli(m, (1.f-p), 1.f \/ (1.f-p));\n Eigen::array<ptrdiff_t, 4> bcast = {1, 1, 1, 1}; bcast[dimension] = xs[0]->d[dimension];\n tb<3>(fx).device(*dev.edevice) = tb<3>(*xs[0]) * tb<3>(m).broadcast(bcast);\n}\n\ntemplate<class MyDevice>\nvoid DropoutDim::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n Dim mask_dim(dim);\n mask_dim.d[dimension]=1;\n Tensor m(mask_dim, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n Eigen::array<ptrdiff_t, 4> bcast = {1, 1, 1, 1}; bcast[dimension] = dEdf.d[dimension];\n tb<3>(dEdxi).device(*dev.edevice) += tb<3>(dEdf) * tb<3>(m).broadcast(bcast);\n}\nDYNET_NODE_INST_DEV_IMPL(DropoutDim)\n\n\/\/ ************* DropoutBatch *************\n\n#ifndef __CUDACC__\n\nstring DropoutBatch::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"dropout_batch(\" << arg_names[0] << \",p=\" << p << ')';\n return s.str();\n}\n\nDim DropoutBatch::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(xs.size() == 1, \"Failed input count check in DropoutBatch\")\n return xs[0];\n}\n\nsize_t DropoutBatch::aux_storage_size() const {\n return dim.batch_elems() * sizeof(float);\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid DropoutBatch::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n Dim mask_dim({1},xs[0]->d.batch_elems());\n Tensor m(mask_dim, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n TensorTools::randomize_bernoulli(m, (1.f-p), 1.f \/ (1.f-p));\n Eigen::array<ptrdiff_t, 2> bcast = {xs[0]->d.batch_size(), 1};\n tbvec(fx).device(*dev.edevice) = tbvec(*xs[0]) * tbvec(m).broadcast(bcast);\n}\n\ntemplate<class MyDevice>\nvoid DropoutBatch::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n Dim mask_dim({1},xs[0]->d.batch_elems());\n Tensor m(mask_dim, (float*)aux_mem, fx.device, DeviceMempool::FXS);\n Eigen::array<ptrdiff_t, 2> bcast = {xs[0]->d.batch_size(), 1};\n tbvec(dEdxi).device(*dev.edevice) += tbvec(dEdf) * tbvec(m).broadcast(bcast);\n}\nDYNET_NODE_INST_DEV_IMPL(DropoutBatch)\n\n\/\/ ************* BlockDropout *************\n\n#ifndef __CUDACC__\n\nstring BlockDropout::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"block_dropout(\" << arg_names[0] << \",dropout_probability=\" << dropout_probability << ')';\n return s.str();\n}\n\nDim BlockDropout::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(xs.size() == 1, \"Failed input count check in BlockDropout\")\n return xs[0];\n}\n\nsize_t BlockDropout::aux_storage_size() const {\n \/\/ we just need to remember whether this entire block is turned on (1.0) or off (0.0)\n return 1 * sizeof(float);\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid BlockDropout::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n float p = dropout_probability;\n Tensor m(Dim({1}), (float*)aux_mem, fx.device, DeviceMempool::FXS);\n if (p > 1.0 || p < 0.0) {\n DYNET_INVALID_ARG(\"Dropout probability must be in the range [0, 1]\");\n } else {\n if (p == 1.0)\n TensorTools::zero(m);\n else\n TensorTools::randomize_bernoulli(m, (1.f-p), 1.f \/ (1.f-p));\n }\n float block_multiplier = as_scalar(m);\n tvec(fx).device(*dev.edevice) = tvec(*xs[0]) * block_multiplier;\n}\n\ntemplate<class MyDevice>\nvoid BlockDropout::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n Tensor m(Dim({1}), (float*)aux_mem, fx.device, DeviceMempool::FXS);\n float block_multiplier = as_scalar(m);\n tvec(dEdxi).device(*dev.edevice) += tvec(dEdf) * block_multiplier;\n}\nDYNET_NODE_INST_DEV_IMPL(BlockDropout)\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Ingen.\n * Copyright (C) 2007 Dave Robillard <http:\/\/drobilla.net>\n * \n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n * \n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for 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 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <sys\/mman.h>\n#include <iostream>\n#include \"QueuedEventSource.hpp\"\n#include \"QueuedEvent.hpp\"\n#include \"PostProcessor.hpp\"\n#include \"ThreadManager.hpp\"\n#include \"ProcessContext.hpp\"\n\nusing namespace std;\n\nnamespace Ingen {\n\n\nQueuedEventSource::QueuedEventSource(size_t queued_size, size_t stamped_size)\n\t: _front(0)\n\t, _back(0)\n\t, _prepared_back(0)\n\t, _size(queued_size+1)\n\t, _blocking_semaphore(0)\n\t, _full_semaphore(0)\n\t, _stamped_queue(stamped_size)\n{\n\t_events = (QueuedEvent**)calloc(_size, sizeof(QueuedEvent*));\n\n\tmlock(_events, _size * sizeof(QueuedEvent*));\n\n\tThread::set_context(THREAD_PRE_PROCESS);\n\tassert(context() == THREAD_PRE_PROCESS);\n\n\tset_name(\"QueuedEventSource\");\n}\n\n\nQueuedEventSource::~QueuedEventSource()\n{\n\tThread::stop();\n\t\n\tfree(_events);\n}\n\n\n\/** Push an unprepared event onto the queue.\n *\/\nvoid\nQueuedEventSource::push_queued(QueuedEvent* const ev)\n{\n\tassert(!ev->is_prepared());\n\n\tunsigned back = _back.get();\n\tbool full = (((_front.get() - back + _size) % _size) == 1);\n\twhile (full) {\n\t\twhip();\n\t\tcerr << \"WARNING: Event queue full. Waiting...\" << endl;\n\t\t_full_semaphore.wait();\n\t\tback = _back.get();\n\t\tfull = (((_front.get() - back + _size) % _size) == 1);\n\t}\n\t\t\n\tassert(_events[back] == NULL);\n\t_events[back] = ev;\n\t_back = (back + 1) % _size;\n\twhip();\n}\n\n\n\/** Process all events for a cycle.\n *\n * Executed events will be pushed to @a dest.\n *\/\nvoid\nQueuedEventSource::process(PostProcessor& dest, ProcessContext& context)\n{\n\tassert(ThreadManager::current_thread_id() == THREAD_PROCESS);\n\n\tEvent* ev = NULL;\n\n\t\/* Limit the maximum number of queued events to process per cycle. This\n\t * makes the process callback (more) realtime-safe by preventing being\n\t * choked by events coming in faster than they can be processed.\n\t * FIXME: test this and figure out a good value *\/\n\tconst unsigned int MAX_QUEUED_EVENTS = context.nframes() \/ 100;\n\n\tunsigned int num_events_processed = 0;\n\t\n\t\/* FIXME: Merge these next two loops into one *\/\n\n\twhile ((ev = pop_earliest_queued_before(context.end()))) {\n\t\tev->execute(context);\n\t\tdest.push(ev);\n\t\tif (++num_events_processed > MAX_QUEUED_EVENTS)\n\t\t\tbreak;\n\t}\n\t\n\twhile ((ev = pop_earliest_stamped_before(context.end()))) {\n\t\tev->execute(context);\n\t\tdest.push(ev);\n\t\t++num_events_processed;\n\t}\n\n\tif (num_events_processed > 0)\n\t\twhile (_full_semaphore.has_waiter())\n\t\t\t_full_semaphore.post();\n}\n\n\n\/** Pops the prepared event at the front of the prepare queue, if it exists.\n *\n * This method will only pop events that have been prepared, and are\n * stamped before the time passed. In other words, it may return NULL\n * even if there are events pending in the queue. The events returned are\n * actually QueuedEvents, but after this they are \"normal\" events and the\n * engine deals with them just like a realtime in-band event. The engine will\n * not use the timestamps of the returned events in any way, since it is free\n * to execute these non-time-stamped events whenever it wants (at whatever rate\n * it wants).\n *\/\nEvent*\nQueuedEventSource::pop_earliest_queued_before(const SampleCount time)\n{\n\tassert(ThreadManager::current_thread_id() == THREAD_PROCESS);\n\n\tconst unsigned front = _front.get();\n\tQueuedEvent* const front_event = _events[front];\n\t\n\t\/\/ Pop\n\tif (front_event && front_event->is_prepared() && front_event->time() < time) {\n\t\t_events[front] = NULL;\n\t\t_front = (front + 1) % _size;\n\t\treturn front_event;\n\t} else {\n\t\treturn NULL;\n\t}\n}\n\n\n\/\/ Private \/\/\n\n\n\/** Pre-process a single event *\/\nvoid\nQueuedEventSource::_whipped()\n{\n\tconst unsigned prepared_back = _prepared_back.get();\n\tQueuedEvent* const ev = _events[prepared_back];\n\tif (!ev)\n\t\treturn;\n\t\n\tassert(!ev->is_prepared());\n\tev->pre_process();\n\tassert(ev->is_prepared());\n\n\t_prepared_back = (prepared_back + 1) % _size;\n\n\t\/\/ If event was blocking, wait for event to being run through the\n\t\/\/ process thread before preparing the next event\n\tif (ev->is_blocking())\n\t\t_blocking_semaphore.wait();\n}\n\n\n} \/\/ namespace Ingen\n\n<commit_msg>Better handling of large patch loading.<commit_after>\/* This file is part of Ingen.\n * Copyright (C) 2007 Dave Robillard <http:\/\/drobilla.net>\n * \n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n * \n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for 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 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <sys\/mman.h>\n#include <iostream>\n#include \"QueuedEventSource.hpp\"\n#include \"QueuedEvent.hpp\"\n#include \"PostProcessor.hpp\"\n#include \"ThreadManager.hpp\"\n#include \"ProcessContext.hpp\"\n\nusing namespace std;\n\nnamespace Ingen {\n\n\nQueuedEventSource::QueuedEventSource(size_t queued_size, size_t stamped_size)\n\t: _front(0)\n\t, _back(0)\n\t, _prepared_back(0)\n\t, _size(queued_size+1)\n\t, _blocking_semaphore(0)\n\t, _full_semaphore(0)\n\t, _stamped_queue(stamped_size)\n{\n\t_events = (QueuedEvent**)calloc(_size, sizeof(QueuedEvent*));\n\n\tmlock(_events, _size * sizeof(QueuedEvent*));\n\n\tThread::set_context(THREAD_PRE_PROCESS);\n\tassert(context() == THREAD_PRE_PROCESS);\n\n\tset_name(\"QueuedEventSource\");\n}\n\n\nQueuedEventSource::~QueuedEventSource()\n{\n\tThread::stop();\n\t\n\tfree(_events);\n}\n\n\n\/** Push an unprepared event onto the queue.\n *\/\nvoid\nQueuedEventSource::push_queued(QueuedEvent* const ev)\n{\n\tassert(!ev->is_prepared());\n\n\tunsigned back = _back.get();\n\tbool full = (((_front.get() - back + _size) % _size) == 1);\n\twhile (full) {\n\t\twhip();\n\t\tcerr << \"WARNING: Event queue full. Waiting...\" << endl;\n\t\t_full_semaphore.wait();\n\t\tback = _back.get();\n\t\tfull = (((_front.get() - back + _size) % _size) == 1);\n\t}\n\t\t\n\tassert(_events[back] == NULL);\n\t_events[back] = ev;\n\t_back = (back + 1) % _size;\n\twhip();\n}\n\n\n\/** Process all events for a cycle.\n *\n * Executed events will be pushed to @a dest.\n *\/\nvoid\nQueuedEventSource::process(PostProcessor& dest, ProcessContext& context)\n{\n\tassert(ThreadManager::current_thread_id() == THREAD_PROCESS);\n\n\tEvent* ev = NULL;\n\n\t\/* Limit the maximum number of queued events to process per cycle. This\n\t * makes the process callback (more) realtime-safe by preventing being\n\t * choked by events coming in faster than they can be processed.\n\t * FIXME: test this and figure out a good value *\/\n\tconst unsigned int MAX_QUEUED_EVENTS = context.nframes() \/ 64;\n\n\tunsigned int num_events_processed = 0;\n\t\n\t\/* FIXME: Merge these next two loops into one *\/\n\n\twhile ((ev = pop_earliest_queued_before(context.end()))) {\n\t\tev->execute(context);\n\t\tdest.push(ev);\n\t\tif (++num_events_processed > MAX_QUEUED_EVENTS)\n\t\t\tbreak;\n\t}\n\t\n\twhile ((ev = pop_earliest_stamped_before(context.end()))) {\n\t\tev->execute(context);\n\t\tdest.push(ev);\n\t\t++num_events_processed;\n\t}\n\n\tif (_full_semaphore.has_waiter()) {\n\t\tconst bool full = (((_front.get() - _back.get() + _size) % _size) == 1);\n\t\tif (!full)\n\t\t\t_full_semaphore.post();\n\t}\n}\n\n\n\/** Pops the prepared event at the front of the prepare queue, if it exists.\n *\n * This method will only pop events that have been prepared, and are\n * stamped before the time passed. In other words, it may return NULL\n * even if there are events pending in the queue. The events returned are\n * actually QueuedEvents, but after this they are \"normal\" events and the\n * engine deals with them just like a realtime in-band event. The engine will\n * not use the timestamps of the returned events in any way, since it is free\n * to execute these non-time-stamped events whenever it wants (at whatever rate\n * it wants).\n *\/\nEvent*\nQueuedEventSource::pop_earliest_queued_before(const SampleCount time)\n{\n\tassert(ThreadManager::current_thread_id() == THREAD_PROCESS);\n\n\tconst unsigned front = _front.get();\n\tQueuedEvent* const front_event = _events[front];\n\t\n\t\/\/ Pop\n\tif (front_event && front_event->is_prepared() && front_event->time() < time) {\n\t\t_events[front] = NULL;\n\t\t_front = (front + 1) % _size;\n\t\treturn front_event;\n\t} else {\n\t\treturn NULL;\n\t}\n}\n\n\n\/\/ Private \/\/\n\n\n\/** Pre-process a single event *\/\nvoid\nQueuedEventSource::_whipped()\n{\n\tconst unsigned prepared_back = _prepared_back.get();\n\tQueuedEvent* const ev = _events[prepared_back];\n\tif (!ev)\n\t\treturn;\n\t\n\tassert(!ev->is_prepared());\n\tev->pre_process();\n\tassert(ev->is_prepared());\n\n\t_prepared_back = (prepared_back + 1) % _size;\n\n\t\/\/ If event was blocking, wait for event to being run through the\n\t\/\/ process thread before preparing the next event\n\tif (ev->is_blocking())\n\t\t_blocking_semaphore.wait();\n}\n\n\n} \/\/ namespace Ingen\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ENTT_ENTITY_RUNTIME_VIEW_HPP\n#define ENTT_ENTITY_RUNTIME_VIEW_HPP\n\n\n#include <iterator>\n#include <cassert>\n#include <vector>\n#include <utility>\n#include <algorithm>\n#include <type_traits>\n#include \"..\/config\/config.h\"\n#include \"sparse_set.hpp\"\n#include \"entity.hpp\"\n#include \"fwd.hpp\"\n\n\nnamespace entt {\n\n\n\/**\n * @brief Runtime view.\n *\n * Runtime views iterate over those entities that have at least all the given\n * components in their bags. During initialization, a runtime view looks at the\n * number of entities available for each component and picks up a reference to\n * the smallest set of candidate entities in order to get a performance boost\n * when iterate.<br\/>\n * Order of elements during iterations are highly dependent on the order of the\n * underlying data structures. See sparse_set and its specializations for more\n * details.\n *\n * @b Important\n *\n * Iterators aren't invalidated if:\n *\n * * New instances of the given components are created and assigned to entities.\n * * The entity currently pointed is modified (as an example, if one of the\n * given components is removed from the entity to which the iterator points).\n * * The entity currently pointed is destroyed.\n *\n * In all the other cases, modifying the pools of the given components in any\n * way invalidates all the iterators and using them results in undefined\n * behavior.\n *\n * @note\n * Views share references to the underlying data structures of the registry that\n * generated them. Therefore any change to the entities and to the components\n * made by means of the registry are immediately reflected by the views, unless\n * a pool was missing when the view was built (in this case, the view won't\n * have a valid reference and won't be updated accordingly).\n *\n * @warning\n * Lifetime of a view must overcome the one of the registry that generated it.\n * In any other case, attempting to use a view results in undefined behavior.\n *\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nclass basic_runtime_view {\n \/*! @brief A registry is allowed to create views. *\/\n friend class basic_registry<Entity>;\n\n using underlying_iterator_type = typename sparse_set<Entity>::iterator_type;\n using traits_type = entt_traits<std::underlying_type_t<Entity>>;\n\n class iterator {\n friend class basic_runtime_view<Entity>;\n\n iterator(underlying_iterator_type first, underlying_iterator_type last, const sparse_set<Entity> * const *others, const sparse_set<Entity> * const *length) ENTT_NOEXCEPT\n : begin{first},\n end{last},\n from{others},\n to{length}\n {\n if(begin != end && !valid()) {\n ++(*this);\n }\n }\n\n bool valid() const ENTT_NOEXCEPT {\n const auto entt = *begin;\n const auto sz = size_type(to_integer(entt) & traits_type::entity_mask);\n\n return std::all_of(from, to, [entt](const auto *view) {\n return view->has(entt);\n });\n }\n\n public:\n using difference_type = typename underlying_iterator_type::difference_type;\n using value_type = typename underlying_iterator_type::value_type;\n using pointer = typename underlying_iterator_type::pointer;\n using reference = typename underlying_iterator_type::reference;\n using iterator_category = std::forward_iterator_tag;\n\n iterator() ENTT_NOEXCEPT = default;\n\n iterator & operator++() ENTT_NOEXCEPT {\n return (++begin != end && !valid()) ? ++(*this) : *this;\n }\n\n iterator operator++(int) ENTT_NOEXCEPT {\n iterator orig = *this;\n return ++(*this), orig;\n }\n\n bool operator==(const iterator &other) const ENTT_NOEXCEPT {\n return other.begin == begin;\n }\n\n bool operator!=(const iterator &other) const ENTT_NOEXCEPT {\n return !(*this == other);\n }\n\n pointer operator->() const ENTT_NOEXCEPT {\n return begin.operator->();\n }\n\n reference operator*() const ENTT_NOEXCEPT {\n return *operator->();\n }\n\n private:\n underlying_iterator_type begin;\n underlying_iterator_type end;\n const sparse_set<Entity> * const *from;\n const sparse_set<Entity> * const *to;\n };\n\n basic_runtime_view(std::vector<const sparse_set<Entity> *> others) ENTT_NOEXCEPT\n : pools{std::move(others)}\n {\n const auto it = std::min_element(pools.begin(), pools.end(), [](const auto *lhs, const auto *rhs) {\n return (!lhs && rhs) || (lhs && rhs && lhs->size() < rhs->size());\n });\n\n \/\/ brings the best candidate (if any) on front of the vector\n std::rotate(pools.begin(), it, pools.end());\n }\n\n bool valid() const ENTT_NOEXCEPT {\n return !pools.empty() && pools.front();\n }\n\npublic:\n \/*! @brief Underlying entity identifier. *\/\n using entity_type = typename sparse_set<Entity>::entity_type;\n \/*! @brief Unsigned integer type. *\/\n using size_type = typename sparse_set<Entity>::size_type;\n \/*! @brief Input iterator type. *\/\n using iterator_type = iterator;\n\n \/**\n * @brief Estimates the number of entities that have the given components.\n * @return Estimated number of entities that have the given components.\n *\/\n size_type size() const ENTT_NOEXCEPT {\n return valid() ? pools.front()->size() : size_type{};\n }\n\n \/**\n * @brief Checks if the view is definitely empty.\n * @return True if the view is definitely empty, false otherwise.\n *\/\n bool empty() const ENTT_NOEXCEPT {\n return !valid() || pools.front()->empty();\n }\n\n \/**\n * @brief Returns an iterator to the first entity that has the given\n * components.\n *\n * The returned iterator points to the first entity that has the given\n * components. If the view is empty, the returned iterator will be equal to\n * `end()`.\n *\n * @note\n * Input iterators stay true to the order imposed to the underlying data\n * structures.\n *\n * @return An iterator to the first entity that has the given components.\n *\/\n iterator_type begin() const ENTT_NOEXCEPT {\n iterator_type it{};\n\n if(valid()) {\n const auto &pool = *pools.front();\n const auto * const *data = pools.data();\n it = { pool.begin(), pool.end(), data + 1, data + pools.size() };\n }\n\n return it;\n }\n\n \/**\n * @brief Returns an iterator that is past the last entity that has the\n * given components.\n *\n * The returned iterator points to the entity following the last entity that\n * has the given components. Attempting to dereference the returned iterator\n * results in undefined behavior.\n *\n * @note\n * Input iterators stay true to the order imposed to the underlying data\n * structures.\n *\n * @return An iterator to the entity following the last entity that has the\n * given components.\n *\/\n iterator_type end() const ENTT_NOEXCEPT {\n iterator_type it{};\n\n if(valid()) {\n const auto &pool = *pools.front();\n it = { pool.end(), pool.end(), nullptr, nullptr };\n }\n\n return it;\n }\n\n \/**\n * @brief Checks if a view contains an entity.\n * @param entt A valid entity identifier.\n * @return True if the view contains the given entity, false otherwise.\n *\/\n bool contains(const entity_type entt) const ENTT_NOEXCEPT {\n return valid() && std::all_of(pools.cbegin(), pools.cend(), [entt](const auto *view) {\n return view->find(entt) != view->end();\n });\n }\n\n \/**\n * @brief Iterates entities and applies the given function object to them.\n *\n * The function object is invoked for each entity. It is provided only with\n * the entity itself. To get the components, users can use the registry with\n * which the view was built.<br\/>\n * The signature of the function should be equivalent to the following:\n *\n * @code{.cpp}\n * void(const entity_type);\n * @endcode\n *\n * @tparam Func Type of the function object to invoke.\n * @param func A valid function object.\n *\/\n template<typename Func>\n void each(Func func) const {\n std::for_each(begin(), end(), func);\n }\n\nprivate:\n std::vector<const sparse_set<Entity> *> pools;\n};\n\n\n}\n\n\n#endif \/\/ ENTT_ENTITY_RUNTIME_VIEW_HPP\n<commit_msg>cleanup<commit_after>#ifndef ENTT_ENTITY_RUNTIME_VIEW_HPP\n#define ENTT_ENTITY_RUNTIME_VIEW_HPP\n\n\n#include <iterator>\n#include <cassert>\n#include <vector>\n#include <utility>\n#include <algorithm>\n#include <type_traits>\n#include \"..\/config\/config.h\"\n#include \"sparse_set.hpp\"\n#include \"entity.hpp\"\n#include \"fwd.hpp\"\n\n\nnamespace entt {\n\n\n\/**\n * @brief Runtime view.\n *\n * Runtime views iterate over those entities that have at least all the given\n * components in their bags. During initialization, a runtime view looks at the\n * number of entities available for each component and picks up a reference to\n * the smallest set of candidate entities in order to get a performance boost\n * when iterate.<br\/>\n * Order of elements during iterations are highly dependent on the order of the\n * underlying data structures. See sparse_set and its specializations for more\n * details.\n *\n * @b Important\n *\n * Iterators aren't invalidated if:\n *\n * * New instances of the given components are created and assigned to entities.\n * * The entity currently pointed is modified (as an example, if one of the\n * given components is removed from the entity to which the iterator points).\n * * The entity currently pointed is destroyed.\n *\n * In all the other cases, modifying the pools of the given components in any\n * way invalidates all the iterators and using them results in undefined\n * behavior.\n *\n * @note\n * Views share references to the underlying data structures of the registry that\n * generated them. Therefore any change to the entities and to the components\n * made by means of the registry are immediately reflected by the views, unless\n * a pool was missing when the view was built (in this case, the view won't\n * have a valid reference and won't be updated accordingly).\n *\n * @warning\n * Lifetime of a view must overcome the one of the registry that generated it.\n * In any other case, attempting to use a view results in undefined behavior.\n *\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nclass basic_runtime_view {\n \/*! @brief A registry is allowed to create views. *\/\n friend class basic_registry<Entity>;\n\n using underlying_iterator_type = typename sparse_set<Entity>::iterator_type;\n using traits_type = entt_traits<std::underlying_type_t<Entity>>;\n\n class iterator {\n friend class basic_runtime_view<Entity>;\n\n iterator(underlying_iterator_type first, underlying_iterator_type last, const sparse_set<Entity> * const *others, const sparse_set<Entity> * const *length) ENTT_NOEXCEPT\n : begin{first},\n end{last},\n from{others},\n to{length}\n {\n if(begin != end && !valid()) {\n ++(*this);\n }\n }\n\n bool valid() const ENTT_NOEXCEPT {\n return std::all_of(from, to, [entt = *begin](const auto *view) {\n return view->has(entt);\n });\n }\n\n public:\n using difference_type = typename underlying_iterator_type::difference_type;\n using value_type = typename underlying_iterator_type::value_type;\n using pointer = typename underlying_iterator_type::pointer;\n using reference = typename underlying_iterator_type::reference;\n using iterator_category = std::forward_iterator_tag;\n\n iterator() ENTT_NOEXCEPT = default;\n\n iterator & operator++() ENTT_NOEXCEPT {\n return (++begin != end && !valid()) ? ++(*this) : *this;\n }\n\n iterator operator++(int) ENTT_NOEXCEPT {\n iterator orig = *this;\n return ++(*this), orig;\n }\n\n bool operator==(const iterator &other) const ENTT_NOEXCEPT {\n return other.begin == begin;\n }\n\n bool operator!=(const iterator &other) const ENTT_NOEXCEPT {\n return !(*this == other);\n }\n\n pointer operator->() const ENTT_NOEXCEPT {\n return begin.operator->();\n }\n\n reference operator*() const ENTT_NOEXCEPT {\n return *operator->();\n }\n\n private:\n underlying_iterator_type begin;\n underlying_iterator_type end;\n const sparse_set<Entity> * const *from;\n const sparse_set<Entity> * const *to;\n };\n\n basic_runtime_view(std::vector<const sparse_set<Entity> *> others) ENTT_NOEXCEPT\n : pools{std::move(others)}\n {\n const auto it = std::min_element(pools.begin(), pools.end(), [](const auto *lhs, const auto *rhs) {\n return (!lhs && rhs) || (lhs && rhs && lhs->size() < rhs->size());\n });\n\n \/\/ brings the best candidate (if any) on front of the vector\n std::rotate(pools.begin(), it, pools.end());\n }\n\n bool valid() const ENTT_NOEXCEPT {\n return !pools.empty() && pools.front();\n }\n\npublic:\n \/*! @brief Underlying entity identifier. *\/\n using entity_type = typename sparse_set<Entity>::entity_type;\n \/*! @brief Unsigned integer type. *\/\n using size_type = typename sparse_set<Entity>::size_type;\n \/*! @brief Input iterator type. *\/\n using iterator_type = iterator;\n\n \/**\n * @brief Estimates the number of entities that have the given components.\n * @return Estimated number of entities that have the given components.\n *\/\n size_type size() const ENTT_NOEXCEPT {\n return valid() ? pools.front()->size() : size_type{};\n }\n\n \/**\n * @brief Checks if the view is definitely empty.\n * @return True if the view is definitely empty, false otherwise.\n *\/\n bool empty() const ENTT_NOEXCEPT {\n return !valid() || pools.front()->empty();\n }\n\n \/**\n * @brief Returns an iterator to the first entity that has the given\n * components.\n *\n * The returned iterator points to the first entity that has the given\n * components. If the view is empty, the returned iterator will be equal to\n * `end()`.\n *\n * @note\n * Input iterators stay true to the order imposed to the underlying data\n * structures.\n *\n * @return An iterator to the first entity that has the given components.\n *\/\n iterator_type begin() const ENTT_NOEXCEPT {\n iterator_type it{};\n\n if(valid()) {\n const auto &pool = *pools.front();\n const auto * const *data = pools.data();\n it = { pool.begin(), pool.end(), data + 1, data + pools.size() };\n }\n\n return it;\n }\n\n \/**\n * @brief Returns an iterator that is past the last entity that has the\n * given components.\n *\n * The returned iterator points to the entity following the last entity that\n * has the given components. Attempting to dereference the returned iterator\n * results in undefined behavior.\n *\n * @note\n * Input iterators stay true to the order imposed to the underlying data\n * structures.\n *\n * @return An iterator to the entity following the last entity that has the\n * given components.\n *\/\n iterator_type end() const ENTT_NOEXCEPT {\n iterator_type it{};\n\n if(valid()) {\n const auto &pool = *pools.front();\n it = { pool.end(), pool.end(), nullptr, nullptr };\n }\n\n return it;\n }\n\n \/**\n * @brief Checks if a view contains an entity.\n * @param entt A valid entity identifier.\n * @return True if the view contains the given entity, false otherwise.\n *\/\n bool contains(const entity_type entt) const ENTT_NOEXCEPT {\n return valid() && std::all_of(pools.cbegin(), pools.cend(), [entt](const auto *view) {\n return view->find(entt) != view->end();\n });\n }\n\n \/**\n * @brief Iterates entities and applies the given function object to them.\n *\n * The function object is invoked for each entity. It is provided only with\n * the entity itself. To get the components, users can use the registry with\n * which the view was built.<br\/>\n * The signature of the function should be equivalent to the following:\n *\n * @code{.cpp}\n * void(const entity_type);\n * @endcode\n *\n * @tparam Func Type of the function object to invoke.\n * @param func A valid function object.\n *\/\n template<typename Func>\n void each(Func func) const {\n std::for_each(begin(), end(), func);\n }\n\nprivate:\n std::vector<const sparse_set<Entity> *> pools;\n};\n\n\n}\n\n\n#endif \/\/ ENTT_ENTITY_RUNTIME_VIEW_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef ENTT_ENTITY_RUNTIME_VIEW_HPP\n#define ENTT_ENTITY_RUNTIME_VIEW_HPP\n\n\n#include <iterator>\n#include <vector>\n#include <utility>\n#include <algorithm>\n#include <type_traits>\n#include \"..\/config\/config.h\"\n#include \"sparse_set.hpp\"\n#include \"fwd.hpp\"\n\n\nnamespace entt {\n\n\n\/**\n * @brief Runtime view.\n *\n * Runtime views iterate over those entities that have at least all the given\n * components in their bags. During initialization, a runtime view looks at the\n * number of entities available for each component and picks up a reference to\n * the smallest set of candidate entities in order to get a performance boost\n * when iterate.<br\/>\n * Order of elements during iterations are highly dependent on the order of the\n * underlying data structures. See sparse_set and its specializations for more\n * details.\n *\n * @b Important\n *\n * Iterators aren't invalidated if:\n *\n * * New instances of the given components are created and assigned to entities.\n * * The entity currently pointed is modified (as an example, if one of the\n * given components is removed from the entity to which the iterator points).\n * * The entity currently pointed is destroyed.\n *\n * In all the other cases, modifying the pools of the given components in any\n * way invalidates all the iterators and using them results in undefined\n * behavior.\n *\n * @note\n * Views share references to the underlying data structures of the registry that\n * generated them. Therefore any change to the entities and to the components\n * made by means of the registry are immediately reflected by the views, unless\n * a pool was missing when the view was built (in this case, the view won't\n * have a valid reference and won't be updated accordingly).\n *\n * @warning\n * Lifetime of a view must not overcome that of the registry that generated it.\n * In any other case, attempting to use a view results in undefined behavior.\n *\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nclass basic_runtime_view {\n \/*! @brief A registry is allowed to create views. *\/\n friend class basic_registry<Entity>;\n\n using underlying_iterator = typename sparse_set<Entity>::iterator;\n\n class view_iterator final {\n friend class basic_runtime_view<Entity>;\n\n view_iterator(const std::vector<const sparse_set<Entity> *> &cpools, const std::vector<const sparse_set<Entity> *> &ignore, underlying_iterator curr) ENTT_NOEXCEPT\n : pools{&cpools},\n filter{&ignore},\n it{curr}\n {\n if(it != (*pools)[0]->end() && !valid()) {\n ++(*this);\n }\n }\n\n [[nodiscard]] bool valid() const {\n return std::all_of(pools->begin()++, pools->end(), [entt = *it](const auto *curr) { return curr->contains(entt); })\n && std::none_of(filter->cbegin(), filter->cend(), [entt = *it](const auto *curr) { return curr && curr->contains(entt); });\n }\n\n public:\n using difference_type = typename underlying_iterator::difference_type;\n using value_type = typename underlying_iterator::value_type;\n using pointer = typename underlying_iterator::pointer;\n using reference = typename underlying_iterator::reference;\n using iterator_category = std::bidirectional_iterator_tag;\n\n view_iterator() ENTT_NOEXCEPT = default;\n\n view_iterator & operator++() {\n while(++it != (*pools)[0]->end() && !valid());\n return *this;\n }\n\n view_iterator operator++(int) {\n view_iterator orig = *this;\n return ++(*this), orig;\n }\n\n view_iterator & operator--() ENTT_NOEXCEPT {\n while(--it != (*pools)[0]->begin() && !valid());\n return *this;\n }\n\n view_iterator operator--(int) ENTT_NOEXCEPT {\n view_iterator orig = *this;\n return operator--(), orig;\n }\n\n [[nodiscard]] bool operator==(const view_iterator &other) const ENTT_NOEXCEPT {\n return other.it == it;\n }\n\n [[nodiscard]] bool operator!=(const view_iterator &other) const ENTT_NOEXCEPT {\n return !(*this == other);\n }\n\n [[nodiscard]] pointer operator->() const {\n return it.operator->();\n }\n\n [[nodiscard]] reference operator*() const {\n return *operator->();\n }\n\n private:\n const std::vector<const sparse_set<Entity> *> *pools;\n const std::vector<const sparse_set<Entity> *> *filter;\n underlying_iterator it;\n };\n\n basic_runtime_view(std::vector<const sparse_set<Entity> *> cpools, std::vector<const sparse_set<Entity> *> exclude) ENTT_NOEXCEPT\n : pools{std::move(cpools)},\n filter{std::move(exclude)}\n {\n const auto it = std::min_element(pools.begin(), pools.end(), [](const auto *lhs, const auto *rhs) {\n return (!lhs && rhs) || (lhs && rhs && lhs->size() < rhs->size());\n });\n\n \/\/ brings the best candidate (if any) on front of the vector\n std::rotate(pools.begin(), it, pools.end());\n }\n\n [[nodiscard]] bool valid() const {\n return !pools.empty() && pools.front();\n }\n\npublic:\n \/*! @brief Underlying entity identifier. *\/\n using entity_type = Entity;\n \/*! @brief Unsigned integer type. *\/\n using size_type = std::size_t;\n \/*! @brief Bidirectional iterator type. *\/\n using iterator = view_iterator;\n\n \/**\n * @brief Estimates the number of entities that have the given components.\n * @return Estimated number of entities that have the given components.\n *\/\n [[nodiscard]] size_type size() const {\n return valid() ? pools.front()->size() : size_type{};\n }\n\n \/**\n * @brief Checks if the view is definitely empty.\n * @return True if the view is definitely empty, false otherwise.\n *\/\n [[nodiscard]] bool empty() const {\n return !valid() || pools.front()->empty();\n }\n\n \/**\n * @brief Returns an iterator to the first entity that has the given\n * components.\n *\n * The returned iterator points to the first entity that has the given\n * components. If the view is empty, the returned iterator will be equal to\n * `end()`.\n *\n * @note\n * Iterators stay true to the order imposed to the underlying data\n * structures.\n *\n * @return An iterator to the first entity that has the given components.\n *\/\n [[nodiscard]] iterator begin() const {\n return valid() ? iterator{pools, filter, pools[0]->begin()} : iterator{};\n }\n\n \/**\n * @brief Returns an iterator that is past the last entity that has the\n * given components.\n *\n * The returned iterator points to the entity following the last entity that\n * has the given components. Attempting to dereference the returned iterator\n * results in undefined behavior.\n *\n * @note\n * Iterators stay true to the order imposed to the underlying data\n * structures.\n *\n * @return An iterator to the entity following the last entity that has the\n * given components.\n *\/\n [[nodiscard]] iterator end() const {\n return valid() ? iterator{pools, filter, pools[0]->end()} : iterator{};\n }\n\n \/**\n * @brief Checks if a view contains an entity.\n * @param entt A valid entity identifier.\n * @return True if the view contains the given entity, false otherwise.\n *\/\n [[nodiscard]] bool contains(const entity_type entt) const {\n return valid() && std::all_of(pools.cbegin(), pools.cend(), [entt](const auto *curr) { return curr->contains(entt); })\n && std::none_of(filter.cbegin(), filter.cend(), [entt](const auto *curr) { return curr && curr->contains(entt); });\n }\n\n \/**\n * @brief Iterates entities and applies the given function object to them.\n *\n * The function object is invoked for each entity. It is provided only with\n * the entity itself. To get the components, users can use the registry with\n * which the view was built.<br\/>\n * The signature of the function should be equivalent to the following:\n *\n * @code{.cpp}\n * void(const entity_type);\n * @endcode\n *\n * @tparam Func Type of the function object to invoke.\n * @param func A valid function object.\n *\/\n template<typename Func>\n void each(Func func) const {\n for(const auto entity: *this) {\n func(entity);\n }\n }\n\nprivate:\n std::vector<const sparse_set<Entity> *> pools;\n std::vector<const sparse_set<Entity> *> filter;\n};\n\n\n}\n\n\n#endif\n<commit_msg>runtime view: suppress warnings for shadow variables<commit_after>#ifndef ENTT_ENTITY_RUNTIME_VIEW_HPP\n#define ENTT_ENTITY_RUNTIME_VIEW_HPP\n\n\n#include <iterator>\n#include <vector>\n#include <utility>\n#include <algorithm>\n#include <type_traits>\n#include \"..\/config\/config.h\"\n#include \"sparse_set.hpp\"\n#include \"fwd.hpp\"\n\n\nnamespace entt {\n\n\n\/**\n * @brief Runtime view.\n *\n * Runtime views iterate over those entities that have at least all the given\n * components in their bags. During initialization, a runtime view looks at the\n * number of entities available for each component and picks up a reference to\n * the smallest set of candidate entities in order to get a performance boost\n * when iterate.<br\/>\n * Order of elements during iterations are highly dependent on the order of the\n * underlying data structures. See sparse_set and its specializations for more\n * details.\n *\n * @b Important\n *\n * Iterators aren't invalidated if:\n *\n * * New instances of the given components are created and assigned to entities.\n * * The entity currently pointed is modified (as an example, if one of the\n * given components is removed from the entity to which the iterator points).\n * * The entity currently pointed is destroyed.\n *\n * In all the other cases, modifying the pools of the given components in any\n * way invalidates all the iterators and using them results in undefined\n * behavior.\n *\n * @note\n * Views share references to the underlying data structures of the registry that\n * generated them. Therefore any change to the entities and to the components\n * made by means of the registry are immediately reflected by the views, unless\n * a pool was missing when the view was built (in this case, the view won't\n * have a valid reference and won't be updated accordingly).\n *\n * @warning\n * Lifetime of a view must not overcome that of the registry that generated it.\n * In any other case, attempting to use a view results in undefined behavior.\n *\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nclass basic_runtime_view {\n \/*! @brief A registry is allowed to create views. *\/\n friend class basic_registry<Entity>;\n\n using underlying_iterator = typename sparse_set<Entity>::iterator;\n\n class view_iterator final {\n friend class basic_runtime_view<Entity>;\n\n view_iterator(const std::vector<const sparse_set<Entity> *> &cpools, const std::vector<const sparse_set<Entity> *> &ignore, underlying_iterator curr) ENTT_NOEXCEPT\n : pools{&cpools},\n filter{&ignore},\n it{curr}\n {\n if(it != (*pools)[0]->end() && !valid()) {\n ++(*this);\n }\n }\n\n [[nodiscard]] bool valid() const {\n return std::all_of(pools->begin()++, pools->end(), [entt = *it](const auto *curr) { return curr->contains(entt); })\n && std::none_of(filter->cbegin(), filter->cend(), [entt = *it](const auto *curr) { return curr && curr->contains(entt); });\n }\n\n public:\n using difference_type = typename underlying_iterator::difference_type;\n using value_type = typename underlying_iterator::value_type;\n using pointer = typename underlying_iterator::pointer;\n using reference = typename underlying_iterator::reference;\n using iterator_category = std::bidirectional_iterator_tag;\n\n view_iterator() ENTT_NOEXCEPT = default;\n\n view_iterator & operator++() {\n while(++it != (*pools)[0]->end() && !valid());\n return *this;\n }\n\n view_iterator operator++(int) {\n view_iterator orig = *this;\n return ++(*this), orig;\n }\n\n view_iterator & operator--() ENTT_NOEXCEPT {\n while(--it != (*pools)[0]->begin() && !valid());\n return *this;\n }\n\n view_iterator operator--(int) ENTT_NOEXCEPT {\n view_iterator orig = *this;\n return operator--(), orig;\n }\n\n [[nodiscard]] bool operator==(const view_iterator &other) const ENTT_NOEXCEPT {\n return other.it == it;\n }\n\n [[nodiscard]] bool operator!=(const view_iterator &other) const ENTT_NOEXCEPT {\n return !(*this == other);\n }\n\n [[nodiscard]] pointer operator->() const {\n return it.operator->();\n }\n\n [[nodiscard]] reference operator*() const {\n return *operator->();\n }\n\n private:\n const std::vector<const sparse_set<Entity> *> *pools;\n const std::vector<const sparse_set<Entity> *> *filter;\n underlying_iterator it;\n };\n\n basic_runtime_view(std::vector<const sparse_set<Entity> *> cpools, std::vector<const sparse_set<Entity> *> epools) ENTT_NOEXCEPT\n : pools{std::move(cpools)},\n filter{std::move(epools)}\n {\n const auto it = std::min_element(pools.begin(), pools.end(), [](const auto *lhs, const auto *rhs) {\n return (!lhs && rhs) || (lhs && rhs && lhs->size() < rhs->size());\n });\n\n \/\/ brings the best candidate (if any) on front of the vector\n std::rotate(pools.begin(), it, pools.end());\n }\n\n [[nodiscard]] bool valid() const {\n return !pools.empty() && pools.front();\n }\n\npublic:\n \/*! @brief Underlying entity identifier. *\/\n using entity_type = Entity;\n \/*! @brief Unsigned integer type. *\/\n using size_type = std::size_t;\n \/*! @brief Bidirectional iterator type. *\/\n using iterator = view_iterator;\n\n \/**\n * @brief Estimates the number of entities that have the given components.\n * @return Estimated number of entities that have the given components.\n *\/\n [[nodiscard]] size_type size() const {\n return valid() ? pools.front()->size() : size_type{};\n }\n\n \/**\n * @brief Checks if the view is definitely empty.\n * @return True if the view is definitely empty, false otherwise.\n *\/\n [[nodiscard]] bool empty() const {\n return !valid() || pools.front()->empty();\n }\n\n \/**\n * @brief Returns an iterator to the first entity that has the given\n * components.\n *\n * The returned iterator points to the first entity that has the given\n * components. If the view is empty, the returned iterator will be equal to\n * `end()`.\n *\n * @note\n * Iterators stay true to the order imposed to the underlying data\n * structures.\n *\n * @return An iterator to the first entity that has the given components.\n *\/\n [[nodiscard]] iterator begin() const {\n return valid() ? iterator{pools, filter, pools[0]->begin()} : iterator{};\n }\n\n \/**\n * @brief Returns an iterator that is past the last entity that has the\n * given components.\n *\n * The returned iterator points to the entity following the last entity that\n * has the given components. Attempting to dereference the returned iterator\n * results in undefined behavior.\n *\n * @note\n * Iterators stay true to the order imposed to the underlying data\n * structures.\n *\n * @return An iterator to the entity following the last entity that has the\n * given components.\n *\/\n [[nodiscard]] iterator end() const {\n return valid() ? iterator{pools, filter, pools[0]->end()} : iterator{};\n }\n\n \/**\n * @brief Checks if a view contains an entity.\n * @param entt A valid entity identifier.\n * @return True if the view contains the given entity, false otherwise.\n *\/\n [[nodiscard]] bool contains(const entity_type entt) const {\n return valid() && std::all_of(pools.cbegin(), pools.cend(), [entt](const auto *curr) { return curr->contains(entt); })\n && std::none_of(filter.cbegin(), filter.cend(), [entt](const auto *curr) { return curr && curr->contains(entt); });\n }\n\n \/**\n * @brief Iterates entities and applies the given function object to them.\n *\n * The function object is invoked for each entity. It is provided only with\n * the entity itself. To get the components, users can use the registry with\n * which the view was built.<br\/>\n * The signature of the function should be equivalent to the following:\n *\n * @code{.cpp}\n * void(const entity_type);\n * @endcode\n *\n * @tparam Func Type of the function object to invoke.\n * @param func A valid function object.\n *\/\n template<typename Func>\n void each(Func func) const {\n for(const auto entity: *this) {\n func(entity);\n }\n }\n\nprivate:\n std::vector<const sparse_set<Entity> *> pools;\n std::vector<const sparse_set<Entity> *> filter;\n};\n\n\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"updater.h\"\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QProcess>\n#include <QtXml\/QDomDocument>\n\nusing namespace updatesChecker;\n\nUpdater::Updater(QObject *parent)\n\t: QObject(parent)\n\t, mUpdaterProcess(nullptr)\n{\n}\n\nvoid Updater::checkForNewVersion()\n{\n\texecuteUpdater(\"--checkupdates\");\n}\n\nvoid Updater::start()\n{\n\texecuteUpdater(\"--updater\");\n}\n\nvoid Updater::executeUpdater(QString const &mode)\n{\n\tmUpdaterProcess = new QProcess(this);\n\tmUpdaterProcess->setWorkingDirectory(QCoreApplication::applicationDirPath());\n\tconnect(mUpdaterProcess, SIGNAL(finished(int)), this, SLOT(readAnswer()));\n\n\tif (mode == \"--updater\") {\n\t\tmUpdaterProcess->startDetached(QCoreApplication::applicationDirPath() + \"\/maintenance\", {mode});\n\t} else {\n\t\tmUpdaterProcess->start(QCoreApplication::applicationDirPath() + \"\/maintenance\", {mode});\n\t}\n}\n\nvoid Updater::readAnswer()\n{\n\tQString const output = mUpdaterProcess->readAllStandardOutput();\n\t\/\/ Checking that output is a valid XML\n\tQDomDocument parser;\n\tparser.setContent(output);\n\tif (!output.isEmpty() && !parser.isNull()) {\n\t\temit newVersionAvailable();\n\t} else {\n\t\temit noNewVersionAvailable();\n\t}\n}\n<commit_msg>Added updater output logging<commit_after>#include \"updater.h\"\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QProcess>\n#include <QtXml\/QDomDocument>\n\n#include <qrkernel\/logging.h>\n\nusing namespace updatesChecker;\n\nUpdater::Updater(QObject *parent)\n\t: QObject(parent)\n\t, mUpdaterProcess(nullptr)\n{\n}\n\nvoid Updater::checkForNewVersion()\n{\n\texecuteUpdater(\"--checkupdates\");\n}\n\nvoid Updater::start()\n{\n\texecuteUpdater(\"--updater\");\n}\n\nvoid Updater::executeUpdater(QString const &mode)\n{\n\tmUpdaterProcess = new QProcess(this);\n\tmUpdaterProcess->setWorkingDirectory(QCoreApplication::applicationDirPath());\n\tconnect(mUpdaterProcess, SIGNAL(finished(int)), this, SLOT(readAnswer()));\n\n\tif (mode == \"--updater\") {\n\t\tmUpdaterProcess->startDetached(QCoreApplication::applicationDirPath() + \"\/maintenance\", {mode});\n\t} else {\n\t\tmUpdaterProcess->start(QCoreApplication::applicationDirPath() + \"\/maintenance\", {mode});\n\t}\n}\n\nvoid Updater::readAnswer()\n{\n\tQString const output = mUpdaterProcess->readAllStandardOutput();\n\t\/\/ Checking that output is a valid XML\n\tQDomDocument parser;\n\tparser.setContent(output);\n\tif (!output.isEmpty() && !parser.isNull()) {\n\t\tQLOG_INFO() << \"Updater output:\" << output;\n\t\temit newVersionAvailable();\n\t} else {\n\t\temit noNewVersionAvailable();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\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 files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n#include <ode\/odeconfig.h>\n#include \"config.h\"\n#include <ode\/memory.h>\n#include <ode\/error.h>\n\n\nstatic dAllocFunction *allocfn = 0;\nstatic dReallocFunction *reallocfn = 0;\nstatic dFreeFunction *freefn = 0;\n\n\n\nvoid dSetAllocHandler (dAllocFunction *fn)\n{\n allocfn = fn;\n}\n\n\nvoid dSetReallocHandler (dReallocFunction *fn)\n{\n reallocfn = fn;\n}\n\n\nvoid dSetFreeHandler (dFreeFunction *fn)\n{\n freefn = fn;\n}\n\n\ndAllocFunction *dGetAllocHandler()\n{\n return allocfn;\n}\n\n\ndReallocFunction *dGetReallocHandler()\n{\n return reallocfn;\n}\n\n\ndFreeFunction *dGetFreeHandler()\n{\n return freefn;\n}\n\n\nvoid * dAlloc (size_t size)\n{\n if (allocfn) return allocfn (size); else return malloc (size);\n}\n\n\nvoid * dRealloc (void *ptr, size_t oldsize, size_t newsize)\n{\n if (reallocfn) return reallocfn (ptr,oldsize,newsize);\n else return realloc (ptr,newsize);\n}\n\n\nvoid dFree (void *ptr, size_t size)\n{\n if (!ptr) return;\n if (freefn) freefn (ptr,size); else free (ptr);\n}\n<commit_msg>Added guard for AC_FUNC_MALLOC and AC_FUNC_REALLOC in memory.cpp, the macros break cross compilation Linux-to-Windows by defining malloc and realloc as rpl_malloc and rpl_realloc respectively<commit_after>\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\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 files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n#include <ode\/odeconfig.h>\n#include \"config.h\"\n#include <ode\/memory.h>\n#include <ode\/error.h>\n\n\nstatic dAllocFunction *allocfn = 0;\nstatic dReallocFunction *reallocfn = 0;\nstatic dFreeFunction *freefn = 0;\n\n#ifdef __MINGW32__\n\/* \n this is a guard against AC_FUNC_MALLOC and AC_FUNC_REALLOC\n which break cross compilation, no issues in native MSYS.\n*\/\n#undef malloc\n#undef realloc\n#endif\n\nvoid dSetAllocHandler (dAllocFunction *fn)\n{\n allocfn = fn;\n}\n\n\nvoid dSetReallocHandler (dReallocFunction *fn)\n{\n reallocfn = fn;\n}\n\n\nvoid dSetFreeHandler (dFreeFunction *fn)\n{\n freefn = fn;\n}\n\n\ndAllocFunction *dGetAllocHandler()\n{\n return allocfn;\n}\n\n\ndReallocFunction *dGetReallocHandler()\n{\n return reallocfn;\n}\n\n\ndFreeFunction *dGetFreeHandler()\n{\n return freefn;\n}\n\n\nvoid * dAlloc (size_t size)\n{\n if (allocfn) return allocfn (size); else return malloc (size);\n}\n\n\nvoid * dRealloc (void *ptr, size_t oldsize, size_t newsize)\n{\n if (reallocfn) return reallocfn (ptr,oldsize,newsize);\n else return realloc (ptr,newsize);\n}\n\n\nvoid dFree (void *ptr, size_t size)\n{\n if (!ptr) return;\n if (freefn) freefn (ptr,size); else free (ptr);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ the trajectory action server for two wheel robot\n\n\/\/ communication includes\n \/\/ subscribe to topic \"swarm_robot_poses\" with message swarm_robot_poses.msg\n \/\/ subscribe to topic \"two_wheel_poses\" with message two_wheel_poses.msg\n \/\/ publish to topic \"two_wheel_poses_cmd\" with message two_wheel_poses.msg\n \/\/ host a action server \"two_wheel_traj_action\" with message swarm_robot_traj.action\n\n\/\/ there are different wheel trajectories of moving to a target position\n\/\/ Method 1:\n \/\/ first rotating the robot to the direction of the target position\n \/\/ then moving the robot in straight line to the target position\n \/\/ pros:\n \/\/ simple and straightforward wheel position increment calculation\n \/\/ easy to debug the potential problems\n \/\/ cons:\n \/\/ ugly and inefficient to take two movements to moving to the target\n\/\/ Method 2:\n \/\/ the path between start position and target position is circular\n \/\/ the center of the circular path is on the common axis of the two wheels\n \/\/ pros:\n \/\/ taking only one movements to move to the target, much more elegant\n \/\/ two wheel position are linearly interpolated because of this circular path\n \/\/ cons:\n \/\/ a bit difficult to calculate the increment of the wheel positions\n \/\/ difficult to debug the algorithm for the wheel positions\n\n\/\/ for the convenience of wheel position calculation and debug, method 1 is implemented here\n\n\/\/ one significant problem of the controller of two_wheel_robot is that\n \/\/ when one wheel is commanded rotating and the other is remained current position\n \/\/ the static wheel will naturally rotating at the other direction because of inertia\n \/\/ how to solve or avoid this problem? and make position control more precise\n\n#include <ros\/ros.h>\n#include <math.h>\n#include <actionlib\/server\/simple_action_server.h>\n#include <swarm_robot_action\/swarm_robot_trajAction.h>\n#include <swarm_robot_msgs\/two_wheel_poses.h>\n\n\/\/ interpolation parameters, change setup here\nconst double dt = 0.01; \/\/ interpolating resolution\n\/\/ minimal distance with goal position to interpolate\n\/\/ distance small than ds_min will be neglected, cube size of two_wheel_robot is 0.0254\n\/\/ this value should be set very low\nconst double ds_min = 0.001;\n\/\/ half distance of two wheels\n\/\/ not a good way to get this value here\nconst double half_wheel_dist = 0.0177;\n\nclass TwoWheelTrajActionServer {\npublic:\n TwoWheelTrajActionServer(ros::NodeHandle* nodehandle);\n\nprivate:\n void swarmRobotPosesCb(const swarm_robot_msgs::swarm_robot_poses& message_holder);\n void twoWheelPosesCb(const swarm_robot_msgs::two_wheel_poses& message_holder);\n void executeCb(const \n actionlib::SimpleActionServer<swarm_robot_action::swarm_robot_trajAction>::GoalConstPtr& goal);\n\n ros::NodeHandle nh_; \/\/ a node handle is needed\n\n \/\/ declare a subscribers to topic \"swarm_robot_poses\" and \"two_wheel_poses\"\n ros::Subscriber swarm_robot_poses_subscriber;\n ros::Subscriber two_wheel_poses_subscriber;\n \/\/ declare a publisher to topic \"two_wheel_poses_cmd\"\n ros::Publisher two_wheel_poses_cmd_publisher;\n \/\/ declare an action server\n actionlib::SimpleActionServer<swarm_robot_action::swarm_robot_trajAction> as_;\n \n \/\/ messages\n swarm_robot_msgs::swarm_robot_poses robot_poses_msg; \/\/ current robot poses\n swarm_robot_msgs::two_wheel_poses wheel_poses_msg; \/\/ current wheel poses\n swarm_robot_msgs::two_wheel_poses wheel_poses_cmd_msg; \/\/ wheel poses command\n \/\/ for trajectory interpolation\n swarm_robot_msgs::two_wheel_poses wheel_poses_self_rotating;\n swarm_robot_msgs::two_wheel_poses wheel_poses_line_moving;\n \/\/ action messages\n swarm_robot_action::swarm_robot_trajActionGoal goal_;\n swarm_robot_action::swarm_robot_trajActionResult result_;\n swarm_robot_action::swarm_robot_trajActionFeedback feedback_;\n\n \/\/ other variables\n std::string robot_model_name; \/\/ from parameter server\n int robot_quantity; \/\/ from parameter server\n bool b_robot_poses_cb_started;\n bool b_wheel_poses_cb_started;\n};\n\n\/\/ most initialization work will be done here\nTwoWheelTrajActionServer::TwoWheelTrajActionServer(ros::NodeHandle* nodehandle):\n nh_(*nodehandle), \/\/ dereference the pointer and pass the value\n as_(nh_, \"two_wheel_traj_action\", boost::bind(&TwoWheelTrajActionServer::executeCb, this, _1), false)\n{\n ROS_INFO(\"in constructor of TwoWheelTrajActionServer...\");\n\n \/\/ initialize the subscribers\n b_robot_poses_cb_started = false;\n swarm_robot_poses_subscriber = nh_.subscribe(\"swarm_robot_poses\", 1, swarmRobotPosesCb);\n b_poses_callback_started = false;\n two_wheel_poses_subscriber = nh_.subscribe(\"two_wheel_poses\", 1, twoWheelPosesCb);\n \/\/ initialize the publisher\n two_wheel_poses_cmd_publisher = nh_.advertise<swarm_robot_msgs::two_wheel_poses>(\"two_wheel_poses_cmd\", 1);\n\n \/\/ get initialization message of robot swarm from parameter server\n bool get_name, get_quantity;\n get_name = nh_.getParam(\"\/robot_model_name\", robot_model_name);\n get_quantity = nh_.getParam(\"\/robot_quantity\", robot_quantity);\n if (!(get_name && get_quantity))\n return 0; \/\/ return if fail to get parameter\n\n \/\/ make sure topics \"swarm_robot_poses\" and \"two_wheel_poses\" are active\n while (!(b_robot_poses_cb_started && b_wheel_poses_cb_started)) {\n ros::Duration(0.5).sleep();\n ros::spinOnce();\n }\n std::cout << \"topic message from swarm_robot_poses and two_wheel_poses is ready\" << std::endl;\n\n as_.start(); \/\/ start the \"two_wheel_traj_action\"\n}\n\n\/\/ callback for message from topic \"swarm_robot_poses\"\nvoid TwoWheelTrajActionServer::swarmRobotPosesCb(const swarm_robot_msgs::swarm_robot_poses& message_holder) {\n if (!b_robot_poses_cb_started) \/\/ first time to be invoked\n b_robot_poses_cb_started = true;\n robot_poses_msg = message_holder;\n}\n\n\/\/ callback for message from topic \"two_wheel_poses\"\nvoid TwoWheelTrajActionServer::twoWheelPosesCb(const swarm_robot_msgs::two_wheel_poses& message_holder) {\n if (!b_wheel_poses_cb_started) \/\/ first time to be invoked\n b_wheel_poses_cb_started = true;\n wheel_poses_msg = message_holder;\n}\n\n\/\/ most practical work will be done here\nvoid TwoWheelTrajActionServer::executeCb(const actionlib::\n SimpleActionServer<swarm_robot_action::swarm_robot_trajAction>::GoalConstPtr& goal)\n{\n ROS_INFO(\"in executeCb...\");\n\n \/\/ copy the goal message, avoid using \"->\" too much\n double goal_x[] = goal -> x;\n double goal_y[] = goal -> y;\n double goal_time = goal -> time;\n\n\n\n\/\/ messages\nswarm_robot_msgs::swarm_robot_poses robot_poses_msg; \/\/ current robot poses\nswarm_robot_msgs::two_wheel_poses wheel_poses_msg; \/\/ current wheel poses\nswarm_robot_msgs::two_wheel_poses wheel_poses_cmd_msg; \/\/ wheel poses command\n\nswarm_robot_msgs::two_wheel_poses wheel_poses_self_rotating;\nswarm_robot_msgs::two_wheel_poses wheel_poses_line_moving;\n\n\n\n \/\/ the time for this two movements are linearly distributed according to the wheel path\n\n double x_start;\n double y_start;\n double x_end;\n double y_end;\n double distance;\n double angle_start;\n double angle_end;\n double angle_rotate;\n \/\/ calculate the cmd message for each robot\n for (int i=0; i<robot_quantity; i++) {\n x_start = robot_poses_msg.x[i];\n y_start = robot_poses_msg.y[i];\n x_end = goal_x[i];\n y_end = goal_y[i];\n distance = sqrt(pow((x_end - x_start), 2) + pow((y_end - y_start), 2));\n \/\/ check if target position is too close\n if (distance < ds_min) {\n \/\/ copy the current wheel position\n wheel_poses_self_rotating.left_wheel_pos[i] = wheel_poses_msg.left_wheel_pos[i];\n wheel_poses_line_moving.left_wheel_pos[i] = wheel_poses_msg.left_wheel_pos[i];\n wheel_poses_self_rotating.right_wheel_pos[i] = wheel_poses_msg.right_wheel_pos[i];\n wheel_poses_line_moving.right_wheel_pos[i] = wheel_poses_msg.right_wheel_pos[i];\n }\n else {\n \/\/ two stage movement calculation\n \/\/ stage 1, self rotating calculation\n angle_start = robot_poses_msg.angle[i];\n angle_end = atan2(y_end - y_start, x_end - x_start);\n angle_rotate = angle_end - angle_start; \/\/ rotate from angle_start to angle_end\n \/\/ angel_end and angle_start both belong to range of (-M_PI, M_PI)\n \n }\n\n\n\n }\n\n\/\/ if the goal position is too close, neglect it\n\/\/ rotation angle is between -M_PI and M_PI\n\n\/\/ remember to ros::spinOnce at place that is necessary\n\n\n}\n\n\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"two_wheel_traj_interpolator_as\");\n ros::NodeHandle nh;\n\n ROS_INFO(\"instantiating an object of class TwoWheelTrajActionServer...\");\n TwoWheelTrajActionServer as_object(&nh);\n\n ROS_INFO(\"going into spin...\");\n\n while (ros::ok()) {\n ros::spinOnce();\n ros::Duration(0.1).sleep();\n }\n return 0;\n}\n\n<commit_msg>update two wheel trajectory interpolator<commit_after>\/\/ the trajectory action server for two wheel robot\n\n\/\/ communication includes\n \/\/ subscribe to topic \"swarm_robot_poses\" with message swarm_robot_poses.msg\n \/\/ subscribe to topic \"two_wheel_poses\" with message two_wheel_poses.msg\n \/\/ publish to topic \"two_wheel_poses_cmd\" with message two_wheel_poses.msg\n \/\/ host a action server \"two_wheel_traj_action\" with message swarm_robot_traj.action\n\n\/\/ there are different wheel trajectories of moving to a target position\n\/\/ Method 1:\n \/\/ first rotating the robot to the direction of the target position\n \/\/ then moving the robot in straight line to the target position\n \/\/ pros:\n \/\/ simple and straightforward wheel position increment calculation\n \/\/ easy to debug the potential problems\n \/\/ cons:\n \/\/ ugly and inefficient to take two movements to moving to the target\n\/\/ Method 2:\n \/\/ the path between start position and target position is circular\n \/\/ the center of the circular path is on the common axis of the two wheels\n \/\/ pros:\n \/\/ taking only one movements to move to the target, much more elegant\n \/\/ two wheel position are linearly interpolated because of this circular path\n \/\/ cons:\n \/\/ a bit difficult to calculate the increment of the wheel positions\n \/\/ difficult to debug the algorithm for the wheel positions\n\n\/\/ for the convenience of wheel position calculation and debug, method 1 is implemented here\n\n\/\/ one significant problem of the controller of two_wheel_robot is that\n \/\/ when one wheel is commanded rotating and the other is remained current position\n \/\/ the static wheel will naturally rotating at the other direction because of inertia\n \/\/ how to solve or avoid this problem? and make position control more precise\n\n#include <ros\/ros.h>\n#include <math.h>\n#include <actionlib\/server\/simple_action_server.h>\n#include <swarm_robot_action\/swarm_robot_trajAction.h>\n#include <swarm_robot_msgs\/two_wheel_poses.h>\n\n\/\/ interpolation parameters, change setup here\nconst double dt = 0.01; \/\/ interpolating resolution on time\n\/\/ minimal distance with goal position to interpolate\n\/\/ distance small than ds_min will be neglected, cube size of two_wheel_robot is 0.0254\n\/\/ this value should be set very low\nconst double ds_min = 0.001;\n\/\/ half distance of two wheels\n\/\/ not a good way to get this value here\nconst double half_wheel_dist = 0.0177;\n\nclass TwoWheelTrajActionServer {\npublic:\n TwoWheelTrajActionServer(ros::NodeHandle* nodehandle);\n\nprivate:\n void swarmRobotPosesCb(const swarm_robot_msgs::swarm_robot_poses& message_holder);\n void twoWheelPosesCb(const swarm_robot_msgs::two_wheel_poses& message_holder);\n void executeCb(const \n actionlib::SimpleActionServer<swarm_robot_action::swarm_robot_trajAction>::GoalConstPtr& goal);\n\n ros::NodeHandle nh_; \/\/ a node handle is needed\n\n \/\/ declare a subscribers to topic \"swarm_robot_poses\" and \"two_wheel_poses\"\n ros::Subscriber swarm_robot_poses_subscriber;\n ros::Subscriber two_wheel_poses_subscriber;\n \/\/ declare a publisher to topic \"two_wheel_poses_cmd\"\n ros::Publisher two_wheel_poses_cmd_publisher;\n \/\/ declare an action server\n actionlib::SimpleActionServer<swarm_robot_action::swarm_robot_trajAction> as_;\n \n \/\/ messages\n swarm_robot_msgs::swarm_robot_poses robot_poses_msg; \/\/ current robot poses\n swarm_robot_msgs::two_wheel_poses wheel_poses_msg; \/\/ current wheel poses\n swarm_robot_msgs::two_wheel_poses wheel_poses_cmd_msg; \/\/ wheel poses command\n \/\/ for trajectory interpolation\n swarm_robot_msgs::two_wheel_poses wheel_poses_self_rotating;\n swarm_robot_msgs::two_wheel_poses wheel_poses_line_moving;\n \/\/ action messages\n swarm_robot_action::swarm_robot_trajActionGoal goal_;\n swarm_robot_action::swarm_robot_trajActionResult result_;\n swarm_robot_action::swarm_robot_trajActionFeedback feedback_;\n\n \/\/ other variables\n std::string robot_model_name; \/\/ from parameter server\n int robot_quantity; \/\/ from parameter server\n bool b_robot_poses_cb_started;\n bool b_wheel_poses_cb_started;\n};\n\n\/\/ most initialization work will be done here\nTwoWheelTrajActionServer::TwoWheelTrajActionServer(ros::NodeHandle* nodehandle):\n nh_(*nodehandle), \/\/ dereference the pointer and pass the value\n as_(nh_, \"two_wheel_traj_action\", boost::bind(&TwoWheelTrajActionServer::executeCb, this, _1), false)\n{\n ROS_INFO(\"in constructor of TwoWheelTrajActionServer...\");\n\n \/\/ initialize the subscribers\n b_robot_poses_cb_started = false;\n swarm_robot_poses_subscriber = nh_.subscribe(\"swarm_robot_poses\", 1, swarmRobotPosesCb);\n b_poses_callback_started = false;\n two_wheel_poses_subscriber = nh_.subscribe(\"two_wheel_poses\", 1, twoWheelPosesCb);\n \/\/ initialize the publisher\n two_wheel_poses_cmd_publisher = nh_.advertise<swarm_robot_msgs::two_wheel_poses>(\"two_wheel_poses_cmd\", 1);\n\n \/\/ get initialization message of robot swarm from parameter server\n bool get_name, get_quantity;\n get_name = nh_.getParam(\"\/robot_model_name\", robot_model_name);\n get_quantity = nh_.getParam(\"\/robot_quantity\", robot_quantity);\n if (!(get_name && get_quantity))\n return 0; \/\/ return if fail to get parameter\n\n \/\/ make sure topics \"swarm_robot_poses\" and \"two_wheel_poses\" are active\n while (!(b_robot_poses_cb_started && b_wheel_poses_cb_started)) {\n ros::Duration(0.5).sleep();\n ros::spinOnce();\n }\n std::cout << \"topic message from swarm_robot_poses and two_wheel_poses is ready\" << std::endl;\n\n as_.start(); \/\/ start the \"two_wheel_traj_action\"\n}\n\n\/\/ callback for message from topic \"swarm_robot_poses\"\nvoid TwoWheelTrajActionServer::swarmRobotPosesCb(const swarm_robot_msgs::swarm_robot_poses& message_holder) {\n if (!b_robot_poses_cb_started) \/\/ first time to be invoked\n b_robot_poses_cb_started = true;\n robot_poses_msg = message_holder;\n}\n\n\/\/ callback for message from topic \"two_wheel_poses\"\nvoid TwoWheelTrajActionServer::twoWheelPosesCb(const swarm_robot_msgs::two_wheel_poses& message_holder) {\n if (!b_wheel_poses_cb_started) \/\/ first time to be invoked\n b_wheel_poses_cb_started = true;\n wheel_poses_msg = message_holder;\n}\n\n\/\/ most practical work will be done here\nvoid TwoWheelTrajActionServer::executeCb(const actionlib::\n SimpleActionServer<swarm_robot_action::swarm_robot_trajAction>::GoalConstPtr& goal)\n{\n ROS_INFO(\"in executeCb...\");\n\n \/\/ copy the goal message, avoid using \"->\" too much\n double goal_x[] = goal -> x;\n double goal_y[] = goal -> y;\n double goal_time = goal -> time;\n\n \/\/ variables needed in wheel trajectory calculation\n double x_start;\n double y_start;\n double x_end;\n double y_end;\n double distance;\n double angle_start; \/\/ current angle of the robot\n double angle_end; \/\/ target angle of the robot\n double angle_rotate; \/\/ rotated angle of the robot\n double wheel_incre_self_rotating; \/\/ the wheel postion increment in self rotating stage\n double wheel_incre_line_moving; \/\/ the wheel position increment in line moving stage\n \/\/ both increment are signed after been given values\n \/\/ calculate the cmd message for each robot\n for (int i=0; i<robot_quantity; i++) {\n x_start = robot_poses_msg.x[i];\n y_start = robot_poses_msg.y[i];\n x_end = goal_x[i];\n y_end = goal_y[i];\n distance = sqrt(pow((x_end - x_start), 2) + pow((y_end - y_start), 2));\n \/\/ check if target position is too close\n if (distance < ds_min) {\n \/\/ copy the current wheel position\n wheel_poses_self_rotating.left_wheel_pos[i] = wheel_poses_msg.left_wheel_pos[i];\n wheel_poses_self_rotating.right_wheel_pos[i] = wheel_poses_msg.right_wheel_pos[i];\n wheel_poses_line_moving.left_wheel_pos[i] = wheel_poses_msg.left_wheel_pos[i];\n wheel_poses_line_moving.right_wheel_pos[i] = wheel_poses_msg.right_wheel_pos[i];\n }\n else {\n \/\/ two stage movement calculation\n \n \/\/ stage 1, self rotating calculation\n angle_start = robot_poses_msg.angle[i];\n angle_end = atan2(y_end - y_start, x_end - x_start);\n angle_rotate = angle_end - angle_start; \/\/ rotate from angle_start to angle_end\n \/\/ angel_end and angle_start both belong to range of (-M_PI, M_PI)\n \/\/ change angle_rotate into the same range (-M_PI, M_PI)\n if (angle_rotate > M_PI)\n angle_rotate = angle_rotate - 2 * M_PI;\n if (angle_rotate < -M_PI)\n angle_rotate = angle_rotate + 2 * M_PI;\n bool robot_heading = true; \/\/ whether the robot is heading or backing to the target\n \/\/ it's not necessary to rotate the heading direction to the target every time\n \/\/ because the two wheel robot can also moving backward\n \/\/ change angle_rotate into the range (-M_PI\/2, M_PI\/2), use robot_heading to mark it\n if (angle_rotate > M_PI\/2) {\n robot_heading = false;\n angle_rotate = angle_rotate - M_PI;\n }\n if (angle_rotate < -M_PI\/2) {\n robot_heading = false;\n angle_rotate = angle_rotate + M_PI;\n }\n \/\/ prepare wheel poses message base on current wheel positions\n wheel_incre_self_rotating = angle_rotate * half_wheel_dist;\n \/\/ left wheel move backward when rotating angle is positive\n wheel_poses_self_rotating.left_wheel_pos[i] =\n wheel_poses_msg.left_wheel_pos[i] - wheel_incre_self_rotating;\n \/\/ right wheel move forward when rotating angle is positive\n wheel_poses_self_rotating.right_wheel_pos[i] =\n wheel_poses_msg.right_wheel_pos[i] + wheel_incre_self_rotating;\n\n \/\/ stage 2, line moving calculation\n \/\/ prepare wheel poses message bese on self rotated wheel positions\n if (robot_heading)\n wheel_incre_line_moving = distance; \/\/ moving forward\n else\n wheel_incre_line_moving = -distance; \/\/ moving backward\n \/\/ both left and right wheel rotating at same direction\n wheel_poses_line_moving.left_wheel_pos[i] = \n wheel_poses_self_rotating.left_wheel_pos[i] + wheel_incre_line_moving;\n wheel_poses_line_moving.right_wheel_pos[i] = \n wheel_poses_self_rotating.right_wheel_pos[i] + wheel_incre_line_moving;\n }\n }\n\n \/\/ trajectory interpolation\n \/\/ time for the two movements are linearly distributed wrt the wheel rotation\n double time_self_rotating;\n double time_line_moving;\n time_self_rotating = goal_time * (abs(wheel_incre_self_rotating)) \/\n (abs(wheel_incre_self_rotating) + abs(wheel_incre_line_moving));\n time_line_moving = goal_time - time_self_rotating;\n\n\n\/\/ messages\nswarm_robot_msgs::swarm_robot_poses robot_poses_msg; \/\/ current robot poses\nswarm_robot_msgs::two_wheel_poses wheel_poses_msg; \/\/ current wheel poses\nswarm_robot_msgs::two_wheel_poses wheel_poses_cmd_msg; \/\/ wheel poses command\n\nswarm_robot_msgs::two_wheel_poses wheel_poses_self_rotating;\nswarm_robot_msgs::two_wheel_poses wheel_poses_line_moving;\n\n\n\n\/\/ remember to ros::spinOnce at place that is necessary\n\n\n}\n\n\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"two_wheel_traj_interpolator_as\");\n ros::NodeHandle nh;\n\n ROS_INFO(\"instantiating an object of class TwoWheelTrajActionServer...\");\n TwoWheelTrajActionServer as_object(&nh);\n\n ROS_INFO(\"going into spin...\");\n\n while (ros::ok()) {\n ros::spinOnce();\n ros::Duration(0.1).sleep();\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Genetic5.cpp : Defines the entry point for the console application.\n\/\/\n\n#pragma warning(disable:4786)\t\t\/\/ disable debug warning\n\n#include <iostream>\t\t\t\t\t\/\/ for cout etc.\n#include <vector>\t\t\t\t\t\/\/ for vector class\n#include <string>\t\t\t\t\t\/\/ for string class\n#include <algorithm>\t\t\t\t\/\/ for sort algorithm\n#include <time.h>\t\t\t\t\t\/\/ for random seed\n#include <math.h>\t\t\t\t\t\/\/ for abs()\n\n#define GA_POPSIZE 2048 \/\/ ga population size\n#define GA_MAXITER 16384 \/\/ maximum iterations\n#define GA_ELITRATE 0.10f \/\/ elitism rate\n#define GA_MUTATIONRATE 0.25f \/\/ mutation rate\n#define GA_MUTATION RAND_MAX * GA_MUTATIONRATE\n#define GA_TARGET std::string(\"Hello world!\")\n\nusing namespace std; \/\/ polluting global namespace, but hey...\n\nstruct ga_struct {\n string str; \/\/ the string\n unsigned int fitness; \/\/ its fitness\n};\n\ntypedef vector<ga_struct> ga_vector;\/\/ for brevity\n\nvoid init_population(ga_vector &population,\n ga_vector &buffer) {\n int tsize = GA_TARGET.size();\n\n for (int i = 0; i < GA_POPSIZE; i++) {\n ga_struct citizen;\n\n citizen.fitness = 0;\n citizen.str.erase();\n\n for (int j = 0; j < tsize; j++)\n citizen.str += (rand() % 90) + 32;\n\n population.push_back(citizen);\n }\n\n buffer.resize(GA_POPSIZE);\n}\n\nint heuristic1(string elem, string target) {\n unsigned int fitness = 0;\n for (int j = 0; j < target.size(); j++) {\n fitness += abs(int(elem[j] - target[j]));\n }\n return fitness;\n}\n\n\nint heuristic2(string elem, string target) {\n unsigned int fitness = 0;\n for (int j = 0; j < target.size(); j++) {\n fitness += elem[j] == target[j] ? 0 : 1;\n }\n return fitness;\n}\n\nbool strContains(string s, char c) {\n for (int i = 0; i < s.length(); i++) {\n if (s[i] == c) return true;\n }\n return false;\n}\n\nint generalHeuristic3(string elem, string target, unsigned int containsWeight, unsigned int eqWeight) {\n unsigned int fitness = 0;\n for (int j = 0; j < target.size(); j++) {\n bool contains = strContains(target, elem[j]);\n bool eq = elem[j] == target[j];\n\n fitness += (containsWeight + eqWeight) - containsWeight * contains - eqWeight * eq;\n }\n return fitness;\n}\n\nint heuristic3(string elem, string target) {\n return generalHeuristic3(elem, target, 1, 2);\n}\n\nvoid calc_fitness(ga_vector &population) {\n string target = GA_TARGET;\n for (int i = 0; i < GA_POPSIZE; i++) {\n population[i].fitness = heuristic3(population[i].str, target);\n }\n}\n\nbool fitness_sort(ga_struct x, ga_struct y) {\n return (x.fitness < y.fitness);\n}\n\ninline void sort_by_fitness(ga_vector &population) {\n sort(population.begin(), population.end(), fitness_sort);\n}\n\nvoid elitism(ga_vector &population,\n ga_vector &buffer, int esize) {\n for (int i = 0; i < esize; i++) {\n buffer[i].str = population[i].str;\n buffer[i].fitness = population[i].fitness;\n }\n}\n\nvoid mutate(ga_struct &member) {\n int tsize = GA_TARGET.size();\n int ipos = rand() % tsize;\n int delta = (rand() % 90) + 32;\n\n member.str[ipos] = ((member.str[ipos] + delta) % 122);\n}\n\nvoid mate(ga_vector &population, ga_vector &buffer) {\n int esize = GA_POPSIZE * GA_ELITRATE;\n int tsize = GA_TARGET.size(), spos, i1, i2;\n\n elitism(population, buffer, esize);\n\n \/\/ Mate the rest\n for (int i = esize; i < GA_POPSIZE; i++) {\n i1 = rand() % (GA_POPSIZE \/ 2);\n i2 = rand() % (GA_POPSIZE \/ 2);\n spos = rand() % tsize;\n\n buffer[i].str = population[i1].str.substr(0, spos) +\n population[i2].str.substr(spos, tsize - spos);\n\n if (rand() < GA_MUTATION) mutate(buffer[i]);\n }\n}\n\n\ninline void swap(ga_vector *&population,\n ga_vector *&buffer) {\n ga_vector *temp = population;\n population = buffer;\n buffer = temp;\n}\n\ndouble average(ga_vector &vect) {\n double sum = 0;\n int size = vect.size();\n\n for (int i = 0; i < vect.size(); i++)\n sum += vect[i].fitness;\n\n return sum \/ size;\n}\n\ndouble variance(ga_vector &vect) {\n double sumOfDiffs = 0;\n double avg = average(vect);\n int size = vect.size();\n\n for (int i = 0; i < vect.size(); i++) {\n double diff = (double) vect[i].fitness - avg;\n sumOfDiffs += diff * diff;\n }\n\n return sumOfDiffs \/ size;\n}\n\ndouble standardDeviation(ga_vector &vect) {\n return sqrt(variance(vect));\n}\n\nvoid print_best(ga_vector &gav, unsigned int iteration) {\n cout << \"Gen \" << iteration << endl;\n cout << \"Best: \" << gav[0].str << \" (\" << gav[0].fitness << \")\" << endl;\n cout << \"Average Fitness: \" << average(gav) << endl;\n cout << \"Standard Deviation: \" << standardDeviation(gav) << endl << endl;\n}\n\nint main() {\n srand(unsigned(time(NULL)));\n\n ga_vector pop_alpha, pop_beta;\n ga_vector *population, *buffer;\n\n init_population(pop_alpha, pop_beta);\n population = &pop_alpha;\n buffer = &pop_beta;\n\n for (int i = 0; i < GA_MAXITER; i++) {\n calc_fitness(*population); \/\/ calculate fitness\n sort_by_fitness(*population); \/\/ sort them\n print_best(*population, i); \/\/ print the best one\n\n if ((*population)[0].fitness == 0) break;\n\n mate(*population, *buffer); \/\/ mate the population together\n swap(population, buffer); \/\/ swap buffers\n }\n\n return 0;\n}\n<commit_msg>Lab1: Get rid of warnings<commit_after>\/\/ Genetic5.cpp : Defines the entry point for the console application.\n\/\/\n\n#pragma warning(disable:4786)\t\t\/\/ disable debug warning\n\n#include <iostream>\t\t\t\t\t\/\/ for cout etc.\n#include <vector>\t\t\t\t\t\/\/ for vector class\n#include <string>\t\t\t\t\t\/\/ for string class\n#include <algorithm>\t\t\t\t\/\/ for sort algorithm\n#include <time.h>\t\t\t\t\t\/\/ for random seed\n#include <math.h>\t\t\t\t\t\/\/ for abs()\n\n#define GA_POPSIZE 2048 \/\/ ga population size\n#define GA_MAXITER 16384 \/\/ maximum iterations\n#define GA_ELITRATE 0.10f \/\/ elitism rate\n#define GA_MUTATIONRATE 0.25f \/\/ mutation rate\n#define GA_MUTATION RAND_MAX * GA_MUTATIONRATE\n#define GA_TARGET std::string(\"Hello world!\")\n\nusing namespace std; \/\/ polluting global namespace, but hey...\n\nstruct ga_struct {\n string str; \/\/ the string\n unsigned int fitness; \/\/ its fitness\n};\n\ntypedef vector<ga_struct> ga_vector;\/\/ for brevity\n\nvoid init_population(ga_vector &population,\n ga_vector &buffer) {\n int tsize = (int) GA_TARGET.size();\n\n for (int i = 0; i < GA_POPSIZE; i++) {\n ga_struct citizen;\n\n citizen.fitness = 0;\n citizen.str.erase();\n\n for (int j = 0; j < tsize; j++)\n citizen.str += (rand() % 90) + 32;\n\n population.push_back(citizen);\n }\n\n buffer.resize(GA_POPSIZE);\n}\n\nunsigned int heuristic1(string elem, string target) {\n unsigned int fitness = 0;\n for (int j = 0; j < target.size(); j++) {\n fitness += abs(int(elem[j] - target[j]));\n }\n return fitness;\n}\n\n\nunsigned int heuristic2(string elem, string target) {\n unsigned int fitness = 0;\n for (int j = 0; j < target.size(); j++) {\n fitness += elem[j] == target[j] ? 0 : 1;\n }\n return fitness;\n}\n\nbool strContains(string s, char c) {\n for (int i = 0; i < s.length(); i++) {\n if (s[i] == c) return true;\n }\n return false;\n}\n\nunsigned int generalHeuristic3(string elem, string target, unsigned int containsWeight, unsigned int eqWeight) {\n unsigned int fitness = 0;\n for (int j = 0; j < target.size(); j++) {\n bool contains = strContains(target, elem[j]);\n bool eq = elem[j] == target[j];\n\n fitness += (containsWeight + eqWeight) - containsWeight * contains - eqWeight * eq;\n }\n return fitness;\n}\n\nunsigned int heuristic3(string elem, string target) {\n return generalHeuristic3(elem, target, 1, 2);\n}\n\nvoid calc_fitness(ga_vector &population) {\n string target = GA_TARGET;\n for (int i = 0; i < GA_POPSIZE; i++) {\n population[i].fitness = heuristic3(population[i].str, target);\n }\n}\n\nbool fitness_sort(ga_struct x, ga_struct y) {\n return (x.fitness < y.fitness);\n}\n\ninline void sort_by_fitness(ga_vector &population) {\n sort(population.begin(), population.end(), fitness_sort);\n}\n\nvoid elitism(ga_vector &population,\n ga_vector &buffer, int esize) {\n for (int i = 0; i < esize; i++) {\n buffer[i].str = population[i].str;\n buffer[i].fitness = population[i].fitness;\n }\n}\n\nvoid mutate(ga_struct &member) {\n int tsize = (int) GA_TARGET.size();\n int ipos = rand() % tsize;\n int delta = (rand() % 90) + 32;\n\n member.str[ipos] = (char) ((member.str[ipos] + delta) % 122);\n}\n\nvoid mate(ga_vector &population, ga_vector &buffer) {\n int esize = (int) (GA_POPSIZE * GA_ELITRATE);\n size_t tsize = GA_TARGET.size();\n\n elitism(population, buffer, esize);\n\n \/\/ Mate the rest\n for (int i = esize; i < GA_POPSIZE; i++) {\n int i1 = rand() % (GA_POPSIZE \/ 2);\n int i2 = rand() % (GA_POPSIZE \/ 2);\n size_t spos = rand() % tsize;\n\n buffer[i].str = population[i1].str.substr(0, spos) +\n population[i2].str.substr(spos, tsize - spos);\n\n if (rand() < GA_MUTATION) mutate(buffer[i]);\n }\n}\n\n\ninline void swap(ga_vector *&population,\n ga_vector *&buffer) {\n ga_vector *temp = population;\n population = buffer;\n buffer = temp;\n}\n\ndouble average(ga_vector &vect) {\n double sum = 0;\n size_t size = vect.size();\n\n for (int i = 0; i < vect.size(); i++)\n sum += vect[i].fitness;\n\n return sum \/ size;\n}\n\ndouble variance(ga_vector &vect) {\n double sumOfDiffs = 0;\n double avg = average(vect);\n size_t size = vect.size();\n\n for (int i = 0; i < vect.size(); i++) {\n double diff = (double) vect[i].fitness - avg;\n sumOfDiffs += diff * diff;\n }\n\n return sumOfDiffs \/ size;\n}\n\ndouble standardDeviation(ga_vector &vect) {\n return sqrt(variance(vect));\n}\n\nvoid print_best(ga_vector &gav, unsigned int iteration) {\n cout << \"Gen \" << iteration << endl;\n cout << \"Best: \" << gav[0].str << \" (\" << gav[0].fitness << \")\" << endl;\n cout << \"Average Fitness: \" << average(gav) << endl;\n cout << \"Standard Deviation: \" << standardDeviation(gav) << endl << endl;\n}\n\nint main() {\n srand(unsigned(time(NULL)));\n\n ga_vector pop_alpha, pop_beta;\n ga_vector *population, *buffer;\n\n init_population(pop_alpha, pop_beta);\n population = &pop_alpha;\n buffer = &pop_beta;\n\n for (unsigned int i = 0; i < GA_MAXITER; i++) {\n calc_fitness(*population); \/\/ calculate fitness\n sort_by_fitness(*population); \/\/ sort them\n print_best(*population, i); \/\/ print the best one\n\n if ((*population)[0].fitness == 0) break;\n\n mate(*population, *buffer); \/\/ mate the population together\n swap(population, buffer); \/\/ swap buffers\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/profiler\/convert\/op_stats_to_overview_page.h\"\n\n#include <algorithm>\n#include <utility>\n\n#include \"google\/protobuf\/any.pb.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/protobuf.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n#include \"tensorflow\/core\/profiler\/convert\/op_metrics_to_record.h\"\n#include \"tensorflow\/core\/profiler\/convert\/op_stats_to_input_pipeline_analysis.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/hardware_types.pb.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/input_pipeline.pb.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/op_metrics.pb.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/op_stats.pb.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/overview_page.pb.h\"\n#include \"tensorflow\/core\/profiler\/utils\/math_utils.h\"\n#include \"tensorflow\/core\/profiler\/utils\/op_metrics_db_utils.h\"\n#include \"tensorflow\/core\/profiler\/utils\/time_utils.h\"\n\nnamespace tensorflow {\nnamespace profiler {\n\nnamespace {\n\nOverviewPageTip MakeOverviewPageTip(const string& text) {\n OverviewPageTip tip;\n tip.set_link(text);\n return tip;\n}\n\nstring AnchorElement(const string& url, const string& text) {\n return absl::StrCat(\"<a href=\\\"\", url, \"\\\" target=\\\"_blank\\\">\", text, \"<\/a>\");\n}\n\n\/\/ Makes a recommendation for looking up a document.\n\/\/ doc_url is expected to be already be escaped suitably for use in an HTML\n\/\/ attribute.\nOverviewPageTip MakeOverviewPageTipDocLink(const string& doc_url,\n const string& text) {\n OverviewPageTip tip;\n tip.set_link(AnchorElement(doc_url, text));\n return tip;\n}\n\nvoid ComputeHostTips(OverviewPageRecommendation* re) {\n *re->add_host_tips() = MakeOverviewPageTip(\n \"input_pipeline_analyzer (especially Section 3 for the breakdown of \"\n \"input operations on the Host)\");\n *re->add_host_tips() = MakeOverviewPageTip(\n \"trace_viewer (look at the activities on the timeline of each Host \"\n \"Thread near the bottom of the trace view)\");\n}\n\nvoid ComputeDeviceTips(HardwareType hardware_type,\n OverviewPageRecommendation* re) {\n const string& device_name = HardwareType_Name(hardware_type);\n string timeline_name =\n (hardware_type == tensorflow::profiler::TPU) ? \"TPU core\" : device_name;\n *re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(\n \"op_profile (identify the time-consuming operations executed on the \",\n device_name, \")\"));\n *re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(\n \"trace_viewer (look at the activities on the timeline of each \",\n timeline_name, \" in the trace view)\"));\n}\n\nvoid ComputeFaqTips(OverviewPageRecommendation* re) {\n *re->add_faq_tips() = MakeOverviewPageTip(\"Refer to the Cloud tools FAQ\");\n}\n\nvoid ComputeDocumentationTips(OverviewPageRecommendation* re) {\n *re->add_documentation_tips() = MakeOverviewPageTipDocLink(\n \"https:\/\/www.tensorflow.org\/versions\/master\/api_docs\/python\/tf\/data\/\"\n \"Dataset\",\n \"TensorFlow Input Pipeline API\");\n}\n\n} \/\/ namespace\n\nvoid SetCommonRecommendation(const CommonBottleneck& bottleneck,\n HardwareType hardware_type,\n OverviewPageRecommendation* re) {\n re->set_bottleneck(bottleneck.input_classification);\n re->set_statement(bottleneck.input_statement);\n ComputeHostTips(re);\n ComputeDeviceTips(hardware_type, re);\n ComputeDocumentationTips(re);\n ComputeFaqTips(re);\n}\n\nOverviewPageRecommendation ComputeGenericRecommendation(\n const GenericBottleneck& bottleneck) {\n OverviewPageRecommendation re;\n GenericRecommendation generic;\n generic.set_kernel_launch_bottleneck(bottleneck.kernel_launch_classification);\n generic.set_kernel_launch_statement(bottleneck.kernel_launch_statement);\n generic.set_all_other_bottleneck(bottleneck.all_other_classification);\n generic.set_all_other_statement(bottleneck.all_other_statement);\n re.mutable_recommendation()->PackFrom(generic);\n return re;\n}\n\nOverviewPageAnalysis ComputeAnalysisResult(const OpStats& op_stats) {\n OverviewPageAnalysis analysis;\n OpMetricsDb metrics_db =\n CreateTfMetricsDbFromHloMetricsDb(op_stats.device_op_metrics_db());\n uint64 total_device_time_ps = metrics_db.total_time_ps();\n constexpr int kNumTopOpsShown = 10;\n double device_cumulative_fraction = 0.0;\n for (const OpMetrics* metrics :\n SortedOpMetricsDb(metrics_db, kNumTopOpsShown)) {\n OverviewTfOp* op = analysis.add_top_device_ops();\n op->set_name(metrics->name());\n op->set_category(metrics->category());\n op->set_self_time_fraction(\n SafeDivide(metrics->self_time_ps(), total_device_time_ps));\n device_cumulative_fraction += op->self_time_fraction();\n op->set_cumulative_time_fraction(device_cumulative_fraction);\n op->set_flop_rate(\n SafeDivide(metrics->flops(), PicosToNanos(metrics->time_ps())));\n }\n return analysis;\n}\n\n\/\/ Converts from HostIndependentJobInfo to OverviewPageHostIndependentJobInfo.\nOverviewPageHostIndependentJobInfo ToOverviewPageHostIndependentJobInfo(\n const HostIndependentJobInfoResult& host_independent_job_info) {\n OverviewPageHostIndependentJobInfo result;\n result.set_change_list(host_independent_job_info.change_list());\n result.set_build_time(host_independent_job_info.build_time());\n result.set_build_target(host_independent_job_info.build_target());\n result.set_profile_duration_ms(\n host_independent_job_info.profile_duration_ms());\n return result;\n}\n\n\/\/ Converts from HostDependentJobInfo to OverviewPageHostDependentJobInfo.\nOverviewPageHostDependentJobInfo ToOverviewPageHostDependentJobInfo(\n const HostDependentJobInfoResult& host_dependent_job_info) {\n OverviewPageHostDependentJobInfo result;\n result.set_host_id(host_dependent_job_info.host_id());\n result.set_command_line(host_dependent_job_info.command_line());\n result.set_start_time(host_dependent_job_info.start_time());\n result.set_bns_address(host_dependent_job_info.bns_address());\n result.set_profile_time_ns(host_dependent_job_info.profile_time_ns());\n return result;\n}\n\nOverviewPageRunEnvironment ComputeRunEnvironment(\n const RunEnvironment& run_environment) {\n OverviewPageRunEnvironment re;\n re.set_host_count(run_environment.host_count());\n re.set_task_count(run_environment.task_count());\n re.set_device_type(run_environment.device_type());\n re.set_device_core_count(run_environment.device_core_count());\n re.set_per_core_batch_size(run_environment.per_core_batch_size());\n re.set_replica_count(run_environment.replica_count());\n re.set_num_cores_per_replica(run_environment.num_cores_per_replica());\n *re.mutable_host_independent_job_info() =\n ToOverviewPageHostIndependentJobInfo(\n run_environment.host_independent_job_info());\n for (const auto& host_dependent_job_info :\n run_environment.host_dependent_job_info()) {\n *re.add_host_dependent_job_info() =\n ToOverviewPageHostDependentJobInfo(host_dependent_job_info);\n }\n return re;\n}\n\nOverviewPage ConvertOpStatsToOverviewPage(const OpStats& op_stats,\n HardwareType hardware_type) {\n OverviewPageAnalysis analysis = ComputeAnalysisResult(op_stats);\n InputPipelineAnalysisResult input_analysis =\n ConvertOpStatsToInputPipelineAnalysis(op_stats, hardware_type);\n GenericBottleneck bottleneck = GenericOverallBottleneck(input_analysis);\n OverviewPageRecommendation recommendation =\n ComputeGenericRecommendation(bottleneck);\n SetCommonRecommendation(bottleneck.common, hardware_type, &recommendation);\n\n OverviewPage overview_page;\n *overview_page.mutable_run_environment() =\n ComputeRunEnvironment(op_stats.run_environment());\n *overview_page.mutable_analysis() = analysis;\n *overview_page.mutable_input_analysis() = input_analysis;\n *overview_page.mutable_recommendation() = recommendation;\n return overview_page;\n}\n\n} \/\/ namespace profiler\n} \/\/ namespace tensorflow\n<commit_msg>Fix output of overview page and input-pipeline analyzer for Cloud TPU.<commit_after>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/profiler\/convert\/op_stats_to_overview_page.h\"\n\n#include <algorithm>\n#include <utility>\n\n#include \"google\/protobuf\/any.pb.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/protobuf.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n#include \"tensorflow\/core\/profiler\/convert\/op_metrics_to_record.h\"\n#include \"tensorflow\/core\/profiler\/convert\/op_stats_to_input_pipeline_analysis.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/hardware_types.pb.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/input_pipeline.pb.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/op_metrics.pb.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/op_stats.pb.h\"\n#include \"tensorflow\/core\/profiler\/protobuf\/overview_page.pb.h\"\n#include \"tensorflow\/core\/profiler\/utils\/math_utils.h\"\n#include \"tensorflow\/core\/profiler\/utils\/op_metrics_db_utils.h\"\n#include \"tensorflow\/core\/profiler\/utils\/time_utils.h\"\n\nnamespace tensorflow {\nnamespace profiler {\n\nnamespace {\n\nOverviewPageTip MakeOverviewPageTip(const string& text) {\n OverviewPageTip tip;\n tip.set_link(text);\n return tip;\n}\n\nstring AnchorElement(const string& url, const string& text) {\n return absl::StrCat(\"<a href=\\\"\", url, \"\\\" target=\\\"_blank\\\">\", text, \"<\/a>\");\n}\n\n\/\/ Makes a recommendation for looking up a document.\n\/\/ doc_url is expected to be already be escaped suitably for use in an HTML\n\/\/ attribute.\nOverviewPageTip MakeOverviewPageTipDocLink(const string& doc_url,\n const string& text) {\n OverviewPageTip tip;\n tip.set_link(AnchorElement(doc_url, text));\n return tip;\n}\n\nvoid ComputeHostTips(OverviewPageRecommendation* re) {\n *re->add_host_tips() = MakeOverviewPageTip(\n \"input_pipeline_analyzer (especially Section 3 for the breakdown of \"\n \"input operations on the Host)\");\n *re->add_host_tips() = MakeOverviewPageTip(\n \"trace_viewer (look at the activities on the timeline of each Host \"\n \"Thread near the bottom of the trace view)\");\n}\n\nvoid ComputeDeviceTips(HardwareType hardware_type,\n OverviewPageRecommendation* re) {\n const string& device_name = HardwareType_Name(hardware_type);\n string timeline_name =\n (hardware_type == tensorflow::profiler::TPU) ? \"TPU core\" : device_name;\n *re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(\n \"op_profile (identify the time-consuming operations executed on the \",\n device_name, \")\"));\n *re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(\n \"trace_viewer (look at the activities on the timeline of each \",\n timeline_name, \" in the trace view)\"));\n}\n\nvoid ComputeFaqTips(OverviewPageRecommendation* re) {\n *re->add_faq_tips() = MakeOverviewPageTip(\"Refer to the Cloud tools FAQ\");\n}\n\nvoid ComputeDocumentationTips(OverviewPageRecommendation* re) {\n *re->add_documentation_tips() = MakeOverviewPageTipDocLink(\n \"https:\/\/www.tensorflow.org\/guide\/\"\n \"data_performance\",\n \"Better performance with the tf.data API\");\n}\n\n} \/\/ namespace\n\nvoid SetCommonRecommendation(const CommonBottleneck& bottleneck,\n HardwareType hardware_type,\n OverviewPageRecommendation* re) {\n re->set_bottleneck(bottleneck.input_classification);\n re->set_statement(bottleneck.input_statement);\n ComputeHostTips(re);\n ComputeDeviceTips(hardware_type, re);\n ComputeDocumentationTips(re);\n ComputeFaqTips(re);\n}\n\nOverviewPageRecommendation ComputeGenericRecommendation(\n const GenericBottleneck& bottleneck) {\n OverviewPageRecommendation re;\n GenericRecommendation generic;\n generic.set_kernel_launch_bottleneck(bottleneck.kernel_launch_classification);\n generic.set_kernel_launch_statement(bottleneck.kernel_launch_statement);\n generic.set_all_other_bottleneck(bottleneck.all_other_classification);\n generic.set_all_other_statement(bottleneck.all_other_statement);\n re.mutable_recommendation()->PackFrom(generic);\n return re;\n}\n\nOverviewPageAnalysis ComputeAnalysisResult(const OpStats& op_stats) {\n OverviewPageAnalysis analysis;\n OpMetricsDb metrics_db =\n CreateTfMetricsDbFromHloMetricsDb(op_stats.device_op_metrics_db());\n uint64 total_device_time_ps = metrics_db.total_time_ps();\n constexpr int kNumTopOpsShown = 10;\n double device_cumulative_fraction = 0.0;\n for (const OpMetrics* metrics :\n SortedOpMetricsDb(metrics_db, kNumTopOpsShown)) {\n OverviewTfOp* op = analysis.add_top_device_ops();\n op->set_name(metrics->name());\n op->set_category(metrics->category());\n op->set_self_time_fraction(\n SafeDivide(metrics->self_time_ps(), total_device_time_ps));\n device_cumulative_fraction += op->self_time_fraction();\n op->set_cumulative_time_fraction(device_cumulative_fraction);\n op->set_flop_rate(\n SafeDivide(metrics->flops(), PicosToNanos(metrics->time_ps())));\n }\n return analysis;\n}\n\n\/\/ Converts from HostIndependentJobInfo to OverviewPageHostIndependentJobInfo.\nOverviewPageHostIndependentJobInfo ToOverviewPageHostIndependentJobInfo(\n const HostIndependentJobInfoResult& host_independent_job_info) {\n OverviewPageHostIndependentJobInfo result;\n result.set_change_list(host_independent_job_info.change_list());\n result.set_build_time(host_independent_job_info.build_time());\n result.set_build_target(host_independent_job_info.build_target());\n result.set_profile_duration_ms(\n host_independent_job_info.profile_duration_ms());\n return result;\n}\n\n\/\/ Converts from HostDependentJobInfo to OverviewPageHostDependentJobInfo.\nOverviewPageHostDependentJobInfo ToOverviewPageHostDependentJobInfo(\n const HostDependentJobInfoResult& host_dependent_job_info) {\n OverviewPageHostDependentJobInfo result;\n result.set_host_id(host_dependent_job_info.host_id());\n result.set_command_line(host_dependent_job_info.command_line());\n result.set_start_time(host_dependent_job_info.start_time());\n result.set_bns_address(host_dependent_job_info.bns_address());\n result.set_profile_time_ns(host_dependent_job_info.profile_time_ns());\n return result;\n}\n\nOverviewPageRunEnvironment ComputeRunEnvironment(\n const RunEnvironment& run_environment) {\n OverviewPageRunEnvironment re;\n re.set_host_count(run_environment.host_count());\n re.set_task_count(run_environment.task_count());\n re.set_device_type(run_environment.device_type());\n re.set_device_core_count(run_environment.device_core_count());\n re.set_per_core_batch_size(run_environment.per_core_batch_size());\n re.set_replica_count(run_environment.replica_count());\n re.set_num_cores_per_replica(run_environment.num_cores_per_replica());\n *re.mutable_host_independent_job_info() =\n ToOverviewPageHostIndependentJobInfo(\n run_environment.host_independent_job_info());\n for (const auto& host_dependent_job_info :\n run_environment.host_dependent_job_info()) {\n *re.add_host_dependent_job_info() =\n ToOverviewPageHostDependentJobInfo(host_dependent_job_info);\n }\n return re;\n}\n\nOverviewPage ConvertOpStatsToOverviewPage(const OpStats& op_stats,\n HardwareType hardware_type) {\n OverviewPageAnalysis analysis = ComputeAnalysisResult(op_stats);\n InputPipelineAnalysisResult input_analysis =\n ConvertOpStatsToInputPipelineAnalysis(op_stats, hardware_type);\n GenericBottleneck bottleneck = GenericOverallBottleneck(input_analysis);\n OverviewPageRecommendation recommendation =\n ComputeGenericRecommendation(bottleneck);\n SetCommonRecommendation(bottleneck.common, hardware_type, &recommendation);\n\n OverviewPage overview_page;\n *overview_page.mutable_run_environment() =\n ComputeRunEnvironment(op_stats.run_environment());\n *overview_page.mutable_analysis() = analysis;\n *overview_page.mutable_input_analysis() = input_analysis;\n *overview_page.mutable_recommendation() = recommendation;\n return overview_page;\n}\n\n} \/\/ namespace profiler\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>#include <fcntl.h>\n#include <stdio.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <sys\/socket.h> \n#include <sys\/un.h> \n#include <errno.h> \n \n#define MAX_BUF 1024\n\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <chrono>\nusing namespace std;\n#include <boost\/property_tree\/json_parser.hpp>\n\n\nconst static double PI = 3.14159265;\nconst static int iConstRound = 60;\nconst static double iConstRoundLimit = sin(iConstRound*PI\/180.0);\n\nstatic int fd = -1;\n#include <signal.h>\n#include <stdio.h>\nvoid sigcatch(int) {\n\tif(fd > 0) {\n\t\tclose(fd);\n\t}\n\texit(0);\n}\nint main(int ac,char*av[])\n{\n\tsystem(\"rm -f \/tmp\/mpu.6050.unix.domain\");\n\tif (SIG_ERR == signal(SIGINT, sigcatch)) {\n\t\tprintf(\"failed to set signal handler.n\");\n\t\texit(1);\n\t}\n fd = socket( AF_LOCAL, SOCK_DGRAM, 0 );\n\t\n\tstruct sockaddr_un addr;\n\tbzero( &addr, sizeof(addr) );\n\taddr.sun_family = AF_LOCAL;\n\tstrcpy( addr.sun_path, \"\/tmp\/mpu.6050.unix.domain\" );\n\t\n int use = 1; \n if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) {\n perror(\"setsockopt(SO_REUSEADDR) failed\");\n }\n\n\tstruct timeval timeout;\n\ttimeout.tv_sec = 0;\n\ttimeout.tv_usec = 1000;\n \tif (::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {\n\t \tperror(\"setsockopt(SO_RCVTIMEO) failed\");\n \t}\n\n if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)\n {\n\n printf(\" cannot bind socket: %d. \\n\",errno);\n close(fd);\n\n return 0;\n\n }\n\n char buf[MAX_BUF];\n double degree = 90.0;\n if(ac > 1) {\n \tdegree = ::atof(av[1]);\n }\n degree = std::fabs(degree);\n int iRound = degree\/iConstRound;\n double dRemain = degree - (iRound *iConstRound);\n double startDeg = 0.0;\n bool restartBase = true;\n chrono::steady_clock::time_point start = std::chrono::steady_clock::now();\n int msRun = 0;\n \/\/ 1000 ms \n while(msRun < 1000) {\n \tchrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n \tmsRun = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n \t\/\/printf(\"msRun=<%d>\\n\",msRun);\n\n\n \t\n \tsocklen_t len = sizeof(addr);\n int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len);\n if(ret>0){\n \/\/printf(\"Received: %s\\n\", buf);\n string recvStr(buf,ret);\n \/\/std::cout << recvStr << std::endl;\n std::stringstream ss;\n ss << recvStr;\n try {\n \tboost::property_tree::ptree pt;\n \tboost::property_tree::read_json(ss, pt);\n \tauto current = pt.get<double>(\"yaw\");\n \t\/\/std::cout << current << std::endl;\n \tif(restartBase) {\n \t\tstartDeg = current;\n \t\trestartBase = false;\n \t\tcontinue;\n \t}\n \tdouble dRoundRad = 0.0;\n \tif(iRound >0) {\n \t\tdRoundRad = iConstRoundLimit;\n \t} else {\n \t\tdRoundRad = sin(PI*dRemain\/180.0);\n \t}\n \tdouble diffDeg = std::fabs(current - startDeg);\n \t\/\/\/ over \n \tif(diffDeg > iConstRound) {\n \t\tdiffDeg = std::fabs(360 -diffDeg);\n \t}\n \tdouble diffRad = (PI*diffDeg\/180.0);\n \tdouble diff = dRoundRad - sin(diffRad);\n \tstd::cout << \"diff=<\" << diff <<\">\"<< std::endl;\n \tif(diff <=0) {\n \t\tstd::cout << \"iRound=<\" << iRound <<\">\"<< std::endl;\n \t\tif(iRound >0) {\n \t\t\tiRound--;\n\t \t\trestartBase = true;\n \t\t}\n \t\telse {\n \t\t\tbreak;\n \t\t}\n \t}\n } catch(std::exception e) {\n \tstd::cout << e.what() << std::endl;\n }\n } else if (ret==0){\n \t\/\/printf(\"ret=<%d>\\n\",ret);\n } else {\n \t\/\/printf(\"ret=<%d>\\n\",ret);\n }\n }\n close(fd);\n\n return 0;\n}\n<commit_msg>Update turn.cpp<commit_after>#include <fcntl.h>\n#include <stdio.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <sys\/socket.h> \n#include <sys\/un.h> \n#include <errno.h> \n \n#define MAX_BUF 1024\n\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <chrono>\nusing namespace std;\n#include <boost\/property_tree\/json_parser.hpp>\n\n\nconst static double PI = 3.14159265;\nconst static int iConstRound = 60;\nconst static double iConstRoundLimit = sin(iConstRound*PI\/180.0);\n\nstatic int fd = -1;\n#include <signal.h>\n#include <stdio.h>\nvoid sigcatch(int) {\n\tif(fd > 0) {\n\t\tclose(fd);\n\t}\n\texit(0);\n}\nint main(int ac,char*av[])\n{\n\tsystem(\"rm -f \/tmp\/mpu.6050.unix.domain\");\n\tif (SIG_ERR == signal(SIGINT, sigcatch)) {\n\t\tprintf(\"failed to set signal handler.n\");\n\t\texit(1);\n\t}\n fd = socket( AF_LOCAL, SOCK_DGRAM, 0 );\n\t\n\tstruct sockaddr_un addr;\n\tbzero( &addr, sizeof(addr) );\n\taddr.sun_family = AF_LOCAL;\n\tstrcpy( addr.sun_path, \"\/tmp\/mpu.6050.unix.domain\" );\n\t\n int use = 1; \n if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) {\n perror(\"setsockopt(SO_REUSEADDR) failed\");\n }\n\n\tstruct timeval timeout;\n\ttimeout.tv_sec = 0;\n\ttimeout.tv_usec = 1000;\n \tif (::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {\n\t \tperror(\"setsockopt(SO_RCVTIMEO) failed\");\n \t}\n\n if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)\n {\n\n printf(\" cannot bind socket: %d. \\n\",errno);\n close(fd);\n\n return 0;\n\n }\n\n char buf[MAX_BUF];\n double degree = 90.0;\n if(ac > 1) {\n \tdegree = ::atof(av[1]);\n }\n degree = std::fabs(degree);\n int iRound = degree\/iConstRound;\n double dRemain = degree - (iRound *iConstRound);\n double startDeg = 0.0;\n bool restartBase = true;\n chrono::steady_clock::time_point start = std::chrono::steady_clock::now();\n int msRun = 0;\n \/\/ 1000 ms \n while(msRun < 1000) {\n \tchrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n \tmsRun = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n \t\/\/printf(\"msRun=<%d>\\n\",msRun);\n\n\n \t\n \tsocklen_t len = sizeof(addr);\n int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len);\n if(ret>0){\n \/\/printf(\"Received: %s\\n\", buf);\n string recvStr(buf,ret);\n \/\/std::cout << recvStr << std::endl;\n std::stringstream ss;\n ss << recvStr;\n try {\n \tboost::property_tree::ptree pt;\n \tboost::property_tree::read_json(ss, pt);\n \tauto current = pt.get<double>(\"yaw\");\n \t\/\/std::cout << current << std::endl;\n \tif(restartBase) {\n \t\tstartDeg = current;\n \t\trestartBase = false;\n \t\tcontinue;\n \t}\n \tdouble dRoundRad = 0.0;\n \tif(iRound >0) {\n \t\tdRoundRad = iConstRoundLimit;\n \t} else {\n \t\tdRoundRad = sin(PI*dRemain\/180.0);\n \t}\n \tdouble diffDeg = std::fabs(current - startDeg);\n \tstd::cout << \"diffDeg=<\" << diffDeg <<\">\"<< std::endl;\n \t\/\/\/ over \n \tif(diffDeg > iConstRound) {\n \t\tdiffDeg = std::fabs(360 -diffDeg);\n \t}\n \tstd::cout << \"diffDeg=<\" << diffDeg <<\">\"<< std::endl;\n \tdouble diffRad = (PI*diffDeg\/180.0);\n \tdouble diff = dRoundRad - sin(diffRad);\n \tstd::cout << \"diff=<\" << diff <<\">\"<< std::endl;\n \tif(diff <=0) {\n \t\tstd::cout << \"iRound=<\" << iRound <<\">\"<< std::endl;\n \t\tif(iRound >0) {\n \t\t\tiRound--;\n\t \t\trestartBase = true;\n \t\t}\n \t\telse {\n \t\t\tbreak;\n \t\t}\n \t}\n } catch(std::exception e) {\n \tstd::cout << e.what() << std::endl;\n }\n } else if (ret==0){\n \t\/\/printf(\"ret=<%d>\\n\",ret);\n } else {\n \t\/\/printf(\"ret=<%d>\\n\",ret);\n }\n }\n close(fd);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <osvr\/ClientKit\/Context.h>\r\n#include <osvr\/ClientKit\/Interface.h>\r\n#include <osvr\/ClientKit\/InterfaceStateC.h>\r\n\r\n#include <windows.h>\r\n#include <iostream>\r\n#include <chrono>\r\n\r\n\/\/ OSVR Helper Functions\r\nnamespace osvrMouseTracker\r\n{\r\n\tdouble osvrQuatGetPitch(const OSVR_Quaternion *p)\r\n\t{\r\n\t\treturn asin(2.0f * (osvrQuatGetX(p) * osvrQuatGetY(p) - osvrQuatGetW(p) * osvrQuatGetZ(p)));\r\n\r\n\t}\r\n\r\n\tdouble osvrQuatGetYaw(const OSVR_Quaternion *p)\r\n\t{\r\n\t\treturn atan2(2.0f * osvrQuatGetX(p) * osvrQuatGetZ(p) + 2.0f * osvrQuatGetY(p) * osvrQuatGetW(p), 1.0f - 2.0f * (osvrQuatGetZ(p) * osvrQuatGetZ(p) + osvrQuatGetY(p) * osvrQuatGetY(p)));\r\n\r\n\t}\r\n\r\n\tdouble osvrQuatGetRoll(const OSVR_Quaternion *p)\r\n\t{\r\n\t\treturn atan2(2.0f * osvrQuatGetX(p) * osvrQuatGetW(p) + 2.0f * osvrQuatGetZ(p) * osvrQuatGetY(p), 1.0f - 2.0f * (osvrQuatGetY(p) * osvrQuatGetY(p) + osvrQuatGetW(p) * osvrQuatGetW(p)));\r\n\r\n\t}\r\n\r\n}\r\n\r\nint main()\r\n{\r\n\tosvr::clientkit::ClientContext context(\"com.osvr.MouseTracker\");\r\n\r\n\t\/\/ HMD Interface: \/me\/head\r\n\tosvr::clientkit::Interface hmd = context.getInterface(\"\/me\/head\");\r\n\r\n\tbool isInitState = false, isActive = false, isKeyDown = false, isKeyAction = false;\r\n\tOSVR_PoseState state, prevState;\r\n\tstd::chrono::high_resolution_clock::time_point stateTime, prevStateTime;\r\n\r\n\twhile (true)\r\n\t{\r\n\t\t\/\/ Update HMD Tracker State\r\n\t\tcontext.update();\r\n\r\n\t\t\/\/ Acquire Current HMD Orientation\r\n\t\tOSVR_TimeValue timestamp;\r\n\t\tOSVR_ReturnCode ret = osvrGetPoseState(hmd.get(), ×tamp, &state);\r\n\t\tstateTime = std::chrono::steady_clock::now();\r\n\r\n\t\tif (ret == OSVR_RETURN_SUCCESS)\r\n\t\t{\r\n\t\t\t\/\/ Toggle Mouse Tracking Using Shift Key\r\n\t\t\tisKeyDown = (GetAsyncKeyState(VK_SHIFT) >= 0);\r\n\t\t\tif (isKeyDown && !isKeyAction) isKeyAction = true;\r\n\t\t\tif (!isKeyDown && isKeyAction)\r\n\t\t\t{\r\n\t\t\t\tisActive = !isActive;\r\n\t\t\t\tisKeyAction = false;\r\n\r\n\t\t\t}\r\n\r\n\t\t\tif (isInitState && isActive)\r\n\t\t\t{\r\n\t\t\t\t\/\/ Calculate X-Axis Rotation From HMD Yaw\r\n\t\t\t\tdouble xAngle = osvrMouseTracker::osvrQuatGetYaw(&state.rotation);\r\n\t\t\t\tdouble xAnglePrev = osvrMouseTracker::osvrQuatGetYaw(&prevState.rotation);\r\n\r\n\t\t\t\t\/\/ Calculate Y-Axis Rotation From HMD Pitch\r\n\t\t\t\tdouble yAngle = osvrMouseTracker::osvrQuatGetPitch(&state.rotation);\r\n\t\t\t\tdouble yAnglePrev = osvrMouseTracker::osvrQuatGetPitch(&prevState.rotation);\r\n\r\n\t\t\t\tconst double SCALING_FACTOR = 1000000.0f;\r\n\t\t\t\tconst double SENSITIVITY = 20.0f;\r\n\r\n\t\t\t\t\/\/ Calculate X-Axis Rotation Delta\r\n\t\t\t\tint xCurAngle = (xAngle * (180 \/ 3.141592654)) * SCALING_FACTOR;\r\n\t\t\t\tint xPrevAngle = (xAnglePrev * (180 \/ 3.141592654)) * SCALING_FACTOR;\r\n\t\t\t\tif (xCurAngle < 0) xCurAngle += (360 * SCALING_FACTOR);\r\n\t\t\t\tif (xPrevAngle < 0) xPrevAngle += (360 * SCALING_FACTOR);\r\n\t\t\t\tint xDeltaAngle = (xCurAngle - xPrevAngle); \/\/ 360 (Turning Left) > 180 > 0 (Turning Right)\r\n\r\n\t\t\t\t\/\/ Calculate Y-Axis Rotation Delta\r\n\t\t\t\tint yCurAngle = (yAngle * (180 \/ 3.141592654)) * SCALING_FACTOR;\r\n\t\t\t\tint yPrevAngle = (yAnglePrev * (180 \/ 3.141592654)) * SCALING_FACTOR;\r\n\t\t\t\tint yDeltaAngle = (yCurAngle - yPrevAngle); \/\/ -90 (Facing Up) > 0 > 90 (Facing Down)\r\n\r\n\t\t\t\tauto elaspedTime = std::chrono::duration_cast<std::chrono::milliseconds>(stateTime - prevStateTime).count();\r\n\r\n\t\t\t\tif (elaspedTime >= 10)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble xDeltaPos = (static_cast<double>(xDeltaAngle) * elaspedTime \/ SCALING_FACTOR);\r\n\t\t\t\t\tdouble yDeltaPos = (static_cast<double>(yDeltaAngle) * elaspedTime \/ SCALING_FACTOR);\r\n\t\t\t\t\tstd::cout << elaspedTime << \"ms Elapsed, X: \" << xCurAngle \/ SCALING_FACTOR << \", \" << xDeltaPos << \", Y: \" << yCurAngle \/ SCALING_FACTOR << \", \" << yDeltaPos << std::endl;\r\n\t\t\t\t\tINPUT input;\r\n\t\t\t\t\tinput.type = INPUT_MOUSE;\r\n\t\t\t\t\tinput.mi.mouseData = 0;\r\n\t\t\t\t\tinput.mi.dx = -xDeltaPos;\r\n\t\t\t\t\tinput.mi.dy = yDeltaPos;\r\n\t\t\t\t\t\/\/input.mi.dx = -(static_cast<float>(xDeltaAngle) \/ SCALING_FACTOR) * SENSITIVITY;\/\/ *(65536.0f \/ GetSystemMetrics(SM_CXSCREEN));\r\n\t\t\t\t\t\/\/input.mi.dy = -(static_cast<float>(yDeltaAngle) \/ SCALING_FACTOR) * SENSITIVITY;\/\/ *(65536.0f \/ GetSystemMetrics(SM_CYSCREEN));\r\n\t\t\t\t\tinput.mi.dwFlags = MOUSEEVENTF_MOVE;\/\/ | MOUSEEVENTF_ABSOLUTE;\r\n\t\t\t\t\tSendInput(1, &input, sizeof(input));\r\n\r\n\t\t\t\t\t\/\/POINT mousepos;\r\n\t\t\t\t\t\/\/GetCursorPos(&mousepos);\r\n\t\t\t\t\t\/\/SetCursorPos(mousepos.x - static_cast<int>(static_cast<float>(xDeltaAngle) \/ SCALING_FACTOR) * SENSITIVITY, mousepos.y - static_cast<int>(static_cast<float>(yDeltaAngle) \/ SCALING_FACTOR) * SENSITIVITY);\r\n\r\n\t\t\t\t\tprevState = state;\r\n\t\t\t\t\tprevStateTime = stateTime;\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tisInitState = true;\r\n\t\t\t\tprevState = state;\r\n\t\t\t\tprevStateTime = stateTime;\r\n\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn 0;\r\n\r\n}\r\n<commit_msg>Switched to calculating mouse delta using HMD's angular velocity report to eliminate euler angle singularities.<commit_after>#include <osvr\/ClientKit\/Context.h>\r\n#include <osvr\/ClientKit\/Interface.h>\r\n#include <osvr\/ClientKit\/InterfaceStateC.h>\r\n\r\n#include <windows.h>\r\n#include <iostream>\r\n#include <chrono>\r\n\r\n\/\/ OSVR Helper Functions\r\nnamespace osvrMathHelpers\r\n{\r\n\t\/\/ Extract Pitch Angle From Quaternion\r\n\tdouble osvrQuatGetPitch(const OSVR_Quaternion *q)\r\n\t{\r\n\t\treturn asin(2.0f * (osvrQuatGetX(q) * osvrQuatGetY(q) - osvrQuatGetW(q) * osvrQuatGetZ(q)));\r\n\r\n\t}\r\n\r\n\t\/\/ Extract Yaw Angle From Quaternion\r\n\tdouble osvrQuatGetYaw(const OSVR_Quaternion *q)\r\n\t{\r\n\t\treturn atan2(2.0f * osvrQuatGetX(q) * osvrQuatGetZ(q) + 2.0f * osvrQuatGetY(q) * osvrQuatGetW(q), 1.0f - 2.0f * (osvrQuatGetZ(q) * osvrQuatGetZ(q) + osvrQuatGetY(q) * osvrQuatGetY(q)));\r\n\r\n\t}\r\n\r\n\t\/\/ Extract Roll Angle From Quaternion\r\n\tdouble osvrQuatGetRoll(const OSVR_Quaternion *q)\r\n\t{\r\n\t\treturn atan2(2.0f * osvrQuatGetX(q) * osvrQuatGetW(q) + 2.0f * osvrQuatGetZ(q) * osvrQuatGetY(q), 1.0f - 2.0f * (osvrQuatGetY(q) * osvrQuatGetY(q) + osvrQuatGetW(q) * osvrQuatGetW(q)));\r\n\r\n\t}\r\n\r\n}\r\n\r\nint main()\r\n{\r\n\tosvr::clientkit::ClientContext context(\"com.osvr.MouseTracker\");\r\n\r\n\t\/\/ HMD Interface: \/me\/head\r\n\tosvr::clientkit::Interface hmd = context.getInterface(\"\/me\/head\");\r\n\r\n\tbool isInitState = false, isActive = false, isKeyDown = false, isKeyAction = false;\r\n\tOSVR_AngularVelocityState angularVelocityState, prevAngularVelocityState;\r\n\tstd::chrono::high_resolution_clock::time_point stateTime, prevStateTime = std::chrono::steady_clock::now();\r\n\r\n\twhile (true)\r\n\t{\r\n\t\tstateTime = std::chrono::steady_clock::now();\r\n\t\tauto elaspedTime = std::chrono::duration_cast<std::chrono::milliseconds>(stateTime - prevStateTime).count();\r\n\r\n\t\t\/\/ Update HMD Tracker State Every 10ms\r\n\t\tif (elaspedTime >= 10)\r\n\t\t{\r\n\t\t\t\/\/ Update HMD Tracker State\r\n\t\t\tcontext.update();\r\n\r\n\t\t\t\/\/ Acquire Current HMD Orientation\r\n\t\t\tOSVR_TimeValue timestamp;\r\n\t\t\tOSVR_ReturnCode ret = osvrGetAngularVelocityState(hmd.get(), ×tamp, &angularVelocityState);\r\n\r\n\t\t\t\/\/ Toggle Mouse Tracking Using Shift Key\r\n\t\t\tisKeyDown = (GetAsyncKeyState(VK_SHIFT) >= 0);\r\n\t\t\tif (isKeyDown && !isKeyAction) isKeyAction = true;\r\n\t\t\tif (!isKeyDown && isKeyAction)\r\n\t\t\t{\r\n\t\t\t\tisActive = !isActive;\r\n\t\t\t\tisKeyAction = false;\r\n\r\n\t\t\t}\r\n\r\n\t\t\tif (ret == OSVR_RETURN_SUCCESS)\r\n\t\t\t{\r\n\t\t\t\tif (isInitState && isActive)\r\n\t\t\t\t{\r\n\t\t\t\t\tconst double SCALING_FACTOR = 1000000.0f;\r\n\t\t\t\t\tconst double SENSITIVITY = 5.0f;\r\n\r\n\t\t\t\t\t\/\/ Calculate X-Axis Rotation Delta From HMD Pitch\r\n\t\t\t\t\tdouble xAngle = osvrMathHelpers::osvrQuatGetPitch(&angularVelocityState.incrementalRotation);\r\n\t\t\t\t\tint xDeltaAngle = (xAngle * (180 \/ 3.141592654)) * SCALING_FACTOR;\r\n\r\n\t\t\t\t\t\/\/ Calculate Y-Axis Rotation Delta From HMD Yaw\r\n\t\t\t\t\tdouble yAngle = osvrMathHelpers::osvrQuatGetYaw(&angularVelocityState.incrementalRotation);\r\n\t\t\t\t\tint yDeltaAngle = (yAngle * (180 \/ 3.141592654)) * SCALING_FACTOR;\r\n\r\n\t\t\t\t\tdouble xDeltaPos = (static_cast<double>(xDeltaAngle) * elaspedTime \/ SCALING_FACTOR) * SENSITIVITY;\r\n\t\t\t\t\tdouble yDeltaPos = (static_cast<double>(yDeltaAngle) * elaspedTime \/ SCALING_FACTOR) * SENSITIVITY;\r\n\r\n\t\t\t\t\tINPUT input;\r\n\t\t\t\t\tinput.type = INPUT_MOUSE;\r\n\t\t\t\t\tinput.mi.mouseData = 0;\r\n\t\t\t\t\tinput.mi.dx = xDeltaPos;\r\n\t\t\t\t\tinput.mi.dy = yDeltaPos;\r\n\t\t\t\t\tinput.mi.dwFlags = MOUSEEVENTF_MOVE;\r\n\t\t\t\t\tSendInput(1, &input, sizeof(input));\r\n\r\n\t\t\t\t\tprevAngularVelocityState = angularVelocityState;\r\n\t\t\t\t\tprevStateTime = stateTime;\r\n\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tisInitState = true;\r\n\t\t\t\t\tprevAngularVelocityState = angularVelocityState;\r\n\t\t\t\t\tprevStateTime = stateTime;\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn 0;\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008, Google Inc.\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:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. 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#include \"config.h\"\n\n#if ENABLE(SVG)\n#include \"SVGPaintServerSolid.h\"\n\n#include \"GraphicsContext.h\"\n#include \"RenderPath.h\"\n#include \"SkiaSupport.h\"\n\n#include <SkPaintContext.h>\n#include \"SkiaUtils.h\"\n\nnamespace WebCore {\n\n\/\/ TODO(jhaas): probably there's already an implementation of this somewhere; find it\n inline int FloatAlphaToInt(float alpha) { return std::min(0xFF, std::max(0, static_cast<int>(alpha * 0xFF))); }\n\nbool SVGPaintServerSolid::setup(GraphicsContext*& context, const RenderObject* object, SVGPaintTargetType type, bool isPaintingText) const\n{\n const RenderStyle* style = object ? object->style() : NULL;\n const SVGRenderStyle* svgStyle = style ? style->svgStyle() : NULL;\n\n int red = color().red();\n int green = color().green();\n int blue = color().blue();\n int alpha = color().alpha(); \n\n if ((type & ApplyToFillTargetType) && (!svgStyle || svgStyle->hasFill())) {\n if (svgStyle) {\n alpha = FloatAlphaToInt(svgStyle->fillOpacity());\n context->setFillRule(svgStyle->fillRule());\n }\n\n if (isPaintingText) \n context->setTextDrawingMode(cTextFill);\n\n context->setFillColor(SkColorSetARGB(alpha, red, green, blue));\n }\n\n if ((type & ApplyToStrokeTargetType) && (!svgStyle || svgStyle->hasStroke())) {\n if (svgStyle) {\n alpha = FloatAlphaToInt(svgStyle->strokeOpacity());\n context->setStrokeColor(SkColorSetARGB(alpha, red, green, blue));\n }\n\n if (isPaintingText) \n context->setTextDrawingMode(cTextStroke);\n\n applyStrokeStyleToContext(context, style, object);\n }\n\n return true;\n}\n\n} \/\/ namespace WebCore\n\n#endif\n<commit_msg>Add missing file from my last checkin moving Skia painting objects around. Review URL: http:\/\/codereview.chromium.org\/8759<commit_after>\/\/ Copyright 2008, Google Inc.\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:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. 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#include \"config.h\"\n\n#if ENABLE(SVG)\n#include \"SVGPaintServerSolid.h\"\n\n#include \"GraphicsContext.h\"\n#include \"RenderPath.h\"\n#include \"SkiaSupport.h\"\n\n#include \"SkiaUtils.h\"\n\nnamespace WebCore {\n\n\/\/ TODO(jhaas): probably there's already an implementation of this somewhere; find it\n inline int FloatAlphaToInt(float alpha) { return std::min(0xFF, std::max(0, static_cast<int>(alpha * 0xFF))); }\n\nbool SVGPaintServerSolid::setup(GraphicsContext*& context, const RenderObject* object, SVGPaintTargetType type, bool isPaintingText) const\n{\n const RenderStyle* style = object ? object->style() : NULL;\n const SVGRenderStyle* svgStyle = style ? style->svgStyle() : NULL;\n\n int red = color().red();\n int green = color().green();\n int blue = color().blue();\n int alpha = color().alpha(); \n\n if ((type & ApplyToFillTargetType) && (!svgStyle || svgStyle->hasFill())) {\n if (svgStyle) {\n alpha = FloatAlphaToInt(svgStyle->fillOpacity());\n context->setFillRule(svgStyle->fillRule());\n }\n\n if (isPaintingText) \n context->setTextDrawingMode(cTextFill);\n\n context->setFillColor(SkColorSetARGB(alpha, red, green, blue));\n }\n\n if ((type & ApplyToStrokeTargetType) && (!svgStyle || svgStyle->hasStroke())) {\n if (svgStyle) {\n alpha = FloatAlphaToInt(svgStyle->strokeOpacity());\n context->setStrokeColor(SkColorSetARGB(alpha, red, green, blue));\n }\n\n if (isPaintingText) \n context->setTextDrawingMode(cTextStroke);\n\n applyStrokeStyleToContext(context, style, object);\n }\n\n return true;\n}\n\n} \/\/ namespace WebCore\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: uielementwrapperbase.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 14:01:27 $\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_framework.hxx\"\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_HELPER_UIELEMENTWRAPPERBASE_HXX_\n#include <helper\/uielementwrapperbase.hxx>\n#endif\n\n#ifndef __FRAMEWORK_GENERAL_H_\n#include <general.h>\n#endif\n\n#ifndef __FRAMEWORK_PROPERTIES_H_\n#include <properties.h>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_\n#include <threadhelp\/resetableguard.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes of other projects\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\nconst int UIELEMENT_PROPHANDLE_RESOURCEURL = 1;\nconst int UIELEMENT_PROPHANDLE_TYPE = 2;\nconst int UIELEMENT_PROPHANDLE_FRAME = 3;\nconst int UIELEMENT_PROPCOUNT = 3;\nconst rtl::OUString UIELEMENT_PROPNAME_RESOURCEURL( RTL_CONSTASCII_USTRINGPARAM( \"ResourceURL\" ));\nconst rtl::OUString UIELEMENT_PROPNAME_TYPE( RTL_CONSTASCII_USTRINGPARAM( \"Type\" ));\nconst rtl::OUString UIELEMENT_PROPNAME_FRAME( RTL_CONSTASCII_USTRINGPARAM( \"Frame\" ));\n\nusing namespace rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::frame;\n\nnamespace framework\n{\n\n\/\/*****************************************************************************************************************\n\/\/ XInterface, XTypeProvider\n\/\/*****************************************************************************************************************\nDEFINE_XINTERFACE_8 ( UIElementWrapperBase ,\n OWeakObject ,\n DIRECT_INTERFACE( ::com::sun::star::lang::XTypeProvider ),\n DIRECT_INTERFACE( ::com::sun::star::ui::XUIElement ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XMultiPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XFastPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::lang::XInitialization ),\n DIRECT_INTERFACE( ::com::sun::star::util::XUpdatable ),\n DIRECT_INTERFACE( ::com::sun::star::lang::XComponent )\n )\n\nDEFINE_XTYPEPROVIDER_8 ( UIElementWrapperBase ,\n ::com::sun::star::lang::XTypeProvider ,\n ::com::sun::star::ui::XUIElement ,\n ::com::sun::star::beans::XMultiPropertySet ,\n ::com::sun::star::beans::XFastPropertySet ,\n ::com::sun::star::beans::XPropertySet ,\n ::com::sun::star::lang::XInitialization ,\n ::com::sun::star::util::XUpdatable ,\n ::com::sun::star::lang::XComponent\n )\n\nUIElementWrapperBase::UIElementWrapperBase( sal_Int16 nType )\n : ThreadHelpBase ( &Application::GetSolarMutex() )\n , ::cppu::OBroadcastHelperVar< ::cppu::OMultiTypeInterfaceContainerHelper, ::cppu::OMultiTypeInterfaceContainerHelper::keyType >( m_aLock.getShareableOslMutex() )\n , ::cppu::OPropertySetHelper ( *(static_cast< ::cppu::OBroadcastHelper* >(this)) )\n , ::cppu::OWeakObject ( )\n , m_aListenerContainer ( m_aLock.getShareableOslMutex() )\n , m_nType ( nType )\n , m_bInitialized ( sal_False )\n , m_bDisposed ( sal_False )\n{\n}\n\nUIElementWrapperBase::~UIElementWrapperBase()\n{\n}\n\nvoid SAL_CALL UIElementWrapperBase::dispose() throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ must be implemented by derived class\n ResetableGuard aLock( m_aLock );\n m_bDisposed = sal_True;\n}\n\nvoid SAL_CALL UIElementWrapperBase::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)\n{\n m_aListenerContainer.addInterface( ::getCppuType( ( const css::uno::Reference< css::lang::XEventListener >* ) NULL ), xListener );\n}\n\nvoid SAL_CALL UIElementWrapperBase::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)\n{\n m_aListenerContainer.removeInterface( ::getCppuType( ( const css::uno::Reference< css::lang::XEventListener >* ) NULL ), xListener );\n}\n\nvoid SAL_CALL UIElementWrapperBase::initialize( const Sequence< Any >& aArguments )\nthrow ( Exception, RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( !m_bInitialized )\n {\n for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )\n {\n PropertyValue aPropValue;\n if ( aArguments[n] >>= aPropValue )\n {\n if ( aPropValue.Name.equalsAscii( \"ResourceURL\" ))\n aPropValue.Value >>= m_aResourceURL;\n else if ( aPropValue.Name.equalsAscii( \"Frame\" ))\n {\n Reference< XFrame > xFrame;\n aPropValue.Value >>= xFrame;\n m_xWeakFrame = xFrame;\n }\n }\n }\n\n m_bInitialized = sal_True;\n }\n}\n\n\/\/ XUpdatable\nvoid SAL_CALL UIElementWrapperBase::update() throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ can be implemented by derived class\n}\n\n\/\/ XPropertySet helper\nsal_Bool SAL_CALL UIElementWrapperBase::convertFastPropertyValue( Any& \/*aConvertedValue*\/ ,\n Any& \/*aOldValue*\/ ,\n sal_Int32 \/*nHandle*\/ ,\n const Any& \/*aValue*\/ ) throw( com::sun::star::lang::IllegalArgumentException )\n{\n \/\/ Initialize state with FALSE !!!\n \/\/ (Handle can be invalid)\n return sal_False ;\n}\n\nvoid SAL_CALL UIElementWrapperBase::setFastPropertyValue_NoBroadcast( sal_Int32 \/*nHandle*\/ ,\n const com::sun::star::uno::Any& \/*aValue*\/ ) throw( com::sun::star::uno::Exception )\n{\n}\n\nvoid SAL_CALL UIElementWrapperBase::getFastPropertyValue( com::sun::star::uno::Any& aValue ,\n sal_Int32 nHandle ) const\n{\n switch( nHandle )\n {\n case UIELEMENT_PROPHANDLE_RESOURCEURL:\n aValue <<= m_aResourceURL;\n break;\n case UIELEMENT_PROPHANDLE_TYPE:\n aValue <<= m_nType;\n break;\n case UIELEMENT_PROPHANDLE_FRAME:\n Reference< XFrame > xFrame( m_xWeakFrame );\n aValue <<= xFrame;\n break;\n }\n}\n\n::cppu::IPropertyArrayHelper& SAL_CALL UIElementWrapperBase::getInfoHelper()\n{\n \/\/ Optimize this method !\n \/\/ We initialize a static variable only one time. And we don't must use a mutex at every call!\n \/\/ For the first call; pInfoHelper is NULL - for the second call pInfoHelper is different from NULL!\n static ::cppu::OPropertyArrayHelper* pInfoHelper = NULL;\n\n if( pInfoHelper == NULL )\n {\n \/\/ Ready for multithreading\n osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;\n\n \/\/ Control this pointer again, another instance can be faster then these!\n if( pInfoHelper == NULL )\n {\n \/\/ Define static member to give structure of properties to baseclass \"OPropertySetHelper\".\n \/\/ \"impl_getStaticPropertyDescriptor\" is a non exported and static funtion, who will define a static propertytable.\n \/\/ \"sal_True\" say: Table is sorted by name.\n static ::cppu::OPropertyArrayHelper aInfoHelper( impl_getStaticPropertyDescriptor(), sal_True );\n pInfoHelper = &aInfoHelper;\n }\n }\n\n return(*pInfoHelper);\n}\n\ncom::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL UIElementWrapperBase::getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ Optimize this method !\n \/\/ We initialize a static variable only one time. And we don't must use a mutex at every call!\n \/\/ For the first call; pInfo is NULL - for the second call pInfo is different from NULL!\n static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo >* pInfo = NULL;\n\n if( pInfo == NULL )\n {\n \/\/ Ready for multithreading\n osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;\n \/\/ Control this pointer again, another instance can be faster then these!\n if( pInfo == NULL )\n {\n \/\/ Create structure of propertysetinfo for baseclass \"OPropertySetHelper\".\n \/\/ (Use method \"getInfoHelper()\".)\n static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );\n pInfo = &xInfo;\n }\n }\n\n return (*pInfo);\n}\n\nconst com::sun::star::uno::Sequence< com::sun::star::beans::Property > UIElementWrapperBase::impl_getStaticPropertyDescriptor()\n{\n \/\/ Create a new static property array to initialize sequence!\n \/\/ Table of all predefined properties of this class. Its used from OPropertySetHelper-class!\n \/\/ Don't forget to change the defines (see begin of this file), if you add, change or delete a property in this list!!!\n \/\/ It's necessary for methods of OPropertySetHelper.\n \/\/ ATTENTION:\n \/\/ YOU MUST SORT FOLLOW TABLE BY NAME ALPHABETICAL !!!\n\n static const com::sun::star::beans::Property pProperties[] =\n {\n com::sun::star::beans::Property( UIELEMENT_PROPNAME_FRAME , UIELEMENT_PROPHANDLE_FRAME , ::getCppuType((Reference< XFrame >*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY ),\n com::sun::star::beans::Property( UIELEMENT_PROPNAME_RESOURCEURL , UIELEMENT_PROPHANDLE_RESOURCEURL , ::getCppuType((sal_Int16*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY ),\n com::sun::star::beans::Property( UIELEMENT_PROPNAME_TYPE , UIELEMENT_PROPHANDLE_TYPE , ::getCppuType((const ::rtl::OUString*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY )\n };\n \/\/ Use it to initialize sequence!\n static const com::sun::star::uno::Sequence< com::sun::star::beans::Property > lPropertyDescriptor( pProperties, UIELEMENT_PROPCOUNT );\n \/\/ Return static \"PropertyDescriptor\"\n return lPropertyDescriptor;\n}\n\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.262); FILE MERGED 2008\/04\/01 15:18:39 thb 1.7.262.3: #i85898# Stripping all external header guards 2008\/04\/01 10:58:07 thb 1.7.262.2: #i85898# Stripping all external header guards 2008\/03\/28 15:35:17 rt 1.7.262.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: uielementwrapperbase.cxx,v $\n * $Revision: 1.8 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_framework.hxx\"\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n#include <helper\/uielementwrapperbase.hxx>\n#include <general.h>\n#include <properties.h>\n#include <threadhelp\/resetableguard.hxx>\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes of other projects\n\/\/_________________________________________________________________________________________________________________\n#include <vcl\/svapp.hxx>\n\nconst int UIELEMENT_PROPHANDLE_RESOURCEURL = 1;\nconst int UIELEMENT_PROPHANDLE_TYPE = 2;\nconst int UIELEMENT_PROPHANDLE_FRAME = 3;\nconst int UIELEMENT_PROPCOUNT = 3;\nconst rtl::OUString UIELEMENT_PROPNAME_RESOURCEURL( RTL_CONSTASCII_USTRINGPARAM( \"ResourceURL\" ));\nconst rtl::OUString UIELEMENT_PROPNAME_TYPE( RTL_CONSTASCII_USTRINGPARAM( \"Type\" ));\nconst rtl::OUString UIELEMENT_PROPNAME_FRAME( RTL_CONSTASCII_USTRINGPARAM( \"Frame\" ));\n\nusing namespace rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::frame;\n\nnamespace framework\n{\n\n\/\/*****************************************************************************************************************\n\/\/ XInterface, XTypeProvider\n\/\/*****************************************************************************************************************\nDEFINE_XINTERFACE_8 ( UIElementWrapperBase ,\n OWeakObject ,\n DIRECT_INTERFACE( ::com::sun::star::lang::XTypeProvider ),\n DIRECT_INTERFACE( ::com::sun::star::ui::XUIElement ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XMultiPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XFastPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::lang::XInitialization ),\n DIRECT_INTERFACE( ::com::sun::star::util::XUpdatable ),\n DIRECT_INTERFACE( ::com::sun::star::lang::XComponent )\n )\n\nDEFINE_XTYPEPROVIDER_8 ( UIElementWrapperBase ,\n ::com::sun::star::lang::XTypeProvider ,\n ::com::sun::star::ui::XUIElement ,\n ::com::sun::star::beans::XMultiPropertySet ,\n ::com::sun::star::beans::XFastPropertySet ,\n ::com::sun::star::beans::XPropertySet ,\n ::com::sun::star::lang::XInitialization ,\n ::com::sun::star::util::XUpdatable ,\n ::com::sun::star::lang::XComponent\n )\n\nUIElementWrapperBase::UIElementWrapperBase( sal_Int16 nType )\n : ThreadHelpBase ( &Application::GetSolarMutex() )\n , ::cppu::OBroadcastHelperVar< ::cppu::OMultiTypeInterfaceContainerHelper, ::cppu::OMultiTypeInterfaceContainerHelper::keyType >( m_aLock.getShareableOslMutex() )\n , ::cppu::OPropertySetHelper ( *(static_cast< ::cppu::OBroadcastHelper* >(this)) )\n , ::cppu::OWeakObject ( )\n , m_aListenerContainer ( m_aLock.getShareableOslMutex() )\n , m_nType ( nType )\n , m_bInitialized ( sal_False )\n , m_bDisposed ( sal_False )\n{\n}\n\nUIElementWrapperBase::~UIElementWrapperBase()\n{\n}\n\nvoid SAL_CALL UIElementWrapperBase::dispose() throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ must be implemented by derived class\n ResetableGuard aLock( m_aLock );\n m_bDisposed = sal_True;\n}\n\nvoid SAL_CALL UIElementWrapperBase::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)\n{\n m_aListenerContainer.addInterface( ::getCppuType( ( const css::uno::Reference< css::lang::XEventListener >* ) NULL ), xListener );\n}\n\nvoid SAL_CALL UIElementWrapperBase::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)\n{\n m_aListenerContainer.removeInterface( ::getCppuType( ( const css::uno::Reference< css::lang::XEventListener >* ) NULL ), xListener );\n}\n\nvoid SAL_CALL UIElementWrapperBase::initialize( const Sequence< Any >& aArguments )\nthrow ( Exception, RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( !m_bInitialized )\n {\n for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )\n {\n PropertyValue aPropValue;\n if ( aArguments[n] >>= aPropValue )\n {\n if ( aPropValue.Name.equalsAscii( \"ResourceURL\" ))\n aPropValue.Value >>= m_aResourceURL;\n else if ( aPropValue.Name.equalsAscii( \"Frame\" ))\n {\n Reference< XFrame > xFrame;\n aPropValue.Value >>= xFrame;\n m_xWeakFrame = xFrame;\n }\n }\n }\n\n m_bInitialized = sal_True;\n }\n}\n\n\/\/ XUpdatable\nvoid SAL_CALL UIElementWrapperBase::update() throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ can be implemented by derived class\n}\n\n\/\/ XPropertySet helper\nsal_Bool SAL_CALL UIElementWrapperBase::convertFastPropertyValue( Any& \/*aConvertedValue*\/ ,\n Any& \/*aOldValue*\/ ,\n sal_Int32 \/*nHandle*\/ ,\n const Any& \/*aValue*\/ ) throw( com::sun::star::lang::IllegalArgumentException )\n{\n \/\/ Initialize state with FALSE !!!\n \/\/ (Handle can be invalid)\n return sal_False ;\n}\n\nvoid SAL_CALL UIElementWrapperBase::setFastPropertyValue_NoBroadcast( sal_Int32 \/*nHandle*\/ ,\n const com::sun::star::uno::Any& \/*aValue*\/ ) throw( com::sun::star::uno::Exception )\n{\n}\n\nvoid SAL_CALL UIElementWrapperBase::getFastPropertyValue( com::sun::star::uno::Any& aValue ,\n sal_Int32 nHandle ) const\n{\n switch( nHandle )\n {\n case UIELEMENT_PROPHANDLE_RESOURCEURL:\n aValue <<= m_aResourceURL;\n break;\n case UIELEMENT_PROPHANDLE_TYPE:\n aValue <<= m_nType;\n break;\n case UIELEMENT_PROPHANDLE_FRAME:\n Reference< XFrame > xFrame( m_xWeakFrame );\n aValue <<= xFrame;\n break;\n }\n}\n\n::cppu::IPropertyArrayHelper& SAL_CALL UIElementWrapperBase::getInfoHelper()\n{\n \/\/ Optimize this method !\n \/\/ We initialize a static variable only one time. And we don't must use a mutex at every call!\n \/\/ For the first call; pInfoHelper is NULL - for the second call pInfoHelper is different from NULL!\n static ::cppu::OPropertyArrayHelper* pInfoHelper = NULL;\n\n if( pInfoHelper == NULL )\n {\n \/\/ Ready for multithreading\n osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;\n\n \/\/ Control this pointer again, another instance can be faster then these!\n if( pInfoHelper == NULL )\n {\n \/\/ Define static member to give structure of properties to baseclass \"OPropertySetHelper\".\n \/\/ \"impl_getStaticPropertyDescriptor\" is a non exported and static funtion, who will define a static propertytable.\n \/\/ \"sal_True\" say: Table is sorted by name.\n static ::cppu::OPropertyArrayHelper aInfoHelper( impl_getStaticPropertyDescriptor(), sal_True );\n pInfoHelper = &aInfoHelper;\n }\n }\n\n return(*pInfoHelper);\n}\n\ncom::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL UIElementWrapperBase::getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ Optimize this method !\n \/\/ We initialize a static variable only one time. And we don't must use a mutex at every call!\n \/\/ For the first call; pInfo is NULL - for the second call pInfo is different from NULL!\n static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo >* pInfo = NULL;\n\n if( pInfo == NULL )\n {\n \/\/ Ready for multithreading\n osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;\n \/\/ Control this pointer again, another instance can be faster then these!\n if( pInfo == NULL )\n {\n \/\/ Create structure of propertysetinfo for baseclass \"OPropertySetHelper\".\n \/\/ (Use method \"getInfoHelper()\".)\n static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );\n pInfo = &xInfo;\n }\n }\n\n return (*pInfo);\n}\n\nconst com::sun::star::uno::Sequence< com::sun::star::beans::Property > UIElementWrapperBase::impl_getStaticPropertyDescriptor()\n{\n \/\/ Create a new static property array to initialize sequence!\n \/\/ Table of all predefined properties of this class. Its used from OPropertySetHelper-class!\n \/\/ Don't forget to change the defines (see begin of this file), if you add, change or delete a property in this list!!!\n \/\/ It's necessary for methods of OPropertySetHelper.\n \/\/ ATTENTION:\n \/\/ YOU MUST SORT FOLLOW TABLE BY NAME ALPHABETICAL !!!\n\n static const com::sun::star::beans::Property pProperties[] =\n {\n com::sun::star::beans::Property( UIELEMENT_PROPNAME_FRAME , UIELEMENT_PROPHANDLE_FRAME , ::getCppuType((Reference< XFrame >*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY ),\n com::sun::star::beans::Property( UIELEMENT_PROPNAME_RESOURCEURL , UIELEMENT_PROPHANDLE_RESOURCEURL , ::getCppuType((sal_Int16*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY ),\n com::sun::star::beans::Property( UIELEMENT_PROPNAME_TYPE , UIELEMENT_PROPHANDLE_TYPE , ::getCppuType((const ::rtl::OUString*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY )\n };\n \/\/ Use it to initialize sequence!\n static const com::sun::star::uno::Sequence< com::sun::star::beans::Property > lPropertyDescriptor( pProperties, UIELEMENT_PROPCOUNT );\n \/\/ Return static \"PropertyDescriptor\"\n return lPropertyDescriptor;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015-2016 The Gulden developers\n\/\/ Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)\n\/\/ Distributed under the GULDEN software license, see the accompanying\n\/\/ file COPYING\n\n#ifdef __APPLE__\n #include <TargetConditionals.h>\n#endif\n#include \"diff_common.h\"\n#include \"diff_delta.h\"\n#include \"diff_old.h\"\n\n#ifdef BUILD_IOS\n#include \"BRMerkleBlock.h\"\n#endif\n\n#ifdef __JAVA__\npackage org.bitcoinj.core;\nimport org.bitcoinj.store.BlockStore;\nimport java.math.BigInteger;\nimport org.bitcoinj.store.BlockStoreException;\npublic class CommonDiff extends DeltaDiff {\npublic static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(550000, 250000);\npublic static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(200, 437600);\npublic static\n#endif\nunsigned int GetNextWorkRequired(const INDEX_TYPE indexLast, const BLOCK_TYPE block, unsigned int nPowTargetSpacing, unsigned int nPowLimit\n#ifdef __JAVA__\n,final BlockStore blockStore\n#endif\t\n)\n{\n #ifndef __JAVA__\n static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(550000, 250000);\n static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(200, 437600);\n #endif\n\n\n if (INDEX_HEIGHT(indexLast)+1 >= nOldDiffSwitchoverBlock)\n {\n if (INDEX_HEIGHT(indexLast)+1 >= nDeltaSwitchoverBlock)\n {\n #ifdef __JAVA__\n return GetNextWorkRequired_DELTA(indexLast, block, (int)nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock, blockStore);\n #else\n return GetNextWorkRequired_DELTA(indexLast, block, nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock);\n #endif\n }\n else\n {\n return 524287999;\n }\n }\n return diff_old(INDEX_HEIGHT(indexLast)+1, nPowLimit);\n}\n\n\n#ifdef __JAVA__\n}\n#endif\n<commit_msg>Revert previous change.<commit_after>\/\/ Copyright (c) 2015-2016 The Gulden developers\n\/\/ Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)\n\/\/ Distributed under the GULDEN software license, see the accompanying\n\/\/ file COPYING\n\n#ifdef __APPLE__\n #include <TargetConditionals.h>\n#endif\n#include \"diff_common.h\"\n#include \"diff_delta.h\"\n#include \"diff_old.h\"\n\n#ifdef BUILD_IOS\n#include \"BRMerkleBlock.h\"\n#endif\n\n#ifdef __JAVA__\npackage org.bitcoinj.core;\nimport org.bitcoinj.store.BlockStore;\nimport java.math.BigInteger;\nimport org.bitcoinj.store.BlockStoreException;\npublic class CommonDiff extends DeltaDiff {\npublic static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(350000, 250000);\npublic static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(200, 437600);\npublic static\n#endif\nunsigned int GetNextWorkRequired(const INDEX_TYPE indexLast, const BLOCK_TYPE block, unsigned int nPowTargetSpacing, unsigned int nPowLimit\n#ifdef __JAVA__\n,final BlockStore blockStore\n#endif\t\n)\n{\n #ifndef __JAVA__\n static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(350000, 250000);\n static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(200, 437600);\n #endif\n\n\n if (INDEX_HEIGHT(indexLast)+1 >= nOldDiffSwitchoverBlock)\n {\n if (INDEX_HEIGHT(indexLast)+1 >= nDeltaSwitchoverBlock)\n {\n #ifdef __JAVA__\n return GetNextWorkRequired_DELTA(indexLast, block, (int)nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock, blockStore);\n #else\n return GetNextWorkRequired_DELTA(indexLast, block, nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock);\n #endif\n }\n else\n {\n return 524287999;\n }\n }\n return diff_old(INDEX_HEIGHT(indexLast)+1, nPowLimit);\n}\n\n\n#ifdef __JAVA__\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2011 StormMQ Limited\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#include <TestHarness.h>\n#include \"Thread\/Thread.h\"\n#include \"Thread\/FastMutex.h\"\n\n#include \"debug_helper.h\"\n\nSUITE(Thread)\n{\n class ThreadFixture\n {\n public:\n ThreadFixture() : saved_from_thread(0)\n {\n amqp_threading_initialize();\n amqp_mutex_initialize(&mutex);\n amqp_condition_initialize(&cv);\n }\n\n ~ThreadFixture()\n {\n amqp_condition_destroy(&cv);\n amqp_mutex_destroy(&mutex);\n amqp_threading_cleanup();\n }\n\n const char *saved_from_thread;\n\n amqp_mutex_t mutex;\n amqp_condition_variable_t cv;\n\n static const char *pattern;\n static void handler(void *argument);\n private:\n };\n\n const char *ThreadFixture::pattern = \"HeLlO wOrLd\";\n void ThreadFixture::handler(void *argument)\n {\n ThreadFixture *fixture = (ThreadFixture *) argument;\n amqp_mutex_lock(&fixture->mutex);\n\n fixture->saved_from_thread = ThreadFixture::pattern;\n\n amqp_condition_notify(&fixture->cv);\n\n amqp_mutex_unlock(&fixture->mutex);\n }\n\n \/\/ Not really proof that the threading wrappers do the right thing.\n TEST_FIXTURE(ThreadFixture, exercise_thread_api)\n {\n CHECK_EQUAL((void *) 0, saved_from_thread);\n\n amqp_mutex_lock(&mutex);\n amqp_thread_t *thread = amqp_thread_start(ThreadFixture::handler, this);\n amqp_condition_wait(&cv, &mutex);\n amqp_mutex_unlock(&mutex);\n\n amqp_thread_destroy(thread);\n\n CHECK_EQUAL(pattern, saved_from_thread);\n }\n\n class FastMutexFixture\n {\n public:\n FastMutexFixture() : count(0), thread_done_count(0), thread_ready_count(0)\n {\n amqp_threading_initialize();\n amqp_fast_mutex_initialize(&fast_mutex);\n amqp_mutex_initialize(&mutex);\n amqp_condition_initialize(&cv);\n amqp_condition_initialize(&cv_gate);\n }\n\n ~FastMutexFixture()\n {\n amqp_condition_destroy(&cv);\n amqp_condition_destroy(&cv_gate);\n amqp_mutex_destroy(&mutex);\n amqp_fast_mutex_destroy(&fast_mutex);\n amqp_threading_cleanup();\n }\n\n amqp_fast_mutex_t fast_mutex;\n amqp_mutex_t mutex;\n amqp_condition_variable_t cv;\n amqp_condition_variable_t cv_gate;\n\n int count;\n int thread_done_count;\n int thread_ready_count;\n static void handler(void *argument);\n private:\n };\n\n TEST_FIXTURE(FastMutexFixture, validate_fast_lock_lock_value)\n {\n CHECK_EQUAL(0, fast_mutex);\n amqp_fast_mutex_lock(&fast_mutex);\n CHECK_EQUAL(1, fast_mutex);\n amqp_fast_mutex_unlock(&fast_mutex);\n CHECK_EQUAL(0, fast_mutex);\n }\n\n void FastMutexFixture::handler(void *argument)\n {\n FastMutexFixture *fixture = (FastMutexFixture *) argument;\n\n amqp_mutex_lock(&fixture->mutex);\n fixture->thread_ready_count++;\n amqp_condition_notify(&fixture->cv);\n amqp_condition_wait(&fixture->cv_gate, &fixture->mutex);\n amqp_mutex_unlock(&fixture->mutex);\n\n for (int i = 0; i < 10000; i++)\n {\n amqp_fast_mutex_lock(&fixture->fast_mutex);\n fixture->count++;\n amqp_fast_mutex_unlock(&fixture->fast_mutex);\n }\n\n amqp_mutex_lock(&fixture->mutex);\n fixture->thread_done_count++;\n amqp_condition_notify(&fixture->cv);\n amqp_mutex_unlock(&fixture->mutex);\n }\n\n TEST_FIXTURE(FastMutexFixture, exercise_thread_api_with_fast_mutex)\n {\n const int N_THREADS = 11;\n amqp_thread_t *threads[N_THREADS];\n\n for (int i = 0; i < N_THREADS; i++)\n {\n threads[i] = amqp_thread_start(FastMutexFixture::handler, this);\n }\n\n amqp_mutex_lock(&mutex);\n while (thread_ready_count < N_THREADS)\n {\n amqp_condition_wait(&cv, &mutex);\n }\n amqp_condition_broadcast(&cv_gate);\n\n while (thread_done_count < N_THREADS)\n {\n amqp_condition_wait(&cv, &mutex);\n }\n amqp_mutex_unlock(&mutex);\n\n CHECK_EQUAL(N_THREADS * 10000, count);\n\n for (int i = 0; i < N_THREADS; i++)\n {\n amqp_thread_destroy(threads[i]);\n }\n }\n}\n<commit_msg>Ensure build works when LIBAMQP_DISABLE_FAST_MUTEX is defined<commit_after>\/*\n Copyright 2011 StormMQ Limited\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#include <TestHarness.h>\n#include \"Thread\/Thread.h\"\n#include \"Thread\/FastMutex.h\"\n\n#include \"debug_helper.h\"\n\nSUITE(Thread)\n{\n class ThreadFixture\n {\n public:\n ThreadFixture() : saved_from_thread(0)\n {\n amqp_threading_initialize();\n amqp_mutex_initialize(&mutex);\n amqp_condition_initialize(&cv);\n }\n\n ~ThreadFixture()\n {\n amqp_condition_destroy(&cv);\n amqp_mutex_destroy(&mutex);\n amqp_threading_cleanup();\n }\n\n const char *saved_from_thread;\n\n amqp_mutex_t mutex;\n amqp_condition_variable_t cv;\n\n static const char *pattern;\n static void handler(void *argument);\n private:\n };\n\n const char *ThreadFixture::pattern = \"HeLlO wOrLd\";\n void ThreadFixture::handler(void *argument)\n {\n ThreadFixture *fixture = (ThreadFixture *) argument;\n amqp_mutex_lock(&fixture->mutex);\n\n fixture->saved_from_thread = ThreadFixture::pattern;\n\n amqp_condition_notify(&fixture->cv);\n\n amqp_mutex_unlock(&fixture->mutex);\n }\n\n \/\/ Not really proof that the threading wrappers do the right thing.\n TEST_FIXTURE(ThreadFixture, exercise_thread_api)\n {\n CHECK_EQUAL((void *) 0, saved_from_thread);\n\n amqp_mutex_lock(&mutex);\n amqp_thread_t *thread = amqp_thread_start(ThreadFixture::handler, this);\n amqp_condition_wait(&cv, &mutex);\n amqp_mutex_unlock(&mutex);\n\n amqp_thread_destroy(thread);\n\n CHECK_EQUAL(pattern, saved_from_thread);\n }\n\n\n class FastMutexFixture\n {\n public:\n FastMutexFixture() : count(0), thread_done_count(0), thread_ready_count(0)\n {\n amqp_threading_initialize();\n amqp_fast_mutex_initialize(&fast_mutex);\n amqp_mutex_initialize(&mutex);\n amqp_condition_initialize(&cv);\n amqp_condition_initialize(&cv_gate);\n }\n\n ~FastMutexFixture()\n {\n amqp_condition_destroy(&cv);\n amqp_condition_destroy(&cv_gate);\n amqp_mutex_destroy(&mutex);\n amqp_fast_mutex_destroy(&fast_mutex);\n amqp_threading_cleanup();\n }\n\n amqp_fast_mutex_t fast_mutex;\n amqp_mutex_t mutex;\n amqp_condition_variable_t cv;\n amqp_condition_variable_t cv_gate;\n\n int count;\n int thread_done_count;\n int thread_ready_count;\n static void handler(void *argument);\n private:\n };\n\n#if !defined(LIBAMQP_DISABLE_FAST_MUTEX)\n TEST_FIXTURE(FastMutexFixture, validate_fast_mutex_internal_value)\n {\n CHECK_EQUAL(0, fast_mutex);\n amqp_fast_mutex_lock(&fast_mutex);\n CHECK_EQUAL(1, fast_mutex);\n amqp_fast_mutex_unlock(&fast_mutex);\n CHECK_EQUAL(0, fast_mutex);\n }\n#endif\n\n void FastMutexFixture::handler(void *argument)\n {\n FastMutexFixture *fixture = (FastMutexFixture *) argument;\n\n amqp_mutex_lock(&fixture->mutex);\n fixture->thread_ready_count++;\n amqp_condition_notify(&fixture->cv);\n amqp_condition_wait(&fixture->cv_gate, &fixture->mutex);\n amqp_mutex_unlock(&fixture->mutex);\n\n for (int i = 0; i < 10000; i++)\n {\n amqp_fast_mutex_lock(&fixture->fast_mutex);\n fixture->count++;\n amqp_fast_mutex_unlock(&fixture->fast_mutex);\n }\n\n amqp_mutex_lock(&fixture->mutex);\n fixture->thread_done_count++;\n amqp_condition_notify(&fixture->cv);\n amqp_mutex_unlock(&fixture->mutex);\n }\n\n TEST_FIXTURE(FastMutexFixture, exercise_thread_api_with_fast_mutex)\n {\n const int N_THREADS = 11;\n amqp_thread_t *threads[N_THREADS];\n\n for (int i = 0; i < N_THREADS; i++)\n {\n threads[i] = amqp_thread_start(FastMutexFixture::handler, this);\n }\n\n amqp_mutex_lock(&mutex);\n while (thread_ready_count < N_THREADS)\n {\n amqp_condition_wait(&cv, &mutex);\n }\n amqp_condition_broadcast(&cv_gate);\n\n while (thread_done_count < N_THREADS)\n {\n amqp_condition_wait(&cv, &mutex);\n }\n amqp_mutex_unlock(&mutex);\n\n CHECK_EQUAL(N_THREADS * 10000, count);\n\n for (int i = 0; i < N_THREADS; i++)\n {\n amqp_thread_destroy(threads[i]);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <iostream>\n#include <ctime>\n\n#include \"MUSI8903Config.h\"\n\n#include \"AudioFileIf.h\"\n#include \"IIRCombFilter.h\"\n#include \"FIRCombFilter.h\"\n#include \"TestBuffering.h\"\n#include \"TestFilter.h\"\n\nusing std::cout;\nusing std::endl;\n\n\/\/ local function declarations\nvoid showClInfo ();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ main function\nint main(int argc, char* argv[])\n{\n std::string _sInputFilePath, \/\/!< file paths\n _sOutputFilePath;\n\n long long _llBlockLength = 0; \/\/!< length of block\n \n float _fDelayLenInSec = 0.0f; \/\/!< delay Length in Seconds\n\n float _fGain = 0.0f;\n\n clock_t time = 0;\n\n float **ppfAudioData = 0;\n\n CAudioFileIf *phAudioFile = 0;\n \n std::ofstream outFile;\n\n Filter * _FilterProcess;\n \n showClInfo ();\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Testing\n \n \/\/ Test for Buffer class\n TestBuffering tTestBuf( 100 );\n std::cout<<\"Testing the Buffering Class. The result is shown below: 1 represents success, 0 represents failure. \"<<std::endl;\n std::cout<<\"Initialization: \"<<tTestBuf.isInit()<<std::endl;\n std::cout<<\"Writing : \"<<tTestBuf.isReadWrite()<< \"\\n\"<<std::endl;\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Test for Filter classes\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Filter Test: IIR naive test\n \n TestFilter testee1(1);\n testee1.zeroInputTest();\n testee1.unitImpulseTest();\n std::cout << \"The output of IIR Filter test has been written to a text file at ..\/bin\/debug\/ \" << std::endl;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Filter Test: FIR naive test\n \n TestFilter testee2(0);\n testee2.zeroInputTest();\n testee2.unitImpulseTest();\n std::cout << \"The output of FIR Filter test has been written to a text file at ..\/bin\/debug\/ \\n\" << std::endl;\n\n std::cout << \"Use audioFileTest() in TestFilter class for more evaluation results\\n\\n\"; \n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ parse command line arguments\n if (argc<6) {\n std::cerr << \"The arguments are not properly provided. Filter cannot be used.\" << std::endl;\n return -1;\n }\n else {\n _sInputFilePath = argv[1];\n _sOutputFilePath = _sInputFilePath + \".txt\";\n \n _llBlockLength = atoi(argv[2]);\n _fDelayLenInSec = (float) (atof(argv[3]));\n _fGain = (float) (atof(argv[4]));\n\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ open the input wave file\n CAudioFileIf::FileIoType_t fileType = CAudioFileIf::kFileRead;\n CAudioFileIf::create(phAudioFile);\n \n phAudioFile -> openFile(_sInputFilePath+\".wav\", fileType);\n \n CAudioFileIf::FileSpec_t fileSpec;\n phAudioFile -> getFileSpec(fileSpec);\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ allocate memory\n \n time = clock();\n\n if (atoi(argv[5]) == 0) {\n _FilterProcess = new class FIRCombFilter(_fDelayLenInSec, fileSpec.fSampleRateInHz, _fGain, fileSpec.iNumChannels);\n }\n else if(atoi(argv[5]) == 1) {\n _FilterProcess = new class IIRCombFilter(_fDelayLenInSec, fileSpec.fSampleRateInHz, _fGain, fileSpec.iNumChannels);\n }\n else {\n std::cout << \"Filter Type Selection Error. Please select 0 or 1\" << std::endl;\n return -1;\n }\n\n ppfAudioData = new float* [fileSpec.iNumChannels];\n for (int channel = 0; channel < fileSpec.iNumChannels; channel++) {\n ppfAudioData[channel] = new float [_llBlockLength];\n }\n outFile.open(_sOutputFilePath);\n \n \/\/ process the signal\n while (!phAudioFile->isEof()) {\n phAudioFile -> readData(ppfAudioData, _llBlockLength);\n for (int channel=0; channel<fileSpec.iNumChannels; channel++ ) {\n _FilterProcess -> filterProcess(ppfAudioData[channel], _llBlockLength, channel);\n }\n for ( int sample = 0; sample < _llBlockLength; sample++ ) {\n for ( int channel = 0; channel < fileSpec.iNumChannels; channel++ ) {\n outFile << ppfAudioData[channel][sample]<<\"\\t\";\n }\n outFile << \"\\n\";\n }\n }\n outFile.close();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ clean-up\n delete _FilterProcess;\n for (int channel = 0; channel < fileSpec.iNumChannels; channel++) {\n delete [] ppfAudioData[channel];\n }\n delete [] ppfAudioData;\n std::cout << \"Comb filter processing is done within \" << (clock() - time)*1.f \/ CLOCKS_PER_SEC << \" seconds.\" << std::endl;\n CAudioFileIf::destroy(phAudioFile);\n \n return 0;\n}\n\n\nvoid showClInfo()\n {\n cout << \"GTCMT MUSI8903\" << endl;\n cout << \"(c) 2016 by Liang Tang and Rithesh Kumar\" << endl;\n cout << endl;\n \n return;\n }\n\n<commit_msg>Consolidated Push(1)<commit_after>\n#include <iostream>\n#include <ctime>\n\n#include \"MUSI8903Config.h\"\n\n#include \"AudioFileIf.h\"\n#include \"IIRCombFilter.h\"\n#include \"FIRCombFilter.h\"\n#include \"TestBuffering.h\"\n#include \"TestFilter.h\"\n\nusing std::cout;\nusing std::endl;\n\n\/\/ local function declarations\nvoid showClInfo ();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ main function\nint main(int argc, char* argv[])\n{\n std::string _sInputFilePath, \/\/!< file paths\n _sOutputFilePath;\n\n long long _llBlockLength = 0; \/\/!< length of block\n \n float _fDelayLenInSec = 0.0f; \/\/!< delay Length in Seconds\n\n float _fGain = 0.0f;\n\n clock_t time = 0;\n\n float **ppfAudioData = 0;\n\n CAudioFileIf *phAudioFile = 0;\n \n std::ofstream outFile;\n\n Filter * _FilterProcess;\n \n showClInfo ();\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Testing\n \n \/\/ Test for Buffer class\n TestBuffering tTestBuf( 100 );\n std::cout<<\"Testing the Buffering Class. The result is shown below: 1 represents success, 0 represents failure. \"<<std::endl;\n std::cout<<\"Initialization: \"<<tTestBuf.isInit()<<std::endl;\n std::cout<<\"Writing : \"<<tTestBuf.isReadWrite()<< \"\\n\"<<std::endl;\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Test for Filter classes\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Filter Test: IIR naive test\n \n TestFilter testee1(1);\n testee1.zeroInputTest();\n testee1.unitImpulseTest();\n std::cout << \"The output of IIR Filter test has been written to a text file at ..\/bin\/debug\/ \" << std::endl;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Filter Test: FIR naive test\n \n TestFilter testee2(0);\n testee2.zeroInputTest();\n testee2.unitImpulseTest();\n std::cout << \"The output of FIR Filter test has been written to a text file at ..\/bin\/debug\/ \\n\" << std::endl;\n\n std::cout << \"Use audioFileTest() in TestFilter class for more evaluation results\\n\\n\"; \n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ parse command line arguments\n if (argc<6) {\n std::cerr << \"The arguments are not properly provided. Filter cannot be used.\" << std::endl;\n return -1;\n }\n else {\n _sInputFilePath = argv[1];\n _sOutputFilePath = _sInputFilePath + \".txt\";\n \n _llBlockLength = atoi(argv[2]);\n _fDelayLenInSec = (float) (atof(argv[3]));\n _fGain = (float) (atof(argv[4]));\n\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ open the input wave file\n CAudioFileIf::FileIoType_t fileType = CAudioFileIf::kFileRead;\n CAudioFileIf::create(phAudioFile);\n \n phAudioFile -> openFile(_sInputFilePath+\".wav\", fileType);\n \n CAudioFileIf::FileSpec_t fileSpec;\n phAudioFile -> getFileSpec(fileSpec);\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ allocate memory\n \n time = clock();\n\n if (atoi(argv[5]) == 0) {\n _FilterProcess = new class FIRCombFilter(_fDelayLenInSec, fileSpec.fSampleRateInHz, _fGain, fileSpec.iNumChannels);\n }\n else if(atoi(argv[5]) == 1) {\n _FilterProcess = new class IIRCombFilter(_fDelayLenInSec, fileSpec.fSampleRateInHz, _fGain, fileSpec.iNumChannels);\n }\n else {\n std::cout << \"Filter Type Selection Error. Please select 0 or 1\" << std::endl;\n return -1;\n }\n\n ppfAudioData = new float* [fileSpec.iNumChannels];\n for (int channel = 0; channel < fileSpec.iNumChannels; channel++) {\n ppfAudioData[channel] = new float [_llBlockLength];\n }\n outFile.open(_sOutputFilePath);\n \n \/\/ process the signal\n while (!phAudioFile->isEof()) {\n phAudioFile -> readData(ppfAudioData, _llBlockLength);\n for (int channel=0; channel<fileSpec.iNumChannels; channel++ ) {\n _FilterProcess -> filterProcess(ppfAudioData[channel], _llBlockLength, channel);\n }\n for ( int sample = 0; sample < _llBlockLength; sample++ ) {\n for ( int channel = 0; channel < fileSpec.iNumChannels; channel++ ) {\n outFile << ppfAudioData[channel][sample]<<\"\\t\";\n }\n outFile << \"\\n\";\n }\n }\n outFile.close();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ clean-up\n delete _FilterProcess;\n for (int channel = 0; channel < fileSpec.iNumChannels; channel++) {\n delete [] ppfAudioData[channel];\n }\n delete [] ppfAudioData;\n std::cout << \"Comb filter processing is done within \" << (clock() - time)*1.f \/ CLOCKS_PER_SEC << \" seconds.\" << std::endl;\n CAudioFileIf::destroy(phAudioFile);\n \n return 0;\n}\n\n\nvoid showClInfo()\n {\n cout << \"GTCMT MUSI8903\" << endl;\n cout << \"(c) 2016 by Liang Tang and Rithesh Kumar\" << endl;\n cout << endl;\n \n return;\n }\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#include \"Mesh.h\"\n#include \"Framework.h\"\n#include \"GraphicsWorld.h\"\n#include \"Placeable.h\"\n#include \"Scene\/Scene.h\"\n#include \"AttributeMetadata.h\"\n#include \"LoggingFunctions.h\"\n#include \"AssetRefListener.h\"\n#include \"IMeshAsset.h\"\n#include \"IMaterialAsset.h\"\n\n#include <Engine\/Scene\/Scene.h>\n#include <Engine\/Scene\/Node.h>\n#include <Engine\/Graphics\/AnimatedModel.h>\n#include <Engine\/Resource\/ResourceCache.h>\n\nnamespace Tundra\n{\n\nMesh::Mesh(Urho3D::Context* context, Scene* scene) :\n IComponent(context, scene),\n INIT_ATTRIBUTE_VALUE(nodeTransformation, \"Transform\", Transform(float3(0,0,0),float3(0,0,0),float3(1,1,1))),\n INIT_ATTRIBUTE_VALUE(meshRef, \"Mesh ref\", AssetReference(\"\", \"OgreMesh\")),\n INIT_ATTRIBUTE_VALUE(skeletonRef, \"Skeleton ref\", AssetReference(\"\", \"OgreSkeleton\")),\n INIT_ATTRIBUTE_VALUE(materialRefs, \"Material refs\", AssetReferenceList(\"OgreMaterial\")),\n INIT_ATTRIBUTE_VALUE(drawDistance, \"Draw distance\", 0.0f),\n INIT_ATTRIBUTE_VALUE(castShadows, \"Cast shadows\", false),\n INIT_ATTRIBUTE_VALUE(useInstancing, \"Use instancing\", false)\n{\n if (scene)\n world_ = scene->Subsystem<GraphicsWorld>();\n\n static AttributeMetadata drawDistanceData(\"\", \"0\", \"10000\");\n drawDistance.SetMetadata(&drawDistanceData);\n\n static AttributeMetadata materialMetadata;\n materialMetadata.elementType = \"AssetReference\";\n materialRefs.SetMetadata(&materialMetadata);\n\n ParentEntitySet.Connect(this, &Mesh::UpdateSignals);\n}\n\nMesh::~Mesh()\n{\n if (world_.Expired())\n {\n if (mesh_)\n LogError(\"Mesh: World has expired, skipping uninitialization!\");\n return;\n }\n\n if (mesh_)\n {\n MeshAboutToBeDestroyed.Emit();\n \n mesh_.Reset();\n \/\/ The mesh component will be destroyed along with the adjustment node\n adjustmentNode_->Remove();\n adjustmentNode_.Reset();\n }\n}\n\nUrho3D::Node* Mesh::BoneNode(const String& name) const\n{\n \/\/ When a skeletal mesh is created, the bone hierarchy will be under the adjustment node\n return adjustmentNode_ ? adjustmentNode_->GetChild(name, true) : nullptr;\n}\n\nvoid Mesh::DeserializeFrom(Urho3D::XMLElement& element, AttributeChange::Type change)\n{\n if (!BeginDeserialization(element))\n return;\n\n if (change == AttributeChange::Default)\n change = updateMode;\n assert(change != AttributeChange::Default);\n\n Urho3D::XMLElement attributeElement = element.GetChild(\"attribute\");\n while(attributeElement)\n {\n if (attributeElement.GetAttribute(\"id\").Empty() && attributeElement.GetAttribute(\"name\").Compare(\"Mesh materials\", false) == 0)\n attributeElement.SetAttribute(\"name\", \"Material refs\");\n DeserializeAttributeFrom(attributeElement, change);\n attributeElement = attributeElement.GetNext(\"attribute\");\n }\n}\n\nUrho3D::AnimatedModel* Mesh::UrhoMesh() const\n{\n return mesh_;\n}\n\nvoid Mesh::UpdateSignals()\n{\n Entity* parent = ParentEntity();\n if (!parent)\n return;\n\n \/\/ If scene is not view-enabled, no further action\n if (!ViewEnabled())\n return;\n\n meshRefListener_ = new AssetRefListener();\n materialRefListListener_ = new AssetRefListListener(framework->Asset());\n \n parent->ComponentAdded.Connect(this, &Mesh::OnComponentStructureChanged);\n parent->ComponentRemoved.Connect(this, &Mesh::OnComponentStructureChanged);\n\n if (parent->ParentScene())\n world_ = parent->ParentScene()->Subsystem<GraphicsWorld>();\n\n if (world_ && !mesh_)\n {\n Urho3D::Scene* urhoScene = world_->UrhoScene();\n adjustmentNode_ = urhoScene->CreateChild(\"AdjustmentNode\");\n \n \/\/ Make the entity & component links for identifying raycasts\n adjustmentNode_->SetVar(GraphicsWorld::entityLink, Variant(WeakPtr<RefCounted>(parent)));\n adjustmentNode_->SetVar(GraphicsWorld::componentLink, Variant(WeakPtr<RefCounted>(this)));\n\n mesh_ = adjustmentNode_->CreateComponent<Urho3D::AnimatedModel>();\n\n \/\/ Connect ref listeners\n meshRefListener_->Loaded.Connect(this, &Mesh::OnMeshAssetLoaded);\n materialRefListListener_->Changed.Connect(this, &Mesh::OnMaterialAssetRefsChanged);\n materialRefListListener_->Failed.Connect(this, &Mesh::OnMaterialAssetFailed);\n materialRefListListener_->Loaded.Connect(this, &Mesh::OnMaterialAssetLoaded);\n }\n\n \/\/ Make sure we attach to the Placeable if exists.\n AttachMesh();\n}\n\nvoid Mesh::DetachMesh()\n{\n if (!mesh_ || world_.Expired())\n return;\n\n if (placeable_)\n {\n Urho3D::Scene* urhoScene = world_->UrhoScene();\n \/\/ When removed from the placeable, attach to scene root to avoid being removed from scene\n adjustmentNode_->SetParent(urhoScene);\n placeable_.Reset();\n mesh_->SetEnabled(false); \/\/ We should not render while detached\n }\n}\n\nvoid Mesh::AttachMesh()\n{\n if (!mesh_ || world_.Expired())\n return;\n\n \/\/ Detach first, in case the original placeable no longer exists\n DetachMesh();\n\n Entity *entity = ParentEntity();\n if (!entity)\n return;\n placeable_ = entity->Component<Placeable>();\n if (!placeable_)\n return;\n\n Urho3D::Node* placeableNode = placeable_->UrhoSceneNode();\n if (!placeableNode)\n {\n LogError(\"Can not attach mesh: placeable does not have an Urho3D scene node\");\n return;\n }\n adjustmentNode_->SetParent(placeableNode);\n mesh_->SetEnabled(true);\n}\n\nvoid Mesh::OnComponentStructureChanged(IComponent*, AttributeChange::Type)\n{\n \/\/ No-op if attached to the same placeable already\n if (placeable_ == parentEntity->Component<Placeable>())\n return;\n\n AttachMesh();\n}\n\nvoid Mesh::AttributesChanged()\n{\n \/\/ None of the attributes have an effect when the scene is not viewenabled and there is no actual mesh\n if (!mesh_)\n return;\n\n if (drawDistance.ValueChanged())\n mesh_->SetDrawDistance(drawDistance.Get());\n if (castShadows.ValueChanged())\n mesh_->SetCastShadows(castShadows.Get());\n if (nodeTransformation.ValueChanged())\n {\n const Transform &newTransform = nodeTransformation.Get();\n adjustmentNode_->SetPosition(newTransform.pos);\n adjustmentNode_->SetRotation(newTransform.Orientation());\n adjustmentNode_->SetScale(newTransform.scale);\n }\n if (meshRef.ValueChanged() && meshRefListener_)\n {\n \/\/\/ @todo Why is this warning here? Pretty normal to clear mesh ref...\n if (meshRef.Get().ref.Trimmed().Empty())\n LogDebug(\"Warning: Mesh \\\"\" + this->parentEntity->Name() + \"\\\" mesh ref was set to an empty reference!\");\n meshRefListener_->HandleAssetRefChange(&meshRef);\n }\n if (materialRefs.ValueChanged() && materialRefListListener_)\n {\n \/* Let the listener resolve and cleanup the refs, while us keeping the originals intact.\n Changes are handled in OnMaterialAssetRefsChanged\/Failed\/Loaded. *\/\n materialRefListListener_->HandleChange(materialRefs.Get());\n }\n if (skeletonRef.ValueChanged())\n {\n \/\/\/ \\todo Implement\n }\n}\n\nvoid Mesh::OnMeshAssetLoaded(AssetPtr asset)\n{\n IMeshAsset* mAsset = dynamic_cast<IMeshAsset*>(asset.Get());\n if (!mAsset)\n {\n LogErrorF(\"Mesh: Mesh asset load finished for '%s', but downloaded asset was not of type IMeshAsset!\", asset->Name().CString());\n return;\n }\n\n if (mesh_)\n {\n mesh_->SetModel(mAsset->UrhoModel());\n\n \/\/ Apply all materials that have been loaded so far.\n \/\/ OnMaterialAssetLoaded will do the right thing once model has been set.\n Vector<AssetPtr> materialAssets = materialRefListListener_->Assets();\n for(uint mi=0; mi<materialAssets.Size(); ++mi)\n {\n AssetPtr &materialAssetPtr = materialAssets[mi];\n IMaterialAsset *materialAsset = dynamic_cast<IMaterialAsset*>(materialAssetPtr.Get());\n if (materialAsset && materialAsset->IsLoaded())\n {\n if (mi < mesh_->GetNumGeometries())\n mesh_->SetMaterial(mi, materialAsset->UrhoMaterial());\n else\n LogWarningF(\"Mesh: Illegal submesh index %d for material %s. Target mesh %s has %d submeshes.\", mi, materialAsset->Name().CString(), meshRef.Get().ref.CString(), mesh_->GetNumGeometries());\n }\n }\n }\n else\n LogWarningF(\"Mesh: Model asset loaded but target mesh has not been created yet in %s\", ParentEntity()->ToString().CString());\n}\n\nvoid Mesh::OnMaterialAssetRefsChanged(const AssetReferenceList &mRefs)\n{\n if (!mesh_ || !mesh_->GetModel())\n return;\n\n for (uint gi=0; gi<mesh_->GetNumGeometries(); ++gi)\n {\n \/** @todo Set empty material to these indexes!\n For Lasse to fill.\n\n if (gi >= mRefs.Size() || mRefs.refs[gi].ref.Empty())\n mesh_->SetMaterial(index, <default_empty_material> or nullptr?);\n *\/\n }\n}\n\nvoid Mesh::OnMaterialAssetFailed(uint index, IAssetTransfer* \/*transfer*\/, String \/*error*\/)\n{\n \/** @todo Set error material to these indexes!\n For Lasse to fill.\n\n if (mesh_ && mesh_->GetModel())\n mesh_->SetMaterial(index, <default_error_material>);\n *\/\n}\n\nvoid Mesh::OnMaterialAssetLoaded(uint index, AssetPtr asset)\n{\n IMaterialAsset* mAsset = dynamic_cast<IMaterialAsset*>(asset.Get());\n if (!mAsset)\n {\n LogErrorF(\"Mesh: Material asset load finished for '%s', but downloaded asset was not of type IMaterialAsset!\", asset->Name().CString());\n return;\n }\n\n if (mesh_ && mesh_->GetModel())\n {\n if (index < mesh_->GetNumGeometries())\n mesh_->SetMaterial(index, mAsset->UrhoMaterial());\n else\n LogWarningF(\"Mesh: Illegal submesh index %d for material %s. Target mesh %s has %d submeshes.\", index, mAsset->Name().CString(), meshRef.Get().ref.CString(), mesh_->GetNumGeometries());\n }\n}\n\n}\n<commit_msg>Mesh: Fix atm commented code.<commit_after>\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#include \"Mesh.h\"\n#include \"Framework.h\"\n#include \"GraphicsWorld.h\"\n#include \"Placeable.h\"\n#include \"Scene\/Scene.h\"\n#include \"AttributeMetadata.h\"\n#include \"LoggingFunctions.h\"\n#include \"AssetRefListener.h\"\n#include \"IMeshAsset.h\"\n#include \"IMaterialAsset.h\"\n\n#include <Engine\/Scene\/Scene.h>\n#include <Engine\/Scene\/Node.h>\n#include <Engine\/Graphics\/AnimatedModel.h>\n#include <Engine\/Resource\/ResourceCache.h>\n\nnamespace Tundra\n{\n\nMesh::Mesh(Urho3D::Context* context, Scene* scene) :\n IComponent(context, scene),\n INIT_ATTRIBUTE_VALUE(nodeTransformation, \"Transform\", Transform(float3(0,0,0),float3(0,0,0),float3(1,1,1))),\n INIT_ATTRIBUTE_VALUE(meshRef, \"Mesh ref\", AssetReference(\"\", \"OgreMesh\")),\n INIT_ATTRIBUTE_VALUE(skeletonRef, \"Skeleton ref\", AssetReference(\"\", \"OgreSkeleton\")),\n INIT_ATTRIBUTE_VALUE(materialRefs, \"Material refs\", AssetReferenceList(\"OgreMaterial\")),\n INIT_ATTRIBUTE_VALUE(drawDistance, \"Draw distance\", 0.0f),\n INIT_ATTRIBUTE_VALUE(castShadows, \"Cast shadows\", false),\n INIT_ATTRIBUTE_VALUE(useInstancing, \"Use instancing\", false)\n{\n if (scene)\n world_ = scene->Subsystem<GraphicsWorld>();\n\n static AttributeMetadata drawDistanceData(\"\", \"0\", \"10000\");\n drawDistance.SetMetadata(&drawDistanceData);\n\n static AttributeMetadata materialMetadata;\n materialMetadata.elementType = \"AssetReference\";\n materialRefs.SetMetadata(&materialMetadata);\n\n ParentEntitySet.Connect(this, &Mesh::UpdateSignals);\n}\n\nMesh::~Mesh()\n{\n if (world_.Expired())\n {\n if (mesh_)\n LogError(\"Mesh: World has expired, skipping uninitialization!\");\n return;\n }\n\n if (mesh_)\n {\n MeshAboutToBeDestroyed.Emit();\n \n mesh_.Reset();\n \/\/ The mesh component will be destroyed along with the adjustment node\n adjustmentNode_->Remove();\n adjustmentNode_.Reset();\n }\n}\n\nUrho3D::Node* Mesh::BoneNode(const String& name) const\n{\n \/\/ When a skeletal mesh is created, the bone hierarchy will be under the adjustment node\n return adjustmentNode_ ? adjustmentNode_->GetChild(name, true) : nullptr;\n}\n\nvoid Mesh::DeserializeFrom(Urho3D::XMLElement& element, AttributeChange::Type change)\n{\n if (!BeginDeserialization(element))\n return;\n\n if (change == AttributeChange::Default)\n change = updateMode;\n assert(change != AttributeChange::Default);\n\n Urho3D::XMLElement attributeElement = element.GetChild(\"attribute\");\n while(attributeElement)\n {\n if (attributeElement.GetAttribute(\"id\").Empty() && attributeElement.GetAttribute(\"name\").Compare(\"Mesh materials\", false) == 0)\n attributeElement.SetAttribute(\"name\", \"Material refs\");\n DeserializeAttributeFrom(attributeElement, change);\n attributeElement = attributeElement.GetNext(\"attribute\");\n }\n}\n\nUrho3D::AnimatedModel* Mesh::UrhoMesh() const\n{\n return mesh_;\n}\n\nvoid Mesh::UpdateSignals()\n{\n Entity* parent = ParentEntity();\n if (!parent)\n return;\n\n \/\/ If scene is not view-enabled, no further action\n if (!ViewEnabled())\n return;\n\n meshRefListener_ = new AssetRefListener();\n materialRefListListener_ = new AssetRefListListener(framework->Asset());\n \n parent->ComponentAdded.Connect(this, &Mesh::OnComponentStructureChanged);\n parent->ComponentRemoved.Connect(this, &Mesh::OnComponentStructureChanged);\n\n if (parent->ParentScene())\n world_ = parent->ParentScene()->Subsystem<GraphicsWorld>();\n\n if (world_ && !mesh_)\n {\n Urho3D::Scene* urhoScene = world_->UrhoScene();\n adjustmentNode_ = urhoScene->CreateChild(\"AdjustmentNode\");\n \n \/\/ Make the entity & component links for identifying raycasts\n adjustmentNode_->SetVar(GraphicsWorld::entityLink, Variant(WeakPtr<RefCounted>(parent)));\n adjustmentNode_->SetVar(GraphicsWorld::componentLink, Variant(WeakPtr<RefCounted>(this)));\n\n mesh_ = adjustmentNode_->CreateComponent<Urho3D::AnimatedModel>();\n\n \/\/ Connect ref listeners\n meshRefListener_->Loaded.Connect(this, &Mesh::OnMeshAssetLoaded);\n materialRefListListener_->Changed.Connect(this, &Mesh::OnMaterialAssetRefsChanged);\n materialRefListListener_->Failed.Connect(this, &Mesh::OnMaterialAssetFailed);\n materialRefListListener_->Loaded.Connect(this, &Mesh::OnMaterialAssetLoaded);\n }\n\n \/\/ Make sure we attach to the Placeable if exists.\n AttachMesh();\n}\n\nvoid Mesh::DetachMesh()\n{\n if (!mesh_ || world_.Expired())\n return;\n\n if (placeable_)\n {\n Urho3D::Scene* urhoScene = world_->UrhoScene();\n \/\/ When removed from the placeable, attach to scene root to avoid being removed from scene\n adjustmentNode_->SetParent(urhoScene);\n placeable_.Reset();\n mesh_->SetEnabled(false); \/\/ We should not render while detached\n }\n}\n\nvoid Mesh::AttachMesh()\n{\n if (!mesh_ || world_.Expired())\n return;\n\n \/\/ Detach first, in case the original placeable no longer exists\n DetachMesh();\n\n Entity *entity = ParentEntity();\n if (!entity)\n return;\n placeable_ = entity->Component<Placeable>();\n if (!placeable_)\n return;\n\n Urho3D::Node* placeableNode = placeable_->UrhoSceneNode();\n if (!placeableNode)\n {\n LogError(\"Can not attach mesh: placeable does not have an Urho3D scene node\");\n return;\n }\n adjustmentNode_->SetParent(placeableNode);\n mesh_->SetEnabled(true);\n}\n\nvoid Mesh::OnComponentStructureChanged(IComponent*, AttributeChange::Type)\n{\n \/\/ No-op if attached to the same placeable already\n if (placeable_ == parentEntity->Component<Placeable>())\n return;\n\n AttachMesh();\n}\n\nvoid Mesh::AttributesChanged()\n{\n \/\/ None of the attributes have an effect when the scene is not viewenabled and there is no actual mesh\n if (!mesh_)\n return;\n\n if (drawDistance.ValueChanged())\n mesh_->SetDrawDistance(drawDistance.Get());\n if (castShadows.ValueChanged())\n mesh_->SetCastShadows(castShadows.Get());\n if (nodeTransformation.ValueChanged())\n {\n const Transform &newTransform = nodeTransformation.Get();\n adjustmentNode_->SetPosition(newTransform.pos);\n adjustmentNode_->SetRotation(newTransform.Orientation());\n adjustmentNode_->SetScale(newTransform.scale);\n }\n if (meshRef.ValueChanged() && meshRefListener_)\n {\n \/\/\/ @todo Why is this warning here? Pretty normal to clear mesh ref...\n if (meshRef.Get().ref.Trimmed().Empty())\n LogDebug(\"Warning: Mesh \\\"\" + this->parentEntity->Name() + \"\\\" mesh ref was set to an empty reference!\");\n meshRefListener_->HandleAssetRefChange(&meshRef);\n }\n if (materialRefs.ValueChanged() && materialRefListListener_)\n {\n \/* Let the listener resolve and cleanup the refs, while us keeping the originals intact.\n Changes are handled in OnMaterialAssetRefsChanged\/Failed\/Loaded. *\/\n materialRefListListener_->HandleChange(materialRefs.Get());\n }\n if (skeletonRef.ValueChanged())\n {\n \/\/\/ \\todo Implement\n }\n}\n\nvoid Mesh::OnMeshAssetLoaded(AssetPtr asset)\n{\n IMeshAsset* mAsset = dynamic_cast<IMeshAsset*>(asset.Get());\n if (!mAsset)\n {\n LogErrorF(\"Mesh: Mesh asset load finished for '%s', but downloaded asset was not of type IMeshAsset!\", asset->Name().CString());\n return;\n }\n\n if (mesh_)\n {\n mesh_->SetModel(mAsset->UrhoModel());\n\n \/\/ Apply all materials that have been loaded so far.\n \/\/ OnMaterialAssetLoaded will do the right thing once model has been set.\n Vector<AssetPtr> materialAssets = materialRefListListener_->Assets();\n for(uint mi=0; mi<materialAssets.Size(); ++mi)\n {\n AssetPtr &materialAssetPtr = materialAssets[mi];\n IMaterialAsset *materialAsset = dynamic_cast<IMaterialAsset*>(materialAssetPtr.Get());\n if (materialAsset && materialAsset->IsLoaded())\n {\n if (mi < mesh_->GetNumGeometries())\n mesh_->SetMaterial(mi, materialAsset->UrhoMaterial());\n else\n LogWarningF(\"Mesh: Illegal submesh index %d for material %s. Target mesh %s has %d submeshes.\", mi, materialAsset->Name().CString(), meshRef.Get().ref.CString(), mesh_->GetNumGeometries());\n }\n }\n }\n else\n LogWarningF(\"Mesh: Model asset loaded but target mesh has not been created yet in %s\", ParentEntity()->ToString().CString());\n}\n\nvoid Mesh::OnMaterialAssetRefsChanged(const AssetReferenceList &mRefs)\n{\n if (!mesh_ || !mesh_->GetModel())\n return;\n\n for (uint gi=0; gi<mesh_->GetNumGeometries(); ++gi)\n {\n \/** @todo Set empty material to these indexes!\n For Lasse to fill.\n\n if (gi >= mRefs.Size() || mRefs.refs[gi].ref.Empty())\n mesh_->SetMaterial(gi, <default_empty_material> or nullptr?);\n *\/\n }\n}\n\nvoid Mesh::OnMaterialAssetFailed(uint index, IAssetTransfer* \/*transfer*\/, String \/*error*\/)\n{\n \/** @todo Set error material to these indexes!\n For Lasse to fill.\n\n \/\/ Don't log an warning on load failure if index is out of submesh range.\n if (mesh_ && mesh_->GetModel() && index < mesh_->GetNumGeometries())\n mesh_->SetMaterial(index, <default_error_material>);\n *\/\n}\n\nvoid Mesh::OnMaterialAssetLoaded(uint index, AssetPtr asset)\n{\n IMaterialAsset* mAsset = dynamic_cast<IMaterialAsset*>(asset.Get());\n if (!mAsset)\n {\n LogErrorF(\"Mesh: Material asset load finished for '%s', but downloaded asset was not of type IMaterialAsset!\", asset->Name().CString());\n return;\n }\n\n if (mesh_ && mesh_->GetModel())\n {\n if (index < mesh_->GetNumGeometries())\n mesh_->SetMaterial(index, mAsset->UrhoMaterial());\n else\n LogWarningF(\"Mesh: Illegal submesh index %d for material %s. Target mesh %s has %d submeshes.\", index, mAsset->Name().CString(), meshRef.Get().ref.CString(), mesh_->GetNumGeometries());\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * advanced_dialog.cpp\r\n * PHD Guiding\r\n *\r\n * Created by Craig Stark.\r\n * Copyright (c) 2006-2010 Craig Stark.\r\n * All rights reserved.\r\n *\r\n * This source code is distributed under the following \"BSD\" license\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * Neither the name of Craig Stark, Stark Labs nor the names of its\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n\r\n#include \"phd.h\"\r\nAdvancedDialog::AdvancedDialog():\r\n\/\/#if defined (__WINDOWS__)\r\n\/\/wxDialog(pFrame, wxID_ANY, _(\"Advanced setup\"), wxPoint(-1,-1), wxSize(210,350), wxCAPTION | wxCLOSE_BOX)\r\n\/\/#else\r\n\/\/wxDialog(pFrame, wxID_ANY, _(\"Advanced setup\"), wxPoint(-1,-1), wxSize(250,350), wxCAPTION | wxCLOSE_BOX)\r\n\/\/#endif\r\nwxDialog(pFrame, wxID_ANY, _(\"Advanced setup\"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)\r\n{\r\n \/*\r\n * the advanced dialog is made up of a number of \"on the fly\" generated slices that configure different things.\r\n *\r\n * pTopLevelSizer is a top level Box Sizer in wxVERTICAL mode that contains a pair of sizers,\r\n * pConfigSizer to hold all the configuration panes and an unamed Button sizer and the OK and CANCEL buttons.\r\n *\r\n * pConfigSizer is a Horizontal Box Sizer which contains two Vertical Box sizers, one\r\n * for each column of panes\r\n *\r\n * +------------------------------------+------------------------------------+\r\n * | General (Frame) Settings | Guider Base Class Settings |\r\n * +------------------------------------| |\r\n * | Mount Base Class Settings | Ra Guide Algorithm Settings |\r\n * | | |\r\n * | Mount Sub Class Settings | Dec Guide Alogrithm Settings |\r\n * +------------------------------------| |\r\n * | Camera Base Class Settings | Guider Sub Class Settings |\r\n * | |------------------------------------+\r\n * | Camera Sub Calss Settings | |\r\n * +------------------------------------| |\r\n * | Camera Base Class Settings | |\r\n * +-------------------------------------------------------------------------|\r\n * | OK and Cancel Buttons |\r\n * +-------------------------------------------------------------------------+\r\n *\r\n *\/\r\n\r\n wxNotebook *pNotebook = new wxNotebook(this, wxID_ANY);\r\n\r\n wxSizerFlags sizer_flags = wxSizerFlags(0).Center().Border(wxALL,2).Expand();\r\n\r\n \/\/ build all the empty sizer\r\n wxBoxSizer *pGlobalTabSizer = new wxBoxSizer(wxVERTICAL);\r\n wxBoxSizer *pGuidingTabSizer = new wxBoxSizer(wxVERTICAL);\r\n\r\n \/\/ build tabs\r\n wxPanel *globalSettingsPanel = new wxPanel(pNotebook);\r\n wxPanel *guiderSettingsPanel = new wxPanel(pNotebook);\r\n globalSettingsPanel->SetSizer(pGlobalTabSizer);\r\n guiderSettingsPanel->SetSizer(pGuidingTabSizer);\r\n pNotebook->AddPage(globalSettingsPanel, _(\"Global\"), true);\r\n pNotebook->AddPage(guiderSettingsPanel, _(\"Guiding\"));\r\n\r\n \/\/ Build the global tab pane\r\n m_pFramePane = pFrame->GetConfigDialogPane(globalSettingsPanel);\r\n pGlobalTabSizer->Add(m_pFramePane, sizer_flags);\r\n\r\n m_pGuiderPane = pFrame->pGuider->GetConfigDialogPane(globalSettingsPanel);\r\n pGlobalTabSizer->Add(m_pGuiderPane, sizer_flags);\r\n\r\n if (pCamera)\r\n {\r\n m_pCameraPane = pCamera->GetConfigDialogPane(globalSettingsPanel);\r\n if (m_pCameraPane != NULL)\r\n pGlobalTabSizer->Add(m_pCameraPane, sizer_flags);\r\n }\r\n else\r\n {\r\n m_pCameraPane=NULL;\r\n wxStaticBoxSizer *pBox = new wxStaticBoxSizer(new wxStaticBox(globalSettingsPanel, wxID_ANY, _(\"Camera Settings\")), wxVERTICAL);\r\n wxStaticText *pText = new wxStaticText(globalSettingsPanel, wxID_ANY, _(\"No Camera Connected\"),wxPoint(-1,-1),wxSize(-1,-1));\r\n pBox->Add(pText);\r\n pGlobalTabSizer->Add(pBox, sizer_flags);\r\n }\r\n\r\n \/\/ Build guiding tab\r\n\r\n if (pSecondaryMount)\r\n {\r\n \/\/ if there are two mounts, the mount config goes to the Adaptive Optics tab\r\n wxPanel *aoSettingsPanel = new wxPanel(pNotebook);\r\n wxBoxSizer *pAoSizer = new wxBoxSizer(wxVERTICAL);\r\n m_pMountPane = pMount->GetConfigDialogPane(aoSettingsPanel);\r\n pAoSizer->Add(m_pMountPane, sizer_flags);\r\n aoSettingsPanel->SetSizer(pAoSizer);\r\n pNotebook->AddPage(aoSettingsPanel, _(\"Adaptive Optics\"));\r\n\r\n \/\/ the secondary goes to the global tab pane\r\n m_pSecondaryMountPane = pSecondaryMount->GetConfigDialogPane(guiderSettingsPanel);\r\n pGuidingTabSizer->Add(m_pSecondaryMountPane, sizer_flags);\r\n }\r\n else\r\n {\r\n \/\/ otherwise there is no secondary mount, so we put up an empty AO box\r\n m_pSecondaryMountPane = NULL;\r\n \/\/wxStaticBoxSizer *pBox = new wxStaticBoxSizer(new wxStaticBox(globalSettingsPanel, wxID_ANY, _(\"AO Settings\")), wxVERTICAL);\r\n \/\/wxStaticText *pText = new wxStaticText(globalSettingsPanel, wxID_ANY, _(\"No AO Connected\"),wxPoint(-1,-1),wxSize(-1,-1));\r\n \/\/pBox->Add(pText);\r\n \/\/pGlobalTabSizer->Add(pBox, sizer_flags);\r\n\r\n \/\/ and the mount goes on the right\r\n m_pMountPane = pMount->GetConfigDialogPane(guiderSettingsPanel);\r\n pGuidingTabSizer->Add(m_pMountPane, sizer_flags);\r\n\r\n }\r\n\r\n wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);\r\n pTopLevelSizer->Add(pNotebook, wxSizerFlags(0).Expand().Border(wxALL, 5));\r\n pTopLevelSizer->Add(CreateButtonSizer(wxOK | wxCANCEL), wxSizerFlags(0).Expand().Border(wxALL, 5));\r\n SetSizerAndFit(pTopLevelSizer);\r\n}\r\n\r\n\r\nvoid AdvancedDialog::LoadValues(void)\r\n{\r\n m_pFramePane->LoadValues();\r\n m_pMountPane->LoadValues();\r\n if (m_pSecondaryMountPane)\r\n {\r\n m_pSecondaryMountPane->LoadValues();\r\n }\r\n m_pGuiderPane->LoadValues();\r\n\r\n if (m_pCameraPane != NULL)\r\n {\r\n m_pCameraPane->LoadValues();\r\n }\r\n}\r\n\r\nvoid AdvancedDialog::UnloadValues(void)\r\n{\r\n m_pFramePane->UnloadValues();\r\n m_pMountPane->UnloadValues();\r\n if (m_pSecondaryMountPane)\r\n {\r\n m_pSecondaryMountPane->UnloadValues();\r\n }\r\n m_pGuiderPane->UnloadValues();\r\n\r\n if (m_pCameraPane != NULL)\r\n {\r\n m_pCameraPane->UnloadValues();\r\n }\r\n}\r\n\r\nBEGIN_EVENT_TABLE(AdvancedDialog, wxDialog)\r\n EVT_BUTTON(wxID_PROPERTIES,AdvancedDialog::OnSetupCamera)\r\nEND_EVENT_TABLE()\r\n\r\nvoid AdvancedDialog::OnSetupCamera(wxCommandEvent& WXUNUSED(event)) {\r\n \/\/ Prior to this we check to make sure the current camera is a WDM camera (main dialog) but...\r\n\r\n if (pFrame->CaptureActive || !pCamera || !pCamera->Connected || !pCamera->HasPropertyDialog) return; \/\/ One more safety check\r\n \/*if (pCamera == &Camera_WDM)\r\n Camera_WDM.ShowPropertyDialog();\r\n else if (pCamera == &Camera_VFW)\r\n Camera_VFW.ShowPropertyDialog();*\/\r\n pCamera->ShowPropertyDialog();\r\n}\r\n\r\n<commit_msg>Adding additional tabs to the advanced config box<commit_after>\/*\r\n * advanced_dialog.cpp\r\n * PHD Guiding\r\n *\r\n * Created by Craig Stark.\r\n * Copyright (c) 2006-2010 Craig Stark.\r\n * All rights reserved.\r\n *\r\n * This source code is distributed under the following \"BSD\" license\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * Neither the name of Craig Stark, Stark Labs nor the names of its\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n\r\n#include \"phd.h\"\r\nAdvancedDialog::AdvancedDialog():\r\n\/\/#if defined (__WINDOWS__)\r\n\/\/wxDialog(pFrame, wxID_ANY, _(\"Advanced setup\"), wxPoint(-1,-1), wxSize(210,350), wxCAPTION | wxCLOSE_BOX)\r\n\/\/#else\r\n\/\/wxDialog(pFrame, wxID_ANY, _(\"Advanced setup\"), wxPoint(-1,-1), wxSize(250,350), wxCAPTION | wxCLOSE_BOX)\r\n\/\/#endif\r\nwxDialog(pFrame, wxID_ANY, _(\"Advanced setup\"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)\r\n{\r\n \/*\r\n * the advanced dialog is made up of a number of \"on the fly\" generated slices that configure different things.\r\n *\r\n * pTopLevelSizer is a top level Box Sizer in wxVERTICAL mode that contains a pair of sizers,\r\n * pConfigSizer to hold all the configuration panes and an unamed Button sizer and the OK and CANCEL buttons.\r\n *\r\n * pConfigSizer is a Horizontal Box Sizer which contains two Vertical Box sizers, one\r\n * for each column of panes\r\n *\r\n * +------------------------------------+------------------------------------+\r\n * | General (Frame) Settings | Guider Base Class Settings |\r\n * +------------------------------------| |\r\n * | Mount Base Class Settings | Ra Guide Algorithm Settings |\r\n * | | |\r\n * | Mount Sub Class Settings | Dec Guide Alogrithm Settings |\r\n * +------------------------------------| |\r\n * | Camera Base Class Settings | Guider Sub Class Settings |\r\n * | |------------------------------------+\r\n * | Camera Sub Calss Settings | |\r\n * +------------------------------------| |\r\n * | Camera Base Class Settings | |\r\n * +-------------------------------------------------------------------------|\r\n * | OK and Cancel Buttons |\r\n * +-------------------------------------------------------------------------+\r\n *\r\n *\/\r\n\r\n wxNotebook *pNotebook = new wxNotebook(this, wxID_ANY);\r\n\r\n wxSizerFlags sizer_flags = wxSizerFlags(0).Align(wxALIGN_TOP|wxALIGN_CENTER_HORIZONTAL).Border(wxALL,2).Expand();\r\n\r\n \/\/ build tabs -- each needs the tab, and a sizer. Once built\r\n \/\/ it needs to be populated\r\n\r\n \/\/ Build the global tab pane\r\n wxPanel *pGlobalSettingsPanel = new wxPanel(pNotebook);\r\n wxBoxSizer *pGlobalTabSizer = new wxBoxSizer(wxVERTICAL);\r\n pGlobalSettingsPanel->SetSizer(pGlobalTabSizer);\r\n pNotebook->AddPage(pGlobalSettingsPanel, _(\"Global\"), true);\r\n\r\n \/\/ and populate it\r\n m_pFramePane = pFrame->GetConfigDialogPane(pGlobalSettingsPanel);\r\n pGlobalTabSizer->Add(m_pFramePane, sizer_flags);\r\n\r\n \/\/ Build the guider tab\r\n wxPanel *pGuiderSettingsPanel = new wxPanel(pNotebook);\r\n wxBoxSizer *pGuidingTabSizer = new wxBoxSizer(wxVERTICAL);\r\n pGuiderSettingsPanel->SetSizer(pGuidingTabSizer);\r\n pNotebook->AddPage(pGuiderSettingsPanel, _(\"Guiding\"));\r\n\r\n \/\/ and populate it\r\n m_pGuiderPane = pFrame->pGuider->GetConfigDialogPane(pGuiderSettingsPanel);\r\n pGuidingTabSizer->Add(m_pGuiderPane, sizer_flags);\r\n\r\n \/\/ Build the camera tab\r\n wxPanel *pCameraSettingsPanel = new wxPanel(pNotebook);\r\n wxBoxSizer *pCameraTabSizer = new wxBoxSizer(wxVERTICAL);\r\n pCameraSettingsPanel->SetSizer(pCameraTabSizer);\r\n pNotebook->AddPage(pCameraSettingsPanel, _(\"Camera\"));\r\n\r\n \/\/ and populate it\r\n if (pCamera)\r\n {\r\n m_pCameraPane = pCamera->GetConfigDialogPane(pCameraSettingsPanel);\r\n if (m_pCameraPane)\r\n {\r\n pCameraTabSizer->Add(m_pCameraPane, sizer_flags);\r\n }\r\n }\r\n else\r\n {\r\n m_pCameraPane=NULL;\r\n wxStaticBoxSizer *pBox = new wxStaticBoxSizer(new wxStaticBox(pCameraSettingsPanel, wxID_ANY, _(\"Camera Settings\")), wxVERTICAL);\r\n wxStaticText *pText = new wxStaticText(pCameraSettingsPanel, wxID_ANY, _(\"No Camera Connected\"),wxPoint(-1,-1),wxSize(-1,-1));\r\n pBox->Add(pText);\r\n pCameraTabSizer->Add(pBox, sizer_flags);\r\n }\r\n\r\n \/\/ Build scope tab\r\n wxPanel *pScopeSettingsPanel = new wxPanel(pNotebook);\r\n wxBoxSizer *pScopeTabSizer = new wxBoxSizer(wxVERTICAL);\r\n pScopeSettingsPanel->SetSizer(pScopeTabSizer);\r\n pNotebook->AddPage(pScopeSettingsPanel, _(\"Scope\"));\r\n\r\n \/\/ and populate it\r\n if (pSecondaryMount)\r\n {\r\n \/\/ if there are two mounts, the secondary mount config goes to the\r\n \/\/ scope tab\r\n m_pMountPane = pMount->GetConfigDialogPane(pScopeSettingsPanel);\r\n pScopeTabSizer->Add(m_pMountPane, sizer_flags);\r\n }\r\n else\r\n {\r\n \/\/ the primary mount goes to the scope tab\r\n m_pMountPane = pMount->GetConfigDialogPane(pScopeSettingsPanel);\r\n pScopeTabSizer->Add(m_pMountPane, sizer_flags);\r\n }\r\n\r\n \/\/ Build AO tab\r\n wxPanel *pAoSettingsPanel = new wxPanel(pNotebook);\r\n wxBoxSizer *pAoTabSizer = new wxBoxSizer(wxVERTICAL);\r\n pAoSettingsPanel->SetSizer(pAoTabSizer);\r\n pNotebook->AddPage(pAoSettingsPanel, _(\"AO\"));\r\n\r\n \/\/ and populate it\r\n if (pSecondaryMount)\r\n {\r\n \/\/ if there are two mounts, the primary mount config goes to the Adaptive Optics tab\r\n m_pMountPane = pMount->GetConfigDialogPane(pAoSettingsPanel);\r\n pAoTabSizer->Add(m_pMountPane, sizer_flags);\r\n }\r\n else\r\n {\r\n \/\/ otherwise there is no secondary mount, so there is no AO.\r\n \/\/ construct a text box informing the user of that fact\r\n\r\n m_pSecondaryMountPane = NULL;\r\n\r\n wxStaticBoxSizer *pBox = new wxStaticBoxSizer(new wxStaticBox(pAoSettingsPanel, wxID_ANY, _(\"AO Settings\")), wxVERTICAL);\r\n wxStaticText *pText = new wxStaticText(pAoSettingsPanel, wxID_ANY, _(\"No AO Connected\"),wxPoint(-1,-1),wxSize(-1,-1));\r\n pBox->Add(pText);\r\n pAoTabSizer->Add(pBox, sizer_flags);\r\n }\r\n\r\n wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);\r\n pTopLevelSizer->Add(pNotebook, wxSizerFlags(0).Expand().Border(wxALL, 5));\r\n pTopLevelSizer->Add(CreateButtonSizer(wxOK | wxCANCEL), wxSizerFlags(0).Expand().Border(wxALL, 5));\r\n SetSizerAndFit(pTopLevelSizer);\r\n}\r\n\r\n\r\nvoid AdvancedDialog::LoadValues(void)\r\n{\r\n m_pFramePane->LoadValues();\r\n m_pMountPane->LoadValues();\r\n\r\n if (m_pSecondaryMountPane)\r\n {\r\n m_pSecondaryMountPane->LoadValues();\r\n }\r\n\r\n m_pGuiderPane->LoadValues();\r\n\r\n if (m_pCameraPane != NULL)\r\n {\r\n m_pCameraPane->LoadValues();\r\n }\r\n}\r\n\r\nvoid AdvancedDialog::UnloadValues(void)\r\n{\r\n m_pFramePane->UnloadValues();\r\n m_pMountPane->UnloadValues();\r\n if (m_pSecondaryMountPane)\r\n {\r\n m_pSecondaryMountPane->UnloadValues();\r\n }\r\n m_pGuiderPane->UnloadValues();\r\n\r\n if (m_pCameraPane != NULL)\r\n {\r\n m_pCameraPane->UnloadValues();\r\n }\r\n}\r\n\r\nBEGIN_EVENT_TABLE(AdvancedDialog, wxDialog)\r\n EVT_BUTTON(wxID_PROPERTIES,AdvancedDialog::OnSetupCamera)\r\nEND_EVENT_TABLE()\r\n\r\nvoid AdvancedDialog::OnSetupCamera(wxCommandEvent& WXUNUSED(event)) {\r\n \/\/ Prior to this we check to make sure the current camera is a WDM camera (main dialog) but...\r\n\r\n if (pFrame->CaptureActive || !pCamera || !pCamera->Connected || !pCamera->HasPropertyDialog) return; \/\/ One more safety check\r\n \/*if (pCamera == &Camera_WDM)\r\n Camera_WDM.ShowPropertyDialog();\r\n else if (pCamera == &Camera_VFW)\r\n Camera_VFW.ShowPropertyDialog();*\/\r\n pCamera->ShowPropertyDialog();\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ http:\/\/code.google.com\/p\/protobuf\/\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:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. 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\/\/ Author: kenton@google.com (Kenton Varda)\n\/\/ Based on original Protocol Buffers design by\n\/\/ Sanjay Ghemawat, Jeff Dean, and others.\n\n\/\/ Copyright (c) 2008-2013, Dave Benson. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\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\/\/ Modified to implement C code by Dave Benson.\n\n#include <set>\n#include <map>\n\n#include <protoc-c\/c_enum.h>\n#include <protoc-c\/c_helpers.h>\n#include <google\/protobuf\/io\/printer.h>\n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace c {\n\nEnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,\n const string& dllexport_decl)\n : descriptor_(descriptor),\n dllexport_decl_(dllexport_decl) {\n}\n\nEnumGenerator::~EnumGenerator() {}\n\nvoid EnumGenerator::GenerateDefinition(io::Printer* printer) {\n map<string, string> vars;\n vars[\"classname\"] = FullNameToC(descriptor_->full_name());\n vars[\"shortname\"] = descriptor_->name();\n vars[\"uc_name\"] = FullNameToUpper(descriptor_->full_name());\n\n SourceLocation sourceLoc;\n descriptor_->GetSourceLocation(&sourceLoc);\n PrintComment (printer, sourceLoc.leading_comments);\n\n printer->Print(vars, \"typedef enum _$classname$ {\\n\");\n printer->Indent();\n\n const EnumValueDescriptor* min_value = descriptor_->value(0);\n const EnumValueDescriptor* max_value = descriptor_->value(0);\n\n\n vars[\"opt_comma\"] = \",\";\n vars[\"prefix\"] = FullNameToUpper(descriptor_->full_name()) + \"__\";\n for (int i = 0; i < descriptor_->value_count(); i++) {\n vars[\"name\"] = descriptor_->value(i)->name();\n vars[\"number\"] = SimpleItoa(descriptor_->value(i)->number());\n if (i + 1 == descriptor_->value_count())\n vars[\"opt_comma\"] = \"\";\n\n SourceLocation valSourceLoc;\n descriptor_->value(i)->GetSourceLocation(&valSourceLoc);\n\n PrintComment (printer, valSourceLoc.leading_comments);\n PrintComment (printer, valSourceLoc.trailing_comments);\n printer->Print(vars, \"$prefix$$name$ = $number$$opt_comma$\\n\");\n\n if (descriptor_->value(i)->number() < min_value->number()) {\n min_value = descriptor_->value(i);\n }\n if (descriptor_->value(i)->number() > max_value->number()) {\n max_value = descriptor_->value(i);\n }\n }\n\n printer->Print(vars, \" PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE($uc_name$)\\n\");\n printer->Outdent();\n printer->Print(vars, \"} $classname$;\\n\");\n}\n\nvoid EnumGenerator::GenerateDescriptorDeclarations(io::Printer* printer) {\n map<string, string> vars;\n if (dllexport_decl_.empty()) {\n vars[\"dllexport\"] = \"\";\n } else {\n vars[\"dllexport\"] = dllexport_decl_ + \" \";\n }\n vars[\"classname\"] = FullNameToC(descriptor_->full_name());\n vars[\"lcclassname\"] = FullNameToLower(descriptor_->full_name());\n\n printer->Print(vars,\n \"extern $dllexport$const ProtobufCEnumDescriptor $lcclassname$__descriptor;\\n\");\n}\n\nstruct ValueIndex\n{\n int value;\n unsigned index;\n unsigned final_index;\t\t\/* index in uniqified array of values *\/\n const char *name;\n};\nvoid EnumGenerator::GenerateValueInitializer(io::Printer *printer, int index)\n{\n const EnumValueDescriptor *vd = descriptor_->value(index);\n map<string, string> vars;\n vars[\"enum_value_name\"] = vd->name();\n vars[\"c_enum_value_name\"] = FullNameToUpper(descriptor_->full_name()) + \"__\" + vd->name();\n vars[\"value\"] = SimpleItoa(vd->number());\n printer->Print(vars,\n \" { \\\"$enum_value_name$\\\", \\\"$c_enum_value_name$\\\", $value$ },\\n\");\n}\n\nstatic int compare_value_indices_by_value_then_index(const void *a, const void *b)\n{\n const ValueIndex *vi_a = (const ValueIndex *) a;\n const ValueIndex *vi_b = (const ValueIndex *) b;\n if (vi_a->value < vi_b->value) return -1;\n if (vi_a->value > vi_b->value) return +1;\n if (vi_a->index < vi_b->index) return -1;\n if (vi_a->index > vi_b->index) return +1;\n return 0;\n}\n\nstatic int compare_value_indices_by_name(const void *a, const void *b)\n{\n const ValueIndex *vi_a = (const ValueIndex *) a;\n const ValueIndex *vi_b = (const ValueIndex *) b;\n return strcmp (vi_a->name, vi_b->name);\n}\n\nvoid EnumGenerator::GenerateEnumDescriptor(io::Printer* printer) {\n map<string, string> vars;\n vars[\"fullname\"] = descriptor_->full_name();\n vars[\"lcclassname\"] = FullNameToLower(descriptor_->full_name());\n vars[\"cname\"] = FullNameToC(descriptor_->full_name());\n vars[\"shortname\"] = descriptor_->name();\n vars[\"packagename\"] = descriptor_->file()->package();\n vars[\"value_count\"] = SimpleItoa(descriptor_->value_count());\n\n \/\/ Sort by name and value, dropping duplicate values if they appear later.\n \/\/ TODO: use a c++ paradigm for this!\n NameIndex *name_index = new NameIndex[descriptor_->value_count()];\n ValueIndex *value_index = new ValueIndex[descriptor_->value_count()];\n for (int j = 0; j < descriptor_->value_count(); j++) {\n const EnumValueDescriptor *vd = descriptor_->value(j);\n name_index[j].index = j;\n name_index[j].name = vd->name().c_str();\n value_index[j].index = j;\n value_index[j].value = vd->number();\n value_index[j].name = vd->name().c_str();\n }\n qsort(value_index, descriptor_->value_count(),\n\tsizeof(ValueIndex), compare_value_indices_by_value_then_index);\n\n \/\/ only record unique values\n int n_unique_values;\n if (descriptor_->value_count() == 0) {\n n_unique_values = 0; \/\/ should never happen\n } else {\n n_unique_values = 1;\n value_index[0].final_index = 0;\n for (int j = 1; j < descriptor_->value_count(); j++) {\n if (value_index[j-1].value != value_index[j].value)\n\tvalue_index[j].final_index = n_unique_values++;\n else\n\tvalue_index[j].final_index = n_unique_values - 1;\n }\n }\n\n vars[\"unique_value_count\"] = SimpleItoa(n_unique_values);\n printer->Print(vars,\n \"const ProtobufCEnumValue $lcclassname$__enum_values_by_number[$unique_value_count$] =\\n\"\n \"{\\n\");\n if (descriptor_->value_count() > 0) {\n GenerateValueInitializer(printer, value_index[0].index);\n for (int j = 1; j < descriptor_->value_count(); j++) {\n if (value_index[j-1].value != value_index[j].value) {\n\tGenerateValueInitializer(printer, value_index[j].index);\n }\n }\n }\n printer->Print(vars, \"};\\n\");\n printer->Print(vars, \"static const ProtobufCIntRange $lcclassname$__value_ranges[] = {\\n\");\n unsigned n_ranges = 0;\n if (descriptor_->value_count() > 0) {\n unsigned range_start = 0;\n unsigned range_len = 1;\n int range_start_value = value_index[0].value;\n int last_value = range_start_value;\n for (int j = 1; j < descriptor_->value_count(); j++) {\n if (value_index[j-1].value != value_index[j].value) {\n\tif (last_value + 1 == value_index[j].value) {\n\t range_len++;\n\t} else {\n\t \/\/ output range\n\t vars[\"range_start_value\"] = SimpleItoa(range_start_value);\n\t vars[\"orig_index\"] = SimpleItoa(range_start);\n\t printer->Print (vars, \"{$range_start_value$, $orig_index$},\");\n\t range_start_value = value_index[j].value;\n\t range_start += range_len;\n\t range_len = 1;\n\t n_ranges++;\n\t}\n\tlast_value = value_index[j].value;\n }\n }\n {\n vars[\"range_start_value\"] = SimpleItoa(range_start_value);\n vars[\"orig_index\"] = SimpleItoa(range_start);\n printer->Print (vars, \"{$range_start_value$, $orig_index$},\");\n range_start += range_len;\n n_ranges++;\n }\n {\n vars[\"range_start_value\"] = SimpleItoa(0);\n vars[\"orig_index\"] = SimpleItoa(range_start);\n printer->Print (vars, \"{$range_start_value$, $orig_index$}\\n};\\n\");\n }\n }\n vars[\"n_ranges\"] = SimpleItoa(n_ranges);\n\n qsort(value_index, descriptor_->value_count(),\n sizeof(ValueIndex), compare_value_indices_by_name);\n printer->Print(vars,\n \"const ProtobufCEnumValueIndex $lcclassname$__enum_values_by_name[$value_count$] =\\n\"\n \"{\\n\");\n for (int j = 0; j < descriptor_->value_count(); j++) {\n vars[\"index\"] = SimpleItoa(value_index[j].final_index);\n vars[\"name\"] = value_index[j].name;\n printer->Print (vars, \" { \\\"$name$\\\", $index$ },\\n\");\n }\n printer->Print(vars, \"};\\n\");\n\n printer->Print(vars,\n \"const ProtobufCEnumDescriptor $lcclassname$__descriptor =\\n\"\n \"{\\n\"\n \" PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC,\\n\"\n \" \\\"$fullname$\\\",\\n\"\n \" \\\"$shortname$\\\",\\n\"\n \" \\\"$cname$\\\",\\n\"\n \" \\\"$packagename$\\\",\\n\"\n \" $unique_value_count$,\\n\"\n \" $lcclassname$__enum_values_by_number,\\n\"\n \" $value_count$,\\n\"\n \" $lcclassname$__enum_values_by_name,\\n\"\n \" $n_ranges$,\\n\"\n \" $lcclassname$__value_ranges,\\n\"\n \" NULL,NULL,NULL,NULL \/* reserved[1234] *\/\\n\"\n \"};\\n\");\n\n delete[] value_index;\n delete[] name_index;\n}\n\n\n\n} \/\/ namespace c\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<commit_msg>protoc-c\/c_enum.cc: Make enum_values_{by_name,by_number} structs static<commit_after>\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ http:\/\/code.google.com\/p\/protobuf\/\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:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. 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\/\/ Author: kenton@google.com (Kenton Varda)\n\/\/ Based on original Protocol Buffers design by\n\/\/ Sanjay Ghemawat, Jeff Dean, and others.\n\n\/\/ Copyright (c) 2008-2013, Dave Benson. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\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\/\/ Modified to implement C code by Dave Benson.\n\n#include <set>\n#include <map>\n\n#include <protoc-c\/c_enum.h>\n#include <protoc-c\/c_helpers.h>\n#include <google\/protobuf\/io\/printer.h>\n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace c {\n\nEnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,\n const string& dllexport_decl)\n : descriptor_(descriptor),\n dllexport_decl_(dllexport_decl) {\n}\n\nEnumGenerator::~EnumGenerator() {}\n\nvoid EnumGenerator::GenerateDefinition(io::Printer* printer) {\n map<string, string> vars;\n vars[\"classname\"] = FullNameToC(descriptor_->full_name());\n vars[\"shortname\"] = descriptor_->name();\n vars[\"uc_name\"] = FullNameToUpper(descriptor_->full_name());\n\n SourceLocation sourceLoc;\n descriptor_->GetSourceLocation(&sourceLoc);\n PrintComment (printer, sourceLoc.leading_comments);\n\n printer->Print(vars, \"typedef enum _$classname$ {\\n\");\n printer->Indent();\n\n const EnumValueDescriptor* min_value = descriptor_->value(0);\n const EnumValueDescriptor* max_value = descriptor_->value(0);\n\n\n vars[\"opt_comma\"] = \",\";\n vars[\"prefix\"] = FullNameToUpper(descriptor_->full_name()) + \"__\";\n for (int i = 0; i < descriptor_->value_count(); i++) {\n vars[\"name\"] = descriptor_->value(i)->name();\n vars[\"number\"] = SimpleItoa(descriptor_->value(i)->number());\n if (i + 1 == descriptor_->value_count())\n vars[\"opt_comma\"] = \"\";\n\n SourceLocation valSourceLoc;\n descriptor_->value(i)->GetSourceLocation(&valSourceLoc);\n\n PrintComment (printer, valSourceLoc.leading_comments);\n PrintComment (printer, valSourceLoc.trailing_comments);\n printer->Print(vars, \"$prefix$$name$ = $number$$opt_comma$\\n\");\n\n if (descriptor_->value(i)->number() < min_value->number()) {\n min_value = descriptor_->value(i);\n }\n if (descriptor_->value(i)->number() > max_value->number()) {\n max_value = descriptor_->value(i);\n }\n }\n\n printer->Print(vars, \" PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE($uc_name$)\\n\");\n printer->Outdent();\n printer->Print(vars, \"} $classname$;\\n\");\n}\n\nvoid EnumGenerator::GenerateDescriptorDeclarations(io::Printer* printer) {\n map<string, string> vars;\n if (dllexport_decl_.empty()) {\n vars[\"dllexport\"] = \"\";\n } else {\n vars[\"dllexport\"] = dllexport_decl_ + \" \";\n }\n vars[\"classname\"] = FullNameToC(descriptor_->full_name());\n vars[\"lcclassname\"] = FullNameToLower(descriptor_->full_name());\n\n printer->Print(vars,\n \"extern $dllexport$const ProtobufCEnumDescriptor $lcclassname$__descriptor;\\n\");\n}\n\nstruct ValueIndex\n{\n int value;\n unsigned index;\n unsigned final_index;\t\t\/* index in uniqified array of values *\/\n const char *name;\n};\nvoid EnumGenerator::GenerateValueInitializer(io::Printer *printer, int index)\n{\n const EnumValueDescriptor *vd = descriptor_->value(index);\n map<string, string> vars;\n vars[\"enum_value_name\"] = vd->name();\n vars[\"c_enum_value_name\"] = FullNameToUpper(descriptor_->full_name()) + \"__\" + vd->name();\n vars[\"value\"] = SimpleItoa(vd->number());\n printer->Print(vars,\n \" { \\\"$enum_value_name$\\\", \\\"$c_enum_value_name$\\\", $value$ },\\n\");\n}\n\nstatic int compare_value_indices_by_value_then_index(const void *a, const void *b)\n{\n const ValueIndex *vi_a = (const ValueIndex *) a;\n const ValueIndex *vi_b = (const ValueIndex *) b;\n if (vi_a->value < vi_b->value) return -1;\n if (vi_a->value > vi_b->value) return +1;\n if (vi_a->index < vi_b->index) return -1;\n if (vi_a->index > vi_b->index) return +1;\n return 0;\n}\n\nstatic int compare_value_indices_by_name(const void *a, const void *b)\n{\n const ValueIndex *vi_a = (const ValueIndex *) a;\n const ValueIndex *vi_b = (const ValueIndex *) b;\n return strcmp (vi_a->name, vi_b->name);\n}\n\nvoid EnumGenerator::GenerateEnumDescriptor(io::Printer* printer) {\n map<string, string> vars;\n vars[\"fullname\"] = descriptor_->full_name();\n vars[\"lcclassname\"] = FullNameToLower(descriptor_->full_name());\n vars[\"cname\"] = FullNameToC(descriptor_->full_name());\n vars[\"shortname\"] = descriptor_->name();\n vars[\"packagename\"] = descriptor_->file()->package();\n vars[\"value_count\"] = SimpleItoa(descriptor_->value_count());\n\n \/\/ Sort by name and value, dropping duplicate values if they appear later.\n \/\/ TODO: use a c++ paradigm for this!\n NameIndex *name_index = new NameIndex[descriptor_->value_count()];\n ValueIndex *value_index = new ValueIndex[descriptor_->value_count()];\n for (int j = 0; j < descriptor_->value_count(); j++) {\n const EnumValueDescriptor *vd = descriptor_->value(j);\n name_index[j].index = j;\n name_index[j].name = vd->name().c_str();\n value_index[j].index = j;\n value_index[j].value = vd->number();\n value_index[j].name = vd->name().c_str();\n }\n qsort(value_index, descriptor_->value_count(),\n\tsizeof(ValueIndex), compare_value_indices_by_value_then_index);\n\n \/\/ only record unique values\n int n_unique_values;\n if (descriptor_->value_count() == 0) {\n n_unique_values = 0; \/\/ should never happen\n } else {\n n_unique_values = 1;\n value_index[0].final_index = 0;\n for (int j = 1; j < descriptor_->value_count(); j++) {\n if (value_index[j-1].value != value_index[j].value)\n\tvalue_index[j].final_index = n_unique_values++;\n else\n\tvalue_index[j].final_index = n_unique_values - 1;\n }\n }\n\n vars[\"unique_value_count\"] = SimpleItoa(n_unique_values);\n printer->Print(vars,\n \"static const ProtobufCEnumValue $lcclassname$__enum_values_by_number[$unique_value_count$] =\\n\"\n \"{\\n\");\n if (descriptor_->value_count() > 0) {\n GenerateValueInitializer(printer, value_index[0].index);\n for (int j = 1; j < descriptor_->value_count(); j++) {\n if (value_index[j-1].value != value_index[j].value) {\n\tGenerateValueInitializer(printer, value_index[j].index);\n }\n }\n }\n printer->Print(vars, \"};\\n\");\n printer->Print(vars, \"static const ProtobufCIntRange $lcclassname$__value_ranges[] = {\\n\");\n unsigned n_ranges = 0;\n if (descriptor_->value_count() > 0) {\n unsigned range_start = 0;\n unsigned range_len = 1;\n int range_start_value = value_index[0].value;\n int last_value = range_start_value;\n for (int j = 1; j < descriptor_->value_count(); j++) {\n if (value_index[j-1].value != value_index[j].value) {\n\tif (last_value + 1 == value_index[j].value) {\n\t range_len++;\n\t} else {\n\t \/\/ output range\n\t vars[\"range_start_value\"] = SimpleItoa(range_start_value);\n\t vars[\"orig_index\"] = SimpleItoa(range_start);\n\t printer->Print (vars, \"{$range_start_value$, $orig_index$},\");\n\t range_start_value = value_index[j].value;\n\t range_start += range_len;\n\t range_len = 1;\n\t n_ranges++;\n\t}\n\tlast_value = value_index[j].value;\n }\n }\n {\n vars[\"range_start_value\"] = SimpleItoa(range_start_value);\n vars[\"orig_index\"] = SimpleItoa(range_start);\n printer->Print (vars, \"{$range_start_value$, $orig_index$},\");\n range_start += range_len;\n n_ranges++;\n }\n {\n vars[\"range_start_value\"] = SimpleItoa(0);\n vars[\"orig_index\"] = SimpleItoa(range_start);\n printer->Print (vars, \"{$range_start_value$, $orig_index$}\\n};\\n\");\n }\n }\n vars[\"n_ranges\"] = SimpleItoa(n_ranges);\n\n qsort(value_index, descriptor_->value_count(),\n sizeof(ValueIndex), compare_value_indices_by_name);\n printer->Print(vars,\n \"static const ProtobufCEnumValueIndex $lcclassname$__enum_values_by_name[$value_count$] =\\n\"\n \"{\\n\");\n for (int j = 0; j < descriptor_->value_count(); j++) {\n vars[\"index\"] = SimpleItoa(value_index[j].final_index);\n vars[\"name\"] = value_index[j].name;\n printer->Print (vars, \" { \\\"$name$\\\", $index$ },\\n\");\n }\n printer->Print(vars, \"};\\n\");\n\n printer->Print(vars,\n \"const ProtobufCEnumDescriptor $lcclassname$__descriptor =\\n\"\n \"{\\n\"\n \" PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC,\\n\"\n \" \\\"$fullname$\\\",\\n\"\n \" \\\"$shortname$\\\",\\n\"\n \" \\\"$cname$\\\",\\n\"\n \" \\\"$packagename$\\\",\\n\"\n \" $unique_value_count$,\\n\"\n \" $lcclassname$__enum_values_by_number,\\n\"\n \" $value_count$,\\n\"\n \" $lcclassname$__enum_values_by_name,\\n\"\n \" $n_ranges$,\\n\"\n \" $lcclassname$__value_ranges,\\n\"\n \" NULL,NULL,NULL,NULL \/* reserved[1234] *\/\\n\"\n \"};\\n\");\n\n delete[] value_index;\n delete[] name_index;\n}\n\n\n\n} \/\/ namespace c\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<|endoftext|>"} {"text":"<commit_before>#include \"balance.h\"\n#include \"util.h\"\n\n#include <deque>\n#include <algorithm>\n\nnamespace ledger {\n\namount_t balance_t::amount(const commodity_t& commodity) const\n{\n if (! commodity) {\n if (amounts.size() == 1) {\n amounts_map::const_iterator i = amounts.begin();\n return (*i).second;\n }\n }\n else if (amounts.size() > 0) {\n amounts_map::const_iterator i = amounts.find(&commodity);\n if (i != amounts.end())\n return (*i).second;\n }\n return amount_t();\n}\n\nbalance_t balance_t::value(const std::time_t moment) const\n{\n balance_t temp;\n\n for (amounts_map::const_iterator i = amounts.begin();\n i != amounts.end();\n i++)\n temp += (*i).second.value(moment);\n\n return temp;\n}\n\nbalance_t balance_t::price() const\n{\n balance_t temp;\n\n for (amounts_map::const_iterator i = amounts.begin();\n i != amounts.end();\n i++)\n temp += (*i).second.price();\n\n return temp;\n}\n\nstruct compare_amount_commodities {\n bool operator()(const amount_t * left, const amount_t * right) const {\n return left->commodity().symbol < right->commodity().symbol;\n }\n};\n\nvoid balance_t::write(std::ostream& out,\n\t\t const int first_width,\n\t\t const int latter_width) const\n{\n bool first = true;\n int lwidth = latter_width;\n\n if (lwidth == -1)\n lwidth = first_width;\n\n typedef std::deque<const amount_t *> amounts_deque;\n amounts_deque sorted;\n\n for (amounts_map::const_iterator i = amounts.begin();\n i != amounts.end();\n i++)\n if ((*i).second)\n sorted.push_back(&(*i).second);\n\n std::stable_sort(sorted.begin(), sorted.end(), compare_amount_commodities());\n\n for (amounts_deque::const_iterator i = sorted.begin();\n i != sorted.end();\n i++) {\n int width;\n if (! first) {\n out << std::endl;\n width = lwidth;\n } else {\n first = false;\n width = first_width;\n }\n\n out.width(width);\n out.fill(' ');\n out << std::right << **i;\n }\n\n if (first) {\n out.width(first_width);\n out.fill(' ');\n out << std::right << \"0\";\n }\n}\n\nbalance_t& balance_t::operator*=(const balance_t& bal)\n{\n if (! *this || ! bal)\n return (*this = 0L);\n else if (amounts.size() == 1 && bal.amounts.size() == 1)\n return *this *= (*bal.amounts.begin()).second;\n else {\n std::string msg;\n std::ostringstream errmsg(msg);\n errmsg << \"It makes no sense to multiply two balances: \"\n\t << *this << \" * \" << bal;\n throw amount_error(errmsg.str());\n }\n}\n\nbalance_t& balance_t::operator\/=(const balance_t& bal)\n{\n if (! *this) {\n return (*this = 0L);\n }\n else if (! bal) {\n std::string msg;\n std::ostringstream errmsg(msg);\n errmsg << \"Attempt to divide by zero: \" << *this << \" \/ \" << bal;\n throw amount_error(errmsg.str());\n }\n else if (amounts.size() == 1 && bal.amounts.size() == 1) {\n return *this \/= (*bal.amounts.begin()).second;\n }\n else if (*this == bal) {\n return (*this = 1L);\n }\n else {\n std::string msg;\n std::ostringstream errmsg(msg);\n errmsg << \"It makes no sense to divide two balances: \"\n\t << *this << \" \/ \" << bal;\n throw amount_error(errmsg.str());\n }\n}\n\nbalance_t::operator amount_t() const\n{\n if (amounts.size() == 1) {\n return (*amounts.begin()).second;\n }\n else if (amounts.size() == 0) {\n return amount_t();\n }\n else {\n std::string msg;\n std::ostringstream errmsg(msg);\n errmsg << \"Cannot convert a balance with \"\n\t << \"multiple commodities to an amount: \" << *this;\n throw amount_error(errmsg.str());\n }\n}\n\nbalance_pair_t& balance_pair_t::operator\/=(const balance_pair_t& bal_pair)\n{\n if (bal_pair.cost && ! cost)\n cost = new balance_t(quantity);\n quantity \/= bal_pair.quantity;\n if (cost)\n *cost \/= bal_pair.cost ? *bal_pair.cost : bal_pair.quantity;\n\n if (bal_pair.price && *bal_pair.price) {\n if (price)\n *price \/= *bal_pair.price;\n }\n return *this;\n}\n\n} \/\/ namespace ledger\n<commit_msg>*** empty log message ***<commit_after>#include \"balance.h\"\n#include \"util.h\"\n\n#include <deque>\n#include <algorithm>\n\nnamespace ledger {\n\namount_t balance_t::amount(const commodity_t& commodity) const\n{\n if (! commodity) {\n if (amounts.size() == 1) {\n amounts_map::const_iterator i = amounts.begin();\n return (*i).second;\n }\n }\n else if (amounts.size() > 0) {\n amounts_map::const_iterator i = amounts.find(&commodity);\n if (i != amounts.end())\n return (*i).second;\n }\n return amount_t();\n}\n\nbalance_t balance_t::value(const std::time_t moment) const\n{\n balance_t temp;\n\n for (amounts_map::const_iterator i = amounts.begin();\n i != amounts.end();\n i++)\n temp += (*i).second.value(moment);\n\n return temp;\n}\n\nbalance_t balance_t::price() const\n{\n balance_t temp;\n\n for (amounts_map::const_iterator i = amounts.begin();\n i != amounts.end();\n i++)\n temp += (*i).second.price();\n\n return temp;\n}\n\nstruct compare_amount_commodities {\n bool operator()(const amount_t * left, const amount_t * right) const {\n return left->commodity().symbol < right->commodity().symbol;\n }\n};\n\nvoid balance_t::write(std::ostream& out,\n\t\t const int first_width,\n\t\t const int latter_width) const\n{\n bool first = true;\n int lwidth = latter_width;\n\n if (lwidth == -1)\n lwidth = first_width;\n\n typedef std::deque<const amount_t *> amounts_deque;\n amounts_deque sorted;\n\n for (amounts_map::const_iterator i = amounts.begin();\n i != amounts.end();\n i++)\n if ((*i).second)\n sorted.push_back(&(*i).second);\n\n std::stable_sort(sorted.begin(), sorted.end(), compare_amount_commodities());\n\n for (amounts_deque::const_iterator i = sorted.begin();\n i != sorted.end();\n i++) {\n int width;\n if (! first) {\n out << std::endl;\n width = lwidth;\n } else {\n first = false;\n width = first_width;\n }\n\n out.width(width);\n out.fill(' ');\n out << std::right << **i;\n }\n\n if (first) {\n out.width(first_width);\n out.fill(' ');\n out << std::right << \"0\";\n }\n}\n\nbalance_t& balance_t::operator*=(const balance_t& bal)\n{\n if (! *this || ! bal) {\n return (*this = 0L);\n }\n else if (amounts.size() == 1 && bal.amounts.size() == 1) {\n return *this *= (*bal.amounts.begin()).second;\n }\n else {\n std::string msg;\n std::ostringstream errmsg(msg);\n errmsg << \"It makes no sense to multiply two balances: \"\n\t << *this << \" * \" << bal;\n throw amount_error(errmsg.str());\n }\n}\n\nbalance_t& balance_t::operator\/=(const balance_t& bal)\n{\n if (! *this) {\n return (*this = 0L);\n }\n else if (! bal) {\n std::string msg;\n std::ostringstream errmsg(msg);\n errmsg << \"Attempt to divide by zero: \" << *this << \" \/ \" << bal;\n throw amount_error(errmsg.str());\n }\n else if (amounts.size() == 1 && bal.amounts.size() == 1) {\n return *this \/= (*bal.amounts.begin()).second;\n }\n else if (*this == bal) {\n return (*this = 1L);\n }\n else {\n std::string msg;\n std::ostringstream errmsg(msg);\n errmsg << \"It makes no sense to divide two balances: \"\n\t << *this << \" \/ \" << bal;\n throw amount_error(errmsg.str());\n }\n}\n\nbalance_t::operator amount_t() const\n{\n if (amounts.size() == 1) {\n return (*amounts.begin()).second;\n }\n else if (amounts.size() == 0) {\n return amount_t();\n }\n else {\n std::string msg;\n std::ostringstream errmsg(msg);\n errmsg << \"Cannot convert a balance with \"\n\t << \"multiple commodities to an amount: \" << *this;\n throw amount_error(errmsg.str());\n }\n}\n\nbalance_pair_t& balance_pair_t::operator\/=(const balance_pair_t& bal_pair)\n{\n if (bal_pair.cost && ! cost)\n cost = new balance_t(quantity);\n quantity \/= bal_pair.quantity;\n if (cost)\n *cost \/= bal_pair.cost ? *bal_pair.cost : bal_pair.quantity;\n\n if (bal_pair.price && *bal_pair.price && price)\n *price \/= *bal_pair.price;\n return *this;\n}\n\n} \/\/ namespace ledger\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/mman.h>\n#include <math.h>\n#include <pthread.h>\n#include <assert.h>\n\n#include \"buffer.h\"\n\nextern \"C\" {\n\n#define PTR_OFFSET(ptr,offset)\t((void*)((char*)(ptr) + (offset)))\n\nbuffer_t* __posix_force_include_buffer_t;\n\nvoid *fast_malloc(size_t x) {\n void *orig = malloc(x+16);\n \/\/ Walk either 8 or 16 bytes forward\n void *ptr = (void *)((((size_t)orig + 16) >> 4) << 4);\n ((void **)ptr)[-1] = orig;\n return ptr;\n}\n\nvoid fast_free(void *ptr) {\n free(((void**)ptr)[-1]);\n}\n\nvoid *safe_malloc(size_t x) {\n void *mem;\n x = ((x + 4095)\/4096) * 4096;\n posix_memalign(&mem, 4096, x + 4096 * 3);\n printf(\"Allocated %lu bytes at %p with an electric fence\\n\", x, mem);\n\n \/\/ write the end address to unprotect in the initial fence\n ((void **)mem)[0] = PTR_OFFSET(mem, x + 4096);\n \n mprotect(mem, 4096, PROT_NONE);\n mprotect(PTR_OFFSET(mem, x + 4096), 4096, PROT_NONE);\n \n return PTR_OFFSET(mem, 4096);\n}\n\nvoid safe_free(void *ptr) {\n void *start = PTR_OFFSET(ptr, -4096);\n mprotect(start, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);\n void *end = ((void **)start)[0];\n mprotect(end, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);\n free(start);\n}\n\nstruct work {\n void (*f)(int, uint8_t *);\n int next, max;\n uint8_t *closure;\n int id;\n int active_workers;\n};\n\n#define MAX_JOBS 4096\n#define THREADS 4\nstruct {\n work jobs[MAX_JOBS];\n int head;\n int tail;\n pthread_mutex_t mutex;\n pthread_cond_t not_empty;\n pthread_t threads[THREADS];\n int ids;\n} work_queue;\n\nstruct worker_arg {\n int id;\n work *job;\n};\n\nvoid *worker(void *void_arg) {\n worker_arg *arg = (worker_arg *)void_arg;\n while (1) {\n \/\/fprintf(stderr, \"About to lock mutex\\n\");\n pthread_mutex_lock(&work_queue.mutex);\n \/\/fprintf(stderr, \"Mutex locked, checking for work\\n\");\n\n \/\/ we're master, and there's no more work\n if (arg && arg->job->id != arg->id) {\n \/\/ wait until other workers are done\n if (arg->job->active_workers) {\n pthread_mutex_unlock(&work_queue.mutex);\n while (true) {\n \/\/fprintf(stderr, \"Master waiting for workers to finish\\n\");\n pthread_mutex_lock(&work_queue.mutex);\n if (!arg->job->active_workers)\n break;\n pthread_mutex_unlock(&work_queue.mutex);\n }\n }\n \/\/ job is actually done\n pthread_mutex_unlock(&work_queue.mutex);\n \/\/fprintf(stderr, \"My work here is done. I am needed ... elsewhere!\\n\");\n return NULL;\n }\n \n if (work_queue.head == work_queue.tail) {\n assert(!arg); \/\/ the master should never get here\n \/\/fprintf(stderr, \"No work left. Going to sleep.\\n\");\n\n pthread_cond_wait(&work_queue.not_empty, &work_queue.mutex);\n pthread_mutex_unlock(&work_queue.mutex);\n continue;\n }\n\n \/\/fprintf(stderr, \"There is work\\n\");\n work *job = work_queue.jobs + work_queue.head;\n if (job->next == job->max) {\n \/\/fprintf(stderr, \"Found a finished job. Removing it\\n\");\n work_queue.head = (work_queue.head + 1) % MAX_JOBS; \n job->id = 0; \/\/ mark the job done\n pthread_mutex_unlock(&work_queue.mutex);\n } else {\n \/\/ claim this task\n work myjob = *job;\n job->next++;\n job->active_workers++;\n pthread_mutex_unlock(&work_queue.mutex);\n \/\/fprintf(stderr, \"Doing job %d\\n\", myjob.next);\n myjob.f(myjob.next, myjob.closure);\n \/\/fprintf(stderr, \"Done with job %d\\n\", myjob.next);\n pthread_mutex_lock(&work_queue.mutex);\n job->active_workers--;\n pthread_mutex_unlock(&work_queue.mutex);\n } \n }\n}\n\nvoid do_par_for(void (*f)(int, uint8_t *), int min, int size, uint8_t *closure) {\n static bool thread_pool_initialized = false;\n if (!thread_pool_initialized) {\n pthread_mutex_init(&work_queue.mutex, NULL);\n pthread_cond_init(&work_queue.not_empty, NULL);\n work_queue.head = work_queue.tail = 0;\n work_queue.ids = 1;\n for (int i = 0; i < THREADS; i++) {\n pthread_create(work_queue.threads + i, NULL, worker, NULL);\n }\n\n thread_pool_initialized = true;\n }\n\n \/\/ Enqueue the job\n pthread_mutex_lock(&work_queue.mutex);\n \/\/fprintf(stderr, \"Enqueuing some work\\n\");\n work job = {f, min, min + size, closure, work_queue.ids++, 0};\n if (job.id == 0) job.id = work_queue.ids++; \/\/ disallow zero, as it flags a completed job\n work_queue.jobs[work_queue.tail] = job;\n work *jobPtr = work_queue.jobs + work_queue.tail;\n worker_arg arg = {job.id, jobPtr};\n int new_tail = (work_queue.tail + 1) % MAX_JOBS;\n assert(new_tail != work_queue.head); \n work_queue.tail = new_tail;\n\n \/\/ TODO: check to make sure the work queue doesn't overflow\n pthread_mutex_unlock(&work_queue.mutex);\n \n \/\/ Wake up everyone\n pthread_cond_broadcast(&work_queue.not_empty);\n\n \/\/ Do some work myself\n worker((void *)(&arg));\n}\n\nfloat sqrt_f32(float x) {\n return sqrtf(x);\n}\n\nfloat sin_f32(float x) {\n return sinf(x);\n}\n\nfloat cos_f32(float x) {\n return cosf(x);\n}\n\nfloat exp_f32(float x) {\n return expf(x);\n}\n\nfloat log_f32(float x) {\n return logf(x);\n}\n\nfloat pow_f32(float x, float y) {\n return powf(x, y);\n}\n\nfloat floor_f32(float x) {\n return floorf(x);\n}\n\nfloat ceil_f32(float x) {\n return ceilf(x);\n}\n\nfloat round_f32(float x) {\n return roundf(x);\n}\n\n#include <sys\/time.h>\n\nint currentTime() {\n static bool initialized = false;\n static timeval start;\n if (!initialized) {\n gettimeofday(&start, NULL);\n initialized = true;\n return 0;\n } else {\n timeval now;\n gettimeofday(&now, NULL);\n return\n (now.tv_sec - start.tv_sec)*1000 + \n (now.tv_usec - start.tv_usec)\/1000;\n }\n}\n\n}\n<commit_msg>thread count settable with environment var<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/mman.h>\n#include <math.h>\n#include <pthread.h>\n#include <assert.h>\n\n#include \"buffer.h\"\n\nextern \"C\" {\n\n#define PTR_OFFSET(ptr,offset)\t((void*)((char*)(ptr) + (offset)))\n\nbuffer_t* __posix_force_include_buffer_t;\n\nvoid *fast_malloc(size_t x) {\n void *orig = malloc(x+16);\n \/\/ Walk either 8 or 16 bytes forward\n void *ptr = (void *)((((size_t)orig + 16) >> 4) << 4);\n ((void **)ptr)[-1] = orig;\n return ptr;\n}\n\nvoid fast_free(void *ptr) {\n free(((void**)ptr)[-1]);\n}\n\nvoid *safe_malloc(size_t x) {\n void *mem;\n x = ((x + 4095)\/4096) * 4096;\n posix_memalign(&mem, 4096, x + 4096 * 3);\n printf(\"Allocated %lu bytes at %p with an electric fence\\n\", x, mem);\n\n \/\/ write the end address to unprotect in the initial fence\n ((void **)mem)[0] = PTR_OFFSET(mem, x + 4096);\n \n mprotect(mem, 4096, PROT_NONE);\n mprotect(PTR_OFFSET(mem, x + 4096), 4096, PROT_NONE);\n \n return PTR_OFFSET(mem, 4096);\n}\n\nvoid safe_free(void *ptr) {\n void *start = PTR_OFFSET(ptr, -4096);\n mprotect(start, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);\n void *end = ((void **)start)[0];\n mprotect(end, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);\n free(start);\n}\n\nstruct work {\n void (*f)(int, uint8_t *);\n int next, max;\n uint8_t *closure;\n int id;\n int active_workers;\n};\n\n#define MAX_JOBS 65536\n#define MAX_THREADS 64\nstruct {\n work jobs[MAX_JOBS];\n int head;\n int tail;\n pthread_mutex_t mutex;\n pthread_cond_t not_empty;\n pthread_t threads[MAX_THREADS];\n int ids;\n} work_queue;\n\nstruct worker_arg {\n int id;\n work *job;\n};\n\nint threads;\n\nvoid *worker(void *void_arg) {\n worker_arg *arg = (worker_arg *)void_arg;\n while (1) {\n \/\/fprintf(stderr, \"About to lock mutex\\n\");\n pthread_mutex_lock(&work_queue.mutex);\n \/\/fprintf(stderr, \"Mutex locked, checking for work\\n\");\n\n \/\/ we're master, and there's no more work\n if (arg && arg->job->id != arg->id) {\n \/\/ wait until other workers are done\n if (arg->job->active_workers) {\n pthread_mutex_unlock(&work_queue.mutex);\n while (true) {\n \/\/fprintf(stderr, \"Master waiting for workers to finish\\n\");\n pthread_mutex_lock(&work_queue.mutex);\n if (!arg->job->active_workers)\n break;\n pthread_mutex_unlock(&work_queue.mutex);\n }\n }\n \/\/ job is actually done\n pthread_mutex_unlock(&work_queue.mutex);\n \/\/fprintf(stderr, \"My work here is done. I am needed ... elsewhere!\\n\");\n return NULL;\n }\n \n if (work_queue.head == work_queue.tail) {\n assert(!arg); \/\/ the master should never get here\n \/\/fprintf(stderr, \"No work left. Going to sleep.\\n\");\n\n pthread_cond_wait(&work_queue.not_empty, &work_queue.mutex);\n pthread_mutex_unlock(&work_queue.mutex);\n continue;\n }\n\n \/\/fprintf(stderr, \"There is work\\n\");\n work *job = work_queue.jobs + work_queue.head;\n if (job->next == job->max) {\n \/\/fprintf(stderr, \"Found a finished job. Removing it\\n\");\n work_queue.head = (work_queue.head + 1) % MAX_JOBS; \n job->id = 0; \/\/ mark the job done\n pthread_mutex_unlock(&work_queue.mutex);\n } else {\n int remaining = job->max - job->next;\n \/\/ Claim some tasks\n \/\/int claimed = (remaining + threads - 1)\/threads;\n int claimed = 1;\n \/\/printf(\"Claiming %d tasks\\n\", claimed);\n work myjob = *job;\n job->next += claimed; \n myjob.max = job->next;\n job->active_workers++;\n pthread_mutex_unlock(&work_queue.mutex);\n \/\/fprintf(stderr, \"Doing job %d\\n\", myjob.next);\n for (; myjob.next < myjob.max; myjob.next++)\n myjob.f(myjob.next, myjob.closure);\n \/\/fprintf(stderr, \"Done with job %d\\n\", myjob.next);\n pthread_mutex_lock(&work_queue.mutex);\n job->active_workers--;\n pthread_mutex_unlock(&work_queue.mutex);\n } \n }\n}\n\nvoid do_par_for(void (*f)(int, uint8_t *), int min, int size, uint8_t *closure) {\n static bool thread_pool_initialized = false;\n if (!thread_pool_initialized) {\n pthread_mutex_init(&work_queue.mutex, NULL);\n pthread_cond_init(&work_queue.not_empty, NULL);\n work_queue.head = work_queue.tail = 0;\n work_queue.ids = 1;\n char *threadStr = getenv(\"HL_NUMTHREADS\");\n threads = 8;\n if (threadStr) {\n threads = atoi(threadStr);\n } else {\n printf(\"HL_NUMTHREADS not defined. Defaulting to 8 threads.\\n\");\n }\n if (threads > MAX_THREADS) threads = MAX_THREADS;\n for (int i = 0; i < threads-1; i++) {\n pthread_create(work_queue.threads + i, NULL, worker, NULL);\n }\n\n thread_pool_initialized = true;\n }\n\n \/\/ Enqueue the job\n pthread_mutex_lock(&work_queue.mutex);\n \/\/fprintf(stderr, \"Enqueuing some work\\n\");\n work job = {f, min, min + size, closure, work_queue.ids++, 0};\n if (job.id == 0) job.id = work_queue.ids++; \/\/ disallow zero, as it flags a completed job\n work_queue.jobs[work_queue.tail] = job;\n work *jobPtr = work_queue.jobs + work_queue.tail;\n worker_arg arg = {job.id, jobPtr};\n int new_tail = (work_queue.tail + 1) % MAX_JOBS;\n assert(new_tail != work_queue.head); \n work_queue.tail = new_tail;\n\n \/\/ TODO: check to make sure the work queue doesn't overflow\n pthread_mutex_unlock(&work_queue.mutex);\n \n \/\/ Wake up everyone\n pthread_cond_broadcast(&work_queue.not_empty);\n\n \/\/ Do some work myself\n worker((void *)(&arg));\n}\n\nfloat sqrt_f32(float x) {\n return sqrtf(x);\n}\n\nfloat sin_f32(float x) {\n return sinf(x);\n}\n\nfloat cos_f32(float x) {\n return cosf(x);\n}\n\nfloat exp_f32(float x) {\n return expf(x);\n}\n\nfloat log_f32(float x) {\n return logf(x);\n}\n\nfloat pow_f32(float x, float y) {\n return powf(x, y);\n}\n\nfloat floor_f32(float x) {\n return floorf(x);\n}\n\nfloat ceil_f32(float x) {\n return ceilf(x);\n}\n\nfloat round_f32(float x) {\n return roundf(x);\n}\n\n#include <sys\/time.h>\n\nint currentTime() {\n static bool initialized = false;\n static timeval start;\n if (!initialized) {\n gettimeofday(&start, NULL);\n initialized = true;\n return 0;\n } else {\n timeval now;\n gettimeofday(&now, NULL);\n return\n (now.tv_sec - start.tv_sec)*1000 + \n (now.tv_usec - start.tv_usec)\/1000;\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <random>\n\n#include \"genetic.h\"\n\nstd::mt19937 Context::rng;\n\nnamespace Config {\n const float selectBias = 3;\n const int popSize = 500;\n const int popSize2 = 500;\n const int nGen = 200;\n\n const float expLengthIni = 100;\n const float expLengthAdd = 5;\n const float pLength = 1\/1000.0;\n const float pControl = 1\/1000.0;\n\n const int nIn = 6;\n const int nOut = 3;\n const int nAnc = 3;\n const int nBit = nIn + nOut + nAnc;\n\n unsigned f(unsigned in) {\n int in1 = in & ((1 << Config::nIn\/2) - 1);\n int in2 = (in >> Config::nIn\/2) & ((1 << Config::nIn\/2) - 1);\n return (in1 + in2) & ((1 << Config::nOut) - 1);\n }\n}\n\n\nclass Gene {\n int tgt;\n unsigned ctrlEnc;\n unsigned ctrl;\n\n public:\n Gene(int _target, unsigned _control): tgt(_target), ctrlEnc(_control) {\n ctrl =\n ((ctrlEnc >> tgt) << (tgt+1)) \/\/ shift bits left of tgt to the left\n |\n (ctrlEnc & ((1 << tgt) - 1)); \/\/ keep bits right of tgt\n }\n\n int target() const {\n return tgt;\n }\n\n int control() const {\n return ctrlEnc;\n }\n\n unsigned apply(unsigned src) {\n return ((src & ctrl) == ctrl)\n ? (src ^ (1 << tgt))\n : src;\n }\n\n friend std::ostream& operator<< (std::ostream& os, const Gene& g) {\n os << g.tgt+1;\n auto c = g.ctrl;\n if(c != 0) {\n os << '[';\n for(int i = 1, m = 1; i <= Config::nBit; i++, m <<= 1)\n if(c & m)\n os << i;\n os << ']';\n }\n return os;\n }\n};\n\n\nclass Candidate: public ICandidate<float> {\n std::vector<Gene> gt;\n\n public:\n Candidate() = default;\n\n Candidate(auto _gt): gt(_gt) { }\n\n static Candidate m1(const Candidate&);\n static Candidate m2(const Candidate&);\n static Candidate m3(const Candidate&);\n static Candidate m4(const Candidate&);\n static Candidate m5(const Candidate&);\n static Candidate m6(const Candidate&);\n static Candidate crossover(const Candidate&, const Candidate&);\n\n friend std::ostream& operator<< (std::ostream& os, const Candidate& c) {\n os << c.fitness() << ':';\n for(Gene g : c.gt)\n os << ' ' << g;\n return os;\n }\n\n private:\n float computeFitness() const {\n register unsigned work;\n unsigned out;\n int mism = 0;\n for(int in = 0; in < (1 << Config::nIn); in++) {\n work = in;\n for(Gene g : gt)\n work = g.apply(work);\n out = (work >> Config::nIn) & ((1 << Config::nOut) - 1);\n if(out != Config::f(in))\n mism++;\n }\n return mism + gt.size()*Config::pLength + Config::pControl*hamming();\n }\n\n int hamming() const {\n int v = 0;\n for(Gene g : gt) {\n unsigned ctrl = g.control();\n int h = 0;\n for(int i = 0, m = 1; i < Config::nBit - 1; i++, m <<= 1)\n if(ctrl & m)\n h++;\n v += h*h;\n }\n return v;\n }\n};\n\n\n\n\/* Alter target in one gene *\/\nCandidate Candidate::m1(const Candidate& p) {\n auto gm = p.gt;\n if(gm.size() == 0)\n return p;\n std::uniform_int_distribution<> dPos(0, gm.size() - 1);\n std::uniform_int_distribution<> dTgt(0, Config::nBit - 1);\n int pos = dPos(Context::rng);\n gm[pos] = Gene(dTgt(Context::rng), gm[pos].control());\n return Candidate(gm);\n}\n\n\/* Alter control in one gene *\/\nCandidate Candidate::m2(const Candidate& p) {\n auto gm = p.gt;\n if(gm.size() == 0)\n return p;\n std::uniform_int_distribution<> dPos(0, gm.size() - 1);\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n int pos = dPos(Context::rng);\n gm[pos] = Gene(gm[pos].target(), dCtrl(Context::rng));\n return Candidate(gm);\n}\n\n\/* Add a random operation sequence *\/\nCandidate Candidate::m3(const Candidate& p) {\n auto gm = p.gt;\n std::uniform_int_distribution<> dPos(0, gm.size());\n std::uniform_int_distribution<> dTgt(0, Config::nBit - 1);\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n std::uniform_real_distribution<> dProb(0, 1);\n int pos = dPos(Context::rng);\n float probTerm = 1\/Config::expLengthAdd;\n do {\n gm.insert(gm.begin() + pos, Gene(dTgt(Context::rng), dCtrl(Context::rng)));\n } while(dProb(Context::rng) > probTerm);\n return Candidate(gm);\n}\n\n\/* Add an operation pair *\/\nCandidate Candidate::m4(const Candidate& p) {\n auto gm = p.gt;\n std::uniform_int_distribution<> dPos(0, gm.size());\n std::uniform_int_distribution<> dTgt(0, Config::nBit - 1);\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n int pos1 = dPos(Context::rng),\n pos2 = dPos(Context::rng);\n if(pos2 < pos1)\n std::swap(pos1, pos2);\n unsigned tgt = dTgt(Context::rng),\n ctrl = dCtrl(Context::rng);\n gm.insert(gm.begin() + pos2, Gene(tgt, ctrl));\n gm.insert(gm.begin() + pos1, Gene(tgt, ctrl));\n return Candidate(gm);\n}\n\n\/* Delete a random slice *\/\nCandidate Candidate::m5(const Candidate& p) {\n auto gm = p.gt;\n if(gm.size() == 0)\n return p;\n std::uniform_int_distribution<> dPos(0, gm.size());\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n int pos1 = dPos(Context::rng),\n pos2 = dPos(Context::rng);\n if(pos2 < pos1)\n std::swap(pos1, pos2);\n gm.erase(gm.begin() + pos1, gm.begin() + pos2);\n return Candidate(gm);\n}\n\n\/* Permute gates (split & swap) *\/\nCandidate Candidate::m6(const Candidate& p) {\n if(p.gt.size() == 0)\n return p;\n std::uniform_int_distribution<> dPos(0, p.gt.size());\n int pos = dPos(Context::rng);\n std::vector<Gene> gm(p.gt.begin() + pos, p.gt.end());\n gm.insert(gm.end(), p.gt.begin(), p.gt.begin() + pos);\n return Candidate(gm);\n}\n\n\/* One-point crossover *\/\nCandidate Candidate::crossover(const Candidate& p1, const Candidate& p2) {\n auto gt1 = p1.gt,\n gt2 = p2.gt;\n std::uniform_int_distribution<> dPos1(0, gt1.size()), dPos2(0, gt2.size());\n int pos1 = dPos1(Context::rng),\n pos2 = dPos2(Context::rng);\n std::vector<Gene> gm(gt1.begin(), gt1.begin() + pos1);\n gm.insert(gm.end(), gt2.begin() + pos2, gt2.end());\n return Candidate(gm);\n}\n\n\nint main() {\n Context::rng = std::mt19937((std::random_device())());\n\n Population<Candidate> pop;\n {\n float probTerm = 1\/Config::expLengthIni; \/* probability of termination; expLength = expected number of genes *\/\n std::uniform_real_distribution<float> rDist(0, 1);\n std::uniform_int_distribution<> dTgt(0, Config::nBit - 1);\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n for(int i = 0; i < Config::popSize; i++) {\n std::vector<Gene> gt;\n do {\n gt.push_back(Gene(dTgt(Context::rng), dCtrl(Context::rng)));\n } while(rDist(Context::rng) > probTerm);\n pop.add(Candidate(gt));\n }\n }\n\n for(int gen = 0; gen < Config::nGen; gen++) {\n Population<Candidate> pop2 = pop;\n \/\/std::uniform_real_distribution<float> rDist(0, 1);\n std::uniform_int_distribution<> rDist(0, 5);\n Candidate (*func[])(const Candidate&) = {Candidate::m1, Candidate::m2, Candidate::m3, Candidate::m4, Candidate::m5, Candidate::m6};\n for(int b = 0; b < Config::popSize2; b++)\n pop2.add(func[rDist(Context::rng)](pop.rankSelect()));\n\n pop = pop2.trim();\n\n std::cout << \"Gen \" << gen << \": best of pop \" << pop.best() << std::endl;\n }\n}\n<commit_msg>Candidate::getNew()<commit_after>#include <iostream>\n#include <random>\n#include <functional>\n\n#include \"genetic.h\"\n\nstd::mt19937 Context::rng;\n\nnamespace Config {\n const float selectBias = 3;\n const int popSize = 500;\n const int popSize2 = 500;\n const int nGen = 500;\n\n const float expLengthIni = 100;\n const float expLengthAdd = 5;\n const float pLength = 1\/1000.0;\n const float pControl = 1\/1000.0;\n\n const int nIn = 6;\n const int nOut = 1;\n const int nAnc = 3;\n const int nBit = nIn + nOut + nAnc;\n\n unsigned f(unsigned in) {\n int in1 = in & ((1 << Config::nIn\/2) - 1);\n int in2 = (in >> Config::nIn\/2) & ((1 << Config::nIn\/2) - 1);\n return (in1 + in2 >> 2) & ((1 << Config::nOut) - 1);\n }\n}\n\n\nclass Gene {\n int tgt;\n unsigned ctrlEnc;\n unsigned ctrl;\n\n public:\n Gene(int _target, unsigned _control): tgt(_target), ctrlEnc(_control) {\n ctrl =\n ((ctrlEnc >> tgt) << (tgt+1)) \/\/ shift bits left of tgt to the left\n |\n (ctrlEnc & ((1 << tgt) - 1)); \/\/ keep bits right of tgt\n }\n\n int target() const {\n return tgt;\n }\n\n int control() const {\n return ctrlEnc;\n }\n\n unsigned apply(unsigned src) {\n return ((src & ctrl) == ctrl)\n ? (src ^ (1 << tgt))\n : src;\n }\n\n friend std::ostream& operator<< (std::ostream& os, const Gene& g) {\n os << g.tgt+1;\n auto c = g.ctrl;\n if(c != 0) {\n os << '[';\n for(int i = 1, m = 1; i <= Config::nBit; i++, m <<= 1)\n if(c & m)\n os << i;\n os << ']';\n }\n return os;\n }\n};\n\n\nclass Candidate: public ICandidate<float> {\n std::vector<Gene> gt;\n\n public:\n Candidate() = default;\n\n Candidate(auto _gt): gt(_gt) { }\n\n static Candidate m1(const Candidate&);\n static Candidate m2(const Candidate&);\n static Candidate m3(const Candidate&);\n static Candidate m4(const Candidate&);\n static Candidate m5(const Candidate&);\n static Candidate m6(const Candidate&);\n static Candidate crossover(const Candidate&, const Candidate&);\n\n static Candidate getNew(std::function<Candidate()>);\n\n friend std::ostream& operator<< (std::ostream& os, const Candidate& c) {\n os << c.fitness() << ':';\n for(Gene g : c.gt)\n os << ' ' << g;\n return os;\n }\n\n private:\n float computeFitness() const {\n register unsigned work;\n unsigned out;\n int mism = 0;\n for(int in = 0; in < (1 << Config::nIn); in++) {\n work = in;\n for(Gene g : gt)\n work = g.apply(work);\n out = (work >> Config::nIn) & ((1 << Config::nOut) - 1);\n if(out != Config::f(in))\n mism++;\n }\n return mism + gt.size()*Config::pLength + Config::pControl*hamming();\n }\n\n int hamming() const {\n int v = 0;\n for(Gene g : gt) {\n unsigned ctrl = g.control();\n int h = 0;\n for(int i = 0, m = 1; i < Config::nBit - 1; i++, m <<= 1)\n if(ctrl & m)\n h++;\n v += h*h;\n }\n return v;\n }\n};\n\n\n\n\/* Alter target in one gene *\/\nCandidate Candidate::m1(const Candidate& p) {\n auto gm = p.gt;\n if(gm.size() == 0)\n return p;\n std::uniform_int_distribution<> dPos(0, gm.size() - 1);\n std::uniform_int_distribution<> dTgt(0, Config::nBit - 1);\n int pos = dPos(Context::rng);\n gm[pos] = Gene(dTgt(Context::rng), gm[pos].control());\n return Candidate(gm);\n}\n\n\/* Alter control in one gene *\/\nCandidate Candidate::m2(const Candidate& p) {\n auto gm = p.gt;\n if(gm.size() == 0)\n return p;\n std::uniform_int_distribution<> dPos(0, gm.size() - 1);\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n int pos = dPos(Context::rng);\n gm[pos] = Gene(gm[pos].target(), dCtrl(Context::rng));\n return Candidate(gm);\n}\n\n\/* Add a random operation sequence *\/\nCandidate Candidate::m3(const Candidate& p) {\n auto gm = p.gt;\n std::uniform_int_distribution<> dPos(0, gm.size());\n std::uniform_int_distribution<> dTgt(0, Config::nBit - 1);\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n std::uniform_real_distribution<> dProb(0, 1);\n int pos = dPos(Context::rng);\n float probTerm = 1\/Config::expLengthAdd;\n do {\n gm.insert(gm.begin() + pos, Gene(dTgt(Context::rng), dCtrl(Context::rng)));\n } while(dProb(Context::rng) > probTerm);\n return Candidate(gm);\n}\n\n\/* Add an operation pair *\/\nCandidate Candidate::m4(const Candidate& p) {\n auto gm = p.gt;\n std::uniform_int_distribution<> dPos(0, gm.size());\n std::uniform_int_distribution<> dTgt(0, Config::nBit - 1);\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n int pos1 = dPos(Context::rng),\n pos2 = dPos(Context::rng);\n if(pos2 < pos1)\n std::swap(pos1, pos2);\n unsigned tgt = dTgt(Context::rng),\n ctrl = dCtrl(Context::rng);\n gm.insert(gm.begin() + pos2, Gene(tgt, ctrl));\n gm.insert(gm.begin() + pos1, Gene(tgt, ctrl));\n return Candidate(gm);\n}\n\n\/* Delete a random slice *\/\nCandidate Candidate::m5(const Candidate& p) {\n auto gm = p.gt;\n if(gm.size() == 0)\n return p;\n std::uniform_int_distribution<> dPos(0, gm.size());\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n int pos1 = dPos(Context::rng),\n pos2 = dPos(Context::rng);\n if(pos2 < pos1)\n std::swap(pos1, pos2);\n gm.erase(gm.begin() + pos1, gm.begin() + pos2);\n return Candidate(gm);\n}\n\n\/* Permute gates (split & swap) *\/\nCandidate Candidate::m6(const Candidate& p) {\n if(p.gt.size() == 0)\n return p;\n std::uniform_int_distribution<> dPos(0, p.gt.size());\n int pos = dPos(Context::rng);\n std::vector<Gene> gm(p.gt.begin() + pos, p.gt.end());\n gm.insert(gm.end(), p.gt.begin(), p.gt.begin() + pos);\n return Candidate(gm);\n}\n\n\/* One-point crossover *\/\nCandidate Candidate::crossover(const Candidate& p1, const Candidate& p2) {\n auto gt1 = p1.gt,\n gt2 = p2.gt;\n std::uniform_int_distribution<> dPos1(0, gt1.size()), dPos2(0, gt2.size());\n int pos1 = dPos1(Context::rng),\n pos2 = dPos2(Context::rng);\n std::vector<Gene> gm(gt1.begin(), gt1.begin() + pos1);\n gm.insert(gm.end(), gt2.begin() + pos2, gt2.end());\n return Candidate(gm);\n}\n\nCandidate Candidate::getNew(std::function<Candidate()> get) {\n Candidate (*mutations[])(const Candidate&) = {Candidate::m1, Candidate::m2, Candidate::m3, Candidate::m4, Candidate::m5, Candidate::m6};\n \/\/std::uniform_real_distribution<float> rDist(0, 1);\n std::uniform_int_distribution<> rDist(0, 6);\n int which = rDist(Context::rng);\n if(which < 6)\n return mutations[which](get());\n else\n return Candidate::crossover(get(), get());\n}\n\n\nint main() {\n Context::rng = std::mt19937((std::random_device())());\n\n Population<Candidate> pop;\n {\n float probTerm = 1\/Config::expLengthIni; \/* probability of termination; expLength = expected number of genes *\/\n std::uniform_real_distribution<float> rDist(0, 1);\n std::uniform_int_distribution<> dTgt(0, Config::nBit - 1);\n std::uniform_int_distribution<> dCtrl(0, (1 << (Config::nBit-1)) - 1);\n for(int i = 0; i < Config::popSize; i++) {\n std::vector<Gene> gt;\n do {\n gt.push_back(Gene(dTgt(Context::rng), dCtrl(Context::rng)));\n } while(rDist(Context::rng) > probTerm);\n pop.add(Candidate(gt));\n }\n }\n\n for(int gen = 0; gen < Config::nGen; gen++) {\n Population<Candidate> pop2 = pop;\n for(int b = 0; b < Config::popSize2; b++)\n pop2.add(Candidate::getNew([&] { return pop.rankSelect(); }));\n\n pop = pop2.trim();\n\n std::cout << \"Gen \" << gen << \": best of pop \" << pop.best() << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2006-2008 The FLWOR 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#include \"stdafx.h\"\n\n#include <ostream>\n#include <sstream>\n\n#include \"compiler\/parser\/query_loc.h\"\n\nnamespace zorba \n{\n\nQueryLoc QueryLoc::null;\n\n\nQueryLoc::QueryLoc()\n :\n theFilename(\"\"),\n theLineBegin (0),\n theColumnBegin (0),\n theLineEnd (0),\n theColumnEnd (0)\n{\n}\n\n\nQueryLoc::QueryLoc( zstring const &filename, line_type lineBegin,\n line_type lineEnd, column_type columnBegin,\n column_type columnEnd ) :\n theFilename(filename),\n theLineBegin(lineBegin),\n theColumnBegin(columnBegin),\n theLineEnd(lineEnd),\n theColumnEnd(columnEnd)\n{\n}\n\n\nstd::ostream& operator<<(std::ostream& aOstr, const QueryLoc& aQueryLoc) \n{\n std::stringstream lLoc;\n\n if (!aQueryLoc.theFilename.empty())\n {\n lLoc << aQueryLoc.theFilename;\n }\n\n bool lPrintLines = aQueryLoc.theLineBegin;\n bool lPrintColumns = aQueryLoc.theLineBegin && aQueryLoc.theLineEnd &&\n aQueryLoc.theColumnBegin && aQueryLoc.theColumnEnd;\n\n if (lPrintLines)\n {\n lLoc << \":\" << aQueryLoc.theLineBegin;\n if (lPrintColumns)\n lLoc << \".\" << aQueryLoc.theColumnBegin;\n\n lLoc << \"-\" << (aQueryLoc.theLineEnd ? aQueryLoc.theLineEnd : aQueryLoc.theLineBegin);\n if (lPrintColumns)\n lLoc << \".\" << aQueryLoc.theColumnEnd;\n }\n\n return aOstr;\n}\n\n\nbool QueryLoc::equals(const QueryLoc& loc) const\n{\n std::stringstream lFile;\n lFile << theFilename.c_str();\n std::string lFile1(lFile.str());\n std::string lFile2;\n std::string::iterator it;\n\n for (it = lFile1.begin(); it != lFile1.end(); ++it)\n {\n if (*it == '\\\\')\n {\n lFile2.append(1, *it);\n ++it;\n if (*it == '\\\\')\n {\n continue;\n }\n }\n lFile2.append(1, *it);\n }\n\n return (loc.getFilename() == lFile2 &&\n theColumnBegin == loc.getColumnBegin() &&\n theColumnEnd == loc.getColumnEnd() &&\n theLineBegin == loc.getLineBegin() &&\n theLineEnd == loc.getLineEnd());\n}\n\n\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<commit_msg>Fixed operator<<<commit_after>\/*\n * Copyright 2006-2008 The FLWOR 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#include \"stdafx.h\"\n\n#include <ostream>\n#include <sstream>\n\n#include \"compiler\/parser\/query_loc.h\"\n\nnamespace zorba \n{\n\nQueryLoc QueryLoc::null;\n\n\nQueryLoc::QueryLoc()\n :\n theFilename(\"\"),\n theLineBegin (0),\n theColumnBegin (0),\n theLineEnd (0),\n theColumnEnd (0)\n{\n}\n\n\nQueryLoc::QueryLoc( zstring const &filename, line_type lineBegin,\n line_type lineEnd, column_type columnBegin,\n column_type columnEnd ) :\n theFilename(filename),\n theLineBegin(lineBegin),\n theColumnBegin(columnBegin),\n theLineEnd(lineEnd),\n theColumnEnd(columnEnd)\n{\n}\n\n\nstd::ostream& operator<<(std::ostream& aOstr, const QueryLoc& aQueryLoc) \n{\n if (!aQueryLoc.theFilename.empty())\n {\n aOstr << aQueryLoc.theFilename;\n }\n\n bool lPrintLines = aQueryLoc.theLineBegin;\n bool lPrintColumns = aQueryLoc.theLineBegin && aQueryLoc.theLineEnd &&\n aQueryLoc.theColumnBegin && aQueryLoc.theColumnEnd;\n\n if (lPrintLines)\n {\n aOstr << \":\" << aQueryLoc.theLineBegin;\n if (lPrintColumns)\n aOstr << \".\" << aQueryLoc.theColumnBegin;\n\n aOstr << \"-\" << (aQueryLoc.theLineEnd ? aQueryLoc.theLineEnd : aQueryLoc.theLineBegin);\n if (lPrintColumns)\n aOstr << \".\" << aQueryLoc.theColumnEnd;\n }\n\n return aOstr;\n}\n\n\nbool QueryLoc::equals(const QueryLoc& loc) const\n{\n std::stringstream lFile;\n lFile << theFilename.c_str();\n std::string lFile1(lFile.str());\n std::string lFile2;\n std::string::iterator it;\n\n for (it = lFile1.begin(); it != lFile1.end(); ++it)\n {\n if (*it == '\\\\')\n {\n lFile2.append(1, *it);\n ++it;\n if (*it == '\\\\')\n {\n continue;\n }\n }\n lFile2.append(1, *it);\n }\n\n return (loc.getFilename() == lFile2 &&\n theColumnBegin == loc.getColumnBegin() &&\n theColumnEnd == loc.getColumnEnd() &&\n theLineBegin == loc.getLineBegin() &&\n theLineEnd == loc.getLineEnd());\n}\n\n\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * 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#include \"condor_common.h\"\n#include \"condor_constants.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"condor_uid.h\"\n#include \"file_lock.h\"\n#include \"utc_time.h\"\n\nextern \"C\" int lock_file( int fd, LOCK_TYPE type, BOOLEAN do_block );\n\nFileLockBase::FileLockBase( void )\n{\n\tm_state = UN_LOCK;\n\tm_blocking = true;\n\trecordExistence();\n}\n\nFileLockBase::~FileLockBase(void)\n{\n\teraseExistence();\n}\n\nconst char *\nFileLockBase::getStateString( LOCK_TYPE state ) const\n{\n\tswitch( state ) {\n\tcase READ_LOCK:\n\t\treturn \"READ\";\n\tcase WRITE_LOCK:\n\t\treturn \"WRITE\";\n\tcase UN_LOCK:\n\t\treturn \"UNLOCKED\";\n\tdefault:\n\t\treturn \"UNKNOWN\";\n\t}\n}\n\nvoid\nFileLockBase::updateAllLockTimestamps(void)\n{\n\tFileLockEntry *fle = NULL;\n\n\tfle = m_all_locks;\n\n\t\/\/ walk the locks list and have each one update its timestamp\n\twhile(fle != NULL) {\n\t\tfle->fl->updateLockTimestamp();\n\t\tfle = fle->next;\n\t}\n}\n\nvoid \nFileLockBase::recordExistence(void)\n{\n\tFileLockEntry *fle = new FileLockEntry;\n\t\n\tfle->fl = this;\n\n\t\/\/ insert it at the head of the singly linked list\n\tfle->next = m_all_locks;\n\tm_all_locks = fle;\n}\n\nvoid \nFileLockBase::eraseExistence(void)\n{\n\t\/\/ do a little brother style removal in the singly linked list\n\n\tFileLockEntry *prev = NULL;\n\tFileLockEntry *curr = NULL;\n\tFileLockEntry *del = NULL;\n\n\tif (m_all_locks == NULL) {\n\t\tgoto bail_out;\n\t}\n\n\t\/\/ is it the first one?\n\tif (m_all_locks->fl == this) {\n\t\tdel = m_all_locks;\n\t\tm_all_locks = m_all_locks->next;\n\t\tdelete del;\n\t\treturn;\n\t}\n\n\t\/\/ if it is the second one or beyond, find it and delete the entry\n\t\/\/ from the list.\n\tprev = m_all_locks;\n\tcurr = m_all_locks->next;\n\n\twhile(curr != NULL) {\n\t\tif (curr->fl == this) {\n\t\t\t\/\/ found it, mark it for deletion.\n\t\t\tdel = curr;\n\t\t\t\/\/ remove it from the list.\n\t\t\tprev->next = curr->next;\n\t\t\tdel->next = NULL;\n\t\t\tdelete del;\n\n\t\t\t\/\/ all done.\n\t\t\treturn;\n\t\t}\n\t\tcurr = curr->next;\n\t\tprev = prev->next;\n\t}\n\n\tbail_out:\n\t\/\/ I *must* have recorded my existence before erasing it, so if not, then\n\t\/\/ a programmer error has happened.\n\tEXCEPT(\"FileLock::erase_existence(): Programmer error. A FileLock to \"\n\t\t\t\"be erased was not found.\");\n}\n\n\nFileLockBase::FileLockEntry* FileLockBase::m_all_locks = NULL;\n\n\/\/\n\/\/ Methods for the \"real\" file lock class\n\/\/\nFileLock::FileLock( int fd, FILE *fp_arg, const char* path )\n\t\t: FileLockBase( )\n{\n\tReset( );\n\tm_fd = fd;\n\tm_fp = fp_arg;\n\n\t\/\/ check to ensure that if we have a real fd or fp_arg, the file is\n\t\/\/ defined. However, if the fd nor the fp_arg is defined, the file may be\n\t\/\/ NULL.\n\tif ((path == NULL && (fd >= 0 || fp_arg != NULL)))\n\t{\n\t\tEXCEPT(\"FileLock::FileLock(). You must supply a valid file argument \"\n\t\t\t\"with a valid fd or fp_arg\");\n\t}\n\n\t\/\/ path could be NULL if fd is -1 and fp is NULL, in which case we don't\n\t\/\/ insert ourselves into a the m_all_locks list.\n\tif (path) {\n\t\tm_path = strdup(path);\n\t\tupdateLockTimestamp();\n\t}\n}\n\nFileLock::FileLock( const char *path )\n\t\t: FileLockBase( )\n{\n\tReset( );\n\n\tASSERT(path != NULL);\n\n\tm_path = strdup(path);\n\tupdateLockTimestamp();\n}\n\nFileLock::~FileLock( void )\n{\n\tif( m_state != UN_LOCK ) {\n\t\trelease();\n\t}\n\tm_use_kernel_mutex = -1;\n#ifdef WIN32\n\tif (m_debug_win32_mutex) {\n\t\t::CloseHandle(m_debug_win32_mutex);\n\t\tm_debug_win32_mutex = NULL;\n\t}\n#endif\n\tif ( m_path) {\n\t\tfree(m_path);\n\t\tm_path = NULL;\n\t}\n}\n\nvoid\nFileLock::Reset( void )\n{\n\tm_fd = -1;\n\tm_fp = NULL;\n\tm_blocking = true;\n\tm_state = UN_LOCK;\n\tm_path = NULL;\n\tm_use_kernel_mutex = -1;\n#ifdef WIN32\n\tm_debug_win32_mutex = NULL;\n#endif\n}\n\nvoid\nFileLock::SetFdFpFile( int fd, FILE *fp, const char *file )\n{\n\t\/\/ if I'm -1, NULL, NULL, that's ok, however, if file != NULL, then\n\t\/\/ either the fd or the fp must also be valid.\n\tif ((file == NULL && (fd >= 0 || fp != NULL)))\n\t{\n\t\tEXCEPT(\"FileLock::SetFdFpFile(). You must supply a valid file argument \"\n\t\t\t\"with a valid fd or fp_arg\");\n\t}\n\n\tm_fd = fd;\n\tm_fp = fp;\n\n\t\/\/ Make sure we record our existence in the static list properly depending\n\t\/\/ on what the user is setting the variables to...\n\tif (m_path == NULL && file != NULL) {\n\t\t\/\/ moving from a NULL object to a object needed to update the timestamp\n\n\t\tm_path = strdup(file);\n\t\t\/\/ This will use the new lock file in m_path\n\t\tupdateLockTimestamp();\n\n\t} else if (m_path != NULL && file == NULL) {\n\t\t\/\/ moving from an updatable timestamped object to a NULL object\n\n\t\tfree(m_path);\n\t\tm_path = NULL;\n\n\t} else if (m_path != NULL && file != NULL) {\n\t\t\/\/ keeping the updatability of the object, but updating the path.\n\n\t\tfree(m_path);\n\t\tm_path = strdup(file);\n\t\tupdateLockTimestamp();\n\t}\n}\n\nvoid\nFileLock::display( void ) const\n{\n\tdprintf( D_FULLDEBUG, \"fd = %d\\n\", m_fd );\n\tdprintf( D_FULLDEBUG, \"blocking = %s\\n\", m_blocking ? \"TRUE\" : \"FALSE\" );\n\tdprintf( D_FULLDEBUG, \"state = %s\\n\", getStateString( m_state ) );\n}\n\nint\nFileLock::lockViaMutex(LOCK_TYPE type)\n{\n\t(void) type;\n\tint result = -1;\n\n#ifdef WIN32\t\/\/ only implemented on Win32 so far...\n\tchar * filename = NULL;\n\tint filename_len;\n\tchar *ptr = NULL;\n\tchar mutex_name[MAX_PATH];\n\n\n\t\t\/\/ If we made it here, we want to use a kernel mutex.\n\t\t\/\/\n\t\t\/\/ We use a kernel mutex by default to fix a major shortcoming\n\t\t\/\/ with using Win32 file locking: file locking on Win32 is\n\t\t\/\/ non-deterministic. Thus, we have observed processes\n\t\t\/\/ starving to get the lock. The Win32 mutex object,\n\t\t\/\/ on the other hand, is FIFO --- thus starvation is avoided.\n\n\t\t\/\/ first, open a handle to the mutex if we haven't already\n\tif ( m_debug_win32_mutex == NULL && m_path ) {\n\t\t\t\/\/ Create the mutex name based upon the lock file\n\t\t\t\/\/ specified in the config file. \t\t\t\t\n\t\tchar * filename = strdup(m_path);\n\t\tfilename_len = strlen(filename);\n\t\t\t\/\/ Note: Win32 will not allow backslashes in the name, \n\t\t\t\/\/ so get rid of em here.\n\t\tptr = strchr(filename,'\\\\');\n\t\twhile ( ptr ) {\n\t\t\t*ptr = '\/';\n\t\t\tptr = strchr(filename,'\\\\');\n\t\t}\n\t\t\t\/\/ The mutex name is case-sensitive, but the NTFS filesystem\n\t\t\t\/\/ is not. So to avoid user confusion, strlwr.\n\t\tstrlwr(filename);\n\t\t\t\/\/ Now, we pre-append \"Global\\\" to the name so that it\n\t\t\t\/\/ works properly on systems running Terminal Services\n\t\t_snprintf(mutex_name,MAX_PATH,\"Global\\\\%s\",filename);\n\t\tfree(filename);\n\t\tfilename = NULL;\n\t\t\t\/\/ Call CreateMutex - this will create the mutex if it does\n\t\t\t\/\/ not exist, or just open it if it already does. Note that\n\t\t\t\/\/ the handle to the mutex is automatically closed by the\n\t\t\t\/\/ operating system when the process exits, and the mutex\n\t\t\t\/\/ object is automatically destroyed when there are no more\n\t\t\t\/\/ handles... go win32 kernel! Thus, although we are not\n\t\t\t\/\/ explicitly closing any handles, nothing is being leaked.\n\t\t\t\/\/ Note: someday, to make BoundsChecker happy, we should\n\t\t\t\/\/ add a dprintf subsystem shutdown routine to nicely\n\t\t\t\/\/ deallocate this stuff instead of relying on the OS.\n\t\tm_debug_win32_mutex = ::CreateMutex(0,FALSE,mutex_name);\n\t}\n\n\t\t\/\/ now, if we have mutex, grab it or release it as needed\n\tif ( m_debug_win32_mutex ) {\n\t\tif ( type == UN_LOCK ) {\n\t\t\t\t\/\/ release mutex\n\t\t\tReleaseMutex(m_debug_win32_mutex);\n\t\t\tresult = 0;\t\/\/ 0 means success\n\t\t} else {\n\t\t\t\t\/\/ grab mutex\n\t\t\t\t\/\/ block 10 secs if do_block is false, else block forever\n\t\t\tresult = WaitForSingleObject(m_debug_win32_mutex, \n\t\t\t\tm_blocking ? INFINITE : 10 * 1000);\t\/\/ time in milliseconds\n\t\t\t\t\/\/ consider WAIT_ABANDONED as success so we do not EXCEPT\n\t\t\tif ( result==WAIT_OBJECT_0 || result==WAIT_ABANDONED ) {\n\t\t\t\tresult = 0;\n\t\t\t} else {\n\t\t\t\tresult = -1;\n\t\t\t}\n\t\t}\n\n\t}\n#endif\n\n\treturn result;\n}\n\n\nbool\nFileLock::obtain( LOCK_TYPE t )\n{\n\/\/ lock_file uses lseeks in order to lock the first 4 bytes of the file on NT\n\/\/ It DOES properly reset the lseek version of the file position, but that is\n\/\/ not the same (in some very inconsistent and weird ways) as the fseek one,\n\/\/ so if the user has given us a FILE *, we need to make sure we don't ruin\n\/\/ their current position. The lesson here is don't use fseeks and lseeks\n\/\/ interchangeably...\n\tint\t\tstatus = -1;\n\n\tif ( m_use_kernel_mutex == -1 ) {\n\t\tm_use_kernel_mutex = param_boolean_int(\"FILE_LOCK_VIA_MUTEX\", TRUE);\n\t}\n\n\t\t\/\/ If we have the path, we can try to lock via a mutex. \n\tif ( m_path && m_use_kernel_mutex ) {\n\t\tstatus = lockViaMutex(t);\n\t}\n\n\t\t\/\/ We cannot lock via a mutex, or we tried and failed.\n\t\t\/\/ Try via filesystem lock.\n\tif ( status < 0) {\n\t\tlong lPosBeforeLock = 0;\n\t\tif (m_fp) \/\/ if the user has a FILE * as well as an fd\n\t\t{\n\t\t\t\/\/ save their FILE*-based current position\n\t\t\tlPosBeforeLock = ftell(m_fp); \n\t\t}\n\t\t\n\t\t\t\/\/ We're seeing sporadic test suite failures where a daemon\n\t\t\t\/\/ takes more than 10 seconds to write to the user log.\n\t\t\t\/\/ This will help narrow down where the delay is coming from.\n\t\ttime_t before = time(NULL);\n\t\tstatus = lock_file( m_fd, t, m_blocking );\n\t\ttime_t after = time(NULL);\n\t\tif ( (after - before) > 5 ) {\n\t\t\tdprintf( D_FULLDEBUG, \"FileLock::obtain(%d): lock_file() took %d seconds\\n\",t);\n\t\t}\n\t\t\n\t\tif (m_fp)\n\t\t{\n\t\t\t\/\/ restore their FILE*-position\n\t\t\tfseek(m_fp, lPosBeforeLock, SEEK_SET); \t\n\t\t}\n\t}\n\n\tif( status == 0 ) {\n\t\tm_state = t;\n\t}\n\tif ( status != 0 ) {\n\t\tdprintf( D_ALWAYS, \"FileLock::obtain(%d) failed - errno %d (%s)\\n\",\n\t t, errno, strerror(errno) );\n\t}\n\telse {\n\t\tUtcTime\tnow( true );\n\t\tdprintf( D_FULLDEBUG,\n\t\t\t\t \"FileLock::obtain(%d) - @%.6f lock on %s now %s\\n\",\n\t\t\t\t t, now.combined(), m_path, getStateString(t) );\n\t}\n\treturn status == 0;\n}\n\nbool\nFileLock::release(void)\n{\n\treturn obtain( UN_LOCK );\n}\n\nvoid\nFileLock::updateLockTimestamp(void)\n{\n\tpriv_state p;\n\n\tif (m_path) {\n\n\t\tdprintf(D_FULLDEBUG, \"FileLock object is updating timestamp on: %s\\n\",\n\t\t\tm_path);\n\n\t\t\/\/ NOTE:\n\t\t\/\/ At the time of writing, if we try to update the lock and fail\n\t\t\/\/ because the lock is not owned by Condor, we ignore it and leave the\n\t\t\/\/ lock timestamp not updated and we don't even write a message about\n\t\t\/\/ it in the logs. This behaviour is warranted because the main reason\n\t\t\/\/ why this is here at all if to prevent Condor owned lock files from\n\t\t\/\/ being deleted by tmpwatch and other administrative programs.\n\t\t\/\/ According to Todd 07\/15\/2008, a new feature will shortly be going\n\t\t\/\/ into Condor which will make *ALL* file locking use separate lock\n\t\t\/\/ file elsewhere which will all be owned by Condor, in which case this\n\t\t\/\/ will work perfectly.\n\n\t\t\/\/ One of the main reasons why we just don't store the privledge state\n\t\t\/\/ of the process when this object is created is because the semantics\n\t\t\/\/ of this object have been that the caller is resposible for \n\t\t\/\/ maintaining the correct priv state when dealing with the lock\n\t\t\/\/ object. If we circumvent that by having the lock object alter\n\t\t\/\/ it privstate to match what it was constructed under, it will be \n\t\t\/\/ very surprising if the caller knows a file has changed ownership\n\t\t\/\/ or similar things.\n\n\t\tp = set_condor_priv();\n\n\t\t\/\/ set the updated atime and mtime for the file to now.\n\t\tif (utime(m_path, NULL) < 0) {\n\n\t\t\t\/\/ Only emit message if it isn't a permission problem....\n\t\t\tif (errno != EACCES && errno != EPERM) {\n\t\t\t\tdprintf(D_FULLDEBUG, \"FileLock::updateLockTime(): utime() \"\n\t\t\t\t\t\"failed %d(%s) on lock file %s. Not updating timestamp.\\n\",\n\t\t\t\t\terrno, strerror(errno), m_path);\n\t\t\t}\n\t\t}\n\t\tset_priv(p);\n\n\t\treturn;\n\t}\n}\n<commit_msg>Fixed a compiler warning.<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * 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#include \"condor_common.h\"\n#include \"condor_constants.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"condor_uid.h\"\n#include \"file_lock.h\"\n#include \"utc_time.h\"\n\nextern \"C\" int lock_file( int fd, LOCK_TYPE type, BOOLEAN do_block );\n\nFileLockBase::FileLockBase( void )\n{\n\tm_state = UN_LOCK;\n\tm_blocking = true;\n\trecordExistence();\n}\n\nFileLockBase::~FileLockBase(void)\n{\n\teraseExistence();\n}\n\nconst char *\nFileLockBase::getStateString( LOCK_TYPE state ) const\n{\n\tswitch( state ) {\n\tcase READ_LOCK:\n\t\treturn \"READ\";\n\tcase WRITE_LOCK:\n\t\treturn \"WRITE\";\n\tcase UN_LOCK:\n\t\treturn \"UNLOCKED\";\n\tdefault:\n\t\treturn \"UNKNOWN\";\n\t}\n}\n\nvoid\nFileLockBase::updateAllLockTimestamps(void)\n{\n\tFileLockEntry *fle = NULL;\n\n\tfle = m_all_locks;\n\n\t\/\/ walk the locks list and have each one update its timestamp\n\twhile(fle != NULL) {\n\t\tfle->fl->updateLockTimestamp();\n\t\tfle = fle->next;\n\t}\n}\n\nvoid \nFileLockBase::recordExistence(void)\n{\n\tFileLockEntry *fle = new FileLockEntry;\n\t\n\tfle->fl = this;\n\n\t\/\/ insert it at the head of the singly linked list\n\tfle->next = m_all_locks;\n\tm_all_locks = fle;\n}\n\nvoid \nFileLockBase::eraseExistence(void)\n{\n\t\/\/ do a little brother style removal in the singly linked list\n\n\tFileLockEntry *prev = NULL;\n\tFileLockEntry *curr = NULL;\n\tFileLockEntry *del = NULL;\n\n\tif (m_all_locks == NULL) {\n\t\tgoto bail_out;\n\t}\n\n\t\/\/ is it the first one?\n\tif (m_all_locks->fl == this) {\n\t\tdel = m_all_locks;\n\t\tm_all_locks = m_all_locks->next;\n\t\tdelete del;\n\t\treturn;\n\t}\n\n\t\/\/ if it is the second one or beyond, find it and delete the entry\n\t\/\/ from the list.\n\tprev = m_all_locks;\n\tcurr = m_all_locks->next;\n\n\twhile(curr != NULL) {\n\t\tif (curr->fl == this) {\n\t\t\t\/\/ found it, mark it for deletion.\n\t\t\tdel = curr;\n\t\t\t\/\/ remove it from the list.\n\t\t\tprev->next = curr->next;\n\t\t\tdel->next = NULL;\n\t\t\tdelete del;\n\n\t\t\t\/\/ all done.\n\t\t\treturn;\n\t\t}\n\t\tcurr = curr->next;\n\t\tprev = prev->next;\n\t}\n\n\tbail_out:\n\t\/\/ I *must* have recorded my existence before erasing it, so if not, then\n\t\/\/ a programmer error has happened.\n\tEXCEPT(\"FileLock::erase_existence(): Programmer error. A FileLock to \"\n\t\t\t\"be erased was not found.\");\n}\n\n\nFileLockBase::FileLockEntry* FileLockBase::m_all_locks = NULL;\n\n\/\/\n\/\/ Methods for the \"real\" file lock class\n\/\/\nFileLock::FileLock( int fd, FILE *fp_arg, const char* path )\n\t\t: FileLockBase( )\n{\n\tReset( );\n\tm_fd = fd;\n\tm_fp = fp_arg;\n\n\t\/\/ check to ensure that if we have a real fd or fp_arg, the file is\n\t\/\/ defined. However, if the fd nor the fp_arg is defined, the file may be\n\t\/\/ NULL.\n\tif ((path == NULL && (fd >= 0 || fp_arg != NULL)))\n\t{\n\t\tEXCEPT(\"FileLock::FileLock(). You must supply a valid file argument \"\n\t\t\t\"with a valid fd or fp_arg\");\n\t}\n\n\t\/\/ path could be NULL if fd is -1 and fp is NULL, in which case we don't\n\t\/\/ insert ourselves into a the m_all_locks list.\n\tif (path) {\n\t\tm_path = strdup(path);\n\t\tupdateLockTimestamp();\n\t}\n}\n\nFileLock::FileLock( const char *path )\n\t\t: FileLockBase( )\n{\n\tReset( );\n\n\tASSERT(path != NULL);\n\n\tm_path = strdup(path);\n\tupdateLockTimestamp();\n}\n\nFileLock::~FileLock( void )\n{\n\tif( m_state != UN_LOCK ) {\n\t\trelease();\n\t}\n\tm_use_kernel_mutex = -1;\n#ifdef WIN32\n\tif (m_debug_win32_mutex) {\n\t\t::CloseHandle(m_debug_win32_mutex);\n\t\tm_debug_win32_mutex = NULL;\n\t}\n#endif\n\tif ( m_path) {\n\t\tfree(m_path);\n\t\tm_path = NULL;\n\t}\n}\n\nvoid\nFileLock::Reset( void )\n{\n\tm_fd = -1;\n\tm_fp = NULL;\n\tm_blocking = true;\n\tm_state = UN_LOCK;\n\tm_path = NULL;\n\tm_use_kernel_mutex = -1;\n#ifdef WIN32\n\tm_debug_win32_mutex = NULL;\n#endif\n}\n\nvoid\nFileLock::SetFdFpFile( int fd, FILE *fp, const char *file )\n{\n\t\/\/ if I'm -1, NULL, NULL, that's ok, however, if file != NULL, then\n\t\/\/ either the fd or the fp must also be valid.\n\tif ((file == NULL && (fd >= 0 || fp != NULL)))\n\t{\n\t\tEXCEPT(\"FileLock::SetFdFpFile(). You must supply a valid file argument \"\n\t\t\t\"with a valid fd or fp_arg\");\n\t}\n\n\tm_fd = fd;\n\tm_fp = fp;\n\n\t\/\/ Make sure we record our existence in the static list properly depending\n\t\/\/ on what the user is setting the variables to...\n\tif (m_path == NULL && file != NULL) {\n\t\t\/\/ moving from a NULL object to a object needed to update the timestamp\n\n\t\tm_path = strdup(file);\n\t\t\/\/ This will use the new lock file in m_path\n\t\tupdateLockTimestamp();\n\n\t} else if (m_path != NULL && file == NULL) {\n\t\t\/\/ moving from an updatable timestamped object to a NULL object\n\n\t\tfree(m_path);\n\t\tm_path = NULL;\n\n\t} else if (m_path != NULL && file != NULL) {\n\t\t\/\/ keeping the updatability of the object, but updating the path.\n\n\t\tfree(m_path);\n\t\tm_path = strdup(file);\n\t\tupdateLockTimestamp();\n\t}\n}\n\nvoid\nFileLock::display( void ) const\n{\n\tdprintf( D_FULLDEBUG, \"fd = %d\\n\", m_fd );\n\tdprintf( D_FULLDEBUG, \"blocking = %s\\n\", m_blocking ? \"TRUE\" : \"FALSE\" );\n\tdprintf( D_FULLDEBUG, \"state = %s\\n\", getStateString( m_state ) );\n}\n\nint\nFileLock::lockViaMutex(LOCK_TYPE type)\n{\n\t(void) type;\n\tint result = -1;\n\n#ifdef WIN32\t\/\/ only implemented on Win32 so far...\n\tchar * filename = NULL;\n\tint filename_len;\n\tchar *ptr = NULL;\n\tchar mutex_name[MAX_PATH];\n\n\n\t\t\/\/ If we made it here, we want to use a kernel mutex.\n\t\t\/\/\n\t\t\/\/ We use a kernel mutex by default to fix a major shortcoming\n\t\t\/\/ with using Win32 file locking: file locking on Win32 is\n\t\t\/\/ non-deterministic. Thus, we have observed processes\n\t\t\/\/ starving to get the lock. The Win32 mutex object,\n\t\t\/\/ on the other hand, is FIFO --- thus starvation is avoided.\n\n\t\t\/\/ first, open a handle to the mutex if we haven't already\n\tif ( m_debug_win32_mutex == NULL && m_path ) {\n\t\t\t\/\/ Create the mutex name based upon the lock file\n\t\t\t\/\/ specified in the config file. \t\t\t\t\n\t\tchar * filename = strdup(m_path);\n\t\tfilename_len = strlen(filename);\n\t\t\t\/\/ Note: Win32 will not allow backslashes in the name, \n\t\t\t\/\/ so get rid of em here.\n\t\tptr = strchr(filename,'\\\\');\n\t\twhile ( ptr ) {\n\t\t\t*ptr = '\/';\n\t\t\tptr = strchr(filename,'\\\\');\n\t\t}\n\t\t\t\/\/ The mutex name is case-sensitive, but the NTFS filesystem\n\t\t\t\/\/ is not. So to avoid user confusion, strlwr.\n\t\tstrlwr(filename);\n\t\t\t\/\/ Now, we pre-append \"Global\\\" to the name so that it\n\t\t\t\/\/ works properly on systems running Terminal Services\n\t\t_snprintf(mutex_name,MAX_PATH,\"Global\\\\%s\",filename);\n\t\tfree(filename);\n\t\tfilename = NULL;\n\t\t\t\/\/ Call CreateMutex - this will create the mutex if it does\n\t\t\t\/\/ not exist, or just open it if it already does. Note that\n\t\t\t\/\/ the handle to the mutex is automatically closed by the\n\t\t\t\/\/ operating system when the process exits, and the mutex\n\t\t\t\/\/ object is automatically destroyed when there are no more\n\t\t\t\/\/ handles... go win32 kernel! Thus, although we are not\n\t\t\t\/\/ explicitly closing any handles, nothing is being leaked.\n\t\t\t\/\/ Note: someday, to make BoundsChecker happy, we should\n\t\t\t\/\/ add a dprintf subsystem shutdown routine to nicely\n\t\t\t\/\/ deallocate this stuff instead of relying on the OS.\n\t\tm_debug_win32_mutex = ::CreateMutex(0,FALSE,mutex_name);\n\t}\n\n\t\t\/\/ now, if we have mutex, grab it or release it as needed\n\tif ( m_debug_win32_mutex ) {\n\t\tif ( type == UN_LOCK ) {\n\t\t\t\t\/\/ release mutex\n\t\t\tReleaseMutex(m_debug_win32_mutex);\n\t\t\tresult = 0;\t\/\/ 0 means success\n\t\t} else {\n\t\t\t\t\/\/ grab mutex\n\t\t\t\t\/\/ block 10 secs if do_block is false, else block forever\n\t\t\tresult = WaitForSingleObject(m_debug_win32_mutex, \n\t\t\t\tm_blocking ? INFINITE : 10 * 1000);\t\/\/ time in milliseconds\n\t\t\t\t\/\/ consider WAIT_ABANDONED as success so we do not EXCEPT\n\t\t\tif ( result==WAIT_OBJECT_0 || result==WAIT_ABANDONED ) {\n\t\t\t\tresult = 0;\n\t\t\t} else {\n\t\t\t\tresult = -1;\n\t\t\t}\n\t\t}\n\n\t}\n#endif\n\n\treturn result;\n}\n\n\nbool\nFileLock::obtain( LOCK_TYPE t )\n{\n\/\/ lock_file uses lseeks in order to lock the first 4 bytes of the file on NT\n\/\/ It DOES properly reset the lseek version of the file position, but that is\n\/\/ not the same (in some very inconsistent and weird ways) as the fseek one,\n\/\/ so if the user has given us a FILE *, we need to make sure we don't ruin\n\/\/ their current position. The lesson here is don't use fseeks and lseeks\n\/\/ interchangeably...\n\tint\t\tstatus = -1;\n\n\tif ( m_use_kernel_mutex == -1 ) {\n\t\tm_use_kernel_mutex = param_boolean_int(\"FILE_LOCK_VIA_MUTEX\", TRUE);\n\t}\n\n\t\t\/\/ If we have the path, we can try to lock via a mutex. \n\tif ( m_path && m_use_kernel_mutex ) {\n\t\tstatus = lockViaMutex(t);\n\t}\n\n\t\t\/\/ We cannot lock via a mutex, or we tried and failed.\n\t\t\/\/ Try via filesystem lock.\n\tif ( status < 0) {\n\t\tlong lPosBeforeLock = 0;\n\t\tif (m_fp) \/\/ if the user has a FILE * as well as an fd\n\t\t{\n\t\t\t\/\/ save their FILE*-based current position\n\t\t\tlPosBeforeLock = ftell(m_fp); \n\t\t}\n\t\t\n\t\t\t\/\/ We're seeing sporadic test suite failures where a daemon\n\t\t\t\/\/ takes more than 10 seconds to write to the user log.\n\t\t\t\/\/ This will help narrow down where the delay is coming from.\n\t\ttime_t before = time(NULL);\n\t\tstatus = lock_file( m_fd, t, m_blocking );\n\t\ttime_t after = time(NULL);\n\t\tif ( (after - before) > 5 ) {\n\t\t\tdprintf( D_FULLDEBUG,\n\t\t\t\t\t \"FileLock::obtain(%d): lock_file() took %ld seconds\\n\",\n\t\t\t\t\t t, (after-before) );\n\t\t}\n\t\t\n\t\tif (m_fp)\n\t\t{\n\t\t\t\/\/ restore their FILE*-position\n\t\t\tfseek(m_fp, lPosBeforeLock, SEEK_SET); \t\n\t\t}\n\t}\n\n\tif( status == 0 ) {\n\t\tm_state = t;\n\t}\n\tif ( status != 0 ) {\n\t\tdprintf( D_ALWAYS, \"FileLock::obtain(%d) failed - errno %d (%s)\\n\",\n\t t, errno, strerror(errno) );\n\t}\n\telse {\n\t\tUtcTime\tnow( true );\n\t\tdprintf( D_FULLDEBUG,\n\t\t\t\t \"FileLock::obtain(%d) - @%.6f lock on %s now %s\\n\",\n\t\t\t\t t, now.combined(), m_path, getStateString(t) );\n\t}\n\treturn status == 0;\n}\n\nbool\nFileLock::release(void)\n{\n\treturn obtain( UN_LOCK );\n}\n\nvoid\nFileLock::updateLockTimestamp(void)\n{\n\tpriv_state p;\n\n\tif (m_path) {\n\n\t\tdprintf(D_FULLDEBUG, \"FileLock object is updating timestamp on: %s\\n\",\n\t\t\tm_path);\n\n\t\t\/\/ NOTE:\n\t\t\/\/ At the time of writing, if we try to update the lock and fail\n\t\t\/\/ because the lock is not owned by Condor, we ignore it and leave the\n\t\t\/\/ lock timestamp not updated and we don't even write a message about\n\t\t\/\/ it in the logs. This behaviour is warranted because the main reason\n\t\t\/\/ why this is here at all if to prevent Condor owned lock files from\n\t\t\/\/ being deleted by tmpwatch and other administrative programs.\n\t\t\/\/ According to Todd 07\/15\/2008, a new feature will shortly be going\n\t\t\/\/ into Condor which will make *ALL* file locking use separate lock\n\t\t\/\/ file elsewhere which will all be owned by Condor, in which case this\n\t\t\/\/ will work perfectly.\n\n\t\t\/\/ One of the main reasons why we just don't store the privledge state\n\t\t\/\/ of the process when this object is created is because the semantics\n\t\t\/\/ of this object have been that the caller is resposible for \n\t\t\/\/ maintaining the correct priv state when dealing with the lock\n\t\t\/\/ object. If we circumvent that by having the lock object alter\n\t\t\/\/ it privstate to match what it was constructed under, it will be \n\t\t\/\/ very surprising if the caller knows a file has changed ownership\n\t\t\/\/ or similar things.\n\n\t\tp = set_condor_priv();\n\n\t\t\/\/ set the updated atime and mtime for the file to now.\n\t\tif (utime(m_path, NULL) < 0) {\n\n\t\t\t\/\/ Only emit message if it isn't a permission problem....\n\t\t\tif (errno != EACCES && errno != EPERM) {\n\t\t\t\tdprintf(D_FULLDEBUG, \"FileLock::updateLockTime(): utime() \"\n\t\t\t\t\t\"failed %d(%s) on lock file %s. Not updating timestamp.\\n\",\n\t\t\t\t\terrno, strerror(errno), m_path);\n\t\t\t}\n\t\t}\n\t\tset_priv(p);\n\n\t\treturn;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"condor_classad.h\"\n#include \"HashTable.h\"\n#include \"hashkey.h\"\n#include \"sched.h\"\n#include \"condor_attributes.h\"\n\n#ifndef WIN32\n#include <netinet\/in.h>\n#endif\n\nextern \"C\" char * sin_to_string(struct sockaddr_in *);\n\ntemplate class HashTable<HashKey, ClassAd *>;\nextern void parseIpPort (char *, char *);\n\nvoid HashKey::sprint (char *s)\n{\n\tif (ip_addr[0])\n\t\tsprintf (s, \"< %s , %s >\", name, ip_addr);\n\telse\n\t\tsprintf (s, \"< %s >\", name);\n}\n\nbool operator== (const HashKey &lhs, const HashKey &rhs)\n{\n return (strcmp (lhs.name, rhs.name) == 0 &&\n\t\t\tstrcmp (lhs.ip_addr, rhs.ip_addr) == 0);\n}\n\nostream &operator<< (ostream &out, const HashKey &hk)\n{\n\tout << \"Hashkey: (\" << hk.name << \",\" << hk.ip_addr;\n\tout << \")\" << endl;\n\treturn out;\n}\n\nint hashFunction (const HashKey &key, int numBuckets)\n{\n unsigned int bkt = 0;\n int i;\n\n for (i = 0; key.name[i] ; bkt += key.name[i++]);\n for (i = 0; key.ip_addr[i]; bkt += key.ip_addr[i++]);\n\n bkt %= numBuckets;\n\n return bkt;\n}\n\nint hashOnName (const HashKey &key, int numBuckets)\n{\n\tunsigned int bkt = 0;\n\tint i;\n\n\tfor (i = 0; key.name [i]; bkt += key.name[i++]);\n\tbkt %= numBuckets;\n\n\treturn bkt;\n}\n\n\/\/ functions to make the hashkeys ...\n\/\/ make hashkeys from the obtained ad\nbool\nmakeStartdAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tExprTree *tree;\n\tchar buffer [30];\n\tchar buf2 [64];\n\tint inferred = 0;\n\n\t\/\/ get the name of the startd\n\tif (!(tree = ad->Lookup (\"Name\")))\n\t{\t\t\n\t\t\/\/ ... if name was not specified\n\t\tdprintf(D_FULLDEBUG,\"Warning: No 'Name' attribute; trying 'Machine'\\n\");\n\t\ttree = ad->Lookup (\"Machine\");\n\t}\n\n\tif (tree)\n\t{\n\t\tstrcpy (hk.name, ((String *)tree->RArg())->Value());\n\t}\n\telse\n\t{\n\t\t\/\/ neither Name nor Machine specified in ad\n\t\tdprintf (D_ALWAYS, \"Error: Neither 'Name' nor 'Machine' specified\\n\");\n\t\treturn false;\n\t}\n\t\n\t\/\/ get the IP and port of the startd \n\ttree = ad->Lookup (ATTR_STARTD_IP_ADDR);\n\t\n\t\/\/ if not there, try to lookup the old style \"STARTD_IP_ADDR\" string\n\tif (!tree) tree = ad->Lookup (\"STARTD_IP_ADDR\");\n\n\tif (tree)\n\t{\n\t\tstrcpy (buffer, ((String *)tree->RArg())->Value());\n\t}\n\telse\n\t{\n\t\tdprintf (D_FULLDEBUG,\"Warning: No STARTD_IP_ADDR; inferring address\\n\");\n\t\tstrcpy (buffer, sin_to_string (from));\t\n\n\t\tsprintf (buf2, \"%s = \\\"%s\\\"\", ATTR_STARTD_IP_ADDR, buffer);\n\t\tad->Insert (buf2);\n\t\tdprintf (D_FULLDEBUG, \"(Inferred address: %s)\\n\", buf2);\n\t\tinferred = 1;\n\t}\n\n\tparseIpPort (buffer, hk.ip_addr);\n\n\treturn true;\n}\n\n\nbool\nmakeScheddAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tExprTree *tree;\n\tchar buffer [30];\n\tchar buf2 [64];\n\tint inferred = 0;\n\n\t\/\/ get the name of the startd\n\tif (!(tree = ad->Lookup (\"Name\")))\n\t{\n\t\tdprintf(D_FULLDEBUG,\"Warning: No 'Name' attribute; trying 'Machine'\\n\");\n\t\t\/\/ ... if name was not specified\n\t\ttree = ad->Lookup (\"Machine\");\n\t}\n\n\tif (tree)\n\t{\n\t\tstrcpy (hk.name, ((String *)tree->RArg())->Value());\n\t}\n\telse\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: Neither 'Name' nor 'Machine' specified\\n\");\n\t\t\/\/ neither Name nor Machine specified\n\t\treturn false;\n\t}\n\t\n\t\/\/ get the IP and port of the startd \n\ttree = ad->Lookup (ATTR_SCHEDD_IP_ADDR);\n\t\n\tif (!tree)\n\t\ttree = ad->Lookup (\"SCHEDD_IP_ADDR\");\n\n\tif (tree)\n\t{\n\t\tstrcpy (buffer, ((String *)tree->RArg())->Value());\n\t}\n\telse\n\t{\n\t\tdprintf(D_FULLDEBUG,\"Warning: No SCHEDD_IP_ADDR; inferring address\\n\");\n\t\tstrcpy (buffer, sin_to_string (from));\n\n \/\/ since we have done the work ...\n sprintf (buf2, \"%s = \\\"%s\\\"\", ATTR_SCHEDD_IP_ADDR, buffer);\n\t\tad->Insert (buf2);\n\t\tdprintf (D_FULLDEBUG, \"(Inferred address: %s)\\n\", buf2);\n\t\tinferred = 1;\n\t}\n\n\tparseIpPort (buffer, hk.ip_addr);\n\n\treturn true;\n}\n\n\nbool\nmakeLicenseAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tExprTree *tree;\n\tchar buffer [30];\n\tchar buf2 [64];\n\tint inferred = 0;\n\n\t\/\/ get the name of the startd\n\tif (!(tree = ad->Lookup (\"Name\")))\n\t{\n\t\tdprintf(D_FULLDEBUG,\"Warning: No 'Name' attribute; trying 'Machine'\\n\");\n\t\t\/\/ ... if name was not specified\n\t\ttree = ad->Lookup (\"Machine\");\n\t}\n\n\tif (tree)\n\t{\n\t\tstrcpy (hk.name, ((String *)tree->RArg())->Value());\n\t}\n\telse\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: Neither 'Name' nor 'Machine' specified\\n\");\n\t\t\/\/ neither Name nor Machine specified\n\t\treturn false;\n\t}\n\t\n\t\/\/ get the IP and port of the startd \n\ttree = ad->Lookup (ATTR_MY_ADDRESS);\n\t\n\tif (tree)\n\t{\n\t\tstrcpy (buffer, ((String *)tree->RArg())->Value());\n\t}\n\telse\n\t{\n\t\tdprintf(D_FULLDEBUG,\"Warning: No MY_ADDRESS; inferring address\\n\");\n\t\tstrcpy (buffer, sin_to_string (from));\n\n \/\/ since we have done the work ...\n sprintf (buf2, \"%s = \\\"%s\\\"\", ATTR_MY_ADDRESS, buffer);\n\t\tad->Insert (buf2);\n\t\tdprintf (D_FULLDEBUG, \"(Inferred address: %s)\\n\", buf2);\n\t\tinferred = 1;\n\t}\n\n\tparseIpPort (buffer, hk.ip_addr);\n\n\treturn true;\n}\n\n\nbool\nmakeMasterAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tExprTree *tree;\n\n\tif (!(tree = ad->Lookup (\"Name\")))\n\t{\n\t\tdprintf( D_FULLDEBUG, \n\t\t\t\t \"Warning: No 'Name' attribute; trying 'Machine'\\n\" );\n\t\t\t\/\/ ... if name was not specified\n\t\ttree = ad->Lookup (\"Machine\");\n\t}\n\n\tif (tree)\n\t{\n\t\tstrcpy (hk.name, ((String *)tree->RArg())->Value ());\n\t}\n\telse\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: Neither 'Name' nor 'Machine' specified\\n\");\n\t\t\/\/ neither Name nor Machine specified\n\t\treturn false;\n\t}\n\n\t\/\/ ip_addr not necessary\n\thk.ip_addr [0] = '\\0';\n\n\treturn true;\n}\n\n\nbool\nmakeCkptSrvrAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tif (!ad->LookupString (\"Machine\", hk.name))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: No 'Machine' attribute\\n\");\n\t\treturn false;\n\t}\n\n\thk.ip_addr[0] = '\\0';\n\n\treturn true;\n}\n\nbool\nmakeCollectorAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tif (!ad->LookupString (\"Machine\", hk.name))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: No 'Machine' attribute\\n\");\n\t\treturn false;\n\t}\n\n\thk.ip_addr[0] = '\\0';\n\n\treturn true;\n}\n\nbool\nmakeStorageAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tif (!ad->LookupString (\"Name\", hk.name))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: No 'Name' attribute\\n\");\n\t\treturn false;\n\t}\n\n\thk.ip_addr[0] = '\\0';\n\n\treturn true;\n}\n\n\/\/ utility function: parse the string <aaa.bbb.ccc.ddd:pppp>\nvoid \nparseIpPort (char *ip_port_pair, char *ip_addr)\n{\n char *ip_port = ip_port_pair + 1;\n char *ip = ip_addr;\n while (*ip_port != ':')\n {\n *ip = *ip_port;\n ip++;\n ip_port++;\n }\n\n *ip = '\\0';\n\n\t\/\/ don't care about port number\n}\n\n\n<commit_msg>Updated to use new ClassAd unparsing<commit_after>\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"condor_classad.h\"\n#include \"HashTable.h\"\n#include \"hashkey.h\"\n#include \"sched.h\"\n#include \"condor_attributes.h\"\n\n#ifndef WIN32\n#include <netinet\/in.h>\n#endif\n\nextern \"C\" char * sin_to_string(struct sockaddr_in *);\n\ntemplate class HashTable<HashKey, ClassAd *>;\nextern void parseIpPort (char *, char *);\n\nvoid HashKey::sprint (char *s)\n{\n\tif (ip_addr[0])\n\t\tsprintf (s, \"< %s , %s >\", name, ip_addr);\n\telse\n\t\tsprintf (s, \"< %s >\", name);\n}\n\nbool operator== (const HashKey &lhs, const HashKey &rhs)\n{\n return (strcmp (lhs.name, rhs.name) == 0 &&\n\t\t\tstrcmp (lhs.ip_addr, rhs.ip_addr) == 0);\n}\n\nostream &operator<< (ostream &out, const HashKey &hk)\n{\n\tout << \"Hashkey: (\" << hk.name << \",\" << hk.ip_addr;\n\tout << \")\" << endl;\n\treturn out;\n}\n\nint hashFunction (const HashKey &key, int numBuckets)\n{\n unsigned int bkt = 0;\n int i;\n\n for (i = 0; key.name[i] ; bkt += key.name[i++]);\n for (i = 0; key.ip_addr[i]; bkt += key.ip_addr[i++]);\n\n bkt %= numBuckets;\n\n return bkt;\n}\n\nint hashOnName (const HashKey &key, int numBuckets)\n{\n\tunsigned int bkt = 0;\n\tint i;\n\n\tfor (i = 0; key.name [i]; bkt += key.name[i++]);\n\tbkt %= numBuckets;\n\n\treturn bkt;\n}\n\n\/\/ functions to make the hashkeys ...\n\/\/ make hashkeys from the obtained ad\nbool\nmakeStartdAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tExprTree *tree;\n\tchar buffer [30];\n\tchar buf2 [64];\n\tint inferred = 0;\n\tClassAdUnParser unp;\n\tstring buffString;\n\n\t\/\/ get the name of the startd\n\tif (!(tree = ad->Lookup (\"Name\")))\n\t{\t\t\n\t\t\/\/ ... if name was not specified\n\t\tdprintf(D_FULLDEBUG,\"Warning: No 'Name' attribute; trying 'Machine'\\n\");\n\t\ttree = ad->Lookup (\"Machine\");\n\t}\n\n\tif (tree)\n\t{\n\t\tunp.Unparse( buffString, tree );\n\/\/\t\tstrcpy (hk.name, ((String *)tree->RArg())->Value());\n\t\tstrcpy (hk.name, buffString.c_str( ) );\n\t\tbuffString = \"\";\n\t}\n\telse\n\t{\n\t\t\/\/ neither Name nor Machine specified in ad\n\t\tdprintf (D_ALWAYS, \"Error: Neither 'Name' nor 'Machine' specified\\n\");\n\t\treturn false;\n\t}\n\t\n\t\/\/ get the IP and port of the startd \n\ttree = ad->Lookup (ATTR_STARTD_IP_ADDR);\n\t\n\t\/\/ if not there, try to lookup the old style \"STARTD_IP_ADDR\" string\n\tif (!tree) tree = ad->Lookup (\"STARTD_IP_ADDR\");\n\n\tif (tree)\n\t{\n\t\tunp.Unparse( buffString, tree );\n\/\/\t\tstrcpy (buffer, ((String *)tree->RArg())->Value());\n\t\tstrcpy (buffer, buffString.c_str( ) );\n\t\tbuffString = \"\";\n\t}\n\telse\n\t{\n\t\tdprintf (D_FULLDEBUG,\"Warning: No STARTD_IP_ADDR; inferring address\\n\");\n\t\tstrcpy (buffer, sin_to_string (from));\t\n\n\t\tsprintf (buf2, \"%s = \\\"%s\\\"\", ATTR_STARTD_IP_ADDR, buffer);\n\t\tad->Insert (buf2);\n\t\tdprintf (D_FULLDEBUG, \"(Inferred address: %s)\\n\", buf2);\n\t\tinferred = 1;\n\t}\n\n\tparseIpPort (buffer, hk.ip_addr);\n\n\treturn true;\n}\n\n\nbool\nmakeScheddAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tExprTree *tree;\n\tchar buffer [30];\n\tchar buf2 [64];\n\tint inferred = 0;\n\tClassAdUnParser unp;\n\tstring buffString;\n\n\t\/\/ get the name of the startd\n\tif (!(tree = ad->Lookup (\"Name\")))\n\t{\n\t\tdprintf(D_FULLDEBUG,\"Warning: No 'Name' attribute; trying 'Machine'\\n\");\n\t\t\/\/ ... if name was not specified\n\t\ttree = ad->Lookup (\"Machine\");\n\t}\n\n\tif (tree)\n\t{\n\t\tunp.Unparse( buffString, tree );\n\/\/\t\tstrcpy (hk.name, ((String *)tree->RArg())->Value());\n\t\tstrcpy (hk.name, buffString.c_str( ) );\n\t\tbuffString = \"\";\n\t}\n\telse\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: Neither 'Name' nor 'Machine' specified\\n\");\n\t\t\/\/ neither Name nor Machine specified\n\t\treturn false;\n\t}\n\t\n\t\/\/ get the IP and port of the startd \n\ttree = ad->Lookup (ATTR_SCHEDD_IP_ADDR);\n\t\n\tif (!tree)\n\t\ttree = ad->Lookup (\"SCHEDD_IP_ADDR\");\n\n\tif (tree)\n\t{\n\t\tunp.Unparse( buffString, tree );\n\/\/\t\tstrcpy (buffer, ((String *)tree->RArg())->Value());\n\t\tstrcpy (buffer, buffString.c_str( ) );\n\t\tbuffString = \"\";\n\t}\n\telse\n\t{\n\t\tdprintf(D_FULLDEBUG,\"Warning: No SCHEDD_IP_ADDR; inferring address\\n\");\n\t\tstrcpy (buffer, sin_to_string (from));\n\n \/\/ since we have done the work ...\n sprintf (buf2, \"%s = \\\"%s\\\"\", ATTR_SCHEDD_IP_ADDR, buffer);\n\t\tad->Insert (buf2);\n\t\tdprintf (D_FULLDEBUG, \"(Inferred address: %s)\\n\", buf2);\n\t\tinferred = 1;\n\t}\n\n\tparseIpPort (buffer, hk.ip_addr);\n\n\treturn true;\n}\n\n\nbool\nmakeLicenseAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tExprTree *tree;\n\tchar buffer [30];\n\tchar buf2 [64];\n\tint inferred = 0;\n\tClassAdUnParser unp;\n\tstring buffString;\n\n\t\/\/ get the name of the startd\n\tif (!(tree = ad->Lookup (\"Name\")))\n\t{\n\t\tdprintf(D_FULLDEBUG,\"Warning: No 'Name' attribute; trying 'Machine'\\n\");\n\t\t\/\/ ... if name was not specified\n\t\ttree = ad->Lookup (\"Machine\");\n\t}\n\n\tif (tree)\n\t{\n\t\tunp.Unparse( buffString, tree );\n\/\/\t\tstrcpy (hk.name, ((String *)tree->RArg())->Value());\n\t\tstrcpy (hk.name, buffString.c_str( ) );\n\t\tbuffString = \"\";\n\t}\n\telse\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: Neither 'Name' nor 'Machine' specified\\n\");\n\t\t\/\/ neither Name nor Machine specified\n\t\treturn false;\n\t}\n\t\n\t\/\/ get the IP and port of the startd \n\ttree = ad->Lookup (ATTR_MY_ADDRESS);\n\t\n\tif (tree)\n\t{\n\t\tunp.Unparse( buffString, tree );\n\/\/\t\tstrcpy (buffer, ((String *)tree->RArg())->Value());\n\t\tstrcpy (buffer, buffString.c_str( ) );\n\t\tbuffString = \"\";\n\t}\n\telse\n\t{\n\t\tdprintf(D_FULLDEBUG,\"Warning: No MY_ADDRESS; inferring address\\n\");\n\t\tstrcpy (buffer, sin_to_string (from));\n\n \/\/ since we have done the work ...\n sprintf (buf2, \"%s = \\\"%s\\\"\", ATTR_MY_ADDRESS, buffer);\n\t\tad->Insert (buf2);\n\t\tdprintf (D_FULLDEBUG, \"(Inferred address: %s)\\n\", buf2);\n\t\tinferred = 1;\n\t}\n\n\tparseIpPort (buffer, hk.ip_addr);\n\n\treturn true;\n}\n\n\nbool\nmakeMasterAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tExprTree *tree;\n\tClassAdUnParser unp;\n\tstring buffString;\n\n\tif (!(tree = ad->Lookup (\"Name\")))\n\t{\n\t\tdprintf( D_FULLDEBUG, \n\t\t\t\t \"Warning: No 'Name' attribute; trying 'Machine'\\n\" );\n\t\t\t\/\/ ... if name was not specified\n\t\ttree = ad->Lookup (\"Machine\");\n\t}\n\n\tif (tree)\n\t{\n\t\tunp.Unparse( buffString, tree );\n\/\/\t\tstrcpy (hk.name, ((String *)tree->RArg())->Value ());\n\t\tstrcpy (hk.name, buffString.c_str( ) );\n\t\tbuffString = \"\";\n\t}\n\telse\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: Neither 'Name' nor 'Machine' specified\\n\");\n\t\t\/\/ neither Name nor Machine specified\n\t\treturn false;\n\t}\n\n\t\/\/ ip_addr not necessary\n\thk.ip_addr [0] = '\\0';\n\n\treturn true;\n}\n\n\nbool\nmakeCkptSrvrAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tif (!ad->LookupString (\"Machine\", hk.name))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: No 'Machine' attribute\\n\");\n\t\treturn false;\n\t}\n\n\thk.ip_addr[0] = '\\0';\n\n\treturn true;\n}\n\nbool\nmakeCollectorAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tif (!ad->LookupString (\"Machine\", hk.name))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: No 'Machine' attribute\\n\");\n\t\treturn false;\n\t}\n\n\thk.ip_addr[0] = '\\0';\n\n\treturn true;\n}\n\nbool\nmakeStorageAdHashKey (HashKey &hk, ClassAd *ad, sockaddr_in *from)\n{\n\tif (!ad->LookupString (\"Name\", hk.name))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error: No 'Name' attribute\\n\");\n\t\treturn false;\n\t}\n\n\thk.ip_addr[0] = '\\0';\n\n\treturn true;\n}\n\n\/\/ utility function: parse the string <aaa.bbb.ccc.ddd:pppp>\nvoid \nparseIpPort (char *ip_port_pair, char *ip_addr)\n{\n char *ip_port = ip_port_pair + 1;\n char *ip = ip_addr;\n while (*ip_port != ':')\n {\n *ip = *ip_port;\n ip++;\n ip_port++;\n }\n\n *ip = '\\0';\n\n\t\/\/ don't care about port number\n}\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix a crash in QSystemLocalePrivate::uiLanguages().<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood\n * Copyright (c) 2009 Advanced Micro Devices, Inc.\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\n#include \"cpu\/testers\/rubytest\/Check.hh\"\n#include \"mem\/ruby\/common\/SubBlock.hh\"\n#include \"mem\/ruby\/system\/Sequencer.hh\"\n#include \"mem\/ruby\/system\/System.hh\"\n\ntypedef RubyTester::SenderState SenderState;\n\nCheck::Check(const Address& address, const Address& pc,\n int _num_cpu_sequencers, RubyTester* _tester)\n : m_num_cpu_sequencers(_num_cpu_sequencers), m_tester_ptr(_tester)\n{\n m_status = TesterStatus_Idle;\n\n pickValue();\n pickInitiatingNode();\n changeAddress(address);\n m_pc = pc;\n m_access_mode = RubyAccessMode(random() % RubyAccessMode_NUM);\n m_store_count = 0;\n}\n\nvoid\nCheck::initiate()\n{\n DPRINTF(RubyTest, \"initiating\\n\");\n debugPrint();\n\n \/\/ currently no protocols support prefetches\n if (false && (random() & 0xf) == 0) {\n initiatePrefetch(); \/\/ Prefetch from random processor\n }\n\n if (m_tester_ptr->getCheckFlush() && (random() & 0xff) == 0) {\n initiateFlush(); \/\/ issue a Flush request from random processor\n }\n\n if (m_status == TesterStatus_Idle) {\n initiateAction();\n } else if (m_status == TesterStatus_Ready) {\n initiateCheck();\n } else {\n \/\/ Pending - do nothing\n DPRINTF(RubyTest,\n \"initiating action\/check - failed: action\/check is pending\\n\");\n }\n}\n\nvoid\nCheck::initiatePrefetch()\n{\n DPRINTF(RubyTest, \"initiating prefetch\\n\");\n\n int index = random() % m_num_cpu_sequencers;\n RubyTester::CpuPort* port =\n safe_cast<RubyTester::CpuPort*>(m_tester_ptr->getCpuPort(index));\n\n Request::Flags flags;\n flags.set(Request::PREFETCH);\n\n Packet::Command cmd;\n\n \/\/ 1 in 8 chance this will be an exclusive prefetch\n if ((random() & 0x7) != 0) {\n cmd = MemCmd::ReadReq;\n\n \/\/ 50% chance that the request will be an instruction fetch\n if ((random() & 0x1) == 0) {\n flags.set(Request::INST_FETCH);\n }\n } else {\n cmd = MemCmd::WriteReq;\n flags.set(Request::PF_EXCLUSIVE);\n }\n\n \/\/ Prefetches are assumed to be 0 sized\n Request *req = new Request(m_address.getAddress(), 0, flags, curTick(),\n m_pc.getAddress());\n\n PacketPtr pkt = new Packet(req, cmd, port->idx);\n\n \/\/ push the subblock onto the sender state. The sequencer will\n \/\/ update the subblock on the return\n pkt->senderState =\n new SenderState(m_address, req->getSize(), pkt->senderState);\n\n if (port->sendTiming(pkt)) {\n DPRINTF(RubyTest, \"successfully initiated prefetch.\\n\");\n } else {\n \/\/ If the packet did not issue, must delete\n SenderState* senderState = safe_cast<SenderState*>(pkt->senderState);\n pkt->senderState = senderState->saved;\n delete senderState;\n delete pkt->req;\n delete pkt;\n\n DPRINTF(RubyTest,\n \"prefetch initiation failed because Port was busy.\\n\");\n }\n}\n\nvoid\nCheck::initiateFlush()\n{\n\n DPRINTF(RubyTest, \"initiating Flush\\n\");\n\n int index = random() % m_num_cpu_sequencers;\n RubyTester::CpuPort* port =\n safe_cast<RubyTester::CpuPort*>(m_tester_ptr->getCpuPort(index));\n\n Request::Flags flags;\n\n Request *req = new Request(m_address.getAddress(), CHECK_SIZE, flags, curTick(),\n m_pc.getAddress());\n\n Packet::Command cmd;\n\n cmd = MemCmd::FlushReq;\n\n PacketPtr pkt = new Packet(req, cmd, port->idx);\n\n \/\/ push the subblock onto the sender state. The sequencer will\n \/\/ update the subblock on the return\n pkt->senderState =\n new SenderState(m_address, req->getSize(), pkt->senderState);\n\n if (port->sendTiming(pkt)) {\n DPRINTF(RubyTest, \"initiating Flush - successful\\n\");\n }\n}\n\nvoid\nCheck::initiateAction()\n{\n DPRINTF(RubyTest, \"initiating Action\\n\");\n assert(m_status == TesterStatus_Idle);\n\n int index = random() % m_num_cpu_sequencers;\n RubyTester::CpuPort* port =\n safe_cast<RubyTester::CpuPort*>(m_tester_ptr->getCpuPort(index));\n\n Request::Flags flags;\n\n \/\/ Create the particular address for the next byte to be written\n Address writeAddr(m_address.getAddress() + m_store_count);\n\n \/\/ Stores are assumed to be 1 byte-sized\n Request *req = new Request(writeAddr.getAddress(), 1, flags, curTick(),\n m_pc.getAddress());\n\n Packet::Command cmd;\n\n \/\/ 1 out of 8 chance, issue an atomic rather than a write\n \/\/ if ((random() & 0x7) == 0) {\n \/\/ cmd = MemCmd::SwapReq;\n \/\/ } else {\n cmd = MemCmd::WriteReq;\n \/\/ }\n\n PacketPtr pkt = new Packet(req, cmd, port->idx);\n uint8_t* writeData = new uint8_t;\n *writeData = m_value + m_store_count;\n pkt->dataDynamic(writeData);\n\n DPRINTF(RubyTest, \"data 0x%x check 0x%x\\n\",\n *(pkt->getPtr<uint8_t>()), *writeData);\n\n \/\/ push the subblock onto the sender state. The sequencer will\n \/\/ update the subblock on the return\n pkt->senderState =\n new SenderState(writeAddr, req->getSize(), pkt->senderState);\n\n if (port->sendTiming(pkt)) {\n DPRINTF(RubyTest, \"initiating action - successful\\n\");\n DPRINTF(RubyTest, \"status before action update: %s\\n\",\n (TesterStatus_to_string(m_status)).c_str());\n m_status = TesterStatus_Action_Pending;\n } else {\n \/\/ If the packet did not issue, must delete\n \/\/ Note: No need to delete the data, the packet destructor\n \/\/ will delete it\n SenderState* senderState = safe_cast<SenderState*>(pkt->senderState);\n pkt->senderState = senderState->saved;\n delete senderState;\n delete pkt->req;\n delete pkt;\n\n DPRINTF(RubyTest, \"failed to initiate action - sequencer not ready\\n\");\n }\n\n DPRINTF(RubyTest, \"status after action update: %s\\n\",\n (TesterStatus_to_string(m_status)).c_str());\n}\n\nvoid\nCheck::initiateCheck()\n{\n DPRINTF(RubyTest, \"Initiating Check\\n\");\n assert(m_status == TesterStatus_Ready);\n\n int index = random() % m_num_cpu_sequencers;\n RubyTester::CpuPort* port =\n safe_cast<RubyTester::CpuPort*>(m_tester_ptr->getCpuPort(index));\n\n Request::Flags flags;\n\n \/\/ 50% chance that the request will be an instruction fetch\n if ((random() & 0x1) == 0) {\n flags.set(Request::INST_FETCH);\n }\n\n \/\/ Checks are sized depending on the number of bytes written\n Request *req = new Request(m_address.getAddress(), CHECK_SIZE, flags,\n curTick(), m_pc.getAddress());\n\n PacketPtr pkt = new Packet(req, MemCmd::ReadReq, port->idx);\n uint8_t* dataArray = new uint8_t[CHECK_SIZE];\n pkt->dataDynamicArray(dataArray);\n\n \/\/ push the subblock onto the sender state. The sequencer will\n \/\/ update the subblock on the return\n pkt->senderState =\n new SenderState(m_address, req->getSize(), pkt->senderState);\n\n if (port->sendTiming(pkt)) {\n DPRINTF(RubyTest, \"initiating check - successful\\n\");\n DPRINTF(RubyTest, \"status before check update: %s\\n\",\n TesterStatus_to_string(m_status).c_str());\n m_status = TesterStatus_Check_Pending;\n } else {\n \/\/ If the packet did not issue, must delete\n \/\/ Note: No need to delete the data, the packet destructor\n \/\/ will delete it\n SenderState* senderState = safe_cast<SenderState*>(pkt->senderState);\n pkt->senderState = senderState->saved;\n delete senderState;\n delete pkt->req;\n delete pkt;\n\n DPRINTF(RubyTest, \"failed to initiate check - cpu port not ready\\n\");\n }\n\n DPRINTF(RubyTest, \"status after check update: %s\\n\",\n TesterStatus_to_string(m_status).c_str());\n}\n\nvoid\nCheck::performCallback(NodeID proc, SubBlock* data)\n{\n Address address = data->getAddress();\n\n \/\/ This isn't exactly right since we now have multi-byte checks\n \/\/ assert(getAddress() == address);\n\n assert(getAddress().getLineAddress() == address.getLineAddress());\n assert(data != NULL);\n\n DPRINTF(RubyTest, \"RubyTester Callback\\n\");\n debugPrint();\n\n if (m_status == TesterStatus_Action_Pending) {\n DPRINTF(RubyTest, \"Action callback write value: %d, currently %d\\n\",\n (m_value + m_store_count), data->getByte(0));\n \/\/ Perform store one byte at a time\n data->setByte(0, (m_value + m_store_count));\n m_store_count++;\n if (m_store_count == CHECK_SIZE) {\n m_status = TesterStatus_Ready;\n } else {\n m_status = TesterStatus_Idle;\n }\n DPRINTF(RubyTest, \"Action callback return data now %d\\n\",\n data->getByte(0));\n } else if (m_status == TesterStatus_Check_Pending) {\n DPRINTF(RubyTest, \"Check callback\\n\");\n \/\/ Perform load\/check\n for (int byte_number=0; byte_number<CHECK_SIZE; byte_number++) {\n if (uint8(m_value + byte_number) != data->getByte(byte_number)) {\n panic(\"Action\/check failure: proc: %d address: %s data: %s \"\n \"byte_number: %d m_value+byte_number: %d byte: %d %s\"\n \"Time: %d\\n\",\n proc, address, data, byte_number,\n (int)m_value + byte_number,\n (int)data->getByte(byte_number), *this,\n g_eventQueue_ptr->getTime());\n }\n }\n DPRINTF(RubyTest, \"Action\/check success\\n\");\n debugPrint();\n\n \/\/ successful check complete, increment complete\n m_tester_ptr->incrementCheckCompletions();\n\n m_status = TesterStatus_Idle;\n pickValue();\n\n } else {\n panic(\"Unexpected TesterStatus: %s proc: %d data: %s m_status: %s \"\n \"time: %d\\n\",\n *this, proc, data, m_status, g_eventQueue_ptr->getTime());\n }\n\n DPRINTF(RubyTest, \"proc: %d, Address: 0x%x\\n\", proc,\n getAddress().getLineAddress());\n DPRINTF(RubyTest, \"Callback done\\n\");\n debugPrint();\n}\n\nvoid\nCheck::changeAddress(const Address& address)\n{\n assert(m_status == TesterStatus_Idle || m_status == TesterStatus_Ready);\n m_status = TesterStatus_Idle;\n m_address = address;\n m_store_count = 0;\n}\n\nvoid\nCheck::pickValue()\n{\n assert(m_status == TesterStatus_Idle);\n m_status = TesterStatus_Idle;\n m_value = random() & 0xff; \/\/ One byte\n m_store_count = 0;\n}\n\nvoid\nCheck::pickInitiatingNode()\n{\n assert(m_status == TesterStatus_Idle || m_status == TesterStatus_Ready);\n m_status = TesterStatus_Idle;\n m_initiatingNode = (random() % m_num_cpu_sequencers);\n DPRINTF(RubyTest, \"picked initiating node %d\\n\", m_initiatingNode);\n m_store_count = 0;\n}\n\nvoid\nCheck::print(std::ostream& out) const\n{\n out << \"[\"\n << m_address << \", value: \"\n << (int)m_value << \", status: \"\n << m_status << \", initiating node: \"\n << m_initiatingNode << \", store_count: \"\n << m_store_count\n << \"]\" << std::flush;\n}\n\nvoid\nCheck::debugPrint()\n{\n DPRINTF(RubyTest,\n \"[%#x, value: %d, status: %s, initiating node: %d, store_count: %d]\\n\",\n m_address.getAddress(), (int)m_value,\n TesterStatus_to_string(m_status).c_str(),\n m_initiatingNode, m_store_count);\n}\n<commit_msg>Ruby: have the rubytester pass contextId to Ruby.<commit_after>\/*\n * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood\n * Copyright (c) 2009 Advanced Micro Devices, Inc.\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\n#include \"cpu\/testers\/rubytest\/Check.hh\"\n#include \"mem\/ruby\/common\/SubBlock.hh\"\n#include \"mem\/ruby\/system\/Sequencer.hh\"\n#include \"mem\/ruby\/system\/System.hh\"\n\ntypedef RubyTester::SenderState SenderState;\n\nCheck::Check(const Address& address, const Address& pc,\n int _num_cpu_sequencers, RubyTester* _tester)\n : m_num_cpu_sequencers(_num_cpu_sequencers), m_tester_ptr(_tester)\n{\n m_status = TesterStatus_Idle;\n\n pickValue();\n pickInitiatingNode();\n changeAddress(address);\n m_pc = pc;\n m_access_mode = RubyAccessMode(random() % RubyAccessMode_NUM);\n m_store_count = 0;\n}\n\nvoid\nCheck::initiate()\n{\n DPRINTF(RubyTest, \"initiating\\n\");\n debugPrint();\n\n \/\/ currently no protocols support prefetches\n if (false && (random() & 0xf) == 0) {\n initiatePrefetch(); \/\/ Prefetch from random processor\n }\n\n if (m_tester_ptr->getCheckFlush() && (random() & 0xff) == 0) {\n initiateFlush(); \/\/ issue a Flush request from random processor\n }\n\n if (m_status == TesterStatus_Idle) {\n initiateAction();\n } else if (m_status == TesterStatus_Ready) {\n initiateCheck();\n } else {\n \/\/ Pending - do nothing\n DPRINTF(RubyTest,\n \"initiating action\/check - failed: action\/check is pending\\n\");\n }\n}\n\nvoid\nCheck::initiatePrefetch()\n{\n DPRINTF(RubyTest, \"initiating prefetch\\n\");\n\n int index = random() % m_num_cpu_sequencers;\n RubyTester::CpuPort* port =\n safe_cast<RubyTester::CpuPort*>(m_tester_ptr->getCpuPort(index));\n\n Request::Flags flags;\n flags.set(Request::PREFETCH);\n\n Packet::Command cmd;\n\n \/\/ 1 in 8 chance this will be an exclusive prefetch\n if ((random() & 0x7) != 0) {\n cmd = MemCmd::ReadReq;\n\n \/\/ 50% chance that the request will be an instruction fetch\n if ((random() & 0x1) == 0) {\n flags.set(Request::INST_FETCH);\n }\n } else {\n cmd = MemCmd::WriteReq;\n flags.set(Request::PF_EXCLUSIVE);\n }\n\n \/\/ Prefetches are assumed to be 0 sized\n Request *req = new Request(m_address.getAddress(), 0, flags, curTick(),\n m_pc.getAddress());\n req->setThreadContext(index, 0);\n\n PacketPtr pkt = new Packet(req, cmd, port->idx);\n\n \/\/ push the subblock onto the sender state. The sequencer will\n \/\/ update the subblock on the return\n pkt->senderState =\n new SenderState(m_address, req->getSize(), pkt->senderState);\n\n if (port->sendTiming(pkt)) {\n DPRINTF(RubyTest, \"successfully initiated prefetch.\\n\");\n } else {\n \/\/ If the packet did not issue, must delete\n SenderState* senderState = safe_cast<SenderState*>(pkt->senderState);\n pkt->senderState = senderState->saved;\n delete senderState;\n delete pkt->req;\n delete pkt;\n\n DPRINTF(RubyTest,\n \"prefetch initiation failed because Port was busy.\\n\");\n }\n}\n\nvoid\nCheck::initiateFlush()\n{\n\n DPRINTF(RubyTest, \"initiating Flush\\n\");\n\n int index = random() % m_num_cpu_sequencers;\n RubyTester::CpuPort* port =\n safe_cast<RubyTester::CpuPort*>(m_tester_ptr->getCpuPort(index));\n\n Request::Flags flags;\n\n Request *req = new Request(m_address.getAddress(), CHECK_SIZE, flags, curTick(),\n m_pc.getAddress());\n\n Packet::Command cmd;\n\n cmd = MemCmd::FlushReq;\n\n PacketPtr pkt = new Packet(req, cmd, port->idx);\n\n \/\/ push the subblock onto the sender state. The sequencer will\n \/\/ update the subblock on the return\n pkt->senderState =\n new SenderState(m_address, req->getSize(), pkt->senderState);\n\n if (port->sendTiming(pkt)) {\n DPRINTF(RubyTest, \"initiating Flush - successful\\n\");\n }\n}\n\nvoid\nCheck::initiateAction()\n{\n DPRINTF(RubyTest, \"initiating Action\\n\");\n assert(m_status == TesterStatus_Idle);\n\n int index = random() % m_num_cpu_sequencers;\n RubyTester::CpuPort* port =\n safe_cast<RubyTester::CpuPort*>(m_tester_ptr->getCpuPort(index));\n\n Request::Flags flags;\n\n \/\/ Create the particular address for the next byte to be written\n Address writeAddr(m_address.getAddress() + m_store_count);\n\n \/\/ Stores are assumed to be 1 byte-sized\n Request *req = new Request(writeAddr.getAddress(), 1, flags, curTick(),\n m_pc.getAddress());\n\n req->setThreadContext(index, 0);\n Packet::Command cmd;\n\n \/\/ 1 out of 8 chance, issue an atomic rather than a write\n \/\/ if ((random() & 0x7) == 0) {\n \/\/ cmd = MemCmd::SwapReq;\n \/\/ } else {\n cmd = MemCmd::WriteReq;\n \/\/ }\n\n PacketPtr pkt = new Packet(req, cmd, port->idx);\n uint8_t* writeData = new uint8_t;\n *writeData = m_value + m_store_count;\n pkt->dataDynamic(writeData);\n\n DPRINTF(RubyTest, \"data 0x%x check 0x%x\\n\",\n *(pkt->getPtr<uint8_t>()), *writeData);\n\n \/\/ push the subblock onto the sender state. The sequencer will\n \/\/ update the subblock on the return\n pkt->senderState =\n new SenderState(writeAddr, req->getSize(), pkt->senderState);\n\n if (port->sendTiming(pkt)) {\n DPRINTF(RubyTest, \"initiating action - successful\\n\");\n DPRINTF(RubyTest, \"status before action update: %s\\n\",\n (TesterStatus_to_string(m_status)).c_str());\n m_status = TesterStatus_Action_Pending;\n } else {\n \/\/ If the packet did not issue, must delete\n \/\/ Note: No need to delete the data, the packet destructor\n \/\/ will delete it\n SenderState* senderState = safe_cast<SenderState*>(pkt->senderState);\n pkt->senderState = senderState->saved;\n delete senderState;\n delete pkt->req;\n delete pkt;\n\n DPRINTF(RubyTest, \"failed to initiate action - sequencer not ready\\n\");\n }\n\n DPRINTF(RubyTest, \"status after action update: %s\\n\",\n (TesterStatus_to_string(m_status)).c_str());\n}\n\nvoid\nCheck::initiateCheck()\n{\n DPRINTF(RubyTest, \"Initiating Check\\n\");\n assert(m_status == TesterStatus_Ready);\n\n int index = random() % m_num_cpu_sequencers;\n RubyTester::CpuPort* port =\n safe_cast<RubyTester::CpuPort*>(m_tester_ptr->getCpuPort(index));\n\n Request::Flags flags;\n\n \/\/ 50% chance that the request will be an instruction fetch\n if ((random() & 0x1) == 0) {\n flags.set(Request::INST_FETCH);\n }\n\n \/\/ Checks are sized depending on the number of bytes written\n Request *req = new Request(m_address.getAddress(), CHECK_SIZE, flags,\n curTick(), m_pc.getAddress());\n\n req->setThreadContext(index, 0);\n PacketPtr pkt = new Packet(req, MemCmd::ReadReq, port->idx);\n uint8_t* dataArray = new uint8_t[CHECK_SIZE];\n pkt->dataDynamicArray(dataArray);\n\n \/\/ push the subblock onto the sender state. The sequencer will\n \/\/ update the subblock on the return\n pkt->senderState =\n new SenderState(m_address, req->getSize(), pkt->senderState);\n\n if (port->sendTiming(pkt)) {\n DPRINTF(RubyTest, \"initiating check - successful\\n\");\n DPRINTF(RubyTest, \"status before check update: %s\\n\",\n TesterStatus_to_string(m_status).c_str());\n m_status = TesterStatus_Check_Pending;\n } else {\n \/\/ If the packet did not issue, must delete\n \/\/ Note: No need to delete the data, the packet destructor\n \/\/ will delete it\n SenderState* senderState = safe_cast<SenderState*>(pkt->senderState);\n pkt->senderState = senderState->saved;\n delete senderState;\n delete pkt->req;\n delete pkt;\n\n DPRINTF(RubyTest, \"failed to initiate check - cpu port not ready\\n\");\n }\n\n DPRINTF(RubyTest, \"status after check update: %s\\n\",\n TesterStatus_to_string(m_status).c_str());\n}\n\nvoid\nCheck::performCallback(NodeID proc, SubBlock* data)\n{\n Address address = data->getAddress();\n\n \/\/ This isn't exactly right since we now have multi-byte checks\n \/\/ assert(getAddress() == address);\n\n assert(getAddress().getLineAddress() == address.getLineAddress());\n assert(data != NULL);\n\n DPRINTF(RubyTest, \"RubyTester Callback\\n\");\n debugPrint();\n\n if (m_status == TesterStatus_Action_Pending) {\n DPRINTF(RubyTest, \"Action callback write value: %d, currently %d\\n\",\n (m_value + m_store_count), data->getByte(0));\n \/\/ Perform store one byte at a time\n data->setByte(0, (m_value + m_store_count));\n m_store_count++;\n if (m_store_count == CHECK_SIZE) {\n m_status = TesterStatus_Ready;\n } else {\n m_status = TesterStatus_Idle;\n }\n DPRINTF(RubyTest, \"Action callback return data now %d\\n\",\n data->getByte(0));\n } else if (m_status == TesterStatus_Check_Pending) {\n DPRINTF(RubyTest, \"Check callback\\n\");\n \/\/ Perform load\/check\n for (int byte_number=0; byte_number<CHECK_SIZE; byte_number++) {\n if (uint8(m_value + byte_number) != data->getByte(byte_number)) {\n panic(\"Action\/check failure: proc: %d address: %s data: %s \"\n \"byte_number: %d m_value+byte_number: %d byte: %d %s\"\n \"Time: %d\\n\",\n proc, address, data, byte_number,\n (int)m_value + byte_number,\n (int)data->getByte(byte_number), *this,\n g_eventQueue_ptr->getTime());\n }\n }\n DPRINTF(RubyTest, \"Action\/check success\\n\");\n debugPrint();\n\n \/\/ successful check complete, increment complete\n m_tester_ptr->incrementCheckCompletions();\n\n m_status = TesterStatus_Idle;\n pickValue();\n\n } else {\n panic(\"Unexpected TesterStatus: %s proc: %d data: %s m_status: %s \"\n \"time: %d\\n\",\n *this, proc, data, m_status, g_eventQueue_ptr->getTime());\n }\n\n DPRINTF(RubyTest, \"proc: %d, Address: 0x%x\\n\", proc,\n getAddress().getLineAddress());\n DPRINTF(RubyTest, \"Callback done\\n\");\n debugPrint();\n}\n\nvoid\nCheck::changeAddress(const Address& address)\n{\n assert(m_status == TesterStatus_Idle || m_status == TesterStatus_Ready);\n m_status = TesterStatus_Idle;\n m_address = address;\n m_store_count = 0;\n}\n\nvoid\nCheck::pickValue()\n{\n assert(m_status == TesterStatus_Idle);\n m_status = TesterStatus_Idle;\n m_value = random() & 0xff; \/\/ One byte\n m_store_count = 0;\n}\n\nvoid\nCheck::pickInitiatingNode()\n{\n assert(m_status == TesterStatus_Idle || m_status == TesterStatus_Ready);\n m_status = TesterStatus_Idle;\n m_initiatingNode = (random() % m_num_cpu_sequencers);\n DPRINTF(RubyTest, \"picked initiating node %d\\n\", m_initiatingNode);\n m_store_count = 0;\n}\n\nvoid\nCheck::print(std::ostream& out) const\n{\n out << \"[\"\n << m_address << \", value: \"\n << (int)m_value << \", status: \"\n << m_status << \", initiating node: \"\n << m_initiatingNode << \", store_count: \"\n << m_store_count\n << \"]\" << std::flush;\n}\n\nvoid\nCheck::debugPrint()\n{\n DPRINTF(RubyTest,\n \"[%#x, value: %d, status: %s, initiating node: %d, store_count: %d]\\n\",\n m_address.getAddress(), (int)m_value,\n TesterStatus_to_string(m_status).c_str(),\n m_initiatingNode, m_store_count);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ jsb_templates.hpp\n\/\/ hello_world-mobile\n\/\/\n\/\/ Created by Duc Nguyen on 7\/13\/18.\n\/\/\n\n#ifndef JSB_TEMPLATES_HPP__\n#define JSB_TEMPLATES_HPP__\n\n#include <type_traits>\n\n#include \"cocos\/scripting\/js-bindings\/jswrapper\/SeApi.h\"\n#include \"cocos\/scripting\/js-bindings\/manual\/jsb_conversions.hpp\"\n\n#include <ee\/Core.hpp>\n\nnamespace ee {\nnamespace core {\n\ntemplate <typename T> T get_value(const se::Value& value);\n\ntemplate <> inline bool get_value(const se::Value& value) {\n return value.toBoolean();\n}\n\ntemplate <> inline std::int32_t get_value(const se::Value& value) {\n return value.toInt32();\n}\n\ntemplate <> inline std::string get_value(const se::Value& value) {\n return std::move(value.toString());\n}\n\ntemplate <> inline const std::string& get_value(const se::Value& value) {\n return value.toString();\n}\n\ntemplate <typename T> void set_value(se::Value& value, T input);\n\ntemplate <> inline void set_value(se::Value& value, std::int32_t input) {\n value.setInt32(input);\n}\n\ntemplate <> inline void set_value(se::Value& value, std::string input) {\n value.setString(input);\n}\n\ntemplate <> inline void set_value(se::Value& value, bool input) {\n value.setBoolean(input);\n}\n\ntemplate <> inline void set_value(se::Value& value, se::Object* obj) {\n value.setObject(obj);\n}\n\ntemplate <auto FunctionPtr, typename... Args, std::size_t... Indices>\nauto call_static_func(const se::ValueArray& args,\n std::index_sequence<Indices...>) {\n return (*FunctionPtr)(get_value<Args>(args[Indices])...);\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename... Args,\n std::size_t... Indices>\nauto call_instance_func(InstanceType* instance, const se::ValueArray& args,\n std::index_sequence<Indices...>) {\n return (instance->*FunctionPtr)(get_value<Args>(args[Indices])...);\n}\n\ntemplate <typename T, typename... Args, std::size_t... Indices>\nauto make_object(const se::ValueArray& args, std::index_sequence<Indices...>) {\n return new T(get_value<Args>(args[Indices])...);\n}\n\ntemplate <typename T, typename... Args>\nstatic bool jsb_constructor(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = make_object<T, Args...>(args, Indices());\n s.thisObject()->setPrivateData(cObj);\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %d.\", argc,\n 2);\n return false;\n}\n\ntemplate <typename T> static bool jsb_finalize(se::State& s) {\n T* cObj = static_cast<T*>(s.nativeThisObject());\n delete cObj;\n return true;\n}\n\ntemplate <auto Function, typename... Args> bool jsb_static_call(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n call_static_func<Function, Args...>(args, Indices());\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename ReturnType, auto FunctionPtr, typename... Args>\nbool jsb_static_get(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto result = call_static_func<FunctionPtr, Args...>(args, Indices());\n set_value<ReturnType>(s.rval(), result);\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename ReturnType, auto MemberPtr>\nbool jsb_static_property_get(se::State& s) {\n set_value<ReturnType>(s.rval(), *MemberPtr);\n return true;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename... Args>\nbool jsb_method_call(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n call_instance_func<InstanceType, FunctionPtr, Args...>(cObj, args,\n Indices());\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename... Args>\nbool jsb_method_call_on_ui_thread(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n ee::runOnUiThread([cObj, args] {\n call_instance_func<InstanceType, FunctionPtr, Args...>(cObj, args,\n Indices());\n });\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename... Args>\nbool jsb_method_call_on_ui_thread_and_wait(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n ee::runOnUiThreadAndWait([cObj, args] {\n call_instance_func<InstanceType, FunctionPtr, Args...>(cObj, args,\n Indices());\n });\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ReturnType,\n typename... Args>\nbool jsb_method_get(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n set_value<ReturnType>(\n s.rval(), call_instance_func<InstanceType, FunctionPtr, Args...>(\n cObj, args, Indices()));\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ReturnType,\n typename... Args>\nbool jsb_method_get_on_ui_thread(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n set_value<ReturnType>(\n s.rval(),\n ee::runOnUiThreadAndWaitResult([cObj, args]() -> ReturnType {\n call_instance_func<InstanceType, FunctionPtr, Args...>(\n cObj, args, Indices());\n }));\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ReturnType>\nbool jsb_accessor_get(se::State& s) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n set_value<ReturnType>(s.rval(), std::bind(FunctionPtr, cObj)());\n return true;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ReturnType>\nbool jsb_accessor_get_on_ui_thread(se::State& s) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n set_value<ReturnType>(\n s.rval(),\n ee::runOnUiThreadAndWaitResult<ReturnType>(\n [cObj]() -> ReturnType { return std::bind(FunctionPtr, cObj)(); }));\n return true;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ArgumentType>\nbool jsb_accessor_set(se::State& s) {\n const auto& args = s.args();\n if (args.size() == 1) {\n auto* cObj = static_cast<InstanceType*>(s.nativeThisObject());\n std::bind(FunctionPtr, cObj, get_value<ArgumentType>(args[0]))();\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %d.\",\n args.size(), 1);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ArgumentType>\nbool jsb_accessor_set_on_ui_thread(se::State& s) {\n const auto& args = s.args();\n if (args.size() == 1) {\n auto* cObj = static_cast<InstanceType*>(s.nativeThisObject());\n ee::runOnUiThread([cObj, args] {\n std::bind(FunctionPtr, cObj, get_value<ArgumentType>(args[0]))();\n });\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %d.\",\n args.size(), 1);\n return false;\n}\n\ntemplate <typename InstanceType, auto MemberPtr, typename ReturnType>\nbool jsb_propterty_get(se::State& s) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n auto input(cObj->*MemberPtr);\n set_value<ReturnType>(s.rval(), std::move(input));\n return true;\n}\n\ntemplate <typename InstanceType, auto MemberPtr, typename ArgumentType>\nbool jsb_propterty_set(se::State& s) {\n const auto& args = s.args();\n if (args.size() == 1) {\n auto* cObj = static_cast<InstanceType*>(s.nativeThisObject());\n cObj->*MemberPtr = get_value<std::decay_t<ArgumentType>>(args[0]);\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %d.\",\n args.size(), 1);\n return false;\n}\n\n} \/\/ namespace core\n} \/\/ namespace ee\n\n#endif \/* JSB_TEMPLATES_HPP__ *\/\n<commit_msg>- Adding utility methods.<commit_after>\/\/\n\/\/ jsb_templates.hpp\n\/\/ hello_world-mobile\n\/\/\n\/\/ Created by Duc Nguyen on 7\/13\/18.\n\/\/\n\n#ifndef JSB_TEMPLATES_HPP__\n#define JSB_TEMPLATES_HPP__\n\n#include <type_traits>\n\n#include \"cocos\/scripting\/js-bindings\/jswrapper\/SeApi.h\"\n#include \"cocos\/scripting\/js-bindings\/manual\/jsb_conversions.hpp\"\n\n#include <ee\/Core.hpp>\n#include <ee\/nlohmann\/json.hpp>\n\nnamespace ee {\nnamespace core {\n\ntemplate <typename T> se::Object* create_JSON_object(const T& value);\n\ntemplate <>\ninline se::Object* create_JSON_object(const std::pair<float, float>& value) {\n auto&& jsonArray = nlohmann::json::array();\n jsonArray.push_back(value.first);\n jsonArray.push_back(value.second);\n return se::Object::createJSONObject(jsonArray.dump());\n}\n\ntemplate <>\ninline se::Object* create_JSON_object(const std::pair<int, int>& value) {\n auto&& jsonArray = nlohmann::json::array();\n jsonArray.push_back(value.first);\n jsonArray.push_back(value.second);\n return se::Object::createJSONObject(jsonArray.dump());\n}\n\ntemplate <typename T> T get_value(const se::Value& value);\n\ntemplate <> inline bool get_value(const se::Value& value) {\n return value.toBoolean();\n}\n\ntemplate <> inline std::int32_t get_value(const se::Value& value) {\n return value.toInt32();\n}\n\ntemplate <> inline float get_value(const se::Value& value) {\n return value.toFloat();\n}\n\ntemplate <> inline std::string get_value(const se::Value& value) {\n return std::move(value.toString());\n}\n\ntemplate <> inline const std::string& get_value(const se::Value& value) {\n return value.toString();\n}\n\ntemplate <typename T> void set_value(se::Value& value, T input);\n\ntemplate <> inline void set_value(se::Value& value, std::int32_t input) {\n value.setInt32(input);\n}\n\ntemplate <> inline void set_value(se::Value& value, std::string input) {\n value.setString(input);\n}\n\ntemplate <> inline void set_value(se::Value& value, bool input) {\n value.setBoolean(input);\n}\n\ntemplate <> inline void set_value(se::Value& value, se::Object* obj) {\n value.setObject(obj);\n}\n\ntemplate <>\ninline void set_value(se::Value& value, std::pair<float, float> input) {\n auto obj = create_JSON_object<std::pair<float, float>>(input);\n value.setObject(obj);\n}\n\ntemplate <> inline void set_value(se::Value& value, std::pair<int, int> input) {\n auto obj = create_JSON_object<std::pair<int, int>>(input);\n value.setObject(obj);\n}\n\ntemplate <auto FunctionPtr, typename... Args, std::size_t... Indices>\nauto call_static_func(const se::ValueArray& args,\n std::index_sequence<Indices...>) {\n return (*FunctionPtr)(get_value<Args>(args[Indices])...);\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename... Args,\n std::size_t... Indices>\nauto call_instance_func(InstanceType* instance, const se::ValueArray& args,\n std::index_sequence<Indices...>) {\n return (instance->*FunctionPtr)(get_value<Args>(args[Indices])...);\n}\n\ntemplate <typename T, typename... Args, std::size_t... Indices>\nauto make_object(const se::ValueArray& args, std::index_sequence<Indices...>) {\n return new T(get_value<Args>(args[Indices])...);\n}\n\ntemplate <typename T, typename... Args>\nstatic bool jsb_constructor(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = make_object<T, Args...>(args, Indices());\n s.thisObject()->setPrivateData(cObj);\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %d.\", argc,\n 2);\n return false;\n}\n\ntemplate <typename T> static bool jsb_finalize(se::State& s) {\n T* cObj = static_cast<T*>(s.nativeThisObject());\n delete cObj;\n return true;\n}\n\ntemplate <auto Function, typename... Args> bool jsb_static_call(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n call_static_func<Function, Args...>(args, Indices());\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename ReturnType, auto FunctionPtr, typename... Args>\nbool jsb_static_get(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto result = call_static_func<FunctionPtr, Args...>(args, Indices());\n set_value<ReturnType>(s.rval(), result);\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename ReturnType, auto MemberPtr>\nbool jsb_static_property_get(se::State& s) {\n set_value<ReturnType>(s.rval(), *MemberPtr);\n return true;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename... Args>\nbool jsb_method_call(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n call_instance_func<InstanceType, FunctionPtr, Args...>(cObj, args,\n Indices());\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename... Args>\nbool jsb_method_call_on_ui_thread(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n ee::runOnUiThread([cObj, args] {\n call_instance_func<InstanceType, FunctionPtr, Args...>(cObj, args,\n Indices());\n });\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename... Args>\nbool jsb_method_call_on_ui_thread_and_wait(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n ee::runOnUiThreadAndWait([cObj, args] {\n call_instance_func<InstanceType, FunctionPtr, Args...>(cObj, args,\n Indices());\n });\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ReturnType,\n typename... Args>\nbool jsb_method_get(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n set_value<ReturnType>(\n s.rval(), call_instance_func<InstanceType, FunctionPtr, Args...>(\n cObj, args, Indices()));\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ReturnType,\n typename... Args>\nbool jsb_method_get_on_ui_thread(se::State& s) {\n auto argc = sizeof...(Args);\n const auto& args = s.args();\n using Indices = std::make_index_sequence<sizeof...(Args)>;\n\n if (argc == args.size()) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n set_value<ReturnType>(\n s.rval(),\n ee::runOnUiThreadAndWaitResult<ReturnType>([cObj,\n args]() -> ReturnType {\n return std::forward<ReturnType>(call_instance_func<InstanceType, FunctionPtr, Args...>(\n cObj, args, Indices()));\n }));\n return true;\n }\n\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %ld.\",\n args.size(), argc);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ReturnType>\nbool jsb_accessor_get(se::State& s) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n set_value<ReturnType>(s.rval(), std::bind(FunctionPtr, cObj)());\n return true;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ReturnType>\nbool jsb_accessor_get_on_ui_thread(se::State& s) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n set_value<ReturnType>(\n s.rval(),\n ee::runOnUiThreadAndWaitResult<ReturnType>(\n [cObj]() -> ReturnType { return std::bind(FunctionPtr, cObj)(); }));\n return true;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ArgumentType>\nbool jsb_accessor_set(se::State& s) {\n const auto& args = s.args();\n if (args.size() == 1) {\n auto* cObj = static_cast<InstanceType*>(s.nativeThisObject());\n std::bind(FunctionPtr, cObj, get_value<ArgumentType>(args[0]))();\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %d.\",\n args.size(), 1);\n return false;\n}\n\ntemplate <typename InstanceType, auto FunctionPtr, typename ArgumentType>\nbool jsb_accessor_set_on_ui_thread(se::State& s) {\n const auto& args = s.args();\n if (args.size() == 1) {\n auto* cObj = static_cast<InstanceType*>(s.nativeThisObject());\n ee::runOnUiThread([cObj, args] {\n std::bind(FunctionPtr, cObj, get_value<ArgumentType>(args[0]))();\n });\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %d.\",\n args.size(), 1);\n return false;\n}\n\ntemplate <typename InstanceType, auto MemberPtr, typename ReturnType>\nbool jsb_propterty_get(se::State& s) {\n auto cObj = static_cast<InstanceType*>(s.nativeThisObject());\n auto input(cObj->*MemberPtr);\n set_value<ReturnType>(s.rval(), std::move(input));\n return true;\n}\n\ntemplate <typename InstanceType, auto MemberPtr, typename ArgumentType>\nbool jsb_propterty_set(se::State& s) {\n const auto& args = s.args();\n if (args.size() == 1) {\n auto* cObj = static_cast<InstanceType*>(s.nativeThisObject());\n cObj->*MemberPtr = get_value<std::decay_t<ArgumentType>>(args[0]);\n return true;\n }\n SE_REPORT_ERROR(\"Wrong number of arguments: %ld, was expecting: %d.\",\n args.size(), 1);\n return false;\n}\n\n} \/\/ namespace core\n} \/\/ namespace ee\n\n#endif \/* JSB_TEMPLATES_HPP__ *\/\n<|endoftext|>"} {"text":"<commit_before>#include <xzero\/executor\/ThreadedExecutor.h>\n#include <xzero\/sysconfig.h>\n#include <memory>\n#include <algorithm>\n#include <limits>\n#include <pthread.h>\n\nnamespace xzero {\n\n#if 0 \/\/!defined(NDEBUG)\nstatic std::mutex m;\n#define TRACE(msg...) do { \\\n m.lock(); \\\n printf(\"ThreadedExecutor: \" msg); \\\n printf(\"\\n\"); \\\n m.unlock(); \\\n } while (0);\n#else\n#define TRACE(msg...) do { } while (0)\n#endif\n\nThreadedExecutor::ThreadedExecutor() : threads_() {\n}\n\nThreadedExecutor::~ThreadedExecutor() {\n joinAll();\n}\n\nstatic std::string getThreadName(pthread_t tid) {\n char name[16];\n name[0] = '\\0';\n pthread_getname_np(tid, name, sizeof(name));\n return name;\n}\n\nvoid ThreadedExecutor::joinAll() {\n for (;;) {\n pthread_t tid = 0;\n {\n TRACE(\"joinAll: getting lock for getting TID\");\n std::lock_guard<std::mutex> lock(mutex_);\n if (threads_.empty())\n break;\n\n tid = threads_.front();\n threads_.pop_front();\n }\n TRACE(\"joinAll: join(%lu) %s\", tid, getThreadName(tid).c_str());\n pthread_join(tid, nullptr);\n }\n TRACE(\"joinAll: done\");\n}\n\nvoid* ThreadedExecutor::launchme(void* ptr) {\n TRACE(\"launchme[%d](%p) enter\", pthread_self(), ptr);\n std::unique_ptr<Executor::Task> task(reinterpret_cast<Executor::Task*>(ptr));\n (*task)();\n TRACE(\"launchme[%d](%p) leave\", pthread_self(), ptr);\n return nullptr;\n}\n\nvoid ThreadedExecutor::execute(const std::string& name, Task&& task) {\n pthread_t tid;\n pthread_create(&tid, NULL, &launchme, new Task{std::move(task)});\n pthread_setname_np(tid, name.c_str());\n\n std::lock_guard<std::mutex> lock(mutex_);\n threads_.push_back(tid);\n}\n\nvoid ThreadedExecutor::execute(Task&& task) {\n pthread_t tid = 0;\n \/\/pthread_create(&tid, NULL, &launchme, new Task{std::move(task)});\n pthread_create(&tid, NULL, &launchme, new Task([this, tid, task]{\n task();\n {\n TRACE(\"task %s finished. getting lock for cleanup\", getThreadName(pthread_self()).c_str());\n std::lock_guard<std::mutex> lock(mutex_);\n pthread_detach(tid);\n auto i = std::find(threads_.begin(), threads_.end(), tid);\n if (i != threads_.end()) {\n threads_.erase(i);\n }\n }\n }));\n std::lock_guard<std::mutex> lock(mutex_);\n threads_.push_back(tid);\n}\n\nsize_t ThreadedExecutor::maxConcurrency() const noexcept {\n return std::numeric_limits<size_t>::max();\n}\n\nstd::string ThreadedExecutor::toString() const {\n char buf[32];\n snprintf(buf, sizeof(buf), \"ThreadedExecutor@%p\", this);\n return buf;\n}\n\n} \/\/ namespace xzero\n<commit_msg>apple-port: defer ThreadeExecutor's native thread naming until later<commit_after>#include <xzero\/executor\/ThreadedExecutor.h>\n#include <xzero\/sysconfig.h>\n#include <memory>\n#include <algorithm>\n#include <limits>\n#include <pthread.h>\n\nnamespace xzero {\n\n#if 0 \/\/!defined(NDEBUG)\nstatic std::mutex m;\n#define TRACE(msg...) do { \\\n m.lock(); \\\n printf(\"ThreadedExecutor: \" msg); \\\n printf(\"\\n\"); \\\n m.unlock(); \\\n } while (0);\n#else\n#define TRACE(msg...) do { } while (0)\n#endif\n\nThreadedExecutor::ThreadedExecutor() : threads_() {\n}\n\nThreadedExecutor::~ThreadedExecutor() {\n joinAll();\n}\n\nstatic std::string getThreadName(pthread_t tid) {\n char name[16];\n name[0] = '\\0';\n pthread_getname_np(tid, name, sizeof(name));\n return name;\n}\n\nvoid ThreadedExecutor::joinAll() {\n for (;;) {\n pthread_t tid = 0;\n {\n TRACE(\"joinAll: getting lock for getting TID\");\n std::lock_guard<std::mutex> lock(mutex_);\n if (threads_.empty())\n break;\n\n tid = threads_.front();\n threads_.pop_front();\n }\n TRACE(\"joinAll: join(%lu) %s\", tid, getThreadName(tid).c_str());\n pthread_join(tid, nullptr);\n }\n TRACE(\"joinAll: done\");\n}\n\nvoid* ThreadedExecutor::launchme(void* ptr) {\n TRACE(\"launchme[%d](%p) enter\", pthread_self(), ptr);\n std::unique_ptr<Executor::Task> task(reinterpret_cast<Executor::Task*>(ptr));\n (*task)();\n TRACE(\"launchme[%d](%p) leave\", pthread_self(), ptr);\n return nullptr;\n}\n\nvoid ThreadedExecutor::execute(const std::string& name, Task&& task) {\n pthread_t tid;\n pthread_create(&tid, NULL, &launchme, new Task{std::move(task)});\n\n#if !defined(__APPLE__)\n \/\/ OS\/x doesn't support setting thread names for other threads\n \/\/ TODO: pass thread name to target thread and set it inside\n pthread_setname_np(tid, name.c_str());\n#endif\n\n std::lock_guard<std::mutex> lock(mutex_);\n threads_.push_back(tid);\n}\n\nvoid ThreadedExecutor::execute(Task&& task) {\n pthread_t tid = 0;\n \/\/pthread_create(&tid, NULL, &launchme, new Task{std::move(task)});\n pthread_create(&tid, NULL, &launchme, new Task([this, tid, task]{\n task();\n {\n TRACE(\"task %s finished. getting lock for cleanup\", getThreadName(pthread_self()).c_str());\n std::lock_guard<std::mutex> lock(mutex_);\n pthread_detach(tid);\n auto i = std::find(threads_.begin(), threads_.end(), tid);\n if (i != threads_.end()) {\n threads_.erase(i);\n }\n }\n }));\n std::lock_guard<std::mutex> lock(mutex_);\n threads_.push_back(tid);\n}\n\nsize_t ThreadedExecutor::maxConcurrency() const noexcept {\n return std::numeric_limits<size_t>::max();\n}\n\nstd::string ThreadedExecutor::toString() const {\n char buf[32];\n snprintf(buf, sizeof(buf), \"ThreadedExecutor@%p\", this);\n return buf;\n}\n\n} \/\/ namespace xzero\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: Reference.hxx,v $\n *\n * $Revision: 1.22 $\n *\n * last change: $Author: kz $ $Date: 2004-07-30 15:03:07 $\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#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#define _COM_SUN_STAR_UNO_REFERENCE_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HDL_\n#include <com\/sun\/star\/uno\/XInterface.hdl>\n#endif\n#ifndef _COM_SUN_STAR_UNO_GENFUNC_HXX_\n#include <com\/sun\/star\/uno\/genfunc.hxx>\n#endif\n\nnamespace com\n{\nnamespace sun\n{\nnamespace star\n{\nnamespace uno\n{\n\n\/\/__________________________________________________________________________________________________\ninline XInterface * BaseReference::iquery(\n XInterface * pInterface, const Type & rType )\n SAL_THROW( (RuntimeException) )\n{\n if (pInterface)\n {\n Any aRet( pInterface->queryInterface( rType ) );\n if (typelib_TypeClass_INTERFACE == aRet.pType->eTypeClass)\n {\n XInterface * pRet = reinterpret_cast< XInterface * >( aRet.pReserved );\n aRet.pReserved = 0;\n return pRet;\n }\n }\n return 0;\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline XInterface * Reference< interface_type >::iquery(\n XInterface * pInterface ) SAL_THROW( (RuntimeException) )\n{\n return BaseReference::iquery(pInterface, interface_type::static_type());\n}\n#ifndef EXCEPTIONS_OFF\nextern \"C\" rtl_uString * SAL_CALL cppu_unsatisfied_iquery_msg(\n typelib_TypeDescriptionReference * pType )\n SAL_THROW_EXTERN_C();\n\/\/__________________________________________________________________________________________________\ninline XInterface * BaseReference::iquery_throw(\n XInterface * pInterface, const Type & rType )\n SAL_THROW( (RuntimeException) )\n{\n XInterface * pQueried = iquery( pInterface, rType );\n if (pQueried)\n return pQueried;\n throw RuntimeException(\n ::rtl::OUString( cppu_unsatisfied_iquery_msg( rType.getTypeLibType() ), SAL_NO_ACQUIRE ),\n Reference< XInterface >( pInterface ) );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline XInterface * Reference< interface_type >::iquery_throw(\n XInterface * pInterface ) SAL_THROW( (RuntimeException) )\n{\n return BaseReference::iquery_throw(\n pInterface, interface_type::static_type());\n}\n#endif\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::~Reference() SAL_THROW( () )\n{\n if (_pInterface)\n _pInterface->release();\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference() SAL_THROW( () )\n{\n _pInterface = 0;\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const Reference< interface_type > & rRef ) SAL_THROW( () )\n{\n _pInterface = rRef._pInterface;\n if (_pInterface)\n _pInterface->acquire();\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( interface_type * pInterface ) SAL_THROW( () )\n{\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n if (_pInterface)\n _pInterface->acquire();\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( interface_type * pInterface, __sal_NoAcquire ) SAL_THROW( () )\n{\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( interface_type * pInterface, UnoReference_NoAcquire ) SAL_THROW( () )\n{\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const BaseReference & rRef, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery( rRef.get() );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( XInterface * pInterface, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery( pInterface );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const Any & rAny, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = (typelib_TypeClass_INTERFACE == rAny.pType->eTypeClass\n ? iquery( reinterpret_cast< XInterface * >( rAny.pReserved ) ) : 0);\n}\n#ifndef EXCEPTIONS_OFF\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const BaseReference & rRef, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery_throw( rRef.get() );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( XInterface * pInterface, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery_throw( pInterface );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const Any & rAny, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery_throw( typelib_TypeClass_INTERFACE == rAny.pType->eTypeClass\n ? reinterpret_cast< XInterface * >( rAny.pReserved ) : 0 );\n}\n#endif\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline void Reference< interface_type >::clear() SAL_THROW( () )\n{\n if (_pInterface)\n {\n _pInterface->release();\n _pInterface = 0;\n }\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n interface_type * pInterface ) SAL_THROW( () )\n{\n if (pInterface)\n reinterpret_cast< XInterface * >(pInterface)->acquire();\n if (_pInterface)\n _pInterface->release();\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n return (0 != pInterface);\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n interface_type * pInterface, __sal_NoAcquire ) SAL_THROW( () )\n{\n if (_pInterface)\n _pInterface->release();\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n return (0 != pInterface);\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n interface_type * pInterface, UnoReference_NoAcquire ) SAL_THROW( () )\n{\n return set( pInterface, SAL_NO_ACQUIRE );\n}\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n const Reference< interface_type > & rRef ) SAL_THROW( () )\n{\n return set( reinterpret_cast< interface_type * >( rRef._pInterface ) );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n XInterface * pInterface, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n return set(\n reinterpret_cast< interface_type * >(iquery( pInterface )),\n SAL_NO_ACQUIRE );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n const BaseReference & rRef, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n return set(\n reinterpret_cast< interface_type * >(iquery( rRef.get() )),\n SAL_NO_ACQUIRE );\n}\n\n\/\/______________________________________________________________________________\ntemplate< class interface_type >\ninline bool Reference< interface_type >::set(\n Any const & rAny, UnoReference_Query )\n{\n return set(\n reinterpret_cast< interface_type * >(\n iquery(\n rAny.pType->eTypeClass == typelib_TypeClass_INTERFACE\n ? reinterpret_cast< XInterface * >( rAny.pReserved ) : 0 )),\n SAL_NO_ACQUIRE );\n}\n\n#ifndef EXCEPTIONS_OFF\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline void Reference< interface_type >::set(\n XInterface * pInterface, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n set( reinterpret_cast< interface_type * >(iquery_throw( pInterface )),\n SAL_NO_ACQUIRE );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline void Reference< interface_type >::set(\n const BaseReference & rRef, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n set( reinterpret_cast< interface_type * >(iquery_throw( rRef.get() )),\n SAL_NO_ACQUIRE );\n}\n\n\/\/______________________________________________________________________________\ntemplate< class interface_type >\ninline void Reference< interface_type >::set(\n Any const & rAny, UnoReference_QueryThrow )\n{\n set( reinterpret_cast< interface_type * >(\n iquery_throw(\n rAny.pType->eTypeClass == typelib_TypeClass_INTERFACE\n ? reinterpret_cast< XInterface * >( rAny.pReserved ) : 0 )),\n SAL_NO_ACQUIRE );\n}\n\n#endif\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type > & Reference< interface_type >::operator = (\n interface_type * pInterface ) SAL_THROW( () )\n{\n set( pInterface );\n return *this;\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type > & Reference< interface_type >::operator = (\n const Reference< interface_type > & rRef ) SAL_THROW( () )\n{\n set( reinterpret_cast< interface_type * >( rRef._pInterface ) );\n return *this;\n}\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type > Reference< interface_type >::query(\n const BaseReference & rRef ) SAL_THROW( (RuntimeException) )\n{\n return Reference< interface_type >(\n reinterpret_cast< interface_type * >(iquery( rRef.get() )),\n SAL_NO_ACQUIRE );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type > Reference< interface_type >::query(\n XInterface * pInterface ) SAL_THROW( (RuntimeException) )\n{\n return Reference< interface_type >(\n reinterpret_cast< interface_type * >(iquery( pInterface )),\n SAL_NO_ACQUIRE );\n}\n\n\/\/##################################################################################################\n\n\/\/__________________________________________________________________________________________________\ninline sal_Bool BaseReference::operator == ( XInterface * pInterface ) const SAL_THROW( () )\n{\n if (_pInterface == pInterface)\n return sal_True;\n#ifndef EXCEPTIONS_OFF\n try\n {\n#endif\n \/\/ only the query to XInterface must return the same pointer if they belong to same objects\n Reference< XInterface > x1( _pInterface, UNO_QUERY );\n Reference< XInterface > x2( pInterface, UNO_QUERY );\n return (x1._pInterface == x2._pInterface);\n#ifndef EXCEPTIONS_OFF\n }\n catch (RuntimeException &)\n {\n return sal_False;\n }\n#endif\n}\n\n\/\/______________________________________________________________________________\ninline sal_Bool BaseReference::operator < (\n const BaseReference & rRef ) const SAL_THROW( () )\n{\n if (_pInterface == rRef._pInterface)\n return sal_False;\n#if ! defined EXCEPTIONS_OFF\n try\n {\n#endif\n \/\/ only the query to XInterface must return the same pointer:\n Reference< XInterface > x1( _pInterface, UNO_QUERY );\n Reference< XInterface > x2( rRef, UNO_QUERY );\n return (x1._pInterface < x2._pInterface);\n#if ! defined EXCEPTIONS_OFF\n }\n catch (RuntimeException &)\n {\n return sal_False;\n }\n#endif\n}\n\n\/\/__________________________________________________________________________________________________\ninline sal_Bool BaseReference::operator != ( XInterface * pInterface ) const SAL_THROW( () )\n{\n return (! operator == ( pInterface ));\n}\n\/\/__________________________________________________________________________________________________\ninline sal_Bool BaseReference::operator == ( const BaseReference & rRef ) const SAL_THROW( () )\n{\n return operator == ( rRef._pInterface );\n}\n\/\/__________________________________________________________________________________________________\ninline sal_Bool BaseReference::operator != ( const BaseReference & rRef ) const SAL_THROW( () )\n{\n return (! operator == ( rRef._pInterface ));\n}\n\n}\n}\n}\n}\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.22.34); FILE MERGED 2005\/09\/05 13:54:11 rt 1.22.34.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: Reference.hxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 08:34:00 $\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 _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#define _COM_SUN_STAR_UNO_REFERENCE_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HDL_\n#include <com\/sun\/star\/uno\/XInterface.hdl>\n#endif\n#ifndef _COM_SUN_STAR_UNO_GENFUNC_HXX_\n#include <com\/sun\/star\/uno\/genfunc.hxx>\n#endif\n\nnamespace com\n{\nnamespace sun\n{\nnamespace star\n{\nnamespace uno\n{\n\n\/\/__________________________________________________________________________________________________\ninline XInterface * BaseReference::iquery(\n XInterface * pInterface, const Type & rType )\n SAL_THROW( (RuntimeException) )\n{\n if (pInterface)\n {\n Any aRet( pInterface->queryInterface( rType ) );\n if (typelib_TypeClass_INTERFACE == aRet.pType->eTypeClass)\n {\n XInterface * pRet = reinterpret_cast< XInterface * >( aRet.pReserved );\n aRet.pReserved = 0;\n return pRet;\n }\n }\n return 0;\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline XInterface * Reference< interface_type >::iquery(\n XInterface * pInterface ) SAL_THROW( (RuntimeException) )\n{\n return BaseReference::iquery(pInterface, interface_type::static_type());\n}\n#ifndef EXCEPTIONS_OFF\nextern \"C\" rtl_uString * SAL_CALL cppu_unsatisfied_iquery_msg(\n typelib_TypeDescriptionReference * pType )\n SAL_THROW_EXTERN_C();\n\/\/__________________________________________________________________________________________________\ninline XInterface * BaseReference::iquery_throw(\n XInterface * pInterface, const Type & rType )\n SAL_THROW( (RuntimeException) )\n{\n XInterface * pQueried = iquery( pInterface, rType );\n if (pQueried)\n return pQueried;\n throw RuntimeException(\n ::rtl::OUString( cppu_unsatisfied_iquery_msg( rType.getTypeLibType() ), SAL_NO_ACQUIRE ),\n Reference< XInterface >( pInterface ) );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline XInterface * Reference< interface_type >::iquery_throw(\n XInterface * pInterface ) SAL_THROW( (RuntimeException) )\n{\n return BaseReference::iquery_throw(\n pInterface, interface_type::static_type());\n}\n#endif\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::~Reference() SAL_THROW( () )\n{\n if (_pInterface)\n _pInterface->release();\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference() SAL_THROW( () )\n{\n _pInterface = 0;\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const Reference< interface_type > & rRef ) SAL_THROW( () )\n{\n _pInterface = rRef._pInterface;\n if (_pInterface)\n _pInterface->acquire();\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( interface_type * pInterface ) SAL_THROW( () )\n{\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n if (_pInterface)\n _pInterface->acquire();\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( interface_type * pInterface, __sal_NoAcquire ) SAL_THROW( () )\n{\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( interface_type * pInterface, UnoReference_NoAcquire ) SAL_THROW( () )\n{\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const BaseReference & rRef, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery( rRef.get() );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( XInterface * pInterface, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery( pInterface );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const Any & rAny, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = (typelib_TypeClass_INTERFACE == rAny.pType->eTypeClass\n ? iquery( reinterpret_cast< XInterface * >( rAny.pReserved ) ) : 0);\n}\n#ifndef EXCEPTIONS_OFF\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const BaseReference & rRef, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery_throw( rRef.get() );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( XInterface * pInterface, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery_throw( pInterface );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type >::Reference( const Any & rAny, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n _pInterface = iquery_throw( typelib_TypeClass_INTERFACE == rAny.pType->eTypeClass\n ? reinterpret_cast< XInterface * >( rAny.pReserved ) : 0 );\n}\n#endif\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline void Reference< interface_type >::clear() SAL_THROW( () )\n{\n if (_pInterface)\n {\n _pInterface->release();\n _pInterface = 0;\n }\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n interface_type * pInterface ) SAL_THROW( () )\n{\n if (pInterface)\n reinterpret_cast< XInterface * >(pInterface)->acquire();\n if (_pInterface)\n _pInterface->release();\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n return (0 != pInterface);\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n interface_type * pInterface, __sal_NoAcquire ) SAL_THROW( () )\n{\n if (_pInterface)\n _pInterface->release();\n _pInterface = reinterpret_cast< XInterface * >(pInterface);\n return (0 != pInterface);\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n interface_type * pInterface, UnoReference_NoAcquire ) SAL_THROW( () )\n{\n return set( pInterface, SAL_NO_ACQUIRE );\n}\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n const Reference< interface_type > & rRef ) SAL_THROW( () )\n{\n return set( reinterpret_cast< interface_type * >( rRef._pInterface ) );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n XInterface * pInterface, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n return set(\n reinterpret_cast< interface_type * >(iquery( pInterface )),\n SAL_NO_ACQUIRE );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline sal_Bool Reference< interface_type >::set(\n const BaseReference & rRef, UnoReference_Query ) SAL_THROW( (RuntimeException) )\n{\n return set(\n reinterpret_cast< interface_type * >(iquery( rRef.get() )),\n SAL_NO_ACQUIRE );\n}\n\n\/\/______________________________________________________________________________\ntemplate< class interface_type >\ninline bool Reference< interface_type >::set(\n Any const & rAny, UnoReference_Query )\n{\n return set(\n reinterpret_cast< interface_type * >(\n iquery(\n rAny.pType->eTypeClass == typelib_TypeClass_INTERFACE\n ? reinterpret_cast< XInterface * >( rAny.pReserved ) : 0 )),\n SAL_NO_ACQUIRE );\n}\n\n#ifndef EXCEPTIONS_OFF\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline void Reference< interface_type >::set(\n XInterface * pInterface, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n set( reinterpret_cast< interface_type * >(iquery_throw( pInterface )),\n SAL_NO_ACQUIRE );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline void Reference< interface_type >::set(\n const BaseReference & rRef, UnoReference_QueryThrow ) SAL_THROW( (RuntimeException) )\n{\n set( reinterpret_cast< interface_type * >(iquery_throw( rRef.get() )),\n SAL_NO_ACQUIRE );\n}\n\n\/\/______________________________________________________________________________\ntemplate< class interface_type >\ninline void Reference< interface_type >::set(\n Any const & rAny, UnoReference_QueryThrow )\n{\n set( reinterpret_cast< interface_type * >(\n iquery_throw(\n rAny.pType->eTypeClass == typelib_TypeClass_INTERFACE\n ? reinterpret_cast< XInterface * >( rAny.pReserved ) : 0 )),\n SAL_NO_ACQUIRE );\n}\n\n#endif\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type > & Reference< interface_type >::operator = (\n interface_type * pInterface ) SAL_THROW( () )\n{\n set( pInterface );\n return *this;\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type > & Reference< interface_type >::operator = (\n const Reference< interface_type > & rRef ) SAL_THROW( () )\n{\n set( reinterpret_cast< interface_type * >( rRef._pInterface ) );\n return *this;\n}\n\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type > Reference< interface_type >::query(\n const BaseReference & rRef ) SAL_THROW( (RuntimeException) )\n{\n return Reference< interface_type >(\n reinterpret_cast< interface_type * >(iquery( rRef.get() )),\n SAL_NO_ACQUIRE );\n}\n\/\/__________________________________________________________________________________________________\ntemplate< class interface_type >\ninline Reference< interface_type > Reference< interface_type >::query(\n XInterface * pInterface ) SAL_THROW( (RuntimeException) )\n{\n return Reference< interface_type >(\n reinterpret_cast< interface_type * >(iquery( pInterface )),\n SAL_NO_ACQUIRE );\n}\n\n\/\/##################################################################################################\n\n\/\/__________________________________________________________________________________________________\ninline sal_Bool BaseReference::operator == ( XInterface * pInterface ) const SAL_THROW( () )\n{\n if (_pInterface == pInterface)\n return sal_True;\n#ifndef EXCEPTIONS_OFF\n try\n {\n#endif\n \/\/ only the query to XInterface must return the same pointer if they belong to same objects\n Reference< XInterface > x1( _pInterface, UNO_QUERY );\n Reference< XInterface > x2( pInterface, UNO_QUERY );\n return (x1._pInterface == x2._pInterface);\n#ifndef EXCEPTIONS_OFF\n }\n catch (RuntimeException &)\n {\n return sal_False;\n }\n#endif\n}\n\n\/\/______________________________________________________________________________\ninline sal_Bool BaseReference::operator < (\n const BaseReference & rRef ) const SAL_THROW( () )\n{\n if (_pInterface == rRef._pInterface)\n return sal_False;\n#if ! defined EXCEPTIONS_OFF\n try\n {\n#endif\n \/\/ only the query to XInterface must return the same pointer:\n Reference< XInterface > x1( _pInterface, UNO_QUERY );\n Reference< XInterface > x2( rRef, UNO_QUERY );\n return (x1._pInterface < x2._pInterface);\n#if ! defined EXCEPTIONS_OFF\n }\n catch (RuntimeException &)\n {\n return sal_False;\n }\n#endif\n}\n\n\/\/__________________________________________________________________________________________________\ninline sal_Bool BaseReference::operator != ( XInterface * pInterface ) const SAL_THROW( () )\n{\n return (! operator == ( pInterface ));\n}\n\/\/__________________________________________________________________________________________________\ninline sal_Bool BaseReference::operator == ( const BaseReference & rRef ) const SAL_THROW( () )\n{\n return operator == ( rRef._pInterface );\n}\n\/\/__________________________________________________________________________________________________\ninline sal_Bool BaseReference::operator != ( const BaseReference & rRef ) const SAL_THROW( () )\n{\n return (! operator == ( rRef._pInterface ));\n}\n\n}\n}\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"game\/skirmish\/mapmanager.hpp\"\n\n#include <cstdlib>\n#include <fstream>\n#include <regex>\n\n#include <SFML\/Graphics\/Texture.hpp>\n#include <SFML\/Graphics\/RenderTexture.hpp>\n\n#include \"foundation\/spritecomponent.hpp\"\n\n#include \"meta\/metamanager.hpp\"\n\n#include \"engine\/board.hpp\"\n#include \"game\/constants.hpp\"\n#include \"game\/deploymentzone.hpp\"\n#include \"game\/skirmish\/structure.hpp\"\n#include \"engine\/terrain.hpp\"\n\nnamespace fs = std::experimental::filesystem;\n\nnamespace qrw\n{\n\nMapManager::MapManager(MetaManager& metaManager)\n : metaManager_(metaManager),\n\tmapValidator_(new MapValidator())\n{\n}\n\nMapManager::~MapManager()\n{\n}\n\nMapDto MapManager::loadMap(\n\tconst std::string& mapName,\n\tLoadErrors& error)\n{\n\tMapDto mapDto;\n\n\tif(!doesMapExist(mapName))\n\t{\n\t\terror = LoadErrors::MAP_NOT_FOUND;\n\t\treturn mapDto;\n\t}\n\n\tstd::vector<YAML::Node> documents = YAML::LoadAllFromFile(getUserMapDir() \/ convertMapNameToPath(mapName, \".map\"));\n\tif(!mapValidator_->validate(documents))\n\t{\n\t\terror = LoadErrors::MAP_VALIDATION_FAILED;\n\t\treturn mapDto;\n\t}\n\n\tYAML::Node gameObjectsNode = documents.at(1);\n\n\tfor(auto node : gameObjectsNode)\n\t{\n\t\tauto gameObject = metaManager_.deserialize(node);\n\n\t\tif(auto zone = dynamic_cast<DeploymentZone*>(gameObject))\n\t\t{\n\t\t\tmapDto.deploymentZones.push_back(zone);\n\t\t}\n\t\telse if(auto board = dynamic_cast<Board*>(gameObject))\n\t\t{\n\t\t\tmapDto.board = board;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"Found unsupported game object in map \\'\"\n\t\t\t\t\t<< mapName << \"\\': \"\n\t\t\t\t \t<< node[MetaClass::TYPE_NAME_YAML_KEY].as<std::string>() << std::endl << std::flush;\n\t\t}\n\t}\n\n\terror = LoadErrors::SUCCESS;\n\treturn mapDto;\n}\n\nbool MapManager::doesMapExist(const std::string& mapName)\n{\n\tfs::path mapFilePath = getUserMapDir() \/ convertMapNameToPath(mapName, \".map\");\n\n\treturn fs::exists(mapFilePath);\n}\n\nvoid MapManager::saveMap(\n\tconst std::string& mapName,\n\tconst MapDto& dto)\n{\n\tconst std::string fileName = convertMapNameToPath(mapName, \".map\");\n\n\tYAML::Emitter yaml;\n\tyaml << YAML::BeginDoc\n\t\t << YAML::Comment(\"Description\")\n\t\t << YAML::BeginMap\n\t\t\t<< YAML::Key << \"name\" << YAML::Value << mapName\n\t\t\t<< YAML::Key << \"short-description\" << YAML::Value << \"Here goes the short description\"\n\t\t\t<< YAML::Key << \"playerCount\" << YAML::Value << 2\n\t << YAML::EndMap;\n\n\tyaml << YAML::BeginDoc\n\t\t << YAML::BeginSeq;\n\t\t\tmetaManager_.serialize(dto.board, yaml);\n\t\t\tfor(auto& zone : dto.deploymentZones)\n\t\t\t\tmetaManager_.serialize(zone, yaml);\n\tyaml << YAML::EndSeq;\n\n\tstd::ofstream mapFile;\n\tfs::path userMapDir = getUserMapDir();\n\n\tif(!fs::exists(userMapDir))\n\t\tfs::create_directories(userMapDir);\n\n\tmapFile.open(userMapDir \/ fileName, std::ofstream::out | std::ofstream::trunc);\n\tmapFile << yaml.c_str() << std::endl;\n\tmapFile.close();\n\n\tcreateAndSaveMapPreview(mapName, dto);\n}\n\nstd::vector<std::string> MapManager::getMapList() const\n{\n\tstd::vector<std::string> mapNames;\n\n\tfor(auto& p: fs::directory_iterator(getUserMapDir()))\n\t\tmapNames.push_back(convertPathToMapName(p));\n\n\treturn mapNames;\n}\n\nstd::string MapManager::convertMapNameToPath(const std::string& mapName, const std::string& extension) const\n{\n\tstd::regex whitespaceMatcher(\"\\\\s+\");\n\treturn std::regex_replace(mapName, whitespaceMatcher, \"-\") += extension;\n}\n\nstd::string MapManager::convertPathToMapName(const fs::path& filePath) const\n{\n\tstd::regex dashMatcher(\"-\");\n\treturn std::regex_replace(filePath.stem().string(), dashMatcher, \" \");\n}\n\nvoid MapManager::createAndSaveMapPreview(const std::string mapName, const MapDto& dto)\n{\n\tsf::RenderTexture renderTexture;\n\trenderTexture.create(\n\t\t\tstatic_cast<unsigned int>(dto.board->getWidth() * SQUARE_DIMENSION),\n\t\t\tstatic_cast<unsigned int>(dto.board->getHeight() * SQUARE_DIMENSION));\n\n\tdto.board->getComponent<SpriteComponent>()->render(renderTexture);\n\tfor(auto& structureIter : dto.board->getStructures())\n\t\tstructureIter.second->getComponent<SpriteComponent>()->render(renderTexture);\n\tfor(auto& terrainIter : dto.board->getTerrains())\n\t\tterrainIter.second->getComponent<SpriteComponent>()->render(renderTexture);\n\tfor(auto& deploymentZone : dto.deploymentZones)\n\t\tdeploymentZone->render(renderTexture);\n\n\trenderTexture.display();\n\trenderTexture.getTexture().copyToImage().saveToFile(getUserMapDir() \/ (convertMapNameToPath(mapName, \".png\")));\n}\n\nsf::Texture* MapManager::loadMapPreview(const std::string& mapName)\n{\n\tsf::Texture* image = new sf::Texture();\n\tfs::path previewPath = getUserMapDir() \/ (convertMapNameToPath(mapName, \".png\"));\n\tstd::cerr << \"Loading map preview from '\" << previewPath << \"'\" << std::endl << std::flush;\n\tif(!image->loadFromFile(previewPath))\n\t\tstd::cerr << \"Failed to load map preview from '\" << previewPath << \"'\" << std::endl << std::flush;\n\n\treturn image;\n}\n\nfs::path MapManager::getUserMapDir() const\n{\n\treturn std::string(getenv(\"HOME\")) + \"\/.qrw\/maps\";\n}\n\n} \/\/ namespace qrw\n<commit_msg>Only treat files with '.map' extension as maps<commit_after>#include \"game\/skirmish\/mapmanager.hpp\"\n\n#include <cstdlib>\n#include <fstream>\n#include <regex>\n\n#include <SFML\/Graphics\/Texture.hpp>\n#include <SFML\/Graphics\/RenderTexture.hpp>\n\n#include \"foundation\/spritecomponent.hpp\"\n\n#include \"meta\/metamanager.hpp\"\n\n#include \"engine\/board.hpp\"\n#include \"game\/constants.hpp\"\n#include \"game\/deploymentzone.hpp\"\n#include \"game\/skirmish\/structure.hpp\"\n#include \"engine\/terrain.hpp\"\n\nnamespace fs = std::experimental::filesystem;\n\nnamespace qrw\n{\n\nMapManager::MapManager(MetaManager& metaManager)\n : metaManager_(metaManager),\n\tmapValidator_(new MapValidator())\n{\n}\n\nMapManager::~MapManager()\n{\n}\n\nMapDto MapManager::loadMap(\n\tconst std::string& mapName,\n\tLoadErrors& error)\n{\n\tMapDto mapDto;\n\n\tif(!doesMapExist(mapName))\n\t{\n\t\terror = LoadErrors::MAP_NOT_FOUND;\n\t\treturn mapDto;\n\t}\n\n\tstd::vector<YAML::Node> documents = YAML::LoadAllFromFile(getUserMapDir() \/ convertMapNameToPath(mapName, \".map\"));\n\tif(!mapValidator_->validate(documents))\n\t{\n\t\terror = LoadErrors::MAP_VALIDATION_FAILED;\n\t\treturn mapDto;\n\t}\n\n\tYAML::Node gameObjectsNode = documents.at(1);\n\n\tfor(auto node : gameObjectsNode)\n\t{\n\t\tauto gameObject = metaManager_.deserialize(node);\n\n\t\tif(auto zone = dynamic_cast<DeploymentZone*>(gameObject))\n\t\t{\n\t\t\tmapDto.deploymentZones.push_back(zone);\n\t\t}\n\t\telse if(auto board = dynamic_cast<Board*>(gameObject))\n\t\t{\n\t\t\tmapDto.board = board;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"Found unsupported game object in map \\'\"\n\t\t\t\t\t<< mapName << \"\\': \"\n\t\t\t\t \t<< node[MetaClass::TYPE_NAME_YAML_KEY].as<std::string>() << std::endl << std::flush;\n\t\t}\n\t}\n\n\terror = LoadErrors::SUCCESS;\n\treturn mapDto;\n}\n\nbool MapManager::doesMapExist(const std::string& mapName)\n{\n\tfs::path mapFilePath = getUserMapDir() \/ convertMapNameToPath(mapName, \".map\");\n\n\treturn fs::exists(mapFilePath);\n}\n\nvoid MapManager::saveMap(\n\tconst std::string& mapName,\n\tconst MapDto& dto)\n{\n\tconst std::string fileName = convertMapNameToPath(mapName, \".map\");\n\n\tYAML::Emitter yaml;\n\tyaml << YAML::BeginDoc\n\t\t << YAML::Comment(\"Description\")\n\t\t << YAML::BeginMap\n\t\t\t<< YAML::Key << \"name\" << YAML::Value << mapName\n\t\t\t<< YAML::Key << \"short-description\" << YAML::Value << \"Here goes the short description\"\n\t\t\t<< YAML::Key << \"playerCount\" << YAML::Value << 2\n\t << YAML::EndMap;\n\n\tyaml << YAML::BeginDoc\n\t\t << YAML::BeginSeq;\n\t\t\tmetaManager_.serialize(dto.board, yaml);\n\t\t\tfor(auto& zone : dto.deploymentZones)\n\t\t\t\tmetaManager_.serialize(zone, yaml);\n\tyaml << YAML::EndSeq;\n\n\tstd::ofstream mapFile;\n\tfs::path userMapDir = getUserMapDir();\n\n\tif(!fs::exists(userMapDir))\n\t\tfs::create_directories(userMapDir);\n\n\tmapFile.open(userMapDir \/ fileName, std::ofstream::out | std::ofstream::trunc);\n\tmapFile << yaml.c_str() << std::endl;\n\tmapFile.close();\n\n\tcreateAndSaveMapPreview(mapName, dto);\n}\n\nstd::vector<std::string> MapManager::getMapList() const\n{\n\tstd::vector<std::string> mapNames;\n\n\tfor(auto& p : fs::directory_iterator(getUserMapDir()))\n\t{\n\t\tif(p.path().extension().compare(\".map\") == 0)\n\t\t\tmapNames.push_back(convertPathToMapName(p));\n\t}\n\n\treturn mapNames;\n}\n\nstd::string MapManager::convertMapNameToPath(const std::string& mapName, const std::string& extension) const\n{\n\tstd::regex whitespaceMatcher(\"\\\\s+\");\n\treturn std::regex_replace(mapName, whitespaceMatcher, \"-\") += extension;\n}\n\nstd::string MapManager::convertPathToMapName(const fs::path& filePath) const\n{\n\tstd::regex dashMatcher(\"-\");\n\treturn std::regex_replace(filePath.stem().string(), dashMatcher, \" \");\n}\n\nvoid MapManager::createAndSaveMapPreview(const std::string mapName, const MapDto& dto)\n{\n\tsf::RenderTexture renderTexture;\n\trenderTexture.create(\n\t\t\tstatic_cast<unsigned int>(dto.board->getWidth() * SQUARE_DIMENSION),\n\t\t\tstatic_cast<unsigned int>(dto.board->getHeight() * SQUARE_DIMENSION));\n\n\tdto.board->getComponent<SpriteComponent>()->render(renderTexture);\n\tfor(auto& structureIter : dto.board->getStructures())\n\t\tstructureIter.second->getComponent<SpriteComponent>()->render(renderTexture);\n\tfor(auto& terrainIter : dto.board->getTerrains())\n\t\tterrainIter.second->getComponent<SpriteComponent>()->render(renderTexture);\n\tfor(auto& deploymentZone : dto.deploymentZones)\n\t\tdeploymentZone->render(renderTexture);\n\n\trenderTexture.display();\n\trenderTexture.getTexture().copyToImage().saveToFile(getUserMapDir() \/ (convertMapNameToPath(mapName, \".png\")));\n}\n\nsf::Texture* MapManager::loadMapPreview(const std::string& mapName)\n{\n\tsf::Texture* image = new sf::Texture();\n\tfs::path previewPath = getUserMapDir() \/ (convertMapNameToPath(mapName, \".png\"));\n\tstd::cerr << \"Loading map preview from '\" << previewPath << \"'\" << std::endl << std::flush;\n\tif(!image->loadFromFile(previewPath))\n\t\tstd::cerr << \"Failed to load map preview from '\" << previewPath << \"'\" << std::endl << std::flush;\n\n\treturn image;\n}\n\nfs::path MapManager::getUserMapDir() const\n{\n\treturn std::string(getenv(\"HOME\")) + \"\/.qrw\/maps\";\n}\n\n} \/\/ namespace qrw\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2013, Regents of the University of Alaska\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * Neither the name of the Geographic Information Network of Alaska nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThis code was developed by Dan Stahlke for the Geographic Information Network of Alaska.\n*\/\n\n\n\n#include \"common.h\"\n#include \"polygon.h\"\n#include \"debugplot.h\"\n\nusing namespace dangdal;\n\nvoid plot_points(const Ring &pl, const std::string &fn);\n\nstruct PointStats {\n\tPointStats() : \n\t\ttotal(0),\n\t\tproj_ok(0),\n\t\tcontained(0)\n\t{ }\n\n\tvoid printYaml(const char *label) {\n\t\tprintf(\"%s:\\n\", label);\n\t\tprintf(\" total: %zd\\n\", total);\n\t\tprintf(\" proj_ok: %zd\\n\", proj_ok);\n\t\tprintf(\" contained: %zd\\n\", contained);\n\t}\n\n\tsize_t total;\n\tsize_t proj_ok;\n\tsize_t contained;\n};\n\nvoid usage(const std::string &cmdname) {\n\tprintf(\"Usage: %s [options] \\n\", cmdname.c_str());\n\tprintf(\" -s_wkt <fn> File containing WKT of source region\\n\");\n\tprintf(\" -t_bounds_wkt <fn> File containing WKT for valid region of target SRS (optional)\\n\");\n\tprintf(\" -s_srs <srs_def> Source SRS\\n\");\n\tprintf(\" -t_srs <srs_def> Target SRS\\n\");\n\tprintf(\" -report <out.ppm> Ouput a graphical report (optional)\\n\");\n\tprintf(\"\\nOutput is the envelope of the source region projected into the target SRS.\\n\");\n\tprintf(\"If the -t_bounds_wkt option is given it will be used as a clip mask in the\\n\");\n\tprintf(\"projected space.\\n\");\n\tprintf(\"\\n\");\n\t\n\texit(1);\n}\n\n\/\/ This function transforms a point, and then as a check transforms it back to\n\/\/ see if it comes back to the same place. This allows us to detect cases\n\/\/ where OCTTransform reports success when really it just returned some\n\/\/ meaningless result.\nbool picky_transform(\n\tOGRCoordinateTransformationH fwd_xform,\n\tOGRCoordinateTransformationH inv_xform,\n\tVertex *v_in\n) {\n\t\/\/ tolerance in meters, could probably be much smaller\n\tconst double toler = 1.0;\n\n\tVertex v_out = *v_in;\n\tif(!OCTTransform(fwd_xform, 1, &v_out.x, &v_out.y, NULL)) {\n\t\treturn 0;\n\t}\n\n\tVertex v_back = v_out;\n\tif(!OCTTransform(inv_xform, 1, &v_back.x, &v_back.y, NULL)) {\n\t\treturn 0;\n\t}\n\n\tdouble err = hypot(v_in->x - v_back.x, v_in->y - v_back.y);\n\t\/\/fprintf(stderr, \"err=%g\\n\", err);\n\tif(err > toler) {\n\t\treturn 0;\n\t}\n\n\t*v_in = v_out;\n\treturn 1;\n}\n\nint main(int argc, char **argv) {\n\tconst std::string cmdname = argv[0];\n\tif(argc == 1) usage(cmdname);\n\tstd::vector<std::string> arg_list = argv_to_list(argc, argv);\n\n\tstd::string src_wkt_fn;\n\tstd::string t_bounds_wkt_fn;\n\tstd::string s_srs;\n\tstd::string t_srs;\n\tstd::string report_fn;\n\n\tsize_t argp = 1;\n\twhile(argp < arg_list.size()) {\n\t\tconst std::string &arg = arg_list[argp++];\n\t\t\/\/ FIXME - check duplicate values\n\t\tif(arg[0] == '-') {\n\t\t\tif(arg == \"-v\") {\n\t\t\t\tVERBOSE++;\n\t\t\t} else if(arg == \"-s_wkt\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\tsrc_wkt_fn = arg_list[argp++];\n\t\t\t} else if(arg == \"-t_bounds_wkt\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\tt_bounds_wkt_fn = arg_list[argp++];\n\t\t\t} else if(arg == \"-s_srs\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\ts_srs = arg_list[argp++];\n\t\t\t} else if(arg == \"-t_srs\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\tt_srs = arg_list[argp++];\n\t\t\t} else if(arg == \"-report\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\treport_fn = arg_list[argp++];\n\t\t\t} else {\n\t\t\t\tusage(cmdname);\n\t\t\t}\n\t\t} else {\n\t\t\tusage(cmdname);\n\t\t}\n\t}\n\n\tif(src_wkt_fn.empty() || s_srs.empty() || t_srs.empty()) usage(cmdname);\n\n\tGDALAllRegister();\n\n\tCPLPushErrorHandler(CPLQuietErrorHandler);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\tOGRSpatialReferenceH s_sref = OSRNewSpatialReference(NULL);\n\tif(OSRImportFromProj4(s_sref, s_srs.c_str()) != OGRERR_NONE)\n\t\tfatal_error(\"cannot parse proj4 definition for -s_srs\");\n\n\tOGRSpatialReferenceH t_sref = OSRNewSpatialReference(NULL);\n\tif(OSRImportFromProj4(t_sref, t_srs.c_str()) != OGRERR_NONE)\n\t\tfatal_error(\"cannot parse proj4 definition for -t_srs\");\n\n\tOGRCoordinateTransformationH fwd_xform = \n\t\tOCTNewCoordinateTransformation(s_sref, t_sref);\n\tOGRCoordinateTransformationH inv_xform = \n\t\tOCTNewCoordinateTransformation(t_sref, s_sref);\n\n\tMpoly src_mp = mpoly_from_wktfile(src_wkt_fn);\n\tBbox src_bbox = src_mp.getBbox();\n\n\tMpoly t_bounds_mp;\n\tbool use_t_bounds;\n\tBbox t_bounds_bbox;\n\tif(t_bounds_wkt_fn.size()) {\n\t\tuse_t_bounds = 1;\n\t\tt_bounds_mp = mpoly_from_wktfile(t_bounds_wkt_fn);\n\t\tt_bounds_bbox = t_bounds_mp.getBbox();\n\t} else {\n\t\tuse_t_bounds = 0;\n\t}\n\n\tRing pl;\n\n\tPointStats ps_border;\n\tPointStats ps_interior;\n\tPointStats ps_bounds;\n\n\t\/\/ Sample a regular grid of points, take the ones within the source region,\n\t\/\/ and project them to the target projection. This is done to handle the\n\t\/\/ cases where the projected border does not necessarily encircle the\n\t\/\/ source region (such as would be the case for a source region that\n\t\/\/ encircles the pole with a target lonlat projection).\n\tint num_grid_steps = 100;\n\tfor(int grid_xi=0; grid_xi<=num_grid_steps; grid_xi++) {\n\t\tVertex src_pt;\n\t\tdouble alpha_x = (double)grid_xi \/ (double)num_grid_steps;\n\t\tsrc_pt.x = src_bbox.min_x + (src_bbox.max_x - src_bbox.min_x) * alpha_x;\n\t\tfor(int grid_yi=0; grid_yi<=num_grid_steps; grid_yi++) {\n\t\t\tdouble alpha_y = (double)grid_yi \/ (double)num_grid_steps;\n\t\t\tsrc_pt.y = src_bbox.min_y + (src_bbox.max_y - src_bbox.min_y) * alpha_y;\n\t\t\tif(!src_mp.contains(src_pt)) continue;\n\n\t\t\tps_interior.total++;\n\n\t\t\tVertex tgt_pt = src_pt;\n\t\t\tif(!picky_transform(fwd_xform, inv_xform, &tgt_pt)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tps_interior.proj_ok++;\n\n\t\t\tif(!use_t_bounds || t_bounds_mp.contains(tgt_pt)) {\n\t\t\t\tps_interior.contained++;\n\t\t\t\tpl.pts.push_back(tgt_pt);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Project points along the source region border to the target projection.\n\tdouble max_step_len = std::max(\n\t\tsrc_bbox.max_x - src_bbox.min_x,\n\t\tsrc_bbox.max_y - src_bbox.min_y) \/ 1000.0;\n\tfor(size_t r_idx=0; r_idx<src_mp.rings.size(); r_idx++) {\n\t\tconst Ring &ring = src_mp.rings[r_idx];\n\t\tfor(size_t v_idx=0; v_idx<ring.pts.size(); v_idx++) {\n\t\t\tVertex v1 = ring.pts[v_idx];\n\t\t\tVertex v2 = ring.pts[(v_idx+1) % ring.pts.size()];\n\t\t\tdouble dx = v2.x - v1.x;\n\t\t\tdouble dy = v2.y - v1.y;\n\t\t\tdouble len = sqrt(dx*dx + dy*dy);\n\t\t\tint num_steps = 1 + (int)(len \/ max_step_len);\n\t\t\tfor(int step=0; step<=num_steps; step++) {\n\t\t\t\tdouble alpha = (double)step \/ (double)num_steps;\n\t\t\t\tVertex src_pt;\n\t\t\t\tsrc_pt.x = v1.x + dx * alpha;\n\t\t\t\tsrc_pt.y = v1.y + dy * alpha;\n\n\t\t\t\tps_border.total++;\n\n\t\t\t\tVertex tgt_pt = src_pt;\n\t\t\t\tif(!picky_transform(fwd_xform, inv_xform, &tgt_pt)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tps_border.proj_ok++;\n\n\t\t\t\tif(!use_t_bounds || t_bounds_mp.contains(tgt_pt)) {\n\t\t\t\t\tps_border.contained++;\n\t\t\t\t\tpl.pts.push_back(tgt_pt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Take points along the border of the t_bounds clip shape that lie within the\n\t\/\/ source region.\n\tif(use_t_bounds) {\n\t\tdouble max_step_len = std::max(\n\t\t\tt_bounds_bbox.max_x - t_bounds_bbox.min_x,\n\t\t\tt_bounds_bbox.max_y - t_bounds_bbox.min_y) \/ 1000.0;\n\t\tfor(size_t r_idx=0; r_idx<t_bounds_mp.rings.size(); r_idx++) {\n\t\t\tconst Ring &ring = t_bounds_mp.rings[r_idx];\n\t\t\tfor(size_t v_idx=0; v_idx<ring.pts.size(); v_idx++) {\n\t\t\t\tVertex v1 = ring.pts[v_idx];\n\t\t\t\tVertex v2 = ring.pts[(v_idx+1) % ring.pts.size()];\n\t\t\t\tdouble dx = v2.x - v1.x;\n\t\t\t\tdouble dy = v2.y - v1.y;\n\t\t\t\tdouble len = sqrt(dx*dx + dy*dy);\n\t\t\t\tint num_steps = 1 + (int)(len \/ max_step_len);\n\t\t\t\tfor(int step=0; step<=num_steps; step++) {\n\t\t\t\t\tdouble alpha = (double)step \/ (double)num_steps;\n\t\t\t\t\tVertex tgt_pt;\n\t\t\t\t\ttgt_pt.x = v1.x + dx * alpha;\n\t\t\t\t\ttgt_pt.y = v1.y + dy * alpha;\n\n\t\t\t\t\tps_bounds.total++;\n\n\t\t\t\t\tVertex src_pt = tgt_pt;\n\t\t\t\t\tif(!picky_transform(inv_xform, fwd_xform, &src_pt)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tps_bounds.proj_ok++;\n\n\t\t\t\t\tif(src_mp.contains(src_pt)) {\n\t\t\t\t\t\tps_bounds.contained++;\n\t\t\t\t\t\tpl.pts.push_back(tgt_pt);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/bool debug = 1;\n\t\/\/if(debug) {\n\t\/\/\tps_border.printYaml(\"stats_border\");\n\t\/\/\tps_interior.printYaml(\"stats_interior\");\n\t\/\/\tps_bounds.printYaml(\"stats_bounds\");\n\t\/\/}\n\n\t\/\/fprintf(stderr, \"got %zd points\\n\", pl.npts);\n\tBbox bbox = pl.getBbox();\n\tprintf(\"bounds:\\n\");\n\tprintf(\" min_e: %.15f\\n\", bbox.min_x);\n\tprintf(\" min_n: %.15f\\n\", bbox.min_y);\n\tprintf(\" max_e: %.15f\\n\", bbox.max_x);\n\tprintf(\" max_n: %.15f\\n\", bbox.max_y);\n\n\tif(report_fn.size()) plot_points(pl, report_fn);\n\n\treturn 0;\n}\n\nvoid plot_points(const Ring &pl, const std::string &fn) {\n\tBbox bbox = pl.getBbox();\n\tbbox.min_x -= (bbox.max_x - bbox.min_x) * .05;\n\tbbox.max_x += (bbox.max_x - bbox.min_x) * .05;\n\tbbox.min_y -= (bbox.max_y - bbox.min_y) * .05;\n\tbbox.max_y += (bbox.max_y - bbox.min_y) * .05;\n\tdouble W = bbox.max_x - bbox.min_x;\n\tdouble H = bbox.max_y - bbox.min_y;\n\tDebugPlot dbuf(W, H, PLOT_NORMAL);\n\tfor(size_t i=0; i<pl.pts.size(); i++) {\n\t\tVertex v = pl.pts[i];\n\t\tdouble x = v.x - bbox.min_x;\n\t\tdouble y = bbox.max_y - v.y;\n\t\tdbuf.plotPoint(x, y, 255, 255, 255);\n\t}\n\tdbuf.writePlot(fn);\n}\n<commit_msg>Fix 'Ouput' typo, replace with 'Output'.<commit_after>\/*\nCopyright (c) 2013, Regents of the University of Alaska\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * Neither the name of the Geographic Information Network of Alaska nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThis code was developed by Dan Stahlke for the Geographic Information Network of Alaska.\n*\/\n\n\n\n#include \"common.h\"\n#include \"polygon.h\"\n#include \"debugplot.h\"\n\nusing namespace dangdal;\n\nvoid plot_points(const Ring &pl, const std::string &fn);\n\nstruct PointStats {\n\tPointStats() : \n\t\ttotal(0),\n\t\tproj_ok(0),\n\t\tcontained(0)\n\t{ }\n\n\tvoid printYaml(const char *label) {\n\t\tprintf(\"%s:\\n\", label);\n\t\tprintf(\" total: %zd\\n\", total);\n\t\tprintf(\" proj_ok: %zd\\n\", proj_ok);\n\t\tprintf(\" contained: %zd\\n\", contained);\n\t}\n\n\tsize_t total;\n\tsize_t proj_ok;\n\tsize_t contained;\n};\n\nvoid usage(const std::string &cmdname) {\n\tprintf(\"Usage: %s [options] \\n\", cmdname.c_str());\n\tprintf(\" -s_wkt <fn> File containing WKT of source region\\n\");\n\tprintf(\" -t_bounds_wkt <fn> File containing WKT for valid region of target SRS (optional)\\n\");\n\tprintf(\" -s_srs <srs_def> Source SRS\\n\");\n\tprintf(\" -t_srs <srs_def> Target SRS\\n\");\n\tprintf(\" -report <out.ppm> Output a graphical report (optional)\\n\");\n\tprintf(\"\\nOutput is the envelope of the source region projected into the target SRS.\\n\");\n\tprintf(\"If the -t_bounds_wkt option is given it will be used as a clip mask in the\\n\");\n\tprintf(\"projected space.\\n\");\n\tprintf(\"\\n\");\n\t\n\texit(1);\n}\n\n\/\/ This function transforms a point, and then as a check transforms it back to\n\/\/ see if it comes back to the same place. This allows us to detect cases\n\/\/ where OCTTransform reports success when really it just returned some\n\/\/ meaningless result.\nbool picky_transform(\n\tOGRCoordinateTransformationH fwd_xform,\n\tOGRCoordinateTransformationH inv_xform,\n\tVertex *v_in\n) {\n\t\/\/ tolerance in meters, could probably be much smaller\n\tconst double toler = 1.0;\n\n\tVertex v_out = *v_in;\n\tif(!OCTTransform(fwd_xform, 1, &v_out.x, &v_out.y, NULL)) {\n\t\treturn 0;\n\t}\n\n\tVertex v_back = v_out;\n\tif(!OCTTransform(inv_xform, 1, &v_back.x, &v_back.y, NULL)) {\n\t\treturn 0;\n\t}\n\n\tdouble err = hypot(v_in->x - v_back.x, v_in->y - v_back.y);\n\t\/\/fprintf(stderr, \"err=%g\\n\", err);\n\tif(err > toler) {\n\t\treturn 0;\n\t}\n\n\t*v_in = v_out;\n\treturn 1;\n}\n\nint main(int argc, char **argv) {\n\tconst std::string cmdname = argv[0];\n\tif(argc == 1) usage(cmdname);\n\tstd::vector<std::string> arg_list = argv_to_list(argc, argv);\n\n\tstd::string src_wkt_fn;\n\tstd::string t_bounds_wkt_fn;\n\tstd::string s_srs;\n\tstd::string t_srs;\n\tstd::string report_fn;\n\n\tsize_t argp = 1;\n\twhile(argp < arg_list.size()) {\n\t\tconst std::string &arg = arg_list[argp++];\n\t\t\/\/ FIXME - check duplicate values\n\t\tif(arg[0] == '-') {\n\t\t\tif(arg == \"-v\") {\n\t\t\t\tVERBOSE++;\n\t\t\t} else if(arg == \"-s_wkt\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\tsrc_wkt_fn = arg_list[argp++];\n\t\t\t} else if(arg == \"-t_bounds_wkt\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\tt_bounds_wkt_fn = arg_list[argp++];\n\t\t\t} else if(arg == \"-s_srs\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\ts_srs = arg_list[argp++];\n\t\t\t} else if(arg == \"-t_srs\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\tt_srs = arg_list[argp++];\n\t\t\t} else if(arg == \"-report\") {\n\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\treport_fn = arg_list[argp++];\n\t\t\t} else {\n\t\t\t\tusage(cmdname);\n\t\t\t}\n\t\t} else {\n\t\t\tusage(cmdname);\n\t\t}\n\t}\n\n\tif(src_wkt_fn.empty() || s_srs.empty() || t_srs.empty()) usage(cmdname);\n\n\tGDALAllRegister();\n\n\tCPLPushErrorHandler(CPLQuietErrorHandler);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\tOGRSpatialReferenceH s_sref = OSRNewSpatialReference(NULL);\n\tif(OSRImportFromProj4(s_sref, s_srs.c_str()) != OGRERR_NONE)\n\t\tfatal_error(\"cannot parse proj4 definition for -s_srs\");\n\n\tOGRSpatialReferenceH t_sref = OSRNewSpatialReference(NULL);\n\tif(OSRImportFromProj4(t_sref, t_srs.c_str()) != OGRERR_NONE)\n\t\tfatal_error(\"cannot parse proj4 definition for -t_srs\");\n\n\tOGRCoordinateTransformationH fwd_xform = \n\t\tOCTNewCoordinateTransformation(s_sref, t_sref);\n\tOGRCoordinateTransformationH inv_xform = \n\t\tOCTNewCoordinateTransformation(t_sref, s_sref);\n\n\tMpoly src_mp = mpoly_from_wktfile(src_wkt_fn);\n\tBbox src_bbox = src_mp.getBbox();\n\n\tMpoly t_bounds_mp;\n\tbool use_t_bounds;\n\tBbox t_bounds_bbox;\n\tif(t_bounds_wkt_fn.size()) {\n\t\tuse_t_bounds = 1;\n\t\tt_bounds_mp = mpoly_from_wktfile(t_bounds_wkt_fn);\n\t\tt_bounds_bbox = t_bounds_mp.getBbox();\n\t} else {\n\t\tuse_t_bounds = 0;\n\t}\n\n\tRing pl;\n\n\tPointStats ps_border;\n\tPointStats ps_interior;\n\tPointStats ps_bounds;\n\n\t\/\/ Sample a regular grid of points, take the ones within the source region,\n\t\/\/ and project them to the target projection. This is done to handle the\n\t\/\/ cases where the projected border does not necessarily encircle the\n\t\/\/ source region (such as would be the case for a source region that\n\t\/\/ encircles the pole with a target lonlat projection).\n\tint num_grid_steps = 100;\n\tfor(int grid_xi=0; grid_xi<=num_grid_steps; grid_xi++) {\n\t\tVertex src_pt;\n\t\tdouble alpha_x = (double)grid_xi \/ (double)num_grid_steps;\n\t\tsrc_pt.x = src_bbox.min_x + (src_bbox.max_x - src_bbox.min_x) * alpha_x;\n\t\tfor(int grid_yi=0; grid_yi<=num_grid_steps; grid_yi++) {\n\t\t\tdouble alpha_y = (double)grid_yi \/ (double)num_grid_steps;\n\t\t\tsrc_pt.y = src_bbox.min_y + (src_bbox.max_y - src_bbox.min_y) * alpha_y;\n\t\t\tif(!src_mp.contains(src_pt)) continue;\n\n\t\t\tps_interior.total++;\n\n\t\t\tVertex tgt_pt = src_pt;\n\t\t\tif(!picky_transform(fwd_xform, inv_xform, &tgt_pt)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tps_interior.proj_ok++;\n\n\t\t\tif(!use_t_bounds || t_bounds_mp.contains(tgt_pt)) {\n\t\t\t\tps_interior.contained++;\n\t\t\t\tpl.pts.push_back(tgt_pt);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Project points along the source region border to the target projection.\n\tdouble max_step_len = std::max(\n\t\tsrc_bbox.max_x - src_bbox.min_x,\n\t\tsrc_bbox.max_y - src_bbox.min_y) \/ 1000.0;\n\tfor(size_t r_idx=0; r_idx<src_mp.rings.size(); r_idx++) {\n\t\tconst Ring &ring = src_mp.rings[r_idx];\n\t\tfor(size_t v_idx=0; v_idx<ring.pts.size(); v_idx++) {\n\t\t\tVertex v1 = ring.pts[v_idx];\n\t\t\tVertex v2 = ring.pts[(v_idx+1) % ring.pts.size()];\n\t\t\tdouble dx = v2.x - v1.x;\n\t\t\tdouble dy = v2.y - v1.y;\n\t\t\tdouble len = sqrt(dx*dx + dy*dy);\n\t\t\tint num_steps = 1 + (int)(len \/ max_step_len);\n\t\t\tfor(int step=0; step<=num_steps; step++) {\n\t\t\t\tdouble alpha = (double)step \/ (double)num_steps;\n\t\t\t\tVertex src_pt;\n\t\t\t\tsrc_pt.x = v1.x + dx * alpha;\n\t\t\t\tsrc_pt.y = v1.y + dy * alpha;\n\n\t\t\t\tps_border.total++;\n\n\t\t\t\tVertex tgt_pt = src_pt;\n\t\t\t\tif(!picky_transform(fwd_xform, inv_xform, &tgt_pt)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tps_border.proj_ok++;\n\n\t\t\t\tif(!use_t_bounds || t_bounds_mp.contains(tgt_pt)) {\n\t\t\t\t\tps_border.contained++;\n\t\t\t\t\tpl.pts.push_back(tgt_pt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Take points along the border of the t_bounds clip shape that lie within the\n\t\/\/ source region.\n\tif(use_t_bounds) {\n\t\tdouble max_step_len = std::max(\n\t\t\tt_bounds_bbox.max_x - t_bounds_bbox.min_x,\n\t\t\tt_bounds_bbox.max_y - t_bounds_bbox.min_y) \/ 1000.0;\n\t\tfor(size_t r_idx=0; r_idx<t_bounds_mp.rings.size(); r_idx++) {\n\t\t\tconst Ring &ring = t_bounds_mp.rings[r_idx];\n\t\t\tfor(size_t v_idx=0; v_idx<ring.pts.size(); v_idx++) {\n\t\t\t\tVertex v1 = ring.pts[v_idx];\n\t\t\t\tVertex v2 = ring.pts[(v_idx+1) % ring.pts.size()];\n\t\t\t\tdouble dx = v2.x - v1.x;\n\t\t\t\tdouble dy = v2.y - v1.y;\n\t\t\t\tdouble len = sqrt(dx*dx + dy*dy);\n\t\t\t\tint num_steps = 1 + (int)(len \/ max_step_len);\n\t\t\t\tfor(int step=0; step<=num_steps; step++) {\n\t\t\t\t\tdouble alpha = (double)step \/ (double)num_steps;\n\t\t\t\t\tVertex tgt_pt;\n\t\t\t\t\ttgt_pt.x = v1.x + dx * alpha;\n\t\t\t\t\ttgt_pt.y = v1.y + dy * alpha;\n\n\t\t\t\t\tps_bounds.total++;\n\n\t\t\t\t\tVertex src_pt = tgt_pt;\n\t\t\t\t\tif(!picky_transform(inv_xform, fwd_xform, &src_pt)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tps_bounds.proj_ok++;\n\n\t\t\t\t\tif(src_mp.contains(src_pt)) {\n\t\t\t\t\t\tps_bounds.contained++;\n\t\t\t\t\t\tpl.pts.push_back(tgt_pt);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/bool debug = 1;\n\t\/\/if(debug) {\n\t\/\/\tps_border.printYaml(\"stats_border\");\n\t\/\/\tps_interior.printYaml(\"stats_interior\");\n\t\/\/\tps_bounds.printYaml(\"stats_bounds\");\n\t\/\/}\n\n\t\/\/fprintf(stderr, \"got %zd points\\n\", pl.npts);\n\tBbox bbox = pl.getBbox();\n\tprintf(\"bounds:\\n\");\n\tprintf(\" min_e: %.15f\\n\", bbox.min_x);\n\tprintf(\" min_n: %.15f\\n\", bbox.min_y);\n\tprintf(\" max_e: %.15f\\n\", bbox.max_x);\n\tprintf(\" max_n: %.15f\\n\", bbox.max_y);\n\n\tif(report_fn.size()) plot_points(pl, report_fn);\n\n\treturn 0;\n}\n\nvoid plot_points(const Ring &pl, const std::string &fn) {\n\tBbox bbox = pl.getBbox();\n\tbbox.min_x -= (bbox.max_x - bbox.min_x) * .05;\n\tbbox.max_x += (bbox.max_x - bbox.min_x) * .05;\n\tbbox.min_y -= (bbox.max_y - bbox.min_y) * .05;\n\tbbox.max_y += (bbox.max_y - bbox.min_y) * .05;\n\tdouble W = bbox.max_x - bbox.min_x;\n\tdouble H = bbox.max_y - bbox.min_y;\n\tDebugPlot dbuf(W, H, PLOT_NORMAL);\n\tfor(size_t i=0; i<pl.pts.size(); i++) {\n\t\tVertex v = pl.pts[i];\n\t\tdouble x = v.x - bbox.min_x;\n\t\tdouble y = bbox.max_y - v.y;\n\t\tdbuf.plotPoint(x, y, 255, 255, 255);\n\t}\n\tdbuf.writePlot(fn);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: proxy.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: svesik $ $Date: 2004-04-21 13:43:44 $\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#if OSL_DEBUG_LEVEL == 0\n# ifndef NDEBUG\n# define NDEBUG\n# endif\n#endif\n#include <assert.h>\n#include <sal\/alloca.h>\n#include <bridges\/remote\/proxy.hxx>\n#include <bridges\/remote\/context.h>\n\n#include <uno\/data.h>\n#include <uno\/mapping.hxx>\n#include <uno\/environment.h>\n\n#include <com\/sun\/star\/uno\/Any.hxx>\n\n#include <bridges\/remote\/bridgeimpl.hxx>\n\n#include \"remote_types.hxx\"\n\n#if OSL_DEBUG_LEVEL > 1\n#include <bridges\/remote\/counter.hxx>\nstatic MyCounter thisCounter( \"DEBUG : Remote2UnoProxy\");\n#endif\n\nusing namespace ::bridges_remote;\nusing namespace ::com::sun::star::uno;\n\nnamespace bridges_remote {\n\nvoid Remote2UnoProxy::thisFree( uno_ExtEnvironment *pEnvUno , void *pThis )\n{\n delete (Remote2UnoProxy*) pThis;\n}\n\nvoid Remote2UnoProxy::thisAcquire( uno_Interface *pThis )\n{\n Remote2UnoProxy *p = ( Remote2UnoProxy * ) pThis;\n if( 1 == osl_incrementInterlockedCount( &(p->m_nRef) ) )\n {\n p->m_pEnvUno->pExtEnv->registerProxyInterface(\n p->m_pEnvUno->pExtEnv,\n (void**)&pThis,\n Remote2UnoProxy::thisFree,\n p->m_sOid.pData,\n p->m_pType );\n assert( (uno_Interface *)p == pThis );\n }\n}\n\nvoid Remote2UnoProxy::thisRelease( uno_Interface *pThis )\n{\n Remote2UnoProxy *p = ( Remote2UnoProxy * ) pThis;\n if ( 0 == osl_decrementInterlockedCount( &(p->m_nRef) ))\n {\n p->m_pEnvUno->pExtEnv->revokeInterface( p->m_pEnvUno->pExtEnv, p );\n }\n}\n\nvoid SAL_CALL remote_release( void *pRemoteI )\n{\n ((remote_Interface * )pRemoteI)->release( (remote_Interface * ) pRemoteI );\n}\n\nvoid Remote2UnoProxy::thisDispatch(\n uno_Interface * pUnoI,\n typelib_TypeDescription * pType,\n void * pReturn,\n void * ppArgs[],\n uno_Any ** ppException )\n{\n Remote2UnoProxy *p = ( Remote2UnoProxy * ) pUnoI;\n RemoteThreadCounter counter( p->m_pEnvRemote );\n\n typelib_InterfaceMethodTypeDescription *pMethodType = 0;\n typelib_InterfaceAttributeTypeDescription *pAttributeType = 0;\n typelib_TypeDescription *pReturnType = 0;\n typelib_TypeDescription **ppArgType = 0;\n sal_Int32 nArgCount = 0;\n sal_Bool *pbIsIn = 0;\n sal_Bool *pbIsOut = 0;\n sal_Bool *pbConversionNeeded = 0;\n sal_Bool bConversionNeededForReturn = 0;\n\n \/\/--------------------------------\n \/\/ Collect all needed types !\n \/\/--------------------------------\n if( typelib_TypeClass_INTERFACE_ATTRIBUTE == pType->eTypeClass )\n {\n pAttributeType = ( typelib_InterfaceAttributeTypeDescription * ) pType;\n if( pReturn )\n {\n TYPELIB_DANGER_GET( &pReturnType , pAttributeType->pAttributeTypeRef );\n bConversionNeededForReturn = remote_relatesToInterface( pReturnType );\n }\n else\n {\n nArgCount = 1;\n ppArgType = (typelib_TypeDescription **) alloca( sizeof( void * ) );\n pbIsIn = ( sal_Bool * ) alloca( sizeof( sal_Bool ) );\n pbIsOut = ( sal_Bool * ) alloca( sizeof( sal_Bool ) );\n pbConversionNeeded = ( sal_Bool *) alloca( sizeof( sal_Bool ) );\n\n pbIsIn[0] = sal_True;\n pbIsOut[0] = sal_False;\n ppArgType[0] = 0;\n TYPELIB_DANGER_GET( &( ppArgType[0] ) , pAttributeType->pAttributeTypeRef );\n pbConversionNeeded[0] = remote_relatesToInterface( ppArgType[0] );\n\n }\n }\n if( typelib_TypeClass_INTERFACE_METHOD == pType->eTypeClass )\n {\n pMethodType = ( typelib_InterfaceMethodTypeDescription * ) pType;\n TYPELIB_DANGER_GET( &pReturnType , pMethodType->pReturnTypeRef );\n bConversionNeededForReturn = remote_relatesToInterface( pReturnType );\n nArgCount = pMethodType->nParams;\n ppArgType = (typelib_TypeDescription **) alloca( sizeof( void * ) * nArgCount );\n pbIsIn = (sal_Bool * ) alloca( sizeof( sal_Bool ) * nArgCount );\n pbIsOut = (sal_Bool * ) alloca( sizeof( sal_Bool ) * nArgCount );\n pbConversionNeeded = ( sal_Bool *) alloca( sizeof( sal_Bool ) * nArgCount );\n sal_Int32 i;\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n ppArgType[i] = 0;\n TYPELIB_DANGER_GET( & (ppArgType[i]) , pMethodType->pParams[i].pTypeRef );\n pbIsIn[i] = pMethodType->pParams[i].bIn;\n pbIsOut[i] = pMethodType->pParams[i].bOut;\n pbConversionNeeded[i] = remote_relatesToInterface( ppArgType[i] );\n }\n }\n\n void *pRemoteReturn = 0;\n if( pReturnType )\n {\n if( bConversionNeededForReturn )\n {\n pRemoteReturn = alloca( pReturnType->nSize );\n }\n else\n {\n pRemoteReturn = pReturn;\n }\n }\n\n void ** ppRemoteArgs = 0;\n if( nArgCount )\n {\n ppRemoteArgs = (void**) alloca( sizeof( void * ) * nArgCount );\n }\n\n sal_Int32 i;\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n if( pbConversionNeeded[i] )\n {\n ppRemoteArgs[i] = alloca( ppArgType[i]->nSize );\n\n if( pbIsIn[i] ) {\n uno_copyAndConvertData(\n ppRemoteArgs[i],\n ppArgs[i],\n ppArgType[i],\n p->m_mapUno2Remote.get() );\n }\n }\n else\n {\n ppRemoteArgs[i] = ppArgs[i];\n }\n }\n\n uno_Any any;\n uno_Any *pAny = &any;\n\n p->m_pRemoteI->pDispatcher( p->m_pRemoteI,\n pType,\n pRemoteReturn,\n ppRemoteArgs,\n &pAny );\n\n if( ! pAny )\n {\n if( pReturn && bConversionNeededForReturn )\n {\n uno_copyAndConvertData(\n pReturn ,\n pRemoteReturn,\n pReturnType,\n p->m_mapRemote2Uno.get() );\n uno_destructData( pRemoteReturn , pReturnType , remote_release );\n }\n\n sal_Int32 i;\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n if( pbConversionNeeded[i] )\n {\n if( pbIsIn[i] ) {\n if( pbIsOut[i] ) {\n uno_destructData( ppArgs[i] ,\n ppArgType[i] ,\n 0 );\n uno_copyAndConvertData( ppArgs[i] ,\n ppRemoteArgs[i],\n ppArgType[i],\n p->m_mapRemote2Uno.get() );\n }\n }\n else \/\/ pure out\n {\n uno_copyAndConvertData( ppArgs[i] ,\n ppRemoteArgs[i],\n ppArgType[i],\n p->m_mapRemote2Uno.get() );\n }\n uno_destructData( ppRemoteArgs[i],\n ppArgType[i],\n remote_release );\n }\n }\n *ppException = 0;\n }\n else\n {\n \/\/ -----------------------\n \/\/ an exception occured\n \/\/ -----------------------\n typelib_TypeDescription *pAnyType = 0;\n getCppuType( (::com::sun::star::uno::Any*) 0 ).getDescription( &pAnyType );\n uno_copyAndConvertData( *ppException ,\n pAny ,\n pAnyType,\n p->m_mapRemote2Uno.get() );\n uno_destructData( pAny , pAnyType , remote_release );\n typelib_typedescription_release( pAnyType );\n\n \/\/ destruct remote in parameters ( out parameters have not been constructed )\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n if( pbConversionNeeded[i] && pbIsIn[i] )\n {\n uno_destructData( ppRemoteArgs[i],\n ppArgType[i],\n remote_release );\n }\n }\n }\n\n \/\/--------------------------\n \/\/ release all acquired types\n \/\/--------------------------\n if( pReturnType )\n {\n TYPELIB_DANGER_RELEASE( pReturnType );\n }\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n TYPELIB_DANGER_RELEASE( ppArgType[ i] );\n }\n\n}\n\nRemote2UnoProxy::Remote2UnoProxy( remote_Interface *pRemoteI,\n rtl_uString *pOid,\n typelib_InterfaceTypeDescription *pType,\n uno_Environment *pEnvUno,\n uno_Environment *pEnvRemote ) :\n m_sOid( pOid ),\n m_pType( pType ),\n m_pRemoteI( pRemoteI ),\n m_pEnvUno( pEnvUno ),\n m_pEnvRemote( pEnvRemote ),\n m_mapRemote2Uno( pEnvRemote, pEnvUno ),\n m_mapUno2Remote( pEnvUno , pEnvRemote ),\n m_nRef( 1 )\n{\n typelib_typedescription_acquire( (typelib_TypeDescription * ) m_pType );\n m_pEnvUno->acquire( m_pEnvUno );\n m_pEnvRemote->acquire( m_pEnvRemote );\n\n acquire = thisAcquire;\n release = thisRelease;\n pDispatcher = ( uno_DispatchMethod ) thisDispatch;\n\n m_pEnvRemote->pExtEnv->registerInterface(\n m_pEnvRemote->pExtEnv,\n (void**)&m_pRemoteI,\n m_sOid.pData,\n m_pType );\n m_pRemoteI->acquire( m_pRemoteI );\n\n#if OSL_DEBUG_LEVEL > 1\n thisCounter.acquire();\n#endif\n}\n\nRemote2UnoProxy::~Remote2UnoProxy()\n{\n \/\/ revoke external ref (oid)\n m_pEnvRemote->pExtEnv->revokeInterface( m_pEnvRemote->pExtEnv , m_pRemoteI );\n\n typelib_typedescription_release( (typelib_TypeDescription * )m_pType );\n m_pRemoteI->release( m_pRemoteI );\n m_pEnvUno->release( m_pEnvUno );\n m_pEnvRemote->release( m_pEnvRemote );\n#if OSL_DEBUG_LEVEL > 1\n thisCounter.release();\n#endif\n}\n\n} \/\/ end namespace bridge_remote\n<commit_msg>INTEGRATION: CWS ooo19126 (1.9.86); FILE MERGED 2005\/09\/05 17:07:50 rt 1.9.86.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: proxy.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 22:43:14 $\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#if OSL_DEBUG_LEVEL == 0\n# ifndef NDEBUG\n# define NDEBUG\n# endif\n#endif\n#include <assert.h>\n#include <sal\/alloca.h>\n#include <bridges\/remote\/proxy.hxx>\n#include <bridges\/remote\/context.h>\n\n#include <uno\/data.h>\n#include <uno\/mapping.hxx>\n#include <uno\/environment.h>\n\n#include <com\/sun\/star\/uno\/Any.hxx>\n\n#include <bridges\/remote\/bridgeimpl.hxx>\n\n#include \"remote_types.hxx\"\n\n#if OSL_DEBUG_LEVEL > 1\n#include <bridges\/remote\/counter.hxx>\nstatic MyCounter thisCounter( \"DEBUG : Remote2UnoProxy\");\n#endif\n\nusing namespace ::bridges_remote;\nusing namespace ::com::sun::star::uno;\n\nnamespace bridges_remote {\n\nvoid Remote2UnoProxy::thisFree( uno_ExtEnvironment *pEnvUno , void *pThis )\n{\n delete (Remote2UnoProxy*) pThis;\n}\n\nvoid Remote2UnoProxy::thisAcquire( uno_Interface *pThis )\n{\n Remote2UnoProxy *p = ( Remote2UnoProxy * ) pThis;\n if( 1 == osl_incrementInterlockedCount( &(p->m_nRef) ) )\n {\n p->m_pEnvUno->pExtEnv->registerProxyInterface(\n p->m_pEnvUno->pExtEnv,\n (void**)&pThis,\n Remote2UnoProxy::thisFree,\n p->m_sOid.pData,\n p->m_pType );\n assert( (uno_Interface *)p == pThis );\n }\n}\n\nvoid Remote2UnoProxy::thisRelease( uno_Interface *pThis )\n{\n Remote2UnoProxy *p = ( Remote2UnoProxy * ) pThis;\n if ( 0 == osl_decrementInterlockedCount( &(p->m_nRef) ))\n {\n p->m_pEnvUno->pExtEnv->revokeInterface( p->m_pEnvUno->pExtEnv, p );\n }\n}\n\nvoid SAL_CALL remote_release( void *pRemoteI )\n{\n ((remote_Interface * )pRemoteI)->release( (remote_Interface * ) pRemoteI );\n}\n\nvoid Remote2UnoProxy::thisDispatch(\n uno_Interface * pUnoI,\n typelib_TypeDescription * pType,\n void * pReturn,\n void * ppArgs[],\n uno_Any ** ppException )\n{\n Remote2UnoProxy *p = ( Remote2UnoProxy * ) pUnoI;\n RemoteThreadCounter counter( p->m_pEnvRemote );\n\n typelib_InterfaceMethodTypeDescription *pMethodType = 0;\n typelib_InterfaceAttributeTypeDescription *pAttributeType = 0;\n typelib_TypeDescription *pReturnType = 0;\n typelib_TypeDescription **ppArgType = 0;\n sal_Int32 nArgCount = 0;\n sal_Bool *pbIsIn = 0;\n sal_Bool *pbIsOut = 0;\n sal_Bool *pbConversionNeeded = 0;\n sal_Bool bConversionNeededForReturn = 0;\n\n \/\/--------------------------------\n \/\/ Collect all needed types !\n \/\/--------------------------------\n if( typelib_TypeClass_INTERFACE_ATTRIBUTE == pType->eTypeClass )\n {\n pAttributeType = ( typelib_InterfaceAttributeTypeDescription * ) pType;\n if( pReturn )\n {\n TYPELIB_DANGER_GET( &pReturnType , pAttributeType->pAttributeTypeRef );\n bConversionNeededForReturn = remote_relatesToInterface( pReturnType );\n }\n else\n {\n nArgCount = 1;\n ppArgType = (typelib_TypeDescription **) alloca( sizeof( void * ) );\n pbIsIn = ( sal_Bool * ) alloca( sizeof( sal_Bool ) );\n pbIsOut = ( sal_Bool * ) alloca( sizeof( sal_Bool ) );\n pbConversionNeeded = ( sal_Bool *) alloca( sizeof( sal_Bool ) );\n\n pbIsIn[0] = sal_True;\n pbIsOut[0] = sal_False;\n ppArgType[0] = 0;\n TYPELIB_DANGER_GET( &( ppArgType[0] ) , pAttributeType->pAttributeTypeRef );\n pbConversionNeeded[0] = remote_relatesToInterface( ppArgType[0] );\n\n }\n }\n if( typelib_TypeClass_INTERFACE_METHOD == pType->eTypeClass )\n {\n pMethodType = ( typelib_InterfaceMethodTypeDescription * ) pType;\n TYPELIB_DANGER_GET( &pReturnType , pMethodType->pReturnTypeRef );\n bConversionNeededForReturn = remote_relatesToInterface( pReturnType );\n nArgCount = pMethodType->nParams;\n ppArgType = (typelib_TypeDescription **) alloca( sizeof( void * ) * nArgCount );\n pbIsIn = (sal_Bool * ) alloca( sizeof( sal_Bool ) * nArgCount );\n pbIsOut = (sal_Bool * ) alloca( sizeof( sal_Bool ) * nArgCount );\n pbConversionNeeded = ( sal_Bool *) alloca( sizeof( sal_Bool ) * nArgCount );\n sal_Int32 i;\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n ppArgType[i] = 0;\n TYPELIB_DANGER_GET( & (ppArgType[i]) , pMethodType->pParams[i].pTypeRef );\n pbIsIn[i] = pMethodType->pParams[i].bIn;\n pbIsOut[i] = pMethodType->pParams[i].bOut;\n pbConversionNeeded[i] = remote_relatesToInterface( ppArgType[i] );\n }\n }\n\n void *pRemoteReturn = 0;\n if( pReturnType )\n {\n if( bConversionNeededForReturn )\n {\n pRemoteReturn = alloca( pReturnType->nSize );\n }\n else\n {\n pRemoteReturn = pReturn;\n }\n }\n\n void ** ppRemoteArgs = 0;\n if( nArgCount )\n {\n ppRemoteArgs = (void**) alloca( sizeof( void * ) * nArgCount );\n }\n\n sal_Int32 i;\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n if( pbConversionNeeded[i] )\n {\n ppRemoteArgs[i] = alloca( ppArgType[i]->nSize );\n\n if( pbIsIn[i] ) {\n uno_copyAndConvertData(\n ppRemoteArgs[i],\n ppArgs[i],\n ppArgType[i],\n p->m_mapUno2Remote.get() );\n }\n }\n else\n {\n ppRemoteArgs[i] = ppArgs[i];\n }\n }\n\n uno_Any any;\n uno_Any *pAny = &any;\n\n p->m_pRemoteI->pDispatcher( p->m_pRemoteI,\n pType,\n pRemoteReturn,\n ppRemoteArgs,\n &pAny );\n\n if( ! pAny )\n {\n if( pReturn && bConversionNeededForReturn )\n {\n uno_copyAndConvertData(\n pReturn ,\n pRemoteReturn,\n pReturnType,\n p->m_mapRemote2Uno.get() );\n uno_destructData( pRemoteReturn , pReturnType , remote_release );\n }\n\n sal_Int32 i;\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n if( pbConversionNeeded[i] )\n {\n if( pbIsIn[i] ) {\n if( pbIsOut[i] ) {\n uno_destructData( ppArgs[i] ,\n ppArgType[i] ,\n 0 );\n uno_copyAndConvertData( ppArgs[i] ,\n ppRemoteArgs[i],\n ppArgType[i],\n p->m_mapRemote2Uno.get() );\n }\n }\n else \/\/ pure out\n {\n uno_copyAndConvertData( ppArgs[i] ,\n ppRemoteArgs[i],\n ppArgType[i],\n p->m_mapRemote2Uno.get() );\n }\n uno_destructData( ppRemoteArgs[i],\n ppArgType[i],\n remote_release );\n }\n }\n *ppException = 0;\n }\n else\n {\n \/\/ -----------------------\n \/\/ an exception occured\n \/\/ -----------------------\n typelib_TypeDescription *pAnyType = 0;\n getCppuType( (::com::sun::star::uno::Any*) 0 ).getDescription( &pAnyType );\n uno_copyAndConvertData( *ppException ,\n pAny ,\n pAnyType,\n p->m_mapRemote2Uno.get() );\n uno_destructData( pAny , pAnyType , remote_release );\n typelib_typedescription_release( pAnyType );\n\n \/\/ destruct remote in parameters ( out parameters have not been constructed )\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n if( pbConversionNeeded[i] && pbIsIn[i] )\n {\n uno_destructData( ppRemoteArgs[i],\n ppArgType[i],\n remote_release );\n }\n }\n }\n\n \/\/--------------------------\n \/\/ release all acquired types\n \/\/--------------------------\n if( pReturnType )\n {\n TYPELIB_DANGER_RELEASE( pReturnType );\n }\n for( i = 0 ; i < nArgCount ; i ++ )\n {\n TYPELIB_DANGER_RELEASE( ppArgType[ i] );\n }\n\n}\n\nRemote2UnoProxy::Remote2UnoProxy( remote_Interface *pRemoteI,\n rtl_uString *pOid,\n typelib_InterfaceTypeDescription *pType,\n uno_Environment *pEnvUno,\n uno_Environment *pEnvRemote ) :\n m_sOid( pOid ),\n m_pType( pType ),\n m_pRemoteI( pRemoteI ),\n m_pEnvUno( pEnvUno ),\n m_pEnvRemote( pEnvRemote ),\n m_mapRemote2Uno( pEnvRemote, pEnvUno ),\n m_mapUno2Remote( pEnvUno , pEnvRemote ),\n m_nRef( 1 )\n{\n typelib_typedescription_acquire( (typelib_TypeDescription * ) m_pType );\n m_pEnvUno->acquire( m_pEnvUno );\n m_pEnvRemote->acquire( m_pEnvRemote );\n\n acquire = thisAcquire;\n release = thisRelease;\n pDispatcher = ( uno_DispatchMethod ) thisDispatch;\n\n m_pEnvRemote->pExtEnv->registerInterface(\n m_pEnvRemote->pExtEnv,\n (void**)&m_pRemoteI,\n m_sOid.pData,\n m_pType );\n m_pRemoteI->acquire( m_pRemoteI );\n\n#if OSL_DEBUG_LEVEL > 1\n thisCounter.acquire();\n#endif\n}\n\nRemote2UnoProxy::~Remote2UnoProxy()\n{\n \/\/ revoke external ref (oid)\n m_pEnvRemote->pExtEnv->revokeInterface( m_pEnvRemote->pExtEnv , m_pRemoteI );\n\n typelib_typedescription_release( (typelib_TypeDescription * )m_pType );\n m_pRemoteI->release( m_pRemoteI );\n m_pEnvUno->release( m_pEnvUno );\n m_pEnvRemote->release( m_pEnvRemote );\n#if OSL_DEBUG_LEVEL > 1\n thisCounter.release();\n#endif\n}\n\n} \/\/ end namespace bridge_remote\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Kung.\n\n Copyright (c) 2005 Tobias Koenig <tokoe@kde.org>\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 License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include <kfiledialog.h>\n#include <kio\/netaccess.h>\n#include <kcodecs.h>\n#include <kmessagebox.h>\n#include <kmimemagic.h>\n#include <klocale.h>\n#include <kparts\/part.h>\n#include <kparts\/componentfactory.h>\n#include <ktemporaryfile.h>\n\n#include <QFile>\n#include <QLabel>\n#include <QLayout>\n#include <QPushButton>\n#include <QWidget>\n\n#include <schema\/simpletype.h>\n\n#include \"binaryinputfield.h\"\n\nBinaryInputField::BinaryInputField( const QString &name, const QString &typeName, const XSD::SimpleType *type )\n : SimpleInputField( name, type ),\n mValue( 0 ), mTypeName( typeName )\n{\n}\n\nvoid BinaryInputField::setXMLData( const QDomElement &element )\n{\n if ( mName != element.tagName() ) {\n qDebug( \"BinaryInputField: Wrong dom element passed: expected %s, got %s\", qPrintable( mName ), qPrintable( element.tagName() ) );\n return;\n }\n\n setData( element.text() );\n}\n\nvoid BinaryInputField::xmlData( QDomDocument &document, QDomElement &parent )\n{\n QDomElement element = document.createElement( mName );\n element.setAttribute( \"xsi:type\", \"xsd:\" + mTypeName );\n QDomText text = document.createTextNode( data() );\n element.appendChild( text );\n\n parent.appendChild( element );\n}\n\nvoid BinaryInputField::setData( const QString &data )\n{\n KCodecs::base64Decode( data.toUtf8(), mValue );\n}\n\nQString BinaryInputField::data() const\n{\n QByteArray data = KCodecs::base64Encode( mValue, false );\n return QString::fromUtf8( data.data(), data.size() );\n}\n\nQWidget *BinaryInputField::createWidget( QWidget *parent )\n{\n mInputWidget = new BinaryWidget( parent );\n\n if ( !mValue.isEmpty() )\n mInputWidget->setData( mValue );\n\n return mInputWidget;\n}\n\nvoid BinaryInputField::valueChanged( const QByteArray &value )\n{\n mValue = value;\n\n emit modified();\n}\n\n\nBinaryWidget::BinaryWidget( QWidget *parent )\n : QWidget( parent ),\n mMainWidget( 0 )\n{\n setObjectName( \"BinaryWidget\" );\n\n mLayout = new QGridLayout( this );\n mLayout->setSpacing( 6 );\n mLayout->setMargin( 11 );\n\n mLoadButton = new QPushButton( i18n( \"Load...\" ), this );\n mSaveButton = new QPushButton( i18n( \"Save...\" ), this );\n mSaveButton->setEnabled( false );\n\n mLayout->addWidget( mLoadButton, 0, 1 );\n mLayout->addWidget( mSaveButton, 1, 1 );\n\n connect( mLoadButton, SIGNAL( clicked() ), SLOT( load() ) );\n connect( mSaveButton, SIGNAL( clicked() ), SLOT( save() ) );\n}\n\nvoid BinaryWidget::setData( const QByteArray &data )\n{\n KMimeMagic magic;\n QString mimetype;\n\n delete mMainWidget;\n\n KMimeMagicResult *result = magic.findBufferType( data );\n if ( result->isValid() )\n mimetype = result->mimeType();\n\n if ( !mimetype.isEmpty() ) {\n KParts::ReadOnlyPart *part = 0;\n \/\/KParts::ReadOnlyPart *part = KParts::ComponentFactory::createPartInstanceFromQuery<KParts::ReadOnlyPart>( mimetype, QString::null, this, 0, this, 0 ); \/\/ FIXME: doesn't work\n if ( part ) {\n KTemporaryFile file;\n file.setAutoRemove(false);\n file.open();\n file.write( data );\n file.flush();\n part->openUrl( KUrl( file.fileName() ) );\n mMainWidget = part->widget();\n } else {\n mMainWidget = new QLabel( i18n( \"No part found for visualization of mimetype %1\", mimetype ), this );\n }\n\n mData = data;\n mSaveButton->setEnabled( true );\n } else {\n mMainWidget = new QLabel( i18n( \"Got data of unknown mimetype\" ), this );\n }\n\n mLayout->addWidget( mMainWidget, 0, 0, 3, 1);\n mMainWidget->show();\n}\n\nvoid BinaryWidget::load()\n{\n KUrl url = KFileDialog::getOpenUrl( QString(), QString(), this );\n if ( url.isEmpty() )\n return;\n\n QString tempFile;\n if ( KIO::NetAccess::download( url, tempFile, this ) ) {\n QFile file( tempFile );\n if ( !file.open( QIODevice::ReadOnly ) ) {\n KMessageBox::error( this, i18n( \"Unable to open file %1\", url.url() ) );\n return;\n }\n\n QByteArray data = file.readAll();\n setData( data );\n\n file.close();\n KIO::NetAccess::removeTempFile( tempFile );\n\n emit valueChanged( data );\n } else\n KMessageBox::error( this, KIO::NetAccess::lastErrorString() );\n}\n\nvoid BinaryWidget::save()\n{\n KUrl url = KFileDialog::getSaveUrl( QString(), QString(), this );\n if ( url.isEmpty() )\n return;\n\n KTemporaryFile tempFile;\n tempFile.open();\n tempFile.write( mData );\n tempFile.flush();\n\n if ( !KIO::NetAccess::upload( tempFile.fileName(), url, this ) )\n KMessageBox::error( this, KIO::NetAccess::lastErrorString() );\n}\n\n#include \"binaryinputfield.moc\"\n<commit_msg>KMimeMagic -> KMimeType and port the ComponentFactory call.<commit_after>\/*\n This file is part of Kung.\n\n Copyright (c) 2005 Tobias Koenig <tokoe@kde.org>\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 License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include <kfiledialog.h>\n#include <kio\/netaccess.h>\n#include <kcodecs.h>\n#include <kmessagebox.h>\n#include <kmimetype.h>\n#include <klocale.h>\n#include <kparts\/part.h>\n#include <kparts\/componentfactory.h>\n#include <ktemporaryfile.h>\n\n#include <QFile>\n#include <QLabel>\n#include <QLayout>\n#include <QPushButton>\n#include <QWidget>\n\n#include <schema\/simpletype.h>\n\n#include \"binaryinputfield.h\"\n\nBinaryInputField::BinaryInputField( const QString &name, const QString &typeName, const XSD::SimpleType *type )\n : SimpleInputField( name, type ),\n mValue( 0 ), mTypeName( typeName )\n{\n}\n\nvoid BinaryInputField::setXMLData( const QDomElement &element )\n{\n if ( mName != element.tagName() ) {\n qDebug( \"BinaryInputField: Wrong dom element passed: expected %s, got %s\", qPrintable( mName ), qPrintable( element.tagName() ) );\n return;\n }\n\n setData( element.text() );\n}\n\nvoid BinaryInputField::xmlData( QDomDocument &document, QDomElement &parent )\n{\n QDomElement element = document.createElement( mName );\n element.setAttribute( \"xsi:type\", \"xsd:\" + mTypeName );\n QDomText text = document.createTextNode( data() );\n element.appendChild( text );\n\n parent.appendChild( element );\n}\n\nvoid BinaryInputField::setData( const QString &data )\n{\n KCodecs::base64Decode( data.toUtf8(), mValue );\n}\n\nQString BinaryInputField::data() const\n{\n QByteArray data = KCodecs::base64Encode( mValue, false );\n return QString::fromUtf8( data.data(), data.size() );\n}\n\nQWidget *BinaryInputField::createWidget( QWidget *parent )\n{\n mInputWidget = new BinaryWidget( parent );\n\n if ( !mValue.isEmpty() )\n mInputWidget->setData( mValue );\n\n return mInputWidget;\n}\n\nvoid BinaryInputField::valueChanged( const QByteArray &value )\n{\n mValue = value;\n\n emit modified();\n}\n\n\nBinaryWidget::BinaryWidget( QWidget *parent )\n : QWidget( parent ),\n mMainWidget( 0 )\n{\n setObjectName( \"BinaryWidget\" );\n\n mLayout = new QGridLayout( this );\n mLayout->setSpacing( 6 );\n mLayout->setMargin( 11 );\n\n mLoadButton = new QPushButton( i18n( \"Load...\" ), this );\n mSaveButton = new QPushButton( i18n( \"Save...\" ), this );\n mSaveButton->setEnabled( false );\n\n mLayout->addWidget( mLoadButton, 0, 1 );\n mLayout->addWidget( mSaveButton, 1, 1 );\n\n connect( mLoadButton, SIGNAL( clicked() ), SLOT( load() ) );\n connect( mSaveButton, SIGNAL( clicked() ), SLOT( save() ) );\n}\n\nvoid BinaryWidget::setData( const QByteArray &data )\n{\n delete mMainWidget;\n\n QString mimetype;\n KMimeType::Ptr mime = KMimeType::findByContent( data );\n if ( mime && !mime->isDefault() )\n mimetype = mime->name();\n\n if ( !mimetype.isEmpty() ) {\n KParts::ReadOnlyPart *part = KParts::ComponentFactory::createPartInstanceFromQuery<KParts::ReadOnlyPart>( mimetype, QString(), this, this );\n if ( part ) {\n KTemporaryFile file;\n file.setAutoRemove(false);\n file.open();\n file.write( data );\n file.flush();\n part->openUrl( KUrl( file.fileName() ) );\n mMainWidget = part->widget();\n } else {\n mMainWidget = new QLabel( i18n( \"No part found for visualization of mimetype %1\", mimetype ), this );\n }\n\n mData = data;\n mSaveButton->setEnabled( true );\n } else {\n mMainWidget = new QLabel( i18n( \"Got data of unknown mimetype\" ), this );\n }\n\n mLayout->addWidget( mMainWidget, 0, 0, 3, 1);\n mMainWidget->show();\n}\n\nvoid BinaryWidget::load()\n{\n KUrl url = KFileDialog::getOpenUrl( QString(), QString(), this );\n if ( url.isEmpty() )\n return;\n\n QString tempFile;\n if ( KIO::NetAccess::download( url, tempFile, this ) ) {\n QFile file( tempFile );\n if ( !file.open( QIODevice::ReadOnly ) ) {\n KMessageBox::error( this, i18n( \"Unable to open file %1\", url.url() ) );\n return;\n }\n\n QByteArray data = file.readAll();\n setData( data );\n\n file.close();\n KIO::NetAccess::removeTempFile( tempFile );\n\n emit valueChanged( data );\n } else\n KMessageBox::error( this, KIO::NetAccess::lastErrorString() );\n}\n\nvoid BinaryWidget::save()\n{\n KUrl url = KFileDialog::getSaveUrl( QString(), QString(), this );\n if ( url.isEmpty() )\n return;\n\n KTemporaryFile tempFile;\n tempFile.open();\n tempFile.write( mData );\n tempFile.flush();\n\n if ( !KIO::NetAccess::upload( tempFile.fileName(), url, this ) )\n KMessageBox::error( this, KIO::NetAccess::lastErrorString() );\n}\n\n#include \"binaryinputfield.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KDE.\n\n Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>\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 License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"parserrelaxng.h\"\n\n#include <kdebug.h>\n\n#include <iostream>\n\nusing namespace RNG;\n\nPattern::Pattern()\n : optional( false ), zeroOrMore( false ), oneOrMore( false ),\n choice( false )\n{\n}\n\nbool Pattern::isEmpty()\n{\n return !optional && !zeroOrMore && !oneOrMore && !choice;\n}\n\nQString Pattern::asString()\n{\n if ( isEmpty() ) return \"\";\n QString str = \"( \";\n if ( optional ) str += \"optional \";\n if ( zeroOrMore ) str += \"zeroOrMore \";\n if ( oneOrMore ) str += \"oneOrMore \";\n if ( choice ) str += \"choice \";\n str += ')';\n return str;\n}\n\nvoid Pattern::merge( Pattern p )\n{\n if ( p.optional ) optional = true;\n if ( p.zeroOrMore ) zeroOrMore = true;\n if ( p.oneOrMore ) oneOrMore = true;\n if ( p.choice ) choice = true;\n}\n\nElement::Element()\n : hasText( false ), isEmpty( false )\n{\n}\n\nParserRelaxng::ParserRelaxng()\n{\n}\n\nvoid ParserRelaxng::setVerbose( bool verbose )\n{\n mVerbose = verbose; \n}\n\nElement *ParserRelaxng::parse( const QDomElement &docElement )\n{\n Element *start = 0;\n\n QDomNode n1;\n for( n1 = docElement.firstChild(); !n1.isNull(); n1 = n1.nextSibling() ) {\n QDomElement e1 = n1.toElement();\n if ( mVerbose ) {\n kDebug() << \"TOP LEVEL element \" << e1.tagName() << endl;\n }\n if ( e1.tagName() == \"define\" ) {\n Element *d = new Element;\n d->name = e1.attribute( \"name\" );\n parseElement( e1, d, Pattern() );\n Element::List definitions;\n QMap<QString,Element::List >::ConstIterator it;\n it = mDefinitionMap.find( d->name );\n if ( it != mDefinitionMap.end() ) definitions = *it;\n definitions.append( d );\n mDefinitionMap.insert( d->name, definitions );\n } else if ( e1.tagName() == \"start\" ) {\n start = new Element;\n parseElement( e1, start, Pattern() );\n } else {\n kDebug() << \"parseGrammar: Unrecognized tag: \" << e1.tagName() << endl;\n }\n }\n\n return start;\n}\n\nReference *ParserRelaxng::parseReference( const QDomElement &referenceElement )\n{\n Reference *r = new Reference;\n r->name = referenceElement.attribute( \"name\" );\n return r;\n}\n\nbool ParserRelaxng::parseAttribute( const QDomElement &attributeElement,\n Attribute *a )\n{\n a->name = attributeElement.attribute( \"name\" );\n\n return true;\n}\n\nbool ParserRelaxng::parseElement( const QDomElement &elementElement, Element *e,\n Pattern pattern )\n{\n if ( mVerbose ) {\n kDebug() << \"parseElement \" << e->name << endl;\n }\n\n QDomNode n1;\n for( n1 = elementElement.firstChild(); !n1.isNull(); n1 = n1.nextSibling() ) {\n QDomElement e1 = n1.toElement();\n if ( e1.tagName() == \"element\" ) {\n Element *element = new Element;\n element->name = e1.attribute( \"name\" );\n element->pattern = pattern;\n parseElement( e1, element, Pattern() );\n e->elements.append( element );\n } else if ( e1.tagName() == \"attribute\" ) {\n Attribute *a = new Attribute;\n a->name = e1.attribute( \"name\" );\n a->pattern = pattern;\n if ( mVerbose ) {\n kDebug() << \"ATTRIBUTE: \" << a->name << \" \" << a->pattern.asString()\n << endl;\n }\n parseAttribute( e1, a );\n e->attributes.append( a );\n } else if ( e1.tagName() == \"ref\" ) {\n Reference *r = parseReference( e1 );\n r->pattern = pattern;\n e->references.append( r );\n } else if ( e1.tagName() == \"text\" ) {\n e->hasText = true;\n } else if ( e1.tagName() == \"empty\" ) {\n e->isEmpty = true;\n } else {\n Pattern p = pattern;\n if ( e1.tagName() == \"optional\" ) p.optional = true;\n else if ( e1.tagName() == \"zeroOrMore\" ) p.zeroOrMore = true;\n else if ( e1.tagName() == \"oneOrMore\" ) p.oneOrMore = true;\n else if ( e1.tagName() == \"choice\" ) p.choice = true;\n else {\n kDebug() << \"Unsupported pattern '\" << e1.tagName() << \"'\" << endl;\n }\n parseElement( e1, e, p );\n }\n }\n\n return true;\n}\n\nvoid ParserRelaxng::substituteReferences( Element *s )\n{\n if ( mVerbose ) {\n kDebug() << \"substituteReferences for '\" << s->name << \"'\" << endl;\n }\n Reference::List::Iterator it = s->references.begin();\n while( it != s->references.end() ) {\n Reference *r = *it;\n if ( mVerbose ) {\n kDebug() << \"REF \" << r->name << endl;\n }\n if ( r->name == s->name ) {\n if ( mVerbose ) {\n kDebug() << \"Don't resolve self reference\" << endl;\n }\n return;\n }\n if ( r->substituted ) {\n if ( mVerbose ) {\n kDebug() << \"Already substituted.\" << endl;\n }\n ++it;\n continue;\n } else {\n r->substituted = true;\n }\n QMap<QString,Element::List >::ConstIterator it1;\n it1 = mDefinitionMap.find( r->name );\n if ( it1 != mDefinitionMap.end() ) {\n Element::List elements = *it1;\n Element::List::ConstIterator it4;\n for( it4 = elements.begin(); it4 != elements.end(); ++it4 ) {\n Element *d = *it4;\n substituteReferences( d );\n Element::List::ConstIterator it2;\n for( it2 = d->elements.begin(); it2 != d->elements.end(); ++it2 ) {\n Element *e = *it2;\n e->pattern.merge( r->pattern );\n substituteReferences( e );\n s->elements.append( e );\n }\n Attribute::List::ConstIterator it3;\n for( it3 = d->attributes.begin(); it3 != d->attributes.end();\n ++it3 ) {\n Attribute *a = *it3;\n a->pattern.merge( r->pattern );\n s->attributes.append( a );\n }\n }\n it = s->references.erase( it );\n } else {\n kDebug() << \"Reference not found\" << endl;\n ++it;\n }\n }\n}\n\nvoid ParserRelaxng::doIndent( int cols )\n{\n for( int i = 0; i < cols; ++i ) std::cout << \" \";\n}\n\nvoid ParserRelaxng::dumpPattern( Pattern pattern )\n{\n std::cout << pattern.asString().toLocal8Bit().data();\n}\n\nvoid ParserRelaxng::dumpReferences( const Reference::List &references, int indent )\n{\n Reference::List::ConstIterator it;\n for( it = references.begin(); it != references.end(); ++it ) {\n Reference *r = *it;\n doIndent( indent );\n std::cout << \"REFERENCE \" << r->name.toLocal8Bit().data();\n dumpPattern( r->pattern );\n std::cout << std::endl;\n }\n}\n\nvoid ParserRelaxng::dumpAttributes( const Attribute::List &attributes, int indent )\n{\n Attribute::List::ConstIterator it;\n for( it = attributes.begin(); it != attributes.end(); ++it ) {\n Attribute *a = *it;\n doIndent( indent );\n std::cout << \"ATTRIBUTE \" << a->name.toLocal8Bit().data();\n dumpPattern( a->pattern );\n std::cout << std::endl;\n }\n}\n\nvoid ParserRelaxng::dumpElements( const Element::List &elements, int indent )\n{\n Element::List::ConstIterator it;\n for( it = elements.begin(); it != elements.end(); ++it ) {\n Element *e = *it;\n dumpElement( e, indent );\n }\n}\n\nvoid ParserRelaxng::dumpElement( Element *e, int indent )\n{\n doIndent( indent );\n std::cout << \"ELEMENT \" << e->name.toLocal8Bit().data();\n dumpPattern( e->pattern );\n std::cout << std::endl;\n\n if ( e->hasText ) {\n doIndent( indent + 2 );\n std::cout << \"TEXT\" << std::endl;\n }\n\n dumpAttributes( e->attributes, indent + 2 );\n dumpElements( e->elements, indent + 2 );\n dumpReferences( e->references, indent + 2 );\n}\n\nvoid ParserRelaxng::dumpTree( Element *s )\n{\n std::cout << \"START \" << s->name.toLocal8Bit().data() << std::endl;\n dumpElements( s->elements, 2 );\n dumpReferences( s->references, 2 );\n}\n\nvoid ParserRelaxng::dumpDefinitionMap()\n{\n std::cout << \"DEFINITION MAP\" << std::endl;\n QMap<QString,Element::List >::ConstIterator it;\n for( it = mDefinitionMap.begin(); it != mDefinitionMap.end(); ++it ) {\n dumpElements( *it, 2 );\n }\n}\n\nSchema::Document ParserRelaxng::convertToSchema( Element *start )\n{\n Element::List elements = start->elements;\n if ( !elements.isEmpty() ) {\n Schema::Element element = convertToSchemaElement( elements.first() );\n mDocument.setStartElement( element );\n }\n\n return mDocument;\n}\n\nSchema::Element ParserRelaxng::convertToSchemaElement( Element *e )\n{\n Schema::Element schemaElement;\n schemaElement.setName( e->name );\n schemaElement.setIdentifier( e->name );\n\n if ( e->hasText ) schemaElement.setText( true );\n\n foreach( Element *element, e->elements ) {\n QString id = element->name;\n if ( !mDocument.element( id ).isValid() ) {\n Schema::Element relatedElement = convertToSchemaElement( element );\n }\n Schema::Relation relation = convertToRelation( element->pattern, id );\n schemaElement.addElementRelation( relation );\n }\n\n foreach( Attribute *attribute, e->attributes ) {\n QString id = schemaElement.identifier() + '\/' + attribute->name;\n if ( !mDocument.attribute( id ).isValid() ) {\n Schema::Attribute relatedAttribute = convertToSchemaAttribute(\n schemaElement.identifier(), attribute );\n }\n Schema::Relation relation = convertToRelation( attribute->pattern, id );\n schemaElement.addAttributeRelation( relation );\n }\n\n foreach( Reference *reference, e->references ) {\n QString id = reference->name;\n Schema::Relation relation = convertToRelation( reference->pattern, id );\n schemaElement.addElementRelation( relation );\n }\n\n mDocument.addElement( schemaElement );\n\n return schemaElement;\n}\n\nSchema::Relation ParserRelaxng::convertToRelation( const Pattern &pattern,\n const QString &id )\n{\n Schema::Relation relation( id );\n if ( pattern.optional ) {\n relation.setMinOccurs( 0 );\n relation.setMaxOccurs( 1 );\n } else if ( pattern.zeroOrMore ) {\n relation.setMinOccurs( 0 );\n relation.setMaxOccurs( Schema::Relation::Unbounded );\n } else if ( pattern.oneOrMore ) {\n relation.setMinOccurs( 1 );\n relation.setMaxOccurs( Schema::Relation::Unbounded );\n }\n\n return relation;\n}\n\nSchema::Attribute ParserRelaxng::convertToSchemaAttribute( const QString &path,\n Attribute *a )\n{\n Schema::Attribute schemaAttribute;\n schemaAttribute.setName( a->name );\n schemaAttribute.setIdentifier( path + '\/' + a->name );\n\n mDocument.addAttribute( schemaAttribute );\n\n return schemaAttribute;\n}\n<commit_msg>Don't loop over all DOM nodes, convert them to elements and ignore the null elements. Rather simply loop over all DOM elements in the first place. Thanks to Tobias for the hint. This reduces the output of 'unrecognized patterns' of the kxml_compiler by half...<commit_after>\/*\n This file is part of KDE.\n\n Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>\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 License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"parserrelaxng.h\"\n\n#include <kdebug.h>\n\n#include <iostream>\n\nusing namespace RNG;\n\nPattern::Pattern()\n : optional( false ), zeroOrMore( false ), oneOrMore( false ),\n choice( false )\n{\n}\n\nbool Pattern::isEmpty()\n{\n return !optional && !zeroOrMore && !oneOrMore && !choice;\n}\n\nQString Pattern::asString()\n{\n if ( isEmpty() ) return \"\";\n QString str = \"( \";\n if ( optional ) str += \"optional \";\n if ( zeroOrMore ) str += \"zeroOrMore \";\n if ( oneOrMore ) str += \"oneOrMore \";\n if ( choice ) str += \"choice \";\n str += ')';\n return str;\n}\n\nvoid Pattern::merge( Pattern p )\n{\n if ( p.optional ) optional = true;\n if ( p.zeroOrMore ) zeroOrMore = true;\n if ( p.oneOrMore ) oneOrMore = true;\n if ( p.choice ) choice = true;\n}\n\nElement::Element()\n : hasText( false ), isEmpty( false )\n{\n}\n\nParserRelaxng::ParserRelaxng()\n{\n}\n\nvoid ParserRelaxng::setVerbose( bool verbose )\n{\n mVerbose = verbose; \n}\n\nElement *ParserRelaxng::parse( const QDomElement &docElement )\n{\n Element *start = 0;\n\n QDomNode n1;\n QDomElement e1;\n for( e1 = docElement.firstChildElement(); !e1.isNull(); e1 = e1.nextSiblingElement() ) {\n if ( mVerbose ) {\n kDebug() << \"TOP LEVEL element \" << e1.tagName() << endl;\n }\n if ( e1.tagName() == \"define\" ) {\n Element *d = new Element;\n d->name = e1.attribute( \"name\" );\n parseElement( e1, d, Pattern() );\n Element::List definitions;\n QMap<QString,Element::List >::ConstIterator it;\n it = mDefinitionMap.find( d->name );\n if ( it != mDefinitionMap.end() ) definitions = *it;\n definitions.append( d );\n mDefinitionMap.insert( d->name, definitions );\n } else if ( e1.tagName() == \"start\" ) {\n start = new Element;\n parseElement( e1, start, Pattern() );\n } else if ( e1.isComment() ) {\n \/\/ Ignore all comments for now!\n } else {\n kDebug() << \"parseGrammar: Unrecognized tag: \" << e1.tagName() << endl;\n }\n }\n\n return start;\n}\n\nReference *ParserRelaxng::parseReference( const QDomElement &referenceElement )\n{\n Reference *r = new Reference;\n r->name = referenceElement.attribute( \"name\" );\n return r;\n}\n\nbool ParserRelaxng::parseAttribute( const QDomElement &attributeElement,\n Attribute *a )\n{\n a->name = attributeElement.attribute( \"name\" );\n\n return true;\n}\n\nbool ParserRelaxng::parseElement( const QDomElement &elementElement, Element *e,\n Pattern pattern )\n{\n if ( mVerbose ) {\n kDebug() << \"parseElement \" << e->name << endl;\n }\n\n QDomNode n1;\n QDomElement e1;\n for( e1 = elementElement.firstChildElement(); !e1.isNull(); e1 = e1.nextSiblingElement() ) {\n if ( e1.tagName() == \"element\" ) {\n Element *element = new Element;\n element->name = e1.attribute( \"name\" );\n element->pattern = pattern;\n parseElement( e1, element, Pattern() );\n e->elements.append( element );\n } else if ( e1.tagName() == \"attribute\" ) {\n Attribute *a = new Attribute;\n a->name = e1.attribute( \"name\" );\n a->pattern = pattern;\n if ( mVerbose ) {\n kDebug() << \"ATTRIBUTE: \" << a->name << \" \" << a->pattern.asString()\n << endl;\n }\n parseAttribute( e1, a );\n e->attributes.append( a );\n } else if ( e1.tagName() == \"ref\" ) {\n Reference *r = parseReference( e1 );\n r->pattern = pattern;\n e->references.append( r );\n } else if ( e1.tagName() == \"text\" ) {\n e->hasText = true;\n } else if ( e1.tagName() == \"empty\" ) {\n e->isEmpty = true;\n } else {\n Pattern p = pattern;\n if ( e1.tagName() == \"optional\" ) p.optional = true;\n else if ( e1.tagName() == \"zeroOrMore\" ) p.zeroOrMore = true;\n else if ( e1.tagName() == \"oneOrMore\" ) p.oneOrMore = true;\n else if ( e1.tagName() == \"choice\" ) p.choice = true;\n else {\n kDebug() << \"Unsupported pattern '\" << e1.tagName() << \"'\" << endl;\n }\n parseElement( e1, e, p );\n }\n }\n\n return true;\n}\n\nvoid ParserRelaxng::substituteReferences( Element *s )\n{\n if ( mVerbose ) {\n kDebug() << \"substituteReferences for '\" << s->name << \"'\" << endl;\n }\n Reference::List::Iterator it = s->references.begin();\n while( it != s->references.end() ) {\n Reference *r = *it;\n if ( mVerbose ) {\n kDebug() << \"REF \" << r->name << endl;\n }\n if ( r->name == s->name ) {\n if ( mVerbose ) {\n kDebug() << \"Don't resolve self reference\" << endl;\n }\n return;\n }\n if ( r->substituted ) {\n if ( mVerbose ) {\n kDebug() << \"Already substituted.\" << endl;\n }\n ++it;\n continue;\n } else {\n r->substituted = true;\n }\n QMap<QString,Element::List >::ConstIterator it1;\n it1 = mDefinitionMap.find( r->name );\n if ( it1 != mDefinitionMap.end() ) {\n Element::List elements = *it1;\n Element::List::ConstIterator it4;\n for( it4 = elements.begin(); it4 != elements.end(); ++it4 ) {\n Element *d = *it4;\n substituteReferences( d );\n Element::List::ConstIterator it2;\n for( it2 = d->elements.begin(); it2 != d->elements.end(); ++it2 ) {\n Element *e = *it2;\n e->pattern.merge( r->pattern );\n substituteReferences( e );\n s->elements.append( e );\n }\n Attribute::List::ConstIterator it3;\n for( it3 = d->attributes.begin(); it3 != d->attributes.end();\n ++it3 ) {\n Attribute *a = *it3;\n a->pattern.merge( r->pattern );\n s->attributes.append( a );\n }\n }\n it = s->references.erase( it );\n } else {\n kDebug() << \"Reference not found\" << endl;\n ++it;\n }\n }\n}\n\nvoid ParserRelaxng::doIndent( int cols )\n{\n for( int i = 0; i < cols; ++i ) std::cout << \" \";\n}\n\nvoid ParserRelaxng::dumpPattern( Pattern pattern )\n{\n std::cout << pattern.asString().toLocal8Bit().data();\n}\n\nvoid ParserRelaxng::dumpReferences( const Reference::List &references, int indent )\n{\n Reference::List::ConstIterator it;\n for( it = references.begin(); it != references.end(); ++it ) {\n Reference *r = *it;\n doIndent( indent );\n std::cout << \"REFERENCE \" << r->name.toLocal8Bit().data();\n dumpPattern( r->pattern );\n std::cout << std::endl;\n }\n}\n\nvoid ParserRelaxng::dumpAttributes( const Attribute::List &attributes, int indent )\n{\n Attribute::List::ConstIterator it;\n for( it = attributes.begin(); it != attributes.end(); ++it ) {\n Attribute *a = *it;\n doIndent( indent );\n std::cout << \"ATTRIBUTE \" << a->name.toLocal8Bit().data();\n dumpPattern( a->pattern );\n std::cout << std::endl;\n }\n}\n\nvoid ParserRelaxng::dumpElements( const Element::List &elements, int indent )\n{\n Element::List::ConstIterator it;\n for( it = elements.begin(); it != elements.end(); ++it ) {\n Element *e = *it;\n dumpElement( e, indent );\n }\n}\n\nvoid ParserRelaxng::dumpElement( Element *e, int indent )\n{\n doIndent( indent );\n std::cout << \"ELEMENT \" << e->name.toLocal8Bit().data();\n dumpPattern( e->pattern );\n std::cout << std::endl;\n\n if ( e->hasText ) {\n doIndent( indent + 2 );\n std::cout << \"TEXT\" << std::endl;\n }\n\n dumpAttributes( e->attributes, indent + 2 );\n dumpElements( e->elements, indent + 2 );\n dumpReferences( e->references, indent + 2 );\n}\n\nvoid ParserRelaxng::dumpTree( Element *s )\n{\n std::cout << \"START \" << s->name.toLocal8Bit().data() << std::endl;\n dumpElements( s->elements, 2 );\n dumpReferences( s->references, 2 );\n}\n\nvoid ParserRelaxng::dumpDefinitionMap()\n{\n std::cout << \"DEFINITION MAP\" << std::endl;\n QMap<QString,Element::List >::ConstIterator it;\n for( it = mDefinitionMap.begin(); it != mDefinitionMap.end(); ++it ) {\n dumpElements( *it, 2 );\n }\n}\n\nSchema::Document ParserRelaxng::convertToSchema( Element *start )\n{\n Element::List elements = start->elements;\n if ( !elements.isEmpty() ) {\n Schema::Element element = convertToSchemaElement( elements.first() );\n mDocument.setStartElement( element );\n }\n\n return mDocument;\n}\n\nSchema::Element ParserRelaxng::convertToSchemaElement( Element *e )\n{\n Schema::Element schemaElement;\n schemaElement.setName( e->name );\n schemaElement.setIdentifier( e->name );\n\n if ( e->hasText ) schemaElement.setText( true );\n\n foreach( Element *element, e->elements ) {\n QString id = element->name;\n if ( !mDocument.element( id ).isValid() ) {\n Schema::Element relatedElement = convertToSchemaElement( element );\n }\n Schema::Relation relation = convertToRelation( element->pattern, id );\n schemaElement.addElementRelation( relation );\n }\n\n foreach( Attribute *attribute, e->attributes ) {\n QString id = schemaElement.identifier() + '\/' + attribute->name;\n if ( !mDocument.attribute( id ).isValid() ) {\n Schema::Attribute relatedAttribute = convertToSchemaAttribute(\n schemaElement.identifier(), attribute );\n }\n Schema::Relation relation = convertToRelation( attribute->pattern, id );\n schemaElement.addAttributeRelation( relation );\n }\n\n foreach( Reference *reference, e->references ) {\n QString id = reference->name;\n Schema::Relation relation = convertToRelation( reference->pattern, id );\n schemaElement.addElementRelation( relation );\n }\n\n mDocument.addElement( schemaElement );\n\n return schemaElement;\n}\n\nSchema::Relation ParserRelaxng::convertToRelation( const Pattern &pattern,\n const QString &id )\n{\n Schema::Relation relation( id );\n if ( pattern.optional ) {\n relation.setMinOccurs( 0 );\n relation.setMaxOccurs( 1 );\n } else if ( pattern.zeroOrMore ) {\n relation.setMinOccurs( 0 );\n relation.setMaxOccurs( Schema::Relation::Unbounded );\n } else if ( pattern.oneOrMore ) {\n relation.setMinOccurs( 1 );\n relation.setMaxOccurs( Schema::Relation::Unbounded );\n }\n\n return relation;\n}\n\nSchema::Attribute ParserRelaxng::convertToSchemaAttribute( const QString &path,\n Attribute *a )\n{\n Schema::Attribute schemaAttribute;\n schemaAttribute.setName( a->name );\n schemaAttribute.setIdentifier( path + '\/' + a->name );\n\n mDocument.addAttribute( schemaAttribute );\n\n return schemaAttribute;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: except.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-09-13 11:02:18 $\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#include <stdio.h>\n#include <dlfcn.h>\n#include <cxxabi.h>\n#include <hash_map>\n\n#include <rtl\/strbuf.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <osl\/diagnose.h>\n#include <osl\/mutex.hxx>\n\n#include <com\/sun\/star\/uno\/genfunc.hxx>\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include <typelib\/typedescription.hxx>\n#include <uno\/any2.h>\n\n#include \"share.hxx\"\n\n\nusing namespace ::std;\nusing namespace ::osl;\nusing namespace ::rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::__cxxabiv1;\n\n\nnamespace CPPU_CURRENT_NAMESPACE\n{\n\nvoid dummy_can_throw_anything( char const * )\n{\n}\n\n\/\/==================================================================================================\nstatic OUString toUNOname( char const * p ) SAL_THROW( () )\n{\n#if OSL_DEBUG_LEVEL > 1\n char const * start = p;\n#endif\n\n \/\/ example: N3com3sun4star4lang24IllegalArgumentExceptionE\n\n OUStringBuffer buf( 64 );\n OSL_ASSERT( 'N' == *p );\n ++p; \/\/ skip N\n\n while ('E' != *p)\n {\n \/\/ read chars count\n long n = (*p++ - '0');\n while ('0' <= *p && '9' >= *p)\n {\n n *= 10;\n n += (*p++ - '0');\n }\n buf.appendAscii( p, n );\n p += n;\n if ('E' != *p)\n buf.append( (sal_Unicode)'.' );\n }\n\n#if OSL_DEBUG_LEVEL > 1\n OUString ret( buf.makeStringAndClear() );\n OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) );\n fprintf( stderr, \"> toUNOname(): %s => %s\\n\", start, c_ret.getStr() );\n return ret;\n#else\n return buf.makeStringAndClear();\n#endif\n}\n\n\/\/==================================================================================================\nclass RTTI\n{\n typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map;\n\n Mutex m_mutex;\n t_rtti_map m_rttis;\n t_rtti_map m_generatedRttis;\n\n void * m_hApp;\n\npublic:\n RTTI() SAL_THROW( () );\n ~RTTI() SAL_THROW( () );\n\n type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () );\n};\n\/\/__________________________________________________________________________________________________\nRTTI::RTTI() SAL_THROW( () )\n : m_hApp( dlopen( 0, RTLD_LAZY ) )\n{\n}\n\/\/__________________________________________________________________________________________________\nRTTI::~RTTI() SAL_THROW( () )\n{\n dlclose( m_hApp );\n}\n\n\/\/__________________________________________________________________________________________________\ntype_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () )\n{\n type_info * rtti;\n\n OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName;\n\n MutexGuard guard( m_mutex );\n t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) );\n if (iFind == m_rttis.end())\n {\n \/\/ RTTI symbol\n OStringBuffer buf( 64 );\n buf.append( RTL_CONSTASCII_STRINGPARAM(\"_ZTIN\") );\n sal_Int32 index = 0;\n do\n {\n OUString token( unoName.getToken( 0, '.', index ) );\n buf.append( token.getLength() );\n OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );\n buf.append( c_token );\n }\n while (index >= 0);\n buf.append( 'E' );\n\n OString symName( buf.makeStringAndClear() );\n rtti = (type_info *)dlsym( m_hApp, symName.getStr() );\n\n if (rtti)\n {\n pair< t_rtti_map::iterator, bool > insertion(\n m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );\n OSL_ENSURE( insertion.second, \"### inserting new rtti failed?!\" );\n }\n else\n {\n \/\/ try to lookup the symbol in the generated rtti map\n t_rtti_map::const_iterator iFind2( m_generatedRttis.find( unoName ) );\n if (iFind2 == m_generatedRttis.end())\n {\n \/\/ we must generate it !\n \/\/ symbol and rtti-name is nearly identical,\n \/\/ the symbol is prefixed with _ZTI\n char const * rttiName = symName.getStr() +4;\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stderr,\"generated rtti for %s\\n\", rttiName );\n#endif\n if (pTypeDescr->pBaseTypeDescription)\n {\n \/\/ ensure availability of base\n type_info * base_rtti = getRTTI(\n (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription );\n rtti = new __si_class_type_info(\n strdup( rttiName ), (__class_type_info *)base_rtti );\n }\n else\n {\n \/\/ this class has no base class\n rtti = new __class_type_info( strdup( rttiName ) );\n }\n\n pair< t_rtti_map::iterator, bool > insertion(\n m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );\n OSL_ENSURE( insertion.second, \"### inserting new generated rtti failed?!\" );\n }\n else \/\/ taking already generated rtti\n {\n rtti = iFind2->second;\n }\n }\n }\n else\n {\n rtti = iFind->second;\n }\n\n return rtti;\n}\n\n\/\/--------------------------------------------------------------------------------------------------\nstatic void deleteException( void * pExc )\n{\n __cxa_exception const * header = ((__cxa_exception const *)pExc - 1);\n typelib_TypeDescription * pTD = 0;\n OUString unoName( toUNOname( header->exceptionType->name() ) );\n ::typelib_typedescription_getByName( &pTD, unoName.pData );\n OSL_ENSURE( pTD, \"### unknown exception type! leaving out destruction => leaking!!!\" );\n if (pTD)\n {\n ::uno_destructData( pExc, pTD, cpp_release );\n ::typelib_typedescription_release( pTD );\n }\n}\n\n\/\/==================================================================================================\nvoid raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )\n{\n#if OSL_DEBUG_LEVEL > 1\n OString cstr(\n OUStringToOString(\n *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),\n RTL_TEXTENCODING_ASCII_US ) );\n fprintf( stderr, \"> uno exception occured: %s\\n\", cstr.getStr() );\n#endif\n void * pCppExc;\n type_info * rtti;\n\n {\n \/\/ construct cpp exception object\n typelib_TypeDescription * pTypeDescr = 0;\n TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );\n OSL_ASSERT( pTypeDescr );\n if (! pTypeDescr)\n {\n throw RuntimeException(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"cannot get typedescription for type \") ) +\n *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),\n Reference< XInterface >() );\n }\n\n pCppExc = __cxa_allocate_exception( pTypeDescr->nSize );\n ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );\n\n \/\/ destruct uno exception\n ::uno_any_destruct( pUnoExc, 0 );\n \/\/ avoiding locked counts\n static RTTI * s_rtti = 0;\n if (! s_rtti)\n {\n MutexGuard guard( Mutex::getGlobalMutex() );\n if (! s_rtti)\n {\n#ifdef LEAK_STATIC_DATA\n s_rtti = new RTTI();\n#else\n static RTTI rtti_data;\n s_rtti = &rtti_data;\n#endif\n }\n }\n rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr );\n TYPELIB_DANGER_RELEASE( pTypeDescr );\n OSL_ENSURE( rtti, \"### no rtti for throwing exception!\" );\n if (! rtti)\n {\n throw RuntimeException(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"no rtti for type \") ) +\n *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),\n Reference< XInterface >() );\n }\n }\n\n __cxa_throw( pCppExc, rtti, deleteException );\n}\n\n\/\/==================================================================================================\nvoid fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno )\n{\n if (! header)\n {\n RuntimeException aRE(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"no exception header!\") ),\n Reference< XInterface >() );\n Type const & rType = ::getCppuType( &aRE );\n uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );\n#if OSL_DEBUG_LEVEL > 0\n OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_ENSURE( 0, cstr.getStr() );\n#endif\n return;\n }\n\n typelib_TypeDescription * pExcTypeDescr = 0;\n OUString unoName( toUNOname( header->exceptionType->name() ) );\n#if OSL_DEBUG_LEVEL > 1\n OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) );\n fprintf( stderr, \"> c++ exception occured: %s\\n\", cstr_unoName.getStr() );\n#endif\n typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );\n if (0 == pExcTypeDescr)\n {\n RuntimeException aRE(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"exception type not found: \") ) + unoName,\n Reference< XInterface >() );\n Type const & rType = ::getCppuType( &aRE );\n uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );\n#if OSL_DEBUG_LEVEL > 0\n OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_ENSURE( 0, cstr.getStr() );\n#endif\n }\n else\n {\n \/\/ construct uno exception any\n uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );\n typelib_typedescription_release( pExcTypeDescr );\n }\n}\n\n}\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.2.48); FILE MERGED 2006\/09\/01 17:17:35 kaib 1.2.48.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: except.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 15:51:22 $\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_bridges.hxx\"\n\n#include <stdio.h>\n#include <dlfcn.h>\n#include <cxxabi.h>\n#include <hash_map>\n\n#include <rtl\/strbuf.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <osl\/diagnose.h>\n#include <osl\/mutex.hxx>\n\n#include <com\/sun\/star\/uno\/genfunc.hxx>\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include <typelib\/typedescription.hxx>\n#include <uno\/any2.h>\n\n#include \"share.hxx\"\n\n\nusing namespace ::std;\nusing namespace ::osl;\nusing namespace ::rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::__cxxabiv1;\n\n\nnamespace CPPU_CURRENT_NAMESPACE\n{\n\nvoid dummy_can_throw_anything( char const * )\n{\n}\n\n\/\/==================================================================================================\nstatic OUString toUNOname( char const * p ) SAL_THROW( () )\n{\n#if OSL_DEBUG_LEVEL > 1\n char const * start = p;\n#endif\n\n \/\/ example: N3com3sun4star4lang24IllegalArgumentExceptionE\n\n OUStringBuffer buf( 64 );\n OSL_ASSERT( 'N' == *p );\n ++p; \/\/ skip N\n\n while ('E' != *p)\n {\n \/\/ read chars count\n long n = (*p++ - '0');\n while ('0' <= *p && '9' >= *p)\n {\n n *= 10;\n n += (*p++ - '0');\n }\n buf.appendAscii( p, n );\n p += n;\n if ('E' != *p)\n buf.append( (sal_Unicode)'.' );\n }\n\n#if OSL_DEBUG_LEVEL > 1\n OUString ret( buf.makeStringAndClear() );\n OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) );\n fprintf( stderr, \"> toUNOname(): %s => %s\\n\", start, c_ret.getStr() );\n return ret;\n#else\n return buf.makeStringAndClear();\n#endif\n}\n\n\/\/==================================================================================================\nclass RTTI\n{\n typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map;\n\n Mutex m_mutex;\n t_rtti_map m_rttis;\n t_rtti_map m_generatedRttis;\n\n void * m_hApp;\n\npublic:\n RTTI() SAL_THROW( () );\n ~RTTI() SAL_THROW( () );\n\n type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () );\n};\n\/\/__________________________________________________________________________________________________\nRTTI::RTTI() SAL_THROW( () )\n : m_hApp( dlopen( 0, RTLD_LAZY ) )\n{\n}\n\/\/__________________________________________________________________________________________________\nRTTI::~RTTI() SAL_THROW( () )\n{\n dlclose( m_hApp );\n}\n\n\/\/__________________________________________________________________________________________________\ntype_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () )\n{\n type_info * rtti;\n\n OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName;\n\n MutexGuard guard( m_mutex );\n t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) );\n if (iFind == m_rttis.end())\n {\n \/\/ RTTI symbol\n OStringBuffer buf( 64 );\n buf.append( RTL_CONSTASCII_STRINGPARAM(\"_ZTIN\") );\n sal_Int32 index = 0;\n do\n {\n OUString token( unoName.getToken( 0, '.', index ) );\n buf.append( token.getLength() );\n OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );\n buf.append( c_token );\n }\n while (index >= 0);\n buf.append( 'E' );\n\n OString symName( buf.makeStringAndClear() );\n rtti = (type_info *)dlsym( m_hApp, symName.getStr() );\n\n if (rtti)\n {\n pair< t_rtti_map::iterator, bool > insertion(\n m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );\n OSL_ENSURE( insertion.second, \"### inserting new rtti failed?!\" );\n }\n else\n {\n \/\/ try to lookup the symbol in the generated rtti map\n t_rtti_map::const_iterator iFind2( m_generatedRttis.find( unoName ) );\n if (iFind2 == m_generatedRttis.end())\n {\n \/\/ we must generate it !\n \/\/ symbol and rtti-name is nearly identical,\n \/\/ the symbol is prefixed with _ZTI\n char const * rttiName = symName.getStr() +4;\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stderr,\"generated rtti for %s\\n\", rttiName );\n#endif\n if (pTypeDescr->pBaseTypeDescription)\n {\n \/\/ ensure availability of base\n type_info * base_rtti = getRTTI(\n (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription );\n rtti = new __si_class_type_info(\n strdup( rttiName ), (__class_type_info *)base_rtti );\n }\n else\n {\n \/\/ this class has no base class\n rtti = new __class_type_info( strdup( rttiName ) );\n }\n\n pair< t_rtti_map::iterator, bool > insertion(\n m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );\n OSL_ENSURE( insertion.second, \"### inserting new generated rtti failed?!\" );\n }\n else \/\/ taking already generated rtti\n {\n rtti = iFind2->second;\n }\n }\n }\n else\n {\n rtti = iFind->second;\n }\n\n return rtti;\n}\n\n\/\/--------------------------------------------------------------------------------------------------\nstatic void deleteException( void * pExc )\n{\n __cxa_exception const * header = ((__cxa_exception const *)pExc - 1);\n typelib_TypeDescription * pTD = 0;\n OUString unoName( toUNOname( header->exceptionType->name() ) );\n ::typelib_typedescription_getByName( &pTD, unoName.pData );\n OSL_ENSURE( pTD, \"### unknown exception type! leaving out destruction => leaking!!!\" );\n if (pTD)\n {\n ::uno_destructData( pExc, pTD, cpp_release );\n ::typelib_typedescription_release( pTD );\n }\n}\n\n\/\/==================================================================================================\nvoid raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )\n{\n#if OSL_DEBUG_LEVEL > 1\n OString cstr(\n OUStringToOString(\n *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),\n RTL_TEXTENCODING_ASCII_US ) );\n fprintf( stderr, \"> uno exception occured: %s\\n\", cstr.getStr() );\n#endif\n void * pCppExc;\n type_info * rtti;\n\n {\n \/\/ construct cpp exception object\n typelib_TypeDescription * pTypeDescr = 0;\n TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );\n OSL_ASSERT( pTypeDescr );\n if (! pTypeDescr)\n {\n throw RuntimeException(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"cannot get typedescription for type \") ) +\n *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),\n Reference< XInterface >() );\n }\n\n pCppExc = __cxa_allocate_exception( pTypeDescr->nSize );\n ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );\n\n \/\/ destruct uno exception\n ::uno_any_destruct( pUnoExc, 0 );\n \/\/ avoiding locked counts\n static RTTI * s_rtti = 0;\n if (! s_rtti)\n {\n MutexGuard guard( Mutex::getGlobalMutex() );\n if (! s_rtti)\n {\n#ifdef LEAK_STATIC_DATA\n s_rtti = new RTTI();\n#else\n static RTTI rtti_data;\n s_rtti = &rtti_data;\n#endif\n }\n }\n rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr );\n TYPELIB_DANGER_RELEASE( pTypeDescr );\n OSL_ENSURE( rtti, \"### no rtti for throwing exception!\" );\n if (! rtti)\n {\n throw RuntimeException(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"no rtti for type \") ) +\n *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),\n Reference< XInterface >() );\n }\n }\n\n __cxa_throw( pCppExc, rtti, deleteException );\n}\n\n\/\/==================================================================================================\nvoid fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno )\n{\n if (! header)\n {\n RuntimeException aRE(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"no exception header!\") ),\n Reference< XInterface >() );\n Type const & rType = ::getCppuType( &aRE );\n uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );\n#if OSL_DEBUG_LEVEL > 0\n OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_ENSURE( 0, cstr.getStr() );\n#endif\n return;\n }\n\n typelib_TypeDescription * pExcTypeDescr = 0;\n OUString unoName( toUNOname( header->exceptionType->name() ) );\n#if OSL_DEBUG_LEVEL > 1\n OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) );\n fprintf( stderr, \"> c++ exception occured: %s\\n\", cstr_unoName.getStr() );\n#endif\n typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );\n if (0 == pExcTypeDescr)\n {\n RuntimeException aRE(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"exception type not found: \") ) + unoName,\n Reference< XInterface >() );\n Type const & rType = ::getCppuType( &aRE );\n uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );\n#if OSL_DEBUG_LEVEL > 0\n OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_ENSURE( 0, cstr.getStr() );\n#endif\n }\n else\n {\n \/\/ construct uno exception any\n uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );\n typelib_typedescription_release( pExcTypeDescr );\n }\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef LCPP_OBJECT_H\n#define LCPP_OBJECT_H\n\n#include <luacpp\/reference.hpp>\n#include <luacpp\/table.hpp>\n#include <luacpp\/function.hpp>\n\nnamespace lua\n{\n\tclass object : virtual public reference, public table, public function\n\t{\n\t\tpublic:\n\t\tobject(lua_State* L, int index) : reference(L, index)\n\t\t{\n\t\t}\n\n\t\tobject(){}\n\n\t\tprivate:\n\t};\n}\n\n#endif\n<commit_msg>Added implicit conversion operator for lua::object<commit_after>#ifndef LCPP_OBJECT_H\n#define LCPP_OBJECT_H\n\n#include <luacpp\/stack.hpp>\n#include <luacpp\/reference.hpp>\n#include <luacpp\/table.hpp>\n#include <luacpp\/function.hpp>\n\nnamespace lua\n{\n\tclass object : virtual public reference, public table, public function\n\t{\n\t\tpublic:\n\t\tobject(lua_State* L, int index) : reference(L, index)\n\t\t{\n\t\t}\n\n\t\tobject(){}\n\n\t\ttemplate<typename T>\n\t\toperator T()\n\t\t{\n\t\t\tpush();\n\t\t\tassertType(state(), -1, typeOf<T>(state()));\n\n\t\t\tT t;\n\n\t\t\tgetValue(state(), -1, t);\n\n\t\t\treturn t;\n\t\t}\n\t};\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ yas_db_utils.cpp\n\/\/\n\n#include \"yas_db_additional_protocol.h\"\n#include \"yas_db_attribute.h\"\n#include \"yas_db_database.h\"\n#include \"yas_db_model.h\"\n#include \"yas_db_row_set.h\"\n#include \"yas_db_select_option.h\"\n#include \"yas_db_sql_utils.h\"\n#include \"yas_db_utils.h\"\n#include \"yas_unless.h\"\n\nusing namespace yas;\n\ndb::update_result db::create_table(db::database &db, std::string const &table_name,\n std::vector<std::string> const &fields) {\n return db.execute_update(create_table_sql(table_name, fields));\n}\n\ndb::update_result db::alter_table(db::database &db, std::string const &table_name, std::string const &field) {\n return db.execute_update(alter_table_sql(table_name, field));\n}\n\ndb::update_result db::drop_table(db::database &db, std::string const &table_name) {\n return db.execute_update(drop_table_sql(table_name));\n}\n\ndb::update_result db::create_index(database &db, std::string const &index_name, std::string const &table_name,\n std::vector<std::string> const &fields) {\n return db.execute_update(create_index_sql(index_name, table_name, fields));\n}\n\ndb::update_result db::drop_index(database &db, std::string const &index_name) {\n return db.execute_update(drop_index_sql(index_name));\n}\n\ndb::update_result db::begin_transaction(db::database &db) {\n return db.execute_update(\"BEGIN EXCLUSIVE TRANSACTION\");\n}\n\ndb::update_result db::begin_deferred_transaction(db::database &db) {\n return db.execute_update(\"BEGIN DEFERRED TRANSACTION\");\n}\n\ndb::update_result db::commit(db::database &db) {\n return db.execute_update(\"COMMIT TRANSACTION\");\n}\n\ndb::update_result db::rollback(db::database &db) {\n return db.execute_update(\"ROLLBACK TRANSACTION\");\n}\n\n#if SQLITE_VERSION_NUMBER >= 3007000\n\nnamespace yas {\nnamespace db {\n static std::string escape_save_point_name(std::string const &name) {\n return replaced(name, \"'\", \"''\");\n }\n}\n}\n\ndb::update_result db::start_save_point(db::database &db, std::string const &name) {\n if (name.size() == 0) {\n return update_result{error{error_type::invalid_argument}};\n }\n return db.execute_update(\"SAVEPOINT '\" + escape_save_point_name(name) + \"';\");\n}\n\ndb::update_result db::release_save_point(db::database &db, std::string const &name) {\n if (name.size() == 0) {\n return update_result{error{error_type::invalid_argument}};\n }\n return db.execute_update(\"RELEASE SAVEPOINT '\" + escape_save_point_name(name) + \"';\");\n}\n\ndb::update_result db::rollback_save_point(db::database &db, std::string const &name) {\n if (name.size() == 0) {\n return update_result{error{error_type::invalid_argument}};\n }\n return db.execute_update(\"ROLLBACK TRANSACTION TO SAVEPOINT '\" + escape_save_point_name(name) + \"';\");\n}\n\ndb::update_result db::in_save_point(db::database &db, std::function<void(bool &rollback)> const function) {\n static unsigned long save_point_idx = 0;\n std::string const name = \"db_save_point_\" + std::to_string(save_point_idx++);\n\n if (auto ul = unless(start_save_point(db, name))) {\n return std::move(ul.value);\n }\n\n bool should_rollback = false;\n\n function(should_rollback);\n\n if (should_rollback) {\n rollback_save_point(db, name);\n }\n\n return release_save_point(db, name);\n}\n\n#endif\n\nbool db::table_exists(database const &db, std::string const &table_name) {\n if (auto row_set = get_table_schema(db, table_name)) {\n if (row_set.next()) {\n return true;\n }\n }\n return false;\n}\n\nbool db::index_exists(database const &db, std::string const &index_name) {\n if (auto row_set = get_index_schema(db, index_name)) {\n if (row_set.next()) {\n return true;\n }\n }\n return false;\n}\n\ndb::row_set db::get_schema(database const &db) {\n if (auto query_result = db.execute_query(\n \"select type, name, tbl_name, rootpage, sql from (select * from sqlite_master union all select * from \"\n \"sqlite_temp_master) where type != 'meta' and name not like 'sqlite_%' order by tbl_name, type desc, \"\n \"name\")) {\n return query_result.value();\n }\n return nullptr;\n}\n\ndb::row_set db::get_table_schema(database const &db, std::string const &table_name) {\n if (auto query_result = db.execute_query(\"PRAGMA table_info('\" + table_name + \"')\")) {\n return query_result.value();\n }\n return nullptr;\n}\n\ndb::row_set db::get_index_schema(database const &db, std::string const &index_name) {\n if (auto query_result =\n db.execute_query(\"SELECT * FROM sqlite_master WHERE type = 'index' AND name = '\" + index_name + \"';\")) {\n return query_result.value();\n }\n return nullptr;\n}\n\nbool db::column_exists(database const &db, std::string column_name, std::string table_name) {\n std::string lower_table_name = to_lower(std::move(table_name));\n std::string lower_column_name = to_lower(std::move(column_name));\n\n if (auto row_set = get_table_schema(db, lower_table_name)) {\n while (row_set.next()) {\n auto value = row_set.column_value(\"name\");\n if (to_lower(value.get<db::text>()) == lower_column_name) {\n return true;\n }\n }\n }\n\n return false;\n}\n\ndb::select_result db::select(db::database const &db, select_option const &option) {\n auto const sql =\n select_sql(option.table, option.fields, option.where_exprs, option.field_orders, option.limit_range);\n\n db::value_map_vector value_map_vector;\n\n if (auto query_result = db.execute_query(sql, option.arguments)) {\n auto row_set = query_result.value();\n while (row_set.next()) {\n value_map_vector.emplace_back(row_set.value_map());\n }\n } else {\n return select_result{std::move(query_result.error())};\n }\n\n return select_result{value_map_vector};\n}\n\ndb::select_result db::select_last(database const &db, select_option option, value const &save_id,\n bool const include_removed) {\n std::vector<std::string> components;\n\n if (save_id) {\n components.emplace_back(expr(save_id_field, \"<=\", to_string(save_id)));\n }\n\n if (option.where_exprs.size() > 0) {\n components.emplace_back(option.where_exprs);\n }\n\n std::string sub_where = components.size() > 0 ? \" WHERE \" + joined(components, \" AND \") : \"\";\n\n std::string where_exprs =\n \"rowid IN (SELECT MAX(rowid) FROM \" + option.table + sub_where + \" GROUP BY \" + db::object_id_field + \")\";\n if (!include_removed) {\n static std::string const exc_removed_expr = action_field + \" != '\" + remove_action + \"'\";\n where_exprs = joined({where_exprs, exc_removed_expr}, \" AND \");\n }\n option.where_exprs = where_exprs;\n\n return select(db, option);\n}\n\ndb::select_result db::select_undo(database const &db, std::string const &table_name, integer::type const revert_save_id,\n integer::type const current_save_id) {\n if (current_save_id <= revert_save_id) {\n throw \"revert_save_id greater than or equal to current_save_id\";\n }\n\n std::vector<std::string> components;\n components.emplace_back(object_id_field + \" IN (SELECT DISTINCT \" + object_id_field + \" FROM \" + table_name +\n \" WHERE \" + joined({expr(save_id_field, \"<=\", std::to_string(current_save_id)),\n expr(save_id_field, \">\", std::to_string(revert_save_id))},\n \" AND \") +\n \")\");\n components.emplace_back(expr(save_id_field, \"<=\", std::to_string(revert_save_id)));\n\n select_option option{.table = table_name,\n .where_exprs = \"rowid IN (SELECT MAX(rowid) FROM \" + table_name + \" WHERE \" +\n joined(components, \" AND \") + \" GROUP BY \" + object_id_field + \")\",\n .field_orders = {{object_id_field, order::ascending}}};\n\n auto result = select(db, option);\n if (!result) {\n return select_result{std::move(result.error())};\n }\n\n select_option empty_option{.table = table_name,\n .fields = {object_id_field},\n .where_exprs = joined({expr(save_id_field, \"<=\", std::to_string(current_save_id)),\n expr(save_id_field, \">\", std::to_string(revert_save_id)),\n equal_field_expr(action_field)},\n \" AND \"),\n .arguments = {{action_field, db::value{insert_action}}},\n .field_orders = {{object_id_field, order::ascending}}};\n auto empty_result = select(db, empty_option);\n if (!empty_result) {\n return select_result{std::move(empty_result.error())};\n }\n\n return select_result{connect(std::move(result.value()), std::move(empty_result.value()))};\n}\n\ndb::select_result db::select_redo(database const &db, std::string const &table_name, integer::type const revert_save_id,\n integer::type const current_save_id) {\n if (revert_save_id <= current_save_id) {\n throw \"current_save_id greater than or equal to revert_save_id\";\n }\n\n std::vector<std::string> components;\n components.emplace_back(expr(save_id_field, \">\", std::to_string(current_save_id)));\n\n db::select_option option{.table = table_name,\n .where_exprs = joined(components, \" AND \"),\n .field_orders = {{object_id_field, db::order::ascending}}};\n\n return select_last(db, std::move(option), db::value{revert_save_id}, true);\n}\n\ndb::select_result db::select_revert(database const &db, std::string const &table_name,\n integer::type const revert_save_id, integer::type const current_save_id) {\n if (revert_save_id < current_save_id) {\n return select_undo(db, table_name, revert_save_id, current_save_id);\n } else if (current_save_id < revert_save_id) {\n return select_redo(db, table_name, revert_save_id, current_save_id);\n }\n\n return select_result{value_map_vector{}};\n}\n\ndb::select_single_result db::select_single(database const &db, select_option option) {\n option.limit_range = {.location = 0, .length = 1};\n\n if (auto result = select(db, option)) {\n if (result.value().size() > 0) {\n return select_single_result{std::move(result.value().at(0))};\n }\n }\n\n return select_single_result{nullptr};\n}\n\ndb::select_single_result db::select_db_info(database const &db) {\n return select_single(db, db::select_option{.table = db::info_table});\n}\n\ndb::update_result db::purge(database &db, std::string const &table_name) {\n std::string where_exprs =\n \"NOT rowid IN (SELECT MAX(rowid) FROM \" + table_name + \" GROUP BY \" + db::object_id_field + \")\";\n return db.execute_update(delete_sql(table_name, where_exprs));\n}\n\ndb::update_result db::purge_relation(database &db, std::string const &table_name, std::string const &src_table_name) {\n std::string where_exprs = \"NOT \" + db::src_id_field + \" IN (SELECT rowid FROM \" + src_table_name + \")\";\n return db.execute_update(delete_sql(table_name, where_exprs));\n}\n\ndb::value db::max(database const &db, std::string const &table_name, std::string const &field) {\n if (auto query_result = db.execute_query(\"SELECT MAX(\" + field + \") FROM \" + table_name + \";\")) {\n auto &row_set = query_result.value();\n if (row_set.next()) {\n return row_set.column_value(0);\n }\n }\n return nullptr;\n}\n<commit_msg>fix include in db_utils<commit_after>\/\/\n\/\/ yas_db_utils.cpp\n\/\/\n\n#include \"yas_db_additional_protocol.h\"\n#include \"yas_db_attribute.h\"\n#include \"yas_db_database.h\"\n#include \"yas_db_model.h\"\n#include \"yas_db_row_set.h\"\n#include \"yas_db_select_option.h\"\n#include \"yas_db_sql_utils.h\"\n#include \"yas_db_utils.h\"\n#include \"yas_stl_utils.h\"\n#include \"yas_unless.h\"\n\nusing namespace yas;\n\ndb::update_result db::create_table(db::database &db, std::string const &table_name,\n std::vector<std::string> const &fields) {\n return db.execute_update(create_table_sql(table_name, fields));\n}\n\ndb::update_result db::alter_table(db::database &db, std::string const &table_name, std::string const &field) {\n return db.execute_update(alter_table_sql(table_name, field));\n}\n\ndb::update_result db::drop_table(db::database &db, std::string const &table_name) {\n return db.execute_update(drop_table_sql(table_name));\n}\n\ndb::update_result db::create_index(database &db, std::string const &index_name, std::string const &table_name,\n std::vector<std::string> const &fields) {\n return db.execute_update(create_index_sql(index_name, table_name, fields));\n}\n\ndb::update_result db::drop_index(database &db, std::string const &index_name) {\n return db.execute_update(drop_index_sql(index_name));\n}\n\ndb::update_result db::begin_transaction(db::database &db) {\n return db.execute_update(\"BEGIN EXCLUSIVE TRANSACTION\");\n}\n\ndb::update_result db::begin_deferred_transaction(db::database &db) {\n return db.execute_update(\"BEGIN DEFERRED TRANSACTION\");\n}\n\ndb::update_result db::commit(db::database &db) {\n return db.execute_update(\"COMMIT TRANSACTION\");\n}\n\ndb::update_result db::rollback(db::database &db) {\n return db.execute_update(\"ROLLBACK TRANSACTION\");\n}\n\n#if SQLITE_VERSION_NUMBER >= 3007000\n\nnamespace yas {\nnamespace db {\n static std::string escape_save_point_name(std::string const &name) {\n return replaced(name, \"'\", \"''\");\n }\n}\n}\n\ndb::update_result db::start_save_point(db::database &db, std::string const &name) {\n if (name.size() == 0) {\n return update_result{error{error_type::invalid_argument}};\n }\n return db.execute_update(\"SAVEPOINT '\" + escape_save_point_name(name) + \"';\");\n}\n\ndb::update_result db::release_save_point(db::database &db, std::string const &name) {\n if (name.size() == 0) {\n return update_result{error{error_type::invalid_argument}};\n }\n return db.execute_update(\"RELEASE SAVEPOINT '\" + escape_save_point_name(name) + \"';\");\n}\n\ndb::update_result db::rollback_save_point(db::database &db, std::string const &name) {\n if (name.size() == 0) {\n return update_result{error{error_type::invalid_argument}};\n }\n return db.execute_update(\"ROLLBACK TRANSACTION TO SAVEPOINT '\" + escape_save_point_name(name) + \"';\");\n}\n\ndb::update_result db::in_save_point(db::database &db, std::function<void(bool &rollback)> const function) {\n static unsigned long save_point_idx = 0;\n std::string const name = \"db_save_point_\" + std::to_string(save_point_idx++);\n\n if (auto ul = unless(start_save_point(db, name))) {\n return std::move(ul.value);\n }\n\n bool should_rollback = false;\n\n function(should_rollback);\n\n if (should_rollback) {\n rollback_save_point(db, name);\n }\n\n return release_save_point(db, name);\n}\n\n#endif\n\nbool db::table_exists(database const &db, std::string const &table_name) {\n if (auto row_set = get_table_schema(db, table_name)) {\n if (row_set.next()) {\n return true;\n }\n }\n return false;\n}\n\nbool db::index_exists(database const &db, std::string const &index_name) {\n if (auto row_set = get_index_schema(db, index_name)) {\n if (row_set.next()) {\n return true;\n }\n }\n return false;\n}\n\ndb::row_set db::get_schema(database const &db) {\n if (auto query_result = db.execute_query(\n \"select type, name, tbl_name, rootpage, sql from (select * from sqlite_master union all select * from \"\n \"sqlite_temp_master) where type != 'meta' and name not like 'sqlite_%' order by tbl_name, type desc, \"\n \"name\")) {\n return query_result.value();\n }\n return nullptr;\n}\n\ndb::row_set db::get_table_schema(database const &db, std::string const &table_name) {\n if (auto query_result = db.execute_query(\"PRAGMA table_info('\" + table_name + \"')\")) {\n return query_result.value();\n }\n return nullptr;\n}\n\ndb::row_set db::get_index_schema(database const &db, std::string const &index_name) {\n if (auto query_result =\n db.execute_query(\"SELECT * FROM sqlite_master WHERE type = 'index' AND name = '\" + index_name + \"';\")) {\n return query_result.value();\n }\n return nullptr;\n}\n\nbool db::column_exists(database const &db, std::string column_name, std::string table_name) {\n std::string lower_table_name = to_lower(std::move(table_name));\n std::string lower_column_name = to_lower(std::move(column_name));\n\n if (auto row_set = get_table_schema(db, lower_table_name)) {\n while (row_set.next()) {\n auto value = row_set.column_value(\"name\");\n if (to_lower(value.get<db::text>()) == lower_column_name) {\n return true;\n }\n }\n }\n\n return false;\n}\n\ndb::select_result db::select(db::database const &db, select_option const &option) {\n auto const sql =\n select_sql(option.table, option.fields, option.where_exprs, option.field_orders, option.limit_range);\n\n db::value_map_vector value_map_vector;\n\n if (auto query_result = db.execute_query(sql, option.arguments)) {\n auto row_set = query_result.value();\n while (row_set.next()) {\n value_map_vector.emplace_back(row_set.value_map());\n }\n } else {\n return select_result{std::move(query_result.error())};\n }\n\n return select_result{value_map_vector};\n}\n\ndb::select_result db::select_last(database const &db, select_option option, value const &save_id,\n bool const include_removed) {\n std::vector<std::string> components;\n\n if (save_id) {\n components.emplace_back(expr(save_id_field, \"<=\", to_string(save_id)));\n }\n\n if (option.where_exprs.size() > 0) {\n components.emplace_back(option.where_exprs);\n }\n\n std::string sub_where = components.size() > 0 ? \" WHERE \" + joined(components, \" AND \") : \"\";\n\n std::string where_exprs =\n \"rowid IN (SELECT MAX(rowid) FROM \" + option.table + sub_where + \" GROUP BY \" + db::object_id_field + \")\";\n if (!include_removed) {\n static std::string const exc_removed_expr = action_field + \" != '\" + remove_action + \"'\";\n where_exprs = joined({where_exprs, exc_removed_expr}, \" AND \");\n }\n option.where_exprs = where_exprs;\n\n return select(db, option);\n}\n\ndb::select_result db::select_undo(database const &db, std::string const &table_name, integer::type const revert_save_id,\n integer::type const current_save_id) {\n if (current_save_id <= revert_save_id) {\n throw \"revert_save_id greater than or equal to current_save_id\";\n }\n\n std::vector<std::string> components;\n components.emplace_back(object_id_field + \" IN (SELECT DISTINCT \" + object_id_field + \" FROM \" + table_name +\n \" WHERE \" + joined({expr(save_id_field, \"<=\", std::to_string(current_save_id)),\n expr(save_id_field, \">\", std::to_string(revert_save_id))},\n \" AND \") +\n \")\");\n components.emplace_back(expr(save_id_field, \"<=\", std::to_string(revert_save_id)));\n\n select_option option{.table = table_name,\n .where_exprs = \"rowid IN (SELECT MAX(rowid) FROM \" + table_name + \" WHERE \" +\n joined(components, \" AND \") + \" GROUP BY \" + object_id_field + \")\",\n .field_orders = {{object_id_field, order::ascending}}};\n\n auto result = select(db, option);\n if (!result) {\n return select_result{std::move(result.error())};\n }\n\n select_option empty_option{.table = table_name,\n .fields = {object_id_field},\n .where_exprs = joined({expr(save_id_field, \"<=\", std::to_string(current_save_id)),\n expr(save_id_field, \">\", std::to_string(revert_save_id)),\n equal_field_expr(action_field)},\n \" AND \"),\n .arguments = {{action_field, db::value{insert_action}}},\n .field_orders = {{object_id_field, order::ascending}}};\n auto empty_result = select(db, empty_option);\n if (!empty_result) {\n return select_result{std::move(empty_result.error())};\n }\n\n return select_result{connect(std::move(result.value()), std::move(empty_result.value()))};\n}\n\ndb::select_result db::select_redo(database const &db, std::string const &table_name, integer::type const revert_save_id,\n integer::type const current_save_id) {\n if (revert_save_id <= current_save_id) {\n throw \"current_save_id greater than or equal to revert_save_id\";\n }\n\n std::vector<std::string> components;\n components.emplace_back(expr(save_id_field, \">\", std::to_string(current_save_id)));\n\n db::select_option option{.table = table_name,\n .where_exprs = joined(components, \" AND \"),\n .field_orders = {{object_id_field, db::order::ascending}}};\n\n return select_last(db, std::move(option), db::value{revert_save_id}, true);\n}\n\ndb::select_result db::select_revert(database const &db, std::string const &table_name,\n integer::type const revert_save_id, integer::type const current_save_id) {\n if (revert_save_id < current_save_id) {\n return select_undo(db, table_name, revert_save_id, current_save_id);\n } else if (current_save_id < revert_save_id) {\n return select_redo(db, table_name, revert_save_id, current_save_id);\n }\n\n return select_result{value_map_vector{}};\n}\n\ndb::select_single_result db::select_single(database const &db, select_option option) {\n option.limit_range = {.location = 0, .length = 1};\n\n if (auto result = select(db, option)) {\n if (result.value().size() > 0) {\n return select_single_result{std::move(result.value().at(0))};\n }\n }\n\n return select_single_result{nullptr};\n}\n\ndb::select_single_result db::select_db_info(database const &db) {\n return select_single(db, db::select_option{.table = db::info_table});\n}\n\ndb::update_result db::purge(database &db, std::string const &table_name) {\n std::string where_exprs =\n \"NOT rowid IN (SELECT MAX(rowid) FROM \" + table_name + \" GROUP BY \" + db::object_id_field + \")\";\n return db.execute_update(delete_sql(table_name, where_exprs));\n}\n\ndb::update_result db::purge_relation(database &db, std::string const &table_name, std::string const &src_table_name) {\n std::string where_exprs = \"NOT \" + db::src_id_field + \" IN (SELECT rowid FROM \" + src_table_name + \")\";\n return db.execute_update(delete_sql(table_name, where_exprs));\n}\n\ndb::value db::max(database const &db, std::string const &table_name, std::string const &field) {\n if (auto query_result = db.execute_query(\"SELECT MAX(\" + field + \") FROM \" + table_name + \";\")) {\n auto &row_set = query_result.value();\n if (row_set.next()) {\n return row_set.column_value(0);\n }\n }\n return nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012 Utkin Dmitry\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 * This file is part of the WSF Staff project.\n * Please, visit http:\/\/code.google.com\/p\/staff for more information.\n *\/\n\n#include <staff\/utils\/console.h>\n#include <staff\/utils\/Log.h>\n#include <staff\/utils\/SharedPtr.h>\n#include <staff\/utils\/stringutils.h>\n#include <staff\/xml\/Document.h>\n#include <staff\/common\/Exception.h>\n#include <staff\/common\/Runtime.h>\n#include <staff\/common\/DataObject.h>\n#include <staff\/common\/Operation.h>\n#include <staff\/component\/SharedContext.h>\n#include <staff\/component\/ServiceWrapper.h>\n#include <staff\/das\/common\/DataSource.h>\n#include <staff\/das\/common\/Executor.h>\n#include \"Services.h\"\n\n\nnamespace staff\n{\nnamespace das\n{\n\n class ServicesRawExecutor: public IRawExecutor\n {\n public:\n ServicesRawExecutor(ServicesProvider* pProvider):\n m_pProvider(pProvider)\n {\n }\n\n virtual void Execute(const std::string& sSessionId,\n const std::string& sExecute, const DataObject& rdoContext,\n const DataType& \/*rReturnType*\/, DataObject& rdoResult)\n {\n STAFF_ASSERT(m_pProvider != NULL && m_pProvider->m_pServiceWrapper != NULL, \"Not Initialized\");\n\n std::string::size_type nPosBegin = 0;\n std::string::size_type nPosEnd = 0;\n\n nPosBegin = sExecute.find('(');\n nPosEnd = sExecute.find_last_of(')');\n\n STAFF_ASSERT(nPosBegin != std::string::npos && nPosEnd != std::string::npos &&\n nPosEnd > nPosBegin, \"Invalid execute statement.\\nIt should be in form \"\n \"\\\"<execute>ElementName([par0=val, par1=$var1, par2=$[DO_val], ...])<\/execute>\\\"\");\n\n std::string sParam;\n std::string sValue;\n std::string sElement;\n std::string sArguments = sExecute.substr(nPosBegin + 1, nPosEnd - nPosBegin - 1);\n\n StringTrim(sArguments);\n\n \/\/ check for junk\n sElement = sExecute.substr(nPosEnd + 1);\n StringTrim(sElement);\n STAFF_ASSERT(sElement.empty(), \"Junk at end of operation: [\" + sElement + \"]\");\n\n \/\/ request element name\n sElement = sExecute.substr(0, nPosBegin);\n StringTrim(sElement);\n\n \/\/ operation name\n staff::Operation tOperation(sElement);\n staff::DataObject& rdoRequest = tOperation.Request();\n tOperation.SetResponse(rdoResult);\n tOperation.GetResponse().SetOwner(false);\n\n if (!sArguments.empty())\n {\n nPosBegin = 0;\n nPosEnd = 0;\n\n while (nPosEnd != std::string::npos)\n {\n nPosEnd = sArguments.find('=', nPosBegin);\n STAFF_ASSERT(nPosEnd != std::string::npos, \"Unexpected end of parameter after: [\"\n + sArguments.substr(nPosBegin) + \"]\");\n\n \/\/ parameter's name\n sParam = sArguments.substr(nPosBegin, nPosEnd - nPosBegin);\n StringTrim(sParam);\n nPosBegin = nPosEnd + 1;\n\n \/\/ parameter's value\n nPosEnd = sArguments.find(',', nPosBegin);\n\n if (nPosEnd != std::string::npos)\n {\n sValue = sArguments.substr(nPosBegin, nPosEnd - nPosBegin);\n }\n else\n {\n sValue = sArguments.substr(nPosBegin);\n }\n StringTrim(sValue);\n\n if (!sValue.empty() && sValue[0] == '$')\n {\n \/\/ pass dataobject\n if (sValue[1] == '[' && sValue[sValue.size() - 1] == ']')\n {\n const std::string& sChildName = sValue.substr(2, sValue.size() - 3);\n DataObject doChild;\n GetChild(rdoContext, sChildName, doChild);\n doChild.SetLocalName(sParam);\n rdoRequest.AppendChild(doChild);\n }\n }\n else\n {\n rdoRequest.CreateChild(sParam, sValue);\n }\n\n nPosBegin = nPosEnd + 1;\n }\n }\n\n#ifdef _DEBUG\n LogDebug2() << \"Invoking service [\" << m_pProvider->m_pServiceWrapper->GetName() << \"]: \\n\"\n << ColorTextBlue << rdoRequest.ToString() << ColorDefault;\n#endif\n m_pProvider->m_pServiceWrapper->Invoke(tOperation, sSessionId, \"\");\n\n if (rdoResult != tOperation.GetResponse())\n {\n \/\/ this may occur in case of using variables as return value\n std::string sResponseName;\n rdoResult.GetLocalName(sResponseName);\n rdoResult.ReplaceNode(tOperation.GetResponse());\n rdoResult.SetLocalName(sResponseName);\n }\n\n#ifdef _DEBUG\n LogDebug2() << \"Service [\" << m_pProvider->m_pServiceWrapper->GetName() << \"] response: \\n\"\n << ColorTextBlue << rdoResult.ToString() << ColorDefault;\n#endif\n\n \/* example of response:\n <Response>\n <RowItem>\n <Field_1>data 1<\/Field_1><Field_2>2<\/Field_2>...\n <\/RowItem>\n ...\n <\/Response>\n *\/\n }\n\n void GetChild(const DataObject& rdoContext, const std::string& sPath, DataObject& rdoResult)\n {\n rdoResult = rdoContext;\n\n if (!sPath.empty())\n {\n std::string sName;\n std::string::size_type nSize = sPath.size();\n STAFF_ASSERT(nSize > 1, \"invalid node name: [\" + sPath + \"]\");\n\n std::string::size_type nBegin = 0;\n std::string::size_type nEnd = 0;\n do\n {\n nEnd = sPath.find('.', nBegin);\n if (nEnd == std::string::npos)\n {\n sName = sPath.substr(nBegin);\n }\n else\n {\n sName = sPath.substr(nBegin, nEnd - nBegin);\n }\n\n if (sName.empty()) \/\/ parent node\n {\n rdoResult = rdoResult.Parent();\n STAFF_ASSERT(!rdoResult.IsNull(), \"parent of root element reached while GetChild[\" + sPath + \"]\");\n }\n else\n {\n rdoResult = rdoResult.GetChildByLocalName(sName);\n }\n\n nBegin = nEnd + 1;\n }\n while(nEnd != std::string::npos);\n }\n }\n\n private:\n ServicesProvider* m_pProvider;\n };\n\n\n ServicesProvider::ServicesProvider():\n m_pServiceWrapper(NULL)\n {\n }\n\n ServicesProvider::~ServicesProvider()\n {\n Deinit();\n }\n\n void ServicesProvider::Init(const xml::Element& rConfig)\n {\n \/\/ initialize connection\n const xml::Element& rConnection = rConfig.GetChildElementByName(\"connection\");\n\n const std::string& sService = rConnection.GetChildElementByName(\"service\").GetValue();\n m_pServiceWrapper = SharedContext::Inst().GetService(sService);\n STAFF_ASSERT(m_pServiceWrapper, \"Can't find service: [\" + sService + \"]\");\n }\n\n void ServicesProvider::Deinit()\n {\n if (m_pServiceWrapper)\n {\n m_pServiceWrapper = NULL;\n }\n }\n\n const std::string& ServicesProvider::GetName() const\n {\n static const std::string sName = \"staff.das.Services\";\n return sName;\n }\n\n const std::string& ServicesProvider::GetDescr() const\n {\n static const std::string sDescr = \"Services data access provider\";\n return sDescr;\n }\n\n PExecutor ServicesProvider::GetExecutor()\n {\n return new ServicesRawExecutor(this);\n }\n\n}\n}\n\n<commit_msg>DAS: fixed crash when passing DataObject var over several services<commit_after>\/*\n * Copyright 2012 Utkin Dmitry\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 * This file is part of the WSF Staff project.\n * Please, visit http:\/\/code.google.com\/p\/staff for more information.\n *\/\n\n#include <staff\/utils\/console.h>\n#include <staff\/utils\/Log.h>\n#include <staff\/utils\/SharedPtr.h>\n#include <staff\/utils\/stringutils.h>\n#include <staff\/xml\/Document.h>\n#include <staff\/common\/Exception.h>\n#include <staff\/common\/Runtime.h>\n#include <staff\/common\/DataObject.h>\n#include <staff\/common\/Operation.h>\n#include <staff\/component\/SharedContext.h>\n#include <staff\/component\/ServiceWrapper.h>\n#include <staff\/das\/common\/DataSource.h>\n#include <staff\/das\/common\/Executor.h>\n#include \"Services.h\"\n\n\nnamespace staff\n{\nnamespace das\n{\n\n class ServicesRawExecutor: public IRawExecutor\n {\n public:\n ServicesRawExecutor(ServicesProvider* pProvider):\n m_pProvider(pProvider)\n {\n }\n\n virtual void Execute(const std::string& sSessionId,\n const std::string& sExecute, const DataObject& rdoContext,\n const DataType& \/*rReturnType*\/, DataObject& rdoResult)\n {\n STAFF_ASSERT(m_pProvider != NULL && m_pProvider->m_pServiceWrapper != NULL, \"Not Initialized\");\n\n std::string::size_type nPosBegin = 0;\n std::string::size_type nPosEnd = 0;\n\n nPosBegin = sExecute.find('(');\n nPosEnd = sExecute.find_last_of(')');\n\n STAFF_ASSERT(nPosBegin != std::string::npos && nPosEnd != std::string::npos &&\n nPosEnd > nPosBegin, \"Invalid execute statement.\\nIt should be in form \"\n \"\\\"<execute>ElementName([par0=val, par1=$var1, par2=$[DO_val], ...])<\/execute>\\\"\");\n\n std::string sParam;\n std::string sValue;\n std::string sElement;\n std::string sArguments = sExecute.substr(nPosBegin + 1, nPosEnd - nPosBegin - 1);\n\n StringTrim(sArguments);\n\n \/\/ check for junk\n sElement = sExecute.substr(nPosEnd + 1);\n StringTrim(sElement);\n STAFF_ASSERT(sElement.empty(), \"Junk at end of operation: [\" + sElement + \"]\");\n\n \/\/ request element name\n sElement = sExecute.substr(0, nPosBegin);\n StringTrim(sElement);\n\n \/\/ operation name\n staff::Operation tOperation(sElement);\n staff::DataObject& rdoRequest = tOperation.Request();\n tOperation.SetResponse(rdoResult);\n tOperation.GetResponse().SetOwner(false);\n\n if (!sArguments.empty())\n {\n nPosBegin = 0;\n nPosEnd = 0;\n\n while (nPosEnd != std::string::npos)\n {\n nPosEnd = sArguments.find('=', nPosBegin);\n STAFF_ASSERT(nPosEnd != std::string::npos, \"Unexpected end of parameter after: [\"\n + sArguments.substr(nPosBegin) + \"]\");\n\n \/\/ parameter's name\n sParam = sArguments.substr(nPosBegin, nPosEnd - nPosBegin);\n StringTrim(sParam);\n nPosBegin = nPosEnd + 1;\n\n \/\/ parameter's value\n nPosEnd = sArguments.find(',', nPosBegin);\n\n if (nPosEnd != std::string::npos)\n {\n sValue = sArguments.substr(nPosBegin, nPosEnd - nPosBegin);\n }\n else\n {\n sValue = sArguments.substr(nPosBegin);\n }\n StringTrim(sValue);\n\n if (!sValue.empty() && sValue[0] == '$')\n {\n \/\/ pass dataobject\n if (sValue[1] == '[' && sValue[sValue.size() - 1] == ']')\n {\n const std::string& sChildName = sValue.substr(2, sValue.size() - 3);\n DataObject doChild;\n GetChild(rdoContext, sChildName, doChild);\n doChild.SetLocalName(sParam);\n rdoRequest.AppendChild(doChild);\n }\n }\n else\n {\n rdoRequest.CreateChild(sParam, sValue);\n }\n\n nPosBegin = nPosEnd + 1;\n }\n }\n\n#ifdef _DEBUG\n LogDebug2() << \"Invoking service [\" << m_pProvider->m_pServiceWrapper->GetName() << \"]: \\n\"\n << ColorTextBlue << rdoRequest.ToString() << ColorDefault;\n#endif\n m_pProvider->m_pServiceWrapper->Invoke(tOperation, sSessionId, \"\");\n\n if (rdoResult != tOperation.GetResponse())\n {\n \/\/ this may occur in case of using variables as return value\n std::string sResponseName;\n rdoResult.GetLocalName(sResponseName);\n rdoResult.ReplaceNode(tOperation.GetResponse());\n rdoResult.SetLocalName(sResponseName);\n }\n\n#ifdef _DEBUG\n LogDebug2() << \"Service [\" << m_pProvider->m_pServiceWrapper->GetName() << \"] response: \\n\"\n << ColorTextBlue << rdoResult.ToString() << ColorDefault;\n#endif\n\n \/* example of response:\n <Response>\n <RowItem>\n <Field_1>data 1<\/Field_1><Field_2>2<\/Field_2>...\n <\/RowItem>\n ...\n <\/Response>\n *\/\n }\n\n void GetChild(const DataObject& rdoContext, const std::string& sPath, DataObject& rdoResult)\n {\n rdoResult = rdoContext.Copy();\n\n if (!sPath.empty())\n {\n std::string sName;\n std::string::size_type nSize = sPath.size();\n STAFF_ASSERT(nSize > 1, \"invalid node name: [\" + sPath + \"]\");\n\n std::string::size_type nBegin = 0;\n std::string::size_type nEnd = 0;\n do\n {\n nEnd = sPath.find('.', nBegin);\n if (nEnd == std::string::npos)\n {\n sName = sPath.substr(nBegin);\n }\n else\n {\n sName = sPath.substr(nBegin, nEnd - nBegin);\n }\n\n if (sName.empty()) \/\/ parent node\n {\n rdoResult = rdoResult.Parent();\n STAFF_ASSERT(!rdoResult.IsNull(), \"parent of root element reached while GetChild[\" + sPath + \"]\");\n }\n else\n {\n rdoResult = rdoResult.GetChildByLocalName(sName);\n }\n\n nBegin = nEnd + 1;\n }\n while(nEnd != std::string::npos);\n }\n }\n\n private:\n ServicesProvider* m_pProvider;\n };\n\n\n ServicesProvider::ServicesProvider():\n m_pServiceWrapper(NULL)\n {\n }\n\n ServicesProvider::~ServicesProvider()\n {\n Deinit();\n }\n\n void ServicesProvider::Init(const xml::Element& rConfig)\n {\n \/\/ initialize connection\n const xml::Element& rConnection = rConfig.GetChildElementByName(\"connection\");\n\n const std::string& sService = rConnection.GetChildElementByName(\"service\").GetValue();\n m_pServiceWrapper = SharedContext::Inst().GetService(sService);\n STAFF_ASSERT(m_pServiceWrapper, \"Can't find service: [\" + sService + \"]\");\n }\n\n void ServicesProvider::Deinit()\n {\n if (m_pServiceWrapper)\n {\n m_pServiceWrapper = NULL;\n }\n }\n\n const std::string& ServicesProvider::GetName() const\n {\n static const std::string sName = \"staff.das.Services\";\n return sName;\n }\n\n const std::string& ServicesProvider::GetDescr() const\n {\n static const std::string sDescr = \"Services data access provider\";\n return sDescr;\n }\n\n PExecutor ServicesProvider::GetExecutor()\n {\n return new ServicesRawExecutor(this);\n }\n\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Anitomy\n** Copyright (C) 2014-2015, Eren Okka\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, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <algorithm>\n\n#include \"element.h\"\n\nnamespace anitomy {\n\nbool Elements::empty() const {\n return elements_.empty();\n}\n\nsize_t Elements::size() const {\n return elements_.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nelement_iterator_t Elements::begin() {\n return elements_.begin();\n}\n\nelement_const_iterator_t Elements::begin() const {\n return elements_.begin();\n}\n\nelement_const_iterator_t Elements::cbegin() const {\n return elements_.begin();\n}\n\nelement_iterator_t Elements::end() {\n return elements_.end();\n}\n\nelement_const_iterator_t Elements::end() const {\n return elements_.end();\n}\n\nelement_const_iterator_t Elements::cend() const {\n return elements_.end();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nelement_pair_t& Elements::at(size_t position) {\n return elements_.at(position);\n}\n\nconst element_pair_t& Elements::at(size_t position) const {\n return elements_.at(position);\n}\n\nelement_pair_t& Elements::operator[](size_t position) {\n return elements_[position];\n}\n\nconst element_pair_t& Elements::operator[](size_t position) const {\n return elements_[position];\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstring_t& Elements::get(ElementCategory category) {\n auto element = find(category);\n\n if (element == elements_.end())\n element = elements_.insert(elements_.end(),\n std::make_pair(category, string_t()));\n\n return element->second;\n}\n\nstd::vector<string_t> Elements::get_all(ElementCategory category) const {\n std::vector<string_t> elements;\n\n for (const auto& element : elements_)\n if (element.first == category)\n elements.push_back(element.second);\n\n return elements;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Elements::clear() {\n elements_.clear();\n}\n\nvoid Elements::insert(ElementCategory category, const string_t& value) {\n if (!value.empty())\n elements_.push_back(std::make_pair(category, value));\n}\n\nvoid Elements::erase(ElementCategory category) {\n elements_.erase(std::remove_if(elements_.begin(), elements_.end(),\n [&](const element_pair_t& element) {\n return element.first == category;\n }));\n}\n\nelement_iterator_t Elements::erase(element_iterator_t iterator) {\n return elements_.erase(iterator);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t Elements::count(ElementCategory category) const {\n return std::count_if(elements_.begin(), elements_.end(),\n [&](const element_pair_t& element) {\n return element.first == category;\n });\n}\n\nbool Elements::empty(ElementCategory category) const {\n return find(category) == elements_.end();\n}\n\nelement_iterator_t Elements::find(ElementCategory category) {\n return std::find_if(elements_.begin(), elements_.end(),\n [&](const element_pair_t& element) {\n return element.first == category;\n });\n}\n\nelement_const_iterator_t Elements::find(ElementCategory category) const {\n return std::find_if(elements_.cbegin(), elements_.cend(),\n [&](const element_pair_t& element) {\n return element.first == category;\n });\n}\n\n} \/\/ namespace anitomy<commit_msg>Fix crash when trying to erase inexistent element<commit_after>\/*\n** Anitomy\n** Copyright (C) 2014-2015, Eren Okka\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, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <algorithm>\n\n#include \"element.h\"\n\nnamespace anitomy {\n\nbool Elements::empty() const {\n return elements_.empty();\n}\n\nsize_t Elements::size() const {\n return elements_.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nelement_iterator_t Elements::begin() {\n return elements_.begin();\n}\n\nelement_const_iterator_t Elements::begin() const {\n return elements_.begin();\n}\n\nelement_const_iterator_t Elements::cbegin() const {\n return elements_.begin();\n}\n\nelement_iterator_t Elements::end() {\n return elements_.end();\n}\n\nelement_const_iterator_t Elements::end() const {\n return elements_.end();\n}\n\nelement_const_iterator_t Elements::cend() const {\n return elements_.end();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nelement_pair_t& Elements::at(size_t position) {\n return elements_.at(position);\n}\n\nconst element_pair_t& Elements::at(size_t position) const {\n return elements_.at(position);\n}\n\nelement_pair_t& Elements::operator[](size_t position) {\n return elements_[position];\n}\n\nconst element_pair_t& Elements::operator[](size_t position) const {\n return elements_[position];\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstring_t& Elements::get(ElementCategory category) {\n auto element = find(category);\n\n if (element == elements_.end())\n element = elements_.insert(elements_.end(),\n std::make_pair(category, string_t()));\n\n return element->second;\n}\n\nstd::vector<string_t> Elements::get_all(ElementCategory category) const {\n std::vector<string_t> elements;\n\n for (const auto& element : elements_)\n if (element.first == category)\n elements.push_back(element.second);\n\n return elements;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Elements::clear() {\n elements_.clear();\n}\n\nvoid Elements::insert(ElementCategory category, const string_t& value) {\n if (!value.empty())\n elements_.push_back(std::make_pair(category, value));\n}\n\nvoid Elements::erase(ElementCategory category) {\n auto iterator = std::remove_if(elements_.begin(), elements_.end(),\n [&](const element_pair_t& element) {\n return element.first == category;\n });\n elements_.erase(iterator, elements_.end());\n}\n\nelement_iterator_t Elements::erase(element_iterator_t iterator) {\n return elements_.erase(iterator);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t Elements::count(ElementCategory category) const {\n return std::count_if(elements_.begin(), elements_.end(),\n [&](const element_pair_t& element) {\n return element.first == category;\n });\n}\n\nbool Elements::empty(ElementCategory category) const {\n return find(category) == elements_.end();\n}\n\nelement_iterator_t Elements::find(ElementCategory category) {\n return std::find_if(elements_.begin(), elements_.end(),\n [&](const element_pair_t& element) {\n return element.first == category;\n });\n}\n\nelement_const_iterator_t Elements::find(ElementCategory category) const {\n return std::find_if(elements_.cbegin(), elements_.cend(),\n [&](const element_pair_t& element) {\n return element.first == category;\n });\n}\n\n} \/\/ namespace anitomy<|endoftext|>"} {"text":"<commit_before>\n\/\/ .\\Release\\x64\\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Newhall \/\/ NOLINT(whitespace\/line_length)\n\/\/ Benchmarking on 1 X 3310 MHz CPU\n\/\/ 2015\/05\/24-13:16:32\n\/\/ Benchmark Time(ns) CPU(ns) Iterations\n\/\/ -----------------------------------------------------------\n\/\/ BM_NewhallApproximation\/4 589 562 2000000\n\/\/ BM_NewhallApproximation\/8 657 624 2000000\n\/\/ BM_NewhallApproximation\/16 754 741 2000000\n\n#include <random>\n#include <vector>\n\n#include \"benchmark\/benchmark.h\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"numerics\/newhall.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\n\nusing geometry::Instant;\nusing quantities::Variation;\nusing quantities::si::Second;\n\nnamespace numerics {\n\nvoid BM_NewhallApproximation(benchmark::State& state) {\n int const degree = state.range_x();\n std::mt19937_64 random(42);\n std::vector<double> p;\n std::vector<Variation<double>> v;\n Instant const t0;\n Instant const t_min = t0 + static_cast<double>(random()) * Second;\n Instant const t_max = t_min + static_cast<double>(random()) * Second;\n\n while (state.KeepRunning()) {\n state.PauseTiming();\n p.clear();\n v.clear();\n for (int i = 0; i <= 8; ++i) {\n p.push_back(static_cast<double>(static_cast<double>(random())));\n v.push_back(static_cast<double>(static_cast<double>(random())) \/ Second);\n }\n state.ResumeTiming();\n auto const series =\n newhall::ApproximationInЧебышёвBasis<double>(\n degree, p, v, t_min, t_max);\n }\n}\n\nBENCHMARK(BM_NewhallApproximation)->Arg(4)->Arg(8)->Arg(16);\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<commit_msg>The benchmark.<commit_after>\n\/\/ .\\Release\\x64\\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Newhall \/\/ NOLINT(whitespace\/line_length)\n\/\/ Benchmarking on 1 X 3310 MHz CPU\n\/\/ 2015\/05\/24-13:16:32\n\/\/ Benchmark Time(ns) CPU(ns) Iterations\n\/\/ -----------------------------------------------------------\n\/\/ BM_NewhallApproximation\/4 589 562 2000000\n\/\/ BM_NewhallApproximation\/8 657 624 2000000\n\/\/ BM_NewhallApproximation\/16 754 741 2000000\n\n#include <random>\n#include <vector>\n\n#include \"benchmark\/benchmark.h\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"numerics\/newhall.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\n\nusing geometry::Instant;\nusing quantities::Variation;\nusing quantities::si::Second;\n\nnamespace numerics {\n\nvoid BM_NewhallApproximation(benchmark::State& state) {\n int const degree = state.range_x();\n std::mt19937_64 random(42);\n std::vector<double> p;\n std::vector<Variation<double>> v;\n Instant const t0;\n Instant const t_min = t0 + static_cast<double>(random()) * Second;\n Instant const t_max = t_min + static_cast<double>(random()) * Second;\n\n while (state.KeepRunning()) {\n state.PauseTiming();\n p.clear();\n v.clear();\n for (int i = 0; i <= 8; ++i) {\n p.push_back(static_cast<double>(static_cast<double>(random())));\n v.push_back(static_cast<double>(static_cast<double>(random())) \/ Second);\n }\n state.ResumeTiming();\n auto const series =\n NewhallApproximationInЧебышёвBasis<double>(degree, p, v, t_min, t_max);\n }\n}\n\nBENCHMARK(BM_NewhallApproximation)->Arg(4)->Arg(8)->Arg(16);\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"gaf_master.h\"\n#include \"readjsonsource.h\"\n\n#if GAF_TEST_JSON\n#include \"gaf_rapidjson_master.h\"\n#endif\n\nusing Catch::Matchers::Equals;\ntemplate<typename T>\nstruct Vector : public std::vector<T>\n{\n Vector<T>& operator<<(const T& t) {this->push_back(t); return *this;}\n};\n\nTEST_CASE(\"custom vector equals works\") {\n std::vector<int> a;\n a.push_back(1);\n a.push_back(2);\n a.push_back(3);\n\n REQUIRE_THAT(a, Equals(Vector<int>() << 1 << 2 << 3));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ standard\n\nTEST_CASE(\"std constructor\") {\n Standard fb;\n REQUIRE(fb.a == 0);\n REQUIRE(fb.b == 0);\n REQUIRE(fb.c == 0);\n REQUIRE(fb.d == 0);\n REQUIRE(fb.ua == 0);\n REQUIRE(fb.ub == 0);\n REQUIRE(fb.uc == 0);\n REQUIRE(fb.ud == 0);\n REQUIRE(fb.e == 0);\n REQUIRE(fb.f == false);\n REQUIRE(fb.g == 0);\n REQUIRE(fb.h == 0);\n REQUIRE(fb.i == \"\");\n}\n\n#if GAF_TEST_JSON\n\nTEST_CASE(\"std json\") {\n Standard fb;\n const std::string load = ReadJsonSource(&fb,\n \"{\\\n \\\"a\\\": 1,\\\n \\\"b\\\": 2,\\\n \\\"c\\\": 3,\\\n \\\"d\\\": 4,\\\n \\\"ua\\\": 5,\\\n \\\"ub\\\": 6,\\\n \\\"uc\\\": 7,\\\n \\\"ud\\\": 8,\\\n \\\"e\\\": 9,\\\n \\\"f\\\": true,\\\n \\\"g\\\": 10.0,\\\n \\\"h\\\": 11.0,\\\n \\\"i\\\": \\\"dog\\\"}\"\n );\n REQUIRE(load == \"\");\n\n REQUIRE(fb.a == 1);\n REQUIRE(fb.b == 2);\n REQUIRE(fb.c == 3);\n REQUIRE(fb.d == 4);\n REQUIRE(fb.ua == 5);\n REQUIRE(fb.ub == 6);\n REQUIRE(fb.uc == 7);\n REQUIRE(fb.ud == 8);\n REQUIRE(fb.e == 9);\n REQUIRE(fb.f == true);\n REQUIRE(fb.g == 10.0);\n REQUIRE(fb.h == 11.0);\n REQUIRE(fb.i == \"dog\");\n}\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ arrays\n\nTEST_CASE(\"array constructor\") {\n Arrays fb;\n REQUIRE(fb.a.size() == 0);\n REQUIRE(fb.b.size() == 0);\n REQUIRE(fb.c.size() == 0);\n REQUIRE(fb.d.size() == 0);\n REQUIRE(fb.ua.size() == 0);\n REQUIRE(fb.ub.size() == 0);\n REQUIRE(fb.uc.size() == 0);\n REQUIRE(fb.ud.size() == 0);\n REQUIRE(fb.e.size() == 0);\n REQUIRE(fb.f.size() == 0);\n REQUIRE(fb.g.size() == 0);\n REQUIRE(fb.h.size() == 0);\n REQUIRE(fb.i.size() == 0);\n REQUIRE(fb.standard.size() == 0);\n}\n\n#if GAF_TEST_JSON\n\nTEST_CASE(\"array empty json\") {\n Arrays advanced;\n\n const std::string load = ReadJsonSource(&advanced, \"{}\");\n REQUIRE(load != \"\");\n}\n\nTEST_CASE(\"array basic json\") {\n Arrays fb;\n const std::string load = ReadJsonSource(&fb,\n \"{\\\n \\\"a\\\": [],\\\n \\\"b\\\": [],\\\n \\\"c\\\": [],\\\n \\\"d\\\": [],\\\n \\\"ua\\\": [],\\\n \\\"ub\\\": [],\\\n \\\"uc\\\": [],\\\n \\\"ud\\\": [],\\\n \\\"e\\\": [],\\\n \\\"f\\\": [],\\\n \\\"g\\\": [],\\\n \\\"h\\\": [],\\\n \\\"i\\\": [],\\\n \\\"standard\\\": []}\"\n );\n REQUIRE(load == \"\");\n\n REQUIRE(fb.a.size() == 0);\n REQUIRE(fb.b.size() == 0);\n REQUIRE(fb.c.size() == 0);\n REQUIRE(fb.d.size() == 0);\n REQUIRE(fb.ua.size() == 0);\n REQUIRE(fb.ub.size() == 0);\n REQUIRE(fb.uc.size() == 0);\n REQUIRE(fb.ud.size() == 0);\n REQUIRE(fb.e.size() == 0);\n REQUIRE(fb.f.size() == 0);\n REQUIRE(fb.g.size() == 0);\n REQUIRE(fb.h.size() == 0);\n REQUIRE(fb.i.size() == 0);\n REQUIRE(fb.standard.size() == 0);\n}\n\n\/\/ todo: parse standard too\nTEST_CASE(\"arrays advanced json\") {\n Arrays fb;\n const std::string load = ReadJsonSource(&fb,\n \"{\\\n \\\"a\\\": [1, 2],\\\n \\\"b\\\": [3, 4],\\\n \\\"c\\\": [5, 6],\\\n \\\"d\\\": [7, 8],\\\n \\\"ua\\\": [9, 10],\\\n \\\"ub\\\": [11, 12],\\\n \\\"uc\\\": [13, 14],\\\n \\\"ud\\\": [15, 16],\\\n \\\"e\\\": [17, 18],\\\n \\\"f\\\": [false, true],\\\n \\\"g\\\": [19, 20],\\\n \\\"h\\\": [21, 22],\\\n \\\"i\\\": [\\\"cat\\\", \\\"dog\\\"],\\\n \\\"standard\\\": []}\"\n );\n REQUIRE(load == \"\");\n\n REQUIRE_THAT(fb.a, Equals(Vector<std::int8_t>() << 1 << 2));\n REQUIRE_THAT(fb.b, Equals(Vector<std::int16_t>() << 3 << 4));\n REQUIRE_THAT(fb.c, Equals(Vector<std::int32_t>() << 5 << 6));\n REQUIRE_THAT(fb.d, Equals(Vector<std::int64_t>() << 7 << 8));\n\n REQUIRE_THAT(fb.ua, Equals(Vector<std::uint8_t>() << 9 << 10));\n REQUIRE_THAT(fb.ub, Equals(Vector<std::uint16_t>() << 11 << 12));\n REQUIRE_THAT(fb.uc, Equals(Vector<std::uint32_t>() << 13 << 14));\n REQUIRE_THAT(fb.ud, Equals(Vector<std::uint64_t>() << 15 << 16));\n\n REQUIRE_THAT(fb.e, Equals(Vector<char>() << 17 << 18));\n REQUIRE_THAT(fb.f, Equals(Vector<bool>() << false << true));\n REQUIRE_THAT(fb.g, Equals(Vector<float>() << 19 << 20));\n REQUIRE_THAT(fb.h, Equals(Vector<double>() << 21 << 22));\n\n REQUIRE_THAT(fb.i, Equals(Vector<std::string>() << \"cat\" << \"dog\"));\n}\n\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ optional\n\nTEST_CASE(\"pointer constructor\") {\n Foo foo;\n REQUIRE(foo.value == nullptr);\n\n FooRoot bar;\n REQUIRE(bar.name == nullptr);\n REQUIRE(bar.foo == nullptr);\n}\n\nTEST_CASE(\"optional constructor\") {\n Bar foo;\n REQUIRE(foo.value == 0);\n\n BarRoot bar;\n REQUIRE(bar.name == \"\");\n REQUIRE(bar.foo.value == 0);\n}\n\n#if GAF_TEST_JSON\n\nTEST_CASE(\"pointer json_basic\") {\n Foo foo;\n const std::string load = ReadJsonSource(&foo, \" {\\\"value\\\": 12} \");\n REQUIRE(load == \"\");\n REQUIRE(foo.value != nullptr);\n REQUIRE(*foo.value == 12);\n}\n\nTEST_CASE(\"optional json_basic\") {\n Bar foo;\n const std::string load = ReadJsonSource(&foo, \" {\\\"value\\\": 12} \");\n REQUIRE(load == \"\");\n REQUIRE(foo.value == 12);\n}\n\nTEST_CASE(\"pointer json_missing_foo\") {\n FooRoot bar;\n const std::string load = ReadJsonSource(&bar, \" {\\\"name\\\": \\\"good dog\\\"} \");\n REQUIRE(load == \"\");\n REQUIRE(bar.name != nullptr);\n REQUIRE(*bar.name == \"good dog\");\n REQUIRE(bar.foo == nullptr);\n}\n\nTEST_CASE(\"optional json_missing_foo\") {\n BarRoot bar;\n const std::string load = ReadJsonSource(&bar, \" {\\\"name\\\": \\\"good dog\\\"} \");\n REQUIRE(load == \"\");\n REQUIRE(bar.name == \"good dog\");\n REQUIRE(bar.foo.value == 0);\n}\n\nTEST_CASE(\"pointer json_invalid_value_for_name\") {\n \/\/ optional means optional, not accept if invalid\n FooRoot bar;\n const std::string load = ReadJsonSource(&bar, \" {\\\"name\\\": 3} \");\n REQUIRE(load != \"\");\n}\n\nTEST_CASE(\"optional json_invalid_value_for_name\") {\n \/\/ optional means optional, not accept if invalid\n BarRoot bar;\n const std::string load = ReadJsonSource(&bar, \" {\\\"name\\\": 3} \");\n REQUIRE(load != \"\");\n}\n\n\nTEST_CASE(\"pointer json_empty_document\") {\n FooRoot bar;\n const std::string load = ReadJsonSource(&bar, \"{}\");\n REQUIRE(load == \"\");\n REQUIRE(bar.name == nullptr);\n REQUIRE(bar.foo == nullptr);\n}\n\nTEST_CASE(\"optional json_empty_document\") {\n BarRoot bar;\n const std::string load = ReadJsonSource(&bar, \"{}\");\n REQUIRE(load == \"\");\n REQUIRE(bar.name == \"\");\n REQUIRE(bar.foo.value == 0);\n}\n\n\nTEST_CASE(\"pointer json_optional_struct\") {\n FooRoot bar;\n const std::string load = ReadJsonSource(&bar, \"{\\\"foo\\\": {\\\"value\\\": 5}}\");\n REQUIRE(load == \"\");\n CHECK(bar.name == nullptr);\n CHECK(bar.foo != nullptr);\n CHECK(bar.foo->value != nullptr);\n CHECK(*bar.foo->value == 5);\n}\n\nTEST_CASE(\"optional json_optional_struct\") {\n BarRoot bar;\n const std::string load = ReadJsonSource(&bar, \"{\\\"foo\\\": {\\\"value\\\": 5}}\");\n REQUIRE(load == \"\");\n CHECK(bar.name == \"\");\n CHECK(bar.foo.value == 5);\n}\n\n#endif\n\n<commit_msg>fix: double\/float warning<commit_after>#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"gaf_master.h\"\n#include \"readjsonsource.h\"\n\n#if GAF_TEST_JSON\n#include \"gaf_rapidjson_master.h\"\n#endif\n\nusing Catch::Matchers::Equals;\ntemplate<typename T>\nstruct Vector : public std::vector<T>\n{\n Vector<T>& operator<<(const T& t) {this->push_back(t); return *this;}\n};\n\nTEST_CASE(\"custom vector equals works\") {\n std::vector<int> a;\n a.push_back(1);\n a.push_back(2);\n a.push_back(3);\n\n REQUIRE_THAT(a, Equals(Vector<int>() << 1 << 2 << 3));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ standard\n\nTEST_CASE(\"std constructor\") {\n Standard fb;\n REQUIRE(fb.a == 0);\n REQUIRE(fb.b == 0);\n REQUIRE(fb.c == 0);\n REQUIRE(fb.d == 0);\n REQUIRE(fb.ua == 0);\n REQUIRE(fb.ub == 0);\n REQUIRE(fb.uc == 0);\n REQUIRE(fb.ud == 0);\n REQUIRE(fb.e == 0);\n REQUIRE(fb.f == false);\n REQUIRE(fb.g == 0);\n REQUIRE(fb.h == 0);\n REQUIRE(fb.i == \"\");\n}\n\n#if GAF_TEST_JSON\n\nTEST_CASE(\"std json\") {\n Standard fb;\n const std::string load = ReadJsonSource(&fb,\n \"{\\\n \\\"a\\\": 1,\\\n \\\"b\\\": 2,\\\n \\\"c\\\": 3,\\\n \\\"d\\\": 4,\\\n \\\"ua\\\": 5,\\\n \\\"ub\\\": 6,\\\n \\\"uc\\\": 7,\\\n \\\"ud\\\": 8,\\\n \\\"e\\\": 9,\\\n \\\"f\\\": true,\\\n \\\"g\\\": 10.0,\\\n \\\"h\\\": 11.0,\\\n \\\"i\\\": \\\"dog\\\"}\"\n );\n REQUIRE(load == \"\");\n\n REQUIRE(fb.a == 1);\n REQUIRE(fb.b == 2);\n REQUIRE(fb.c == 3);\n REQUIRE(fb.d == 4);\n REQUIRE(fb.ua == 5);\n REQUIRE(fb.ub == 6);\n REQUIRE(fb.uc == 7);\n REQUIRE(fb.ud == 8);\n REQUIRE(fb.e == 9);\n REQUIRE(fb.f == true);\n REQUIRE(fb.g == 10.0f);\n REQUIRE(fb.h == 11.0);\n REQUIRE(fb.i == \"dog\");\n}\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ arrays\n\nTEST_CASE(\"array constructor\") {\n Arrays fb;\n REQUIRE(fb.a.size() == 0);\n REQUIRE(fb.b.size() == 0);\n REQUIRE(fb.c.size() == 0);\n REQUIRE(fb.d.size() == 0);\n REQUIRE(fb.ua.size() == 0);\n REQUIRE(fb.ub.size() == 0);\n REQUIRE(fb.uc.size() == 0);\n REQUIRE(fb.ud.size() == 0);\n REQUIRE(fb.e.size() == 0);\n REQUIRE(fb.f.size() == 0);\n REQUIRE(fb.g.size() == 0);\n REQUIRE(fb.h.size() == 0);\n REQUIRE(fb.i.size() == 0);\n REQUIRE(fb.standard.size() == 0);\n}\n\n#if GAF_TEST_JSON\n\nTEST_CASE(\"array empty json\") {\n Arrays advanced;\n\n const std::string load = ReadJsonSource(&advanced, \"{}\");\n REQUIRE(load != \"\");\n}\n\nTEST_CASE(\"array basic json\") {\n Arrays fb;\n const std::string load = ReadJsonSource(&fb,\n \"{\\\n \\\"a\\\": [],\\\n \\\"b\\\": [],\\\n \\\"c\\\": [],\\\n \\\"d\\\": [],\\\n \\\"ua\\\": [],\\\n \\\"ub\\\": [],\\\n \\\"uc\\\": [],\\\n \\\"ud\\\": [],\\\n \\\"e\\\": [],\\\n \\\"f\\\": [],\\\n \\\"g\\\": [],\\\n \\\"h\\\": [],\\\n \\\"i\\\": [],\\\n \\\"standard\\\": []}\"\n );\n REQUIRE(load == \"\");\n\n REQUIRE(fb.a.size() == 0);\n REQUIRE(fb.b.size() == 0);\n REQUIRE(fb.c.size() == 0);\n REQUIRE(fb.d.size() == 0);\n REQUIRE(fb.ua.size() == 0);\n REQUIRE(fb.ub.size() == 0);\n REQUIRE(fb.uc.size() == 0);\n REQUIRE(fb.ud.size() == 0);\n REQUIRE(fb.e.size() == 0);\n REQUIRE(fb.f.size() == 0);\n REQUIRE(fb.g.size() == 0);\n REQUIRE(fb.h.size() == 0);\n REQUIRE(fb.i.size() == 0);\n REQUIRE(fb.standard.size() == 0);\n}\n\n\/\/ todo: parse standard too\nTEST_CASE(\"arrays advanced json\") {\n Arrays fb;\n const std::string load = ReadJsonSource(&fb,\n \"{\\\n \\\"a\\\": [1, 2],\\\n \\\"b\\\": [3, 4],\\\n \\\"c\\\": [5, 6],\\\n \\\"d\\\": [7, 8],\\\n \\\"ua\\\": [9, 10],\\\n \\\"ub\\\": [11, 12],\\\n \\\"uc\\\": [13, 14],\\\n \\\"ud\\\": [15, 16],\\\n \\\"e\\\": [17, 18],\\\n \\\"f\\\": [false, true],\\\n \\\"g\\\": [19, 20],\\\n \\\"h\\\": [21, 22],\\\n \\\"i\\\": [\\\"cat\\\", \\\"dog\\\"],\\\n \\\"standard\\\": []}\"\n );\n REQUIRE(load == \"\");\n\n REQUIRE_THAT(fb.a, Equals(Vector<std::int8_t>() << 1 << 2));\n REQUIRE_THAT(fb.b, Equals(Vector<std::int16_t>() << 3 << 4));\n REQUIRE_THAT(fb.c, Equals(Vector<std::int32_t>() << 5 << 6));\n REQUIRE_THAT(fb.d, Equals(Vector<std::int64_t>() << 7 << 8));\n\n REQUIRE_THAT(fb.ua, Equals(Vector<std::uint8_t>() << 9 << 10));\n REQUIRE_THAT(fb.ub, Equals(Vector<std::uint16_t>() << 11 << 12));\n REQUIRE_THAT(fb.uc, Equals(Vector<std::uint32_t>() << 13 << 14));\n REQUIRE_THAT(fb.ud, Equals(Vector<std::uint64_t>() << 15 << 16));\n\n REQUIRE_THAT(fb.e, Equals(Vector<char>() << 17 << 18));\n REQUIRE_THAT(fb.f, Equals(Vector<bool>() << false << true));\n REQUIRE_THAT(fb.g, Equals(Vector<float>() << 19 << 20));\n REQUIRE_THAT(fb.h, Equals(Vector<double>() << 21 << 22));\n\n REQUIRE_THAT(fb.i, Equals(Vector<std::string>() << \"cat\" << \"dog\"));\n}\n\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ optional\n\nTEST_CASE(\"pointer constructor\") {\n Foo foo;\n REQUIRE(foo.value == nullptr);\n\n FooRoot bar;\n REQUIRE(bar.name == nullptr);\n REQUIRE(bar.foo == nullptr);\n}\n\nTEST_CASE(\"optional constructor\") {\n Bar foo;\n REQUIRE(foo.value == 0);\n\n BarRoot bar;\n REQUIRE(bar.name == \"\");\n REQUIRE(bar.foo.value == 0);\n}\n\n#if GAF_TEST_JSON\n\nTEST_CASE(\"pointer json_basic\") {\n Foo foo;\n const std::string load = ReadJsonSource(&foo, \" {\\\"value\\\": 12} \");\n REQUIRE(load == \"\");\n REQUIRE(foo.value != nullptr);\n REQUIRE(*foo.value == 12);\n}\n\nTEST_CASE(\"optional json_basic\") {\n Bar foo;\n const std::string load = ReadJsonSource(&foo, \" {\\\"value\\\": 12} \");\n REQUIRE(load == \"\");\n REQUIRE(foo.value == 12);\n}\n\nTEST_CASE(\"pointer json_missing_foo\") {\n FooRoot bar;\n const std::string load = ReadJsonSource(&bar, \" {\\\"name\\\": \\\"good dog\\\"} \");\n REQUIRE(load == \"\");\n REQUIRE(bar.name != nullptr);\n REQUIRE(*bar.name == \"good dog\");\n REQUIRE(bar.foo == nullptr);\n}\n\nTEST_CASE(\"optional json_missing_foo\") {\n BarRoot bar;\n const std::string load = ReadJsonSource(&bar, \" {\\\"name\\\": \\\"good dog\\\"} \");\n REQUIRE(load == \"\");\n REQUIRE(bar.name == \"good dog\");\n REQUIRE(bar.foo.value == 0);\n}\n\nTEST_CASE(\"pointer json_invalid_value_for_name\") {\n \/\/ optional means optional, not accept if invalid\n FooRoot bar;\n const std::string load = ReadJsonSource(&bar, \" {\\\"name\\\": 3} \");\n REQUIRE(load != \"\");\n}\n\nTEST_CASE(\"optional json_invalid_value_for_name\") {\n \/\/ optional means optional, not accept if invalid\n BarRoot bar;\n const std::string load = ReadJsonSource(&bar, \" {\\\"name\\\": 3} \");\n REQUIRE(load != \"\");\n}\n\n\nTEST_CASE(\"pointer json_empty_document\") {\n FooRoot bar;\n const std::string load = ReadJsonSource(&bar, \"{}\");\n REQUIRE(load == \"\");\n REQUIRE(bar.name == nullptr);\n REQUIRE(bar.foo == nullptr);\n}\n\nTEST_CASE(\"optional json_empty_document\") {\n BarRoot bar;\n const std::string load = ReadJsonSource(&bar, \"{}\");\n REQUIRE(load == \"\");\n REQUIRE(bar.name == \"\");\n REQUIRE(bar.foo.value == 0);\n}\n\n\nTEST_CASE(\"pointer json_optional_struct\") {\n FooRoot bar;\n const std::string load = ReadJsonSource(&bar, \"{\\\"foo\\\": {\\\"value\\\": 5}}\");\n REQUIRE(load == \"\");\n CHECK(bar.name == nullptr);\n CHECK(bar.foo != nullptr);\n CHECK(bar.foo->value != nullptr);\n CHECK(*bar.foo->value == 5);\n}\n\nTEST_CASE(\"optional json_optional_struct\") {\n BarRoot bar;\n const std::string load = ReadJsonSource(&bar, \"{\\\"foo\\\": {\\\"value\\\": 5}}\");\n REQUIRE(load == \"\");\n CHECK(bar.name == \"\");\n CHECK(bar.foo.value == 5);\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include <rmc++.h>\n\nvoid lol(int n);\n\nvoid nus(rmc::atomic<int*> &a, int *p) {\n \/\/ A -> B -*-> B, needs dmb\n XEDGE_HERE(a, b);\n int *q = L(a, a);\n while (1) {\n int n = L(b, *q);\n q = p;\n lol(n);\n }\n}\n\n\/\/ this one *shouldn't* require a dmb!!\nvoid nus2(rmc::atomic<int*> &a) {\n \/\/ A -> B -*-> B, shouldn't need dmb\n XEDGE_HERE(a, b);\n int *q = L(a, a);\n while (1) {\n int n = L(b, *q);\n lol(n);\n }\n}\n\nvoid nus3(rmc::atomic<int*> &a, int *p, int i) {\n \/\/ A -> C -*-> C -> B, needs dmb\n XEDGE_HERE(a, b);\n int *q = L(a, a);\n\n int *r;\n \/\/ r = q if we go through this loop exactly once\n \/\/ if the loop condition repeats then r = p\n do {\n r = q;\n q = p;\n } while (--i);\n\n int n = L(b, *r);\n lol(n);\n}\n\n\nvoid nus4(rmc::atomic<int*> &a, int *p, int i) {\n \/\/ We wish we could only insert a dmb along the branch,\n \/\/ but can't right now. Oh well.\n XEDGE_HERE(a, b);\n int *q = L(a, a);\n\n if (i) {\n q = p;\n }\n\n int n = L(b, *q);\n lol(n);\n}\n<commit_msg>Add another mildly tricky test<commit_after>#include <rmc++.h>\n\nvoid lol(int n);\n\nvoid nus(rmc::atomic<int*> &a, int *p) {\n \/\/ A -> B -*-> B, needs dmb\n XEDGE_HERE(a, b);\n int *q = L(a, a);\n while (1) {\n int n = L(b, *q);\n q = p;\n lol(n);\n }\n}\n\n\/\/ this one *shouldn't* require a dmb!!\nvoid nus2(rmc::atomic<int*> &a) {\n \/\/ A -> B -*-> B, shouldn't need dmb\n XEDGE_HERE(a, b);\n int *q = L(a, a);\n while (1) {\n int n = L(b, *q);\n lol(n);\n }\n}\n\nvoid nus3(rmc::atomic<int*> &a, int *p, int i) {\n \/\/ A -> C -*-> C -> B, needs dmb\n XEDGE_HERE(a, b);\n int *q = L(a, a);\n\n int *r;\n \/\/ r = q if we go through this loop exactly once\n \/\/ if the loop condition repeats then r = p\n do {\n r = q;\n q = p;\n } while (--i);\n\n int n = L(b, *r);\n lol(n);\n}\n\n\nvoid nus4(rmc::atomic<int*> &a, int *p, int i) {\n \/\/ We wish we could only insert a dmb along the branch,\n \/\/ but can't right now. Oh well.\n XEDGE_HERE(a, b);\n int *q = L(a, a);\n\n if (i) {\n q = p;\n }\n\n int n = L(b, *q);\n lol(n);\n}\n\nvoid nus5(rmc::atomic<int*> &a, int *p) {\n \/\/ Should only need the one dmb.\n XEDGE(a, b);\n int *q = L(a, a);\n int n = L(b, *q);\n VEDGE(c, d); LS(c, lol(n)); LS(d, lol(n));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n \\file time_time.cpp\n \\brief Time example\n \\author Ivan Shynkarenka\n \\date 13.07.2016\n \\copyright MIT License\n*\/\n\n#include \"time\/time.h\"\n\n#include <iostream>\n\nvoid show(const CppCommon::Time& time)\n{\n std::cout << \"Time.year() = \" << time.year() << std::endl;\n std::cout << \"Time.month() = \" << time.month() << std::endl;\n std::cout << \"Time.day() = \" << time.day() << std::endl;\n std::cout << \"Time.hour() = \" << time.hour() << std::endl;\n std::cout << \"Time.minute() = \" << time.minute() << std::endl;\n std::cout << \"Time.second() = \" << time.second() << std::endl;\n std::cout << \"Time.millisecond() = \" << time.millisecond() << std::endl;\n std::cout << \"Time.microsecond() = \" << time.microsecond() << std::endl;\n std::cout << \"Time.nanosecond() = \" << time.nanosecond() << std::endl;\n std::cout << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n std::cout << \"UTC time:\" << std::endl;\n show(CppCommon::UtcTime());\n\n std::cout << \"Local time:\" << std::endl;\n show(CppCommon::LocalTime());\n\n return 0;\n}\n<commit_msg>update<commit_after>\/*!\n \\file time_time.cpp\n \\brief Time example\n \\author Ivan Shynkarenka\n \\date 13.07.2016\n \\copyright MIT License\n*\/\n\n#include \"time\/time.h\"\n\n#include <iostream>\n\nvoid show(const CppCommon::Time& time)\n{\n std::cout << \"Time.year() = \" << time.year() << std::endl;\n std::cout << \"Time.month() = \" << time.month() << std::endl;\n std::cout << \"Time.day() = \" << time.day() << std::endl;\n std::cout << \"Time.hour() = \" << time.hour() << std::endl;\n std::cout << \"Time.minute() = \" << time.minute() << std::endl;\n std::cout << \"Time.second() = \" << time.second() << std::endl;\n std::cout << \"Time.millisecond() = \" << time.millisecond() << std::endl;\n std::cout << \"Time.microsecond() = \" << time.microsecond() << std::endl;\n std::cout << \"Time.nanosecond() = \" << time.nanosecond() << std::endl;\n std::cout << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n std::cout << \"UTC time:\" << std::endl;\n show(CppCommon::UtcTime());\n\n std::cout << \"Local time:\" << std::endl;\n show(CppCommon::LocalTime());\n\n std::cout << \"Min time:\" << std::endl;\n show(CppCommon::UtcTime(CppCommon::Timestamp(0)));\n\n std::cout << \"Max time:\" << std::endl;\n show(CppCommon::UtcTime(CppCommon::Timestamp(0xFFFFFFFFFFFFFFFF)));\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkOpenDicomEditorAction.h\"\n\n#include <QFileDialog>\n#include <QFileInfo>\n\n#include \"mitkCoreObjectFactory.h\"\n#include \"mitkSceneIO.h\"\n#include \"mitkProgressBar.h\"\n\n#include <mitkDataStorageEditorInput.h>\n#include <berryIEditorPart.h>\n#include <berryIWorkbenchPage.h>\n#include <berryIPreferencesService.h>\n#include <berryIWorkbench.h>\n#include <berryPlatform.h>\n#include <berryFileEditorInput.h>\n\n#include \"mitkProperties.h\"\n#include \"mitkNodePredicateData.h\"\n#include \"mitkNodePredicateNot.h\"\n#include \"mitkNodePredicateProperty.h\"\n\n\n\/\/#include <QmitkStdMultiWidgetEditor.h>\n\nQmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(berry::IWorkbenchWindow::Pointer window)\n: QAction(0)\n{\n this->init(window);\n}\n\nQmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window)\n: QAction(0)\n{\n this->setIcon(icon);\n\n this->init(window);\n}\n\nvoid QmitkOpenDicomEditorAction::init(berry::IWorkbenchWindow::Pointer window)\n{\n m_Window = window;\n this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl()));\n this->setText(\"&DICOM\");\n this->setToolTip(\"Open dicom tool\");\n\n berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService();\n\n m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node(\"\/General\");\n\n this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run()));\n}\n\nvoid QmitkOpenDicomEditorAction::Run()\n{\n\n \/\/ check if there is an open perspective, if not open the default perspective\n if (m_Window->GetActivePage().IsNull())\n {\n QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective();\n m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window);\n }\n\n \/\/mitk::DataStorageEditorInput::Pointer editorInput;\n \/\/mitk::DataStorage::Pointer dataStorage;\n \/\/QmitkStdMultiWidgetEditor::Pointer multiWidgetEditor;\n \/\/berry::IEditorPart::Pointer editor = m_Window->GetActivePage()->GetActiveEditor();\n\n\n\n \/\/if (editor.Cast<QmitkStdMultiWidgetEditor>().IsNull())\n \/\/{\n \/\/ editorInput = new mitk::DataStorageEditorInput();\n \/\/ dataStorage = editorInput->GetDataStorageReference()->GetDataStorage();\n \/\/}\n \/\/else\n \/\/{\n \/\/ multiWidgetEditor = editor.Cast<QmitkStdMultiWidgetEditor>();\n \/\/ dataStorage = multiWidgetEditor->GetEditorInput().Cast<mitk::DataStorageEditorInput>()->GetDataStorageReference()->GetDataStorage();\n \/\/}\n\n \/\/if (multiWidgetEditor.IsNull())\n \/\/{\n \/\/ \/\/berry::IEditorPart::Pointer editor = m_Window->GetActivePage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID);\n \/\/ multiWidgetEditor = editor.Cast<QmitkStdMultiWidgetEditor>();\n \/\/}\n \/\/else\n \/\/{\n \/\/ multiWidgetEditor->GetStdMultiWidget()->RequestUpdate();\n \/\/}\n\n berry::IEditorInput::Pointer editorInput2(new berry::FileEditorInput(QString()));\n m_Window->GetActivePage()->OpenEditor(editorInput2, \"org.mitk.editors.dicomeditor\");\n}\n\n<commit_msg>Remove (commented) references to multi widget from org.mitk.gui.qt.ext and extapplication<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkOpenDicomEditorAction.h\"\n\n#include <QFileDialog>\n#include <QFileInfo>\n\n#include \"mitkCoreObjectFactory.h\"\n#include \"mitkSceneIO.h\"\n#include \"mitkProgressBar.h\"\n\n#include <mitkDataStorageEditorInput.h>\n#include <berryIEditorPart.h>\n#include <berryIWorkbenchPage.h>\n#include <berryIPreferencesService.h>\n#include <berryIWorkbench.h>\n#include <berryPlatform.h>\n#include <berryFileEditorInput.h>\n\n#include \"mitkProperties.h\"\n#include \"mitkNodePredicateData.h\"\n#include \"mitkNodePredicateNot.h\"\n#include \"mitkNodePredicateProperty.h\"\n\n\nQmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(berry::IWorkbenchWindow::Pointer window)\n: QAction(0)\n{\n this->init(window);\n}\n\nQmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window)\n: QAction(0)\n{\n this->setIcon(icon);\n\n this->init(window);\n}\n\nvoid QmitkOpenDicomEditorAction::init(berry::IWorkbenchWindow::Pointer window)\n{\n m_Window = window;\n this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl()));\n this->setText(\"&DICOM\");\n this->setToolTip(\"Open dicom tool\");\n\n berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService();\n\n m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node(\"\/General\");\n\n this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run()));\n}\n\nvoid QmitkOpenDicomEditorAction::Run()\n{\n\n \/\/ check if there is an open perspective, if not open the default perspective\n if (m_Window->GetActivePage().IsNull())\n {\n QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective();\n m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window);\n }\n\n berry::IEditorInput::Pointer editorInput2(new berry::FileEditorInput(QString()));\n m_Window->GetActivePage()->OpenEditor(editorInput2, \"org.mitk.editors.dicomeditor\");\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <utility.h>\n#include \"mbed.h\"\n#include \"BtuLinear.h\"\n\n#define NUM_FLOATS 6\n#define TIMESTEP 0.05\n#define DEPTH_THRESHOLD 0.3\n#define MIN_MISSION_DEPTH 0.2\n#define MISSION_TIMEOUT 60.0\n#define ERROR_THRESHOLD 0.125\n#define SUCCESS_TIME 8.0\n#define DEBRIEF_TIME_LIMIT 20.0\n#define UNWOUND_POS 1.0\n\n#define DEF_V_KC 0.5\n#define DEF_V_TAUI 0\n#define DEF_V_TAUD 0\n\n#define DEF_P_KC 1\n#define DEF_P_TAUI 0\n#define DEF_P_TAUD 0\n\n#define DRY_RUN 1\n\n#define CONTROL_MODE 55\n#define MISSION_MODE 66\n\n#define FREQUENCY 20\n\n\n#include \"MODSERIAL\/MODSERIAL.h\"\n#include \"SerialComm\/SerialComm.h\"\n\nMODSERIAL pcSerial(USBTX, USBRX);\n\/\/ AnalogIn pot1(p15);\nDigitalOut TestLED(LED1);\nDigitalOut TestLED2(LED2);\nDigitalOut inMission(LED3);\nDigitalOut missionSuccess(LED4);\n\nLocalFileSystem local(\"local\");\n\n\/\/ bool clk = true;\nBtuLinear btu = BtuLinear();\nint counter = 0;\nint mode = 2;\nfloat Kc = 1.0;\nfloat TauI = 0.0;\nfloat TauD = 0.0;\nfloat floorVal; \/\/ temp value for mission parameters\nfloat jumpVal; \/\/ temp value for mission parameters\nfloat missionFloor; \/\/ Lowest depth of a mission\nfloat missionStep; \/\/ Distance between waypoints of a mission\nfloat setVal = 0.0; \/\/ meters\nTicker Control;\nTicker Mission; \/\/ Ticker for running Mission in parallel with main loop\nfloat timeout = 0.0; \/\/ time in seconds since last waypoint reached\nfloat missionTime = 0.0; \/\/ time in seconds that mission has taken\nfloat successTime = 0.0; \/\/ time in seconds spent within waypoint\nfloat missionDepth = 0.0; \/\/ current waypoint depth\nbool missionStarted = false; \/\/ boolean detailing whether or not robot has begun automatically following mission parameters\nfloat debriefTime = 0.0; \/\/ amount of time spent recording log after mission has ended\nbool debriefMode = false; \/\/ boolean indicating whether in debrief mode\nFILE *fp; \/\/ pointer for writing log\nbool returnTrip = false; \/\/ determines whether the robot is in the descending or ascending part of the mission. true = ascending\nfloat valueFloats[NUM_FLOATS];\nbool missionMode = false;\nSerialComm serialComm(&pcSerial);\n\n\n\/\/ end a mission and reset the various parameters.\nvoid terminateMission() {\n Mission.detach(); \/\/ stop running mission loop asynchronously\n fclose(fp); \/\/ close the file\n counter = 0; \/\/ resets the LED mission loop counter\n TestLED = 0; \/\/ turns off the mission loop LED\n inMission = 0; \/\/ turns off the inMission LED\n timeout = 0.0;\n successTime = 0.0;\n missionTime = 0.0;\n missionStarted = false;\n debriefMode = false;\n debriefTime = 0.0;\n returnTrip = false;\n\n btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS); \/\/ attempt to return to surface\n}\n\n\/\/ returns true if we're close enough to current waypoint\nbool checkThreshold() {\n float error = btu.getDepth() - missionDepth;\n \/\/ float error = btu.getServoPos() - missionDepth;\n float absError = (error > 0) ? error : (-1 * error);\n return (absError <= ERROR_THRESHOLD);\n}\n\n\n\/\/ Main mission loop\nvoid runMission() {\n \/\/ if in debrief mode, update timer and loop again\n\tif(debriefMode) {\n\t\tinMission = 0;\n\t\tmissionDepth = 0;\n\t\tbtu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);\n \/\/ finally tidy up and kill loop if debrief time has completed\n\t\tif(debriefTime >= DEBRIEF_TIME_LIMIT) {\n\t\t\tterminateMission();\n\t\t}\n\t\tdebriefTime += TIMESTEP;\n\t\treturn; \/\/ start over the mission loop without checking all the later conditions\n\t}\n \/\/ counter just for flicking the LED every second\n counter = (counter + 1) % 20;\n if(!counter) {\n TestLED = !TestLED;\n }\n \/\/ start the mission if we're below depth threshold. Does not reset any values. Cannot end a mission, so running it multiple times is innocuous\n if(btu.getDepth() >= DEPTH_THRESHOLD) {\n inMission = 1;\n missionStarted = true;\n btu.updateMode(DEPTH_CTRL_MODE);\n }\n \/\/ Do nothing if mission has not yet begun\n if(!missionStarted) {\n return;\n }\n \/\/ otherwise run depth controller\n btu.runCycle(missionDepth);\n\n \/\/ if we're close enough to our next waypoint, begin counting success time. Otherwise, reset success time\n if(checkThreshold()) {\n \tsuccessTime += TIMESTEP;\n } else {\n \tsuccessTime = 0.0;\n }\n\n \/\/ if we've been near the waypoint for long enough\n if (successTime >= SUCCESS_TIME) {\n \/\/ check if we're completely done. i.e. done surfacing on our return trip. If so, report success and begin debriefing\n if((missionDepth <= MIN_MISSION_DEPTH) && (returnTrip == true)) {\n missionSuccess = 1;\n debriefMode = true;\n return;\n } else if(missionDepth == missionFloor) { \/\/ otherwise, check if we reached the bottom of our mission and need to begin resurfacing\n returnTrip = true;\n successTime = 0.0;\n missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);\n timeout = 0.0;\n } else { \/\/ otherwise, just advance the mission\n \tsuccessTime = 0.0;\n \/\/ if we're on the return trip, move up instead of down\n if(returnTrip) {\n missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);\n } else {\n missionDepth = utility::clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);\n }\n timeout = 0.0;\n }\n }\n \/\/ mission failure. Taken too long to reach a waypoint. Begin resurfacing, report failure.\n if (timeout >= MISSION_TIMEOUT) {\n missionSuccess = 0;\n debriefMode = true;\n return;\n }\n \/\/ advance time\n missionTime += TIMESTEP;\n timeout += TIMESTEP;\n}\n\n\n\/\/ sets various mission parameters, being sure to detach a mission if it is already present.\nvoid startMission(float kc, float taui, float taud, float setDepth, float stepDist) {\n terminateMission();\n fp = fopen(\"\/local\/log\", \"w\");\n fprintf(fp, \"MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\\r\\n\", setDepth, stepDist);\n\n missionSuccess = 0;\n missionFloor = setDepth;\n missionDepth = utility::clip(stepDist, MIN_MISSION_DEPTH, missionFloor);\n missionStep = stepDist;\n returnTrip = false;\n btu.updateDepthTunings(kc, taui, taud);\n btu.updateVelTunings(DEF_V_KC, DEF_V_TAUI, DEF_V_TAUD);\n btu.updatePosTunings(DEF_P_KC, DEF_P_TAUI, DEF_P_TAUD);\n \/\/ btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);\n Mission.attach(&runMission, TIMESTEP);\n}\n\nvoid runControl() {\n counter = (counter + 1) % FREQUENCY;\n if(!counter) {\n\t\/\/ blink every second\n TestLED = !TestLED;\n }\n\n \/\/setVal = pot1;\n \/\/setVal = (b1-a1)*setVal+a1;\n\n\n \/\/ Update Mode and Run Cycle\n btu.updateAndRunCycle(mode, setVal);\n}\n\nvoid switchModes() {\n\tControl.detach();\n\tterminateMission();\n\tbtu.stop();\n\tmissionMode = !missionMode;\n\tif(!missionMode) {\n\t\tControl.attach(&runControl, TIMESTEP);\n\t}\n}\n\nvoid missionCycle() {\n\t\/\/ log in either mission or debrief modes\n\tif(inMission || debriefMode) {\n\t\tfloat depth = btu.getDepth();\n\t\tfprintf(fp, \"m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f, rt:%d\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), missionDepth, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, missionDepth - depth, missionTime, timeout, returnTrip);\n\t} else { \/\/ otherwise just try to surface\n\t\tbtu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);\n\t}\n\n\t\/\/ take in serial messages to start new missions\n\tif(serialComm.checkIfNewMessage()) {\n\t\tserialComm.getFloats(valueFloats, NUM_FLOATS);\n\t\tif(valueFloats[0] == CONTROL_MODE) {\n\t\t\tswitchModes();\n\t\t\treturn;\n\t\t}\n\t\t\/\/ mode = (int) valueFloats[0];\n\t\tKc = valueFloats[0];\n\t\tTauI = valueFloats[1];\n\t\tTauD = valueFloats[2];\n\t\tjumpVal = valueFloats[3];\n\t\tfloorVal = valueFloats[4];\n\t\tbtu.setDryMode(!valueFloats[5]);\n\t\tstartMission(Kc, TauI, TauD, floorVal, jumpVal);\n\t}\n}\n\n\n\n\nvoid testCycle() {\n\tfloat depth = 0;\n\tdepth = btu.getDepth();\n\tif (mode == DEPTH_CTRL_MODE) {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - depth);\n\t} else if (mode == POSITION_CTRL_MODE) {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, pos_er:%.4f %.4f\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getPkC(), btu.getPkI(), btu.getPkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - btu.getActPosition(ACT_A), setVal - btu.getActPosition(ACT_B));\n\t} else {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f\\r\\n\", btu.getMode(), Kc, TauI, TauD, setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth);\n\t}\n\n\tif(serialComm.checkIfNewMessage()) {\n\t\tserialComm.getFloats(valueFloats, NUM_FLOATS);\n\n\t\tif(valueFloats[0] == MISSION_MODE) {\n\t\t\tswitchModes();\n\t\t\treturn;\n\t\t}\n\t\tmode = (int) valueFloats[0];\n\t\tKc = valueFloats[1];\n\t\tTauI = valueFloats[2];\n\t\tTauD = valueFloats[3];\n\t\tsetVal = valueFloats[4];\n\t\tbtu.setDryMode(!valueFloats[5]);\n\n\t\t\/\/ Based on Mode, update Tunings\n\t\tif(mode == VELOCITY_CTRL_MODE) {\n\t\t\tbtu.updateVelTunings(Kc, TauI, TauD);\n\t\t} else if (mode == POSITION_CTRL_MODE){\n\t\t\tbtu.updatePosTunings(Kc, TauI, TauD);\n\t\t} else {\n\t\t\tbtu.updateDepthTunings(Kc, TauI, TauD);\n\t\t}\n\t}\n}\n\n\nint main() {\n pcSerial.printf(\"Start!\\n\");\n\n btu.init();\n pcSerial.printf(\"pressure at start: %.6f\\r\\n\", btu.getPressure());\n TestLED = 0;\n Control.attach(&runControl, TIMESTEP);\n\n while(1) {\n\t if(missionMode) {\n\t\t missionCycle();\n\t } else {\n\t\t testCycle();\n\t }\n wait_ms(1000);\n TestLED2 = !TestLED2;\n }\n}\n<commit_msg>adjust gains<commit_after>#include <utility.h>\n#include \"mbed.h\"\n#include \"BtuLinear.h\"\n\n#define NUM_FLOATS 6\n#define TIMESTEP 0.05\n#define DEPTH_THRESHOLD 0.5\n#define MIN_MISSION_DEPTH 0.5\n#define MISSION_TIMEOUT 60.0\n#define ERROR_THRESHOLD 0.125\n#define SUCCESS_TIME 8.0\n#define DEBRIEF_TIME_LIMIT 20.0\n#define UNWOUND_POS 1.0\n\n#define DEF_V_KC 0.5\n#define DEF_V_TAUI 0\n#define DEF_V_TAUD 0\n\n#define DEF_P_KC 16\n#define DEF_P_TAUI 2\n#define DEF_P_TAUD 1\n\n#define DRY_RUN 1\n\n#define CONTROL_MODE 55\n#define MISSION_MODE 66\n\n#define FREQUENCY 20\n\n\n#include \"MODSERIAL\/MODSERIAL.h\"\n#include \"SerialComm\/SerialComm.h\"\n\nMODSERIAL pcSerial(USBTX, USBRX);\n\/\/ AnalogIn pot1(p15);\nDigitalOut TestLED(LED1);\nDigitalOut TestLED2(LED2);\nDigitalOut inMission(LED3);\nDigitalOut missionSuccess(LED4);\n\nLocalFileSystem local(\"local\");\n\n\/\/ bool clk = true;\nBtuLinear btu = BtuLinear();\nint counter = 0;\nint mode = 2;\nfloat Kc = 1.0;\nfloat TauI = 0.0;\nfloat TauD = 0.0;\nfloat floorVal; \/\/ temp value for mission parameters\nfloat jumpVal; \/\/ temp value for mission parameters\nfloat missionFloor; \/\/ Lowest depth of a mission\nfloat missionStep; \/\/ Distance between waypoints of a mission\nfloat setVal = 0.0; \/\/ meters\nTicker Control;\nTicker Mission; \/\/ Ticker for running Mission in parallel with main loop\nfloat timeout = 0.0; \/\/ time in seconds since last waypoint reached\nfloat missionTime = 0.0; \/\/ time in seconds that mission has taken\nfloat successTime = 0.0; \/\/ time in seconds spent within waypoint\nfloat missionDepth = 0.0; \/\/ current waypoint depth\nbool missionStarted = false; \/\/ boolean detailing whether or not robot has begun automatically following mission parameters\nfloat debriefTime = 0.0; \/\/ amount of time spent recording log after mission has ended\nbool debriefMode = false; \/\/ boolean indicating whether in debrief mode\nFILE *fp; \/\/ pointer for writing log\nbool returnTrip = false; \/\/ determines whether the robot is in the descending or ascending part of the mission. true = ascending\nfloat valueFloats[NUM_FLOATS];\nbool missionMode = false;\nSerialComm serialComm(&pcSerial);\n\n\n\/\/ end a mission and reset the various parameters.\nvoid terminateMission() {\n Mission.detach(); \/\/ stop running mission loop asynchronously\n fclose(fp); \/\/ close the file\n counter = 0; \/\/ resets the LED mission loop counter\n TestLED = 0; \/\/ turns off the mission loop LED\n inMission = 0; \/\/ turns off the inMission LED\n timeout = 0.0;\n successTime = 0.0;\n missionTime = 0.0;\n missionStarted = false;\n debriefMode = false;\n debriefTime = 0.0;\n returnTrip = false;\n\n btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS); \/\/ attempt to return to surface\n}\n\n\/\/ returns true if we're close enough to current waypoint\nbool checkThreshold() {\n float error = btu.getDepth() - missionDepth;\n \/\/ float error = btu.getServoPos() - missionDepth;\n float absError = (error > 0) ? error : (-1 * error);\n return (absError <= ERROR_THRESHOLD);\n}\n\n\n\/\/ Main mission loop\nvoid runMission() {\n \/\/ if in debrief mode, update timer and loop again\n\tif(debriefMode) {\n\t\tinMission = 0;\n\t\tmissionDepth = 0;\n\t\tbtu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);\n \/\/ finally tidy up and kill loop if debrief time has completed\n\t\tif(debriefTime >= DEBRIEF_TIME_LIMIT) {\n\t\t\tterminateMission();\n\t\t}\n\t\tdebriefTime += TIMESTEP;\n\t\treturn; \/\/ start over the mission loop without checking all the later conditions\n\t}\n \/\/ counter just for flicking the LED every second\n counter = (counter + 1) % 20;\n if(!counter) {\n TestLED = !TestLED;\n }\n \/\/ start the mission if we're below depth threshold. Does not reset any values. Cannot end a mission, so running it multiple times is innocuous\n if(btu.getDepth() >= DEPTH_THRESHOLD) {\n inMission = 1;\n missionStarted = true;\n btu.updateMode(DEPTH_CTRL_MODE);\n }\n \/\/ Do nothing if mission has not yet begun\n if(!missionStarted) {\n return;\n }\n \/\/ otherwise run depth controller\n btu.runCycle(missionDepth);\n\n \/\/ if we're close enough to our next waypoint, begin counting success time. Otherwise, reset success time\n if(checkThreshold()) {\n \tsuccessTime += TIMESTEP;\n } else {\n \tsuccessTime = 0.0;\n }\n\n \/\/ if we've been near the waypoint for long enough\n if (successTime >= SUCCESS_TIME) {\n \/\/ check if we're completely done. i.e. done surfacing on our return trip. If so, report success and begin debriefing\n if((missionDepth <= MIN_MISSION_DEPTH) && (returnTrip == true)) {\n missionSuccess = 1;\n debriefMode = true;\n return;\n } else if(missionDepth == missionFloor) { \/\/ otherwise, check if we reached the bottom of our mission and need to begin resurfacing\n returnTrip = true;\n successTime = 0.0;\n missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);\n timeout = 0.0;\n } else { \/\/ otherwise, just advance the mission\n \tsuccessTime = 0.0;\n \/\/ if we're on the return trip, move up instead of down\n if(returnTrip) {\n missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);\n } else {\n missionDepth = utility::clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);\n }\n timeout = 0.0;\n }\n }\n \/\/ mission failure. Taken too long to reach a waypoint. Begin resurfacing, report failure.\n if (timeout >= MISSION_TIMEOUT) {\n missionSuccess = 0;\n debriefMode = true;\n return;\n }\n \/\/ advance time\n missionTime += TIMESTEP;\n timeout += TIMESTEP;\n}\n\n\n\/\/ sets various mission parameters, being sure to detach a mission if it is already present.\nvoid startMission(float kc, float taui, float taud, float setDepth, float stepDist) {\n terminateMission();\n fp = fopen(\"\/local\/log\", \"w\");\n fprintf(fp, \"MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\\r\\n\", setDepth, stepDist);\n\n missionSuccess = 0;\n missionFloor = setDepth;\n missionDepth = utility::clip(stepDist, MIN_MISSION_DEPTH, missionFloor);\n missionStep = stepDist;\n returnTrip = false;\n btu.updateDepthTunings(kc, taui, taud);\n btu.updateVelTunings(DEF_V_KC, DEF_V_TAUI, DEF_V_TAUD);\n btu.updatePosTunings(DEF_P_KC, DEF_P_TAUI, DEF_P_TAUD);\n \/\/ btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);\n Mission.attach(&runMission, TIMESTEP);\n}\n\nvoid runControl() {\n counter = (counter + 1) % FREQUENCY;\n if(!counter) {\n\t\/\/ blink every second\n TestLED = !TestLED;\n }\n\n \/\/setVal = pot1;\n \/\/setVal = (b1-a1)*setVal+a1;\n\n\n \/\/ Update Mode and Run Cycle\n btu.updateAndRunCycle(mode, setVal);\n}\n\nvoid switchModes() {\n\tControl.detach();\n\tterminateMission();\n\tbtu.stop();\n\tmissionMode = !missionMode;\n\tif(!missionMode) {\n\t\tControl.attach(&runControl, TIMESTEP);\n\t}\n}\n\nvoid missionCycle() {\n\t\/\/ log in either mission or debrief modes\n\tif(inMission || debriefMode) {\n\t\tfloat depth = btu.getDepth();\n\t\tfprintf(fp, \"m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f, rt:%d\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), missionDepth, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, missionDepth - depth, missionTime, timeout, returnTrip);\n\t} else { \/\/ otherwise just try to surface\n\t\tbtu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);\n\t}\n\n\t\/\/ take in serial messages to start new missions\n\tif(serialComm.checkIfNewMessage()) {\n\t\tserialComm.getFloats(valueFloats, NUM_FLOATS);\n\t\tif(valueFloats[0] == CONTROL_MODE) {\n\t\t\tswitchModes();\n\t\t\treturn;\n\t\t}\n\t\t\/\/ mode = (int) valueFloats[0];\n\t\tKc = valueFloats[0];\n\t\tTauI = valueFloats[1];\n\t\tTauD = valueFloats[2];\n\t\tjumpVal = valueFloats[3];\n\t\tfloorVal = valueFloats[4];\n\t\tbtu.setDryMode(!valueFloats[5]);\n\t\tstartMission(Kc, TauI, TauD, floorVal, jumpVal);\n\t}\n}\n\n\n\n\nvoid testCycle() {\n\tfloat depth = 0;\n\tdepth = btu.getDepth();\n\tif (mode == DEPTH_CTRL_MODE) {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - depth);\n\t} else if (mode == POSITION_CTRL_MODE) {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, pos_er:%.4f %.4f\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getPkC(), btu.getPkI(), btu.getPkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - btu.getActPosition(ACT_A), setVal - btu.getActPosition(ACT_B));\n\t} else {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f\\r\\n\", btu.getMode(), Kc, TauI, TauD, setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth);\n\t}\n\n\tif(serialComm.checkIfNewMessage()) {\n\t\tserialComm.getFloats(valueFloats, NUM_FLOATS);\n\n\t\tif(valueFloats[0] == MISSION_MODE) {\n\t\t\tswitchModes();\n\t\t\treturn;\n\t\t}\n\t\tmode = (int) valueFloats[0];\n\t\tKc = valueFloats[1];\n\t\tTauI = valueFloats[2];\n\t\tTauD = valueFloats[3];\n\t\tsetVal = valueFloats[4];\n\t\tbtu.setDryMode(!valueFloats[5]);\n\n\t\t\/\/ Based on Mode, update Tunings\n\t\tif(mode == VELOCITY_CTRL_MODE) {\n\t\t\tbtu.updateVelTunings(Kc, TauI, TauD);\n\t\t} else if (mode == POSITION_CTRL_MODE){\n\t\t\tbtu.updatePosTunings(Kc, TauI, TauD);\n\t\t} else {\n\t\t\tbtu.updateDepthTunings(Kc, TauI, TauD);\n\t\t}\n\t}\n}\n\n\nint main() {\n pcSerial.printf(\"Start!\\n\");\n\n btu.init();\n pcSerial.printf(\"pressure at start: %.6f\\r\\n\", btu.getPressure());\n TestLED = 0;\n Control.attach(&runControl, TIMESTEP);\n\n while(1) {\n\t if(missionMode) {\n\t\t missionCycle();\n\t } else {\n\t\t testCycle();\n\t }\n wait_ms(1000);\n TestLED2 = !TestLED2;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <utility.h>\n#include \"mbed.h\"\n#include \"BtuLinear.h\"\n\n#define NUM_FLOATS 6\n#define TIMESTEP 0.05\n#define DEPTH_THRESHOLD 0.3\n#define MIN_MISSION_DEPTH 0.2\n#define MISSION_TIMEOUT 60.0\n#define ERROR_THRESHOLD 0.125\n#define SUCCESS_TIME 8.0\n#define DEBRIEF_TIME_LIMIT 20.0\n#define UNWOUND_POS 1.0\n\n#define DEF_V_KC 0.5\n#define DEF_V_TAUI 0\n#define DEF_V_TAUD 0\n\n#define DEF_P_KC 1\n#define DEF_P_TAUI 0\n#define DEF_P_TAUD 0\n\n#define DRY_RUN 1\n\n#define CONTROL_MODE 55\n#define MISSION_MODE 66\n\n#define FREQUENCY 20\n\n\n#include \"MODSERIAL\/MODSERIAL.h\"\n#include \"SerialComm\/SerialComm.h\"\n\nMODSERIAL pcSerial(USBTX, USBRX);\n\/\/ AnalogIn pot1(p15);\nDigitalOut TestLED(LED1);\nDigitalOut TestLED2(LED2);\nDigitalOut inMission(LED3);\nDigitalOut missionSuccess(LED4);\n\nLocalFileSystem local(\"local\");\n\n\/\/ bool clk = true;\nBtuLinear btu = BtuLinear();\nint counter = 0;\nint mode = 2;\nfloat Kc = 1.0;\nfloat TauI = 0.0;\nfloat TauD = 0.0;\nfloat floorVal; \/\/ temp value for mission parameters\nfloat jumpVal; \/\/ temp value for mission parameters\nfloat missionFloor; \/\/ Lowest depth of a mission\nfloat missionStep; \/\/ Distance between waypoints of a mission\nfloat setVal = 0.0; \/\/ meters\nTicker Control;\nTicker Mission; \/\/ Ticker for running Mission in parallel with main loop\nfloat timeout = 0.0; \/\/ time in seconds since last waypoint reached\nfloat missionTime = 0.0; \/\/ time in seconds that mission has taken\nfloat successTime = 0.0; \/\/ time in seconds spent within waypoint\nfloat missionDepth = 0.0; \/\/ current waypoint depth\nbool missionStarted = false; \/\/ boolean detailing whether or not robot has begun automatically following mission parameters\nfloat debriefTime = 0.0; \/\/ amount of time spent recording log after mission has ended\nbool debriefMode = false; \/\/ boolean indicating whether in debrief mode\nFILE *fp; \/\/ pointer for writing log\nbool returnTrip = false; \/\/ determines whether the robot is in the descending or ascending part of the mission. true = ascending\nfloat valueFloats[NUM_FLOATS];\nbool missionMode = false;\nSerialComm serialComm(&pcSerial);\n\n\n\/\/ end a mission and reset the various parameters.\nvoid terminateMission() {\n Mission.detach(); \/\/ stop running mission loop asynchronously\n fclose(fp); \/\/ close the file\n counter = 0; \/\/ resets the LED mission loop counter\n TestLED = 0; \/\/ turns off the mission loop LED\n inMission = 0; \/\/ turns off the inMission LED\n timeout = 0.0;\n successTime = 0.0;\n missionTime = 0.0;\n missionStarted = false;\n debriefMode = false;\n debriefTime = 0.0;\n returnTrip = false;\n\n btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS); \/\/ attempt to return to surface\n}\n\n\/\/ returns true if we're close enough to current waypoint\nbool checkThreshold() {\n float error = btu.getDepth() - missionDepth;\n \/\/ float error = btu.getServoPos() - missionDepth;\n float absError = (error > 0) ? error : (-1 * error);\n return (absError <= ERROR_THRESHOLD);\n}\n\n\n\/\/ Main mission loop\nvoid runMission() {\n \/\/ if in debrief mode, update timer and loop again\n\tif(debriefMode) {\n\t\tinMission = 0;\n\t\tmissionDepth = 0;\n\t\tbtu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);\n \/\/ finally tidy up and kill loop if debrief time has completed\n\t\tif(debriefTime >= DEBRIEF_TIME_LIMIT) {\n\t\t\tterminateMission();\n\t\t}\n\t\tdebriefTime += TIMESTEP;\n\t\treturn; \/\/ start over the mission loop without checking all the later conditions\n\t}\n \/\/ counter just for flicking the LED every second\n counter = (counter + 1) % 20;\n if(!counter) {\n TestLED = !TestLED;\n }\n \/\/ start the mission if we're below depth threshold. Does not reset any values. Cannot end a mission, so running it multiple times is innocuous\n if(btu.getDepth() >= DEPTH_THRESHOLD) {\n inMission = 1;\n missionStarted = true;\n btu.updateMode(DEPTH_CTRL_MODE);\n }\n \/\/ Do nothing if mission has not yet begun\n if(!missionStarted) {\n return;\n }\n \/\/ otherwise run depth controller\n btu.runCycle(missionDepth);\n\n \/\/ if we're close enough to our next waypoint, begin counting success time. Otherwise, reset success time\n if(checkThreshold()) {\n \tsuccessTime += TIMESTEP;\n } else {\n \tsuccessTime = 0.0;\n }\n\n \/\/ if we've been near the waypoint for long enough\n if (successTime >= SUCCESS_TIME) {\n \/\/ check if we're completely done. i.e. done surfacing on our return trip. If so, report success and begin debriefing\n if((missionDepth <= MIN_MISSION_DEPTH) && (returnTrip == true)) {\n missionSuccess = 1;\n debriefMode = true;\n return;\n } else if(missionDepth == missionFloor) { \/\/ otherwise, check if we reached the bottom of our mission and need to begin resurfacing\n returnTrip = true;\n successTime = 0.0;\n missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);\n timeout = 0.0;\n } else { \/\/ otherwise, just advance the mission\n \tsuccessTime = 0.0;\n \/\/ if we're on the return trip, move up instead of down\n if(returnTrip) {\n missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);\n } else {\n missionDepth = utility::clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);\n }\n timeout = 0.0;\n }\n }\n \/\/ mission failure. Taken too long to reach a waypoint. Begin resurfacing, report failure.\n if (timeout >= MISSION_TIMEOUT) {\n missionSuccess = 0;\n debriefMode = true;\n return;\n }\n \/\/ advance time\n missionTime += TIMESTEP;\n timeout += TIMESTEP;\n}\n\n\n\/\/ sets various mission parameters, being sure to detach a mission if it is already present.\nvoid startMission(float kc, float taui, float taud, float setDepth, float stepDist) {\n terminateMission();\n fp = fopen(\"\/local\/log\", \"w\");\n fprintf(fp, \"MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\\r\\n\", setDepth, stepDist);\n\n missionSuccess = 0;\n missionFloor = setDepth;\n missionDepth = utility::clip(stepDist, MIN_MISSION_DEPTH, missionFloor);\n missionStep = stepDist;\n returnTrip = false;\n btu.updateDepthTunings(kc, taui, taud);\n btu.updateVelTunings(DEF_V_KC, DEF_V_TAUI, DEF_V_TAUD);\n btu.updatePosTunings(DEF_P_KC, DEF_P_TAUI, DEF_P_TAUD);\n \/\/ btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);\n Mission.attach(&runMission, TIMESTEP);\n}\n\nvoid runControl() {\n counter = (counter + 1) % FREQUENCY;\n if(!counter) {\n\t\/\/ blink every second\n TestLED = !TestLED;\n }\n\n \/\/setVal = pot1;\n \/\/setVal = (b1-a1)*setVal+a1;\n\n\n \/\/ Update Mode and Run Cycle\n btu.updateAndRunCycle(mode, setVal);\n}\n\nvoid switchModes() {\n\tControl.detach();\n\tterminateMission();\n\tbtu.stop();\n\tmissionMode = !missionMode;\n\tif(!missionMode) {\n\t\tControl.attach(&runControl, TIMESTEP);\n\t}\n}\n\nvoid missionCycle() {\n\t\/\/ log in either mission or debrief modes\n\tif(inMission || debriefMode) {\n\t\tfloat depth = btu.getDepth();\n\t\tfprintf(fp, \"m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f, rt:%d\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), missionDepth, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, missionDepth - depth, missionTime, timeout, returnTrip);\n\t} else { \/\/ otherwise just try to surface\n\t\tbtu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);\n\t}\n\n\t\/\/ take in serial messages to start new missions\n\tif(serialComm.checkIfNewMessage()) {\n\t\tserialComm.getFloats(valueFloats, NUM_FLOATS);\n\t\tif(valueFloats[0] == CONTROL_MODE) {\n\t\t\tswitchModes();\n\t\t\treturn;\n\t\t}\n\t\t\/\/ mode = (int) valueFloats[0];\n\t\tKc = valueFloats[0];\n\t\tTauI = valueFloats[1];\n\t\tTauD = valueFloats[2];\n\t\tjumpVal = valueFloats[3];\n\t\tfloorVal = valueFloats[4];\n\t\tbtu.setDryMode(!valueFloats[5]);\n\t\tstartMission(Kc, TauI, TauD, floorVal, jumpVal);\n\t}\n}\n\n\n\n\nvoid testCycle() {\n\tfloat depth = 0;\n\tdepth = btu.getDepth();\n\tif (mode == DEPTH_CTRL_MODE) {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - depth);\n\t} else if (mode == POSITION_CTRL_MODE) {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, pos_er:%.4f %.4f\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getPkC(), btu.getPkI(), btu.getPkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - btu.getActPosition(ACT_A), setVal - btu.getActPosition(ACT_B));\n\t} else {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f\\r\\n\", btu.getMode(), Kc, TauI, TauD, setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth);\n\t}\n\n\tif(serialComm.checkIfNewMessage()) {\n\t\tserialComm.getFloats(valueFloats, NUM_FLOATS);\n\n\t\tif(valueFloats[0] == MISSION_MODE) {\n\t\t\tswitchModes();\n\t\t\treturn;\n\t\t}\n\t\tmode = (int) valueFloats[0];\n\t\tKc = valueFloats[1];\n\t\tTauI = valueFloats[2];\n\t\tTauD = valueFloats[3];\n\t\tsetVal = valueFloats[4];\n\t\tbtu.setDryMode(!valueFloats[5]);\n\n\t\t\/\/ Based on Mode, update Tunings\n\t\tif(mode == VELOCITY_CTRL_MODE) {\n\t\t\tbtu.updateVelTunings(Kc, TauI, TauD);\n\t\t} else if (mode == POSITION_CTRL_MODE){\n\t\t\tbtu.updatePosTunings(Kc, TauI, TauD);\n\t\t} else {\n\t\t\tbtu.updateDepthTunings(Kc, TauI, TauD);\n\t\t}\n\t}\n}\n\n\nint main() {\n pcSerial.printf(\"Start!\\n\");\n\n btu.init();\n pcSerial.printf(\"pressure at start: %.6f\\r\\n\", btu.getPressure());\n TestLED = 0;\n Control.attach(&runControl, TIMESTEP);\n\n while(1) {\n\t if(missionMode) {\n\t\t missionCycle();\n\t } else {\n\t\t testCycle();\n\t }\n wait_ms(500);\n TestLED2 = !TestLED2;\n }\n}\n<commit_msg>fixed loop freezing issue<commit_after>#include <utility.h>\n#include \"mbed.h\"\n#include \"BtuLinear.h\"\n\n#define NUM_FLOATS 6\n#define TIMESTEP 0.05\n#define DEPTH_THRESHOLD 0.3\n#define MIN_MISSION_DEPTH 0.2\n#define MISSION_TIMEOUT 60.0\n#define ERROR_THRESHOLD 0.125\n#define SUCCESS_TIME 8.0\n#define DEBRIEF_TIME_LIMIT 20.0\n#define UNWOUND_POS 1.0\n\n#define DEF_V_KC 0.5\n#define DEF_V_TAUI 0\n#define DEF_V_TAUD 0\n\n#define DEF_P_KC 1\n#define DEF_P_TAUI 0\n#define DEF_P_TAUD 0\n\n#define DRY_RUN 1\n\n#define CONTROL_MODE 55\n#define MISSION_MODE 66\n\n#define FREQUENCY 20\n\n\n#include \"MODSERIAL\/MODSERIAL.h\"\n#include \"SerialComm\/SerialComm.h\"\n\nMODSERIAL pcSerial(USBTX, USBRX);\n\/\/ AnalogIn pot1(p15);\nDigitalOut TestLED(LED1);\nDigitalOut TestLED2(LED2);\nDigitalOut inMission(LED3);\nDigitalOut missionSuccess(LED4);\n\nLocalFileSystem local(\"local\");\n\n\/\/ bool clk = true;\nBtuLinear btu = BtuLinear();\nint counter = 0;\nint mode = 2;\nfloat Kc = 1.0;\nfloat TauI = 0.0;\nfloat TauD = 0.0;\nfloat floorVal; \/\/ temp value for mission parameters\nfloat jumpVal; \/\/ temp value for mission parameters\nfloat missionFloor; \/\/ Lowest depth of a mission\nfloat missionStep; \/\/ Distance between waypoints of a mission\nfloat setVal = 0.0; \/\/ meters\nTicker Control;\nTicker Mission; \/\/ Ticker for running Mission in parallel with main loop\nfloat timeout = 0.0; \/\/ time in seconds since last waypoint reached\nfloat missionTime = 0.0; \/\/ time in seconds that mission has taken\nfloat successTime = 0.0; \/\/ time in seconds spent within waypoint\nfloat missionDepth = 0.0; \/\/ current waypoint depth\nbool missionStarted = false; \/\/ boolean detailing whether or not robot has begun automatically following mission parameters\nfloat debriefTime = 0.0; \/\/ amount of time spent recording log after mission has ended\nbool debriefMode = false; \/\/ boolean indicating whether in debrief mode\nFILE *fp; \/\/ pointer for writing log\nbool returnTrip = false; \/\/ determines whether the robot is in the descending or ascending part of the mission. true = ascending\nfloat valueFloats[NUM_FLOATS];\nbool missionMode = false;\nSerialComm serialComm(&pcSerial);\n\n\n\/\/ end a mission and reset the various parameters.\nvoid terminateMission() {\n Mission.detach(); \/\/ stop running mission loop asynchronously\n fclose(fp); \/\/ close the file\n counter = 0; \/\/ resets the LED mission loop counter\n TestLED = 0; \/\/ turns off the mission loop LED\n inMission = 0; \/\/ turns off the inMission LED\n timeout = 0.0;\n successTime = 0.0;\n missionTime = 0.0;\n missionStarted = false;\n debriefMode = false;\n debriefTime = 0.0;\n returnTrip = false;\n\n btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS); \/\/ attempt to return to surface\n}\n\n\/\/ returns true if we're close enough to current waypoint\nbool checkThreshold() {\n float error = btu.getDepth() - missionDepth;\n \/\/ float error = btu.getServoPos() - missionDepth;\n float absError = (error > 0) ? error : (-1 * error);\n return (absError <= ERROR_THRESHOLD);\n}\n\n\n\/\/ Main mission loop\nvoid runMission() {\n \/\/ if in debrief mode, update timer and loop again\n\tif(debriefMode) {\n\t\tinMission = 0;\n\t\tmissionDepth = 0;\n\t\tbtu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);\n \/\/ finally tidy up and kill loop if debrief time has completed\n\t\tif(debriefTime >= DEBRIEF_TIME_LIMIT) {\n\t\t\tterminateMission();\n\t\t}\n\t\tdebriefTime += TIMESTEP;\n\t\treturn; \/\/ start over the mission loop without checking all the later conditions\n\t}\n \/\/ counter just for flicking the LED every second\n counter = (counter + 1) % 20;\n if(!counter) {\n TestLED = !TestLED;\n }\n \/\/ start the mission if we're below depth threshold. Does not reset any values. Cannot end a mission, so running it multiple times is innocuous\n if(btu.getDepth() >= DEPTH_THRESHOLD) {\n inMission = 1;\n missionStarted = true;\n btu.updateMode(DEPTH_CTRL_MODE);\n }\n \/\/ Do nothing if mission has not yet begun\n if(!missionStarted) {\n return;\n }\n \/\/ otherwise run depth controller\n btu.runCycle(missionDepth);\n\n \/\/ if we're close enough to our next waypoint, begin counting success time. Otherwise, reset success time\n if(checkThreshold()) {\n \tsuccessTime += TIMESTEP;\n } else {\n \tsuccessTime = 0.0;\n }\n\n \/\/ if we've been near the waypoint for long enough\n if (successTime >= SUCCESS_TIME) {\n \/\/ check if we're completely done. i.e. done surfacing on our return trip. If so, report success and begin debriefing\n if((missionDepth <= MIN_MISSION_DEPTH) && (returnTrip == true)) {\n missionSuccess = 1;\n debriefMode = true;\n return;\n } else if(missionDepth == missionFloor) { \/\/ otherwise, check if we reached the bottom of our mission and need to begin resurfacing\n returnTrip = true;\n successTime = 0.0;\n missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);\n timeout = 0.0;\n } else { \/\/ otherwise, just advance the mission\n \tsuccessTime = 0.0;\n \/\/ if we're on the return trip, move up instead of down\n if(returnTrip) {\n missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);\n } else {\n missionDepth = utility::clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);\n }\n timeout = 0.0;\n }\n }\n \/\/ mission failure. Taken too long to reach a waypoint. Begin resurfacing, report failure.\n if (timeout >= MISSION_TIMEOUT) {\n missionSuccess = 0;\n debriefMode = true;\n return;\n }\n \/\/ advance time\n missionTime += TIMESTEP;\n timeout += TIMESTEP;\n}\n\n\n\/\/ sets various mission parameters, being sure to detach a mission if it is already present.\nvoid startMission(float kc, float taui, float taud, float setDepth, float stepDist) {\n terminateMission();\n fp = fopen(\"\/local\/log\", \"w\");\n fprintf(fp, \"MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\\r\\n\", setDepth, stepDist);\n\n missionSuccess = 0;\n missionFloor = setDepth;\n missionDepth = utility::clip(stepDist, MIN_MISSION_DEPTH, missionFloor);\n missionStep = stepDist;\n returnTrip = false;\n btu.updateDepthTunings(kc, taui, taud);\n btu.updateVelTunings(DEF_V_KC, DEF_V_TAUI, DEF_V_TAUD);\n btu.updatePosTunings(DEF_P_KC, DEF_P_TAUI, DEF_P_TAUD);\n \/\/ btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);\n Mission.attach(&runMission, TIMESTEP);\n}\n\nvoid runControl() {\n counter = (counter + 1) % FREQUENCY;\n if(!counter) {\n\t\/\/ blink every second\n TestLED = !TestLED;\n }\n\n \/\/setVal = pot1;\n \/\/setVal = (b1-a1)*setVal+a1;\n\n\n \/\/ Update Mode and Run Cycle\n btu.updateAndRunCycle(mode, setVal);\n}\n\nvoid switchModes() {\n\tControl.detach();\n\tterminateMission();\n\tbtu.stop();\n\tmissionMode = !missionMode;\n\tif(!missionMode) {\n\t\tControl.attach(&runControl, TIMESTEP);\n\t}\n}\n\nvoid missionCycle() {\n\t\/\/ log in either mission or debrief modes\n\tif(inMission || debriefMode) {\n\t\tfloat depth = btu.getDepth();\n\t\tfprintf(fp, \"m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f, rt:%d\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), missionDepth, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, missionDepth - depth, missionTime, timeout, returnTrip);\n\t} else { \/\/ otherwise just try to surface\n\t\tbtu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);\n\t}\n\n\t\/\/ take in serial messages to start new missions\n\tif(serialComm.checkIfNewMessage()) {\n\t\tserialComm.getFloats(valueFloats, NUM_FLOATS);\n\t\tif(valueFloats[0] == CONTROL_MODE) {\n\t\t\tswitchModes();\n\t\t\treturn;\n\t\t}\n\t\t\/\/ mode = (int) valueFloats[0];\n\t\tKc = valueFloats[0];\n\t\tTauI = valueFloats[1];\n\t\tTauD = valueFloats[2];\n\t\tjumpVal = valueFloats[3];\n\t\tfloorVal = valueFloats[4];\n\t\tbtu.setDryMode(!valueFloats[5]);\n\t\tstartMission(Kc, TauI, TauD, floorVal, jumpVal);\n\t}\n}\n\n\n\n\nvoid testCycle() {\n\tfloat depth = 0;\n\tdepth = btu.getDepth();\n\tif (mode == DEPTH_CTRL_MODE) {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - depth);\n\t} else if (mode == POSITION_CTRL_MODE) {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, pos_er:%.4f %.4f\\r\\n\",\n\t\t\t\tbtu.getMode(), btu.getPkC(), btu.getPkI(), btu.getPkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - btu.getActPosition(ACT_A), setVal - btu.getActPosition(ACT_B));\n\t} else {\n\t\tpcSerial.printf(\"m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f\\r\\n\", btu.getMode(), Kc, TauI, TauD, setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth);\n\t}\n\n\tif(serialComm.checkIfNewMessage()) {\n\t\tserialComm.getFloats(valueFloats, NUM_FLOATS);\n\n\t\tif(valueFloats[0] == MISSION_MODE) {\n\t\t\tswitchModes();\n\t\t\treturn;\n\t\t}\n\t\tmode = (int) valueFloats[0];\n\t\tKc = valueFloats[1];\n\t\tTauI = valueFloats[2];\n\t\tTauD = valueFloats[3];\n\t\tsetVal = valueFloats[4];\n\t\tbtu.setDryMode(!valueFloats[5]);\n\n\t\t\/\/ Based on Mode, update Tunings\n\t\tif(mode == VELOCITY_CTRL_MODE) {\n\t\t\tbtu.updateVelTunings(Kc, TauI, TauD);\n\t\t} else if (mode == POSITION_CTRL_MODE){\n\t\t\tbtu.updatePosTunings(Kc, TauI, TauD);\n\t\t} else {\n\t\t\tbtu.updateDepthTunings(Kc, TauI, TauD);\n\t\t}\n\t}\n}\n\n\nint main() {\n pcSerial.printf(\"Start!\\n\");\n\n btu.init();\n pcSerial.printf(\"pressure at start: %.6f\\r\\n\", btu.getPressure());\n TestLED = 0;\n Control.attach(&runControl, TIMESTEP);\n\n while(1) {\n\t if(missionMode) {\n\t\t missionCycle();\n\t } else {\n\t\t testCycle();\n\t }\n wait_ms(1000);\n TestLED2 = !TestLED2;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Author: Thomas Ingleby <thomas.c.ingleby@intel.com>\n * Copyright (c) 2014 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"common.h\"\n#include \"types.hpp\"\n#include <string>\n\n\/**\n * @namespace mraa namespace\n *\/\nnamespace mraa\n{\n\n\/**\n * @file\n * @brief API to common functions of MRAA\n *\n * This file defines the interface for libmraa common functions\n *\/\n\n\/**\n * Initialise MRAA\n *\n * Detects running platform and attempts to use included pinmap, this is run on\n * module\/library init\/load but is handy to rerun to check board initialised\n * correctly. MRAA_SUCCESS inidicates correct (first time) initialisation\n * whilst MRAA_ERROR_PLATFORM_ALREADY_INITIALISED indicates the board is\n * already initialised correctly\n *\n * @return Result of operation\n *\/\ninline Result\ninit()\n{\n return (Result) mraa_init();\n}\n\n\/**\n * Get libmraa version.\n *\n * @return libmraa version (e.g. v0.4.0-20-gb408207)\n *\/\ninline std::string\ngetVersion()\n{\n std::string ret = mraa_get_version();\n return ret;\n}\n\n\/**\n * This function attempts to set the mraa process to a given priority and the\n * scheduler to SCHED_RR. Highest * priority is typically 99 and minimum is 0.\n * This function * will set to MAX if * priority is > MAX. Function will return\n * -1 on failure.\n *\n * @param priority Value from typically 0 to 99\n * @return The priority value set\n *\/\ninline int\nsetPriority(const unsigned int priority)\n{\n return mraa_set_priority(priority);\n}\n\n\/**\n * Get platform type, board must be initialised.\n *\n * @return mraa::platform Platform type enum\n *\/\ninline Platform\ngetPlatformType()\n{\n return (Platform) mraa_get_platform_type();\n}\n\n\/**\n * Print a textual representation of the mraa::Result\n *\n * @param Result the Result to print\n *\/\ninline void\nprintError(Result result)\n{\n mraa_result_print((mraa_result_t) result);\n}\n\n\/**\n * Checks if a pin is able to use the passed in mode.\n *\n * @param pin Physical Pin to be checked.\n * @param mode the mode to be tested.\n * @return boolean if the mode is supported, 0=false.\n *\/\ninline bool\npinModeTest(int pin, Pinmodes mode)\n{\n return (bool) mraa_pin_mode_test(pin, (mraa_pinmodes_t) mode);\n}\n\n\/**\n * Check the board's bit size when reading the value\n *\n * @return raw bits being read from kernel module. Zero if no ADC\n *\/\ninline unsigned int\nadcRawBits()\n{\n return mraa_adc_raw_bits();\n}\n\n\/**\n * Return value that the raw value should be shifted to. Zero if no ADC\n *\n * @return return actual bit size the adc value should be understood as.\n *\/\ninline unsigned int\nadcSupportedBits()\n{\n return mraa_adc_supported_bits();\n}\n\n\/**\n * Return Platform Name. Returns NULL if no platform inited.\n *\n * @return platform name\n *\/\ninline std::string\ngetPlatformName()\n{\n std::string ret_val(mraa_get_platform_name());\n return ret_val;\n}\n\n\/**\n * Return platform versioning info. Returns NULL if no info present.\n *\n * @param optional subplatform identifier\n * @return platform versioning info\n *\/\ninline std::string\ngetPlatformVersion(int platform_offset=MRAA_MAIN_PLATFORM_OFFSET)\n{\n std::string ret_val(mraa_get_platform_version(platform_offset));\n return ret_val;\n}\n\n\/**\n * Return count of physical pins on the running platform\n *\n * @return uint of physical pins.\n *\/\ninline unsigned int\ngetPinCount()\n{\n return mraa_get_pin_count();\n}\n\n\/**\n * Get platform usable I2C bus count, board must be initialised.\n *\n * @return number f usable I2C bus count on the current platform. Function will\n * return -1 on failure\n *\/\ninline int\ngetI2cBusCount()\n{\n return mraa_get_i2c_bus_count();\n}\n\n\/**\n * Get I2C adapter number in sysfs.\n *\n * @param i2c_bus the logical I2C bus number\n * @return I2C adapter number in sysfs. Function will return -1 on failure\n *\/\ninline int\ngetI2cBusId(unsigned int i2c_bus)\n{\n return mraa_get_i2c_bus_id(i2c_bus);\n}\n\n\/**\n* Get name of pin, board must be initialised.\n*\n* @param pin number\n*\n* @return char* of pin name\n*\/\ninline std::string\ngetPinName(int pin)\n{\n std::string ret_val(mraa_get_pin_name(pin));\n return ret_val;\n}\n\n\/**\n * Sets the log level to use from 0-7 where 7 is very verbose. These are the\n * syslog log levels, see syslog(3) for more information on the levels.\n *\n * @param level\n * @return Result of operation\n *\/\ninline Result\nsetLogLevel(int level)\n{\n return (Result) mraa_set_log_level(level);\n}\n\n\/**\n * Detect presence of sub platform.\n *\n * @return bool true if sub platform is present and initialized, false otherwise\n *\/\ninline bool\nhasSubPlatform()\n{\n return static_cast<bool>(mraa_has_sub_platform());\n}\n\n\n\n\/**\n * Check if pin or bus id includes sub platform mask.\n *\n * @param int pin or bus number\n *\n * @return mraa_boolean_t 1 if pin or bus is for sub platform, 0 otherwise\n *\/\ninline bool\nisSubPlatformId(int pin_or_bus_id)\n{\n return static_cast<bool>(mraa_is_sub_platform_id(pin_or_bus_id));\n}\n\n\/**\n * Convert pin or bus index to corresponding sub platform id.\n *\n * @param int pin or bus index\n *\n * @return int sub platform pin or bus number\n *\/\ninline int \ngetSubPlatformId(int pin_or_bus_index)\n{\n return mraa_get_sub_platform_id(pin_or_bus_index);\n}\n\n\/**\n * Convert pin or bus sub platform id to index.\n *\n * @param int sub platform pin or bus id\n *\n * @return int pin or bus index\n *\/\ninline int\ngetSubPlatformIndex(int pin_or_bus_id)\n{\n return mraa_get_sub_platform_index(pin_or_bus_id);\n}\n\n\/**\n * Get default i2c bus, board must be initialised.\n *\n * @param optional subplatform identifier\n * @return default i2c bus for paltform\n *\/\ninline int\ngetDefaultI2cBus(int platform_offset=MRAA_MAIN_PLATFORM_OFFSET)\n{\n return mraa_get_default_i2c_bus(platform_offset);\n}\n}\n<commit_msg>common.hpp: remove whitespace<commit_after>\/*\n * Author: Thomas Ingleby <thomas.c.ingleby@intel.com>\n * Copyright (c) 2014 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"common.h\"\n#include \"types.hpp\"\n#include <string>\n\n\/**\n * @namespace mraa namespace\n *\/\nnamespace mraa\n{\n\n\/**\n * @file\n * @brief API to common functions of MRAA\n *\n * This file defines the interface for libmraa common functions\n *\/\n\n\/**\n * Initialise MRAA\n *\n * Detects running platform and attempts to use included pinmap, this is run on\n * module\/library init\/load but is handy to rerun to check board initialised\n * correctly. MRAA_SUCCESS inidicates correct (first time) initialisation\n * whilst MRAA_ERROR_PLATFORM_ALREADY_INITIALISED indicates the board is\n * already initialised correctly\n *\n * @return Result of operation\n *\/\ninline Result\ninit()\n{\n return (Result) mraa_init();\n}\n\n\/**\n * Get libmraa version.\n *\n * @return libmraa version (e.g. v0.4.0-20-gb408207)\n *\/\ninline std::string\ngetVersion()\n{\n std::string ret = mraa_get_version();\n return ret;\n}\n\n\/**\n * This function attempts to set the mraa process to a given priority and the\n * scheduler to SCHED_RR. Highest * priority is typically 99 and minimum is 0.\n * This function * will set to MAX if * priority is > MAX. Function will return\n * -1 on failure.\n *\n * @param priority Value from typically 0 to 99\n * @return The priority value set\n *\/\ninline int\nsetPriority(const unsigned int priority)\n{\n return mraa_set_priority(priority);\n}\n\n\/**\n * Get platform type, board must be initialised.\n *\n * @return mraa::platform Platform type enum\n *\/\ninline Platform\ngetPlatformType()\n{\n return (Platform) mraa_get_platform_type();\n}\n\n\/**\n * Print a textual representation of the mraa::Result\n *\n * @param Result the Result to print\n *\/\ninline void\nprintError(Result result)\n{\n mraa_result_print((mraa_result_t) result);\n}\n\n\/**\n * Checks if a pin is able to use the passed in mode.\n *\n * @param pin Physical Pin to be checked.\n * @param mode the mode to be tested.\n * @return boolean if the mode is supported, 0=false.\n *\/\ninline bool\npinModeTest(int pin, Pinmodes mode)\n{\n return (bool) mraa_pin_mode_test(pin, (mraa_pinmodes_t) mode);\n}\n\n\/**\n * Check the board's bit size when reading the value\n *\n * @return raw bits being read from kernel module. Zero if no ADC\n *\/\ninline unsigned int\nadcRawBits()\n{\n return mraa_adc_raw_bits();\n}\n\n\/**\n * Return value that the raw value should be shifted to. Zero if no ADC\n *\n * @return return actual bit size the adc value should be understood as.\n *\/\ninline unsigned int\nadcSupportedBits()\n{\n return mraa_adc_supported_bits();\n}\n\n\/**\n * Return Platform Name. Returns NULL if no platform inited.\n *\n * @return platform name\n *\/\ninline std::string\ngetPlatformName()\n{\n std::string ret_val(mraa_get_platform_name());\n return ret_val;\n}\n\n\/**\n * Return platform versioning info. Returns NULL if no info present.\n *\n * @param optional subplatform identifier\n * @return platform versioning info\n *\/\ninline std::string\ngetPlatformVersion(int platform_offset=MRAA_MAIN_PLATFORM_OFFSET)\n{\n std::string ret_val(mraa_get_platform_version(platform_offset));\n return ret_val;\n}\n\n\/**\n * Return count of physical pins on the running platform\n *\n * @return uint of physical pins.\n *\/\ninline unsigned int\ngetPinCount()\n{\n return mraa_get_pin_count();\n}\n\n\/**\n * Get platform usable I2C bus count, board must be initialised.\n *\n * @return number f usable I2C bus count on the current platform. Function will\n * return -1 on failure\n *\/\ninline int\ngetI2cBusCount()\n{\n return mraa_get_i2c_bus_count();\n}\n\n\/**\n * Get I2C adapter number in sysfs.\n *\n * @param i2c_bus the logical I2C bus number\n * @return I2C adapter number in sysfs. Function will return -1 on failure\n *\/\ninline int\ngetI2cBusId(unsigned int i2c_bus)\n{\n return mraa_get_i2c_bus_id(i2c_bus);\n}\n\n\/**\n* Get name of pin, board must be initialised.\n*\n* @param pin number\n*\n* @return char* of pin name\n*\/\ninline std::string\ngetPinName(int pin)\n{\n std::string ret_val(mraa_get_pin_name(pin));\n return ret_val;\n}\n\n\/**\n * Sets the log level to use from 0-7 where 7 is very verbose. These are the\n * syslog log levels, see syslog(3) for more information on the levels.\n *\n * @param level\n * @return Result of operation\n *\/\ninline Result\nsetLogLevel(int level)\n{\n return (Result) mraa_set_log_level(level);\n}\n\n\/**\n * Detect presence of sub platform.\n *\n * @return bool true if sub platform is present and initialized, false otherwise\n *\/\ninline bool\nhasSubPlatform()\n{\n return static_cast<bool>(mraa_has_sub_platform());\n}\n\n\/**\n * Check if pin or bus id includes sub platform mask.\n *\n * @param int pin or bus number\n *\n * @return mraa_boolean_t 1 if pin or bus is for sub platform, 0 otherwise\n *\/\ninline bool\nisSubPlatformId(int pin_or_bus_id)\n{\n return static_cast<bool>(mraa_is_sub_platform_id(pin_or_bus_id));\n}\n\n\/**\n * Convert pin or bus index to corresponding sub platform id.\n *\n * @param int pin or bus index\n *\n * @return int sub platform pin or bus number\n *\/\ninline int \ngetSubPlatformId(int pin_or_bus_index)\n{\n return mraa_get_sub_platform_id(pin_or_bus_index);\n}\n\n\/**\n * Convert pin or bus sub platform id to index.\n *\n * @param int sub platform pin or bus id\n *\n * @return int pin or bus index\n *\/\ninline int\ngetSubPlatformIndex(int pin_or_bus_id)\n{\n return mraa_get_sub_platform_index(pin_or_bus_id);\n}\n\n\/**\n * Get default i2c bus, board must be initialised.\n *\n * @param optional subplatform identifier\n * @return default i2c bus for paltform\n *\/\ninline int\ngetDefaultI2cBus(int platform_offset=MRAA_MAIN_PLATFORM_OFFSET)\n{\n return mraa_get_default_i2c_bus(platform_offset);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\\Project2\\list.h\"\n#include \"..\\Project2\\list.cpp\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace NP_ADT;\n\nnamespace Project2Tests\n{\t\t\n\tTEST_CLASS(ListTests)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(TestEmptyConstructor)\n\t\t{\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\tAssert::AreEqual(unsigned int(0), test.getSize());\n\t\t\tAssert::IsTrue(nullptr == test.head());\n\t\t\tAssert::IsTrue(nullptr == test.tail());\n\t\t}\n\n\t\tTEST_METHOD(TestPushFrontConnections) \n\t\t{\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_front(5);\n\t\t\ttest.push_front(0);\n\n\t\t\tAssert::IsTrue(test.head() == test.head()->next->prev);\n\t\t\tAssert::IsTrue(test.head() == test.head()->prev->next);\n\t\t\tAssert::IsTrue(test.tail() == test.tail()->next->prev);\n\t\t\tAssert::IsTrue(test.tail() == test.tail()->prev->next);\n\t\t}\n\n\t\tTEST_METHOD(TestPushBackConnections)\n\t\t{\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_back(5);\n\t\t\ttest.push_back(0);\n\n\t\t\tAssert::IsTrue(test.head() == test.head()->next->prev);\n\t\t\tAssert::IsTrue(test.head() == test.head()->prev->next);\n\t\t\tAssert::IsTrue(test.tail() == test.tail()->next->prev);\n\t\t\tAssert::IsTrue(test.tail() == test.tail()->prev->next);\n\t\t}\n\n\t\tTEST_METHOD(TestOnePushFrontItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_front(0);\n\t\t\t\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(1), test.getSize());\n\t\t\tAssert::IsTrue(unsigned int(0) == test.tail()->data);\n\t\t\t\n\t\t\tCDLL<int>::node * ptr = test.head();\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\n\n\t\t\tAssert::IsTrue(ptr == nextPtr);\n\t\t\tAssert::IsTrue(nextPtr == doubleNextPtr);\n\t\t\tAssert::IsTrue(doubleNextPtr == prevPtr);\n\t\t\tAssert::IsTrue(prevPtr == doublePrevPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestTwoPushFrontItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_front(0);\n\t\t\ttest.push_front(1);\n\t\t\t\/\/ <-> 1 <-> 0 <->\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(2), test.getSize());\n\t\t\t\n\t\t\tAssert::IsTrue(unsigned int(1) == test.head()->data);\n\t\t\tAssert::IsTrue(unsigned int(0) == test.tail()->data);\n\t\t\t\n\t\t\t\n\t\t\tCDLL<int>::node * ptr = test.head();\t\t\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\t\/\/ == 1\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\t\/\/ == 1\n\n\t\t\tAssert::IsTrue(ptr == doubleNextPtr);\n\t\t\tAssert::IsTrue(nextPtr == prevPtr);\n\t\t\tAssert::IsTrue(doubleNextPtr == doublePrevPtr);\n\t\t\tAssert::IsTrue(ptr != nextPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestThreePushFrontItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_front(0);\n\t\t\ttest.push_front(1);\n\t\t\ttest.push_front(2);\n\t\t\t\/\/ <-> 2 <-> 1 <-> 0 <->\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(3), test.getSize());\n\n\t\t\tAssert::IsTrue(unsigned int(2) == test.head()->data);\n\t\t\tAssert::IsTrue(unsigned int(0) == test.tail()->data);\n\n\t\t\tCDLL<int>::node * ptr = test.head();\t\t\t\t\/\/ == 2\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\t\/\/ == 0\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\t\/\/ == 1\n\n\t\t\tAssert::IsTrue(ptr == doubleNextPtr->next);\n\t\t\tAssert::IsTrue(nextPtr == doublePrevPtr);\n\t\t\tAssert::IsTrue(prevPtr == doubleNextPtr);\n\t\t\tAssert::IsTrue(ptr != nextPtr);\n\t\t\tAssert::IsTrue(nextPtr != doubleNextPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestOnePushBackItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_back(0);\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(1), test.getSize());\n\t\t\tAssert::IsTrue(unsigned int(0) == test.tail()->data);\n\n\t\t\tCDLL<int>::node * ptr = test.head();\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\n\n\t\t\tAssert::IsTrue(ptr == nextPtr);\n\t\t\tAssert::IsTrue(nextPtr == doubleNextPtr);\n\t\t\tAssert::IsTrue(doubleNextPtr == prevPtr);\n\t\t\tAssert::IsTrue(prevPtr == doublePrevPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestTwoPushBackItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_back(0);\n\t\t\ttest.push_back(1);\n\t\t\t\/\/ <-> 0 <-> 1 <->\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(2), test.getSize());\n\n\t\t\tAssert::IsTrue(unsigned int(0) == test.head()->data);\n\t\t\tAssert::IsTrue(unsigned int(1) == test.tail()->data);\n\n\n\t\t\tCDLL<int>::node * ptr = test.head();\t\t\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\t\/\/ == 0\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\t\/\/ == 0\n\n\t\t\tAssert::IsTrue(ptr == doubleNextPtr);\n\t\t\tAssert::IsTrue(nextPtr == prevPtr);\n\t\t\tAssert::IsTrue(doubleNextPtr == doublePrevPtr);\n\t\t\tAssert::IsTrue(ptr != nextPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestThreePushBackItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_back(0);\n\t\t\ttest.push_back(1);\n\t\t\ttest.push_back(2);\n\t\t\t\/\/ <-> 0 <-> 1 <-> 2 <->\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(3), test.getSize());\n\n\t\t\tAssert::IsTrue(unsigned int(0) == test.head()->data);\n\t\t\tAssert::IsTrue(unsigned int(2) == test.tail()->data);\n\n\t\t\tCDLL<int>::node * ptr = test.head();\t\t\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\t\/\/ == 2\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\t\t\/\/ == 2\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\t\/\/ == 0\n\n\t\t\tAssert::IsTrue(ptr == doubleNextPtr->next);\n\t\t\tAssert::IsTrue(nextPtr == doublePrevPtr);\n\t\t\tAssert::IsTrue(prevPtr == doubleNextPtr);\n\t\t\tAssert::IsTrue(ptr != nextPtr);\n\t\t\tAssert::IsTrue(nextPtr != doubleNextPtr);\n\t\t}\n\t};\n}<commit_msg>create tests for popping<commit_after>#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\\Project2\\list.h\"\n#include \"..\\Project2\\list.cpp\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace NP_ADT;\n\nnamespace Project2Tests\n{\t\t\n\tTEST_CLASS(ListTests)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(TestEmptyConstructor)\n\t\t{\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\tAssert::AreEqual(unsigned int(0), test.getSize());\n\t\t\tAssert::IsTrue(nullptr == test.head());\n\t\t\tAssert::IsTrue(nullptr == test.tail());\n\t\t}\n\n\t\tTEST_METHOD(TestPushFrontConnections) \n\t\t{\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_front(5);\n\t\t\ttest.push_front(0);\n\n\t\t\tAssert::IsTrue(test.head() == test.head()->next->prev);\n\t\t\tAssert::IsTrue(test.head() == test.head()->prev->next);\n\t\t\tAssert::IsTrue(test.tail() == test.tail()->next->prev);\n\t\t\tAssert::IsTrue(test.tail() == test.tail()->prev->next);\n\t\t}\n\n\t\tTEST_METHOD(TestPushBackConnections)\n\t\t{\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_back(5);\n\t\t\ttest.push_back(0);\n\n\t\t\tAssert::IsTrue(test.head() == test.head()->next->prev);\n\t\t\tAssert::IsTrue(test.head() == test.head()->prev->next);\n\t\t\tAssert::IsTrue(test.tail() == test.tail()->next->prev);\n\t\t\tAssert::IsTrue(test.tail() == test.tail()->prev->next);\n\t\t}\n\n\t\tTEST_METHOD(TestOnePushFrontItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_front(0);\n\t\t\t\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(1), test.getSize());\n\t\t\tAssert::IsTrue(unsigned int(0) == test.tail()->data);\n\t\t\t\n\t\t\tCDLL<int>::node * ptr = test.head();\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\n\n\t\t\tAssert::IsTrue(ptr == nextPtr);\n\t\t\tAssert::IsTrue(nextPtr == doubleNextPtr);\n\t\t\tAssert::IsTrue(doubleNextPtr == prevPtr);\n\t\t\tAssert::IsTrue(prevPtr == doublePrevPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestTwoPushFrontItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_front(0);\n\t\t\ttest.push_front(1);\n\t\t\t\/\/ <-> 1 <-> 0 <->\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(2), test.getSize());\n\t\t\t\n\t\t\tAssert::IsTrue(unsigned int(1) == test.head()->data);\n\t\t\tAssert::IsTrue(unsigned int(0) == test.tail()->data);\n\t\t\t\n\t\t\t\n\t\t\tCDLL<int>::node * ptr = test.head();\t\t\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\t\/\/ == 1\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\t\/\/ == 1\n\n\t\t\tAssert::IsTrue(ptr == doubleNextPtr);\n\t\t\tAssert::IsTrue(nextPtr == prevPtr);\n\t\t\tAssert::IsTrue(doubleNextPtr == doublePrevPtr);\n\t\t\tAssert::IsTrue(ptr != nextPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestThreePushFrontItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_front(0);\n\t\t\ttest.push_front(1);\n\t\t\ttest.push_front(2);\n\t\t\t\/\/ <-> 2 <-> 1 <-> 0 <->\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(3), test.getSize());\n\n\t\t\tAssert::IsTrue(unsigned int(2) == test.head()->data);\n\t\t\tAssert::IsTrue(unsigned int(0) == test.tail()->data);\n\n\t\t\tCDLL<int>::node * ptr = test.head();\t\t\t\t\/\/ == 2\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\t\/\/ == 0\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\t\/\/ == 1\n\n\t\t\tAssert::IsTrue(ptr == doubleNextPtr->next);\n\t\t\tAssert::IsTrue(nextPtr == doublePrevPtr);\n\t\t\tAssert::IsTrue(prevPtr == doubleNextPtr);\n\t\t\tAssert::IsTrue(ptr != nextPtr);\n\t\t\tAssert::IsTrue(nextPtr != doubleNextPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestOnePushBackItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_back(0);\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(1), test.getSize());\n\t\t\tAssert::IsTrue(unsigned int(0) == test.tail()->data);\n\n\t\t\tCDLL<int>::node * ptr = test.head();\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\n\n\t\t\tAssert::IsTrue(ptr == nextPtr);\n\t\t\tAssert::IsTrue(nextPtr == doubleNextPtr);\n\t\t\tAssert::IsTrue(doubleNextPtr == prevPtr);\n\t\t\tAssert::IsTrue(prevPtr == doublePrevPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestTwoPushBackItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_back(0);\n\t\t\ttest.push_back(1);\n\t\t\t\/\/ <-> 0 <-> 1 <->\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(2), test.getSize());\n\n\t\t\tAssert::IsTrue(unsigned int(0) == test.head()->data);\n\t\t\tAssert::IsTrue(unsigned int(1) == test.tail()->data);\n\n\n\t\t\tCDLL<int>::node * ptr = test.head();\t\t\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\t\/\/ == 0\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\t\/\/ == 0\n\n\t\t\tAssert::IsTrue(ptr == doubleNextPtr);\n\t\t\tAssert::IsTrue(nextPtr == prevPtr);\n\t\t\tAssert::IsTrue(doubleNextPtr == doublePrevPtr);\n\t\t\tAssert::IsTrue(ptr != nextPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestThreePushBackItemList) {\n\t\t\tCDLL<int> test = CDLL<int>();\n\t\t\ttest.push_back(0);\n\t\t\ttest.push_back(1);\n\t\t\ttest.push_back(2);\n\t\t\t\/\/ <-> 0 <-> 1 <-> 2 <->\n\n\t\t\tCDLL<int>::node * thisThing = test.head();\n\n\t\t\tAssert::AreEqual(unsigned int(3), test.getSize());\n\n\t\t\tAssert::IsTrue(unsigned int(0) == test.head()->data);\n\t\t\tAssert::IsTrue(unsigned int(2) == test.tail()->data);\n\n\t\t\tCDLL<int>::node * ptr = test.head();\t\t\t\t\/\/ == 0\n\t\t\tCDLL<int>::node * nextPtr = test.head()->next;\t\t\/\/ == 1\n\t\t\tCDLL<int>::node * doubleNextPtr = nextPtr->next;\t\/\/ == 2\n\t\t\tCDLL<int>::node * prevPtr = test.head()->prev;\t\t\/\/ == 2\n\t\t\tCDLL<int>::node * doublePrevPtr = prevPtr->prev;\t\/\/ == 0\n\n\t\t\tAssert::IsTrue(ptr == doubleNextPtr->next);\n\t\t\tAssert::IsTrue(nextPtr == doublePrevPtr);\n\t\t\tAssert::IsTrue(prevPtr == doubleNextPtr);\n\t\t\tAssert::IsTrue(ptr != nextPtr);\n\t\t\tAssert::IsTrue(nextPtr != doubleNextPtr);\n\t\t}\n\n\t\tTEST_METHOD(TestPopFrontEmptyList) {\n\t\t\tbool exceptionThrown = false;\n\t\t\tauto test = CDLL<int>();\n\t\t\ttry {\n\t\t\t\ttest.pop_front();\n\t\t\t}\n\t\t\tcatch (runtime_error) {\n\t\t\t\texceptionThrown = true;\n\t\t\t}\n\t\t\tAssert::IsTrue(exceptionThrown);\n\t\t}\n\n\t\tTEST_METHOD(TestPopFrontAfterPushFront) {\n\t\t\tauto test = CDLL<int>();\n\t\t\ttest.push_front(1);\n\t\t\tAssert::AreEqual(1, test.pop_front());\n\t\t\tAssert::IsTrue(test.head() == nullptr);\n\t\t\tAssert::IsTrue(test.tail() == nullptr);\n\t\t}\n\n\t\tTEST_METHOD(TestPopFrontAfterTwoPushFront) {\n\t\t\tauto test = CDLL<int>();\n\t\t\ttest.push_front(1);\n\t\t\ttest.push_front(2);\n\t\t\tAssert::AreEqual(2, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(1, test.pop_front());\n\t\t\tAssert::IsTrue(test.head() == nullptr);\n\t\t\tAssert::IsTrue(test.tail() == nullptr);\n\t\t}\n\n\t\tTEST_METHOD(TestPopFrontAfterThreePushFront) {\n\t\t\tauto test = CDLL<int>();\n\t\t\ttest.push_front(1);\n\t\t\ttest.push_front(2);\n\t\t\ttest.push_front(3);\n\t\t\tAssert::AreEqual(3, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(2, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(1, test.pop_front());\n\t\t\tAssert::IsTrue(test.head() == nullptr);\n\t\t\tAssert::IsTrue(test.tail() == nullptr);\n\t\t}\n\n\t\tTEST_METHOD(TestPopFrontAfterPushBack) {\n\t\t\tauto test = CDLL<int>();\n\t\t\ttest.push_back(1);\n\t\t\tAssert::AreEqual(1, test.pop_front());\n\t\t\tAssert::IsTrue(test.head() == nullptr);\n\t\t\tAssert::IsTrue(test.tail() == nullptr);\n\t\t}\n\n\t\tTEST_METHOD(TestPopFrontAfterTwoPushBack) {\n\t\t\tauto test = CDLL<int>();\n\t\t\ttest.push_back(1);\n\t\t\ttest.push_back(2);\n\t\t\tAssert::AreEqual(1, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(2, test.pop_front());\n\t\t\tAssert::IsTrue(test.head() == nullptr);\n\t\t\tAssert::IsTrue(test.tail() == nullptr);\n\t\t}\n\n\t\tTEST_METHOD(TestPopFrontAfterThreePushBack) {\n\t\t\tauto test = CDLL<int>();\n\t\t\ttest.push_back(1);\n\t\t\ttest.push_back(2);\n\t\t\ttest.push_back(3);\n\t\t\tAssert::AreEqual(1, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(2, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(3, test.pop_front());\n\t\t\tAssert::IsTrue(test.head() == nullptr);\n\t\t\tAssert::IsTrue(test.tail() == nullptr);\n\t\t}\n\n\t\tTEST_METHOD(TestPopFrontRandomPushSeries) {\n\t\t\tauto test = CDLL<int>();\n\t\t\ttest.push_back(1);\n\t\t\ttest.push_front(4);\n\t\t\ttest.push_back(3);\n\t\t\ttest.push_front(2);\n\t\t\ttest.push_back(5);\n\t\t\ttest.push_back(6);\n\n\t\t\tAssert::AreEqual(2, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(4, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(1, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(3, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(5, test.pop_front());\n\t\t\tAssert::IsTrue(test.head()->next->prev == test.head());\n\t\t\tAssert::IsTrue(test.head()->prev->next == test.head());\n\t\t\tAssert::AreEqual(6, test.pop_front());\n\t\t\tAssert::IsTrue(test.head() == nullptr);\n\t\t\tAssert::IsTrue(test.tail() == nullptr);\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"<commit_before>\/*\n *\n *\/\n\n#include <iostream>\n#include <chrono>\n#include <cstdint>\n#include <string>\n#include <thread>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n#include <comm\/usb.hpp>\n#include <comm\/buffer.hpp>\n#include <comm\/util\/priority.hpp>\n\nint main (int argc, char *argv[])\n{\n const uint16_t vid = 0x04b4; \/\/ Netchip Technology, Inc\n const uint16_t pid = 0x00f1; \/\/ Linux-USB \"Gadget Zero\"\n const std::string name = \"\/tmp\/usb_to_pipe\";\n const int thresh = 1;\n std::atomic<size_t> sum(0);\n\n comm::util::set_realtime_priority();\n\n comm::usb::source src(vid, pid, comm::usb::endpoint::EP6_IN);\n\n std::thread usb([&]{ while(true) src(); });\n usb.detach();\n\n std::thread throughput([&]{\n while (true)\n {\n comm::util::set_normal_priority();\n\n sum = 0;\n\n auto start = std::chrono::steady_clock::now();\n\n std::this_thread::sleep_for(std::chrono::seconds(1));\n\n auto end = std::chrono::steady_clock::now();\n\n std::chrono::duration<double> diff = end - start;\n\n std::cout << \"Effective rate: \" << sum \/ 2.0 \/ diff.count() \/ 1e6 << \" Msps\" << std::endl;\n }\n });\n throughput.detach();\n\n auto out = src.make_reader<unsigned char>();\n\n if (mkfifo(name.c_str(), 0666) == -1)\n throw std::runtime_error(\"Unable to create a named pipe\");\n\n int fd = open(name.c_str(), O_WRONLY);\n if (fd == -1)\n throw std::runtime_error(\"Unable to open the named pipe\");\n\n while (true)\n {\n out.wait(thresh);\n\n size_t len = out.size();\n\n if (write(fd, out.begin(), len) == -1)\n throw std::runtime_error(\"Failed to write to the named pipe\");\n\n out.consume(len);\n\n sum += len;\n }\n\n return 0;\n}\n<commit_msg>app: add floating point formating<commit_after>\/*\n *\n *\/\n\n#include <iostream>\n#include <iomanip>\n#include <chrono>\n#include <cstdint>\n#include <string>\n#include <thread>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n#include <comm\/usb.hpp>\n#include <comm\/buffer.hpp>\n#include <comm\/util\/priority.hpp>\n\nint main (int argc, char *argv[])\n{\n const uint16_t vid = 0x04b4; \/\/ Netchip Technology, Inc\n const uint16_t pid = 0x00f1; \/\/ Linux-USB \"Gadget Zero\"\n const std::string name = \"\/tmp\/usb_to_pipe\";\n const int thresh = 1;\n std::atomic<size_t> sum(0);\n\n comm::util::set_realtime_priority();\n\n comm::usb::source src(vid, pid, comm::usb::endpoint::EP6_IN);\n\n std::thread usb([&]{ while(true) src(); });\n usb.detach();\n\n std::thread throughput([&]{\n std::cout << std::fixed << std::setprecision(2);\n\n while (true)\n {\n comm::util::set_normal_priority();\n\n sum = 0;\n\n auto start = std::chrono::steady_clock::now();\n\n std::this_thread::sleep_for(std::chrono::seconds(1));\n\n auto end = std::chrono::steady_clock::now();\n\n std::chrono::duration<double> diff = end - start;\n\n std::cout << \"Effective rate: \" << sum \/ 2.0 \/ diff.count() \/ 1e6 << \" Msps\" << std::endl;\n }\n });\n throughput.detach();\n\n auto out = src.make_reader<unsigned char>();\n\n if (mkfifo(name.c_str(), 0666) == -1)\n throw std::runtime_error(\"Unable to create a named pipe\");\n\n int fd = open(name.c_str(), O_WRONLY);\n if (fd == -1)\n throw std::runtime_error(\"Unable to open the named pipe\");\n\n while (true)\n {\n out.wait(thresh);\n\n size_t len = out.size();\n\n if (write(fd, out.begin(), len) == -1)\n throw std::runtime_error(\"Failed to write to the named pipe\");\n\n out.consume(len);\n\n sum += len;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Google 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 \"riegeli\/messages\/message_parse.h\"\n\n#include <stddef.h>\n#include <stdint.h>\n\n#include <limits>\n#include <string>\n\n#include \"absl\/base\/attributes.h\"\n#include \"absl\/base\/optimization.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/strings\/cord.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/types\/optional.h\"\n#include \"google\/protobuf\/io\/coded_stream.h\"\n#include \"google\/protobuf\/io\/zero_copy_stream_impl_lite.h\"\n#include \"google\/protobuf\/message_lite.h\"\n#include \"riegeli\/base\/base.h\"\n#include \"riegeli\/base\/chain.h\"\n#include \"riegeli\/bytes\/chain_reader.h\"\n#include \"riegeli\/bytes\/cord_reader.h\"\n#include \"riegeli\/bytes\/limiting_reader.h\"\n#include \"riegeli\/bytes\/reader.h\"\n\nnamespace riegeli {\n\nnamespace {\n\nABSL_ATTRIBUTE_COLD\ninline absl::Status ParseError(google::protobuf::MessageLite& dest) {\n return absl::InvalidArgumentError(\n absl::StrCat(\"Failed to parse message of type \", dest.GetTypeName()));\n}\n\nABSL_ATTRIBUTE_COLD\ninline absl::Status ParseError(Reader& src,\n google::protobuf::MessageLite& dest) {\n return src.AnnotateStatus(ParseError(dest));\n}\n\ninline absl::Status CheckInitialized(google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.partial() && ABSL_PREDICT_FALSE(!dest.IsInitialized())) {\n return absl::InvalidArgumentError(\n absl::StrCat(\"Failed to parse message of type \", dest.GetTypeName(),\n \" because it is missing required fields: \",\n dest.InitializationErrorString()));\n }\n return absl::OkStatus();\n}\n\ninline absl::Status CheckInitialized(Reader& src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.partial() && ABSL_PREDICT_FALSE(!dest.IsInitialized())) {\n return src.AnnotateStatus(absl::InvalidArgumentError(\n absl::StrCat(\"Failed to parse message of type \", dest.GetTypeName(),\n \" because it is missing required fields: \",\n dest.InitializationErrorString())));\n }\n return absl::OkStatus();\n}\n\n} \/\/ namespace\n\nnamespace messages_internal {\n\nabsl::Status ParseFromReaderImpl(Reader& src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&\n src.SupportsSize()) {\n const absl::optional<Position> size = src.Size();\n if (ABSL_PREDICT_FALSE(size == absl::nullopt)) return src.status();\n src.Pull();\n if (src.limit_pos() == *size && src.available() <= kMaxBytesToCopy) {\n \/\/ The data are flat. `ParsePartialFromArray()` is faster than\n \/\/ `ParsePartialFromZeroCopyStream()`.\n const bool parse_ok = dest.ParsePartialFromArray(\n src.cursor(), IntCast<int>(src.available()));\n src.move_cursor(src.available());\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);\n return CheckInitialized(src, dest, options);\n }\n }\n ReaderInputStream input_stream(&src);\n if (!options.merge()) dest.Clear();\n bool parse_ok;\n if (options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);\n } else {\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n if (ABSL_PREDICT_FALSE(!src.ok())) return src.status();\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);\n return CheckInitialized(src, dest, options);\n}\n\n} \/\/ namespace messages_internal\n\nabsl::Status ParseFromReaderWithLength(Reader& src, size_t length,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&\n length <= kMaxBytesToCopy) {\n src.Pull();\n if (src.available() >= length) {\n \/\/ The data are flat. `ParsePartialFromArray()` is faster than\n \/\/ `ParsePartialFromZeroCopyStream()`.\n const bool parse_ok =\n dest.ParsePartialFromArray(src.cursor(), IntCast<int>(length));\n src.move_cursor(length);\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);\n return CheckInitialized(src, dest, options);\n }\n }\n LimitingReader<> reader(\n &src, LimitingReaderBase::Options().set_exact_length(length));\n ReaderInputStream input_stream(&reader);\n if (!options.merge()) dest.Clear();\n bool parse_ok;\n if (options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);\n } else {\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n if (ABSL_PREDICT_FALSE(!reader.ok())) return reader.status();\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(reader, dest);\n const absl::Status status = CheckInitialized(reader, dest, options);\n if (!reader.Close()) {\n RIEGELI_ASSERT_UNREACHABLE() << \"A LimitingReader with !fail_if_longer() \"\n \"has no reason to fail only in Close(): \"\n << reader.status();\n }\n return status;\n}\n\nabsl::Status ParseFromString(absl::string_view src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n bool parse_ok;\n if (ABSL_PREDICT_FALSE(src.size() >\n size_t{std::numeric_limits<int>::max()})) {\n parse_ok = false;\n } else if (!options.merge() && options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::\n GetDefaultRecursionLimit()) {\n parse_ok = dest.ParsePartialFromArray(src.data(), IntCast<int>(src.size()));\n } else {\n if (!options.merge()) dest.Clear();\n google::protobuf::io::ArrayInputStream input_stream(\n src.data(), IntCast<int>(src.size()));\n if (options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);\n } else {\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n }\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);\n return CheckInitialized(dest, options);\n}\n\nabsl::Status ParseFromChain(const Chain& src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&\n src.size() <= kMaxBytesToCopy) {\n if (const absl::optional<absl::string_view> flat = src.TryFlat()) {\n \/\/ The data are flat. `ParsePartialFromArray()` is faster than\n \/\/ `ParsePartialFromZeroCopyStream()`.\n if (ABSL_PREDICT_FALSE(!dest.ParsePartialFromArray(\n flat->data(), IntCast<int>(flat->size())))) {\n return ParseError(dest);\n }\n return CheckInitialized(dest, options);\n }\n }\n ChainReader<> reader(&src);\n ReaderInputStream input_stream(&reader);\n if (!options.merge()) dest.Clear();\n bool parse_ok;\n if (options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);\n } else {\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n RIEGELI_ASSERT(reader.ok())\n << \"A ChainReader has no reason to fail: \" << reader.status();\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);\n return CheckInitialized(dest, options);\n}\n\nabsl::Status ParseFromCord(const absl::Cord& src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&\n src.size() <= kMaxBytesToCopy) {\n if (const absl::optional<absl::string_view> flat = src.TryFlat()) {\n \/\/ The data are flat. `ParsePartialFromArray()` is faster than\n \/\/ `ParsePartialFromZeroCopyStream()`.\n if (ABSL_PREDICT_FALSE(!dest.ParsePartialFromArray(\n flat->data(), IntCast<int>(flat->size())))) {\n return ParseError(dest);\n }\n return CheckInitialized(dest, options);\n }\n }\n CordReader<> reader(&src);\n ReaderInputStream input_stream(&reader);\n if (!options.merge()) dest.Clear();\n bool parse_ok;\n if (options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);\n } else {\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n RIEGELI_ASSERT(reader.ok())\n << \"A CordReader has no reason to fail: \" << reader.status();\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);\n return CheckInitialized(dest, options);\n}\n\nbool ReaderInputStream::Next(const void** data, int* size) {\n if (ABSL_PREDICT_FALSE(src_->pos() >=\n Position{std::numeric_limits<int64_t>::max()})) {\n return false;\n }\n const Position max_length =\n Position{std::numeric_limits<int64_t>::max()} - src_->pos();\n if (ABSL_PREDICT_FALSE(!src_->Pull())) return false;\n *data = src_->cursor();\n *size = SaturatingIntCast<int>(UnsignedMin(src_->available(), max_length));\n src_->move_cursor(IntCast<size_t>(*size));\n return true;\n}\n\nvoid ReaderInputStream::BackUp(int length) {\n RIEGELI_ASSERT_GE(length, 0)\n << \"Failed precondition of ZeroCopyInputStream::BackUp(): \"\n \"negative length\";\n RIEGELI_ASSERT_LE(IntCast<size_t>(length), src_->start_to_cursor())\n << \"Failed precondition of ZeroCopyInputStream::BackUp(): \"\n \"length larger than the amount of buffered data\";\n src_->set_cursor(src_->cursor() - length);\n}\n\nbool ReaderInputStream::Skip(int length) {\n RIEGELI_ASSERT_GE(length, 0)\n << \"Failed precondition of ZeroCopyInputStream::Skip(): negative length\";\n const Position max_length =\n SaturatingSub(Position{std::numeric_limits<int64_t>::max()}, src_->pos());\n const size_t length_to_skip =\n UnsignedMin(IntCast<size_t>(length), max_length);\n return src_->Skip(length_to_skip) &&\n length_to_skip == IntCast<size_t>(length);\n}\n\nint64_t ReaderInputStream::ByteCount() const {\n return SaturatingIntCast<int64_t>(src_->pos());\n}\n\n} \/\/ namespace riegeli\n<commit_msg>Fix proto parsing.<commit_after>\/\/ Copyright 2017 Google 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 \"riegeli\/messages\/message_parse.h\"\n\n#include <stddef.h>\n#include <stdint.h>\n\n#include <limits>\n#include <string>\n\n#include \"absl\/base\/attributes.h\"\n#include \"absl\/base\/optimization.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/strings\/cord.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/types\/optional.h\"\n#include \"google\/protobuf\/io\/coded_stream.h\"\n#include \"google\/protobuf\/io\/zero_copy_stream_impl_lite.h\"\n#include \"google\/protobuf\/message_lite.h\"\n#include \"riegeli\/base\/base.h\"\n#include \"riegeli\/base\/chain.h\"\n#include \"riegeli\/bytes\/chain_reader.h\"\n#include \"riegeli\/bytes\/cord_reader.h\"\n#include \"riegeli\/bytes\/limiting_reader.h\"\n#include \"riegeli\/bytes\/reader.h\"\n\nnamespace riegeli {\n\nnamespace {\n\nABSL_ATTRIBUTE_COLD\ninline absl::Status ParseError(google::protobuf::MessageLite& dest) {\n return absl::InvalidArgumentError(\n absl::StrCat(\"Failed to parse message of type \", dest.GetTypeName()));\n}\n\nABSL_ATTRIBUTE_COLD\ninline absl::Status ParseError(Reader& src,\n google::protobuf::MessageLite& dest) {\n return src.AnnotateStatus(ParseError(dest));\n}\n\ninline absl::Status CheckInitialized(google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.partial() && ABSL_PREDICT_FALSE(!dest.IsInitialized())) {\n return absl::InvalidArgumentError(\n absl::StrCat(\"Failed to parse message of type \", dest.GetTypeName(),\n \" because it is missing required fields: \",\n dest.InitializationErrorString()));\n }\n return absl::OkStatus();\n}\n\ninline absl::Status CheckInitialized(Reader& src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.partial() && ABSL_PREDICT_FALSE(!dest.IsInitialized())) {\n return src.AnnotateStatus(absl::InvalidArgumentError(\n absl::StrCat(\"Failed to parse message of type \", dest.GetTypeName(),\n \" because it is missing required fields: \",\n dest.InitializationErrorString())));\n }\n return absl::OkStatus();\n}\n\n} \/\/ namespace\n\nnamespace messages_internal {\n\nabsl::Status ParseFromReaderImpl(Reader& src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&\n src.SupportsSize()) {\n const absl::optional<Position> size = src.Size();\n if (ABSL_PREDICT_FALSE(size == absl::nullopt)) return src.status();\n src.Pull();\n if (src.limit_pos() == *size && src.available() <= kMaxBytesToCopy) {\n \/\/ The data are flat. `ParsePartialFromArray()` is faster than\n \/\/ `ParsePartialFromZeroCopyStream()`.\n const bool parse_ok = dest.ParsePartialFromArray(\n src.cursor(), IntCast<int>(src.available()));\n src.move_cursor(src.available());\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);\n return CheckInitialized(src, dest, options);\n }\n }\n ReaderInputStream input_stream(&src);\n bool parse_ok;\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.ParsePartialFromZeroCopyStream(&input_stream);\n } else {\n if (!options.merge()) dest.Clear();\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n if (ABSL_PREDICT_FALSE(!src.ok())) return src.status();\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);\n return CheckInitialized(src, dest, options);\n}\n\n} \/\/ namespace messages_internal\n\nabsl::Status ParseFromReaderWithLength(Reader& src, size_t length,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&\n length <= kMaxBytesToCopy) {\n src.Pull();\n if (src.available() >= length) {\n \/\/ The data are flat. `ParsePartialFromArray()` is faster than\n \/\/ `ParsePartialFromZeroCopyStream()`.\n const bool parse_ok =\n dest.ParsePartialFromArray(src.cursor(), IntCast<int>(length));\n src.move_cursor(length);\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);\n return CheckInitialized(src, dest, options);\n }\n }\n LimitingReader<> reader(\n &src, LimitingReaderBase::Options().set_exact_length(length));\n ReaderInputStream input_stream(&reader);\n bool parse_ok;\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.ParsePartialFromZeroCopyStream(&input_stream);\n } else {\n if (!options.merge()) dest.Clear();\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n if (ABSL_PREDICT_FALSE(!reader.ok())) return reader.status();\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(reader, dest);\n const absl::Status status = CheckInitialized(reader, dest, options);\n if (!reader.Close()) {\n RIEGELI_ASSERT_UNREACHABLE() << \"A LimitingReader with !fail_if_longer() \"\n \"has no reason to fail only in Close(): \"\n << reader.status();\n }\n return status;\n}\n\nabsl::Status ParseFromString(absl::string_view src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n bool parse_ok;\n if (ABSL_PREDICT_FALSE(src.size() >\n size_t{std::numeric_limits<int>::max()})) {\n parse_ok = false;\n } else if (!options.merge() && options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::\n GetDefaultRecursionLimit()) {\n parse_ok = dest.ParsePartialFromArray(src.data(), IntCast<int>(src.size()));\n } else {\n if (!options.merge()) dest.Clear();\n google::protobuf::io::ArrayInputStream input_stream(\n src.data(), IntCast<int>(src.size()));\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);\n return CheckInitialized(dest, options);\n}\n\nabsl::Status ParseFromChain(const Chain& src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&\n src.size() <= kMaxBytesToCopy) {\n if (const absl::optional<absl::string_view> flat = src.TryFlat()) {\n \/\/ The data are flat. `ParsePartialFromArray()` is faster than\n \/\/ `ParsePartialFromZeroCopyStream()`.\n if (ABSL_PREDICT_FALSE(!dest.ParsePartialFromArray(\n flat->data(), IntCast<int>(flat->size())))) {\n return ParseError(dest);\n }\n return CheckInitialized(dest, options);\n }\n }\n ChainReader<> reader(&src);\n ReaderInputStream input_stream(&reader);\n bool parse_ok;\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.ParsePartialFromZeroCopyStream(&input_stream);\n } else {\n if (!options.merge()) dest.Clear();\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n RIEGELI_ASSERT(reader.ok())\n << \"A ChainReader has no reason to fail: \" << reader.status();\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);\n return CheckInitialized(dest, options);\n}\n\nabsl::Status ParseFromCord(const absl::Cord& src,\n google::protobuf::MessageLite& dest,\n ParseOptions options) {\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&\n src.size() <= kMaxBytesToCopy) {\n if (const absl::optional<absl::string_view> flat = src.TryFlat()) {\n \/\/ The data are flat. `ParsePartialFromArray()` is faster than\n \/\/ `ParsePartialFromZeroCopyStream()`.\n if (ABSL_PREDICT_FALSE(!dest.ParsePartialFromArray(\n flat->data(), IntCast<int>(flat->size())))) {\n return ParseError(dest);\n }\n return CheckInitialized(dest, options);\n }\n }\n CordReader<> reader(&src);\n ReaderInputStream input_stream(&reader);\n bool parse_ok;\n if (!options.merge() &&\n options.recursion_limit() ==\n google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {\n parse_ok = dest.ParsePartialFromZeroCopyStream(&input_stream);\n } else {\n if (!options.merge()) dest.Clear();\n google::protobuf::io::CodedInputStream coded_stream(&input_stream);\n coded_stream.SetRecursionLimit(options.recursion_limit());\n parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&\n coded_stream.ConsumedEntireMessage();\n }\n RIEGELI_ASSERT(reader.ok())\n << \"A CordReader has no reason to fail: \" << reader.status();\n if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);\n return CheckInitialized(dest, options);\n}\n\nbool ReaderInputStream::Next(const void** data, int* size) {\n if (ABSL_PREDICT_FALSE(src_->pos() >=\n Position{std::numeric_limits<int64_t>::max()})) {\n return false;\n }\n const Position max_length =\n Position{std::numeric_limits<int64_t>::max()} - src_->pos();\n if (ABSL_PREDICT_FALSE(!src_->Pull())) return false;\n *data = src_->cursor();\n *size = SaturatingIntCast<int>(UnsignedMin(src_->available(), max_length));\n src_->move_cursor(IntCast<size_t>(*size));\n return true;\n}\n\nvoid ReaderInputStream::BackUp(int length) {\n RIEGELI_ASSERT_GE(length, 0)\n << \"Failed precondition of ZeroCopyInputStream::BackUp(): \"\n \"negative length\";\n RIEGELI_ASSERT_LE(IntCast<size_t>(length), src_->start_to_cursor())\n << \"Failed precondition of ZeroCopyInputStream::BackUp(): \"\n \"length larger than the amount of buffered data\";\n src_->set_cursor(src_->cursor() - length);\n}\n\nbool ReaderInputStream::Skip(int length) {\n RIEGELI_ASSERT_GE(length, 0)\n << \"Failed precondition of ZeroCopyInputStream::Skip(): negative length\";\n const Position max_length =\n SaturatingSub(Position{std::numeric_limits<int64_t>::max()}, src_->pos());\n const size_t length_to_skip =\n UnsignedMin(IntCast<size_t>(length), max_length);\n return src_->Skip(length_to_skip) &&\n length_to_skip == IntCast<size_t>(length);\n}\n\nint64_t ReaderInputStream::ByteCount() const {\n return SaturatingIntCast<int64_t>(src_->pos());\n}\n\n} \/\/ namespace riegeli\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: modulemanager.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:45:18 $\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#include \"services\/modulemanager.hxx\"\n#include \"services\/frame.hxx\"\n\n\/\/_______________________________________________\n\/\/ own includes\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include <threadhelp\/readguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include <threadhelp\/writeguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_SERVICES_H_\n#include <services.h>\n#endif\n\n\/\/_______________________________________________\n\/\/ interface includes\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include <com\/sun\/star\/frame\/XController.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#endif\n\n\/\/_______________________________________________\n\/\/ other includes\n\n#ifndef css\nnamespace css = ::com::sun::star;\n#endif\n\nnamespace framework\n{\n\n\/*-----------------------------------------------\n 04.12.2003 09:32\n-----------------------------------------------*\/\nDEFINE_XINTERFACE_5(ModuleManager ,\n OWeakObject ,\n DIRECT_INTERFACE(css::lang::XTypeProvider ),\n DIRECT_INTERFACE(css::lang::XServiceInfo ),\n DIRECT_INTERFACE(css::container::XNameAccess ),\n DIRECT_INTERFACE(css::container::XElementAccess),\n DIRECT_INTERFACE(css::frame::XModuleManager ))\n\n\/*-----------------------------------------------\n 04.12.2003 09:32\n-----------------------------------------------*\/\nDEFINE_XTYPEPROVIDER_5(ModuleManager ,\n css::lang::XTypeProvider ,\n css::lang::XServiceInfo ,\n css::container::XNameAccess ,\n css::container::XElementAccess,\n css::frame::XModuleManager )\n\n\/*-----------------------------------------------\n 04.12.2003 09:35\n-----------------------------------------------*\/\nDEFINE_XSERVICEINFO_ONEINSTANCESERVICE(ModuleManager ,\n ::cppu::OWeakObject ,\n SERVICENAME_MODULEMANAGER ,\n IMPLEMENTATIONNAME_MODULEMANAGER)\n\n\/*-----------------------------------------------\n 04.12.2003 09:35\n-----------------------------------------------*\/\nDEFINE_INIT_SERVICE(\n ModuleManager,\n {\n \/*Attention\n I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()\n to create a new instance of this class by our own supported service factory.\n see macro DEFINE_XSERVICEINFO_MULTISERVICE and \"impl_initService()\" for further informations!\n *\/\n }\n )\n\n\/*-----------------------------------------------\n 04.12.2003 09:30\n-----------------------------------------------*\/\nModuleManager::ModuleManager(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR)\n : ThreadHelpBase( )\n , m_xSMGR (xSMGR)\n{\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:59\n-----------------------------------------------*\/\nModuleManager::~ModuleManager()\n{\n if (m_xCFG.is())\n m_xCFG.clear();\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:02\n-----------------------------------------------*\/\n::rtl::OUString SAL_CALL ModuleManager::identify(const css::uno::Reference< css::uno::XInterface >& xModule)\n throw(css::lang::IllegalArgumentException,\n css::frame::UnknownModuleException,\n css::uno::RuntimeException )\n{\n \/\/ valid parameter?\n css::uno::Reference< css::frame::XFrame > xFrame (xModule, css::uno::UNO_QUERY);\n css::uno::Reference< css::frame::XController > xController(xModule, css::uno::UNO_QUERY);\n css::uno::Reference< css::frame::XModel > xModel (xModule, css::uno::UNO_QUERY);\n\n if (\n (!xFrame.is() ) &&\n (!xController.is()) &&\n (!xModel.is() )\n )\n {\n throw css::lang::IllegalArgumentException(\n ::rtl::OUString::createFromAscii(\"Not a XFrame, XController nor a XModel reference.\"),\n static_cast< ::cppu::OWeakObject* >(this),\n 1);\n }\n\n \/\/ frame empty?\n \/\/ controller\/model?\n \/\/ all needed interfaces available?\n css::uno::Reference< css::lang::XServiceInfo > xInfo;\n if (xFrame.is())\n xController = xFrame->getController();\n if (xController.is())\n xModel = xController->getModel();\n\n if (xModel.is())\n xInfo = css::uno::Reference< css::lang::XServiceInfo >(xModel, css::uno::UNO_QUERY);\n else if (xController.is())\n xInfo = css::uno::Reference< css::lang::XServiceInfo >(xController, css::uno::UNO_QUERY);\n else if (xFrame.is()) \/\/ needed for detection of special modules (like e.g. help)!\n xInfo = css::uno::Reference< css::lang::XServiceInfo >(xFrame, css::uno::UNO_QUERY);\n\n if (!xInfo.is())\n throw css::frame::UnknownModuleException(\n ::rtl::OUString::createFromAscii(\"Cant classify given module.\"),\n static_cast< ::cppu::OWeakObject* >(this));\n\n \/\/ SAFE -> ----------------------------------\n ReadGuard aReadLock(m_aLock);\n \/\/ TODO\n \/\/ Please migrate to new method impl_identifyNew() in case every office module\n \/\/ supports it right service name and can be asked directly ...\n\n \/\/ throws an UnknownModuleException in case module has no configuration!\n ::rtl::OUString sIdentifier = impl_identify(xInfo);\n aReadLock.unlock();\n \/\/ <- SAFE ----------------------------------\n return sIdentifier;\n}\n\n\/*-----------------------------------------------\n 10.12.2003 12:05\n-----------------------------------------------*\/\ncss::uno::Any SAL_CALL ModuleManager::getByName(const ::rtl::OUString& sName)\n throw(css::container::NoSuchElementException,\n css::lang::WrappedTargetException ,\n css::uno::RuntimeException )\n{\n \/\/ get access to the element\n css::uno::Reference< css::container::XNameAccess > xCFG = implts_openConfig();\n css::uno::Any aElement = xCFG->getByName(sName);\n\n css::uno::Reference< css::container::XNameAccess > xElement;\n aElement >>= xElement;\n if (!xElement.is())\n {\n throw css::container::NoSuchElementException(\n ::rtl::OUString::createFromAscii(\"The module configuration seems to be corrupted.\"),\n static_cast< css::container::XNameAccess* >(this));\n }\n\n \/\/ convert it to seq< PropertyValue >!\n const css::uno::Sequence< ::rtl::OUString > lProps = xElement->getElementNames();\n const ::rtl::OUString* pProps = lProps.getConstArray();\n sal_Int32 c = lProps.getLength();\n\n css::uno::Sequence< css::beans::PropertyValue > lElement(c);\n css::beans::PropertyValue* pElement = lElement.getArray();\n\n for (sal_Int32 i=0; i<c; ++i)\n {\n pElement[i].Name = pProps[i];\n pElement[i].Value = xElement->getByName(pProps[i]);\n }\n\n \/* TODO\n a) add some implicit properties for readonly\/mandatory ...\n b) catch exception during property access ...\n But how they should be handled?\n *\/\n\n return css::uno::makeAny(lElement);\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:58\n-----------------------------------------------*\/\ncss::uno::Sequence< ::rtl::OUString > SAL_CALL ModuleManager::getElementNames()\n throw(css::uno::RuntimeException)\n{\n css::uno::Reference< css::container::XNameAccess > xCFG = implts_openConfig();\n return xCFG->getElementNames();\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:57\n-----------------------------------------------*\/\nsal_Bool SAL_CALL ModuleManager::hasByName(const ::rtl::OUString& sName)\n throw(css::uno::RuntimeException)\n{\n css::uno::Reference< css::container::XNameAccess > xCFG = implts_openConfig();\n return xCFG->hasByName(sName);\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:35\n-----------------------------------------------*\/\ncss::uno::Type SAL_CALL ModuleManager::getElementType()\n throw(css::uno::RuntimeException)\n{\n return ::getCppuType((const css::uno::Sequence< css::beans::PropertyValue >*)0);\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:56\n-----------------------------------------------*\/\nsal_Bool SAL_CALL ModuleManager::hasElements()\n throw(css::uno::RuntimeException)\n{\n css::uno::Reference< css::container::XNameAccess > xCFG = implts_openConfig();\n return xCFG->hasElements();\n}\n\n\/*-----------------------------------------------\n 14.12.2003 09:45\n-----------------------------------------------*\/\ncss::uno::Reference< css::container::XNameAccess > ModuleManager::implts_openConfig()\n throw(css::uno::RuntimeException)\n{\n \/\/ SAFE -> ----------------------------------\n WriteGuard aWriteLock(m_aLock);\n if (m_xCFG.is())\n return m_xCFG;\n\n css::uno::Reference< css::uno::XInterface > xCFG;\n try\n {\n css::uno::Reference< css::lang::XMultiServiceFactory > xConfigProvider(\n m_xSMGR->createInstance(SERVICENAME_CFGPROVIDER), css::uno::UNO_QUERY);\n\n if (!xConfigProvider.is())\n throw css::uno::RuntimeException(\n ::rtl::OUString::createFromAscii(\"Could not locate configuration service.\"),\n static_cast< css::container::XNameAccess* >(this));\n\n \/\/ set root path\n css::uno::Sequence< css::uno::Any > lParams(1);\n css::beans::PropertyValue aParam;\n aParam.Name = ::rtl::OUString::createFromAscii(\"nodepath\");\n aParam.Value <<= ::rtl::OUString::createFromAscii(\"\/org.openoffice.Setup\/Office\/Factories\");\n lParams[0] <<= aParam;\n\n \/\/ open it\n xCFG = xConfigProvider->createInstanceWithArguments(SERVICENAME_CFGREADACCESS, lParams);\n }\n catch(const css::uno::RuntimeException&)\n { throw; }\n catch(const css::uno::Exception&)\n { xCFG.clear(); }\n\n m_xCFG = css::uno::Reference< css::container::XNameAccess >(xCFG, css::uno::UNO_QUERY);\n if (!m_xCFG.is())\n {\n throw css::uno::RuntimeException(\n ::rtl::OUString::createFromAscii(\"Could not open configuration package \/org.openoffice.Setup\/Office\/Factories.\"),\n static_cast< css::container::XNameAccess* >(this));\n }\n\n return m_xCFG;\n \/\/ <- SAFE ----------------------------------\n}\n\n\/*-----------------------------------------------\n 30.01.2004 07:54\n-----------------------------------------------*\/\n::rtl::OUString ModuleManager::impl_identify(const css::uno::Reference< css::lang::XServiceInfo >& xModule)\n throw(css::frame::UnknownModuleException)\n{\n const css::uno::Sequence< ::rtl::OUString > lKnownModules = getElementNames();\n const ::rtl::OUString* pKnownModules = lKnownModules.getConstArray();\n sal_Int32 c = lKnownModules.getLength();\n\n \/\/ detect modules in a generic way ...\n for (sal_Int32 m=0; m<c; ++m)\n {\n if (xModule->supportsService(pKnownModules[m]))\n return pKnownModules[m];\n }\n\n throw css::frame::UnknownModuleException(\n ::rtl::OUString::createFromAscii(\"Cant classify given module.\"),\n static_cast< ::cppu::OWeakObject* >(this));\n}\n\n} \/\/ namespace framework\n<commit_msg>INTEGRATION: CWS pchfix02 (1.6.202); FILE MERGED 2006\/09\/01 17:29:20 kaib 1.6.202.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: modulemanager.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 14:11:01 $\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_framework.hxx\"\n\n#include \"services\/modulemanager.hxx\"\n#include \"services\/frame.hxx\"\n\n\/\/_______________________________________________\n\/\/ own includes\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include <threadhelp\/readguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include <threadhelp\/writeguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_SERVICES_H_\n#include <services.h>\n#endif\n\n\/\/_______________________________________________\n\/\/ interface includes\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include <com\/sun\/star\/frame\/XController.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#endif\n\n\/\/_______________________________________________\n\/\/ other includes\n\n#ifndef css\nnamespace css = ::com::sun::star;\n#endif\n\nnamespace framework\n{\n\n\/*-----------------------------------------------\n 04.12.2003 09:32\n-----------------------------------------------*\/\nDEFINE_XINTERFACE_5(ModuleManager ,\n OWeakObject ,\n DIRECT_INTERFACE(css::lang::XTypeProvider ),\n DIRECT_INTERFACE(css::lang::XServiceInfo ),\n DIRECT_INTERFACE(css::container::XNameAccess ),\n DIRECT_INTERFACE(css::container::XElementAccess),\n DIRECT_INTERFACE(css::frame::XModuleManager ))\n\n\/*-----------------------------------------------\n 04.12.2003 09:32\n-----------------------------------------------*\/\nDEFINE_XTYPEPROVIDER_5(ModuleManager ,\n css::lang::XTypeProvider ,\n css::lang::XServiceInfo ,\n css::container::XNameAccess ,\n css::container::XElementAccess,\n css::frame::XModuleManager )\n\n\/*-----------------------------------------------\n 04.12.2003 09:35\n-----------------------------------------------*\/\nDEFINE_XSERVICEINFO_ONEINSTANCESERVICE(ModuleManager ,\n ::cppu::OWeakObject ,\n SERVICENAME_MODULEMANAGER ,\n IMPLEMENTATIONNAME_MODULEMANAGER)\n\n\/*-----------------------------------------------\n 04.12.2003 09:35\n-----------------------------------------------*\/\nDEFINE_INIT_SERVICE(\n ModuleManager,\n {\n \/*Attention\n I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()\n to create a new instance of this class by our own supported service factory.\n see macro DEFINE_XSERVICEINFO_MULTISERVICE and \"impl_initService()\" for further informations!\n *\/\n }\n )\n\n\/*-----------------------------------------------\n 04.12.2003 09:30\n-----------------------------------------------*\/\nModuleManager::ModuleManager(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR)\n : ThreadHelpBase( )\n , m_xSMGR (xSMGR)\n{\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:59\n-----------------------------------------------*\/\nModuleManager::~ModuleManager()\n{\n if (m_xCFG.is())\n m_xCFG.clear();\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:02\n-----------------------------------------------*\/\n::rtl::OUString SAL_CALL ModuleManager::identify(const css::uno::Reference< css::uno::XInterface >& xModule)\n throw(css::lang::IllegalArgumentException,\n css::frame::UnknownModuleException,\n css::uno::RuntimeException )\n{\n \/\/ valid parameter?\n css::uno::Reference< css::frame::XFrame > xFrame (xModule, css::uno::UNO_QUERY);\n css::uno::Reference< css::frame::XController > xController(xModule, css::uno::UNO_QUERY);\n css::uno::Reference< css::frame::XModel > xModel (xModule, css::uno::UNO_QUERY);\n\n if (\n (!xFrame.is() ) &&\n (!xController.is()) &&\n (!xModel.is() )\n )\n {\n throw css::lang::IllegalArgumentException(\n ::rtl::OUString::createFromAscii(\"Not a XFrame, XController nor a XModel reference.\"),\n static_cast< ::cppu::OWeakObject* >(this),\n 1);\n }\n\n \/\/ frame empty?\n \/\/ controller\/model?\n \/\/ all needed interfaces available?\n css::uno::Reference< css::lang::XServiceInfo > xInfo;\n if (xFrame.is())\n xController = xFrame->getController();\n if (xController.is())\n xModel = xController->getModel();\n\n if (xModel.is())\n xInfo = css::uno::Reference< css::lang::XServiceInfo >(xModel, css::uno::UNO_QUERY);\n else if (xController.is())\n xInfo = css::uno::Reference< css::lang::XServiceInfo >(xController, css::uno::UNO_QUERY);\n else if (xFrame.is()) \/\/ needed for detection of special modules (like e.g. help)!\n xInfo = css::uno::Reference< css::lang::XServiceInfo >(xFrame, css::uno::UNO_QUERY);\n\n if (!xInfo.is())\n throw css::frame::UnknownModuleException(\n ::rtl::OUString::createFromAscii(\"Cant classify given module.\"),\n static_cast< ::cppu::OWeakObject* >(this));\n\n \/\/ SAFE -> ----------------------------------\n ReadGuard aReadLock(m_aLock);\n \/\/ TODO\n \/\/ Please migrate to new method impl_identifyNew() in case every office module\n \/\/ supports it right service name and can be asked directly ...\n\n \/\/ throws an UnknownModuleException in case module has no configuration!\n ::rtl::OUString sIdentifier = impl_identify(xInfo);\n aReadLock.unlock();\n \/\/ <- SAFE ----------------------------------\n return sIdentifier;\n}\n\n\/*-----------------------------------------------\n 10.12.2003 12:05\n-----------------------------------------------*\/\ncss::uno::Any SAL_CALL ModuleManager::getByName(const ::rtl::OUString& sName)\n throw(css::container::NoSuchElementException,\n css::lang::WrappedTargetException ,\n css::uno::RuntimeException )\n{\n \/\/ get access to the element\n css::uno::Reference< css::container::XNameAccess > xCFG = implts_openConfig();\n css::uno::Any aElement = xCFG->getByName(sName);\n\n css::uno::Reference< css::container::XNameAccess > xElement;\n aElement >>= xElement;\n if (!xElement.is())\n {\n throw css::container::NoSuchElementException(\n ::rtl::OUString::createFromAscii(\"The module configuration seems to be corrupted.\"),\n static_cast< css::container::XNameAccess* >(this));\n }\n\n \/\/ convert it to seq< PropertyValue >!\n const css::uno::Sequence< ::rtl::OUString > lProps = xElement->getElementNames();\n const ::rtl::OUString* pProps = lProps.getConstArray();\n sal_Int32 c = lProps.getLength();\n\n css::uno::Sequence< css::beans::PropertyValue > lElement(c);\n css::beans::PropertyValue* pElement = lElement.getArray();\n\n for (sal_Int32 i=0; i<c; ++i)\n {\n pElement[i].Name = pProps[i];\n pElement[i].Value = xElement->getByName(pProps[i]);\n }\n\n \/* TODO\n a) add some implicit properties for readonly\/mandatory ...\n b) catch exception during property access ...\n But how they should be handled?\n *\/\n\n return css::uno::makeAny(lElement);\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:58\n-----------------------------------------------*\/\ncss::uno::Sequence< ::rtl::OUString > SAL_CALL ModuleManager::getElementNames()\n throw(css::uno::RuntimeException)\n{\n css::uno::Reference< css::container::XNameAccess > xCFG = implts_openConfig();\n return xCFG->getElementNames();\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:57\n-----------------------------------------------*\/\nsal_Bool SAL_CALL ModuleManager::hasByName(const ::rtl::OUString& sName)\n throw(css::uno::RuntimeException)\n{\n css::uno::Reference< css::container::XNameAccess > xCFG = implts_openConfig();\n return xCFG->hasByName(sName);\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:35\n-----------------------------------------------*\/\ncss::uno::Type SAL_CALL ModuleManager::getElementType()\n throw(css::uno::RuntimeException)\n{\n return ::getCppuType((const css::uno::Sequence< css::beans::PropertyValue >*)0);\n}\n\n\/*-----------------------------------------------\n 10.12.2003 11:56\n-----------------------------------------------*\/\nsal_Bool SAL_CALL ModuleManager::hasElements()\n throw(css::uno::RuntimeException)\n{\n css::uno::Reference< css::container::XNameAccess > xCFG = implts_openConfig();\n return xCFG->hasElements();\n}\n\n\/*-----------------------------------------------\n 14.12.2003 09:45\n-----------------------------------------------*\/\ncss::uno::Reference< css::container::XNameAccess > ModuleManager::implts_openConfig()\n throw(css::uno::RuntimeException)\n{\n \/\/ SAFE -> ----------------------------------\n WriteGuard aWriteLock(m_aLock);\n if (m_xCFG.is())\n return m_xCFG;\n\n css::uno::Reference< css::uno::XInterface > xCFG;\n try\n {\n css::uno::Reference< css::lang::XMultiServiceFactory > xConfigProvider(\n m_xSMGR->createInstance(SERVICENAME_CFGPROVIDER), css::uno::UNO_QUERY);\n\n if (!xConfigProvider.is())\n throw css::uno::RuntimeException(\n ::rtl::OUString::createFromAscii(\"Could not locate configuration service.\"),\n static_cast< css::container::XNameAccess* >(this));\n\n \/\/ set root path\n css::uno::Sequence< css::uno::Any > lParams(1);\n css::beans::PropertyValue aParam;\n aParam.Name = ::rtl::OUString::createFromAscii(\"nodepath\");\n aParam.Value <<= ::rtl::OUString::createFromAscii(\"\/org.openoffice.Setup\/Office\/Factories\");\n lParams[0] <<= aParam;\n\n \/\/ open it\n xCFG = xConfigProvider->createInstanceWithArguments(SERVICENAME_CFGREADACCESS, lParams);\n }\n catch(const css::uno::RuntimeException&)\n { throw; }\n catch(const css::uno::Exception&)\n { xCFG.clear(); }\n\n m_xCFG = css::uno::Reference< css::container::XNameAccess >(xCFG, css::uno::UNO_QUERY);\n if (!m_xCFG.is())\n {\n throw css::uno::RuntimeException(\n ::rtl::OUString::createFromAscii(\"Could not open configuration package \/org.openoffice.Setup\/Office\/Factories.\"),\n static_cast< css::container::XNameAccess* >(this));\n }\n\n return m_xCFG;\n \/\/ <- SAFE ----------------------------------\n}\n\n\/*-----------------------------------------------\n 30.01.2004 07:54\n-----------------------------------------------*\/\n::rtl::OUString ModuleManager::impl_identify(const css::uno::Reference< css::lang::XServiceInfo >& xModule)\n throw(css::frame::UnknownModuleException)\n{\n const css::uno::Sequence< ::rtl::OUString > lKnownModules = getElementNames();\n const ::rtl::OUString* pKnownModules = lKnownModules.getConstArray();\n sal_Int32 c = lKnownModules.getLength();\n\n \/\/ detect modules in a generic way ...\n for (sal_Int32 m=0; m<c; ++m)\n {\n if (xModule->supportsService(pKnownModules[m]))\n return pKnownModules[m];\n }\n\n throw css::frame::UnknownModuleException(\n ::rtl::OUString::createFromAscii(\"Cant classify given module.\"),\n static_cast< ::cppu::OWeakObject* >(this));\n}\n\n} \/\/ namespace framework\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011, Google Inc. All rights reserved.\n * Copyright (C) 2012, Samsung Electronics. 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 met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; 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 ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/navigatorcontentutils\/NavigatorContentUtils.h\"\n\n#include \"bindings\/v8\/ExceptionState.h\"\n#include \"core\/dom\/Document.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/frame\/Navigator.h\"\n#include \"core\/page\/Page.h\"\n#include \"wtf\/HashSet.h\"\n\nnamespace WebCore {\n\nstatic HashSet<String>* protocolWhitelist;\n\nstatic void initProtocolHandlerWhitelist()\n{\n protocolWhitelist = new HashSet<String>;\n static const char* const protocols[] = {\n \"bitcoin\",\n \"geo\",\n \"im\",\n \"irc\",\n \"ircs\",\n \"magnet\",\n \"mailto\",\n \"mms\",\n \"news\",\n \"nntp\",\n \"sip\",\n \"sms\",\n \"smsto\",\n \"ssh\",\n \"tel\",\n \"urn\",\n \"webcal\",\n \"wtai\",\n \"xmpp\",\n };\n for (size_t i = 0; i < WTF_ARRAY_LENGTH(protocols); ++i)\n protocolWhitelist->add(protocols[i]);\n}\n\nstatic bool verifyCustomHandlerURL(const KURL& baseURL, const String& url, ExceptionState& exceptionState)\n{\n \/\/ The specification requires that it is a SyntaxError if the \"%s\" token is\n \/\/ not present.\n static const char token[] = \"%s\";\n int index = url.find(token);\n if (-1 == index) {\n exceptionState.throwDOMException(SyntaxError, \"The url provided ('\" + url + \"') does not contain '%s'.\");\n return false;\n }\n\n \/\/ It is also a SyntaxError if the custom handler URL, as created by removing\n \/\/ the \"%s\" token and prepending the base url, does not resolve.\n String newURL = url;\n newURL.remove(index, WTF_ARRAY_LENGTH(token) - 1);\n\n KURL kurl(baseURL, newURL);\n\n if (kurl.isEmpty() || !kurl.isValid()) {\n exceptionState.throwDOMException(SyntaxError, \"The custom handler URL created by removing '%s' and prepending '\" + baseURL.string() + \"' is invalid.\");\n return false;\n }\n\n return true;\n}\n\nstatic bool isProtocolWhitelisted(const String& scheme)\n{\n if (!protocolWhitelist)\n initProtocolHandlerWhitelist();\n return protocolWhitelist->contains(scheme);\n}\n\nstatic bool verifyProtocolHandlerScheme(const String& scheme, const String& method, ExceptionState& exceptionState)\n{\n if (scheme.startsWith(\"web+\")) {\n \/\/ The specification requires that the length of scheme is at least five characteres (including 'web+' prefix).\n if (scheme.length() >= 5 && isValidProtocol(scheme))\n return true;\n if (!isValidProtocol(scheme))\n exceptionState.throwSecurityError(\"The scheme '\" + scheme + \"' is not a valid protocol.\");\n else\n exceptionState.throwSecurityError(\"The scheme '\" + scheme + \"' is less than five characters long.\");\n return false;\n }\n\n if (isProtocolWhitelisted(scheme))\n return true;\n exceptionState.throwSecurityError(\"The scheme '\" + scheme + \"' doesn't belong to the protocol whitelist. Please prefix non-whitelisted schemes with the string 'web+'.\");\n return false;\n}\n\nNavigatorContentUtils* NavigatorContentUtils::from(Page& page)\n{\n return static_cast<NavigatorContentUtils*>(Supplement<Page>::from(page, supplementName()));\n}\n\nNavigatorContentUtils::~NavigatorContentUtils()\n{\n}\n\nPassOwnPtr<NavigatorContentUtils> NavigatorContentUtils::create(PassOwnPtr<NavigatorContentUtilsClient> client)\n{\n return adoptPtr(new NavigatorContentUtils(client));\n}\n\nvoid NavigatorContentUtils::registerProtocolHandler(Navigator& navigator, const String& scheme, const String& url, const String& title, ExceptionState& exceptionState)\n{\n if (!navigator.frame())\n return;\n\n Document* document = navigator.frame()->document();\n if (!document)\n return;\n\n KURL baseURL = document->baseURL();\n\n if (!verifyCustomHandlerURL(baseURL, url, exceptionState))\n return;\n\n if (!verifyProtocolHandlerScheme(scheme, \"registerProtocolHandler\", exceptionState))\n return;\n\n ASSERT(navigator.frame()->page());\n NavigatorContentUtils::from(*navigator.frame()->page())->client()->registerProtocolHandler(scheme, baseURL, KURL(ParsedURLString, url), title);\n}\n\nstatic String customHandlersStateString(const NavigatorContentUtilsClient::CustomHandlersState state)\n{\n DEFINE_STATIC_LOCAL(const String, newHandler, (\"new\"));\n DEFINE_STATIC_LOCAL(const String, registeredHandler, (\"registered\"));\n DEFINE_STATIC_LOCAL(const String, declinedHandler, (\"declined\"));\n\n switch (state) {\n case NavigatorContentUtilsClient::CustomHandlersNew:\n return newHandler;\n case NavigatorContentUtilsClient::CustomHandlersRegistered:\n return registeredHandler;\n case NavigatorContentUtilsClient::CustomHandlersDeclined:\n return declinedHandler;\n }\n\n ASSERT_NOT_REACHED();\n return String();\n}\n\nString NavigatorContentUtils::isProtocolHandlerRegistered(Navigator& navigator, const String& scheme, const String& url, ExceptionState& exceptionState)\n{\n DEFINE_STATIC_LOCAL(const String, declined, (\"declined\"));\n\n if (!navigator.frame())\n return declined;\n\n Document* document = navigator.frame()->document();\n if (document->activeDOMObjectsAreStopped())\n return declined;\n\n KURL baseURL = document->baseURL();\n\n if (!verifyCustomHandlerURL(baseURL, url, exceptionState))\n return declined;\n\n if (!verifyProtocolHandlerScheme(scheme, \"isProtocolHandlerRegistered\", exceptionState))\n return declined;\n\n ASSERT(navigator.frame()->page());\n return customHandlersStateString(NavigatorContentUtils::from(*navigator.frame()->page())->client()->isProtocolHandlerRegistered(scheme, baseURL, KURL(ParsedURLString, url)));\n}\n\nvoid NavigatorContentUtils::unregisterProtocolHandler(Navigator& navigator, const String& scheme, const String& url, ExceptionState& exceptionState)\n{\n if (!navigator.frame())\n return;\n\n Document* document = navigator.frame()->document();\n KURL baseURL = document->baseURL();\n\n if (!verifyCustomHandlerURL(baseURL, url, exceptionState))\n return;\n\n if (!verifyProtocolHandlerScheme(scheme, \"unregisterProtocolHandler\", exceptionState))\n return;\n\n ASSERT(navigator.frame()->page());\n NavigatorContentUtils::from(*navigator.frame()->page())->client()->unregisterProtocolHandler(scheme, baseURL, KURL(ParsedURLString, url));\n}\n\nconst char* NavigatorContentUtils::supplementName()\n{\n return \"NavigatorContentUtils\";\n}\n\nvoid provideNavigatorContentUtilsTo(Page& page, PassOwnPtr<NavigatorContentUtilsClient> client)\n{\n NavigatorContentUtils::provideTo(page, NavigatorContentUtils::supplementName(), NavigatorContentUtils::create(client));\n}\n\n} \/\/ namespace WebCore\n<commit_msg>Remove unnecessary null checking in NavigatorContentUtils<commit_after>\/*\n * Copyright (C) 2011, Google Inc. All rights reserved.\n * Copyright (C) 2012, Samsung Electronics. 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 met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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 *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; 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 ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/navigatorcontentutils\/NavigatorContentUtils.h\"\n\n#include \"bindings\/v8\/ExceptionState.h\"\n#include \"core\/dom\/Document.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/frame\/Navigator.h\"\n#include \"core\/page\/Page.h\"\n#include \"wtf\/HashSet.h\"\n\nnamespace WebCore {\n\nstatic HashSet<String>* protocolWhitelist;\n\nstatic void initProtocolHandlerWhitelist()\n{\n protocolWhitelist = new HashSet<String>;\n static const char* const protocols[] = {\n \"bitcoin\",\n \"geo\",\n \"im\",\n \"irc\",\n \"ircs\",\n \"magnet\",\n \"mailto\",\n \"mms\",\n \"news\",\n \"nntp\",\n \"sip\",\n \"sms\",\n \"smsto\",\n \"ssh\",\n \"tel\",\n \"urn\",\n \"webcal\",\n \"wtai\",\n \"xmpp\",\n };\n for (size_t i = 0; i < WTF_ARRAY_LENGTH(protocols); ++i)\n protocolWhitelist->add(protocols[i]);\n}\n\nstatic bool verifyCustomHandlerURL(const KURL& baseURL, const String& url, ExceptionState& exceptionState)\n{\n \/\/ The specification requires that it is a SyntaxError if the \"%s\" token is\n \/\/ not present.\n static const char token[] = \"%s\";\n int index = url.find(token);\n if (-1 == index) {\n exceptionState.throwDOMException(SyntaxError, \"The url provided ('\" + url + \"') does not contain '%s'.\");\n return false;\n }\n\n \/\/ It is also a SyntaxError if the custom handler URL, as created by removing\n \/\/ the \"%s\" token and prepending the base url, does not resolve.\n String newURL = url;\n newURL.remove(index, WTF_ARRAY_LENGTH(token) - 1);\n\n KURL kurl(baseURL, newURL);\n\n if (kurl.isEmpty() || !kurl.isValid()) {\n exceptionState.throwDOMException(SyntaxError, \"The custom handler URL created by removing '%s' and prepending '\" + baseURL.string() + \"' is invalid.\");\n return false;\n }\n\n return true;\n}\n\nstatic bool isProtocolWhitelisted(const String& scheme)\n{\n if (!protocolWhitelist)\n initProtocolHandlerWhitelist();\n return protocolWhitelist->contains(scheme);\n}\n\nstatic bool verifyProtocolHandlerScheme(const String& scheme, const String& method, ExceptionState& exceptionState)\n{\n if (scheme.startsWith(\"web+\")) {\n \/\/ The specification requires that the length of scheme is at least five characteres (including 'web+' prefix).\n if (scheme.length() >= 5 && isValidProtocol(scheme))\n return true;\n if (!isValidProtocol(scheme))\n exceptionState.throwSecurityError(\"The scheme '\" + scheme + \"' is not a valid protocol.\");\n else\n exceptionState.throwSecurityError(\"The scheme '\" + scheme + \"' is less than five characters long.\");\n return false;\n }\n\n if (isProtocolWhitelisted(scheme))\n return true;\n exceptionState.throwSecurityError(\"The scheme '\" + scheme + \"' doesn't belong to the protocol whitelist. Please prefix non-whitelisted schemes with the string 'web+'.\");\n return false;\n}\n\nNavigatorContentUtils* NavigatorContentUtils::from(Page& page)\n{\n return static_cast<NavigatorContentUtils*>(Supplement<Page>::from(page, supplementName()));\n}\n\nNavigatorContentUtils::~NavigatorContentUtils()\n{\n}\n\nPassOwnPtr<NavigatorContentUtils> NavigatorContentUtils::create(PassOwnPtr<NavigatorContentUtilsClient> client)\n{\n return adoptPtr(new NavigatorContentUtils(client));\n}\n\nvoid NavigatorContentUtils::registerProtocolHandler(Navigator& navigator, const String& scheme, const String& url, const String& title, ExceptionState& exceptionState)\n{\n if (!navigator.frame())\n return;\n\n ASSERT(navigator.frame()->document());\n KURL baseURL = navigator.frame()->document()->baseURL();\n\n if (!verifyCustomHandlerURL(baseURL, url, exceptionState))\n return;\n\n if (!verifyProtocolHandlerScheme(scheme, \"registerProtocolHandler\", exceptionState))\n return;\n\n ASSERT(navigator.frame()->page());\n NavigatorContentUtils::from(*navigator.frame()->page())->client()->registerProtocolHandler(scheme, baseURL, KURL(ParsedURLString, url), title);\n}\n\nstatic String customHandlersStateString(const NavigatorContentUtilsClient::CustomHandlersState state)\n{\n DEFINE_STATIC_LOCAL(const String, newHandler, (\"new\"));\n DEFINE_STATIC_LOCAL(const String, registeredHandler, (\"registered\"));\n DEFINE_STATIC_LOCAL(const String, declinedHandler, (\"declined\"));\n\n switch (state) {\n case NavigatorContentUtilsClient::CustomHandlersNew:\n return newHandler;\n case NavigatorContentUtilsClient::CustomHandlersRegistered:\n return registeredHandler;\n case NavigatorContentUtilsClient::CustomHandlersDeclined:\n return declinedHandler;\n }\n\n ASSERT_NOT_REACHED();\n return String();\n}\n\nString NavigatorContentUtils::isProtocolHandlerRegistered(Navigator& navigator, const String& scheme, const String& url, ExceptionState& exceptionState)\n{\n DEFINE_STATIC_LOCAL(const String, declined, (\"declined\"));\n\n if (!navigator.frame())\n return declined;\n\n Document* document = navigator.frame()->document();\n ASSERT(document);\n if (document->activeDOMObjectsAreStopped())\n return declined;\n\n KURL baseURL = document->baseURL();\n\n if (!verifyCustomHandlerURL(baseURL, url, exceptionState))\n return declined;\n\n if (!verifyProtocolHandlerScheme(scheme, \"isProtocolHandlerRegistered\", exceptionState))\n return declined;\n\n ASSERT(navigator.frame()->page());\n return customHandlersStateString(NavigatorContentUtils::from(*navigator.frame()->page())->client()->isProtocolHandlerRegistered(scheme, baseURL, KURL(ParsedURLString, url)));\n}\n\nvoid NavigatorContentUtils::unregisterProtocolHandler(Navigator& navigator, const String& scheme, const String& url, ExceptionState& exceptionState)\n{\n if (!navigator.frame())\n return;\n\n ASSERT(navigator.frame()->document());\n KURL baseURL = navigator.frame()->document()->baseURL();\n\n if (!verifyCustomHandlerURL(baseURL, url, exceptionState))\n return;\n\n if (!verifyProtocolHandlerScheme(scheme, \"unregisterProtocolHandler\", exceptionState))\n return;\n\n ASSERT(navigator.frame()->page());\n NavigatorContentUtils::from(*navigator.frame()->page())->client()->unregisterProtocolHandler(scheme, baseURL, KURL(ParsedURLString, url));\n}\n\nconst char* NavigatorContentUtils::supplementName()\n{\n return \"NavigatorContentUtils\";\n}\n\nvoid provideNavigatorContentUtilsTo(Page& page, PassOwnPtr<NavigatorContentUtilsClient> client)\n{\n NavigatorContentUtils::provideTo(page, NavigatorContentUtils::supplementName(), NavigatorContentUtils::create(client));\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n\n#include <unistd.h>\n#include <getopt.h>\n\n#include <rsa-attack-lib\/common_modulus.hh> \/\/ comodulus namespace\n#include <rsa-attack-lib\/low_exponent.hh> \/\/ lowexp namespace\n#include <rsa-attack-lib\/factorization_attack.hh> \/\/ factoratk namespace\n#include <rsa-attack-lib\/rsa-attack-lib.hh> \/\/ rsatk namespace\n\n\nconst std::vector<std::string> attack_types = {\"factoring\", \"common_modulus\", \"other\"};\n\nvoid what_attack_types() {\n std::cerr << \"\\nType can be \";\n for (std::size_t i = 0; i < attack_types.size(); ++i) {\n std::cerr << \"\\'\" << attack_types[i] << \"\\', \";\n }\n std::cerr << std::endl;\n}\n\nvoid usage() {\n std::cerr << \"Usage is --attack [type] --pubkey1 [filename] (--pubkey2 [filename] --pubkey3 [filename] --ciphertext [filename])\" << std::endl;\n}\n\nbool is_everything_correct(int file_count, int aflag, bool ioerror) {\n if (ioerror) {\n std::cerr\n << \"File i\/o error. Check that file exists and has correct permissions.\"\n << std::endl;\n return false;\n }\n if (aflag == -1) {\n std::cerr << \"missing argument --attack [type]\" << std::endl;\n what_attack_types();\n return false;\n }\n if(aflag == 1 && file_count < 2){\n std::cerr << \"needs two filenames for the \" << attack_types[aflag] << \"attack\" << std::endl;\n return false;\n }\n if(aflag == 2 && file_count < 4){\n std::cerr << \"needs three public keys, and one ciphertext\";\n }\n else if (file_count == 0) {\n std::cerr << \"missing argument --pubkey1 [file_to_crack]\" << std::endl;\n return false;\n }\n return true;\n}\n\nint main(int argc, char* argv[]) {\n \/* options descriptor *\/\n static struct option longopts[] = {{\"attack\", required_argument, NULL, 'a'},\n {\"ciphertext\", required_argument, NULL, 'b'},\n {\"ciphertext2\", required_argument, NULL, 'c'},\n {\"pubkey1\", required_argument, NULL, 'x'},\n {\"pubkey2\", required_argument, NULL, 'y'},\n {\"pubkey3\", required_argument, NULL, 'z'},\n {\"help\", no_argument, NULL, 'h'},\n {NULL, 0, NULL, 0}};\n\n bool ioerror = false;\n int option_index = 0;\n int file_count = 0, aflag = -1, ch = 0;\n std::fstream f_1;\n std::fstream f_2;\n std::fstream f_3;\n std::fstream cipher_file, cipher_file2;\n while ((ch = getopt_long(argc, argv, \"a:b:c:x:y:z:h\", longopts, &option_index)) !=\n -1) {\n switch (ch) {\n case 'a': {\n for(size_t i = 0; i < attack_types.size(); ++i){\n if(attack_types[i] == optarg) {\n aflag = i;\n }\n }\n if(aflag == -1) {\n what_attack_types();\n }\n break;\n }\n case 'x': {\n file_count += 1;\n std::string fname = std::string(optarg);\n f_1.open(fname, std::ios::in);\n if (!f_1.is_open()) {\n ioerror = true;\n std::cout << fname << \" : error.\" << std::endl;\n }\n\n break;\n }\n case 'y': {\n file_count += 1;\n\n std::string fname = std::string(optarg);\n f_2.open(fname, std::ios::in);\n if (!f_2.is_open()) {\n ioerror = true;\n std::cout << fname << \" : error.\" << std::endl;\n }\n break;\n }\n case 'z': {\n file_count += 1;\n\n std::string fname = std::string(optarg);\n f_3.open(fname, std::ios::in);\n if (!f_3.is_open()) {\n ioerror = true;\n std::cout << fname << \" : error.\" << std::endl;\n }\n break;\n }\n case 'b': {\n file_count += 1;\n\n std::string fname = std::string(optarg);\n cipher_file.open(fname, std::ios::in);\n if (!cipher_file.is_open()) {\n ioerror = true;\n std::cout << fname << \" : error.\" << std::endl;\n }\n break;\n }\n case 'c': {\n file_count += 1;\n\n std::string fname = std::string(optarg);\n cipher_file2.open(fname, std::ios::in);\n if (!cipher_file2.is_open()) {\n std::cout << fname << \" : error.\" << std::endl;\n ioerror = true;\n }\n break;\n }\n case 'h':\n break;\n case '?':\n break;\n default: {\n usage();\n what_attack_types();\n std::exit(EXIT_FAILURE);\n }\n }\n }\n\n bool good = is_everything_correct(file_count, aflag, ioerror);\n\n if(good){\n std::cout << \"Starting decryption...\" << std::endl;\n rsatk::RSA_data r_1 = rsatk::parse_rsa_file(f_1);\n if(aflag == 0) {\n factoratk::factorization_attack(r_1);\n }\n else if (aflag == 1) {\n rsatk::RSA_data r_2 = rsatk::parse_rsa_file(f_2);\n r_1.C = base64_decode(rsatk::read_cipher_text(cipher_file));\n r_2.C = base64_decode(rsatk::read_cipher_text(cipher_file2));\n\n comodulus::common_modulus_attack(r_1, r_2);\n }\n else if (aflag == 2) {\n rsatk::RSA_data r_2 = rsatk::parse_rsa_file(f_2);\n rsatk::RSA_data r_3 = rsatk::parse_rsa_file(f_3);\n std::string c = base64_decode(rsatk::read_cipher_text(cipher_file));\n r_1.C = r_2.C = r_3.C = c;\n lowexp::low_exponent_attack(r_1, r_2, r_3);\n }\n }\n\n argc -= optind;\n argv += optind;\n\n\n std::exit(EXIT_SUCCESS);\n}\n<commit_msg>Now has sane prompt instead of a million args<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n\n#include <unistd.h>\n#include <getopt.h>\n\n#include <rsa-attack-lib\/common_modulus.hh> \/\/ comodulus namespace\n#include <rsa-attack-lib\/low_exponent.hh> \/\/ lowexp namespace\n#include <rsa-attack-lib\/factorization_attack.hh> \/\/ factoratk namespace\n#include <rsa-attack-lib\/rsa-attack-lib.hh> \/\/ rsatk namespace\n\n\nconst std::vector<std::string> attack_types = {\"factoring\", \"common_modulus\", \"low_exponent\"};\n\nbool is_whole_number(std::string s)\n{\n for(int i = 0; i < s.size(); ++i){\n if(!(int(s[i]) >= 48 && (int)s[i] <= 57)){\n return false;\n }\n }\n return true;\n}\n\nmpz_class get_whole_number(){\n int attempts = 0;\n mpz_class n = 0;\n std::string n_str = \"\";\n while(attempts < 5){\n std::cout << \"(Please enter a whole number):\\n\";\n try {\n std::cin >> n_str;\n\n if (!is_whole_number(n_str) || std::cin.fail()){\n throw \"Sorry, I don't think that's a whole number?\\n\";\n }\n if (n < 0){\n throw \"Sorry, no negative numbers. Try something else? \\n\";\n }\n \/\/std::cin.clear();\n n = mpz_class(n_str);\n return n;\n }\n catch (const char* error) {\n std::cout << error;\n attempts++;\n }\n }\n return -1;\n}\n\nvoid run_factoring(){\n rsatk::RSA_data r_1;\n\n std::cout << \"What is the n value? \\n\";\n r_1.n = get_whole_number();\n std::cout << \"What is the e value? \\n\";\n r_1.e = get_whole_number();\n std::cout << \"Starting decryption...\" << r_1.n << r_1.e;\n factoratk::factorization_attack(r_1);\n}\n\n\nvoid run_comodulus(){\n rsatk::RSA_data r_1;\n rsatk::RSA_data r_2;\n\n std::cout << \"What is the common n value? \\n\";\n r_1.n = r_2.n = get_whole_number();\n\n std::cout << \"What is the first message's e value? \";\n r_1.e = get_whole_number();\n std::cout << \"What is the second message's e value? \";\n r_2.e = get_whole_number();\n std::cout << \"Provide the first encrypted message:\\n\";\n std::cin >> r_1.C;\n std::cout << \"Provide the second encrypted message:\\n\";\n std::cin >> r_2.C;\n std::cout << \"Starting decryption...\";\n comodulus::common_modulus_attack(r_1, r_2);\n}\n\nvoid run_low_exp(){\n rsatk::RSA_data r_1;\n rsatk::RSA_data r_2;\n rsatk::RSA_data r_3;\n\n std::cout << \"What is the common e value? \";\n r_1.e = r_2.e = r_3.e = get_whole_number();\n std::cout << \"What is the first n value? \";\n r_1.n = get_whole_number();\n std::cout << \"What is the second n value? \";\n r_2.n = get_whole_number();\n std::cout << \"What is the third n value? \";\n r_3.n = get_whole_number();\n std::cout << \"Provide the first encrypted message: \\n\";\n std::cin >> r_1.C;\n std::cout << \"Provide the second encrypted message: \\n\";\n std::cin >> r_2.C;\n std::cout << \"Provide the third encrypted message: \\n\";\n std::cin >> r_3.C;\n std::cout << \"Starting decryption...\";\n lowexp::low_exponent_attack(r_1, r_2, r_3);\n}\n\n\nvoid what_attack_types() {\n std::cerr << \"\\nType can be \";\n for (std::size_t i = 0; i < attack_types.size(); ++i) {\n std::cerr << \"\\'\" << attack_types[i] << \"\\', \";\n }\n std::cerr << std::endl;\n}\n\nvoid usage() {\n std::cerr << \"Usage is --attack [type] \" << std::endl;\n}\n\n\nint main(int argc, char* argv[]) {\n \/* options descriptor *\/\n static struct option longopts[] = {{\"attack\", required_argument, NULL, 'a'},\n {\"help\", no_argument, NULL, 'h'},\n {NULL, 0, NULL, 0}};\n\n bool ioerror = false;\n int option_index = 0;\n int file_count = 0, aflag = -1, ch = 0;\n while ((ch = getopt_long(argc, argv, \"a:h\", longopts, &option_index)) !=\n -1) {\n switch (ch) {\n case 'a': {\n for(size_t i = 0; i < attack_types.size(); ++i){\n if(attack_types[i] == optarg) {\n aflag = i;\n }\n }\n if(aflag == -1) {\n what_attack_types();\n }\n break;\n }\n case 'h':\n break;\n case '?':\n break;\n default: {\n usage();\n what_attack_types();\n std::exit(EXIT_FAILURE);\n }\n }\n argc -= optind;\n argv += optind;\n\n }\n if(aflag == -1){\n usage();\n what_attack_types();\n std::exit(EXIT_FAILURE);\n }\n\n if(aflag == 0) {\n run_factoring();\n }\n if(aflag == 1) {\n run_comodulus();\n }\n if(aflag == 2) {\n run_low_exp();\n }\n\n std::exit(EXIT_SUCCESS);\n}\n\n\/\/rsatk::RSA_data r_1 = rsatk::parse_rsa_file(f_1);\n\/\/else if (aflag == 1) {\n\/\/rsatk::RSA_data r_2 = rsatk::parse_rsa_file(f_2);\n\/\/r_1.C = base64_decode(rsatk::read_cipher_text(cipher_file));\n\/\/r_2.C = base64_decode(rsatk::read_cipher_text(cipher_file2));\n\/\/\n\/\/comodulus::common_modulus_attack(r_1, r_2);\n\/\/}\n\/\/else if (aflag == 2) {\n\/\/rsatk::RSA_data r_2 = rsatk::parse_rsa_file(f_2);\n\/\/rsatk::RSA_data r_3 = rsatk::parse_rsa_file(f_3);\n\/\/std::string c = base64_decode(rsatk::read_cipher_text(cipher_file));\n\/\/r_1.C = r_2.C = r_3.C = c;\n\/\/lowexp::low_exponent_attack(r_1, r_2, r_3);\n\/\/}\n\/\/}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/testing\/testing.hpp\"\n\n#include \"..\/xml_element.hpp\"\n#include \"..\/osm2type.hpp\"\n\n#include \"..\/..\/indexer\/feature_data.hpp\"\n#include \"..\/..\/indexer\/classificator.hpp\"\n\n\nnamespace\n{\n void FillXmlElement(char const * arr[][2], size_t count, XMLElement * p)\n {\n p->parent = 0;\n for (size_t i = 0; i < count; ++i)\n {\n p->childs.push_back(XMLElement());\n p->childs.back().name = \"tag\";\n p->childs.back().attrs[\"k\"] = arr[i][0];\n p->childs.back().attrs[\"v\"] = arr[i][1];\n }\n }\n\n uint32_t GetType(char const * arr[2])\n {\n vector<string> path;\n path.push_back(arr[0]);\n path.push_back(arr[1]);\n return classif().GetTypeByPath(path);\n }\n}\n\nUNIT_TEST(OsmType_SkipDummy)\n{\n char const * arr[][2] = {\n { \"abutters\", \"residential\" },\n { \"highway\", \"primary\" },\n { \"osmarender:renderRef\", \"no\" },\n { \"ref\", \"E51\" }\n };\n\n XMLElement e;\n FillXmlElement(arr, ARRAY_SIZE(arr), &e);\n\n FeatureParams params;\n ftype::GetNameAndType(&e, params);\n\n TEST_EQUAL ( params.m_Types.size(), 1, () );\n TEST_EQUAL ( params.m_Types[0], GetType(arr[1]), () );\n}\n<commit_msg>Fix OsmType unit test - add classificator loading.<commit_after>#include \"..\/..\/testing\/testing.hpp\"\n\n#include \"..\/xml_element.hpp\"\n#include \"..\/osm2type.hpp\"\n\n#include \"..\/..\/indexer\/feature_data.hpp\"\n#include \"..\/..\/indexer\/classificator.hpp\"\n#include \"..\/..\/indexer\/classificator_loader.hpp\"\n\n#include \"..\/..\/platform\/platform.hpp\"\n\n\nnamespace\n{\n void FillXmlElement(char const * arr[][2], size_t count, XMLElement * p)\n {\n p->parent = 0;\n for (size_t i = 0; i < count; ++i)\n {\n p->childs.push_back(XMLElement());\n p->childs.back().name = \"tag\";\n p->childs.back().attrs[\"k\"] = arr[i][0];\n p->childs.back().attrs[\"v\"] = arr[i][1];\n }\n }\n\n uint32_t GetType(char const * arr[2])\n {\n vector<string> path;\n path.push_back(arr[0]);\n path.push_back(arr[1]);\n return classif().GetTypeByPath(path);\n }\n}\n\nUNIT_TEST(OsmType_SkipDummy)\n{\n Platform & p = GetPlatform();\n classificator::Read(p.GetReader(\"drawing_rules.bin\"),\n p.GetReader(\"classificator.txt\"),\n p.GetReader(\"visibility.txt\"),\n p.GetReader(\"types.txt\"));\n\n char const * arr[][2] = {\n { \"abutters\", \"residential\" },\n { \"highway\", \"primary\" },\n { \"osmarender:renderRef\", \"no\" },\n { \"ref\", \"E51\" }\n };\n\n XMLElement e;\n FillXmlElement(arr, ARRAY_SIZE(arr), &e);\n\n FeatureParams params;\n ftype::GetNameAndType(&e, params);\n\n TEST_EQUAL ( params.m_Types.size(), 1, () );\n TEST_EQUAL ( params.m_Types[0], GetType(arr[1]), () );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Usage:\n\/\/ makeResults.C(\"tasks\", \"file_list\", \"\"task_id, kGRID)\n\/\/ tasks : \"ALL\" or one\/more of the following separated by space:\n\/\/ \"EFF\" : TRD Tracking Efficiency \n\/\/ \"EFFC\" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations\n\/\/ \"RES\" : TRD tracking Resolution\n\/\/ \"PID\" : TRD PID - pion efficiency \n\/\/ \"DET\" : Basic TRD Detector checks\n\/\/ \"NOFR\" : Data set does not have AliESDfriends.root \n\/\/ \"NOMC\" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely\n\/\/ on MC information are switched off\n\/\/ file_list : is the list of the files to be processed. \n\/\/ They should contain the full path. Here is an example:\n\/\/ \/lustre\/alice\/local\/TRDdata\/SIM\/P-Flat\/TRUNK\/RUN0\/TRD.Performance.root\n\/\/ or for GRID alien:\/\/\/alice\/cern.ch\/user\/m\/mfasel\/MinBiasProd\/results\/ppMinBias80000\/1\/TRD.Performance.root\n\/\/ task_id : identifier of task speciality as defined by the AddMacro.C. \n\/\/ (e.g. AddTRDresolution.C defines \"\" for barrel tracks, \"K\" for kink tracks and \"SA\" for stand alone tracks)\n\/\/ kGRID : specify if files are comming from a GRID collection [default kFALSE]\n\/\/\n\/\/ HOW TO BUILD THE FILE LIST\n\/\/ 1. locally\n\/\/ ls -1 BaseDir\/RUN*\/TRD.Performance.root > files.lst\n\/\/ \n\/\/ 2. on Grid\n\/\/ char *BaseDir=\"\/alice\/cern.ch\/user\/m\/mfasel\/MinBiasProd\/results\/ppMinBias80000\/\";\n\/\/ TGrid::Connect(\"alien:\/\/\");\n\/\/ TGridResult *res = gGrid->Query(BaseDir, \"%\/TRD.Performance.root\");\n\/\/ TGridCollection *col = gGrid->OpenCollectionQuery(res);\n\/\/ col->Reset();\n\/\/ TMap *map = 0x0;\n\/\/ while(map = (TMap*)col->Next()){\n\/\/ TIter it((TCollection*)map);\n\/\/ TObjString *info = 0x0;\n\/\/ while(info=(TObjString*)it()){\n\/\/ printf(\"alien:\/\/%s\\n\", col->GetLFN(info->GetString().Data()));\n\/\/ }\n\/\/ }\n\/\/\n\/\/ The files which will be processed are the intersection between the\n\/\/ condition on the tasks and the files in the file list.\n\/\/\n\/\/ Authors:\n\/\/ Alex Bercuci (A.Bercuci@gsi.de) \n\/\/ Markus Fasel (m.Fasel@gsi.de) \n\/\/\n\n#if ! defined (__CINT__) || defined (__MAKECINT__)\n#include <fstream>\n#include \"TError.h\"\n#include <TClass.h>\n#include <TCanvas.h>\n#include <TH1.h>\n#include <TGraph.h>\n#include <TObjArray.h>\n#include <TObjString.h>\n#include <TString.h>\n#include <TROOT.h>\n#include <TStyle.h>\n#include <TGrid.h>\n#include <TGridResult.h>\n#include <TGridCollection.h>\n\n#include \"AliLog.h\"\n\n#include \"PWG1\/TRD\/AliTRDrecoTask.h\"\n#include \"PWG1\/TRD\/AliTRDcheckESD.h\"\n\n#endif\n\n#include \"AliTRDperformanceTrain.h\"\n#include \"helper.C\"\n\/\/#include \"..\/..\/PWG1\/macros\/AddPerformanceTask.h\"\n\nChar_t *libs[] = {\"libProofPlayer.so\", \"libANALYSIS.so\", \"libANALYSISalice.so\", \"libTENDER.so\", \"libPWG1.so\"};\n\/\/ define setup\nTCanvas *c = 0x0;\nBool_t mc(kFALSE), friends(kFALSE);\nBool_t summary(kTRUE);\n\nvoid processTRD(TNamed* task, const Char_t *filename);\nvoid processESD(TNamed* task, const Char_t *filename);\nvoid makeResults(Char_t *opt = \"ALL\", const Char_t *files=\"QAResults.root\", Char_t *cid = \"\", Bool_t kGRID=kFALSE, Bool_t dosummary = kTRUE)\n{\n if(kGRID){\n if(!gSystem->Getenv(\"GSHELL_ROOT\")){\n Error(\"makeResults.C\", \"AliEn not initialized.\");\n return;\n }\n TGrid::Connect(\"alien:\/\/\");\n }\n\n\t\/\/ Load Libraries in interactive mode\n Int_t nlibs = static_cast<Int_t>(sizeof(libs)\/sizeof(Char_t *));\n for(Int_t ilib=0; ilib<nlibs; ilib++){\n if(gSystem->Load(libs[ilib]) >= 0) continue;\n Error(\"makeResults.C\", Form(\"Failed to load %s.\", libs[ilib]));\n return;\n }\n\n mc = HasReadMCData(opt);\n friends = HasReadFriendData(opt);\n\n gStyle->SetOptStat(0);\n gStyle->SetOptFit(0);\n TString outputFile;\n if(!TString(files).EndsWith(\".root\")){ \n outputFile = Form(\"%s\/QAResults.root\", gSystem->ExpandPathName(\"$PWD\"));\n mergeProd(\"QAResults.root\", files);\n } else {\n outputFile = files;\n }\n Int_t fSteerTask = ParseOptions(opt);\n\n if(!dosummary){\n summary = kFLASE;\n if(!c) c=new TCanvas(\"c\", \"Performance\", 10, 10, 800, 500);\n }\n\n TClass *ctask = new TClass;\n AliAnalysisTask *task = 0x0;\n for(Int_t itask = NTRDQATASKS; itask--;){\n if(!TSTBIT(fSteerTask, itask)) continue;\n new(ctask) TClass(fgkTRDtaskClassName[itask]);\n task = (AliAnalysisTask*)ctask->New();\n task->SetName(Form(\"%s%s\", task->GetName(), cid));\n printf(\"task %s, output file %s\\n\", task->GetName(), outputFile.Data());\n if(task->IsA()->InheritsFrom(\"AliTRDrecoTask\")) processTRD(task, outputFile.Data());\n else processESD(task, outputFile.Data());\n }\n delete ctask;\n delete c;\n}\n\n\n\/\/______________________________________________________\nvoid processTRD(TNamed *otask, const Char_t *filename)\n{\n printf(\"process[%s] : %s\\n\", otask->GetName(), otask->GetTitle());\n Int_t debug(0);\n AliTRDrecoTask *task = dynamic_cast<AliTRDrecoTask*>(otask);\n task->SetDebugLevel(debug);\n AliLog::SetClassDebugLevel(otask->IsA()->GetName(), debug);\n task->SetMCdata(mc);\n task->SetFriends(friends);\n\n \/\/if(!task->Load(Form(\"%s\/AnalysisResults.root\", gSystem->ExpandPathName(\"$PWD\")))){\n if(!task->Load(filename)){\n Error(\"makeResults.C\", Form(\"Load data container for task %s failed.\", task->GetName()));\n delete task;\n return;\n }\n\n if(!task->PostProcess()){\n Error(\"makeResults.C\", Form(\"Processing data container for task %s failed.\", task->GetName()));\n delete task;\n return;\n }\n if(summary) task->MakeSummary();\n else{\n for(Int_t ipic=0; ipic<task->GetNRefFigures(); ipic++){\n c->Clear();\n if(!task->GetRefFigure(ipic)) continue;\n c->SaveAs(Form(\"%s_Fig%02d.gif\", task->GetName(), ipic), \"gif\");\n }\n }\n delete task;\n}\n\n\/\/______________________________________________________\nvoid processESD(TNamed *otask, const Char_t *filename)\n{\n printf(\"process[%s] : %s\\n\", otask->GetName(), otask->GetTitle());\n\n AliTRDcheckESD *esd = dynamic_cast<AliTRDcheckESD*>(otask);\n if(!esd){\n Info(\"makeResults.C\", Form(\"Processing of task %s failed.\", otask->GetName()));\n delete otask;\n return;\n }\n \/\/if(!esd->Load(Form(\"%s\/AnalysisResults.root\", gSystem->ExpandPathName(\"$PWD\")), \"TRD_Performance\")){\n if(!esd->Load(filename, \"TRD_Performance\")){\n Error(\"makeResults.C\", Form(\"Load data container for task %s failed.\", esd->GetName()));\n delete esd;\n return;\n }\n esd->Terminate(NULL);\n \n if(summary) esd->MakeSummary();\n else{\n for(Int_t ipic(0); ipic<esd->GetNRefFigures(); ipic++){\n c->Clear(); \n if(!esd->GetRefFigure(ipic)) continue;\n c->SaveAs(Form(\"%s_Fig%02d.gif\", esd->GetName(), ipic));\n }\n }\n delete esd;\n}\n<commit_msg>fix typo<commit_after>\/\/ Usage:\n\/\/ makeResults.C(\"tasks\", \"file_list\", \"\"task_id, kGRID)\n\/\/ tasks : \"ALL\" or one\/more of the following separated by space:\n\/\/ \"EFF\" : TRD Tracking Efficiency \n\/\/ \"EFFC\" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations\n\/\/ \"RES\" : TRD tracking Resolution\n\/\/ \"PID\" : TRD PID - pion efficiency \n\/\/ \"DET\" : Basic TRD Detector checks\n\/\/ \"NOFR\" : Data set does not have AliESDfriends.root \n\/\/ \"NOMC\" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely\n\/\/ on MC information are switched off\n\/\/ file_list : is the list of the files to be processed. \n\/\/ They should contain the full path. Here is an example:\n\/\/ \/lustre\/alice\/local\/TRDdata\/SIM\/P-Flat\/TRUNK\/RUN0\/TRD.Performance.root\n\/\/ or for GRID alien:\/\/\/alice\/cern.ch\/user\/m\/mfasel\/MinBiasProd\/results\/ppMinBias80000\/1\/TRD.Performance.root\n\/\/ task_id : identifier of task speciality as defined by the AddMacro.C. \n\/\/ (e.g. AddTRDresolution.C defines \"\" for barrel tracks, \"K\" for kink tracks and \"SA\" for stand alone tracks)\n\/\/ kGRID : specify if files are comming from a GRID collection [default kFALSE]\n\/\/\n\/\/ HOW TO BUILD THE FILE LIST\n\/\/ 1. locally\n\/\/ ls -1 BaseDir\/RUN*\/TRD.Performance.root > files.lst\n\/\/ \n\/\/ 2. on Grid\n\/\/ char *BaseDir=\"\/alice\/cern.ch\/user\/m\/mfasel\/MinBiasProd\/results\/ppMinBias80000\/\";\n\/\/ TGrid::Connect(\"alien:\/\/\");\n\/\/ TGridResult *res = gGrid->Query(BaseDir, \"%\/TRD.Performance.root\");\n\/\/ TGridCollection *col = gGrid->OpenCollectionQuery(res);\n\/\/ col->Reset();\n\/\/ TMap *map = 0x0;\n\/\/ while(map = (TMap*)col->Next()){\n\/\/ TIter it((TCollection*)map);\n\/\/ TObjString *info = 0x0;\n\/\/ while(info=(TObjString*)it()){\n\/\/ printf(\"alien:\/\/%s\\n\", col->GetLFN(info->GetString().Data()));\n\/\/ }\n\/\/ }\n\/\/\n\/\/ The files which will be processed are the intersection between the\n\/\/ condition on the tasks and the files in the file list.\n\/\/\n\/\/ Authors:\n\/\/ Alex Bercuci (A.Bercuci@gsi.de) \n\/\/ Markus Fasel (m.Fasel@gsi.de) \n\/\/\n\n#if ! defined (__CINT__) || defined (__MAKECINT__)\n#include <fstream>\n#include \"TError.h\"\n#include <TClass.h>\n#include <TCanvas.h>\n#include <TH1.h>\n#include <TGraph.h>\n#include <TObjArray.h>\n#include <TObjString.h>\n#include <TString.h>\n#include <TROOT.h>\n#include <TStyle.h>\n#include <TGrid.h>\n#include <TGridResult.h>\n#include <TGridCollection.h>\n\n#include \"AliLog.h\"\n\n#include \"PWG1\/TRD\/AliTRDrecoTask.h\"\n#include \"PWG1\/TRD\/AliTRDcheckESD.h\"\n\n#endif\n\n#include \"AliTRDperformanceTrain.h\"\n#include \"helper.C\"\n\/\/#include \"..\/..\/PWG1\/macros\/AddPerformanceTask.h\"\n\nChar_t *libs[] = {\"libProofPlayer.so\", \"libANALYSIS.so\", \"libANALYSISalice.so\", \"libTENDER.so\", \"libPWG1.so\"};\n\/\/ define setup\nTCanvas *c = 0x0;\nBool_t mc(kFALSE), friends(kFALSE);\nBool_t summary(kTRUE);\n\nvoid processTRD(TNamed* task, const Char_t *filename);\nvoid processESD(TNamed* task, const Char_t *filename);\nvoid makeResults(Char_t *opt = \"ALL\", const Char_t *files=\"QAResults.root\", Char_t *cid = \"\", Bool_t kGRID=kFALSE, Bool_t dosummary = kTRUE)\n{\n if(kGRID){\n if(!gSystem->Getenv(\"GSHELL_ROOT\")){\n Error(\"makeResults.C\", \"AliEn not initialized.\");\n return;\n }\n TGrid::Connect(\"alien:\/\/\");\n }\n\n\t\/\/ Load Libraries in interactive mode\n Int_t nlibs = static_cast<Int_t>(sizeof(libs)\/sizeof(Char_t *));\n for(Int_t ilib=0; ilib<nlibs; ilib++){\n if(gSystem->Load(libs[ilib]) >= 0) continue;\n Error(\"makeResults.C\", Form(\"Failed to load %s.\", libs[ilib]));\n return;\n }\n\n mc = HasReadMCData(opt);\n friends = HasReadFriendData(opt);\n\n gStyle->SetOptStat(0);\n gStyle->SetOptFit(0);\n TString outputFile;\n if(!TString(files).EndsWith(\".root\")){ \n outputFile = Form(\"%s\/QAResults.root\", gSystem->ExpandPathName(\"$PWD\"));\n mergeProd(\"QAResults.root\", files);\n } else {\n outputFile = files;\n }\n Int_t fSteerTask = ParseOptions(opt);\n\n if(!dosummary){\n summary = kFALSE;\n if(!c) c=new TCanvas(\"c\", \"Performance\", 10, 10, 800, 500);\n }\n\n TClass *ctask = new TClass;\n AliAnalysisTask *task = 0x0;\n for(Int_t itask = NTRDQATASKS; itask--;){\n if(!TSTBIT(fSteerTask, itask)) continue;\n new(ctask) TClass(fgkTRDtaskClassName[itask]);\n task = (AliAnalysisTask*)ctask->New();\n task->SetName(Form(\"%s%s\", task->GetName(), cid));\n printf(\"task %s, output file %s\\n\", task->GetName(), outputFile.Data());\n if(task->IsA()->InheritsFrom(\"AliTRDrecoTask\")) processTRD(task, outputFile.Data());\n else processESD(task, outputFile.Data());\n }\n delete ctask;\n delete c;\n}\n\n\n\/\/______________________________________________________\nvoid processTRD(TNamed *otask, const Char_t *filename)\n{\n printf(\"process[%s] : %s\\n\", otask->GetName(), otask->GetTitle());\n Int_t debug(0);\n AliTRDrecoTask *task = dynamic_cast<AliTRDrecoTask*>(otask);\n task->SetDebugLevel(debug);\n AliLog::SetClassDebugLevel(otask->IsA()->GetName(), debug);\n task->SetMCdata(mc);\n task->SetFriends(friends);\n\n \/\/if(!task->Load(Form(\"%s\/AnalysisResults.root\", gSystem->ExpandPathName(\"$PWD\")))){\n if(!task->Load(filename)){\n Error(\"makeResults.C\", Form(\"Load data container for task %s failed.\", task->GetName()));\n delete task;\n return;\n }\n\n if(!task->PostProcess()){\n Error(\"makeResults.C\", Form(\"Processing data container for task %s failed.\", task->GetName()));\n delete task;\n return;\n }\n if(summary) task->MakeSummary();\n else{\n for(Int_t ipic=0; ipic<task->GetNRefFigures(); ipic++){\n c->Clear();\n if(!task->GetRefFigure(ipic)) continue;\n c->SaveAs(Form(\"%s_Fig%02d.gif\", task->GetName(), ipic), \"gif\");\n }\n }\n delete task;\n}\n\n\/\/______________________________________________________\nvoid processESD(TNamed *otask, const Char_t *filename)\n{\n printf(\"process[%s] : %s\\n\", otask->GetName(), otask->GetTitle());\n\n AliTRDcheckESD *esd = dynamic_cast<AliTRDcheckESD*>(otask);\n if(!esd){\n Info(\"makeResults.C\", Form(\"Processing of task %s failed.\", otask->GetName()));\n delete otask;\n return;\n }\n \/\/if(!esd->Load(Form(\"%s\/AnalysisResults.root\", gSystem->ExpandPathName(\"$PWD\")), \"TRD_Performance\")){\n if(!esd->Load(filename, \"TRD_Performance\")){\n Error(\"makeResults.C\", Form(\"Load data container for task %s failed.\", esd->GetName()));\n delete esd;\n return;\n }\n esd->Terminate(NULL);\n \n if(summary) esd->MakeSummary();\n else{\n for(Int_t ipic(0); ipic<esd->GetNRefFigures(); ipic++){\n c->Clear(); \n if(!esd->GetRefFigure(ipic)) continue;\n c->SaveAs(Form(\"%s_Fig%02d.gif\", esd->GetName(), ipic));\n }\n }\n delete esd;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Usage:\n\/\/ makeResults.C(\"tasks\", \"file_list\", \"\"task_id, kGRID)\n\/\/ tasks : \"ALL\" or one\/more of the following separated by space:\n\/\/ \"EFF\" : TRD Tracking Efficiency \n\/\/ \"EFFC\" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations\n\/\/ \"RES\" : TRD tracking Resolution\n\/\/ \"PID\" : TRD PID - pion efficiency \n\/\/ \"DET\" : Basic TRD Detector checks\n\/\/ \"NOFR\" : Data set does not have AliESDfriends.root \n\/\/ \"NOMC\" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely\n\/\/ on MC information are switched off\n\/\/ file_list : is the list of the files to be processed. \n\/\/ They should contain the full path. Here is an example:\n\/\/ \/lustre\/alice\/local\/TRDdata\/SIM\/P-Flat\/TRUNK\/RUN0\/TRD.Performance.root\n\/\/ or for GRID alien:\/\/\/alice\/cern.ch\/user\/m\/mfasel\/MinBiasProd\/results\/ppMinBias80000\/1\/TRD.Performance.root\n\/\/ task_id : identifier of task speciality as defined by the AddMacro.C. \n\/\/ (e.g. AddTRDresolution.C defines \"\" for barrel tracks, \"K\" for kink tracks and \"SA\" for stand alone tracks)\n\/\/ kGRID : specify if files are comming from a GRID collection [default kFALSE]\n\/\/\n\/\/ HOW TO BUILD THE FILE LIST\n\/\/ 1. locally\n\/\/ ls -1 BaseDir\/RUN*\/TRD.Performance.root > files.lst\n\/\/ \n\/\/ 2. on Grid\n\/\/ char *BaseDir=\"\/alice\/cern.ch\/user\/m\/mfasel\/MinBiasProd\/results\/ppMinBias80000\/\";\n\/\/ TGrid::Connect(\"alien:\/\/\");\n\/\/ TGridResult *res = gGrid->Query(BaseDir, \"%\/TRD.Performance.root\");\n\/\/ TGridCollection *col = gGrid->OpenCollectionQuery(res);\n\/\/ col->Reset();\n\/\/ TMap *map = 0x0;\n\/\/ while(map = (TMap*)col->Next()){\n\/\/ TIter it((TCollection*)map);\n\/\/ TObjString *info = 0x0;\n\/\/ while(info=(TObjString*)it()){\n\/\/ printf(\"alien:\/\/%s\\n\", col->GetLFN(info->GetString().Data()));\n\/\/ }\n\/\/ }\n\/\/\n\/\/ The files which will be processed are the intersection between the\n\/\/ condition on the tasks and the files in the file list.\n\/\/\n\/\/ Authors:\n\/\/ Alex Bercuci (A.Bercuci@gsi.de) \n\/\/ Markus Fasel (m.Fasel@gsi.de) \n\/\/\n\n#if ! defined (__CINT__) || defined (__MAKECINT__)\n#include <fstream>\n#include \"TError.h\"\n#include <TClass.h>\n#include <TCanvas.h>\n#include <TH1.h>\n#include <TGraph.h>\n#include <TObjArray.h>\n#include <TObjString.h>\n#include <TString.h>\n#include <TROOT.h>\n#include <TStyle.h>\n#include <TGrid.h>\n#include <TGridResult.h>\n#include <TGridCollection.h>\n\n#include \"AliLog.h\"\n\n#include \"PWG1\/TRD\/AliTRDrecoTask.h\"\n#include \"PWG1\/TRD\/AliTRDcheckESD.h\"\n\n#endif\n\n#include \"AliTRDperformanceTrain.h\"\n#include \"helper.C\"\n\/\/#include \"..\/..\/PWG1\/macros\/AddPerformanceTask.h\"\n\nChar_t *libs[] = {\"libProofPlayer.so\", \"libANALYSIS.so\", \"libANALYSISalice.so\", \"libTENDER.so\", \"libPWG1.so\"};\n\/\/ define setup\nTCanvas *c = 0x0;\nBool_t mc(kFALSE), friends(kFALSE);\nBool_t summary(kTRUE);\n\nvoid processTRD(TNamed* task, const Char_t *filename);\nvoid processESD(TNamed* task, const Char_t *filename);\nvoid makeResults(Char_t *opt = \"ALL\", const Char_t *files=\"QAResults.root\", Char_t *cid = \"\", Bool_t kGRID=kFALSE, Bool_t dosummary = kTRUE)\n{\n if(kGRID){\n if(!gSystem->Getenv(\"GSHELL_ROOT\")){\n Error(\"makeResults.C\", \"AliEn not initialized.\");\n return;\n }\n TGrid::Connect(\"alien:\/\/\");\n }\n\n\t\/\/ Load Libraries in interactive mode\n Int_t nlibs = static_cast<Int_t>(sizeof(libs)\/sizeof(Char_t *));\n for(Int_t ilib=0; ilib<nlibs; ilib++){\n if(gSystem->Load(libs[ilib]) >= 0) continue;\n Error(\"makeResults.C\", Form(\"Failed to load %s.\", libs[ilib]));\n return;\n }\n\n mc = HasReadMCData(opt);\n friends = HasReadFriendData(opt);\n\n gStyle->SetOptStat(0);\n gStyle->SetOptFit(0);\n TString outputFile;\n if(!TString(files).EndsWith(\".root\")){ \n outputFile = Form(\"%s\/QAResults.root\", gSystem->ExpandPathName(\"$PWD\"));\n mergeProd(\"QAResults.root\", files);\n } else {\n outputFile = files;\n }\n Int_t fSteerTask = ParseOptions(opt);\n\n if(!dosummary){\n summary = kFLASE;\n if(!c) c=new TCanvas(\"c\", \"Performance\", 10, 10, 800, 500);\n }\n\n TClass *ctask = new TClass;\n AliAnalysisTask *task = 0x0;\n for(Int_t itask = NTRDQATASKS; itask--;){\n if(!TSTBIT(fSteerTask, itask)) continue;\n new(ctask) TClass(fgkTRDtaskClassName[itask]);\n task = (AliAnalysisTask*)ctask->New();\n task->SetName(Form(\"%s%s\", task->GetName(), cid));\n printf(\"task %s, output file %s\\n\", task->GetName(), outputFile.Data());\n if(task->IsA()->InheritsFrom(\"AliTRDrecoTask\")) processTRD(task, outputFile.Data());\n else processESD(task, outputFile.Data());\n }\n delete ctask;\n delete c;\n}\n\n\n\/\/______________________________________________________\nvoid processTRD(TNamed *otask, const Char_t *filename)\n{\n printf(\"process[%s] : %s\\n\", otask->GetName(), otask->GetTitle());\n Int_t debug(0);\n AliTRDrecoTask *task = dynamic_cast<AliTRDrecoTask*>(otask);\n task->SetDebugLevel(debug);\n AliLog::SetClassDebugLevel(otask->IsA()->GetName(), debug);\n task->SetMCdata(mc);\n task->SetFriends(friends);\n\n \/\/if(!task->Load(Form(\"%s\/AnalysisResults.root\", gSystem->ExpandPathName(\"$PWD\")))){\n if(!task->Load(filename)){\n Error(\"makeResults.C\", Form(\"Load data container for task %s failed.\", task->GetName()));\n delete task;\n return;\n }\n\n if(!task->PostProcess()){\n Error(\"makeResults.C\", Form(\"Processing data container for task %s failed.\", task->GetName()));\n delete task;\n return;\n }\n if(summary) task->MakeSummary();\n else{\n for(Int_t ipic=0; ipic<task->GetNRefFigures(); ipic++){\n c->Clear();\n if(!task->GetRefFigure(ipic)) continue;\n c->SaveAs(Form(\"%s_Fig%02d.gif\", task->GetName(), ipic), \"gif\");\n }\n }\n delete task;\n}\n\n\/\/______________________________________________________\nvoid processESD(TNamed *otask, const Char_t *filename)\n{\n printf(\"process[%s] : %s\\n\", otask->GetName(), otask->GetTitle());\n\n AliTRDcheckESD *esd = dynamic_cast<AliTRDcheckESD*>(otask);\n if(!esd){\n Info(\"makeResults.C\", Form(\"Processing of task %s failed.\", otask->GetName()));\n delete otask;\n return;\n }\n \/\/if(!esd->Load(Form(\"%s\/AnalysisResults.root\", gSystem->ExpandPathName(\"$PWD\")), \"TRD_Performance\")){\n if(!esd->Load(filename, \"TRD_Performance\")){\n Error(\"makeResults.C\", Form(\"Load data container for task %s failed.\", esd->GetName()));\n delete esd;\n return;\n }\n esd->Terminate(NULL);\n \n if(summary) esd->MakeSummary();\n else{\n for(Int_t ipic(0); ipic<esd->GetNRefFigures(); ipic++){\n c->Clear(); \n if(!esd->GetRefFigure(ipic)) continue;\n c->SaveAs(Form(\"%s_Fig%02d.gif\", esd->GetName(), ipic));\n }\n }\n delete esd;\n}\n<commit_msg>fix typo<commit_after>\/\/ Usage:\n\/\/ makeResults.C(\"tasks\", \"file_list\", \"\"task_id, kGRID)\n\/\/ tasks : \"ALL\" or one\/more of the following separated by space:\n\/\/ \"EFF\" : TRD Tracking Efficiency \n\/\/ \"EFFC\" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations\n\/\/ \"RES\" : TRD tracking Resolution\n\/\/ \"PID\" : TRD PID - pion efficiency \n\/\/ \"DET\" : Basic TRD Detector checks\n\/\/ \"NOFR\" : Data set does not have AliESDfriends.root \n\/\/ \"NOMC\" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely\n\/\/ on MC information are switched off\n\/\/ file_list : is the list of the files to be processed. \n\/\/ They should contain the full path. Here is an example:\n\/\/ \/lustre\/alice\/local\/TRDdata\/SIM\/P-Flat\/TRUNK\/RUN0\/TRD.Performance.root\n\/\/ or for GRID alien:\/\/\/alice\/cern.ch\/user\/m\/mfasel\/MinBiasProd\/results\/ppMinBias80000\/1\/TRD.Performance.root\n\/\/ task_id : identifier of task speciality as defined by the AddMacro.C. \n\/\/ (e.g. AddTRDresolution.C defines \"\" for barrel tracks, \"K\" for kink tracks and \"SA\" for stand alone tracks)\n\/\/ kGRID : specify if files are comming from a GRID collection [default kFALSE]\n\/\/\n\/\/ HOW TO BUILD THE FILE LIST\n\/\/ 1. locally\n\/\/ ls -1 BaseDir\/RUN*\/TRD.Performance.root > files.lst\n\/\/ \n\/\/ 2. on Grid\n\/\/ char *BaseDir=\"\/alice\/cern.ch\/user\/m\/mfasel\/MinBiasProd\/results\/ppMinBias80000\/\";\n\/\/ TGrid::Connect(\"alien:\/\/\");\n\/\/ TGridResult *res = gGrid->Query(BaseDir, \"%\/TRD.Performance.root\");\n\/\/ TGridCollection *col = gGrid->OpenCollectionQuery(res);\n\/\/ col->Reset();\n\/\/ TMap *map = 0x0;\n\/\/ while(map = (TMap*)col->Next()){\n\/\/ TIter it((TCollection*)map);\n\/\/ TObjString *info = 0x0;\n\/\/ while(info=(TObjString*)it()){\n\/\/ printf(\"alien:\/\/%s\\n\", col->GetLFN(info->GetString().Data()));\n\/\/ }\n\/\/ }\n\/\/\n\/\/ The files which will be processed are the intersection between the\n\/\/ condition on the tasks and the files in the file list.\n\/\/\n\/\/ Authors:\n\/\/ Alex Bercuci (A.Bercuci@gsi.de) \n\/\/ Markus Fasel (m.Fasel@gsi.de) \n\/\/\n\n#if ! defined (__CINT__) || defined (__MAKECINT__)\n#include <fstream>\n#include \"TError.h\"\n#include <TClass.h>\n#include <TCanvas.h>\n#include <TH1.h>\n#include <TGraph.h>\n#include <TObjArray.h>\n#include <TObjString.h>\n#include <TString.h>\n#include <TROOT.h>\n#include <TStyle.h>\n#include <TGrid.h>\n#include <TGridResult.h>\n#include <TGridCollection.h>\n\n#include \"AliLog.h\"\n\n#include \"PWG1\/TRD\/AliTRDrecoTask.h\"\n#include \"PWG1\/TRD\/AliTRDcheckESD.h\"\n\n#endif\n\n#include \"AliTRDperformanceTrain.h\"\n#include \"helper.C\"\n\/\/#include \"..\/..\/PWG1\/macros\/AddPerformanceTask.h\"\n\nChar_t *libs[] = {\"libProofPlayer.so\", \"libANALYSIS.so\", \"libANALYSISalice.so\", \"libTENDER.so\", \"libPWG1.so\"};\n\/\/ define setup\nTCanvas *c = 0x0;\nBool_t mc(kFALSE), friends(kFALSE);\nBool_t summary(kTRUE);\n\nvoid processTRD(TNamed* task, const Char_t *filename);\nvoid processESD(TNamed* task, const Char_t *filename);\nvoid makeResults(Char_t *opt = \"ALL\", const Char_t *files=\"QAResults.root\", Char_t *cid = \"\", Bool_t kGRID=kFALSE, Bool_t dosummary = kTRUE)\n{\n if(kGRID){\n if(!gSystem->Getenv(\"GSHELL_ROOT\")){\n Error(\"makeResults.C\", \"AliEn not initialized.\");\n return;\n }\n TGrid::Connect(\"alien:\/\/\");\n }\n\n\t\/\/ Load Libraries in interactive mode\n Int_t nlibs = static_cast<Int_t>(sizeof(libs)\/sizeof(Char_t *));\n for(Int_t ilib=0; ilib<nlibs; ilib++){\n if(gSystem->Load(libs[ilib]) >= 0) continue;\n Error(\"makeResults.C\", Form(\"Failed to load %s.\", libs[ilib]));\n return;\n }\n\n mc = HasReadMCData(opt);\n friends = HasReadFriendData(opt);\n\n gStyle->SetOptStat(0);\n gStyle->SetOptFit(0);\n TString outputFile;\n if(!TString(files).EndsWith(\".root\")){ \n outputFile = Form(\"%s\/QAResults.root\", gSystem->ExpandPathName(\"$PWD\"));\n mergeProd(\"QAResults.root\", files);\n } else {\n outputFile = files;\n }\n Int_t fSteerTask = ParseOptions(opt);\n\n if(!dosummary){\n summary = kFALSE;\n if(!c) c=new TCanvas(\"c\", \"Performance\", 10, 10, 800, 500);\n }\n\n TClass *ctask = new TClass;\n AliAnalysisTask *task = 0x0;\n for(Int_t itask = NTRDQATASKS; itask--;){\n if(!TSTBIT(fSteerTask, itask)) continue;\n new(ctask) TClass(fgkTRDtaskClassName[itask]);\n task = (AliAnalysisTask*)ctask->New();\n task->SetName(Form(\"%s%s\", task->GetName(), cid));\n printf(\"task %s, output file %s\\n\", task->GetName(), outputFile.Data());\n if(task->IsA()->InheritsFrom(\"AliTRDrecoTask\")) processTRD(task, outputFile.Data());\n else processESD(task, outputFile.Data());\n }\n delete ctask;\n delete c;\n}\n\n\n\/\/______________________________________________________\nvoid processTRD(TNamed *otask, const Char_t *filename)\n{\n printf(\"process[%s] : %s\\n\", otask->GetName(), otask->GetTitle());\n Int_t debug(0);\n AliTRDrecoTask *task = dynamic_cast<AliTRDrecoTask*>(otask);\n task->SetDebugLevel(debug);\n AliLog::SetClassDebugLevel(otask->IsA()->GetName(), debug);\n task->SetMCdata(mc);\n task->SetFriends(friends);\n\n \/\/if(!task->Load(Form(\"%s\/AnalysisResults.root\", gSystem->ExpandPathName(\"$PWD\")))){\n if(!task->Load(filename)){\n Error(\"makeResults.C\", Form(\"Load data container for task %s failed.\", task->GetName()));\n delete task;\n return;\n }\n\n if(!task->PostProcess()){\n Error(\"makeResults.C\", Form(\"Processing data container for task %s failed.\", task->GetName()));\n delete task;\n return;\n }\n if(summary) task->MakeSummary();\n else{\n for(Int_t ipic=0; ipic<task->GetNRefFigures(); ipic++){\n c->Clear();\n if(!task->GetRefFigure(ipic)) continue;\n c->SaveAs(Form(\"%s_Fig%02d.gif\", task->GetName(), ipic), \"gif\");\n }\n }\n delete task;\n}\n\n\/\/______________________________________________________\nvoid processESD(TNamed *otask, const Char_t *filename)\n{\n printf(\"process[%s] : %s\\n\", otask->GetName(), otask->GetTitle());\n\n AliTRDcheckESD *esd = dynamic_cast<AliTRDcheckESD*>(otask);\n if(!esd){\n Info(\"makeResults.C\", Form(\"Processing of task %s failed.\", otask->GetName()));\n delete otask;\n return;\n }\n \/\/if(!esd->Load(Form(\"%s\/AnalysisResults.root\", gSystem->ExpandPathName(\"$PWD\")), \"TRD_Performance\")){\n if(!esd->Load(filename, \"TRD_Performance\")){\n Error(\"makeResults.C\", Form(\"Load data container for task %s failed.\", esd->GetName()));\n delete esd;\n return;\n }\n esd->Terminate(NULL);\n \n if(summary) esd->MakeSummary();\n else{\n for(Int_t ipic(0); ipic<esd->GetNRefFigures(); ipic++){\n c->Clear(); \n if(!esd->GetRefFigure(ipic)) continue;\n c->SaveAs(Form(\"%s_Fig%02d.gif\", esd->GetName(), ipic));\n }\n }\n delete esd;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ClientHandler.cpp\n\/\/ ProxyServer\n\/\/\n\/\/ Created by Hanzhou Shi on 12\/16\/15.\n\/\/ Copyright © 2015 USF. All rights reserved.\n\/\/\n\n#include \"ClientHandler.hpp\"\n#include \"Utils.hpp\"\n\n#include <sstream>\n\n#include <sys\/types.h>\n#include <sys\/uio.h>\n#include <unistd.h>\n#include <assert.h>\n\nClientHandler::ClientHandler(const std::string &host, unsigned short port)\n: host(host), port(port), dataLen(0), dispatched(false)\n{\n resetBuffer();\n}\n\nClientHandler::~ClientHandler() {\n}\n\nstd::string ClientHandler::dump() {\n return host + \":\" + std::to_string(port);\n}\n\nvoid ClientHandler::processRequest(int fd) {\n \/\/\/ don't reset buffer here, since we could\n \/\/\/ get partial header.\n if (fillReadBuffer(fd) < 0) return;\n \n \/\/\/ get header from current buffer.\n size_t usedDataLen = getLines(buffer, dataLen, lines);\n size_t remainDataLen = dataLen - usedDataLen;\n \/\/\/ update buffer\n if (usedDataLen < MAX_BUFFER_LEN) {\n \/\/\/ move unused data to beginning.\n memmove(buffer, buffer+usedDataLen, remainDataLen);\n }\n memset(buffer+remainDataLen, 0, MAX_BUFFER_LEN-remainDataLen);\n}\n\nint ClientHandler::fillReadBuffer(int fd) {\n char *bufferStart = ((char *)buffer) + dataLen;\n ssize_t ret = read(fd, bufferStart, MAX_BUFFER_LEN - dataLen);\n if (ret >= 0) dataLen += ret;\n return (int)ret;\n}\n\n\/\/\/ launch a thread to communicate with upstream and\n\/\/\/ forward response to the client using fd.\nvoid ClientHandler::requestUpstreamAndForward(int fd) {\n \/\/\/ process command.\n std::string cmd = lines.front();\n std::vector<std::string> parts = getPartsFromCmd(cmd);\n if (!parts[2].compare(\"HTTP\/1.1\")) parts[2] = \"HTTP\/1.0\";\n cmd = parts[0] + \" \" + parts[1] + \" \" + parts[2];\n \n std::string host = getHostFromUrl(parts[1]);\n int upstream = connectToHost(host);\n if (upstream < 0) {\n std::cerr\n << \"connect to upstream failed.. \"\n << strerror(errno)\n << std::endl;\n return;\n }\n LSS headers = getHeaderList();\n \n std::string request = writeHeader(headers, cmd);\n \n process(request, upstream, fd);\n close(upstream);\n}\n\nbool ClientHandler::canDispatch() {\n return lines.size() > 0 && lines.back().size() == 0 && !dispatched;\n}\n\nvoid ClientHandler::setDispatched(bool status) {\n dispatched = status;\n}\n\nvoid *ClientHandler::run(void *args) {\n ClientHandlerArgs *runArgs = (ClientHandlerArgs *)args;\n ClientHandler *client = runArgs->clientHandler;\n client->requestUpstreamAndForward(runArgs->fd);\n delete runArgs;\n return NULL;\n}\n\nLSS ClientHandler::getHeaderList() {\n \/\/\/ split lines into pairs, and strip \"User-Agent\" and\n \/\/\/ \"referer\" browser headers.\n LSS headers;\n for (int i = 1; i < lines.size()-1; ++i) {\n PSS p = pairByColon(lines[i]);\n const std::string &name = p.first;\n const std::string &value = p.second;\n if (!name.compare(\"REFERER\") || !name.compare(\"USER-AGENT\") ||\n !value.compare(\"Keep-Alive\"))\n continue;\n headers.push_back(p);\n }\n lines.clear();\n return headers;\n}\n\nstd::string ClientHandler::writeHeader(const LSS &headers,\n const std::string &cmd) {\n std::string header = cmd + \"\\r\\n\";\n for (auto p : headers) header += p.first + \": \" + p.second + \"\\r\\n\";\n header += \"\\r\\n\"; \/\/\/ an extra CRLF for termination\n return header;\n}\n\nvoid ClientHandler::process(const std::string &req, int us, int ds) {\n debug(\"request: \");\n debug(req);\n debug(\"request ended.\");\n \n ssize_t ret = flushBuffer(req.c_str(), req.size(), us);\n if (ret < 0) return;\n \n getResponseAndForward(us, ds);\n}\n\nvoid ClientHandler::getResponseAndForward(int us, int ds) {\n lines.clear();\n resetBuffer();\n \n \/\/\/ process response header first.\n size_t usedDataLen;\n while (fillReadBuffer(us) > 0) {\n usedDataLen = getLines(buffer, dataLen, lines);\n dataLen -= usedDataLen;\n leftShiftData(usedDataLen, dataLen);\n if (lines.size() > 0 && lines.back().size() == 0) break;\n }\n forwardResponseHeader(ds);\n \n \/\/\/ forward all data.\n size_t total = 0;\n while (fillReadBuffer(us) > 0) {\n total += dataLen;\n if (flushBuffer(buffer, dataLen, ds) <0) break;\n resetBuffer();\n }\n}\n\nvoid ClientHandler::forwardResponseHeader(int fd) {\n std::string cmd = lines.front();\n std::vector<std::string> parts = getPartsFromCmd(cmd);\n if (!parts[0].compare(\"HTTP\/1.1\")) parts[0] = \"HTTP\/1.0\";\n cmd = parts[0] + \" \" + parts[1] + \" \" + parts[2];\n \n LSS headers = getHeaderList();\n std::string header = writeHeader(headers, cmd);\n debug(\"response: \");\n debug(header);\n debug(\"response ended.\");\n\n flushBuffer(header.c_str(), header.size(), fd);\n}\n\nvoid ClientHandler::resetBuffer() {\n memset(buffer, 0, MAX_BUFFER_LEN);\n dataLen = 0;\n}\n\nvoid ClientHandler::leftShiftData(size_t lo, size_t len) {\n memmove(buffer, buffer + lo, len);\n memset(buffer+len, 0, MAX_BUFFER_LEN-len);\n dataLen = len;\n}\n\nint ClientHandler::flushBuffer(const char *buffer, ssize_t len, int fd) {\n debug(\">>> flushing to fd: \" + std::to_string(fd) + \" <<<\");\n ssize_t ret;\n ssize_t consumedLen = 0;\n while (consumedLen < len) {\n ret = write(fd, buffer + consumedLen, len - consumedLen);\n if (ret < 0) {\n error(\"flush buffer error.\");\n return -1;\n }\n consumedLen += ret;\n }\n assert(len == consumedLen);\n return 0;\n}\n<commit_msg>Get rid of useless output.<commit_after>\/\/\n\/\/ ClientHandler.cpp\n\/\/ ProxyServer\n\/\/\n\/\/ Created by Hanzhou Shi on 12\/16\/15.\n\/\/ Copyright © 2015 USF. All rights reserved.\n\/\/\n\n#include \"ClientHandler.hpp\"\n#include \"Utils.hpp\"\n\n#include <sstream>\n\n#include <sys\/types.h>\n#include <sys\/uio.h>\n#include <unistd.h>\n#include <assert.h>\n\nClientHandler::ClientHandler(const std::string &host, unsigned short port)\n: host(host), port(port), dataLen(0), dispatched(false)\n{\n resetBuffer();\n}\n\nClientHandler::~ClientHandler() {\n}\n\nstd::string ClientHandler::dump() {\n return host + \":\" + std::to_string(port);\n}\n\nvoid ClientHandler::processRequest(int fd) {\n \/\/\/ don't reset buffer here, since we could\n \/\/\/ get partial header.\n if (fillReadBuffer(fd) < 0) return;\n \n \/\/\/ get header from current buffer.\n size_t usedDataLen = getLines(buffer, dataLen, lines);\n size_t remainDataLen = dataLen - usedDataLen;\n \/\/\/ update buffer\n if (usedDataLen < MAX_BUFFER_LEN) {\n \/\/\/ move unused data to beginning.\n memmove(buffer, buffer+usedDataLen, remainDataLen);\n }\n memset(buffer+remainDataLen, 0, MAX_BUFFER_LEN-remainDataLen);\n}\n\nint ClientHandler::fillReadBuffer(int fd) {\n char *bufferStart = ((char *)buffer) + dataLen;\n ssize_t ret = read(fd, bufferStart, MAX_BUFFER_LEN - dataLen);\n if (ret >= 0) dataLen += ret;\n return (int)ret;\n}\n\n\/\/\/ launch a thread to communicate with upstream and\n\/\/\/ forward response to the client using fd.\nvoid ClientHandler::requestUpstreamAndForward(int fd) {\n \/\/\/ process command.\n std::string cmd = lines.front();\n std::vector<std::string> parts = getPartsFromCmd(cmd);\n if (!parts[2].compare(\"HTTP\/1.1\")) parts[2] = \"HTTP\/1.0\";\n cmd = parts[0] + \" \" + parts[1] + \" \" + parts[2];\n \n std::string host = getHostFromUrl(parts[1]);\n int upstream = connectToHost(host);\n if (upstream < 0) {\n std::cerr\n << \"connect to upstream failed.. \"\n << strerror(errno)\n << std::endl;\n return;\n }\n LSS headers = getHeaderList();\n \n std::string request = writeHeader(headers, cmd);\n \n process(request, upstream, fd);\n close(upstream);\n}\n\nbool ClientHandler::canDispatch() {\n return lines.size() > 0 && lines.back().size() == 0 && !dispatched;\n}\n\nvoid ClientHandler::setDispatched(bool status) {\n dispatched = status;\n}\n\nvoid *ClientHandler::run(void *args) {\n ClientHandlerArgs *runArgs = (ClientHandlerArgs *)args;\n ClientHandler *client = runArgs->clientHandler;\n client->requestUpstreamAndForward(runArgs->fd);\n delete runArgs;\n return NULL;\n}\n\nLSS ClientHandler::getHeaderList() {\n \/\/\/ split lines into pairs, and strip \"User-Agent\" and\n \/\/\/ \"referer\" browser headers.\n LSS headers;\n for (int i = 1; i < lines.size()-1; ++i) {\n PSS p = pairByColon(lines[i]);\n const std::string &name = p.first;\n const std::string &value = p.second;\n if (!name.compare(\"REFERER\") || !name.compare(\"USER-AGENT\") ||\n !value.compare(\"Keep-Alive\"))\n continue;\n headers.push_back(p);\n }\n lines.clear();\n return headers;\n}\n\nstd::string ClientHandler::writeHeader(const LSS &headers,\n const std::string &cmd) {\n std::string header = cmd + \"\\r\\n\";\n for (auto p : headers) header += p.first + \": \" + p.second + \"\\r\\n\";\n header += \"\\r\\n\"; \/\/\/ an extra CRLF for termination\n return header;\n}\n\nvoid ClientHandler::process(const std::string &req, int us, int ds) {\n debug(\"request: \");\n debug(req);\n debug(\"request ended.\");\n \n ssize_t ret = flushBuffer(req.c_str(), req.size(), us);\n if (ret < 0) return;\n \n getResponseAndForward(us, ds);\n}\n\nvoid ClientHandler::getResponseAndForward(int us, int ds) {\n lines.clear();\n resetBuffer();\n \n \/\/\/ process response header first.\n size_t usedDataLen;\n while (fillReadBuffer(us) > 0) {\n usedDataLen = getLines(buffer, dataLen, lines);\n dataLen -= usedDataLen;\n leftShiftData(usedDataLen, dataLen);\n if (lines.size() > 0 && lines.back().size() == 0) break;\n }\n forwardResponseHeader(ds);\n \n \/\/\/ forward all data.\n size_t total = 0;\n while (fillReadBuffer(us) > 0) {\n total += dataLen;\n if (flushBuffer(buffer, dataLen, ds) <0) break;\n resetBuffer();\n }\n}\n\nvoid ClientHandler::forwardResponseHeader(int fd) {\n std::string cmd = lines.front();\n std::vector<std::string> parts = getPartsFromCmd(cmd);\n if (!parts[0].compare(\"HTTP\/1.1\")) parts[0] = \"HTTP\/1.0\";\n cmd = parts[0] + \" \" + parts[1] + \" \" + parts[2];\n \n LSS headers = getHeaderList();\n std::string header = writeHeader(headers, cmd);\n debug(\"response: \");\n debug(header);\n debug(\"response ended.\");\n\n flushBuffer(header.c_str(), header.size(), fd);\n}\n\nvoid ClientHandler::resetBuffer() {\n memset(buffer, 0, MAX_BUFFER_LEN);\n dataLen = 0;\n}\n\nvoid ClientHandler::leftShiftData(size_t lo, size_t len) {\n memmove(buffer, buffer + lo, len);\n memset(buffer+len, 0, MAX_BUFFER_LEN-len);\n dataLen = len;\n}\n\nint ClientHandler::flushBuffer(const char *buffer, ssize_t len, int fd) {\n ssize_t ret;\n ssize_t consumedLen = 0;\n while (consumedLen < len) {\n ret = write(fd, buffer + consumedLen, len - consumedLen);\n if (ret < 0) {\n error(\"flush buffer error.\");\n return -1;\n }\n consumedLen += ret;\n }\n assert(len == consumedLen);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * PrimeSieveProcess.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2012 Kim Walisch, <kim.walisch@gmail.com>\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, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n#include \"PrimeSieveProcess.hpp\"\n#include <primesieve\/ParallelPrimeSieve.hpp>\n\n#include <QtGlobal>\n#include <QStringList>\n#include <QCoreApplication>\n#include <stdexcept>\n\n#if defined(Q_OS_WIN)\n #include <windows.h>\n#else\n #include <unistd.h>\n#endif\n\nPrimeSieveProcess::PrimeSieveProcess(QObject* parent) :\n QProcess(parent) {\n sharedMemory_.setParent(parent);\n sharedMemory_.setKey(QString::number(this->getProcessId()));\n}\n\nPrimeSieveProcess::~PrimeSieveProcess() {\n \/\/ disconnect all signals, must be used to avoid zombie processes\n this->disconnect();\n \/\/ kill() and terminate() = trouble, close() works fine\n this->close();\n sharedMemory_.detach();\n}\n\n\/**\n * Get the process ID of the current process. I tried to use\n * QProcess::pid() but got a lot of trouble on Windows and Mac OS X,\n * also it is not portable.\n *\/\nint PrimeSieveProcess::getProcessId() {\n#if defined(Q_OS_WIN)\n return static_cast<int>(GetCurrentProcessId());\n#else\n return static_cast<int>(getpid());\n#endif\n}\n\n\/**\n * Create a shared memory segement for communication with the\n * ParallelPrimeSieve process.\n *\/\nvoid PrimeSieveProcess::createSharedMemory() {\n \/\/ attach the shared memory\n if (!sharedMemory_.isAttached() &&\n !sharedMemory_.create(sizeof(shm_))) {\n throw std::runtime_error(\n \"Interprocess communication error, could not allocate shared memory.\");\n }\n \/\/ map the attached shared memory to the shm_ segment\n shm_ = static_cast<primesieve::ParallelPrimeSieve::SharedMemory*>(sharedMemory_.data());\n}\n\n\/**\n * Start a new ParallelPrimeSieve process that sieves\n * the primes within [start, stop].\n *\/\nvoid PrimeSieveProcess::start(quint64 start, quint64 stop,\n int sieveSize, int flags, int threads) {\n this->createSharedMemory();\n \/\/ initialize the shared memory segment\n shm_->start = start;\n shm_->stop = stop;\n shm_->sieveSize = sieveSize;\n shm_->flags = flags;\n shm_->threads = threads;\n shm_->status = 0.0;\n shm_->seconds = 0.0;\n for (int i = 0; i < 6; i++)\n shm_->counts[i] = 0;\n \/\/ path + file name of the aplication\n QString path = QCoreApplication::applicationFilePath();\n \/\/ process arguments, see main.cpp\n QStringList args;\n args << \"PrimeSieveProcess\" << sharedMemory_.key();\n \/\/\/ start a new ParallelPrimeSieve process\n \/\/\/ @see main.cpp\n QProcess::start(path, args, QIODevice::ReadOnly);\n}\n\nbool PrimeSieveProcess::isFinished() {\n return (static_cast<int>(shm_->status) == 100);\n}\n\n\/**\n * @return The count of primes\/k-tuplets within [start, stop].\n * @pre index < 6\n *\/\nquint64 PrimeSieveProcess::getCount(unsigned int index) const {\n return shm_->counts[index];\n}\n\n\/**\n * @return The sieving status in percent.\n *\/\ndouble PrimeSieveProcess::getStatus() const {\n return shm_->status;\n}\n\n\/**\n * @return The time elapsed in seconds (if sieving is finished).\n *\/\ndouble PrimeSieveProcess::getSeconds() const {\n return shm_->seconds;\n}\n<commit_msg>Fix comment<commit_after>\/*\n * PrimeSieveProcess.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2012 Kim Walisch, <kim.walisch@gmail.com>\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, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n#include \"PrimeSieveProcess.hpp\"\n#include <primesieve\/ParallelPrimeSieve.hpp>\n\n#include <QtGlobal>\n#include <QStringList>\n#include <QCoreApplication>\n#include <stdexcept>\n\n#if defined(Q_OS_WIN)\n #include <windows.h>\n#else\n #include <unistd.h>\n#endif\n\nPrimeSieveProcess::PrimeSieveProcess(QObject* parent) :\n QProcess(parent) {\n sharedMemory_.setParent(parent);\n sharedMemory_.setKey(QString::number(this->getProcessId()));\n}\n\nPrimeSieveProcess::~PrimeSieveProcess() {\n \/\/ disconnect all signals, must be used to avoid zombie processes\n this->disconnect();\n \/\/ kill() and terminate() = trouble, close() works fine\n this->close();\n sharedMemory_.detach();\n}\n\n\/**\n * Get the process ID of the current process. I tried to use\n * QProcess::pid() but got a lot of trouble on Windows and Mac OS X,\n * also it is not portable.\n *\/\nint PrimeSieveProcess::getProcessId() {\n#if defined(Q_OS_WIN)\n return static_cast<int>(GetCurrentProcessId());\n#else\n return static_cast<int>(getpid());\n#endif\n}\n\n\/**\n * Create a shared memory segment for communication with the\n * ParallelPrimeSieve process.\n *\/\nvoid PrimeSieveProcess::createSharedMemory() {\n \/\/ attach the shared memory\n if (!sharedMemory_.isAttached() &&\n !sharedMemory_.create(sizeof(shm_))) {\n throw std::runtime_error(\n \"Interprocess communication error, could not allocate shared memory.\");\n }\n \/\/ map the attached shared memory to the shm_ segment\n shm_ = static_cast<primesieve::ParallelPrimeSieve::SharedMemory*>(sharedMemory_.data());\n}\n\n\/**\n * Start a new ParallelPrimeSieve process that sieves\n * the primes within [start, stop].\n *\/\nvoid PrimeSieveProcess::start(quint64 start, quint64 stop,\n int sieveSize, int flags, int threads) {\n this->createSharedMemory();\n \/\/ initialize the shared memory segment\n shm_->start = start;\n shm_->stop = stop;\n shm_->sieveSize = sieveSize;\n shm_->flags = flags;\n shm_->threads = threads;\n shm_->status = 0.0;\n shm_->seconds = 0.0;\n for (int i = 0; i < 6; i++)\n shm_->counts[i] = 0;\n \/\/ path + file name of the aplication\n QString path = QCoreApplication::applicationFilePath();\n \/\/ process arguments, see main.cpp\n QStringList args;\n args << \"PrimeSieveProcess\" << sharedMemory_.key();\n \/\/\/ start a new ParallelPrimeSieve process\n \/\/\/ @see main.cpp\n QProcess::start(path, args, QIODevice::ReadOnly);\n}\n\nbool PrimeSieveProcess::isFinished() {\n return (static_cast<int>(shm_->status) == 100);\n}\n\n\/**\n * @return The count of primes\/k-tuplets within [start, stop].\n * @pre index < 6\n *\/\nquint64 PrimeSieveProcess::getCount(unsigned int index) const {\n return shm_->counts[index];\n}\n\n\/**\n * @return The sieving status in percent.\n *\/\ndouble PrimeSieveProcess::getStatus() const {\n return shm_->status;\n}\n\n\/**\n * @return The time elapsed in seconds (if sieving is finished).\n *\/\ndouble PrimeSieveProcess::getSeconds() const {\n return shm_->seconds;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <SDKDDKVer.h>\n#include <windows.h>\n#include <iostream>\n#include <sstream>\n#include <chrono>\n#include <random>\n#include \"..\/src\/SQFGenerator.h\"\n#include \"..\/src\/SQFGenerator.cpp\"\n\ntypedef void (__stdcall *RVExtension_t)(char *output, int outputSize, const char *function);\n\nRVExtension_t RVExtension;\n\nvoid test()\n{\n char output[10*1024];\n const int iterations = 10000;\n const char *command = \"['pythia.ping', 'asd', 'ert', 3]\";\n\n std::cout << \"Calling \" << iterations << \" times: \" << command << std::endl;\n\n \/\/ First call to initialize everything (in case it is needed)\n RVExtension(output, sizeof(output), command);\n\n auto start = std::chrono::system_clock::now();\n for (int i = iterations; i > 0; i--)\n {\n RVExtension(output, sizeof(output), command);\n }\n auto end = std::chrono::system_clock::now();\n auto elapsed = end - start;\n\n std::cout << \"Last call output: \" << output << std::endl;\n std::cout << \"Each function time: \" << elapsed.count() \/ 10000.0 \/ (double)iterations << \"ms\" << std::endl;\n}\n\nstd::string createPingRequest(std::string sqf)\n{\n if (sqf == \"[]\")\n {\n return std::string(\"['pythia.ping']\");\n }\n else\n {\n return std::string(\"['pythia.ping', \") + (sqf.c_str()+1);\n }\n}\n\nvoid parseMultipart(const char *output, int &id, int &count)\n{\n \/\/ Poor man's parsing :)\n std::stringstream ss(output);\n std::string start;\n std::string comma;\n std::string count_s;\n\n ss >> start;\n ss >> id;\n ss >> comma;\n ss >> count_s;\n count = atoi(count_s.c_str());\n}\n\nint compareRegularResponse(const char *response, std::string &expected)\n{\n const char responseTemplate[] = \"[\\\"r\\\",\";\n const int payloadOffset = sizeof(responseTemplate) - 1;\n\n if (strncmp(response, responseTemplate, payloadOffset) == 0)\n {\n if (!strncmp(response + payloadOffset, expected.c_str(), expected.size()))\n {\n if (!strcmp(response + payloadOffset + expected.size(), \"]\"))\n {\n return 0;\n }\n }\n\n std::cout << \"Expected: \" << response << expected << \"]\" << std::endl;\n std::cout << \"Got: \" << response << std::endl;\n return 1;\n }\n\n return -1; \/\/ Not a regular response\n}\n\nstd::string handleMultipart(int id, int count)\n{\n char output[10 * 1024];\n std::string multipartRequest = std::string(\"['pythia.multipart',\") + std::to_string(id) + ']';\n std::string fullOutput;\n\n for (int i = 0; i < count; i++)\n {\n output[0] = '\\0';\n RVExtension(output, sizeof(output), multipartRequest.c_str());\n fullOutput += output;\n }\n \/\/std::cout << fullOutput << std::endl;\n return fullOutput;\n}\n\nint test_fuzzing_single()\n{\n char output[10 * 1024];\n\n const char multipartTemplate[] = \"[\\\"m\\\",\";\n const int payloadOffset = sizeof(multipartTemplate) - 1;\n\n SQFGenerator builder = SQFGenerator(0, 100);\n std::string sqf = builder.generate(2);\n std::string request = createPingRequest(sqf);\n\n RVExtension(output, sizeof(output), request.c_str());\n\n \/\/ Check for regular response\n int regularResponse = compareRegularResponse(output, sqf);\n if (regularResponse != -1)\n return regularResponse;\n\n if (strncmp(output, multipartTemplate, payloadOffset) == 0)\n {\n \/\/std::cout << output << std::endl;\n int id, count;\n parseMultipart(output, id, count);\n std::string multipartOutput = handleMultipart(id, count);\n\n int multipartResponse = compareRegularResponse(multipartOutput.c_str(), sqf);\n if (multipartResponse == 0)\n {\n \/\/std::cout << \"OK :)\" << std::endl;\n return 0;\n }\n else\n {\n std::cout << \"Got unknown response: \" << multipartOutput << std::endl;\n return 1;\n }\n }\n else\n {\n std::cout << \"Got unknown response: \" << output << std::endl;\n return 1;\n }\n}\n\nvoid test_fuzzing_multiple()\n{\n for (int i = 0; i < 10000; i++)\n {\n if (i % 10 == 0)\n std::cout << \"Test: \" << std::to_string(i) << std::endl;\n\n if (test_fuzzing_single() != 0)\n return;\n }\n std::cout << \"Tests OK!\" << std::endl;\n}\n\nvoid test_coroutines()\n{\n char output[10 * 1024];\n const int iterations = 10000;\n const char *command = \"['python.coroutines.test_coroutines']\";\n char *response = _strdup(\"['pythia.continue', , 'tralala something']\");\n char number[10];\n\n int continue_val;\n\n std::cout << \"Calling \" << iterations << \" times: \" << command << std::endl;\n\n \/\/ First call to initialize everything (in case it is needed)\n RVExtension(output, sizeof(output), command);\n\n auto start = std::chrono::system_clock::now();\n for (int i = iterations; i > 0; i--)\n {\n RVExtension(output, sizeof(output), command);\n while (output[2] == 's')\n {\n continue_val = atoi(output + 5);\n sprintf_s(number, \"%6d\", continue_val);\n for (int j = 0; j < 6; j++)\n {\n response[20 + j] = number[j];\n }\n RVExtension(output, sizeof(output), response);\n }\n }\n auto end = std::chrono::system_clock::now();\n auto elapsed = end - start;\n\n std::cout << \"Last call output: \" << output << std::endl;\n std::cout << \"Each function time: \" << elapsed.count() \/ 10000.0 \/ (double)iterations << \"ms\" << std::endl;\n}\n\n#ifdef _WIN64\n#define PYTHIA_DLL \"Pythia_x64.dll\"\n#define FUNCNAME \"RVExtension\"\n#else\n#define PYTHIA_DLL \"Pythia.dll\"\n#define FUNCNAME \"_RVExtension@12\"\n#endif\n\n\nint main()\n{\n HINSTANCE hInstLibrary = LoadLibrary(TEXT(PYTHIA_DLL));\n\n if (hInstLibrary)\n {\n RVExtension = (RVExtension_t)GetProcAddress(hInstLibrary, FUNCNAME);\n\n if (RVExtension)\n {\n test();\n }\n else\n {\n std::cout << \"Could not get RVExtension function.\" << std::endl;\n }\n FreeLibrary(hInstLibrary);\n }\n else\n {\n std::cout << \"Could not open library dll.\" << std::endl;\n }\n\n std::cout << \"Press enter to continue...\";\n std::cin.get();\n return 0;\n}\n\n<commit_msg>Count time for fuzzing<commit_after>#include <SDKDDKVer.h>\n#include <windows.h>\n#include <iostream>\n#include <sstream>\n#include <chrono>\n#include <random>\n#include \"..\/src\/SQFGenerator.h\"\n#include \"..\/src\/SQFGenerator.cpp\"\n\ntypedef void (__stdcall *RVExtension_t)(char *output, int outputSize, const char *function);\n\nRVExtension_t RVExtension;\n\nvoid test()\n{\n char output[10*1024];\n const int iterations = 10000;\n const char *command = \"['pythia.ping', 'asd', 'ert', 3]\";\n\n std::cout << \"Calling \" << iterations << \" times: \" << command << std::endl;\n\n \/\/ First call to initialize everything (in case it is needed)\n RVExtension(output, sizeof(output), command);\n\n auto start = std::chrono::system_clock::now();\n for (int i = iterations; i > 0; i--)\n {\n RVExtension(output, sizeof(output), command);\n }\n auto end = std::chrono::system_clock::now();\n auto elapsed = end - start;\n\n std::cout << \"Last call output: \" << output << std::endl;\n std::cout << \"Each function time: \" << elapsed.count() \/ 10000.0 \/ (double)iterations << \"ms\" << std::endl;\n}\n\nstd::string createPingRequest(std::string sqf)\n{\n if (sqf == \"[]\")\n {\n return std::string(\"['pythia.ping']\");\n }\n else\n {\n return std::string(\"['pythia.ping', \") + (sqf.c_str()+1);\n }\n}\n\nvoid parseMultipart(const char *output, int &id, int &count)\n{\n \/\/ Poor man's parsing :)\n std::stringstream ss(output);\n std::string start;\n std::string comma;\n std::string count_s;\n\n ss >> start;\n ss >> id;\n ss >> comma;\n ss >> count_s;\n count = atoi(count_s.c_str());\n}\n\nint compareRegularResponse(const char *response, std::string &expected)\n{\n const char responseTemplate[] = \"[\\\"r\\\",\";\n const int payloadOffset = sizeof(responseTemplate) - 1;\n\n if (strncmp(response, responseTemplate, payloadOffset) == 0)\n {\n if (!strncmp(response + payloadOffset, expected.c_str(), expected.size()))\n {\n if (!strcmp(response + payloadOffset + expected.size(), \"]\"))\n {\n return 0;\n }\n }\n\n std::cout << \"Expected: \" << response << expected << \"]\" << std::endl;\n std::cout << \"Got: \" << response << std::endl;\n return 1;\n }\n\n return -1; \/\/ Not a regular response\n}\n\nstd::string handleMultipart(int id, int count)\n{\n char output[10 * 1024];\n std::string multipartRequest = std::string(\"['pythia.multipart',\") + std::to_string(id) + ']';\n std::string fullOutput;\n\n for (int i = 0; i < count; i++)\n {\n output[0] = '\\0';\n RVExtension(output, sizeof(output), multipartRequest.c_str());\n fullOutput += output;\n }\n \/\/std::cout << fullOutput << std::endl;\n return fullOutput;\n}\n\nint test_fuzzing_single()\n{\n char output[10 * 1024];\n\n const char multipartTemplate[] = \"[\\\"m\\\",\";\n const int payloadOffset = sizeof(multipartTemplate) - 1;\n\n SQFGenerator builder = SQFGenerator(0, 100);\n std::string sqf = builder.generate(2);\n std::string request = createPingRequest(sqf);\n\n RVExtension(output, sizeof(output), request.c_str());\n\n \/\/ Check for regular response\n int regularResponse = compareRegularResponse(output, sqf);\n if (regularResponse != -1)\n return regularResponse;\n\n if (strncmp(output, multipartTemplate, payloadOffset) == 0)\n {\n \/\/std::cout << output << std::endl;\n int id, count;\n parseMultipart(output, id, count);\n std::string multipartOutput = handleMultipart(id, count);\n\n int multipartResponse = compareRegularResponse(multipartOutput.c_str(), sqf);\n if (multipartResponse == 0)\n {\n \/\/std::cout << \"OK :)\" << std::endl;\n return 0;\n }\n else\n {\n std::cout << \"Got unknown response: \" << multipartOutput << std::endl;\n return 1;\n }\n }\n else\n {\n std::cout << \"Got unknown response: \" << output << std::endl;\n return 1;\n }\n}\n\nvoid test_fuzzing_multiple()\n{\n int iterations = 10000;\n\n auto start = std::chrono::system_clock::now();\n for (int i = 0; i < iterations; i++)\n {\n if (i % 10 == 0)\n std::cout << \"Test: \" << std::to_string(i) << std::endl;\n\n if (test_fuzzing_single() != 0)\n return;\n }\n auto end = std::chrono::system_clock::now();\n auto elapsed = end - start;\n std::cout << \"Tests OK!\" << std::endl;\n std::cout << \"Each function time: \" << elapsed.count() \/ 10000.0 \/ (double)iterations << \"ms\" << std::endl;\n}\n\nvoid test_coroutines()\n{\n char output[10 * 1024];\n const int iterations = 10000;\n const char *command = \"['python.coroutines.test_coroutines']\";\n char *response = _strdup(\"['pythia.continue', , 'tralala something']\");\n char number[10];\n\n int continue_val;\n\n std::cout << \"Calling \" << iterations << \" times: \" << command << std::endl;\n\n \/\/ First call to initialize everything (in case it is needed)\n RVExtension(output, sizeof(output), command);\n\n auto start = std::chrono::system_clock::now();\n for (int i = iterations; i > 0; i--)\n {\n RVExtension(output, sizeof(output), command);\n while (output[2] == 's')\n {\n continue_val = atoi(output + 5);\n sprintf_s(number, \"%6d\", continue_val);\n for (int j = 0; j < 6; j++)\n {\n response[20 + j] = number[j];\n }\n RVExtension(output, sizeof(output), response);\n }\n }\n auto end = std::chrono::system_clock::now();\n auto elapsed = end - start;\n\n std::cout << \"Last call output: \" << output << std::endl;\n std::cout << \"Each function time: \" << elapsed.count() \/ 10000.0 \/ (double)iterations << \"ms\" << std::endl;\n}\n\n#ifdef _WIN64\n#define PYTHIA_DLL \"Pythia_x64.dll\"\n#define FUNCNAME \"RVExtension\"\n#else\n#define PYTHIA_DLL \"Pythia.dll\"\n#define FUNCNAME \"_RVExtension@12\"\n#endif\n\n\nint main()\n{\n HINSTANCE hInstLibrary = LoadLibrary(TEXT(PYTHIA_DLL));\n\n if (hInstLibrary)\n {\n RVExtension = (RVExtension_t)GetProcAddress(hInstLibrary, FUNCNAME);\n\n if (RVExtension)\n {\n test();\n }\n else\n {\n std::cout << \"Could not get RVExtension function.\" << std::endl;\n }\n FreeLibrary(hInstLibrary);\n }\n else\n {\n std::cout << \"Could not open library dll.\" << std::endl;\n }\n\n std::cout << \"Press enter to continue...\";\n std::cin.get();\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- SparcAsmPrinter.cpp - Sparc LLVM assembly writer ------------------===\/\/\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\/\/ This file contains a printer that converts from our internal representation\n\/\/ of machine-dependent LLVM code to GAS-format SPARC assembly language.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"asm-printer\"\n#include \"Sparc.h\"\n#include \"SparcInstrInfo.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/Target\/TargetAsmInfo.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Support\/Mangler.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include <cctype>\n#include <cstring>\n#include <map>\nusing namespace llvm;\n\nSTATISTIC(EmittedInsts, \"Number of machine instrs printed\");\n\nnamespace {\n struct VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {\n SparcAsmPrinter(raw_ostream &O, TargetMachine &TM, const TargetAsmInfo *T)\n : AsmPrinter(O, TM, T) {\n }\n\n \/\/\/ We name each basic block in a Function with a unique number, so\n \/\/\/ that we can consistently refer to them later. This is cleared\n \/\/\/ at the beginning of each call to runOnMachineFunction().\n \/\/\/\n typedef std::map<const Value *, unsigned> ValueMapTy;\n ValueMapTy NumberForBB;\n\n virtual const char *getPassName() const {\n return \"Sparc Assembly Printer\";\n }\n\n void printModuleLevelGV(const GlobalVariable* GVar);\n void printOperand(const MachineInstr *MI, int opNum);\n void printMemOperand(const MachineInstr *MI, int opNum,\n const char *Modifier = 0);\n void printCCOperand(const MachineInstr *MI, int opNum);\n\n bool printInstruction(const MachineInstr *MI); \/\/ autogenerated.\n bool runOnMachineFunction(MachineFunction &F);\n bool doInitialization(Module &M);\n bool doFinalization(Module &M);\n };\n} \/\/ end of anonymous namespace\n\n#include \"SparcGenAsmWriter.inc\"\n\n\/\/\/ createSparcCodePrinterPass - Returns a pass that prints the SPARC\n\/\/\/ assembly code for a MachineFunction to the given output stream,\n\/\/\/ using the given target machine description. This should work\n\/\/\/ regardless of whether the function is in SSA form.\n\/\/\/\nFunctionPass *llvm::createSparcCodePrinterPass(raw_ostream &o,\n TargetMachine &tm) {\n return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo());\n}\n\n\/\/\/ runOnMachineFunction - This uses the printInstruction()\n\/\/\/ method to print assembly for each instruction.\n\/\/\/\nbool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {\n SetupMachineFunction(MF);\n\n \/\/ Print out constants referenced by the function\n EmitConstantPool(MF.getConstantPool());\n\n \/\/ BBNumber is used here so that a given Printer will never give two\n \/\/ BBs the same name. (If you have a better way, please let me know!)\n static unsigned BBNumber = 0;\n\n O << \"\\n\\n\";\n \/\/ What's my mangled name?\n CurrentFnName = Mang->getValueName(MF.getFunction());\n\n \/\/ Print out the label for the function.\n const Function *F = MF.getFunction();\n SwitchToSection(TAI->SectionForGlobal(F));\n EmitAlignment(4, F);\n O << \"\\t.globl\\t\" << CurrentFnName << '\\n';\n\n printVisibility(CurrentFnName, F->getVisibility());\n\n O << \"\\t.type\\t\" << CurrentFnName << \", #function\\n\";\n O << CurrentFnName << \":\\n\";\n\n \/\/ Number each basic block so that we can consistently refer to them\n \/\/ in PC-relative references.\n \/\/ FIXME: Why not use the MBB numbers?\n NumberForBB.clear();\n for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();\n I != E; ++I) {\n NumberForBB[I->getBasicBlock()] = BBNumber++;\n }\n\n \/\/ Print out code for the function.\n for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();\n I != E; ++I) {\n \/\/ Print a label for the basic block.\n if (I != MF.begin()) {\n printBasicBlockLabel(I, true, true);\n O << '\\n';\n }\n for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();\n II != E; ++II) {\n \/\/ Print the assembly for the instruction.\n printInstruction(II);\n ++EmittedInsts;\n }\n }\n\n \/\/ We didn't modify anything.\n return false;\n}\n\nvoid SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {\n const MachineOperand &MO = MI->getOperand (opNum);\n const TargetRegisterInfo &RI = *TM.getRegisterInfo();\n bool CloseParen = false;\n if (MI->getOpcode() == SP::SETHIi && !MO.isReg() && !MO.isImm()) {\n O << \"%hi(\";\n CloseParen = true;\n } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri) &&\n !MO.isReg() && !MO.isImm()) {\n O << \"%lo(\";\n CloseParen = true;\n }\n switch (MO.getType()) {\n case MachineOperand::MO_Register:\n if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))\n O << \"%\" << LowercaseString (RI.get(MO.getReg()).AsmName);\n else\n O << \"%reg\" << MO.getReg();\n break;\n\n case MachineOperand::MO_Immediate:\n O << (int)MO.getImm();\n break;\n case MachineOperand::MO_MachineBasicBlock:\n printBasicBlockLabel(MO.getMBB());\n return;\n case MachineOperand::MO_GlobalAddress:\n O << Mang->getValueName(MO.getGlobal());\n break;\n case MachineOperand::MO_ExternalSymbol:\n O << MO.getSymbolName();\n break;\n case MachineOperand::MO_ConstantPoolIndex:\n O << TAI->getPrivateGlobalPrefix() << \"CPI\" << getFunctionNumber() << \"_\"\n << MO.getIndex();\n break;\n default:\n O << \"<unknown operand type>\"; abort (); break;\n }\n if (CloseParen) O << \")\";\n}\n\nvoid SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,\n const char *Modifier) {\n printOperand(MI, opNum);\n\n \/\/ If this is an ADD operand, emit it like normal operands.\n if (Modifier && !strcmp(Modifier, \"arith\")) {\n O << \", \";\n printOperand(MI, opNum+1);\n return;\n }\n\n if (MI->getOperand(opNum+1).isReg() &&\n MI->getOperand(opNum+1).getReg() == SP::G0)\n return; \/\/ don't print \"+%g0\"\n if (MI->getOperand(opNum+1).isImm() &&\n MI->getOperand(opNum+1).getImm() == 0)\n return; \/\/ don't print \"+0\"\n\n O << \"+\";\n if (MI->getOperand(opNum+1).isGlobal() ||\n MI->getOperand(opNum+1).isCPI()) {\n O << \"%lo(\";\n printOperand(MI, opNum+1);\n O << \")\";\n } else {\n printOperand(MI, opNum+1);\n }\n}\n\nvoid SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {\n int CC = (int)MI->getOperand(opNum).getImm();\n O << SPARCCondCodeToString((SPCC::CondCodes)CC);\n}\n\n\n\nbool SparcAsmPrinter::doInitialization(Module &M) {\n Mang = new Mangler(M);\n return false; \/\/ success\n}\n\nbool SparcAsmPrinter::doFinalization(Module &M) {\n \/\/ Print out module-level global variables here.\n for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();\n I != E; ++I)\n printModuleLevelGV(I);\n\n O << '\\n';\n\n return AsmPrinter::doFinalization(M);\n}\n\nvoid SparcAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {\n const TargetData *TD = TM.getTargetData();\n\n if (!GVar->hasInitializer())\n return; \/\/ External global require no code\n\n \/\/ Check to see if this is a special global used by LLVM, if so, emit it.\n if (EmitSpecialLLVMGlobal(GVar))\n return;\n\n O << \"\\n\\n\";\n std::string name = Mang->getValueName(GVar);\n Constant *C = GVar->getInitializer();\n unsigned Size = TD->getABITypeSize(C->getType());\n unsigned Align = TD->getPreferredAlignment(GVar);\n\n printVisibility(name, GVar->getVisibility());\n\n SwitchToSection(TAI->SectionForGlobal(GVar));\n\n if (C->isNullValue() && !GVar->hasSection()) {\n if (!GVar->isThreadLocal() &&\n (GVar->hasInternalLinkage() || GVar->mayBeOverridden())) {\n if (Size == 0) Size = 1; \/\/ .comm Foo, 0 is undefined, avoid it.\n\n if (GVar->hasInternalLinkage())\n O << \"\\t.local \" << name << '\\n';\n\n O << TAI->getCOMMDirective() << name << ',' << Size;\n if (TAI->getCOMMDirectiveTakesAlignment())\n O << ',' << (1 << Align);\n\n O << '\\n';\n return;\n }\n }\n\n switch (GVar->getLinkage()) {\n case GlobalValue::CommonLinkage:\n case GlobalValue::LinkOnceLinkage:\n case GlobalValue::WeakLinkage: \/\/ FIXME: Verify correct for weak.\n \/\/ Nonnull linkonce -> weak\n O << \"\\t.weak \" << name << '\\n';\n break;\n case GlobalValue::AppendingLinkage:\n \/\/ FIXME: appending linkage variables should go into a section of\n \/\/ their name or something. For now, just emit them as external.\n case GlobalValue::ExternalLinkage:\n \/\/ If external or appending, declare as a global symbol\n O << TAI->getGlobalDirective() << name << '\\n';\n \/\/ FALL THROUGH\n case GlobalValue::InternalLinkage:\n break;\n case GlobalValue::GhostLinkage:\n cerr << \"Should not have any unmaterialized functions!\\n\";\n abort();\n case GlobalValue::DLLImportLinkage:\n cerr << \"DLLImport linkage is not supported by this target!\\n\";\n abort();\n case GlobalValue::DLLExportLinkage:\n cerr << \"DLLExport linkage is not supported by this target!\\n\";\n abort();\n default:\n assert(0 && \"Unknown linkage type!\");\n }\n\n EmitAlignment(Align, GVar);\n\n if (TAI->hasDotTypeDotSizeDirective()) {\n O << \"\\t.type \" << name << \",#object\\n\";\n O << \"\\t.size \" << name << ',' << Size << '\\n';\n }\n\n O << name << \":\\n\";\n EmitGlobalConstant(C);\n}\n<commit_msg>Add rudimentary asmprinter support for printing inline asm operands for sparc.<commit_after>\/\/===-- SparcAsmPrinter.cpp - Sparc LLVM assembly writer ------------------===\/\/\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\/\/ This file contains a printer that converts from our internal representation\n\/\/ of machine-dependent LLVM code to GAS-format SPARC assembly language.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"asm-printer\"\n#include \"Sparc.h\"\n#include \"SparcInstrInfo.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/Target\/TargetAsmInfo.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Support\/Mangler.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include <cctype>\n#include <cstring>\n#include <map>\nusing namespace llvm;\n\nSTATISTIC(EmittedInsts, \"Number of machine instrs printed\");\n\nnamespace {\n struct VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {\n SparcAsmPrinter(raw_ostream &O, TargetMachine &TM, const TargetAsmInfo *T)\n : AsmPrinter(O, TM, T) {\n }\n\n \/\/\/ We name each basic block in a Function with a unique number, so\n \/\/\/ that we can consistently refer to them later. This is cleared\n \/\/\/ at the beginning of each call to runOnMachineFunction().\n \/\/\/\n typedef std::map<const Value *, unsigned> ValueMapTy;\n ValueMapTy NumberForBB;\n\n virtual const char *getPassName() const {\n return \"Sparc Assembly Printer\";\n }\n\n void printModuleLevelGV(const GlobalVariable* GVar);\n void printOperand(const MachineInstr *MI, int opNum);\n void printMemOperand(const MachineInstr *MI, int opNum,\n const char *Modifier = 0);\n void printCCOperand(const MachineInstr *MI, int opNum);\n\n bool printInstruction(const MachineInstr *MI); \/\/ autogenerated.\n bool runOnMachineFunction(MachineFunction &F);\n bool doInitialization(Module &M);\n bool doFinalization(Module &M);\n bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,\n unsigned AsmVariant, const char *ExtraCode);\n bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,\n unsigned AsmVariant, const char *ExtraCode);\n };\n} \/\/ end of anonymous namespace\n\n#include \"SparcGenAsmWriter.inc\"\n\n\/\/\/ createSparcCodePrinterPass - Returns a pass that prints the SPARC\n\/\/\/ assembly code for a MachineFunction to the given output stream,\n\/\/\/ using the given target machine description. This should work\n\/\/\/ regardless of whether the function is in SSA form.\n\/\/\/\nFunctionPass *llvm::createSparcCodePrinterPass(raw_ostream &o,\n TargetMachine &tm) {\n return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo());\n}\n\n\/\/\/ runOnMachineFunction - This uses the printInstruction()\n\/\/\/ method to print assembly for each instruction.\n\/\/\/\nbool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {\n SetupMachineFunction(MF);\n\n \/\/ Print out constants referenced by the function\n EmitConstantPool(MF.getConstantPool());\n\n \/\/ BBNumber is used here so that a given Printer will never give two\n \/\/ BBs the same name. (If you have a better way, please let me know!)\n static unsigned BBNumber = 0;\n\n O << \"\\n\\n\";\n \/\/ What's my mangled name?\n CurrentFnName = Mang->getValueName(MF.getFunction());\n\n \/\/ Print out the label for the function.\n const Function *F = MF.getFunction();\n SwitchToSection(TAI->SectionForGlobal(F));\n EmitAlignment(4, F);\n O << \"\\t.globl\\t\" << CurrentFnName << '\\n';\n\n printVisibility(CurrentFnName, F->getVisibility());\n\n O << \"\\t.type\\t\" << CurrentFnName << \", #function\\n\";\n O << CurrentFnName << \":\\n\";\n\n \/\/ Number each basic block so that we can consistently refer to them\n \/\/ in PC-relative references.\n \/\/ FIXME: Why not use the MBB numbers?\n NumberForBB.clear();\n for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();\n I != E; ++I) {\n NumberForBB[I->getBasicBlock()] = BBNumber++;\n }\n\n \/\/ Print out code for the function.\n for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();\n I != E; ++I) {\n \/\/ Print a label for the basic block.\n if (I != MF.begin()) {\n printBasicBlockLabel(I, true, true);\n O << '\\n';\n }\n for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();\n II != E; ++II) {\n \/\/ Print the assembly for the instruction.\n printInstruction(II);\n ++EmittedInsts;\n }\n }\n\n \/\/ We didn't modify anything.\n return false;\n}\n\nvoid SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {\n const MachineOperand &MO = MI->getOperand (opNum);\n const TargetRegisterInfo &RI = *TM.getRegisterInfo();\n bool CloseParen = false;\n if (MI->getOpcode() == SP::SETHIi && !MO.isReg() && !MO.isImm()) {\n O << \"%hi(\";\n CloseParen = true;\n } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri) &&\n !MO.isReg() && !MO.isImm()) {\n O << \"%lo(\";\n CloseParen = true;\n }\n switch (MO.getType()) {\n case MachineOperand::MO_Register:\n if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))\n O << \"%\" << LowercaseString (RI.get(MO.getReg()).AsmName);\n else\n O << \"%reg\" << MO.getReg();\n break;\n\n case MachineOperand::MO_Immediate:\n O << (int)MO.getImm();\n break;\n case MachineOperand::MO_MachineBasicBlock:\n printBasicBlockLabel(MO.getMBB());\n return;\n case MachineOperand::MO_GlobalAddress:\n O << Mang->getValueName(MO.getGlobal());\n break;\n case MachineOperand::MO_ExternalSymbol:\n O << MO.getSymbolName();\n break;\n case MachineOperand::MO_ConstantPoolIndex:\n O << TAI->getPrivateGlobalPrefix() << \"CPI\" << getFunctionNumber() << \"_\"\n << MO.getIndex();\n break;\n default:\n O << \"<unknown operand type>\"; abort (); break;\n }\n if (CloseParen) O << \")\";\n}\n\nvoid SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,\n const char *Modifier) {\n printOperand(MI, opNum);\n\n \/\/ If this is an ADD operand, emit it like normal operands.\n if (Modifier && !strcmp(Modifier, \"arith\")) {\n O << \", \";\n printOperand(MI, opNum+1);\n return;\n }\n\n if (MI->getOperand(opNum+1).isReg() &&\n MI->getOperand(opNum+1).getReg() == SP::G0)\n return; \/\/ don't print \"+%g0\"\n if (MI->getOperand(opNum+1).isImm() &&\n MI->getOperand(opNum+1).getImm() == 0)\n return; \/\/ don't print \"+0\"\n\n O << \"+\";\n if (MI->getOperand(opNum+1).isGlobal() ||\n MI->getOperand(opNum+1).isCPI()) {\n O << \"%lo(\";\n printOperand(MI, opNum+1);\n O << \")\";\n } else {\n printOperand(MI, opNum+1);\n }\n}\n\nvoid SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {\n int CC = (int)MI->getOperand(opNum).getImm();\n O << SPARCCondCodeToString((SPCC::CondCodes)CC);\n}\n\nbool SparcAsmPrinter::doInitialization(Module &M) {\n Mang = new Mangler(M);\n return false; \/\/ success\n}\n\nbool SparcAsmPrinter::doFinalization(Module &M) {\n \/\/ Print out module-level global variables here.\n for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();\n I != E; ++I)\n printModuleLevelGV(I);\n\n O << '\\n';\n\n return AsmPrinter::doFinalization(M);\n}\n\nvoid SparcAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {\n const TargetData *TD = TM.getTargetData();\n\n if (!GVar->hasInitializer())\n return; \/\/ External global require no code\n\n \/\/ Check to see if this is a special global used by LLVM, if so, emit it.\n if (EmitSpecialLLVMGlobal(GVar))\n return;\n\n O << \"\\n\\n\";\n std::string name = Mang->getValueName(GVar);\n Constant *C = GVar->getInitializer();\n unsigned Size = TD->getABITypeSize(C->getType());\n unsigned Align = TD->getPreferredAlignment(GVar);\n\n printVisibility(name, GVar->getVisibility());\n\n SwitchToSection(TAI->SectionForGlobal(GVar));\n\n if (C->isNullValue() && !GVar->hasSection()) {\n if (!GVar->isThreadLocal() &&\n (GVar->hasInternalLinkage() || GVar->mayBeOverridden())) {\n if (Size == 0) Size = 1; \/\/ .comm Foo, 0 is undefined, avoid it.\n\n if (GVar->hasInternalLinkage())\n O << \"\\t.local \" << name << '\\n';\n\n O << TAI->getCOMMDirective() << name << ',' << Size;\n if (TAI->getCOMMDirectiveTakesAlignment())\n O << ',' << (1 << Align);\n\n O << '\\n';\n return;\n }\n }\n\n switch (GVar->getLinkage()) {\n case GlobalValue::CommonLinkage:\n case GlobalValue::LinkOnceLinkage:\n case GlobalValue::WeakLinkage: \/\/ FIXME: Verify correct for weak.\n \/\/ Nonnull linkonce -> weak\n O << \"\\t.weak \" << name << '\\n';\n break;\n case GlobalValue::AppendingLinkage:\n \/\/ FIXME: appending linkage variables should go into a section of\n \/\/ their name or something. For now, just emit them as external.\n case GlobalValue::ExternalLinkage:\n \/\/ If external or appending, declare as a global symbol\n O << TAI->getGlobalDirective() << name << '\\n';\n \/\/ FALL THROUGH\n case GlobalValue::InternalLinkage:\n break;\n case GlobalValue::GhostLinkage:\n cerr << \"Should not have any unmaterialized functions!\\n\";\n abort();\n case GlobalValue::DLLImportLinkage:\n cerr << \"DLLImport linkage is not supported by this target!\\n\";\n abort();\n case GlobalValue::DLLExportLinkage:\n cerr << \"DLLExport linkage is not supported by this target!\\n\";\n abort();\n default:\n assert(0 && \"Unknown linkage type!\");\n }\n\n EmitAlignment(Align, GVar);\n\n if (TAI->hasDotTypeDotSizeDirective()) {\n O << \"\\t.type \" << name << \",#object\\n\";\n O << \"\\t.size \" << name << ',' << Size << '\\n';\n }\n\n O << name << \":\\n\";\n EmitGlobalConstant(C);\n}\n\n\/\/\/ PrintAsmOperand - Print out an operand for an inline asm expression.\n\/\/\/\nbool SparcAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,\n unsigned AsmVariant,\n const char *ExtraCode) {\n if (ExtraCode && ExtraCode[0])\n return true; \/\/ Unknown modifier\n\n printOperand(MI, OpNo);\n\n return false;\n}\n\nbool SparcAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,\n unsigned OpNo,\n unsigned AsmVariant,\n const char *ExtraCode) {\n if (ExtraCode && ExtraCode[0])\n return true; \/\/ Unknown modifier\n\n O << '[';\n printMemOperand(MI, OpNo);\n O << ']';\n\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===\/\/\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\/\/ This file implements a simple interprocedural pass which walks the\n\/\/ call-graph, looking for functions which do not access or only read\n\/\/ non-local memory, and marking them readnone\/readonly. In addition,\n\/\/ it marks function arguments (of pointer type) 'nocapture' if a call\n\/\/ to the function does not create any copies of the pointer value that\n\/\/ outlive the call. This more or less means that the pointer is only\n\/\/ dereferenced, and not returned from the function or stored in a global.\n\/\/ This pass is implemented as a bottom-up traversal of the call-graph.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"functionattrs\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/CallGraphSCCPass.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Analysis\/CaptureTracking.h\"\n#include \"llvm\/Analysis\/MallocHelper.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/UniqueVector.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/InstIterator.h\"\nusing namespace llvm;\n\nSTATISTIC(NumReadNone, \"Number of functions marked readnone\");\nSTATISTIC(NumReadOnly, \"Number of functions marked readonly\");\nSTATISTIC(NumNoCapture, \"Number of arguments marked nocapture\");\nSTATISTIC(NumNoAlias, \"Number of function returns marked noalias\");\n\nnamespace {\n struct VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {\n static char ID; \/\/ Pass identification, replacement for typeid\n FunctionAttrs() : CallGraphSCCPass(&ID) {}\n\n \/\/ runOnSCC - Analyze the SCC, performing the transformation if possible.\n bool runOnSCC(std::vector<CallGraphNode *> &SCC);\n\n \/\/ AddReadAttrs - Deduce readonly\/readnone attributes for the SCC.\n bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);\n\n \/\/ AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.\n bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);\n\n \/\/ IsFunctionMallocLike - Does this function allocate new memory?\n bool IsFunctionMallocLike(Function *F,\n SmallPtrSet<Function*, 8> &) const;\n\n \/\/ AddNoAliasAttrs - Deduce noalias attributes for the SCC.\n bool AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC);\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n CallGraphSCCPass::getAnalysisUsage(AU);\n }\n\n bool PointsToLocalMemory(Value *V);\n };\n}\n\nchar FunctionAttrs::ID = 0;\nstatic RegisterPass<FunctionAttrs>\nX(\"functionattrs\", \"Deduce function attributes\");\n\nPass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }\n\n\n\/\/\/ PointsToLocalMemory - Returns whether the given pointer value points to\n\/\/\/ memory that is local to the function. Global constants are considered\n\/\/\/ local to all functions.\nbool FunctionAttrs::PointsToLocalMemory(Value *V) {\n V = V->getUnderlyingObject();\n \/\/ An alloca instruction defines local memory.\n if (isa<AllocaInst>(V))\n return true;\n \/\/ A global constant counts as local memory for our purposes.\n if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))\n return GV->isConstant();\n \/\/ Could look through phi nodes and selects here, but it doesn't seem\n \/\/ to be useful in practice.\n return false;\n}\n\n\/\/\/ AddReadAttrs - Deduce readonly\/readnone attributes for the SCC.\nbool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {\n SmallPtrSet<Function*, 8> SCCNodes;\n\n \/\/ Fill SCCNodes with the elements of the SCC. Used for quickly\n \/\/ looking up whether a given CallGraphNode is in this SCC.\n for (unsigned i = 0, e = SCC.size(); i != e; ++i)\n SCCNodes.insert(SCC[i]->getFunction());\n\n \/\/ Check if any of the functions in the SCC read or write memory. If they\n \/\/ write memory then they can't be marked readnone or readonly.\n bool ReadsMemory = false;\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n\n if (F == 0)\n \/\/ External node - may write memory. Just give up.\n return false;\n\n if (F->doesNotAccessMemory())\n \/\/ Already perfect!\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime with\n \/\/ something that writes memory, so treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden()) {\n if (!F->onlyReadsMemory())\n \/\/ May write memory. Just give up.\n return false;\n\n ReadsMemory = true;\n continue;\n }\n\n \/\/ Scan the function body for instructions that may read or write memory.\n for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {\n Instruction *I = &*II;\n\n \/\/ Some instructions can be ignored even if they read or write memory.\n \/\/ Detect these now, skipping to the next instruction if one is found.\n CallSite CS = CallSite::get(I);\n if (CS.getInstruction() && CS.getCalledFunction()) {\n \/\/ Ignore calls to functions in the same SCC.\n if (SCCNodes.count(CS.getCalledFunction()))\n continue;\n } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {\n \/\/ Ignore loads from local memory.\n if (PointsToLocalMemory(LI->getPointerOperand()))\n continue;\n } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {\n \/\/ Ignore stores to local memory.\n if (PointsToLocalMemory(SI->getPointerOperand()))\n continue;\n }\n\n \/\/ Any remaining instructions need to be taken seriously! Check if they\n \/\/ read or write memory.\n if (I->mayWriteToMemory())\n \/\/ Writes memory. Just give up.\n return false;\n\n if (isa<MallocInst>(I))\n \/\/ malloc claims not to write memory! PR3754.\n return false;\n\n \/\/ If this instruction may read memory, remember that.\n ReadsMemory |= I->mayReadFromMemory();\n }\n }\n\n \/\/ Success! Functions in this SCC do not access memory, or only read memory.\n \/\/ Give them the appropriate attribute.\n bool MadeChange = false;\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n\n if (F->doesNotAccessMemory())\n \/\/ Already perfect!\n continue;\n\n if (F->onlyReadsMemory() && ReadsMemory)\n \/\/ No change.\n continue;\n\n MadeChange = true;\n\n \/\/ Clear out any existing attributes.\n F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);\n\n \/\/ Add in the new attribute.\n F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);\n\n if (ReadsMemory)\n ++NumReadOnly;\n else\n ++NumReadNone;\n }\n\n return MadeChange;\n}\n\n\/\/\/ AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.\nbool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {\n bool Changed = false;\n\n \/\/ Check each function in turn, determining which pointer arguments are not\n \/\/ captured.\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n\n if (F == 0)\n \/\/ External node - skip it;\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime with\n \/\/ something that writes memory, so treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden())\n continue;\n\n for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)\n if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr() &&\n !PointerMayBeCaptured(A, true)) {\n A->addAttr(Attribute::NoCapture);\n ++NumNoCapture;\n Changed = true;\n }\n }\n\n return Changed;\n}\n\n\/\/\/ IsFunctionMallocLike - A function is malloc-like if it returns either null\n\/\/\/ or a pointer that doesn't alias any other pointer visible to the caller.\nbool FunctionAttrs::IsFunctionMallocLike(Function *F,\n SmallPtrSet<Function*, 8> &SCCNodes) const {\n UniqueVector<Value *> FlowsToReturn;\n for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)\n if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))\n FlowsToReturn.insert(Ret->getReturnValue());\n\n for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {\n Value *RetVal = FlowsToReturn[i+1]; \/\/ UniqueVector[0] is reserved.\n\n if (Constant *C = dyn_cast<Constant>(RetVal)) {\n if (!C->isNullValue() && !isa<UndefValue>(C))\n return false;\n\n continue;\n }\n\n if (isa<Argument>(RetVal))\n return false;\n\n if (Instruction *RVI = dyn_cast<Instruction>(RetVal))\n switch (RVI->getOpcode()) {\n \/\/ Extend the analysis by looking upwards.\n case Instruction::BitCast:\n if (isMalloc(RVI))\n break;\n \/\/ fall through\n case Instruction::GetElementPtr:\n FlowsToReturn.insert(RVI->getOperand(0));\n continue;\n case Instruction::Select: {\n SelectInst *SI = cast<SelectInst>(RVI);\n FlowsToReturn.insert(SI->getTrueValue());\n FlowsToReturn.insert(SI->getFalseValue());\n } continue;\n case Instruction::PHI: {\n PHINode *PN = cast<PHINode>(RVI);\n for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)\n FlowsToReturn.insert(PN->getIncomingValue(i));\n } continue;\n\n \/\/ Check whether the pointer came from an allocation.\n case Instruction::Alloca:\n case Instruction::Malloc:\n break;\n case Instruction::Call:\n if (isMalloc(RVI))\n break;\n case Instruction::Invoke: {\n CallSite CS(RVI);\n if (CS.paramHasAttr(0, Attribute::NoAlias))\n break;\n if (CS.getCalledFunction() &&\n SCCNodes.count(CS.getCalledFunction()))\n break;\n } \/\/ fall-through\n default:\n return false; \/\/ Did not come from an allocation.\n }\n\n if (PointerMayBeCaptured(RetVal, false))\n return false;\n }\n\n return true;\n}\n\n\/\/\/ AddNoAliasAttrs - Deduce noalias attributes for the SCC.\nbool FunctionAttrs::AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC) {\n SmallPtrSet<Function*, 8> SCCNodes;\n\n \/\/ Fill SCCNodes with the elements of the SCC. Used for quickly\n \/\/ looking up whether a given CallGraphNode is in this SCC.\n for (unsigned i = 0, e = SCC.size(); i != e; ++i)\n SCCNodes.insert(SCC[i]->getFunction());\n\n \/\/ Check each function in turn, determining which functions return noalias\n \/\/ pointers.\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n\n if (F == 0)\n \/\/ External node - skip it;\n return false;\n\n \/\/ Already noalias.\n if (F->doesNotAlias(0))\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime, so\n \/\/ treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden())\n return false;\n\n \/\/ We annotate noalias return values, which are only applicable to \n \/\/ pointer types.\n if (!isa<PointerType>(F->getReturnType()))\n continue;\n\n if (!IsFunctionMallocLike(F, SCCNodes))\n return false;\n }\n\n bool MadeChange = false;\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n if (F->doesNotAlias(0) || !isa<PointerType>(F->getReturnType()))\n continue;\n\n F->setDoesNotAlias(0);\n ++NumNoAlias;\n MadeChange = true;\n }\n\n return MadeChange;\n}\n\nbool FunctionAttrs::runOnSCC(std::vector<CallGraphNode *> &SCC) {\n bool Changed = AddReadAttrs(SCC);\n Changed |= AddNoCaptureAttrs(SCC);\n Changed |= AddNoAliasAttrs(SCC);\n return Changed;\n}\n<commit_msg>remove special handling of bitcast(malloc), it will be handled when the loop inspects the bitcast operand.<commit_after>\/\/===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===\/\/\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\/\/ This file implements a simple interprocedural pass which walks the\n\/\/ call-graph, looking for functions which do not access or only read\n\/\/ non-local memory, and marking them readnone\/readonly. In addition,\n\/\/ it marks function arguments (of pointer type) 'nocapture' if a call\n\/\/ to the function does not create any copies of the pointer value that\n\/\/ outlive the call. This more or less means that the pointer is only\n\/\/ dereferenced, and not returned from the function or stored in a global.\n\/\/ This pass is implemented as a bottom-up traversal of the call-graph.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"functionattrs\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/CallGraphSCCPass.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Analysis\/CaptureTracking.h\"\n#include \"llvm\/Analysis\/MallocHelper.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/UniqueVector.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/InstIterator.h\"\nusing namespace llvm;\n\nSTATISTIC(NumReadNone, \"Number of functions marked readnone\");\nSTATISTIC(NumReadOnly, \"Number of functions marked readonly\");\nSTATISTIC(NumNoCapture, \"Number of arguments marked nocapture\");\nSTATISTIC(NumNoAlias, \"Number of function returns marked noalias\");\n\nnamespace {\n struct VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {\n static char ID; \/\/ Pass identification, replacement for typeid\n FunctionAttrs() : CallGraphSCCPass(&ID) {}\n\n \/\/ runOnSCC - Analyze the SCC, performing the transformation if possible.\n bool runOnSCC(std::vector<CallGraphNode *> &SCC);\n\n \/\/ AddReadAttrs - Deduce readonly\/readnone attributes for the SCC.\n bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);\n\n \/\/ AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.\n bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);\n\n \/\/ IsFunctionMallocLike - Does this function allocate new memory?\n bool IsFunctionMallocLike(Function *F,\n SmallPtrSet<Function*, 8> &) const;\n\n \/\/ AddNoAliasAttrs - Deduce noalias attributes for the SCC.\n bool AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC);\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n CallGraphSCCPass::getAnalysisUsage(AU);\n }\n\n bool PointsToLocalMemory(Value *V);\n };\n}\n\nchar FunctionAttrs::ID = 0;\nstatic RegisterPass<FunctionAttrs>\nX(\"functionattrs\", \"Deduce function attributes\");\n\nPass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }\n\n\n\/\/\/ PointsToLocalMemory - Returns whether the given pointer value points to\n\/\/\/ memory that is local to the function. Global constants are considered\n\/\/\/ local to all functions.\nbool FunctionAttrs::PointsToLocalMemory(Value *V) {\n V = V->getUnderlyingObject();\n \/\/ An alloca instruction defines local memory.\n if (isa<AllocaInst>(V))\n return true;\n \/\/ A global constant counts as local memory for our purposes.\n if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))\n return GV->isConstant();\n \/\/ Could look through phi nodes and selects here, but it doesn't seem\n \/\/ to be useful in practice.\n return false;\n}\n\n\/\/\/ AddReadAttrs - Deduce readonly\/readnone attributes for the SCC.\nbool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {\n SmallPtrSet<Function*, 8> SCCNodes;\n\n \/\/ Fill SCCNodes with the elements of the SCC. Used for quickly\n \/\/ looking up whether a given CallGraphNode is in this SCC.\n for (unsigned i = 0, e = SCC.size(); i != e; ++i)\n SCCNodes.insert(SCC[i]->getFunction());\n\n \/\/ Check if any of the functions in the SCC read or write memory. If they\n \/\/ write memory then they can't be marked readnone or readonly.\n bool ReadsMemory = false;\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n\n if (F == 0)\n \/\/ External node - may write memory. Just give up.\n return false;\n\n if (F->doesNotAccessMemory())\n \/\/ Already perfect!\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime with\n \/\/ something that writes memory, so treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden()) {\n if (!F->onlyReadsMemory())\n \/\/ May write memory. Just give up.\n return false;\n\n ReadsMemory = true;\n continue;\n }\n\n \/\/ Scan the function body for instructions that may read or write memory.\n for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {\n Instruction *I = &*II;\n\n \/\/ Some instructions can be ignored even if they read or write memory.\n \/\/ Detect these now, skipping to the next instruction if one is found.\n CallSite CS = CallSite::get(I);\n if (CS.getInstruction() && CS.getCalledFunction()) {\n \/\/ Ignore calls to functions in the same SCC.\n if (SCCNodes.count(CS.getCalledFunction()))\n continue;\n } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {\n \/\/ Ignore loads from local memory.\n if (PointsToLocalMemory(LI->getPointerOperand()))\n continue;\n } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {\n \/\/ Ignore stores to local memory.\n if (PointsToLocalMemory(SI->getPointerOperand()))\n continue;\n }\n\n \/\/ Any remaining instructions need to be taken seriously! Check if they\n \/\/ read or write memory.\n if (I->mayWriteToMemory())\n \/\/ Writes memory. Just give up.\n return false;\n\n if (isa<MallocInst>(I))\n \/\/ malloc claims not to write memory! PR3754.\n return false;\n\n \/\/ If this instruction may read memory, remember that.\n ReadsMemory |= I->mayReadFromMemory();\n }\n }\n\n \/\/ Success! Functions in this SCC do not access memory, or only read memory.\n \/\/ Give them the appropriate attribute.\n bool MadeChange = false;\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n\n if (F->doesNotAccessMemory())\n \/\/ Already perfect!\n continue;\n\n if (F->onlyReadsMemory() && ReadsMemory)\n \/\/ No change.\n continue;\n\n MadeChange = true;\n\n \/\/ Clear out any existing attributes.\n F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);\n\n \/\/ Add in the new attribute.\n F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);\n\n if (ReadsMemory)\n ++NumReadOnly;\n else\n ++NumReadNone;\n }\n\n return MadeChange;\n}\n\n\/\/\/ AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.\nbool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {\n bool Changed = false;\n\n \/\/ Check each function in turn, determining which pointer arguments are not\n \/\/ captured.\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n\n if (F == 0)\n \/\/ External node - skip it;\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime with\n \/\/ something that writes memory, so treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden())\n continue;\n\n for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)\n if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr() &&\n !PointerMayBeCaptured(A, true)) {\n A->addAttr(Attribute::NoCapture);\n ++NumNoCapture;\n Changed = true;\n }\n }\n\n return Changed;\n}\n\n\/\/\/ IsFunctionMallocLike - A function is malloc-like if it returns either null\n\/\/\/ or a pointer that doesn't alias any other pointer visible to the caller.\nbool FunctionAttrs::IsFunctionMallocLike(Function *F,\n SmallPtrSet<Function*, 8> &SCCNodes) const {\n UniqueVector<Value *> FlowsToReturn;\n for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)\n if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))\n FlowsToReturn.insert(Ret->getReturnValue());\n\n for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {\n Value *RetVal = FlowsToReturn[i+1]; \/\/ UniqueVector[0] is reserved.\n\n if (Constant *C = dyn_cast<Constant>(RetVal)) {\n if (!C->isNullValue() && !isa<UndefValue>(C))\n return false;\n\n continue;\n }\n\n if (isa<Argument>(RetVal))\n return false;\n\n if (Instruction *RVI = dyn_cast<Instruction>(RetVal))\n switch (RVI->getOpcode()) {\n \/\/ Extend the analysis by looking upwards.\n case Instruction::BitCast:\n case Instruction::GetElementPtr:\n FlowsToReturn.insert(RVI->getOperand(0));\n continue;\n case Instruction::Select: {\n SelectInst *SI = cast<SelectInst>(RVI);\n FlowsToReturn.insert(SI->getTrueValue());\n FlowsToReturn.insert(SI->getFalseValue());\n continue;\n }\n case Instruction::PHI: {\n PHINode *PN = cast<PHINode>(RVI);\n for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)\n FlowsToReturn.insert(PN->getIncomingValue(i));\n continue;\n }\n\n \/\/ Check whether the pointer came from an allocation.\n case Instruction::Alloca:\n case Instruction::Malloc:\n break;\n case Instruction::Call:\n if (isMalloc(RVI))\n break;\n case Instruction::Invoke: {\n CallSite CS(RVI);\n if (CS.paramHasAttr(0, Attribute::NoAlias))\n break;\n if (CS.getCalledFunction() &&\n SCCNodes.count(CS.getCalledFunction()))\n break;\n } \/\/ fall-through\n default:\n return false; \/\/ Did not come from an allocation.\n }\n\n if (PointerMayBeCaptured(RetVal, false))\n return false;\n }\n\n return true;\n}\n\n\/\/\/ AddNoAliasAttrs - Deduce noalias attributes for the SCC.\nbool FunctionAttrs::AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC) {\n SmallPtrSet<Function*, 8> SCCNodes;\n\n \/\/ Fill SCCNodes with the elements of the SCC. Used for quickly\n \/\/ looking up whether a given CallGraphNode is in this SCC.\n for (unsigned i = 0, e = SCC.size(); i != e; ++i)\n SCCNodes.insert(SCC[i]->getFunction());\n\n \/\/ Check each function in turn, determining which functions return noalias\n \/\/ pointers.\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n\n if (F == 0)\n \/\/ External node - skip it;\n return false;\n\n \/\/ Already noalias.\n if (F->doesNotAlias(0))\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime, so\n \/\/ treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden())\n return false;\n\n \/\/ We annotate noalias return values, which are only applicable to \n \/\/ pointer types.\n if (!isa<PointerType>(F->getReturnType()))\n continue;\n\n if (!IsFunctionMallocLike(F, SCCNodes))\n return false;\n }\n\n bool MadeChange = false;\n for (unsigned i = 0, e = SCC.size(); i != e; ++i) {\n Function *F = SCC[i]->getFunction();\n if (F->doesNotAlias(0) || !isa<PointerType>(F->getReturnType()))\n continue;\n\n F->setDoesNotAlias(0);\n ++NumNoAlias;\n MadeChange = true;\n }\n\n return MadeChange;\n}\n\nbool FunctionAttrs::runOnSCC(std::vector<CallGraphNode *> &SCC) {\n bool Changed = AddReadAttrs(SCC);\n Changed |= AddNoCaptureAttrs(SCC);\n Changed |= AddNoAliasAttrs(SCC);\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>added support to save nr of points in search results<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/**\r\n \\file GLVolume2DTex.cpp\r\n \\author Jens Krueger\r\n DFKI Saarbruecken & SCI Institute University of Utah\r\n \\date May 2010\r\n*\/\r\n\r\n#include \"GLVolume2DTex.h\"\r\n#include \"GLTexture2D.h\"\r\n#include <cstring> \/\/ for memcpy\r\n\r\nusing namespace tuvok;\r\nusing namespace std;\r\n\r\n\r\nGLVolume2DTex::GLVolume2DTex(UINT32 iSizeX, UINT32 iSizeY, UINT32 iSizeZ,\r\n GLint internalformat, GLenum format, GLenum type,\r\n UINT32 iSizePerElement,\r\n const GLvoid *voxels,\r\n GLint iMagFilter,\r\n GLint iMinFilter,\r\n GLint wrapX,\r\n GLint wrapY,\r\n GLint wrapZ) :\r\n m_iSizeX(iSizeX),\r\n m_iSizeY(iSizeY),\r\n m_iSizeZ(iSizeZ),\r\n m_internalformat(internalformat),\r\n m_format(format),\r\n m_type(type),\r\n m_iSizePerElement(iSizePerElement),\r\n m_iMagFilter(iMagFilter),\r\n m_iMinFilter(iMinFilter),\r\n m_wrapX(wrapX),\r\n m_wrapY(wrapY),\r\n m_wrapZ(wrapZ),\r\n m_iGPUSize(0),\r\n m_iCPUSize(0)\r\n{\r\n m_pTextures.resize(3);\r\n CreateGLResources();\r\n SetData(voxels);\r\n}\r\n\r\nGLVolume2DTex::GLVolume2DTex() :\r\n m_iSizeX(0),\r\n m_iSizeY(0),\r\n m_iSizeZ(0),\r\n m_internalformat(0),\r\n m_format(0),\r\n m_type(0),\r\n m_iSizePerElement(0),\r\n m_iMagFilter(GL_NEAREST),\r\n m_iMinFilter(GL_NEAREST),\r\n m_wrapX(GL_CLAMP_TO_EDGE),\r\n m_wrapY(GL_CLAMP_TO_EDGE),\r\n m_wrapZ(GL_CLAMP_TO_EDGE),\r\n m_iGPUSize(0),\r\n m_iCPUSize(0)\r\n{\r\n m_pTextures.resize(3);\r\n}\r\n\r\nGLVolume2DTex::~GLVolume2DTex() {\r\n}\r\n\r\nvoid GLVolume2DTex::Bind(UINT32 iUnit,\r\n int depth,\r\n int iStack) {\r\n if (depth < 0) \r\n m_pTextures[iStack][0]->Bind(iUnit);\r\n else \r\n if (static_cast<size_t>(depth) < m_pTextures[iStack].size()) \r\n m_pTextures[iStack][depth]->Bind(iUnit);\r\n else\r\n m_pTextures[iStack][m_pTextures[iStack].size()-1]->Bind(iUnit);\r\n}\r\n\r\nvoid GLVolume2DTex::CreateGLResources() {\r\n m_pTextures[0].resize(m_iSizeX);\r\n for (size_t i = 0;i<m_pTextures[0].size();i++){\r\n m_pTextures[0][i] = new GLTexture2D(m_iSizeZ, m_iSizeY, m_internalformat,\r\n m_format, m_type, m_iSizePerElement,\r\n NULL, m_iMagFilter, m_iMinFilter,\r\n m_wrapZ, m_wrapY);\r\n }\r\n m_pTextures[1].resize(m_iSizeY);\r\n for (size_t i = 0;i<m_pTextures[1].size();i++){\r\n m_pTextures[1][i] = new GLTexture2D(m_iSizeX, m_iSizeZ, m_internalformat,\r\n m_format, m_type, m_iSizePerElement,\r\n NULL, m_iMagFilter, m_iMinFilter,\r\n m_wrapX, m_wrapZ);\r\n }\r\n m_pTextures[2].resize(m_iSizeZ);\r\n for (size_t i = 0;i<m_pTextures[2].size();i++){\r\n m_pTextures[2][i] = new GLTexture2D(m_iSizeX, m_iSizeY, m_internalformat,\r\n m_format, m_type, m_iSizePerElement,\r\n NULL, m_iMagFilter, m_iMinFilter,\r\n m_wrapX, m_wrapY);\r\n }\r\n}\r\n\r\nvoid GLVolume2DTex::FreeGLResources() {\r\n for (size_t iDir = 0;iDir<m_pTextures.size();iDir++){\r\n for (size_t i = 0;i<m_pTextures[iDir].size();i++){\r\n if (m_pTextures[iDir][i]) {\r\n m_pTextures[iDir][i]->Delete();\r\n delete m_pTextures[iDir][i];\r\n }\r\n m_pTextures[iDir][i] = NULL;\r\n }\r\n m_pTextures[iDir].resize(0);\r\n }\r\n m_iCPUSize = 0;\r\n m_iGPUSize = 0;\r\n}\r\n\r\nvoid GLVolume2DTex::SetData(const void *voxels) {\r\n \/\/ push data into the stacks\r\n \/\/ z is easy as this matches the data layout\r\n \/\/ x and y are more nasty and require a\r\n \/\/ random acces traversal througth the data, hence\r\n \/\/ the complicated indexing\r\n\r\n\r\n const char* charPtr = static_cast<const char*>(voxels);\r\n char* copyBuffer = new char[max(m_pTextures[0][0]->GetCPUSize(),\r\n m_pTextures[1][0]->GetCPUSize())];\r\n size_t sliceElemCount = m_iSizeY*m_iSizeX;\r\n\r\n for (size_t i = 0;i<m_pTextures[0].size();i++){\r\n size_t targetPos = 0;\r\n size_t sourcePos = 0;\r\n for (size_t y = 0;y<m_iSizeY;y++) {\r\n for (size_t z = 0;z<m_iSizeZ;z++) {\r\n \/\/ compute position in source array\r\n sourcePos = (i+y*m_iSizeX+z*sliceElemCount)*m_iSizePerElement;\r\n \/\/ copy one element into the target buffer\r\n memcpy(copyBuffer+targetPos,charPtr+sourcePos,m_iSizePerElement);\r\n targetPos += m_iSizePerElement;\r\n }\r\n }\r\n \/\/ copy into 2D texture slice\r\n m_pTextures[0][i]->SetData(copyBuffer);\r\n }\r\n\r\n for (size_t i = 0;i<m_pTextures[1].size();i++){\r\n size_t targetPos = 0;\r\n size_t sourcePos = 0;\r\n for (size_t z = 0;z<m_iSizeZ;z++) {\r\n for (size_t x = 0;x<m_iSizeX;x++) {\r\n \/\/ compute position in source array\r\n sourcePos = (x+i*m_iSizeX+z*sliceElemCount)*m_iSizePerElement;\r\n \/\/ copy one element into the target buffer\r\n memcpy(copyBuffer+targetPos,charPtr+sourcePos,m_iSizePerElement);\r\n targetPos += m_iSizePerElement;\r\n }\r\n }\r\n \/\/ copy into 2D texture slice\r\n m_pTextures[1][i]->SetData(copyBuffer);\r\n }\r\n\r\n delete[] copyBuffer;\r\n\r\n \/\/ z direction is easy \r\n size_t stepping = m_pTextures[2][0]->GetCPUSize();\r\n\r\n for (size_t i = 0;i<m_pTextures[2].size();i++){\r\n m_pTextures[2][i]->SetData(charPtr);\r\n charPtr += stepping;\r\n }\r\n}\r\n\r\nUINT64 GLVolume2DTex::GetCPUSize() {\r\n if (m_iCPUSize) return m_iCPUSize;\r\n\r\n UINT64 iSize = 0;\r\n for (size_t iDir = 0;iDir<m_pTextures.size();iDir++){\r\n for (size_t i = 0;i<m_pTextures[iDir].size();i++){\r\n iSize += m_pTextures[iDir][i]->GetCPUSize();\r\n }\r\n }\r\n return iSize;\r\n}\r\n\r\nUINT64 GLVolume2DTex::GetGPUSize() {\r\n if (m_iGPUSize) return m_iGPUSize;\r\n\r\n UINT64 iSize = 0;\r\n for (size_t iDir = 0;iDir<m_pTextures.size();iDir++){\r\n for (size_t i = 0;i<m_pTextures[iDir].size();i++){\r\n iSize += m_pTextures[iDir][i]->GetGPUSize();\r\n }\r\n }\r\n return iSize;\r\n}<commit_msg>implemented a mirrored repeat-like texture assignment strategy at the boundaries (this turns the forward differences for the gradient computation int backward differences which is better than breaking them by implementing a clamp like behavior) lighting will still look odd (due to the flipping of the normal) but the gradient magnitude is correct<commit_after>\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/**\r\n \\file GLVolume2DTex.cpp\r\n \\author Jens Krueger\r\n DFKI Saarbruecken & SCI Institute University of Utah\r\n \\date May 2010\r\n*\/\r\n\r\n#include \"GLVolume2DTex.h\"\r\n#include \"GLTexture2D.h\"\r\n#include <cstring> \/\/ for memcpy\r\n\r\nusing namespace tuvok;\r\nusing namespace std;\r\n\r\n\r\nGLVolume2DTex::GLVolume2DTex(UINT32 iSizeX, UINT32 iSizeY, UINT32 iSizeZ,\r\n GLint internalformat, GLenum format, GLenum type,\r\n UINT32 iSizePerElement,\r\n const GLvoid *voxels,\r\n GLint iMagFilter,\r\n GLint iMinFilter,\r\n GLint wrapX,\r\n GLint wrapY,\r\n GLint wrapZ) :\r\n m_iSizeX(iSizeX),\r\n m_iSizeY(iSizeY),\r\n m_iSizeZ(iSizeZ),\r\n m_internalformat(internalformat),\r\n m_format(format),\r\n m_type(type),\r\n m_iSizePerElement(iSizePerElement),\r\n m_iMagFilter(iMagFilter),\r\n m_iMinFilter(iMinFilter),\r\n m_wrapX(wrapX),\r\n m_wrapY(wrapY),\r\n m_wrapZ(wrapZ),\r\n m_iGPUSize(0),\r\n m_iCPUSize(0)\r\n{\r\n m_pTextures.resize(3);\r\n CreateGLResources();\r\n SetData(voxels);\r\n}\r\n\r\nGLVolume2DTex::GLVolume2DTex() :\r\n m_iSizeX(0),\r\n m_iSizeY(0),\r\n m_iSizeZ(0),\r\n m_internalformat(0),\r\n m_format(0),\r\n m_type(0),\r\n m_iSizePerElement(0),\r\n m_iMagFilter(GL_NEAREST),\r\n m_iMinFilter(GL_NEAREST),\r\n m_wrapX(GL_CLAMP_TO_EDGE),\r\n m_wrapY(GL_CLAMP_TO_EDGE),\r\n m_wrapZ(GL_CLAMP_TO_EDGE),\r\n m_iGPUSize(0),\r\n m_iCPUSize(0)\r\n{\r\n m_pTextures.resize(3);\r\n}\r\n\r\nGLVolume2DTex::~GLVolume2DTex() {\r\n}\r\n\r\nvoid GLVolume2DTex::Bind(UINT32 iUnit,\r\n int depth,\r\n int iStack) {\r\n if (depth < 0) \r\n m_pTextures[iStack][1]->Bind(iUnit); \/\/ resembles mirrored repeat\r\n else \r\n if (static_cast<size_t>(depth) < m_pTextures[iStack].size()) \r\n m_pTextures[iStack][depth]->Bind(iUnit);\r\n else\r\n m_pTextures[iStack][m_pTextures[iStack].size()-2]->Bind(iUnit);\r\n \/\/ resembles mirrored repeat\r\n}\r\n\r\nvoid GLVolume2DTex::CreateGLResources() {\r\n m_pTextures[0].resize(m_iSizeX);\r\n for (size_t i = 0;i<m_pTextures[0].size();i++){\r\n m_pTextures[0][i] = new GLTexture2D(m_iSizeZ, m_iSizeY, m_internalformat,\r\n m_format, m_type, m_iSizePerElement,\r\n NULL, m_iMagFilter, m_iMinFilter,\r\n m_wrapZ, m_wrapY);\r\n }\r\n m_pTextures[1].resize(m_iSizeY);\r\n for (size_t i = 0;i<m_pTextures[1].size();i++){\r\n m_pTextures[1][i] = new GLTexture2D(m_iSizeX, m_iSizeZ, m_internalformat,\r\n m_format, m_type, m_iSizePerElement,\r\n NULL, m_iMagFilter, m_iMinFilter,\r\n m_wrapX, m_wrapZ);\r\n }\r\n m_pTextures[2].resize(m_iSizeZ);\r\n for (size_t i = 0;i<m_pTextures[2].size();i++){\r\n m_pTextures[2][i] = new GLTexture2D(m_iSizeX, m_iSizeY, m_internalformat,\r\n m_format, m_type, m_iSizePerElement,\r\n NULL, m_iMagFilter, m_iMinFilter,\r\n m_wrapX, m_wrapY);\r\n }\r\n}\r\n\r\nvoid GLVolume2DTex::FreeGLResources() {\r\n for (size_t iDir = 0;iDir<m_pTextures.size();iDir++){\r\n for (size_t i = 0;i<m_pTextures[iDir].size();i++){\r\n if (m_pTextures[iDir][i]) {\r\n m_pTextures[iDir][i]->Delete();\r\n delete m_pTextures[iDir][i];\r\n }\r\n m_pTextures[iDir][i] = NULL;\r\n }\r\n m_pTextures[iDir].resize(0);\r\n }\r\n m_iCPUSize = 0;\r\n m_iGPUSize = 0;\r\n}\r\n\r\nvoid GLVolume2DTex::SetData(const void *voxels) {\r\n \/\/ push data into the stacks\r\n \/\/ z is easy as this matches the data layout\r\n \/\/ x and y are more nasty and require a\r\n \/\/ random acces traversal througth the data, hence\r\n \/\/ the complicated indexing\r\n\r\n\r\n const char* charPtr = static_cast<const char*>(voxels);\r\n char* copyBuffer = new char[max(m_pTextures[0][0]->GetCPUSize(),\r\n m_pTextures[1][0]->GetCPUSize())];\r\n size_t sliceElemCount = m_iSizeY*m_iSizeX;\r\n\r\n for (size_t i = 0;i<m_pTextures[0].size();i++){\r\n size_t targetPos = 0;\r\n size_t sourcePos = 0;\r\n for (size_t y = 0;y<m_iSizeY;y++) {\r\n for (size_t z = 0;z<m_iSizeZ;z++) {\r\n \/\/ compute position in source array\r\n sourcePos = (i+y*m_iSizeX+z*sliceElemCount)*m_iSizePerElement;\r\n \/\/ copy one element into the target buffer\r\n memcpy(copyBuffer+targetPos,charPtr+sourcePos,m_iSizePerElement);\r\n targetPos += m_iSizePerElement;\r\n }\r\n }\r\n \/\/ copy into 2D texture slice\r\n m_pTextures[0][i]->SetData(copyBuffer);\r\n }\r\n\r\n for (size_t i = 0;i<m_pTextures[1].size();i++){\r\n size_t targetPos = 0;\r\n size_t sourcePos = 0;\r\n for (size_t z = 0;z<m_iSizeZ;z++) {\r\n for (size_t x = 0;x<m_iSizeX;x++) {\r\n \/\/ compute position in source array\r\n sourcePos = (x+i*m_iSizeX+z*sliceElemCount)*m_iSizePerElement;\r\n \/\/ copy one element into the target buffer\r\n memcpy(copyBuffer+targetPos,charPtr+sourcePos,m_iSizePerElement);\r\n targetPos += m_iSizePerElement;\r\n }\r\n }\r\n \/\/ copy into 2D texture slice\r\n m_pTextures[1][i]->SetData(copyBuffer);\r\n }\r\n\r\n delete[] copyBuffer;\r\n\r\n \/\/ z direction is easy \r\n size_t stepping = m_pTextures[2][0]->GetCPUSize();\r\n\r\n for (size_t i = 0;i<m_pTextures[2].size();i++){\r\n m_pTextures[2][i]->SetData(charPtr);\r\n charPtr += stepping;\r\n }\r\n}\r\n\r\nUINT64 GLVolume2DTex::GetCPUSize() {\r\n if (m_iCPUSize) return m_iCPUSize;\r\n\r\n UINT64 iSize = 0;\r\n for (size_t iDir = 0;iDir<m_pTextures.size();iDir++){\r\n for (size_t i = 0;i<m_pTextures[iDir].size();i++){\r\n iSize += m_pTextures[iDir][i]->GetCPUSize();\r\n }\r\n }\r\n return iSize;\r\n}\r\n\r\nUINT64 GLVolume2DTex::GetGPUSize() {\r\n if (m_iGPUSize) return m_iGPUSize;\r\n\r\n UINT64 iSize = 0;\r\n for (size_t iDir = 0;iDir<m_pTextures.size();iDir++){\r\n for (size_t i = 0;i<m_pTextures[iDir].size();i++){\r\n iSize += m_pTextures[iDir][i]->GetGPUSize();\r\n }\r\n }\r\n return iSize;\r\n}<|endoftext|>"} {"text":"<commit_before>#include \"StdAfx.h\"\n#include \"Inject.h\"\n\n#include \"Util.h\"\n\n\/\/ Ripped from Oblivion Script Extender \n\/\/ http:\/\/obse.silverlock.org\/\n\/\/ The sordid thread-suspending logic in DoInjectDLL is my own dismal contribution for ModelMod\n\nextern BOOL SuspendProcessThreads(DWORD dwOwnerPID, bool suspend);\n\nInject::Inject(void)\n{\n}\n\n\nInject::~Inject(void)\n{\n}\n\nbool Inject::InjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)\n{\n\tbool\tresult = false;\n\n\t\/\/ wrap DLL injection in SEH, if it crashes print a message\n\t__try {\n\t\tresult = DoInjectDLL(processId, dllPath, processWasLaunched);\n\t}\n\t__except(EXCEPTION_EXECUTE_HANDLER)\n\t{\n\t\t_injectError = \"DLL injection failed. In most cases, this is caused by an overly paranoid software firewall or antivirus package. Disabling either of these may solve the problem.\";\n\t\tresult = false;\n\t}\n\n\treturn result;\n}\n\n\/*** jmp hook layout\n *\tE9 ## ## ## ##\tjmp LoadLibraryA\n *\t\t\t\t\t\toffset = LoadLibraryA - (base + 5)\n *\t<string>\t\tname of function\n ***\/\n\ntypedef unsigned int UInt32;\ntypedef unsigned char UInt8;\n\nbool Inject::DoInjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)\n{\n\tbool result = false; \/\/ assume failure\n\n\tHANDLE process = OpenProcess(\n\t\tPROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, processId);\n\tif(process)\n\t{\n\t\tUInt32\thookBase = (UInt32)VirtualAllocEx(process, NULL, 8192, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n\t\tif(hookBase)\n\t\t{\n\t\t\t\/\/ safe because kernel32 is loaded at the same address in all processes\n\t\t\t\/\/ (can change across restarts)\n\t\t\tUInt32\tloadLibraryAAddr = (UInt32)GetProcAddress(GetModuleHandle(\"kernel32.dll\"), \"LoadLibraryA\");\n\n\t\t\t\/\/_MESSAGE(\"hookBase = %08X\", hookBase);\n\t\t\t\/\/_MESSAGE(\"loadLibraryAAddr = %08X\", loadLibraryAAddr);\n\n\t\t\tSIZE_T\tbytesWritten;\n\t\t\tWriteProcessMemory(process, (LPVOID)(hookBase + 5), dllPath, strlen(dllPath) + 1, &bytesWritten);\n\n\t\t\tUInt8\thookCode[5];\n\n\t\t\thookCode[0] = 0xE9;\n\t\t\t*((UInt32 *)&hookCode[1]) = loadLibraryAAddr - (hookBase + 5);\n\n\t\t\tWriteProcessMemory(process, (LPVOID)(hookBase), hookCode, sizeof(hookCode), &bytesWritten);\n\n\t\t\t\/\/ So, if we are attaching to an existing process, all of its threads should have already been suspended by the loader.\n\t\t\t\/\/ however, its quite possible that we suspended the threads inside a critical section, and we'll have problems either\n\t\t\t\/\/ creating the hook thread or waiting for it to exit.\n\t\t\t\/\/ So what we'll do is wait for a bit on the hook thread, and if we timeout, resume all threads in the target process for a brief period,\n\t\t\t\/\/ then resuspend them. Then resume our hook thread and try again. Do this some number of times and hopefully we'll be successful. \n\t\t\t\/\/ Its basically a jackhammer, and it can fail (especially if our hook thread does a bunch of slow initialization stuff), but it\n\t\t\t\/\/ usually succeeds.\n\n\t\t\tconst int SuspendSleepTime = 1;\n\n\t\t\tint hook_thread_attempts = 3;\n\t\t\tHANDLE hookThread = NULL;\n\t\t\tbool hookThreadValid = false;\n\t\t\twhile (!hookThreadValid && hook_thread_attempts > 0) {\n\t\t\t\thook_thread_attempts--;\n\t\t\t\thookThread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)hookBase, (void *)(hookBase + 5), 0, NULL);\n\t\t\t\thookThreadValid = hookThread && hookThread != INVALID_HANDLE_VALUE;\n\t\t\t\tif (!hookThreadValid) {\n\t\t\t\t\tUtil::Log(\"Failed to create hook thread (%d more attempts)\\n\", hook_thread_attempts);\n\t\t\t\t\tSuspendProcessThreads(processId, false);\n\t\t\t\t\tSleep(SuspendSleepTime);\n\t\t\t\t\tSuspendProcessThreads(processId, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hookThreadValid)\n\t\t\t{\n\t\t\t\tResumeThread(hookThread);\n\n\t\t\t\tDWORD waitTimeout;\n\t\t\t\tint MaxHookAttempts;\n\t\t\t\tif (processWasLaunched) {\n\t\t\t\t\twaitTimeout = INFINITE;\n\t\t\t\t\tMaxHookAttempts = 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twaitTimeout = 500;\n\t\t\t\t\t\/\/ Note, if you need to debug injection (via attaching during SpinWhileFileExists),\n\t\t\t\t\t\/\/ set this to a large number \n\t\t\t\t\t\/\/ to prevent the loader from bailing and aborting\n\t\t\t\t\t\/\/ during the time it takes you to attach.\n\t\t\t\t\t\/\/ 100 attempts at 500 timeout = about 50 seconds of waiting.\n\t\t\t\t\t\/\/ Don't use waitTimeout INFINITE as above, it will deadlock.\n\t\t\t\t\tMaxHookAttempts = 25; \n\t\t\t\t}\n\t\t\t\t\t \n\t\t\t\tint attempt = 0;\n\n\t\t\t\tfor (attempt = 0; !result && attempt < MaxHookAttempts; ++attempt) {\n\t\t\t\t\tUtil::Log(\"Waiting for hook thread: attempt %d; timeout: %d\\n\", attempt, waitTimeout);\n\n\t\t\t\t\tswitch(WaitForSingleObject(hookThread, waitTimeout)) \/\/ g_options.m_threadTimeout\n\t\t\t\t\t{\n\t\t\t\t\t\tcase WAIT_OBJECT_0:\n\t\t\t\t\t\t\tUtil::Log(\"Hook Thread complete\\n\");\n\t\t\t\t\t\t\tresult = true;\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase WAIT_ABANDONED:\n\t\t\t\t\t\t\t_injectError = \"Hook Thread WAIT_ABANDONED\";\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase WAIT_TIMEOUT:\n\t\t\t\t\t\t\t\/\/ Possible lock contention.\n\t\t\t\t\t\t\t\/\/ Resume all threads, sleep for a bit then suspend them all again. Then resume hook thread and retry.\n\t\t\t\t\t\t\tUtil::Log(\"Timeout\\n\");\n\t\t\t\t\t\t\tSuspendProcessThreads(processId,false);\n\t\t\t\t\t\t\tSleep(SuspendSleepTime);\n\t\t\t\t\t\t\tSuspendProcessThreads(processId,true);\n\t\t\t\t\t\t\tResumeThread(hookThread);\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase WAIT_FAILED:\n\t\t\t\t\t\t\t_injectError = \"Hook Thread WAIT_FAILED\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t_injectError = \"Hook Thread Unknown wait state\";\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!result) {\n\t\t\t\t\t_injectError = \"Unable to complete hook thread after several attempts\";\n\t\t\t\t}\n\n\t\t\t\tCloseHandle(hookThread);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/http:\/\/stackoverflow.com\/questions\/3006229\/get-a-text-from-the-error-code-returns-from-the-getlasterror-function\n\t\t\t\tDWORD dwLastError = ::GetLastError();\n\t\t\t\tconst DWORD BufSize = 256;\n\t\t\t\tTCHAR lpBuffer[BufSize] = _T(\"?\");\n\t\t\t\tif(dwLastError != 0) \/\/ Don't want to see a \"operation done successfully\" error ;-)\n\t\t\t\t::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, \/\/ Its a system error\n NULL, \/\/ No string to be formatted needed\n dwLastError, \/\/ Hey Windows: Please explain this error!\n MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), \/\/ Do it in the standard language\n lpBuffer, \/\/ Put the message here\n BufSize-1, \/\/ Number of bytes to store the message\n NULL);\n\n\t\t\t\t_injectError = string(\"CreateRemoteThread failed: \") + string(lpBuffer);\n\t\t\t}\n\t\t\t\t\n\n\t\t\t\/\/ the size parameter must be 0 when using MEM_RELEASE (CodeAnalysis C6333)\n\t\t\tVirtualFreeEx(process, (LPVOID)hookBase, 0, MEM_RELEASE);\n\t\t}\n\t\telse\n\t\t\t_injectError = \"Process::InstallHook: couldn't allocate memory in target process\";\n\n\t\tCloseHandle(process);\n\t}\n\telse\n\t\t_injectError = \"Process::InstallHook: couldn't get process handle. You may need to run MMLoader as an adminstrator.\";\n\n\treturn result;\n}\n<commit_msg>MMLoader(CodeAnalysis): fix unlikely failure getting handle of kernel32.dll<commit_after>#include \"StdAfx.h\"\n#include \"Inject.h\"\n\n#include \"Util.h\"\n\n\/\/ Ripped from Oblivion Script Extender \n\/\/ http:\/\/obse.silverlock.org\/\n\/\/ The sordid thread-suspending logic in DoInjectDLL is my own dismal contribution for ModelMod\n\nextern BOOL SuspendProcessThreads(DWORD dwOwnerPID, bool suspend);\n\nInject::Inject(void)\n{\n}\n\n\nInject::~Inject(void)\n{\n}\n\nbool Inject::InjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)\n{\n\tbool\tresult = false;\n\n\t\/\/ wrap DLL injection in SEH, if it crashes print a message\n\t__try {\n\t\tresult = DoInjectDLL(processId, dllPath, processWasLaunched);\n\t}\n\t__except(EXCEPTION_EXECUTE_HANDLER)\n\t{\n\t\t_injectError = \"DLL injection failed. In most cases, this is caused by an overly paranoid software firewall or antivirus package. Disabling either of these may solve the problem.\";\n\t\tresult = false;\n\t}\n\n\treturn result;\n}\n\n\/*** jmp hook layout\n *\tE9 ## ## ## ##\tjmp LoadLibraryA\n *\t\t\t\t\t\toffset = LoadLibraryA - (base + 5)\n *\t<string>\t\tname of function\n ***\/\n\ntypedef unsigned int UInt32;\ntypedef unsigned char UInt8;\n\nbool Inject::DoInjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)\n{\n\tbool result = false; \/\/ assume failure\n\n\tHMODULE k32 = GetModuleHandle(\"kernel32.dll\");\n\tif (k32 == 0) {\n\t\t_injectError = \"Failed to obtain handle for kernel32.dll\";\n\t\treturn result;\n\t}\n\n\tHANDLE process = OpenProcess(\n\t\tPROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, processId);\n\tif(process)\n\t{\n\t\tUInt32\thookBase = (UInt32)VirtualAllocEx(process, NULL, 8192, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n\t\tif(hookBase)\n\t\t{\n\t\t\t\/\/ safe because kernel32 is loaded at the same address in all processes\n\t\t\t\/\/ (can change across restarts)\n\t\t\tUInt32\tloadLibraryAAddr = (UInt32)GetProcAddress(k32, \"LoadLibraryA\");\n\n\t\t\t\/\/_MESSAGE(\"hookBase = %08X\", hookBase);\n\t\t\t\/\/_MESSAGE(\"loadLibraryAAddr = %08X\", loadLibraryAAddr);\n\n\t\t\tSIZE_T\tbytesWritten;\n\t\t\tWriteProcessMemory(process, (LPVOID)(hookBase + 5), dllPath, strlen(dllPath) + 1, &bytesWritten);\n\n\t\t\tUInt8\thookCode[5];\n\n\t\t\thookCode[0] = 0xE9;\n\t\t\t*((UInt32 *)&hookCode[1]) = loadLibraryAAddr - (hookBase + 5);\n\n\t\t\tWriteProcessMemory(process, (LPVOID)(hookBase), hookCode, sizeof(hookCode), &bytesWritten);\n\n\t\t\t\/\/ So, if we are attaching to an existing process, all of its threads should have already been suspended by the loader.\n\t\t\t\/\/ however, its quite possible that we suspended the threads inside a critical section, and we'll have problems either\n\t\t\t\/\/ creating the hook thread or waiting for it to exit.\n\t\t\t\/\/ So what we'll do is wait for a bit on the hook thread, and if we timeout, resume all threads in the target process for a brief period,\n\t\t\t\/\/ then resuspend them. Then resume our hook thread and try again. Do this some number of times and hopefully we'll be successful. \n\t\t\t\/\/ Its basically a jackhammer, and it can fail (especially if our hook thread does a bunch of slow initialization stuff), but it\n\t\t\t\/\/ usually succeeds.\n\n\t\t\tconst int SuspendSleepTime = 1;\n\n\t\t\tint hook_thread_attempts = 3;\n\t\t\tHANDLE hookThread = NULL;\n\t\t\tbool hookThreadValid = false;\n\t\t\twhile (!hookThreadValid && hook_thread_attempts > 0) {\n\t\t\t\thook_thread_attempts--;\n\t\t\t\thookThread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)hookBase, (void *)(hookBase + 5), 0, NULL);\n\t\t\t\thookThreadValid = hookThread && hookThread != INVALID_HANDLE_VALUE;\n\t\t\t\tif (!hookThreadValid) {\n\t\t\t\t\tUtil::Log(\"Failed to create hook thread (%d more attempts)\\n\", hook_thread_attempts);\n\t\t\t\t\tSuspendProcessThreads(processId, false);\n\t\t\t\t\tSleep(SuspendSleepTime);\n\t\t\t\t\tSuspendProcessThreads(processId, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hookThreadValid)\n\t\t\t{\n\t\t\t\tResumeThread(hookThread);\n\n\t\t\t\tDWORD waitTimeout;\n\t\t\t\tint MaxHookAttempts;\n\t\t\t\tif (processWasLaunched) {\n\t\t\t\t\twaitTimeout = INFINITE;\n\t\t\t\t\tMaxHookAttempts = 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twaitTimeout = 500;\n\t\t\t\t\t\/\/ Note, if you need to debug injection (via attaching during SpinWhileFileExists),\n\t\t\t\t\t\/\/ set this to a large number \n\t\t\t\t\t\/\/ to prevent the loader from bailing and aborting\n\t\t\t\t\t\/\/ during the time it takes you to attach.\n\t\t\t\t\t\/\/ 100 attempts at 500 timeout = about 50 seconds of waiting.\n\t\t\t\t\t\/\/ Don't use waitTimeout INFINITE as above, it will deadlock.\n\t\t\t\t\tMaxHookAttempts = 25; \n\t\t\t\t}\n\t\t\t\t\t \n\t\t\t\tint attempt = 0;\n\n\t\t\t\tfor (attempt = 0; !result && attempt < MaxHookAttempts; ++attempt) {\n\t\t\t\t\tUtil::Log(\"Waiting for hook thread: attempt %d; timeout: %d\\n\", attempt, waitTimeout);\n\n\t\t\t\t\tswitch(WaitForSingleObject(hookThread, waitTimeout)) \/\/ g_options.m_threadTimeout\n\t\t\t\t\t{\n\t\t\t\t\t\tcase WAIT_OBJECT_0:\n\t\t\t\t\t\t\tUtil::Log(\"Hook Thread complete\\n\");\n\t\t\t\t\t\t\tresult = true;\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase WAIT_ABANDONED:\n\t\t\t\t\t\t\t_injectError = \"Hook Thread WAIT_ABANDONED\";\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase WAIT_TIMEOUT:\n\t\t\t\t\t\t\t\/\/ Possible lock contention.\n\t\t\t\t\t\t\t\/\/ Resume all threads, sleep for a bit then suspend them all again. Then resume hook thread and retry.\n\t\t\t\t\t\t\tUtil::Log(\"Timeout\\n\");\n\t\t\t\t\t\t\tSuspendProcessThreads(processId,false);\n\t\t\t\t\t\t\tSleep(SuspendSleepTime);\n\t\t\t\t\t\t\tSuspendProcessThreads(processId,true);\n\t\t\t\t\t\t\tResumeThread(hookThread);\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase WAIT_FAILED:\n\t\t\t\t\t\t\t_injectError = \"Hook Thread WAIT_FAILED\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t_injectError = \"Hook Thread Unknown wait state\";\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!result) {\n\t\t\t\t\t_injectError = \"Unable to complete hook thread after several attempts\";\n\t\t\t\t}\n\n\t\t\t\tCloseHandle(hookThread);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/http:\/\/stackoverflow.com\/questions\/3006229\/get-a-text-from-the-error-code-returns-from-the-getlasterror-function\n\t\t\t\tDWORD dwLastError = ::GetLastError();\n\t\t\t\tconst DWORD BufSize = 256;\n\t\t\t\tTCHAR lpBuffer[BufSize] = _T(\"?\");\n\t\t\t\tif(dwLastError != 0) \/\/ Don't want to see a \"operation done successfully\" error ;-)\n\t\t\t\t::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, \/\/ Its a system error\n NULL, \/\/ No string to be formatted needed\n dwLastError, \/\/ Hey Windows: Please explain this error!\n MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), \/\/ Do it in the standard language\n lpBuffer, \/\/ Put the message here\n BufSize-1, \/\/ Number of bytes to store the message\n NULL);\n\n\t\t\t\t_injectError = string(\"CreateRemoteThread failed: \") + string(lpBuffer);\n\t\t\t}\n\t\t\t\t\n\n\t\t\t\/\/ the size parameter must be 0 when using MEM_RELEASE (CodeAnalysis C6333)\n\t\t\tVirtualFreeEx(process, (LPVOID)hookBase, 0, MEM_RELEASE);\n\t\t}\n\t\telse\n\t\t\t_injectError = \"Process::InstallHook: couldn't allocate memory in target process\";\n\n\t\tCloseHandle(process);\n\t}\n\telse\n\t\t_injectError = \"Process::InstallHook: couldn't get process handle. You may need to run MMLoader as an adminstrator.\";\n\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"susi\/duktape\/DuktapeEngine.h\"\n\nstd::string Susi::Duktape::susiJS = R\"SUSIJS(\n\nvar susi = { \n _consumerCallbacks: [], \n _processorCallbacks: [],\n\n _processorTopicCounter: {},\n _consumerTopicCounter: {},\n\n _publishCallbacks: {},\n _processorProcesses: {},\n\n _processed: [],\n\n registerConsumer: function(topic,callback) {\n var id = this._genID(); \n this._consumerCallbacks.push({topic: topic, callback: callback, id: id}); \n var count = this._consumerTopicCounter[topic] || 0;\n count++;\n this._consumerTopicCounter[topic] = count;\n if(count == 1){ \n _registerConsumer(topic); \n } \n return id; \n },\n\n registerProcessor: function(topic,callback) { \n var id = this._genID(); \n this._processorCallbacks.push({topic: topic, callback: callback, id: id}); \n var count = this._processorTopicCounter[topic] || 0;\n count++;\n this._processorTopicCounter[topic] = count;\n if(count == 1){ \n _registerProcessor(topic);\n } \n return id; \n },\n\n unregisterConsumer: function(id){ \n for(var i=0;i<this._consumerCallbacks;i++){\n if(this._consumerCallbacks[i].id === id){\n var topic = this._consumerCallbacks[i].topic;\n this._consumerCallbacks.splice(i,1);\n var count = this._consumerTopicCounter[topic];\n count--;\n if(count === 0){\n delete(this._consumerTopicCounter[topic]);\n _unregisterConsumer(topic);\n }else{\n this._consumerTopicCounter[topic] = count;\n }\n return true;\n }\n }\n return false; \n },\n\n unregisterProcessor: function(id){ \n for(var i=0;i<this._processorCallbacks;i++){\n if(this._processorCallbacks[i].id === id){\n var topic = this._processorCallbacks[i].topic;\n this._processorCallbacks.splice(i,1);\n var count = this._processorTopicCounter[topic];\n count--;\n if(count === 0){\n delete(this._processorTopicCounter[topic]);\n _unregisterProcessor(topic);\n }else{\n this._processorTopicCounter[topic] = count;\n }\n return true;\n }\n }\n return false; \n },\n\n publish: function(event,callback) { \n if(event.id === undefined){ \n event.id = ''+this._genID(); \n } \n if(callback !== undefined) { \n this._publishCallbacks[event.id] = callback; \n }\n _publish(JSON.stringify(event)); \n },\n\n ack: function(event){\n var process = this._processorProcesses[event.id];\n if(process.next >= process.processors.length){\n delete this._processorProcesses[event.id];\n _ack(JSON.stringify(event)); \n }else{\n process.next++;\n process.processors[process.next-1](event);\n }\n },\n\n dismiss: function(event){ \n delete(this._processorProcesses[event.id]);\n _dismiss(JSON.stringify(event));\n },\n\n \/\/used by js to interact with c++ part\n _processConsumerEvent: function(event,topic){\n event = JSON.parse(event);\n for(var i=0;i<this._consumerCallbacks.length;i++){\n if(topic.match(this._consumerCallbacks[i].topic)){\n this._consumerCallbacks[i].callback(event);\n }\n }\n },\n\n _processProcessorEvent: function(event,topic){\n event = JSON.parse(event); \n if(this._processed.indexOf(event.id) !== -1){\n _ack(JSON.stringify(event));\n return;\n }\n this._processed.push(event.id);\n if(this._processed.length > 64){\n this._processed.splice(0,1);\n }\n Duktape.fin(event,function(event){ \n susi.ack(event); \n });\n var process = {\n processors: [],\n next: 0\n };\n\n for (var i = 0; i<this._processorCallbacks.length; i++) {\n if(event.topic.match(this._processorCallbacks[i].topic)){\n process.processors.push(this._processorCallbacks[i].callback);\n } \n }\n\n this._processorProcesses[event.id] = process;\n this.ack(event);\n Duktape.gc(); \n },\n\n _processAck: function(event){ \n event = JSON.parse(event); \n var cb = this._publishCallbacks[event.id]; \n if(cb !== undefined) { \n cb(event); \n delete this._publishCallbacks[event.id]; \n }\n },\n\n _genID: function(){ \n return Math.floor(Math.random()*1000000000000); \n } \n}; \n\n\/\/called by c++ part\nfunction _processConsumerEvent(event,topic){ \n susi._processConsumerEvent(event,topic); \n}\n\nfunction _processProcessorEvent(event,topic){ \n susi._processProcessorEvent(event,topic) \n}\n\nfunction _processAck(event){ \n susi._processAck(event); \n}\n\nvar duktapeLogger = new Duktape.Logger('susi-js');\nduktapeLogger.l = 0;\n\nvar console = {\n _prepareArguments: function(args){\n var newArgs = [];\n for(var i=0;i<args.length;i++){\n if(typeof args[i] === 'object'){\n newArgs.push(Duktape.enc('jx',args[i]));\n }else{\n newArgs.push(args[i]);\n }\n }\n return newArgs;\n },\n _getLine: function(){\n var e = new Error(arguments);\n return e.stack.split('\\n')[3].trim().split(' ')[1];\n },\n log: function(){\n duktapeLogger.info.apply(duktapeLogger,this._prepareArguments(arguments));\n },\n debug: function(){\n duktapeLogger.n = 'susi-js: '+this._getLine();\n duktapeLogger.debug.apply(duktapeLogger,this._prepareArguments(arguments));\n duktapeLogger.n = 'susi-js';\n },\n error: function(){\n duktapeLogger.n = 'susi-js: '+this._getLine();\n duktapeLogger.error.apply(duktapeLogger,this._prepareArguments(arguments));\n duktapeLogger.n = 'susi-js';\n }\n};\n\n)SUSIJS\";\n<commit_msg>[susi-duktape] fixed header location;<commit_after>#include \"susi\/DuktapeEngine.h\"\n\nstd::string Susi::Duktape::susiJS = R\"SUSIJS(\n\nvar susi = { \n _consumerCallbacks: [], \n _processorCallbacks: [],\n\n _processorTopicCounter: {},\n _consumerTopicCounter: {},\n\n _publishCallbacks: {},\n _processorProcesses: {},\n\n _processed: [],\n\n registerConsumer: function(topic,callback) {\n var id = this._genID(); \n this._consumerCallbacks.push({topic: topic, callback: callback, id: id}); \n var count = this._consumerTopicCounter[topic] || 0;\n count++;\n this._consumerTopicCounter[topic] = count;\n if(count == 1){ \n _registerConsumer(topic); \n } \n return id; \n },\n\n registerProcessor: function(topic,callback) { \n var id = this._genID(); \n this._processorCallbacks.push({topic: topic, callback: callback, id: id}); \n var count = this._processorTopicCounter[topic] || 0;\n count++;\n this._processorTopicCounter[topic] = count;\n if(count == 1){ \n _registerProcessor(topic);\n } \n return id; \n },\n\n unregisterConsumer: function(id){ \n for(var i=0;i<this._consumerCallbacks;i++){\n if(this._consumerCallbacks[i].id === id){\n var topic = this._consumerCallbacks[i].topic;\n this._consumerCallbacks.splice(i,1);\n var count = this._consumerTopicCounter[topic];\n count--;\n if(count === 0){\n delete(this._consumerTopicCounter[topic]);\n _unregisterConsumer(topic);\n }else{\n this._consumerTopicCounter[topic] = count;\n }\n return true;\n }\n }\n return false; \n },\n\n unregisterProcessor: function(id){ \n for(var i=0;i<this._processorCallbacks;i++){\n if(this._processorCallbacks[i].id === id){\n var topic = this._processorCallbacks[i].topic;\n this._processorCallbacks.splice(i,1);\n var count = this._processorTopicCounter[topic];\n count--;\n if(count === 0){\n delete(this._processorTopicCounter[topic]);\n _unregisterProcessor(topic);\n }else{\n this._processorTopicCounter[topic] = count;\n }\n return true;\n }\n }\n return false; \n },\n\n publish: function(event,callback) { \n if(event.id === undefined){ \n event.id = ''+this._genID(); \n } \n if(callback !== undefined) { \n this._publishCallbacks[event.id] = callback; \n }\n _publish(JSON.stringify(event)); \n },\n\n ack: function(event){\n var process = this._processorProcesses[event.id];\n if(process.next >= process.processors.length){\n delete this._processorProcesses[event.id];\n _ack(JSON.stringify(event)); \n }else{\n process.next++;\n process.processors[process.next-1](event);\n }\n },\n\n dismiss: function(event){ \n delete(this._processorProcesses[event.id]);\n _dismiss(JSON.stringify(event));\n },\n\n \/\/used by js to interact with c++ part\n _processConsumerEvent: function(event,topic){\n event = JSON.parse(event);\n for(var i=0;i<this._consumerCallbacks.length;i++){\n if(topic.match(this._consumerCallbacks[i].topic)){\n this._consumerCallbacks[i].callback(event);\n }\n }\n },\n\n _processProcessorEvent: function(event,topic){\n event = JSON.parse(event); \n if(this._processed.indexOf(event.id) !== -1){\n _ack(JSON.stringify(event));\n return;\n }\n this._processed.push(event.id);\n if(this._processed.length > 64){\n this._processed.splice(0,1);\n }\n Duktape.fin(event,function(event){ \n susi.ack(event); \n });\n var process = {\n processors: [],\n next: 0\n };\n\n for (var i = 0; i<this._processorCallbacks.length; i++) {\n if(event.topic.match(this._processorCallbacks[i].topic)){\n process.processors.push(this._processorCallbacks[i].callback);\n } \n }\n\n this._processorProcesses[event.id] = process;\n this.ack(event);\n Duktape.gc(); \n },\n\n _processAck: function(event){ \n event = JSON.parse(event); \n var cb = this._publishCallbacks[event.id]; \n if(cb !== undefined) { \n cb(event); \n delete this._publishCallbacks[event.id]; \n }\n },\n\n _genID: function(){ \n return Math.floor(Math.random()*1000000000000); \n } \n}; \n\n\/\/called by c++ part\nfunction _processConsumerEvent(event,topic){ \n susi._processConsumerEvent(event,topic); \n}\n\nfunction _processProcessorEvent(event,topic){ \n susi._processProcessorEvent(event,topic) \n}\n\nfunction _processAck(event){ \n susi._processAck(event); \n}\n\nvar duktapeLogger = new Duktape.Logger('susi-js');\nduktapeLogger.l = 0;\n\nvar console = {\n _prepareArguments: function(args){\n var newArgs = [];\n for(var i=0;i<args.length;i++){\n if(typeof args[i] === 'object'){\n newArgs.push(Duktape.enc('jx',args[i]));\n }else{\n newArgs.push(args[i]);\n }\n }\n return newArgs;\n },\n _getLine: function(){\n var e = new Error(arguments);\n return e.stack.split('\\n')[3].trim().split(' ')[1];\n },\n log: function(){\n duktapeLogger.info.apply(duktapeLogger,this._prepareArguments(arguments));\n },\n debug: function(){\n duktapeLogger.n = 'susi-js: '+this._getLine();\n duktapeLogger.debug.apply(duktapeLogger,this._prepareArguments(arguments));\n duktapeLogger.n = 'susi-js';\n },\n error: function(){\n duktapeLogger.n = 'susi-js: '+this._getLine();\n duktapeLogger.error.apply(duktapeLogger,this._prepareArguments(arguments));\n duktapeLogger.n = 'susi-js';\n }\n};\n\n)SUSIJS\";\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: textdoc.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 21:02:18 $\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 _TEXTDOC_HXX\n#define _TEXTDOC_HXX\n\n#ifndef _SVARRAY_HXX\n#include <svarray.hxx>\n#endif\n\n#ifndef _TEXTDATA_HXX\n#include <textdata.hxx>\n#endif\n\n#ifndef _TXTATTR_HXX\n#include <txtattr.hxx>\n#endif\n\n#include <tools\/debug.hxx>\n\n#ifndef _STRING_HXX \/\/autogen\n#include <tools\/string.hxx>\n#endif\n\n#ifndef _LIST_HXX \/\/autogen\n#include <tools\/list.hxx>\n#endif\n\ntypedef TextCharAttrib* TextCharAttribPtr;\nSV_DECL_PTRARR_DEL( TextCharAttribs, TextCharAttribPtr, 0, 4 )\n\nclass TextCharAttribList : private TextCharAttribs\n{\nprivate:\n BOOL mbHasEmptyAttribs;\n\n TextCharAttribList( const TextCharAttribList& ) : TextCharAttribs() {}\n\npublic:\n TextCharAttribList();\n ~TextCharAttribList();\n\n void Clear( BOOL bDestroyAttribs );\n USHORT Count() const { return TextCharAttribs::Count(); }\n\n TextCharAttrib* GetAttrib( USHORT n ) const { return TextCharAttribs::GetObject( n ); }\n void RemoveAttrib( USHORT n ) { TextCharAttribs::Remove( n, 1 ); }\n\n void InsertAttrib( TextCharAttrib* pAttrib );\n\n void DeleteEmptyAttribs();\n void ResortAttribs();\n\n BOOL HasEmptyAttribs() const { return mbHasEmptyAttribs; }\n BOOL& HasEmptyAttribs() { return mbHasEmptyAttribs; }\n\n TextCharAttrib* FindAttrib( USHORT nWhich, USHORT nPos );\n TextCharAttrib* FindNextAttrib( USHORT nWhich, USHORT nFromPos, USHORT nMaxPos = 0xFFFF ) const;\n TextCharAttrib* FindEmptyAttrib( USHORT nWhich, USHORT nPos );\n BOOL HasAttrib( USHORT nWhich ) const;\n BOOL HasBoundingAttrib( USHORT nBound );\n\n#ifdef DBG_UTIL\n BOOL DbgCheckAttribs();\n#endif\n};\n\n\nclass TextNode\n{\nprivate:\n String maText;\n TextCharAttribList maCharAttribs;\n\n TextNode( const TextNode& ) {;}\nprotected:\n void ExpandAttribs( USHORT nIndex, USHORT nNewChars );\n void CollapsAttribs( USHORT nIndex, USHORT nDelChars );\n\npublic:\n TextNode( const String& rText );\n\n\n const String& GetText() const { return maText; }\n\n const TextCharAttribList& GetCharAttribs() const { return maCharAttribs; }\n TextCharAttribList& GetCharAttribs() { return maCharAttribs; }\n\n void InsertText( USHORT nPos, const String& rText );\n void InsertText( USHORT nPos, sal_Unicode c );\n void RemoveText( USHORT nPos, USHORT nChars );\n\n TextNode* Split( USHORT nPos, BOOL bKeepEndigAttribs );\n void Append( const TextNode& rNode );\n};\n\nclass TextDoc\n{\nprivate:\n ToolsList<TextNode*> maTextNodes;\n USHORT mnLeftMargin;\n\nprotected:\n void DestroyTextNodes();\n\npublic:\n TextDoc();\n ~TextDoc();\n\n void Clear();\n\n ToolsList<TextNode*>& GetNodes() { return maTextNodes; }\n const ToolsList<TextNode*>& GetNodes() const { return maTextNodes; }\n\n TextPaM RemoveChars( const TextPaM& rPaM, USHORT nChars );\n TextPaM InsertText( const TextPaM& rPaM, sal_Unicode c );\n TextPaM InsertText( const TextPaM& rPaM, const String& rStr );\n\n TextPaM InsertParaBreak( const TextPaM& rPaM, BOOL bKeepEndingAttribs );\n TextPaM ConnectParagraphs( TextNode* pLeft, TextNode* pRight );\n\n ULONG GetTextLen( const sal_Unicode* pSep, const TextSelection* pSel = NULL ) const;\n String GetText( const sal_Unicode* pSep ) const;\n String GetText( ULONG nPara ) const;\n\n void SetLeftMargin( USHORT n ) { mnLeftMargin = n; }\n USHORT GetLeftMargin() const { return mnLeftMargin; }\n\n\/\/ BOOL RemoveAttribs( TextNode* pNode, USHORT nStart, USHORT nEnd ), USHORT nWhich = 0 );\n\/\/ BOOL RemoveAttribs( TextNode* pNode, USHORT nStart, USHORT nEnd, TextCharAttrib*& rpStarting, TextCharAttrib*& rpEnding, USHORT nWhich = 0 );\n\/\/ void InsertAttrib( const EditCharAttrib* pAttr );\n\/\/ void InsertAttribInSelection( const EditCharAttrib* pAttr );\n\/\/ void FindAttribs( TextNode* pNode, USHORT nStartPos, USHORT nEndPos, SfxItemSet& rCurSet );\n\n BOOL IsValidPaM( const TextPaM& rPaM );\n};\n\n#endif \/\/ _TEXTDOC_HXX\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.298); FILE MERGED 2007\/06\/04 13:31:35 vg 1.4.298.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: textdoc.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 21:31:18 $\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 _TEXTDOC_HXX\n#define _TEXTDOC_HXX\n\n#ifndef _SVARRAY_HXX\n#include <svtools\/svarray.hxx>\n#endif\n\n#ifndef _TEXTDATA_HXX\n#include <svtools\/textdata.hxx>\n#endif\n\n#ifndef _TXTATTR_HXX\n#include <txtattr.hxx>\n#endif\n\n#include <tools\/debug.hxx>\n\n#ifndef _STRING_HXX \/\/autogen\n#include <tools\/string.hxx>\n#endif\n\n#ifndef _LIST_HXX \/\/autogen\n#include <tools\/list.hxx>\n#endif\n\ntypedef TextCharAttrib* TextCharAttribPtr;\nSV_DECL_PTRARR_DEL( TextCharAttribs, TextCharAttribPtr, 0, 4 )\n\nclass TextCharAttribList : private TextCharAttribs\n{\nprivate:\n BOOL mbHasEmptyAttribs;\n\n TextCharAttribList( const TextCharAttribList& ) : TextCharAttribs() {}\n\npublic:\n TextCharAttribList();\n ~TextCharAttribList();\n\n void Clear( BOOL bDestroyAttribs );\n USHORT Count() const { return TextCharAttribs::Count(); }\n\n TextCharAttrib* GetAttrib( USHORT n ) const { return TextCharAttribs::GetObject( n ); }\n void RemoveAttrib( USHORT n ) { TextCharAttribs::Remove( n, 1 ); }\n\n void InsertAttrib( TextCharAttrib* pAttrib );\n\n void DeleteEmptyAttribs();\n void ResortAttribs();\n\n BOOL HasEmptyAttribs() const { return mbHasEmptyAttribs; }\n BOOL& HasEmptyAttribs() { return mbHasEmptyAttribs; }\n\n TextCharAttrib* FindAttrib( USHORT nWhich, USHORT nPos );\n TextCharAttrib* FindNextAttrib( USHORT nWhich, USHORT nFromPos, USHORT nMaxPos = 0xFFFF ) const;\n TextCharAttrib* FindEmptyAttrib( USHORT nWhich, USHORT nPos );\n BOOL HasAttrib( USHORT nWhich ) const;\n BOOL HasBoundingAttrib( USHORT nBound );\n\n#ifdef DBG_UTIL\n BOOL DbgCheckAttribs();\n#endif\n};\n\n\nclass TextNode\n{\nprivate:\n String maText;\n TextCharAttribList maCharAttribs;\n\n TextNode( const TextNode& ) {;}\nprotected:\n void ExpandAttribs( USHORT nIndex, USHORT nNewChars );\n void CollapsAttribs( USHORT nIndex, USHORT nDelChars );\n\npublic:\n TextNode( const String& rText );\n\n\n const String& GetText() const { return maText; }\n\n const TextCharAttribList& GetCharAttribs() const { return maCharAttribs; }\n TextCharAttribList& GetCharAttribs() { return maCharAttribs; }\n\n void InsertText( USHORT nPos, const String& rText );\n void InsertText( USHORT nPos, sal_Unicode c );\n void RemoveText( USHORT nPos, USHORT nChars );\n\n TextNode* Split( USHORT nPos, BOOL bKeepEndigAttribs );\n void Append( const TextNode& rNode );\n};\n\nclass TextDoc\n{\nprivate:\n ToolsList<TextNode*> maTextNodes;\n USHORT mnLeftMargin;\n\nprotected:\n void DestroyTextNodes();\n\npublic:\n TextDoc();\n ~TextDoc();\n\n void Clear();\n\n ToolsList<TextNode*>& GetNodes() { return maTextNodes; }\n const ToolsList<TextNode*>& GetNodes() const { return maTextNodes; }\n\n TextPaM RemoveChars( const TextPaM& rPaM, USHORT nChars );\n TextPaM InsertText( const TextPaM& rPaM, sal_Unicode c );\n TextPaM InsertText( const TextPaM& rPaM, const String& rStr );\n\n TextPaM InsertParaBreak( const TextPaM& rPaM, BOOL bKeepEndingAttribs );\n TextPaM ConnectParagraphs( TextNode* pLeft, TextNode* pRight );\n\n ULONG GetTextLen( const sal_Unicode* pSep, const TextSelection* pSel = NULL ) const;\n String GetText( const sal_Unicode* pSep ) const;\n String GetText( ULONG nPara ) const;\n\n void SetLeftMargin( USHORT n ) { mnLeftMargin = n; }\n USHORT GetLeftMargin() const { return mnLeftMargin; }\n\n\/\/ BOOL RemoveAttribs( TextNode* pNode, USHORT nStart, USHORT nEnd ), USHORT nWhich = 0 );\n\/\/ BOOL RemoveAttribs( TextNode* pNode, USHORT nStart, USHORT nEnd, TextCharAttrib*& rpStarting, TextCharAttrib*& rpEnding, USHORT nWhich = 0 );\n\/\/ void InsertAttrib( const EditCharAttrib* pAttr );\n\/\/ void InsertAttribInSelection( const EditCharAttrib* pAttr );\n\/\/ void FindAttribs( TextNode* pNode, USHORT nStartPos, USHORT nEndPos, SfxItemSet& rCurSet );\n\n BOOL IsValidPaM( const TextPaM& rPaM );\n};\n\n#endif \/\/ _TEXTDOC_HXX\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: rtfout.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-05-10 07:55:10 $\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 _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _RTL_STRING_HXX_\n#include <rtl\/string.hxx>\n#endif\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _RTFKEYWD_HXX\n#include <rtfkeywd.hxx>\n#endif\n#ifndef _RTFOUT_HXX\n#include <rtfout.hxx>\n#endif\n\nusing namespace rtl;\n\n#if defined(MAC)\nconst sal_Char RTFOutFuncs::sNewLine = '\\015';\n#elif defined(UNX)\nconst sal_Char RTFOutFuncs::sNewLine = '\\012';\n#else\nconst sal_Char __FAR_DATA RTFOutFuncs::sNewLine[] = \"\\015\\012\";\n#endif\n\n\nSvStream& RTFOutFuncs::Out_Char(SvStream& rStream, sal_Unicode c,\n int *pUCMode, rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n const sal_Char* pStr = 0;\n switch (c)\n {\n case 0x1:\n case 0x2:\n \/\/ this are control character of our textattributes and will never be\n \/\/ written\n break;\n case 0xA0:\n rStream << \"\\\\~\";\n break;\n case 0xAD:\n rStream << \"\\\\-\";\n break;\n case 0x2011:\n rStream << \"\\\\_\";\n break;\n case '\\n':\n pStr = sRTF_LINE;\n break;\n case '\\t':\n pStr = sRTF_TAB;\n break;\n default:\n if(!bWriteHelpFile)\n {\n switch(c)\n {\n case 149:\n pStr = sRTF_BULLET;\n break;\n case 150:\n pStr = sRTF_ENDASH;\n break;\n case 151:\n pStr = sRTF_EMDASH;\n break;\n case 145:\n pStr = sRTF_LQUOTE;\n break;\n case 146:\n pStr = sRTF_RQUOTE;\n break;\n case 147:\n pStr = sRTF_LDBLQUOTE;\n break;\n case 148:\n pStr = sRTF_RDBLQUOTE;\n break;\n }\n\n if (pStr)\n break;\n }\n\n switch (c)\n {\n case '\\\\':\n case '}':\n case '{':\n rStream << '\\\\' << (sal_Char)c;\n break;\n default:\n if (c >= ' ' && c <= '~')\n rStream << (sal_Char)c;\n else\n {\n \/\/If we can't convert to the dest encoding, or if\n \/\/its an uncommon multibyte sequence which most\n \/\/readers won't be able to handle correctly, then\n \/\/If we can't convert to the dest encoding, then\n \/\/export as unicode\n OUString sBuf(&c, 1);\n OString sConverted;\n sal_uInt32 nFlags =\n RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |\n RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR;\n bool bWriteAsUnicode = !(sBuf.convertToString(&sConverted,\n eDestEnc, nFlags))\n || (RTL_TEXTENCODING_UTF8==eDestEnc); \/\/ #i43933# do not export UTF-8 chars in RTF;\n if (bWriteAsUnicode)\n {\n sBuf.convertToString(&sConverted,\n eDestEnc, OUSTRING_TO_OSTRING_CVTFLAGS);\n }\n const sal_Int32 nLen = sConverted.getLength();\n\n if (bWriteAsUnicode && pUCMode)\n {\n \/\/ then write as unicode - character\n if (*pUCMode != nLen)\n {\n rStream << \"\\\\uc\" << ByteString::CreateFromInt32(nLen).GetBuffer() << \" \"; \/\/ #i47831# add an additional whitespace, so that \"document whitespaces\" are not ignored.;\n *pUCMode = nLen;\n }\n ByteString sNo(ByteString::CreateFromInt32(c));\n rStream << \"\\\\u\" << sNo.GetBuffer();\n }\n\n for (sal_Int32 nI = 0; nI < nLen; ++nI)\n {\n rStream << \"\\\\'\";\n Out_Hex(rStream, sConverted.getStr()[nI], 2);\n }\n }\n break;\n }\n break;\n }\n\n if (pStr)\n rStream << pStr << ' ';\n\n return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_String( SvStream& rStream, const String& rStr,\n rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n int nUCMode = 1;\n for (xub_StrLen n = 0; n < rStr.Len(); ++n)\n Out_Char(rStream, rStr.GetChar(n), &nUCMode, eDestEnc, bWriteHelpFile);\n if (nUCMode != 1)\n rStream << \"\\\\uc1\"<< \" \"; \/\/ #i47831# add an additional whitespace, so that \"document whitespaces\" are not ignored.;\n return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_Fontname(SvStream& rStream, const String& rStr,\n rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n \/\/Fontnames in word have a quirk in that \\uc and usage of ansi replacement\n \/\/chars after a \\u don't work and in wordpad \\u doesn't work, so we are\n \/\/left with forcing ansi characters only for fontnames\n for (xub_StrLen n = 0; n < rStr.Len(); ++n)\n Out_Char(rStream, rStr.GetChar(n), 0, eDestEnc, bWriteHelpFile);\n return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_Hex( SvStream& rStream, ULONG nHex, BYTE nLen )\n{\n sal_Char aNToABuf[] = \"0000000000000000\";\n\n DBG_ASSERT( nLen < sizeof(aNToABuf), \"zu viele Stellen\" );\n if( nLen >= sizeof(aNToABuf) )\n nLen = (sizeof(aNToABuf)-1);\n\n \/\/ Pointer an das Bufferende setzen\n sal_Char* pStr = aNToABuf + (sizeof(aNToABuf)-1);\n for( BYTE n = 0; n < nLen; ++n )\n {\n *(--pStr) = (sal_Char)(nHex & 0xf ) + 48;\n if( *pStr > '9' )\n *pStr += 39;\n nHex >>= 4;\n }\n return rStream << pStr;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.7.114); FILE MERGED 2005\/09\/05 14:54:19 rt 1.7.114.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rtfout.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 16:50:06 $\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 _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _RTL_STRING_HXX_\n#include <rtl\/string.hxx>\n#endif\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _RTFKEYWD_HXX\n#include <rtfkeywd.hxx>\n#endif\n#ifndef _RTFOUT_HXX\n#include <rtfout.hxx>\n#endif\n\nusing namespace rtl;\n\n#if defined(MAC)\nconst sal_Char RTFOutFuncs::sNewLine = '\\015';\n#elif defined(UNX)\nconst sal_Char RTFOutFuncs::sNewLine = '\\012';\n#else\nconst sal_Char __FAR_DATA RTFOutFuncs::sNewLine[] = \"\\015\\012\";\n#endif\n\n\nSvStream& RTFOutFuncs::Out_Char(SvStream& rStream, sal_Unicode c,\n int *pUCMode, rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n const sal_Char* pStr = 0;\n switch (c)\n {\n case 0x1:\n case 0x2:\n \/\/ this are control character of our textattributes and will never be\n \/\/ written\n break;\n case 0xA0:\n rStream << \"\\\\~\";\n break;\n case 0xAD:\n rStream << \"\\\\-\";\n break;\n case 0x2011:\n rStream << \"\\\\_\";\n break;\n case '\\n':\n pStr = sRTF_LINE;\n break;\n case '\\t':\n pStr = sRTF_TAB;\n break;\n default:\n if(!bWriteHelpFile)\n {\n switch(c)\n {\n case 149:\n pStr = sRTF_BULLET;\n break;\n case 150:\n pStr = sRTF_ENDASH;\n break;\n case 151:\n pStr = sRTF_EMDASH;\n break;\n case 145:\n pStr = sRTF_LQUOTE;\n break;\n case 146:\n pStr = sRTF_RQUOTE;\n break;\n case 147:\n pStr = sRTF_LDBLQUOTE;\n break;\n case 148:\n pStr = sRTF_RDBLQUOTE;\n break;\n }\n\n if (pStr)\n break;\n }\n\n switch (c)\n {\n case '\\\\':\n case '}':\n case '{':\n rStream << '\\\\' << (sal_Char)c;\n break;\n default:\n if (c >= ' ' && c <= '~')\n rStream << (sal_Char)c;\n else\n {\n \/\/If we can't convert to the dest encoding, or if\n \/\/its an uncommon multibyte sequence which most\n \/\/readers won't be able to handle correctly, then\n \/\/If we can't convert to the dest encoding, then\n \/\/export as unicode\n OUString sBuf(&c, 1);\n OString sConverted;\n sal_uInt32 nFlags =\n RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |\n RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR;\n bool bWriteAsUnicode = !(sBuf.convertToString(&sConverted,\n eDestEnc, nFlags))\n || (RTL_TEXTENCODING_UTF8==eDestEnc); \/\/ #i43933# do not export UTF-8 chars in RTF;\n if (bWriteAsUnicode)\n {\n sBuf.convertToString(&sConverted,\n eDestEnc, OUSTRING_TO_OSTRING_CVTFLAGS);\n }\n const sal_Int32 nLen = sConverted.getLength();\n\n if (bWriteAsUnicode && pUCMode)\n {\n \/\/ then write as unicode - character\n if (*pUCMode != nLen)\n {\n rStream << \"\\\\uc\" << ByteString::CreateFromInt32(nLen).GetBuffer() << \" \"; \/\/ #i47831# add an additional whitespace, so that \"document whitespaces\" are not ignored.;\n *pUCMode = nLen;\n }\n ByteString sNo(ByteString::CreateFromInt32(c));\n rStream << \"\\\\u\" << sNo.GetBuffer();\n }\n\n for (sal_Int32 nI = 0; nI < nLen; ++nI)\n {\n rStream << \"\\\\'\";\n Out_Hex(rStream, sConverted.getStr()[nI], 2);\n }\n }\n break;\n }\n break;\n }\n\n if (pStr)\n rStream << pStr << ' ';\n\n return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_String( SvStream& rStream, const String& rStr,\n rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n int nUCMode = 1;\n for (xub_StrLen n = 0; n < rStr.Len(); ++n)\n Out_Char(rStream, rStr.GetChar(n), &nUCMode, eDestEnc, bWriteHelpFile);\n if (nUCMode != 1)\n rStream << \"\\\\uc1\"<< \" \"; \/\/ #i47831# add an additional whitespace, so that \"document whitespaces\" are not ignored.;\n return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_Fontname(SvStream& rStream, const String& rStr,\n rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n \/\/Fontnames in word have a quirk in that \\uc and usage of ansi replacement\n \/\/chars after a \\u don't work and in wordpad \\u doesn't work, so we are\n \/\/left with forcing ansi characters only for fontnames\n for (xub_StrLen n = 0; n < rStr.Len(); ++n)\n Out_Char(rStream, rStr.GetChar(n), 0, eDestEnc, bWriteHelpFile);\n return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_Hex( SvStream& rStream, ULONG nHex, BYTE nLen )\n{\n sal_Char aNToABuf[] = \"0000000000000000\";\n\n DBG_ASSERT( nLen < sizeof(aNToABuf), \"zu viele Stellen\" );\n if( nLen >= sizeof(aNToABuf) )\n nLen = (sizeof(aNToABuf)-1);\n\n \/\/ Pointer an das Bufferende setzen\n sal_Char* pStr = aNToABuf + (sizeof(aNToABuf)-1);\n for( BYTE n = 0; n < nLen; ++n )\n {\n *(--pStr) = (sal_Char)(nHex & 0xf ) + 48;\n if( *pStr > '9' )\n *pStr += 39;\n nHex >>= 4;\n }\n return rStream << pStr;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>when beforeFirst\/afterLast, there is no value, so none to notify<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"playercontrols.h\"\n\n#include <QBoxLayout>\n#include <QSlider>\n#include <QStyle>\n#include <QToolButton>\n#include <QComboBox>\n\n\/\/ constructor\nPlayerControls::PlayerControls(QWidget *parent) :\n QWidget(parent),\n playerState(QMediaPlayer::StoppedState),\n playerMuted(false),\n playButton(NULL),\n stopButton(NULL),\n nextButton(NULL),\n previousButton(NULL),\n muteButton(NULL),\n volumeSlider(NULL),\n rateBox(NULL)\n{\n playButton = new QToolButton(this);\n playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n connect(playButton, SIGNAL(clicked()), this, SLOT(playClicked()));\n\n stopButton = new QToolButton(this);\n stopButton->setIcon(style()->standardIcon(QStyle::SP_MediaStop));\n stopButton->setEnabled(false);\n connect(stopButton, SIGNAL(clicked()), this, SIGNAL(stop()));\n\n nextButton = new QToolButton(this);\n nextButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward));\n connect(nextButton, SIGNAL(clicked()), this, SIGNAL(next()));\n\n previousButton = new QToolButton(this);\n previousButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward));\n connect(previousButton, SIGNAL(clicked()), this, SIGNAL(previous()));\n\n muteButton = new QToolButton(this);\n muteButton->setIcon(style()->standardIcon(QStyle::SP_MediaVolume));\n connect(muteButton, SIGNAL(clicked()), this, SLOT(muteClicked()));\n\n volumeSlider = new QSlider(Qt::Horizontal, this);\n volumeSlider->setRange(0, 100);\n volumeSlider->setFixedSize(volumeSlider->sizeHint());\n connect(volumeSlider, SIGNAL(sliderMoved(int)), this, SIGNAL(changeVolume(int)));\n\n \/\/ playback rate box chooser\n \/* Works like the following:\n * 1) whenver the box is \"activiated\" - user choosing something, call updateRate()\n * 2) updateRate() calls changeRate() on playbackRate();\n * - playbackRate() is used to figure out which one is selected from the rateBox\n * 3) The changeRate() signal is caught by the setPlaybackRate() slot.\n * 4) The argment to setPlaybackRate() is the index of the item chosen. The slot then\n * compares the index with the values in the box and set it.\n *\/\n rateBox = new QComboBox(this);\n rateBox->addItem(\"0.5x\", QVariant(0.5));\n rateBox->addItem(\"1.0x\", QVariant(1.0));\n rateBox->addItem(\"2.0x\", QVariant(2.0));\n rateBox->setCurrentIndex(1);\n rateBox->setFixedSize(rateBox->sizeHint());\n connect(rateBox, SIGNAL(activated(int)), SLOT(updateRate()));\n\n \/\/ layout stuff\n QBoxLayout *layout = new QHBoxLayout;\n layout->setMargin(0);\n layout->addWidget(stopButton);\n layout->addWidget(previousButton);\n layout->addWidget(playButton);\n layout->addWidget(nextButton);\n layout->addWidget(muteButton);\n layout->addStretch();\n layout->setSpacing(0);\n\n QBoxLayout *rightEndLayout = new QHBoxLayout;\n rightEndLayout->setDirection(QBoxLayout::RightToLeft);\n rightEndLayout->addWidget(rateBox);\n rightEndLayout->addWidget(volumeSlider);\n\n layout->addLayout(rightEndLayout);\n setLayout(layout);\n}\n\nPlayerControls::~PlayerControls() {\n delete playButton;\n delete stopButton;\n delete nextButton;\n delete previousButton;\n delete muteButton;\n delete volumeSlider;\n delete rateBox;\n}\n\nQMediaPlayer::State PlayerControls::state() const {\n return playerState;\n}\n\nvoid PlayerControls::setState(QMediaPlayer::State state) {\n \/\/ change button styles on different states\n if (state != playerState) {\n playerState = state;\n\n switch(state) {\n case QMediaPlayer::StoppedState:\n stopButton->setEnabled(false);\n playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n break;\n case QMediaPlayer::PlayingState:\n stopButton->setEnabled(true);\n playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));\n break;\n case QMediaPlayer::PausedState:\n stopButton->setEnabled(true);\n playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n break;\n }\n }\n}\n\nint PlayerControls::volume() const {\n return volumeSlider ? volumeSlider->value() : 0;\n}\n\nvoid PlayerControls::setVolume(int volume) {\n if (volumeSlider) \n volumeSlider->setValue(volume);\n}\n\nbool PlayerControls::isMuted() const {\n return playerMuted;\n}\n\nvoid PlayerControls::setMuted(bool muted) {\n if (muted != playerMuted) {\n playerMuted = muted;\n\n muteButton->setIcon(style()->standardIcon(muted ? \n QStyle::SP_MediaVolumeMuted : QStyle::SP_MediaVolume));\n }\n}\n\nvoid PlayerControls::playClicked() {\n switch (playerState) {\n case QMediaPlayer::StoppedState:\n case QMediaPlayer::PausedState:\n emit play();\n break;\n case QMediaPlayer::PlayingState:\n emit pause();\n break;\n }\n}\n\nvoid PlayerControls::muteClicked() {\n emit changeMuting(!playerMuted);\n}\n\nqreal PlayerControls::playbackRate() const {\n return rateBox->itemData(rateBox->currentIndex()).toDouble();\n}\n\nvoid PlayerControls::setPlaybackRate(float rate) {\n for (int i=0; i<rateBox->count(); ++i) {\n if (qFuzzyCompare(rate, float(rateBox->itemData(i).toDouble()))) {\n rateBox->setCurrentIndex(i);\n return;\n }\n }\n\n rateBox->addItem(QString(\"%1x\").arg(rate),QVariant(rate));\n rateBox->setCurrentIndex(rateBox->count() - 1);\n}\n\nvoid PlayerControls::updateRate() {\n emit changeRate(playbackRate());\n}\n\n \n<commit_msg>Adjusted volume control+rateBox spacing.<commit_after>#include \"playercontrols.h\"\n\n#include <QBoxLayout>\n#include <QSlider>\n#include <QStyle>\n#include <QToolButton>\n#include <QComboBox>\n\n\/\/ constructor\nPlayerControls::PlayerControls(QWidget *parent) :\n QWidget(parent),\n playerState(QMediaPlayer::StoppedState),\n playerMuted(false),\n playButton(NULL),\n stopButton(NULL),\n nextButton(NULL),\n previousButton(NULL),\n muteButton(NULL),\n volumeSlider(NULL),\n rateBox(NULL)\n{\n playButton = new QToolButton(this);\n playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n connect(playButton, SIGNAL(clicked()), this, SLOT(playClicked()));\n\n stopButton = new QToolButton(this);\n stopButton->setIcon(style()->standardIcon(QStyle::SP_MediaStop));\n stopButton->setEnabled(false);\n connect(stopButton, SIGNAL(clicked()), this, SIGNAL(stop()));\n\n nextButton = new QToolButton(this);\n nextButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward));\n connect(nextButton, SIGNAL(clicked()), this, SIGNAL(next()));\n\n previousButton = new QToolButton(this);\n previousButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward));\n connect(previousButton, SIGNAL(clicked()), this, SIGNAL(previous()));\n\n muteButton = new QToolButton(this);\n muteButton->setIcon(style()->standardIcon(QStyle::SP_MediaVolume));\n connect(muteButton, SIGNAL(clicked()), this, SLOT(muteClicked()));\n\n volumeSlider = new QSlider(Qt::Horizontal, this);\n volumeSlider->setRange(0, 100);\n volumeSlider->setFixedSize(volumeSlider->sizeHint());\n connect(volumeSlider, SIGNAL(sliderMoved(int)), this, SIGNAL(changeVolume(int)));\n\n \/\/ playback rate box chooser\n \/* Works like the following:\n * 1) whenver the box is \"activiated\" - user choosing something, call updateRate()\n * 2) updateRate() calls changeRate() on playbackRate();\n * - playbackRate() is used to figure out which one is selected from the rateBox\n * 3) The changeRate() signal is caught by the setPlaybackRate() slot.\n * 4) The argment to setPlaybackRate() is the index of the item chosen. The slot then\n * compares the index with the values in the box and set it.\n *\/\n rateBox = new QComboBox(this);\n rateBox->addItem(\"0.5x\", QVariant(0.5));\n rateBox->addItem(\"1.0x\", QVariant(1.0));\n rateBox->addItem(\"2.0x\", QVariant(2.0));\n rateBox->setCurrentIndex(1);\n rateBox->setFixedSize(rateBox->sizeHint());\n connect(rateBox, SIGNAL(activated(int)), SLOT(updateRate()));\n\n \/\/ layout stuff\n QBoxLayout *layout = new QHBoxLayout;\n layout->setMargin(0);\n layout->addWidget(stopButton);\n layout->addWidget(previousButton);\n layout->addWidget(playButton);\n layout->addWidget(nextButton);\n layout->addStretch();\n layout->setSpacing(0);\n\n QBoxLayout *rightEndLayout = new QHBoxLayout;\n rightEndLayout->setDirection(QBoxLayout::RightToLeft);\n rightEndLayout->addWidget(rateBox);\n rightEndLayout->setSpacing(2);\n rightEndLayout->addWidget(volumeSlider);\n rightEndLayout->addWidget(muteButton);\n\n layout->addLayout(rightEndLayout);\n setLayout(layout);\n}\n\nPlayerControls::~PlayerControls() {\n delete playButton;\n delete stopButton;\n delete nextButton;\n delete previousButton;\n delete muteButton;\n delete volumeSlider;\n delete rateBox;\n}\n\nQMediaPlayer::State PlayerControls::state() const {\n return playerState;\n}\n\nvoid PlayerControls::setState(QMediaPlayer::State state) {\n \/\/ change button styles on different states\n if (state != playerState) {\n playerState = state;\n\n switch(state) {\n case QMediaPlayer::StoppedState:\n stopButton->setEnabled(false);\n playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n break;\n case QMediaPlayer::PlayingState:\n stopButton->setEnabled(true);\n playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));\n break;\n case QMediaPlayer::PausedState:\n stopButton->setEnabled(true);\n playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n break;\n }\n }\n}\n\nint PlayerControls::volume() const {\n return volumeSlider ? volumeSlider->value() : 0;\n}\n\nvoid PlayerControls::setVolume(int volume) {\n if (volumeSlider) \n volumeSlider->setValue(volume);\n}\n\nbool PlayerControls::isMuted() const {\n return playerMuted;\n}\n\nvoid PlayerControls::setMuted(bool muted) {\n if (muted != playerMuted) {\n playerMuted = muted;\n\n muteButton->setIcon(style()->standardIcon(muted ? \n QStyle::SP_MediaVolumeMuted : QStyle::SP_MediaVolume));\n }\n}\n\nvoid PlayerControls::playClicked() {\n switch (playerState) {\n case QMediaPlayer::StoppedState:\n case QMediaPlayer::PausedState:\n emit play();\n break;\n case QMediaPlayer::PlayingState:\n emit pause();\n break;\n }\n}\n\nvoid PlayerControls::muteClicked() {\n emit changeMuting(!playerMuted);\n}\n\nqreal PlayerControls::playbackRate() const {\n return rateBox->itemData(rateBox->currentIndex()).toDouble();\n}\n\nvoid PlayerControls::setPlaybackRate(float rate) {\n for (int i=0; i<rateBox->count(); ++i) {\n if (qFuzzyCompare(rate, float(rateBox->itemData(i).toDouble()))) {\n rateBox->setCurrentIndex(i);\n return;\n }\n }\n\n rateBox->addItem(QString(\"%1x\").arg(rate),QVariant(rate));\n rateBox->setCurrentIndex(rateBox->count() - 1);\n}\n\nvoid PlayerControls::updateRate() {\n emit changeRate(playbackRate());\n}\n\n \n<|endoftext|>"} {"text":"<commit_before>#include <phypp.hpp>\n\nint main(int argc, char* argv[]) {\n if (argc < 2) {\n print(\"usage: make_skymaker gencat.fits band=... maglim=... out=...\");\n return 1;\n }\n\n std::string band;\n std::string out_file;\n double maglim = dnan;\n double aspix = 0.06;\n\n read_args(argc-1, argv+1, arg_list(band, name(out_file, \"out\"), maglim, aspix));\n\n struct {\n vec1d ra, dec;\n\n vec1f disk_angle, disk_radius, disk_ratio;\n vec1f bulge_angle, bulge_radius, bulge_ratio;\n\n vec2f flux_disk, flux_bulge;\n vec1s bands;\n } cat;\n\n fits::read_table(argv[1], cat);\n\n vec1u idb = where(cat.bands == band);\n if (idb.empty()) {\n error(\"no band named '\", band, \"' in this catalog\");\n return 1;\n } else if (idb.size() > 1) {\n error(\"multiple bands named '\", band, \"' in this catalog\");\n return 1;\n }\n\n uint_t b = idb[0];\n\n vec1f mag = uJy2mag(cat.flux_disk(_,b)+cat.flux_bulge(_,b));\n vec1f bt = cat.flux_bulge(_,b)\/(cat.flux_disk(_,b)+cat.flux_bulge(_,b));\n\n fits::make_wcs_header_params wcs_params;\n wcs_params.pixel_scale = aspix;\n wcs_params.pixel_ref_x = 0.0; wcs_params.pixel_ref_y = 0.0;\n wcs_params.sky_ref_ra = max(cat.ra); wcs_params.sky_ref_dec = min(cat.dec);\n move_ra_dec(wcs_params.sky_ref_ra, wcs_params.sky_ref_dec, +5.0, -5.0);\n\n fits::header hdr;\n if (!fits::make_wcs_header(wcs_params, hdr)) {\n error(\"could not make WCS header\");\n return 1;\n }\n\n vec1d x, y;\n fits::ad2xy(fits::wcs(hdr), cat.ra, cat.dec, x, y);\n\n\n vec1u ids;\n if (finite(maglim)) {\n ids = where(mag < maglim);\n if (ids.empty()) {\n error(\"no source brighter than \", maglim);\n note(\"maximum magnitude is \", max(mag));\n return 1;\n }\n } else {\n ids = uindgen(x.size());\n vec1u idbad = where(!finite(mag));\n mag[idbad] = 99;\n }\n\n if (out_file.empty()) {\n out_file = erase_end(argv[1], \".fits\")+\"-\"+band+\".cat\";\n }\n\n file::mkdir(file::get_directory(out_file));\n\n file::write_table_hdr(out_file, 16,\n {\"type\", \"x\", \"y\", \"mag\", \"bt\",\n \"bulge_radius\", \"bulge_ratio\", \"bulge_angle\",\n \"disk_radius\", \"disk_ratio\", \"disk_angle\"},\n replicate(200u, ids.size()), x[ids], y[ids],\n mag[ids], bt[ids],\n cat.bulge_radius[ids], cat.bulge_ratio[ids], cat.bulge_angle[ids],\n cat.disk_radius[ids], cat.disk_ratio[ids], cat.disk_angle[ids]\n );\n\n \/\/ Write FITS header to a file\n {\n std::ofstream ohdr(erase_end(out_file, \".cat\")+\"-hdr.txt\");\n vec1s shdr = cut(hdr, 80);\n for (auto& s : shdr) {\n ohdr << s << \"\\n\";\n }\n }\n\n return 0;\n}\n<commit_msg>Removed use reflection feature in make_skymaker<commit_after>#include <phypp.hpp>\n\nint main(int argc, char* argv[]) {\n if (argc < 2) {\n print(\"usage: make_skymaker gencat.fits band=... maglim=... out=...\");\n return 1;\n }\n\n std::string band;\n std::string out_file;\n double maglim = dnan;\n double aspix = 0.06;\n\n read_args(argc-1, argv+1, arg_list(band, name(out_file, \"out\"), maglim, aspix));\n\n struct {\n vec1d ra, dec;\n\n vec1f disk_angle, disk_radius, disk_ratio;\n vec1f bulge_angle, bulge_radius, bulge_ratio;\n\n vec2f flux_disk, flux_bulge;\n vec1s bands;\n } cat;\n\n fits::read_table(argv[1], ftable(\n cat.ra, cat.dec,\n cat.disk_angle, cat.disk_radius, cat.disk_ratio,\n cat.bulge_angle, cat.bulge_radius, cat.bulge_ratio,\n cat.flux_disk, cat.flux_bulge, cat.bands\n ));\n\n vec1u idb = where(cat.bands == band);\n if (idb.empty()) {\n error(\"no band named '\", band, \"' in this catalog\");\n return 1;\n } else if (idb.size() > 1) {\n error(\"multiple bands named '\", band, \"' in this catalog\");\n return 1;\n }\n\n uint_t b = idb[0];\n\n vec1f mag = uJy2mag(cat.flux_disk(_,b)+cat.flux_bulge(_,b));\n vec1f bt = cat.flux_bulge(_,b)\/(cat.flux_disk(_,b)+cat.flux_bulge(_,b));\n\n fits::make_wcs_header_params wcs_params;\n wcs_params.pixel_scale = aspix;\n wcs_params.pixel_ref_x = 0.0; wcs_params.pixel_ref_y = 0.0;\n wcs_params.sky_ref_ra = max(cat.ra); wcs_params.sky_ref_dec = min(cat.dec);\n move_ra_dec(wcs_params.sky_ref_ra, wcs_params.sky_ref_dec, +5.0, -5.0);\n\n fits::header hdr;\n if (!fits::make_wcs_header(wcs_params, hdr)) {\n error(\"could not make WCS header\");\n return 1;\n }\n\n vec1d x, y;\n fits::ad2xy(fits::wcs(hdr), cat.ra, cat.dec, x, y);\n\n vec1u ids;\n if (finite(maglim)) {\n ids = where(mag < maglim);\n if (ids.empty()) {\n error(\"no source brighter than \", maglim);\n note(\"maximum magnitude is \", max(mag));\n return 1;\n }\n } else {\n ids = uindgen(x.size());\n vec1u idbad = where(!finite(mag));\n mag[idbad] = 99;\n }\n\n if (out_file.empty()) {\n out_file = erase_end(argv[1], \".fits\")+\"-\"+band+\".cat\";\n }\n\n file::mkdir(file::get_directory(out_file));\n\n file::write_table_hdr(out_file, 16,\n {\"type\", \"x\", \"y\", \"mag\", \"bt\",\n \"bulge_radius\", \"bulge_ratio\", \"bulge_angle\",\n \"disk_radius\", \"disk_ratio\", \"disk_angle\"},\n replicate(200u, ids.size()), x[ids], y[ids],\n mag[ids], bt[ids],\n cat.bulge_radius[ids], cat.bulge_ratio[ids], cat.bulge_angle[ids],\n cat.disk_radius[ids], cat.disk_ratio[ids], cat.disk_angle[ids]\n );\n\n \/\/ Write FITS header to a file\n {\n std::ofstream ohdr(erase_end(out_file, \".cat\")+\"-hdr.txt\");\n vec1s shdr = cut(hdr, 80);\n for (auto& s : shdr) {\n ohdr << s << \"\\n\";\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: svdomedia.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: pjunck $ $Date: 2004-11-03 11:00:50 $\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#include \"svdomedia.hxx\"\n#include \"svdglob.hxx\"\n#include \"svdstr.hrc\"\n\n#ifndef _SDR_CONTACT_VIEWCONTACTOFSDRMEDIAOBJ_HXX\n#include <svx\/sdr\/contact\/viewcontactofsdrmediaobj.hxx>\n#endif\n\n\n\/\/ ---------------\n\/\/ - SdrMediaObj -\n\/\/ ---------------\n\nTYPEINIT1( SdrMediaObj, SdrRectObj );\n\n\/\/ ------------------------------------------------------------------------------\n\nSdrMediaObj::SdrMediaObj()\n{\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nSdrMediaObj::SdrMediaObj( const Rectangle& rRect ) :\n SdrRectObj( rRect )\n{\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nSdrMediaObj::~SdrMediaObj()\n{\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nFASTBOOL SdrMediaObj::HasTextEdit() const\n{\n return FALSE;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nsdr::contact::ViewContact* SdrMediaObj::CreateObjectSpecificViewContact()\n{\n return new ::sdr::contact::ViewContactOfSdrMediaObj( *this );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const\n{\n rInfo.bSelectAllowed = true;\n rInfo.bMoveAllowed = true;\n rInfo.bResizeFreeAllowed = true;\n rInfo.bResizePropAllowed = true;\n rInfo.bRotateFreeAllowed = false;\n rInfo.bRotate90Allowed = false;\n rInfo.bMirrorFreeAllowed = false;\n rInfo.bMirror45Allowed = false;\n rInfo.bMirror90Allowed = false;\n rInfo.bTransparenceAllowed = false;\n rInfo.bGradientAllowed = false;\n rInfo.bShearAllowed = false;\n rInfo.bEdgeRadiusAllowed = false;\n rInfo.bNoOrthoDesired = false;\n rInfo.bNoContortion = false;\n rInfo.bCanConvToPath = false;\n rInfo.bCanConvToPoly = false;\n rInfo.bCanConvToContour = false;\n rInfo.bCanConvToPathLineToArea = false;\n rInfo.bCanConvToPolyLineToArea = false;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nUINT16 SdrMediaObj::GetObjIdentifier() const\n{\n return UINT16( OBJ_MEDIA );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nsal_Bool SdrMediaObj::DoPaintObject(XOutputDevice& rXOut, const SdrPaintInfoRec& rInfoRec) const\n{\n return true;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::TakeObjNameSingul(XubString& rName) const\n{\n rName=ImpGetResStr(STR_ObjNameSingulMEDIA);\n\n String aName( GetName() );\n\n if(aName.Len())\n {\n rName += sal_Unicode(' ');\n rName += sal_Unicode('\\'');\n rName += aName;\n rName += sal_Unicode('\\'');\n }\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::TakeObjNamePlural(XubString& rName) const\n{\n rName=ImpGetResStr(STR_ObjNamePluralMEDIA);\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::operator=(const SdrObject& rObj)\n{\n SdrRectObj::operator=( rObj );\n\n if( rObj.ISA( SdrMediaObj ) )\n setMediaProperties( static_cast< const SdrMediaObj& >( rObj ).getMediaProperties() );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::setURL( const ::rtl::OUString& rURL )\n{\n ::avmedia::MediaItem aURLItem;\n\n aURLItem.setURL( rURL );\n setMediaProperties( aURLItem );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nconst ::rtl::OUString& SdrMediaObj::getURL() const\n{\n return getMediaProperties().getURL();\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::setMediaProperties( const ::avmedia::MediaItem& rState )\n{\n mediaPropertiesChanged( rState );\n static_cast< ::sdr::contact::ViewContactOfSdrMediaObj& >( GetViewContact() ).executeMediaItem( getMediaProperties() );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nconst ::avmedia::MediaItem& SdrMediaObj::getMediaProperties() const\n{\n return maMediaProperties;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nbool SdrMediaObj::hasPreferredSize() const\n{\n return static_cast< ::sdr::contact::ViewContactOfSdrMediaObj& >( GetViewContact() ).hasPreferredSize();\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nSize SdrMediaObj::getPreferredSize() const\n{\n return static_cast< ::sdr::contact::ViewContactOfSdrMediaObj& >( GetViewContact() ).getPreferredSize();\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::mediaPropertiesChanged( const ::avmedia::MediaItem& rNewProperties )\n{\n const sal_uInt32 nMaskSet = rNewProperties.getMaskSet();\n\n \/\/ use only a subset of MediaItem properties for own own properties\n if( AVMEDIA_SETMASK_URL & nMaskSet )\n maMediaProperties.setURL( rNewProperties.getURL() );\n\n if( AVMEDIA_SETMASK_LOOP & nMaskSet )\n maMediaProperties.setLoop( rNewProperties.isLoop() );\n\n if( AVMEDIA_SETMASK_MUTE & nMaskSet )\n maMediaProperties.setMute( rNewProperties.isMute() );\n\n if( AVMEDIA_SETMASK_VOLUMEDB & nMaskSet )\n maMediaProperties.setVolumeDB( rNewProperties.getVolumeDB() );\n\n if( AVMEDIA_SETMASK_ZOOM & nMaskSet )\n maMediaProperties.setZoom( rNewProperties.getZoom() );\n}\n<commit_msg>INTEGRATION: CWS jmf5 (1.3.130); FILE MERGED 2005\/01\/21 14:31:24 ka 1.3.130.1: #i37255#: use FrameGrabber<commit_after>\/*************************************************************************\n *\n * $RCSfile: svdomedia.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 12:42:54 $\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#include \"svdomedia.hxx\"\n#include \"svdglob.hxx\"\n#include \"svdstr.hrc\"\n\n#ifndef _SDR_CONTACT_VIEWCONTACTOFSDRMEDIAOBJ_HXX\n#include <svx\/sdr\/contact\/viewcontactofsdrmediaobj.hxx>\n#endif\n#ifndef _AVMEDIA_MEDIAWINDOW_HXX\n#include <avmedia\/mediawindow.hxx>\n#endif\n\n\/\/ ---------------\n\/\/ - SdrMediaObj -\n\/\/ ---------------\n\nTYPEINIT1( SdrMediaObj, SdrRectObj );\n\n\/\/ ------------------------------------------------------------------------------\n\nSdrMediaObj::SdrMediaObj()\n{\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nSdrMediaObj::SdrMediaObj( const Rectangle& rRect ) :\n SdrRectObj( rRect )\n{\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nSdrMediaObj::~SdrMediaObj()\n{\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nFASTBOOL SdrMediaObj::HasTextEdit() const\n{\n return FALSE;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nsdr::contact::ViewContact* SdrMediaObj::CreateObjectSpecificViewContact()\n{\n return new ::sdr::contact::ViewContactOfSdrMediaObj( *this );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const\n{\n rInfo.bSelectAllowed = true;\n rInfo.bMoveAllowed = true;\n rInfo.bResizeFreeAllowed = true;\n rInfo.bResizePropAllowed = true;\n rInfo.bRotateFreeAllowed = false;\n rInfo.bRotate90Allowed = false;\n rInfo.bMirrorFreeAllowed = false;\n rInfo.bMirror45Allowed = false;\n rInfo.bMirror90Allowed = false;\n rInfo.bTransparenceAllowed = false;\n rInfo.bGradientAllowed = false;\n rInfo.bShearAllowed = false;\n rInfo.bEdgeRadiusAllowed = false;\n rInfo.bNoOrthoDesired = false;\n rInfo.bNoContortion = false;\n rInfo.bCanConvToPath = false;\n rInfo.bCanConvToPoly = false;\n rInfo.bCanConvToContour = false;\n rInfo.bCanConvToPathLineToArea = false;\n rInfo.bCanConvToPolyLineToArea = false;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nUINT16 SdrMediaObj::GetObjIdentifier() const\n{\n return UINT16( OBJ_MEDIA );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nsal_Bool SdrMediaObj::DoPaintObject(XOutputDevice& rXOut, const SdrPaintInfoRec& rInfoRec) const\n{\n return true;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::TakeObjNameSingul(XubString& rName) const\n{\n rName=ImpGetResStr(STR_ObjNameSingulMEDIA);\n\n String aName( GetName() );\n\n if(aName.Len())\n {\n rName += sal_Unicode(' ');\n rName += sal_Unicode('\\'');\n rName += aName;\n rName += sal_Unicode('\\'');\n }\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::TakeObjNamePlural(XubString& rName) const\n{\n rName=ImpGetResStr(STR_ObjNamePluralMEDIA);\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::operator=(const SdrObject& rObj)\n{\n SdrRectObj::operator=( rObj );\n\n if( rObj.ISA( SdrMediaObj ) )\n {\n const SdrMediaObj& rMediaObj = static_cast< const SdrMediaObj& >( rObj );\n\n setMediaProperties( rMediaObj.getMediaProperties() );\n setGraphic( rMediaObj.mapGraphic.get() );\n }\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::setURL( const ::rtl::OUString& rURL )\n{\n ::avmedia::MediaItem aURLItem;\n\n aURLItem.setURL( rURL );\n setMediaProperties( aURLItem );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nconst ::rtl::OUString& SdrMediaObj::getURL() const\n{\n return getMediaProperties().getURL();\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::setMediaProperties( const ::avmedia::MediaItem& rState )\n{\n mediaPropertiesChanged( rState );\n static_cast< ::sdr::contact::ViewContactOfSdrMediaObj& >( GetViewContact() ).executeMediaItem( getMediaProperties() );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nconst ::avmedia::MediaItem& SdrMediaObj::getMediaProperties() const\n{\n return maMediaProperties;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nbool SdrMediaObj::hasPreferredSize() const\n{\n return static_cast< ::sdr::contact::ViewContactOfSdrMediaObj& >( GetViewContact() ).hasPreferredSize();\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nSize SdrMediaObj::getPreferredSize() const\n{\n return static_cast< ::sdr::contact::ViewContactOfSdrMediaObj& >( GetViewContact() ).getPreferredSize();\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nconst Graphic& SdrMediaObj::getGraphic() const\n{\n if( !mapGraphic.get() )\n const_cast< SdrMediaObj* >( this )->mapGraphic.reset( new Graphic( ::avmedia::MediaWindow::grabFrame( getURL(), true ) ) );\n\n return *mapGraphic;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::setGraphic( const Graphic* pGraphic )\n{\n mapGraphic.reset( pGraphic ? new Graphic( *pGraphic ) : NULL );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid SdrMediaObj::mediaPropertiesChanged( const ::avmedia::MediaItem& rNewProperties )\n{\n const sal_uInt32 nMaskSet = rNewProperties.getMaskSet();\n\n \/\/ use only a subset of MediaItem properties for own own properties\n if( ( AVMEDIA_SETMASK_URL & nMaskSet ) &&\n ( rNewProperties.getURL() != getURL() ) )\n {\n setGraphic();\n maMediaProperties.setURL( rNewProperties.getURL() );\n }\n\n if( AVMEDIA_SETMASK_LOOP & nMaskSet )\n maMediaProperties.setLoop( rNewProperties.isLoop() );\n\n if( AVMEDIA_SETMASK_MUTE & nMaskSet )\n maMediaProperties.setMute( rNewProperties.isMute() );\n\n if( AVMEDIA_SETMASK_VOLUMEDB & nMaskSet )\n maMediaProperties.setVolumeDB( rNewProperties.getVolumeDB() );\n\n if( AVMEDIA_SETMASK_ZOOM & nMaskSet )\n maMediaProperties.setZoom( rNewProperties.getZoom() );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2019 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\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 *\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\n * distribution.\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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"FifoBufferIstream.hxx\"\n#include \"Bucket.hxx\"\n#include \"fb_pool.hxx\"\n\n#include <string.h>\n\nsize_t\nFifoBufferIstream::Push(ConstBuffer<void> src) noexcept\n{\n\tbuffer.AllocateIfNull(fb_pool_get());\n\n\tauto w = buffer.Write();\n\tsize_t nbytes = std::min(w.size, src.size);\n\tmemcpy(w.data, src.data, nbytes);\n\tbuffer.Append(nbytes);\n\treturn nbytes;\n}\n\nvoid\nFifoBufferIstream::SetEof() noexcept\n{\n\teof = true;\n\tSubmitBuffer();\n}\n\nvoid\nFifoBufferIstream::SubmitBuffer() noexcept\n{\n\twhile (!buffer.empty()) {\n\t\tsize_t nbytes = SendFromBuffer(buffer);\n\t\tif (nbytes == 0)\n\t\t\treturn;\n\n\t\thandler.OnFifoBufferIstreamConsumed(nbytes);\n\n\t\tif (buffer.empty() && !eof)\n\t\t\thandler.OnFifoBufferIstreamDrained();\n\t}\n\n\tif (buffer.empty()) {\n\t\tif (eof)\n\t\t\tDestroyEof();\n\t\telse\n\t\t\tbuffer.FreeIfDefined();\n\t}\n}\n\noff_t\nFifoBufferIstream::_Skip(off_t length) noexcept\n{\n\tsize_t nbytes = std::min<decltype(length)>(length, buffer.GetAvailable());\n\tbuffer.Consume(nbytes);\n\tbuffer.FreeIfEmpty();\n\tConsumed(nbytes);\n\thandler.OnFifoBufferIstreamConsumed(nbytes);\n\treturn nbytes;\n}\n\nvoid\nFifoBufferIstream::_Read() noexcept\n{\n\tSubmitBuffer();\n}\n\nvoid\nFifoBufferIstream::_FillBucketList(IstreamBucketList &list) noexcept\n{\n\tauto r = buffer.Read();\n\tif (!r.empty())\n\t\tlist.Push(r.ToVoid());\n\n\tif (!eof)\n\t\tlist.SetMore();\n}\n\nsize_t\nFifoBufferIstream::_ConsumeBucketList(size_t nbytes) noexcept\n{\n\tsize_t consumed = std::min(nbytes, buffer.GetAvailable());\n\tbuffer.Consume(consumed);\n\tConsumed(nbytes);\n\thandler.OnFifoBufferIstreamConsumed(consumed);\n\n\tif (consumed > 0 && buffer.empty() && !eof) {\n\t\thandler.OnFifoBufferIstreamDrained();\n\n\t\tif (buffer.empty())\n\t\t\tbuffer.Free();\n\t}\n\n\treturn nbytes - consumed;\n}\n<commit_msg>istream\/FifoBufferIstream: add missing `eof` checks before invoking handler<commit_after>\/*\n * Copyright 2007-2019 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\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 *\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\n * distribution.\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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"FifoBufferIstream.hxx\"\n#include \"Bucket.hxx\"\n#include \"fb_pool.hxx\"\n\n#include <string.h>\n\nsize_t\nFifoBufferIstream::Push(ConstBuffer<void> src) noexcept\n{\n\tbuffer.AllocateIfNull(fb_pool_get());\n\n\tauto w = buffer.Write();\n\tsize_t nbytes = std::min(w.size, src.size);\n\tmemcpy(w.data, src.data, nbytes);\n\tbuffer.Append(nbytes);\n\treturn nbytes;\n}\n\nvoid\nFifoBufferIstream::SetEof() noexcept\n{\n\teof = true;\n\tSubmitBuffer();\n}\n\nvoid\nFifoBufferIstream::SubmitBuffer() noexcept\n{\n\twhile (!buffer.empty()) {\n\t\tsize_t nbytes = SendFromBuffer(buffer);\n\t\tif (nbytes == 0)\n\t\t\treturn;\n\n\t\tif (!eof) {\n\t\t\thandler.OnFifoBufferIstreamConsumed(nbytes);\n\t\t\tif (buffer.empty())\n\t\t\t\thandler.OnFifoBufferIstreamDrained();\n\t\t}\n\t}\n\n\tif (buffer.empty()) {\n\t\tif (eof)\n\t\t\tDestroyEof();\n\t\telse\n\t\t\tbuffer.FreeIfDefined();\n\t}\n}\n\noff_t\nFifoBufferIstream::_Skip(off_t length) noexcept\n{\n\tsize_t nbytes = std::min<decltype(length)>(length, buffer.GetAvailable());\n\tbuffer.Consume(nbytes);\n\tbuffer.FreeIfEmpty();\n\tConsumed(nbytes);\n\n\tif (nbytes > 0 && !eof) {\n\t\thandler.OnFifoBufferIstreamConsumed(nbytes);\n\t\tif (buffer.empty())\n\t\t\thandler.OnFifoBufferIstreamDrained();\n\t}\n\n\treturn nbytes;\n}\n\nvoid\nFifoBufferIstream::_Read() noexcept\n{\n\tSubmitBuffer();\n}\n\nvoid\nFifoBufferIstream::_FillBucketList(IstreamBucketList &list) noexcept\n{\n\tauto r = buffer.Read();\n\tif (!r.empty())\n\t\tlist.Push(r.ToVoid());\n\n\tif (!eof)\n\t\tlist.SetMore();\n}\n\nsize_t\nFifoBufferIstream::_ConsumeBucketList(size_t nbytes) noexcept\n{\n\tsize_t consumed = std::min(nbytes, buffer.GetAvailable());\n\tbuffer.Consume(consumed);\n\tConsumed(consumed);\n\n\tif (consumed > 0 && !eof) {\n\t\thandler.OnFifoBufferIstreamConsumed(consumed);\n\t\tif (buffer.empty())\n\t\t\thandler.OnFifoBufferIstreamDrained();\n\n\t\tif (buffer.empty())\n\t\t\tbuffer.Free();\n\t}\n\n\treturn nbytes - consumed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unoshcol.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 06:15:37 $\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_svx.hxx\"\n\n#ifndef _COM_SUN_STAR_DOCUMENT_EVENTOBJECT_HPP_\n#include <com\/sun\/star\/document\/EventObject.hpp>\n#endif\n\n#include \"unoshcol.hxx\"\n#include \"unoprov.hxx\"\n\nusing namespace ::rtl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::drawing;\n\n\/***********************************************************************\n* *\n***********************************************************************\/\nSvxShapeCollection::SvxShapeCollection() throw()\n: maShapeContainer( maMutex ), mrBHelper( maMutex )\n{\n}\n\n\/\/----------------------------------------------------------------------\nSvxShapeCollection::~SvxShapeCollection() throw()\n{\n}\n\n\n\/\/----------------------------------------------------------------------\nReference< uno::XInterface > SvxShapeCollection_NewInstance() throw()\n{\n Reference< drawing::XShapes > xShapes( new SvxShapeCollection() );\n Reference< uno::XInterface > xRef( xShapes, UNO_QUERY );\n return xRef;\n}\n\n\/\/ XInterface\nvoid SvxShapeCollection::release() throw()\n{\n uno::Reference< uno::XInterface > x( xDelegator );\n if (! x.is())\n {\n if (osl_decrementInterlockedCount( &m_refCount ) == 0)\n {\n if (! mrBHelper.bDisposed)\n {\n uno::Reference< uno::XInterface > xHoldAlive( (uno::XWeak*)this );\n \/\/ First dispose\n try\n {\n dispose();\n }\n catch(::com::sun::star::uno::Exception&)\n {\n \/\/ release should not throw exceptions\n }\n\n \/\/ only the alive ref holds the object\n OSL_ASSERT( m_refCount == 1 );\n \/\/ destroy the object if xHoldAlive decrement the refcount to 0\n return;\n }\n }\n \/\/ restore the reference count\n osl_incrementInterlockedCount( &m_refCount );\n }\n OWeakAggObject::release();\n}\n\n\/\/ XComponent\nvoid SvxShapeCollection::disposing() throw()\n{\n maShapeContainer.clear();\n}\n\n\/\/ XComponent\nvoid SvxShapeCollection::dispose()\n throw(::com::sun::star::uno::RuntimeException)\n{\n \/\/ An frequently programming error is to release the last\n \/\/ reference to this object in the disposing message.\n \/\/ Make it rubust, hold a self Reference.\n uno::Reference< lang::XComponent > xSelf( this );\n\n \/\/ Guard dispose against multible threading\n \/\/ Remark: It is an error to call dispose more than once\n sal_Bool bDoDispose = sal_False;\n {\n osl::MutexGuard aGuard( mrBHelper.rMutex );\n if( !mrBHelper.bDisposed && !mrBHelper.bInDispose )\n {\n \/\/ only one call go into this section\n mrBHelper.bInDispose = sal_True;\n bDoDispose = sal_True;\n }\n }\n\n \/\/ Do not hold the mutex because we are broadcasting\n if( bDoDispose )\n {\n \/\/ Create an event with this as sender\n try\n {\n uno::Reference< uno::XInterface > xSource( uno::Reference< uno::XInterface >::query( (lang::XComponent *)this ) );\n document::EventObject aEvt;\n aEvt.Source = xSource;\n \/\/ inform all listeners to release this object\n \/\/ The listener container are automaticly cleared\n mrBHelper.aLC.disposeAndClear( aEvt );\n \/\/ notify subclasses to do their dispose\n disposing();\n }\n catch(::com::sun::star::uno::Exception& e)\n {\n \/\/ catch exception and throw again but signal that\n \/\/ the object was disposed. Dispose should be called\n \/\/ only once.\n mrBHelper.bDisposed = sal_True;\n mrBHelper.bInDispose = sal_False;\n throw e;\n }\n\n \/\/ the values bDispose and bInDisposing must set in this order.\n \/\/ No multithread call overcome the \"!rBHelper.bDisposed && !rBHelper.bInDispose\" guard.\n mrBHelper.bDisposed = sal_True;\n mrBHelper.bInDispose = sal_False;\n }\n else\n {\n \/\/ in a multithreaded environment, it can't be avoided, that dispose is called twice.\n \/\/ However this condition is traced, because it MAY indicate an error.\n OSL_TRACE( \"OComponentHelper::dispose() - dispose called twice\" );\n }\n}\n\n\/\/ XComponent\nvoid SAL_CALL SvxShapeCollection::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException)\n{\n mrBHelper.addListener( ::getCppuType( &aListener ) , aListener );\n}\n\n\/\/ XComponent\nvoid SAL_CALL SvxShapeCollection::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException)\n{\n mrBHelper.removeListener( ::getCppuType( &aListener ) , aListener );\n}\n\n\/\/ XShapes\n\/\/----------------------------------------------------------------------\nvoid SAL_CALL SvxShapeCollection::add( const Reference< drawing::XShape >& xShape ) throw( uno::RuntimeException )\n{\n maShapeContainer.addInterface( xShape );\n}\n\n\/\/----------------------------------------------------------------------\nvoid SAL_CALL SvxShapeCollection::remove( const uno::Reference< drawing::XShape >& xShape ) throw( uno::RuntimeException )\n{\n maShapeContainer.removeInterface( xShape );\n}\n\n\/\/----------------------------------------------------------------------\nsal_Int32 SAL_CALL SvxShapeCollection::getCount() throw( uno::RuntimeException )\n{\n return maShapeContainer.getLength();\n}\n\n\/\/----------------------------------------------------------------------\nuno::Any SAL_CALL SvxShapeCollection::getByIndex( sal_Int32 Index )\n throw( lang::IndexOutOfBoundsException, lang::WrappedTargetException, uno::RuntimeException )\n{\n if( Index < 0 || Index >= getCount() )\n throw lang::IndexOutOfBoundsException();\n\n uno::Sequence< Reference< uno::XInterface> > xElements( maShapeContainer.getElements() );\n\n\n return uno::makeAny( Reference< XShape>(static_cast< drawing::XShape* >( xElements.getArray()[Index].get())) );\n}\n\n\/\/ XElementAccess\n\n\/\/----------------------------------------------------------------------\nuno::Type SAL_CALL SvxShapeCollection::getElementType() throw( uno::RuntimeException )\n{\n return ::getCppuType(( const Reference< drawing::XShape >*)0);\n}\n\n\/\/----------------------------------------------------------------------\nsal_Bool SAL_CALL SvxShapeCollection::hasElements() throw( uno::RuntimeException )\n{\n return getCount() != 0;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ XServiceInfo\n\/\/----------------------------------------------------------------------\nOUString SAL_CALL SvxShapeCollection::getImplementationName()\n throw( uno::RuntimeException )\n{\n return getImplementationName_Static();\n}\n\nOUString SvxShapeCollection::getImplementationName_Static()\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.SvxShapeCollection\") );\n}\n\nsal_Bool SAL_CALL SvxShapeCollection::supportsService( const OUString& ServiceName )\n throw( uno::RuntimeException )\n{\n return SvxServiceInfoHelper::supportsService( ServiceName, getSupportedServiceNames() );\n}\n\nuno::Sequence< OUString > SAL_CALL SvxShapeCollection::getSupportedServiceNames() throw( uno::RuntimeException )\n{\n return getSupportedServiceNames_Static();\n}\n\nuno::Sequence< OUString > SvxShapeCollection::getSupportedServiceNames_Static()\n{\n uno::Sequence< OUString > aSeq(2);\n aSeq.getArray()[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.Shapes\") );\n aSeq.getArray()[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.ShapeCollection\") );\n return aSeq;\n}\n\nReference< XInterface > SAL_CALL SvxShapeCollection_createInstance( const Reference< ::com::sun::star::lang::XMultiServiceFactory >& )\n{\n return *( new SvxShapeCollection() );\n}\n\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.8.352); FILE MERGED 2007\/06\/04 13:27:37 vg 1.8.352.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unoshcol.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 19:27:22 $\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_svx.hxx\"\n\n#ifndef _COM_SUN_STAR_DOCUMENT_EVENTOBJECT_HPP_\n#include <com\/sun\/star\/document\/EventObject.hpp>\n#endif\n\n#include \"unoshcol.hxx\"\n#include <svx\/unoprov.hxx>\n\nusing namespace ::rtl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::drawing;\n\n\/***********************************************************************\n* *\n***********************************************************************\/\nSvxShapeCollection::SvxShapeCollection() throw()\n: maShapeContainer( maMutex ), mrBHelper( maMutex )\n{\n}\n\n\/\/----------------------------------------------------------------------\nSvxShapeCollection::~SvxShapeCollection() throw()\n{\n}\n\n\n\/\/----------------------------------------------------------------------\nReference< uno::XInterface > SvxShapeCollection_NewInstance() throw()\n{\n Reference< drawing::XShapes > xShapes( new SvxShapeCollection() );\n Reference< uno::XInterface > xRef( xShapes, UNO_QUERY );\n return xRef;\n}\n\n\/\/ XInterface\nvoid SvxShapeCollection::release() throw()\n{\n uno::Reference< uno::XInterface > x( xDelegator );\n if (! x.is())\n {\n if (osl_decrementInterlockedCount( &m_refCount ) == 0)\n {\n if (! mrBHelper.bDisposed)\n {\n uno::Reference< uno::XInterface > xHoldAlive( (uno::XWeak*)this );\n \/\/ First dispose\n try\n {\n dispose();\n }\n catch(::com::sun::star::uno::Exception&)\n {\n \/\/ release should not throw exceptions\n }\n\n \/\/ only the alive ref holds the object\n OSL_ASSERT( m_refCount == 1 );\n \/\/ destroy the object if xHoldAlive decrement the refcount to 0\n return;\n }\n }\n \/\/ restore the reference count\n osl_incrementInterlockedCount( &m_refCount );\n }\n OWeakAggObject::release();\n}\n\n\/\/ XComponent\nvoid SvxShapeCollection::disposing() throw()\n{\n maShapeContainer.clear();\n}\n\n\/\/ XComponent\nvoid SvxShapeCollection::dispose()\n throw(::com::sun::star::uno::RuntimeException)\n{\n \/\/ An frequently programming error is to release the last\n \/\/ reference to this object in the disposing message.\n \/\/ Make it rubust, hold a self Reference.\n uno::Reference< lang::XComponent > xSelf( this );\n\n \/\/ Guard dispose against multible threading\n \/\/ Remark: It is an error to call dispose more than once\n sal_Bool bDoDispose = sal_False;\n {\n osl::MutexGuard aGuard( mrBHelper.rMutex );\n if( !mrBHelper.bDisposed && !mrBHelper.bInDispose )\n {\n \/\/ only one call go into this section\n mrBHelper.bInDispose = sal_True;\n bDoDispose = sal_True;\n }\n }\n\n \/\/ Do not hold the mutex because we are broadcasting\n if( bDoDispose )\n {\n \/\/ Create an event with this as sender\n try\n {\n uno::Reference< uno::XInterface > xSource( uno::Reference< uno::XInterface >::query( (lang::XComponent *)this ) );\n document::EventObject aEvt;\n aEvt.Source = xSource;\n \/\/ inform all listeners to release this object\n \/\/ The listener container are automaticly cleared\n mrBHelper.aLC.disposeAndClear( aEvt );\n \/\/ notify subclasses to do their dispose\n disposing();\n }\n catch(::com::sun::star::uno::Exception& e)\n {\n \/\/ catch exception and throw again but signal that\n \/\/ the object was disposed. Dispose should be called\n \/\/ only once.\n mrBHelper.bDisposed = sal_True;\n mrBHelper.bInDispose = sal_False;\n throw e;\n }\n\n \/\/ the values bDispose and bInDisposing must set in this order.\n \/\/ No multithread call overcome the \"!rBHelper.bDisposed && !rBHelper.bInDispose\" guard.\n mrBHelper.bDisposed = sal_True;\n mrBHelper.bInDispose = sal_False;\n }\n else\n {\n \/\/ in a multithreaded environment, it can't be avoided, that dispose is called twice.\n \/\/ However this condition is traced, because it MAY indicate an error.\n OSL_TRACE( \"OComponentHelper::dispose() - dispose called twice\" );\n }\n}\n\n\/\/ XComponent\nvoid SAL_CALL SvxShapeCollection::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException)\n{\n mrBHelper.addListener( ::getCppuType( &aListener ) , aListener );\n}\n\n\/\/ XComponent\nvoid SAL_CALL SvxShapeCollection::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException)\n{\n mrBHelper.removeListener( ::getCppuType( &aListener ) , aListener );\n}\n\n\/\/ XShapes\n\/\/----------------------------------------------------------------------\nvoid SAL_CALL SvxShapeCollection::add( const Reference< drawing::XShape >& xShape ) throw( uno::RuntimeException )\n{\n maShapeContainer.addInterface( xShape );\n}\n\n\/\/----------------------------------------------------------------------\nvoid SAL_CALL SvxShapeCollection::remove( const uno::Reference< drawing::XShape >& xShape ) throw( uno::RuntimeException )\n{\n maShapeContainer.removeInterface( xShape );\n}\n\n\/\/----------------------------------------------------------------------\nsal_Int32 SAL_CALL SvxShapeCollection::getCount() throw( uno::RuntimeException )\n{\n return maShapeContainer.getLength();\n}\n\n\/\/----------------------------------------------------------------------\nuno::Any SAL_CALL SvxShapeCollection::getByIndex( sal_Int32 Index )\n throw( lang::IndexOutOfBoundsException, lang::WrappedTargetException, uno::RuntimeException )\n{\n if( Index < 0 || Index >= getCount() )\n throw lang::IndexOutOfBoundsException();\n\n uno::Sequence< Reference< uno::XInterface> > xElements( maShapeContainer.getElements() );\n\n\n return uno::makeAny( Reference< XShape>(static_cast< drawing::XShape* >( xElements.getArray()[Index].get())) );\n}\n\n\/\/ XElementAccess\n\n\/\/----------------------------------------------------------------------\nuno::Type SAL_CALL SvxShapeCollection::getElementType() throw( uno::RuntimeException )\n{\n return ::getCppuType(( const Reference< drawing::XShape >*)0);\n}\n\n\/\/----------------------------------------------------------------------\nsal_Bool SAL_CALL SvxShapeCollection::hasElements() throw( uno::RuntimeException )\n{\n return getCount() != 0;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ XServiceInfo\n\/\/----------------------------------------------------------------------\nOUString SAL_CALL SvxShapeCollection::getImplementationName()\n throw( uno::RuntimeException )\n{\n return getImplementationName_Static();\n}\n\nOUString SvxShapeCollection::getImplementationName_Static()\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.SvxShapeCollection\") );\n}\n\nsal_Bool SAL_CALL SvxShapeCollection::supportsService( const OUString& ServiceName )\n throw( uno::RuntimeException )\n{\n return SvxServiceInfoHelper::supportsService( ServiceName, getSupportedServiceNames() );\n}\n\nuno::Sequence< OUString > SAL_CALL SvxShapeCollection::getSupportedServiceNames() throw( uno::RuntimeException )\n{\n return getSupportedServiceNames_Static();\n}\n\nuno::Sequence< OUString > SvxShapeCollection::getSupportedServiceNames_Static()\n{\n uno::Sequence< OUString > aSeq(2);\n aSeq.getArray()[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.Shapes\") );\n aSeq.getArray()[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.ShapeCollection\") );\n return aSeq;\n}\n\nReference< XInterface > SAL_CALL SvxShapeCollection_createInstance( const Reference< ::com::sun::star::lang::XMultiServiceFactory >& )\n{\n return *( new SvxShapeCollection() );\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unoedhlp.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:10:29 $\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#pragma hdrstop\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#include \"unoedhlp.hxx\"\n#include \"editdata.hxx\"\n#include \"editeng.hxx\"\n\n\/\/------------------------------------------------------------------------\n\nTYPEINIT1( SvxEditSourceHint, TextHint );\n\nSvxEditSourceHint::SvxEditSourceHint( ULONG _nId ) :\n TextHint( _nId ),\n mnStart( 0 ),\n mnEnd( 0 )\n{\n}\n\nSvxEditSourceHint::SvxEditSourceHint( ULONG _nId, ULONG nValue, ULONG nStart, ULONG nEnd ) :\n TextHint( _nId, nValue ),\n mnStart( nStart),\n mnEnd( nEnd )\n{\n}\n\nULONG SvxEditSourceHint::GetValue() const\n{\n return TextHint::GetValue();\n}\n\nULONG SvxEditSourceHint::GetStartValue() const\n{\n return mnStart;\n}\n\nULONG SvxEditSourceHint::GetEndValue() const\n{\n return mnEnd;\n}\n\nvoid SvxEditSourceHint::SetValue( ULONG n )\n{\n TextHint::SetValue( n );\n}\n\nvoid SvxEditSourceHint::SetStartValue( ULONG n )\n{\n mnStart = n;\n}\n\nvoid SvxEditSourceHint::SetEndValue( ULONG n )\n{\n mnEnd = n;\n}\n\n\/\/------------------------------------------------------------------------\n\n::std::auto_ptr<SfxHint> SvxEditSourceHelper::EENotification2Hint( EENotify* aNotify )\n{\n if( aNotify )\n {\n switch( aNotify->eNotificationType )\n {\n case EE_NOTIFY_TEXTMODIFIED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_MODIFIED, aNotify->nParagraph ) );\n\n case EE_NOTIFY_PARAGRAPHINSERTED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_PARAINSERTED, aNotify->nParagraph ) );\n\n case EE_NOTIFY_PARAGRAPHREMOVED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_PARAREMOVED, aNotify->nParagraph ) );\n\n case EE_NOTIFY_PARAGRAPHSMOVED:\n return ::std::auto_ptr<SfxHint>( new SvxEditSourceHint( EDITSOURCE_HINT_PARASMOVED, aNotify->nParagraph, aNotify->nParam1, aNotify->nParam2 ) );\n\n case EE_NOTIFY_TEXTHEIGHTCHANGED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_TEXTHEIGHTCHANGED, aNotify->nParagraph ) );\n\n case EE_NOTIFY_TEXTVIEWSCROLLED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_VIEWSCROLLED ) );\n\n case EE_NOTIFY_TEXTVIEWSELECTIONCHANGED:\n return ::std::auto_ptr<SfxHint>( new SvxEditSourceHint( EDITSOURCE_HINT_SELECTIONCHANGED ) );\n\n case EE_NOTIFY_BLOCKNOTIFICATION_START:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_BLOCKNOTIFICATION_START, 0 ) );\n\n case EE_NOTIFY_BLOCKNOTIFICATION_END:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_BLOCKNOTIFICATION_END, 0 ) );\n\n case EE_NOTIFY_INPUT_START:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_INPUT_START, 0 ) );\n\n case EE_NOTIFY_INPUT_END:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_INPUT_END, 0 ) );\n\n default:\n DBG_ERROR( \"SvxEditSourceHelper::EENotification2Hint unknown notification\" );\n break;\n }\n }\n\n return ::std::auto_ptr<SfxHint>( new SfxHint() );\n}\n\nsal_Bool SvxEditSourceHelper::GetAttributeRun( USHORT& nStartIndex, USHORT& nEndIndex, const EditEngine& rEE, USHORT nPara, USHORT nIndex )\n{\n EECharAttribArray aCharAttribs;\n\n rEE.GetCharAttribs( nPara, aCharAttribs );\n\n \/\/ find closest index in front of nIndex\n USHORT nAttr, nCurrIndex;\n sal_Int32 nClosestStartIndex;\n for( nAttr=0, nClosestStartIndex=0; nAttr<aCharAttribs.Count(); ++nAttr )\n {\n nCurrIndex = aCharAttribs[nAttr].nStart;\n\n if( nCurrIndex > nIndex )\n break; \/\/ aCharAttribs array is sorted in increasing order for nStart values\n\n if( nCurrIndex > nClosestStartIndex )\n {\n nClosestStartIndex = nCurrIndex;\n }\n }\n\n \/\/ find closest index behind of nIndex\n sal_Int32 nClosestEndIndex;\n for( nAttr=0, nClosestEndIndex=rEE.GetTextLen(nPara); nAttr<aCharAttribs.Count(); ++nAttr )\n {\n nCurrIndex = aCharAttribs[nAttr].nEnd;\n\n if( nCurrIndex > nIndex &&\n nCurrIndex < nClosestEndIndex )\n {\n nClosestEndIndex = nCurrIndex;\n }\n }\n\n nStartIndex = static_cast<USHORT>( nClosestStartIndex );\n nEndIndex = static_cast<USHORT>( nClosestEndIndex );\n\n return sal_True;\n}\n\nPoint SvxEditSourceHelper::EEToUserSpace( const Point& rPoint, const Size& rEESize, bool bIsVertical )\n{\n return bIsVertical ? Point( -rPoint.Y() + rEESize.Height(), rPoint.X() ) : rPoint;\n}\n\nPoint SvxEditSourceHelper::UserSpaceToEE( const Point& rPoint, const Size& rEESize, bool bIsVertical )\n{\n return bIsVertical ? Point( rPoint.Y(), -rPoint.X() + rEESize.Height() ) : rPoint;\n}\n\nRectangle SvxEditSourceHelper::EEToUserSpace( const Rectangle& rRect, const Size& rEESize, bool bIsVertical )\n{\n \/\/ #106775# Don't touch rect if not vertical\n return bIsVertical ? Rectangle( EEToUserSpace(rRect.BottomLeft(), rEESize, bIsVertical),\n EEToUserSpace(rRect.TopRight(), rEESize, bIsVertical) ) : rRect;\n}\n\nRectangle SvxEditSourceHelper::UserSpaceToEE( const Rectangle& rRect, const Size& rEESize, bool bIsVertical )\n{\n \/\/ #106775# Don't touch rect if not vertical\n return bIsVertical ? Rectangle( UserSpaceToEE(rRect.TopRight(), rEESize, bIsVertical),\n UserSpaceToEE(rRect.BottomLeft(), rEESize, bIsVertical) ) : rRect;\n}\n<commit_msg>INTEGRATION: CWS warnings01 (1.7.220); FILE MERGED 2006\/02\/17 16:21:31 cl 1.7.220.1: warning free code changes<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unoedhlp.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 17:01:10 $\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 _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#include \"unoedhlp.hxx\"\n#include \"editdata.hxx\"\n#include \"editeng.hxx\"\n\n\/\/------------------------------------------------------------------------\n\nTYPEINIT1( SvxEditSourceHint, TextHint );\n\nSvxEditSourceHint::SvxEditSourceHint( ULONG _nId ) :\n TextHint( _nId ),\n mnStart( 0 ),\n mnEnd( 0 )\n{\n}\n\nSvxEditSourceHint::SvxEditSourceHint( ULONG _nId, ULONG nValue, ULONG nStart, ULONG nEnd ) :\n TextHint( _nId, nValue ),\n mnStart( nStart),\n mnEnd( nEnd )\n{\n}\n\nULONG SvxEditSourceHint::GetValue() const\n{\n return TextHint::GetValue();\n}\n\nULONG SvxEditSourceHint::GetStartValue() const\n{\n return mnStart;\n}\n\nULONG SvxEditSourceHint::GetEndValue() const\n{\n return mnEnd;\n}\n\nvoid SvxEditSourceHint::SetValue( ULONG n )\n{\n TextHint::SetValue( n );\n}\n\nvoid SvxEditSourceHint::SetStartValue( ULONG n )\n{\n mnStart = n;\n}\n\nvoid SvxEditSourceHint::SetEndValue( ULONG n )\n{\n mnEnd = n;\n}\n\n\/\/------------------------------------------------------------------------\n\n::std::auto_ptr<SfxHint> SvxEditSourceHelper::EENotification2Hint( EENotify* aNotify )\n{\n if( aNotify )\n {\n switch( aNotify->eNotificationType )\n {\n case EE_NOTIFY_TEXTMODIFIED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_MODIFIED, aNotify->nParagraph ) );\n\n case EE_NOTIFY_PARAGRAPHINSERTED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_PARAINSERTED, aNotify->nParagraph ) );\n\n case EE_NOTIFY_PARAGRAPHREMOVED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_PARAREMOVED, aNotify->nParagraph ) );\n\n case EE_NOTIFY_PARAGRAPHSMOVED:\n return ::std::auto_ptr<SfxHint>( new SvxEditSourceHint( EDITSOURCE_HINT_PARASMOVED, aNotify->nParagraph, aNotify->nParam1, aNotify->nParam2 ) );\n\n case EE_NOTIFY_TEXTHEIGHTCHANGED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_TEXTHEIGHTCHANGED, aNotify->nParagraph ) );\n\n case EE_NOTIFY_TEXTVIEWSCROLLED:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_VIEWSCROLLED ) );\n\n case EE_NOTIFY_TEXTVIEWSELECTIONCHANGED:\n return ::std::auto_ptr<SfxHint>( new SvxEditSourceHint( EDITSOURCE_HINT_SELECTIONCHANGED ) );\n\n case EE_NOTIFY_BLOCKNOTIFICATION_START:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_BLOCKNOTIFICATION_START, 0 ) );\n\n case EE_NOTIFY_BLOCKNOTIFICATION_END:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_BLOCKNOTIFICATION_END, 0 ) );\n\n case EE_NOTIFY_INPUT_START:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_INPUT_START, 0 ) );\n\n case EE_NOTIFY_INPUT_END:\n return ::std::auto_ptr<SfxHint>( new TextHint( TEXT_HINT_INPUT_END, 0 ) );\n\n default:\n DBG_ERROR( \"SvxEditSourceHelper::EENotification2Hint unknown notification\" );\n break;\n }\n }\n\n return ::std::auto_ptr<SfxHint>( new SfxHint() );\n}\n\nsal_Bool SvxEditSourceHelper::GetAttributeRun( USHORT& nStartIndex, USHORT& nEndIndex, const EditEngine& rEE, USHORT nPara, USHORT nIndex )\n{\n EECharAttribArray aCharAttribs;\n\n rEE.GetCharAttribs( nPara, aCharAttribs );\n\n \/\/ find closest index in front of nIndex\n USHORT nAttr, nCurrIndex;\n sal_Int32 nClosestStartIndex;\n for( nAttr=0, nClosestStartIndex=0; nAttr<aCharAttribs.Count(); ++nAttr )\n {\n nCurrIndex = aCharAttribs[nAttr].nStart;\n\n if( nCurrIndex > nIndex )\n break; \/\/ aCharAttribs array is sorted in increasing order for nStart values\n\n if( nCurrIndex > nClosestStartIndex )\n {\n nClosestStartIndex = nCurrIndex;\n }\n }\n\n \/\/ find closest index behind of nIndex\n sal_Int32 nClosestEndIndex;\n for( nAttr=0, nClosestEndIndex=rEE.GetTextLen(nPara); nAttr<aCharAttribs.Count(); ++nAttr )\n {\n nCurrIndex = aCharAttribs[nAttr].nEnd;\n\n if( nCurrIndex > nIndex &&\n nCurrIndex < nClosestEndIndex )\n {\n nClosestEndIndex = nCurrIndex;\n }\n }\n\n nStartIndex = static_cast<USHORT>( nClosestStartIndex );\n nEndIndex = static_cast<USHORT>( nClosestEndIndex );\n\n return sal_True;\n}\n\nPoint SvxEditSourceHelper::EEToUserSpace( const Point& rPoint, const Size& rEESize, bool bIsVertical )\n{\n return bIsVertical ? Point( -rPoint.Y() + rEESize.Height(), rPoint.X() ) : rPoint;\n}\n\nPoint SvxEditSourceHelper::UserSpaceToEE( const Point& rPoint, const Size& rEESize, bool bIsVertical )\n{\n return bIsVertical ? Point( rPoint.Y(), -rPoint.X() + rEESize.Height() ) : rPoint;\n}\n\nRectangle SvxEditSourceHelper::EEToUserSpace( const Rectangle& rRect, const Size& rEESize, bool bIsVertical )\n{\n \/\/ #106775# Don't touch rect if not vertical\n return bIsVertical ? Rectangle( EEToUserSpace(rRect.BottomLeft(), rEESize, bIsVertical),\n EEToUserSpace(rRect.TopRight(), rEESize, bIsVertical) ) : rRect;\n}\n\nRectangle SvxEditSourceHelper::UserSpaceToEE( const Rectangle& rRect, const Size& rEESize, bool bIsVertical )\n{\n \/\/ #106775# Don't touch rect if not vertical\n return bIsVertical ? Rectangle( UserSpaceToEE(rRect.TopRight(), rEESize, bIsVertical),\n UserSpaceToEE(rRect.BottomLeft(), rEESize, bIsVertical) ) : rRect;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: visiturl.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: jp $ $Date: 2001-08-31 11:07:56 $\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#ifdef PRECOMPILED\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\n#ifndef _SFXDOCFILE_HXX \/\/autogen\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef _INETHIST_HXX \/\/autogen\n#include <svtools\/inethist.hxx>\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen\n#include <tools\/urlobj.hxx>\n#endif\n\n#ifndef _FMTINFMT_HXX \/\/autogen\n#include <fmtinfmt.hxx>\n#endif\n#ifndef _TXTINET_HXX \/\/autogen\n#include <txtinet.hxx>\n#endif\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _VISITURL_HXX\n#include <visiturl.hxx>\n#endif\n#ifndef _HINTS_HXX\n#include <hints.hxx>\n#endif\n#ifndef _NDTXT_HXX\n#include <ndtxt.hxx>\n#endif\n#ifndef _EDITSH_HXX\n#include <editsh.hxx>\n#endif\n#ifndef _DOCSH_HXX\n#include <docsh.hxx>\n#endif\n\n\nSwURLStateChanged::SwURLStateChanged( const SwDoc* pD )\n : pDoc( pD )\n{\n StartListening( *INetURLHistory::GetOrCreate() );\n}\n\nSwURLStateChanged::~SwURLStateChanged()\n{\n EndListening( *INetURLHistory::GetOrCreate() );\n}\n\nvoid SwURLStateChanged::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )\n{\n if( rHint.ISA( INetURLHistoryHint ) && pDoc->GetRootFrm() )\n {\n \/\/ diese URL wurde veraendert:\n const INetURLObject* pIURL = ((INetURLHistoryHint&)rHint).GetObject();\n String sURL( pIURL->GetMainURL( INetURLObject::NO_DECODE ) ), sBkmk;\n\n SwEditShell* pESh = pDoc->GetEditShell();\n\n if( pDoc->GetDocShell() && pDoc->GetDocShell()->GetMedium() &&\n \/\/ falls das unser Doc ist, kann es auch lokale Spruenge geben!\n sURL == pDoc->GetDocShell()->GetMedium()->GetName() )\n (sBkmk = pIURL->GetMark()).Insert( INET_MARK_TOKEN, 0 );\n\n BOOL bAction = FALSE, bUnLockView = FALSE;\n const SwFmtINetFmt* pItem;\n const SwTxtINetFmt* pTxtAttr;\n const SwTxtNode* pTxtNd;\n USHORT n, nMaxItems = pDoc->GetAttrPool().GetItemCount( RES_TXTATR_INETFMT );\n for( n = 0; n < nMaxItems; ++n )\n if( 0 != (pItem = (SwFmtINetFmt*)pDoc->GetAttrPool().GetItem(\n RES_TXTATR_INETFMT, n ) ) &&\n ( pItem->GetValue() == sURL ||\n ( sBkmk.Len() && pItem->GetValue() == sBkmk )) &&\n 0 != ( pTxtAttr = pItem->GetTxtINetFmt()) &&\n 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) )\n {\n if( !bAction && pESh )\n {\n pESh->StartAllAction();\n bAction = TRUE;\n bUnLockView = !pESh->IsViewLocked();\n pESh->LockView( TRUE );\n }\n ((SwTxtINetFmt*)pTxtAttr)->SetValidVis( FALSE );\n const SwTxtAttr* pAttr = pTxtAttr;\n SwUpdateAttr aUpdateAttr( *pAttr->GetStart(),\n *pAttr->GetEnd(),\n RES_FMT_CHG );\n ((SwTxtNode*)pTxtNd)->SwCntntNode::Modify( &aUpdateAttr,\n &aUpdateAttr );\n }\n\n if( bAction )\n pESh->EndAllAction();\n if( bUnLockView )\n pESh->LockView( FALSE );\n }\n}\n\n \/\/ erfrage ob die URL besucht war. Uebers Doc, falls nur ein Bookmark\n \/\/ angegeben ist. Dann muss der Doc. Name davor gesetzt werden!\nBOOL SwDoc::IsVisitedURL( const String& rURL ) const\n{\n#ifdef DEBUG\n static long nTmp = 0;\n ++nTmp;\n#endif\n\n BOOL bRet = FALSE;\n if( rURL.Len() )\n {\n INetURLHistory *pHist = INetURLHistory::GetOrCreate();\n if( '#' == rURL.GetChar( 0 ) && pDocShell && pDocShell->GetMedium() )\n {\n INetURLObject aIObj( pDocShell->GetMedium()->GetURLObject() );\n aIObj.SetMark( rURL.Copy( 1 ) );\n bRet = pHist->QueryUrl( aIObj );\n }\n else\n bRet = pHist->QueryUrl( rURL );\n\n \/\/ dann wollen wird auch ueber Statusaenderungen in der History\n \/\/ informiert werden!\n if( !pURLStateChgd )\n {\n SwDoc* pD = (SwDoc*)this;\n pD->pURLStateChgd = new SwURLStateChanged( this );\n }\n }\n return bRet;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS dbgmacros1 (1.2.170); FILE MERGED 2003\/04\/10 09:01:06 kso 1.2.170.1: #108413# - debug macro unification.<commit_after>\/*************************************************************************\n *\n * $RCSfile: visiturl.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-04-15 16:49:09 $\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#ifdef PRECOMPILED\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\n#ifndef _SFXDOCFILE_HXX \/\/autogen\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef _INETHIST_HXX \/\/autogen\n#include <svtools\/inethist.hxx>\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen\n#include <tools\/urlobj.hxx>\n#endif\n\n#ifndef _FMTINFMT_HXX \/\/autogen\n#include <fmtinfmt.hxx>\n#endif\n#ifndef _TXTINET_HXX \/\/autogen\n#include <txtinet.hxx>\n#endif\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _VISITURL_HXX\n#include <visiturl.hxx>\n#endif\n#ifndef _HINTS_HXX\n#include <hints.hxx>\n#endif\n#ifndef _NDTXT_HXX\n#include <ndtxt.hxx>\n#endif\n#ifndef _EDITSH_HXX\n#include <editsh.hxx>\n#endif\n#ifndef _DOCSH_HXX\n#include <docsh.hxx>\n#endif\n\n\nSwURLStateChanged::SwURLStateChanged( const SwDoc* pD )\n : pDoc( pD )\n{\n StartListening( *INetURLHistory::GetOrCreate() );\n}\n\nSwURLStateChanged::~SwURLStateChanged()\n{\n EndListening( *INetURLHistory::GetOrCreate() );\n}\n\nvoid SwURLStateChanged::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )\n{\n if( rHint.ISA( INetURLHistoryHint ) && pDoc->GetRootFrm() )\n {\n \/\/ diese URL wurde veraendert:\n const INetURLObject* pIURL = ((INetURLHistoryHint&)rHint).GetObject();\n String sURL( pIURL->GetMainURL( INetURLObject::NO_DECODE ) ), sBkmk;\n\n SwEditShell* pESh = pDoc->GetEditShell();\n\n if( pDoc->GetDocShell() && pDoc->GetDocShell()->GetMedium() &&\n \/\/ falls das unser Doc ist, kann es auch lokale Spruenge geben!\n sURL == pDoc->GetDocShell()->GetMedium()->GetName() )\n (sBkmk = pIURL->GetMark()).Insert( INET_MARK_TOKEN, 0 );\n\n BOOL bAction = FALSE, bUnLockView = FALSE;\n const SwFmtINetFmt* pItem;\n const SwTxtINetFmt* pTxtAttr;\n const SwTxtNode* pTxtNd;\n USHORT n, nMaxItems = pDoc->GetAttrPool().GetItemCount( RES_TXTATR_INETFMT );\n for( n = 0; n < nMaxItems; ++n )\n if( 0 != (pItem = (SwFmtINetFmt*)pDoc->GetAttrPool().GetItem(\n RES_TXTATR_INETFMT, n ) ) &&\n ( pItem->GetValue() == sURL ||\n ( sBkmk.Len() && pItem->GetValue() == sBkmk )) &&\n 0 != ( pTxtAttr = pItem->GetTxtINetFmt()) &&\n 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) )\n {\n if( !bAction && pESh )\n {\n pESh->StartAllAction();\n bAction = TRUE;\n bUnLockView = !pESh->IsViewLocked();\n pESh->LockView( TRUE );\n }\n ((SwTxtINetFmt*)pTxtAttr)->SetValidVis( FALSE );\n const SwTxtAttr* pAttr = pTxtAttr;\n SwUpdateAttr aUpdateAttr( *pAttr->GetStart(),\n *pAttr->GetEnd(),\n RES_FMT_CHG );\n ((SwTxtNode*)pTxtNd)->SwCntntNode::Modify( &aUpdateAttr,\n &aUpdateAttr );\n }\n\n if( bAction )\n pESh->EndAllAction();\n if( bUnLockView )\n pESh->LockView( FALSE );\n }\n}\n\n \/\/ erfrage ob die URL besucht war. Uebers Doc, falls nur ein Bookmark\n \/\/ angegeben ist. Dann muss der Doc. Name davor gesetzt werden!\nBOOL SwDoc::IsVisitedURL( const String& rURL ) const\n{\n#if OSL_DEBUG_LEVEL > 1\n static long nTmp = 0;\n ++nTmp;\n#endif\n\n BOOL bRet = FALSE;\n if( rURL.Len() )\n {\n INetURLHistory *pHist = INetURLHistory::GetOrCreate();\n if( '#' == rURL.GetChar( 0 ) && pDocShell && pDocShell->GetMedium() )\n {\n INetURLObject aIObj( pDocShell->GetMedium()->GetURLObject() );\n aIObj.SetMark( rURL.Copy( 1 ) );\n bRet = pHist->QueryUrl( aIObj );\n }\n else\n bRet = pHist->QueryUrl( rURL );\n\n \/\/ dann wollen wird auch ueber Statusaenderungen in der History\n \/\/ informiert werden!\n if( !pURLStateChgd )\n {\n SwDoc* pD = (SwDoc*)this;\n pD->pURLStateChgd = new SwURLStateChanged( this );\n }\n }\n return bRet;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef BLUETOE_ENCRYPTION_HPP\n#define BLUETOE_ENCRYPTION_HPP\n\n#include <bluetoe\/options.hpp>\n#include <bluetoe\/meta_types.hpp>\n\nnamespace bluetoe {\n\n template < typename ... Options >\n class server;\n\n template < typename ... Options >\n class service;\n\n template < typename ... Options >\n class characteristic;\n\n namespace details {\n struct requires_encryption_meta_type {};\n struct no_encryption_required_meta_type {};\n struct may_require_encryption_meta_type {};\n };\n\n \/**\n * @brief defines that access to characteristic(s) require an encrypted link without\n * MITM Protection.\n *\n * Can be used on server, service or characteristic level to define that the access\n * to a characteristic requires an encrypted link. If the link is not encrypted,\n * when accessing the characteristic, Bluetoe replies with an ATT Insufficient Authorization\n * error, if the requesting device is not paired and ATT Insufficient Encryption, if the\n * device is paired, but the link is not encrypted.\n * (see table 10.2 Vol 3, Part C, 10.3.1)\n *\n * If applied to a server or service definition, this definition applies to all containing\n * characteristics, where it can be overridden.\n *\n * Example\n * @code\n char simple_value = 0;\n constexpr char name[] = \"This is the name of the characteristic\";\n\n using server = bluetoe::server<\n \/\/ By default, require encryption for all characteristics of\n \/\/ all services.\n bluetoe::requires_encryption,\n \/\/ Service A\n bluetoe::service<\n \/\/ But for this service, no encryption is required\n bluetoe::no_encryption_required,\n service_uuid_a,\n ...\n >,\n \/\/ Service B\n bluetoe::service<\n service_uuid_b,\n bluetoe::characteristic<\n char_uuid,\n \/\/ For all characteristics of this service, but this characteristic,\n \/\/ encryption is required\n bluetoe::no_encryption_required\n >,\n ...\n >,\n \/\/ Service C\n >;\n * @endcode\n *\n * @sa characteristic\n * @sa service\n * @sa server\n * @sa no_encryption_required\n * @sa may_require_encryption\n *\/\n struct requires_encryption {\n \/** @cond HIDDEN_SYMBOLS *\/\n struct meta_type :\n details::requires_encryption_meta_type,\n details::valid_server_option_meta_type,\n details::valid_service_option_meta_type,\n details::valid_characteristic_option_meta_type {};\n \/** @endcond *\/\n };\n\n \/**\n * @brief defines that access to characteristic(s) does not require an encrypted link.\n *\n * If applied to a server or service definition, this definition applies to all containing\n * characteristics, where it can be overridden.\n *\n * If no characteristic in the entire server requires encryption, Bluetoe will leave out\n * the support code for encryption.\n *\n * @sa requires_encryption\n * @sa may_require_encryption\n *\/\n struct no_encryption_required {\n \/** @cond HIDDEN_SYMBOLS *\/\n struct meta_type :\n details::no_encryption_required_meta_type,\n details::valid_server_option_meta_type,\n details::valid_service_option_meta_type,\n details::valid_characteristic_option_meta_type {};\n \/** @endcond *\/\n };\n\n \/**\n * @brief defines that a characteristic may require encyption\n *\n * The declaration forces bluetoe add the required code for encrypting\n * links. Basecally this means that a custom characterstic read or write handler\n * may require encryption under specific circumstances.\n *\n * This option can be passed to a server, service or a characteristic declaration.\n *\n * @sa requires_encryption\n * @sa no_encryption_required\n *\/\n struct may_require_encryption {\n \/** @cond HIDDEN_SYMBOLS *\/\n struct meta_type :\n details::may_require_encryption_meta_type,\n details::valid_server_option_meta_type,\n details::valid_service_option_meta_type,\n details::valid_characteristic_option_meta_type {};\n \/** @endcond *\/\n };\n\n namespace details {\n\n template < typename Server, bool Default = false >\n struct requires_encryption_support_t\n {\n static bool constexpr value = Default;\n };\n\n template < typename ... Options, typename T >\n struct requires_encryption_support_t< std::tuple< T, Options... >, false >\n {\n static bool constexpr value =\n requires_encryption_support_t< T, false >::value\n || requires_encryption_support_t< std::tuple< Options... >, false >::value;\n };\n\n template < typename ... Options, typename T >\n struct requires_encryption_support_t< std::tuple< T, Options... >, true >\n {\n static bool constexpr value =\n requires_encryption_support_t< T, true >::value\n && requires_encryption_support_t< std::tuple< Options... >, true >::value;\n };\n\n template < bool Default, typename ... Options >\n struct encryption_default\n {\n static bool constexpr require_encryption =\n details::has_option< requires_encryption, Options... >::value\n || details::has_option< may_require_encryption, Options... >::value;\n\n static bool constexpr require_not_encryption =\n details::has_option< no_encryption_required, Options... >::value;\n\n \/\/ require !require default | value\n \/\/ true false false | true\n \/\/ false true false | false\n \/\/ false false false | false\n \/\/ true false true | true\n \/\/ false true true | false\n \/\/ false false true | true\n static bool constexpr value =\n ( require_encryption && !require_not_encryption )\n || ( !require_encryption && !require_not_encryption && Default );\n\n };\n\n template < typename ... Options, bool Default >\n struct requires_encryption_support_t< bluetoe::server< Options... >, Default > {\n static bool constexpr default_val = encryption_default< Default, Options... >::value;\n\n static bool constexpr value =\n requires_encryption_support_t<\n typename bluetoe::server< Options... >::services,\n default_val >::value;\n };\n\n template < typename ... Options, bool Default >\n struct requires_encryption_support_t< bluetoe::service< Options... >, Default > {\n static bool constexpr default_val = encryption_default< Default, Options... >::value;\n\n static bool constexpr value =\n requires_encryption_support_t<\n typename bluetoe::service< Options... >::characteristics,\n default_val >::value;\n };\n\n template < typename ... Options, bool Default >\n struct requires_encryption_support_t< bluetoe::characteristic< Options... >, Default > {\n \/\/ @TODO the default for a characteristic should always be true\n static bool constexpr value = encryption_default< Default, Options... >::value;\n };\n\n template < typename Characteristic, typename Service, typename Server >\n struct characteristic_requires_encryption;\n\n template < typename ... CharacteristicOptions, typename ... ServiceOptions, typename ... ServerOptions >\n struct characteristic_requires_encryption<\n bluetoe::characteristic< CharacteristicOptions... >,\n bluetoe::service< ServiceOptions... >,\n bluetoe::server< ServerOptions... > >\n {\n \/\/ @TODO the default for a characteristic should always be true\n static bool constexpr server_requires_encryption = encryption_default< false, ServerOptions... >::value;\n static bool constexpr service_requires_encryption = encryption_default< server_requires_encryption, ServiceOptions... >::value;\n\n static bool constexpr value = encryption_default< service_requires_encryption, CharacteristicOptions... >::value;\n };\n }\n\n} \/\/ namespace bluetoe\n\n#endif\n<commit_msg>; removed<commit_after>#ifndef BLUETOE_ENCRYPTION_HPP\n#define BLUETOE_ENCRYPTION_HPP\n\n#include <bluetoe\/options.hpp>\n#include <bluetoe\/meta_types.hpp>\n\nnamespace bluetoe {\n\n template < typename ... Options >\n class server;\n\n template < typename ... Options >\n class service;\n\n template < typename ... Options >\n class characteristic;\n\n namespace details {\n struct requires_encryption_meta_type {};\n struct no_encryption_required_meta_type {};\n struct may_require_encryption_meta_type {};\n }\n\n \/**\n * @brief defines that access to characteristic(s) require an encrypted link without\n * MITM Protection.\n *\n * Can be used on server, service or characteristic level to define that the access\n * to a characteristic requires an encrypted link. If the link is not encrypted,\n * when accessing the characteristic, Bluetoe replies with an ATT Insufficient Authorization\n * error, if the requesting device is not paired and ATT Insufficient Encryption, if the\n * device is paired, but the link is not encrypted.\n * (see table 10.2 Vol 3, Part C, 10.3.1)\n *\n * If applied to a server or service definition, this definition applies to all containing\n * characteristics, where it can be overridden.\n *\n * Example\n * @code\n char simple_value = 0;\n constexpr char name[] = \"This is the name of the characteristic\";\n\n using server = bluetoe::server<\n \/\/ By default, require encryption for all characteristics of\n \/\/ all services.\n bluetoe::requires_encryption,\n \/\/ Service A\n bluetoe::service<\n \/\/ But for this service, no encryption is required\n bluetoe::no_encryption_required,\n service_uuid_a,\n ...\n >,\n \/\/ Service B\n bluetoe::service<\n service_uuid_b,\n bluetoe::characteristic<\n char_uuid,\n \/\/ For all characteristics of this service, but this characteristic,\n \/\/ encryption is required\n bluetoe::no_encryption_required\n >,\n ...\n >,\n \/\/ Service C\n >;\n * @endcode\n *\n * @sa characteristic\n * @sa service\n * @sa server\n * @sa no_encryption_required\n * @sa may_require_encryption\n *\/\n struct requires_encryption {\n \/** @cond HIDDEN_SYMBOLS *\/\n struct meta_type :\n details::requires_encryption_meta_type,\n details::valid_server_option_meta_type,\n details::valid_service_option_meta_type,\n details::valid_characteristic_option_meta_type {};\n \/** @endcond *\/\n };\n\n \/**\n * @brief defines that access to characteristic(s) does not require an encrypted link.\n *\n * If applied to a server or service definition, this definition applies to all containing\n * characteristics, where it can be overridden.\n *\n * If no characteristic in the entire server requires encryption, Bluetoe will leave out\n * the support code for encryption.\n *\n * @sa requires_encryption\n * @sa may_require_encryption\n *\/\n struct no_encryption_required {\n \/** @cond HIDDEN_SYMBOLS *\/\n struct meta_type :\n details::no_encryption_required_meta_type,\n details::valid_server_option_meta_type,\n details::valid_service_option_meta_type,\n details::valid_characteristic_option_meta_type {};\n \/** @endcond *\/\n };\n\n \/**\n * @brief defines that a characteristic may require encyption\n *\n * The declaration forces bluetoe add the required code for encrypting\n * links. Basecally this means that a custom characterstic read or write handler\n * may require encryption under specific circumstances.\n *\n * This option can be passed to a server, service or a characteristic declaration.\n *\n * @sa requires_encryption\n * @sa no_encryption_required\n *\/\n struct may_require_encryption {\n \/** @cond HIDDEN_SYMBOLS *\/\n struct meta_type :\n details::may_require_encryption_meta_type,\n details::valid_server_option_meta_type,\n details::valid_service_option_meta_type,\n details::valid_characteristic_option_meta_type {};\n \/** @endcond *\/\n };\n\n namespace details {\n\n template < typename Server, bool Default = false >\n struct requires_encryption_support_t\n {\n static bool constexpr value = Default;\n };\n\n template < typename ... Options, typename T >\n struct requires_encryption_support_t< std::tuple< T, Options... >, false >\n {\n static bool constexpr value =\n requires_encryption_support_t< T, false >::value\n || requires_encryption_support_t< std::tuple< Options... >, false >::value;\n };\n\n template < typename ... Options, typename T >\n struct requires_encryption_support_t< std::tuple< T, Options... >, true >\n {\n static bool constexpr value =\n requires_encryption_support_t< T, true >::value\n && requires_encryption_support_t< std::tuple< Options... >, true >::value;\n };\n\n template < bool Default, typename ... Options >\n struct encryption_default\n {\n static bool constexpr require_encryption =\n details::has_option< requires_encryption, Options... >::value\n || details::has_option< may_require_encryption, Options... >::value;\n\n static bool constexpr require_not_encryption =\n details::has_option< no_encryption_required, Options... >::value;\n\n \/\/ require !require default | value\n \/\/ true false false | true\n \/\/ false true false | false\n \/\/ false false false | false\n \/\/ true false true | true\n \/\/ false true true | false\n \/\/ false false true | true\n static bool constexpr value =\n ( require_encryption && !require_not_encryption )\n || ( !require_encryption && !require_not_encryption && Default );\n\n };\n\n template < typename ... Options, bool Default >\n struct requires_encryption_support_t< bluetoe::server< Options... >, Default > {\n static bool constexpr default_val = encryption_default< Default, Options... >::value;\n\n static bool constexpr value =\n requires_encryption_support_t<\n typename bluetoe::server< Options... >::services,\n default_val >::value;\n };\n\n template < typename ... Options, bool Default >\n struct requires_encryption_support_t< bluetoe::service< Options... >, Default > {\n static bool constexpr default_val = encryption_default< Default, Options... >::value;\n\n static bool constexpr value =\n requires_encryption_support_t<\n typename bluetoe::service< Options... >::characteristics,\n default_val >::value;\n };\n\n template < typename ... Options, bool Default >\n struct requires_encryption_support_t< bluetoe::characteristic< Options... >, Default > {\n \/\/ @TODO the default for a characteristic should always be true\n static bool constexpr value = encryption_default< Default, Options... >::value;\n };\n\n template < typename Characteristic, typename Service, typename Server >\n struct characteristic_requires_encryption;\n\n template < typename ... CharacteristicOptions, typename ... ServiceOptions, typename ... ServerOptions >\n struct characteristic_requires_encryption<\n bluetoe::characteristic< CharacteristicOptions... >,\n bluetoe::service< ServiceOptions... >,\n bluetoe::server< ServerOptions... > >\n {\n \/\/ @TODO the default for a characteristic should always be true\n static bool constexpr server_requires_encryption = encryption_default< false, ServerOptions... >::value;\n static bool constexpr service_requires_encryption = encryption_default< server_requires_encryption, ServiceOptions... >::value;\n\n static bool constexpr value = encryption_default< service_requires_encryption, CharacteristicOptions... >::value;\n };\n }\n\n} \/\/ namespace bluetoe\n\n#endif\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Translate German comments, fix some English ones<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: splittbl.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2007-04-26 09:20:21 $\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_sw.hxx\"\n\n#ifdef SW_DLLIMPLEMENTATION\n#undef SW_DLLIMPLEMENTATION\n#endif\n\n\n\n#ifndef _WRTSH_HXX \/\/autogen\n#include <wrtsh.hxx>\n#endif\n#ifndef _SPLITTBL_HXX\n#include <splittbl.hxx>\n#endif\n#include <splittbl.hrc>\n#include <table.hrc>\n#ifndef _TBLENUM_HXX\n#include <tblenum.hxx>\n#endif\n\/*-----------------17.03.98 10:56-------------------\n\n--------------------------------------------------*\/\nSwSplitTblDlg::SwSplitTblDlg( Window *pParent, SwWrtShell &rSh ) :\n SvxStandardDialog(pParent, SW_RES(DLG_SPLIT_TABLE)),\n aOKPB( this, SW_RES(PB_OK )),\n aCancelPB( this, SW_RES(PB_CANCEL )),\n aHelpPB( this, SW_RES(PB_HELP )),\n aSplitFL( this, SW_RES(FL_SPLIT )),\n aCntntCopyRB( this, SW_RES(RB_CNTNT )),\n aBoxAttrCopyWithParaRB( this, SW_RES(RB_BOX_PARA )),\n aBoxAttrCopyNoParaRB( this, SW_RES(RB_BOX_NOPARA)),\n aBorderCopyRB( this, SW_RES(RB_BORDER )),\n rShell(rSh)\n{\n FreeResource();\n aCntntCopyRB.Check();\n}\n\n\/*-----------------17.03.98 10:56-------------------\n\n--------------------------------------------------*\/\nvoid SwSplitTblDlg::Apply()\n{\n USHORT nSplit = HEADLINE_CNTNTCOPY;\n if(aBoxAttrCopyWithParaRB.IsChecked())\n nSplit = HEADLINE_BOXATRCOLLCOPY;\n if(aBoxAttrCopyNoParaRB.IsChecked())\n nSplit = HEADLINE_BOXATTRCOPY;\n else if(aBorderCopyRB.IsChecked())\n nSplit = HEADLINE_BORDERCOPY;\n\n rShell.SplitTable( nSplit );\n\n}\n\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.8.438); FILE MERGED 2008\/04\/01 12:55:52 thb 1.8.438.2: #i85898# Stripping all external header guards 2008\/03\/31 16:59:35 rt 1.8.438.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: splittbl.cxx,v $\n * $Revision: 1.9 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_sw.hxx\"\n\n#ifdef SW_DLLIMPLEMENTATION\n#undef SW_DLLIMPLEMENTATION\n#endif\n\n\n#include <wrtsh.hxx>\n#include <splittbl.hxx>\n#include <splittbl.hrc>\n#include <table.hrc>\n#include <tblenum.hxx>\n\/*-----------------17.03.98 10:56-------------------\n\n--------------------------------------------------*\/\nSwSplitTblDlg::SwSplitTblDlg( Window *pParent, SwWrtShell &rSh ) :\n SvxStandardDialog(pParent, SW_RES(DLG_SPLIT_TABLE)),\n aOKPB( this, SW_RES(PB_OK )),\n aCancelPB( this, SW_RES(PB_CANCEL )),\n aHelpPB( this, SW_RES(PB_HELP )),\n aSplitFL( this, SW_RES(FL_SPLIT )),\n aCntntCopyRB( this, SW_RES(RB_CNTNT )),\n aBoxAttrCopyWithParaRB( this, SW_RES(RB_BOX_PARA )),\n aBoxAttrCopyNoParaRB( this, SW_RES(RB_BOX_NOPARA)),\n aBorderCopyRB( this, SW_RES(RB_BORDER )),\n rShell(rSh)\n{\n FreeResource();\n aCntntCopyRB.Check();\n}\n\n\/*-----------------17.03.98 10:56-------------------\n\n--------------------------------------------------*\/\nvoid SwSplitTblDlg::Apply()\n{\n USHORT nSplit = HEADLINE_CNTNTCOPY;\n if(aBoxAttrCopyWithParaRB.IsChecked())\n nSplit = HEADLINE_BOXATRCOLLCOPY;\n if(aBoxAttrCopyNoParaRB.IsChecked())\n nSplit = HEADLINE_BOXATTRCOPY;\n else if(aBorderCopyRB.IsChecked())\n nSplit = HEADLINE_BORDERCOPY;\n\n rShell.SplitTable( nSplit );\n\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>refactor AutoFmtPreview to use RenderContext<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/framework\/ir\/graph.h\"\n#include \"paddle\/fluid\/framework\/program_desc.h\"\n#include \"paddle\/fluid\/framework\/var_desc.h\"\n\nnamespace paddle {\nnamespace framework {\n\n\/\/ NOTE(paddle-dev): This graph contains circle.\nGraph::Graph(const ProgramDesc &program) : program_(program) {\n VLOG(3) << \"block in program:\" << program_.Size();\n std::unordered_map<std::string, VarDesc *> all_vars;\n for (auto *var : program.Block(0).AllVars()) {\n all_vars.emplace(var->Name(), var);\n }\n\n std::map<std::string, ir::Node *> var_nodes;\n for (auto *op : program.Block(0).AllOps()) {\n ir::Node *node = CreateOpNode(op);\n\n for (auto &each_var_name : op->InputArgumentNames()) {\n ir::Node *var = nullptr;\n if (var_nodes.find(each_var_name) != var_nodes.end()) {\n var = var_nodes.at(each_var_name);\n } else if (all_vars.count(each_var_name) != 0) {\n var = CreateVarNode(all_vars.at(each_var_name));\n var_nodes[each_var_name] = var;\n } else {\n \/\/ TODO(paddle-dev): Seems some assumption doesn't hold?\n LOG(ERROR) << op->Type()\n << \" input var not in all_var list: \" << each_var_name;\n var = CreateEmptyNode(each_var_name, ir::Node::Type::kVariable);\n var_nodes[each_var_name] = var;\n }\n node->inputs.push_back(var);\n var->outputs.push_back(node);\n }\n\n for (auto &each_var_name : op->OutputArgumentNames()) {\n ir::Node *var = nullptr;\n if (var_nodes.find(each_var_name) != var_nodes.end()) {\n var = var_nodes.at(each_var_name);\n } else {\n var = CreateVarNode(all_vars.at(each_var_name));\n var_nodes[each_var_name] = var;\n }\n node->outputs.push_back(var);\n var->inputs.push_back(node);\n }\n }\n}\n} \/\/ namespace framework\n} \/\/ namespace paddle\n<commit_msg>disable warning<commit_after>\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/framework\/ir\/graph.h\"\n#include \"paddle\/fluid\/framework\/program_desc.h\"\n#include \"paddle\/fluid\/framework\/var_desc.h\"\n\nnamespace paddle {\nnamespace framework {\n\n\/\/ NOTE(paddle-dev): This graph contains circle.\nGraph::Graph(const ProgramDesc &program) : program_(program) {\n VLOG(3) << \"block in program:\" << program_.Size();\n std::unordered_map<std::string, VarDesc *> all_vars;\n for (auto *var : program.Block(0).AllVars()) {\n all_vars.emplace(var->Name(), var);\n }\n\n std::map<std::string, ir::Node *> var_nodes;\n for (auto *op : program.Block(0).AllOps()) {\n ir::Node *node = CreateOpNode(op);\n\n for (auto &each_var_name : op->InputArgumentNames()) {\n ir::Node *var = nullptr;\n if (var_nodes.find(each_var_name) != var_nodes.end()) {\n var = var_nodes.at(each_var_name);\n } else if (all_vars.count(each_var_name) != 0) {\n var = CreateVarNode(all_vars.at(each_var_name));\n var_nodes[each_var_name] = var;\n } else {\n \/\/ TODO(paddle-dev): Seems some assumption doesn't hold?\n VLOG(3) << op->Type()\n << \" input var not in all_var list: \" << each_var_name;\n var = CreateEmptyNode(each_var_name, ir::Node::Type::kVariable);\n var_nodes[each_var_name] = var;\n }\n node->inputs.push_back(var);\n var->outputs.push_back(node);\n }\n\n for (auto &each_var_name : op->OutputArgumentNames()) {\n ir::Node *var = nullptr;\n if (var_nodes.find(each_var_name) != var_nodes.end()) {\n var = var_nodes.at(each_var_name);\n } else {\n var = CreateVarNode(all_vars.at(each_var_name));\n var_nodes[each_var_name] = var;\n }\n node->outputs.push_back(var);\n var->inputs.push_back(node);\n }\n }\n}\n} \/\/ namespace framework\n} \/\/ namespace paddle\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2015 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : scene\/test\/loader_mtl.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ includes, system\n\n#include <array> \/\/ std::array<>\n#include <glm\/gtx\/io.hpp> \/\/ glm::io::*\n\n\/\/ includes, project\n\n#include <loader\/mtl.hpp>\n\n#define UKACHULLDCS_USE_TRACE\n#undef UKACHULLDCS_USE_TRACE\n#include <support\/trace.hpp>\n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n\n \/\/ variables, internal\n\n std::array<std::string const, 3> const materials = {\n {\n { \"# Wavefront material file\\n\" },\n \n { \"newmtl coating_black\\n\"\n \"Ka 0.150000 0.150000 0.150000\\n\"\n \"Kd 0.082353 0.082353 0.082353\\n\"\n \"Ks 0.016471 0.016471 0.016471\\n\"\n \"illum 2\\n\"\n \"Ns 8\\n\" },\n \n { \"newmtl seats\\n\"\n \"#Ka 0.150000 0.150000 0.150000\\n\"\n \"#Kd 0.480392 0.480392 0.431372\\n\"\n \"#Ks 0.096078 0.096078 0.086274\\n\"\n \"#illum 2\\n\"\n \"#Ns 8\\n\"\n \"Ka 0.150000 0.150000 0.150000\\n\"\n \"Kd 1 1 1\\n\"\n \"Ks 0.226471 0.226471 0.226471\\n\"\n \"illum 2\\n\"\n \"Ns 8\\n\"\n \"map_Kd leather_coarse.png\\n\" },\n }\n };\n \n \/\/ functions, internal\n\n} \/\/ namespace {\n\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(test_scene_loader_mtl_size)\n{\n std::stringstream str;\n\n for (auto m : materials) {\n str << m << '\\n';\n }\n\n \/\/ 'mtl::load' returns list of materials + dflt material\n BOOST_CHECK(materials.size() == scene::file::mtl::load(str).size());\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_loader_mtl_properties)\n{\n std::stringstream str;\n\n for (auto m : materials) {\n str << m << '\\n';\n }\n\n using namespace scene::file;\n\n mtl::list_type const result(mtl::load(str));\n \n BOOST_CHECK(\"coating_black\" == result[1]->name.get());\n BOOST_CHECK(glm::vec3(0.150000, 0.150000, 0.150000) == result[1]->ambient.get());\n BOOST_CHECK(glm::vec3(0.082353, 0.082353, 0.082353) == result[1]->diffuse.get());\n BOOST_CHECK(glm::vec3(0.016471, 0.016471, 0.016471) == result[1]->specular.get());\n BOOST_CHECK(8 == result[1]->shininess.get());\n}\n<commit_msg>update: material tests<commit_after>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2015 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : scene\/test\/loader_mtl.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ includes, system\n\n#include <array> \/\/ std::array<>\n#include <glm\/gtx\/io.hpp> \/\/ glm::io::*\n\n\/\/ includes, project\n\n#include <loader\/mtl.hpp>\n\n#define UKACHULLDCS_USE_TRACE\n#undef UKACHULLDCS_USE_TRACE\n#include <support\/trace.hpp>\n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n\n \/\/ variables, internal\n\n std::array<std::string const, 17> const materials = {\n {\n { \"# Wavefront material file\\n\"\n \"# Material examples from [http:\/\/www.fileformat.info\/format\/material\/]\\n\" },\n \n { \"newmtl 01_neon_green\\n\"\n \"Kd 0.0000 1.0000 0.0000\\n\"\n \"illum 0\\n\" },\n\n { \"newmtl 02_flat_green\\n\"\n \"Ka 0.0000 1.0000 0.0000\\n\"\n \"Kd 0.0000 1.0000 0.0000\\n\"\n \"illum 1\\n\" },\n\n { \"newmtl 03_dissolved_green\\n\"\n \"Ka 0.0000 1.0000 0.0000\\n\"\n \"Kd 0.0000 1.0000 0.0000\\n\"\n \"d 0.8000\\n\"\n \"illum 1\\n\" },\n\n { \"newmtl 04_shiny_green\\n\"\n \"Ka 0.0000 1.0000 0.0000\\n\"\n \"Kd 0.0000 1.0000 0.0000\\n\"\n \"Ks 1.0000 1.0000 1.0000\\n\"\n \"Ns 200.0000\\n\"\n \"illum 1\\n\" },\n\n { \"newmtl 05_green_mirror\\n\"\n \"Ka 0.0000 1.0000 0.0000\\n\"\n \"Kd 0.0000 1.0000 0.0000\\n\"\n \"Ks 0.0000 1.0000 0.0000\\n\"\n \"Ns 200.0000\\n\"\n \"illum 3\\n\" },\n\n { \"newmtl 06_fake_windshield\\n\"\n \"Ka 0.0000 0.0000 0.0000\\n\"\n \"Kd 0.0000 0.0000 0.0000\\n\"\n \"Ks 0.9000 0.9000 0.9000\\n\"\n \"d 0.1000\\n\"\n \"Ns 200\\n\"\n \"illum 4\\n\" },\n \n { \"newmtl 07_fresnel_blue\\n\"\n \"Ka 0.0000 0.0000 0.0000\\n\"\n \"Kd 0.0000 0.0000 0.0000\\n\"\n \"Ks 0.6180 0.8760 0.1430\\n\"\n \"Ns 200\\n\"\n \"illum 5\\n\" },\n\n { \"newmtl 08_real_windshield\\n\"\n \"Ka 0.0000 0.0000 0.0000\\n\"\n \"Kd 0.0000 0.0000 0.0000\\n\"\n \"Ks 0.0000 0.0000 0.0000\\n\"\n \"Tf 1.0000 1.0000 1.0000\\n\"\n \"Ns 200\\n\"\n \"Ni 1.2000\\n\"\n \"illum 6\\n\" },\n\n { \"newmtl 09_fresnel_windshield\\n\"\n \"Ka 0.0000 0.0000 1.0000\\n\"\n \"Kd 0.0000 0.0000 1.0000\\n\"\n \"Ks 0.6180 0.8760 0.1430\\n\"\n \"Tf 1.0000 1.0000 1.0000\\n\"\n \"Ns 200\\n\"\n \"Ni 1.2000\\n\"\n \"illum 7\\n\" },\n\n { \"newmtl 10_tin\\n\"\n \"Ka spectral tin.rfl\\n\"\n \"Kd spectral tin.rfl\\n\"\n \"Ks spectral tin.rfl\\n\"\n \"Ns 200\\n\"\n \"illum 3\\n\" },\n\n { \"newmtl 11_pine_wood\\n\"\n \"Ka spectral ident.rfl 1\\n\"\n \"Kd spectral ident.rfl 1\\n\"\n \"illum 1\\n\"\n \"map_Ka pine.mpc\\n\"\n \"map_Kd pine.mpc\\n\" },\n \n { \"newmtl 12_bumpy_leather\\n\"\n \"Ka spectral ident.rfl 1\\n\"\n \"Kd spectral ident.rfl 1\\n\"\n \"Ks spectral ident.rfl 1\\n\"\n \"illum 2\\n\"\n \"map_Ka brown.mpc\\n\"\n \"map_Kd brown.mpc\\n\"\n \"map_Ks brown.mpc\\n\"\n \"bump -bm 2.000 leath.mpb\\n\" },\n\n { \"newmtl 13_frosted_window\\n\"\n \"Ka 0.2 0.2 0.2\\n\"\n \"Kd 0.6 0.6 0.6\\n\"\n \"Ks 0.1 0.1 0.1\\n\"\n \"d 1\\n\"\n \"Ns 200\\n\"\n \"illum 2\\n\"\n \"map_d -mm 0.200 0.800 window.mps\\n\" },\n\n { \"newmtl 14_shifted_logo\\n\"\n \"Ka spectral ident.rfl 1\\n\"\n \"Kd spectral ident.rfl 1\\n\"\n \"Ks spectral ident.rfl 1\\n\"\n \"illum 2\\n\"\n \"map_Ka -o 0.200 0.000 0.000 logo.mpc\\n\"\n \"map_Kd -o 0.200 0.000 0.000 logo.mpc\\n\"\n \"map_Ks -o 0.200 0.000 0.000 logo.mpc\\n\" },\n\n { \"newmtl 15_scaled_logo\\n\"\n \"Ka spectral ident.rfl 1\\n\"\n \"Kd spectral ident.rfl 1\\n\"\n \"Ks spectral ident.rfl 1\\n\"\n \"illum 2\\n\"\n \"map_Ka -s 1.200 1.200 0.000 logo.mpc\\n\"\n \"map_Kd -s 1.200 1.200 0.000 logo.mpc\\n\"\n \"map_Ks -s 1.200 1.200 0.000 logo.mpc\\n\" },\n\n { \"newmtl 16_chrome_with_spherical_reflection_map\\n\"\n \"Ka 0 0 0\\n\"\n \"Kd 0 0 0\\n\"\n \"Ks .7 .7 .7\\n\"\n \"illum 1\\n\"\n \"refl -type sphere chrome.rla\\n\" },\n }\n };\n \n \/\/ functions, internal\n\n} \/\/ namespace {\n\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(test_scene_loader_mtl_size)\n{\n std::stringstream str;\n\n for (auto m : materials) {\n str << m << '\\n';\n }\n\n \/\/ 'mtl::load' returns list of materials + dflt material\n BOOST_CHECK(materials.size() == scene::file::mtl::load(str).size());\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_loader_mtl_properties)\n{\n std::stringstream str;\n\n for (auto m : materials) {\n str << m << '\\n';\n }\n\n using namespace scene::file;\n\n mtl::list_type const result(mtl::load(str));\n \n BOOST_CHECK(\"01_neon_green\" == result[1]->name.get());\n BOOST_CHECK(glm::vec3(0.0, 1.0, 0.0) == result[1]->diffuse.get());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"coordsys.h\"\n#include <pybind11\/pybind11.h>\n#include <pybind11\/numpy.h>\n#include <tuple>\n\nPYBIND11_MAKE_OPAQUE(std::vector<batoid::Vec3>);\nPYBIND11_MAKE_OPAQUE(std::vector<batoid::Ray>);\n\nnamespace py = pybind11;\n\nnamespace batoid {\n void pyExportCoordSys(py::module& m) {\n py::class_<CoordSys, std::shared_ptr<CoordSys>>(m, \"CoordSys\")\n .def(py::init<>())\n .def(py::init<Vec3,Rot3>())\n .def_readonly(\"origin\", &CoordSys::origin, \"Global origin\")\n .def_readonly(\"rotation\", &CoordSys::rotation, \"Unit vector rotation matrix\")\n .def_property_readonly(\"x\", &CoordSys::getX)\n .def_property_readonly(\"y\", &CoordSys::getY)\n .def_property_readonly(\"z\", &CoordSys::getZ)\n .def(\"__repr__\", &CoordSys::repr)\n .def(\"shiftGlobal\", &CoordSys::shiftGlobal)\n .def(\"shiftLocal\", &CoordSys::shiftLocal)\n .def(\"rotateGlobal\", (CoordSys (CoordSys::*) (const Rot3&) const) &CoordSys::rotateGlobal)\n .def(\"rotateGlobal\", (CoordSys (CoordSys::*) (const Rot3&, const Vec3&, std::shared_ptr<CoordSys>) const) &CoordSys::rotateGlobal)\n .def(\"rotateLocal\", (CoordSys (CoordSys::*) (const Rot3&) const) &CoordSys::rotateLocal)\n .def(\"rotateLocal\", (CoordSys (CoordSys::*) (const Rot3&, const Vec3&, std::shared_ptr<CoordSys>) const) &CoordSys::rotateLocal);\n }\n\n std::tuple<py::array_t<double>, py::array_t<double>, py::array_t<double>>\n numpyApplyForward(const CoordTransform& ct,\n py::array_t<double> xs,\n py::array_t<double> ys,\n py::array_t<double> zs) {\n auto bufX = xs.request();\n auto bufY = ys.request();\n auto bufZ = zs.request();\n if (bufX.ndim != bufY.ndim || bufX.ndim != bufZ.ndim)\n throw std::runtime_error(\"Dimensions must match\");\n if (bufX.size != bufY.size || bufX.size != bufZ.size)\n throw std::runtime_error(\"Sizes much match\");\n auto resultX = py::array_t<double>(bufX.shape, bufX.strides);\n auto resultY = py::array_t<double>(bufY.shape, bufY.strides);\n auto resultZ = py::array_t<double>(bufZ.shape, bufZ.strides);\n auto bufXOut = resultX.request();\n auto bufYOut = resultY.request();\n auto bufZOut = resultZ.request();\n\n double *ptrX = (double *) bufX.ptr;\n double *ptrY = (double *) bufY.ptr;\n double *ptrZ = (double *) bufZ.ptr;\n double *ptrXOut = (double *) bufXOut.ptr;\n double *ptrYOut = (double *) bufYOut.ptr;\n double *ptrZOut = (double *) bufZOut.ptr;\n\n auto v = Vec3();\n for (size_t idx = 0; idx < bufX.size; idx++) {\n v = ct.applyForward(Vec3(ptrX[idx], ptrY[idx], ptrZ[idx]));\n ptrXOut[idx] = v.x;\n ptrYOut[idx] = v.y;\n ptrZOut[idx] = v.z;\n }\n return std::make_tuple(resultX, resultY, resultZ);\n }\n\n void pyExportCoordTransform(py::module& m) {\n py::class_<CoordTransform, std::shared_ptr<CoordTransform>>(m, \"CoordTransform\")\n .def(py::init<std::shared_ptr<CoordSys>,std::shared_ptr<CoordSys>>())\n .def(\"applyForward\", (Vec3 (CoordTransform::*)(const Vec3&) const) &CoordTransform::applyForward)\n .def(\"applyReverse\", (Vec3 (CoordTransform::*)(const Vec3&) const) &CoordTransform::applyReverse)\n .def(\"applyForward\", [](const CoordTransform& ct, py::array_t<double> xs, py::array_t<double> ys, py::array_t<double> zs){\n return numpyApplyForward(ct, xs, ys, zs);\n })\n .def(\"applyForward\", (Ray (CoordTransform::*)(const Ray&) const) &CoordTransform::applyForward)\n .def(\"applyReverse\", (Ray (CoordTransform::*)(const Ray&) const) &CoordTransform::applyReverse)\n .def(\"applyForward\", (std::vector<Ray> (CoordTransform::*)(const std::vector<Ray>&) const) &CoordTransform::applyForward)\n .def(\"applyReverse\", (std::vector<Ray> (CoordTransform::*)(const std::vector<Ray>&) const) &CoordTransform::applyReverse)\n .def_readonly(\"source\", &CoordTransform::source)\n .def_readonly(\"destination\", &CoordTransform::destination);\n }\n}\n<commit_msg>Use correct size typedef<commit_after>#include \"coordsys.h\"\n#include <pybind11\/pybind11.h>\n#include <pybind11\/numpy.h>\n#include <tuple>\n\nPYBIND11_MAKE_OPAQUE(std::vector<batoid::Vec3>);\nPYBIND11_MAKE_OPAQUE(std::vector<batoid::Ray>);\n\nnamespace py = pybind11;\n\nnamespace batoid {\n void pyExportCoordSys(py::module& m) {\n py::class_<CoordSys, std::shared_ptr<CoordSys>>(m, \"CoordSys\")\n .def(py::init<>())\n .def(py::init<Vec3,Rot3>())\n .def_readonly(\"origin\", &CoordSys::origin, \"Global origin\")\n .def_readonly(\"rotation\", &CoordSys::rotation, \"Unit vector rotation matrix\")\n .def_property_readonly(\"x\", &CoordSys::getX)\n .def_property_readonly(\"y\", &CoordSys::getY)\n .def_property_readonly(\"z\", &CoordSys::getZ)\n .def(\"__repr__\", &CoordSys::repr)\n .def(\"shiftGlobal\", &CoordSys::shiftGlobal)\n .def(\"shiftLocal\", &CoordSys::shiftLocal)\n .def(\"rotateGlobal\", (CoordSys (CoordSys::*) (const Rot3&) const) &CoordSys::rotateGlobal)\n .def(\"rotateGlobal\", (CoordSys (CoordSys::*) (const Rot3&, const Vec3&, std::shared_ptr<CoordSys>) const) &CoordSys::rotateGlobal)\n .def(\"rotateLocal\", (CoordSys (CoordSys::*) (const Rot3&) const) &CoordSys::rotateLocal)\n .def(\"rotateLocal\", (CoordSys (CoordSys::*) (const Rot3&, const Vec3&, std::shared_ptr<CoordSys>) const) &CoordSys::rotateLocal);\n }\n\n std::tuple<py::array_t<double>, py::array_t<double>, py::array_t<double>>\n numpyApplyForward(const CoordTransform& ct,\n py::array_t<double> xs,\n py::array_t<double> ys,\n py::array_t<double> zs) {\n auto bufX = xs.request();\n auto bufY = ys.request();\n auto bufZ = zs.request();\n if (bufX.ndim != bufY.ndim || bufX.ndim != bufZ.ndim)\n throw std::runtime_error(\"Dimensions must match\");\n if (bufX.size != bufY.size || bufX.size != bufZ.size)\n throw std::runtime_error(\"Sizes much match\");\n auto resultX = py::array_t<double>(bufX.shape, bufX.strides);\n auto resultY = py::array_t<double>(bufY.shape, bufY.strides);\n auto resultZ = py::array_t<double>(bufZ.shape, bufZ.strides);\n auto bufXOut = resultX.request();\n auto bufYOut = resultY.request();\n auto bufZOut = resultZ.request();\n\n double *ptrX = (double *) bufX.ptr;\n double *ptrY = (double *) bufY.ptr;\n double *ptrZ = (double *) bufZ.ptr;\n double *ptrXOut = (double *) bufXOut.ptr;\n double *ptrYOut = (double *) bufYOut.ptr;\n double *ptrZOut = (double *) bufZOut.ptr;\n\n auto v = Vec3();\n for (ssize_t idx = 0; idx < bufX.size; idx++) {\n v = ct.applyForward(Vec3(ptrX[idx], ptrY[idx], ptrZ[idx]));\n ptrXOut[idx] = v.x;\n ptrYOut[idx] = v.y;\n ptrZOut[idx] = v.z;\n }\n return std::make_tuple(resultX, resultY, resultZ);\n }\n\n void pyExportCoordTransform(py::module& m) {\n py::class_<CoordTransform, std::shared_ptr<CoordTransform>>(m, \"CoordTransform\")\n .def(py::init<std::shared_ptr<CoordSys>,std::shared_ptr<CoordSys>>())\n .def(\"applyForward\", (Vec3 (CoordTransform::*)(const Vec3&) const) &CoordTransform::applyForward)\n .def(\"applyReverse\", (Vec3 (CoordTransform::*)(const Vec3&) const) &CoordTransform::applyReverse)\n .def(\"applyForward\", [](const CoordTransform& ct, py::array_t<double> xs, py::array_t<double> ys, py::array_t<double> zs){\n return numpyApplyForward(ct, xs, ys, zs);\n })\n .def(\"applyForward\", (Ray (CoordTransform::*)(const Ray&) const) &CoordTransform::applyForward)\n .def(\"applyReverse\", (Ray (CoordTransform::*)(const Ray&) const) &CoordTransform::applyReverse)\n .def(\"applyForward\", (std::vector<Ray> (CoordTransform::*)(const std::vector<Ray>&) const) &CoordTransform::applyForward)\n .def(\"applyReverse\", (std::vector<Ray> (CoordTransform::*)(const std::vector<Ray>&) const) &CoordTransform::applyReverse)\n .def_readonly(\"source\", &CoordTransform::source)\n .def_readonly(\"destination\", &CoordTransform::destination);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Initial version copied from https:\/\/github.com\/JetBrains\/intellij-community\/blob\/master\/native\/fsNotifier\/mac\/fsnotifier.c\n *\/\n\/\/ Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.\n\n\/*\n * Apple specific functions.\n *\/\n#if defined(__APPLE__)\n\n#include \"native.h\"\n#include \"generic.h\"\n#include <CoreServices\/CoreServices.h>\n#include <pthread.h>\n#include <strings.h>\n\nJavaVM* jvm = NULL;\nbool invalidStateDetected = false;\n\ntypedef struct watch_details {\n CFMutableArrayRef rootsToWatch;\n FSEventStreamRef watcherStream;\n pthread_t watcherThread;\n jobject watcherCallback;\n CFRunLoopRef threadLoop;\n} watch_details_t;\n\nstatic void reportEvent(jint type, char *path, watch_details_t *details) {\n \/\/ TODO What does this do?\n size_t len = 0;\n if (path != NULL) {\n len = strlen(path);\n for (char *p = path; *p != '\\0'; p++) {\n if (*p == '\\n') {\n *p = '\\0';\n }\n }\n }\n\n \/\/ TODO Extract this logic to some global function\n JNIEnv* env;\n int getEnvStat = jvm->GetEnv((void **)&env, JNI_VERSION_1_6);\n if (getEnvStat == JNI_EDETACHED) {\n if (jvm->AttachCurrentThread((void **) &env, NULL) != JNI_OK) {\n invalidStateDetected = true;\n return;\n }\n } else if (getEnvStat == JNI_EVERSION) {\n invalidStateDetected = true;\n return;\n }\n\n printf(\"~~~~ Changed: %s %d\\n\", path, type);\n\n jobject watcherCallback = details->watcherCallback;\n jclass callback_class = env->GetObjectClass(watcherCallback);\n jmethodID methodCallback = env->GetMethodID(callback_class, \"pathChanged\", \"(ILjava\/lang\/String;)V\");\n env->CallVoidMethod(watcherCallback, methodCallback, type, env->NewStringUTF(path));\n}\n\nstatic void callback(ConstFSEventStreamRef streamRef,\n void *clientCallBackInfo,\n size_t numEvents,\n void *eventPaths,\n const FSEventStreamEventFlags eventFlags[],\n const FSEventStreamEventId eventIds[]) {\n if (invalidStateDetected) return;\n char **paths = (char**) eventPaths;\n\n watch_details_t *details = (watch_details_t*) clientCallBackInfo;\n\n for (int i = 0; i < numEvents; i++) {\n FSEventStreamEventFlags flags = eventFlags[i];\n printf(\"~~~~ Event flags: 0x%x for %s\\n\", flags, paths[i]);\n jint type;\n if (IS_SET(flags, kFSEventStreamEventFlagMustScanSubDirs)) {\n type = FILE_EVENT_INVALIDATE;\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemRenamed)) {\n if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) {\n type = FILE_EVENT_REMOVED;\n } else {\n type = FILE_EVENT_CREATED;\n }\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemModified)) {\n type = FILE_EVENT_MODIFIED;\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemRemoved)) {\n type = FILE_EVENT_REMOVED;\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) {\n type = FILE_EVENT_CREATED;\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemInodeMetaMod)) {\n \/\/ File locked\n type = FILE_EVENT_MODIFIED;\n } else {\n printf(\"~~~~ Unknown event 0x%x for %s\\n\", flags, paths[i]);\n type = FILE_EVENT_UNKNOWN;\n }\n reportEvent(type, paths[i], details);\n }\n}\n\nstatic void *EventProcessingThread(void *data) {\n watch_details_t *details = (watch_details_t*) data;\n\n printf(\"~~~~ Starting thread\\n\");\n\n CFRunLoopRef threadLoop = CFRunLoopGetCurrent();\n FSEventStreamScheduleWithRunLoop(details->watcherStream, threadLoop, kCFRunLoopDefaultMode);\n FSEventStreamStart(details->watcherStream);\n details->threadLoop = threadLoop;\n \/\/ TODO We should wait for this in the caller thread otherwise stopWatching() might crash\n \/\/ This triggers run loop for this thread, causing it to run until we explicitly stop it.\n CFRunLoopRun();\n\n printf(\"~~~~ Stopping thread\\n\");\n\n return NULL;\n}\n\nvoid freeDetails(JNIEnv *env, watch_details_t *details) {\n CFMutableArrayRef rootsToWatch = details->rootsToWatch;\n FSEventStreamRef watcherStream = details->watcherStream;\n pthread_t watcherThread = details->watcherThread;\n jobject watcherCallback = details->watcherCallback;\n CFRunLoopRef threadLoop = details->threadLoop;\n free(details);\n\n if (threadLoop != NULL) {\n CFRunLoopStop(threadLoop);\n }\n\n if (watcherThread != NULL) {\n pthread_join(watcherThread, NULL);\n }\n\n if (rootsToWatch != NULL) {\n for (int i = 0; i < CFArrayGetCount(rootsToWatch); i++) {\n const void *value = CFArrayGetValueAtIndex(rootsToWatch, i);\n CFRelease(value);\n }\n \/\/ TODO Can we release these earlier?\n CFRelease(rootsToWatch);\n }\n\n if (watcherStream != NULL) {\n FSEventStreamStop(watcherStream);\n FSEventStreamInvalidate(watcherStream);\n FSEventStreamRelease(watcherStream);\n \/\/ TODO: consider using FSEventStreamFlushSync to flush all pending events.\n }\n\n if (watcherCallback != NULL) {\n env->DeleteGlobalRef(watcherCallback);\n }\n}\n\nJNIEXPORT jobject JNICALL\nJava_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, long latencyInMillis, jobject javaCallback, jobject result) {\n\n printf(\"\\n~~~~ Configuring...\\n\");\n\n invalidStateDetected = false;\n CFMutableArrayRef rootsToWatch = CFArrayCreateMutable(NULL, 0, NULL);\n if (rootsToWatch == NULL) {\n mark_failed_with_errno(env, \"Could not allocate array to store roots to watch.\", result);\n return NULL;\n }\n int count = env->GetArrayLength(paths);\n if (count == 0) {\n mark_failed_with_errno(env, \"No paths given to watch.\", result);\n return NULL;\n }\n\n watch_details_t* details = (watch_details_t*) malloc(sizeof(watch_details_t));\n details->rootsToWatch = rootsToWatch;\n for (int i = 0; i < count; i++) {\n jstring path = (jstring) env->GetObjectArrayElement(paths, i);\n char* watchedPath = java_to_char(env, path, result);\n printf(\"~~~~ Watching %s\\n\", watchedPath);\n if (watchedPath == NULL) {\n mark_failed_with_errno(env, \"Could not allocate string to store root to watch.\", result);\n freeDetails(env, details);\n return NULL;\n }\n CFStringRef stringPath = CFStringCreateWithCString(NULL, watchedPath, kCFStringEncodingUTF8);\n free(watchedPath);\n if (stringPath == NULL) {\n mark_failed_with_errno(env, \"Could not create CFStringRef.\", result);\n freeDetails(env, details);\n return NULL;\n }\n CFArrayAppendValue(rootsToWatch, stringPath);\n }\n\n details->watcherCallback = env->NewGlobalRef(javaCallback);\n if (details->watcherCallback == NULL) {\n mark_failed_with_errno(env, \"Could not create global reference for callback.\", result);\n freeDetails(env, details);\n return NULL;\n }\n\n FSEventStreamContext context = {0, (void*) details, NULL, NULL, NULL};\n details->watcherStream = FSEventStreamCreate (\n NULL,\n &callback,\n &context,\n rootsToWatch,\n kFSEventStreamEventIdSinceNow,\n latencyInMillis \/ 1000.0,\n kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents);\n if (details->watcherStream == NULL) {\n mark_failed_with_errno(env, \"Could not create FSEventStreamCreate to track changes.\", result);\n freeDetails(env, details);\n return NULL;\n }\n\n if (pthread_create(&(details->watcherThread), NULL, EventProcessingThread, details) != 0) {\n mark_failed_with_errno(env, \"Could not create file watcher thread.\", result);\n freeDetails(env, details);\n return NULL;\n }\n\n \/\/ TODO Should this be somewhere global?\n int jvmStatus = env->GetJavaVM(&jvm);\n if (jvmStatus < 0) {\n mark_failed_with_errno(env, \"Could not store jvm instance.\", result);\n freeDetails(env, details);\n return NULL;\n }\n\n jclass clsWatcher = env->FindClass(\"net\/rubygrapefruit\/platform\/internal\/jni\/OsxFileEventFunctions$WatcherImpl\");\n jmethodID constructor = env->GetMethodID(clsWatcher, \"<init>\", \"(Ljava\/lang\/Object;)V\");\n return env->NewObject(clsWatcher, constructor, env->NewDirectByteBuffer(details, sizeof(details)));\n}\n\nJNIEXPORT void JNICALL\nJava_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) {\n watch_details_t *details = (watch_details_t*) env->GetDirectBufferAddress(detailsObj);\n\n if (invalidStateDetected) {\n \/\/ report and reset flag, but try to clean up state as much as possible\n mark_failed_with_errno(env, \"Watcher is in invalid state, reported changes may be incorrect.\", result);\n }\n\n freeDetails(env, details);\n}\n\n#endif\n<commit_msg>Attach\/detach JNI to watcher thread only once<commit_after>\/*\n * Initial version copied from https:\/\/github.com\/JetBrains\/intellij-community\/blob\/master\/native\/fsNotifier\/mac\/fsnotifier.c\n *\/\n\/\/ Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.\n\n\/*\n * Apple specific functions.\n *\/\n#if defined(__APPLE__)\n\n#include \"native.h\"\n#include \"generic.h\"\n#include <CoreServices\/CoreServices.h>\n#include <pthread.h>\n#include <strings.h>\n\nJavaVM* jvm = NULL;\nbool invalidStateDetected = false;\n\ntypedef struct watch_details {\n CFMutableArrayRef rootsToWatch;\n FSEventStreamRef watcherStream;\n pthread_t watcherThread;\n JNIEnv *env;\n jobject watcherCallback;\n CFRunLoopRef threadLoop;\n} watch_details_t;\n\nstatic void reportEvent(jint type, char *path, watch_details_t *details) {\n \/\/ TODO What does this do?\n size_t len = 0;\n if (path != NULL) {\n len = strlen(path);\n for (char *p = path; *p != '\\0'; p++) {\n if (*p == '\\n') {\n *p = '\\0';\n }\n }\n }\n\n printf(\"~~~~ Changed: %s %d\\n\", path, type);\n\n JNIEnv *env = details->env;\n jobject watcherCallback = details->watcherCallback;\n jclass callback_class = env->GetObjectClass(watcherCallback);\n jmethodID methodCallback = env->GetMethodID(callback_class, \"pathChanged\", \"(ILjava\/lang\/String;)V\");\n env->CallVoidMethod(watcherCallback, methodCallback, type, env->NewStringUTF(path));\n}\n\nstatic void callback(ConstFSEventStreamRef streamRef,\n void *clientCallBackInfo,\n size_t numEvents,\n void *eventPaths,\n const FSEventStreamEventFlags eventFlags[],\n const FSEventStreamEventId eventIds[]) {\n if (invalidStateDetected) return;\n char **paths = (char**) eventPaths;\n\n watch_details_t *details = (watch_details_t*) clientCallBackInfo;\n\n for (int i = 0; i < numEvents; i++) {\n FSEventStreamEventFlags flags = eventFlags[i];\n printf(\"~~~~ Event flags: 0x%x for %s\\n\", flags, paths[i]);\n jint type;\n if (IS_SET(flags, kFSEventStreamEventFlagMustScanSubDirs)) {\n type = FILE_EVENT_INVALIDATE;\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemRenamed)) {\n if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) {\n type = FILE_EVENT_REMOVED;\n } else {\n type = FILE_EVENT_CREATED;\n }\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemModified)) {\n type = FILE_EVENT_MODIFIED;\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemRemoved)) {\n type = FILE_EVENT_REMOVED;\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) {\n type = FILE_EVENT_CREATED;\n } else if (IS_SET(flags, kFSEventStreamEventFlagItemInodeMetaMod)) {\n \/\/ File locked\n type = FILE_EVENT_MODIFIED;\n } else {\n printf(\"~~~~ Unknown event 0x%x for %s\\n\", flags, paths[i]);\n type = FILE_EVENT_UNKNOWN;\n }\n reportEvent(type, paths[i], details);\n }\n}\n\nstatic void *EventProcessingThread(void *data) {\n watch_details_t *details = (watch_details_t*) data;\n\n printf(\"~~~~ Starting thread\\n\");\n\n \/\/ TODO Extract this logic to some global function\n jint statAttach = jvm->AttachCurrentThreadAsDaemon((void **) &(details->env), NULL);\n if (statAttach != JNI_OK) {\n printf(\"Failed to attach JNI to current thread: %d\\n\", statAttach);\n invalidStateDetected = true;\n return NULL;\n }\n\n CFRunLoopRef threadLoop = CFRunLoopGetCurrent();\n FSEventStreamScheduleWithRunLoop(details->watcherStream, threadLoop, kCFRunLoopDefaultMode);\n FSEventStreamStart(details->watcherStream);\n details->threadLoop = threadLoop;\n \/\/ TODO We should wait for this in the caller thread otherwise stopWatching() might crash\n \/\/ This triggers run loop for this thread, causing it to run until we explicitly stop it.\n CFRunLoopRun();\n\n printf(\"~~~~ Stopping thread\\n\");\n\n jint statDetach = jvm->DetachCurrentThread();\n if (statDetach != JNI_OK) {\n printf(\"Failed to detach JNI from current thread: %d\\n\", statAttach);\n invalidStateDetected = true;\n return NULL;\n }\n\n return NULL;\n}\n\nvoid freeDetails(JNIEnv *env, watch_details_t *details) {\n CFMutableArrayRef rootsToWatch = details->rootsToWatch;\n FSEventStreamRef watcherStream = details->watcherStream;\n pthread_t watcherThread = details->watcherThread;\n jobject watcherCallback = details->watcherCallback;\n CFRunLoopRef threadLoop = details->threadLoop;\n free(details);\n\n if (threadLoop != NULL) {\n CFRunLoopStop(threadLoop);\n }\n\n if (watcherThread != NULL) {\n pthread_join(watcherThread, NULL);\n }\n\n if (rootsToWatch != NULL) {\n for (int i = 0; i < CFArrayGetCount(rootsToWatch); i++) {\n const void *value = CFArrayGetValueAtIndex(rootsToWatch, i);\n CFRelease(value);\n }\n \/\/ TODO Can we release these earlier?\n CFRelease(rootsToWatch);\n }\n\n if (watcherStream != NULL) {\n FSEventStreamStop(watcherStream);\n FSEventStreamInvalidate(watcherStream);\n FSEventStreamRelease(watcherStream);\n \/\/ TODO: consider using FSEventStreamFlushSync to flush all pending events.\n }\n\n if (watcherCallback != NULL) {\n env->DeleteGlobalRef(watcherCallback);\n }\n}\n\nJNIEXPORT jobject JNICALL\nJava_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, long latencyInMillis, jobject javaCallback, jobject result) {\n\n printf(\"\\n~~~~ Configuring...\\n\");\n\n invalidStateDetected = false;\n CFMutableArrayRef rootsToWatch = CFArrayCreateMutable(NULL, 0, NULL);\n if (rootsToWatch == NULL) {\n mark_failed_with_errno(env, \"Could not allocate array to store roots to watch.\", result);\n return NULL;\n }\n int count = env->GetArrayLength(paths);\n if (count == 0) {\n mark_failed_with_errno(env, \"No paths given to watch.\", result);\n return NULL;\n }\n\n watch_details_t* details = (watch_details_t*) malloc(sizeof(watch_details_t));\n details->rootsToWatch = rootsToWatch;\n for (int i = 0; i < count; i++) {\n jstring path = (jstring) env->GetObjectArrayElement(paths, i);\n char* watchedPath = java_to_char(env, path, result);\n printf(\"~~~~ Watching %s\\n\", watchedPath);\n if (watchedPath == NULL) {\n mark_failed_with_errno(env, \"Could not allocate string to store root to watch.\", result);\n freeDetails(env, details);\n return NULL;\n }\n CFStringRef stringPath = CFStringCreateWithCString(NULL, watchedPath, kCFStringEncodingUTF8);\n free(watchedPath);\n if (stringPath == NULL) {\n mark_failed_with_errno(env, \"Could not create CFStringRef.\", result);\n freeDetails(env, details);\n return NULL;\n }\n CFArrayAppendValue(rootsToWatch, stringPath);\n }\n\n details->watcherCallback = env->NewGlobalRef(javaCallback);\n if (details->watcherCallback == NULL) {\n mark_failed_with_errno(env, \"Could not create global reference for callback.\", result);\n freeDetails(env, details);\n return NULL;\n }\n\n FSEventStreamContext context = {0, (void*) details, NULL, NULL, NULL};\n details->watcherStream = FSEventStreamCreate (\n NULL,\n &callback,\n &context,\n rootsToWatch,\n kFSEventStreamEventIdSinceNow,\n latencyInMillis \/ 1000.0,\n kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents);\n if (details->watcherStream == NULL) {\n mark_failed_with_errno(env, \"Could not create FSEventStreamCreate to track changes.\", result);\n freeDetails(env, details);\n return NULL;\n }\n\n if (pthread_create(&(details->watcherThread), NULL, EventProcessingThread, details) != 0) {\n mark_failed_with_errno(env, \"Could not create file watcher thread.\", result);\n freeDetails(env, details);\n return NULL;\n }\n\n \/\/ TODO Should this be somewhere global?\n int jvmStatus = env->GetJavaVM(&jvm);\n if (jvmStatus < 0) {\n mark_failed_with_errno(env, \"Could not store jvm instance.\", result);\n freeDetails(env, details);\n return NULL;\n }\n\n jclass clsWatcher = env->FindClass(\"net\/rubygrapefruit\/platform\/internal\/jni\/OsxFileEventFunctions$WatcherImpl\");\n jmethodID constructor = env->GetMethodID(clsWatcher, \"<init>\", \"(Ljava\/lang\/Object;)V\");\n return env->NewObject(clsWatcher, constructor, env->NewDirectByteBuffer(details, sizeof(details)));\n}\n\nJNIEXPORT void JNICALL\nJava_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) {\n watch_details_t *details = (watch_details_t*) env->GetDirectBufferAddress(detailsObj);\n\n if (invalidStateDetected) {\n \/\/ report and reset flag, but try to clean up state as much as possible\n mark_failed_with_errno(env, \"Watcher is in invalid state, reported changes may be incorrect.\", result);\n }\n\n freeDetails(env, details);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: mkdir -p %t\n\/\/ RUN: %clang_cc1 -x c++ -emit-module -o %t\/left.pcm %s -D MODULE_LEFT\n\/\/ RUN: %clang_cc1 -x c++ -emit-module -o %t\/right.pcm %s -D MODULE_RIGHT\n\/\/ RUN: %clang_cc1 -fmodule-cache-path %t %s -verify\n\n#if defined(MODULE_LEFT)\n\n__module_private__ struct HiddenStruct;\n\nstruct HiddenStruct {\n};\n\n\nint &f0(int);\n\ntemplate<typename T>\n__module_private__ void f1(T*);\n\ntemplate<typename T>\nvoid f1(T*);\n\ntemplate<typename T>\n__module_private__ class vector;\n\ntemplate<typename T>\nclass vector {\n};\n\nvector<float> vec_float;\n\ntypedef __module_private__ int Integer;\ntypedef int Integer;\n\n#elif defined(MODULE_RIGHT)\n__module_private__ double &f0(double);\ndouble &f0(double);\n\n__module_private__ int hidden_var;\n\ninline void test_f0_in_right() {\n double &dr = f0(hidden_var);\n}\n\nstruct VisibleStruct {\n __module_private__ int field;\n __module_private__ void setField(int f);\n};\n\n#else\n__import_module__ left;\n__import_module__ right;\n\nvoid test() {\n int &ir = f0(1.0); \/\/ okay: f0() from 'right' is not visible\n}\n\nint test_broken() {\n HiddenStruct hidden; \/\/ expected-error{{use of undeclared identifier 'HiddenStruct'}}\n\n Integer i; \/\/ expected-error{{use of undeclared identifier 'Integer'}}\n\n int *ip = 0;\n f1(ip); \/\/ expected-error{{use of undeclared identifier 'f1'}}\n\n vector<int> vec; \/\/ expected-error{{use of undeclared identifier 'vector'}} \\\n \/\/ expected-error{{expected '(' for function-style cast or type construction}} \\\n \/\/ expected-error{{use of undeclared identifier 'vec'}}\n\n VisibleStruct vs;\n vs.field = 0; \/\/ expected-error{{no member named 'field' in 'VisibleStruct'}}\n vs.setField(1); \/\/ expected-error{{no member named 'setField' in 'VisibleStruct'}}\n\n return hidden_var; \/\/ expected-error{{use of undeclared identifier 'hidden_var'}}\n}\n\n\/\/ Check for private redeclarations of public entities.\ntemplate<typename T>\nclass public_class_template; \/\/ expected-note{{previous declaration is here}}\n\ntemplate<typename T>\n__module_private__ class public_class_template; \/\/ expected-error{{__module_private__ declaration of 'public_class_template' follows public declaration}}\n\n\ntypedef int public_typedef; \/\/ expected-note{{previous declaration is here}}\ntypedef __module_private__ int public_typedef; \/\/ expected-error{{__module_private__ declaration of 'public_typedef' follows public declaration}}\n\nextern int public_var; \/\/ expected-note{{previous declaration is here}}\nextern __module_private__ int public_var; \/\/ expected-error{{__module_private__ declaration of 'public_var' follows public declaration}}\n\nvoid public_func(); \/\/ expected-note{{previous declaration is here}}\n__module_private__ void public_func(); \/\/ expected-error{{__module_private__ declaration of 'public_func' follows public declaration}}\n\ntemplate<typename T>\nvoid public_func_template(); \/\/ expected-note{{previous declaration is here}}\ntemplate<typename T>\n__module_private__ void public_func_template(); \/\/ expected-error{{__module_private__ declaration of 'public_func_template' follows public declaration}}\n\nstruct public_struct; \/\/ expected-note{{previous declaration is here}}\n__module_private__ struct public_struct; \/\/ expected-error{{__module_private__ declaration of 'public_struct' follows public declaration}}\n\n\/\/ Check for attempts to make specializations private\ntemplate<> __module_private__ void public_func_template<int>(); \/\/ expected-error{{template specialization cannot be declared __module_private__}}\n\ntemplate<typename T>\nstruct public_class {\n struct inner_struct;\n static int static_var;\n\n friend __module_private__ void public_func_friend();\n friend __module_private__ struct public_struct_friend;\n};\n\ntemplate<> __module_private__ struct public_class<int>::inner_struct { }; \/\/ expected-error{{member specialization cannot be declared __module_private__}}\ntemplate<> __module_private__ int public_class<int>::static_var = 17; \/\/ expected-error{{member specialization cannot be declared __module_private__}}\n\ntemplate<>\n__module_private__ struct public_class<float> { }; \/\/ expected-error{{template specialization cannot be declared __module_private__}}\n\ntemplate<typename T>\n__module_private__ struct public_class<T *> { }; \/\/ expected-error{{partial specialization cannot be declared __module_private__}}\n\n\/\/ Check for attempts to make parameters and variables with automatic\n\/\/ storage module-private.\n\nvoid local_var_private(__module_private__ int param) { \/\/ expected-error{{parameter 'param' cannot be declared __module_private__}}\n __module_private__ struct Local { int x, y; } local; \/\/expected-error{{local variable 'local' cannot be declared __module_private__}}\n\n __module_private__ struct OtherLocal { int x; }; \/\/ expected-error{{local struct cannot be declared __module_private__}}\n\n typedef __module_private__ int local_typedef; \/\/ expected-error{{typedef 'local_typedef' cannot be declared __module_private__}}\n}\n#endif\n<commit_msg>Add a struct-size check for modules when dealing with module-private fields<commit_after>\/\/ RUN: mkdir -p %t\n\/\/ RUN: %clang_cc1 -x c++ -emit-module -o %t\/left.pcm %s -D MODULE_LEFT\n\/\/ RUN: %clang_cc1 -x c++ -emit-module -o %t\/right.pcm %s -D MODULE_RIGHT\n\/\/ RUN: %clang_cc1 -fmodule-cache-path %t %s -verify\n\n#if defined(MODULE_LEFT)\n\n__module_private__ struct HiddenStruct;\n\nstruct HiddenStruct {\n};\n\n\nint &f0(int);\n\ntemplate<typename T>\n__module_private__ void f1(T*);\n\ntemplate<typename T>\nvoid f1(T*);\n\ntemplate<typename T>\n__module_private__ class vector;\n\ntemplate<typename T>\nclass vector {\n};\n\nvector<float> vec_float;\n\ntypedef __module_private__ int Integer;\ntypedef int Integer;\n\n#elif defined(MODULE_RIGHT)\n__module_private__ double &f0(double);\ndouble &f0(double);\n\n__module_private__ int hidden_var;\n\ninline void test_f0_in_right() {\n double &dr = f0(hidden_var);\n}\n\nstruct VisibleStruct {\n __module_private__ int field;\n __module_private__ virtual void setField(int f);\n};\n\n#else\n__import_module__ left;\n__import_module__ right;\n\nvoid test() {\n int &ir = f0(1.0); \/\/ okay: f0() from 'right' is not visible\n}\n\nint test_broken() {\n HiddenStruct hidden; \/\/ expected-error{{use of undeclared identifier 'HiddenStruct'}}\n\n Integer i; \/\/ expected-error{{use of undeclared identifier 'Integer'}}\n\n int *ip = 0;\n f1(ip); \/\/ expected-error{{use of undeclared identifier 'f1'}}\n\n vector<int> vec; \/\/ expected-error{{use of undeclared identifier 'vector'}} \\\n \/\/ expected-error{{expected '(' for function-style cast or type construction}} \\\n \/\/ expected-error{{use of undeclared identifier 'vec'}}\n\n VisibleStruct vs;\n vs.field = 0; \/\/ expected-error{{no member named 'field' in 'VisibleStruct'}}\n vs.setField(1); \/\/ expected-error{{no member named 'setField' in 'VisibleStruct'}}\n\n return hidden_var; \/\/ expected-error{{use of undeclared identifier 'hidden_var'}}\n}\n\n\/\/ Check for private redeclarations of public entities.\ntemplate<typename T>\nclass public_class_template; \/\/ expected-note{{previous declaration is here}}\n\ntemplate<typename T>\n__module_private__ class public_class_template; \/\/ expected-error{{__module_private__ declaration of 'public_class_template' follows public declaration}}\n\n\ntypedef int public_typedef; \/\/ expected-note{{previous declaration is here}}\ntypedef __module_private__ int public_typedef; \/\/ expected-error{{__module_private__ declaration of 'public_typedef' follows public declaration}}\n\nextern int public_var; \/\/ expected-note{{previous declaration is here}}\nextern __module_private__ int public_var; \/\/ expected-error{{__module_private__ declaration of 'public_var' follows public declaration}}\n\nvoid public_func(); \/\/ expected-note{{previous declaration is here}}\n__module_private__ void public_func(); \/\/ expected-error{{__module_private__ declaration of 'public_func' follows public declaration}}\n\ntemplate<typename T>\nvoid public_func_template(); \/\/ expected-note{{previous declaration is here}}\ntemplate<typename T>\n__module_private__ void public_func_template(); \/\/ expected-error{{__module_private__ declaration of 'public_func_template' follows public declaration}}\n\nstruct public_struct; \/\/ expected-note{{previous declaration is here}}\n__module_private__ struct public_struct; \/\/ expected-error{{__module_private__ declaration of 'public_struct' follows public declaration}}\n\n\/\/ Check for attempts to make specializations private\ntemplate<> __module_private__ void public_func_template<int>(); \/\/ expected-error{{template specialization cannot be declared __module_private__}}\n\ntemplate<typename T>\nstruct public_class {\n struct inner_struct;\n static int static_var;\n\n friend __module_private__ void public_func_friend();\n friend __module_private__ struct public_struct_friend;\n};\n\ntemplate<> __module_private__ struct public_class<int>::inner_struct { }; \/\/ expected-error{{member specialization cannot be declared __module_private__}}\ntemplate<> __module_private__ int public_class<int>::static_var = 17; \/\/ expected-error{{member specialization cannot be declared __module_private__}}\n\ntemplate<>\n__module_private__ struct public_class<float> { }; \/\/ expected-error{{template specialization cannot be declared __module_private__}}\n\ntemplate<typename T>\n__module_private__ struct public_class<T *> { }; \/\/ expected-error{{partial specialization cannot be declared __module_private__}}\n\n\/\/ Check for attempts to make parameters and variables with automatic\n\/\/ storage module-private.\n\nvoid local_var_private(__module_private__ int param) { \/\/ expected-error{{parameter 'param' cannot be declared __module_private__}}\n __module_private__ struct Local { int x, y; } local; \/\/expected-error{{local variable 'local' cannot be declared __module_private__}}\n\n __module_private__ struct OtherLocal { int x; }; \/\/ expected-error{{local struct cannot be declared __module_private__}}\n\n typedef __module_private__ int local_typedef; \/\/ expected-error{{typedef 'local_typedef' cannot be declared __module_private__}}\n}\n\n\/\/ Check struct size\nstruct LikeVisibleStruct {\n int field;\n virtual void setField(int f);\n};\n\nint check_struct_size[sizeof(VisibleStruct) == sizeof(LikeVisibleStruct)? 1 : -1];\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The Loki Library\n\/\/ Copyright (c) 2005 Peter Kmmel\n\/\/ Permission to use, copy, modify, distribute and sell this software for any \n\/\/ purpose is hereby granted without fee, provided that the above copyright \n\/\/ notice appear in all copies and that both that copyright notice and this \n\/\/ permission notice appear in supporting documentation.\n\/\/ The authors make no representations about the \n\/\/ suitability of this software for any purpose. It is provided \"as is\" \n\/\/ without express or implied warranty.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <iostream>\n\n#include \"loki\/SmallObj.h\"\n#include \"loki\/Function.h\"\n\n\nusing namespace Loki;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Data object for all singletons\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<template <class> class T, int Nr>\nstruct SingletonDataObject\n{\n SingletonDataObject() {std::cout<<\"new SingletonDataObject\"<<Nr<<\"\\n\\n\";}\n ~SingletonDataObject(){std::cout<<\"delete SingletonDataObject\"<<Nr<<\"\\n\\n\";}\n \n int i[Nr];\n};\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ How to use LongevityLifetime policies \n\/\/ DieAsSmallObjectParent\/DieAsSmallObjectChild with SmallObjects?\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LongevityLifetime::DieAsSmallObjectParent is the default \n\/\/ lifetime of SmallObject template:\ntypedef Loki::SmallObject<> \nSmallObject_DieAs;\n\nclass MySmallObject_DieAs : public SmallObject_DieAs\n{};\n\ntypedef SingletonHolder\n<\n MySmallObject_DieAs, \n CreateUsingNew, \n LongevityLifetime::DieAsSmallObjectChild\n>\nSingleton_with_MySmallObject_DieAs;\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ How to use LongevityLifetime policies \n\/\/ DieAsSmallObjectParent\/DieAsSmallObjectChild with \n\/\/ classes containing a Functor\/Function?\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nstruct MyFunctionObject_DieAs\n{\n MyFunctionObject_DieAs()\n {\n functor = Functor<void> (this, &MyFunctionObject_DieAs::f);\n function = Function< void()>(this, &MyFunctionObject_DieAs::f);\n }\n\n void f(){}\n Functor<void> functor;\n Function<void()> function;\n \n};\n\ntypedef SingletonHolder\n<\n MyFunctionObject_DieAs, \n CreateUsingNew, \n LongevityLifetime::DieAsSmallObjectChild\n>\nSingleton_MyFunctionObject_DieAs;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Test code for LongevityLifetime Policy\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<template <class> class Lifetime>\nstruct Master_die_first\n{\n Master_die_first() \n {\n data = &Singleton::Instance();\n }\n\n virtual ~Master_die_first(){}\n\n typedef Master_die_first<Lifetime> ThisType;\n typedef SingletonDataObject<Lifetime,888> MasterSingleton;\n typedef SingletonHolder<MasterSingleton,CreateUsingNew,Lifetime> Singleton;\n\n MasterSingleton* data;\n};\n\ntemplate<template <class> class Lifetime>\nstruct Master_die_last\n{\n Master_die_last() \n {\n data = &Singleton::Instance();\n }\n\n virtual ~Master_die_last(){}\n\n typedef Master_die_last<Lifetime> ThisType;\n typedef SingletonDataObject<Lifetime,555> MasterSingleton;\n typedef SingletonHolder<MasterSingleton,CreateUsingNew,Lifetime> Singleton;\n\n MasterSingleton* data;\n};\n\ntypedef Master_die_first<LongevityLifetime::DieFirst>\nMaster1_die_first;\n\ntypedef Master_die_last<LongevityLifetime::DieLast>\nMaster1_die_last;\n\nclass B1_die_first;\nclass B1_die_last;\n\ntypedef SingletonHolder<B1_die_first,CreateUsingNew, \nLongevityLifetime::DieFirst\n> Follower1_Singleton_B1_die_first;\n\ntypedef SingletonHolder<B1_die_last,CreateUsingNew, \nLongevityLifetime::DieLast\n> Follower1_Singleton_B1_die_last;\n\nclass B1_die_first : public Master1_die_last\n{\npublic:\n B1_die_first(){std::cout<<\"new B1_die_first, look for SingletonDataObject555\\n\\n\";}\n ~B1_die_first(){std::cout<<\"delete B1_die_first, look for SingletonDataObject555\\n\\n\";}\n};\n\nclass B1_die_last : public Master1_die_first\n{\npublic:\n B1_die_last(){std::cout<<\"new B1_die_last, look for SingletonDataObject888\\n\\n\";}\n ~B1_die_last(){std::cout<<\"delete B1_die_last, look for SingletonDataObject888\\n\\n\";}\n};\n\n\n#if !defined(_MSC_VER) || (_MSC_VER>=1400)\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ How to use FollowIntoDeath with SmallObjects?\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef Loki::SmallObject\n< \n LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,\n LOKI_DEFAULT_CHUNK_SIZE, \n LOKI_MAX_SMALL_OBJECT_SIZE,\n LOKI_DEFAULT_OBJECT_ALIGNMENT, \n FollowIntoDeath::With<DefaultLifetime>::AsMasterLifetime\n>\nMySmallObjectBase;\n\nstruct MySmallObject : public MySmallObjectBase\n{\n};\n\ntypedef SingletonHolder\n<\n MySmallObject, \n CreateUsingNew, \n FollowIntoDeath::AfterMaster<MySmallObjectBase::ObjAllocatorSingleton>::IsDestroyed\n>\nSingleton_of_with_a_MySmallObject;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ How to use FollowIntoDeath with classes containing a Functor\/Function?\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct MyFunctionObject \n{\n MyFunctionObject()\n {\n functor = Functor<void> (this, &MyFunctionObject::f);\n function = Function< void()>(this, &MyFunctionObject::f);\n }\n\n void f(){}\n Functor<void> functor;\n Function<void()> function;\n \n};\n\ntypedef SingletonHolder\n<\n MyFunctionObject, \n CreateUsingNew, \n FollowIntoDeath::AfterMaster<Function<>::Impl::ObjAllocatorSingleton>::IsDestroyed\n>\nSingleton_MyFunctionObject1;\n\ntypedef SingletonHolder\n<\n MyFunctionObject, \n CreateUsingNew, \n FollowIntoDeath::AfterMaster<Functor<>::Impl::ObjAllocatorSingleton>::IsDestroyed\n>\nSingleton_MyFunctionObject2;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Test code for FollowIntoDeath policy\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ntemplate<template <class> class Lifetime>\nstruct Master1\n{\n Master1() \n {\n data = &Singleton::Instance();\n }\n\n virtual ~Master1(){}\n\n typedef Master1<Lifetime> ThisType;\n typedef SingletonDataObject<Lifetime,1> MasterSingleton;\n typedef SingletonHolder<MasterSingleton,CreateUsingNew,Lifetime> Singleton;\n\n MasterSingleton* data;\n};\n\ntypedef Master1<FollowIntoDeath::With<DefaultLifetime>::AsMasterLifetime>\nMaster1_DefaultLifetime;\n\ntypedef Master1<FollowIntoDeath::With<NoDestroy>::AsMasterLifetime>\nMaster1_NoDestroy;\n\ntypedef Master1<FollowIntoDeath::With<PhoenixSingleton>::AsMasterLifetime>\nMaster1_PhoenixSingleton;\n\ntypedef Master1<FollowIntoDeath::With<DeletableSingleton>::AsMasterLifetime>\nMaster1_DeletableSingleton;\n\n\nclass B1_DefaultLifetime : public Master1_DefaultLifetime\n{\npublic:\n B1_DefaultLifetime(){std::cout<<\"new B1_DefaultLifetime\\n\";}\n ~B1_DefaultLifetime(){std::cout<<\"delete B1_DefaultLifetime\\n\";}\n};\n\nclass B1_NoDestroy : public Master1_NoDestroy\n{\npublic:\n B1_NoDestroy(){std::cout<<\"new B1_NoDestroy. B1_NoDestroy must not be deleted\\n\";}\n ~B1_NoDestroy(){std::cout<<\"delete B1_NoDestroy\\n\";};\n};\n\nclass B1_PhoenixSingleton : public Master1_PhoenixSingleton\n{\npublic:\n B1_PhoenixSingleton(){std::cout<<\"new B1_PhoenixSingleton\\n\";}\n ~B1_PhoenixSingleton(){std::cout<<\"delete B1_PhoenixSingleton\\n\";}\n};\n\nclass B1_DeletableSingleton : public Master1_DeletableSingleton\n{\npublic:\n B1_DeletableSingleton(){std::cout<<\"new B1_DeletableSingleton\\n\";}\n ~B1_DeletableSingleton(){std::cout<<\"delete B1_DeletableSingleton\\n\";}\n};\n\ntypedef SingletonHolder<B1_DefaultLifetime,CreateUsingNew, \nFollowIntoDeath::AfterMaster<Master1_DefaultLifetime::MasterSingleton>::IsDestroyed\n> Follower1_Singleton_DefaultLifetime;\n\ntypedef SingletonHolder<B1_NoDestroy,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master1_NoDestroy::MasterSingleton>::IsDestroyed\n> Follower1_Singleton_NoDestroy;\n\ntypedef SingletonHolder<B1_PhoenixSingleton,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master1_PhoenixSingleton::MasterSingleton>::IsDestroyed\n> Follower1_Singleton_PhoenixSingleton;\n\ntypedef SingletonHolder<B1_DeletableSingleton,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master1_DeletableSingleton::MasterSingleton>::IsDestroyed\n> Follower1_Singleton_DeletableSingleton;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Test code for FollowIntoDeath policy with reverse instantiation\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<template <class> class Lifetime>\nstruct Master2\n{\n Master2() \n {\n \/\/ don't create a MasterSingleton2 object!!\n \/\/ to test the FollowIntoDeath policy\n }\n\n virtual ~Master2(){}\n\n typedef Master2<Lifetime> ThisType;\n typedef SingletonDataObject<Lifetime,2> MasterSingleton;\n typedef SingletonHolder<MasterSingleton,CreateUsingNew,Lifetime> Singleton;\n\n MasterSingleton* data;\n};\n\ntypedef Master2<FollowIntoDeath::With<DefaultLifetime>::AsMasterLifetime>\nMaster2_DefaultLifetime;\n\ntypedef Master2<FollowIntoDeath::With<NoDestroy>::AsMasterLifetime>\nMaster2_NoDestroy;\n\ntypedef Master2<FollowIntoDeath::With<PhoenixSingleton>::AsMasterLifetime>\nMaster2_PhoenixSingleton;\n\ntypedef Master2<FollowIntoDeath::With<DeletableSingleton>::AsMasterLifetime>\nMaster2_DeletableSingleton;\n\n\n\nclass B2_DefaultLifetime : public Master2_DefaultLifetime\n{\npublic:\n B2_DefaultLifetime(){std::cout<<\"new B2_DefaultLifetime\\n\";}\n ~B2_DefaultLifetime(){std::cout<<\"delete B2_DefaultLifetime\\n\";}\n};\n\nclass B2_NoDestroy : public Master2_NoDestroy\n{\npublic:\n B2_NoDestroy(){std::cout<<\"new B2_NoDestroy. B2_NoDestroy must not be deleted\\n\";}\n ~B2_NoDestroy(){std::cout<<\"delete B2_NoDestroy\\n\";};\n};\n\nclass B2_PhoenixSingleton : public Master2_PhoenixSingleton\n{\npublic:\n B2_PhoenixSingleton(){std::cout<<\"new B2_PhoenixSingleton\\n\";}\n ~B2_PhoenixSingleton(){std::cout<<\"delete B2_PhoenixSingleton\\n\";}\n};\n\nclass B2_DeletableSingleton : public Master2_DeletableSingleton\n{\npublic:\n B2_DeletableSingleton(){std::cout<<\"new B2_DeletableSingleton\\n\";}\n ~B2_DeletableSingleton(){std::cout<<\"delete B2_DeletableSingleton\\n\";}\n};\n\ntypedef SingletonHolder<B2_DefaultLifetime,CreateUsingNew, \nFollowIntoDeath::AfterMaster<Master2_DefaultLifetime::MasterSingleton>::IsDestroyed\n> Follower2_Singleton_DefaultLifetime;\n\ntypedef SingletonHolder<B2_NoDestroy,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master2_NoDestroy::MasterSingleton>::IsDestroyed\n> Follower2_Singleton_NoDestroy;\n\ntypedef SingletonHolder<B2_PhoenixSingleton,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master2_PhoenixSingleton::MasterSingleton>::IsDestroyed\n> Follower2_Singleton_PhoenixSingleton;\n\ntypedef SingletonHolder<B2_DeletableSingleton,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master2_DeletableSingleton::MasterSingleton>::IsDestroyed\n> Follower2_Singleton_DeletableSingleton;\n\n#endif \/\/#if !defined(_MSC_VER) || (_MSC_VER>=1400)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ detect memory leaks on MSVC Ide\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef _MSC_VER\n\n#include <crtdbg.h>\n#include <cassert>\n\nvoid heap_debug()\n{\n int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );\n\n \/\/ Turn on leak-checking bit\n tmpFlag |= _CRTDBG_LEAK_CHECK_DF;\n\n \/\/tmpFlag |= _CRTDBG_CHECK_MasterLWMasterYS_DF;\n\n \/\/ Turn off CRT block checking bit\n tmpFlag &= ~_CRTDBG_CHECK_CRT_DF;\n\n \/\/ Set flag to the new value\n _CrtSetDbgFlag( tmpFlag );\n\n}\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ main\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main(int argc, char *argv[])\n{\n \n#ifdef _MSC_VER\n heap_debug();\n#endif\n\n\n MySmallObject_DieAs *s_DieAs = &Singleton_with_MySmallObject_DieAs::Instance();\n MyFunctionObject_DieAs *f_DieAs = &Singleton_MyFunctionObject_DieAs::Instance();\n\n std::cout<<\"\\n\";\n\n B1_die_first *first= &Follower1_Singleton_B1_die_first::Instance();\n B1_die_last *last = &Follower1_Singleton_B1_die_last::Instance();\n\n\n \/\/ test of FollowIntoDeath policy, not supported by msvc 7.1 compiler\n#if !defined(_MSC_VER) || (_MSC_VER>=1400)\n\n MyFunctionObject *f1 = &Singleton_MyFunctionObject1::Instance();\n MyFunctionObject *f2 = &Singleton_MyFunctionObject2::Instance();\n\n std::cout << \"\\nMaster1:\\n\\n\";\n\n B1_DefaultLifetime *def = &Follower1_Singleton_DefaultLifetime::Instance();\n B1_PhoenixSingleton *pho = &Follower1_Singleton_PhoenixSingleton::Instance();\n B1_DeletableSingleton *del = &Follower1_Singleton_DeletableSingleton::Instance();\n \n\n std::cout << \"\\n\\nMaster2:\\n\\n\";\n\n B2_DefaultLifetime *def2 = &Follower2_Singleton_DefaultLifetime::Instance();\n def2->data = &Master2_DefaultLifetime::Singleton::Instance();\n\n B2_PhoenixSingleton *pho2 = &Follower2_Singleton_PhoenixSingleton::Instance();\n pho2->data = &Master2_PhoenixSingleton::Singleton::Instance();\n\n B2_DeletableSingleton *del2 = &Follower2_Singleton_DeletableSingleton::Instance();\n del2->data = &Master2_DeletableSingleton::Singleton::Instance();\n \n \/\/ memory leak when code is enabled\n \/\/#define ENMasterBLE_LEMasterK\n#ifdef ENMasterBLE_LEMasterK\n B1_NoDestroy *no = &Follower1_Singleton_NoDestroy::Instance();\n B2_NoDestroy *no2 = &Follower2_Singleton_NoDestro0::Instance();\n no2->data = &Master2_NoDestroy::Singleton::Instance();\n#endif\n\n#endif \/\/#if !defined(_MSC_VER) || (_MSC_VER>=1400)\n\n#if defined(__BORLANDC__) || defined(__GNUC__) || defined(_MSC_VER)\n system(\"pause\"); \/\/ Stop console window from closing if run from IDE.\n#endif\n\n std::cout << \"\\nnow leaving main \\n\";\n std::cout << \"________________________________\\n\\n\";\n\n return 0;\n}\n<commit_msg>remove warnings and adjust code to new default lifetimes of SmallObjects<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The Loki Library\n\/\/ Copyright (c) 2005 Peter Kmmel\n\/\/ Permission to use, copy, modify, distribute and sell this software for any \n\/\/ purpose is hereby granted without fee, provided that the above copyright \n\/\/ notice appear in all copies and that both that copyright notice and this \n\/\/ permission notice appear in supporting documentation.\n\/\/ The authors make no representations about the \n\/\/ suitability of this software for any purpose. It is provided \"as is\" \n\/\/ without express or implied warranty.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include <iostream>\n\n#include \"loki\/SmallObj.h\"\n#include \"loki\/Function.h\"\n\n\nusing namespace Loki;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Data object for all singletons\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<template <class> class T, int Nr>\nstruct SingletonDataObject\n{\n SingletonDataObject() {std::cout<<\"new SingletonDataObject\"<<Nr<<\"\\n\\n\";}\n ~SingletonDataObject(){std::cout<<\"delete SingletonDataObject\"<<Nr<<\"\\n\\n\";}\n \n int i[Nr];\n};\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ How to use LongevityLifetime policies \n\/\/ DieAsSmallObjectParent\/DieAsSmallObjectChild with SmallObjects?\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LongevityLifetime::DieAsSmallObjectParent is the default lifetime \n\/\/ of SmallObject template:\ntypedef Loki::SmallObject<> \nSmallObject_DieAs;\n\nclass MySmallObject_DieAs : public SmallObject_DieAs\n{};\n\ntypedef SingletonHolder\n<\n MySmallObject_DieAs, \n CreateUsingNew, \n LongevityLifetime::DieAsSmallObjectChild\n>\nSingleton_with_MySmallObject_DieAs;\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ How to use LongevityLifetime policies \n\/\/ DieAsSmallObjectParent\/DieAsSmallObjectChild with \n\/\/ classes containing a Functor\/Function?\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nstruct MyFunctionObject_DieAs\n{\n MyFunctionObject_DieAs()\n {\n functor = Functor<void> (this, &MyFunctionObject_DieAs::f);\n function = Function< void()>(this, &MyFunctionObject_DieAs::f);\n }\n\n void f(){}\n Functor<void> functor;\n Function<void()> function;\n \n};\n\ntypedef SingletonHolder\n<\n MyFunctionObject_DieAs, \n CreateUsingNew, \n LongevityLifetime::DieAsSmallObjectChild\n>\nSingleton_MyFunctionObject_DieAs;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Test code for LongevityLifetime Policy\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<template <class> class Lifetime>\nstruct Master_die_first\n{\n Master_die_first() \n {\n data = &Singleton::Instance();\n }\n\n virtual ~Master_die_first(){}\n\n typedef Master_die_first<Lifetime> ThisType;\n typedef SingletonDataObject<Lifetime,888> MasterSingleton;\n typedef SingletonHolder<MasterSingleton,CreateUsingNew,Lifetime> Singleton;\n\n MasterSingleton* data;\n};\n\ntemplate<template <class> class Lifetime>\nstruct Master_die_last\n{\n Master_die_last() \n {\n data = &Singleton::Instance();\n }\n\n virtual ~Master_die_last(){}\n\n typedef Master_die_last<Lifetime> ThisType;\n typedef SingletonDataObject<Lifetime,555> MasterSingleton;\n typedef SingletonHolder<MasterSingleton,CreateUsingNew,Lifetime> Singleton;\n\n MasterSingleton* data;\n};\n\ntypedef Master_die_first<LongevityLifetime::DieFirst>\nMaster1_die_first;\n\ntypedef Master_die_last<LongevityLifetime::DieLast>\nMaster1_die_last;\n\nclass B1_die_first;\nclass B1_die_last;\n\ntypedef SingletonHolder<B1_die_first,CreateUsingNew, \nLongevityLifetime::DieFirst\n> Follower1_Singleton_B1_die_first;\n\ntypedef SingletonHolder<B1_die_last,CreateUsingNew, \nLongevityLifetime::DieLast\n> Follower1_Singleton_B1_die_last;\n\nclass B1_die_first : public Master1_die_last\n{\npublic:\n B1_die_first(){std::cout<<\"new B1_die_first, look for SingletonDataObject555\\n\\n\";}\n ~B1_die_first(){std::cout<<\"delete B1_die_first, look for SingletonDataObject555\\n\\n\";}\n};\n\nclass B1_die_last : public Master1_die_first\n{\npublic:\n B1_die_last(){std::cout<<\"new B1_die_last, look for SingletonDataObject888\\n\\n\";}\n ~B1_die_last(){std::cout<<\"delete B1_die_last, look for SingletonDataObject888\\n\\n\";}\n};\n\n\/\/ test of FollowIntoDeath policy, not supported by msvc 7.1 compiler\n#if !defined(_MSC_VER) || (_MSC_VER>=1400)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ How to use FollowIntoDeath with SmallObjects?\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef Loki::SmallObject\n< \n LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,\n LOKI_DEFAULT_CHUNK_SIZE, \n LOKI_MAX_SMALL_OBJECT_SIZE,\n LOKI_DEFAULT_OBJECT_ALIGNMENT, \n FollowIntoDeath::With<DefaultLifetime>::AsMasterLifetime\n>\nMySmallObjectBase;\n\nstruct MySmallObject : public MySmallObjectBase\n{\n};\n\ntypedef SingletonHolder\n<\n MySmallObject, \n CreateUsingNew, \n FollowIntoDeath::AfterMaster<MySmallObjectBase::ObjAllocatorSingleton>::IsDestroyed\n>\nSingleton_of_with_a_MySmallObject;\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Test code for FollowIntoDeath policy\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ntemplate<template <class> class Lifetime>\nstruct Master1\n{\n Master1() \n {\n data = &Singleton::Instance();\n }\n\n virtual ~Master1(){}\n\n typedef Master1<Lifetime> ThisType;\n typedef SingletonDataObject<Lifetime,1> MasterSingleton;\n typedef SingletonHolder<MasterSingleton,CreateUsingNew,Lifetime> Singleton;\n\n MasterSingleton* data;\n};\n\ntypedef Master1<FollowIntoDeath::With<DefaultLifetime>::AsMasterLifetime>\nMaster1_DefaultLifetime;\n\ntypedef Master1<FollowIntoDeath::With<NoDestroy>::AsMasterLifetime>\nMaster1_NoDestroy;\n\ntypedef Master1<FollowIntoDeath::With<PhoenixSingleton>::AsMasterLifetime>\nMaster1_PhoenixSingleton;\n\ntypedef Master1<FollowIntoDeath::With<DeletableSingleton>::AsMasterLifetime>\nMaster1_DeletableSingleton;\n\n\nclass B1_DefaultLifetime : public Master1_DefaultLifetime\n{\npublic:\n B1_DefaultLifetime(){std::cout<<\"new B1_DefaultLifetime\\n\";}\n ~B1_DefaultLifetime(){std::cout<<\"delete B1_DefaultLifetime\\n\";}\n};\n\nclass B1_NoDestroy : public Master1_NoDestroy\n{\npublic:\n B1_NoDestroy(){std::cout<<\"new B1_NoDestroy. B1_NoDestroy must not be deleted\\n\";}\n ~B1_NoDestroy(){std::cout<<\"delete B1_NoDestroy\\n\";};\n};\n\nclass B1_PhoenixSingleton : public Master1_PhoenixSingleton\n{\npublic:\n B1_PhoenixSingleton(){std::cout<<\"new B1_PhoenixSingleton\\n\";}\n ~B1_PhoenixSingleton(){std::cout<<\"delete B1_PhoenixSingleton\\n\";}\n};\n\nclass B1_DeletableSingleton : public Master1_DeletableSingleton\n{\npublic:\n B1_DeletableSingleton(){std::cout<<\"new B1_DeletableSingleton\\n\";}\n ~B1_DeletableSingleton(){std::cout<<\"delete B1_DeletableSingleton\\n\";}\n};\n\ntypedef SingletonHolder<B1_DefaultLifetime,CreateUsingNew, \nFollowIntoDeath::AfterMaster<Master1_DefaultLifetime::MasterSingleton>::IsDestroyed\n> Follower1_Singleton_DefaultLifetime;\n\ntypedef SingletonHolder<B1_NoDestroy,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master1_NoDestroy::MasterSingleton>::IsDestroyed\n> Follower1_Singleton_NoDestroy;\n\ntypedef SingletonHolder<B1_PhoenixSingleton,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master1_PhoenixSingleton::MasterSingleton>::IsDestroyed\n> Follower1_Singleton_PhoenixSingleton;\n\ntypedef SingletonHolder<B1_DeletableSingleton,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master1_DeletableSingleton::MasterSingleton>::IsDestroyed\n> Follower1_Singleton_DeletableSingleton;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Test code for FollowIntoDeath policy with reverse instantiation\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate<template <class> class Lifetime>\nstruct Master2\n{\n Master2() \n {\n \/\/ don't create a MasterSingleton2 object!!\n \/\/ to test the FollowIntoDeath policy\n }\n\n virtual ~Master2(){}\n\n typedef Master2<Lifetime> ThisType;\n typedef SingletonDataObject<Lifetime,2> MasterSingleton;\n typedef SingletonHolder<MasterSingleton,CreateUsingNew,Lifetime> Singleton;\n\n MasterSingleton* data;\n};\n\ntypedef Master2<FollowIntoDeath::With<DefaultLifetime>::AsMasterLifetime>\nMaster2_DefaultLifetime;\n\ntypedef Master2<FollowIntoDeath::With<NoDestroy>::AsMasterLifetime>\nMaster2_NoDestroy;\n\ntypedef Master2<FollowIntoDeath::With<PhoenixSingleton>::AsMasterLifetime>\nMaster2_PhoenixSingleton;\n\ntypedef Master2<FollowIntoDeath::With<DeletableSingleton>::AsMasterLifetime>\nMaster2_DeletableSingleton;\n\n\n\nclass B2_DefaultLifetime : public Master2_DefaultLifetime\n{\npublic:\n B2_DefaultLifetime(){std::cout<<\"new B2_DefaultLifetime\\n\";}\n ~B2_DefaultLifetime(){std::cout<<\"delete B2_DefaultLifetime\\n\";}\n};\n\nclass B2_NoDestroy : public Master2_NoDestroy\n{\npublic:\n B2_NoDestroy(){std::cout<<\"new B2_NoDestroy. B2_NoDestroy must not be deleted\\n\";}\n ~B2_NoDestroy(){std::cout<<\"delete B2_NoDestroy\\n\";};\n};\n\nclass B2_PhoenixSingleton : public Master2_PhoenixSingleton\n{\npublic:\n B2_PhoenixSingleton(){std::cout<<\"new B2_PhoenixSingleton\\n\";}\n ~B2_PhoenixSingleton(){std::cout<<\"delete B2_PhoenixSingleton\\n\";}\n};\n\nclass B2_DeletableSingleton : public Master2_DeletableSingleton\n{\npublic:\n B2_DeletableSingleton(){std::cout<<\"new B2_DeletableSingleton\\n\";}\n ~B2_DeletableSingleton(){std::cout<<\"delete B2_DeletableSingleton\\n\";}\n};\n\ntypedef SingletonHolder<B2_DefaultLifetime,CreateUsingNew, \nFollowIntoDeath::AfterMaster<Master2_DefaultLifetime::MasterSingleton>::IsDestroyed\n> Follower2_Singleton_DefaultLifetime;\n\ntypedef SingletonHolder<B2_NoDestroy,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master2_NoDestroy::MasterSingleton>::IsDestroyed\n> Follower2_Singleton_NoDestroy;\n\ntypedef SingletonHolder<B2_PhoenixSingleton,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master2_PhoenixSingleton::MasterSingleton>::IsDestroyed\n> Follower2_Singleton_PhoenixSingleton;\n\ntypedef SingletonHolder<B2_DeletableSingleton,CreateUsingNew, \n FollowIntoDeath::AfterMaster<Master2_DeletableSingleton::MasterSingleton>::IsDestroyed\n> Follower2_Singleton_DeletableSingleton;\n\n#endif \/\/#if !defined(_MSC_VER) || (_MSC_VER>=1400)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ detect memory leaks on MSVC Ide\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef _MSC_VER\n\n#include <crtdbg.h>\n#include <cassert>\n\nvoid heap_debug()\n{\n int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );\n\n \/\/ Turn on leak-checking bit\n tmpFlag |= _CRTDBG_LEAK_CHECK_DF;\n\n \/\/tmpFlag |= _CRTDBG_CHECK_MasterLWMasterYS_DF;\n\n \/\/ Turn off CRT block checking bit\n tmpFlag &= ~_CRTDBG_CHECK_CRT_DF;\n\n \/\/ Set flag to the new value\n _CrtSetDbgFlag( tmpFlag );\n\n}\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ main\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main()\n{\n \n#ifdef _MSC_VER\n heap_debug();\n#endif\n\n void* p;\n\n p = (void*) &Singleton_with_MySmallObject_DieAs::Instance();\n p = (void*) &Singleton_MyFunctionObject_DieAs::Instance();\n\n std::cout<<\"\\n\";\n\n p = (void*) &Follower1_Singleton_B1_die_first::Instance();\n p = (void*) &Follower1_Singleton_B1_die_last::Instance();\n\n\n \/\/ test of FollowIntoDeath policy, not supported by msvc 7.1 compiler\n#if !defined(_MSC_VER) || (_MSC_VER>=1400)\n\n std::cout << \"\\nMaster1:\\n\\n\";\n\n p = (void*) &Follower1_Singleton_DefaultLifetime::Instance();\n p = (void*) &Follower1_Singleton_PhoenixSingleton::Instance();\n p = (void*) &Follower1_Singleton_DeletableSingleton::Instance();\n \n\n std::cout << \"\\n\\nMaster2:\\n\\n\";\n\n B2_DefaultLifetime *def2 = &Follower2_Singleton_DefaultLifetime::Instance();\n def2->data = &Master2_DefaultLifetime::Singleton::Instance();\n\n B2_PhoenixSingleton *pho2 = &Follower2_Singleton_PhoenixSingleton::Instance();\n pho2->data = &Master2_PhoenixSingleton::Singleton::Instance();\n\n B2_DeletableSingleton *del2 = &Follower2_Singleton_DeletableSingleton::Instance();\n del2->data = &Master2_DeletableSingleton::Singleton::Instance();\n \n \/\/ memory leak when code is enabled\n\/\/#define ENABLE_MEMORY_LEAK\n#ifdef ENABLE_MEMORY_LEAK\n p = (void*) &Follower1_Singleton_NoDestroy::Instance();\n B2_NoDestroy *no2 = &Follower2_Singleton_NoDestroy::Instance();\n no2->data = &Master2_NoDestroy::Singleton::Instance();\n#endif\n\n#endif \/\/#if !defined(_MSC_VER) || (_MSC_VER>=1400)\n\n#if defined(__BORLANDC__) || defined(__GNUC__) || defined(_MSC_VER)\n system(\"pause\");\n#endif\n\n std::cout << \"\\nnow leaving main \\n\";\n std::cout << \"________________________________\\n\\n\";\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/#define LOKI_CLASS_LEVEL_THREADING\n\/\/#define LOKI_OBJECT_LEVEL_THREADING\n\n#include \"SmallObj.h\"\n#include \"timer.h\"\n\n#include <string>\n\nusing namespace std;\n\t\n\t\n\t\t\nclass ThisIsASmallObject\n{\n\tint i;\n\tdouble d;\n\t\/\/std::string s;\n};\t\n\ntemplate<class T>\t\t\nstruct Base : public ThisIsASmallObject, public T {};\ntemplate<>\t\t\nstruct Base<void> : public ThisIsASmallObject {};\n\ntypedef Base<void> \nA;\ntypedef Base<Loki::SmallObject<> > \nB;\ntypedef Base<Loki::SmallValueObject<> > \nC;\n\n\n\/*\nclass A \n{ int i; int* p;};\nclass B : public Loki::SmallObject<>\n{ int i; int* p;};\nclass C : public Loki::SmallValueObject<> \n{ int i; int* p;};\n*\/\n\n\ntemplate<class T>\nint run_new_delete(int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\n\t{\t\t\n\t\tT* p = new T;\n\t\tdelete p;\n\t}\n\t\/****************************************************************\/\t \n\tt.stop();\n\tt.print(t.t(),s);\n\treturn t.t();\n}\n\ntemplate<class T>\nint run_new_delete(T** array, int N, int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\n\t\tfor (int n=0; n<N; n++)\n\t\t{\t\n\t\t\tarray[n] = new T;\n\t\t\tdelete array[n];\n\t\t}\n\t\/****************************************************************\/\t \n\tt.stop();\t\n\tt.print(t.t(),s);\n\treturn t.t();\n}\n\ntemplate<class T>\nint run_new(T** array, int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\t\n\t\tarray[i] = new T;\n\t\/****************************************************************\/\t \n\tt.stop();\t\n\tt.print(t.t(),s);\n\treturn t.t();\n}\ntemplate<class T>\nint run_delete(T** array, int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\t\n\t\tdelete array[i];\n\t\/****************************************************************\/\t \n\tt.stop();\t\n\tt.print(t.t(),s);\n\treturn t.t();\n}\n\n\ntemplate<class T>\nint run_new_delete_array(int N, int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\n\t{\t\t\n\t\tT* p = new T[N];\n\t\tdelete [] p;\n\t}\n\t\/****************************************************************\/\t \n\tt.stop();\n\tt.print(t.t(),s);\n\treturn t.t();\n}\n\n\nint main()\n{\t\n\tint loop = 1000000\n\t;\n\t\n\tTimer t;\n\n\tt.t100 = 0;\n\tt.t100 = run_new_delete<A>(loop,t,\"new & delete A : \");\n\trun_new_delete<B>(loop,t,\"new & delete B : \");\n\trun_new_delete<C>(loop,t,\"new & delete C : \");\n\t\n\tcout << endl << endl;\n\/\/ Loki::AllocatorSingleton<>::ClearExtraMemory();\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\tint N = 100000;\n\tint loop2 = loop\/N*10;\n\t\n\tA** a = new A*[N];\n\tB** b = new B*[N];\n\tC** c = new C*[N];\n\t\n\tfor(int i=0; i<N; i++)\n\t{\n\t\ta[i]=0;\n\t\tb[i]=0;\n\t\tc[i]=0;\n\t}\n\t\n\tt.t100 = 0;\n\tt.t100 = run_new_delete(a,N,loop2,t,\"new & delete A on array : \");\n\trun_new_delete(b,N,loop2,t,\"new & delete B on array : \");\n\trun_new_delete(c,N,loop2,t,\"new & delete C on array : \");\n\n\tcout << endl << endl;\n\/\/ Loki::AllocatorSingleton<>::ClearExtraMemory();\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\tt.t100 = 0;\n\tt.t100 = run_new(a,N,t,\"new A on array : \");\n\trun_new(b,N,t,\"new B on array : \");\n\trun_new(c,N,t,\"new C on array : \");\n\n\tcout << endl;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tt.t100 = 0;\n\tt.t100 = run_delete(a,N,t,\"delete A on array : \");\n\trun_delete(b,N,t,\"delete B on array : \");\n\trun_delete(c,N,t,\"delete C on array : \");\n\n\n\tdelete [] a;\n\tdelete [] b;\n\tdelete [] c;\n\t\n\tcout << endl << endl;\n\/\/ Loki::AllocatorSingleton<>::ClearExtraMemory();\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\tN = 5;\n\t\n\tt.t100 = 0;\n\tt.t100 = run_new_delete_array<A>(N,loop,t,\"new & delete [] A : \");\n\trun_new_delete_array<B>(N,loop,t,\"new & delete [] B : \");\n\trun_new_delete_array<C>(N,loop,t,\"new & delete [] C : \");\n\t\n\tcout << endl << endl;\n Loki::AllocatorSingleton<>::ClearExtraMemory();\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\tcout << endl;\n\tsystem(\"PAUSE\");\n\treturn 0;\n}\n\n<commit_msg>Added comments saying how to test array forms of new and delete.<commit_after>\n\/\/#define LOKI_CLASS_LEVEL_THREADING\n\/\/#define LOKI_OBJECT_LEVEL_THREADING\n\n\/\/ Uncomment this to test new [] and delete [].\n\/\/ #define LOKI_SMALL_OBJECT_USE_NEW_ARRAY\n\n#include \"SmallObj.h\"\n#include \"timer.h\"\n\n#include <string>\n\nusing namespace std;\n\t\n\t\n\t\t\nclass ThisIsASmallObject\n{\n\tint i;\n\tdouble d;\n\t\/\/std::string s;\n};\t\n\ntemplate<class T>\t\t\nstruct Base : public ThisIsASmallObject, public T {};\ntemplate<>\t\t\nstruct Base<void> : public ThisIsASmallObject {};\n\ntypedef Base<void> \nA;\ntypedef Base<Loki::SmallObject<> > \nB;\ntypedef Base<Loki::SmallValueObject<> > \nC;\n\n\n\/*\nclass A \n{ int i; int* p;};\nclass B : public Loki::SmallObject<>\n{ int i; int* p;};\nclass C : public Loki::SmallValueObject<> \n{ int i; int* p;};\n*\/\n\n\ntemplate<class T>\nint run_new_delete(int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\n\t{\t\t\n\t\tT* p = new T;\n\t\tdelete p;\n\t}\n\t\/****************************************************************\/\t \n\tt.stop();\n\tt.print(t.t(),s);\n\treturn t.t();\n}\n\ntemplate<class T>\nint run_new_delete(T** array, int N, int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\n\t\tfor (int n=0; n<N; n++)\n\t\t{\t\n\t\t\tarray[n] = new T;\n\t\t\tdelete array[n];\n\t\t}\n\t\/****************************************************************\/\t \n\tt.stop();\t\n\tt.print(t.t(),s);\n\treturn t.t();\n}\n\ntemplate<class T>\nint run_new(T** array, int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\t\n\t\tarray[i] = new T;\n\t\/****************************************************************\/\t \n\tt.stop();\t\n\tt.print(t.t(),s);\n\treturn t.t();\n}\ntemplate<class T>\nint run_delete(T** array, int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\t\n\t\tdelete array[i];\n\t\/****************************************************************\/\t \n\tt.stop();\t\n\tt.print(t.t(),s);\n\treturn t.t();\n}\n\n\ntemplate<class T>\nint run_new_delete_array(int N, int loop, Timer& t, char* s)\n{\n\tt.start();\n\t\/****************************************************************\/\t \n\tfor (int i=0; i<loop; ++i)\n\t{\t\t\n\t\tT* p = new T[N];\n\t\tdelete [] p;\n\t}\n\t\/****************************************************************\/\t \n\tt.stop();\n\tt.print(t.t(),s);\n\treturn t.t();\n}\n\n\nint main()\n{\t\n\tint loop = 1000000\n\t;\n\t\n\tTimer t;\n\n\tt.t100 = 0;\n\tt.t100 = run_new_delete<A>(loop,t,\"new & delete A : \");\n\trun_new_delete<B>(loop,t,\"new & delete B : \");\n\trun_new_delete<C>(loop,t,\"new & delete C : \");\n\t\n\tcout << endl << endl;\n\/\/ Loki::AllocatorSingleton<>::ClearExtraMemory();\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\tint N = 100000;\n\tint loop2 = loop\/N*10;\n\t\n\tA** a = new A*[N];\n\tB** b = new B*[N];\n\tC** c = new C*[N];\n\t\n\tfor(int i=0; i<N; i++)\n\t{\n\t\ta[i]=0;\n\t\tb[i]=0;\n\t\tc[i]=0;\n\t}\n\t\n\tt.t100 = 0;\n\tt.t100 = run_new_delete(a,N,loop2,t,\"new & delete A on array : \");\n\trun_new_delete(b,N,loop2,t,\"new & delete B on array : \");\n\trun_new_delete(c,N,loop2,t,\"new & delete C on array : \");\n\n\tcout << endl << endl;\n\/\/ Loki::AllocatorSingleton<>::ClearExtraMemory();\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\tt.t100 = 0;\n\tt.t100 = run_new(a,N,t,\"new A on array : \");\n\trun_new(b,N,t,\"new B on array : \");\n\trun_new(c,N,t,\"new C on array : \");\n\n\tcout << endl;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tt.t100 = 0;\n\tt.t100 = run_delete(a,N,t,\"delete A on array : \");\n\trun_delete(b,N,t,\"delete B on array : \");\n\trun_delete(c,N,t,\"delete C on array : \");\n\n\n\tdelete [] a;\n\tdelete [] b;\n\tdelete [] c;\n\t\n\tcout << endl << endl;\n\/\/ Loki::AllocatorSingleton<>::ClearExtraMemory();\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\tN = 5;\n\t\n\tt.t100 = 0;\n\tt.t100 = run_new_delete_array<A>(N,loop,t,\"new & delete [] A : \");\n\trun_new_delete_array<B>(N,loop,t,\"new & delete [] B : \");\n\trun_new_delete_array<C>(N,loop,t,\"new & delete [] C : \");\n\t\n\tcout << endl << endl;\n Loki::AllocatorSingleton<>::ClearExtraMemory();\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\tcout << endl;\n\tsystem(\"PAUSE\");\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n *\n * @brief Adapter implementation that wraps a single std::string value\n *\n * This allows property names to be validated against a schema as though they are a generic JSON\n * value, while allowing the rest of Valijson's API to expose property names as plain std::string\n * values.\n *\n * This was added while implementing draft 7 support. This included support for a constraint\n * called propertyNames, which can be used to ensure that the property names in an object\n * validate against a subschema.\n *\/\n\n#pragma once\n\n#include <string>\n\n#include <valijson\/adapters\/adapter.hpp>\n#include <valijson\/adapters\/frozen_value.hpp>\n\nnamespace valijson {\nnamespace adapters {\n\nclass StdStringAdapter;\nclass StdStringArrayValueIterator;\nclass StdStringObjectMemberIterator;\n\ntypedef std::pair<std::string, StdStringAdapter> StdStringObjectMember;\n\nclass StdStringArray\n{\npublic:\n typedef StdStringArrayValueIterator const_iterator;\n typedef StdStringArrayValueIterator iterator;\n\n StdStringArray() { }\n\n StdStringArrayValueIterator begin() const;\n\n StdStringArrayValueIterator end() const;\n\n size_t size() const\n {\n return 0;\n }\n};\n\nclass StdStringObject\n{\npublic:\n typedef StdStringObjectMemberIterator const_iterator;\n typedef StdStringObjectMemberIterator iterator;\n\n StdStringObject() { }\n\n StdStringObjectMemberIterator begin() const;\n\n StdStringObjectMemberIterator end() const;\n\n StdStringObjectMemberIterator find(const std::string &propertyName) const;\n\n size_t size() const\n {\n return 0;\n }\n};\n\nclass StdStringFrozenValue: public FrozenValue\n{\npublic:\n explicit StdStringFrozenValue(const std::string &source)\n : value(source) { }\n\n virtual FrozenValue * clone() const\n {\n return new StdStringFrozenValue(value);\n }\n\n virtual bool equalTo(const Adapter &other, bool strict) const;\n\nprivate:\n std::string value;\n};\n\nclass StdStringAdapter: public Adapter\n{\npublic:\n typedef StdStringArray Array;\n typedef StdStringObject Object;\n typedef StdStringObjectMember ObjectMember;\n\n StdStringAdapter(const std::string &value)\n : value(value) { }\n\n virtual bool applyToArray(ArrayValueCallback fn) const\n {\n return maybeArray();\n }\n\n virtual bool applyToObject(ObjectMemberCallback fn) const\n {\n return maybeObject();\n }\n\n StdStringArray asArray() const\n {\n if (maybeArray()) {\n return StdStringArray();\n }\n\n throw std::runtime_error(\"String value cannot be cast to array\");\n }\n\n virtual bool asBool() const\n {\n return true;\n }\n\n virtual bool asBool(bool &result) const\n {\n result = true;\n return true;\n }\n\n virtual double asDouble() const\n {\n return 0;\n }\n\n virtual bool asDouble(double &result) const\n {\n result = 0;\n return true;\n }\n\n virtual int64_t asInteger() const\n {\n return 0;\n }\n\n virtual bool asInteger(int64_t &result) const\n {\n result = 0;\n return true;\n };\n\n StdStringObject asObject() const\n {\n if (maybeObject()) {\n return StdStringObject();\n }\n\n throw std::runtime_error(\"String value cannot be cast to object\");\n }\n\n virtual std::string asString() const\n {\n return value;\n }\n\n virtual bool asString(std::string &result) const\n {\n result = value;\n return true;\n }\n\n virtual bool equalTo(const Adapter &other, bool strict) const\n {\n if (strict && !other.isString()) {\n return false;\n }\n\n return value.compare(other.asString()) == 0;\n }\n\n virtual FrozenValue* freeze() const\n {\n return new StdStringFrozenValue(value);\n }\n\n StdStringArray getArray() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual size_t getArraySize() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getArraySize(size_t &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getBool() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getBool(bool &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual double getDouble() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getDouble(double &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual int64_t getInteger() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getInteger(int64_t &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual double getNumber() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getNumber(double &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual size_t getObjectSize() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getObjectSize(size_t &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual std::string getString() const\n {\n return value;\n }\n\n virtual bool getString(std::string &result) const\n {\n result = value;\n return true;\n }\n\n virtual bool hasStrictTypes() const\n {\n return true;\n }\n\n virtual bool isArray() const\n {\n return false;\n }\n\n virtual bool isBool() const\n {\n return false;\n }\n\n virtual bool isDouble() const\n {\n return false;\n }\n\n virtual bool isInteger() const\n {\n return false;\n }\n\n virtual bool isNull() const\n {\n return false;\n }\n\n virtual bool isNumber() const\n {\n return false;\n }\n\n virtual bool isObject() const\n {\n return false;\n }\n\n virtual bool isString() const\n {\n return true;\n }\n\n virtual bool maybeArray() const\n {\n return false;\n }\n\n virtual bool maybeBool() const\n {\n return value.compare(\"true\") == 0 || value.compare(\"false\") == 0;\n }\n\n virtual bool maybeDouble() const\n {\n const char *b = value.c_str();\n char *e = NULL;\n strtod(b, &e);\n return e != b && e == b + value.length();\n }\n\n virtual bool maybeInteger() const\n {\n std::istringstream i(value);\n int64_t x;\n char c;\n if (!(i >> x) || i.get(c)) {\n return false;\n }\n\n return true;\n }\n\n virtual bool maybeNull() const\n {\n return value.size() == 0;\n }\n\n virtual bool maybeObject() const\n {\n return value.size() == 0;\n }\n\n virtual bool maybeString() const\n {\n return true;\n }\n\nprivate:\n const std::string &value;\n};\n\nclass StdStringArrayValueIterator:\n public std::iterator<\n std::bidirectional_iterator_tag,\n StdStringAdapter>\n{\npublic:\n StdStringAdapter operator*() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n DerefProxy<StdStringAdapter> operator->() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n bool operator==(const StdStringArrayValueIterator &other) const\n {\n return true;\n }\n\n bool operator!=(const StdStringArrayValueIterator &other) const\n {\n return false;\n }\n\n const StdStringArrayValueIterator& operator++()\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n StdStringArrayValueIterator operator++(int)\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n const StdStringArrayValueIterator& operator--()\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n void advance(std::ptrdiff_t n)\n {\n throw std::runtime_error(\"Not supported\");\n }\n};\n\ninline StdStringArrayValueIterator StdStringArray::begin() const\n{\n return StdStringArrayValueIterator();\n}\n\ninline StdStringArrayValueIterator StdStringArray::end() const\n{\n return StdStringArrayValueIterator();\n}\n\nclass StdStringObjectMemberIterator:\n public std::iterator<\n std::bidirectional_iterator_tag,\n StdStringObjectMember>\n{\npublic:\n StdStringObjectMember operator*() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n DerefProxy<StdStringObjectMember> operator->() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n bool operator==(const StdStringObjectMemberIterator &) const\n {\n return true;\n }\n\n bool operator!=(const StdStringObjectMemberIterator &) const\n {\n return false;\n }\n\n const StdStringObjectMemberIterator& operator++()\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n StdStringObjectMemberIterator operator++(int)\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n const StdStringObjectMemberIterator& operator--()\n {\n throw std::runtime_error(\"Not supported\");\n }\n};\n\ninline StdStringObjectMemberIterator StdStringObject::begin() const\n{\n return StdStringObjectMemberIterator();\n}\n\ninline StdStringObjectMemberIterator StdStringObject::end() const\n{\n return StdStringObjectMemberIterator();\n}\n\ninline StdStringObjectMemberIterator StdStringObject::find(const std::string &propertyName) const\n{\n return StdStringObjectMemberIterator();\n}\n\ntemplate<>\nstruct AdapterTraits<valijson::adapters::StdStringAdapter>\n{\n typedef std::string DocumentType;\n\n static std::string adapterName()\n {\n return \"StdStringAdapter\";\n }\n};\n\ninline bool StdStringFrozenValue::equalTo(const Adapter &other, bool strict) const\n{\n return StdStringAdapter(value).equalTo(other, strict);\n}\n\n} \/\/ namespace adapters\n} \/\/ namespace valijson\n<commit_msg>Add missing include for DerefProxy<commit_after>\/**\n * @file\n *\n * @brief Adapter implementation that wraps a single std::string value\n *\n * This allows property names to be validated against a schema as though they are a generic JSON\n * value, while allowing the rest of Valijson's API to expose property names as plain std::string\n * values.\n *\n * This was added while implementing draft 7 support. This included support for a constraint\n * called propertyNames, which can be used to ensure that the property names in an object\n * validate against a subschema.\n *\/\n\n#pragma once\n\n#include <string>\n\n#include <valijson\/adapters\/adapter.hpp>\n#include <valijson\/adapters\/frozen_value.hpp>\n#include <valijson\/adapters\/basic_adapter.hpp>\n\nnamespace valijson {\nnamespace adapters {\n\nclass StdStringAdapter;\nclass StdStringArrayValueIterator;\nclass StdStringObjectMemberIterator;\n\ntypedef std::pair<std::string, StdStringAdapter> StdStringObjectMember;\n\nclass StdStringArray\n{\npublic:\n typedef StdStringArrayValueIterator const_iterator;\n typedef StdStringArrayValueIterator iterator;\n\n StdStringArray() { }\n\n StdStringArrayValueIterator begin() const;\n\n StdStringArrayValueIterator end() const;\n\n size_t size() const\n {\n return 0;\n }\n};\n\nclass StdStringObject\n{\npublic:\n typedef StdStringObjectMemberIterator const_iterator;\n typedef StdStringObjectMemberIterator iterator;\n\n StdStringObject() { }\n\n StdStringObjectMemberIterator begin() const;\n\n StdStringObjectMemberIterator end() const;\n\n StdStringObjectMemberIterator find(const std::string &propertyName) const;\n\n size_t size() const\n {\n return 0;\n }\n};\n\nclass StdStringFrozenValue: public FrozenValue\n{\npublic:\n explicit StdStringFrozenValue(const std::string &source)\n : value(source) { }\n\n virtual FrozenValue * clone() const\n {\n return new StdStringFrozenValue(value);\n }\n\n virtual bool equalTo(const Adapter &other, bool strict) const;\n\nprivate:\n std::string value;\n};\n\nclass StdStringAdapter: public Adapter\n{\npublic:\n typedef StdStringArray Array;\n typedef StdStringObject Object;\n typedef StdStringObjectMember ObjectMember;\n\n StdStringAdapter(const std::string &value)\n : value(value) { }\n\n virtual bool applyToArray(ArrayValueCallback fn) const\n {\n return maybeArray();\n }\n\n virtual bool applyToObject(ObjectMemberCallback fn) const\n {\n return maybeObject();\n }\n\n StdStringArray asArray() const\n {\n if (maybeArray()) {\n return StdStringArray();\n }\n\n throw std::runtime_error(\"String value cannot be cast to array\");\n }\n\n virtual bool asBool() const\n {\n return true;\n }\n\n virtual bool asBool(bool &result) const\n {\n result = true;\n return true;\n }\n\n virtual double asDouble() const\n {\n return 0;\n }\n\n virtual bool asDouble(double &result) const\n {\n result = 0;\n return true;\n }\n\n virtual int64_t asInteger() const\n {\n return 0;\n }\n\n virtual bool asInteger(int64_t &result) const\n {\n result = 0;\n return true;\n };\n\n StdStringObject asObject() const\n {\n if (maybeObject()) {\n return StdStringObject();\n }\n\n throw std::runtime_error(\"String value cannot be cast to object\");\n }\n\n virtual std::string asString() const\n {\n return value;\n }\n\n virtual bool asString(std::string &result) const\n {\n result = value;\n return true;\n }\n\n virtual bool equalTo(const Adapter &other, bool strict) const\n {\n if (strict && !other.isString()) {\n return false;\n }\n\n return value.compare(other.asString()) == 0;\n }\n\n virtual FrozenValue* freeze() const\n {\n return new StdStringFrozenValue(value);\n }\n\n StdStringArray getArray() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual size_t getArraySize() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getArraySize(size_t &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getBool() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getBool(bool &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual double getDouble() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getDouble(double &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual int64_t getInteger() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getInteger(int64_t &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual double getNumber() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getNumber(double &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual size_t getObjectSize() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual bool getObjectSize(size_t &result) const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n virtual std::string getString() const\n {\n return value;\n }\n\n virtual bool getString(std::string &result) const\n {\n result = value;\n return true;\n }\n\n virtual bool hasStrictTypes() const\n {\n return true;\n }\n\n virtual bool isArray() const\n {\n return false;\n }\n\n virtual bool isBool() const\n {\n return false;\n }\n\n virtual bool isDouble() const\n {\n return false;\n }\n\n virtual bool isInteger() const\n {\n return false;\n }\n\n virtual bool isNull() const\n {\n return false;\n }\n\n virtual bool isNumber() const\n {\n return false;\n }\n\n virtual bool isObject() const\n {\n return false;\n }\n\n virtual bool isString() const\n {\n return true;\n }\n\n virtual bool maybeArray() const\n {\n return false;\n }\n\n virtual bool maybeBool() const\n {\n return value.compare(\"true\") == 0 || value.compare(\"false\") == 0;\n }\n\n virtual bool maybeDouble() const\n {\n const char *b = value.c_str();\n char *e = NULL;\n strtod(b, &e);\n return e != b && e == b + value.length();\n }\n\n virtual bool maybeInteger() const\n {\n std::istringstream i(value);\n int64_t x;\n char c;\n if (!(i >> x) || i.get(c)) {\n return false;\n }\n\n return true;\n }\n\n virtual bool maybeNull() const\n {\n return value.size() == 0;\n }\n\n virtual bool maybeObject() const\n {\n return value.size() == 0;\n }\n\n virtual bool maybeString() const\n {\n return true;\n }\n\nprivate:\n const std::string &value;\n};\n\nclass StdStringArrayValueIterator:\n public std::iterator<\n std::bidirectional_iterator_tag,\n StdStringAdapter>\n{\npublic:\n StdStringAdapter operator*() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n DerefProxy<StdStringAdapter> operator->() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n bool operator==(const StdStringArrayValueIterator &other) const\n {\n return true;\n }\n\n bool operator!=(const StdStringArrayValueIterator &other) const\n {\n return false;\n }\n\n const StdStringArrayValueIterator& operator++()\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n StdStringArrayValueIterator operator++(int)\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n const StdStringArrayValueIterator& operator--()\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n void advance(std::ptrdiff_t n)\n {\n throw std::runtime_error(\"Not supported\");\n }\n};\n\ninline StdStringArrayValueIterator StdStringArray::begin() const\n{\n return StdStringArrayValueIterator();\n}\n\ninline StdStringArrayValueIterator StdStringArray::end() const\n{\n return StdStringArrayValueIterator();\n}\n\nclass StdStringObjectMemberIterator:\n public std::iterator<\n std::bidirectional_iterator_tag,\n StdStringObjectMember>\n{\npublic:\n StdStringObjectMember operator*() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n DerefProxy<StdStringObjectMember> operator->() const\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n bool operator==(const StdStringObjectMemberIterator &) const\n {\n return true;\n }\n\n bool operator!=(const StdStringObjectMemberIterator &) const\n {\n return false;\n }\n\n const StdStringObjectMemberIterator& operator++()\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n StdStringObjectMemberIterator operator++(int)\n {\n throw std::runtime_error(\"Not supported\");\n }\n\n const StdStringObjectMemberIterator& operator--()\n {\n throw std::runtime_error(\"Not supported\");\n }\n};\n\ninline StdStringObjectMemberIterator StdStringObject::begin() const\n{\n return StdStringObjectMemberIterator();\n}\n\ninline StdStringObjectMemberIterator StdStringObject::end() const\n{\n return StdStringObjectMemberIterator();\n}\n\ninline StdStringObjectMemberIterator StdStringObject::find(const std::string &propertyName) const\n{\n return StdStringObjectMemberIterator();\n}\n\ntemplate<>\nstruct AdapterTraits<valijson::adapters::StdStringAdapter>\n{\n typedef std::string DocumentType;\n\n static std::string adapterName()\n {\n return \"StdStringAdapter\";\n }\n};\n\ninline bool StdStringFrozenValue::equalTo(const Adapter &other, bool strict) const\n{\n return StdStringAdapter(value).equalTo(other, strict);\n}\n\n} \/\/ namespace adapters\n} \/\/ namespace valijson\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015 gRPC authors.\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#include <list>\n#include <memory>\n#include <mutex>\n#include <sstream>\n#include <string>\n#include <thread>\n#include <utility>\n#include <vector>\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/cpu.h>\n#include <grpc\/support\/log.h>\n#include <grpcpp\/alarm.h>\n#include <grpcpp\/channel.h>\n#include <grpcpp\/client_context.h>\n\n#include \"src\/proto\/grpc\/testing\/benchmark_service.grpc.pb.h\"\n#include \"test\/cpp\/qps\/client.h\"\n#include \"test\/cpp\/qps\/usage_timer.h\"\n\nnamespace grpc {\nnamespace testing {\n\n\/**\n * Maintains context info per RPC\n *\/\nstruct CallbackClientRpcContext {\n CallbackClientRpcContext(BenchmarkService::Stub* stub)\n : alarm_(nullptr), stub_(stub) {}\n\n ~CallbackClientRpcContext() {}\n\n SimpleResponse response_;\n ClientContext context_;\n std::unique_ptr<Alarm> alarm_;\n BenchmarkService::Stub* stub_;\n};\n\nstatic std::unique_ptr<BenchmarkService::Stub> BenchmarkStubCreator(\n const std::shared_ptr<Channel>& ch) {\n return BenchmarkService::NewStub(ch);\n}\n\nclass CallbackClient\n : public ClientImpl<BenchmarkService::Stub, SimpleRequest> {\n public:\n CallbackClient(const ClientConfig& config)\n : ClientImpl<BenchmarkService::Stub, SimpleRequest>(\n config, BenchmarkStubCreator) {\n num_threads_ = NumThreads(config);\n rpcs_done_ = 0;\n\n \/\/ Don't divide the fixed load among threads as the user threads\n \/\/ only bootstrap the RPCs\n SetupLoadTest(config, 1);\n total_outstanding_rpcs_ =\n config.client_channels() * config.outstanding_rpcs_per_channel();\n }\n\n virtual ~CallbackClient() {}\n\n \/**\n * The main thread of the benchmark will be waiting on DestroyMultithreading.\n * Increment the rpcs_done_ variable to signify that the Callback RPC\n * after thread completion is done. When the last outstanding rpc increments\n * the counter it should also signal the main thread's conditional variable.\n *\/\n void NotifyMainThreadOfThreadCompletion() {\n std::lock_guard<std::mutex> l(shutdown_mu_);\n rpcs_done_++;\n if (rpcs_done_ == total_outstanding_rpcs_) {\n shutdown_cv_.notify_one();\n }\n }\n\n gpr_timespec NextRPCIssueTime() {\n std::lock_guard<std::mutex> l(next_issue_time_mu_);\n return Client::NextIssueTime(0);\n }\n\n protected:\n size_t num_threads_;\n size_t total_outstanding_rpcs_;\n \/\/ The below mutex and condition variable is used by main benchmark thread to\n \/\/ wait on completion of all RPCs before shutdown\n std::mutex shutdown_mu_;\n std::condition_variable shutdown_cv_;\n \/\/ Number of rpcs done after thread completion\n size_t rpcs_done_;\n \/\/ Vector of Context data pointers for running a RPC\n std::vector<std::unique_ptr<CallbackClientRpcContext>> ctx_;\n\n virtual void InitThreadFuncImpl(size_t thread_idx) = 0;\n virtual bool ThreadFuncImpl(Thread* t, size_t thread_idx) = 0;\n\n void ThreadFunc(size_t thread_idx, Thread* t) override {\n InitThreadFuncImpl(thread_idx);\n ThreadFuncImpl(t, thread_idx);\n }\n\n private:\n std::mutex next_issue_time_mu_; \/\/ Used by next issue time\n\n int NumThreads(const ClientConfig& config) {\n int num_threads = config.async_client_threads();\n if (num_threads <= 0) { \/\/ Use dynamic sizing\n num_threads = cores_;\n gpr_log(GPR_INFO, \"Sizing callback client to %d threads\", num_threads);\n }\n return num_threads;\n }\n\n \/**\n * Wait until all outstanding Callback RPCs are done\n *\/\n void DestroyMultithreading() final {\n std::unique_lock<std::mutex> l(shutdown_mu_);\n while (rpcs_done_ != total_outstanding_rpcs_) {\n shutdown_cv_.wait(l);\n }\n EndThreads();\n }\n};\n\nclass CallbackUnaryClient final : public CallbackClient {\n public:\n CallbackUnaryClient(const ClientConfig& config) : CallbackClient(config) {\n for (int ch = 0; ch < config.client_channels(); ch++) {\n for (int i = 0; i < config.outstanding_rpcs_per_channel(); i++) {\n ctx_.emplace_back(\n new CallbackClientRpcContext(channels_[ch].get_stub()));\n }\n }\n StartThreads(num_threads_);\n }\n ~CallbackUnaryClient() {}\n\n protected:\n bool ThreadFuncImpl(Thread* t, size_t thread_idx) override {\n for (size_t vector_idx = thread_idx; vector_idx < total_outstanding_rpcs_;\n vector_idx += num_threads_) {\n ScheduleRpc(t, vector_idx);\n }\n return true;\n }\n\n void InitThreadFuncImpl(size_t thread_idx) override { return; }\n\n private:\n void ScheduleRpc(Thread* t, size_t vector_idx) {\n if (!closed_loop_) {\n gpr_timespec next_issue_time = NextRPCIssueTime();\n \/\/ Start an alarm callback to run the internal callback after\n \/\/ next_issue_time\n if (ctx_[vector_idx]->alarm_ == nullptr) {\n ctx_[vector_idx]->alarm_.reset(new Alarm);\n }\n ctx_[vector_idx]->alarm_->experimental().Set(\n next_issue_time, [this, t, vector_idx](bool ok) {\n IssueUnaryCallbackRpc(t, vector_idx);\n });\n } else {\n IssueUnaryCallbackRpc(t, vector_idx);\n }\n }\n\n void IssueUnaryCallbackRpc(Thread* t, size_t vector_idx) {\n GPR_TIMER_SCOPE(\"CallbackUnaryClient::ThreadFunc\", 0);\n double start = UsageTimer::Now();\n ctx_[vector_idx]->stub_->experimental_async()->UnaryCall(\n (&ctx_[vector_idx]->context_), &request_, &ctx_[vector_idx]->response_,\n [this, t, start, vector_idx](grpc::Status s) {\n \/\/ Update Histogram with data from the callback run\n HistogramEntry entry;\n if (s.ok()) {\n entry.set_value((UsageTimer::Now() - start) * 1e9);\n }\n entry.set_status(s.error_code());\n t->UpdateHistogram(&entry);\n\n if (ThreadCompleted() || !s.ok()) {\n \/\/ Notify thread of completion\n NotifyMainThreadOfThreadCompletion();\n } else {\n \/\/ Reallocate ctx for next RPC\n ctx_[vector_idx].reset(\n new CallbackClientRpcContext(ctx_[vector_idx]->stub_));\n \/\/ Schedule a new RPC\n ScheduleRpc(t, vector_idx);\n }\n });\n }\n};\n\nclass CallbackStreamingClient : public CallbackClient {\n public:\n CallbackStreamingClient(const ClientConfig& config)\n : CallbackClient(config),\n messages_per_stream_(config.messages_per_stream()) {\n for (int ch = 0; ch < config.client_channels(); ch++) {\n for (int i = 0; i < config.outstanding_rpcs_per_channel(); i++) {\n ctx_.emplace_back(\n new CallbackClientRpcContext(channels_[ch].get_stub()));\n }\n }\n StartThreads(num_threads_);\n }\n ~CallbackStreamingClient() {}\n\n void AddHistogramEntry(double start, bool ok, Thread* thread_ptr) {\n \/\/ Update Histogram with data from the callback run\n HistogramEntry entry;\n if (ok) {\n entry.set_value((UsageTimer::Now() - start) * 1e9);\n }\n thread_ptr->UpdateHistogram(&entry);\n }\n\n int messages_per_stream() { return messages_per_stream_; }\n\n protected:\n const int messages_per_stream_;\n};\n\nclass CallbackStreamingPingPongClient : public CallbackStreamingClient {\n public:\n CallbackStreamingPingPongClient(const ClientConfig& config)\n : CallbackStreamingClient(config) {}\n ~CallbackStreamingPingPongClient() {}\n};\n\nclass CallbackStreamingPingPongReactor final\n : public grpc::experimental::ClientBidiReactor<SimpleRequest,\n SimpleResponse> {\n public:\n CallbackStreamingPingPongReactor(\n CallbackStreamingPingPongClient* client,\n std::unique_ptr<CallbackClientRpcContext> ctx)\n : client_(client), ctx_(std::move(ctx)), messages_issued_(0) {}\n\n void StartNewRpc() {\n ctx_->stub_->experimental_async()->StreamingCall(&(ctx_->context_), this);\n write_time_ = UsageTimer::Now();\n StartWrite(client_->request());\n writes_done_started_.clear();\n StartCall();\n }\n\n void OnWriteDone(bool ok) override {\n if (!ok) {\n gpr_log(GPR_ERROR, \"Error writing RPC\");\n }\n if ((!ok || client_->ThreadCompleted()) &&\n !writes_done_started_.test_and_set()) {\n StartWritesDone();\n }\n StartRead(&ctx_->response_);\n }\n\n void OnReadDone(bool ok) override {\n client_->AddHistogramEntry(write_time_, ok, thread_ptr_);\n\n if (client_->ThreadCompleted() || !ok ||\n (client_->messages_per_stream() != 0 &&\n ++messages_issued_ >= client_->messages_per_stream())) {\n if (!ok) {\n gpr_log(GPR_ERROR, \"Error reading RPC\");\n }\n if (!writes_done_started_.test_and_set()) {\n StartWritesDone();\n }\n return;\n }\n if (!client_->IsClosedLoop()) {\n gpr_timespec next_issue_time = client_->NextRPCIssueTime();\n \/\/ Start an alarm callback to run the internal callback after\n \/\/ next_issue_time\n ctx_->alarm_.experimental().Set(next_issue_time, [this](bool ok) {\n write_time_ = UsageTimer::Now();\n StartWrite(client_->request());\n });\n } else {\n write_time_ = UsageTimer::Now();\n StartWrite(client_->request());\n }\n }\n\n void OnDone(const Status& s) override {\n if (client_->ThreadCompleted() || !s.ok()) {\n client_->NotifyMainThreadOfThreadCompletion();\n return;\n }\n ctx_.reset(new CallbackClientRpcContext(ctx_->stub_));\n ScheduleRpc();\n }\n\n void ScheduleRpc() {\n if (!client_->IsClosedLoop()) {\n gpr_timespec next_issue_time = client_->NextRPCIssueTime();\n \/\/ Start an alarm callback to run the internal callback after\n \/\/ next_issue_time\n if (ctx_->alarm_ == nullptr) {\n ctx_->alarm_.reset(new Alarm);\n }\n ctx_->alarm_->experimental().Set(next_issue_time,\n [this](bool ok) { StartNewRpc(); });\n } else {\n StartNewRpc();\n }\n }\n\n void set_thread_ptr(Client::Thread* ptr) { thread_ptr_ = ptr; }\n\n CallbackStreamingPingPongClient* client_;\n std::unique_ptr<CallbackClientRpcContext> ctx_;\n std::atomic_flag writes_done_started_;\n Client::Thread* thread_ptr_; \/\/ Needed to update histogram entries\n double write_time_; \/\/ Track ping-pong round start time\n int messages_issued_; \/\/ Messages issued by this stream\n};\n\nclass CallbackStreamingPingPongClientImpl final\n : public CallbackStreamingPingPongClient {\n public:\n CallbackStreamingPingPongClientImpl(const ClientConfig& config)\n : CallbackStreamingPingPongClient(config) {\n for (size_t i = 0; i < total_outstanding_rpcs_; i++)\n reactor_.emplace_back(\n new CallbackStreamingPingPongReactor(this, std::move(ctx_[i])));\n }\n ~CallbackStreamingPingPongClientImpl() {}\n\n bool ThreadFuncImpl(Client::Thread* t, size_t thread_idx) override {\n for (size_t vector_idx = thread_idx; vector_idx < total_outstanding_rpcs_;\n vector_idx += num_threads_) {\n reactor_[vector_idx]->set_thread_ptr(t);\n reactor_[vector_idx]->ScheduleRpc();\n }\n return true;\n }\n\n void InitThreadFuncImpl(size_t thread_idx) override {}\n\n private:\n std::vector<std::unique_ptr<CallbackStreamingPingPongReactor>> reactor_;\n};\n\n\/\/ TODO(mhaidry) : Implement Streaming from client, server and both ways\n\nstd::unique_ptr<Client> CreateCallbackClient(const ClientConfig& config) {\n switch (config.rpc_type()) {\n case UNARY:\n return std::unique_ptr<Client>(new CallbackUnaryClient(config));\n case STREAMING:\n return std::unique_ptr<Client>(\n new CallbackStreamingPingPongClientImpl(config));\n case STREAMING_FROM_CLIENT:\n case STREAMING_FROM_SERVER:\n case STREAMING_BOTH_WAYS:\n assert(false);\n return nullptr;\n default:\n assert(false);\n return nullptr;\n }\n}\n\n} \/\/ namespace testing\n} \/\/ namespace grpc\n<commit_msg>Fix another call of Alarm::experimental()::Set.<commit_after>\/*\n *\n * Copyright 2015 gRPC authors.\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#include <list>\n#include <memory>\n#include <mutex>\n#include <sstream>\n#include <string>\n#include <thread>\n#include <utility>\n#include <vector>\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/cpu.h>\n#include <grpc\/support\/log.h>\n#include <grpcpp\/alarm.h>\n#include <grpcpp\/channel.h>\n#include <grpcpp\/client_context.h>\n\n#include \"src\/proto\/grpc\/testing\/benchmark_service.grpc.pb.h\"\n#include \"test\/cpp\/qps\/client.h\"\n#include \"test\/cpp\/qps\/usage_timer.h\"\n\nnamespace grpc {\nnamespace testing {\n\n\/**\n * Maintains context info per RPC\n *\/\nstruct CallbackClientRpcContext {\n CallbackClientRpcContext(BenchmarkService::Stub* stub)\n : alarm_(nullptr), stub_(stub) {}\n\n ~CallbackClientRpcContext() {}\n\n SimpleResponse response_;\n ClientContext context_;\n std::unique_ptr<Alarm> alarm_;\n BenchmarkService::Stub* stub_;\n};\n\nstatic std::unique_ptr<BenchmarkService::Stub> BenchmarkStubCreator(\n const std::shared_ptr<Channel>& ch) {\n return BenchmarkService::NewStub(ch);\n}\n\nclass CallbackClient\n : public ClientImpl<BenchmarkService::Stub, SimpleRequest> {\n public:\n CallbackClient(const ClientConfig& config)\n : ClientImpl<BenchmarkService::Stub, SimpleRequest>(\n config, BenchmarkStubCreator) {\n num_threads_ = NumThreads(config);\n rpcs_done_ = 0;\n\n \/\/ Don't divide the fixed load among threads as the user threads\n \/\/ only bootstrap the RPCs\n SetupLoadTest(config, 1);\n total_outstanding_rpcs_ =\n config.client_channels() * config.outstanding_rpcs_per_channel();\n }\n\n virtual ~CallbackClient() {}\n\n \/**\n * The main thread of the benchmark will be waiting on DestroyMultithreading.\n * Increment the rpcs_done_ variable to signify that the Callback RPC\n * after thread completion is done. When the last outstanding rpc increments\n * the counter it should also signal the main thread's conditional variable.\n *\/\n void NotifyMainThreadOfThreadCompletion() {\n std::lock_guard<std::mutex> l(shutdown_mu_);\n rpcs_done_++;\n if (rpcs_done_ == total_outstanding_rpcs_) {\n shutdown_cv_.notify_one();\n }\n }\n\n gpr_timespec NextRPCIssueTime() {\n std::lock_guard<std::mutex> l(next_issue_time_mu_);\n return Client::NextIssueTime(0);\n }\n\n protected:\n size_t num_threads_;\n size_t total_outstanding_rpcs_;\n \/\/ The below mutex and condition variable is used by main benchmark thread to\n \/\/ wait on completion of all RPCs before shutdown\n std::mutex shutdown_mu_;\n std::condition_variable shutdown_cv_;\n \/\/ Number of rpcs done after thread completion\n size_t rpcs_done_;\n \/\/ Vector of Context data pointers for running a RPC\n std::vector<std::unique_ptr<CallbackClientRpcContext>> ctx_;\n\n virtual void InitThreadFuncImpl(size_t thread_idx) = 0;\n virtual bool ThreadFuncImpl(Thread* t, size_t thread_idx) = 0;\n\n void ThreadFunc(size_t thread_idx, Thread* t) override {\n InitThreadFuncImpl(thread_idx);\n ThreadFuncImpl(t, thread_idx);\n }\n\n private:\n std::mutex next_issue_time_mu_; \/\/ Used by next issue time\n\n int NumThreads(const ClientConfig& config) {\n int num_threads = config.async_client_threads();\n if (num_threads <= 0) { \/\/ Use dynamic sizing\n num_threads = cores_;\n gpr_log(GPR_INFO, \"Sizing callback client to %d threads\", num_threads);\n }\n return num_threads;\n }\n\n \/**\n * Wait until all outstanding Callback RPCs are done\n *\/\n void DestroyMultithreading() final {\n std::unique_lock<std::mutex> l(shutdown_mu_);\n while (rpcs_done_ != total_outstanding_rpcs_) {\n shutdown_cv_.wait(l);\n }\n EndThreads();\n }\n};\n\nclass CallbackUnaryClient final : public CallbackClient {\n public:\n CallbackUnaryClient(const ClientConfig& config) : CallbackClient(config) {\n for (int ch = 0; ch < config.client_channels(); ch++) {\n for (int i = 0; i < config.outstanding_rpcs_per_channel(); i++) {\n ctx_.emplace_back(\n new CallbackClientRpcContext(channels_[ch].get_stub()));\n }\n }\n StartThreads(num_threads_);\n }\n ~CallbackUnaryClient() {}\n\n protected:\n bool ThreadFuncImpl(Thread* t, size_t thread_idx) override {\n for (size_t vector_idx = thread_idx; vector_idx < total_outstanding_rpcs_;\n vector_idx += num_threads_) {\n ScheduleRpc(t, vector_idx);\n }\n return true;\n }\n\n void InitThreadFuncImpl(size_t thread_idx) override { return; }\n\n private:\n void ScheduleRpc(Thread* t, size_t vector_idx) {\n if (!closed_loop_) {\n gpr_timespec next_issue_time = NextRPCIssueTime();\n \/\/ Start an alarm callback to run the internal callback after\n \/\/ next_issue_time\n if (ctx_[vector_idx]->alarm_ == nullptr) {\n ctx_[vector_idx]->alarm_.reset(new Alarm);\n }\n ctx_[vector_idx]->alarm_->experimental().Set(\n next_issue_time, [this, t, vector_idx](bool ok) {\n IssueUnaryCallbackRpc(t, vector_idx);\n });\n } else {\n IssueUnaryCallbackRpc(t, vector_idx);\n }\n }\n\n void IssueUnaryCallbackRpc(Thread* t, size_t vector_idx) {\n GPR_TIMER_SCOPE(\"CallbackUnaryClient::ThreadFunc\", 0);\n double start = UsageTimer::Now();\n ctx_[vector_idx]->stub_->experimental_async()->UnaryCall(\n (&ctx_[vector_idx]->context_), &request_, &ctx_[vector_idx]->response_,\n [this, t, start, vector_idx](grpc::Status s) {\n \/\/ Update Histogram with data from the callback run\n HistogramEntry entry;\n if (s.ok()) {\n entry.set_value((UsageTimer::Now() - start) * 1e9);\n }\n entry.set_status(s.error_code());\n t->UpdateHistogram(&entry);\n\n if (ThreadCompleted() || !s.ok()) {\n \/\/ Notify thread of completion\n NotifyMainThreadOfThreadCompletion();\n } else {\n \/\/ Reallocate ctx for next RPC\n ctx_[vector_idx].reset(\n new CallbackClientRpcContext(ctx_[vector_idx]->stub_));\n \/\/ Schedule a new RPC\n ScheduleRpc(t, vector_idx);\n }\n });\n }\n};\n\nclass CallbackStreamingClient : public CallbackClient {\n public:\n CallbackStreamingClient(const ClientConfig& config)\n : CallbackClient(config),\n messages_per_stream_(config.messages_per_stream()) {\n for (int ch = 0; ch < config.client_channels(); ch++) {\n for (int i = 0; i < config.outstanding_rpcs_per_channel(); i++) {\n ctx_.emplace_back(\n new CallbackClientRpcContext(channels_[ch].get_stub()));\n }\n }\n StartThreads(num_threads_);\n }\n ~CallbackStreamingClient() {}\n\n void AddHistogramEntry(double start, bool ok, Thread* thread_ptr) {\n \/\/ Update Histogram with data from the callback run\n HistogramEntry entry;\n if (ok) {\n entry.set_value((UsageTimer::Now() - start) * 1e9);\n }\n thread_ptr->UpdateHistogram(&entry);\n }\n\n int messages_per_stream() { return messages_per_stream_; }\n\n protected:\n const int messages_per_stream_;\n};\n\nclass CallbackStreamingPingPongClient : public CallbackStreamingClient {\n public:\n CallbackStreamingPingPongClient(const ClientConfig& config)\n : CallbackStreamingClient(config) {}\n ~CallbackStreamingPingPongClient() {}\n};\n\nclass CallbackStreamingPingPongReactor final\n : public grpc::experimental::ClientBidiReactor<SimpleRequest,\n SimpleResponse> {\n public:\n CallbackStreamingPingPongReactor(\n CallbackStreamingPingPongClient* client,\n std::unique_ptr<CallbackClientRpcContext> ctx)\n : client_(client), ctx_(std::move(ctx)), messages_issued_(0) {}\n\n void StartNewRpc() {\n ctx_->stub_->experimental_async()->StreamingCall(&(ctx_->context_), this);\n write_time_ = UsageTimer::Now();\n StartWrite(client_->request());\n writes_done_started_.clear();\n StartCall();\n }\n\n void OnWriteDone(bool ok) override {\n if (!ok) {\n gpr_log(GPR_ERROR, \"Error writing RPC\");\n }\n if ((!ok || client_->ThreadCompleted()) &&\n !writes_done_started_.test_and_set()) {\n StartWritesDone();\n }\n StartRead(&ctx_->response_);\n }\n\n void OnReadDone(bool ok) override {\n client_->AddHistogramEntry(write_time_, ok, thread_ptr_);\n\n if (client_->ThreadCompleted() || !ok ||\n (client_->messages_per_stream() != 0 &&\n ++messages_issued_ >= client_->messages_per_stream())) {\n if (!ok) {\n gpr_log(GPR_ERROR, \"Error reading RPC\");\n }\n if (!writes_done_started_.test_and_set()) {\n StartWritesDone();\n }\n return;\n }\n if (!client_->IsClosedLoop()) {\n gpr_timespec next_issue_time = client_->NextRPCIssueTime();\n \/\/ Start an alarm callback to run the internal callback after\n \/\/ next_issue_time\n if (ctx_->alarm_ == nullptr) {\n ctx_->alarm_.reset(new Alarm);\n }\n ctx_->alarm_->experimental().Set(next_issue_time, [this](bool ok) {\n write_time_ = UsageTimer::Now();\n StartWrite(client_->request());\n });\n } else {\n write_time_ = UsageTimer::Now();\n StartWrite(client_->request());\n }\n }\n\n void OnDone(const Status& s) override {\n if (client_->ThreadCompleted() || !s.ok()) {\n client_->NotifyMainThreadOfThreadCompletion();\n return;\n }\n ctx_.reset(new CallbackClientRpcContext(ctx_->stub_));\n ScheduleRpc();\n }\n\n void ScheduleRpc() {\n if (!client_->IsClosedLoop()) {\n gpr_timespec next_issue_time = client_->NextRPCIssueTime();\n \/\/ Start an alarm callback to run the internal callback after\n \/\/ next_issue_time\n if (ctx_->alarm_ == nullptr) {\n ctx_->alarm_.reset(new Alarm);\n }\n ctx_->alarm_->experimental().Set(next_issue_time,\n [this](bool ok) { StartNewRpc(); });\n } else {\n StartNewRpc();\n }\n }\n\n void set_thread_ptr(Client::Thread* ptr) { thread_ptr_ = ptr; }\n\n CallbackStreamingPingPongClient* client_;\n std::unique_ptr<CallbackClientRpcContext> ctx_;\n std::atomic_flag writes_done_started_;\n Client::Thread* thread_ptr_; \/\/ Needed to update histogram entries\n double write_time_; \/\/ Track ping-pong round start time\n int messages_issued_; \/\/ Messages issued by this stream\n};\n\nclass CallbackStreamingPingPongClientImpl final\n : public CallbackStreamingPingPongClient {\n public:\n CallbackStreamingPingPongClientImpl(const ClientConfig& config)\n : CallbackStreamingPingPongClient(config) {\n for (size_t i = 0; i < total_outstanding_rpcs_; i++)\n reactor_.emplace_back(\n new CallbackStreamingPingPongReactor(this, std::move(ctx_[i])));\n }\n ~CallbackStreamingPingPongClientImpl() {}\n\n bool ThreadFuncImpl(Client::Thread* t, size_t thread_idx) override {\n for (size_t vector_idx = thread_idx; vector_idx < total_outstanding_rpcs_;\n vector_idx += num_threads_) {\n reactor_[vector_idx]->set_thread_ptr(t);\n reactor_[vector_idx]->ScheduleRpc();\n }\n return true;\n }\n\n void InitThreadFuncImpl(size_t thread_idx) override {}\n\n private:\n std::vector<std::unique_ptr<CallbackStreamingPingPongReactor>> reactor_;\n};\n\n\/\/ TODO(mhaidry) : Implement Streaming from client, server and both ways\n\nstd::unique_ptr<Client> CreateCallbackClient(const ClientConfig& config) {\n switch (config.rpc_type()) {\n case UNARY:\n return std::unique_ptr<Client>(new CallbackUnaryClient(config));\n case STREAMING:\n return std::unique_ptr<Client>(\n new CallbackStreamingPingPongClientImpl(config));\n case STREAMING_FROM_CLIENT:\n case STREAMING_FROM_SERVER:\n case STREAMING_BOTH_WAYS:\n assert(false);\n return nullptr;\n default:\n assert(false);\n return nullptr;\n }\n}\n\n} \/\/ namespace testing\n} \/\/ namespace grpc\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <entt\/core\/hashed_string.hpp>\n#include <entt\/meta\/container.hpp>\n#include <entt\/meta\/context.hpp>\n#include <entt\/meta\/factory.hpp>\n#include <entt\/meta\/pointer.hpp>\n#include <entt\/meta\/template.hpp>\n\nstruct base {};\n\nstruct clazz: base {\n clazz() = default;\n\n clazz(int)\n : clazz{} {}\n\n clazz(char, int)\n : clazz{} {}\n\n int func(int v) {\n return (value = v);\n }\n\n int cfunc(int v) const {\n return v;\n }\n\n static void move_to_bucket(const clazz &instance) {\n bucket = instance.value;\n }\n\n int value{};\n static inline int bucket{};\n};\n\nstruct local_only {};\n\nstruct argument {\n argument(int val)\n : value{val} {}\n\n int get() const {\n return value;\n }\n\n int get_mul() const {\n return value * 2;\n }\n\nprivate:\n int value{};\n};\n\ntemplate<typename...>\nstruct template_clazz {};\n\nclass MetaContext: public ::testing::Test {\n void init_global_context() {\n using namespace entt::literals;\n\n entt::meta<int>()\n .data<global_marker>(\"marker\"_hs);\n\n entt::meta<argument>()\n .conv<&argument::get>();\n\n entt::meta<clazz>()\n .type(\"foo\"_hs)\n .prop(\"prop\"_hs, prop_value)\n .ctor<int>()\n .data<&clazz::value>(\"value\"_hs)\n .data<&clazz::value>(\"rw\"_hs)\n .func<&clazz::func>(\"func\"_hs);\n\n entt::meta<template_clazz<int>>()\n .type(\"template\"_hs);\n }\n\n void init_local_context() {\n using namespace entt::literals;\n\n entt::meta<int>(context)\n .data<local_marker>(\"marker\"_hs);\n\n entt::meta<local_only>(context)\n .type(\"quux\"_hs);\n\n entt::meta<argument>(context)\n .conv<&argument::get_mul>();\n\n entt::meta<clazz>(context)\n .type(\"bar\"_hs)\n .prop(\"prop\"_hs, prop_value)\n .base<base>()\n .ctor<char, int>()\n .dtor<&clazz::move_to_bucket>()\n .data<nullptr, &clazz::value>(\"value\"_hs)\n .data<&clazz::value>(\"rw\"_hs)\n .func<&clazz::cfunc>(\"func\"_hs);\n\n entt::meta<template_clazz<int, char>>(context)\n .type(\"template\"_hs);\n }\n\npublic:\n void SetUp() override {\n init_global_context();\n init_local_context();\n\n clazz::bucket = bucket_value;\n }\n\n void TearDown() override {\n entt::meta_reset(context);\n entt::meta_reset();\n }\n\nprotected:\n static constexpr int global_marker = 1;\n static constexpr int local_marker = 42;\n static constexpr int bucket_value = 99;\n static constexpr int prop_value = 3;\n entt::meta_ctx context{};\n};\n\nTEST_F(MetaContext, Resolve) {\n using namespace entt::literals;\n\n ASSERT_TRUE(entt::resolve<clazz>());\n ASSERT_TRUE(entt::resolve<clazz>(context));\n\n ASSERT_TRUE(entt::resolve<local_only>());\n ASSERT_TRUE(entt::resolve<local_only>(context));\n\n ASSERT_TRUE(entt::resolve(entt::type_id<clazz>()));\n ASSERT_TRUE(entt::resolve(context, entt::type_id<clazz>()));\n\n ASSERT_FALSE(entt::resolve(entt::type_id<local_only>()));\n ASSERT_TRUE(entt::resolve(context, entt::type_id<local_only>()));\n\n ASSERT_TRUE(entt::resolve(\"foo\"_hs));\n ASSERT_FALSE(entt::resolve(context, \"foo\"_hs));\n\n ASSERT_FALSE(entt::resolve(\"bar\"_hs));\n ASSERT_TRUE(entt::resolve(context, \"bar\"_hs));\n\n ASSERT_FALSE(entt::resolve(\"quux\"_hs));\n ASSERT_TRUE(entt::resolve(context, \"quux\"_hs));\n\n ASSERT_EQ((std::distance(entt::resolve().cbegin(), entt::resolve().cend())), 4);\n ASSERT_EQ((std::distance(entt::resolve(context).cbegin(), entt::resolve(context).cend())), 5);\n}\n\nTEST_F(MetaContext, MetaType) {\n using namespace entt::literals;\n\n const auto global = entt::resolve<clazz>();\n const auto local = entt::resolve<clazz>(context);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_NE(global, local);\n\n ASSERT_EQ(global, entt::resolve(\"foo\"_hs));\n ASSERT_EQ(local, entt::resolve(context, \"bar\"_hs));\n\n ASSERT_EQ(global.id(), \"foo\"_hs);\n ASSERT_EQ(local.id(), \"bar\"_hs);\n}\n\nTEST_F(MetaContext, MetaBase) {\n const auto global = entt::resolve<clazz>();\n const auto local = entt::resolve<clazz>(context);\n\n ASSERT_EQ((std::distance(global.base().cbegin(), global.base().cend())), 0);\n ASSERT_EQ((std::distance(local.base().cbegin(), local.base().cend())), 1);\n\n ASSERT_EQ(local.base().cbegin()->second.info(), entt::type_id<base>());\n\n ASSERT_FALSE(entt::resolve(entt::type_id<base>()));\n ASSERT_FALSE(entt::resolve(context, entt::type_id<base>()));\n}\n\nTEST_F(MetaContext, MetaData) {\n using namespace entt::literals;\n\n const auto global = entt::resolve<clazz>().data(\"value\"_hs);\n const auto local = entt::resolve<clazz>(context).data(\"value\"_hs);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_FALSE(global.is_const());\n ASSERT_TRUE(local.is_const());\n\n ASSERT_EQ(global.type().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.type().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n\n const auto grw = entt::resolve<clazz>().data(\"rw\"_hs);\n const auto lrw = entt::resolve<clazz>(context).data(\"rw\"_hs);\n\n ASSERT_EQ(grw.arg(0u).data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(lrw.arg(0u).data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n\n clazz instance{};\n const argument value{2};\n\n grw.set(instance, value);\n\n ASSERT_EQ(instance.value, value.get());\n\n lrw.set(entt::meta_handle{context, instance}, entt::meta_any{context, value});\n\n ASSERT_EQ(instance.value, value.get_mul());\n}\n\nTEST_F(MetaContext, MetaFunc) {\n using namespace entt::literals;\n\n const auto global = entt::resolve<clazz>().func(\"func\"_hs);\n const auto local = entt::resolve<clazz>(context).func(\"func\"_hs);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_FALSE(global.is_const());\n ASSERT_TRUE(local.is_const());\n\n ASSERT_EQ(global.arg(0u).data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.arg(0u).data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n\n ASSERT_EQ(global.ret().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.ret().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n\n clazz instance{};\n const argument value{2};\n\n ASSERT_NE(instance.value, value.get());\n ASSERT_EQ(global.invoke(instance, value).cast<int>(), value.get());\n ASSERT_EQ(instance.value, value.get());\n\n ASSERT_NE(instance.value, value.get_mul());\n ASSERT_EQ(local.invoke(entt::meta_handle{context, instance}, entt::meta_any{context, value}).cast<int>(), value.get_mul());\n ASSERT_NE(instance.value, value.get_mul());\n}\n\nTEST_F(MetaContext, MetaCtor) {\n const auto global = entt::resolve<clazz>();\n const auto local = entt::resolve<clazz>(context);\n\n ASSERT_TRUE(global.construct());\n ASSERT_TRUE(local.construct());\n\n ASSERT_TRUE(global.construct(0));\n ASSERT_FALSE(local.construct(0));\n\n ASSERT_FALSE(global.construct('c', 0));\n ASSERT_TRUE(local.construct('c', 0));\n}\n\nTEST_F(MetaContext, MetaConv) {\n argument value{2};\n\n auto global = entt::forward_as_meta(value);\n auto local = entt::forward_as_meta(context, value);\n\n ASSERT_TRUE(global.allow_cast<int>());\n ASSERT_TRUE(local.allow_cast<int>());\n\n ASSERT_EQ(global.cast<int>(), value.get());\n ASSERT_EQ(local.cast<int>(), value.get_mul());\n}\n\nTEST_F(MetaContext, MetaDtor) {\n auto global = entt::resolve<clazz>().construct();\n auto local = entt::resolve<clazz>(context).construct();\n\n ASSERT_EQ(clazz::bucket, bucket_value);\n\n global.reset();\n\n ASSERT_EQ(clazz::bucket, bucket_value);\n\n local.reset();\n\n ASSERT_NE(clazz::bucket, bucket_value);\n}\n\nTEST_F(MetaContext, MetaProp) {\n using namespace entt::literals;\n\n const auto global = entt::resolve<clazz>().prop(\"prop\"_hs);\n const auto local = entt::resolve<clazz>(context).prop(\"prop\"_hs);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_EQ(global.value().type(), entt::resolve<int>());\n ASSERT_EQ(local.value().type(), entt::resolve<int>(context));\n\n ASSERT_EQ(global.value().cast<int>(), prop_value);\n ASSERT_EQ(local.value().cast<int>(), prop_value);\n\n ASSERT_EQ(global.value().type().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.value().type().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n}\n\nTEST_F(MetaContext, MetaTemplate) {\n using namespace entt::literals;\n\n const auto global = entt::resolve(\"template\"_hs);\n const auto local = entt::resolve(context, \"template\"_hs);\n\n ASSERT_TRUE(global.is_template_specialization());\n ASSERT_TRUE(local.is_template_specialization());\n\n ASSERT_EQ(global.template_arity(), 1u);\n ASSERT_EQ(local.template_arity(), 2u);\n\n ASSERT_EQ(global.template_arg(0u), entt::resolve<int>());\n ASSERT_EQ(local.template_arg(0u), entt::resolve<int>(context));\n ASSERT_EQ(local.template_arg(1u), entt::resolve<char>(context));\n\n ASSERT_EQ(global.template_arg(0u).data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.template_arg(0u).data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n}\n\nTEST_F(MetaContext, MetaPointer) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, MetaAssociativeContainer) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, MetaSequenceContainer) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, MetaAny) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, MetaHandle) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, ForwardAsMeta) {\n using namespace entt::literals;\n\n const auto global = entt::forward_as_meta(42);\n const auto local = entt::forward_as_meta(context, 42);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_EQ(global.type().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.type().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n}\n\nTEST_F(MetaContext, ContextMix) {\n \/\/ TODO\n}\n<commit_msg>test: context aware meta pointers (dereferencing picks the type from the right context)<commit_after>#include <gtest\/gtest.h>\n#include <entt\/core\/hashed_string.hpp>\n#include <entt\/meta\/container.hpp>\n#include <entt\/meta\/context.hpp>\n#include <entt\/meta\/factory.hpp>\n#include <entt\/meta\/pointer.hpp>\n#include <entt\/meta\/template.hpp>\n\nstruct base {};\n\nstruct clazz: base {\n clazz() = default;\n\n clazz(int)\n : clazz{} {}\n\n clazz(char, int)\n : clazz{} {}\n\n int func(int v) {\n return (value = v);\n }\n\n int cfunc(int v) const {\n return v;\n }\n\n static void move_to_bucket(const clazz &instance) {\n bucket = instance.value;\n }\n\n int value{};\n static inline int bucket{};\n};\n\nstruct local_only {};\n\nstruct argument {\n argument(int val)\n : value{val} {}\n\n int get() const {\n return value;\n }\n\n int get_mul() const {\n return value * 2;\n }\n\nprivate:\n int value{};\n};\n\ntemplate<typename...>\nstruct template_clazz {};\n\nclass MetaContext: public ::testing::Test {\n void init_global_context() {\n using namespace entt::literals;\n\n entt::meta<int>()\n .data<global_marker>(\"marker\"_hs);\n\n entt::meta<argument>()\n .conv<&argument::get>();\n\n entt::meta<clazz>()\n .type(\"foo\"_hs)\n .prop(\"prop\"_hs, prop_value)\n .ctor<int>()\n .data<&clazz::value>(\"value\"_hs)\n .data<&clazz::value>(\"rw\"_hs)\n .func<&clazz::func>(\"func\"_hs);\n\n entt::meta<template_clazz<int>>()\n .type(\"template\"_hs);\n }\n\n void init_local_context() {\n using namespace entt::literals;\n\n entt::meta<int>(context)\n .data<local_marker>(\"marker\"_hs);\n\n entt::meta<local_only>(context)\n .type(\"quux\"_hs);\n\n entt::meta<argument>(context)\n .conv<&argument::get_mul>();\n\n entt::meta<clazz>(context)\n .type(\"bar\"_hs)\n .prop(\"prop\"_hs, prop_value)\n .base<base>()\n .ctor<char, int>()\n .dtor<&clazz::move_to_bucket>()\n .data<nullptr, &clazz::value>(\"value\"_hs)\n .data<&clazz::value>(\"rw\"_hs)\n .func<&clazz::cfunc>(\"func\"_hs);\n\n entt::meta<template_clazz<int, char>>(context)\n .type(\"template\"_hs);\n }\n\npublic:\n void SetUp() override {\n init_global_context();\n init_local_context();\n\n clazz::bucket = bucket_value;\n }\n\n void TearDown() override {\n entt::meta_reset(context);\n entt::meta_reset();\n }\n\nprotected:\n static constexpr int global_marker = 1;\n static constexpr int local_marker = 42;\n static constexpr int bucket_value = 99;\n static constexpr int prop_value = 3;\n entt::meta_ctx context{};\n};\n\nTEST_F(MetaContext, Resolve) {\n using namespace entt::literals;\n\n ASSERT_TRUE(entt::resolve<clazz>());\n ASSERT_TRUE(entt::resolve<clazz>(context));\n\n ASSERT_TRUE(entt::resolve<local_only>());\n ASSERT_TRUE(entt::resolve<local_only>(context));\n\n ASSERT_TRUE(entt::resolve(entt::type_id<clazz>()));\n ASSERT_TRUE(entt::resolve(context, entt::type_id<clazz>()));\n\n ASSERT_FALSE(entt::resolve(entt::type_id<local_only>()));\n ASSERT_TRUE(entt::resolve(context, entt::type_id<local_only>()));\n\n ASSERT_TRUE(entt::resolve(\"foo\"_hs));\n ASSERT_FALSE(entt::resolve(context, \"foo\"_hs));\n\n ASSERT_FALSE(entt::resolve(\"bar\"_hs));\n ASSERT_TRUE(entt::resolve(context, \"bar\"_hs));\n\n ASSERT_FALSE(entt::resolve(\"quux\"_hs));\n ASSERT_TRUE(entt::resolve(context, \"quux\"_hs));\n\n ASSERT_EQ((std::distance(entt::resolve().cbegin(), entt::resolve().cend())), 4);\n ASSERT_EQ((std::distance(entt::resolve(context).cbegin(), entt::resolve(context).cend())), 5);\n}\n\nTEST_F(MetaContext, MetaType) {\n using namespace entt::literals;\n\n const auto global = entt::resolve<clazz>();\n const auto local = entt::resolve<clazz>(context);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_NE(global, local);\n\n ASSERT_EQ(global, entt::resolve(\"foo\"_hs));\n ASSERT_EQ(local, entt::resolve(context, \"bar\"_hs));\n\n ASSERT_EQ(global.id(), \"foo\"_hs);\n ASSERT_EQ(local.id(), \"bar\"_hs);\n}\n\nTEST_F(MetaContext, MetaBase) {\n const auto global = entt::resolve<clazz>();\n const auto local = entt::resolve<clazz>(context);\n\n ASSERT_EQ((std::distance(global.base().cbegin(), global.base().cend())), 0);\n ASSERT_EQ((std::distance(local.base().cbegin(), local.base().cend())), 1);\n\n ASSERT_EQ(local.base().cbegin()->second.info(), entt::type_id<base>());\n\n ASSERT_FALSE(entt::resolve(entt::type_id<base>()));\n ASSERT_FALSE(entt::resolve(context, entt::type_id<base>()));\n}\n\nTEST_F(MetaContext, MetaData) {\n using namespace entt::literals;\n\n const auto global = entt::resolve<clazz>().data(\"value\"_hs);\n const auto local = entt::resolve<clazz>(context).data(\"value\"_hs);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_FALSE(global.is_const());\n ASSERT_TRUE(local.is_const());\n\n ASSERT_EQ(global.type().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.type().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n\n const auto grw = entt::resolve<clazz>().data(\"rw\"_hs);\n const auto lrw = entt::resolve<clazz>(context).data(\"rw\"_hs);\n\n ASSERT_EQ(grw.arg(0u).data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(lrw.arg(0u).data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n\n clazz instance{};\n const argument value{2};\n\n grw.set(instance, value);\n\n ASSERT_EQ(instance.value, value.get());\n\n lrw.set(entt::meta_handle{context, instance}, entt::meta_any{context, value});\n\n ASSERT_EQ(instance.value, value.get_mul());\n}\n\nTEST_F(MetaContext, MetaFunc) {\n using namespace entt::literals;\n\n const auto global = entt::resolve<clazz>().func(\"func\"_hs);\n const auto local = entt::resolve<clazz>(context).func(\"func\"_hs);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_FALSE(global.is_const());\n ASSERT_TRUE(local.is_const());\n\n ASSERT_EQ(global.arg(0u).data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.arg(0u).data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n\n ASSERT_EQ(global.ret().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.ret().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n\n clazz instance{};\n const argument value{2};\n\n ASSERT_NE(instance.value, value.get());\n ASSERT_EQ(global.invoke(instance, value).cast<int>(), value.get());\n ASSERT_EQ(instance.value, value.get());\n\n ASSERT_NE(instance.value, value.get_mul());\n ASSERT_EQ(local.invoke(entt::meta_handle{context, instance}, entt::meta_any{context, value}).cast<int>(), value.get_mul());\n ASSERT_NE(instance.value, value.get_mul());\n}\n\nTEST_F(MetaContext, MetaCtor) {\n const auto global = entt::resolve<clazz>();\n const auto local = entt::resolve<clazz>(context);\n\n ASSERT_TRUE(global.construct());\n ASSERT_TRUE(local.construct());\n\n ASSERT_TRUE(global.construct(0));\n ASSERT_FALSE(local.construct(0));\n\n ASSERT_FALSE(global.construct('c', 0));\n ASSERT_TRUE(local.construct('c', 0));\n}\n\nTEST_F(MetaContext, MetaConv) {\n argument value{2};\n\n auto global = entt::forward_as_meta(value);\n auto local = entt::forward_as_meta(context, value);\n\n ASSERT_TRUE(global.allow_cast<int>());\n ASSERT_TRUE(local.allow_cast<int>());\n\n ASSERT_EQ(global.cast<int>(), value.get());\n ASSERT_EQ(local.cast<int>(), value.get_mul());\n}\n\nTEST_F(MetaContext, MetaDtor) {\n auto global = entt::resolve<clazz>().construct();\n auto local = entt::resolve<clazz>(context).construct();\n\n ASSERT_EQ(clazz::bucket, bucket_value);\n\n global.reset();\n\n ASSERT_EQ(clazz::bucket, bucket_value);\n\n local.reset();\n\n ASSERT_NE(clazz::bucket, bucket_value);\n}\n\nTEST_F(MetaContext, MetaProp) {\n using namespace entt::literals;\n\n const auto global = entt::resolve<clazz>().prop(\"prop\"_hs);\n const auto local = entt::resolve<clazz>(context).prop(\"prop\"_hs);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_EQ(global.value().type(), entt::resolve<int>());\n ASSERT_EQ(local.value().type(), entt::resolve<int>(context));\n\n ASSERT_EQ(global.value().cast<int>(), prop_value);\n ASSERT_EQ(local.value().cast<int>(), prop_value);\n\n ASSERT_EQ(global.value().type().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.value().type().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n}\n\nTEST_F(MetaContext, MetaTemplate) {\n using namespace entt::literals;\n\n const auto global = entt::resolve(\"template\"_hs);\n const auto local = entt::resolve(context, \"template\"_hs);\n\n ASSERT_TRUE(global.is_template_specialization());\n ASSERT_TRUE(local.is_template_specialization());\n\n ASSERT_EQ(global.template_arity(), 1u);\n ASSERT_EQ(local.template_arity(), 2u);\n\n ASSERT_EQ(global.template_arg(0u), entt::resolve<int>());\n ASSERT_EQ(local.template_arg(0u), entt::resolve<int>(context));\n ASSERT_EQ(local.template_arg(1u), entt::resolve<char>(context));\n\n ASSERT_EQ(global.template_arg(0u).data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.template_arg(0u).data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n}\n\nTEST_F(MetaContext, MetaPointer) {\n using namespace entt::literals;\n\n int value = 42;\n\n const entt::meta_any global{&value};\n const entt::meta_any local{context, &value};\n\n ASSERT_TRUE(global.type().is_pointer());\n ASSERT_TRUE(local.type().is_pointer());\n\n ASSERT_TRUE(global.type().is_pointer_like());\n ASSERT_TRUE(local.type().is_pointer_like());\n\n ASSERT_EQ((*global).type().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ((*local).type().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n}\n\nTEST_F(MetaContext, MetaAssociativeContainer) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, MetaSequenceContainer) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, MetaAny) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, MetaHandle) {\n \/\/ TODO\n}\n\nTEST_F(MetaContext, ForwardAsMeta) {\n using namespace entt::literals;\n\n const auto global = entt::forward_as_meta(42);\n const auto local = entt::forward_as_meta(context, 42);\n\n ASSERT_TRUE(global);\n ASSERT_TRUE(local);\n\n ASSERT_EQ(global.type().data(\"marker\"_hs).get({}).cast<int>(), global_marker);\n ASSERT_EQ(local.type().data(\"marker\"_hs).get({}).cast<int>(), local_marker);\n}\n\nTEST_F(MetaContext, ContextMix) {\n \/\/ TODO\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio> \/\/ for sprintf\n#include <cstring> \/\/ for strcmp\n\n#include <sampgdk.h>\n\n#include \"amxplugin.h\"\n\ntypedef void (*logprintf_t)(const char *fmt, ...);\nstatic logprintf_t logprintf;\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {\n\tSetGameModeText(\"Hello, World!\");\n\n\tAddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);\n\n\tlogprintf(\"------------------------------------------\\n\");\n\tlogprintf(\" HelloWorld gamemode got loaded. \\n\");\n\tlogprintf(\"------------------------------------------\\n\");\n\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {\n\tSendClientMessage(playerid, 0xFFFFFFFF, \"Welcome to the HelloWorld server!\");\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {\n\tSetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\tSetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\tSetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {\n\tif (std::strcmp(cmdtext, \"\/hello\") == 0) {\n\t\tchar name[MAX_PLAYER_NAME];\n\t\tGetPlayerName(playerid, name);\n\t\tchar message[128];\n\t\tstd::sprintf(message, \"Hello, %s!\", name);\n\t\tSendClientMessage(playerid, 0x00FF00FF, message);\n\t}\n\treturn true;\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n\treturn SUPPORTS_VERSION;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppPluginData) {\n\tlogprintf = (logprintf_t)ppPluginData[PLUGIN_DATA_LOGPRINTF];\n\n\tSampGdkInit(ppPluginData);\n\tSampGdkRegisterPlugin(SampGdkGetPluginHandle((void*)Load));\n\n\treturn true;\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload() {\n\treturn;\n}\n<commit_msg>Fix spacing<commit_after>#include <cstdio> \/\/ for sprintf\n#include <cstring> \/\/ for strcmp\n\n#include <sampgdk.h>\n\n#include \"amxplugin.h\"\n\ntypedef void (*logprintf_t)(const char *fmt, ...);\nstatic logprintf_t logprintf;\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {\n\tSetGameModeText(\"Hello, World!\");\n\n\tAddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);\n\n\tlogprintf(\"------------------------------------------\\n\");\n\tlogprintf(\" HelloWorld gamemode got loaded. \\n\");\n\tlogprintf(\"------------------------------------------\\n\");\n\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {\n\tSendClientMessage(playerid, 0xFFFFFFFF, \"Welcome to the HelloWorld server!\");\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {\n\tSetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\tSetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\tSetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n\treturn true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {\n\tif (std::strcmp(cmdtext, \"\/hello\") == 0) {\n\t\tchar name[MAX_PLAYER_NAME];\n\t\tGetPlayerName(playerid, name);\n\t\tchar message[128];\n\t\tstd::sprintf(message, \"Hello, %s!\", name);\n\t\tSendClientMessage(playerid, 0x00FF00FF, message);\n\t}\n\treturn true;\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n\treturn SUPPORTS_VERSION;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppPluginData) {\n\tlogprintf = (logprintf_t)ppPluginData[PLUGIN_DATA_LOGPRINTF];\n\n\tSampGdkInit(ppPluginData);\n\tSampGdkRegisterPlugin(SampGdkGetPluginHandle((void*)Load));\n\n\treturn true;\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload() {\n\treturn;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Rapicorn\n * Copyright (C) 2005 Tim Janik\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 * A copy of the GNU Lesser General Public License should ship along\n * with this library; if not, see http:\/\/www.gnu.org\/copyleft\/.\n *\/\n#include \"slider.hh\"\n#include \"tableimpl.hh\"\n#include \"painter.hh\"\n#include \"factory.hh\"\n#include \"root.hh\"\n\nnamespace Rapicorn {\n\nSliderArea::SliderArea() :\n sig_slider_changed (*this, &SliderArea::slider_changed)\n{}\n\nvoid\nSliderArea::slider_changed()\n{}\n\nbool\nSliderArea::move (int distance)\n{\n Adjustment *adj = adjustment();\n double pi = adj->page_increment();\n double si = adj->step_increment();\n if (flipped())\n {\n pi = -pi;\n si = -si;\n }\n switch (adj ? distance : 0)\n {\n case +2:\n adj->value (adj->value() + pi);\n return true;\n case +1:\n adj->value (adj->value() + si);\n return true;\n case -1:\n adj->value (adj->value() - si);\n return true;\n case -2:\n adj->value (adj->value() - pi);\n return true;\n default:\n return false;\n }\n}\n\nconst CommandList&\nSliderArea::list_commands ()\n{\n static Command *commands[] = {\n MakeNamedCommand (SliderArea, \"increment\", _(\"Increment slider\"), move, +1),\n MakeNamedCommand (SliderArea, \"decrement\", _(\"Decrement slider\"), move, -1),\n MakeNamedCommand (SliderArea, \"page-increment\", _(\"Large slider increment\"), move, +2),\n MakeNamedCommand (SliderArea, \"page-decrement\", _(\"Large slider decrement\"), move, -2),\n };\n static const CommandList command_list (commands, Container::list_commands());\n return command_list;\n}\n\nconst PropertyList&\nSliderArea::list_properties()\n{\n static Property *properties[] = {\n MakeProperty (SliderArea, flipped, _(\"Flipped\"), _(\"Invert (flip) display of the adjustment value\"), \"rw\"),\n MakeProperty (SliderArea, adjustment_source, _(\"Adjustment Source\"), _(\"Type of source to retrive an adjustment from\"), \"rw\"),\n };\n static const PropertyList property_list (properties, Container::list_properties());\n return property_list;\n}\n\nclass SliderAreaImpl : public virtual SliderArea, public virtual TableImpl {\n Adjustment *m_adjustment;\n AdjustmentSourceType m_adjustment_source;\n bool m_flip;\n void\n unset_adjustment()\n {\n m_adjustment->sig_value_changed -= slot (sig_slider_changed);\n m_adjustment->sig_range_changed -= slot (sig_slider_changed);\n m_adjustment->unref();\n m_adjustment = NULL;\n }\n virtual const PropertyList& list_properties() { return SliderArea::list_properties(); }\nprotected:\n virtual AdjustmentSourceType\n adjustment_source () const\n {\n return m_adjustment_source;\n }\n virtual void\n adjustment_source (AdjustmentSourceType adj_source)\n {\n m_adjustment_source = adj_source;\n }\n virtual void\n hierarchy_changed (Item *old_toplevel)\n {\n this->TableImpl::hierarchy_changed (old_toplevel);\n if (anchored() && m_adjustment_source != ADJUSTMENT_SOURCE_NONE)\n {\n Adjustment *adj = NULL;\n find_adjustments (m_adjustment_source, &adj);\n if (!adj)\n {\n EnumTypeAdjustmentSourceType ast;\n throw Exception (\"SliderArea failed to get Adjustment (\",\n ast.string (m_adjustment_source),\n \") from ancestors: \", name());\n }\n adjustment (*adj);\n }\n }\n virtual bool\n flipped () const\n {\n return m_flip;\n }\n virtual void\n flipped (bool flip)\n {\n if (m_flip != flip)\n {\n m_flip = flip;\n changed();\n }\n }\n virtual ~SliderAreaImpl()\n {\n unset_adjustment();\n }\npublic:\n SliderAreaImpl() :\n m_adjustment (NULL),\n m_adjustment_source (ADJUSTMENT_SOURCE_NONE),\n m_flip (false)\n {\n Adjustment *adj = Adjustment::create();\n adjustment (*adj);\n adj->unref();\n }\n virtual void\n adjustment (Adjustment &adjustment)\n {\n adjustment.ref();\n if (m_adjustment)\n unset_adjustment();\n m_adjustment = &adjustment;\n m_adjustment->sig_value_changed += slot (sig_slider_changed);\n m_adjustment->sig_range_changed += slot (sig_slider_changed);\n changed();\n }\n virtual Adjustment*\n adjustment () const\n {\n return m_adjustment;\n }\n virtual void\n control (const String &command_name,\n const String &arg)\n {\n }\n};\nstatic const ItemFactory<SliderAreaImpl> slider_area_factory (\"Rapicorn::Factory::SliderArea\");\n\nclass SliderSkidImpl;\n\nclass SliderTroughImpl : public virtual EventHandler, public virtual SingleContainerImpl {\n bool\n flipped()\n {\n SliderArea *slider_area = parent_interface<SliderArea*>();\n return slider_area ? slider_area->flipped() : false;\n }\npublic:\n SliderTroughImpl()\n {}\n ~SliderTroughImpl()\n {}\nprotected:\n virtual void\n hierarchy_changed (Item *old_toplevel)\n {\n SliderArea *slider_area = parent_interface<SliderArea*>();\n if (slider_area)\n slider_area->sig_slider_changed -= slot (*this, &SliderTroughImpl::reallocate_child);\n this->SingleContainerImpl::hierarchy_changed (old_toplevel);\n if (anchored())\n {\n if (!slider_area)\n throw Exception (\"SliderTrough without SliderArea ancestor: \", name());\n slider_area->sig_slider_changed += slot (*this, &SliderTroughImpl::reallocate_child);\n }\n }\n Adjustment*\n adjustment () const\n {\n SliderArea *slider_area = parent_interface<SliderArea*>();\n return slider_area ? slider_area->adjustment() : NULL;\n }\n double\n nvalue()\n {\n Adjustment &adj = *adjustment();\n return flipped() ? adj.flipped_nvalue() : adj.nvalue();\n }\n void\n size_request (Requisition &requisition)\n {\n if (has_allocatable_child())\n {\n Item &child = get_child();\n requisition = child.size_request ();\n \/* we confine spreading to within the trough, so don't propagate hspread\/vspread here *\/\n }\n }\n virtual void\n size_allocate (Allocation area)\n {\n allocation (area);\n reallocate_child();\n }\n void\n reallocate_child ()\n {\n Allocation area = allocation();\n if (!has_allocatable_child())\n return;\n Item &child = get_child();\n Requisition rq = child.size_request();\n \/* expand\/scale child *\/\n if (area.width > rq.width && !child.hspread())\n {\n if (child.hexpand())\n {\n Adjustment &adj = *adjustment();\n double cwidth = round (adj.abs_length() * area.width);\n rq.width = MAX (cwidth, rq.width);\n }\n area.x += round (nvalue() * (area.width - rq.width));\n area.width = round (rq.width);\n }\n if (area.height > rq.height && !child.vspread())\n {\n if (child.vexpand())\n {\n Adjustment &adj = *adjustment();\n double cheight = round (adj.abs_length() * area.height);\n rq.height = MAX (cheight, rq.height);\n }\n area.y += round ((1.0 - nvalue()) * (area.height - rq.height));\n area.height = round (rq.height);\n }\n child.set_allocation (area);\n }\n friend class SliderSkidImpl;\n virtual void\n reset (ResetMode mode = RESET_ALL)\n {}\n virtual bool\n handle_event (const Event &event)\n {\n bool handled = false;\n switch (event.type)\n {\n case BUTTON_PRESS:\n case BUTTON_2PRESS:\n case BUTTON_3PRESS:\n case BUTTON_RELEASE:\n case BUTTON_2RELEASE:\n case BUTTON_3RELEASE:\n case BUTTON_CANCELED:\n \/* forward button events to allow slider warps *\/\n if (has_visible_child())\n handled = get_child().process_event (event);\n break;\n case SCROLL_UP:\n case SCROLL_RIGHT:\n exec_command (\"increment\");\n break;\n case SCROLL_DOWN:\n case SCROLL_LEFT:\n exec_command (\"decrement\");\n break;\n default: break;\n }\n return handled;\n }\n};\nstatic const ItemFactory<SliderTroughImpl> slider_trough_factory (\"Rapicorn::Factory::SliderTrough\");\n\nclass SliderSkidImpl : public virtual EventHandler, public virtual SingleContainerImpl {\n uint m_button;\n double m_coffset;\n bool m_vertical_skid;\n bool\n flipped()\n {\n SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();\n return trough.flipped() ^ m_vertical_skid;\n }\n bool\n vertical_skid () const\n {\n return m_vertical_skid;\n }\n void\n vertical_skid (bool vs)\n {\n if (m_vertical_skid != vs)\n {\n m_vertical_skid = vs;\n changed();\n }\n }\npublic:\n SliderSkidImpl() :\n m_button (0),\n m_coffset (0),\n m_vertical_skid (false)\n {}\n ~SliderSkidImpl()\n {}\nprotected:\n virtual void\n size_request (Requisition &requisition)\n {\n bool chspread = false, cvspread = false;\n if (has_children())\n {\n Item &child = get_child();\n if (child.allocatable())\n {\n requisition = child.size_request ();\n chspread = child.hspread();\n cvspread = child.vspread();\n }\n }\n set_flag (HSPREAD_CONTAINER, chspread);\n set_flag (VSPREAD_CONTAINER, cvspread);\n }\n#if 0\n double\n nvalue()\n {\n SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();\n Adjustment &adj = *trough.adjustment();\n return flipped() ? adj.flipped_nvalue() : adj.nvalue();\n }\n#endif\n virtual void\n reset (ResetMode mode = RESET_ALL)\n {\n m_button = 0;\n m_coffset = 0;\n }\n virtual bool\n handle_event (const Event &event)\n {\n bool handled = false, proper_release = false;\n SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();\n Adjustment &adj = *trough.adjustment();\n switch (event.type)\n {\n const EventButton *bevent;\n case MOUSE_ENTER:\n this->prelight (true);\n break;\n case MOUSE_LEAVE:\n this->prelight (false);\n break;\n case BUTTON_PRESS:\n case BUTTON_2PRESS:\n case BUTTON_3PRESS:\n bevent = dynamic_cast<const EventButton*> (&event);\n if (!m_button and (bevent->button == 1 or bevent->button == 2))\n {\n m_button = bevent->button;\n get_root()->add_grab (this, true);\n handled = true;\n m_coffset = 0;\n double ep = vertical_skid() ? event.y : event.x;\n double cp = vertical_skid() ? ep - allocation().y : ep - allocation().x;\n double clength = vertical_skid() ? allocation().height : allocation().width;\n if (cp >= 0 && cp < clength)\n m_coffset = cp \/ clength;\n else\n {\n m_coffset = 0.5;\n \/* confine offset to not slip the skip off trough boundaries *\/\n cp = ep - clength * m_coffset;\n const Allocation &ta = trough.allocation();\n double start_slip = (vertical_skid() ? ta.y : ta.x) - cp;\n double tlength = vertical_skid() ? ta.y + ta.height : ta.x + ta.width;\n double end_slip = cp + clength - tlength;\n \/* adjust skid position *\/\n cp += MAX (0, start_slip);\n cp -= MAX (0, end_slip);\n \/* recalculate offset *\/\n m_coffset = (ep - cp) \/ clength;\n }\n }\n break;\n case MOUSE_MOVE:\n if (m_button)\n {\n double ep = vertical_skid() ? event.y : event.x;\n const Allocation &ta = trough.allocation();\n double tp = vertical_skid() ? ta.y : ta.x;\n double pos = ep - tp;\n double tlength = vertical_skid() ? ta.height : ta.width;\n double clength = vertical_skid() ? allocation().height : allocation().width;\n tlength -= clength;\n pos -= m_coffset * clength;\n if (tlength > 0)\n pos \/= tlength;\n pos = CLAMP (pos, 0, 1);\n if (flipped())\n adj.flipped_nvalue (pos);\n else\n adj.nvalue (pos);\n }\n break;\n case BUTTON_RELEASE:\n case BUTTON_2RELEASE:\n case BUTTON_3RELEASE:\n proper_release = true;\n case BUTTON_CANCELED:\n bevent = dynamic_cast<const EventButton*> (&event);\n if (m_button == bevent->button)\n {\n get_root()->remove_grab (this);\n m_button = 0;\n m_coffset = 0;\n handled = true;\n }\n break;\n default: break;\n }\n return handled;\n }\nprivate:\n virtual const PropertyList&\n list_properties() \/\/ escape check-list_properties ';'\n {\n static Property *properties[] = {\n MakeProperty (SliderSkidImpl, vertical_skid, _(\"Vertical Skid\"), _(\"Adjust behaviour to vertical skid movement\"), \"rw\"),\n };\n static const PropertyList property_list (properties, SingleContainerImpl::list_properties());\n return property_list;\n }\n};\nstatic const ItemFactory<SliderSkidImpl> slider_skid_factory (\"Rapicorn::Factory::SliderSkid\");\n\n} \/\/ Rapicorn\n<commit_msg>slider.cc: fixed scroll wheel handling to decrement for left\/up, otherwise increment<commit_after>\/* Rapicorn\n * Copyright (C) 2005 Tim Janik\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 * A copy of the GNU Lesser General Public License should ship along\n * with this library; if not, see http:\/\/www.gnu.org\/copyleft\/.\n *\/\n#include \"slider.hh\"\n#include \"tableimpl.hh\"\n#include \"painter.hh\"\n#include \"factory.hh\"\n#include \"root.hh\"\n\nnamespace Rapicorn {\n\nSliderArea::SliderArea() :\n sig_slider_changed (*this, &SliderArea::slider_changed)\n{}\n\nvoid\nSliderArea::slider_changed()\n{}\n\nbool\nSliderArea::move (int distance)\n{\n Adjustment *adj = adjustment();\n double pi = adj->page_increment();\n double si = adj->step_increment();\n if (flipped())\n {\n pi = -pi;\n si = -si;\n }\n switch (adj ? distance : 0)\n {\n case +2:\n adj->value (adj->value() + pi);\n return true;\n case +1:\n adj->value (adj->value() + si);\n return true;\n case -1:\n adj->value (adj->value() - si);\n return true;\n case -2:\n adj->value (adj->value() - pi);\n return true;\n default:\n return false;\n }\n}\n\nconst CommandList&\nSliderArea::list_commands ()\n{\n static Command *commands[] = {\n MakeNamedCommand (SliderArea, \"increment\", _(\"Increment slider\"), move, +1),\n MakeNamedCommand (SliderArea, \"decrement\", _(\"Decrement slider\"), move, -1),\n MakeNamedCommand (SliderArea, \"page-increment\", _(\"Large slider increment\"), move, +2),\n MakeNamedCommand (SliderArea, \"page-decrement\", _(\"Large slider decrement\"), move, -2),\n };\n static const CommandList command_list (commands, Container::list_commands());\n return command_list;\n}\n\nconst PropertyList&\nSliderArea::list_properties()\n{\n static Property *properties[] = {\n MakeProperty (SliderArea, flipped, _(\"Flipped\"), _(\"Invert (flip) display of the adjustment value\"), \"rw\"),\n MakeProperty (SliderArea, adjustment_source, _(\"Adjustment Source\"), _(\"Type of source to retrive an adjustment from\"), \"rw\"),\n };\n static const PropertyList property_list (properties, Container::list_properties());\n return property_list;\n}\n\nclass SliderAreaImpl : public virtual SliderArea, public virtual TableImpl {\n Adjustment *m_adjustment;\n AdjustmentSourceType m_adjustment_source;\n bool m_flip;\n void\n unset_adjustment()\n {\n m_adjustment->sig_value_changed -= slot (sig_slider_changed);\n m_adjustment->sig_range_changed -= slot (sig_slider_changed);\n m_adjustment->unref();\n m_adjustment = NULL;\n }\n virtual const PropertyList& list_properties() { return SliderArea::list_properties(); }\nprotected:\n virtual AdjustmentSourceType\n adjustment_source () const\n {\n return m_adjustment_source;\n }\n virtual void\n adjustment_source (AdjustmentSourceType adj_source)\n {\n m_adjustment_source = adj_source;\n }\n virtual void\n hierarchy_changed (Item *old_toplevel)\n {\n this->TableImpl::hierarchy_changed (old_toplevel);\n if (anchored() && m_adjustment_source != ADJUSTMENT_SOURCE_NONE)\n {\n Adjustment *adj = NULL;\n find_adjustments (m_adjustment_source, &adj);\n if (!adj)\n {\n EnumTypeAdjustmentSourceType ast;\n throw Exception (\"SliderArea failed to get Adjustment (\",\n ast.string (m_adjustment_source),\n \") from ancestors: \", name());\n }\n adjustment (*adj);\n }\n }\n virtual bool\n flipped () const\n {\n return m_flip;\n }\n virtual void\n flipped (bool flip)\n {\n if (m_flip != flip)\n {\n m_flip = flip;\n changed();\n }\n }\n virtual ~SliderAreaImpl()\n {\n unset_adjustment();\n }\npublic:\n SliderAreaImpl() :\n m_adjustment (NULL),\n m_adjustment_source (ADJUSTMENT_SOURCE_NONE),\n m_flip (false)\n {\n Adjustment *adj = Adjustment::create();\n adjustment (*adj);\n adj->unref();\n }\n virtual void\n adjustment (Adjustment &adjustment)\n {\n adjustment.ref();\n if (m_adjustment)\n unset_adjustment();\n m_adjustment = &adjustment;\n m_adjustment->sig_value_changed += slot (sig_slider_changed);\n m_adjustment->sig_range_changed += slot (sig_slider_changed);\n changed();\n }\n virtual Adjustment*\n adjustment () const\n {\n return m_adjustment;\n }\n virtual void\n control (const String &command_name,\n const String &arg)\n {\n }\n};\nstatic const ItemFactory<SliderAreaImpl> slider_area_factory (\"Rapicorn::Factory::SliderArea\");\n\nclass SliderSkidImpl;\n\nclass SliderTroughImpl : public virtual EventHandler, public virtual SingleContainerImpl {\n bool\n flipped()\n {\n SliderArea *slider_area = parent_interface<SliderArea*>();\n return slider_area ? slider_area->flipped() : false;\n }\npublic:\n SliderTroughImpl()\n {}\n ~SliderTroughImpl()\n {}\nprotected:\n virtual void\n hierarchy_changed (Item *old_toplevel)\n {\n SliderArea *slider_area = parent_interface<SliderArea*>();\n if (slider_area)\n slider_area->sig_slider_changed -= slot (*this, &SliderTroughImpl::reallocate_child);\n this->SingleContainerImpl::hierarchy_changed (old_toplevel);\n if (anchored())\n {\n if (!slider_area)\n throw Exception (\"SliderTrough without SliderArea ancestor: \", name());\n slider_area->sig_slider_changed += slot (*this, &SliderTroughImpl::reallocate_child);\n }\n }\n Adjustment*\n adjustment () const\n {\n SliderArea *slider_area = parent_interface<SliderArea*>();\n return slider_area ? slider_area->adjustment() : NULL;\n }\n double\n nvalue()\n {\n Adjustment &adj = *adjustment();\n return flipped() ? adj.flipped_nvalue() : adj.nvalue();\n }\n void\n size_request (Requisition &requisition)\n {\n if (has_allocatable_child())\n {\n Item &child = get_child();\n requisition = child.size_request ();\n \/* we confine spreading to within the trough, so don't propagate hspread\/vspread here *\/\n }\n }\n virtual void\n size_allocate (Allocation area)\n {\n allocation (area);\n reallocate_child();\n }\n void\n reallocate_child ()\n {\n Allocation area = allocation();\n if (!has_allocatable_child())\n return;\n Item &child = get_child();\n Requisition rq = child.size_request();\n \/* expand\/scale child *\/\n if (area.width > rq.width && !child.hspread())\n {\n if (child.hexpand())\n {\n Adjustment &adj = *adjustment();\n double cwidth = round (adj.abs_length() * area.width);\n rq.width = MAX (cwidth, rq.width);\n }\n area.x += round (nvalue() * (area.width - rq.width));\n area.width = round (rq.width);\n }\n if (area.height > rq.height && !child.vspread())\n {\n if (child.vexpand())\n {\n Adjustment &adj = *adjustment();\n double cheight = round (adj.abs_length() * area.height);\n rq.height = MAX (cheight, rq.height);\n }\n area.y += round ((1.0 - nvalue()) * (area.height - rq.height));\n area.height = round (rq.height);\n }\n child.set_allocation (area);\n }\n friend class SliderSkidImpl;\n virtual void\n reset (ResetMode mode = RESET_ALL)\n {}\n virtual bool\n handle_event (const Event &event)\n {\n bool handled = false;\n switch (event.type)\n {\n case BUTTON_PRESS:\n case BUTTON_2PRESS:\n case BUTTON_3PRESS:\n case BUTTON_RELEASE:\n case BUTTON_2RELEASE:\n case BUTTON_3RELEASE:\n case BUTTON_CANCELED:\n \/* forward button events to allow slider warps *\/\n if (has_visible_child())\n handled = get_child().process_event (event);\n break;\n case SCROLL_UP:\n case SCROLL_LEFT:\n exec_command (\"decrement\");\n break;\n case SCROLL_DOWN:\n case SCROLL_RIGHT:\n exec_command (\"increment\");\n break;\n default: break;\n }\n return handled;\n }\n};\nstatic const ItemFactory<SliderTroughImpl> slider_trough_factory (\"Rapicorn::Factory::SliderTrough\");\n\nclass SliderSkidImpl : public virtual EventHandler, public virtual SingleContainerImpl {\n uint m_button;\n double m_coffset;\n bool m_vertical_skid;\n bool\n flipped()\n {\n SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();\n return trough.flipped() ^ m_vertical_skid;\n }\n bool\n vertical_skid () const\n {\n return m_vertical_skid;\n }\n void\n vertical_skid (bool vs)\n {\n if (m_vertical_skid != vs)\n {\n m_vertical_skid = vs;\n changed();\n }\n }\npublic:\n SliderSkidImpl() :\n m_button (0),\n m_coffset (0),\n m_vertical_skid (false)\n {}\n ~SliderSkidImpl()\n {}\nprotected:\n virtual void\n size_request (Requisition &requisition)\n {\n bool chspread = false, cvspread = false;\n if (has_children())\n {\n Item &child = get_child();\n if (child.allocatable())\n {\n requisition = child.size_request ();\n chspread = child.hspread();\n cvspread = child.vspread();\n }\n }\n set_flag (HSPREAD_CONTAINER, chspread);\n set_flag (VSPREAD_CONTAINER, cvspread);\n }\n#if 0\n double\n nvalue()\n {\n SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();\n Adjustment &adj = *trough.adjustment();\n return flipped() ? adj.flipped_nvalue() : adj.nvalue();\n }\n#endif\n virtual void\n reset (ResetMode mode = RESET_ALL)\n {\n m_button = 0;\n m_coffset = 0;\n }\n virtual bool\n handle_event (const Event &event)\n {\n bool handled = false, proper_release = false;\n SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();\n Adjustment &adj = *trough.adjustment();\n switch (event.type)\n {\n const EventButton *bevent;\n case MOUSE_ENTER:\n this->prelight (true);\n break;\n case MOUSE_LEAVE:\n this->prelight (false);\n break;\n case BUTTON_PRESS:\n case BUTTON_2PRESS:\n case BUTTON_3PRESS:\n bevent = dynamic_cast<const EventButton*> (&event);\n if (!m_button and (bevent->button == 1 or bevent->button == 2))\n {\n m_button = bevent->button;\n get_root()->add_grab (this, true);\n handled = true;\n m_coffset = 0;\n double ep = vertical_skid() ? event.y : event.x;\n double cp = vertical_skid() ? ep - allocation().y : ep - allocation().x;\n double clength = vertical_skid() ? allocation().height : allocation().width;\n if (cp >= 0 && cp < clength)\n m_coffset = cp \/ clength;\n else\n {\n m_coffset = 0.5;\n \/* confine offset to not slip the skip off trough boundaries *\/\n cp = ep - clength * m_coffset;\n const Allocation &ta = trough.allocation();\n double start_slip = (vertical_skid() ? ta.y : ta.x) - cp;\n double tlength = vertical_skid() ? ta.y + ta.height : ta.x + ta.width;\n double end_slip = cp + clength - tlength;\n \/* adjust skid position *\/\n cp += MAX (0, start_slip);\n cp -= MAX (0, end_slip);\n \/* recalculate offset *\/\n m_coffset = (ep - cp) \/ clength;\n }\n }\n break;\n case MOUSE_MOVE:\n if (m_button)\n {\n double ep = vertical_skid() ? event.y : event.x;\n const Allocation &ta = trough.allocation();\n double tp = vertical_skid() ? ta.y : ta.x;\n double pos = ep - tp;\n double tlength = vertical_skid() ? ta.height : ta.width;\n double clength = vertical_skid() ? allocation().height : allocation().width;\n tlength -= clength;\n pos -= m_coffset * clength;\n if (tlength > 0)\n pos \/= tlength;\n pos = CLAMP (pos, 0, 1);\n if (flipped())\n adj.flipped_nvalue (pos);\n else\n adj.nvalue (pos);\n }\n break;\n case BUTTON_RELEASE:\n case BUTTON_2RELEASE:\n case BUTTON_3RELEASE:\n proper_release = true;\n case BUTTON_CANCELED:\n bevent = dynamic_cast<const EventButton*> (&event);\n if (m_button == bevent->button)\n {\n get_root()->remove_grab (this);\n m_button = 0;\n m_coffset = 0;\n handled = true;\n }\n break;\n default: break;\n }\n return handled;\n }\nprivate:\n virtual const PropertyList&\n list_properties() \/\/ escape check-list_properties ';'\n {\n static Property *properties[] = {\n MakeProperty (SliderSkidImpl, vertical_skid, _(\"Vertical Skid\"), _(\"Adjust behaviour to vertical skid movement\"), \"rw\"),\n };\n static const PropertyList property_list (properties, SingleContainerImpl::list_properties());\n return property_list;\n }\n};\nstatic const ItemFactory<SliderSkidImpl> slider_skid_factory (\"Rapicorn::Factory::SliderSkid\");\n\n} \/\/ Rapicorn\n<|endoftext|>"} {"text":"<commit_before>\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ http:\/\/code.google.com\/p\/protobuf\/\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:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. 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\/\/ Author: kenton@google.com (Kenton Varda)\n\/\/ Based on original Protocol Buffers design by\n\/\/ Sanjay Ghemawat, Jeff Dean, and others.\n\n\/\/ Copyright (c) 2008-2014, Dave Benson and the protobuf-c authors.\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\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\/\/ Modified to implement C code by Dave Benson.\n\n#include <protoc-c\/c_file.h>\n#include <protoc-c\/c_enum.h>\n#include <protoc-c\/c_service.h>\n#include <protoc-c\/c_extension.h>\n#include <protoc-c\/c_helpers.h>\n#include <protoc-c\/c_message.h>\n#include <google\/protobuf\/io\/printer.h>\n#include <google\/protobuf\/descriptor.pb.h>\n\n#include \"protobuf-c.h\"\n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace c {\n\n\/\/ ===================================================================\n\nFileGenerator::FileGenerator(const FileDescriptor* file,\n const string& dllexport_decl)\n : file_(file),\n message_generators_(\n new scoped_ptr<MessageGenerator>[file->message_type_count()]),\n enum_generators_(\n new scoped_ptr<EnumGenerator>[file->enum_type_count()]),\n service_generators_(\n new scoped_ptr<ServiceGenerator>[file->service_count()]),\n extension_generators_(\n new scoped_ptr<ExtensionGenerator>[file->extension_count()]) {\n\n for (int i = 0; i < file->message_type_count(); i++) {\n message_generators_[i].reset(\n new MessageGenerator(file->message_type(i), dllexport_decl));\n }\n\n for (int i = 0; i < file->enum_type_count(); i++) {\n enum_generators_[i].reset(\n new EnumGenerator(file->enum_type(i), dllexport_decl));\n }\n\n for (int i = 0; i < file->service_count(); i++) {\n service_generators_[i].reset(\n new ServiceGenerator(file->service(i), dllexport_decl));\n }\n\n for (int i = 0; i < file->extension_count(); i++) {\n extension_generators_[i].reset(\n new ExtensionGenerator(file->extension(i), dllexport_decl));\n }\n\n SplitStringUsing(file_->package(), \".\", &package_parts_);\n}\n\nFileGenerator::~FileGenerator() {}\n\nvoid FileGenerator::GenerateHeader(io::Printer* printer) {\n string filename_identifier = FilenameIdentifier(file_->name());\n\n static const int min_header_version = 1000000;\n\n \/\/ Generate top of header.\n printer->Print(\n \"\/* Generated by the protocol buffer compiler. DO NOT EDIT! *\/\\n\"\n \"\/* Generated from: $filename$ *\/\\n\"\n \"\\n\"\n \"#ifndef PROTOBUF_C_$filename_identifier$__INCLUDED\\n\"\n \"#define PROTOBUF_C_$filename_identifier$__INCLUDED\\n\"\n \"\\n\"\n \"#include <protobuf-c\/protobuf-c.h>\\n\"\n \"\\n\"\n \"PROTOBUF_C_BEGIN_DECLS\\n\"\n \"\\n\",\n \"filename\", file_->name(),\n \"filename_identifier\", filename_identifier);\n\n \/\/ Verify the protobuf-c library header version is compatible with the\n \/\/ protoc-c version before going any further.\n printer->Print(\n \"#if PROTOBUF_C_VERSION_NUMBER < $min_header_version$\\n\"\n \"# error This file was generated by a newer version of protoc-c which is \"\n \"incompatible with your libprotobuf-c headers. Please update your headers.\\n\"\n \"#elif $protoc_version$ < PROTOBUF_C_MIN_COMPILER_VERSION\\n\"\n \"# error This file was generated by an older version of protoc-c which is \"\n \"incompatible with your libprotobuf-c headers. Please regenerate this file \"\n \"with a newer version of protoc-c.\\n\"\n \"#endif\\n\"\n \"\\n\",\n \"min_header_version\", SimpleItoa(min_header_version),\n \"protoc_version\", SimpleItoa(PROTOBUF_C_VERSION_NUMBER));\n\n for (int i = 0; i < file_->dependency_count(); i++) {\n printer->Print(\n \"#include \\\"$dependency$.pb-c.h\\\"\\n\",\n \"dependency\", StripProto(file_->dependency(i)->name()));\n }\n\n printer->Print(\"\\n\");\n\n \/\/ Generate forward declarations of classes.\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateStructTypedef(printer);\n }\n\n printer->Print(\"\\n\");\n\n \/\/ Generate enum definitions.\n printer->Print(\"\\n\/* --- enums --- *\/\\n\\n\");\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateEnumDefinitions(printer);\n }\n for (int i = 0; i < file_->enum_type_count(); i++) {\n enum_generators_[i]->GenerateDefinition(printer);\n }\n\n \/\/ Generate class definitions.\n printer->Print(\"\\n\/* --- messages --- *\/\\n\\n\");\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateStructDefinition(printer);\n }\n\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateHelperFunctionDeclarations(printer, false);\n }\n\n printer->Print(\"\/* --- per-message closures --- *\/\\n\\n\");\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateClosureTypedef(printer);\n }\n\n \/\/ Generate service definitions.\n printer->Print(\"\\n\/* --- services --- *\/\\n\\n\");\n for (int i = 0; i < file_->service_count(); i++) {\n service_generators_[i]->GenerateMainHFile(printer);\n }\n\n \/\/ Declare extension identifiers.\n for (int i = 0; i < file_->extension_count(); i++) {\n extension_generators_[i]->GenerateDeclaration(printer);\n }\n\n printer->Print(\"\\n\/* --- descriptors --- *\/\\n\\n\");\n for (int i = 0; i < file_->enum_type_count(); i++) {\n enum_generators_[i]->GenerateDescriptorDeclarations(printer);\n }\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateDescriptorDeclarations(printer);\n }\n for (int i = 0; i < file_->service_count(); i++) {\n service_generators_[i]->GenerateDescriptorDeclarations(printer);\n }\n\n printer->Print(\n \"\\n\"\n \"PROTOBUF_C_END_DECLS\\n\"\n \"\\n\\n#endif \/* PROTOBUF_$filename_identifier$__INCLUDED *\/\\n\",\n \"filename_identifier\", filename_identifier);\n}\n\nvoid FileGenerator::GenerateSource(io::Printer* printer) {\n printer->Print(\n \"\/* Generated by the protocol buffer compiler. DO NOT EDIT! *\/\\n\"\n \"\/* Generated from: $filename$ *\/\\n\"\n \"\\n\"\n \"\/* Do not generate deprecated warnings for self *\/\\n\"\n \"#ifndef PROTOBUF_C_NO_DEPRECATED\\n\"\n \"#define PROTOBUF_C_NO_DEPRECATED\\n\"\n \"#endif\\n\"\n \"\\n\"\n \"#include \\\"$basename$.pb-c.h\\\"\\n\",\n \"filename\", file_->name(),\n \"basename\", StripProto(file_->name()));\n\n#if 0\n \/\/ For each dependency, write a prototype for that dependency's\n \/\/ BuildDescriptors() function. We don't expose these in the header because\n \/\/ they are internal implementation details, and since this is generated code\n \/\/ we don't have the usual risks involved with declaring external functions\n \/\/ within a .cc file.\n for (int i = 0; i < file_->dependency_count(); i++) {\n const FileDescriptor* dependency = file_->dependency(i);\n \/\/ Open the dependency's namespace.\n vector<string> dependency_package_parts;\n SplitStringUsing(dependency->package(), \".\", &dependency_package_parts);\n \/\/ Declare its BuildDescriptors() function.\n printer->Print(\n \"void $function$();\",\n \"function\", GlobalBuildDescriptorsName(dependency->name()));\n \/\/ Close the namespace.\n for (int i = 0; i < dependency_package_parts.size(); i++) {\n printer->Print(\" }\");\n }\n printer->Print(\"\\n\");\n }\n#endif\n\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateHelperFunctionDefinitions(printer, false);\n }\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateMessageDescriptor(printer);\n }\n for (int i = 0; i < file_->enum_type_count(); i++) {\n enum_generators_[i]->GenerateEnumDescriptor(printer);\n }\n for (int i = 0; i < file_->service_count(); i++) {\n service_generators_[i]->GenerateCFile(printer);\n }\n\n}\n\n} \/\/ namespace c\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<commit_msg>cosmetics<commit_after>\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ http:\/\/code.google.com\/p\/protobuf\/\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:\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 disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. 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\/\/ Author: kenton@google.com (Kenton Varda)\n\/\/ Based on original Protocol Buffers design by\n\/\/ Sanjay Ghemawat, Jeff Dean, and others.\n\n\/\/ Copyright (c) 2008-2014, Dave Benson and the protobuf-c authors.\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\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\/\/ Modified to implement C code by Dave Benson.\n\n#include <protoc-c\/c_file.h>\n#include <protoc-c\/c_enum.h>\n#include <protoc-c\/c_service.h>\n#include <protoc-c\/c_extension.h>\n#include <protoc-c\/c_helpers.h>\n#include <protoc-c\/c_message.h>\n#include <google\/protobuf\/io\/printer.h>\n#include <google\/protobuf\/descriptor.pb.h>\n\n#include \"protobuf-c.h\"\n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace c {\n\n\/\/ ===================================================================\n\nFileGenerator::FileGenerator(const FileDescriptor* file,\n const string& dllexport_decl)\n : file_(file),\n message_generators_(\n new scoped_ptr<MessageGenerator>[file->message_type_count()]),\n enum_generators_(\n new scoped_ptr<EnumGenerator>[file->enum_type_count()]),\n service_generators_(\n new scoped_ptr<ServiceGenerator>[file->service_count()]),\n extension_generators_(\n new scoped_ptr<ExtensionGenerator>[file->extension_count()]) {\n\n for (int i = 0; i < file->message_type_count(); i++) {\n message_generators_[i].reset(\n new MessageGenerator(file->message_type(i), dllexport_decl));\n }\n\n for (int i = 0; i < file->enum_type_count(); i++) {\n enum_generators_[i].reset(\n new EnumGenerator(file->enum_type(i), dllexport_decl));\n }\n\n for (int i = 0; i < file->service_count(); i++) {\n service_generators_[i].reset(\n new ServiceGenerator(file->service(i), dllexport_decl));\n }\n\n for (int i = 0; i < file->extension_count(); i++) {\n extension_generators_[i].reset(\n new ExtensionGenerator(file->extension(i), dllexport_decl));\n }\n\n SplitStringUsing(file_->package(), \".\", &package_parts_);\n}\n\nFileGenerator::~FileGenerator() {}\n\nvoid FileGenerator::GenerateHeader(io::Printer* printer) {\n string filename_identifier = FilenameIdentifier(file_->name());\n\n static const int min_header_version = 1000000;\n\n \/\/ Generate top of header.\n printer->Print(\n \"\/* Generated by the protocol buffer compiler. DO NOT EDIT! *\/\\n\"\n \"\/* Generated from: $filename$ *\/\\n\"\n \"\\n\"\n \"#ifndef PROTOBUF_C_$filename_identifier$__INCLUDED\\n\"\n \"#define PROTOBUF_C_$filename_identifier$__INCLUDED\\n\"\n \"\\n\"\n \"#include <protobuf-c\/protobuf-c.h>\\n\"\n \"\\n\"\n \"PROTOBUF_C_BEGIN_DECLS\\n\"\n \"\\n\",\n \"filename\", file_->name(),\n \"filename_identifier\", filename_identifier);\n\n \/\/ Verify the protobuf-c library header version is compatible with the\n \/\/ protoc-c version before going any further.\n printer->Print(\n \"#if PROTOBUF_C_VERSION_NUMBER < $min_header_version$\\n\"\n \"# error This file was generated by a newer version of protoc-c which is \"\n \"incompatible with your libprotobuf-c headers. Please update your headers.\\n\"\n \"#elif $protoc_version$ < PROTOBUF_C_MIN_COMPILER_VERSION\\n\"\n \"# error This file was generated by an older version of protoc-c which is \"\n \"incompatible with your libprotobuf-c headers. Please regenerate this file \"\n \"with a newer version of protoc-c.\\n\"\n \"#endif\\n\"\n \"\\n\",\n \"min_header_version\", SimpleItoa(min_header_version),\n \"protoc_version\", SimpleItoa(PROTOBUF_C_VERSION_NUMBER));\n\n for (int i = 0; i < file_->dependency_count(); i++) {\n printer->Print(\n \"#include \\\"$dependency$.pb-c.h\\\"\\n\",\n \"dependency\", StripProto(file_->dependency(i)->name()));\n }\n\n printer->Print(\"\\n\");\n\n \/\/ Generate forward declarations of classes.\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateStructTypedef(printer);\n }\n\n printer->Print(\"\\n\");\n\n \/\/ Generate enum definitions.\n printer->Print(\"\\n\/* --- enums --- *\/\\n\\n\");\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateEnumDefinitions(printer);\n }\n for (int i = 0; i < file_->enum_type_count(); i++) {\n enum_generators_[i]->GenerateDefinition(printer);\n }\n\n \/\/ Generate class definitions.\n printer->Print(\"\\n\/* --- messages --- *\/\\n\\n\");\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateStructDefinition(printer);\n }\n\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateHelperFunctionDeclarations(printer, false);\n }\n\n printer->Print(\"\/* --- per-message closures --- *\/\\n\\n\");\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateClosureTypedef(printer);\n }\n\n \/\/ Generate service definitions.\n printer->Print(\"\\n\/* --- services --- *\/\\n\\n\");\n for (int i = 0; i < file_->service_count(); i++) {\n service_generators_[i]->GenerateMainHFile(printer);\n }\n\n \/\/ Declare extension identifiers.\n for (int i = 0; i < file_->extension_count(); i++) {\n extension_generators_[i]->GenerateDeclaration(printer);\n }\n\n printer->Print(\"\\n\/* --- descriptors --- *\/\\n\\n\");\n for (int i = 0; i < file_->enum_type_count(); i++) {\n enum_generators_[i]->GenerateDescriptorDeclarations(printer);\n }\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateDescriptorDeclarations(printer);\n }\n for (int i = 0; i < file_->service_count(); i++) {\n service_generators_[i]->GenerateDescriptorDeclarations(printer);\n }\n\n printer->Print(\n \"\\n\"\n \"PROTOBUF_C_END_DECLS\\n\"\n \"\\n\\n#endif \/* PROTOBUF_C_$filename_identifier$__INCLUDED *\/\\n\",\n \"filename_identifier\", filename_identifier);\n}\n\nvoid FileGenerator::GenerateSource(io::Printer* printer) {\n printer->Print(\n \"\/* Generated by the protocol buffer compiler. DO NOT EDIT! *\/\\n\"\n \"\/* Generated from: $filename$ *\/\\n\"\n \"\\n\"\n \"\/* Do not generate deprecated warnings for self *\/\\n\"\n \"#ifndef PROTOBUF_C_NO_DEPRECATED\\n\"\n \"#define PROTOBUF_C_NO_DEPRECATED\\n\"\n \"#endif\\n\"\n \"\\n\"\n \"#include \\\"$basename$.pb-c.h\\\"\\n\",\n \"filename\", file_->name(),\n \"basename\", StripProto(file_->name()));\n\n#if 0\n \/\/ For each dependency, write a prototype for that dependency's\n \/\/ BuildDescriptors() function. We don't expose these in the header because\n \/\/ they are internal implementation details, and since this is generated code\n \/\/ we don't have the usual risks involved with declaring external functions\n \/\/ within a .cc file.\n for (int i = 0; i < file_->dependency_count(); i++) {\n const FileDescriptor* dependency = file_->dependency(i);\n \/\/ Open the dependency's namespace.\n vector<string> dependency_package_parts;\n SplitStringUsing(dependency->package(), \".\", &dependency_package_parts);\n \/\/ Declare its BuildDescriptors() function.\n printer->Print(\n \"void $function$();\",\n \"function\", GlobalBuildDescriptorsName(dependency->name()));\n \/\/ Close the namespace.\n for (int i = 0; i < dependency_package_parts.size(); i++) {\n printer->Print(\" }\");\n }\n printer->Print(\"\\n\");\n }\n#endif\n\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateHelperFunctionDefinitions(printer, false);\n }\n for (int i = 0; i < file_->message_type_count(); i++) {\n message_generators_[i]->GenerateMessageDescriptor(printer);\n }\n for (int i = 0; i < file_->enum_type_count(); i++) {\n enum_generators_[i]->GenerateEnumDescriptor(printer);\n }\n for (int i = 0; i < file_->service_count(); i++) {\n service_generators_[i]->GenerateCFile(printer);\n }\n\n}\n\n} \/\/ namespace c\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<|endoftext|>"} {"text":"<commit_before>void build(Solution &s)\n{\n auto &tess = s.addProject(\"google.tesseract\", \"master\");\n tess += Git(\"https:\/\/github.com\/tesseract-ocr\/tesseract\", \"\", \"{v}\");\n\n auto &libtesseract = tess.addTarget<LibraryTarget>(\"libtesseract\");\n {\n libtesseract.setChecks(\"libtesseract\");\n\n libtesseract.ExportAllSymbols = true;\n libtesseract.PackageDefinitions = true;\n\n libtesseract -= \"src\/lstm\/.*\\\\.cc\"_rr;\n libtesseract -= \"src\/training\/.*\"_rr;\n\n libtesseract -=\n \"src\/api\/tesseractmain.cpp\",\n \"src\/viewer\/svpaint.cpp\";\n\n libtesseract.Public += \"include\"_idir;\n libtesseract.Protected +=\n \"src\/opencl\"_id,\n \"src\/ccmain\"_id,\n \"src\/api\"_id,\n \"src\/dict\"_id,\n \"src\/viewer\"_id,\n \"src\/wordrec\"_id,\n \"src\/ccstruct\"_id,\n \"src\/cutil\"_id,\n \"src\/textord\"_id,\n \"src\/ccutil\"_id,\n \"src\/lstm\"_id,\n \"src\/classify\"_id,\n \"src\/arch\"_id,\n \"src\/training\"_id;\n\n if (libtesseract.getCompilerType() == CompilerType::MSVC ||\n libtesseract.getCompilerType() == CompilerType::ClangCl)\n {\n libtesseract += \"__SSE4_1__\"_def;\n libtesseract.CompileOptions.push_back(\"-arch:AVX2\");\n\n libtesseract -=\n \"src\/arch\/dotproductfma.cpp\";\n }\n\n libtesseract.Public += \"HAVE_CONFIG_H\"_d;\n libtesseract.Public += \"_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1\"_d;\n libtesseract.Public += \"HAVE_LIBARCHIVE\"_d;\n libtesseract.Interface += sw::Shared, \"TESS_IMPORTS\"_d;\n libtesseract.Private += sw::Shared, \"TESS_EXPORTS\"_d;\n\n libtesseract.Public += \"org.sw.demo.danbloomberg.leptonica\"_dep;\n libtesseract.Public += \"org.sw.demo.libarchive.libarchive\"_dep;\n\n if (libtesseract.getBuildSettings().TargetOS.Type == OSType::Windows)\n {\n libtesseract.Public += \"ws2_32.lib\"_slib;\n libtesseract.Protected += \"NOMINMAX\"_def;\n }\n\n libtesseract.Variables[\"TESSERACT_MAJOR_VERSION\"] = libtesseract.Variables[\"PACKAGE_MAJOR_VERSION\"];\n libtesseract.Variables[\"TESSERACT_MINOR_VERSION\"] = libtesseract.Variables[\"PACKAGE_MINOR_VERSION\"];\n libtesseract.Variables[\"TESSERACT_MICRO_VERSION\"] = libtesseract.Variables[\"PACKAGE_PATCH_VERSION\"];\n libtesseract.Variables[\"TESSERACT_VERSION_STR\"] = \"master\";\n libtesseract.configureFile(\"include\/tesseract\/version.h.in\", \"tesseract\/version.h\");\n }\n\n \/\/\n auto &tesseract = tess.addExecutable(\"tesseract\");\n tesseract += \"src\/api\/tesseractmain.cpp\";\n tesseract += libtesseract;\n\n \/\/\n auto &tessopt = tess.addStaticLibrary(\"tessopt\");\n tessopt += \"src\/training\/tessopt.*\"_rr;\n tessopt.Public += libtesseract;\n\n \/\/\n auto &common_training = tess.addStaticLibrary(\"common_training\");\n common_training +=\n \"src\/training\/commandlineflags.cpp\",\n \"src\/training\/commandlineflags.h\",\n \"src\/training\/commontraining.cpp\",\n \"src\/training\/commontraining.h\",\n \"src\/training\/ctc.cpp\",\n \"src\/training\/ctc.h\",\n \"src\/training\/errorcounter.cpp\",\n \"src\/training\/errorcounter.h\",\n \"src\/training\/intfeaturedist.cpp\",\n \"src\/training\/intfeaturedist.h\",\n \"src\/training\/intfeaturemap.cpp\",\n \"src\/training\/intfeaturemap.h\",\n \"src\/training\/mastertrainer.cpp\",\n \"src\/training\/mastertrainer.h\",\n \"src\/training\/networkbuilder.cpp\",\n \"src\/training\/networkbuilder.h\",\n \"src\/training\/sampleiterator.cpp\",\n \"src\/training\/sampleiterator.h\",\n \"src\/training\/trainingsampleset.cpp\",\n \"src\/training\/trainingsampleset.h\";\n common_training.Public += tessopt;\n\n \/\/\n auto &unicharset_training = tess.addStaticLibrary(\"unicharset_training\");\n unicharset_training +=\n \"src\/training\/fileio.*\"_rr,\n \"src\/training\/icuerrorcode.*\"_rr,\n \"src\/training\/icuerrorcode.h\",\n \"src\/training\/lang_model_helpers.*\"_rr,\n \"src\/training\/lstmtester.*\"_rr,\n \"src\/training\/lstmtrainer.*\"_rr,\n \"src\/training\/normstrngs.*\"_rr,\n \"src\/training\/unicharset_training_utils.*\"_rr,\n \"src\/training\/validat.*\"_rr;\n unicharset_training.Public += common_training;\n unicharset_training.Public += \"org.sw.demo.unicode.icu.i18n\"_dep;\n\n \/\/\n#define ADD_EXE(n, ...) \\\n auto &n = tess.addExecutable(#n); \\\n n += \"src\/training\/\" #n \".*\"_rr; \\\n n.Public += __VA_ARGS__; \\\n n\n\n ADD_EXE(ambiguous_words, libtesseract);\n ADD_EXE(classifier_tester, common_training);\n ADD_EXE(combine_lang_model, unicharset_training);\n ADD_EXE(combine_tessdata, libtesseract);\n ADD_EXE(cntraining, common_training);\n ADD_EXE(dawg2wordlist, libtesseract);\n ADD_EXE(mftraining, common_training) += \"src\/training\/mergenf.*\"_rr;\n ADD_EXE(shapeclustering, common_training);\n ADD_EXE(unicharset_extractor, unicharset_training);\n ADD_EXE(wordlist2dawg, libtesseract);\n ADD_EXE(lstmeval, unicharset_training);\n ADD_EXE(lstmtraining, unicharset_training);\n ADD_EXE(set_unicharset_properties, unicharset_training);\n\n ADD_EXE(text2image, unicharset_training);\n text2image +=\n \"src\/training\/boxchar.cpp\",\n \"src\/training\/boxchar.h\",\n \"src\/training\/degradeimage.cpp\",\n \"src\/training\/degradeimage.h\",\n \"src\/training\/icuerrorcode.h\",\n \"src\/training\/ligature_table.cpp\",\n \"src\/training\/ligature_table.h\",\n \"src\/training\/normstrngs.cpp\",\n \"src\/training\/normstrngs.h\",\n \"src\/training\/pango_font_info.cpp\",\n \"src\/training\/pango_font_info.h\",\n \"src\/training\/stringrenderer.cpp\",\n \"src\/training\/stringrenderer.h\",\n \"src\/training\/text2image.cpp\",\n \"src\/training\/tlog.cpp\",\n \"src\/training\/tlog.h\",\n \"src\/training\/util.h\";\n text2image.Public += \"org.sw.demo.gnome.pango.pangocairo\"_dep;\n}\n\nvoid check(Checker &c)\n{\n auto &s = c.addSet(\"libtesseract\");\n s.checkFunctionExists(\"getline\");\n s.checkIncludeExists(\"dlfcn.h\");\n s.checkIncludeExists(\"inttypes.h\");\n s.checkIncludeExists(\"limits.h\");\n s.checkIncludeExists(\"malloc.h\");\n s.checkIncludeExists(\"memory.h\");\n s.checkIncludeExists(\"stdbool.h\");\n s.checkIncludeExists(\"stdint.h\");\n s.checkIncludeExists(\"stdlib.h\");\n s.checkIncludeExists(\"string.h\");\n s.checkIncludeExists(\"sys\/ipc.h\");\n s.checkIncludeExists(\"sys\/shm.h\");\n s.checkIncludeExists(\"sys\/stat.h\");\n s.checkIncludeExists(\"sys\/types.h\");\n s.checkIncludeExists(\"sys\/wait.h\");\n s.checkIncludeExists(\"tiffio.h\");\n s.checkIncludeExists(\"unistd.h\");\n s.checkTypeSize(\"long long int\");\n s.checkTypeSize(\"mbstate_t\");\n s.checkTypeSize(\"off_t\");\n s.checkTypeSize(\"size_t\");\n s.checkTypeSize(\"void *\");\n s.checkTypeSize(\"wchar_t\");\n s.checkTypeSize(\"_Bool\");\n {\n auto &c = s.checkSymbolExists(\"snprintf\");\n c.Parameters.Includes.push_back(\"stdio.h\");\n }\n}\n<commit_msg>[sw] Fix linux build.<commit_after>void build(Solution &s)\n{\n auto &tess = s.addProject(\"google.tesseract\", \"master\");\n tess += Git(\"https:\/\/github.com\/tesseract-ocr\/tesseract\", \"\", \"{v}\");\n\n auto &libtesseract = tess.addTarget<LibraryTarget>(\"libtesseract\");\n {\n libtesseract.setChecks(\"libtesseract\");\n\n libtesseract.ExportAllSymbols = true;\n libtesseract.PackageDefinitions = true;\n\n libtesseract += \"src\/.*\"_rr;\n libtesseract -= \"src\/lstm\/.*\\\\.cc\"_rr;\n libtesseract -= \"src\/training\/.*\"_rr;\n\n libtesseract -=\n \"src\/api\/tesseractmain.cpp\",\n \"src\/viewer\/svpaint.cpp\";\n\n libtesseract.Public += \"include\"_idir;\n libtesseract.Protected +=\n \"src\/opencl\"_id,\n \"src\/ccmain\"_id,\n \"src\/api\"_id,\n \"src\/dict\"_id,\n \"src\/viewer\"_id,\n \"src\/wordrec\"_id,\n \"src\/ccstruct\"_id,\n \"src\/cutil\"_id,\n \"src\/textord\"_id,\n \"src\/ccutil\"_id,\n \"src\/lstm\"_id,\n \"src\/classify\"_id,\n \"src\/arch\"_id,\n \"src\/training\"_id;\n\n if (libtesseract.getCompilerType() == CompilerType::MSVC ||\n libtesseract.getCompilerType() == CompilerType::ClangCl)\n {\n libtesseract += \"__SSE4_1__\"_def;\n libtesseract.CompileOptions.push_back(\"-arch:AVX2\");\n }\n\n \/\/ check fma flags\n libtesseract -= \"src\/arch\/dotproductfma.cpp\";\n\n if (libtesseract.getBuildSettings().TargetOS.Type != OSType::Windows)\n {\n libtesseract[\"src\/arch\/dotproductavx.cpp\"].args.push_back(\"-mavx\");\n libtesseract[\"src\/arch\/dotproductsse.cpp\"].args.push_back(\"-msse4.1\");\n libtesseract[\"src\/arch\/intsimdmatrixsse.cpp\"].args.push_back(\"-msse4.1\");\n libtesseract[\"src\/arch\/intsimdmatrixavx2.cpp\"].args.push_back(\"-mavx2\");\n\n libtesseract += \"pthread\"_slib;\n }\n\n libtesseract.Public += \"HAVE_CONFIG_H\"_d;\n libtesseract.Public += \"_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1\"_d;\n libtesseract.Public += \"HAVE_LIBARCHIVE\"_d;\n libtesseract.Interface += sw::Shared, \"TESS_IMPORTS\"_d;\n libtesseract.Private += sw::Shared, \"TESS_EXPORTS\"_d;\n\n libtesseract.Public += \"org.sw.demo.danbloomberg.leptonica\"_dep;\n libtesseract.Public += \"org.sw.demo.libarchive.libarchive\"_dep;\n\n if (libtesseract.getBuildSettings().TargetOS.Type == OSType::Windows)\n {\n libtesseract.Public += \"ws2_32.lib\"_slib;\n libtesseract.Protected += \"NOMINMAX\"_def;\n }\n\n libtesseract.Variables[\"TESSERACT_MAJOR_VERSION\"] = libtesseract.Variables[\"PACKAGE_MAJOR_VERSION\"];\n libtesseract.Variables[\"TESSERACT_MINOR_VERSION\"] = libtesseract.Variables[\"PACKAGE_MINOR_VERSION\"];\n libtesseract.Variables[\"TESSERACT_MICRO_VERSION\"] = libtesseract.Variables[\"PACKAGE_PATCH_VERSION\"];\n libtesseract.Variables[\"TESSERACT_VERSION_STR\"] = \"master\";\n libtesseract.configureFile(\"include\/tesseract\/version.h.in\", \"tesseract\/version.h\");\n }\n\n \/\/\n auto &tesseract = tess.addExecutable(\"tesseract\");\n tesseract += \"src\/api\/tesseractmain.cpp\";\n tesseract += libtesseract;\n\n \/\/\n auto &tessopt = tess.addStaticLibrary(\"tessopt\");\n tessopt += \"src\/training\/tessopt.*\"_rr;\n tessopt.Public += libtesseract;\n\n \/\/\n auto &common_training = tess.addStaticLibrary(\"common_training\");\n common_training +=\n \"src\/training\/commandlineflags.cpp\",\n \"src\/training\/commandlineflags.h\",\n \"src\/training\/commontraining.cpp\",\n \"src\/training\/commontraining.h\",\n \"src\/training\/ctc.cpp\",\n \"src\/training\/ctc.h\",\n \"src\/training\/errorcounter.cpp\",\n \"src\/training\/errorcounter.h\",\n \"src\/training\/intfeaturedist.cpp\",\n \"src\/training\/intfeaturedist.h\",\n \"src\/training\/intfeaturemap.cpp\",\n \"src\/training\/intfeaturemap.h\",\n \"src\/training\/mastertrainer.cpp\",\n \"src\/training\/mastertrainer.h\",\n \"src\/training\/networkbuilder.cpp\",\n \"src\/training\/networkbuilder.h\",\n \"src\/training\/sampleiterator.cpp\",\n \"src\/training\/sampleiterator.h\",\n \"src\/training\/trainingsampleset.cpp\",\n \"src\/training\/trainingsampleset.h\";\n common_training.Public += tessopt;\n\n \/\/\n auto &unicharset_training = tess.addStaticLibrary(\"unicharset_training\");\n unicharset_training +=\n \"src\/training\/fileio.*\"_rr,\n \"src\/training\/icuerrorcode.*\"_rr,\n \"src\/training\/icuerrorcode.h\",\n \"src\/training\/lang_model_helpers.*\"_rr,\n \"src\/training\/lstmtester.*\"_rr,\n \"src\/training\/lstmtrainer.*\"_rr,\n \"src\/training\/normstrngs.*\"_rr,\n \"src\/training\/unicharset_training_utils.*\"_rr,\n \"src\/training\/validat.*\"_rr;\n unicharset_training.Public += common_training;\n unicharset_training.Public += \"org.sw.demo.unicode.icu.i18n\"_dep;\n\n \/\/\n#define ADD_EXE(n, ...) \\\n auto &n = tess.addExecutable(#n); \\\n n += \"src\/training\/\" #n \".*\"_rr; \\\n n.Public += __VA_ARGS__; \\\n n\n\n ADD_EXE(ambiguous_words, libtesseract);\n ADD_EXE(classifier_tester, common_training);\n ADD_EXE(combine_lang_model, unicharset_training);\n ADD_EXE(combine_tessdata, libtesseract);\n ADD_EXE(cntraining, common_training);\n ADD_EXE(dawg2wordlist, libtesseract);\n ADD_EXE(mftraining, common_training) += \"src\/training\/mergenf.*\"_rr;\n ADD_EXE(shapeclustering, common_training);\n ADD_EXE(unicharset_extractor, unicharset_training);\n ADD_EXE(wordlist2dawg, libtesseract);\n ADD_EXE(lstmeval, unicharset_training);\n ADD_EXE(lstmtraining, unicharset_training);\n ADD_EXE(set_unicharset_properties, unicharset_training);\n\n ADD_EXE(text2image, unicharset_training);\n text2image +=\n \"src\/training\/boxchar.cpp\",\n \"src\/training\/boxchar.h\",\n \"src\/training\/degradeimage.cpp\",\n \"src\/training\/degradeimage.h\",\n \"src\/training\/icuerrorcode.h\",\n \"src\/training\/ligature_table.cpp\",\n \"src\/training\/ligature_table.h\",\n \"src\/training\/normstrngs.cpp\",\n \"src\/training\/normstrngs.h\",\n \"src\/training\/pango_font_info.cpp\",\n \"src\/training\/pango_font_info.h\",\n \"src\/training\/stringrenderer.cpp\",\n \"src\/training\/stringrenderer.h\",\n \"src\/training\/text2image.cpp\",\n \"src\/training\/tlog.cpp\",\n \"src\/training\/tlog.h\",\n \"src\/training\/util.h\";\n text2image.Public += \"org.sw.demo.gnome.pango.pangocairo\"_dep;\n}\n\nvoid check(Checker &c)\n{\n auto &s = c.addSet(\"libtesseract\");\n s.checkFunctionExists(\"getline\");\n s.checkIncludeExists(\"dlfcn.h\");\n s.checkIncludeExists(\"inttypes.h\");\n s.checkIncludeExists(\"limits.h\");\n s.checkIncludeExists(\"malloc.h\");\n s.checkIncludeExists(\"memory.h\");\n s.checkIncludeExists(\"stdbool.h\");\n s.checkIncludeExists(\"stdint.h\");\n s.checkIncludeExists(\"stdlib.h\");\n s.checkIncludeExists(\"string.h\");\n s.checkIncludeExists(\"sys\/ipc.h\");\n s.checkIncludeExists(\"sys\/shm.h\");\n s.checkIncludeExists(\"sys\/stat.h\");\n s.checkIncludeExists(\"sys\/types.h\");\n s.checkIncludeExists(\"sys\/wait.h\");\n s.checkIncludeExists(\"tiffio.h\");\n s.checkIncludeExists(\"unistd.h\");\n s.checkTypeSize(\"long long int\");\n s.checkTypeSize(\"mbstate_t\");\n s.checkTypeSize(\"off_t\");\n s.checkTypeSize(\"size_t\");\n s.checkTypeSize(\"void *\");\n s.checkTypeSize(\"wchar_t\");\n s.checkTypeSize(\"_Bool\");\n {\n auto &c = s.checkSymbolExists(\"snprintf\");\n c.Parameters.Includes.push_back(\"stdio.h\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of mcompositor.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\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 \\class MCompositeWindowAnimation\n \\brief MCompositeWindowAnimation class which provides full control \n of position transformation and opacity animations of composite window objects.\n\n To create more complex animations, re-implement the virtual functions\n windowShown(), windowClosed(), widowIconified() and windowRestored(); \n A QParallelAnimationGroup object is provided which can be a container\n for more complex animations for more flexibility.\n*\/\n\/\/ TODO: import icongeometry. export signals when animation done to hook\n\/\/ to composting on off\n\n#include <QMetaMethod>\n#include <QRectF>\n#include <QDesktopWidget>\n#include <QPropertyAnimation>\n#include <mcompositewindow.h>\n#include <mcompositewindowanimation.h>\n#include <QApplication>\n#include <QParallelAnimationGroup>\n#include <mcompositemanager.h>\n#include <mcompositemanager_p.h>\n#include <QVector>\n\nclass McParallelAnimation: public QParallelAnimationGroup\n{\npublic:\n McParallelAnimation(MCompositeWindowAnimation* p)\n :QParallelAnimationGroup(p),\n parent(p)\n {}\n \nprotected:\n virtual void updateCurrentTime(int currentTime)\n { \n MCompositeWindow::update();\n QParallelAnimationGroup::updateCurrentTime(currentTime);\n }\n\n virtual void updateState(QAbstractAnimation::State newState, \n QAbstractAnimation::State oldState)\n { \n if (newState == QAbstractAnimation::Running && \n oldState == QAbstractAnimation::Stopped) {\n parent->ensureAnimationVisible();\n if (parent->targetWindow())\n parent->targetWindow()->beginAnimation();\n if (parent->targetWindow2())\n parent->targetWindow2()->beginAnimation();\n } else if (newState == QAbstractAnimation::Stopped) {\n if (parent->targetWindow())\n parent->targetWindow()->endAnimation();\n if (parent->targetWindow2())\n parent->targetWindow2()->endAnimation();\n }\n QParallelAnimationGroup::updateState(newState, oldState);\n }\nprivate:\n MCompositeWindowAnimation* parent;\n};\n\nclass MCompositeWindowAnimationPrivate\n{\npublic:\n \n MCompositeWindowAnimationPrivate(MCompositeWindowAnimation* animation)\n : crossfade(0),\n pending_animation(MCompositeWindowAnimation::NoAnimation),\n is_replaceable(true),\n animhandler(MCompositeWindowAnimation::AnimationTotal, 0)\n {\n const MCompositeManager *mc = static_cast<MCompositeManager*>(qApp);\n int duration = mc->configInt(\"startup-anim-duration\");\n\n scale = new QPropertyAnimation(animation);\n scale->setPropertyName(\"scale\");\n scale->setDuration(duration);\n \n position = new QPropertyAnimation(animation);\n position->setPropertyName(\"pos\");\n position->setDuration(duration);\n \n opacity = new QPropertyAnimation(animation);\n opacity->setPropertyName(\"opacity\");\n opacity->setDuration(duration);\n \n scalepos = new McParallelAnimation(animation);\n scalepos->addAnimation(scale);\n scalepos->addAnimation(position);\n scalepos->addAnimation(opacity);\n \n QObject::connect(scalepos, SIGNAL(finished()), animation,\n SLOT(finalizeState()));\n }\n\n void setTargetWindow(MCompositeWindow* window)\n {\n if (scale && position && opacity) {\n scale->setTargetObject(window);\n position->setTargetObject(window);\n opacity->setTargetObject(window);\n }\n }\n\n bool handledByInvoker(MCompositeWindowAnimation::AnimationType type)\n {\n if (animhandler[type]) {\n switch (type) {\n case MCompositeWindowAnimation::Showing:\n animhandler[type]->windowShown();\n return true;\n case MCompositeWindowAnimation::Closing:\n animhandler[type]->windowClosed();\n return true;\n case MCompositeWindowAnimation::Iconify:\n animhandler[type]->windowIconified();\n return true;\n case MCompositeWindowAnimation::Restore:\n animhandler[type]->windowRestored();\n return true;\n default:\n break;\n }\n }\n \n return false;\n }\n\n QPointer<MCompositeWindow> target_window, target_window2;\n QPointer<QPropertyAnimation> scale;\n QPointer<QPropertyAnimation> position;\n QPointer<QPropertyAnimation> opacity;\n McParallelAnimation* scalepos, *crossfade;\n MCompositeWindowAnimation::AnimationType pending_animation;\n bool is_replaceable;\n QVector< MAbstractAnimationHandler* > animhandler;\n};\n\nMCompositeWindowAnimation::MCompositeWindowAnimation(QObject* parent)\n :QObject(parent),\n d_ptr(new MCompositeWindowAnimationPrivate(this))\n{\n}\n\nMCompositeWindowAnimation::~MCompositeWindowAnimation()\n{\n}\n\nvoid MCompositeWindowAnimation::setTargetWindow(MCompositeWindow* window)\n{\n Q_D(MCompositeWindowAnimation);\n\n \/\/ never override a non-replaceable animation\n if (window->animator && !window->animator->isReplaceable()) {\n deleteLater();\n return;\n }\n \n \/\/ replace the old animator if there is one\n if (window->animator && (window->animator != this))\n delete window->animator;\n\n d->target_window = window;\n d->target_window->animator = this;\n disconnect(SIGNAL(q_finalizeState()));\n connect(this, SIGNAL(q_finalizeState()), window, SLOT(finalizeState()));\n \n d->setTargetWindow(window);\n}\n\nvoid MCompositeWindowAnimation::finalizeState()\n{\n emit q_finalizeState();\n}\n\n\/\/ returns a group animation for this animator \nQParallelAnimationGroup* MCompositeWindowAnimation::animationGroup() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->scalepos;\n}\n\nMCompositeWindow* MCompositeWindowAnimation::targetWindow() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->target_window;\n}\n\nMCompositeWindow* MCompositeWindowAnimation::targetWindow2() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->target_window2;\n}\n\n\/\/ Exposed animation properties\nQPropertyAnimation* MCompositeWindowAnimation::scaleAnimation() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->scale;\n}\n\nQPropertyAnimation* MCompositeWindowAnimation::positionAnimation() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->position;\n}\n\nQPropertyAnimation* MCompositeWindowAnimation::opacityAnimation() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->opacity;\n}\n\n\/\/ Default effect\nvoid MCompositeWindowAnimation::windowShown()\n{\n#define OPAQUE 1.0\n#define DIMMED 0.1\n Q_D(MCompositeWindowAnimation);\n if (!d->target_window)\n return;\n\n if (d->handledByInvoker(Showing))\n return;\n \n const qreal scaleStart = 0.2;\n const QRectF &iconGeometry = d->target_window->propertyCache()->iconGeometry();\n QPointF topLeft = iconGeometry.topLeft();\n\n if (iconGeometry.isEmpty()) {\n const QRectF d = QApplication::desktop()->availableGeometry();\n topLeft.setX(d.width()\/2.0f * (1.0f-scaleStart));\n topLeft.setY(d.height()\/2.0f * (1.0f-scaleStart));\n }\n\n d->target_window->setPos(topLeft);\n positionAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n positionAnimation()->setStartValue(topLeft);\n positionAnimation()->setEndValue(\n QPointF(d->target_window->propertyCache()->realGeometry().x(),\n d->target_window->propertyCache()->realGeometry().y()));\n scaleAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n \n \/\/ TODO: use icon geometry signal\n scaleAnimation()->setStartValue(scaleStart);\n scaleAnimation()->setEndValue(1.0);\n opacityAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n opacityAnimation()->setStartValue(DIMMED);\n opacityAnimation()->setEndValue(OPAQUE);\n\n animationGroup()->setDirection(QAbstractAnimation::Forward);\n animationGroup()->start();\n}\n\nvoid MCompositeWindowAnimation::windowClosed()\n{\n Q_D(MCompositeWindowAnimation);\n if (d->handledByInvoker(Closing))\n return;\n\n positionAnimation()->setEasingCurve(QEasingCurve::InQuad);\n scaleAnimation()->setEasingCurve(QEasingCurve::InQuad);\n opacityAnimation()->setEasingCurve(QEasingCurve::InQuad);\n animationGroup()->setDirection(QAbstractAnimation::Backward);\n animationGroup()->start();\n}\n\nvoid MCompositeWindowAnimation::deferAnimation(MCompositeWindowAnimation::AnimationType type)\n{\n Q_D(MCompositeWindowAnimation);\n d->pending_animation = type;\n}\n\nvoid MCompositeWindowAnimation::windowIconified()\n{\n Q_D(MCompositeWindowAnimation);\n\n if (d->handledByInvoker(Iconify))\n return;\n positionAnimation()->setEasingCurve(QEasingCurve::InQuad);\n scaleAnimation()->setEasingCurve(QEasingCurve::InQuad);\n opacityAnimation()->setEasingCurve(QEasingCurve::InQuad);\n animationGroup()->setDirection(QAbstractAnimation::Backward);\n animationGroup()->start();\n}\n\nvoid MCompositeWindowAnimation::windowRestored()\n{\n Q_D(MCompositeWindowAnimation);\n\n if (d->handledByInvoker(Restore))\n return;\n positionAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n scaleAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n opacityAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n animationGroup()->setDirection(QAbstractAnimation::Forward);\n animationGroup()->start();\n}\n\nvoid MCompositeWindowAnimation::crossFadeTo(MCompositeWindow *cw)\n{\n Q_D(MCompositeWindowAnimation);\n const MCompositeManager *mc = static_cast<MCompositeManager*>(qApp);\n\n if (d->crossfade)\n delete d->crossfade;\n d->crossfade = new McParallelAnimation(this);\n\n QPropertyAnimation *op = new QPropertyAnimation(this);\n op->setTargetObject(cw);\n op->setEasingCurve(QEasingCurve::Linear);\n op->setPropertyName(\"opacity\");\n op->setDuration(mc->configInt(\"crossfade-duration\"));\n op->setStartValue(0);\n op->setEndValue(1);\n d->crossfade->addAnimation(op);\n\n d->target_window2 = cw;\n\n d->crossfade->setDirection(QAbstractAnimation::Forward);\n}\n\nvoid MCompositeWindowAnimation::startTransition()\n{ \n Q_D(MCompositeWindowAnimation);\n \n switch (d->pending_animation) {\n case Showing:\n windowShown();\n d->pending_animation = NoAnimation;\n break;\n case Closing:\n windowClosed();\n d->pending_animation = NoAnimation;\n break;\n case Iconify:\n windowIconified();\n d->pending_animation = NoAnimation;\n break;\n case Restore:\n windowRestored();\n d->pending_animation = NoAnimation;\n break;\n case CrossFade:\n if (targetWindow2())\n targetWindow2()->show();\n d->crossfade->start();\n d->pending_animation = NoAnimation;\n break;\n default: break;\n }\n}\n\nvoid MCompositeWindowAnimation::ensureAnimationVisible()\n{\n \/\/ Always ensure the animation is REALLY visible. Z-values get corrected \n \/\/ later at checkStacking if needed\n if (targetWindow() && \n targetWindow()->propertyCache()->windowState() != IconicState)\n targetWindow()->setZValue(\n ((MCompositeManager*)qApp)->d->stacking_list.size() + 1);\n if (targetWindow2())\n targetWindow2()->setZValue(\n ((MCompositeManager*)qApp)->d->stacking_list.size() + 2);\n}\n\n\/\/ plays the animation group;\nvoid MCompositeWindowAnimation::start()\n{\n animationGroup()->start();\n}\n\n\/\/ pauses the animation group;\nvoid MCompositeWindowAnimation::pause()\n{\n animationGroup()->pause();\n}\n\nvoid MCompositeWindowAnimation::finish()\n{\n animationGroup()->setCurrentTime(animationGroup()->duration());\n animationGroup()->stop();\n}\n\nbool MCompositeWindowAnimation::isActive()\n{\n return (animationGroup()->state() != QAbstractAnimation::Stopped);\n}\n\nMCompositeWindowAnimation::AnimationType MCompositeWindowAnimation::pendingAnimation() const \n{ \n Q_D(const MCompositeWindowAnimation);\n \n return d->pending_animation; \n}\n\n\/*!\n Enabled or disables this animation. Re-implement this function to customize\n how a custom animation can be disabled or disabled\n *\/\nvoid MCompositeWindowAnimation::setEnabled(bool enabled)\n{\n if (enabled) {\n if (animationGroup()->indexOfAnimation(positionAnimation()) == -1)\n animationGroup()->addAnimation(positionAnimation());\n if (animationGroup()->indexOfAnimation(scaleAnimation()) == -1)\n animationGroup()->addAnimation(scaleAnimation());\n if (animationGroup()->indexOfAnimation(opacityAnimation()) == -1)\n animationGroup()->addAnimation(opacityAnimation());\n } else if (!enabled) {\n animationGroup()->stop();\n animationGroup()->removeAnimation(positionAnimation());\n animationGroup()->removeAnimation(scaleAnimation());\n animationGroup()->removeAnimation(opacityAnimation());\n }\n}\n\n\/*!\n \\return Whether this animation can be replaced or not. By default, window\n animations can be replaced with a custom animation \n *\/\nbool MCompositeWindowAnimation::isReplaceable() const\n{\n Q_D(const MCompositeWindowAnimation);\n \n return d->is_replaceable;\n}\n\n\/*!\n If \\a replaceable is true, this animation can be replaced with another custom\n animation object. If \\a replaceable is false, the animation may not be \n replaced with another animation and will be set for the lifetime of the \n window that is initially associated with it.\n *\/\nvoid MCompositeWindowAnimation::setReplaceable(bool replaceable)\n{\n Q_D(MCompositeWindowAnimation);\n\n d->is_replaceable = replaceable;\n}\n\n\/*!\n Sets a custom external animation handler for animation \\a type. If an \n external handler is set it will use the virtual functions of that animation\n \\a handler instead of this object's handlers. \n To create an external handler, inherit from MAbstractAnimationHandler class\n and reimplement the required animation functions as needed.\n *\/\nvoid MCompositeWindowAnimation::setAnimationHandler(AnimationType type, \n MAbstractAnimationHandler* handler)\n{\n Q_D(MCompositeWindowAnimation);\n\n handler->target_window = targetWindow();\n d->animhandler[type] = handler;\n}\n\nvoid MCompositeWindowAnimation::disconnectHandler(MAbstractAnimationHandler* handler)\n{\n Q_D(MCompositeWindowAnimation);\n int type = d->animhandler.indexOf(handler);\n if (type > -1)\n d->animhandler[type] = 0;\n}\n\nvoid MAbstractAnimationHandler::windowShown()\n{\/\/ NOOP\n}\n\nvoid MAbstractAnimationHandler::windowClosed()\n{\/\/ NOOP\n}\n\nvoid MAbstractAnimationHandler::windowIconified() \n{\/\/ NOOP\n}\n\nvoid MAbstractAnimationHandler::windowRestored()\n{\/\/ NOOP\n}\n\nMCompositeWindow* MAbstractAnimationHandler::targetWindow() const\n{\n return target_window;\n}\n\nMAbstractAnimationHandler::~MAbstractAnimationHandler()\n{\n if (main_animator)\n main_animator->disconnectHandler(this);\n}\n<commit_msg>Changes: Fix the forgotten assignment to the main_operator of the external animation handler<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of mcompositor.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\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 \\class MCompositeWindowAnimation\n \\brief MCompositeWindowAnimation class which provides full control \n of position transformation and opacity animations of composite window objects.\n\n To create more complex animations, re-implement the virtual functions\n windowShown(), windowClosed(), widowIconified() and windowRestored(); \n A QParallelAnimationGroup object is provided which can be a container\n for more complex animations for more flexibility.\n*\/\n\/\/ TODO: import icongeometry. export signals when animation done to hook\n\/\/ to composting on off\n\n#include <QMetaMethod>\n#include <QRectF>\n#include <QDesktopWidget>\n#include <QPropertyAnimation>\n#include <mcompositewindow.h>\n#include <mcompositewindowanimation.h>\n#include <QApplication>\n#include <QParallelAnimationGroup>\n#include <mcompositemanager.h>\n#include <mcompositemanager_p.h>\n#include <QVector>\n\nclass McParallelAnimation: public QParallelAnimationGroup\n{\npublic:\n McParallelAnimation(MCompositeWindowAnimation* p)\n :QParallelAnimationGroup(p),\n parent(p)\n {}\n \nprotected:\n virtual void updateCurrentTime(int currentTime)\n { \n MCompositeWindow::update();\n QParallelAnimationGroup::updateCurrentTime(currentTime);\n }\n\n virtual void updateState(QAbstractAnimation::State newState, \n QAbstractAnimation::State oldState)\n { \n if (newState == QAbstractAnimation::Running && \n oldState == QAbstractAnimation::Stopped) {\n parent->ensureAnimationVisible();\n if (parent->targetWindow())\n parent->targetWindow()->beginAnimation();\n if (parent->targetWindow2())\n parent->targetWindow2()->beginAnimation();\n } else if (newState == QAbstractAnimation::Stopped) {\n if (parent->targetWindow())\n parent->targetWindow()->endAnimation();\n if (parent->targetWindow2())\n parent->targetWindow2()->endAnimation();\n }\n QParallelAnimationGroup::updateState(newState, oldState);\n }\nprivate:\n MCompositeWindowAnimation* parent;\n};\n\nclass MCompositeWindowAnimationPrivate\n{\npublic:\n \n MCompositeWindowAnimationPrivate(MCompositeWindowAnimation* animation)\n : crossfade(0),\n pending_animation(MCompositeWindowAnimation::NoAnimation),\n is_replaceable(true),\n animhandler(MCompositeWindowAnimation::AnimationTotal, 0)\n {\n const MCompositeManager *mc = static_cast<MCompositeManager*>(qApp);\n int duration = mc->configInt(\"startup-anim-duration\");\n\n scale = new QPropertyAnimation(animation);\n scale->setPropertyName(\"scale\");\n scale->setDuration(duration);\n \n position = new QPropertyAnimation(animation);\n position->setPropertyName(\"pos\");\n position->setDuration(duration);\n \n opacity = new QPropertyAnimation(animation);\n opacity->setPropertyName(\"opacity\");\n opacity->setDuration(duration);\n \n scalepos = new McParallelAnimation(animation);\n scalepos->addAnimation(scale);\n scalepos->addAnimation(position);\n scalepos->addAnimation(opacity);\n \n QObject::connect(scalepos, SIGNAL(finished()), animation,\n SLOT(finalizeState()));\n }\n\n void setTargetWindow(MCompositeWindow* window)\n {\n if (scale && position && opacity) {\n scale->setTargetObject(window);\n position->setTargetObject(window);\n opacity->setTargetObject(window);\n }\n }\n\n bool handledByInvoker(MCompositeWindowAnimation::AnimationType type)\n {\n if (animhandler[type]) {\n switch (type) {\n case MCompositeWindowAnimation::Showing:\n animhandler[type]->windowShown();\n return true;\n case MCompositeWindowAnimation::Closing:\n animhandler[type]->windowClosed();\n return true;\n case MCompositeWindowAnimation::Iconify:\n animhandler[type]->windowIconified();\n return true;\n case MCompositeWindowAnimation::Restore:\n animhandler[type]->windowRestored();\n return true;\n default:\n break;\n }\n }\n \n return false;\n }\n\n QPointer<MCompositeWindow> target_window, target_window2;\n QPointer<QPropertyAnimation> scale;\n QPointer<QPropertyAnimation> position;\n QPointer<QPropertyAnimation> opacity;\n McParallelAnimation* scalepos, *crossfade;\n MCompositeWindowAnimation::AnimationType pending_animation;\n bool is_replaceable;\n QVector< MAbstractAnimationHandler* > animhandler;\n};\n\nMCompositeWindowAnimation::MCompositeWindowAnimation(QObject* parent)\n :QObject(parent),\n d_ptr(new MCompositeWindowAnimationPrivate(this))\n{\n}\n\nMCompositeWindowAnimation::~MCompositeWindowAnimation()\n{\n}\n\nvoid MCompositeWindowAnimation::setTargetWindow(MCompositeWindow* window)\n{\n Q_D(MCompositeWindowAnimation);\n\n \/\/ never override a non-replaceable animation\n if (window->animator && !window->animator->isReplaceable()) {\n deleteLater();\n return;\n }\n \n \/\/ replace the old animator if there is one\n if (window->animator && (window->animator != this))\n delete window->animator;\n\n d->target_window = window;\n d->target_window->animator = this;\n disconnect(SIGNAL(q_finalizeState()));\n connect(this, SIGNAL(q_finalizeState()), window, SLOT(finalizeState()));\n \n d->setTargetWindow(window);\n}\n\nvoid MCompositeWindowAnimation::finalizeState()\n{\n emit q_finalizeState();\n}\n\n\/\/ returns a group animation for this animator \nQParallelAnimationGroup* MCompositeWindowAnimation::animationGroup() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->scalepos;\n}\n\nMCompositeWindow* MCompositeWindowAnimation::targetWindow() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->target_window;\n}\n\nMCompositeWindow* MCompositeWindowAnimation::targetWindow2() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->target_window2;\n}\n\n\/\/ Exposed animation properties\nQPropertyAnimation* MCompositeWindowAnimation::scaleAnimation() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->scale;\n}\n\nQPropertyAnimation* MCompositeWindowAnimation::positionAnimation() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->position;\n}\n\nQPropertyAnimation* MCompositeWindowAnimation::opacityAnimation() const\n{\n Q_D(const MCompositeWindowAnimation);\n return d->opacity;\n}\n\n\/\/ Default effect\nvoid MCompositeWindowAnimation::windowShown()\n{\n#define OPAQUE 1.0\n#define DIMMED 0.1\n Q_D(MCompositeWindowAnimation);\n if (!d->target_window)\n return;\n\n if (d->handledByInvoker(Showing))\n return;\n \n const qreal scaleStart = 0.2;\n const QRectF &iconGeometry = d->target_window->propertyCache()->iconGeometry();\n QPointF topLeft = iconGeometry.topLeft();\n\n if (iconGeometry.isEmpty()) {\n const QRectF d = QApplication::desktop()->availableGeometry();\n topLeft.setX(d.width()\/2.0f * (1.0f-scaleStart));\n topLeft.setY(d.height()\/2.0f * (1.0f-scaleStart));\n }\n\n d->target_window->setPos(topLeft);\n positionAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n positionAnimation()->setStartValue(topLeft);\n positionAnimation()->setEndValue(\n QPointF(d->target_window->propertyCache()->realGeometry().x(),\n d->target_window->propertyCache()->realGeometry().y()));\n scaleAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n \n \/\/ TODO: use icon geometry signal\n scaleAnimation()->setStartValue(scaleStart);\n scaleAnimation()->setEndValue(1.0);\n opacityAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n opacityAnimation()->setStartValue(DIMMED);\n opacityAnimation()->setEndValue(OPAQUE);\n\n animationGroup()->setDirection(QAbstractAnimation::Forward);\n animationGroup()->start();\n}\n\nvoid MCompositeWindowAnimation::windowClosed()\n{\n Q_D(MCompositeWindowAnimation);\n if (d->handledByInvoker(Closing))\n return;\n\n positionAnimation()->setEasingCurve(QEasingCurve::InQuad);\n scaleAnimation()->setEasingCurve(QEasingCurve::InQuad);\n opacityAnimation()->setEasingCurve(QEasingCurve::InQuad);\n animationGroup()->setDirection(QAbstractAnimation::Backward);\n animationGroup()->start();\n}\n\nvoid MCompositeWindowAnimation::deferAnimation(MCompositeWindowAnimation::AnimationType type)\n{\n Q_D(MCompositeWindowAnimation);\n d->pending_animation = type;\n}\n\nvoid MCompositeWindowAnimation::windowIconified()\n{\n Q_D(MCompositeWindowAnimation);\n\n if (d->handledByInvoker(Iconify))\n return;\n positionAnimation()->setEasingCurve(QEasingCurve::InQuad);\n scaleAnimation()->setEasingCurve(QEasingCurve::InQuad);\n opacityAnimation()->setEasingCurve(QEasingCurve::InQuad);\n animationGroup()->setDirection(QAbstractAnimation::Backward);\n animationGroup()->start();\n}\n\nvoid MCompositeWindowAnimation::windowRestored()\n{\n Q_D(MCompositeWindowAnimation);\n\n if (d->handledByInvoker(Restore))\n return;\n positionAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n scaleAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n opacityAnimation()->setEasingCurve(QEasingCurve::OutQuad);\n animationGroup()->setDirection(QAbstractAnimation::Forward);\n animationGroup()->start();\n}\n\nvoid MCompositeWindowAnimation::crossFadeTo(MCompositeWindow *cw)\n{\n Q_D(MCompositeWindowAnimation);\n const MCompositeManager *mc = static_cast<MCompositeManager*>(qApp);\n\n if (d->crossfade)\n delete d->crossfade;\n d->crossfade = new McParallelAnimation(this);\n\n QPropertyAnimation *op = new QPropertyAnimation(this);\n op->setTargetObject(cw);\n op->setEasingCurve(QEasingCurve::Linear);\n op->setPropertyName(\"opacity\");\n op->setDuration(mc->configInt(\"crossfade-duration\"));\n op->setStartValue(0);\n op->setEndValue(1);\n d->crossfade->addAnimation(op);\n\n d->target_window2 = cw;\n\n d->crossfade->setDirection(QAbstractAnimation::Forward);\n}\n\nvoid MCompositeWindowAnimation::startTransition()\n{ \n Q_D(MCompositeWindowAnimation);\n \n switch (d->pending_animation) {\n case Showing:\n windowShown();\n d->pending_animation = NoAnimation;\n break;\n case Closing:\n windowClosed();\n d->pending_animation = NoAnimation;\n break;\n case Iconify:\n windowIconified();\n d->pending_animation = NoAnimation;\n break;\n case Restore:\n windowRestored();\n d->pending_animation = NoAnimation;\n break;\n case CrossFade:\n if (targetWindow2())\n targetWindow2()->show();\n d->crossfade->start();\n d->pending_animation = NoAnimation;\n break;\n default: break;\n }\n}\n\nvoid MCompositeWindowAnimation::ensureAnimationVisible()\n{\n \/\/ Always ensure the animation is REALLY visible. Z-values get corrected \n \/\/ later at checkStacking if needed\n if (targetWindow() && \n targetWindow()->propertyCache()->windowState() != IconicState)\n targetWindow()->setZValue(\n ((MCompositeManager*)qApp)->d->stacking_list.size() + 1);\n if (targetWindow2())\n targetWindow2()->setZValue(\n ((MCompositeManager*)qApp)->d->stacking_list.size() + 2);\n}\n\n\/\/ plays the animation group;\nvoid MCompositeWindowAnimation::start()\n{\n animationGroup()->start();\n}\n\n\/\/ pauses the animation group;\nvoid MCompositeWindowAnimation::pause()\n{\n animationGroup()->pause();\n}\n\nvoid MCompositeWindowAnimation::finish()\n{\n animationGroup()->setCurrentTime(animationGroup()->duration());\n animationGroup()->stop();\n}\n\nbool MCompositeWindowAnimation::isActive()\n{\n return (animationGroup()->state() != QAbstractAnimation::Stopped);\n}\n\nMCompositeWindowAnimation::AnimationType MCompositeWindowAnimation::pendingAnimation() const \n{ \n Q_D(const MCompositeWindowAnimation);\n \n return d->pending_animation; \n}\n\n\/*!\n Enabled or disables this animation. Re-implement this function to customize\n how a custom animation can be disabled or disabled\n *\/\nvoid MCompositeWindowAnimation::setEnabled(bool enabled)\n{\n if (enabled) {\n if (animationGroup()->indexOfAnimation(positionAnimation()) == -1)\n animationGroup()->addAnimation(positionAnimation());\n if (animationGroup()->indexOfAnimation(scaleAnimation()) == -1)\n animationGroup()->addAnimation(scaleAnimation());\n if (animationGroup()->indexOfAnimation(opacityAnimation()) == -1)\n animationGroup()->addAnimation(opacityAnimation());\n } else if (!enabled) {\n animationGroup()->stop();\n animationGroup()->removeAnimation(positionAnimation());\n animationGroup()->removeAnimation(scaleAnimation());\n animationGroup()->removeAnimation(opacityAnimation());\n }\n}\n\n\/*!\n \\return Whether this animation can be replaced or not. By default, window\n animations can be replaced with a custom animation \n *\/\nbool MCompositeWindowAnimation::isReplaceable() const\n{\n Q_D(const MCompositeWindowAnimation);\n \n return d->is_replaceable;\n}\n\n\/*!\n If \\a replaceable is true, this animation can be replaced with another custom\n animation object. If \\a replaceable is false, the animation may not be \n replaced with another animation and will be set for the lifetime of the \n window that is initially associated with it.\n *\/\nvoid MCompositeWindowAnimation::setReplaceable(bool replaceable)\n{\n Q_D(MCompositeWindowAnimation);\n\n d->is_replaceable = replaceable;\n}\n\n\/*!\n Sets a custom external animation handler for animation \\a type. If an \n external handler is set it will use the virtual functions of that animation\n \\a handler instead of this object's handlers. \n To create an external handler, inherit from MAbstractAnimationHandler class\n and reimplement the required animation functions as needed.\n *\/\nvoid MCompositeWindowAnimation::setAnimationHandler(AnimationType type, \n MAbstractAnimationHandler* handler)\n{\n Q_D(MCompositeWindowAnimation);\n\n handler->target_window = targetWindow();\n handler->main_animator = this;\n d->animhandler[type] = handler;\n}\n\nvoid MCompositeWindowAnimation::disconnectHandler(MAbstractAnimationHandler* handler)\n{\n Q_D(MCompositeWindowAnimation);\n int type = d->animhandler.indexOf(handler);\n if (type > -1)\n d->animhandler[type] = 0;\n}\n\nvoid MAbstractAnimationHandler::windowShown()\n{\/\/ NOOP\n}\n\nvoid MAbstractAnimationHandler::windowClosed()\n{\/\/ NOOP\n}\n\nvoid MAbstractAnimationHandler::windowIconified() \n{\/\/ NOOP\n}\n\nvoid MAbstractAnimationHandler::windowRestored()\n{\/\/ NOOP\n}\n\nMCompositeWindow* MAbstractAnimationHandler::targetWindow() const\n{\n return target_window;\n}\n\nMAbstractAnimationHandler::~MAbstractAnimationHandler()\n{\n if (main_animator)\n main_animator->disconnectHandler(this);\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <algorithm>\n#include <vector>\n\n#include \"nano_function.hpp\"\n#include \"nano_mutex.hpp\"\n\nnamespace Nano\n{\n\ntemplate <typename MT_Policy = ST_Policy>\nclass Observer : private MT_Policy\n{\n \/\/ Only Nano::Signal is allowed private access\n template <typename, typename> friend class Signal;\n\n struct Connection\n {\n Delegate_Key delegate;\n typename MT_Policy::Weak_Ptr observer;\n\n Connection() noexcept = default;\n Connection(Delegate_Key const& key) : delegate(key), observer() {}\n Connection(Delegate_Key const& key, Observer* obs) : delegate(key), observer(obs->weak_ptr()) {}\n };\n\n struct Z_Order\n {\n inline bool operator()(Delegate_Key const& lhs, Delegate_Key const& rhs) const\n {\n std::size_t x = lhs[0] ^ rhs[0];\n std::size_t y = lhs[1] ^ rhs[1];\n auto k = (x < y) && x < (x ^ y);\n return lhs[k] < rhs[k];\n }\n\n inline bool operator()(Connection const& lhs, Connection const& rhs) const\n {\n return operator()(lhs.delegate, rhs.delegate);\n }\n };\n\n std::vector<Connection> connections;\n\n \/\/--------------------------------------------------------------------------\n\n void insert(Delegate_Key const& key, Observer* obs)\n {\n [[maybe_unused]] auto lock = MT_Policy::lock_guard();\n\n auto begin = std::begin(connections);\n auto end = std::end(connections);\n\n connections.emplace(std::upper_bound(begin, end, key, Z_Order()), key, obs);\n }\n\n void remove(Delegate_Key const& key) noexcept\n {\n [[maybe_unused]] auto lock = MT_Policy::lock_guard();\n\n auto begin = std::begin(connections);\n auto end = std::end(connections);\n\n auto slots = std::equal_range(begin, end, key, Z_Order());\n connections.erase(slots.first, slots.second);\n }\n\n \/\/--------------------------------------------------------------------------\n\n template <typename Function, typename... Uref>\n void for_each(Uref&&... args)\n {\n auto lock = MT_Policy::lock_guard();\n\n for (auto const& slot : MT_Policy::copy_or_ref(connections, lock))\n {\n if (auto observer = MT_Policy::observed(slot.observer))\n {\n Function::bind(slot.delegate)(args...);\n }\n }\n }\n\n template <typename Function, typename Accumulate, typename... Uref>\n void for_each_accumulate(Accumulate&& accumulate, Uref&&... args)\n {\n auto lock = MT_Policy::lock_guard();\n\n for (auto const& slot : MT_Policy::copy_or_ref(connections, lock))\n {\n if (auto observer = MT_Policy::observed(slot.observer))\n {\n accumulate(Function::bind(slot.delegate)(args...));\n }\n }\n }\n\n \/\/--------------------------------------------------------------------------\n\n public:\n\n void disconnect_all() noexcept\n {\n [[maybe_unused]] auto lock = MT_Policy::lock_guard();\n\n for (auto const& slot : connections)\n {\n if (auto observer = MT_Policy::visiting(slot.observer))\n {\n static_cast<Observer*>(MT_Policy::unmask(observer))->remove(slot.delegate);\n }\n }\n connections.clear();\n }\n\n bool is_empty() const noexcept\n {\n auto lock = MT_Policy::lock_guard();\n\n return connections.empty();\n }\n\n protected:\n\n \/\/ Guideline #4: A base class destructor should be\n \/\/ either public and virtual, or protected and non-virtual.\n ~Observer()\n {\n MT_Policy::before_disconnect_all();\n\n disconnect_all();\n }\n\n Observer() noexcept = default;\n\n \/\/ Observer may be movable depending on policy, but should never be copied\n Observer(Observer const&) noexcept = delete;\n Observer& operator= (Observer const&) noexcept = delete;\n\n Observer(Observer&&) noexcept = default;\n Observer& operator=(Observer&&) noexcept = default;\n};\n\n} \/\/ namespace Nano ------------------------------------------------------------\n<commit_msg>Move connections when moving an observer<commit_after>#pragma once\n\n#include <algorithm>\n#include <vector>\n\n#include \"nano_function.hpp\"\n#include \"nano_mutex.hpp\"\n\nnamespace Nano\n{\n\ntemplate <typename MT_Policy = ST_Policy>\nclass Observer : private MT_Policy\n{\n \/\/ Only Nano::Signal is allowed private access\n template <typename, typename> friend class Signal;\n\n struct Connection\n {\n Delegate_Key delegate;\n typename MT_Policy::Weak_Ptr observer;\n\n Connection() noexcept = default;\n Connection(Delegate_Key const& key) : delegate(key), observer() {}\n Connection(Delegate_Key const& key, Observer* obs) : delegate(key), observer(obs->weak_ptr()) {}\n };\n\n struct Z_Order\n {\n inline bool operator()(Delegate_Key const& lhs, Delegate_Key const& rhs) const\n {\n std::size_t x = lhs[0] ^ rhs[0];\n std::size_t y = lhs[1] ^ rhs[1];\n auto k = (x < y) && x < (x ^ y);\n return lhs[k] < rhs[k];\n }\n\n inline bool operator()(Connection const& lhs, Connection const& rhs) const\n {\n return operator()(lhs.delegate, rhs.delegate);\n }\n };\n\n std::vector<Connection> connections;\n bool movedFrom = false;\n\n \/\/--------------------------------------------------------------------------\n\n void insert(Delegate_Key const& key, Observer* obs)\n {\n [[maybe_unused]] auto lock = MT_Policy::lock_guard();\n\n auto begin = std::begin(connections);\n auto end = std::end(connections);\n\n connections.emplace(std::upper_bound(begin, end, key, Z_Order()), key, obs);\n }\n\n void remove(Delegate_Key const& key) noexcept\n {\n [[maybe_unused]] auto lock = MT_Policy::lock_guard();\n\n auto begin = std::begin(connections);\n auto end = std::end(connections);\n\n auto slots = std::equal_range(begin, end, key, Z_Order());\n connections.erase(slots.first, slots.second);\n }\n\n \/\/--------------------------------------------------------------------------\n\n template <typename Function, typename... Uref>\n void for_each(Uref&&... args)\n {\n auto lock = MT_Policy::lock_guard();\n\n for (auto const& slot : MT_Policy::copy_or_ref(connections, lock))\n {\n if (auto observer = MT_Policy::observed(slot.observer))\n {\n Function::bind(slot.delegate)(args...);\n }\n }\n }\n\n template <typename Function, typename Accumulate, typename... Uref>\n void for_each_accumulate(Accumulate&& accumulate, Uref&&... args)\n {\n auto lock = MT_Policy::lock_guard();\n\n for (auto const& slot : MT_Policy::copy_or_ref(connections, lock))\n {\n if (auto observer = MT_Policy::observed(slot.observer))\n {\n accumulate(Function::bind(slot.delegate)(args...));\n }\n }\n }\n\n void move_connections_from(Observer* other) noexcept\n {\n [[maybe_unused]] auto lock = MT_Policy::lock_guard();\n [[maybe_unused]] auto otherLock = other->lock_guard();\n\n connections.clear();\n\n \/\/ Disconnect other from everyone else, and connect them to us instead\n for (auto const& slot : other->connections)\n {\n if (auto observer = MT_Policy::visiting(slot.observer))\n {\n auto obsPtr = static_cast<Observer*>(MT_Policy::unmask(observer));\n obsPtr->remove(slot.delegate);\n obsPtr->insert(slot.delegate, this);\n\n insert(slot.delegate, obsPtr);\n }\n }\n\n other->connections.clear();\n }\n\n \/\/--------------------------------------------------------------------------\n\n public:\n\n void disconnect_all() noexcept\n {\n [[maybe_unused]] auto lock = MT_Policy::lock_guard();\n\n for (auto const& slot : connections)\n {\n if (auto observer = MT_Policy::visiting(slot.observer))\n {\n static_cast<Observer*>(MT_Policy::unmask(observer))->remove(slot.delegate);\n }\n }\n connections.clear();\n }\n\n bool is_empty() const noexcept\n {\n auto lock = MT_Policy::lock_guard();\n\n return connections.empty();\n }\n\n protected:\n\n \/\/ Guideline #4: A base class destructor should be\n \/\/ either public and virtual, or protected and non-virtual.\n ~Observer()\n {\n MT_Policy::before_disconnect_all();\n\n if (!movedFrom)\n disconnect_all();\n }\n\n Observer() noexcept = default;\n\n \/\/ Observer may be movable depending on policy, but should never be copied\n Observer(Observer const&) noexcept = delete;\n Observer& operator= (Observer const&) noexcept = delete;\n\n \/\/ When moving an observer, make sure everyone it's connected to knows about it\n Observer(Observer&& other) noexcept\n {\n move_connections_from(&other);\n other.movedFrom = true;\n }\n\n Observer& operator=(Observer&& other) noexcept\n {\n move_connections_from(&other);\n other.movedFrom = true;\n return *this;\n }\n};\n\n} \/\/ namespace Nano ------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2012-2016 PX4 Development Team. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 * @file load_mon.cpp\n *\n * @author Jonathan Challinger <jonathan@3drobotics.com>\n * @author Julian Oes <julian@oes.ch\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <px4_config.h>\n#include <px4_workqueue.h>\n\n#include <drivers\/drv_hrt.h>\n\n#include <systemlib\/systemlib.h>\n#include <systemlib\/err.h>\n#include <systemlib\/cpuload.h>\n\n#include <uORB\/uORB.h>\n#include <uORB\/topics\/cpuload.h>\n\nextern struct system_load_s system_load;\n\n\nnamespace load_mon\n{\n\nextern \"C\" __EXPORT int load_mon_main(int argc, char *argv[]);\n\n\/\/ Run it at 1 Hz.\nconst unsigned LOAD_MON_INTERVAL_US = 1000000;\n\nclass LoadMon\n{\npublic:\n\tLoadMon();\n\t~LoadMon();\n\n\t\/* Start the load monitoring\n\t *\n\t * @return 0 if successfull, -1 on error. *\/\n\tint start();\n\n\t\/* Stop the load monitoring *\/\n\tvoid stop();\n\n\t\/* Trampoline for the work queue. *\/\n\tstatic void cycle_trampoline(void *arg);\n\n\tbool isRunning() { return _taskIsRunning; }\n\nprivate:\n\t\/* Do a compute and schedule the next cycle. *\/\n\tvoid _cycle();\n\n\t\/* Do a calculation of the CPU load and publish it. *\/\n\tvoid _compute();\n\n\tbool _taskShouldExit;\n\tbool _taskIsRunning;\n\tstruct work_s _work;\n\n\tstruct cpuload_s _cpuload;\n\torb_advert_t _cpuload_pub;\n\thrt_abstime _last_idle_time;\n};\n\n\nLoadMon::LoadMon() :\n\t_taskShouldExit(false),\n\t_taskIsRunning(false),\n\t_work{},\n\t_cpuload{},\n\t_cpuload_pub(nullptr),\n\t_last_idle_time(0)\n{}\n\nLoadMon::~LoadMon()\n{\n\twork_cancel(HPWORK, &_work);\n\t_taskIsRunning = false;\n}\n\nint LoadMon::start()\n{\n\t\/* Schedule a cycle to start things. *\/\n\treturn work_queue(HPWORK, &_work, (worker_t)&LoadMon::cycle_trampoline, this, 0);\n}\n\nvoid LoadMon::stop()\n{\n\t_taskShouldExit = true;\n}\n\nvoid\nLoadMon::cycle_trampoline(void *arg)\n{\n\tLoadMon *dev = reinterpret_cast<LoadMon *>(arg);\n\n\tdev->_cycle();\n}\n\nvoid LoadMon::_cycle()\n{\n\t_taskIsRunning = true;\n\n\t_compute();\n\n\tif (!_taskShouldExit) {\n\t\twork_queue(HPWORK, &_work, (worker_t)&LoadMon::cycle_trampoline, this,\n\t\t\t USEC2TICK(LOAD_MON_INTERVAL_US));\n\t}\n}\n\nvoid LoadMon::_compute()\n{\n\tif (_last_idle_time == 0) {\n\t\t\/* Just get the time in the first iteration *\/\n\t\t_last_idle_time = system_load.tasks[0].total_runtime;\n\t\treturn;\n\t}\n\n\t\/* compute system load *\/\n\tconst hrt_abstime interval_idletime = system_load.tasks[0].total_runtime - _last_idle_time;\n\t_last_idle_time = system_load.tasks[0].total_runtime;\n\n\t_cpuload.timestamp = hrt_absolute_time();\n\t_cpuload.load = 1.0f - (float)interval_idletime \/ (float)LOAD_MON_INTERVAL_US;\n\n\tif (_cpuload_pub == nullptr) {\n\t\t_cpuload_pub = orb_advertise(ORB_ID(cpuload), &_cpuload);\n\n\t} else {\n\t\torb_publish(ORB_ID(cpuload), _cpuload_pub, &_cpuload);\n\t}\n}\n\n\n\n\/**\n * Print the correct usage.\n *\/\nstatic void usage(const char *reason);\n\nstatic void\nusage(const char *reason)\n{\n\tif (reason) {\n\t\tPX4_ERR(\"%s\", reason);\n\t}\n\n\tPX4_INFO(\"usage: load_mon {start|stop|status}\");\n}\n\n\nstatic LoadMon *load_mon = nullptr;\n\n\/**\n * The daemon app only briefly exists to start\n * the background job. The stack size assigned in the\n * Makefile does only apply to this management task.\n *\n * The actual stack size should be set in the call\n * to task_create().\n *\/\nint load_mon_main(int argc, char *argv[])\n{\n\tif (argc < 2) {\n\t\tusage(\"missing command\");\n\t\treturn 1;\n\t}\n\n\tif (!strcmp(argv[1], \"start\")) {\n\n\t\tif (load_mon != nullptr && load_mon->isRunning()) {\n\t\t\tPX4_WARN(\"already running\");\n\t\t\t\/* this is not an error *\/\n\t\t\treturn 0;\n\t\t}\n\n\t\tload_mon = new LoadMon();\n\n\t\t\/\/ Check if alloc worked.\n\t\tif (load_mon == nullptr) {\n\t\t\tPX4_ERR(\"alloc failed\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tint ret = load_mon->start();\n\n\t\tif (ret != 0) {\n\t\t\tPX4_ERR(\"start failed\");\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(argv[1], \"stop\")) {\n\n\t\tif (load_mon == nullptr || load_mon->isRunning()) {\n\t\t\tPX4_WARN(\"not running\");\n\t\t\t\/* this is not an error *\/\n\t\t\treturn 0;\n\t\t}\n\n\t\tload_mon->stop();\n\n\t\t\/\/ Wait for task to die\n\t\tint i = 0;\n\n\t\tdo {\n\t\t\t\/* wait up to 3s *\/\n\t\t\tusleep(100000);\n\n\t\t} while (load_mon->isRunning() && ++i < 30);\n\n\t\tdelete load_mon;\n\t\tload_mon = nullptr;\n\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(argv[1], \"status\")) {\n\t\tif (load_mon != nullptr && load_mon->isRunning()) {\n\t\t\tPX4_INFO(\"running\");\n\n\t\t} else {\n\t\t\tPX4_INFO(\"not running\\n\");\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tusage(\"unrecognized command\");\n\treturn 1;\n}\n\n} \/\/ namespace load_mon\n<commit_msg>load_mon: added missing include<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2012-2016 PX4 Development Team. 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. 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\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * 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; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * 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 * @file load_mon.cpp\n *\n * @author Jonathan Challinger <jonathan@3drobotics.com>\n * @author Julian Oes <julian@oes.ch\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <px4_config.h>\n#include <px4_workqueue.h>\n#include <px4_defines.h>\n\n#include <drivers\/drv_hrt.h>\n\n#include <systemlib\/systemlib.h>\n#include <systemlib\/err.h>\n#include <systemlib\/cpuload.h>\n\n#include <uORB\/uORB.h>\n#include <uORB\/topics\/cpuload.h>\n\nextern struct system_load_s system_load;\n\n\nnamespace load_mon\n{\n\nextern \"C\" __EXPORT int load_mon_main(int argc, char *argv[]);\n\n\/\/ Run it at 1 Hz.\nconst unsigned LOAD_MON_INTERVAL_US = 1000000;\n\nclass LoadMon\n{\npublic:\n\tLoadMon();\n\t~LoadMon();\n\n\t\/* Start the load monitoring\n\t *\n\t * @return 0 if successfull, -1 on error. *\/\n\tint start();\n\n\t\/* Stop the load monitoring *\/\n\tvoid stop();\n\n\t\/* Trampoline for the work queue. *\/\n\tstatic void cycle_trampoline(void *arg);\n\n\tbool isRunning() { return _taskIsRunning; }\n\nprivate:\n\t\/* Do a compute and schedule the next cycle. *\/\n\tvoid _cycle();\n\n\t\/* Do a calculation of the CPU load and publish it. *\/\n\tvoid _compute();\n\n\tbool _taskShouldExit;\n\tbool _taskIsRunning;\n\tstruct work_s _work;\n\n\tstruct cpuload_s _cpuload;\n\torb_advert_t _cpuload_pub;\n\thrt_abstime _last_idle_time;\n};\n\n\nLoadMon::LoadMon() :\n\t_taskShouldExit(false),\n\t_taskIsRunning(false),\n\t_work{},\n\t_cpuload{},\n\t_cpuload_pub(nullptr),\n\t_last_idle_time(0)\n{}\n\nLoadMon::~LoadMon()\n{\n\twork_cancel(HPWORK, &_work);\n\t_taskIsRunning = false;\n}\n\nint LoadMon::start()\n{\n\t\/* Schedule a cycle to start things. *\/\n\treturn work_queue(HPWORK, &_work, (worker_t)&LoadMon::cycle_trampoline, this, 0);\n}\n\nvoid LoadMon::stop()\n{\n\t_taskShouldExit = true;\n}\n\nvoid\nLoadMon::cycle_trampoline(void *arg)\n{\n\tLoadMon *dev = reinterpret_cast<LoadMon *>(arg);\n\n\tdev->_cycle();\n}\n\nvoid LoadMon::_cycle()\n{\n\t_taskIsRunning = true;\n\n\t_compute();\n\n\tif (!_taskShouldExit) {\n\t\twork_queue(HPWORK, &_work, (worker_t)&LoadMon::cycle_trampoline, this,\n\t\t\t USEC2TICK(LOAD_MON_INTERVAL_US));\n\t}\n}\n\nvoid LoadMon::_compute()\n{\n\tif (_last_idle_time == 0) {\n\t\t\/* Just get the time in the first iteration *\/\n\t\t_last_idle_time = system_load.tasks[0].total_runtime;\n\t\treturn;\n\t}\n\n\t\/* compute system load *\/\n\tconst hrt_abstime interval_idletime = system_load.tasks[0].total_runtime - _last_idle_time;\n\t_last_idle_time = system_load.tasks[0].total_runtime;\n\n\t_cpuload.timestamp = hrt_absolute_time();\n\t_cpuload.load = 1.0f - (float)interval_idletime \/ (float)LOAD_MON_INTERVAL_US;\n\n\tif (_cpuload_pub == nullptr) {\n\t\t_cpuload_pub = orb_advertise(ORB_ID(cpuload), &_cpuload);\n\n\t} else {\n\t\torb_publish(ORB_ID(cpuload), _cpuload_pub, &_cpuload);\n\t}\n}\n\n\n\n\/**\n * Print the correct usage.\n *\/\nstatic void usage(const char *reason);\n\nstatic void\nusage(const char *reason)\n{\n\tif (reason) {\n\t\tPX4_ERR(\"%s\", reason);\n\t}\n\n\tPX4_INFO(\"usage: load_mon {start|stop|status}\");\n}\n\n\nstatic LoadMon *load_mon = nullptr;\n\n\/**\n * The daemon app only briefly exists to start\n * the background job. The stack size assigned in the\n * Makefile does only apply to this management task.\n *\n * The actual stack size should be set in the call\n * to task_create().\n *\/\nint load_mon_main(int argc, char *argv[])\n{\n\tif (argc < 2) {\n\t\tusage(\"missing command\");\n\t\treturn 1;\n\t}\n\n\tif (!strcmp(argv[1], \"start\")) {\n\n\t\tif (load_mon != nullptr && load_mon->isRunning()) {\n\t\t\tPX4_WARN(\"already running\");\n\t\t\t\/* this is not an error *\/\n\t\t\treturn 0;\n\t\t}\n\n\t\tload_mon = new LoadMon();\n\n\t\t\/\/ Check if alloc worked.\n\t\tif (load_mon == nullptr) {\n\t\t\tPX4_ERR(\"alloc failed\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tint ret = load_mon->start();\n\n\t\tif (ret != 0) {\n\t\t\tPX4_ERR(\"start failed\");\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(argv[1], \"stop\")) {\n\n\t\tif (load_mon == nullptr || load_mon->isRunning()) {\n\t\t\tPX4_WARN(\"not running\");\n\t\t\t\/* this is not an error *\/\n\t\t\treturn 0;\n\t\t}\n\n\t\tload_mon->stop();\n\n\t\t\/\/ Wait for task to die\n\t\tint i = 0;\n\n\t\tdo {\n\t\t\t\/* wait up to 3s *\/\n\t\t\tusleep(100000);\n\n\t\t} while (load_mon->isRunning() && ++i < 30);\n\n\t\tdelete load_mon;\n\t\tload_mon = nullptr;\n\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(argv[1], \"status\")) {\n\t\tif (load_mon != nullptr && load_mon->isRunning()) {\n\t\t\tPX4_INFO(\"running\");\n\n\t\t} else {\n\t\t\tPX4_INFO(\"not running\\n\");\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tusage(\"unrecognized command\");\n\treturn 1;\n}\n\n} \/\/ namespace load_mon\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright 2009-2013,2015 Centreon\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** For more information : contact@centreon.com\n*\/\n\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/io\/events.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n#include \"com\/centreon\/broker\/neb\/events.hh\"\n#include \"com\/centreon\/broker\/neb\/internal.hh\"\n#include \"com\/centreon\/broker\/neb\/node_events_factory.hh\"\n#include \"com\/centreon\/broker\/io\/protocols.hh\"\n\nusing namespace com::centreon::broker;\n\nstatic unsigned int neb_instances(0);\n\nextern \"C\" {\n \/**\n * Module version symbol. Used to check for version mismatch.\n *\/\n char const* broker_module_version = CENTREON_BROKER_VERSION;\n\n \/**\n * Module deinitialization routine.\n *\/\n void broker_module_deinit() {\n if (!--neb_instances) {\n \/\/ Remove factory.\n io::protocols::instance().unreg(\"node_events\");\n\n \/\/ Remove events.\n io::events::instance().unregister_category(io::events::neb);\n }\n return ;\n }\n\n \/**\n * Module initialization routine.\n *\n * @param[in] arg Configuration object.\n *\/\n void broker_module_init(void const* arg) {\n (void)arg;\n if (!neb_instances++) {\n logging::info(logging::high)\n << \"NEB: module for Centreon Broker \"\n << CENTREON_BROKER_VERSION;\n io::events& e(io::events::instance());\n\n \/\/ Register category.\n int neb_category(e.register_category(\"neb\", io::events::neb));\n if (neb_category != io::events::neb) {\n e.unregister_category(neb_category);\n --neb_instances;\n throw (exceptions::msg() << \"NEB: category \" << io::events::neb\n << \" is already registered whereas it should be \"\n << \"reserved for the NEB module\");\n }\n\n \/\/ Register events.\n {\n e.register_event(\n io::events::neb,\n neb::de_acknowledgement,\n io::event_info(\n \"acknowledgement\",\n &neb::acknowledgement::operations,\n neb::acknowledgement::entries,\n \"rt_acknowledgements\",\n \"acknowledgements\"));\n e.register_event(\n io::events::neb,\n neb::de_comment,\n io::event_info(\n \"comment\",\n &neb::comment::operations,\n neb::comment::entries,\n \"\",\n \"comments\"));\n e.register_event(\n io::events::neb,\n neb::de_custom_variable,\n io::event_info(\n \"custom_variable\",\n &neb::custom_variable::operations,\n neb::custom_variable::entries,\n \"rt_customvariables\",\n \"customvariables\"));\n e.register_event(\n io::events::neb,\n neb::de_custom_variable_status,\n io::event_info(\n \"custom_variable_status\",\n &neb::custom_variable_status::operations,\n neb::custom_variable_status::entries,\n \"rt_customvariables\",\n \"customvariables\"));\n e.register_event(\n io::events::neb,\n neb::de_downtime,\n io::event_info(\n \"downtime\",\n &neb::downtime::operations,\n neb::downtime::entries,\n \"rt_downtimes\",\n \"downtimes\"));\n e.register_event(\n io::events::neb,\n neb::de_event_handler,\n io::event_info(\n \"event_handler\",\n &neb::event_handler::operations,\n neb::event_handler::entries,\n \"rt_eventhandlers\",\n \"eventhandlers\"));\n e.register_event(\n io::events::neb,\n neb::de_flapping_status,\n io::event_info(\n \"flapping_status\",\n &neb::flapping_status::operations,\n neb::flapping_status::entries,\n \"rt_flappingstatuses\",\n \"flappingstatuses\"));\n e.register_event(\n io::events::neb,\n neb::de_host_check,\n io::event_info(\n \"host_check\",\n &neb::host_check::operations,\n neb::host_check::entries,\n \"rt_hosts\",\n \"hosts\"));\n e.register_event(\n io::events::neb,\n neb::de_host_dependency,\n io::event_info(\n \"host_dependency\",\n &neb::host_dependency::operations,\n neb::host_dependency::entries,\n \"rt_hosts_hosts_dependencies\",\n \"hosts_hosts_dependencies\"));\n e.register_event(\n io::events::neb,\n neb::de_host,\n io::event_info(\n \"host\",\n &neb::host::operations,\n neb::host::entries,\n \"rt_hosts\",\n \"hosts\"));\n e.register_event(\n io::events::neb,\n neb::de_host_group,\n io::event_info(\n \"host_group\",\n &neb::host_group::operations,\n neb::host_group::entries,\n \"\",\n \"hostgroups\"));\n e.register_event(\n io::events::neb,\n neb::de_host_group_member,\n io::event_info(\n \"host_group_member\",\n &neb::host_group_member::operations,\n neb::host_group_member::entries,\n \"\",\n \"hosts_hostgroups\"));\n e.register_event(\n io::events::neb,\n neb::de_host_parent,\n io::event_info(\n \"host_parent\",\n &neb::host_parent::operations,\n neb::host_parent::entries,\n \"rt_hosts_hosts_parents\",\n \"hosts_hosts_parents\"));\n e.register_event(\n io::events::neb,\n neb::de_host_status,\n io::event_info(\n \"host_status\",\n &neb::host_status::operations,\n neb::host_status::entries,\n \"rt_hosts\",\n \"hosts\"));\n e.register_event(\n io::events::neb,\n neb::de_instance,\n io::event_info(\n \"instance\",\n &neb::instance::operations,\n neb::instance::entries,\n \"rt_instances\",\n \"instances\"));\n e.register_event(\n io::events::neb,\n neb::de_instance_status,\n io::event_info(\n \"instance_status\",\n &neb::instance_status::operations,\n neb::instance_status::entries,\n \"rt_instances\",\n \"instances\"));\n e.register_event(\n io::events::neb,\n neb::de_log_entry,\n io::event_info(\n \"log_entry\",\n &neb::log_entry::operations,\n neb::log_entry::entries,\n \"log_logs\",\n \"logs\"));\n e.register_event(\n io::events::neb,\n neb::de_module,\n io::event_info(\n \"module\",\n &neb::module::operations,\n neb::module::entries,\n \"rt_modules\",\n \"modules\"));\n e.register_event(\n io::events::neb,\n neb::de_service_check,\n io::event_info(\n \"service_check\",\n &neb::service_check::operations,\n neb::service_check::entries,\n \"rt_services\",\n \"services\"));\n e.register_event(\n io::events::neb,\n neb::de_service_dependency,\n io::event_info(\n \"service_dependency\",\n &neb::service_dependency::operations,\n neb::service_dependency::entries,\n \"rt_services_services_dependencies\",\n \"services_services_dependencies\"));\n e.register_event(\n io::events::neb,\n neb::de_service,\n io::event_info(\n \"service\",\n &neb::service::operations,\n neb::service::entries,\n \"rt_services\",\n \"services\"));\n e.register_event(\n io::events::neb,\n neb::de_service_group,\n io::event_info(\n \"service_group\",\n &neb::service_group::operations,\n neb::service_group::entries,\n \"\",\n \"servicegroups\"));\n e.register_event(\n io::events::neb,\n neb::de_service_group_member,\n io::event_info(\n \"service_group_member\",\n &neb::service_group_member::operations,\n neb::service_group_member::entries,\n \"\",\n \"services_servicegroups\"));\n e.register_event(\n io::events::neb,\n neb::de_service_status,\n io::event_info(\n \"service_status\",\n &neb::service_status::operations,\n neb::service_status::entries,\n \"rt_services\",\n \"services\"));\n e.register_event(\n io::events::neb,\n neb::de_service_status,\n io::event_info(\n \"instance_configuration\",\n &neb::instance_configuration::operations,\n neb::instance_configuration::entries));\n }\n\n \/\/ Register neb layer.\n io::protocols::instance().reg(\n \"node_events\",\n neb::node_events_factory(),\n 1,\n 7);\n }\n\n return ;\n }\n}\n<commit_msg>Neb: fix instance configuration registering.<commit_after>\/*\n** Copyright 2009-2013,2015 Centreon\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** For more information : contact@centreon.com\n*\/\n\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/io\/events.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n#include \"com\/centreon\/broker\/neb\/events.hh\"\n#include \"com\/centreon\/broker\/neb\/internal.hh\"\n#include \"com\/centreon\/broker\/neb\/node_events_factory.hh\"\n#include \"com\/centreon\/broker\/io\/protocols.hh\"\n\nusing namespace com::centreon::broker;\n\nstatic unsigned int neb_instances(0);\n\nextern \"C\" {\n \/**\n * Module version symbol. Used to check for version mismatch.\n *\/\n char const* broker_module_version = CENTREON_BROKER_VERSION;\n\n \/**\n * Module deinitialization routine.\n *\/\n void broker_module_deinit() {\n if (!--neb_instances) {\n \/\/ Remove factory.\n io::protocols::instance().unreg(\"node_events\");\n\n \/\/ Remove events.\n io::events::instance().unregister_category(io::events::neb);\n }\n return ;\n }\n\n \/**\n * Module initialization routine.\n *\n * @param[in] arg Configuration object.\n *\/\n void broker_module_init(void const* arg) {\n (void)arg;\n if (!neb_instances++) {\n logging::info(logging::high)\n << \"NEB: module for Centreon Broker \"\n << CENTREON_BROKER_VERSION;\n io::events& e(io::events::instance());\n\n \/\/ Register category.\n int neb_category(e.register_category(\"neb\", io::events::neb));\n if (neb_category != io::events::neb) {\n e.unregister_category(neb_category);\n --neb_instances;\n throw (exceptions::msg() << \"NEB: category \" << io::events::neb\n << \" is already registered whereas it should be \"\n << \"reserved for the NEB module\");\n }\n\n \/\/ Register events.\n {\n e.register_event(\n io::events::neb,\n neb::de_acknowledgement,\n io::event_info(\n \"acknowledgement\",\n &neb::acknowledgement::operations,\n neb::acknowledgement::entries,\n \"rt_acknowledgements\",\n \"acknowledgements\"));\n e.register_event(\n io::events::neb,\n neb::de_comment,\n io::event_info(\n \"comment\",\n &neb::comment::operations,\n neb::comment::entries,\n \"\",\n \"comments\"));\n e.register_event(\n io::events::neb,\n neb::de_custom_variable,\n io::event_info(\n \"custom_variable\",\n &neb::custom_variable::operations,\n neb::custom_variable::entries,\n \"rt_customvariables\",\n \"customvariables\"));\n e.register_event(\n io::events::neb,\n neb::de_custom_variable_status,\n io::event_info(\n \"custom_variable_status\",\n &neb::custom_variable_status::operations,\n neb::custom_variable_status::entries,\n \"rt_customvariables\",\n \"customvariables\"));\n e.register_event(\n io::events::neb,\n neb::de_downtime,\n io::event_info(\n \"downtime\",\n &neb::downtime::operations,\n neb::downtime::entries,\n \"rt_downtimes\",\n \"downtimes\"));\n e.register_event(\n io::events::neb,\n neb::de_event_handler,\n io::event_info(\n \"event_handler\",\n &neb::event_handler::operations,\n neb::event_handler::entries,\n \"rt_eventhandlers\",\n \"eventhandlers\"));\n e.register_event(\n io::events::neb,\n neb::de_flapping_status,\n io::event_info(\n \"flapping_status\",\n &neb::flapping_status::operations,\n neb::flapping_status::entries,\n \"rt_flappingstatuses\",\n \"flappingstatuses\"));\n e.register_event(\n io::events::neb,\n neb::de_host_check,\n io::event_info(\n \"host_check\",\n &neb::host_check::operations,\n neb::host_check::entries,\n \"rt_hosts\",\n \"hosts\"));\n e.register_event(\n io::events::neb,\n neb::de_host_dependency,\n io::event_info(\n \"host_dependency\",\n &neb::host_dependency::operations,\n neb::host_dependency::entries,\n \"rt_hosts_hosts_dependencies\",\n \"hosts_hosts_dependencies\"));\n e.register_event(\n io::events::neb,\n neb::de_host,\n io::event_info(\n \"host\",\n &neb::host::operations,\n neb::host::entries,\n \"rt_hosts\",\n \"hosts\"));\n e.register_event(\n io::events::neb,\n neb::de_host_group,\n io::event_info(\n \"host_group\",\n &neb::host_group::operations,\n neb::host_group::entries,\n \"\",\n \"hostgroups\"));\n e.register_event(\n io::events::neb,\n neb::de_host_group_member,\n io::event_info(\n \"host_group_member\",\n &neb::host_group_member::operations,\n neb::host_group_member::entries,\n \"\",\n \"hosts_hostgroups\"));\n e.register_event(\n io::events::neb,\n neb::de_host_parent,\n io::event_info(\n \"host_parent\",\n &neb::host_parent::operations,\n neb::host_parent::entries,\n \"rt_hosts_hosts_parents\",\n \"hosts_hosts_parents\"));\n e.register_event(\n io::events::neb,\n neb::de_host_status,\n io::event_info(\n \"host_status\",\n &neb::host_status::operations,\n neb::host_status::entries,\n \"rt_hosts\",\n \"hosts\"));\n e.register_event(\n io::events::neb,\n neb::de_instance,\n io::event_info(\n \"instance\",\n &neb::instance::operations,\n neb::instance::entries,\n \"rt_instances\",\n \"instances\"));\n e.register_event(\n io::events::neb,\n neb::de_instance_status,\n io::event_info(\n \"instance_status\",\n &neb::instance_status::operations,\n neb::instance_status::entries,\n \"rt_instances\",\n \"instances\"));\n e.register_event(\n io::events::neb,\n neb::de_log_entry,\n io::event_info(\n \"log_entry\",\n &neb::log_entry::operations,\n neb::log_entry::entries,\n \"log_logs\",\n \"logs\"));\n e.register_event(\n io::events::neb,\n neb::de_module,\n io::event_info(\n \"module\",\n &neb::module::operations,\n neb::module::entries,\n \"rt_modules\",\n \"modules\"));\n e.register_event(\n io::events::neb,\n neb::de_service_check,\n io::event_info(\n \"service_check\",\n &neb::service_check::operations,\n neb::service_check::entries,\n \"rt_services\",\n \"services\"));\n e.register_event(\n io::events::neb,\n neb::de_service_dependency,\n io::event_info(\n \"service_dependency\",\n &neb::service_dependency::operations,\n neb::service_dependency::entries,\n \"rt_services_services_dependencies\",\n \"services_services_dependencies\"));\n e.register_event(\n io::events::neb,\n neb::de_service,\n io::event_info(\n \"service\",\n &neb::service::operations,\n neb::service::entries,\n \"rt_services\",\n \"services\"));\n e.register_event(\n io::events::neb,\n neb::de_service_group,\n io::event_info(\n \"service_group\",\n &neb::service_group::operations,\n neb::service_group::entries,\n \"\",\n \"servicegroups\"));\n e.register_event(\n io::events::neb,\n neb::de_service_group_member,\n io::event_info(\n \"service_group_member\",\n &neb::service_group_member::operations,\n neb::service_group_member::entries,\n \"\",\n \"services_servicegroups\"));\n e.register_event(\n io::events::neb,\n neb::de_service_status,\n io::event_info(\n \"service_status\",\n &neb::service_status::operations,\n neb::service_status::entries,\n \"rt_services\",\n \"services\"));\n e.register_event(\n io::events::neb,\n neb::de_instance_configuration,\n io::event_info(\n \"instance_configuration\",\n &neb::instance_configuration::operations,\n neb::instance_configuration::entries));\n }\n\n \/\/ Register neb layer.\n io::protocols::instance().reg(\n \"node_events\",\n neb::node_events_factory(),\n 1,\n 7);\n }\n\n return ;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*! @file\r\n @brief ネット・メイン @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/renesas.hpp\"\r\n#include \"common\/ip_adrs.hpp\"\r\n#include \"common\/dhcp_client.hpp\"\r\n#include \"net2\/ethernet.hpp\"\r\n#include \"net2\/net_st.hpp\"\r\n\r\n#define NET_MAIN_DEBUG\r\n\r\nnamespace net {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief net_main テンプレート・クラス\r\n\t\t@param[in]\tETHD\tイーサーネット・ドライバー\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <class ETHD>\r\n\tclass net_main {\r\n\tpublic:\r\n\t\ttypedef ethernet<ETHD> ETHERNET;\r\n\r\n\tprivate:\r\n#ifndef NET_MAIN_DEBUG\r\n\t\ttypedef utils::null_format debug_format;\r\n#else\r\n\t\ttypedef utils::format debug_format;\r\n#endif\r\n\r\n\t\tenum class task : uint8_t {\r\n\t\t\twait_link,\t\/\/ リンクアップを待つ\r\n\t\t\twait_dhcp,\t\/\/ DHCP IP アドレスの取得を待つ\r\n\t\t\tmain_init,\t\/\/ メイン初期化\r\n\t\t\tmain_loop,\t\/\/ メインループ\r\n\t\t\tstall,\t\t\/\/ ストール\r\n\t\t};\r\n\r\n\t\tETHD&\t\tethd_;\r\n\r\n\t\ttypedef dhcp_client<ETHD> DHCP;\r\n\t\tDHCP\t\tdhcp_;\r\n\r\n\t\tETHERNET\tethernet_;\r\n\r\n\t\ttask\t\ttask_;\r\n\r\n\t\tuint8_t\t\tlink_interval_;\r\n\t\tuint8_t\t\tstall_loop_;\r\n\r\n\t\tvoid set_tcpudp_env_()\r\n\t\t{\r\n\t\t\tconst DHCP_INFO& info = dhcp_.get_info();\r\n\t\t\tinfo.list();\r\n\t\t\tethernet_.at_info().ip.set(info.ipaddr);\r\n\t\t\tethernet_.at_info().mask.set(info.maskaddr);\r\n\t\t\tethernet_.at_info().gw.set(info.gwaddr);\r\n\t\t\tethernet_.at_info().dns.set(info.dnsaddr);\r\n\t\t\tethernet_.at_info().dns2.set(info.dnsaddr2);\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t\t@param[in]\tETHD\tイーサーネット・ドライバー・クラス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tnet_main(ETHD& ethd) : ethd_(ethd), dhcp_(ethd), ethernet_(ethd),\r\n\t\t\ttask_(task::wait_link), link_interval_(0), stall_loop_(0)\r\n\t\t\t{\r\n\t\t\t\tethernet_.at_info().ip.set(192, 168, 3, 20);\r\n\t\t\t\tethernet_.at_info().mask.set(255, 255, 255, 0);\r\n\t\t\t\tethernet_.at_info().gw.set(192, 168, 3, 1);\r\n\t\t\t\tethernet_.at_info().dns.set(192, 168, 3, 1);\r\n\t\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ネット情報を参照\r\n\t\t\t@return ネット情報\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst net_info& get_info() const { return ethernet_.get_info(); }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief イーサーネットの参照\r\n\t\t\t@return\tインサーネット\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tETHERNET& at_ethernet() { return ethernet_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 開始\r\n\t\t\t@param[in]\tmac\tインサーネット・コントローラー MAC アドレス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool start(const uint8_t* mac)\r\n\t\t{\r\n\t\t\tbool ret = ethd_.open(mac);\r\n\t\t\tif(ret) {\r\n\t\t\t\tdebug_format(\"net_main: start OK\\n\");\r\n\t\t\t\tlink_interval_ = 0;\r\n\t\t\t\tstd::memcpy(ethernet_.at_info().mac, ethd_.get_mac(), 6);\r\n\t\t\t\ttask_ = task::wait_link;\r\n\t\t\t} else {\r\n\t\t\t\tdebug_format(\"net_main: start NG\\n\");\r\n\t\t\t\ttask_ = task::stall;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief プロセス(割り込みタスク)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid process()\r\n\t\t{\r\n\t\t\tif(task_ == task::main_loop) {\r\n\t\t\t\tethernet_.process();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief サービス(10ミリ秒毎に呼び出す)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid service()\r\n\t\t{\r\n\t\t\tethernet_.service();\r\n\r\n\t\t\tswitch(task_) {\r\n\r\n\t\t\tcase task::wait_link:\r\n\t\t\t\t{\r\n\t\t\t\t\tif(link_interval_ >= 100) {\r\n\t\t\t\t\t\tethd_.polling_link_status();\r\n\t\t\t\t\t\tlink_interval_ = 0;\r\n\t\t\t\t\t\tdebug_format(\"net_main: PHY wait link loop\\n\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\t++link_interval_;\r\n\r\n\t\t\t\t\tbool link = ethd_.service_link();\r\n\t\t\t\t\tif(link) {\r\n\t\t\t\t\t\tdhcp_.start();\r\n\t\t\t\t\t\ttask_ = task::wait_dhcp;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase task::wait_dhcp:\r\n\t\t\t\tdhcp_.service();\r\n\t\t\t\tif(dhcp_.get_info().state == DHCP_INFO::state_t::collect) {\r\n\t\t\t\t\tdebug_format(\"net_main: DHCP Collect\\n\");\r\n\t\t\t\t\tset_tcpudp_env_();\r\n\t\t\t\t\ttask_ = task::main_init;\r\n\t\t\t\t} else if(dhcp_.get_info().state == DHCP_INFO::state_t::timeout) {\r\n\t\t\t\t\tdebug_format(\"net_main: DHCP Timeout (setup for fixed IP)\\n\");\r\n\t\t\t\t\ttask_ = task::main_init;\r\n\t\t\t\t} else if(dhcp_.get_info().state == DHCP_INFO::state_t::error) {\r\n\t\t\t\t\tdebug_format(\"net_main: DHCP Error\\n\");\r\n\t\t\t\t\ttask_ = task::stall;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase task::main_init:\r\n\t\t\t\tethd_.service_link();\r\n\r\n\r\n\t\t\t\t\/\/ test code\r\n\t\t\t\t{\r\n\r\n\t\t\t\t}\r\n\r\n\r\n\r\n\t\t\t\ttask_ = task::main_loop;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase task::main_loop:\r\n\t\t\t\tethd_.service_link();\r\n\r\n\t\t\t\tif(link_interval_ >= 100) {\r\n\t\t\t\t\tethd_.polling_link_status();\r\n\t\t\t\t\tlink_interval_ = 0;\r\n\t\t\t\t}\r\n\t\t\t\t++link_interval_;\r\n\r\n\t\t\t\tif(!ethd_.get_stat().link_) {\r\n\t\t\t\t\ttask_ = task::wait_link;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase task::stall:\r\n\t\t\t\tif(stall_loop_ >= 250) {\r\n\t\t\t\t\tdebug_format(\"net_main: stall\\n\");\r\n\t\t\t\t\tstall_loop_ = 0;\r\n\t\t\t\t}\r\n\t\t\t\t++stall_loop_;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tdefault:\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief メインを確認する\r\n\t\t\t@return 「true」なら、リンク\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool check_main() const { return task_ == task::main_loop; }\r\n\t};\r\n}\r\n<commit_msg>add UDP test code<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*! @file\r\n @brief ネット・メイン @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/renesas.hpp\"\r\n#include \"common\/ip_adrs.hpp\"\r\n#include \"common\/dhcp_client.hpp\"\r\n#include \"net2\/ethernet.hpp\"\r\n#include \"net2\/net_st.hpp\"\r\n\r\n#define NET_MAIN_DEBUG\r\n\r\nnamespace net {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief net_main テンプレート・クラス\r\n\t\t@param[in]\tETHD\tイーサーネット・ドライバー\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <class ETHD>\r\n\tclass net_main {\r\n\tpublic:\r\n\t\ttypedef ethernet<ETHD> ETHERNET;\r\n\r\n\tprivate:\r\n#ifndef NET_MAIN_DEBUG\r\n\t\ttypedef utils::null_format debug_format;\r\n#else\r\n\t\ttypedef utils::format debug_format;\r\n#endif\r\n\r\n\t\tenum class task : uint8_t {\r\n\t\t\twait_link,\t\/\/ リンクアップを待つ\r\n\t\t\twait_dhcp,\t\/\/ DHCP IP アドレスの取得を待つ\r\n\t\t\tmain_init,\t\/\/ メイン初期化\r\n\t\t\tmain_loop,\t\/\/ メインループ\r\n\t\t\tstall,\t\t\/\/ ストール\r\n\t\t};\r\n\r\n\t\tETHD&\t\tethd_;\r\n\r\n\t\ttypedef dhcp_client<ETHD> DHCP;\r\n\t\tDHCP\t\tdhcp_;\r\n\r\n\t\tETHERNET\tethernet_;\r\n\r\n\t\ttask\t\ttask_;\r\n\r\n\t\tuint8_t\t\tlink_interval_;\r\n\t\tuint8_t\t\tstall_loop_;\r\n\r\n\t\tint\t\t\tudp_dsc_;\r\n\r\n\t\tvoid set_tcpudp_env_()\r\n\t\t{\r\n\t\t\tconst DHCP_INFO& info = dhcp_.get_info();\r\n\t\t\tinfo.list();\r\n\t\t\tethernet_.at_info().ip.set(info.ipaddr);\r\n\t\t\tethernet_.at_info().mask.set(info.maskaddr);\r\n\t\t\tethernet_.at_info().gw.set(info.gwaddr);\r\n\t\t\tethernet_.at_info().dns.set(info.dnsaddr);\r\n\t\t\tethernet_.at_info().dns2.set(info.dnsaddr2);\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t\t@param[in]\tETHD\tイーサーネット・ドライバー・クラス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tnet_main(ETHD& ethd) : ethd_(ethd), dhcp_(ethd), ethernet_(ethd),\r\n\t\t\ttask_(task::wait_link), link_interval_(0), stall_loop_(0),\r\n\t\t\tudp_dsc_(-1)\r\n\t\t\t{\r\n\t\t\t\tethernet_.at_info().ip.set(192, 168, 3, 20);\r\n\t\t\t\tethernet_.at_info().mask.set(255, 255, 255, 0);\r\n\t\t\t\tethernet_.at_info().gw.set(192, 168, 3, 1);\r\n\t\t\t\tethernet_.at_info().dns.set(192, 168, 3, 1);\r\n\t\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ネット情報を参照\r\n\t\t\t@return ネット情報\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst net_info& get_info() const { return ethernet_.get_info(); }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief イーサーネットの参照\r\n\t\t\t@return\tインサーネット\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tETHERNET& at_ethernet() { return ethernet_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 開始\r\n\t\t\t@param[in]\tmac\tインサーネット・コントローラー MAC アドレス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool start(const uint8_t* mac)\r\n\t\t{\r\n\t\t\tbool ret = ethd_.open(mac);\r\n\t\t\tif(ret) {\r\n\t\t\t\tdebug_format(\"net_main: start OK\\n\");\r\n\t\t\t\tlink_interval_ = 0;\r\n\t\t\t\tstd::memcpy(ethernet_.at_info().mac, ethd_.get_mac(), 6);\r\n\t\t\t\ttask_ = task::wait_link;\r\n\t\t\t} else {\r\n\t\t\t\tdebug_format(\"net_main: start NG\\n\");\r\n\t\t\t\ttask_ = task::stall;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief プロセス(割り込みタスク)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid process()\r\n\t\t{\r\n\t\t\tif(task_ == task::main_loop) {\r\n\t\t\t\tethernet_.process();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief サービス(10ミリ秒毎に呼び出す)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid service()\r\n\t\t{\r\n\t\t\tethernet_.service();\r\n\r\n\t\t\tswitch(task_) {\r\n\r\n\t\t\tcase task::wait_link:\r\n\t\t\t\t{\r\n\t\t\t\t\tif(link_interval_ >= 100) {\r\n\t\t\t\t\t\tethd_.polling_link_status();\r\n\t\t\t\t\t\tlink_interval_ = 0;\r\n\t\t\t\t\t\tdebug_format(\"net_main: PHY wait link loop\\n\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\t++link_interval_;\r\n\r\n\t\t\t\t\tbool link = ethd_.service_link();\r\n\t\t\t\t\tif(link) {\r\n\t\t\t\t\t\tdhcp_.start();\r\n\t\t\t\t\t\ttask_ = task::wait_dhcp;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase task::wait_dhcp:\r\n\t\t\t\tdhcp_.service();\r\n\t\t\t\tif(dhcp_.get_info().state == DHCP_INFO::state_t::collect) {\r\n\t\t\t\t\tdebug_format(\"net_main: DHCP Collect\\n\");\r\n\t\t\t\t\tset_tcpudp_env_();\r\n\t\t\t\t\ttask_ = task::main_init;\r\n\t\t\t\t} else if(dhcp_.get_info().state == DHCP_INFO::state_t::timeout) {\r\n\t\t\t\t\tdebug_format(\"net_main: DHCP Timeout (setup for fixed IP)\\n\");\r\n\t\t\t\t\ttask_ = task::main_init;\r\n\t\t\t\t} else if(dhcp_.get_info().state == DHCP_INFO::state_t::error) {\r\n\t\t\t\t\tdebug_format(\"net_main: DHCP Error\\n\");\r\n\t\t\t\t\ttask_ = task::stall;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase task::main_init:\r\n\t\t\t\tethd_.service_link();\r\n\r\n\r\n\t\t\t\t\/\/ test code\r\n\t\t\t\t{\r\n\t\t\t\t\tauto& ipv4 = ethernet_.at_ipv4();\r\n\t\t\t\t\tauto& udp = ipv4.at_udp();\r\n\r\n\t\t\t\t\tudp_dsc_ = udp.open(ip_adrs(), 3000, 3000);\r\n\r\n\t\t\t\t}\r\n\r\n\r\n\r\n\t\t\t\ttask_ = task::main_loop;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase task::main_loop:\r\n\t\t\t\tethd_.service_link();\r\n\r\n\t\t\t\tif(link_interval_ >= 100) {\r\n\t\t\t\t\tethd_.polling_link_status();\r\n\t\t\t\t\tlink_interval_ = 0;\r\n\t\t\t\t}\r\n\t\t\t\t++link_interval_;\r\n\r\n\t\t\t\tif(!ethd_.get_stat().link_) {\r\n\t\t\t\t\ttask_ = task::wait_link;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase task::stall:\r\n\t\t\t\tif(stall_loop_ >= 250) {\r\n\t\t\t\t\tdebug_format(\"net_main: stall\\n\");\r\n\t\t\t\t\tstall_loop_ = 0;\r\n\t\t\t\t}\r\n\t\t\t\t++stall_loop_;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tdefault:\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief メインを確認する\r\n\t\t\t@return 「true」なら、リンク\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool check_main() const { return task_ == task::main_loop; }\r\n\t};\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"oddlib\/compressiontype3ae.hpp\"\n#include \"oddlib\/stream.hpp\"\n#include \"logger.hpp\"\n#include <vector>\n#include <cassert>\n\nstatic Uint16 ReadUint16(Oddlib::IStream& stream)\n{\n Uint16 ret = 0;\n stream.ReadUInt16(ret);\n return ret;\n}\n\nstatic Uint32 ReadUint32(Oddlib::IStream& stream)\n{\n Uint32 ret = 0;\n stream.ReadUInt32(ret);\n return ret;\n}\n\ntemplate<typename T>\nstatic void ReadNextSource(Oddlib::IStream& stream, int& control_byte, T& dstIndex)\n{\n if (control_byte)\n {\n if (control_byte == 0xE)\n {\n control_byte = 0x1Eu;\n dstIndex |= ReadUint16(stream) << 14;\n }\n }\n else\n {\n dstIndex = ReadUint32(stream);\n control_byte = 0x20u;\n }\n control_byte -= 6;\n}\n\n\nnamespace Oddlib\n{\n std::vector<Uint8> CompressionType3Ae::Decompress(IStream& stream, Uint32 size, Uint32 w, Uint32 h)\n {\n LOG_INFO(\"Data size is \" << size);\n\n \/\/ TODO: Shouldn't need to be * 4\n std::vector< unsigned char > buffer(w*h * 4);\n \n int dstPos = 0;\n int control_byte = 0;\n\n int width = ReadUint16(stream);\n int height = ReadUint16(stream);\n if (height > 0)\n {\n int dstIndex = 0;\n do\n {\n int columnNumber = 0;\n while (columnNumber < width)\n {\n ReadNextSource(stream, control_byte, dstIndex);\n\n const unsigned char blackBytes = dstIndex & 0x3F;\n \n unsigned int srcByte = (unsigned int)dstIndex >> 6;\n\n\n const int bytesToWrite = blackBytes + columnNumber;\n if (blackBytes > 0)\n {\n const unsigned int doubleBBytes = (unsigned int)blackBytes >> 2;\n for (auto i = 0u; i < 4 * doubleBBytes; i++)\n {\n buffer[dstPos + i] = 0;\n }\n\n for (int i = blackBytes & 3; i; --i)\n {\n buffer[(dstPos + 4 * doubleBBytes) + i] = 0;\n }\n dstPos += blackBytes;\n }\n\n ReadNextSource(stream, control_byte, srcByte);\n\n const unsigned char bytes = srcByte & 0x3F;\n dstIndex = srcByte >> 6;\n\n columnNumber = bytes + bytesToWrite;\n if (bytes > 0)\n {\n int byteCount = bytes;\n do\n {\n ReadNextSource(stream, control_byte, dstIndex);\n \n const char dstByte = dstIndex & 0x3F;\n dstIndex = (unsigned int)dstIndex >> 6;\n\n buffer[dstPos] = dstByte;\n dstPos++;\n --byteCount;\n } while (byteCount);\n }\n }\n if (columnNumber & 3)\n {\n do\n {\n ++dstPos;\n ++columnNumber;\n } while (columnNumber & 3);\n }\n } while (height-- != 1);\n }\n\n return buffer;\n }\n}\n<commit_msg>Remove the \"blacking out\" part the of decompression algorithm since our buffers are init'ed to 0's. Its easier to do this then check the \"blacking out\" part of the algorithm is 100% correct<commit_after>#include \"oddlib\/compressiontype3ae.hpp\"\n#include \"oddlib\/stream.hpp\"\n#include \"logger.hpp\"\n#include <vector>\n#include <cassert>\n\nstatic Uint16 ReadUint16(Oddlib::IStream& stream)\n{\n Uint16 ret = 0;\n stream.ReadUInt16(ret);\n return ret;\n}\n\nstatic Uint32 ReadUint32(Oddlib::IStream& stream)\n{\n Uint32 ret = 0;\n stream.ReadUInt32(ret);\n return ret;\n}\n\ntemplate<typename T>\nstatic void ReadNextSource(Oddlib::IStream& stream, int& control_byte, T& dstIndex)\n{\n if (control_byte)\n {\n if (control_byte == 0xE)\n {\n control_byte = 0x1Eu;\n dstIndex |= ReadUint16(stream) << 14;\n }\n }\n else\n {\n dstIndex = ReadUint32(stream);\n control_byte = 0x20u;\n }\n control_byte -= 6;\n}\n\n\nnamespace Oddlib\n{\n std::vector<Uint8> CompressionType3Ae::Decompress(IStream& stream, Uint32 size, Uint32 w, Uint32 h)\n {\n LOG_INFO(\"Data size is \" << size);\n\n \/\/ TODO: Shouldn't need to be * 4\n std::vector< unsigned char > buffer(w*h * 4);\n \n int dstPos = 0;\n int control_byte = 0;\n\n int width = ReadUint16(stream);\n int height = ReadUint16(stream);\n if (height > 0)\n {\n unsigned int dstIndex = 0;\n do\n {\n int columnNumber = 0;\n while (columnNumber < width)\n {\n ReadNextSource(stream, control_byte, dstIndex);\n\n const unsigned char blackBytes = dstIndex & 0x3F;\n unsigned int srcByte = dstIndex >> 6;\n\n \/\/ Here the \"black\" bytes would be written, since our buffers are inited to zeros we\n \/\/ don't have to worry about getting this bit correct\n const int bytesToWrite = blackBytes + columnNumber;\n \n \/\/ Pretend we just blacked out an area\n dstPos += blackBytes;\n ReadNextSource(stream, control_byte, srcByte);\n\n const unsigned char bytes = srcByte & 0x3F;\n dstIndex = srcByte >> 6;\n\n columnNumber = bytes + bytesToWrite;\n if (bytes > 0)\n {\n int byteCount = bytes;\n do\n {\n ReadNextSource(stream, control_byte, dstIndex);\n \n const char dstByte = dstIndex & 0x3F;\n dstIndex = dstIndex >> 6;\n\n buffer[dstPos] = dstByte;\n dstPos++;\n --byteCount;\n } while (byteCount);\n }\n }\n if (columnNumber & 3)\n {\n do\n {\n ++dstPos;\n ++columnNumber;\n } while (columnNumber & 3);\n }\n } while (height-- != 1);\n }\n\n return buffer;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2008-2016 The Communi Project\n\n You may use this file under the terms of BSD license as follows:\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the copyright holder 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 \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY 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\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"gnomeplugin.h\"\n#include \"gnomemenu.h\"\n#include \"x11helper.h\"\n#include \"themeinfo.h\"\n#include <QSystemTrayIcon>\n#include <QMainWindow>\n#include <QAction>\n\nGnomePlugin::GnomePlugin(QObject* parent) : QObject(parent)\n{\n d.mute = 0;\n d.window = 0;\n}\n\nvoid GnomePlugin::windowCreated(QMainWindow* window)\n{\n d.window = window;\n\n#ifdef COMMUNI_HAVE_GIO\n GnomeMenu *section1 = new GnomeMenu(window);\n section1->addSimpleItem(\"showConnect\", \"Connect...\", window, \"doConnect\");\n section1->addSimpleItem(\"showSettings\", \"Settings\", window, \"showSettings\");\n section1->addSimpleItem(\"showHelp\", \"Help\", window, \"showHelp\");\n\n GnomeMenu *section2 = new GnomeMenu(window);\n section2->addToggleItem(\"toggleMute\", \"Mute\", d.mute->isChecked(), d.mute, \"toggle\");\n\n GnomeMenu *section3 = new GnomeMenu(window);\n section3->addSimpleItem(\"quit\", \"Quit\", window, \"close\");\n\n GnomeMenu *builder = new GnomeMenu(window);\n builder->addSection(section1);\n builder->addSection(section2);\n builder->addSection(section3);\n builder->setMenuToWindow(window->winId(), \"\/org\/communi\/gnomeintegration\");\n#endif \/\/ COMMUNI_HAVE_GIO\n}\n\nvoid GnomePlugin::themeChanged(const ThemeInfo& theme)\n{\n QByteArray gtkTheme = theme.gtkTheme().toUtf8();\n X11Helper::setWindowProperty(d.window->winId(), \"_GTK_THEME_VARIANT\", gtkTheme);\n}\n\nvoid GnomePlugin::setupTrayIcon(QSystemTrayIcon* tray)\n{\n tray->setVisible(false);\n}\n\nvoid GnomePlugin::setupMuteAction(QAction* action)\n{\n d.mute = action;\n}\n<commit_msg>KDE: keep tray icon visible<commit_after>\/*\n Copyright (C) 2008-2016 The Communi Project\n\n You may use this file under the terms of BSD license as follows:\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the copyright holder 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 \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY 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\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"gnomeplugin.h\"\n#include \"gnomemenu.h\"\n#include \"x11helper.h\"\n#include \"themeinfo.h\"\n#include <QSystemTrayIcon>\n#include <QMainWindow>\n#include <QAction>\n\nGnomePlugin::GnomePlugin(QObject* parent) : QObject(parent)\n{\n d.mute = 0;\n d.window = 0;\n}\n\nvoid GnomePlugin::windowCreated(QMainWindow* window)\n{\n d.window = window;\n\n#ifdef COMMUNI_HAVE_GIO\n GnomeMenu *section1 = new GnomeMenu(window);\n section1->addSimpleItem(\"showConnect\", \"Connect...\", window, \"doConnect\");\n section1->addSimpleItem(\"showSettings\", \"Settings\", window, \"showSettings\");\n section1->addSimpleItem(\"showHelp\", \"Help\", window, \"showHelp\");\n\n GnomeMenu *section2 = new GnomeMenu(window);\n section2->addToggleItem(\"toggleMute\", \"Mute\", d.mute->isChecked(), d.mute, \"toggle\");\n\n GnomeMenu *section3 = new GnomeMenu(window);\n section3->addSimpleItem(\"quit\", \"Quit\", window, \"close\");\n\n GnomeMenu *builder = new GnomeMenu(window);\n builder->addSection(section1);\n builder->addSection(section2);\n builder->addSection(section3);\n builder->setMenuToWindow(window->winId(), \"\/org\/communi\/gnomeintegration\");\n#endif \/\/ COMMUNI_HAVE_GIO\n}\n\nvoid GnomePlugin::themeChanged(const ThemeInfo& theme)\n{\n QByteArray gtkTheme = theme.gtkTheme().toUtf8();\n X11Helper::setWindowProperty(d.window->winId(), \"_GTK_THEME_VARIANT\", gtkTheme);\n}\n\nvoid GnomePlugin::setupTrayIcon(QSystemTrayIcon* tray)\n{\n if (qgetenv(\"XDG_CURRENT_DESKTOP\") != \"KDE\" && qgetenv(\"KDE_FULL_SESSION\").isEmpty())\n tray->setVisible(false);\n}\n\nvoid GnomePlugin::setupMuteAction(QAction* action)\n{\n d.mute = action;\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************************\n * Copyright (C) 2014 Aleix Pol Gonzalez <aleixpol@blue-systems.com> *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (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. 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, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *\n ************************************************************************************\/\n\n#include <purpose\/pluginbase.h>\n#include \"mpform.h\"\n#include <QDebug>\n#include <QTimer>\n#include <QStandardPaths>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QJsonArray>\n#include <KLocalizedString>\n#include <KPluginFactory>\n#include <KJob>\n#include <KIO\/TransferJob>\n#include <KIO\/StoredTransferJob>\n\nEXPORT_SHARE_VERSION\n\n\/\/ Taken from \"share\" Data Engine\n\/\/ key associated with plasma-devel@kde.org\n\/\/ thanks to Alan Schaaf of Imgur (alan@imgur.com)\nstatic const QString apiKey = QStringLiteral(\"d0757bc2e94a0d4652f28079a0be9379\");\nstatic const QUrl imgurUrl(QStringLiteral(\"https:\/\/api.imgur.com\/2\/upload.json?key=\")+apiKey);\n\nclass ImgurShareJob : public Purpose::Job\n{\n Q_OBJECT\n public:\n ImgurShareJob(QObject* parent)\n : Purpose::Job(parent)\n , m_pendingJobs(0)\n {}\n\n virtual void start() override\n {\n QJsonArray urls = data().value(QStringLiteral(\"urls\")).toArray();\n qDebug() << \"starting...\" << data().toVariantMap();\n if (urls.isEmpty()) {\n qWarning() << \"no urls to share\" << urls << data();\n emitResult();\n return;\n }\n\n foreach(const QJsonValue &val, urls) {\n QString u = val.toString();\n if (u.startsWith(QLatin1String(\"data:\"))) {\n QByteArray data = QByteArray::fromBase64(u.mid(4).toLatin1());\n QFile f(QStringLiteral(\"\/tmp\/puta.png\"));\n Q_ASSERT(f.open(QFile::WriteOnly));\n f.write(data);\n m_form.addFile(QStringLiteral(\"image\"), QUrl(QStringLiteral(\"file:\/\/\/not-in-the-file-system\")), data);\n } else {\n KIO::StoredTransferJob* job = KIO::storedGet(QUrl(u));\n connect(job, &KJob::finished, this, &ImgurShareJob::fileFetched);\n m_pendingJobs++;\n }\n }\n if (m_pendingJobs == 0) {\n performUpload();\n }\n }\n\n void fileFetched(KJob* j)\n {\n KIO::StoredTransferJob* job = qobject_cast<KIO::StoredTransferJob*>(j);\n m_form.addFile(QStringLiteral(\"image\"), job->url(), job->data());\n --m_pendingJobs;\n if (m_pendingJobs == 0)\n performUpload();\n }\n\n void performUpload()\n {\n m_form.finish();\n\n KIO::TransferJob *tJob = KIO::http_post(imgurUrl, m_form.formData(), KIO::HideProgressInfo);\n tJob->setMetaData(QMap<QString,QString>{{ QStringLiteral(\"content-type\"), QString::fromLocal8Bit(m_form.contentType()) }});\n connect(tJob, &KIO::TransferJob::data, this, [this](KIO::Job*, const QByteArray& data) { m_resultData += data; });\n connect(tJob, &KJob::result, this, &ImgurShareJob::imagesUploaded);\n\n m_form.reset(); \/\/we can free some resources already\n }\n\n void imagesUploaded(KJob* job) {\n QJsonParseError error;\n QJsonObject resultMap = QJsonDocument::fromJson(m_resultData, &error).object();\n if (static_cast<KIO::TransferJob *>(job)->isErrorPage()) {\n setError(3);\n setErrorText(i18n(\"Error page returned\"));\n qDebug() << \"Error page :(\";\n } else if (job->error()) {\n setError(job->error());\n setErrorText(job->errorText());\n } else if (error.error) {\n setError(1);\n setErrorText(error.errorString());\n } else if ( resultMap.contains(QLatin1String(\"error\")) ) {\n setError(2);\n QJsonObject errorMap = resultMap[QStringLiteral(\"error\")].toObject();\n setErrorText(errorMap[QStringLiteral(\"message\")].toString());\n } else {\n QJsonObject uploadMap = resultMap[QStringLiteral(\"upload\")].toObject();\n QJsonObject linksMap = uploadMap[QStringLiteral(\"links\")].toObject();\n QString url = linksMap[QStringLiteral(\"original\")].toString();\n Q_EMIT infoMessage(this, url, QStringLiteral(\"<a href='%1'>%1<\/a>\").arg(url));\n }\n emitResult();\n }\n\n virtual QUrl configSourceCode() const override\n {\n return QUrl();\n }\n\n private:\n int m_pendingJobs;\n MPForm m_form;\n QByteArray m_resultData;\n};\n\nclass Q_DECL_EXPORT ImgurPlugin : public Purpose::PluginBase\n{\n Q_OBJECT\n public:\n ImgurPlugin(QObject* p, const QVariantList& ) : Purpose::PluginBase(p) {}\n\n virtual Purpose::Job* share() const override\n {\n return new ImgurShareJob(nullptr);\n }\n};\n\nK_PLUGIN_FACTORY_WITH_JSON(ImgurShare, \"imgurplugin.json\", registerPlugin<ImgurPlugin>();)\n\n#include \"imgurplugin.moc\"\n<commit_msg>Revert the data: protocol support<commit_after>\/************************************************************************************\n * Copyright (C) 2014 Aleix Pol Gonzalez <aleixpol@blue-systems.com> *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (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. 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, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *\n ************************************************************************************\/\n\n#include <purpose\/pluginbase.h>\n#include \"mpform.h\"\n#include <QDebug>\n#include <QTimer>\n#include <QStandardPaths>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QJsonArray>\n#include <KLocalizedString>\n#include <KPluginFactory>\n#include <KJob>\n#include <KIO\/TransferJob>\n#include <KIO\/StoredTransferJob>\n\nEXPORT_SHARE_VERSION\n\n\/\/ Taken from \"share\" Data Engine\n\/\/ key associated with plasma-devel@kde.org\n\/\/ thanks to Alan Schaaf of Imgur (alan@imgur.com)\nstatic const QString apiKey = QStringLiteral(\"d0757bc2e94a0d4652f28079a0be9379\");\nstatic const QUrl imgurUrl(QStringLiteral(\"https:\/\/api.imgur.com\/2\/upload.json?key=\")+apiKey);\n\nclass ImgurShareJob : public Purpose::Job\n{\n Q_OBJECT\n public:\n ImgurShareJob(QObject* parent)\n : Purpose::Job(parent)\n , m_pendingJobs(0)\n {}\n\n virtual void start() override\n {\n QJsonArray urls = data().value(QStringLiteral(\"urls\")).toArray();\n qDebug() << \"starting...\" << data().toVariantMap();\n if (urls.isEmpty()) {\n qWarning() << \"no urls to share\" << urls << data();\n emitResult();\n return;\n }\n\n foreach(const QJsonValue &val, urls) {\n QString u = val.toString();\n KIO::StoredTransferJob* job = KIO::storedGet(QUrl(u));\n connect(job, &KJob::finished, this, &ImgurShareJob::fileFetched);\n m_pendingJobs++;\n }\n Q_ASSERT(m_pendingJobs>0);\n }\n\n void fileFetched(KJob* j)\n {\n KIO::StoredTransferJob* job = qobject_cast<KIO::StoredTransferJob*>(j);\n m_form.addFile(QStringLiteral(\"image\"), job->url(), job->data());\n --m_pendingJobs;\n if (m_pendingJobs == 0)\n performUpload();\n }\n\n void performUpload()\n {\n m_form.finish();\n\n KIO::TransferJob *tJob = KIO::http_post(imgurUrl, m_form.formData(), KIO::HideProgressInfo);\n tJob->setMetaData(QMap<QString,QString>{{ QStringLiteral(\"content-type\"), QString::fromLocal8Bit(m_form.contentType()) }});\n connect(tJob, &KIO::TransferJob::data, this, [this](KIO::Job*, const QByteArray& data) { m_resultData += data; });\n connect(tJob, &KJob::result, this, &ImgurShareJob::imagesUploaded);\n\n m_form.reset(); \/\/we can free some resources already\n }\n\n void imagesUploaded(KJob* job) {\n QJsonParseError error;\n QJsonObject resultMap = QJsonDocument::fromJson(m_resultData, &error).object();\n if (static_cast<KIO::TransferJob *>(job)->isErrorPage()) {\n setError(3);\n setErrorText(i18n(\"Error page returned\"));\n qDebug() << \"Error page :(\";\n } else if (job->error()) {\n setError(job->error());\n setErrorText(job->errorText());\n } else if (error.error) {\n setError(1);\n setErrorText(error.errorString());\n } else if ( resultMap.contains(QLatin1String(\"error\")) ) {\n setError(2);\n QJsonObject errorMap = resultMap[QStringLiteral(\"error\")].toObject();\n setErrorText(errorMap[QStringLiteral(\"message\")].toString());\n } else {\n QJsonObject uploadMap = resultMap[QStringLiteral(\"upload\")].toObject();\n QJsonObject linksMap = uploadMap[QStringLiteral(\"links\")].toObject();\n QString url = linksMap[QStringLiteral(\"original\")].toString();\n Q_EMIT infoMessage(this, url, QStringLiteral(\"<a href='%1'>%1<\/a>\").arg(url));\n }\n emitResult();\n }\n\n virtual QUrl configSourceCode() const override\n {\n return QUrl();\n }\n\n private:\n int m_pendingJobs;\n MPForm m_form;\n QByteArray m_resultData;\n};\n\nclass Q_DECL_EXPORT ImgurPlugin : public Purpose::PluginBase\n{\n Q_OBJECT\n public:\n ImgurPlugin(QObject* p, const QVariantList& ) : Purpose::PluginBase(p) {}\n\n virtual Purpose::Job* share() const override\n {\n return new ImgurShareJob(nullptr);\n }\n};\n\nK_PLUGIN_FACTORY_WITH_JSON(ImgurShare, \"imgurplugin.json\", registerPlugin<ImgurPlugin>();)\n\n#include \"imgurplugin.moc\"\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.8.18); FILE MERGED 2008\/04\/01 16:09:54 thb 1.8.18.3: #i85898# Stripping all external header guards 2008\/04\/01 13:05:01 thb 1.8.18.2: #i85898# Stripping all external header guards 2008\/03\/31 16:28:21 rt 1.8.18.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Basic archetype<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Marks session as connected upon StartSession success<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2016 Rhys Ulerich\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include <iterator>\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <descendu\/map.hpp>\n\nusing namespace descendu;\n\nTEST_CASE( \"map\" ) {\n\n map m;\n\n SECTION( \"populate\" ) {\n \/\/ Empty on construction\n REQUIRE( m.cbegin() == m.cend() );\n\n \/\/ Insertion with explicit type\n m.populate(map::key_type(0, 0));\n auto a = m.cbegin();\n std::advance(a, 1);\n REQUIRE( a == m.cend() );\n\n \/\/ Idempotent re-insertion\n m.populate(map::key_type(0, 0));\n auto b = m.cbegin();\n std::advance(b, 1);\n REQUIRE( b == m.cend() );\n\n \/\/ Insertion with nicety provided by hex\n m.populate(map::key_type(1, 0));\n auto c = m.cbegin();\n std::advance(c, 2);\n REQUIRE( c == m.cend() );\n }\n\n SECTION( \"mutable\" ) {\n auto& a = m.populate({0, 0});\n a.cannon.increase(1);\n REQUIRE( a.cannon.total() == 1 );\n\n auto& b = m.lookup({0, 0}).value();\n REQUIRE( b.cannon.total() == 1 );\n }\n\n SECTION( \"not_found\" ) {\n REQUIRE( !m.lookup({0, 0}).has_value() );\n REQUIRE( !m.lookup({0, 0}) );\n }\n\n}\n<commit_msg>Enforce no clobber of existing<commit_after>\/*\n * Copyright (C) 2016 Rhys Ulerich\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include <iterator>\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <descendu\/map.hpp>\n\nusing namespace descendu;\n\nTEST_CASE( \"map\" ) {\n\n map m;\n\n SECTION( \"populate\" ) {\n \/\/ Empty on construction\n REQUIRE( m.cbegin() == m.cend() );\n\n \/\/ Insertion with explicit type\n m.populate(map::key_type(0, 0));\n auto a = m.cbegin();\n std::advance(a, 1);\n REQUIRE( a == m.cend() );\n\n \/\/ Idempotent re-insertion\n m.populate(map::key_type(0, 0));\n auto b = m.cbegin();\n std::advance(b, 1);\n REQUIRE( b == m.cend() );\n\n \/\/ Insertion with nicety provided by hex\n m.populate(map::key_type(1, 0));\n auto c = m.cbegin();\n std::advance(c, 2);\n REQUIRE( c == m.cend() );\n }\n\n SECTION( \"mutable\" ) {\n auto& a = m.populate({0, 0});\n a.cannon.increase(1);\n REQUIRE( a.cannon.total() == 1 );\n\n auto& b = m.lookup({0, 0}).value();\n REQUIRE( b.cannon.total() == 1 );\n\n \/\/ No clobber of existing entry\n auto& c = m.populate({0, 0});\n REQUIRE( c.cannon.total() == 1 );\n }\n\n SECTION( \"not_found\" ) {\n REQUIRE( !m.lookup({0, 0}).has_value() );\n REQUIRE( !m.lookup({0, 0}) );\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"chrome\/browser\/sync\/sync_setup_flow.h\"\n\n#include \"app\/gfx\/font.h\"\n#include \"app\/gfx\/font_util.h\"\n#include \"base\/histogram.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/json\/json_writer.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/google_service_auth_error.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/locale_settings.h\"\n\n\/\/ XPath expression for finding specific iframes.\nstatic const wchar_t* kLoginIFrameXPath = L\"\/\/iframe[@id='login']\";\nstatic const wchar_t* kMergeIFrameXPath = L\"\/\/iframe[@id='merge']\";\nstatic const wchar_t* kDoneIframeXPath = L\"\/\/iframe[@id='done']\";\n\n\/\/ Helper function to read the JSON string from the Value parameter.\nstatic std::string GetJsonResponse(const Value* content) {\n if (!content || !content->IsType(Value::TYPE_LIST)) {\n NOTREACHED();\n return std::string();\n }\n const ListValue* args = static_cast<const ListValue*>(content);\n if (args->GetSize() != 1) {\n NOTREACHED();\n return std::string();\n }\n\n std::string result;\n Value* value = NULL;\n if (!args->Get(0, &value) || !value->GetAsString(&result)) {\n NOTREACHED();\n return std::string();\n }\n\n return result;\n}\n\nvoid FlowHandler::RegisterMessages() {\n dom_ui_->RegisterMessageCallback(\"SubmitAuth\",\n NewCallback(this, &FlowHandler::HandleSubmitAuth));\n dom_ui_->RegisterMessageCallback(\"SubmitMergeAndSync\",\n NewCallback(this, &FlowHandler::HandleSubmitMergeAndSync));\n}\n\nstatic bool GetAuthData(const std::string& json,\n std::string* username, std::string* password, std::string* captcha) {\n scoped_ptr<Value> parsed_value(base::JSONReader::Read(json, false));\n if (!parsed_value.get() || !parsed_value->IsType(Value::TYPE_DICTIONARY))\n return false;\n\n DictionaryValue* result = static_cast<DictionaryValue*>(parsed_value.get());\n if (!result->GetString(L\"user\", username) ||\n !result->GetString(L\"pass\", password) ||\n !result->GetString(L\"captcha\", captcha)) {\n return false;\n }\n return true;\n}\n\nvoid FlowHandler::HandleSubmitAuth(const Value* value) {\n std::string json(GetJsonResponse(value));\n std::string username, password, captcha;\n if (json.empty())\n return;\n\n if (!GetAuthData(json, &username, &password, &captcha)) {\n \/\/ The page sent us something that we didn't understand.\n \/\/ This probably indicates a programming error.\n NOTREACHED();\n return;\n }\n\n if (flow_)\n flow_->OnUserSubmittedAuth(username, password, captcha);\n}\n\nvoid FlowHandler::HandleSubmitMergeAndSync(const Value* value) {\n if (flow_)\n flow_->OnUserAcceptedMergeAndSync();\n}\n\n\/\/ Called by SyncSetupFlow::Advance.\nvoid FlowHandler::ShowGaiaLogin(const DictionaryValue& args) {\n std::string json;\n base::JSONWriter::Write(&args, false, &json);\n std::wstring javascript = std::wstring(L\"showGaiaLogin\") +\n L\"(\" + UTF8ToWide(json) + L\");\";\n ExecuteJavascriptInIFrame(kLoginIFrameXPath, javascript);\n}\n\nvoid FlowHandler::ShowGaiaSuccessAndClose() {\n ExecuteJavascriptInIFrame(kLoginIFrameXPath, L\"showGaiaSuccessAndClose();\");\n}\n\nvoid FlowHandler::ShowGaiaSuccessAndSettingUp() {\n ExecuteJavascriptInIFrame(kLoginIFrameXPath,\n L\"showGaiaSuccessAndSettingUp();\");\n}\n\nvoid FlowHandler::ShowMergeAndSync() {\n if (dom_ui_) \/\/ NULL during testing.\n dom_ui_->CallJavascriptFunction(L\"showMergeAndSync\");\n}\n\nvoid FlowHandler::ShowSetupDone(const std::wstring& user) {\n StringValue synced_to_string(WideToUTF8(l10n_util::GetStringF(\n IDS_SYNC_NTP_SYNCED_TO, user)));\n std::string json;\n base::JSONWriter::Write(&synced_to_string, false, &json);\n std::wstring javascript = std::wstring(L\"setSyncedToUser\") +\n L\"(\" + UTF8ToWide(json) + L\");\";\n ExecuteJavascriptInIFrame(kDoneIframeXPath, javascript);\n\n if (dom_ui_)\n dom_ui_->CallJavascriptFunction(L\"showSetupDone\", synced_to_string);\n}\n\nvoid FlowHandler::ShowFirstTimeDone(const std::wstring& user) {\n ExecuteJavascriptInIFrame(kDoneIframeXPath,\n L\"setShowFirstTimeSetupSummary();\");\n ShowSetupDone(user);\n}\n\nvoid FlowHandler::ShowMergeAndSyncError() {\n ExecuteJavascriptInIFrame(kMergeIFrameXPath, L\"showMergeAndSyncError();\");\n}\n\nvoid FlowHandler::ExecuteJavascriptInIFrame(const std::wstring& iframe_xpath,\n const std::wstring& js) {\n if (dom_ui_) {\n RenderViewHost* rvh = dom_ui_->tab_contents()->render_view_host();\n rvh->ExecuteJavascriptInWebFrame(iframe_xpath, js);\n }\n}\n\nSyncSetupFlow::~SyncSetupFlow() {\n flow_handler_->set_flow(NULL);\n}\n\nvoid SyncSetupFlow::GetDialogSize(gfx::Size* size) const {\n PrefService* prefs = service_->profile()->GetPrefs();\n gfx::Font approximate_web_font = gfx::Font::CreateFont(\n prefs->GetString(prefs::kWebKitSansSerifFontFamily),\n prefs->GetInteger(prefs::kWebKitDefaultFontSize));\n\n *size = gfx::GetLocalizedContentsSizeForFont(\n IDS_SYNC_SETUP_WIZARD_WIDTH_CHARS,\n IDS_SYNC_SETUP_WIZARD_HEIGHT_LINES,\n approximate_web_font);\n\n#if !defined(OS_WIN)\n \/\/ NOTE(akalin): This is a hack to work around a problem with font height on\n \/\/ windows. Basically font metrics are incorrectly returned in logical units\n \/\/ instead of pixels on Windows. Logical units are very commonly 96 DPI\n \/\/ so our localized char\/line counts are too small by a factor of 96\/72.\n \/\/ So we compensate for this on non-windows platform.\n \/\/\n \/\/ TODO(akalin): Remove this hack once we fix the windows font problem (or at\n \/\/ least work around it in some other place).\n float scale_hack = 96.f\/72.f;\n size->set_width(size->width() * scale_hack);\n size->set_height(size->height() * scale_hack);\n#endif\n}\n\n\/\/ A callback to notify the delegate that the dialog closed.\nvoid SyncSetupFlow::OnDialogClosed(const std::string& json_retval) {\n DCHECK(json_retval.empty());\n container_->set_flow(NULL); \/\/ Sever ties from the wizard.\n if (current_state_ == SyncSetupWizard::DONE ||\n current_state_ == SyncSetupWizard::DONE_FIRST_TIME) {\n service_->SetSyncSetupCompleted();\n }\n\n \/\/ Record the state at which the user cancelled the signon dialog.\n switch (current_state_) {\n case SyncSetupWizard::GAIA_LOGIN:\n ProfileSyncService::SyncEvent(\n ProfileSyncService::CANCEL_FROM_SIGNON_WITHOUT_AUTH);\n break;\n case SyncSetupWizard::GAIA_SUCCESS:\n ProfileSyncService::SyncEvent(\n ProfileSyncService::CANCEL_DURING_SIGNON);\n break;\n case SyncSetupWizard::MERGE_AND_SYNC:\n ProfileSyncService::SyncEvent(\n ProfileSyncService::CANCEL_DURING_SIGNON_AFTER_MERGE);\n break;\n case SyncSetupWizard::DONE_FIRST_TIME:\n case SyncSetupWizard::DONE:\n UMA_HISTOGRAM_MEDIUM_TIMES(\"Sync.UserPerceivedAuthorizationTime\",\n base::TimeTicks::Now() - login_start_time_);\n break;\n default:\n break;\n }\n\n service_->OnUserCancelledDialog();\n delete this;\n}\n\n\/\/ static\nvoid SyncSetupFlow::GetArgsForGaiaLogin(const ProfileSyncService* service,\n DictionaryValue* args) {\n const GoogleServiceAuthError& error = service->GetAuthError();\n if (!service->last_attempted_user_email().empty()) {\n args->SetString(L\"user\", service->last_attempted_user_email());\n args->SetInteger(L\"error\", error.state());\n } else {\n std::wstring user(UTF16ToWide(service->GetAuthenticatedUsername()));\n args->SetString(L\"user\", user);\n args->SetInteger(L\"error\", user.empty() ? 0 : error.state());\n }\n\n args->SetString(L\"captchaUrl\", error.captcha().image_url.spec());\n}\n\nvoid SyncSetupFlow::GetDOMMessageHandlers(\n std::vector<DOMMessageHandler*>* handlers) const {\n handlers->push_back(flow_handler_);\n}\n\nbool SyncSetupFlow::ShouldAdvance(SyncSetupWizard::State state) {\n switch (state) {\n case SyncSetupWizard::GAIA_LOGIN:\n return current_state_ == SyncSetupWizard::GAIA_LOGIN;\n case SyncSetupWizard::GAIA_SUCCESS:\n return current_state_ == SyncSetupWizard::GAIA_LOGIN;\n case SyncSetupWizard::MERGE_AND_SYNC:\n return current_state_ == SyncSetupWizard::GAIA_SUCCESS;\n case SyncSetupWizard::FATAL_ERROR:\n return true; \/\/ You can always hit the panic button.\n case SyncSetupWizard::DONE_FIRST_TIME:\n case SyncSetupWizard::DONE:\n return current_state_ == SyncSetupWizard::MERGE_AND_SYNC ||\n current_state_ == SyncSetupWizard::GAIA_SUCCESS;\n default:\n NOTREACHED() << \"Unhandled State: \" << state;\n return false;\n }\n}\n\nvoid SyncSetupFlow::Advance(SyncSetupWizard::State advance_state) {\n if (!ShouldAdvance(advance_state))\n return;\n switch (advance_state) {\n case SyncSetupWizard::GAIA_LOGIN: {\n DictionaryValue args;\n SyncSetupFlow::GetArgsForGaiaLogin(service_, &args);\n flow_handler_->ShowGaiaLogin(args);\n break;\n }\n case SyncSetupWizard::GAIA_SUCCESS:\n if (end_state_ == SyncSetupWizard::GAIA_SUCCESS)\n flow_handler_->ShowGaiaSuccessAndClose();\n else\n flow_handler_->ShowGaiaSuccessAndSettingUp();\n break;\n case SyncSetupWizard::MERGE_AND_SYNC:\n flow_handler_->ShowMergeAndSync();\n break;\n case SyncSetupWizard::FATAL_ERROR:\n if (current_state_ == SyncSetupWizard::MERGE_AND_SYNC)\n flow_handler_->ShowMergeAndSyncError();\n break;\n case SyncSetupWizard::DONE_FIRST_TIME:\n flow_handler_->ShowFirstTimeDone(\n UTF16ToWide(service_->GetAuthenticatedUsername()));\n break;\n case SyncSetupWizard::DONE:\n flow_handler_->ShowSetupDone(\n UTF16ToWide(service_->GetAuthenticatedUsername()));\n break;\n default:\n NOTREACHED() << \"Invalid advance state: \" << advance_state;\n }\n current_state_ = advance_state;\n}\n\n\/\/ static\nSyncSetupFlow* SyncSetupFlow::Run(ProfileSyncService* service,\n SyncSetupFlowContainer* container,\n SyncSetupWizard::State start,\n SyncSetupWizard::State end) {\n DictionaryValue args;\n if (start == SyncSetupWizard::GAIA_LOGIN)\n SyncSetupFlow::GetArgsForGaiaLogin(service, &args);\n std::string json_args;\n base::JSONWriter::Write(&args, false, &json_args);\n\n Browser* b = BrowserList::GetLastActive();\n if (!b)\n return NULL;\n\n FlowHandler* handler = new FlowHandler();\n SyncSetupFlow* flow = new SyncSetupFlow(start, end, json_args,\n container, handler, service);\n handler->set_flow(flow);\n b->BrowserShowHtmlDialog(flow, NULL);\n return flow;\n}\n<commit_msg>Change the layout have in sync_setup_flow.cc to only be active on MacOS.<commit_after>\/\/ 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 \"chrome\/browser\/sync\/sync_setup_flow.h\"\n\n#include \"app\/gfx\/font.h\"\n#include \"app\/gfx\/font_util.h\"\n#include \"base\/histogram.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/json\/json_writer.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/google_service_auth_error.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/locale_settings.h\"\n\n\/\/ XPath expression for finding specific iframes.\nstatic const wchar_t* kLoginIFrameXPath = L\"\/\/iframe[@id='login']\";\nstatic const wchar_t* kMergeIFrameXPath = L\"\/\/iframe[@id='merge']\";\nstatic const wchar_t* kDoneIframeXPath = L\"\/\/iframe[@id='done']\";\n\n\/\/ Helper function to read the JSON string from the Value parameter.\nstatic std::string GetJsonResponse(const Value* content) {\n if (!content || !content->IsType(Value::TYPE_LIST)) {\n NOTREACHED();\n return std::string();\n }\n const ListValue* args = static_cast<const ListValue*>(content);\n if (args->GetSize() != 1) {\n NOTREACHED();\n return std::string();\n }\n\n std::string result;\n Value* value = NULL;\n if (!args->Get(0, &value) || !value->GetAsString(&result)) {\n NOTREACHED();\n return std::string();\n }\n\n return result;\n}\n\nvoid FlowHandler::RegisterMessages() {\n dom_ui_->RegisterMessageCallback(\"SubmitAuth\",\n NewCallback(this, &FlowHandler::HandleSubmitAuth));\n dom_ui_->RegisterMessageCallback(\"SubmitMergeAndSync\",\n NewCallback(this, &FlowHandler::HandleSubmitMergeAndSync));\n}\n\nstatic bool GetAuthData(const std::string& json,\n std::string* username, std::string* password, std::string* captcha) {\n scoped_ptr<Value> parsed_value(base::JSONReader::Read(json, false));\n if (!parsed_value.get() || !parsed_value->IsType(Value::TYPE_DICTIONARY))\n return false;\n\n DictionaryValue* result = static_cast<DictionaryValue*>(parsed_value.get());\n if (!result->GetString(L\"user\", username) ||\n !result->GetString(L\"pass\", password) ||\n !result->GetString(L\"captcha\", captcha)) {\n return false;\n }\n return true;\n}\n\nvoid FlowHandler::HandleSubmitAuth(const Value* value) {\n std::string json(GetJsonResponse(value));\n std::string username, password, captcha;\n if (json.empty())\n return;\n\n if (!GetAuthData(json, &username, &password, &captcha)) {\n \/\/ The page sent us something that we didn't understand.\n \/\/ This probably indicates a programming error.\n NOTREACHED();\n return;\n }\n\n if (flow_)\n flow_->OnUserSubmittedAuth(username, password, captcha);\n}\n\nvoid FlowHandler::HandleSubmitMergeAndSync(const Value* value) {\n if (flow_)\n flow_->OnUserAcceptedMergeAndSync();\n}\n\n\/\/ Called by SyncSetupFlow::Advance.\nvoid FlowHandler::ShowGaiaLogin(const DictionaryValue& args) {\n std::string json;\n base::JSONWriter::Write(&args, false, &json);\n std::wstring javascript = std::wstring(L\"showGaiaLogin\") +\n L\"(\" + UTF8ToWide(json) + L\");\";\n ExecuteJavascriptInIFrame(kLoginIFrameXPath, javascript);\n}\n\nvoid FlowHandler::ShowGaiaSuccessAndClose() {\n ExecuteJavascriptInIFrame(kLoginIFrameXPath, L\"showGaiaSuccessAndClose();\");\n}\n\nvoid FlowHandler::ShowGaiaSuccessAndSettingUp() {\n ExecuteJavascriptInIFrame(kLoginIFrameXPath,\n L\"showGaiaSuccessAndSettingUp();\");\n}\n\nvoid FlowHandler::ShowMergeAndSync() {\n if (dom_ui_) \/\/ NULL during testing.\n dom_ui_->CallJavascriptFunction(L\"showMergeAndSync\");\n}\n\nvoid FlowHandler::ShowSetupDone(const std::wstring& user) {\n StringValue synced_to_string(WideToUTF8(l10n_util::GetStringF(\n IDS_SYNC_NTP_SYNCED_TO, user)));\n std::string json;\n base::JSONWriter::Write(&synced_to_string, false, &json);\n std::wstring javascript = std::wstring(L\"setSyncedToUser\") +\n L\"(\" + UTF8ToWide(json) + L\");\";\n ExecuteJavascriptInIFrame(kDoneIframeXPath, javascript);\n\n if (dom_ui_)\n dom_ui_->CallJavascriptFunction(L\"showSetupDone\", synced_to_string);\n}\n\nvoid FlowHandler::ShowFirstTimeDone(const std::wstring& user) {\n ExecuteJavascriptInIFrame(kDoneIframeXPath,\n L\"setShowFirstTimeSetupSummary();\");\n ShowSetupDone(user);\n}\n\nvoid FlowHandler::ShowMergeAndSyncError() {\n ExecuteJavascriptInIFrame(kMergeIFrameXPath, L\"showMergeAndSyncError();\");\n}\n\nvoid FlowHandler::ExecuteJavascriptInIFrame(const std::wstring& iframe_xpath,\n const std::wstring& js) {\n if (dom_ui_) {\n RenderViewHost* rvh = dom_ui_->tab_contents()->render_view_host();\n rvh->ExecuteJavascriptInWebFrame(iframe_xpath, js);\n }\n}\n\nSyncSetupFlow::~SyncSetupFlow() {\n flow_handler_->set_flow(NULL);\n}\n\nvoid SyncSetupFlow::GetDialogSize(gfx::Size* size) const {\n PrefService* prefs = service_->profile()->GetPrefs();\n gfx::Font approximate_web_font = gfx::Font::CreateFont(\n prefs->GetString(prefs::kWebKitSansSerifFontFamily),\n prefs->GetInteger(prefs::kWebKitDefaultFontSize));\n\n *size = gfx::GetLocalizedContentsSizeForFont(\n IDS_SYNC_SETUP_WIZARD_WIDTH_CHARS,\n IDS_SYNC_SETUP_WIZARD_HEIGHT_LINES,\n approximate_web_font);\n\n#if defined(OS_MACOSX)\n \/\/ NOTE(akalin): This is a hack to work around a problem with font height on\n \/\/ windows. Basically font metrics are incorrectly returned in logical units\n \/\/ instead of pixels on Windows. Logical units are very commonly 96 DPI\n \/\/ so our localized char\/line counts are too small by a factor of 96\/72.\n \/\/ So we compensate for this on non-windows platform.\n \/\/\n \/\/ TODO(akalin): Remove this hack once we fix the windows font problem (or at\n \/\/ least work around it in some other place).\n float scale_hack = 96.f\/72.f;\n size->set_width(size->width() * scale_hack);\n size->set_height(size->height() * scale_hack);\n#endif\n}\n\n\/\/ A callback to notify the delegate that the dialog closed.\nvoid SyncSetupFlow::OnDialogClosed(const std::string& json_retval) {\n DCHECK(json_retval.empty());\n container_->set_flow(NULL); \/\/ Sever ties from the wizard.\n if (current_state_ == SyncSetupWizard::DONE ||\n current_state_ == SyncSetupWizard::DONE_FIRST_TIME) {\n service_->SetSyncSetupCompleted();\n }\n\n \/\/ Record the state at which the user cancelled the signon dialog.\n switch (current_state_) {\n case SyncSetupWizard::GAIA_LOGIN:\n ProfileSyncService::SyncEvent(\n ProfileSyncService::CANCEL_FROM_SIGNON_WITHOUT_AUTH);\n break;\n case SyncSetupWizard::GAIA_SUCCESS:\n ProfileSyncService::SyncEvent(\n ProfileSyncService::CANCEL_DURING_SIGNON);\n break;\n case SyncSetupWizard::MERGE_AND_SYNC:\n ProfileSyncService::SyncEvent(\n ProfileSyncService::CANCEL_DURING_SIGNON_AFTER_MERGE);\n break;\n case SyncSetupWizard::DONE_FIRST_TIME:\n case SyncSetupWizard::DONE:\n UMA_HISTOGRAM_MEDIUM_TIMES(\"Sync.UserPerceivedAuthorizationTime\",\n base::TimeTicks::Now() - login_start_time_);\n break;\n default:\n break;\n }\n\n service_->OnUserCancelledDialog();\n delete this;\n}\n\n\/\/ static\nvoid SyncSetupFlow::GetArgsForGaiaLogin(const ProfileSyncService* service,\n DictionaryValue* args) {\n const GoogleServiceAuthError& error = service->GetAuthError();\n if (!service->last_attempted_user_email().empty()) {\n args->SetString(L\"user\", service->last_attempted_user_email());\n args->SetInteger(L\"error\", error.state());\n } else {\n std::wstring user(UTF16ToWide(service->GetAuthenticatedUsername()));\n args->SetString(L\"user\", user);\n args->SetInteger(L\"error\", user.empty() ? 0 : error.state());\n }\n\n args->SetString(L\"captchaUrl\", error.captcha().image_url.spec());\n}\n\nvoid SyncSetupFlow::GetDOMMessageHandlers(\n std::vector<DOMMessageHandler*>* handlers) const {\n handlers->push_back(flow_handler_);\n}\n\nbool SyncSetupFlow::ShouldAdvance(SyncSetupWizard::State state) {\n switch (state) {\n case SyncSetupWizard::GAIA_LOGIN:\n return current_state_ == SyncSetupWizard::GAIA_LOGIN;\n case SyncSetupWizard::GAIA_SUCCESS:\n return current_state_ == SyncSetupWizard::GAIA_LOGIN;\n case SyncSetupWizard::MERGE_AND_SYNC:\n return current_state_ == SyncSetupWizard::GAIA_SUCCESS;\n case SyncSetupWizard::FATAL_ERROR:\n return true; \/\/ You can always hit the panic button.\n case SyncSetupWizard::DONE_FIRST_TIME:\n case SyncSetupWizard::DONE:\n return current_state_ == SyncSetupWizard::MERGE_AND_SYNC ||\n current_state_ == SyncSetupWizard::GAIA_SUCCESS;\n default:\n NOTREACHED() << \"Unhandled State: \" << state;\n return false;\n }\n}\n\nvoid SyncSetupFlow::Advance(SyncSetupWizard::State advance_state) {\n if (!ShouldAdvance(advance_state))\n return;\n switch (advance_state) {\n case SyncSetupWizard::GAIA_LOGIN: {\n DictionaryValue args;\n SyncSetupFlow::GetArgsForGaiaLogin(service_, &args);\n flow_handler_->ShowGaiaLogin(args);\n break;\n }\n case SyncSetupWizard::GAIA_SUCCESS:\n if (end_state_ == SyncSetupWizard::GAIA_SUCCESS)\n flow_handler_->ShowGaiaSuccessAndClose();\n else\n flow_handler_->ShowGaiaSuccessAndSettingUp();\n break;\n case SyncSetupWizard::MERGE_AND_SYNC:\n flow_handler_->ShowMergeAndSync();\n break;\n case SyncSetupWizard::FATAL_ERROR:\n if (current_state_ == SyncSetupWizard::MERGE_AND_SYNC)\n flow_handler_->ShowMergeAndSyncError();\n break;\n case SyncSetupWizard::DONE_FIRST_TIME:\n flow_handler_->ShowFirstTimeDone(\n UTF16ToWide(service_->GetAuthenticatedUsername()));\n break;\n case SyncSetupWizard::DONE:\n flow_handler_->ShowSetupDone(\n UTF16ToWide(service_->GetAuthenticatedUsername()));\n break;\n default:\n NOTREACHED() << \"Invalid advance state: \" << advance_state;\n }\n current_state_ = advance_state;\n}\n\n\/\/ static\nSyncSetupFlow* SyncSetupFlow::Run(ProfileSyncService* service,\n SyncSetupFlowContainer* container,\n SyncSetupWizard::State start,\n SyncSetupWizard::State end) {\n DictionaryValue args;\n if (start == SyncSetupWizard::GAIA_LOGIN)\n SyncSetupFlow::GetArgsForGaiaLogin(service, &args);\n std::string json_args;\n base::JSONWriter::Write(&args, false, &json_args);\n\n Browser* b = BrowserList::GetLastActive();\n if (!b)\n return NULL;\n\n FlowHandler* handler = new FlowHandler();\n SyncSetupFlow* flow = new SyncSetupFlow(start, end, json_args,\n container, handler, service);\n handler->set_flow(flow);\n b->BrowserShowHtmlDialog(flow, NULL);\n return flow;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-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 <string>\n#include <windows.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/basictypes.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n class ChromeLoggingTest : public testing::Test {\n public:\n \/\/ Stores the current value of the log file name environment\n \/\/ variable and sets the variable to new_value.\n void SaveEnvironmentVariable(std::wstring new_value) {\n unsigned status = GetEnvironmentVariable(env_vars::kLogFileName,\n environment_filename_,\n MAX_PATH);\n if (!status) {\n wcscpy_s(environment_filename_, L\"\");\n }\n\n SetEnvironmentVariable(env_vars::kLogFileName, new_value.c_str());\n }\n\n \/\/ Restores the value of the log file nave environment variable\n \/\/ previously saved by SaveEnvironmentVariable().\n void RestoreEnvironmentVariable() {\n SetEnvironmentVariable(env_vars::kLogFileName, environment_filename_);\n }\n\n private:\n wchar_t environment_filename_[MAX_PATH]; \/\/ Saves real environment value.\n };\n};\n\n\/\/ Tests the log file name getter without an environment variable.\nTEST_F(ChromeLoggingTest, LogFileName) {\n SaveEnvironmentVariable(std::wstring());\n\n FilePath filename = logging::GetLogFileName();\n ASSERT_NE(FilePath::StringType::npos,\n filename.value().find(FILE_PATH_LITERAL(\"chrome_debug.log\")));\n\n RestoreEnvironmentVariable();\n}\n\n\/\/ Tests the log file name getter with an environment variable.\nTEST_F(ChromeLoggingTest, EnvironmentLogFileName) {\n SaveEnvironmentVariable(std::wstring(L\"test value\"));\n\n FilePath filename = logging::GetLogFileName();\n ASSERT_EQ(FilePath(FILE_PATH_LITERAL(\"test value\")).value(),\n filename.value());\n\n RestoreEnvironmentVariable();\n}\n\n#ifndef NDEBUG \/\/ We don't have assertions in release builds.\n\/\/ Tests whether we correctly fail on browser assertions during tests.\nclass AssertionTest : public UITest {\n protected:\n AssertionTest() : UITest()\n {\n \/\/ Initial loads will never complete due to assertion.\n wait_for_initial_loads_ = false;\n\n \/\/ We're testing the renderer rather than the browser assertion here,\n \/\/ because the browser assertion would flunk the test during SetUp()\n \/\/ (since TAU wouldn't be able to find the browser window).\n launch_arguments_.AppendSwitch(switches::kRendererAssertTest);\n }\n};\n\n\/\/ Launch the app in assertion test mode, then close the app.\nTEST_F(AssertionTest, Assertion) {\n if (UITest::in_process_renderer()) {\n \/\/ in process mode doesn't do the crashing.\n expected_errors_ = 0;\n expected_crashes_ = 0;\n } else {\n expected_errors_ = 1;\n expected_crashes_ = 1;\n }\n}\n#endif \/\/ NDEBUG\n\n\/\/ Tests whether we correctly fail on browser crashes during UI Tests.\nclass RendererCrashTest : public UITest {\n protected:\n RendererCrashTest() : UITest()\n {\n \/\/ Initial loads will never complete due to crash.\n wait_for_initial_loads_ = false;\n\n launch_arguments_.AppendSwitch(switches::kRendererCrashTest);\n }\n};\n\n\/\/ Launch the app in renderer crash test mode, then close the app.\nTEST_F(RendererCrashTest, Crash) {\n if (UITest::in_process_renderer()) {\n \/\/ in process mode doesn't do the crashing.\n expected_crashes_ = 0;\n } else {\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));\n expected_crashes_ = 1;\n }\n}\n\n\/\/ Tests whether we correctly fail on browser crashes during UI Tests.\nclass BrowserCrashTest : public UITest {\n protected:\n BrowserCrashTest() : UITest()\n {\n \/\/ Initial loads will never complete due to crash.\n wait_for_initial_loads_ = false;\n\n launch_arguments_.AppendSwitch(switches::kBrowserCrashTest);\n }\n};\n\n\/\/ Launch the app in browser crash test mode.\n\/\/ This test is disabled. See bug 6910.\nTEST_F(BrowserCrashTest, DISABLED_Crash) {\n \/\/ Wait while the process is writing the crash dump.\n PlatformThread::Sleep(5000);\n expected_crashes_ = 1;\n}\n<commit_msg>Remove the BrowserCrashTest.Crash test from the code because it never worked. I will make bug 3910 about creating such test.<commit_after>\/\/ Copyright (c) 2006-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 <string>\n#include <windows.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/basictypes.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n class ChromeLoggingTest : public testing::Test {\n public:\n \/\/ Stores the current value of the log file name environment\n \/\/ variable and sets the variable to new_value.\n void SaveEnvironmentVariable(std::wstring new_value) {\n unsigned status = GetEnvironmentVariable(env_vars::kLogFileName,\n environment_filename_,\n MAX_PATH);\n if (!status) {\n wcscpy_s(environment_filename_, L\"\");\n }\n\n SetEnvironmentVariable(env_vars::kLogFileName, new_value.c_str());\n }\n\n \/\/ Restores the value of the log file nave environment variable\n \/\/ previously saved by SaveEnvironmentVariable().\n void RestoreEnvironmentVariable() {\n SetEnvironmentVariable(env_vars::kLogFileName, environment_filename_);\n }\n\n private:\n wchar_t environment_filename_[MAX_PATH]; \/\/ Saves real environment value.\n };\n};\n\n\/\/ Tests the log file name getter without an environment variable.\nTEST_F(ChromeLoggingTest, LogFileName) {\n SaveEnvironmentVariable(std::wstring());\n\n FilePath filename = logging::GetLogFileName();\n ASSERT_NE(FilePath::StringType::npos,\n filename.value().find(FILE_PATH_LITERAL(\"chrome_debug.log\")));\n\n RestoreEnvironmentVariable();\n}\n\n\/\/ Tests the log file name getter with an environment variable.\nTEST_F(ChromeLoggingTest, EnvironmentLogFileName) {\n SaveEnvironmentVariable(std::wstring(L\"test value\"));\n\n FilePath filename = logging::GetLogFileName();\n ASSERT_EQ(FilePath(FILE_PATH_LITERAL(\"test value\")).value(),\n filename.value());\n\n RestoreEnvironmentVariable();\n}\n\n#ifndef NDEBUG \/\/ We don't have assertions in release builds.\n\/\/ Tests whether we correctly fail on browser assertions during tests.\nclass AssertionTest : public UITest {\n protected:\n AssertionTest() : UITest()\n {\n \/\/ Initial loads will never complete due to assertion.\n wait_for_initial_loads_ = false;\n\n \/\/ We're testing the renderer rather than the browser assertion here,\n \/\/ because the browser assertion would flunk the test during SetUp()\n \/\/ (since TAU wouldn't be able to find the browser window).\n launch_arguments_.AppendSwitch(switches::kRendererAssertTest);\n }\n};\n\n\/\/ Launch the app in assertion test mode, then close the app.\nTEST_F(AssertionTest, Assertion) {\n if (UITest::in_process_renderer()) {\n \/\/ in process mode doesn't do the crashing.\n expected_errors_ = 0;\n expected_crashes_ = 0;\n } else {\n expected_errors_ = 1;\n expected_crashes_ = 1;\n }\n}\n#endif \/\/ NDEBUG\n\n\/\/ Tests whether we correctly fail on browser crashes during UI Tests.\nclass RendererCrashTest : public UITest {\n protected:\n RendererCrashTest() : UITest()\n {\n \/\/ Initial loads will never complete due to crash.\n wait_for_initial_loads_ = false;\n\n launch_arguments_.AppendSwitch(switches::kRendererCrashTest);\n }\n};\n\n\/\/ Launch the app in renderer crash test mode, then close the app.\nTEST_F(RendererCrashTest, Crash) {\n if (UITest::in_process_renderer()) {\n \/\/ in process mode doesn't do the crashing.\n expected_crashes_ = 0;\n } else {\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));\n expected_crashes_ = 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 <atlbase.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/process_util.h\"\n#include \"base\/test\/test_suite.h\"\n#include \"base\/threading\/platform_thread.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/chrome_frame_ui_test_utils.h\"\n#include \"chrome_frame\/test_utils.h\"\n#include \"chrome_frame\/utils.h\"\n\n\/\/ To enable ATL-based code to run in this module\nclass ChromeFrameUnittestsModule\n : public CAtlExeModuleT<ChromeFrameUnittestsModule> {\n public:\n static HRESULT InitializeCom() {\n return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);\n }\n};\n\nChromeFrameUnittestsModule _AtlModule;\n\nconst char kNoRegistrationSwitch[] = \"no-registration\";\n\nvoid PureCall() {\n __debugbreak();\n}\n\n\/\/ This class implements the Run method and registers an exception handler to\n\/\/ ensure that any ChromeFrame processes like IE, Firefox, etc are terminated\n\/\/ if there is a crash in the chrome frame test suite.\nclass ChromeFrameTestSuite : public base::TestSuite {\n public:\n ChromeFrameTestSuite(int argc, char** argv)\n : base::TestSuite(argc, argv) {}\n\n int Run() {\n \/\/ Register a stack based exception handler to catch any exceptions which\n \/\/ occur in the course of the test.\n int ret = -1;\n __try {\n ret = base::TestSuite::Run();\n }\n\n _except(EXCEPTION_EXECUTE_HANDLER) {\n ret = -1;\n }\n return ret;\n }\n};\n\nint main(int argc, char **argv) {\n base::EnableTerminationOnHeapCorruption();\n base::PlatformThread::SetName(\"ChromeFrame tests\");\n\n _set_purecall_handler(PureCall);\n\n ChromeFrameTestSuite test_suite(argc, argv);\n\n SetConfigBool(kChromeFrameHeadlessMode, true);\n SetConfigBool(kChromeFrameAccessibleMode, true);\n\n base::ProcessHandle crash_service = chrome_frame_test::StartCrashService();\n int ret = -1;\n \/\/ If mini_installer is used to register CF, we use the switch\n \/\/ --no-registration to avoid repetitive registration.\n if (CommandLine::ForCurrentProcess()->HasSwitch(kNoRegistrationSwitch)) {\n ret = test_suite.Run();\n } else {\n \/\/ Register paths needed by the ScopedChromeFrameRegistrar.\n chrome::RegisterPathProvider();\n\n \/\/ This will register the chrome frame in the build directory. It currently\n \/\/ leaves that chrome frame registered once the tests are done. It must be\n \/\/ constructed AFTER the TestSuite is created since TestSuites create THE\n \/\/ AtExitManager.\n \/\/ TODO(robertshield): Make these tests restore the original registration\n \/\/ once done.\n ScopedChromeFrameRegistrar registrar;\n\n \/\/ Register IAccessible2 proxy stub DLL, needed for some tests.\n ScopedChromeFrameRegistrar ia2_registrar(\n chrome_frame_test::GetIAccessible2ProxyStubPath().value());\n\n ret = test_suite.Run();\n }\n\n if (ret == -1) {\n LOG(ERROR) << \"ChromeFrame tests crashed\";\n chrome_frame_test::KillProcesses(L\"iexplore.exe\", 0, false);\n chrome_frame_test::KillProcesses(L\"firefox.exe\", 0, false);\n }\n\n DeleteConfigValue(kChromeFrameHeadlessMode);\n DeleteConfigValue(kChromeFrameAccessibleMode);\n\n if (crash_service)\n base::KillProcess(crash_service, 0, false);\n}\n<commit_msg>Fix a dumb error in the chrome frame tests code which attempts to terminate any running browser processes on a crash. The exception handler was not registered correctly.<commit_after>\/\/ Copyright (c) 2010 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 <atlbase.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/process_util.h\"\n#include \"base\/test\/test_suite.h\"\n#include \"base\/threading\/platform_thread.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/chrome_frame_ui_test_utils.h\"\n#include \"chrome_frame\/test_utils.h\"\n#include \"chrome_frame\/utils.h\"\n\n\/\/ To enable ATL-based code to run in this module\nclass ChromeFrameUnittestsModule\n : public CAtlExeModuleT<ChromeFrameUnittestsModule> {\n public:\n static HRESULT InitializeCom() {\n return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);\n }\n};\n\nChromeFrameUnittestsModule _AtlModule;\n\nconst char kNoRegistrationSwitch[] = \"no-registration\";\n\nvoid PureCall() {\n __debugbreak();\n}\n\n\/\/ This class implements the Run method and registers an exception handler to\n\/\/ ensure that any ChromeFrame processes like IE, Firefox, etc are terminated\n\/\/ if there is a crash in the chrome frame test suite.\nclass ChromeFrameTestSuite : public base::TestSuite {\n public:\n ChromeFrameTestSuite(int argc, char** argv)\n : base::TestSuite(argc, argv) {}\n\n int Run() {\n \/\/ Register a stack based exception handler to catch any exceptions which\n \/\/ occur in the course of the test.\n int ret = -1;\n __try {\n ret = base::TestSuite::Run();\n }\n\n __except(EXCEPTION_EXECUTE_HANDLER) {\n ret = -1;\n }\n return ret;\n }\n};\n\nint main(int argc, char **argv) {\n base::EnableTerminationOnHeapCorruption();\n base::PlatformThread::SetName(\"ChromeFrame tests\");\n\n _set_purecall_handler(PureCall);\n\n ChromeFrameTestSuite test_suite(argc, argv);\n\n SetConfigBool(kChromeFrameHeadlessMode, true);\n SetConfigBool(kChromeFrameAccessibleMode, true);\n\n base::ProcessHandle crash_service = chrome_frame_test::StartCrashService();\n int ret = -1;\n \/\/ If mini_installer is used to register CF, we use the switch\n \/\/ --no-registration to avoid repetitive registration.\n if (CommandLine::ForCurrentProcess()->HasSwitch(kNoRegistrationSwitch)) {\n ret = test_suite.Run();\n } else {\n \/\/ Register paths needed by the ScopedChromeFrameRegistrar.\n chrome::RegisterPathProvider();\n\n \/\/ This will register the chrome frame in the build directory. It currently\n \/\/ leaves that chrome frame registered once the tests are done. It must be\n \/\/ constructed AFTER the TestSuite is created since TestSuites create THE\n \/\/ AtExitManager.\n \/\/ TODO(robertshield): Make these tests restore the original registration\n \/\/ once done.\n ScopedChromeFrameRegistrar registrar;\n\n \/\/ Register IAccessible2 proxy stub DLL, needed for some tests.\n ScopedChromeFrameRegistrar ia2_registrar(\n chrome_frame_test::GetIAccessible2ProxyStubPath().value());\n\n ret = test_suite.Run();\n }\n\n if (ret == -1) {\n LOG(ERROR) << \"ChromeFrame tests crashed\";\n chrome_frame_test::KillProcesses(L\"iexplore.exe\", 0, false);\n chrome_frame_test::KillProcesses(L\"firefox.exe\", 0, false);\n }\n\n DeleteConfigValue(kChromeFrameHeadlessMode);\n DeleteConfigValue(kChromeFrameAccessibleMode);\n\n if (crash_service)\n base::KillProcess(crash_service, 0, false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * PathResolver.cpp\n * openc2e\n *\n * Created by Bryan Donlan\n * Copyright (c) 2005 Bryan Donlan. 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 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 *\/\n\n#include \"PathResolver.h\"\n\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <set>\n#include <map>\n#include <cctype>\n#include <string>\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::filesystem;\n\nstatic set<string> dircache;\nstatic map<string, string> cache;\n\nstatic bool checkDirCache(path &dir);\nstatic bool doCacheDir(path &dir);\n\n\/* C++ is far too verbose for its own good *\/\nstatic string toLowerCase(string in) {\n\ttransform(in.begin(), in.end(), in.begin(), (int(*)(int))tolower);\n\treturn in;\n}\n\nstatic path lcpath(path &orig) {\n\treturn path(toLowerCase(orig.string()), native);\n}\n\nstatic path lcleaf(path &orig) {\n\tpath br, leaf;\n\tbr = orig.branch_path();\n\tleaf = path(toLowerCase(orig.leaf()), native);\n\treturn br \/ leaf;\n}\n\nbool resolveFile(path &p) {\n\tstring s = p.string();\n\tif (!resolveFile(s))\n\t\treturn false;\n\tp = path(s);\n\treturn true;\n}\n\nbool resolveFile_(string &srcPath) {\n\tpath orig(srcPath, native);\n\tif (exists(orig))\n\t\treturn true;\n\t\n\torig.normalize();\n\tpath dir = orig.branch_path();\n\tpath leaf = path(orig.leaf(), native);\n\n\tif (!checkDirCache(dir))\n\t\treturn false;\n\n\torig = dir \/ lcpath(leaf);\n\tstring fn = orig.string();\n\n\/*\tif (exists(orig)) {\n\t\tsrcPath = fn;\n\t\treturn true;\n\t}*\/\n\n\tmap<string, string>::iterator i = cache.find(fn);\n\tif (i == cache.end()) {\n\t\tassert(!exists(orig));\n\t\treturn false;\n\t}\n\tsrcPath = cache[fn];\n\treturn true;\n}\n\nbool resolveFile(std::string &path) {\n\tstd::string orig = path;\n\tbool res = resolveFile_(path);\n\tstd::cerr << orig << \" -> \";\n\tif (!res)\n\t\tstd::cerr << \"(nil)\";\n\telse\n\t\tstd::cerr << path;\n\tstd::cerr << std::endl;\n\treturn res;\n}\n\n\/* If dir is cached, do nothing.\n * If dir exists, cache it.\n * If dir does not exist, see if there's one with different capitalization.\n *\n * If we find a dir, return true. Else, false.\n *\/\nbool checkDirCache(path &dir) {\n\tif (dircache.end() != dircache.find(dir.string()))\n\t\treturn true;\n\tif (exists(dir))\n\t\treturn doCacheDir(dir);\n\tif (dir.empty())\n\t\treturn false;\n\tbool res = resolveFile(dir);\n\tif (!res)\n\t\treturn false;\n\treturn checkDirCache(dir);\n}\n\n\/* Cache a dir. Return true for success.\n *\/\nbool doCacheDir(path &dir) {\n\tdirectory_iterator it(dir);\n\tdirectory_iterator fsend;\n\twhile (it != fsend) {\n\t\tpath cur = *it++;\n\t\tstring key, val;\n\t\tkey = cur.string();\n\t\tval = lcleaf(cur).string();\n\t\tcache[val] = key;\n\t}\n\tdircache.insert(dir.string());\n\treturn true;\n}\n\/* vim: set noet: *\/\n<commit_msg>make PathResolver work, temporarily<commit_after>\/*\n * PathResolver.cpp\n * openc2e\n *\n * Created by Bryan Donlan\n * Copyright (c) 2005 Bryan Donlan. 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 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 *\/\n\n#include \"PathResolver.h\"\n\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <set>\n#include <map>\n#include <cctype>\n#include <string>\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::filesystem;\n\nstatic set<string> dircache;\nstatic map<string, string> cache;\n\nstatic bool checkDirCache(path &dir);\nstatic bool doCacheDir(path &dir);\n\n\/* C++ is far too verbose for its own good *\/\nstatic string toLowerCase(string in) {\n\ttransform(in.begin(), in.end(), in.begin(), (int(*)(int))tolower);\n\treturn in;\n}\n\nstatic path lcpath(path &orig) {\n\treturn path(toLowerCase(orig.string()), native);\n}\n\nstatic path lcleaf(path &orig) {\n\tpath br, leaf;\n\tbr = orig.branch_path();\n\tleaf = path(toLowerCase(orig.leaf()), native);\n\treturn br \/ leaf;\n}\n\nbool resolveFile(path &p) {\n\tstring s = p.string();\n\tif (!resolveFile(s))\n\t\treturn false;\n\tp = path(s);\n\treturn true;\n}\n\nbool resolveFile_(string &srcPath) {\n\tpath orig(srcPath, native);\n\tif (exists(orig))\n\t\treturn true;\n\t\n\torig.normalize();\n\tpath dir = orig.branch_path();\n\tpath leaf = path(orig.leaf(), native);\n\n\tif (!checkDirCache(dir))\n\t\treturn false;\n\n\torig = dir \/ lcpath(leaf);\n\tstring fn = orig.string();\n\n\tif (exists(orig)) {\n\t\tsrcPath = fn;\n\t\treturn true;\n\t}\n\n\tmap<string, string>::iterator i = cache.find(fn);\n\tif (i == cache.end()) {\n\t\tassert(!exists(orig));\n\t\treturn false;\n\t}\n\tsrcPath = cache[fn];\n\treturn true;\n}\n\nbool resolveFile(std::string &path) {\n\tstd::string orig = path;\n\tbool res = resolveFile_(path);\n\t\/*std::cerr << orig << \" -> \";\n\tif (!res)\n\t\tstd::cerr << \"(nil)\";\n\telse\n\t\tstd::cerr << path;\n\tstd::cerr << std::endl;*\/\n\treturn res;\n}\n\n\/* If dir is cached, do nothing.\n * If dir exists, cache it.\n * If dir does not exist, see if there's one with different capitalization.\n *\n * If we find a dir, return true. Else, false.\n *\/\nbool checkDirCache(path &dir) {\n\tif (dircache.end() != dircache.find(dir.string()))\n\t\treturn true;\n\tif (exists(dir))\n\t\treturn doCacheDir(dir);\n\tif (dir.empty())\n\t\treturn false;\n\tbool res = resolveFile(dir);\n\tif (!res)\n\t\treturn false;\n\treturn checkDirCache(dir);\n}\n\n\/* Cache a dir. Return true for success.\n *\/\nbool doCacheDir(path &dir) {\n\tdirectory_iterator it(dir);\n\tdirectory_iterator fsend;\n\twhile (it != fsend) {\n\t\tpath cur = *it++;\n\t\tstring key, val;\n\t\tkey = cur.string();\n\t\tval = lcleaf(cur).string();\n\t\tcache[val] = key;\n\t}\n\tdircache.insert(dir.string());\n\treturn true;\n}\n\/* vim: set noet: *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"test.h\"\n#include \"test-stats.h\"\n\n#include \"grok\/context.h\"\n#include \"input\/input-stream.h\"\n#include \"input\/readline.h\"\n#include \"lexer\/lexer.h\"\n#include \"object\/jsbasicobject.h\"\n#include \"object\/argument.h\"\n#include \"object\/function.h\"\n#include \"parser\/parser.h\"\n#include \"vm\/codegen.h\"\n#include \"vm\/context.h\"\n#include \"vm\/instruction-list.h\"\n#include \"vm\/printer.h\"\n#include \"vm\/vm.h\"\n#include \"common\/colors.h\"\n\n#include <iostream>\n#include <cerrno>\n#include <chrono>\n#include <algorithm>\n#include <boost\/filesystem.hpp>\n\nusing namespace grok;\nusing namespace grok::vm;\nusing namespace grok::parser;\nusing namespace grok::input;\n\nnamespace grok {\nnamespace test {\n\ntemplate<typename Diff>\nvoid log_progress(Diff d)\n{\n std::cout << \n (double)std::chrono::duration_cast\n <std::chrono::microseconds>(d).count() \/ (double)1000\n << \"ms\" << std::flush;\n}\n\nstd::shared_ptr<grok::obj::Handle>\n AssertEqual(std::shared_ptr<grok::obj::Argument> args)\n{\n auto rhs = args->GetProperty(\"rhs\")->as<grok::obj::JSObject>();\n auto lhs = args->GetProperty(\"lhs\")->as<grok::obj::JSObject>();\n auto msg = args->GetProperty(\"msg\")->as<grok::obj::JSObject>()->ToString();\n\n if ((rhs->GetType() == grok::obj::ObjectType::_double\n || rhs->GetType() == grok::obj::ObjectType::_number)\n && (lhs->GetType() == grok::obj::ObjectType::_double\n || lhs->GetType() == grok::obj::ObjectType::_number)\n && (rhs->ToString() == lhs->ToString())\n && (rhs->AsString() == lhs->AsString()))\n return grok::obj::CreateUndefinedObject();\n \n if (rhs->GetType() != lhs->GetType()) {\n throw std::runtime_error(std::string(\"AssertEqual failed: \")\n + rhs->ToString() + \" is not equal to \" + lhs->ToString()\n + \" types were not same [ msg: \" + msg + \"]\");\n }\n if (rhs->ToString() != lhs->ToString())\n throw std::runtime_error(std::string(\"AssertEqual failed: \")\n + rhs->ToString() + \" is not equal to \" + lhs->ToString()\n + \" toString's were not same [ msg: \" + msg + \"]\");\n\n if (rhs->AsString() != lhs->AsString())\n throw std::runtime_error(std::string(\"AssertEqual failed: \")\n + rhs->ToString() + \" is not equal to \" + lhs->ToString()\n + \" asString's were not same [ msg: \" + msg + \"]\");\n\n return grok::obj::CreateUndefinedObject();\n}\n\nstd::shared_ptr<grok::obj::Handle>\n AssertNotEqual(std::shared_ptr<grok::obj::Argument> args)\n{\n auto rhs = args->GetProperty(\"rhs\")->as<grok::obj::JSObject>();\n auto lhs = args->GetProperty(\"lhs\")->as<grok::obj::JSObject>();\n\n if (rhs->GetType() == lhs->GetType()) {\n throw std::runtime_error(std::string(\"AssertNotEqual failed: \")\n + rhs->ToString() + \" is equal to \" + lhs->ToString());\n }\n if (rhs->ToString() == lhs->ToString())\n throw std::runtime_error(std::string(\"AssertNotEqual failed: \")\n + rhs->ToString() + \" is equal to \" + lhs->ToString());\n\n if (rhs->AsString() == lhs->AsString())\n throw std::runtime_error(std::string(\"AssertNotEqual failed: \")\n + rhs->ToString() + \" is equal to \" + lhs->ToString());\n\n return grok::obj::CreateUndefinedObject();\n}\n\nTest &Test::Prepare(std::string file)\n{\n file_ = file;\n expected_result_file_ = file;\n expected_result_file_.resize(file.size() - 3);\n expected_result_file_ += \".txt\";\n\n grok::vm::InitializeVMContext();\n auto v = grok::vm::GetGlobalVMContext()->GetVStore();\n auto func = grok::obj::CreateFunction(AssertEqual);\n func->as<grok::obj::Function>()->SetParams({ \"lhs\", \"rhs\", \"msg\" });\n v->StoreValue(\"assert_equal\", func);\n\n func = grok::obj::CreateFunction(AssertNotEqual);\n func->as<grok::obj::Function>()->SetParams({ \"lhs\", \"rhs\" });\n v->StoreValue(\"assert_not_equal\", func);\n return *this;\n}\n\nstd::string ReadFile(std::string file_)\n{\n std::string v;\n if (FILE *fp = fopen(file_.c_str(), \"r\"))\n {\n char buf[1024];\n while (size_t len = fread(buf, 1, sizeof(buf), fp))\n v.insert(v.end(), buf, buf + len);\n fclose(fp);\n } else {\n std::cout << \"fatal: \" << file_ << \": \"\n << strerror(errno);\n throw std::runtime_error(\"\");\n }\n return v;\n}\n\nbool Test::CheckResult(std::string result)\n{\n std::string expected_result = ReadFile(expected_result_file_);\n\n return expected_result == result;\n}\n\nbool Test::StartTest(int32_t flags)\n{\n std::string file = ReadFile(file_);\n\n auto lex = std::make_unique<Lexer>(file);\n\n GrokParser parser{ std::move(lex) };\n if (!parser.ParseExpression())\n return !(flags & f_syntax_errors); \/\/ test failed\n\n auto ast = parser.ParsedAST();\n\n std::shared_ptr<InstructionList> IR;\n try {\n CodeGenerator codegen;\n codegen.Generate(ast.get());\n\n IR = codegen.GetIR();\n if (!IR || IR->size() == 0) \n return true;\n\n } catch (std::exception &e) {\n if (f_print_reason & flags)\n std::cout << e.what() << std::endl;\n return !(flags & f_ir_errors);\n }\n\n try {\n auto vm = grok::vm::CreateVM(grok::vm::GetGlobalVMContext());\n vm->SetCounters(IR->begin(), IR->end());\n \n vm->Run();\n\n Value result = vm->GetResult();\n auto obj = result.O->as<grok::obj::JSObject>();\n\n std::string res = obj->AsString();\n\n grok::GetContext()->RunIO();\n return true;\n } catch (std::exception &e) {\n if (flags & f_print_reason)\n std::cout << e.what() << std::endl;\n return !(flags & f_vm_errors);\n }\n}\n\n}\n}\n\nint main(int argc, char *argv[])\n{\n grok::InitializeContext();\n int test_id = -1;\n\n if (argc >= 2) { \n if (std::string(argv[1]) == \"-h\" || \n std::string(argv[1]) == \"--help\") {\n std::cerr << \"Usage: \" << argv[0] << \" <test_number>\" << std::endl;\n return 1;\n } else {\n try {\n test_id = std::stoi(argv[1]);\n } catch (std::exception &e) {\n std::cerr << \"bad number\" << std::endl;\n return 1;\n }\n }\n }\n grok::GetContext()->SetDebugExecution();\n using namespace boost::filesystem;\n using namespace grok::test;\n using namespace std;\n\n path p(\"..\/test\/testing\");\n\n try {\n if (!exists(p)) {\n std::cerr << \"There is no test directory! Did you delete it?\"\n << std::endl;\n }\n\n if (!is_directory(p)) {\n std::cerr << \"It is odd. 'test' was always a directory containing\"\n \" many test files but it turns out that 'test' is not a \"\n \"directory at all.\" << std::endl;\n }\n\n \/\/ we are good\n std::vector<std::string> files;\n size_t count = 0;\n \tdirectory_iterator e;\n for (directory_iterator it(p); it != e; ++it) {\n std::cout << \"\\rCounting test files: \" << count++;\n std::cout << std::flush;\n files.push_back(it->path().string());\n }\n std::cout << std::endl;\n\n std::sort(files.begin(), files.end());\n TestStats stats;\n size_t i = 0;\n\n \/\/ run the tests\n\n if (test_id < 0) {\n for (auto file : files) {\n auto s = std::chrono::high_resolution_clock::now();\n \n std::cout << \"Testing '\" << file + '\\'' << std::endl;\n Test test{ grok::GetContext() };\n\n if (test.Prepare(file).StartTest(f_syntax_errors | f_ir_errors\n | f_vm_errors | f_print_reason)) {\n std::cout << \"Test[\" << ++i << \"] <\"\n << file << \">: passed.\";\n stats.AddPassed();\n } else {\n std::cout << \"Test[\" << ++i << \"] <\"\n << file << \">: failed.\";\n stats.AddFailed();\n }\n\n auto e = std::chrono::high_resolution_clock::now();\n std::cout << \"[ time: \";\n log_progress(e - s);\n std::cout << \" ]\" << std::endl;\n }\n } else {\n auto s = std::chrono::high_resolution_clock::now();\n if (test_id > files.size()) {\n std::cerr << \"test not written yet!\" << std::endl;\n return 1;\n }\n auto file = files[test_id];\n std::cout << \"Testing '\" << file + '\\'' << std::endl;\n Test test{ grok::GetContext() };\n\n if (test.Prepare(file).StartTest(f_syntax_errors | f_ir_errors\n | f_vm_errors | f_print_reason)) {\n std::cout << \"Test[\" << ++i << \"] <\"\n << file << \">: passed.\";\n stats.AddPassed();\n } else {\n std::cout << \"Test[\" << ++i << \"] <\"\n << file << \">: failed.\";\n stats.AddFailed();\n }\n\n auto e = std::chrono::high_resolution_clock::now();\n std::cout << \"[ time: \";\n log_progress(e - s);\n std::cout << \" ]\" << std::endl;\n }\n\n std::cout << stats << std::endl;\n return 0;\n } catch (std::exception &e) {\n std::cerr << e.what() << std::endl;\n }\n return -1;\n}\n\n<commit_msg>Show colored output<commit_after>#include \"test.h\"\n#include \"test-stats.h\"\n\n#include \"grok\/context.h\"\n#include \"input\/input-stream.h\"\n#include \"input\/readline.h\"\n#include \"lexer\/lexer.h\"\n#include \"object\/jsbasicobject.h\"\n#include \"object\/argument.h\"\n#include \"object\/function.h\"\n#include \"parser\/parser.h\"\n#include \"vm\/codegen.h\"\n#include \"vm\/context.h\"\n#include \"vm\/instruction-list.h\"\n#include \"vm\/printer.h\"\n#include \"vm\/vm.h\"\n#include \"common\/colors.h\"\n\n#include <iostream>\n#include <cerrno>\n#include <chrono>\n#include <algorithm>\n#include <boost\/filesystem.hpp>\n\nusing namespace grok;\nusing namespace grok::vm;\nusing namespace grok::parser;\nusing namespace grok::input;\n\nnamespace grok {\nnamespace test {\n\ntemplate<typename Diff>\nvoid log_progress(Diff d)\n{\n std::cout << \n (double)std::chrono::duration_cast\n <std::chrono::microseconds>(d).count() \/ (double)1000\n << \"ms\" << std::flush;\n}\n\nstd::shared_ptr<grok::obj::Handle>\n AssertEqual(std::shared_ptr<grok::obj::Argument> args)\n{\n auto rhs = args->GetProperty(\"rhs\")->as<grok::obj::JSObject>();\n auto lhs = args->GetProperty(\"lhs\")->as<grok::obj::JSObject>();\n auto msg = args->GetProperty(\"msg\")->as<grok::obj::JSObject>()->ToString();\n\n if ((rhs->GetType() == grok::obj::ObjectType::_double\n || rhs->GetType() == grok::obj::ObjectType::_number)\n && (lhs->GetType() == grok::obj::ObjectType::_double\n || lhs->GetType() == grok::obj::ObjectType::_number)\n && (rhs->ToString() == lhs->ToString())\n && (rhs->AsString() == lhs->AsString()))\n return grok::obj::CreateUndefinedObject();\n \n if (rhs->GetType() != lhs->GetType()) {\n throw std::runtime_error(std::string(\"AssertEqual failed: \")\n + rhs->ToString() + \" is not equal to \" + lhs->ToString()\n + \" types were not same [ msg: \" + msg + \"]\");\n }\n if (rhs->ToString() != lhs->ToString())\n throw std::runtime_error(std::string(\"AssertEqual failed: \")\n + rhs->ToString() + \" is not equal to \" + lhs->ToString()\n + \" toString's were not same [ msg: \" + msg + \"]\");\n\n if (rhs->AsString() != lhs->AsString())\n throw std::runtime_error(std::string(\"AssertEqual failed: \")\n + rhs->ToString() + \" is not equal to \" + lhs->ToString()\n + \" asString's were not same [ msg: \" + msg + \"]\");\n\n return grok::obj::CreateUndefinedObject();\n}\n\nstd::shared_ptr<grok::obj::Handle>\n AssertNotEqual(std::shared_ptr<grok::obj::Argument> args)\n{\n auto rhs = args->GetProperty(\"rhs\")->as<grok::obj::JSObject>();\n auto lhs = args->GetProperty(\"lhs\")->as<grok::obj::JSObject>();\n\n if (rhs->GetType() == lhs->GetType()) {\n throw std::runtime_error(std::string(\"AssertNotEqual failed: \")\n + rhs->ToString() + \" is equal to \" + lhs->ToString());\n }\n if (rhs->ToString() == lhs->ToString())\n throw std::runtime_error(std::string(\"AssertNotEqual failed: \")\n + rhs->ToString() + \" is equal to \" + lhs->ToString());\n\n if (rhs->AsString() == lhs->AsString())\n throw std::runtime_error(std::string(\"AssertNotEqual failed: \")\n + rhs->ToString() + \" is equal to \" + lhs->ToString());\n\n return grok::obj::CreateUndefinedObject();\n}\n\nTest &Test::Prepare(std::string file)\n{\n file_ = file;\n expected_result_file_ = file;\n expected_result_file_.resize(file.size() - 3);\n expected_result_file_ += \".txt\";\n\n grok::vm::InitializeVMContext();\n auto v = grok::vm::GetGlobalVMContext()->GetVStore();\n auto func = grok::obj::CreateFunction(AssertEqual);\n func->as<grok::obj::Function>()->SetParams({ \"lhs\", \"rhs\", \"msg\" });\n v->StoreValue(\"assert_equal\", func);\n\n func = grok::obj::CreateFunction(AssertNotEqual);\n func->as<grok::obj::Function>()->SetParams({ \"lhs\", \"rhs\" });\n v->StoreValue(\"assert_not_equal\", func);\n return *this;\n}\n\nstd::string ReadFile(std::string file_)\n{\n std::string v;\n if (FILE *fp = fopen(file_.c_str(), \"r\"))\n {\n char buf[1024];\n while (size_t len = fread(buf, 1, sizeof(buf), fp))\n v.insert(v.end(), buf, buf + len);\n fclose(fp);\n } else {\n std::cout << \"fatal: \" << file_ << \": \"\n << strerror(errno);\n throw std::runtime_error(\"\");\n }\n return v;\n}\n\nbool Test::CheckResult(std::string result)\n{\n std::string expected_result = ReadFile(expected_result_file_);\n\n return expected_result == result;\n}\n\nbool Test::StartTest(int32_t flags)\n{\n std::string file = ReadFile(file_);\n\n auto lex = std::make_unique<Lexer>(file);\n\n GrokParser parser{ std::move(lex) };\n if (!parser.ParseExpression())\n return !(flags & f_syntax_errors); \/\/ test failed\n\n auto ast = parser.ParsedAST();\n\n std::shared_ptr<InstructionList> IR;\n try {\n CodeGenerator codegen;\n codegen.Generate(ast.get());\n\n IR = codegen.GetIR();\n if (!IR || IR->size() == 0) \n return true;\n\n } catch (std::exception &e) {\n if (f_print_reason & flags)\n std::cout << e.what() << std::endl;\n return !(flags & f_ir_errors);\n }\n\n try {\n auto vm = grok::vm::CreateVM(grok::vm::GetGlobalVMContext());\n vm->SetCounters(IR->begin(), IR->end());\n \n vm->Run();\n\n Value result = vm->GetResult();\n auto obj = result.O->as<grok::obj::JSObject>();\n\n std::string res = obj->AsString();\n\n grok::GetContext()->RunIO();\n return true;\n } catch (std::exception &e) {\n if (flags & f_print_reason)\n std::cout << e.what() << std::endl;\n return !(flags & f_vm_errors);\n }\n}\n\n}\n}\n\nint main(int argc, char *argv[])\n{\n grok::InitializeContext();\n int test_id = -1;\n\n if (argc >= 2) { \n if (std::string(argv[1]) == \"-h\" || \n std::string(argv[1]) == \"--help\") {\n std::cerr << \"Usage: \" << argv[0] << \" <test_number>\" << std::endl;\n return 1;\n } else {\n try {\n test_id = std::stoi(argv[1]);\n } catch (std::exception &e) {\n std::cerr << \"bad number\" << std::endl;\n return 1;\n }\n }\n }\n grok::GetContext()->SetDebugExecution();\n using namespace boost::filesystem;\n using namespace grok::test;\n using namespace std;\n\n path p(\"..\/test\/testing\");\n\n try {\n if (!exists(p)) {\n std::cerr << \"There is no test directory! Did you delete it?\"\n << std::endl;\n }\n\n if (!is_directory(p)) {\n std::cerr << \"It is odd. 'test' was always a directory containing\"\n \" many test files but it turns out that 'test' is not a \"\n \"directory at all.\" << std::endl;\n }\n\n \/\/ we are good\n std::vector<std::string> files;\n size_t count = 0;\n \tdirectory_iterator e;\n for (directory_iterator it(p); it != e; ++it) {\n std::cout << \"\\rCounting test files: \" << count++;\n std::cout << std::flush;\n files.push_back(it->path().string());\n }\n std::cout << std::endl;\n\n std::sort(files.begin(), files.end());\n TestStats stats;\n size_t i = 0;\n\n \/\/ run the tests\n\n if (test_id < 0) {\n for (auto file : files) {\n auto s = std::chrono::high_resolution_clock::now();\n \n std::cout << \"Testing '\" << file + '\\'' << std::endl;\n Test test{ grok::GetContext() };\n\n if (test.Prepare(file).StartTest(f_syntax_errors | f_ir_errors\n | f_vm_errors | f_print_reason)) {\n std::cout << Color::Color(Color::fgreen, Color::dim)\n << \"Test[\" << ++i << \"] <\" << file\n << \">: passed.\" << Color::Reset();\n stats.AddPassed();\n } else {\n std::cout << Color::Color(Color::fgreen, Color::bold)\n << \"Test[\" << ++i << \"] <\"\n << file << \">: failed.\" << Color::Reset();\n stats.AddFailed();\n }\n\n auto e = std::chrono::high_resolution_clock::now();\n std::cout << \"[ time: \";\n log_progress(e - s);\n std::cout << \" ]\" << std::endl;\n }\n } else {\n auto s = std::chrono::high_resolution_clock::now();\n if (test_id > files.size()) {\n std::cerr << \"test not written yet!\" << std::endl;\n return 1;\n }\n auto file = files[test_id];\n std::cout << \"Testing '\" << file + '\\'' << std::endl;\n Test test{ grok::GetContext() };\n\n if (test.Prepare(file).StartTest(f_syntax_errors | f_ir_errors\n | f_vm_errors | f_print_reason)) {\n std::cout << \"Test[\" << ++i << \"] <\"\n << file << \">: passed.\";\n stats.AddPassed();\n } else {\n std::cout << \"Test[\" << ++i << \"] <\"\n << file << \">: failed.\";\n stats.AddFailed();\n }\n\n auto e = std::chrono::high_resolution_clock::now();\n std::cout << \"[ time: \";\n log_progress(e - s);\n std::cout << \" ]\" << std::endl;\n }\n\n std::cout << stats << std::endl;\n return 0;\n } catch (std::exception &e) {\n std::cerr << e.what() << std::endl;\n }\n return -1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)alimdc:$Name$:$Id$\n\/\/ Author: Fons Rademakers 26\/11\/99\n\n\/**************************************************************************\n * Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ AliRunDB \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <TSystem.h>\n#include <TFile.h>\n#include <TString.h>\n#include <TDatime.h>\n#include <TSQLServer.h>\n#include <TSQLResult.h>\n#include <TGrid.h>\n\n#include \"AliStats.h\"\n#include \"AliRawDB.h\"\n\n#include \"AliRunDB.h\"\n\n\nClassImp(AliRunDB)\n\n\n\/\/______________________________________________________________________________\nAliRunDB::AliRunDB(const char* localFS, Bool_t rdbms, \n\t\t const char* alienHost, const char* alienDir) :\n fRunDB(NULL),\n fRDBMS(rdbms),\n fAlienHost(alienHost),\n fAlienDir(alienDir)\n{\n \/\/ Open run database, and get or create tree.\n\n if (!localFS) return;\n\n \/\/ Get hostname\n char hostname[64], filename[64];\n\n \/\/ check that fs exists (crude check fails if fs is a file)\n gSystem->MakeDirectory(localFS);\n\n strcpy(hostname, gSystem->HostName());\n\n char *s;\n if ((s = strchr(hostname, '.')))\n *s = 0;\n\n sprintf(filename, \"%s\/%s_rundb.root\", localFS, hostname);\n\n if (!gSystem->AccessPathName(filename, kFileExists))\n fRunDB = new TFile(filename, \"UPDATE\");\n else\n fRunDB = new TFile(filename, \"CREATE\", Form(\"ALICE MDC%d Run DB\", AliRawDB::kMDC));\n}\n\n\/\/______________________________________________________________________________\nAliRunDB::AliRunDB(const AliRunDB& runDB): TObject(runDB)\n{\n\/\/ copy constructor\n\n Fatal(\"AliRunDB\", \"copy constructor not implemented\");\n}\n\n\/\/______________________________________________________________________________\nAliRunDB& AliRunDB::operator = (const AliRunDB& \/*runDB*\/)\n{\n\/\/ assignment operator\n\n Fatal(\"operator =\", \"assignment operator not implemented\");\n return *this;\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::Update(AliStats *stats)\n{\n UpdateLocal(stats);\n UpdateRDBMS(stats);\n UpdateAliEn(stats);\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::UpdateLocal(AliStats *stats)\n{\n \/\/ Add stats object to database.\n\n if (!stats || !fRunDB) return;\n\n TDirectory *ds = gDirectory;\n fRunDB->cd();\n\n char sname[64];\n char *s = (char*)strrchr(stats->GetFileName(), '\/');\n if (s) {\n s++;\n strcpy(sname, s);\n } else\n strcpy(sname, stats->GetFileName());\n s = strchr(sname, '.');\n if (s) *s = 0;\n\n stats->Write(sname);\n\n ds->cd();\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::UpdateRDBMS(AliStats *stats)\n{\n \/\/ Add stats object to central MySQL DB.\n\n if (!stats || !fRDBMS) return;\n\n char sql[4096];\n char bt[25], et[25];\n\n strcpy(bt, stats->GetBeginTime().AsSQLString());\n strcpy(et, stats->GetEndTime().AsSQLString());\n\n sprintf(sql, \"INSERT INTO mdc%dcatalog VALUES (0, '%s', %d, \"\n \"%d, %d, %d, %d, %d, %d, %.2f, '%s', '%s', '%s')\", AliRawDB::kMDC,\n stats->GetFileName(), (int)stats->GetFileSize(), stats->GetEvents(),\n stats->GetFirstRun(), stats->GetFirstEvent(), stats->GetLastRun(),\n stats->GetLastEvent(), stats->GetCompressionMode(),\n stats->GetCompressionFactor(), stats->GetFilterState() ? \"on\" : \"off\",\n bt, et);\n\n \/\/ open connection to MySQL server on pcsalo\n TSQLServer *db = TSQLServer::Connect(\"mysql:\/\/pcsalo.cern.ch\/mdc\", \"alice\", \"amdc\");\n\n if (!db || db->IsZombie()) {\n Error(\"UpdateRDBMS\", \"failed to connect to MySQL server on pcsalo\");\n printf(\"%s\\n\", sql);\n delete db;\n return;\n }\n\n TSQLResult *res = db->Query(sql);\n\n if (!res) {\n Error(\"UpdateRDBMS\", Form(\"insert into mdc%dcatalog failed\", AliRawDB::kMDC));\n printf(\"%s\\n\", sql);\n }\n\n delete res;\n delete db;\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::UpdateAliEn(AliStats *stats)\n{\n \/\/ Record file in AliEn catalog.\n\n if (!stats || fAlienHost.IsNull()) return;\n\n TGrid *g = TGrid::Connect(fAlienHost, \"\");\n\n TString lfn = fAlienDir;\n TDatime dt;\n\n \/\/ make a subdirectory for each day\n lfn += \"\/adc-\";\n lfn += dt.GetDate();\n\n \/\/ check if directory exists, if not create it\n Grid_ResultHandle_t res = 0;\n if (!(res = g->OpenDir(lfn))) {\n \/\/ directory does not exist, create it\n if (g->Mkdir(lfn) == -1) {\n Error(\"UpdateAliEn\", \"cannot create directory %s\", lfn.Data());\n lfn = fAlienDir;\n }\n }\n if (res) g->CloseResult(res);\n\n lfn += \"\/\";\n lfn += gSystem->BaseName(stats->GetFileName());\n\n Int_t result = g->AddFile(lfn, stats->GetFileName(),\n\t\t\t (int)stats->GetFileSize());\n\n if (result == -1) {\n Error(\"UpdateAliEn\", \"error adding file to AliEn catalog\");\n printf(\"AliEn: AddFile(%s, %s, %d)\\n\", lfn.Data(), stats->GetFileName(),\n (int)stats->GetFileSize());\n }\n\n delete g;\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::Close()\n{\n \/\/ Close run database.\n\n if (fRunDB) fRunDB->Close();\n delete fRunDB;\n}\n\n<commit_msg>Additional protection in case ROOT is compiled without AliEn support<commit_after>\/\/ @(#)alimdc:$Name$:$Id$\n\/\/ Author: Fons Rademakers 26\/11\/99\n\n\/**************************************************************************\n * Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ AliRunDB \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <TSystem.h>\n#include <TFile.h>\n#include <TString.h>\n#include <TDatime.h>\n#include <TSQLServer.h>\n#include <TSQLResult.h>\n#include <TGrid.h>\n\n#include \"AliStats.h\"\n#include \"AliRawDB.h\"\n\n#include \"AliRunDB.h\"\n\n\nClassImp(AliRunDB)\n\n\n\/\/______________________________________________________________________________\nAliRunDB::AliRunDB(const char* localFS, Bool_t rdbms, \n\t\t const char* alienHost, const char* alienDir) :\n fRunDB(NULL),\n fRDBMS(rdbms),\n fAlienHost(alienHost),\n fAlienDir(alienDir)\n{\n \/\/ Open run database, and get or create tree.\n\n if (!localFS) return;\n\n \/\/ Get hostname\n char hostname[64], filename[64];\n\n \/\/ check that fs exists (crude check fails if fs is a file)\n gSystem->MakeDirectory(localFS);\n\n strcpy(hostname, gSystem->HostName());\n\n char *s;\n if ((s = strchr(hostname, '.')))\n *s = 0;\n\n sprintf(filename, \"%s\/%s_rundb.root\", localFS, hostname);\n\n if (!gSystem->AccessPathName(filename, kFileExists))\n fRunDB = new TFile(filename, \"UPDATE\");\n else\n fRunDB = new TFile(filename, \"CREATE\", Form(\"ALICE MDC%d Run DB\", AliRawDB::kMDC));\n}\n\n\/\/______________________________________________________________________________\nAliRunDB::AliRunDB(const AliRunDB& runDB): TObject(runDB)\n{\n\/\/ copy constructor\n\n Fatal(\"AliRunDB\", \"copy constructor not implemented\");\n}\n\n\/\/______________________________________________________________________________\nAliRunDB& AliRunDB::operator = (const AliRunDB& \/*runDB*\/)\n{\n\/\/ assignment operator\n\n Fatal(\"operator =\", \"assignment operator not implemented\");\n return *this;\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::Update(AliStats *stats)\n{\n UpdateLocal(stats);\n UpdateRDBMS(stats);\n UpdateAliEn(stats);\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::UpdateLocal(AliStats *stats)\n{\n \/\/ Add stats object to database.\n\n if (!stats || !fRunDB) return;\n\n TDirectory *ds = gDirectory;\n fRunDB->cd();\n\n char sname[64];\n char *s = (char*)strrchr(stats->GetFileName(), '\/');\n if (s) {\n s++;\n strcpy(sname, s);\n } else\n strcpy(sname, stats->GetFileName());\n s = strchr(sname, '.');\n if (s) *s = 0;\n\n stats->Write(sname);\n\n ds->cd();\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::UpdateRDBMS(AliStats *stats)\n{\n \/\/ Add stats object to central MySQL DB.\n\n if (!stats || !fRDBMS) return;\n\n char sql[4096];\n char bt[25], et[25];\n\n strcpy(bt, stats->GetBeginTime().AsSQLString());\n strcpy(et, stats->GetEndTime().AsSQLString());\n\n sprintf(sql, \"INSERT INTO mdc%dcatalog VALUES (0, '%s', %d, \"\n \"%d, %d, %d, %d, %d, %d, %.2f, '%s', '%s', '%s')\", AliRawDB::kMDC,\n stats->GetFileName(), (int)stats->GetFileSize(), stats->GetEvents(),\n stats->GetFirstRun(), stats->GetFirstEvent(), stats->GetLastRun(),\n stats->GetLastEvent(), stats->GetCompressionMode(),\n stats->GetCompressionFactor(), stats->GetFilterState() ? \"on\" : \"off\",\n bt, et);\n\n \/\/ open connection to MySQL server on pcsalo\n TSQLServer *db = TSQLServer::Connect(\"mysql:\/\/pcsalo.cern.ch\/mdc\", \"alice\", \"amdc\");\n\n if (!db || db->IsZombie()) {\n Error(\"UpdateRDBMS\", \"failed to connect to MySQL server on pcsalo\");\n printf(\"%s\\n\", sql);\n delete db;\n return;\n }\n\n TSQLResult *res = db->Query(sql);\n\n if (!res) {\n Error(\"UpdateRDBMS\", Form(\"insert into mdc%dcatalog failed\", AliRawDB::kMDC));\n printf(\"%s\\n\", sql);\n }\n\n delete res;\n delete db;\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::UpdateAliEn(AliStats *stats)\n{\n \/\/ Record file in AliEn catalog.\n\n if (!stats || fAlienHost.IsNull()) return;\n\n TGrid *g = TGrid::Connect(fAlienHost, \"\");\n\n \/\/Protection in case root is compiled without AliEn support\n if(!g) {\n Error(\"UpdateAliEn\", \"ROOT compiled without AliEn support\");\n return;\n }\n\n TString lfn = fAlienDir;\n TDatime dt;\n\n \/\/ make a subdirectory for each day\n lfn += \"\/adc-\";\n lfn += dt.GetDate();\n\n \/\/ check if directory exists, if not create it\n Grid_ResultHandle_t res = 0;\n if (!(res = g->OpenDir(lfn))) {\n \/\/ directory does not exist, create it\n if (g->Mkdir(lfn) == -1) {\n Error(\"UpdateAliEn\", \"cannot create directory %s\", lfn.Data());\n lfn = fAlienDir;\n }\n }\n if (res) g->CloseResult(res);\n\n lfn += \"\/\";\n lfn += gSystem->BaseName(stats->GetFileName());\n\n Int_t result = g->AddFile(lfn, stats->GetFileName(),\n\t\t\t (int)stats->GetFileSize());\n\n if (result == -1) {\n Error(\"UpdateAliEn\", \"error adding file to AliEn catalog\");\n printf(\"AliEn: AddFile(%s, %s, %d)\\n\", lfn.Data(), stats->GetFileName(),\n (int)stats->GetFileSize());\n }\n\n delete g;\n}\n\n\/\/______________________________________________________________________________\nvoid AliRunDB::Close()\n{\n \/\/ Close run database.\n\n if (fRunDB) fRunDB->Close();\n delete fRunDB;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>iox-#25 Add further info to todo and disable unimplemented tests (again)<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"ShelfPlayback.h\"\n\nvoid ShelfPlayback::begin() {\n\n if (AMP_POWER > 0) {\n \/\/ Disable amp\n pinMode(AMP_POWER, OUTPUT);\n digitalWrite(AMP_POWER, LOW);\n Serial.println(F(\"Amp powered down\"));\n }\n\n \/\/ initialise the music player\n if (!_musicPlayer.begin()) { \/\/ initialise the music player\n Serial.println(F(\"Couldn't find VS1053, do you have the right pins defined?\"));\n while (1) delay(500);\n }\n Serial.println(F(\"VS1053 found\"));\n\n \/* Fix for the design fuckup of the cheap LC Technology MP3 shield\n see http:\/\/www.bajdi.com\/lcsoft-vs1053-mp3-module\/#comment-33773\n Doesn't hurt for other shields\n *\/\n _musicPlayer.sciWrite(VS1053_REG_WRAMADDR, VS1053_GPIO_DDR);\n _musicPlayer.sciWrite(VS1053_REG_WRAM, 0x0003);\n _musicPlayer.GPIO_digitalWrite(0x0000);\n _musicPlayer.softReset();\n\n Serial.println(F(\"VS1053 soft reset done\"));\n\n if (patchVS1053()) {\n#ifdef USE_DIFFERENTIAL_OUTPUT\n \/\/ Enable differential output\n uint16_t mode = VS1053_MODE_SM_DIFF | VS1053_MODE_SM_SDINEW;\n _musicPlayer.sciWrite(VS1053_REG_MODE, mode);\n#else\n \/\/ Enable Mono Output\n _musicPlayer.sciWrite(VS1053_REG_WRAMADDR, 0x1e09);\n _musicPlayer.sciWrite(VS1053_REG_WRAM, 0x0001);\n#endif\n Serial.println(F(\"VS1053 patch installed\"));\n } else {\n Serial.println(F(\"Could not load patch\"));\n }\n\n Serial.print(F(\"SampleRate \"));\n Serial.println(_musicPlayer.sciRead(VS1053_REG_AUDATA));\n\n _musicPlayer.setVolume(_volume, _volume);\n\n setBassAndTreble(TREBLE_AMPLITUDE, TREBLE_FREQLIMIT, BASS_AMPLITUDE, BASS_FREQLIMIT);\n\n _musicPlayer.dumpRegs();\n\n Serial.println(F(\"VS1053 found\"));\n}\n\n\nbool ShelfPlayback::switchFolder(const char *folder) {\n Serial.print(F(\"Switching folder to \"));\n Serial.println(folder);\n\n if (!_SD.exists(folder)) {\n Serial.println(F(\"Folder does not exist\"));\n return false;\n }\n stopPlayback();\n _SD.chdir(folder);\n _SD.vwd()->rewind();\n _currentFile = \"\";\n return true;\n}\n\nvoid ShelfPlayback::resumePlayback() {\n if(_playing == PLAYBACK_PAUSED) {\n _musicPlayer.pausePlaying(false);\n _playing = PLAYBACK_FILE;\n }\n}\n\nvoid ShelfPlayback::pausePlayback() {\n if(_playing == PLAYBACK_FILE) {\n _musicPlayer.pausePlaying(false);\n _playing = PLAYBACK_PAUSED;\n }\n}\n\nvoid ShelfPlayback::stopPlayback() {\n Serial.println(F(\"Stopping playback\"));\n if(_playing == PLAYBACK_NO) {\n Serial.println(F(\"Already stopped\"));\n return;\n }\n \n if (AMP_POWER > 0) {\n digitalWrite(AMP_POWER, LOW);\n }\n if(_playing == PLAYBACK_FILE) {\n _musicPlayer.stopPlaying();\n }\n _playing = PLAYBACK_NO;\n if(isNight()) {\n _lastNightActivity = millis();\n }\n}\n\nvoid ShelfPlayback::startPlayback() {\n \/\/ IO takes time, reset watchdog timer so it does not kill us\n ESP.wdtFeed();\n SdFile file;\n _SD.vwd()->rewind();\n\n char filenameChar[100];\n _SD.vwd()->getName(filenameChar, 100);\n String dirname = \"\/\" + String(filenameChar) + \"\/\";\n\n String nextFile = \"\";\n\n while (file.openNext(_SD.vwd(), O_READ))\n {\n\n file.getName(filenameChar, 100);\n file.close();\n\n if (file.isDir() || !_musicPlayer.isMP3File(filenameChar)) {\n Serial.print(F(\"Ignoring \")); Serial.println(filenameChar);\n continue;\n }\n\n String tmpFile = String(filenameChar);\n if (_currentFile < tmpFile && (tmpFile < nextFile || nextFile == \"\")) {\n nextFile = tmpFile;\n }\n }\n\n \/\/ Start folder from the beginning\n if (nextFile == \"\" && _currentFile != \"\") {\n _currentFile = \"\";\n startPlayback();\n return;\n }\n\n \/\/ No _currentFile && no nextFile => Nothing to play!\n if (nextFile == \"\") {\n Serial.print(F(\"No mp3 files in \")); Serial.println(dirname);\n stopPlayback();\n return;\n }\n\n startFilePlayback((char *)dirname.c_str(), (char *)nextFile.c_str());\n}\n\nvoid ShelfPlayback::startFilePlayback(const char* folder, const char* nextFile) {\n Serial.print(F(\"Playing \")); Serial.print(folder); Serial.println(nextFile);\n\n _playing = PLAYBACK_FILE;\n _currentFile = nextFile;\n \n char fullPath[116] = \"\";\n strcat(fullPath, folder);\n strcat(fullPath, nextFile);\n _musicPlayer.startPlayingFile(fullPath);\n\n if (AMP_POWER > 0) {\n digitalWrite(AMP_POWER, HIGH);\n }\n}\n\nvoid ShelfPlayback::skipFile() {\n _musicPlayer.stopPlaying();\n startPlayback();\n}\n\nvoid ShelfPlayback::volume(uint8_t volume) {\n if(volume > 50) {\n _volume = 50;\n } else {\n _volume = volume;\n }\n\n uint8_t calcVolume = volume;\n \n if(isNight()) {\n calcVolume = 50 - (NIGHT_FACTOR * (50 - _volume));\n }\n _musicPlayer.setVolume(calcVolume, calcVolume);\n}\n\nvoid ShelfPlayback::volumeUp() {\n if(_volume < 5) {\n volume(0);\n } else {\n volume(_volume - 5);\n }\n}\n\nvoid ShelfPlayback::volumeDown() {\n volume(_volume + 5);\n}\n\n\nvoid ShelfPlayback::setBassAndTreble(uint8_t trebleAmplitude, uint8_t trebleFreqLimit, uint8_t bassAmplitude, uint8_t bassFreqLimit) {\n uint16_t bassReg = 0;\n bassReg |= trebleAmplitude;\n bassReg <<= 4;\n bassReg |= trebleFreqLimit;\n bassReg <<= 4;\n bassReg |= bassAmplitude;\n bassReg <<= 4;\n bassReg |= bassFreqLimit;\n Serial.printf(F(\"bass value: %04x\\n\"), bassReg);\n _musicPlayer.sciWrite(VS1053_REG_BASS, bassReg);\n}\n\nbool ShelfPlayback::patchVS1053() {\n Serial.println(F(\"Installing patch to VS1053\"));\n\n SdFile file;\n if (!file.open(\"patches.053\", O_READ)) return false;\n\n uint16_t addr, n, val, i = 0;\n\n while (file.read(&addr, 2) && file.read(&n, 2)) {\n i += 2;\n if (n & 0x8000U) {\n n &= 0x7FFF;\n if (!file.read(&val, 2)) {\n file.close();\n return false;\n }\n while (n--) {\n _musicPlayer.sciWrite(addr, val);\n }\n } else {\n while (n--) {\n if (!file.read(&val, 2)) {\n file.close();\n return false;\n }\n i++;\n _musicPlayer.sciWrite(addr, val);\n }\n }\n }\n file.close();\n\n Serial.print(F(\"Number of bytes: \")); Serial.println(i);\n return true;\n}\n\nvoid ShelfPlayback::work() {\n if (_playing == PLAYBACK_FILE) {\n if (_musicPlayer.playingMusic) {\n _musicPlayer.feedBuffer();\n } else {\n startPlayback();\n }\n return;\n }\n\n if ((_playing == PLAYBACK_NO || _playing == PLAYBACK_PAUSED) && isNight() && (millis() - _lastNightActivity > NIGHT_TIMEOUT)) {\n stopNight();\n }\n}\n\nvoid ShelfPlayback::startNight() {\n _lastNightActivity = millis();\n _nightMode = true;\n volume(_volume);\n}\n\nbool ShelfPlayback::isNight() {\n return _nightMode;\n}\n\nvoid ShelfPlayback::stopNight() {\n _nightMode = false;\n volume(_volume);\n}\n<commit_msg>Fix pause\/nightmode bugs<commit_after>#include \"ShelfPlayback.h\"\n\nvoid ShelfPlayback::begin() {\n\n if (AMP_POWER > 0) {\n \/\/ Disable amp\n pinMode(AMP_POWER, OUTPUT);\n digitalWrite(AMP_POWER, LOW);\n Serial.println(F(\"Amp powered down\"));\n }\n\n \/\/ initialise the music player\n if (!_musicPlayer.begin()) { \/\/ initialise the music player\n Serial.println(F(\"Couldn't find VS1053, do you have the right pins defined?\"));\n while (1) delay(500);\n }\n Serial.println(F(\"VS1053 found\"));\n\n \/* Fix for the design fuckup of the cheap LC Technology MP3 shield\n see http:\/\/www.bajdi.com\/lcsoft-vs1053-mp3-module\/#comment-33773\n Doesn't hurt for other shields\n *\/\n _musicPlayer.sciWrite(VS1053_REG_WRAMADDR, VS1053_GPIO_DDR);\n _musicPlayer.sciWrite(VS1053_REG_WRAM, 0x0003);\n _musicPlayer.GPIO_digitalWrite(0x0000);\n _musicPlayer.softReset();\n\n Serial.println(F(\"VS1053 soft reset done\"));\n\n if (patchVS1053()) {\n#ifdef USE_DIFFERENTIAL_OUTPUT\n \/\/ Enable differential output\n uint16_t mode = VS1053_MODE_SM_DIFF | VS1053_MODE_SM_SDINEW;\n _musicPlayer.sciWrite(VS1053_REG_MODE, mode);\n#else\n \/\/ Enable Mono Output\n _musicPlayer.sciWrite(VS1053_REG_WRAMADDR, 0x1e09);\n _musicPlayer.sciWrite(VS1053_REG_WRAM, 0x0001);\n#endif\n Serial.println(F(\"VS1053 patch installed\"));\n } else {\n Serial.println(F(\"Could not load patch\"));\n }\n\n Serial.print(F(\"SampleRate \"));\n Serial.println(_musicPlayer.sciRead(VS1053_REG_AUDATA));\n\n _musicPlayer.setVolume(_volume, _volume);\n\n setBassAndTreble(TREBLE_AMPLITUDE, TREBLE_FREQLIMIT, BASS_AMPLITUDE, BASS_FREQLIMIT);\n\n _musicPlayer.dumpRegs();\n\n Serial.println(F(\"VS1053 found\"));\n}\n\n\nbool ShelfPlayback::switchFolder(const char *folder) {\n Serial.print(F(\"Switching folder to \"));\n Serial.println(folder);\n\n if (!_SD.exists(folder)) {\n Serial.println(F(\"Folder does not exist\"));\n return false;\n }\n stopPlayback();\n _SD.chdir(folder);\n _SD.vwd()->rewind();\n _currentFile = \"\";\n return true;\n}\n\nvoid ShelfPlayback::resumePlayback() {\n if(_playing == PLAYBACK_PAUSED) {\n _musicPlayer.pausePlaying(false);\n _playing = PLAYBACK_FILE;\n }\n}\n\nvoid ShelfPlayback::pausePlayback() {\n if(_playing == PLAYBACK_FILE) {\n _musicPlayer.pausePlaying(true);\n _playing = PLAYBACK_PAUSED;\n if(isNight()) {\n _lastNightActivity = millis();\n }\n }\n}\n\nvoid ShelfPlayback::stopPlayback() {\n Serial.println(F(\"Stopping playback\"));\n if(_playing == PLAYBACK_NO) {\n Serial.println(F(\"Already stopped\"));\n return;\n }\n \n if (AMP_POWER > 0) {\n digitalWrite(AMP_POWER, LOW);\n }\n if(_playing == PLAYBACK_FILE) {\n _musicPlayer.stopPlaying();\n }\n _playing = PLAYBACK_NO;\n if(isNight()) {\n _lastNightActivity = millis();\n }\n}\n\nvoid ShelfPlayback::startPlayback() {\n \/\/ IO takes time, reset watchdog timer so it does not kill us\n ESP.wdtFeed();\n SdFile file;\n _SD.vwd()->rewind();\n\n char filenameChar[100];\n _SD.vwd()->getName(filenameChar, 100);\n String dirname = \"\/\" + String(filenameChar) + \"\/\";\n\n String nextFile = \"\";\n\n while (file.openNext(_SD.vwd(), O_READ))\n {\n\n file.getName(filenameChar, 100);\n file.close();\n\n if (file.isDir() || !_musicPlayer.isMP3File(filenameChar)) {\n Serial.print(F(\"Ignoring \")); Serial.println(filenameChar);\n continue;\n }\n\n String tmpFile = String(filenameChar);\n if (_currentFile < tmpFile && (tmpFile < nextFile || nextFile == \"\")) {\n nextFile = tmpFile;\n }\n }\n\n \/\/ Start folder from the beginning\n if (nextFile == \"\" && _currentFile != \"\") {\n _currentFile = \"\";\n startPlayback();\n return;\n }\n\n \/\/ No _currentFile && no nextFile => Nothing to play!\n if (nextFile == \"\") {\n Serial.print(F(\"No mp3 files in \")); Serial.println(dirname);\n stopPlayback();\n return;\n }\n\n startFilePlayback((char *)dirname.c_str(), (char *)nextFile.c_str());\n}\n\nvoid ShelfPlayback::startFilePlayback(const char* folder, const char* nextFile) {\n Serial.print(F(\"Playing \")); Serial.print(folder); Serial.println(nextFile);\n\n _playing = PLAYBACK_FILE;\n _currentFile = nextFile;\n \n char fullPath[116] = \"\";\n strcat(fullPath, folder);\n strcat(fullPath, nextFile);\n _musicPlayer.startPlayingFile(fullPath);\n\n if (AMP_POWER > 0) {\n digitalWrite(AMP_POWER, HIGH);\n }\n}\n\nvoid ShelfPlayback::skipFile() {\n _musicPlayer.stopPlaying();\n startPlayback();\n}\n\nvoid ShelfPlayback::volume(uint8_t volume) {\n if(volume > 50) {\n _volume = 50;\n } else {\n _volume = volume;\n }\n\n uint8_t calcVolume = volume;\n \n if(isNight()) {\n calcVolume = 50 - (NIGHT_FACTOR * (50 - _volume));\n }\n _musicPlayer.setVolume(calcVolume, calcVolume);\n}\n\nvoid ShelfPlayback::volumeUp() {\n if(_volume < 5) {\n volume(0);\n } else {\n volume(_volume - 5);\n }\n}\n\nvoid ShelfPlayback::volumeDown() {\n volume(_volume + 5);\n}\n\n\nvoid ShelfPlayback::setBassAndTreble(uint8_t trebleAmplitude, uint8_t trebleFreqLimit, uint8_t bassAmplitude, uint8_t bassFreqLimit) {\n uint16_t bassReg = 0;\n bassReg |= trebleAmplitude;\n bassReg <<= 4;\n bassReg |= trebleFreqLimit;\n bassReg <<= 4;\n bassReg |= bassAmplitude;\n bassReg <<= 4;\n bassReg |= bassFreqLimit;\n Serial.printf(F(\"bass value: %04x\\n\"), bassReg);\n _musicPlayer.sciWrite(VS1053_REG_BASS, bassReg);\n}\n\nbool ShelfPlayback::patchVS1053() {\n Serial.println(F(\"Installing patch to VS1053\"));\n\n SdFile file;\n if (!file.open(\"patches.053\", O_READ)) return false;\n\n uint16_t addr, n, val, i = 0;\n\n while (file.read(&addr, 2) && file.read(&n, 2)) {\n i += 2;\n if (n & 0x8000U) {\n n &= 0x7FFF;\n if (!file.read(&val, 2)) {\n file.close();\n return false;\n }\n while (n--) {\n _musicPlayer.sciWrite(addr, val);\n }\n } else {\n while (n--) {\n if (!file.read(&val, 2)) {\n file.close();\n return false;\n }\n i++;\n _musicPlayer.sciWrite(addr, val);\n }\n }\n }\n file.close();\n\n Serial.print(F(\"Number of bytes: \")); Serial.println(i);\n return true;\n}\n\nvoid ShelfPlayback::work() {\n if (_playing == PLAYBACK_FILE) {\n if (_musicPlayer.playingMusic) {\n _musicPlayer.feedBuffer();\n } else {\n startPlayback();\n }\n return;\n }\n\n if ((_playing == PLAYBACK_NO || _playing == PLAYBACK_PAUSED) && isNight() && (millis() - _lastNightActivity > NIGHT_TIMEOUT)) {\n stopNight();\n }\n}\n\nvoid ShelfPlayback::startNight() {\n _lastNightActivity = millis();\n _nightMode = true;\n volume(_volume);\n}\n\nbool ShelfPlayback::isNight() {\n return _nightMode;\n}\n\nvoid ShelfPlayback::stopNight() {\n _nightMode = false;\n volume(_volume);\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\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 \"ut_mpannableviewport.h\"\n#include <mtheme.h>\n#include <mpositionindicator.h>\n#include \"mpannableviewport.h\"\n#include \"mpannableviewport_p.h\"\n#include <QGraphicsWidget>\n#include <QGraphicsLinearLayout>\n#include <QTest>\n#include <mapplication.h>\n#include <mwidgetview.h>\n\nMApplication *app;\n\nvoid Ut_MPannableViewport::initTestCase()\n{\n static int argc = 1;\n static char *app_name[] = { (char *) \".\/ut_mpannableviewport\" };\n\n app = new MApplication(argc, app_name);\n}\n\n\nvoid Ut_MPannableViewport::cleanupTestCase()\n{\n \/\/ We do not delete the app on purpose. Due to some weird (toolchain?) problem\n \/\/ this can cause a crash when libraries are unregistered later.\n \/\/delete app;\n}\n\n\nvoid Ut_MPannableViewport::init()\n{\n subject = new MPannableViewport();\n}\n\nvoid Ut_MPannableViewport::cleanup()\n{\n delete subject;\n subject = 0;\n}\n\nvoid Ut_MPannableViewport::constructor()\n{\n QCOMPARE(subject->flags(), QGraphicsItem::ItemClipsChildrenToShape);\n}\n\nvoid Ut_MPannableViewport::setWidget()\n{\n QGraphicsWidget *widget = new QGraphicsWidget();\n subject->setWidget(widget);\n\n widget->setZValue(1);\n QCOMPARE(widget->zValue(), 1.0);\n\n QCOMPARE(static_cast<MPannableViewportPrivate *>(subject->d_ptr)->pannedWidget, widget);\n QCOMPARE(static_cast<MPannableViewportPrivate *>(subject->d_ptr)->pannedWidget->parentItem(), subject);\n\n}\n\nvoid Ut_MPannableViewport::setGeometry_data()\n{\n QTest::addColumn< QSizeF >(\"viewportSize\");\n QTest::addColumn< QSizeF >(\"pannedSize\");\n QTest::addColumn< QSizeF >(\"physicsRange\");\n\n QTest::newRow(\"set 1\") << QSizeF(100, 50) << QSizeF(400, 200) << QSizeF(300, 150);\n QTest::newRow(\"set 2\") << QSizeF(400, 50) << QSizeF(100, 200) << QSizeF(0, 150);\n QTest::newRow(\"set 3\") << QSizeF(100, 200) << QSizeF(400, 50) << QSizeF(300, 0);\n}\n\nvoid Ut_MPannableViewport::setGeometry()\n{\n QFETCH(QSizeF, viewportSize);\n QFETCH(QSizeF, pannedSize);\n QFETCH(QSizeF, physicsRange);\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setMinimumSize(pannedSize);\n widget->setMaximumSize(pannedSize);\n\n subject->setWidget(widget);\n subject->setGeometry(QRectF(QPointF(), viewportSize));\n\n QCOMPARE(subject->physics()->range().size(), physicsRange);\n}\n\nvoid Ut_MPannableViewport::event_data()\n{\n QTest::addColumn< QSizeF >(\"viewportSize\");\n QTest::addColumn< QSizeF >(\"pannedSize\");\n QTest::addColumn< QSizeF >(\"physicsRange\");\n\n QTest::newRow(\"set 1\") << QSizeF(100, 50) << QSizeF(400, 200) << QSizeF(300, 150);\n QTest::newRow(\"set 2\") << QSizeF(400, 50) << QSizeF(100, 200) << QSizeF(0, 150);\n QTest::newRow(\"set 3\") << QSizeF(100, 200) << QSizeF(400, 50) << QSizeF(300, 0);\n}\n\nvoid Ut_MPannableViewport::event()\n{\n QEvent *event = new QEvent(QEvent::LayoutRequest);\n\n QFETCH(QSizeF, viewportSize);\n QFETCH(QSizeF, pannedSize);\n QFETCH(QSizeF, physicsRange);\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n \/\/ Forcing the size of panned widget\n widget->setMinimumSize(pannedSize);\n widget->setPreferredSize(pannedSize);\n widget->setMaximumSize(pannedSize);\n\n \/\/ Forcing the size of subject\n subject->setMinimumSize(viewportSize);\n subject->setPreferredSize(viewportSize);\n subject->setMaximumSize(viewportSize);\n\n subject->setWidget(widget);\n\n subject->event(event);\n\n QCOMPARE(subject->physics()->range().size(), physicsRange);\n}\n\nvoid Ut_MPannableViewport::updatePosition()\n{\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setMinimumSize(QSizeF(10,10));\n widget->setMaximumSize(QSizeF(10,10));\n subject->setWidget(widget);\n\n \/\/ Forcing the size of subject to some value\n subject->setMinimumSize(QSizeF(500, 300));\n subject->setMaximumSize(QSizeF(500, 300));\n subject->adjustSize();\n\n QSignalSpy spy(subject, SIGNAL(positionChanged(QPointF)));\n\n subject->physics()->setPosition(QPointF(0,75));\n\n QCOMPARE(static_cast<MPannableViewportPrivate *>(subject->d_ptr)->pannedWidget->pos(), -QPointF(0, 75));\n\n QCOMPARE(spy.count(), 1);\n\n}\n\nvoid Ut_MPannableViewport::updateSamePosition()\n{\n QGraphicsWidget *mainWidget = new QGraphicsWidget();\n QPointF point(0.0, 0.0);\n\n subject->setMinimumSize(100, 480);\n subject->setPreferredSize(100, 480);\n subject->setMaximumSize(100, 480);\n\n mainWidget->setMinimumSize(100, 1000);\n mainWidget->setPreferredSize(100, 1000);\n mainWidget->setMaximumSize(100, 1000);\n\n subject->setWidget(mainWidget);\n\n subject->updatePosition(point);\n\n QSignalSpy spy(subject,\n SIGNAL(positionChanged(QPointF)));\n\n subject->updatePosition(point);\n\n \/\/ Should not have emitted anything since nothing changed\n QCOMPARE(spy.count(), 0);\n}\n\n\/*\n * While the pannedWidget is populated, sizePosChanged() signal should be\n * emitted only once for each actual change in pannedWidget's size.\n *\n * See NB#143428\n *\/\nvoid Ut_MPannableViewport::sizePosChangedAfterPopulatingPannedWidget()\n{\n QGraphicsWidget *mainWidget = new QGraphicsWidget();\n QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical);\n QGraphicsWidget *childWidget;\n\n \/\/Settle initial layout position\n subject->adjustSize();\n\n mainWidget->setLayout(layout);\n\n subject->setWidget(mainWidget);\n\n QSignalSpy spyRange(subject,\n SIGNAL(rangeChanged(QRectF)));\n QSignalSpy spyViewportSize(subject,\n SIGNAL(viewportSizeChanged(QSizeF)));\n QSignalSpy spyPosition(subject,\n SIGNAL(positionChanged(QPointF)));\n\n\n for (int i = 0; i < 30; i++) {\n childWidget = new QGraphicsWidget;\n\n childWidget->setMinimumSize(100, 200);\n childWidget->setPreferredSize(100, 200);\n\n layout->addItem(childWidget);\n }\n\n \/\/ Force layout to work.\n subject->adjustSize();\n\n \/\/ Check consecutive signals (if any), are different from each other.\n \/\/ We don't want to send out the very same event twice.\n for (int i = 1; i < spyRange.size(); i++) {\n QVERIFY(spyRange.at(i) != spyRange.at(i - 1));\n }\n for (int i = 1; i < spyPosition.size(); i++) {\n QVERIFY(spyPosition.at(i) != spyPosition.at(i - 1));\n }\n for (int i = 1; i < spyViewportSize.size(); i++) {\n QVERIFY(spyViewportSize.at(i) != spyViewportSize.at(i - 1));\n }\n}\n\nvoid Ut_MPannableViewport::settingNewPositionIndicator()\n{\n MPositionIndicator* newPositionIndicator = new MPositionIndicator();\n subject->setPositionIndicator(newPositionIndicator);\n\n QVERIFY(subject->positionIndicator() == newPositionIndicator);\n}\n\nvoid Ut_MPannableViewport::settingNULLPositionIndicatorShouldNotBeAccepted()\n{\n subject->setPositionIndicator(NULL);\n\n QVERIFY(subject->positionIndicator() != NULL);\n}\n\nvoid Ut_MPannableViewport::disabledViewportShouldNotAllowWigetToBeBiggerThanViewport()\n{\n subject->setVerticalPanningPolicy(MPannableWidget::PanningAlwaysOff);\n subject->setHorizontalPanningPolicy(MPannableWidget::PanningAlwaysOff);\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setPreferredSize(1000,1000);\n subject->setWidget(widget);\n\n\n \/\/ Forcing the size of subject to some value\n subject->setMinimumSize(QSizeF(500, 300));\n subject->setMaximumSize(QSizeF(500, 300));\n\n subject->adjustSize();\n\n QCOMPARE(widget->size(), QSizeF(500,300));\n subject->setVerticalPanningPolicy(MPannableWidget::PanningAlwaysOn);\n subject->setHorizontalPanningPolicy(MPannableWidget::PanningAlwaysOff);\n\n}\n\nvoid Ut_MPannableViewport::rangeOfViewportShouldBeSizeOfPannedWidgetMinusViewportSize()\n{\n \/\/ Forcing the size of subject to some value\n subject->setMinimumSize(QSizeF(500, 300));\n subject->setMaximumSize(QSizeF(500, 300));\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setMinimumSize(1000,1000);\n subject->setWidget(widget);\n\n subject->adjustSize();\n\n QCOMPARE(subject->range(), QRectF(0,0,500,700));\n}\n\nvoid Ut_MPannableViewport::testSetClipping()\n{\n subject->setClipping(true);\n QCOMPARE(subject->hasClipping(), true);\n subject->setClipping(false);\n QCOMPARE(subject->hasClipping(), false);\n}\n\nvoid Ut_MPannableViewport::testRangeSetting()\n{\n subject->setAutoRange(false);\n QCOMPARE(subject->autoRange(), false);\n\n subject->setRange(QRectF(0,0,100,100));\n QCOMPARE(subject->range(), QRectF(0,0,100,100));\n}\n\nvoid Ut_MPannableViewport::testExtendedRange_data()\n{\n QTest::addColumn<qreal>(\"autoScrollHeightExtension\");\n QTest::addColumn<qreal>(\"sipHeightExtension\");\n QTest::addColumn<qreal>(\"verticalRange\");\n QTest::addColumn<qreal>(\"expectedVerticalRange\");\n\n QTest::newRow(\"Zero range\") << 0.0 << 0.0 << 0.0 << 0.0;\n QTest::newRow(\"autoscroll extension\") << 1.0 << 0.0 << 0.0 << 1.0;\n QTest::newRow(\"sip extension\") << 0.0 << 1.0 << 0.0 << 1.0;\n QTest::newRow(\"autoscroll & sip #1\") << 1.0 << 1.0 << 0.0 << 1.0;\n QTest::newRow(\"autoscroll & sip #2\") << 5.0 << 1.0 << 0.0 << 5.0;\n QTest::newRow(\"autoscroll & sip #3\") << 1.0 << 5.0 << 0.0 << 5.0;\n QTest::newRow(\"autoscroll & sip #4\") << 1.0 << 5.0 << 2.0 << 7.0;\n}\n\nvoid Ut_MPannableViewport::testExtendedRange()\n{\n QFETCH(qreal, autoScrollHeightExtension);\n QFETCH(qreal, sipHeightExtension);\n QFETCH(qreal, verticalRange);\n QFETCH(qreal, expectedVerticalRange);\n\n QGraphicsScene scene;\n scene.addItem(subject);\n\n const QSizeF viewportSize(100, 100);\n subject->resize(viewportSize);\n subject->setMinimumSize(viewportSize);\n subject->setMaximumSize(viewportSize);\n subject->setAutoRange(false);\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setMinimumSize(1000,1000);\n subject->setWidget(widget);\n\n subject->adjustSize();\n\n subject->setRange(QRectF(QPointF(), QSizeF(0, verticalRange)));\n\n \/\/ Set autoscrolling extension\n subject->d_func()->setAutoScrollingExtension(autoScrollHeightExtension);\n\n \/\/ Set area occupied by input method area.\n const QRect imArea(subject->geometry().adjusted(0, (viewportSize.height() - sipHeightExtension),\n 0, 0).toRect());\n subject->d_func()->setInputMethodArea(imArea);\n\n const qreal actualVerticalRange = subject->range().height();\n\n \/\/ Remove from scene before possible return\/fail from QCOMPARE.\n scene.removeItem(subject);\n\n QCOMPARE(actualVerticalRange, expectedVerticalRange);\n}\n\nQTEST_APPLESS_MAIN(Ut_MPannableViewport)\n<commit_msg>Fixes: ut_mpannableviewport on arm<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\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 \"ut_mpannableviewport.h\"\n#include <mtheme.h>\n#include <mpositionindicator.h>\n#include \"mpannableviewport.h\"\n#include \"mpannableviewport_p.h\"\n#include <QGraphicsWidget>\n#include <QGraphicsLinearLayout>\n#include <QTest>\n#include <mapplication.h>\n#include <mwidgetview.h>\n\nMApplication *app;\n\nvoid Ut_MPannableViewport::initTestCase()\n{\n static int argc = 1;\n static char *app_name[] = { (char *) \".\/ut_mpannableviewport\" };\n\n app = new MApplication(argc, app_name);\n}\n\n\nvoid Ut_MPannableViewport::cleanupTestCase()\n{\n \/\/ We do not delete the app on purpose. Due to some weird (toolchain?) problem\n \/\/ this can cause a crash when libraries are unregistered later.\n \/\/delete app;\n}\n\n\nvoid Ut_MPannableViewport::init()\n{\n subject = new MPannableViewport();\n}\n\nvoid Ut_MPannableViewport::cleanup()\n{\n delete subject;\n subject = 0;\n}\n\nvoid Ut_MPannableViewport::constructor()\n{\n QCOMPARE(subject->flags(), QGraphicsItem::ItemClipsChildrenToShape);\n}\n\nvoid Ut_MPannableViewport::setWidget()\n{\n QGraphicsWidget *widget = new QGraphicsWidget();\n subject->setWidget(widget);\n\n widget->setZValue(1);\n QCOMPARE(widget->zValue(), 1.0);\n\n QCOMPARE(static_cast<MPannableViewportPrivate *>(subject->d_ptr)->pannedWidget, widget);\n QCOMPARE(static_cast<MPannableViewportPrivate *>(subject->d_ptr)->pannedWidget->parentItem(), subject);\n\n}\n\nvoid Ut_MPannableViewport::setGeometry_data()\n{\n QTest::addColumn< QSizeF >(\"viewportSize\");\n QTest::addColumn< QSizeF >(\"pannedSize\");\n QTest::addColumn< QSizeF >(\"physicsRange\");\n\n QTest::newRow(\"set 1\") << QSizeF(100, 50) << QSizeF(400, 200) << QSizeF(300, 150);\n QTest::newRow(\"set 2\") << QSizeF(400, 50) << QSizeF(100, 200) << QSizeF(0, 150);\n QTest::newRow(\"set 3\") << QSizeF(100, 200) << QSizeF(400, 50) << QSizeF(300, 0);\n}\n\nvoid Ut_MPannableViewport::setGeometry()\n{\n QFETCH(QSizeF, viewportSize);\n QFETCH(QSizeF, pannedSize);\n QFETCH(QSizeF, physicsRange);\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setMinimumSize(pannedSize);\n widget->setMaximumSize(pannedSize);\n\n subject->setWidget(widget);\n subject->setGeometry(QRectF(QPointF(), viewportSize));\n\n QCOMPARE(subject->physics()->range().size(), physicsRange);\n}\n\nvoid Ut_MPannableViewport::event_data()\n{\n QTest::addColumn< QSizeF >(\"viewportSize\");\n QTest::addColumn< QSizeF >(\"pannedSize\");\n QTest::addColumn< QSizeF >(\"physicsRange\");\n\n QTest::newRow(\"set 1\") << QSizeF(100, 50) << QSizeF(400, 200) << QSizeF(300, 150);\n QTest::newRow(\"set 2\") << QSizeF(400, 50) << QSizeF(100, 200) << QSizeF(0, 150);\n QTest::newRow(\"set 3\") << QSizeF(100, 200) << QSizeF(400, 50) << QSizeF(300, 0);\n}\n\nvoid Ut_MPannableViewport::event()\n{\n QEvent *event = new QEvent(QEvent::LayoutRequest);\n\n QFETCH(QSizeF, viewportSize);\n QFETCH(QSizeF, pannedSize);\n QFETCH(QSizeF, physicsRange);\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n \/\/ Forcing the size of panned widget\n widget->setMinimumSize(pannedSize);\n widget->setPreferredSize(pannedSize);\n widget->setMaximumSize(pannedSize);\n\n \/\/ Forcing the size of subject\n subject->setMinimumSize(viewportSize);\n subject->setPreferredSize(viewportSize);\n subject->setMaximumSize(viewportSize);\n\n subject->setWidget(widget);\n\n subject->event(event);\n\n QCOMPARE(subject->physics()->range().size(), physicsRange);\n}\n\nvoid Ut_MPannableViewport::updatePosition()\n{\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setMinimumSize(QSizeF(10,10));\n widget->setMaximumSize(QSizeF(10,10));\n subject->setWidget(widget);\n\n \/\/ Forcing the size of subject to some value\n subject->setMinimumSize(QSizeF(500, 300));\n subject->setMaximumSize(QSizeF(500, 300));\n subject->adjustSize();\n\n QSignalSpy spy(subject, SIGNAL(positionChanged(QPointF)));\n\n subject->physics()->setPosition(QPointF(0,75));\n\n QCOMPARE(static_cast<MPannableViewportPrivate *>(subject->d_ptr)->pannedWidget->pos(), -QPointF(0, 75));\n\n QCOMPARE(spy.count(), 1);\n\n}\n\nvoid Ut_MPannableViewport::updateSamePosition()\n{\n QGraphicsWidget *mainWidget = new QGraphicsWidget();\n QPointF point(0.0, 0.0);\n\n subject->setMinimumSize(100, 480);\n subject->setPreferredSize(100, 480);\n subject->setMaximumSize(100, 480);\n\n mainWidget->setMinimumSize(100, 1000);\n mainWidget->setPreferredSize(100, 1000);\n mainWidget->setMaximumSize(100, 1000);\n\n subject->setWidget(mainWidget);\n\n subject->updatePosition(point);\n\n QSignalSpy spy(subject,\n SIGNAL(positionChanged(QPointF)));\n\n subject->updatePosition(point);\n\n \/\/ Should not have emitted anything since nothing changed\n QCOMPARE(spy.count(), 0);\n}\n\n\/*\n * While the pannedWidget is populated, sizePosChanged() signal should be\n * emitted only once for each actual change in pannedWidget's size.\n *\n * See NB#143428\n *\/\nvoid Ut_MPannableViewport::sizePosChangedAfterPopulatingPannedWidget()\n{\n QGraphicsWidget *mainWidget = new QGraphicsWidget();\n QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical);\n QGraphicsWidget *childWidget;\n\n \/\/Settle initial layout position\n subject->adjustSize();\n\n mainWidget->setLayout(layout);\n\n subject->setWidget(mainWidget);\n\n QSignalSpy spyRange(subject,\n SIGNAL(rangeChanged(QRectF)));\n QSignalSpy spyViewportSize(subject,\n SIGNAL(viewportSizeChanged(QSizeF)));\n QSignalSpy spyPosition(subject,\n SIGNAL(positionChanged(QPointF)));\n\n\n for (int i = 0; i < 30; i++) {\n childWidget = new QGraphicsWidget;\n\n childWidget->setMinimumSize(100, 200);\n childWidget->setPreferredSize(100, 200);\n\n layout->addItem(childWidget);\n }\n\n \/\/ Force layout to work.\n subject->adjustSize();\n\n \/\/ Check consecutive signals (if any), are different from each other.\n \/\/ We don't want to send out the very same event twice.\n for (int i = 1; i < spyRange.size(); i++) {\n QVERIFY(spyRange.at(i) != spyRange.at(i - 1));\n }\n for (int i = 1; i < spyPosition.size(); i++) {\n QVERIFY(spyPosition.at(i) != spyPosition.at(i - 1));\n }\n for (int i = 1; i < spyViewportSize.size(); i++) {\n QVERIFY(spyViewportSize.at(i) != spyViewportSize.at(i - 1));\n }\n}\n\nvoid Ut_MPannableViewport::settingNewPositionIndicator()\n{\n MPositionIndicator* newPositionIndicator = new MPositionIndicator();\n subject->setPositionIndicator(newPositionIndicator);\n\n QVERIFY(subject->positionIndicator() == newPositionIndicator);\n}\n\nvoid Ut_MPannableViewport::settingNULLPositionIndicatorShouldNotBeAccepted()\n{\n subject->setPositionIndicator(NULL);\n\n QVERIFY(subject->positionIndicator() != NULL);\n}\n\nvoid Ut_MPannableViewport::disabledViewportShouldNotAllowWigetToBeBiggerThanViewport()\n{\n subject->setVerticalPanningPolicy(MPannableWidget::PanningAlwaysOff);\n subject->setHorizontalPanningPolicy(MPannableWidget::PanningAlwaysOff);\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setPreferredSize(1000,1000);\n subject->setWidget(widget);\n\n\n \/\/ Forcing the size of subject to some value\n subject->setMinimumSize(QSizeF(500, 300));\n subject->setMaximumSize(QSizeF(500, 300));\n\n subject->adjustSize();\n\n QCOMPARE(widget->size(), QSizeF(500,300));\n subject->setVerticalPanningPolicy(MPannableWidget::PanningAlwaysOn);\n subject->setHorizontalPanningPolicy(MPannableWidget::PanningAlwaysOff);\n\n}\n\nvoid Ut_MPannableViewport::rangeOfViewportShouldBeSizeOfPannedWidgetMinusViewportSize()\n{\n \/\/ Forcing the size of subject to some value\n subject->setMinimumSize(QSizeF(500, 300));\n subject->setMaximumSize(QSizeF(500, 300));\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setMinimumSize(1000,1000);\n subject->setWidget(widget);\n\n subject->adjustSize();\n\n QCOMPARE(subject->range(), QRectF(0,0,500,700));\n}\n\nvoid Ut_MPannableViewport::testSetClipping()\n{\n subject->setClipping(true);\n QCOMPARE(subject->hasClipping(), true);\n subject->setClipping(false);\n QCOMPARE(subject->hasClipping(), false);\n}\n\nvoid Ut_MPannableViewport::testRangeSetting()\n{\n subject->setAutoRange(false);\n QCOMPARE(subject->autoRange(), false);\n\n subject->setRange(QRectF(0,0,100,100));\n QCOMPARE(subject->range(), QRectF(0,0,100,100));\n}\n\nvoid Ut_MPannableViewport::testExtendedRange_data()\n{\n QTest::addColumn<qreal>(\"autoScrollHeightExtension\");\n QTest::addColumn<qreal>(\"sipHeightExtension\");\n QTest::addColumn<qreal>(\"verticalRange\");\n QTest::addColumn<qreal>(\"expectedVerticalRange\");\n\n QTest::newRow(\"Zero range\") << (qreal)0.0 << (qreal)0.0 << (qreal)0.0 << (qreal)0.0;\n QTest::newRow(\"autoscroll extension\") << (qreal)1.0 << (qreal)0.0 << (qreal)0.0 << (qreal)1.0;\n QTest::newRow(\"sip extension\") << (qreal)0.0 << (qreal)1.0 << (qreal)0.0 << (qreal)1.0;\n QTest::newRow(\"autoscroll & sip #1\") << (qreal)1.0 << (qreal)1.0 << (qreal)0.0 << (qreal)1.0;\n QTest::newRow(\"autoscroll & sip #2\") << (qreal)5.0 << (qreal)1.0 << (qreal)0.0 << (qreal)5.0;\n QTest::newRow(\"autoscroll & sip #3\") << (qreal)1.0 << (qreal)5.0 << (qreal)0.0 << (qreal)5.0;\n QTest::newRow(\"autoscroll & sip #4\") << (qreal)1.0 << (qreal)5.0 << (qreal)2.0 << (qreal)7.0;\n}\n\nvoid Ut_MPannableViewport::testExtendedRange()\n{\n QFETCH(qreal, autoScrollHeightExtension);\n QFETCH(qreal, sipHeightExtension);\n QFETCH(qreal, verticalRange);\n QFETCH(qreal, expectedVerticalRange);\n\n QGraphicsScene scene;\n scene.addItem(subject);\n\n const QSizeF viewportSize(100, 100);\n subject->resize(viewportSize);\n subject->setMinimumSize(viewportSize);\n subject->setMaximumSize(viewportSize);\n subject->setAutoRange(false);\n\n QGraphicsWidget *widget = new QGraphicsWidget();\n widget->setMinimumSize(1000,1000);\n subject->setWidget(widget);\n\n subject->adjustSize();\n\n subject->setRange(QRectF(QPointF(), QSizeF(0, verticalRange)));\n\n \/\/ Set autoscrolling extension\n subject->d_func()->setAutoScrollingExtension(autoScrollHeightExtension);\n\n \/\/ Set area occupied by input method area.\n const QRect imArea(subject->geometry().adjusted(0, (viewportSize.height() - sipHeightExtension),\n 0, 0).toRect());\n subject->d_func()->setInputMethodArea(imArea);\n\n const qreal actualVerticalRange = subject->range().height();\n\n \/\/ Remove from scene before possible return\/fail from QCOMPARE.\n scene.removeItem(subject);\n\n QCOMPARE(actualVerticalRange, expectedVerticalRange);\n}\n\nQTEST_APPLESS_MAIN(Ut_MPannableViewport)\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n\n#include <readline\/readline.h>\n#include <readline\/history.h>\n\n#include \"shared.hh\"\n#include \"eval.hh\"\n#include \"eval-inline.hh\"\n#include \"store-api.hh\"\n\nusing namespace std;\nusing namespace nix;\n\n\nstring programId = \"nix-repl\";\n\n\nstruct NixRepl\n{\n string curDir;\n EvalState state;\n\n StaticEnv staticEnv;\n Env * env;\n int displ;\n\n NixRepl();\n void mainLoop();\n void processLine(string line);\n void addVar(const Symbol & name, Value * v);\n Expr * parseString(string s);\n void evalString(string s, Value & v);\n};\n\n\nvoid printHelp()\n{\n std::cout << \"Usage: nix-repl\\n\";\n}\n\n\nbool getLine(string & line)\n{\n char * s = readline(\"nix-repl> \");\n if (!s) return false;\n line = chomp(string(s));\n free(s);\n if (line != \"\") add_history(line.c_str());\n return true;\n}\n\n\nNixRepl::NixRepl()\n : staticEnv(false, &state.staticBaseEnv)\n{\n curDir = absPath(\".\");\n\n env = &state.allocEnv(32768);\n env->up = &state.baseEnv;\n displ = 0;\n\n store = openStore();\n}\n\n\nvoid NixRepl::mainLoop()\n{\n std::cerr << \"Welcome to Nix version \" << NIX_VERSION << \". Type :? for help.\" << std::endl << std::endl;\n\n while (true) {\n string line;\n if (!getLine(line)) break;\n\n \/* Remove preceeding whitespace. *\/\n size_t n = line.find_first_not_of(\" \\n\\r\\t\");\n if (n != string::npos) line = string(line, n);\n\n try {\n processLine(line);\n } catch (Error & e) {\n printMsg(lvlError, e.msg());\n }\n\n std::cout << std::endl;\n }\n\n std::cout << std::endl;\n}\n\n\nvoid NixRepl::processLine(string line)\n{\n if (string(line, 0, 2) == \":a\") {\n Value v;\n evalString(string(line, 2), v);\n state.forceAttrs(v);\n foreach (Bindings::iterator, i, *v.attrs)\n addVar(i->name, i->value);\n }\n\n else if (string(line, 0, 2) == \":t\") {\n Value v;\n evalString(string(line, 2), v);\n std::cout << showType(v) << std::endl;\n }\n\n else if (string(line, 0, 1) == \":\") {\n throw Error(format(\"unknown command ‘%1%’\") % string(line, 0, 2));\n }\n\n else {\n Value v;\n evalString(line, v);\n state.strictForceValue(v);\n std::cout << v << std::endl;\n }\n}\n\n\nvoid NixRepl::addVar(const Symbol & name, Value * v)\n{\n staticEnv.vars[name] = displ;\n env->values[displ++] = v;\n}\n\n\nExpr * NixRepl::parseString(string s)\n{\n Expr * e = state.parseExprFromString(s, curDir, staticEnv);\n return e;\n}\n\n\nvoid NixRepl::evalString(string s, Value & v)\n{\n Expr * e = parseString(s);\n e->eval(state, *env, v);\n state.forceValue(v);\n}\n\n\nvoid run(nix::Strings args)\n{\n NixRepl repl;\n repl.mainLoop();\n}\n<commit_msg>Add a command :l for loading a file into scope<commit_after>#include <iostream>\n#include <cstdlib>\n\n#include <readline\/readline.h>\n#include <readline\/history.h>\n\n#include \"shared.hh\"\n#include \"eval.hh\"\n#include \"eval-inline.hh\"\n#include \"store-api.hh\"\n#include \"common-opts.hh\"\n\nusing namespace std;\nusing namespace nix;\n\n\nstring programId = \"nix-repl\";\n\n\nstruct NixRepl\n{\n string curDir;\n EvalState state;\n\n StaticEnv staticEnv;\n Env * env;\n int displ;\n\n NixRepl();\n void mainLoop();\n void processLine(string line);\n void addAttrsToScope(Value & attrs);\n void addVarToScope(const Symbol & name, Value * v);\n Expr * parseString(string s);\n void evalString(string s, Value & v);\n};\n\n\nvoid printHelp()\n{\n std::cout << \"Usage: nix-repl\\n\";\n}\n\n\nbool getLine(string & line)\n{\n char * s = readline(\"nix-repl> \");\n if (!s) return false;\n line = chomp(string(s));\n free(s);\n if (line != \"\") add_history(line.c_str());\n return true;\n}\n\n\nstring removeWhitespace(string s)\n{\n s = chomp(s);\n size_t n = s.find_first_not_of(\" \\n\\r\\t\");\n if (n != string::npos) s = string(s, n);\n return s;\n}\n\n\nNixRepl::NixRepl()\n : staticEnv(false, &state.staticBaseEnv)\n{\n curDir = absPath(\".\");\n\n env = &state.allocEnv(32768);\n env->up = &state.baseEnv;\n displ = 0;\n\n store = openStore();\n}\n\n\nvoid NixRepl::mainLoop()\n{\n std::cerr << \"Welcome to Nix version \" << NIX_VERSION << \". Type :? for help.\" << std::endl << std::endl;\n\n while (true) {\n string line;\n if (!getLine(line)) break;\n\n try {\n processLine(removeWhitespace(line));\n } catch (Error & e) {\n printMsg(lvlError, e.msg());\n }\n\n std::cout << std::endl;\n }\n\n std::cout << std::endl;\n}\n\n\nvoid NixRepl::processLine(string line)\n{\n if (string(line, 0, 2) == \":a\") {\n Value v;\n evalString(string(line, 2), v);\n addAttrsToScope(v);\n }\n\n else if (string(line, 0, 2) == \":l\") {\n state.resetFileCache();\n Path path = lookupFileArg(state, removeWhitespace(string(line, 2)));\n Value v, v2;\n state.evalFile(path, v);\n Bindings bindings;\n state.autoCallFunction(bindings, v, v2);\n addAttrsToScope(v2);\n }\n\n else if (string(line, 0, 2) == \":t\") {\n Value v;\n evalString(string(line, 2), v);\n std::cout << showType(v) << std::endl;\n }\n\n else if (string(line, 0, 1) == \":\") {\n throw Error(format(\"unknown command ‘%1%’\") % string(line, 0, 2));\n }\n\n else {\n Value v;\n evalString(line, v);\n state.strictForceValue(v);\n std::cout << v << std::endl;\n }\n}\n\n\nvoid NixRepl::addAttrsToScope(Value & attrs)\n{\n state.forceAttrs(attrs);\n foreach (Bindings::iterator, i, *attrs.attrs)\n addVarToScope(i->name, i->value);\n}\n\n\nvoid NixRepl::addVarToScope(const Symbol & name, Value * v)\n{\n staticEnv.vars[name] = displ;\n env->values[displ++] = v;\n}\n\n\nExpr * NixRepl::parseString(string s)\n{\n Expr * e = state.parseExprFromString(s, curDir, staticEnv);\n return e;\n}\n\n\nvoid NixRepl::evalString(string s, Value & v)\n{\n Expr * e = parseString(s);\n e->eval(state, *env, v);\n state.forceValue(v);\n}\n\n\nvoid run(nix::Strings args)\n{\n NixRepl repl;\n repl.mainLoop();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The MIT License (MIT)\n * \n * Copyright (c) 2018 Scott Moreau\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 all\n * 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 THE\n * SOFTWARE.\n *\/\n\n#include <plugin.hpp>\n#include <output.hpp>\n#include <opengl.hpp>\n#include <debug.hpp>\n#include <animation.hpp>\n#include <render-manager.hpp>\n\nstatic const char* vertex_shader =\nR\"(\n#version 100\n\nattribute mediump vec2 position;\n\nvoid main() {\n\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n)\";\n\nstatic const char* fragment_shader =\nR\"(\n#version 100\nprecision mediump float;\n\nuniform vec2 u_resolution;\nuniform vec2 u_mouse;\nuniform float u_radius;\nuniform float u_zoom;\nuniform sampler2D u_texture;\n\nconst float PI = 3.1415926535;\n\nvoid main()\n{\n float radius = u_radius;\n\n float zoom = u_zoom;\n float pw = 1.0 \/ u_resolution.x;\n float ph = 1.0 \/ u_resolution.y;\n\n vec4 p0 = vec4(u_mouse.x, u_resolution.y - u_mouse.y, 1.0 \/ radius, 0.0);\n vec4 p1 = vec4(pw, ph, PI \/ radius, (zoom - 1.0) * zoom);\n vec4 p2 = vec4(0, 0, -PI \/ 2.0, 0.0);\n\n vec4 t0, t1, t2, t3;\n\n vec3 tc = vec3(1.0, 0.0, 0.0);\n vec2 uv = vec2(gl_FragCoord.x, gl_FragCoord.y);\n\n t1 = p0.xyww - vec4(uv, 0.0, 0.0);\n t2.x = t2.y = t2.z = t2.w = 1.0 \/ sqrt(dot(t1.xyz, t1.xyz));\n t0 = t2 - p0;\n\n t3.x = t3.y = t3.z = t3.w = 1.0 \/ t2.x;\n t3 = t3 * p1.z + p2.z;\n t3.x = t3.y = t3.z = t3.w = cos(t3.x);\n\n t3 = t3 * p1.w;\n\n t1 = t2 * t1;\n t1 = t1 * t3 + vec4(uv, 0.0, 0.0);\n\n if (t0.z < 0.0) {\n t1.x = uv.x;\n t1.y = uv.y;\n }\n\n t1 = t1 * p1 + p2;\n\n tc = texture2D(u_texture, t1.xy).rgb;\n\n gl_FragColor = vec4(tc, 1.0);\n}\n)\";\n\nclass wayfire_fisheye : public wayfire_plugin_t\n{\n\n post_hook_t hook;\n key_callback toggle_cb;\n wf_duration duration;\n float target_zoom;\n bool active, hook_set;\n wf_option radius, zoom;\n\n GLuint program, posID, mouseID, resID, radiusID, zoomID;\n\n public:\n void init(wayfire_config *config)\n {\n auto section = config->get_section(\"fisheye\");\n auto toggle_key = section->get_option(\"toggle\", \"<super> KEY_F\");\n radius = section->get_option(\"radius\", \"300\");\n zoom = section->get_option(\"zoom\", \"7\");\n\n if (!toggle_key->as_key().valid())\n return;\n\n target_zoom = zoom->as_double();\n\n hook = [=] (uint32_t fb, uint32_t tex, uint32_t target)\n {\n render(fb, tex, target);\n };\n\n toggle_cb = [=] (uint32_t key)\n {\n if (active)\n {\n active = false;\n duration.start(duration.progress(), 0);\n } else\n {\n active = true;\n duration.start(duration.progress(), target_zoom);\n\n if (!hook_set)\n {\n hook_set = true;\n output->render->add_post(&hook);\n }\n }\n };\n\n auto vs = OpenGL::compile_shader(vertex_shader, GL_VERTEX_SHADER);\n auto fs = OpenGL::compile_shader(fragment_shader, GL_FRAGMENT_SHADER);\n\n program = GL_CALL(glCreateProgram());\n GL_CALL(glAttachShader(program, vs));\n GL_CALL(glAttachShader(program, fs));\n GL_CALL(glLinkProgram(program));\n\n posID = GL_CALL(glGetAttribLocation(program, \"position\"));\n mouseID = GL_CALL(glGetUniformLocation(program, \"u_mouse\"));\n resID = GL_CALL(glGetUniformLocation(program, \"u_resolution\"));\n radiusID = GL_CALL(glGetUniformLocation(program, \"u_radius\"));\n zoomID = GL_CALL(glGetUniformLocation(program, \"u_zoom\"));\n\n duration = wf_duration(new_static_option(\"700\"));\n duration.start(0, 0); \/\/ so that the first value we get is correct\n\n output->add_key(toggle_key, &toggle_cb);\n }\n\n void render(uint32_t fb, uint32_t tex, uint32_t target)\n {\n GetTuple(x, y, output->get_cursor_position());\n GL_CALL(glUseProgram(program));\n GL_CALL(glBindTexture(GL_TEXTURE_2D, tex));\n GL_CALL(glActiveTexture(GL_TEXTURE0));\n\n static const float vertexData[] = {\n -1.0f, -1.0f,\n 1.0f, -1.0f,\n 1.0f, 1.0f,\n -1.0f, 1.0f\n };\n\n auto current_zoom = duration.progress();\n target_zoom = zoom->as_double();\n\n glUniform2f(mouseID, x, y);\n glUniform2f(resID, output->handle->width, output->handle->height);\n glUniform1f(radiusID, radius->as_double());\n glUniform1f(zoomID, current_zoom);\n\n GL_CALL(glVertexAttribPointer(posID, 2, GL_FLOAT, GL_FALSE, 0, vertexData));\n GL_CALL(glEnableVertexAttribArray(posID));\n\n GL_CALL(glDisable(GL_BLEND));\n GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target));\n GL_CALL(glDrawArrays (GL_TRIANGLE_FAN, 0, 4));\n GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0));\n\n GL_CALL(glDisableVertexAttribArray(posID));\n GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));\n\n if (active)\n {\n \/* Reset animation in case target_zoom\n * was changed via config *\/\n duration.start(current_zoom, target_zoom);\n } else if (!duration.running())\n {\n output->render->rem_post(&hook);\n hook_set = false;\n }\n }\n};\n\nextern \"C\"\n{\n wayfire_plugin_t *newInstance()\n {\n return new wayfire_fisheye();\n }\n}\n<commit_msg>Transform mouse coordinates<commit_after>\/*\n * The MIT License (MIT)\n * \n * Copyright (c) 2018 Scott Moreau\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 all\n * 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 THE\n * SOFTWARE.\n *\/\n\n#include <plugin.hpp>\n#include <output.hpp>\n#include <opengl.hpp>\n#include <debug.hpp>\n#include <animation.hpp>\n#include <render-manager.hpp>\n\nstatic const char* vertex_shader =\nR\"(\n#version 100\n\nattribute mediump vec2 position;\n\nvoid main() {\n\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n)\";\n\nstatic const char* fragment_shader =\nR\"(\n#version 100\nprecision mediump float;\n\nuniform vec2 u_resolution;\nuniform vec2 u_mouse;\nuniform float u_radius;\nuniform float u_zoom;\nuniform sampler2D u_texture;\n\nconst float PI = 3.1415926535;\n\nvoid main()\n{\n float radius = u_radius;\n\n float zoom = u_zoom;\n float pw = 1.0 \/ u_resolution.x;\n float ph = 1.0 \/ u_resolution.y;\n\n vec4 p0 = vec4(u_mouse.x, u_resolution.y - u_mouse.y, 1.0 \/ radius, 0.0);\n vec4 p1 = vec4(pw, ph, PI \/ radius, (zoom - 1.0) * zoom);\n vec4 p2 = vec4(0, 0, -PI \/ 2.0, 0.0);\n\n vec4 t0, t1, t2, t3;\n\n vec3 tc = vec3(1.0, 0.0, 0.0);\n vec2 uv = vec2(gl_FragCoord.x, gl_FragCoord.y);\n\n t1 = p0.xyww - vec4(uv, 0.0, 0.0);\n t2.x = t2.y = t2.z = t2.w = 1.0 \/ sqrt(dot(t1.xyz, t1.xyz));\n t0 = t2 - p0;\n\n t3.x = t3.y = t3.z = t3.w = 1.0 \/ t2.x;\n t3 = t3 * p1.z + p2.z;\n t3.x = t3.y = t3.z = t3.w = cos(t3.x);\n\n t3 = t3 * p1.w;\n\n t1 = t2 * t1;\n t1 = t1 * t3 + vec4(uv, 0.0, 0.0);\n\n if (t0.z < 0.0) {\n t1.x = uv.x;\n t1.y = uv.y;\n }\n\n t1 = t1 * p1 + p2;\n\n tc = texture2D(u_texture, t1.xy).rgb;\n\n gl_FragColor = vec4(tc, 1.0);\n}\n)\";\n\nclass wayfire_fisheye : public wayfire_plugin_t\n{\n\n post_hook_t hook;\n key_callback toggle_cb;\n wf_duration duration;\n float target_zoom;\n bool active, hook_set;\n wf_option radius, zoom;\n\n GLuint program, posID, mouseID, resID, radiusID, zoomID;\n\n public:\n void init(wayfire_config *config)\n {\n auto section = config->get_section(\"fisheye\");\n auto toggle_key = section->get_option(\"toggle\", \"<super> KEY_F\");\n radius = section->get_option(\"radius\", \"300\");\n zoom = section->get_option(\"zoom\", \"7\");\n\n if (!toggle_key->as_key().valid())\n return;\n\n target_zoom = zoom->as_double();\n\n hook = [=] (uint32_t fb, uint32_t tex, uint32_t target)\n {\n render(fb, tex, target);\n };\n\n toggle_cb = [=] (uint32_t key)\n {\n if (active)\n {\n active = false;\n duration.start(duration.progress(), 0);\n } else\n {\n active = true;\n duration.start(duration.progress(), target_zoom);\n\n if (!hook_set)\n {\n hook_set = true;\n output->render->add_post(&hook);\n }\n }\n };\n\n auto vs = OpenGL::compile_shader(vertex_shader, GL_VERTEX_SHADER);\n auto fs = OpenGL::compile_shader(fragment_shader, GL_FRAGMENT_SHADER);\n\n program = GL_CALL(glCreateProgram());\n GL_CALL(glAttachShader(program, vs));\n GL_CALL(glAttachShader(program, fs));\n GL_CALL(glLinkProgram(program));\n\n posID = GL_CALL(glGetAttribLocation(program, \"position\"));\n mouseID = GL_CALL(glGetUniformLocation(program, \"u_mouse\"));\n resID = GL_CALL(glGetUniformLocation(program, \"u_resolution\"));\n radiusID = GL_CALL(glGetUniformLocation(program, \"u_radius\"));\n zoomID = GL_CALL(glGetUniformLocation(program, \"u_zoom\"));\n\n duration = wf_duration(new_static_option(\"700\"));\n duration.start(0, 0); \/\/ so that the first value we get is correct\n\n output->add_key(toggle_key, &toggle_cb);\n }\n\n void render(uint32_t fb, uint32_t tex, uint32_t target)\n {\n GetTuple(x, y, output->get_cursor_position());\n wlr_box box = {x, y, 1, 1};\n box = output_transform_box(output, box);\n x = box.x;\n y = box.y;\n\n GL_CALL(glUseProgram(program));\n GL_CALL(glBindTexture(GL_TEXTURE_2D, tex));\n GL_CALL(glActiveTexture(GL_TEXTURE0));\n\n static const float vertexData[] = {\n -1.0f, -1.0f,\n 1.0f, -1.0f,\n 1.0f, 1.0f,\n -1.0f, 1.0f\n };\n\n auto current_zoom = duration.progress();\n target_zoom = zoom->as_double();\n\n glUniform2f(mouseID, x, y);\n glUniform2f(resID, output->handle->width, output->handle->height);\n glUniform1f(radiusID, radius->as_double());\n glUniform1f(zoomID, current_zoom);\n\n GL_CALL(glVertexAttribPointer(posID, 2, GL_FLOAT, GL_FALSE, 0, vertexData));\n GL_CALL(glEnableVertexAttribArray(posID));\n\n GL_CALL(glDisable(GL_BLEND));\n GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target));\n GL_CALL(glDrawArrays (GL_TRIANGLE_FAN, 0, 4));\n GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0));\n\n GL_CALL(glDisableVertexAttribArray(posID));\n GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));\n\n if (active)\n {\n \/* Reset animation in case target_zoom\n * was changed via config *\/\n duration.start(current_zoom, target_zoom);\n } else if (!duration.running())\n {\n output->render->rem_post(&hook);\n hook_set = false;\n }\n }\n};\n\nextern \"C\"\n{\n wayfire_plugin_t *newInstance()\n {\n return new wayfire_fisheye();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This code is subject to the terms of the Mozilla Public License, v.2.0. http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n#include \"UdtServer.h\"\n\n#include \"UdtSocket.h\"\n#include \"socket\/IpAddress.h\"\n#include <iostream>\n\n#include \"udt4\/src\/udt.h\"\n#include <arpa\/inet.h>\n\/\/#include <netinet\/in.h>\n#include <string.h>\n\/\/#include <unistd.h>\n\nnamespace\n{\n\tint _epollEventFlag = EPOLLOpt::UDT_EPOLL_IN ^ EPOLLOpt::UDT_EPOLL_ERR;\n}\n\n\/\/ TODO: investigate delays\/unreliabiliy when using concurrent UDT::epoll_wait(), e.g. numThreads > 1?\nUdtServer::UdtServer(short port, std::function<void(const IIpSocket&, const std::string&)> onPacket, unsigned numThreads\/*=1*\/, unsigned maxPacketSize)\n\t: _running(false)\n\t, _sock(-1)\n\t, _port(port)\n\t, _numThreads(numThreads)\n\t, _maxPacketSize(maxPacketSize)\n\t, _onPacket(onPacket)\n{\n}\n\nUdtServer::~UdtServer()\n{\n\tstop();\n}\n\nbool UdtServer::start()\n{\n\tif (_running)\n\t\treturn true;\n\n\t_running = true;\n\t_sock = UDT::socket(AF_INET, SOCK_DGRAM, 0);\n\tif (_sock == UDT::INVALID_SOCK)\n\t{\n\t\tfatalError(\"couldn't create socket!\");\n\t\treturn _running = false;\n\t}\n\n\tstruct sockaddr_in si_me;\n\tmemset((char*)&si_me, 0, sizeof(si_me));\n\n\tsi_me.sin_family = AF_INET;\n\tsi_me.sin_port = htons(_port);\n\tsi_me.sin_addr.s_addr = htonl(INADDR_ANY);\n\tif (UDT::bind(_sock, (struct sockaddr*)&si_me, sizeof(si_me)) == UDT::ERROR)\n\t{\n\t\tfatalError(\"couldn't bind to port: \" + std::string(UDT::getlasterror().getErrorMessage()));\n\t\treturn _running = false;\n\t}\n\tif (UDT::listen(_sock, 20) == UDT::ERROR)\n\t{\n\t\tfatalError(\"couldn't get udt socket to listen: \" + std::string(UDT::getlasterror().getErrorMessage()));\n\t\tUDT::close(_sock);\n\t\treturn _running = false;\n\t}\n\n\t_pollPackets = UDT::epoll_create();\n\tif (_pollPackets < 0)\n\t{\n\t\tfatalError(\"couldn't get udt epoll to work: \" + std::string(UDT::getlasterror().getErrorMessage()));\n\t\tUDT::close(_sock);\n\t\treturn _running = false;\n\t}\n\n\t_acceptor = std::thread( std::bind(&UdtServer::accept, this) );\n\tfor (unsigned i = 0; i < _numThreads; ++i)\n\t\t_runners.push_back( std::thread(std::bind(&UdtServer::run, this)) );\n\t_started.wait();\n\treturn _running;\n}\n\nvoid UdtServer::stop()\n{\n\t_running = false;\n\tUDT::epoll_release(_pollPackets);\n\tUDT::close(_sock);\n\tfor (tbb::concurrent_unordered_map<std::string,int>::iterator it = _connections.begin(); it != _connections.end(); ++it)\n\t\tUDT::close(it->second);\n\n\tfor (std::list<std::thread>::iterator it = _runners.begin(); it != _runners.end(); ++it)\n\t{\n\t\t if (it->joinable())\n\t\t\tit->join();\n\t}\n\t_runners.clear();\n\tif (_acceptor.joinable())\n\t\t_acceptor.join();\n}\n\n\/\/ TODO: probably eventually want two epoll groups.\n\/\/ one for new connections,\n\/\/ and one for known (good) peers.\n\/\/ that way we can safely do a LRU scheme for good peers...\nvoid UdtServer::accept()\n{\n\t_started.shutdown();\n\n\tstruct sockaddr_in their_addr;\n\tint addr_sz = sizeof(their_addr);\n\tmemset((char*)&their_addr, 0, addr_sz);\n\n\twhile (_running)\n\t{\n\t\tUDTSOCKET conn = UDT::accept(_sock, (sockaddr*)&their_addr, &addr_sz);\n\t\tif (conn == UDT::INVALID_SOCK)\n\t\t\tcontinue;\n\n\t\tif (UDT::epoll_add_usock(_pollPackets, conn, &_epollEventFlag) < 0)\n\t\t{\n\t\t\tstd::cout << \"UDT::epoll_add_usock error.\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid UdtServer::run()\n{\n\tstd::string buffer;\n\tstd::set<UDTSOCKET> irrelevant;\n\tstd::set<UDTSOCKET> reads;\n\twhile (_running)\n\t{\n\t\treads.clear();\n\t\tirrelevant.clear();\n\n\t\tint waiters;\n\t\tif ((waiters = UDT::epoll_wait(_pollPackets, &reads, &irrelevant, 5000)) < 0)\n\t\t{\n\t\t\tstd::cout << \"epoll_wait did an error! :( \" << waiters << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tstd::cout << \"epoll says there are \" << waiters << \" guys ready. Yes, \" << reads.size() << \" ... ? \" << irrelevant.size() << std::endl;\n\n\t\tfor (std::set<UDTSOCKET>::const_iterator it = reads.begin(); it != reads.end(); ++it)\n\t\t{\n\t\t\tUdtSocket sock(*it);\n\t\t\tstd::cout << \"udt read: \" << sock.getTarget().toString() << std::endl;\n\n\t\t\tbuffer.resize(_maxPacketSize);\n\t\t\tif (sock.recv(buffer) <= 0)\n\t\t\t{\n\t\t\t\tstd::cout << \"badness. :(\" << std::endl;\n\t\t\t\tUDT::epoll_remove_usock(_pollPackets, *it);\n\t\t\t\tUDT::close(*it);\n\t\t\t}\n\n\t\t\t_onPacket(sock, buffer);\n\t\t\t_connections[sock.getTarget().toString()] = *it;\n\t\t}\n\t}\n}\n\nbool UdtServer::isRunning() const\n{\n\treturn _running;\n}\n\nstd::string UdtServer::lastError() const\n{\n\treturn _lastError;\n}\n\nvoid UdtServer::fatalError(const std::string& error)\n{\n\t_lastError = error;\n}\n\nstd::shared_ptr<IIpSocket> UdtServer::sock(const IpAddress& addr)\n{\n\t\/\/ concurrent unordered map or something\n\tstd::shared_ptr<IIpSocket> res;\n\tstd::pair< tbb::concurrent_unordered_map<std::string, int>::iterator, bool> pear = _connections.insert( {addr.toString(), -1} );\n\tif (pear.first->second < 0)\n\t{\n\t\tUDTSOCKET handle = UDT::socket(AF_INET, SOCK_DGRAM, 0);\n\t\tif (handle == UDT::INVALID_SOCK)\n\t\t\treturn NULL;\n\n\t\tUdtSocket* sock = new UdtSocket(handle);\n\t\tres.reset(sock);\n\t\tif (!sock->connect(addr))\n\t\t\treturn NULL;\n\t\tpear.first->second = handle;\n\n\t\tif (UDT::epoll_add_usock(_pollPackets, handle, &_epollEventFlag) < 0)\n\t\t\tstd::cout << \"UDT::epoll_add_usock error for client sock.\" << std::endl;\n\t}\n\telse\n\t\tres.reset(new UdtSocket(pear.first->second));\n\treturn std::shared_ptr<IIpSocket>(res);\n}\n<commit_msg>Less noisyness from the udt server...<commit_after>\/* This code is subject to the terms of the Mozilla Public License, v.2.0. http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n#include \"UdtServer.h\"\n\n#include \"UdtSocket.h\"\n#include \"socket\/IpAddress.h\"\n#include <iostream>\n\n#include \"udt4\/src\/udt.h\"\n#include <arpa\/inet.h>\n\/\/#include <netinet\/in.h>\n#include <string.h>\n\/\/#include <unistd.h>\n\nnamespace\n{\n\tint _epollEventFlag = EPOLLOpt::UDT_EPOLL_IN ^ EPOLLOpt::UDT_EPOLL_ERR;\n}\n\n\/\/ TODO: investigate delays\/unreliabiliy when using concurrent UDT::epoll_wait(), e.g. numThreads > 1?\nUdtServer::UdtServer(short port, std::function<void(const IIpSocket&, const std::string&)> onPacket, unsigned numThreads\/*=1*\/, unsigned maxPacketSize)\n\t: _running(false)\n\t, _sock(-1)\n\t, _port(port)\n\t, _numThreads(numThreads)\n\t, _maxPacketSize(maxPacketSize)\n\t, _onPacket(onPacket)\n{\n}\n\nUdtServer::~UdtServer()\n{\n\tstop();\n}\n\nbool UdtServer::start()\n{\n\tif (_running)\n\t\treturn true;\n\n\t_running = true;\n\t_sock = UDT::socket(AF_INET, SOCK_DGRAM, 0);\n\tif (_sock == UDT::INVALID_SOCK)\n\t{\n\t\tfatalError(\"couldn't create socket!\");\n\t\treturn _running = false;\n\t}\n\n\tstruct sockaddr_in si_me;\n\tmemset((char*)&si_me, 0, sizeof(si_me));\n\n\tsi_me.sin_family = AF_INET;\n\tsi_me.sin_port = htons(_port);\n\tsi_me.sin_addr.s_addr = htonl(INADDR_ANY);\n\tif (UDT::bind(_sock, (struct sockaddr*)&si_me, sizeof(si_me)) == UDT::ERROR)\n\t{\n\t\tfatalError(\"couldn't bind to port: \" + std::string(UDT::getlasterror().getErrorMessage()));\n\t\treturn _running = false;\n\t}\n\tif (UDT::listen(_sock, 20) == UDT::ERROR)\n\t{\n\t\tfatalError(\"couldn't get udt socket to listen: \" + std::string(UDT::getlasterror().getErrorMessage()));\n\t\tUDT::close(_sock);\n\t\treturn _running = false;\n\t}\n\n\t_pollPackets = UDT::epoll_create();\n\tif (_pollPackets < 0)\n\t{\n\t\tfatalError(\"couldn't get udt epoll to work: \" + std::string(UDT::getlasterror().getErrorMessage()));\n\t\tUDT::close(_sock);\n\t\treturn _running = false;\n\t}\n\n\t_acceptor = std::thread( std::bind(&UdtServer::accept, this) );\n\tfor (unsigned i = 0; i < _numThreads; ++i)\n\t\t_runners.push_back( std::thread(std::bind(&UdtServer::run, this)) );\n\t_started.wait();\n\treturn _running;\n}\n\nvoid UdtServer::stop()\n{\n\t_running = false;\n\tUDT::epoll_release(_pollPackets);\n\tUDT::close(_sock);\n\tfor (tbb::concurrent_unordered_map<std::string,int>::iterator it = _connections.begin(); it != _connections.end(); ++it)\n\t\tUDT::close(it->second);\n\n\tfor (std::list<std::thread>::iterator it = _runners.begin(); it != _runners.end(); ++it)\n\t{\n\t\t if (it->joinable())\n\t\t\tit->join();\n\t}\n\t_runners.clear();\n\tif (_acceptor.joinable())\n\t\t_acceptor.join();\n}\n\n\/\/ TODO: probably eventually want two epoll groups.\n\/\/ one for new connections,\n\/\/ and one for known (good) peers.\n\/\/ that way we can safely do a LRU scheme for good peers...\nvoid UdtServer::accept()\n{\n\t_started.shutdown();\n\n\tstruct sockaddr_in their_addr;\n\tint addr_sz = sizeof(their_addr);\n\tmemset((char*)&their_addr, 0, addr_sz);\n\n\twhile (_running)\n\t{\n\t\tUDTSOCKET conn = UDT::accept(_sock, (sockaddr*)&their_addr, &addr_sz);\n\t\tif (conn == UDT::INVALID_SOCK)\n\t\t\tcontinue;\n\n\t\tif (UDT::epoll_add_usock(_pollPackets, conn, &_epollEventFlag) < 0)\n\t\t{\n\t\t\tstd::cout << \"UDT::epoll_add_usock error.\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid UdtServer::run()\n{\n\tstd::string buffer;\n\tstd::set<UDTSOCKET> irrelevant;\n\tstd::set<UDTSOCKET> reads;\n\twhile (_running)\n\t{\n\t\treads.clear();\n\t\tirrelevant.clear();\n\n\t\tint waiters;\n\t\tif ((waiters = UDT::epoll_wait(_pollPackets, &reads, &irrelevant, 5000)) < 0)\n\t\t{\n\t\t\tstd::cout << \"epoll_wait did an error! :( \" << waiters << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/std::cout << \"epoll says there are \" << waiters << \" guys ready. Yes, \" << reads.size() << \" ... ? \" << irrelevant.size() << std::endl;\n\n\t\tfor (std::set<UDTSOCKET>::const_iterator it = reads.begin(); it != reads.end(); ++it)\n\t\t{\n\t\t\tUdtSocket sock(*it);\n\t\t\t\/\/std::cout << \"udt read: \" << sock.getTarget().toString() << std::endl;\n\n\t\t\tbuffer.resize(_maxPacketSize);\n\t\t\tif (sock.recv(buffer) <= 0)\n\t\t\t{\n\t\t\t\tstd::cout << \"udt badness. :(\" << std::endl;\n\t\t\t\tUDT::epoll_remove_usock(_pollPackets, *it);\n\t\t\t\tUDT::close(*it);\n\t\t\t}\n\n\t\t\t_onPacket(sock, buffer);\n\t\t\t_connections[sock.getTarget().toString()] = *it;\n\t\t}\n\t}\n}\n\nbool UdtServer::isRunning() const\n{\n\treturn _running;\n}\n\nstd::string UdtServer::lastError() const\n{\n\treturn _lastError;\n}\n\nvoid UdtServer::fatalError(const std::string& error)\n{\n\t_lastError = error;\n}\n\nstd::shared_ptr<IIpSocket> UdtServer::sock(const IpAddress& addr)\n{\n\t\/\/ concurrent unordered map or something\n\tstd::shared_ptr<IIpSocket> res;\n\tstd::pair< tbb::concurrent_unordered_map<std::string, int>::iterator, bool> pear = _connections.insert( {addr.toString(), -1} );\n\tif (pear.first->second < 0)\n\t{\n\t\tUDTSOCKET handle = UDT::socket(AF_INET, SOCK_DGRAM, 0);\n\t\tif (handle == UDT::INVALID_SOCK)\n\t\t\treturn NULL;\n\n\t\tUdtSocket* sock = new UdtSocket(handle);\n\t\tres.reset(sock);\n\t\tif (!sock->connect(addr))\n\t\t\treturn NULL;\n\t\tpear.first->second = handle;\n\n\t\tif (UDT::epoll_add_usock(_pollPackets, handle, &_epollEventFlag) < 0)\n\t\t\tstd::cout << \"UDT::epoll_add_usock error for client sock.\" << std::endl;\n\t}\n\telse\n\t\tres.reset(new UdtSocket(pear.first->second));\n\treturn std::shared_ptr<IIpSocket>(res);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ofp\/rpc\/rpcevents.h\"\n#include \"ofp\/unittest.h\"\n\nTEST(rpcevents, test_TrimErrorMessage) {\n std::string msg1 = \"x\\n ^\";\n ofp::rpc::TrimErrorMessage(msg1);\n EXPECT_EQ(msg1, \"x\");\n\n std::string msg2 = \"\";\n ofp::rpc::TrimErrorMessage(msg2);\n EXPECT_EQ(msg2, \"\");\n\n std::string msg3 = \"abc\";\n ofp::rpc::TrimErrorMessage(msg3);\n EXPECT_EQ(msg3, \"abc\");\n}\n<commit_msg>cpplint fix.<commit_after>\/\/ Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)\n\/\/ This file is distributed under the MIT License.\n\n#include \"ofp\/rpc\/rpcevents.h\"\n#include \"ofp\/unittest.h\"\n\nTEST(rpcevents, test_TrimErrorMessage) {\n std::string msg1 = \"x\\n ^\";\n ofp::rpc::TrimErrorMessage(msg1);\n EXPECT_EQ(msg1, \"x\");\n\n std::string msg2 = \"\";\n ofp::rpc::TrimErrorMessage(msg2);\n EXPECT_EQ(msg2, \"\");\n\n std::string msg3 = \"abc\";\n ofp::rpc::TrimErrorMessage(msg3);\n EXPECT_EQ(msg3, \"abc\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <memory>\n#include <gmock\/gmock.h>\n\n#include \"smartsqlite\/connection.h\"\n#include \"smartsqlite\/exceptions.h\"\n#include \"smartsqlite\/scopedtransaction.h\"\n\nusing namespace testing;\nusing ConnPtr = std::shared_ptr<SmartSqlite::Connection>;\n\nstatic ConnPtr makeConnection()\n{\n return std::make_shared<SmartSqlite::Connection>(\n SmartSqlite::makeConnection(\":memory:\"));\n}\n\nstatic int getUserVersion(ConnPtr conn)\n{\n auto stmt = conn->prepare(\"PRAGMA user_version\");\n return stmt.execWithSingleResult().get<int>(0);\n}\n\nstatic void setUserVersion(ConnPtr conn, int version)\n{\n conn->exec(\"PRAGMA user_version = \" + std::to_string(version));\n}\n\n\nTEST(ScopedTransaction, ctorDoesntThrow)\n{\n SmartSqlite::ScopedTransaction tx(makeConnection());\n}\n\nTEST(ScopedTransaction, ctorBeginsTransaction)\n{\n auto conn = makeConnection();\n SmartSqlite::ScopedTransaction tx(conn);\n (void)tx;\n\n EXPECT_THROW(conn->beginTransaction(), SmartSqlite::SqliteException);\n}\n\nTEST(ScopedTransaction, dtorRollsBack)\n{\n auto conn = makeConnection();\n int origVersion = 23;\n conn->exec(\"PRAGMA user_version = \" + std::to_string(origVersion));\n {\n SmartSqlite::ScopedTransaction tx(conn);\n (void)tx;\n setUserVersion(conn, 42);\n }\n\n EXPECT_THAT(getUserVersion(conn), Eq(origVersion));\n}\n\nTEST(ScopedTransaction, commitEndsTransaction)\n{\n auto conn = makeConnection();\n SmartSqlite::ScopedTransaction tx(conn);\n tx.commit();\n\n \/\/ would throw if commit didn't end the transaction\n conn->beginTransaction();\n}\n\nTEST(ScopedTransaction, commitCancelsRollback)\n{\n auto conn = makeConnection();\n setUserVersion(conn, 42);\n int version = 23;\n {\n SmartSqlite::ScopedTransaction tx(conn);\n tx.commit();\n\n conn->beginTransaction();\n setUserVersion(conn, version);\n }\n\n \/\/ user_version would be 42 if ~ScopedTransaction would rollback\n EXPECT_THAT(getUserVersion(conn), Eq(version));\n}\n<commit_msg>ScopedTransaction tests: Reuse SQL<commit_after>#include <memory>\n#include <gmock\/gmock.h>\n\n#include \"smartsqlite\/connection.h\"\n#include \"smartsqlite\/exceptions.h\"\n#include \"smartsqlite\/scopedtransaction.h\"\n\nusing namespace testing;\nusing ConnPtr = std::shared_ptr<SmartSqlite::Connection>;\n\nstatic ConnPtr makeConnection()\n{\n return std::make_shared<SmartSqlite::Connection>(\n SmartSqlite::makeConnection(\":memory:\"));\n}\n\nstatic int getUserVersion(ConnPtr conn)\n{\n auto stmt = conn->prepare(\"PRAGMA user_version\");\n return stmt.execWithSingleResult().get<int>(0);\n}\n\nstatic void setUserVersion(ConnPtr conn, int version)\n{\n conn->exec(\"PRAGMA user_version = \" + std::to_string(version));\n}\n\n\nTEST(ScopedTransaction, ctorDoesntThrow)\n{\n SmartSqlite::ScopedTransaction tx(makeConnection());\n}\n\nTEST(ScopedTransaction, ctorBeginsTransaction)\n{\n auto conn = makeConnection();\n SmartSqlite::ScopedTransaction tx(conn);\n (void)tx;\n\n EXPECT_THROW(conn->beginTransaction(), SmartSqlite::SqliteException);\n}\n\nTEST(ScopedTransaction, dtorRollsBack)\n{\n auto conn = makeConnection();\n int origVersion = 23;\n setUserVersion(conn, origVersion);\n {\n SmartSqlite::ScopedTransaction tx(conn);\n (void)tx;\n setUserVersion(conn, 42);\n }\n\n EXPECT_THAT(getUserVersion(conn), Eq(origVersion));\n}\n\nTEST(ScopedTransaction, commitEndsTransaction)\n{\n auto conn = makeConnection();\n SmartSqlite::ScopedTransaction tx(conn);\n tx.commit();\n\n \/\/ would throw if commit didn't end the transaction\n conn->beginTransaction();\n}\n\nTEST(ScopedTransaction, commitCancelsRollback)\n{\n auto conn = makeConnection();\n setUserVersion(conn, 42);\n int version = 23;\n {\n SmartSqlite::ScopedTransaction tx(conn);\n tx.commit();\n\n conn->beginTransaction();\n setUserVersion(conn, version);\n }\n\n \/\/ user_version would be 42 if ~ScopedTransaction would rollback\n EXPECT_THAT(getUserVersion(conn), Eq(version));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Written by Nitin Kumar Maharana\n * nitin.maharana@gmail.com\n *\/\n\n\/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n *\/\nclass Solution {\n TreeNode* buildTree(vector<int>& inorder, vector<int>& preorder, int l, int r, int i)\n {\n if(l > r || i >= preorder.size())\n return NULL;\n \n int found = -1;\n \n for(int j = l; j <= r; j++)\n {\n if(inorder[j] == preorder[i])\n {\n found = j;\n break;\n }\n }\n \n if(found == -1)\n return buildTree(inorder, preorder, l, r, i+1);\n \n TreeNode* head;\n \n head = new TreeNode(preorder[i]);\n \n head->left = buildTree(inorder, preorder, l, found-1, i+1);\n \n head->right = buildTree(inorder, preorder, found+1, r, i+1);\n }\npublic:\n TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {\n return buildTree(inorder, preorder, 0, inorder.size()-1, 0);\n }\n};<commit_msg>105. Construct Binary Tree from Preorder and Inorder Traversal - Optimized<commit_after>\/*\n * Written by Nitin Kumar Maharana\n * nitin.maharana@gmail.com\n *\/\n\n\/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n *\/\nclass Solution {\n TreeNode* buildTree(vector<int>& inorder, vector<int>& preorder, int l, int r, int i)\n {\n if(l > r || i >= preorder.size())\n return NULL;\n \n int found;\n \n for(int j = l; j <= r; j++)\n {\n if(inorder[j] == preorder[i])\n {\n found = j;\n break;\n }\n }\n \n TreeNode* head;\n \n head = new TreeNode(preorder[i]);\n \n head->left = buildTree(inorder, preorder, l, found-1, i+1);\n \n head->right = buildTree(inorder, preorder, found+1, r, i+1+found-l);\n }\npublic:\n TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {\n return buildTree(inorder, preorder, 0, inorder.size()-1, 0);\n }\n};<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com>\n\n This file is a part of TelegramQt library.\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 *\/\n\n#include \"DataStorage_p.hpp\"\n\n#include \"ApiUtils.hpp\"\n#include \"TLTypesDebug.hpp\"\n#include \"Utils.hpp\"\n#include \"Debug.hpp\"\n\n#include \"TelegramNamespace_p.hpp\"\n\n#include <QLoggingCategory>\n\nnamespace Telegram {\n\nnamespace Client {\n\n\/*!\n \\class Telegram::Client::DataStorage\n \\brief The DataStorage class provides a basic interface for session\n data management\n \\inmodule TelegramQt\n \\ingroup Client\n\n \\sa AccountStorage\n*\/\n\nDataStorage::DataStorage(QObject *parent) :\n DataStorage(new DataStoragePrivate(), parent)\n{\n}\n\nDcConfiguration DataStorage::serverConfiguration() const\n{\n Q_D(const DataStorage);\n return d->m_serverConfig;\n}\n\nvoid DataStorage::setServerConfiguration(const DcConfiguration &configuration)\n{\n Q_D(DataStorage);\n d->m_serverConfig = configuration;\n}\n\nQVector<Peer> DataStorage::dialogs() const\n{\n Q_D(const DataStorage);\n const TLMessagesDialogs dialogs = d->m_api->m_dialogs;\n QVector<Peer> result;\n result.reserve(dialogs.count);\n for (const TLDialog &dialog : dialogs.dialogs) {\n result.append(Utils::toPublicPeer(dialog.peer));\n }\n return result;\n}\n\nQVector<Peer> DataStorage::contactList() const\n{\n Q_D(const DataStorage);\n const TLVector<TLContact> contacts = d->m_api->m_contactList;\n QVector<Peer> result;\n result.reserve(contacts.count());\n for (const TLContact &contact : contacts) {\n result.append(Peer::fromUserId(contact.userId));\n }\n return result;\n}\n\nquint32 DataStorage::selfUserId() const\n{\n Q_D(const DataStorage);\n return d->m_api->selfUserId();\n}\n\nbool DataStorage::getDialogInfo(DialogInfo *info, const Peer &peer) const\n{\n Q_D(const DataStorage);\n const auto &dialogs = d->m_api->m_dialogs;\n for (const TLDialog &dialog : dialogs.dialogs) {\n Telegram::Peer thisDialogPeer = Utils::toPublicPeer(dialog.peer);\n if (thisDialogPeer == peer) {\n TLDialog *infoData = Telegram::DialogInfo::Private::get(info);\n *infoData = dialog;\n return true;\n }\n }\n qDebug() << Q_FUNC_INFO << \"Unknown dialog\" << peer.toString();\n return false;\n}\n\nbool DataStorage::getUserInfo(UserInfo *info, quint32 userId) const\n{\n Q_D(const DataStorage);\n const auto &users = d->m_api->m_users;\n if (!users.contains(userId)) {\n qDebug() << Q_FUNC_INFO << \"Unknown user\" << userId;\n return false;\n }\n\n const TLUser *user = users.value(userId);\n TLUser *infoData = Telegram::UserInfo::Private::get(info);\n *infoData = *user;\n return true;\n}\n\nbool DataStorage::getChatInfo(ChatInfo *info, const Telegram::Peer &peer) const\n{\n Q_D(const DataStorage);\n const quint32 chatId = peer.id;\n const auto &chats = d->m_api->m_chats;\n if (!chats.contains(chatId)) {\n qDebug() << Q_FUNC_INFO << \"Unknown user\" << chatId;\n return false;\n }\n\n const TLChat *chat = chats.value(chatId);\n TLChat *infoData = Telegram::ChatInfo::Private::get(info);\n *infoData = *chat;\n return true;\n}\n\nbool DataStorage::getMessage(Message *message, const Peer &peer, quint32 messageId)\n{\n Q_D(const DataStorage);\n const TLMessage *m = d->m_api->getMessage(peer, messageId);\n if (!m) {\n qDebug() << Q_FUNC_INFO << \"Unknown message\" << peer << messageId;\n return false;\n }\n const TLMessageMedia &media = m->media;\n\n message->id = messageId;\n message->type = Telegram::Utils::getPublicMessageType(media);\n message->fromId = m->fromId;\n message->timestamp = m->date;\n message->text = m->message;\n message->flags = TelegramNamespace::MessageFlagNone;\n if (m->out()) {\n message->flags |= TelegramNamespace::MessageFlagOut;\n }\n if (m->flags & TLMessage::FwdFrom) {\n message->flags |= TelegramNamespace::MessageFlagForwarded;\n if (m->fwdFrom.flags & TLMessageFwdHeader::FromId) {\n \/\/message->setForwardFromPeer((m->fwdFrom))\n }\n }\n return true;\n}\n\nbool DataStorage::getMessageMediaInfo(MessageMediaInfo *info, const Peer &peer, quint32 messageId)\n{\n Q_D(const DataStorage);\n const TLMessage *m = nullptr;\n if (peer.type == Peer::Channel) {\n quint64 key = DataInternalApi::channelMessageToKey(peer.id, messageId);\n m = d->m_api->m_channelMessages.value(key);\n } else {\n m = d->m_api->m_clientMessages.value(messageId);\n }\n if (!m) {\n qDebug() << Q_FUNC_INFO << \"Unknown message\" << peer << messageId;\n return false;\n }\n const TLMessageMedia &media = m->media;\n\n MessageMediaInfo::Private *privateInfo = MessageMediaInfo::Private::get(info);\n *privateInfo = media;\n return true;\n}\n\nDataStorage::DataStorage(DataStoragePrivate *priv, QObject *parent)\n : QObject(parent),\n d(priv)\n{\n d->m_api = new DataInternalApi(this);\n}\n\nInMemoryDataStorage::InMemoryDataStorage(QObject *parent) :\n DataStorage(parent)\n{\n}\n\nDataInternalApi::DataInternalApi(QObject *parent) :\n QObject(parent)\n{\n}\n\nDataInternalApi::~DataInternalApi()\n{\n}\n\nconst TLUser *DataInternalApi::getSelfUser() const\n{\n if (!m_selfUserId) {\n return nullptr;\n }\n return m_users.value(m_selfUserId);\n}\n\nconst TLMessage *DataInternalApi::getMessage(const Peer &peer, quint32 messageId) const\n{\n if (peer.type == Peer::Channel) {\n quint64 key = DataInternalApi::channelMessageToKey(peer.id, messageId);\n return m_channelMessages.value(key);\n }\n return m_clientMessages.value(messageId);\n}\n\nvoid DataInternalApi::processData(const TLMessage &message)\n{\n TLMessage *m = nullptr;\n if (message.toId.tlType == TLValue::PeerChannel) {\n const quint64 key = channelMessageToKey(message.toId.channelId, message.id);\n if (!m_channelMessages.contains(key)) {\n m_channelMessages.insert(key, new TLMessage());\n }\n m = m_channelMessages.value(key);\n } else {\n const quint32 key = message.id;\n if (!m_clientMessages.contains(key)) {\n m_clientMessages.insert(key, new TLMessage());\n }\n m = m_clientMessages.value(key);\n }\n *m = message;\n}\n\nvoid DataInternalApi::processData(const TLVector<TLChat> &chats)\n{\n for (const TLChat &chat : chats) {\n processData(chat);\n }\n}\n\nvoid DataInternalApi::processData(const TLChat &chat)\n{\n if (!m_chats.contains(chat.id)) {\n TLChat *newChatInstance = new TLChat(chat);\n m_chats.insert(chat.id, newChatInstance);\n } else {\n *m_chats[chat.id] = chat;\n }\n}\n\nvoid DataInternalApi::processData(const TLVector<TLUser> &users)\n{\n for (const TLUser &user : users) {\n processData(user);\n }\n}\n\nvoid DataInternalApi::processData(const TLUser &user)\n{\n TLUser *existsUser = m_users.value(user.id);\n if (existsUser) {\n *existsUser = user;\n } else {\n m_users.insert(user.id, new TLUser(user));\n }\n if (user.self()) {\n if (m_selfUserId && (m_selfUserId != user.id)) {\n qWarning() << \"Got self user with different id.\";\n }\n m_selfUserId = user.id;\n }\n}\n\nvoid DataInternalApi::processData(const TLAuthAuthorization &authorization)\n{\n processData(authorization.user);\n}\n\nvoid DataInternalApi::processData(const TLMessagesDialogs &dialogs)\n{\n \/\/qDebug() << Q_FUNC_INFO << dialogs;\n m_dialogs = dialogs;\n processData(dialogs.users);\n processData(dialogs.chats);\n for (const TLMessage &message : dialogs.messages) {\n processData(message);\n }\n}\n\nvoid DataInternalApi::processData(const TLMessagesMessages &messages)\n{\n processData(messages.users);\n processData(messages.chats);\n for (const TLMessage &message : messages.messages) {\n processData(message);\n }\n}\n\nvoid DataInternalApi::setContactList(const TLVector<TLContact> &contacts)\n{\n m_contactList = contacts;\n}\n\nquint64 DataInternalApi::enqueueMessage(const Telegram::Peer peer, const QString &message, quint32 replyToMsgId)\n{\n SentMessage sentMessage;\n sentMessage.peer = peer;\n sentMessage.text = message;\n sentMessage.replyToMsgId = replyToMsgId;\n sentMessage.randomId = Utils::randomBytes<quint64>();\n m_queuedMessages.append(sentMessage);\n return sentMessage.randomId;\n}\n\nDataInternalApi::SentMessage DataInternalApi::getQueuedMessage(quint64 randomMessageId) const\n{\n for (const SentMessage &message : m_queuedMessages) {\n if (message.randomId == randomMessageId) {\n return message;\n }\n }\n return SentMessage();\n}\n\nDataInternalApi::SentMessage DataInternalApi::dequeueMessage(quint64 messageRandomId, quint32 messageId)\n{\n if (m_queuedMessages.isEmpty()) {\n qWarning() << Q_FUNC_INFO << \"Invalid dequeue request (message queue is empty):\" << messageRandomId << messageId;\n return SentMessage();\n }\n if (m_queuedMessages.head().randomId == messageRandomId) {\n return m_queuedMessages.dequeue();\n }\n for (int i = 0; i < m_queuedMessages.count(); ++i) {\n if (m_queuedMessages.at(i).randomId == messageRandomId) {\n return m_queuedMessages.takeAt(i);\n }\n }\n qWarning() << Q_FUNC_INFO << \"Invalid dequeue request (message not found):\" << messageRandomId << messageId;\n return SentMessage();\n}\n\nTLInputPeer DataInternalApi::toInputPeer(const Peer &peer) const\n{\n TLInputPeer inputPeer;\n switch (peer.type) {\n case Telegram::Peer::Chat:\n inputPeer.tlType = TLValue::InputPeerChat;\n inputPeer.chatId = peer.id;\n break;\n case Telegram::Peer::Channel:\n if (m_chats.contains(peer.id)) {\n inputPeer.tlType = TLValue::InputPeerChannel;\n inputPeer.channelId = peer.id;\n inputPeer.accessHash = m_chats.value(peer.id)->accessHash;\n } else {\n qWarning() << Q_FUNC_INFO << \"Unknown public channel id\" << peer.id;\n }\n break;\n case Telegram::Peer::User:\n if (peer.id == m_selfUserId) {\n inputPeer.tlType = TLValue::InputPeerSelf;\n } else {\n if (m_users.contains(peer.id)) {\n inputPeer.tlType = TLValue::InputPeerUser;\n inputPeer.userId = peer.id;\n inputPeer.accessHash = m_users.value(peer.id)->accessHash;\n } else {\n qWarning() << Q_FUNC_INFO << \"Unknown user\" << peer.id;\n }\n }\n break;\n default:\n qWarning() << Q_FUNC_INFO << \"Unknown peer type\" << peer.type << \"(id:\" << peer.id << \")\";\n break;\n }\n return inputPeer;\n}\n\nTLInputUser DataInternalApi::toInputUser(quint32 userId) const\n{\n TLInputUser inputUser;\n if (userId == selfUserId()) {\n inputUser.tlType = TLValue::InputUserSelf;\n return inputUser;\n }\n const TLUser *user = m_users.value(userId);\n if (user) {\n if (user->tlType == TLValue::User) {\n inputUser.tlType = TLValue::InputUser;\n inputUser.userId = user->id;\n inputUser.accessHash = user->accessHash;\n } else {\n qWarning() << Q_FUNC_INFO << \"Unknown user type: \" << QString::number(user->tlType, 16);\n }\n } else {\n qWarning() << Q_FUNC_INFO << \"Unknown user.\";\n }\n return inputUser;\n}\n\nquint64 DataInternalApi::channelMessageToKey(quint32 channelId, quint32 messageId)\n{\n quint64 key = channelId;\n return (key << 32) + messageId;\n}\n\nDataStoragePrivate *DataStoragePrivate::get(DataStorage *parent)\n{\n return parent->d;\n}\n\n} \/\/ Client namespace\n\n} \/\/ Telegram namespace\n<commit_msg>DataStorage: Use extracted getMessage()<commit_after>\/*\n Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com>\n\n This file is a part of TelegramQt library.\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 *\/\n\n#include \"DataStorage_p.hpp\"\n\n#include \"ApiUtils.hpp\"\n#include \"TLTypesDebug.hpp\"\n#include \"Utils.hpp\"\n#include \"Debug.hpp\"\n\n#include \"TelegramNamespace_p.hpp\"\n\n#include <QLoggingCategory>\n\nnamespace Telegram {\n\nnamespace Client {\n\n\/*!\n \\class Telegram::Client::DataStorage\n \\brief The DataStorage class provides a basic interface for session\n data management\n \\inmodule TelegramQt\n \\ingroup Client\n\n \\sa AccountStorage\n*\/\n\nDataStorage::DataStorage(QObject *parent) :\n DataStorage(new DataStoragePrivate(), parent)\n{\n}\n\nDcConfiguration DataStorage::serverConfiguration() const\n{\n Q_D(const DataStorage);\n return d->m_serverConfig;\n}\n\nvoid DataStorage::setServerConfiguration(const DcConfiguration &configuration)\n{\n Q_D(DataStorage);\n d->m_serverConfig = configuration;\n}\n\nQVector<Peer> DataStorage::dialogs() const\n{\n Q_D(const DataStorage);\n const TLMessagesDialogs dialogs = d->m_api->m_dialogs;\n QVector<Peer> result;\n result.reserve(dialogs.count);\n for (const TLDialog &dialog : dialogs.dialogs) {\n result.append(Utils::toPublicPeer(dialog.peer));\n }\n return result;\n}\n\nQVector<Peer> DataStorage::contactList() const\n{\n Q_D(const DataStorage);\n const TLVector<TLContact> contacts = d->m_api->m_contactList;\n QVector<Peer> result;\n result.reserve(contacts.count());\n for (const TLContact &contact : contacts) {\n result.append(Peer::fromUserId(contact.userId));\n }\n return result;\n}\n\nquint32 DataStorage::selfUserId() const\n{\n Q_D(const DataStorage);\n return d->m_api->selfUserId();\n}\n\nbool DataStorage::getDialogInfo(DialogInfo *info, const Peer &peer) const\n{\n Q_D(const DataStorage);\n const auto &dialogs = d->m_api->m_dialogs;\n for (const TLDialog &dialog : dialogs.dialogs) {\n Telegram::Peer thisDialogPeer = Utils::toPublicPeer(dialog.peer);\n if (thisDialogPeer == peer) {\n TLDialog *infoData = Telegram::DialogInfo::Private::get(info);\n *infoData = dialog;\n return true;\n }\n }\n qDebug() << Q_FUNC_INFO << \"Unknown dialog\" << peer.toString();\n return false;\n}\n\nbool DataStorage::getUserInfo(UserInfo *info, quint32 userId) const\n{\n Q_D(const DataStorage);\n const auto &users = d->m_api->m_users;\n if (!users.contains(userId)) {\n qDebug() << Q_FUNC_INFO << \"Unknown user\" << userId;\n return false;\n }\n\n const TLUser *user = users.value(userId);\n TLUser *infoData = Telegram::UserInfo::Private::get(info);\n *infoData = *user;\n return true;\n}\n\nbool DataStorage::getChatInfo(ChatInfo *info, const Telegram::Peer &peer) const\n{\n Q_D(const DataStorage);\n const quint32 chatId = peer.id;\n const auto &chats = d->m_api->m_chats;\n if (!chats.contains(chatId)) {\n qDebug() << Q_FUNC_INFO << \"Unknown user\" << chatId;\n return false;\n }\n\n const TLChat *chat = chats.value(chatId);\n TLChat *infoData = Telegram::ChatInfo::Private::get(info);\n *infoData = *chat;\n return true;\n}\n\nbool DataStorage::getMessage(Message *message, const Peer &peer, quint32 messageId)\n{\n Q_D(const DataStorage);\n const TLMessage *m = d->m_api->getMessage(peer, messageId);\n if (!m) {\n qDebug() << Q_FUNC_INFO << \"Unknown message\" << peer << messageId;\n return false;\n }\n const TLMessageMedia &media = m->media;\n\n message->id = messageId;\n message->type = Telegram::Utils::getPublicMessageType(media);\n message->fromId = m->fromId;\n message->timestamp = m->date;\n message->text = m->message;\n message->flags = TelegramNamespace::MessageFlagNone;\n if (m->out()) {\n message->flags |= TelegramNamespace::MessageFlagOut;\n }\n if (m->flags & TLMessage::FwdFrom) {\n message->flags |= TelegramNamespace::MessageFlagForwarded;\n if (m->fwdFrom.flags & TLMessageFwdHeader::FromId) {\n \/\/message->setForwardFromPeer((m->fwdFrom))\n }\n }\n return true;\n}\n\nbool DataStorage::getMessageMediaInfo(MessageMediaInfo *info, const Peer &peer, quint32 messageId)\n{\n Q_D(const DataStorage);\n const TLMessage *m = d->m_api->getMessage(peer, messageId);\n if (!m) {\n qDebug() << Q_FUNC_INFO << \"Unknown message\" << peer << messageId;\n return false;\n }\n const TLMessageMedia &media = m->media;\n\n MessageMediaInfo::Private *privateInfo = MessageMediaInfo::Private::get(info);\n *privateInfo = media;\n return true;\n}\n\nDataStorage::DataStorage(DataStoragePrivate *priv, QObject *parent)\n : QObject(parent),\n d(priv)\n{\n d->m_api = new DataInternalApi(this);\n}\n\nInMemoryDataStorage::InMemoryDataStorage(QObject *parent) :\n DataStorage(parent)\n{\n}\n\nDataInternalApi::DataInternalApi(QObject *parent) :\n QObject(parent)\n{\n}\n\nDataInternalApi::~DataInternalApi()\n{\n}\n\nconst TLUser *DataInternalApi::getSelfUser() const\n{\n if (!m_selfUserId) {\n return nullptr;\n }\n return m_users.value(m_selfUserId);\n}\n\nconst TLMessage *DataInternalApi::getMessage(const Peer &peer, quint32 messageId) const\n{\n if (peer.type == Peer::Channel) {\n quint64 key = DataInternalApi::channelMessageToKey(peer.id, messageId);\n return m_channelMessages.value(key);\n }\n return m_clientMessages.value(messageId);\n}\n\nvoid DataInternalApi::processData(const TLMessage &message)\n{\n TLMessage *m = nullptr;\n if (message.toId.tlType == TLValue::PeerChannel) {\n const quint64 key = channelMessageToKey(message.toId.channelId, message.id);\n if (!m_channelMessages.contains(key)) {\n m_channelMessages.insert(key, new TLMessage());\n }\n m = m_channelMessages.value(key);\n } else {\n const quint32 key = message.id;\n if (!m_clientMessages.contains(key)) {\n m_clientMessages.insert(key, new TLMessage());\n }\n m = m_clientMessages.value(key);\n }\n *m = message;\n}\n\nvoid DataInternalApi::processData(const TLVector<TLChat> &chats)\n{\n for (const TLChat &chat : chats) {\n processData(chat);\n }\n}\n\nvoid DataInternalApi::processData(const TLChat &chat)\n{\n if (!m_chats.contains(chat.id)) {\n TLChat *newChatInstance = new TLChat(chat);\n m_chats.insert(chat.id, newChatInstance);\n } else {\n *m_chats[chat.id] = chat;\n }\n}\n\nvoid DataInternalApi::processData(const TLVector<TLUser> &users)\n{\n for (const TLUser &user : users) {\n processData(user);\n }\n}\n\nvoid DataInternalApi::processData(const TLUser &user)\n{\n TLUser *existsUser = m_users.value(user.id);\n if (existsUser) {\n *existsUser = user;\n } else {\n m_users.insert(user.id, new TLUser(user));\n }\n if (user.self()) {\n if (m_selfUserId && (m_selfUserId != user.id)) {\n qWarning() << \"Got self user with different id.\";\n }\n m_selfUserId = user.id;\n }\n}\n\nvoid DataInternalApi::processData(const TLAuthAuthorization &authorization)\n{\n processData(authorization.user);\n}\n\nvoid DataInternalApi::processData(const TLMessagesDialogs &dialogs)\n{\n \/\/qDebug() << Q_FUNC_INFO << dialogs;\n m_dialogs = dialogs;\n processData(dialogs.users);\n processData(dialogs.chats);\n for (const TLMessage &message : dialogs.messages) {\n processData(message);\n }\n}\n\nvoid DataInternalApi::processData(const TLMessagesMessages &messages)\n{\n processData(messages.users);\n processData(messages.chats);\n for (const TLMessage &message : messages.messages) {\n processData(message);\n }\n}\n\nvoid DataInternalApi::setContactList(const TLVector<TLContact> &contacts)\n{\n m_contactList = contacts;\n}\n\nquint64 DataInternalApi::enqueueMessage(const Telegram::Peer peer, const QString &message, quint32 replyToMsgId)\n{\n SentMessage sentMessage;\n sentMessage.peer = peer;\n sentMessage.text = message;\n sentMessage.replyToMsgId = replyToMsgId;\n sentMessage.randomId = Utils::randomBytes<quint64>();\n m_queuedMessages.append(sentMessage);\n return sentMessage.randomId;\n}\n\nDataInternalApi::SentMessage DataInternalApi::getQueuedMessage(quint64 randomMessageId) const\n{\n for (const SentMessage &message : m_queuedMessages) {\n if (message.randomId == randomMessageId) {\n return message;\n }\n }\n return SentMessage();\n}\n\nDataInternalApi::SentMessage DataInternalApi::dequeueMessage(quint64 messageRandomId, quint32 messageId)\n{\n if (m_queuedMessages.isEmpty()) {\n qWarning() << Q_FUNC_INFO << \"Invalid dequeue request (message queue is empty):\" << messageRandomId << messageId;\n return SentMessage();\n }\n if (m_queuedMessages.head().randomId == messageRandomId) {\n return m_queuedMessages.dequeue();\n }\n for (int i = 0; i < m_queuedMessages.count(); ++i) {\n if (m_queuedMessages.at(i).randomId == messageRandomId) {\n return m_queuedMessages.takeAt(i);\n }\n }\n qWarning() << Q_FUNC_INFO << \"Invalid dequeue request (message not found):\" << messageRandomId << messageId;\n return SentMessage();\n}\n\nTLInputPeer DataInternalApi::toInputPeer(const Peer &peer) const\n{\n TLInputPeer inputPeer;\n switch (peer.type) {\n case Telegram::Peer::Chat:\n inputPeer.tlType = TLValue::InputPeerChat;\n inputPeer.chatId = peer.id;\n break;\n case Telegram::Peer::Channel:\n if (m_chats.contains(peer.id)) {\n inputPeer.tlType = TLValue::InputPeerChannel;\n inputPeer.channelId = peer.id;\n inputPeer.accessHash = m_chats.value(peer.id)->accessHash;\n } else {\n qWarning() << Q_FUNC_INFO << \"Unknown public channel id\" << peer.id;\n }\n break;\n case Telegram::Peer::User:\n if (peer.id == m_selfUserId) {\n inputPeer.tlType = TLValue::InputPeerSelf;\n } else {\n if (m_users.contains(peer.id)) {\n inputPeer.tlType = TLValue::InputPeerUser;\n inputPeer.userId = peer.id;\n inputPeer.accessHash = m_users.value(peer.id)->accessHash;\n } else {\n qWarning() << Q_FUNC_INFO << \"Unknown user\" << peer.id;\n }\n }\n break;\n default:\n qWarning() << Q_FUNC_INFO << \"Unknown peer type\" << peer.type << \"(id:\" << peer.id << \")\";\n break;\n }\n return inputPeer;\n}\n\nTLInputUser DataInternalApi::toInputUser(quint32 userId) const\n{\n TLInputUser inputUser;\n if (userId == selfUserId()) {\n inputUser.tlType = TLValue::InputUserSelf;\n return inputUser;\n }\n const TLUser *user = m_users.value(userId);\n if (user) {\n if (user->tlType == TLValue::User) {\n inputUser.tlType = TLValue::InputUser;\n inputUser.userId = user->id;\n inputUser.accessHash = user->accessHash;\n } else {\n qWarning() << Q_FUNC_INFO << \"Unknown user type: \" << QString::number(user->tlType, 16);\n }\n } else {\n qWarning() << Q_FUNC_INFO << \"Unknown user.\";\n }\n return inputUser;\n}\n\nquint64 DataInternalApi::channelMessageToKey(quint32 channelId, quint32 messageId)\n{\n quint64 key = channelId;\n return (key << 32) + messageId;\n}\n\nDataStoragePrivate *DataStoragePrivate::get(DataStorage *parent)\n{\n return parent->d;\n}\n\n} \/\/ Client namespace\n\n} \/\/ Telegram namespace\n<|endoftext|>"} {"text":"<commit_before>#include \"Histo.h\"\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nHisto::Histo() {output_reset();}\n\nHisto::Histo(int in, double imin, double imax) {\n\tset(in,imin,imax);\n\toutput_reset();\n}\t\n\nvoid Histo::set(int in, double imin, double imax) {\n\tn = in;\n\tmin = imin;\n\tmax = imax;\n\t\n\twidth = (max-min)\/n;\n\tmin_border = min + width;\n\tmax_border = max - width;\n\tmin_output = min + width * .5;\n\t\t\n\thist.clear();\n\thist.resize(n);\n}\n\nvoid Histo::set(int in, double imax) {set(in,-imax,imax);}\n\nvoid Histo::add(double val) {\n\tcount++;\n\tif ( val >= max || val < min ) return;\n\tif ( val < min_border ) hist[0]++;\n\telse if (val >= max_border ) hist[n-1]++;\n\telse hist[ (int) ( (val-min) \/ width ) ]++;\n}\n\nbool Histo::output(ostream& os) {\n\tif ( n_out >= n ) return false;\n\tos.precision(8);\n\tos << scientific;\n\tos << min_output + n_out * width << \" \";\n\tos << hist[n_out] << \" \";\n\tn_out++;\n\treturn true;\n}\n\nbool Histo::output() {return output(cout);}\n\nvoid Histo::output_reset() {n_out=0;}\n\nvoid Histo::norm() {\n\tdouble scale{count * width};\n\tfor (auto& s : hist) s \/= scale;\n}\n<commit_msg>count initiert Ausgabe auf Tabulatoren umgestellt<commit_after>#include \"Histo.h\"\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nHisto::Histo() {output_reset();}\n\nHisto::Histo(int in, double imin, double imax) {\n\tset(in,imin,imax);\n\toutput_reset();\n}\t\n\nvoid Histo::set(int in, double imin, double imax) {\n\tn = in;\n\tmin = imin;\n\tmax = imax;\n\t\n\twidth = (max-min)\/n;\n\tmin_border = min + width;\n\tmax_border = max - width;\n\tmin_output = min + width * .5;\n\t\t\n\thist.clear();\n\thist.resize(n);\n\tcount = 0;\n}\n\nvoid Histo::set(int in, double imax) {set(in,-imax,imax);}\n\nvoid Histo::add(double val) {\n\tcount++;\n\tif ( val >= max || val < min ) return;\n\tif ( val < min_border ) hist[0]++;\n\telse if (val >= max_border ) hist[n-1]++;\n\telse hist[ (int) ( (val-min) \/ width ) ]++;\n}\n\nbool Histo::output(ostream& os) {\n\tif ( n_out >= n ) { \n\t\tos << \" \\t \\t\";\n\t\treturn false;\n\t}\n\tos.precision(8);\n\tos << scientific;\n\tos << min_output + n_out * width << '\\t';\n\tos << hist[n_out] << '\\t';\n\tn_out++;\n\treturn true;\n}\n\nbool Histo::output() {return output(cout);}\n\nvoid Histo::output_reset() {n_out=0;}\n\nvoid Histo::norm() {\n\tdouble scale{count * width};\n\tfor (auto& s : hist) s \/= scale;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"tables.h\"\n\n\/*This information was previously in main but was moved out to make test programs\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/INITIALIZIING\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace editor\n{\n int WIN_HEIGHT, WIN_WIDTH;\n WIN *ptrnwin;\n WIN *instwin;\n WIN *metawin;\n WIN *volwin;\n WIN *wavewin;\n WIN *pulsewin;\n WIN *dialog;\n\n WIN *wingroup;\n WIN *inputwin;\n WIN *lastwin;\n\n bool running;\n\n\n int numBuffer;\n char charBuffer[CHARBUFFER_SIZE];\n char charInputBuffer[CMDBAR_SIZE];\n\n char charInputHistory[HISTORY_SIZE][CMDBAR_SIZE];\n char history_head;\n char history_size;\n\n char lastSongPath[LASTSONG_SIZE];\n char textCursorPos;\n bool *muted_tracks;\n float playamp;\n\n\n Song *song;\n int daemonpid;\n Song *playback;\n unsigned char playback_length;\n unsigned char playback_mark;\n Instrument *selinst;\n}\n\n\/\/Pattern Editor\nnamespace patternedtr\n{\n std::map<int,unsigned int> notemap;\n Pattern *selptrn; \n unsigned char viewporttrack;\n unsigned char viewportrow;\n\n unsigned char maxtracksviewport;\n unsigned char maxrowsviewport;\n\n unsigned char selrow;\n unsigned char seltrack;\n unsigned char seltrackseg;\n unsigned char selorder;\n\n unsigned char selinstrument;\n unsigned char edit_step;\n unsigned char row_underline;\n unsigned char octave;\n unsigned char key;\n unsigned char scalespinner;\n unsigned char scaleconst[12];\/\/Scale construction pattern\n unsigned int entryclipboard;\n\n\n \/\/METADATA (Main controls)\n unsigned char metaobjindex;\n bool metaobjedit;\n\n unsigned char selobjmeta;\/\/x\n unsigned char selrowmeta;\/\/y\n\n}\n\n\/\/Instrument Editor\nnamespace instedtr\n{\n unsigned short waveclipboard;\n unsigned short pulseclipboard;\n unsigned short volclipboard;\n\n bool instobjedit;\n unsigned char selinstrow;\n unsigned char selinstobj;\n unsigned short selwavrow;\n unsigned short selpulrow;\n unsigned char selpulseg;\n\n\n unsigned char selwavseg;\n unsigned short viewportwave;\n unsigned short viewportpulse;\n unsigned char viewportvol;\n\n\n unsigned char selvolrow;\n unsigned char selvolseg;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/DONE INITIALIZING\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Moved functions from utility into externinit.cpp<commit_after>#include \"tables.h\"\n#include \"daemoncomm.h\"\n\n\/*This information was previously in main but was moved out to make test programs\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/INITIALIZIING\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace editor\n{\n int WIN_HEIGHT, WIN_WIDTH;\n WIN *ptrnwin;\n WIN *instwin;\n WIN *metawin;\n WIN *volwin;\n WIN *wavewin;\n WIN *pulsewin;\n WIN *dialog;\n\n WIN *wingroup;\n WIN *inputwin;\n WIN *lastwin;\n\n bool running;\n\n\n int numBuffer;\n char charBuffer[CHARBUFFER_SIZE];\n char charInputBuffer[CMDBAR_SIZE];\n\n char charInputHistory[HISTORY_SIZE][CMDBAR_SIZE];\n char history_head;\n char history_size;\n\n char lastSongPath[LASTSONG_SIZE];\n char textCursorPos;\n bool *muted_tracks;\n float playamp;\n\n\n Song *song;\n int daemonpid;\n Song *playback;\n unsigned char playback_length;\n unsigned char playback_mark;\n Instrument *selinst;\n}\n\n\/\/Pattern Editor\nnamespace patternedtr\n{\n std::map<int,unsigned int> notemap;\n Pattern *selptrn; \n unsigned char viewporttrack;\n unsigned char viewportrow;\n\n unsigned char maxtracksviewport;\n unsigned char maxrowsviewport;\n\n unsigned char selrow;\n unsigned char seltrack;\n unsigned char seltrackseg;\n unsigned char selorder;\n\n unsigned char selinstrument;\n unsigned char edit_step;\n unsigned char row_underline;\n unsigned char octave;\n unsigned char key;\n unsigned char scalespinner;\n unsigned char scaleconst[CHROMATIC_NOTES];\/\/Scale construction pattern\n unsigned int entryclipboard;\n\n\n \/\/METADATA (Main controls)\n unsigned char metaobjindex;\n bool metaobjedit;\n\n unsigned char selobjmeta;\/\/x\n unsigned char selrowmeta;\/\/y\n\n}\n\n\/\/Instrument Editor\nnamespace instedtr\n{\n unsigned short waveclipboard;\n unsigned short pulseclipboard;\n unsigned short volclipboard;\n\n bool instobjedit;\n unsigned char selinstrow;\n unsigned char selinstobj;\n unsigned short selwavrow;\n unsigned short selpulrow;\n unsigned char selpulseg;\n\n\n unsigned char selwavseg;\n unsigned short viewportwave;\n unsigned short viewportpulse;\n unsigned char viewportvol;\n\n\n unsigned char selvolrow;\n unsigned char selvolseg;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/DONE INITIALIZING\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool editor::validateHexChar(char a)\n{\n if(a >= 'a')\n a -= 32;\n return(a <= '9' && a >= '0' || a >= 'A' && a <= 'F');\n}\n\nbool editor::validate64(char str[2])\n{\n \/\/values < 64 have to start with 0 to 3\n \/\/invalid ascii characters are filterred\n return str[0] < '4' && str[0] >= '0' && validateHexChar(str[1]);\n} \nunsigned char editor::charHex(char c)\n{\n if(c<='9' && c>='0')\n return c-'0';\n if(c >= 'a')\n c -= 32;\n if(c>='A' && c <= 'F')\n return c-55;\n return -1;\n}\n\nchar *editor::byteString(char *string, unsigned char byte)\n{\n unsigned char d = byte % 0x10;\n string[1] = hexnums[d];\n byte \/=0x10;\n d = byte % 0x10;\n string[0] = hexnums[d];\n return string;\n}\nchar *editor::intString(char *string, unsigned int integer, const unsigned int &strlen)\n{\n unsigned char d;\n for(int i = 0; i < strlen; i++)\n {\n d = integer & 0xF;\n string[strlen-i-1]= hexnums[d];\n integer >>= 4;\n }\n return string;\n}\n\nchar *editor::shortString(char *string, unsigned short shrt, const unsigned int &strlen)\n{\n unsigned char d;\n for(int i = 0; i < strlen; i++)\n {\n d = shrt & 0xF;\n string[strlen-i-1]= hexnums[d];\n shrt >>= 4;\n }\n return string;\n}\n\nunsigned char editor::parseHexChar(char str[2])\n{\n \/\/values < 64 have to start with 0 to 3\n \/\/invalid ascii characters are filterred\n unsigned char out = charHex(str[0])*0x10;\n out + charHex(str[1]);\n return out;\n}\n\n\nvoid editor::inform(const char *message)\n{\n int length = strlen(message);\n int msglen = length;\n if(length < 64)\n length = 64;\n attroff(-1);\n attron(COLOR_PAIR(patternedtr::COL_META_SSU));\n mvprintw(3,4,\"+--------------------------------------------------------------+\",stdscr);\n\n mvprintw(8,4,\"+--------------------------------------------------------------+\",stdscr);\n attroff(-1);\n attron(COLOR_PAIR(patternedtr::COL_META_US));\n mvprintw(4,4,\" \",stdscr);\n mvprintw(5,4,message,stdscr);\n if(msglen < 64)\n for(int i = msglen; i < 64; i++)\n mvprintw(5, 4+i, \" \", stdscr);\n mvprintw(6,4,\" \",stdscr);\n mvprintw(7,4,\" Press [Space] to continue \",stdscr);\n editor::lastwin = editor::dialog;\n int ch;\n while((ch=getch()) != ' ' && ch != '\\n');\n return;\n}\nbool editor::confirm(const char *message)\n{\n int length = strlen(message);\n int msglen = length;\n if(length < 64)\n length = 64;\n attroff(-1);\n attron(COLOR_PAIR(patternedtr::COL_META_SSU));\n \/\/modify these to output to the length\n mvprintw(3,4,\"+--------------------------------------------------------------+\",stdscr);\n mvprintw(8,4,\"+--------------------------------------------------------------+\",stdscr);\n attroff(-1);\n attron(COLOR_PAIR(patternedtr::COL_META_US));\n mvprintw(4,4,\" \",stdscr);\n mvprintw(5,4,message,stdscr);\n if(msglen < 64)\n for(int i = msglen; i < 64; i++)\n mvprintw(5, 4+i, \" \", stdscr);\n mvprintw(6,4,\" \",stdscr);\n mvprintw(7,4,\" Are you sure? [y\/n] \",stdscr);\n editor::lastwin = editor::dialog;\n\n int ch;\n while((ch=getch()) != 'y' && ch != 'n' && ch != 27);\n if(ch == 'y')\n return true;\n return false;\n}\nvoid editor::displayAbout()\n{\n attroff(-1);\n attron(COLOR_PAIR(patternedtr::COL_META_SSU));\n mvprintw(3,4, \"+---------------------------------+\",stdscr);\n mvprintw(15,4,\"+---------------------------------+\",stdscr);\n attroff(-1);\n attron(COLOR_PAIR(patternedtr::COL_META_US));\n mvprintw(4,4, \" Welcome to PLEBTracker! v1 \",stdscr);\n mvprintw(5,4, \" \",stdscr);\n mvprintw(6,4, \"Press TAB to switch windows \",stdscr);\n mvprintw(7,4, \"Press : to open the command bar \",stdscr);\n mvprintw(8,4, \" \",stdscr);\n mvprintw(9,4, \"To view a list of commands, see \",stdscr);\n mvprintw(10,4,\" the man page for plebtrkraw(1) \",stdscr);\n mvprintw(11,4,\" \",stdscr);\n mvprintw(12,4,\" -Dan Frazier \",stdscr);\n mvprintw(13,4,\" \",stdscr);\n mvprintw(14,4,\" Press [Space] to continue \",stdscr);\n editor::lastwin = editor::dialog;\n int ch;\n while((ch=getch()) != ' ' && ch != '\\n');\n return;\n}\n\nvoid editor::setPID(int PID)\n{\n \/\/Prepare the paths that the daemon will use\n std::string playpath(\"\/var\/tmp\/plebtrk\/\");\n if(PID)\n playpath += std::to_string(PID);\n std::string signalpath(playpath + \"signal\");\n playpath+= \"playback.plb\";\n\n editor::playbackpath = new char[playpath.length()];\n for(int i = 0; i < playpath.length(); i++)\n editor::playbackpath[i]=playpath.at(i);\n\n editor::signalpath = new char[signalpath.length()];\n for(int i = 0; i < signalpath.length(); i++)\n editor::signalpath[i]=signalpath.at(i);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <common\/buffer.h>\n#include <common\/test.h>\n\n#define\tFILL_BYTE\t(0xa5)\n#define\tFILL_NUMBER\t(1024)\n#define\tFILL_LENGTH\t(242)\n\nint\nmain(void)\n{\n\tTestGroup g(\"\/test\/buffer\/cut1\", \"Buffer::cut #1\");\n\n\tunsigned n;\n\tfor (n = 1; n < 12; n++) {\n\t\tBuffer big;\n\n\t\tbig.append(\"Hello, \");\n\t\tsize_t headerlen = big.length();\n\n\t\tuint8_t fill[n * FILL_LENGTH];\n\t\tunsigned i;\n\t\tfor (i = 0; i < sizeof fill; i++) {\n\t\t\tfill[i] = FILL_BYTE;\n\t\t}\n\n\t\tfor (i = 0; i < FILL_NUMBER; i++) {\n\t\t\tbig.append(fill, sizeof fill);\n\t\t}\n\n\t\tbig.append(\"world!\\n\");\n\n\t\t{\n\t\t\tTest _(g, \"Cut fill bytes.\");\n\n\t\t\tBuffer small(big);\n\t\t\tsmall.cut(headerlen, FILL_NUMBER * sizeof fill);\n\t\t\tif (small.equal(\"Hello, world!\\n\"))\n\t\t\t\t_.pass();\n\t\t}\n\n\t\t{\n\t\t\tTest _(g, \"Proxy skip and trim.\");\n\n\t\t\tbig.cut(0, headerlen);\n\t\t\tbig.cut(FILL_NUMBER * sizeof fill,\n\t\t\t\tbig.length() - (FILL_NUMBER * sizeof fill));\n\t\t\tif (big.length() == FILL_NUMBER * sizeof fill)\n\t\t\t\t_.pass();\n\t\t}\n\n\t\t{\n\t\t\tTest _(g, \"Correct fill byte checksum.\");\n\n\t\t\tuint64_t sum = 0;\n\t\t\twhile (!big.empty()) {\n\t\t\t\tsum += big.peek();\n\t\t\t\tbig.skip(1);\n\t\t\t}\n\n\t\t\tsum \/= FILL_NUMBER * sizeof fill * FILL_BYTE;\n\t\t\tif (sum == 1)\n\t\t\t\t_.pass();\n\t\t}\n\t}\n\n\treturn (0);\n}\n<commit_msg>Do a faster checksum.<commit_after>#include <common\/buffer.h>\n#include <common\/test.h>\n\n#define\tFILL_BYTE\t(0xa5)\n#define\tFILL_NUMBER\t(1024)\n#define\tFILL_LENGTH\t(242)\n\nint\nmain(void)\n{\n\tTestGroup g(\"\/test\/buffer\/cut1\", \"Buffer::cut #1\");\n\n\tunsigned n;\n\tfor (n = 1; n < 12; n++) {\n\t\tBuffer big;\n\n\t\tbig.append(\"Hello, \");\n\t\tsize_t headerlen = big.length();\n\n\t\tuint8_t fill[n * FILL_LENGTH];\n\t\tunsigned i;\n\t\tfor (i = 0; i < sizeof fill; i++) {\n\t\t\tfill[i] = FILL_BYTE;\n\t\t}\n\n\t\tfor (i = 0; i < FILL_NUMBER; i++) {\n\t\t\tbig.append(fill, sizeof fill);\n\t\t}\n\n\t\tbig.append(\"world!\\n\");\n\n\t\t{\n\t\t\tTest _(g, \"Cut fill bytes.\");\n\n\t\t\tBuffer small(big);\n\t\t\tsmall.cut(headerlen, FILL_NUMBER * sizeof fill);\n\t\t\tif (small.equal(\"Hello, world!\\n\"))\n\t\t\t\t_.pass();\n\t\t}\n\n\t\t{\n\t\t\tTest _(g, \"Proxy skip and trim.\");\n\n\t\t\tbig.cut(0, headerlen);\n\t\t\tbig.cut(FILL_NUMBER * sizeof fill,\n\t\t\t\tbig.length() - (FILL_NUMBER * sizeof fill));\n\t\t\tif (big.length() == FILL_NUMBER * sizeof fill)\n\t\t\t\t_.pass();\n\t\t}\n\n\t\t{\n\t\t\tTest _(g, \"Correct fill byte checksum.\");\n\n\t\t\tuint64_t sum = 0;\n\t\t\tBuffer::SegmentIterator iter = big.segments();\n\t\t\twhile (!iter.end()) {\n\t\t\t\tconst BufferSegment *seg = *iter;\n\t\t\t\tconst uint8_t *p;\n\t\t\t\tconst uint8_t *q = seg->end();\n\t\t\t\tfor (p = seg->data(); p < q; p++)\n\t\t\t\t\tsum += *p;\n\t\t\t\titer.next();\n\t\t\t}\n\t\t\tbig.clear();\n\n\t\t\tsum \/= FILL_NUMBER * sizeof fill * FILL_BYTE;\n\t\t\tif (sum == 1)\n\t\t\t\t_.pass();\n\t\t}\n\t}\n\n\treturn (0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <string.h>\n#include \"cmm_conn_bootstrapper.h\"\n#include \"cmm_socket.private.h\"\n#include \"csocket_mapping.h\"\n#include \"debug.h\"\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <errno.h>\n\nConnBootstrapper::ConnBootstrapper(CMMSocketImpl *sk_,\n int bootstrap_sock_,\n const struct sockaddr *remote_addr_,\n socklen_t addrlen_)\n : sk(sk_), bootstrap_sock(bootstrap_sock_), status_(EINPROGRESS),\n addrlen(addrlen_)\n{\n remote_addr = new char[addrlen];\n memcpy(remote_addr, remote_addr_, addrlen);\n}\n\nConnBootstrapper::~ConnBootstrapper()\n{\n delete [] remote_addr;\n}\n\nvoid\nConnBootstrapper::stop()\n{\n dbgprintf(\"Aborting bootstrapper for multisocket %d\\n\",\n sk->sock);\n shutdown(bootstrap_sock, SHUT_RDWR);\n}\n\nvoid\nConnBootstrapper::Finish()\n{\n close(bootstrap_sock);\n dbgprintf(\"Exiting.\\n\");\n}\n\n\nvoid ConnBootstrapper::Run()\n{\n char name[MAX_NAME_LEN+1];\n memset(name, 0, MAX_NAME_LEN+1);\n snprintf(name, MAX_NAME_LEN, \"Bootstrapper %d\", sk->sock);\n set_thread_name(name);\n\n PthreadScopedRWLock sock_lock(&sk->my_lock, true);\n \n if (sk->non_blocking) {\n detach();\n }\n\n try {\n if (bootstrap_sock != -1) {\n \/* we are accepting a connection *\/\n dbgprintf(\"Accepting connection; using socket %d \"\n \"to bootstrap\\n\", bootstrap_sock);\n sk->recv_remote_listeners(bootstrap_sock);\n sk->send_local_listeners(bootstrap_sock);\n } else {\n \/* we are connecting *\/\n assert(remote_addr);\n \n bootstrap_sock = socket(sk->sock_family, sk->sock_type, \n sk->sock_protocol);\n if (bootstrap_sock < 0) {\n return;\n }\n \n struct sockaddr *addr = (struct sockaddr *)remote_addr;\n int rc = connect(bootstrap_sock, addr, addrlen);\n if (rc < 0) {\n perror(\"connect\");\n status_ = errno;\n dbgprintf(\"Error connecting bootstrap socket\\n\");\n throw rc;\n }\n \n dbgprintf(\"Initiating connection; using socket %d \"\n \"to bootstrap\\n\", bootstrap_sock);\n sk->send_local_listeners(bootstrap_sock);\n sk->recv_remote_listeners(bootstrap_sock);\n }\n\n \/\/ no errors; must have succeeded\n status_ = 0;\n } catch (int error_rc) {\n if (status_ != EINPROGRESS) {\n status_ = ECONNREFUSED;\n }\n \/\/ fall through so write-select returns\n }\n\n char ch = 42;\n int rc = write(sk->write_ready_pipe[1], &ch, 1);\n assert(rc == 1);\n}\n\nbool \nConnBootstrapper::succeeded()\n{\n return status_ == 0;\n}\n\nbool\nConnBootstrapper::done()\n{\n return status_ != EINPROGRESS;\n}\n\nint\nConnBootstrapper::status()\n{\n return status_;\n}\n<commit_msg>Fixed non_blocking\/is_non_blocking issues<commit_after>#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <string.h>\n#include \"cmm_conn_bootstrapper.h\"\n#include \"cmm_socket.private.h\"\n#include \"csocket_mapping.h\"\n#include \"debug.h\"\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <errno.h>\n\nConnBootstrapper::ConnBootstrapper(CMMSocketImpl *sk_,\n int bootstrap_sock_,\n const struct sockaddr *remote_addr_,\n socklen_t addrlen_)\n : sk(sk_), bootstrap_sock(bootstrap_sock_), status_(EINPROGRESS),\n addrlen(addrlen_)\n{\n remote_addr = new char[addrlen];\n memcpy(remote_addr, remote_addr_, addrlen);\n}\n\nConnBootstrapper::~ConnBootstrapper()\n{\n delete [] remote_addr;\n}\n\nvoid\nConnBootstrapper::stop()\n{\n dbgprintf(\"Aborting bootstrapper for multisocket %d\\n\",\n sk->sock);\n shutdown(bootstrap_sock, SHUT_RDWR);\n}\n\nvoid\nConnBootstrapper::Finish()\n{\n close(bootstrap_sock);\n dbgprintf(\"Exiting.\\n\");\n}\n\n\nvoid ConnBootstrapper::Run()\n{\n char name[MAX_NAME_LEN+1];\n memset(name, 0, MAX_NAME_LEN+1);\n snprintf(name, MAX_NAME_LEN, \"Bootstrapper %d\", sk->sock);\n set_thread_name(name);\n\n PthreadScopedRWLock sock_lock(&sk->my_lock, true);\n \n if (sk->is_non_blocking()) {\n detach();\n }\n\n try {\n if (bootstrap_sock != -1) {\n \/* we are accepting a connection *\/\n dbgprintf(\"Accepting connection; using socket %d \"\n \"to bootstrap\\n\", bootstrap_sock);\n sk->recv_remote_listeners(bootstrap_sock);\n sk->send_local_listeners(bootstrap_sock);\n } else {\n \/* we are connecting *\/\n assert(remote_addr);\n \n bootstrap_sock = socket(sk->sock_family, sk->sock_type, \n sk->sock_protocol);\n if (bootstrap_sock < 0) {\n dbgprintf(\"Error creating bootstrap socket: %s\\n\",\n strerror(errno));\n return;\n }\n \n struct sockaddr *addr = (struct sockaddr *)remote_addr;\n int rc = connect(bootstrap_sock, addr, addrlen);\n if (rc < 0) {\n status_ = errno;\n dbgprintf(\"Error connecting bootstrap socket: %s\\n\",\n strerror(errno));\n throw rc;\n }\n \n dbgprintf(\"Initiating connection; using socket %d \"\n \"to bootstrap\\n\", bootstrap_sock);\n sk->send_local_listeners(bootstrap_sock);\n sk->recv_remote_listeners(bootstrap_sock);\n }\n\n \/\/ no errors; must have succeeded\n status_ = 0;\n } catch (int error_rc) {\n if (status_ != EINPROGRESS) {\n status_ = ECONNREFUSED;\n }\n \/\/ fall through so write-select returns\n }\n\n char ch = 42;\n int rc = write(sk->write_ready_pipe[1], &ch, 1);\n assert(rc == 1);\n}\n\nbool \nConnBootstrapper::succeeded()\n{\n return status_ == 0;\n}\n\nbool\nConnBootstrapper::done()\n{\n return status_ != EINPROGRESS;\n}\n\nint\nConnBootstrapper::status()\n{\n return status_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018 The Android Open Source Project\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#include \"src\/profiling\/memory\/unwinding.h\"\n\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include <unwindstack\/MachineArm.h>\n#include <unwindstack\/MachineArm64.h>\n#include <unwindstack\/MachineMips.h>\n#include <unwindstack\/MachineMips64.h>\n#include <unwindstack\/MachineX86.h>\n#include <unwindstack\/MachineX86_64.h>\n#include <unwindstack\/Maps.h>\n#include <unwindstack\/Memory.h>\n#include <unwindstack\/Regs.h>\n#include <unwindstack\/RegsArm.h>\n#include <unwindstack\/RegsArm64.h>\n#include <unwindstack\/RegsMips.h>\n#include <unwindstack\/RegsMips64.h>\n#include <unwindstack\/RegsX86.h>\n#include <unwindstack\/RegsX86_64.h>\n#include <unwindstack\/Unwinder.h>\n#include <unwindstack\/UserArm.h>\n#include <unwindstack\/UserArm64.h>\n#include <unwindstack\/UserMips.h>\n#include <unwindstack\/UserMips64.h>\n#include <unwindstack\/UserX86.h>\n#include <unwindstack\/UserX86_64.h>\n\n#include <procinfo\/process_map.h>\n\n#include \"perfetto\/base\/file_utils.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/base\/scoped_file.h\"\n#include \"perfetto\/base\/string_utils.h\"\n#include \"perfetto\/base\/task_runner.h\"\n#include \"perfetto\/base\/thread_task_runner.h\"\n#include \"src\/profiling\/memory\/wire_protocol.h\"\n\nnamespace perfetto {\nnamespace profiling {\nnamespace {\n\nsize_t kMaxFrames = 1000;\n\n#pragma GCC diagnostic push\n\/\/ We do not care about deterministic destructor order.\n#pragma GCC diagnostic ignored \"-Wglobal-constructors\"\n#pragma GCC diagnostic ignored \"-Wexit-time-destructors\"\nstatic std::vector<std::string> kSkipMaps{\"heapprofd_client.so\"};\n#pragma GCC diagnostic pop\n\nstd::unique_ptr<unwindstack::Regs> CreateFromRawData(unwindstack::ArchEnum arch,\n void* raw_data) {\n std::unique_ptr<unwindstack::Regs> ret;\n \/\/ unwindstack::RegsX::Read returns a raw ptr which we are expected to free.\n switch (arch) {\n case unwindstack::ARCH_X86:\n ret.reset(unwindstack::RegsX86::Read(raw_data));\n break;\n case unwindstack::ARCH_X86_64:\n ret.reset(unwindstack::RegsX86_64::Read(raw_data));\n break;\n case unwindstack::ARCH_ARM:\n ret.reset(unwindstack::RegsArm::Read(raw_data));\n break;\n case unwindstack::ARCH_ARM64:\n ret.reset(unwindstack::RegsArm64::Read(raw_data));\n break;\n case unwindstack::ARCH_MIPS:\n ret.reset(unwindstack::RegsMips::Read(raw_data));\n break;\n case unwindstack::ARCH_MIPS64:\n ret.reset(unwindstack::RegsMips64::Read(raw_data));\n break;\n case unwindstack::ARCH_UNKNOWN:\n ret.reset(nullptr);\n break;\n }\n return ret;\n}\n\n\/\/ Behaves as a pread64, emulating it if not already exposed by the standard\n\/\/ library. Safe to use on 32bit platforms for addresses with the top bit set.\n\/\/ Clobbers the |fd| seek position if emulating.\nssize_t ReadAtOffsetClobberSeekPos(int fd,\n void* buf,\n size_t count,\n uint64_t addr) {\n#ifdef __BIONIC__\n return pread64(fd, buf, count, static_cast<off64_t>(addr));\n#else\n if (lseek64(fd, static_cast<off64_t>(addr), SEEK_SET) == -1)\n return -1;\n return read(fd, buf, count);\n#endif\n}\n\n} \/\/ namespace\n\nStackOverlayMemory::StackOverlayMemory(std::shared_ptr<unwindstack::Memory> mem,\n uint64_t sp,\n uint8_t* stack,\n size_t size)\n : mem_(std::move(mem)), sp_(sp), stack_end_(sp + size), stack_(stack) {}\n\nsize_t StackOverlayMemory::Read(uint64_t addr, void* dst, size_t size) {\n if (addr >= sp_ && addr + size <= stack_end_ && addr + size > sp_) {\n size_t offset = static_cast<size_t>(addr - sp_);\n memcpy(dst, stack_ + offset, size);\n return size;\n }\n\n return mem_->Read(addr, dst, size);\n}\n\nFDMemory::FDMemory(base::ScopedFile mem_fd) : mem_fd_(std::move(mem_fd)) {}\n\nsize_t FDMemory::Read(uint64_t addr, void* dst, size_t size) {\n ssize_t rd = ReadAtOffsetClobberSeekPos(*mem_fd_, dst, size, addr);\n if (rd == -1) {\n PERFETTO_DPLOG(\"read of %zu at offset %\" PRIu64, size, addr);\n return 0;\n }\n return static_cast<size_t>(rd);\n}\n\nFileDescriptorMaps::FileDescriptorMaps(base::ScopedFile fd)\n : fd_(std::move(fd)) {}\n\nbool FileDescriptorMaps::Parse() {\n \/\/ If the process has already exited, lseek or ReadFileDescriptor will\n \/\/ return false.\n if (lseek(*fd_, 0, SEEK_SET) == -1)\n return false;\n\n std::string content;\n if (!base::ReadFileDescriptor(*fd_, &content))\n return false;\n return android::procinfo::ReadMapFileContent(\n &content[0], [&](uint64_t start, uint64_t end, uint16_t flags,\n uint64_t pgoff, ino_t, const char* name) {\n \/\/ Mark a device map in \/dev\/ and not in \/dev\/ashmem\/ specially.\n if (strncmp(name, \"\/dev\/\", 5) == 0 &&\n strncmp(name + 5, \"ashmem\/\", 7) != 0) {\n flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;\n }\n maps_.emplace_back(\n new unwindstack::MapInfo(nullptr, start, end, pgoff, flags, name));\n });\n}\n\nvoid FileDescriptorMaps::Reset() {\n maps_.clear();\n}\n\nbool DoUnwind(WireMessage* msg, UnwindingMetadata* metadata, AllocRecord* out) {\n AllocMetadata* alloc_metadata = msg->alloc_header;\n std::unique_ptr<unwindstack::Regs> regs(\n CreateFromRawData(alloc_metadata->arch, alloc_metadata->register_data));\n if (regs == nullptr) {\n PERFETTO_DLOG(\"Unable to construct unwindstack::Regs\");\n unwindstack::FrameData frame_data{};\n frame_data.function_name = \"ERROR READING REGISTERS\";\n frame_data.map_name = \"ERROR\";\n\n out->frames.emplace_back(frame_data, \"\");\n return false;\n }\n uint8_t* stack = reinterpret_cast<uint8_t*>(msg->payload);\n std::shared_ptr<unwindstack::Memory> mems =\n std::make_shared<StackOverlayMemory>(metadata->fd_mem,\n alloc_metadata->stack_pointer, stack,\n msg->payload_size);\n\n unwindstack::Unwinder unwinder(kMaxFrames, &metadata->maps, regs.get(), mems);\n#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)\n unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());\n unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());\n#endif\n \/\/ Surpress incorrect \"variable may be uninitialized\" error for if condition\n \/\/ after this loop. error_code = LastErrorCode gets run at least once.\n uint8_t error_code = 0;\n for (int attempt = 0; attempt < 2; ++attempt) {\n if (attempt > 0) {\n PERFETTO_DLOG(\"Reparsing maps\");\n metadata->ReparseMaps();\n#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)\n unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());\n unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());\n#endif\n }\n unwinder.Unwind(&kSkipMaps, nullptr);\n error_code = unwinder.LastErrorCode();\n if (error_code != unwindstack::ERROR_INVALID_MAP)\n break;\n }\n std::vector<unwindstack::FrameData> frames = unwinder.ConsumeFrames();\n for (unwindstack::FrameData& fd : frames) {\n std::string build_id;\n if (fd.map_name != \"\") {\n unwindstack::MapInfo* map_info = metadata->maps.Find(fd.pc);\n if (map_info)\n build_id = map_info->GetBuildID();\n }\n\n out->frames.emplace_back(std::move(fd), std::move(build_id));\n }\n\n if (error_code != 0) {\n PERFETTO_DLOG(\"Unwinding error %\" PRIu8, error_code);\n unwindstack::FrameData frame_data{};\n frame_data.function_name = \"ERROR \" + std::to_string(error_code);\n frame_data.map_name = \"ERROR\";\n\n out->frames.emplace_back(frame_data, \"\");\n }\n\n return true;\n}\n\nvoid UnwindingWorker::OnDisconnect(base::UnixSocket* self) {\n \/\/ TODO(fmayer): Maybe try to drain shmem one last time.\n auto it = client_data_.find(self->peer_pid());\n if (it == client_data_.end()) {\n PERFETTO_DFATAL(\"Disconnected unexpecter socket.\");\n return;\n }\n ClientData& client_data = it->second;\n DataSourceInstanceID ds_id = client_data.data_source_instance_id;\n client_data_.erase(it);\n delegate_->PostSocketDisconnected(ds_id, self->peer_pid());\n}\n\nvoid UnwindingWorker::OnDataAvailable(base::UnixSocket* self) {\n \/\/ Drain buffer to clear the notification.\n char recv_buf[1024];\n self->Receive(recv_buf, sizeof(recv_buf));\n\n auto it = client_data_.find(self->peer_pid());\n if (it == client_data_.end()) {\n PERFETTO_DFATAL(\"Unexpected data.\");\n return;\n }\n\n ClientData& client_data = it->second;\n SharedRingBuffer& shmem = client_data.shmem;\n SharedRingBuffer::Buffer buf;\n\n for (;;) {\n \/\/ TODO(fmayer): Allow spinlock acquisition to fail and repost Task if it\n \/\/ did.\n buf = shmem.BeginRead();\n if (!buf)\n break;\n HandleBuffer(buf, &client_data.metadata,\n client_data.data_source_instance_id,\n client_data.sock->peer_pid(), delegate_);\n shmem.EndRead(std::move(buf));\n }\n}\n\n\/\/ static\nvoid UnwindingWorker::HandleBuffer(const SharedRingBuffer::Buffer& buf,\n UnwindingMetadata* unwinding_metadata,\n DataSourceInstanceID data_source_instance_id,\n pid_t peer_pid,\n Delegate* delegate) {\n WireMessage msg;\n \/\/ TODO(fmayer): standardise on char* or uint8_t*.\n \/\/ char* has stronger guarantees regarding aliasing.\n \/\/ see https:\/\/timsong-cpp.github.io\/cppwp\/n3337\/basic.lval#10.8\n if (!ReceiveWireMessage(reinterpret_cast<char*>(buf.data), buf.size, &msg)) {\n PERFETTO_DFATAL(\"Failed to receive wire message.\");\n return;\n }\n\n if (msg.record_type == RecordType::Malloc) {\n AllocRecord rec;\n rec.alloc_metadata = *msg.alloc_header;\n rec.pid = peer_pid;\n rec.data_source_instance_id = data_source_instance_id;\n DoUnwind(&msg, unwinding_metadata, &rec);\n delegate->PostAllocRecord(std::move(rec));\n } else if (msg.record_type == RecordType::Free) {\n FreeRecord rec;\n rec.pid = peer_pid;\n rec.data_source_instance_id = data_source_instance_id;\n \/\/ We need to copy this, so we can return the memory to the shmem buffer.\n memcpy(&rec.free_batch, msg.free_header, sizeof(*msg.free_header));\n delegate->PostFreeRecord(std::move(rec));\n } else {\n PERFETTO_DFATAL(\"Invalid record type.\");\n }\n}\n\nvoid UnwindingWorker::PostHandoffSocket(HandoffData handoff_data) {\n \/\/ Even with C++14, this cannot be moved, as std::function has to be\n \/\/ copyable, which HandoffData is not.\n HandoffData* raw_data = new HandoffData(std::move(handoff_data));\n \/\/ We do not need to use a WeakPtr here because the task runner will not\n \/\/ outlive its UnwindingWorker.\n thread_task_runner_.get()->PostTask([this, raw_data] {\n HandoffData data = std::move(*raw_data);\n delete raw_data;\n HandleHandoffSocket(std::move(data));\n });\n}\n\nvoid UnwindingWorker::HandleHandoffSocket(HandoffData handoff_data) {\n auto sock = base::UnixSocket::AdoptConnected(\n handoff_data.sock.ReleaseFd(), this, this->thread_task_runner_.get(),\n base::SockType::kStream);\n pid_t peer_pid = sock->peer_pid();\n\n UnwindingMetadata metadata(peer_pid,\n std::move(handoff_data.fds[kHandshakeMaps]),\n std::move(handoff_data.fds[kHandshakeMem]));\n ClientData client_data{\n handoff_data.data_source_instance_id, std::move(sock),\n std::move(metadata), std::move(handoff_data.shmem),\n };\n client_data_.emplace(peer_pid, std::move(client_data));\n}\n\nvoid UnwindingWorker::PostDisconnectSocket(pid_t pid) {\n \/\/ We do not need to use a WeakPtr here because the task runner will not\n \/\/ outlive its UnwindingWorker.\n thread_task_runner_.get()->PostTask(\n [this, pid] { HandleDisconnectSocket(pid); });\n}\n\nvoid UnwindingWorker::HandleDisconnectSocket(pid_t pid) {\n client_data_.erase(pid);\n}\n\nUnwindingWorker::Delegate::~Delegate() = default;\n\n} \/\/ namespace profiling\n} \/\/ namespace perfetto\n<commit_msg>heapprofd: fix unwinding of native frames in apk-embedded native libs am: f7104562e5 am: 19d8dd7f39 am: 11a7e09118<commit_after>\/*\n * Copyright (C) 2018 The Android Open Source Project\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#include \"src\/profiling\/memory\/unwinding.h\"\n\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include <unwindstack\/MachineArm.h>\n#include <unwindstack\/MachineArm64.h>\n#include <unwindstack\/MachineMips.h>\n#include <unwindstack\/MachineMips64.h>\n#include <unwindstack\/MachineX86.h>\n#include <unwindstack\/MachineX86_64.h>\n#include <unwindstack\/Maps.h>\n#include <unwindstack\/Memory.h>\n#include <unwindstack\/Regs.h>\n#include <unwindstack\/RegsArm.h>\n#include <unwindstack\/RegsArm64.h>\n#include <unwindstack\/RegsMips.h>\n#include <unwindstack\/RegsMips64.h>\n#include <unwindstack\/RegsX86.h>\n#include <unwindstack\/RegsX86_64.h>\n#include <unwindstack\/Unwinder.h>\n#include <unwindstack\/UserArm.h>\n#include <unwindstack\/UserArm64.h>\n#include <unwindstack\/UserMips.h>\n#include <unwindstack\/UserMips64.h>\n#include <unwindstack\/UserX86.h>\n#include <unwindstack\/UserX86_64.h>\n\n#include <procinfo\/process_map.h>\n\n#include \"perfetto\/base\/file_utils.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/base\/scoped_file.h\"\n#include \"perfetto\/base\/string_utils.h\"\n#include \"perfetto\/base\/task_runner.h\"\n#include \"perfetto\/base\/thread_task_runner.h\"\n#include \"src\/profiling\/memory\/wire_protocol.h\"\n\nnamespace perfetto {\nnamespace profiling {\nnamespace {\n\nsize_t kMaxFrames = 1000;\n\n#pragma GCC diagnostic push\n\/\/ We do not care about deterministic destructor order.\n#pragma GCC diagnostic ignored \"-Wglobal-constructors\"\n#pragma GCC diagnostic ignored \"-Wexit-time-destructors\"\nstatic std::vector<std::string> kSkipMaps{\"heapprofd_client.so\"};\n#pragma GCC diagnostic pop\n\nstd::unique_ptr<unwindstack::Regs> CreateFromRawData(unwindstack::ArchEnum arch,\n void* raw_data) {\n std::unique_ptr<unwindstack::Regs> ret;\n \/\/ unwindstack::RegsX::Read returns a raw ptr which we are expected to free.\n switch (arch) {\n case unwindstack::ARCH_X86:\n ret.reset(unwindstack::RegsX86::Read(raw_data));\n break;\n case unwindstack::ARCH_X86_64:\n ret.reset(unwindstack::RegsX86_64::Read(raw_data));\n break;\n case unwindstack::ARCH_ARM:\n ret.reset(unwindstack::RegsArm::Read(raw_data));\n break;\n case unwindstack::ARCH_ARM64:\n ret.reset(unwindstack::RegsArm64::Read(raw_data));\n break;\n case unwindstack::ARCH_MIPS:\n ret.reset(unwindstack::RegsMips::Read(raw_data));\n break;\n case unwindstack::ARCH_MIPS64:\n ret.reset(unwindstack::RegsMips64::Read(raw_data));\n break;\n case unwindstack::ARCH_UNKNOWN:\n ret.reset(nullptr);\n break;\n }\n return ret;\n}\n\n\/\/ Behaves as a pread64, emulating it if not already exposed by the standard\n\/\/ library. Safe to use on 32bit platforms for addresses with the top bit set.\n\/\/ Clobbers the |fd| seek position if emulating.\nssize_t ReadAtOffsetClobberSeekPos(int fd,\n void* buf,\n size_t count,\n uint64_t addr) {\n#ifdef __BIONIC__\n return pread64(fd, buf, count, static_cast<off64_t>(addr));\n#else\n if (lseek64(fd, static_cast<off64_t>(addr), SEEK_SET) == -1)\n return -1;\n return read(fd, buf, count);\n#endif\n}\n\n} \/\/ namespace\n\nStackOverlayMemory::StackOverlayMemory(std::shared_ptr<unwindstack::Memory> mem,\n uint64_t sp,\n uint8_t* stack,\n size_t size)\n : mem_(std::move(mem)), sp_(sp), stack_end_(sp + size), stack_(stack) {}\n\nsize_t StackOverlayMemory::Read(uint64_t addr, void* dst, size_t size) {\n if (addr >= sp_ && addr + size <= stack_end_ && addr + size > sp_) {\n size_t offset = static_cast<size_t>(addr - sp_);\n memcpy(dst, stack_ + offset, size);\n return size;\n }\n\n return mem_->Read(addr, dst, size);\n}\n\nFDMemory::FDMemory(base::ScopedFile mem_fd) : mem_fd_(std::move(mem_fd)) {}\n\nsize_t FDMemory::Read(uint64_t addr, void* dst, size_t size) {\n ssize_t rd = ReadAtOffsetClobberSeekPos(*mem_fd_, dst, size, addr);\n if (rd == -1) {\n PERFETTO_DPLOG(\"read of %zu at offset %\" PRIu64, size, addr);\n return 0;\n }\n return static_cast<size_t>(rd);\n}\n\nFileDescriptorMaps::FileDescriptorMaps(base::ScopedFile fd)\n : fd_(std::move(fd)) {}\n\nbool FileDescriptorMaps::Parse() {\n \/\/ If the process has already exited, lseek or ReadFileDescriptor will\n \/\/ return false.\n if (lseek(*fd_, 0, SEEK_SET) == -1)\n return false;\n\n std::string content;\n if (!base::ReadFileDescriptor(*fd_, &content))\n return false;\n return android::procinfo::ReadMapFileContent(\n &content[0], [&](uint64_t start, uint64_t end, uint16_t flags,\n uint64_t pgoff, ino_t, const char* name) {\n \/\/ Mark a device map in \/dev\/ and not in \/dev\/ashmem\/ specially.\n if (strncmp(name, \"\/dev\/\", 5) == 0 &&\n strncmp(name + 5, \"ashmem\/\", 7) != 0) {\n flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;\n }\n unwindstack::MapInfo* prev_map =\n maps_.empty() ? nullptr : maps_.back().get();\n maps_.emplace_back(\n new unwindstack::MapInfo(prev_map, start, end, pgoff, flags, name));\n });\n}\n\nvoid FileDescriptorMaps::Reset() {\n maps_.clear();\n}\n\nbool DoUnwind(WireMessage* msg, UnwindingMetadata* metadata, AllocRecord* out) {\n AllocMetadata* alloc_metadata = msg->alloc_header;\n std::unique_ptr<unwindstack::Regs> regs(\n CreateFromRawData(alloc_metadata->arch, alloc_metadata->register_data));\n if (regs == nullptr) {\n PERFETTO_DLOG(\"Unable to construct unwindstack::Regs\");\n unwindstack::FrameData frame_data{};\n frame_data.function_name = \"ERROR READING REGISTERS\";\n frame_data.map_name = \"ERROR\";\n\n out->frames.emplace_back(frame_data, \"\");\n return false;\n }\n uint8_t* stack = reinterpret_cast<uint8_t*>(msg->payload);\n std::shared_ptr<unwindstack::Memory> mems =\n std::make_shared<StackOverlayMemory>(metadata->fd_mem,\n alloc_metadata->stack_pointer, stack,\n msg->payload_size);\n\n unwindstack::Unwinder unwinder(kMaxFrames, &metadata->maps, regs.get(), mems);\n#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)\n unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());\n unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());\n#endif\n \/\/ Surpress incorrect \"variable may be uninitialized\" error for if condition\n \/\/ after this loop. error_code = LastErrorCode gets run at least once.\n uint8_t error_code = 0;\n for (int attempt = 0; attempt < 2; ++attempt) {\n if (attempt > 0) {\n PERFETTO_DLOG(\"Reparsing maps\");\n metadata->ReparseMaps();\n#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)\n unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());\n unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());\n#endif\n }\n unwinder.Unwind(&kSkipMaps, nullptr);\n error_code = unwinder.LastErrorCode();\n if (error_code != unwindstack::ERROR_INVALID_MAP)\n break;\n }\n std::vector<unwindstack::FrameData> frames = unwinder.ConsumeFrames();\n for (unwindstack::FrameData& fd : frames) {\n std::string build_id;\n if (fd.map_name != \"\") {\n unwindstack::MapInfo* map_info = metadata->maps.Find(fd.pc);\n if (map_info)\n build_id = map_info->GetBuildID();\n }\n\n out->frames.emplace_back(std::move(fd), std::move(build_id));\n }\n\n if (error_code != 0) {\n PERFETTO_DLOG(\"Unwinding error %\" PRIu8, error_code);\n unwindstack::FrameData frame_data{};\n frame_data.function_name = \"ERROR \" + std::to_string(error_code);\n frame_data.map_name = \"ERROR\";\n\n out->frames.emplace_back(frame_data, \"\");\n }\n\n return true;\n}\n\nvoid UnwindingWorker::OnDisconnect(base::UnixSocket* self) {\n \/\/ TODO(fmayer): Maybe try to drain shmem one last time.\n auto it = client_data_.find(self->peer_pid());\n if (it == client_data_.end()) {\n PERFETTO_DFATAL(\"Disconnected unexpecter socket.\");\n return;\n }\n ClientData& client_data = it->second;\n DataSourceInstanceID ds_id = client_data.data_source_instance_id;\n client_data_.erase(it);\n delegate_->PostSocketDisconnected(ds_id, self->peer_pid());\n}\n\nvoid UnwindingWorker::OnDataAvailable(base::UnixSocket* self) {\n \/\/ Drain buffer to clear the notification.\n char recv_buf[1024];\n self->Receive(recv_buf, sizeof(recv_buf));\n\n auto it = client_data_.find(self->peer_pid());\n if (it == client_data_.end()) {\n PERFETTO_DFATAL(\"Unexpected data.\");\n return;\n }\n\n ClientData& client_data = it->second;\n SharedRingBuffer& shmem = client_data.shmem;\n SharedRingBuffer::Buffer buf;\n\n for (;;) {\n \/\/ TODO(fmayer): Allow spinlock acquisition to fail and repost Task if it\n \/\/ did.\n buf = shmem.BeginRead();\n if (!buf)\n break;\n HandleBuffer(buf, &client_data.metadata,\n client_data.data_source_instance_id,\n client_data.sock->peer_pid(), delegate_);\n shmem.EndRead(std::move(buf));\n }\n}\n\n\/\/ static\nvoid UnwindingWorker::HandleBuffer(const SharedRingBuffer::Buffer& buf,\n UnwindingMetadata* unwinding_metadata,\n DataSourceInstanceID data_source_instance_id,\n pid_t peer_pid,\n Delegate* delegate) {\n WireMessage msg;\n \/\/ TODO(fmayer): standardise on char* or uint8_t*.\n \/\/ char* has stronger guarantees regarding aliasing.\n \/\/ see https:\/\/timsong-cpp.github.io\/cppwp\/n3337\/basic.lval#10.8\n if (!ReceiveWireMessage(reinterpret_cast<char*>(buf.data), buf.size, &msg)) {\n PERFETTO_DFATAL(\"Failed to receive wire message.\");\n return;\n }\n\n if (msg.record_type == RecordType::Malloc) {\n AllocRecord rec;\n rec.alloc_metadata = *msg.alloc_header;\n rec.pid = peer_pid;\n rec.data_source_instance_id = data_source_instance_id;\n DoUnwind(&msg, unwinding_metadata, &rec);\n delegate->PostAllocRecord(std::move(rec));\n } else if (msg.record_type == RecordType::Free) {\n FreeRecord rec;\n rec.pid = peer_pid;\n rec.data_source_instance_id = data_source_instance_id;\n \/\/ We need to copy this, so we can return the memory to the shmem buffer.\n memcpy(&rec.free_batch, msg.free_header, sizeof(*msg.free_header));\n delegate->PostFreeRecord(std::move(rec));\n } else {\n PERFETTO_DFATAL(\"Invalid record type.\");\n }\n}\n\nvoid UnwindingWorker::PostHandoffSocket(HandoffData handoff_data) {\n \/\/ Even with C++14, this cannot be moved, as std::function has to be\n \/\/ copyable, which HandoffData is not.\n HandoffData* raw_data = new HandoffData(std::move(handoff_data));\n \/\/ We do not need to use a WeakPtr here because the task runner will not\n \/\/ outlive its UnwindingWorker.\n thread_task_runner_.get()->PostTask([this, raw_data] {\n HandoffData data = std::move(*raw_data);\n delete raw_data;\n HandleHandoffSocket(std::move(data));\n });\n}\n\nvoid UnwindingWorker::HandleHandoffSocket(HandoffData handoff_data) {\n auto sock = base::UnixSocket::AdoptConnected(\n handoff_data.sock.ReleaseFd(), this, this->thread_task_runner_.get(),\n base::SockType::kStream);\n pid_t peer_pid = sock->peer_pid();\n\n UnwindingMetadata metadata(peer_pid,\n std::move(handoff_data.fds[kHandshakeMaps]),\n std::move(handoff_data.fds[kHandshakeMem]));\n ClientData client_data{\n handoff_data.data_source_instance_id, std::move(sock),\n std::move(metadata), std::move(handoff_data.shmem),\n };\n client_data_.emplace(peer_pid, std::move(client_data));\n}\n\nvoid UnwindingWorker::PostDisconnectSocket(pid_t pid) {\n \/\/ We do not need to use a WeakPtr here because the task runner will not\n \/\/ outlive its UnwindingWorker.\n thread_task_runner_.get()->PostTask(\n [this, pid] { HandleDisconnectSocket(pid); });\n}\n\nvoid UnwindingWorker::HandleDisconnectSocket(pid_t pid) {\n client_data_.erase(pid);\n}\n\nUnwindingWorker::Delegate::~Delegate() = default;\n\n} \/\/ namespace profiling\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"<commit_before>\/**\nCopyright (c) 2015, Intel Corporation. All rights reserved.\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Intel Corporation nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\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 INTEL CORPORATION BE LIABLE FOR ANY\nDIRECT, 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\nON ANY 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#include <cstdio>\n#include <cstring>\n#include <climits>\n#include <algorithm>\n\n#include <omp.h>\n\n#include \"CSR.hpp\"\n#include \"COO.hpp\"\n#include \"mm_io.h\"\n#include \"Utils.hpp\"\n#include \"MemoryPool.hpp\"\n\n#ifdef LOADIMBA\n#include \"synk\/loadimba.hpp\"\n#else\n#include \"synk\/barrier.hpp\"\n#endif\n\nusing namespace std;\n\n#ifdef LOADIMBA\nextern synk::LoadImba *bar;\n#else\nextern synk::Barrier *bar;\n#endif\n\nnamespace SpMP\n{\n\nbool CSR::useMemoryPool_() const\n{\n return MemoryPool::getSingleton()->contains(rowptr);\n}\n\nCSR::CSR() : rowptr(NULL), colidx(NULL), values(NULL), idiag(NULL), diag(NULL), diagptr(NULL), extptr(NULL), base(0), ownData_(false)\n{\n}\n\nvoid CSR::alloc(int m, int nnz, bool createSeparateDiagData \/*= true*\/)\n{\n this->m = m;\n\n rowptr = MALLOC(int, m + 1);\n colidx = MALLOC(int, nnz);\n values = MALLOC(double, nnz);\n diagptr = MALLOC(int, m);\n\n assert(rowptr != NULL);\n assert(colidx != NULL);\n assert(values != NULL);\n assert(diagptr != NULL);\n\n if (createSeparateDiagData) {\n idiag = MALLOC(double, m);\n diag = MALLOC(double, m);\n assert(idiag != NULL);\n assert(diag != NULL);\n }\n\n ownData_ = true;\n}\n\nCSR::CSR(int m, int n, int nnz, int base \/*=0*\/)\n : base(base)\n{\n this->m=m;\n this->n=n;\n alloc(n, nnz);\n}\n\nCSR::CSR(const char *file, bool forceSymmetric \/*=false*\/, int pad \/*=1*\/)\n : base(0), rowptr(NULL), colidx(NULL), values(NULL), idiag(NULL), diag(NULL), diagptr(NULL), extptr(NULL)\n{\n int m = atoi(file);\n char buf[1024];\n sprintf(buf, \"%d\", m);\n\n int l = strlen(file);\n\n if (!strcmp(buf, file)) {\n generate3D27PtLaplacian(this, m);\n }\n else {\n COO Acoo;\n load_matrix_market((char *)file, Acoo, forceSymmetric, pad);\n\n alloc(Acoo.m, Acoo.nnz);\n\n dcoo2crs(&Acoo, this);\n }\n}\n\nCSR::CSR(int m, int n, int *rowptr, int *colidx, double *values, int base \/*=0*\/) :\n m(m), n(n), rowptr(rowptr), colidx(colidx), values(values), ownData_(false), idiag(NULL), diag(NULL), extptr(NULL)\n{\n diagptr = MALLOC(int, m);\n#pragma omp parallel for\n for (int i = 0; i < m; ++i) {\n for (int j = rowptr[i] - base; j < rowptr[i + 1] - base; ++j) {\n if (colidx[j] - base == i) {\n diagptr[i] = j + base;\n }\n }\n }\n}\n\nvoid CSR::dealloc()\n{\n if (useMemoryPool_()) {\n \/\/ a large single contiguous chunk is allocated to\n \/\/ buffers except rowptr and colidx.\n rowptr = NULL;\n extptr = NULL;\n colidx = NULL;\n values = NULL;\n idiag = NULL;\n diag = NULL;\n diagptr = NULL;\n }\n else {\n if (ownData_) {\n FREE(rowptr);\n FREE(extptr);\n FREE(colidx);\n FREE(values);\n }\n\n FREE(idiag);\n FREE(diag);\n FREE(diagptr);\n }\n}\n\nCSR::~CSR()\n{\n dealloc();\n}\n\nbool CSR::isSymmetric(bool checkValues \/*=true*\/, bool printFirstNonSymmetry \/* = false*\/) const\n{\n const int *extptr = this->extptr ? this->extptr : rowptr + 1;\n for (int i = 0; i < m; ++i) {\n for (int j = rowptr[i] - base; j < extptr[i] - base; ++j) {\n int c = colidx[j] - base;\n if (c > i) {\n bool hasPair = false;\n for (int k = rowptr[c] - base; k < extptr[c] - base; ++k) {\n if (colidx[k] - base == i) {\n hasPair = true;\n if (checkValues && values[j] != values[k]) {\n if (printFirstNonSymmetry) {\n printf(\n \"assymmetric (%d, %d) = %g, (%d, %d) = %g\\n\", \n i + 1, c + 1, values[j], c + 1, i + 1, values[k]);\n }\n return false;\n }\n break;\n }\n }\n if (!hasPair) {\n if (printFirstNonSymmetry) {\n printf(\n \"assymmetric (%d, %d) exists but (%d, %d) doesn't\\n\",\n i + 1, c + 1, c + 1, i + 1);\n }\n return false;\n }\n }\n }\n } \/\/ for each row\n\n return true;\n}\n\nvoid CSR::store_matrix_market(const char *file_name) const\n{\n FILE *fp = fopen(file_name, \"w\");\n assert(fp);\n\n MM_typecode matcode;\n mm_initialize_typecode(&matcode);\n mm_set_matrix(&matcode);\n mm_set_sparse(&matcode);\n mm_set_real(&matcode);\n\n \/\/ print banner followed by typecode.\n fprintf(fp, \"%s \", MatrixMarketBanner);\n fprintf(fp, \"%s\\n\", mm_typecode_to_str(matcode));\n\n \/\/ print matrix size and nonzeros.\n fprintf(fp, \"%d %d %d\\n\", m, n, rowptr[m]);\n \n \/\/ print values\n for (int i = 0; i < m; ++i) {\n for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {\n fprintf(fp, \"%d %d %20.16g\\n\", i + 1, colidx[j] + 1, values[j]);\n }\n }\n\n fclose(fp);\n}\n\nvoid CSR::make0BasedIndexing()\n{\n if (0 == base) return;\n\n#pragma omp parallel for\n for(int i=0; i <= m; i++)\n rowptr[i]--;\n\n int nnz = rowptr[m];\n#pragma omp parallel for\n for(int i=0; i < nnz; i++)\n colidx[i]--;\n\n base = 0;\n}\n\nvoid CSR::make1BasedIndexing()\n{\n if (1 == base) return;\n\n#pragma omp parallel for\n for(int i=0; i <= m; i++)\n rowptr[i]++;\n\n int nnz = rowptr[m];\n#pragma omp parallel for\n for(int i=0; i < nnz; i++)\n colidx[i]++;\n\n base = 1;\n}\n\n\/**\n * idx = idx2*dim1 + idx1\n * -> ret = idx1*dim2 + idx2\n * = (idx%dim1)*dim2 + idx\/dim1\n *\/\nstatic inline int transpose_idx(int idx, int dim1, int dim2)\n{\n return idx%dim1*dim2 + idx\/dim1;\n}\n\n\/\/ TODO: only supports local matrix for now\n\/**\n * Transposition using parallel counting sort\n *\/\nCSR *CSR::transpose() const\n{\n const double *A_data = values;\n const int *A_i = rowptr;\n const int *A_j = colidx;\n int num_rowsA = m;\n int num_colsA = n;\n int nnz = rowptr[m];\n int num_nonzerosA = nnz;\n\n CSR *AT = new CSR();\n\n AT->m = m;\n AT->n = n;\n AT->colidx = MALLOC(int, nnz);\n assert(AT->colidx);\n if (A_data) {\n AT->values = MALLOC(double, nnz);\n assert(AT->values);\n }\n if (diagptr) {\n AT->diagptr = MALLOC(int, m);\n assert(AT->diagptr);\n }\n\n if (0 == num_colsA) {\n return AT;\n }\n\n int *AT_j = AT->colidx;\n double *AT_data = AT->values;\n\n double t = omp_get_wtime();\n\n int *bucket = MALLOC(\n int, (num_colsA + 1)*omp_get_max_threads());\n\n#ifndef NDEBUG\n int i;\n for (i = 0; i < num_rowsA; ++i) {\n assert(A_i[i + 1] >= A_i[i]);\n }\n#endif\n\n#define MIN(a, b) (((a) <= (b)) ? (a) : (b))\n\n#pragma omp parallel\n {\n int nthreads = omp_get_num_threads();\n int tid = omp_get_thread_num();\n\n int nnzPerThread = (num_nonzerosA + nthreads - 1)\/nthreads;\n int iBegin = lower_bound(A_i, A_i + num_rowsA, nnzPerThread*tid) - A_i;\n int iEnd = lower_bound(A_i, A_i + num_rowsA, nnzPerThread*(tid + 1)) - A_i;\n\n int i, j;\n memset(bucket + tid*num_colsA, 0, sizeof(int)*num_colsA);\n\n \/\/ count the number of keys that will go into each bucket\n for (j = A_i[iBegin]; j < A_i[iEnd]; ++j) {\n int idx = A_j[j];\n#ifndef NDEBUG\n if (idx < 0 || idx >= num_colsA) {\n printf(\"tid = %d num_rowsA = %d num_colsA = %d num_nonzerosA = %d iBegin = %d iEnd = %d A_i[iBegin] = %d A_i[iEnd] = %d j = %d idx = %d\\n\", tid, num_rowsA, num_colsA, num_nonzerosA, iBegin, iEnd, A_i[iBegin], A_i[iEnd], j, idx);\n }\n#endif\n assert(idx >= 0 && idx < num_colsA);\n bucket[tid*num_colsA + idx]++;\n }\n \/\/ up to here, bucket is used as int[nthreads][num_colsA] 2D array\n\n \/\/ prefix sum\n#pragma omp barrier\n\n for (i = tid*num_colsA + 1; i < (tid + 1)*num_colsA; ++i) {\n int transpose_i = transpose_idx(i, nthreads, num_colsA);\n int transpose_i_minus_1 = transpose_idx(i - 1, nthreads, num_colsA);\n\n bucket[transpose_i] += bucket[transpose_i_minus_1];\n }\n\n#pragma omp barrier\n#pragma omp master\n {\n for (i = 1; i < nthreads; ++i) {\n int j0 = num_colsA*i - 1, j1 = num_colsA*(i + 1) - 1;\n int transpose_j0 = transpose_idx(j0, nthreads, num_colsA);\n int transpose_j1 = transpose_idx(j1, nthreads, num_colsA);\n\n bucket[transpose_j1] += bucket[transpose_j0];\n }\n bucket[num_colsA] = num_nonzerosA;\n }\n#pragma omp barrier\n\n if (tid > 0) {\n int transpose_i0 = transpose_idx(num_colsA*tid - 1, nthreads, num_colsA);\n\n for (i = tid*num_colsA; i < (tid + 1)*num_colsA - 1; ++i) {\n int transpose_i = transpose_idx(i, nthreads, num_colsA);\n\n bucket[transpose_i] += bucket[transpose_i0];\n }\n }\n\n#pragma omp barrier\n\n if (A_data) {\n for (i = iEnd - 1; i >= iBegin; --i) {\n for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) {\n int idx = A_j[j];\n --bucket[tid*num_colsA + idx];\n\n int offset = bucket[tid*num_colsA + idx];\n\n assert(offset >= 0 && offset < num_nonzerosA);\n AT_data[offset] = A_data[j];\n AT_j[offset] = i;\n }\n }\n }\n else {\n for (i = iEnd - 1; i >= iBegin; --i) {\n for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) {\n int idx = A_j[j];\n --bucket[tid*num_colsA + idx];\n\n int offset = bucket[tid*num_colsA + idx];\n\n AT_j[offset] = i;\n }\n }\n }\n\n if (diagptr) {\n#pragma omp barrier\n for (i = iBegin; i < iEnd; ++i) {\n for (int j = bucket[i]; j < bucket[i + 1]; ++j) {\n int c = AT_j[j];\n if (c == i) AT->diagptr[i] = j;\n }\n }\n }\n\n } \/\/ omp parallel\n\n AT->rowptr = bucket; \n\n return AT;\n }\n\ntemplate<int BASE = 0>\nint getBandwidth_(const CSR *A)\n{\n int bw = INT_MIN;\n#pragma omp parallel for reduction(max:bw)\n for (int i = 0; i < A->m; ++i) {\n for (int j = A->rowptr[i] - BASE; j < A->rowptr[i + 1] - BASE; ++j) {\n int c = A->colidx[j] - BASE;\n int temp = c - i;\n if (temp < 0) temp = -temp;\n bw = max(temp, bw);\n }\n }\n return bw;\n}\n\nint CSR::getBandwidth() const\n{\n if (0 == base) {\n return getBandwidth_<0>(this);\n }\n else {\n assert(1 == base);\n return getBandwidth_<1>(this);\n }\n}\n\n} \/\/ namespace SpMP\n<commit_msg>initialize base<commit_after>\/**\nCopyright (c) 2015, Intel Corporation. All rights reserved.\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Intel Corporation nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\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 INTEL CORPORATION BE LIABLE FOR ANY\nDIRECT, 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\nON ANY 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#include <cstdio>\n#include <cstring>\n#include <climits>\n#include <algorithm>\n\n#include <omp.h>\n\n#include \"CSR.hpp\"\n#include \"COO.hpp\"\n#include \"mm_io.h\"\n#include \"Utils.hpp\"\n#include \"MemoryPool.hpp\"\n\n#ifdef LOADIMBA\n#include \"synk\/loadimba.hpp\"\n#else\n#include \"synk\/barrier.hpp\"\n#endif\n\nusing namespace std;\n\n#ifdef LOADIMBA\nextern synk::LoadImba *bar;\n#else\nextern synk::Barrier *bar;\n#endif\n\nnamespace SpMP\n{\n\nbool CSR::useMemoryPool_() const\n{\n return MemoryPool::getSingleton()->contains(rowptr);\n}\n\nCSR::CSR() : rowptr(NULL), colidx(NULL), values(NULL), idiag(NULL), diag(NULL), diagptr(NULL), extptr(NULL), base(0), ownData_(false)\n{\n}\n\nvoid CSR::alloc(int m, int nnz, bool createSeparateDiagData \/*= true*\/)\n{\n this->m = m;\n\n rowptr = MALLOC(int, m + 1);\n colidx = MALLOC(int, nnz);\n values = MALLOC(double, nnz);\n diagptr = MALLOC(int, m);\n\n assert(rowptr != NULL);\n assert(colidx != NULL);\n assert(values != NULL);\n assert(diagptr != NULL);\n\n if (createSeparateDiagData) {\n idiag = MALLOC(double, m);\n diag = MALLOC(double, m);\n assert(idiag != NULL);\n assert(diag != NULL);\n }\n\n ownData_ = true;\n}\n\nCSR::CSR(int m, int n, int nnz, int base \/*=0*\/)\n : base(base)\n{\n this->m=m;\n this->n=n;\n alloc(n, nnz);\n}\n\nCSR::CSR(const char *file, bool forceSymmetric \/*=false*\/, int pad \/*=1*\/)\n : base(0), rowptr(NULL), colidx(NULL), values(NULL), idiag(NULL), diag(NULL), diagptr(NULL), extptr(NULL)\n{\n int m = atoi(file);\n char buf[1024];\n sprintf(buf, \"%d\", m);\n\n int l = strlen(file);\n\n if (!strcmp(buf, file)) {\n generate3D27PtLaplacian(this, m);\n }\n else {\n COO Acoo;\n load_matrix_market((char *)file, Acoo, forceSymmetric, pad);\n\n alloc(Acoo.m, Acoo.nnz);\n\n dcoo2crs(&Acoo, this);\n }\n}\n\nCSR::CSR(int m, int n, int *rowptr, int *colidx, double *values, int base \/*=0*\/) :\n m(m), n(n), rowptr(rowptr), colidx(colidx), values(values), ownData_(false), idiag(NULL), diag(NULL), extptr(NULL), base(base)\n{\n diagptr = MALLOC(int, m);\n#pragma omp parallel for\n for (int i = 0; i < m; ++i) {\n for (int j = rowptr[i] - base; j < rowptr[i + 1] - base; ++j) {\n if (colidx[j] - base == i) {\n diagptr[i] = j + base;\n }\n }\n }\n}\n\nvoid CSR::dealloc()\n{\n if (useMemoryPool_()) {\n \/\/ a large single contiguous chunk is allocated to\n \/\/ buffers except rowptr and colidx.\n rowptr = NULL;\n extptr = NULL;\n colidx = NULL;\n values = NULL;\n idiag = NULL;\n diag = NULL;\n diagptr = NULL;\n }\n else {\n if (ownData_) {\n FREE(rowptr);\n FREE(extptr);\n FREE(colidx);\n FREE(values);\n }\n\n FREE(idiag);\n FREE(diag);\n FREE(diagptr);\n }\n}\n\nCSR::~CSR()\n{\n dealloc();\n}\n\nbool CSR::isSymmetric(bool checkValues \/*=true*\/, bool printFirstNonSymmetry \/* = false*\/) const\n{\n const int *extptr = this->extptr ? this->extptr : rowptr + 1;\n for (int i = 0; i < m; ++i) {\n for (int j = rowptr[i] - base; j < extptr[i] - base; ++j) {\n int c = colidx[j] - base;\n if (c != i) {\n bool hasPair = false;\n for (int k = rowptr[c] - base; k < extptr[c] - base; ++k) {\n if (colidx[k] - base == i) {\n hasPair = true;\n if (checkValues && values[j] != values[k]) {\n if (printFirstNonSymmetry) {\n printf(\n \"assymmetric (%d, %d) = %g, (%d, %d) = %g\\n\", \n i + 1, c + 1, values[j], c + 1, i + 1, values[k]);\n }\n return false;\n }\n break;\n }\n }\n if (!hasPair) {\n if (printFirstNonSymmetry) {\n printf(\n \"assymmetric (%d, %d) exists but (%d, %d) doesn't\\n\",\n i + 1, c + 1, c + 1, i + 1);\n }\n return false;\n }\n }\n }\n } \/\/ for each row\n\n return true;\n}\n\nvoid CSR::store_matrix_market(const char *file_name) const\n{\n FILE *fp = fopen(file_name, \"w\");\n assert(fp);\n\n MM_typecode matcode;\n mm_initialize_typecode(&matcode);\n mm_set_matrix(&matcode);\n mm_set_sparse(&matcode);\n mm_set_real(&matcode);\n\n \/\/ print banner followed by typecode.\n fprintf(fp, \"%s \", MatrixMarketBanner);\n fprintf(fp, \"%s\\n\", mm_typecode_to_str(matcode));\n\n \/\/ print matrix size and nonzeros.\n fprintf(fp, \"%d %d %d\\n\", m, n, rowptr[m]);\n \n \/\/ print values\n for (int i = 0; i < m; ++i) {\n for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {\n fprintf(fp, \"%d %d %20.16g\\n\", i + 1, colidx[j] + 1, values[j]);\n }\n }\n\n fclose(fp);\n}\n\nvoid CSR::make0BasedIndexing()\n{\n if (0 == base) return;\n\n#pragma omp parallel for\n for(int i=0; i <= m; i++)\n rowptr[i]--;\n\n int nnz = rowptr[m];\n#pragma omp parallel for\n for(int i=0; i < nnz; i++)\n colidx[i]--;\n\n base = 0;\n}\n\nvoid CSR::make1BasedIndexing()\n{\n if (1 == base) return;\n\n#pragma omp parallel for\n for(int i=0; i <= m; i++)\n rowptr[i]++;\n\n int nnz = rowptr[m];\n#pragma omp parallel for\n for(int i=0; i < nnz; i++)\n colidx[i]++;\n\n base = 1;\n}\n\n\/**\n * idx = idx2*dim1 + idx1\n * -> ret = idx1*dim2 + idx2\n * = (idx%dim1)*dim2 + idx\/dim1\n *\/\nstatic inline int transpose_idx(int idx, int dim1, int dim2)\n{\n return idx%dim1*dim2 + idx\/dim1;\n}\n\n\/\/ TODO: only supports local matrix for now\n\/**\n * Transposition using parallel counting sort\n *\/\nCSR *CSR::transpose() const\n{\n const double *A_data = values;\n const int *A_i = rowptr;\n const int *A_j = colidx;\n int num_rowsA = m;\n int num_colsA = n;\n int nnz = rowptr[m];\n int num_nonzerosA = nnz;\n\n CSR *AT = new CSR();\n\n AT->m = m;\n AT->n = n;\n AT->colidx = MALLOC(int, nnz);\n assert(AT->colidx);\n if (A_data) {\n AT->values = MALLOC(double, nnz);\n assert(AT->values);\n }\n if (diagptr) {\n AT->diagptr = MALLOC(int, m);\n assert(AT->diagptr);\n }\n\n if (0 == num_colsA) {\n return AT;\n }\n\n int *AT_j = AT->colidx;\n double *AT_data = AT->values;\n\n double t = omp_get_wtime();\n\n int *bucket = MALLOC(\n int, (num_colsA + 1)*omp_get_max_threads());\n\n#ifndef NDEBUG\n int i;\n for (i = 0; i < num_rowsA; ++i) {\n assert(A_i[i + 1] >= A_i[i]);\n }\n#endif\n\n#define MIN(a, b) (((a) <= (b)) ? (a) : (b))\n\n#pragma omp parallel\n {\n int nthreads = omp_get_num_threads();\n int tid = omp_get_thread_num();\n\n int nnzPerThread = (num_nonzerosA + nthreads - 1)\/nthreads;\n int iBegin = lower_bound(A_i, A_i + num_rowsA, nnzPerThread*tid) - A_i;\n int iEnd = lower_bound(A_i, A_i + num_rowsA, nnzPerThread*(tid + 1)) - A_i;\n\n int i, j;\n memset(bucket + tid*num_colsA, 0, sizeof(int)*num_colsA);\n\n \/\/ count the number of keys that will go into each bucket\n for (j = A_i[iBegin]; j < A_i[iEnd]; ++j) {\n int idx = A_j[j];\n#ifndef NDEBUG\n if (idx < 0 || idx >= num_colsA) {\n printf(\"tid = %d num_rowsA = %d num_colsA = %d num_nonzerosA = %d iBegin = %d iEnd = %d A_i[iBegin] = %d A_i[iEnd] = %d j = %d idx = %d\\n\", tid, num_rowsA, num_colsA, num_nonzerosA, iBegin, iEnd, A_i[iBegin], A_i[iEnd], j, idx);\n }\n#endif\n assert(idx >= 0 && idx < num_colsA);\n bucket[tid*num_colsA + idx]++;\n }\n \/\/ up to here, bucket is used as int[nthreads][num_colsA] 2D array\n\n \/\/ prefix sum\n#pragma omp barrier\n\n for (i = tid*num_colsA + 1; i < (tid + 1)*num_colsA; ++i) {\n int transpose_i = transpose_idx(i, nthreads, num_colsA);\n int transpose_i_minus_1 = transpose_idx(i - 1, nthreads, num_colsA);\n\n bucket[transpose_i] += bucket[transpose_i_minus_1];\n }\n\n#pragma omp barrier\n#pragma omp master\n {\n for (i = 1; i < nthreads; ++i) {\n int j0 = num_colsA*i - 1, j1 = num_colsA*(i + 1) - 1;\n int transpose_j0 = transpose_idx(j0, nthreads, num_colsA);\n int transpose_j1 = transpose_idx(j1, nthreads, num_colsA);\n\n bucket[transpose_j1] += bucket[transpose_j0];\n }\n bucket[num_colsA] = num_nonzerosA;\n }\n#pragma omp barrier\n\n if (tid > 0) {\n int transpose_i0 = transpose_idx(num_colsA*tid - 1, nthreads, num_colsA);\n\n for (i = tid*num_colsA; i < (tid + 1)*num_colsA - 1; ++i) {\n int transpose_i = transpose_idx(i, nthreads, num_colsA);\n\n bucket[transpose_i] += bucket[transpose_i0];\n }\n }\n\n#pragma omp barrier\n\n if (A_data) {\n for (i = iEnd - 1; i >= iBegin; --i) {\n for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) {\n int idx = A_j[j];\n --bucket[tid*num_colsA + idx];\n\n int offset = bucket[tid*num_colsA + idx];\n\n assert(offset >= 0 && offset < num_nonzerosA);\n AT_data[offset] = A_data[j];\n AT_j[offset] = i;\n }\n }\n }\n else {\n for (i = iEnd - 1; i >= iBegin; --i) {\n for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) {\n int idx = A_j[j];\n --bucket[tid*num_colsA + idx];\n\n int offset = bucket[tid*num_colsA + idx];\n\n AT_j[offset] = i;\n }\n }\n }\n\n if (diagptr) {\n#pragma omp barrier\n for (i = iBegin; i < iEnd; ++i) {\n for (int j = bucket[i]; j < bucket[i + 1]; ++j) {\n int c = AT_j[j];\n if (c == i) AT->diagptr[i] = j;\n }\n }\n }\n\n } \/\/ omp parallel\n\n AT->rowptr = bucket; \n\n return AT;\n }\n\ntemplate<int BASE = 0>\nint getBandwidth_(const CSR *A)\n{\n int bw = INT_MIN;\n#pragma omp parallel for reduction(max:bw)\n for (int i = 0; i < A->m; ++i) {\n for (int j = A->rowptr[i] - BASE; j < A->rowptr[i + 1] - BASE; ++j) {\n int c = A->colidx[j] - BASE;\n int temp = c - i;\n if (temp < 0) temp = -temp;\n bw = max(temp, bw);\n }\n }\n return bw;\n}\n\nint CSR::getBandwidth() const\n{\n if (0 == base) {\n return getBandwidth_<0>(this);\n }\n else {\n assert(1 == base);\n return getBandwidth_<1>(this);\n }\n}\n\n} \/\/ namespace SpMP\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Workaround a race condition caused by not synchronization destruction of the pipeline.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sequence.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2007-07-06 10:19:13 $\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 _COMPHELPER_SEQUENCE_HXX_\n#define _COMPHELPER_SEQUENCE_HXX_\n\n#ifndef INCLUDED_ALGORITHM\n#include <algorithm> \/\/ copy algorithm\n#define INCLUDED_ALGORITHM\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n#include <vector>\n\n\/\/.........................................................................\nnamespace comphelper\n{\n\/\/.........................................................................\n\n namespace staruno = ::com::sun::star::uno;\n\n \/\/-------------------------------------------------------------------------\n \/** search the given string within the given sequence, return the positions where it was found.\n if _bOnlyFirst is sal_True, only the first occurence will be returned.\n *\/\n COMPHELPER_DLLPUBLIC staruno::Sequence<sal_Int16> findValue(const staruno::Sequence< ::rtl::OUString >& _rList, const ::rtl::OUString& _rValue, sal_Bool _bOnlyFirst = sal_False);\n\n \/** Checks if the name exists\n *\n * \\param Value The value to search for.\n * \\param _aList The list in which to search for the value.\n * \\return <TRUE\/> if the value can be found, otherwise <FALSE\/>.\n *\/\n COMPHELPER_DLLPUBLIC sal_Bool existsValue(const ::rtl::OUString& Value,const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _aList);\n\n\n \/\/-------------------------------------------------------------------------\n namespace internal\n {\n template <class T>\n void implCopySequence(const T* _pSource, T*& _pDest, sal_Int32 _nSourceLen)\n {\n for (sal_Int32 i=0; i<_nSourceLen; ++i, ++_pSource, ++_pDest)\n *_pDest = *_pSource;\n }\n }\n \/\/-------------------------------------------------------------------------\n \/\/\/ concat two sequences\n template <class T>\n staruno::Sequence<T> concatSequences(const staruno::Sequence<T>& _rLeft, const staruno::Sequence<T>& _rRight)\n {\n sal_Int32 nLeft(_rLeft.getLength()), nRight(_rRight.getLength());\n const T* pLeft = _rLeft.getConstArray();\n const T* pRight = _rRight.getConstArray();\n\n sal_Int32 nReturnLen(nLeft + nRight);\n staruno::Sequence<T> aReturn(nReturnLen);\n T* pReturn = aReturn.getArray();\n\n internal::implCopySequence(pLeft, pReturn, nLeft);\n internal::implCopySequence(pRight, pReturn, nRight);\n\n return aReturn;\n }\n\n \/\/-------------------------------------------------------------------------\n \/\/\/ concat three sequences\n template <class T>\n staruno::Sequence<T> concatSequences(const staruno::Sequence<T>& _rLeft, const staruno::Sequence<T>& _rMiddle, const staruno::Sequence<T>& _rRight)\n {\n sal_Int32 nLeft(_rLeft.getLength()), nMiddle(_rMiddle.getLength()), nRight(_rRight.getLength());\n const T* pLeft = _rLeft.getConstArray();\n const T* pMiddle = _rMiddle.getConstArray();\n const T* pRight = _rRight.getConstArray();\n\n sal_Int32 nReturnLen(nLeft + nMiddle + nRight);\n staruno::Sequence<T> aReturn(nReturnLen);\n T* pReturn = aReturn.getArray();\n\n internal::implCopySequence(pLeft, pReturn, nLeft);\n internal::implCopySequence(pMiddle, pReturn, nMiddle);\n internal::implCopySequence(pRight, pReturn, nRight);\n\n return aReturn;\n }\n\n \/\/-------------------------------------------------------------------------\n \/\/\/ remove a specified element from a sequences\n template<class T>\n void removeElementAt(staruno::Sequence<T>& _rSeq, sal_Int32 _nPos)\n {\n sal_uInt32 nLength = _rSeq.getLength();\n\n OSL_ENSURE(0 <= _nPos && (sal_uInt32)_nPos < nLength, \"invalid index\");\n\n for (sal_uInt32 i = (sal_uInt32)_nPos + 1; i < nLength; ++i)\n {\n _rSeq[i-1] = _rSeq[i];\n }\n\n _rSeq.realloc(nLength-1);\n }\n\n \/\/=====================================================================\n \/\/= iterating through sequences\n \/\/=====================================================================\n class SAL_NO_VTABLE IIterator\n {\n public:\n virtual sal_Bool hasMoreElements() const = 0;\n virtual ::com::sun::star::uno::Any nextElement() = 0;\n };\n \/** a helper class for iterating through a sequence\n *\/\n template <class TYPE>\n class OSequenceIterator : public IIterator\n {\n const TYPE* m_pElements;\n sal_Int32 m_nLen;\n const TYPE* m_pCurrent;\n\n public:\n \/** contrcuct a sequence iterator from a sequence\n *\/\n OSequenceIterator(const ::com::sun::star::uno::Sequence< TYPE >& _rSeq);\n \/** contrcuct a sequence iterator from a Any containing a sequence\n *\/\n OSequenceIterator(const ::com::sun::star::uno::Any& _rSequenceAny);\n\n virtual sal_Bool hasMoreElements() const;\n virtual ::com::sun::star::uno::Any nextElement();\n\n protected:\n void construct(const ::com::sun::star::uno::Sequence< TYPE >& _rSeq);\n };\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n OSequenceIterator<TYPE>::OSequenceIterator(const ::com::sun::star::uno::Sequence< TYPE >& _rSeq)\n :m_pElements(NULL)\n ,m_nLen(0)\n ,m_pCurrent(NULL)\n {\n construct(_rSeq);\n }\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n OSequenceIterator<TYPE>::OSequenceIterator(const ::com::sun::star::uno::Any& _rSequenceAny)\n :m_pElements(NULL)\n ,m_nLen(0)\n ,m_pCurrent(NULL)\n {\n ::com::sun::star::uno::Sequence< TYPE > aContainer;\n #ifdef DBG_UTIL\n sal_Bool bSuccess =\n #endif\n _rSequenceAny >>= aContainer;\n #ifdef DBG_UTIL\n OSL_ENSURE(bSuccess, \"OSequenceIterator::OSequenceIterator: invalid Any!\");\n #endif\n construct(aContainer);\n }\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n void OSequenceIterator<TYPE>::construct(const ::com::sun::star::uno::Sequence< TYPE >& _rSeq)\n {\n m_pElements = _rSeq.getConstArray();\n m_nLen = _rSeq.getLength();\n m_pCurrent = m_pElements;\n }\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n sal_Bool OSequenceIterator<TYPE>::hasMoreElements() const\n {\n return m_pCurrent - m_pElements < m_nLen;\n }\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n ::com::sun::star::uno::Any OSequenceIterator<TYPE>::nextElement()\n {\n return ::com::sun::star::uno::makeAny(*m_pCurrent++);\n }\n\n \/\/-------------------------------------------------------------------------\n \/** Copy from a plain C\/C++ array into a Sequence.\n\n @tpl SrcType\n Array element type. Must be assignable to DstType\n\n @tpl DstType\n Sequence element type. Must be assignable from SrcType\n\n @param i_pArray\n Valid pointer to at least num elements of type SrcType\n\n @param nNum\n Number of array elements to copy\n\n @return the resulting Sequence\n\n @attention when copying from e.g. a double array to a\n Sequence<int>, no proper rounding will be performed, but the\n values will be truncated. There's currently no measure to\n prevent or detect precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n ::com::sun::star::uno::Sequence< DstType > arrayToSequence( const SrcType* i_pArray, sal_Int32 nNum )\n {\n ::com::sun::star::uno::Sequence< DstType > result( nNum );\n ::std::copy( i_pArray, i_pArray+nNum, result.getArray() );\n return result;\n }\n\n \/\/-------------------------------------------------------------------------\n \/** Copy from a Sequence into a plain C\/C++ array\n\n @tpl SrcType\n Sequence element type. Must be assignable to DstType\n\n @tpl DstType\n Array element type. Must be assignable from SrcType\n\n @param io_pArray\n Valid pointer to at least i_Sequence.getLength() elements of\n type DstType\n\n @param i_Sequence\n Reference to a Sequence of SrcType elements\n\n @return a pointer to the array\n\n @attention when copying from e.g. a Sequence<double> to an int\n array, no proper rounding will be performed, but the values\n will be truncated. There's currently no measure to prevent or\n detect precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n DstType* sequenceToArray( DstType* io_pArray, const ::com::sun::star::uno::Sequence< SrcType >& i_Sequence )\n {\n ::std::copy( i_Sequence.getConstArray(), i_Sequence.getConstArray()+i_Sequence.getLength(), io_pArray );\n return io_pArray;\n }\n\n \/\/-------------------------------------------------------------------------\n \/** Copy from a container into a Sequence\n\n @tpl SrcType\n Container type. This type must fulfill the STL container\n concept, in particular, the size(), begin() and end() methods\n must be available and have the usual semantics.\n\n @tpl DstType\n Sequence element type. Must be assignable from SrcType's\n elements\n\n @param i_Container\n Reference to the input contain with elements of type SrcType\n\n @return the generated Sequence\n\n @attention this function always performs a copy. Furthermore,\n when copying from e.g. a vector<double> to a Sequence<int>, no\n proper rounding will be performed, but the values will be\n truncated. There's currently no measure to prevent or detect\n precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n ::com::sun::star::uno::Sequence< DstType > containerToSequence( const SrcType& i_Container )\n {\n ::com::sun::star::uno::Sequence< DstType > result( i_Container.size() );\n ::std::copy( i_Container.begin(), i_Container.end(), result.getArray() );\n return result;\n }\n\n template <typename T>\n inline ::com::sun::star::uno::Sequence<T> containerToSequence(\n ::std::vector<T> const& v )\n {\n return ::com::sun::star::uno::Sequence<T>(\n v.empty() ? 0 : &v[0], static_cast<sal_Int32>(v.size()) );\n }\n\n \/\/-------------------------------------------------------------------------\n \/** Copy from a Sequence into a container\n\n @tpl SrcType\n Sequence element type. Must be assignable to SrcType's\n elements\n\n @tpl DstType\n Container type. This type must fulfill the STL container and\n sequence concepts, in particular, the begin(), end() and the\n unary constructor DstType(int) methods must be available and\n have the usual semantics.\n\n @param i_Sequence\n Reference to a Sequence of SrcType elements\n\n @return a pointer to the generated container\n\n @attention this function always performs a copy. Furthermore,\n when copying from e.g. a Sequence<double> to a vector<int>, no\n proper rounding will be performed, but the values will be\n truncated. There's currently no measure to prevent or detect\n precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n DstType sequenceToContainer( const ::com::sun::star::uno::Sequence< SrcType >& i_Sequence )\n {\n DstType result( i_Sequence.getLength() );\n ::std::copy( i_Sequence.getConstArray(), i_Sequence.getConstArray()+i_Sequence.getLength(), result.begin() );\n return result;\n }\n\n\/\/.........................................................................\n} \/\/ namespace comphelper\n\/\/.........................................................................\n\n\n#endif \/\/ _COMPHELPER_SEQUENCE_HXX_\n\n<commit_msg>INTEGRATION: CWS pdfimport (1.11.68); FILE MERGED 2008\/01\/25 08:30:20 akhva 1.11.68.1: #i80825# resync<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sequence.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: kz $ $Date: 2008-04-04 16:14: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#ifndef _COMPHELPER_SEQUENCE_HXX_\n#define _COMPHELPER_SEQUENCE_HXX_\n\n#ifndef INCLUDED_ALGORITHM\n#include <algorithm> \/\/ copy algorithm\n#define INCLUDED_ALGORITHM\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n#include <vector>\n\n\/\/.........................................................................\nnamespace comphelper\n{\n\/\/.........................................................................\n\n namespace staruno = ::com::sun::star::uno;\n\n \/\/-------------------------------------------------------------------------\n \/** search the given string within the given sequence, return the positions where it was found.\n if _bOnlyFirst is sal_True, only the first occurence will be returned.\n *\/\n COMPHELPER_DLLPUBLIC staruno::Sequence<sal_Int16> findValue(const staruno::Sequence< ::rtl::OUString >& _rList, const ::rtl::OUString& _rValue, sal_Bool _bOnlyFirst = sal_False);\n\n \/** Checks if the name exists\n *\n * \\param Value The value to search for.\n * \\param _aList The list in which to search for the value.\n * \\return <TRUE\/> if the value can be found, otherwise <FALSE\/>.\n *\/\n COMPHELPER_DLLPUBLIC sal_Bool existsValue(const ::rtl::OUString& Value,const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _aList);\n\n\n \/\/-------------------------------------------------------------------------\n namespace internal\n {\n template <class T>\n void implCopySequence(const T* _pSource, T*& _pDest, sal_Int32 _nSourceLen)\n {\n for (sal_Int32 i=0; i<_nSourceLen; ++i, ++_pSource, ++_pDest)\n *_pDest = *_pSource;\n }\n }\n \/\/-------------------------------------------------------------------------\n \/\/\/ concat two sequences\n template <class T>\n staruno::Sequence<T> concatSequences(const staruno::Sequence<T>& _rLeft, const staruno::Sequence<T>& _rRight)\n {\n sal_Int32 nLeft(_rLeft.getLength()), nRight(_rRight.getLength());\n const T* pLeft = _rLeft.getConstArray();\n const T* pRight = _rRight.getConstArray();\n\n sal_Int32 nReturnLen(nLeft + nRight);\n staruno::Sequence<T> aReturn(nReturnLen);\n T* pReturn = aReturn.getArray();\n\n internal::implCopySequence(pLeft, pReturn, nLeft);\n internal::implCopySequence(pRight, pReturn, nRight);\n\n return aReturn;\n }\n\n \/\/-------------------------------------------------------------------------\n \/\/\/ concat three sequences\n template <class T>\n staruno::Sequence<T> concatSequences(const staruno::Sequence<T>& _rLeft, const staruno::Sequence<T>& _rMiddle, const staruno::Sequence<T>& _rRight)\n {\n sal_Int32 nLeft(_rLeft.getLength()), nMiddle(_rMiddle.getLength()), nRight(_rRight.getLength());\n const T* pLeft = _rLeft.getConstArray();\n const T* pMiddle = _rMiddle.getConstArray();\n const T* pRight = _rRight.getConstArray();\n\n sal_Int32 nReturnLen(nLeft + nMiddle + nRight);\n staruno::Sequence<T> aReturn(nReturnLen);\n T* pReturn = aReturn.getArray();\n\n internal::implCopySequence(pLeft, pReturn, nLeft);\n internal::implCopySequence(pMiddle, pReturn, nMiddle);\n internal::implCopySequence(pRight, pReturn, nRight);\n\n return aReturn;\n }\n\n \/\/-------------------------------------------------------------------------\n \/\/\/ remove a specified element from a sequences\n template<class T>\n void removeElementAt(staruno::Sequence<T>& _rSeq, sal_Int32 _nPos)\n {\n sal_uInt32 nLength = _rSeq.getLength();\n\n OSL_ENSURE(0 <= _nPos && (sal_uInt32)_nPos < nLength, \"invalid index\");\n\n for (sal_uInt32 i = (sal_uInt32)_nPos + 1; i < nLength; ++i)\n {\n _rSeq[i-1] = _rSeq[i];\n }\n\n _rSeq.realloc(nLength-1);\n }\n\n \/\/=====================================================================\n \/\/= iterating through sequences\n \/\/=====================================================================\n class SAL_NO_VTABLE IIterator\n {\n public:\n virtual sal_Bool hasMoreElements() const = 0;\n virtual ::com::sun::star::uno::Any nextElement() = 0;\n };\n \/** a helper class for iterating through a sequence\n *\/\n template <class TYPE>\n class OSequenceIterator : public IIterator\n {\n const TYPE* m_pElements;\n sal_Int32 m_nLen;\n const TYPE* m_pCurrent;\n\n public:\n \/** contrcuct a sequence iterator from a sequence\n *\/\n OSequenceIterator(const ::com::sun::star::uno::Sequence< TYPE >& _rSeq);\n \/** contrcuct a sequence iterator from a Any containing a sequence\n *\/\n OSequenceIterator(const ::com::sun::star::uno::Any& _rSequenceAny);\n\n virtual sal_Bool hasMoreElements() const;\n virtual ::com::sun::star::uno::Any nextElement();\n\n protected:\n void construct(const ::com::sun::star::uno::Sequence< TYPE >& _rSeq);\n };\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n OSequenceIterator<TYPE>::OSequenceIterator(const ::com::sun::star::uno::Sequence< TYPE >& _rSeq)\n :m_pElements(NULL)\n ,m_nLen(0)\n ,m_pCurrent(NULL)\n {\n construct(_rSeq);\n }\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n OSequenceIterator<TYPE>::OSequenceIterator(const ::com::sun::star::uno::Any& _rSequenceAny)\n :m_pElements(NULL)\n ,m_nLen(0)\n ,m_pCurrent(NULL)\n {\n ::com::sun::star::uno::Sequence< TYPE > aContainer;\n #ifdef DBG_UTIL\n sal_Bool bSuccess =\n #endif\n _rSequenceAny >>= aContainer;\n #ifdef DBG_UTIL\n OSL_ENSURE(bSuccess, \"OSequenceIterator::OSequenceIterator: invalid Any!\");\n #endif\n construct(aContainer);\n }\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n void OSequenceIterator<TYPE>::construct(const ::com::sun::star::uno::Sequence< TYPE >& _rSeq)\n {\n m_pElements = _rSeq.getConstArray();\n m_nLen = _rSeq.getLength();\n m_pCurrent = m_pElements;\n }\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n sal_Bool OSequenceIterator<TYPE>::hasMoreElements() const\n {\n return m_pCurrent - m_pElements < m_nLen;\n }\n\n \/\/---------------------------------------------------------------------\n template <class TYPE>\n ::com::sun::star::uno::Any OSequenceIterator<TYPE>::nextElement()\n {\n return ::com::sun::star::uno::makeAny(*m_pCurrent++);\n }\n\n \/\/-------------------------------------------------------------------------\n \/** Copy from a plain C\/C++ array into a Sequence.\n\n @tpl SrcType\n Array element type. Must be assignable to DstType\n\n @tpl DstType\n Sequence element type. Must be assignable from SrcType\n\n @param i_pArray\n Valid pointer to at least num elements of type SrcType\n\n @param nNum\n Number of array elements to copy\n\n @return the resulting Sequence\n\n @attention when copying from e.g. a double array to a\n Sequence<int>, no proper rounding will be performed, but the\n values will be truncated. There's currently no measure to\n prevent or detect precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n ::com::sun::star::uno::Sequence< DstType > arrayToSequence( const SrcType* i_pArray, sal_Int32 nNum )\n {\n ::com::sun::star::uno::Sequence< DstType > result( nNum );\n ::std::copy( i_pArray, i_pArray+nNum, result.getArray() );\n return result;\n }\n\n \/\/-------------------------------------------------------------------------\n \/** Copy from a Sequence into a plain C\/C++ array\n\n @tpl SrcType\n Sequence element type. Must be assignable to DstType\n\n @tpl DstType\n Array element type. Must be assignable from SrcType\n\n @param io_pArray\n Valid pointer to at least i_Sequence.getLength() elements of\n type DstType\n\n @param i_Sequence\n Reference to a Sequence of SrcType elements\n\n @return a pointer to the array\n\n @attention when copying from e.g. a Sequence<double> to an int\n array, no proper rounding will be performed, but the values\n will be truncated. There's currently no measure to prevent or\n detect precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n DstType* sequenceToArray( DstType* io_pArray, const ::com::sun::star::uno::Sequence< SrcType >& i_Sequence )\n {\n ::std::copy( i_Sequence.getConstArray(), i_Sequence.getConstArray()+i_Sequence.getLength(), io_pArray );\n return io_pArray;\n }\n\n \/\/-------------------------------------------------------------------------\n \/** Copy from a container into a Sequence\n\n @tpl SrcType\n Container type. This type must fulfill the STL container\n concept, in particular, the size(), begin() and end() methods\n must be available and have the usual semantics.\n\n @tpl DstType\n Sequence element type. Must be assignable from SrcType's\n elements\n\n @param i_Container\n Reference to the input contain with elements of type SrcType\n\n @return the generated Sequence\n\n @attention this function always performs a copy. Furthermore,\n when copying from e.g. a vector<double> to a Sequence<int>, no\n proper rounding will be performed, but the values will be\n truncated. There's currently no measure to prevent or detect\n precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n ::com::sun::star::uno::Sequence< DstType > containerToSequence( const SrcType& i_Container )\n {\n ::com::sun::star::uno::Sequence< DstType > result( i_Container.size() );\n ::std::copy( i_Container.begin(), i_Container.end(), result.getArray() );\n return result;\n }\n\n template <typename T>\n inline ::com::sun::star::uno::Sequence<T> containerToSequence(\n ::std::vector<T> const& v )\n {\n return ::com::sun::star::uno::Sequence<T>(\n v.empty() ? 0 : &v[0], static_cast<sal_Int32>(v.size()) );\n }\n\n \/\/-------------------------------------------------------------------------\n \/** Copy from a Sequence into a container\n\n @tpl SrcType\n Sequence element type. Must be assignable to SrcType's\n elements\n\n @tpl DstType\n Container type. This type must fulfill the STL container and\n sequence concepts, in particular, the begin(), end() and the\n unary constructor DstType(int) methods must be available and\n have the usual semantics.\n\n @param i_Sequence\n Reference to a Sequence of SrcType elements\n\n @return the generated container\n\n @attention this function always performs a copy. Furthermore,\n when copying from e.g. a Sequence<double> to a vector<int>, no\n proper rounding will be performed, but the values will be\n truncated. There's currently no measure to prevent or detect\n precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n DstType sequenceToContainer( const ::com::sun::star::uno::Sequence< SrcType >& i_Sequence )\n {\n DstType result( i_Sequence.getLength() );\n ::std::copy( i_Sequence.getConstArray(), i_Sequence.getConstArray()+i_Sequence.getLength(), result.begin() );\n return result;\n }\n \/\/-------------------------------------------------------------------------\n \/** Copy from a Sequence into an existing container\n\n This potentially saves a needless extra copy operation over\n the whole container, as it passes the target object by\n reference.\n\n @tpl SrcType\n Sequence element type. Must be assignable to SrcType's\n elements\n\n @tpl DstType\n Container type. This type must fulfill the STL container and\n sequence concepts, in particular, the begin(), end() and\n resize(int) methods must be available and have the usual\n semantics.\n\n @param o_Output\n Reference to the target container\n\n @param i_Sequence\n Reference to a Sequence of SrcType elements\n\n @return a non-const reference to the given container\n\n @attention this function always performs a copy. Furthermore,\n when copying from e.g. a Sequence<double> to a vector<int>, no\n proper rounding will be performed, but the values will be\n truncated. There's currently no measure to prevent or detect\n precision loss, overflow or truncation.\n *\/\n template < typename DstType, typename SrcType >\n DstType& sequenceToContainer( DstType& o_Output, const ::com::sun::star::uno::Sequence< SrcType >& i_Sequence )\n {\n o_Output.resize( i_Sequence.getLength() );\n ::std::copy( i_Sequence.getConstArray(), i_Sequence.getConstArray()+i_Sequence.getLength(), o_Output.begin() );\n return o_Output;\n }\n\n\/\/.........................................................................\n} \/\/ namespace comphelper\n\/\/.........................................................................\n\n\n#endif \/\/ _COMPHELPER_SEQUENCE_HXX_\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>document why the test fails and is disabled<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Copyright (c) 2017-2020 The PIVX developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"transactionfilterproxy.h\"\n\n#include \"transactionrecord.h\"\n#include \"transactiontablemodel.h\"\n\n#include <cstdlib>\n\n#include <QDateTime>\n\n\/\/ Earliest date that can be represented (far in the past)\nconst QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0);\n\/\/ Last date that can be represented (far in the future)\nconst QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF);\n\nTransactionFilterProxy::TransactionFilterProxy(QObject* parent) : QSortFilterProxyModel(parent),\n dateFrom(MIN_DATE),\n dateTo(MAX_DATE),\n addrPrefix(),\n typeFilter(ALL_TYPES),\n watchOnlyFilter(WatchOnlyFilter_All),\n minAmount(0),\n limitRows(-1),\n showInactive(true),\n fHideOrphans(true)\n{\n}\n\nbool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const\n{\n QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);\n\n int type = index.data(TransactionTableModel::TypeRole).toInt();\n QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();\n bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool();\n QString address = index.data(TransactionTableModel::AddressRole).toString();\n QString label = index.data(TransactionTableModel::LabelRole).toString();\n qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());\n int status = index.data(TransactionTableModel::StatusRole).toInt();\n\n if (!showInactive && status == TransactionStatus::Conflicted)\n return false;\n if (fHideOrphans && isOrphan(status, type))\n return false;\n if (!(TYPE(type) & typeFilter))\n return false;\n if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No)\n return false;\n if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes)\n return false;\n if (datetime < dateFrom || datetime > dateTo)\n return false;\n if (!addrPrefix.isEmpty()) {\n if (!address.contains(addrPrefix, Qt::CaseInsensitive) && !label.contains(addrPrefix, Qt::CaseInsensitive))\n return false;\n }\n if (amount < minAmount)\n return false;\n if (fOnlyZc && !isZcTx(type)){\n return false;\n }\n if (fOnlyStakes && !isStakeTx(type))\n return false;\n\n if (fOnlyColdStaking && !isColdStake(type))\n return false;\n\n return true;\n}\n\nvoid TransactionFilterProxy::setDateRange(const QDateTime& from, const QDateTime& to)\n{\n if (from == this->dateFrom && to == this->dateTo)\n return; \/\/ No need to set the range.\n this->dateFrom = from;\n this->dateTo = to;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setAddressPrefix(const QString& addrPrefix)\n{\n this->addrPrefix = addrPrefix;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setTypeFilter(quint32 modes)\n{\n this->typeFilter = modes;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setMinAmount(const CAmount& minimum)\n{\n this->minAmount = minimum;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter)\n{\n this->watchOnlyFilter = filter;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setLimit(int limit)\n{\n this->limitRows = limit;\n}\n\nvoid TransactionFilterProxy::setShowInactive(bool showInactive)\n{\n this->showInactive = showInactive;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setHideOrphans(bool fHide)\n{\n this->fHideOrphans = fHide;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setShowZcTxes(bool fOnlyZc)\n{\n this->fOnlyZc = fOnlyZc;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setOnlyStakes(bool fOnlyStakes)\n{\n this->fOnlyStakes = fOnlyStakes;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setOnlyColdStakes(bool fOnlyColdStakes)\n{\n this->fOnlyColdStaking = fOnlyColdStakes;\n invalidateFilter();\n}\n\nint TransactionFilterProxy::rowCount(const QModelIndex& parent) const\n{\n if (limitRows != -1) {\n return std::min(QSortFilterProxyModel::rowCount(parent), limitRows);\n } else {\n return QSortFilterProxyModel::rowCount(parent);\n }\n}\n\nbool TransactionFilterProxy::isOrphan(const int status, const int type)\n{\n return ( (type == TransactionRecord::Generated || type == TransactionRecord::StakeMint ||\n type == TransactionRecord::StakeZPIV || type == TransactionRecord::MNReward)\n && (status == TransactionStatus::Conflicted || status == TransactionStatus::NotAccepted) );\n}\n\nbool TransactionFilterProxy::isZcTx(int type) const {\n return (type == TransactionRecord::ZerocoinMint || type == TransactionRecord::ZerocoinSpend || type == TransactionRecord::ZerocoinSpend_Change_zPiv\n || type == TransactionRecord::ZerocoinSpend_FromMe || type == TransactionRecord::RecvFromZerocoinSpend);\n}\n\nbool TransactionFilterProxy::isStakeTx(int type) const {\n return type == TransactionRecord::StakeMint || type == TransactionRecord::Generated || type == TransactionRecord::StakeZPIV || type == TransactionRecord::StakeDelegated;\n}\n\nbool TransactionFilterProxy::isColdStake(int type) const {\n return type == TransactionRecord::P2CSDelegation || type == TransactionRecord::P2CSDelegationSent || type == TransactionRecord::P2CSDelegationSentOwner || type == TransactionRecord::StakeDelegated || type == TransactionRecord::StakeHot;\n}\n\n\/*QVariant TransactionFilterProxy::dataFromSourcePos(int sourceRow, int role) const {\n QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);\n return index.data(index, role);\n}\n *\/<commit_msg>[GUI] Explicit cast from quint32 to bool in filterAcceptsRow<commit_after>\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Copyright (c) 2017-2020 The PIVX developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"transactionfilterproxy.h\"\n\n#include \"transactionrecord.h\"\n#include \"transactiontablemodel.h\"\n\n#include <cstdlib>\n\n#include <QDateTime>\n\n\/\/ Earliest date that can be represented (far in the past)\nconst QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0);\n\/\/ Last date that can be represented (far in the future)\nconst QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF);\n\nTransactionFilterProxy::TransactionFilterProxy(QObject* parent) : QSortFilterProxyModel(parent),\n dateFrom(MIN_DATE),\n dateTo(MAX_DATE),\n addrPrefix(),\n typeFilter(ALL_TYPES),\n watchOnlyFilter(WatchOnlyFilter_All),\n minAmount(0),\n limitRows(-1),\n showInactive(true),\n fHideOrphans(true)\n{\n}\n\nbool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const\n{\n QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);\n\n int type = index.data(TransactionTableModel::TypeRole).toInt();\n QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();\n bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool();\n QString address = index.data(TransactionTableModel::AddressRole).toString();\n QString label = index.data(TransactionTableModel::LabelRole).toString();\n qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());\n int status = index.data(TransactionTableModel::StatusRole).toInt();\n\n if (!showInactive && status == TransactionStatus::Conflicted)\n return false;\n if (fHideOrphans && isOrphan(status, type))\n return false;\n if (!(bool)(TYPE(type) & typeFilter))\n return false;\n if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No)\n return false;\n if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes)\n return false;\n if (datetime < dateFrom || datetime > dateTo)\n return false;\n if (!addrPrefix.isEmpty()) {\n if (!address.contains(addrPrefix, Qt::CaseInsensitive) && !label.contains(addrPrefix, Qt::CaseInsensitive))\n return false;\n }\n if (amount < minAmount)\n return false;\n if (fOnlyZc && !isZcTx(type)){\n return false;\n }\n if (fOnlyStakes && !isStakeTx(type))\n return false;\n\n if (fOnlyColdStaking && !isColdStake(type))\n return false;\n\n return true;\n}\n\nvoid TransactionFilterProxy::setDateRange(const QDateTime& from, const QDateTime& to)\n{\n if (from == this->dateFrom && to == this->dateTo)\n return; \/\/ No need to set the range.\n this->dateFrom = from;\n this->dateTo = to;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setAddressPrefix(const QString& addrPrefix)\n{\n this->addrPrefix = addrPrefix;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setTypeFilter(quint32 modes)\n{\n this->typeFilter = modes;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setMinAmount(const CAmount& minimum)\n{\n this->minAmount = minimum;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter)\n{\n this->watchOnlyFilter = filter;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setLimit(int limit)\n{\n this->limitRows = limit;\n}\n\nvoid TransactionFilterProxy::setShowInactive(bool showInactive)\n{\n this->showInactive = showInactive;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setHideOrphans(bool fHide)\n{\n this->fHideOrphans = fHide;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setShowZcTxes(bool fOnlyZc)\n{\n this->fOnlyZc = fOnlyZc;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setOnlyStakes(bool fOnlyStakes)\n{\n this->fOnlyStakes = fOnlyStakes;\n invalidateFilter();\n}\n\nvoid TransactionFilterProxy::setOnlyColdStakes(bool fOnlyColdStakes)\n{\n this->fOnlyColdStaking = fOnlyColdStakes;\n invalidateFilter();\n}\n\nint TransactionFilterProxy::rowCount(const QModelIndex& parent) const\n{\n if (limitRows != -1) {\n return std::min(QSortFilterProxyModel::rowCount(parent), limitRows);\n } else {\n return QSortFilterProxyModel::rowCount(parent);\n }\n}\n\nbool TransactionFilterProxy::isOrphan(const int status, const int type)\n{\n return ( (type == TransactionRecord::Generated || type == TransactionRecord::StakeMint ||\n type == TransactionRecord::StakeZPIV || type == TransactionRecord::MNReward)\n && (status == TransactionStatus::Conflicted || status == TransactionStatus::NotAccepted) );\n}\n\nbool TransactionFilterProxy::isZcTx(int type) const {\n return (type == TransactionRecord::ZerocoinMint || type == TransactionRecord::ZerocoinSpend || type == TransactionRecord::ZerocoinSpend_Change_zPiv\n || type == TransactionRecord::ZerocoinSpend_FromMe || type == TransactionRecord::RecvFromZerocoinSpend);\n}\n\nbool TransactionFilterProxy::isStakeTx(int type) const {\n return type == TransactionRecord::StakeMint || type == TransactionRecord::Generated || type == TransactionRecord::StakeZPIV || type == TransactionRecord::StakeDelegated;\n}\n\nbool TransactionFilterProxy::isColdStake(int type) const {\n return type == TransactionRecord::P2CSDelegation || type == TransactionRecord::P2CSDelegationSent || type == TransactionRecord::P2CSDelegationSentOwner || type == TransactionRecord::StakeDelegated || type == TransactionRecord::StakeHot;\n}\n\n\/*QVariant TransactionFilterProxy::dataFromSourcePos(int sourceRow, int role) const {\n QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);\n return index.data(index, role);\n}\n *\/\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\n\/*** Copyright (c), The Regents of the University of California ***\n *** For more information please refer to files in the COPYRIGHT directory ***\/\n\/* rsStructFileBundle.c. See structFileBundle.h for a description of\n * this API call.*\/\n\n#include \"reFuncDefs.hpp\"\n#include \"apiHeaderAll.hpp\"\n#include \"objMetaOpr.hpp\"\n#include \"dataObjOpr.hpp\"\n#include \"physPath.hpp\"\n#include \"miscServerFunct.hpp\"\n#include \"rcGlobalExtern.hpp\"\n#include \"reGlobalsExtern.hpp\"\n\n\/\/ =-=-=-=-=-=-=-\n#include \"irods_log.hpp\"\n#include \"irods_file_object.hpp\"\n#include \"irods_stacktrace.hpp\"\n#include \"irods_resource_redirect.hpp\"\n\nint\nrsStructFileBundle( rsComm_t *rsComm,\n structFileExtAndRegInp_t *structFileBundleInp ) {\n int status;\n rodsServerHost_t *rodsServerHost;\n int remoteFlag;\n\/\/ rodsHostAddr_t rescAddr;\n dataObjInp_t dataObjInp;\n\/\/ rescGrpInfo_t *rescGrpInfo = NULL;\n\n memset( &dataObjInp, 0, sizeof( dataObjInp ) );\n rstrcpy( dataObjInp.objPath, structFileBundleInp->objPath,\n MAX_NAME_LEN );\n\n remoteFlag = getAndConnRemoteZone( rsComm, &dataObjInp, &rodsServerHost,\n REMOTE_CREATE );\n\n if ( remoteFlag < 0 ) {\n return ( remoteFlag );\n }\n else if ( remoteFlag == REMOTE_HOST ) {\n status = rcStructFileBundle( rodsServerHost->conn,\n structFileBundleInp );\n return status;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ working on the \"home zone\", determine if we need to redirect to a different\n \/\/ server in this zone for this operation. if there is a RESC_HIER_STR_KW then\n \/\/ we know that the redirection decision has already been made\n std::string hier;\n int local = LOCAL_HOST;\n rodsServerHost_t* host = 0;\n dataObjInp_t data_inp;\n bzero( &data_inp, sizeof( data_inp ) );\n rstrcpy( data_inp.objPath, structFileBundleInp->objPath, MAX_NAME_LEN );\n copyKeyValPairStruct( &structFileBundleInp->condInput, &data_inp.condInput );\n if ( getValByKey( &structFileBundleInp->condInput, RESC_HIER_STR_KW ) == NULL ) {\n irods::error ret = irods::resource_redirect( irods::CREATE_OPERATION, rsComm,\n &data_inp, hier, host, local );\n if ( !ret.ok() ) {\n std::stringstream msg;\n msg << \"rsStructFileBundle :: failed in irods::resource_redirect for [\";\n msg << &data_inp.objPath << \"]\";\n irods::log( PASSMSG( msg.str(), ret ) );\n return ret.code();\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ we resolved the redirect and have a host, set the hier str for subsequent\n \/\/ api calls, etc.\n addKeyVal( &structFileBundleInp->condInput, RESC_HIER_STR_KW, hier.c_str() );\n\n } \/\/ if keyword\n\n if ( LOCAL_HOST == local ) {\n status = _rsStructFileBundle( rsComm, structFileBundleInp );\n }\n else {\n status = rcStructFileBundle( host->conn, structFileBundleInp );\n } \/\/ else remote host\n\n\n return status;\n}\n\nint _rsStructFileBundle( rsComm_t* rsComm,\n structFileExtAndRegInp_t* structFileBundleInp ) {\n int status;\n int handleInx;\n char phyBunDir[MAX_NAME_LEN];\n char tmpPath[MAX_NAME_LEN];\n int l1descInx;\n char* dataType = 0; \/\/ JMC - backport 4664\n openedDataObjInp_t dataObjCloseInp;\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ create an empty data obj\n dataObjInp_t dataObjInp;\n memset( &dataObjInp, 0, sizeof( dataObjInp ) );\n dataObjInp.openFlags = O_WRONLY;\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ get the data type of the structured file\n dataType = getValByKey( &structFileBundleInp->condInput, DATA_TYPE_KW );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ ensure that the file name will end in .zip, if necessary\n if ( dataType != NULL && strstr( dataType, ZIP_DT_STR ) != NULL ) {\n int len = strlen( structFileBundleInp->objPath );\n if ( strcmp( &structFileBundleInp->objPath[len - 4], \".zip\" ) != 0 ) {\n strcat( structFileBundleInp->objPath, \".zip\" );\n }\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ capture the object path in the data obj struct\n rstrcpy( dataObjInp.objPath, structFileBundleInp->objPath, MAX_NAME_LEN );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ replicate the condInput. may have resource input\n replKeyVal( &structFileBundleInp->condInput, &dataObjInp.condInput );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ open the file if we are in an add operation, otherwise create the new file\n if ( ( structFileBundleInp->oprType & ADD_TO_TAR_OPR ) != 0 ) { \/\/ JMC - backport 4643\n l1descInx = rsDataObjOpen( rsComm, &dataObjInp );\n\n }\n else {\n l1descInx = rsDataObjCreate( rsComm, &dataObjInp );\n\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ error check create \/ open\n if ( l1descInx < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: rsDataObjCreate of %s error. status = %d\",\n dataObjInp.objPath, l1descInx );\n return l1descInx;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ FIXME :: Why, when we replicate them above?\n clearKeyVal( &dataObjInp.condInput ); \/\/ JMC - backport 4637\n \/\/ ???? l3Close (rsComm, l1descInx);\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ zip does not like a zero length file as target\n \/\/L1desc[ l1descInx ].l3descInx = 0;\n \/\/if( dataType != NULL && strstr( dataType, ZIP_DT_STR ) != NULL ) {\n \/\/ if( ( structFileBundleInp->oprType & ADD_TO_TAR_OPR) == 0 ) { \/\/ JMC - backport 4643\n \/\/ l3Unlink( rsComm, L1desc[l1descInx].dataObjInfo );\n \/\/ }\n \/\/}\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ check object permissions \/ stat\n chkObjPermAndStat_t chkObjPermAndStatInp;\n memset( &chkObjPermAndStatInp, 0, sizeof( chkObjPermAndStatInp ) );\n rstrcpy( chkObjPermAndStatInp.objPath, structFileBundleInp->collection, MAX_NAME_LEN );\n chkObjPermAndStatInp.flags = CHK_COLL_FOR_BUNDLE_OPR;\n addKeyVal( &chkObjPermAndStatInp.condInput, RESC_NAME_KW, L1desc[l1descInx].dataObjInfo->rescName );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ get the resc hier string\n std::string resc_hier;\n char* resc_hier_ptr = getValByKey( &structFileBundleInp->condInput, RESC_HIER_STR_KW );\n if ( !resc_hier_ptr ) {\n rodsLog( LOG_NOTICE, \"_rsStructFileBundle :: RESC_HIER_STR_KW is NULL\" );\n }\n else {\n addKeyVal( &chkObjPermAndStatInp.condInput, RESC_HIER_STR_KW, resc_hier_ptr );\n resc_hier = resc_hier_ptr;\n }\n\n status = rsChkObjPermAndStat( rsComm, &chkObjPermAndStatInp );\n if ( status < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: rsChkObjPermAndStat of %s error. stat = %d\",\n chkObjPermAndStatInp.objPath, status );\n dataObjCloseInp.l1descInx = l1descInx;\n rsDataObjClose( rsComm, &dataObjCloseInp );\n return status;\n }\n\n clearKeyVal( &chkObjPermAndStatInp.condInput );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ create the special hidden directory where the bundling happens\n createPhyBundleDir( rsComm, L1desc[ l1descInx ].dataObjInfo->filePath, phyBunDir, L1desc[ l1descInx ].dataObjInfo->rescHier );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ build a collection open input structure\n collInp_t collInp;\n bzero( &collInp, sizeof( collInp ) );\n collInp.flags = RECUR_QUERY_FG | VERY_LONG_METADATA_FG | NO_TRIM_REPL_FG | INCLUDE_CONDINPUT_IN_QUERY;\n rstrcpy( collInp.collName, structFileBundleInp->collection, MAX_NAME_LEN );\n addKeyVal( &collInp.condInput, RESC_NAME_KW, L1desc[ l1descInx ].dataObjInfo->rescName );\n\n rodsLog( LOG_NOTICE, \"rsStructFileBundle: calling rsOpenCollection for [%s]\", structFileBundleInp->collection );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ open the collection from which we will bundle\n handleInx = rsOpenCollection( rsComm, &collInp );\n if ( handleInx < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: rsOpenCollection of %s error. status = %d\",\n collInp.collName, handleInx );\n rmdir( phyBunDir );\n return handleInx;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ preserve the collection path?\n int collLen = 0;\n if ( ( structFileBundleInp->oprType & PRESERVE_COLL_PATH ) != 0 ) {\n \/\/ =-=-=-=-=-=-=-\n \/\/ preserve the last entry of the coll path\n char* tmpPtr = collInp.collName;\n int tmpLen = 0;\n collLen = 0;\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ find length to the last '\/'\n while ( *tmpPtr != '\\0' ) {\n if ( *tmpPtr == '\/' ) {\n collLen = tmpLen;\n }\n\n tmpLen++;\n tmpPtr++;\n }\n\n }\n else {\n collLen = strlen( collInp.collName );\n\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ preserve the collection path?\n collEnt_t* collEnt = NULL;\n while ( ( status = rsReadCollection( rsComm, &handleInx, &collEnt ) ) >= 0 ) {\n if ( NULL == collEnt ) { \/\/ JMC cppcheck - nullptr\n rodsLog( LOG_ERROR, \"rsStructFileBundle: collEnt is NULL\" );\n continue;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ entry is a data object\n if ( collEnt->objType == DATA_OBJ_T ) {\n if ( collEnt->collName[collLen] == '\\0' ) {\n snprintf(\n tmpPath,\n MAX_NAME_LEN,\n \"%s\/%s\",\n phyBunDir,\n collEnt->dataName );\n }\n else {\n snprintf(\n tmpPath,\n MAX_NAME_LEN, \"%s\/%s\/%s\",\n phyBunDir,\n collEnt->collName + collLen + 1,\n collEnt->dataName );\n mkDirForFilePath(\n rsComm,\n phyBunDir,\n tmpPath,\n collEnt->resc_hier,\n getDefDirMode() );\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ filter out any possible replicas that are not on this resource\n if ( resc_hier == collEnt->resc_hier ) {\n \/\/ =-=-=-=-=-=-=-\n \/\/ add a link\n status = link( collEnt->phyPath, tmpPath );\n if ( status < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: link error %s to %s. errno = %d\",\n collEnt->phyPath, tmpPath, errno );\n rmLinkedFilesInUnixDir( phyBunDir );\n rmdir( phyBunDir );\n return ( UNIX_FILE_LINK_ERR - errno );\n }\n else {\n \/\/rodsLog( LOG_NOTICE, \"_rsStructFileBundle - LINK [%s] on resc [%s]\", collEnt->phyPath, collEnt->resc_hier );\n }\n }\n else {\n \/\/rodsLog( LOG_NOTICE, \"_rsStructFileBundle - skipping [%s] on resc [%s]\", collEnt->phyPath, collEnt->resc_hier );\n }\n }\n else {\n \/\/ =-=-=-=-=-=-=-\n \/\/ entry is a collection\n if ( ( int ) strlen( collEnt->collName ) + 1 <= collLen ) {\n free( collEnt );\n continue;\n }\n snprintf( tmpPath, MAX_NAME_LEN, \"%s\/%s\", phyBunDir, collEnt->collName + collLen );\n mkFileDirR( rsComm, phyBunDir, tmpPath, collEnt->resc_hier, getDefDirMode() );\n } \/\/ else\n\n if ( collEnt != NULL ) {\n free( collEnt );\n collEnt = NULL;\n }\n\n } \/\/ while\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ clean up key vals and close the collection\n clearKeyVal( &collInp.condInput );\n rsCloseCollection( rsComm, &handleInx );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ call the helper function to do the actual bundling\n status = phyBundle( rsComm, L1desc[l1descInx].dataObjInfo, phyBunDir,\n collInp.collName, structFileBundleInp->oprType ); \/\/ JMC - backport 4643\n\n int savedStatus = 0;\n if ( status < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: phyBundle of %s error. stat = %d\",\n L1desc[ l1descInx ].dataObjInfo->objPath, status );\n L1desc[ l1descInx ].bytesWritten = 0;\n savedStatus = status;\n }\n else {\n \/\/ mark it was written so the size would be adjusted\n L1desc[ l1descInx ].bytesWritten = 1;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ clean up after the bundle directory\n rmLinkedFilesInUnixDir( phyBunDir );\n rmdir( phyBunDir );\n\n dataObjCloseInp.l1descInx = l1descInx;\n status = rsDataObjClose( rsComm, &dataObjCloseInp );\n if ( status >= 0 ) {\n return savedStatus;\n }\n\n return ( status );\n}\n\nint\nremoteStructFileBundle( rsComm_t *rsComm,\n structFileExtAndRegInp_t *structFileBundleInp, rodsServerHost_t *rodsServerHost ) {\n int status;\n\n if ( rodsServerHost == NULL ) {\n rodsLog( LOG_NOTICE,\n \"remoteStructFileBundle: Invalid rodsServerHost\" );\n return SYS_INVALID_SERVER_HOST;\n }\n\n if ( ( status = svrToSvrConnect( rsComm, rodsServerHost ) ) < 0 ) {\n return status;\n }\n\n status = rcStructFileBundle( rodsServerHost->conn, structFileBundleInp );\n return status;\n}\n\n<commit_msg>[#2182] use local resc_hier for destination<commit_after>\/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\n\/*** Copyright (c), The Regents of the University of California ***\n *** For more information please refer to files in the COPYRIGHT directory ***\/\n\/* rsStructFileBundle.c. See structFileBundle.h for a description of\n * this API call.*\/\n\n#include \"reFuncDefs.hpp\"\n#include \"apiHeaderAll.hpp\"\n#include \"objMetaOpr.hpp\"\n#include \"dataObjOpr.hpp\"\n#include \"physPath.hpp\"\n#include \"miscServerFunct.hpp\"\n#include \"rcGlobalExtern.hpp\"\n#include \"reGlobalsExtern.hpp\"\n\n\/\/ =-=-=-=-=-=-=-\n#include \"irods_log.hpp\"\n#include \"irods_file_object.hpp\"\n#include \"irods_stacktrace.hpp\"\n#include \"irods_resource_redirect.hpp\"\n\nint\nrsStructFileBundle( rsComm_t *rsComm,\n structFileExtAndRegInp_t *structFileBundleInp ) {\n int status;\n rodsServerHost_t *rodsServerHost;\n int remoteFlag;\n\/\/ rodsHostAddr_t rescAddr;\n dataObjInp_t dataObjInp;\n\/\/ rescGrpInfo_t *rescGrpInfo = NULL;\n\n memset( &dataObjInp, 0, sizeof( dataObjInp ) );\n rstrcpy( dataObjInp.objPath, structFileBundleInp->objPath,\n MAX_NAME_LEN );\n\n remoteFlag = getAndConnRemoteZone( rsComm, &dataObjInp, &rodsServerHost,\n REMOTE_CREATE );\n\n if ( remoteFlag < 0 ) {\n return ( remoteFlag );\n }\n else if ( remoteFlag == REMOTE_HOST ) {\n status = rcStructFileBundle( rodsServerHost->conn,\n structFileBundleInp );\n return status;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ working on the \"home zone\", determine if we need to redirect to a different\n \/\/ server in this zone for this operation. if there is a RESC_HIER_STR_KW then\n \/\/ we know that the redirection decision has already been made\n std::string hier;\n int local = LOCAL_HOST;\n rodsServerHost_t* host = 0;\n dataObjInp_t data_inp;\n bzero( &data_inp, sizeof( data_inp ) );\n rstrcpy( data_inp.objPath, structFileBundleInp->objPath, MAX_NAME_LEN );\n copyKeyValPairStruct( &structFileBundleInp->condInput, &data_inp.condInput );\n if ( getValByKey( &structFileBundleInp->condInput, RESC_HIER_STR_KW ) == NULL ) {\n irods::error ret = irods::resource_redirect( irods::CREATE_OPERATION, rsComm,\n &data_inp, hier, host, local );\n if ( !ret.ok() ) {\n std::stringstream msg;\n msg << \"rsStructFileBundle :: failed in irods::resource_redirect for [\";\n msg << &data_inp.objPath << \"]\";\n irods::log( PASSMSG( msg.str(), ret ) );\n return ret.code();\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ we resolved the redirect and have a host, set the hier str for subsequent\n \/\/ api calls, etc.\n addKeyVal( &structFileBundleInp->condInput, RESC_HIER_STR_KW, hier.c_str() );\n\n } \/\/ if keyword\n\n if ( LOCAL_HOST == local ) {\n status = _rsStructFileBundle( rsComm, structFileBundleInp );\n }\n else {\n status = rcStructFileBundle( host->conn, structFileBundleInp );\n } \/\/ else remote host\n\n\n return status;\n}\n\nint _rsStructFileBundle( rsComm_t* rsComm,\n structFileExtAndRegInp_t* structFileBundleInp ) {\n int status;\n int handleInx;\n char phyBunDir[MAX_NAME_LEN];\n char tmpPath[MAX_NAME_LEN];\n int l1descInx;\n char* dataType = 0; \/\/ JMC - backport 4664\n openedDataObjInp_t dataObjCloseInp;\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ create an empty data obj\n dataObjInp_t dataObjInp;\n memset( &dataObjInp, 0, sizeof( dataObjInp ) );\n dataObjInp.openFlags = O_WRONLY;\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ get the data type of the structured file\n dataType = getValByKey( &structFileBundleInp->condInput, DATA_TYPE_KW );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ ensure that the file name will end in .zip, if necessary\n if ( dataType != NULL && strstr( dataType, ZIP_DT_STR ) != NULL ) {\n int len = strlen( structFileBundleInp->objPath );\n if ( strcmp( &structFileBundleInp->objPath[len - 4], \".zip\" ) != 0 ) {\n strcat( structFileBundleInp->objPath, \".zip\" );\n }\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ capture the object path in the data obj struct\n rstrcpy( dataObjInp.objPath, structFileBundleInp->objPath, MAX_NAME_LEN );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ replicate the condInput. may have resource input\n replKeyVal( &structFileBundleInp->condInput, &dataObjInp.condInput );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ open the file if we are in an add operation, otherwise create the new file\n if ( ( structFileBundleInp->oprType & ADD_TO_TAR_OPR ) != 0 ) { \/\/ JMC - backport 4643\n l1descInx = rsDataObjOpen( rsComm, &dataObjInp );\n\n }\n else {\n l1descInx = rsDataObjCreate( rsComm, &dataObjInp );\n\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ error check create \/ open\n if ( l1descInx < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: rsDataObjCreate of %s error. status = %d\",\n dataObjInp.objPath, l1descInx );\n return l1descInx;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ FIXME :: Why, when we replicate them above?\n clearKeyVal( &dataObjInp.condInput ); \/\/ JMC - backport 4637\n \/\/ ???? l3Close (rsComm, l1descInx);\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ zip does not like a zero length file as target\n \/\/L1desc[ l1descInx ].l3descInx = 0;\n \/\/if( dataType != NULL && strstr( dataType, ZIP_DT_STR ) != NULL ) {\n \/\/ if( ( structFileBundleInp->oprType & ADD_TO_TAR_OPR) == 0 ) { \/\/ JMC - backport 4643\n \/\/ l3Unlink( rsComm, L1desc[l1descInx].dataObjInfo );\n \/\/ }\n \/\/}\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ check object permissions \/ stat\n chkObjPermAndStat_t chkObjPermAndStatInp;\n memset( &chkObjPermAndStatInp, 0, sizeof( chkObjPermAndStatInp ) );\n rstrcpy( chkObjPermAndStatInp.objPath, structFileBundleInp->collection, MAX_NAME_LEN );\n chkObjPermAndStatInp.flags = CHK_COLL_FOR_BUNDLE_OPR;\n addKeyVal( &chkObjPermAndStatInp.condInput, RESC_NAME_KW, L1desc[l1descInx].dataObjInfo->rescName );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ get the resc hier string\n std::string resc_hier;\n char* resc_hier_ptr = getValByKey( &structFileBundleInp->condInput, RESC_HIER_STR_KW );\n if ( !resc_hier_ptr ) {\n rodsLog( LOG_NOTICE, \"_rsStructFileBundle :: RESC_HIER_STR_KW is NULL\" );\n }\n else {\n addKeyVal( &chkObjPermAndStatInp.condInput, RESC_HIER_STR_KW, resc_hier_ptr );\n resc_hier = resc_hier_ptr;\n }\n\n status = rsChkObjPermAndStat( rsComm, &chkObjPermAndStatInp );\n if ( status < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: rsChkObjPermAndStat of %s error. stat = %d\",\n chkObjPermAndStatInp.objPath, status );\n dataObjCloseInp.l1descInx = l1descInx;\n rsDataObjClose( rsComm, &dataObjCloseInp );\n return status;\n }\n\n clearKeyVal( &chkObjPermAndStatInp.condInput );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ create the special hidden directory where the bundling happens\n createPhyBundleDir( rsComm, L1desc[ l1descInx ].dataObjInfo->filePath, phyBunDir, L1desc[ l1descInx ].dataObjInfo->rescHier );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ build a collection open input structure\n collInp_t collInp;\n bzero( &collInp, sizeof( collInp ) );\n collInp.flags = RECUR_QUERY_FG | VERY_LONG_METADATA_FG | NO_TRIM_REPL_FG | INCLUDE_CONDINPUT_IN_QUERY;\n rstrcpy( collInp.collName, structFileBundleInp->collection, MAX_NAME_LEN );\n addKeyVal( &collInp.condInput, RESC_NAME_KW, L1desc[ l1descInx ].dataObjInfo->rescName );\n\n rodsLog( LOG_NOTICE, \"rsStructFileBundle: calling rsOpenCollection for [%s]\", structFileBundleInp->collection );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ open the collection from which we will bundle\n handleInx = rsOpenCollection( rsComm, &collInp );\n if ( handleInx < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: rsOpenCollection of %s error. status = %d\",\n collInp.collName, handleInx );\n rmdir( phyBunDir );\n return handleInx;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ preserve the collection path?\n int collLen = 0;\n if ( ( structFileBundleInp->oprType & PRESERVE_COLL_PATH ) != 0 ) {\n \/\/ =-=-=-=-=-=-=-\n \/\/ preserve the last entry of the coll path\n char* tmpPtr = collInp.collName;\n int tmpLen = 0;\n collLen = 0;\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ find length to the last '\/'\n while ( *tmpPtr != '\\0' ) {\n if ( *tmpPtr == '\/' ) {\n collLen = tmpLen;\n }\n\n tmpLen++;\n tmpPtr++;\n }\n\n }\n else {\n collLen = strlen( collInp.collName );\n\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ preserve the collection path?\n collEnt_t* collEnt = NULL;\n while ( ( status = rsReadCollection( rsComm, &handleInx, &collEnt ) ) >= 0 ) {\n if ( NULL == collEnt ) { \/\/ JMC cppcheck - nullptr\n rodsLog( LOG_ERROR, \"rsStructFileBundle: collEnt is NULL\" );\n continue;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ entry is a data object\n if ( collEnt->objType == DATA_OBJ_T ) {\n if ( collEnt->collName[collLen] == '\\0' ) {\n snprintf(\n tmpPath,\n MAX_NAME_LEN,\n \"%s\/%s\",\n phyBunDir,\n collEnt->dataName );\n }\n else {\n snprintf(\n tmpPath,\n MAX_NAME_LEN, \"%s\/%s\/%s\",\n phyBunDir,\n collEnt->collName + collLen + 1,\n collEnt->dataName );\n mkDirForFilePath(\n rsComm,\n phyBunDir,\n tmpPath,\n collEnt->resc_hier,\n getDefDirMode() );\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ filter out any possible replicas that are not on this resource\n if ( resc_hier == collEnt->resc_hier ) {\n \/\/ =-=-=-=-=-=-=-\n \/\/ add a link\n status = link( collEnt->phyPath, tmpPath );\n if ( status < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: link error %s to %s. errno = %d\",\n collEnt->phyPath, tmpPath, errno );\n rmLinkedFilesInUnixDir( phyBunDir );\n rmdir( phyBunDir );\n return ( UNIX_FILE_LINK_ERR - errno );\n }\n else {\n \/\/rodsLog( LOG_NOTICE, \"_rsStructFileBundle - LINK [%s] on resc [%s]\", collEnt->phyPath, collEnt->resc_hier );\n }\n }\n else {\n \/\/rodsLog( LOG_NOTICE, \"_rsStructFileBundle - skipping [%s] on resc [%s]\", collEnt->phyPath, collEnt->resc_hier );\n }\n }\n else {\n \/\/ =-=-=-=-=-=-=-\n \/\/ entry is a collection\n if ( ( int ) strlen( collEnt->collName ) + 1 <= collLen ) {\n free( collEnt );\n continue;\n }\n snprintf( tmpPath, MAX_NAME_LEN, \"%s\/%s\", phyBunDir, collEnt->collName + collLen );\n mkFileDirR( rsComm, phyBunDir, tmpPath, resc_hier.c_str(), getDefDirMode() );\n } \/\/ else\n\n if ( collEnt != NULL ) {\n free( collEnt );\n collEnt = NULL;\n }\n\n } \/\/ while\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ clean up key vals and close the collection\n clearKeyVal( &collInp.condInput );\n rsCloseCollection( rsComm, &handleInx );\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ call the helper function to do the actual bundling\n status = phyBundle( rsComm, L1desc[l1descInx].dataObjInfo, phyBunDir,\n collInp.collName, structFileBundleInp->oprType ); \/\/ JMC - backport 4643\n\n int savedStatus = 0;\n if ( status < 0 ) {\n rodsLog( LOG_ERROR, \"rsStructFileBundle: phyBundle of %s error. stat = %d\",\n L1desc[ l1descInx ].dataObjInfo->objPath, status );\n L1desc[ l1descInx ].bytesWritten = 0;\n savedStatus = status;\n }\n else {\n \/\/ mark it was written so the size would be adjusted\n L1desc[ l1descInx ].bytesWritten = 1;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ clean up after the bundle directory\n rmLinkedFilesInUnixDir( phyBunDir );\n rmdir( phyBunDir );\n\n dataObjCloseInp.l1descInx = l1descInx;\n status = rsDataObjClose( rsComm, &dataObjCloseInp );\n if ( status >= 0 ) {\n return savedStatus;\n }\n\n return ( status );\n}\n\nint\nremoteStructFileBundle( rsComm_t *rsComm,\n structFileExtAndRegInp_t *structFileBundleInp, rodsServerHost_t *rodsServerHost ) {\n int status;\n\n if ( rodsServerHost == NULL ) {\n rodsLog( LOG_NOTICE,\n \"remoteStructFileBundle: Invalid rodsServerHost\" );\n return SYS_INVALID_SERVER_HOST;\n }\n\n if ( ( status = svrToSvrConnect( rsComm, rodsServerHost ) ) < 0 ) {\n return status;\n }\n\n status = rcStructFileBundle( rodsServerHost->conn, structFileBundleInp );\n return status;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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 * @file\n * @brief IronBee++ --- ParserSuite adaptors\n *\n * This file provides code for adapting ParserSuite results to IronBee++.\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n *\/\n\n#ifndef __IBPP__PARSERSUITE_ADAPTORS__\n#define __IBPP__PARSERSUITE_ADAPTORS__\n\n#include <modules\/parser_suite.hpp>\n\n#include <ironbeepp\/parsed_header.hpp>\n\n#include <boost\/iterator\/transform_iterator.hpp>\n\nnamespace IronBee {\n\n\/**\n * Functional to translate a ParserSuite header to a ParsedHeader.\n *\n * Headers with multiple values (extended headers) will have their values\n * concatenated. Headers with a single value will have their header directly\n * aliased.\n **\/\nclass PSHeaderToParsedHeader :\n public std::unary_function<\n const ParserSuite::parse_headers_result_t::header_t&,\n ParsedHeader\n >\n{\npublic:\n \/**\n * Constructor.\n *\n * @param[in] memory_pool Memory pool to use for allocations.\n **\/\n explicit\n PSHeaderToParsedHeader(MemoryPool memory_pool);\n\n \/**\n * Call operator.\n *\n * @param[in] header Header to translate.\n * @return ParsedHeader aliasing members of @a header.\n **\/\n ParsedHeader operator()(\n const ParserSuite::parse_headers_result_t::header_t& header\n ) const;\n\nprivate:\n \/\/! Memory pool to allocate bytestrings and ParserHeader from.\n MemoryPool m_memory_pool;\n};\n\n\/\/! Type of iterator from adapt_headers().\ntypedef boost::transform_iterator<\n PSHeaderToParsedHeader,\n ParserSuite::parse_headers_result_t::headers_t::const_iterator\n> psheader_to_parsed_header_const_iterator;\n\n\/\/! Range of @ref parsed_headers_const_iterator.\ntypedef boost::iterator_range<\n psheader_to_parsed_header_const_iterator\n> psheader_to_parsed_header_const_range_t;\n\n\/**\n * Adapt @ref parse_header_result_t::headers_t to a sequence of ParsedHeader.\n *\n * @param[in] memory_pool Memory pool to use.\n * @param[in] headers Headers to adapt.\n * @return Range of ParsedHeader.\n **\/\npsheader_to_parsed_header_const_range_t psheaders_to_parsed_headers(\n IronBee::MemoryPool memory_pool,\n const ParserSuite::parse_headers_result_t::headers_t& headers\n);\n\n} \/\/ IronBee\n\n#endif\n<commit_msg>ironbeepp\/parser_suite_adaptors.hpp: Doxygen fixes.<commit_after>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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 * @file\n * @brief IronBee++ --- ParserSuite adaptors\n *\n * This file provides code for adapting ParserSuite results to IronBee++.\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n *\/\n\n#ifndef __IBPP__PARSERSUITE_ADAPTORS__\n#define __IBPP__PARSERSUITE_ADAPTORS__\n\n#include <modules\/parser_suite.hpp>\n\n#include <ironbeepp\/parsed_header.hpp>\n\n#include <boost\/iterator\/transform_iterator.hpp>\n\nnamespace IronBee {\n\n\/**\n * Functional to translate a ParserSuite header to a ParsedHeader.\n *\n * Headers with multiple values (extended headers) will have their values\n * concatenated. Headers with a single value will have their header directly\n * aliased.\n **\/\nclass PSHeaderToParsedHeader :\n public std::unary_function<\n const ParserSuite::parse_headers_result_t::header_t&,\n ParsedHeader\n >\n{\npublic:\n \/**\n * Constructor.\n *\n * @param[in] memory_pool Memory pool to use for allocations.\n **\/\n explicit\n PSHeaderToParsedHeader(MemoryPool memory_pool);\n\n \/**\n * Call operator.\n *\n * @param[in] header Header to translate.\n * @return ParsedHeader aliasing members of @a header.\n **\/\n ParsedHeader operator()(\n const ParserSuite::parse_headers_result_t::header_t& header\n ) const;\n\nprivate:\n \/\/! Memory pool to allocate bytestrings and ParserHeader from.\n MemoryPool m_memory_pool;\n};\n\n\/\/! Type of iterator from adapt_headers().\ntypedef boost::transform_iterator<\n PSHeaderToParsedHeader,\n ParserSuite::parse_headers_result_t::headers_t::const_iterator\n> psheader_to_parsed_header_const_iterator;\n\n\/\/! Range of @ref psheader_to_parsed_header_const_iterator.\ntypedef boost::iterator_range<\n psheader_to_parsed_header_const_iterator\n> psheader_to_parsed_header_const_range_t;\n\n\/**\n * Adapt ParserSuite::parse_headers_result_t::headers_t to a sequence of\n * ParsedHeader.\n *\n * @param[in] memory_pool Memory pool to use.\n * @param[in] headers Headers to adapt.\n * @return Range of ParsedHeader.\n **\/\npsheader_to_parsed_header_const_range_t psheaders_to_parsed_headers(\n IronBee::MemoryPool memory_pool,\n const ParserSuite::parse_headers_result_t::headers_t& headers\n);\n\n} \/\/ IronBee\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <QtCore>\n#include <QDebug>\n#include <QCryptographicHash>\n\n\/\/#include <QApplication>\n#include <iostream>\n\nusing namespace std;\n\nvoid test()\n{\n QProcess process;\n process.start(\"du -chs \/home\/rasmus\/gcode\/snippet\/\");\n process.waitForFinished(-1); \/\/ will wait forever until finished\n\n QString stdout = process.readAllStandardOutput();\n QString stderr = process.readAllStandardError();\n\n qDebug() << \"stdout: \" << stdout;\n qDebug() << \"stderr: \" << stderr;\n}\n\n\nQString get_info()\n{\n QByteArray user = qgetenv(\"USER\");\n QByteArray host = qgetenv(\"HOSTNAME\");\n QString s = QString(user) + \"@\" + QString(host) + \" \";\n s = s + QString(__DATE__) + \" \" + QString(__TIME__);\n \/\/qDebug() << \"s: \" << s;\n\n return s;\n}\n\nQString getFilenameHash(const QString& fn)\n{\n QCryptographicHash hash( QCryptographicHash::Md5 );\n hash.addData(fn.toStdString().c_str(), fn.length());\n QString result = hash.result().toHex().data();\n return result;\n}\n\n\/\/ ifn: input video filename\nQString extractOneFrameFromVideo(const QString& ifn)\n{\n QString ofn = getFilenameHash(ifn);\n QString cmd = QString(\"avconv -ss 0:0:10 -i %1 -vsync 1 -t 0.01 %2.png\")\n .arg(ifn).arg(ofn);\n\n QProcess process;\n process.start(cmd);\n \/\/ will it block???\n process.waitForFinished(-1); \/\/ will wait forever until finished\n\n \/\/ just for debug\n \/\/ QString stdout = process.readAllStandardOutput();\n \/\/ QString stderr = process.readAllStandardError();\n \/\/ qDebug() << \"stdout: \" << stdout;\n \/\/ qDebug() << \"stderr: \" << stderr;\n \/\/ just for debug\n\n return ofn;\n}\n\n#include <iostream>\n\nvoid print_sizeof(const QString& msg, size_t size)\n{\n qDebug() << \"sizeof\" << msg << \"is\" << size;\n}\n\nvoid print_sz(const std::string msg, size_t size)\n{\n using namespace std;\n cout << \"[STL] msg: \" << msg << \", sizeof: \" << size << endl;\n}\n\nvoid test_sizeof()\n{\n using namespace std;\n\n const char* hello = \"hello\";\n const char vocano[] = \"vocano\";\n const string car = \"car\";\n const QString quickfox = \"quickfox\";\n\n print_sizeof(hello, sizeof(hello));\n print_sizeof(vocano, sizeof(vocano));\n print_sz(car, sizeof(car));\n print_sizeof(quickfox, sizeof(quickfox));\n}\n\nint main(int argc, char *argv[])\n{\n Q_UNUSED(argc);\n Q_UNUSED(argv);\n\n QString fn = \"clip.mp4\";\n qDebug() << \"output: \" << extractOneFrameFromVideo(fn);\n\n test_sizeof();\n\n return 0;\n}\n<commit_msg>UPDATE qt-env, refine output<commit_after>#include <QtCore>\n#include <QDebug>\n#include <QCryptographicHash>\n\n\/\/#include <QApplication>\n#include <iostream>\n\n#define SHOWHEADER() \\\n qDebug() << Q_FUNC_INFO << \"===>\"\n\nusing namespace std;\n\nvoid test()\n{\n QProcess process;\n process.start(\"du -chs \/home\/rasmus\/gcode\/snippet\/\");\n process.waitForFinished(-1); \/\/ will wait forever until finished\n\n QString stdout = process.readAllStandardOutput();\n QString stderr = process.readAllStandardError();\n\n qDebug() << \"stdout: \" << stdout;\n qDebug() << \"stderr: \" << stderr;\n}\n\n\nQString get_info()\n{\n SHOWHEADER();\n\n QByteArray user = qgetenv(\"USER\");\n QByteArray host = qgetenv(\"HOSTNAME\");\n QString s = QString(user) + \"@\" + QString(host) + \" \";\n QString b = QString(__DATE__) + \" \" + QString(__TIME__);\n qDebug() << \"s: \" << s << endl\n << \"b: \" << b;\n\n return s;\n}\n\nQString getFilenameHash(const QString& fn)\n{\n QCryptographicHash hash( QCryptographicHash::Md5 );\n hash.addData(fn.toStdString().c_str(), fn.length());\n QString result = hash.result().toHex().data();\n return result;\n}\n\n\/\/ ifn: input video filename\nQString extractOneFrameFromVideo(const QString& ifn)\n{\n SHOWHEADER();\n\n QString ofn = getFilenameHash(ifn);\n QString cmd = QString(\"avconv -ss 0:0:10 -i %1 -vsync 1 -t 0.01 %2.png\")\n .arg(ifn).arg(ofn);\n\n QProcess process;\n process.start(cmd);\n \/\/ will it block???\n process.waitForFinished(-1); \/\/ will wait forever until finished\n int exitCode = process.exitCode();\n qDebug() << \"exit code:\" << exitCode;\n \/\/ just for debug\n QString stdout = process.readAllStandardOutput();\n QString stderr = process.readAllStandardError();\n qDebug() << \"stdout: \" << stdout;\n qDebug() << \"stderr: \" << stderr;\n \/\/ just for debug\n\n return ofn;\n}\n\nvoid print_sizeof(const QString& msg, size_t size)\n{\n qDebug() << \"sizeof\" << msg << \"is\" << size;\n}\n\nvoid print_sz(const std::string msg, size_t size)\n{\n std::cout << \"[STL] msg: \" << msg << \", sizeof: \" << size << std::endl;\n}\n\nvoid test_sizeof()\n{\n SHOWHEADER();\n\n using namespace std;\n\n const char* hello = \"hello\";\n const char vocano[] = \"vocano\";\n const string car = \"car\";\n const QString quickfox = \"quickfox\";\n\n print_sizeof(hello, sizeof(hello));\n print_sizeof(vocano, sizeof(vocano));\n print_sz(car, sizeof(car));\n print_sizeof(quickfox, sizeof(quickfox));\n}\n\nint main(int argc, char *argv[])\n{\n Q_UNUSED(argc);\n Q_UNUSED(argv);\n\n QString fn = \"clip.mp4\";\n qDebug() << \"md5(fn): \" << extractOneFrameFromVideo(fn);\n\n test_sizeof();\n\n get_info();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file\n\/\/\/ @copyright Copyright (C) 2017, Jonathan Bryan Schmalhofer\n\/\/\/\n\/\/\/ @brief Node to wrap airsim_to_ros to receive Data from AirSim and make available in ROS as ROS-Message\n\/\/\/\n#include <string>\n#include <ros\/ros.h>\n#include <image_transport\/image_transport.h>\n#include \"js_airsim_to_ros_library\/airsim_to_ros_class.h\"\n\nsensor_msgs::Image airsim_image_left_msg airsim_image_right_msg;\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"airsim_to_ros_node\");\n ros::NodeHandle node_handle;\n \n ROS_INFO(\"Starting node\");\n\n js_airsim_to_ros_library::AirSimToRosClass airsim_to_ros(\"tcp:\/\/192.168.178.56:5676\");\n \n ROS_INFO(\"Created airsim_to_ros\");\n\n image_transport::ImageTransport image_transport(node_handle);\n image_transport::Publisher left_stereoimage_chatter = image_transport.advertise(\"\/AirSimLeftStereoImage\", 1);\n image_transport::Publisher right_stereoimage_chatter = image_transport.advertise(\"\/AirSimRightStereoImage\", 1);\n\n std::uint32_t last_sequence_sent = 0;\n while (ros::ok())\n {\n ROS_INFO(\"Waiting for data\");\n int8_t received_return_value = airsim_to_ros.ReceivedMessage();\n if (1 == received_return_value)\n {\n switch (airsim_to_ros.GetImageType())\n {\n case 0: \/\/ Unknown\n break;\n case 1: \/\/ Left\n ROS_INFO(\"Left image received\");\n \/\/ Header\n airsim_image_left_msg.header.seq = airsim_to_ros.GetImageHeaderSeq();\n airsim_image_left_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec();\n airsim_image_left_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec();\n airsim_image_left_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid();\n \/\/ Image\n airsim_image_left_msg.height = airsim_to_ros.GetImageHeight();\n airsim_image_left_msg.width = airsim_to_ros.GetImageWidth();\n airsim_image_left_msg.encoding = airsim_to_ros.GetImageEncoding();\n airsim_image_left_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian();\n airsim_image_left_msg.step = airsim_to_ros.GetImageStep();\n airsim_image_left_msg.data.resize(airsim_to_ros.GetImageDataSize());\n memcpy((char*)(&airsim_image_left_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize());\n break;\n case 2: \/\/ Right\n ROS_INFO(\"Right image received\");\n \/\/ Header\n airsim_image_right_msg.header.seq = airsim_to_ros.GetImageHeaderSeq();\n airsim_image_right_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec();\n airsim_image_right_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec();\n airsim_image_right_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid();\n \/\/ Image\n airsim_image_right_msg.height = airsim_to_ros.GetImageHeight();\n airsim_image_right_msg.width = airsim_to_ros.GetImageWidth();\n airsim_image_right_msg.encoding = airsim_to_ros.GetImageEncoding();\n airsim_image_right_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian();\n airsim_image_right_msg.step = airsim_to_ros.GetImageStep();\n airsim_image_right_msg.data.resize(airsim_to_ros.GetImageDataSize());\n memcpy((char*)(&airsim_image_right_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize());\n break;\n default:\n break;\n }\n \n \/\/ TODO: Introduce Debug Mode\n ROS_INFO(\"Image received\");\n ROS_INFO(\" Image.header.seq %d\", airsim_to_ros.GetImageHeaderSeq());\n ROS_INFO(\" Image.header.stamp.sec %d\", airsim_to_ros.GetImageHeaderStampSec());\n ROS_INFO(\" Image.header.stamp.nsec %d\", airsim_to_ros.GetImageHeaderStampNsec());\n ROS_INFO(\" Image.header.frame_id %s\", airsim_to_ros.GetImageHeaderFrameid());\n ROS_INFO(\" Image.height %d\", airsim_to_ros.GetImageHeight());\n ROS_INFO(\" Image.width %d\", airsim_to_ros.GetImageWidth());\n ROS_INFO(\" Image.encoding %s\", airsim_to_ros.GetImageEncoding());\n ROS_INFO(\" Image.is_bigendian %d\", airsim_to_ros.GetImageIsBigendian());\n ROS_INFO(\" Image.step %d\", airsim_to_ros.GetImageStep());\n ROS_INFO(\" size(Image.data) %d\", airsim_to_ros.GetImageDataSize());\n \n if (\n airsim_image_left_msg.header.seq == airsim_image_right_msg.header.seq \n && airsim_image_left_msg.header.seq > last_sequence_sent\n )\n {\n left_stereoimage_chatter.publish(airsim_image_msg);\n right_stereoimage_chatter.publish(airsim_image_msg);\n }\n }\n else if (-1 == received_return_value)\n {\n ROS_INFO(\"Invalid Image received - did not forward\");\n }\n }\n\n return 0;\n}\n<commit_msg>bugfix: typo in message names for left and right<commit_after>\/\/\/\n\/\/\/ @file\n\/\/\/ @copyright Copyright (C) 2017, Jonathan Bryan Schmalhofer\n\/\/\/\n\/\/\/ @brief Node to wrap airsim_to_ros to receive Data from AirSim and make available in ROS as ROS-Message\n\/\/\/\n#include <string>\n#include <ros\/ros.h>\n#include <image_transport\/image_transport.h>\n#include \"js_airsim_to_ros_library\/airsim_to_ros_class.h\"\n\nsensor_msgs::Image airsim_image_left_msg, airsim_image_right_msg;\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"airsim_to_ros_node\");\n ros::NodeHandle node_handle;\n \n ROS_INFO(\"Starting node\");\n\n js_airsim_to_ros_library::AirSimToRosClass airsim_to_ros(\"tcp:\/\/192.168.178.56:5676\");\n \n ROS_INFO(\"Created airsim_to_ros\");\n\n image_transport::ImageTransport image_transport(node_handle);\n image_transport::Publisher left_stereoimage_chatter = image_transport.advertise(\"\/AirSimLeftStereoImage\", 1);\n image_transport::Publisher right_stereoimage_chatter = image_transport.advertise(\"\/AirSimRightStereoImage\", 1);\n\n std::uint32_t last_sequence_sent = 0;\n while (ros::ok())\n {\n ROS_INFO(\"Waiting for data\");\n int8_t received_return_value = airsim_to_ros.ReceivedMessage();\n if (1 == received_return_value)\n {\n switch (airsim_to_ros.GetImageType())\n {\n case 0: \/\/ Unknown\n break;\n case 1: \/\/ Left\n ROS_INFO(\"Left image received\");\n \/\/ Header\n airsim_image_left_msg.header.seq = airsim_to_ros.GetImageHeaderSeq();\n airsim_image_left_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec();\n airsim_image_left_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec();\n airsim_image_left_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid();\n \/\/ Image\n airsim_image_left_msg.height = airsim_to_ros.GetImageHeight();\n airsim_image_left_msg.width = airsim_to_ros.GetImageWidth();\n airsim_image_left_msg.encoding = airsim_to_ros.GetImageEncoding();\n airsim_image_left_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian();\n airsim_image_left_msg.step = airsim_to_ros.GetImageStep();\n airsim_image_left_msg.data.resize(airsim_to_ros.GetImageDataSize());\n memcpy((char*)(&airsim_image_left_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize());\n break;\n case 2: \/\/ Right\n ROS_INFO(\"Right image received\");\n \/\/ Header\n airsim_image_right_msg.header.seq = airsim_to_ros.GetImageHeaderSeq();\n airsim_image_right_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec();\n airsim_image_right_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec();\n airsim_image_right_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid();\n \/\/ Image\n airsim_image_right_msg.height = airsim_to_ros.GetImageHeight();\n airsim_image_right_msg.width = airsim_to_ros.GetImageWidth();\n airsim_image_right_msg.encoding = airsim_to_ros.GetImageEncoding();\n airsim_image_right_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian();\n airsim_image_right_msg.step = airsim_to_ros.GetImageStep();\n airsim_image_right_msg.data.resize(airsim_to_ros.GetImageDataSize());\n memcpy((char*)(&airsim_image_right_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize());\n break;\n default:\n break;\n }\n \n \/\/ TODO: Introduce Debug Mode\n ROS_INFO(\"Image received\");\n ROS_INFO(\" Image.header.seq %d\", airsim_to_ros.GetImageHeaderSeq());\n ROS_INFO(\" Image.header.stamp.sec %d\", airsim_to_ros.GetImageHeaderStampSec());\n ROS_INFO(\" Image.header.stamp.nsec %d\", airsim_to_ros.GetImageHeaderStampNsec());\n ROS_INFO(\" Image.header.frame_id %s\", airsim_to_ros.GetImageHeaderFrameid());\n ROS_INFO(\" Image.height %d\", airsim_to_ros.GetImageHeight());\n ROS_INFO(\" Image.width %d\", airsim_to_ros.GetImageWidth());\n ROS_INFO(\" Image.encoding %s\", airsim_to_ros.GetImageEncoding());\n ROS_INFO(\" Image.is_bigendian %d\", airsim_to_ros.GetImageIsBigendian());\n ROS_INFO(\" Image.step %d\", airsim_to_ros.GetImageStep());\n ROS_INFO(\" size(Image.data) %d\", airsim_to_ros.GetImageDataSize());\n \n if (\n airsim_image_left_msg.header.seq == airsim_image_right_msg.header.seq \n && airsim_image_left_msg.header.seq > last_sequence_sent\n )\n {\n ROS_INFO(\"Images forwarded\");\n left_stereoimage_chatter.publish(airsim_image_left_msg);\n right_stereoimage_chatter.publish(airsim_image_right_msg);\n }\n }\n else if (-1 == received_return_value)\n {\n ROS_INFO(\"Invalid Image received - did not forward\");\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ComputeViscCoeff.h\"\n\ntemplate<>\nInputParameters validParams<ComputeViscCoeff>()\n{\n InputParameters params = validParams<Material>();\n\n params.addParam<std::string>(\"viscosity_name\", \"FIRST_ORDER\", \"Name of the viscosity definition to use: set to first order by default.\");\n \/\/ Coupled variables\n params.addRequiredCoupledVar(\"h\" , \"h: water height\");\n params.addRequiredCoupledVar(\"q_x\", \"x component of momentum\");\n params.addCoupledVar(\"q_y\", \"y component of momentum\");\n \/\/ Coupled aux variables\n params.addRequiredCoupledVar(\"entropy\", \"entropy function\");\n params.addRequiredCoupledVar(\"F\", \"x-component of the entropy flux \");\n params.addCoupledVar(\"G\", \"y-component of the entropy flux \");\n params.addCoupledVar(\"B\", \"bathymetry data\"); \n params.addParam<Real>(\"gravity\", 9.81, \"gravity magnitude\");\n \/\/ constant parameters:\n \/\/params.addParam<bool>(\"is_first_order\", false, \"if true, use the first-order viscosity coefficient\");\n params.addParam<double>(\"Ce\" , 1.0, \"Coefficient for entropy viscosity\");\n params.addParam<double>(\"Cjump\", 1.0, \"Coefficient for jumps\");\n params.addParam<double>(\"Cmax\" , 0.5, \"Coefficient for first-order viscosity\");\n \/\/ Userobject:\n params.addRequiredParam<UserObjectName>(\"eos\", \"Equation of state\");\n \/\/ PPS names:\n \/\/params.addParam<std::string>(\"press_PPS_name\", \"name of the pps computing pressure\");\n \n return params;\n}\n\nComputeViscCoeff::ComputeViscCoeff(const std::string & name, \n InputParameters parameters) :\n Material(name, parameters),\n \/\/ Declare viscosity types\n _visc_type(\"NONE FIRST_ORDER ENTROPY INVALID\", getParam<std::string>(\"viscosity_name\")), \/\/ Declare variables\n _h(coupledValue(\"h\")),\n _q_x(coupledValue(\"q_x\")),\n _q_y(_mesh.dimension() == 2 ? coupledValue(\"q_y\") : _zero),\n \/\/ entropy:\n _E(coupledValue(\"entropy\")),\n _E_old(coupledValueOld(\"entropy\")),\n _E_older(coupledValueOlder(\"entropy\")),\n \/\/ entropy flux:\n _grad_F(coupledGradient(\"F\")),\n _grad_G(_mesh.dimension() == 2 ? coupledGradient(\"G\") : _grad_zero),\n \/\/ bathymetry:\n _bathymetry(isCoupled(\"B\") ? coupledValue(\"B\") : _zero),\n _gravity(getParam<Real>(\"gravity\")),\n \/\/ Jump of entropy gradients:\n \/\/_jump_grad_entropy(isCoupled(\"jump_grad_entropy\") ? coupledValue(\"jump_grad_entropy\") : _zero),\n \/\/ Declare material properties\n _kappa(declareProperty<Real>(\"kappa\")),\n _kappa_max(declareProperty<Real>(\"kappa_max\")),\n _residual(declareProperty<Real>(\"residual\")), \/\/ jcr: why declare property for residual?, for output\n \/\/ Get constant parameters\n \/\/_is_first_order(getParam<bool>(\"is_first_order\")),\n _Ce(getParam<double>(\"Ce\")),\n _Cjump(getParam<double>(\"Cjump\")),\n _Cmax(getParam<double>(\"Cmax\")),\n \/\/ UserObject:\n _eos(getUserObject<HydrostaticPressure>(\"eos\")),\n \/\/ PPS name:\n \/\/_entropy_pps_name(getParam<std::string>(\"PPS_name\"))\n{\n if (_Ce < 0. || _Ce > 2.)\n mooseError(\"The coefficient Ce has to be positive and cannot be larger than 2.\");\n}\n\nvoid\nComputeViscCoeff::computeQpProperties()\n{\n \/\/ Determine h (length used in definition of first and second order viscosities):\n Real _h_min = _current_elem->hmin();\/\/ \/_qrule->get_order(); jcr why called min, not cell?\n \n \/\/ vector q\n RealVectorValue _vector_q( _q_x[_qp], _q_y[_qp], 0. );\n\n \/\/ Compute first order viscosity:\n Real c = std::sqrt(_eos.c2(_h[_qp], _vector_q));\n _kappa_max[_qp] = _Cmax*_h_min*(_vector_q.size()\/_h[_qp] + c);\n \n \n\n \/\/ Epsilon value normalization of unit vectors:\n Real _eps = std::sqrt(std::numeric_limits<Real>::min());\n \n \/\/ Compute Mach number and velocity variable to use in the normalization parameter:\n \/\/ Real entropy_pps = std::max(getPostprocessorValueByName(_entropy_pps_name), eps);\n \n \/\/ Initialize some vector, values, ... for entropy viscosity method:\n RealVectorValue _vector_vel = _vector_q \/ _h[_qp];\n\n Real jump=0.;\n \n \/\/ Switch statement over viscosity type:\n switch (_visc_type) {\n case NONE: \n _kappa[_qp] = 0.;\n break;\n case FIRST_ORDER:\n _kappa[_qp] = _kappa_max[_qp];\n break;\n case ENTROPY:\n \/\/ Compute the viscosity coefficients:\n if (_t_step == 1) {\n _kappa[_qp] = _kappa_max[_qp];\n }\n else {\n \/\/ Weights for BDF2\n Real w0 = _t_step > 2 ? (2.*_dt+_dt_old)\/(_dt*(_dt+_dt_old)) : 1. \/ _dt;\n Real w1 = _t_step > 2 ? -(_dt+_dt_old)\/(_dt*_dt_old) : -1. \/ _dt;\n Real w2 = _t_step > 2 ? _dt\/(_dt_old*(_dt+_dt_old)) : 0.;\n\n \/\/ Entropy residual\n Real residual = w0*_E[_qp]+w1*_E_old[_qp]+w2*_E_older[_qp];\n residual += _grad_F[_qp](0)+_grad_G[_qp](1);\n \/\/ store at qp\n _residual[_qp] = std::fabs(residual);\n \n \/\/ Compute kappa_e:\n \/*if (_isJumpOn)\n jump = _Cjump*_norm_vel[_qp]*std::max( _jump_grad_entropy[_qp], c*c*_jump_grad_dens[_qp] );\n else\n jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );*\/\n\n \/\/ Froude number (use from Marco while I figure out |s-save|)\n Real Froude = _vector_q.size()\/_h[_qp]\/std::sqrt(_gravity*(_h[_qp]+_eps));\n\t\t\t\tReal _norm = _gravity*(_h[_qp]+_bathymetry[_qp]+_eps);\n Real kappa_e = _Ce*_h_min*_h_min*(std::fabs(residual) + jump) \/ _norm;\n\n \/\/jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );\n \n \/\/ Compute kappa:\n _kappa[_qp] = std::min( _kappa_max[_qp], kappa_e);\n }\n break;\n default:\n mooseError(\"The viscosity type entered in the input file is not implemented.\");\n break;\n }\n}\n<commit_msg>forgot remove ,<commit_after>#include \"ComputeViscCoeff.h\"\n\ntemplate<>\nInputParameters validParams<ComputeViscCoeff>()\n{\n InputParameters params = validParams<Material>();\n\n params.addParam<std::string>(\"viscosity_name\", \"FIRST_ORDER\", \"Name of the viscosity definition to use: set to first order by default.\");\n \/\/ Coupled variables\n params.addRequiredCoupledVar(\"h\" , \"h: water height\");\n params.addRequiredCoupledVar(\"q_x\", \"x component of momentum\");\n params.addCoupledVar(\"q_y\", \"y component of momentum\");\n \/\/ Coupled aux variables\n params.addRequiredCoupledVar(\"entropy\", \"entropy function\");\n params.addRequiredCoupledVar(\"F\", \"x-component of the entropy flux \");\n params.addCoupledVar(\"G\", \"y-component of the entropy flux \");\n params.addCoupledVar(\"B\", \"bathymetry data\"); \n params.addParam<Real>(\"gravity\", 9.81, \"gravity magnitude\");\n \/\/ constant parameters:\n \/\/params.addParam<bool>(\"is_first_order\", false, \"if true, use the first-order viscosity coefficient\");\n params.addParam<double>(\"Ce\" , 1.0, \"Coefficient for entropy viscosity\");\n params.addParam<double>(\"Cjump\", 1.0, \"Coefficient for jumps\");\n params.addParam<double>(\"Cmax\" , 0.5, \"Coefficient for first-order viscosity\");\n \/\/ Userobject:\n params.addRequiredParam<UserObjectName>(\"eos\", \"Equation of state\");\n \/\/ PPS names:\n \/\/params.addParam<std::string>(\"press_PPS_name\", \"name of the pps computing pressure\");\n \n return params;\n}\n\nComputeViscCoeff::ComputeViscCoeff(const std::string & name, \n InputParameters parameters) :\n Material(name, parameters),\n \/\/ Declare viscosity types\n _visc_type(\"NONE FIRST_ORDER ENTROPY INVALID\", getParam<std::string>(\"viscosity_name\")), \/\/ Declare variables\n _h(coupledValue(\"h\")),\n _q_x(coupledValue(\"q_x\")),\n _q_y(_mesh.dimension() == 2 ? coupledValue(\"q_y\") : _zero),\n \/\/ entropy:\n _E(coupledValue(\"entropy\")),\n _E_old(coupledValueOld(\"entropy\")),\n _E_older(coupledValueOlder(\"entropy\")),\n \/\/ entropy flux:\n _grad_F(coupledGradient(\"F\")),\n _grad_G(_mesh.dimension() == 2 ? coupledGradient(\"G\") : _grad_zero),\n \/\/ bathymetry:\n _bathymetry(isCoupled(\"B\") ? coupledValue(\"B\") : _zero),\n _gravity(getParam<Real>(\"gravity\")),\n \/\/ Jump of entropy gradients:\n \/\/_jump_grad_entropy(isCoupled(\"jump_grad_entropy\") ? coupledValue(\"jump_grad_entropy\") : _zero),\n \/\/ Declare material properties\n _kappa(declareProperty<Real>(\"kappa\")),\n _kappa_max(declareProperty<Real>(\"kappa_max\")),\n _residual(declareProperty<Real>(\"residual\")), \/\/ jcr: why declare property for residual?, for output\n \/\/ Get constant parameters\n \/\/_is_first_order(getParam<bool>(\"is_first_order\")),\n _Ce(getParam<double>(\"Ce\")),\n _Cjump(getParam<double>(\"Cjump\")),\n _Cmax(getParam<double>(\"Cmax\")),\n \/\/ UserObject:\n _eos(getUserObject<HydrostaticPressure>(\"eos\")) \/\/,\n \/\/ PPS name:\n \/\/_entropy_pps_name(getParam<std::string>(\"PPS_name\"))\n{\n if (_Ce < 0. || _Ce > 2.)\n mooseError(\"The coefficient Ce has to be positive and cannot be larger than 2.\");\n}\n\nvoid\nComputeViscCoeff::computeQpProperties()\n{\n \/\/ Determine h (length used in definition of first and second order viscosities):\n Real _h_min = _current_elem->hmin();\/\/ \/_qrule->get_order(); jcr why called min, not cell?\n \n \/\/ vector q\n RealVectorValue _vector_q( _q_x[_qp], _q_y[_qp], 0. );\n\n \/\/ Compute first order viscosity:\n Real c = std::sqrt(_eos.c2(_h[_qp], _vector_q));\n _kappa_max[_qp] = _Cmax*_h_min*(_vector_q.size()\/_h[_qp] + c);\n \n \n\n \/\/ Epsilon value normalization of unit vectors:\n Real _eps = std::sqrt(std::numeric_limits<Real>::min());\n \n \/\/ Compute Mach number and velocity variable to use in the normalization parameter:\n \/\/ Real entropy_pps = std::max(getPostprocessorValueByName(_entropy_pps_name), eps);\n \n \/\/ Initialize some vector, values, ... for entropy viscosity method:\n RealVectorValue _vector_vel = _vector_q \/ _h[_qp];\n\n Real jump=0.;\n \n \/\/ Switch statement over viscosity type:\n switch (_visc_type) {\n case NONE: \n _kappa[_qp] = 0.;\n break;\n case FIRST_ORDER:\n _kappa[_qp] = _kappa_max[_qp];\n break;\n case ENTROPY:\n \/\/ Compute the viscosity coefficients:\n if (_t_step == 1) {\n _kappa[_qp] = _kappa_max[_qp];\n }\n else {\n \/\/ Weights for BDF2\n Real w0 = _t_step > 2 ? (2.*_dt+_dt_old)\/(_dt*(_dt+_dt_old)) : 1. \/ _dt;\n Real w1 = _t_step > 2 ? -(_dt+_dt_old)\/(_dt*_dt_old) : -1. \/ _dt;\n Real w2 = _t_step > 2 ? _dt\/(_dt_old*(_dt+_dt_old)) : 0.;\n\n \/\/ Entropy residual\n Real residual = w0*_E[_qp]+w1*_E_old[_qp]+w2*_E_older[_qp];\n residual += _grad_F[_qp](0)+_grad_G[_qp](1);\n \/\/ store at qp\n _residual[_qp] = std::fabs(residual);\n \n \/\/ Compute kappa_e:\n \/*if (_isJumpOn)\n jump = _Cjump*_norm_vel[_qp]*std::max( _jump_grad_entropy[_qp], c*c*_jump_grad_dens[_qp] );\n else\n jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );*\/\n\n \/\/ Froude number (use from Marco while I figure out |s-save|)\n Real Froude = _vector_q.size()\/_h[_qp]\/std::sqrt(_gravity*(_h[_qp]+_eps));\n\t\t\t\tReal _norm = _gravity*(_h[_qp]+_bathymetry[_qp]+_eps);\n Real kappa_e = _Ce*_h_min*_h_min*(std::fabs(residual) + jump) \/ _norm;\n\n \/\/jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );\n \n \/\/ Compute kappa:\n _kappa[_qp] = std::min( _kappa_max[_qp], kappa_e);\n }\n break;\n default:\n mooseError(\"The viscosity type entered in the input file is not implemented.\");\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Kontact.\n Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>\n Copyright (c) 2005-2006 Allen Winter <winter@kde.org>\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; 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. 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <QCursor>\n#include <QLabel>\n#include <QLayout>\n#include <QPixmap>\n#include <QVBoxLayout>\n#include <QGridLayout>\n#include <QEvent>\n\n\n#include <kdialog.h>\n#include <kglobal.h>\n#include <kicon.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kparts\/part.h>\n#include <kmenu.h>\n#include <kstandarddirs.h>\n#include <kurllabel.h>\n\n#include <kcal\/calendar.h>\n#include <kcal\/resourcecalendar.h>\n#include <kcal\/resourcelocal.h>\n#include <kcal\/todo.h>\n#include <kcal\/incidenceformatter.h>\n#include <libkdepim\/kpimprefs.h>\n\n#include \"core.h\"\n#include \"plugin.h\"\n#include \"todoplugin.h\"\n\n#include \"korganizer\/stdcalendar.h\"\n#include \"korganizer\/koglobals.h\"\n#include \"korganizer\/incidencechanger.h\"\n\n#include \"todosummarywidget.h\"\n#include \"korganizerinterface.h\"\n\nTodoSummaryWidget::TodoSummaryWidget( TodoPlugin *plugin,\n QWidget *parent )\n : Kontact::Summary( parent ), mPlugin( plugin )\n{\n QVBoxLayout *mainLayout = new QVBoxLayout( this );\n mainLayout->setSpacing( 3 );\n mainLayout->setMargin( 3 );\n\n QPixmap icon =\n KIconLoader::global()->loadIcon( \"view-pim-tasks\",\n KIconLoader::Desktop, KIconLoader::SizeMedium );\n QWidget *header = createHeader( this, icon, i18n( \"Pending To-dos\" ) );\n mainLayout->addWidget( header );\n\n mLayout = new QGridLayout();\n mainLayout->addItem( mLayout );\n mLayout->setSpacing( 3 );\n mLayout->setRowStretch( 6, 1 );\n\n mCalendar = KOrg::StdCalendar::self();\n mCalendar->load();\n\n connect( mCalendar, SIGNAL( calendarChanged() ), SLOT( updateView() ) );\n connect( mPlugin->core(), SIGNAL( dayChanged( const QDate& ) ),\n SLOT( updateView() ) );\n\n updateView();\n}\n\nTodoSummaryWidget::~TodoSummaryWidget()\n{\n}\n\nvoid TodoSummaryWidget::updateView()\n{\n qDeleteAll( mLabels );\n mLabels.clear();\n\n KConfig _config( \"kcmtodosummaryrc\" );\n KConfigGroup config(&_config, \"Days\" );\n int mDaysToGo = config.readEntry( \"DaysToShow\", 7 );\n\n config.changeGroup( \"Hide\" );\n mHideInProgress = config.readEntry( \"InProgress\", false );\n mHideOverdue = config.readEntry( \"Overdue\", false );\n mHideCompleted = config.readEntry( \"Completed\", true );\n mHideOpenEnded = config.readEntry( \"OpenEnded\", true );\n mHideNotStarted = config.readEntry( \"NotStarted\", false );\n\n \/\/ for each todo,\n \/\/ if it passes the filter, append to a list\n \/\/ else continue\n \/\/ sort todolist by summary\n \/\/ sort todolist by priority\n \/\/ sort todolist by due-date\n \/\/ print todolist\n\n \/\/ the filter is created by the configuration summary options, but includes\n \/\/ days to go before to-do is due\n \/\/ which types of to-dos to hide\n\n KCal::Todo::List todos = mCalendar->todos();\n KCal::Todo::List prList;\n KCal::Todo::List::ConstIterator it;\n KCal::Todo *todo;\n\n if ( todos.count() > 0 ) {\n for ( it = todos.begin(); it != todos.end(); ++it ) {\n todo = *it;\n\n if ( todo->hasDueDate() ) {\n int daysTo = QDate::currentDate().daysTo( todo->dtDue().date() );\n if ( daysTo >= mDaysToGo )\n continue;\n }\n\n if ( mHideOverdue && overdue( todo ) )\n continue;\n if ( mHideInProgress && inProgress( todo ) )\n continue;\n if ( mHideCompleted && completed( todo ) )\n continue;\n if ( mHideOpenEnded && openEnded( todo ) )\n continue;\n if ( mHideNotStarted && notStarted( todo ) )\n continue;\n\n prList.append( todo );\n }\n\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortSummary,\n KCal::SortDirectionAscending );\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortPriority,\n KCal::SortDirectionAscending );\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortDueDate,\n KCal::SortDirectionAscending );\n }\n\n \/\/ The to-do print consists of the following fields:\n \/\/ icon:due date:days-to-go:priority:summary:status\n \/\/ where,\n \/\/ the icon is the typical to-do icon\n \/\/ the due date it the to-do due date\n \/\/ the days-to-go\/past is the #days until\/since the to-do is due\n \/\/ this field is left blank if the to-do is open-ended\n \/\/ the priority is the to-do priority\n \/\/ the summary is the to-do summary\n \/\/ the status is comma-separated list of:\n \/\/ overdue\n \/\/ in-progress (started, or >0% completed)\n \/\/ complete (100% completed)\n \/\/ open-ended\n \/\/ not-started (no start date and 0% completed)\n\n \/\/ No reason to show the date year\n QString savefmt = KGlobal::locale()->dateFormat();\n KGlobal::locale()->setDateFormat( KGlobal::locale()->\n dateFormat().replace( 'Y', ' ' ) );\n\n int counter = 0;\n QLabel *label = 0;\n\n if ( prList.count() > 0 ) {\n\n KIconLoader loader( \"korganizer\" );\n QPixmap pm = loader.loadIcon( \"view-calendar-tasks\", KIconLoader::Small );\n\n QString str;\n\n for ( it = prList.begin(); it != prList.end(); ++it ) {\n todo = *it;\n bool makeBold = false;\n int daysTo = -1;\n\n \/\/ Icon label\n label = new QLabel( this );\n label->setPixmap( pm );\n label->setMaximumWidth( label->minimumSizeHint().width() );\n mLayout->addWidget( label, counter, 0 );\n mLabels.append( label );\n\n \/\/ Due date label\n str = \"\";\n if ( todo->hasDueDate() ) {\n daysTo = QDate::currentDate().daysTo( todo->dtDue().date() );\n\n if ( daysTo == 0 ) {\n makeBold = true;\n str = i18n( \"Today\" );\n } else if ( daysTo == 1 ) {\n str = i18n( \"Tomorrow\" );\n } else {\n str = KGlobal::locale()->formatDate( todo->dtDue().date() );\n }\n }\n\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 1 );\n mLabels.append( label );\n if ( makeBold ) {\n QFont font = label->font();\n font.setBold( true );\n label->setFont( font );\n }\n\n \/\/ Days togo\/ago label\n str = \"\";\n if ( todo->hasDueDate() ) {\n if ( daysTo > 0 ) {\n str = i18np( \"in 1 day\", \"in %1 days\", daysTo );\n } else if ( daysTo < 0 ) {\n str = i18np( \"1 day ago\", \"%1 days ago\", -daysTo );\n } else{\n str = i18n( \"due\" );\n }\n }\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 2 );\n mLabels.append( label );\n\n \/\/ Priority label\n str = '[' + QString::number( todo->priority() ) + ']';\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignRight | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 3 );\n mLabels.append( label );\n\n \/\/ Summary label\n str = todo->summary();\n if ( todo->relatedTo() ) { \/\/ show parent only, not entire ancestry\n str = todo->relatedTo()->summary() + ':' + str;\n }\n\n KUrlLabel *urlLabel = new KUrlLabel( this );\n urlLabel->setText( str );\n urlLabel->setUrl( todo->uid() );\n urlLabel->installEventFilter( this );\n urlLabel->setTextFormat( Qt::RichText );\n mLayout->addWidget( urlLabel, counter, 4 );\n mLabels.append( urlLabel );\n\n connect( urlLabel, SIGNAL( leftClickedUrl( const QString& ) ),\n this, SLOT( viewTodo( const QString& ) ) );\n connect( urlLabel, SIGNAL( rightClickedUrl( const QString& ) ),\n this, SLOT( popupMenu( const QString& ) ) );\n\n QString tipText( KCal::IncidenceFormatter::toolTipString( todo, true ) );\n if ( !tipText.isEmpty() ) {\n urlLabel->setToolTip( tipText );\n }\n\n \/\/ State text label\n str = stateStr( todo );\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 5 );\n mLabels.append( label );\n\n counter++;\n }\n }\n\n if ( counter == 0 ) {\n QLabel *noTodos = new QLabel(\n i18np( \"No pending to-dos due within the next day\",\n \"No pending to-dos due within the next %1 days\",\n mDaysToGo ), this );\n noTodos->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );\n mLayout->addWidget( noTodos, 0, 2 );\n mLabels.append( noTodos );\n }\n\n Q_FOREACH( label, mLabels )\n label->show();\n\n KGlobal::locale()->setDateFormat( savefmt );\n}\n\nvoid TodoSummaryWidget::viewTodo( const QString &uid )\n{\n mPlugin->core()->selectPlugin( \"kontact_todoplugin\" );\/\/ensure loaded\n OrgKdeKorganizerKorganizerInterface korganizer( \"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.editIncidence( uid );\n}\n\nvoid TodoSummaryWidget::removeTodo( const QString &uid )\n{\n mPlugin->core()->selectPlugin( \"kontact_todoplugin\" );\/\/ensure loaded\n OrgKdeKorganizerKorganizerInterface korganizer( \"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.deleteIncidence( uid, false );\n}\n\nvoid TodoSummaryWidget::completeTodo( const QString &uid )\n{\n KCal::Todo *todo = mCalendar->todo( uid );\n IncidenceChanger *changer = new IncidenceChanger( mCalendar, this );\n if ( !todo->isReadOnly() && changer->beginChange( todo ) ) {\n KCal::Todo *oldTodo = todo->clone();\n todo->setCompleted( KDateTime::currentLocalDateTime() );\n changer->changeIncidence( oldTodo, todo, KOGlobals::COMPLETION_MODIFIED );\n changer->endChange( todo );\n delete oldTodo;\n updateView();\n }\n}\n\nvoid TodoSummaryWidget::popupMenu( const QString &uid )\n{\n KMenu popup( this );\n QAction *editIt = popup.addAction( i18n( \"&Edit To-do...\" ) );\n QAction *delIt = popup.addAction( i18n( \"&Delete To-do\" ) );\n delIt->setIcon( KIconLoader::global()->\n loadIcon( \"edit-delete\", KIconLoader::Small) );\n QAction *doneIt = 0;\n KCal::Todo *todo = mCalendar->todo( uid );\n if ( !todo->isCompleted() ) {\n doneIt = popup.addAction( i18n( \"&Mark To-do Completed\" ) );\n doneIt->setIcon( KIconLoader::global()->\n loadIcon( \"task-complete\", KIconLoader::Small) );\n }\n \/\/ TODO: add icons to the menu actions\n\n const QAction *selectedAction = popup.exec( QCursor::pos() );\n if ( selectedAction == editIt ) {\n viewTodo( uid );\n } else if ( selectedAction == delIt ) {\n removeTodo( uid );\n } else if ( doneIt && selectedAction == doneIt ) {\n completeTodo( uid );\n }\n}\n\nbool TodoSummaryWidget::eventFilter( QObject *obj, QEvent* e )\n{\n if ( obj->inherits( \"KUrlLabel\" ) ) {\n KUrlLabel* label = static_cast<KUrlLabel*>( obj );\n if ( e->type() == QEvent::Enter )\n emit message( i18n( \"Edit To-do: \\\"%1\\\"\", label->text() ) );\n if ( e->type() == QEvent::Leave )\n emit message( QString::null );\t\/\/krazy:exclude=nullstrassign for old broken gcc\n }\n\n return Kontact::Summary::eventFilter( obj, e );\n}\n\nQStringList TodoSummaryWidget::configModules() const\n{\n return QStringList( \"kcmtodosummary.desktop\" );\n}\n\nbool TodoSummaryWidget::overdue( KCal::Todo *todo )\n{\n if ( todo->hasDueDate() && !todo->isCompleted() &&\n todo->dtDue().date() < QDate::currentDate() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::starts( KCal::Todo *todo )\n{\n if ( todo->hasStartDate() &&\n todo->dtStart().date() == QDate::currentDate() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::completed( KCal::Todo *todo )\n{\n return todo->isCompleted();\n}\n\nbool TodoSummaryWidget::openEnded( KCal::Todo *todo )\n{\n if ( !todo->hasDueDate() && !todo->isCompleted() )\n return true;\n else\n return false;\n}\n\nbool TodoSummaryWidget::inProgress( KCal::Todo *todo )\n{\n if ( todo->percentComplete() > 0 )\n return true;\n\n if ( todo->hasStartDate() && todo->hasDueDate() &&\n todo->dtStart().date() < QDate::currentDate() &&\n QDate::currentDate() < todo->dtDue().date() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::notStarted( KCal::Todo *todo )\n{\n if ( todo->percentComplete() > 0 )\n return false;\n\n if ( !todo->hasStartDate() )\n return false;\n\n if ( todo->dtStart().date() >= QDate::currentDate() )\n return false;\n\n return true;\n}\n\nconst QString TodoSummaryWidget::stateStr( KCal::Todo *todo )\n{\n QString str1, str2;\n\n if ( openEnded( todo ) ) {\n str1 = i18n( \"open-ended\" );\n } else if ( overdue( todo ) ) {\n str1 = i18n( \"overdue\" );\n } else if ( starts( todo ) ) {\n str1 = i18n( \"starts today\" );\n }\n\n if ( notStarted( todo ) ) {\n str2 += i18n( \"not-started\" );\n } else if ( completed( todo ) ) {\n str2 += i18n( \"completed\" );\n } else if ( inProgress( todo ) ) {\n str2 += i18n( \"in-progress \" );\n str2 += \" (\" + QString::number( todo->percentComplete() ) + \"%)\";\n }\n\n if ( !str1.isEmpty() && !str2.isEmpty() )\n str1 += i18nc( \"Separator for status like this: overdue, completed\", \",\" );\n\n return str1 + str2;\n}\n\n#include \"todosummarywidget.moc\"\n<commit_msg>clear it up: use foreach<commit_after>\/*\n This file is part of Kontact.\n Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>\n Copyright (c) 2005-2006 Allen Winter <winter@kde.org>\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; 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. 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <QCursor>\n#include <QLabel>\n#include <QLayout>\n#include <QPixmap>\n#include <QVBoxLayout>\n#include <QGridLayout>\n#include <QEvent>\n\n\n#include <kdialog.h>\n#include <kglobal.h>\n#include <kicon.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kparts\/part.h>\n#include <kmenu.h>\n#include <kstandarddirs.h>\n#include <kurllabel.h>\n\n#include <kcal\/calendar.h>\n#include <kcal\/resourcecalendar.h>\n#include <kcal\/resourcelocal.h>\n#include <kcal\/todo.h>\n#include <kcal\/incidenceformatter.h>\n#include <libkdepim\/kpimprefs.h>\n\n#include \"core.h\"\n#include \"plugin.h\"\n#include \"todoplugin.h\"\n\n#include \"korganizer\/stdcalendar.h\"\n#include \"korganizer\/koglobals.h\"\n#include \"korganizer\/incidencechanger.h\"\n\n#include \"todosummarywidget.h\"\n#include \"korganizerinterface.h\"\n\nTodoSummaryWidget::TodoSummaryWidget( TodoPlugin *plugin,\n QWidget *parent )\n : Kontact::Summary( parent ), mPlugin( plugin )\n{\n QVBoxLayout *mainLayout = new QVBoxLayout( this );\n mainLayout->setSpacing( 3 );\n mainLayout->setMargin( 3 );\n\n QPixmap icon =\n KIconLoader::global()->loadIcon( \"view-pim-tasks\",\n KIconLoader::Desktop, KIconLoader::SizeMedium );\n QWidget *header = createHeader( this, icon, i18n( \"Pending To-dos\" ) );\n mainLayout->addWidget( header );\n\n mLayout = new QGridLayout();\n mainLayout->addItem( mLayout );\n mLayout->setSpacing( 3 );\n mLayout->setRowStretch( 6, 1 );\n\n mCalendar = KOrg::StdCalendar::self();\n mCalendar->load();\n\n connect( mCalendar, SIGNAL( calendarChanged() ), SLOT( updateView() ) );\n connect( mPlugin->core(), SIGNAL( dayChanged( const QDate& ) ),\n SLOT( updateView() ) );\n\n updateView();\n}\n\nTodoSummaryWidget::~TodoSummaryWidget()\n{\n}\n\nvoid TodoSummaryWidget::updateView()\n{\n qDeleteAll( mLabels );\n mLabels.clear();\n\n KConfig _config( \"kcmtodosummaryrc\" );\n KConfigGroup config(&_config, \"Days\" );\n int mDaysToGo = config.readEntry( \"DaysToShow\", 7 );\n\n config.changeGroup( \"Hide\" );\n mHideInProgress = config.readEntry( \"InProgress\", false );\n mHideOverdue = config.readEntry( \"Overdue\", false );\n mHideCompleted = config.readEntry( \"Completed\", true );\n mHideOpenEnded = config.readEntry( \"OpenEnded\", true );\n mHideNotStarted = config.readEntry( \"NotStarted\", false );\n\n \/\/ for each todo,\n \/\/ if it passes the filter, append to a list\n \/\/ else continue\n \/\/ sort todolist by summary\n \/\/ sort todolist by priority\n \/\/ sort todolist by due-date\n \/\/ print todolist\n\n \/\/ the filter is created by the configuration summary options, but includes\n \/\/ days to go before to-do is due\n \/\/ which types of to-dos to hide\n\n KCal::Todo::List prList;\n\n Q_FOREACH ( KCal::Todo *todo, mCalendar->todos() ) {\n if ( todo->hasDueDate() ) {\n int daysTo = QDate::currentDate().daysTo( todo->dtDue().date() );\n if ( daysTo >= mDaysToGo )\n continue;\n }\n\n if ( mHideOverdue && overdue( todo ) )\n continue;\n if ( mHideInProgress && inProgress( todo ) )\n continue;\n if ( mHideCompleted && completed( todo ) )\n continue;\n if ( mHideOpenEnded && openEnded( todo ) )\n continue;\n if ( mHideNotStarted && notStarted( todo ) )\n continue;\n\n prList.append( todo );\n }\n if ( !prList.isEmpty() ) {\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortSummary,\n KCal::SortDirectionAscending );\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortPriority,\n KCal::SortDirectionAscending );\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortDueDate,\n KCal::SortDirectionAscending );\n }\n\n \/\/ The to-do print consists of the following fields:\n \/\/ icon:due date:days-to-go:priority:summary:status\n \/\/ where,\n \/\/ the icon is the typical to-do icon\n \/\/ the due date it the to-do due date\n \/\/ the days-to-go\/past is the #days until\/since the to-do is due\n \/\/ this field is left blank if the to-do is open-ended\n \/\/ the priority is the to-do priority\n \/\/ the summary is the to-do summary\n \/\/ the status is comma-separated list of:\n \/\/ overdue\n \/\/ in-progress (started, or >0% completed)\n \/\/ complete (100% completed)\n \/\/ open-ended\n \/\/ not-started (no start date and 0% completed)\n\n \/\/ No reason to show the date year\n QString savefmt = KGlobal::locale()->dateFormat();\n KGlobal::locale()->setDateFormat( KGlobal::locale()->\n dateFormat().replace( 'Y', ' ' ) );\n\n int counter = 0;\n QLabel *label = 0;\n\n if ( !prList.isEmpty() ) {\n\n KIconLoader loader( \"korganizer\" );\n QPixmap pm = loader.loadIcon( \"view-calendar-tasks\", KIconLoader::Small );\n\n QString str;\n\n Q_FOREACH ( KCal::Todo *todo, prList ) {\n bool makeBold = false;\n int daysTo = -1;\n\n \/\/ Icon label\n label = new QLabel( this );\n label->setPixmap( pm );\n label->setMaximumWidth( label->minimumSizeHint().width() );\n mLayout->addWidget( label, counter, 0 );\n mLabels.append( label );\n\n \/\/ Due date label\n str = \"\";\n if ( todo->hasDueDate() ) {\n daysTo = QDate::currentDate().daysTo( todo->dtDue().date() );\n\n if ( daysTo == 0 ) {\n makeBold = true;\n str = i18n( \"Today\" );\n } else if ( daysTo == 1 ) {\n str = i18n( \"Tomorrow\" );\n } else {\n str = KGlobal::locale()->formatDate( todo->dtDue().date() );\n }\n }\n\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 1 );\n mLabels.append( label );\n if ( makeBold ) {\n QFont font = label->font();\n font.setBold( true );\n label->setFont( font );\n }\n\n \/\/ Days togo\/ago label\n str = \"\";\n if ( todo->hasDueDate() ) {\n if ( daysTo > 0 ) {\n str = i18np( \"in 1 day\", \"in %1 days\", daysTo );\n } else if ( daysTo < 0 ) {\n str = i18np( \"1 day ago\", \"%1 days ago\", -daysTo );\n } else{\n str = i18n( \"due\" );\n }\n }\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 2 );\n mLabels.append( label );\n\n \/\/ Priority label\n str = '[' + QString::number( todo->priority() ) + ']';\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignRight | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 3 );\n mLabels.append( label );\n\n \/\/ Summary label\n str = todo->summary();\n if ( todo->relatedTo() ) { \/\/ show parent only, not entire ancestry\n str = todo->relatedTo()->summary() + ':' + str;\n }\n\n KUrlLabel *urlLabel = new KUrlLabel( this );\n urlLabel->setText( str );\n urlLabel->setUrl( todo->uid() );\n urlLabel->installEventFilter( this );\n urlLabel->setTextFormat( Qt::RichText );\n mLayout->addWidget( urlLabel, counter, 4 );\n mLabels.append( urlLabel );\n\n connect( urlLabel, SIGNAL( leftClickedUrl( const QString& ) ),\n this, SLOT( viewTodo( const QString& ) ) );\n connect( urlLabel, SIGNAL( rightClickedUrl( const QString& ) ),\n this, SLOT( popupMenu( const QString& ) ) );\n\n QString tipText( KCal::IncidenceFormatter::toolTipString( todo, true ) );\n if ( !tipText.isEmpty() ) {\n urlLabel->setToolTip( tipText );\n }\n\n \/\/ State text label\n str = stateStr( todo );\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 5 );\n mLabels.append( label );\n\n counter++;\n }\n } \/\/foreach\n\n if ( counter == 0 ) {\n QLabel *noTodos = new QLabel(\n i18np( \"No pending to-dos due within the next day\",\n \"No pending to-dos due within the next %1 days\",\n mDaysToGo ), this );\n noTodos->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );\n mLayout->addWidget( noTodos, 0, 2 );\n mLabels.append( noTodos );\n }\n\n Q_FOREACH( label, mLabels )\n label->show();\n\n KGlobal::locale()->setDateFormat( savefmt );\n}\n\nvoid TodoSummaryWidget::viewTodo( const QString &uid )\n{\n mPlugin->core()->selectPlugin( \"kontact_todoplugin\" );\/\/ensure loaded\n OrgKdeKorganizerKorganizerInterface korganizer( \"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.editIncidence( uid );\n}\n\nvoid TodoSummaryWidget::removeTodo( const QString &uid )\n{\n mPlugin->core()->selectPlugin( \"kontact_todoplugin\" );\/\/ensure loaded\n OrgKdeKorganizerKorganizerInterface korganizer( \"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.deleteIncidence( uid, false );\n}\n\nvoid TodoSummaryWidget::completeTodo( const QString &uid )\n{\n KCal::Todo *todo = mCalendar->todo( uid );\n IncidenceChanger *changer = new IncidenceChanger( mCalendar, this );\n if ( !todo->isReadOnly() && changer->beginChange( todo ) ) {\n KCal::Todo *oldTodo = todo->clone();\n todo->setCompleted( KDateTime::currentLocalDateTime() );\n changer->changeIncidence( oldTodo, todo, KOGlobals::COMPLETION_MODIFIED );\n changer->endChange( todo );\n delete oldTodo;\n updateView();\n }\n}\n\nvoid TodoSummaryWidget::popupMenu( const QString &uid )\n{\n KMenu popup( this );\n QAction *editIt = popup.addAction( i18n( \"&Edit To-do...\" ) );\n QAction *delIt = popup.addAction( i18n( \"&Delete To-do\" ) );\n delIt->setIcon( KIconLoader::global()->\n loadIcon( \"edit-delete\", KIconLoader::Small) );\n QAction *doneIt = 0;\n KCal::Todo *todo = mCalendar->todo( uid );\n if ( !todo->isCompleted() ) {\n doneIt = popup.addAction( i18n( \"&Mark To-do Completed\" ) );\n doneIt->setIcon( KIconLoader::global()->\n loadIcon( \"task-complete\", KIconLoader::Small) );\n }\n \/\/ TODO: add icons to the menu actions\n\n const QAction *selectedAction = popup.exec( QCursor::pos() );\n if ( selectedAction == editIt ) {\n viewTodo( uid );\n } else if ( selectedAction == delIt ) {\n removeTodo( uid );\n } else if ( doneIt && selectedAction == doneIt ) {\n completeTodo( uid );\n }\n}\n\nbool TodoSummaryWidget::eventFilter( QObject *obj, QEvent* e )\n{\n if ( obj->inherits( \"KUrlLabel\" ) ) {\n KUrlLabel* label = static_cast<KUrlLabel*>( obj );\n if ( e->type() == QEvent::Enter )\n emit message( i18n( \"Edit To-do: \\\"%1\\\"\", label->text() ) );\n if ( e->type() == QEvent::Leave )\n emit message( QString::null );\t\/\/krazy:exclude=nullstrassign for old broken gcc\n }\n\n return Kontact::Summary::eventFilter( obj, e );\n}\n\nQStringList TodoSummaryWidget::configModules() const\n{\n return QStringList( \"kcmtodosummary.desktop\" );\n}\n\nbool TodoSummaryWidget::overdue( KCal::Todo *todo )\n{\n if ( todo->hasDueDate() && !todo->isCompleted() &&\n todo->dtDue().date() < QDate::currentDate() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::starts( KCal::Todo *todo )\n{\n if ( todo->hasStartDate() &&\n todo->dtStart().date() == QDate::currentDate() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::completed( KCal::Todo *todo )\n{\n return todo->isCompleted();\n}\n\nbool TodoSummaryWidget::openEnded( KCal::Todo *todo )\n{\n if ( !todo->hasDueDate() && !todo->isCompleted() )\n return true;\n else\n return false;\n}\n\nbool TodoSummaryWidget::inProgress( KCal::Todo *todo )\n{\n if ( todo->percentComplete() > 0 )\n return true;\n\n if ( todo->hasStartDate() && todo->hasDueDate() &&\n todo->dtStart().date() < QDate::currentDate() &&\n QDate::currentDate() < todo->dtDue().date() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::notStarted( KCal::Todo *todo )\n{\n if ( todo->percentComplete() > 0 )\n return false;\n\n if ( !todo->hasStartDate() )\n return false;\n\n if ( todo->dtStart().date() >= QDate::currentDate() )\n return false;\n\n return true;\n}\n\nconst QString TodoSummaryWidget::stateStr( KCal::Todo *todo )\n{\n QString str1, str2;\n\n if ( openEnded( todo ) ) {\n str1 = i18n( \"open-ended\" );\n } else if ( overdue( todo ) ) {\n str1 = i18n( \"overdue\" );\n } else if ( starts( todo ) ) {\n str1 = i18n( \"starts today\" );\n }\n\n if ( notStarted( todo ) ) {\n str2 += i18n( \"not-started\" );\n } else if ( completed( todo ) ) {\n str2 += i18n( \"completed\" );\n } else if ( inProgress( todo ) ) {\n str2 += i18n( \"in-progress \" );\n str2 += \" (\" + QString::number( todo->percentComplete() ) + \"%)\";\n }\n\n if ( !str1.isEmpty() && !str2.isEmpty() )\n str1 += i18nc( \"Separator for status like this: overdue, completed\", \",\" );\n\n return str1 + str2;\n}\n\n#include \"todosummarywidget.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <cstddef>\n#include <type_traits>\n#include <utility>\n\n#include <visionaray\/math\/limits.h>\n#include <visionaray\/math\/matrix.h>\n#include <visionaray\/math\/ray.h>\n#include <visionaray\/intersector.h>\n#include <visionaray\/update_if.h>\n\n#include \"..\/exit_traversal.h\"\n#include \"..\/multi_hit.h\"\n#include \"..\/stack.h\"\n#include \"..\/tags.h\"\n#include \"..\/traversal_result.h\"\n#include \"hit_record.h\"\n\nnamespace visionaray\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Ray \/ BVH intersection\n\/\/\n\ntemplate <\n detail::traversal_type Traversal,\n size_t MultiHitMax = 1, \/\/ Max hits for multi-hit traversal\n typename T,\n typename BVH,\n typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,\n typename = typename std::enable_if<!is_any_bvh_inst<BVH>::value>::type,\n typename Intersector,\n typename Cond = is_closer_t\n >\nVSNRAY_FUNC\ninline auto intersect(\n basic_ray<T> const& ray,\n BVH const& b,\n Intersector& isect,\n T max_t = numeric_limits<T>::max(),\n Cond update_cond = Cond()\n )\n -> typename detail::traversal_result< hit_record_bvh<\n basic_ray<T>,\n decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )\n >, Traversal, MultiHitMax>::type\n{\n\n using namespace detail;\n using HR = hit_record_bvh<\n basic_ray<T>,\n decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )\n >;\n\n using RT = typename detail::traversal_result<HR, Traversal, MultiHitMax>::type;\n\n RT result;\n\n stack<32> st;\n st.push(0); \/\/ address of root node\n\n auto inv_dir = T(1.0) \/ ray.dir;\n\n \/\/ while ray not terminated\nnext:\n while (!st.empty())\n {\n auto node = b.node(st.pop());\n\n \/\/ while node does not contain primitives\n \/\/ traverse to the next node\n\n while (!is_leaf(node))\n {\n auto children = &b.node(node.get_child(0));\n\n auto hr1 = isect(ray, children[0].get_bounds(), inv_dir);\n auto hr2 = isect(ray, children[1].get_bounds(), inv_dir);\n\n auto b1 = any( is_closer(hr1, result, max_t) );\n auto b2 = any( is_closer(hr2, result, max_t) );\n\n if (b1 && b2)\n {\n unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1;\n st.push(node.get_child(!near_addr));\n node = b.node(node.get_child(near_addr));\n }\n else if (b1)\n {\n node = b.node(node.get_child(0));\n }\n else if (b2)\n {\n node = b.node(node.get_child(1));\n }\n else\n {\n goto next;\n }\n }\n\n\n \/\/ while node contains untested primitives\n \/\/ perform a ray-primitive intersection test\n\n for (auto i = node.get_indices().first; i != node.get_indices().last; ++i)\n {\n auto prim = b.primitive(i);\n\n auto hr = HR(isect(ray, prim), i);\n auto closer = update_cond(hr, result, max_t);\n\n#ifndef __CUDA_ARCH__\n if (!any(closer))\n {\n continue;\n }\n#endif\n\n update_if(result, hr, closer);\n\n exit_traversal<Traversal> early_exit;\n if (early_exit.check(result))\n {\n return result;\n }\n }\n }\n\n return result;\n\n}\n\n\n\/\/ Overload for instances ---------------------------------\n\ntemplate <\n detail::traversal_type Traversal,\n size_t MultiHitMax = 1, \/\/ Max hits for multi-hit traversal\n typename T,\n typename BVH,\n typename = typename std::enable_if<is_any_bvh_inst<BVH>::value>::type,\n typename Intersector,\n typename Cond = is_closer_t\n >\nVSNRAY_FUNC\ninline auto intersect(\n basic_ray<T> const& ray,\n BVH const& b,\n Intersector& isect,\n T max_t = numeric_limits<T>::max(),\n Cond update_cond = Cond()\n )\n -> typename detail::traversal_result< hit_record_bvh_inst<\n basic_ray<T>,\n decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )\n >, Traversal, MultiHitMax>::type\n{\n using namespace detail;\n using HR = hit_record_bvh_inst<\n basic_ray<T>,\n decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )\n >;\n\n using RT = typename detail::traversal_result<HR, Traversal, MultiHitMax>::type;\n\n basic_ray<T> transformed_ray = ray;\n transformed_ray.ori = (matrix<4, 4, T>(b.transform_inv()) * vector<4, T>(ray.ori, T(1.0))).xyz();\n auto p2 = (matrix<4, 4, T>(b.transform_inv()) * vector<4, T>(ray.ori + ray.dir, T(1.0))).xyz();\n transformed_ray.dir = (p2 - transformed_ray.ori);\n \/\/ NOTE: dir is in general *not* normalized!\n\n auto hr = intersect<Traversal, MultiHitMax>(\n transformed_ray,\n b.get_ref(),\n isect,\n max_t,\n update_cond\n );\n\n return RT(hr, b.get_inst_id(), matrix<4, 4, T>(b.transform_inv()));\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Default intersect returns closest hit!\n\/\/\n\n\/\/ overload w\/ custom intersector -------------------------\n\ntemplate <\n typename T,\n typename BVH,\n typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,\n typename Intersector,\n typename Cond = is_closer_t\n >\nVSNRAY_FUNC\ninline auto intersect(\n basic_ray<T> const& ray,\n BVH const& b,\n Intersector& isect,\n Cond update_cond = Cond()\n )\n -> decltype(intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond))\n{\n return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond);\n}\n\n\/\/ overload w\/ default intersector ------------------------\n\ntemplate <\n typename T,\n typename BVH,\n typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,\n typename Cond = is_closer_t\n >\nVSNRAY_FUNC\ninline auto intersect(\n basic_ray<T> const& ray,\n BVH const& b,\n Cond update_cond = Cond()\n )\n -> decltype(intersect<detail::ClosestHit>(ray, b, std::declval<default_intersector&>(), numeric_limits<T>::max(), update_cond))\n{\n default_intersector isect;\n return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond);\n}\n\n\n} \/\/ visionaray\n<commit_msg>Transform ray.dir like a vector<commit_after>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <cstddef>\n#include <type_traits>\n#include <utility>\n\n#include <visionaray\/math\/limits.h>\n#include <visionaray\/math\/matrix.h>\n#include <visionaray\/math\/ray.h>\n#include <visionaray\/intersector.h>\n#include <visionaray\/update_if.h>\n\n#include \"..\/exit_traversal.h\"\n#include \"..\/multi_hit.h\"\n#include \"..\/stack.h\"\n#include \"..\/tags.h\"\n#include \"..\/traversal_result.h\"\n#include \"hit_record.h\"\n\nnamespace visionaray\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Ray \/ BVH intersection\n\/\/\n\ntemplate <\n detail::traversal_type Traversal,\n size_t MultiHitMax = 1, \/\/ Max hits for multi-hit traversal\n typename T,\n typename BVH,\n typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,\n typename = typename std::enable_if<!is_any_bvh_inst<BVH>::value>::type,\n typename Intersector,\n typename Cond = is_closer_t\n >\nVSNRAY_FUNC\ninline auto intersect(\n basic_ray<T> const& ray,\n BVH const& b,\n Intersector& isect,\n T max_t = numeric_limits<T>::max(),\n Cond update_cond = Cond()\n )\n -> typename detail::traversal_result< hit_record_bvh<\n basic_ray<T>,\n decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )\n >, Traversal, MultiHitMax>::type\n{\n\n using namespace detail;\n using HR = hit_record_bvh<\n basic_ray<T>,\n decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )\n >;\n\n using RT = typename detail::traversal_result<HR, Traversal, MultiHitMax>::type;\n\n RT result;\n\n stack<32> st;\n st.push(0); \/\/ address of root node\n\n auto inv_dir = T(1.0) \/ ray.dir;\n\n \/\/ while ray not terminated\nnext:\n while (!st.empty())\n {\n auto node = b.node(st.pop());\n\n \/\/ while node does not contain primitives\n \/\/ traverse to the next node\n\n while (!is_leaf(node))\n {\n auto children = &b.node(node.get_child(0));\n\n auto hr1 = isect(ray, children[0].get_bounds(), inv_dir);\n auto hr2 = isect(ray, children[1].get_bounds(), inv_dir);\n\n auto b1 = any( is_closer(hr1, result, max_t) );\n auto b2 = any( is_closer(hr2, result, max_t) );\n\n if (b1 && b2)\n {\n unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1;\n st.push(node.get_child(!near_addr));\n node = b.node(node.get_child(near_addr));\n }\n else if (b1)\n {\n node = b.node(node.get_child(0));\n }\n else if (b2)\n {\n node = b.node(node.get_child(1));\n }\n else\n {\n goto next;\n }\n }\n\n\n \/\/ while node contains untested primitives\n \/\/ perform a ray-primitive intersection test\n\n for (auto i = node.get_indices().first; i != node.get_indices().last; ++i)\n {\n auto prim = b.primitive(i);\n\n auto hr = HR(isect(ray, prim), i);\n auto closer = update_cond(hr, result, max_t);\n\n#ifndef __CUDA_ARCH__\n if (!any(closer))\n {\n continue;\n }\n#endif\n\n update_if(result, hr, closer);\n\n exit_traversal<Traversal> early_exit;\n if (early_exit.check(result))\n {\n return result;\n }\n }\n }\n\n return result;\n\n}\n\n\n\/\/ Overload for instances ---------------------------------\n\ntemplate <\n detail::traversal_type Traversal,\n size_t MultiHitMax = 1, \/\/ Max hits for multi-hit traversal\n typename T,\n typename BVH,\n typename = typename std::enable_if<is_any_bvh_inst<BVH>::value>::type,\n typename Intersector,\n typename Cond = is_closer_t\n >\nVSNRAY_FUNC\ninline auto intersect(\n basic_ray<T> const& ray,\n BVH const& b,\n Intersector& isect,\n T max_t = numeric_limits<T>::max(),\n Cond update_cond = Cond()\n )\n -> typename detail::traversal_result< hit_record_bvh_inst<\n basic_ray<T>,\n decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )\n >, Traversal, MultiHitMax>::type\n{\n using namespace detail;\n using HR = hit_record_bvh_inst<\n basic_ray<T>,\n decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )\n >;\n\n using RT = typename detail::traversal_result<HR, Traversal, MultiHitMax>::type;\n\n basic_ray<T> transformed_ray = ray;\n transformed_ray.ori = (matrix<4, 4, T>(b.transform_inv()) * vector<4, T>(ray.ori, T(1.0))).xyz();\n transformed_ray.dir = (matrix<4, 4, T>(b.transform_inv()) * vector<4, T>(ray.dir, T(0.0))).xyz();\n \/\/ NOTE: dir is in general *not* normalized!\n\n auto hr = intersect<Traversal, MultiHitMax>(\n transformed_ray,\n b.get_ref(),\n isect,\n max_t,\n update_cond\n );\n\n return RT(hr, b.get_inst_id(), matrix<4, 4, T>(b.transform_inv()));\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Default intersect returns closest hit!\n\/\/\n\n\/\/ overload w\/ custom intersector -------------------------\n\ntemplate <\n typename T,\n typename BVH,\n typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,\n typename Intersector,\n typename Cond = is_closer_t\n >\nVSNRAY_FUNC\ninline auto intersect(\n basic_ray<T> const& ray,\n BVH const& b,\n Intersector& isect,\n Cond update_cond = Cond()\n )\n -> decltype(intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond))\n{\n return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond);\n}\n\n\/\/ overload w\/ default intersector ------------------------\n\ntemplate <\n typename T,\n typename BVH,\n typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,\n typename Cond = is_closer_t\n >\nVSNRAY_FUNC\ninline auto intersect(\n basic_ray<T> const& ray,\n BVH const& b,\n Cond update_cond = Cond()\n )\n -> decltype(intersect<detail::ClosestHit>(ray, b, std::declval<default_intersector&>(), numeric_limits<T>::max(), update_cond))\n{\n default_intersector isect;\n return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond);\n}\n\n\n} \/\/ visionaray\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- llvm\/lib\/CodeGen\/AsmPrinter\/WinCodeViewLineTables.cpp --*- C++ -*--===\/\/\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\/\/ This file contains support for writing line tables info into COFF files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"WinCodeViewLineTables.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/MC\/MCSymbol.h\"\n#include \"llvm\/Support\/COFF.h\"\n\nnamespace llvm {\n\nStringRef WinCodeViewLineTables::getFullFilepath(const MDNode *S) {\n assert(S);\n DIDescriptor D(S);\n assert((D.isCompileUnit() || D.isFile() || D.isSubprogram() ||\n D.isLexicalBlockFile() || D.isLexicalBlock()) &&\n \"Unexpected scope info\");\n\n DIScope Scope(S);\n StringRef Dir = Scope.getDirectory(),\n Filename = Scope.getFilename();\n char *&Result = DirAndFilenameToFilepathMap[std::make_pair(Dir, Filename)];\n if (Result)\n return Result;\n\n \/\/ Clang emits directory and relative filename info into the IR, but CodeView\n \/\/ operates on full paths. We could change Clang to emit full paths too, but\n \/\/ that would increase the IR size and probably not needed for other users.\n \/\/ For now, just concatenate and canonicalize the path here.\n std::string Filepath;\n if (Filename.find(':') == 1)\n Filepath = Filename;\n else\n Filepath = (Dir + Twine(\"\\\\\") + Filename).str();\n\n \/\/ Canonicalize the path. We have to do it textually because we may no longer\n \/\/ have access the file in the filesystem.\n \/\/ First, replace all slashes with backslashes.\n std::replace(Filepath.begin(), Filepath.end(), '\/', '\\\\');\n\n \/\/ Remove all \"\\.\\\" with \"\\\".\n size_t Cursor = 0;\n while ((Cursor = Filepath.find(\"\\\\.\\\\\", Cursor)) != std::string::npos)\n Filepath.erase(Cursor, 2);\n\n \/\/ Replace all \"\\XXX\\..\\\" with \"\\\". Don't try too hard though as the original\n \/\/ path should be well-formatted, e.g. start with a drive letter, etc.\n Cursor = 0;\n while ((Cursor = Filepath.find(\"\\\\..\\\\\", Cursor)) != std::string::npos) {\n \/\/ Something's wrong if the path starts with \"\\..\\\", abort.\n if (Cursor == 0)\n break;\n\n size_t PrevSlash = Filepath.rfind('\\\\', Cursor - 1);\n if (PrevSlash == std::string::npos)\n \/\/ Something's wrong, abort.\n break;\n\n Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);\n \/\/ The next \"..\" might be following the one we've just erased.\n Cursor = PrevSlash;\n }\n\n \/\/ Remove all duplicate backslashes.\n Cursor = 0;\n while ((Cursor = Filepath.find(\"\\\\\\\\\", Cursor)) != std::string::npos)\n Filepath.erase(Cursor, 1);\n\n Result = strdup(Filepath.c_str());\n return StringRef(Result);\n}\n\nvoid WinCodeViewLineTables::maybeRecordLocation(DebugLoc DL,\n const MachineFunction *MF) {\n const MDNode *Scope = DL.getScope(MF->getFunction()->getContext());\n if (!Scope)\n return;\n StringRef Filename = getFullFilepath(Scope);\n\n \/\/ Skip this instruction if it has the same file:line as the previous one.\n assert(CurFn);\n if (!CurFn->Instrs.empty()) {\n const InstrInfoTy &LastInstr = InstrInfo[CurFn->Instrs.back()];\n if (LastInstr.Filename == Filename && LastInstr.LineNumber == DL.getLine())\n return;\n }\n FileNameRegistry.add(Filename);\n\n MCSymbol *MCL = Asm->MMI->getContext().CreateTempSymbol();\n Asm->OutStreamer.EmitLabel(MCL);\n CurFn->Instrs.push_back(MCL);\n InstrInfo[MCL] = InstrInfoTy(Filename, DL.getLine());\n}\n\nWinCodeViewLineTables::WinCodeViewLineTables(AsmPrinter *AP)\n : Asm(nullptr), CurFn(nullptr) {\n MachineModuleInfo *MMI = AP->MMI;\n\n \/\/ If module doesn't have named metadata anchors or COFF debug section\n \/\/ is not available, skip any debug info related stuff.\n if (!MMI->getModule()->getNamedMetadata(\"llvm.dbg.cu\") ||\n !AP->getObjFileLowering().getCOFFDebugSymbolsSection())\n return;\n\n \/\/ Tell MMI that we have debug info.\n MMI->setDebugInfoAvailability(true);\n Asm = AP;\n}\n\nstatic void EmitLabelDiff(MCStreamer &Streamer,\n const MCSymbol *From, const MCSymbol *To) {\n MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;\n MCContext &Context = Streamer.getContext();\n const MCExpr *FromRef = MCSymbolRefExpr::Create(From, Variant, Context),\n *ToRef = MCSymbolRefExpr::Create(To, Variant, Context);\n const MCExpr *AddrDelta =\n MCBinaryExpr::Create(MCBinaryExpr::Sub, ToRef, FromRef, Context);\n Streamer.EmitValue(AddrDelta, 4);\n}\n\nvoid WinCodeViewLineTables::emitDebugInfoForFunction(const Function *GV) {\n \/\/ For each function there is a separate subsection\n \/\/ which holds the PC to file:line table.\n const MCSymbol *Fn = Asm->getSymbol(GV);\n assert(Fn);\n\n const FunctionInfo &FI = FnDebugInfo[GV];\n if (FI.Instrs.empty())\n return;\n assert(FI.End && \"Don't know where the function ends?\");\n\n \/\/ PCs\/Instructions are grouped into segments sharing the same filename.\n \/\/ Pre-calculate the lengths (in instructions) of these segments and store\n \/\/ them in a map for convenience. Each index in the map is the sequential\n \/\/ number of the respective instruction that starts a new segment.\n DenseMap<size_t, size_t> FilenameSegmentLengths;\n size_t LastSegmentEnd = 0;\n StringRef PrevFilename = InstrInfo[FI.Instrs[0]].Filename;\n for (size_t J = 1, F = FI.Instrs.size(); J != F; ++J) {\n if (PrevFilename == InstrInfo[FI.Instrs[J]].Filename)\n continue;\n FilenameSegmentLengths[LastSegmentEnd] = J - LastSegmentEnd;\n LastSegmentEnd = J;\n PrevFilename = InstrInfo[FI.Instrs[J]].Filename;\n }\n FilenameSegmentLengths[LastSegmentEnd] = FI.Instrs.size() - LastSegmentEnd;\n\n \/\/ Emit the control code of the subsection followed by the payload size.\n Asm->OutStreamer.AddComment(\n \"Linetable subsection for \" + Twine(Fn->getName()));\n Asm->EmitInt32(COFF::DEBUG_LINE_TABLE_SUBSECTION);\n MCSymbol *SubsectionBegin = Asm->MMI->getContext().CreateTempSymbol(),\n *SubsectionEnd = Asm->MMI->getContext().CreateTempSymbol();\n EmitLabelDiff(Asm->OutStreamer, SubsectionBegin, SubsectionEnd);\n Asm->OutStreamer.EmitLabel(SubsectionBegin);\n\n \/\/ Identify the function this subsection is for.\n Asm->OutStreamer.EmitCOFFSecRel32(Fn);\n Asm->OutStreamer.EmitCOFFSectionIndex(Fn);\n \/\/ Insert padding after a 16-bit section index.\n Asm->EmitInt16(0);\n\n \/\/ Length of the function's code, in bytes.\n EmitLabelDiff(Asm->OutStreamer, Fn, FI.End);\n\n \/\/ PC-to-linenumber lookup table:\n MCSymbol *FileSegmentEnd = nullptr;\n for (size_t J = 0, F = FI.Instrs.size(); J != F; ++J) {\n MCSymbol *Instr = FI.Instrs[J];\n assert(InstrInfo.count(Instr));\n\n if (FilenameSegmentLengths.count(J)) {\n \/\/ We came to a beginning of a new filename segment.\n if (FileSegmentEnd)\n Asm->OutStreamer.EmitLabel(FileSegmentEnd);\n StringRef CurFilename = InstrInfo[FI.Instrs[J]].Filename;\n assert(FileNameRegistry.Infos.count(CurFilename));\n size_t IndexInStringTable =\n FileNameRegistry.Infos[CurFilename].FilenameID;\n \/\/ Each segment starts with the offset of the filename\n \/\/ in the string table.\n Asm->OutStreamer.AddComment(\n \"Segment for file '\" + Twine(CurFilename) + \"' begins\");\n MCSymbol *FileSegmentBegin = Asm->MMI->getContext().CreateTempSymbol();\n Asm->OutStreamer.EmitLabel(FileSegmentBegin);\n Asm->EmitInt32(8 * IndexInStringTable);\n\n \/\/ Number of PC records in the lookup table.\n size_t SegmentLength = FilenameSegmentLengths[J];\n Asm->EmitInt32(SegmentLength);\n\n \/\/ Full size of the segment for this filename, including the prev two\n \/\/ records.\n FileSegmentEnd = Asm->MMI->getContext().CreateTempSymbol();\n EmitLabelDiff(Asm->OutStreamer, FileSegmentBegin, FileSegmentEnd);\n }\n\n \/\/ The first PC with the given linenumber and the linenumber itself.\n EmitLabelDiff(Asm->OutStreamer, Fn, Instr);\n Asm->EmitInt32(InstrInfo[Instr].LineNumber);\n }\n\n if (FileSegmentEnd)\n Asm->OutStreamer.EmitLabel(FileSegmentEnd);\n Asm->OutStreamer.EmitLabel(SubsectionEnd);\n}\n\nvoid WinCodeViewLineTables::endModule() {\n if (FnDebugInfo.empty())\n return;\n\n assert(Asm != nullptr);\n Asm->OutStreamer.SwitchSection(\n Asm->getObjFileLowering().getCOFFDebugSymbolsSection());\n Asm->EmitInt32(COFF::DEBUG_SECTION_MAGIC);\n\n \/\/ The COFF .debug$S section consists of several subsections, each starting\n \/\/ with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length\n \/\/ of the payload followed by the payload itself. The subsections are 4-byte\n \/\/ aligned.\n\n for (size_t I = 0, E = VisitedFunctions.size(); I != E; ++I)\n emitDebugInfoForFunction(VisitedFunctions[I]);\n\n \/\/ This subsection holds a file index to offset in string table table.\n Asm->OutStreamer.AddComment(\"File index to string table offset subsection\");\n Asm->EmitInt32(COFF::DEBUG_INDEX_SUBSECTION);\n size_t NumFilenames = FileNameRegistry.Infos.size();\n Asm->EmitInt32(8 * NumFilenames);\n for (size_t I = 0, E = FileNameRegistry.Filenames.size(); I != E; ++I) {\n StringRef Filename = FileNameRegistry.Filenames[I];\n \/\/ For each unique filename, just write its offset in the string table.\n Asm->EmitInt32(FileNameRegistry.Infos[Filename].StartOffset);\n \/\/ The function name offset is not followed by any additional data.\n Asm->EmitInt32(0);\n }\n\n \/\/ This subsection holds the string table.\n Asm->OutStreamer.AddComment(\"String table\");\n Asm->EmitInt32(COFF::DEBUG_STRING_TABLE_SUBSECTION);\n Asm->EmitInt32(FileNameRegistry.LastOffset);\n \/\/ The payload starts with a null character.\n Asm->EmitInt8(0);\n\n for (size_t I = 0, E = FileNameRegistry.Filenames.size(); I != E; ++I) {\n \/\/ Just emit unique filenames one by one, separated by a null character.\n Asm->OutStreamer.EmitBytes(FileNameRegistry.Filenames[I]);\n Asm->EmitInt8(0);\n }\n\n \/\/ No more subsections. Fill with zeros to align the end of the section by 4.\n Asm->OutStreamer.EmitFill((-FileNameRegistry.LastOffset) % 4, 0);\n\n clear();\n}\n\nvoid WinCodeViewLineTables::beginFunction(const MachineFunction *MF) {\n assert(!CurFn && \"Can't process two functions at once!\");\n\n if (!Asm || !Asm->MMI->hasDebugInfo())\n return;\n\n const Function *GV = MF->getFunction();\n assert(FnDebugInfo.count(GV) == false);\n VisitedFunctions.push_back(GV);\n CurFn = &FnDebugInfo[GV];\n\n \/\/ Find the end of the function prolog.\n \/\/ FIXME: is there a simpler a way to do this? Can we just search\n \/\/ for the first instruction of the function, not the last of the prolog?\n DebugLoc PrologEndLoc;\n bool EmptyPrologue = true;\n for (const auto &MBB : *MF) {\n if (!PrologEndLoc.isUnknown())\n break;\n for (const auto &MI : MBB) {\n if (MI.isDebugValue())\n continue;\n\n \/\/ First known non-DBG_VALUE and non-frame setup location marks\n \/\/ the beginning of the function body.\n \/\/ FIXME: do we need the first subcondition?\n if (!MI.getFlag(MachineInstr::FrameSetup) &&\n (!MI.getDebugLoc().isUnknown())) {\n PrologEndLoc = MI.getDebugLoc();\n break;\n }\n EmptyPrologue = false;\n }\n }\n \/\/ Record beginning of function if we have a non-empty prologue.\n if (!PrologEndLoc.isUnknown() && !EmptyPrologue) {\n DebugLoc FnStartDL =\n PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());\n maybeRecordLocation(FnStartDL, MF);\n }\n}\n\nvoid WinCodeViewLineTables::endFunction(const MachineFunction *MF) {\n if (!Asm || !CurFn) \/\/ We haven't created any debug info for this function.\n return;\n\n const Function *GV = MF->getFunction();\n assert(FnDebugInfo.count(GV));\n assert(CurFn == &FnDebugInfo[GV]);\n\n if (CurFn->Instrs.empty()) {\n FnDebugInfo.erase(GV);\n VisitedFunctions.pop_back();\n } else {\n \/\/ Define end label for subprogram.\n MCSymbol *FunctionEndSym = Asm->OutStreamer.getContext().CreateTempSymbol();\n Asm->OutStreamer.EmitLabel(FunctionEndSym);\n CurFn->End = FunctionEndSym;\n }\n CurFn = nullptr;\n}\n\nvoid WinCodeViewLineTables::beginInstruction(const MachineInstr *MI) {\n \/\/ Ignore DBG_VALUE locations and function prologue.\n if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))\n return;\n DebugLoc DL = MI->getDebugLoc();\n if (DL == PrevInstLoc || DL.isUnknown())\n return;\n maybeRecordLocation(DL, Asm->MF);\n}\n}\n<commit_msg>Reorder functions in WinCodeViewLineTables.cpp [NFC]<commit_after>\/\/===-- llvm\/lib\/CodeGen\/AsmPrinter\/WinCodeViewLineTables.cpp --*- C++ -*--===\/\/\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\/\/ This file contains support for writing line tables info into COFF files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"WinCodeViewLineTables.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/MC\/MCSymbol.h\"\n#include \"llvm\/Support\/COFF.h\"\n\nnamespace llvm {\n\nStringRef WinCodeViewLineTables::getFullFilepath(const MDNode *S) {\n assert(S);\n DIDescriptor D(S);\n assert((D.isCompileUnit() || D.isFile() || D.isSubprogram() ||\n D.isLexicalBlockFile() || D.isLexicalBlock()) &&\n \"Unexpected scope info\");\n\n DIScope Scope(S);\n StringRef Dir = Scope.getDirectory(),\n Filename = Scope.getFilename();\n char *&Result = DirAndFilenameToFilepathMap[std::make_pair(Dir, Filename)];\n if (Result)\n return Result;\n\n \/\/ Clang emits directory and relative filename info into the IR, but CodeView\n \/\/ operates on full paths. We could change Clang to emit full paths too, but\n \/\/ that would increase the IR size and probably not needed for other users.\n \/\/ For now, just concatenate and canonicalize the path here.\n std::string Filepath;\n if (Filename.find(':') == 1)\n Filepath = Filename;\n else\n Filepath = (Dir + Twine(\"\\\\\") + Filename).str();\n\n \/\/ Canonicalize the path. We have to do it textually because we may no longer\n \/\/ have access the file in the filesystem.\n \/\/ First, replace all slashes with backslashes.\n std::replace(Filepath.begin(), Filepath.end(), '\/', '\\\\');\n\n \/\/ Remove all \"\\.\\\" with \"\\\".\n size_t Cursor = 0;\n while ((Cursor = Filepath.find(\"\\\\.\\\\\", Cursor)) != std::string::npos)\n Filepath.erase(Cursor, 2);\n\n \/\/ Replace all \"\\XXX\\..\\\" with \"\\\". Don't try too hard though as the original\n \/\/ path should be well-formatted, e.g. start with a drive letter, etc.\n Cursor = 0;\n while ((Cursor = Filepath.find(\"\\\\..\\\\\", Cursor)) != std::string::npos) {\n \/\/ Something's wrong if the path starts with \"\\..\\\", abort.\n if (Cursor == 0)\n break;\n\n size_t PrevSlash = Filepath.rfind('\\\\', Cursor - 1);\n if (PrevSlash == std::string::npos)\n \/\/ Something's wrong, abort.\n break;\n\n Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);\n \/\/ The next \"..\" might be following the one we've just erased.\n Cursor = PrevSlash;\n }\n\n \/\/ Remove all duplicate backslashes.\n Cursor = 0;\n while ((Cursor = Filepath.find(\"\\\\\\\\\", Cursor)) != std::string::npos)\n Filepath.erase(Cursor, 1);\n\n Result = strdup(Filepath.c_str());\n return StringRef(Result);\n}\n\nvoid WinCodeViewLineTables::maybeRecordLocation(DebugLoc DL,\n const MachineFunction *MF) {\n const MDNode *Scope = DL.getScope(MF->getFunction()->getContext());\n if (!Scope)\n return;\n StringRef Filename = getFullFilepath(Scope);\n\n \/\/ Skip this instruction if it has the same file:line as the previous one.\n assert(CurFn);\n if (!CurFn->Instrs.empty()) {\n const InstrInfoTy &LastInstr = InstrInfo[CurFn->Instrs.back()];\n if (LastInstr.Filename == Filename && LastInstr.LineNumber == DL.getLine())\n return;\n }\n FileNameRegistry.add(Filename);\n\n MCSymbol *MCL = Asm->MMI->getContext().CreateTempSymbol();\n Asm->OutStreamer.EmitLabel(MCL);\n CurFn->Instrs.push_back(MCL);\n InstrInfo[MCL] = InstrInfoTy(Filename, DL.getLine());\n}\n\nWinCodeViewLineTables::WinCodeViewLineTables(AsmPrinter *AP)\n : Asm(nullptr), CurFn(nullptr) {\n MachineModuleInfo *MMI = AP->MMI;\n\n \/\/ If module doesn't have named metadata anchors or COFF debug section\n \/\/ is not available, skip any debug info related stuff.\n if (!MMI->getModule()->getNamedMetadata(\"llvm.dbg.cu\") ||\n !AP->getObjFileLowering().getCOFFDebugSymbolsSection())\n return;\n\n \/\/ Tell MMI that we have debug info.\n MMI->setDebugInfoAvailability(true);\n Asm = AP;\n}\n\nvoid WinCodeViewLineTables::endModule() {\n if (FnDebugInfo.empty())\n return;\n\n assert(Asm != nullptr);\n Asm->OutStreamer.SwitchSection(\n Asm->getObjFileLowering().getCOFFDebugSymbolsSection());\n Asm->EmitInt32(COFF::DEBUG_SECTION_MAGIC);\n\n \/\/ The COFF .debug$S section consists of several subsections, each starting\n \/\/ with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length\n \/\/ of the payload followed by the payload itself. The subsections are 4-byte\n \/\/ aligned.\n\n \/\/ Emit per-function debug information. This code is extracted into a\n \/\/ separate function for readability.\n for (size_t I = 0, E = VisitedFunctions.size(); I != E; ++I)\n emitDebugInfoForFunction(VisitedFunctions[I]);\n\n \/\/ This subsection holds a file index to offset in string table table.\n Asm->OutStreamer.AddComment(\"File index to string table offset subsection\");\n Asm->EmitInt32(COFF::DEBUG_INDEX_SUBSECTION);\n size_t NumFilenames = FileNameRegistry.Infos.size();\n Asm->EmitInt32(8 * NumFilenames);\n for (size_t I = 0, E = FileNameRegistry.Filenames.size(); I != E; ++I) {\n StringRef Filename = FileNameRegistry.Filenames[I];\n \/\/ For each unique filename, just write its offset in the string table.\n Asm->EmitInt32(FileNameRegistry.Infos[Filename].StartOffset);\n \/\/ The function name offset is not followed by any additional data.\n Asm->EmitInt32(0);\n }\n\n \/\/ This subsection holds the string table.\n Asm->OutStreamer.AddComment(\"String table\");\n Asm->EmitInt32(COFF::DEBUG_STRING_TABLE_SUBSECTION);\n Asm->EmitInt32(FileNameRegistry.LastOffset);\n \/\/ The payload starts with a null character.\n Asm->EmitInt8(0);\n\n for (size_t I = 0, E = FileNameRegistry.Filenames.size(); I != E; ++I) {\n \/\/ Just emit unique filenames one by one, separated by a null character.\n Asm->OutStreamer.EmitBytes(FileNameRegistry.Filenames[I]);\n Asm->EmitInt8(0);\n }\n\n \/\/ No more subsections. Fill with zeros to align the end of the section by 4.\n Asm->OutStreamer.EmitFill((-FileNameRegistry.LastOffset) % 4, 0);\n\n clear();\n}\n\nstatic void EmitLabelDiff(MCStreamer &Streamer,\n const MCSymbol *From, const MCSymbol *To) {\n MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;\n MCContext &Context = Streamer.getContext();\n const MCExpr *FromRef = MCSymbolRefExpr::Create(From, Variant, Context),\n *ToRef = MCSymbolRefExpr::Create(To, Variant, Context);\n const MCExpr *AddrDelta =\n MCBinaryExpr::Create(MCBinaryExpr::Sub, ToRef, FromRef, Context);\n Streamer.EmitValue(AddrDelta, 4);\n}\n\nvoid WinCodeViewLineTables::emitDebugInfoForFunction(const Function *GV) {\n \/\/ For each function there is a separate subsection\n \/\/ which holds the PC to file:line table.\n const MCSymbol *Fn = Asm->getSymbol(GV);\n assert(Fn);\n\n const FunctionInfo &FI = FnDebugInfo[GV];\n if (FI.Instrs.empty())\n return;\n assert(FI.End && \"Don't know where the function ends?\");\n\n \/\/ PCs\/Instructions are grouped into segments sharing the same filename.\n \/\/ Pre-calculate the lengths (in instructions) of these segments and store\n \/\/ them in a map for convenience. Each index in the map is the sequential\n \/\/ number of the respective instruction that starts a new segment.\n DenseMap<size_t, size_t> FilenameSegmentLengths;\n size_t LastSegmentEnd = 0;\n StringRef PrevFilename = InstrInfo[FI.Instrs[0]].Filename;\n for (size_t J = 1, F = FI.Instrs.size(); J != F; ++J) {\n if (PrevFilename == InstrInfo[FI.Instrs[J]].Filename)\n continue;\n FilenameSegmentLengths[LastSegmentEnd] = J - LastSegmentEnd;\n LastSegmentEnd = J;\n PrevFilename = InstrInfo[FI.Instrs[J]].Filename;\n }\n FilenameSegmentLengths[LastSegmentEnd] = FI.Instrs.size() - LastSegmentEnd;\n\n \/\/ Emit a line table subsection, requred to do PC-to-file:line lookup.\n Asm->OutStreamer.AddComment(\n \"Line table subsection for \" + Twine(Fn->getName()));\n Asm->EmitInt32(COFF::DEBUG_LINE_TABLE_SUBSECTION);\n MCSymbol *SubsectionBegin = Asm->MMI->getContext().CreateTempSymbol(),\n *SubsectionEnd = Asm->MMI->getContext().CreateTempSymbol();\n EmitLabelDiff(Asm->OutStreamer, SubsectionBegin, SubsectionEnd);\n Asm->OutStreamer.EmitLabel(SubsectionBegin);\n\n \/\/ Identify the function this subsection is for.\n Asm->OutStreamer.EmitCOFFSecRel32(Fn);\n Asm->OutStreamer.EmitCOFFSectionIndex(Fn);\n \/\/ Insert padding after a 16-bit section index.\n Asm->EmitInt16(0);\n\n \/\/ Length of the function's code, in bytes.\n EmitLabelDiff(Asm->OutStreamer, Fn, FI.End);\n\n \/\/ PC-to-linenumber lookup table:\n MCSymbol *FileSegmentEnd = nullptr;\n for (size_t J = 0, F = FI.Instrs.size(); J != F; ++J) {\n MCSymbol *Instr = FI.Instrs[J];\n assert(InstrInfo.count(Instr));\n\n if (FilenameSegmentLengths.count(J)) {\n \/\/ We came to a beginning of a new filename segment.\n if (FileSegmentEnd)\n Asm->OutStreamer.EmitLabel(FileSegmentEnd);\n StringRef CurFilename = InstrInfo[FI.Instrs[J]].Filename;\n assert(FileNameRegistry.Infos.count(CurFilename));\n size_t IndexInStringTable =\n FileNameRegistry.Infos[CurFilename].FilenameID;\n \/\/ Each segment starts with the offset of the filename\n \/\/ in the string table.\n Asm->OutStreamer.AddComment(\n \"Segment for file '\" + Twine(CurFilename) + \"' begins\");\n MCSymbol *FileSegmentBegin = Asm->MMI->getContext().CreateTempSymbol();\n Asm->OutStreamer.EmitLabel(FileSegmentBegin);\n Asm->EmitInt32(8 * IndexInStringTable);\n\n \/\/ Number of PC records in the lookup table.\n size_t SegmentLength = FilenameSegmentLengths[J];\n Asm->EmitInt32(SegmentLength);\n\n \/\/ Full size of the segment for this filename, including the prev two\n \/\/ records.\n FileSegmentEnd = Asm->MMI->getContext().CreateTempSymbol();\n EmitLabelDiff(Asm->OutStreamer, FileSegmentBegin, FileSegmentEnd);\n }\n\n \/\/ The first PC with the given linenumber and the linenumber itself.\n EmitLabelDiff(Asm->OutStreamer, Fn, Instr);\n Asm->EmitInt32(InstrInfo[Instr].LineNumber);\n }\n\n if (FileSegmentEnd)\n Asm->OutStreamer.EmitLabel(FileSegmentEnd);\n Asm->OutStreamer.EmitLabel(SubsectionEnd);\n}\n\nvoid WinCodeViewLineTables::beginFunction(const MachineFunction *MF) {\n assert(!CurFn && \"Can't process two functions at once!\");\n\n if (!Asm || !Asm->MMI->hasDebugInfo())\n return;\n\n const Function *GV = MF->getFunction();\n assert(FnDebugInfo.count(GV) == false);\n VisitedFunctions.push_back(GV);\n CurFn = &FnDebugInfo[GV];\n\n \/\/ Find the end of the function prolog.\n \/\/ FIXME: is there a simpler a way to do this? Can we just search\n \/\/ for the first instruction of the function, not the last of the prolog?\n DebugLoc PrologEndLoc;\n bool EmptyPrologue = true;\n for (const auto &MBB : *MF) {\n if (!PrologEndLoc.isUnknown())\n break;\n for (const auto &MI : MBB) {\n if (MI.isDebugValue())\n continue;\n\n \/\/ First known non-DBG_VALUE and non-frame setup location marks\n \/\/ the beginning of the function body.\n \/\/ FIXME: do we need the first subcondition?\n if (!MI.getFlag(MachineInstr::FrameSetup) &&\n (!MI.getDebugLoc().isUnknown())) {\n PrologEndLoc = MI.getDebugLoc();\n break;\n }\n EmptyPrologue = false;\n }\n }\n \/\/ Record beginning of function if we have a non-empty prologue.\n if (!PrologEndLoc.isUnknown() && !EmptyPrologue) {\n DebugLoc FnStartDL =\n PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());\n maybeRecordLocation(FnStartDL, MF);\n }\n}\n\nvoid WinCodeViewLineTables::endFunction(const MachineFunction *MF) {\n if (!Asm || !CurFn) \/\/ We haven't created any debug info for this function.\n return;\n\n const Function *GV = MF->getFunction();\n assert(FnDebugInfo.count(GV));\n assert(CurFn == &FnDebugInfo[GV]);\n\n if (CurFn->Instrs.empty()) {\n FnDebugInfo.erase(GV);\n VisitedFunctions.pop_back();\n } else {\n \/\/ Define end label for subprogram.\n MCSymbol *FunctionEndSym = Asm->OutStreamer.getContext().CreateTempSymbol();\n Asm->OutStreamer.EmitLabel(FunctionEndSym);\n CurFn->End = FunctionEndSym;\n }\n CurFn = nullptr;\n}\n\nvoid WinCodeViewLineTables::beginInstruction(const MachineInstr *MI) {\n \/\/ Ignore DBG_VALUE locations and function prologue.\n if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))\n return;\n DebugLoc DL = MI->getDebugLoc();\n if (DL == PrevInstLoc || DL.isUnknown())\n return;\n maybeRecordLocation(DL, Asm->MF);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"messagehandler.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QTime>\n\n#define DEBUG_MESSAGEHANDLER 0\n\nMessageHandler::MessageHandler()\n : m_connectWait(false)\n{\n}\n\nMessageHandler::~MessageHandler()\n{\n}\n\nvoid MessageHandler::expectMessage(const QHostAddress& address)\n{\n {\n QMutexLocker locker(&m_connectWaitMutex);\n m_connectWait = true;\n }\n\n {\n QMutexLocker locker(&m_messageWaitMutex);\n m_messageWait = address;\n }\n}\n\nbool MessageHandler::waitForMessage(unsigned long timeout)\n{\n QTime time;\n if (timeout != ULONG_MAX)\n time.start();\n\n {\n QMutexLocker locker(&m_connectWaitMutex);\n if (m_connectWait && !m_connectWaitCondition.wait(&m_connectWaitMutex, timeout))\n return false;\n }\n\n {\n QMutexLocker locker(&m_messageWaitMutex);\n if (!m_messageWait.isNull() && !m_messageWaitCondition.wait(&m_messageWaitMutex, timeout == ULONG_MAX ? timeout : timeout - time.elapsed()))\n return false;\n }\n return true;\n}\n\nvoid MessageHandler::incomingConnectionInternal(const QHostAddress& address)\n{\n emit incomingConnection(address);\n\n QMutexLocker locker(&m_connectWaitMutex);\n if (m_connectWait) {\n m_connectWait = false;\n m_connectWaitCondition.wakeAll();\n }\n}\n\nvoid MessageHandler::receivedMessageInternal(QSharedPointer<Message> msg, const QHostAddress& address)\n{\n#if DEBUG_MESSAGEHANDLER\n qDebug() << \"Receiving message\" << *msg << \"from\" << address;\n#endif\n\n emit receivedMessage(msg, address);\n\n QMutexLocker locker(&m_messageWaitMutex);\n if (!m_messageWait.isNull() && address == m_messageWait) {\n m_messageWait = QHostAddress();\n m_messageWaitCondition.wakeAll();\n }\n}\n<commit_msg>Reset the conditions in the case that waitForMessage times out.<commit_after>#include \"messagehandler.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QTime>\n\n#define DEBUG_MESSAGEHANDLER 0\n\nMessageHandler::MessageHandler()\n : m_connectWait(false)\n{\n}\n\nMessageHandler::~MessageHandler()\n{\n}\n\nvoid MessageHandler::expectMessage(const QHostAddress& address)\n{\n {\n QMutexLocker locker(&m_connectWaitMutex);\n m_connectWait = true;\n }\n\n {\n QMutexLocker locker(&m_messageWaitMutex);\n m_messageWait = address;\n }\n}\n\nbool MessageHandler::waitForMessage(unsigned long timeout)\n{\n QTime time;\n if (timeout != ULONG_MAX)\n time.start();\n\n {\n QMutexLocker locker(&m_connectWaitMutex);\n if (m_connectWait && !m_connectWaitCondition.wait(&m_connectWaitMutex, timeout)) {\n m_connectWait = false;\n return false;\n }\n }\n\n {\n QMutexLocker locker(&m_messageWaitMutex);\n if (!m_messageWait.isNull() && !m_messageWaitCondition.wait(&m_messageWaitMutex, timeout == ULONG_MAX ? timeout : timeout - time.elapsed())) {\n m_messageWait = QHostAddress();\n return false;\n }\n }\n return true;\n}\n\nvoid MessageHandler::incomingConnectionInternal(const QHostAddress& address)\n{\n emit incomingConnection(address);\n\n QMutexLocker locker(&m_connectWaitMutex);\n if (m_connectWait) {\n m_connectWait = false;\n m_connectWaitCondition.wakeAll();\n }\n}\n\nvoid MessageHandler::receivedMessageInternal(QSharedPointer<Message> msg, const QHostAddress& address)\n{\n#if DEBUG_MESSAGEHANDLER\n qDebug() << \"Receiving message\" << *msg << \"from\" << address;\n#endif\n\n emit receivedMessage(msg, address);\n\n QMutexLocker locker(&m_messageWaitMutex);\n if (!m_messageWait.isNull() && address == m_messageWait) {\n m_messageWait = QHostAddress();\n m_messageWaitCondition.wakeAll();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===\/\/\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\/\/ This implements the SelectionDAG::viewGraph method.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/ScheduleDAG.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/Target\/MRegisterInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Support\/GraphWriter.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Config\/config.h\"\n#include <fstream>\n#include <sstream>\nusing namespace llvm;\n\nnamespace llvm {\n template<>\n struct DOTGraphTraits<SelectionDAG*> : public DefaultDOTGraphTraits {\n static std::string getGraphName(const SelectionDAG *G) {\n return G->getMachineFunction().getFunction()->getName();\n }\n\n static bool renderGraphFromBottomUp() {\n return true;\n }\n \n static bool hasNodeAddressLabel(const SDNode *Node,\n const SelectionDAG *Graph) {\n return true;\n }\n \n \/\/\/ If you want to override the dot attributes printed for a particular\n \/\/\/ edge, override this method.\n template<typename EdgeIter>\n static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {\n SDOperand Op = EI.getNode()->getOperand(EI.getOperand());\n MVT::ValueType VT = Op.getValueType();\n if (VT == MVT::Flag)\n return \"color=red,style=bold\";\n else if (VT == MVT::Other)\n return \"color=blue,style=dashed\";\n return \"\";\n }\n \n\n static std::string getNodeLabel(const SDNode *Node,\n const SelectionDAG *Graph);\n static std::string getNodeAttributes(const SDNode *N,\n const SelectionDAG *Graph) {\n#ifndef NDEBUG\n const std::string &Attrs = Graph->getGraphAttrs(N);\n if (!Attrs.empty()) {\n if (Attrs.find(\"shape=\") == std::string::npos)\n return std::string(\"shape=Mrecord,\") + Attrs;\n else\n return Attrs;\n }\n#endif\n return \"shape=Mrecord\";\n }\n\n static void addCustomGraphFeatures(SelectionDAG *G,\n GraphWriter<SelectionDAG*> &GW) {\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n if (G->getRoot().Val)\n GW.emitEdge(0, -1, G->getRoot().Val, -1, \"\");\n }\n };\n}\n\nstd::string DOTGraphTraits<SelectionDAG*>::getNodeLabel(const SDNode *Node,\n const SelectionDAG *G) {\n std::string Op = Node->getOperationName(G);\n\n for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)\n if (Node->getValueType(i) == MVT::Other)\n Op += \":ch\";\n else\n Op = Op + \":\" + MVT::getValueTypeString(Node->getValueType(i));\n \n if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(Node)) {\n Op += \": \" + utostr(CSDN->getValue());\n } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(Node)) {\n Op += \": \" + ftostr(CSDN->getValueAPF());\n } else if (const GlobalAddressSDNode *GADN =\n dyn_cast<GlobalAddressSDNode>(Node)) {\n int offset = GADN->getOffset();\n Op += \": \" + GADN->getGlobal()->getName();\n if (offset > 0)\n Op += \"+\" + itostr(offset);\n else\n Op += itostr(offset);\n } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(Node)) {\n Op += \" \" + itostr(FIDN->getIndex());\n } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(Node)) {\n Op += \" \" + itostr(JTDN->getIndex());\n } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Node)){\n if (CP->isMachineConstantPoolEntry()) {\n std::ostringstream SS;\n CP->getMachineCPVal()->print(SS);\n Op += \"<\" + SS.str() + \">\";\n } else {\n if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))\n Op += \"<\" + ftostr(CFP->getValueAPF()) + \">\";\n else if (ConstantInt *CI = dyn_cast<ConstantInt>(CP->getConstVal()))\n Op += \"<\" + utostr(CI->getZExtValue()) + \">\";\n else {\n std::ostringstream SS;\n WriteAsOperand(SS, CP->getConstVal(), false);\n Op += \"<\" + SS.str() + \">\";\n }\n }\n } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(Node)) {\n Op = \"BB: \";\n const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();\n if (LBB)\n Op += LBB->getName();\n \/\/Op += \" \" + (const void*)BBDN->getBasicBlock();\n } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node)) {\n if (G && R->getReg() != 0 &&\n MRegisterInfo::isPhysicalRegister(R->getReg())) {\n Op = Op + \" \" + G->getTarget().getRegisterInfo()->getName(R->getReg());\n } else {\n Op += \" #\" + utostr(R->getReg());\n }\n } else if (const ExternalSymbolSDNode *ES =\n dyn_cast<ExternalSymbolSDNode>(Node)) {\n Op += \"'\" + std::string(ES->getSymbol()) + \"'\";\n } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(Node)) {\n if (M->getValue())\n Op += \"<\" + M->getValue()->getName() + \":\" + itostr(M->getOffset()) + \">\";\n else\n Op += \"<null:\" + itostr(M->getOffset()) + \">\";\n } else if (const VTSDNode *N = dyn_cast<VTSDNode>(Node)) {\n Op = Op + \" VT=\" + MVT::getValueTypeString(N->getVT());\n } else if (const StringSDNode *N = dyn_cast<StringSDNode>(Node)) {\n Op = Op + \"\\\"\" + N->getValue() + \"\\\"\";\n } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(Node)) {\n bool doExt = true;\n switch (LD->getExtensionType()) {\n default: doExt = false; break;\n case ISD::EXTLOAD:\n Op = Op + \"<anyext \";\n break;\n case ISD::SEXTLOAD:\n Op = Op + \" <sext \";\n break;\n case ISD::ZEXTLOAD:\n Op = Op + \" <zext \";\n break;\n }\n if (doExt)\n Op = Op + MVT::getValueTypeString(LD->getLoadedVT()) + \">\";\n\n Op += LD->getIndexedModeName(LD->getAddressingMode());\n } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(Node)) {\n if (ST->isTruncatingStore())\n Op = Op + \"<trunc \" + MVT::getValueTypeString(ST->getStoredVT()) + \">\";\n Op += ST->getIndexedModeName(ST->getAddressingMode());\n }\n\n#if 0\n Op += \" Id=\" + itostr(Node->getNodeId());\n#endif\n \n return Op;\n}\n\n\n\/\/\/ viewGraph - Pop up a ghostview window with the reachable parts of the DAG\n\/\/\/ rendered using 'dot'.\n\/\/\/\nvoid SelectionDAG::viewGraph() {\n\/\/ This code is only for debugging!\n#ifndef NDEBUG\n ViewGraph(this, \"dag.\" + getMachineFunction().getFunction()->getName());\n#else\n cerr << \"SelectionDAG::viewGraph is only available in debug builds on \"\n << \"systems with Graphviz or gv!\\n\";\n#endif \/\/ NDEBUG\n}\n\n\n\/\/\/ clearGraphAttrs - Clear all previously defined node graph attributes.\n\/\/\/ Intended to be used from a debugging tool (eg. gdb).\nvoid SelectionDAG::clearGraphAttrs() {\n#ifndef NDEBUG\n NodeGraphAttrs.clear();\n#else\n cerr << \"SelectionDAG::clearGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\n\/\/\/ setGraphAttrs - Set graph attributes for a node. (eg. \"color=red\".)\n\/\/\/\nvoid SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {\n#ifndef NDEBUG\n NodeGraphAttrs[N] = Attrs;\n#else\n cerr << \"SelectionDAG::setGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\n\/\/\/ getGraphAttrs - Get graph attributes for a node. (eg. \"color=red\".)\n\/\/\/ Used from getNodeAttributes.\nconst std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {\n#ifndef NDEBUG\n std::map<const SDNode *, std::string>::const_iterator I =\n NodeGraphAttrs.find(N);\n \n if (I != NodeGraphAttrs.end())\n return I->second;\n else\n return \"\";\n#else\n cerr << \"SelectionDAG::getGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n return std::string(\"\");\n#endif\n}\n\n\/\/\/ setGraphColor - Convenience for setting node color attribute.\n\/\/\/\nvoid SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {\n#ifndef NDEBUG\n NodeGraphAttrs[N] = std::string(\"color=\") + Color;\n#else\n cerr << \"SelectionDAG::setGraphColor is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\nnamespace llvm {\n template<>\n struct DOTGraphTraits<ScheduleDAG*> : public DefaultDOTGraphTraits {\n static std::string getGraphName(const ScheduleDAG *G) {\n return DOTGraphTraits<SelectionDAG*>::getGraphName(&G->DAG);\n }\n\n static bool renderGraphFromBottomUp() {\n return true;\n }\n \n static bool hasNodeAddressLabel(const SUnit *Node,\n const ScheduleDAG *Graph) {\n return true;\n }\n \n \/\/\/ If you want to override the dot attributes printed for a particular\n \/\/\/ edge, override this method.\n template<typename EdgeIter>\n static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {\n if (EI.isCtrlDep())\n return \"color=blue,style=dashed\";\n return \"\";\n }\n \n\n static std::string getNodeLabel(const SUnit *Node,\n const ScheduleDAG *Graph);\n static std::string getNodeAttributes(const SUnit *N,\n const ScheduleDAG *Graph) {\n return \"shape=Mrecord\";\n }\n\n static void addCustomGraphFeatures(ScheduleDAG *G,\n GraphWriter<ScheduleDAG*> &GW) {\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n if (G->DAG.getRoot().Val)\n GW.emitEdge(0, -1, G->SUnitMap[G->DAG.getRoot().Val].front(), -1, \"\");\n }\n };\n}\n\nstd::string DOTGraphTraits<ScheduleDAG*>::getNodeLabel(const SUnit *SU,\n const ScheduleDAG *G) {\n std::string Op;\n\n for (unsigned i = 0; i < SU->FlaggedNodes.size(); ++i) {\n Op += DOTGraphTraits<SelectionDAG*>::getNodeLabel(SU->FlaggedNodes[i],\n &G->DAG) + \"\\n\";\n }\n\n Op += DOTGraphTraits<SelectionDAG*>::getNodeLabel(SU->Node, &G->DAG);\n\n return Op;\n}\n\n\n\/\/\/ viewGraph - Pop up a ghostview window with the reachable parts of the DAG\n\/\/\/ rendered using 'dot'.\n\/\/\/\nvoid ScheduleDAG::viewGraph() {\n\/\/ This code is only for debugging!\n#ifndef NDEBUG\n ViewGraph(this, \"dag.\" + DAG.getMachineFunction().getFunction()->getName());\n#else\n cerr << \"ScheduleDAG::viewGraph is only available in debug builds on \"\n << \"systems with Graphviz or gv!\\n\";\n#endif \/\/ NDEBUG\n}\n<commit_msg>include alignment and volatility information in -view-*-dags output<commit_after>\/\/===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===\/\/\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\/\/ This implements the SelectionDAG::viewGraph method.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/ScheduleDAG.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/Target\/MRegisterInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Support\/GraphWriter.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Config\/config.h\"\n#include <fstream>\n#include <sstream>\nusing namespace llvm;\n\nnamespace llvm {\n template<>\n struct DOTGraphTraits<SelectionDAG*> : public DefaultDOTGraphTraits {\n static std::string getGraphName(const SelectionDAG *G) {\n return G->getMachineFunction().getFunction()->getName();\n }\n\n static bool renderGraphFromBottomUp() {\n return true;\n }\n \n static bool hasNodeAddressLabel(const SDNode *Node,\n const SelectionDAG *Graph) {\n return true;\n }\n \n \/\/\/ If you want to override the dot attributes printed for a particular\n \/\/\/ edge, override this method.\n template<typename EdgeIter>\n static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {\n SDOperand Op = EI.getNode()->getOperand(EI.getOperand());\n MVT::ValueType VT = Op.getValueType();\n if (VT == MVT::Flag)\n return \"color=red,style=bold\";\n else if (VT == MVT::Other)\n return \"color=blue,style=dashed\";\n return \"\";\n }\n \n\n static std::string getNodeLabel(const SDNode *Node,\n const SelectionDAG *Graph);\n static std::string getNodeAttributes(const SDNode *N,\n const SelectionDAG *Graph) {\n#ifndef NDEBUG\n const std::string &Attrs = Graph->getGraphAttrs(N);\n if (!Attrs.empty()) {\n if (Attrs.find(\"shape=\") == std::string::npos)\n return std::string(\"shape=Mrecord,\") + Attrs;\n else\n return Attrs;\n }\n#endif\n return \"shape=Mrecord\";\n }\n\n static void addCustomGraphFeatures(SelectionDAG *G,\n GraphWriter<SelectionDAG*> &GW) {\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n if (G->getRoot().Val)\n GW.emitEdge(0, -1, G->getRoot().Val, -1, \"\");\n }\n };\n}\n\nstd::string DOTGraphTraits<SelectionDAG*>::getNodeLabel(const SDNode *Node,\n const SelectionDAG *G) {\n std::string Op = Node->getOperationName(G);\n\n for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)\n if (Node->getValueType(i) == MVT::Other)\n Op += \":ch\";\n else\n Op = Op + \":\" + MVT::getValueTypeString(Node->getValueType(i));\n \n if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(Node)) {\n Op += \": \" + utostr(CSDN->getValue());\n } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(Node)) {\n Op += \": \" + ftostr(CSDN->getValueAPF());\n } else if (const GlobalAddressSDNode *GADN =\n dyn_cast<GlobalAddressSDNode>(Node)) {\n int offset = GADN->getOffset();\n Op += \": \" + GADN->getGlobal()->getName();\n if (offset > 0)\n Op += \"+\" + itostr(offset);\n else\n Op += itostr(offset);\n } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(Node)) {\n Op += \" \" + itostr(FIDN->getIndex());\n } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(Node)) {\n Op += \" \" + itostr(JTDN->getIndex());\n } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Node)){\n if (CP->isMachineConstantPoolEntry()) {\n std::ostringstream SS;\n CP->getMachineCPVal()->print(SS);\n Op += \"<\" + SS.str() + \">\";\n } else {\n if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))\n Op += \"<\" + ftostr(CFP->getValueAPF()) + \">\";\n else if (ConstantInt *CI = dyn_cast<ConstantInt>(CP->getConstVal()))\n Op += \"<\" + utostr(CI->getZExtValue()) + \">\";\n else {\n std::ostringstream SS;\n WriteAsOperand(SS, CP->getConstVal(), false);\n Op += \"<\" + SS.str() + \">\";\n }\n }\n } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(Node)) {\n Op = \"BB: \";\n const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();\n if (LBB)\n Op += LBB->getName();\n \/\/Op += \" \" + (const void*)BBDN->getBasicBlock();\n } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node)) {\n if (G && R->getReg() != 0 &&\n MRegisterInfo::isPhysicalRegister(R->getReg())) {\n Op = Op + \" \" + G->getTarget().getRegisterInfo()->getName(R->getReg());\n } else {\n Op += \" #\" + utostr(R->getReg());\n }\n } else if (const ExternalSymbolSDNode *ES =\n dyn_cast<ExternalSymbolSDNode>(Node)) {\n Op += \"'\" + std::string(ES->getSymbol()) + \"'\";\n } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(Node)) {\n if (M->getValue())\n Op += \"<\" + M->getValue()->getName() + \":\" + itostr(M->getOffset()) + \">\";\n else\n Op += \"<null:\" + itostr(M->getOffset()) + \">\";\n } else if (const VTSDNode *N = dyn_cast<VTSDNode>(Node)) {\n Op = Op + \" VT=\" + MVT::getValueTypeString(N->getVT());\n } else if (const StringSDNode *N = dyn_cast<StringSDNode>(Node)) {\n Op = Op + \"\\\"\" + N->getValue() + \"\\\"\";\n } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(Node)) {\n bool doExt = true;\n switch (LD->getExtensionType()) {\n default: doExt = false; break;\n case ISD::EXTLOAD:\n Op = Op + \"<anyext \";\n break;\n case ISD::SEXTLOAD:\n Op = Op + \" <sext \";\n break;\n case ISD::ZEXTLOAD:\n Op = Op + \" <zext \";\n break;\n }\n if (doExt)\n Op += MVT::getValueTypeString(LD->getLoadedVT()) + \">\";\n if (LD->isVolatile())\n Op += \"<V>\";\n Op += LD->getIndexedModeName(LD->getAddressingMode());\n if (LD->getAlignment() > 1)\n Op += \" A=\" + utostr(LD->getAlignment());\n } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(Node)) {\n if (ST->isTruncatingStore())\n Op += \"<trunc \" + MVT::getValueTypeString(ST->getStoredVT()) + \">\";\n if (ST->isVolatile())\n Op += \"<V>\";\n Op += ST->getIndexedModeName(ST->getAddressingMode());\n if (ST->getAlignment() > 1)\n Op += \" A=\" + utostr(ST->getAlignment());\n }\n\n#if 0\n Op += \" Id=\" + itostr(Node->getNodeId());\n#endif\n \n return Op;\n}\n\n\n\/\/\/ viewGraph - Pop up a ghostview window with the reachable parts of the DAG\n\/\/\/ rendered using 'dot'.\n\/\/\/\nvoid SelectionDAG::viewGraph() {\n\/\/ This code is only for debugging!\n#ifndef NDEBUG\n ViewGraph(this, \"dag.\" + getMachineFunction().getFunction()->getName());\n#else\n cerr << \"SelectionDAG::viewGraph is only available in debug builds on \"\n << \"systems with Graphviz or gv!\\n\";\n#endif \/\/ NDEBUG\n}\n\n\n\/\/\/ clearGraphAttrs - Clear all previously defined node graph attributes.\n\/\/\/ Intended to be used from a debugging tool (eg. gdb).\nvoid SelectionDAG::clearGraphAttrs() {\n#ifndef NDEBUG\n NodeGraphAttrs.clear();\n#else\n cerr << \"SelectionDAG::clearGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\n\/\/\/ setGraphAttrs - Set graph attributes for a node. (eg. \"color=red\".)\n\/\/\/\nvoid SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {\n#ifndef NDEBUG\n NodeGraphAttrs[N] = Attrs;\n#else\n cerr << \"SelectionDAG::setGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\n\/\/\/ getGraphAttrs - Get graph attributes for a node. (eg. \"color=red\".)\n\/\/\/ Used from getNodeAttributes.\nconst std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {\n#ifndef NDEBUG\n std::map<const SDNode *, std::string>::const_iterator I =\n NodeGraphAttrs.find(N);\n \n if (I != NodeGraphAttrs.end())\n return I->second;\n else\n return \"\";\n#else\n cerr << \"SelectionDAG::getGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n return std::string(\"\");\n#endif\n}\n\n\/\/\/ setGraphColor - Convenience for setting node color attribute.\n\/\/\/\nvoid SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {\n#ifndef NDEBUG\n NodeGraphAttrs[N] = std::string(\"color=\") + Color;\n#else\n cerr << \"SelectionDAG::setGraphColor is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\nnamespace llvm {\n template<>\n struct DOTGraphTraits<ScheduleDAG*> : public DefaultDOTGraphTraits {\n static std::string getGraphName(const ScheduleDAG *G) {\n return DOTGraphTraits<SelectionDAG*>::getGraphName(&G->DAG);\n }\n\n static bool renderGraphFromBottomUp() {\n return true;\n }\n \n static bool hasNodeAddressLabel(const SUnit *Node,\n const ScheduleDAG *Graph) {\n return true;\n }\n \n \/\/\/ If you want to override the dot attributes printed for a particular\n \/\/\/ edge, override this method.\n template<typename EdgeIter>\n static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {\n if (EI.isCtrlDep())\n return \"color=blue,style=dashed\";\n return \"\";\n }\n \n\n static std::string getNodeLabel(const SUnit *Node,\n const ScheduleDAG *Graph);\n static std::string getNodeAttributes(const SUnit *N,\n const ScheduleDAG *Graph) {\n return \"shape=Mrecord\";\n }\n\n static void addCustomGraphFeatures(ScheduleDAG *G,\n GraphWriter<ScheduleDAG*> &GW) {\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n if (G->DAG.getRoot().Val)\n GW.emitEdge(0, -1, G->SUnitMap[G->DAG.getRoot().Val].front(), -1, \"\");\n }\n };\n}\n\nstd::string DOTGraphTraits<ScheduleDAG*>::getNodeLabel(const SUnit *SU,\n const ScheduleDAG *G) {\n std::string Op;\n\n for (unsigned i = 0; i < SU->FlaggedNodes.size(); ++i) {\n Op += DOTGraphTraits<SelectionDAG*>::getNodeLabel(SU->FlaggedNodes[i],\n &G->DAG) + \"\\n\";\n }\n\n Op += DOTGraphTraits<SelectionDAG*>::getNodeLabel(SU->Node, &G->DAG);\n\n return Op;\n}\n\n\n\/\/\/ viewGraph - Pop up a ghostview window with the reachable parts of the DAG\n\/\/\/ rendered using 'dot'.\n\/\/\/\nvoid ScheduleDAG::viewGraph() {\n\/\/ This code is only for debugging!\n#ifndef NDEBUG\n ViewGraph(this, \"dag.\" + DAG.getMachineFunction().getFunction()->getName());\n#else\n cerr << \"ScheduleDAG::viewGraph is only available in debug builds on \"\n << \"systems with Graphviz or gv!\\n\";\n#endif \/\/ NDEBUG\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- lib\/ReaderWriter\/PECOFF\/PECOFFLinkingContext.cpp -------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Atoms.h\"\n#include \"EdataPass.h\"\n#include \"GroupedSectionsPass.h\"\n#include \"IdataPass.h\"\n#include \"LinkerGeneratedSymbolFile.h\"\n#include \"SetSubsystemPass.h\"\n\n#include \"lld\/Core\/PassManager.h\"\n#include \"lld\/Passes\/LayoutPass.h\"\n#include \"lld\/Passes\/RoundTripNativePass.h\"\n#include \"lld\/Passes\/RoundTripYAMLPass.h\"\n#include \"lld\/ReaderWriter\/PECOFFLinkingContext.h\"\n#include \"lld\/ReaderWriter\/Reader.h\"\n#include \"lld\/ReaderWriter\/Simple.h\"\n#include \"lld\/ReaderWriter\/Writer.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/Allocator.h\"\n#include \"llvm\/Support\/Path.h\"\n\n#include <bitset>\n#include <climits>\n#include <set>\n\nnamespace lld {\n\nstatic void assignOrdinals(PECOFFLinkingContext &ctx) {\n int maxOrdinal = -1;\n for (const PECOFFLinkingContext::ExportDesc &desc : ctx.getDllExports())\n maxOrdinal = std::max(maxOrdinal, desc.ordinal);\n int nextOrdinal = (maxOrdinal == -1) ? 1 : (maxOrdinal + 1);\n for (PECOFFLinkingContext::ExportDesc &desc : ctx.getDllExports())\n if (desc.ordinal == -1)\n desc.ordinal = nextOrdinal++;\n}\n\nbool PECOFFLinkingContext::validateImpl(raw_ostream &diagnostics) {\n if (_stackReserve < _stackCommit) {\n diagnostics << \"Invalid stack size: reserve size must be equal to or \"\n << \"greater than commit size, but got \" << _stackCommit\n << \" and \" << _stackReserve << \".\\n\";\n return false;\n }\n\n if (_heapReserve < _heapCommit) {\n diagnostics << \"Invalid heap size: reserve size must be equal to or \"\n << \"greater than commit size, but got \" << _heapCommit\n << \" and \" << _heapReserve << \".\\n\";\n return false;\n }\n\n \/\/ It's an error if the base address is not multiple of 64K.\n if (_baseAddress & 0xffff) {\n diagnostics << \"Base address have to be multiple of 64K, but got \"\n << _baseAddress << \"\\n\";\n return false;\n }\n\n \/\/ Check for duplicate export ordinals.\n std::set<int> exports;\n for (const PECOFFLinkingContext::ExportDesc &desc : getDllExports()) {\n if (desc.ordinal == -1)\n continue;\n if (exports.count(desc.ordinal) == 1) {\n diagnostics << \"Duplicate export ordinals: \" << desc.ordinal << \"\\n\";\n return false;\n }\n exports.insert(desc.ordinal);\n }\n\n std::bitset<64> alignment(_sectionDefaultAlignment);\n if (alignment.count() != 1) {\n diagnostics << \"Section alignment must be a power of 2, but got \"\n << _sectionDefaultAlignment << \"\\n\";\n return false;\n }\n\n \/\/ Architectures other than i386 is not supported yet.\n if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) {\n diagnostics << \"Machine type other than x86 is not supported.\\n\";\n return false;\n }\n\n \/\/ Assign default ordinals to export symbols.\n assignOrdinals(*this);\n\n _writer = createWriterPECOFF(*this);\n return true;\n}\n\nstd::unique_ptr<File> PECOFFLinkingContext::createEntrySymbolFile() const {\n if (entrySymbolName().empty())\n return nullptr;\n std::unique_ptr<SimpleFile> entryFile(\n new SimpleFile(\"command line option \/entry\"));\n entryFile->addAtom(\n *(new (_allocator) SimpleUndefinedAtom(*entryFile, entrySymbolName())));\n return std::move(entryFile);\n}\n\nstd::unique_ptr<File> PECOFFLinkingContext::createUndefinedSymbolFile() const {\n if (_initialUndefinedSymbols.empty())\n return nullptr;\n std::unique_ptr<SimpleFile> undefinedSymFile(\n new SimpleFile(\"command line option \/c (or) \/include\"));\n for (auto undefSymStr : _initialUndefinedSymbols)\n undefinedSymFile->addAtom(*(new (_allocator) SimpleUndefinedAtom(\n *undefinedSymFile, undefSymStr)));\n return std::move(undefinedSymFile);\n}\n\nbool PECOFFLinkingContext::createImplicitFiles(\n std::vector<std::unique_ptr<File> > &) const {\n std::unique_ptr<SimpleFileNode> fileNode(\n new SimpleFileNode(\"Implicit Files\"));\n std::unique_ptr<File> linkerGeneratedSymFile(\n new pecoff::LinkerGeneratedSymbolFile(*this));\n fileNode->appendInputFile(std::move(linkerGeneratedSymFile));\n inputGraph().insertOneElementAt(std::move(fileNode),\n InputGraph::Position::END);\n return true;\n}\n\n\/\/\/ Returns the section name in the resulting executable.\n\/\/\/\n\/\/\/ Sections in object files are usually output to the executable with the same\n\/\/\/ name, but you can rename by command line option. \/merge:from=to makes the\n\/\/\/ linker to combine \"from\" section contents to \"to\" section in the\n\/\/\/ executable. We have a mapping for the renaming. This method looks up the\n\/\/\/ table and returns a new section name if renamed.\nStringRef\nPECOFFLinkingContext::getOutputSectionName(StringRef sectionName) const {\n auto it = _renamedSections.find(sectionName);\n if (it == _renamedSections.end())\n return sectionName;\n return getOutputSectionName(it->second);\n}\n\n\/\/\/ Adds a mapping to the section renaming table. This method will be used for\n\/\/\/ \/merge command line option.\nbool PECOFFLinkingContext::addSectionRenaming(raw_ostream &diagnostics,\n StringRef from, StringRef to) {\n auto it = _renamedSections.find(from);\n if (it != _renamedSections.end()) {\n if (it->second == to)\n \/\/ There's already the same mapping.\n return true;\n diagnostics << \"Section \\\"\" << from << \"\\\" is already mapped to \\\"\"\n << it->second << \", so it cannot be mapped to \\\"\" << to << \"\\\".\";\n return true;\n }\n\n \/\/ Add a mapping, and check if there's no cycle in the renaming mapping. The\n \/\/ cycle detection algorithm we use here is naive, but that's OK because the\n \/\/ number of mapping is usually less than 10.\n _renamedSections[from] = to;\n for (auto elem : _renamedSections) {\n StringRef sectionName = elem.first;\n std::set<StringRef> visited;\n visited.insert(sectionName);\n for (;;) {\n auto pos = _renamedSections.find(sectionName);\n if (pos == _renamedSections.end())\n break;\n if (visited.count(pos->second)) {\n diagnostics << \"\/merge:\" << from << \"=\" << to << \" makes a cycle\";\n return false;\n }\n sectionName = pos->second;\n visited.insert(sectionName);\n }\n }\n return true;\n}\n\nStringRef PECOFFLinkingContext::getAlternateName(StringRef def) const {\n auto it = _alternateNames.find(def);\n if (it == _alternateNames.end())\n return \"\";\n return it->second;\n}\n\nvoid PECOFFLinkingContext::setAlternateName(StringRef weak, StringRef def) {\n _alternateNames[def] = weak;\n}\n\n\/\/\/ Try to find the input library file from the search paths and append it to\n\/\/\/ the input file list. Returns true if the library file is found.\nStringRef PECOFFLinkingContext::searchLibraryFile(StringRef filename) const {\n \/\/ Current directory always takes precedence over the search paths.\n if (llvm::sys::path::is_absolute(filename) || llvm::sys::fs::exists(filename))\n return filename;\n \/\/ Iterate over the search paths.\n for (StringRef dir : _inputSearchPaths) {\n SmallString<128> path = dir;\n llvm::sys::path::append(path, filename);\n if (llvm::sys::fs::exists(path.str()))\n return allocate(path.str());\n }\n return filename;\n}\n\n\/\/\/ Returns the decorated name of the given symbol name. On 32-bit x86, it\n\/\/\/ adds \"_\" at the beginning of the string. On other architectures, the\n\/\/\/ return value is the same as the argument.\nStringRef PECOFFLinkingContext::decorateSymbol(StringRef name) const {\n if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386)\n return name;\n std::string str = \"_\";\n str.append(name);\n return allocate(str);\n}\n\nStringRef PECOFFLinkingContext::undecorateSymbol(StringRef name) const {\n if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386)\n return name;\n assert(name.startswith(\"_\"));\n return name.substr(1);\n}\n\nWriter &PECOFFLinkingContext::writer() const { return *_writer; }\n\n\nvoid PECOFFLinkingContext::setSectionSetMask(StringRef sectionName,\n uint32_t newFlags) {\n _sectionSetMask[sectionName] |= newFlags;\n _sectionClearMask[sectionName] &= ~newFlags;\n const uint32_t rwx = (llvm::COFF::IMAGE_SCN_MEM_READ |\n llvm::COFF::IMAGE_SCN_MEM_WRITE |\n llvm::COFF::IMAGE_SCN_MEM_EXECUTE);\n if (newFlags & rwx)\n _sectionClearMask[sectionName] |= ~_sectionSetMask[sectionName] & rwx;\n assert((_sectionSetMask[sectionName] & _sectionClearMask[sectionName]) == 0);\n}\n\nvoid PECOFFLinkingContext::setSectionClearMask(StringRef sectionName,\n uint32_t newFlags) {\n _sectionClearMask[sectionName] |= newFlags;\n _sectionSetMask[sectionName] &= ~newFlags;\n assert((_sectionSetMask[sectionName] & _sectionClearMask[sectionName]) == 0);\n}\n\nuint32_t PECOFFLinkingContext::getSectionAttributes(StringRef sectionName,\n uint32_t flags) const {\n auto si = _sectionSetMask.find(sectionName);\n uint32_t setMask = (si == _sectionSetMask.end()) ? 0 : si->second;\n auto ci = _sectionClearMask.find(sectionName);\n uint32_t clearMask = (ci == _sectionClearMask.end()) ? 0 : ci->second;\n return (flags | setMask) & ~clearMask;\n}\n\nvoid PECOFFLinkingContext::addDllExport(ExportDesc &desc) {\n if (_dllExportSet.count(desc.name)) {\n llvm::errs() << \"Export symbol '\" << desc.name\n << \"' specified more than once.\";\n return;\n }\n _dllExports.push_back(desc);\n _dllExportSet.insert(_dllExports.back().name);\n}\n\nvoid PECOFFLinkingContext::addPasses(PassManager &pm) {\n pm.add(std::unique_ptr<Pass>(new pecoff::SetSubsystemPass(*this)));\n pm.add(std::unique_ptr<Pass>(new pecoff::EdataPass(*this)));\n pm.add(std::unique_ptr<Pass>(new pecoff::IdataPass(*this)));\n pm.add(std::unique_ptr<Pass>(new LayoutPass()));\n pm.add(std::unique_ptr<Pass>(new pecoff::GroupedSectionsPass()));\n}\n\n} \/\/ end namespace lld\n<commit_msg>Add a newline to an error message.<commit_after>\/\/===- lib\/ReaderWriter\/PECOFF\/PECOFFLinkingContext.cpp -------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Atoms.h\"\n#include \"EdataPass.h\"\n#include \"GroupedSectionsPass.h\"\n#include \"IdataPass.h\"\n#include \"LinkerGeneratedSymbolFile.h\"\n#include \"SetSubsystemPass.h\"\n\n#include \"lld\/Core\/PassManager.h\"\n#include \"lld\/Passes\/LayoutPass.h\"\n#include \"lld\/Passes\/RoundTripNativePass.h\"\n#include \"lld\/Passes\/RoundTripYAMLPass.h\"\n#include \"lld\/ReaderWriter\/PECOFFLinkingContext.h\"\n#include \"lld\/ReaderWriter\/Reader.h\"\n#include \"lld\/ReaderWriter\/Simple.h\"\n#include \"lld\/ReaderWriter\/Writer.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/Allocator.h\"\n#include \"llvm\/Support\/Path.h\"\n\n#include <bitset>\n#include <climits>\n#include <set>\n\nnamespace lld {\n\nstatic void assignOrdinals(PECOFFLinkingContext &ctx) {\n int maxOrdinal = -1;\n for (const PECOFFLinkingContext::ExportDesc &desc : ctx.getDllExports())\n maxOrdinal = std::max(maxOrdinal, desc.ordinal);\n int nextOrdinal = (maxOrdinal == -1) ? 1 : (maxOrdinal + 1);\n for (PECOFFLinkingContext::ExportDesc &desc : ctx.getDllExports())\n if (desc.ordinal == -1)\n desc.ordinal = nextOrdinal++;\n}\n\nbool PECOFFLinkingContext::validateImpl(raw_ostream &diagnostics) {\n if (_stackReserve < _stackCommit) {\n diagnostics << \"Invalid stack size: reserve size must be equal to or \"\n << \"greater than commit size, but got \" << _stackCommit\n << \" and \" << _stackReserve << \".\\n\";\n return false;\n }\n\n if (_heapReserve < _heapCommit) {\n diagnostics << \"Invalid heap size: reserve size must be equal to or \"\n << \"greater than commit size, but got \" << _heapCommit\n << \" and \" << _heapReserve << \".\\n\";\n return false;\n }\n\n \/\/ It's an error if the base address is not multiple of 64K.\n if (_baseAddress & 0xffff) {\n diagnostics << \"Base address have to be multiple of 64K, but got \"\n << _baseAddress << \"\\n\";\n return false;\n }\n\n \/\/ Check for duplicate export ordinals.\n std::set<int> exports;\n for (const PECOFFLinkingContext::ExportDesc &desc : getDllExports()) {\n if (desc.ordinal == -1)\n continue;\n if (exports.count(desc.ordinal) == 1) {\n diagnostics << \"Duplicate export ordinals: \" << desc.ordinal << \"\\n\";\n return false;\n }\n exports.insert(desc.ordinal);\n }\n\n std::bitset<64> alignment(_sectionDefaultAlignment);\n if (alignment.count() != 1) {\n diagnostics << \"Section alignment must be a power of 2, but got \"\n << _sectionDefaultAlignment << \"\\n\";\n return false;\n }\n\n \/\/ Architectures other than i386 is not supported yet.\n if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) {\n diagnostics << \"Machine type other than x86 is not supported.\\n\";\n return false;\n }\n\n \/\/ Assign default ordinals to export symbols.\n assignOrdinals(*this);\n\n _writer = createWriterPECOFF(*this);\n return true;\n}\n\nstd::unique_ptr<File> PECOFFLinkingContext::createEntrySymbolFile() const {\n if (entrySymbolName().empty())\n return nullptr;\n std::unique_ptr<SimpleFile> entryFile(\n new SimpleFile(\"command line option \/entry\"));\n entryFile->addAtom(\n *(new (_allocator) SimpleUndefinedAtom(*entryFile, entrySymbolName())));\n return std::move(entryFile);\n}\n\nstd::unique_ptr<File> PECOFFLinkingContext::createUndefinedSymbolFile() const {\n if (_initialUndefinedSymbols.empty())\n return nullptr;\n std::unique_ptr<SimpleFile> undefinedSymFile(\n new SimpleFile(\"command line option \/c (or) \/include\"));\n for (auto undefSymStr : _initialUndefinedSymbols)\n undefinedSymFile->addAtom(*(new (_allocator) SimpleUndefinedAtom(\n *undefinedSymFile, undefSymStr)));\n return std::move(undefinedSymFile);\n}\n\nbool PECOFFLinkingContext::createImplicitFiles(\n std::vector<std::unique_ptr<File> > &) const {\n std::unique_ptr<SimpleFileNode> fileNode(\n new SimpleFileNode(\"Implicit Files\"));\n std::unique_ptr<File> linkerGeneratedSymFile(\n new pecoff::LinkerGeneratedSymbolFile(*this));\n fileNode->appendInputFile(std::move(linkerGeneratedSymFile));\n inputGraph().insertOneElementAt(std::move(fileNode),\n InputGraph::Position::END);\n return true;\n}\n\n\/\/\/ Returns the section name in the resulting executable.\n\/\/\/\n\/\/\/ Sections in object files are usually output to the executable with the same\n\/\/\/ name, but you can rename by command line option. \/merge:from=to makes the\n\/\/\/ linker to combine \"from\" section contents to \"to\" section in the\n\/\/\/ executable. We have a mapping for the renaming. This method looks up the\n\/\/\/ table and returns a new section name if renamed.\nStringRef\nPECOFFLinkingContext::getOutputSectionName(StringRef sectionName) const {\n auto it = _renamedSections.find(sectionName);\n if (it == _renamedSections.end())\n return sectionName;\n return getOutputSectionName(it->second);\n}\n\n\/\/\/ Adds a mapping to the section renaming table. This method will be used for\n\/\/\/ \/merge command line option.\nbool PECOFFLinkingContext::addSectionRenaming(raw_ostream &diagnostics,\n StringRef from, StringRef to) {\n auto it = _renamedSections.find(from);\n if (it != _renamedSections.end()) {\n if (it->second == to)\n \/\/ There's already the same mapping.\n return true;\n diagnostics << \"Section \\\"\" << from << \"\\\" is already mapped to \\\"\"\n << it->second << \", so it cannot be mapped to \\\"\" << to << \"\\\".\";\n return true;\n }\n\n \/\/ Add a mapping, and check if there's no cycle in the renaming mapping. The\n \/\/ cycle detection algorithm we use here is naive, but that's OK because the\n \/\/ number of mapping is usually less than 10.\n _renamedSections[from] = to;\n for (auto elem : _renamedSections) {\n StringRef sectionName = elem.first;\n std::set<StringRef> visited;\n visited.insert(sectionName);\n for (;;) {\n auto pos = _renamedSections.find(sectionName);\n if (pos == _renamedSections.end())\n break;\n if (visited.count(pos->second)) {\n diagnostics << \"\/merge:\" << from << \"=\" << to << \" makes a cycle\";\n return false;\n }\n sectionName = pos->second;\n visited.insert(sectionName);\n }\n }\n return true;\n}\n\nStringRef PECOFFLinkingContext::getAlternateName(StringRef def) const {\n auto it = _alternateNames.find(def);\n if (it == _alternateNames.end())\n return \"\";\n return it->second;\n}\n\nvoid PECOFFLinkingContext::setAlternateName(StringRef weak, StringRef def) {\n _alternateNames[def] = weak;\n}\n\n\/\/\/ Try to find the input library file from the search paths and append it to\n\/\/\/ the input file list. Returns true if the library file is found.\nStringRef PECOFFLinkingContext::searchLibraryFile(StringRef filename) const {\n \/\/ Current directory always takes precedence over the search paths.\n if (llvm::sys::path::is_absolute(filename) || llvm::sys::fs::exists(filename))\n return filename;\n \/\/ Iterate over the search paths.\n for (StringRef dir : _inputSearchPaths) {\n SmallString<128> path = dir;\n llvm::sys::path::append(path, filename);\n if (llvm::sys::fs::exists(path.str()))\n return allocate(path.str());\n }\n return filename;\n}\n\n\/\/\/ Returns the decorated name of the given symbol name. On 32-bit x86, it\n\/\/\/ adds \"_\" at the beginning of the string. On other architectures, the\n\/\/\/ return value is the same as the argument.\nStringRef PECOFFLinkingContext::decorateSymbol(StringRef name) const {\n if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386)\n return name;\n std::string str = \"_\";\n str.append(name);\n return allocate(str);\n}\n\nStringRef PECOFFLinkingContext::undecorateSymbol(StringRef name) const {\n if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386)\n return name;\n assert(name.startswith(\"_\"));\n return name.substr(1);\n}\n\nWriter &PECOFFLinkingContext::writer() const { return *_writer; }\n\n\nvoid PECOFFLinkingContext::setSectionSetMask(StringRef sectionName,\n uint32_t newFlags) {\n _sectionSetMask[sectionName] |= newFlags;\n _sectionClearMask[sectionName] &= ~newFlags;\n const uint32_t rwx = (llvm::COFF::IMAGE_SCN_MEM_READ |\n llvm::COFF::IMAGE_SCN_MEM_WRITE |\n llvm::COFF::IMAGE_SCN_MEM_EXECUTE);\n if (newFlags & rwx)\n _sectionClearMask[sectionName] |= ~_sectionSetMask[sectionName] & rwx;\n assert((_sectionSetMask[sectionName] & _sectionClearMask[sectionName]) == 0);\n}\n\nvoid PECOFFLinkingContext::setSectionClearMask(StringRef sectionName,\n uint32_t newFlags) {\n _sectionClearMask[sectionName] |= newFlags;\n _sectionSetMask[sectionName] &= ~newFlags;\n assert((_sectionSetMask[sectionName] & _sectionClearMask[sectionName]) == 0);\n}\n\nuint32_t PECOFFLinkingContext::getSectionAttributes(StringRef sectionName,\n uint32_t flags) const {\n auto si = _sectionSetMask.find(sectionName);\n uint32_t setMask = (si == _sectionSetMask.end()) ? 0 : si->second;\n auto ci = _sectionClearMask.find(sectionName);\n uint32_t clearMask = (ci == _sectionClearMask.end()) ? 0 : ci->second;\n return (flags | setMask) & ~clearMask;\n}\n\nvoid PECOFFLinkingContext::addDllExport(ExportDesc &desc) {\n if (_dllExportSet.count(desc.name)) {\n llvm::errs() << \"Export symbol '\" << desc.name\n << \"' specified more than once.\\n\";\n return;\n }\n _dllExports.push_back(desc);\n _dllExportSet.insert(_dllExports.back().name);\n}\n\nvoid PECOFFLinkingContext::addPasses(PassManager &pm) {\n pm.add(std::unique_ptr<Pass>(new pecoff::SetSubsystemPass(*this)));\n pm.add(std::unique_ptr<Pass>(new pecoff::EdataPass(*this)));\n pm.add(std::unique_ptr<Pass>(new pecoff::IdataPass(*this)));\n pm.add(std::unique_ptr<Pass>(new LayoutPass()));\n pm.add(std::unique_ptr<Pass>(new pecoff::GroupedSectionsPass()));\n}\n\n} \/\/ end namespace lld\n<|endoftext|>"} {"text":"<commit_before>#include <imgui\/imgui.h>\n\n#include \"game_view.h\"\n#include \"editor\/asset_browser.h\"\n#include \"editor\/asset_compiler.h\"\n#include \"editor\/studio_app.h\"\n#include \"editor\/utils.h\"\n#include \"editor\/world_editor.h\"\n#include \"engine\/crc32.h\"\n#include \"engine\/engine.h\"\n#include \"engine\/geometry.h\"\n#include \"engine\/input_system.h\"\n#include \"engine\/lua_wrapper.h\"\n#include \"engine\/plugin_manager.h\"\n#include \"engine\/profiler.h\"\n#include \"engine\/resource_manager.h\"\n#include \"engine\/universe\/universe.h\"\n#include \"gui\/gui_system.h\"\n#include \"renderer\/gpu\/gpu.h\"\n#include \"renderer\/pipeline.h\"\n#include \"renderer\/render_scene.h\"\n#include \"renderer\/renderer.h\"\n#include \"renderer\/texture.h\"\n\n\nnamespace Lumix\n{\n\n\nstruct GUIInterface : GUISystem::Interface\n{\n\texplicit GUIInterface(GameView& game_view)\n\t\t: m_game_view(game_view)\n\t{\n\t}\n\n\tPipeline* getPipeline() override { return m_game_view.m_pipeline; }\n\tVec2 getPos() const override { return m_game_view.m_pos; }\n\tVec2 getSize() const override { return m_game_view.m_size; }\n\n\t\n\tvoid enableCursor(bool enable) override\n\t{ \n\t\tm_game_view.enableIngameCursor(enable);\n\t}\n\n\n\tGameView& m_game_view;\n};\n\n\nGameView::GameView(StudioApp& app)\n\t: m_studio_app(app)\n\t, m_is_open(false)\n\t, m_is_fullscreen(false)\n\t, m_pipeline(nullptr)\n\t, m_is_mouse_captured(false)\n\t, m_is_ingame_cursor(false)\n\t, m_time_multiplier(1.0f)\n\t, m_paused(false)\n\t, m_show_stats(false)\n\t, m_gui_interface(nullptr)\n\t, m_editor(app.getWorldEditor())\n{\n\tEngine& engine = app.getWorldEditor().getEngine();\n\tauto f = &LuaWrapper::wrapMethodClosure<&GameView::forceViewport>;\n\tLuaWrapper::createSystemClosure(engine.getState(), \"GameView\", this, \"forceViewport\", f);\n\n\tWorldEditor& editor = app.getWorldEditor();\n\tAction* action = LUMIX_NEW(editor.getAllocator(), Action)(\"Game View\", \"Toggle game view\", \"game_view\");\n\taction->func.bind<&GameView::onAction>(this);\n\taction->is_selected.bind<&GameView::isOpen>(this);\n\tapp.addWindowAction(action);\n\n\tAction* fullscreen_action = LUMIX_NEW(editor.getAllocator(), Action)(\"Game View fullscreen\", \"Game View fullscreen\", \"game_view_fullscreen\");\n\tfullscreen_action->func.bind<&GameView::toggleFullscreen>(this);\n\tapp.addAction(fullscreen_action);\n\n\tauto* renderer = (Renderer*)engine.getPluginManager().getPlugin(\"renderer\");\n\tPipelineResource* pres = engine.getResourceManager().load<PipelineResource>(Path(\"pipelines\/main.pln\"));\n\tm_pipeline = Pipeline::create(*renderer, pres, \"GAME_VIEW\", engine.getAllocator());\n\n\teditor.universeCreated().bind<&GameView::onUniverseCreated>(this);\n\teditor.universeDestroyed().bind<&GameView::onUniverseDestroyed>(this);\n\tif (editor.getUniverse()) onUniverseCreated();\n\n\tauto* gui = static_cast<GUISystem*>(engine.getPluginManager().getPlugin(\"gui\"));\n\tif (gui)\n\t{\n\t\tm_gui_interface = LUMIX_NEW(engine.getAllocator(), GUIInterface)(*this);\n\t\tgui->setInterface(m_gui_interface);\n\t}\n}\n\n\nGameView::~GameView()\n{\n\tm_editor.universeCreated().unbind<&GameView::onUniverseCreated>(this);\n\tm_editor.universeDestroyed().unbind<&GameView::onUniverseDestroyed>(this);\n\tauto* gui = static_cast<GUISystem*>(m_editor.getEngine().getPluginManager().getPlugin(\"gui\"));\n\tif (gui)\n\t{\n\t\tgui->setInterface(nullptr);\n\t\tLUMIX_DELETE(m_editor.getEngine().getAllocator(), m_gui_interface);\n\t}\n\tPipeline::destroy(m_pipeline);\n\tm_pipeline = nullptr;\n\n}\n\n\nvoid GameView::enableIngameCursor(bool enable)\n{\n\tm_is_ingame_cursor = enable;\n\tif (!m_is_mouse_captured) return;\n\n\tOS::showCursor(m_is_ingame_cursor);\n}\n\n\nvoid GameView::onUniverseCreated()\n{\n\tauto* scene = m_editor.getUniverse()->getScene(crc32(\"renderer\"));\n\tm_pipeline->setScene(static_cast<RenderScene*>(scene));\n}\n\n\nvoid GameView::onUniverseDestroyed()\n{\n\tm_pipeline->setScene(nullptr);\n}\n\n\n\nvoid GameView::setScene(RenderScene* scene)\n{\n\tm_pipeline->setScene(scene);\n}\n\n\nvoid GameView::captureMouse(bool capture)\n{\n\tif (m_is_mouse_captured == capture) return;\n\n\tm_is_mouse_captured = capture;\n\tm_editor.getEngine().getInputSystem().enable(m_is_mouse_captured);\n\tOS::showCursor(!capture || m_is_ingame_cursor);\n\t\n\tif (capture) {\n\t\tconst OS::Point cp = OS::getMouseScreenPos();\n\t\tm_captured_mouse_x = cp.x;\n\t\tm_captured_mouse_y = cp.y;\n\t}\n\telse {\n\t\tOS::unclipCursor();\n\t\tOS::setMouseScreenPos(m_captured_mouse_x, m_captured_mouse_y);\n\t}\n}\n\n\nvoid GameView::onFullscreenGUI()\n{\n\tprocessInputEvents();\n\n\tImGuiIO& io = ImGui::GetIO();\n\tbool open = true;\n\tImVec2 size = io.DisplaySize;\n\tImGui::SetNextWindowPos(ImGui::GetMainViewport()->Pos);\n\tImGui::SetNextWindowSize(size);\n\tif (!ImGui::Begin(\"game view fullscreen\",\n\t\t&open,\n\t\tImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse |\n\t\tImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))\n\t{\n\t\tImGui::End();\n\t\treturn;\n\t}\n\n\tEntityPtr camera = m_pipeline->getScene()->getActiveCamera();\n\tif (camera.isValid()) {\n\t\tViewport vp = m_pipeline->getScene()->getCameraViewport((EntityRef)camera);\n\t\tvp.w = (int)size.x;\n\t\tvp.h = (int)size.y;\n\t\tm_pipeline->getScene()->setCameraScreenSize((EntityRef)camera, vp.w, vp.h);\n\t\tm_pipeline->setViewport(vp);\n\t\tm_pipeline->render(false);\n\t\tconst gpu::TextureHandle texture_handle = m_pipeline->getOutput();\n\t\tif (gpu::isOriginBottomLeft())\n\t\t{\n\t\t\tImGui::Image((void*)(uintptr_t)texture_handle.value, size, ImVec2(0, 1), ImVec2(1, 0));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tImGui::Image((void*)(uintptr_t)texture_handle.value, size);\n\t\t}\n\t}\n\telse {\n\t\tImGui::Rect(size.x, size.y, 0xff0000FF);\n\t}\n\tm_pos = ImGui::GetItemRectMin();\n\tm_size = ImGui::GetItemRectSize();\n\n\tImGui::End();\n\n\tif (m_is_fullscreen && (io.KeysDown[ImGui::GetKeyIndex(ImGuiKey_Escape)] || !m_editor.isGameMode()))\n\t{\n\t\tsetFullscreen(false);\n\t}\n}\n\n\nvoid GameView::toggleFullscreen()\n{\n\tif (!m_editor.isGameMode()) return;\n\tsetFullscreen(!m_is_fullscreen);\n}\n\n\nvoid GameView::setFullscreen(bool fullscreen)\n{\n\tcaptureMouse(fullscreen);\n\tm_studio_app.setFullscreen(fullscreen);\n\tm_is_fullscreen = fullscreen;\n}\n\n\nvoid GameView::onStatsGUI(const ImVec2& view_pos)\n{\n\tif (!m_show_stats || !m_is_open) return;\n\t\n\tfloat toolbar_height = 24 + ImGui::GetStyle().FramePadding.y * 2;\n\tImVec2 v = view_pos;\n\tv.x += ImGui::GetStyle().FramePadding.x;\n\tv.y += ImGui::GetStyle().FramePadding.y + toolbar_height;\n\tImGui::SetNextWindowPos(v);\n\tauto col = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];\n\tcol.w = 0.3f;\n\tImGui::PushStyleColor(ImGuiCol_WindowBg, col);\n\tImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings;\n\tif (ImGui::Begin(\"###stats_overlay\", nullptr, flags)) {\n\t\tconst auto& stats = m_pipeline->getStats();\n\t\tImGui::LabelText(\"Draw calls\", \"%d\", stats.draw_call_count);\n\t\tImGui::LabelText(\"Instances\", \"%d\", stats.instance_count);\n\t\tchar buf[30];\n\t\ttoCStringPretty(stats.triangle_count, Span(buf));\n\t\tImGui::LabelText(\"Triangles\", \"%s\", buf);\n\t\tImGui::LabelText(\"Resolution\", \"%dx%d\", (int)m_size.x, (int)m_size.y);\n\t}\n\tImGui::End();\n\tImGui::PopStyleColor();\n}\n\n\nvoid GameView::forceViewport(bool enable, int w, int h)\n{\n\tm_forced_viewport.enabled = enable;\n\tm_forced_viewport.width = w;\n\tm_forced_viewport.height = h;\n}\n\nvoid GameView::processInputEvents()\n{\n\tif (!m_is_mouse_captured) return;\n\t\n\tInputSystem& input = m_editor.getEngine().getInputSystem();\n\tconst OS::Event* events = m_studio_app.getEvents();\n\tfor (int i = 0, c = m_studio_app.getEventsCount(); i < c; ++i) {\n\t\tinput.injectEvent(events[i]);\n\t}\n}\n\nvoid GameView::controlsGUI() {\n\tif (ImGui::Checkbox(\"Pause\", &m_paused)) m_editor.getEngine().pause(m_paused);\n\tif (m_paused) {\n\t\tImGui::SameLine();\n\t\tif (ImGui::Button(\"Next frame\")) m_editor.getEngine().nextFrame();\n\t}\n\tImGui::SameLine();\n\tImGui::PushItemWidth(50);\n\tif (ImGui::DragFloat(\"Time multiplier\", &m_time_multiplier, 0.01f, 0.01f, 30.0f)) {\n\t\tm_editor.getEngine().setTimeMultiplier(m_time_multiplier);\n\t}\n\tImGui::PopItemWidth();\n\tif(m_editor.isGameMode()) {\n\t\tImGui::SameLine();\n\t\tif (ImGui::Button(\"Fullscreen\")) setFullscreen(true);\n\t}\n\tImGui::SameLine();\n\tImGui::Checkbox(\"Stats\", &m_show_stats);\n\tImGui::SameLine();\n\tm_pipeline->callLuaFunction(\"onGUI\");\n}\n\n\nvoid GameView::onWindowGUI()\n{\n\tPROFILE_FUNCTION();\n\tif (!m_pipeline->isReady()) {\n\t\tcaptureMouse(false);\n\t\treturn;\n\t}\n\n\tImGuiIO& io = ImGui::GetIO();\n\tif (m_is_mouse_captured && (io.KeysDown[ImGui::GetKeyIndex(ImGuiKey_Escape)] || !m_editor.isGameMode())) {\n\t\tcaptureMouse(false);\n\t}\n\n\tconst char* window_name = \"Game View###game_view\";\n\tif (m_is_mouse_captured) window_name = \"Game View (mouse captured)###game_view\";\n\t\n\tif (m_is_fullscreen) {\n\t\tonFullscreenGUI();\n\t\treturn;\n\t}\n\n\tif (!m_is_open) {\n\t\tcaptureMouse(false);\n\t\treturn;\n\t}\n\n\tImVec2 view_pos;\n\tbool is_game_view_visible = false;\n\tif (ImGui::Begin(window_name, &m_is_open, ImGuiWindowFlags_NoNavInputs)) {\n\t\tis_game_view_visible = true;\n\t\tview_pos = ImGui::GetCursorScreenPos();\n\n\t\tconst ImVec2 content_min = ImGui::GetCursorScreenPos();\n\t\tImVec2 size = ImGui::GetContentRegionAvail();\n\t\tsize.y -= ImGui::GetTextLineHeightWithSpacing();\n\t\tImVec2 content_max(content_min.x + size.x, content_min.y + size.y);\n\t\tif (m_forced_viewport.enabled) size = { (float)m_forced_viewport.width, (float)m_forced_viewport.height };\n\t\tif (size.x > 0 && size.y > 0) {\n\t\t\tRenderScene* scene = m_pipeline->getScene();\n\t\t\tconst EntityPtr camera = scene->getActiveCamera();\n\t\t\tViewport vp;\n\t\t\tvp.w = (int)size.x;\n\t\t\tvp.h = (int)size.y;\n\t\t\tif (camera.isValid()) {\n\t\t\t\tvp = scene->getCameraViewport((EntityRef)camera);\n\t\t\t\tscene->setCameraScreenSize((EntityRef)camera, vp.w, vp.h);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvp.fov = degreesToRadians(90.f);\n\t\t\t\tvp.is_ortho = false;\n\t\t\t\tvp.far = 10'000.f;\n\t\t\t\tvp.near = 1.f;\n\t\t\t\tvp.pos = DVec3(0);\n\t\t\t\tvp.rot = Quat(0, 0, 0, 1);\n\t\t\t}\n\t\t\tm_pipeline->setViewport(vp);\n\t\t\tm_pipeline->render(false);\n\t\t\tconst gpu::TextureHandle texture_handle = m_pipeline->getOutput();\n\n\t\t\tif (texture_handle.isValid()) {\n\t\t\t\tif (gpu::isOriginBottomLeft()) {\n\t\t\t\t\tImGui::Image((void*)(uintptr_t)texture_handle.value, size, ImVec2(0, 1), ImVec2(1, 0));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tImGui::Image((void*)(uintptr_t)texture_handle.value, size);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tImGui::Rect(size.x, size.y, 0xffFF00FF);\n\t\t\t}\n\t\t\tconst bool is_hovered = ImGui::IsItemHovered();\n\t\t\tif (is_hovered && ImGui::IsMouseClicked(0) && m_editor.isGameMode()) captureMouse(true);\n\t\t\tm_pos = ImGui::GetItemRectMin();\n\t\t\tm_size = ImGui::GetItemRectSize();\n\n\t\t\tif (m_is_mouse_captured && m_is_ingame_cursor) {\n\t\t\t\tOS::clipCursor(ImGui::GetWindowViewport()->PlatformHandle, (int)m_pos.x, (int)m_pos.y, (int)m_size.x, (int)m_size.y);\n\t\t\t}\n\n\t\t\tprocessInputEvents();\n\t\t\tcontrolsGUI();\n\t\t}\n\n\t}\n\tif (m_is_mouse_captured && OS::getFocused() != ImGui::GetWindowViewport()->PlatformHandle) captureMouse(false);\n\tImGui::End();\n\tif (is_game_view_visible) onStatsGUI(view_pos);\n}\n\n\n} \/\/ namespace Lumix\n<commit_msg>fixed game view resolution<commit_after>#include <imgui\/imgui.h>\n\n#include \"game_view.h\"\n#include \"editor\/asset_browser.h\"\n#include \"editor\/asset_compiler.h\"\n#include \"editor\/studio_app.h\"\n#include \"editor\/utils.h\"\n#include \"editor\/world_editor.h\"\n#include \"engine\/crc32.h\"\n#include \"engine\/engine.h\"\n#include \"engine\/geometry.h\"\n#include \"engine\/input_system.h\"\n#include \"engine\/lua_wrapper.h\"\n#include \"engine\/plugin_manager.h\"\n#include \"engine\/profiler.h\"\n#include \"engine\/resource_manager.h\"\n#include \"engine\/universe\/universe.h\"\n#include \"gui\/gui_system.h\"\n#include \"renderer\/gpu\/gpu.h\"\n#include \"renderer\/pipeline.h\"\n#include \"renderer\/render_scene.h\"\n#include \"renderer\/renderer.h\"\n#include \"renderer\/texture.h\"\n\n\nnamespace Lumix\n{\n\n\nstruct GUIInterface : GUISystem::Interface\n{\n\texplicit GUIInterface(GameView& game_view)\n\t\t: m_game_view(game_view)\n\t{\n\t}\n\n\tPipeline* getPipeline() override { return m_game_view.m_pipeline; }\n\tVec2 getPos() const override { return m_game_view.m_pos; }\n\tVec2 getSize() const override { return m_game_view.m_size; }\n\n\t\n\tvoid enableCursor(bool enable) override\n\t{ \n\t\tm_game_view.enableIngameCursor(enable);\n\t}\n\n\n\tGameView& m_game_view;\n};\n\n\nGameView::GameView(StudioApp& app)\n\t: m_studio_app(app)\n\t, m_is_open(false)\n\t, m_is_fullscreen(false)\n\t, m_pipeline(nullptr)\n\t, m_is_mouse_captured(false)\n\t, m_is_ingame_cursor(false)\n\t, m_time_multiplier(1.0f)\n\t, m_paused(false)\n\t, m_show_stats(false)\n\t, m_gui_interface(nullptr)\n\t, m_editor(app.getWorldEditor())\n{\n\tEngine& engine = app.getWorldEditor().getEngine();\n\tauto f = &LuaWrapper::wrapMethodClosure<&GameView::forceViewport>;\n\tLuaWrapper::createSystemClosure(engine.getState(), \"GameView\", this, \"forceViewport\", f);\n\n\tWorldEditor& editor = app.getWorldEditor();\n\tAction* action = LUMIX_NEW(editor.getAllocator(), Action)(\"Game View\", \"Toggle game view\", \"game_view\");\n\taction->func.bind<&GameView::onAction>(this);\n\taction->is_selected.bind<&GameView::isOpen>(this);\n\tapp.addWindowAction(action);\n\n\tAction* fullscreen_action = LUMIX_NEW(editor.getAllocator(), Action)(\"Game View fullscreen\", \"Game View fullscreen\", \"game_view_fullscreen\");\n\tfullscreen_action->func.bind<&GameView::toggleFullscreen>(this);\n\tapp.addAction(fullscreen_action);\n\n\tauto* renderer = (Renderer*)engine.getPluginManager().getPlugin(\"renderer\");\n\tPipelineResource* pres = engine.getResourceManager().load<PipelineResource>(Path(\"pipelines\/main.pln\"));\n\tm_pipeline = Pipeline::create(*renderer, pres, \"GAME_VIEW\", engine.getAllocator());\n\n\teditor.universeCreated().bind<&GameView::onUniverseCreated>(this);\n\teditor.universeDestroyed().bind<&GameView::onUniverseDestroyed>(this);\n\tif (editor.getUniverse()) onUniverseCreated();\n\n\tauto* gui = static_cast<GUISystem*>(engine.getPluginManager().getPlugin(\"gui\"));\n\tif (gui)\n\t{\n\t\tm_gui_interface = LUMIX_NEW(engine.getAllocator(), GUIInterface)(*this);\n\t\tgui->setInterface(m_gui_interface);\n\t}\n}\n\n\nGameView::~GameView()\n{\n\tm_editor.universeCreated().unbind<&GameView::onUniverseCreated>(this);\n\tm_editor.universeDestroyed().unbind<&GameView::onUniverseDestroyed>(this);\n\tauto* gui = static_cast<GUISystem*>(m_editor.getEngine().getPluginManager().getPlugin(\"gui\"));\n\tif (gui)\n\t{\n\t\tgui->setInterface(nullptr);\n\t\tLUMIX_DELETE(m_editor.getEngine().getAllocator(), m_gui_interface);\n\t}\n\tPipeline::destroy(m_pipeline);\n\tm_pipeline = nullptr;\n\n}\n\n\nvoid GameView::enableIngameCursor(bool enable)\n{\n\tm_is_ingame_cursor = enable;\n\tif (!m_is_mouse_captured) return;\n\n\tOS::showCursor(m_is_ingame_cursor);\n}\n\n\nvoid GameView::onUniverseCreated()\n{\n\tauto* scene = m_editor.getUniverse()->getScene(crc32(\"renderer\"));\n\tm_pipeline->setScene(static_cast<RenderScene*>(scene));\n}\n\n\nvoid GameView::onUniverseDestroyed()\n{\n\tm_pipeline->setScene(nullptr);\n}\n\n\n\nvoid GameView::setScene(RenderScene* scene)\n{\n\tm_pipeline->setScene(scene);\n}\n\n\nvoid GameView::captureMouse(bool capture)\n{\n\tif (m_is_mouse_captured == capture) return;\n\n\tm_is_mouse_captured = capture;\n\tm_editor.getEngine().getInputSystem().enable(m_is_mouse_captured);\n\tOS::showCursor(!capture || m_is_ingame_cursor);\n\t\n\tif (capture) {\n\t\tconst OS::Point cp = OS::getMouseScreenPos();\n\t\tm_captured_mouse_x = cp.x;\n\t\tm_captured_mouse_y = cp.y;\n\t}\n\telse {\n\t\tOS::unclipCursor();\n\t\tOS::setMouseScreenPos(m_captured_mouse_x, m_captured_mouse_y);\n\t}\n}\n\n\nvoid GameView::onFullscreenGUI()\n{\n\tprocessInputEvents();\n\n\tImGuiIO& io = ImGui::GetIO();\n\tbool open = true;\n\tImVec2 size = io.DisplaySize;\n\tImGui::SetNextWindowPos(ImGui::GetMainViewport()->Pos);\n\tImGui::SetNextWindowSize(size);\n\tif (!ImGui::Begin(\"game view fullscreen\",\n\t\t&open,\n\t\tImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse |\n\t\tImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))\n\t{\n\t\tImGui::End();\n\t\treturn;\n\t}\n\n\tEntityPtr camera = m_pipeline->getScene()->getActiveCamera();\n\tif (camera.isValid()) {\n\t\tViewport vp = m_pipeline->getScene()->getCameraViewport((EntityRef)camera);\n\t\tvp.w = (int)size.x;\n\t\tvp.h = (int)size.y;\n\t\tm_pipeline->getScene()->setCameraScreenSize((EntityRef)camera, vp.w, vp.h);\n\t\tm_pipeline->setViewport(vp);\n\t\tm_pipeline->render(false);\n\t\tconst gpu::TextureHandle texture_handle = m_pipeline->getOutput();\n\t\tif (gpu::isOriginBottomLeft())\n\t\t{\n\t\t\tImGui::Image((void*)(uintptr_t)texture_handle.value, size, ImVec2(0, 1), ImVec2(1, 0));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tImGui::Image((void*)(uintptr_t)texture_handle.value, size);\n\t\t}\n\t}\n\telse {\n\t\tImGui::Rect(size.x, size.y, 0xff0000FF);\n\t}\n\tm_pos = ImGui::GetItemRectMin();\n\tm_size = ImGui::GetItemRectSize();\n\n\tImGui::End();\n\n\tif (m_is_fullscreen && (io.KeysDown[ImGui::GetKeyIndex(ImGuiKey_Escape)] || !m_editor.isGameMode()))\n\t{\n\t\tsetFullscreen(false);\n\t}\n}\n\n\nvoid GameView::toggleFullscreen()\n{\n\tif (!m_editor.isGameMode()) return;\n\tsetFullscreen(!m_is_fullscreen);\n}\n\n\nvoid GameView::setFullscreen(bool fullscreen)\n{\n\tcaptureMouse(fullscreen);\n\tm_studio_app.setFullscreen(fullscreen);\n\tm_is_fullscreen = fullscreen;\n}\n\n\nvoid GameView::onStatsGUI(const ImVec2& view_pos)\n{\n\tif (!m_show_stats || !m_is_open) return;\n\t\n\tfloat toolbar_height = 24 + ImGui::GetStyle().FramePadding.y * 2;\n\tImVec2 v = view_pos;\n\tv.x += ImGui::GetStyle().FramePadding.x;\n\tv.y += ImGui::GetStyle().FramePadding.y + toolbar_height;\n\tImGui::SetNextWindowPos(v);\n\tauto col = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];\n\tcol.w = 0.3f;\n\tImGui::PushStyleColor(ImGuiCol_WindowBg, col);\n\tImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings;\n\tif (ImGui::Begin(\"###stats_overlay\", nullptr, flags)) {\n\t\tconst auto& stats = m_pipeline->getStats();\n\t\tImGui::LabelText(\"Draw calls\", \"%d\", stats.draw_call_count);\n\t\tImGui::LabelText(\"Instances\", \"%d\", stats.instance_count);\n\t\tchar buf[30];\n\t\ttoCStringPretty(stats.triangle_count, Span(buf));\n\t\tImGui::LabelText(\"Triangles\", \"%s\", buf);\n\t\tImGui::LabelText(\"Resolution\", \"%dx%d\", (int)m_size.x, (int)m_size.y);\n\t}\n\tImGui::End();\n\tImGui::PopStyleColor();\n}\n\n\nvoid GameView::forceViewport(bool enable, int w, int h)\n{\n\tm_forced_viewport.enabled = enable;\n\tm_forced_viewport.width = w;\n\tm_forced_viewport.height = h;\n}\n\nvoid GameView::processInputEvents()\n{\n\tif (!m_is_mouse_captured) return;\n\t\n\tInputSystem& input = m_editor.getEngine().getInputSystem();\n\tconst OS::Event* events = m_studio_app.getEvents();\n\tfor (int i = 0, c = m_studio_app.getEventsCount(); i < c; ++i) {\n\t\tinput.injectEvent(events[i]);\n\t}\n}\n\nvoid GameView::controlsGUI() {\n\tif (ImGui::Checkbox(\"Pause\", &m_paused)) m_editor.getEngine().pause(m_paused);\n\tif (m_paused) {\n\t\tImGui::SameLine();\n\t\tif (ImGui::Button(\"Next frame\")) m_editor.getEngine().nextFrame();\n\t}\n\tImGui::SameLine();\n\tImGui::PushItemWidth(50);\n\tif (ImGui::DragFloat(\"Time multiplier\", &m_time_multiplier, 0.01f, 0.01f, 30.0f)) {\n\t\tm_editor.getEngine().setTimeMultiplier(m_time_multiplier);\n\t}\n\tImGui::PopItemWidth();\n\tif(m_editor.isGameMode()) {\n\t\tImGui::SameLine();\n\t\tif (ImGui::Button(\"Fullscreen\")) setFullscreen(true);\n\t}\n\tImGui::SameLine();\n\tImGui::Checkbox(\"Stats\", &m_show_stats);\n\tImGui::SameLine();\n\tm_pipeline->callLuaFunction(\"onGUI\");\n}\n\n\nvoid GameView::onWindowGUI()\n{\n\tPROFILE_FUNCTION();\n\tif (!m_pipeline->isReady()) {\n\t\tcaptureMouse(false);\n\t\treturn;\n\t}\n\n\tImGuiIO& io = ImGui::GetIO();\n\tif (m_is_mouse_captured && (io.KeysDown[ImGui::GetKeyIndex(ImGuiKey_Escape)] || !m_editor.isGameMode())) {\n\t\tcaptureMouse(false);\n\t}\n\n\tconst char* window_name = \"Game View###game_view\";\n\tif (m_is_mouse_captured) window_name = \"Game View (mouse captured)###game_view\";\n\t\n\tif (m_is_fullscreen) {\n\t\tonFullscreenGUI();\n\t\treturn;\n\t}\n\n\tif (!m_is_open) {\n\t\tcaptureMouse(false);\n\t\treturn;\n\t}\n\n\tImVec2 view_pos;\n\tbool is_game_view_visible = false;\n\tif (ImGui::Begin(window_name, &m_is_open, ImGuiWindowFlags_NoNavInputs)) {\n\t\tis_game_view_visible = true;\n\t\tview_pos = ImGui::GetCursorScreenPos();\n\n\t\tconst ImVec2 content_min = ImGui::GetCursorScreenPos();\n\t\tImVec2 size = ImGui::GetContentRegionAvail();\n\t\tsize.y -= ImGui::GetTextLineHeightWithSpacing();\n\t\tImVec2 content_max(content_min.x + size.x, content_min.y + size.y);\n\t\tif (m_forced_viewport.enabled) size = { (float)m_forced_viewport.width, (float)m_forced_viewport.height };\n\t\tif (size.x > 0 && size.y > 0) {\n\t\t\tRenderScene* scene = m_pipeline->getScene();\n\t\t\tconst EntityPtr camera = scene->getActiveCamera();\n\t\t\tViewport vp;\n\t\t\tif (camera.isValid()) {\n\t\t\t\tvp = scene->getCameraViewport((EntityRef)camera);\n\t\t\t\tvp.w = (int)size.x;\n\t\t\t\tvp.h = (int)size.y;\n\t\t\t\tscene->setCameraScreenSize((EntityRef)camera, vp.w, vp.h);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvp.w = (int)size.x;\n\t\t\t\tvp.h = (int)size.y;\n\t\t\t\tvp.fov = degreesToRadians(90.f);\n\t\t\t\tvp.is_ortho = false;\n\t\t\t\tvp.far = 10'000.f;\n\t\t\t\tvp.near = 1.f;\n\t\t\t\tvp.pos = DVec3(0);\n\t\t\t\tvp.rot = Quat(0, 0, 0, 1);\n\t\t\t}\n\t\t\tm_pipeline->setViewport(vp);\n\t\t\tm_pipeline->render(false);\n\t\t\tconst gpu::TextureHandle texture_handle = m_pipeline->getOutput();\n\n\t\t\tif (texture_handle.isValid()) {\n\t\t\t\tif (gpu::isOriginBottomLeft()) {\n\t\t\t\t\tImGui::Image((void*)(uintptr_t)texture_handle.value, size, ImVec2(0, 1), ImVec2(1, 0));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tImGui::Image((void*)(uintptr_t)texture_handle.value, size);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tImGui::Rect(size.x, size.y, 0xffFF00FF);\n\t\t\t}\n\t\t\tconst bool is_hovered = ImGui::IsItemHovered();\n\t\t\tif (is_hovered && ImGui::IsMouseClicked(0) && m_editor.isGameMode()) captureMouse(true);\n\t\t\tm_pos = ImGui::GetItemRectMin();\n\t\t\tm_size = ImGui::GetItemRectSize();\n\n\t\t\tif (m_is_mouse_captured && m_is_ingame_cursor) {\n\t\t\t\tOS::clipCursor(ImGui::GetWindowViewport()->PlatformHandle, (int)m_pos.x, (int)m_pos.y, (int)m_size.x, (int)m_size.y);\n\t\t\t}\n\n\t\t\tprocessInputEvents();\n\t\t\tcontrolsGUI();\n\t\t}\n\n\t}\n\tif (m_is_mouse_captured && OS::getFocused() != ImGui::GetWindowViewport()->PlatformHandle) captureMouse(false);\n\tImGui::End();\n\tif (is_game_view_visible) onStatsGUI(view_pos);\n}\n\n\n} \/\/ namespace Lumix\n<|endoftext|>"} {"text":"<commit_before>#ifndef RENHOOK_HOOKS_INLINE_HOOK_H\n#define RENHOOK_HOOKS_INLINE_HOOK_H\n\n#include <string>\n#include <Windows.h>\n\n#include <renhook\/exception.hpp>\n#include <renhook\/executable.hpp>\n#include <renhook\/hook_writer.hpp>\n#include <renhook\/pattern.hpp>\n#include <renhook\/suspend_threads.hpp>\n#include <renhook\/zydis.hpp>\n\n#include <renhook\/memory\/memory_allocator.hpp>\n#include <renhook\/memory\/virtual_protect.hpp>\n\nnamespace renhook\n{\n \/**\n * @brief An inline hook.\n *\n * @tparam T The hooked function type.\n *\/\n template<typename T>\n class inline_hook\n {\n public:\n\n \/**\n * @brief Construct an empty hook.\n *\/\n inline_hook()\n : m_target_address(0)\n , m_detour_address(0)\n , m_wildcard(0)\n , m_offset(0)\n , m_attached(false)\n , m_decoded_length(0)\n , m_block(nullptr)\n {\n }\n\n \/**\n * @brief Construct a new hook.\n *\n * @param target_address[in] The address of the function that will be hooked.\n * @param detour_address[in] The address of the callback.\n *\/\n inline_hook(uintptr_t target_address, uintptr_t detour_address)\n : inline_hook()\n {\n m_target_address = target_address;\n m_detour_address = detour_address;\n }\n\n \/**\n * @brief Construct a new hook.\n *\n * @param target_address[in] The address of the function that will be hooked.\n * @param detour_address[in] The address of the callback.\n *\/\n inline_hook(uintptr_t target_address, T detour_address)\n : inline_hook(target_address, reinterpret_cast<uintptr_t>(detour_address))\n {\n }\n\n \/**\n * @brief Construct a new hook using a pattern.\n *\n * @param pattern[in] The pattern of the function that will be hooked.\n * @param detour_address[in] The address of the callback.\n * @param wildcard[in] The wildcard for #pattern.\n * @param offset[in] The offset of the #pattern.\n *\/\n inline_hook(pattern pattern, uintptr_t detour_address, uint8_t wildcard = 0xCC, size_t offset = 0)\n : inline_hook()\n {\n m_detour_address = detour_address;\n m_pattern = std::move(pattern);\n m_wildcard = wildcard;\n m_offset = offset;\n }\n\n \/**\n * @brief Construct a new hook using a pattern.\n *\n * @param pattern[in] The pattern of the function that will be hooked.\n * @param detour_address[in] The address of the callback.\n * @param wildcard[in] The wildcard for #pattern.\n * @param offset[in] The offset of the #pattern.\n *\/\n inline_hook(pattern pattern, T detour_address, uint8_t wildcard = 0xCC, size_t offset = 0)\n : inline_hook(pattern, reinterpret_cast<uintptr_t>(detour_address), wildcard, offset)\n {\n }\n\n \/**\n * @brief Construct a new hook.\n *\n * @param module[in] The module which contain the #function.\n * @param function[in] The function that will be hooked.\n * @param detour_address[in] The address of the callback.\n *\n * @note If the module is not loaded, the library will load it when the hook is attached.\n *\/\n inline_hook(const std::string& module, const std::string& function, uintptr_t detour_address)\n : inline_hook()\n {\n m_module = module;\n m_function = function;\n }\n\n \/**\n * @brief Construct a new hook.\n *\n * @param module[in] The module which contain the #function.\n * @param function[in] The function that will be hooked.\n * @param detour_address[in] The address of the callback.\n *\n * @note If the module is not loaded, the library will load it when the hook is attached.\n *\/\n inline_hook(const std::string& module, const std::string& function, T detour_address)\n : inline_hook(module, function, reinterpret_cast<uintptr_t>(detour_address))\n {\n }\n\n inline_hook(inline_hook&& rhs) noexcept\n : m_target_address(rhs.m_target_address)\n , m_detour_address(rhs.m_detour_address)\n , m_pattern(std::move(rhs.m_pattern))\n , m_wildcard(rhs.m_wildcard)\n , m_offset(rhs.m_offset)\n , m_attached(rhs.m_attached)\n , m_decoded_length(rhs.m_decoded_length)\n , m_block(rhs.m_block)\n {\n rhs.m_attached = false;\n rhs.m_block = nullptr;\n }\n\n ~inline_hook()\n {\n detach();\n }\n\n inline_hook& operator=(inline_hook&& rhs) noexcept\n {\n m_target_address = rhs.m_target_address;\n m_detour_address = rhs.m_detour_address;\n m_pattern = std::move(rhs.m_pattern);\n m_wildcard = rhs.m_wildcard;\n m_offset = rhs.m_offset;\n m_attached = rhs.m_attached;\n m_decoded_length = rhs.m_decoded_length;\n m_block = rhs.m_block;\n\n rhs.m_attached = false;\n rhs.m_block = nullptr;\n\n return *this;\n }\n\n inline_hook(inline_hook&) = delete;\n inline_hook& operator=(const inline_hook&) = delete;\n\n \/**\n * @brief Call the original function.\n *\n * @return The value returned by the original function.\n *\/\n operator T() const\n {\n return reinterpret_cast<T>(m_block);\n }\n\n \/**\n * @brief Enable the hook.\n *\/\n void attach()\n {\n using namespace renhook::memory;\n\n if (m_attached)\n {\n return;\n }\n\n if (!m_module.empty())\n {\n auto module_handle = GetModuleHandleA(m_module.c_str());\n if (!module_handle)\n {\n LoadLibraryA(m_module.c_str());\n\n module_handle = GetModuleHandleA(m_module.c_str());\n if (!module_handle)\n {\n throw renhook::exception(\"module not found\");\n }\n }\n\n m_target_address = reinterpret_cast<uintptr_t>(GetProcAddress(module_handle, m_function.c_str()));\n if (m_target_address == 0)\n {\n throw renhook::exception(\"cannot find function in module\");\n }\n }\n\n if (m_target_address == 0)\n {\n if (m_pattern.empty())\n {\n throw renhook::exception(\"cannot attach an empty hook\");\n }\n\n auto addresses = m_pattern.find(m_wildcard);\n m_target_address = addresses.at(m_offset);\n }\n\n m_target_address = skip_jumps(m_target_address);\n m_detour_address = skip_jumps(m_detour_address);\n\n renhook::zydis zydis;\n auto instructions = zydis.decode(m_target_address, executable::get_code_size(), hook_size, m_decoded_length);\n\n suspend_threads threads(m_target_address, m_decoded_length);\n\n extern memory_allocator global_allocator;\n m_block = static_cast<uint8_t*>(global_allocator.alloc());\n\n \/\/ Write the bytes to our memory.\n virtual_protect block_protection(m_block, memory_allocator::block_size, protection::write);\n hook_writer block_writer(m_block);\n\n block_writer.copy_from(m_target_address, m_decoded_length);\n block_writer.write_jump(m_target_address + m_decoded_length);\n\n relocate_instructions(instructions, &block_writer);\n\n \/\/ Write the jump in the original function.\n virtual_protect func_protection(m_target_address, m_decoded_length, protection::write);\n hook_writer func_writer(m_target_address);\n\n func_writer.write_jump(m_detour_address);\n func_writer.write_nops(m_decoded_length - hook_size);\n\n flush_cache();\n m_attached = true;\n }\n\n \/**\n * @brief Disable the hook.\n *\/\n void detach()\n {\n using namespace renhook::memory;\n\n if (!m_attached)\n {\n return;\n }\n\n suspend_threads threads(m_target_address, m_decoded_length);\n virtual_protect func_protection(m_target_address, m_decoded_length, protection::write);\n\n hook_writer func_writer(m_target_address);\n func_writer.copy_from(m_block, m_decoded_length);\n\n renhook::zydis zydis;\n auto instructions = zydis.decode(reinterpret_cast<uintptr_t>(m_block), executable::get_code_size(), m_decoded_length, m_decoded_length);\n\n relocate_instructions(instructions, nullptr);\n\n extern memory_allocator global_allocator;\n global_allocator.free(m_block);\n\n m_block = nullptr;\n\n flush_cache();\n m_attached = false;\n }\n\n protected:\n\n \/**\n * @brief Get the block address.\n *\n * @return The block address.\n *\n * @note This is only used in tests.\n *\/\n const uint8_t* get_block_address() const\n {\n return m_block;\n }\n\n private:\n\n \/**\n * @brief The size of the hook.\n *\/\n#ifdef _WIN64\n static constexpr size_t hook_size = 14;\n#else\n static constexpr size_t hook_size = 5;\n#endif\n\n \/**\n * @brief Check if the first instruction is a jump, if it is follow it until the real address of the function is found.\n *\n * @param address[in] The address to check.\n *\n * @return The real function's address.\n *\/\n uintptr_t skip_jumps(uintptr_t address) const\n {\n if (address == 0)\n {\n return 0;\n }\n\n auto memory = reinterpret_cast<uint8_t*>(address);\n if (memory[0] == 0xEB)\n {\n \/\/ We have a 8-bit offset to the target.\n address = reinterpret_cast<uintptr_t>(memory + 2 + *reinterpret_cast<int8_t*>(&memory[1]));\n return skip_jumps(address);\n }\n else if (memory[0] == 0xE9)\n {\n \/\/ We have a 32-bit offset to the target.\n address = reinterpret_cast<uintptr_t>(memory + 5 + *reinterpret_cast<int32_t*>(&memory[1]));\n return skip_jumps(address);\n }\n else if (memory[0] == 0xFF && memory[1] == 0x25)\n {\n#ifdef _WIN64\n \/\/ We have a 32bit offset to the target.\n address = reinterpret_cast<uintptr_t>(memory + 6 + *reinterpret_cast<int32_t*>(&memory[2]));\n#else\n \/\/ We have an absolute pointer.\n address = *reinterpret_cast<uintptr_t*>(&memory[2]);\n#endif\n\n return skip_jumps(address);\n }\n#ifdef _WIN64\n else if (memory[0] == 0x48 && memory[1] == 0xFF && memory[2] == 0x25)\n {\n \/\/ We have a 32bit offset to the target.\n address = reinterpret_cast<uintptr_t>(memory + 7 + *reinterpret_cast<int32_t*>(&memory[3]));\n return skip_jumps(address);\n }\n#endif\n\n return address;\n }\n\n \/**\n * @brief Relocate all EIP \/ RIP instructions.\n *\n * @param instructions[in] An array of decoded instructions.\n * @param block_writer[in] The writer of the block (only necessary if the hook is attached).\n *\/\n void relocate_instructions(std::vector<zydis::instruction>& instructions, hook_writer* block_writer)\n {\n auto instr_address = m_attached ? m_target_address : reinterpret_cast<uintptr_t>(m_block);\n size_t index = 0;\n\n for (auto& instr : instructions)\n {\n \/\/ Check if it is a conditional jump.\n if (instr.is_relative &&\n ((instr.decoded.opcode & 0xF0) == 0x70 ||\n (instr.decoded.opcode_map == ZYDIS_OPCODE_MAP_0F && (instr.decoded.opcode & 0xF0) == 0x80) ||\n instr.decoded.mnemonic == ZYDIS_MNEMONIC_CALL))\n {\n \/\/ Calculate where the displacement is in instruction.\n auto disp_address = instr_address + instr.disp.offset;\n\n#ifdef _WIN64\n constexpr size_t jmp_size = 14;\n constexpr size_t jmp_instr_size = 6;\n#else\n constexpr size_t jmp_size = 5;\n constexpr size_t jmp_instr_size = 1;\n#endif\n\n auto table_address = m_block + m_decoded_length + hook_size;\n\n \/\/ The address of the jump instruction in jump table for the current instruction.\n auto jmp_instr_address = table_address + (jmp_size * index);\n\n \/\/ Create a jump table if it is not attached, else get the real address from jump table.\n if (!m_attached)\n {\n block_writer->write_jump(instr.disp.absolute_address);\n instr.disp.absolute_address = reinterpret_cast<uintptr_t>(jmp_instr_address);\n }\n else\n {\n instr.disp.absolute_address = *reinterpret_cast<uintptr_t*>(jmp_instr_address + jmp_instr_size);\n\n#ifndef _WIN64\n \/\/ On x86 we have a displacement instead of absolute address.\n instr.disp.absolute_address += reinterpret_cast<uintptr_t>(jmp_instr_address) + jmp_size;\n#endif\n }\n\n switch (instr.disp.size)\n {\n case 8:\n {\n *reinterpret_cast<int8_t*>(disp_address) = static_cast<int8_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));\n break;\n }\n case 16:\n {\n *reinterpret_cast<int16_t*>(disp_address) = static_cast<int16_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));\n break;\n }\n case 32:\n {\n *reinterpret_cast<int32_t*>(disp_address) = static_cast<int32_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));\n break;\n }\n }\n\n index++;\n }\n\n instr_address += instr.decoded.length;\n }\n }\n\n \/**\n * @brief Flush instruction cache for the original function and for the codecave.\n *\/\n void flush_cache() const\n {\n auto current_process = GetCurrentProcess();\n\n FlushInstructionCache(current_process, m_block, memory::memory_allocator::block_size);\n FlushInstructionCache(current_process, reinterpret_cast<void*>(m_target_address), m_decoded_length);\n }\n\n uintptr_t m_target_address;\n uintptr_t m_detour_address;\n\n pattern m_pattern;\n uint8_t m_wildcard;\n size_t m_offset;\n\n std::string m_module;\n std::string m_function;\n\n bool m_attached;\n\n size_t m_decoded_length;\n uint8_t* m_block;\n };\n}\n#endif\n<commit_msg>Change function and block protection to RWX when writing the hook<commit_after>#ifndef RENHOOK_HOOKS_INLINE_HOOK_H\n#define RENHOOK_HOOKS_INLINE_HOOK_H\n\n#include <string>\n#include <Windows.h>\n\n#include <renhook\/exception.hpp>\n#include <renhook\/executable.hpp>\n#include <renhook\/hook_writer.hpp>\n#include <renhook\/pattern.hpp>\n#include <renhook\/suspend_threads.hpp>\n#include <renhook\/zydis.hpp>\n\n#include <renhook\/memory\/memory_allocator.hpp>\n#include <renhook\/memory\/virtual_protect.hpp>\n\nnamespace renhook\n{\n \/**\n * @brief An inline hook.\n *\n * @tparam T The hooked function type.\n *\/\n template<typename T>\n class inline_hook\n {\n public:\n\n \/**\n * @brief Construct an empty hook.\n *\/\n inline_hook()\n : m_target_address(0)\n , m_detour_address(0)\n , m_wildcard(0)\n , m_offset(0)\n , m_attached(false)\n , m_decoded_length(0)\n , m_block(nullptr)\n {\n }\n\n \/**\n * @brief Construct a new hook.\n *\n * @param target_address[in] The address of the function that will be hooked.\n * @param detour_address[in] The address of the callback.\n *\/\n inline_hook(uintptr_t target_address, uintptr_t detour_address)\n : inline_hook()\n {\n m_target_address = target_address;\n m_detour_address = detour_address;\n }\n\n \/**\n * @brief Construct a new hook.\n *\n * @param target_address[in] The address of the function that will be hooked.\n * @param detour_address[in] The address of the callback.\n *\/\n inline_hook(uintptr_t target_address, T detour_address)\n : inline_hook(target_address, reinterpret_cast<uintptr_t>(detour_address))\n {\n }\n\n \/**\n * @brief Construct a new hook using a pattern.\n *\n * @param pattern[in] The pattern of the function that will be hooked.\n * @param detour_address[in] The address of the callback.\n * @param wildcard[in] The wildcard for #pattern.\n * @param offset[in] The offset of the #pattern.\n *\/\n inline_hook(pattern pattern, uintptr_t detour_address, uint8_t wildcard = 0xCC, size_t offset = 0)\n : inline_hook()\n {\n m_detour_address = detour_address;\n m_pattern = std::move(pattern);\n m_wildcard = wildcard;\n m_offset = offset;\n }\n\n \/**\n * @brief Construct a new hook using a pattern.\n *\n * @param pattern[in] The pattern of the function that will be hooked.\n * @param detour_address[in] The address of the callback.\n * @param wildcard[in] The wildcard for #pattern.\n * @param offset[in] The offset of the #pattern.\n *\/\n inline_hook(pattern pattern, T detour_address, uint8_t wildcard = 0xCC, size_t offset = 0)\n : inline_hook(pattern, reinterpret_cast<uintptr_t>(detour_address), wildcard, offset)\n {\n }\n\n \/**\n * @brief Construct a new hook.\n *\n * @param module[in] The module which contain the #function.\n * @param function[in] The function that will be hooked.\n * @param detour_address[in] The address of the callback.\n *\n * @note If the module is not loaded, the library will load it when the hook is attached.\n *\/\n inline_hook(const std::string& module, const std::string& function, uintptr_t detour_address)\n : inline_hook()\n {\n m_module = module;\n m_function = function;\n }\n\n \/**\n * @brief Construct a new hook.\n *\n * @param module[in] The module which contain the #function.\n * @param function[in] The function that will be hooked.\n * @param detour_address[in] The address of the callback.\n *\n * @note If the module is not loaded, the library will load it when the hook is attached.\n *\/\n inline_hook(const std::string& module, const std::string& function, T detour_address)\n : inline_hook(module, function, reinterpret_cast<uintptr_t>(detour_address))\n {\n }\n\n inline_hook(inline_hook&& rhs) noexcept\n : m_target_address(rhs.m_target_address)\n , m_detour_address(rhs.m_detour_address)\n , m_pattern(std::move(rhs.m_pattern))\n , m_wildcard(rhs.m_wildcard)\n , m_offset(rhs.m_offset)\n , m_attached(rhs.m_attached)\n , m_decoded_length(rhs.m_decoded_length)\n , m_block(rhs.m_block)\n {\n rhs.m_attached = false;\n rhs.m_block = nullptr;\n }\n\n ~inline_hook()\n {\n detach();\n }\n\n inline_hook& operator=(inline_hook&& rhs) noexcept\n {\n m_target_address = rhs.m_target_address;\n m_detour_address = rhs.m_detour_address;\n m_pattern = std::move(rhs.m_pattern);\n m_wildcard = rhs.m_wildcard;\n m_offset = rhs.m_offset;\n m_attached = rhs.m_attached;\n m_decoded_length = rhs.m_decoded_length;\n m_block = rhs.m_block;\n\n rhs.m_attached = false;\n rhs.m_block = nullptr;\n\n return *this;\n }\n\n inline_hook(inline_hook&) = delete;\n inline_hook& operator=(const inline_hook&) = delete;\n\n \/**\n * @brief Call the original function.\n *\n * @return The value returned by the original function.\n *\/\n operator T() const\n {\n return reinterpret_cast<T>(m_block);\n }\n\n \/**\n * @brief Enable the hook.\n *\/\n void attach()\n {\n using namespace renhook::memory;\n\n if (m_attached)\n {\n return;\n }\n\n if (!m_module.empty())\n {\n auto module_handle = GetModuleHandleA(m_module.c_str());\n if (!module_handle)\n {\n LoadLibraryA(m_module.c_str());\n\n module_handle = GetModuleHandleA(m_module.c_str());\n if (!module_handle)\n {\n throw renhook::exception(\"module not found\");\n }\n }\n\n m_target_address = reinterpret_cast<uintptr_t>(GetProcAddress(module_handle, m_function.c_str()));\n if (m_target_address == 0)\n {\n throw renhook::exception(\"cannot find function in module\");\n }\n }\n\n if (m_target_address == 0)\n {\n if (m_pattern.empty())\n {\n throw renhook::exception(\"cannot attach an empty hook\");\n }\n\n auto addresses = m_pattern.find(m_wildcard);\n m_target_address = addresses.at(m_offset);\n }\n\n m_target_address = skip_jumps(m_target_address);\n m_detour_address = skip_jumps(m_detour_address);\n\n renhook::zydis zydis;\n auto instructions = zydis.decode(m_target_address, executable::get_code_size(), hook_size, m_decoded_length);\n\n suspend_threads threads(m_target_address, m_decoded_length);\n\n extern memory_allocator global_allocator;\n m_block = static_cast<uint8_t*>(global_allocator.alloc());\n\n \/\/ Write the bytes to our memory.\n virtual_protect block_protection(m_block, memory_allocator::block_size, protection::read | protection::write | protection::execute);\n hook_writer block_writer(m_block);\n\n block_writer.copy_from(m_target_address, m_decoded_length);\n block_writer.write_jump(m_target_address + m_decoded_length);\n\n relocate_instructions(instructions, &block_writer);\n\n \/\/ Write the jump in the original function.\n virtual_protect func_protection(m_target_address, m_decoded_length, protection::read | protection::write | protection::execute);\n hook_writer func_writer(m_target_address);\n\n func_writer.write_jump(m_detour_address);\n func_writer.write_nops(m_decoded_length - hook_size);\n\n flush_cache();\n m_attached = true;\n }\n\n \/**\n * @brief Disable the hook.\n *\/\n void detach()\n {\n using namespace renhook::memory;\n\n if (!m_attached)\n {\n return;\n }\n\n suspend_threads threads(m_target_address, m_decoded_length);\n virtual_protect func_protection(m_target_address, m_decoded_length, protection::read | protection::write | protection::execute);\n\n hook_writer func_writer(m_target_address);\n func_writer.copy_from(m_block, m_decoded_length);\n\n renhook::zydis zydis;\n auto instructions = zydis.decode(reinterpret_cast<uintptr_t>(m_block), executable::get_code_size(), m_decoded_length, m_decoded_length);\n\n relocate_instructions(instructions, nullptr);\n\n extern memory_allocator global_allocator;\n global_allocator.free(m_block);\n\n m_block = nullptr;\n\n flush_cache();\n m_attached = false;\n }\n\n protected:\n\n \/**\n * @brief Get the block address.\n *\n * @return The block address.\n *\n * @note This is only used in tests.\n *\/\n const uint8_t* get_block_address() const\n {\n return m_block;\n }\n\n private:\n\n \/**\n * @brief The size of the hook.\n *\/\n#ifdef _WIN64\n static constexpr size_t hook_size = 14;\n#else\n static constexpr size_t hook_size = 5;\n#endif\n\n \/**\n * @brief Check if the first instruction is a jump, if it is follow it until the real address of the function is found.\n *\n * @param address[in] The address to check.\n *\n * @return The real function's address.\n *\/\n uintptr_t skip_jumps(uintptr_t address) const\n {\n if (address == 0)\n {\n return 0;\n }\n\n auto memory = reinterpret_cast<uint8_t*>(address);\n if (memory[0] == 0xEB)\n {\n \/\/ We have a 8-bit offset to the target.\n address = reinterpret_cast<uintptr_t>(memory + 2 + *reinterpret_cast<int8_t*>(&memory[1]));\n return skip_jumps(address);\n }\n else if (memory[0] == 0xE9)\n {\n \/\/ We have a 32-bit offset to the target.\n address = reinterpret_cast<uintptr_t>(memory + 5 + *reinterpret_cast<int32_t*>(&memory[1]));\n return skip_jumps(address);\n }\n else if (memory[0] == 0xFF && memory[1] == 0x25)\n {\n#ifdef _WIN64\n \/\/ We have a 32bit offset to the target.\n address = reinterpret_cast<uintptr_t>(memory + 6 + *reinterpret_cast<int32_t*>(&memory[2]));\n#else\n \/\/ We have an absolute pointer.\n address = *reinterpret_cast<uintptr_t*>(&memory[2]);\n#endif\n\n return skip_jumps(address);\n }\n#ifdef _WIN64\n else if (memory[0] == 0x48 && memory[1] == 0xFF && memory[2] == 0x25)\n {\n \/\/ We have a 32bit offset to the target.\n address = reinterpret_cast<uintptr_t>(memory + 7 + *reinterpret_cast<int32_t*>(&memory[3]));\n return skip_jumps(address);\n }\n#endif\n\n return address;\n }\n\n \/**\n * @brief Relocate all EIP \/ RIP instructions.\n *\n * @param instructions[in] An array of decoded instructions.\n * @param block_writer[in] The writer of the block (only necessary if the hook is attached).\n *\/\n void relocate_instructions(std::vector<zydis::instruction>& instructions, hook_writer* block_writer)\n {\n auto instr_address = m_attached ? m_target_address : reinterpret_cast<uintptr_t>(m_block);\n size_t index = 0;\n\n for (auto& instr : instructions)\n {\n \/\/ Check if it is a conditional jump.\n if (instr.is_relative &&\n ((instr.decoded.opcode & 0xF0) == 0x70 ||\n (instr.decoded.opcode_map == ZYDIS_OPCODE_MAP_0F && (instr.decoded.opcode & 0xF0) == 0x80) ||\n instr.decoded.mnemonic == ZYDIS_MNEMONIC_CALL))\n {\n \/\/ Calculate where the displacement is in instruction.\n auto disp_address = instr_address + instr.disp.offset;\n\n#ifdef _WIN64\n constexpr size_t jmp_size = 14;\n constexpr size_t jmp_instr_size = 6;\n#else\n constexpr size_t jmp_size = 5;\n constexpr size_t jmp_instr_size = 1;\n#endif\n\n auto table_address = m_block + m_decoded_length + hook_size;\n\n \/\/ The address of the jump instruction in jump table for the current instruction.\n auto jmp_instr_address = table_address + (jmp_size * index);\n\n \/\/ Create a jump table if it is not attached, else get the real address from jump table.\n if (!m_attached)\n {\n block_writer->write_jump(instr.disp.absolute_address);\n instr.disp.absolute_address = reinterpret_cast<uintptr_t>(jmp_instr_address);\n }\n else\n {\n instr.disp.absolute_address = *reinterpret_cast<uintptr_t*>(jmp_instr_address + jmp_instr_size);\n\n#ifndef _WIN64\n \/\/ On x86 we have a displacement instead of absolute address.\n instr.disp.absolute_address += reinterpret_cast<uintptr_t>(jmp_instr_address) + jmp_size;\n#endif\n }\n\n switch (instr.disp.size)\n {\n case 8:\n {\n *reinterpret_cast<int8_t*>(disp_address) = static_cast<int8_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));\n break;\n }\n case 16:\n {\n *reinterpret_cast<int16_t*>(disp_address) = static_cast<int16_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));\n break;\n }\n case 32:\n {\n *reinterpret_cast<int32_t*>(disp_address) = static_cast<int32_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));\n break;\n }\n }\n\n index++;\n }\n\n instr_address += instr.decoded.length;\n }\n }\n\n \/**\n * @brief Flush instruction cache for the original function and for the codecave.\n *\/\n void flush_cache() const\n {\n auto current_process = GetCurrentProcess();\n\n FlushInstructionCache(current_process, m_block, memory::memory_allocator::block_size);\n FlushInstructionCache(current_process, reinterpret_cast<void*>(m_target_address), m_decoded_length);\n }\n\n uintptr_t m_target_address;\n uintptr_t m_detour_address;\n\n pattern m_pattern;\n uint8_t m_wildcard;\n size_t m_offset;\n\n std::string m_module;\n std::string m_function;\n\n bool m_attached;\n\n size_t m_decoded_length;\n uint8_t* m_block;\n };\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ -----------------------------------------------------------------------\n\/\/ pion-common: a collection of common libraries used by the Pion Platform\n\/\/ -----------------------------------------------------------------------\n\/\/ Copyright (C) 2007 Atomic Labs, Inc. (http:\/\/www.atomiclabs.com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ See accompanying file COPYING or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt\n\/\/\n\n#include <boost\/filesystem\/operations.hpp>\n#include <pion\/PionConfig.hpp>\n#include <pion\/PionPlugin.hpp>\n\n#ifdef PION_WIN32\n\t#include <windows.h>\n#else\n\t#include <dlfcn.h>\n#endif\n\n#include <iostream>\n\nnamespace pion {\t\/\/ begin namespace pion\n\t\n\/\/ static members of PionPlugin\n\t\nconst std::string\t\t\tPionPlugin::PION_PLUGIN_CREATE(\"pion_create_\");\nconst std::string\t\t\tPionPlugin::PION_PLUGIN_DESTROY(\"pion_destroy_\");\n#ifdef PION_WIN32\n\tconst std::string\t\t\tPionPlugin::PION_PLUGIN_EXTENSION(\".dll\");\n#else\n\tconst std::string\t\t\tPionPlugin::PION_PLUGIN_EXTENSION(\".so\");\n#endif\nconst std::string\t\t\tPionPlugin::PION_CONFIG_EXTENSION(\".conf\");\nstd::vector<std::string>\tPionPlugin::m_plugin_dirs;\nPionPlugin::PluginMap\t\tPionPlugin::m_plugin_map;\nboost::mutex\t\t\t\tPionPlugin::m_plugin_mutex;\nPionPlugin::StaticEntryPointList\t*PionPlugin::m_entry_points_ptr = NULL;\n\n\t\n\/\/ PionPlugin member functions\n\t\nvoid PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,\n\t\t\t\t\t\t\t\t const std::string& start_path)\n{\n#if defined(PION_WIN32) && defined(PION_CYGWIN_DIRECTORY)\n\t\/\/ try prepending PION_CYGWIN_DIRECTORY if not complete\n\tif (! final_path.is_complete() && final_path.has_root_directory()) {\n\t\tfinal_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path);\n\t}\n#endif\n}\n\nvoid PionPlugin::addPluginDirectory(const std::string& dir)\n{\n\tboost::filesystem::path plugin_path = boost::filesystem::system_complete(dir);\n\tcheckCygwinPath(plugin_path, dir);\n\tif (! boost::filesystem::exists(plugin_path) )\n\t\tthrow DirectoryNotFoundException(dir);\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tm_plugin_dirs.push_back(plugin_path.directory_string());\n}\n\nvoid PionPlugin::resetPluginDirectories(void)\n{\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tm_plugin_dirs.clear();\n}\n\nvoid PionPlugin::open(const std::string& plugin_name)\n{\n\tstd::string plugin_file;\n\n\tif (!findPluginFile(plugin_file, plugin_name))\n\t\tthrow PluginNotFoundException(plugin_name);\n\t\t\n\topenFile(plugin_file);\n}\n\nvoid PionPlugin::openFile(const std::string& plugin_file)\n{\n\treleaseData();\t\/\/ make sure we're not already pointing to something\n\t\n\t\/\/ use a temporary object first since openPlugin() may throw\n\tPionPluginData plugin_data(getPluginName(plugin_file));\n\t\n\t\/\/ check to see if we already have a matching shared library\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tPluginMap::iterator itr = m_plugin_map.find(plugin_data.m_plugin_name);\n\tif (itr == m_plugin_map.end()) {\n\t\t\/\/ no plug-ins found with the same name\n\t\t\n\t\t\/\/ open up the shared library using our temporary data object\n\t\topenPlugin(plugin_file, plugin_data);\t\/\/ may throw\n\t\t\n\t\t\/\/ all is good -> insert it into the plug-in map\n\t\tm_plugin_data = new PionPluginData(plugin_data);\n\t\tm_plugin_map.insert( std::make_pair(m_plugin_data->m_plugin_name,\n\t\t\t\t\t\t\t\t\t\t\tm_plugin_data) );\n\t} else {\n\t\t\/\/ found an existing plug-in with the same name\n\t\tm_plugin_data = itr->second;\n\t}\n\t\n\t\/\/ increment the number of references\n\t++ m_plugin_data->m_references;\n}\n\nvoid PionPlugin::openStaticLinked(const std::string& plugin_name,\n\t\t\t\t\t\t\t\t void *create_func,\n\t\t\t\t\t\t\t\t void *destroy_func)\n{\n\treleaseData();\t\/\/ make sure we're not already pointing to something\n\n\t\/\/ check to see if we already have a matching shared library\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tPluginMap::iterator itr = m_plugin_map.find(plugin_name);\n\tif (itr == m_plugin_map.end()) {\n\t\t\/\/ no plug-ins found with the same name\n\n\t\t\/\/ all is good -> insert it into the plug-in map\n\t\tm_plugin_data = new PionPluginData(plugin_name);\n\t\tm_plugin_data->m_lib_handle = NULL; \/\/ this will indicate that we are using statically linked plug-in\n\t\tm_plugin_data->m_create_func = create_func;\n\t\tm_plugin_data->m_destroy_func = destroy_func;\n\t\tm_plugin_map.insert(std::make_pair(m_plugin_data->m_plugin_name,\n\t\t\t\t\t\t\t\t\t\t m_plugin_data));\n\t} else {\n\t\t\/\/ found an existing plug-in with the same name\n\t\tm_plugin_data = itr->second;\n\t}\n\n\t\/\/ increment the number of references\n\t++ m_plugin_data->m_references;\n}\n\nvoid PionPlugin::releaseData(void)\n{\n\tif (m_plugin_data != NULL) {\n\t\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\t\t\/\/ double-check after locking mutex\n\t\tif (m_plugin_data != NULL && --m_plugin_data->m_references == 0) {\n\t\t\t\/\/ no more references to the plug-in library\n\t\t\t\n\t\t\t\/\/ release the shared object\n\t\t\tcloseDynamicLibrary(m_plugin_data->m_lib_handle);\n\t\t\t\n\t\t\t\/\/ remove it from the plug-in map\n\t\t\tPluginMap::iterator itr = m_plugin_map.find(m_plugin_data->m_plugin_name);\n\t\t\t\/\/ check itr just to be safe (it SHOULD always find a match)\n\t\t\tif (itr != m_plugin_map.end())\n\t\t\t\tm_plugin_map.erase(itr);\n\t\t\t\n\t\t\t\/\/ release the heap object\n\t\t\tdelete m_plugin_data;\n\t\t}\n\t\tm_plugin_data = NULL;\n\t}\n}\n\nvoid PionPlugin::grabData(const PionPlugin& p)\n{\n\treleaseData();\t\/\/ make sure we're not already pointing to something\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tm_plugin_data = const_cast<PionPluginData*>(p.m_plugin_data);\n\tif (m_plugin_data != NULL) {\n\t\t++ m_plugin_data->m_references;\n\t}\n}\n\nbool PionPlugin::findFile(std::string& path_to_file, const std::string& name,\n\t\t\t\t\t\t const std::string& extension)\n{\n\t\/\/ first, try the name as-is\n\tif (checkForFile(path_to_file, name, \"\", extension))\n\t\treturn true;\n\n\t\/\/ nope, check search paths\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tfor (std::vector<std::string>::iterator i = m_plugin_dirs.begin();\n\t\t i != m_plugin_dirs.end(); ++i)\n\t{\n\t\tif (checkForFile(path_to_file, *i, name, extension))\n\t\t\treturn true;\n\t}\n\t\n\t\/\/ no plug-in file found\n\treturn false;\n}\n\nbool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,\n\t\t\t\t\t\t\t const std::string& name, const std::string& extension)\n{\n\t\/\/ check for cygwin path oddities\n\tboost::filesystem::path cygwin_safe_path(start_path);\n\tcheckCygwinPath(cygwin_safe_path, start_path);\n\tboost::filesystem::path test_path(cygwin_safe_path);\n\n\t\/\/ if a name is specified, append it to the test path\n\tif (! name.empty())\n\t\ttest_path \/= name;\n\n\t\/\/ check for existence of plug-in (without extension)\t\t\n\tif (boost::filesystem::exists(test_path)) {\n\t\tfinal_path = test_path.file_string();\n\t\treturn true;\n\t}\n\t\t\n\t\/\/ next, try appending the plug-in extension\t\t\n\tif (name.empty()) {\n\t\t\/\/ no \"name\" specified -> append it directly to start_path\n\t\ttest_path = boost::filesystem::path(start_path + extension);\n\t\t\/\/ in this case, we need to re-check for the cygwin oddities\n\t\tcheckCygwinPath(test_path, start_path + extension);\n\t} else {\n\t\t\/\/ name is specified, so we can just re-use cygwin_safe_path\n\t\ttest_path = cygwin_safe_path \/\n\t\t\tboost::filesystem::path(name + extension);\n\t}\n\n\t\/\/ re-check for existence of plug-in (after adding extension)\t\t\n\tif (boost::filesystem::exists(test_path)) {\n\t\tfinal_path = test_path.file_string();\n\t\treturn true;\n\t}\n\t\n\t\/\/ no plug-in file found\n\treturn false;\n}\n\nvoid PionPlugin::openPlugin(const std::string& plugin_file,\n\t\t\t\t\t\t\tPionPluginData& plugin_data)\n{\n\t\/\/ get the name of the plugin (for create\/destroy symbol names)\n\tplugin_data.m_plugin_name = getPluginName(plugin_file);\n\t\n\t\/\/ attempt to open the plugin; note that this tries all search paths\n\t\/\/ and also tries a variety of platform-specific extensions\n\tplugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());\n\tif (plugin_data.m_lib_handle == NULL)\n\t\tthrow PluginNotFoundException(plugin_file);\n\t\n\t\/\/ find the function used to create new plugin objects\n\tplugin_data.m_create_func =\n\t\tgetLibrarySymbol(plugin_data.m_lib_handle,\n\t\t\t\t\t\t PION_PLUGIN_CREATE + plugin_data.m_plugin_name);\n\tif (plugin_data.m_create_func == NULL) {\n\t\tcloseDynamicLibrary(plugin_data.m_lib_handle);\n\t\tthrow PluginMissingCreateException(plugin_file);\n\t}\n\n\t\/\/ find the function used to destroy existing plugin objects\n\tplugin_data.m_destroy_func =\n\t\tgetLibrarySymbol(plugin_data.m_lib_handle,\n\t\t\t\t\t\t PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);\n\tif (plugin_data.m_destroy_func == NULL) {\n\t\tcloseDynamicLibrary(plugin_data.m_lib_handle);\n\t\tthrow PluginMissingDestroyException(plugin_file);\n\t}\n}\n\nstd::string PionPlugin::getPluginName(const std::string& plugin_file)\n{\n\t\/\/ strip path\n#ifdef PION_WIN32\n\tstd::string::size_type pos = plugin_file.find_last_of('\\\\');\n#else\n\tstd::string::size_type pos = plugin_file.find_last_of('\/');\n#endif\n\tstd::string plugin_name = (pos == std::string::npos ?\n\t\t\t\t\t\t\t plugin_file : plugin_file.substr(pos+1));\n\tpos = plugin_name.find('.');\n\n\t\/\/ truncate extension\n\tif (pos != std::string::npos)\n\t\tplugin_name.resize(pos);\n\t\t\t\t\t\t\t\n\treturn plugin_name;\t\t\t\t\t\t\n}\n\nvoid *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)\n{\n#ifdef PION_WIN32\n\t#ifdef BOOST_MSVC\n\t\treturn LoadLibraryA(plugin_file.c_str());\n\t#else\n\t\treturn LoadLibrary(plugin_file.c_str());\n\t#endif\n#else\n\tstd::cout << \"trying to open \" << plugin_file << std::endl;\n\treturn dlopen(plugin_file.c_str(), RTLD_LAZY);\n#endif\n}\n\nvoid PionPlugin::closeDynamicLibrary(void *lib_handle)\n{\n#ifdef PION_WIN32\n\tFreeLibrary((HINSTANCE) lib_handle);\n#else\n\tdlclose(lib_handle);\n#endif\n}\n\nvoid *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)\n{\n#ifdef PION_WIN32\n\treturn (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());\n#else\n\treturn dlsym(lib_handle, symbol.c_str());\n#endif\n}\n\nbool PionPlugin::findStaticEntryPoint(const std::string& plugin_name,\n\t\t\t\t\t\t\t\t\t void **create_func,\n\t\t\t\t\t\t\t\t\t void **destroy_func)\n{\n\t\/\/ check simple case first: no entry points exist\n\tif (m_entry_points_ptr == NULL || m_entry_points_ptr->empty())\n\t\treturn false;\n\n\t\/\/ try to find the entry point for the plugin\n\tfor (std::list<StaticEntryPoint>::const_iterator i = m_entry_points_ptr->begin();\n\t\t i != m_entry_points_ptr->end(); ++i) {\n\t\t\tif (i->m_plugin_name==plugin_name) {\n\t\t\t\t*create_func = i->m_create_func;\n\t\t\t\t*destroy_func = i->m_destroy_func;\n\t\t\t\treturn true;\n\t\t\t}\n\t}\n\treturn false;\n}\n\nvoid PionPlugin::addStaticEntryPoint(const std::string& plugin_name,\n\t\t\t\t\t\t\t\t\t void *create_func,\n\t\t\t\t\t\t\t\t\t void *destroy_func)\n{\n\t\/\/ make sure that this function can only be called by one thread at a time\n\tstatic boost::mutex\t\t\tentrypoint_mutex;\n\tboost::mutex::scoped_lock\tentrypoint_lock(entrypoint_mutex);\n\n\t\/\/ create the entry point list if it doesn't already exist\n\tif (m_entry_points_ptr == NULL)\n\t\tm_entry_points_ptr = new StaticEntryPointList;\n\t\n\t\/\/ insert it into the entry point list\n\tm_entry_points_ptr->push_back(StaticEntryPoint(plugin_name, create_func, destroy_func));\n}\n\n}\t\/\/ end namespace pion\n<commit_msg>Removed debugging info left in from previous commit<commit_after>\/\/ -----------------------------------------------------------------------\n\/\/ pion-common: a collection of common libraries used by the Pion Platform\n\/\/ -----------------------------------------------------------------------\n\/\/ Copyright (C) 2007 Atomic Labs, Inc. (http:\/\/www.atomiclabs.com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ See accompanying file COPYING or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt\n\/\/\n\n#include <boost\/filesystem\/operations.hpp>\n#include <pion\/PionConfig.hpp>\n#include <pion\/PionPlugin.hpp>\n\n#ifdef PION_WIN32\n\t#include <windows.h>\n#else\n\t#include <dlfcn.h>\n#endif\n\n\nnamespace pion {\t\/\/ begin namespace pion\n\t\n\/\/ static members of PionPlugin\n\t\nconst std::string\t\t\tPionPlugin::PION_PLUGIN_CREATE(\"pion_create_\");\nconst std::string\t\t\tPionPlugin::PION_PLUGIN_DESTROY(\"pion_destroy_\");\n#ifdef PION_WIN32\n\tconst std::string\t\t\tPionPlugin::PION_PLUGIN_EXTENSION(\".dll\");\n#else\n\tconst std::string\t\t\tPionPlugin::PION_PLUGIN_EXTENSION(\".so\");\n#endif\nconst std::string\t\t\tPionPlugin::PION_CONFIG_EXTENSION(\".conf\");\nstd::vector<std::string>\tPionPlugin::m_plugin_dirs;\nPionPlugin::PluginMap\t\tPionPlugin::m_plugin_map;\nboost::mutex\t\t\t\tPionPlugin::m_plugin_mutex;\nPionPlugin::StaticEntryPointList\t*PionPlugin::m_entry_points_ptr = NULL;\n\n\t\n\/\/ PionPlugin member functions\n\t\nvoid PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,\n\t\t\t\t\t\t\t\t const std::string& start_path)\n{\n#if defined(PION_WIN32) && defined(PION_CYGWIN_DIRECTORY)\n\t\/\/ try prepending PION_CYGWIN_DIRECTORY if not complete\n\tif (! final_path.is_complete() && final_path.has_root_directory()) {\n\t\tfinal_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path);\n\t}\n#endif\n}\n\nvoid PionPlugin::addPluginDirectory(const std::string& dir)\n{\n\tboost::filesystem::path plugin_path = boost::filesystem::system_complete(dir);\n\tcheckCygwinPath(plugin_path, dir);\n\tif (! boost::filesystem::exists(plugin_path) )\n\t\tthrow DirectoryNotFoundException(dir);\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tm_plugin_dirs.push_back(plugin_path.directory_string());\n}\n\nvoid PionPlugin::resetPluginDirectories(void)\n{\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tm_plugin_dirs.clear();\n}\n\nvoid PionPlugin::open(const std::string& plugin_name)\n{\n\tstd::string plugin_file;\n\n\tif (!findPluginFile(plugin_file, plugin_name))\n\t\tthrow PluginNotFoundException(plugin_name);\n\t\t\n\topenFile(plugin_file);\n}\n\nvoid PionPlugin::openFile(const std::string& plugin_file)\n{\n\treleaseData();\t\/\/ make sure we're not already pointing to something\n\t\n\t\/\/ use a temporary object first since openPlugin() may throw\n\tPionPluginData plugin_data(getPluginName(plugin_file));\n\t\n\t\/\/ check to see if we already have a matching shared library\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tPluginMap::iterator itr = m_plugin_map.find(plugin_data.m_plugin_name);\n\tif (itr == m_plugin_map.end()) {\n\t\t\/\/ no plug-ins found with the same name\n\t\t\n\t\t\/\/ open up the shared library using our temporary data object\n\t\topenPlugin(plugin_file, plugin_data);\t\/\/ may throw\n\t\t\n\t\t\/\/ all is good -> insert it into the plug-in map\n\t\tm_plugin_data = new PionPluginData(plugin_data);\n\t\tm_plugin_map.insert( std::make_pair(m_plugin_data->m_plugin_name,\n\t\t\t\t\t\t\t\t\t\t\tm_plugin_data) );\n\t} else {\n\t\t\/\/ found an existing plug-in with the same name\n\t\tm_plugin_data = itr->second;\n\t}\n\t\n\t\/\/ increment the number of references\n\t++ m_plugin_data->m_references;\n}\n\nvoid PionPlugin::openStaticLinked(const std::string& plugin_name,\n\t\t\t\t\t\t\t\t void *create_func,\n\t\t\t\t\t\t\t\t void *destroy_func)\n{\n\treleaseData();\t\/\/ make sure we're not already pointing to something\n\n\t\/\/ check to see if we already have a matching shared library\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tPluginMap::iterator itr = m_plugin_map.find(plugin_name);\n\tif (itr == m_plugin_map.end()) {\n\t\t\/\/ no plug-ins found with the same name\n\n\t\t\/\/ all is good -> insert it into the plug-in map\n\t\tm_plugin_data = new PionPluginData(plugin_name);\n\t\tm_plugin_data->m_lib_handle = NULL; \/\/ this will indicate that we are using statically linked plug-in\n\t\tm_plugin_data->m_create_func = create_func;\n\t\tm_plugin_data->m_destroy_func = destroy_func;\n\t\tm_plugin_map.insert(std::make_pair(m_plugin_data->m_plugin_name,\n\t\t\t\t\t\t\t\t\t\t m_plugin_data));\n\t} else {\n\t\t\/\/ found an existing plug-in with the same name\n\t\tm_plugin_data = itr->second;\n\t}\n\n\t\/\/ increment the number of references\n\t++ m_plugin_data->m_references;\n}\n\nvoid PionPlugin::releaseData(void)\n{\n\tif (m_plugin_data != NULL) {\n\t\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\t\t\/\/ double-check after locking mutex\n\t\tif (m_plugin_data != NULL && --m_plugin_data->m_references == 0) {\n\t\t\t\/\/ no more references to the plug-in library\n\t\t\t\n\t\t\t\/\/ release the shared object\n\t\t\tcloseDynamicLibrary(m_plugin_data->m_lib_handle);\n\t\t\t\n\t\t\t\/\/ remove it from the plug-in map\n\t\t\tPluginMap::iterator itr = m_plugin_map.find(m_plugin_data->m_plugin_name);\n\t\t\t\/\/ check itr just to be safe (it SHOULD always find a match)\n\t\t\tif (itr != m_plugin_map.end())\n\t\t\t\tm_plugin_map.erase(itr);\n\t\t\t\n\t\t\t\/\/ release the heap object\n\t\t\tdelete m_plugin_data;\n\t\t}\n\t\tm_plugin_data = NULL;\n\t}\n}\n\nvoid PionPlugin::grabData(const PionPlugin& p)\n{\n\treleaseData();\t\/\/ make sure we're not already pointing to something\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tm_plugin_data = const_cast<PionPluginData*>(p.m_plugin_data);\n\tif (m_plugin_data != NULL) {\n\t\t++ m_plugin_data->m_references;\n\t}\n}\n\nbool PionPlugin::findFile(std::string& path_to_file, const std::string& name,\n\t\t\t\t\t\t const std::string& extension)\n{\n\t\/\/ first, try the name as-is\n\tif (checkForFile(path_to_file, name, \"\", extension))\n\t\treturn true;\n\n\t\/\/ nope, check search paths\n\tboost::mutex::scoped_lock plugin_lock(m_plugin_mutex);\n\tfor (std::vector<std::string>::iterator i = m_plugin_dirs.begin();\n\t\t i != m_plugin_dirs.end(); ++i)\n\t{\n\t\tif (checkForFile(path_to_file, *i, name, extension))\n\t\t\treturn true;\n\t}\n\t\n\t\/\/ no plug-in file found\n\treturn false;\n}\n\nbool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,\n\t\t\t\t\t\t\t const std::string& name, const std::string& extension)\n{\n\t\/\/ check for cygwin path oddities\n\tboost::filesystem::path cygwin_safe_path(start_path);\n\tcheckCygwinPath(cygwin_safe_path, start_path);\n\tboost::filesystem::path test_path(cygwin_safe_path);\n\n\t\/\/ if a name is specified, append it to the test path\n\tif (! name.empty())\n\t\ttest_path \/= name;\n\n\t\/\/ check for existence of plug-in (without extension)\t\t\n\tif (boost::filesystem::exists(test_path)) {\n\t\tfinal_path = test_path.file_string();\n\t\treturn true;\n\t}\n\t\t\n\t\/\/ next, try appending the plug-in extension\t\t\n\tif (name.empty()) {\n\t\t\/\/ no \"name\" specified -> append it directly to start_path\n\t\ttest_path = boost::filesystem::path(start_path + extension);\n\t\t\/\/ in this case, we need to re-check for the cygwin oddities\n\t\tcheckCygwinPath(test_path, start_path + extension);\n\t} else {\n\t\t\/\/ name is specified, so we can just re-use cygwin_safe_path\n\t\ttest_path = cygwin_safe_path \/\n\t\t\tboost::filesystem::path(name + extension);\n\t}\n\n\t\/\/ re-check for existence of plug-in (after adding extension)\t\t\n\tif (boost::filesystem::exists(test_path)) {\n\t\tfinal_path = test_path.file_string();\n\t\treturn true;\n\t}\n\t\n\t\/\/ no plug-in file found\n\treturn false;\n}\n\nvoid PionPlugin::openPlugin(const std::string& plugin_file,\n\t\t\t\t\t\t\tPionPluginData& plugin_data)\n{\n\t\/\/ get the name of the plugin (for create\/destroy symbol names)\n\tplugin_data.m_plugin_name = getPluginName(plugin_file);\n\t\n\t\/\/ attempt to open the plugin; note that this tries all search paths\n\t\/\/ and also tries a variety of platform-specific extensions\n\tplugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());\n\tif (plugin_data.m_lib_handle == NULL)\n\t\tthrow PluginNotFoundException(plugin_file);\n\t\n\t\/\/ find the function used to create new plugin objects\n\tplugin_data.m_create_func =\n\t\tgetLibrarySymbol(plugin_data.m_lib_handle,\n\t\t\t\t\t\t PION_PLUGIN_CREATE + plugin_data.m_plugin_name);\n\tif (plugin_data.m_create_func == NULL) {\n\t\tcloseDynamicLibrary(plugin_data.m_lib_handle);\n\t\tthrow PluginMissingCreateException(plugin_file);\n\t}\n\n\t\/\/ find the function used to destroy existing plugin objects\n\tplugin_data.m_destroy_func =\n\t\tgetLibrarySymbol(plugin_data.m_lib_handle,\n\t\t\t\t\t\t PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);\n\tif (plugin_data.m_destroy_func == NULL) {\n\t\tcloseDynamicLibrary(plugin_data.m_lib_handle);\n\t\tthrow PluginMissingDestroyException(plugin_file);\n\t}\n}\n\nstd::string PionPlugin::getPluginName(const std::string& plugin_file)\n{\n\t\/\/ strip path\n#ifdef PION_WIN32\n\tstd::string::size_type pos = plugin_file.find_last_of('\\\\');\n#else\n\tstd::string::size_type pos = plugin_file.find_last_of('\/');\n#endif\n\tstd::string plugin_name = (pos == std::string::npos ?\n\t\t\t\t\t\t\t plugin_file : plugin_file.substr(pos+1));\n\tpos = plugin_name.find('.');\n\n\t\/\/ truncate extension\n\tif (pos != std::string::npos)\n\t\tplugin_name.resize(pos);\n\t\t\t\t\t\t\t\n\treturn plugin_name;\t\t\t\t\t\t\n}\n\nvoid *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)\n{\n#ifdef PION_WIN32\n\t#ifdef BOOST_MSVC\n\t\treturn LoadLibraryA(plugin_file.c_str());\n\t#else\n\t\treturn LoadLibrary(plugin_file.c_str());\n\t#endif\n#else\n\treturn dlopen(plugin_file.c_str(), RTLD_LAZY);\n#endif\n}\n\nvoid PionPlugin::closeDynamicLibrary(void *lib_handle)\n{\n#ifdef PION_WIN32\n\tFreeLibrary((HINSTANCE) lib_handle);\n#else\n\tdlclose(lib_handle);\n#endif\n}\n\nvoid *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)\n{\n#ifdef PION_WIN32\n\treturn (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());\n#else\n\treturn dlsym(lib_handle, symbol.c_str());\n#endif\n}\n\nbool PionPlugin::findStaticEntryPoint(const std::string& plugin_name,\n\t\t\t\t\t\t\t\t\t void **create_func,\n\t\t\t\t\t\t\t\t\t void **destroy_func)\n{\n\t\/\/ check simple case first: no entry points exist\n\tif (m_entry_points_ptr == NULL || m_entry_points_ptr->empty())\n\t\treturn false;\n\n\t\/\/ try to find the entry point for the plugin\n\tfor (std::list<StaticEntryPoint>::const_iterator i = m_entry_points_ptr->begin();\n\t\t i != m_entry_points_ptr->end(); ++i) {\n\t\t\tif (i->m_plugin_name==plugin_name) {\n\t\t\t\t*create_func = i->m_create_func;\n\t\t\t\t*destroy_func = i->m_destroy_func;\n\t\t\t\treturn true;\n\t\t\t}\n\t}\n\treturn false;\n}\n\nvoid PionPlugin::addStaticEntryPoint(const std::string& plugin_name,\n\t\t\t\t\t\t\t\t\t void *create_func,\n\t\t\t\t\t\t\t\t\t void *destroy_func)\n{\n\t\/\/ make sure that this function can only be called by one thread at a time\n\tstatic boost::mutex\t\t\tentrypoint_mutex;\n\tboost::mutex::scoped_lock\tentrypoint_lock(entrypoint_mutex);\n\n\t\/\/ create the entry point list if it doesn't already exist\n\tif (m_entry_points_ptr == NULL)\n\t\tm_entry_points_ptr = new StaticEntryPointList;\n\t\n\t\/\/ insert it into the entry point list\n\tm_entry_points_ptr->push_back(StaticEntryPoint(plugin_name, create_func, destroy_func));\n}\n\n}\t\/\/ end namespace pion\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: wrapexception.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 04:03:06 $\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 CONFIGMGR_WRAPEXCEPTION_HXX\n#define CONFIGMGR_WRAPEXCEPTION_HXX\n\n#include <com\/sun\/star\/configuration\/MissingBootstrapFileException.hpp>\n#include <com\/sun\/star\/configuration\/InvalidBootstrapFileException.hpp>\n#include <com\/sun\/star\/configuration\/InstallationIncompleteException.hpp>\n#include <com\/sun\/star\/configuration\/CannotLoadConfigurationException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/BackendSetupException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/AuthenticationFailedException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/InvalidAuthenticationMechanismException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/CannotConnectException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/InsufficientAccessRightsException.hpp>\n\n#include <com\/sun\/star\/configuration\/backend\/BackendAccessException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/ConnectionLostException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/MalformedDataException.hpp>\n\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#include <com\/sun\/star\/lang\/WrappedTargetException.hpp>\n#include <com\/sun\/star\/lang\/WrappedTargetRuntimeException.hpp>\n#include <com\/sun\/star\/xml\/sax\/SAXException.hpp>\n#include <com\/sun\/star\/xml\/sax\/SAXParseException.hpp>\n\n#define WRAP_EXCEPTION( ETyp, Raise ) \\\n catch (ETyp & _e_) { Raise( uno::makeAny(_e_) ); }\n\n#define WRAP_EXCEPTION1( ETyp, Raise, Arg ) \\\n catch (ETyp & _e_) { Raise( uno::makeAny(_e_), (Arg) ); }\n\n#define PASS_EXCEPTION( ETyp ) \\\n catch (ETyp & ) { throw; }\n\n#define WRAP_CONFIGBACKEND_CREATION_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::AuthenticationFailedException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::InvalidAuthenticationMechanismException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::CannotConnectException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendSetupException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendAccessException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::MissingBootstrapFileException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::InvalidBootstrapFileException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::InstallationIncompleteException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::CannotLoadConfigurationException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetRuntimeException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::lang::DisposedException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::uno::RuntimeException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::uno::Exception, Raise)\n\n#define WRAP_CONFIGBACKEND_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::ConnectionLostException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendAccessException, Raise) \\\n\n#define WRAP_CONFIGDATA_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::MalformedDataException, Raise) \\\n WRAP_CONFIGBACKEND_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetException, Raise) \\\n\n#define WRAP_SAX_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::xml::sax::SAXParseException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::xml::sax::SAXException, Raise) \\\n\n#define WRAP_OTHER_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::uno::Exception, Raise)\n\n#define WRAP_CONFIGBACKEND_CREATION_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::AuthenticationFailedException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InvalidAuthenticationMechanismException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::CannotConnectException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendSetupException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendAccessException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::MissingBootstrapFileException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::InvalidBootstrapFileException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::InstallationIncompleteException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::CannotLoadConfigurationException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetRuntimeException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::lang::DisposedException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::uno::RuntimeException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::uno::Exception, Raise, Arg)\n\n#define WRAP_CONFIGBACKEND_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::ConnectionLostException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendAccessException, Raise, Arg) \\\n\n#define WRAP_CONFIGDATA_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::MalformedDataException, Raise, Arg) \\\n WRAP_CONFIGBACKEND_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetException, Raise, Arg) \\\n\n#define WRAP_SAX_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::xml::sax::SAXParseException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::xml::sax::SAXException, Raise, Arg) \\\n\n#define WRAP_OTHER_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::uno::Exception, Raise, Arg)\n\n#endif \/\/ CONFIGMGR_WRAPEXCEPTION_HXX\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.130); FILE MERGED 2008\/03\/31 12:22:46 rt 1.4.130.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: wrapexception.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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_WRAPEXCEPTION_HXX\n#define CONFIGMGR_WRAPEXCEPTION_HXX\n\n#include <com\/sun\/star\/configuration\/MissingBootstrapFileException.hpp>\n#include <com\/sun\/star\/configuration\/InvalidBootstrapFileException.hpp>\n#include <com\/sun\/star\/configuration\/InstallationIncompleteException.hpp>\n#include <com\/sun\/star\/configuration\/CannotLoadConfigurationException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/BackendSetupException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/AuthenticationFailedException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/InvalidAuthenticationMechanismException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/CannotConnectException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/InsufficientAccessRightsException.hpp>\n\n#include <com\/sun\/star\/configuration\/backend\/BackendAccessException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/ConnectionLostException.hpp>\n#include <com\/sun\/star\/configuration\/backend\/MalformedDataException.hpp>\n\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#include <com\/sun\/star\/lang\/WrappedTargetException.hpp>\n#include <com\/sun\/star\/lang\/WrappedTargetRuntimeException.hpp>\n#include <com\/sun\/star\/xml\/sax\/SAXException.hpp>\n#include <com\/sun\/star\/xml\/sax\/SAXParseException.hpp>\n\n#define WRAP_EXCEPTION( ETyp, Raise ) \\\n catch (ETyp & _e_) { Raise( uno::makeAny(_e_) ); }\n\n#define WRAP_EXCEPTION1( ETyp, Raise, Arg ) \\\n catch (ETyp & _e_) { Raise( uno::makeAny(_e_), (Arg) ); }\n\n#define PASS_EXCEPTION( ETyp ) \\\n catch (ETyp & ) { throw; }\n\n#define WRAP_CONFIGBACKEND_CREATION_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::AuthenticationFailedException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::InvalidAuthenticationMechanismException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::CannotConnectException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendSetupException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendAccessException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::MissingBootstrapFileException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::InvalidBootstrapFileException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::InstallationIncompleteException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::CannotLoadConfigurationException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetRuntimeException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::lang::DisposedException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::uno::RuntimeException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::uno::Exception, Raise)\n\n#define WRAP_CONFIGBACKEND_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::ConnectionLostException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendAccessException, Raise) \\\n\n#define WRAP_CONFIGDATA_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::configuration::backend::MalformedDataException, Raise) \\\n WRAP_CONFIGBACKEND_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetException, Raise) \\\n\n#define WRAP_SAX_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::xml::sax::SAXParseException, Raise) \\\n WRAP_EXCEPTION(::com::sun::star::xml::sax::SAXException, Raise) \\\n\n#define WRAP_OTHER_EXCEPTIONS( Raise ) \\\n WRAP_EXCEPTION(::com::sun::star::uno::Exception, Raise)\n\n#define WRAP_CONFIGBACKEND_CREATION_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::AuthenticationFailedException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InvalidAuthenticationMechanismException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::CannotConnectException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendSetupException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendAccessException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::MissingBootstrapFileException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::InvalidBootstrapFileException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::InstallationIncompleteException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::CannotLoadConfigurationException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetRuntimeException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::lang::DisposedException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::uno::RuntimeException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::uno::Exception, Raise, Arg)\n\n#define WRAP_CONFIGBACKEND_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::ConnectionLostException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendAccessException, Raise, Arg) \\\n\n#define WRAP_CONFIGDATA_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::configuration::backend::MalformedDataException, Raise, Arg) \\\n WRAP_CONFIGBACKEND_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetException, Raise, Arg) \\\n\n#define WRAP_SAX_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::xml::sax::SAXParseException, Raise, Arg) \\\n WRAP_EXCEPTION1(::com::sun::star::xml::sax::SAXException, Raise, Arg) \\\n\n#define WRAP_OTHER_EXCEPTIONS1( Raise, Arg ) \\\n WRAP_EXCEPTION1(::com::sun::star::uno::Exception, Raise, Arg)\n\n#endif \/\/ CONFIGMGR_WRAPEXCEPTION_HXX\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <dlfcn.h>\nusing namespace std;\n\nint main(int argc, char *argv[] ) {\n void *hdl = dlopen(\"build\/liblua\", RTLD_NOW);\n if(hdl == 0) {\n cout << dlerror() << endl;\n return -1;\n }\n cout << \"hdl=\" << (long)hdl << endl;\n void *f = dlsym(hdl, \"lua_createtable\");\n cout << \"f=\" << (long)f << endl;\n return 0;\n}\n\n\n<commit_msg>update<commit_after>#include <iostream>\n#include <dlfcn.h>\nusing namespace std;\n\nint main(int argc, char *argv[] ) {\n void *hdl = dlopen(\"libbar.dylib\", RTLD_NOW);\n if(hdl == 0) {\n cout << dlerror() << endl;\n return -1;\n }\n cout << \"hdl=\" << (long)hdl << endl;\n void *f = dlsym(hdl, \"lua_createtable\");\n cout << \"f=\" << (long)f << endl;\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <Python.h>\n\n#include \"s2.h\"\n#include \"s2cap.h\"\n#include \"s2cellid.h\"\n#include \"s2latlng.h\"\n#include \"s2regioncoverer.h\"\n\nconst double kEarthCircumferenceMeters = 6371008.8 * M_PI * 2;\n\n\/\/ Generates a list of cells at the target s2 cell levels which cover\n\/\/ a cap of radius 'radius_meters' with center at lat & lng.\nstatic PyObject *GetCellIDs(PyObject *self, PyObject *args) {\n double lat, lon;\n unsigned short int radius;\n if (!PyArg_ParseTuple(args, \"ddH\", &lat, &lon, &radius))\n return NULL;\n const S2Cap region = S2Cap::FromAxisAngle(\n S2LatLng::FromDegrees(lat, lon).ToPoint(),\n S1Angle::Degrees(360 * radius \/ kEarthCircumferenceMeters));\n S2RegionCoverer coverer;\n coverer.set_min_level(15);\n coverer.set_max_level(15);\n\n vector<S2CellId> covering;\n coverer.GetCovering(region, &covering);\n PyObject *cells, *cell;\n cells = PyTuple_New(covering.size());\n for (size_t i = 0; i < covering.size(); ++i) {\n cell = PyLong_FromUnsignedLongLong(covering[i].id());\n PyTuple_SetItem(cells, i, cell);\n }\n return cells;\n}\n\n\/* List of functions defined in the module *\/\nstatic PyMethodDef PogeoMethods[] = {\n {\"get_cell_ids\", GetCellIDs, METH_VARARGS,\n \"Get the cell IDs for the given coordinates.\"},\n {NULL, NULL, 0, NULL} \/* sentinel *\/\n};\n\nstatic struct PyModuleDef pogeomodule = {\n PyModuleDef_HEAD_INIT, \"pogeo\", \/* name of module *\/\n NULL, \/* module documentation, may be NULL *\/\n -1, \/* size of per-interpreter state of the module,\n or -1 if the module keeps state in global variables. *\/\n PogeoMethods\n};\n\nPyMODINIT_FUNC PyInit_pogeo(void) { return PyModule_Create(&pogeomodule); }\n<commit_msg>Make radius parameter optional<commit_after>#include <Python.h>\n\n#include \"s2.h\"\n#include \"s2cap.h\"\n#include \"s2cellid.h\"\n#include \"s2latlng.h\"\n#include \"s2regioncoverer.h\"\n\nconst double kEarthCircumferenceMeters = 6371008.8 * M_PI * 2;\n\n\/\/ Generates a list of cells at the target s2 cell levels which cover\n\/\/ a cap of radius 'radius_meters' with center at lat & lng.\nstatic PyObject *GetCellIDs(PyObject *self, PyObject *args) {\n double lat, lon;\n unsigned short int radius;\n radius = 500;\n if (!PyArg_ParseTuple(args, \"dd|H\", &lat, &lon, &radius))\n return NULL;\n const S2Cap region = S2Cap::FromAxisAngle(\n S2LatLng::FromDegrees(lat, lon).ToPoint(),\n S1Angle::Degrees(360 * radius \/ kEarthCircumferenceMeters));\n S2RegionCoverer coverer;\n coverer.set_min_level(15);\n coverer.set_max_level(15);\n\n vector<S2CellId> covering;\n coverer.GetCovering(region, &covering);\n PyObject *cells, *cell;\n cells = PyTuple_New(covering.size());\n for (size_t i = 0; i < covering.size(); ++i) {\n cell = PyLong_FromUnsignedLongLong(covering[i].id());\n PyTuple_SetItem(cells, i, cell);\n }\n return cells;\n}\n\n\/* List of functions defined in the module *\/\nstatic PyMethodDef PogeoMethods[] = {\n {\"get_cell_ids\", GetCellIDs, METH_VARARGS,\n \"Get the cell IDs for the given coordinates.\"},\n {NULL, NULL, 0, NULL} \/* sentinel *\/\n};\n\nstatic struct PyModuleDef pogeomodule = {\n PyModuleDef_HEAD_INIT, \"pogeo\", \/* name of module *\/\n NULL, \/* module documentation, may be NULL *\/\n -1, \/* size of per-interpreter state of the module,\n or -1 if the module keeps state in global variables. *\/\n PogeoMethods\n};\n\nPyMODINIT_FUNC PyInit_pogeo(void) { return PyModule_Create(&pogeomodule); }\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: c++; c-basic-offset:4 -*-\n dialogs\/exportsecretkeydialog.cpp\n\n This file is part of Kleopatra, the KDE keymanager\n Copyright (c) 2008 Klarälvdalens Datakonsult AB\n\n Kleopatra 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 Kleopatra 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 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include <config-kleopatra.h>\n\n#include \"exportsecretkeydialog.h\"\n\n#include \"ui_exportsecretkeydialog.h\"\n\n#include <utils\/formatting.h>\n\n#include <gpgme++\/key.h>\n\n#include <KDebug>\n#include <KMessageBox>\n#include <KLocalizedString>\n\n#include <cassert>\n\nusing namespace Kleo;\nusing namespace Kleo::Dialogs;\nusing namespace GpgME;\n\n\/\/ This comes from gnupg's sources, agent\/minip12.c\n\/\/ In fact, any charset supported by iconv would work, but we don't link to iconv directly...\nstatic const char *charsets[] = {\n \"utf8\",\n \"iso-8859-1\",\n \"iso-8859-15\",\n \"iso-8859-2\",\n \"iso-8859-3\",\n \"iso-8859-4\",\n \"iso-8859-5\",\n \"iso-8859-6\",\n \"iso-8859-7\",\n \"iso-8859-8\",\n \"iso-8859-9\",\n \"koi8-r\",\n \"ibm437\",\n \"ibm850\",\n \"euc-jp\",\n \"big5\",\n};\nstatic const unsigned int numCharsets = sizeof charsets \/ sizeof *charsets;\n\nclass ExportSecretKeyDialog::Private {\n friend class ::Kleo::Dialogs::ExportSecretKeyDialog;\n ExportSecretKeyDialog * const q;\npublic:\n explicit Private( ExportSecretKeyDialog * qq )\n : q( qq ),\n ui( q )\n {\n\n }\n\nprivate:\n void updateWidgets() {\n const bool x509 = key.protocol() == CMS;\n ui.charsetCB->setVisible( x509 );\n ui.charsetLB->setVisible( x509 );\n }\n\n void updateFileName() {\n const bool x509 = key.protocol() == CMS;\n const bool armor = q->useArmor();\n\n static const char * extensions[] = {\n \".gpg\", \".asc\", \".der\", \".pem\"\n };\n const unsigned int idx = 2*x509+armor;\n const char * const extension = extensions[idx];\n\n const QString nf = i18n(\"Secret Key Files\") + QString::fromLatin1(\"(*%1 *%2 *%3 *%4)\")\n .arg( extensions[idx], extensions[(idx+1)%4], extensions[(idx+2)%4], extensions[(idx+3)%4] );\n ui.outputFileFR->setNameFilter( nf );\n\n QString fn = q->fileName();\n if ( fn.isEmpty() )\n return;\n\n bool found = false;\n for ( unsigned int i = 0 ; i < sizeof extensions \/ sizeof *extensions ; ++i )\n if ( fn.endsWith( extensions[i], Qt::CaseInsensitive ) ) {\n fn.chop( 4 );\n found = true;\n break;\n }\n if ( found )\n q->setFileName( fn + extension );\n }\n\n void updateLabel() {\n ui.descriptionLB->setText( i18nc(\"@info\",\n \"Please select export options for %1:\",\n Formatting::formatForComboBox( key ) ) );\n }\nprivate:\n Key key;\n\n struct UI : public Ui_ExportSecretKeyDialog {\n explicit UI( Dialogs::ExportSecretKeyDialog * qq )\n : Ui_ExportSecretKeyDialog()\n {\n setupUi( qq );\n\n outputFileFR->setExistingOnly( false );\n outputFileFR->setFilter( QDir::Files );\n outputFileFR->setNameFilter( i18n(\"Secret Key Files (*.pem *.der *.gpg *.asc)\") );\n\n for ( unsigned int i = 0 ; i < numCharsets ; ++i )\n charsetCB->addItem( QString::fromLatin1( charsets[i] ) );\n charsetCB->setCurrentIndex( -1 );\n \n }\n } ui;\n};\n\nExportSecretKeyDialog::ExportSecretKeyDialog( QWidget * p, Qt::WindowFlags f )\n : QDialog( p, f ), d( new Private( this ) )\n{\n\n}\n\nExportSecretKeyDialog::~ExportSecretKeyDialog() {}\n\n\nvoid ExportSecretKeyDialog::setKey( const Key & key ) {\n if ( qstricmp( key.primaryFingerprint(), d->key.primaryFingerprint() ) == 0 )\n return;\n d->key = key;\n d->updateWidgets();\n d->updateLabel();\n d->updateFileName();\n}\n\nKey ExportSecretKeyDialog::key() const {\n return d->key;\n}\n\nvoid ExportSecretKeyDialog::setFileName( const QString & fileName ) {\n d->ui.outputFileFR->setFileName( fileName );\n}\n\nQString ExportSecretKeyDialog::fileName() const {\n return d->ui.outputFileFR->fileName();\n}\n\nvoid ExportSecretKeyDialog::setCharset( const QByteArray & charset ) {\n for ( unsigned int i = 0 ; i < sizeof charsets \/ sizeof *charsets ; ++i )\n if ( charset == charsets[i] ) {\n d->ui.charsetCB->setCurrentIndex( i );\n return;\n }\n}\n\nQByteArray ExportSecretKeyDialog::charset() const {\n if ( d->ui.charsetCB->isVisible() )\n return d->ui.charsetCB->currentText().toLatin1();\n else\n return QByteArray();\n}\n\nvoid ExportSecretKeyDialog::setUseArmor( bool on ) {\n d->ui.armorCB->setChecked( on );\n}\n\nbool ExportSecretKeyDialog::useArmor() const {\n return d->ui.armorCB->isChecked();\n}\n\nvoid ExportSecretKeyDialog::accept() {\n d->updateFileName();\n const QString fn = fileName();\n if ( fn.isEmpty() ) {\n KMessageBox::information( this, i18nc(\"@info\",\n \"You have to enter an output filename.\" ),\n i18nc(\"@title\", \"Incomplete data\") );\n d->ui.outputFileFR->setFocus();\n return;\n }\n\n const QByteArray cs = charset();\n if ( d->key.protocol() == CMS && cs.isEmpty() ) {\n KMessageBox::information( this, i18nc(\"@info\",\n \"You have to choose a passphrase character set.\" ),\n i18nc(\"@title\", \"Incomplete data\") );\n d->ui.charsetCB->setFocus();\n return;\n }\n\n QDialog::accept();\n}\n\n#include \"moc_exportsecretkeydialog.cpp\"\n<commit_msg>Oops, secret key files are .12, not .der<commit_after>\/* -*- mode: c++; c-basic-offset:4 -*-\n dialogs\/exportsecretkeydialog.cpp\n\n This file is part of Kleopatra, the KDE keymanager\n Copyright (c) 2008 Klarälvdalens Datakonsult AB\n\n Kleopatra 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 Kleopatra 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 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include <config-kleopatra.h>\n\n#include \"exportsecretkeydialog.h\"\n\n#include \"ui_exportsecretkeydialog.h\"\n\n#include <utils\/formatting.h>\n\n#include <gpgme++\/key.h>\n\n#include <KDebug>\n#include <KMessageBox>\n#include <KLocalizedString>\n\n#include <cassert>\n\nusing namespace Kleo;\nusing namespace Kleo::Dialogs;\nusing namespace GpgME;\n\n\/\/ This comes from gnupg's sources, agent\/minip12.c\n\/\/ In fact, any charset supported by iconv would work, but we don't link to iconv directly...\nstatic const char *charsets[] = {\n \"utf8\",\n \"iso-8859-1\",\n \"iso-8859-15\",\n \"iso-8859-2\",\n \"iso-8859-3\",\n \"iso-8859-4\",\n \"iso-8859-5\",\n \"iso-8859-6\",\n \"iso-8859-7\",\n \"iso-8859-8\",\n \"iso-8859-9\",\n \"koi8-r\",\n \"ibm437\",\n \"ibm850\",\n \"euc-jp\",\n \"big5\",\n};\nstatic const unsigned int numCharsets = sizeof charsets \/ sizeof *charsets;\n\nclass ExportSecretKeyDialog::Private {\n friend class ::Kleo::Dialogs::ExportSecretKeyDialog;\n ExportSecretKeyDialog * const q;\npublic:\n explicit Private( ExportSecretKeyDialog * qq )\n : q( qq ),\n ui( q )\n {\n\n }\n\nprivate:\n void updateWidgets() {\n const bool x509 = key.protocol() == CMS;\n ui.charsetCB->setVisible( x509 );\n ui.charsetLB->setVisible( x509 );\n }\n\n void updateFileName() {\n const bool x509 = key.protocol() == CMS;\n const bool armor = q->useArmor();\n\n static const char * extensions[] = {\n \".gpg\", \".asc\", \".p12\", \".pem\"\n };\n const unsigned int idx = 2*x509+armor;\n const char * const extension = extensions[idx];\n\n const QString nf = i18n(\"Secret Key Files\") + QString::fromLatin1(\"(*%1 *%2 *%3 *%4)\")\n .arg( extensions[idx], extensions[(idx+1)%4], extensions[(idx+2)%4], extensions[(idx+3)%4] );\n ui.outputFileFR->setNameFilter( nf );\n\n QString fn = q->fileName();\n if ( fn.isEmpty() )\n return;\n\n bool found = false;\n for ( unsigned int i = 0 ; i < sizeof extensions \/ sizeof *extensions ; ++i )\n if ( fn.endsWith( extensions[i], Qt::CaseInsensitive ) ) {\n fn.chop( 4 );\n found = true;\n break;\n }\n if ( found )\n q->setFileName( fn + extension );\n }\n\n void updateLabel() {\n ui.descriptionLB->setText( i18nc(\"@info\",\n \"Please select export options for %1:\",\n Formatting::formatForComboBox( key ) ) );\n }\nprivate:\n Key key;\n\n struct UI : public Ui_ExportSecretKeyDialog {\n explicit UI( Dialogs::ExportSecretKeyDialog * qq )\n : Ui_ExportSecretKeyDialog()\n {\n setupUi( qq );\n\n outputFileFR->setExistingOnly( false );\n outputFileFR->setFilter( QDir::Files );\n outputFileFR->setNameFilter( i18n(\"Secret Key Files (*.pem *.p12 *.gpg *.asc)\") );\n\n for ( unsigned int i = 0 ; i < numCharsets ; ++i )\n charsetCB->addItem( QString::fromLatin1( charsets[i] ) );\n charsetCB->setCurrentIndex( -1 );\n \n }\n } ui;\n};\n\nExportSecretKeyDialog::ExportSecretKeyDialog( QWidget * p, Qt::WindowFlags f )\n : QDialog( p, f ), d( new Private( this ) )\n{\n\n}\n\nExportSecretKeyDialog::~ExportSecretKeyDialog() {}\n\n\nvoid ExportSecretKeyDialog::setKey( const Key & key ) {\n if ( qstricmp( key.primaryFingerprint(), d->key.primaryFingerprint() ) == 0 )\n return;\n d->key = key;\n d->updateWidgets();\n d->updateLabel();\n d->updateFileName();\n}\n\nKey ExportSecretKeyDialog::key() const {\n return d->key;\n}\n\nvoid ExportSecretKeyDialog::setFileName( const QString & fileName ) {\n d->ui.outputFileFR->setFileName( fileName );\n}\n\nQString ExportSecretKeyDialog::fileName() const {\n return d->ui.outputFileFR->fileName();\n}\n\nvoid ExportSecretKeyDialog::setCharset( const QByteArray & charset ) {\n for ( unsigned int i = 0 ; i < sizeof charsets \/ sizeof *charsets ; ++i )\n if ( charset == charsets[i] ) {\n d->ui.charsetCB->setCurrentIndex( i );\n return;\n }\n}\n\nQByteArray ExportSecretKeyDialog::charset() const {\n if ( d->ui.charsetCB->isVisible() )\n return d->ui.charsetCB->currentText().toLatin1();\n else\n return QByteArray();\n}\n\nvoid ExportSecretKeyDialog::setUseArmor( bool on ) {\n d->ui.armorCB->setChecked( on );\n}\n\nbool ExportSecretKeyDialog::useArmor() const {\n return d->ui.armorCB->isChecked();\n}\n\nvoid ExportSecretKeyDialog::accept() {\n d->updateFileName();\n const QString fn = fileName();\n if ( fn.isEmpty() ) {\n KMessageBox::information( this, i18nc(\"@info\",\n \"You have to enter an output filename.\" ),\n i18nc(\"@title\", \"Incomplete data\") );\n d->ui.outputFileFR->setFocus();\n return;\n }\n\n const QByteArray cs = charset();\n if ( d->key.protocol() == CMS && cs.isEmpty() ) {\n KMessageBox::information( this, i18nc(\"@info\",\n \"You have to choose a passphrase character set.\" ),\n i18nc(\"@title\", \"Incomplete data\") );\n d->ui.charsetCB->setFocus();\n return;\n }\n\n QDialog::accept();\n}\n\n#include \"moc_exportsecretkeydialog.cpp\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of telepathy-integration-daemon\n *\n * Copyright (C) 2009 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"telepathyaccount.h\"\n\n#include \"telepathyaccountmonitor.h\"\n\n\/\/ Ontology uri's\n#include \"nco.h\"\n#include \"pimo.h\"\n#include \"tpaccount.h\"\n\n\/\/ Full Ontologies\n#include \"personcontact.h\"\n\n#include <Akonadi\/AgentManager>\n\n#include <kdebug.h>\n\n#include <Nepomuk\/Thing>\n#include <Nepomuk\/Variant>\n\n#include <TelepathyQt4\/PendingOperation>\n#include <TelepathyQt4\/PendingReady>\n\nTelepathyAccount::TelepathyAccount(const QString &path, TelepathyAccountMonitor *parent)\n : QObject(parent),\n m_parent(parent),\n m_path(path)\n{\n \/\/ We need to get the Tp::Account ready before we do any other stuff.\n m_account = m_parent->accountManager()->accountForPath(path);\n\n Tp::Features features;\n features << Tp::Account::FeatureCore\n << Tp::Account::FeatureProtocolInfo;\n\n connect(m_account->becomeReady(features),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onAccountReady(Tp::PendingOperation*)));\n}\n\nTelepathyAccount::~TelepathyAccount()\n{\n\n}\n\nvoid TelepathyAccount::onAccountReady(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Account\" << m_path << \"cannot become ready:\"\n << op->errorName() << \"-\" << op->errorMessage();\n return;\n }\n\n \/\/ Check that this Account is set up in nepomuk.\n doNepomukSetup();\n\n \/\/ Once the nepomuk setup is complete, do the Akonadi setup.\n doAkonadiSetup();\n}\n\nvoid TelepathyAccount::doNepomukSetup()\n{\n \/\/ Get the PIMO:Person for \"me\" from nepomuk\n Nepomuk::Thing me(QUrl::fromEncoded(\"nepomuk:\/myself\"));\n\n if (!me.exists()) {\n \/\/ The PIMO:Person representing \"me\" does not exist, so we need to create it.\n me.addType(Nepomuk::Vocabulary::PIMO::Person());\n }\n\n \/\/ Loop through all the grounding instances of this person\n Q_FOREACH (Nepomuk::Resource resource, me.groundingOccurrences()) {\n \/\/ See if this grounding instance is of type nco:contact.\n if (resource.hasType(Nepomuk::Vocabulary::NCO::Contact())) {\n \/\/ we have an NCO:Contact. See if it is for this Telepathy Account.\n if (resource.hasProperty(Nepomuk::Vocabulary::TPACCOUNT::identifier())) {\n \/\/ we have a tpaccount property. See if it is the same as the path of this account.\n if (resource.property(Nepomuk::Vocabulary::TPACCOUNT::identifier()).toString() == m_path) {\n \/\/ Nepomuk has this account already. Don't need to do anything.\n return;\n }\n }\n }\n }\n\n kDebug() << \"Telepathy Account\" << m_path << \"does not exist is nepomuk yet. Add it.\";\n \/\/ Nepomuk doesn't yet have this account. Add it.\n Nepomuk::PersonContact contact(m_path);\n contact.setLabel(m_account->nickname());\n\n me.addProperty(Nepomuk::Vocabulary::NCO::PersonContact(), contact);\n}\n\nvoid TelepathyAccount::doAkonadiSetup()\n{\n \/\/ Loop over the list of Agents to find one with the unique identifier of this account and with\n \/\/ the correct type.\n Akonadi::AgentInstance::List agentList = Akonadi::AgentManager::self()->instances();\n\n foreach (Akonadi::AgentInstance agent, agentList) {\n if (agent.type().identifier() == \"telepathy_contacts_resource\") {\n if (agent.type().identifier() == \"telepathy_contacts_resource\") {\n \/\/ This is our agent. Nothing to do. Return.\n return;\n }\n }\n }\n\n \/\/ If we reach here, the agent doesn't exist for this account, so create an instance of it.\n \/\/ TODO: Implement me!\n}\n\n<commit_msg>Add some debug statements.<commit_after>\/*\n * This file is part of telepathy-integration-daemon\n *\n * Copyright (C) 2009 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"telepathyaccount.h\"\n\n#include \"telepathyaccountmonitor.h\"\n\n\/\/ Ontology uri's\n#include \"nco.h\"\n#include \"pimo.h\"\n#include \"tpaccount.h\"\n\n\/\/ Full Ontologies\n#include \"personcontact.h\"\n\n#include <Akonadi\/AgentManager>\n\n#include <kdebug.h>\n\n#include <Nepomuk\/Thing>\n#include <Nepomuk\/Variant>\n\n#include <TelepathyQt4\/PendingOperation>\n#include <TelepathyQt4\/PendingReady>\n\nTelepathyAccount::TelepathyAccount(const QString &path, TelepathyAccountMonitor *parent)\n : QObject(parent),\n m_parent(parent),\n m_path(path)\n{\n \/\/ We need to get the Tp::Account ready before we do any other stuff.\n m_account = m_parent->accountManager()->accountForPath(path);\n\n Tp::Features features;\n features << Tp::Account::FeatureCore\n << Tp::Account::FeatureProtocolInfo;\n\n connect(m_account->becomeReady(features),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onAccountReady(Tp::PendingOperation*)));\n}\n\nTelepathyAccount::~TelepathyAccount()\n{\n\n}\n\nvoid TelepathyAccount::onAccountReady(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Account\" << m_path << \"cannot become ready:\"\n << op->errorName() << \"-\" << op->errorMessage();\n return;\n }\n\n \/\/ Check that this Account is set up in nepomuk.\n doNepomukSetup();\n\n \/\/ Once the nepomuk setup is complete, do the Akonadi setup.\n doAkonadiSetup();\n}\n\nvoid TelepathyAccount::doNepomukSetup()\n{\n \/\/ Get the PIMO:Person for \"me\" from nepomuk\n Nepomuk::Thing me(QUrl::fromEncoded(\"nepomuk:\/myself\"));\n\n if (!me.exists()) {\n \/\/ The PIMO:Person representing \"me\" does not exist, so we need to create it.\n me.addType(Nepomuk::Vocabulary::PIMO::Person());\n }\n\n \/\/ Loop through all the grounding instances of this person\n Q_FOREACH (Nepomuk::Resource resource, me.groundingOccurrences()) {\n \/\/ See if this grounding instance is of type nco:contact.\n if (resource.hasType(Nepomuk::Vocabulary::NCO::Contact())) {\n \/\/ we have an NCO:Contact. See if it is for this Telepathy Account.\n if (resource.hasProperty(Nepomuk::Vocabulary::TPACCOUNT::identifier())) {\n \/\/ we have a tpaccount property. See if it is the same as the path of this account.\n if (resource.property(Nepomuk::Vocabulary::TPACCOUNT::identifier()).toString() == m_path) {\n \/\/ Nepomuk has this account already. Don't need to do anything.\n return;\n }\n }\n }\n }\n\n kDebug() << \"Telepathy Account\" << m_path << \"does not exist is nepomuk yet. Add it.\";\n \/\/ Nepomuk doesn't yet have this account. Add it.\n Nepomuk::PersonContact contact(m_path);\n contact.setLabel(m_account->nickname());\n\n me.addProperty(Nepomuk::Vocabulary::NCO::PersonContact(), contact);\n}\n\nvoid TelepathyAccount::doAkonadiSetup()\n{\n \/\/ Loop over the list of Agents to find one with the unique identifier of this account and with\n \/\/ the correct type.\n Akonadi::AgentInstance::List agentList = Akonadi::AgentManager::self()->instances();\n\n foreach (Akonadi::AgentInstance agent, agentList) {\n if (agent.type().identifier() == \"telepathy_contacts_resource\") {\n if (agent.type().identifier() == \"telepathy_contacts_resource\") {\n \/\/ This is our agent. Nothing to do. Return.\n kDebug() << \"This telepathy account already has a Akonadi Resource for it.\";\n return;\n }\n }\n }\n\n \/\/ If we reach here, the agent doesn't exist for this account, so create an instance of it.\n kDebug() << \"This telepathy account doesn't already have an Akonadi Resource for it. Create one.\";\n \/\/ TODO: Implement me!\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <QtTest>\n#include <QtCore>\n\n#include <options.h>\n#include <idmapping.h>\n\n#include <KGlobal>\n#include <KStandardDirs>\n\n#include \"qtest_kde.h\"\n\nclass IDMappingTest : public QObject\n{\n\tQ_OBJECT\n\t\npublic:\n\tIDMappingTest();\n\t\nprivate slots:\n\tvoid testMap();\n\tvoid testRemove();\n\tvoid testIsValid();\n\tvoid testRecordId();\n\tvoid testCommitRollBack();\n\tvoid cleanupTestCase();\n\t\n\nprivate:\n\tvoid cleanDir();\n\t\n\tQString fUser;\n\tQString fConduit;\n};\n\nIDMappingTest::IDMappingTest() : fUser( \"test-user\" )\n\t, fConduit(\"test-conduit\")\n{\n}\n\nvoid IDMappingTest::testMap()\n{\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\t\n\tQVERIFY( mapping.contains( CSL1( \"hh-1\" ) ) );\n\tQVERIFY( mapping.contains( CSL1( \"pc-100\" ) ) );\n}\n\nvoid IDMappingTest::testRemove()\n{\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.remove( CSL1( \"hh-1\" ) );\n\t\n\tQVERIFY( !mapping.contains( CSL1( \"hh-1\" ) ) );\n\tQVERIFY( !mapping.contains( CSL1( \"pc-100\" ) ) );\n\t\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.remove( CSL1( \"pc-100\" ) );\n\t\n\tQVERIFY( !mapping.contains( CSL1( \"hh-1\" ) ) );\n\tQVERIFY( !mapping.contains( CSL1( \"pc-100\" ) ) );\n}\n\nvoid IDMappingTest::testIsValid()\n{\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.map( CSL1( \"hh-2\" ), CSL1( \"pc-40\" ) );\n\tmapping.map( CSL1( \"hh-3\" ), CSL1( \"pc-46\" ) );\n\t\n\tQStringList hhIds;\n\thhIds << CSL1( \"hh-1\" ) << CSL1( \"hh-2\" ) << CSL1( \"hh-3\" );\n\t\n\tQStringList pcIds;\n\tpcIds << CSL1( \"pc-100\" ) << CSL1( \"pc-40\" ) << CSL1( \"pc-46\" );\n\t\n\t\/*\n\t * This is a bit tricky. There are three id's in the list and there are three\n\t * mappings. Also for each id in this list exists a mapping. BUT the ids of \n\t * hh and are mixed here and have a mapping all by coincidence, however this\n\t * does not garantee that the mapping is valid. If for example \"hh-1\" maps to\n\t * \"pc-78\" the mapping is invalid because it should map to \"pc-100\"\n\t *\/\n\tQStringList trickyIds;\n\ttrickyIds << CSL1( \"hh-1\" ) << CSL1( \"pc-40\" ) << CSL1( \"pc-46\" );\n\t\n\tQStringList randomIds;\n\trandomIds << CSL1( \"random-2\" ) << CSL1( \"random-14\" );\n\trandomIds\t<< CSL1( \"random-109\" );\n\t\n\tQVERIFY( mapping.isValid( hhIds ) );\n\tQVERIFY( mapping.isValid( pcIds ) );\n\tQVERIFY( !mapping.isValid( trickyIds ) );\n\tQVERIFY( !mapping.isValid( randomIds ) );\n}\n\nvoid IDMappingTest::testRecordId()\n{\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.map( CSL1( \"hh-2\" ), CSL1( \"pc-40\" ) );\n\t\n\tQVERIFY( mapping.recordId( CSL1( \"hh-1\" ) ) == CSL1( \"pc-100\" ) );\n\tQVERIFY( mapping.recordId( CSL1( \"pc-100\" ) ) == CSL1( \"hh-1\" ) );\n\tQVERIFY( mapping.recordId( CSL1( \"hh-2\" ) ) == CSL1( \"pc-40\" ) );\n\tQVERIFY( mapping.recordId( CSL1( \"pc-40\" ) ) == CSL1( \"hh-2\" ) );\n}\n\nvoid IDMappingTest::testCommitRollBack()\n{\n\t\/\/ Clean up things to ensure this test won't be influenced by earlier data\n\t\/\/ which might be there.\n\tcleanDir();\n\t\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.map( CSL1( \"hh-2\" ), CSL1( \"pc-40\" ) );\n\tmapping.commit();\n\t\n\t\/\/ Should contain 2 mappings\n\tIDMapping mapping2( fUser, fConduit );\n\t\n\tQStringList hhIds, hhIds2;\n\thhIds << CSL1( \"hh-1\" ) << CSL1( \"hh-2\" );\n\thhIds2 << hhIds << CSL1( \"hh-3\" );\n\t\n\tQVERIFY( mapping.isValid( hhIds ) );\n\t\n\tmapping2.map( CSL1( \"hh-3\" ), CSL1( \"pc-23\" ) );\n\tmapping2.commit();\n\t\n\tQVERIFY( mapping2.isValid( hhIds2 ) );\n\t\n\tmapping2.rollback();\n\t\n\tQVERIFY( mapping2.isValid( hhIds ) );\n\t\n\tIDMapping mapping3( fUser, fConduit );\n\t\n\tQVERIFY( mapping3.isValid( hhIds ) );\n}\n\nvoid IDMappingTest::cleanDir()\n{\n\tQString pathName = KGlobal::dirs()->saveLocation( \"data\",\n\t\tCSL1(\"kpilot\/conduits\/\"));\n\t\t\n\tQDir dir( pathName );\n\tdir.cd( fUser );\n\tdir.cd( CSL1( \"mapping\" ) );\n\tdir.remove( fConduit + CSL1( \"-mapping.xml\" ) );\n\tdir.remove( fConduit + CSL1( \"-mapping.xml~\" ) );\n\tdir.remove( fConduit + CSL1( \"-mapping.xml.fail\" ) );\n\tdir.cd( CSL1( \"..\" ) );\n\tdir.rmdir( CSL1( \"mapping\" ) );\n\tdir.cd( CSL1( \"..\" ) );\n\tdir.rmdir( fUser );\n}\n\nvoid IDMappingTest::cleanupTestCase()\n{\n\t\/\/cleanDir();\n}\n\n \nQTEST_KDEMAIN(IDMappingTest, NoGUI)\n\n#include \"idmappingtest.moc\"\n<commit_msg>SVN_SILENT: - Added copyright<commit_after>\/* idmappingtest.cc\t\t\tKPilot\n**\n** Copyright (C) 2007 by Bertjan Broeksema\n** Copyright (C) 2007 by Jason \"vanRijn\" Kasper\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as published by\n** the Free Software Foundation; either version 2.1 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. See the\n** GNU Lesser General Public License for more details.\n**\n** You should have received a copy of the GNU Lesser General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n** MA 02110-1301, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\n#include <QtTest>\n#include <QtCore>\n\n#include <options.h>\n#include <idmapping.h>\n\n#include <KGlobal>\n#include <KStandardDirs>\n\n#include \"qtest_kde.h\"\n\nclass IDMappingTest : public QObject\n{\n\tQ_OBJECT\n\t\npublic:\n\tIDMappingTest();\n\t\nprivate slots:\n\tvoid testMap();\n\tvoid testRemove();\n\tvoid testIsValid();\n\tvoid testRecordId();\n\tvoid testCommitRollBack();\n\tvoid cleanupTestCase();\n\t\n\nprivate:\n\tvoid cleanDir();\n\t\n\tQString fUser;\n\tQString fConduit;\n};\n\nIDMappingTest::IDMappingTest() : fUser( \"test-user\" )\n\t, fConduit(\"test-conduit\")\n{\n}\n\nvoid IDMappingTest::testMap()\n{\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\t\n\tQVERIFY( mapping.contains( CSL1( \"hh-1\" ) ) );\n\tQVERIFY( mapping.contains( CSL1( \"pc-100\" ) ) );\n}\n\nvoid IDMappingTest::testRemove()\n{\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.remove( CSL1( \"hh-1\" ) );\n\t\n\tQVERIFY( !mapping.contains( CSL1( \"hh-1\" ) ) );\n\tQVERIFY( !mapping.contains( CSL1( \"pc-100\" ) ) );\n\t\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.remove( CSL1( \"pc-100\" ) );\n\t\n\tQVERIFY( !mapping.contains( CSL1( \"hh-1\" ) ) );\n\tQVERIFY( !mapping.contains( CSL1( \"pc-100\" ) ) );\n}\n\nvoid IDMappingTest::testIsValid()\n{\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.map( CSL1( \"hh-2\" ), CSL1( \"pc-40\" ) );\n\tmapping.map( CSL1( \"hh-3\" ), CSL1( \"pc-46\" ) );\n\t\n\tQStringList hhIds;\n\thhIds << CSL1( \"hh-1\" ) << CSL1( \"hh-2\" ) << CSL1( \"hh-3\" );\n\t\n\tQStringList pcIds;\n\tpcIds << CSL1( \"pc-100\" ) << CSL1( \"pc-40\" ) << CSL1( \"pc-46\" );\n\t\n\t\/*\n\t * This is a bit tricky. There are three id's in the list and there are three\n\t * mappings. Also for each id in this list exists a mapping. BUT the ids of \n\t * hh and are mixed here and have a mapping all by coincidence, however this\n\t * does not garantee that the mapping is valid. If for example \"hh-1\" maps to\n\t * \"pc-78\" the mapping is invalid because it should map to \"pc-100\"\n\t *\/\n\tQStringList trickyIds;\n\ttrickyIds << CSL1( \"hh-1\" ) << CSL1( \"pc-40\" ) << CSL1( \"pc-46\" );\n\t\n\tQStringList randomIds;\n\trandomIds << CSL1( \"random-2\" ) << CSL1( \"random-14\" );\n\trandomIds\t<< CSL1( \"random-109\" );\n\t\n\tQVERIFY( mapping.isValid( hhIds ) );\n\tQVERIFY( mapping.isValid( pcIds ) );\n\tQVERIFY( !mapping.isValid( trickyIds ) );\n\tQVERIFY( !mapping.isValid( randomIds ) );\n}\n\nvoid IDMappingTest::testRecordId()\n{\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.map( CSL1( \"hh-2\" ), CSL1( \"pc-40\" ) );\n\t\n\tQVERIFY( mapping.recordId( CSL1( \"hh-1\" ) ) == CSL1( \"pc-100\" ) );\n\tQVERIFY( mapping.recordId( CSL1( \"pc-100\" ) ) == CSL1( \"hh-1\" ) );\n\tQVERIFY( mapping.recordId( CSL1( \"hh-2\" ) ) == CSL1( \"pc-40\" ) );\n\tQVERIFY( mapping.recordId( CSL1( \"pc-40\" ) ) == CSL1( \"hh-2\" ) );\n}\n\nvoid IDMappingTest::testCommitRollBack()\n{\n\t\/\/ Clean up things to ensure this test won't be influenced by earlier data\n\t\/\/ which might be there.\n\tcleanDir();\n\t\n\tIDMapping mapping( fUser, fConduit );\n\tmapping.map( CSL1( \"hh-1\" ), CSL1( \"pc-100\" ) );\n\tmapping.map( CSL1( \"hh-2\" ), CSL1( \"pc-40\" ) );\n\tmapping.commit();\n\t\n\t\/\/ Should contain 2 mappings\n\tIDMapping mapping2( fUser, fConduit );\n\t\n\tQStringList hhIds, hhIds2;\n\thhIds << CSL1( \"hh-1\" ) << CSL1( \"hh-2\" );\n\thhIds2 << hhIds << CSL1( \"hh-3\" );\n\t\n\tQVERIFY( mapping.isValid( hhIds ) );\n\t\n\tmapping2.map( CSL1( \"hh-3\" ), CSL1( \"pc-23\" ) );\n\tmapping2.commit();\n\t\n\tQVERIFY( mapping2.isValid( hhIds2 ) );\n\t\n\tmapping2.rollback();\n\t\n\tQVERIFY( mapping2.isValid( hhIds ) );\n\t\n\tIDMapping mapping3( fUser, fConduit );\n\t\n\tQVERIFY( mapping3.isValid( hhIds ) );\n}\n\nvoid IDMappingTest::cleanDir()\n{\n\tQString pathName = KGlobal::dirs()->saveLocation( \"data\",\n\t\tCSL1(\"kpilot\/conduits\/\"));\n\t\t\n\tQDir dir( pathName );\n\tdir.cd( fUser );\n\tdir.cd( CSL1( \"mapping\" ) );\n\tdir.remove( fConduit + CSL1( \"-mapping.xml\" ) );\n\tdir.remove( fConduit + CSL1( \"-mapping.xml~\" ) );\n\tdir.remove( fConduit + CSL1( \"-mapping.xml.fail\" ) );\n\tdir.cd( CSL1( \"..\" ) );\n\tdir.rmdir( CSL1( \"mapping\" ) );\n\tdir.cd( CSL1( \"..\" ) );\n\tdir.rmdir( fUser );\n}\n\nvoid IDMappingTest::cleanupTestCase()\n{\n\tcleanDir();\n}\n\n \nQTEST_KDEMAIN(IDMappingTest, NoGUI)\n\n#include \"idmappingtest.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include <functional>\n#include <future>\n#include \"coverage.h\"\n#include \"numericrange.h\"\n#include \"numericdomain.h\"\n#include \"columndefinition.h\"\n#include \"table.h\"\n#include \"factory.h\"\n#include \"abstractfactory.h\"\n#include \"featurefactory.h\"\n#include \"featurecoverage.h\"\n#include \"feature.h\"\n#include \"featureiterator.h\"\n#include \"symboltable.h\"\n#include \"operationExpression.h\"\n#include \"operationmetadata.h\"\n#include \"operation.h\"\n#include \"tablemerger.h\"\n#include \"binarymathfeature.h\"\n\nusing namespace Ilwis;\nusing namespace BaseOperations;\n\nREGISTER_OPERATION(BinaryMathFeature)\n\nBinaryMathFeature::BinaryMathFeature()\n{\n}\n\nBinaryMathFeature::BinaryMathFeature(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)\n{\n}\n\nbool BinaryMathFeature::execute(ExecutionContext *ctx, SymbolTable &symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx, symTable)) != sPREPARED)\n return false;\n\n\n FeatureIterator iterIn1(_inputFeatureSet1);\n for_each(iterIn1, iterIn1.end(), [&](SPFeatureI feature){\n _outputFeatures->newFeatureFrom(feature, _inputFeatureSet1->coordinateSystem());\n });\n\n FeatureIterator iterIn2(_inputFeatureSet2);\n for_each(iterIn2, iterIn2.end(), [&](SPFeatureI feature){\n _outputFeatures->newFeatureFrom(feature, _inputFeatureSet2->coordinateSystem());\n });\n\n ITable attTarget = _outputFeatures->attributeTable();\n _merger.mergeTableData(_inputFeatureSet1->attributeTable(), _inputFeatureSet2->attributeTable(), attTarget);\n\n return true;\n}\n\nOperationImplementation *BinaryMathFeature::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new BinaryMathFeature(metaid, expr);\n}\n\nOperationImplementation::State BinaryMathFeature::prepare(ExecutionContext *ctx, const SymbolTable &)\n{\n QString featureCovName = _expression.parm(0).value();\n if (!_inputFeatureSet1.prepare(featureCovName)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,featureCovName,\"\" );\n return sPREPAREFAILED;\n }\n featureCovName = _expression.parm(1).value();\n if (!_inputFeatureSet2.prepare(featureCovName)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,featureCovName,\"\" );\n return sPREPAREFAILED;\n }\n bool ok = false;\n if ( ctx->_masterCsy != sUNDEF) {\n ok = _csyTarget.prepare(ctx->_masterCsy);\n if (!ok){\n WARN1(WARN_COULDNT_CREATE_OBJECT_FOR_1,ctx->_masterCsy);\n }\n }\n if (!ok) {\n _csyTarget = _inputFeatureSet1->coordinateSystem();\n }\n\n Resource resource(_inputFeatureSet1->ilwisType() | _inputFeatureSet2->ilwisType());\n _outputFeatures.prepare(resource);\n Envelope envelope = addEnvelopes();\n _outputFeatures->coordinateSystem(_csyTarget);\n _outputFeatures->envelope(envelope);\n\n ITable attTable = _merger.mergeMetadataTables(_inputFeatureSet1->attributeTable(), _inputFeatureSet2->attributeTable());\n attTable->recordCount(_inputFeatureSet1->featureCount() + _inputFeatureSet2->featureCount());\n _outputFeatures->attributesFromTable(attTable);\n\n QString outname = _expression.parm(0,false).value();\n if ( outname != sUNDEF)\n _outputFeatures->name(outname);\n\n return sPREPARED;\n}\n\nEnvelope BinaryMathFeature::addEnvelopes() const {\n Envelope envelope = _csyTarget->convertEnvelope(_inputFeatureSet1->coordinateSystem(),_inputFeatureSet1->envelope());\n envelope += _csyTarget->convertEnvelope(_inputFeatureSet2->coordinateSystem(),_inputFeatureSet2->envelope());\n return envelope;\n}\n\nquint64 BinaryMathFeature::createMetadata()\n{\n OperationResource operation({\"ilwis:\/\/operations\/binarymathfeatures\"});\n operation.setSyntax(\"binarymathfeatures(featurecoverage1,featurescoverage2,add|substract)\");\n operation.setDescription(TR(\"generates a new featurecoverage that puts all the features of both coverages into one coverage\"));\n operation.setInParameterCount({3});\n operation.addInParameter(0,itFEATURE, TR(\"first input feature coverage\"));\n operation.addInParameter(1,itFEATURE, TR(\"second input feature coverage\"));\n operation.addInParameter(2,itSTRING , TR(\"Operator\"),TR(\"operator applied to the other 2 input parameters\"));\n operation.setOutParameterCount({1});\n operation.addOutParameter(0,itFEATURE, TR(\"output featurecoverage\"));\n operation.setKeywords(\"features, merge\");\n\n mastercatalog()->addItems({operation});\n return operation.id();\n}\n<commit_msg>set default operation<commit_after>#include <functional>\n#include <future>\n#include \"coverage.h\"\n#include \"numericrange.h\"\n#include \"numericdomain.h\"\n#include \"columndefinition.h\"\n#include \"table.h\"\n#include \"factory.h\"\n#include \"abstractfactory.h\"\n#include \"featurefactory.h\"\n#include \"featurecoverage.h\"\n#include \"feature.h\"\n#include \"featureiterator.h\"\n#include \"symboltable.h\"\n#include \"operationExpression.h\"\n#include \"operationmetadata.h\"\n#include \"operation.h\"\n#include \"tablemerger.h\"\n#include \"binarymathfeature.h\"\n\nusing namespace Ilwis;\nusing namespace BaseOperations;\n\nREGISTER_OPERATION(BinaryMathFeature)\n\nBinaryMathFeature::BinaryMathFeature()\n{\n}\n\nBinaryMathFeature::BinaryMathFeature(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)\n{\n}\n\nbool BinaryMathFeature::execute(ExecutionContext *ctx, SymbolTable &symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx, symTable)) != sPREPARED)\n return false;\n\n\n FeatureIterator iterIn1(_inputFeatureSet1);\n for_each(iterIn1, iterIn1.end(), [&](SPFeatureI feature){\n _outputFeatures->newFeatureFrom(feature, _inputFeatureSet1->coordinateSystem());\n });\n\n FeatureIterator iterIn2(_inputFeatureSet2);\n for_each(iterIn2, iterIn2.end(), [&](SPFeatureI feature){\n _outputFeatures->newFeatureFrom(feature, _inputFeatureSet2->coordinateSystem());\n });\n\n ITable attTarget = _outputFeatures->attributeTable();\n _merger.mergeTableData(_inputFeatureSet1->attributeTable(), _inputFeatureSet2->attributeTable(), attTarget);\n\n return true;\n}\n\nOperationImplementation *BinaryMathFeature::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new BinaryMathFeature(metaid, expr);\n}\n\nOperationImplementation::State BinaryMathFeature::prepare(ExecutionContext *ctx, const SymbolTable &)\n{\n QString featureCovName = _expression.parm(0).value();\n if (!_inputFeatureSet1.prepare(featureCovName)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,featureCovName,\"\" );\n return sPREPAREFAILED;\n }\n featureCovName = _expression.parm(1).value();\n if (!_inputFeatureSet2.prepare(featureCovName)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,featureCovName,\"\" );\n return sPREPAREFAILED;\n }\n bool ok = false;\n if ( ctx->_masterCsy != sUNDEF) {\n ok = _csyTarget.prepare(ctx->_masterCsy);\n if (!ok){\n WARN1(WARN_COULDNT_CREATE_OBJECT_FOR_1,ctx->_masterCsy);\n }\n }\n if (!ok) {\n _csyTarget = _inputFeatureSet1->coordinateSystem();\n }\n\n Resource resource(_inputFeatureSet1->ilwisType() | _inputFeatureSet2->ilwisType());\n _outputFeatures.prepare(resource);\n Envelope envelope = addEnvelopes();\n _outputFeatures->coordinateSystem(_csyTarget);\n _outputFeatures->envelope(envelope);\n\n ITable attTable = _merger.mergeMetadataTables(_inputFeatureSet1->attributeTable(), _inputFeatureSet2->attributeTable());\n attTable->recordCount(_inputFeatureSet1->featureCount() + _inputFeatureSet2->featureCount());\n _outputFeatures->attributesFromTable(attTable);\n\n QString outname = _expression.parm(0,false).value();\n if ( outname != sUNDEF)\n _outputFeatures->name(outname);\n\n return sPREPARED;\n}\n\nEnvelope BinaryMathFeature::addEnvelopes() const {\n Envelope envelope = _csyTarget->convertEnvelope(_inputFeatureSet1->coordinateSystem(),_inputFeatureSet1->envelope());\n envelope += _csyTarget->convertEnvelope(_inputFeatureSet2->coordinateSystem(),_inputFeatureSet2->envelope());\n return envelope;\n}\n\nquint64 BinaryMathFeature::createMetadata()\n{\n OperationResource operation({\"ilwis:\/\/operations\/binarymathfeatures\"});\n operation.setSyntax(\"binarymathfeatures(featurecoverage1,featurescoverage2,!add|substract)\");\n operation.setDescription(TR(\"generates a new featurecoverage that puts all the features of both coverages into one coverage\"));\n operation.setInParameterCount({3});\n operation.addInParameter(0,itFEATURE, TR(\"first input feature coverage\"));\n operation.addInParameter(1,itFEATURE, TR(\"second input feature coverage\"));\n operation.addInParameter(2,itSTRING , TR(\"Operator\"),TR(\"operator applied to the other 2 input parameters\"));\n operation.setOutParameterCount({1});\n operation.addOutParameter(0,itFEATURE, TR(\"output featurecoverage\"));\n operation.setKeywords(\"features, merge\");\n\n mastercatalog()->addItems({operation});\n return operation.id();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dsa_common.h\"\n\n#include \"tcp_connection.h\"\n\n#include <boost\/bind.hpp>\n\n#include \"session_manager.h\"\n\nnamespace dsa {\n\nTcpConnection::TcpConnection(std::shared_ptr<App> app, const Config &config)\n : Connection(app, config), _socket(app->io_service()), _strand(app->io_service()) {\n}\n\nvoid TcpConnection::close() {\n _socket.cancel();\n _deadline->cancel();\n}\n\nvoid TcpConnection::read_loop(size_t from_prev, const boost::system::error_code &error, size_t bytes_transferred) {\n \/\/ reset deadline timer for each new message\n reset_standard_deadline_timer();\n\n if (!error \/* && !destroyed() *\/) {\n std::cout << std::endl << \"in read loop\" << std::endl;\n\n BufferPtr buf = std::move(_read_buffer);\n _read_buffer.reset(new Buffer());\n\n size_t total_bytes = from_prev + bytes_transferred;\n uint8_t *data = buf->data();\n size_t cur = 0;\n\n while (cur < total_bytes) {\n \/\/ always want full static header instead of just message size to make sure it's a valid message\n if (total_bytes - cur < StaticHeaders::TotalSize) {\n size_t partial_size = total_bytes - cur;\n _read_buffer->assign(&data[cur], partial_size);\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data() + partial_size,\n _read_buffer->capacity() - partial_size),\n boost::bind(&TcpConnection::read_loop, share_this<TcpConnection>(), partial_size,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n return;\n }\n\n StaticHeaders header(&data[cur]);\n if (header.message_size < total_bytes - cur) {\n size_t partial_size = total_bytes - cur;\n\n \/\/ make sure buffer capacity is enough to read full message\n _read_buffer->resize(header.message_size);\n _read_buffer->assign(&data[cur], partial_size);\n\n \/\/ read the rest of the message\n boost::asio::async_read(_socket,\n boost::asio::buffer(_read_buffer->data() + partial_size,\n _read_buffer->capacity() - partial_size),\n boost::bind(&TcpConnection::read_loop, share_this<TcpConnection>(), partial_size,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n return;\n }\n\n \/\/ post job with message buffer\n _app->io_service().post(boost::bind(&TcpConnection::handle_message, shared_from_this(),\n buf->get_shared_buffer(cur, header.message_size)));\n\n cur += header.message_size;\n }\n\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpConnection::read_loop, share_this<TcpConnection>(), 0,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n}\n\nvoid TcpConnection::write_handler(WriteHandler callback, const boost::system::error_code &error) {\n if (!error \/* && !destroyed() *\/) callback();\n}\n\nvoid TcpConnection::write(BufferPtr buf, size_t size, WriteHandler callback) {\n \/\/ check to see if current number of pending messages is above allowed limit\n if (++_pending_messages > _config.max_pending_messages()) {\n close();\n return;\n }\n\n boost::asio::async_write(_socket, boost::asio::buffer(buf->data(), size),\n boost::bind(&TcpConnection::write_handler, share_this<TcpConnection>(), callback,\n boost::asio::placeholders::error));\n}\n\nvoid TcpConnection::start() throw() {\n if (_session == nullptr)\n throw std::runtime_error(\"Error: connection started with no session\");\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpConnection::read_loop, share_this<TcpConnection>(), 0,\n boost::asio::placeholders::error, 0));\n}\n\ntcp_socket &TcpConnection::socket() { return _socket; }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TcpServerConnection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTcpServerConnection::TcpServerConnection(std::shared_ptr<App> app, const Server::Config &config)\n : Connection(app, Config()), TcpConnection(app, Config(config.message_handler())) {\n _path = std::make_shared<Buffer>(config.path());\n}\n\nvoid TcpServerConnection::connect() {\n start_handshake();\n}\n\nvoid TcpServerConnection::start_handshake() {\n \/\/ start timeout timer with handshake timeout specified in config\n _deadline->expires_from_now(boost::posix_time::milliseconds(_config.handshake_timout()));\n _deadline->async_wait(boost::bind(&TcpServerConnection::timeout,\n share_this<TcpServerConnection>(),\n boost::asio::placeholders::error));\n\n \/\/ start listening for f0\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpServerConnection::f0_received, share_this<TcpServerConnection>(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n\n \/\/ prepare and send f1 then make sure it was successful [success_or_close(...)]\n size_t f1_size = load_f1(*_write_buffer);\n boost::asio::async_write(_socket, boost::asio::buffer(_write_buffer->data(), f1_size),\n boost::bind(&TcpServerConnection::success_or_close, share_this<TcpServerConnection>(),\n boost::asio::placeholders::error));\n}\n\nvoid TcpServerConnection::f0_received(const boost::system::error_code &error, size_t bytes_transferred) {\n \/\/ reset timeout\n _deadline->expires_from_now(boost::posix_time::milliseconds(_config.handshake_timout()));\n _deadline->async_wait(boost::bind(&TcpServerConnection::timeout, share_this<TcpServerConnection>(),\n boost::asio::placeholders::error));\n\n if (!error \/* && !destroyed() *\/ && parse_f0(bytes_transferred)) {\n \/\/ start shared_secret computation\n _strand.post(boost::bind(&TcpServerConnection::compute_secret, this));\n\n \/\/ read and goto -> f2_received()\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpServerConnection::f2_received, share_this<TcpServerConnection>(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n}\n\nvoid TcpServerConnection::f2_received(const boost::system::error_code &error, size_t bytes_transferred) {\n \/\/ stop timeout timer\n _deadline->cancel();\n\n if (!error \/* && !destroyed() *\/ && parse_f2(bytes_transferred)) {\n \/\/ setup session now that client session id has been parsed\n if (auto server = _server.lock()) {\n std::string session_id = _session_id->to_string();\n _session = server->session_manager()->get_session(_app->security_context().dsid(), session_id);\n if (_session == nullptr) _session = server->session_manager()->create_session(_app->security_context().dsid());\n } else {\n \/\/ if server no longer exists, connection needs to shutdown\n return;\n }\n\n _session_id = _session->session_id();\n\n \/\/ wait for shared secret computation to finish then send f3\n _strand.post(boost::bind(&TcpServerConnection::send_f3, share_this<TcpServerConnection>()));\n\n \/\/ start session\n _session->set_connection(shared_from_this());\n _session->start();\n }\n}\n\nvoid TcpServerConnection::send_f3() {\n \/\/ send f3\n size_t f3_size = load_f3(*_read_buffer);\n boost::asio::async_write(_socket, boost::asio::buffer(_read_buffer->data(), f3_size),\n boost::bind(&TcpServerConnection::success_or_close, shared_from_this(),\n boost::asio::placeholders::error));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TcpClientConnection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTcpClientConnection::TcpClientConnection(std::shared_ptr<App> app)\n : Connection(app, Config()), TcpConnection(app, Config()) {}\n\nTcpClientConnection::TcpClientConnection(std::shared_ptr<App> app, const Config &config)\n : Connection(app, Config()), TcpConnection(app, config) {}\n\nvoid TcpClientConnection::connect() {\n using tcp = boost::asio::ip::tcp;\n tcp::resolver resolver(_app->io_service());\n tcp::resolver::query query(_config.host(), std::to_string(_config.port()));\n tcp::endpoint endpoint = *resolver.resolve(query);\n _socket.async_connect(*resolver.resolve(query),\n boost::bind(&TcpClientConnection::start_handshake, share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n}\n\nvoid TcpClientConnection::start_handshake(const boost::system::error_code &error) {\n if (error != nullptr) throw std::runtime_error(\"Couldn't connect to specified host\");\n \/\/ start timeout timer\n _deadline->expires_from_now(boost::posix_time::milliseconds(_config.handshake_timout()));\n _deadline->async_wait(boost::bind(&TcpClientConnection::timeout, share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpClientConnection::f1_received,\n share_this<TcpClientConnection>(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n\n size_t f0_size = load_f0(*_write_buffer);\n boost::asio::async_write(_socket, boost::asio::buffer(_write_buffer->data(), f0_size),\n boost::bind(&TcpClientConnection::success_or_close, share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n}\n\nvoid TcpClientConnection::f1_received(const boost::system::error_code &error, size_t bytes_transferred) {\n if (!error \/* && !destroyed() *\/ && parse_f1(bytes_transferred)) {\n \/\/ cancel timer before timeout\n _deadline->expires_from_now(boost::posix_time::milliseconds(_config.handshake_timout()));\n\n \/\/ server should be parsing f0 and waiting for f2 at this point\n \/\/ so we can compute the shared secret synchronously\n compute_secret();\n size_t f2_size = load_f2(*_write_buffer);\n boost::asio::async_write(_socket, boost::asio::buffer(_write_buffer->data(), f2_size),\n boost::bind(&TcpClientConnection::success_or_close,\n share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n\n \/\/ restart timeout timer\n _deadline->async_wait(boost::bind(&TcpClientConnection::timeout, share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpClientConnection::f3_received,\n share_this<TcpClientConnection>(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n}\n\nvoid TcpClientConnection::f3_received(const boost::system::error_code &error, size_t bytes_transferred) {\n \/\/ stop timeout timer\n _deadline->cancel();\n\n if (!error \/* && !destroyed() *\/ && parse_f3(bytes_transferred)) {\n uint8_t *auth = _auth->data(), *other_auth = _other_auth->data();\n for (size_t i = 0; i < AuthLength; ++i)\n if (auth[i] != other_auth[i]) return;\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpClientConnection::read_loop, share_this<TcpClientConnection>(), 0,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n\n \/\/ start standard dsa 1 minute timeout\n reset_standard_deadline_timer();\n }\n}\n\n} \/\/ namespace dsa<commit_msg>fix exception type of tcp_connection<commit_after>#include \"dsa_common.h\"\n\n#include \"tcp_connection.h\"\n\n#include <boost\/bind.hpp>\n\n#include \"session_manager.h\"\n\nnamespace dsa {\n\nTcpConnection::TcpConnection(std::shared_ptr<App> app, const Config &config)\n : Connection(app, config), _socket(app->io_service()), _strand(app->io_service()) {\n}\n\nvoid TcpConnection::close() {\n _socket.cancel();\n _deadline->cancel();\n}\n\nvoid TcpConnection::read_loop(size_t from_prev, const boost::system::error_code &error, size_t bytes_transferred) {\n \/\/ reset deadline timer for each new message\n reset_standard_deadline_timer();\n\n if (!error \/* && !destroyed() *\/) {\n std::cout << std::endl << \"in read loop\" << std::endl;\n\n BufferPtr buf = std::move(_read_buffer);\n _read_buffer.reset(new Buffer());\n\n size_t total_bytes = from_prev + bytes_transferred;\n uint8_t *data = buf->data();\n size_t cur = 0;\n\n while (cur < total_bytes) {\n \/\/ always want full static header instead of just message size to make sure it's a valid message\n if (total_bytes - cur < StaticHeaders::TotalSize) {\n size_t partial_size = total_bytes - cur;\n _read_buffer->assign(&data[cur], partial_size);\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data() + partial_size,\n _read_buffer->capacity() - partial_size),\n boost::bind(&TcpConnection::read_loop, share_this<TcpConnection>(), partial_size,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n return;\n }\n\n StaticHeaders header(&data[cur]);\n if (header.message_size < total_bytes - cur) {\n size_t partial_size = total_bytes - cur;\n\n \/\/ make sure buffer capacity is enough to read full message\n _read_buffer->resize(header.message_size);\n _read_buffer->assign(&data[cur], partial_size);\n\n \/\/ read the rest of the message\n boost::asio::async_read(_socket,\n boost::asio::buffer(_read_buffer->data() + partial_size,\n _read_buffer->capacity() - partial_size),\n boost::bind(&TcpConnection::read_loop, share_this<TcpConnection>(), partial_size,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n return;\n }\n\n \/\/ post job with message buffer\n _app->io_service().post(boost::bind(&TcpConnection::handle_message, shared_from_this(),\n buf->get_shared_buffer(cur, header.message_size)));\n\n cur += header.message_size;\n }\n\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpConnection::read_loop, share_this<TcpConnection>(), 0,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n}\n\nvoid TcpConnection::write_handler(WriteHandler callback, const boost::system::error_code &error) {\n if (!error \/* && !destroyed() *\/) callback();\n}\n\nvoid TcpConnection::write(BufferPtr buf, size_t size, WriteHandler callback) {\n \/\/ check to see if current number of pending messages is above allowed limit\n if (++_pending_messages > _config.max_pending_messages()) {\n close();\n return;\n }\n\n boost::asio::async_write(_socket, boost::asio::buffer(buf->data(), size),\n boost::bind(&TcpConnection::write_handler, share_this<TcpConnection>(), callback,\n boost::asio::placeholders::error));\n}\n\nvoid TcpConnection::start() throw(const std::runtime_error&) {\n if (_session == nullptr)\n throw std::runtime_error(\"Error: connection started with no session\");\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpConnection::read_loop, share_this<TcpConnection>(), 0,\n boost::asio::placeholders::error, 0));\n}\n\ntcp_socket &TcpConnection::socket() { return _socket; }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TcpServerConnection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTcpServerConnection::TcpServerConnection(std::shared_ptr<App> app, const Server::Config &config)\n : Connection(app, Config()), TcpConnection(app, Config(config.message_handler())) {\n _path = std::make_shared<Buffer>(config.path());\n}\n\nvoid TcpServerConnection::connect() {\n start_handshake();\n}\n\nvoid TcpServerConnection::start_handshake() {\n \/\/ start timeout timer with handshake timeout specified in config\n _deadline->expires_from_now(boost::posix_time::milliseconds(_config.handshake_timout()));\n _deadline->async_wait(boost::bind(&TcpServerConnection::timeout,\n share_this<TcpServerConnection>(),\n boost::asio::placeholders::error));\n\n \/\/ start listening for f0\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpServerConnection::f0_received, share_this<TcpServerConnection>(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n\n \/\/ prepare and send f1 then make sure it was successful [success_or_close(...)]\n size_t f1_size = load_f1(*_write_buffer);\n boost::asio::async_write(_socket, boost::asio::buffer(_write_buffer->data(), f1_size),\n boost::bind(&TcpServerConnection::success_or_close, share_this<TcpServerConnection>(),\n boost::asio::placeholders::error));\n}\n\nvoid TcpServerConnection::f0_received(const boost::system::error_code &error, size_t bytes_transferred) {\n \/\/ reset timeout\n _deadline->expires_from_now(boost::posix_time::milliseconds(_config.handshake_timout()));\n _deadline->async_wait(boost::bind(&TcpServerConnection::timeout, share_this<TcpServerConnection>(),\n boost::asio::placeholders::error));\n\n if (!error \/* && !destroyed() *\/ && parse_f0(bytes_transferred)) {\n \/\/ start shared_secret computation\n _strand.post(boost::bind(&TcpServerConnection::compute_secret, this));\n\n \/\/ read and goto -> f2_received()\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpServerConnection::f2_received, share_this<TcpServerConnection>(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n}\n\nvoid TcpServerConnection::f2_received(const boost::system::error_code &error, size_t bytes_transferred) {\n \/\/ stop timeout timer\n _deadline->cancel();\n\n if (!error \/* && !destroyed() *\/ && parse_f2(bytes_transferred)) {\n \/\/ setup session now that client session id has been parsed\n if (auto server = _server.lock()) {\n std::string session_id = _session_id->to_string();\n _session = server->session_manager()->get_session(_app->security_context().dsid(), session_id);\n if (_session == nullptr) _session = server->session_manager()->create_session(_app->security_context().dsid());\n } else {\n \/\/ if server no longer exists, connection needs to shutdown\n return;\n }\n\n _session_id = _session->session_id();\n\n \/\/ wait for shared secret computation to finish then send f3\n _strand.post(boost::bind(&TcpServerConnection::send_f3, share_this<TcpServerConnection>()));\n\n \/\/ start session\n _session->set_connection(shared_from_this());\n _session->start();\n }\n}\n\nvoid TcpServerConnection::send_f3() {\n \/\/ send f3\n size_t f3_size = load_f3(*_read_buffer);\n boost::asio::async_write(_socket, boost::asio::buffer(_read_buffer->data(), f3_size),\n boost::bind(&TcpServerConnection::success_or_close, shared_from_this(),\n boost::asio::placeholders::error));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TcpClientConnection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTcpClientConnection::TcpClientConnection(std::shared_ptr<App> app)\n : Connection(app, Config()), TcpConnection(app, Config()) {}\n\nTcpClientConnection::TcpClientConnection(std::shared_ptr<App> app, const Config &config)\n : Connection(app, Config()), TcpConnection(app, config) {}\n\nvoid TcpClientConnection::connect() {\n using tcp = boost::asio::ip::tcp;\n tcp::resolver resolver(_app->io_service());\n tcp::resolver::query query(_config.host(), std::to_string(_config.port()));\n tcp::endpoint endpoint = *resolver.resolve(query);\n _socket.async_connect(*resolver.resolve(query),\n boost::bind(&TcpClientConnection::start_handshake, share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n}\n\nvoid TcpClientConnection::start_handshake(const boost::system::error_code &error) {\n if (error != nullptr) throw std::runtime_error(\"Couldn't connect to specified host\");\n \/\/ start timeout timer\n _deadline->expires_from_now(boost::posix_time::milliseconds(_config.handshake_timout()));\n _deadline->async_wait(boost::bind(&TcpClientConnection::timeout, share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpClientConnection::f1_received,\n share_this<TcpClientConnection>(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n\n size_t f0_size = load_f0(*_write_buffer);\n boost::asio::async_write(_socket, boost::asio::buffer(_write_buffer->data(), f0_size),\n boost::bind(&TcpClientConnection::success_or_close, share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n}\n\nvoid TcpClientConnection::f1_received(const boost::system::error_code &error, size_t bytes_transferred) {\n if (!error \/* && !destroyed() *\/ && parse_f1(bytes_transferred)) {\n \/\/ cancel timer before timeout\n _deadline->expires_from_now(boost::posix_time::milliseconds(_config.handshake_timout()));\n\n \/\/ server should be parsing f0 and waiting for f2 at this point\n \/\/ so we can compute the shared secret synchronously\n compute_secret();\n size_t f2_size = load_f2(*_write_buffer);\n boost::asio::async_write(_socket, boost::asio::buffer(_write_buffer->data(), f2_size),\n boost::bind(&TcpClientConnection::success_or_close,\n share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n\n \/\/ restart timeout timer\n _deadline->async_wait(boost::bind(&TcpClientConnection::timeout, share_this<TcpClientConnection>(),\n boost::asio::placeholders::error));\n\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpClientConnection::f3_received,\n share_this<TcpClientConnection>(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n}\n\nvoid TcpClientConnection::f3_received(const boost::system::error_code &error, size_t bytes_transferred) {\n \/\/ stop timeout timer\n _deadline->cancel();\n\n if (!error \/* && !destroyed() *\/ && parse_f3(bytes_transferred)) {\n uint8_t *auth = _auth->data(), *other_auth = _other_auth->data();\n for (size_t i = 0; i < AuthLength; ++i)\n if (auth[i] != other_auth[i]) return;\n _socket.async_read_some(boost::asio::buffer(_read_buffer->data(), _read_buffer->capacity()),\n boost::bind(&TcpClientConnection::read_loop, share_this<TcpClientConnection>(), 0,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n\n \/\/ start standard dsa 1 minute timeout\n reset_standard_deadline_timer();\n }\n}\n\n} \/\/ namespace dsa<|endoftext|>"} {"text":"<commit_before>#include \"sequential_trim_simulator.h\"\n\nSequential_Trim_Simulator::Sequential_Trim_Simulator(std::vector<Command*>& commands, int maxparallelops):Simulator(commands, maxparallelops)\t{\n\n}\n\nSequential_Trim_Simulator::~Sequential_Trim_Simulator()\t{\n\tcommandPtr = NULL;\n}\n\nvoid Sequential_Trim_Simulator::startSimulation(double readProcessTime, double writeProcessTime, double trimProcessTime)\t{\n\tint commandCounter = 0;\n\t\n\t\/\/ bool driverBusy = false;\n\n\t\/\/ start simulation\n\twhile(1)\t{\n\t\t\/\/ if there are command that has not been issue yet\n\t\tif(commandCounter < commandPtr->size())\t{\n\t\t\tCommand* nextCommand = commandPtr->at(commandCounter);\n\t\t\tif(nextCommand->getIssueTime() <= clock)\t{\n\t\t\t\t\/\/ put the command in to queue\n\t\t\t\tif(nextCommand->getType() == TRIM_COMMAND)\t{\n\t\t\t\t\ttrimQueue.push((Trim_Command*)nextCommand);\n\t\t\t\t}\n\t\t\t\telse\t{\n\t\t\t\t\tioQueue.push((IO_Command*)nextCommand);\n\t\t\t\t}\n\t\t\t\t\/\/ move on to the next command\n\t\t\t\tcommandCounter++;\n\t\t\t}\n\t\t}\n\t\tadvanceDriverBusyTime();\n\t\t\/\/ check if simulator can execute any command\n\t\tif(!availableDriverSlot.empty())\t{\n\t\t\t\/\/ while there are available slot, and there are commands in the queue\n\t\t\twhile(!availableDriverSlot.empty() && (!trimQueue.empty() || !ioQueue.empty()))\t{\n\n\t\t\t\t\/\/ get the index of driver slot\n\t\t\t\tint driverSlotIndex = availableDriverSlot.front();\n\t\t\t\n\t\t\t\t\/\/ now check to see which command should be serve first\n\t\t\t\tTrim_Command* nextTrimCommand = NULL;\n\t\t\t\tIO_Command* nextIOCommand = NULL;\n\t\t\t\t\/\/ check both queue, see which one is not empty\n\t\t\t\tif(!trimQueue.empty())\t{\n\t\t\t\t\tnextTrimCommand = trimQueue.front();\n\t\t\t\t}\n\t\t\t\tif(!ioQueue.empty())\t{\n\t\t\t\t\tnextIOCommand = ioQueue.front();\n\t\t\t\t}\n\n\t\t\t\t\/\/ printf(\"%.9lf\\n\", clock);\n\t\t\t\t\/\/ std::cout<<\" \"<<availableDriverSlot.size()<<\" \"<<currentServingType<<\" \"<<trimQueue.size()<<\" \"<<ioQueue.size()<<\"\\n\";\n\n\t\t\t\tdouble servicesTime = 0.0;\n\t\t\t\t\/\/ if both there are command from either queue\n\t\t\t\tif(nextTrimCommand != NULL && nextIOCommand != NULL)\t{\n\t\t\t\t\tdouble timeDiff = nextIOCommand->getIssueTime() - nextTrimCommand->getIssueTime();\n\t\t\t\t\tif(currentServingType == ANY_COMMAND)\t{\n\t\t\t\t\t\t\/\/ TRIM\n\t\t\t\t\t\tif(timeDiff > 0)\t{\n\t\t\t\t\t\t\t\/\/ execute the command\n\t\t\t\t\t\t\tservicesTime = trimProcessTime;\n\t\t\t\t\t\t\t\/\/ pop it from the queue\n\t\t\t\t\t\t\ttrimQueue.pop();\n\t\t\t\t\t\t\tcurrentServingType = TRIM_COMMAND;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ Normal IO\n\t\t\t\t\t\telse\t{\n\t\t\t\t\t\t\t\/\/ set the driver busy time\n\t\t\t\t\t\t\tservicesTime = (nextIOCommand->getType() == WRITE_COMMAND)?writeProcessTime:readProcessTime;\n\t\t\t\t\t\t\t\/\/ pop the command off ioQueue\n\t\t\t\t\t\t\tioQueue.pop();\n\t\t\t\t\t\t\tcurrentServingType = IO_COMMAND;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(currentServingType == TRIM_COMMAND)\t{\n\t\t\t\t\t\tif(timeDiff > 0)\t{\n\t\t\t\t\t\t\t\/\/ execute the command\n\t\t\t\t\t\t\tservicesTime = trimProcessTime;\n\t\t\t\t\t\t\t\/\/ pop it from the queue\n\t\t\t\t\t\t\ttrimQueue.pop();\n\t\t\t\t\t\t\tcurrentServingType = TRIM_COMMAND;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(currentServingType == IO_COMMAND)\t{\n\t\t\t\t\t\tif(timeDiff < 0)\t{\n\t\t\t\t\t\t\t\/\/ set the driver busy time\n\t\t\t\t\t\t\tservicesTime = (nextIOCommand->getType() == WRITE_COMMAND)?writeProcessTime:readProcessTime;\n\t\t\t\t\t\t\t\/\/ pop the command off ioQueue\n\t\t\t\t\t\t\tioQueue.pop();\n\t\t\t\t\t\t\tcurrentServingType = IO_COMMAND;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ if there is some trim command in trim queue\n\t\t\t\telse if(nextTrimCommand != NULL)\t{\n\t\t\t\t\tif(currentServingType == TRIM_COMMAND || currentServingType == ANY_COMMAND)\t{\n\t\t\t\t\t\t\/\/ execute the command\n\t\t\t\t\t\tservicesTime = trimProcessTime;\n\t\t\t\t\t\t\/\/ pop it from the queue\n\t\t\t\t\t\ttrimQueue.pop();\n\t\t\t\t\t\tcurrentServingType = TRIM_COMMAND;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ if there is some trim command in io queue\n\t\t\t\telse if(nextIOCommand != NULL)\t{\n\t\t\t\t\tif(currentServingType == IO_COMMAND || currentServingType == ANY_COMMAND)\t{\n\t\t\t\t\t\tservicesTime = (nextIOCommand->getType() == WRITE_COMMAND)?writeProcessTime:readProcessTime;\n\t\t\t\t\t\t\/\/ pop the command off ioQueue\n\t\t\t\t\t\tioQueue.pop();\n\t\t\t\t\t\tcurrentServingType = IO_COMMAND;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ set the slot with services time\n\t\t\t\tif(servicesTime > 0.0)\t{\n\t\t\t\t\tsetDriverBusyTimer(driverSlotIndex, servicesTime);\n\t\t\t\t\t\/\/ pop it off the queue\n\t\t\t\t\tavailableDriverSlot.pop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\t{\n\t\t\ttotalBlockingTime += CLOCK_SPEED;\n\t\t\t\/\/ driverBusyTime -= CLOCK_SPEED;\t\n\t\t}\n\t\tif (allCompleted()) {\n\t\t\tcurrentServingType = ANY_COMMAND;\n\t\t\t\/\/printf(\"all completed at: %.9lf, totalBusyTime: %.9lf\\n\", clock, totalBlockingTime);\n\t\t}\n\n\t\t\/\/ std::cout<<driverBusy<<\" \"<<driverBusyTime<<\"\\n\";\n\t\tif((commandCounter == commandPtr->size()) && trimQueue.empty() && ioQueue.empty() && allCompleted())\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tadvanceClock();\n\t}\n\n\tstd::cout << \"System was blocking \"<< totalBlockingTime \/clock * 100<<\"% of time\\n\";\n\tstd::cout << \"System was prcessing IO \" << totalIOTime \/ clock * 100 << \"% of time\\n\";\n\tstd::cout << \"System was processing TRIM \" << totalTrimTime \/ clock * 100 << \"% of time\\n\";\n}<commit_msg>testing<commit_after>#include \"sequential_trim_simulator.h\"\n\nSequential_Trim_Simulator::Sequential_Trim_Simulator(std::vector<Command*>& commands, int maxparallelops):Simulator(commands, maxparallelops)\t{\n\n}\n\nSequential_Trim_Simulator::~Sequential_Trim_Simulator()\t{\n\tcommandPtr = NULL;\n}\n\nvoid Sequential_Trim_Simulator::startSimulation(double readProcessTime, double writeProcessTime, double trimProcessTime)\t{\n\tint commandCounter = 0;\n\t\n\t\/\/ bool driverBusy = false;\n\t\/\/test\n\n\t\/\/ start simulation\n\twhile(1)\t{\n\t\t\/\/ if there are command that has not been issue yet\n\t\tif(commandCounter < commandPtr->size())\t{\n\t\t\tCommand* nextCommand = commandPtr->at(commandCounter);\n\t\t\tif(nextCommand->getIssueTime() <= clock)\t{\n\t\t\t\t\/\/ put the command in to queue\n\t\t\t\tif(nextCommand->getType() == TRIM_COMMAND)\t{\n\t\t\t\t\ttrimQueue.push((Trim_Command*)nextCommand);\n\t\t\t\t}\n\t\t\t\telse\t{\n\t\t\t\t\tioQueue.push((IO_Command*)nextCommand);\n\t\t\t\t}\n\t\t\t\t\/\/ move on to the next command\n\t\t\t\tcommandCounter++;\n\t\t\t}\n\t\t}\n\t\tadvanceDriverBusyTime();\n\t\t\/\/ check if simulator can execute any command\n\t\tif(!availableDriverSlot.empty())\t{\n\t\t\t\/\/ while there are available slot, and there are commands in the queue\n\t\t\twhile(!availableDriverSlot.empty() && (!trimQueue.empty() || !ioQueue.empty()))\t{\n\n\t\t\t\t\/\/ get the index of driver slot\n\t\t\t\tint driverSlotIndex = availableDriverSlot.front();\n\t\t\t\n\t\t\t\t\/\/ now check to see which command should be serve first\n\t\t\t\tTrim_Command* nextTrimCommand = NULL;\n\t\t\t\tIO_Command* nextIOCommand = NULL;\n\t\t\t\t\/\/ check both queue, see which one is not empty\n\t\t\t\tif(!trimQueue.empty())\t{\n\t\t\t\t\tnextTrimCommand = trimQueue.front();\n\t\t\t\t}\n\t\t\t\tif(!ioQueue.empty())\t{\n\t\t\t\t\tnextIOCommand = ioQueue.front();\n\t\t\t\t}\n\n\t\t\t\t\/\/ printf(\"%.9lf\\n\", clock);\n\t\t\t\t\/\/ std::cout<<\" \"<<availableDriverSlot.size()<<\" \"<<currentServingType<<\" \"<<trimQueue.size()<<\" \"<<ioQueue.size()<<\"\\n\";\n\n\t\t\t\tdouble servicesTime = 0.0;\n\t\t\t\t\/\/ if both there are command from either queue\n\t\t\t\tif(nextTrimCommand != NULL && nextIOCommand != NULL)\t{\n\t\t\t\t\tdouble timeDiff = nextIOCommand->getIssueTime() - nextTrimCommand->getIssueTime();\n\t\t\t\t\tif(currentServingType == ANY_COMMAND)\t{\n\t\t\t\t\t\t\/\/ TRIM\n\t\t\t\t\t\tif(timeDiff > 0)\t{\n\t\t\t\t\t\t\t\/\/ execute the command\n\t\t\t\t\t\t\tservicesTime = trimProcessTime;\n\t\t\t\t\t\t\t\/\/ pop it from the queue\n\t\t\t\t\t\t\ttrimQueue.pop();\n\t\t\t\t\t\t\tcurrentServingType = TRIM_COMMAND;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ Normal IO\n\t\t\t\t\t\telse\t{\n\t\t\t\t\t\t\t\/\/ set the driver busy time\n\t\t\t\t\t\t\tservicesTime = (nextIOCommand->getType() == WRITE_COMMAND)?writeProcessTime:readProcessTime;\n\t\t\t\t\t\t\t\/\/ pop the command off ioQueue\n\t\t\t\t\t\t\tioQueue.pop();\n\t\t\t\t\t\t\tcurrentServingType = IO_COMMAND;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(currentServingType == TRIM_COMMAND)\t{\n\t\t\t\t\t\tif(timeDiff > 0)\t{\n\t\t\t\t\t\t\t\/\/ execute the command\n\t\t\t\t\t\t\tservicesTime = trimProcessTime;\n\t\t\t\t\t\t\t\/\/ pop it from the queue\n\t\t\t\t\t\t\ttrimQueue.pop();\n\t\t\t\t\t\t\tcurrentServingType = TRIM_COMMAND;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(currentServingType == IO_COMMAND)\t{\n\t\t\t\t\t\tif(timeDiff < 0)\t{\n\t\t\t\t\t\t\t\/\/ set the driver busy time\n\t\t\t\t\t\t\tservicesTime = (nextIOCommand->getType() == WRITE_COMMAND)?writeProcessTime:readProcessTime;\n\t\t\t\t\t\t\t\/\/ pop the command off ioQueue\n\t\t\t\t\t\t\tioQueue.pop();\n\t\t\t\t\t\t\tcurrentServingType = IO_COMMAND;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ if there is some trim command in trim queue\n\t\t\t\telse if(nextTrimCommand != NULL)\t{\n\t\t\t\t\tif(currentServingType == TRIM_COMMAND || currentServingType == ANY_COMMAND)\t{\n\t\t\t\t\t\t\/\/ execute the command\n\t\t\t\t\t\tservicesTime = trimProcessTime;\n\t\t\t\t\t\t\/\/ pop it from the queue\n\t\t\t\t\t\ttrimQueue.pop();\n\t\t\t\t\t\tcurrentServingType = TRIM_COMMAND;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ if there is some trim command in io queue\n\t\t\t\telse if(nextIOCommand != NULL)\t{\n\t\t\t\t\tif(currentServingType == IO_COMMAND || currentServingType == ANY_COMMAND)\t{\n\t\t\t\t\t\tservicesTime = (nextIOCommand->getType() == WRITE_COMMAND)?writeProcessTime:readProcessTime;\n\t\t\t\t\t\t\/\/ pop the command off ioQueue\n\t\t\t\t\t\tioQueue.pop();\n\t\t\t\t\t\tcurrentServingType = IO_COMMAND;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ set the slot with services time\n\t\t\t\tif(servicesTime > 0.0)\t{\n\t\t\t\t\tsetDriverBusyTimer(driverSlotIndex, servicesTime);\n\t\t\t\t\t\/\/ pop it off the queue\n\t\t\t\t\tavailableDriverSlot.pop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\t{\n\t\t\ttotalBlockingTime += CLOCK_SPEED;\n\t\t\t\/\/ driverBusyTime -= CLOCK_SPEED;\t\n\t\t}\n\t\tif (allCompleted()) {\n\t\t\tcurrentServingType = ANY_COMMAND;\n\t\t\t\/\/printf(\"all completed at: %.9lf, totalBusyTime: %.9lf\\n\", clock, totalBlockingTime);\n\t\t}\n\n\t\t\/\/ std::cout<<driverBusy<<\" \"<<driverBusyTime<<\"\\n\";\n\t\tif((commandCounter == commandPtr->size()) && trimQueue.empty() && ioQueue.empty() && allCompleted())\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tadvanceClock();\n\t}\n\n\tstd::cout << \"System was blocking \"<< totalBlockingTime \/clock * 100<<\"% of time\\n\";\n\tstd::cout << \"System was prcessing IO \" << totalIOTime \/ clock * 100 << \"% of time\\n\";\n\tstd::cout << \"System was processing TRIM \" << totalTrimTime \/ clock * 100 << \"% of time\\n\";\n}<|endoftext|>"} {"text":"<commit_before>#ifndef ARDUINO\n\/*\n * CONTROLS:\n *\n * NW - Q\n * SW - A\n * NE - P\n * SE - L\n *\n * LEFT - <LEFT>\n * RIGHT - <RIGHT>\n * UP - <UP>\n * DOWN - <DOWN>\n * A - X\n * B - Z\n * SELECT - ,\n * START - .\n *\n *\/\n\n\n\n\n#include <SFML\/Graphics.hpp>\n#include <stdint.h>\n#include <libgame.h>\n#include <sprite.h>\n#include <font.h>\n#include <storage.h>\n\nconst int SCALE = 8;\n\nsf::VertexArray *screen;\nsf::RenderWindow *window;\nsf::Clock running_clock;\n\nuint16_t buttons = 0;\n\nbool paused = false;\n\nvoid render();\nvoid update(unsigned long delta);\nvoid prepare();\n\nunsigned long millis()\n{\n return running_clock.getElapsedTime().asMilliseconds();\n}\n\n\nvoid storage_init() {}\nvoid storage_format() {}\n\nvoid storage_read(const char *name, void *buffer, size_t size){};\nbool storage_write(const char *name, const void *buffer, size_t size){return 0;};\n\nuint8_t game_sprite_width(const struct game_sprite *s)\n{\n return s->width;\n}\n\nuint8_t game_sprite_height(const struct game_sprite *s)\n{\n return s->height;\n}\n\nvoid game_draw_pixel(int x, int y, uint8_t c)\n{\n if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)\n return;\n int pos = 4 * (x * WIDTH + y);\n sf::Color color(((c >> 4) & 3) * 85, ((c >> 2) & 3) * 85, (c & 3) * 85);\n (*screen)[pos + 0].color = color;\n (*screen)[pos + 1].color = color;\n (*screen)[pos + 2].color = color;\n (*screen)[pos + 3].color = color;\n}\n\nvoid game_draw_vline(int x, int y1, int y2, uint8_t color)\n{\n for (int i = y1 ; i <= y2 ; ++i)\n game_draw_pixel(x, i, color);\n}\n\nvoid clear_screen()\n{\n for (int x = 0; x < HEIGHT; ++x)\n {\n for (int y = 0; y < WIDTH; ++y)\n {\n game_draw_pixel(x, y, BLACK);\n }\n }\n}\n\nbool game_is_button_pressed(uint8_t button)\n{\n return (buttons >> button) & 1;\n}\n\nbool game_is_any_button_pressed(uint16_t bitmask)\n{\n return buttons & bitmask;\n}\n\nvoid set_pressed(uint8_t button, bool pressed)\n{\n if (pressed)\n {\n buttons |= (1 << button);\n }\n else\n {\n buttons &= ~(1 << button);\n }\n}\n\nvoid game_setup()\n{\n screen = new sf::VertexArray(sf::Quads, WIDTH * HEIGHT * 4);\n for (int x = 0; x < WIDTH; ++x)\n {\n for (int y = 0; y < HEIGHT; ++y)\n {\n int pos = 4 * (x * HEIGHT + y);\n (*screen)[pos + 0].position = sf::Vector2f(x * SCALE, y * SCALE);\n (*screen)[pos + 1].position = sf::Vector2f((x + 1) * SCALE, y * SCALE);\n (*screen)[pos + 2].position = sf::Vector2f((x + 1) * SCALE, (y + 1) * SCALE);\n (*screen)[pos + 3].position = sf::Vector2f(x * SCALE, (y + 1) * SCALE);\n game_draw_pixel(x, y, BLACK);\n }\n }\n window = new sf::RenderWindow(sf::VideoMode(SCALE * WIDTH, SCALE * HEIGHT), \"emulator\", sf::Style::Close);\n}\n\nvoid game_set_ups(int ups)\n{\n if (ups)\n window->setFramerateLimit(ups);\n else\n window->setFramerateLimit(30);\n}\n\nvoid game_draw_sprite(const struct game_sprite *s, int x, int y, uint8_t color)\n{\n for (int dx = 0; dx < s->width; ++dx)\n {\n for (int dy = 0; dy < s->height; ++dy)\n {\n int xx = x + dx;\n int yy = y + dy;\n if (xx < 0 || xx >= WIDTH || yy < 0 || yy >= HEIGHT)\n continue;\n int byte = s->lineSize * dy + dx \/ 8;\n int bit = 7 - dx % 8;\n if ((s->lines[byte] >> bit) & 1)\n game_draw_pixel(xx, yy, color);\n }\n }\n}\n\nvoid game_draw_text(const uint8_t *s, int x, int y, uint8_t color)\n{\n int xx = x;\n int yy = y;\n for (const uint8_t *c = s; *c; ++c)\n {\n game_draw_char(*c, xx, yy, color);\n xx += FONT_WIDTH + 1;\n }\n}\n\nvoid game_draw_char(uint8_t c, int x, int y, uint8_t color)\n{\n int pos = (int)c * FONT_HEIGHT;\n for (int i = 0; i < FONT_WIDTH; ++i)\n {\n for (int j = 0; j < FONT_HEIGHT; ++j)\n {\n uint8_t d = font_data[pos + j];\n if ((d >> (FONT_WIDTH - 1 - i)) & 1)\n game_draw_pixel(x + i, y + j, color);\n }\n }\n}\n\nint main()\n{\n prepare();\n running_clock.restart();\n sf::Clock elapsed;\n while (window->isOpen())\n {\n elapsed.restart();\n sf::Event event;\n while (window->pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n {\n window->close();\n }\n if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased)\n {\n bool status = event.type == sf::Event::KeyPressed;\n if (event.key.code == sf::Keyboard::Q) set_pressed(BUTTON_NW, status);\n if (event.key.code == sf::Keyboard::A) set_pressed(BUTTON_SW, status);\n if (event.key.code == sf::Keyboard::P) set_pressed(BUTTON_NE, status);\n if (event.key.code == sf::Keyboard::L) set_pressed(BUTTON_SE, status);\n\n if (event.key.code == sf::Keyboard::Left) set_pressed(BUTTON_LEFT, status);\n if (event.key.code == sf::Keyboard::Right) set_pressed(BUTTON_RIGHT, status);\n if (event.key.code == sf::Keyboard::Up) set_pressed(BUTTON_UP, status);\n if (event.key.code == sf::Keyboard::Down) set_pressed(BUTTON_DOWN, status);\n if (event.key.code == sf::Keyboard::X) set_pressed(BUTTON_A, status);\n if (event.key.code == sf::Keyboard::Z) set_pressed(BUTTON_B, status);\n if (event.key.code == sf::Keyboard::Comma) set_pressed(BUTTON_SELECT, status);\n if (event.key.code == sf::Keyboard::Period) set_pressed(BUTTON_START, status);\n \n if (status && event.key.code == sf::Keyboard::Space) paused = !paused;\n if (status && event.key.code == sf::Keyboard::Escape) window->close();\n }\n }\n\n window->clear(sf::Color::Black);\n window->draw(*screen);\n window->display();\n\n if (!paused)\n {\n update(elapsed.getElapsedTime().asMilliseconds());\n clear_screen();\n render();\n }\n }\n\n return 0;\n}\n#endif\n<commit_msg>Fixed emulator<commit_after>#ifndef ARDUINO\n\/*\n * CONTROLS:\n *\n * NW - Q\n * SW - A\n * NE - P\n * SE - L\n *\n * LEFT - <LEFT>\n * RIGHT - <RIGHT>\n * UP - <UP>\n * DOWN - <DOWN>\n * A - X\n * B - Z\n * SELECT - ,\n * START - .\n *\n *\/\n\n\n\n\n#include <SFML\/Graphics.hpp>\n#include <stdint.h>\n#include <libgame.h>\n#include \"graphics.h\"\n#include \"controls.h\"\n#include \"font.h\"\n#include \"storage.h\"\n#include \"font_data.h\"\n\nconst int SCALE = 8;\n\nsf::VertexArray *screen;\nsf::RenderWindow *window;\nsf::Clock running_clock;\n\nuint16_t buttons = 0;\n\nbool paused = false;\n\nvoid render();\nvoid update(unsigned long delta);\nvoid prepare();\n\nunsigned long millis()\n{\n return running_clock.getElapsedTime().asMilliseconds();\n}\n\n\nvoid storage_init() {}\nvoid storage_format() {}\n\nvoid storage_read(const char *name, void *buffer, size_t size){};\nbool storage_write(const char *name, const void *buffer, size_t size){return 0;};\n\nuint8_t game_sprite_width(const struct game_sprite *s)\n{\n return s->width;\n}\n\nuint8_t game_sprite_height(const struct game_sprite *s)\n{\n return s->height;\n}\n\nvoid game_draw_pixel(int x, int y, uint8_t c)\n{\n if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)\n return;\n int pos = 4 * (x * WIDTH + y);\n sf::Color color(((c >> 4) & 3) * 85, ((c >> 2) & 3) * 85, (c & 3) * 85);\n (*screen)[pos + 0].color = color;\n (*screen)[pos + 1].color = color;\n (*screen)[pos + 2].color = color;\n (*screen)[pos + 3].color = color;\n}\n\nvoid game_draw_vline(int x, int y1, int y2, uint8_t color)\n{\n for (int i = y1 ; i <= y2 ; ++i)\n game_draw_pixel(x, i, color);\n}\n\nvoid clear_screen()\n{\n for (int x = 0; x < HEIGHT; ++x)\n {\n for (int y = 0; y < WIDTH; ++y)\n {\n game_draw_pixel(x, y, BLACK);\n }\n }\n}\n\nbool game_is_button_pressed(uint8_t button)\n{\n return (buttons >> button) & 1;\n}\n\nbool game_is_any_button_pressed(uint16_t bitmask)\n{\n return buttons & bitmask;\n}\n\nvoid set_pressed(uint8_t button, bool pressed)\n{\n if (pressed)\n {\n buttons |= (1 << button);\n }\n else\n {\n buttons &= ~(1 << button);\n }\n}\n\nvoid game_setup()\n{\n screen = new sf::VertexArray(sf::Quads, WIDTH * HEIGHT * 4);\n for (int x = 0; x < WIDTH; ++x)\n {\n for (int y = 0; y < HEIGHT; ++y)\n {\n int pos = 4 * (x * HEIGHT + y);\n (*screen)[pos + 0].position = sf::Vector2f(x * SCALE, y * SCALE);\n (*screen)[pos + 1].position = sf::Vector2f((x + 1) * SCALE, y * SCALE);\n (*screen)[pos + 2].position = sf::Vector2f((x + 1) * SCALE, (y + 1) * SCALE);\n (*screen)[pos + 3].position = sf::Vector2f(x * SCALE, (y + 1) * SCALE);\n game_draw_pixel(x, y, BLACK);\n }\n }\n window = new sf::RenderWindow(sf::VideoMode(SCALE * WIDTH, SCALE * HEIGHT), \"emulator\", sf::Style::Close);\n}\n\nvoid game_set_ups(int ups)\n{\n if (ups)\n window->setFramerateLimit(ups);\n else\n window->setFramerateLimit(30);\n}\n\nvoid game_draw_sprite(const struct game_sprite *s, int x, int y, uint8_t color)\n{\n for (int dx = 0; dx < s->width; ++dx)\n {\n for (int dy = 0; dy < s->height; ++dy)\n {\n int xx = x + dx;\n int yy = y + dy;\n if (xx < 0 || xx >= WIDTH || yy < 0 || yy >= HEIGHT)\n continue;\n int byte = s->lineSize * dy + dx \/ 8;\n int bit = 7 - dx % 8;\n if ((s->lines[byte] >> bit) & 1)\n game_draw_pixel(xx, yy, color);\n }\n }\n}\n\nvoid game_draw_text(const uint8_t *s, int x, int y, uint8_t color)\n{\n int xx = x;\n int yy = y;\n for (const uint8_t *c = s; *c; ++c)\n {\n game_draw_char(*c, xx, yy, color);\n xx += FONT_WIDTH + 1;\n }\n}\n\nvoid game_draw_char(uint8_t c, int x, int y, uint8_t color)\n{\n int pos = (int)c * FONT_HEIGHT;\n for (int i = 0; i < FONT_WIDTH; ++i)\n {\n for (int j = 0; j < FONT_HEIGHT; ++j)\n {\n uint8_t d = font_data[pos + j];\n if ((d >> (FONT_WIDTH - 1 - i)) & 1)\n game_draw_pixel(x + i, y + j, color);\n }\n }\n}\n\nvoid game_draw_digits(uint16_t num, int len, int x, int y, uint8_t color)\n{\n x += (len - 1) * (DIGIT_WIDTH + 1);\n for (int i = len - 1 ; i >= 0 ; --i, x -= DIGIT_WIDTH + 1)\n {\n uint8_t d = num % 10;\n num \/= 10;\n for (int8_t dy = 0 ; dy < DIGIT_HEIGHT ; ++dy)\n {\n uint8_t dd = digits_data[d * DIGIT_HEIGHT + dy];\n for (int b = 0 ; b < DIGIT_WIDTH ; ++b)\n {\n if ((dd >> (DIGIT_WIDTH - 1 - b)) & 1)\n game_draw_pixel(x + b, y + dy, color);\n }\n }\n }\n}\n\nint main()\n{\n game_setup();\n running_clock.restart();\n sf::Clock elapsed;\n while (window->isOpen())\n {\n elapsed.restart();\n sf::Event event;\n while (window->pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n {\n window->close();\n }\n if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased)\n {\n bool status = event.type == sf::Event::KeyPressed;\n if (event.key.code == sf::Keyboard::Q) set_pressed(BUTTON_NW, status);\n if (event.key.code == sf::Keyboard::A) set_pressed(BUTTON_SW, status);\n if (event.key.code == sf::Keyboard::P) set_pressed(BUTTON_NE, status);\n if (event.key.code == sf::Keyboard::L) set_pressed(BUTTON_SE, status);\n\n if (event.key.code == sf::Keyboard::Left) set_pressed(BUTTON_LEFT, status);\n if (event.key.code == sf::Keyboard::Right) set_pressed(BUTTON_RIGHT, status);\n if (event.key.code == sf::Keyboard::Up) set_pressed(BUTTON_UP, status);\n if (event.key.code == sf::Keyboard::Down) set_pressed(BUTTON_DOWN, status);\n if (event.key.code == sf::Keyboard::X) set_pressed(BUTTON_A, status);\n if (event.key.code == sf::Keyboard::Z) set_pressed(BUTTON_B, status);\n if (event.key.code == sf::Keyboard::Comma) set_pressed(BUTTON_SELECT, status);\n if (event.key.code == sf::Keyboard::Period) set_pressed(BUTTON_START, status);\n \n if (status && event.key.code == sf::Keyboard::Space) paused = !paused;\n if (status && event.key.code == sf::Keyboard::Escape) window->close();\n }\n }\n\n window->clear(sf::Color::Black);\n window->draw(*screen);\n window->display();\n\n if (!paused)\n {\n update(elapsed.getElapsedTime().asMilliseconds());\n clear_screen();\n render();\n }\n }\n\n return 0;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- AnalyzerOptions.cpp - Analysis Engine Options -----------*- C++ -*-===\/\/\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\/\/ This file contains special accessors for analyzer configuration options\n\/\/ with string representations.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/StaticAnalyzer\/Core\/AnalyzerOptions.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n\nusing namespace clang;\nusing namespace llvm;\n\nbool\nAnalyzerOptions::mayInlineCXXMemberFunction(CXXInlineableMemberKind K) const {\n if (IPAMode < Inlining)\n return false;\n\n if (!CXXMemberInliningMode) {\n static const char *ModeKey = \"c++-inlining\";\n std::string ModeStr = Config.lookup(ModeKey);\n\n CXXInlineableMemberKind &MutableMode =\n const_cast<CXXInlineableMemberKind &>(CXXMemberInliningMode);\n\n MutableMode = llvm::StringSwitch<CXXInlineableMemberKind>(ModeStr)\n .Case(\"\", CIMK_MemberFunctions)\n .Case(\"constructors\", CIMK_Constructors)\n .Case(\"destructors\", CIMK_Destructors)\n .Case(\"none\", CIMK_None)\n .Case(\"methods\", CIMK_MemberFunctions)\n .Default(CXXInlineableMemberKind());\n\n if (!MutableMode) {\n \/\/ FIXME: We should emit a warning here about an unknown inlining kind,\n \/\/ but the AnalyzerOptions doesn't have access to a diagnostic engine.\n MutableMode = CIMK_None;\n }\n }\n\n return CXXMemberInliningMode >= K;\n}\n\nbool AnalyzerOptions::getBooleanOption(StringRef Name, bool DefaultVal) const {\n \/\/ FIXME: We should emit a warning here if the value is something other than\n \/\/ \"true\", \"false\", or the empty string (meaning the default value),\n \/\/ but the AnalyzerOptions doesn't have access to a diagnostic engine.\n return llvm::StringSwitch<bool>(Config.lookup(Name))\n .Case(\"true\", true)\n .Case(\"false\", false)\n .Default(DefaultVal);\n}\n\nbool AnalyzerOptions::includeTemporaryDtorsInCFG() const {\n if (!IncludeTemporaryDtorsInCFG.hasValue())\n const_cast<llvm::Optional<bool> &>(IncludeTemporaryDtorsInCFG) =\n getBooleanOption(\"cfg-temporary-dtors\", \/*Default=*\/false);\n \n return *IncludeTemporaryDtorsInCFG;\n}\n\nbool AnalyzerOptions::mayInlineCXXStandardLibrary() const {\n if (!InlineCXXStandardLibrary.hasValue())\n const_cast<llvm::Optional<bool> &>(InlineCXXStandardLibrary) =\n getBooleanOption(\"c++-stdlib-inlining\", \/*Default=*\/true);\n \n return *InlineCXXStandardLibrary;\n}\n\nbool AnalyzerOptions::mayInlineTemplateFunctions() const {\n if (!InlineTemplateFunctions.hasValue())\n const_cast<llvm::Optional<bool> &>(InlineTemplateFunctions) =\n getBooleanOption(\"c++-template-inlining\", \/*Default=*\/true);\n \n return *InlineTemplateFunctions;\n}\n\nbool AnalyzerOptions::mayInlineObjCMethod() const {\n if (!ObjCInliningMode.hasValue())\n const_cast<llvm::Optional<bool> &>(ObjCInliningMode) =\n getBooleanOption(\"objc-inlining\", \/*Default=*\/true);\n\n return *ObjCInliningMode;\n}\n\nint AnalyzerOptions::getOptionAsInteger(StringRef Name, int DefaultVal) const {\n std::string OptStr = Config.lookup(Name);\n if (OptStr.empty())\n return DefaultVal;\n\n int Res = DefaultVal;\n assert(StringRef(OptStr).getAsInteger(10, Res) == false &&\n \"analyzer-config option should be numeric.\");\n\n return Res;\n}\n\nunsigned AnalyzerOptions::getAlwaysInlineSize() const {\n if (!AlwaysInlineSize.hasValue()) {\n unsigned DefaultSize = 3;\n const_cast<Optional<unsigned> &>(AlwaysInlineSize) =\n getOptionAsInteger(\"ipa-always-inline-size\", DefaultSize);\n }\n\n return AlwaysInlineSize.getValue();\n}\n\nbool AnalyzerOptions::shouldSynthesizeBodies() const {\n return getBooleanOption(\"faux-bodies\", false);\n}\n<commit_msg>Flip \"faux-bodies\" in the analyzer on by default to flush out bugs.<commit_after>\/\/===-- AnalyzerOptions.cpp - Analysis Engine Options -----------*- C++ -*-===\/\/\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\/\/ This file contains special accessors for analyzer configuration options\n\/\/ with string representations.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/StaticAnalyzer\/Core\/AnalyzerOptions.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n\nusing namespace clang;\nusing namespace llvm;\n\nbool\nAnalyzerOptions::mayInlineCXXMemberFunction(CXXInlineableMemberKind K) const {\n if (IPAMode < Inlining)\n return false;\n\n if (!CXXMemberInliningMode) {\n static const char *ModeKey = \"c++-inlining\";\n std::string ModeStr = Config.lookup(ModeKey);\n\n CXXInlineableMemberKind &MutableMode =\n const_cast<CXXInlineableMemberKind &>(CXXMemberInliningMode);\n\n MutableMode = llvm::StringSwitch<CXXInlineableMemberKind>(ModeStr)\n .Case(\"\", CIMK_MemberFunctions)\n .Case(\"constructors\", CIMK_Constructors)\n .Case(\"destructors\", CIMK_Destructors)\n .Case(\"none\", CIMK_None)\n .Case(\"methods\", CIMK_MemberFunctions)\n .Default(CXXInlineableMemberKind());\n\n if (!MutableMode) {\n \/\/ FIXME: We should emit a warning here about an unknown inlining kind,\n \/\/ but the AnalyzerOptions doesn't have access to a diagnostic engine.\n MutableMode = CIMK_None;\n }\n }\n\n return CXXMemberInliningMode >= K;\n}\n\nbool AnalyzerOptions::getBooleanOption(StringRef Name, bool DefaultVal) const {\n \/\/ FIXME: We should emit a warning here if the value is something other than\n \/\/ \"true\", \"false\", or the empty string (meaning the default value),\n \/\/ but the AnalyzerOptions doesn't have access to a diagnostic engine.\n return llvm::StringSwitch<bool>(Config.lookup(Name))\n .Case(\"true\", true)\n .Case(\"false\", false)\n .Default(DefaultVal);\n}\n\nbool AnalyzerOptions::includeTemporaryDtorsInCFG() const {\n if (!IncludeTemporaryDtorsInCFG.hasValue())\n const_cast<llvm::Optional<bool> &>(IncludeTemporaryDtorsInCFG) =\n getBooleanOption(\"cfg-temporary-dtors\", \/*Default=*\/false);\n \n return *IncludeTemporaryDtorsInCFG;\n}\n\nbool AnalyzerOptions::mayInlineCXXStandardLibrary() const {\n if (!InlineCXXStandardLibrary.hasValue())\n const_cast<llvm::Optional<bool> &>(InlineCXXStandardLibrary) =\n getBooleanOption(\"c++-stdlib-inlining\", \/*Default=*\/true);\n \n return *InlineCXXStandardLibrary;\n}\n\nbool AnalyzerOptions::mayInlineTemplateFunctions() const {\n if (!InlineTemplateFunctions.hasValue())\n const_cast<llvm::Optional<bool> &>(InlineTemplateFunctions) =\n getBooleanOption(\"c++-template-inlining\", \/*Default=*\/true);\n \n return *InlineTemplateFunctions;\n}\n\nbool AnalyzerOptions::mayInlineObjCMethod() const {\n if (!ObjCInliningMode.hasValue())\n const_cast<llvm::Optional<bool> &>(ObjCInliningMode) =\n getBooleanOption(\"objc-inlining\", \/*Default=*\/true);\n\n return *ObjCInliningMode;\n}\n\nint AnalyzerOptions::getOptionAsInteger(StringRef Name, int DefaultVal) const {\n std::string OptStr = Config.lookup(Name);\n if (OptStr.empty())\n return DefaultVal;\n\n int Res = DefaultVal;\n assert(StringRef(OptStr).getAsInteger(10, Res) == false &&\n \"analyzer-config option should be numeric.\");\n\n return Res;\n}\n\nunsigned AnalyzerOptions::getAlwaysInlineSize() const {\n if (!AlwaysInlineSize.hasValue()) {\n unsigned DefaultSize = 3;\n const_cast<Optional<unsigned> &>(AlwaysInlineSize) =\n getOptionAsInteger(\"ipa-always-inline-size\", DefaultSize);\n }\n\n return AlwaysInlineSize.getValue();\n}\n\nbool AnalyzerOptions::shouldSynthesizeBodies() const {\n return getBooleanOption(\"faux-bodies\", true);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP\n#define STAN_IO_ARRAY_VAR_CONTEXT_HPP\n\n#include <stan\/io\/var_context.hpp>\n#include <boost\/throw_exception.hpp>\n#include <stan\/math\/prim\/mat\/fun\/Eigen.hpp>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <vector>\n#include <utility>\n\nnamespace stan {\n\nnamespace io {\n\n\/**\n * An array_var_context object represents a named arrays\n * with dimensions constructed from an array, a vector\n * of names, and a vector of all dimensions for each element.\n *\/\nclass array_var_context : public var_context {\n private:\n \/\/ Pairs\n template <typename T>\n using pair_\n = std::pair<std::string, std::pair<std::vector<T>, std::vector<size_t>>>;\n\n \/\/ Map holding reals\n using map_r_ = std::vector<pair_<double>>;\n map_r_ vars_r_;\n using map_i_ = std::vector<pair_<int>>;\n map_i_ vars_i_;\n \/\/ When search for variable name fails, return one these\n std::vector<double> const empty_vec_r_;\n std::vector<int> const empty_vec_i_;\n std::vector<size_t> const empty_vec_ui_;\n\n template <typename Str>\n auto find_var_r(Str&& name) const {\n return std::find_if(vars_r_.begin(), vars_r_.end(),\n [&](auto&& element){ return element.first == name;});\n }\n\n template <typename Str>\n auto find_var_i(Str&& name) const {\n return std::find_if(vars_i_.begin(), vars_i_.end(),\n [&](auto&& element){ return element.first == name;});\n }\n\n \/\/ Find method\n bool contains_r_only(const std::string& name) const {\n return find_var_r(name) != vars_r_.end();\n }\n\n \/**\n * Check (1) if the vector size of dimensions is no smaller\n * than the name vector size; (2) if the size of the input\n * array is large enough for what is needed.\n *\n * @param names The names for each variable\n * @param array_size The total size of the vector holding the values we want\n * to access.\n * @param dims Vector holding the dimensions for each variable.\n * @return If the array size is equal to the number of dimensions,\n * a vector of the cumulative sum of the dimensions of each inner element of\n * dims. The return of this function is used in the add_* methods to get the\n * sequence of values For each variable.\n *\/\n\n template <typename T>\n std::vector<size_t> validate_dims(\n const std::vector<std::string>& names, const T array_size,\n const std::vector<std::vector<size_t>>& dims) {\n const size_t num_par = names.size();\n if (num_par > dims.size()) {\n std::stringstream msg;\n msg << \"size of vector of dimensions (found \" << dims.size() << \") \"\n << \"should be no smaller than number of parameters (found \" << num_par\n << \").\";\n BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n }\n std::vector<size_t> elem_dims_total(dims.size() + 1);\n elem_dims_total[0] = 0;\n int i = 0;\n for (i = 0; i < dims.size(); i++) {\n elem_dims_total[i + 1] = std::accumulate(dims[i].begin(), dims[i].end(),\n 1, std::multiplies<T>());\n elem_dims_total[i + 1] += elem_dims_total[i];\n }\n if (elem_dims_total[i] > array_size) {\n std::stringstream msg;\n msg << \"array is not long enough for all elements: \" << array_size\n << \" is found, but \" << elem_dims_total[i] << \" is needed.\";\n BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n }\n return elem_dims_total;\n }\n\n \/**\n * Adds a set of floating point variables to the floating point map.\n * @param names Names of each variable.\n * @param values The real values of variable in a contiguous\n * column major order container.\n * @param dims the dimensions for each variable.\n *\/\n void add_r(const std::vector<std::string>& names,\n const std::vector<double>& values,\n const std::vector<std::vector<size_t>>& dims) {\n std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims);\n for (size_t i = 0; i < names.size(); i++) {\n vars_r_[i]\n = {names[i],\n {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]},\n dims[i]}};\n }\n }\n\n void add_r(const std::vector<std::string>& names,\n const Eigen::VectorXd& values,\n const std::vector<std::vector<size_t>>& dims) {\n std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims);\n using val_d_t = decltype(values.data());\n for (size_t i = 0; i < names.size(); i++) {\n vars_r_[i]\n = {names[i],\n {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]},\n dims[i]}};\n }\n }\n\n \/**\n * Adds a set of integer variables to the integer map.\n * @param names Names of each variable.\n * @param values The integer values of variable in a vector.\n * @param dims the dimensions for each variable.\n *\/\n void add_i(const std::vector<std::string>& names,\n const std::vector<int>& values,\n const std::vector<std::vector<size_t>>& dims) {\n std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims);\n for (size_t i = 0; i < names.size(); i++) {\n vars_i_[i]\n = {names[i],\n {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]},\n dims[i]}};\n }\n }\n\n public:\n \/**\n * Construct an array_var_context from only real value arrays.\n *\n * @param names_r names for each element\n * @param values_r a vector of double values for all elements\n * @param dim_r a vector of dimensions\n *\/\n array_var_context(const std::vector<std::string>& names_r,\n const std::vector<double>& values_r,\n const std::vector<std::vector<size_t>>& dim_r)\n : vars_r_(names_r.size()) {\n add_r(names_r, values_r, dim_r);\n }\n\n array_var_context(const std::vector<std::string>& names_r,\n const Eigen::VectorXd& values_r,\n const std::vector<std::vector<size_t>>& dim_r)\n : vars_r_(names_r.size()) {\n add_r(names_r, values_r, dim_r);\n }\n\n \/**\n * Construct an array_var_context from only integer value arrays.\n *\n * @param names_i names for each element\n * @param values_i a vector of integer values for all elements\n * @param dim_i a vector of dimensions\n *\/\n array_var_context(const std::vector<std::string>& names_i,\n const std::vector<int>& values_i,\n const std::vector<std::vector<size_t>>& dim_i)\n : vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n }\n\n \/**\n * Construct an array_var_context from arrays of both double\n * and integer separately\n *\n *\/\n array_var_context(const std::vector<std::string>& names_r,\n const std::vector<double>& values_r,\n const std::vector<std::vector<size_t>>& dim_r,\n const std::vector<std::string>& names_i,\n const std::vector<int>& values_i,\n const std::vector<std::vector<size_t>>& dim_i)\n : vars_r_(names_r.size()), vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n add_r(names_r, values_r, dim_r);\n }\n\n array_var_context(const std::vector<std::string>& names_r,\n const Eigen::VectorXd& values_r,\n const std::vector<std::vector<size_t>>& dim_r,\n const std::vector<std::string>& names_i,\n const std::vector<int>& values_i,\n const std::vector<std::vector<size_t>>& dim_i)\n : vars_r_(names_r.size()), vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n add_r(names_r, values_r, dim_r);\n }\n\n \/**\n * Return <code>true<\/code> if this dump contains the specified\n * variable name is defined. This method returns <code>true<\/code>\n * even if the values are all integers.\n *\n * @param name Variable name to test.\n * @return <code>true<\/code> if the variable exists.\n *\/\n bool contains_r(const std::string& name) const {\n return contains_r_only(name) || contains_i(name);\n }\n\n \/**\n * Return <code>true<\/code> if this dump contains an integer\n * valued array with the specified name.\n *\n * @param name Variable name to test.\n * @return <code>true<\/code> if the variable name has an integer\n * array value.\n *\/\n bool contains_i(const std::string& name) const {\n return find_var_i(name) != vars_i_.end();\n }\n\n \/**\n * Return the double values for the variable with the specified\n * name or null.\n *\n * @param name Name of variable.\n * @return Values of variable.\n *\n *\/\n std::vector<double> vals_r(const std::string& name) const {\n auto ret_val_r = find_var_r(name);\n if (ret_val_r != vars_r_.end()) {\n return ret_val_r->second.first;\n } else {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return {ret_val_i->second.first.begin(), ret_val_i->second.first.end()};\n }\n }\n return empty_vec_r_;\n }\n\n \/**\n * Return the dimensions for the double variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Dimensions of variable.\n *\/\n std::vector<size_t> dims_r(const std::string& name) const {\n auto ret_val_r = find_var_r(name);\n if (ret_val_r != vars_r_.end()) {\n return ret_val_r->second.second;\n } else {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.second;\n }\n }\n return empty_vec_ui_;\n }\n\n \/**\n * Return the integer values for the variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Values.\n *\/\n std::vector<int> vals_i(const std::string& name) const {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.first;\n }\n return empty_vec_i_;\n }\n\n \/**\n * Return the dimensions for the integer variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Dimensions of variable.\n *\/\n std::vector<size_t> dims_i(const std::string& name) const {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.second;\n }\n return empty_vec_ui_;\n }\n\n \/**\n * Return a list of the names of the floating point variables in\n * the dump.\n *\n * @param names Vector to store the list of names in.\n *\/\n virtual void names_r(std::vector<std::string>& names) const {\n names.clear();\n for (const auto& vars_r_iter : vars_r_) {\n names.push_back(vars_r_iter.first);\n }\n }\n\n \/**\n * Return a list of the names of the integer variables in\n * the dump.\n *\n * @param names Vector to store the list of names in.\n *\/\n virtual void names_i(std::vector<std::string>& names) const {\n names.clear();\n for (const auto& vars_i_iter : vars_r_) {\n names.push_back(vars_i_iter.first);\n }\n }\n\n \/**\n * Remove variable from the object.\n *\n * @param name Name of the variable to remove.\n * @return If variable is removed returns <code>true<\/code>, else\n * returns <code>false<\/code>.\n *\/\n bool remove(const std::string& name) {\n vars_i_.erase(find_var_i(name));\n vars_r_.erase(find_var_r(name));\n return true;\n }\n};\n} \/\/ namespace io\n} \/\/ namespace stan\n#endif\n<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags\/google\/stable\/2017-11-14)<commit_after>#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP\n#define STAN_IO_ARRAY_VAR_CONTEXT_HPP\n\n#include <stan\/io\/var_context.hpp>\n#include <boost\/throw_exception.hpp>\n#include <stan\/math\/prim\/mat\/fun\/Eigen.hpp>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <vector>\n#include <utility>\n\nnamespace stan {\n\nnamespace io {\n\n\/**\n * An array_var_context object represents a named arrays\n * with dimensions constructed from an array, a vector\n * of names, and a vector of all dimensions for each element.\n *\/\nclass array_var_context : public var_context {\n private:\n \/\/ Pairs\n template <typename T>\n using pair_\n = std::pair<std::string, std::pair<std::vector<T>, std::vector<size_t>>>;\n\n \/\/ Map holding reals\n using map_r_ = std::vector<pair_<double>>;\n map_r_ vars_r_;\n using map_i_ = std::vector<pair_<int>>;\n map_i_ vars_i_;\n \/\/ When search for variable name fails, return one these\n std::vector<double> const empty_vec_r_;\n std::vector<int> const empty_vec_i_;\n std::vector<size_t> const empty_vec_ui_;\n\n template <typename Str>\n auto find_var_r(Str&& name) const {\n return std::find_if(vars_r_.begin(), vars_r_.end(),\n [&](auto&& element) { return element.first == name; });\n }\n\n template <typename Str>\n auto find_var_i(Str&& name) const {\n return std::find_if(vars_i_.begin(), vars_i_.end(),\n [&](auto&& element) { return element.first == name; });\n }\n\n \/\/ Find method\n bool contains_r_only(const std::string& name) const {\n return find_var_r(name) != vars_r_.end();\n }\n\n \/**\n * Check (1) if the vector size of dimensions is no smaller\n * than the name vector size; (2) if the size of the input\n * array is large enough for what is needed.\n *\n * @param names The names for each variable\n * @param array_size The total size of the vector holding the values we want\n * to access.\n * @param dims Vector holding the dimensions for each variable.\n * @return If the array size is equal to the number of dimensions,\n * a vector of the cumulative sum of the dimensions of each inner element of\n * dims. The return of this function is used in the add_* methods to get the\n * sequence of values For each variable.\n *\/\n\n template <typename T>\n std::vector<size_t> validate_dims(\n const std::vector<std::string>& names, const T array_size,\n const std::vector<std::vector<size_t>>& dims) {\n const size_t num_par = names.size();\n if (num_par > dims.size()) {\n std::stringstream msg;\n msg << \"size of vector of dimensions (found \" << dims.size() << \") \"\n << \"should be no smaller than number of parameters (found \" << num_par\n << \").\";\n BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n }\n std::vector<size_t> elem_dims_total(dims.size() + 1);\n elem_dims_total[0] = 0;\n int i = 0;\n for (i = 0; i < dims.size(); i++) {\n elem_dims_total[i + 1] = std::accumulate(dims[i].begin(), dims[i].end(),\n 1, std::multiplies<T>());\n elem_dims_total[i + 1] += elem_dims_total[i];\n }\n if (elem_dims_total[i] > array_size) {\n std::stringstream msg;\n msg << \"array is not long enough for all elements: \" << array_size\n << \" is found, but \" << elem_dims_total[i] << \" is needed.\";\n BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n }\n return elem_dims_total;\n }\n\n \/**\n * Adds a set of floating point variables to the floating point map.\n * @param names Names of each variable.\n * @param values The real values of variable in a contiguous\n * column major order container.\n * @param dims the dimensions for each variable.\n *\/\n void add_r(const std::vector<std::string>& names,\n const std::vector<double>& values,\n const std::vector<std::vector<size_t>>& dims) {\n std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims);\n for (size_t i = 0; i < names.size(); i++) {\n vars_r_[i]\n = {names[i],\n {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]},\n dims[i]}};\n }\n }\n\n void add_r(const std::vector<std::string>& names,\n const Eigen::VectorXd& values,\n const std::vector<std::vector<size_t>>& dims) {\n std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims);\n using val_d_t = decltype(values.data());\n for (size_t i = 0; i < names.size(); i++) {\n vars_r_[i]\n = {names[i],\n {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]},\n dims[i]}};\n }\n }\n\n \/**\n * Adds a set of integer variables to the integer map.\n * @param names Names of each variable.\n * @param values The integer values of variable in a vector.\n * @param dims the dimensions for each variable.\n *\/\n void add_i(const std::vector<std::string>& names,\n const std::vector<int>& values,\n const std::vector<std::vector<size_t>>& dims) {\n std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims);\n for (size_t i = 0; i < names.size(); i++) {\n vars_i_[i]\n = {names[i],\n {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]},\n dims[i]}};\n }\n }\n\n public:\n \/**\n * Construct an array_var_context from only real value arrays.\n *\n * @param names_r names for each element\n * @param values_r a vector of double values for all elements\n * @param dim_r a vector of dimensions\n *\/\n array_var_context(const std::vector<std::string>& names_r,\n const std::vector<double>& values_r,\n const std::vector<std::vector<size_t>>& dim_r)\n : vars_r_(names_r.size()) {\n add_r(names_r, values_r, dim_r);\n }\n\n array_var_context(const std::vector<std::string>& names_r,\n const Eigen::VectorXd& values_r,\n const std::vector<std::vector<size_t>>& dim_r)\n : vars_r_(names_r.size()) {\n add_r(names_r, values_r, dim_r);\n }\n\n \/**\n * Construct an array_var_context from only integer value arrays.\n *\n * @param names_i names for each element\n * @param values_i a vector of integer values for all elements\n * @param dim_i a vector of dimensions\n *\/\n array_var_context(const std::vector<std::string>& names_i,\n const std::vector<int>& values_i,\n const std::vector<std::vector<size_t>>& dim_i)\n : vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n }\n\n \/**\n * Construct an array_var_context from arrays of both double\n * and integer separately\n *\n *\/\n array_var_context(const std::vector<std::string>& names_r,\n const std::vector<double>& values_r,\n const std::vector<std::vector<size_t>>& dim_r,\n const std::vector<std::string>& names_i,\n const std::vector<int>& values_i,\n const std::vector<std::vector<size_t>>& dim_i)\n : vars_r_(names_r.size()), vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n add_r(names_r, values_r, dim_r);\n }\n\n array_var_context(const std::vector<std::string>& names_r,\n const Eigen::VectorXd& values_r,\n const std::vector<std::vector<size_t>>& dim_r,\n const std::vector<std::string>& names_i,\n const std::vector<int>& values_i,\n const std::vector<std::vector<size_t>>& dim_i)\n : vars_r_(names_r.size()), vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n add_r(names_r, values_r, dim_r);\n }\n\n \/**\n * Return <code>true<\/code> if this dump contains the specified\n * variable name is defined. This method returns <code>true<\/code>\n * even if the values are all integers.\n *\n * @param name Variable name to test.\n * @return <code>true<\/code> if the variable exists.\n *\/\n bool contains_r(const std::string& name) const {\n return contains_r_only(name) || contains_i(name);\n }\n\n \/**\n * Return <code>true<\/code> if this dump contains an integer\n * valued array with the specified name.\n *\n * @param name Variable name to test.\n * @return <code>true<\/code> if the variable name has an integer\n * array value.\n *\/\n bool contains_i(const std::string& name) const {\n return find_var_i(name) != vars_i_.end();\n }\n\n \/**\n * Return the double values for the variable with the specified\n * name or null.\n *\n * @param name Name of variable.\n * @return Values of variable.\n *\n *\/\n std::vector<double> vals_r(const std::string& name) const {\n auto ret_val_r = find_var_r(name);\n if (ret_val_r != vars_r_.end()) {\n return ret_val_r->second.first;\n } else {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return {ret_val_i->second.first.begin(), ret_val_i->second.first.end()};\n }\n }\n return empty_vec_r_;\n }\n\n \/**\n * Return the dimensions for the double variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Dimensions of variable.\n *\/\n std::vector<size_t> dims_r(const std::string& name) const {\n auto ret_val_r = find_var_r(name);\n if (ret_val_r != vars_r_.end()) {\n return ret_val_r->second.second;\n } else {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.second;\n }\n }\n return empty_vec_ui_;\n }\n\n \/**\n * Return the integer values for the variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Values.\n *\/\n std::vector<int> vals_i(const std::string& name) const {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.first;\n }\n return empty_vec_i_;\n }\n\n \/**\n * Return the dimensions for the integer variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Dimensions of variable.\n *\/\n std::vector<size_t> dims_i(const std::string& name) const {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.second;\n }\n return empty_vec_ui_;\n }\n\n \/**\n * Return a list of the names of the floating point variables in\n * the dump.\n *\n * @param names Vector to store the list of names in.\n *\/\n virtual void names_r(std::vector<std::string>& names) const {\n names.clear();\n for (const auto& vars_r_iter : vars_r_) {\n names.push_back(vars_r_iter.first);\n }\n }\n\n \/**\n * Return a list of the names of the integer variables in\n * the dump.\n *\n * @param names Vector to store the list of names in.\n *\/\n virtual void names_i(std::vector<std::string>& names) const {\n names.clear();\n for (const auto& vars_i_iter : vars_r_) {\n names.push_back(vars_i_iter.first);\n }\n }\n\n \/**\n * Remove variable from the object.\n *\n * @param name Name of the variable to remove.\n * @return If variable is removed returns <code>true<\/code>, else\n * returns <code>false<\/code>.\n *\/\n bool remove(const std::string& name) {\n vars_i_.erase(find_var_i(name));\n vars_r_.erase(find_var_r(name));\n return true;\n }\n};\n} \/\/ namespace io\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>\r\n\/\/ Standard C++ includes\r\n#include <stdlib.h>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <assert.h>\r\n#include <float.h>\r\n#include <math.h>\r\n#include <vector>\r\n#include <string>\r\n#include <algorithm>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\n\r\n\/\/ Public interface of the MySQL Connector\/C++\r\n#include <cppconn\/mysql_public_iface.h>\r\n#include \"filtering.h\"\r\n#include \"preprocessing.h\"\r\n\r\nusing namespace std;\r\n \r\n\/**\r\n* Usage example for Driver Manager, Connection, (simple) Statement, ResultSet\r\n*\/\r\n\r\nint main(int argc, char** argv) {\r\n\t\r\n\tstring productName = \"Camera\";\t\r\n\tstringstream sql;\r\n\t\r\n\tint clusterN; \r\n\tint conFeatureN;\r\n\tint catFeatureN;\r\n\tint boolFeatureN;\r\n\tint varNamesN;\r\n\tint range; \r\n\tint session_id;\r\n\tint repW; \r\n\tint clusterID = 0;\r\n\t\r\n\tstring argu = argv[1];\r\n\tint ind, endit, startit, lengthit;\r\n\tstring var;\r\n\r\n\t\/\/productName\r\n\tvar = \"product_name\";\r\n\tind = argu.find(var, 0);\r\n\tendit = argu.find(\"\\n\", ind);\r\n\tstartit = ind + var.length() + 2;\r\n\tlengthit = endit - startit;\r\n\tif (lengthit>0){\r\n\t\tproductName = (argu.substr(startit, lengthit)).c_str();\r\n\t}\r\n\telse{\r\n\t\tcout<<\"ERROR - Specify a productName\"<<endl;\r\n\t}\r\n\t\/\/session_id\r\n\tvar = \"session_id\";\r\n\tind = argu.find(var, 0);\r\n\tendit = argu.find(\"\\n\", ind);\r\n\tstartit = ind + var.length() + 2;\r\n\tlengthit = endit - startit;\r\n\tif (lengthit>0){\r\n\t\tsession_id = atoi((argu.substr(startit, lengthit)).c_str());\r\n\t}\r\n\t\r\n\tstring tableName = productName;\r\n\ttableName.append(\"s\");\r\n\tmap<const string, int> productNames;\r\n\tproductNames[\"camera\"] = 1;\r\n\tproductNames[\"printer\"] = 2;\r\n\t\r\n\tswitch(productNames[productName]){\r\n\t\t\r\n\t\tcase 1:\r\n\t\t\r\n\t\t\t\t\tclusterN = 9; \r\n\t\t\t\t\tconFeatureN= 4;\r\n\t\t\t\t\tcatFeatureN= 1;\r\n\t\t\t\t\tboolFeatureN= 0;\r\n\t\t\t\t\tvarNamesN= 12;\r\n\t\t\t\t\trange= 2;\r\n\t\t\t\t\trepW = 9; \r\n\t\t\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 2:\r\n\t\t\t\t\tclusterN = 9; \r\n\t\t\t\t\tconFeatureN= 4;\r\n\t\t\t\t\tcatFeatureN= 1;\r\n\t\t\t\t\tboolFeatureN= 0;\r\n\t\t\t\t\tvarNamesN= 12;\r\n\t\t\t\t\trange= 2;\r\n\t\t\t\t\trepW = 9; \r\n\t\t\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\t\t\tclusterN = 9; \r\n\t\t\t\t\tconFeatureN= 4;\r\n\t\t\t\t\tcatFeatureN= 1;\r\n\t\t\t\t\tboolFeatureN= 0;\r\n\t\t\t\t\tvarNamesN= 12;\r\n\t\t\t\t\trange= 2;\r\n\t\t\t\t\trepW = 9; \r\n\t\t\t\t\tbreak;\r\n\t}\r\n\t\r\n\tstring* brands = new string [1] ;\r\n\tint* mergedClusterIDInput = new int[clusterN];\r\n\tbool smallNFlag =false;\r\n\tstring* indicatorNames = new string[conFeatureN];\r\n\tint ** indicators = new int*[conFeatureN];\r\n\tdouble** conFeatureRange = new double* [conFeatureN];\r\n\t\r\n\tfor (int f=0; f<conFeatureN; f++){\r\n\t\tconFeatureRange[f] = new double [2];\r\n\t\tindicators[f] = new int[repW];\r\n\t\tfor (int i=0; i<repW; i++){\r\n\t\tindicators[f][i] = 0;\r\n\t\t}\r\n\t}\r\n\tostringstream session_idStream;\r\n\t\r\n\tstring *varNames = new string[varNamesN];\r\n\tstring *catFeatureNames = new string [catFeatureN];\r\n\tstring *conFeatureNames = new string[conFeatureN];\r\n\tdouble **filteredRange = new double* [conFeatureN];\r\n\tbool *conFilteredFeatures = new bool[conFeatureN]; \r\n\tbool *catFilteredFeatures = new bool[catFeatureN];\r\n\tbool *boolFilteredFeatures = new bool[boolFeatureN];\r\n\tmap<const string, string*> productFeatures;\r\n \tfor(int f=0; f<conFeatureN; f++){\r\n\t\tconFilteredFeatures[f] = 0;\r\n\t\tfilteredRange[f] = new double [range];\t\t\r\n\t}\r\n\t\r\n\tfor (int f=0; f<catFeatureN; f++){\r\n\t catFilteredFeatures[f] = 0;\r\n\t}\r\n\r\n for (int f=0; f<boolFeatureN; f++){\r\n\t\tboolFilteredFeatures[f] = 0;\r\n\t}\r\n\r\n\r\n\t\/\/cluster_id\r\n\tvar = \"cluster_id\";\r\n\tind = argu.find(var, 0);\r\n\tendit = argu.find(\"\\n\", ind);\r\n\t\r\n\tstartit = ind + var.length() + 2;\r\n\tlengthit = endit - startit;\r\n\r\n\r\n\tif(lengthit>0){\r\n\t\t\r\n\t\tstring valueString = argu.substr(startit, lengthit);\r\n\t\tint found = valueString.find(\"-\");\r\n\t\tint mergedClusterN=0;\r\n\t\twhile ( found != (int)string::npos){\t\r\n\t\t\tmergedClusterIDInput[mergedClusterN] = atoi((valueString.substr(found+1,1)).c_str());\r\n\t\t\tfound = valueString.find(\"-\", found+2, 1);\r\n\t\t\tmergedClusterN++; \r\n\t\t}\t\r\n\t\tif (mergedClusterN >0){\r\n\t\t\tclusterID = -1 * mergedClusterN;\r\n\t\t}\r\n\t\tif (found == (int)string::npos){\r\n\t\t\t\tclusterID = atoi((argu.substr(startit, lengthit)).c_str());\r\n\t\t}\r\n\t}\r\n\r\n\tparseInput(varNames, productNames, productName, argu, brands, catFilteredFeatures, conFilteredFeatures, boolFilteredFeatures, filteredRange, \r\n\t\t\t\tvarNamesN, conFeatureNames, catFeatureNames, indicatorNames);\r\n\t\t\t\r\n \t\r\n\tstring brand = \"\";\r\n\r\n\/\/ Driver Manager\r\n\r\n \tsql::mysql::MySQL_Driver *driver;\r\n\r\n\tsql::Connection\t*con;\r\n\tsql::Statement\t*stmt;\r\n\t\r\n\tsql::ResultSet\t*res;\r\n\tsql::ResultSet\t*res2;\r\n\t\tstring line;\r\n\t\tstring buf; \r\n\t\tvector<string> tokens;\r\n\t\tifstream myfile;\r\n\t\tint i=0;\r\n\t myfile.open(\"\/optemo\/site\/config\/database.yml\"); \r\n\t if (myfile.is_open()){\r\n\t\twhile (! myfile.eof()){\r\n\t\t\tgetline (myfile,line);\r\n\t\t\tstringstream ss(line);\r\n\t\t\twhile(ss>>buf){\r\n\t\t\t\ttokens.push_back(buf);\r\n\t\t\t\ti++;\t}\r\n\t\t}\r\n\t myfile.close();\r\n }\r\n\t else{\r\n\t\t\tcout<<\"Can't open file \"<<myfile<<endl;\r\n\t }\r\n\r\n\tstring databaseString = tokens.at(findVec(tokens, \"database:\") + 1);\r\n\tstring usernameString = tokens.at(findVec(tokens, \"username:\") + 1);\r\n\tstring passwordString = tokens.at(findVec(tokens, \"password:\") + 1);\r\n\tstring hostString = tokens.at(findVec(tokens, \"host:\") + 1);\r\n\r\n\t #define PORT \"3306\" \r\n\t \t#define DB \"optemo_development\"\r\n\t\t#define HOST hostString \r\n\t\t#define USER usernameString \r\n\t #define PASS passwordString \r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\t\r\n\t\t\ttry {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\/\/ Using the Driver to create a connection\r\n\t\t\t\tdriver = sql::mysql::get_mysql_driver_instance();\r\n\t\t\t\tcon = driver->connect(HOST, PORT, USER, PASS);\r\n\t\t\t\tstmt = con->createStatement();\r\n\t\t\t\tstmt->execute(\"USE \" DB);\r\n\t\t\t\tstring command;\t\r\n\t\t\t\tint size;\r\n\t\t\t\tstring out = \"\";\r\n\t\t\t\r\n\t\t\t\tbool reped = false;\r\n\t\t\t\r\n\t\t\tif (clusterID == 0){\r\n\t\t\t\tcommand = \"SELECT id from \";\r\n\t\t\t\tcommand += tableName;\r\n\t\t\t\tcommand += \";\";\r\n \t\t\t\tres = stmt->executeQuery(command);\r\n\t\t\t\tsize = res->rowsCount();\t\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tcommand = \"SELECT id from \";\r\n\t\t\t\tcommand += productName;\r\n\t\t\t\tcommand += \"_nodes where cluster_id=\";\r\n\t\t\t\tostringstream cid;\r\n\t\t\t\tcid<<clusterID;\r\n\t\t\t\tcommand += cid.str();\r\n\t\t\t\tcommand += \";\";\r\n\t\t\t\tres = stmt->executeQuery(command);\r\n\t\t\t\tsize = res->rowsCount();\r\n\t\t\t}\t\r\n\t\t\tint* productIDs = new int [size];\r\n\t\t\tint productN = filter2(filteredRange, brand, stmt, res, res2, productIDs, conFilteredFeatures, catFilteredFeatures, clusterID, clusterN, conFeatureN, conFeatureRange, productName, conFeatureNames);\r\n\t\t\tif (productN> 0){\r\n\t\t\t\tif (productN<=repW){\r\n\t\t\t\t\trepW = productN; \r\n\t\t\t\t\tsmallNFlag = true;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tint* reps = new int [repW];\t\t\r\n\t\t\t\tint* clusterIDs = new int[repW];\r\n\t\t\t\tint* clusterCounts = new int[repW];\r\n\t\t\t\tint* mergedClusterIDs;\r\n\t\t\t\r\n\t\t\t\treped = getRep(reps, productIDs, productN, clusterIDs, clusterCounts, conFeatureN, repW, stmt, res, res2, clusterID, smallNFlag, mergedClusterIDs, mergedClusterIDInput, productName, conFeatureNames);\r\n\t\t\t\t\r\n\t\t\r\n\t\t\t\tif(reped){\r\n\t\t\t\t\t\t\r\n\t\t\t\t\tgetIndicators(clusterIDs,repW, conFeatureN, indicators, stmt, res, mergedClusterIDs, productName, conFeatureNames);\r\n\t\t\t\t}\r\n\t\t\r\n\/\/Generating the output string \r\n\t\t\t\/\/\trepW = 9;\r\n\t\t\r\n\t\t\t\r\n\t\t\t\tout = generateOutput(indicatorNames, conFeatureN, productN, conFeatureRange, varNames, repW, reps, reped, clusterIDs, mergedClusterIDs, clusterCounts, indicators);\r\n\t\t\t}\r\n\t\t\telse{\t\/\/productN=0;\r\n\t\t\t\tout = \"--- !map:HashWithIndifferentAccess \\n\";\r\n\t\t\t\tout.append(\"result_count: \");\r\n\t\t\t\tostringstream resultCountStream;\r\n\t\t\t\tresultCountStream << productN;\r\n\t\t\t\tout.append(resultCountStream.str());\r\n\t\t\t\tout.append(\"\\n\");\r\n\r\n\t\t\t}\r\n\t\tcout<<out<<endl;\r\n\t\t\r\n\r\n\t\/\/ Clean up\r\n\r\n \tdelete stmt;\r\n \tdelete con;\r\n\r\n \r\n\r\n \t} catch (sql::mysql::MySQL_DbcException *e) {\r\n\r\n\t\tdelete e;\r\n\t\treturn EXIT_FAILURE;\r\n\r\n\t} catch (sql::DbcException *e) {\r\n\t\t\/* Exception is not caused by the MySQL Server *\/\r\n\r\n\t\tdelete e;\r\n\t\treturn EXIT_FAILURE;\r\n\t}\r\n\r\n\r\nreturn 1; \/\/EXIT_SUCCESS;\r\n}<commit_msg>changed connect.cpp<commit_after>\r\n\/\/ Standard C++ includes\r\n#include <stdlib.h>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <assert.h>\r\n#include <float.h>\r\n#include <math.h>\r\n#include <vector>\r\n#include <string>\r\n#include <algorithm>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\n\r\n\/\/ Public interface of the MySQL Connector\/C++\r\n#include <cppconn\/mysql_public_iface.h>\r\n#include \"filtering.h\"\r\n#include \"preprocessing.h\"\r\n\r\nusing namespace std;\r\n \r\n\/**\r\n* Usage example for Driver Manager, Connection, (simple) Statement, ResultSet\r\n*\/\r\n\r\nint main(int argc, char** argv) {\r\n\t\r\n\tstring productName = \"Camera\";\t\r\n\tstringstream sql;\r\n\t\r\n\tint clusterN; \r\n\tint conFeatureN;\r\n\tint catFeatureN;\r\n\tint boolFeatureN;\r\n\tint varNamesN;\r\n\tint range; \r\n\tint session_id;\r\n\tint repW; \r\n\tint clusterID = 0;\r\n\t\r\n\tstring argu = argv[1];\r\n\tint ind, endit, startit, lengthit;\r\n\tstring var;\r\n\r\n\t\/\/productName\r\n\tvar = \"product_name\";\r\n\tind = argu.find(var, 0);\r\n\tendit = argu.find(\"\\n\", ind);\r\n\tstartit = ind + var.length() + 2;\r\n\tlengthit = endit - startit;\r\n\tif (lengthit>0){\r\n\t\tproductName = (argu.substr(startit, lengthit)).c_str();\r\n\t}\r\n\telse{\r\n\t\tcout<<\"ERROR - Specify a productName\"<<endl;\r\n\t}\r\n\t\/\/session_id\r\n\tvar = \"session_id\";\r\n\tind = argu.find(var, 0);\r\n\tendit = argu.find(\"\\n\", ind);\r\n\tstartit = ind + var.length() + 2;\r\n\tlengthit = endit - startit;\r\n\tif (lengthit>0){\r\n\t\tsession_id = atoi((argu.substr(startit, lengthit)).c_str());\r\n\t}\r\n\t\r\n\tstring tableName = productName;\r\n\ttableName.append(\"s\");\r\n\tmap<const string, int> productNames;\r\n\tproductNames[\"camera\"] = 1;\r\n\tproductNames[\"printer\"] = 2;\r\n\t\r\n\tswitch(productNames[productName]){\r\n\t\t\r\n\t\tcase 1:\r\n\t\t\t\t\t\/\/productName = \"Camera\";\r\n\t\t\t\t\tclusterN = 9; \r\n\t\t\t\t\tconFeatureN= 4;\r\n\t\t\t\t\tcatFeatureN= 1;\r\n\t\t\t\t\tboolFeatureN= 0;\r\n\t\t\t\t\tvarNamesN= 12;\r\n\t\t\t\t\trange= 2;\r\n\t\t\t\t\trepW = 9; \r\n\t\t\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 2: \t\r\n\t\t\t\t\/\/\tproductName = \"Printer\";\r\n\t\t\t\t\tclusterN = 9; \r\n\t\t\t\t\tconFeatureN= 4;\r\n\t\t\t\t\tcatFeatureN= 1;\r\n\t\t\t\t\tboolFeatureN= 0;\r\n\t\t\t\t\tvarNamesN= 12;\r\n\t\t\t\t\trange= 2;\r\n\t\t\t\t\trepW = 9; \r\n\t\t\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\t\t\tclusterN = 9; \r\n\t\t\t\t\tconFeatureN= 4;\r\n\t\t\t\t\tcatFeatureN= 1;\r\n\t\t\t\t\tboolFeatureN= 0;\r\n\t\t\t\t\tvarNamesN= 12;\r\n\t\t\t\t\trange= 2;\r\n\t\t\t\t\trepW = 9; \r\n\t\t\t\t\tbreak;\r\n\t}\r\n\t\r\n\tstring* brands = new string [1] ;\r\n\tint* mergedClusterIDInput = new int[clusterN];\r\n\tbool smallNFlag =false;\r\n\tstring* indicatorNames = new string[conFeatureN];\r\n\tint ** indicators = new int*[conFeatureN];\r\n\tdouble** conFeatureRange = new double* [conFeatureN];\r\n\t\r\n\tfor (int f=0; f<conFeatureN; f++){\r\n\t\tconFeatureRange[f] = new double [2];\r\n\t\tindicators[f] = new int[repW];\r\n\t\tfor (int i=0; i<repW; i++){\r\n\t\tindicators[f][i] = 0;\r\n\t\t}\r\n\t}\r\n\tostringstream session_idStream;\r\n\t\r\n\tstring *varNames = new string[varNamesN];\r\n\tstring *catFeatureNames = new string [catFeatureN];\r\n\tstring *conFeatureNames = new string[conFeatureN];\r\n\tdouble **filteredRange = new double* [conFeatureN];\r\n\tbool *conFilteredFeatures = new bool[conFeatureN]; \r\n\tbool *catFilteredFeatures = new bool[catFeatureN];\r\n\tbool *boolFilteredFeatures = new bool[boolFeatureN];\r\n\tmap<const string, string*> productFeatures;\r\n \tfor(int f=0; f<conFeatureN; f++){\r\n\t\tconFilteredFeatures[f] = 0;\r\n\t\tfilteredRange[f] = new double [range];\t\t\r\n\t}\r\n\t\r\n\tfor (int f=0; f<catFeatureN; f++){\r\n\t catFilteredFeatures[f] = 0;\r\n\t}\r\n\r\n for (int f=0; f<boolFeatureN; f++){\r\n\t\tboolFilteredFeatures[f] = 0;\r\n\t}\r\n\r\n\r\n\t\/\/cluster_id\r\n\tvar = \"cluster_id\";\r\n\tind = argu.find(var, 0);\r\n\tendit = argu.find(\"\\n\", ind);\r\n\t\r\n\tstartit = ind + var.length() + 2;\r\n\tlengthit = endit - startit;\r\n\r\n\r\n\tif(lengthit>0){\r\n\t\t\r\n\t\tstring valueString = argu.substr(startit, lengthit);\r\n\t\tint found = valueString.find(\"-\");\r\n\t\tint mergedClusterN=0;\r\n\t\twhile ( found != (int)string::npos){\t\r\n\t\t\tmergedClusterIDInput[mergedClusterN] = atoi((valueString.substr(found+1,1)).c_str());\r\n\t\t\tfound = valueString.find(\"-\", found+2, 1);\r\n\t\t\tmergedClusterN++; \r\n\t\t}\t\r\n\t\tif (mergedClusterN >0){\r\n\t\t\tclusterID = -1 * mergedClusterN;\r\n\t\t}\r\n\t\tif (found == (int)string::npos){\r\n\t\t\t\tclusterID = atoi((argu.substr(startit, lengthit)).c_str());\r\n\t\t}\r\n\t}\r\n\r\n\tparseInput(varNames, productNames, productName, argu, brands, catFilteredFeatures, conFilteredFeatures, boolFilteredFeatures, filteredRange, \r\n\t\t\t\tvarNamesN, conFeatureNames, catFeatureNames, indicatorNames);\r\n\t\t\t\r\n \t\r\n\tstring brand = \"\";\r\n\r\n\/\/ Driver Manager\r\n\r\n \tsql::mysql::MySQL_Driver *driver;\r\n\r\n\tsql::Connection\t*con;\r\n\tsql::Statement\t*stmt;\r\n\t\r\n\tsql::ResultSet\t*res;\r\n\tsql::ResultSet\t*res2;\r\n\t\tstring line;\r\n\t\tstring buf; \r\n\t\tvector<string> tokens;\r\n\t\tifstream myfile;\r\n\t\tint i=0;\r\n\t myfile.open(\"\/optemo\/site\/config\/database.yml\"); \r\n\t if (myfile.is_open()){\r\n\t\twhile (! myfile.eof()){\r\n\t\t\tgetline (myfile,line);\r\n\t\t\tstringstream ss(line);\r\n\t\t\twhile(ss>>buf){\r\n\t\t\t\ttokens.push_back(buf);\r\n\t\t\t\ti++;\t}\r\n\t\t}\r\n\t myfile.close();\r\n }\r\n\t else{\r\n\t\t\tcout<<\"Can't open file \"<<myfile<<endl;\r\n\t }\r\n\r\n\tstring databaseString = tokens.at(findVec(tokens, \"database:\") + 1);\r\n\tstring usernameString = tokens.at(findVec(tokens, \"username:\") + 1);\r\n\tstring passwordString = tokens.at(findVec(tokens, \"password:\") + 1);\r\n\tstring hostString = tokens.at(findVec(tokens, \"host:\") + 1);\r\n\r\n\t #define PORT \"3306\" \r\n\t \t#define DB \"optemo_development\"\r\n\t\t#define HOST hostString \r\n\t\t#define USER usernameString \r\n\t #define PASS passwordString \r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\t\r\n\t\t\ttry {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\/\/ Using the Driver to create a connection\r\n\t\t\t\tdriver = sql::mysql::get_mysql_driver_instance();\r\n\t\t\t\tcon = driver->connect(HOST, PORT, USER, PASS);\r\n\t\t\t\tstmt = con->createStatement();\r\n\t\t\t\tstmt->execute(\"USE \" DB);\r\n\t\t\t\tstring command;\t\r\n\t\t\t\tint size;\r\n\t\t\t\tstring out = \"\";\r\n\t\t\t\r\n\t\t\t\tbool reped = false;\r\n\t\t\t\r\n\t\t\tif (clusterID == 0){\r\n\t\t\t\tcommand = \"SELECT id from \";\r\n\t\t\t\tcommand += tableName;\r\n\t\t\t\tcommand += \";\";\r\n \t\t\t\tres = stmt->executeQuery(command);\r\n\t\t\t\tsize = res->rowsCount();\t\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tcommand = \"SELECT id from \";\r\n\t\t\t\tcommand += productName;\r\n\t\t\t\tcommand += \"_nodes where cluster_id=\";\r\n\t\t\t\tostringstream cid;\r\n\t\t\t\tcid<<clusterID;\r\n\t\t\t\tcommand += cid.str();\r\n\t\t\t\tcommand += \";\";\r\n\t\t\t\tres = stmt->executeQuery(command);\r\n\t\t\t\tsize = res->rowsCount();\r\n\t\t\t}\t\r\n\t\t\tint* productIDs = new int [size];\r\n\t\t\tint productN = filter2(filteredRange, brand, stmt, res, res2, productIDs, conFilteredFeatures, catFilteredFeatures, clusterID, clusterN, conFeatureN, conFeatureRange, productName, conFeatureNames);\r\n\t\t\tif (productN> 0){\r\n\t\t\t\tif (productN<=repW){\r\n\t\t\t\t\trepW = productN; \r\n\t\t\t\t\tsmallNFlag = true;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tint* reps = new int [repW];\t\t\r\n\t\t\t\tint* clusterIDs = new int[repW];\r\n\t\t\t\tint* clusterCounts = new int[repW];\r\n\t\t\t\tint* mergedClusterIDs;\r\n\t\t\t\r\n\t\t\t\treped = getRep(reps, productIDs, productN, clusterIDs, clusterCounts, conFeatureN, repW, stmt, res, res2, clusterID, smallNFlag, mergedClusterIDs, mergedClusterIDInput, productName, conFeatureNames);\r\n\t\t\t\t\r\n\t\t\r\n\t\t\t\tif(reped){\r\n\t\t\t\t\t\t\r\n\t\t\t\t\tgetIndicators(clusterIDs,repW, conFeatureN, indicators, stmt, res, mergedClusterIDs, productName, conFeatureNames);\r\n\t\t\t\t}\r\n\t\t\r\n\/\/Generating the output string \r\n\t\t\t\/\/\trepW = 9;\r\n\t\t\r\n\t\t\t\r\n\t\t\t\tout = generateOutput(indicatorNames, conFeatureN, productN, conFeatureRange, varNames, repW, reps, reped, clusterIDs, mergedClusterIDs, clusterCounts, indicators);\r\n\t\t\t}\r\n\t\t\telse{\t\/\/productN=0;\r\n\t\t\t\tout = \"--- !map:HashWithIndifferentAccess \\n\";\r\n\t\t\t\tout.append(\"result_count: \");\r\n\t\t\t\tostringstream resultCountStream;\r\n\t\t\t\tresultCountStream << productN;\r\n\t\t\t\tout.append(resultCountStream.str());\r\n\t\t\t\tout.append(\"\\n\");\r\n\r\n\t\t\t}\r\n\t\tcout<<out<<endl;\r\n\t\t\r\n\r\n\t\/\/ Clean up\r\n\r\n \tdelete stmt;\r\n \tdelete con;\r\n\r\n \r\n\r\n \t} catch (sql::mysql::MySQL_DbcException *e) {\r\n\r\n\t\tdelete e;\r\n\t\treturn EXIT_FAILURE;\r\n\r\n\t} catch (sql::DbcException *e) {\r\n\t\t\/* Exception is not caused by the MySQL Server *\/\r\n\r\n\t\tdelete e;\r\n\t\treturn EXIT_FAILURE;\r\n\t}\r\n\r\n\r\nreturn 1; \/\/EXIT_SUCCESS;\r\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * PlayerInputSystem.cpp\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Ashley Davis\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 all\n * 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 THE\n * SOFTWARE.\n *\/\n\n#include <cstdio>\n\n#include <Ashley\/core\/ComponentMapper.hpp>\n\n#include <glm\/vec2.hpp>\n#include <libtcod.hpp>\n\n#include \"components\/Position.hpp\"\n#include \"components\/PlayerInputListener.hpp\"\n#include \"components\/Inventory.hpp\"\n#include \"components\/Interactible.hpp\"\n#include \"components\/Battling.hpp\"\n\n#include \"systems\/PlayerInputSystem.hpp\"\n\n#include \"RGL.hpp\"\n#include \"Map.hpp\"\n#include \"Message.hpp\"\n\n#include \"easylogging++.h\"\n\nvoid rgl::PlayerInputSystem::processEntity(ashley::Entity * const &entity, float deltaTime) {\n\tconst auto inputComponent = ashley::ComponentMapper<PlayerInputListener>::getMapper().get(entity);\n\n\tif (f5Pressed) {\n\t\tconst auto inventory = ashley::ComponentMapper<Inventory>::getMapper().get(entity);\n\n\t\tif (inventory != nullptr) {\n\t\t\tfor (const auto &item : inventory->contents) {\n\t\t\t\tRGLL->debug(\"Player has: %v\", item.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch (inputComponent->state) {\n\tcase PlayerInputState::NORMAL: {\n\t\tprocessNormalState(entity, deltaTime, inputComponent);\n\t\tbreak;\n\t}\n\n\tcase PlayerInputState::TARGETTING: {\n\t\tprocessTargettingState(entity, deltaTime, inputComponent);\n\t\tbreak;\n\t}\n\n\tcase PlayerInputState::RESPONDING: {\n\t\tprocessRespondingState(entity, deltaTime, inputComponent);\n\t\tbreak;\n\t}\n\n\tdefault: {\n\t\tRGLL->debug(\"Unhandled case in PlayerInputSystem switch.\");\n\t\tbreak;\n\t}\n}\n}\n\nvoid rgl::PlayerInputSystem::processNormalState(ashley::Entity * const &entity, float deltaTime,\n PlayerInputListener * const listener) {\n\tconst auto pos = ashley::ComponentMapper<Position>::getMapper().get(entity);\n\tglm::ivec2 target(pos->position);\n\n\tif (spacePressed) {\n\t\tlistener->state = PlayerInputState::TARGETTING;\n\t\treturn;\n\t} else if (upPressed) {\n\t\t--target.y;\n\t} else if (downPressed) {\n\t\t++target.y;\n\t} else if (leftPressed) {\n\t\t--target.x;\n\t} else if (rightPressed) {\n\t\t++target.x;\n\t}\n\n\t\/\/ check if target is clear\n\tif (target.x >= 0 && target.x < map->getWidth() && target.y >= 0 && target.y < map->getHeight()) {\n\t\tconst auto targetTile = map->getTileAt(target.x, target.y);\n\n\t\tif (targetTile != nullptr && !targetTile->solid) {\n\t\t\tpos->position = target;\n\t\t}\n\t}\n}\n\nvoid rgl::PlayerInputSystem::processTargettingState(ashley::Entity * const &entity, float deltaTime,\n PlayerInputListener * const listener) {\n\tconst auto pos = ashley::ComponentMapper<Position>::getMapper().get(entity);\n\tglm::ivec2 target(pos->position);\n\tbool interactionDone = false;\n\n\tif (spacePressed) {\n\t\tinteractionDone = true;\n\t} else if (upPressed) {\n\t\tinteractionDone = true;\n\t\t--target.y;\n\t} else if (downPressed) {\n\t\tinteractionDone = true;\n\t\t++target.y;\n\t} else if (leftPressed) {\n\t\tinteractionDone = true;\n\t\t--target.x;\n\t} else if (rightPressed) {\n\t\tinteractionDone = true;\n\t\t++target.x;\n\t}\n\n\tconst auto targetTile = map->getTileAt(target.x, target.y);\n\n\tif (targetTile != nullptr) {\n\t\tlistener->target = target;\n\n\t\tif (!targetTile->contains.empty()) {\n\t\t\tfor (const auto &e : targetTile->contains) {\n\t\t\t\tconst auto interactible = ashley::ComponentMapper<Interactible>::getMapper().get(e);\n\n\t\t\t\tif (interactible == nullptr) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tlistener->choice = e;\n\n\t\t\t\t\tswitch (interactible->type) {\n\t\t\t\t\tcase InteractionType::LOOT: {\n\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\"There's a chest here; open it? (Y\/N)\");\n\t\t\t\t\t\tlistener->state = PlayerInputState::RESPONDING;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase InteractionType::FIGHT: {\n\t\t\t\t\t\tbattleSystem->addAttack(Attack(entity, e));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tMessageHandler::globalHandler->addMessage(\"There's nothing there.\");\n\t\t}\n\t}\n\n\tif (interactionDone) {\n\t\tlistener->choice = nullptr;\n\t\tlistener->target.x = -1;\n\t\tlistener->target.y = -1;\n\t\tlistener->state = PlayerInputState::NORMAL;\n\t}\n}\n\nvoid rgl::PlayerInputSystem::processRespondingState(ashley::Entity * const &entity, float deltaTime,\n PlayerInputListener * const listener) {\n\tif (yPressed || nPressed) {\n\t\tif (yPressed) {\n\t\t\tconst auto targetTile = map->getTileAt(listener->target.x, listener->target.y);\n\t\t\tbool targetFound = false;\n\n\t\t\t\/\/ make sure the tile still contains the interaction choice.\n\t\t\tif (targetTile != nullptr && listener->choice != nullptr) {\n\t\t\t\tfor (const auto &content : targetTile->contains) {\n\t\t\t\t\tif (content == listener->choice) {\n\t\t\t\t\t\ttargetFound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (targetTile == nullptr || listener->choice == nullptr || !targetFound) {\n\t\t\t\tMessageHandler::globalHandler->addMessage(\"Huh? You could've sworn there was something here!\");\n\t\t\t} else {\n\t\t\t\t\/\/ interactible is still there so proceed with interaction.\n\t\t\t\tconst auto interactible = ashley::ComponentMapper<Interactible>::getMapper().get(listener->choice);\n\n\t\t\t\tswitch (interactible->type) {\n\t\t\t\tcase InteractionType::LOOT: {\n\t\t\t\t\tconst auto inventory = ashley::ComponentMapper<Inventory>::getMapper().get(listener->choice);\n\n\t\t\t\t\tif (inventory == nullptr || inventory->contents.empty()) {\n\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\"Seems to be empty...\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\"The chest creaks open.\");\n\t\t\t\t\t\tconst auto playerInventory = ashley::ComponentMapper<Inventory>::getMapper().get(entity);\n\n\t\t\t\t\t\tif (playerInventory != nullptr) {\n\t\t\t\t\t\t\tfor (const auto &item : inventory->contents) {\n\t\t\t\t\t\t\t\tMessageHandler::globalHandler->addObtainedMessage(item.name);\n\t\t\t\t\t\t\t\tplayerInventory->contents.push_back(item);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tinventory->contents.clear();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\/\/\t\t\t\tcase InteractionType::FIGHT: {\n\/\/\t\t\t\t\tconst auto battling = ashley::ComponentMapper<Battling>::getMapper().get(entity);\n\/\/\n\/\/\t\t\t\t\tif (battling == nullptr) {\n\/\/\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\n\/\/\t\t\t\t\t\t \"It looks defenceless... you can't bring yourself to attack it.\");\n\/\/\t\t\t\t\t} else {\n\/\/\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\"You bash it with your stick.\");\n\/\/\t\t\t\t\t}\n\/\/\n\/\/\t\t\t\t\tbreak;\n\/\/\t\t\t\t}\n\n\t\t\t\tdefault: {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (nPressed) {\n\t\t\tMessageHandler::globalHandler->addMessage(\"Never mind.\");\n\t\t}\n\n\t\tlistener->state = PlayerInputState::NORMAL;\n\t\tlistener->target.x = -1;\n\t\tlistener->target.y = -1;\n\t}\n}\n\nvoid rgl::PlayerInputSystem::update(float deltaTime) {\n\tTCOD_key_t key;\n\tTCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS, &key, nullptr);\n\n\tif (key.vk != TCODK_NONE) {\n\t\tif (key.vk == TCODK_CHAR) {\n\t\t\tswitch (key.c) {\n\t\t\tcase 'w':\n\t\t\tcase 'W': {\n\t\t\t\tkey.vk = TCODK_UP;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 's':\n\t\t\tcase 'S': {\n\t\t\t\tkey.vk = TCODK_DOWN;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'a':\n\t\t\tcase 'A': {\n\t\t\t\tkey.vk = TCODK_LEFT;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'd':\n\t\t\tcase 'D': {\n\t\t\t\tkey.vk = TCODK_RIGHT;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'y':\n\t\t\tcase 'Y': {\n\t\t\t\tyPressed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'n':\n\t\t\tcase 'N': {\n\t\t\t\tnPressed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tswitch (key.vk) {\n\t\tcase TCODK_UP: {\n\t\t\tupPressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_DOWN: {\n\t\t\tdownPressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_LEFT: {\n\t\t\tleftPressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_RIGHT: {\n\t\t\trightPressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_SPACE: {\n\t\t\tspacePressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_F5: {\n\t\t\tf5Pressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tashley::IteratingSystem::update(deltaTime);\n\n\t\tresetPressedKeys();\n\t}\n}\n<commit_msg>Remove extraneous include<commit_after>\/*\n * PlayerInputSystem.cpp\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Ashley Davis\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 all\n * 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 THE\n * SOFTWARE.\n *\/\n\n#include <cstdio>\n\n#include <Ashley\/core\/ComponentMapper.hpp>\n\n#include <glm\/vec2.hpp>\n#include <libtcod.hpp>\n\n#include \"components\/Position.hpp\"\n#include \"components\/PlayerInputListener.hpp\"\n#include \"components\/Inventory.hpp\"\n#include \"components\/Interactible.hpp\"\n#include \"components\/Battling.hpp\"\n\n#include \"systems\/PlayerInputSystem.hpp\"\n\n#include \"RGL.hpp\"\n#include \"Map.hpp\"\n#include \"Message.hpp\"\n\nvoid rgl::PlayerInputSystem::processEntity(ashley::Entity * const &entity, float deltaTime) {\n\tconst auto inputComponent = ashley::ComponentMapper<PlayerInputListener>::getMapper().get(entity);\n\n\tif (f5Pressed) {\n\t\tconst auto inventory = ashley::ComponentMapper<Inventory>::getMapper().get(entity);\n\n\t\tif (inventory != nullptr) {\n\t\t\tfor (const auto &item : inventory->contents) {\n\t\t\t\tRGLL->debug(\"Player has: %v\", item.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch (inputComponent->state) {\n\tcase PlayerInputState::NORMAL: {\n\t\tprocessNormalState(entity, deltaTime, inputComponent);\n\t\tbreak;\n\t}\n\n\tcase PlayerInputState::TARGETTING: {\n\t\tprocessTargettingState(entity, deltaTime, inputComponent);\n\t\tbreak;\n\t}\n\n\tcase PlayerInputState::RESPONDING: {\n\t\tprocessRespondingState(entity, deltaTime, inputComponent);\n\t\tbreak;\n\t}\n\n\tdefault: {\n\t\tRGLL->debug(\"Unhandled case in PlayerInputSystem switch.\");\n\t\tbreak;\n\t}\n}\n}\n\nvoid rgl::PlayerInputSystem::processNormalState(ashley::Entity * const &entity, float deltaTime,\n PlayerInputListener * const listener) {\n\tconst auto pos = ashley::ComponentMapper<Position>::getMapper().get(entity);\n\tglm::ivec2 target(pos->position);\n\n\tif (spacePressed) {\n\t\tlistener->state = PlayerInputState::TARGETTING;\n\t\treturn;\n\t} else if (upPressed) {\n\t\t--target.y;\n\t} else if (downPressed) {\n\t\t++target.y;\n\t} else if (leftPressed) {\n\t\t--target.x;\n\t} else if (rightPressed) {\n\t\t++target.x;\n\t}\n\n\t\/\/ check if target is clear\n\tif (target.x >= 0 && target.x < map->getWidth() && target.y >= 0 && target.y < map->getHeight()) {\n\t\tconst auto targetTile = map->getTileAt(target.x, target.y);\n\n\t\tif (targetTile != nullptr && !targetTile->solid) {\n\t\t\tpos->position = target;\n\t\t}\n\t}\n}\n\nvoid rgl::PlayerInputSystem::processTargettingState(ashley::Entity * const &entity, float deltaTime,\n PlayerInputListener * const listener) {\n\tconst auto pos = ashley::ComponentMapper<Position>::getMapper().get(entity);\n\tglm::ivec2 target(pos->position);\n\tbool interactionDone = false;\n\n\tif (spacePressed) {\n\t\tinteractionDone = true;\n\t} else if (upPressed) {\n\t\tinteractionDone = true;\n\t\t--target.y;\n\t} else if (downPressed) {\n\t\tinteractionDone = true;\n\t\t++target.y;\n\t} else if (leftPressed) {\n\t\tinteractionDone = true;\n\t\t--target.x;\n\t} else if (rightPressed) {\n\t\tinteractionDone = true;\n\t\t++target.x;\n\t}\n\n\tconst auto targetTile = map->getTileAt(target.x, target.y);\n\n\tif (targetTile != nullptr) {\n\t\tlistener->target = target;\n\n\t\tif (!targetTile->contains.empty()) {\n\t\t\tfor (const auto &e : targetTile->contains) {\n\t\t\t\tconst auto interactible = ashley::ComponentMapper<Interactible>::getMapper().get(e);\n\n\t\t\t\tif (interactible == nullptr) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tlistener->choice = e;\n\n\t\t\t\t\tswitch (interactible->type) {\n\t\t\t\t\tcase InteractionType::LOOT: {\n\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\"There's a chest here; open it? (Y\/N)\");\n\t\t\t\t\t\tlistener->state = PlayerInputState::RESPONDING;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase InteractionType::FIGHT: {\n\t\t\t\t\t\tbattleSystem->addAttack(Attack(entity, e));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tMessageHandler::globalHandler->addMessage(\"There's nothing there.\");\n\t\t}\n\t}\n\n\tif (interactionDone) {\n\t\tlistener->choice = nullptr;\n\t\tlistener->target.x = -1;\n\t\tlistener->target.y = -1;\n\t\tlistener->state = PlayerInputState::NORMAL;\n\t}\n}\n\nvoid rgl::PlayerInputSystem::processRespondingState(ashley::Entity * const &entity, float deltaTime,\n PlayerInputListener * const listener) {\n\tif (yPressed || nPressed) {\n\t\tif (yPressed) {\n\t\t\tconst auto targetTile = map->getTileAt(listener->target.x, listener->target.y);\n\t\t\tbool targetFound = false;\n\n\t\t\t\/\/ make sure the tile still contains the interaction choice.\n\t\t\tif (targetTile != nullptr && listener->choice != nullptr) {\n\t\t\t\tfor (const auto &content : targetTile->contains) {\n\t\t\t\t\tif (content == listener->choice) {\n\t\t\t\t\t\ttargetFound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (targetTile == nullptr || listener->choice == nullptr || !targetFound) {\n\t\t\t\tMessageHandler::globalHandler->addMessage(\"Huh? You could've sworn there was something here!\");\n\t\t\t} else {\n\t\t\t\t\/\/ interactible is still there so proceed with interaction.\n\t\t\t\tconst auto interactible = ashley::ComponentMapper<Interactible>::getMapper().get(listener->choice);\n\n\t\t\t\tswitch (interactible->type) {\n\t\t\t\tcase InteractionType::LOOT: {\n\t\t\t\t\tconst auto inventory = ashley::ComponentMapper<Inventory>::getMapper().get(listener->choice);\n\n\t\t\t\t\tif (inventory == nullptr || inventory->contents.empty()) {\n\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\"Seems to be empty...\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\"The chest creaks open.\");\n\t\t\t\t\t\tconst auto playerInventory = ashley::ComponentMapper<Inventory>::getMapper().get(entity);\n\n\t\t\t\t\t\tif (playerInventory != nullptr) {\n\t\t\t\t\t\t\tfor (const auto &item : inventory->contents) {\n\t\t\t\t\t\t\t\tMessageHandler::globalHandler->addObtainedMessage(item.name);\n\t\t\t\t\t\t\t\tplayerInventory->contents.push_back(item);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tinventory->contents.clear();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\/\/\t\t\t\tcase InteractionType::FIGHT: {\n\/\/\t\t\t\t\tconst auto battling = ashley::ComponentMapper<Battling>::getMapper().get(entity);\n\/\/\n\/\/\t\t\t\t\tif (battling == nullptr) {\n\/\/\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\n\/\/\t\t\t\t\t\t \"It looks defenceless... you can't bring yourself to attack it.\");\n\/\/\t\t\t\t\t} else {\n\/\/\t\t\t\t\t\tMessageHandler::globalHandler->addMessage(\"You bash it with your stick.\");\n\/\/\t\t\t\t\t}\n\/\/\n\/\/\t\t\t\t\tbreak;\n\/\/\t\t\t\t}\n\n\t\t\t\tdefault: {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (nPressed) {\n\t\t\tMessageHandler::globalHandler->addMessage(\"Never mind.\");\n\t\t}\n\n\t\tlistener->state = PlayerInputState::NORMAL;\n\t\tlistener->target.x = -1;\n\t\tlistener->target.y = -1;\n\t}\n}\n\nvoid rgl::PlayerInputSystem::update(float deltaTime) {\n\tTCOD_key_t key;\n\tTCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS, &key, nullptr);\n\n\tif (key.vk != TCODK_NONE) {\n\t\tif (key.vk == TCODK_CHAR) {\n\t\t\tswitch (key.c) {\n\t\t\tcase 'w':\n\t\t\tcase 'W': {\n\t\t\t\tkey.vk = TCODK_UP;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 's':\n\t\t\tcase 'S': {\n\t\t\t\tkey.vk = TCODK_DOWN;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'a':\n\t\t\tcase 'A': {\n\t\t\t\tkey.vk = TCODK_LEFT;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'd':\n\t\t\tcase 'D': {\n\t\t\t\tkey.vk = TCODK_RIGHT;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'y':\n\t\t\tcase 'Y': {\n\t\t\t\tyPressed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'n':\n\t\t\tcase 'N': {\n\t\t\t\tnPressed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tswitch (key.vk) {\n\t\tcase TCODK_UP: {\n\t\t\tupPressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_DOWN: {\n\t\t\tdownPressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_LEFT: {\n\t\t\tleftPressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_RIGHT: {\n\t\t\trightPressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_SPACE: {\n\t\t\tspacePressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase TCODK_F5: {\n\t\t\tf5Pressed = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tashley::IteratingSystem::update(deltaTime);\n\n\t\tresetPressedKeys();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <banman.h>\n#include <chainparams.h>\n#include <config.h>\n#include <consensus\/consensus.h>\n#include <net.h>\n#include <net_processing.h>\n#include <protocol.h>\n#include <scheduler.h>\n#include <script\/script.h>\n#include <streams.h>\n#include <validationinterface.h>\n#include <version.h>\n\n#include <test\/fuzz\/FuzzedDataProvider.h>\n#include <test\/fuzz\/fuzz.h>\n#include <test\/util\/mining.h>\n#include <test\/util\/net.h>\n#include <test\/util\/setup_common.h>\n\n#include <algorithm>\n#include <atomic>\n#include <cassert>\n#include <chrono>\n#include <cstdint>\n#include <iosfwd>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <set>\n#include <string>\n#include <vector>\n\nnamespace {\n\n#ifdef MESSAGE_TYPE\n#define TO_STRING_(s) #s\n#define TO_STRING(s) TO_STRING_(s)\nconst std::string LIMIT_TO_MESSAGE_TYPE{TO_STRING(MESSAGE_TYPE)};\n#else\nconst std::string LIMIT_TO_MESSAGE_TYPE;\n#endif\n\nconst std::map<std::string, std::set<std::string>>\n EXPECTED_DESERIALIZATION_EXCEPTIONS = {\n {\"CDataStream::read(): end of data: iostream error\",\n {\"addr\", \"block\", \"blocktxn\", \"cmpctblock\", \"feefilter\", \"filteradd\",\n \"filterload\", \"getblocks\", \"getblocktxn\", \"getdata\", \"getheaders\",\n \"headers\", \"inv\", \"notfound\", \"ping\", \"sendcmpct\", \"tx\"}},\n {\"CompactSize exceeds limit of type: iostream error\", {\"cmpctblock\"}},\n {\"differential value overflow: iostream error\", {\"getblocktxn\"}},\n {\"index overflowed 16 bits: iostream error\", {\"getblocktxn\"}},\n {\"index overflowed 16-bits: iostream error\", {\"cmpctblock\"}},\n {\"indexes overflowed 16 bits: iostream error\", {\"getblocktxn\"}},\n {\"non-canonical ReadCompactSize(): iostream error\",\n {\"addr\", \"block\", \"blocktxn\", \"cmpctblock\", \"filteradd\", \"filterload\",\n \"getblocks\", \"getblocktxn\", \"getdata\", \"getheaders\", \"headers\", \"inv\",\n \"notfound\", \"tx\"}},\n {\"ReadCompactSize(): size too large: iostream error\",\n {\"addr\", \"block\", \"blocktxn\", \"cmpctblock\", \"filteradd\", \"filterload\",\n \"getblocks\", \"getblocktxn\", \"getdata\", \"getheaders\", \"headers\", \"inv\",\n \"notfound\", \"tx\"}},\n {\"Superfluous witness record: iostream error\",\n {\"block\", \"blocktxn\", \"cmpctblock\", \"tx\"}},\n {\"Unknown transaction optional data: iostream error\",\n {\"block\", \"blocktxn\", \"cmpctblock\", \"tx\"}},\n};\n\nconst TestingSetup *g_setup;\n} \/\/ namespace\n\nvoid initialize() {\n static TestingSetup setup{\n CBaseChainParams::REGTEST,\n {\n \"-nodebuglogfile\",\n },\n };\n g_setup = &setup;\n\n for (int i = 0; i < 2 * COINBASE_MATURITY; i++) {\n MineBlock(GetConfig(), g_setup->m_node, CScript() << OP_TRUE);\n }\n SyncWithValidationInterfaceQueue();\n}\n\nvoid test_one_input(const std::vector<uint8_t> &buffer) {\n const Config &config = GetConfig();\n FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());\n ConnmanTestMsg &connman = *(ConnmanTestMsg *)g_setup->m_node.connman.get();\n const std::string random_message_type{\n fuzzed_data_provider.ConsumeBytesAsString(CMessageHeader::COMMAND_SIZE)\n .c_str()};\n if (!LIMIT_TO_MESSAGE_TYPE.empty() &&\n random_message_type != LIMIT_TO_MESSAGE_TYPE) {\n return;\n }\n CDataStream random_bytes_data_stream{\n fuzzed_data_provider.ConsumeRemainingBytes<uint8_t>(), SER_NETWORK,\n PROTOCOL_VERSION};\n CNode &p2p_node =\n *std::make_unique<CNode>(\n 0, ServiceFlags(NODE_NETWORK | NODE_BLOOM), 0, INVALID_SOCKET,\n CAddress{CService{in_addr{0x0100007f}, 7777}, NODE_NETWORK}, 0, 0,\n 0, CAddress{}, std::string{}, ConnectionType::OUTBOUND)\n .release();\n p2p_node.fSuccessfullyConnected = true;\n p2p_node.nVersion = PROTOCOL_VERSION;\n p2p_node.SetSendVersion(PROTOCOL_VERSION);\n connman.AddTestNode(p2p_node);\n g_setup->m_node.peer_logic->InitializeNode(config, &p2p_node);\n try {\n g_setup->m_node.peer_logic->ProcessMessage(\n config, p2p_node, random_message_type, random_bytes_data_stream,\n GetTimeMillis(), std::atomic<bool>{false});\n } catch (const std::ios_base::failure &e) {\n const std::string exception_message{e.what()};\n const auto p =\n EXPECTED_DESERIALIZATION_EXCEPTIONS.find(exception_message);\n if (p == EXPECTED_DESERIALIZATION_EXCEPTIONS.cend() ||\n p->second.count(random_message_type) == 0) {\n std::cout << \"Unexpected exception when processing message type \\\"\"\n << random_message_type << \"\\\": \" << exception_message\n << std::endl;\n assert(false);\n }\n }\n SyncWithValidationInterfaceQueue();\n \/\/ See init.cpp for rationale for implicit locking order requirement\n LOCK2(::cs_main, g_cs_orphans);\n g_setup->m_node.connman->StopNodes();\n}\n<commit_msg>fuzz: Remove enumeration of expected deserialization exceptions in ProcessMessage(...) fuzzer<commit_after>\/\/ Copyright (c) 2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <banman.h>\n#include <chainparams.h>\n#include <config.h>\n#include <consensus\/consensus.h>\n#include <net.h>\n#include <net_processing.h>\n#include <protocol.h>\n#include <scheduler.h>\n#include <script\/script.h>\n#include <streams.h>\n#include <validationinterface.h>\n#include <version.h>\n\n#include <test\/fuzz\/FuzzedDataProvider.h>\n#include <test\/fuzz\/fuzz.h>\n#include <test\/util\/mining.h>\n#include <test\/util\/net.h>\n#include <test\/util\/setup_common.h>\n\n#include <atomic>\n#include <cassert>\n#include <chrono>\n#include <cstdint>\n#include <iosfwd>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace {\n\n#ifdef MESSAGE_TYPE\n#define TO_STRING_(s) #s\n#define TO_STRING(s) TO_STRING_(s)\nconst std::string LIMIT_TO_MESSAGE_TYPE{TO_STRING(MESSAGE_TYPE)};\n#else\nconst std::string LIMIT_TO_MESSAGE_TYPE;\n#endif\n\nconst TestingSetup *g_setup;\n} \/\/ namespace\n\nvoid initialize() {\n static TestingSetup setup{\n CBaseChainParams::REGTEST,\n {\n \"-nodebuglogfile\",\n },\n };\n g_setup = &setup;\n\n for (int i = 0; i < 2 * COINBASE_MATURITY; i++) {\n MineBlock(GetConfig(), g_setup->m_node, CScript() << OP_TRUE);\n }\n SyncWithValidationInterfaceQueue();\n}\n\nvoid test_one_input(const std::vector<uint8_t> &buffer) {\n const Config &config = GetConfig();\n FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());\n ConnmanTestMsg &connman = *(ConnmanTestMsg *)g_setup->m_node.connman.get();\n const std::string random_message_type{\n fuzzed_data_provider.ConsumeBytesAsString(CMessageHeader::COMMAND_SIZE)\n .c_str()};\n if (!LIMIT_TO_MESSAGE_TYPE.empty() &&\n random_message_type != LIMIT_TO_MESSAGE_TYPE) {\n return;\n }\n CDataStream random_bytes_data_stream{\n fuzzed_data_provider.ConsumeRemainingBytes<uint8_t>(), SER_NETWORK,\n PROTOCOL_VERSION};\n CNode &p2p_node =\n *std::make_unique<CNode>(\n 0, ServiceFlags(NODE_NETWORK | NODE_BLOOM), 0, INVALID_SOCKET,\n CAddress{CService{in_addr{0x0100007f}, 7777}, NODE_NETWORK}, 0, 0,\n 0, CAddress{}, std::string{}, ConnectionType::OUTBOUND)\n .release();\n p2p_node.fSuccessfullyConnected = true;\n p2p_node.nVersion = PROTOCOL_VERSION;\n p2p_node.SetSendVersion(PROTOCOL_VERSION);\n connman.AddTestNode(p2p_node);\n g_setup->m_node.peer_logic->InitializeNode(config, &p2p_node);\n try {\n g_setup->m_node.peer_logic->ProcessMessage(\n config, p2p_node, random_message_type, random_bytes_data_stream,\n GetTimeMillis(), std::atomic<bool>{false});\n } catch (const std::ios_base::failure &) {\n }\n SyncWithValidationInterfaceQueue();\n \/\/ See init.cpp for rationale for implicit locking order requirement\n LOCK2(::cs_main, g_cs_orphans);\n g_setup->m_node.connman->StopNodes();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This File is part of Davix, The IO library for HTTP based protocols\n * Copyright (C) 2013 Adrien Devresse <adrien.devresse@cern.ch>, CERN\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*\/\n\n\n#include <davix_internal.hpp>\n#include <davix.hpp>\n#include <tools\/davix_tool_params.hpp>\n#include <tools\/davix_tool_util.hpp>\n#include <tools\/davix_taskqueue.hpp>\n#include <tools\/davix_op.hpp>\n#include <tools\/davix_thread_pool.hpp>\n#include <utils\/davix_logger_internal.hpp>\n\n\n\/\/ @author : Devresse Adrien\n\/\/ main file for davix-get operation\n\n\nusing namespace Davix;\nusing namespace std;\n\n#define READ_BLOCK_SIZE 4096\n\n\nconst std::string scope_get = \"Davix::Tools::davix-get\";\n\n\nstatic std::string help_msg(const std::string &cmd_path){\n std::string help_msg = fmt::format(\"Usage : {} \", cmd_path);\n help_msg += Tool::get_get_description_options();\n help_msg += Tool::get_common_options();\n\n return help_msg;\n}\n\nint get_output_get_fstream(const Tool::OptParams & opts, const std::string & scope, std::string uri, DavixError** err){\n int fd = -1;\n if(uri.empty() == false){\n if((fd = open(uri.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0777)) <0 ){\n davix_errno_to_davix_error(errno, scope, std::string(\"for destination file \").append(opts.output_file_path), err);\n return -1;\n }\n }else{\n fd = dup(STDOUT_FILENO);\n }\n return fd;\n}\n\nstatic int excute_get(Context& c, const Tool::OptParams & opts, int out_fd, std::string uri, DavixError** err){\n int ret;\n DavFile f(c, uri);\n ret = f.getToFd(&opts.params, out_fd, err);\n return (ret >= 0)?0:-1;\n}\n\nstatic int populateTaskQueue(Context& c, const Tool::OptParams & opts, std::string uri, DavixTaskQueue* tq, DavixError** err ){\n DAVIX_DIR* fd = NULL;\n DavPosix pos(&c);\n DavixError* tmp_err=NULL;\n std::string outputPath;\n struct stat st;\n struct dirent* d;\n int entry_counter=0;\n std::string last_success_entry;\n\n std::deque<std::pair<std::string,std::string> > dirQueue;\n std::deque<std::pair<std::string,std::string> > opQueue;\n\n outputPath = opts.output_file_path;\n\n \/\/ set up first entry\n if(!uri.empty()){\n \/\/ if output path is not specified, default to current directory\n if(outputPath.empty()){\n std::deque<std::string> dirVec;\n \n std::string tmp = Uri(uri).getPath();\n if(tmp == \"\/\"){ \/\/ no output path and no token in url to use as default, fallback to .\/temp\n outputPath = \".\/temp\";\n }\n else{\n Tool::tokeniseUrl(Uri(uri).getPath(), dirVec);\n outputPath = \".\/\"+dirVec.back();\n }\n }\n dirQueue.push_back(std::make_pair(uri, outputPath));\n }\n else\n DavixError::setupError(&tmp_err, \"Davix::Tool::Get\", StatusCode::InvalidArgument, \" target URL is empty.\");\n\n while(!dirQueue.empty()){\n if( (fd = pos.opendirpp(&opts.params, dirQueue.front().first, &tmp_err)) == NULL){\n Tool::errorPrint(&tmp_err);\n return -1;\n }\n\n \/\/ dir opened successfully, create local dir\n Tool::mkdirP(dirQueue.front().second, false);\n\n \/\/if S3, remove last token of url to accommodate duplicate token in d_name\n if (opts.params.getProtocol() == RequestProtocol::AwsS3){\n dirQueue.front().first = \"s3:\/\/\"+(Uri(dirQueue.front().first).getHost())+\"\/\";\n } \n\n while( ((d = pos.readdirpp(fd, &st, &tmp_err)) != NULL)){ \/\/ if one entry insidce a directory fails, the loop exits, the other entires are not processed\n\n last_success_entry = dirQueue.front().first+d->d_name;\n \/\/ for each entry, do a stat to see if it's a directory, if yes, push to dirQueue for further processing \n if(st.st_mode & S_IFDIR){\n DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, \"Directory entry found, pushing {}\/ to dirQueue\", dirQueue.front().first+d->d_name);\n dirQueue.push_back(std::make_pair(dirQueue.front().first+d->d_name+\"\/\",dirQueue.front().second+\"\/\"+d->d_name));\n }\n else if(!(st.st_mode & S_IFDIR)){\n \/\/if we spend too long in here, server will likely close the connection mid-readdirpp, need to get all the entries quickly before processing them\n opQueue.push_back(std::make_pair(dirQueue.front().first+d->d_name, dirQueue.front().second+\"\/\"+d->d_name));\n entry_counter++;\n }\n if(!opts.debug)\n Tool::batchTransferMonitor(dirQueue.front().first, \"Crawling\", entry_counter, 0);\n }\n \n if(tmp_err){\n Tool::errorPrint(&tmp_err);\n cerr << endl << \"Error occured during listing \" << dirQueue.front().first << \" Number of entries processed in current directory: \" << entry_counter << \". Continuing...\"<< endl;\n cerr << endl << \"Last succesful entry is \" << last_success_entry << endl;\n }\n\n entry_counter = 0;\n \n pos.closedirpp(fd, NULL);\n\n int num_of_ops = opQueue.size();\n\n for(std::deque<std::pair<std::string,std::string> >::iterator it = opQueue.begin(); it!=opQueue.end(); ++it){\n \/\/push op to task queue\n DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, \"Adding item to work queue, target is {} and destination is {}.\", opQueue.front().first, opQueue.front().second);\n GetOp* op = new GetOp(opts, (opQueue.front().first), (opQueue.front().second), c);\n tq->pushOp(op);\n opQueue.pop_front();\n\n entry_counter++;\n if(!opts.debug)\n Tool::batchTransferMonitor(dirQueue.front().first, \"Populating task queue for\", entry_counter, num_of_ops);\n }\n entry_counter = 0;\n dirQueue.pop_front();\n }\n if(tmp_err){\n DavixError::propagateError(err, tmp_err);\n return -1;\n }\n return 0;\n}\n\nstatic int preGetCheck(Tool::OptParams & opts, DavixError** err ){\n Context c;\n configureContext(c, opts);\n File f(c, opts.vec_arg[0]);\n struct stat st; \n DavixError* tmp_err=NULL;\n \n \n \/\/ Try to understand what to do\n \/\/ If the URL is for plain HTTP then we don't want to stat\n bool justgetfile = true;\n cout << \"---------------------\" << opts.vec_arg[0] << \"---------------\" << endl;\n if ( opts.vec_arg[0].compare(0, 4, \"http\") != 0 ) {\n int r = f.stat(&opts.params, &st, &tmp_err);\n \n if (r && tmp_err) {\n DavixError::propagateError(err, tmp_err);\n return -1;\n }\n \n \n if ( !r && (st.st_mode & S_IFDIR) ) justgetfile = false;\n }\n \n if (justgetfile) {\n \/\/ target resource is a file or request protocol is http, just get it normally\n int out_fd= -1;\n if( ( (out_fd = get_output_get_fstream(opts, scope_get, opts.output_file_path, &tmp_err)) > 0)\n && (Tool::configureMonitorCB(opts, Transfer::Read)) == 0){\n excute_get(c, opts, out_fd, opts.vec_arg[0], &tmp_err);\n Tool::flushFinalLineShell(out_fd);\n close(out_fd);\n }\n }\n else {\n \n \n std::string url(opts.vec_arg[0]);\n \n if (url[url.size()-1] != '\/')\n url += '\/';\n \n DavixTaskQueue tq;\n \n \/\/ create threadpool instance \n DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, \"Creating threadpool\");\n DavixThreadPool tp(&tq);\n \n \/\/ if protocol is S3, set listing mode to SemiHierarchical, we want to get every object under the same prefix in one go\n if (opts.params.getProtocol() == RequestProtocol::AwsS3){\n opts.params.setS3ListingMode(S3ListingMode::SemiHierarchical);\n \/\/ unfortunately s3 defaults max-keys to 1000 and doesn't provide a way to disable the cap, set to large number\n opts.params.setS3MaxKey(999999999); \n }\n \n populateTaskQueue(c, opts, url, &tq, &tmp_err);\n \n \/\/ if task queue is empty, then all work is done, stop workers. Otherwise wait.\n while(!tq.isEmpty()){\n sleep(2);\n }\n tp.shutdown();\n Tool::flushFinalLineShell(STDOUT_FILENO);\n } \n \n if(tmp_err){\n DavixError::propagateError(err, tmp_err);\n return -1;\n }\n return 0;\n}\n\nint main(int argc, char** argv){\n int retcode=-1;\n Tool::OptParams opts;\n DavixError* tmp_err=NULL;\n opts.help_msg = help_msg(argv[0]);\n\n if( (retcode= Tool::parse_davix_get_options(argc, argv, opts, &tmp_err)) ==0\n && (retcode = Tool::configureAuth(opts)) == 0){\n retcode = preGetCheck(opts, &tmp_err);\n }\n Tool::errorPrint(&tmp_err);\n\n return retcode;\n}\n\n<commit_msg>Fix indentation Remove forgotten cout<commit_after>\/*\n * This File is part of Davix, The IO library for HTTP based protocols\n * Copyright (C) 2013 Adrien Devresse <adrien.devresse@cern.ch>, CERN\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*\/\n\n\n#include <davix_internal.hpp>\n#include <davix.hpp>\n#include <tools\/davix_tool_params.hpp>\n#include <tools\/davix_tool_util.hpp>\n#include <tools\/davix_taskqueue.hpp>\n#include <tools\/davix_op.hpp>\n#include <tools\/davix_thread_pool.hpp>\n#include <utils\/davix_logger_internal.hpp>\n\n\n\/\/ @author : Devresse Adrien\n\/\/ main file for davix-get operation\n\n\nusing namespace Davix;\nusing namespace std;\n\n#define READ_BLOCK_SIZE 4096\n\n\nconst std::string scope_get = \"Davix::Tools::davix-get\";\n\n\nstatic std::string help_msg(const std::string &cmd_path){\n std::string help_msg = fmt::format(\"Usage : {} \", cmd_path);\n help_msg += Tool::get_get_description_options();\n help_msg += Tool::get_common_options();\n\n return help_msg;\n}\n\nint get_output_get_fstream(const Tool::OptParams & opts, const std::string & scope, std::string uri, DavixError** err){\n int fd = -1;\n if(uri.empty() == false){\n if((fd = open(uri.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0777)) <0 ){\n davix_errno_to_davix_error(errno, scope, std::string(\"for destination file \").append(opts.output_file_path), err);\n return -1;\n }\n }else{\n fd = dup(STDOUT_FILENO);\n }\n return fd;\n}\n\nstatic int excute_get(Context& c, const Tool::OptParams & opts, int out_fd, std::string uri, DavixError** err){\n int ret;\n DavFile f(c, uri);\n ret = f.getToFd(&opts.params, out_fd, err);\n return (ret >= 0)?0:-1;\n}\n\nstatic int populateTaskQueue(Context& c, const Tool::OptParams & opts, std::string uri, DavixTaskQueue* tq, DavixError** err ){\n DAVIX_DIR* fd = NULL;\n DavPosix pos(&c);\n DavixError* tmp_err=NULL;\n std::string outputPath;\n struct stat st;\n struct dirent* d;\n int entry_counter=0;\n std::string last_success_entry;\n\n std::deque<std::pair<std::string,std::string> > dirQueue;\n std::deque<std::pair<std::string,std::string> > opQueue;\n\n outputPath = opts.output_file_path;\n\n \/\/ set up first entry\n if(!uri.empty()){\n \/\/ if output path is not specified, default to current directory\n if(outputPath.empty()){\n std::deque<std::string> dirVec;\n \n std::string tmp = Uri(uri).getPath();\n if(tmp == \"\/\"){ \/\/ no output path and no token in url to use as default, fallback to .\/temp\n outputPath = \".\/temp\";\n }\n else{\n Tool::tokeniseUrl(Uri(uri).getPath(), dirVec);\n outputPath = \".\/\"+dirVec.back();\n }\n }\n dirQueue.push_back(std::make_pair(uri, outputPath));\n }\n else\n DavixError::setupError(&tmp_err, \"Davix::Tool::Get\", StatusCode::InvalidArgument, \" target URL is empty.\");\n\n while(!dirQueue.empty()){\n if( (fd = pos.opendirpp(&opts.params, dirQueue.front().first, &tmp_err)) == NULL){\n Tool::errorPrint(&tmp_err);\n return -1;\n }\n\n \/\/ dir opened successfully, create local dir\n Tool::mkdirP(dirQueue.front().second, false);\n\n \/\/if S3, remove last token of url to accommodate duplicate token in d_name\n if (opts.params.getProtocol() == RequestProtocol::AwsS3){\n dirQueue.front().first = \"s3:\/\/\"+(Uri(dirQueue.front().first).getHost())+\"\/\";\n } \n\n while( ((d = pos.readdirpp(fd, &st, &tmp_err)) != NULL)){ \/\/ if one entry insidce a directory fails, the loop exits, the other entires are not processed\n\n last_success_entry = dirQueue.front().first+d->d_name;\n \/\/ for each entry, do a stat to see if it's a directory, if yes, push to dirQueue for further processing \n if(st.st_mode & S_IFDIR){\n DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, \"Directory entry found, pushing {}\/ to dirQueue\", dirQueue.front().first+d->d_name);\n dirQueue.push_back(std::make_pair(dirQueue.front().first+d->d_name+\"\/\",dirQueue.front().second+\"\/\"+d->d_name));\n }\n else if(!(st.st_mode & S_IFDIR)){\n \/\/if we spend too long in here, server will likely close the connection mid-readdirpp, need to get all the entries quickly before processing them\n opQueue.push_back(std::make_pair(dirQueue.front().first+d->d_name, dirQueue.front().second+\"\/\"+d->d_name));\n entry_counter++;\n }\n if(!opts.debug)\n Tool::batchTransferMonitor(dirQueue.front().first, \"Crawling\", entry_counter, 0);\n }\n \n if(tmp_err){\n Tool::errorPrint(&tmp_err);\n cerr << endl << \"Error occured during listing \" << dirQueue.front().first << \" Number of entries processed in current directory: \" << entry_counter << \". Continuing...\"<< endl;\n cerr << endl << \"Last succesful entry is \" << last_success_entry << endl;\n }\n\n entry_counter = 0;\n \n pos.closedirpp(fd, NULL);\n\n int num_of_ops = opQueue.size();\n\n for(std::deque<std::pair<std::string,std::string> >::iterator it = opQueue.begin(); it!=opQueue.end(); ++it){\n \/\/push op to task queue\n DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, \"Adding item to work queue, target is {} and destination is {}.\", opQueue.front().first, opQueue.front().second);\n GetOp* op = new GetOp(opts, (opQueue.front().first), (opQueue.front().second), c);\n tq->pushOp(op);\n opQueue.pop_front();\n\n entry_counter++;\n if(!opts.debug)\n Tool::batchTransferMonitor(dirQueue.front().first, \"Populating task queue for\", entry_counter, num_of_ops);\n }\n entry_counter = 0;\n dirQueue.pop_front();\n }\n if(tmp_err){\n DavixError::propagateError(err, tmp_err);\n return -1;\n }\n return 0;\n}\n\nstatic int preGetCheck(Tool::OptParams & opts, DavixError** err ) {\n Context c;\n configureContext(c, opts);\n File f(c, opts.vec_arg[0]);\n struct stat st; \n DavixError* tmp_err=NULL;\n \n \n \/\/ Try to understand what to do\n \/\/ If the URL is for plain HTTP then we don't want to stat\n bool justgetfile = true;\n \n if ( opts.vec_arg[0].compare(0, 4, \"http\") != 0 ) {\n int r = f.stat(&opts.params, &st, &tmp_err); \n if (r && tmp_err) {\n DavixError::propagateError(err, tmp_err);\n return -1;\n }\n \n if ( !r && (st.st_mode & S_IFDIR) ) justgetfile = false;\n }\n \n if (justgetfile) {\n \/\/ target resource is a file or request protocol is http, just get it normally\n int out_fd= -1;\n if( ( (out_fd = get_output_get_fstream(opts, scope_get, opts.output_file_path, &tmp_err)) > 0)\n && (Tool::configureMonitorCB(opts, Transfer::Read)) == 0) {\n \n excute_get(c, opts, out_fd, opts.vec_arg[0], &tmp_err);\n Tool::flushFinalLineShell(out_fd);\n close(out_fd);\n }\n }\n else {\n \n std::string url(opts.vec_arg[0]);\n \n if (url[url.size()-1] != '\/')\n url += '\/';\n \n DavixTaskQueue tq;\n \n \/\/ create threadpool instance \n DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, \"Creating threadpool\");\n DavixThreadPool tp(&tq);\n \n \/\/ if protocol is S3, set listing mode to SemiHierarchical, we want to get every object under the same prefix in one go\n if (opts.params.getProtocol() == RequestProtocol::AwsS3){\n opts.params.setS3ListingMode(S3ListingMode::SemiHierarchical);\n \/\/ unfortunately s3 defaults max-keys to 1000 and doesn't provide a way to disable the cap, set to large number\n opts.params.setS3MaxKey(999999999); \n }\n \n populateTaskQueue(c, opts, url, &tq, &tmp_err);\n \n \/\/ if task queue is empty, then all work is done, stop workers. Otherwise wait.\n while(!tq.isEmpty()){\n sleep(2);\n }\n tp.shutdown();\n Tool::flushFinalLineShell(STDOUT_FILENO);\n } \n \n if(tmp_err){\n DavixError::propagateError(err, tmp_err);\n return -1;\n }\n return 0;\n}\n\nint main(int argc, char** argv){\n int retcode=-1;\n Tool::OptParams opts;\n DavixError* tmp_err=NULL;\n opts.help_msg = help_msg(argv[0]);\n\n if( (retcode= Tool::parse_davix_get_options(argc, argv, opts, &tmp_err)) ==0\n && (retcode = Tool::configureAuth(opts)) == 0){\n retcode = preGetCheck(opts, &tmp_err);\n }\n Tool::errorPrint(&tmp_err);\n\n return retcode;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"serverConnection.h\"\n#include <vector>\n#include <boost\/bind.hpp>\n#include <boost\/foreach.hpp>\n\n#include <libwatcher\/message.h>\n#include <libwatcher\/messageStatus.h>\n#include <libwatcher\/seekWatcherMessage.h>\n#include <libwatcher\/speedWatcherMessage.h>\n#include <libwatcher\/nodeStatusMessage.h>\n\n#include \"watcherd.h\"\n#include \"writeDBMessageHandler.h\"\n#include \"watcherdConfig.h\"\n#include \"replayState.h\"\n\nusing namespace std; \nusing namespace boost::asio;\n\nnamespace {\n using namespace watcher::event;\n\n \/* Grr, because there is no std::copy_if have to use the negation with\n * remove_copy_if() *\/\n bool not_feeder_message(const MessagePtr& m)\n {\n return !isFeederEvent(m->type);\n }\n}\n\nnamespace watcher {\n using namespace event;\n\n INIT_LOGGER(ServerConnection, \"Connection.ServerConnection\");\n\n ServerConnection::ServerConnection(Watcherd& w, boost::asio::io_service& io_service) :\n Connection(io_service),\n watcher(w),\n io_service_(io_service),\n strand_(io_service),\n write_strand_(io_service),\n conn_type(unknown),\n isPlaying_(false), isLive_(true)\n {\n TRACE_ENTER(); \n TRACE_EXIT();\n }\n\n ServerConnection::~ServerConnection()\n {\n TRACE_ENTER();\n \/\/shared_from_this() not allowed in destructor\n \/\/watcher.unsubscribe(shared_from_this());\n TRACE_EXIT();\n }\n\n \/** Initialization point for start of new ServerConnection thread. *\/\n void ServerConnection::run()\n {\n TRACE_ENTER(); \n boost::asio::async_read(\n theSocket, \n boost::asio::buffer(incomingBuffer, DataMarshaller::header_length),\n strand_.wrap(\n boost::bind(\n &ServerConnection::handle_read_header, \n shared_from_this(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred)));\n TRACE_EXIT();\n }\n\n void ServerConnection::read_error(const boost::system::error_code &e)\n {\n TRACE_ENTER();\n\n if (e == boost::asio::error::eof)\n {\n LOG_DEBUG(\"Received empty message from client or client closed connection.\");\n LOG_INFO(\"Connection to client closed.\"); \n\n }\n else\n {\n LOG_ERROR(\"Error reading socket: \" << e.message());\n }\n\n \/\/ unsubscribe to event stream, otherwise it will hold a\n \/\/ shared_ptr open\n if (conn_type == gui)\n watcher.unsubscribe(shared_from_this());\n\n TRACE_EXIT();\n }\n\n void ServerConnection::handle_read_header(const boost::system::error_code& e, size_t bytes_transferred)\n {\n TRACE_ENTER(); \n if (!e)\n {\n LOG_DEBUG(\"Read \" << bytes_transferred << \" bytes.\"); \n\n size_t payloadSize;\n unsigned short numOfMessages;\n if (!DataMarshaller::unmarshalHeader(incomingBuffer.begin(), bytes_transferred, payloadSize, numOfMessages))\n {\n LOG_ERROR(\"Error parsing incoming message header.\");\n\n if (conn_type == gui)\n watcher.unsubscribe(shared_from_this());\n }\n else\n {\n LOG_DEBUG(\"Reading packet payload of \" << payloadSize << \" bytes.\");\n\n boost::asio::async_read(\n theSocket, \n boost::asio::buffer(\n incomingBuffer, \n payloadSize), \/\/ Should incoming buffer be new'd()? \n strand_.wrap(\n boost::bind(\n &ServerConnection::handle_read_payload,\n shared_from_this(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred, \n numOfMessages)));\n }\n }\n else\n read_error(e);\n TRACE_EXIT();\n }\n\n void ServerConnection::seek(event::MessagePtr& m)\n {\n TRACE_ENTER();\n SeekMessagePtr p = boost::dynamic_pointer_cast<SeekMessage>(m);\n if (p) {\n if (p->offset == SeekMessage::eof) {\n if (isLive_) {\n \/\/ nothing to do\n } else if (replay->speed() >= 0) {\n \/\/ switch to live stream\n isLive_ = true;\n replay->pause();\n if (isPlaying_)\n watcher.subscribe(shared_from_this());\n } else {\n replay->seek( SeekMessage::eof );\n }\n } else {\n replay->seek(p->offset);\n\n \/\/ when switching from live to replay while playing, kick off the replay strand\n if (isLive_ && isPlaying_)\n replay->run();\n isLive_ = false;\n }\n } else {\n LOG_WARN(\"unable to dynamic_pointer_cast to SeekMessage!\");\n }\n TRACE_EXIT();\n }\n\n void ServerConnection::start(event::MessagePtr&)\n {\n TRACE_ENTER();\n LOG_DEBUG(\"in: isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n if (!isPlaying_) {\n isPlaying_ = true;\n if (isLive_)\n watcher.subscribe(shared_from_this());\n else\n replay->run();\n }\n LOG_DEBUG(\"out: isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n TRACE_EXIT();\n }\n\n void ServerConnection::stop(event::MessagePtr&)\n {\n TRACE_ENTER();\n LOG_DEBUG(\"isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n if (isPlaying_) {\n LOG_DEBUG(\"stopping playback\");\n if (isLive_)\n watcher.unsubscribe(shared_from_this());\n else\n replay->pause();\n isPlaying_ = false;\n } else\n LOG_DEBUG(\"stop message received, but playback is stopped\");\n LOG_DEBUG(\"out: isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n TRACE_EXIT();\n }\n\n void ServerConnection::speed(event::MessagePtr& m)\n {\n TRACE_ENTER();\n LOG_DEBUG(\"isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n SpeedMessagePtr p = boost::dynamic_pointer_cast<SpeedMessage>(m);\n if (p) {\n if (isLive_ && p->speed >= 1.0f) {\n \/\/ ignore, can't predict the future\n } else {\n replay->speed(p->speed);\n if (isLive_) {\n isLive_ = false;\n \/* when transitioning from live playback, automatically\n * seek to the end of the database.\n *\/\n replay->seek( SeekMessage::eof );\n if (isPlaying_)\n replay->run();\n }\n }\n } else {\n LOG_WARN(\"unable to dynamic_pointer_cast to SpeedMessage!\");\n }\n LOG_DEBUG(\"out: isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n TRACE_EXIT();\n }\n\n bool ServerConnection::dispatch_gui_event(MessagePtr& m)\n {\n static const struct {\n MessageType type;\n void (ServerConnection::*fn)(event::MessagePtr&);\n } dispatch[] = {\n { START_MESSAGE_TYPE, &ServerConnection::start },\n { STOP_MESSAGE_TYPE, &ServerConnection::stop },\n { SEEK_MESSAGE_TYPE, &ServerConnection::seek },\n { SPEED_MESSAGE_TYPE, &ServerConnection::speed },\n { UNKNOWN_MESSAGE_TYPE, 0 }\n };\n\n TRACE_ENTER();\n\n for (size_t i = 0; dispatch[i].type != UNKNOWN_MESSAGE_TYPE; ++i) {\n if (m->type == dispatch[i].type) {\n if (conn_type == unknown) {\n conn_type = gui;\n replay.reset(new ReplayState(shared_from_this()));\n }\n (this->*(dispatch[i].fn)) (m);\n TRACE_EXIT_RET_BOOL(true);\n return true;\n }\n }\n TRACE_EXIT_RET_BOOL(false);\n return false;\n }\n\n void ServerConnection::handle_read_payload(const boost::system::error_code& e, size_t bytes_transferred, unsigned short numOfMessages)\n {\n TRACE_ENTER();\n\n if (!e)\n {\n vector<MessagePtr> arrivedMessages; \n if (DataMarshaller::unmarshalPayload(arrivedMessages, numOfMessages, incomingBuffer.begin(), bytes_transferred))\n {\n LOG_INFO(\"Recvd \" << arrivedMessages.size() << \" message\" <<\n (arrivedMessages.size()>1?\"s\":\"\") << \" from \" <<\n remoteEndpoint().address()); \n\n \/\/ Add the incoming address to the Message so everyone\n \/\/ knows who the message came from.\n boost::asio::ip::tcp::endpoint ep = getSocket().remote_endpoint();\n BOOST_FOREACH(MessagePtr m, arrivedMessages) {\n if(m->fromNodeID==NodeIdentifier()) \/\/ is empty\n m->fromNodeID=ep.address();\n }\n\n \/*\n * If this connection type is unknown or gui, then traverse the\n * list of arrived messages. For GUI clients, look for the\n * STOP_MESSAGE to unsubscribe from the event stream.\n *\n * For unknown clients, infer the type from the message\n * received:\n * START_MESSAGE => gui\n * isFeederMessage => feeder\n *\/\n if (conn_type == unknown || conn_type == gui) {\n BOOST_FOREACH(MessagePtr& i, arrivedMessages) {\n if (dispatch_gui_event(i)) {\n \/\/empty\n } else if (isFeederEvent(i->type)) {\n conn_type = feeder;\n\n \/*\n * This connection is a watcher test daemon.\n * Add a message handler to write its event\n * stream to the database.\n *\/\n addMessageHandler(MessageHandlerPtr(new WriteDBMessageHandler()));\n }\n }\n }\n\n \/* Flag indicating whether to continue reading from this\n * connection. *\/\n bool fail = false;\n\n BOOST_FOREACH(MessageHandlerPtr& mh, messageHandlers) {\n if (mh->handleMessagesArrive(shared_from_this(), arrivedMessages)) {\n fail = true;\n LOG_DEBUG(\"Message handler told us to close this connection.\"); \n }\n }\n\n if (!fail) {\n \/\/ initiate request to read next message\n LOG_DEBUG(\"Waiting for next message.\");\n run();\n }\n\n if (conn_type == feeder) {\n \/* relay feeder message to any client requesting the live stream.\n * Warning: currently there is no check to make sure that a client doesn't\n * receive a message it just sent. This should be OK since we are just\n * relaying feeder messages only, and the GUIs should not be sending\n * them. *\/\n vector<MessagePtr> feeder;\n remove_copy_if(arrivedMessages.begin(), arrivedMessages.end(), back_inserter(feeder), not_feeder_message);\n if (! feeder.empty()) {\n LOG_DEBUG(\"Sending \" << feeder.size() << \" feeder messages to clients.\");\n watcher.sendMessage(feeder);\n }\n }\n }\n }\n else\n read_error(e);\n\n \/\/ If an error occurs then no new asynchronous operations are started. This\n \/\/ means that all shared_ptr references to the ServerConnection object will\n \/\/ disappear and the object will be destroyed automatically after this\n \/\/ handler returns. The ServerConnection class's destructor closes the socket.\n\n TRACE_EXIT();\n }\n\n void ServerConnection::handle_write(const boost::system::error_code& e, MessagePtr message)\n {\n TRACE_ENTER(); \n\n if (!e)\n {\n LOG_DEBUG(\"Successfully sent message to client: \" << message); \n\n BOOST_FOREACH(MessageHandlerPtr mh, messageHandlers)\n {\n#if 0\n \/* melkins\n * The reads and writes to the socket are asynchronous, so\n * we should never be waiting for something to be read as\n * a result of a write.\n *\/\n if(waitForResponse) \/\/ someone already said they wanted a response, so ignore ret val for others\n mh->handleMessageSent(message);\n else\n waitForResponse=mh->handleMessageSent(message);\n#endif\n mh->handleMessageSent(message);\n }\n\n \/\/ melkins\n \/\/ start() calls async_read(), which is not what we want to do here\n \/*\n if(waitForResponse)\n start(); \n *\/\n }\n else\n {\n LOG_WARN(\"Error while sending response to client: \" << e);\n if (conn_type == gui)\n watcher.unsubscribe(shared_from_this());\n }\n\n \/\/ No new asynchronous operations are started. This means that all shared_ptr\n \/\/ references to the connection object will disappear and the object will be\n \/\/ destroyed automatically after this handler returns. The connection class's\n \/\/ destructor closes the socket.\n\n \/* NOTE: The refcount will not go to zero so long as there is an\n * async_read operation also oustanding. *\/\n\n TRACE_EXIT();\n }\n\n \/** Send a single message to this connected client. *\/\n void ServerConnection::sendMessage(MessagePtr msg)\n {\n TRACE_ENTER();\n DataMarshaller::NetworkMarshalBuffers outBuffers;\n DataMarshaller::marshalPayload(msg, outBuffers);\n\n \/\/\/ FIXME melkins 2004-04-19\n \/\/ is it safe to call async_write and async_read from different\n \/\/ threads at the same time? asio::tcp::socket() is listed at not\n \/\/ shared thread safe\n async_write(theSocket,\n outBuffers,\n write_strand_.wrap( boost::bind( &ServerConnection::handle_write,\n shared_from_this(),\n placeholders::error,\n msg)));\n TRACE_EXIT();\n }\n\n \/** Send a set of messages to this connected client. *\/\n void ServerConnection::sendMessage(const std::vector<MessagePtr>& msgs)\n {\n TRACE_ENTER();\n DataMarshaller::NetworkMarshalBuffers outBuffers;\n DataMarshaller::marshalPayload(msgs, outBuffers);\n\n \/\/\/ FIXME melkins 2004-04-19\n \/\/ is it safe to call async_write and async_read from different\n \/\/ threads at the same time?\n async_write(theSocket,\n outBuffers,\n write_strand_.wrap( boost::bind( &ServerConnection::handle_write,\n shared_from_this(),\n placeholders::error,\n msgs.front())));\n TRACE_EXIT();\n }\n\n}\n<commit_msg>save timestamp when receiving StopMessage during live playback so the next StartMessage resumes from the db at the proper location<commit_after>#include \"serverConnection.h\"\n#include <vector>\n#include <boost\/bind.hpp>\n#include <boost\/foreach.hpp>\n\n#include <libwatcher\/message.h>\n#include <libwatcher\/messageStatus.h>\n#include <libwatcher\/seekWatcherMessage.h>\n#include <libwatcher\/speedWatcherMessage.h>\n#include <libwatcher\/nodeStatusMessage.h>\n\n#include \"watcherd.h\"\n#include \"writeDBMessageHandler.h\"\n#include \"watcherdConfig.h\"\n#include \"replayState.h\"\n\nusing namespace std; \nusing namespace boost::asio;\n\nnamespace {\n using namespace watcher::event;\n\n \/* Grr, because there is no std::copy_if have to use the negation with\n * remove_copy_if() *\/\n bool not_feeder_message(const MessagePtr& m)\n {\n return !isFeederEvent(m->type);\n }\n}\n\nnamespace watcher {\n using namespace event;\n\n INIT_LOGGER(ServerConnection, \"Connection.ServerConnection\");\n\n ServerConnection::ServerConnection(Watcherd& w, boost::asio::io_service& io_service) :\n Connection(io_service),\n watcher(w),\n io_service_(io_service),\n strand_(io_service),\n write_strand_(io_service),\n conn_type(unknown),\n isPlaying_(false), isLive_(true)\n {\n TRACE_ENTER(); \n TRACE_EXIT();\n }\n\n ServerConnection::~ServerConnection()\n {\n TRACE_ENTER();\n \/\/shared_from_this() not allowed in destructor\n \/\/watcher.unsubscribe(shared_from_this());\n TRACE_EXIT();\n }\n\n \/** Initialization point for start of new ServerConnection thread. *\/\n void ServerConnection::run()\n {\n TRACE_ENTER(); \n boost::asio::async_read(\n theSocket, \n boost::asio::buffer(incomingBuffer, DataMarshaller::header_length),\n strand_.wrap(\n boost::bind(\n &ServerConnection::handle_read_header, \n shared_from_this(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred)));\n TRACE_EXIT();\n }\n\n void ServerConnection::read_error(const boost::system::error_code &e)\n {\n TRACE_ENTER();\n\n if (e == boost::asio::error::eof)\n {\n LOG_DEBUG(\"Received empty message from client or client closed connection.\");\n LOG_INFO(\"Connection to client closed.\"); \n\n }\n else\n {\n LOG_ERROR(\"Error reading socket: \" << e.message());\n }\n\n \/\/ unsubscribe to event stream, otherwise it will hold a\n \/\/ shared_ptr open\n if (conn_type == gui)\n watcher.unsubscribe(shared_from_this());\n\n TRACE_EXIT();\n }\n\n void ServerConnection::handle_read_header(const boost::system::error_code& e, size_t bytes_transferred)\n {\n TRACE_ENTER(); \n if (!e)\n {\n LOG_DEBUG(\"Read \" << bytes_transferred << \" bytes.\"); \n\n size_t payloadSize;\n unsigned short numOfMessages;\n if (!DataMarshaller::unmarshalHeader(incomingBuffer.begin(), bytes_transferred, payloadSize, numOfMessages))\n {\n LOG_ERROR(\"Error parsing incoming message header.\");\n\n if (conn_type == gui)\n watcher.unsubscribe(shared_from_this());\n }\n else\n {\n LOG_DEBUG(\"Reading packet payload of \" << payloadSize << \" bytes.\");\n\n boost::asio::async_read(\n theSocket, \n boost::asio::buffer(\n incomingBuffer, \n payloadSize), \/\/ Should incoming buffer be new'd()? \n strand_.wrap(\n boost::bind(\n &ServerConnection::handle_read_payload,\n shared_from_this(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred, \n numOfMessages)));\n }\n }\n else\n read_error(e);\n TRACE_EXIT();\n }\n\n void ServerConnection::seek(event::MessagePtr& m)\n {\n TRACE_ENTER();\n SeekMessagePtr p = boost::dynamic_pointer_cast<SeekMessage>(m);\n if (p) {\n if (p->offset == SeekMessage::eof) {\n if (isLive_) {\n \/\/ nothing to do\n } else if (replay->speed() >= 0) {\n \/\/ switch to live stream\n isLive_ = true;\n replay->pause();\n if (isPlaying_)\n watcher.subscribe(shared_from_this());\n } else {\n replay->seek( SeekMessage::eof );\n }\n } else {\n replay->seek(p->offset);\n\n \/\/ when switching from live to replay while playing, kick off the replay strand\n if (isLive_ && isPlaying_)\n replay->run();\n isLive_ = false;\n }\n } else {\n LOG_WARN(\"unable to dynamic_pointer_cast to SeekMessage!\");\n }\n TRACE_EXIT();\n }\n\n void ServerConnection::start(event::MessagePtr&)\n {\n TRACE_ENTER();\n LOG_DEBUG(\"in: isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n if (!isPlaying_) {\n isPlaying_ = true;\n if (isLive_)\n watcher.subscribe(shared_from_this());\n else\n replay->run();\n }\n LOG_DEBUG(\"out: isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n TRACE_EXIT();\n }\n\n void ServerConnection::stop(event::MessagePtr&)\n {\n TRACE_ENTER();\n LOG_DEBUG(\"isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n if (isPlaying_) {\n LOG_DEBUG(\"stopping playback\");\n if (isLive_) {\n watcher.unsubscribe(shared_from_this());\n \/* save current Timestamp so we can resume from the database *\/\n isLive_ = false;\n replay->seek( getCurrentTime() );\n } else\n replay->pause();\n isPlaying_ = false;\n } else\n LOG_DEBUG(\"stop message received, but playback is stopped\");\n LOG_DEBUG(\"out: isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n TRACE_EXIT();\n }\n\n void ServerConnection::speed(event::MessagePtr& m)\n {\n TRACE_ENTER();\n LOG_DEBUG(\"isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n SpeedMessagePtr p = boost::dynamic_pointer_cast<SpeedMessage>(m);\n if (p) {\n if (isLive_ && p->speed >= 1.0f) {\n \/\/ ignore, can't predict the future\n } else {\n replay->speed(p->speed);\n if (isLive_) {\n isLive_ = false;\n \/* when transitioning from live playback, automatically\n * seek to the end of the database.\n *\/\n replay->seek( SeekMessage::eof );\n if (isPlaying_)\n replay->run();\n }\n }\n } else {\n LOG_WARN(\"unable to dynamic_pointer_cast to SpeedMessage!\");\n }\n LOG_DEBUG(\"out: isPlaying_=\" << isPlaying_ << \", isLive_=\" << isLive_);\n TRACE_EXIT();\n }\n\n bool ServerConnection::dispatch_gui_event(MessagePtr& m)\n {\n static const struct {\n MessageType type;\n void (ServerConnection::*fn)(event::MessagePtr&);\n } dispatch[] = {\n { START_MESSAGE_TYPE, &ServerConnection::start },\n { STOP_MESSAGE_TYPE, &ServerConnection::stop },\n { SEEK_MESSAGE_TYPE, &ServerConnection::seek },\n { SPEED_MESSAGE_TYPE, &ServerConnection::speed },\n { UNKNOWN_MESSAGE_TYPE, 0 }\n };\n\n TRACE_ENTER();\n\n for (size_t i = 0; dispatch[i].type != UNKNOWN_MESSAGE_TYPE; ++i) {\n if (m->type == dispatch[i].type) {\n if (conn_type == unknown) {\n conn_type = gui;\n replay.reset(new ReplayState(shared_from_this()));\n }\n (this->*(dispatch[i].fn)) (m);\n TRACE_EXIT_RET_BOOL(true);\n return true;\n }\n }\n TRACE_EXIT_RET_BOOL(false);\n return false;\n }\n\n void ServerConnection::handle_read_payload(const boost::system::error_code& e, size_t bytes_transferred, unsigned short numOfMessages)\n {\n TRACE_ENTER();\n\n if (!e)\n {\n vector<MessagePtr> arrivedMessages; \n if (DataMarshaller::unmarshalPayload(arrivedMessages, numOfMessages, incomingBuffer.begin(), bytes_transferred))\n {\n LOG_INFO(\"Recvd \" << arrivedMessages.size() << \" message\" <<\n (arrivedMessages.size()>1?\"s\":\"\") << \" from \" <<\n remoteEndpoint().address()); \n\n \/\/ Add the incoming address to the Message so everyone\n \/\/ knows who the message came from.\n boost::asio::ip::tcp::endpoint ep = getSocket().remote_endpoint();\n BOOST_FOREACH(MessagePtr m, arrivedMessages) {\n if(m->fromNodeID==NodeIdentifier()) \/\/ is empty\n m->fromNodeID=ep.address();\n }\n\n \/*\n * If this connection type is unknown or gui, then traverse the\n * list of arrived messages. For GUI clients, look for the\n * STOP_MESSAGE to unsubscribe from the event stream.\n *\n * For unknown clients, infer the type from the message\n * received:\n * START_MESSAGE => gui\n * isFeederMessage => feeder\n *\/\n if (conn_type == unknown || conn_type == gui) {\n BOOST_FOREACH(MessagePtr& i, arrivedMessages) {\n if (dispatch_gui_event(i)) {\n \/\/empty\n } else if (isFeederEvent(i->type)) {\n conn_type = feeder;\n\n \/*\n * This connection is a watcher test daemon.\n * Add a message handler to write its event\n * stream to the database.\n *\/\n addMessageHandler(MessageHandlerPtr(new WriteDBMessageHandler()));\n }\n }\n }\n\n \/* Flag indicating whether to continue reading from this\n * connection. *\/\n bool fail = false;\n\n BOOST_FOREACH(MessageHandlerPtr& mh, messageHandlers) {\n if (mh->handleMessagesArrive(shared_from_this(), arrivedMessages)) {\n fail = true;\n LOG_DEBUG(\"Message handler told us to close this connection.\"); \n }\n }\n\n if (!fail) {\n \/\/ initiate request to read next message\n LOG_DEBUG(\"Waiting for next message.\");\n run();\n }\n\n if (conn_type == feeder) {\n \/* relay feeder message to any client requesting the live stream.\n * Warning: currently there is no check to make sure that a client doesn't\n * receive a message it just sent. This should be OK since we are just\n * relaying feeder messages only, and the GUIs should not be sending\n * them. *\/\n vector<MessagePtr> feeder;\n remove_copy_if(arrivedMessages.begin(), arrivedMessages.end(), back_inserter(feeder), not_feeder_message);\n if (! feeder.empty()) {\n LOG_DEBUG(\"Sending \" << feeder.size() << \" feeder messages to clients.\");\n watcher.sendMessage(feeder);\n }\n }\n }\n }\n else\n read_error(e);\n\n \/\/ If an error occurs then no new asynchronous operations are started. This\n \/\/ means that all shared_ptr references to the ServerConnection object will\n \/\/ disappear and the object will be destroyed automatically after this\n \/\/ handler returns. The ServerConnection class's destructor closes the socket.\n\n TRACE_EXIT();\n }\n\n void ServerConnection::handle_write(const boost::system::error_code& e, MessagePtr message)\n {\n TRACE_ENTER(); \n\n if (!e)\n {\n LOG_DEBUG(\"Successfully sent message to client: \" << message); \n\n BOOST_FOREACH(MessageHandlerPtr mh, messageHandlers)\n {\n#if 0\n \/* melkins\n * The reads and writes to the socket are asynchronous, so\n * we should never be waiting for something to be read as\n * a result of a write.\n *\/\n if(waitForResponse) \/\/ someone already said they wanted a response, so ignore ret val for others\n mh->handleMessageSent(message);\n else\n waitForResponse=mh->handleMessageSent(message);\n#endif\n mh->handleMessageSent(message);\n }\n\n \/\/ melkins\n \/\/ start() calls async_read(), which is not what we want to do here\n \/*\n if(waitForResponse)\n start(); \n *\/\n }\n else\n {\n LOG_WARN(\"Error while sending response to client: \" << e);\n if (conn_type == gui)\n watcher.unsubscribe(shared_from_this());\n }\n\n \/\/ No new asynchronous operations are started. This means that all shared_ptr\n \/\/ references to the connection object will disappear and the object will be\n \/\/ destroyed automatically after this handler returns. The connection class's\n \/\/ destructor closes the socket.\n\n \/* NOTE: The refcount will not go to zero so long as there is an\n * async_read operation also oustanding. *\/\n\n TRACE_EXIT();\n }\n\n \/** Send a single message to this connected client. *\/\n void ServerConnection::sendMessage(MessagePtr msg)\n {\n TRACE_ENTER();\n DataMarshaller::NetworkMarshalBuffers outBuffers;\n DataMarshaller::marshalPayload(msg, outBuffers);\n\n \/\/\/ FIXME melkins 2004-04-19\n \/\/ is it safe to call async_write and async_read from different\n \/\/ threads at the same time? asio::tcp::socket() is listed at not\n \/\/ shared thread safe\n async_write(theSocket,\n outBuffers,\n write_strand_.wrap( boost::bind( &ServerConnection::handle_write,\n shared_from_this(),\n placeholders::error,\n msg)));\n TRACE_EXIT();\n }\n\n \/** Send a set of messages to this connected client. *\/\n void ServerConnection::sendMessage(const std::vector<MessagePtr>& msgs)\n {\n TRACE_ENTER();\n DataMarshaller::NetworkMarshalBuffers outBuffers;\n DataMarshaller::marshalPayload(msgs, outBuffers);\n\n \/\/\/ FIXME melkins 2004-04-19\n \/\/ is it safe to call async_write and async_read from different\n \/\/ threads at the same time?\n async_write(theSocket,\n outBuffers,\n write_strand_.wrap( boost::bind( &ServerConnection::handle_write,\n shared_from_this(),\n placeholders::error,\n msgs.front())));\n TRACE_EXIT();\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you 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#if !defined(XALANDEQUE_HEADER_GUARD_1357924680)\n#define XALANDEQUE_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include <xalanc\/Include\/PlatformDefinitions.hpp>\n\n\n\n#include <xalanc\/Include\/XalanVector.hpp>\n#include <xalanc\/Include\/XalanMemoryManagement.hpp> \n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\ntemplate <class Value>\nstruct XalanDequeIteratorTraits\n{\n typedef Value value_type;\n typedef Value& reference;\n typedef Value* pointer;\n typedef const Value& const_reference;\n};\n\ntemplate <class Value>\nstruct XalanDequeConstIteratorTraits\n{\n typedef Value value_type;\n typedef const Value& reference;\n typedef const Value* pointer;\n typedef const Value& const_reference;\n};\n\ntemplate <class Traits, class XalanDeque>\nclass XalanDequeIterator\n{\npublic:\n\n typedef size_t size_type;\n typedef typename Traits::value_type value_type;\n typedef typename Traits::reference reference;\n typedef typename Traits::pointer pointer;\n typedef typename Traits::const_reference const_reference;\n typedef ptrdiff_t difference_type;\n\n typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category;\n\n \/\/ The non-const iterator type. In the case of the non-const instatiation, this\n \/\/ is the same type.\n typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator;\n\n \/\/ The const version needs access to our private data members for copy construction and\n \/\/ assignment. For the const instantiation, this is a superfluous friend declaration,\n \/\/ since it's the same type as the class itself.\n friend class XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, XalanDeque>;\n\n XalanDequeIterator(\n XalanDeque* deque,\n size_type pos) :\n m_deque(deque),\n m_pos(pos)\n {\n }\n\n \/\/ The is standard copy-construction for the non-const iterator type. For the\n \/\/ const iterator type, this is copy construction from the non-const type, and the\n \/\/ compiler will generate the standard copy constructor.\n XalanDequeIterator(const Iterator& iterator) :\n m_deque(iterator.m_deque),\n m_pos(iterator.m_pos)\n {\n }\n\n \/\/ The is the standard assignment operator for the non-const iterator type.\n \/\/ For the const iterator type, this is the assignment operator from the\n \/\/ non-const type, and the compiler will generate the standard assignment\n \/\/ operator.\n XalanDequeIterator&\n operator=(const Iterator& iterator)\n {\n m_deque = iterator.m_deque;\n m_pos = iterator.m_pos;\n\n return *this;\n }\n\n XalanDequeIterator&\n operator++()\n {\n ++m_pos;\n\n return *this;\n }\n\n XalanDequeIterator\n operator++(int)\n {\n XalanDequeIterator temp = *this;\n ++m_pos;\n\n return temp;\n }\n\n XalanDequeIterator&\n operator--()\n { \n --m_pos;\n\n return *this;\n }\n\n pointer\n operator->()\n {\n return &(*m_deque[m_pos]);\n }\n\n reference\n operator*()\n {\n return (*m_deque)[m_pos];\n }\n\n const_reference\n operator*() const\n {\n return (*m_deque)[m_pos];\n }\n\n XalanDequeIterator\n operator+(difference_type difference) const\n {\n return XalanDequeIterator(m_deque, m_pos + difference);\n }\n\n XalanDequeIterator\n operator-(difference_type difference) const\n {\n return XalanDequeIterator(m_deque, m_pos - difference);\n }\n\n difference_type\n operator-(const XalanDequeIterator& theRHS) const\n {\n return m_pos - theRHS.m_pos;\n }\n\n bool\n operator==(const XalanDequeIterator& theRHS) const\n {\n return theRHS.m_deque == m_deque &&\n theRHS.m_pos == m_pos;\n }\n\n bool\n operator!=(const XalanDequeIterator& theRHS) const\n {\n return !(theRHS == *this);\n }\n\n bool\n operator<(const XalanDequeIterator& theRHS) const\n {\n return m_pos < theRHS.m_pos;\n }\n\nprivate:\n\n XalanDeque* m_deque;\n\n size_type m_pos;\n};\n\n\/**\n * Xalan implementation of deque\n *\/\ntemplate <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> >\nclass XalanDeque\n{\npublic:\n\n typedef size_t size_type;\n\n typedef Type value_type;\n typedef Type& reference;\n typedef const Type& const_reference;\n\n typedef XalanVector<Type, ConstructionTraits> BlockType;\n typedef XalanVector<BlockType*> BlockIndexType;\n\n typedef XalanDeque<Type, ConstructionTraits> ThisType;\n\n typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, ThisType> iterator;\n typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, ThisType> const_iterator;\n\n#if defined(XALAN_HAS_STD_ITERATORS)\n typedef XALAN_STD_QUALIFIER reverse_iterator<iterator> reverse_iterator_;\n typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator> const_reverse_iterator_;\n#elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC)\n typedef typename iterator::iterator_category iterator_category;\n\n \/\/ This is a specific case for the Rogue Wave STL on Solaris.\n typedef XALAN_STD_QUALIFIER reverse_iterator<\n iterator,\n iterator_category,\n value_type> reverse_iterator_;\n\n typedef XALAN_STD_QUALIFIER reverse_iterator<\n const_iterator,\n iterator_category,\n const value_type> const_reverse_iterator_;\n#else\n typedef XALAN_STD_QUALIFIER reverse_iterator<\n iterator,\n value_type> reverse_iterator_;\n\n typedef XALAN_STD_QUALIFIER reverse_iterator<\n const_iterator,\n value_type,\n const_reference> const_reverse_iterator_;\n#endif\n\n typedef reverse_iterator_ reverse_iterator;\n typedef const_reverse_iterator_ const_reverse_iterator;\n\n typedef typename ConstructionTraits::Constructor Constructor;\n typedef typename Constructor::ConstructableType ConstructableType;\n\n XalanDeque(\n MemoryManager& memoryManager,\n size_type initialSize = 0,\n size_type blockSize = 10) :\n m_memoryManager(&memoryManager),\n m_blockSize(blockSize),\n m_blockIndex(memoryManager,\n initialSize \/ blockSize + (initialSize % blockSize == 0 ? 0 : 1)), \n m_freeBlockVector(memoryManager)\n {\n const ConstructableType defaultValue(*m_memoryManager);\n\n XALAN_USING_STD(fill_n)\n XALAN_USING_STD(back_inserter)\n\n fill_n(\n back_inserter(*this),\n initialSize, \n defaultValue.value);\n }\n\n XalanDeque(\n const XalanDeque& theRHS,\n MemoryManager& theMemoryManager) :\n m_memoryManager(&theMemoryManager),\n m_blockSize(theRHS.m_blockSize),\n m_blockIndex(*theRHS.m_memoryManager,\n theRHS.size() \/ theRHS.m_blockSize + (theRHS.size() % theRHS.m_blockSize == 0 ? 0 : 1)),\n m_freeBlockVector(theMemoryManager)\n {\n XALAN_USING_STD(copy)\n XALAN_USING_STD(back_inserter)\n\n copy(\n theRHS.begin(),\n theRHS.end(), \n back_inserter(*this));\n }\n\n static XalanDeque*\n create(\n MemoryManager& theManager,\n size_type initialSize = 0,\n size_type blockSize = 10)\n {\n XalanAllocationGuard theGuard(theManager, theManager.allocate(sizeof(ThisType)));\n\n ThisType* const theResult =\n new (theGuard.get()) ThisType(theManager, initialSize, blockSize);\n\n theGuard.release();\n\n return theResult;\n }\n\n ~XalanDeque()\n {\n destroyBlockList(m_freeBlockVector);\n\n destroyBlockList(m_blockIndex);\n }\n\n iterator\n begin()\n {\n return iterator(this, 0);\n }\n\n const_iterator\n begin() const\n {\n return const_iterator(const_cast<XalanDeque*>(this), 0);\n }\n\n iterator\n end()\n {\n return iterator(this, size());\n }\n\n const_iterator \n end() const\n {\n return const_iterator(const_cast<XalanDeque*>(this), size());\n }\n\n const_reverse_iterator \n rbegin() const\n {\n return const_reverse_iterator(end());\n }\n\n const_reverse_iterator \n rend() const\n {\n return const_reverse_iterator(begin());\n }\n\n bool \n empty() const\n {\n return m_blockIndex.empty();\n }\n\n size_type \n size() const\n {\n if (m_blockIndex.empty())\n {\n return 0;\n }\n else\n {\n return (m_blockIndex.size() - 1) * m_blockSize\n + m_blockIndex.back()->size();\n }\n }\n\n value_type&\n back()\n {\n return m_blockIndex.back()->back();\n }\n\n value_type&\n operator[](size_type index)\n {\n BlockType& block = *m_blockIndex[index \/ m_blockSize];\n\n return block[index % m_blockSize];\n }\n\n const value_type&\n operator[](size_type index) const\n {\n BlockType& block = *m_blockIndex[index \/ m_blockSize];\n\n return block[index % m_blockSize];\n }\n\n void\n clear()\n {\n typename BlockIndexType::iterator iter = m_blockIndex.begin();\n\n m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size());\n\n while (iter != m_blockIndex.end())\n {\n (*iter)->clear();\n m_freeBlockVector.push_back(*iter);\n ++iter;\n }\n\n m_blockIndex.clear();\n }\n\n void\n push_back(const value_type& value)\n {\n if (m_blockIndex.empty() ||\n m_blockIndex.back()->size() >= m_blockSize)\n {\n pushNewIndexBlock();\n }\n\n m_blockIndex.back()->push_back(value);\n }\n\n void\n pop_back()\n {\n assert(!empty());\n\n BlockType& lastBlock = *m_blockIndex.back();\n lastBlock.pop_back();\n\n if (lastBlock.empty())\n {\n m_freeBlockVector.push_back(&lastBlock);\n m_blockIndex.pop_back();\n }\n }\n\n void\n resize(size_type newSize)\n {\n const ConstructableType defaultValue(*m_memoryManager);\n\n if (newSize > size())\n {\n for (size_type i = 0; i < newSize - size(); ++i)\n {\n push_back(defaultValue.value);\n }\n }\n else\n {\n for (size_type i = 0; i < size() - newSize; ++i)\n {\n pop_back();\n }\n }\n }\n\n void\n swap(XalanDeque& theRHS)\n {\n XALAN_USING_STD(swap)\n\n swap(m_memoryManager, theRHS.m_memoryManager);\n\n theRHS.m_blockIndex.swap(m_blockIndex);\n theRHS.m_freeBlockVector.swap(m_freeBlockVector);\n }\n\n XalanDeque&\n operator=(const XalanDeque& theRHS) \n {\n if (this != &theRHS)\n {\n XALAN_USING_STD(copy)\n XALAN_USING_STD(back_inserter)\n\n clear();\n\n copy(\n theRHS.begin(),\n theRHS.end(),\n back_inserter(*this));\n }\n\n return *this;\n }\n\n MemoryManager&\n getMemoryManager()\n {\n assert (m_memoryManager != 0);\n\n return *m_memoryManager;\n }\n\nprivate:\n\n void\n pushNewIndexBlock()\n {\n \/\/ Allocate space first, so we don't have to worry\n \/\/ about an out-of-memory error once we've constructed\n \/\/ the new block.\n m_blockIndex.push_back(0);\n\n if (m_freeBlockVector.empty())\n {\n XalanConstruct(\n *m_memoryManager,\n m_blockIndex.back(),\n *m_memoryManager,\n m_blockSize);\n }\n else\n {\n m_blockIndex.back() = m_freeBlockVector.back();\n\n \/\/ Now that ownership has been transfered, pop\n \/\/ it off the free list.\n m_freeBlockVector.pop_back();\n }\n\n assert(m_blockIndex.back() != 0);\n }\n\n void\n destroyBlockList(BlockIndexType& theBlockIndex)\n {\n typename BlockIndexType::iterator iter =\n theBlockIndex.begin();\n\n while (iter != theBlockIndex.end())\n {\n XalanDestroy(*m_memoryManager, **iter);\n\n ++iter;\n }\n }\n\n void\n deallocate(BlockType* pointer)\n {\n m_memoryManager->deallocate(pointer);\n }\n\n MemoryManager* m_memoryManager;\n\n const size_type m_blockSize;\n\n BlockIndexType\t\tm_blockIndex; \n BlockIndexType\t\tm_freeBlockVector;\n\n\n \/\/ These are not implemented\n XalanDeque();\n\n XalanDeque(const XalanDeque&);\n};\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif \/\/ XALANDEQUE_HEADER_GUARD_1357924680\n\n<commit_msg>Removed unused member function and fixed tabs.<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you 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#if !defined(XALANDEQUE_HEADER_GUARD_1357924680)\n#define XALANDEQUE_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include <xalanc\/Include\/PlatformDefinitions.hpp>\n\n\n\n#include <xalanc\/Include\/XalanVector.hpp>\n#include <xalanc\/Include\/XalanMemoryManagement.hpp> \n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\ntemplate <class Value>\nstruct XalanDequeIteratorTraits\n{\n typedef Value value_type;\n typedef Value& reference;\n typedef Value* pointer;\n typedef const Value& const_reference;\n};\n\ntemplate <class Value>\nstruct XalanDequeConstIteratorTraits\n{\n typedef Value value_type;\n typedef const Value& reference;\n typedef const Value* pointer;\n typedef const Value& const_reference;\n};\n\ntemplate <class Traits, class XalanDeque>\nclass XalanDequeIterator\n{\npublic:\n\n typedef size_t size_type;\n typedef typename Traits::value_type value_type;\n typedef typename Traits::reference reference;\n typedef typename Traits::pointer pointer;\n typedef typename Traits::const_reference const_reference;\n typedef ptrdiff_t difference_type;\n\n typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category;\n\n \/\/ The non-const iterator type. In the case of the non-const instatiation, this\n \/\/ is the same type.\n typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator;\n\n \/\/ The const version needs access to our private data members for copy construction and\n \/\/ assignment. For the const instantiation, this is a superfluous friend declaration,\n \/\/ since it's the same type as the class itself.\n friend class XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, XalanDeque>;\n\n XalanDequeIterator(\n XalanDeque* deque,\n size_type pos) :\n m_deque(deque),\n m_pos(pos)\n {\n }\n\n \/\/ The is standard copy-construction for the non-const iterator type. For the\n \/\/ const iterator type, this is copy construction from the non-const type, and the\n \/\/ compiler will generate the standard copy constructor.\n XalanDequeIterator(const Iterator& iterator) :\n m_deque(iterator.m_deque),\n m_pos(iterator.m_pos)\n {\n }\n\n \/\/ The is the standard assignment operator for the non-const iterator type.\n \/\/ For the const iterator type, this is the assignment operator from the\n \/\/ non-const type, and the compiler will generate the standard assignment\n \/\/ operator.\n XalanDequeIterator&\n operator=(const Iterator& iterator)\n {\n m_deque = iterator.m_deque;\n m_pos = iterator.m_pos;\n\n return *this;\n }\n\n XalanDequeIterator&\n operator++()\n {\n ++m_pos;\n\n return *this;\n }\n\n XalanDequeIterator\n operator++(int)\n {\n XalanDequeIterator temp = *this;\n ++m_pos;\n\n return temp;\n }\n\n XalanDequeIterator&\n operator--()\n { \n --m_pos;\n\n return *this;\n }\n\n pointer\n operator->()\n {\n return &(*m_deque[m_pos]);\n }\n\n reference\n operator*()\n {\n return (*m_deque)[m_pos];\n }\n\n const_reference\n operator*() const\n {\n return (*m_deque)[m_pos];\n }\n\n XalanDequeIterator\n operator+(difference_type difference) const\n {\n return XalanDequeIterator(m_deque, m_pos + difference);\n }\n\n XalanDequeIterator\n operator-(difference_type difference) const\n {\n return XalanDequeIterator(m_deque, m_pos - difference);\n }\n\n difference_type\n operator-(const XalanDequeIterator& theRHS) const\n {\n return m_pos - theRHS.m_pos;\n }\n\n bool\n operator==(const XalanDequeIterator& theRHS) const\n {\n return theRHS.m_deque == m_deque &&\n theRHS.m_pos == m_pos;\n }\n\n bool\n operator!=(const XalanDequeIterator& theRHS) const\n {\n return !(theRHS == *this);\n }\n\n bool\n operator<(const XalanDequeIterator& theRHS) const\n {\n return m_pos < theRHS.m_pos;\n }\n\nprivate:\n\n XalanDeque* m_deque;\n\n size_type m_pos;\n};\n\n\/**\n * Xalan implementation of deque\n *\/\ntemplate <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> >\nclass XalanDeque\n{\npublic:\n\n typedef size_t size_type;\n\n typedef Type value_type;\n typedef Type& reference;\n typedef const Type& const_reference;\n\n typedef XalanVector<Type, ConstructionTraits> BlockType;\n typedef XalanVector<BlockType*> BlockIndexType;\n\n typedef XalanDeque<Type, ConstructionTraits> ThisType;\n\n typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, ThisType> iterator;\n typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, ThisType> const_iterator;\n\n#if defined(XALAN_HAS_STD_ITERATORS)\n typedef XALAN_STD_QUALIFIER reverse_iterator<iterator> reverse_iterator_;\n typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator> const_reverse_iterator_;\n#elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC)\n typedef typename iterator::iterator_category iterator_category;\n\n \/\/ This is a specific case for the Rogue Wave STL on Solaris.\n typedef XALAN_STD_QUALIFIER reverse_iterator<\n iterator,\n iterator_category,\n value_type> reverse_iterator_;\n\n typedef XALAN_STD_QUALIFIER reverse_iterator<\n const_iterator,\n iterator_category,\n const value_type> const_reverse_iterator_;\n#else\n typedef XALAN_STD_QUALIFIER reverse_iterator<\n iterator,\n value_type> reverse_iterator_;\n\n typedef XALAN_STD_QUALIFIER reverse_iterator<\n const_iterator,\n value_type,\n const_reference> const_reverse_iterator_;\n#endif\n\n typedef reverse_iterator_ reverse_iterator;\n typedef const_reverse_iterator_ const_reverse_iterator;\n\n typedef typename ConstructionTraits::Constructor Constructor;\n typedef typename Constructor::ConstructableType ConstructableType;\n\n XalanDeque(\n MemoryManager& memoryManager,\n size_type initialSize = 0,\n size_type blockSize = 10) :\n m_memoryManager(&memoryManager),\n m_blockSize(blockSize),\n m_blockIndex(memoryManager,\n initialSize \/ blockSize + (initialSize % blockSize == 0 ? 0 : 1)), \n m_freeBlockVector(memoryManager)\n {\n const ConstructableType defaultValue(*m_memoryManager);\n\n XALAN_USING_STD(fill_n)\n XALAN_USING_STD(back_inserter)\n\n fill_n(\n back_inserter(*this),\n initialSize, \n defaultValue.value);\n }\n\n XalanDeque(\n const XalanDeque& theRHS,\n MemoryManager& theMemoryManager) :\n m_memoryManager(&theMemoryManager),\n m_blockSize(theRHS.m_blockSize),\n m_blockIndex(*theRHS.m_memoryManager,\n theRHS.size() \/ theRHS.m_blockSize + (theRHS.size() % theRHS.m_blockSize == 0 ? 0 : 1)),\n m_freeBlockVector(theMemoryManager)\n {\n XALAN_USING_STD(copy)\n XALAN_USING_STD(back_inserter)\n\n copy(\n theRHS.begin(),\n theRHS.end(), \n back_inserter(*this));\n }\n\n static XalanDeque*\n create(\n MemoryManager& theManager,\n size_type initialSize = 0,\n size_type blockSize = 10)\n {\n XalanAllocationGuard theGuard(theManager, theManager.allocate(sizeof(ThisType)));\n\n ThisType* const theResult =\n new (theGuard.get()) ThisType(theManager, initialSize, blockSize);\n\n theGuard.release();\n\n return theResult;\n }\n\n ~XalanDeque()\n {\n destroyBlockList(m_freeBlockVector);\n\n destroyBlockList(m_blockIndex);\n }\n\n iterator\n begin()\n {\n return iterator(this, 0);\n }\n\n const_iterator\n begin() const\n {\n return const_iterator(const_cast<XalanDeque*>(this), 0);\n }\n\n iterator\n end()\n {\n return iterator(this, size());\n }\n\n const_iterator \n end() const\n {\n return const_iterator(const_cast<XalanDeque*>(this), size());\n }\n\n const_reverse_iterator \n rbegin() const\n {\n return const_reverse_iterator(end());\n }\n\n const_reverse_iterator \n rend() const\n {\n return const_reverse_iterator(begin());\n }\n\n bool \n empty() const\n {\n return m_blockIndex.empty();\n }\n\n size_type \n size() const\n {\n if (m_blockIndex.empty())\n {\n return 0;\n }\n else\n {\n return (m_blockIndex.size() - 1) * m_blockSize\n + m_blockIndex.back()->size();\n }\n }\n\n value_type&\n back()\n {\n return m_blockIndex.back()->back();\n }\n\n value_type&\n operator[](size_type index)\n {\n BlockType& block = *m_blockIndex[index \/ m_blockSize];\n\n return block[index % m_blockSize];\n }\n\n const value_type&\n operator[](size_type index) const\n {\n BlockType& block = *m_blockIndex[index \/ m_blockSize];\n\n return block[index % m_blockSize];\n }\n\n void\n clear()\n {\n typename BlockIndexType::iterator iter = m_blockIndex.begin();\n\n m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size());\n\n while (iter != m_blockIndex.end())\n {\n (*iter)->clear();\n m_freeBlockVector.push_back(*iter);\n ++iter;\n }\n\n m_blockIndex.clear();\n }\n\n void\n push_back(const value_type& value)\n {\n if (m_blockIndex.empty() ||\n m_blockIndex.back()->size() >= m_blockSize)\n {\n pushNewIndexBlock();\n }\n\n m_blockIndex.back()->push_back(value);\n }\n\n void\n pop_back()\n {\n assert(!empty());\n\n BlockType& lastBlock = *m_blockIndex.back();\n lastBlock.pop_back();\n\n if (lastBlock.empty())\n {\n m_freeBlockVector.push_back(&lastBlock);\n m_blockIndex.pop_back();\n }\n }\n\n void\n resize(size_type newSize)\n {\n const ConstructableType defaultValue(*m_memoryManager);\n\n if (newSize > size())\n {\n for (size_type i = 0; i < newSize - size(); ++i)\n {\n push_back(defaultValue.value);\n }\n }\n else\n {\n for (size_type i = 0; i < size() - newSize; ++i)\n {\n pop_back();\n }\n }\n }\n\n void\n swap(XalanDeque& theRHS)\n {\n XALAN_USING_STD(swap)\n\n swap(m_memoryManager, theRHS.m_memoryManager);\n\n theRHS.m_blockIndex.swap(m_blockIndex);\n theRHS.m_freeBlockVector.swap(m_freeBlockVector);\n }\n\n XalanDeque&\n operator=(const XalanDeque& theRHS) \n {\n if (this != &theRHS)\n {\n XALAN_USING_STD(copy)\n XALAN_USING_STD(back_inserter)\n\n clear();\n\n copy(\n theRHS.begin(),\n theRHS.end(),\n back_inserter(*this));\n }\n\n return *this;\n }\n\n MemoryManager&\n getMemoryManager()\n {\n assert (m_memoryManager != 0);\n\n return *m_memoryManager;\n }\n\nprivate:\n\n void\n pushNewIndexBlock()\n {\n \/\/ Allocate space first, so we don't have to worry\n \/\/ about an out-of-memory error once we've constructed\n \/\/ the new block.\n m_blockIndex.push_back(0);\n\n if (m_freeBlockVector.empty())\n {\n XalanConstruct(\n *m_memoryManager,\n m_blockIndex.back(),\n *m_memoryManager,\n m_blockSize);\n }\n else\n {\n m_blockIndex.back() = m_freeBlockVector.back();\n\n \/\/ Now that ownership has been transfered, pop\n \/\/ it off the free list.\n m_freeBlockVector.pop_back();\n }\n\n assert(m_blockIndex.back() != 0);\n }\n\n void\n destroyBlockList(BlockIndexType& theBlockIndex)\n {\n typename BlockIndexType::iterator iter =\n theBlockIndex.begin();\n\n while (iter != theBlockIndex.end())\n {\n XalanDestroy(*m_memoryManager, **iter);\n\n ++iter;\n }\n }\n\n MemoryManager* m_memoryManager;\n\n const size_type m_blockSize;\n\n BlockIndexType\t m_blockIndex; \n BlockIndexType\t m_freeBlockVector;\n\n\n \/\/ These are not implemented\n XalanDeque();\n\n XalanDeque(const XalanDeque&);\n};\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif \/\/ XALANDEQUE_HEADER_GUARD_1357924680\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ coding: utf-8\n\/\/ ----------------------------------------------------------------------------\n\/* Copyright (c) 2011, Roboterclub Aachen e.V.\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 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 the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Roboterclub Aachen e.V. nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef XPCC__GUI_ABSTRACT_VIEW_HPP\n#define XPCC__GUI_ABSTRACT_VIEW_HPP\n\n#include \"..\/display\/graphic_display.hpp\"\n\n#include \"types.hpp\"\n#include \"widgets\/widget.hpp\"\n#include \"colorpalette.hpp\"\n\n#include \"..\/menu\/abstract_view.hpp\"\n\nnamespace xpcc\n{\nnamespace gui\n{\n\t\/\/ forward declaration\n\tclass GuiViewStack;\n\t\n\t\/**\n\t * @brief The View class is the base class for all screens\n\t * handled by the ViewStack class\n\t *\n\t *\\author Thorsten Lajewski\n\t *\\ingroup display_menu\n\t *\/\n\n\tclass View : public xpcc::AbstractView\n\t{\n\t\tfriend class GuiViewStack;\n\t\t\n\tpublic:\n\t\t\/**\n\t\t * @param stack pointer to the stack, the screen should be displayed on.\n\t\t * @param identifier can be used to determine which screen is the currently\n\t\t * displayed on the graphicDisplay\n\t\t *\/\n\t\tView(xpcc::gui::GuiViewStack* stack, uint8_t identifier, xpcc::gui::Dimension dimension);\n\t\t\n\t\tvirtual ~View() = 0;\n\n\t\t\/**\n\t\t * @brief May be called as often as possible. Handles input events\n\t\t * located in the parent GuiViewStack\n\t\t *\/\n\t\tvirtual void\n\t\tupdate();\n\n\t\tvirtual void\n\t\tpreUpdate()\n\t\t{\n\t\t}\n\n\t\tvirtual void\n\t\tpostUpdate()\n\t\t{\n\t\t}\n\n\t\t\/**\n\t\t * @brief hasChanged indicates the current displayed view has changed.\n\t\t * This function prevents unnecessary drawing of the display\n\t\t * @return if true the display has to be redrawn.\n\t\t *\/\n\t\tvirtual bool\n\t\thasChanged() = 0;\n\t\t\n\t\t\/**\n\t\t * @brief draw determine the output on the Graphic Display\n\t\t *\/\n\t\tvirtual void\n\t\tdraw();\n\t\t\n\t\t\/**\n\t\t * @brief add widget to view\n\t\t *\/\n\t\tbool\n\t\tpack(Widget *w, const xpcc::glcd::Point &coord);\n\n\t\t\/**\n\t\t * @brief remove the view from the screen. The viewStack handles the deletion.\n\t\t *\/\n\t\tvoid\n\t\tremove();\n\n\t\t\/**\n\t\t * @brief set color palette for every contained widget\n\t\t *\/\n\t\tvoid\n\t\tsetColorPalette(ColorPalette& cp);\n\n\t\tColorPalette&\n\t\tgetColorPalette()\n\t\t{\n\t\t\treturn this->colorpalette;\n\t\t}\n\n\t\tvoid\n\t\tmarkDirty();\n\n\t\tvoid\n\t\tmarkDrawn();\n\t\t\n\t\tinline xpcc::gui::GuiViewStack*\n\t\tgetViewStack()\n\t\t{\n\t\t\treturn stack;\n\t\t}\n\n\tprotected:\n\t\txpcc::gui::GuiViewStack* stack;\n\t\tDimension dimension;\n\t\tWidgetContainer widgets;\n\t\txpcc::gui::ColorPalette colorpalette;\n\t};\n}\n}\n\n#endif \/\/ XPCC__GUI_ABSTRACT_VIEW_HPP\n<commit_msg>Remove hasChanged and use it from base class.<commit_after>\/\/ coding: utf-8\n\/\/ ----------------------------------------------------------------------------\n\/* Copyright (c) 2011, Roboterclub Aachen e.V.\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 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 the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Roboterclub Aachen e.V. nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef XPCC__GUI_ABSTRACT_VIEW_HPP\n#define XPCC__GUI_ABSTRACT_VIEW_HPP\n\n#include \"..\/display\/graphic_display.hpp\"\n\n#include \"types.hpp\"\n#include \"widgets\/widget.hpp\"\n#include \"colorpalette.hpp\"\n\n#include \"..\/menu\/abstract_view.hpp\"\n\nnamespace xpcc\n{\nnamespace gui\n{\n\t\/\/ forward declaration\n\tclass GuiViewStack;\n\t\n\t\/**\n\t * @brief The View class is the base class for all screens\n\t * handled by the ViewStack class\n\t *\n\t *\\author Thorsten Lajewski\n\t *\\ingroup display_menu\n\t *\/\n\n\tclass View : public xpcc::AbstractView\n\t{\n\t\tfriend class GuiViewStack;\n\t\t\n\tpublic:\n\t\t\/**\n\t\t * @param stack pointer to the stack, the screen should be displayed on.\n\t\t * @param identifier can be used to determine which screen is the currently\n\t\t * displayed on the graphicDisplay\n\t\t *\/\n\t\tView(xpcc::gui::GuiViewStack* stack, uint8_t identifier, xpcc::gui::Dimension dimension);\n\t\t\n\t\tvirtual ~View() = 0;\n\n\t\t\/**\n\t\t * @brief May be called as often as possible. Handles input events\n\t\t * located in the parent GuiViewStack\n\t\t *\/\n\t\tvirtual void\n\t\tupdate();\n\n\t\tvirtual void\n\t\tpreUpdate()\n\t\t{\n\t\t}\n\n\t\tvirtual void\n\t\tpostUpdate()\n\t\t{\n\t\t}\n\t\t\n\t\t\/**\n\t\t * @brief draw determine the output on the Graphic Display\n\t\t *\/\n\t\tvirtual void\n\t\tdraw();\n\t\t\n\t\t\/**\n\t\t * @brief add widget to view\n\t\t *\/\n\t\tbool\n\t\tpack(Widget *w, const xpcc::glcd::Point &coord);\n\n\t\t\/**\n\t\t * @brief remove the view from the screen. The viewStack handles the deletion.\n\t\t *\/\n\t\tvoid\n\t\tremove();\n\n\t\t\/**\n\t\t * @brief set color palette for every contained widget\n\t\t *\/\n\t\tvoid\n\t\tsetColorPalette(ColorPalette& cp);\n\n\t\tColorPalette&\n\t\tgetColorPalette()\n\t\t{\n\t\t\treturn this->colorpalette;\n\t\t}\n\n\t\tvoid\n\t\tmarkDirty();\n\n\t\tvoid\n\t\tmarkDrawn();\n\t\t\n\t\tinline xpcc::gui::GuiViewStack*\n\t\tgetViewStack()\n\t\t{\n\t\t\treturn stack;\n\t\t}\n\n\tprotected:\n\t\txpcc::gui::GuiViewStack* stack;\n\t\tDimension dimension;\n\t\tWidgetContainer widgets;\n\t\txpcc::gui::ColorPalette colorpalette;\n\t};\n}\n}\n\n#endif \/\/ XPCC__GUI_ABSTRACT_VIEW_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: dbaobjectex.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2004-08-02 16:42:27 $\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 EXPRESS 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 SVX_DBAOBJECTEX_HXX\n#include \"dbaobjectex.hxx\"\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbcx\/XTablesSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_\n#include <com\/sun\/star\/sdb\/XSQLQueryComposerFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_\n#include <com\/sun\/star\/sdb\/XSQLQueryComposerFactory.hpp>\n#endif\n#ifndef _SVX_FMPROP_HRC\n#include \"fmprop.hrc\"\n#endif\n#ifndef _COMPHELPER_EXTRACT_HXX_\n#include <comphelper\/extract.hxx>\n#endif\n#ifndef _SOT_FORMATS_HXX\n#include <sot\/formats.hxx>\n#endif\n#ifndef _SOT_EXCHANGE_HXX\n#include <sot\/exchange.hxx>\n#endif\n#ifndef _COMPHELPER_PROPERTSETINFO_HXX_\n#include <comphelper\/propertysetinfo.hxx>\n#endif\n#ifndef _SVX_FMPROP_HRC\n#include \"fmprop.hrc\"\n#endif\n\n\/\/........................................................................\nnamespace svx\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::sdb;\n using namespace ::com::sun::star::sdbc;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::ucb;\n using namespace ::com::sun::star::sdbcx;\n using namespace ::com::sun::star::container;\n using namespace ::com::sun::star::datatransfer;\n using namespace ::svxform;\n using namespace ::comphelper;\n\n \/\/====================================================================\n \/\/= OComponentTransferable\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OComponentTransferable::OComponentTransferable(const ::rtl::OUString& _rDatasourceOrLocation\n ,const Reference< XContent>& _xContent)\n {\n m_aDescriptor.setDataSource(_rDatasourceOrLocation);\n m_aDescriptor[daComponent] <<= _xContent;\n }\n\n\n \/\/--------------------------------------------------------------------\n sal_uInt32 OComponentTransferable::getDescriptorFormatId()\n {\n static sal_uInt32 s_nFormat = (sal_uInt32)-1;\n if ((sal_uInt32)-1 == s_nFormat)\n {\n s_nFormat = SotExchange::RegisterFormatName(String::CreateFromAscii(\"application\/x-openoffice;windows_formatname=\\\"dbaccess.ComponentDescriptorTransfer\\\"\"));\n OSL_ENSURE((sal_uInt32)-1 != s_nFormat, \"OComponentTransferable::getDescriptorFormatId: bad exchange id!\");\n }\n return s_nFormat;\n }\n\n \/\/--------------------------------------------------------------------\n void OComponentTransferable::AddSupportedFormats()\n {\n AddFormat(getDescriptorFormatId());\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OComponentTransferable::GetData( const DataFlavor& _rFlavor )\n {\n const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);\n if ( nFormatId == getDescriptorFormatId() )\n return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );\n\n return sal_False;\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OComponentTransferable::canExtractComponentDescriptor(const DataFlavorExVector& _rFlavors )\n {\n DataFlavorExVector::const_iterator aEnd = _rFlavors.end();\n for ( DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();\n aCheck != aEnd;\n ++aCheck\n )\n {\n if ( getDescriptorFormatId() == aCheck->mnSotId )\n return sal_True;\n }\n\n return sal_False;\n }\n\n \/\/--------------------------------------------------------------------\n ODataAccessDescriptor OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData)\n {\n if ( _rData.HasFormat(getDescriptorFormatId()) )\n {\n \/\/ the object has a real descriptor object (not just the old compatible format)\n\n \/\/ extract the any from the transferable\n DataFlavor aFlavor;\n#if OSL_DEBUG_LEVEL > 0\n sal_Bool bSuccess =\n#endif\n SotExchange::GetFormatDataFlavor(getDescriptorFormatId(), aFlavor);\n OSL_ENSURE(bSuccess, \"OComponentTransferable::extractColumnDescriptor: invalid data format (no flavor)!\");\n\n Any aDescriptor = _rData.GetAny(aFlavor);\n\n \/\/ extract the property value sequence\n Sequence< PropertyValue > aDescriptorProps;\n#if OSL_DEBUG_LEVEL > 0\n bSuccess =\n#endif\n aDescriptor >>= aDescriptorProps;\n OSL_ENSURE(bSuccess, \"OComponentTransferable::extractColumnDescriptor: invalid clipboard format!\");\n\n \/\/ build the real descriptor\n return ODataAccessDescriptor(aDescriptorProps);\n }\n\n return ODataAccessDescriptor();\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData\n , ::rtl::OUString& _rDatasourceOrLocation\n , ::com::sun::star::uno::Reference< XContent>& _xContent)\n {\n if (_rData.HasFormat(getDescriptorFormatId()))\n {\n ODataAccessDescriptor aDescriptor = extractComponentDescriptor(_rData);\n _rDatasourceOrLocation = aDescriptor.getDataSource();\n aDescriptor[daComponent] >>= _xContent;\n return sal_True;\n }\n\n return sal_False;\n }\n\/\/........................................................................\n} \/\/ namespace svx\n\/\/........................................................................\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.756); FILE MERGED 2005\/09\/05 14:24:18 rt 1.2.756.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dbaobjectex.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:45:06 $\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 SVX_DBAOBJECTEX_HXX\n#include \"dbaobjectex.hxx\"\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbcx\/XTablesSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_\n#include <com\/sun\/star\/sdb\/XSQLQueryComposerFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_\n#include <com\/sun\/star\/sdb\/XSQLQueryComposerFactory.hpp>\n#endif\n#ifndef _SVX_FMPROP_HRC\n#include \"fmprop.hrc\"\n#endif\n#ifndef _COMPHELPER_EXTRACT_HXX_\n#include <comphelper\/extract.hxx>\n#endif\n#ifndef _SOT_FORMATS_HXX\n#include <sot\/formats.hxx>\n#endif\n#ifndef _SOT_EXCHANGE_HXX\n#include <sot\/exchange.hxx>\n#endif\n#ifndef _COMPHELPER_PROPERTSETINFO_HXX_\n#include <comphelper\/propertysetinfo.hxx>\n#endif\n#ifndef _SVX_FMPROP_HRC\n#include \"fmprop.hrc\"\n#endif\n\n\/\/........................................................................\nnamespace svx\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::sdb;\n using namespace ::com::sun::star::sdbc;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::ucb;\n using namespace ::com::sun::star::sdbcx;\n using namespace ::com::sun::star::container;\n using namespace ::com::sun::star::datatransfer;\n using namespace ::svxform;\n using namespace ::comphelper;\n\n \/\/====================================================================\n \/\/= OComponentTransferable\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OComponentTransferable::OComponentTransferable(const ::rtl::OUString& _rDatasourceOrLocation\n ,const Reference< XContent>& _xContent)\n {\n m_aDescriptor.setDataSource(_rDatasourceOrLocation);\n m_aDescriptor[daComponent] <<= _xContent;\n }\n\n\n \/\/--------------------------------------------------------------------\n sal_uInt32 OComponentTransferable::getDescriptorFormatId()\n {\n static sal_uInt32 s_nFormat = (sal_uInt32)-1;\n if ((sal_uInt32)-1 == s_nFormat)\n {\n s_nFormat = SotExchange::RegisterFormatName(String::CreateFromAscii(\"application\/x-openoffice;windows_formatname=\\\"dbaccess.ComponentDescriptorTransfer\\\"\"));\n OSL_ENSURE((sal_uInt32)-1 != s_nFormat, \"OComponentTransferable::getDescriptorFormatId: bad exchange id!\");\n }\n return s_nFormat;\n }\n\n \/\/--------------------------------------------------------------------\n void OComponentTransferable::AddSupportedFormats()\n {\n AddFormat(getDescriptorFormatId());\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OComponentTransferable::GetData( const DataFlavor& _rFlavor )\n {\n const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);\n if ( nFormatId == getDescriptorFormatId() )\n return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );\n\n return sal_False;\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OComponentTransferable::canExtractComponentDescriptor(const DataFlavorExVector& _rFlavors )\n {\n DataFlavorExVector::const_iterator aEnd = _rFlavors.end();\n for ( DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();\n aCheck != aEnd;\n ++aCheck\n )\n {\n if ( getDescriptorFormatId() == aCheck->mnSotId )\n return sal_True;\n }\n\n return sal_False;\n }\n\n \/\/--------------------------------------------------------------------\n ODataAccessDescriptor OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData)\n {\n if ( _rData.HasFormat(getDescriptorFormatId()) )\n {\n \/\/ the object has a real descriptor object (not just the old compatible format)\n\n \/\/ extract the any from the transferable\n DataFlavor aFlavor;\n#if OSL_DEBUG_LEVEL > 0\n sal_Bool bSuccess =\n#endif\n SotExchange::GetFormatDataFlavor(getDescriptorFormatId(), aFlavor);\n OSL_ENSURE(bSuccess, \"OComponentTransferable::extractColumnDescriptor: invalid data format (no flavor)!\");\n\n Any aDescriptor = _rData.GetAny(aFlavor);\n\n \/\/ extract the property value sequence\n Sequence< PropertyValue > aDescriptorProps;\n#if OSL_DEBUG_LEVEL > 0\n bSuccess =\n#endif\n aDescriptor >>= aDescriptorProps;\n OSL_ENSURE(bSuccess, \"OComponentTransferable::extractColumnDescriptor: invalid clipboard format!\");\n\n \/\/ build the real descriptor\n return ODataAccessDescriptor(aDescriptorProps);\n }\n\n return ODataAccessDescriptor();\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData\n , ::rtl::OUString& _rDatasourceOrLocation\n , ::com::sun::star::uno::Reference< XContent>& _xContent)\n {\n if (_rData.HasFormat(getDescriptorFormatId()))\n {\n ODataAccessDescriptor aDescriptor = extractComponentDescriptor(_rData);\n _rDatasourceOrLocation = aDescriptor.getDataSource();\n aDescriptor[daComponent] >>= _xContent;\n return sal_True;\n }\n\n return sal_False;\n }\n\/\/........................................................................\n} \/\/ namespace svx\n\/\/........................................................................\n\n\n<|endoftext|>"} {"text":"<commit_before> \/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: acccell.cxx,v $\n *\n * $Revision: 1.21 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 12:12:32 $\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_sw.hxx\"\n\n\n#ifndef _VOS_MUTEX_HXX_ \/\/autogen\n#include <vos\/mutex.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleStateType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleEventId.hpp>\n#endif\n\n#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_\n#include <unotools\/accessiblestatesethelper.hxx>\n#endif\n\n#ifndef _RTL_UUID_H_\n#include <rtl\/uuid.h>\n#endif\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _CELLFRM_HXX\n#include <cellfrm.hxx>\n#endif\n#ifndef _TABFRM_HXX\n#include <tabfrm.hxx>\n#endif\n#ifndef _SWTABLE_HXX\n#include <swtable.hxx>\n#endif\n#ifndef _CRSRSH_HXX\n#include \"crsrsh.hxx\"\n#endif\n#ifndef _VISCRS_HXX\n#include \"viscrs.hxx\"\n#endif\n#ifndef _ACCFRMOBJSLIST_HXX\n#include <accfrmobjslist.hxx>\n#endif\n#ifndef _FRMFMT_HXX\n#include \"frmfmt.hxx\"\n#endif\n#ifndef _CELLATR_HXX\n#include \"cellatr.hxx\"\n#endif\n\n#ifndef _ACCMAP_HXX\n#include \"accmap.hxx\"\n#endif\n#ifndef _ACCCELL_HXX\n#include <acccell.hxx>\n#endif\n\n#ifndef _STLP_CFLOAT\n#include <cfloat>\n#endif\n\n#include <limits.h>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::accessibility;\nusing ::rtl::OUString;\n\nconst sal_Char sServiceName[] = \"com.sun.star.table.AccessibleCellView\";\nconst sal_Char sImplementationName[] = \"com.sun.star.comp.Writer.SwAccessibleCellView\";\n\nsal_Bool SwAccessibleCell::IsSelected()\n{\n sal_Bool bRet = sal_False;\n\n DBG_ASSERT( GetMap(), \"no map?\" );\n const ViewShell *pVSh = GetMap()->GetShell();\n DBG_ASSERT( pVSh, \"no shell?\" );\n if( pVSh->ISA( SwCrsrShell ) )\n {\n const SwCrsrShell *pCSh = static_cast< const SwCrsrShell * >( pVSh );\n if( pCSh->IsTableMode() )\n {\n const SwCellFrm *pCFrm =\n static_cast< const SwCellFrm * >( GetFrm() );\n SwTableBox *pBox =\n const_cast< SwTableBox *>( pCFrm->GetTabBox() ); \/\/SVPtrArr!\n bRet = pCSh->GetTableCrsr()->GetBoxes().Seek_Entry( pBox );\n }\n }\n\n return bRet;\n}\n\nvoid SwAccessibleCell::GetStates(\n ::utl::AccessibleStateSetHelper& rStateSet )\n{\n SwAccessibleContext::GetStates( rStateSet );\n\n \/\/ SELECTABLE\n const ViewShell *pVSh = GetMap()->GetShell();\n DBG_ASSERT( pVSh, \"no shell?\" );\n if( pVSh->ISA( SwCrsrShell ) )\n rStateSet.AddState( AccessibleStateType::SELECTABLE );\n\n \/\/ SELECTED\n if( IsSelected() )\n {\n rStateSet.AddState( AccessibleStateType::SELECTED );\n ASSERT( bIsSelected, \"bSelected out of sync\" );\n ::vos::ORef < SwAccessibleContext > xThis( this );\n GetMap()->SetCursorContext( xThis );\n }\n}\n\nSwAccessibleCell::SwAccessibleCell(\n SwAccessibleMap *pInitMap,\n const SwCellFrm *pCellFrm ) :\n SwAccessibleContext( pInitMap, AccessibleRole::TABLE_CELL, pCellFrm ),\n bIsSelected( sal_False )\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n OUString sBoxName( pCellFrm->GetTabBox()->GetName() );\n SetName( sBoxName );\n\n bIsSelected = IsSelected();\n}\n\nsal_Bool SwAccessibleCell::_InvalidateMyCursorPos()\n{\n sal_Bool bNew = IsSelected();\n sal_Bool bOld;\n {\n vos::OGuard aGuard( aMutex );\n bOld = bIsSelected;\n bIsSelected = bNew;\n }\n if( bNew )\n {\n \/\/ remember that object as the one that has the caret. This is\n \/\/ neccessary to notify that object if the cursor leaves it.\n ::vos::ORef < SwAccessibleContext > xThis( this );\n GetMap()->SetCursorContext( xThis );\n }\n\n sal_Bool bChanged = bOld != bNew;\n if( bChanged )\n FireStateChangedEvent( AccessibleStateType::SELECTED, bNew );\n\n return bChanged;\n}\n\nsal_Bool SwAccessibleCell::_InvalidateChildrenCursorPos( const SwFrm *pFrm )\n{\n sal_Bool bChanged = sal_False;\n\n const SwFrmOrObjSList aVisList( GetVisArea(), pFrm );\n SwFrmOrObjSList::const_iterator aIter( aVisList.begin() );\n while( aIter != aVisList.end() )\n {\n const SwFrmOrObj& rLower = *aIter;\n const SwFrm *pLower = rLower.GetSwFrm();\n if( pLower )\n {\n if( rLower.IsAccessible( GetMap()->GetShell()->IsPreView() ) )\n {\n ::vos::ORef< SwAccessibleContext > xAccImpl(\n GetMap()->GetContextImpl( pLower, sal_False ) );\n if( xAccImpl.isValid() )\n {\n ASSERT( xAccImpl->GetFrm()->IsCellFrm(),\n \"table child is not a cell frame\" )\n bChanged |= static_cast< SwAccessibleCell *>(\n xAccImpl.getBodyPtr() )->_InvalidateMyCursorPos();\n }\n else\n bChanged = sal_True; \/\/ If the context is not know we\n \/\/ don't know whether the selection\n \/\/ changed or not.\n }\n else\n {\n \/\/ This is a box with sub rows.\n bChanged |= _InvalidateChildrenCursorPos( pLower );\n }\n }\n ++aIter;\n }\n\n return bChanged;\n}\n\nvoid SwAccessibleCell::_InvalidateCursorPos()\n{\n\n const SwFrm *pParent = GetParent( GetFrm(), IsInPagePreview() );\n ASSERT( pParent->IsTabFrm(), \"parent is not a tab frame\" );\n const SwTabFrm *pTabFrm = static_cast< const SwTabFrm * >( pParent );\n if( pTabFrm->IsFollow() )\n pTabFrm = pTabFrm->FindMaster();\n\n while( pTabFrm )\n {\n sal_Bool bChanged = _InvalidateChildrenCursorPos( pTabFrm );\n if( bChanged )\n {\n ::vos::ORef< SwAccessibleContext > xAccImpl(\n GetMap()->GetContextImpl( pTabFrm, sal_False ) );\n if( xAccImpl.isValid() )\n {\n AccessibleEventObject aEvent;\n aEvent.EventId = AccessibleEventId::SELECTION_CHANGED;\n xAccImpl->FireAccessibleEvent( aEvent );\n }\n }\n\n pTabFrm = pTabFrm->GetFollow();\n }\n}\n\nsal_Bool SwAccessibleCell::HasCursor()\n{\n vos::OGuard aGuard( aMutex );\n return bIsSelected;\n}\n\nSwAccessibleCell::~SwAccessibleCell()\n{\n}\n\nOUString SAL_CALL SwAccessibleCell::getAccessibleDescription (void)\n throw (uno::RuntimeException)\n{\n return GetName();\n}\n\nOUString SAL_CALL SwAccessibleCell::getImplementationName()\n throw( uno::RuntimeException )\n{\n return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationName));\n}\n\nsal_Bool SAL_CALL SwAccessibleCell::supportsService(\n const ::rtl::OUString& sTestServiceName)\n throw (uno::RuntimeException)\n{\n return sTestServiceName.equalsAsciiL( sServiceName,\n sizeof(sServiceName)-1 ) ||\n sTestServiceName.equalsAsciiL( sAccessibleServiceName,\n sizeof(sAccessibleServiceName)-1 );\n}\n\nuno::Sequence< OUString > SAL_CALL SwAccessibleCell::getSupportedServiceNames()\n throw( uno::RuntimeException )\n{\n uno::Sequence< OUString > aRet(2);\n OUString* pArray = aRet.getArray();\n pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceName) );\n pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );\n return aRet;\n}\n\nvoid SwAccessibleCell::Dispose( sal_Bool bRecursive )\n{\n const SwFrm *pParent = GetParent( GetFrm(), IsInPagePreview() );\n ::vos::ORef< SwAccessibleContext > xAccImpl(\n GetMap()->GetContextImpl( pParent, sal_False ) );\n if( xAccImpl.isValid() )\n xAccImpl->DisposeChild( GetFrm(), bRecursive );\n SwAccessibleContext::Dispose( bRecursive );\n}\n\nvoid SwAccessibleCell::InvalidatePosOrSize( const SwRect& rOldBox )\n{\n const SwFrm *pParent = GetParent( GetFrm(), IsInPagePreview() );\n ::vos::ORef< SwAccessibleContext > xAccImpl(\n GetMap()->GetContextImpl( pParent, sal_False ) );\n if( xAccImpl.isValid() )\n xAccImpl->InvalidateChildPosOrSize( GetFrm(), rOldBox );\n SwAccessibleContext::InvalidatePosOrSize( rOldBox );\n}\n\n\n\/\/ ===== XAccessibleInterface ===========================================\n\nuno::Any SwAccessibleCell::queryInterface( const uno::Type& rType )\n throw( uno::RuntimeException )\n{\n if ( rType == ::getCppuType( static_cast< uno::Reference< XAccessibleValue > * >( 0 ) ) )\n {\n uno::Reference<XAccessibleValue> xValue = this;\n uno::Any aRet;\n aRet <<= xValue;\n return aRet;\n }\n else\n {\n return SwAccessibleContext::queryInterface( rType );\n }\n}\n\n\/\/====== XTypeProvider ====================================================\nuno::Sequence< uno::Type > SAL_CALL SwAccessibleCell::getTypes()\n throw(uno::RuntimeException)\n{\n uno::Sequence< uno::Type > aTypes( SwAccessibleContext::getTypes() );\n\n sal_Int32 nIndex = aTypes.getLength();\n aTypes.realloc( nIndex + 1 );\n\n uno::Type* pTypes = aTypes.getArray();\n pTypes[nIndex] = ::getCppuType( static_cast< uno::Reference< XAccessibleValue > * >( 0 ) );\n\n return aTypes;\n}\n\nuno::Sequence< sal_Int8 > SAL_CALL SwAccessibleCell::getImplementationId()\n throw(uno::RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n static uno::Sequence< sal_Int8 > aId( 16 );\n static sal_Bool bInit = sal_False;\n if(!bInit)\n {\n rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );\n bInit = sal_True;\n }\n return aId;\n}\n\n\/\/ ===== XAccessibleValue ===============================================\n\nSwFrmFmt* SwAccessibleCell::GetTblBoxFormat() const\n{\n DBG_ASSERT( GetFrm() != NULL, \"no frame?\" );\n DBG_ASSERT( GetFrm()->IsCellFrm(), \"no cell frame?\" );\n\n const SwCellFrm* pCellFrm = static_cast<const SwCellFrm*>( GetFrm() );\n return pCellFrm->GetTabBox()->GetFrmFmt();\n}\n\n\nuno::Any SwAccessibleCell::getCurrentValue( )\n throw( uno::RuntimeException )\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n CHECK_FOR_DEFUNC( XAccessibleValue );\n\n uno::Any aAny;\n aAny <<= GetTblBoxFormat()->GetTblBoxValue().GetValue();\n return aAny;\n}\n\nsal_Bool SwAccessibleCell::setCurrentValue( const uno::Any& aNumber )\n throw( uno::RuntimeException )\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n CHECK_FOR_DEFUNC( XAccessibleValue );\n\n double fValue = 0;\n sal_Bool bValid = (aNumber >>= fValue);\n if( bValid )\n {\n SwTblBoxValue aValue( fValue );\n GetTblBoxFormat()->SetAttr( aValue );\n }\n return bValid;\n}\n\nuno::Any SwAccessibleCell::getMaximumValue( )\n throw( uno::RuntimeException )\n{\n uno::Any aAny;\n aAny <<= DBL_MAX;\n return aAny;\n}\n\nuno::Any SwAccessibleCell::getMinimumValue( )\n throw( uno::RuntimeException )\n{\n uno::Any aAny;\n aAny <<= -DBL_MAX;\n return aAny;\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.21.32); FILE MERGED 2008\/04\/01 15:56:39 thb 1.21.32.3: #i85898# Stripping all external header guards 2008\/04\/01 12:53:44 thb 1.21.32.2: #i85898# Stripping all external header guards 2008\/03\/31 16:53:37 rt 1.21.32.1: #i87441# Change license header to LPGL v3.<commit_after> \/*************************************************************************\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: acccell.cxx,v $\n * $Revision: 1.22 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_sw.hxx\"\n\n\n#include <vos\/mutex.hxx>\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#include <com\/sun\/star\/accessibility\/AccessibleStateType.hpp>\n#include <com\/sun\/star\/accessibility\/AccessibleEventId.hpp>\n#include <unotools\/accessiblestatesethelper.hxx>\n#include <rtl\/uuid.h>\n#include <vcl\/svapp.hxx>\n#include <cellfrm.hxx>\n#include <tabfrm.hxx>\n#include <swtable.hxx>\n#include \"crsrsh.hxx\"\n#include \"viscrs.hxx\"\n#include <accfrmobjslist.hxx>\n#include \"frmfmt.hxx\"\n#include \"cellatr.hxx\"\n#include \"accmap.hxx\"\n#include <acccell.hxx>\n\n#ifndef _STLP_CFLOAT\n#include <cfloat>\n#endif\n\n#include <limits.h>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::accessibility;\nusing ::rtl::OUString;\n\nconst sal_Char sServiceName[] = \"com.sun.star.table.AccessibleCellView\";\nconst sal_Char sImplementationName[] = \"com.sun.star.comp.Writer.SwAccessibleCellView\";\n\nsal_Bool SwAccessibleCell::IsSelected()\n{\n sal_Bool bRet = sal_False;\n\n DBG_ASSERT( GetMap(), \"no map?\" );\n const ViewShell *pVSh = GetMap()->GetShell();\n DBG_ASSERT( pVSh, \"no shell?\" );\n if( pVSh->ISA( SwCrsrShell ) )\n {\n const SwCrsrShell *pCSh = static_cast< const SwCrsrShell * >( pVSh );\n if( pCSh->IsTableMode() )\n {\n const SwCellFrm *pCFrm =\n static_cast< const SwCellFrm * >( GetFrm() );\n SwTableBox *pBox =\n const_cast< SwTableBox *>( pCFrm->GetTabBox() ); \/\/SVPtrArr!\n bRet = pCSh->GetTableCrsr()->GetBoxes().Seek_Entry( pBox );\n }\n }\n\n return bRet;\n}\n\nvoid SwAccessibleCell::GetStates(\n ::utl::AccessibleStateSetHelper& rStateSet )\n{\n SwAccessibleContext::GetStates( rStateSet );\n\n \/\/ SELECTABLE\n const ViewShell *pVSh = GetMap()->GetShell();\n DBG_ASSERT( pVSh, \"no shell?\" );\n if( pVSh->ISA( SwCrsrShell ) )\n rStateSet.AddState( AccessibleStateType::SELECTABLE );\n\n \/\/ SELECTED\n if( IsSelected() )\n {\n rStateSet.AddState( AccessibleStateType::SELECTED );\n ASSERT( bIsSelected, \"bSelected out of sync\" );\n ::vos::ORef < SwAccessibleContext > xThis( this );\n GetMap()->SetCursorContext( xThis );\n }\n}\n\nSwAccessibleCell::SwAccessibleCell(\n SwAccessibleMap *pInitMap,\n const SwCellFrm *pCellFrm ) :\n SwAccessibleContext( pInitMap, AccessibleRole::TABLE_CELL, pCellFrm ),\n bIsSelected( sal_False )\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n OUString sBoxName( pCellFrm->GetTabBox()->GetName() );\n SetName( sBoxName );\n\n bIsSelected = IsSelected();\n}\n\nsal_Bool SwAccessibleCell::_InvalidateMyCursorPos()\n{\n sal_Bool bNew = IsSelected();\n sal_Bool bOld;\n {\n vos::OGuard aGuard( aMutex );\n bOld = bIsSelected;\n bIsSelected = bNew;\n }\n if( bNew )\n {\n \/\/ remember that object as the one that has the caret. This is\n \/\/ neccessary to notify that object if the cursor leaves it.\n ::vos::ORef < SwAccessibleContext > xThis( this );\n GetMap()->SetCursorContext( xThis );\n }\n\n sal_Bool bChanged = bOld != bNew;\n if( bChanged )\n FireStateChangedEvent( AccessibleStateType::SELECTED, bNew );\n\n return bChanged;\n}\n\nsal_Bool SwAccessibleCell::_InvalidateChildrenCursorPos( const SwFrm *pFrm )\n{\n sal_Bool bChanged = sal_False;\n\n const SwFrmOrObjSList aVisList( GetVisArea(), pFrm );\n SwFrmOrObjSList::const_iterator aIter( aVisList.begin() );\n while( aIter != aVisList.end() )\n {\n const SwFrmOrObj& rLower = *aIter;\n const SwFrm *pLower = rLower.GetSwFrm();\n if( pLower )\n {\n if( rLower.IsAccessible( GetMap()->GetShell()->IsPreView() ) )\n {\n ::vos::ORef< SwAccessibleContext > xAccImpl(\n GetMap()->GetContextImpl( pLower, sal_False ) );\n if( xAccImpl.isValid() )\n {\n ASSERT( xAccImpl->GetFrm()->IsCellFrm(),\n \"table child is not a cell frame\" )\n bChanged |= static_cast< SwAccessibleCell *>(\n xAccImpl.getBodyPtr() )->_InvalidateMyCursorPos();\n }\n else\n bChanged = sal_True; \/\/ If the context is not know we\n \/\/ don't know whether the selection\n \/\/ changed or not.\n }\n else\n {\n \/\/ This is a box with sub rows.\n bChanged |= _InvalidateChildrenCursorPos( pLower );\n }\n }\n ++aIter;\n }\n\n return bChanged;\n}\n\nvoid SwAccessibleCell::_InvalidateCursorPos()\n{\n\n const SwFrm *pParent = GetParent( GetFrm(), IsInPagePreview() );\n ASSERT( pParent->IsTabFrm(), \"parent is not a tab frame\" );\n const SwTabFrm *pTabFrm = static_cast< const SwTabFrm * >( pParent );\n if( pTabFrm->IsFollow() )\n pTabFrm = pTabFrm->FindMaster();\n\n while( pTabFrm )\n {\n sal_Bool bChanged = _InvalidateChildrenCursorPos( pTabFrm );\n if( bChanged )\n {\n ::vos::ORef< SwAccessibleContext > xAccImpl(\n GetMap()->GetContextImpl( pTabFrm, sal_False ) );\n if( xAccImpl.isValid() )\n {\n AccessibleEventObject aEvent;\n aEvent.EventId = AccessibleEventId::SELECTION_CHANGED;\n xAccImpl->FireAccessibleEvent( aEvent );\n }\n }\n\n pTabFrm = pTabFrm->GetFollow();\n }\n}\n\nsal_Bool SwAccessibleCell::HasCursor()\n{\n vos::OGuard aGuard( aMutex );\n return bIsSelected;\n}\n\nSwAccessibleCell::~SwAccessibleCell()\n{\n}\n\nOUString SAL_CALL SwAccessibleCell::getAccessibleDescription (void)\n throw (uno::RuntimeException)\n{\n return GetName();\n}\n\nOUString SAL_CALL SwAccessibleCell::getImplementationName()\n throw( uno::RuntimeException )\n{\n return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationName));\n}\n\nsal_Bool SAL_CALL SwAccessibleCell::supportsService(\n const ::rtl::OUString& sTestServiceName)\n throw (uno::RuntimeException)\n{\n return sTestServiceName.equalsAsciiL( sServiceName,\n sizeof(sServiceName)-1 ) ||\n sTestServiceName.equalsAsciiL( sAccessibleServiceName,\n sizeof(sAccessibleServiceName)-1 );\n}\n\nuno::Sequence< OUString > SAL_CALL SwAccessibleCell::getSupportedServiceNames()\n throw( uno::RuntimeException )\n{\n uno::Sequence< OUString > aRet(2);\n OUString* pArray = aRet.getArray();\n pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceName) );\n pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );\n return aRet;\n}\n\nvoid SwAccessibleCell::Dispose( sal_Bool bRecursive )\n{\n const SwFrm *pParent = GetParent( GetFrm(), IsInPagePreview() );\n ::vos::ORef< SwAccessibleContext > xAccImpl(\n GetMap()->GetContextImpl( pParent, sal_False ) );\n if( xAccImpl.isValid() )\n xAccImpl->DisposeChild( GetFrm(), bRecursive );\n SwAccessibleContext::Dispose( bRecursive );\n}\n\nvoid SwAccessibleCell::InvalidatePosOrSize( const SwRect& rOldBox )\n{\n const SwFrm *pParent = GetParent( GetFrm(), IsInPagePreview() );\n ::vos::ORef< SwAccessibleContext > xAccImpl(\n GetMap()->GetContextImpl( pParent, sal_False ) );\n if( xAccImpl.isValid() )\n xAccImpl->InvalidateChildPosOrSize( GetFrm(), rOldBox );\n SwAccessibleContext::InvalidatePosOrSize( rOldBox );\n}\n\n\n\/\/ ===== XAccessibleInterface ===========================================\n\nuno::Any SwAccessibleCell::queryInterface( const uno::Type& rType )\n throw( uno::RuntimeException )\n{\n if ( rType == ::getCppuType( static_cast< uno::Reference< XAccessibleValue > * >( 0 ) ) )\n {\n uno::Reference<XAccessibleValue> xValue = this;\n uno::Any aRet;\n aRet <<= xValue;\n return aRet;\n }\n else\n {\n return SwAccessibleContext::queryInterface( rType );\n }\n}\n\n\/\/====== XTypeProvider ====================================================\nuno::Sequence< uno::Type > SAL_CALL SwAccessibleCell::getTypes()\n throw(uno::RuntimeException)\n{\n uno::Sequence< uno::Type > aTypes( SwAccessibleContext::getTypes() );\n\n sal_Int32 nIndex = aTypes.getLength();\n aTypes.realloc( nIndex + 1 );\n\n uno::Type* pTypes = aTypes.getArray();\n pTypes[nIndex] = ::getCppuType( static_cast< uno::Reference< XAccessibleValue > * >( 0 ) );\n\n return aTypes;\n}\n\nuno::Sequence< sal_Int8 > SAL_CALL SwAccessibleCell::getImplementationId()\n throw(uno::RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n static uno::Sequence< sal_Int8 > aId( 16 );\n static sal_Bool bInit = sal_False;\n if(!bInit)\n {\n rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );\n bInit = sal_True;\n }\n return aId;\n}\n\n\/\/ ===== XAccessibleValue ===============================================\n\nSwFrmFmt* SwAccessibleCell::GetTblBoxFormat() const\n{\n DBG_ASSERT( GetFrm() != NULL, \"no frame?\" );\n DBG_ASSERT( GetFrm()->IsCellFrm(), \"no cell frame?\" );\n\n const SwCellFrm* pCellFrm = static_cast<const SwCellFrm*>( GetFrm() );\n return pCellFrm->GetTabBox()->GetFrmFmt();\n}\n\n\nuno::Any SwAccessibleCell::getCurrentValue( )\n throw( uno::RuntimeException )\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n CHECK_FOR_DEFUNC( XAccessibleValue );\n\n uno::Any aAny;\n aAny <<= GetTblBoxFormat()->GetTblBoxValue().GetValue();\n return aAny;\n}\n\nsal_Bool SwAccessibleCell::setCurrentValue( const uno::Any& aNumber )\n throw( uno::RuntimeException )\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n CHECK_FOR_DEFUNC( XAccessibleValue );\n\n double fValue = 0;\n sal_Bool bValid = (aNumber >>= fValue);\n if( bValid )\n {\n SwTblBoxValue aValue( fValue );\n GetTblBoxFormat()->SetAttr( aValue );\n }\n return bValid;\n}\n\nuno::Any SwAccessibleCell::getMaximumValue( )\n throw( uno::RuntimeException )\n{\n uno::Any aAny;\n aAny <<= DBL_MAX;\n return aAny;\n}\n\nuno::Any SwAccessibleCell::getMinimumValue( )\n throw( uno::RuntimeException )\n{\n uno::Any aAny;\n aAny <<= -DBL_MAX;\n return aAny;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swtypes.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 03:01:53 $\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#include \"swtypes.hxx\"\n\n#ifndef _STRING_HXX\n#include \"tools\/string.hxx\"\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _SV_WINDOW_HXX \/\/autogen\n#include <vcl\/window.hxx>\n#endif\n#ifndef _SV_GRAPH_HXX \/\/autogen\n#include <vcl\/graph.hxx>\n#endif\n#ifndef _UNO_LINGU_HXX\n#include <svx\/unolingu.hxx>\n#endif\n\n#ifndef _PAGEFRM_HXX\n#include <pagefrm.hxx>\n#endif\n#ifndef _SWATRSET_HXX\n#include <swatrset.hxx>\n#endif\n#ifndef _FRMFMT_HXX\n#include <frmfmt.hxx>\n#endif\n#ifndef _FRMTOOL_HXX\n#include <frmtool.hxx>\n#endif\n#ifndef _NDTXT_HXX\n#include <ndtxt.hxx>\n#endif\n#ifndef _UNDOBJ_HXX\n#include <undobj.hxx>\n#endif\n#ifndef _SWTABLE_HXX\n#include <swtable.hxx>\n#endif\n#ifndef _VISCRS_HXX\n#include <viscrs.hxx>\n#endif\n#ifndef _FNTCACHE_HXX\n#include <fntcache.hxx>\n#endif\n#ifndef _SWFNTCCH_HXX\n#include <swfntcch.hxx>\n#endif\n#ifndef _HFFRM_HXX\n#include <hffrm.hxx>\n#endif\n#ifndef _COLFRM_HXX\n#include <colfrm.hxx>\n#endif\n#ifndef _BODYFRM_HXX\n#include <bodyfrm.hxx>\n#endif\n#ifndef _TABFRM_HXX\n#include <tabfrm.hxx>\n#endif\n#ifndef _TXTFRM_HXX\n#include <txtfrm.hxx>\n#endif\n#ifndef _SWTBLFMT_HXX\n#include <swtblfmt.hxx>\n#endif\n#ifndef _ROWFRM_HXX\n#include <rowfrm.hxx>\n#endif\n#ifndef _CELLFRM_HXX\n#include <cellfrm.hxx>\n#endif\n#ifndef _SECTFRM_HXX\n#include <sectfrm.hxx>\n#endif\n\nnamespace css = com::sun::star;\n\n#ifndef PROFILE\n\/\/ Code zum Initialisieren von Statics im eigenen Code-Segment\n#pragma code_seg( \"SWSTATICS\" )\n#endif\n\nByteString aEmptyByteStr; \/\/ Konstante Strings\nString aEmptyStr; \/\/ Konstante Strings\nString aDotStr('.'); \/\/ Konstante Strings\n\nIMPL_FIXEDMEMPOOL_NEWDEL( SwAttrSet, 25, 25 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwStartNode, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwEndNode, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTableBox, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwUndoDelete, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwUndoInsert, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwPaM, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwCursor, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwShellCrsr, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTxtNode, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwpHints, 25, 25 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwFntObj, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwFontObj, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwBorderAttrs, 100, 100 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwCellFrm, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwRowFrm, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwColumnFrm, 40, 40 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwSectionFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTabFrm, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwPageFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwBodyFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwHeaderFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwFooterFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTxtFrm, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTableFmt, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTableLineFmt, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTableBoxFmt, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( _SwCursor_SavePos, 20, 20 )\n\n\n#ifndef PROFILE\n#pragma code_seg()\n#endif\n\nSize GetGraphicSizeTwip( const Graphic& rGraphic, OutputDevice* pOutDev )\n{\n const MapMode aMapTwip( MAP_TWIP );\n Size aSize( rGraphic.GetPrefSize() );\n if( MAP_PIXEL == rGraphic.GetPrefMapMode().GetMapUnit() )\n {\n if( !pOutDev )\n pOutDev = Application::GetDefaultDevice();\n aSize = pOutDev->PixelToLogic( aSize, aMapTwip );\n }\n else\n aSize = OutputDevice::LogicToLogic( aSize,\n rGraphic.GetPrefMapMode(), aMapTwip );\n return aSize;\n}\n\n\ncss::uno::Reference< css::linguistic2::XSpellChecker1 > GetSpellChecker()\n{\n return LinguMgr::GetSpellChecker();\n}\n\n\ncss::uno::Reference< css::linguistic2::XHyphenator > GetHyphenator()\n{\n return LinguMgr::GetHyphenator();\n}\n\n\ncss::uno::Reference< css::linguistic2::XThesaurus > GetThesaurus()\n{\n return LinguMgr::GetThesaurus();\n}\n\n\ncss::uno::Reference< css::linguistic2::XDictionaryList > GetDictionaryList()\n{\n return LinguMgr::GetDictionaryList();\n}\n\n\ncss::uno::Reference< css::beans::XPropertySet > GetLinguPropertySet()\n{\n return LinguMgr::GetLinguPropertySet();\n}\n\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.11.476); FILE MERGED 2006\/09\/01 17:51:17 kaib 1.11.476.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swtypes.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 20:43:48 $\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_sw.hxx\"\n\n#include \"swtypes.hxx\"\n\n#ifndef _STRING_HXX\n#include \"tools\/string.hxx\"\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _SV_WINDOW_HXX \/\/autogen\n#include <vcl\/window.hxx>\n#endif\n#ifndef _SV_GRAPH_HXX \/\/autogen\n#include <vcl\/graph.hxx>\n#endif\n#ifndef _UNO_LINGU_HXX\n#include <svx\/unolingu.hxx>\n#endif\n\n#ifndef _PAGEFRM_HXX\n#include <pagefrm.hxx>\n#endif\n#ifndef _SWATRSET_HXX\n#include <swatrset.hxx>\n#endif\n#ifndef _FRMFMT_HXX\n#include <frmfmt.hxx>\n#endif\n#ifndef _FRMTOOL_HXX\n#include <frmtool.hxx>\n#endif\n#ifndef _NDTXT_HXX\n#include <ndtxt.hxx>\n#endif\n#ifndef _UNDOBJ_HXX\n#include <undobj.hxx>\n#endif\n#ifndef _SWTABLE_HXX\n#include <swtable.hxx>\n#endif\n#ifndef _VISCRS_HXX\n#include <viscrs.hxx>\n#endif\n#ifndef _FNTCACHE_HXX\n#include <fntcache.hxx>\n#endif\n#ifndef _SWFNTCCH_HXX\n#include <swfntcch.hxx>\n#endif\n#ifndef _HFFRM_HXX\n#include <hffrm.hxx>\n#endif\n#ifndef _COLFRM_HXX\n#include <colfrm.hxx>\n#endif\n#ifndef _BODYFRM_HXX\n#include <bodyfrm.hxx>\n#endif\n#ifndef _TABFRM_HXX\n#include <tabfrm.hxx>\n#endif\n#ifndef _TXTFRM_HXX\n#include <txtfrm.hxx>\n#endif\n#ifndef _SWTBLFMT_HXX\n#include <swtblfmt.hxx>\n#endif\n#ifndef _ROWFRM_HXX\n#include <rowfrm.hxx>\n#endif\n#ifndef _CELLFRM_HXX\n#include <cellfrm.hxx>\n#endif\n#ifndef _SECTFRM_HXX\n#include <sectfrm.hxx>\n#endif\n\nnamespace css = com::sun::star;\n\n#ifndef PROFILE\n\/\/ Code zum Initialisieren von Statics im eigenen Code-Segment\n#pragma code_seg( \"SWSTATICS\" )\n#endif\n\nByteString aEmptyByteStr; \/\/ Konstante Strings\nString aEmptyStr; \/\/ Konstante Strings\nString aDotStr('.'); \/\/ Konstante Strings\n\nIMPL_FIXEDMEMPOOL_NEWDEL( SwAttrSet, 25, 25 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwStartNode, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwEndNode, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTableBox, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwUndoDelete, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwUndoInsert, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwPaM, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwCursor, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwShellCrsr, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTxtNode, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwpHints, 25, 25 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwFntObj, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwFontObj, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwBorderAttrs, 100, 100 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwCellFrm, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwRowFrm, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwColumnFrm, 40, 40 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwSectionFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTabFrm, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwPageFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwBodyFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwHeaderFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwFooterFrm, 20, 20 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTxtFrm, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTableFmt, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTableLineFmt, 10, 10 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTableBoxFmt, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( _SwCursor_SavePos, 20, 20 )\n\n\n#ifndef PROFILE\n#pragma code_seg()\n#endif\n\nSize GetGraphicSizeTwip( const Graphic& rGraphic, OutputDevice* pOutDev )\n{\n const MapMode aMapTwip( MAP_TWIP );\n Size aSize( rGraphic.GetPrefSize() );\n if( MAP_PIXEL == rGraphic.GetPrefMapMode().GetMapUnit() )\n {\n if( !pOutDev )\n pOutDev = Application::GetDefaultDevice();\n aSize = pOutDev->PixelToLogic( aSize, aMapTwip );\n }\n else\n aSize = OutputDevice::LogicToLogic( aSize,\n rGraphic.GetPrefMapMode(), aMapTwip );\n return aSize;\n}\n\n\ncss::uno::Reference< css::linguistic2::XSpellChecker1 > GetSpellChecker()\n{\n return LinguMgr::GetSpellChecker();\n}\n\n\ncss::uno::Reference< css::linguistic2::XHyphenator > GetHyphenator()\n{\n return LinguMgr::GetHyphenator();\n}\n\n\ncss::uno::Reference< css::linguistic2::XThesaurus > GetThesaurus()\n{\n return LinguMgr::GetThesaurus();\n}\n\n\ncss::uno::Reference< css::linguistic2::XDictionaryList > GetDictionaryList()\n{\n return LinguMgr::GetDictionaryList();\n}\n\n\ncss::uno::Reference< css::beans::XPropertySet > GetLinguPropertySet()\n{\n return LinguMgr::GetLinguPropertySet();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fdo#75492: table names can start the same way and still be different<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/===--- Index.cpp -----------------------------------------------*- C++-*-===\/\/\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#include \"Index.h\"\n#include \"Logger.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Support\/Error.h\"\n#include \"llvm\/Support\/SHA1.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\nnamespace clang {\nnamespace clangd {\n\nconstexpr uint32_t SymbolLocation::Position::MaxLine;\nconstexpr uint32_t SymbolLocation::Position::MaxColumn;\nvoid SymbolLocation::Position::setLine(uint32_t L) {\n if (L > MaxLine) {\n Line = MaxLine;\n return;\n }\n Line = L;\n}\nvoid SymbolLocation::Position::setColumn(uint32_t Col) {\n if (Col > MaxColumn) {\n Column = MaxColumn;\n return;\n }\n Column = Col;\n}\n\nraw_ostream &operator<<(raw_ostream &OS, const SymbolLocation &L) {\n if (!L)\n return OS << \"(none)\";\n return OS << L.FileURI << \"[\" << L.Start.line() << \":\" << L.Start.column()\n << \"-\" << L.End.line() << \":\" << L.End.column() << \")\";\n}\n\nSymbolID::SymbolID(StringRef USR) {\n auto Hash = SHA1::hash(arrayRefFromStringRef(USR));\n static_assert(sizeof(Hash) >= RawSize, \"RawSize larger than SHA1\");\n memcpy(HashValue.data(), Hash.data(), RawSize);\n}\n\nraw_ostream &operator<<(raw_ostream &OS, const SymbolID &ID) {\n return OS << toHex(ID.raw());\n}\n\nSymbolID SymbolID::fromRaw(StringRef Raw) {\n SymbolID ID;\n assert(Raw.size() == RawSize);\n memcpy(ID.HashValue.data(), Raw.data(), RawSize);\n return ID;\n}\n\nstd::string SymbolID::str() const { return toHex(raw()); }\n\nExpected<SymbolID> SymbolID::fromStr(StringRef Str) {\n if (Str.size() != RawSize * 2)\n return createStringError(inconvertibleErrorCode(), \"Bad ID length\");\n for (char C : Str)\n if (!isHexDigit(C))\n return createStringError(inconvertibleErrorCode(), \"Bad hex ID\");\n return fromRaw(fromHex(Str));\n}\n\nraw_ostream &operator<<(raw_ostream &OS, SymbolOrigin O) {\n if (O == SymbolOrigin::Unknown)\n return OS << \"unknown\";\n constexpr static char Sigils[] = \"ADSM4567\";\n for (unsigned I = 0; I < sizeof(Sigils); ++I)\n if (static_cast<uint8_t>(O) & 1u << I)\n OS << Sigils[I];\n return OS;\n}\n\nraw_ostream &operator<<(raw_ostream &OS, Symbol::SymbolFlag F) {\n if (F == Symbol::None)\n return OS << \"None\";\n std::string s;\n if (F & Symbol::Deprecated)\n s += \"deprecated|\";\n if (F & Symbol::IndexedForCodeCompletion)\n s += \"completion|\";\n return OS << StringRef(s).rtrim('|');\n}\n\nraw_ostream &operator<<(raw_ostream &OS, const Symbol &S) {\n return OS << S.Scope << S.Name;\n}\n\nfloat quality(const Symbol &S) {\n \/\/ This avoids a sharp gradient for tail symbols, and also neatly avoids the\n \/\/ question of whether 0 references means a bad symbol or missing data.\n if (S.References < 3)\n return 1;\n return std::log(S.References);\n}\n\nSymbolSlab::const_iterator SymbolSlab::find(const SymbolID &ID) const {\n auto It = std::lower_bound(\n Symbols.begin(), Symbols.end(), ID,\n [](const Symbol &S, const SymbolID &I) { return S.ID < I; });\n if (It != Symbols.end() && It->ID == ID)\n return It;\n return Symbols.end();\n}\n\n\/\/ Copy the underlying data of the symbol into the owned arena.\nstatic void own(Symbol &S, UniqueStringSaver &Strings) {\n visitStrings(S, [&](StringRef &V) { V = Strings.save(V); });\n}\n\nvoid SymbolSlab::Builder::insert(const Symbol &S) {\n auto R = SymbolIndex.try_emplace(S.ID, Symbols.size());\n if (R.second) {\n Symbols.push_back(S);\n own(Symbols.back(), UniqueStrings);\n } else {\n auto &Copy = Symbols[R.first->second] = S;\n own(Copy, UniqueStrings);\n }\n}\n\nSymbolSlab SymbolSlab::Builder::build() && {\n Symbols = {Symbols.begin(), Symbols.end()}; \/\/ Force shrink-to-fit.\n \/\/ Sort symbols so the slab can binary search over them.\n llvm::sort(Symbols,\n [](const Symbol &L, const Symbol &R) { return L.ID < R.ID; });\n \/\/ We may have unused strings from overwritten symbols. Build a new arena.\n BumpPtrAllocator NewArena;\n UniqueStringSaver Strings(NewArena);\n for (auto &S : Symbols)\n own(S, Strings);\n return SymbolSlab(std::move(NewArena), std::move(Symbols));\n}\n\nraw_ostream &operator<<(raw_ostream &OS, RefKind K) {\n if (K == RefKind::Unknown)\n return OS << \"Unknown\";\n static const std::vector<const char *> Messages = {\"Decl\", \"Def\", \"Ref\"};\n bool VisitedOnce = false;\n for (unsigned I = 0; I < Messages.size(); ++I) {\n if (static_cast<uint8_t>(K) & 1u << I) {\n if (VisitedOnce)\n OS << \", \";\n OS << Messages[I];\n VisitedOnce = true;\n }\n }\n return OS;\n}\n\nraw_ostream &operator<<(raw_ostream &OS, const Ref &R) {\n return OS << R.Location << \":\" << R.Kind;\n}\n\nvoid RefSlab::Builder::insert(const SymbolID &ID, const Ref &S) {\n auto &M = Refs[ID];\n M.push_back(S);\n M.back().Location.FileURI = UniqueStrings.save(M.back().Location.FileURI);\n}\n\nRefSlab RefSlab::Builder::build() && {\n \/\/ We can reuse the arena, as it only has unique strings and we need them all.\n \/\/ Reallocate refs on the arena to reduce waste and indirections when reading.\n std::vector<std::pair<SymbolID, ArrayRef<Ref>>> Result;\n Result.reserve(Refs.size());\n size_t NumRefs = 0;\n for (auto &Sym : Refs) {\n auto &SymRefs = Sym.second;\n llvm::sort(SymRefs);\n \/\/ FIXME: do we really need to dedup?\n SymRefs.erase(std::unique(SymRefs.begin(), SymRefs.end()), SymRefs.end());\n\n NumRefs += SymRefs.size();\n auto *Array = Arena.Allocate<Ref>(SymRefs.size());\n std::uninitialized_copy(SymRefs.begin(), SymRefs.end(), Array);\n Result.emplace_back(Sym.first, ArrayRef<Ref>(Array, SymRefs.size()));\n }\n return RefSlab(std::move(Result), std::move(Arena), NumRefs);\n}\n\nvoid SwapIndex::reset(std::unique_ptr<SymbolIndex> Index) {\n \/\/ Keep the old index alive, so we don't destroy it under lock (may be slow).\n std::shared_ptr<SymbolIndex> Pin;\n {\n std::lock_guard<std::mutex> Lock(Mutex);\n Pin = std::move(this->Index);\n this->Index = std::move(Index);\n }\n}\nstd::shared_ptr<SymbolIndex> SwapIndex::snapshot() const {\n std::lock_guard<std::mutex> Lock(Mutex);\n return Index;\n}\n\nbool fromJSON(const json::Value &Parameters, FuzzyFindRequest &Request) {\n json::ObjectMapper O(Parameters);\n int64_t Limit;\n bool OK =\n O && O.map(\"Query\", Request.Query) && O.map(\"Scopes\", Request.Scopes) &&\n O.map(\"Limit\", Limit) &&\n O.map(\"RestrictForCodeCompletion\", Request.RestrictForCodeCompletion) &&\n O.map(\"ProximityPaths\", Request.ProximityPaths);\n if (OK && Limit <= std::numeric_limits<uint32_t>::max())\n Request.Limit = Limit;\n return OK;\n}\n\njson::Value toJSON(const FuzzyFindRequest &Request) {\n return json::Object{\n {\"Query\", Request.Query},\n {\"Scopes\", json::Array{Request.Scopes}},\n {\"Limit\", Request.Limit},\n {\"RestrictForCodeCompletion\", Request.RestrictForCodeCompletion},\n {\"ProximityPaths\", json::Array{Request.ProximityPaths}},\n };\n}\n\nbool SwapIndex::fuzzyFind(const FuzzyFindRequest &R,\n function_ref<void(const Symbol &)> CB) const {\n return snapshot()->fuzzyFind(R, CB);\n}\nvoid SwapIndex::lookup(const LookupRequest &R,\n function_ref<void(const Symbol &)> CB) const {\n return snapshot()->lookup(R, CB);\n}\nvoid SwapIndex::refs(const RefsRequest &R,\n function_ref<void(const Ref &)> CB) const {\n return snapshot()->refs(R, CB);\n}\nsize_t SwapIndex::estimateMemoryUsage() const {\n return snapshot()->estimateMemoryUsage();\n}\n\n} \/\/ namespace clangd\n} \/\/ namespace clang\n<commit_msg>[clangd] Remember to serialize AnyScope in FuzzyFindRequest json.<commit_after>\/\/===--- Index.cpp -----------------------------------------------*- C++-*-===\/\/\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#include \"Index.h\"\n#include \"Logger.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Support\/Error.h\"\n#include \"llvm\/Support\/SHA1.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\nnamespace clang {\nnamespace clangd {\n\nconstexpr uint32_t SymbolLocation::Position::MaxLine;\nconstexpr uint32_t SymbolLocation::Position::MaxColumn;\nvoid SymbolLocation::Position::setLine(uint32_t L) {\n if (L > MaxLine) {\n Line = MaxLine;\n return;\n }\n Line = L;\n}\nvoid SymbolLocation::Position::setColumn(uint32_t Col) {\n if (Col > MaxColumn) {\n Column = MaxColumn;\n return;\n }\n Column = Col;\n}\n\nraw_ostream &operator<<(raw_ostream &OS, const SymbolLocation &L) {\n if (!L)\n return OS << \"(none)\";\n return OS << L.FileURI << \"[\" << L.Start.line() << \":\" << L.Start.column()\n << \"-\" << L.End.line() << \":\" << L.End.column() << \")\";\n}\n\nSymbolID::SymbolID(StringRef USR) {\n auto Hash = SHA1::hash(arrayRefFromStringRef(USR));\n static_assert(sizeof(Hash) >= RawSize, \"RawSize larger than SHA1\");\n memcpy(HashValue.data(), Hash.data(), RawSize);\n}\n\nraw_ostream &operator<<(raw_ostream &OS, const SymbolID &ID) {\n return OS << toHex(ID.raw());\n}\n\nSymbolID SymbolID::fromRaw(StringRef Raw) {\n SymbolID ID;\n assert(Raw.size() == RawSize);\n memcpy(ID.HashValue.data(), Raw.data(), RawSize);\n return ID;\n}\n\nstd::string SymbolID::str() const { return toHex(raw()); }\n\nExpected<SymbolID> SymbolID::fromStr(StringRef Str) {\n if (Str.size() != RawSize * 2)\n return createStringError(inconvertibleErrorCode(), \"Bad ID length\");\n for (char C : Str)\n if (!isHexDigit(C))\n return createStringError(inconvertibleErrorCode(), \"Bad hex ID\");\n return fromRaw(fromHex(Str));\n}\n\nraw_ostream &operator<<(raw_ostream &OS, SymbolOrigin O) {\n if (O == SymbolOrigin::Unknown)\n return OS << \"unknown\";\n constexpr static char Sigils[] = \"ADSM4567\";\n for (unsigned I = 0; I < sizeof(Sigils); ++I)\n if (static_cast<uint8_t>(O) & 1u << I)\n OS << Sigils[I];\n return OS;\n}\n\nraw_ostream &operator<<(raw_ostream &OS, Symbol::SymbolFlag F) {\n if (F == Symbol::None)\n return OS << \"None\";\n std::string s;\n if (F & Symbol::Deprecated)\n s += \"deprecated|\";\n if (F & Symbol::IndexedForCodeCompletion)\n s += \"completion|\";\n return OS << StringRef(s).rtrim('|');\n}\n\nraw_ostream &operator<<(raw_ostream &OS, const Symbol &S) {\n return OS << S.Scope << S.Name;\n}\n\nfloat quality(const Symbol &S) {\n \/\/ This avoids a sharp gradient for tail symbols, and also neatly avoids the\n \/\/ question of whether 0 references means a bad symbol or missing data.\n if (S.References < 3)\n return 1;\n return std::log(S.References);\n}\n\nSymbolSlab::const_iterator SymbolSlab::find(const SymbolID &ID) const {\n auto It = std::lower_bound(\n Symbols.begin(), Symbols.end(), ID,\n [](const Symbol &S, const SymbolID &I) { return S.ID < I; });\n if (It != Symbols.end() && It->ID == ID)\n return It;\n return Symbols.end();\n}\n\n\/\/ Copy the underlying data of the symbol into the owned arena.\nstatic void own(Symbol &S, UniqueStringSaver &Strings) {\n visitStrings(S, [&](StringRef &V) { V = Strings.save(V); });\n}\n\nvoid SymbolSlab::Builder::insert(const Symbol &S) {\n auto R = SymbolIndex.try_emplace(S.ID, Symbols.size());\n if (R.second) {\n Symbols.push_back(S);\n own(Symbols.back(), UniqueStrings);\n } else {\n auto &Copy = Symbols[R.first->second] = S;\n own(Copy, UniqueStrings);\n }\n}\n\nSymbolSlab SymbolSlab::Builder::build() && {\n Symbols = {Symbols.begin(), Symbols.end()}; \/\/ Force shrink-to-fit.\n \/\/ Sort symbols so the slab can binary search over them.\n llvm::sort(Symbols,\n [](const Symbol &L, const Symbol &R) { return L.ID < R.ID; });\n \/\/ We may have unused strings from overwritten symbols. Build a new arena.\n BumpPtrAllocator NewArena;\n UniqueStringSaver Strings(NewArena);\n for (auto &S : Symbols)\n own(S, Strings);\n return SymbolSlab(std::move(NewArena), std::move(Symbols));\n}\n\nraw_ostream &operator<<(raw_ostream &OS, RefKind K) {\n if (K == RefKind::Unknown)\n return OS << \"Unknown\";\n static const std::vector<const char *> Messages = {\"Decl\", \"Def\", \"Ref\"};\n bool VisitedOnce = false;\n for (unsigned I = 0; I < Messages.size(); ++I) {\n if (static_cast<uint8_t>(K) & 1u << I) {\n if (VisitedOnce)\n OS << \", \";\n OS << Messages[I];\n VisitedOnce = true;\n }\n }\n return OS;\n}\n\nraw_ostream &operator<<(raw_ostream &OS, const Ref &R) {\n return OS << R.Location << \":\" << R.Kind;\n}\n\nvoid RefSlab::Builder::insert(const SymbolID &ID, const Ref &S) {\n auto &M = Refs[ID];\n M.push_back(S);\n M.back().Location.FileURI = UniqueStrings.save(M.back().Location.FileURI);\n}\n\nRefSlab RefSlab::Builder::build() && {\n \/\/ We can reuse the arena, as it only has unique strings and we need them all.\n \/\/ Reallocate refs on the arena to reduce waste and indirections when reading.\n std::vector<std::pair<SymbolID, ArrayRef<Ref>>> Result;\n Result.reserve(Refs.size());\n size_t NumRefs = 0;\n for (auto &Sym : Refs) {\n auto &SymRefs = Sym.second;\n llvm::sort(SymRefs);\n \/\/ FIXME: do we really need to dedup?\n SymRefs.erase(std::unique(SymRefs.begin(), SymRefs.end()), SymRefs.end());\n\n NumRefs += SymRefs.size();\n auto *Array = Arena.Allocate<Ref>(SymRefs.size());\n std::uninitialized_copy(SymRefs.begin(), SymRefs.end(), Array);\n Result.emplace_back(Sym.first, ArrayRef<Ref>(Array, SymRefs.size()));\n }\n return RefSlab(std::move(Result), std::move(Arena), NumRefs);\n}\n\nvoid SwapIndex::reset(std::unique_ptr<SymbolIndex> Index) {\n \/\/ Keep the old index alive, so we don't destroy it under lock (may be slow).\n std::shared_ptr<SymbolIndex> Pin;\n {\n std::lock_guard<std::mutex> Lock(Mutex);\n Pin = std::move(this->Index);\n this->Index = std::move(Index);\n }\n}\nstd::shared_ptr<SymbolIndex> SwapIndex::snapshot() const {\n std::lock_guard<std::mutex> Lock(Mutex);\n return Index;\n}\n\nbool fromJSON(const json::Value &Parameters, FuzzyFindRequest &Request) {\n json::ObjectMapper O(Parameters);\n int64_t Limit;\n bool OK =\n O && O.map(\"Query\", Request.Query) && O.map(\"Scopes\", Request.Scopes) &&\n O.map(\"AnyScope\", Request.AnyScope) && O.map(\"Limit\", Limit) &&\n O.map(\"RestrictForCodeCompletion\", Request.RestrictForCodeCompletion) &&\n O.map(\"ProximityPaths\", Request.ProximityPaths);\n if (OK && Limit <= std::numeric_limits<uint32_t>::max())\n Request.Limit = Limit;\n return OK;\n}\n\njson::Value toJSON(const FuzzyFindRequest &Request) {\n return json::Object{\n {\"Query\", Request.Query},\n {\"Scopes\", json::Array{Request.Scopes}},\n {\"AnyScope\", Request.AnyScope},\n {\"Limit\", Request.Limit},\n {\"RestrictForCodeCompletion\", Request.RestrictForCodeCompletion},\n {\"ProximityPaths\", json::Array{Request.ProximityPaths}},\n };\n}\n\nbool SwapIndex::fuzzyFind(const FuzzyFindRequest &R,\n function_ref<void(const Symbol &)> CB) const {\n return snapshot()->fuzzyFind(R, CB);\n}\nvoid SwapIndex::lookup(const LookupRequest &R,\n function_ref<void(const Symbol &)> CB) const {\n return snapshot()->lookup(R, CB);\n}\nvoid SwapIndex::refs(const RefsRequest &R,\n function_ref<void(const Ref &)> CB) const {\n return snapshot()->refs(R, CB);\n}\nsize_t SwapIndex::estimateMemoryUsage() const {\n return snapshot()->estimateMemoryUsage();\n}\n\n} \/\/ namespace clangd\n} \/\/ namespace clang\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlfonte.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-08-14 17:22:45 $\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#pragma hdrstop\n\n#ifndef _HINTIDS_HXX\n#include \"hintids.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_\n#include <com\/sun\/star\/text\/XTextDocument.hpp>\n#endif\n#ifndef _XMLOFF_XMLFONTAUTOSTYLEPOOL_HXX\n#include <xmloff\/XMLFontAutoStylePool.hxx>\n#endif\n#ifndef _SVX_FONTITEM_HXX\n#include <svx\/fontitem.hxx>\n#endif\n#ifndef _UNOOBJ_HXX\n#include <unoobj.hxx>\n#endif\n#ifndef _DOC_HXX \/\/autogen wg. SwDoc\n#include <doc.hxx>\n#endif\n\n#ifndef _XMLEXP_HXX\n#include <xmlexp.hxx>\n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::text;\n\nclass SwXMLFontAutoStylePool_Impl: public XMLFontAutoStylePool\n{\n public:\n\n SwXMLFontAutoStylePool_Impl( SwXMLExport& rExport );\n\n};\n\nSwXMLFontAutoStylePool_Impl::SwXMLFontAutoStylePool_Impl(\n SwXMLExport& rExport ) :\n XMLFontAutoStylePool( rExport )\n{\n sal_uInt16 aWhichIds[3] = { RES_CHRATR_FONT, RES_CHRATR_CJK_FONT,\n RES_CHRATR_CTL_FONT };\n\n Reference < XTextDocument > xTextDoc( rExport.GetModel(), UNO_QUERY );\n Reference < XText > xText = xTextDoc->getText();\n Reference<XUnoTunnel> xTextTunnel( xText, UNO_QUERY);\n ASSERT( xTextTunnel.is(), \"missing XUnoTunnel for Cursor\" );\n if( !xTextTunnel.is() )\n return;\n\n SwXText *pText = (SwXText *)xTextTunnel->getSomething(\n SwXText::getUnoTunnelId() );\n ASSERT( pText, \"SwXText missing\" );\n if( !pText )\n return;\n\n const SfxItemPool& rPool = pText->GetDoc()->GetAttrPool();\n const SfxPoolItem* pItem;\n for( sal_uInt16 i=0; i<3; i++ )\n {\n sal_uInt16 nWhichId = aWhichIds[i];\n\n const SvxFontItem& rFont =\n (const SvxFontItem&)rPool.GetDefaultItem( nWhichId );\n Add( rFont.GetFamilyName(), rFont.GetStyleName(),\n rFont.GetFamily(), rFont.GetPitch(), rFont.GetCharSet() );\n sal_uInt16 nItems = rPool.GetItemCount( nWhichId );\n for( sal_uInt16 j = 0; j < nItems; ++j )\n {\n if( 0 != (pItem = rPool.GetItem( nWhichId, j ) ) )\n {\n const SvxFontItem *pFont =\n (const SvxFontItem *)pItem;\n Add( pFont->GetFamilyName(), pFont->GetStyleName(),\n pFont->GetFamily(), pFont->GetPitch(),\n pFont->GetCharSet() );\n }\n }\n }\n}\n\n\nXMLFontAutoStylePool* SwXMLExport::CreateFontAutoStylePool()\n{\n return new SwXMLFontAutoStylePool_Impl( *this );\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.6.2); FILE MERGED 2006\/09\/01 17:52:46 kaib 1.6.2.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlfonte.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 22:29:06 $\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_sw.hxx\"\n\n\n#ifndef _HINTIDS_HXX\n#include \"hintids.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_\n#include <com\/sun\/star\/text\/XTextDocument.hpp>\n#endif\n#ifndef _XMLOFF_XMLFONTAUTOSTYLEPOOL_HXX\n#include <xmloff\/XMLFontAutoStylePool.hxx>\n#endif\n#ifndef _SVX_FONTITEM_HXX\n#include <svx\/fontitem.hxx>\n#endif\n#ifndef _UNOOBJ_HXX\n#include <unoobj.hxx>\n#endif\n#ifndef _DOC_HXX \/\/autogen wg. SwDoc\n#include <doc.hxx>\n#endif\n\n#ifndef _XMLEXP_HXX\n#include <xmlexp.hxx>\n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::text;\n\nclass SwXMLFontAutoStylePool_Impl: public XMLFontAutoStylePool\n{\n public:\n\n SwXMLFontAutoStylePool_Impl( SwXMLExport& rExport );\n\n};\n\nSwXMLFontAutoStylePool_Impl::SwXMLFontAutoStylePool_Impl(\n SwXMLExport& rExport ) :\n XMLFontAutoStylePool( rExport )\n{\n sal_uInt16 aWhichIds[3] = { RES_CHRATR_FONT, RES_CHRATR_CJK_FONT,\n RES_CHRATR_CTL_FONT };\n\n Reference < XTextDocument > xTextDoc( rExport.GetModel(), UNO_QUERY );\n Reference < XText > xText = xTextDoc->getText();\n Reference<XUnoTunnel> xTextTunnel( xText, UNO_QUERY);\n ASSERT( xTextTunnel.is(), \"missing XUnoTunnel for Cursor\" );\n if( !xTextTunnel.is() )\n return;\n\n SwXText *pText = (SwXText *)xTextTunnel->getSomething(\n SwXText::getUnoTunnelId() );\n ASSERT( pText, \"SwXText missing\" );\n if( !pText )\n return;\n\n const SfxItemPool& rPool = pText->GetDoc()->GetAttrPool();\n const SfxPoolItem* pItem;\n for( sal_uInt16 i=0; i<3; i++ )\n {\n sal_uInt16 nWhichId = aWhichIds[i];\n\n const SvxFontItem& rFont =\n (const SvxFontItem&)rPool.GetDefaultItem( nWhichId );\n Add( rFont.GetFamilyName(), rFont.GetStyleName(),\n rFont.GetFamily(), rFont.GetPitch(), rFont.GetCharSet() );\n sal_uInt16 nItems = rPool.GetItemCount( nWhichId );\n for( sal_uInt16 j = 0; j < nItems; ++j )\n {\n if( 0 != (pItem = rPool.GetItem( nWhichId, j ) ) )\n {\n const SvxFontItem *pFont =\n (const SvxFontItem *)pItem;\n Add( pFont->GetFamilyName(), pFont->GetStyleName(),\n pFont->GetFamily(), pFont->GetPitch(),\n pFont->GetCharSet() );\n }\n }\n }\n}\n\n\nXMLFontAutoStylePool* SwXMLExport::CreateFontAutoStylePool()\n{\n return new SwXMLFontAutoStylePool_Impl( *this );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swabstdlg.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2007-10-15 12:15:35 $\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_sw.hxx\"\n\n#include \"swabstdlg.hxx\"\n#include \"swuilib.hxx\"\n\n#include <osl\/module.hxx>\n#include <tools\/string.hxx>\n\ntypedef SwAbstractDialogFactory* (__LOADONCALLAPI *SwFuncPtrCreateDialogFactory)();\n\nextern \"C\" { static void SAL_CALL thisModule() {} }\n\nSwAbstractDialogFactory* SwAbstractDialogFactory::Create()\n{\n SwFuncPtrCreateDialogFactory fp = 0;\n static ::osl::Module aDialogLibrary;\n if ( aDialogLibrary.is() || aDialogLibrary.loadRelative( &thisModule, String( RTL_CONSTASCII_USTRINGPARAM( DLL_NAME ) ) ) )\n fp = ( SwAbstractDialogFactory* (__LOADONCALLAPI*)() )\n aDialogLibrary.getFunctionSymbol( ::rtl::OUString::createFromAscii(\"CreateDialogFactory\") );\n if ( fp )\n return fp();\n return 0;\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.226); FILE MERGED 2008\/03\/31 16:57:41 rt 1.6.226.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: swabstdlg.cxx,v $\n * $Revision: 1.7 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_sw.hxx\"\n\n#include \"swabstdlg.hxx\"\n#include \"swuilib.hxx\"\n\n#include <osl\/module.hxx>\n#include <tools\/string.hxx>\n\ntypedef SwAbstractDialogFactory* (__LOADONCALLAPI *SwFuncPtrCreateDialogFactory)();\n\nextern \"C\" { static void SAL_CALL thisModule() {} }\n\nSwAbstractDialogFactory* SwAbstractDialogFactory::Create()\n{\n SwFuncPtrCreateDialogFactory fp = 0;\n static ::osl::Module aDialogLibrary;\n if ( aDialogLibrary.is() || aDialogLibrary.loadRelative( &thisModule, String( RTL_CONSTASCII_USTRINGPARAM( DLL_NAME ) ) ) )\n fp = ( SwAbstractDialogFactory* (__LOADONCALLAPI*)() )\n aDialogLibrary.getFunctionSymbol( ::rtl::OUString::createFromAscii(\"CreateDialogFactory\") );\n if ( fp )\n return fp();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _TASKING_SCHEDULER_HPP_\n#define _TASKING_SCHEDULER_HPP_\n\n#include \"Scheduler.hpp\"\n#include <Timestamp.hpp>\n#include <glog\/logging.h>\n\nDECLARE_int64( periodic_poll_ticks );\n\nclass TaskManager;\nstruct task_worker_args;\n\nclass TaskingScheduler : public Scheduler {\n private:\n ThreadQueue readyQ;\n ThreadQueue periodicQ;\n ThreadQueue unassignedQ;\n\n Thread * master;\n Thread * current_thread; \n threadid_t nextId;\n \n uint64_t num_idle;\n TaskManager * task_manager;\n uint64_t num_workers;\n \n Thread * getWorker ();\n\n task_worker_args * work_args;\n\n \/\/ STUB: replace with real periodic threads\n SoftXMT_Timestamp previous_periodic_ts;\n int periodctr;\n Thread * periodicDequeue() {\n \/\/ tick the timestap counter\n SoftXMT_tick();\n SoftXMT_Timestamp current_ts = SoftXMT_get_timestamp();\n\n if( current_ts - previous_periodic_ts > FLAGS_periodic_poll_ticks ) {\n previous_periodic_ts = current_ts;\n return periodicQ.dequeue();\n } else {\n return NULL;\n }\n }\n \/\/\/\/\/\/\n\n bool queuesFinished();\n\n Thread * nextCoroutine ( bool isBlocking=true ) {\n do {\n Thread * result;\n\n \/\/ check for periodic tasks\n result = periodicDequeue();\n if (result != NULL) {\n \/\/ DVLOG(5) << current_thread->id << \" scheduler: pick periodic\";\n return result;\n }\n\n \/\/ check ready tasks\n result = readyQ.dequeue();\n if (result != NULL) {\n \/\/ DVLOG(5) << current_thread->id << \" scheduler: pick ready\";\n return result;\n }\n\n \/\/ check for new workers\n result = getWorker();\n if (result != NULL) {\n \/\/ DVLOG(5) << current_thread->id << \" scheduler: pick task worker\";\n return result;\n }\n\n \/\/ no coroutines can run, so handle\n \/*DVLOG(5) << current_thread->id << \" scheduler: no coroutines can run\"\n << \"[isBlocking=\" << isBlocking\n << \" periodQ=\" << (periodicQ.empty() ? \"empty\" : \"full\")\n << \" unassignedQ=\" << (unassignedQ.empty() ? \"empty\" : \"full\") << \"]\";*\/\n usleep(1);\n } while ( isBlocking || !queuesFinished() );\n \/\/ exit if all threads exited, including idle workers\n \/\/ TODO just as use mightBeWork as shortcut, also kill all idle unassigned workers on cbarrier_exit\n \n return NULL;\n }\n\n\n public:\n TaskingScheduler ( Thread * master, TaskManager * taskman ); \n\n Thread * get_current_thread() {\n return current_thread;\n }\n \n void assignTid( Thread * thr ) {\n thr->id = nextId++;\n }\n \n void createWorkers( uint64_t num );\n Thread* maybeSpawnCoroutines( );\n void onWorkerStart( );\n\n void unassigned( Thread * thr ) {\n unassignedQ.enqueue( thr );\n }\n\n void ready( Thread * thr ) {\n readyQ.enqueue( thr );\n }\n\n void periodic( Thread * thr ) {\n periodicQ.enqueue( thr );\n }\n\n \/\/\/ run threads until all exit \n void run ( ); \n\n bool thread_yield( );\n bool thread_yield_periodic( );\n void thread_suspend( );\n void thread_wake( Thread * next );\n void thread_yield_wake( Thread * next );\n void thread_suspend_wake( Thread * next );\n bool thread_idle( uint64_t total_idle ); \n bool thread_idle( );\n void thread_join( Thread* wait_on );\n\n \/\/ Start running threads from <scheduler> until one dies. Return that Thread\n \/\/ (which can't be restarted--it's trash.) If <result> non-NULL,\n \/\/ store the Thread's exit value there.\n \/\/ If no threads to run, returns NULL.\n Thread * thread_wait( void **result );\n\n\n void thread_on_exit( );\n}; \n\nstruct task_worker_args {\n TaskManager *const tasks;\n TaskingScheduler *const scheduler;\n\n task_worker_args( TaskManager * task_manager, TaskingScheduler * sched )\n : tasks( task_manager )\n , scheduler( sched ) { }\n};\n \n\n\/\/\/ Yield the CPU to the next Thread on your scheduler. Doesn't ever touch\n\/\/\/ the master Thread.\ninline bool TaskingScheduler::thread_yield( ) {\n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n\n ready( current_thread ); \n \n Thread * yieldedThr = current_thread;\n\n Thread * next = nextCoroutine( );\n bool gotRescheduled = (next == yieldedThr);\n \n current_thread = next;\n \/\/DVLOG(5) << \"Thread \" << yieldedThr->id << \" yielding to \" << next->id << (gotRescheduled ? \" (same thread).\" : \" (diff thread).\");\n thread_context_switch( yieldedThr, next, NULL);\n \n return gotRescheduled; \/\/ 0=another ran; 1=me got rescheduled immediately\n}\n\n\/\/\/ For periodic threads: yield the CPU to the next Thread on your scheduler. Doesn't ever touch\n\/\/\/ the master Thread.\ninline bool TaskingScheduler::thread_yield_periodic( ) {\n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n\n periodic( current_thread ); \n \n Thread * yieldedThr = current_thread;\n\n Thread * next = nextCoroutine( );\n bool gotRescheduled = (next == yieldedThr);\n \n current_thread = next;\n \/\/DVLOG(5) << \"Thread \" << yieldedThr->id << \" yielding to \" << next->id << (gotRescheduled ? \" (same thread).\" : \" (diff thread).\");\n thread_context_switch( yieldedThr, next, NULL);\n \n return gotRescheduled; \/\/ 0=another ran; 1=me got rescheduled immediately\n}\n\n\/\/\/ Suspend the current Thread. Thread is not placed on any queue.\ninline void TaskingScheduler::thread_suspend( ) {\n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n CHECK( thread_is_running(current_thread) ) << \"may only suspend a running coroutine\";\n \n Thread * yieldedThr = current_thread;\n \n Thread * next = nextCoroutine( );\n \n current_thread = next;\n thread_context_switch( yieldedThr, next, NULL);\n}\n\n\/\/\/ Wake a suspended Thread by putting it on the run queue.\n\/\/\/ For now, waking a running Thread is a fatal error.\n\/\/\/ For now, waking a queued Thread is also a fatal error. \n\/\/\/ For now, can only wake a Thread on your scheduler\ninline void TaskingScheduler::thread_wake( Thread * next ) {\n CHECK( next->sched == this ) << \"can only wake a Thread on your scheduler\";\n CHECK( next->next == NULL ) << \"woken Thread should not be on any queue\";\n CHECK( !thread_is_running( next ) ) << \"woken Thread should not be running\";\n \n DVLOG(5) << \"Thread \" << current_thread->id << \" wakes thread \" << next->id;\n\n ready( next );\n}\n\n\/\/\/ Yield the current Thread and wake a suspended thread.\n\/\/\/ For now, waking a running Thread is a fatal error.\n\/\/\/ For now, waking a queued Thread is also a fatal error. \ninline void TaskingScheduler::thread_yield_wake( Thread * next ) { \n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n CHECK( next->sched == this ) << \"can only wake a Thread on your scheduler\";\n CHECK( next->next == NULL ) << \"woken Thread should not be on any queue\";\n CHECK( !thread_is_running( next ) ) << \"woken Thread should not be running\";\n \n Thread * yieldedThr = current_thread;\n ready( yieldedThr );\n \n current_thread = next;\n thread_context_switch( yieldedThr, next, NULL);\n}\n\n\/\/\/ Suspend current Thread and wake a suspended thread.\n\/\/\/ For now, waking a running Thread is a fatal error.\n\/\/\/ For now, waking a queued Thread is also a fatal error. \ninline void TaskingScheduler::thread_suspend_wake( Thread *next ) {\n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n CHECK( next->next == NULL ) << \"woken Thread should not be on any queue\";\n CHECK( !thread_is_running( next ) ) << \"woken Thread should not be running\";\n \n Thread * yieldedThr = current_thread;\n \n current_thread = next;\n thread_context_switch( yieldedThr, next, NULL);\n}\n\n \n\/\/\/ Make the current Thread idle.\n\/\/\/ Like suspend except the Thread is not blocking on a\n\/\/\/ particular resource, just waiting to be woken.\ninline bool TaskingScheduler::thread_idle( uint64_t total_idle ) {\n CHECK( num_idle+1 <= total_idle ) << \"number of idle threads should not be more than total\"\n << \" (\" << num_idle+1 << \" \/ \" << total_idle << \")\";\n if (num_idle+1 == total_idle) {\n DVLOG(5) << \"going idle and is last\";\n return false;\n } else {\n DVLOG(5) << \"going idle and is \" << num_idle+1 << \" of \" << total_idle;\n num_idle++;\n \n unassigned( current_thread );\n \n thread_suspend( );\n \n \/\/ woke so decrement idle counter\n num_idle--;\n\n return true;\n }\n}\n\ninline bool TaskingScheduler::thread_idle( ) {\n return thread_idle( num_workers );\n}\n\ninline void TaskingScheduler::thread_on_exit( ) {\n Thread * exitedThr = current_thread;\n current_thread = master;\n\n thread_context_switch( exitedThr, master, (void *)exitedThr);\n}\n\n\n\n\n#endif\n\n<commit_msg>make sure suspend sets running bit before finding next coro<commit_after>#ifndef _TASKING_SCHEDULER_HPP_\n#define _TASKING_SCHEDULER_HPP_\n\n#include \"Scheduler.hpp\"\n#include <Timestamp.hpp>\n#include <glog\/logging.h>\n\nDECLARE_int64( periodic_poll_ticks );\n\nclass TaskManager;\nstruct task_worker_args;\n\nclass TaskingScheduler : public Scheduler {\n private:\n ThreadQueue readyQ;\n ThreadQueue periodicQ;\n ThreadQueue unassignedQ;\n\n Thread * master;\n Thread * current_thread; \n threadid_t nextId;\n \n uint64_t num_idle;\n TaskManager * task_manager;\n uint64_t num_workers;\n \n Thread * getWorker ();\n\n task_worker_args * work_args;\n\n \/\/ STUB: replace with real periodic threads\n SoftXMT_Timestamp previous_periodic_ts;\n int periodctr;\n Thread * periodicDequeue() {\n \/\/ tick the timestap counter\n SoftXMT_tick();\n SoftXMT_Timestamp current_ts = SoftXMT_get_timestamp();\n\n if( current_ts - previous_periodic_ts > FLAGS_periodic_poll_ticks ) {\n previous_periodic_ts = current_ts;\n return periodicQ.dequeue();\n } else {\n return NULL;\n }\n }\n \/\/\/\/\/\/\n\n bool queuesFinished();\n\n Thread * nextCoroutine ( bool isBlocking=true ) {\n do {\n Thread * result;\n\n \/\/ check for periodic tasks\n result = periodicDequeue();\n if (result != NULL) {\n \/\/ DVLOG(5) << current_thread->id << \" scheduler: pick periodic\";\n return result;\n }\n\n \/\/ check ready tasks\n result = readyQ.dequeue();\n if (result != NULL) {\n \/\/ DVLOG(5) << current_thread->id << \" scheduler: pick ready\";\n return result;\n }\n\n \/\/ check for new workers\n result = getWorker();\n if (result != NULL) {\n \/\/ DVLOG(5) << current_thread->id << \" scheduler: pick task worker\";\n return result;\n }\n\n \/\/ no coroutines can run, so handle\n \/*DVLOG(5) << current_thread->id << \" scheduler: no coroutines can run\"\n << \"[isBlocking=\" << isBlocking\n << \" periodQ=\" << (periodicQ.empty() ? \"empty\" : \"full\")\n << \" unassignedQ=\" << (unassignedQ.empty() ? \"empty\" : \"full\") << \"]\";*\/\n usleep(1);\n } while ( isBlocking || !queuesFinished() );\n \/\/ exit if all threads exited, including idle workers\n \/\/ TODO just as use mightBeWork as shortcut, also kill all idle unassigned workers on cbarrier_exit\n \n return NULL;\n }\n\n\n public:\n TaskingScheduler ( Thread * master, TaskManager * taskman ); \n\n Thread * get_current_thread() {\n return current_thread;\n }\n \n void assignTid( Thread * thr ) {\n thr->id = nextId++;\n }\n \n void createWorkers( uint64_t num );\n Thread* maybeSpawnCoroutines( );\n void onWorkerStart( );\n\n void unassigned( Thread * thr ) {\n unassignedQ.enqueue( thr );\n }\n\n void ready( Thread * thr ) {\n readyQ.enqueue( thr );\n }\n\n void periodic( Thread * thr ) {\n periodicQ.enqueue( thr );\n }\n\n \/\/\/ run threads until all exit \n void run ( ); \n\n bool thread_yield( );\n bool thread_yield_periodic( );\n void thread_suspend( );\n void thread_wake( Thread * next );\n void thread_yield_wake( Thread * next );\n void thread_suspend_wake( Thread * next );\n bool thread_idle( uint64_t total_idle ); \n bool thread_idle( );\n void thread_join( Thread* wait_on );\n\n \/\/ Start running threads from <scheduler> until one dies. Return that Thread\n \/\/ (which can't be restarted--it's trash.) If <result> non-NULL,\n \/\/ store the Thread's exit value there.\n \/\/ If no threads to run, returns NULL.\n Thread * thread_wait( void **result );\n\n\n void thread_on_exit( );\n}; \n\nstruct task_worker_args {\n TaskManager *const tasks;\n TaskingScheduler *const scheduler;\n\n task_worker_args( TaskManager * task_manager, TaskingScheduler * sched )\n : tasks( task_manager )\n , scheduler( sched ) { }\n};\n \n\n\/\/\/ Yield the CPU to the next Thread on your scheduler. Doesn't ever touch\n\/\/\/ the master Thread.\ninline bool TaskingScheduler::thread_yield( ) {\n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n\n ready( current_thread ); \n \n Thread * yieldedThr = current_thread;\n\n Thread * next = nextCoroutine( );\n bool gotRescheduled = (next == yieldedThr);\n \n current_thread = next;\n \/\/DVLOG(5) << \"Thread \" << yieldedThr->id << \" yielding to \" << next->id << (gotRescheduled ? \" (same thread).\" : \" (diff thread).\");\n thread_context_switch( yieldedThr, next, NULL);\n \n return gotRescheduled; \/\/ 0=another ran; 1=me got rescheduled immediately\n}\n\n\/\/\/ For periodic threads: yield the CPU to the next Thread on your scheduler. Doesn't ever touch\n\/\/\/ the master Thread.\ninline bool TaskingScheduler::thread_yield_periodic( ) {\n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n\n periodic( current_thread ); \n \n Thread * yieldedThr = current_thread;\n\n Thread * next = nextCoroutine( );\n bool gotRescheduled = (next == yieldedThr);\n \n current_thread = next;\n \/\/DVLOG(5) << \"Thread \" << yieldedThr->id << \" yielding to \" << next->id << (gotRescheduled ? \" (same thread).\" : \" (diff thread).\");\n thread_context_switch( yieldedThr, next, NULL);\n \n return gotRescheduled; \/\/ 0=another ran; 1=me got rescheduled immediately\n}\n\n\/\/\/ Suspend the current Thread. Thread is not placed on any queue.\ninline void TaskingScheduler::thread_suspend( ) {\n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n CHECK( thread_is_running(current_thread) ) << \"may only suspend a running coroutine\";\n \n Thread * yieldedThr = current_thread;\n yieldedThr->co->running = 0;\n Thread * next = nextCoroutine( );\n \n current_thread = next;\n thread_context_switch( yieldedThr, next, NULL);\n}\n\n\/\/\/ Wake a suspended Thread by putting it on the run queue.\n\/\/\/ For now, waking a running Thread is a fatal error.\n\/\/\/ For now, waking a queued Thread is also a fatal error. \n\/\/\/ For now, can only wake a Thread on your scheduler\ninline void TaskingScheduler::thread_wake( Thread * next ) {\n CHECK( next->sched == this ) << \"can only wake a Thread on your scheduler\";\n CHECK( next->next == NULL ) << \"woken Thread should not be on any queue\";\n CHECK( !thread_is_running( next ) ) << \"woken Thread should not be running\";\n \n DVLOG(5) << \"Thread \" << current_thread->id << \" wakes thread \" << next->id;\n\n ready( next );\n}\n\n\/\/\/ Yield the current Thread and wake a suspended thread.\n\/\/\/ For now, waking a running Thread is a fatal error.\n\/\/\/ For now, waking a queued Thread is also a fatal error. \ninline void TaskingScheduler::thread_yield_wake( Thread * next ) { \n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n CHECK( next->sched == this ) << \"can only wake a Thread on your scheduler\";\n CHECK( next->next == NULL ) << \"woken Thread should not be on any queue\";\n CHECK( !thread_is_running( next ) ) << \"woken Thread should not be running\";\n \n Thread * yieldedThr = current_thread;\n ready( yieldedThr );\n \n current_thread = next;\n thread_context_switch( yieldedThr, next, NULL);\n}\n\n\/\/\/ Suspend current Thread and wake a suspended thread.\n\/\/\/ For now, waking a running Thread is a fatal error.\n\/\/\/ For now, waking a queued Thread is also a fatal error. \ninline void TaskingScheduler::thread_suspend_wake( Thread *next ) {\n CHECK( current_thread != master ) << \"can't yield on a system Thread\";\n CHECK( next->next == NULL ) << \"woken Thread should not be on any queue\";\n CHECK( !thread_is_running( next ) ) << \"woken Thread should not be running\";\n \n Thread * yieldedThr = current_thread;\n \n current_thread = next;\n thread_context_switch( yieldedThr, next, NULL);\n}\n\n \n\/\/\/ Make the current Thread idle.\n\/\/\/ Like suspend except the Thread is not blocking on a\n\/\/\/ particular resource, just waiting to be woken.\ninline bool TaskingScheduler::thread_idle( uint64_t total_idle ) {\n CHECK( num_idle+1 <= total_idle ) << \"number of idle threads should not be more than total\"\n << \" (\" << num_idle+1 << \" \/ \" << total_idle << \")\";\n if (num_idle+1 == total_idle) {\n DVLOG(5) << \"going idle and is last\";\n return false;\n } else {\n DVLOG(5) << \"going idle and is \" << num_idle+1 << \" of \" << total_idle;\n num_idle++;\n \n unassigned( current_thread );\n \n thread_suspend( );\n \n \/\/ woke so decrement idle counter\n num_idle--;\n\n return true;\n }\n}\n\ninline bool TaskingScheduler::thread_idle( ) {\n return thread_idle( num_workers );\n}\n\ninline void TaskingScheduler::thread_on_exit( ) {\n Thread * exitedThr = current_thread;\n current_thread = master;\n\n thread_context_switch( exitedThr, master, (void *)exitedThr);\n}\n\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\n\/**************************************************************************\n * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n#include <TTree.h> \n#include <TVector.h>\n#include <TObjArray.h>\n#include <TFile.h>\n#include <TDirectory.h>\n#include <TRandom.h>\n#include <TArrayI.h>\n#include <TH1.h>\n\n\n#include \"AliSTARTDigitizer.h\"\n#include \"AliSTART.h\"\n#include \"AliSTARThit.h\"\n#include \"AliSTARThitPhoton.h\"\n#include \"AliSTARTdigit.h\"\n#include \"AliRunDigitizer.h\"\n#include \"AliHeader.h\"\n#include \"AliGenEventHeader.h\"\n#include \"AliRun.h\"\n#include \"AliPDG.h\"\n#include \"AliLoader.h\"\n#include \"AliRunLoader.h\"\n#include \"AliSTARTLoader.h\"\n\n#include <stdlib.h>\n#include <Riostream.h>\n#include <Riostream.h>\n\nClassImp(AliSTARTDigitizer)\n\n\/\/___________________________________________\n AliSTARTDigitizer::AliSTARTDigitizer() :AliDigitizer()\n{\n\/\/ Default ctor - don't use it\n ;\n}\n\n\/\/___________________________________________\nAliSTARTDigitizer::AliSTARTDigitizer(AliRunDigitizer* manager) \n :AliDigitizer(manager) \n{\n\tcout<<\"AliSTARTDigitizer::AliSTARTDigitizer\"<<endl;\n\/\/ ctor which should be used\n\/\/ fDebug =0;\n \/\/ if (GetDebug()>2)\n \/\/ cerr<<\"AliSTARTDigitizer::AliSTARTDigitizer\"\n \/\/ <<\"(AliRunDigitizer* manager) was processed\"<<endl;\n\n}\n\n\/\/------------------------------------------------------------------------\nAliSTARTDigitizer::~AliSTARTDigitizer()\n{\n\/\/ Destructor\n\n\n}\n\n \/\/------------------------------------------------------------------------\nBool_t AliSTARTDigitizer::Init()\n{\n\/\/ Initialization\n cout<<\"AliSTARTDigitizer::Init\"<<endl;\n return kTRUE;\n}\n \n\n\/\/---------------------------------------------------------------------\n\nvoid AliSTARTDigitizer::Exec(Option_t* \/*option*\/)\n{\n\n\n AliRunLoader *inRL, *outRL;\/\/in and out Run Loaders\n AliLoader *ingime, *outgime;\/\/ in and out ITSLoaders\n\n outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());\n outgime = outRL->GetLoader(\"STARTLoader\");\n\n#ifdef DEBUG\n cout<<\"AliSTARTDigitizer::>SDigits2Digits start...\\n\";\n#endif\n \/\/\n \/\/ From hits to digits\n \/\/\n Int_t hit, nhits;\n Int_t CountEr[13],CountEl[13];\t\t\t\t\t\t\t\/\/!!!\n Int_t volume,pmt,tr,tl,sumRight;\n Float_t timediff,timeav;\n Float_t besttimeright,besttimeleft,meanTime;\n Int_t bestRightADC,bestLeftADC;\n Float_t besttimeleftGaus, besttimerightGaus;\n Float_t timeright[13]={13*0};\n Float_t timeleft[13]={13*0};\n Float_t channelWidth=2.5; \/\/ps\n Int_t channelWidthADC=1; \/\/ps\n \/\/ Int_t thresholdAmpl=10;\n\n ftimeRightTDC = new TArrayI(12); \n ftimeLeftTDC = new TArrayI(12); \n fRightADC = new TArrayI(12); \n fLeftADC = new TArrayI(12); \n \n inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(0));\n inRL->LoadgAlice();\n \n \/\/ fHits = new TClonesArray (\"AliSTARThit\", 1000);\n fPhotons = new TClonesArray (\"AliSTARThitPhoton\", 10000);\t\t\t\/\/!!!\n AliSTART *START = (AliSTART*) gAlice->GetDetector(\"START\");\n AliSTARThit *startHit;\n \/\/use if Cherenkov photons\n \/\/ AliSTARThitPhoton *startHitPhoton;\t\t\t\t\t\t\/\/!!!\n TBranch *brHits=0;\n TBranch *brHitPhoton=0;\n fdigits= new AliSTARTdigit();\n\n Int_t nFiles=fManager->GetNinputs();\n for (Int_t inputFile=0; inputFile<nFiles; inputFile++) {\n\n besttimeright=9999.;\n besttimeleft=9999.;\n Int_t timeDiff=0;\n Int_t timeAv=0;\n sumRight=0;\n for (Int_t i0=0; i0<13; i0++)\n {\n\ttimeright[i0]=0; timeleft[i0]=0;\n\tCountEr[i0]=0; CountEl[i0]=0;\n }\n\n inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));\n ingime = inRL->GetLoader(\"STARTLoader\");\n ingime->LoadHits(\"READ\");\/\/probably it is necessary to load them before\n ingime->LoadDigits(\"UPDATE\");\/\/probably it is necessary to load them before\n \/\/use if Cherenkov photons\n \/\/ TClonesArray *STARThitsPhotons = START->Photons ();\n TClonesArray *fHits = START->Hits ();\n \/\/ cout<<\" Load \"<<AliSTARTLoader::LoadDigits()<<endl;\n\n TTree *th = ingime->TreeH();\n brHits = th->GetBranch(\"START\");\n brHitPhoton = th->GetBranch(\"STARThitPhoton\");\n if (brHits) {\n START->SetHitsAddressBranch(brHits,brHitPhoton);\n }else{\n cerr<<\"EXEC Branch START hit not found\"<<endl;\n exit(111);\n } \n Int_t ntracks = (Int_t) th->GetEntries();\n cout<<\" ntracks \"<<ntracks<<endl;\n if (ntracks<=0) return;\n \/\/ Start loop on tracks in the photon hits containers \n \/\/ for amplitude\n \/*\n if(brHitPhoton) {\n cout<<\"brHitPhoton \"<<endl; \n for (Int_t track=0; track<ntracks;track++) {\n\tbrHitPhoton -> GetEntry(track);;\n\tnhits = STARThitsPhotons->GetEntriesFast();\n\tfor (hit=0;hit<nhits;hit++) {\n\t startHitPhoton = (AliSTARThitPhoton*) \n\t STARThitsPhotons ->UncheckedAt(hit);\n\t pmt=startHitPhoton->fPmt;\n\t volume = startHitPhoton->fArray;\n\t if(RegisterPhotoE(startHitPhoton)) \n\t {\n\t if (volume == 1) CountEr[pmt]++;\n\t if (volume == 2) CountEl[pmt]++;\n\t }\n\t} \/\/hit photons\n } \/\/track photons\n } \/\/ was photons\n *\/\n \/\/ Start loop on tracks in the hits containers\n for (Int_t track=0; track<ntracks;track++) {\n brHits->GetEntry(track);\n nhits = fHits->GetEntriesFast();\n \/\/ cout<<\" brHits hits \"<<nhits<<endl;\n for (hit=0;hit<nhits;hit++) {\n\tstartHit = (AliSTARThit*) fHits->UncheckedAt(hit);\n\tpmt=startHit->Pmt();\n\tvolume = startHit->Volume();\n\tif(volume==1){\n\t timeright[pmt] = startHit->Time();\n\t if(timeright[pmt]<besttimeright)\n\t \/\/&&CountEr[pmt-1]>thresholdAmpl)\n\t {\n\t besttimeright=timeright[pmt];\n\t } \/\/timeright\n\t}\/\/time for right shoulder\n\tif(volume==2){ \n\t timeleft[pmt] = startHit->Time();\n\t if(timeleft[pmt]<besttimeleft)\n\t \/\/&&CountEl[pmt-1]>thresholdAmpl) \n\t {\n\t besttimeleft=timeleft[pmt];\n\t \n\t } \/\/timeleftbest\n\t}\/\/time for left shoulder\n } \/\/hit loop\n } \/\/track loop\n \n \/\/ z position\n cout<<\" right time \"<<besttimeright<<\n \" right distance \"<<besttimeright*30<<endl;;\n cout<<\" left time \"<<besttimeleft<<\n \" left distance \"<<besttimeleft*30<<endl;;\n \n\n \/\/folding with experimental time distribution\n \n besttimeleftGaus=gRandom->Gaus(besttimeright,0.05);\n cout<<\" besttimeleftGaus \"<<besttimeleftGaus<<endl;\n bestLeftADC=Int_t (besttimeleftGaus*1000\/channelWidth);\n Float_t koef=69.7\/350.;\n besttimeright=koef*besttimeleft;\n besttimerightGaus=gRandom->Gaus(besttimeleft,0.05);\n \n bestRightADC=Int_t (besttimerightGaus*1000\/channelWidth);\n timediff=besttimerightGaus-besttimeleftGaus;\n cout<<\" timediff in ns \"<<timediff<<\" z= \"<<timediff*30<<endl;\n meanTime=(besttimerightGaus+besttimeleftGaus)\/2.;\n if ( TMath::Abs(timediff)<TMath::Abs(0.3) ) \n {\n\tFloat_t t1=1000.*besttimeleftGaus;\n\tFloat_t t2=1000.*besttimerightGaus;\n\tt1=t1\/channelWidth; \/\/time in ps to channelWidth\n\tt2=t2\/channelWidth; \/\/time in ps to channelWidth\n\ttimeav=(t1+t2)\/2.;\n\t\n\t\/\/ Time to TDC signal\n\t\/\/ 256 channels for timediff, range 1ns\n\t\n\ttimediff=512+1000*timediff\/channelWidth; \/\/ time in ps \n\t\n\ttimeAv = (Int_t)(timeav); \/\/ time channel numbres\n\ttimeDiff = (Int_t)(timediff); \/\/ time channel numbres\n\t\/\/ fill digits\n\tfdigits->SetTimeBestLeft(bestLeftADC);\n\tfdigits->SetTimeBestRight(bestRightADC);\n\tfdigits->SetMeanTime(timeAv);\n\tfdigits->SetTimeDiff(timeDiff);\n\tfor (Int_t i=0; i<12; i++)\n\t {\n\t \/\/ fill TDC\n\t timeright[i+1]=gRandom->Gaus(timeright[i+1],0.05);\n\t timeleft[i+1]=gRandom->Gaus(timeleft[i+1],0.05);\n\t tr= Int_t (timeright[i+1]*1000\/channelWidth); \n\t if(tr<200) tr=0;\n\t tl= Int_t (timeleft[i+1]*1000\/channelWidth); \n\t if(tl<1000) tl=0;\n\t \n\t ftimeRightTDC->AddAt(tr,i);\n\t ftimeLeftTDC->AddAt(tl,i);\n\t \/\/fill ADC\n\t Int_t al=( Int_t ) CountEl[i+1]\/ channelWidthADC;\n\t Int_t ar=( Int_t ) CountEr[i+1]\/ channelWidthADC;\n\t fRightADC->AddAt(ar,i);\n\t fLeftADC ->AddAt(al,i);\n\t sumRight+=CountEr[i+1];\n\t }\n\tfdigits->SetTimeRight(*ftimeRightTDC);\n\tfdigits->SetTimeLeft(*ftimeLeftTDC);\n\tfdigits->SetADCRight(*fRightADC);\n\tfdigits->SetADCLeft(*fLeftADC);\n\t\/\/ cout<<\" before sum\"<<endl;\n\tfdigits->SetSumADCRight(sumRight);\n }\n else\n {timeAv=999999; timeDiff=99999;}\n\n\/\/ trick to find out output dir:\n\n\n\/*\n \/\/ trick to find out output dir:\n TTree *outTree = fManager->GetTreeD();\n if (!outTree) {\n cerr<<\"something wrong with output....\"<<endl;\n exit(111);\n }\n\n Char_t nameDigits[20];\n TDirectory *wd = gDirectory;\n outTree->GetDirectory()->cd();\n fdigits->Write(nameDigits);\n cout<<nameDigits<<endl;\n wd->cd();\n*\/ \n\n Char_t nameDigits[20];\n sprintf(nameDigits,\"START_D_%d\",fManager->GetOutputEventNr());\n fdigits->Write(nameDigits);\n\n \/\/ outgime->WriteDigits(\"OVERWRITE\");\n }\n}\n\n\n\/\/------------------------------------------------------------------------\nBool_t AliSTARTDigitizer::RegisterPhotoE(\/*AliSTARThitPhoton *hit*\/)\n{\n Double_t P = 0.2; \n Double_t p;\n \n p = gRandom->Rndm();\n if (p > P)\n return kFALSE;\n \n return kTRUE;\n}\n\/\/----------------------------------------------------------------------------\n<commit_msg>Protection in case of missing hit (alpha)<commit_after>\n\/**************************************************************************\n * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n#include <TTree.h> \n#include <TVector.h>\n#include <TObjArray.h>\n#include <TFile.h>\n#include <TDirectory.h>\n#include <TRandom.h>\n#include <TArrayI.h>\n#include <TH1.h>\n#include <TError.h>\n\n\n#include \"AliSTARTDigitizer.h\"\n#include \"AliSTART.h\"\n#include \"AliSTARThit.h\"\n#include \"AliSTARThitPhoton.h\"\n#include \"AliSTARTdigit.h\"\n#include \"AliRunDigitizer.h\"\n#include \"AliHeader.h\"\n#include \"AliGenEventHeader.h\"\n#include \"AliRun.h\"\n#include \"AliPDG.h\"\n#include \"AliLoader.h\"\n#include \"AliRunLoader.h\"\n#include \"AliSTARTLoader.h\"\n\n#include <stdlib.h>\n#include <Riostream.h>\n#include <Riostream.h>\n\nClassImp(AliSTARTDigitizer)\n\n\/\/___________________________________________\n AliSTARTDigitizer::AliSTARTDigitizer() :AliDigitizer()\n{\n\/\/ Default ctor - don't use it\n ;\n}\n\n\/\/___________________________________________\nAliSTARTDigitizer::AliSTARTDigitizer(AliRunDigitizer* manager) \n :AliDigitizer(manager) \n{\n\tcout<<\"AliSTARTDigitizer::AliSTARTDigitizer\"<<endl;\n\/\/ ctor which should be used\n\/\/ fDebug =0;\n \/\/ if (GetDebug()>2)\n \/\/ cerr<<\"AliSTARTDigitizer::AliSTARTDigitizer\"\n \/\/ <<\"(AliRunDigitizer* manager) was processed\"<<endl;\n\n}\n\n\/\/------------------------------------------------------------------------\nAliSTARTDigitizer::~AliSTARTDigitizer()\n{\n\/\/ Destructor\n\n\n}\n\n \/\/------------------------------------------------------------------------\nBool_t AliSTARTDigitizer::Init()\n{\n\/\/ Initialization\n cout<<\"AliSTARTDigitizer::Init\"<<endl;\n return kTRUE;\n}\n \n\n\/\/---------------------------------------------------------------------\n\nvoid AliSTARTDigitizer::Exec(Option_t* \/*option*\/)\n{\n\n\n AliRunLoader *inRL, *outRL;\/\/in and out Run Loaders\n AliLoader *ingime, *outgime;\/\/ in and out ITSLoaders\n\n outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());\n outgime = outRL->GetLoader(\"STARTLoader\");\n\n#ifdef DEBUG\n cout<<\"AliSTARTDigitizer::>SDigits2Digits start...\\n\";\n#endif\n \/\/\n \/\/ From hits to digits\n \/\/\n Int_t hit, nhits;\n Int_t CountEr[13],CountEl[13];\t\t\t\t\t\t\t\/\/!!!\n Int_t volume,pmt,tr,tl,sumRight;\n Float_t timediff,timeav;\n Float_t besttimeright,besttimeleft,meanTime;\n Int_t bestRightADC,bestLeftADC;\n Float_t besttimeleftGaus, besttimerightGaus;\n Float_t timeright[13]={13*0};\n Float_t timeleft[13]={13*0};\n Float_t channelWidth=2.5; \/\/ps\n Int_t channelWidthADC=1; \/\/ps\n \/\/ Int_t thresholdAmpl=10;\n\n ftimeRightTDC = new TArrayI(12); \n ftimeLeftTDC = new TArrayI(12); \n fRightADC = new TArrayI(12); \n fLeftADC = new TArrayI(12); \n \n inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(0));\n inRL->LoadgAlice();\n \n \/\/ fHits = new TClonesArray (\"AliSTARThit\", 1000);\n fPhotons = new TClonesArray (\"AliSTARThitPhoton\", 10000);\t\t\t\/\/!!!\n AliSTART *START = (AliSTART*) gAlice->GetDetector(\"START\");\n AliSTARThit *startHit;\n \/\/use if Cherenkov photons\n \/\/ AliSTARThitPhoton *startHitPhoton;\t\t\t\t\t\t\/\/!!!\n TBranch *brHits=0;\n TBranch *brHitPhoton=0;\n fdigits= new AliSTARTdigit();\n\n Int_t nFiles=fManager->GetNinputs();\n for (Int_t inputFile=0; inputFile<nFiles; inputFile++) {\n\n besttimeright=9999.;\n besttimeleft=9999.;\n Int_t timeDiff=0;\n Int_t timeAv=0;\n sumRight=0;\n for (Int_t i0=0; i0<13; i0++)\n {\n\ttimeright[i0]=0; timeleft[i0]=0;\n\tCountEr[i0]=0; CountEl[i0]=0;\n }\n\n inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));\n ingime = inRL->GetLoader(\"STARTLoader\");\n ingime->LoadHits(\"READ\");\/\/probably it is necessary to load them before\n ingime->LoadDigits(\"UPDATE\");\/\/probably it is necessary to load them before\n \/\/use if Cherenkov photons\n \/\/ TClonesArray *STARThitsPhotons = START->Photons ();\n TClonesArray *fHits = START->Hits ();\n \/\/ cout<<\" Load \"<<AliSTARTLoader::LoadDigits()<<endl;\n\n TTree *th = ingime->TreeH();\n brHits = th->GetBranch(\"START\");\n brHitPhoton = th->GetBranch(\"STARThitPhoton\");\n if (brHits) {\n START->SetHitsAddressBranch(brHits,brHitPhoton);\n }else{\n cerr<<\"EXEC Branch START hit not found\"<<endl;\n exit(111);\n } \n Int_t ntracks = (Int_t) th->GetEntries();\n cout<<\" ntracks \"<<ntracks<<endl;\n if (ntracks<=0) return;\n \/\/ Start loop on tracks in the photon hits containers \n \/\/ for amplitude\n \/*\n if(brHitPhoton) {\n cout<<\"brHitPhoton \"<<endl; \n for (Int_t track=0; track<ntracks;track++) {\n\tbrHitPhoton -> GetEntry(track);;\n\tnhits = STARThitsPhotons->GetEntriesFast();\n\tfor (hit=0;hit<nhits;hit++) {\n\t startHitPhoton = (AliSTARThitPhoton*) \n\t STARThitsPhotons ->UncheckedAt(hit);\n\t pmt=startHitPhoton->fPmt;\n\t volume = startHitPhoton->fArray;\n\t if(RegisterPhotoE(startHitPhoton)) \n\t {\n\t if (volume == 1) CountEr[pmt]++;\n\t if (volume == 2) CountEl[pmt]++;\n\t }\n\t} \/\/hit photons\n } \/\/track photons\n } \/\/ was photons\n *\/\n \/\/ Start loop on tracks in the hits containers\n for (Int_t track=0; track<ntracks;track++) {\n brHits->GetEntry(track);\n nhits = fHits->GetEntriesFast();\n \/\/ cout<<\" brHits hits \"<<nhits<<endl;\n for (hit=0;hit<nhits;hit++) {\n\tstartHit = (AliSTARThit*) fHits->UncheckedAt(hit);\n\tif (!startHit) {\n\t ::Error(\"Exec\",\"The unchecked hit doesn't exist\");\n\t break;\n\t}\n\tpmt=startHit->Pmt();\n\tvolume = startHit->Volume();\n\tif(volume==1){\n\t timeright[pmt] = startHit->Time();\n\t if(timeright[pmt]<besttimeright)\n\t \/\/&&CountEr[pmt-1]>thresholdAmpl)\n\t {\n\t besttimeright=timeright[pmt];\n\t } \/\/timeright\n\t}\/\/time for right shoulder\n\tif(volume==2){ \n\t timeleft[pmt] = startHit->Time();\n\t if(timeleft[pmt]<besttimeleft)\n\t \/\/&&CountEl[pmt-1]>thresholdAmpl) \n\t {\n\t besttimeleft=timeleft[pmt];\n\t \n\t } \/\/timeleftbest\n\t}\/\/time for left shoulder\n } \/\/hit loop\n } \/\/track loop\n \n \/\/ z position\n cout<<\" right time \"<<besttimeright<<\n \" right distance \"<<besttimeright*30<<endl;;\n cout<<\" left time \"<<besttimeleft<<\n \" left distance \"<<besttimeleft*30<<endl;;\n \n\n \/\/folding with experimental time distribution\n \n besttimeleftGaus=gRandom->Gaus(besttimeright,0.05);\n cout<<\" besttimeleftGaus \"<<besttimeleftGaus<<endl;\n bestLeftADC=Int_t (besttimeleftGaus*1000\/channelWidth);\n Float_t koef=69.7\/350.;\n besttimeright=koef*besttimeleft;\n besttimerightGaus=gRandom->Gaus(besttimeleft,0.05);\n \n bestRightADC=Int_t (besttimerightGaus*1000\/channelWidth);\n timediff=besttimerightGaus-besttimeleftGaus;\n cout<<\" timediff in ns \"<<timediff<<\" z= \"<<timediff*30<<endl;\n meanTime=(besttimerightGaus+besttimeleftGaus)\/2.;\n if ( TMath::Abs(timediff)<TMath::Abs(0.3) ) \n {\n\tFloat_t t1=1000.*besttimeleftGaus;\n\tFloat_t t2=1000.*besttimerightGaus;\n\tt1=t1\/channelWidth; \/\/time in ps to channelWidth\n\tt2=t2\/channelWidth; \/\/time in ps to channelWidth\n\ttimeav=(t1+t2)\/2.;\n\t\n\t\/\/ Time to TDC signal\n\t\/\/ 256 channels for timediff, range 1ns\n\t\n\ttimediff=512+1000*timediff\/channelWidth; \/\/ time in ps \n\t\n\ttimeAv = (Int_t)(timeav); \/\/ time channel numbres\n\ttimeDiff = (Int_t)(timediff); \/\/ time channel numbres\n\t\/\/ fill digits\n\tfdigits->SetTimeBestLeft(bestLeftADC);\n\tfdigits->SetTimeBestRight(bestRightADC);\n\tfdigits->SetMeanTime(timeAv);\n\tfdigits->SetTimeDiff(timeDiff);\n\tfor (Int_t i=0; i<12; i++)\n\t {\n\t \/\/ fill TDC\n\t timeright[i+1]=gRandom->Gaus(timeright[i+1],0.05);\n\t timeleft[i+1]=gRandom->Gaus(timeleft[i+1],0.05);\n\t tr= Int_t (timeright[i+1]*1000\/channelWidth); \n\t if(tr<200) tr=0;\n\t tl= Int_t (timeleft[i+1]*1000\/channelWidth); \n\t if(tl<1000) tl=0;\n\t \n\t ftimeRightTDC->AddAt(tr,i);\n\t ftimeLeftTDC->AddAt(tl,i);\n\t \/\/fill ADC\n\t Int_t al=( Int_t ) CountEl[i+1]\/ channelWidthADC;\n\t Int_t ar=( Int_t ) CountEr[i+1]\/ channelWidthADC;\n\t fRightADC->AddAt(ar,i);\n\t fLeftADC ->AddAt(al,i);\n\t sumRight+=CountEr[i+1];\n\t }\n\tfdigits->SetTimeRight(*ftimeRightTDC);\n\tfdigits->SetTimeLeft(*ftimeLeftTDC);\n\tfdigits->SetADCRight(*fRightADC);\n\tfdigits->SetADCLeft(*fLeftADC);\n\t\/\/ cout<<\" before sum\"<<endl;\n\tfdigits->SetSumADCRight(sumRight);\n }\n else\n {timeAv=999999; timeDiff=99999;}\n\n\/\/ trick to find out output dir:\n\n\n\/*\n \/\/ trick to find out output dir:\n TTree *outTree = fManager->GetTreeD();\n if (!outTree) {\n cerr<<\"something wrong with output....\"<<endl;\n exit(111);\n }\n\n Char_t nameDigits[20];\n TDirectory *wd = gDirectory;\n outTree->GetDirectory()->cd();\n fdigits->Write(nameDigits);\n cout<<nameDigits<<endl;\n wd->cd();\n*\/ \n\n Char_t nameDigits[20];\n sprintf(nameDigits,\"START_D_%d\",fManager->GetOutputEventNr());\n fdigits->Write(nameDigits);\n\n \/\/ outgime->WriteDigits(\"OVERWRITE\");\n }\n}\n\n\n\/\/------------------------------------------------------------------------\nBool_t AliSTARTDigitizer::RegisterPhotoE(\/*AliSTARThitPhoton *hit*\/)\n{\n Double_t P = 0.2; \n Double_t p;\n \n p = gRandom->Rndm();\n if (p > P)\n return kFALSE;\n \n return kTRUE;\n}\n\/\/----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <GL\/glew.h>\n#include \"BMPResource.h\"\n#include \"Debug.h\"\n\nnamespace sark{\n\n\tBMPResource::BMPResource()\n\t\t: mWidth(0), mHeight(0), mPixels(NULL)\n\t{}\n\tBMPResource::BMPResource(const BMPResource& bmp)\n\t\t: mWidth(bmp.mWidth), mHeight(bmp.mHeight)\n\t{\n\t\tinteger size = bmp.mWidth * bmp.mHeight * 3;\n\t\tmPixels = new uint8[size];\n\t\tmemcpy(mPixels, bmp.mPixels, size);\n\t}\n\n\tBMPResource::~BMPResource(){\n\t\tif (mPixels != NULL){\n\t\t\tdelete[] mPixels;\n\t\t}\n\t}\n\n\tconst integer BMPResource::GetWidth() const{\n\t\treturn mWidth;\n\t}\n\n\tconst integer BMPResource::GetHeight() const{\n\t\treturn mHeight;\n\t}\n\n\tconst integer BMPResource::GetDepth() const{\n\t\treturn 0;\n\t}\n\n\tTexture::Format BMPResource::GetPixelFormat() const{\n\t\treturn Texture::Format::RGB;\n\t}\n\n\tTexture::PixelType BMPResource::GetPixelType() const{\n\t\treturn Texture::PixelType::UNSIGNED_BYTE;\n\t}\n\n\tconst void* BMPResource::GetPixels() const{\n\t\treturn mPixels;\n\t}\n\n\tBMPResource* BMPResource::LoadImp(const std::string& name){\n\t\tBITMAPFILEHEADER bmpFileHead;\n\t\tBITMAPINFOHEADER bmpInfoHead;\n\t\tmemset(&bmpFileHead, 0, sizeof(BITMAPFILEHEADER));\n\t\tmemset(&bmpInfoHead, 0, sizeof(BITMAPINFOHEADER));\n\n\t\tstd::ifstream stream;\n\t\tstream.open(name, std::ios::binary | std::ios::beg);\n\t\tif (!stream.is_open()){\n\t\t\tLogWarn(name + \" would not open\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tstream.read((char*)&bmpFileHead, sizeof(BITMAPFILEHEADER));\n\t\tif (((char*)&bmpFileHead)[0] != 'B' || ((char*)&bmpFileHead)[1] != 'M'){\n\t\t\tLogWarn(name + \" has invalid bitmap magic-code\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tstream.read((char*)&bmpInfoHead, sizeof(BITMAPINFOHEADER));\n\t\tif (bmpInfoHead.biSize != 40){\n\t\t\tLogWarn(\"it only support BITMAPINFOHEADER format bitmap\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (bmpInfoHead.biBitCount != 24 && bmpInfoHead.biBitCount != 32){\n\t\t\tLogWarn(name + \" has unsupported bit-count\")\n\t\t\t\treturn NULL;\n\t\t}\n\n\t\tBMPResource* bmp = new BMPResource();\n\t\tbmp->mWidth = bmpInfoHead.biWidth;\n\t\tbmp->mHeight = bmpInfoHead.biHeight;\n\t\tbmp->mPixels = new uint8[bmp->mWidth * bmp->mHeight * 3];\n\n\t\tstream.seekg(bmpFileHead.bfOffBits, std::ios::beg);\n\t\tif (bmpInfoHead.biBitCount == 24){\n\t\t\t\/\/ 24bit bmp has dummy pixels in each rows\n\t\t\tinteger dumbyte = ((bmp->mWidth) % 4);\n\t\t\tdumbyte = (dumbyte == 0 ? 0 : (4 - dumbyte) * 3);\n\n\t\t\tint64 i, k;\n\t\t\tfor (i = 0; i < bmp->mHeight; i++){\n\t\t\t\tfor (k = 0; k < bmp->mWidth; k++){\n\t\t\t\t\t\/\/ read bgr order\n\t\t\t\t\tint64 pix_idx = (bmp->mHeight - i - 1)*bmp->mWidth * 3 + k * 3;\n\t\t\t\t\tstream.read((char*)&bmp->mPixels[pix_idx], 3);\n\n\t\t\t\t\tuint8 t = bmp->mPixels[pix_idx];\n\t\t\t\t\tbmp->mPixels[pix_idx] = bmp->mPixels[pix_idx + 2];\n\t\t\t\t\tbmp->mPixels[pix_idx + 2] = t;\n\t\t\t\t}\n\t\t\t\tstream.seekg(dumbyte, std::ios::cur);\n\t\t\t}\n\t\t}\n\t\telse if (bmpInfoHead.biBitCount == 32){\n\t\t\tuint8 rgba[4];\n\t\t\tint64 i, k;\n\t\t\tfor (i = 0; i < bmp->mHeight; i++){\n\t\t\t\tfor (k = 0; k < bmp->mWidth; k++){\n\t\t\t\t\t\/\/ read rgba order\n\t\t\t\t\tstream.read((char*)rgba, 4);\n\n\t\t\t\t\tint64 pix_idx = (bmp->mHeight - i - 1)*bmp->mWidth * 3 + k * 3;\n\t\t\t\t\tbmp->mPixels[pix_idx] = rgba[0];\n\t\t\t\t\tbmp->mPixels[pix_idx+1] = rgba[1];\n\t\t\t\t\tbmp->mPixels[pix_idx+2] = rgba[2];\n\t\t\t\t\t\/\/ alpha value is discarded\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn bmp;\n\t}\n\n}<commit_msg>minor bug. ';' is missing..<commit_after>#include <fstream>\n#include <GL\/glew.h>\n#include \"BMPResource.h\"\n#include \"Debug.h\"\n\nnamespace sark{\n\n\tBMPResource::BMPResource()\n\t\t: mWidth(0), mHeight(0), mPixels(NULL)\n\t{}\n\tBMPResource::BMPResource(const BMPResource& bmp)\n\t\t: mWidth(bmp.mWidth), mHeight(bmp.mHeight)\n\t{\n\t\tinteger size = bmp.mWidth * bmp.mHeight * 3;\n\t\tmPixels = new uint8[size];\n\t\tmemcpy(mPixels, bmp.mPixels, size);\n\t}\n\n\tBMPResource::~BMPResource(){\n\t\tif (mPixels != NULL){\n\t\t\tdelete[] mPixels;\n\t\t}\n\t}\n\n\tconst integer BMPResource::GetWidth() const{\n\t\treturn mWidth;\n\t}\n\n\tconst integer BMPResource::GetHeight() const{\n\t\treturn mHeight;\n\t}\n\n\tconst integer BMPResource::GetDepth() const{\n\t\treturn 0;\n\t}\n\n\tTexture::Format BMPResource::GetPixelFormat() const{\n\t\treturn Texture::Format::RGB;\n\t}\n\n\tTexture::PixelType BMPResource::GetPixelType() const{\n\t\treturn Texture::PixelType::UNSIGNED_BYTE;\n\t}\n\n\tconst void* BMPResource::GetPixels() const{\n\t\treturn mPixels;\n\t}\n\n\tBMPResource* BMPResource::LoadImp(const std::string& name){\n\t\tBITMAPFILEHEADER bmpFileHead;\n\t\tBITMAPINFOHEADER bmpInfoHead;\n\t\tmemset(&bmpFileHead, 0, sizeof(BITMAPFILEHEADER));\n\t\tmemset(&bmpInfoHead, 0, sizeof(BITMAPINFOHEADER));\n\n\t\tstd::ifstream stream;\n\t\tstream.open(name, std::ios::binary | std::ios::beg);\n\t\tif (!stream.is_open()){\n\t\t\tLogWarn(name + \" would not open\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tstream.read((char*)&bmpFileHead, sizeof(BITMAPFILEHEADER));\n\t\tif (((char*)&bmpFileHead)[0] != 'B' || ((char*)&bmpFileHead)[1] != 'M'){\n\t\t\tLogWarn(name + \" has invalid bitmap magic-code\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tstream.read((char*)&bmpInfoHead, sizeof(BITMAPINFOHEADER));\n\t\tif (bmpInfoHead.biSize != 40){\n\t\t\tLogWarn(\"it only support BITMAPINFOHEADER format bitmap\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (bmpInfoHead.biBitCount != 24 && bmpInfoHead.biBitCount != 32){\n\t\t\tLogWarn(name + \" has unsupported bit-count\");\n\t\t\t\treturn NULL;\n\t\t}\n\n\t\tBMPResource* bmp = new BMPResource();\n\t\tbmp->mWidth = bmpInfoHead.biWidth;\n\t\tbmp->mHeight = bmpInfoHead.biHeight;\n\t\tbmp->mPixels = new uint8[bmp->mWidth * bmp->mHeight * 3];\n\n\t\tstream.seekg(bmpFileHead.bfOffBits, std::ios::beg);\n\t\tif (bmpInfoHead.biBitCount == 24){\n\t\t\t\/\/ 24bit bmp has dummy pixels in each rows\n\t\t\tinteger dumbyte = ((bmp->mWidth) % 4);\n\t\t\tdumbyte = (dumbyte == 0 ? 0 : (4 - dumbyte) * 3);\n\n\t\t\tint64 i, k;\n\t\t\tfor (i = 0; i < bmp->mHeight; i++){\n\t\t\t\tfor (k = 0; k < bmp->mWidth; k++){\n\t\t\t\t\t\/\/ read bgr order\n\t\t\t\t\tint64 pix_idx = (bmp->mHeight - i - 1)*bmp->mWidth * 3 + k * 3;\n\t\t\t\t\tstream.read((char*)&bmp->mPixels[pix_idx], 3);\n\n\t\t\t\t\tuint8 t = bmp->mPixels[pix_idx];\n\t\t\t\t\tbmp->mPixels[pix_idx] = bmp->mPixels[pix_idx + 2];\n\t\t\t\t\tbmp->mPixels[pix_idx + 2] = t;\n\t\t\t\t}\n\t\t\t\tstream.seekg(dumbyte, std::ios::cur);\n\t\t\t}\n\t\t}\n\t\telse if (bmpInfoHead.biBitCount == 32){\n\t\t\tuint8 rgba[4];\n\t\t\tint64 i, k;\n\t\t\tfor (i = 0; i < bmp->mHeight; i++){\n\t\t\t\tfor (k = 0; k < bmp->mWidth; k++){\n\t\t\t\t\t\/\/ read rgba order\n\t\t\t\t\tstream.read((char*)rgba, 4);\n\n\t\t\t\t\tint64 pix_idx = (bmp->mHeight - i - 1)*bmp->mWidth * 3 + k * 3;\n\t\t\t\t\tbmp->mPixels[pix_idx] = rgba[0];\n\t\t\t\t\tbmp->mPixels[pix_idx+1] = rgba[1];\n\t\t\t\t\tbmp->mPixels[pix_idx+2] = rgba[2];\n\t\t\t\t\t\/\/ alpha value is discarded\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn bmp;\n\t}\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# pragma once\n# include \"Common.hpp\"\n# include \"StringView.hpp\"\n\n# if SIV3D_PLATFORM(WINDOWS)\n\n# include <Siv3D\/Windows\/Windows.hpp>\n\nnamespace s3d\n{\n\tusing LibraryHandle = HMODULE;\n\n\tnamespace DLL\n\t{\n\t\t[[nodiscard]]\n\t\tLibraryHandle LoadSystemLibraryNoThrow(const wchar_t* library);\n\n\t\t[[nodiscard]]\n\t\tLibraryHandle LoadSystemLibrary(const wchar_t* library);\n\n\t\t[[nodiscard]]\n\t\tLibraryHandle Load(StringView path);\n\n\t\tvoid Unload(LibraryHandle& library);\n\n\t\tclass GetFunctionNoThrow\n\t\t{\n\t\tpublic:\n\n\t\t\tSIV3D_NODISCARD_CXX20\n\t\t\tGetFunctionNoThrow(LibraryHandle _module, const char* name);\n\n\t\t\ttemplate <class Type>\n\t\t\toperator Type() const noexcept\n\t\t\t{\n\t\t\t\treturn static_cast<Type>(p);\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tconst void* p;\n\t\t};\n\n\t\tclass GetFunction\n\t\t{\n\t\tpublic:\n\n\t\t\tSIV3D_NODISCARD_CXX20\n\t\t\tGetFunction(LibraryHandle _module, const char* name);\n\n\t\t\ttemplate <class Type>\n\t\t\toperator Type() const noexcept\n\t\t\t{\n\t\t\t\treturn static_cast<Type>(p);\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tconst void* p;\n\t\t};\n\t}\n}\n\n# endif\n\n# if SIV3D_PLATFORM(MACOS) || SIV3D_PLATFORM(LINUX)\n\n# include <dlfcn.h>\n\nnamespace s3d\n{\n\tusing LibraryHandle = void*;\n\n\tnamespace DLL\n\t{\n\t\t[[nodiscard]]\n\t\tLibraryHandle Load(StringView path);\n\t\n\t\tvoid Unload(LibraryHandle& library);\n\n\t\tclass GetFunctionNoThrow\n\t\t{\n\t\tpublic:\n\n\t\t\tSIV3D_NODISCARD_CXX20\n\t\t\tGetFunctionNoThrow(LibraryHandle _module, const char* name);\n\n\t\t\ttemplate <class Type>\n\t\t\toperator Type() const noexcept\n\t\t\t{\n\t\t\t\treturn reinterpret_cast<Type>(p);\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tvoid* p;\n\t\t};\n\n\t\tclass GetFunction\n\t\t{\n\t\tpublic:\n\n\t\t\tSIV3D_NODISCARD_CXX20\n\t\t\tGetFunction(LibraryHandle _module, const char* name);\n\n\t\t\ttemplate <class Type>\n\t\t\toperator Type() const noexcept\n\t\t\t{\n\t\t\t\treturn reinterpret_cast<Type>(p);\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tvoid* p;\n\t\t};\n\t}\n}\n\n# endif\n<commit_msg>[共通] SivDLL Web版の処理追加<commit_after>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# pragma once\n# include \"Common.hpp\"\n# include \"StringView.hpp\"\n\n# if SIV3D_PLATFORM(WINDOWS)\n\n# include <Siv3D\/Windows\/Windows.hpp>\n\nnamespace s3d\n{\n\tusing LibraryHandle = HMODULE;\n\n\tnamespace DLL\n\t{\n\t\t[[nodiscard]]\n\t\tLibraryHandle LoadSystemLibraryNoThrow(const wchar_t* library);\n\n\t\t[[nodiscard]]\n\t\tLibraryHandle LoadSystemLibrary(const wchar_t* library);\n\n\t\t[[nodiscard]]\n\t\tLibraryHandle Load(StringView path);\n\n\t\tvoid Unload(LibraryHandle& library);\n\n\t\tclass GetFunctionNoThrow\n\t\t{\n\t\tpublic:\n\n\t\t\tSIV3D_NODISCARD_CXX20\n\t\t\tGetFunctionNoThrow(LibraryHandle _module, const char* name);\n\n\t\t\ttemplate <class Type>\n\t\t\toperator Type() const noexcept\n\t\t\t{\n\t\t\t\treturn static_cast<Type>(p);\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tconst void* p;\n\t\t};\n\n\t\tclass GetFunction\n\t\t{\n\t\tpublic:\n\n\t\t\tSIV3D_NODISCARD_CXX20\n\t\t\tGetFunction(LibraryHandle _module, const char* name);\n\n\t\t\ttemplate <class Type>\n\t\t\toperator Type() const noexcept\n\t\t\t{\n\t\t\t\treturn static_cast<Type>(p);\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tconst void* p;\n\t\t};\n\t}\n}\n\n# endif\n\n# if SIV3D_PLATFORM(MACOS) || SIV3D_PLATFORM(LINUX) || SIV3D_PLATFORM(WEB)\n\n# include <dlfcn.h>\n\nnamespace s3d\n{\n\tusing LibraryHandle = void*;\n\n\tnamespace DLL\n\t{\n\t\t[[nodiscard]]\n\t\tLibraryHandle Load(StringView path);\n\t\n\t\tvoid Unload(LibraryHandle& library);\n\n\t\tclass GetFunctionNoThrow\n\t\t{\n\t\tpublic:\n\n\t\t\tSIV3D_NODISCARD_CXX20\n\t\t\tGetFunctionNoThrow(LibraryHandle _module, const char* name);\n\n\t\t\ttemplate <class Type>\n\t\t\toperator Type() const noexcept\n\t\t\t{\n\t\t\t\treturn reinterpret_cast<Type>(p);\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tvoid* p;\n\t\t};\n\n\t\tclass GetFunction\n\t\t{\n\t\tpublic:\n\n\t\t\tSIV3D_NODISCARD_CXX20\n\t\t\tGetFunction(LibraryHandle _module, const char* name);\n\n\t\t\ttemplate <class Type>\n\t\t\toperator Type() const noexcept\n\t\t\t{\n\t\t\t\treturn reinterpret_cast<Type>(p);\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tvoid* p;\n\t\t};\n\t}\n}\n\n# endif\n<|endoftext|>"} {"text":"<commit_before>#include <thread>\n#include \"TcpClient.h\"\n#include \"platform\/CCFileUtils.h\"\n#include \"base\/CCDirector.h\"\n#include \"base\/CCScheduler.h\"\n#include \"2d\/CCLabel.h\"\n#include \"..\/..\/PacketType.h\"\n#include \"SingleGameScene.h\"\n#include \"ObjectLayer.h\"\n#include \"NetworkScene.h\"\n#include \"LoadingBGLayer.h\"\n#include \"RoomScene.h\"\n#include \"MultiGameScene.h\"\n\n#ifdef _WIN32\n#pragma comment(lib,\"ws2_32.lib\")\n#define sleep(x) Sleep(x)\n#endif\n\nstatic TcpClient* s_TcpClient = nullptr;\n\nTcpClient::TcpClient() : mRecvBuffer(BUF_SIZE), mSock(NULL), mLoginId(-1)\n{\n\t\/\/\/ \n\tauto t = std::thread(CC_CALLBACK_0(TcpClient::networkThread, this));\n\tt.detach();\n}\n\nTcpClient::~TcpClient()\n{\n\tif(mSock == NULL)\n\t\treturn;\n\n#ifndef _WIN32\n\tclose(mSock);\n#else\n\tclosesocket(mSock);\n\tWSACleanup();\n#endif\n}\n\nTcpClient* TcpClient::getInstance()\n{\n\tif (nullptr == s_TcpClient)\n\t{\n\t\ts_TcpClient = new TcpClient();\n\t}\n\treturn s_TcpClient;\n}\n\nvoid TcpClient::destroyInstance()\n{\n\tCC_SAFE_DELETE(s_TcpClient);\n}\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n\t , Լ\n*\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool TcpClient::connect()\n{\n\tif (mSock != NULL)\n\t{\n\t\tTcpClient::getInstance()->disconnect();\n\t}\n\n#ifdef _WIN32\n\tWSADATA wsa;\n\tif (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)\n\t\treturn false;\n#endif\n\n\tmSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tif (mSock == INVALID_SOCKET)\n\t\treturn false;\n\n\tstd::string ipaddr = cocos2d::UserDefault::getInstance()->getStringForKey(\"ipaddr\", std::string(\"localhost\"));\n\tint port = cocos2d::UserDefault::getInstance()->getIntegerForKey(\"port\", 9001);\n\n\tstruct hostent* host;\n\tstruct sockaddr_in hostAddr;\n\n\tif ((host = gethostbyname(ipaddr.c_str())) == 0)\n\t\treturn false;\n\n\tmemset(&hostAddr, 0, sizeof(hostAddr));\n\thostAddr.sin_family = AF_INET;\n\thostAddr.sin_addr.s_addr = inet_addr(\"10.73.38.181\");\n\thostAddr.sin_port = htons(port);\n\n\tif (SOCKET_ERROR == ::connect(mSock, (struct sockaddr*)&hostAddr, sizeof(hostAddr)))\n\t{\n\t\tCCLOG(\"CONNECT FAILED\");\n\t\treturn false;\n\t}\n\n\t\/\/\/ nagle ˰ \n\tint opt = 1;\n\tsetsockopt(mSock, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(int));\n\n\treturn true;\n}\n\nvoid TcpClient::disconnect()\n{\n\tif (mSock == NULL)\n\t\treturn;\n\n#ifndef _WIN32\n\tclose(mSock);\n#else\n\tclosesocket(mSock);\n\tWSACleanup();\n#endif\n\tmSock = NULL;\n\tmLoginId = -1;\n\n\treturn;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n\t Ŷ , ޴ Լ\n*\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool TcpClient::send(const char* data, int length)\n{\n\tint count = 0;\n\twhile (count < length) \n\t{\n\t\tint n = ::send(mSock, data + count, length, 0);\n\t\tif (n == SOCKET_ERROR)\n\t\t{\n\t\t\tCCLOG(\"SEND ERROR\");\n\t\t\treturn false;\n\t\t}\n\t\tcount += n;\n\t\tlength -= n;\n\t}\n\n\treturn true;\n}\n\nvoid TcpClient::networkThread()\n{\n\twhile ( true ) \n\t{\n\t\tchar inBuf[4096] = { 0, };\n\n\t\tint n = ::recv(mSock, inBuf, 4096, 0);\n\n\t\tif (n < 1)\n\t\t{\n\t\t\tsleep(0); \/\/\/< for cpu low-utilization\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!mRecvBuffer.Write(inBuf, n))\n\t\t{\n\t\t\t\/\/\/ á. \n\t\t\tassert(false);\n\t\t}\n\n\t\tprocessPacket();\n\t}\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n\t Ŷ ĽϿ óϴ Լ\n*\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TcpClient::processPacket()\n{\n\tauto scheduler = cocos2d::Director::getInstance()->getScheduler();\n\n\t\/\/\/ Ŷ Ľؼ ϼǴ Ŷ , ش ݹ ҷش. \n\twhile (true)\n\t{\n\t\tPacketHeader header;\n\n\t\tif (false == mRecvBuffer.Peek((char*)&header, sizeof(PacketHeader)))\n\t\t\tbreak;\n\n\t\tif (header.mSize > mRecvBuffer.GetStoredSize())\n\t\t\tbreak;\n\n\t\tswitch (header.mType)\n\t\t{\n\t\tcase PKT_SC_LOGIN:\n\t\t\t{\n\t\t\t\tLoginResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\t\n\t\t\t\tmLoginId = recvData.mPlayerId;\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"NetworkScene\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(NetworkScene::ConnectComplete, dynamic_cast<NetworkScene*>(layer)));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PKT_SC_MAKE_ROOM:\n\t\t\t{\n\t\t\t\tMakeRoomResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId == mLoginId);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"NetworkScene\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(NetworkScene::MakeRoomComplete, dynamic_cast<NetworkScene*>(layer), recvData.mRoomId));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PKT_SC_INOUT_ROOM:\n\t\t\t{\n\t\t\t\tInOutRoomResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId == mLoginId);\n\n\t\t\t\tif (recvData.mIsIn)\n\t\t\t\t{\n\t\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"NetworkScene\");\n\t\t\t\t\tif (layer == nullptr)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(NetworkScene::JoinRoomComplete, dynamic_cast<NetworkScene*>(layer), recvData.mRoomId));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ ÷̾ ó ʿ\n\/\/ \t\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"RoomScene\");\n\/\/ \t\t\t\t\tif (layer == nullptr)\n\/\/ \t\t\t\t\t\tbreak;\n\/\/\t\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(NetworkScene::MakeRoomComplete, dynamic_cast<NetworkScene*>(layer), recvData.mRoomId));\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_ALL_READY:\n\t\t{\n\t\t\t\tGameRunNotify recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"RoomScene\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(RoomScene::GameStartComplete, dynamic_cast<RoomScene*>(layer)));\n\t\t\t\treturn; \/\/callbackԼ ߰\n\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_CREATE_HERO:\n\t\t\t{\n\t\t\t\tCreateHeroResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\")->getChildByName(\"ListenerLayer\")->getChildByName(\"ObjectLayer\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tPoint pos = { recvData.mPosX, recvData.mPosY };\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(ObjectLayer::FirstDrawUnit, dynamic_cast<ObjectLayer*>(layer), recvData.mPlayerId, recvData.mUnitId, recvData.mUnitType, pos));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_RUN_COMPLETE:\n\t\t\t{\n\t\t\t\tServerRunCompleteNotify recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\")->getChildByName(\"LoadingBGLayer\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(LoadingBGLayer::SetLoadingFin, dynamic_cast<LoadingBGLayer*>(layer)));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_START_GAME:\n\t\t\t{\t\n\t\t\t\tStartGameNotify recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(MultiGameScene::StartGame, dynamic_cast<MultiGameScene*>(layer)));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_MOVE:\n\t\t\t{\n\t\t\t\tMoveBroadcastResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\t\t\t\t\t\t\t\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\")->getChildByName(\"ListenerLayer\")->getChildByName(\"ObjectLayer\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tPoint curPos = { recvData.mCurrentPosX, recvData.mCurrentPosY };\n\t\t\t\tPoint targetPos = { recvData.mTargetPosX, recvData.mTargetPosY };\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(ObjectLayer::UnitMove, dynamic_cast<ObjectLayer*>(layer), recvData.mUnitId, curPos, targetPos));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tassert(false);\n\t\t}\n\n\t}\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n\t Ŷ Ľϴ Լ\n*\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TcpClient::loginRequest()\n{\n\tif (mLoginId > 0)\n\t\treturn;\n\n\tsrand(time(NULL));\n\n\tLoginRequest sendData;\n\tsendData.mPlayerId = 1000 + rand() % 101;\n\n\tsend((const char*)&sendData, sizeof(LoginRequest));\n}\n\nvoid TcpClient::makeRoomRequest()\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tMakeRoomRequest sendData;\n\tsendData.mPlayerId = mLoginId;\n\n\tsend((const char*)&sendData, sizeof(MakeRoomRequest));\n}\n\nvoid TcpClient::joinRoomRequest()\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tInOutRoomRequest sendData;\n\tsendData.mPlayerId = mLoginId;\n\tsendData.mIsIn = true;\n\n\tsend((const char*)&sendData, sizeof(InOutRoomRequest));\n}\n\nvoid TcpClient::outRoomRequest(int roomId)\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tInOutRoomRequest sendData;\n\tsendData.mPlayerId = mLoginId;\n\tsendData.mIsIn = false;\n\tsendData.mRoomId = roomId;\n\n\tsend((const char*)&sendData, sizeof(InOutRoomRequest));\n}\n\nvoid TcpClient::startGameRequest()\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tGameReadyNotify sendData;\n\tsendData.mPlayerId = mLoginId;\n\n\tsend((const char*)&sendData, sizeof(GameReadyNotify));\n}\n\nvoid TcpClient::meReadyRequest()\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tClientRunCompleteNotify sendData;\n\tsendData.mPlayerId = mLoginId;\n\n\tsend((const char*)&sendData, sizeof(ClientRunCompleteNotify));\n}\n\nvoid TcpClient::moveRequest(Point curPos, Point targetPos)\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tMoveRequest sendData;\n\tsendData.mPlayerId = mLoginId;\n\tsendData.mCurrentPosX = curPos.x;\n\tsendData.mCurrentPosY = curPos.y;\n\tsendData.mTargetPosX = targetPos.x;\n\tsendData.mTargetPosY = targetPos.y;\n\n\tsend((const char*)&sendData, sizeof(MoveRequest));\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\/\/ void TcpClient::chatRequest(const char* chat)\n\/\/ {\n\/\/ \t if (mLoginId < 0)\n\/\/ \t\t return;\n\/\/ \n\/\/ \t ChatBroadcastRequest sendData;\n\/\/ \n\/\/ \t sendData.mPlayerId = mLoginId;\n\/\/ \t memcpy(sendData.mChat, chat, strlen(chat));\n\/\/ \n\/\/ \t send((const char*)&sendData, sizeof(ChatBroadcastRequest));\n\/\/ }\n\/\/ \n<commit_msg>[C] 패킷받기 하나추가<commit_after>#include <thread>\n#include \"TcpClient.h\"\n#include \"platform\/CCFileUtils.h\"\n#include \"base\/CCDirector.h\"\n#include \"base\/CCScheduler.h\"\n#include \"2d\/CCLabel.h\"\n#include \"..\/..\/PacketType.h\"\n#include \"SingleGameScene.h\"\n#include \"ObjectLayer.h\"\n#include \"NetworkScene.h\"\n#include \"LoadingBGLayer.h\"\n#include \"RoomScene.h\"\n#include \"MultiGameScene.h\"\n\n#ifdef _WIN32\n#pragma comment(lib,\"ws2_32.lib\")\n#define sleep(x) Sleep(x)\n#endif\n\nstatic TcpClient* s_TcpClient = nullptr;\n\nTcpClient::TcpClient() : mRecvBuffer(BUF_SIZE), mSock(NULL), mLoginId(-1)\n{\n\t\/\/\/ \n\tauto t = std::thread(CC_CALLBACK_0(TcpClient::networkThread, this));\n\tt.detach();\n}\n\nTcpClient::~TcpClient()\n{\n\tif(mSock == NULL)\n\t\treturn;\n\n#ifndef _WIN32\n\tclose(mSock);\n#else\n\tclosesocket(mSock);\n\tWSACleanup();\n#endif\n}\n\nTcpClient* TcpClient::getInstance()\n{\n\tif (nullptr == s_TcpClient)\n\t{\n\t\ts_TcpClient = new TcpClient();\n\t}\n\treturn s_TcpClient;\n}\n\nvoid TcpClient::destroyInstance()\n{\n\tCC_SAFE_DELETE(s_TcpClient);\n}\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n\t , Լ\n*\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool TcpClient::connect()\n{\n\tif (mSock != NULL)\n\t{\n\t\tTcpClient::getInstance()->disconnect();\n\t}\n\n#ifdef _WIN32\n\tWSADATA wsa;\n\tif (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)\n\t\treturn false;\n#endif\n\n\tmSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tif (mSock == INVALID_SOCKET)\n\t\treturn false;\n\n\tstd::string ipaddr = cocos2d::UserDefault::getInstance()->getStringForKey(\"ipaddr\", std::string(\"localhost\"));\n\tint port = cocos2d::UserDefault::getInstance()->getIntegerForKey(\"port\", 9001);\n\n\tstruct hostent* host;\n\tstruct sockaddr_in hostAddr;\n\n\tif ((host = gethostbyname(ipaddr.c_str())) == 0)\n\t\treturn false;\n\n\tmemset(&hostAddr, 0, sizeof(hostAddr));\n\thostAddr.sin_family = AF_INET;\n\thostAddr.sin_addr.s_addr = inet_addr(\"10.73.38.181\");\n\thostAddr.sin_port = htons(port);\n\n\tif (SOCKET_ERROR == ::connect(mSock, (struct sockaddr*)&hostAddr, sizeof(hostAddr)))\n\t{\n\t\tCCLOG(\"CONNECT FAILED\");\n\t\treturn false;\n\t}\n\n\t\/\/\/ nagle ˰ \n\tint opt = 1;\n\tsetsockopt(mSock, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(int));\n\n\treturn true;\n}\n\nvoid TcpClient::disconnect()\n{\n\tif (mSock == NULL)\n\t\treturn;\n\n#ifndef _WIN32\n\tclose(mSock);\n#else\n\tclosesocket(mSock);\n\tWSACleanup();\n#endif\n\tmSock = NULL;\n\tmLoginId = -1;\n\n\treturn;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n\t Ŷ , ޴ Լ\n*\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool TcpClient::send(const char* data, int length)\n{\n\tint count = 0;\n\twhile (count < length) \n\t{\n\t\tint n = ::send(mSock, data + count, length, 0);\n\t\tif (n == SOCKET_ERROR)\n\t\t{\n\t\t\tCCLOG(\"SEND ERROR\");\n\t\t\treturn false;\n\t\t}\n\t\tcount += n;\n\t\tlength -= n;\n\t}\n\n\treturn true;\n}\n\nvoid TcpClient::networkThread()\n{\n\twhile ( true ) \n\t{\n\t\tchar inBuf[4096] = { 0, };\n\n\t\tint n = ::recv(mSock, inBuf, 4096, 0);\n\n\t\tif (n < 1)\n\t\t{\n\t\t\tsleep(0); \/\/\/< for cpu low-utilization\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!mRecvBuffer.Write(inBuf, n))\n\t\t{\n\t\t\t\/\/\/ á. \n\t\t\tassert(false);\n\t\t}\n\n\t\tprocessPacket();\n\t}\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n\t Ŷ ĽϿ óϴ Լ\n*\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TcpClient::processPacket()\n{\n\tauto scheduler = cocos2d::Director::getInstance()->getScheduler();\n\n\t\/\/\/ Ŷ Ľؼ ϼǴ Ŷ , ش ݹ ҷش. \n\twhile (true)\n\t{\n\t\tPacketHeader header;\n\n\t\tif (false == mRecvBuffer.Peek((char*)&header, sizeof(PacketHeader)))\n\t\t\tbreak;\n\n\t\tif (header.mSize > mRecvBuffer.GetStoredSize())\n\t\t\tbreak;\n\n\t\tswitch (header.mType)\n\t\t{\n\t\tcase PKT_SC_LOGIN:\n\t\t\t{\n\t\t\t\tLoginResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\t\n\t\t\t\tmLoginId = recvData.mPlayerId;\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"NetworkScene\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(NetworkScene::ConnectComplete, dynamic_cast<NetworkScene*>(layer)));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PKT_SC_MAKE_ROOM:\n\t\t\t{\n\t\t\t\tMakeRoomResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId == mLoginId);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"NetworkScene\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(NetworkScene::MakeRoomComplete, dynamic_cast<NetworkScene*>(layer), recvData.mRoomId));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PKT_SC_INOUT_ROOM:\n\t\t\t{\n\t\t\t\tInOutRoomResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId == mLoginId);\n\n\t\t\t\tif (recvData.mIsIn)\n\t\t\t\t{\n\t\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"NetworkScene\");\n\t\t\t\t\tif (layer == nullptr)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(NetworkScene::JoinRoomComplete, dynamic_cast<NetworkScene*>(layer), recvData.mRoomId));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ ÷̾ ó ʿ\n\/\/ \t\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"RoomScene\");\n\/\/ \t\t\t\t\tif (layer == nullptr)\n\/\/ \t\t\t\t\t\tbreak;\n\/\/\t\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(NetworkScene::MakeRoomComplete, dynamic_cast<NetworkScene*>(layer), recvData.mRoomId));\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_ALL_READY:\n\t\t{\n\t\t\t\tGameRunNotify recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"RoomScene\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(RoomScene::GameStartComplete, dynamic_cast<RoomScene*>(layer)));\n\t\t\t\treturn; \/\/callbackԼ ߰\n\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_CREATE_HERO:\n\t\t\t{\n\t\t\t\tCreateHeroResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\")->getChildByName(\"ListenerLayer\")->getChildByName(\"ObjectLayer\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tPoint pos = { recvData.mPosX, recvData.mPosY };\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(ObjectLayer::FirstDrawUnit, dynamic_cast<ObjectLayer*>(layer), recvData.mPlayerId, recvData.mUnitId, recvData.mUnitType, pos));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_RUN_COMPLETE:\n\t\t\t{\n\t\t\t\tServerRunCompleteNotify recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\")->getChildByName(\"LoadingBGLayer\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(LoadingBGLayer::SetLoadingFin, dynamic_cast<LoadingBGLayer*>(layer)));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_START_GAME:\n\t\t\t{\t\n\t\t\t\tStartGameNotify recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(MultiGameScene::StartGame, dynamic_cast<MultiGameScene*>(layer)));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_MOVE:\n\t\t\t{\n\t\t\t\tMoveBroadcastResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\t\t\t\t\t\t\t\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\")->getChildByName(\"ListenerLayer\")->getChildByName(\"ObjectLayer\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tPoint curPos = { recvData.mCurrentPosX, recvData.mCurrentPosY };\n\t\t\t\tPoint targetPos = { recvData.mTargetPosX, recvData.mTargetPosY };\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(ObjectLayer::UnitMove, dynamic_cast<ObjectLayer*>(layer), recvData.mUnitId, curPos, targetPos));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PKT_SC_CRASH:\n\t\t\t{\n\t\t\t\tCrashedBroadcastResult recvData;\n\t\t\t\tbool ret = mRecvBuffer.Read((char*)&recvData, recvData.mSize);\n\t\t\t\tassert(ret && recvData.mPlayerId != -1);\n\n\t\t\t\tauto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(\"MultiGameScene\")->getChildByName(\"ListenerLayer\")->getChildByName(\"ObjectLayer\");\n\t\t\t\tif (layer == nullptr)\n\t\t\t\t\tbreak;\n\n\t\t\t\tPoint curPos = { recvData.mCurrentPosX, recvData.mCurrentPosY };\n\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(ObjectLayer::UnitCrash, dynamic_cast<ObjectLayer*>(layer), recvData.mUnitId, curPos));\n\t\t\t\tif (!recvData.mIsCrashed)\n\t\t\t\t\tscheduler->performFunctionInCocosThread(CC_CALLBACK_0(ObjectLayer::UnitCrashEnd, dynamic_cast<ObjectLayer*>(layer), recvData.mUnitId));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tassert(false);\n\t\t}\n\n\t}\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n\t Ŷ Ľϴ Լ\n*\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TcpClient::loginRequest()\n{\n\tif (mLoginId > 0)\n\t\treturn;\n\n\tsrand(time(NULL));\n\n\tLoginRequest sendData;\n\tsendData.mPlayerId = 1000 + rand() % 101;\n\n\tsend((const char*)&sendData, sizeof(LoginRequest));\n}\n\nvoid TcpClient::makeRoomRequest()\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tMakeRoomRequest sendData;\n\tsendData.mPlayerId = mLoginId;\n\n\tsend((const char*)&sendData, sizeof(MakeRoomRequest));\n}\n\nvoid TcpClient::joinRoomRequest()\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tInOutRoomRequest sendData;\n\tsendData.mPlayerId = mLoginId;\n\tsendData.mIsIn = true;\n\n\tsend((const char*)&sendData, sizeof(InOutRoomRequest));\n}\n\nvoid TcpClient::outRoomRequest(int roomId)\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tInOutRoomRequest sendData;\n\tsendData.mPlayerId = mLoginId;\n\tsendData.mIsIn = false;\n\tsendData.mRoomId = roomId;\n\n\tsend((const char*)&sendData, sizeof(InOutRoomRequest));\n}\n\nvoid TcpClient::startGameRequest()\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tGameReadyNotify sendData;\n\tsendData.mPlayerId = mLoginId;\n\n\tsend((const char*)&sendData, sizeof(GameReadyNotify));\n}\n\nvoid TcpClient::meReadyRequest()\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tClientRunCompleteNotify sendData;\n\tsendData.mPlayerId = mLoginId;\n\n\tsend((const char*)&sendData, sizeof(ClientRunCompleteNotify));\n}\n\nvoid TcpClient::moveRequest(Point curPos, Point targetPos)\n{\n\tif (mLoginId < 0)\n\t\treturn;\n\n\tMoveRequest sendData;\n\tsendData.mPlayerId = mLoginId;\n\tsendData.mCurrentPosX = curPos.x;\n\tsendData.mCurrentPosY = curPos.y;\n\tsendData.mTargetPosX = targetPos.x;\n\tsendData.mTargetPosY = targetPos.y;\n\n\tsend((const char*)&sendData, sizeof(MoveRequest));\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\/\/ void TcpClient::chatRequest(const char* chat)\n\/\/ {\n\/\/ \t if (mLoginId < 0)\n\/\/ \t\t return;\n\/\/ \n\/\/ \t ChatBroadcastRequest sendData;\n\/\/ \n\/\/ \t sendData.mPlayerId = mLoginId;\n\/\/ \t memcpy(sendData.mChat, chat, strlen(chat));\n\/\/ \n\/\/ \t send((const char*)&sendData, sizeof(ChatBroadcastRequest));\n\/\/ }\n\/\/ \n<|endoftext|>"} {"text":"<commit_before>#include \"sexpr.hpp\"\n\n#include \"..\/parse.hpp\"\n\nnamespace {\n\n template<char ... c>\n static int matches(int x) {\n static const char data[] = {c..., 0};\n\n for(const char* i = data; *i; ++i) {\n if(*i == x) return true;\n }\n\n return false;\n }\n \n}\n\nsexpr parse(std::istream& in) {\n using namespace parser;\n \n static const auto true_parser =\n token(\"true\") >> [](const char*) { return pure(true); };\n \n static const auto false_parser =\n token(\"false\") >> [](const char*) { return pure(false); };\n \n static const auto boolean_parser = true_parser | false_parser;\n\n static const auto separator_parser = \/\/ parser::debug(\"sep\") |=\n noskip(chr<std::isspace>());\n \n static const auto real_parser = \/\/ parser::debug(\"real\") |=\n value<double>();\n \n static const auto number_parser = \/\/ parser::debug(\"num\") |= \n real_parser >> [](real num) {\n const long cast = num;\n const sexpr value = num == real(cast) ? sexpr(cast) : sexpr(num);\n return pure(value); \n };\n\n\n static const auto initial_parser = chr<std::isalpha>(); \n \n static const auto rest_parser = parser::chr<std::isalnum>(); \n\n static const auto symbol_parser = initial_parser >> [](char c) {\n return noskip(*rest_parser >> [c](std::deque<char>&& rest) {\n const std::string tmp = c + std::string(rest.begin(), rest.end());\n return pure(symbol(tmp));\n });\n };\n\n static const auto op_parser =\n parser::chr<matches<'+', '-', '*', '\/', '='>>() >> [](char c) {\n return pure(symbol(std::string(1, c)));\n };\n \n static const auto attr_parser = parser::chr<matches<'@'>>() >> [](char c) { \n return symbol_parser >> [c](symbol s) {\n return pure(symbol(c + std::string(s.get())));\n };\n };\n \n static const auto as_expr = parser::cast<sexpr>();\n\n static auto expr_parser = parser::any<sexpr>();\n\n static const auto lparen = \/\/ parser::debug(\"lparen\") |=\n parser::token(\"(\");\n \n static const auto rparen = \/\/ parser::debug(\"rparen\") |=\n parser::token(\")\");\n\n static const auto exprs_parser = \/\/ parser::debug(\"exprs\") |=\n parser::ref(expr_parser) % separator_parser;\n \n static const auto list_parser = \/\/ parser::debug(\"list\") |=\n lparen >>= exprs_parser >> drop(rparen) \n >> [](std::deque<sexpr>&& es) {\n return pure(make_list(es.begin(), es.end()));\n };\n \n static const auto once =\n (expr_parser\n = (boolean_parser >> as_expr)\n | (symbol_parser >> as_expr)\n | (attr_parser >> as_expr)\n | (op_parser >> as_expr)\n | number_parser\n | (list_parser >> as_expr)\n , 0); (void) once;\n\n parser::debug::stream = &std::clog;\n \n if(auto value = expr_parser(in)) {\n return value.get();\n }\n \n throw parse_error(\"parse error\");\n}\n<commit_msg>tokens<commit_after>#include \"sexpr.hpp\"\n\n#include \"..\/parse.hpp\"\n\nnamespace {\n\n template<char ... c>\n static int matches(int x) {\n static const char data[] = {c..., 0};\n\n for(const char* i = data; *i; ++i) {\n if(*i == x) return true;\n }\n\n return false;\n }\n \n}\n\nsexpr parse(std::istream& in) {\n using namespace parser;\n \n static const auto true_parser =\n token(\"true\") >> [](const char*) { return pure(true); };\n \n static const auto false_parser =\n token(\"false\") >> [](const char*) { return pure(false); };\n \n static const auto boolean_parser = true_parser | false_parser;\n\n static const auto separator_parser = \/\/ parser::debug(\"sep\") |=\n noskip(chr<std::isspace>());\n \n static const auto real_parser = \/\/ parser::debug(\"real\") |=\n value<double>();\n \n static const auto number_parser = \/\/ parser::debug(\"num\") |= \n real_parser >> [](real num) {\n const long cast = num;\n const sexpr value = num == real(cast) ? sexpr(cast) : sexpr(num);\n return pure(value); \n };\n\n\n static const auto initial_parser = chr<std::isalpha>(); \n \n static const auto rest_parser = parser::chr<std::isalnum>(); \n\n static const auto symbol_parser = initial_parser >> [](char c) {\n return noskip(*rest_parser >> [c](std::deque<char>&& rest) {\n const std::string tmp = c + std::string(rest.begin(), rest.end());\n return pure(symbol(tmp));\n });\n };\n\n static const auto op_parser =\n parser::chr<matches<'+', '-', '*', '\/', '=', '<', '>', '%' >>() >> [](char c) {\n return pure(symbol(std::string(1, c)));\n }\n | (token(\"!=\") | token(\"<=\") | token(\">=\")) >> [](const char* s) {\n return pure(symbol(s));\n };\n \n \n static const auto attr_parser = parser::chr<matches<'@'>>() >> [](char c) { \n return symbol_parser >> [c](symbol s) {\n return pure(symbol(c + std::string(s.get())));\n };\n };\n \n static const auto as_expr = parser::cast<sexpr>();\n\n static auto expr_parser = parser::any<sexpr>();\n\n static const auto lparen = \/\/ parser::debug(\"lparen\") |=\n parser::token(\"(\");\n \n static const auto rparen = \/\/ parser::debug(\"rparen\") |=\n parser::token(\")\");\n\n static const auto exprs_parser = \/\/ parser::debug(\"exprs\") |=\n parser::ref(expr_parser) % separator_parser;\n \n static const auto list_parser = \/\/ parser::debug(\"list\") |=\n lparen >>= exprs_parser >> drop(rparen) \n >> [](std::deque<sexpr>&& es) {\n return pure(make_list(es.begin(), es.end()));\n };\n \n static const auto once =\n (expr_parser\n = (boolean_parser >> as_expr)\n | (symbol_parser >> as_expr)\n | (attr_parser >> as_expr)\n | (op_parser >> as_expr)\n | number_parser\n | (list_parser >> as_expr)\n , 0); (void) once;\n\n parser::debug::stream = &std::clog;\n \n if(auto value = expr_parser(in)) {\n return value.get();\n }\n \n throw parse_error(\"parse error\");\n}\n<|endoftext|>"} {"text":"<commit_before>char copyright[] = \"Developed by Bulat Ziganshin\\n\"\n \"The code is placed in public domain\\n\";\n\n\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#define kb 1024\n#define mb (kb*kb)\ntypedef unsigned char byte;\n\nclass Smoker\n{\npublic:\n virtual const char* name() = 0;\n virtual void smoke (void *buf, size_t bufsize, double *entropy) = 0;\n virtual ~Smoker() {}\n};\n\n\n\/**********************************************************************\/\n\/* Byte smoker: calculate compression ratio with the order-0 model *\/\n\/**********************************************************************\/\n\nclass ByteSmoker : public Smoker\n{\npublic:\n virtual const char* name() {return \"ByteSmoker\";};\n virtual void smoke (void *buf, size_t bufsize, double *entropy);\n};\n\nvoid ByteSmoker::smoke (void *buf, size_t bufsize, double *entropy)\n{\n size_t count1[256] = {0};\n size_t count2[256] = {0};\n size_t count3[256] = {0};\n size_t count4[256] = {0};\n\n byte *p = (byte*) buf; int i;\n for (i=0; i<bufsize-3; i+=4)\n count1[ p[i] ]++,\n count2[ p[i+1] ]++,\n count3[ p[i+2] ]++,\n count4[ p[i+3] ]++;\n for (; i<bufsize; i++)\n count1[ p[i] ]++;\n\n double order0 = 0;\n for (int i=0; i<256; i++)\n {\n size_t count = count1[i] + count2[i] + count3[i] + count4[i];\n if (count)\n order0 += count * log(double(bufsize\/count))\/log(double(2)) \/ 8;\n }\n\n *entropy = order0 \/ bufsize;\n}\n\n\n\/**********************************************************************\/\n\/* DWord smoker *\/\n\/**********************************************************************\/\n\nuint32_t hash_function (uint32_t x)\n{\n uint64_t hash = x * uint64_t(123456791u);\n return uint32_t(hash>>32) ^ uint32_t(hash);\n}\n\nconst size_t HASHSIZE = 128*kb;\n\nclass DWordSmoker : public Smoker\n{\n size_t bits[256];\n byte table[HASHSIZE];\npublic:\n DWordSmoker();\n virtual const char* name() {return \"DWordSmoker\";};\n virtual void smoke (void *buf, size_t bufsize, double *entropy);\n virtual ~DWordSmoker() {}\n};\n\nDWordSmoker::DWordSmoker()\n{\n bits[0] = 0;\n for (int i=0; i<256; i++)\n bits[i] = bits[i\/2] + (i%2);\n}\n\nvoid DWordSmoker::smoke (void *buf, size_t bufsize, double *entropy)\n{\n const size_t STEP = 4; \/\/ Check only every n'th position\n const uint32_t FILTER = 16; \/\/ Of those checked, count only every n'th hash\n const uint32_t FILTER_MAX_HASH = (1u<<31) \/ (FILTER\/2); \/\/ Count only hashes smaller than this value\n const uint32_t FILTER_HASH_DIVIDER = FILTER_MAX_HASH \/ CHAR_BIT; \/\/ Dividing filtered hashes by this value will leave only 3 highest bits required to address bit in the byte\n\n memset(table,0,HASHSIZE);\n byte *p = (byte*) buf;\n for (size_t i=0; i<bufsize-STEP+1; i+=STEP)\n {\n uint32_t hash = hash_function(*(uint32_t*)(p+i));\n if (hash < FILTER_MAX_HASH)\n table[hash % HASHSIZE] |= 1 << (hash\/FILTER_HASH_DIVIDER);\n }\n\n size_t count = 0;\n for (size_t i=0; i<HASHSIZE; i++)\n count += bits[table[i]];\n\n \/\/ We have checked bufsize\/(STEP*FILTER) hashes and found `count` original values among them\n *entropy = count \/ (double(bufsize)\/(STEP*FILTER));\n}\n\n\n\/**********************************************************************\/\n\/* Supplementary code *\/\n\/**********************************************************************\/\n\nstatic char* show3 (uint64_t n, char *buf, const char *prepend=\"\")\n{\n char *p = buf + 27+strlen(prepend);\n int i = 4;\n\n *p = '\\0';\n do {\n if (!--i) *--p = ',', i = 3;\n *--p = '0' + (n % 10);\n } while (n \/= 10);\n\n memcpy (p-strlen(prepend), prepend, strlen(prepend));\n return p-strlen(prepend);\n}\n\n\nint main (int argc, char **argv)\n{\n fprintf(stderr, \"DataSmoker 0.1. \");\n\n if (argc==1)\n {\n fprintf(stderr, \"\\n\\nUsage: smoke infile\\n\\n%s\", copyright);\n return EXIT_FAILURE;\n }\n\n FILE *infile = fopen (argv[1], \"rb\"); if (infile==NULL) {fprintf (stderr, \"Can't open input file %s!\\n\", argv[1]); return EXIT_FAILURE;}\n\n ByteSmoker ByteS;\n DWordSmoker DWordS;\n Smoker *smokers[] = {&ByteS, &DWordS};\n const int NumSmokers = sizeof(smokers)\/sizeof(*smokers);\n double entropy, min_entropy[NumSmokers], avg_entropy[NumSmokers] = {0};\n for (int i=0; i<NumSmokers; ++i) min_entropy[i] = 1;\n\n uint64_t origsize = 0;\n for(;;)\n {\n int buf_bytes;\n const int BUFSIZE = 4*mb;\n static char buf[BUFSIZE];\n\n buf_bytes = fread(buf, 1, BUFSIZE, infile);\n if (buf_bytes==0) break;\n\n for (int i=0; i<NumSmokers; i++)\n {\n smokers[i]->smoke(buf, buf_bytes, &entropy);\n if (entropy < min_entropy[i])\n min_entropy[i] = entropy;\n avg_entropy[i] += entropy*buf_bytes;\n }\n\n origsize += buf_bytes;\n }\n\n char temp1[100]; fprintf(stderr, \"Processed %s bytes\\n\", show3(origsize,temp1));\n for (int i=0; i<NumSmokers; i++)\n fprintf(stderr, \"%s entropy: minimum %.2lf%%, average %.2lf%%\\n\", smokers[i]->name(), min_entropy[i]*100, avg_entropy[i]\/origsize*100);\n return EXIT_SUCCESS;\n}\n<commit_msg>DWord smoker modified to support even STEP==FILTER==1 values<commit_after>char copyright[] = \"Developed by Bulat Ziganshin\\n\"\n \"The code is placed in public domain\\n\";\n\n\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <limits.h>\n\n#define kb 1024\n#define mb (kb*kb)\ntypedef unsigned char byte;\n\nclass Smoker\n{\npublic:\n virtual const char* name() = 0;\n virtual void smoke (void *buf, size_t bufsize, double *entropy) = 0;\n virtual ~Smoker() {}\n};\n\n\n\/**********************************************************************\/\n\/* Byte smoker: calculate compression ratio with the order-0 model *\/\n\/**********************************************************************\/\n\nclass ByteSmoker : public Smoker\n{\npublic:\n virtual const char* name() {return \"ByteSmoker\";};\n virtual void smoke (void *buf, size_t bufsize, double *entropy);\n};\n\nvoid ByteSmoker::smoke (void *buf, size_t bufsize, double *entropy)\n{\n size_t count1[256] = {0};\n size_t count2[256] = {0};\n size_t count3[256] = {0};\n size_t count4[256] = {0};\n\n byte *p = (byte*) buf; int i;\n for (i=0; i<bufsize-3; i+=4)\n count1[ p[i] ]++,\n count2[ p[i+1] ]++,\n count3[ p[i+2] ]++,\n count4[ p[i+3] ]++;\n for (; i<bufsize; i++)\n count1[ p[i] ]++;\n\n double order0 = 0;\n for (int i=0; i<256; i++)\n {\n size_t count = count1[i] + count2[i] + count3[i] + count4[i];\n if (count)\n order0 += count * log(double(bufsize\/count))\/log(double(2)) \/ 8;\n }\n\n *entropy = order0 \/ bufsize;\n}\n\n\n\/**********************************************************************\/\n\/* DWord smoker *\/\n\/**********************************************************************\/\n\nuint32_t hash_function (uint32_t x)\n{\n uint64_t hash = x * uint64_t(123456791u);\n return uint32_t(hash>>32) ^ uint32_t(hash);\n}\n\nconst size_t HASHSIZE = 128*kb;\n\nclass DWordSmoker : public Smoker\n{\n size_t bits[256];\n byte table[HASHSIZE];\npublic:\n DWordSmoker();\n virtual const char* name() {return \"DWordSmoker\";};\n virtual void smoke (void *buf, size_t bufsize, double *entropy);\n virtual ~DWordSmoker() {}\n};\n\nDWordSmoker::DWordSmoker()\n{\n bits[0] = 0;\n for (int i=0; i<256; i++)\n bits[i] = bits[i\/2] + (i%2);\n}\n\nvoid DWordSmoker::smoke (void *buf, size_t bufsize, double *entropy)\n{\n const size_t STEP = 4; \/\/ Check only every n'th position\n const uint32_t FILTER = 16; \/\/ Of those checked, count only every n'th hash\n const uint32_t FILTER_MAX_HASH = uint32_t(-1) \/ FILTER; \/\/ Count only hashes smaller or equal to this value\n const uint32_t FILTER_HASH_DIVIDER = (FILTER_MAX_HASH \/ CHAR_BIT) + 1; \/\/ Dividing filtered hashes by this value will leave only 3 highest bits required to address bit in the byte\n\n memset(table,0,HASHSIZE);\n byte *p = (byte*) buf;\n for (size_t i=0; i<bufsize-STEP+1; i+=STEP)\n {\n uint32_t hash = hash_function(*(uint32_t*)(p+i));\n if (hash <= FILTER_MAX_HASH)\n table[hash % HASHSIZE] |= 1 << (hash\/FILTER_HASH_DIVIDER);\n }\n\n size_t count = 0;\n for (size_t i=0; i<HASHSIZE; i++)\n count += bits[table[i]];\n\n \/\/ We have checked bufsize\/(STEP*FILTER) hashes and found `count` original values among them\n *entropy = count \/ (double(bufsize)\/(STEP*FILTER));\n}\n\n\n\/**********************************************************************\/\n\/* Supplementary code *\/\n\/**********************************************************************\/\n\nstatic char* show3 (uint64_t n, char *buf, const char *prepend=\"\")\n{\n char *p = buf + 27+strlen(prepend);\n int i = 4;\n\n *p = '\\0';\n do {\n if (!--i) *--p = ',', i = 3;\n *--p = '0' + (n % 10);\n } while (n \/= 10);\n\n memcpy (p-strlen(prepend), prepend, strlen(prepend));\n return p-strlen(prepend);\n}\n\n\nint main (int argc, char **argv)\n{\n fprintf(stderr, \"DataSmoker 0.1. \");\n\n if (argc==1)\n {\n fprintf(stderr, \"\\n\\nUsage: smoke infile\\n\\n%s\", copyright);\n return EXIT_FAILURE;\n }\n\n FILE *infile = fopen (argv[1], \"rb\"); if (infile==NULL) {fprintf (stderr, \"Can't open input file %s!\\n\", argv[1]); return EXIT_FAILURE;}\n\n ByteSmoker ByteS;\n DWordSmoker DWordS;\n Smoker *smokers[] = {&ByteS, &DWordS};\n const int NumSmokers = sizeof(smokers)\/sizeof(*smokers);\n double entropy, min_entropy[NumSmokers], avg_entropy[NumSmokers] = {0};\n for (int i=0; i<NumSmokers; ++i) min_entropy[i] = 1;\n\n uint64_t origsize = 0;\n for(;;)\n {\n int buf_bytes;\n const int BUFSIZE = 4*mb;\n static char buf[BUFSIZE];\n\n buf_bytes = fread(buf, 1, BUFSIZE, infile);\n if (buf_bytes==0) break;\n\n for (int i=0; i<NumSmokers; i++)\n {\n smokers[i]->smoke(buf, buf_bytes, &entropy);\n if (entropy < min_entropy[i])\n min_entropy[i] = entropy;\n avg_entropy[i] += entropy*buf_bytes;\n }\n\n origsize += buf_bytes;\n }\n\n char temp1[100]; fprintf(stderr, \"Processed %s bytes\\n\", show3(origsize,temp1));\n for (int i=0; i<NumSmokers; i++)\n fprintf(stderr, \"%s entropy: minimum %.2lf%%, average %.2lf%%\\n\", smokers[i]->name(), min_entropy[i]*100, avg_entropy[i]\/origsize*100);\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <v8.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <common.h>\n#include <dirent.h>\n#include <string.h>\n#include <unistd.h>\n\nv8::Handle<v8::Value> _directory(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {\n\treturn v8::ThrowException(v8::String::New(\"Invalid call format. Use 'new Directory(name)'\"));\n }\n \n args.This()->SetInternalField(0, args[0]);\n return args.This();\n}\n\nv8::Handle<v8::Value> _create(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n int mode;\n if (args.Length() == 0) { \n\tmode = 0777; \n } else {\n\tmode = args[0]->Int32Value();\n }\n\n int result = mkdir(*name, mode);\n if (result != 0) {\n\treturn v8::ThrowException(v8::String::New(\"Cannot create directory'\"));\n }\n \n return args.This();\n}\n\nv8::Handle<v8::Value> _listfiles(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n\n DIR * dp;\n struct dirent * ep;\n \n v8::Handle<v8::Array> result = v8::Array::New();\n \n dp = opendir(*name);\n if (dp == NULL) { return v8::ThrowException(v8::String::New(\"Directory cannot be opened\")); }\n int cnt = 0;\n while ((ep = readdir(dp))) { \n\tif (ep->d_type == DT_REG) {\n\t result->Set(v8::Integer::New(cnt++), v8::String::New(ep->d_name));\n\t}\n }\n closedir(dp);\n return result;\n}\n\nv8::Handle<v8::Value> _listdirectories(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n\n DIR * dp;\n struct dirent * ep;\n \n v8::Handle<v8::Array> result = v8::Array::New();\n \n dp = opendir(*name);\n if (dp == NULL) { return v8::ThrowException(v8::String::New(\"Directory cannot be opened\")); }\n int cnt = 0;\n while ((ep = readdir(dp))) { \n\tif (ep->d_type == DT_DIR) {\n\t if (strcmp(ep->d_name, \".\") != 0 && strcmp(ep->d_name, \"..\") != 0) {\n\t\tresult->Set(v8::Integer::New(cnt++), v8::String::New(ep->d_name));\n\t }\n\t}\n }\n closedir(dp);\n return result;\n}\n\nv8::Handle<v8::Value> _file(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {\n\treturn v8::ThrowException(v8::String::New(\"Invalid call format. Use 'new File(name)'\"));\n }\n \n args.This()->SetInternalField(0, args[0]);\n args.This()->SetInternalField(1, v8::Boolean::New(false));\n return args.This();\n}\n\nv8::Handle<v8::Value> _open(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 1) {\n\treturn v8::ThrowException(v8::String::New(\"Bad argument count. Use 'file.open(mode)'\"));\n }\n v8::String::Utf8Value mode(args[0]);\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n if (!file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"File already opened\"));\n }\n \n FILE * f;\n f = fopen(*name, *mode);\n \n if (!f) {\n\treturn v8::ThrowException(v8::String::New(\"Cannot open file\"));\n }\n \n struct stat st;\n if (stat(*name, &st) == 0) {\n\targs.This()->SetInternalField(2, v8::Integer::New(st.st_size));\n }\n args.This()->SetInternalField(1, v8::External::New((void *)f));\n args.This()->SetInternalField(3, v8::Integer::New(0));\n \n return args.This();\n}\n\t\t\nv8::Handle<v8::Value> _close(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n \n if (file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"Cannot close non-opened file\"));\n }\n \n FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());\n fclose(f);\n args.This()->SetInternalField(1, v8::Boolean::New(false));\n return args.This();\n}\n\nv8::Handle<v8::Value> _read(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n \n if (file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"File must be opened before reading\"));\n }\n \n long size = args.This()->GetInternalField(2)->IntegerValue();\n long pos = args.This()->GetInternalField(3)->IntegerValue();\n \n FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());\n \n long avail = size-pos;\n if (!avail) { return v8::Boolean::New(false); }\n \n if (args.Length() && args[0]->IsNumber()) {\n int len = args[0]->IntegerValue();\n\tif (len < avail) { avail = len; }\n }\n char buf[avail];\n fread(buf, sizeof(char), avail, f);\n pos += avail;\n \n args.This()->SetInternalField(3, v8::Integer::New(pos));\n \n if (args.Length() > 1 && args[1]->IsTrue()) {\n return char2array(buf, avail);\n } else {\n return char2string(buf, avail);\n }\n}\n\nv8::Handle<v8::Value> _rewind(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n if (file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"File must be opened before rewinding\"));\n }\n \n FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());\n rewind(f);\n\n args.This()->SetInternalField(3, v8::Integer::New(0));\n return args.This();\n}\n\nv8::Handle<v8::Value> _write(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n \n if (file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"File must be opened before writing\"));\n }\n \n\n FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());\n \n \n if (args[0]->IsArray()) {\n\tv8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]);\n\tint len = arr->Length();\n\t\n\tint max = 4096;\n\tint current = 0;\n\tchar buf[max];\n\tfor (int i=0;i<len;i++) {\n \t v8::Handle<v8::Integer> a = v8::Integer::New(arr->Get(v8::Integer::New(i))->IntegerValue());\n\t buf[current++] = (char) a->Int32Value();\n\t if (current == max) {\n \t\tfwrite(buf, sizeof(char), current, f);\n\t\tcurrent = 0;\n\t }\n\t}\n\tif (current) { fwrite(buf, sizeof(char), current, f); }\n\n } else {\n\tv8::String::Utf8Value data(args[0]);\n \n\tfwrite(*data, sizeof(char), args[0]->ToString()->Utf8Length(), f);\n }\n\t \n return args.This();\n}\n\nv8::Handle<v8::Value> _remove(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n \n if (remove(*name) != 0) {\n\treturn v8::ThrowException(v8::String::New(\"Cannot remove file\/dir\"));\n }\n \n return args.This();\n}\n\nv8::Handle<v8::Value> _getsize(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n \n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n struct stat st;\n if (stat(*name, &st) == 0) {\n\treturn v8::Integer::New(st.st_size);\n } else {\n\treturn v8::Boolean::New(false);\n } \n}\n\nv8::Handle<v8::Value> _copy(char * name1, char * name2) {\n int len = 1024;\n char buf[len];\n \n FILE * f1 = fopen(name1, \"rb\");\n FILE * f2 = fopen(name2, \"wb\");\n \n if (f1 == NULL) { return v8::ThrowException(v8::String::New(\"Cannot open source file\")); }\n if (f2 == NULL) { return v8::ThrowException(v8::String::New(\"Cannot open target file\")); }\n \n int size = 0;\n \n while ((size = fread(buf, sizeof(char), len, f1))) {\n\tfwrite(buf, sizeof(char), size, f2);\n }\n \n fclose(f1);\n fclose(f2);\n return v8::Boolean::New(true);\n}\nv8::Handle<v8::Value> _movefile(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n \n if (args.Length() < 1) {\n\treturn v8::ThrowException(v8::String::New(\"Bad argument count. Use 'file.rename(newname)'\"));\n }\n \n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n v8::String::Utf8Value newname(args[0]);\n\n int renres = rename(*name, *newname);\n\n if (renres != 0) {\n\tv8::Handle<v8::Value> result = _copy(*name, *newname);\n\tif (result->IsTrue()) {\n\t remove(*name);\n\t} else {\n\t return result;\n\t}\n }\n \n args.This()->SetInternalField(0, args[0]);\n return args.This(); \n}\n\nv8::Handle<v8::Value> _copyfile(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 1) {\n\treturn v8::ThrowException(v8::String::New(\"Bad argument count. Use 'file.copy(newname)'\"));\n }\n \n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n v8::String::Utf8Value newname(args[0]);\n\n v8::Handle<v8::Value> result = _copy(*name, *newname); \n if (result->IsTrue()) {\n\treturn _file(args);\n } else {\n\treturn result;\n }\n}\n\n\n\nv8::Handle<v8::Value> _tostring(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n return args.This()->GetInternalField(0);\n}\n\nv8::Handle<v8::Value> _exists(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n int result = access(*name, F_OK);\n return v8::Boolean::New(result == 0);\n}\n\nvoid SetupIo(v8::Handle<v8::Object> target) {\n v8::HandleScope handle_scope;\n\n v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_file);\n ft->SetClassName(v8::String::New(\"File\"));\n v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();\n ot->SetInternalFieldCount(4); \/* filename, handle, size, position *\/\n\n v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();\n pt->Set(\"open\", v8::FunctionTemplate::New(_open));\n pt->Set(\"read\", v8::FunctionTemplate::New(_read));\n pt->Set(\"rewind\", v8::FunctionTemplate::New(_rewind));\n pt->Set(\"close\", v8::FunctionTemplate::New(_close));\n pt->Set(\"write\", v8::FunctionTemplate::New(_write));\n pt->Set(\"remove\", v8::FunctionTemplate::New(_remove));\n pt->Set(\"getSize\", v8::FunctionTemplate::New(_getsize));\n pt->Set(\"toString\", v8::FunctionTemplate::New(_tostring));\n pt->Set(\"exists\", v8::FunctionTemplate::New(_exists));\n pt->Set(\"move\", v8::FunctionTemplate::New(_movefile));\n pt->Set(\"copy\", v8::FunctionTemplate::New(_copyfile));\n\n target->Set(v8::String::New(\"File\"), ft->GetFunction());\t \n \n ft = v8::FunctionTemplate::New(_directory);\n ft->SetClassName(v8::String::New(\"Directory\"));\n ot = ft->InstanceTemplate();\n ot->SetInternalFieldCount(1); \/* dirname *\/\n\n pt = ft->PrototypeTemplate();\n pt->Set(\"create\", v8::FunctionTemplate::New(_create));\n pt->Set(\"listFiles\", v8::FunctionTemplate::New(_listfiles));\n pt->Set(\"listDirectories\", v8::FunctionTemplate::New(_listdirectories));\n pt->Set(\"toString\", v8::FunctionTemplate::New(_tostring));\n pt->Set(\"exists\", v8::FunctionTemplate::New(_exists));\n pt->Set(\"remove\", v8::FunctionTemplate::New(_remove));\n\n target->Set(v8::String::New(\"Directory\"), ft->GetFunction());\t \n \n}\n<commit_msg>Bugfix in file copy behavior<commit_after>#include <v8.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <common.h>\n#include <dirent.h>\n#include <string.h>\n#include <unistd.h>\n\nv8::Handle<v8::FunctionTemplate> ft;\n\nv8::Handle<v8::Value> _directory(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {\n\treturn v8::ThrowException(v8::String::New(\"Invalid call format. Use 'new Directory(name)'\"));\n }\n \n args.This()->SetInternalField(0, args[0]);\n return args.This();\n}\n\nv8::Handle<v8::Value> _create(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n int mode;\n if (args.Length() == 0) { \n\tmode = 0777; \n } else {\n\tmode = args[0]->Int32Value();\n }\n\n int result = mkdir(*name, mode);\n if (result != 0) {\n\treturn v8::ThrowException(v8::String::New(\"Cannot create directory'\"));\n }\n \n return args.This();\n}\n\nv8::Handle<v8::Value> _listfiles(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n\n DIR * dp;\n struct dirent * ep;\n \n v8::Handle<v8::Array> result = v8::Array::New();\n \n dp = opendir(*name);\n if (dp == NULL) { return v8::ThrowException(v8::String::New(\"Directory cannot be opened\")); }\n int cnt = 0;\n while ((ep = readdir(dp))) { \n\tif (ep->d_type == DT_REG) {\n\t result->Set(v8::Integer::New(cnt++), v8::String::New(ep->d_name));\n\t}\n }\n closedir(dp);\n return result;\n}\n\nv8::Handle<v8::Value> _listdirectories(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n\n DIR * dp;\n struct dirent * ep;\n \n v8::Handle<v8::Array> result = v8::Array::New();\n \n dp = opendir(*name);\n if (dp == NULL) { return v8::ThrowException(v8::String::New(\"Directory cannot be opened\")); }\n int cnt = 0;\n while ((ep = readdir(dp))) { \n\tif (ep->d_type == DT_DIR) {\n\t if (strcmp(ep->d_name, \".\") != 0 && strcmp(ep->d_name, \"..\") != 0) {\n\t\tresult->Set(v8::Integer::New(cnt++), v8::String::New(ep->d_name));\n\t }\n\t}\n }\n closedir(dp);\n return result;\n}\n\nv8::Handle<v8::Value> _file(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {\n\treturn v8::ThrowException(v8::String::New(\"Invalid call format. Use 'new File(name)'\"));\n }\n \n args.This()->SetInternalField(0, args[0]);\n args.This()->SetInternalField(1, v8::Boolean::New(false));\n return args.This();\n}\n\nv8::Handle<v8::Value> _open(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 1) {\n\treturn v8::ThrowException(v8::String::New(\"Bad argument count. Use 'file.open(mode)'\"));\n }\n v8::String::Utf8Value mode(args[0]);\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n if (!file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"File already opened\"));\n }\n \n FILE * f;\n f = fopen(*name, *mode);\n \n if (!f) {\n\treturn v8::ThrowException(v8::String::New(\"Cannot open file\"));\n }\n \n struct stat st;\n if (stat(*name, &st) == 0) {\n\targs.This()->SetInternalField(2, v8::Integer::New(st.st_size));\n }\n args.This()->SetInternalField(1, v8::External::New((void *)f));\n args.This()->SetInternalField(3, v8::Integer::New(0));\n \n return args.This();\n}\n\t\t\nv8::Handle<v8::Value> _close(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n \n if (file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"Cannot close non-opened file\"));\n }\n \n FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());\n fclose(f);\n args.This()->SetInternalField(1, v8::Boolean::New(false));\n return args.This();\n}\n\nv8::Handle<v8::Value> _read(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n \n if (file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"File must be opened before reading\"));\n }\n \n long size = args.This()->GetInternalField(2)->IntegerValue();\n long pos = args.This()->GetInternalField(3)->IntegerValue();\n \n FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());\n \n long avail = size-pos;\n if (!avail) { return v8::Boolean::New(false); }\n \n if (args.Length() && args[0]->IsNumber()) {\n int len = args[0]->IntegerValue();\n\tif (len < avail) { avail = len; }\n }\n char buf[avail];\n fread(buf, sizeof(char), avail, f);\n pos += avail;\n \n args.This()->SetInternalField(3, v8::Integer::New(pos));\n \n if (args.Length() > 1 && args[1]->IsTrue()) {\n return char2array(buf, avail);\n } else {\n return char2string(buf, avail);\n }\n}\n\nv8::Handle<v8::Value> _rewind(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n if (file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"File must be opened before rewinding\"));\n }\n \n FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());\n rewind(f);\n\n args.This()->SetInternalField(3, v8::Integer::New(0));\n return args.This();\n}\n\nv8::Handle<v8::Value> _write(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::Handle<v8::Value> file = args.This()->GetInternalField(1);\n \n if (file->IsFalse()) {\n\treturn v8::ThrowException(v8::String::New(\"File must be opened before writing\"));\n }\n \n\n FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());\n \n \n if (args[0]->IsArray()) {\n\tv8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]);\n\tint len = arr->Length();\n\t\n\tint max = 4096;\n\tint current = 0;\n\tchar buf[max];\n\tfor (int i=0;i<len;i++) {\n \t v8::Handle<v8::Integer> a = v8::Integer::New(arr->Get(v8::Integer::New(i))->IntegerValue());\n\t buf[current++] = (char) a->Int32Value();\n\t if (current == max) {\n \t\tfwrite(buf, sizeof(char), current, f);\n\t\tcurrent = 0;\n\t }\n\t}\n\tif (current) { fwrite(buf, sizeof(char), current, f); }\n\n } else {\n\tv8::String::Utf8Value data(args[0]);\n \n\tfwrite(*data, sizeof(char), args[0]->ToString()->Utf8Length(), f);\n }\n\t \n return args.This();\n}\n\nv8::Handle<v8::Value> _remove(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n \n if (remove(*name) != 0) {\n\treturn v8::ThrowException(v8::String::New(\"Cannot remove file\/dir\"));\n }\n \n return args.This();\n}\n\nv8::Handle<v8::Value> _getsize(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n \n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n struct stat st;\n if (stat(*name, &st) == 0) {\n\treturn v8::Integer::New(st.st_size);\n } else {\n\treturn v8::Boolean::New(false);\n } \n}\n\nv8::Handle<v8::Value> _copy(char * name1, char * name2) {\n int len = 1024;\n char buf[len];\n \n FILE * f1 = fopen(name1, \"rb\");\n FILE * f2 = fopen(name2, \"wb\");\n \n if (f1 == NULL) { return v8::ThrowException(v8::String::New(\"Cannot open source file\")); }\n if (f2 == NULL) { return v8::ThrowException(v8::String::New(\"Cannot open target file\")); }\n \n int size = 0;\n \n while ((size = fread(buf, sizeof(char), len, f1))) {\n\tfwrite(buf, sizeof(char), size, f2);\n }\n \n fclose(f1);\n fclose(f2);\n return v8::Boolean::New(true);\n}\nv8::Handle<v8::Value> _movefile(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n \n if (args.Length() < 1) {\n\treturn v8::ThrowException(v8::String::New(\"Bad argument count. Use 'file.rename(newname)'\"));\n }\n \n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n v8::String::Utf8Value newname(args[0]);\n\n int renres = rename(*name, *newname);\n\n if (renres != 0) {\n\tv8::Handle<v8::Value> result = _copy(*name, *newname);\n\tif (result->IsTrue()) {\n\t remove(*name);\n\t} else {\n\t return result;\n\t}\n }\n \n args.This()->SetInternalField(0, args[0]);\n return args.This(); \n}\n\nv8::Handle<v8::Value> _copyfile(const v8::Arguments & args) {\n v8::HandleScope handle_scope;\n if (args.Length() < 1) {\n\treturn v8::ThrowException(v8::String::New(\"Bad argument count. Use 'file.copy(newname)'\"));\n }\n \n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n v8::String::Utf8Value newname(args[0]);\n\n v8::Handle<v8::Value> result = _copy(*name, *newname); \n if (result->IsTrue()) {\n\tv8::Handle<v8::Value> fargs[] = { args[0] };\n \treturn ft->GetFunction()->NewInstance(1, fargs);\n } else {\n\treturn result;\n }\n}\n\n\n\nv8::Handle<v8::Value> _tostring(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n return args.This()->GetInternalField(0);\n}\n\nv8::Handle<v8::Value> _exists(const v8::Arguments& args) {\n v8::HandleScope handle_scope;\n v8::String::Utf8Value name(args.This()->GetInternalField(0));\n int result = access(*name, F_OK);\n return v8::Boolean::New(result == 0);\n}\n\nvoid SetupIo(v8::Handle<v8::Object> target) {\n\n ft = v8::FunctionTemplate::New(_file);\n ft->SetClassName(v8::String::New(\"File\"));\n v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();\n ot->SetInternalFieldCount(4); \/* filename, handle, size, position *\/\n\n v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();\n pt->Set(\"open\", v8::FunctionTemplate::New(_open));\n pt->Set(\"read\", v8::FunctionTemplate::New(_read));\n pt->Set(\"rewind\", v8::FunctionTemplate::New(_rewind));\n pt->Set(\"close\", v8::FunctionTemplate::New(_close));\n pt->Set(\"write\", v8::FunctionTemplate::New(_write));\n pt->Set(\"remove\", v8::FunctionTemplate::New(_remove));\n pt->Set(\"getSize\", v8::FunctionTemplate::New(_getsize));\n pt->Set(\"toString\", v8::FunctionTemplate::New(_tostring));\n pt->Set(\"exists\", v8::FunctionTemplate::New(_exists));\n pt->Set(\"move\", v8::FunctionTemplate::New(_movefile));\n pt->Set(\"copy\", v8::FunctionTemplate::New(_copyfile));\n\n target->Set(v8::String::New(\"File\"), ft->GetFunction());\t \n \n ft = v8::FunctionTemplate::New(_directory);\n ft->SetClassName(v8::String::New(\"Directory\"));\n ot = ft->InstanceTemplate();\n ot->SetInternalFieldCount(1); \/* dirname *\/\n\n pt = ft->PrototypeTemplate();\n pt->Set(\"create\", v8::FunctionTemplate::New(_create));\n pt->Set(\"listFiles\", v8::FunctionTemplate::New(_listfiles));\n pt->Set(\"listDirectories\", v8::FunctionTemplate::New(_listdirectories));\n pt->Set(\"toString\", v8::FunctionTemplate::New(_tostring));\n pt->Set(\"exists\", v8::FunctionTemplate::New(_exists));\n pt->Set(\"remove\", v8::FunctionTemplate::New(_remove));\n\n target->Set(v8::String::New(\"Directory\"), ft->GetFunction());\t \n \n}\n<|endoftext|>"} {"text":"<commit_before>#include \"style.h\"\n#include \"document.h\"\n#include \"element.h\"\n#include \"composite_element.h\"\n#include \"helpers.h\"\n#include \"attribute.h\"\n#include <iostream>\n#include <sstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <algorithm>\n\n#define XSL_NS \"xsl\"\n#define XSL_TEMPLATES \"template\"\n#define XSL_APPLY_TEMPLATES \"apply-templates\"\n#define XSL_MATCH \"match\"\n#define XSL_ROOT_MATCH \"\/\"\n\nnamespace Xsl\n{\n typedef ::Document XMLDocument;\n\n bool is_element(Element const &, std::string const & = \"\");\n\n class Document\n {\n public:\n Document(XMLDocument const &);\n\n void apply_style_to(XMLDocument const &, std::ostream &) const;\n\n private:\n void handle_e(Element const &, Element const &, std::ostream &) const;\n void handle_ce(CompositeElement const &, Element const &, std::ostream &) const;\n void handle_xsl(Element const &, Element const &, std::ostream &) const;\n\n std::multimap<std::string, Element const *> _absolute_path_templates;\n std::multimap<std::string, Element const *> _relative_path_templates;\n };\n\n \/\/ Implementation\n\n bool is_element(Element const & element, std::string const & tag)\n {\n auto ns_split = element.ns_split();\n\n \/\/ F**king lower() method\n std::transform(ns_split.first.begin(), ns_split.first.end(),\n ns_split.first.begin(), ::tolower);\n std::transform(ns_split.second.begin(), ns_split.second.end(),\n ns_split.second.begin(), ::tolower);\n\n \/\/ Only xsl namespace\n return ns_split.first == XSL_NS && (tag.empty() || ns_split.second == tag);\n }\n\n Document::Document(XMLDocument const & doc):\n _absolute_path_templates(),\n _relative_path_templates()\n {\n for (auto child : doc.root()->children())\n {\n Element * element = dynamic_cast<Element *>(child);\n if (element != nullptr && is_element(*element, XSL_TEMPLATES))\n {\n for (auto attr : element->attributes())\n {\n if (attr->name() == XSL_MATCH && !attr->value().empty())\n {\n ((Helpers::trim(Helpers::split(attr->value(), '\/')[0]).empty())\n ? _absolute_path_templates\n : _relative_path_templates\n ).insert({ attr->value(), { element } });\n\n break; \/\/ because f**k you that's why !\n }\n }\n }\n }\n }\n\n void Document::apply_style_to(XMLDocument const & xml, std::ostream & os) const\n {\n auto range = _absolute_path_templates.equal_range(\"\/\");\n for (auto it = range.first; it != range.second; it++)\n {\n if (it != _absolute_path_templates.end())\n {\n auto ce = dynamic_cast<CompositeElement const *>(it->second);\n handle_ce(*ce, *xml.root(), os);\n }\n else\n {\n \/\/ TODO handle when to \"\/\" template is given\n }\n }\n }\n\n void Document::handle_e(Element const & template_element,\n Element const & root_element, std::ostream & os) const\n {\n if (is_element(template_element))\n {\n handle_xsl(template_element, root_element, os);\n }\n else\n {\n auto ce = dynamic_cast<CompositeElement const *>(&template_element);\n if (ce == nullptr)\n {\n os << template_element.str() << std::endl;\n }\n else\n {\n os << ce->begin_str() << std::endl;\n handle_ce(*ce, root_element, os);\n os << ce->end_str() << std::endl;\n }\n }\n }\n\n void Document::handle_ce(CompositeElement const & template_element,\n Element const & root_element, std::ostream & os) const\n {\n for (auto child : template_element.children())\n {\n auto child_element = dynamic_cast<Element const *>(child);\n if (child_element == nullptr)\n {\n os << child->str() << std::endl;\n }\n else\n {\n handle_e(*child_element, root_element, os);\n }\n }\n }\n\n void Document::handle_xsl(Element const & template_element,\n Element const & element, std::ostream & os) const\n {\n os << template_element.str()<< std::endl;\n }\n}\n\nvoid xml_apply_style(Document const & xml, Document const & xsl, std::ostream & os)\n{\n Xsl::Document xsl_doc(xsl); \/\/ FIXME check for xsl:stylesheet root element\n xsl_doc.apply_style_to(xml, os);\n}\n\n\/\/ vim:ft=cpp et sw=2 sts=2:\n<commit_msg>Remove multimap<commit_after>#include \"style.h\"\n#include \"document.h\"\n#include \"element.h\"\n#include \"composite_element.h\"\n#include \"helpers.h\"\n#include \"attribute.h\"\n#include <iostream>\n#include <sstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <algorithm>\n\n#define XSL_NS \"xsl\"\n#define XSL_TEMPLATES \"template\"\n#define XSL_APPLY_TEMPLATES \"apply-templates\"\n#define XSL_MATCH \"match\"\n#define XSL_ROOT_MATCH \"\/\"\n\nnamespace Xsl\n{\n typedef ::Document XMLDocument;\n\n bool is_element(Element const &, std::string const & = \"\");\n\n class Document\n {\n public:\n Document(XMLDocument const &);\n\n void apply_style_to(XMLDocument const &, std::ostream &) const;\n\n private:\n void handle_e(Element const &, Element const &, std::ostream &) const;\n void handle_ce(CompositeElement const &, Element const &, std::ostream &) const;\n void handle_xsl(Element const &, Element const &, std::ostream &) const;\n\n std::map<std::string, Element const *> _absolute_path_templates;\n std::map<std::string, Element const *> _relative_path_templates;\n };\n\n \/\/ Implementation\n\n bool is_element(Element const & element, std::string const & tag)\n {\n auto ns_split = element.ns_split();\n\n \/\/ F**king lower() method\n std::transform(ns_split.first.begin(), ns_split.first.end(),\n ns_split.first.begin(), ::tolower);\n std::transform(ns_split.second.begin(), ns_split.second.end(),\n ns_split.second.begin(), ::tolower);\n\n \/\/ Only xsl namespace\n return ns_split.first == XSL_NS && (tag.empty() || ns_split.second == tag);\n }\n\n Document::Document(XMLDocument const & doc):\n _absolute_path_templates(),\n _relative_path_templates()\n {\n for (auto child : doc.root()->children())\n {\n Element * element = dynamic_cast<Element *>(child);\n if (element != nullptr && is_element(*element, XSL_TEMPLATES))\n {\n for (auto attr : element->attributes())\n {\n if (attr->name() == XSL_MATCH && !attr->value().empty())\n {\n ((Helpers::trim(Helpers::split(attr->value(), '\/')[0]).empty())\n ? _absolute_path_templates\n : _relative_path_templates\n )[attr->value()] = { element };\n\n break; \/\/ because f**k you that's why !\n }\n }\n }\n }\n }\n\n void Document::apply_style_to(XMLDocument const & xml, std::ostream & os) const\n {\n auto it = _absolute_path_templates.find(\"\/\");\n if (it != _absolute_path_templates.end())\n {\n auto ce = dynamic_cast<CompositeElement const *>(it->second);\n handle_ce(*ce, *xml.root(), os);\n }\n else\n {\n \/\/ TODO handle when no \"\/\" template is given\n }\n }\n\n void Document::handle_e(Element const & template_element,\n Element const & root_element, std::ostream & os) const\n {\n if (is_element(template_element))\n {\n handle_xsl(template_element, root_element, os);\n }\n else\n {\n auto ce = dynamic_cast<CompositeElement const *>(&template_element);\n if (ce == nullptr)\n {\n os << template_element.str() << std::endl;\n }\n else\n {\n os << ce->begin_str() << std::endl;\n handle_ce(*ce, root_element, os);\n os << ce->end_str() << std::endl;\n }\n }\n }\n\n void Document::handle_ce(CompositeElement const & template_element,\n Element const & root_element, std::ostream & os) const\n {\n for (auto child : template_element.children())\n {\n auto child_element = dynamic_cast<Element const *>(child);\n if (child_element == nullptr)\n {\n os << child->str() << std::endl;\n }\n else\n {\n handle_e(*child_element, root_element, os);\n }\n }\n }\n\n void Document::handle_xsl(Element const & template_element,\n Element const & element, std::ostream & os) const\n {\n os << template_element.str()<< std::endl;\n }\n}\n\nvoid xml_apply_style(Document const & xml, Document const & xsl, std::ostream & os)\n{\n Xsl::Document xsl_doc(xsl); \/\/ FIXME check for xsl:stylesheet root element\n xsl_doc.apply_style_to(xml, os);\n}\n\n\/\/ vim:ft=cpp et sw=2 sts=2:\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include \"gtest\/gtest.h\"\n#include <Utils\/ResponseUtils.h>\n#include <Utils\/TestUtils.h>\n\n#include <hspp\/Tasks\/BasicTasks\/CombatTask.h>\n#include <hspp\/Tasks\/BasicTasks\/InitAttackCountTask.h>\n\nusing namespace Hearthstonepp;\n\nclass CombatTester\n{\n public:\n CombatTester()\n : m_gen(CardClass::DRUID, CardClass::ROGUE),\n m_agent(std::move(m_gen.player1), std::move(m_gen.player2)),\n m_resp(m_agent),\n m_combat(m_agent.GetTaskAgent())\n {\n \/\/ Do Nothing\n }\n\n std::tuple<Player&, Player&> GetPlayer()\n {\n return { m_agent.GetPlayer1(), m_agent.GetPlayer2() };\n }\n\n void Attack(size_t src, size_t dst, MetaData expected, bool init = false)\n {\n if (init)\n {\n m_init.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());\n m_init.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1());\n }\n auto target = m_resp.Target(src, dst);\n MetaData result =\n m_combat.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());\n EXPECT_EQ(result, expected);\n\n TaskMeta meta = target.get();\n EXPECT_EQ(meta.id, +TaskID::REQUIRE);\n }\n\n private:\n TestUtils::PlayerGenerator m_gen;\n\n GameAgent m_agent;\n TestUtils::AutoResponder m_resp;\n\n BasicTasks::CombatTask m_combat;\n BasicTasks::InitAttackCountTask m_init;\n};\n\nTEST(CombatTask, GetTaskID)\n{\n TaskAgent agent;\n BasicTasks::CombatTask combat(agent);\n EXPECT_EQ(combat.GetTaskID(), +TaskID::COMBAT);\n}\n\nTEST(CombatTask, Default)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n\n auto card1 = TestUtils::GenerateMinionCard(\"minion1\", 3, 6);\n auto card2 = TestUtils::GenerateMinionCard(\"minion2\", 5, 4);\n\n player1.field.emplace_back(new Minion(card1));\n player2.field.emplace_back(new Minion(card2));\n\n tester.Attack(1, 0, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth);\n EXPECT_EQ(player2.hero->health,\n player2.hero->maxHealth - player1.field[0]->attack);\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(1));\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));\n EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));\n\n auto card3 = TestUtils::GenerateMinionCard(\"minion3\", 5, 6);\n auto card4 = TestUtils::GenerateMinionCard(\"minion4\", 5, 4);\n\n player1.field.emplace_back(new Minion(card3));\n player2.field.emplace_back(new Minion(card4));\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1));\n EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));\n\n auto card5 = TestUtils::GenerateMinionCard(\"minion5\", 5, 4);\n\n player1.field[0]->attack = 1;\n player2.field.emplace_back(new Minion(card5));\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(3));\n}\n\nTEST(CombatTask, IndexOutOfRange)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion1\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n tester.Attack(1, 2, MetaData::COMBAT_DST_IDX_OUT_OF_RANGE, true);\n tester.Attack(2, 1, MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE, true);\n}\n\nTEST(CombatTask, Charge)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion1\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::CHARGE, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, false);\n\n player1.field[0]->SetAbility(GameTag::CHARGE, false);\n tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED, false);\n}\n\nTEST(CombatTask, Taunt)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion1\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player2.field[1]->SetAbility(GameTag::TAUNT, true);\n tester.Attack(1, 1, MetaData::COMBAT_FIELD_HAVE_TAUNT, true);\n\n player2.field[1]->SetAbility(GameTag::TAUNT, false);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n}\n\nTEST(CombatTask, Stealth)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player2.field[0]->SetAbility(GameTag::STEALTH, true);\n\n tester.Attack(1, 1, MetaData::COMBAT_TARGET_STEALTH, true);\n\n player1.field[0]->SetAbility(GameTag::STEALTH, true);\n player2.field[0]->SetAbility(GameTag::STEALTH, false);\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field[0]->gameTags[+GameTag::STEALTH], 0);\n}\n\nTEST(CombatTask, Immune)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player2.field[0]->SetAbility(GameTag::IMMUNE, true);\n\n tester.Attack(1, 1, MetaData::COMBAT_TARGET_IMMUNE, true);\n}\n\nTEST(CombatTask, Windfury)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED);\n\n player1.field[0]->SetAbility(GameTag::WINDFURY, true);\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS);\n tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED);\n}\n\nTEST(CombatTask, DivineShield)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::DIVINE_SHIELD, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n\n EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth);\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));\n\n player2.field[0]->SetAbility(GameTag::DIVINE_SHIELD, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));\n}\n\nTEST(CombatTask, Poisonous)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::POISONOUS, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));\n EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));\n\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::POISONOUS, false);\n player2.field[0]->SetAbility(GameTag::POISONOUS, true);\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));\n}\n<commit_msg>test: Add unit test to freeze ability<commit_after>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include \"gtest\/gtest.h\"\n#include <Utils\/ResponseUtils.h>\n#include <Utils\/TestUtils.h>\n\n#include <hspp\/Tasks\/BasicTasks\/CombatTask.h>\n#include <hspp\/Tasks\/BasicTasks\/InitAttackCountTask.h>\n\nusing namespace Hearthstonepp;\n\nclass CombatTester\n{\n public:\n CombatTester()\n : m_gen(CardClass::DRUID, CardClass::ROGUE),\n m_agent(std::move(m_gen.player1), std::move(m_gen.player2)),\n m_resp(m_agent),\n m_combat(m_agent.GetTaskAgent())\n {\n \/\/ Do Nothing\n }\n\n std::tuple<Player&, Player&> GetPlayer()\n {\n return { m_agent.GetPlayer1(), m_agent.GetPlayer2() };\n }\n\n void Attack(size_t src, size_t dst, MetaData expected, bool init = false)\n {\n if (init)\n {\n m_init.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());\n m_init.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1());\n }\n auto target = m_resp.Target(src, dst);\n MetaData result =\n m_combat.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());\n EXPECT_EQ(result, expected);\n\n TaskMeta meta = target.get();\n EXPECT_EQ(meta.id, +TaskID::REQUIRE);\n }\n\n void ReverseAttack(size_t src, size_t dst, MetaData expected,\n bool init = false)\n {\n if (init)\n {\n m_init.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1());\n m_init.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());\n }\n auto target = m_resp.Target(src, dst);\n MetaData result =\n m_combat.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1());\n EXPECT_EQ(result, expected);\n\n TaskMeta meta = target.get();\n EXPECT_EQ(meta.id, +TaskID::REQUIRE);\n }\n\n private:\n TestUtils::PlayerGenerator m_gen;\n\n GameAgent m_agent;\n TestUtils::AutoResponder m_resp;\n\n BasicTasks::CombatTask m_combat;\n BasicTasks::InitAttackCountTask m_init;\n};\n\nTEST(CombatTask, GetTaskID)\n{\n TaskAgent agent;\n BasicTasks::CombatTask combat(agent);\n EXPECT_EQ(combat.GetTaskID(), +TaskID::COMBAT);\n}\n\nTEST(CombatTask, Default)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n\n auto card1 = TestUtils::GenerateMinionCard(\"minion1\", 3, 6);\n auto card2 = TestUtils::GenerateMinionCard(\"minion2\", 5, 4);\n\n player1.field.emplace_back(new Minion(card1));\n player2.field.emplace_back(new Minion(card2));\n\n tester.Attack(1, 0, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth);\n EXPECT_EQ(player2.hero->health,\n player2.hero->maxHealth - player1.field[0]->attack);\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(1));\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));\n EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));\n\n auto card3 = TestUtils::GenerateMinionCard(\"minion3\", 5, 6);\n auto card4 = TestUtils::GenerateMinionCard(\"minion4\", 5, 4);\n\n player1.field.emplace_back(new Minion(card3));\n player2.field.emplace_back(new Minion(card4));\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1));\n EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));\n\n auto card5 = TestUtils::GenerateMinionCard(\"minion5\", 5, 4);\n\n player1.field[0]->attack = 1;\n player2.field.emplace_back(new Minion(card5));\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(3));\n}\n\nTEST(CombatTask, IndexOutOfRange)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion1\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n tester.Attack(1, 2, MetaData::COMBAT_DST_IDX_OUT_OF_RANGE, true);\n tester.Attack(2, 1, MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE, true);\n}\n\nTEST(CombatTask, Charge)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion1\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::CHARGE, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, false);\n\n player1.field[0]->SetAbility(GameTag::CHARGE, false);\n tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED, false);\n}\n\nTEST(CombatTask, Taunt)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion1\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player2.field[1]->SetAbility(GameTag::TAUNT, true);\n tester.Attack(1, 1, MetaData::COMBAT_FIELD_HAVE_TAUNT, true);\n\n player2.field[1]->SetAbility(GameTag::TAUNT, false);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n}\n\nTEST(CombatTask, Stealth)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player2.field[0]->SetAbility(GameTag::STEALTH, true);\n\n tester.Attack(1, 1, MetaData::COMBAT_TARGET_STEALTH, true);\n\n player1.field[0]->SetAbility(GameTag::STEALTH, true);\n player2.field[0]->SetAbility(GameTag::STEALTH, false);\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field[0]->gameTags[+GameTag::STEALTH], 0);\n}\n\nTEST(CombatTask, Immune)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player2.field[0]->SetAbility(GameTag::IMMUNE, true);\n\n tester.Attack(1, 1, MetaData::COMBAT_TARGET_IMMUNE, true);\n}\n\nTEST(CombatTask, Windfury)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED);\n\n player1.field[0]->SetAbility(GameTag::WINDFURY, true);\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS);\n tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED);\n}\n\nTEST(CombatTask, DivineShield)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::DIVINE_SHIELD, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n\n EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth);\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));\n\n player2.field[0]->SetAbility(GameTag::DIVINE_SHIELD, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));\n}\n\nTEST(CombatTask, Poisonous)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::POISONOUS, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));\n EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));\n\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::POISONOUS, false);\n player2.field[0]->SetAbility(GameTag::POISONOUS, true);\n\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));\n}\n\nTEST(CombatTask, Freeze)\n{\n CombatTester tester;\n auto [player1, player2] = tester.GetPlayer();\n auto card = TestUtils::GenerateMinionCard(\"minion\", 1, 10);\n\n player1.field.emplace_back(new Minion(card));\n player2.field.emplace_back(new Minion(card));\n\n player1.field[0]->SetAbility(GameTag::FREEZE, true);\n tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);\n EXPECT_EQ(player2.field[0]->HasAbility(GameTag::FROZEN), true);\n tester.ReverseAttack(1, 1, MetaData::COMBAT_SOURCE_FROZEN, false);\n\n EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));\n EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));\n}<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"OkvisSLAMSystem.h\"\n\nnamespace ark {\n\n OkvisSLAMSystem::OkvisSLAMSystem(const std::string & strVocFile, const std::string & strSettingsFile) :\n start_(0.0), t_imu_(0.0), deltaT_(1.0), num_frames_(0), kill(false), \n sparse_map_vector(), active_map_index(-1), new_map_checker(false){\n\n okvis::VioParametersReader vio_parameters_reader;\n try {\n vio_parameters_reader.readConfigFile(strSettingsFile);\n }\n catch (okvis::VioParametersReader::Exception ex) {\n std::cerr << ex.what() << \"\\n\";\n return;\n }\n\n \/\/okvis::VioParameters parameters;\n vio_parameters_reader.getParameters(parameters_);\n\n createNewMap();\n getActiveMap()->setEnableLoopClosure(parameters_.loopClosureParameters.enabled,strVocFile,true, new brisk::BruteForceMatcher());\n\n \/\/initialize Visual odometry\n okvis_estimator_ = std::make_shared<okvis::ThreadedKFVio>(parameters_);\n okvis_estimator_->setBlocking(true);\n\n \/\/Okvis's outframe is our inframe\n auto frame_callback = [this](const okvis::Time& timestamp, okvis::OutFrameData::Ptr frame_data) {\n frame_data_queue_.enqueue({ frame_data,timestamp });\n };\n\n okvis_estimator_->setFrameCallback(frame_callback);\n\n \/\/at thread to pull from queue and call our own callbacks\n frameConsumerThread_ = std::thread(&OkvisSLAMSystem::FrameConsumerLoop, this);\n\n frame_data_queue_.clear();\n frame_queue_.clear();\n std::cout << \"SLAM Initialized\\n\";\n }\n\n void OkvisSLAMSystem::Start() {\n \/\/Do nothing, starts automatically\n }\n\n void OkvisSLAMSystem::FrameConsumerLoop() {\n while (!kill) {\n \n \/\/Get processed frame data from OKVIS\n StampedFrameData frame_data;\n while (!frame_data_queue_.try_dequeue(&frame_data)) {\n if (okvis_estimator_->isReset()) {\n frame_data_queue_.clear();\n frame_queue_.clear();\n }\n if(okvis_estimator_->isReset() && !new_map_checker)\n {\n cout<<\"Created new map\"<<endl;\n new_map_checker = true;\n createNewMap();\n }\n else if(!okvis_estimator_->isReset())\n new_map_checker = false;\n if(kill)\n return;\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n }\n \/\/Get the corresponding frame from queue\n WrappedMultiCameraFrame wrapped_frame;\n bool frame_found = false;\n do {\n if (!(frame_found = frame_queue_.try_dequeue(&wrapped_frame))) {\n break;\n } \n } while (okvis::Time(wrapped_frame.frame->timestamp_) < frame_data.timestamp);\n if (!frame_found){\n std::cout << \"ERROR, FRAME NOT FOUND, THIS SHOULDN'T HAPPEN\\n\";\n continue;\n }\n\n \/\/construct output frame\n MultiCameraFrame::Ptr out_frame = wrapped_frame.frame;\n out_frame->frameId_ = frame_data.data->id;\n out_frame->T_KS_ = frame_data.data->T_KS.T();\n out_frame->keyframeId_ = frame_data.data->keyframe_id;\n\n \/\/add sensor transforms\n \/\/Note: this could potentially just be done once for the system\n \/\/Including here for now in case we switch to optimized results\n for (size_t i = 0; i < wrapped_frame.frame->images_.size(); i++) {\n okvis::kinematics::Transformation T_SC;\n if (i < parameters_.nCameraSystem.numCameras()) {\n T_SC = (*parameters_.nCameraSystem.T_SC(i));\n }\n else if (i - parameters_.nCameraSystem.numCameras() < parameters_.secondaryCameraSystem.numCameras()) {\n T_SC = (*parameters_.secondaryCameraSystem.T_SC(i - parameters_.nCameraSystem.numCameras()));\n } else {\n \/\/no relationship data to imu\n \/\/TODO: throw errror\n T_SC = okvis::kinematics::Transformation::Identity();\n }\n out_frame->T_SC_.push_back(T_SC.T());\n }\n\n \/\/check if keyframe\n if(frame_data.data->is_keyframe){\n if(out_frame->keyframeId_!=out_frame->frameId_){\n std::cout << \"ERROR, KEYFRAME ID INCORRECT, THIS SHOULDN'T HAPPEN\\n\";\n continue;\n }\n MapKeyFrame::Ptr keyframe = MapKeyFrame::Ptr(new MapKeyFrame);\n keyframe->frameId_=out_frame->frameId_;\n keyframe->T_WS_ = frame_data.data->T_WS.T();\n keyframe->T_SC_ = out_frame->T_SC_;\n keyframe->timestamp_ = out_frame->timestamp_;\n \/\/copy keypoints and descriptors to output\n keyframe->keypoints_.resize(frame_data.data->keypoints.size());\n keyframe->keypoints3dh_C.resize(frame_data.data->keypoints.size());\n keyframe->descriptors_.resize(frame_data.data->descriptors.size());\n for(size_t cam_idx=0 ; cam_idx<frame_data.data->keypoints.size() ; cam_idx++){\n keyframe->keypoints_[cam_idx].resize(frame_data.data->keypoints[cam_idx].size()); \n\n keyframe->keypoints3dh_C[cam_idx].resize(frame_data.data->keypoints[cam_idx].size());\n \/\/get transform of the camera\n for(int i=0; i<frame_data.data->keypoints[cam_idx].size(); i++){\n \/\/copy keypoint\n keyframe->keypoints_[cam_idx][i] = frame_data.data->keypoints[cam_idx][i];\n \/\/get estimated 3d position of keypoint in current camera frame\n cv::Vec3f pt3d = out_frame->images_[2].at<cv::Vec3f>(\n std::round(keyframe->keypoints_[cam_idx][i].pt.y),\n std::round(keyframe->keypoints_[cam_idx][i].pt.x));\n if(pt3d[2] >0)\n keyframe->keypoints3dh_C[cam_idx][i] = Eigen::Vector4d(pt3d[0],pt3d[1],pt3d[2],1);\n else\n keyframe->keypoints3dh_C[cam_idx][i] = Eigen::Vector4d(0,0,0,0);\n }\n keyframe->descriptors_[cam_idx]=frame_data.data->descriptors[cam_idx];\n }\n\n \/\/ if(sparseMap_->detectLoopClosure(keyframe))\n \/\/ {\n \/\/ cout<<\"Found loop with my function\"<<endl;\n \/\/ }\n \/\/ push to map\n for (int i = 0; i < sparse_map_vector.size(); i++) {\n const auto sparseMap = sparse_map_vector[i];\n if (sparseMap->detectLoopClosure(keyframe)) {\n active_map_index = i;\n }\n }\n\n if(getActiveMap()->addKeyframe(keyframe)){ \/\/add keyframe returns true if a loop closure was detected\n for (MapLoopClosureDetectedHandler::const_iterator callback_iter = mMapLoopClosureHandler.begin();\n callback_iter != mMapLoopClosureHandler.end(); ++callback_iter) {\n const MapLoopClosureDetectedHandler::value_type& pair = *callback_iter;\n pair.second();\n }\n }\n }\n\n out_frame->keyframe_ = getActiveMap()->getKeyframe(out_frame->keyframeId_);\n\n \/\/Notify callbacks\n if(frame_data.data->is_keyframe){\n for (MapKeyFrameAvailableHandler::const_iterator callback_iter = mMapKeyFrameAvailableHandler.begin();\n callback_iter != mMapKeyFrameAvailableHandler.end(); ++callback_iter) {\n const MapKeyFrameAvailableHandler::value_type& pair = *callback_iter;\n pair.second(out_frame);\n }\n }\n\n for (MapFrameAvailableHandler::const_iterator callback_iter = mMapFrameAvailableHandler.begin();\n callback_iter != mMapFrameAvailableHandler.end(); ++callback_iter) {\n const MapFrameAvailableHandler::value_type& pair = *callback_iter;\n pair.second(out_frame);\n }\n }\n }\n\n \/*void OkvisSLAMSystem::PushFrame(const std::vector<cv::Mat>& images, const double ×tamp) {\n if (okvis_estimator_ == nullptr)\n return;\n okvis::Time t_image(timestamp \/ 1e9);\n if (start_ == okvis::Time(0.0)) {\n start_ = t_image;\n }\n\n if (t_image - start_ > deltaT_) {\n if(mMapFrameAvailableHandler.size()>0){\n frame_queue_.enqueue({ images,t_image,num_frames_ });\n }\n num_frames_++;\n for (size_t i = 0; i < images.size(); i++) {\n if (i < parameters_.nCameraSystem.numCameras()){\n \/\/printf(\"add image: %i\\n\", i);\n okvis_estimator_->addImage(t_image, i, images[i]);\n }\n }\n }\n }\n\n void OkvisSLAMSystem::PushFrame(const cv::Mat image, const double ×tamp) {\n if (okvis_estimator_ == nullptr)\n return;\n okvis::Time t_image(timestamp \/ 1e9);\n if (start_ == okvis::Time(0.0)) {\n start_ = t_image;\n }\n\n if (t_image - start_ > deltaT_) {\n std::vector<cv::Mat> images;\n images.push_back(image);\n if(mMapFrameAvailableHandler.size()>0){\n frame_queue_.enqueue({ images,t_image,num_frames_ });\n }\n num_frames_++;\n okvis_estimator_->addImage(t_image, 0, image);\n }\n }*\/\n\n void OkvisSLAMSystem::PushFrame(MultiCameraFrame::Ptr frame){\n if (okvis_estimator_ == nullptr)\n return;\n okvis::Time t_image(frame->timestamp_ \/ 1e9);\n if (start_ == okvis::Time(0.0)) {\n start_ = t_image;\n }\n\n if (t_image - start_ > deltaT_) {\n if(mMapFrameAvailableHandler.size()>0){\n frame_queue_.enqueue({ frame});\n }\n num_frames_++;\n for (size_t i = 0; i < frame->images_.size(); i++) {\n if (i < parameters_.nCameraSystem.numCameras()){\n \/\/printf(\"add image: %i\\n\", i);\n okvis_estimator_->addImage(t_image, i, frame->images_[i]);\n }\n }\n } \n }\n\n void OkvisSLAMSystem::PushIMU(const std::vector<ImuPair>& imu) {\n if (okvis_estimator_ == nullptr) return;\n for (size_t i = 0; i < imu.size(); i++) {\n PushIMU(imu[i]);\n }\n }\n\n void OkvisSLAMSystem::PushIMU(const ImuPair& imu) {\n if (okvis_estimator_ == nullptr) return;\n t_imu_ = okvis::Time(imu.timestamp \/ 1e9);\n if (t_imu_ - start_ + okvis::Duration(1.0) > deltaT_) {\n \/\/std::cout << imu.timestamp \/ 1e9 << \" , \" << imu.accel.transpose() << \" , \" << imu.gyro.transpose() << std::endl;\n okvis_estimator_->addImuMeasurement(t_imu_, imu.accel, imu.gyro);\n }\n }\n\n void OkvisSLAMSystem::PushIMU(double timestamp, const Eigen::Vector3d& accel, const Eigen::Vector3d gyro) {\n if (okvis_estimator_ == nullptr) return;\n t_imu_ = okvis::Time(timestamp \/ 1e9);\n if (t_imu_ - start_ + okvis::Duration(1.0) > deltaT_) {\n okvis_estimator_->addImuMeasurement(t_imu_, accel, gyro);\n }\n }\n\n void OkvisSLAMSystem::createNewMap() {\n sparse_map_vector.push_back(std::make_shared<SparseMap<DBoW2::FBRISK::TDescriptor, DBoW2::FBRISK>>());\n \/\/ set it to the latest one\n active_map_index = static_cast<int>(sparse_map_vector.size())-1;\n }\n\n void OkvisSLAMSystem::display() {\n if (okvis_estimator_ == nullptr)\n return;\n okvis_estimator_->display();\n }\n\n void OkvisSLAMSystem::ShutDown()\n {\n frame_queue_.clear();\n frame_data_queue_.clear();\n kill=true;\n frameConsumerThread_.join();\n okvis_estimator_.reset();\n }\n\n OkvisSLAMSystem::~OkvisSLAMSystem() {\n frame_queue_.clear();\n frame_data_queue_.clear();\n kill=true;\n }\n\n void OkvisSLAMSystem::RequestStop()\n {\n okvis_estimator_ = nullptr;\n }\n\n bool OkvisSLAMSystem::IsRunning()\n {\n return okvis_estimator_ == nullptr;\n }\n\n void OkvisSLAMSystem::getTrajectory(std::vector<Eigen::Matrix4d>& trajOut){\n getActiveMap()->getTrajectory(trajOut);\n }\n\n std::shared_ptr<SparseMap<DBoW2::FBRISK::TDescriptor, DBoW2::FBRISK>> OkvisSLAMSystem:: getActiveMap() {\n if (0 <= active_map_index && active_map_index < sparse_map_vector.size()) {\n return sparse_map_vector[active_map_index];\n } else {\n return nullptr;\n }\n }\n \n\n} \/\/ark<commit_msg>Refactor remove latency<commit_after>#include \"stdafx.h\"\n#include \"OkvisSLAMSystem.h\"\n\nnamespace ark {\n\n OkvisSLAMSystem::OkvisSLAMSystem(const std::string & strVocFile, const std::string & strSettingsFile) :\n start_(0.0), t_imu_(0.0), deltaT_(1.0), num_frames_(0), kill(false), \n sparse_map_vector(), active_map_index(-1), new_map_checker(false){\n\n okvis::VioParametersReader vio_parameters_reader;\n try {\n vio_parameters_reader.readConfigFile(strSettingsFile);\n }\n catch (okvis::VioParametersReader::Exception ex) {\n std::cerr << ex.what() << \"\\n\";\n return;\n }\n\n \/\/okvis::VioParameters parameters;\n vio_parameters_reader.getParameters(parameters_);\n\n createNewMap();\n getActiveMap()->setEnableLoopClosure(parameters_.loopClosureParameters.enabled,strVocFile,true, new brisk::BruteForceMatcher());\n\n \/\/initialize Visual odometry\n okvis_estimator_ = std::make_shared<okvis::ThreadedKFVio>(parameters_);\n okvis_estimator_->setBlocking(true);\n\n \/\/Okvis's outframe is our inframe\n auto frame_callback = [this](const okvis::Time& timestamp, okvis::OutFrameData::Ptr frame_data) {\n frame_data_queue_.enqueue({ frame_data,timestamp });\n };\n\n okvis_estimator_->setFrameCallback(frame_callback);\n\n \/\/at thread to pull from queue and call our own callbacks\n frameConsumerThread_ = std::thread(&OkvisSLAMSystem::FrameConsumerLoop, this);\n\n frame_data_queue_.clear();\n frame_queue_.clear();\n std::cout << \"SLAM Initialized\\n\";\n }\n\n void OkvisSLAMSystem::Start() {\n \/\/Do nothing, starts automatically\n }\n\n void OkvisSLAMSystem::FrameConsumerLoop() {\n while (!kill) {\n \n \/\/Get processed frame data from OKVIS\n StampedFrameData frame_data;\n while (!frame_data_queue_.try_dequeue(&frame_data)) {\n if (okvis_estimator_->isReset() && !new_map_checker) {\n cout<<\"Created new map\"<<endl;\n new_map_checker = true;\n createNewMap();\n } else if (!okvis_estimator_->isReset() && new_map_checker) {\n frame_queue_.clear();\n new_map_checker = false;\n }\n if(kill)\n return;\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n }\n \/\/Get the corresponding frame from queue\n WrappedMultiCameraFrame wrapped_frame;\n bool frame_found = false;\n do {\n if (!(frame_found = frame_queue_.try_dequeue(&wrapped_frame))) {\n break;\n } \n } while (okvis::Time(wrapped_frame.frame->timestamp_) < frame_data.timestamp);\n if (!frame_found){\n std::cout << \"ERROR, FRAME NOT FOUND, THIS SHOULDN'T HAPPEN\\n\";\n continue;\n }\n\n \/\/construct output frame\n MultiCameraFrame::Ptr out_frame = wrapped_frame.frame;\n out_frame->frameId_ = frame_data.data->id;\n out_frame->T_KS_ = frame_data.data->T_KS.T();\n out_frame->keyframeId_ = frame_data.data->keyframe_id;\n\n \/\/add sensor transforms\n \/\/Note: this could potentially just be done once for the system\n \/\/Including here for now in case we switch to optimized results\n for (size_t i = 0; i < wrapped_frame.frame->images_.size(); i++) {\n okvis::kinematics::Transformation T_SC;\n if (i < parameters_.nCameraSystem.numCameras()) {\n T_SC = (*parameters_.nCameraSystem.T_SC(i));\n }\n else if (i - parameters_.nCameraSystem.numCameras() < parameters_.secondaryCameraSystem.numCameras()) {\n T_SC = (*parameters_.secondaryCameraSystem.T_SC(i - parameters_.nCameraSystem.numCameras()));\n } else {\n \/\/no relationship data to imu\n \/\/TODO: throw errror\n T_SC = okvis::kinematics::Transformation::Identity();\n }\n out_frame->T_SC_.push_back(T_SC.T());\n }\n\n \/\/check if keyframe\n if(frame_data.data->is_keyframe){\n if(out_frame->keyframeId_!=out_frame->frameId_){\n std::cout << \"ERROR, KEYFRAME ID INCORRECT, THIS SHOULDN'T HAPPEN\\n\";\n continue;\n }\n MapKeyFrame::Ptr keyframe = MapKeyFrame::Ptr(new MapKeyFrame);\n keyframe->frameId_=out_frame->frameId_;\n keyframe->T_WS_ = frame_data.data->T_WS.T();\n keyframe->T_SC_ = out_frame->T_SC_;\n keyframe->timestamp_ = out_frame->timestamp_;\n \/\/copy keypoints and descriptors to output\n keyframe->keypoints_.resize(frame_data.data->keypoints.size());\n keyframe->keypoints3dh_C.resize(frame_data.data->keypoints.size());\n keyframe->descriptors_.resize(frame_data.data->descriptors.size());\n for(size_t cam_idx=0 ; cam_idx<frame_data.data->keypoints.size() ; cam_idx++){\n keyframe->keypoints_[cam_idx].resize(frame_data.data->keypoints[cam_idx].size()); \n\n keyframe->keypoints3dh_C[cam_idx].resize(frame_data.data->keypoints[cam_idx].size());\n \/\/get transform of the camera\n for(int i=0; i<frame_data.data->keypoints[cam_idx].size(); i++){\n \/\/copy keypoint\n keyframe->keypoints_[cam_idx][i] = frame_data.data->keypoints[cam_idx][i];\n \/\/get estimated 3d position of keypoint in current camera frame\n cv::Vec3f pt3d = out_frame->images_[2].at<cv::Vec3f>(\n std::round(keyframe->keypoints_[cam_idx][i].pt.y),\n std::round(keyframe->keypoints_[cam_idx][i].pt.x));\n if(pt3d[2] >0)\n keyframe->keypoints3dh_C[cam_idx][i] = Eigen::Vector4d(pt3d[0],pt3d[1],pt3d[2],1);\n else\n keyframe->keypoints3dh_C[cam_idx][i] = Eigen::Vector4d(0,0,0,0);\n }\n keyframe->descriptors_[cam_idx]=frame_data.data->descriptors[cam_idx];\n }\n\n \/\/ if(sparseMap_->detectLoopClosure(keyframe))\n \/\/ {\n \/\/ cout<<\"Found loop with my function\"<<endl;\n \/\/ }\n \/\/ push to map\n for (int i = 0; i < sparse_map_vector.size(); i++) {\n const auto sparseMap = sparse_map_vector[i];\n if (sparseMap->detectLoopClosure(keyframe)) {\n active_map_index = i;\n }\n }\n\n if(getActiveMap()->addKeyframe(keyframe)){ \/\/add keyframe returns true if a loop closure was detected\n for (MapLoopClosureDetectedHandler::const_iterator callback_iter = mMapLoopClosureHandler.begin();\n callback_iter != mMapLoopClosureHandler.end(); ++callback_iter) {\n const MapLoopClosureDetectedHandler::value_type& pair = *callback_iter;\n pair.second();\n }\n }\n }\n\n out_frame->keyframe_ = getActiveMap()->getKeyframe(out_frame->keyframeId_);\n\n \/\/Notify callbacks\n if(frame_data.data->is_keyframe){\n for (MapKeyFrameAvailableHandler::const_iterator callback_iter = mMapKeyFrameAvailableHandler.begin();\n callback_iter != mMapKeyFrameAvailableHandler.end(); ++callback_iter) {\n const MapKeyFrameAvailableHandler::value_type& pair = *callback_iter;\n pair.second(out_frame);\n }\n }\n\n for (MapFrameAvailableHandler::const_iterator callback_iter = mMapFrameAvailableHandler.begin();\n callback_iter != mMapFrameAvailableHandler.end(); ++callback_iter) {\n const MapFrameAvailableHandler::value_type& pair = *callback_iter;\n pair.second(out_frame);\n }\n }\n }\n\n \/*void OkvisSLAMSystem::PushFrame(const std::vector<cv::Mat>& images, const double ×tamp) {\n if (okvis_estimator_ == nullptr)\n return;\n okvis::Time t_image(timestamp \/ 1e9);\n if (start_ == okvis::Time(0.0)) {\n start_ = t_image;\n }\n\n if (t_image - start_ > deltaT_) {\n if(mMapFrameAvailableHandler.size()>0){\n frame_queue_.enqueue({ images,t_image,num_frames_ });\n }\n num_frames_++;\n for (size_t i = 0; i < images.size(); i++) {\n if (i < parameters_.nCameraSystem.numCameras()){\n \/\/printf(\"add image: %i\\n\", i);\n okvis_estimator_->addImage(t_image, i, images[i]);\n }\n }\n }\n }\n\n void OkvisSLAMSystem::PushFrame(const cv::Mat image, const double ×tamp) {\n if (okvis_estimator_ == nullptr)\n return;\n okvis::Time t_image(timestamp \/ 1e9);\n if (start_ == okvis::Time(0.0)) {\n start_ = t_image;\n }\n\n if (t_image - start_ > deltaT_) {\n std::vector<cv::Mat> images;\n images.push_back(image);\n if(mMapFrameAvailableHandler.size()>0){\n frame_queue_.enqueue({ images,t_image,num_frames_ });\n }\n num_frames_++;\n okvis_estimator_->addImage(t_image, 0, image);\n }\n }*\/\n\n void OkvisSLAMSystem::PushFrame(MultiCameraFrame::Ptr frame){\n if (okvis_estimator_ == nullptr)\n return;\n okvis::Time t_image(frame->timestamp_ \/ 1e9);\n if (start_ == okvis::Time(0.0)) {\n start_ = t_image;\n }\n\n if (t_image - start_ > deltaT_) {\n if(mMapFrameAvailableHandler.size()>0){\n frame_queue_.enqueue({ frame});\n }\n num_frames_++;\n for (size_t i = 0; i < frame->images_.size(); i++) {\n if (i < parameters_.nCameraSystem.numCameras()){\n \/\/printf(\"add image: %i\\n\", i);\n okvis_estimator_->addImage(t_image, i, frame->images_[i]);\n }\n }\n } \n }\n\n void OkvisSLAMSystem::PushIMU(const std::vector<ImuPair>& imu) {\n if (okvis_estimator_ == nullptr) return;\n for (size_t i = 0; i < imu.size(); i++) {\n PushIMU(imu[i]);\n }\n }\n\n void OkvisSLAMSystem::PushIMU(const ImuPair& imu) {\n if (okvis_estimator_ == nullptr) return;\n t_imu_ = okvis::Time(imu.timestamp \/ 1e9);\n if (t_imu_ - start_ + okvis::Duration(1.0) > deltaT_) {\n \/\/std::cout << imu.timestamp \/ 1e9 << \" , \" << imu.accel.transpose() << \" , \" << imu.gyro.transpose() << std::endl;\n okvis_estimator_->addImuMeasurement(t_imu_, imu.accel, imu.gyro);\n }\n }\n\n void OkvisSLAMSystem::PushIMU(double timestamp, const Eigen::Vector3d& accel, const Eigen::Vector3d gyro) {\n if (okvis_estimator_ == nullptr) return;\n t_imu_ = okvis::Time(timestamp \/ 1e9);\n if (t_imu_ - start_ + okvis::Duration(1.0) > deltaT_) {\n okvis_estimator_->addImuMeasurement(t_imu_, accel, gyro);\n }\n }\n\n void OkvisSLAMSystem::createNewMap() {\n sparse_map_vector.push_back(std::make_shared<SparseMap<DBoW2::FBRISK::TDescriptor, DBoW2::FBRISK>>());\n \/\/ set it to the latest one\n active_map_index = static_cast<int>(sparse_map_vector.size())-1;\n }\n\n void OkvisSLAMSystem::display() {\n if (okvis_estimator_ == nullptr)\n return;\n okvis_estimator_->display();\n }\n\n void OkvisSLAMSystem::ShutDown()\n {\n frame_queue_.clear();\n frame_data_queue_.clear();\n kill=true;\n frameConsumerThread_.join();\n okvis_estimator_.reset();\n }\n\n OkvisSLAMSystem::~OkvisSLAMSystem() {\n frame_queue_.clear();\n frame_data_queue_.clear();\n kill=true;\n }\n\n void OkvisSLAMSystem::RequestStop()\n {\n okvis_estimator_ = nullptr;\n }\n\n bool OkvisSLAMSystem::IsRunning()\n {\n return okvis_estimator_ == nullptr;\n }\n\n void OkvisSLAMSystem::getTrajectory(std::vector<Eigen::Matrix4d>& trajOut){\n getActiveMap()->getTrajectory(trajOut);\n }\n\n std::shared_ptr<SparseMap<DBoW2::FBRISK::TDescriptor, DBoW2::FBRISK>> OkvisSLAMSystem:: getActiveMap() {\n if (0 <= active_map_index && active_map_index < sparse_map_vector.size()) {\n return sparse_map_vector[active_map_index];\n } else {\n std::cout << \"Null map returned \\n\";\n return nullptr;\n }\n }\n \n\n} \/\/ark<|endoftext|>"} {"text":"<commit_before>#include \"options.h\"\n#include <string>\n#include <vector>\n#include <map>\n\/**\n * @brief Stores a vector of parameters comming from command line\n * @param args vector of strings\n *\/\nvoid Options::registerArgs(std::vector<std::string> args){\n std::map<std::string, std::string> parts;\n for(std::vector<Param>::iterator param_ite = this->internal_params.begin(); param_ite != this->internal_params.end(); param_ite++) {\n for (std::vector<std::string>::iterator args_ite = args.begin(); args_ite != args.end(); args_ite++) {\n parts = this->getParts( (*args_ite));\n if (this->isCommand(parts.begin()->first)) {\n this->commands[parts.begin()->first] = true; \/\/parts.begin()->second;\n } else {\n \/\/ The Param ignores invalid assignments\n (*param_ite).setValue(parts.begin()->first, parts.begin()->second);\n }\n }\n }\n\n}\n\nbool Options::isCommand(std::string value) {\n bool is_command = false;\n if (value.find(\"help\") != std::string::npos) {\n is_command = true;\n }\n return is_command;\n}\n\nvoid Options::runCommands() {\n std::cout << \"Options::runCommands()\" << ENDL;\n for(std::map<std::string, bool>::iterator command_ite = this->commands.begin(); command_ite != this->commands.end(); command_ite++) {\n std::cout << \"Options::runCommands() -> Running command \" << (*command_ite).first << ENDL;\n if ((*command_ite).first == \"help\") {\n this->cmdHelp();\n }\n }\n\n \/\/ this->printVector(command);\n}\n\nbool Options::hasCommands() {\n return this->commands.size() > 0;\n}\n\nvoid Options::cmdHelp() {\n std::cout << \"[ This is the cmd_help ]\" << ENDL;\n for(std::vector<Param>::iterator param_ite = this->internal_params.begin(); param_ite != this->internal_params.end(); param_ite++) {\n std::cout << \"-\" << (*param_ite).getShortForm() << ENDL;\n std::cout << \" --\" << (*param_ite).getLongForm() << \"\\t\\t\" << (*param_ite).getDescription() << ENDL;\n }\n}\n\n\/**\n * @brief Splits cli arguments\n * @details from \"--name=value\" to [name] = value\n * or \"--something\" to [something] = \"\"\n *\n * @param value A cli argument in the form \"-s\", \"--long\" or \"--short=val\"\n * @return [description]\n *\/\nstd::map<std::string, std::string> Options::getParts(std::string value) {\n std::map <std::string, std::string> out;\n \/\/ Remove leading dashes\n do {\n value = value.substr(1);\n } while ( value.substr(0,1) == \"-\");\n\n \/\/ Split by =\n int pos_eq = value.find('=');\n if (pos_eq != std::string::npos) {\n std::string name = value.substr(0, pos_eq);\n value = value.substr(pos_eq + 1);\n out[name] = value;\n } else {\n \/\/ Or just store an empty right hand value\n out[value] = \"\";\n }\n\n return out;\n}\n\nvoid Options::addParam(Param orig){\n this->internal_params.push_back(orig);\n}\n\nvoid Options::printVector(std::vector<std::string> original) {\n for (std::vector<std::string>::iterator i = original.begin(); i != original.end(); i++) {\n std::cout << *i << ENDL;\n }\n}\nvoid Options::printVector(std::vector<Param> original) {\n for (std::vector<Param>::iterator i = original.begin(); i != original.end(); i++) {\n std::cout << (*i).getLongForm() << \" = \" << (*i).getValue() << ENDL;\n }\n}\n\nvoid Options::printVector(std::map<std::string, std::string> original) {\n for (std::map<std::string, std::string>::iterator i = original.begin(); i != original.end(); i++) {\n std::cout << (*i).first << \" = \" << (*i).second << ENDL;\n }\n}\n\nbool Options::areParamsOk() {\n \/\/ 1. Check that there are params to check\n \/\/ 2.0 Check if any of the params has a dependency\n \/\/ 2.1 Check if they fulfill the dependency\n\n std::cout << \"internal_params:\" << ENDL;\n this->printVector(this->internal_params);\n return true;\n}<commit_msg>Refactor: Remove debug and write to cerr if command is invalid<commit_after>#include \"options.h\"\n#include <string>\n#include <vector>\n#include <map>\n\/**\n * @brief Stores a vector of parameters comming from command line\n * @param args vector of strings\n *\/\nvoid Options::registerArgs(std::vector<std::string> args){\n std::map<std::string, std::string> parts;\n for(std::vector<Param>::iterator param_ite = this->internal_params.begin(); param_ite != this->internal_params.end(); param_ite++) {\n for (std::vector<std::string>::iterator args_ite = args.begin(); args_ite != args.end(); args_ite++) {\n parts = this->getParts( (*args_ite));\n if (this->isCommand(parts.begin()->first)) {\n this->commands[parts.begin()->first] = true; \/\/parts.begin()->second;\n } else {\n \/\/ The Param ignores invalid assignments\n (*param_ite).setValue(parts.begin()->first, parts.begin()->second);\n }\n }\n }\n\n}\n\nbool Options::isCommand(std::string value) {\n bool is_command = false;\n if (value.find(\"help\") != std::string::npos) {\n is_command = true;\n }\n return is_command;\n}\n\nvoid Options::runCommands() {\n for(std::map<std::string, bool>::iterator command_ite = this->commands.begin(); command_ite != this->commands.end(); command_ite++) {\n if ((*command_ite).first == \"help\") {\n this->cmdHelp();\n } else {\n std::cerr << \"This command is invalid: \" << (*command_ite).first << ENDL;\n }\n }\n\n \/\/ this->printVector(command);\n}\n\nbool Options::hasCommands() {\n return this->commands.size() > 0;\n}\n\nvoid Options::cmdHelp() {\n std::cout << \"[ This is the cmd_help ]\" << ENDL;\n for(std::vector<Param>::iterator param_ite = this->internal_params.begin(); param_ite != this->internal_params.end(); param_ite++) {\n std::cout << \"-\" << (*param_ite).getShortForm() << ENDL;\n std::cout << \" --\" << (*param_ite).getLongForm() << \"\\t\\t\" << (*param_ite).getDescription() << ENDL;\n }\n}\n\n\/**\n * @brief Splits cli arguments\n * @details from \"--name=value\" to [name] = value\n * or \"--something\" to [something] = \"\"\n *\n * @param value A cli argument in the form \"-s\", \"--long\" or \"--short=val\"\n * @return [description]\n *\/\nstd::map<std::string, std::string> Options::getParts(std::string value) {\n std::map <std::string, std::string> out;\n \/\/ Remove leading dashes\n do {\n value = value.substr(1);\n } while ( value.substr(0,1) == \"-\");\n\n \/\/ Split by =\n int pos_eq = value.find('=');\n if (pos_eq != std::string::npos) {\n std::string name = value.substr(0, pos_eq);\n value = value.substr(pos_eq + 1);\n out[name] = value;\n } else {\n \/\/ Or just store an empty right hand value\n out[value] = \"\";\n }\n\n return out;\n}\n\nvoid Options::addParam(Param orig){\n this->internal_params.push_back(orig);\n}\n\nvoid Options::printVector(std::vector<std::string> original) {\n for (std::vector<std::string>::iterator i = original.begin(); i != original.end(); i++) {\n std::cout << *i << ENDL;\n }\n}\nvoid Options::printVector(std::vector<Param> original) {\n for (std::vector<Param>::iterator i = original.begin(); i != original.end(); i++) {\n std::cout << (*i).getLongForm() << \" = \" << (*i).getValue() << ENDL;\n }\n}\n\nvoid Options::printVector(std::map<std::string, std::string> original) {\n for (std::map<std::string, std::string>::iterator i = original.begin(); i != original.end(); i++) {\n std::cout << (*i).first << \" = \" << (*i).second << ENDL;\n }\n}\n\nbool Options::areParamsOk() {\n \/\/ 1. Check that there are params to check\n \/\/ 2.0 Check if any of the params has a dependency\n \/\/ 2.1 Check if they fulfill the dependency\n\n std::cout << \"internal_params:\" << ENDL;\n this->printVector(this->internal_params);\n return true;\n}<|endoftext|>"} {"text":"<commit_before>\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n \r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\r\n\/\/! File : ImageVis3D_Settings.cpp\r\n\/\/! Author : Jens Krueger\r\n\/\/! SCI Institute\r\n\/\/! University of Utah\r\n\/\/! Date : September 2008\r\n\/\/\r\n\/\/! Copyright (C) 2008 SCI Institute\r\n\r\n#include \"ImageVis3D.h\"\r\n#include <Basics\/SysTools.h>\r\n#include <QtCore\/QSettings>\r\n#include <QtGui\/QMessageBox>\r\n\r\nusing namespace std;\r\n\r\nvoid MainWindow::CheckSettings() {\r\n QSettings settings;\r\n\r\n \/\/ if memory isn't set this must be the first time we run this app\r\n if (UINT64_INVALID == settings.value(\"Memory\/MaxGPUMem\", UINT64_INVALID).toLongLong()) {\r\n do {\r\n QMessageBox::information(this, \"Initial Setup\", \"As this is the first time you start ImageVis3D on this system you need to check the settings. In particular the memory usage settings need to be set according to the actual hardware configuration of thy machine. Note that these settings can also be changed later in the settings screen.\");\r\n } while(!ShowSettings(SettingsDlg::MEM_TAB));\r\n } else ApplySettings();\r\n}\r\n\r\nbool MainWindow::ShowSettings(SettingsDlg::TabID eTabID) {\r\n QSettings settings;\r\n SettingsDlg settingsDlg(m_MasterController, eTabID, this);\r\n\r\n \/\/ load settings\r\n UINT64 iMaxGPU = settings.value(\"Memory\/MaxGPUMem\", UINT64_INVALID).toLongLong();\r\n\r\n \/\/ if memory is set load other values (otherwise the dialog box will initialize with defaults\r\n if (iMaxGPU != UINT64_INVALID) { \r\n \/\/ load other settings here\r\n UINT64 iMaxCPU = settings.value(\"Memory\/MaxCPUMem\", UINT64_INVALID).toLongLong(); \r\n\r\n \/\/ hand data to form\r\n settingsDlg.Data2Form(iMaxCPU, iMaxGPU);\r\n }\r\n\r\n if (settingsDlg.exec() == QDialog::Accepted) {\r\n\r\n \/\/ save settings\r\n settings.beginGroup(\"Memory\");\r\n settings.setValue(\"MaxGPUMem\", settingsDlg.GetGPUMem());\r\n settings.setValue(\"MaxCPUMem\", settingsDlg.GetCPUMem());\r\n settings.endGroup();\r\n\r\n \/\/ TODO save other settings here\r\n\r\n\r\n ApplySettings();\r\n return true;\r\n } else return false;\r\n\r\n}\r\n\r\n\r\nvoid MainWindow::ApplySettings() {\r\n QSettings settings;\r\n\r\n settings.beginGroup(\"Memory\");\r\n UINT64 iMaxCPU = settings.value(\"MaxCPUMem\", UINT64_INVALID).toLongLong();\r\n UINT64 iMaxGPU = settings.value(\"MaxGPUMem\", UINT64_INVALID).toLongLong();\r\n settings.endGroup();\r\n\r\n m_MasterController.SysInfo()->SetMaxUsableCPUMem(iMaxCPU);\r\n m_MasterController.SysInfo()->SetMaxUsableGPUMem(iMaxGPU);\r\n m_MasterController.MemMan()->MemSizesChanged();\r\n\r\n}<commit_msg><commit_after>\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n \r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\r\n\/\/! File : ImageVis3D_Settings.cpp\r\n\/\/! Author : Jens Krueger\r\n\/\/! SCI Institute\r\n\/\/! University of Utah\r\n\/\/! Date : September 2008\r\n\/\/\r\n\/\/! Copyright (C) 2008 SCI Institute\r\n\r\n#include \"ImageVis3D.h\"\r\n#include <Basics\/SysTools.h>\r\n#include <QtCore\/QSettings>\r\n#include <QtGui\/QMessageBox>\r\n\r\nusing namespace std;\r\n\r\nvoid MainWindow::CheckSettings() {\r\n QSettings settings;\r\n\r\n \/\/ if memory isn't set this must be the first time we run this app\r\n if (UINT64_INVALID == settings.value(\"Memory\/MaxGPUMem\", UINT64_INVALID).toULongLong()) {\r\n do {\r\n QMessageBox::information(this, \"Initial Setup\", \"As this is the first time you start ImageVis3D on this system you need to check the settings. In particular the memory usage settings need to be set according to the actual hardware configuration of thy machine. Note that these settings can also be changed later in the settings screen.\");\r\n } while(!ShowSettings(SettingsDlg::MEM_TAB));\r\n } else ApplySettings();\r\n}\r\n\r\nbool MainWindow::ShowSettings(SettingsDlg::TabID eTabID) {\r\n QSettings settings;\r\n SettingsDlg settingsDlg(m_MasterController, eTabID, this);\r\n\r\n \/\/ load settings\r\n UINT64 iMaxGPU = settings.value(\"Memory\/MaxGPUMem\", UINT64_INVALID).toULongLong();\r\n\r\n \/\/ if memory is set load other values (otherwise the dialog box will initialize with defaults\r\n if (iMaxGPU != UINT64_INVALID) { \r\n \/\/ load other settings here\r\n UINT64 iMaxCPU = settings.value(\"Memory\/MaxCPUMem\", UINT64_INVALID).toULongLong(); \r\n\r\n \/\/ hand data to form\r\n settingsDlg.Data2Form(iMaxCPU, iMaxGPU);\r\n }\r\n\r\n if (settingsDlg.exec() == QDialog::Accepted) {\r\n\r\n \/\/ save settings\r\n settings.beginGroup(\"Memory\");\r\n settings.setValue(\"MaxGPUMem\", settingsDlg.GetGPUMem());\r\n settings.setValue(\"MaxCPUMem\", settingsDlg.GetCPUMem());\r\n settings.endGroup();\r\n\r\n \/\/ TODO save other settings here\r\n\r\n\r\n ApplySettings();\r\n return true;\r\n } else return false;\r\n\r\n}\r\n\r\n\r\nvoid MainWindow::ApplySettings() {\r\n QSettings settings;\r\n\r\n settings.beginGroup(\"Memory\");\r\n UINT64 iMaxCPU = settings.value(\"MaxCPUMem\", UINT64_INVALID).toULongLong();\r\n UINT64 iMaxGPU = settings.value(\"MaxGPUMem\", UINT64_INVALID).toULongLong();\r\n settings.endGroup();\r\n\r\n m_MasterController.SysInfo()->SetMaxUsableCPUMem(iMaxCPU);\r\n m_MasterController.SysInfo()->SetMaxUsableGPUMem(iMaxGPU);\r\n m_MasterController.MemMan()->MemSizesChanged();\r\n\r\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 Stanford University\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <errno.h>\n#include <fcntl.h>\n\n#include <pwd.h>\n\n#include <unistd.h>\n#include <sys\/param.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <dirent.h>\n\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <vector>\n#include <string>\n\n#ifdef __FreeBSD__\n#include <uuid.h>\n#endif \/* __FreeBSD__ *\/\n\n#if defined(__APPLE__) || defined(__linux__)\n#include <uuid\/uuid.h>\n#endif\n\n#include <openssl\/sha.h>\n\n#ifdef OPENSSL_NO_SHA256\n#error \"SHA256 not supported!\"\n#endif\n\n#include \"util.h\"\n#include \"stream.h\"\n\nusing namespace std;\n\n\/*\n * Check if a file exists.\n *\/\nbool\nUtil_FileExists(const string &path)\n{\n struct stat sb;\n\n if (stat(path.c_str(), &sb) == 0)\n\treturn true;\n\n return false;\n}\n\n\/*\n * Check if a file is a directory.\n *\/\nbool\nUtil_IsDirectory(const string &path)\n{\n struct stat sb;\n\n if (stat(path.c_str(), &sb) < 0) {\n\tperror(\"stat file does not exist\");\n\treturn false;\n }\n\n if (sb.st_mode & S_IFDIR)\n\treturn true;\n else\n\treturn false;\n}\n\n\/*\n * Get the file size.\n *\/\nsize_t Util_FileSize(const std::string &path)\n{\n struct stat sb;\n\n if (stat(path.c_str(), &sb) < 0) {\n\tperror(\"stat file does not exist\");\n\treturn -errno;\n }\n\n return sb.st_size;\n}\n\n\/*\n * Return the full path given a relative path.\n * XXX: According to FreeBSD man pages this may be broken on Solaris.\n *\/\nstring\nUtil_RealPath(const string &path)\n{\n char *tmp;\n string rval = \"\";\n\n tmp = realpath(path.c_str(), NULL);\n if (tmp) {\n rval = tmp;\n free(tmp);\n }\n\n return rval;\n}\n\n\/*\n * Read a file containing a text string into memory. There may not be any null \n * characters in the file.\n *\/\nchar *\nUtil_ReadFile(const string &path, size_t *flen)\n{\n FILE *f;\n char *buf;\n size_t len;\n\n f = fopen(path.c_str(), \"rb\");\n if (f == NULL) {\n\treturn NULL;\n }\n\n fseek(f, 0, SEEK_END);\n len = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = new char[len + 1];\n\n fread(buf, 1, len, f);\n fclose(f);\n\n \/\/ Just for simplicity we add a null charecter at the end to allow us to \n \/\/ read and write strings easily.\n buf[len] = '\\0';\n\n if (flen != NULL)\n\t*flen = len;\n\n return buf;\n}\n\n\/*\n * Write an in memory blob to a file.\n *\/\nbool\nUtil_WriteFile(const char *blob, size_t len, const string &path)\n{\n FILE *f;\n size_t bytesWritten;\n\n f = fopen(path.c_str(), \"w+\");\n if (f == NULL) {\n\treturn false;\n }\n\n bytesWritten = fwrite(blob, len, 1, f);\n fclose(f);\n\n return (bytesWritten == len);\n}\n\n#define COPYFILE_BUFSZ\t4096\n\n\/*\n * Copy a file.\n *\/\nint\nUtil_CopyFile(const string &origPath, const string &newPath)\n{\n int srcFd, dstFd;\n char buf[COPYFILE_BUFSZ];\n struct stat sb;\n int64_t bytesLeft;\n int64_t bytesRead, bytesWritten;\n\n srcFd = open(origPath.c_str(), O_RDONLY);\n if (srcFd < 0)\n\treturn -errno;\n\n dstFd = open(newPath.c_str(), O_WRONLY | O_CREAT,\n\t S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n if (dstFd < 0) {\n\tclose(srcFd);\n\treturn -errno;\n }\n\n if (fstat(srcFd, &sb) < 0) {\n\tclose(srcFd);\n\tunlink(newPath.c_str());\n\tclose(dstFd);\n\treturn -errno;\n }\n\n bytesLeft = sb.st_size;\n while(bytesLeft > 0) {\n\tbytesRead = read(srcFd, buf, MIN(bytesLeft, COPYFILE_BUFSZ));\n\tif (bytesRead < 0) {\n\t if (errno == EINTR)\n\t\tcontinue;\n\t goto error;\n\t}\n\nretryWrite:\n\tbytesWritten = write(dstFd, buf, bytesRead);\n\tif (bytesWritten < 0) {\n\t if (errno == EINTR)\n\t\tgoto retryWrite;\n\t goto error;\n\t}\n\n\t\/\/ XXX: Need to handle this case!\n\tassert(bytesRead == bytesWritten);\n\n\tbytesLeft -= bytesRead;\n }\n\n close(srcFd);\n close(dstFd);\n return sb.st_size;\n\nerror:\n close(srcFd);\n unlink(newPath.c_str());\n close(dstFd);\n return -errno;\n}\n\n\/*\n * Safely move a file possibly between file systems.\n *\/\nint\nUtil_MoveFile(const string &origPath, const string &newPath)\n{\n int status = 0;\n\n if (rename(origPath.c_str(), newPath.c_str()) < 0)\n\tstatus = -errno;\n\n \/\/ If the file is on seperate file systems copy it and delete the original.\n if (errno == EXDEV) {\n\tstatus = Util_CopyFile(origPath, newPath);\n\tif (status < 0)\n\t return status;\n\n\tif (unlink(origPath.c_str()) < 0) {\n\t status = -errno;\n\t assert(false);\n\t}\n }\n\n return status;\n}\n\n\/*\n * Compute SHA 256 hash for a string.\n *\/\nstring\nUtil_HashString(const string &str)\n{\n SHA256_CTX state;\n unsigned char hash[SHA256_DIGEST_LENGTH];\n stringstream rval;\n\n SHA256_Init(&state);\n SHA256_Update(&state, str.c_str(), str.size());\n SHA256_Final(hash, &state);\n\n \/\/ Convert into string.\n for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n\trval << hex << setw(2) << setfill('0') << (int)hash[i];\n }\n\n return rval.str();\n}\n\n#define HASHFILE_BUFSZ\t4096\n\n\/*\n * Compute SHA 256 hash for a file.\n *\/\nstring\nUtil_HashFile(const string &path)\n{\n int fd;\n char buf[COPYFILE_BUFSZ];\n struct stat sb;\n int64_t bytesLeft;\n int64_t bytesRead;\n SHA256_CTX state;\n unsigned char hash[SHA256_DIGEST_LENGTH];\n stringstream rval;\n\n SHA256_Init(&state);\n\n fd = open(path.c_str(), O_RDONLY);\n if (fd < 0) {\n\treturn \"\";\n }\n\n if (fstat(fd, &sb) < 0) {\n\tclose(fd);\n\treturn \"\";\n }\n\n bytesLeft = sb.st_size;\n while(bytesLeft > 0) {\n\tbytesRead = read(fd, buf, MIN(bytesLeft, COPYFILE_BUFSZ));\n\tif (bytesRead < 0) {\n\t if (errno == EINTR)\n\t\tcontinue;\n\t close(fd);\n\t return \"\";\n\t}\n\n\tSHA256_Update(&state, buf, bytesRead);\n\tbytesLeft -= bytesRead;\n }\n\n SHA256_Final(hash, &state);\n\n \/\/ Convert into string.\n for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n\trval << hex << setw(2) << setfill('0') << (int)hash[i];\n }\n\n close(fd);\n return rval.str();\n}\n\nvector<string>\nUtil_PathToVector(const string &path)\n{\n int pos = 0;\n vector<string> rval;\n\n if (path[0] == '\/')\n pos = 1;\n\n while (pos < path.length()) {\n int end = path.find('\/', pos);\n if (end == path.npos) {\n rval.push_back(path.substr(pos));\n break;\n }\n\n rval.push_back(path.substr(pos, end - 1));\n pos = end + 1;\n }\n\n return rval;\n}\n\nstring\nUtil_GetFullname()\n{\n struct passwd *pw = getpwuid(getuid());\n\n \/\/ XXX: Error handling\n assert(pw != NULL);\n\n if (pw->pw_gecos != NULL)\n return string(pw->pw_gecos);\n else\n return \"\";\n}\n\nint Util_SetBlocking(int fd, bool block) {\n int old_flags = fcntl(fd, F_GETFL);\n if (old_flags < 0) {\n perror(\"fcntl\");\n return old_flags;\n }\n\n if (block) {\n if (old_flags & O_NONBLOCK) {\n fcntl(fd, F_SETFL, (old_flags & ~O_NONBLOCK));\n }\n }\n else {\n if (!(old_flags & O_NONBLOCK)) {\n fcntl(fd, F_SETFL, old_flags | O_NONBLOCK);\n }\n }\n\n return 0;\n}\n\n\/*\n * Pretty print hex data\n *\/\nvoid\nUtil_PrintHex(const std::string &data, off_t off, size_t limit)\n{\n const int row_size = 16;\n bool stop = false;\n\n \/\/size_t num_printed = 0;\n for (size_t row = 0; !stop; row++) {\n printf(\"\\n\");\n\n printf(\"%08lx \", row * row_size);\n for (size_t col = 0; col < row_size; col++) { \n size_t ix = row * row_size + col;\n if ((limit != 0 && ix >= limit) || ix >= data.length()) {\n stop = true;\n break;\n }\n ix += off;\n\n printf(\"%02X \", (unsigned char)data[ix]);\n }\n printf(\" |\");\n\n for (size_t col = 0; col < row_size; col++) { \n size_t ix = row * row_size + col;\n if ((limit != 0 && ix >= limit) || ix >= data.length()) {\n stop = true;\n break;\n }\n ix += off;\n\n unsigned char c = (unsigned char)data[ix];\n if (c >= 0x20 && c < 0x7F)\n printf(\"%c\", c);\n else\n putchar('.');\n }\n printf(\"|\");\n }\n}\n\n\/*\n * Generate a UUID\n *\/\nstd::string\nUtil_NewUUID()\n{\n#ifdef __FreeBSD__\n uint32_t status;\n uuid_t id;\n char *uuidBuf;\n\n uuid_create(&id, &status);\n if (status != uuid_s_ok) {\n printf(\"Failed to construct UUID!\\n\");\n return \"\";\n }\n uuid_to_string(&id, &uuidBuf, &status);\n if (status != uuid_s_ok) {\n printf(\"Failed to print UUID!\\n\");\n return \"\";\n }\n std::string rval(uuidBuf);\n free(uuidBuf);\n return rval;\n#endif \/* __FreeBSD__ *\/\n\n#if defined(__APPLE__) || defined(__linux__)\n uuid_t id;\n uuid_generate(id);\n char id_buf[128];\n uuid_unparse(id, id_buf);\n \n std::string rval(id_buf);\n return rval;\n#endif \/* __APPLE__ || __linux__ *\/\n}\n\n\nbool\nUtil_IsPathRemote(const char *path) {\n char *cc = strchr(path, ':');\n if (cc == NULL) return false;\n if (cc == path) return false; \/\/ TODO how to handle these cases?\n if (cc == path+strlen(path)-1) return false;\n return true;\n}\n\n\/\/ XXX: Debug Only\n\n#define TESTFILE_SIZE (HASHFILE_BUFSZ * 3 \/ 2)\n\nint\nutil_selftest(void)\n{\n int status;\n char *buf = new char[TESTFILE_SIZE + 1];\n string origHash;\n string newHash;\n\n for (int i = 0; i < TESTFILE_SIZE; i++) {\n\tbuf[i] = '0' + (i % 10);\n }\n buf[TESTFILE_SIZE] = '\\0';\n origHash = Util_HashString(buf);\n\n Util_WriteFile(buf, TESTFILE_SIZE, \"test.orig\");\n\n status = Util_CopyFile(\"test.orig\", \"test.a\");\n if (status < 0) {\n\tprintf(\"Util_CopyFile: %s\\n\", strerror(-status));\n\tassert(false);\n }\n status = Util_CopyFile(\"test.orig\", \"test.b\");\n if (status < 0) {\n\tprintf(\"Util_CopyFile: %s\\n\", strerror(-status));\n\tassert(false);\n }\n status = Util_MoveFile(\"test.b\", \"test.c\");\n if (status < 0) {\n\tprintf(\"Util_CopyFile: %s\\n\", strerror(-status));\n\tassert(false);\n }\n char *fbuf = Util_ReadFile(\"test.c\", NULL);\n assert(fbuf);\n newHash = Util_HashString(fbuf);\n \/\/ XXX: Check that 'test.b' does not exist\n\n if (newHash != origHash) {\n\tprintf(\"Hash mismatch!\\n\");\n\tassert(false);\n }\n\n newHash = Util_HashFile(\"test.a\");\n\n if (newHash != origHash) {\n\tprintf(\"Hash mismatch!\\n\");\n\tassert(false);\n }\n\n vector<string> tv;\n tv = Util_PathToVector(\"\/abc\/def\");\n assert(tv.size() == 2);\n assert(tv[0] == \"abc\");\n assert(tv[1] == \"def\");\n\n\n \/\/ Tests for stream classes\n int test_fd = open(\"test.a\", O_RDWR | O_CREAT);\n write(test_fd, \"hello, world!\", 13);\n fsync(test_fd);\n bytestream *bs = new diskstream(test_fd, 1, 3);\n uint8_t b;\n bs->read(&b, 1);\n assert(b == 'e');\n delete bs;\n\n printf(\"Test Succeeded!\\n\");\n return 0;\n}\n\n<commit_msg>Performance tuning, reduced the number of reads by a couple orders of magnitude.<commit_after>\/*\n * Copyright (c) 2012 Stanford University\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <errno.h>\n#include <fcntl.h>\n\n#include <pwd.h>\n\n#include <unistd.h>\n#include <sys\/param.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <dirent.h>\n\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <vector>\n#include <string>\n\n#ifdef __FreeBSD__\n#include <uuid.h>\n#endif \/* __FreeBSD__ *\/\n\n#if defined(__APPLE__) || defined(__linux__)\n#include <uuid\/uuid.h>\n#endif\n\n#include <openssl\/sha.h>\n\n#ifdef OPENSSL_NO_SHA256\n#error \"SHA256 not supported!\"\n#endif\n\n#include \"util.h\"\n#include \"stream.h\"\n\nusing namespace std;\n\n\/*\n * Check if a file exists.\n *\/\nbool\nUtil_FileExists(const string &path)\n{\n struct stat sb;\n\n if (stat(path.c_str(), &sb) == 0)\n\treturn true;\n\n return false;\n}\n\n\/*\n * Check if a file is a directory.\n *\/\nbool\nUtil_IsDirectory(const string &path)\n{\n struct stat sb;\n\n if (stat(path.c_str(), &sb) < 0) {\n\tperror(\"stat file does not exist\");\n\treturn false;\n }\n\n if (sb.st_mode & S_IFDIR)\n\treturn true;\n else\n\treturn false;\n}\n\n\/*\n * Get the file size.\n *\/\nsize_t Util_FileSize(const std::string &path)\n{\n struct stat sb;\n\n if (stat(path.c_str(), &sb) < 0) {\n\tperror(\"stat file does not exist\");\n\treturn -errno;\n }\n\n return sb.st_size;\n}\n\n\/*\n * Return the full path given a relative path.\n * XXX: According to FreeBSD man pages this may be broken on Solaris.\n *\/\nstring\nUtil_RealPath(const string &path)\n{\n char *tmp;\n string rval = \"\";\n\n tmp = realpath(path.c_str(), NULL);\n if (tmp) {\n rval = tmp;\n free(tmp);\n }\n\n return rval;\n}\n\n\/*\n * Read a file containing a text string into memory. There may not be any null \n * characters in the file.\n *\/\nchar *\nUtil_ReadFile(const string &path, size_t *flen)\n{\n FILE *f;\n char *buf;\n size_t len;\n\n f = fopen(path.c_str(), \"rb\");\n if (f == NULL) {\n\treturn NULL;\n }\n\n fseek(f, 0, SEEK_END);\n len = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = new char[len + 1];\n\n fread(buf, 1, len, f);\n fclose(f);\n\n \/\/ Just for simplicity we add a null charecter at the end to allow us to \n \/\/ read and write strings easily.\n buf[len] = '\\0';\n\n if (flen != NULL)\n\t*flen = len;\n\n return buf;\n}\n\n\/*\n * Write an in memory blob to a file.\n *\/\nbool\nUtil_WriteFile(const char *blob, size_t len, const string &path)\n{\n FILE *f;\n size_t bytesWritten;\n\n f = fopen(path.c_str(), \"w+\");\n if (f == NULL) {\n\treturn false;\n }\n\n bytesWritten = fwrite(blob, len, 1, f);\n fclose(f);\n\n return (bytesWritten == len);\n}\n\n#define COPYFILE_BUFSZ\t(256 * 1024)\n\n\/*\n * Copy a file.\n *\/\nint\nUtil_CopyFile(const string &origPath, const string &newPath)\n{\n int srcFd, dstFd;\n char buf[COPYFILE_BUFSZ];\n struct stat sb;\n int64_t bytesLeft;\n int64_t bytesRead, bytesWritten;\n\n srcFd = open(origPath.c_str(), O_RDONLY);\n if (srcFd < 0)\n\treturn -errno;\n\n dstFd = open(newPath.c_str(), O_WRONLY | O_CREAT,\n\t S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n if (dstFd < 0) {\n\tclose(srcFd);\n\treturn -errno;\n }\n\n if (fstat(srcFd, &sb) < 0) {\n\tclose(srcFd);\n\tunlink(newPath.c_str());\n\tclose(dstFd);\n\treturn -errno;\n }\n\n bytesLeft = sb.st_size;\n while(bytesLeft > 0) {\n\tbytesRead = read(srcFd, buf, MIN(bytesLeft, COPYFILE_BUFSZ));\n\tif (bytesRead < 0) {\n\t if (errno == EINTR)\n\t\tcontinue;\n\t goto error;\n\t}\n\nretryWrite:\n\tbytesWritten = write(dstFd, buf, bytesRead);\n\tif (bytesWritten < 0) {\n\t if (errno == EINTR)\n\t\tgoto retryWrite;\n\t goto error;\n\t}\n\n\t\/\/ XXX: Need to handle this case!\n\tassert(bytesRead == bytesWritten);\n\n\tbytesLeft -= bytesRead;\n }\n\n close(srcFd);\n close(dstFd);\n return sb.st_size;\n\nerror:\n close(srcFd);\n unlink(newPath.c_str());\n close(dstFd);\n return -errno;\n}\n\n\/*\n * Safely move a file possibly between file systems.\n *\/\nint\nUtil_MoveFile(const string &origPath, const string &newPath)\n{\n int status = 0;\n\n if (rename(origPath.c_str(), newPath.c_str()) < 0)\n\tstatus = -errno;\n\n \/\/ If the file is on seperate file systems copy it and delete the original.\n if (errno == EXDEV) {\n\tstatus = Util_CopyFile(origPath, newPath);\n\tif (status < 0)\n\t return status;\n\n\tif (unlink(origPath.c_str()) < 0) {\n\t status = -errno;\n\t assert(false);\n\t}\n }\n\n return status;\n}\n\n\/*\n * Compute SHA 256 hash for a string.\n *\/\nstring\nUtil_HashString(const string &str)\n{\n SHA256_CTX state;\n unsigned char hash[SHA256_DIGEST_LENGTH];\n stringstream rval;\n\n SHA256_Init(&state);\n SHA256_Update(&state, str.c_str(), str.size());\n SHA256_Final(hash, &state);\n\n \/\/ Convert into string.\n for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n\trval << hex << setw(2) << setfill('0') << (int)hash[i];\n }\n\n return rval.str();\n}\n\n#define HASHFILE_BUFSZ\t(256 * 1024)\n\n\/*\n * Compute SHA 256 hash for a file.\n *\/\nstring\nUtil_HashFile(const string &path)\n{\n int fd;\n char buf[COPYFILE_BUFSZ];\n struct stat sb;\n int64_t bytesLeft;\n int64_t bytesRead;\n SHA256_CTX state;\n unsigned char hash[SHA256_DIGEST_LENGTH];\n stringstream rval;\n\n SHA256_Init(&state);\n\n fd = open(path.c_str(), O_RDONLY);\n if (fd < 0) {\n\treturn \"\";\n }\n\n if (fstat(fd, &sb) < 0) {\n\tclose(fd);\n\treturn \"\";\n }\n\n bytesLeft = sb.st_size;\n while(bytesLeft > 0) {\n\tbytesRead = read(fd, buf, MIN(bytesLeft, COPYFILE_BUFSZ));\n\tif (bytesRead < 0) {\n\t if (errno == EINTR)\n\t\tcontinue;\n\t close(fd);\n\t return \"\";\n\t}\n\n\tSHA256_Update(&state, buf, bytesRead);\n\tbytesLeft -= bytesRead;\n }\n\n SHA256_Final(hash, &state);\n\n \/\/ Convert into string.\n for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n\trval << hex << setw(2) << setfill('0') << (int)hash[i];\n }\n\n close(fd);\n return rval.str();\n}\n\nvector<string>\nUtil_PathToVector(const string &path)\n{\n int pos = 0;\n vector<string> rval;\n\n if (path[0] == '\/')\n pos = 1;\n\n while (pos < path.length()) {\n int end = path.find('\/', pos);\n if (end == path.npos) {\n rval.push_back(path.substr(pos));\n break;\n }\n\n rval.push_back(path.substr(pos, end - 1));\n pos = end + 1;\n }\n\n return rval;\n}\n\nstring\nUtil_GetFullname()\n{\n struct passwd *pw = getpwuid(getuid());\n\n \/\/ XXX: Error handling\n assert(pw != NULL);\n\n if (pw->pw_gecos != NULL)\n return string(pw->pw_gecos);\n else\n return \"\";\n}\n\nint Util_SetBlocking(int fd, bool block) {\n int old_flags = fcntl(fd, F_GETFL);\n if (old_flags < 0) {\n perror(\"fcntl\");\n return old_flags;\n }\n\n if (block) {\n if (old_flags & O_NONBLOCK) {\n fcntl(fd, F_SETFL, (old_flags & ~O_NONBLOCK));\n }\n }\n else {\n if (!(old_flags & O_NONBLOCK)) {\n fcntl(fd, F_SETFL, old_flags | O_NONBLOCK);\n }\n }\n\n return 0;\n}\n\n\/*\n * Pretty print hex data\n *\/\nvoid\nUtil_PrintHex(const std::string &data, off_t off, size_t limit)\n{\n const int row_size = 16;\n bool stop = false;\n\n \/\/size_t num_printed = 0;\n for (size_t row = 0; !stop; row++) {\n printf(\"\\n\");\n\n printf(\"%08lx \", row * row_size);\n for (size_t col = 0; col < row_size; col++) { \n size_t ix = row * row_size + col;\n if ((limit != 0 && ix >= limit) || ix >= data.length()) {\n stop = true;\n break;\n }\n ix += off;\n\n printf(\"%02X \", (unsigned char)data[ix]);\n }\n printf(\" |\");\n\n for (size_t col = 0; col < row_size; col++) { \n size_t ix = row * row_size + col;\n if ((limit != 0 && ix >= limit) || ix >= data.length()) {\n stop = true;\n break;\n }\n ix += off;\n\n unsigned char c = (unsigned char)data[ix];\n if (c >= 0x20 && c < 0x7F)\n printf(\"%c\", c);\n else\n putchar('.');\n }\n printf(\"|\");\n }\n}\n\n\/*\n * Generate a UUID\n *\/\nstd::string\nUtil_NewUUID()\n{\n#ifdef __FreeBSD__\n uint32_t status;\n uuid_t id;\n char *uuidBuf;\n\n uuid_create(&id, &status);\n if (status != uuid_s_ok) {\n printf(\"Failed to construct UUID!\\n\");\n return \"\";\n }\n uuid_to_string(&id, &uuidBuf, &status);\n if (status != uuid_s_ok) {\n printf(\"Failed to print UUID!\\n\");\n return \"\";\n }\n std::string rval(uuidBuf);\n free(uuidBuf);\n return rval;\n#endif \/* __FreeBSD__ *\/\n\n#if defined(__APPLE__) || defined(__linux__)\n uuid_t id;\n uuid_generate(id);\n char id_buf[128];\n uuid_unparse(id, id_buf);\n \n std::string rval(id_buf);\n return rval;\n#endif \/* __APPLE__ || __linux__ *\/\n}\n\n\nbool\nUtil_IsPathRemote(const char *path) {\n char *cc = strchr(path, ':');\n if (cc == NULL) return false;\n if (cc == path) return false; \/\/ TODO how to handle these cases?\n if (cc == path+strlen(path)-1) return false;\n return true;\n}\n\n\/\/ XXX: Debug Only\n\n#define TESTFILE_SIZE (HASHFILE_BUFSZ * 3 \/ 2)\n\nint\nutil_selftest(void)\n{\n int status;\n char *buf = new char[TESTFILE_SIZE + 1];\n string origHash;\n string newHash;\n\n for (int i = 0; i < TESTFILE_SIZE; i++) {\n\tbuf[i] = '0' + (i % 10);\n }\n buf[TESTFILE_SIZE] = '\\0';\n origHash = Util_HashString(buf);\n\n Util_WriteFile(buf, TESTFILE_SIZE, \"test.orig\");\n\n status = Util_CopyFile(\"test.orig\", \"test.a\");\n if (status < 0) {\n\tprintf(\"Util_CopyFile: %s\\n\", strerror(-status));\n\tassert(false);\n }\n status = Util_CopyFile(\"test.orig\", \"test.b\");\n if (status < 0) {\n\tprintf(\"Util_CopyFile: %s\\n\", strerror(-status));\n\tassert(false);\n }\n status = Util_MoveFile(\"test.b\", \"test.c\");\n if (status < 0) {\n\tprintf(\"Util_CopyFile: %s\\n\", strerror(-status));\n\tassert(false);\n }\n char *fbuf = Util_ReadFile(\"test.c\", NULL);\n assert(fbuf);\n newHash = Util_HashString(fbuf);\n \/\/ XXX: Check that 'test.b' does not exist\n\n if (newHash != origHash) {\n\tprintf(\"Hash mismatch!\\n\");\n\tassert(false);\n }\n\n newHash = Util_HashFile(\"test.a\");\n\n if (newHash != origHash) {\n\tprintf(\"Hash mismatch!\\n\");\n\tassert(false);\n }\n\n vector<string> tv;\n tv = Util_PathToVector(\"\/abc\/def\");\n assert(tv.size() == 2);\n assert(tv[0] == \"abc\");\n assert(tv[1] == \"def\");\n\n\n \/\/ Tests for stream classes\n int test_fd = open(\"test.a\", O_RDWR | O_CREAT);\n write(test_fd, \"hello, world!\", 13);\n fsync(test_fd);\n bytestream *bs = new diskstream(test_fd, 1, 3);\n uint8_t b;\n bs->read(&b, 1);\n assert(b == 'e');\n delete bs;\n\n printf(\"Test Succeeded!\\n\");\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Speaker.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 12\/01\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Speaker_hpp\n#define Speaker_hpp\n\n#include <stdint.h>\n#include <stdio.h>\n#include <time.h>\n\n#include <memory>\n#include <list>\n\n#include \"..\/SignalProcessing\/Stepper.hpp\"\n#include \"..\/SignalProcessing\/FIRFilter.hpp\"\n#include \"..\/Concurrency\/AsyncTaskQueue.hpp\"\n\nnamespace Outputs {\n\n\/*!\n\tProvides the base class for an audio output source, with an input rate (the speed at which the source will\n\tprovide data), an output rate (the speed at which the destination will receive data), a delegate to receive\n\tthe output and some help for the output in picking an appropriate rate once the input rate is known.\n\n\tIntended to be a parent class, allowing descendants to pick the strategy by which input samples are mapped to\n\toutput samples.\n*\/\nclass Speaker {\n\tpublic:\n\t\tclass Delegate {\n\t\t\tpublic:\n\t\t\t\tvirtual void speaker_did_complete_samples(Speaker *speaker, const int16_t *buffer, int buffer_size) = 0;\n\t\t};\n\n\t\tfloat get_ideal_clock_rate_in_range(float minimum, float maximum)\n\t\t{\n\t\t\t\/\/ return twice the cut off, if applicable\n\t\t\tif(_high_frequency_cut_off > 0.0f && _input_cycles_per_second >= _high_frequency_cut_off * 3.0f && _input_cycles_per_second <= _high_frequency_cut_off * 3.0f) return _high_frequency_cut_off * 3.0f;\n\n\t\t\t\/\/ return exactly the input rate if possible\n\t\t\tif(_input_cycles_per_second >= minimum && _input_cycles_per_second <= maximum) return _input_cycles_per_second;\n\n\t\t\t\/\/ if the input rate is lower, return the minimum\n\t\t\tif(_input_cycles_per_second < minimum) return minimum;\n\n\t\t\t\/\/ otherwise, return the maximum\n\t\t\treturn maximum;\n\t\t}\n\n\t\tvoid set_output_rate(float cycles_per_second, int buffer_size)\n\t\t{\n\t\t\t_output_cycles_per_second = cycles_per_second;\n\t\t\tif(_buffer_size != buffer_size)\n\t\t\t{\n\t\t\t\t_buffer_in_progress.reset(new int16_t[buffer_size]);\n\t\t\t\t_buffer_size = buffer_size;\n\t\t\t}\n\t\t\tset_needs_updated_filter_coefficients();\n\t\t}\n\n\t\tvoid set_output_quality(int number_of_taps)\n\t\t{\n\t\t\t_requested_number_of_taps = number_of_taps;\n\t\t\tset_needs_updated_filter_coefficients();\n\t\t}\n\n\t\tvoid set_delegate(Delegate *delegate)\n\t\t{\n\t\t\t_delegate = delegate;\n\t\t}\n\n\t\tvoid set_input_rate(float cycles_per_second)\n\t\t{\n\t\t\t_input_cycles_per_second = cycles_per_second;\n\t\t\tset_needs_updated_filter_coefficients();\n\t\t}\n\n\t\t\/*!\n\t\t\tSets the cut-off frequency for a low-pass filter attached to the output of this speaker; optional.\n\t\t*\/\n\t\tvoid set_high_frequency_cut_off(float high_frequency)\n\t\t{\n\t\t\t_high_frequency_cut_off = high_frequency;\n\t\t\tset_needs_updated_filter_coefficients();\n\t\t}\n\n\t\tSpeaker() : _buffer_in_progress_pointer(0), _requested_number_of_taps(0), _high_frequency_cut_off(-1.0), _queue(new Concurrency::AsyncTaskQueue) {}\n\n\t\t\/*!\n\t\t\tEnsures any deferred processing occurs now.\n\t\t*\/\n\t\tvoid flush()\n\t\t{\n\t\t\tstd::shared_ptr<std::list<std::function<void(void)>>> queued_functions = _queued_functions;\n\t\t\t_queued_functions.reset();\n\t\t\t_queue->enqueue([queued_functions] {\n\t\t\t\tfor(auto function : *queued_functions)\n\t\t\t\t{\n\t\t\t\t\tfunction();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\tprotected:\n\t\tvoid enqueue(std::function<void(void)> function)\n\t\t{\n\t\t\tif(!_queued_functions) _queued_functions.reset(new std::list<std::function<void(void)>>);\n\t\t\t_queued_functions->push_back(function);\n\t\t}\n\t\tstd::shared_ptr<std::list<std::function<void(void)>>> _queued_functions;\n\n\t\tstd::unique_ptr<int16_t> _buffer_in_progress;\n\t\tfloat _high_frequency_cut_off;\n\t\tint _buffer_size;\n\t\tint _buffer_in_progress_pointer;\n\t\tint _number_of_taps, _requested_number_of_taps;\n\t\tbool _coefficients_are_dirty;\n\t\tDelegate *_delegate;\n\n\t\tfloat _input_cycles_per_second, _output_cycles_per_second;\n\n\t\tvoid set_needs_updated_filter_coefficients()\n\t\t{\n\t\t\t_coefficients_are_dirty = true;\n\t\t}\n\n\t\tvoid get_samples(unsigned int quantity, int16_t *target)\t{}\n\t\tvoid skip_samples(unsigned int quantity)\n\t\t{\n\t\t\tint16_t throwaway_samples[quantity];\n\t\t\tget_samples(quantity, throwaway_samples);\n\t\t}\n\n\t\tstd::unique_ptr<Concurrency::AsyncTaskQueue> _queue;\n};\n\n\/*!\n\tA concrete descendant of Speaker that uses a FIR filter to map from input data to output data when scaling\n\tand a copy-through buffer when input and output rates are the same.\n\n\tAudio sources should use @c Filter as both a template and a parent, implementing at least\n\t`get_samples(unsigned int quantity, int16_t *target)` and ideally also `skip_samples(unsigned int quantity)`\n\tto provide source data.\n\n\tCall `run_for_cycles(n)` to request that the next n cycles of input data are collected.\n*\/\ntemplate <class T> class Filter: public Speaker {\n\tpublic:\n\t\t~Filter()\n\t\t{\n\t\t\t_queue->flush();\n\t\t}\n\n\t\tvoid run_for_cycles(unsigned int input_cycles)\n\t\t{\n\t\t\tenqueue([=]() {\n\t\t\t\tunsigned int cycles_remaining = input_cycles;\n\t\t\t\tif(_coefficients_are_dirty) update_filter_coefficients();\n\n\t\t\t\t\/\/ if input and output rates exactly match, just accumulate results and pass on\n\t\t\t\tif(_input_cycles_per_second == _output_cycles_per_second && _high_frequency_cut_off < 0.0)\n\t\t\t\t{\n\t\t\t\t\twhile(cycles_remaining)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned int cycles_to_read = (unsigned int)(_buffer_size - _buffer_in_progress_pointer);\n\t\t\t\t\t\tif(cycles_to_read > cycles_remaining) cycles_to_read = cycles_remaining;\n\n\t\t\t\t\t\tstatic_cast<T *>(this)->get_samples(cycles_to_read, &_buffer_in_progress.get()[_buffer_in_progress_pointer]);\n\t\t\t\t\t\t_buffer_in_progress_pointer += cycles_to_read;\n\n\t\t\t\t\t\t\/\/ announce to delegate if full\n\t\t\t\t\t\tif(_buffer_in_progress_pointer == _buffer_size)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_buffer_in_progress_pointer = 0;\n\t\t\t\t\t\t\tif(_delegate)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t_delegate->speaker_did_complete_samples(this, _buffer_in_progress.get(), _buffer_size);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcycles_remaining -= cycles_to_read;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\/\/ if the output rate is less than the input rate, use the filter\n\t\t\t\tif(_input_cycles_per_second > _output_cycles_per_second)\n\t\t\t\t{\n\t\t\t\t\twhile(cycles_remaining)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned int cycles_to_read = (unsigned int)std::min((int)cycles_remaining, _number_of_taps - _input_buffer_depth);\n\t\t\t\t\t\tstatic_cast<T *>(this)->get_samples(cycles_to_read, &_input_buffer.get()[_input_buffer_depth]);\n\t\t\t\t\t\tcycles_remaining -= cycles_to_read;\n\t\t\t\t\t\t_input_buffer_depth += cycles_to_read;\n\n\t\t\t\t\t\tif(_input_buffer_depth == _number_of_taps)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_buffer_in_progress.get()[_buffer_in_progress_pointer] = _filter->apply(_input_buffer.get());\n\t\t\t\t\t\t\t_buffer_in_progress_pointer++;\n\n\t\t\t\t\t\t\t\/\/ announce to delegate if full\n\t\t\t\t\t\t\tif(_buffer_in_progress_pointer == _buffer_size)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t_buffer_in_progress_pointer = 0;\n\t\t\t\t\t\t\t\tif(_delegate)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t_delegate->speaker_did_complete_samples(this, _buffer_in_progress.get(), _buffer_size);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\/\/ If the next loop around is going to reuse some of the samples just collected, use a memmove to\n\t\t\t\t\t\t\t\/\/ preserve them in the correct locations (TODO: use a longer buffer to fix that) and don't skip\n\t\t\t\t\t\t\t\/\/ anything. Otherwise skip as required to get to the next sample batch and don't expect to reuse.\n\t\t\t\t\t\t\tuint64_t steps = _stepper->step();\n\t\t\t\t\t\t\tif(steps < _number_of_taps)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint16_t *input_buffer = _input_buffer.get();\n\t\t\t\t\t\t\t\tmemmove(input_buffer, &input_buffer[steps], sizeof(int16_t) * ((size_t)_number_of_taps - (size_t)steps));\n\t\t\t\t\t\t\t\t_input_buffer_depth -= steps;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(steps > _number_of_taps)\n\t\t\t\t\t\t\t\t\tstatic_cast<T *>(this)->skip_samples((unsigned int)steps - (unsigned int)_number_of_taps);\n\t\t\t\t\t\t\t\t_input_buffer_depth = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\/\/ TODO: input rate is less than output rate\n\t\t\t});\n\t\t}\n\n\tprivate:\n\t\tstd::unique_ptr<SignalProcessing::Stepper> _stepper;\n\t\tstd::unique_ptr<SignalProcessing::FIRFilter> _filter;\n\n\t\tstd::unique_ptr<int16_t> _input_buffer;\n\t\tint _input_buffer_depth;\n\n\t\tvoid update_filter_coefficients()\n\t\t{\n\t\t\t\/\/ make a guess at a good number of taps if this hasn't been provided explicitly\n\t\t\tif(_requested_number_of_taps)\n\t\t\t{\n\t\t\t\t_number_of_taps = _requested_number_of_taps;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t_number_of_taps = (int)ceilf((_input_cycles_per_second + _output_cycles_per_second) \/ _output_cycles_per_second);\n\t\t\t\t_number_of_taps *= 2;\n\t\t\t\t_number_of_taps |= 1;\n\t\t\t}\n\n\t\t\t_coefficients_are_dirty = false;\n\t\t\t_buffer_in_progress_pointer = 0;\n\n\t\t\t_stepper.reset(new SignalProcessing::Stepper((uint64_t)_input_cycles_per_second, (uint64_t)_output_cycles_per_second));\n\n\t\t\tfloat high_pass_frequency;\n\t\t\tif(_high_frequency_cut_off > 0.0)\n\t\t\t{\n\t\t\t\thigh_pass_frequency = std::min((float)_output_cycles_per_second \/ 2.0f, _high_frequency_cut_off);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\thigh_pass_frequency = (float)_output_cycles_per_second \/ 2.0f;\n\t\t\t}\n\t\t\t_filter.reset(new SignalProcessing::FIRFilter((unsigned int)_number_of_taps, (float)_input_cycles_per_second, 0.0, high_pass_frequency, SignalProcessing::FIRFilter::DefaultAttenuation));\n\n\t\t\t_input_buffer.reset(new int16_t[_number_of_taps]);\n\t\t\t_input_buffer_depth = 0;\n\t\t}\n};\n\n}\n\n#endif \/* Speaker_hpp *\/\n<commit_msg>Completed flight of 'Outputs' to postfix underscores.<commit_after>\/\/\n\/\/ Speaker.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 12\/01\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Speaker_hpp\n#define Speaker_hpp\n\n#include <stdint.h>\n#include <stdio.h>\n#include <time.h>\n\n#include <memory>\n#include <list>\n\n#include \"..\/SignalProcessing\/Stepper.hpp\"\n#include \"..\/SignalProcessing\/FIRFilter.hpp\"\n#include \"..\/Concurrency\/AsyncTaskQueue.hpp\"\n\nnamespace Outputs {\n\n\/*!\n\tProvides the base class for an audio output source, with an input rate (the speed at which the source will\n\tprovide data), an output rate (the speed at which the destination will receive data), a delegate to receive\n\tthe output and some help for the output in picking an appropriate rate once the input rate is known.\n\n\tIntended to be a parent class, allowing descendants to pick the strategy by which input samples are mapped to\n\toutput samples.\n*\/\nclass Speaker {\n\tpublic:\n\t\tclass Delegate {\n\t\t\tpublic:\n\t\t\t\tvirtual void speaker_did_complete_samples(Speaker *speaker, const int16_t *buffer, int buffer_size) = 0;\n\t\t};\n\n\t\tfloat get_ideal_clock_rate_in_range(float minimum, float maximum)\n\t\t{\n\t\t\t\/\/ return twice the cut off, if applicable\n\t\t\tif(high_frequency_cut_off_ > 0.0f && input_cycles_per_second_ >= high_frequency_cut_off_ * 3.0f && input_cycles_per_second_ <= high_frequency_cut_off_ * 3.0f) return high_frequency_cut_off_ * 3.0f;\n\n\t\t\t\/\/ return exactly the input rate if possible\n\t\t\tif(input_cycles_per_second_ >= minimum && input_cycles_per_second_ <= maximum) return input_cycles_per_second_;\n\n\t\t\t\/\/ if the input rate is lower, return the minimum\n\t\t\tif(input_cycles_per_second_ < minimum) return minimum;\n\n\t\t\t\/\/ otherwise, return the maximum\n\t\t\treturn maximum;\n\t\t}\n\n\t\tvoid set_output_rate(float cycles_per_second, int buffer_size)\n\t\t{\n\t\t\toutput_cycles_per_second_ = cycles_per_second;\n\t\t\tif(buffer_size_ != buffer_size)\n\t\t\t{\n\t\t\t\tbuffer_in_progress_.reset(new int16_t[buffer_size]);\n\t\t\t\tbuffer_size_ = buffer_size;\n\t\t\t}\n\t\t\tset_needs_updated_filter_coefficients();\n\t\t}\n\n\t\tvoid set_output_quality(int number_of_taps)\n\t\t{\n\t\t\trequested_number_of_taps_ = number_of_taps;\n\t\t\tset_needs_updated_filter_coefficients();\n\t\t}\n\n\t\tvoid set_delegate(Delegate *delegate)\n\t\t{\n\t\t\tdelegate_ = delegate;\n\t\t}\n\n\t\tvoid set_input_rate(float cycles_per_second)\n\t\t{\n\t\t\tinput_cycles_per_second_ = cycles_per_second;\n\t\t\tset_needs_updated_filter_coefficients();\n\t\t}\n\n\t\t\/*!\n\t\t\tSets the cut-off frequency for a low-pass filter attached to the output of this speaker; optional.\n\t\t*\/\n\t\tvoid set_high_frequency_cut_off(float high_frequency)\n\t\t{\n\t\t\thigh_frequency_cut_off_ = high_frequency;\n\t\t\tset_needs_updated_filter_coefficients();\n\t\t}\n\n\t\tSpeaker() : buffer_in_progress_pointer_(0), requested_number_of_taps_(0), high_frequency_cut_off_(-1.0), _queue(new Concurrency::AsyncTaskQueue) {}\n\n\t\t\/*!\n\t\t\tEnsures any deferred processing occurs now.\n\t\t*\/\n\t\tvoid flush()\n\t\t{\n\t\t\tstd::shared_ptr<std::list<std::function<void(void)>>> queued_functions = queued_functions_;\n\t\t\tqueued_functions_.reset();\n\t\t\t_queue->enqueue([queued_functions] {\n\t\t\t\tfor(auto function : *queued_functions)\n\t\t\t\t{\n\t\t\t\t\tfunction();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\tprotected:\n\t\tvoid enqueue(std::function<void(void)> function)\n\t\t{\n\t\t\tif(!queued_functions_) queued_functions_.reset(new std::list<std::function<void(void)>>);\n\t\t\tqueued_functions_->push_back(function);\n\t\t}\n\t\tstd::shared_ptr<std::list<std::function<void(void)>>> queued_functions_;\n\n\t\tstd::unique_ptr<int16_t> buffer_in_progress_;\n\t\tfloat high_frequency_cut_off_;\n\t\tint buffer_size_;\n\t\tint buffer_in_progress_pointer_;\n\t\tint number_of_taps_, requested_number_of_taps_;\n\t\tbool coefficients_are_dirty_;\n\t\tDelegate *delegate_;\n\n\t\tfloat input_cycles_per_second_, output_cycles_per_second_;\n\n\t\tvoid set_needs_updated_filter_coefficients()\n\t\t{\n\t\t\tcoefficients_are_dirty_ = true;\n\t\t}\n\n\t\tvoid get_samples(unsigned int quantity, int16_t *target)\t{}\n\t\tvoid skip_samples(unsigned int quantity)\n\t\t{\n\t\t\tint16_t throwaway_samples[quantity];\n\t\t\tget_samples(quantity, throwaway_samples);\n\t\t}\n\n\t\tstd::unique_ptr<Concurrency::AsyncTaskQueue> _queue;\n};\n\n\/*!\n\tA concrete descendant of Speaker that uses a FIR filter to map from input data to output data when scaling\n\tand a copy-through buffer when input and output rates are the same.\n\n\tAudio sources should use @c Filter as both a template and a parent, implementing at least\n\t`get_samples(unsigned int quantity, int16_t *target)` and ideally also `skip_samples(unsigned int quantity)`\n\tto provide source data.\n\n\tCall `run_for_cycles(n)` to request that the next n cycles of input data are collected.\n*\/\ntemplate <class T> class Filter: public Speaker {\n\tpublic:\n\t\t~Filter()\n\t\t{\n\t\t\t_queue->flush();\n\t\t}\n\n\t\tvoid run_for_cycles(unsigned int input_cycles)\n\t\t{\n\t\t\tenqueue([=]() {\n\t\t\t\tunsigned int cycles_remaining = input_cycles;\n\t\t\t\tif(coefficients_are_dirty_) update_filter_coefficients();\n\n\t\t\t\t\/\/ if input and output rates exactly match, just accumulate results and pass on\n\t\t\t\tif(input_cycles_per_second_ == output_cycles_per_second_ && high_frequency_cut_off_ < 0.0)\n\t\t\t\t{\n\t\t\t\t\twhile(cycles_remaining)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned int cycles_to_read = (unsigned int)(buffer_size_ - buffer_in_progress_pointer_);\n\t\t\t\t\t\tif(cycles_to_read > cycles_remaining) cycles_to_read = cycles_remaining;\n\n\t\t\t\t\t\tstatic_cast<T *>(this)->get_samples(cycles_to_read, &buffer_in_progress_.get()[buffer_in_progress_pointer_]);\n\t\t\t\t\t\tbuffer_in_progress_pointer_ += cycles_to_read;\n\n\t\t\t\t\t\t\/\/ announce to delegate if full\n\t\t\t\t\t\tif(buffer_in_progress_pointer_ == buffer_size_)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbuffer_in_progress_pointer_ = 0;\n\t\t\t\t\t\t\tif(delegate_)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdelegate_->speaker_did_complete_samples(this, buffer_in_progress_.get(), buffer_size_);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcycles_remaining -= cycles_to_read;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\/\/ if the output rate is less than the input rate, use the filter\n\t\t\t\tif(input_cycles_per_second_ > output_cycles_per_second_)\n\t\t\t\t{\n\t\t\t\t\twhile(cycles_remaining)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned int cycles_to_read = (unsigned int)std::min((int)cycles_remaining, number_of_taps_ - input_buffer_depth_);\n\t\t\t\t\t\tstatic_cast<T *>(this)->get_samples(cycles_to_read, &input_buffer_.get()[input_buffer_depth_]);\n\t\t\t\t\t\tcycles_remaining -= cycles_to_read;\n\t\t\t\t\t\tinput_buffer_depth_ += cycles_to_read;\n\n\t\t\t\t\t\tif(input_buffer_depth_ == number_of_taps_)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbuffer_in_progress_.get()[buffer_in_progress_pointer_] = filter_->apply(input_buffer_.get());\n\t\t\t\t\t\t\tbuffer_in_progress_pointer_++;\n\n\t\t\t\t\t\t\t\/\/ announce to delegate if full\n\t\t\t\t\t\t\tif(buffer_in_progress_pointer_ == buffer_size_)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tbuffer_in_progress_pointer_ = 0;\n\t\t\t\t\t\t\t\tif(delegate_)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdelegate_->speaker_did_complete_samples(this, buffer_in_progress_.get(), buffer_size_);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\/\/ If the next loop around is going to reuse some of the samples just collected, use a memmove to\n\t\t\t\t\t\t\t\/\/ preserve them in the correct locations (TODO: use a longer buffer to fix that) and don't skip\n\t\t\t\t\t\t\t\/\/ anything. Otherwise skip as required to get to the next sample batch and don't expect to reuse.\n\t\t\t\t\t\t\tuint64_t steps = stepper_->step();\n\t\t\t\t\t\t\tif(steps < number_of_taps_)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint16_t *input_buffer = input_buffer_.get();\n\t\t\t\t\t\t\t\tmemmove(input_buffer, &input_buffer[steps], sizeof(int16_t) * ((size_t)number_of_taps_ - (size_t)steps));\n\t\t\t\t\t\t\t\tinput_buffer_depth_ -= steps;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(steps > number_of_taps_)\n\t\t\t\t\t\t\t\t\tstatic_cast<T *>(this)->skip_samples((unsigned int)steps - (unsigned int)number_of_taps_);\n\t\t\t\t\t\t\t\tinput_buffer_depth_ = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\/\/ TODO: input rate is less than output rate\n\t\t\t});\n\t\t}\n\n\tprivate:\n\t\tstd::unique_ptr<SignalProcessing::Stepper> stepper_;\n\t\tstd::unique_ptr<SignalProcessing::FIRFilter> filter_;\n\n\t\tstd::unique_ptr<int16_t> input_buffer_;\n\t\tint input_buffer_depth_;\n\n\t\tvoid update_filter_coefficients()\n\t\t{\n\t\t\t\/\/ make a guess at a good number of taps if this hasn't been provided explicitly\n\t\t\tif(requested_number_of_taps_)\n\t\t\t{\n\t\t\t\tnumber_of_taps_ = requested_number_of_taps_;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnumber_of_taps_ = (int)ceilf((input_cycles_per_second_ + output_cycles_per_second_) \/ output_cycles_per_second_);\n\t\t\t\tnumber_of_taps_ *= 2;\n\t\t\t\tnumber_of_taps_ |= 1;\n\t\t\t}\n\n\t\t\tcoefficients_are_dirty_ = false;\n\t\t\tbuffer_in_progress_pointer_ = 0;\n\n\t\t\tstepper_.reset(new SignalProcessing::Stepper((uint64_t)input_cycles_per_second_, (uint64_t)output_cycles_per_second_));\n\n\t\t\tfloat high_pass_frequency;\n\t\t\tif(high_frequency_cut_off_ > 0.0)\n\t\t\t{\n\t\t\t\thigh_pass_frequency = std::min((float)output_cycles_per_second_ \/ 2.0f, high_frequency_cut_off_);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\thigh_pass_frequency = (float)output_cycles_per_second_ \/ 2.0f;\n\t\t\t}\n\t\t\tfilter_.reset(new SignalProcessing::FIRFilter((unsigned int)number_of_taps_, (float)input_cycles_per_second_, 0.0, high_pass_frequency, SignalProcessing::FIRFilter::DefaultAttenuation));\n\n\t\t\tinput_buffer_.reset(new int16_t[number_of_taps_]);\n\t\t\tinput_buffer_depth_ = 0;\n\t\t}\n};\n\n}\n\n#endif \/* Speaker_hpp *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PolarLabelPositionHelper.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 01:44: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\n#ifndef _CHART2_VIEW_POLARLABELPOSITIONHELPER_HXX\n#define _CHART2_VIEW_POLARLABELPOSITIONHELPER_HXX\n\n#include \"LabelPositionHelper.hxx\"\n\n#ifndef _COM_SUN_STAR_AWT_POINT_HPP_\n#include <com\/sun\/star\/awt\/Point.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_\n#include <com\/sun\/star\/drawing\/Position3D.hpp>\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/**\n*\/\nclass PolarPlottingPositionHelper;\n\nclass PolarLabelPositionHelper : public LabelPositionHelper\n{\npublic:\n PolarLabelPositionHelper(\n PolarPlottingPositionHelper* pPosHelper\n , sal_Int32 nDimensionCount\n , const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget\n , ShapeFactory* pShapeFactory );\n virtual ~PolarLabelPositionHelper();\n\n ::com::sun::star::awt::Point getLabelScreenPositionAndAlignment(\n LabelAlignment& rAlignment, bool bCenteredPosition\n , double fStartLogicValueOnAngleAxis, double fEndLogicValueOnAngleAxis\n , double fLogicInnerRadius, double fLogicOuterRadius\n , double fLogicZ) const;\n\nprivate:\n PolarPlottingPositionHelper* m_pPosHelper;\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<commit_msg>INTEGRATION: CWS chart2mst3 (1.1.4); FILE MERGED 2006\/08\/10 15:57:01 iha 1.1.4.3: Axis Label Layout - Font&Diagram Size 2005\/10\/07 12:21:11 bm 1.1.4.2: RESYNC: (1.1-1.2); FILE MERGED 2004\/05\/08 17:54:56 iha 1.1.4.1: polartransformation fixes and pie offset implementation<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PolarLabelPositionHelper.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 19:19:56 $\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 _CHART2_VIEW_POLARLABELPOSITIONHELPER_HXX\n#define _CHART2_VIEW_POLARLABELPOSITIONHELPER_HXX\n\n#include \"LabelPositionHelper.hxx\"\n\n#ifndef _COM_SUN_STAR_AWT_POINT_HPP_\n#include <com\/sun\/star\/awt\/Point.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_\n#include <com\/sun\/star\/drawing\/Position3D.hpp>\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/**\n*\/\nclass PolarPlottingPositionHelper;\n\nclass PolarLabelPositionHelper : public LabelPositionHelper\n{\npublic:\n PolarLabelPositionHelper(\n PolarPlottingPositionHelper* pPosHelper\n , sal_Int32 nDimensionCount\n , const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget\n , ShapeFactory* pShapeFactory );\n virtual ~PolarLabelPositionHelper();\n\n ::com::sun::star::awt::Point getLabelScreenPositionAndAlignmentForLogicValues(\n LabelAlignment& rAlignment\n , double fLogicValueOnAngleAxis\n , double fLogicValueOnRadiusAxis\n , double fLogicZ\n , sal_Int32 nScreenValueOffsetInRadiusDirection=0 ) const;\n\n ::com::sun::star::awt::Point getLabelScreenPositionAndAlignmentForUnitCircleValues(\n LabelAlignment& rAlignment, bool bOutsidePosition\n , double fUnitCircleStartAngleDegree, double fUnitCircleWidthAngleDegree\n , double fUnitCircleInnerRadius, double fUnitCircleOuterRadius\n , double fLogicZ\n , sal_Int32 nScreenValueOffsetInRadiusDirection=0 ) const;\n\nprivate:\n PolarPlottingPositionHelper* m_pPosHelper;\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/debugger\/devtools_window.h\"\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/test\/test_server.h\"\n\nnamespace {\n\n\/\/ Used to block until a dev tools client window's browser is closed.\nclass BrowserClosedObserver : public NotificationObserver {\n public:\n explicit BrowserClosedObserver(Browser* browser) {\n registrar_.Add(this, NotificationType::BROWSER_CLOSED,\n Source<Browser>(browser));\n ui_test_utils::RunMessageLoop();\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n MessageLoopForUI::current()->Quit();\n }\n\n private:\n NotificationRegistrar registrar_;\n DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);\n};\n\n\/\/ The delay waited in some cases where we don't have a notifications for an\n\/\/ action we take.\nconst int kActionDelayMs = 500;\n\nconst char kDebuggerTestPage[] = \"files\/devtools\/debugger_test_page.html\";\nconst char kHeapProfilerPage[] = \"files\/devtools\/heap_profiler.html\";\nconst char kPauseWhenLoadingDevTools[] =\n \"files\/devtools\/pause_when_loading_devtools.html\";\nconst char kPauseWhenScriptIsRunning[] =\n \"files\/devtools\/pause_when_script_is_running.html\";\nconst char kPageWithContentScript[] =\n \"files\/devtools\/page_with_content_script.html\";\n\n\nclass DevToolsSanityTest : public InProcessBrowserTest {\n public:\n DevToolsSanityTest() {\n set_show_window(true);\n EnableDOMAutomation();\n }\n\n protected:\n void RunTest(const std::string& test_name, const std::string& test_page) {\n OpenDevToolsWindow(test_page);\n std::string result;\n\n \/\/ At first check that JavaScript part of the front-end is loaded by\n \/\/ checking that global variable uiTests exists(it's created after all js\n \/\/ files have been loaded) and has runTest method.\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"'' + (window.uiTests && (typeof uiTests.runTest)));\",\n &result));\n\n if (result == \"function\") {\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n UTF8ToWide(StringPrintf(\"uiTests.runTest('%s')\",\n test_name.c_str())),\n &result));\n EXPECT_EQ(\"[OK]\", result);\n } else {\n FAIL() << \"DevTools front-end is broken.\";\n }\n CloseDevToolsWindow();\n }\n\n void OpenDevToolsWindow(const std::string& test_page) {\n ASSERT_TRUE(test_server()->Start());\n GURL url = test_server()->GetURL(test_page);\n ui_test_utils::NavigateToURL(browser(), url);\n\n inspected_rvh_ = GetInspectedTab()->render_view_host();\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n devtools_manager->OpenDevToolsWindow(inspected_rvh_);\n\n DevToolsClientHost* client_host =\n devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);\n window_ = client_host->AsDevToolsWindow();\n RenderViewHost* client_rvh = window_->GetRenderViewHost();\n client_contents_ = client_rvh->delegate()->GetAsTabContents();\n ui_test_utils::WaitForNavigation(&client_contents_->controller());\n }\n\n TabContents* GetInspectedTab() {\n return browser()->GetTabContentsAt(0);\n }\n\n void CloseDevToolsWindow() {\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n \/\/ UnregisterDevToolsClientHostFor may destroy window_ so store the browser\n \/\/ first.\n Browser* browser = window_->browser();\n devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);\n\n \/\/ Wait only when DevToolsWindow has a browser. For docked DevTools, this\n \/\/ is NULL and we skip the wait.\n if (browser)\n BrowserClosedObserver close_observer(browser);\n }\n\n TabContents* client_contents_;\n DevToolsWindow* window_;\n RenderViewHost* inspected_rvh_;\n};\n\n\nclass CancelableQuitTask : public Task {\n public:\n explicit CancelableQuitTask(const std::string& timeout_message)\n : timeout_message_(timeout_message),\n cancelled_(false) {\n }\n\n void cancel() {\n cancelled_ = true;\n }\n\n virtual void Run() {\n if (cancelled_) {\n return;\n }\n FAIL() << timeout_message_;\n MessageLoop::current()->Quit();\n }\n\n private:\n std::string timeout_message_;\n bool cancelled_;\n};\n\n\n\/\/ Base class for DevTools tests that test devtools functionality for\n\/\/ extensions and content scripts.\nclass DevToolsExtensionDebugTest : public DevToolsSanityTest,\n public NotificationObserver {\n public:\n DevToolsExtensionDebugTest() : DevToolsSanityTest() {\n PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);\n test_extensions_dir_ = test_extensions_dir_.AppendASCII(\"devtools\");\n test_extensions_dir_ = test_extensions_dir_.AppendASCII(\"extensions\");\n }\n\n protected:\n \/\/ Load an extention from test\\data\\devtools\\extensions\\<extension_name>\n void LoadExtension(const char* extension_name) {\n FilePath path = test_extensions_dir_.AppendASCII(extension_name);\n ASSERT_TRUE(LoadExtensionFromPath(path)) << \"Failed to load extension.\";\n }\n\n private:\n bool LoadExtensionFromPath(const FilePath& path) {\n ExtensionService* service = browser()->profile()->GetExtensionService();\n size_t num_before = service->extensions()->size();\n {\n NotificationRegistrar registrar;\n registrar.Add(this, NotificationType::EXTENSION_LOADED,\n NotificationService::AllSources());\n CancelableQuitTask* delayed_quit =\n new CancelableQuitTask(\"Extension load timed out.\");\n MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,\n 4*1000);\n service->LoadExtension(path);\n ui_test_utils::RunMessageLoop();\n delayed_quit->cancel();\n }\n size_t num_after = service->extensions()->size();\n if (num_after != (num_before + 1))\n return false;\n\n return WaitForExtensionHostsToLoad();\n }\n\n bool WaitForExtensionHostsToLoad() {\n \/\/ Wait for all the extension hosts that exist to finish loading.\n \/\/ NOTE: This assumes that the extension host list is not changing while\n \/\/ this method is running.\n\n NotificationRegistrar registrar;\n registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,\n NotificationService::AllSources());\n CancelableQuitTask* delayed_quit =\n new CancelableQuitTask(\"Extension host load timed out.\");\n MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,\n 4*1000);\n\n ExtensionProcessManager* manager =\n browser()->profile()->GetExtensionProcessManager();\n for (ExtensionProcessManager::const_iterator iter = manager->begin();\n iter != manager->end();) {\n if ((*iter)->did_stop_loading())\n ++iter;\n else\n ui_test_utils::RunMessageLoop();\n }\n\n delayed_quit->cancel();\n return true;\n }\n\n void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::EXTENSION_LOADED:\n case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:\n MessageLoopForUI::current()->Quit();\n break;\n default:\n NOTREACHED();\n break;\n }\n }\n\n FilePath test_extensions_dir_;\n};\n\n\/\/ Tests heap profiler.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FAILS_TestHeapProfiler) {\n RunTest(\"testHeapProfiler\", kHeapProfilerPage);\n}\n\n\/\/ Tests scripts panel showing.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {\n RunTest(\"testShowScriptsTab\", kDebuggerTestPage);\n}\n\n\/\/ Tests that scripts tab is populated with inspected scripts even if it\n\/\/ hadn't been shown by the moment inspected paged refreshed.\n\/\/ @see http:\/\/crbug.com\/26312\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest,\n TestScriptsTabIsPopulatedOnInspectedPageRefresh) {\n \/\/ Clear inspector settings to ensure that Elements will be\n \/\/ current panel when DevTools window is open.\n GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();\n RunTest(\"testScriptsTabIsPopulatedOnInspectedPageRefresh\",\n kDebuggerTestPage);\n}\n\n\/\/ Tests that a content script is in the scripts list.\n\/\/ This test is disabled, see bug 28961.\nIN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,\n TestContentScriptIsPresent) {\n LoadExtension(\"simple_content_script\");\n RunTest(\"testContentScriptIsPresent\", kPageWithContentScript);\n}\n\n\/\/ Tests that scripts are not duplicated after Scripts Panel switch.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest,\n TestNoScriptDuplicatesOnPanelSwitch) {\n RunTest(\"testNoScriptDuplicatesOnPanelSwitch\", kDebuggerTestPage);\n}\n\n\/\/ Tests that debugger works correctly if pause event occurs when DevTools\n\/\/ frontend is being loaded.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {\n RunTest(\"testPauseWhenLoadingDevTools\", kPauseWhenLoadingDevTools);\n}\n\n\/\/ Tests that pressing 'Pause' will pause script execution if the script\n\/\/ is already running.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {\n RunTest(\"testPauseWhenScriptIsRunning\", kPauseWhenScriptIsRunning);\n}\n\n} \/\/ namespace\n<commit_msg>Disable DevToolsSanityTest.TestPauseWhenScriptIsRunning as it always times out.<commit_after>\/\/ Copyright (c) 2010 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 \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/debugger\/devtools_window.h\"\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/test\/test_server.h\"\n\nnamespace {\n\n\/\/ Used to block until a dev tools client window's browser is closed.\nclass BrowserClosedObserver : public NotificationObserver {\n public:\n explicit BrowserClosedObserver(Browser* browser) {\n registrar_.Add(this, NotificationType::BROWSER_CLOSED,\n Source<Browser>(browser));\n ui_test_utils::RunMessageLoop();\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n MessageLoopForUI::current()->Quit();\n }\n\n private:\n NotificationRegistrar registrar_;\n DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);\n};\n\n\/\/ The delay waited in some cases where we don't have a notifications for an\n\/\/ action we take.\nconst int kActionDelayMs = 500;\n\nconst char kDebuggerTestPage[] = \"files\/devtools\/debugger_test_page.html\";\nconst char kHeapProfilerPage[] = \"files\/devtools\/heap_profiler.html\";\nconst char kPauseWhenLoadingDevTools[] =\n \"files\/devtools\/pause_when_loading_devtools.html\";\nconst char kPauseWhenScriptIsRunning[] =\n \"files\/devtools\/pause_when_script_is_running.html\";\nconst char kPageWithContentScript[] =\n \"files\/devtools\/page_with_content_script.html\";\n\n\nclass DevToolsSanityTest : public InProcessBrowserTest {\n public:\n DevToolsSanityTest() {\n set_show_window(true);\n EnableDOMAutomation();\n }\n\n protected:\n void RunTest(const std::string& test_name, const std::string& test_page) {\n OpenDevToolsWindow(test_page);\n std::string result;\n\n \/\/ At first check that JavaScript part of the front-end is loaded by\n \/\/ checking that global variable uiTests exists(it's created after all js\n \/\/ files have been loaded) and has runTest method.\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"'' + (window.uiTests && (typeof uiTests.runTest)));\",\n &result));\n\n if (result == \"function\") {\n ASSERT_TRUE(\n ui_test_utils::ExecuteJavaScriptAndExtractString(\n client_contents_->render_view_host(),\n L\"\",\n UTF8ToWide(StringPrintf(\"uiTests.runTest('%s')\",\n test_name.c_str())),\n &result));\n EXPECT_EQ(\"[OK]\", result);\n } else {\n FAIL() << \"DevTools front-end is broken.\";\n }\n CloseDevToolsWindow();\n }\n\n void OpenDevToolsWindow(const std::string& test_page) {\n ASSERT_TRUE(test_server()->Start());\n GURL url = test_server()->GetURL(test_page);\n ui_test_utils::NavigateToURL(browser(), url);\n\n inspected_rvh_ = GetInspectedTab()->render_view_host();\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n devtools_manager->OpenDevToolsWindow(inspected_rvh_);\n\n DevToolsClientHost* client_host =\n devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);\n window_ = client_host->AsDevToolsWindow();\n RenderViewHost* client_rvh = window_->GetRenderViewHost();\n client_contents_ = client_rvh->delegate()->GetAsTabContents();\n ui_test_utils::WaitForNavigation(&client_contents_->controller());\n }\n\n TabContents* GetInspectedTab() {\n return browser()->GetTabContentsAt(0);\n }\n\n void CloseDevToolsWindow() {\n DevToolsManager* devtools_manager = DevToolsManager::GetInstance();\n \/\/ UnregisterDevToolsClientHostFor may destroy window_ so store the browser\n \/\/ first.\n Browser* browser = window_->browser();\n devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);\n\n \/\/ Wait only when DevToolsWindow has a browser. For docked DevTools, this\n \/\/ is NULL and we skip the wait.\n if (browser)\n BrowserClosedObserver close_observer(browser);\n }\n\n TabContents* client_contents_;\n DevToolsWindow* window_;\n RenderViewHost* inspected_rvh_;\n};\n\n\nclass CancelableQuitTask : public Task {\n public:\n explicit CancelableQuitTask(const std::string& timeout_message)\n : timeout_message_(timeout_message),\n cancelled_(false) {\n }\n\n void cancel() {\n cancelled_ = true;\n }\n\n virtual void Run() {\n if (cancelled_) {\n return;\n }\n FAIL() << timeout_message_;\n MessageLoop::current()->Quit();\n }\n\n private:\n std::string timeout_message_;\n bool cancelled_;\n};\n\n\n\/\/ Base class for DevTools tests that test devtools functionality for\n\/\/ extensions and content scripts.\nclass DevToolsExtensionDebugTest : public DevToolsSanityTest,\n public NotificationObserver {\n public:\n DevToolsExtensionDebugTest() : DevToolsSanityTest() {\n PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);\n test_extensions_dir_ = test_extensions_dir_.AppendASCII(\"devtools\");\n test_extensions_dir_ = test_extensions_dir_.AppendASCII(\"extensions\");\n }\n\n protected:\n \/\/ Load an extention from test\\data\\devtools\\extensions\\<extension_name>\n void LoadExtension(const char* extension_name) {\n FilePath path = test_extensions_dir_.AppendASCII(extension_name);\n ASSERT_TRUE(LoadExtensionFromPath(path)) << \"Failed to load extension.\";\n }\n\n private:\n bool LoadExtensionFromPath(const FilePath& path) {\n ExtensionService* service = browser()->profile()->GetExtensionService();\n size_t num_before = service->extensions()->size();\n {\n NotificationRegistrar registrar;\n registrar.Add(this, NotificationType::EXTENSION_LOADED,\n NotificationService::AllSources());\n CancelableQuitTask* delayed_quit =\n new CancelableQuitTask(\"Extension load timed out.\");\n MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,\n 4*1000);\n service->LoadExtension(path);\n ui_test_utils::RunMessageLoop();\n delayed_quit->cancel();\n }\n size_t num_after = service->extensions()->size();\n if (num_after != (num_before + 1))\n return false;\n\n return WaitForExtensionHostsToLoad();\n }\n\n bool WaitForExtensionHostsToLoad() {\n \/\/ Wait for all the extension hosts that exist to finish loading.\n \/\/ NOTE: This assumes that the extension host list is not changing while\n \/\/ this method is running.\n\n NotificationRegistrar registrar;\n registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,\n NotificationService::AllSources());\n CancelableQuitTask* delayed_quit =\n new CancelableQuitTask(\"Extension host load timed out.\");\n MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,\n 4*1000);\n\n ExtensionProcessManager* manager =\n browser()->profile()->GetExtensionProcessManager();\n for (ExtensionProcessManager::const_iterator iter = manager->begin();\n iter != manager->end();) {\n if ((*iter)->did_stop_loading())\n ++iter;\n else\n ui_test_utils::RunMessageLoop();\n }\n\n delayed_quit->cancel();\n return true;\n }\n\n void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::EXTENSION_LOADED:\n case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:\n MessageLoopForUI::current()->Quit();\n break;\n default:\n NOTREACHED();\n break;\n }\n }\n\n FilePath test_extensions_dir_;\n};\n\n\/\/ Tests heap profiler.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FAILS_TestHeapProfiler) {\n RunTest(\"testHeapProfiler\", kHeapProfilerPage);\n}\n\n\/\/ Tests scripts panel showing.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {\n RunTest(\"testShowScriptsTab\", kDebuggerTestPage);\n}\n\n\/\/ Tests that scripts tab is populated with inspected scripts even if it\n\/\/ hadn't been shown by the moment inspected paged refreshed.\n\/\/ @see http:\/\/crbug.com\/26312\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest,\n TestScriptsTabIsPopulatedOnInspectedPageRefresh) {\n \/\/ Clear inspector settings to ensure that Elements will be\n \/\/ current panel when DevTools window is open.\n GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();\n RunTest(\"testScriptsTabIsPopulatedOnInspectedPageRefresh\",\n kDebuggerTestPage);\n}\n\n\/\/ Tests that a content script is in the scripts list.\n\/\/ This test is disabled, see bug 28961.\nIN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,\n TestContentScriptIsPresent) {\n LoadExtension(\"simple_content_script\");\n RunTest(\"testContentScriptIsPresent\", kPageWithContentScript);\n}\n\n\/\/ Tests that scripts are not duplicated after Scripts Panel switch.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest,\n TestNoScriptDuplicatesOnPanelSwitch) {\n RunTest(\"testNoScriptDuplicatesOnPanelSwitch\", kDebuggerTestPage);\n}\n\n\/\/ Tests that debugger works correctly if pause event occurs when DevTools\n\/\/ frontend is being loaded.\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {\n RunTest(\"testPauseWhenLoadingDevTools\", kPauseWhenLoadingDevTools);\n}\n\n\/\/ Tests that pressing 'Pause' will pause script execution if the script\n\/\/ is already running.\n\/\/ Marked as DISABLED due to http:\/\/crbug.com\/74923\nIN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenScriptIsRunning) {\n RunTest(\"testPauseWhenScriptIsRunning\", kPauseWhenScriptIsRunning);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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\/browser\/extensions\/extension_apitest.h\"\n\n#include \"chrome\/browser\/prefs\/incognito_mode_prefs.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\n\/\/ Possible race in ChromeURLDataManager. http:\/\/crbug.com\/59198\n#if defined(OS_MACOSX) || defined(OS_LINUX)\n#define MAYBE_TabOnRemoved DISABLED_TabOnRemoved\n#else\n#define MAYBE_TabOnRemoved TabOnRemoved\n#endif\n\n\/\/ Window resizes are not completed by the time the callback happens,\n\/\/ so these tests fail on linux. http:\/\/crbug.com\/72369\n#if defined(OS_LINUX)\n#define MAYBE_FocusWindowDoesNotExitFullscreen \\\n DISABLED_FocusWindowDoesNotExitFullscreen\n#define MAYBE_UpdateWindowSizeExitsFullscreen \\\n DISABLED_UpdateWindowSizeExitsFullscreen\n#define MAYBE_UpdateWindowShowState \\\n DISABLED_UpdateWindowShowState\n#else\n#define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen\n#define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen\n#define MAYBE_UpdateWindowShowState UpdateWindowShowState\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs) {\n \/\/ The test creates a tab and checks that the URL of the new tab\n \/\/ is that of the new tab page. Make sure the pref that controls\n \/\/ this is set.\n browser()->profile()->GetPrefs()->SetBoolean(\n prefs::kHomePageIsNewTabPage, true);\n\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"crud.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs2) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"crud2.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabUpdate) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"update.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"pinned.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMove) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"move.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabEvents) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"events.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"relative_urls.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabQuery) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"query.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabHighlight) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"highlight.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"crash.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {\n ASSERT_TRUE(RunExtensionTest(\"tabs\/get_current\")) << message_;\n}\n\n\/\/ Flaky on the trybots. See http:\/\/crbug.com\/96725.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_TabConnect) {\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunExtensionTest(\"tabs\/connect\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {\n ASSERT_TRUE(RunExtensionTest(\"tabs\/on_removed\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabReload) {\n ASSERT_TRUE(RunExtensionTest(\"tabs\/reload\")) << message_;\n}\n\n\/\/ Test is timing out on linux and cros and flaky on others.\n\/\/ See http:\/\/crbug.com\/83876\n#if defined(OS_LINUX)\n#define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg\n#else\n#define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) {\n host_resolver()->AddRule(\"a.com\", \"127.0.0.1\");\n host_resolver()->AddRule(\"b.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/capture_visible_tab\",\n \"test_jpeg.html\")) << message_;\n}\n\n\/\/ Test is timing out on linux and cros and flaky on others.\n\/\/ See http:\/\/crbug.com\/83876\n#if defined(OS_LINUX)\n#define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng\n#else\n#define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) {\n host_resolver()->AddRule(\"a.com\", \"127.0.0.1\");\n host_resolver()->AddRule(\"b.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/capture_visible_tab\",\n \"test_png.html\")) << message_;\n}\n\n\/\/ Times out on non-Windows. See http:\/\/crbug.com\/80212\n#if defined(OS_WIN)\n#define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace\n#else\n#define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/capture_visible_tab\",\n \"test_race.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleFile) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/capture_visible_tab\",\n \"test_file.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleNoFile) {\n ASSERT_TRUE(RunExtensionSubtestNoFileAccess(\"tabs\/capture_visible_tab\",\n \"test_nofile.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {\n ASSERT_TRUE(RunExtensionTest(\"tabs\/on_updated\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest,\n MAYBE_FocusWindowDoesNotExitFullscreen) {\n browser()->window()->EnterFullscreen(\n GURL(), FEB_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION);\n bool is_fullscreen = browser()->window()->IsFullscreen();\n ASSERT_TRUE(RunExtensionTest(\"window_update\/focus\")) << message_;\n ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen());\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest,\n MAYBE_UpdateWindowSizeExitsFullscreen) {\n browser()->window()->EnterFullscreen(\n GURL(), FEB_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION);\n ASSERT_TRUE(RunExtensionTest(\"window_update\/sizing\")) << message_;\n ASSERT_FALSE(browser()->window()->IsFullscreen());\n}\n\n#if defined(OS_WIN) && !defined(USE_AURA)\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) {\n gfx::NativeWindow window = browser()->window()->GetNativeHandle();\n ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0);\n ASSERT_TRUE(RunExtensionTest(\"window_update\/focus\")) << message_;\n ASSERT_TRUE(::IsZoomed(window));\n}\n#endif \/\/ OS_WIN\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowShowState) {\n ASSERT_TRUE(RunExtensionTest(\"window_update\/show_state\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) {\n IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),\n IncognitoModePrefs::DISABLED);\n\n \/\/ This makes sure that creating an incognito window fails due to pref\n \/\/ (policy) being set.\n ASSERT_TRUE(RunExtensionTest(\"tabs\/incognito_disabled\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedPopup) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"get_views_popup.html\"))\n << message_;\n}\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedWindow) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"get_views_window.html\"))\n << message_;\n}\n\n\/\/ Adding a new test? Awesome. But API tests are the old hotness. The\n\/\/ new hotness is extension_test_utils. See extension_tabs_test.cc for\n\/\/ an example. We are trying to phase out many uses of API tests as\n\/\/ they tend to be flaky.\n<commit_msg>Disable failing ExtensionApiTest.Tabs<commit_after>\/\/ Copyright (c) 2011 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\/browser\/extensions\/extension_apitest.h\"\n\n#include \"chrome\/browser\/prefs\/incognito_mode_prefs.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\n\/\/ Possible race in ChromeURLDataManager. http:\/\/crbug.com\/59198\n#if defined(OS_MACOSX) || defined(OS_LINUX)\n#define MAYBE_TabOnRemoved DISABLED_TabOnRemoved\n#else\n#define MAYBE_TabOnRemoved TabOnRemoved\n#endif\n\n\/\/ Window resizes are not completed by the time the callback happens,\n\/\/ so these tests fail on linux. http:\/\/crbug.com\/72369\n#if defined(OS_LINUX)\n#define MAYBE_FocusWindowDoesNotExitFullscreen \\\n DISABLED_FocusWindowDoesNotExitFullscreen\n#define MAYBE_UpdateWindowSizeExitsFullscreen \\\n DISABLED_UpdateWindowSizeExitsFullscreen\n#define MAYBE_UpdateWindowShowState \\\n DISABLED_UpdateWindowShowState\n#else\n#define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen\n#define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen\n#define MAYBE_UpdateWindowShowState UpdateWindowShowState\n#endif\n\n\/\/ See crbug.com\/108492.\n#if defined(USE_AURA) && defined(OS_CHROMEOS)\n#define MAYBE_Tabs DISABLED_Tabs\n#else\n#define MAYBE_Tabs Tabs\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {\n \/\/ The test creates a tab and checks that the URL of the new tab\n \/\/ is that of the new tab page. Make sure the pref that controls\n \/\/ this is set.\n browser()->profile()->GetPrefs()->SetBoolean(\n prefs::kHomePageIsNewTabPage, true);\n\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"crud.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs2) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"crud2.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabUpdate) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"update.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"pinned.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMove) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"move.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabEvents) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"events.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"relative_urls.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabQuery) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"query.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabHighlight) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"highlight.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"crash.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {\n ASSERT_TRUE(RunExtensionTest(\"tabs\/get_current\")) << message_;\n}\n\n\/\/ Flaky on the trybots. See http:\/\/crbug.com\/96725.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_TabConnect) {\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunExtensionTest(\"tabs\/connect\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {\n ASSERT_TRUE(RunExtensionTest(\"tabs\/on_removed\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabReload) {\n ASSERT_TRUE(RunExtensionTest(\"tabs\/reload\")) << message_;\n}\n\n\/\/ Test is timing out on linux and cros and flaky on others.\n\/\/ See http:\/\/crbug.com\/83876\n#if defined(OS_LINUX)\n#define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg\n#else\n#define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) {\n host_resolver()->AddRule(\"a.com\", \"127.0.0.1\");\n host_resolver()->AddRule(\"b.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/capture_visible_tab\",\n \"test_jpeg.html\")) << message_;\n}\n\n\/\/ Test is timing out on linux and cros and flaky on others.\n\/\/ See http:\/\/crbug.com\/83876\n#if defined(OS_LINUX)\n#define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng\n#else\n#define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) {\n host_resolver()->AddRule(\"a.com\", \"127.0.0.1\");\n host_resolver()->AddRule(\"b.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/capture_visible_tab\",\n \"test_png.html\")) << message_;\n}\n\n\/\/ Times out on non-Windows. See http:\/\/crbug.com\/80212\n#if defined(OS_WIN)\n#define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace\n#else\n#define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/capture_visible_tab\",\n \"test_race.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleFile) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/capture_visible_tab\",\n \"test_file.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleNoFile) {\n ASSERT_TRUE(RunExtensionSubtestNoFileAccess(\"tabs\/capture_visible_tab\",\n \"test_nofile.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {\n ASSERT_TRUE(RunExtensionTest(\"tabs\/on_updated\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest,\n MAYBE_FocusWindowDoesNotExitFullscreen) {\n browser()->window()->EnterFullscreen(\n GURL(), FEB_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION);\n bool is_fullscreen = browser()->window()->IsFullscreen();\n ASSERT_TRUE(RunExtensionTest(\"window_update\/focus\")) << message_;\n ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen());\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest,\n MAYBE_UpdateWindowSizeExitsFullscreen) {\n browser()->window()->EnterFullscreen(\n GURL(), FEB_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION);\n ASSERT_TRUE(RunExtensionTest(\"window_update\/sizing\")) << message_;\n ASSERT_FALSE(browser()->window()->IsFullscreen());\n}\n\n#if defined(OS_WIN) && !defined(USE_AURA)\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) {\n gfx::NativeWindow window = browser()->window()->GetNativeHandle();\n ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0);\n ASSERT_TRUE(RunExtensionTest(\"window_update\/focus\")) << message_;\n ASSERT_TRUE(::IsZoomed(window));\n}\n#endif \/\/ OS_WIN\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowShowState) {\n ASSERT_TRUE(RunExtensionTest(\"window_update\/show_state\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) {\n IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),\n IncognitoModePrefs::DISABLED);\n\n \/\/ This makes sure that creating an incognito window fails due to pref\n \/\/ (policy) being set.\n ASSERT_TRUE(RunExtensionTest(\"tabs\/incognito_disabled\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedPopup) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"get_views_popup.html\"))\n << message_;\n}\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedWindow) {\n ASSERT_TRUE(RunExtensionSubtest(\"tabs\/basics\", \"get_views_window.html\"))\n << message_;\n}\n\n\/\/ Adding a new test? Awesome. But API tests are the old hotness. The\n\/\/ new hotness is extension_test_utils. See extension_tabs_test.cc for\n\/\/ an example. We are trying to phase out many uses of API tests as\n\/\/ they tend to be flaky.\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Add more privacy prefs<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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\/browser\/plugin_installer_infobar_delegate.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n#include \"grit\/theme_resources.h\"\n#include \"webkit\/plugins\/npapi\/default_plugin_shared.h\"\n\nPluginInstallerInfoBarDelegate::PluginInstallerInfoBarDelegate(\n TabContents* tab_contents)\n : ConfirmInfoBarDelegate(tab_contents),\n tab_contents_(tab_contents) {\n}\n\nPluginInstallerInfoBarDelegate::~PluginInstallerInfoBarDelegate() {\n \/\/ Remove any InfoBars we may be showing.\n tab_contents_->RemoveInfoBar(this);\n}\n\nvoid PluginInstallerInfoBarDelegate::OnMissingPluginStatus(int status) {\n switch (status) {\n case webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE: {\n tab_contents_->AddInfoBar(this);\n break;\n }\n case webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD: {\n \/\/ Hide the InfoBar if user already started download\/install of the\n \/\/ missing plugin.\n tab_contents_->RemoveInfoBar(this);\n break;\n }\n default: {\n NOTREACHED();\n break;\n }\n }\n}\n\nSkBitmap* PluginInstallerInfoBarDelegate::GetIcon() const {\n return ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_PLUGIN_INSTALL);\n}\n\nstring16 PluginInstallerInfoBarDelegate::GetMessageText() const {\n return l10n_util::GetStringUTF16(IDS_PLUGININSTALLER_MISSINGPLUGIN_PROMPT);\n}\n\nint PluginInstallerInfoBarDelegate::GetButtons() const {\n return BUTTON_OK;\n}\n\nstring16 PluginInstallerInfoBarDelegate::GetButtonLabel(\n InfoBarButton button) const {\n DCHECK_EQ(BUTTON_OK, button);\n return l10n_util::GetStringUTF16(IDS_PLUGININSTALLER_INSTALLPLUGIN_BUTTON);\n}\n\nbool PluginInstallerInfoBarDelegate::Accept() {\n tab_contents_->render_view_host()->InstallMissingPlugin();\n return true;\n}\n\nstring16 PluginInstallerInfoBarDelegate::GetLinkText() {\n return l10n_util::GetStringUTF16(IDS_PLUGININSTALLER_PROBLEMSINSTALLING);\n}\n\nbool PluginInstallerInfoBarDelegate::LinkClicked(\n WindowOpenDisposition disposition) {\n \/\/ Ignore the click dispostion and always open in a new top level tab.\n static const char kLearnMorePluginInstallerUrl[] = \"http:\/\/www.google.com\/\"\n \"support\/chrome\/bin\/answer.py?answer=95697&topic=14687\";\n tab_contents_->OpenURL(GURL(kLearnMorePluginInstallerUrl), GURL(),\n NEW_FOREGROUND_TAB, PageTransition::LINK);\n return false;\n}\n<commit_msg>Fix build break<commit_after>\/\/ Copyright (c) 2011 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\/browser\/plugin_installer_infobar_delegate.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/plugins\/npapi\/default_plugin_shared.h\"\n\nPluginInstallerInfoBarDelegate::PluginInstallerInfoBarDelegate(\n TabContents* tab_contents)\n : ConfirmInfoBarDelegate(tab_contents),\n tab_contents_(tab_contents) {\n}\n\nPluginInstallerInfoBarDelegate::~PluginInstallerInfoBarDelegate() {\n \/\/ Remove any InfoBars we may be showing.\n tab_contents_->RemoveInfoBar(this);\n}\n\nvoid PluginInstallerInfoBarDelegate::OnMissingPluginStatus(int status) {\n switch (status) {\n case webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE: {\n tab_contents_->AddInfoBar(this);\n break;\n }\n case webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD: {\n \/\/ Hide the InfoBar if user already started download\/install of the\n \/\/ missing plugin.\n tab_contents_->RemoveInfoBar(this);\n break;\n }\n default: {\n NOTREACHED();\n break;\n }\n }\n}\n\nSkBitmap* PluginInstallerInfoBarDelegate::GetIcon() const {\n return ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_PLUGIN_INSTALL);\n}\n\nstring16 PluginInstallerInfoBarDelegate::GetMessageText() const {\n return l10n_util::GetStringUTF16(IDS_PLUGININSTALLER_MISSINGPLUGIN_PROMPT);\n}\n\nint PluginInstallerInfoBarDelegate::GetButtons() const {\n return BUTTON_OK;\n}\n\nstring16 PluginInstallerInfoBarDelegate::GetButtonLabel(\n InfoBarButton button) const {\n DCHECK_EQ(BUTTON_OK, button);\n return l10n_util::GetStringUTF16(IDS_PLUGININSTALLER_INSTALLPLUGIN_BUTTON);\n}\n\nbool PluginInstallerInfoBarDelegate::Accept() {\n tab_contents_->render_view_host()->InstallMissingPlugin();\n return true;\n}\n\nstring16 PluginInstallerInfoBarDelegate::GetLinkText() {\n return l10n_util::GetStringUTF16(IDS_PLUGININSTALLER_PROBLEMSINSTALLING);\n}\n\nbool PluginInstallerInfoBarDelegate::LinkClicked(\n WindowOpenDisposition disposition) {\n \/\/ Ignore the click dispostion and always open in a new top level tab.\n static const char kLearnMorePluginInstallerUrl[] = \"http:\/\/www.google.com\/\"\n \"support\/chrome\/bin\/answer.py?answer=95697&topic=14687\";\n tab_contents_->OpenURL(GURL(kLearnMorePluginInstallerUrl), GURL(),\n NEW_FOREGROUND_TAB, PageTransition::LINK);\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Removing a synchronous pause that reduces impact on the IO thread<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Avoid a possible race between entry deletion and a command, in the event a renderer was sending out-of-order messages.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"chrome\/browser\/renderer_host\/render_process_host.h\"\n\n#include \"base\/rand_util.h\"\n#include \"base\/sys_info.h\"\n#include \"chrome\/browser\/child_process_security_policy.h\"\n#include \"chrome\/common\/child_process_info.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/notification_service.h\"\n\nnamespace {\n\nsize_t GetMaxRendererProcessCount() {\n \/\/ Defines the maximum number of renderer processes according to the\n \/\/ amount of installed memory as reported by the OS. The table\n \/\/ values are calculated by assuming that you want the renderers to\n \/\/ use half of the installed ram and assuming that each tab uses\n \/\/ ~40MB, however the curve is not linear but piecewise linear with\n \/\/ interleaved slopes of 3 and 2.\n \/\/ If you modify this table you need to adjust browser\\browser_uitest.cc\n \/\/ to match the expected number of processes.\n\n static const size_t kMaxRenderersByRamTier[] = {\n 3, \/\/ less than 256MB\n 6, \/\/ 256MB\n 9, \/\/ 512MB\n 12, \/\/ 768MB\n 14, \/\/ 1024MB\n 18, \/\/ 1280MB\n 20, \/\/ 1536MB\n 22, \/\/ 1792MB\n 24, \/\/ 2048MB\n 26, \/\/ 2304MB\n 29, \/\/ 2560MB\n 32, \/\/ 2816MB\n 35, \/\/ 3072MB\n 38, \/\/ 3328MB\n 40 \/\/ 3584MB\n };\n\n static size_t max_count = 0;\n if (!max_count) {\n size_t memory_tier = base::SysInfo::AmountOfPhysicalMemoryMB() \/ 256;\n if (memory_tier >= arraysize(kMaxRenderersByRamTier))\n max_count = chrome::kMaxRendererProcessCount;\n else\n max_count = kMaxRenderersByRamTier[memory_tier];\n }\n return max_count;\n}\n\n\/\/ Returns true if the given host is suitable for launching a new view\n\/\/ associated with the given profile.\nstatic bool IsSuitableHost(RenderProcessHost* host, Profile* profile,\n RenderProcessHost::Type type) {\n if (host->profile() != profile)\n return false;\n\n RenderProcessHost::Type host_type = RenderProcessHost::TYPE_NORMAL;\n if (ChildProcessSecurityPolicy::GetInstance()->HasDOMUIBindings(host->id()))\n host_type = RenderProcessHost::TYPE_DOMUI;\n if (ChildProcessSecurityPolicy::GetInstance()->\n HasExtensionBindings(host->id()))\n host_type = RenderProcessHost::TYPE_EXTENSION;\n\n return host_type == type;\n}\n\n\/\/ the global list of all renderer processes\nIDMap<RenderProcessHost> all_hosts;\n\n} \/\/ namespace\n\nbool RenderProcessHost::run_renderer_in_process_ = false;\n\nRenderProcessHost::RenderProcessHost(Profile* profile)\n : max_page_id_(-1),\n fast_shutdown_started_(false),\n id_(ChildProcessInfo::GenerateChildProcessUniqueId()),\n profile_(profile),\n sudden_termination_allowed_(true),\n ignore_input_events_(false) {\n all_hosts.AddWithID(this, id());\n all_hosts.set_check_on_null_data(true);\n}\n\nRenderProcessHost::~RenderProcessHost() {\n all_hosts.Remove(id());\n}\n\nvoid RenderProcessHost::Attach(IPC::Channel::Listener* listener,\n int routing_id) {\n listeners_.AddWithID(listener, routing_id);\n}\n\nvoid RenderProcessHost::Release(int listener_id) {\n DCHECK(listeners_.Lookup(listener_id) != NULL);\n listeners_.Remove(listener_id);\n\n \/\/ Make sure that all associated resource requests are stopped.\n CancelResourceRequests(listener_id);\n\n \/\/ When no other owners of this object, we can delete ourselves\n if (listeners_.IsEmpty()) {\n NotificationService::current()->Notify(\n NotificationType::RENDERER_PROCESS_TERMINATED,\n Source<RenderProcessHost>(this), NotificationService::NoDetails());\n MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n }\n}\n\nvoid RenderProcessHost::ReportExpectingClose(int32 listener_id) {\n listeners_expecting_close_.insert(listener_id);\n}\n\nvoid RenderProcessHost::UpdateMaxPageID(int32 page_id) {\n if (page_id > max_page_id_)\n max_page_id_ = page_id;\n}\n\nbool RenderProcessHost::FastShutdownForPageCount(size_t count) {\n if (listeners_.size() == count)\n return FastShutdownIfPossible();\n return false;\n}\n\n\/\/ static\nRenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {\n return iterator(&all_hosts);\n}\n\n\/\/ static\nRenderProcessHost* RenderProcessHost::FromID(int render_process_id) {\n return all_hosts.Lookup(render_process_id);\n}\n\n\/\/ static\nbool RenderProcessHost::ShouldTryToUseExistingProcessHost() {\n size_t renderer_process_count = all_hosts.size();\n\n \/\/ NOTE: Sometimes it's necessary to create more render processes than\n \/\/ GetMaxRendererProcessCount(), for instance when we want to create\n \/\/ a renderer process for a profile that has no existing renderers.\n \/\/ This is OK in moderation, since the GetMaxRendererProcessCount()\n \/\/ is conservative.\n\n return run_renderer_in_process() ||\n (renderer_process_count >= GetMaxRendererProcessCount());\n}\n\n\/\/ static\nRenderProcessHost* RenderProcessHost::GetExistingProcessHost(Profile* profile,\n Type type) {\n \/\/ First figure out which existing renderers we can use.\n std::vector<RenderProcessHost*> suitable_renderers;\n suitable_renderers.reserve(all_hosts.size());\n\n iterator iter(AllHostsIterator());\n while (!iter.IsAtEnd()) {\n if (run_renderer_in_process() ||\n IsSuitableHost(iter.GetCurrentValue(), profile, type))\n suitable_renderers.push_back(iter.GetCurrentValue());\n\n iter.Advance();\n }\n\n \/\/ Now pick a random suitable renderer, if we have any.\n if (!suitable_renderers.empty()) {\n int suitable_count = static_cast<int>(suitable_renderers.size());\n int random_index = base::RandInt(0, suitable_count - 1);\n return suitable_renderers[random_index];\n }\n\n return NULL;\n}\n<commit_msg>Remove the RenderProcessHost from the list of renderer processes when we call DeleteSoon, not in the destructor. Otherewise the process can be reused in the meantime. This matches what we do in ChildProcessHost.<commit_after>\/\/ 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 \"chrome\/browser\/renderer_host\/render_process_host.h\"\n\n#include \"base\/rand_util.h\"\n#include \"base\/sys_info.h\"\n#include \"chrome\/browser\/child_process_security_policy.h\"\n#include \"chrome\/common\/child_process_info.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/notification_service.h\"\n\nnamespace {\n\nsize_t GetMaxRendererProcessCount() {\n \/\/ Defines the maximum number of renderer processes according to the\n \/\/ amount of installed memory as reported by the OS. The table\n \/\/ values are calculated by assuming that you want the renderers to\n \/\/ use half of the installed ram and assuming that each tab uses\n \/\/ ~40MB, however the curve is not linear but piecewise linear with\n \/\/ interleaved slopes of 3 and 2.\n \/\/ If you modify this table you need to adjust browser\\browser_uitest.cc\n \/\/ to match the expected number of processes.\n\n static const size_t kMaxRenderersByRamTier[] = {\n 3, \/\/ less than 256MB\n 6, \/\/ 256MB\n 9, \/\/ 512MB\n 12, \/\/ 768MB\n 14, \/\/ 1024MB\n 18, \/\/ 1280MB\n 20, \/\/ 1536MB\n 22, \/\/ 1792MB\n 24, \/\/ 2048MB\n 26, \/\/ 2304MB\n 29, \/\/ 2560MB\n 32, \/\/ 2816MB\n 35, \/\/ 3072MB\n 38, \/\/ 3328MB\n 40 \/\/ 3584MB\n };\n\n static size_t max_count = 0;\n if (!max_count) {\n size_t memory_tier = base::SysInfo::AmountOfPhysicalMemoryMB() \/ 256;\n if (memory_tier >= arraysize(kMaxRenderersByRamTier))\n max_count = chrome::kMaxRendererProcessCount;\n else\n max_count = kMaxRenderersByRamTier[memory_tier];\n }\n return max_count;\n}\n\n\/\/ Returns true if the given host is suitable for launching a new view\n\/\/ associated with the given profile.\nstatic bool IsSuitableHost(RenderProcessHost* host, Profile* profile,\n RenderProcessHost::Type type) {\n if (host->profile() != profile)\n return false;\n\n RenderProcessHost::Type host_type = RenderProcessHost::TYPE_NORMAL;\n if (ChildProcessSecurityPolicy::GetInstance()->HasDOMUIBindings(host->id()))\n host_type = RenderProcessHost::TYPE_DOMUI;\n if (ChildProcessSecurityPolicy::GetInstance()->\n HasExtensionBindings(host->id()))\n host_type = RenderProcessHost::TYPE_EXTENSION;\n\n return host_type == type;\n}\n\n\/\/ the global list of all renderer processes\nIDMap<RenderProcessHost> all_hosts;\n\n} \/\/ namespace\n\nbool RenderProcessHost::run_renderer_in_process_ = false;\n\nRenderProcessHost::RenderProcessHost(Profile* profile)\n : max_page_id_(-1),\n fast_shutdown_started_(false),\n id_(ChildProcessInfo::GenerateChildProcessUniqueId()),\n profile_(profile),\n sudden_termination_allowed_(true),\n ignore_input_events_(false) {\n all_hosts.AddWithID(this, id());\n all_hosts.set_check_on_null_data(true);\n}\n\nRenderProcessHost::~RenderProcessHost() {\n \/\/ In unit tests, Release() might not have been called.\n if (all_hosts.Lookup(id()))\n all_hosts.Remove(id());\n}\n\nvoid RenderProcessHost::Attach(IPC::Channel::Listener* listener,\n int routing_id) {\n listeners_.AddWithID(listener, routing_id);\n}\n\nvoid RenderProcessHost::Release(int listener_id) {\n DCHECK(listeners_.Lookup(listener_id) != NULL);\n listeners_.Remove(listener_id);\n\n \/\/ Make sure that all associated resource requests are stopped.\n CancelResourceRequests(listener_id);\n\n \/\/ When no other owners of this object, we can delete ourselves\n if (listeners_.IsEmpty()) {\n NotificationService::current()->Notify(\n NotificationType::RENDERER_PROCESS_TERMINATED,\n Source<RenderProcessHost>(this), NotificationService::NoDetails());\n MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n\n \/\/ Remove ourself from the list of renderer processes so that we can't be\n \/\/ reused in between now and when the Delete task runs.\n all_hosts.Remove(id());\n }\n}\n\nvoid RenderProcessHost::ReportExpectingClose(int32 listener_id) {\n listeners_expecting_close_.insert(listener_id);\n}\n\nvoid RenderProcessHost::UpdateMaxPageID(int32 page_id) {\n if (page_id > max_page_id_)\n max_page_id_ = page_id;\n}\n\nbool RenderProcessHost::FastShutdownForPageCount(size_t count) {\n if (listeners_.size() == count)\n return FastShutdownIfPossible();\n return false;\n}\n\n\/\/ static\nRenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {\n return iterator(&all_hosts);\n}\n\n\/\/ static\nRenderProcessHost* RenderProcessHost::FromID(int render_process_id) {\n return all_hosts.Lookup(render_process_id);\n}\n\n\/\/ static\nbool RenderProcessHost::ShouldTryToUseExistingProcessHost() {\n size_t renderer_process_count = all_hosts.size();\n\n \/\/ NOTE: Sometimes it's necessary to create more render processes than\n \/\/ GetMaxRendererProcessCount(), for instance when we want to create\n \/\/ a renderer process for a profile that has no existing renderers.\n \/\/ This is OK in moderation, since the GetMaxRendererProcessCount()\n \/\/ is conservative.\n\n return run_renderer_in_process() ||\n (renderer_process_count >= GetMaxRendererProcessCount());\n}\n\n\/\/ static\nRenderProcessHost* RenderProcessHost::GetExistingProcessHost(Profile* profile,\n Type type) {\n \/\/ First figure out which existing renderers we can use.\n std::vector<RenderProcessHost*> suitable_renderers;\n suitable_renderers.reserve(all_hosts.size());\n\n iterator iter(AllHostsIterator());\n while (!iter.IsAtEnd()) {\n if (run_renderer_in_process() ||\n IsSuitableHost(iter.GetCurrentValue(), profile, type))\n suitable_renderers.push_back(iter.GetCurrentValue());\n\n iter.Advance();\n }\n\n \/\/ Now pick a random suitable renderer, if we have any.\n if (!suitable_renderers.empty()) {\n int suitable_count = static_cast<int>(suitable_renderers.size());\n int random_index = base::RandInt(0, suitable_count - 1);\n return suitable_renderers[random_index];\n }\n\n return NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KAddressbook.\n Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>\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; 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. 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <kactioncollection.h>\n#include <kconfig.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kservicetypetrader.h>\n\n#include <QSignalMapper>\n#include <QTimer>\n#include <ktoggleaction.h>\n#include <kvbox.h>\n\n#include \"addresseeeditorextension.h\"\n#include \"core.h\"\n#include \"kabprefs.h\"\n\n#include \"extensionmanager.h\"\n\nExtensionManager::ExtensionManager( KAB::Core *core, QWidget *parent )\n : KHBox( parent ), mCore( core ), mCurrentExtensionWidget( 0 ),\n mMapper( 0 )\n{\n createExtensionWidgets();\n\n mActionCollection = new KActionCollection( this);\n mActionCollection->setObjectName( \"ActionCollection\" );\n\n QTimer::singleShot( 0, this, SLOT( createActions() ) );\n}\n\nExtensionManager::~ExtensionManager()\n{\n}\n\nvoid ExtensionManager::restoreSettings()\n{\n for ( int index = 0; index < mExtensionList.size(); ++index ) {\n ExtensionData data = mExtensionList[ index ];\n if ( data.identifier == KABPrefs::instance()->currentExtension() ) {\n KToggleAction *action = mActionList.size() > index ? static_cast<KToggleAction*>( mActionList.at( index ) ) : 0;\n if ( action )\n action->setChecked( true );\n setActiveExtension( index );\n return;\n }\n }\n\n if ( mActionList.first() )\n static_cast<KToggleAction*>( mActionList.first() )->setChecked( true );\n setActiveExtension( 0 );\n}\n\nvoid ExtensionManager::saveSettings()\n{\n QAction *action;\n int index = 0;\n for (int i = 0; i < mActionList.size(); ++i) {\n action = mActionList.at(i);\n if ( static_cast<KToggleAction*>( action )->isChecked() ) {\n index = i;\n break;\n }\n }\n Q_ASSERT( index < mExtensionList.size() );\n\n KABPrefs::instance()->setCurrentExtension( mExtensionList[ index ].identifier );\n}\n\nvoid ExtensionManager::reconfigure()\n{\n saveSettings();\n createExtensionWidgets();\n createActions();\n restoreSettings();\n}\n\nbool ExtensionManager::isQuickEditVisible() const\n{\n return ( mCurrentExtensionWidget &&\n mCurrentExtensionWidget->identifier() == \"contact_editor\" );\n}\n\nvoid ExtensionManager::setSelectionChanged()\n{\n if ( mCurrentExtensionWidget )\n mCurrentExtensionWidget->contactsSelectionChanged();\n}\n\nvoid ExtensionManager::setActiveExtension( int id )\n{\n if ( id == 0 ) {\n hide();\n if ( mCurrentExtensionWidget )\n mCurrentExtensionWidget->hide();\n mCurrentExtensionWidget = 0;\n } else if ( id > 0 ) {\n if ( mCurrentExtensionWidget )\n mCurrentExtensionWidget->hide();\n\n mCurrentExtensionWidget = mExtensionList[ id ].widget;\n if ( mCurrentExtensionWidget ) {\n show();\n mCurrentExtensionWidget->show();\n mCurrentExtensionWidget->contactsSelectionChanged();\n } else {\n hide();\n mCurrentExtensionWidget = 0;\n }\n }\n}\n\nvoid ExtensionManager::createActions()\n{\n mCore->guiClient()->unplugActionList( \"extensions_list\" );\n qDeleteAll( mActionList );\n mActionList.clear();\n\n delete mMapper;\n mMapper = new QSignalMapper( this );\n mMapper->setObjectName( \"SignalMapper\" );\n connect( mMapper, SIGNAL( mapped( int ) ),\n this, SLOT( setActiveExtension( int ) ) );\n\n int actionCounter = 0;\n ExtensionData::List::ConstIterator it;\n QActionGroup* extensionGroup = new QActionGroup(this);\n for ( it = mExtensionList.begin(); it != mExtensionList.end(); ++it ) {\n ExtensionData data = *it;\n KToggleAction *action = mActionCollection->add<KToggleAction>( QString( data.identifier + \"_extension\" ) );\n action->setText( data.title );\n connect(action, SIGNAL(triggered(bool) ), mMapper, SLOT( map() ));\n action->setActionGroup( extensionGroup );\n mMapper->setMapping( action, actionCounter++ );\n mActionList.append( action );\n\n if ( data.widget == mCurrentExtensionWidget )\n action->setChecked( true );\n }\n\n mCore->guiClient()->plugActionList( \"extensions_list\", mActionList );\n\n if ( mCurrentExtensionWidget == 0 && mActionList.first() )\n static_cast<KToggleAction*>( mActionList.first() )->setChecked( true );\n}\n\nvoid ExtensionManager::createExtensionWidgets()\n{\n \/\/ clean up\n ExtensionData::List::ConstIterator dataIt;\n for ( dataIt = mExtensionList.begin(); dataIt != mExtensionList.end(); ++dataIt )\n delete (*dataIt).widget;\n mExtensionList.clear();\n\n KAB::ExtensionWidget *wdg = 0;\n\n {\n \/\/ add 'None' entry\n ExtensionData data;\n data.identifier = \"none\";\n data.title = i18n( \"None\" );\n data.widget = 0;\n mExtensionList.append( data );\n }\n\n {\n \/\/ add addressee editor as default\n wdg = new AddresseeEditorExtension( mCore, this );\n wdg->hide();\n\n connect( wdg, SIGNAL( modified( const KABC::Addressee::List& ) ),\n SIGNAL( modified( const KABC::Addressee::List& ) ) );\n connect( wdg, SIGNAL( deleted( const QStringList& ) ),\n SIGNAL( deleted( const QStringList& ) ) );\n\n ExtensionData data;\n data.identifier = wdg->identifier();\n data.title = wdg->title();\n data.widget = wdg;\n mExtensionList.append( data );\n }\n\n \/\/ load the other extensions\n const KService::List plugins = KServiceTypeTrader::self()->query( \"KAddressBook\/Extension\",\n QString( \"[X-KDE-KAddressBook-ExtensionPluginVersion] == %1\" ).arg( KAB_EXTENSIONWIDGET_PLUGIN_VERSION ) );\n\n KService::List::ConstIterator it;\n for ( it = plugins.begin(); it != plugins.end(); ++it ) {\n KLibFactory *factory = KLibLoader::self()->factory( (*it)->library().toLatin1() );\n if ( !factory ) {\n kDebug(5720) <<\"ExtensionManager::loadExtensions(): Factory creation failed\";\n continue;\n }\n\n KAB::ExtensionFactory *extensionFactory = static_cast<KAB::ExtensionFactory*>( factory );\n\n if ( !extensionFactory ) {\n kDebug(5720) <<\"ExtensionManager::loadExtensions(): Cast failed\";\n continue;\n }\n\n wdg = extensionFactory->extension( mCore, this );\n if ( wdg ) {\n wdg->hide();\n connect( wdg, SIGNAL( modified( const KABC::Addressee::List& ) ),\n SIGNAL( modified( const KABC::Addressee::List& ) ) );\n connect( wdg, SIGNAL( deleted( const QStringList& ) ),\n SIGNAL( deleted( const QStringList& ) ) );\n\n ExtensionData data;\n data.identifier = wdg->identifier();\n data.title = wdg->title();\n data.widget = wdg;\n mExtensionList.append( data );\n }\n }\n\n mCurrentExtensionWidget = 0;\n}\n\n#include \"extensionmanager.moc\"\n<commit_msg>- Fixed crash: QList::first() asserts on empty lists. Probably a porting issue, Qt3 QPtrList::first() did just return 0 in such cases.<commit_after>\/*\n This file is part of KAddressbook.\n Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>\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; 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. 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, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <kactioncollection.h>\n#include <kconfig.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kservicetypetrader.h>\n\n#include <QSignalMapper>\n#include <QTimer>\n#include <ktoggleaction.h>\n#include <kvbox.h>\n\n#include \"addresseeeditorextension.h\"\n#include \"core.h\"\n#include \"kabprefs.h\"\n\n#include \"extensionmanager.h\"\n\nExtensionManager::ExtensionManager( KAB::Core *core, QWidget *parent )\n : KHBox( parent ), mCore( core ), mCurrentExtensionWidget( 0 ),\n mMapper( 0 )\n{\n createExtensionWidgets();\n\n mActionCollection = new KActionCollection( this);\n mActionCollection->setObjectName( \"ActionCollection\" );\n\n QTimer::singleShot( 0, this, SLOT( createActions() ) );\n}\n\nExtensionManager::~ExtensionManager()\n{\n}\n\nvoid ExtensionManager::restoreSettings()\n{\n for ( int index = 0; index < mExtensionList.size(); ++index ) {\n ExtensionData data = mExtensionList[ index ];\n if ( data.identifier == KABPrefs::instance()->currentExtension() ) {\n KToggleAction *action = mActionList.size() > index ? static_cast<KToggleAction*>( mActionList.at( index ) ) : 0;\n if ( action )\n action->setChecked( true );\n setActiveExtension( index );\n return;\n }\n }\n\n if ( !mActionList.isEmpty() && mActionList.first() )\n static_cast<KToggleAction*>( mActionList.first() )->setChecked( true );\n setActiveExtension( 0 );\n}\n\nvoid ExtensionManager::saveSettings()\n{\n QAction *action;\n int index = 0;\n for (int i = 0; i < mActionList.size(); ++i) {\n action = mActionList.at(i);\n if ( static_cast<KToggleAction*>( action )->isChecked() ) {\n index = i;\n break;\n }\n }\n Q_ASSERT( index < mExtensionList.size() );\n\n KABPrefs::instance()->setCurrentExtension( mExtensionList[ index ].identifier );\n}\n\nvoid ExtensionManager::reconfigure()\n{\n saveSettings();\n createExtensionWidgets();\n createActions();\n restoreSettings();\n}\n\nbool ExtensionManager::isQuickEditVisible() const\n{\n return ( mCurrentExtensionWidget &&\n mCurrentExtensionWidget->identifier() == \"contact_editor\" );\n}\n\nvoid ExtensionManager::setSelectionChanged()\n{\n if ( mCurrentExtensionWidget )\n mCurrentExtensionWidget->contactsSelectionChanged();\n}\n\nvoid ExtensionManager::setActiveExtension( int id )\n{\n if ( id == 0 ) {\n hide();\n if ( mCurrentExtensionWidget )\n mCurrentExtensionWidget->hide();\n mCurrentExtensionWidget = 0;\n } else if ( id > 0 ) {\n if ( mCurrentExtensionWidget )\n mCurrentExtensionWidget->hide();\n\n mCurrentExtensionWidget = mExtensionList[ id ].widget;\n if ( mCurrentExtensionWidget ) {\n show();\n mCurrentExtensionWidget->show();\n mCurrentExtensionWidget->contactsSelectionChanged();\n } else {\n hide();\n mCurrentExtensionWidget = 0;\n }\n }\n}\n\nvoid ExtensionManager::createActions()\n{\n mCore->guiClient()->unplugActionList( \"extensions_list\" );\n qDeleteAll( mActionList );\n mActionList.clear();\n\n delete mMapper;\n mMapper = new QSignalMapper( this );\n mMapper->setObjectName( \"SignalMapper\" );\n connect( mMapper, SIGNAL( mapped( int ) ),\n this, SLOT( setActiveExtension( int ) ) );\n\n int actionCounter = 0;\n ExtensionData::List::ConstIterator it;\n QActionGroup* extensionGroup = new QActionGroup(this);\n for ( it = mExtensionList.begin(); it != mExtensionList.end(); ++it ) {\n ExtensionData data = *it;\n KToggleAction *action = mActionCollection->add<KToggleAction>( QString( data.identifier + \"_extension\" ) );\n action->setText( data.title );\n connect(action, SIGNAL(triggered(bool) ), mMapper, SLOT( map() ));\n action->setActionGroup( extensionGroup );\n mMapper->setMapping( action, actionCounter++ );\n mActionList.append( action );\n\n if ( data.widget == mCurrentExtensionWidget )\n action->setChecked( true );\n }\n\n mCore->guiClient()->plugActionList( \"extensions_list\", mActionList );\n\n if ( mCurrentExtensionWidget == 0 && !mActionList.isEmpty() && mActionList.first() )\n static_cast<KToggleAction*>( mActionList.first() )->setChecked( true );\n}\n\nvoid ExtensionManager::createExtensionWidgets()\n{\n \/\/ clean up\n ExtensionData::List::ConstIterator dataIt;\n for ( dataIt = mExtensionList.begin(); dataIt != mExtensionList.end(); ++dataIt )\n delete (*dataIt).widget;\n mExtensionList.clear();\n\n KAB::ExtensionWidget *wdg = 0;\n\n {\n \/\/ add 'None' entry\n ExtensionData data;\n data.identifier = \"none\";\n data.title = i18n( \"None\" );\n data.widget = 0;\n mExtensionList.append( data );\n }\n\n {\n \/\/ add addressee editor as default\n wdg = new AddresseeEditorExtension( mCore, this );\n wdg->hide();\n\n connect( wdg, SIGNAL( modified( const KABC::Addressee::List& ) ),\n SIGNAL( modified( const KABC::Addressee::List& ) ) );\n connect( wdg, SIGNAL( deleted( const QStringList& ) ),\n SIGNAL( deleted( const QStringList& ) ) );\n\n ExtensionData data;\n data.identifier = wdg->identifier();\n data.title = wdg->title();\n data.widget = wdg;\n mExtensionList.append( data );\n }\n\n \/\/ load the other extensions\n const KService::List plugins = KServiceTypeTrader::self()->query( \"KAddressBook\/Extension\",\n QString( \"[X-KDE-KAddressBook-ExtensionPluginVersion] == %1\" ).arg( KAB_EXTENSIONWIDGET_PLUGIN_VERSION ) );\n\n KService::List::ConstIterator it;\n for ( it = plugins.begin(); it != plugins.end(); ++it ) {\n KLibFactory *factory = KLibLoader::self()->factory( (*it)->library().toLatin1() );\n if ( !factory ) {\n kDebug(5720) <<\"ExtensionManager::loadExtensions(): Factory creation failed\";\n continue;\n }\n\n KAB::ExtensionFactory *extensionFactory = static_cast<KAB::ExtensionFactory*>( factory );\n\n if ( !extensionFactory ) {\n kDebug(5720) <<\"ExtensionManager::loadExtensions(): Cast failed\";\n continue;\n }\n\n wdg = extensionFactory->extension( mCore, this );\n if ( wdg ) {\n wdg->hide();\n connect( wdg, SIGNAL( modified( const KABC::Addressee::List& ) ),\n SIGNAL( modified( const KABC::Addressee::List& ) ) );\n connect( wdg, SIGNAL( deleted( const QStringList& ) ),\n SIGNAL( deleted( const QStringList& ) ) );\n\n ExtensionData data;\n data.identifier = wdg->identifier();\n data.title = wdg->title();\n data.widget = wdg;\n mExtensionList.append( data );\n }\n }\n\n mCurrentExtensionWidget = 0;\n}\n\n#include \"extensionmanager.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2009 Brain Research Institute, Melbourne, Australia\n\n Written by J-Donald Tournier, 28\/10\/09.\n\n This file is part of MRtrix.\n\n MRtrix 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 3 of the License, or\n (at your option) any later version.\n\n MRtrix 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 MRtrix. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n\n#include \"command.h\"\n#include \"point.h\"\n#include \"math\/SH.h\"\n#include \"image\/buffer.h\"\n#include \"image\/voxel.h\"\n#include \"math\/vector.h\"\n#include \"image\/loop.h\"\n\n\nusing namespace MR; \nusing namespace App; \n\nvoid usage () {\n DESCRIPTION\n + \"generate a planar ROI.\";\n\n ARGUMENTS\n + Argument (\"point1\",\n \"a point on the plane, supplied as comma-separated \"\n \"3-vector of floating-point values, corresponding to the real\/scanner \"\n \"coordinates of the point in mm.\")\n .type_sequence_float()\n\n + Argument (\"point2\",\n \"a point on the plane, supplied as comma-separated \"\n \"3-vector of floating-point values, corresponding to the real\/scanner \"\n \"coordinates of the point in mm.\")\n .type_sequence_float()\n\n + Argument (\"point3\",\n \"a point on the plane, supplied as comma-separated \"\n \"3-vector of floating-point values, corresponding to the real\/scanner \"\n \"coordinates of the point in mm.\")\n .type_sequence_float()\n\n + Argument (\"template\",\n \"a template image used to compute the required extent of the ROI.\")\n .type_image_in()\n\n + Argument (\"ROI\", \"the output ROI image.\").type_image_out();\n\n OPTIONS\n + Option (\"vox\", \n \"the desired (isotropic) voxel size (default is same as template).\")\n + Argument (\"size\").type_float (0.0, 00.0, std::numeric_limits<float>::max());\n}\n\n\ninline Point<> get_bounds (const Point<>& corner, const Point<>& axis, const Point<>& ref, const Point<>& d1, const Point<>& d2) {\n Math::Matrix<float> M(3,3);\n Math::Vector<float> X(3);\n\n M(0,0) = d1[0]; M(0,1) = d2[0]; M(0,2) = axis[0]; \n M(1,0) = d1[1]; M(1,1) = d2[1]; M(1,2) = axis[1]; \n M(2,0) = d1[2]; M(2,1) = d2[2]; M(2,2) = axis[2]; \n\n X[0] = corner[0] - ref[0];\n X[1] = corner[1] - ref[1];\n X[2] = corner[2] - ref[2];\n\n Math::Permutation p (3);\n int signum;\n Math::LU::decomp (M, p, signum); \n Math::LU::solve (X, M, p);\n\n return Point<> (X[0], X[1], X[2]);\n}\n\n\n\ninline Point<> get_bounds (const Image::Header& header, Point<int> corner, int axis, const Point<>& ref, const Point<>& d1, const Point<>& d2) {\n const Math::Matrix<float>& T (header.transform());\n Point<> pos (T(0,3), T(1,3), T(2,3));\n for (size_t n = 0; n < 3; ++n) \n if (corner[n]) \n pos += header.dim(n) * header.vox(n) * Point<> (T(0,n), T(1,n), T(2,n));\n Point<> dir (T(0,axis), T(1,axis), T(2,axis));\n Point<> ret = get_bounds (pos, dir, ref, d1, d2);\n ret[2] \/= -header.vox (axis) * header.dim (axis);\n return ret;\n}\n\n\ninline void update_bounds (float& min1, float& min2, float& max1, float& max2, const Image::Header& header, Point<int> corner, int axis, const Point<>& ref, const Point<>& d1, const Point<>& d2) {\n Point<> bound = get_bounds (header, corner, axis, ref, d1, d2);\n if (bound[2] >= 0.0 && bound[2] <= 1.0) {\n if (min1 > bound[0]) min1 = bound[0];\n if (min2 > bound[1]) min2 = bound[1];\n if (max1 < bound[0]) max1 = bound[0];\n if (max2 < bound[1]) max2 = bound[1];\n }\n}\n\n\n\n\n\nvoid run () {\n Point<> p[3];\n for (size_t arg = 0; arg < 3; ++arg) {\n std::vector<float> V = argument[arg]; \n if (V.size() != 3) \n throw Exception (\"coordinates must contain 3 elements\");\n p[arg][0] = V[0];\n p[arg][1] = V[1];\n p[arg][2] = V[2];\n }\n\n Image::Header header (argument[3]);\n float vox = std::pow (header.vox(0)*header.vox(1)*header.vox(2), 1.0f\/3.0f);\n Options opt = get_options (\"vox\");\n if (opt.size()) \n vox = opt[0][0];\n\n\n Point<> d1 = p[1] - p[0];\n Point<> d2 = p[2] - p[0];\n d1.normalise();\n d2.normalise();\n\n d2 = d2 - d1 * d1.dot(d2);\n d2.normalise();\n\n Point<> d3 = d1.cross(d2);\n\n\n float min1 = std::numeric_limits<float>::infinity();\n float min2 = std::numeric_limits<float>::infinity();\n float max1 = -std::numeric_limits<float>::infinity();\n float max2 = -std::numeric_limits<float>::infinity();\n\n update_bounds (min1, min2, max1, max2, header, Point<int>(0,0,0), 0, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(0,0,0), 1, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(0,0,0), 2, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(1,0,0), 1, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(1,0,0), 2, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(0,1,0), 0, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(0,1,0), 2, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(0,0,1), 0, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(0,0,1), 1, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(1,1,0), 2, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(1,0,1), 1, p[0], d1, d2);\n update_bounds (min1, min2, max1, max2, header, Point<int>(0,1,1), 0, p[0], d1, d2);\n\n\n Point<> translation (p[0] + min1*d1 + min2*d2);\n\n header.transform()(0,0) = d1[0];\n header.transform()(1,0) = d1[1];\n header.transform()(2,0) = d1[2];\n\n header.transform()(0,1) = d2[0];\n header.transform()(1,1) = d2[1];\n header.transform()(2,1) = d2[2];\n\n header.transform()(0,2) = d3[0];\n header.transform()(1,2) = d3[1];\n header.transform()(2,2) = d3[2];\n\n header.transform()(0,3) = translation[0];\n header.transform()(1,3) = translation[1];\n header.transform()(2,3) = translation[2];\n\n header.set_ndim (3);\n header.dim (0) = (max1-min1) \/ vox;\n header.dim (1) = (max2-min2) \/ vox;\n header.dim (2) = 1;\n\n header.vox(0) = header.vox(1) = header.vox(2) = vox;\n\n header.datatype() = DataType::Bit;\n header.DW_scheme().clear();\n\n Image::Buffer<bool> roi_buffer (argument[4], header);\n auto roi = roi_buffer.voxel();\n for (auto i = Image::LoopInOrder (roi) (roi); i; ++i)\n roi.value() = true;\n\n}\n\n\n<commit_msg>removed roigen command<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: editsrc.hxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 17:38:09 $\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_EDITSRC_HXX\n#define SC_EDITSRC_HXX\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _SVX_UNOEDSRC_HXX\n#include <svx\/unoedsrc.hxx>\n#endif\n\n#ifndef _SFXLSTNER_HXX \/\/autogen\n#include <svtools\/lstner.hxx>\n#endif\n\n#include <memory>\n\nclass ScEditEngineDefaulter;\nclass SvxEditEngineForwarder;\n\nclass ScDocShell;\nclass ScHeaderFooterContentObj;\nclass ScCellTextData;\nclass ScHeaderFooterTextData;\nclass ScAccessibleTextData;\nclass SdrObject;\n\n\nclass ScHeaderFooterChangedHint : public SfxHint\n{\n USHORT nPart;\n\npublic:\n TYPEINFO();\n ScHeaderFooterChangedHint(USHORT nP);\n ~ScHeaderFooterChangedHint();\n\n USHORT GetPart() const { return nPart; }\n};\n\n\n\/\/ all ScSharedHeaderFooterEditSource objects for a single text share the same data\n\nclass ScSharedHeaderFooterEditSource : public SvxEditSource\n{\nprivate:\n ScHeaderFooterTextData* pTextData;\n\nprotected:\n ScHeaderFooterTextData* GetTextData() const { return pTextData; } \/\/ for ScHeaderFooterEditSource\n\npublic:\n ScSharedHeaderFooterEditSource( ScHeaderFooterTextData* pData );\n virtual ~ScSharedHeaderFooterEditSource();\n\n \/\/ GetEditEngine is needed because the forwarder doesn't have field functions\n ScEditEngineDefaulter* GetEditEngine();\n\n virtual SvxEditSource* Clone() const ;\n virtual SvxTextForwarder* GetTextForwarder();\n\n virtual void UpdateData();\n\n};\n\n\/\/ ScHeaderFooterEditSource with local copy of ScHeaderFooterTextData is used by field objects\n\nclass ScHeaderFooterEditSource : public ScSharedHeaderFooterEditSource\n{\npublic:\n ScHeaderFooterEditSource( ScHeaderFooterContentObj* pContent, USHORT nP );\n ScHeaderFooterEditSource( ScHeaderFooterContentObj& rContent, USHORT nP );\n virtual ~ScHeaderFooterEditSource();\n\n virtual SvxEditSource* Clone() const;\n};\n\n\n\/\/ Data (incl. EditEngine) for cell EditSource is now shared in ScCellTextData\n\nclass ScSharedCellEditSource : public SvxEditSource\n{\nprivate:\n ScCellTextData* pCellTextData;\n\nprotected:\n ScCellTextData* GetCellTextData() const { return pCellTextData; } \/\/ for ScCellEditSource\n\npublic:\n ScSharedCellEditSource( ScCellTextData* pData );\n virtual ~ScSharedCellEditSource();\n\n \/\/ GetEditEngine is needed because the forwarder doesn't have field functions\n ScEditEngineDefaulter* GetEditEngine();\n\n virtual SvxEditSource* Clone() const;\n virtual SvxTextForwarder* GetTextForwarder();\n\n virtual void UpdateData();\n\n void SetDoUpdateData(sal_Bool bValue);\n sal_Bool IsDirty() const;\n};\n\n\/\/ ScCellEditSource with local copy of ScCellTextData is used by ScCellFieldsObj, ScCellFieldObj\n\nclass ScCellEditSource : public ScSharedCellEditSource\n{\npublic:\n ScCellEditSource( ScDocShell* pDocSh, const ScAddress& rP );\n virtual ~ScCellEditSource();\n\n virtual SvxEditSource* Clone() const;\n};\n\n\nclass ScAnnotationEditSource : public SvxEditSource, public SfxListener\n{\nprivate:\n ScDocShell* pDocShell;\n ScAddress aCellPos;\n ScEditEngineDefaulter* pEditEngine;\n SvxEditEngineForwarder* pForwarder;\n BOOL bDataValid;\n\n SdrObject* GetCaptionObj();\npublic:\n ScAnnotationEditSource(ScDocShell* pDocSh, const ScAddress& rP);\n virtual ~ScAnnotationEditSource();\n\n virtual SvxEditSource* Clone() const ;\n virtual SvxTextForwarder* GetTextForwarder();\n virtual void UpdateData();\n\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n};\n\n\n\/\/ EditSource with a shared forwarder for all children of one text object\n\nclass ScSimpleEditSource : public SvxEditSource\n{\nprivate:\n SvxTextForwarder* pForwarder;\n\npublic:\n ScSimpleEditSource( SvxTextForwarder* pForw );\n virtual ~ScSimpleEditSource();\n\n virtual SvxEditSource* Clone() const ;\n virtual SvxTextForwarder* GetTextForwarder();\n virtual void UpdateData();\n\n};\n\nclass ScAccessibilityEditSource : public SvxEditSource\n{\nprivate:\n ::std::auto_ptr < ScAccessibleTextData > mpAccessibleTextData;\n\npublic:\n ScAccessibilityEditSource( ::std::auto_ptr < ScAccessibleTextData > pAccessibleCellTextData );\n virtual ~ScAccessibilityEditSource();\n\n virtual SvxEditSource* Clone() const;\n virtual SvxTextForwarder* GetTextForwarder();\n virtual SvxViewForwarder* GetViewForwarder();\n virtual SvxEditViewForwarder* GetEditViewForwarder( sal_Bool bCreate = sal_False );\n virtual void UpdateData();\n virtual SfxBroadcaster& GetBroadcaster() const;\n\n void SetDoUpdateData(sal_Bool bValue);\n sal_Bool IsDirty() const;\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.16.698); FILE MERGED 2008\/04\/01 15:29:31 thb 1.16.698.3: #i85898# Stripping all external header guards 2008\/04\/01 12:35:55 thb 1.16.698.2: #i85898# Stripping all external header guards 2008\/03\/31 17:13:30 rt 1.16.698.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: editsrc.hxx,v $\n * $Revision: 1.17 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_EDITSRC_HXX\n#define SC_EDITSRC_HXX\n\n#include \"address.hxx\"\n#include <svx\/unoedsrc.hxx>\n#include <svtools\/lstner.hxx>\n\n#include <memory>\n\nclass ScEditEngineDefaulter;\nclass SvxEditEngineForwarder;\n\nclass ScDocShell;\nclass ScHeaderFooterContentObj;\nclass ScCellTextData;\nclass ScHeaderFooterTextData;\nclass ScAccessibleTextData;\nclass SdrObject;\n\n\nclass ScHeaderFooterChangedHint : public SfxHint\n{\n USHORT nPart;\n\npublic:\n TYPEINFO();\n ScHeaderFooterChangedHint(USHORT nP);\n ~ScHeaderFooterChangedHint();\n\n USHORT GetPart() const { return nPart; }\n};\n\n\n\/\/ all ScSharedHeaderFooterEditSource objects for a single text share the same data\n\nclass ScSharedHeaderFooterEditSource : public SvxEditSource\n{\nprivate:\n ScHeaderFooterTextData* pTextData;\n\nprotected:\n ScHeaderFooterTextData* GetTextData() const { return pTextData; } \/\/ for ScHeaderFooterEditSource\n\npublic:\n ScSharedHeaderFooterEditSource( ScHeaderFooterTextData* pData );\n virtual ~ScSharedHeaderFooterEditSource();\n\n \/\/ GetEditEngine is needed because the forwarder doesn't have field functions\n ScEditEngineDefaulter* GetEditEngine();\n\n virtual SvxEditSource* Clone() const ;\n virtual SvxTextForwarder* GetTextForwarder();\n\n virtual void UpdateData();\n\n};\n\n\/\/ ScHeaderFooterEditSource with local copy of ScHeaderFooterTextData is used by field objects\n\nclass ScHeaderFooterEditSource : public ScSharedHeaderFooterEditSource\n{\npublic:\n ScHeaderFooterEditSource( ScHeaderFooterContentObj* pContent, USHORT nP );\n ScHeaderFooterEditSource( ScHeaderFooterContentObj& rContent, USHORT nP );\n virtual ~ScHeaderFooterEditSource();\n\n virtual SvxEditSource* Clone() const;\n};\n\n\n\/\/ Data (incl. EditEngine) for cell EditSource is now shared in ScCellTextData\n\nclass ScSharedCellEditSource : public SvxEditSource\n{\nprivate:\n ScCellTextData* pCellTextData;\n\nprotected:\n ScCellTextData* GetCellTextData() const { return pCellTextData; } \/\/ for ScCellEditSource\n\npublic:\n ScSharedCellEditSource( ScCellTextData* pData );\n virtual ~ScSharedCellEditSource();\n\n \/\/ GetEditEngine is needed because the forwarder doesn't have field functions\n ScEditEngineDefaulter* GetEditEngine();\n\n virtual SvxEditSource* Clone() const;\n virtual SvxTextForwarder* GetTextForwarder();\n\n virtual void UpdateData();\n\n void SetDoUpdateData(sal_Bool bValue);\n sal_Bool IsDirty() const;\n};\n\n\/\/ ScCellEditSource with local copy of ScCellTextData is used by ScCellFieldsObj, ScCellFieldObj\n\nclass ScCellEditSource : public ScSharedCellEditSource\n{\npublic:\n ScCellEditSource( ScDocShell* pDocSh, const ScAddress& rP );\n virtual ~ScCellEditSource();\n\n virtual SvxEditSource* Clone() const;\n};\n\n\nclass ScAnnotationEditSource : public SvxEditSource, public SfxListener\n{\nprivate:\n ScDocShell* pDocShell;\n ScAddress aCellPos;\n ScEditEngineDefaulter* pEditEngine;\n SvxEditEngineForwarder* pForwarder;\n BOOL bDataValid;\n\n SdrObject* GetCaptionObj();\npublic:\n ScAnnotationEditSource(ScDocShell* pDocSh, const ScAddress& rP);\n virtual ~ScAnnotationEditSource();\n\n virtual SvxEditSource* Clone() const ;\n virtual SvxTextForwarder* GetTextForwarder();\n virtual void UpdateData();\n\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n};\n\n\n\/\/ EditSource with a shared forwarder for all children of one text object\n\nclass ScSimpleEditSource : public SvxEditSource\n{\nprivate:\n SvxTextForwarder* pForwarder;\n\npublic:\n ScSimpleEditSource( SvxTextForwarder* pForw );\n virtual ~ScSimpleEditSource();\n\n virtual SvxEditSource* Clone() const ;\n virtual SvxTextForwarder* GetTextForwarder();\n virtual void UpdateData();\n\n};\n\nclass ScAccessibilityEditSource : public SvxEditSource\n{\nprivate:\n ::std::auto_ptr < ScAccessibleTextData > mpAccessibleTextData;\n\npublic:\n ScAccessibilityEditSource( ::std::auto_ptr < ScAccessibleTextData > pAccessibleCellTextData );\n virtual ~ScAccessibilityEditSource();\n\n virtual SvxEditSource* Clone() const;\n virtual SvxTextForwarder* GetTextForwarder();\n virtual SvxViewForwarder* GetViewForwarder();\n virtual SvxEditViewForwarder* GetEditViewForwarder( sal_Bool bCreate = sal_False );\n virtual void UpdateData();\n virtual SfxBroadcaster& GetBroadcaster() const;\n\n void SetDoUpdateData(sal_Bool bValue);\n sal_Bool IsDirty() const;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights\n\/\/ reserved. Use of this source code is governed by a BSD-style license that\n\/\/ can be found in the LICENSE file.\n\n#include \"include\/wrapper\/cef_byte_read_handler.h\"\n#include <stdlib.h>\n#include \"libcef_dll\/cef_logging.h\"\n\nCefByteReadHandler::CefByteReadHandler(const unsigned char* bytes, size_t size,\n CefRefPtr<CefBase> source)\n : bytes_(bytes), size_(size), offset_(0), source_(source) {\n}\n\nsize_t CefByteReadHandler::Read(void* ptr, size_t size, size_t n) {\n AutoLock lock_scope(this);\n size_t s = (size_ - offset_) \/ size;\n size_t ret = std::min(n, s);\n memcpy(ptr, bytes_ + offset_, ret * size);\n offset_ += ret * size;\n return ret;\n}\n\nint CefByteReadHandler::Seek(int64 offset, int whence) {\n int rv = -1L;\n AutoLock lock_scope(this);\n switch (whence) {\n case SEEK_CUR:\n if (offset_ + offset > size_ || offset_ + offset < 0)\n break;\n offset_ += offset;\n rv = 0;\n break;\n case SEEK_END: {\n int64 offset_abs = abs(offset);\n if (offset_abs > size_)\n break;\n offset_ = size_ - offset_abs;\n rv = 0;\n break;\n }\n case SEEK_SET:\n if (offset > size_ || offset < 0)\n break;\n offset_ = offset;\n rv = 0;\n break;\n }\n\n return rv;\n}\n\nint64 CefByteReadHandler::Tell() {\n AutoLock lock_scope(this);\n return offset_;\n}\n\nint CefByteReadHandler::Eof() {\n AutoLock lock_scope(this);\n return (offset_ >= size_);\n}\n<commit_msg>Fix compile warning in CefByteReadHandler::Read.<commit_after>\/\/ Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights\n\/\/ reserved. Use of this source code is governed by a BSD-style license that\n\/\/ can be found in the LICENSE file.\n\n#include \"include\/wrapper\/cef_byte_read_handler.h\"\n#include <stdlib.h>\n#include \"libcef_dll\/cef_logging.h\"\n\nCefByteReadHandler::CefByteReadHandler(const unsigned char* bytes, size_t size,\n CefRefPtr<CefBase> source)\n : bytes_(bytes), size_(size), offset_(0), source_(source) {\n}\n\nsize_t CefByteReadHandler::Read(void* ptr, size_t size, size_t n) {\n AutoLock lock_scope(this);\n size_t s = static_cast<size_t>(size_ - offset_) \/ size;\n size_t ret = std::min(n, s);\n memcpy(ptr, bytes_ + offset_, ret * size);\n offset_ += ret * size;\n return ret;\n}\n\nint CefByteReadHandler::Seek(int64 offset, int whence) {\n int rv = -1L;\n AutoLock lock_scope(this);\n switch (whence) {\n case SEEK_CUR:\n if (offset_ + offset > size_ || offset_ + offset < 0)\n break;\n offset_ += offset;\n rv = 0;\n break;\n case SEEK_END: {\n int64 offset_abs = abs(offset);\n if (offset_abs > size_)\n break;\n offset_ = size_ - offset_abs;\n rv = 0;\n break;\n }\n case SEEK_SET:\n if (offset > size_ || offset < 0)\n break;\n offset_ = offset;\n rv = 0;\n break;\n }\n\n return rv;\n}\n\nint64 CefByteReadHandler::Tell() {\n AutoLock lock_scope(this);\n return offset_;\n}\n\nint CefByteReadHandler::Eof() {\n AutoLock lock_scope(this);\n return (offset_ >= size_);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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#include \"ceee\/ie\/plugin\/toolband\/toolband_proxy.h\"\n\n#include <atlbase.h>\n#include \"base\/logging.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/win\/registry.h\"\n#include \"ceee\/common\/com_utils.h\"\n#include \"ceee\/ie\/plugin\/toolband\/resource.h\"\n\n#include \"toolband.h\" \/\/ NOLINT\n\nextern \"C\" {\n\/\/ Declare the entrypoint function(s) generated by MIDL for our proxy\/stubs.\nHRESULT STDAPICALLTYPE ToolbandProxyDllGetClassObject(REFCLSID clsid,\n REFIID iid,\n void** ppv);\n} \/\/ extern \"C\"\n\nnamespace {\n\nstruct InterfaceInfo {\n const wchar_t* name;\n const IID* iid;\n const IID* async_iid;\n};\n\n#define DECLARE_SYNC_INTERFACE(itf) \\\n { L#itf, &IID_##itf, NULL },\n#define DECLARE_ASYNC_INTERFACE(itf) \\\n { L#itf, &IID_##itf, &IID_Async##itf }, \\\n DECLARE_SYNC_INTERFACE(Async##itf)\n\n\/\/ If you add new executor interfaces to toolband.idl, make sure to add\n\/\/ their IIDs here, or you will not be able to marshal them.\nconst InterfaceInfo kInterfaceInfo[] = {\n DECLARE_SYNC_INTERFACE(ICeeeWindowExecutor)\n DECLARE_ASYNC_INTERFACE(ICeeeTabExecutor)\n DECLARE_SYNC_INTERFACE(ICeeeCookieExecutor)\n DECLARE_SYNC_INTERFACE(ICeeeInfobarExecutor)\n};\n\n#ifndef NDEBUG\nvoid CheckAsyncIidRegistered(const IID& iid, const IID& async_iid) {\n std::wstring iid_str;\n bool success = com::GuidToString(iid, &iid_str);\n DCHECK(success);\n std::wstring key_name = base::StringPrintf(\n L\"Interface\\\\%ls\\\\AsynchronousInterface\", iid_str);\n\n base::win::RegKey key;\n if (key.Open(HKEY_CLASSES_ROOT, key_name.c_str(), KEY_READ)) {\n \/\/ It's registered, the rest of this block is debug checking that\n \/\/ the correct IID is indeed registered for the async interface.\n std::wstring async_iid_str;\n DCHECK(key.ReadValue(NULL, &async_iid_str));\n IID read_async_iid;\n DCHECK(SUCCEEDED(::IIDFromString(async_iid_str.c_str(), &read_async_iid)));\n DCHECK(read_async_iid == async_iid);\n } else {\n LOG(WARNING) << \"Sync->Async IID not registered. Key=\" << key_name;\n }\n}\n#endif \/\/ NDEBUG\n\n} \/\/ namespace\n\nbool RegisterProxyStubs(std::vector<DWORD>* cookies) {\n bool succeeded = true;\n\n for (size_t i = 0; i < arraysize(kInterfaceInfo); ++i) {\n CComPtr<IUnknown> factory;\n const InterfaceInfo& info = kInterfaceInfo[i];\n HRESULT hr = ToolbandProxyDllGetClassObject(*info.iid, IID_IUnknown,\n reinterpret_cast<void**>(&factory));\n\n DWORD cookie = 0;\n if (SUCCEEDED(hr)) {\n hr = ::CoRegisterClassObject(*info.iid, factory, CLSCTX_INPROC_SERVER,\n REGCLS_MULTIPLEUSE, &cookie);\n }\n if (SUCCEEDED(hr)) {\n \/\/ Proxy\/stubs have their own IID as class id.\n hr = ::CoRegisterPSClsid(*info.iid, *info.iid);\n if (SUCCEEDED(hr) && cookies != NULL) {\n cookies->push_back(cookie);\n }\n }\n\n#ifndef NDEBUG\n \/\/ If there's a corresponding Async interface, check whether\n \/\/ it's registered. This is a debugging aid only.\n if (info.async_iid != NULL)\n CheckAsyncIidRegistered(*info.iid, *info.async_iid);\n#endif \/\/ NDEBUG\n\n if (FAILED(hr)) {\n succeeded = false;\n LOG(ERROR) << \"Failed to register proxy \" << com::LogHr(hr);\n }\n }\n\n VLOG(1) << \"Registered toolband proxy\/stubs in thread \"\n << ::GetCurrentThreadId();\n\n return succeeded;\n}\n\nvoid UnregisterProxyStubs(const std::vector<DWORD>& cookies) {\n for (size_t i = 0; i < cookies.size(); ++i) {\n HRESULT hr = ::CoRevokeClassObject(cookies[i]);\n if (FAILED(hr)) {\n LOG(ERROR) << \"Failed to revoke class object \" << com::LogHr(hr);\n }\n }\n}\n\nbool RegisterAsyncProxies(bool reg) {\n for (size_t i = 0; i < arraysize(kInterfaceInfo); ++i) {\n \/\/ Register the iid->async iid mapping for async interfaces.\n if (kInterfaceInfo[i].async_iid != NULL) {\n const InterfaceInfo& info = kInterfaceInfo[i];\n std::wstring iid_str;\n bool success = com::GuidToString(*info.iid, &iid_str);\n DCHECK(success) << \"Failed to stringify GUID\";\n std::wstring async_iid_str;\n success = com::GuidToString(*info.async_iid, &async_iid_str);\n DCHECK(success) << \"Failed to stringify GUID\";\n\n _ATL_REGMAP_ENTRY entries[] = {\n { L\"IID\", iid_str.c_str() },\n { L\"ASYNC_IID\", async_iid_str.c_str() },\n { L\"NAME\", info.name },\n { NULL, NULL },\n };\n\n HRESULT hr = _pAtlModule->UpdateRegistryFromResource(\n MAKEINTRESOURCE(IDR_TOOLBAND_PROXY), reg, entries);\n if (FAILED(hr)) {\n LOG(ERROR) << \"Failed to register async interface for \" <<\n info.name << com::LogHr(hr);\n return false;\n }\n }\n }\n\n return true;\n}\n<commit_msg>Commit for siggi, original http:\/\/codereview.chromium.org\/5385004\/<commit_after>\/\/ Copyright (c) 2010 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#include \"ceee\/ie\/plugin\/toolband\/toolband_proxy.h\"\n\n#include <atlbase.h>\n#include \"base\/logging.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/win\/registry.h\"\n#include \"ceee\/common\/com_utils.h\"\n#include \"ceee\/ie\/plugin\/toolband\/resource.h\"\n\n#include \"toolband.h\" \/\/ NOLINT\n\nextern \"C\" {\n\/\/ Declare the entrypoint function(s) generated by MIDL for our proxy\/stubs.\nHRESULT STDAPICALLTYPE ToolbandProxyDllGetClassObject(REFCLSID clsid,\n REFIID iid,\n void** ppv);\n} \/\/ extern \"C\"\n\nnamespace {\n\nstruct InterfaceInfo {\n const wchar_t* name;\n const IID* iid;\n const IID* async_iid;\n};\n\n#define DECLARE_SYNC_INTERFACE(itf) \\\n { L#itf, &IID_##itf, NULL },\n#define DECLARE_ASYNC_INTERFACE(itf) \\\n { L#itf, &IID_##itf, &IID_Async##itf }, \\\n DECLARE_SYNC_INTERFACE(Async##itf)\n\n\/\/ If you add new executor interfaces to toolband.idl, make sure to add\n\/\/ their IIDs here, or you will not be able to marshal them.\nconst InterfaceInfo kInterfaceInfo[] = {\n DECLARE_SYNC_INTERFACE(ICeeeWindowExecutor)\n DECLARE_ASYNC_INTERFACE(ICeeeTabExecutor)\n DECLARE_SYNC_INTERFACE(ICeeeCookieExecutor)\n DECLARE_SYNC_INTERFACE(ICeeeInfobarExecutor)\n};\n\n#ifndef NDEBUG\nvoid CheckAsyncIidRegistered(const IID& iid, const IID& async_iid) {\n std::wstring iid_str;\n bool success = com::GuidToString(iid, &iid_str);\n DCHECK(success);\n std::wstring key_name = base::StringPrintf(\n L\"Interface\\\\%ls\\\\AsynchronousInterface\", iid_str.c_str());\n\n base::win::RegKey key;\n if (key.Open(HKEY_CLASSES_ROOT, key_name.c_str(), KEY_READ)) {\n \/\/ It's registered, the rest of this block is debug checking that\n \/\/ the correct IID is indeed registered for the async interface.\n std::wstring async_iid_str;\n DCHECK(key.ReadValue(NULL, &async_iid_str));\n IID read_async_iid;\n DCHECK(SUCCEEDED(::IIDFromString(async_iid_str.c_str(), &read_async_iid)));\n DCHECK(read_async_iid == async_iid);\n } else {\n LOG(WARNING) << \"Sync->Async IID not registered. Key=\" << key_name;\n }\n}\n#endif \/\/ NDEBUG\n\n} \/\/ namespace\n\nbool RegisterProxyStubs(std::vector<DWORD>* cookies) {\n bool succeeded = true;\n\n for (size_t i = 0; i < arraysize(kInterfaceInfo); ++i) {\n CComPtr<IUnknown> factory;\n const InterfaceInfo& info = kInterfaceInfo[i];\n HRESULT hr = ToolbandProxyDllGetClassObject(*info.iid, IID_IUnknown,\n reinterpret_cast<void**>(&factory));\n\n DWORD cookie = 0;\n if (SUCCEEDED(hr)) {\n hr = ::CoRegisterClassObject(*info.iid, factory, CLSCTX_INPROC_SERVER,\n REGCLS_MULTIPLEUSE, &cookie);\n }\n if (SUCCEEDED(hr)) {\n \/\/ Proxy\/stubs have their own IID as class id.\n hr = ::CoRegisterPSClsid(*info.iid, *info.iid);\n if (SUCCEEDED(hr) && cookies != NULL) {\n cookies->push_back(cookie);\n }\n }\n\n#ifndef NDEBUG\n \/\/ If there's a corresponding Async interface, check whether\n \/\/ it's registered. This is a debugging aid only.\n if (info.async_iid != NULL)\n CheckAsyncIidRegistered(*info.iid, *info.async_iid);\n#endif \/\/ NDEBUG\n\n if (FAILED(hr)) {\n succeeded = false;\n LOG(ERROR) << \"Failed to register proxy \" << com::LogHr(hr);\n }\n }\n\n VLOG(1) << \"Registered toolband proxy\/stubs in thread \"\n << ::GetCurrentThreadId();\n\n return succeeded;\n}\n\nvoid UnregisterProxyStubs(const std::vector<DWORD>& cookies) {\n for (size_t i = 0; i < cookies.size(); ++i) {\n HRESULT hr = ::CoRevokeClassObject(cookies[i]);\n if (FAILED(hr)) {\n LOG(ERROR) << \"Failed to revoke class object \" << com::LogHr(hr);\n }\n }\n}\n\nbool RegisterAsyncProxies(bool reg) {\n for (size_t i = 0; i < arraysize(kInterfaceInfo); ++i) {\n \/\/ Register the iid->async iid mapping for async interfaces.\n if (kInterfaceInfo[i].async_iid != NULL) {\n const InterfaceInfo& info = kInterfaceInfo[i];\n std::wstring iid_str;\n bool success = com::GuidToString(*info.iid, &iid_str);\n DCHECK(success) << \"Failed to stringify GUID\";\n std::wstring async_iid_str;\n success = com::GuidToString(*info.async_iid, &async_iid_str);\n DCHECK(success) << \"Failed to stringify GUID\";\n\n _ATL_REGMAP_ENTRY entries[] = {\n { L\"IID\", iid_str.c_str() },\n { L\"ASYNC_IID\", async_iid_str.c_str() },\n { L\"NAME\", info.name },\n { NULL, NULL },\n };\n\n HRESULT hr = _pAtlModule->UpdateRegistryFromResource(\n MAKEINTRESOURCE(IDR_TOOLBAND_PROXY), reg, entries);\n if (FAILED(hr)) {\n LOG(ERROR) << \"Failed to register async interface for \" <<\n info.name << com::LogHr(hr);\n return false;\n }\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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#include \"ceee\/ie\/plugin\/toolband\/toolband_proxy.h\"\n\n#include <atlbase.h>\n#include \"base\/logging.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/win\/registry.h\"\n#include \"ceee\/common\/com_utils.h\"\n#include \"ceee\/ie\/plugin\/toolband\/resource.h\"\n\n#include \"toolband.h\" \/\/ NOLINT\n\nextern \"C\" {\n\/\/ Declare the entrypoint function(s) generated by MIDL for our proxy\/stubs.\nHRESULT STDAPICALLTYPE ToolbandProxyDllGetClassObject(REFCLSID clsid,\n REFIID iid,\n void** ppv);\n} \/\/ extern \"C\"\n\nnamespace {\n\nstruct InterfaceInfo {\n const wchar_t* name;\n const IID* iid;\n const IID* async_iid;\n};\n\n#define DECLARE_SYNC_INTERFACE(itf) \\\n { L#itf, &IID_##itf, NULL },\n#define DECLARE_ASYNC_INTERFACE(itf) \\\n { L#itf, &IID_##itf, &IID_Async##itf }, \\\n DECLARE_SYNC_INTERFACE(Async##itf)\n\n\/\/ If you add new executor interfaces to toolband.idl, make sure to add\n\/\/ their IIDs here, or you will not be able to marshal them.\nconst InterfaceInfo kInterfaceInfo[] = {\n DECLARE_SYNC_INTERFACE(ICeeeWindowExecutor)\n DECLARE_ASYNC_INTERFACE(ICeeeTabExecutor)\n DECLARE_SYNC_INTERFACE(ICeeeCookieExecutor)\n DECLARE_SYNC_INTERFACE(ICeeeInfobarExecutor)\n};\n\n#ifndef NDEBUG\nvoid CheckAsyncIidRegistered(const IID& iid, const IID& async_iid) {\n std::wstring iid_str;\n bool success = com::GuidToString(iid, &iid_str);\n DCHECK(success);\n std::wstring key_name = base::StringPrintf(\n L\"Interface\\\\%ls\\\\AsynchronousInterface\", iid_str);\n\n base::win::RegKey key;\n if (key.Open(HKEY_CLASSES_ROOT, key_name.c_str(), KEY_READ)) {\n \/\/ It's registered, the rest of this block is debug checking that\n \/\/ the correct IID is indeed registered for the async interface.\n std::wstring async_iid_str;\n DCHECK(key.ReadValue(NULL, &async_iid_str));\n IID read_async_iid;\n DCHECK(SUCCEEDED(::IIDFromString(async_iid_str.c_str(), &read_async_iid)));\n DCHECK(read_async_iid == async_iid);\n } else {\n LOG(WARNING) << \"Sync->Async IID not registered. Key=\" << key_name;\n }\n}\n#endif \/\/ NDEBUG\n\n} \/\/ namespace\n\nbool RegisterProxyStubs(std::vector<DWORD>* cookies) {\n bool succeeded = true;\n\n for (size_t i = 0; i < arraysize(kInterfaceInfo); ++i) {\n CComPtr<IUnknown> factory;\n const InterfaceInfo& info = kInterfaceInfo[i];\n HRESULT hr = ToolbandProxyDllGetClassObject(*info.iid, IID_IUnknown,\n reinterpret_cast<void**>(&factory));\n\n DWORD cookie = 0;\n if (SUCCEEDED(hr)) {\n hr = ::CoRegisterClassObject(*info.iid, factory, CLSCTX_INPROC_SERVER,\n REGCLS_MULTIPLEUSE, &cookie);\n }\n if (SUCCEEDED(hr)) {\n \/\/ Proxy\/stubs have their own IID as class id.\n hr = ::CoRegisterPSClsid(*info.iid, *info.iid);\n if (SUCCEEDED(hr) && cookies != NULL) {\n cookies->push_back(cookie);\n }\n }\n\n#ifndef NDEBUG\n \/\/ If there's a corresponding Async interface, check whether\n \/\/ it's registered. This is a debugging aid only.\n if (info.async_iid != NULL)\n CheckAsyncIidRegistered(*info.iid, *info.async_iid);\n#endif \/\/ NDEBUG\n\n if (FAILED(hr)) {\n succeeded = false;\n LOG(ERROR) << \"Failed to register proxy \" << com::LogHr(hr);\n }\n }\n\n VLOG(1) << \"Registered toolband proxy\/stubs in thread \"\n << ::GetCurrentThreadId();\n\n return succeeded;\n}\n\nvoid UnregisterProxyStubs(const std::vector<DWORD>& cookies) {\n for (size_t i = 0; i < cookies.size(); ++i) {\n HRESULT hr = ::CoRevokeClassObject(cookies[i]);\n if (FAILED(hr)) {\n LOG(ERROR) << \"Failed to revoke class object \" << com::LogHr(hr);\n }\n }\n}\n\nbool RegisterAsyncProxies(bool reg) {\n for (size_t i = 0; i < arraysize(kInterfaceInfo); ++i) {\n \/\/ Register the iid->async iid mapping for async interfaces.\n if (kInterfaceInfo[i].async_iid != NULL) {\n const InterfaceInfo& info = kInterfaceInfo[i];\n std::wstring iid_str;\n bool success = com::GuidToString(*info.iid, &iid_str);\n DCHECK(success) << \"Failed to stringify GUID\";\n std::wstring async_iid_str;\n success = com::GuidToString(*info.async_iid, &async_iid_str);\n DCHECK(success) << \"Failed to stringify GUID\";\n\n _ATL_REGMAP_ENTRY entries[] = {\n { L\"IID\", iid_str.c_str() },\n { L\"ASYNC_IID\", async_iid_str.c_str() },\n { L\"NAME\", info.name },\n { NULL, NULL },\n };\n\n HRESULT hr = _pAtlModule->UpdateRegistryFromResource(\n MAKEINTRESOURCE(IDR_TOOLBAND_PROXY), reg, entries);\n if (FAILED(hr)) {\n LOG(ERROR) << \"Failed to register async interface for \" <<\n info.name << com::LogHr(hr);\n return false;\n }\n }\n }\n\n return true;\n}\n<commit_msg>Commit for siggi, original http:\/\/codereview.chromium.org\/5385004\/<commit_after>\/\/ Copyright (c) 2010 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#include \"ceee\/ie\/plugin\/toolband\/toolband_proxy.h\"\n\n#include <atlbase.h>\n#include \"base\/logging.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/win\/registry.h\"\n#include \"ceee\/common\/com_utils.h\"\n#include \"ceee\/ie\/plugin\/toolband\/resource.h\"\n\n#include \"toolband.h\" \/\/ NOLINT\n\nextern \"C\" {\n\/\/ Declare the entrypoint function(s) generated by MIDL for our proxy\/stubs.\nHRESULT STDAPICALLTYPE ToolbandProxyDllGetClassObject(REFCLSID clsid,\n REFIID iid,\n void** ppv);\n} \/\/ extern \"C\"\n\nnamespace {\n\nstruct InterfaceInfo {\n const wchar_t* name;\n const IID* iid;\n const IID* async_iid;\n};\n\n#define DECLARE_SYNC_INTERFACE(itf) \\\n { L#itf, &IID_##itf, NULL },\n#define DECLARE_ASYNC_INTERFACE(itf) \\\n { L#itf, &IID_##itf, &IID_Async##itf }, \\\n DECLARE_SYNC_INTERFACE(Async##itf)\n\n\/\/ If you add new executor interfaces to toolband.idl, make sure to add\n\/\/ their IIDs here, or you will not be able to marshal them.\nconst InterfaceInfo kInterfaceInfo[] = {\n DECLARE_SYNC_INTERFACE(ICeeeWindowExecutor)\n DECLARE_ASYNC_INTERFACE(ICeeeTabExecutor)\n DECLARE_SYNC_INTERFACE(ICeeeCookieExecutor)\n DECLARE_SYNC_INTERFACE(ICeeeInfobarExecutor)\n};\n\n#ifndef NDEBUG\nvoid CheckAsyncIidRegistered(const IID& iid, const IID& async_iid) {\n std::wstring iid_str;\n bool success = com::GuidToString(iid, &iid_str);\n DCHECK(success);\n std::wstring key_name = base::StringPrintf(\n L\"Interface\\\\%ls\\\\AsynchronousInterface\", iid_str.c_str());\n\n base::win::RegKey key;\n if (key.Open(HKEY_CLASSES_ROOT, key_name.c_str(), KEY_READ)) {\n \/\/ It's registered, the rest of this block is debug checking that\n \/\/ the correct IID is indeed registered for the async interface.\n std::wstring async_iid_str;\n DCHECK(key.ReadValue(NULL, &async_iid_str));\n IID read_async_iid;\n DCHECK(SUCCEEDED(::IIDFromString(async_iid_str.c_str(), &read_async_iid)));\n DCHECK(read_async_iid == async_iid);\n } else {\n LOG(WARNING) << \"Sync->Async IID not registered. Key=\" << key_name;\n }\n}\n#endif \/\/ NDEBUG\n\n} \/\/ namespace\n\nbool RegisterProxyStubs(std::vector<DWORD>* cookies) {\n bool succeeded = true;\n\n for (size_t i = 0; i < arraysize(kInterfaceInfo); ++i) {\n CComPtr<IUnknown> factory;\n const InterfaceInfo& info = kInterfaceInfo[i];\n HRESULT hr = ToolbandProxyDllGetClassObject(*info.iid, IID_IUnknown,\n reinterpret_cast<void**>(&factory));\n\n DWORD cookie = 0;\n if (SUCCEEDED(hr)) {\n hr = ::CoRegisterClassObject(*info.iid, factory, CLSCTX_INPROC_SERVER,\n REGCLS_MULTIPLEUSE, &cookie);\n }\n if (SUCCEEDED(hr)) {\n \/\/ Proxy\/stubs have their own IID as class id.\n hr = ::CoRegisterPSClsid(*info.iid, *info.iid);\n if (SUCCEEDED(hr) && cookies != NULL) {\n cookies->push_back(cookie);\n }\n }\n\n#ifndef NDEBUG\n \/\/ If there's a corresponding Async interface, check whether\n \/\/ it's registered. This is a debugging aid only.\n if (info.async_iid != NULL)\n CheckAsyncIidRegistered(*info.iid, *info.async_iid);\n#endif \/\/ NDEBUG\n\n if (FAILED(hr)) {\n succeeded = false;\n LOG(ERROR) << \"Failed to register proxy \" << com::LogHr(hr);\n }\n }\n\n VLOG(1) << \"Registered toolband proxy\/stubs in thread \"\n << ::GetCurrentThreadId();\n\n return succeeded;\n}\n\nvoid UnregisterProxyStubs(const std::vector<DWORD>& cookies) {\n for (size_t i = 0; i < cookies.size(); ++i) {\n HRESULT hr = ::CoRevokeClassObject(cookies[i]);\n if (FAILED(hr)) {\n LOG(ERROR) << \"Failed to revoke class object \" << com::LogHr(hr);\n }\n }\n}\n\nbool RegisterAsyncProxies(bool reg) {\n for (size_t i = 0; i < arraysize(kInterfaceInfo); ++i) {\n \/\/ Register the iid->async iid mapping for async interfaces.\n if (kInterfaceInfo[i].async_iid != NULL) {\n const InterfaceInfo& info = kInterfaceInfo[i];\n std::wstring iid_str;\n bool success = com::GuidToString(*info.iid, &iid_str);\n DCHECK(success) << \"Failed to stringify GUID\";\n std::wstring async_iid_str;\n success = com::GuidToString(*info.async_iid, &async_iid_str);\n DCHECK(success) << \"Failed to stringify GUID\";\n\n _ATL_REGMAP_ENTRY entries[] = {\n { L\"IID\", iid_str.c_str() },\n { L\"ASYNC_IID\", async_iid_str.c_str() },\n { L\"NAME\", info.name },\n { NULL, NULL },\n };\n\n HRESULT hr = _pAtlModule->UpdateRegistryFromResource(\n MAKEINTRESOURCE(IDR_TOOLBAND_PROXY), reg, entries);\n if (FAILED(hr)) {\n LOG(ERROR) << \"Failed to register async interface for \" <<\n info.name << com::LogHr(hr);\n return false;\n }\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"wiVersion.h\"\n\n#include <string>\n\nnamespace wi::version\n{\n\t\/\/ main engine core\n\tconst int major = 0;\n\t\/\/ minor features, major updates, breaking compatibility changes\n\tconst int minor = 71;\n\t\/\/ minor bug fixes, alterations, refactors, updates\n\tconst int revision = 77;\n\n\tconst std::string version_string = std::to_string(major) + \".\" + std::to_string(minor) + \".\" + std::to_string(revision);\n\n\tint GetMajor()\n\t{\n\t\treturn major;\n\t}\n\tint GetMinor()\n\t{\n\t\treturn minor;\n\t}\n\tint GetRevision()\n\t{\n\t\treturn revision;\n\t}\n\tconst char* GetVersionString()\n\t{\n\t\treturn version_string.c_str();\n\t}\n\n\tconst char* GetCreditsString()\n\t{\n\t\tstatic const char* credits = R\"(\nCredits\n-----------\nCreated by Turánszki János | https:\/\/github.com\/turanszkij\n\n\nContributors\n------------------\n- Silas Oler | https:\/\/github.com\/Kliaxe\n\t- Stochastic Screen Space Reflections\n\t- Realistic Sky\n\t- Volumetric clouds\n\t- Exponential height fog\n- Matteo De Carlo | https:\/\/github.com\/portaloffreedom\n\t- Linux core systems\n\t- Cmake\n- XThemeCore | https:\/\/github.com\/XthemeCore\n\t- Morph targets\n- Amer Koleci https:\/\/github.com\/amerkoleci\n\t- Windows Cmake\n\t- Graphics API improvements\n\t- Dear ImGui integration\n\t- Refactors, fixes\n- James Webb | https:\/\/github.com\/jdswebb\n\t- Graphics API improvements\n\t- Fixes\n- Ben Vinson | https:\/\/github.com\/BenV\n\t- Fixes\n- Alexander Weinrauch | https:\/\/github.com\/AlexAUT\n\t- Fixes\n- Eric Fedosejevs | https:\/\/github.com\/efedo\n\t- Fixes\n- Johan Aires Rastén | https:\/\/github.com\/JohanAR\n\t- Fixes\n- Megumumpkin | https:\/\/github.com\/megumumpkin\n\t- Linux audio implementation\n\t- Linux controller implementation\n\t- Linux network implementation\n\t- ComponentLibrary implementation\n\t- Lua property bindings support, improvements\n\t- Fixes\n- Maeve Garside | https:\/\/github.com\/MolassesLover\n\t- Linux package files\n\t- Visual Studio Code support improvement\n\t- Linux template\n- Igor Alexey | https:\/\/github.com\/sororfortuna\n\t- QOI image loader integration\n- Eddie Ataberk | https:\/\/github.com\/eddieataberk\n\t- Physics improvements\n- Preben Eriksen | https:\/\/github.com\/plemsoft\n\t- Fixes\n\t- Dear ImGui docking sample.\n- matpx | https:\/\/github.com\/matpx\n\t- Fixes\n- Dennis Brakhane | https:\/\/github.com\/brakhane\n\t- Added Liberation Sans default font\n\nPatreon supporters\n---------------------------\n- Nemerle\n- James Webb\n- Quifeng Jin\n- TheGameCreators\n- Joseph Goldin\n- Yuri\n- Sergey K\n- Yukawa Kanta\n- Dragon Josh\n- John\n- LurkingNinja\n- Bernardo Del Castillo\n- Invictus\n- Scott Hunt\n- Yazan Altaki\n- Tuan NV\n- Robert MacGregor\n- cybernescence\n- Alexander Dahlin\n- blueapples\n- Delhills\n- NI NI\n- Sherief\n- ktopoet\n\t\t)\";\n\n\t\treturn credits;\n\t}\n\n}\n<commit_msg>updated credits<commit_after>#include \"wiVersion.h\"\n\n#include <string>\n\nnamespace wi::version\n{\n\t\/\/ main engine core\n\tconst int major = 0;\n\t\/\/ minor features, major updates, breaking compatibility changes\n\tconst int minor = 71;\n\t\/\/ minor bug fixes, alterations, refactors, updates\n\tconst int revision = 77;\n\n\tconst std::string version_string = std::to_string(major) + \".\" + std::to_string(minor) + \".\" + std::to_string(revision);\n\n\tint GetMajor()\n\t{\n\t\treturn major;\n\t}\n\tint GetMinor()\n\t{\n\t\treturn minor;\n\t}\n\tint GetRevision()\n\t{\n\t\treturn revision;\n\t}\n\tconst char* GetVersionString()\n\t{\n\t\treturn version_string.c_str();\n\t}\n\n\tconst char* GetCreditsString()\n\t{\n\t\tstatic const char* credits = R\"(\nCredits\n-----------\nCreated by Turánszki János | https:\/\/github.com\/turanszkij\n\n\nContributors\n------------------\n- Silas Oler | https:\/\/github.com\/Kliaxe\n\t- Stochastic Screen Space Reflections\n\t- Realistic Sky\n\t- Volumetric clouds\n\t- Exponential height fog\n- Matteo De Carlo | https:\/\/github.com\/portaloffreedom\n\t- Linux core systems\n\t- Cmake\n- XThemeCore | https:\/\/github.com\/XthemeCore\n\t- Morph targets\n- Amer Koleci https:\/\/github.com\/amerkoleci\n\t- Windows Cmake\n\t- Graphics API improvements\n\t- Dear ImGui integration\n\t- Refactors, fixes\n- James Webb | https:\/\/github.com\/jdswebb\n\t- Graphics API improvements\n\t- Fixes\n- Ben Vinson | https:\/\/github.com\/BenV\n\t- Fixes\n- Alexander Weinrauch | https:\/\/github.com\/AlexAUT\n\t- Fixes\n- Eric Fedosejevs | https:\/\/github.com\/efedo\n\t- Fixes\n- Johan Aires Rastén | https:\/\/github.com\/JohanAR\n\t- Fixes\n- Megumumpkin | https:\/\/github.com\/megumumpkin\n\t- Linux audio implementation\n\t- Linux controller implementation\n\t- Linux network implementation\n\t- ComponentLibrary implementation\n\t- Lua property bindings support, improvements\n\t- Fixes\n- Maeve Garside | https:\/\/github.com\/MolassesLover\n\t- Linux package files\n\t- Visual Studio Code support improvement\n\t- Linux template\n- Igor Alexey | https:\/\/github.com\/sororfortuna\n\t- QOI image loader integration\n- Eddie Ataberk | https:\/\/github.com\/eddieataberk\n\t- Physics improvements\n- Preben Eriksen | https:\/\/github.com\/plemsoft\n\t- Fixes\n\t- Dear ImGui docking sample.\n- matpx | https:\/\/github.com\/matpx\n\t- Fixes\n- Dennis Brakhane | https:\/\/github.com\/brakhane\n\t- Added Liberation Sans default font\n- Cop46 | https:\/\/github.com\/Cop46\n\t- Brightness, Contrast, Saturation post process\n\nPatreon supporters\n---------------------------\n- Nemerle\n- James Webb\n- Quifeng Jin\n- TheGameCreators\n- Joseph Goldin\n- Yuri\n- Sergey K\n- Yukawa Kanta\n- Dragon Josh\n- John\n- LurkingNinja\n- Bernardo Del Castillo\n- Invictus\n- Scott Hunt\n- Yazan Altaki\n- Tuan NV\n- Robert MacGregor\n- cybernescence\n- Alexander Dahlin\n- blueapples\n- Delhills\n- NI NI\n- Sherief\n- ktopoet\n- Justin Macklin\n- Cédric Fabre\n- TogetherTeam\n- Bartosz Boczula\n\t\t)\";\n\n\t\treturn credits;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"qjulia.h\"\n#include \"qjulia.cpp\"\n\n#define WIN32_LEAN_AND_MEAN\n#define NOMINMAX\n#include <windows.h>\n#include <process.h>\n\n#define k_max_thread_count 16\n\nstruct thread_context_t\n{\n HANDLE h;\n uint32_t id;\n HANDLE done_event;\n application_context_t *app;\n};\n\nstruct system_context_t\n{\n HWND hwnd;\n HDC hdc, mdc;\n HBITMAP hbm;\n\n HANDLE quit_event;\n HANDLE render_semaphore;\n uint32_t thread_count;\n thread_context_t thread[k_max_thread_count];\n volatile long tile_index;\n};\n\nstatic uint32_t WINAPI\nwin_render_thread(void *context)\n{\n thread_context_t *thread = (thread_context_t *)context;\n assert(thread && thread->app && thread->app->sys);\n\n system_context_t *sys = thread->app->sys;\n\n HANDLE wait[2] = { sys->quit_event, sys->render_semaphore };\n\n for (;;) {\n DWORD r = WaitForMultipleObjects(2, wait, FALSE, INFINITE);\n if (r == WAIT_OBJECT_0) break;\n\n for (;;) {\n uint32_t idx = (uint32_t)_InterlockedExchangeAdd(&sys->tile_index, 1);\n if (idx >= k_tile_count) break;\n render_tile(thread->app, idx);\n }\n\n SetEvent(thread->done_event);\n }\n\n return 0;\n}\n\nstatic LRESULT CALLBACK\nwin_message_handler(HWND win, UINT msg, WPARAM wparam, LPARAM lparam)\n{\n switch (msg) {\n case WM_DESTROY:\n case WM_KEYDOWN:\n PostQuitMessage(0);\n return 0;\n }\n return DefWindowProc(win, msg, wparam, lparam);\n}\n\nstatic double\nsys_get_time()\n{\n static LARGE_INTEGER freq = {};\n static LARGE_INTEGER counter0 = {};\n\n if (freq.QuadPart == 0) {\n QueryPerformanceFrequency(&freq);\n QueryPerformanceCounter(&counter0);\n }\n LARGE_INTEGER counter;\n QueryPerformanceCounter(&counter);\n return (counter.QuadPart - counter0.QuadPart) \/ (double)freq.QuadPart;\n}\n\nstatic void\nsys_display_text(system_context_t *sys, const char *text)\n{\n assert(sys && text);\n SetWindowText(sys->hwnd, text);\n}\n\nstatic bool\nwin_init(application_context_t *app)\n{\n assert(app && app->sys);\n system_context_t *sys = app->sys;\n\n WNDCLASS winclass = {};\n winclass.lpfnWndProc = win_message_handler;\n winclass.hInstance = GetModuleHandle(NULL);\n winclass.hCursor = LoadCursor(NULL, IDC_ARROW);\n winclass.lpszClassName = k_app_name;\n if (!RegisterClass(&winclass)) return false;\n\n RECT rect = { 0, 0, k_app_resx, k_app_resy };\n if (!AdjustWindowRect(&rect, WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX,\n FALSE))\n return false;\n\n sys->hwnd = CreateWindow(k_app_name, k_app_name,\n WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX |\n WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,\n rect.right - rect.left, rect.bottom - rect.top,\n NULL, NULL, NULL, 0);\n if (!sys->hwnd) return false;\n if (!(sys->hdc = GetDC(sys->hwnd))) return false;\n\n BITMAPINFO bi = {};\n bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biBitCount = 32;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biWidth = k_app_resx;\n bi.bmiHeader.biHeight = -k_app_resy;\n bi.bmiHeader.biSizeImage = k_app_resx * k_app_resy;\n sys->mdc = CreateCompatibleDC(sys->hdc);\n sys->hbm = CreateDIBSection(sys->hdc, &bi, DIB_RGB_COLORS, (void **)&app->displayptr,\n NULL, 0);\n\n if (!SelectObject(sys->mdc, sys->hbm)) return false;\n\n\n sys->quit_event = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);\n if (!sys->quit_event) return false;\n\n sys->render_semaphore = CreateSemaphore(NULL, 0, sys->thread_count, NULL);\n if (!sys->render_semaphore) return false;\n\n for (uint32_t i = 0; i < sys->thread_count; ++i) {\n sys->thread[i].app = app;\n sys->thread[i].h = NULL;\n sys->thread[i].id = i;\n sys->thread[i].done_event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);\n if (!sys->thread[i].done_event) return false;\n }\n for (uint32_t i = 0; i < sys->thread_count; ++i) {\n sys->thread[i].h = (HANDLE)_beginthreadex(NULL, 0, win_render_thread,\n &sys->thread[i], 0, NULL);\n if (!sys->thread[i].h) return false;\n }\n\n return true;\n}\n\nstatic void\nwin_deinit(system_context_t *sys)\n{\n assert(sys);\n if (sys->hdc) {\n ReleaseDC(sys->hwnd, sys->hdc);\n sys->hdc = NULL;\n }\n}\n\nstatic void\nwin_update(system_context_t *sys)\n{\n assert(sys);\n\n _InterlockedExchange(&sys->tile_index, 0);\n\n ReleaseSemaphore(sys->render_semaphore, sys->thread_count, NULL);\n\n HANDLE done[k_max_thread_count];\n for (uint32_t i = 0; i < sys->thread_count; ++i) {\n done[i] = sys->thread[i].done_event;\n }\n WaitForMultipleObjects(sys->thread_count, done, TRUE, INFINITE);\n\n BitBlt(sys->hdc, 0, 0, k_app_resx, k_app_resy, sys->mdc, 0, 0, SRCCOPY);\n}\n\nint\nmain()\n{\n system_context_t sys = {};\n application_context_t app = {};\n app.sys = &sys;\n\n SYSTEM_INFO si;\n GetSystemInfo(&si);\n sys.thread_count = (uint32_t)si.dwNumberOfProcessors;\n\n if (!win_init(&app)) {\n win_deinit(&sys);\n return 1;\n }\n\n MSG msg = { 0 };\n for (;;) {\n if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {\n DispatchMessage(&msg);\n if (msg.message == WM_QUIT) break;\n } else {\n update(&app);\n win_update(&sys);\n }\n }\n\n win_deinit(&sys);\n return 0;\n}\n<commit_msg>Update<commit_after>#include \"qjulia.h\"\n#include \"qjulia.cpp\"\n\n#define WIN32_LEAN_AND_MEAN\n#define NOMINMAX\n#include <windows.h>\n#include <process.h>\n\n#define k_max_thread_count 16\n\nstruct thread_context_t\n{\n HANDLE h;\n uint32_t id;\n HANDLE start_event, done_event;\n application_context_t *app;\n};\n\nstruct system_context_t\n{\n HWND hwnd;\n HDC hdc, mdc;\n HBITMAP hbm;\n\n HANDLE quit_event;\n uint32_t thread_count;\n thread_context_t thread[k_max_thread_count];\n volatile long tile_index;\n};\n\nstatic uint32_t WINAPI\nwin_render_thread(void *context)\n{\n thread_context_t *thread = (thread_context_t *)context;\n assert(thread && thread->app && thread->app->sys);\n\n system_context_t *sys = thread->app->sys;\n\n HANDLE wait[2] = { sys->quit_event, thread->start_event };\n\n for (;;) {\n DWORD r = WaitForMultipleObjects(2, wait, FALSE, INFINITE);\n if (r == WAIT_OBJECT_0) break;\n\n for (;;) {\n uint32_t idx = (uint32_t)_InterlockedExchangeAdd(&sys->tile_index, 1);\n if (idx >= k_tile_count) break;\n render_tile(thread->app, idx);\n }\n\n SetEvent(thread->done_event);\n }\n\n return 0;\n}\n\nstatic LRESULT CALLBACK\nwin_message_handler(HWND win, UINT msg, WPARAM wparam, LPARAM lparam)\n{\n switch (msg) {\n case WM_DESTROY:\n case WM_KEYDOWN:\n PostQuitMessage(0);\n return 0;\n }\n return DefWindowProc(win, msg, wparam, lparam);\n}\n\nstatic double\nsys_get_time()\n{\n static LARGE_INTEGER freq = {};\n static LARGE_INTEGER counter0 = {};\n\n if (freq.QuadPart == 0) {\n QueryPerformanceFrequency(&freq);\n QueryPerformanceCounter(&counter0);\n }\n LARGE_INTEGER counter;\n QueryPerformanceCounter(&counter);\n return (counter.QuadPart - counter0.QuadPart) \/ (double)freq.QuadPart;\n}\n\nstatic void\nsys_display_text(system_context_t *sys, const char *text)\n{\n assert(sys && text);\n SetWindowText(sys->hwnd, text);\n}\n\nstatic bool\nwin_init(application_context_t *app)\n{\n assert(app && app->sys);\n system_context_t *sys = app->sys;\n\n WNDCLASS winclass = {};\n winclass.lpfnWndProc = win_message_handler;\n winclass.hInstance = GetModuleHandle(NULL);\n winclass.hCursor = LoadCursor(NULL, IDC_ARROW);\n winclass.lpszClassName = k_app_name;\n if (!RegisterClass(&winclass)) return false;\n\n RECT rect = { 0, 0, k_app_resx, k_app_resy };\n if (!AdjustWindowRect(&rect, WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX,\n FALSE))\n return false;\n\n sys->hwnd = CreateWindow(k_app_name, k_app_name,\n WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX |\n WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,\n rect.right - rect.left, rect.bottom - rect.top,\n NULL, NULL, NULL, 0);\n if (!sys->hwnd) return false;\n if (!(sys->hdc = GetDC(sys->hwnd))) return false;\n\n BITMAPINFO bi = {};\n bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biBitCount = 32;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biWidth = k_app_resx;\n bi.bmiHeader.biHeight = -k_app_resy;\n bi.bmiHeader.biSizeImage = k_app_resx * k_app_resy;\n sys->mdc = CreateCompatibleDC(sys->hdc);\n sys->hbm = CreateDIBSection(sys->hdc, &bi, DIB_RGB_COLORS, (void **)&app->displayptr,\n NULL, 0);\n\n if (!SelectObject(sys->mdc, sys->hbm)) return false;\n\n\n sys->quit_event = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);\n if (!sys->quit_event) return false;\n\n for (uint32_t i = 0; i < sys->thread_count; ++i) {\n sys->thread[i].app = app;\n sys->thread[i].h = NULL;\n sys->thread[i].id = i;\n sys->thread[i].start_event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);\n sys->thread[i].done_event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);\n if (!sys->thread[i].done_event || !sys->thread[i].start_event) return false;\n }\n for (uint32_t i = 0; i < sys->thread_count; ++i) {\n sys->thread[i].h = (HANDLE)_beginthreadex(NULL, 0, win_render_thread,\n &sys->thread[i], 0, NULL);\n if (!sys->thread[i].h) return false;\n }\n\n return true;\n}\n\nstatic void\nwin_deinit(system_context_t *sys)\n{\n assert(sys);\n\n \/\/ terminate all worker threads\n SetEvent(sys->quit_event);\n HANDLE done[k_max_thread_count];\n for (uint32_t i = 0; i < sys->thread_count; ++i) done[i] = sys->thread[i].h;\n WaitForMultipleObjects(sys->thread_count, done, TRUE, INFINITE);\n for (uint32_t i = 0; i < sys->thread_count; ++i) CloseHandle(sys->thread[i].h);\n\n if (sys->hdc) {\n ReleaseDC(sys->hwnd, sys->hdc);\n sys->hdc = NULL;\n }\n}\n\nstatic void\nwin_update(system_context_t *sys)\n{\n assert(sys);\n\n _InterlockedExchange(&sys->tile_index, 0);\n\n HANDLE done[k_max_thread_count];\n for (uint32_t i = 0; i < sys->thread_count; ++i) {\n done[i] = sys->thread[i].done_event;\n SetEvent(sys->thread[i].start_event);\n }\n WaitForMultipleObjects(sys->thread_count, done, TRUE, INFINITE);\n\n BitBlt(sys->hdc, 0, 0, k_app_resx, k_app_resy, sys->mdc, 0, 0, SRCCOPY);\n}\n\nint\nmain()\n{\n system_context_t sys = {};\n application_context_t app = {};\n app.sys = &sys;\n\n SYSTEM_INFO si;\n GetSystemInfo(&si);\n sys.thread_count = (uint32_t)si.dwNumberOfProcessors;\n\n if (!win_init(&app)) {\n win_deinit(&sys);\n return 1;\n }\n\n MSG msg = { 0 };\n for (;;) {\n if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {\n DispatchMessage(&msg);\n if (msg.message == WM_QUIT) break;\n } else {\n update(&app);\n win_update(&sys);\n }\n }\n\n win_deinit(&sys);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================\n\/\/\n\/\/\tCopyright (C)1999 by Eric Sunshine <sunshine@sunshineco.com>\n\/\/\n\/\/ The contents of this file are copyrighted by Eric Sunshine. This work is\n\/\/ distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n\/\/ without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n\/\/ PARTICULAR PURPOSE. You may distribute this file provided that this\n\/\/ copyright notice is retained. Send comments to <sunshine@sunshineco.com>.\n\/\/\n\/\/=============================================================================\n\/\/-----------------------------------------------------------------------------\n\/\/ NeXTSystemDriver.cpp\n\/\/\n\/\/\tNeXT-specific hardware & operating\/system drivers for CrystalSpace.\n\/\/\n\/\/-----------------------------------------------------------------------------\n#include \"NeXTSystemDriver.h\"\n#include \"NeXTSystemProxy.h\"\n#include \"version.h\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ COM interface to NeXT-specific csSystemDriver.\n\/\/-----------------------------------------------------------------------------\nBEGIN_INTERFACE_TABLE(SysSystemDriver)\n IMPLEMENTS_COMPOSITE_INTERFACE(System)\n IMPLEMENTS_COMPOSITE_INTERFACE(NeXTSystemDriver)\nEND_INTERFACE_TABLE()\n\nIMPLEMENT_UNKNOWN_NODELETE(SysSystemDriver)\nIMPLEMENT_COMPOSITE_UNKNOWN_AS_EMBEDDED(SysSystemDriver, NeXTSystemDriver)\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constructor\n\/\/-----------------------------------------------------------------------------\nSysSystemDriver::SysSystemDriver() : csSystemDriver(), proxy(0)\n {\n printf(\"Crystal Space for \" OS_NEXT_DESCRIPTION\" \" VERSION \"\\nPorted to \"\n\tOS_NEXT_DESCRIPTION \" by Eric Sunshine <sunshine@sunshineco.com>\\n\\n\");\n }\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Destructor\n\/\/-----------------------------------------------------------------------------\nSysSystemDriver::~SysSystemDriver()\n {\n if (proxy != 0)\n\tdelete proxy;\n }\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Initialize -- Create the COM --> Objective-C proxy.\n\/\/-----------------------------------------------------------------------------\nbool SysSystemDriver::Initialize( int argc, char* argv[], IConfig* pconfig )\n {\n proxy = new NeXTSystemProxy( this );\n return superclass::Initialize( argc, argv, pconfig );\n }\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Loop -- Start the Application's run-loop; return at termination.\n\/\/-----------------------------------------------------------------------------\nvoid SysSystemDriver::Loop()\n {\n proxy->start_loop(); \/\/ Returns when user requests shutdown.\n }\n<commit_msg>Small whitespace fix.<commit_after>\/\/=============================================================================\n\/\/\n\/\/\tCopyright (C)1999 by Eric Sunshine <sunshine@sunshineco.com>\n\/\/\n\/\/ The contents of this file are copyrighted by Eric Sunshine. This work is\n\/\/ distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n\/\/ without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n\/\/ PARTICULAR PURPOSE. You may distribute this file provided that this\n\/\/ copyright notice is retained. Send comments to <sunshine@sunshineco.com>.\n\/\/\n\/\/=============================================================================\n\/\/-----------------------------------------------------------------------------\n\/\/ NeXTSystemDriver.cpp\n\/\/\n\/\/\tNeXT-specific hardware & operating\/system drivers for CrystalSpace.\n\/\/\n\/\/-----------------------------------------------------------------------------\n#include \"NeXTSystemDriver.h\"\n#include \"NeXTSystemProxy.h\"\n#include \"version.h\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ COM interface to NeXT-specific csSystemDriver.\n\/\/-----------------------------------------------------------------------------\nBEGIN_INTERFACE_TABLE(SysSystemDriver)\n IMPLEMENTS_COMPOSITE_INTERFACE(System)\n IMPLEMENTS_COMPOSITE_INTERFACE(NeXTSystemDriver)\nEND_INTERFACE_TABLE()\n\nIMPLEMENT_UNKNOWN_NODELETE(SysSystemDriver)\nIMPLEMENT_COMPOSITE_UNKNOWN_AS_EMBEDDED(SysSystemDriver, NeXTSystemDriver)\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constructor\n\/\/-----------------------------------------------------------------------------\nSysSystemDriver::SysSystemDriver() : csSystemDriver(), proxy(0)\n {\n printf(\"Crystal Space for \" OS_NEXT_DESCRIPTION \" \" VERSION \"\\nPorted to \"\n\tOS_NEXT_DESCRIPTION \" by Eric Sunshine <sunshine@sunshineco.com>\\n\\n\");\n }\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Destructor\n\/\/-----------------------------------------------------------------------------\nSysSystemDriver::~SysSystemDriver()\n {\n if (proxy != 0)\n\tdelete proxy;\n }\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Initialize -- Create the COM --> Objective-C proxy.\n\/\/-----------------------------------------------------------------------------\nbool SysSystemDriver::Initialize( int argc, char* argv[], IConfig* pconfig )\n {\n proxy = new NeXTSystemProxy( this );\n return superclass::Initialize( argc, argv, pconfig );\n }\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Loop -- Start the Application's run-loop; return at termination.\n\/\/-----------------------------------------------------------------------------\nvoid SysSystemDriver::Loop()\n {\n proxy->start_loop(); \/\/ Returns when user requests shutdown.\n }\n<|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*-\n * Copyright (C) 2008 Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\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\n * OpenSceneGraph Public License for more details.\n *\/\n\n#include <osgAnimation\/VertexInfluence>\n#include <osgAnimation\/RigGeometry>\n#include <osgAnimation\/RigTransformSoftware>\n#include <sstream>\n\nusing namespace osgAnimation;\n\n\/\/ The idea is to compute a bounding box with a factor x of the first step we compute the bounding box\nosg::BoundingBox RigComputeBoundingBoxCallback::computeBound(const osg::Drawable& drawable) const\n{\n const osgAnimation::RigGeometry& rig = dynamic_cast<const osgAnimation::RigGeometry&>(drawable);\n\n \/\/ if a valid initial bounding box is set we use it without asking more\n if (rig.getInitialBound().valid())\n return rig.getInitialBound();\n\n if (_computed)\n return _boundingBox;\n\n \/\/ if the computing of bb is invalid (like no geometry inside)\n \/\/ then don't tag the bounding box as computed\n osg::BoundingBox bb = rig.computeBoundingBox();\n if (!bb.valid())\n return bb;\n\n\n _boundingBox.expandBy(bb);\n osg::Vec3 center = _boundingBox.center();\n osg::Vec3 vec = (_boundingBox._max-center)*_factor;\n _boundingBox.expandBy(center + vec);\n _boundingBox.expandBy(center - vec);\n _computed = true;\n\/\/ OSG_NOTICE << \"build the bounding box for RigGeometry \" << rig.getName() << \" \" << _boundingBox._min << \" \" << _boundingBox._max << std::endl;\n return _boundingBox;\n}\n\n\nRigGeometry::RigGeometry()\n{\n _supportsDisplayList = false;\n setUseVertexBufferObjects(true);\n setUpdateCallback(new UpdateRigGeometry);\n setDataVariance(osg::Object::DYNAMIC);\n _needToComputeMatrix = true;\n _matrixFromSkeletonToGeometry = _invMatrixFromSkeletonToGeometry = osg::Matrix::identity();\n \/\/ disable the computation of boundingbox for the rig mesh\n setComputeBoundingBoxCallback(new RigComputeBoundingBoxCallback());\n _rigTransformImplementation = new osgAnimation::RigTransformSoftware;\n\n}\n\n\nRigGeometry::RigGeometry(const RigGeometry& b, const osg::CopyOp& copyop) :\n osg::Geometry(b,copyop),\n _geometry(b._geometry),\n _rigTransformImplementation(osg::clone(_rigTransformImplementation.get(), copyop)),\n _vertexInfluenceMap(b._vertexInfluenceMap),\n _needToComputeMatrix(b._needToComputeMatrix)\n{\n _needToComputeMatrix = true;\n _matrixFromSkeletonToGeometry = _invMatrixFromSkeletonToGeometry = osg::Matrix::identity();\n \/\/ disable the computation of boundingbox for the rig mesh\n\n setComputeBoundingBoxCallback(new RigComputeBoundingBoxCallback());\n \/\/ we don't copy the RigImplementation yet. because the RigImplementation need to be initialized in a valid graph, with a skeleton ...\n \/\/ don't know yet what to do with a clone of a RigGeometry\n\n}\n\n\nconst osg::Matrix& RigGeometry::getMatrixFromSkeletonToGeometry() const { return _matrixFromSkeletonToGeometry; }\nconst osg::Matrix& RigGeometry::getInvMatrixFromSkeletonToGeometry() const { return _invMatrixFromSkeletonToGeometry;}\n\n\nvoid RigGeometry::computeMatrixFromRootSkeleton()\n{\n if (!_root.valid())\n {\n OSG_WARN << \"Warning \" << className() <<\"::computeMatrixFromRootSkeleton if you have this message it means you miss to call buildTransformer(Skeleton* root), or your RigGeometry (\" << getName() <<\") is not attached to a Skeleton subgraph\" << std::endl;\n return;\n }\n osg::MatrixList mtxList = getParent(0)->getWorldMatrices(_root.get());\n osg::Matrix notRoot = _root->getMatrix();\n _matrixFromSkeletonToGeometry = mtxList[0] * osg::Matrix::inverse(notRoot);\n _invMatrixFromSkeletonToGeometry = osg::Matrix::inverse(_matrixFromSkeletonToGeometry);\n _needToComputeMatrix = false;\n}\n\nvoid RigGeometry::update()\n{\n RigTransform& implementation = *_rigTransformImplementation;\n (implementation)(*this);\n}\n\nvoid RigGeometry::copyFrom(osg::Geometry& from)\n{\n if (this==&from) return;\n\n osg::Geometry& target = *this;\n\n target.setStateSet(from.getStateSet());\n\n \/\/ copy over primitive sets.\n target.getPrimitiveSetList() = from.getPrimitiveSetList();\n\n if (from.getVertexArray())\n {\n target.setVertexArray(from.getVertexArray());\n }\n\n if (from.getNormalArray())\n {\n target.setNormalArray(from.getNormalArray());\n }\n\n if (from.getColorArray())\n {\n target.setColorArray(from.getColorArray());\n }\n\n if (from.getSecondaryColorArray())\n {\n target.setSecondaryColorArray(from.getSecondaryColorArray());\n }\n\n if (from.getFogCoordArray())\n {\n target.setFogCoordArray(from.getFogCoordArray());\n }\n\n for(unsigned int ti=0;ti<from.getNumTexCoordArrays();++ti)\n {\n if (from.getTexCoordArray(ti))\n {\n target.setTexCoordArray(ti,from.getTexCoordArray(ti));\n }\n }\n\n osg::Geometry::ArrayList& arrayList = from.getVertexAttribArrayList();\n for(unsigned int vi=0;vi< arrayList.size();++vi)\n {\n osg::Array* array = arrayList[vi].get();\n if (array)\n {\n target.setVertexAttribArray(vi,array);\n }\n }\n}\n\n\n\n\n<commit_msg>Fixed crash in copy constructor due to copy and paste\/typo.<commit_after>\/* -*-c++-*-\n * Copyright (C) 2008 Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\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\n * OpenSceneGraph Public License for more details.\n *\/\n\n#include <osgAnimation\/VertexInfluence>\n#include <osgAnimation\/RigGeometry>\n#include <osgAnimation\/RigTransformSoftware>\n#include <sstream>\n\nusing namespace osgAnimation;\n\n\/\/ The idea is to compute a bounding box with a factor x of the first step we compute the bounding box\nosg::BoundingBox RigComputeBoundingBoxCallback::computeBound(const osg::Drawable& drawable) const\n{\n const osgAnimation::RigGeometry& rig = dynamic_cast<const osgAnimation::RigGeometry&>(drawable);\n\n \/\/ if a valid initial bounding box is set we use it without asking more\n if (rig.getInitialBound().valid())\n return rig.getInitialBound();\n\n if (_computed)\n return _boundingBox;\n\n \/\/ if the computing of bb is invalid (like no geometry inside)\n \/\/ then don't tag the bounding box as computed\n osg::BoundingBox bb = rig.computeBoundingBox();\n if (!bb.valid())\n return bb;\n\n\n _boundingBox.expandBy(bb);\n osg::Vec3 center = _boundingBox.center();\n osg::Vec3 vec = (_boundingBox._max-center)*_factor;\n _boundingBox.expandBy(center + vec);\n _boundingBox.expandBy(center - vec);\n _computed = true;\n\/\/ OSG_NOTICE << \"build the bounding box for RigGeometry \" << rig.getName() << \" \" << _boundingBox._min << \" \" << _boundingBox._max << std::endl;\n return _boundingBox;\n}\n\n\nRigGeometry::RigGeometry()\n{\n _supportsDisplayList = false;\n setUseVertexBufferObjects(true);\n setUpdateCallback(new UpdateRigGeometry);\n setDataVariance(osg::Object::DYNAMIC);\n _needToComputeMatrix = true;\n _matrixFromSkeletonToGeometry = _invMatrixFromSkeletonToGeometry = osg::Matrix::identity();\n \/\/ disable the computation of boundingbox for the rig mesh\n setComputeBoundingBoxCallback(new RigComputeBoundingBoxCallback());\n _rigTransformImplementation = new osgAnimation::RigTransformSoftware;\n\n}\n\n\nRigGeometry::RigGeometry(const RigGeometry& b, const osg::CopyOp& copyop) :\n osg::Geometry(b,copyop),\n _geometry(b._geometry),\n _rigTransformImplementation(osg::clone(b._rigTransformImplementation.get(), copyop)),\n _vertexInfluenceMap(b._vertexInfluenceMap),\n _needToComputeMatrix(b._needToComputeMatrix)\n{\n _needToComputeMatrix = true;\n _matrixFromSkeletonToGeometry = _invMatrixFromSkeletonToGeometry = osg::Matrix::identity();\n \/\/ disable the computation of boundingbox for the rig mesh\n\n setComputeBoundingBoxCallback(new RigComputeBoundingBoxCallback());\n \/\/ we don't copy the RigImplementation yet. because the RigImplementation need to be initialized in a valid graph, with a skeleton ...\n \/\/ don't know yet what to do with a clone of a RigGeometry\n\n}\n\n\nconst osg::Matrix& RigGeometry::getMatrixFromSkeletonToGeometry() const { return _matrixFromSkeletonToGeometry; }\nconst osg::Matrix& RigGeometry::getInvMatrixFromSkeletonToGeometry() const { return _invMatrixFromSkeletonToGeometry;}\n\n\nvoid RigGeometry::computeMatrixFromRootSkeleton()\n{\n if (!_root.valid())\n {\n OSG_WARN << \"Warning \" << className() <<\"::computeMatrixFromRootSkeleton if you have this message it means you miss to call buildTransformer(Skeleton* root), or your RigGeometry (\" << getName() <<\") is not attached to a Skeleton subgraph\" << std::endl;\n return;\n }\n osg::MatrixList mtxList = getParent(0)->getWorldMatrices(_root.get());\n osg::Matrix notRoot = _root->getMatrix();\n _matrixFromSkeletonToGeometry = mtxList[0] * osg::Matrix::inverse(notRoot);\n _invMatrixFromSkeletonToGeometry = osg::Matrix::inverse(_matrixFromSkeletonToGeometry);\n _needToComputeMatrix = false;\n}\n\nvoid RigGeometry::update()\n{\n RigTransform& implementation = *_rigTransformImplementation;\n (implementation)(*this);\n}\n\nvoid RigGeometry::copyFrom(osg::Geometry& from)\n{\n if (this==&from) return;\n\n osg::Geometry& target = *this;\n\n target.setStateSet(from.getStateSet());\n\n \/\/ copy over primitive sets.\n target.getPrimitiveSetList() = from.getPrimitiveSetList();\n\n if (from.getVertexArray())\n {\n target.setVertexArray(from.getVertexArray());\n }\n\n if (from.getNormalArray())\n {\n target.setNormalArray(from.getNormalArray());\n }\n\n if (from.getColorArray())\n {\n target.setColorArray(from.getColorArray());\n }\n\n if (from.getSecondaryColorArray())\n {\n target.setSecondaryColorArray(from.getSecondaryColorArray());\n }\n\n if (from.getFogCoordArray())\n {\n target.setFogCoordArray(from.getFogCoordArray());\n }\n\n for(unsigned int ti=0;ti<from.getNumTexCoordArrays();++ti)\n {\n if (from.getTexCoordArray(ti))\n {\n target.setTexCoordArray(ti,from.getTexCoordArray(ti));\n }\n }\n\n osg::Geometry::ArrayList& arrayList = from.getVertexAttribArrayList();\n for(unsigned int vi=0;vi< arrayList.size();++vi)\n {\n osg::Array* array = arrayList[vi].get();\n if (array)\n {\n target.setVertexAttribArray(vi,array);\n }\n }\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#pragma once\n\n\/**\n * UAVCAN version definition\n * \/\/ TODO: Use git short hash as build id\n *\/\n#define UAVCAN_VERSION_MAJOR 0\n#define UAVCAN_VERSION_MINOR 1\n#define UAVCAN_VERSION_BUILD 0\n\n\/**\n * UAVCAN can be compiled in C++11 mode.\n * This macro allows to detect which version of the C++ standard is being used.\n *\/\n#define UAVCAN_CPP11 2011\n#define UAVCAN_CPP03 2003\n\n#ifndef UAVCAN_CPP_VERSION\n# if __cplusplus > 201200\n# error Unsupported C++ standard\n# elif (__cplusplus > 201100) || defined(__GXX_EXPERIMENTAL_CXX0X__)\n# define UAVCAN_CPP_VERSION UAVCAN_CPP11\n# else\n# define UAVCAN_CPP_VERSION UAVCAN_CPP03\n# endif\n#endif\n\n\/**\n * UAVCAN can be explicitly told to ignore exceptions, or it can be detected automatically.\n *\/\n#ifndef UAVCAN_EXCEPTIONS\n# if __EXCEPTIONS || _HAS_EXCEPTIONS\n# define UAVCAN_EXCEPTIONS 1\n# else\n# define UAVCAN_EXCEPTIONS 0\n# endif\n#endif\n\n\/**\n * Struct layout control.\n * Define UAVCAN_PACK_STRUCTS = 1 to reduce memory usage.\n *\/\n#ifndef UAVCAN_PACK_STRUCTS\n# define UAVCAN_PACK_STRUCTS 0\n#endif\n#ifndef UAVCAN_PACKED_BEGIN\n# define UAVCAN_PACKED_BEGIN\n#endif\n#ifndef UAVCAN_PACKED_END\n# define UAVCAN_PACKED_END\n#endif\n\n\/**\n * Declaration visibility\n * http:\/\/gcc.gnu.org\/wiki\/Visibility\n *\/\n#ifndef UAVCAN_EXPORT\n# define UAVCAN_EXPORT\n#endif\n\n\/**\n * Trade-off between ROM\/RAM usage and functionality\/determinism.\n * Note that this feature is not well tested and should be avoided.\n * Use code search for UAVCAN_TINY to find what functionality will be disabled.\n * This is particularly useful for embedded systems with less than 40kB of ROM.\n *\/\n#ifndef UAVCAN_TINY\n# define UAVCAN_TINY 0\n#endif\n\n\/**\n * It might make sense to remove toString() methods for an embedded system\n *\/\n#ifndef UAVCAN_TOSTRING\n\/\/ Objective is to make sure that we're NOT on a resource constrained platform\n# if __linux__ || __linux || __APPLE__ || _WIN64 || _WIN32\n# define UAVCAN_TOSTRING 1\n# else\n# define UAVCAN_TOSTRING 0\n# endif\n#endif\n\n#if UAVCAN_TOSTRING\n# include <string>\n# include <cstdio>\n#endif\n\n\/**\n * Some C++ implementations are half-broken and do not implement the placement new operator.\n * Setting this preprocessor symbol to 1 makes libuavcan implement its own operator new (std::size_t, void*),\n * and its delete counterpart.\n * This option may be removed in future.\n *\/\n#ifndef UAVCAN_IMPLEMENT_PLACEMENT_NEW\n# define UAVCAN_IMPLEMENT_PLACEMENT_NEW 0\n#endif\n\nnamespace uavcan\n{\n\n\/**\n * Should be OK for any target arch up to AMD64 and any compiler.\n * The library leverages compile-time checks to ensure that all types that are subject to dynamic allocation\n * fit this size; otherwise compilation fails.\n *\/\n#if UAVCAN_MEM_POOL_BLOCK_SIZE\n\/\/\/ Explicitly specified by the user.\nstatic const unsigned MemPoolBlockSize = UAVCAN_MEM_POOL_BLOCK_SIZE;\n#elif defined(__BIGGEST_ALIGNMENT__) && (__BIGGEST_ALIGNMENT__ <= 8)\n\/\/\/ Convenient default for GCC-like compilers - if alignment allows, pool block size can be safely reduced.\nstatic const unsigned MemPoolBlockSize = 56;\n#else\n\/\/\/ Safe default that should be OK for any platform.\nstatic const unsigned MemPoolBlockSize = 64;\n#endif\n\n#ifdef __BIGGEST_ALIGNMENT__\nstatic const unsigned MemPoolAlignment = __BIGGEST_ALIGNMENT__;\n#else\nstatic const unsigned MemPoolAlignment = 16;\n#endif\n\ntypedef char _alignment_check_for_MEM_POOL_BLOCK_SIZE[((MemPoolBlockSize & (MemPoolAlignment - 1)) == 0) ? 1 : -1];\n\ntemplate <typename T>\nstruct UAVCAN_EXPORT IsDynamicallyAllocatable\n{\n static void check()\n {\n char dummy[(sizeof(T) <= MemPoolBlockSize) ? 1 : -1];\n (void)dummy;\n }\n};\n\n}\n<commit_msg>Macro UAVCAN_ASSERT() instead of assert() (not used yet, see the next commit)<commit_after>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#pragma once\n\n\/**\n * UAVCAN version definition\n * \/\/ TODO: Use git short hash as build id\n *\/\n#define UAVCAN_VERSION_MAJOR 0\n#define UAVCAN_VERSION_MINOR 1\n#define UAVCAN_VERSION_BUILD 0\n\n\/**\n * UAVCAN can be compiled in C++11 mode.\n * This macro allows to detect which version of the C++ standard is being used.\n *\/\n#define UAVCAN_CPP11 2011\n#define UAVCAN_CPP03 2003\n\n#ifndef UAVCAN_CPP_VERSION\n# if __cplusplus > 201200\n# error Unsupported C++ standard\n# elif (__cplusplus > 201100) || defined(__GXX_EXPERIMENTAL_CXX0X__)\n# define UAVCAN_CPP_VERSION UAVCAN_CPP11\n# else\n# define UAVCAN_CPP_VERSION UAVCAN_CPP03\n# endif\n#endif\n\n\/**\n * UAVCAN can be explicitly told to ignore exceptions, or it can be detected automatically.\n *\/\n#ifndef UAVCAN_EXCEPTIONS\n# if __EXCEPTIONS || _HAS_EXCEPTIONS\n# define UAVCAN_EXCEPTIONS 1\n# else\n# define UAVCAN_EXCEPTIONS 0\n# endif\n#endif\n\n\/**\n * Struct layout control.\n * Define UAVCAN_PACK_STRUCTS = 1 to reduce memory usage.\n *\/\n#ifndef UAVCAN_PACK_STRUCTS\n# define UAVCAN_PACK_STRUCTS 0\n#endif\n#ifndef UAVCAN_PACKED_BEGIN\n# define UAVCAN_PACKED_BEGIN\n#endif\n#ifndef UAVCAN_PACKED_END\n# define UAVCAN_PACKED_END\n#endif\n\n\/**\n * Declaration visibility\n * http:\/\/gcc.gnu.org\/wiki\/Visibility\n *\/\n#ifndef UAVCAN_EXPORT\n# define UAVCAN_EXPORT\n#endif\n\n\/**\n * Trade-off between ROM\/RAM usage and functionality\/determinism.\n * Note that this feature is not well tested and should be avoided.\n * Use code search for UAVCAN_TINY to find what functionality will be disabled.\n * This is particularly useful for embedded systems with less than 40kB of ROM.\n *\/\n#ifndef UAVCAN_TINY\n# define UAVCAN_TINY 0\n#endif\n\n\/**\n * It might make sense to remove toString() methods for an embedded system\n *\/\n#ifndef UAVCAN_TOSTRING\n\/\/ Objective is to make sure that we're NOT on a resource constrained platform\n# if __linux__ || __linux || __APPLE__ || _WIN64 || _WIN32\n# define UAVCAN_TOSTRING 1\n# else\n# define UAVCAN_TOSTRING 0\n# endif\n#endif\n\n#if UAVCAN_TOSTRING\n# include <string>\n# include <cstdio>\n#endif\n\n\/**\n * Some C++ implementations are half-broken and do not implement the placement new operator.\n * Setting this preprocessor symbol to 1 makes libuavcan implement its own operator new (std::size_t, void*),\n * and its delete counterpart.\n * This option may be removed in future.\n *\/\n#ifndef UAVCAN_IMPLEMENT_PLACEMENT_NEW\n# define UAVCAN_IMPLEMENT_PLACEMENT_NEW 0\n#endif\n\n\/**\n * Run time checks.\n * Resolves to the standard assert() by default.\n * Can be disabled completely.\n *\/\n#ifndef UAVCAN_ASSERT\n# if UAVCAN_NO_ASSERTIONS\n# define UAVCAN_ASSERT(x)\n# else\n# define UAVCAN_ASSERT(x) assert(x)\n# endif\n#endif\n\nnamespace uavcan\n{\n\n\/**\n * Should be OK for any target arch up to AMD64 and any compiler.\n * The library leverages compile-time checks to ensure that all types that are subject to dynamic allocation\n * fit this size; otherwise compilation fails.\n *\/\n#if UAVCAN_MEM_POOL_BLOCK_SIZE\n\/\/\/ Explicitly specified by the user.\nstatic const unsigned MemPoolBlockSize = UAVCAN_MEM_POOL_BLOCK_SIZE;\n#elif defined(__BIGGEST_ALIGNMENT__) && (__BIGGEST_ALIGNMENT__ <= 8)\n\/\/\/ Convenient default for GCC-like compilers - if alignment allows, pool block size can be safely reduced.\nstatic const unsigned MemPoolBlockSize = 56;\n#else\n\/\/\/ Safe default that should be OK for any platform.\nstatic const unsigned MemPoolBlockSize = 64;\n#endif\n\n#ifdef __BIGGEST_ALIGNMENT__\nstatic const unsigned MemPoolAlignment = __BIGGEST_ALIGNMENT__;\n#else\nstatic const unsigned MemPoolAlignment = 16;\n#endif\n\ntypedef char _alignment_check_for_MEM_POOL_BLOCK_SIZE[((MemPoolBlockSize & (MemPoolAlignment - 1)) == 0) ? 1 : -1];\n\ntemplate <typename T>\nstruct UAVCAN_EXPORT IsDynamicallyAllocatable\n{\n static void check()\n {\n char dummy[(sizeof(T) <= MemPoolBlockSize) ? 1 : -1];\n (void)dummy;\n }\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <constrained_ik\/collision_robot_fcl_detailed.h>\n#include <ros\/ros.h>\n#include <ctime>\n\nnamespace constrained_ik\n{\n using namespace collision_detection;\n\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state) const\n {\n return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL, NULL);\n }\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm) const\n {\n return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm, NULL);\n }\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const std::set<const robot_model::LinkModel*> &active_components_only) const\n {\n return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL, &active_components_only);\n }\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm, const std::set<const robot_model::LinkModel*> &active_components_only) const\n {\n return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm, &active_components_only);\n }\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailedHelper(const robot_state::RobotState &state, const AllowedCollisionMatrix *acm, const std::set<const robot_model::LinkModel*> *active_components_only) const\n {\n double duration;\n std::clock_t start = std::clock();\n\n FCLManager manager;\n CollisionRobotFCLDetailed::allocSelfCollisionBroadPhase(state, manager);\n\n DistanceResultDetailed drd(acm, active_components_only);\n\n manager.manager_->distance(&drd, &CollisionRobotFCLDetailed::distanceDetailedCallback);\n duration = ( std::clock() - start ) \/ (double) CLOCKS_PER_SEC;\n ROS_INFO(\"Duration: %f\", duration);\n return drd.distance_detailed_;\n }\n\n bool CollisionRobotFCLDetailed::distanceDetailedCallback(fcl::CollisionObject* o1, fcl::CollisionObject* o2, void* data, double& min_dist)\n {\n DistanceResultDetailed* cdata = reinterpret_cast<DistanceResultDetailed*>(data);\n\n const CollisionGeometryData* cd1 = static_cast<const CollisionGeometryData*>(o1->collisionGeometry()->getUserData());\n const CollisionGeometryData* cd2 = static_cast<const CollisionGeometryData*>(o2->collisionGeometry()->getUserData());\n\n \/\/ If active components are specified\n if (cdata->active_components_only_)\n {\n const robot_model::LinkModel *l1 = cd1->type == BodyTypes::ROBOT_LINK ? cd1->ptr.link : (cd1->type == BodyTypes::ROBOT_ATTACHED ? cd1->ptr.ab->getAttachedLink() : NULL);\n const robot_model::LinkModel *l2 = cd2->type == BodyTypes::ROBOT_LINK ? cd2->ptr.link : (cd2->type == BodyTypes::ROBOT_ATTACHED ? cd2->ptr.ab->getAttachedLink() : NULL);\n\n \/\/ If neither of the involved components is active\n if ((!l1 || cdata->active_components_only_->find(l1) == cdata->active_components_only_->end()) &&\n (!l2 || cdata->active_components_only_->find(l2) == cdata->active_components_only_->end()))\n {\n return false;\n }\n }\n\n \/\/ use the collision matrix (if any) to avoid certain distance checks\n bool always_allow_collision = false;\n if (cdata->acm_)\n {\n AllowedCollision::Type type;\n\n bool found = cdata->acm_->getAllowedCollision(cd1->getID(), cd2->getID(), type);\n if (found)\n {\n \/\/ if we have an entry in the collision matrix, we read it\n if (type == AllowedCollision::ALWAYS)\n {\n always_allow_collision = true;\n if (!cdata->verbose)\n logDebug(\"Collision between '%s' and '%s' is always allowed. No contacts are computed.\",\n cd1->getID().c_str(), cd2->getID().c_str());\n }\n }\n }\n\n \/\/ check if a link is touching an attached object\n if (cd1->type == BodyTypes::ROBOT_LINK && cd2->type == BodyTypes::ROBOT_ATTACHED)\n {\n const std::set<std::string> &tl = cd2->ptr.ab->getTouchLinks();\n if (tl.find(cd1->getID()) != tl.end())\n {\n always_allow_collision = true;\n if (!cdata->verbose)\n logDebug(\"Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.\",\n cd1->getID().c_str(), cd2->getID().c_str());\n }\n }\n else\n {\n if (cd2->type == BodyTypes::ROBOT_LINK && cd1->type == BodyTypes::ROBOT_ATTACHED)\n {\n const std::set<std::string> &tl = cd1->ptr.ab->getTouchLinks();\n if (tl.find(cd2->getID()) != tl.end())\n {\n always_allow_collision = true;\n if (!cdata->verbose)\n logDebug(\"Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.\",\n cd2->getID().c_str(), cd1->getID().c_str());\n }\n }\n }\n\n if(always_allow_collision)\n {\n return false;\n }\n\n if (!cdata->verbose)\n logDebug(\"Actually checking collisions between %s and %s\", cd1->getID().c_str(), cd2->getID().c_str());\n\n\n fcl::DistanceResult dist_result;\n dist_result.min_distance = 0.1;\n \/\/dist_result.update(0.1, NULL, NULL, fcl::DistanceResult::NONE, fcl::DistanceResult::NONE);\n double d = fcl::distance(o1, o2, fcl::DistanceRequest(true), dist_result);\n\n \/\/ Check if either object is already in the map. If not add it or if present\n \/\/ check to see if the new distance is closer. If closer remove the existing\n \/\/ one and add the new distance information.\n if (d < 0.1)\n {\n std::map<std::string, fcl::DistanceResult>::iterator it;\n it = cdata->distance_detailed_.find(cd1->ptr.obj->id_);\n if (it == cdata->distance_detailed_.end())\n {\n cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));\n }\n else\n {\n if (dist_result.min_distance < it->second.min_distance)\n {\n cdata->distance_detailed_.erase(cd1->ptr.obj->id_);\n cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));\n }\n }\n\n it = cdata->distance_detailed_.find(cd2->ptr.obj->id_);\n if (it == cdata->distance_detailed_.end())\n {\n cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));\n }\n else\n {\n if (dist_result.min_distance < it->second.min_distance)\n {\n cdata->distance_detailed_.erase(cd2->ptr.obj->id_);\n cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));\n }\n }\n }\n return false;\n }\n\n bool CollisionRobotFCLDetailed::getDistanceInfo(const DistanceDetailedMap distance_detailed, const std::string link_name, CollisionRobotFCLDetailed::DistanceInfo &dist_info)\n {\n std::map<std::string, fcl::DistanceResult>::const_iterator it;\n it = distance_detailed.find(link_name);\n\n if (it != distance_detailed.end())\n {\n fcl::DistanceResult dist = static_cast<const fcl::DistanceResult>(it->second);\n const collision_detection::CollisionGeometryData* cd1 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o1->getUserData());\n const collision_detection::CollisionGeometryData* cd2 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o2->getUserData());\n if (cd1->ptr.link->getName() == link_name)\n {\n dist_info.nearest_obsticle = cd2->ptr.link->getName();\n dist_info.link_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);\n dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);\n dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[1]-dist.nearest_points[0]).data.vs);\n dist_info.avoidance_vector.norm();\n dist_info.distance = dist.min_distance;\n }\n else if (cd2->ptr.link->getName() == link_name)\n {\n dist_info.nearest_obsticle = cd1->ptr.link->getName();\n dist_info.link_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);\n dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);\n dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[0]-dist.nearest_points[1]).data.vs);\n dist_info.avoidance_vector.norm();\n dist_info.distance = dist.min_distance;\n }\n else\n {\n ROS_ERROR(\"getDistanceInfo was unable to find link after match!\");\n return false;\n }\n return true;\n }\n else\n {\n ROS_DEBUG(\"couldn't find link with that name %s\", link_name.c_str());\n for( it=distance_detailed.begin(); it != distance_detailed.end(); it++)\n {\n ROS_DEBUG(\"name: %s\", it->first.c_str());\n }\n return false;\n }\n }\n\n void CollisionRobotFCLDetailed::DistanceResultDetailed::enableGroup(const robot_model::RobotModelConstPtr &kmodel)\n {\n if (kmodel->hasJointModelGroup(group_name))\n active_components_only_ = &kmodel->getJointModelGroup(group_name)->getUpdatedLinkModelsWithGeometrySet();\n else\n active_components_only_ = NULL;\n }\n}\/\/namespace constrained_ik\n\n<commit_msg>Add active_link_only functionaly<commit_after>\n#include <constrained_ik\/collision_robot_fcl_detailed.h>\n#include <ros\/ros.h>\n#include <ctime>\n\nnamespace constrained_ik\n{\n using namespace collision_detection;\n\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state) const\n {\n return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL, NULL);\n }\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm) const\n {\n return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm, NULL);\n }\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const std::set<const robot_model::LinkModel*> &active_components_only) const\n {\n return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL, &active_components_only);\n }\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm, const std::set<const robot_model::LinkModel*> &active_components_only) const\n {\n return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm, &active_components_only);\n }\n\n CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailedHelper(const robot_state::RobotState &state, const AllowedCollisionMatrix *acm, const std::set<const robot_model::LinkModel*> *active_components_only) const\n {\n FCLManager manager;\n CollisionRobotFCLDetailed::allocSelfCollisionBroadPhase(state, manager);\n DistanceResultDetailed drd(acm, active_components_only);\n\n manager.manager_->distance(&drd, &CollisionRobotFCLDetailed::distanceDetailedCallback);\n\n return drd.distance_detailed_;\n }\n\n bool CollisionRobotFCLDetailed::distanceDetailedCallback(fcl::CollisionObject* o1, fcl::CollisionObject* o2, void* data, double& min_dist)\n {\n DistanceResultDetailed* cdata = reinterpret_cast<DistanceResultDetailed*>(data);\n\n const CollisionGeometryData* cd1 = static_cast<const CollisionGeometryData*>(o1->collisionGeometry()->getUserData());\n const CollisionGeometryData* cd2 = static_cast<const CollisionGeometryData*>(o2->collisionGeometry()->getUserData());\n const robot_model::LinkModel *l1, *l2;\n bool active1 = true, active2 = true;\n\n \/\/ If active components are specified\n if (cdata->active_components_only_)\n {\n l1 = cd1->type == BodyTypes::ROBOT_LINK ? cd1->ptr.link : (cd1->type == BodyTypes::ROBOT_ATTACHED ? cd1->ptr.ab->getAttachedLink() : NULL);\n l2 = cd2->type == BodyTypes::ROBOT_LINK ? cd2->ptr.link : (cd2->type == BodyTypes::ROBOT_ATTACHED ? cd2->ptr.ab->getAttachedLink() : NULL);\n\n \/\/ If neither of the involved components is active\n if ((!l1 || cdata->active_components_only_->find(l1) == cdata->active_components_only_->end()) &&\n (!l2 || cdata->active_components_only_->find(l2) == cdata->active_components_only_->end()))\n {\n return false;\n }\n else\n {\n if (!l1 || cdata->active_components_only_->find(l1) == cdata->active_components_only_->end())\n active1 = false;\n\n if (!l2 || cdata->active_components_only_->find(l2) == cdata->active_components_only_->end())\n active2 = false;\n }\n }\n\n \/\/ use the collision matrix (if any) to avoid certain distance checks\n bool always_allow_collision = false;\n if (cdata->acm_)\n {\n AllowedCollision::Type type;\n\n bool found = cdata->acm_->getAllowedCollision(cd1->getID(), cd2->getID(), type);\n if (found)\n {\n \/\/ if we have an entry in the collision matrix, we read it\n if (type == AllowedCollision::ALWAYS)\n {\n always_allow_collision = true;\n if (!cdata->verbose)\n logDebug(\"Collision between '%s' and '%s' is always allowed. No contacts are computed.\",\n cd1->getID().c_str(), cd2->getID().c_str());\n }\n }\n }\n\n \/\/ check if a link is touching an attached object\n if (cd1->type == BodyTypes::ROBOT_LINK && cd2->type == BodyTypes::ROBOT_ATTACHED)\n {\n const std::set<std::string> &tl = cd2->ptr.ab->getTouchLinks();\n if (tl.find(cd1->getID()) != tl.end())\n {\n always_allow_collision = true;\n if (!cdata->verbose)\n logDebug(\"Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.\",\n cd1->getID().c_str(), cd2->getID().c_str());\n }\n }\n else\n {\n if (cd2->type == BodyTypes::ROBOT_LINK && cd1->type == BodyTypes::ROBOT_ATTACHED)\n {\n const std::set<std::string> &tl = cd1->ptr.ab->getTouchLinks();\n if (tl.find(cd2->getID()) != tl.end())\n {\n always_allow_collision = true;\n if (!cdata->verbose)\n logDebug(\"Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.\",\n cd2->getID().c_str(), cd1->getID().c_str());\n }\n }\n }\n\n if(always_allow_collision)\n {\n return false;\n }\n\n if (!cdata->verbose)\n logDebug(\"Actually checking collisions between %s and %s\", cd1->getID().c_str(), cd2->getID().c_str());\n\n\n fcl::DistanceResult dist_result;\n double dist_threshold = std::numeric_limits<double>::max();\n std::map<std::string, fcl::DistanceResult>::iterator it1, it2;\n\n it1 = cdata->distance_detailed_.find(cd1->ptr.obj->id_);\n it2 = cdata->distance_detailed_.find(cd2->ptr.obj->id_);\n if (cdata->active_components_only_)\n {\n if (active1 && active2)\n {\n if (it1 != cdata->distance_detailed_.end() && it2 != cdata->distance_detailed_.end())\n dist_threshold = std::max(it1->second.min_distance, it2->second.min_distance);\n }\n else if (active1 && !active2)\n {\n if (it1 != cdata->distance_detailed_.end())\n dist_threshold = it1->second.min_distance;\n }\n else if (!active1 && active2)\n {\n if (it2 != cdata->distance_detailed_.end())\n dist_threshold = it2->second.min_distance;\n }\n }\n else\n {\n if (it1 != cdata->distance_detailed_.end() && it2 != cdata->distance_detailed_.end())\n dist_threshold = std::max(it1->second.min_distance, it2->second.min_distance);\n }\n\n dist_result.min_distance = dist_threshold;\n double d = fcl::distance(o1, o2, fcl::DistanceRequest(true), dist_result);\n\n \/\/ Check if either object is already in the map. If not add it or if present\n \/\/ check to see if the new distance is closer. If closer remove the existing\n \/\/ one and add the new distance information.\n if (d < dist_threshold)\n {\n if (it1 == cdata->distance_detailed_.end())\n {\n cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));\n }\n else\n {\n if (dist_result.min_distance < it1->second.min_distance)\n {\n cdata->distance_detailed_.erase(cd1->ptr.obj->id_);\n cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));\n }\n }\n\n if (it2 == cdata->distance_detailed_.end())\n {\n cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));\n }\n else\n {\n if (dist_result.min_distance < it2->second.min_distance)\n {\n cdata->distance_detailed_.erase(cd2->ptr.obj->id_);\n cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));\n }\n }\n }\n return false;\n }\n\n bool CollisionRobotFCLDetailed::getDistanceInfo(const DistanceDetailedMap distance_detailed, const std::string link_name, CollisionRobotFCLDetailed::DistanceInfo &dist_info)\n {\n std::map<std::string, fcl::DistanceResult>::const_iterator it;\n it = distance_detailed.find(link_name);\n\n if (it != distance_detailed.end())\n {\n fcl::DistanceResult dist = static_cast<const fcl::DistanceResult>(it->second);\n const collision_detection::CollisionGeometryData* cd1 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o1->getUserData());\n const collision_detection::CollisionGeometryData* cd2 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o2->getUserData());\n if (cd1->ptr.link->getName() == link_name)\n {\n dist_info.nearest_obsticle = cd2->ptr.link->getName();\n dist_info.link_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);\n dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);\n dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[1]-dist.nearest_points[0]).data.vs);\n dist_info.avoidance_vector.norm();\n dist_info.distance = dist.min_distance;\n }\n else if (cd2->ptr.link->getName() == link_name)\n {\n dist_info.nearest_obsticle = cd1->ptr.link->getName();\n dist_info.link_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);\n dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);\n dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[0]-dist.nearest_points[1]).data.vs);\n dist_info.avoidance_vector.norm();\n dist_info.distance = dist.min_distance;\n }\n else\n {\n ROS_ERROR(\"getDistanceInfo was unable to find link after match!\");\n return false;\n }\n return true;\n }\n else\n {\n ROS_DEBUG(\"couldn't find link with that name %s\", link_name.c_str());\n for( it=distance_detailed.begin(); it != distance_detailed.end(); it++)\n {\n ROS_DEBUG(\"name: %s\", it->first.c_str());\n }\n return false;\n }\n }\n\n void CollisionRobotFCLDetailed::DistanceResultDetailed::enableGroup(const robot_model::RobotModelConstPtr &kmodel)\n {\n if (kmodel->hasJointModelGroup(group_name))\n active_components_only_ = &kmodel->getJointModelGroup(group_name)->getUpdatedLinkModelsWithGeometrySet();\n else\n active_components_only_ = NULL;\n }\n}\/\/namespace constrained_ik\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef WIN32\n\n\/\/===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===\/\/\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\/\/ TerminalReader and TerminalDisplay need to reset the terminal configuration\n\/\/ upon destruction, to leave the terminal as before. To avoid a possible\n\/\/ misunderstanding of what \"before\" means, centralize their storage of the\n\/\/ previous termios and have them share it.\n\/\/\n\/\/ Axel Naumann <axel@cern.ch>, 2011-05-12\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"textinput\/TerminalConfigUnix.h\"\n\n#include <termios.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <cstring>\n\nusing namespace textinput;\nusing std::memcpy;\n\nvoid\nTerminalConfigUnix__handleAbortSignal(int signum) {\n \/\/ Clean up before we are killed.\n TerminalConfigUnix::Get().HandleAbortSignal(signum);\n \n}\n\nTerminalConfigUnix&\nTerminalConfigUnix::Get() {\n static TerminalConfigUnix s;\n return s;\n}\n\nTerminalConfigUnix::TerminalConfigUnix():\n fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {\n#ifdef TCSANOW\n fOldTIOS = new termios;\n fConfTIOS = new termios;\n tcgetattr(fFD, fOldTIOS);\n *fConfTIOS = *fOldTIOS;\n#endif\n fPrevAbortHandler = signal(SIGABRT, TerminalConfigUnix__handleAbortSignal);\n}\n\nTerminalConfigUnix::~TerminalConfigUnix() {\n Detach();\n delete fOldTIOS;\n delete fConfTIOS;\n}\n\nvoid\nTerminalConfigUnix::HandleAbortSignal(int signum) {\n Detach();\n if (fPrevAbortHandler) fPrevAbortHandler(signum);\n}\n\nvoid\nTerminalConfigUnix::Attach() {\n if (fIsAttached) return;\n#ifdef TCSANOW\n tcsetattr(fFD, TCSANOW, fConfTIOS);\n#endif\n fIsAttached = true;\n}\n\nvoid\nTerminalConfigUnix::Detach() {\n \/\/ Reset the terminal configuration.\n if (!fIsAttached) return;\n#ifdef TCSANOW\n tcsetattr(fFD, TCSANOW, fOldTIOS);\n#endif\n fIsAttached = false;\n}\n\n#endif \/\/ ndef WIN32\n<commit_msg>Solaris puts signal only into std::.<commit_after>#ifndef WIN32\n\n\/\/===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===\/\/\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\/\/ TerminalReader and TerminalDisplay need to reset the terminal configuration\n\/\/ upon destruction, to leave the terminal as before. To avoid a possible\n\/\/ misunderstanding of what \"before\" means, centralize their storage of the\n\/\/ previous termios and have them share it.\n\/\/\n\/\/ Axel Naumann <axel@cern.ch>, 2011-05-12\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"textinput\/TerminalConfigUnix.h\"\n\n#include <termios.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <cstring>\n\nusing namespace textinput;\nusing std::memcpy;\nusing std::signal;\n\nvoid\nTerminalConfigUnix__handleAbortSignal(int signum) {\n \/\/ Clean up before we are killed.\n TerminalConfigUnix::Get().HandleAbortSignal(signum);\n \n}\n\nTerminalConfigUnix&\nTerminalConfigUnix::Get() {\n static TerminalConfigUnix s;\n return s;\n}\n\nTerminalConfigUnix::TerminalConfigUnix():\n fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {\n#ifdef TCSANOW\n fOldTIOS = new termios;\n fConfTIOS = new termios;\n tcgetattr(fFD, fOldTIOS);\n *fConfTIOS = *fOldTIOS;\n#endif\n fPrevAbortHandler = signal(SIGABRT, TerminalConfigUnix__handleAbortSignal);\n}\n\nTerminalConfigUnix::~TerminalConfigUnix() {\n Detach();\n delete fOldTIOS;\n delete fConfTIOS;\n}\n\nvoid\nTerminalConfigUnix::HandleAbortSignal(int signum) {\n Detach();\n if (fPrevAbortHandler) fPrevAbortHandler(signum);\n}\n\nvoid\nTerminalConfigUnix::Attach() {\n if (fIsAttached) return;\n#ifdef TCSANOW\n tcsetattr(fFD, TCSANOW, fConfTIOS);\n#endif\n fIsAttached = true;\n}\n\nvoid\nTerminalConfigUnix::Detach() {\n \/\/ Reset the terminal configuration.\n if (!fIsAttached) return;\n#ifdef TCSANOW\n tcsetattr(fFD, TCSANOW, fOldTIOS);\n#endif\n fIsAttached = false;\n}\n\n#endif \/\/ ndef WIN32\n<|endoftext|>"} {"text":"<commit_before><commit_msg>remove this stuff. See comment in code for more information<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. 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,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n#include <memory>\n#include <vector>\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n\n#include \"arrow\/testing\/gtest_common.h\"\n#include \"arrow\/testing\/gtest_util.h\"\n\n#include \"arrow\/array.h\"\n#include \"arrow\/buffer.h\"\n#include \"arrow\/compute\/kernels\/util-internal.h\"\n#include \"arrow\/compute\/test-util.h\"\n\nnamespace arrow {\nnamespace compute {\nnamespace detail {\n\nusing ::testing::_;\nusing ::testing::AllOf;\nusing ::testing::Each;\nusing ::testing::ElementsAre;\nusing ::testing::ElementsAreArray;\nusing ::testing::Eq;\nusing ::testing::Ge;\nusing ::testing::IsNull;\nusing ::testing::Ne;\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nTEST(PropagateNulls, UnknownNullCountWithNullsZeroCopies) {\n ArrayData input(boolean(), \/*length=*\/16, kUnknownNullCount);\n constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);\n input.buffers.push_back(nulls);\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n\n ASSERT_OK(PropagateNulls(&ctx, input, &output));\n\n ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));\n ASSERT_THAT(output.null_count, 9);\n}\n\nTEST(PropagateNulls, UnknownNullCountWithoutNullsLeavesNullptr) {\n ArrayData input(boolean(), \/*length=*\/16, kUnknownNullCount);\n constexpr uint8_t validity_bitmap[8] = {255, 255, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);\n input.buffers.push_back(nulls);\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n\n ASSERT_OK(PropagateNulls(&ctx, input, &output));\n\n EXPECT_THAT(output.null_count, Eq(0));\n EXPECT_THAT(output.buffers, ElementsAre(IsNull())) << output.buffers[0]->data()[0];\n}\n\nTEST(PropagateNulls, OffsetAndHasNulls) {\n ArrayData input(boolean(), \/*length=*\/16, kUnknownNullCount, \/\/ slice off the first 8\n \/*offset=*\/7);\n constexpr uint8_t validity_bitmap[8] = {0, 1, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);\n input.buffers.push_back(nulls);\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n\n ASSERT_OK(PropagateNulls(&ctx, input, &output));\n\n \/\/ Copy is made.\n EXPECT_THAT(output.null_count, Eq(15));\n ASSERT_THAT(output.buffers, ElementsAre(AllOf(Ne(nulls), NotNull())));\n const auto& output_buffer = *output.buffers[0];\n \/\/ the slice shifts the bit one over\n ASSERT_THAT(std::vector<uint8_t>(output_buffer.data(),\n output_buffer.data() + output_buffer.size()),\n ElementsAreArray({2, 0}));\n ASSERT_THAT(std::vector<uint8_t>(output_buffer.data() + output_buffer.size(),\n output_buffer.data() + output_buffer.capacity()),\n Each(0));\n}\n\nTEST(AssignNullIntersection, ZeroCopyWhenZeroNullsOnOneInput) {\n ArrayData some_nulls(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);\n some_nulls.buffers.push_back(nulls);\n\n ArrayData no_nulls(boolean(), \/* length= *\/ 16, \/*null_count=*\/0);\n\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n output.length = 16;\n\n ASSERT_OK(AssignNullIntersection(&ctx, some_nulls, no_nulls, &output));\n ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));\n ASSERT_THAT(output.null_count, 9);\n\n output.buffers[0] = nullptr;\n ASSERT_OK(AssignNullIntersection(&ctx, no_nulls, some_nulls, &output));\n ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));\n ASSERT_THAT(output.null_count, 9);\n}\n\nTEST(AssignNullIntersection, IntersectsNullsWhenSomeOnBoth) {\n ArrayData left(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n constexpr uint8_t left_validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> left_nulls = std::make_shared<Buffer>(left_validity_bitmap, 8);\n left.buffers.push_back(left_nulls);\n\n ArrayData right(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n constexpr uint8_t right_validity_bitmap[8] = {127, 0, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> right_nulls =\n std::make_shared<Buffer>(right_validity_bitmap, 8);\n right.buffers.push_back(right_nulls);\n\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n output.length = 16;\n\n ASSERT_OK(AssignNullIntersection(&ctx, left, right, &output));\n\n EXPECT_THAT(output.null_count, 10);\n ASSERT_THAT(output.buffers, ElementsAre(NotNull()));\n const auto& output_buffer = *output.buffers[0];\n EXPECT_THAT(std::vector<uint8_t>(output_buffer.data(),\n output_buffer.data() + output_buffer.size()),\n ElementsAreArray({126, 0}));\n EXPECT_THAT(std::vector<uint8_t>(output_buffer.data() + output_buffer.size(),\n output_buffer.data() + output_buffer.capacity()),\n Each(0));\n}\n\nTEST(PrimitiveAllocatingUnaryKernel, BooleanFunction) {\n MockUnaryKernel mock;\n EXPECT_CALL(mock, out_type).WillRepeatedly(Return(boolean()));\n EXPECT_CALL(mock, Call(_, _, _)).WillOnce(Return(Status::OK()));\n PrimitiveAllocatingUnaryKernel kernel(&mock);\n\n auto input =\n std::make_shared<ArrayData>(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n FunctionContext ctx(default_memory_pool());\n Datum output;\n output.value = ArrayData::Make(kernel.out_type(), input->length);\n ASSERT_OK(kernel.Call(&ctx, input, &output));\n\n ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));\n auto value_buffer = output.array()->buffers[1];\n EXPECT_THAT(value_buffer->size(), Eq(2));\n EXPECT_THAT(value_buffer->capacity(), Ge(2));\n \/\/ Booleans should have this always zeroed out.\n EXPECT_THAT(*(value_buffer->data() + value_buffer->size() - 1), Eq(0));\n}\n\nTEST(PrimitiveAllocatingUnaryKernel, NonBoolean) {\n MockUnaryKernel mock;\n EXPECT_CALL(mock, out_type).WillRepeatedly(Return(int32()));\n EXPECT_CALL(mock, Call(_, _, _)).WillOnce(Return(Status::OK()));\n PrimitiveAllocatingUnaryKernel kernel(&mock);\n\n auto input =\n std::make_shared<ArrayData>(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n FunctionContext ctx(default_memory_pool());\n Datum output;\n output.value = ArrayData::Make(kernel.out_type(), input->length);\n ASSERT_OK(kernel.Call(&ctx, input, &output));\n\n ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));\n auto value_buffer = output.array()->buffers[1];\n EXPECT_THAT(value_buffer->size(), Eq(64));\n EXPECT_THAT(value_buffer->capacity(), Ge(64));\n}\n\nTEST(PrimitiveAllocatingBinaryKernel, BooleanFunction) {\n MockBinaryKernel mock;\n EXPECT_CALL(mock, out_type).WillRepeatedly(Return(boolean()));\n EXPECT_CALL(mock, Call(_, _, _, _)).WillOnce(Return(Status::OK()));\n PrimitiveAllocatingBinaryKernel kernel(&mock);\n\n auto input =\n std::make_shared<ArrayData>(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n FunctionContext ctx(default_memory_pool());\n Datum output;\n output.value = ArrayData::Make(kernel.out_type(), input->length);\n ASSERT_OK(kernel.Call(&ctx, input, input, &output));\n\n ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));\n auto value_buffer = output.array()->buffers[1];\n EXPECT_THAT(value_buffer->size(), Eq(2));\n EXPECT_THAT(value_buffer->capacity(), Ge(2));\n \/\/ Booleans should have this always zeroed out.\n EXPECT_THAT(*(value_buffer->data() + value_buffer->size() - 1), Eq(0));\n}\n\nTEST(PrimitiveAllocatingBinaryKernel, NonBoolean) {\n MockBinaryKernel mock;\n EXPECT_CALL(mock, out_type).WillRepeatedly(Return(int32()));\n EXPECT_CALL(mock, Call(_, _, _, _)).WillOnce(Return(Status::OK()));\n PrimitiveAllocatingBinaryKernel kernel(&mock);\n\n auto input =\n std::make_shared<ArrayData>(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n FunctionContext ctx(default_memory_pool());\n Datum output;\n output.value = ArrayData::Make(kernel.out_type(), input->length);\n ASSERT_OK(kernel.Call(&ctx, input, input, &output));\n\n ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));\n auto value_buffer = output.array()->buffers[1];\n EXPECT_THAT(value_buffer->size(), Eq(64));\n EXPECT_THAT(value_buffer->capacity(), Ge(64));\n}\n\n} \/\/ namespace detail\n} \/\/ namespace compute\n} \/\/ namespace arrow\n<commit_msg>ARROW-4869: [C++] Fix gmock usage in compute\/kernels\/util-internal-test.cc<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. 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,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n#include <memory>\n#include <vector>\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n\n#include \"arrow\/testing\/gtest_common.h\"\n#include \"arrow\/testing\/gtest_util.h\"\n\n#include \"arrow\/array.h\"\n#include \"arrow\/buffer.h\"\n#include \"arrow\/compute\/kernels\/util-internal.h\"\n#include \"arrow\/compute\/test-util.h\"\n\nnamespace arrow {\nnamespace compute {\nnamespace detail {\n\nusing ::testing::_;\nusing ::testing::AllOf;\nusing ::testing::Each;\nusing ::testing::ElementsAre;\nusing ::testing::ElementsAreArray;\nusing ::testing::Eq;\nusing ::testing::Ge;\nusing ::testing::IsNull;\nusing ::testing::Ne;\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nTEST(PropagateNulls, UnknownNullCountWithNullsZeroCopies) {\n ArrayData input(boolean(), \/*length=*\/16, kUnknownNullCount);\n constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);\n input.buffers.push_back(nulls);\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n\n ASSERT_OK(PropagateNulls(&ctx, input, &output));\n\n ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));\n ASSERT_THAT(output.null_count, 9);\n}\n\nTEST(PropagateNulls, UnknownNullCountWithoutNullsLeavesNullptr) {\n ArrayData input(boolean(), \/*length=*\/16, kUnknownNullCount);\n constexpr uint8_t validity_bitmap[8] = {255, 255, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);\n input.buffers.push_back(nulls);\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n\n ASSERT_OK(PropagateNulls(&ctx, input, &output));\n\n EXPECT_THAT(output.null_count, Eq(0));\n EXPECT_THAT(output.buffers, ElementsAre(IsNull())) << output.buffers[0]->data()[0];\n}\n\nTEST(PropagateNulls, OffsetAndHasNulls) {\n ArrayData input(boolean(), \/*length=*\/16, kUnknownNullCount, \/\/ slice off the first 8\n \/*offset=*\/7);\n constexpr uint8_t validity_bitmap[8] = {0, 1, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);\n input.buffers.push_back(nulls);\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n\n ASSERT_OK(PropagateNulls(&ctx, input, &output));\n\n \/\/ Copy is made.\n EXPECT_THAT(output.null_count, Eq(15));\n ASSERT_THAT(output.buffers, ElementsAre(AllOf(Ne(nulls), NotNull())));\n const auto& output_buffer = *output.buffers[0];\n \/\/ the slice shifts the bit one over\n ASSERT_THAT(std::vector<uint8_t>(output_buffer.data(),\n output_buffer.data() + output_buffer.size()),\n ElementsAreArray({2, 0}));\n ASSERT_THAT(std::vector<uint8_t>(output_buffer.data() + output_buffer.size(),\n output_buffer.data() + output_buffer.capacity()),\n Each(0));\n}\n\nTEST(AssignNullIntersection, ZeroCopyWhenZeroNullsOnOneInput) {\n ArrayData some_nulls(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);\n some_nulls.buffers.push_back(nulls);\n\n ArrayData no_nulls(boolean(), \/* length= *\/ 16, \/*null_count=*\/0);\n\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n output.length = 16;\n\n ASSERT_OK(AssignNullIntersection(&ctx, some_nulls, no_nulls, &output));\n ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));\n ASSERT_THAT(output.null_count, 9);\n\n output.buffers[0] = nullptr;\n ASSERT_OK(AssignNullIntersection(&ctx, no_nulls, some_nulls, &output));\n ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));\n ASSERT_THAT(output.null_count, 9);\n}\n\nTEST(AssignNullIntersection, IntersectsNullsWhenSomeOnBoth) {\n ArrayData left(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n constexpr uint8_t left_validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> left_nulls = std::make_shared<Buffer>(left_validity_bitmap, 8);\n left.buffers.push_back(left_nulls);\n\n ArrayData right(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n constexpr uint8_t right_validity_bitmap[8] = {127, 0, 0, 0, 0, 0, 0, 0};\n std::shared_ptr<Buffer> right_nulls =\n std::make_shared<Buffer>(right_validity_bitmap, 8);\n right.buffers.push_back(right_nulls);\n\n FunctionContext ctx(default_memory_pool());\n ArrayData output;\n output.length = 16;\n\n ASSERT_OK(AssignNullIntersection(&ctx, left, right, &output));\n\n EXPECT_THAT(output.null_count, 10);\n ASSERT_THAT(output.buffers, ElementsAre(NotNull()));\n const auto& output_buffer = *output.buffers[0];\n EXPECT_THAT(std::vector<uint8_t>(output_buffer.data(),\n output_buffer.data() + output_buffer.size()),\n ElementsAreArray({126, 0}));\n EXPECT_THAT(std::vector<uint8_t>(output_buffer.data() + output_buffer.size(),\n output_buffer.data() + output_buffer.capacity()),\n Each(0));\n}\n\nTEST(PrimitiveAllocatingUnaryKernel, BooleanFunction) {\n MockUnaryKernel mock;\n EXPECT_CALL(mock, out_type()).WillRepeatedly(Return(boolean()));\n EXPECT_CALL(mock, Call(_, _, _)).WillOnce(Return(Status::OK()));\n PrimitiveAllocatingUnaryKernel kernel(&mock);\n\n auto input =\n std::make_shared<ArrayData>(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n FunctionContext ctx(default_memory_pool());\n Datum output;\n output.value = ArrayData::Make(kernel.out_type(), input->length);\n ASSERT_OK(kernel.Call(&ctx, input, &output));\n\n ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));\n auto value_buffer = output.array()->buffers[1];\n EXPECT_THAT(value_buffer->size(), Eq(2));\n EXPECT_THAT(value_buffer->capacity(), Ge(2));\n \/\/ Booleans should have this always zeroed out.\n EXPECT_THAT(*(value_buffer->data() + value_buffer->size() - 1), Eq(0));\n}\n\nTEST(PrimitiveAllocatingUnaryKernel, NonBoolean) {\n MockUnaryKernel mock;\n EXPECT_CALL(mock, out_type()).WillRepeatedly(Return(int32()));\n EXPECT_CALL(mock, Call(_, _, _)).WillOnce(Return(Status::OK()));\n PrimitiveAllocatingUnaryKernel kernel(&mock);\n\n auto input =\n std::make_shared<ArrayData>(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n FunctionContext ctx(default_memory_pool());\n Datum output;\n output.value = ArrayData::Make(kernel.out_type(), input->length);\n ASSERT_OK(kernel.Call(&ctx, input, &output));\n\n ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));\n auto value_buffer = output.array()->buffers[1];\n EXPECT_THAT(value_buffer->size(), Eq(64));\n EXPECT_THAT(value_buffer->capacity(), Ge(64));\n}\n\nTEST(PrimitiveAllocatingBinaryKernel, BooleanFunction) {\n MockBinaryKernel mock;\n EXPECT_CALL(mock, out_type()).WillRepeatedly(Return(boolean()));\n EXPECT_CALL(mock, Call(_, _, _, _)).WillOnce(Return(Status::OK()));\n PrimitiveAllocatingBinaryKernel kernel(&mock);\n\n auto input =\n std::make_shared<ArrayData>(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n FunctionContext ctx(default_memory_pool());\n Datum output;\n output.value = ArrayData::Make(kernel.out_type(), input->length);\n ASSERT_OK(kernel.Call(&ctx, input, input, &output));\n\n ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));\n auto value_buffer = output.array()->buffers[1];\n EXPECT_THAT(value_buffer->size(), Eq(2));\n EXPECT_THAT(value_buffer->capacity(), Ge(2));\n \/\/ Booleans should have this always zeroed out.\n EXPECT_THAT(*(value_buffer->data() + value_buffer->size() - 1), Eq(0));\n}\n\nTEST(PrimitiveAllocatingBinaryKernel, NonBoolean) {\n MockBinaryKernel mock;\n EXPECT_CALL(mock, out_type()).WillRepeatedly(Return(int32()));\n EXPECT_CALL(mock, Call(_, _, _, _)).WillOnce(Return(Status::OK()));\n PrimitiveAllocatingBinaryKernel kernel(&mock);\n\n auto input =\n std::make_shared<ArrayData>(boolean(), \/* length= *\/ 16, kUnknownNullCount);\n FunctionContext ctx(default_memory_pool());\n Datum output;\n output.value = ArrayData::Make(kernel.out_type(), input->length);\n ASSERT_OK(kernel.Call(&ctx, input, input, &output));\n\n ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));\n auto value_buffer = output.array()->buffers[1];\n EXPECT_THAT(value_buffer->size(), Eq(64));\n EXPECT_THAT(value_buffer->capacity(), Ge(64));\n}\n\n} \/\/ namespace detail\n} \/\/ namespace compute\n} \/\/ namespace arrow\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH\n#define DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH\n\n#include <memory>\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/common\/deprecated.hh>\n\n#include <dune\/geometry\/genericgeometry\/topologytypes.hh>\n\n#if HAVE_DUNE_PDELAB\n# include <dune\/pdelab\/finiteelementmap\/qkdg.hh>\n# include <dune\/pdelab\/gridfunctionspace\/gridfunctionspace.hh>\n# include <dune\/pdelab\/constraints\/conforming.hh>\n#endif \/\/ HAVE_DUNE_PDELAB\n\n#include <dune\/stuff\/common\/type_utils.hh>\n#include <dune\/stuff\/la\/container\/istl.hh>\n\n#include <dune\/gdt\/spaces\/parallel.hh>\n\n#include \"..\/..\/..\/mapper\/pdelab.hh\"\n#include \"..\/..\/..\/basefunctionset\/pdelab.hh\"\n\n#include \"..\/..\/..\/spaces\/interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Spaces {\nnamespace DG {\n\n#if HAVE_DUNE_PDELAB\n\n\n\/\/ forward, to be used in the traits and to allow for specialization\ntemplate< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >\nclass PdelabBased\n{\n static_assert(Dune::AlwaysFalse< GridViewImp >::value, \"Untested for this combination of dimensions!\");\n}; \/\/class PdelabBased\n\n\ntemplate< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >\nclass PdelabBasedTraits\n{\npublic:\n typedef PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols > derived_type;\n typedef GridViewImp GridViewType;\n static const int polOrder = polynomialOrder;\n \/\/ using this space for the QuadraticSpaces in test\/products_l2weighted.cc results in a test failure\n static_assert(polOrder == 1, \"This space is known to fail for higher polynomial orders!\");\nprivate:\n typedef typename GridViewType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridViewType::dimension;\npublic:\n typedef RangeFieldImp RangeFieldType;\nprivate:\n template< class G, bool single_geom, bool is_simplex, bool is_cube >\n struct FeMap\n {\n static_assert(Dune::AlwaysFalse< G >::value,\n \"This space is only implemented for either fully simplicial or fully cubic grids!\");\n };\n template< class G >\n struct FeMap< G, true, true, false >\n {\n static_assert(Dune::AlwaysFalse< G >::value,\n \"Not yet implemented for simplicial grids!\");\n };\n template< class G >\n struct FeMap< G, true, false, true >\n {\n typedef PDELab::QkDGLocalFiniteElementMap< DomainFieldType, RangeFieldType, polOrder, dimDomain > Type;\n };\n typedef typename GridViewType::Grid GridType;\n static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType< GridType >::v;\n static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId\n == GenericGeometry::SimplexTopology< dimDomain >::type::id);\n static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId\n == GenericGeometry::CubeTopology< dimDomain >::type::id);\n typedef typename FeMap< GridType, single_geom_, simplicial_, cubic_ >::Type FEMapType;\npublic:\n typedef PDELab::GridFunctionSpace< GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints >\n BackendType;\n typedef Mapper::DiscontinuousPdelabWrapper< BackendType > MapperType;\n typedef typename GridViewType::template Codim< 0 >::Entity EntityType;\n typedef BaseFunctionSet::PdelabWrapper\n < BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, rangeDim, rangeDimCols >\n BaseFunctionSetType;\n static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view;\n static const bool needs_grid_view = true;\n typedef CommunicationChooser< GridViewType > CommunicationChooserType;\n typedef typename CommunicationChooserType::Type CommunicatorType;\nprivate:\n friend class PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >;\n}; \/\/ class PdelabBasedTraits\n\n\ntemplate< class GridViewImp, int polynomialOrder, class RangeFieldImp >\nclass PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >\n : public SpaceInterface< PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >,\n GridViewImp::dimension, 1, 1 >\n{\n typedef SpaceInterface< PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >,\n GridViewImp::dimension, 1, 1 > BaseType;\n typedef PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 > ThisType;\npublic:\n typedef PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;\n\n typedef typename Traits::GridViewType GridViewType;\n static const int polOrder = Traits::polOrder;\n typedef typename GridViewType::ctype DomainFieldType;\n static const unsigned int dimDomain = BaseType::dimDomain;\nprivate:\n static_assert(GridViewType::dimension == dimDomain, \"Dimension of GridView has to match dimDomain\");\npublic:\n typedef FieldVector< DomainFieldType, dimDomain > DomainType;\n typedef typename Traits::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = BaseType::dimRange;\n static const unsigned int dimRangeCols = BaseType::dimRangeCols;\n\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::MapperType MapperType;\n typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;\n typedef typename Traits::CommunicationChooserType CommunicationChooserType;\n typedef typename Traits::CommunicatorType CommunicatorType;\n\nprivate:\n typedef typename Traits::FEMapType FEMapType;\n\npublic:\n typedef typename BaseType::IntersectionType IntersectionType;\n typedef typename BaseType::EntityType EntityType;\n typedef typename BaseType::PatternType PatternType;\n typedef typename BaseType::BoundaryInfoType BoundaryInfoType;\n\n PdelabBased(GridViewType gV)\n : grid_view_(gV)\n , fe_map_()\n , backend_(const_cast< GridViewType& >(grid_view_), fe_map_)\n , mapper_(backend_)\n , communicator_(CommunicationChooser<GridViewImp>::create(grid_view_))\n , communicator_prepared_(false)\n {}\n\n \/**\n * \\brief Copy ctor.\n * \\note Manually implemented bc of the std::mutex + communicator_ unique_ptr\n *\/\n PdelabBased(const ThisType& other)\n : grid_view_(other.grid_view_)\n , fe_map_(other.fe_map_)\n , backend_(other.backend_)\n , mapper_(other.mapper_)\n , communicator_(CommunicationChooser< GridViewImp >::create(grid_view_))\n , communicator_prepared_(false)\n {\n \/\/ make sure our new communicator is prepared if other's was\n if (other.communicator_prepared_)\n const auto& DUNE_UNUSED(comm) = this->communicator();\n }\n\n \/**\n * \\brief Move ctor.\n * \\note Manually implemented bc of the std::mutex.\n *\/\n PdelabBased(ThisType&& source)\n : grid_view_(source.grid_view_)\n , fe_map_(source.fe_map_)\n , backend_(source.backend_)\n , mapper_(source.mapper_)\n , communicator_(std::move(source.communicator_))\n , communicator_prepared_(source.communicator_prepared_)\n {}\n\n ThisType& operator=(const ThisType& other) = delete;\n\n ThisType& operator=(ThisType&& source) = delete;\n\n using BaseType::compute_pattern;\n\n template< class G, class S, int d, int r, int rC >\n PatternType compute_pattern(const GridView< G >& local_grid_view,\n const SpaceInterface< S, d, r, rC >& ansatz_space) const\n {\n return BaseType::compute_face_and_volume_pattern(local_grid_view, ansatz_space);\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const BackendType& backend() const\n {\n return backend_;\n }\n\n const MapperType& mapper() const\n {\n return mapper_;\n }\n\n BaseFunctionSetType base_function_set(const EntityType& entity) const\n {\n return BaseFunctionSetType(backend_, entity);\n }\n\n CommunicatorType& communicator() const\n {\n std::lock_guard< std::mutex > DUNE_UNUSED(gg)(communicator_mutex_);\n if (!communicator_prepared_)\n communicator_prepared_ = CommunicationChooser<GridViewType>::prepare(*this, *communicator_);\n return *communicator_;\n } \/\/ ... communicator(...)\n\nprivate:\n const GridViewType grid_view_;\n const FEMapType fe_map_;\n const BackendType backend_;\n const MapperType mapper_;\n mutable std::unique_ptr< CommunicatorType > communicator_;\n mutable bool communicator_prepared_;\n mutable std::mutex communicator_mutex_;\n}; \/\/ class PdelabBased< ..., 1 >\n\n\n#else \/\/ HAVE_DUNE_PDELAB\n\n\ntemplate< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >\nclass PdelabBased\n{\n static_assert(Dune::AlwaysFalse< GridViewImp >::value, \"You are missing dune-pdelab!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_PDELAB\n\n\n} \/\/ namespace DG\nnamespace DiscontinuousLagrange {\n\n\ntemplate< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >\nclass\n DUNE_DEPRECATED_MSG(\"Use DG::PdelabBased instead (21.11.2014)!\")\n PdelabBased\n : public DG::PdelabBased< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >\n{\npublic:\n template< class... Args >\n PdelabBased(Args&& ...args)\n : DG::PdelabBased< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >(std::forward< Args >(args)...)\n {}\n};\n\n\n} \/\/ namespace DiscontinuousLagrange\n} \/\/ namespace Spaces\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH\n<commit_msg>[playground.spaces.dg.pdelab] remove static_assert, refs #25<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH\n#define DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH\n\n#include <memory>\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/common\/deprecated.hh>\n\n#include <dune\/geometry\/genericgeometry\/topologytypes.hh>\n\n#if HAVE_DUNE_PDELAB\n# include <dune\/pdelab\/finiteelementmap\/qkdg.hh>\n# include <dune\/pdelab\/gridfunctionspace\/gridfunctionspace.hh>\n# include <dune\/pdelab\/constraints\/conforming.hh>\n#endif \/\/ HAVE_DUNE_PDELAB\n\n#include <dune\/stuff\/common\/type_utils.hh>\n#include <dune\/stuff\/la\/container\/istl.hh>\n\n#include <dune\/gdt\/spaces\/parallel.hh>\n\n#include \"..\/..\/..\/mapper\/pdelab.hh\"\n#include \"..\/..\/..\/basefunctionset\/pdelab.hh\"\n\n#include \"..\/..\/..\/spaces\/interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Spaces {\nnamespace DG {\n\n#if HAVE_DUNE_PDELAB\n\n\n\/\/ forward, to be used in the traits and to allow for specialization\ntemplate< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >\nclass PdelabBased\n{\n static_assert(Dune::AlwaysFalse< GridViewImp >::value, \"Untested for this combination of dimensions!\");\n}; \/\/class PdelabBased\n\n\ntemplate< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >\nclass PdelabBasedTraits\n{\npublic:\n typedef PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols > derived_type;\n typedef GridViewImp GridViewType;\n static const int polOrder = polynomialOrder;\nprivate:\n typedef typename GridViewType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridViewType::dimension;\npublic:\n typedef RangeFieldImp RangeFieldType;\nprivate:\n template< class G, bool single_geom, bool is_simplex, bool is_cube >\n struct FeMap\n {\n static_assert(Dune::AlwaysFalse< G >::value,\n \"This space is only implemented for either fully simplicial or fully cubic grids!\");\n };\n template< class G >\n struct FeMap< G, true, true, false >\n {\n static_assert(Dune::AlwaysFalse< G >::value,\n \"Not yet implemented for simplicial grids!\");\n };\n template< class G >\n struct FeMap< G, true, false, true >\n {\n typedef PDELab::QkDGLocalFiniteElementMap< DomainFieldType, RangeFieldType, polOrder, dimDomain > Type;\n };\n typedef typename GridViewType::Grid GridType;\n static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType< GridType >::v;\n static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId\n == GenericGeometry::SimplexTopology< dimDomain >::type::id);\n static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId\n == GenericGeometry::CubeTopology< dimDomain >::type::id);\n typedef typename FeMap< GridType, single_geom_, simplicial_, cubic_ >::Type FEMapType;\npublic:\n typedef PDELab::GridFunctionSpace< GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints >\n BackendType;\n typedef Mapper::DiscontinuousPdelabWrapper< BackendType > MapperType;\n typedef typename GridViewType::template Codim< 0 >::Entity EntityType;\n typedef BaseFunctionSet::PdelabWrapper\n < BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, rangeDim, rangeDimCols >\n BaseFunctionSetType;\n static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view;\n static const bool needs_grid_view = true;\n typedef CommunicationChooser< GridViewType > CommunicationChooserType;\n typedef typename CommunicationChooserType::Type CommunicatorType;\nprivate:\n friend class PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >;\n}; \/\/ class PdelabBasedTraits\n\n\ntemplate< class GridViewImp, int polynomialOrder, class RangeFieldImp >\nclass PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >\n : public SpaceInterface< PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >,\n GridViewImp::dimension, 1, 1 >\n{\n typedef SpaceInterface< PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >,\n GridViewImp::dimension, 1, 1 > BaseType;\n typedef PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 > ThisType;\npublic:\n typedef PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;\n\n typedef typename Traits::GridViewType GridViewType;\n static const int polOrder = Traits::polOrder;\n typedef typename GridViewType::ctype DomainFieldType;\n static const unsigned int dimDomain = BaseType::dimDomain;\nprivate:\n static_assert(GridViewType::dimension == dimDomain, \"Dimension of GridView has to match dimDomain\");\npublic:\n typedef FieldVector< DomainFieldType, dimDomain > DomainType;\n typedef typename Traits::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = BaseType::dimRange;\n static const unsigned int dimRangeCols = BaseType::dimRangeCols;\n\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::MapperType MapperType;\n typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;\n typedef typename Traits::CommunicationChooserType CommunicationChooserType;\n typedef typename Traits::CommunicatorType CommunicatorType;\n\nprivate:\n typedef typename Traits::FEMapType FEMapType;\n\npublic:\n typedef typename BaseType::IntersectionType IntersectionType;\n typedef typename BaseType::EntityType EntityType;\n typedef typename BaseType::PatternType PatternType;\n typedef typename BaseType::BoundaryInfoType BoundaryInfoType;\n\n PdelabBased(GridViewType gV)\n : grid_view_(gV)\n , fe_map_()\n , backend_(const_cast< GridViewType& >(grid_view_), fe_map_)\n , mapper_(backend_)\n , communicator_(CommunicationChooser<GridViewImp>::create(grid_view_))\n , communicator_prepared_(false)\n {}\n\n \/**\n * \\brief Copy ctor.\n * \\note Manually implemented bc of the std::mutex + communicator_ unique_ptr\n *\/\n PdelabBased(const ThisType& other)\n : grid_view_(other.grid_view_)\n , fe_map_(other.fe_map_)\n , backend_(other.backend_)\n , mapper_(other.mapper_)\n , communicator_(CommunicationChooser< GridViewImp >::create(grid_view_))\n , communicator_prepared_(false)\n {\n \/\/ make sure our new communicator is prepared if other's was\n if (other.communicator_prepared_)\n const auto& DUNE_UNUSED(comm) = this->communicator();\n }\n\n \/**\n * \\brief Move ctor.\n * \\note Manually implemented bc of the std::mutex.\n *\/\n PdelabBased(ThisType&& source)\n : grid_view_(source.grid_view_)\n , fe_map_(source.fe_map_)\n , backend_(source.backend_)\n , mapper_(source.mapper_)\n , communicator_(std::move(source.communicator_))\n , communicator_prepared_(source.communicator_prepared_)\n {}\n\n ThisType& operator=(const ThisType& other) = delete;\n\n ThisType& operator=(ThisType&& source) = delete;\n\n using BaseType::compute_pattern;\n\n template< class G, class S, int d, int r, int rC >\n PatternType compute_pattern(const GridView< G >& local_grid_view,\n const SpaceInterface< S, d, r, rC >& ansatz_space) const\n {\n return BaseType::compute_face_and_volume_pattern(local_grid_view, ansatz_space);\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const BackendType& backend() const\n {\n return backend_;\n }\n\n const MapperType& mapper() const\n {\n return mapper_;\n }\n\n BaseFunctionSetType base_function_set(const EntityType& entity) const\n {\n return BaseFunctionSetType(backend_, entity);\n }\n\n CommunicatorType& communicator() const\n {\n std::lock_guard< std::mutex > DUNE_UNUSED(gg)(communicator_mutex_);\n if (!communicator_prepared_)\n communicator_prepared_ = CommunicationChooser<GridViewType>::prepare(*this, *communicator_);\n return *communicator_;\n } \/\/ ... communicator(...)\n\nprivate:\n const GridViewType grid_view_;\n const FEMapType fe_map_;\n const BackendType backend_;\n const MapperType mapper_;\n mutable std::unique_ptr< CommunicatorType > communicator_;\n mutable bool communicator_prepared_;\n mutable std::mutex communicator_mutex_;\n}; \/\/ class PdelabBased< ..., 1 >\n\n\n#else \/\/ HAVE_DUNE_PDELAB\n\n\ntemplate< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >\nclass PdelabBased\n{\n static_assert(Dune::AlwaysFalse< GridViewImp >::value, \"You are missing dune-pdelab!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_PDELAB\n\n\n} \/\/ namespace DG\nnamespace DiscontinuousLagrange {\n\n\ntemplate< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >\nclass\n DUNE_DEPRECATED_MSG(\"Use DG::PdelabBased instead (21.11.2014)!\")\n PdelabBased\n : public DG::PdelabBased< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >\n{\npublic:\n template< class... Args >\n PdelabBased(Args&& ...args)\n : DG::PdelabBased< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >(std::forward< Args >(args)...)\n {}\n};\n\n\n} \/\/ namespace DiscontinuousLagrange\n} \/\/ namespace Spaces\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH\n<|endoftext|>"} {"text":"<commit_before>class crb_tc_markers {\r\n title = \"TCells Insurgency Style Markers\"; \r\n values[]= {0,1}; \r\n texts[]= {\"Off\",\"On\"}; \r\n default = 1;\r\n};\r\n\r\nclass crb_tc_intensity {\r\n title = \"TCells Recruitment Intensity per Hour\"; \r\n values[]= {0.25,0.5,1,2,3}; \r\n texts[]= {\"4 Recruits\",\"2 Recruits\",\"1 Recruit\",\"0.5 Recruit\",\"0.33 Recruit\"}; \r\n default = 1;\r\n};\r\n\r\n<commit_msg>- Renamed parameters<commit_after>class crb_tc_markers {\r\n title = \"Enemy - TCells Insurgency Style Markers\"; \r\n values[]= {0,1}; \r\n texts[]= {\"Off\",\"On\"}; \r\n default = 1;\r\n};\r\n\r\nclass crb_tc_intensity {\r\n title = \"Enemy - TCells Recruitment per Hour\"; \r\n values[]= {0.25,0.5,1,2,3}; \r\n texts[]= {\"4 Recruits\",\"2 Recruits\",\"1 Recruit\",\"0.5 Recruit\",\"0.33 Recruit\"}; \r\n default = 1;\r\n};\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2010 Google Inc.\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#include \"esnpapi.h\"\n#include \"proxyImpl.h\"\n\n#include <org\/w3c\/dom.h>\n\nusing namespace org::w3c::dom;\n\nvoid initializeWebDatabaseMetaData()\n{\n ProxyControl::registerMetaData(webdatabase::DatabaseCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::DatabaseCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::Database::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::Database_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::DatabaseSync::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::DatabaseSync_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLError::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLError_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLResultSet::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLResultSet_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLResultSetRowList::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLResultSetRowList_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLStatementCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLStatementCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLStatementErrorCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLStatementErrorCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransactionCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransactionErrorCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionErrorCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransaction::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransaction_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransactionSyncCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionSyncCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransactionSync::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionSync_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLVoidCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLVoidCallback_Bridge<Any, invoke> >::createInstance);\n}\n<commit_msg>(initializeWebDatabaseMetaData) : Register 'VoidCallback' as 'SQLVoidCallback' for WebKit.<commit_after>\/*\n * Copyright 2008-2010 Google Inc.\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#include \"esnpapi.h\"\n#include \"proxyImpl.h\"\n\n#include <org\/w3c\/dom.h>\n\nusing namespace org::w3c::dom;\n\nvoid initializeWebDatabaseMetaData()\n{\n ProxyControl::registerMetaData(webdatabase::DatabaseCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::DatabaseCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::Database::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::Database_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::DatabaseSync::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::DatabaseSync_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLError::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLError_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLResultSet::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLResultSet_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLResultSetRowList::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLResultSetRowList_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLStatementCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLStatementCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLStatementErrorCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLStatementErrorCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransactionCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransactionErrorCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionErrorCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransaction::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransaction_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransactionSyncCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionSyncCallback_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLTransactionSync::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionSync_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(webdatabase::SQLVoidCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLVoidCallback_Bridge<Any, invoke> >::createInstance);\n\n \/\/\n \/\/ Workaround for WebKit\n \/\/\n ProxyControl::registerMetaData(webdatabase::SQLVoidCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLVoidCallback_Bridge<Any, invoke> >::createInstance,\n \"VoidCallback\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <math.h>\n#include \"semanticcomposefunctions.h\"\n#include \"kwindow.h\"\n\n\nstring ComposeAsIs::name = \"As Is\";\nTSemanticValue ComposeAsIs::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n return myInfo->values[ 0 ];\n}\n\n\nstring ComposeSign::name = \"Sign\";\nTSemanticValue ComposeSign::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n if ( myInfo->values[ 0 ] != 0 )\n return 1;\n return 0;\n}\n\n\nstring ComposeUnsign::name = \"1-Sign\";\nTSemanticValue ComposeUnsign::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp;\n\n if ( myInfo->values[ 0 ] != 0 )\n tmp = 1;\n else\n tmp = 0;\n\n return 1 - tmp;\n}\n\n\nstring ComposeMod::name = \"Mod\";\nTSemanticValue ComposeMod::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue remainder = 0, divider;\n\n if ( parameters[ DIVIDER ][ 0 ] != 0 )\n divider = parameters[ DIVIDER ][ 0 ];\n else\n divider = 1;\n\n remainder = fmod( myInfo->values[ 0 ], divider );\n\n return remainder;\n}\n\n\nstring ComposeModPlus1::name = \"Mod+1\";\nTSemanticValue ComposeModPlus1::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue remainder = 0, divider;\n\n if ( parameters[ DIVIDER ][ 0 ] != 0 )\n divider = parameters[ DIVIDER ][ 0 ];\n else\n divider = 1;\n\n remainder = fmod( myInfo->values[ 0 ], divider );\n\n return remainder + 1;\n}\n\n\nstring ComposeDivide::name = \"Div\";\nTSemanticValue ComposeDivide::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue quotient = 0, divider;\n\n if ( parameters[ DIVIDER ][ 0 ] != 0 )\n quotient = myInfo->values[ 0 ] \/ parameters[ DIVIDER ][ 0 ];\n else\n {\n divider = 1;\n quotient = fmod( myInfo->values[ 0 ], divider );\n }\n return quotient;\n}\n\n\nstring ComposeProduct::name = \"Prod\";\nTSemanticValue ComposeProduct::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n return myInfo->values[ 0 ] * parameters[ FACTOR ][ 0 ];\n}\n\n\nstring ComposeAdding::name = \"Add\";\nTSemanticValue ComposeAdding::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n return myInfo->values[ 0 ] + parameters[ FACTOR ][ 0 ];\n}\n\n\nstring ComposeSubstract::name = \"Subs\";\nTSemanticValue ComposeSubstract::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n return myInfo->values[ 0 ] - parameters[ FACTOR ][ 0 ];\n}\n\n\nstring ComposeSelectRange::name = \"Select Range\";\nTSemanticValue ComposeSelectRange::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n if ( myInfo->values[ 0 ] <= parameters[ MAXVALUE ][ 0 ] &&\n myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )\n tmp = myInfo->values[ 0 ];\n else\n tmp = 0;\n\n return tmp;\n}\n\n\nstring ComposeSelectRangeOpen::name = \"Select Range [)\";\nTSemanticValue ComposeSelectRangeOpen::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n if ( myInfo->values[ 0 ] < parameters[ MAXVALUE ][ 0 ] &&\n myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )\n tmp = myInfo->values[ 0 ];\n else\n tmp = 0;\n\n return tmp;\n}\n\n\nstring ComposeIsInRange::name = \"Is In Range\";\nTSemanticValue ComposeIsInRange::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n if ( myInfo->values[ 0 ] <= parameters[ MAXVALUE ][ 0 ] &&\n myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )\n tmp = 1;\n else\n tmp = 0;\n\n return tmp;\n}\n\n\nstring ComposeIsInRangeOpen::name = \"Is In Range [)\";\nTSemanticValue ComposeIsInRangeOpen::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n if ( myInfo->values[ 0 ] < parameters[ MAXVALUE ][ 0 ] &&\n myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )\n tmp = 1;\n else\n tmp = 0;\n\n return tmp;\n}\n\n\nstring ComposeIsEqual::name = \"Is Equal\";\nTSemanticValue ComposeIsEqual::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n for ( TParamIndex i = 0; i < parameters[ VALUES ].size(); i++ )\n {\n if ( myInfo->values[ 0 ] == parameters[ VALUES ][ i ] )\n {\n tmp = myInfo->values[ 0 ];\n break;\n }\n }\n\n return tmp;\n}\n\n\nstring ComposeIsEqualSign::name = \"Is Equal (Sign)\";\nTSemanticValue ComposeIsEqualSign::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n for ( TParamIndex i = 0; i < parameters[ VALUES ].size(); i++ )\n {\n if ( myInfo->values[ 0 ] == parameters[ VALUES ][ i ] )\n {\n tmp = 1;\n break;\n }\n }\n\n return tmp;\n}\n\n\nvoid ComposeStackedValue::init( KWindow *whichWindow )\n{\n myStack.clear();\n\n if ( whichWindow->getTrace()->totalThreads() >\n whichWindow->getTrace()->totalCPUs() )\n {\n myStack.reserve( whichWindow->getTrace()->totalThreads() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )\n myStack.push_back( vector<TSemanticValue>() );\n }\n else\n {\n myStack.reserve( whichWindow->getTrace()->totalCPUs() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )\n myStack.push_back( vector<TSemanticValue>() );\n }\n}\n\n\nstring ComposeStackedValue::name = \"Stacked Val\";\nTSemanticValue ComposeStackedValue::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n\n if ( myInfo->values[ 0 ] != 0 )\n myStack[ tmpOrder ].push_back( myInfo->values[ 0 ] );\n else\n {\n if ( !myStack[ tmpOrder ].empty() )\n myStack[ tmpOrder ].pop_back();\n }\n\n if ( myStack[ tmpOrder ].empty() )\n return 0;\n\n return myStack[ tmpOrder ].back();\n}\n\n\nvoid ComposeInStackedValue::init( KWindow *whichWindow )\n{\n myStack.clear();\n\n if ( whichWindow->getTrace()->totalThreads() >\n whichWindow->getTrace()->totalCPUs() )\n {\n myStack.reserve( whichWindow->getTrace()->totalThreads() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )\n myStack.push_back( vector<TSemanticValue>() );\n }\n else\n {\n myStack.reserve( whichWindow->getTrace()->totalCPUs() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )\n myStack.push_back( vector<TSemanticValue>() );\n }\n}\n\n\nstring ComposeInStackedValue::name = \"In Stacked Val\";\nTSemanticValue ComposeInStackedValue::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n\n if ( myInfo->values[ 0 ] != 0 )\n myStack[ tmpOrder ].push_back( myInfo->values[ 0 ] );\n else\n {\n if ( !myStack[ tmpOrder ].empty() )\n myStack[ tmpOrder ].pop_back();\n }\n\n if ( myStack[ tmpOrder ].empty() )\n return 0;\n\n return myStack[ tmpOrder ].back() == parameters[ VALUE ][ 0 ] ?\n myStack[ tmpOrder ].back() : 0;\n}\n\n\nvoid ComposeNestingLevel::init( KWindow *whichWindow )\n{\n myStack.clear();\n\n if ( whichWindow->getTrace()->totalThreads() >\n whichWindow->getTrace()->totalCPUs() )\n {\n myStack.reserve( whichWindow->getTrace()->totalThreads() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )\n myStack.push_back( 0 );\n }\n else\n {\n myStack.reserve( whichWindow->getTrace()->totalCPUs() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )\n myStack.push_back( 0 );\n }\n}\n\n\nstring ComposeNestingLevel::name = \"Nesting Level\";\nTSemanticValue ComposeNestingLevel::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n\n if ( myInfo->values[ 0 ] != 0 )\n myStack[ tmpOrder ]++;\n else\n myStack[ tmpOrder ]--;\n\n return myStack[ tmpOrder ];\n}\n\n\nvoid ComposeDelta::init( KWindow *whichWindow )\n{\n prevValue.clear();\n semPrevValue.clear();\n\n if ( whichWindow->getTrace()->totalThreads() >\n whichWindow->getTrace()->totalCPUs() )\n {\n prevValue.reserve( whichWindow->getTrace()->totalThreads() );\n semPrevValue.reserve( whichWindow->getTrace()->totalThreads() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )\n {\n prevValue.push_back( 0 );\n semPrevValue.push_back( 0 );\n }\n }\n else\n {\n prevValue.reserve( whichWindow->getTrace()->totalCPUs() );\n semPrevValue.reserve( whichWindow->getTrace()->totalCPUs() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )\n {\n prevValue.push_back( 0 );\n semPrevValue.push_back( 0 );\n }\n }\n}\n\n\nstring ComposeDelta::name = \"Delta\";\nTSemanticValue ComposeDelta::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n TSemanticValue result = 0;\n\n if ( myInfo->values[ 0 ] > semPrevValue[ tmpOrder ] )\n result = myInfo->values[ 0 ] - semPrevValue[ tmpOrder ];\n else if ( myInfo->values[ 0 ] == semPrevValue[ tmpOrder ] )\n result = prevValue[ tmpOrder ];\n\n semPrevValue[ tmpOrder ] = myInfo->values[ 0 ];\n prevValue[ tmpOrder ] = result;\n\n return result;\n}\n\n\nstring ComposeBurstTime::name = \"Burst Time\";\nTSemanticValue ComposeBurstTime::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n TSemanticValue result = myInfo->callingInterval->getEnd()->getTime() -\n myInfo->callingInterval->getBegin()->getTime();\n result = myInfo->callingInterval->getWindow()->traceUnitsToWindowUnits( result );\n return result;\n}\n\n\nstring ComposeJoinBursts::name = \"Join Bursts\";\nTSemanticValue ComposeJoinBursts::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n return myInfo->values[ 0 ];\n}\n<commit_msg>*** empty log message ***<commit_after>#include <math.h>\n#include \"semanticcomposefunctions.h\"\n#include \"kwindow.h\"\n\n\nstring ComposeAsIs::name = \"As Is\";\nTSemanticValue ComposeAsIs::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n return myInfo->values[ 0 ];\n}\n\n\nstring ComposeSign::name = \"Sign\";\nTSemanticValue ComposeSign::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n if ( myInfo->values[ 0 ] != 0 )\n return 1;\n return 0;\n}\n\n\nstring ComposeUnsign::name = \"1-Sign\";\nTSemanticValue ComposeUnsign::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp;\n\n if ( myInfo->values[ 0 ] != 0 )\n tmp = 1;\n else\n tmp = 0;\n\n return 1 - tmp;\n}\n\n\nstring ComposeMod::name = \"Mod\";\nTSemanticValue ComposeMod::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue remainder = 0, divider;\n\n if ( parameters[ DIVIDER ][ 0 ] != 0 )\n divider = parameters[ DIVIDER ][ 0 ];\n else\n divider = 1;\n\n remainder = fmod( myInfo->values[ 0 ], divider );\n\n return remainder;\n}\n\n\nstring ComposeModPlus1::name = \"Mod+1\";\nTSemanticValue ComposeModPlus1::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue remainder = 0, divider;\n\n if ( parameters[ DIVIDER ][ 0 ] != 0 )\n divider = parameters[ DIVIDER ][ 0 ];\n else\n divider = 1;\n\n remainder = fmod( myInfo->values[ 0 ], divider );\n\n return remainder + 1;\n}\n\n\nstring ComposeDivide::name = \"Div\";\nTSemanticValue ComposeDivide::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue quotient = 0, divider;\n\n if ( parameters[ DIVIDER ][ 0 ] != 0 )\n quotient = myInfo->values[ 0 ] \/ parameters[ DIVIDER ][ 0 ];\n else\n {\n divider = 1;\n quotient = fmod( myInfo->values[ 0 ], divider );\n }\n return quotient;\n}\n\n\nstring ComposeProduct::name = \"Prod\";\nTSemanticValue ComposeProduct::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n return myInfo->values[ 0 ] * parameters[ FACTOR ][ 0 ];\n}\n\n\nstring ComposeAdding::name = \"Add\";\nTSemanticValue ComposeAdding::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n return myInfo->values[ 0 ] + parameters[ FACTOR ][ 0 ];\n}\n\n\nstring ComposeSubstract::name = \"Subs\";\nTSemanticValue ComposeSubstract::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n return myInfo->values[ 0 ] - parameters[ FACTOR ][ 0 ];\n}\n\n\nstring ComposeSelectRange::name = \"Select Range\";\nTSemanticValue ComposeSelectRange::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n if ( myInfo->values[ 0 ] <= parameters[ MAXVALUE ][ 0 ] &&\n myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )\n tmp = myInfo->values[ 0 ];\n else\n tmp = 0;\n\n return tmp;\n}\n\n\nstring ComposeSelectRangeOpen::name = \"Select Range [)\";\nTSemanticValue ComposeSelectRangeOpen::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n if ( myInfo->values[ 0 ] < parameters[ MAXVALUE ][ 0 ] &&\n myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )\n tmp = myInfo->values[ 0 ];\n else\n tmp = 0;\n\n return tmp;\n}\n\n\nstring ComposeIsInRange::name = \"Is In Range\";\nTSemanticValue ComposeIsInRange::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n if ( myInfo->values[ 0 ] <= parameters[ MAXVALUE ][ 0 ] &&\n myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )\n tmp = 1;\n else\n tmp = 0;\n\n return tmp;\n}\n\n\nstring ComposeIsInRangeOpen::name = \"Is In Range [)\";\nTSemanticValue ComposeIsInRangeOpen::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n if ( myInfo->values[ 0 ] < parameters[ MAXVALUE ][ 0 ] &&\n myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )\n tmp = 1;\n else\n tmp = 0;\n\n return tmp;\n}\n\n\nstring ComposeIsEqual::name = \"Is Equal\";\nTSemanticValue ComposeIsEqual::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n for ( TParamIndex i = 0; i < parameters[ VALUES ].size(); i++ )\n {\n if ( myInfo->values[ 0 ] == parameters[ VALUES ][ i ] )\n {\n tmp = myInfo->values[ 0 ];\n break;\n }\n }\n\n return tmp;\n}\n\n\nstring ComposeIsEqualSign::name = \"Is Equal (Sign)\";\nTSemanticValue ComposeIsEqualSign::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TSemanticValue tmp = 0;\n\n for ( TParamIndex i = 0; i < parameters[ VALUES ].size(); i++ )\n {\n if ( myInfo->values[ 0 ] == parameters[ VALUES ][ i ] )\n {\n tmp = 1;\n break;\n }\n }\n\n return tmp;\n}\n\n\nvoid ComposeStackedValue::init( KWindow *whichWindow )\n{\n myStack.clear();\n\n if ( whichWindow->getTrace()->totalThreads() >\n whichWindow->getTrace()->totalCPUs() )\n {\n myStack.reserve( whichWindow->getTrace()->totalThreads() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )\n myStack.push_back( vector<TSemanticValue>() );\n }\n else\n {\n myStack.reserve( whichWindow->getTrace()->totalCPUs() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )\n myStack.push_back( vector<TSemanticValue>() );\n }\n}\n\n\nstring ComposeStackedValue::name = \"Stacked Val\";\nTSemanticValue ComposeStackedValue::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n\n if ( myInfo->values[ 0 ] != 0 )\n myStack[ tmpOrder ].push_back( myInfo->values[ 0 ] );\n else\n {\n if ( !myStack[ tmpOrder ].empty() )\n myStack[ tmpOrder ].pop_back();\n }\n\n if ( myStack[ tmpOrder ].empty() )\n return 0;\n\n return myStack[ tmpOrder ].back();\n}\n\n\nvoid ComposeInStackedValue::init( KWindow *whichWindow )\n{\n myStack.clear();\n\n if ( whichWindow->getTrace()->totalThreads() >\n whichWindow->getTrace()->totalCPUs() )\n {\n myStack.reserve( whichWindow->getTrace()->totalThreads() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )\n myStack.push_back( vector<TSemanticValue>() );\n }\n else\n {\n myStack.reserve( whichWindow->getTrace()->totalCPUs() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )\n myStack.push_back( vector<TSemanticValue>() );\n }\n}\n\n\nstring ComposeInStackedValue::name = \"In Stacked Val\";\nTSemanticValue ComposeInStackedValue::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n\n if ( myInfo->values[ 0 ] != 0 )\n myStack[ tmpOrder ].push_back( myInfo->values[ 0 ] );\n else\n {\n if ( !myStack[ tmpOrder ].empty() )\n myStack[ tmpOrder ].pop_back();\n }\n\n if ( myStack[ tmpOrder ].empty() )\n return 0;\n\n return myStack[ tmpOrder ].back() == parameters[ VALUE ][ 0 ] ?\n myStack[ tmpOrder ].back() : 0;\n}\n\n\nvoid ComposeNestingLevel::init( KWindow *whichWindow )\n{\n myStack.clear();\n\n if ( whichWindow->getTrace()->totalThreads() >\n whichWindow->getTrace()->totalCPUs() )\n {\n myStack.reserve( whichWindow->getTrace()->totalThreads() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )\n myStack.push_back( 0 );\n }\n else\n {\n myStack.reserve( whichWindow->getTrace()->totalCPUs() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )\n myStack.push_back( 0 );\n }\n}\n\n\nstring ComposeNestingLevel::name = \"Nesting level\";\nTSemanticValue ComposeNestingLevel::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n\n if ( myInfo->values[ 0 ] != 0 )\n myStack[ tmpOrder ]++;\n else\n myStack[ tmpOrder ]--;\n\n return myStack[ tmpOrder ];\n}\n\n\nvoid ComposeDelta::init( KWindow *whichWindow )\n{\n prevValue.clear();\n semPrevValue.clear();\n\n if ( whichWindow->getTrace()->totalThreads() >\n whichWindow->getTrace()->totalCPUs() )\n {\n prevValue.reserve( whichWindow->getTrace()->totalThreads() );\n semPrevValue.reserve( whichWindow->getTrace()->totalThreads() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )\n {\n prevValue.push_back( 0 );\n semPrevValue.push_back( 0 );\n }\n }\n else\n {\n prevValue.reserve( whichWindow->getTrace()->totalCPUs() );\n semPrevValue.reserve( whichWindow->getTrace()->totalCPUs() );\n for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )\n {\n prevValue.push_back( 0 );\n semPrevValue.push_back( 0 );\n }\n }\n}\n\n\nstring ComposeDelta::name = \"Delta\";\nTSemanticValue ComposeDelta::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n TSemanticValue result = 0;\n\n if ( myInfo->values[ 0 ] > semPrevValue[ tmpOrder ] )\n result = myInfo->values[ 0 ] - semPrevValue[ tmpOrder ];\n else if ( myInfo->values[ 0 ] == semPrevValue[ tmpOrder ] )\n result = prevValue[ tmpOrder ];\n\n semPrevValue[ tmpOrder ] = myInfo->values[ 0 ];\n prevValue[ tmpOrder ] = result;\n\n return result;\n}\n\n\nstring ComposeBurstTime::name = \"Burst Time\";\nTSemanticValue ComposeBurstTime::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n TSemanticValue result = myInfo->callingInterval->getEnd()->getTime() -\n myInfo->callingInterval->getBegin()->getTime();\n result = myInfo->callingInterval->getWindow()->traceUnitsToWindowUnits( result );\n return result;\n}\n\n\nstring ComposeJoinBursts::name = \"Join Bursts\";\nTSemanticValue ComposeJoinBursts::execute( const SemanticInfo *info )\n{\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n return myInfo->values[ 0 ];\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright 2015 Centreon\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** For more information : contact@centreon.com\n*\/\n\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include \"test\/cbd.hh\"\n#include \"test\/centengine.hh\"\n#include \"test\/centengine_config.hh\"\n#include \"test\/db.hh\"\n#include \"test\/file.hh\"\n#include \"test\/misc.hh\"\n#include \"test\/predicate.hh\"\n#include \"test\/time_points.hh\"\n#include \"test\/vars.hh\"\n\nusing namespace com::centreon::broker;\n\n#define TEST_NAME \"rtmonitoring_v2_instances\"\n#define DB_NAME \"broker_\" TEST_NAME\n\n\/\/ Check count.\nstatic int check_number(0);\n\n\/**\n * Precheck routine.\n *\/\nstatic void precheck(test::time_points& tpoints, char const* name) {\n ++check_number;\n std::cout << \"check #\" << check_number << \" (\" << name << \")\\n\";\n tpoints.store();\n return ;\n}\n\n\/**\n * Postcheck routine.\n *\/\nstatic void postcheck(\n test::centengine& engine,\n test::time_points& tpoints,\n test::db& db,\n test::predicate expected[][25]) {\n static std::string check_query(\n \"SELECT instance_id, name, active_host_checks,\"\n \" active_service_checks, check_hosts_freshness,\"\n \" check_services_freshness, deleted, end_time, engine,\"\n \" event_handlers, failure_prediction, flap_detection,\"\n \" global_host_event_handler,\"\n \" global_service_event_handler, last_alive,\"\n \" last_command_check, notifications, obsess_over_hosts,\"\n \" obsess_over_services, outdated, passive_host_checks,\"\n \" passive_service_checks, pid, running, start_time\"\n \/\/ XXX : not checked yet \" version\"\n \" FROM instances\");\n engine.reload();\n test::sleep_for(3);\n tpoints.store();\n expected[0][14]\n = test::predicate(tpoints.prelast(), tpoints.last() + 1);\n db.check_content(check_query, expected);\n std::cout << \" passed\\n\";\n return ;\n}\n\n\/**\n * Check that the instances table work properly.\n *\n * @return EXIT_SUCCESS on success.\n *\/\nint main() {\n \/\/ Error flag.\n bool error(true);\n\n try {\n \/\/ Database.\n char const* tables[] = { \"instances\", NULL };\n test::db db(DB_NAME, tables);\n\n \/\/ Monitoring broker.\n test::file cbd_cfg;\n cbd_cfg.set_template(\n PROJECT_SOURCE_DIR \"\/test\/cfg\/sql.xml.in\");\n cbd_cfg.set(\"BROKER_ID\", \"84\");\n cbd_cfg.set(\"BROKER_NAME\", \"my-broker-cbd\");\n cbd_cfg.set(\"POLLER_ID\", \"42\");\n cbd_cfg.set(\"POLLER_NAME\", \"my-poller\");\n cbd_cfg.set(\"TCP_PORT\", \"5571\");\n cbd_cfg.set(\"DB_NAME\", DB_NAME);\n cbd_cfg.set(\n \"SQL_ADDITIONAL\",\n \"<write_filters>\"\n \" <category>neb:instance<\/category>\"\n \" <category>neb:instance_status<\/category>\"\n \"<\/write_filters>\");\n test::cbd broker;\n broker.set_config_file(cbd_cfg.generate());\n broker.start();\n test::sleep_for(1);\n\n \/\/ Monitoring engine.\n test::file cbmod_cfg;\n cbmod_cfg.set_template(\n PROJECT_SOURCE_DIR \"\/test\/cfg\/tcp.xml.in\");\n cbmod_cfg.set(\"BROKER_ID\", \"83\");\n cbmod_cfg.set(\"BROKER_NAME\", \"my-broker-cbmod\");\n cbmod_cfg.set(\"POLLER_ID\", \"42\");\n cbmod_cfg.set(\"POLLER_NAME\", \"my-poller\");\n cbmod_cfg.set(\"TCP_HOST\", \"localhost\");\n cbmod_cfg.set(\"TCP_PORT\", \"5571\");\n test::centengine_config engine_config;\n engine_config.generate_hosts(3);\n engine_config.generate_services(5);\n engine_config.set_cbmod_cfg_file(cbmod_cfg.generate());\n engine_config.set_directive(\"accept_passive_host_checks\", \"0\");\n engine_config.set_directive(\"accept_passive_service_checks\", \"0\");\n engine_config.set_directive(\"check_host_freshness\", \"0\");\n engine_config.set_directive(\"check_service_freshness\", \"0\");\n engine_config.set_directive(\"enable_event_handlers\", \"0\");\n engine_config.set_directive(\"enable_failure_prediction\", \"0\");\n engine_config.set_directive(\"enable_flap_detection\", \"0\");\n engine_config.set_directive(\"enable_notifications\", \"0\");\n engine_config.set_directive(\"execute_host_checks\", \"0\");\n engine_config.set_directive(\"execute_service_checks\", \"0\");\n engine_config.set_directive(\"obsess_over_hosts\", \"0\");\n engine_config.set_directive(\"obsess_over_services\", \"0\");\n test::centengine engine(&engine_config);\n\n \/\/ Objects.\n test::time_points tpoints;\n\n \/\/ Check default entry.\n precheck(tpoints, \"engine, last_alive, pid, running, start_time\");\n engine.start();\n test::sleep_for(1);\n test::predicate expected[][25] = {\n { 42u, \"my-poller\", false, false, false, false, false,\n test::predicate(test::predicate::type_null), \"Centreon Engine\",\n false, false, false, \"\", \"\",\n test::predicate(tpoints.prelast(), tpoints.last() + 1),\n test::predicate(test::predicate::type_null), false, false,\n false, false, false, false,\n true, \/\/ PID will be converted to boolean, any non-0 will match.\n true, test::predicate(tpoints.prelast(), tpoints.last() + 1) },\n { test::predicate() }\n };\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check name.\n precheck(tpoints, \"name\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check active_host_checks.\n precheck(tpoints, \"active_host_checks\");\n engine_config.set_directive(\"execute_host_checks\", \"1\");\n expected[0][2] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check active_service_checks.\n precheck(tpoints, \"active_service_checks\");\n engine_config.set_directive(\"execute_service_checks\", \"1\");\n expected[0][3] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check check_hosts_freshness.\n precheck(tpoints, \"check_hosts_freshness\");\n engine_config.set_directive(\"check_host_freshness\", \"1\");\n expected[0][4] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check check_service_freshness.\n precheck(tpoints, \"check_service_freshness\");\n engine_config.set_directive(\"check_service_freshness\", \"1\");\n expected[0][5] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check event_handlers.\n precheck(tpoints, \"event_handlers\");\n engine_config.set_directive(\"enable_event_handlers\", \"1\");\n expected[0][9] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check failure_prediction.\n precheck(tpoints, \"failure_prediction\");\n engine_config.set_directive(\"enable_failure_prediction\", \"1\");\n expected[0][10] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check flap_detection.\n precheck(tpoints, \"flap_detection\");\n engine_config.set_directive(\"enable_flap_detection\", \"1\");\n expected[0][11] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check global_host_event_handler.\n precheck(tpoints, \"global_host_event_handler\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check global_service_event_handler.\n precheck(tpoints, \"global_service_event_handler\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check notifications.\n precheck(tpoints, \"enable_notifications\");\n engine_config.set_directive(\"enable_notifications\", \"1\");\n expected[0][16] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check obsess_over_hosts.\n precheck(tpoints, \"obsess_over_hosts\");\n engine_config.set_directive(\"obsess_over_hosts\", \"1\");\n expected[0][17] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check obsess_over_services.\n precheck(tpoints, \"obsess_over_services\");\n engine_config.set_directive(\"obsess_over_services\", \"1\");\n expected[0][18] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check passive_host_checks.\n precheck(tpoints, \"passive_host_checks\");\n engine_config.set_directive(\"accept_passive_host_checks\", \"1\");\n expected[0][20] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check passive_service_checks.\n precheck(tpoints, \"passive_service_checks\");\n engine_config.set_directive(\"accept_passive_service_checks\", \"1\");\n expected[0][21] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check version.\n precheck(tpoints, \"version\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check last_command_check.\n precheck(tpoints, \"last_command_check\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check end_time.\n precheck(tpoints, \"end_time\");\n engine.stop();\n test::sleep_for(2);\n tpoints.store();\n {\n test::predicate expected_end_time[][3] = {\n { 42u, test::predicate(tpoints.prelast(), tpoints.last() + 1),\n false },\n { test::predicate() }\n };\n db.check_content(\n \"SELECT instance_id, end_time, running FROM instances\",\n expected_end_time);\n }\n std::cout << \" passed\\n\";\n\n \/\/ Check outdated.\n precheck(tpoints, \"outdated\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check deleted.\n precheck(tpoints, \"deleted\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Success.\n error = false;\n db.set_remove_db_on_close(true);\n broker.stop();\n }\n catch (std::exception const& e) {\n std::cout << \" \" << e.what() << \"\\n\";\n }\n catch (...) {\n std::cout << \" unknown exception\\n\";\n }\n\n return (error ? EXIT_FAILURE : EXIT_SUCCESS);\n}\n<commit_msg>test: minor fixes to unit test.<commit_after>\/*\n** Copyright 2015 Centreon\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** For more information : contact@centreon.com\n*\/\n\n#include <cstdlib>\n#include <iostream>\n#include \"test\/cbd.hh\"\n#include \"test\/centengine.hh\"\n#include \"test\/centengine_config.hh\"\n#include \"test\/db.hh\"\n#include \"test\/file.hh\"\n#include \"test\/misc.hh\"\n#include \"test\/predicate.hh\"\n#include \"test\/time_points.hh\"\n#include \"test\/vars.hh\"\n\nusing namespace com::centreon::broker;\n\n#define TEST_NAME \"rtmonitoring_v2_instances\"\n#define DB_NAME \"broker_\" TEST_NAME\n\n\/\/ Check count.\nstatic int check_number(0);\n\n\/**\n * Precheck routine.\n *\/\nstatic void precheck(test::time_points& tpoints, char const* name) {\n ++check_number;\n std::cout << \"check #\" << check_number << \" (\" << name << \")\\n\";\n tpoints.store();\n return ;\n}\n\n\/**\n * Postcheck routine.\n *\/\nstatic void postcheck(\n test::centengine& engine,\n test::time_points& tpoints,\n test::db& db,\n test::predicate expected[][25]) {\n static std::string check_query(\n \"SELECT instance_id, name, active_host_checks,\"\n \" active_service_checks, check_hosts_freshness,\"\n \" check_services_freshness, deleted, end_time, engine,\"\n \" event_handlers, failure_prediction, flap_detection,\"\n \" global_host_event_handler,\"\n \" global_service_event_handler, last_alive,\"\n \" last_command_check, notifications, obsess_over_hosts,\"\n \" obsess_over_services, outdated, passive_host_checks,\"\n \" passive_service_checks, pid, running, start_time\"\n \/\/ XXX : not checked yet \" version\"\n \" FROM instances\");\n engine.reload();\n test::sleep_for(3);\n tpoints.store();\n expected[0][14]\n = test::predicate(tpoints.prelast(), tpoints.last() + 1);\n db.check_content(check_query, expected);\n std::cout << \" passed\\n\";\n return ;\n}\n\n\/**\n * Check that the instances table work properly.\n *\n * @return EXIT_SUCCESS on success.\n *\/\nint main() {\n \/\/ Error flag.\n bool error(true);\n\n try {\n \/\/ Database.\n char const* tables[] = { \"instances\", NULL };\n test::db db(DB_NAME, tables);\n\n \/\/ Monitoring broker.\n test::file cbd_cfg;\n cbd_cfg.set_template(\n PROJECT_SOURCE_DIR \"\/test\/cfg\/sql.xml.in\");\n cbd_cfg.set(\"BROKER_ID\", \"84\");\n cbd_cfg.set(\"BROKER_NAME\", TEST_NAME \"-cbd\");\n cbd_cfg.set(\"POLLER_ID\", \"42\");\n cbd_cfg.set(\"POLLER_NAME\", \"my-poller\");\n cbd_cfg.set(\"TCP_PORT\", \"5571\");\n cbd_cfg.set(\"DB_NAME\", DB_NAME);\n cbd_cfg.set(\n \"SQL_ADDITIONAL\",\n \"<write_filters>\"\n \" <category>neb:instance<\/category>\"\n \" <category>neb:instance_status<\/category>\"\n \"<\/write_filters>\");\n test::cbd broker;\n broker.set_config_file(cbd_cfg.generate());\n broker.start();\n test::sleep_for(1);\n\n \/\/ Monitoring engine.\n test::file cbmod_cfg;\n cbmod_cfg.set_template(\n PROJECT_SOURCE_DIR \"\/test\/cfg\/tcp.xml.in\");\n cbmod_cfg.set(\"BROKER_ID\", \"83\");\n cbmod_cfg.set(\"BROKER_NAME\", TEST_NAME \"-cbmod\");\n cbmod_cfg.set(\"POLLER_ID\", \"42\");\n cbmod_cfg.set(\"POLLER_NAME\", \"my-poller\");\n cbmod_cfg.set(\"TCP_HOST\", \"localhost\");\n cbmod_cfg.set(\"TCP_PORT\", \"5571\");\n test::centengine_config engine_config;\n engine_config.generate_hosts(3);\n engine_config.generate_services(5);\n engine_config.set_cbmod_cfg_file(cbmod_cfg.generate());\n engine_config.set_directive(\"accept_passive_host_checks\", \"0\");\n engine_config.set_directive(\"accept_passive_service_checks\", \"0\");\n engine_config.set_directive(\"check_host_freshness\", \"0\");\n engine_config.set_directive(\"check_service_freshness\", \"0\");\n engine_config.set_directive(\"enable_event_handlers\", \"0\");\n engine_config.set_directive(\"enable_failure_prediction\", \"0\");\n engine_config.set_directive(\"enable_flap_detection\", \"0\");\n engine_config.set_directive(\"enable_notifications\", \"0\");\n engine_config.set_directive(\"execute_host_checks\", \"0\");\n engine_config.set_directive(\"execute_service_checks\", \"0\");\n engine_config.set_directive(\"obsess_over_hosts\", \"0\");\n engine_config.set_directive(\"obsess_over_services\", \"0\");\n test::centengine engine(&engine_config);\n\n \/\/ Time points.\n test::time_points tpoints;\n\n \/\/ Check default entry.\n precheck(tpoints, \"engine, last_alive, pid, running, start_time\");\n engine.start();\n test::sleep_for(1);\n test::predicate expected[][25] = {\n { 42u, \"my-poller\", false, false, false, false, false,\n test::predicate(test::predicate::type_null), \"Centreon Engine\",\n false, false, false, \"\", \"\",\n test::predicate(tpoints.prelast(), tpoints.last() + 1),\n test::predicate(test::predicate::type_null), false, false,\n false, false, false, false,\n true, \/\/ PID will be converted to boolean, any non-0 will match.\n true, test::predicate(tpoints.prelast(), tpoints.last() + 1) },\n { test::predicate() }\n };\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check name.\n precheck(tpoints, \"name\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check active_host_checks.\n precheck(tpoints, \"active_host_checks\");\n engine_config.set_directive(\"execute_host_checks\", \"1\");\n expected[0][2] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check active_service_checks.\n precheck(tpoints, \"active_service_checks\");\n engine_config.set_directive(\"execute_service_checks\", \"1\");\n expected[0][3] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check check_hosts_freshness.\n precheck(tpoints, \"check_hosts_freshness\");\n engine_config.set_directive(\"check_host_freshness\", \"1\");\n expected[0][4] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check check_service_freshness.\n precheck(tpoints, \"check_service_freshness\");\n engine_config.set_directive(\"check_service_freshness\", \"1\");\n expected[0][5] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check event_handlers.\n precheck(tpoints, \"event_handlers\");\n engine_config.set_directive(\"enable_event_handlers\", \"1\");\n expected[0][9] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check failure_prediction.\n precheck(tpoints, \"failure_prediction\");\n engine_config.set_directive(\"enable_failure_prediction\", \"1\");\n expected[0][10] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check flap_detection.\n precheck(tpoints, \"flap_detection\");\n engine_config.set_directive(\"enable_flap_detection\", \"1\");\n expected[0][11] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check global_host_event_handler.\n precheck(tpoints, \"global_host_event_handler\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check global_service_event_handler.\n precheck(tpoints, \"global_service_event_handler\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check notifications.\n precheck(tpoints, \"enable_notifications\");\n engine_config.set_directive(\"enable_notifications\", \"1\");\n expected[0][16] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check obsess_over_hosts.\n precheck(tpoints, \"obsess_over_hosts\");\n engine_config.set_directive(\"obsess_over_hosts\", \"1\");\n expected[0][17] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check obsess_over_services.\n precheck(tpoints, \"obsess_over_services\");\n engine_config.set_directive(\"obsess_over_services\", \"1\");\n expected[0][18] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check passive_host_checks.\n precheck(tpoints, \"passive_host_checks\");\n engine_config.set_directive(\"accept_passive_host_checks\", \"1\");\n expected[0][20] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check passive_service_checks.\n precheck(tpoints, \"passive_service_checks\");\n engine_config.set_directive(\"accept_passive_service_checks\", \"1\");\n expected[0][21] = true;\n postcheck(engine, tpoints, db, expected);\n\n \/\/ Check version.\n precheck(tpoints, \"version\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check last_command_check.\n precheck(tpoints, \"last_command_check\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check end_time.\n precheck(tpoints, \"end_time\");\n engine.stop();\n test::sleep_for(2);\n tpoints.store();\n {\n test::predicate expected_end_time[][3] = {\n { 42u, test::predicate(tpoints.prelast(), tpoints.last() + 1),\n false },\n { test::predicate() }\n };\n db.check_content(\n \"SELECT instance_id, end_time, running FROM instances\",\n expected_end_time);\n }\n std::cout << \" passed\\n\";\n\n \/\/ Check outdated.\n precheck(tpoints, \"outdated\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Check deleted.\n precheck(tpoints, \"deleted\");\n \/\/ XXX\n \/\/ postcheck(engine, tpoints, db, expected);\n std::cout << \" not tested\\n\";\n\n \/\/ Success.\n error = false;\n db.set_remove_db_on_close(true);\n broker.stop();\n }\n catch (std::exception const& e) {\n std::cout << \" \" << e.what() << \"\\n\";\n }\n catch (...) {\n std::cout << \" unknown exception\\n\";\n }\n\n return (error ? EXIT_FAILURE : EXIT_SUCCESS);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\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 all\n * 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 THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n\n#include \"miopen\/handle.hpp\"\n#include \"miopen\/legacy_exhaustive_search.hpp\"\n#include \"miopen\/solver.hpp\"\n\nnamespace miopen {\nnamespace solver {\n\nbool ConvOclDirectFwd::IsApplicable(const ConvolutionContext& params) const\n{\n \/\/ clang-format off\n return params.kernel_stride0 == params.kernel_stride1\n && params.pad0 == params.pad1\n && !(params.kernel_size0 == 1 && params.kernel_size1 == 1)\n && !(params.direction.IsBackwardData() && (params.kernel_stride0 > 2 || params.kernel_stride1 > 2))\n \/\/\/ \\todo Workaround to avoid LDS overallocation issue:\n && !(params.direction.IsForward() && params.float_size == 16 && params.kernel_size0 == 11 && params.kernel_size1 == 11)\n \/\/\/ \\todo Workaround to avoid FP16 precision issue:\n \/\/\/ While MIOpenConvUni is up to 4x faster than MIOpenCDFGen (even not auto-tuned),\n \/\/\/ it seems that is has 4x..20x worse precision, and some \"test_conv --half\" tests fail.\n && !(params.direction.IsForward() && params.float_size == 16);\n \/\/ clang-format on\n}\n\nConvSolution ConvOclDirectFwd::GetSolution(const ConvolutionContext& params,\n const LegacyPerformanceConfig& searched_params) const\n{\n ConvSolution result;\n\n \/\/ std::size_t localMemSize = params.stream.GetLocalMemorySize();\n\n searched_params.CopyTo(result);\n auto pad0 = params.pad0;\n auto pad1 = params.pad1;\n\n auto hw_wave_sz = 64;\n \/\/ auto dev_local_mem_sz = localMemSize; \/\/ in bytes\n\n if(!params.direction.IsForward())\n {\n \/\/ backward\n pad0 = params.kernel_size0 - 1 - pad0;\n pad1 = params.kernel_size1 - 1 - pad1;\n }\n\n result.n_in_data_tiles = std::min(params.n_inputs, searched_params.n_in_data_tiles);\n result.n_out_pix_tiles = std::min(params.n_outputs, searched_params.n_out_pix_tiles);\n\n \/\/ hacky fix of the incorrect kernel local memory address calculation for data\n result.out_pix_tile1 = (!params.direction.IsForward() && params.kernel_stride1 > 1)\n ? params.kernel_stride1\n : searched_params.out_pix_tile1;\n result.out_pix_tile0 = (!params.direction.IsForward() && params.kernel_stride0 > 1)\n ? params.kernel_stride0\n : searched_params.out_pix_tile0;\n\n if(result.out_pix_tile1 == 0 || result.out_pix_tile0 == 0 \/* DIV\/0 *\/)\n {\n MIOPEN_LOG_E(\"result.out_pix_tile1 == 0 || result.out_pix_tile0 == 0\");\n return ConvSolution(miopenStatusInternalError);\n }\n result.grp_tile0 = std::max(8, (result.in_tile0 \/ result.out_pix_tile0));\n result.grp_tile1 = std::max(8, (result.in_tile1 \/ result.out_pix_tile1));\n result.in_tile0 = result.grp_tile0 * result.out_pix_tile0;\n result.in_tile1 = result.grp_tile1 * result.out_pix_tile1;\n\n int alu_tile0 = (result.in_tile0 + result.out_pix_tile0 - 1) \/ result.out_pix_tile0;\n int alu_tile1 = (result.in_tile1 + result.out_pix_tile1 - 1) \/ result.out_pix_tile1;\n int alu_tiles_sz = (alu_tile0 * alu_tile1);\n if(alu_tiles_sz > 256 || alu_tiles_sz == 0 \/* DIV\/0 *\/)\n {\n MIOPEN_LOG_E(\"need out pix size ajustments (alu_tiles_sz > 256 || alu_tiles_sz == 0)\");\n return ConvSolution(miopenStatusInternalError);\n }\n\n int n_alus_total = (result.grp_tile0 * result.grp_tile1);\n\n result.n_stacks = std::min(result.n_stacks, (n_alus_total + alu_tiles_sz - 1) \/ alu_tiles_sz);\n result.n_stacks = std::min(params.batch_sz, result.n_stacks);\n\n if(result.n_stacks == 0 \/* DIV\/0 *\/)\n {\n MIOPEN_LOG_E(\"result.n_stacks == 0\");\n return ConvSolution(miopenStatusInternalError);\n }\n int n_alus_perstack = (n_alus_total + result.n_stacks - 1) \/ result.n_stacks;\n\n int n_read_procs;\n if((result.grp_tile1 * result.grp_tile0) <=\n static_cast<float>(result.in_tile1 * result.in_tile0))\n {\n n_read_procs = result.grp_tile1 * result.grp_tile0;\n }\n else\n {\n float proc_data_ratio = static_cast<float>(result.in_tile1 * result.in_tile0) \/\n static_cast<float>(result.grp_tile1 * result.grp_tile0);\n n_read_procs = (proc_data_ratio <= 0.25)\n ? (result.grp_tile1 * result.grp_tile0) \/ 4\n : (proc_data_ratio <= 0.5) ? (result.grp_tile1 * result.grp_tile0) \/ 2\n : (result.grp_tile1 * result.grp_tile0);\n }\n\n int n_out_tile_blocks0 = (params.out_width + result.in_tile0 - 1) \/ (result.in_tile0);\n int n_out_tile_blocks1 = (params.out_height + result.in_tile1 - 1) \/ (result.in_tile1);\n\n int n_alu_tiles_perstack = (n_alus_perstack + alu_tiles_sz - 1) \/ alu_tiles_sz;\n int n_out_tiles_perstack = n_alu_tiles_perstack * result.n_out_pix_tiles;\n\n n_out_tiles_perstack = std::min(n_out_tiles_perstack, params.n_outputs);\n\n KernelInfo kernel_params;\n\n kernel_params.comp_options =\n std::string(\" -DMLO_HW_WAVE_SZ=\") + std::to_string(static_cast<long long>(hw_wave_sz)) +\n std::string(\" -DMLO_DIR_FORWARD=\") + (params.direction.IsForward() ? \"1\" : \"0\") +\n std::string(\" -DMLO_FILTER_SIZE0=\") +\n std::to_string(static_cast<long long>(params.kernel_size0)) +\n std::string(\" -DMLO_FILTER_SIZE1=\") +\n std::to_string(static_cast<long long>(params.kernel_size1)) +\n std::string(\" -DMLO_FILTER_PAD0=\") + std::to_string(static_cast<long long>(pad0)) +\n std::string(\" -DMLO_FILTER_PAD1=\") + std::to_string(static_cast<long long>(pad1)) +\n std::string(\" -DMLO_FILTER_STRIDE0=\") +\n std::to_string(static_cast<long long>(params.kernel_stride0)) +\n std::string(\" -DMLO_FILTER_STRIDE1=\") +\n std::to_string(static_cast<long long>(params.kernel_stride1)) +\n std::string(\" -DMLO_N_OUTPUTS=\") +\n std::to_string(static_cast<long long>(params.n_outputs)) + std::string(\" -DMLO_N_INPUTS=\") +\n std::to_string(static_cast<long long>(params.n_inputs)) + std::string(\" -DMLO_BATCH_SZ=\") +\n std::to_string(static_cast<long long>(params.batch_sz)) + std::string(\" -DMLO_OUT_WIDTH=\") +\n std::to_string(static_cast<long long>(params.out_width)) +\n std::string(\" -DMLO_OUT_HEIGHT=\") +\n std::to_string(static_cast<long long>(params.out_height)) +\n std::string(\" -DMLO_OUT_BATCH_STRIDE=\") +\n std::to_string(static_cast<long long>(params.out_batch_stride)) +\n std::string(\" -DMLO_OUT_CHANNEL_STRIDE=\") +\n std::to_string(static_cast<long long>(params.out_channel_stride)) +\n std::string(\" -DMLO_OUT_STRIDE=\") +\n std::to_string(static_cast<long long>(params.out_stride)) +\n std::string(\" -DMLO_IN_WIDTH=\") + std::to_string(static_cast<long long>(params.in_width)) +\n std::string(\" -DMLO_IN_HEIGHT=\") +\n std::to_string(static_cast<long long>(params.in_height)) +\n std::string(\" -DMLO_IN_BATCH_STRIDE=\") +\n std::to_string(static_cast<long long>(params.in_batch_stride)) +\n std::string(\" -DMLO_IN_CHANNEL_STRIDE=\") +\n std::to_string(static_cast<long long>(params.in_channel_stride)) +\n std::string(\" -DMLO_IN_STRIDE=\") + std::to_string(static_cast<long long>(params.in_stride))\n \/\/ algorithm parameters\n + std::string(\" -DMLO_IN_TILE0=\") +\n std::to_string(static_cast<long long>(result.in_tile0)) \/\/ size of input data per ALU plane\n + std::string(\" -DMLO_IN_TILE1=\") +\n std::to_string(static_cast<long long>(result.in_tile1)) \/\/ size of input data per ALU plane\n + std::string(\" -DMLO_GRP_TILE0=\") +\n std::to_string(static_cast<long long>(result.grp_tile0)) \/\/ # of ALUs (group size)\n + std::string(\" -DMLO_GRP_TILE1=\") +\n std::to_string(static_cast<long long>(result.grp_tile1)) \/\/\n + std::string(\" -DMLO_OUT_TILE0=\") +\n std::to_string(\n static_cast<long long>(result.out_pix_tile0)) \/\/ size of ouptput tile per wk-item (ALU))\n + std::string(\" -DMLO_OUT_TILE1=\") +\n std::to_string(static_cast<long long>(result.out_pix_tile1)) \/\/\n + std::string(\" -DMLO_N_STACKS=\") +\n std::to_string(static_cast<long long>(result.n_stacks)) \/\/ # of diff stacks (part of batch).\n + std::string(\" -DMLO_N_OUT_TILES=\") +\n std::to_string(static_cast<long long>(\n result.n_out_pix_tiles)) \/\/ # output pixel tiles per wk-item (ALU)\n + std::string(\" -DMLO_N_OUT_TILES_PERSTACK=\") +\n std::to_string(static_cast<long long>(n_out_tiles_perstack)) +\n std::string(\" -DMLO_N_IN_TILES_PERSTACK=\") +\n std::to_string(static_cast<long long>(\n result.n_in_data_tiles)) \/\/ total # of blocks of different inputs in LDS\n + std::string(\" -DMLO_N_READ_PROCS=\") +\n std::to_string(static_cast<long long>(n_read_procs)) + std::string(\" -DMLO_CONV_BIAS=\") +\n std::to_string(static_cast<long long>(params.bias)) + std::string(\" -DMLO_ALU_VTILE0=\") +\n std::to_string(static_cast<long long>(alu_tile0)) + std::string(\" -DMLO_ALU_VTILE1=\") +\n std::to_string(static_cast<long long>(alu_tile1)) + params.general_compile_options;\n\n kernel_params.l_wk.push_back(result.grp_tile1 * result.grp_tile0);\n kernel_params.l_wk.push_back(1);\n kernel_params.l_wk.push_back(1);\n\n size_t gbl_wk0 = n_out_tile_blocks0 * n_out_tile_blocks1;\n\n if(n_out_tiles_perstack == 0 \/* DIV\/0 *\/)\n {\n MIOPEN_LOG_E(\"n_out_tiles_perstack == 0\");\n return ConvSolution(miopenStatusInternalError);\n }\n size_t gbl_wk1 = (params.n_outputs + n_out_tiles_perstack - 1) \/ n_out_tiles_perstack;\n size_t gbl_wk2 = (params.batch_sz + result.n_stacks - 1) \/ result.n_stacks;\n\n kernel_params.g_wk.push_back(gbl_wk0 * kernel_params.l_wk[0]);\n kernel_params.g_wk.push_back(gbl_wk1);\n kernel_params.g_wk.push_back(gbl_wk2);\n\n kernel_params.kernel_file = \"MIOpenConvDirUni.cl\";\n kernel_params.kernel_name = \"MIOpenConvUni\";\n\n result.construction_params.push_back(kernel_params);\n return result;\n}\n} \/\/ namespace solver\n} \/\/ namespace miopen\n<commit_msg>select-fastest-solution(27) Narrowed FP16 fwd conv fix (exclusions in MIOpenConvUni).<commit_after>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\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 all\n * 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 THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n\n#include \"miopen\/handle.hpp\"\n#include \"miopen\/legacy_exhaustive_search.hpp\"\n#include \"miopen\/solver.hpp\"\n\nnamespace miopen {\nnamespace solver {\n\nbool ConvOclDirectFwd::IsApplicable(const ConvolutionContext& params) const\n{\n \/\/ clang-format off\n return params.kernel_stride0 == params.kernel_stride1\n && params.pad0 == params.pad1\n && !(params.kernel_size0 == 1 && params.kernel_size1 == 1)\n && !(params.direction.IsBackwardData() && (params.kernel_stride0 > 2 || params.kernel_stride1 > 2))\n \/\/\/ \\todo Workaround to avoid LDS overallocation issue:\n && !(params.direction.IsForward()\n && params.float_size == 16\n && params.kernel_size0 == 11\n && params.kernel_size1 == 11\n && params.kernel_stride0 == 4)\n \/\/\/ \\todo Workaround to avoid FP16 precision issue:\n \/\/\/ While MIOpenConvUni is up to 4x faster than MIOpenCDFGen (even not auto-tuned),\n \/\/\/ it seems that is has 4x..20x worse precision, and some \"test_conv --half\" tests fail.\n && !(params.direction.IsForward()\n && params.float_size == 16\n && params.kernel_stride0 == 2);\n \/\/ clang-format on\n}\n\nConvSolution ConvOclDirectFwd::GetSolution(const ConvolutionContext& params,\n const LegacyPerformanceConfig& searched_params) const\n{\n ConvSolution result;\n\n \/\/ std::size_t localMemSize = params.stream.GetLocalMemorySize();\n\n searched_params.CopyTo(result);\n auto pad0 = params.pad0;\n auto pad1 = params.pad1;\n\n auto hw_wave_sz = 64;\n \/\/ auto dev_local_mem_sz = localMemSize; \/\/ in bytes\n\n if(!params.direction.IsForward())\n {\n \/\/ backward\n pad0 = params.kernel_size0 - 1 - pad0;\n pad1 = params.kernel_size1 - 1 - pad1;\n }\n\n result.n_in_data_tiles = std::min(params.n_inputs, searched_params.n_in_data_tiles);\n result.n_out_pix_tiles = std::min(params.n_outputs, searched_params.n_out_pix_tiles);\n\n \/\/ hacky fix of the incorrect kernel local memory address calculation for data\n result.out_pix_tile1 = (!params.direction.IsForward() && params.kernel_stride1 > 1)\n ? params.kernel_stride1\n : searched_params.out_pix_tile1;\n result.out_pix_tile0 = (!params.direction.IsForward() && params.kernel_stride0 > 1)\n ? params.kernel_stride0\n : searched_params.out_pix_tile0;\n\n if(result.out_pix_tile1 == 0 || result.out_pix_tile0 == 0 \/* DIV\/0 *\/)\n {\n MIOPEN_LOG_E(\"result.out_pix_tile1 == 0 || result.out_pix_tile0 == 0\");\n return ConvSolution(miopenStatusInternalError);\n }\n result.grp_tile0 = std::max(8, (result.in_tile0 \/ result.out_pix_tile0));\n result.grp_tile1 = std::max(8, (result.in_tile1 \/ result.out_pix_tile1));\n result.in_tile0 = result.grp_tile0 * result.out_pix_tile0;\n result.in_tile1 = result.grp_tile1 * result.out_pix_tile1;\n\n int alu_tile0 = (result.in_tile0 + result.out_pix_tile0 - 1) \/ result.out_pix_tile0;\n int alu_tile1 = (result.in_tile1 + result.out_pix_tile1 - 1) \/ result.out_pix_tile1;\n int alu_tiles_sz = (alu_tile0 * alu_tile1);\n if(alu_tiles_sz > 256 || alu_tiles_sz == 0 \/* DIV\/0 *\/)\n {\n MIOPEN_LOG_E(\"need out pix size ajustments (alu_tiles_sz > 256 || alu_tiles_sz == 0)\");\n return ConvSolution(miopenStatusInternalError);\n }\n\n int n_alus_total = (result.grp_tile0 * result.grp_tile1);\n\n result.n_stacks = std::min(result.n_stacks, (n_alus_total + alu_tiles_sz - 1) \/ alu_tiles_sz);\n result.n_stacks = std::min(params.batch_sz, result.n_stacks);\n\n if(result.n_stacks == 0 \/* DIV\/0 *\/)\n {\n MIOPEN_LOG_E(\"result.n_stacks == 0\");\n return ConvSolution(miopenStatusInternalError);\n }\n int n_alus_perstack = (n_alus_total + result.n_stacks - 1) \/ result.n_stacks;\n\n int n_read_procs;\n if((result.grp_tile1 * result.grp_tile0) <=\n static_cast<float>(result.in_tile1 * result.in_tile0))\n {\n n_read_procs = result.grp_tile1 * result.grp_tile0;\n }\n else\n {\n float proc_data_ratio = static_cast<float>(result.in_tile1 * result.in_tile0) \/\n static_cast<float>(result.grp_tile1 * result.grp_tile0);\n n_read_procs = (proc_data_ratio <= 0.25)\n ? (result.grp_tile1 * result.grp_tile0) \/ 4\n : (proc_data_ratio <= 0.5) ? (result.grp_tile1 * result.grp_tile0) \/ 2\n : (result.grp_tile1 * result.grp_tile0);\n }\n\n int n_out_tile_blocks0 = (params.out_width + result.in_tile0 - 1) \/ (result.in_tile0);\n int n_out_tile_blocks1 = (params.out_height + result.in_tile1 - 1) \/ (result.in_tile1);\n\n int n_alu_tiles_perstack = (n_alus_perstack + alu_tiles_sz - 1) \/ alu_tiles_sz;\n int n_out_tiles_perstack = n_alu_tiles_perstack * result.n_out_pix_tiles;\n\n n_out_tiles_perstack = std::min(n_out_tiles_perstack, params.n_outputs);\n\n KernelInfo kernel_params;\n\n kernel_params.comp_options =\n std::string(\" -DMLO_HW_WAVE_SZ=\") + std::to_string(static_cast<long long>(hw_wave_sz)) +\n std::string(\" -DMLO_DIR_FORWARD=\") + (params.direction.IsForward() ? \"1\" : \"0\") +\n std::string(\" -DMLO_FILTER_SIZE0=\") +\n std::to_string(static_cast<long long>(params.kernel_size0)) +\n std::string(\" -DMLO_FILTER_SIZE1=\") +\n std::to_string(static_cast<long long>(params.kernel_size1)) +\n std::string(\" -DMLO_FILTER_PAD0=\") + std::to_string(static_cast<long long>(pad0)) +\n std::string(\" -DMLO_FILTER_PAD1=\") + std::to_string(static_cast<long long>(pad1)) +\n std::string(\" -DMLO_FILTER_STRIDE0=\") +\n std::to_string(static_cast<long long>(params.kernel_stride0)) +\n std::string(\" -DMLO_FILTER_STRIDE1=\") +\n std::to_string(static_cast<long long>(params.kernel_stride1)) +\n std::string(\" -DMLO_N_OUTPUTS=\") +\n std::to_string(static_cast<long long>(params.n_outputs)) + std::string(\" -DMLO_N_INPUTS=\") +\n std::to_string(static_cast<long long>(params.n_inputs)) + std::string(\" -DMLO_BATCH_SZ=\") +\n std::to_string(static_cast<long long>(params.batch_sz)) + std::string(\" -DMLO_OUT_WIDTH=\") +\n std::to_string(static_cast<long long>(params.out_width)) +\n std::string(\" -DMLO_OUT_HEIGHT=\") +\n std::to_string(static_cast<long long>(params.out_height)) +\n std::string(\" -DMLO_OUT_BATCH_STRIDE=\") +\n std::to_string(static_cast<long long>(params.out_batch_stride)) +\n std::string(\" -DMLO_OUT_CHANNEL_STRIDE=\") +\n std::to_string(static_cast<long long>(params.out_channel_stride)) +\n std::string(\" -DMLO_OUT_STRIDE=\") +\n std::to_string(static_cast<long long>(params.out_stride)) +\n std::string(\" -DMLO_IN_WIDTH=\") + std::to_string(static_cast<long long>(params.in_width)) +\n std::string(\" -DMLO_IN_HEIGHT=\") +\n std::to_string(static_cast<long long>(params.in_height)) +\n std::string(\" -DMLO_IN_BATCH_STRIDE=\") +\n std::to_string(static_cast<long long>(params.in_batch_stride)) +\n std::string(\" -DMLO_IN_CHANNEL_STRIDE=\") +\n std::to_string(static_cast<long long>(params.in_channel_stride)) +\n std::string(\" -DMLO_IN_STRIDE=\") + std::to_string(static_cast<long long>(params.in_stride))\n \/\/ algorithm parameters\n + std::string(\" -DMLO_IN_TILE0=\") +\n std::to_string(static_cast<long long>(result.in_tile0)) \/\/ size of input data per ALU plane\n + std::string(\" -DMLO_IN_TILE1=\") +\n std::to_string(static_cast<long long>(result.in_tile1)) \/\/ size of input data per ALU plane\n + std::string(\" -DMLO_GRP_TILE0=\") +\n std::to_string(static_cast<long long>(result.grp_tile0)) \/\/ # of ALUs (group size)\n + std::string(\" -DMLO_GRP_TILE1=\") +\n std::to_string(static_cast<long long>(result.grp_tile1)) \/\/\n + std::string(\" -DMLO_OUT_TILE0=\") +\n std::to_string(\n static_cast<long long>(result.out_pix_tile0)) \/\/ size of ouptput tile per wk-item (ALU))\n + std::string(\" -DMLO_OUT_TILE1=\") +\n std::to_string(static_cast<long long>(result.out_pix_tile1)) \/\/\n + std::string(\" -DMLO_N_STACKS=\") +\n std::to_string(static_cast<long long>(result.n_stacks)) \/\/ # of diff stacks (part of batch).\n + std::string(\" -DMLO_N_OUT_TILES=\") +\n std::to_string(static_cast<long long>(\n result.n_out_pix_tiles)) \/\/ # output pixel tiles per wk-item (ALU)\n + std::string(\" -DMLO_N_OUT_TILES_PERSTACK=\") +\n std::to_string(static_cast<long long>(n_out_tiles_perstack)) +\n std::string(\" -DMLO_N_IN_TILES_PERSTACK=\") +\n std::to_string(static_cast<long long>(\n result.n_in_data_tiles)) \/\/ total # of blocks of different inputs in LDS\n + std::string(\" -DMLO_N_READ_PROCS=\") +\n std::to_string(static_cast<long long>(n_read_procs)) + std::string(\" -DMLO_CONV_BIAS=\") +\n std::to_string(static_cast<long long>(params.bias)) + std::string(\" -DMLO_ALU_VTILE0=\") +\n std::to_string(static_cast<long long>(alu_tile0)) + std::string(\" -DMLO_ALU_VTILE1=\") +\n std::to_string(static_cast<long long>(alu_tile1)) + params.general_compile_options;\n\n kernel_params.l_wk.push_back(result.grp_tile1 * result.grp_tile0);\n kernel_params.l_wk.push_back(1);\n kernel_params.l_wk.push_back(1);\n\n size_t gbl_wk0 = n_out_tile_blocks0 * n_out_tile_blocks1;\n\n if(n_out_tiles_perstack == 0 \/* DIV\/0 *\/)\n {\n MIOPEN_LOG_E(\"n_out_tiles_perstack == 0\");\n return ConvSolution(miopenStatusInternalError);\n }\n size_t gbl_wk1 = (params.n_outputs + n_out_tiles_perstack - 1) \/ n_out_tiles_perstack;\n size_t gbl_wk2 = (params.batch_sz + result.n_stacks - 1) \/ result.n_stacks;\n\n kernel_params.g_wk.push_back(gbl_wk0 * kernel_params.l_wk[0]);\n kernel_params.g_wk.push_back(gbl_wk1);\n kernel_params.g_wk.push_back(gbl_wk2);\n\n kernel_params.kernel_file = \"MIOpenConvDirUni.cl\";\n kernel_params.kernel_name = \"MIOpenConvUni\";\n\n result.construction_params.push_back(kernel_params);\n return result;\n}\n} \/\/ namespace solver\n} \/\/ namespace miopen\n<|endoftext|>"} {"text":"<commit_before>#include \"unlimited.h\"\n\n#include \"test\/test_bitcoin.h\"\n#include \"..\/consensus\/consensus.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/lexical_cast.hpp>\n\nusing namespace std;\n\n\/\/ Defined in rpc_tests.cpp not bitcoin-cli.cpp\nextern UniValue CallRPC(string strMethod);\n\nBOOST_FIXTURE_TEST_SUITE(excessiveblock_test, TestingSetup)\n\nBOOST_AUTO_TEST_CASE(rpc_excessive)\n{\n BOOST_CHECK_NO_THROW(CallRPC(\"getexcessiveblock\"));\n\n BOOST_CHECK_NO_THROW(CallRPC(\"getminingmaxblock\"));\n\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock not_uint\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock 1000000 not_uint\"), boost::bad_lexical_cast);\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock 1000000 -1\"), boost::bad_lexical_cast);\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock -1 0\"), boost::bad_lexical_cast);\n\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock 1000 1\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"setminingmaxblock 1000\"));\n BOOST_CHECK_NO_THROW(CallRPC(\"setexcessiveblock 1000 1\"));\n\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock 1000 0 0\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock 100000\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock not_uint\"), boost::bad_lexical_cast);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock -1\"), boost::bad_lexical_cast);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock 0\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock 0 0\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"setminingmaxblock 1000\"));\n BOOST_CHECK_NO_THROW(CallRPC(\"setminingmaxblock 101\"));\n \n}\n\nBOOST_AUTO_TEST_CASE(buip005)\n{\n string exceptedEB;\n string exceptedAD;\n excessiveBlockSize = 1000000;\n excessiveAcceptDepth = 9999999;\n exceptedEB = \"EB1\";\n exceptedAD = \"AD9999999\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD,\n \"AD ought to have been \" << exceptedAD << \" when excessiveBlockSize = \" << excessiveAcceptDepth);\n excessiveBlockSize = 100000;\n excessiveAcceptDepth = 9999999 + 1;\n exceptedEB = \"EB0.1\";\n exceptedAD = \"AD9999999\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD,\n \"AD ought to have been \" << exceptedAD << \" when excessiveBlockSize = \" << excessiveAcceptDepth);\n excessiveBlockSize = 10000;\n exceptedEB = \"EB0\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n excessiveBlockSize = 150000;\n exceptedEB = \"EB0.1\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been rounded to \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n excessiveBlockSize = 150000;\n exceptedEB = \"EB0.1\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been rounded to \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n\n \/\/ set back to defaults\n excessiveBlockSize = 1000000;\n excessiveAcceptDepth = 4;\n}\n\n\nBOOST_AUTO_TEST_CASE(excessiveChecks)\n{\n CBlock block;\n\n excessiveBlockSize = 16000000; \/\/ Ignore excessive block size when checking sigops and block effort\n\n \/\/ Check sigops values\n\n \/\/ Maintain compatibility with the old sigops calculator for blocks <= 1MB\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), \"improper sigops\");\n\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), \"improper sigops\");\n\n\n \/\/ Check sigops > 1MB.\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2),100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2)+1,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,(2*1000000),(blockSigopsPerMb.value*2)+1,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,(2*1000000)+1,(blockSigopsPerMb.value*2)+1,100,100), \"improper sigops\");\n\n \n \/\/ Check tx size values\n maxTxSize.value = DEFAULT_LARGEST_TRANSACTION;\n\n \/\/ Within a 1 MB block, a 1MB transaction is not excessive\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,1,1,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE), \"improper max tx\");\n\n \/\/ With a > 1 MB block, use the maxTxSize to determine\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value), \"improper max tx\");\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value+1), \"improper max tx\");\n\n\n}\n\nBOOST_AUTO_TEST_CASE(check_validator_rule)\n{\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1000000, 1000000));\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(16000000, 1000000));\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1000001, 1000000));\n\n BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(1000000, 1000001));\n BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(1000000, 16000000));\n\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1357, 1357));\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(161616, 2222));\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(88889, 88888));\n\n BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(929292, 929293));\n BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(4, 234245));\n}\n\nBOOST_AUTO_TEST_CASE(check_excessive_validator)\n{\n \/\/ fudge global variables....\n maxGeneratedBlock = 1000000;\n excessiveBlockSize = 888;\n\n unsigned int tmpExcessive = 1000000;\n std::string str;\n\n str = ExcessiveBlockValidator(tmpExcessive, NULL, true);\n BOOST_CHECK(str.empty());\n\n excessiveBlockSize = 888;\n str = ExcessiveBlockValidator(tmpExcessive, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true);\n BOOST_CHECK(str.empty());\n\n tmpExcessive = maxGeneratedBlock + 1;\n\n str = ExcessiveBlockValidator(tmpExcessive, NULL, true);\n BOOST_CHECK(str.empty());\n\n excessiveBlockSize = 888;\n str = ExcessiveBlockValidator(tmpExcessive, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true);\n BOOST_CHECK(str.empty());\n\n tmpExcessive = maxGeneratedBlock - 1;\n\n str = ExcessiveBlockValidator(tmpExcessive, NULL, true);\n BOOST_CHECK(! str.empty());\n\n str = ExcessiveBlockValidator(tmpExcessive, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true);\n BOOST_CHECK(! str.empty());\n}\n\nBOOST_AUTO_TEST_CASE(check_generated_block_validator)\n{\n \/\/ fudge global variables....\n maxGeneratedBlock = 888;\n excessiveBlockSize = 1000000;\n\n uint64_t tmpMGB = 1000000;\n std::string str;\n\n str = MiningBlockSizeValidator(tmpMGB, NULL, true);\n BOOST_CHECK(str.empty());\n\n maxGeneratedBlock = 8888881;\n str = MiningBlockSizeValidator(tmpMGB, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true);\n BOOST_CHECK(str.empty());\n\n tmpMGB = excessiveBlockSize - 1;\n\n str = MiningBlockSizeValidator(tmpMGB, NULL, true);\n BOOST_CHECK(str.empty());\n\n maxGeneratedBlock = 8888881;\n str = MiningBlockSizeValidator(tmpMGB, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true);\n BOOST_CHECK(str.empty());\n\n tmpMGB = excessiveBlockSize + 1;\n\n str = MiningBlockSizeValidator(tmpMGB, NULL, true);\n BOOST_CHECK(! str.empty());\n\n str = MiningBlockSizeValidator(tmpMGB, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true);\n BOOST_CHECK(! str.empty());\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Made the unit test clean up after itself so as to not interfere with other test cases.<commit_after>#include \"unlimited.h\"\n\n#include \"test\/test_bitcoin.h\"\n#include \"..\/consensus\/consensus.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/lexical_cast.hpp>\n\nusing namespace std;\n\n\/\/ Defined in rpc_tests.cpp not bitcoin-cli.cpp\nextern UniValue CallRPC(string strMethod);\n\nBOOST_FIXTURE_TEST_SUITE(excessiveblock_test, TestingSetup)\n\nBOOST_AUTO_TEST_CASE(rpc_excessive)\n{\n BOOST_CHECK_NO_THROW(CallRPC(\"getexcessiveblock\"));\n\n BOOST_CHECK_NO_THROW(CallRPC(\"getminingmaxblock\"));\n\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock not_uint\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock 1000000 not_uint\"), boost::bad_lexical_cast);\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock 1000000 -1\"), boost::bad_lexical_cast);\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock -1 0\"), boost::bad_lexical_cast);\n\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock 1000 1\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"setminingmaxblock 1000\"));\n BOOST_CHECK_NO_THROW(CallRPC(\"setexcessiveblock 1000 1\"));\n\n BOOST_CHECK_THROW(CallRPC(\"setexcessiveblock 1000 0 0\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock 100000\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock not_uint\"), boost::bad_lexical_cast);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock -1\"), boost::bad_lexical_cast);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock 0\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"setminingmaxblock 0 0\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"setminingmaxblock 1000\"));\n BOOST_CHECK_NO_THROW(CallRPC(\"setminingmaxblock 101\"));\n \n}\n\nBOOST_AUTO_TEST_CASE(buip005)\n{\n string exceptedEB;\n string exceptedAD;\n excessiveBlockSize = 1000000;\n excessiveAcceptDepth = 9999999;\n exceptedEB = \"EB1\";\n exceptedAD = \"AD9999999\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD,\n \"AD ought to have been \" << exceptedAD << \" when excessiveBlockSize = \" << excessiveAcceptDepth);\n excessiveBlockSize = 100000;\n excessiveAcceptDepth = 9999999 + 1;\n exceptedEB = \"EB0.1\";\n exceptedAD = \"AD9999999\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD,\n \"AD ought to have been \" << exceptedAD << \" when excessiveBlockSize = \" << excessiveAcceptDepth);\n excessiveBlockSize = 10000;\n exceptedEB = \"EB0\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n excessiveBlockSize = 150000;\n exceptedEB = \"EB0.1\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been rounded to \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n excessiveBlockSize = 150000;\n exceptedEB = \"EB0.1\";\n settingsToUserAgentString();\n BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB,\n \"EB ought to have been rounded to \" << exceptedEB << \" when excessiveBlockSize = \"\n << excessiveBlockSize << \" but was \" << BUComments.front());\n\n \/\/ set back to defaults\n excessiveBlockSize = 1000000;\n excessiveAcceptDepth = 4;\n}\n\n\nBOOST_AUTO_TEST_CASE(excessiveChecks)\n{\n CBlock block;\n\n excessiveBlockSize = 16000000; \/\/ Ignore excessive block size when checking sigops and block effort\n\n \/\/ Check sigops values\n\n \/\/ Maintain compatibility with the old sigops calculator for blocks <= 1MB\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), \"improper sigops\");\n\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), \"improper sigops\");\n\n\n \/\/ Check sigops > 1MB.\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2),100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2)+1,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,(2*1000000),(blockSigopsPerMb.value*2)+1,100,100), \"improper sigops\");\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,(2*1000000)+1,(blockSigopsPerMb.value*2)+1,100,100), \"improper sigops\");\n\n \n \/\/ Check tx size values\n maxTxSize.value = DEFAULT_LARGEST_TRANSACTION;\n\n \/\/ Within a 1 MB block, a 1MB transaction is not excessive\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,1,1,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE), \"improper max tx\");\n\n \/\/ With a > 1 MB block, use the maxTxSize to determine\n BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value), \"improper max tx\");\n BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value+1), \"improper max tx\");\n\n\n}\n\nBOOST_AUTO_TEST_CASE(check_validator_rule)\n{\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1000000, 1000000));\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(16000000, 1000000));\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1000001, 1000000));\n\n BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(1000000, 1000001));\n BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(1000000, 16000000));\n\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1357, 1357));\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(161616, 2222));\n BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(88889, 88888));\n\n BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(929292, 929293));\n BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(4, 234245));\n}\n\nBOOST_AUTO_TEST_CASE(check_excessive_validator)\n{\n unsigned int c_mgb = maxGeneratedBlock;\n unsigned int c_ebs = excessiveBlockSize;\n\n \/\/ fudge global variables....\n maxGeneratedBlock = 1000000;\n excessiveBlockSize = 888;\n\n unsigned int tmpExcessive = 1000000;\n std::string str;\n\n str = ExcessiveBlockValidator(tmpExcessive, NULL, true);\n BOOST_CHECK(str.empty());\n\n excessiveBlockSize = 888;\n str = ExcessiveBlockValidator(tmpExcessive, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true);\n BOOST_CHECK(str.empty());\n\n tmpExcessive = maxGeneratedBlock + 1;\n\n str = ExcessiveBlockValidator(tmpExcessive, NULL, true);\n BOOST_CHECK(str.empty());\n\n excessiveBlockSize = 888;\n str = ExcessiveBlockValidator(tmpExcessive, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true);\n BOOST_CHECK(str.empty());\n\n tmpExcessive = maxGeneratedBlock - 1;\n\n str = ExcessiveBlockValidator(tmpExcessive, NULL, true);\n BOOST_CHECK(! str.empty());\n\n str = ExcessiveBlockValidator(tmpExcessive, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true);\n BOOST_CHECK(! str.empty());\n\n maxGeneratedBlock = c_mgb;\n excessiveBlockSize = c_ebs;\n}\n\nBOOST_AUTO_TEST_CASE(check_generated_block_validator)\n{\n unsigned int c_mgb = maxGeneratedBlock;\n unsigned int c_ebs = excessiveBlockSize;\n\n \/\/ fudge global variables....\n maxGeneratedBlock = 888;\n excessiveBlockSize = 1000000;\n\n uint64_t tmpMGB = 1000000;\n std::string str;\n\n str = MiningBlockSizeValidator(tmpMGB, NULL, true);\n BOOST_CHECK(str.empty());\n\n maxGeneratedBlock = 8888881;\n str = MiningBlockSizeValidator(tmpMGB, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true);\n BOOST_CHECK(str.empty());\n\n tmpMGB = excessiveBlockSize - 1;\n\n str = MiningBlockSizeValidator(tmpMGB, NULL, true);\n BOOST_CHECK(str.empty());\n\n maxGeneratedBlock = 8888881;\n str = MiningBlockSizeValidator(tmpMGB, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true);\n BOOST_CHECK(str.empty());\n\n tmpMGB = excessiveBlockSize + 1;\n\n str = MiningBlockSizeValidator(tmpMGB, NULL, true);\n BOOST_CHECK(! str.empty());\n\n str = MiningBlockSizeValidator(tmpMGB, NULL, false);\n BOOST_CHECK(str.empty());\n\n str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true);\n BOOST_CHECK(! str.empty());\n\n maxGeneratedBlock = c_mgb;\n excessiveBlockSize = c_ebs;\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include \"Mocks.hpp\"\n\n#include <ctime>\n\nusing namespace blackhole;\n\nclass base_frontend_t {\npublic:\n virtual void handle(log::record_t&& record) = 0;\n};\n\ntemplate<class Formatter, class Sink>\nclass frontend_t : public base_frontend_t {\n const std::unique_ptr<Formatter> m_formatter;\n const std::unique_ptr<Sink> m_sink;\npublic:\n frontend_t(std::unique_ptr<Formatter> formatter, std::unique_ptr<Sink> sink) :\n m_formatter(std::move(formatter)),\n m_sink(std::move(sink))\n {}\n\n void handle(log::record_t&& record) {\n auto msg = std::move(m_formatter->format(record));\n m_sink->consume(msg);\n }\n};\n\ntypedef std::function<bool(const log::attributes_t& attributes)> filter_t;\n\nstruct default_filter_t {\n static default_filter_t& instance() {\n static default_filter_t filter;\n return filter;\n }\n\n bool operator()(const log::attributes_t&) {\n return true;\n }\n\nprivate:\n default_filter_t() {}\n};\n\nnamespace helper {\n\nstruct LessEqThan {\n template<typename L, typename R>\n static bool execute(const L& left, const R& right) {\n return left <= right;\n }\n};\n\nstruct Eq {\n template<typename L, typename R>\n static bool execute(const L& left, const R& right) {\n return left == right;\n }\n};\n\n} \/\/ namespace helper\n\nlog::attributes_t merge(const std::initializer_list<log::attributes_t>& args) {\n log::attributes_t summary;\n for (auto it = args.begin(); it != args.end(); ++it) {\n summary.insert(it->begin(), it->end());\n }\n\n return summary;\n}\n\nnamespace expr {\n\ntemplate<typename T>\nstruct has_attr_action_t {\n bool operator()(const log::attributes_t& attributes) const {\n return attributes.find(T::name()) != attributes.end();\n }\n};\n\ntemplate<typename T>\nhas_attr_action_t<T> has_attr(const T&) {\n return has_attr_action_t<T>();\n}\n\n} \/\/ namespace expr\n\nnamespace keyword {\n\ntemplate<typename T, class = void>\nstruct traits {\n static inline void pack(log::attributes_t& attributes, const std::string& name, const T& value) {\n attributes[name] = value;\n }\n\n static inline T pack(const T& value) {\n return value;\n }\n\n static inline T extract(const log::attributes_t& attributes, const std::string& name) {\n return boost::get<T>(attributes.at(name));\n }\n};\n\ntemplate<typename T>\nstruct traits<T, typename std::enable_if<std::is_enum<T>::value>::type> {\n typedef typename std::underlying_type<T>::type underlying_type;\n\n static inline void pack(log::attributes_t& attributes, const std::string& name, const T& value) {\n attributes[name] = static_cast<underlying_type>(value);\n }\n\n static inline underlying_type pack(const T& value) {\n return static_cast<underlying_type>(value);\n }\n\n static inline T extract(const log::attributes_t& attributes, const std::string& name) {\n return static_cast<T>(boost::get<underlying_type>(attributes.at(name)));\n }\n};\n\n\/\/!@todo: Need testing.\ntemplate<typename T, typename NameProvider>\nstruct keyword_t {\n static const char* name() {\n return NameProvider::name();\n }\n\n log::attribute_pair_t operator =(T value) const {\n return std::make_pair(name(), traits<T>::pack(value));\n }\n\n filter_t operator >=(T value) const {\n return action_t<helper::LessEqThan>({ value });\n }\n\n filter_t operator ==(T value) const {\n return action_t<helper::Eq>({ value });\n }\n\n template<typename Action>\n struct action_t {\n T value;\n\n bool operator()(const log::attributes_t& attributes) const {\n return Action::execute(value, traits<T>::extract(attributes, name()));\n }\n };\n};\n\nnamespace tag {\n\nstruct severity_t {\n static const char* name() { return \"severity\"; }\n};\n\n} \/\/ namespace tag\n\ntemplate<typename T>\nstatic keyword_t<T, tag::severity_t>& severity() {\n static keyword_t<T, tag::severity_t> self;\n return self;\n}\n\n#define DECLARE_KEYWORD(Name, T) \\\n namespace tag { \\\n struct Name##_t { \\\n static const char* name() { return #Name; } \\\n }; \\\n } \\\n static keyword_t<T, tag::Name##_t>& Name() { \\\n static keyword_t<T, tag::Name##_t> self; \\\n return self; \\\n }\n\nDECLARE_KEYWORD(timestamp_id, std::time_t)\n\n} \/\/ namespace keyword\n\nclass logger_base_t {\n bool m_enabled;\n\nprotected:\n filter_t m_filter;\n std::unique_ptr<base_frontend_t> m_frontend;\n log::attributes_t m_global_attributes;\n\npublic:\n logger_base_t() :\n m_enabled(true),\n m_filter(default_filter_t::instance())\n {}\n\n bool enabled() const {\n return m_enabled;\n }\n\n void enable() {\n m_enabled = true;\n }\n\n void disable() {\n m_enabled = false;\n }\n\n void set_filter(filter_t&& filter) {\n m_filter = filter;\n }\n\n void add_attribute(const log::attribute_pair_t& attr) {\n m_global_attributes.insert(attr);\n }\n\n void add_frontend(std::unique_ptr<base_frontend_t> frontend) {\n m_frontend = std::move(frontend);\n }\n\n log::record_t open_record() const {\n return open_record(log::attributes_t());\n }\n\n log::record_t open_record(log::attributes_t&& local_attributes) const {\n if (enabled()) {\n log::attributes_t attributes = merge({\n \/\/ universe_attributes \/\/ Program global.\n \/\/ thread_attributes \/\/ Thread local.\n m_global_attributes, \/\/ Logger object specific.\n std::move(get_scoped_attributes()), \/\/ Depending on event scope, e.g. timestamp.\n std::move(local_attributes) \/\/ Any user attributes.\n });\n\n if (m_filter(attributes)) {\n log::record_t record;\n record.attributes = std::move(attributes);\n return record;\n }\n }\n\n return log::record_t();\n }\n\n void push(log::record_t&& record) {\n m_frontend->handle(std::move(record));\n }\n\nprivate:\n log::attributes_t get_scoped_attributes() const {\n log::attributes_t attributes;\n attributes[\"timestamp_id\"] = std::time(nullptr);\n return attributes;\n }\n};\n\ntemplate<typename Level>\nclass verbose_logger_t : public logger_base_t {\n typedef typename std::underlying_type<Level>::type level_type;\n\npublic:\n log::record_t open_record(Level level) const {\n return logger_base_t::open_record({ keyword::severity<Level>() = level }); \/\/!@todo: Неправильно, нужно во-первых уметь генерировать мапу аттрибутов из вариадика, а во-вторых - оставлять operator= для создания одного аттрибута!\n }\n};\n\nTEST(logger_base_t, CanBeEnabled) {\n logger_base_t log;\n log.enable();\n EXPECT_TRUE(log.enabled());\n}\n\nTEST(logger_base_t, CanBeDisabled) {\n logger_base_t log;\n log.disable();\n EXPECT_FALSE(log.enabled());\n}\n\nTEST(logger_base_t, EnabledByDefault) {\n logger_base_t log;\n EXPECT_TRUE(log.enabled());\n}\n\nTEST(logger_base_t, OpenRecordByDefault) {\n logger_base_t log;\n EXPECT_TRUE(log.open_record().valid());\n}\n\nTEST(logger_base_t, DoNotOpenRecordIfDisabled) {\n logger_base_t log;\n log.disable();\n EXPECT_FALSE(log.open_record().valid());\n}\n\nTEST(verbose_logger_t, Class) {\n enum level : std::uint64_t { debug, info, warn, error };\n verbose_logger_t<level> log;\n UNUSED(log);\n}\n\nTEST(verbose_logger_t, OpenRecordByDefault) {\n enum level : std::uint64_t { debug, info, warn, error };\n verbose_logger_t<level> log;\n log::record_t record = log.open_record(level::debug);\n EXPECT_TRUE(record.valid());\n}\n\nTEST(verbose_logger_t, OpenRecordForValidVerbosityLevel) {\n enum class level : std::uint64_t { debug, info, warn, error };\n verbose_logger_t<level> log;\n log.set_filter(keyword::severity<level>() >= level::info);\n EXPECT_FALSE(log.open_record(level::debug).valid());\n EXPECT_TRUE(log.open_record(level::info).valid());\n EXPECT_TRUE(log.open_record(level::warn).valid());\n EXPECT_TRUE(log.open_record(level::error).valid());\n}\n\nnamespace keyword { DECLARE_KEYWORD(urgent, std::uint8_t) }\n\nTEST(logger_base_t, OpensRecordWhenAttributeFilterSucceeded) {\n logger_base_t log;\n log.set_filter(expr::has_attr(keyword::urgent()));\n log.add_attribute(keyword::urgent() = 1);\n EXPECT_TRUE(log.open_record().valid());\n}\n\nTEST(logger_base_t, DoNotOpenRecordWhenAttributeFilterFailed) {\n logger_base_t log;\n log.set_filter(expr::has_attr(keyword::urgent()));\n EXPECT_FALSE(log.open_record().valid());\n}\n\n\n\/\/TEST(logger_base_t, ComplexFilter) {\n\/\/ logger_base_t log;\n\/\/ log.set_filter(expr::has_attr(keyword::urgent()));\/\/ && keyword::urgent() == 1);\n\/\/ log.set_attribute(keyword::urgent() = 1);\n\/\/ EXPECT_FALSE(log.open_record());\n\/\/}\n\n\/\/ Allow to make custom filters. severity() >= warning || has_tag(urgent()) && urgent() == 1\n\/\/ bool(attr) || bool(attr) && bool(attr)\n\nTEST(verbose_logger_t, Manual) {\n enum level : std::uint64_t { debug, info, warn, error };\n verbose_logger_t<level> log;\n\n \/\/!@note: Factory starts here...\n auto formatter = std::make_unique<formatter::string_t>(\"[]: %(message)s\");\n auto sink = std::make_unique<sink::file_t<>>(\"\/dev\/stdout\");\n auto frontend = std::make_unique<frontend_t<formatter::string_t, sink::file_t<>>>(std::move(formatter), std::move(sink));\n \/\/!@note ... till here.\n log.add_frontend(std::move(frontend));\n\n \/\/!@note: Next lines can be hided via macro: LOG(log, debug, \"Message %s\", \"Hell\", keyword::answer = 42);\n log::record_t record = log.open_record(level::error);\n if (record.valid()) {\n record.attributes[\"message\"] = utils::format(\"Some message from: '%s'!\", \"Hell\");\n \/\/ Add another attributes.\n log.push(std::move(record));\n }\n}\n<commit_msg>Complex filtering has been improved.<commit_after>#include \"Mocks.hpp\"\n\n#include <ctime>\n\nusing namespace blackhole;\n\nclass base_frontend_t {\npublic:\n virtual void handle(log::record_t&& record) = 0;\n};\n\ntemplate<class Formatter, class Sink>\nclass frontend_t : public base_frontend_t {\n const std::unique_ptr<Formatter> m_formatter;\n const std::unique_ptr<Sink> m_sink;\npublic:\n frontend_t(std::unique_ptr<Formatter> formatter, std::unique_ptr<Sink> sink) :\n m_formatter(std::move(formatter)),\n m_sink(std::move(sink))\n {}\n\n void handle(log::record_t&& record) {\n auto msg = std::move(m_formatter->format(record));\n m_sink->consume(msg);\n }\n};\n\ntypedef std::function<bool(const log::attributes_t& attributes)> filter_t;\n\nstruct default_filter_t {\n static default_filter_t& instance() {\n static default_filter_t filter;\n return filter;\n }\n\n bool operator()(const log::attributes_t&) {\n return true;\n }\n\nprivate:\n default_filter_t() {}\n};\n\nnamespace helper {\n\nstruct LessEqThan {\n template<typename L, typename R>\n static bool execute(const L& left, const R& right) {\n return left <= right;\n }\n};\n\nstruct Eq {\n template<typename L, typename R>\n static bool execute(const L& left, const R& right) {\n return left == right;\n }\n};\n\n} \/\/ namespace helper\n\nlog::attributes_t merge(const std::initializer_list<log::attributes_t>& args) {\n log::attributes_t summary;\n for (auto it = args.begin(); it != args.end(); ++it) {\n summary.insert(it->begin(), it->end());\n }\n\n return summary;\n}\n\nnamespace expr {\n\nstruct And {\n filter_t first;\n filter_t second;\n\n bool operator ()(const log::attributes_t& attributes) const {\n return first(attributes) && second(attributes);\n }\n};\n\ntemplate<typename T>\nstruct has_attr_action_t {\n bool operator()(const log::attributes_t& attributes) const {\n return attributes.find(T::name()) != attributes.end();\n }\n\n filter_t operator &&(filter_t other) const {\n return And { *this, other };\n }\n};\n\ntemplate<typename T>\nhas_attr_action_t<T> has_attr(const T&) {\n return has_attr_action_t<T>();\n}\n\n} \/\/ namespace expr\n\nnamespace keyword {\n\ntemplate<typename T, class = void>\nstruct traits {\n static inline void pack(log::attributes_t& attributes, const std::string& name, const T& value) {\n attributes[name] = value;\n }\n\n static inline T pack(const T& value) {\n return value;\n }\n\n static inline T extract(const log::attributes_t& attributes, const std::string& name) {\n return boost::get<T>(attributes.at(name));\n }\n};\n\ntemplate<typename T>\nstruct traits<T, typename std::enable_if<std::is_enum<T>::value>::type> {\n typedef typename std::underlying_type<T>::type underlying_type;\n\n static inline void pack(log::attributes_t& attributes, const std::string& name, const T& value) {\n attributes[name] = static_cast<underlying_type>(value);\n }\n\n static inline underlying_type pack(const T& value) {\n return static_cast<underlying_type>(value);\n }\n\n static inline T extract(const log::attributes_t& attributes, const std::string& name) {\n return static_cast<T>(boost::get<underlying_type>(attributes.at(name)));\n }\n};\n\n\/\/!@todo: Need testing.\ntemplate<typename T, typename NameProvider>\nstruct keyword_t {\n static const char* name() {\n return NameProvider::name();\n }\n\n log::attribute_pair_t operator =(T value) const {\n return std::make_pair(name(), traits<T>::pack(value));\n }\n\n filter_t operator >=(T value) const {\n return action_t<helper::LessEqThan>({ value });\n }\n\n filter_t operator ==(T value) const {\n return action_t<helper::Eq>({ value });\n }\n\n template<typename Action>\n struct action_t {\n T value;\n\n bool operator()(const log::attributes_t& attributes) const {\n return Action::execute(value, traits<T>::extract(attributes, name()));\n }\n };\n};\n\nnamespace tag {\n\nstruct severity_t {\n static const char* name() { return \"severity\"; }\n};\n\n} \/\/ namespace tag\n\ntemplate<typename T>\nstatic keyword_t<T, tag::severity_t>& severity() {\n static keyword_t<T, tag::severity_t> self;\n return self;\n}\n\n#define DECLARE_KEYWORD(Name, T) \\\n namespace tag { \\\n struct Name##_t { \\\n static const char* name() { return #Name; } \\\n }; \\\n } \\\n static keyword_t<T, tag::Name##_t>& Name() { \\\n static keyword_t<T, tag::Name##_t> self; \\\n return self; \\\n }\n\nDECLARE_KEYWORD(timestamp_id, std::time_t)\n\n} \/\/ namespace keyword\n\nclass logger_base_t {\n bool m_enabled;\n\nprotected:\n filter_t m_filter;\n std::unique_ptr<base_frontend_t> m_frontend;\n log::attributes_t m_global_attributes;\n\npublic:\n logger_base_t() :\n m_enabled(true),\n m_filter(default_filter_t::instance())\n {}\n\n bool enabled() const {\n return m_enabled;\n }\n\n void enable() {\n m_enabled = true;\n }\n\n void disable() {\n m_enabled = false;\n }\n\n void set_filter(filter_t&& filter) {\n m_filter = filter;\n }\n\n void add_attribute(const log::attribute_pair_t& attr) {\n m_global_attributes.insert(attr);\n }\n\n void add_frontend(std::unique_ptr<base_frontend_t> frontend) {\n m_frontend = std::move(frontend);\n }\n\n log::record_t open_record() const {\n return open_record(log::attributes_t());\n }\n\n log::record_t open_record(log::attributes_t&& local_attributes) const {\n if (enabled()) {\n log::attributes_t attributes = merge({\n \/\/ universe_attributes \/\/ Program global.\n \/\/ thread_attributes \/\/ Thread local.\n m_global_attributes, \/\/ Logger object specific.\n std::move(get_scoped_attributes()), \/\/ Depending on event scope, e.g. timestamp.\n std::move(local_attributes) \/\/ Any user attributes.\n });\n\n if (m_filter(attributes)) {\n log::record_t record;\n record.attributes = std::move(attributes);\n return record;\n }\n }\n\n return log::record_t();\n }\n\n void push(log::record_t&& record) {\n m_frontend->handle(std::move(record));\n }\n\nprivate:\n log::attributes_t get_scoped_attributes() const {\n log::attributes_t attributes;\n attributes[\"timestamp_id\"] = std::time(nullptr);\n return attributes;\n }\n};\n\ntemplate<typename Level>\nclass verbose_logger_t : public logger_base_t {\n typedef typename std::underlying_type<Level>::type level_type;\n\npublic:\n log::record_t open_record(Level level) const {\n return logger_base_t::open_record({ keyword::severity<Level>() = level }); \/\/!@todo: Неправильно, нужно во-первых уметь генерировать мапу аттрибутов из вариадика, а во-вторых - оставлять operator= для создания одного аттрибута!\n }\n};\n\nTEST(logger_base_t, CanBeEnabled) {\n logger_base_t log;\n log.enable();\n EXPECT_TRUE(log.enabled());\n}\n\nTEST(logger_base_t, CanBeDisabled) {\n logger_base_t log;\n log.disable();\n EXPECT_FALSE(log.enabled());\n}\n\nTEST(logger_base_t, EnabledByDefault) {\n logger_base_t log;\n EXPECT_TRUE(log.enabled());\n}\n\nTEST(logger_base_t, OpenRecordByDefault) {\n logger_base_t log;\n EXPECT_TRUE(log.open_record().valid());\n}\n\nTEST(logger_base_t, DoNotOpenRecordIfDisabled) {\n logger_base_t log;\n log.disable();\n EXPECT_FALSE(log.open_record().valid());\n}\n\nTEST(verbose_logger_t, Class) {\n enum level : std::uint64_t { debug, info, warn, error };\n verbose_logger_t<level> log;\n UNUSED(log);\n}\n\nTEST(verbose_logger_t, OpenRecordByDefault) {\n enum level : std::uint64_t { debug, info, warn, error };\n verbose_logger_t<level> log;\n log::record_t record = log.open_record(level::debug);\n EXPECT_TRUE(record.valid());\n}\n\nTEST(verbose_logger_t, OpenRecordForValidVerbosityLevel) {\n enum class level : std::uint64_t { debug, info, warn, error };\n verbose_logger_t<level> log;\n log.set_filter(keyword::severity<level>() >= level::info);\n EXPECT_FALSE(log.open_record(level::debug).valid());\n EXPECT_TRUE(log.open_record(level::info).valid());\n EXPECT_TRUE(log.open_record(level::warn).valid());\n EXPECT_TRUE(log.open_record(level::error).valid());\n}\n\nnamespace keyword { DECLARE_KEYWORD(urgent, std::uint8_t) }\n\nTEST(logger_base_t, OpensRecordWhenAttributeFilterSucceed) {\n logger_base_t log;\n log.set_filter(expr::has_attr(keyword::urgent()));\n log.add_attribute(keyword::urgent() = 1);\n EXPECT_TRUE(log.open_record().valid());\n}\n\nTEST(logger_base_t, DoNotOpenRecordWhenAttributeFilterFailed) {\n logger_base_t log;\n log.set_filter(expr::has_attr(keyword::urgent()));\n EXPECT_FALSE(log.open_record().valid());\n}\n\nTEST(logger_base_t, OpenRecordWhenComplexFilterSucceed) {\n logger_base_t log;\n log.set_filter(expr::has_attr(keyword::urgent()) && keyword::urgent() == 1);\n log.add_attribute(keyword::urgent() = 1);\n EXPECT_TRUE(log.open_record().valid());\n}\n\nTEST(logger_base_t, DoNotOpenRecordWhenComplexFilterFailed) {\n logger_base_t log;\n log.set_filter(expr::has_attr(keyword::urgent()) && keyword::urgent() == 1);\n log.add_attribute(keyword::urgent() = 2);\n EXPECT_FALSE(log.open_record().valid());\n}\n\n\/\/ Allow to make custom filters. severity() >= warning || has_tag(urgent()) && urgent() == 1\n\/\/ bool(attr) || bool(attr) && bool(attr)\n\nTEST(verbose_logger_t, Manual) {\n enum level : std::uint64_t { debug, info, warn, error };\n verbose_logger_t<level> log;\n\n \/\/!@note: Factory starts here...\n auto formatter = std::make_unique<formatter::string_t>(\"[]: %(message)s\");\n auto sink = std::make_unique<sink::file_t<>>(\"\/dev\/stdout\");\n auto frontend = std::make_unique<frontend_t<formatter::string_t, sink::file_t<>>>(std::move(formatter), std::move(sink));\n \/\/!@note ... till here.\n log.add_frontend(std::move(frontend));\n\n \/\/!@note: Next lines can be hided via macro: LOG(log, debug, \"Message %s\", \"Hell\", keyword::answer = 42);\n log::record_t record = log.open_record(level::error);\n if (record.valid()) {\n record.attributes[\"message\"] = utils::format(\"Some message from: '%s'!\", \"Hell\");\n \/\/ Add another attributes.\n log.push(std::move(record));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"audio\/audio.hpp\"\n#include \"main\/main.hpp\"\n#include \"world\/world.hpp\"\n#include \"graphics\/graphics.hpp\"\n\nnamespace Polarity {\n\nAudioFile *audioTest;\nAudioChannelPlayer *audioPlayer;\n\nbool loaded = false;\n\nvoid loadAssets() {\n test_image = loadImage(\"assets\/helloworld.png\");\n audioPlayer = new AudioChannelPlayer(16);\n if (audioPlayer->addChannel(\"white\", \"assets\/audio\/frozen_star.mp3\", 0) != AudioFileError::OK) {\n std::cerr << \"Couldn't load white track\" << std::endl;\n }\n if (audioPlayer->addChannel(\"black\", \"assets\/audio\/lightless_dawn.mp3\", 1) != AudioFileError::OK) {\n std::cerr << \"Couldn't load black track\" << std::endl;\n }\n}\n\nbool loopIter(SDL_Surface *screen) {\n SDL_Event event;\n std::vector<int> keyUps;\n while (SDL_PollEvent(&event)) {\n if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {\n if (event.type == SDL_KEYDOWN) {\n\t world->keyEvent(event.key.keysym.sym, true);\n\t} else {\n\t keyUps.push_back(event.key.keysym.sym);\n\t}\n if (event.key.keysym.sym == SDLK_SPACE) {\n audioPlayer->playChannel(\"white\");\n audioPlayer->playChannel(\"black\");\n } else if (event.key.keysym.sym == SDLK_ESCAPE) {\n audioPlayer->stopChannel(\"white\");\n audioPlayer->stopChannel(\"black\");\n } else if (event.key.keysym.sym == SDLK_w) {\n audioPlayer->setChannelVolume(\"white\", 1.0);\n audioPlayer->setChannelVolume(\"black\", 0.0);\n } else if (event.key.keysym.sym == SDLK_b) {\n audioPlayer->setChannelVolume(\"white\", 0.0);\n audioPlayer->setChannelVolume(\"black\", 1.0);\n }\n }\n }\n world->tick();\n \/\/ all key up have to happen after key downs so we get a full tick of downs\n for (auto &key : keyUps) {\n world->keyEvent(key, false);\n }\n return true;\n}\n}\n<commit_msg>fix build error<commit_after>#include \"audio\/audio.hpp\"\n#include \"main\/main.hpp\"\n#include \"world\/world.hpp\"\n#include \"graphics\/graphics.hpp\"\n\nnamespace Polarity {\n\nAudioFile *audioTest;\nAudioChannelPlayer *audioPlayer;\n\nbool loaded = false;\n\nvoid loadAssets() {\n audioPlayer = new AudioChannelPlayer(16);\n if (audioPlayer->addChannel(\"white\", \"assets\/audio\/frozen_star.mp3\", 0) != AudioFileError::OK) {\n std::cerr << \"Couldn't load white track\" << std::endl;\n }\n if (audioPlayer->addChannel(\"black\", \"assets\/audio\/lightless_dawn.mp3\", 1) != AudioFileError::OK) {\n std::cerr << \"Couldn't load black track\" << std::endl;\n }\n}\n\nbool loopIter(SDL_Surface *screen) {\n SDL_Event event;\n std::vector<int> keyUps;\n while (SDL_PollEvent(&event)) {\n if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {\n if (event.type == SDL_KEYDOWN) {\n\t world->keyEvent(event.key.keysym.sym, true);\n\t} else {\n\t keyUps.push_back(event.key.keysym.sym);\n\t}\n if (event.key.keysym.sym == SDLK_SPACE) {\n audioPlayer->playChannel(\"white\");\n audioPlayer->playChannel(\"black\");\n } else if (event.key.keysym.sym == SDLK_ESCAPE) {\n audioPlayer->stopChannel(\"white\");\n audioPlayer->stopChannel(\"black\");\n } else if (event.key.keysym.sym == SDLK_w) {\n audioPlayer->setChannelVolume(\"white\", 1.0);\n audioPlayer->setChannelVolume(\"black\", 0.0);\n } else if (event.key.keysym.sym == SDLK_b) {\n audioPlayer->setChannelVolume(\"white\", 0.0);\n audioPlayer->setChannelVolume(\"black\", 1.0);\n }\n }\n }\n world->tick();\n \/\/ all key up have to happen after key downs so we get a full tick of downs\n for (auto &key : keyUps) {\n world->keyEvent(key, false);\n }\n return true;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"Configuration.h\"\n#include \"Extensions.h\"\n#include \"ObjectsActivator.h\"\n#include \"PassiveLProcessor.h\"\n\n\/\/ -----------------------------------------------------------------------------\nusing namespace std;\nusing namespace UniSetTypes;\nusing namespace UniSetExtensions;\n\/\/ -----------------------------------------------------------------------------\nint main(int argc, const char **argv)\n{\n\ttry\n\t{\n\t\tstring confile=UniSetTypes::getArgParam(\"--confile\",argc,argv,\"configure.xml\");\n\t\tconf = new Configuration( argc, argv, confile );\n\n\t\tstring logfilename(conf->getArgParam(\"--logicproc-logfile\"));\n\t\tif( logfilename.empty() )\n\t\t\tlogfilename = \"logicproc.log\";\n\t\n\t\tconf->initDebug(dlog,\"dlog\");\n\t\n\t\tstd::ostringstream logname;\n\t\tstring dir(conf->getLogDir());\n\t\tlogname << dir << logfilename;\n\t\tunideb.logFile( logname.str().c_str() );\n\t\tdlog.logFile( logname.str().c_str() );\n\n\t\tstring schema = conf->getArgParam(\"--schema\");\n\t\tif( schema.empty() )\n\t\t{\n\t\t\tcerr << \"schema-file not defined. Use --schema\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tObjectId shmID = DefaultObjectId;\n\t\tstring sID = conf->getArgParam(\"--smemory-id\");\n\t\tif( !sID.empty() )\n\t\t\tshmID = conf->getControllerID(sID);\n\t\telse\n\t\t\tshmID = getSharedMemoryID();\n\n\t\tif( shmID == DefaultObjectId )\n\t\t{\n\t\t\tcerr << sID << \"? SharedMemoryID not found in \" << conf->getControllersSection() << \" section\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tcout << \"init smemory: \" << sID << \" ID: \" << shmID << endl; \n\t\t\n\t\tstring name = conf->getArgParam(\"--name\",\"LProcessor\");\n\t\tif( name.empty() )\n\t\t{\n\t\t\tcerr << \"(plogicproc): name'\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tObjectId ID = conf->getObjectID(name);\n\t\tif( ID == UniSetTypes::DefaultObjectId )\n\t\t{\n\t\t\tcerr << \"(plogicproc): '\" << name \n\t\t\t\t<< \"' . !\"\n\t\t\t\t<< \" \" << conf->getObjectsSection() << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tcout << \"init name: \" << name << \" ID: \" << ID << endl; \n\n\t\tPassiveLProcessor plc(schema,ID,shmID);\n\n\t\tObjectsActivator act;\n\t\tact.addObject(static_cast<class UniSetObject*>(&plc));\n\n\t\tSystemMessage sm(SystemMessage::StartUp); \n\t\tact.broadcast( sm.transport_msg() );\n\n\t\tunideb(Debug::ANY) << \"\\n\\n\\n\";\n\t\tunideb[Debug::ANY] << \"(main): -------------- IOControl START -------------------------\\n\\n\";\n\t\tdlog(Debug::ANY) << \"\\n\\n\\n\";\n\t\tdlog[Debug::ANY] << \"(main): -------------- IOControl START -------------------------\\n\\n\";\n\t\tact.run(false);\n\t\tpause();\n\t}\n\tcatch( LogicException& ex )\n\t{\n\t\tcerr << ex << endl;\n\t}\n\tcatch( Exception& ex )\n\t{\n\t\tcerr << ex << endl;\n\t}\n\tcatch( ... )\n\t{\n\t\tcerr << \" catch ... \" << endl;\n\t}\n\t\n\treturn 0;\n}\n\/\/ -----------------------------------------------------------------------------\n<commit_msg>use updated logFile<commit_after>#include <iostream>\n#include \"Configuration.h\"\n#include \"Extensions.h\"\n#include \"ObjectsActivator.h\"\n#include \"PassiveLProcessor.h\"\n\n\/\/ -----------------------------------------------------------------------------\nusing namespace std;\nusing namespace UniSetTypes;\nusing namespace UniSetExtensions;\n\/\/ -----------------------------------------------------------------------------\nint main(int argc, const char **argv)\n{\n\ttry\n\t{\n\t\tstring confile=UniSetTypes::getArgParam(\"--confile\",argc,argv,\"configure.xml\");\n\t\tconf = new Configuration( argc, argv, confile );\n\n\t\tstring logfilename(conf->getArgParam(\"--logicproc-logfile\"));\n\t\tif( logfilename.empty() )\n\t\t\tlogfilename = \"logicproc.log\";\n\t\n\t\tconf->initDebug(dlog,\"dlog\");\n\t\n\t\tstd::ostringstream logname;\n\t\tstring dir(conf->getLogDir());\n\t\tlogname << dir << logfilename;\n\t\tunideb.logFile( logname.str() );\n\t\tdlog.logFile( logname.str() );\n\n\t\tstring schema = conf->getArgParam(\"--schema\");\n\t\tif( schema.empty() )\n\t\t{\n\t\t\tcerr << \"schema-file not defined. Use --schema\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tObjectId shmID = DefaultObjectId;\n\t\tstring sID = conf->getArgParam(\"--smemory-id\");\n\t\tif( !sID.empty() )\n\t\t\tshmID = conf->getControllerID(sID);\n\t\telse\n\t\t\tshmID = getSharedMemoryID();\n\n\t\tif( shmID == DefaultObjectId )\n\t\t{\n\t\t\tcerr << sID << \"? SharedMemoryID not found in \" << conf->getControllersSection() << \" section\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tcout << \"init smemory: \" << sID << \" ID: \" << shmID << endl; \n\t\t\n\t\tstring name = conf->getArgParam(\"--name\",\"LProcessor\");\n\t\tif( name.empty() )\n\t\t{\n\t\t\tcerr << \"(plogicproc): name'\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tObjectId ID = conf->getObjectID(name);\n\t\tif( ID == UniSetTypes::DefaultObjectId )\n\t\t{\n\t\t\tcerr << \"(plogicproc): '\" << name \n\t\t\t\t<< \"' . !\"\n\t\t\t\t<< \" \" << conf->getObjectsSection() << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tcout << \"init name: \" << name << \" ID: \" << ID << endl; \n\n\t\tPassiveLProcessor plc(schema,ID,shmID);\n\n\t\tObjectsActivator act;\n\t\tact.addObject(static_cast<class UniSetObject*>(&plc));\n\n\t\tSystemMessage sm(SystemMessage::StartUp); \n\t\tact.broadcast( sm.transport_msg() );\n\n\t\tunideb(Debug::ANY) << \"\\n\\n\\n\";\n\t\tunideb[Debug::ANY] << \"(main): -------------- IOControl START -------------------------\\n\\n\";\n\t\tdlog(Debug::ANY) << \"\\n\\n\\n\";\n\t\tdlog[Debug::ANY] << \"(main): -------------- IOControl START -------------------------\\n\\n\";\n\t\tact.run(false);\n\t\tpause();\n\t}\n\tcatch( LogicException& ex )\n\t{\n\t\tcerr << ex << endl;\n\t}\n\tcatch( Exception& ex )\n\t{\n\t\tcerr << ex << endl;\n\t}\n\tcatch( ... )\n\t{\n\t\tcerr << \" catch ... \" << endl;\n\t}\n\t\n\treturn 0;\n}\n\/\/ -----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Disa Mhembere (disa)\n *\n * This file is part of FlashGraph.\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#include <stdlib.h>\n#include \"matrix\/kmeans_thread.h\"\n#include \"matrix\/kmeans_thread.cpp\"\n#include \"libgraph-algs\/sem_kmeans_util.h\"\n\nvoid test_thread_creation(const unsigned NTHREADS, const unsigned nnodes) {\n std::vector<kmeans_thread::ptr> thds;\n\n \/\/ Always: Build state alone\n for (unsigned i = 0; i < NTHREADS; i++)\n thds.push_back(kmeans_thread::create\n (i%nnodes, i, 69, 200, 2, nullptr, NULL, \"\/dev\/null\"));\n\n \/\/ Always: Start threads alone\n for (unsigned i = 0; i < NTHREADS; i++)\n thds[i]->start(TEST);\n\n unsigned sum = 0;\n unsigned verification = 0;\n for (unsigned i = 0; i < thds.size(); i++) {\n thds[i]->join();\n sum += thds[i]->get_val(); \/\/ OK to do together\n verification += i;\n }\n BOOST_VERIFY(sum == verification);\n std::cout << \"SUCCESS: The sum is: \" << sum << \"\\n\";\n}\n\nvoid test_numa_populate_data() {\n constexpr unsigned NTHREADS = 10;\n constexpr unsigned nnodes = 4;\n constexpr unsigned nrow = 50;\n const unsigned nprocrows = nrow\/NTHREADS;\n constexpr unsigned ncol = 5;\n const std::string fn = \"\/mnt\/nfs\/disa\/data\/tiny\/matrix_r50_c5_rrw.bin\";\n\n std::vector<kmeans_thread::ptr> thds;\n\n \/\/ Always: Build state alone\n for (unsigned i = 0; i < NTHREADS; i++)\n thds.push_back(kmeans_thread::create\n (i%nnodes, i, i*nprocrows*ncol, nprocrows, ncol, nullptr, NULL, fn));\n\n bin_reader<double> br(fn, nrow, ncol);\n double* data = new double [nrow*ncol];\n printf(\"Bin read data\\n\");\n br.read(data);\n\n \/\/ Allocate & move\n std::vector<kmeans_thread::ptr>::iterator it = thds.begin();\n for (; it != thds.end(); ++it)\n (*it)->start(ALLOC_DATA);\n\n for (it = thds.begin(); it != thds.end(); ++it)\n (*it)->join();\n\n \/\/ Print it back\n for (it = thds.begin(); it != thds.end(); ++it) {\n double *dp = &data[(*it)->get_thd_id()*ncol*nprocrows];\n BOOST_VERIFY(eq_all(dp, (*it)->get_local_data(), nprocrows*ncol));\n printf(\"Thread %u PASSED numa_mem_alloc()\\n\", (*it)->get_thd_id());\n }\n delete [] data;\n}\n\nint main(int argc, char* argv[]) {\n\n if (argc < 2) {\n fprintf(stderr, \"usage: .\/test_kmeans_thread nthreads nnodes\\n\");\n exit(EXIT_FAILURE);\n }\n\n test_thread_creation(atoi(argv[1]), atoi(argv[2]));\n test_numa_populate_data();\n\n return (EXIT_SUCCESS);\n}\n<commit_msg>[Test]: Added dummy clusters obj & assertion if KM_TEST not defined<commit_after>\/**\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Disa Mhembere (disa)\n *\n * This file is part of FlashGraph.\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#include <stdlib.h>\n#include \"matrix\/kmeans_thread.h\"\n#include \"matrix\/kmeans_thread.cpp\"\n#include \"libgraph-algs\/sem_kmeans_util.h\"\n\nvoid test_thread_creation(const unsigned NTHREADS, const unsigned nnodes) {\n std::vector<kmeans_thread::ptr> thds;\n\n \/\/ Always: Build state alone\n for (unsigned i = 0; i < NTHREADS; i++) {\n clusters::ptr cl = clusters::create(2,2);\n thds.push_back(kmeans_thread::create\n (i%nnodes, i, 69, 200, 2, cl, NULL, \"\/dev\/null\"));\n }\n\n \/\/ Always: Start threads alone\n for (unsigned i = 0; i < NTHREADS; i++)\n thds[i]->start(TEST);\n\n unsigned sum = 0;\n unsigned verification = 0;\n for (unsigned i = 0; i < thds.size(); i++) {\n thds[i]->join();\n sum += thds[i]->get_val(); \/\/ OK to do together\n verification += i;\n }\n BOOST_VERIFY(sum == verification);\n std::cout << \"SUCCESS: The sum is: \" << sum << \"\\n\";\n}\n\nvoid test_numa_populate_data() {\n constexpr unsigned NTHREADS = 10;\n constexpr unsigned nnodes = 4;\n constexpr unsigned nrow = 50;\n const unsigned nprocrows = nrow\/NTHREADS;\n constexpr unsigned ncol = 5;\n const std::string fn = \"\/mnt\/nfs\/disa\/data\/tiny\/matrix_r50_c5_rrw.bin\";\n\n std::vector<kmeans_thread::ptr> thds;\n\n \/\/ Always: Build state alone\n for (unsigned i = 0; i < NTHREADS; i++) {\n clusters::ptr cl = clusters::create(2,2);\n thds.push_back(kmeans_thread::create\n (i%nnodes, i, i*nprocrows*ncol, nprocrows, ncol,\n cl, NULL, fn));\n }\n\n bin_reader<double> br(fn, nrow, ncol);\n double* data = new double [nrow*ncol];\n printf(\"Bin read data\\n\");\n br.read(data);\n\n \/\/ Allocate & move\n std::vector<kmeans_thread::ptr>::iterator it = thds.begin();\n for (; it != thds.end(); ++it)\n (*it)->start(ALLOC_DATA);\n\n for (it = thds.begin(); it != thds.end(); ++it)\n (*it)->join();\n\n \/\/ Print it back\n for (it = thds.begin(); it != thds.end(); ++it) {\n double *dp = &data[(*it)->get_thd_id()*ncol*nprocrows];\n BOOST_VERIFY(eq_all(dp, (*it)->get_local_data(), nprocrows*ncol));\n printf(\"Thread %u PASSED numa_mem_alloc()\\n\", (*it)->get_thd_id());\n }\n delete [] data;\n}\n\nint main(int argc, char* argv[]) {\n\n if (argc < 2) {\n fprintf(stderr, \"usage: .\/test_kmeans_thread nthreads nnodes\\n\");\n exit(EXIT_FAILURE);\n }\n\n#if KM_TEST\n test_thread_creation(atoi(argv[1]), atoi(argv[2]));\n#else\n printf(\"[FATAL]: Set KM_TEST 1 in kmeans.h\\n\");\n exit(EXIT_FAILURE);\n#endif\n test_numa_populate_data();\n\n return (EXIT_SUCCESS);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xeroot.cxx,v $\n *\n * $Revision: 1.22 $\n *\n * last change: $Author: vg $ $Date: 2007-10-23 14:44:34 $\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_sc.hxx\"\n\n#ifndef SC_XEROOT_HXX\n#include \"xeroot.hxx\"\n#endif\n\n#ifndef _SFXDOCFILE_HXX\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef INCLUDED_SVTOOLS_SAVEOPT_HXX\n#include <svtools\/saveopt.hxx>\n#endif\n\n#ifndef SC_XLTRACER_HXX\n#include \"xltracer.hxx\"\n#endif\n#ifndef SC_XEHELPER_HXX\n#include \"xehelper.hxx\"\n#endif\n#ifndef SC_XEFORMULA_HXX\n#include \"xeformula.hxx\"\n#endif\n#ifndef SC_XELINK_HXX\n#include \"xelink.hxx\"\n#endif\n#ifndef SC_XENAME_HXX\n#include \"xename.hxx\"\n#endif\n#ifndef SC_XESTYLE_HXX\n#include \"xestyle.hxx\"\n#endif\n#ifndef SC_XECONTENT_HXX\n#include \"xecontent.hxx\"\n#endif\n#ifndef SC_XEPIVOT_HXX\n#include \"xepivot.hxx\"\n#endif\n\n\/\/ for filter manager\n#include \"excrecds.hxx\"\n\n\/\/ Global data ================================================================\n\nXclExpRootData::XclExpRootData( XclBiff eBiff, SfxMedium& rMedium,\n SotStorageRef xRootStrg, ScDocument& rDoc, rtl_TextEncoding eTextEnc ) :\n XclRootData( eBiff, rMedium, xRootStrg, rDoc, eTextEnc, true )\n{\n SvtSaveOptions aSaveOpt;\n mbRelUrl = mrMedium.IsRemote() ? aSaveOpt.IsSaveRelINet() : aSaveOpt.IsSaveRelFSys();\n}\n\nXclExpRootData::~XclExpRootData()\n{\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nXclExpRoot::XclExpRoot( XclExpRootData& rExpRootData ) :\n XclRoot( rExpRootData ),\n mrExpData( rExpRootData )\n{\n}\n\nXclExpTabInfo& XclExpRoot::GetTabInfo() const\n{\n DBG_ASSERT( mrExpData.mxTabInfo.is(), \"XclExpRoot::GetTabInfo - missing object (wrong BIFF?)\" );\n return *mrExpData.mxTabInfo;\n}\n\nXclExpAddressConverter& XclExpRoot::GetAddressConverter() const\n{\n DBG_ASSERT( mrExpData.mxAddrConv.is(), \"XclExpRoot::GetAddressConverter - missing object (wrong BIFF?)\" );\n return *mrExpData.mxAddrConv;\n}\n\nXclExpFormulaCompiler& XclExpRoot::GetFormulaCompiler() const\n{\n DBG_ASSERT( mrExpData.mxFmlaComp.is(), \"XclExpRoot::GetFormulaCompiler - missing object (wrong BIFF?)\" );\n return *mrExpData.mxFmlaComp;\n}\n\nXclExpProgressBar& XclExpRoot::GetProgressBar() const\n{\n DBG_ASSERT( mrExpData.mxProgress.is(), \"XclExpRoot::GetProgressBar - missing object (wrong BIFF?)\" );\n return *mrExpData.mxProgress;\n}\n\nXclExpSst& XclExpRoot::GetSst() const\n{\n DBG_ASSERT( mrExpData.mxSst.is(), \"XclExpRoot::GetSst - missing object (wrong BIFF?)\" );\n return *mrExpData.mxSst;\n}\n\nXclExpPalette& XclExpRoot::GetPalette() const\n{\n DBG_ASSERT( mrExpData.mxPalette.is(), \"XclExpRoot::GetPalette - missing object (wrong BIFF?)\" );\n return *mrExpData.mxPalette;\n}\n\nXclExpFontBuffer& XclExpRoot::GetFontBuffer() const\n{\n DBG_ASSERT( mrExpData.mxFontBfr.is(), \"XclExpRoot::GetFontBuffer - missing object (wrong BIFF?)\" );\n return *mrExpData.mxFontBfr;\n}\n\nXclExpNumFmtBuffer& XclExpRoot::GetNumFmtBuffer() const\n{\n DBG_ASSERT( mrExpData.mxNumFmtBfr.is(), \"XclExpRoot::GetNumFmtBuffer - missing object (wrong BIFF?)\" );\n return *mrExpData.mxNumFmtBfr;\n}\n\nXclExpXFBuffer& XclExpRoot::GetXFBuffer() const\n{\n DBG_ASSERT( mrExpData.mxXFBfr.is(), \"XclExpRoot::GetXFBuffer - missing object (wrong BIFF?)\" );\n return *mrExpData.mxXFBfr;\n}\n\nXclExpLinkManager& XclExpRoot::GetGlobalLinkManager() const\n{\n DBG_ASSERT( mrExpData.mxGlobLinkMgr.is(), \"XclExpRoot::GetGlobalLinkManager - missing object (wrong BIFF?)\" );\n return *mrExpData.mxGlobLinkMgr;\n}\n\nXclExpLinkManager& XclExpRoot::GetLocalLinkManager() const\n{\n DBG_ASSERT( GetLocalLinkMgrRef().is(), \"XclExpRoot::GetLocalLinkManager - missing object (wrong BIFF?)\" );\n return *GetLocalLinkMgrRef();\n}\n\nXclExpNameManager& XclExpRoot::GetNameManager() const\n{\n DBG_ASSERT( mrExpData.mxNameMgr.is(), \"XclExpRoot::GetNameManager - missing object (wrong BIFF?)\" );\n return *mrExpData.mxNameMgr;\n}\n\nXclExpFilterManager& XclExpRoot::GetFilterManager() const\n{\n DBG_ASSERT( mrExpData.mxFilterMgr.is(), \"XclExpRoot::GetFilterManager - missing object (wrong BIFF?)\" );\n return *mrExpData.mxFilterMgr;\n}\n\nXclExpPivotTableManager& XclExpRoot::GetPivotTableManager() const\n{\n DBG_ASSERT( mrExpData.mxPTableMgr.is(), \"XclExpRoot::GetPivotTableManager - missing object (wrong BIFF?)\" );\n return *mrExpData.mxPTableMgr;\n}\n\nvoid XclExpRoot::InitializeConvert()\n{\n mrExpData.mxTabInfo.reset( new XclExpTabInfo( GetRoot() ) );\n mrExpData.mxAddrConv.reset( new XclExpAddressConverter( GetRoot() ) );\n mrExpData.mxFmlaComp.reset( new XclExpFormulaCompiler( GetRoot() ) );\n mrExpData.mxProgress.reset( new XclExpProgressBar( GetRoot() ) );\n\n GetProgressBar().Initialize();\n}\n\nvoid XclExpRoot::InitializeGlobals()\n{\n SetCurrScTab( SCTAB_GLOBAL );\n\n if( GetBiff() >= EXC_BIFF5 )\n {\n mrExpData.mxPalette.reset( new XclExpPalette( GetRoot() ) );\n mrExpData.mxFontBfr.reset( new XclExpFontBuffer( GetRoot() ) );\n mrExpData.mxNumFmtBfr.reset( new XclExpNumFmtBuffer( GetRoot() ) );\n mrExpData.mxXFBfr.reset( new XclExpXFBuffer( GetRoot() ) );\n mrExpData.mxGlobLinkMgr.reset( new XclExpLinkManager( GetRoot() ) );\n mrExpData.mxNameMgr.reset( new XclExpNameManager( GetRoot() ) );\n }\n\n if( GetBiff() == EXC_BIFF8 )\n {\n mrExpData.mxSst.reset( new XclExpSst );\n mrExpData.mxFilterMgr.reset( new XclExpFilterManager( GetRoot() ) );\n mrExpData.mxPTableMgr.reset( new XclExpPivotTableManager( GetRoot() ) );\n \/\/ BIFF8: only one link manager for all sheets\n mrExpData.mxLocLinkMgr = mrExpData.mxGlobLinkMgr;\n }\n\n GetXFBuffer().Initialize();\n GetNameManager().Initialize();\n}\n\nvoid XclExpRoot::InitializeTable( SCTAB nScTab )\n{\n SetCurrScTab( nScTab );\n if( GetBiff() == EXC_BIFF5 )\n {\n \/\/ local link manager per sheet\n mrExpData.mxLocLinkMgr.reset( new XclExpLinkManager( GetRoot() ) );\n }\n}\n\nvoid XclExpRoot::InitializeSave()\n{\n GetPalette().Finalize();\n GetXFBuffer().Finalize();\n}\n\nXclExpRecordRef XclExpRoot::CreateRecord( sal_uInt16 nRecId ) const\n{\n XclExpRecordRef xRec;\n switch( nRecId )\n {\n case EXC_ID_PALETTE: xRec = mrExpData.mxPalette; break;\n case EXC_ID_FONTLIST: xRec = mrExpData.mxFontBfr; break;\n case EXC_ID_FORMATLIST: xRec = mrExpData.mxNumFmtBfr; break;\n case EXC_ID_XFLIST: xRec = mrExpData.mxXFBfr; break;\n case EXC_ID_SST: xRec = mrExpData.mxSst; break;\n case EXC_ID_EXTERNSHEET: xRec = GetLocalLinkMgrRef(); break;\n case EXC_ID_NAME: xRec = mrExpData.mxNameMgr; break;\n }\n DBG_ASSERT( xRec.is(), \"XclExpRoot::CreateRecord - unknown record ID or missing object\" );\n return xRec;\n}\n\nXclExpRootData::XclExpLinkMgrRef XclExpRoot::GetLocalLinkMgrRef() const\n{\n return IsInGlobals() ? mrExpData.mxGlobLinkMgr : mrExpData.mxLocLinkMgr;\n}\n\n\/\/ ============================================================================\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.22.158); FILE MERGED 2008\/04\/01 15:30:08 thb 1.22.158.3: #i85898# Stripping all external header guards 2008\/04\/01 12:36:11 thb 1.22.158.2: #i85898# Stripping all external header guards 2008\/03\/31 17:14:31 rt 1.22.158.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: xeroot.cxx,v $\n * $Revision: 1.23 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_sc.hxx\"\n#include \"xeroot.hxx\"\n#include <sfx2\/docfile.hxx>\n#include <svtools\/saveopt.hxx>\n#include \"xltracer.hxx\"\n#include \"xehelper.hxx\"\n#include \"xeformula.hxx\"\n#include \"xelink.hxx\"\n#include \"xename.hxx\"\n#include \"xestyle.hxx\"\n#include \"xecontent.hxx\"\n#include \"xepivot.hxx\"\n\n\/\/ for filter manager\n#include \"excrecds.hxx\"\n\n\/\/ Global data ================================================================\n\nXclExpRootData::XclExpRootData( XclBiff eBiff, SfxMedium& rMedium,\n SotStorageRef xRootStrg, ScDocument& rDoc, rtl_TextEncoding eTextEnc ) :\n XclRootData( eBiff, rMedium, xRootStrg, rDoc, eTextEnc, true )\n{\n SvtSaveOptions aSaveOpt;\n mbRelUrl = mrMedium.IsRemote() ? aSaveOpt.IsSaveRelINet() : aSaveOpt.IsSaveRelFSys();\n}\n\nXclExpRootData::~XclExpRootData()\n{\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nXclExpRoot::XclExpRoot( XclExpRootData& rExpRootData ) :\n XclRoot( rExpRootData ),\n mrExpData( rExpRootData )\n{\n}\n\nXclExpTabInfo& XclExpRoot::GetTabInfo() const\n{\n DBG_ASSERT( mrExpData.mxTabInfo.is(), \"XclExpRoot::GetTabInfo - missing object (wrong BIFF?)\" );\n return *mrExpData.mxTabInfo;\n}\n\nXclExpAddressConverter& XclExpRoot::GetAddressConverter() const\n{\n DBG_ASSERT( mrExpData.mxAddrConv.is(), \"XclExpRoot::GetAddressConverter - missing object (wrong BIFF?)\" );\n return *mrExpData.mxAddrConv;\n}\n\nXclExpFormulaCompiler& XclExpRoot::GetFormulaCompiler() const\n{\n DBG_ASSERT( mrExpData.mxFmlaComp.is(), \"XclExpRoot::GetFormulaCompiler - missing object (wrong BIFF?)\" );\n return *mrExpData.mxFmlaComp;\n}\n\nXclExpProgressBar& XclExpRoot::GetProgressBar() const\n{\n DBG_ASSERT( mrExpData.mxProgress.is(), \"XclExpRoot::GetProgressBar - missing object (wrong BIFF?)\" );\n return *mrExpData.mxProgress;\n}\n\nXclExpSst& XclExpRoot::GetSst() const\n{\n DBG_ASSERT( mrExpData.mxSst.is(), \"XclExpRoot::GetSst - missing object (wrong BIFF?)\" );\n return *mrExpData.mxSst;\n}\n\nXclExpPalette& XclExpRoot::GetPalette() const\n{\n DBG_ASSERT( mrExpData.mxPalette.is(), \"XclExpRoot::GetPalette - missing object (wrong BIFF?)\" );\n return *mrExpData.mxPalette;\n}\n\nXclExpFontBuffer& XclExpRoot::GetFontBuffer() const\n{\n DBG_ASSERT( mrExpData.mxFontBfr.is(), \"XclExpRoot::GetFontBuffer - missing object (wrong BIFF?)\" );\n return *mrExpData.mxFontBfr;\n}\n\nXclExpNumFmtBuffer& XclExpRoot::GetNumFmtBuffer() const\n{\n DBG_ASSERT( mrExpData.mxNumFmtBfr.is(), \"XclExpRoot::GetNumFmtBuffer - missing object (wrong BIFF?)\" );\n return *mrExpData.mxNumFmtBfr;\n}\n\nXclExpXFBuffer& XclExpRoot::GetXFBuffer() const\n{\n DBG_ASSERT( mrExpData.mxXFBfr.is(), \"XclExpRoot::GetXFBuffer - missing object (wrong BIFF?)\" );\n return *mrExpData.mxXFBfr;\n}\n\nXclExpLinkManager& XclExpRoot::GetGlobalLinkManager() const\n{\n DBG_ASSERT( mrExpData.mxGlobLinkMgr.is(), \"XclExpRoot::GetGlobalLinkManager - missing object (wrong BIFF?)\" );\n return *mrExpData.mxGlobLinkMgr;\n}\n\nXclExpLinkManager& XclExpRoot::GetLocalLinkManager() const\n{\n DBG_ASSERT( GetLocalLinkMgrRef().is(), \"XclExpRoot::GetLocalLinkManager - missing object (wrong BIFF?)\" );\n return *GetLocalLinkMgrRef();\n}\n\nXclExpNameManager& XclExpRoot::GetNameManager() const\n{\n DBG_ASSERT( mrExpData.mxNameMgr.is(), \"XclExpRoot::GetNameManager - missing object (wrong BIFF?)\" );\n return *mrExpData.mxNameMgr;\n}\n\nXclExpFilterManager& XclExpRoot::GetFilterManager() const\n{\n DBG_ASSERT( mrExpData.mxFilterMgr.is(), \"XclExpRoot::GetFilterManager - missing object (wrong BIFF?)\" );\n return *mrExpData.mxFilterMgr;\n}\n\nXclExpPivotTableManager& XclExpRoot::GetPivotTableManager() const\n{\n DBG_ASSERT( mrExpData.mxPTableMgr.is(), \"XclExpRoot::GetPivotTableManager - missing object (wrong BIFF?)\" );\n return *mrExpData.mxPTableMgr;\n}\n\nvoid XclExpRoot::InitializeConvert()\n{\n mrExpData.mxTabInfo.reset( new XclExpTabInfo( GetRoot() ) );\n mrExpData.mxAddrConv.reset( new XclExpAddressConverter( GetRoot() ) );\n mrExpData.mxFmlaComp.reset( new XclExpFormulaCompiler( GetRoot() ) );\n mrExpData.mxProgress.reset( new XclExpProgressBar( GetRoot() ) );\n\n GetProgressBar().Initialize();\n}\n\nvoid XclExpRoot::InitializeGlobals()\n{\n SetCurrScTab( SCTAB_GLOBAL );\n\n if( GetBiff() >= EXC_BIFF5 )\n {\n mrExpData.mxPalette.reset( new XclExpPalette( GetRoot() ) );\n mrExpData.mxFontBfr.reset( new XclExpFontBuffer( GetRoot() ) );\n mrExpData.mxNumFmtBfr.reset( new XclExpNumFmtBuffer( GetRoot() ) );\n mrExpData.mxXFBfr.reset( new XclExpXFBuffer( GetRoot() ) );\n mrExpData.mxGlobLinkMgr.reset( new XclExpLinkManager( GetRoot() ) );\n mrExpData.mxNameMgr.reset( new XclExpNameManager( GetRoot() ) );\n }\n\n if( GetBiff() == EXC_BIFF8 )\n {\n mrExpData.mxSst.reset( new XclExpSst );\n mrExpData.mxFilterMgr.reset( new XclExpFilterManager( GetRoot() ) );\n mrExpData.mxPTableMgr.reset( new XclExpPivotTableManager( GetRoot() ) );\n \/\/ BIFF8: only one link manager for all sheets\n mrExpData.mxLocLinkMgr = mrExpData.mxGlobLinkMgr;\n }\n\n GetXFBuffer().Initialize();\n GetNameManager().Initialize();\n}\n\nvoid XclExpRoot::InitializeTable( SCTAB nScTab )\n{\n SetCurrScTab( nScTab );\n if( GetBiff() == EXC_BIFF5 )\n {\n \/\/ local link manager per sheet\n mrExpData.mxLocLinkMgr.reset( new XclExpLinkManager( GetRoot() ) );\n }\n}\n\nvoid XclExpRoot::InitializeSave()\n{\n GetPalette().Finalize();\n GetXFBuffer().Finalize();\n}\n\nXclExpRecordRef XclExpRoot::CreateRecord( sal_uInt16 nRecId ) const\n{\n XclExpRecordRef xRec;\n switch( nRecId )\n {\n case EXC_ID_PALETTE: xRec = mrExpData.mxPalette; break;\n case EXC_ID_FONTLIST: xRec = mrExpData.mxFontBfr; break;\n case EXC_ID_FORMATLIST: xRec = mrExpData.mxNumFmtBfr; break;\n case EXC_ID_XFLIST: xRec = mrExpData.mxXFBfr; break;\n case EXC_ID_SST: xRec = mrExpData.mxSst; break;\n case EXC_ID_EXTERNSHEET: xRec = GetLocalLinkMgrRef(); break;\n case EXC_ID_NAME: xRec = mrExpData.mxNameMgr; break;\n }\n DBG_ASSERT( xRec.is(), \"XclExpRoot::CreateRecord - unknown record ID or missing object\" );\n return xRec;\n}\n\nXclExpRootData::XclExpLinkMgrRef XclExpRoot::GetLocalLinkMgrRef() const\n{\n return IsInGlobals() ? mrExpData.mxGlobLinkMgr : mrExpData.mxLocLinkMgr;\n}\n\n\/\/ ============================================================================\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: xmlannoi.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 07:47:27 $\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#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include \"xmlannoi.hxx\"\n#include \"xmlimprt.hxx\"\n#include \"xmlcelli.hxx\"\n#ifndef SC_XMLCONTI_HXX\n#include \"xmlconti.hxx\"\n#endif\n\n#include <xmloff\/xmltkmap.hxx>\n#include <xmloff\/nmspmap.hxx>\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n\nusing namespace com::sun::star;\nusing namespace xmloff::token;\n\n\/\/------------------------------------------------------------------\n\nScXMLAnnotationContext::ScXMLAnnotationContext( ScXMLImport& rImport,\n USHORT nPrfx,\n const ::rtl::OUString& rLName,\n const uno::Reference<xml::sax::XAttributeList>& xAttrList,\n ScXMLTableRowCellContext* pTempCellContext) :\n SvXMLImportContext( rImport, nPrfx, rLName ),\n nParagraphCount(0),\n bDisplay(sal_False),\n bHasTextP(sal_False)\n{\n pCellContext = pTempCellContext;\n sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetTableAnnotationAttrTokenMap();\n for( sal_Int16 i=0; i < nAttrCount; i++ )\n {\n rtl::OUString sAttrName = xAttrList->getNameByIndex( i );\n rtl::OUString aLocalName;\n USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(\n sAttrName, &aLocalName );\n rtl::OUString sValue = xAttrList->getValueByIndex( i );\n\n switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )\n {\n case XML_TOK_TABLE_ANNOTATION_ATTR_AUTHOR:\n {\n sAuthorBuffer = sValue;\n }\n break;\n case XML_TOK_TABLE_ANNOTATION_ATTR_CREATE_DATE:\n {\n sCreateDateBuffer = sValue;\n }\n break;\n case XML_TOK_TABLE_ANNOTATION_ATTR_CREATE_DATE_STRING:\n {\n sCreateDateStringBuffer = sValue;\n }\n break;\n case XML_TOK_TABLE_ANNOTATION_ATTR_DISPLAY:\n {\n bDisplay = IsXMLToken(sValue, XML_TRUE);\n }\n break;\n }\n }\n}\n\nScXMLAnnotationContext::~ScXMLAnnotationContext()\n{\n}\n\nSvXMLImportContext *ScXMLAnnotationContext::CreateChildContext( USHORT nPrefix,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n\n if( XML_NAMESPACE_DC == nPrefix )\n {\n if( IsXMLToken( rLName, XML_CREATOR ) )\n pContext = new ScXMLContentContext(GetScImport(), nPrefix,\n rLName, xAttrList, sAuthorBuffer);\n else if( IsXMLToken( rLName, XML_DATE ) )\n pContext = new ScXMLContentContext(GetScImport(), nPrefix,\n rLName, xAttrList, sCreateDateBuffer);\n }\n else if( XML_NAMESPACE_META == nPrefix )\n {\n if( IsXMLToken( rLName, XML_DATE_STRING ) )\n pContext = new ScXMLContentContext(GetScImport(), nPrefix,\n rLName, xAttrList, sCreateDateStringBuffer);\n }\n else if ((nPrefix == XML_NAMESPACE_TEXT) && IsXMLToken(rLName, XML_P) )\n {\n if (!bHasTextP)\n {\n bHasTextP = sal_True;\n sOUText.setLength(0);\n }\n if(nParagraphCount)\n sOUText.append(static_cast<sal_Unicode>('\\n'));\n nParagraphCount++;\n pContext = new ScXMLContentContext( GetScImport(), nPrefix, rLName, xAttrList, sOUText);\n }\n\n if( !pContext )\n pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );\n\n return pContext;\n}\n\nvoid ScXMLAnnotationContext::Characters( const ::rtl::OUString& rChars )\n{\n if (!bHasTextP)\n sOUText.append(rChars);\n}\n\nvoid ScXMLAnnotationContext::EndElement()\n{\n ScMyImportAnnotation* pMyAnnotation = new ScMyImportAnnotation();\n pMyAnnotation->sAuthor = sAuthorBuffer.makeStringAndClear();\n pMyAnnotation->sCreateDate = sCreateDateBuffer.makeStringAndClear();\n if (!pMyAnnotation->sCreateDate.getLength())\n pMyAnnotation->sCreateDate = sCreateDateStringBuffer.makeStringAndClear();\n pMyAnnotation->sText = sOUText.makeStringAndClear();\n pMyAnnotation->bDisplay = bDisplay;\n pCellContext->AddAnnotation(pMyAnnotation);\n}\n\n<commit_msg>INTEGRATION: CWS dr12 (1.8.290); FILE MERGED 2004\/08\/09 13:44:36 sab 1.8.290.4: #i21253#; make old notes work 2004\/07\/30 11:48:48 sab 1.8.290.3: #i21253#; make notes work 2004\/07\/27 01:44:03 sab 1.8.290.2: RESYNC: (1.8-1.9); FILE MERGED 2004\/07\/23 20:58:26 sab 1.8.290.1: #i21253#; add formatted notes<commit_after>\/*************************************************************************\n *\n * $RCSfile: xmlannoi.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: hr $ $Date: 2004-09-08 13:50:19 $\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#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include \"xmlannoi.hxx\"\n#include \"xmlimprt.hxx\"\n#include \"xmlcelli.hxx\"\n#ifndef SC_XMLCONTI_HXX\n#include \"xmlconti.hxx\"\n#endif\n#ifndef _SC_XMLTABLESHAPEIMPORTHELPER_HXX\n#include \"XMLTableShapeImportHelper.hxx\"\n#endif\n\n#include <xmloff\/xmltkmap.hxx>\n#include <xmloff\/nmspmap.hxx>\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n#ifndef _SVX_UNOSHAPE_HXX\n#include <svx\/unoshape.hxx>\n#endif\n#ifndef _SVDOBJ_HXX\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef _OUTLOBJ_HXX\n#include <svx\/outlobj.hxx>\n#endif\n\nusing namespace com::sun::star;\nusing namespace xmloff::token;\n\n\/\/------------------------------------------------------------------\n\nScXMLAnnotationContext::ScXMLAnnotationContext( ScXMLImport& rImport,\n USHORT nPrfx,\n const ::rtl::OUString& rLName,\n const uno::Reference<xml::sax::XAttributeList>& xAttrList,\n ScXMLTableRowCellContext* pTempCellContext) :\n SvXMLImportContext( rImport, nPrfx, rLName ),\n nParagraphCount(0),\n bDisplay(sal_False),\n bHasTextP(sal_False),\n bHasPos(sal_False),\n pShapeContext(NULL)\n{\n uno::Reference<drawing::XShapes> xShapes (GetScImport().GetTables().GetCurrentXShapes());\n if (xShapes.is())\n {\n XMLTableShapeImportHelper* pTableShapeImport = (XMLTableShapeImportHelper*)GetScImport().GetShapeImport().get();\n pTableShapeImport->SetAnnotation(this);\n pShapeContext = GetScImport().GetShapeImport()->CreateGroupChildContext(\n GetScImport(), nPrfx, rLName, xAttrList, xShapes);\n }\n\n pCellContext = pTempCellContext;\n sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetTableAnnotationAttrTokenMap();\n for( sal_Int16 i=0; i < nAttrCount; i++ )\n {\n rtl::OUString sAttrName = xAttrList->getNameByIndex( i );\n rtl::OUString aLocalName;\n USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(\n sAttrName, &aLocalName );\n rtl::OUString sValue = xAttrList->getValueByIndex( i );\n\n switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )\n {\n case XML_TOK_TABLE_ANNOTATION_ATTR_AUTHOR:\n {\n sAuthorBuffer = sValue;\n }\n break;\n case XML_TOK_TABLE_ANNOTATION_ATTR_CREATE_DATE:\n {\n sCreateDateBuffer = sValue;\n }\n break;\n case XML_TOK_TABLE_ANNOTATION_ATTR_CREATE_DATE_STRING:\n {\n sCreateDateStringBuffer = sValue;\n }\n break;\n case XML_TOK_TABLE_ANNOTATION_ATTR_DISPLAY:\n {\n bDisplay = IsXMLToken(sValue, XML_TRUE);\n }\n break;\n case XML_TOK_TABLE_ANNOTATION_ATTR_X:\n {\n bHasPos = sal_True;\n }\n break;\n case XML_TOK_TABLE_ANNOTATION_ATTR_Y:\n {\n bHasPos = sal_True;\n }\n break;\n }\n }\n}\n\nScXMLAnnotationContext::~ScXMLAnnotationContext()\n{\n}\n\nvoid ScXMLAnnotationContext::StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList)\n{\n if (pShapeContext)\n pShapeContext->StartElement(xAttrList);\n}\n\nSvXMLImportContext *ScXMLAnnotationContext::CreateChildContext( USHORT nPrefix,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n\n if( XML_NAMESPACE_DC == nPrefix )\n {\n if( IsXMLToken( rLName, XML_CREATOR ) )\n pContext = new ScXMLContentContext(GetScImport(), nPrefix,\n rLName, xAttrList, sAuthorBuffer);\n else if( IsXMLToken( rLName, XML_DATE ) )\n pContext = new ScXMLContentContext(GetScImport(), nPrefix,\n rLName, xAttrList, sCreateDateBuffer);\n }\n else if( XML_NAMESPACE_META == nPrefix )\n {\n if( IsXMLToken( rLName, XML_DATE_STRING ) )\n pContext = new ScXMLContentContext(GetScImport(), nPrefix,\n rLName, xAttrList, sCreateDateStringBuffer);\n }\n\/* else if ((nPrefix == XML_NAMESPACE_TEXT) && IsXMLToken(rLName, XML_P) )\n {\n if (!bHasTextP)\n {\n bHasTextP = sal_True;\n sOUText.setLength(0);\n }\n if(nParagraphCount)\n sOUText.append(static_cast<sal_Unicode>('\\n'));\n nParagraphCount++;\n pContext = new ScXMLContentContext( GetScImport(), nPrefix, rLName, xAttrList, sOUText);\n }*\/\n\n if( !pContext && pShapeContext )\n pContext = pShapeContext->CreateChildContext(nPrefix, rLName, xAttrList);\n\n if( !pContext )\n pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );\n\n return pContext;\n}\n\nvoid ScXMLAnnotationContext::Characters( const ::rtl::OUString& rChars )\n{\n if (!bHasTextP)\n sOUText.append(rChars);\n}\n\nvoid ScXMLAnnotationContext::EndElement()\n{\n if (pShapeContext)\n {\n pShapeContext->EndElement();\n delete pShapeContext;\n }\n\n ScMyImportAnnotation* pMyAnnotation = new ScMyImportAnnotation();\n pMyAnnotation->sAuthor = sAuthorBuffer.makeStringAndClear();\n pMyAnnotation->sCreateDate = sCreateDateBuffer.makeStringAndClear();\n if (!pMyAnnotation->sCreateDate.getLength())\n pMyAnnotation->sCreateDate = sCreateDateStringBuffer.makeStringAndClear();\n pMyAnnotation->sText = sOUText.makeStringAndClear();\n pMyAnnotation->bDisplay = bDisplay;\n\n if (xShape.is() && xShapes.is())\n {\n SvxShape* pShapeImp = SvxShape::getImplementation(xShape);\n if (pShapeImp)\n {\n SdrObject *pSdrObj = pShapeImp->GetSdrObject();\n if (pSdrObj)\n {\n if (bHasPos)\n {\n pMyAnnotation->pItemSet = pSdrObj->GetMergedItemSet().Clone();\n awt::Point aPos = xShape->getPosition();\n awt::Size aSize = xShape->getSize();\n Rectangle aRect(Point(aPos.X, aPos.Y), Size(aSize.Width, aSize.Height));\n pMyAnnotation->pRect = new Rectangle(aRect);\n }\n\n if((pSdrObj->GetOutlinerParaObject()))\n pMyAnnotation->pOPO = new OutlinerParaObject( *(pSdrObj->GetOutlinerParaObject()) );\n\n xShapes->remove(xShape);\n }\n }\n }\n\n XMLTableShapeImportHelper* pTableShapeImport = (XMLTableShapeImportHelper*)GetScImport().GetShapeImport().get();\n pTableShapeImport->SetAnnotation(NULL);\n\n pCellContext->AddAnnotation(pMyAnnotation);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id: AliTRDrawStreamBase.cxx 23387 2008-01-17 17:25:16Z cblume $ *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ This class defines access to TRD digits in raw data. \/\/\n\/\/ \/\/\n\/\/ It loops over all TRD digits in the raw data given by the AliRawReader. \/\/\n\/\/ The Next method goes to the next digit. If there are no digits left \/\/\n\/\/ it returns kFALSE. \/\/\n\/\/ Several getters provide information about the current digit. \/\/\n\/\/ \/\/\n\/\/ Author: M. Ploskon (ploskon@ikf.uni-frankfurt.de) \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliTRDrawStreamOld.h\"\n#include \"AliTRDrawStream.h\"\n\n#include \"AliTRDrawStreamBase.h\"\n\n\/\/--------------------------------------------------------\nClassImp(AliTRDrawStreamBase)\n\nInt_t AliTRDrawStreamBase::fgRawStreamVersion = AliTRDrawStreamBase::kTRDdefaultStream;\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase::AliTRDrawStreamBase()\n : TObject()\n{\n \/\/\n \/\/ this is just for API\n \/\/\n ;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase::AliTRDrawStreamBase(AliRawReader *\/*rawReader*\/)\n : TObject()\n{\n \/\/\n \/\/ this is just for API\n \/\/\n ;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase::AliTRDrawStreamBase(const AliTRDrawStreamBase& \/*st*\/)\n : TObject()\n{\n \/\/\n \/\/ copy\n \/\/\n TRD_NOIMP();\n ;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase::~AliTRDrawStreamBase()\n{\n \/\/\n \/\/ destructor\n \/\/\n ;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase &\nAliTRDrawStreamBase::operator=(const AliTRDrawStreamBase &)\n{\n \/\/\n \/\/ we are not using this functionality\n \/\/\n TRD_NOIMP();\n return *this;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase *AliTRDrawStreamBase::GetRawStream()\n{\n \/\/\n \/\/ Returns the selected raw stream implementation\n \/\/\n\n if (fgRawStreamVersion == kTRDrealStream)\n return new AliTRDrawStreamOld();\n\n if (fgRawStreamVersion == kTRDsimStream)\n return new AliTRDrawStreamOld();\n \n \/\/if (fgRawStreamVersion == kTRDfastStream)\n \/\/ return new AliTRDrawFastStream();\n\n if (fgRawStreamVersion == kTRDdefaultStream)\n return new AliTRDrawStream();\n\n return new AliTRDrawStreamBase;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase *AliTRDrawStreamBase::GetRawStream(AliRawReader *reader)\n{\n \/\/\n \/\/ Returns the selected raw stream implementation\n \/\/\n\n if (fgRawStreamVersion == kTRDrealStream)\n return new AliTRDrawStreamOld(reader);\n\n if (fgRawStreamVersion == kTRDsimStream)\n return new AliTRDrawStreamOld(reader);\n\n\n \/\/if (fgRawStreamVersion == kTRDfastStream){\n \/\/ return new AliTRDrawFastStream(reader);}\n\n if (fgRawStreamVersion == kTRDdefaultStream)\n return new AliTRDrawStream(reader);\n\n return new AliTRDrawStreamBase;\n}\n\n\/\/_____________________________________________________________________________\nvoid AliTRDrawStreamBase::SetRawStreamVersion(const char *opt) \n{ \n \/\/\n \/\/ Sets the raw stream version\n \/\/\n\n fgRawStreamVersion = 0; \n\n if (strstr(opt, \"sim\" ) != 0 || strstr(opt, \"SIM\") != 0) \n fgRawStreamVersion = kTRDsimStream; \n\n if (strstr(opt, \"tb\" ) != 0 || strstr(opt, \"TB\") != 0) \n fgRawStreamVersion = kTRDrealStream; \n\n if (strstr(opt, \"real\" ) != 0 || strstr(opt, \"REAL\") != 0) \n fgRawStreamVersion = kTRDrealStream; \n\n \/\/if (strstr(opt, \"fast\" ) != 0 || strstr(opt, \"FAST\") != 0)\n \/\/ fgRawStreamVersion = kTRDfastStream;\n\n if (strstr(opt, \"default\" ) != 0 || strstr(opt, \"DEFAULT\") != 0)\n fgRawStreamVersion = kTRDdefaultStream;\n \n}\n\n<commit_msg>Remove obsolete classes<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id: AliTRDrawStreamBase.cxx 23387 2008-01-17 17:25:16Z cblume $ *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ This class defines access to TRD digits in raw data. \/\/\n\/\/ \/\/\n\/\/ It loops over all TRD digits in the raw data given by the AliRawReader. \/\/\n\/\/ The Next method goes to the next digit. If there are no digits left \/\/\n\/\/ it returns kFALSE. \/\/\n\/\/ Several getters provide information about the current digit. \/\/\n\/\/ \/\/\n\/\/ Author: M. Ploskon (ploskon@ikf.uni-frankfurt.de) \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliTRDrawStream.h\"\n#include \"AliTRDrawStreamBase.h\"\n\n\/\/--------------------------------------------------------\nClassImp(AliTRDrawStreamBase)\n\nInt_t AliTRDrawStreamBase::fgRawStreamVersion = AliTRDrawStreamBase::kTRDdefaultStream;\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase::AliTRDrawStreamBase()\n : TObject()\n{\n \/\/\n \/\/ this is just for API\n \/\/\n ;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase::AliTRDrawStreamBase(AliRawReader *\/*rawReader*\/)\n : TObject()\n{\n \/\/\n \/\/ this is just for API\n \/\/\n ;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase::AliTRDrawStreamBase(const AliTRDrawStreamBase& \/*st*\/)\n : TObject()\n{\n \/\/\n \/\/ copy\n \/\/\n TRD_NOIMP();\n ;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase::~AliTRDrawStreamBase()\n{\n \/\/\n \/\/ destructor\n \/\/\n ;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase &\nAliTRDrawStreamBase::operator=(const AliTRDrawStreamBase &)\n{\n \/\/\n \/\/ we are not using this functionality\n \/\/\n TRD_NOIMP();\n return *this;\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase *AliTRDrawStreamBase::GetRawStream()\n{\n \/\/\n \/\/ Returns the selected raw stream implementation\n \/\/\n\n \/\/ Always use the new one!\n return new AliTRDrawStream();\n\n}\n\n\/\/_____________________________________________________________________________\nAliTRDrawStreamBase *AliTRDrawStreamBase::GetRawStream(AliRawReader *reader)\n{\n \/\/\n \/\/ Returns the selected raw stream implementation\n \/\/\n\n \/\/ Always use the new one!\n return new AliTRDrawStream(reader);\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliTRDrawStreamBase::SetRawStreamVersion(const char *opt) \n{ \n \/\/\n \/\/ Sets the raw stream version\n \/\/\n\n fgRawStreamVersion = 0; \n\n if (strstr(opt, \"sim\" ) != 0 || strstr(opt, \"SIM\") != 0) \n fgRawStreamVersion = kTRDsimStream; \n\n if (strstr(opt, \"tb\" ) != 0 || strstr(opt, \"TB\") != 0) \n fgRawStreamVersion = kTRDrealStream; \n\n if (strstr(opt, \"real\" ) != 0 || strstr(opt, \"REAL\") != 0) \n fgRawStreamVersion = kTRDrealStream; \n\n \/\/if (strstr(opt, \"fast\" ) != 0 || strstr(opt, \"FAST\") != 0)\n \/\/ fgRawStreamVersion = kTRDfastStream;\n\n if (strstr(opt, \"default\" ) != 0 || strstr(opt, \"DEFAULT\") != 0)\n fgRawStreamVersion = kTRDdefaultStream;\n \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===\/\/\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\/\/ CodeEmitterGen uses the descriptions of instructions and their fields to\n\/\/ construct an automated code emitter: a function that, given a MachineInstr,\n\/\/ returns the (currently, 32-bit unsigned) value of the instruction.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CodeEmitterGen.h\"\n#include \"CodeGenTarget.h\"\n#include \"Record.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/Debug.h\"\nusing namespace llvm;\n\nvoid CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {\n for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();\n I != E; ++I) {\n Record *R = *I;\n if (R->getValueAsString(\"Namespace\") == \"TargetOpcode\")\n continue;\n\n BitsInit *BI = R->getValueAsBitsInit(\"Inst\");\n\n unsigned numBits = BI->getNumBits();\n BitsInit *NewBI = new BitsInit(numBits);\n for (unsigned bit = 0, end = numBits \/ 2; bit != end; ++bit) {\n unsigned bitSwapIdx = numBits - bit - 1;\n Init *OrigBit = BI->getBit(bit);\n Init *BitSwap = BI->getBit(bitSwapIdx);\n NewBI->setBit(bit, BitSwap);\n NewBI->setBit(bitSwapIdx, OrigBit);\n }\n if (numBits % 2) {\n unsigned middle = (numBits + 1) \/ 2;\n NewBI->setBit(middle, BI->getBit(middle));\n }\n\n \/\/ Update the bits in reversed order so that emitInstrOpBits will get the\n \/\/ correct endianness.\n R->getValue(\"Inst\")->setValue(NewBI);\n }\n}\n\n\/\/ If the VarBitInit at position 'bit' matches the specified variable then\n\/\/ return the variable bit position. Otherwise return -1.\nint CodeEmitterGen::getVariableBit(const std::string &VarName,\n BitsInit *BI, int bit) {\n if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {\n TypedInit *TI = VBI->getVariable();\n\n if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {\n if (VI->getName() == VarName) return VBI->getBitNum();\n }\n }\n\n return -1;\n}\n\nvoid CodeEmitterGen::run(raw_ostream &o) {\n CodeGenTarget Target;\n std::vector<Record*> Insts = Records.getAllDerivedDefinitions(\"Instruction\");\n\n \/\/ For little-endian instruction bit encodings, reverse the bit order\n if (Target.isLittleEndianEncoding()) reverseBits(Insts);\n\n EmitSourceFileHeader(\"Machine Code Emitter\", o);\n std::string Namespace = Insts[0]->getValueAsString(\"Namespace\") + \"::\";\n\n const std::vector<const CodeGenInstruction*> &NumberedInstructions =\n Target.getInstructionsByEnumValue();\n\n \/\/ Emit function declaration\n o << \"unsigned \" << Target.getName() << \"CodeEmitter::\"\n << \"getBinaryCodeForInstr(const MachineInstr &MI) const {\\n\";\n\n \/\/ Emit instruction base values\n o << \" static const unsigned InstBits[] = {\\n\";\n for (std::vector<const CodeGenInstruction*>::const_iterator\n IN = NumberedInstructions.begin(),\n EN = NumberedInstructions.end();\n IN != EN; ++IN) {\n const CodeGenInstruction *CGI = *IN;\n Record *R = CGI->TheDef;\n\n if (R->getValueAsString(\"Namespace\") == \"TargetOpcode\") {\n o << \" 0U,\\n\";\n continue;\n }\n\n BitsInit *BI = R->getValueAsBitsInit(\"Inst\");\n\n \/\/ Start by filling in fixed values...\n unsigned Value = 0;\n for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {\n if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {\n Value |= B->getValue() << (e-i-1);\n }\n }\n o << \" \" << Value << \"U,\" << '\\t' << \"\/\/ \" << R->getName() << \"\\n\";\n }\n o << \" 0U\\n };\\n\";\n\n \/\/ Map to accumulate all the cases.\n std::map<std::string, std::vector<std::string> > CaseMap;\n\n \/\/ Construct all cases statement for each opcode\n for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();\n IC != EC; ++IC) {\n Record *R = *IC;\n if (R->getValueAsString(\"Namespace\") == \"TargetOpcode\")\n continue;\n const std::string &InstName = R->getName();\n std::string Case(\"\");\n\n BitsInit *BI = R->getValueAsBitsInit(\"Inst\");\n const std::vector<RecordVal> &Vals = R->getValues();\n CodeGenInstruction &CGI = Target.getInstruction(R);\n\n \/\/ Loop over all of the fields in the instruction, determining which are the\n \/\/ operands to the instruction.\n unsigned NumberedOp = 0;\n for (unsigned i = 0, e = Vals.size(); i != e; ++i) {\n if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {\n \/\/ Is the operand continuous? If so, we can just mask and OR it in\n \/\/ instead of doing it bit-by-bit, saving a lot in runtime cost.\n const std::string &VarName = Vals[i].getName();\n bool gotOp = false;\n\n for (int bit = BI->getNumBits()-1; bit >= 0; ) {\n int varBit = getVariableBit(VarName, BI, bit);\n\n if (varBit == -1) {\n --bit;\n } else {\n int beginInstBit = bit;\n int beginVarBit = varBit;\n int N = 1;\n\n for (--bit; bit >= 0;) {\n varBit = getVariableBit(VarName, BI, bit);\n if (varBit == -1 || varBit != (beginVarBit - N)) break;\n ++N;\n --bit;\n }\n\n if (!gotOp) {\n \/\/ If the operand matches by name, reference according to that\n \/\/ operand number. Non-matching operands are assumed to be in\n \/\/ order.\n unsigned OpIdx;\n if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {\n \/\/ Get the machine operand number for the indicated operand.\n OpIdx = CGI.Operands[OpIdx].MIOperandNo;\n assert (!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&\n \"Explicitly used operand also marked as not emitted!\");\n } else {\n \/\/\/ If this operand is not supposed to be emitted by the\n \/\/\/ generated emitter, skip it.\n while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))\n ++NumberedOp;\n OpIdx = NumberedOp++;\n }\n std::pair<unsigned, unsigned> SO =\n CGI.Operands.getSubOperandNumber(OpIdx);\n std::string &EncoderMethodName =\n CGI.Operands[SO.first].EncoderMethodName;\n\n \/\/ If the source operand has a custom encoder, use it. This will\n \/\/ get the encoding for all of the suboperands.\n if (!EncoderMethodName.empty()) {\n \/\/ A custom encoder has all of the information for the\n \/\/ sub-operands, if there are more than one, so only\n \/\/ query the encoder once per source operand.\n if (SO.second == 0) {\n Case += \" \/\/ op: \" + VarName + \"\\n\"\n + \" op = \" + EncoderMethodName + \"(MI, \"\n + utostr(OpIdx) + \");\\n\";\n }\n } else {\n Case += \" \/\/ op: \" + VarName + \"\\n\"\n + \" op = getMachineOpValue(MI, MI.getOperand(\"\n + utostr(OpIdx) + \"));\\n\";\n }\n gotOp = true;\n }\n\n unsigned opMask = ~0U >> (32-N);\n int opShift = beginVarBit - N + 1;\n opMask <<= opShift;\n opShift = beginInstBit - beginVarBit;\n\n if (opShift > 0) {\n Case += \" Value |= (op & \" + utostr(opMask) + \"U) << \"\n + itostr(opShift) + \";\\n\";\n } else if (opShift < 0) {\n Case += \" Value |= (op & \" + utostr(opMask) + \"U) >> \"\n + itostr(-opShift) + \";\\n\";\n } else {\n Case += \" Value |= op & \" + utostr(opMask) + \"U;\\n\";\n }\n }\n }\n }\n }\n\n std::vector<std::string> &InstList = CaseMap[Case];\n InstList.push_back(InstName);\n }\n\n \/\/ Emit initial function code\n o << \" const unsigned opcode = MI.getOpcode();\\n\"\n << \" unsigned Value = InstBits[opcode];\\n\"\n << \" unsigned op = 0;\\n\"\n << \" op = op; \/\/ suppress warning\\n\"\n << \" switch (opcode) {\\n\";\n\n \/\/ Emit each case statement\n std::map<std::string, std::vector<std::string> >::iterator IE, EE;\n for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {\n const std::string &Case = IE->first;\n std::vector<std::string> &InstList = IE->second;\n\n for (int i = 0, N = InstList.size(); i < N; i++) {\n if (i) o << \"\\n\";\n o << \" case \" << Namespace << InstList[i] << \":\";\n }\n o << \" {\\n\";\n o << Case;\n o << \" break;\\n\"\n << \" }\\n\";\n }\n\n \/\/ Default case: unhandled opcode\n o << \" default:\\n\"\n << \" std::string msg;\\n\"\n << \" raw_string_ostream Msg(msg);\\n\"\n << \" Msg << \\\"Not supported instr: \\\" << MI;\\n\"\n << \" report_fatal_error(Msg.str());\\n\"\n << \" }\\n\"\n << \" return Value;\\n\"\n << \"}\\n\\n\";\n}\n<commit_msg>Revert r114340 (improvements in Darwin function prologue\/epilogue), as it broke assumptions about stack layout. Specifically, LR must be saved next to FP.<commit_after>\/\/===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===\/\/\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\/\/ CodeEmitterGen uses the descriptions of instructions and their fields to\n\/\/ construct an automated code emitter: a function that, given a MachineInstr,\n\/\/ returns the (currently, 32-bit unsigned) value of the instruction.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CodeEmitterGen.h\"\n#include \"CodeGenTarget.h\"\n#include \"Record.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\nusing namespace llvm;\n\nstatic cl::opt<bool>\nMCEmitter(\"mc-code-emitter\",\n cl::desc(\"Generate CodeEmitter for use with the MC library.\"),\n cl::init(false));\n\nvoid CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {\n for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();\n I != E; ++I) {\n Record *R = *I;\n if (R->getValueAsString(\"Namespace\") == \"TargetOpcode\")\n continue;\n\n BitsInit *BI = R->getValueAsBitsInit(\"Inst\");\n\n unsigned numBits = BI->getNumBits();\n BitsInit *NewBI = new BitsInit(numBits);\n for (unsigned bit = 0, end = numBits \/ 2; bit != end; ++bit) {\n unsigned bitSwapIdx = numBits - bit - 1;\n Init *OrigBit = BI->getBit(bit);\n Init *BitSwap = BI->getBit(bitSwapIdx);\n NewBI->setBit(bit, BitSwap);\n NewBI->setBit(bitSwapIdx, OrigBit);\n }\n if (numBits % 2) {\n unsigned middle = (numBits + 1) \/ 2;\n NewBI->setBit(middle, BI->getBit(middle));\n }\n\n \/\/ Update the bits in reversed order so that emitInstrOpBits will get the\n \/\/ correct endianness.\n R->getValue(\"Inst\")->setValue(NewBI);\n }\n}\n\n\/\/ If the VarBitInit at position 'bit' matches the specified variable then\n\/\/ return the variable bit position. Otherwise return -1.\nint CodeEmitterGen::getVariableBit(const std::string &VarName,\n BitsInit *BI, int bit) {\n if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {\n TypedInit *TI = VBI->getVariable();\n\n if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {\n if (VI->getName() == VarName) return VBI->getBitNum();\n }\n }\n\n return -1;\n}\n\nvoid CodeEmitterGen::run(raw_ostream &o) {\n CodeGenTarget Target;\n std::vector<Record*> Insts = Records.getAllDerivedDefinitions(\"Instruction\");\n\n \/\/ For little-endian instruction bit encodings, reverse the bit order\n if (Target.isLittleEndianEncoding()) reverseBits(Insts);\n\n EmitSourceFileHeader(\"Machine Code Emitter\", o);\n std::string Namespace = Insts[0]->getValueAsString(\"Namespace\") + \"::\";\n\n const std::vector<const CodeGenInstruction*> &NumberedInstructions =\n Target.getInstructionsByEnumValue();\n\n \/\/ Emit function declaration\n o << \"unsigned \" << Target.getName() << \"CodeEmitter::\"\n << \"getBinaryCodeForInstr(const MachineInstr &MI) const {\\n\";\n\n \/\/ Emit instruction base values\n o << \" static const unsigned InstBits[] = {\\n\";\n for (std::vector<const CodeGenInstruction*>::const_iterator\n IN = NumberedInstructions.begin(),\n EN = NumberedInstructions.end();\n IN != EN; ++IN) {\n const CodeGenInstruction *CGI = *IN;\n Record *R = CGI->TheDef;\n\n if (R->getValueAsString(\"Namespace\") == \"TargetOpcode\") {\n o << \" 0U,\\n\";\n continue;\n }\n\n BitsInit *BI = R->getValueAsBitsInit(\"Inst\");\n\n \/\/ Start by filling in fixed values...\n unsigned Value = 0;\n for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {\n if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {\n Value |= B->getValue() << (e-i-1);\n }\n }\n o << \" \" << Value << \"U,\" << '\\t' << \"\/\/ \" << R->getName() << \"\\n\";\n }\n o << \" 0U\\n };\\n\";\n\n \/\/ Map to accumulate all the cases.\n std::map<std::string, std::vector<std::string> > CaseMap;\n\n \/\/ Construct all cases statement for each opcode\n for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();\n IC != EC; ++IC) {\n Record *R = *IC;\n if (R->getValueAsString(\"Namespace\") == \"TargetOpcode\")\n continue;\n const std::string &InstName = R->getName();\n std::string Case(\"\");\n\n BitsInit *BI = R->getValueAsBitsInit(\"Inst\");\n const std::vector<RecordVal> &Vals = R->getValues();\n CodeGenInstruction &CGI = Target.getInstruction(R);\n\n \/\/ Loop over all of the fields in the instruction, determining which are the\n \/\/ operands to the instruction.\n unsigned NumberedOp = 0;\n for (unsigned i = 0, e = Vals.size(); i != e; ++i) {\n if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {\n \/\/ Is the operand continuous? If so, we can just mask and OR it in\n \/\/ instead of doing it bit-by-bit, saving a lot in runtime cost.\n const std::string &VarName = Vals[i].getName();\n bool gotOp = false;\n\n for (int bit = BI->getNumBits()-1; bit >= 0; ) {\n int varBit = getVariableBit(VarName, BI, bit);\n\n if (varBit == -1) {\n --bit;\n } else {\n int beginInstBit = bit;\n int beginVarBit = varBit;\n int N = 1;\n\n for (--bit; bit >= 0;) {\n varBit = getVariableBit(VarName, BI, bit);\n if (varBit == -1 || varBit != (beginVarBit - N)) break;\n ++N;\n --bit;\n }\n\n if (!gotOp) {\n \/\/ If the operand matches by name, reference according to that\n \/\/ operand number. Non-matching operands are assumed to be in\n \/\/ order.\n unsigned OpIdx;\n if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {\n \/\/ Get the machine operand number for the indicated operand.\n OpIdx = CGI.Operands[OpIdx].MIOperandNo;\n assert (!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&\n \"Explicitly used operand also marked as not emitted!\");\n } else {\n \/\/\/ If this operand is not supposed to be emitted by the\n \/\/\/ generated emitter, skip it.\n while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))\n ++NumberedOp;\n OpIdx = NumberedOp++;\n }\n std::pair<unsigned, unsigned> SO =\n CGI.Operands.getSubOperandNumber(OpIdx);\n std::string &EncoderMethodName =\n CGI.Operands[SO.first].EncoderMethodName;\n\n \/\/ If the source operand has a custom encoder, use it. This will\n \/\/ get the encoding for all of the suboperands.\n if (!EncoderMethodName.empty()) {\n \/\/ A custom encoder has all of the information for the\n \/\/ sub-operands, if there are more than one, so only\n \/\/ query the encoder once per source operand.\n if (SO.second == 0) {\n Case += \" \/\/ op: \" + VarName + \"\\n\"\n + \" op = \" + EncoderMethodName + \"(MI, \"\n + utostr(OpIdx) + \");\\n\";\n }\n } else {\n Case += \" \/\/ op: \" + VarName + \"\\n\"\n + \" op = getMachineOpValue(MI, MI.getOperand(\"\n + utostr(OpIdx) + \"));\\n\";\n }\n gotOp = true;\n }\n\n unsigned opMask = ~0U >> (32-N);\n int opShift = beginVarBit - N + 1;\n opMask <<= opShift;\n opShift = beginInstBit - beginVarBit;\n\n if (opShift > 0) {\n Case += \" Value |= (op & \" + utostr(opMask) + \"U) << \"\n + itostr(opShift) + \";\\n\";\n } else if (opShift < 0) {\n Case += \" Value |= (op & \" + utostr(opMask) + \"U) >> \"\n + itostr(-opShift) + \";\\n\";\n } else {\n Case += \" Value |= op & \" + utostr(opMask) + \"U;\\n\";\n }\n }\n }\n }\n }\n\n std::vector<std::string> &InstList = CaseMap[Case];\n InstList.push_back(InstName);\n }\n\n \/\/ Emit initial function code\n o << \" const unsigned opcode = MI.getOpcode();\\n\"\n << \" unsigned Value = InstBits[opcode];\\n\"\n << \" unsigned op = 0;\\n\"\n << \" op = op; \/\/ suppress warning\\n\"\n << \" switch (opcode) {\\n\";\n\n \/\/ Emit each case statement\n std::map<std::string, std::vector<std::string> >::iterator IE, EE;\n for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {\n const std::string &Case = IE->first;\n std::vector<std::string> &InstList = IE->second;\n\n for (int i = 0, N = InstList.size(); i < N; i++) {\n if (i) o << \"\\n\";\n o << \" case \" << Namespace << InstList[i] << \":\";\n }\n o << \" {\\n\";\n o << Case;\n o << \" break;\\n\"\n << \" }\\n\";\n }\n\n \/\/ Default case: unhandled opcode\n o << \" default:\\n\"\n << \" std::string msg;\\n\"\n << \" raw_string_ostream Msg(msg);\\n\"\n << \" Msg << \\\"Not supported instr: \\\" << MI;\\n\"\n << \" report_fatal_error(Msg.str());\\n\"\n << \" }\\n\"\n << \" return Value;\\n\"\n << \"}\\n\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/@author A0094446X\n#include \"stdafx.h\"\n#include <memory>\n#include <QApplication>\n#include <QList>\n#include \"session_manager.h\"\n\nYouMainGUI::SessionManager::~SessionManager() {\n\tsaveSession();\n}\n\nvoid YouMainGUI::SessionManager::setup() {\n\tloadSession();\n}\n\nvoid YouMainGUI::SessionManager::loadSession() {\n\tQSettings settings(\"session.txt\", QSettings::IniFormat);\n\tint size = settings.beginReadArray(\"idList\");\n\tfor (int i = 0; i < size; i++) {\n\t\tsettings.setArrayIndex(i);\n\t\ttaskIDs.push_back(settings.value(\"ID\").toLongLong());\n\t}\n\tsettings.endArray();\n\tsettings.beginGroup(\"MainWindow\");\n\tparentGUI->resize(settings.value(\"size\", QSize(400, 400)).toSize());\n\tparentGUI->move(settings.value(\"pos\", QPoint(200, 200)).toPoint());\n\tif (settings.value(\"maximized\", false).toBool()) {\n\t\tparentGUI->setWindowState(\n\t\t\tparentGUI->windowState() | Qt::WindowMaximized);\n\t} else {\n\t\tparentGUI->setWindowState(\n\t\t\tparentGUI->windowState() & (~Qt::WindowMaximized));\n\t}\n\n\tsettings.endGroup();\n}\n\nvoid YouMainGUI::SessionManager::saveSession() {\n\tQSettings settings(\"session.txt\", QSettings::IniFormat);\n\t\/\/ TODO(angathorion): Add a function in main gui that calls fills taskIDs\n\t\/\/ array on close.\n\tsettings.beginWriteArray(\"idList\");\n\tfor (int i = 0; i < taskIDs.size(); i++) {\n\t\tsettings.setArrayIndex(i);\n\t\tsettings.setValue(\"ID\", taskIDs.at(i));\n\t}\n\tsettings.endArray();\n\tsettings.beginGroup(\"MainWindow\");\n\tsettings.setValue(\"size\", parentGUI->size());\n\tsettings.setValue(\"pos\", parentGUI->pos());\n\tsettings.setValue(\"maximized\", parentGUI->isMaximized());\n\tsettings.endGroup();\n}\n<commit_msg>Removed line spacing.<commit_after>\/\/@author A0094446X\n#include \"stdafx.h\"\n#include <memory>\n#include <QApplication>\n#include <QList>\n#include \"session_manager.h\"\n\nYouMainGUI::SessionManager::~SessionManager() {\n\tsaveSession();\n}\n\nvoid YouMainGUI::SessionManager::setup() {\n\tloadSession();\n}\n\nvoid YouMainGUI::SessionManager::loadSession() {\n\tQSettings settings(\"session.txt\", QSettings::IniFormat);\n\tint size = settings.beginReadArray(\"idList\");\n\tfor (int i = 0; i < size; i++) {\n\t\tsettings.setArrayIndex(i);\n\t\ttaskIDs.push_back(settings.value(\"ID\").toLongLong());\n\t}\n\tsettings.endArray();\n\tsettings.beginGroup(\"MainWindow\");\n\tparentGUI->resize(settings.value(\"size\", QSize(400, 400)).toSize());\n\tparentGUI->move(settings.value(\"pos\", QPoint(200, 200)).toPoint());\n\tif (settings.value(\"maximized\", false).toBool()) {\n\t\tparentGUI->setWindowState(\n\t\t\tparentGUI->windowState() | Qt::WindowMaximized);\n\t} else {\n\t\tparentGUI->setWindowState(\n\t\t\tparentGUI->windowState() & (~Qt::WindowMaximized));\n\t}\n\tsettings.endGroup();\n}\n\nvoid YouMainGUI::SessionManager::saveSession() {\n\tQSettings settings(\"session.txt\", QSettings::IniFormat);\n\t\/\/ TODO(angathorion): Add a function in main gui that calls fills taskIDs\n\t\/\/ array on close.\n\tsettings.beginWriteArray(\"idList\");\n\tfor (int i = 0; i < taskIDs.size(); i++) {\n\t\tsettings.setArrayIndex(i);\n\t\tsettings.setValue(\"ID\", taskIDs.at(i));\n\t}\n\tsettings.endArray();\n\tsettings.beginGroup(\"MainWindow\");\n\tsettings.setValue(\"size\", parentGUI->size());\n\tsettings.setValue(\"pos\", parentGUI->pos());\n\tsettings.setValue(\"maximized\", parentGUI->isMaximized());\n\tsettings.endGroup();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2019 pengjian.uestc @ gmail.com\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is seastar::sharded 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 Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include \"redis\/options.hh\"\n#include \"redis\/protocol_parser.hh\"\n#include \"redis\/query_processor.hh\"\n#include \"redis\/reply.hh\"\n#include \"redis\/request.hh\"\n#include \"redis\/stats.hh\"\n\n#include \"auth\/authenticator.hh\"\n#include \"auth\/service.hh\"\n#include \"cql3\/values.hh\"\n#include \"service\/client_state.hh\"\n#include \"service\/storage_proxy.hh\"\n#include \"service_permit.hh\"\n#include \"timeout_config.hh\"\n#include \"utils\/estimated_histogram.hh\"\n#include \"utils\/fragmented_temporary_buffer.hh\"\n\n#include <seastar\/core\/seastar.hh>\n#include <seastar\/core\/semaphore.hh>\n#include <seastar\/core\/sharded.hh>\n#include <seastar\/net\/tls.hh>\n\n#include <memory>\n\ndb::consistency_level make_consistency_level(const sstring&);\n\nclass redis_exception;\n\nnamespace redis_transport {\n\nstruct redis_server_config {\n ::timeout_config _timeout_config;\n size_t _max_request_size;\n db::consistency_level _read_consistency_level;\n db::consistency_level _write_consistency_level;\n size_t _total_redis_db_count;\n};\n\nclass redis_server {\n std::vector<server_socket> _listeners;\n seastar::sharded<service::storage_proxy>& _proxy;\n seastar::sharded<redis::query_processor>& _query_processor;\n redis_server_config _config;\n size_t _max_request_size;\n semaphore _memory_available;\n redis::stats _stats;\n uint64_t _requests_blocked_memory = 0;\n auth::service& _auth_service;\n size_t _total_redis_db_count;\n\npublic:\n redis_server(seastar::sharded<service::storage_proxy>& proxy, seastar::sharded<redis::query_processor>& qp, auth::service& auth_service, redis_server_config config);\n future<> listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> = {}, bool keepalive = false);\n future<> do_accepts(int which, bool keepalive, socket_address server_addr);\n future<> stop();\n\n struct result {\n result(redis::redis_message&& m) : _data(make_foreign(std::make_unique<redis::redis_message>(std::move(m)))) {}\n foreign_ptr<std::unique_ptr<redis::redis_message>> _data;\n inline lw_shared_ptr<scattered_message<char>> make_message() {\n return _data->message();\n }\n };\n using response_type = result;\n\nprivate:\n friend class connection;\n class connection : public boost::intrusive::list_base_hook<> {\n redis_server& _server;\n socket_address _server_addr;\n connected_socket _fd;\n input_stream<char> _read_buf;\n output_stream<char> _write_buf;\n redis_protocol_parser _parser;\n seastar::gate _pending_requests_gate;\n redis::redis_options _options;\n future<> _ready_to_respond = make_ready_future<>();\n unsigned _request_cpu = 0;\n private:\n enum class tracing_request_type : uint8_t {\n not_requested,\n no_write_on_close,\n write_on_close\n }; \n\n using execution_stage_type = inheriting_concrete_execution_stage<\n future<redis_server::result>,\n redis_server::connection*,\n redis::request&&,\n redis::redis_options&,\n service_permit\n >;\n static thread_local execution_stage_type _process_request_stage;\n public:\n connection(redis_server& server, socket_address server_addr, connected_socket&& fd, socket_address addr);\n ~connection();\n future<> process();\n future<> process_request();\n void write_reply(const redis_exception&);\n void write_reply(redis_server::result result);\n future<> shutdown();\n private:\n const ::timeout_config& timeout_config() { return _server.timeout_config(); }\n friend class process_request_executor;\n future<result> process_request_one(redis::request&& request, redis::redis_options&, service_permit permit);\n future<result> process_request_internal();\n };\n\n bool _stopping = false;\n promise<> _all_connections_stopped;\n future<> _stopped = _all_connections_stopped.get_future();\n boost::intrusive::list<connection> _connections_list;\n\n void maybe_idle() {\n if (_stopping && !_stats._connections_being_accepted && !_stats._current_connections) {\n _all_connections_stopped.set_value();\n }\n }\n const ::timeout_config& timeout_config() { return _config._timeout_config; }\n};\n}\n<commit_msg>redis: Remove unused _request_cpu class member<commit_after>\/*\n * Copyright (C) 2019 pengjian.uestc @ gmail.com\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is seastar::sharded 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 Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include \"redis\/options.hh\"\n#include \"redis\/protocol_parser.hh\"\n#include \"redis\/query_processor.hh\"\n#include \"redis\/reply.hh\"\n#include \"redis\/request.hh\"\n#include \"redis\/stats.hh\"\n\n#include \"auth\/authenticator.hh\"\n#include \"auth\/service.hh\"\n#include \"cql3\/values.hh\"\n#include \"service\/client_state.hh\"\n#include \"service\/storage_proxy.hh\"\n#include \"service_permit.hh\"\n#include \"timeout_config.hh\"\n#include \"utils\/estimated_histogram.hh\"\n#include \"utils\/fragmented_temporary_buffer.hh\"\n\n#include <seastar\/core\/seastar.hh>\n#include <seastar\/core\/semaphore.hh>\n#include <seastar\/core\/sharded.hh>\n#include <seastar\/net\/tls.hh>\n\n#include <memory>\n\ndb::consistency_level make_consistency_level(const sstring&);\n\nclass redis_exception;\n\nnamespace redis_transport {\n\nstruct redis_server_config {\n ::timeout_config _timeout_config;\n size_t _max_request_size;\n db::consistency_level _read_consistency_level;\n db::consistency_level _write_consistency_level;\n size_t _total_redis_db_count;\n};\n\nclass redis_server {\n std::vector<server_socket> _listeners;\n seastar::sharded<service::storage_proxy>& _proxy;\n seastar::sharded<redis::query_processor>& _query_processor;\n redis_server_config _config;\n size_t _max_request_size;\n semaphore _memory_available;\n redis::stats _stats;\n uint64_t _requests_blocked_memory = 0;\n auth::service& _auth_service;\n size_t _total_redis_db_count;\n\npublic:\n redis_server(seastar::sharded<service::storage_proxy>& proxy, seastar::sharded<redis::query_processor>& qp, auth::service& auth_service, redis_server_config config);\n future<> listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> = {}, bool keepalive = false);\n future<> do_accepts(int which, bool keepalive, socket_address server_addr);\n future<> stop();\n\n struct result {\n result(redis::redis_message&& m) : _data(make_foreign(std::make_unique<redis::redis_message>(std::move(m)))) {}\n foreign_ptr<std::unique_ptr<redis::redis_message>> _data;\n inline lw_shared_ptr<scattered_message<char>> make_message() {\n return _data->message();\n }\n };\n using response_type = result;\n\nprivate:\n friend class connection;\n class connection : public boost::intrusive::list_base_hook<> {\n redis_server& _server;\n socket_address _server_addr;\n connected_socket _fd;\n input_stream<char> _read_buf;\n output_stream<char> _write_buf;\n redis_protocol_parser _parser;\n seastar::gate _pending_requests_gate;\n redis::redis_options _options;\n future<> _ready_to_respond = make_ready_future<>();\n private:\n enum class tracing_request_type : uint8_t {\n not_requested,\n no_write_on_close,\n write_on_close\n }; \n\n using execution_stage_type = inheriting_concrete_execution_stage<\n future<redis_server::result>,\n redis_server::connection*,\n redis::request&&,\n redis::redis_options&,\n service_permit\n >;\n static thread_local execution_stage_type _process_request_stage;\n public:\n connection(redis_server& server, socket_address server_addr, connected_socket&& fd, socket_address addr);\n ~connection();\n future<> process();\n future<> process_request();\n void write_reply(const redis_exception&);\n void write_reply(redis_server::result result);\n future<> shutdown();\n private:\n const ::timeout_config& timeout_config() { return _server.timeout_config(); }\n friend class process_request_executor;\n future<result> process_request_one(redis::request&& request, redis::redis_options&, service_permit permit);\n future<result> process_request_internal();\n };\n\n bool _stopping = false;\n promise<> _all_connections_stopped;\n future<> _stopped = _all_connections_stopped.get_future();\n boost::intrusive::list<connection> _connections_list;\n\n void maybe_idle() {\n if (_stopping && !_stats._connections_being_accepted && !_stats._current_connections) {\n _all_connections_stopped.set_value();\n }\n }\n const ::timeout_config& timeout_config() { return _config._timeout_config; }\n};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\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: xmlnamespaces.hxx,v $\n * $Revision: 1.3 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_CLASSES_XMLNAMESPACES_HXX_\n#define __FRAMEWORK_CLASSES_XMLNAMESPACES_HXX_\n\n#include <com\/sun\/star\/xml\/sax\/SAXException.hpp>\n\n#include <map>\n\nnamespace framework\n{\n\nclass XMLNamespaces\n{\n public:\n XMLNamespaces();\n XMLNamespaces( const XMLNamespaces& );\n virtual ~XMLNamespaces();\n\n void addNamespace( const ::rtl::OUString& aName, const ::rtl::OUString& aValue )\n throw( ::com::sun::star::xml::sax::SAXException );\n\n ::rtl::OUString applyNSToAttributeName( const ::rtl::OUString& ) const\n throw( ::com::sun::star::xml::sax::SAXException );\n ::rtl::OUString applyNSToElementName( const ::rtl::OUString& ) const\n throw( ::com::sun::star::xml::sax::SAXException );\n\n private:\n typedef ::std::map< ::rtl::OUString, ::rtl::OUString > NamespaceMap;\n\n ::rtl::OUString getNamespaceValue( const ::rtl::OUString& aNamespace ) const\n throw( ::com::sun::star::xml::sax::SAXException );\n\n ::rtl::OUString m_aDefaultNamespace;\n NamespaceMap m_aNamespaceMap;\n};\n\n}\n\n#endif \/\/ __FRAMEWORK_XMLNAMESPACES_HXX_\n<commit_msg>dtardon01: #i107196#: remove stray header framework\/inc\/classes\/xmlnamespaces.hxx<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (c) 2021 Samsung Electronics Co., Ltd.\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\/\/ CLASS HEADER\n#include <dali-toolkit\/devel-api\/utility\/npatch-utilities.h>\n\n\/\/ EXTERNAL INCLUDES\n#include <dali\/integration-api\/debug.h>\n\nnamespace Dali\n{\nnamespace Toolkit\n{\nnamespace NPatchUtility\n{\nnamespace\n{\nUint16Pair ParseRange(uint32_t& index, uint32_t width, uint8_t*& pixel, uint32_t pixelStride, int32_t testByte, int32_t testBits, int32_t testValue)\n{\n unsigned int start = 0xFFFF;\n for(; index < width; ++index, pixel += pixelStride)\n {\n if((pixel[testByte] & testBits) == testValue)\n {\n start = index;\n ++index;\n pixel += pixelStride;\n break;\n }\n }\n\n unsigned int end = width;\n for(; index < width; ++index, pixel += pixelStride)\n {\n if((pixel[testByte] & testBits) != testValue)\n {\n end = index;\n ++index;\n pixel += pixelStride;\n break;\n }\n }\n\n return Uint16Pair(start, end);\n}\n\n} \/\/ unnamed namespace\n\nvoid GetRedOffsetAndMask(Dali::Pixel::Format pixelFormat, int32_t& byteOffset, int32_t& bitMask)\n{\n switch(pixelFormat)\n {\n case Dali::Pixel::A8:\n case Dali::Pixel::L8:\n case Dali::Pixel::LA88:\n {\n byteOffset = 0;\n bitMask = 0;\n break;\n }\n case Dali::Pixel::RGB888:\n case Dali::Pixel::RGB8888:\n case Dali::Pixel::RGBA8888:\n {\n byteOffset = 0;\n bitMask = 0xFF;\n break;\n }\n case Dali::Pixel::BGR8888:\n case Dali::Pixel::BGRA8888:\n {\n byteOffset = 2;\n bitMask = 0xff;\n break;\n }\n case Dali::Pixel::RGB565:\n {\n byteOffset = 0;\n bitMask = 0xf8;\n break;\n }\n case Dali::Pixel::BGR565:\n {\n byteOffset = 1;\n bitMask = 0x1f;\n break;\n }\n case Dali::Pixel::RGBA4444:\n {\n byteOffset = 0;\n bitMask = 0xf0;\n break;\n }\n case Dali::Pixel::BGRA4444:\n {\n byteOffset = 1;\n bitMask = 0xf0;\n break;\n }\n case Dali::Pixel::RGBA5551:\n {\n byteOffset = 0;\n bitMask = 0xf8;\n break;\n }\n case Dali::Pixel::BGRA5551:\n {\n byteOffset = 1;\n bitMask = 0x1e;\n break;\n }\n case Dali::Pixel::INVALID:\n case Dali::Pixel::COMPRESSED_R11_EAC:\n case Dali::Pixel::COMPRESSED_SIGNED_R11_EAC:\n case Dali::Pixel::COMPRESSED_RG11_EAC:\n case Dali::Pixel::COMPRESSED_SIGNED_RG11_EAC:\n case Dali::Pixel::COMPRESSED_RGB8_ETC2:\n case Dali::Pixel::COMPRESSED_SRGB8_ETC2:\n case Dali::Pixel::COMPRESSED_RGB8_ETC1:\n case Dali::Pixel::COMPRESSED_RGB_PVRTC_4BPPV1:\n case Dali::Pixel::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:\n case Dali::Pixel::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:\n case Dali::Pixel::COMPRESSED_RGBA8_ETC2_EAC:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:\n {\n DALI_LOG_ERROR(\"Pixel formats for compressed images are not compatible with simple masking-out of per-pixel alpha.\\n\");\n byteOffset = 0;\n bitMask = 0;\n break;\n }\n case Dali::Pixel::RGB16F:\n case Dali::Pixel::RGB32F:\n case Dali::Pixel::DEPTH_UNSIGNED_INT:\n case Dali::Pixel::DEPTH_FLOAT:\n case Dali::Pixel::DEPTH_STENCIL:\n case Dali::Pixel::R11G11B10F:\n {\n DALI_LOG_ERROR(\"Pixel format not compatible.\\n\");\n byteOffset = 0;\n bitMask = 0;\n break;\n }\n }\n}\n\nvoid ParseBorders(Devel::PixelBuffer& pixelBuffer, StretchRanges& stretchPixelsX, StretchRanges& stretchPixelsY)\n{\n stretchPixelsX.Clear();\n stretchPixelsY.Clear();\n\n Pixel::Format pixelFormat = pixelBuffer.GetPixelFormat();\n\n int32_t alphaByte = 0;\n int32_t alphaBits = 0;\n Pixel::GetAlphaOffsetAndMask(pixelFormat, alphaByte, alphaBits);\n\n int32_t testByte = alphaByte;\n int32_t testBits = alphaBits;\n int32_t testValue = alphaBits; \/\/ Opaque == stretch\n if(!alphaBits)\n {\n GetRedOffsetAndMask(pixelFormat, testByte, testBits);\n testValue = 0; \/\/ Black == stretch\n }\n\n uint32_t bytesPerPixel = Pixel::GetBytesPerPixel(pixelFormat);\n uint32_t width = pixelBuffer.GetWidth();\n uint32_t height = pixelBuffer.GetHeight();\n uint8_t* srcPixels = pixelBuffer.GetBuffer();\n uint32_t srcStride = width * bytesPerPixel;\n\n \/\/ TOP\n uint8_t* top = srcPixels + bytesPerPixel;\n uint32_t index = 0;\n\n for(; index < width - 2;)\n {\n Uint16Pair range = ParseRange(index, width - 2, top, bytesPerPixel, testByte, testBits, testValue);\n if(range.GetX() != 0xFFFF)\n {\n stretchPixelsX.PushBack(range);\n }\n }\n\n \/\/ LEFT\n uint8_t* left = srcPixels + srcStride;\n index = 0;\n for(; index < height - 2;)\n {\n Uint16Pair range = ParseRange(index, height - 2, left, srcStride, testByte, testBits, testValue);\n if(range.GetX() != 0xFFFF)\n {\n stretchPixelsY.PushBack(range);\n }\n }\n\n \/\/ If there are no stretch pixels then make the entire image stretchable\n if(stretchPixelsX.Size() == 0)\n {\n stretchPixelsX.PushBack(Uint16Pair(0, width - 2));\n }\n if(stretchPixelsY.Size() == 0)\n {\n stretchPixelsY.PushBack(Uint16Pair(0, height - 2));\n }\n}\n\nbool IsNinePatchUrl(const std::string& url)\n{\n bool match = false;\n\n std::string::const_reverse_iterator iter = url.rbegin();\n enum\n {\n SUFFIX,\n HASH,\n HASH_DOT,\n DONE\n } state = SUFFIX;\n while(iter < url.rend())\n {\n switch(state)\n {\n case SUFFIX:\n {\n if(*iter == '.')\n {\n state = HASH;\n }\n else if(!isalnum(*iter))\n {\n state = DONE;\n }\n }\n break;\n case HASH:\n {\n if(*iter == '#' || *iter == '9')\n {\n state = HASH_DOT;\n }\n else\n {\n state = DONE;\n }\n }\n break;\n case HASH_DOT:\n {\n if(*iter == '.')\n {\n match = true;\n }\n state = DONE; \/\/ Stop testing characters\n }\n break;\n case DONE:\n {\n }\n break;\n }\n\n \/\/ Satisfy prevent\n if(state == DONE)\n {\n break;\n }\n\n ++iter;\n }\n return match;\n}\n\n} \/\/ namespace NPatchUtility\n\n} \/\/ namespace Toolkit\n\n} \/\/ namespace Dali\n<commit_msg>Add CHROMINANCE pixel format<commit_after>\/*\n* Copyright (c) 2022 Samsung Electronics Co., Ltd.\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\/\/ CLASS HEADER\n#include <dali-toolkit\/devel-api\/utility\/npatch-utilities.h>\n\n\/\/ EXTERNAL INCLUDES\n#include <dali\/integration-api\/debug.h>\n\nnamespace Dali\n{\nnamespace Toolkit\n{\nnamespace NPatchUtility\n{\nnamespace\n{\nUint16Pair ParseRange(uint32_t& index, uint32_t width, uint8_t*& pixel, uint32_t pixelStride, int32_t testByte, int32_t testBits, int32_t testValue)\n{\n unsigned int start = 0xFFFF;\n for(; index < width; ++index, pixel += pixelStride)\n {\n if((pixel[testByte] & testBits) == testValue)\n {\n start = index;\n ++index;\n pixel += pixelStride;\n break;\n }\n }\n\n unsigned int end = width;\n for(; index < width; ++index, pixel += pixelStride)\n {\n if((pixel[testByte] & testBits) != testValue)\n {\n end = index;\n ++index;\n pixel += pixelStride;\n break;\n }\n }\n\n return Uint16Pair(start, end);\n}\n\n} \/\/ unnamed namespace\n\nvoid GetRedOffsetAndMask(Dali::Pixel::Format pixelFormat, int32_t& byteOffset, int32_t& bitMask)\n{\n switch(pixelFormat)\n {\n case Dali::Pixel::A8:\n case Dali::Pixel::L8:\n case Dali::Pixel::LA88:\n {\n byteOffset = 0;\n bitMask = 0;\n break;\n }\n case Dali::Pixel::RGB888:\n case Dali::Pixel::RGB8888:\n case Dali::Pixel::RGBA8888:\n {\n byteOffset = 0;\n bitMask = 0xFF;\n break;\n }\n case Dali::Pixel::BGR8888:\n case Dali::Pixel::BGRA8888:\n {\n byteOffset = 2;\n bitMask = 0xff;\n break;\n }\n case Dali::Pixel::RGB565:\n {\n byteOffset = 0;\n bitMask = 0xf8;\n break;\n }\n case Dali::Pixel::BGR565:\n {\n byteOffset = 1;\n bitMask = 0x1f;\n break;\n }\n case Dali::Pixel::RGBA4444:\n {\n byteOffset = 0;\n bitMask = 0xf0;\n break;\n }\n case Dali::Pixel::BGRA4444:\n {\n byteOffset = 1;\n bitMask = 0xf0;\n break;\n }\n case Dali::Pixel::RGBA5551:\n {\n byteOffset = 0;\n bitMask = 0xf8;\n break;\n }\n case Dali::Pixel::BGRA5551:\n {\n byteOffset = 1;\n bitMask = 0x1e;\n break;\n }\n case Dali::Pixel::INVALID:\n case Dali::Pixel::COMPRESSED_R11_EAC:\n case Dali::Pixel::COMPRESSED_SIGNED_R11_EAC:\n case Dali::Pixel::COMPRESSED_RG11_EAC:\n case Dali::Pixel::COMPRESSED_SIGNED_RG11_EAC:\n case Dali::Pixel::COMPRESSED_RGB8_ETC2:\n case Dali::Pixel::COMPRESSED_SRGB8_ETC2:\n case Dali::Pixel::COMPRESSED_RGB8_ETC1:\n case Dali::Pixel::COMPRESSED_RGB_PVRTC_4BPPV1:\n case Dali::Pixel::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:\n case Dali::Pixel::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:\n case Dali::Pixel::COMPRESSED_RGBA8_ETC2_EAC:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR:\n case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:\n case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:\n {\n DALI_LOG_ERROR(\"Pixel formats for compressed images are not compatible with simple masking-out of per-pixel alpha.\\n\");\n byteOffset = 0;\n bitMask = 0;\n break;\n }\n case Dali::Pixel::RGB16F:\n case Dali::Pixel::RGB32F:\n case Dali::Pixel::DEPTH_UNSIGNED_INT:\n case Dali::Pixel::DEPTH_FLOAT:\n case Dali::Pixel::DEPTH_STENCIL:\n case Dali::Pixel::R11G11B10F:\n case Dali::Pixel::CHROMINANCE_U:\n case Dali::Pixel::CHROMINANCE_V:\n {\n DALI_LOG_ERROR(\"Pixel format not compatible.\\n\");\n byteOffset = 0;\n bitMask = 0;\n break;\n }\n }\n}\n\nvoid ParseBorders(Devel::PixelBuffer& pixelBuffer, StretchRanges& stretchPixelsX, StretchRanges& stretchPixelsY)\n{\n stretchPixelsX.Clear();\n stretchPixelsY.Clear();\n\n Pixel::Format pixelFormat = pixelBuffer.GetPixelFormat();\n\n int32_t alphaByte = 0;\n int32_t alphaBits = 0;\n Pixel::GetAlphaOffsetAndMask(pixelFormat, alphaByte, alphaBits);\n\n int32_t testByte = alphaByte;\n int32_t testBits = alphaBits;\n int32_t testValue = alphaBits; \/\/ Opaque == stretch\n if(!alphaBits)\n {\n GetRedOffsetAndMask(pixelFormat, testByte, testBits);\n testValue = 0; \/\/ Black == stretch\n }\n\n uint32_t bytesPerPixel = Pixel::GetBytesPerPixel(pixelFormat);\n uint32_t width = pixelBuffer.GetWidth();\n uint32_t height = pixelBuffer.GetHeight();\n uint8_t* srcPixels = pixelBuffer.GetBuffer();\n uint32_t srcStride = width * bytesPerPixel;\n\n \/\/ TOP\n uint8_t* top = srcPixels + bytesPerPixel;\n uint32_t index = 0;\n\n for(; index < width - 2;)\n {\n Uint16Pair range = ParseRange(index, width - 2, top, bytesPerPixel, testByte, testBits, testValue);\n if(range.GetX() != 0xFFFF)\n {\n stretchPixelsX.PushBack(range);\n }\n }\n\n \/\/ LEFT\n uint8_t* left = srcPixels + srcStride;\n index = 0;\n for(; index < height - 2;)\n {\n Uint16Pair range = ParseRange(index, height - 2, left, srcStride, testByte, testBits, testValue);\n if(range.GetX() != 0xFFFF)\n {\n stretchPixelsY.PushBack(range);\n }\n }\n\n \/\/ If there are no stretch pixels then make the entire image stretchable\n if(stretchPixelsX.Size() == 0)\n {\n stretchPixelsX.PushBack(Uint16Pair(0, width - 2));\n }\n if(stretchPixelsY.Size() == 0)\n {\n stretchPixelsY.PushBack(Uint16Pair(0, height - 2));\n }\n}\n\nbool IsNinePatchUrl(const std::string& url)\n{\n bool match = false;\n\n std::string::const_reverse_iterator iter = url.rbegin();\n enum\n {\n SUFFIX,\n HASH,\n HASH_DOT,\n DONE\n } state = SUFFIX;\n while(iter < url.rend())\n {\n switch(state)\n {\n case SUFFIX:\n {\n if(*iter == '.')\n {\n state = HASH;\n }\n else if(!isalnum(*iter))\n {\n state = DONE;\n }\n }\n break;\n case HASH:\n {\n if(*iter == '#' || *iter == '9')\n {\n state = HASH_DOT;\n }\n else\n {\n state = DONE;\n }\n }\n break;\n case HASH_DOT:\n {\n if(*iter == '.')\n {\n match = true;\n }\n state = DONE; \/\/ Stop testing characters\n }\n break;\n case DONE:\n {\n }\n break;\n }\n\n \/\/ Satisfy prevent\n if(state == DONE)\n {\n break;\n }\n\n ++iter;\n }\n return match;\n}\n\n} \/\/ namespace NPatchUtility\n\n} \/\/ namespace Toolkit\n\n} \/\/ namespace Dali\n<|endoftext|>"} {"text":"<commit_before><commit_msg>INTEGRATION: CWS xmlfilter04 (1.5.4); FILE MERGED 2008\/03\/19 14:32:12 hbrinkm 1.5.4.8: RESYNC: (1.5-1.6); FILE MERGED 2008\/03\/12 13:53:26 hbrinkm 1.5.4.7: propagateCharacterPropertiesAsSet 2008\/03\/06 08:57:53 os 1.5.4.6: virtual d'tor 2008\/03\/06 08:20:00 hbrinkm 1.5.4.5: removed debug code, use getTarget on OOXMLDocument to set relation path for ShapeHandler 2008\/03\/04 13:40:50 hbrinkm 1.5.4.4: use XMLTags for debug output, OOXMLFastContextWrapper 2008\/02\/27 08:56:21 hbrinkm 1.5.4.3: OOXMLFastContexHandlerWrapper 2008\/02\/26 08:39:18 hbrinkm 1.5.4.2: additionally use type of footnote\/endnote to specify which footnote\/endnote to use 2008\/02\/21 12:33:25 hbrinkm 1.5.4.1: joined changes from xmlfilter03<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ 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\/browser\/ui\/panels\/panel_manager.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/browser\/ui\/panels\/detached_panel_strip.h\"\n#include \"chrome\/browser\/ui\/panels\/docked_panel_strip.h\"\n#include \"chrome\/browser\/ui\/panels\/panel_drag_controller.h\"\n#include \"chrome\/browser\/ui\/panels\/panel_mouse_watcher.h\"\n#include \"chrome\/browser\/ui\/panels\/panel_resize_controller.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n\n#if defined(TOOLKIT_GTK)\n#include \"ui\/base\/x\/x11_util.h\"\n#endif\n\nnamespace {\n\/\/ Width of spacing around panel strip and the left\/right edges of the screen.\nconst int kPanelStripLeftMargin = 6;\nconst int kPanelStripRightMargin = 24;\n\n\/\/ Maxmium width of a panel is based on a factor of the working area.\n#if defined(OS_CHROMEOS)\n\/\/ ChromeOS device screens are relatively small and limiting the width\n\/\/ interferes with some apps (e.g. http:\/\/crbug.com\/111121).\nconst double kPanelMaxWidthFactor = 0.80;\n#else\nconst double kPanelMaxWidthFactor = 0.35;\n#endif\n\n\/\/ Maxmium height of a panel is based on a factor of the working area.\nconst double kPanelMaxHeightFactor = 0.5;\n} \/\/ namespace\n\n\/\/ static\nbool PanelManager::shorten_time_intervals_ = false;\n\n\/\/ static\nPanelManager* PanelManager::GetInstance() {\n static base::LazyInstance<PanelManager> instance = LAZY_INSTANCE_INITIALIZER;\n return instance.Pointer();\n}\n\n\/\/ static\nbool PanelManager::ShouldUsePanels(const std::string& extension_id) {\n#if defined(TOOLKIT_GTK)\n \/\/ Panels are only supported on a white list of window managers for Linux.\n ui::WindowManagerName wm_type = ui::GuessWindowManager();\n if (wm_type != ui::WM_COMPIZ &&\n wm_type != ui::WM_ICE_WM &&\n wm_type != ui::WM_KWIN &&\n wm_type != ui::WM_METACITY &&\n wm_type != ui::WM_MUTTER) {\n return false;\n }\n#endif \/\/ TOOLKIT_GTK\n\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n return CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnablePanels) ||\n extension_id == std::string(\"nckgahadagoaajjgafhacjanaoiihapd\") ||\n extension_id == std::string(\"ljclpkphhpbpinifbeabbhlfddcpfdde\") ||\n extension_id == std::string(\"ppleadejekpmccmnpjdimmlfljlkdfej\") ||\n extension_id == std::string(\"eggnbpckecmjlblplehfpjjdhhidfdoj\");\n }\n\n return true;\n}\n\nPanelManager::PanelManager()\n : panel_mouse_watcher_(PanelMouseWatcher::Create()),\n auto_sizing_enabled_(true) {\n \/\/ DisplaySettingsProvider should be created before the creation of strips\n \/\/ since some strip might depend on it.\n display_settings_provider_.reset(DisplaySettingsProvider::Create());\n display_settings_provider_->AddDisplayAreaObserver(this);\n\n detached_strip_.reset(new DetachedPanelStrip(this));\n docked_strip_.reset(new DockedPanelStrip(this));\n drag_controller_.reset(new PanelDragController(this));\n resize_controller_.reset(new PanelResizeController(this));\n}\n\nPanelManager::~PanelManager() {\n display_settings_provider_->RemoveDisplayAreaObserver(this);\n\n \/\/ Docked strip should be disposed explicitly before DisplaySettingsProvider\n \/\/ is gone since docked strip needs to remove the observer from\n \/\/ DisplaySettingsProvider.\n docked_strip_.reset();\n}\n\nvoid PanelManager::OnDisplayAreaChanged(const gfx::Rect& display_area) {\n if (display_area == display_area_)\n return;\n display_area_ = display_area;\n\n gfx::Rect docked_strip_bounds = display_area;\n docked_strip_bounds.set_x(display_area.x() + kPanelStripLeftMargin);\n docked_strip_bounds.set_width(display_area.width() -\n kPanelStripLeftMargin - kPanelStripRightMargin);\n docked_strip_->SetDisplayArea(docked_strip_bounds);\n\n detached_strip_->SetDisplayArea(display_area);\n}\n\nvoid PanelManager::OnFullScreenModeChanged(bool is_full_screen) {\n docked_strip_->OnFullScreenModeChanged(is_full_screen);\n}\n\nint PanelManager::GetMaxPanelWidth() const {\n return static_cast<int>(display_area_.width() * kPanelMaxWidthFactor);\n}\n\nint PanelManager::GetMaxPanelHeight() const {\n return display_area_.height() * kPanelMaxHeightFactor;\n}\n\nPanel* PanelManager::CreatePanel(Browser* browser) {\n \/\/ Need to sync the display area if no panel is present. This is because:\n \/\/ 1) Display area is not initialized until first panel is created.\n \/\/ 2) On windows, display settings notification is tied to a window. When\n \/\/ display settings are changed at the time that no panel exists, we do\n \/\/ not receive any notification.\n if (num_panels() == 0)\n display_settings_provider_->OnDisplaySettingsChanged();\n\n int width = browser->override_bounds().width();\n int height = browser->override_bounds().height();\n Panel* panel = new Panel(browser, gfx::Size(width, height));\n docked_strip_->AddPanel(panel, PanelStrip::DEFAULT_POSITION);\n docked_strip_->UpdatePanelOnStripChange(panel);\n\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_PANEL_ADDED,\n content::Source<Panel>(panel),\n content::NotificationService::NoDetails());\n\n if (num_panels() == 1) {\n display_settings_provider_->AddFullScreenObserver(this);\n }\n\n return panel;\n}\n\nvoid PanelManager::OnPanelClosed(Panel* panel) {\n if (num_panels() == 1) {\n display_settings_provider_->RemoveFullScreenObserver(this);\n }\n\n drag_controller_->OnPanelClosed(panel);\n resize_controller_->OnPanelClosed(panel);\n panel->panel_strip()->RemovePanel(panel);\n\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_PANEL_CLOSED,\n content::Source<Panel>(panel),\n content::NotificationService::NoDetails());\n}\n\nvoid PanelManager::StartDragging(Panel* panel,\n const gfx::Point& mouse_location) {\n drag_controller_->StartDragging(panel, mouse_location);\n}\n\nvoid PanelManager::Drag(const gfx::Point& mouse_location) {\n drag_controller_->Drag(mouse_location);\n}\n\nvoid PanelManager::EndDragging(bool cancelled) {\n drag_controller_->EndDragging(cancelled);\n}\n\nvoid PanelManager::StartResizingByMouse(Panel* panel,\n const gfx::Point& mouse_location,\n panel::ResizingSides sides) {\n if (panel->CanResizeByMouse() != panel::NOT_RESIZABLE &&\n sides != panel::RESIZE_NONE)\n resize_controller_->StartResizing(panel, mouse_location, sides);\n}\n\nvoid PanelManager::ResizeByMouse(const gfx::Point& mouse_location) {\n if (resize_controller_->IsResizing())\n resize_controller_->Resize(mouse_location);\n}\n\nvoid PanelManager::EndResizingByMouse(bool cancelled) {\n if (resize_controller_->IsResizing()) {\n Panel* resized_panel = resize_controller_->EndResizing(cancelled);\n if (!cancelled && resized_panel->panel_strip())\n resized_panel->panel_strip()->RefreshLayout();\n }\n}\n\nvoid PanelManager::OnPanelExpansionStateChanged(Panel* panel) {\n \/\/ For panels outside of the docked strip changing state is a no-op.\n \/\/ But since this method may be called for panels in other strips\n \/\/ we need to check this condition.\n if (panel->panel_strip() == docked_strip_.get())\n docked_strip_->OnPanelExpansionStateChanged(panel);\n\n}\n\nvoid PanelManager::OnWindowAutoResized(Panel* panel,\n const gfx::Size& preferred_window_size) {\n DCHECK(auto_sizing_enabled_);\n panel->panel_strip()->ResizePanelWindow(panel, preferred_window_size);\n}\n\nvoid PanelManager::ResizePanel(Panel* panel, const gfx::Size& new_size) {\n PanelStrip* panel_strip = panel->panel_strip();\n if (!panel_strip)\n return;\n panel_strip->ResizePanelWindow(panel, new_size);\n panel->SetAutoResizable(false);\n}\n\nvoid PanelManager::OnPanelResizedByMouse(Panel* panel,\n const gfx::Rect& new_bounds) {\n panel->panel_strip()->OnPanelResizedByMouse(panel, new_bounds);\n}\n\nvoid PanelManager::MovePanelToStrip(\n Panel* panel,\n PanelStrip::Type new_layout,\n PanelStrip::PositioningMask positioning_mask) {\n DCHECK(panel);\n PanelStrip* current_strip = panel->panel_strip();\n DCHECK(current_strip);\n DCHECK_NE(current_strip->type(), new_layout);\n current_strip->RemovePanel(panel);\n\n PanelStrip* target_strip = NULL;\n switch (new_layout) {\n case PanelStrip::DETACHED:\n target_strip = detached_strip_.get();\n break;\n case PanelStrip::DOCKED:\n target_strip = docked_strip_.get();\n break;\n default:\n NOTREACHED();\n }\n\n target_strip->AddPanel(panel, positioning_mask);\n target_strip->UpdatePanelOnStripChange(panel);\n}\n\nbool PanelManager::ShouldBringUpTitlebars(int mouse_x, int mouse_y) const {\n return docked_strip_->ShouldBringUpTitlebars(mouse_x, mouse_y);\n}\n\nvoid PanelManager::BringUpOrDownTitlebars(bool bring_up) {\n docked_strip_->BringUpOrDownTitlebars(bring_up);\n}\n\nBrowserWindow* PanelManager::GetNextBrowserWindowToActivate(\n Panel* panel) const {\n \/\/ Find the last active browser window that is not minimized.\n BrowserList::const_reverse_iterator iter = BrowserList::begin_last_active();\n BrowserList::const_reverse_iterator end = BrowserList::end_last_active();\n for (; (iter != end); ++iter) {\n Browser* browser = *iter;\n if (panel->browser() != browser && !browser->window()->IsMinimized())\n return browser->window();\n }\n\n return NULL;\n}\n\nvoid PanelManager::CloseAll() {\n DCHECK(!drag_controller_->IsDragging());\n\n detached_strip_->CloseAll();\n docked_strip_->CloseAll();\n}\n\nint PanelManager::num_panels() const {\n return detached_strip_->num_panels() + docked_strip_->num_panels();\n}\n\nstd::vector<Panel*> PanelManager::panels() const {\n std::vector<Panel*> panels;\n for (DetachedPanelStrip::Panels::const_iterator iter =\n detached_strip_->panels().begin();\n iter != detached_strip_->panels().end(); ++iter)\n panels.push_back(*iter);\n for (DockedPanelStrip::Panels::const_iterator iter =\n docked_strip_->panels().begin();\n iter != docked_strip_->panels().end(); ++iter)\n panels.push_back(*iter);\n return panels;\n}\n\nvoid PanelManager::SetMouseWatcher(PanelMouseWatcher* watcher) {\n panel_mouse_watcher_.reset(watcher);\n}\n\nvoid PanelManager::OnPanelAnimationEnded(Panel* panel) {\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_PANEL_BOUNDS_ANIMATIONS_FINISHED,\n content::Source<Panel>(panel),\n content::NotificationService::NoDetails());\n}\n\n<commit_msg>Use panels instead of popups on XFCE.<commit_after>\/\/ 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\/browser\/ui\/panels\/panel_manager.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/browser\/ui\/panels\/detached_panel_strip.h\"\n#include \"chrome\/browser\/ui\/panels\/docked_panel_strip.h\"\n#include \"chrome\/browser\/ui\/panels\/panel_drag_controller.h\"\n#include \"chrome\/browser\/ui\/panels\/panel_mouse_watcher.h\"\n#include \"chrome\/browser\/ui\/panels\/panel_resize_controller.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n\n#if defined(TOOLKIT_GTK)\n#include \"ui\/base\/x\/x11_util.h\"\n#endif\n\nnamespace {\n\/\/ Width of spacing around panel strip and the left\/right edges of the screen.\nconst int kPanelStripLeftMargin = 6;\nconst int kPanelStripRightMargin = 24;\n\n\/\/ Maxmium width of a panel is based on a factor of the working area.\n#if defined(OS_CHROMEOS)\n\/\/ ChromeOS device screens are relatively small and limiting the width\n\/\/ interferes with some apps (e.g. http:\/\/crbug.com\/111121).\nconst double kPanelMaxWidthFactor = 0.80;\n#else\nconst double kPanelMaxWidthFactor = 0.35;\n#endif\n\n\/\/ Maxmium height of a panel is based on a factor of the working area.\nconst double kPanelMaxHeightFactor = 0.5;\n} \/\/ namespace\n\n\/\/ static\nbool PanelManager::shorten_time_intervals_ = false;\n\n\/\/ static\nPanelManager* PanelManager::GetInstance() {\n static base::LazyInstance<PanelManager> instance = LAZY_INSTANCE_INITIALIZER;\n return instance.Pointer();\n}\n\n\/\/ static\nbool PanelManager::ShouldUsePanels(const std::string& extension_id) {\n#if defined(TOOLKIT_GTK)\n \/\/ Panels are only supported on a white list of window managers for Linux.\n ui::WindowManagerName wm_type = ui::GuessWindowManager();\n if (wm_type != ui::WM_COMPIZ &&\n wm_type != ui::WM_ICE_WM &&\n wm_type != ui::WM_KWIN &&\n wm_type != ui::WM_METACITY &&\n wm_type != ui::WM_MUTTER &&\n wm_type != ui::WM_XFWM4) {\n return false;\n }\n#endif \/\/ TOOLKIT_GTK\n\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n return CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnablePanels) ||\n extension_id == std::string(\"nckgahadagoaajjgafhacjanaoiihapd\") ||\n extension_id == std::string(\"ljclpkphhpbpinifbeabbhlfddcpfdde\") ||\n extension_id == std::string(\"ppleadejekpmccmnpjdimmlfljlkdfej\") ||\n extension_id == std::string(\"eggnbpckecmjlblplehfpjjdhhidfdoj\");\n }\n\n return true;\n}\n\nPanelManager::PanelManager()\n : panel_mouse_watcher_(PanelMouseWatcher::Create()),\n auto_sizing_enabled_(true) {\n \/\/ DisplaySettingsProvider should be created before the creation of strips\n \/\/ since some strip might depend on it.\n display_settings_provider_.reset(DisplaySettingsProvider::Create());\n display_settings_provider_->AddDisplayAreaObserver(this);\n\n detached_strip_.reset(new DetachedPanelStrip(this));\n docked_strip_.reset(new DockedPanelStrip(this));\n drag_controller_.reset(new PanelDragController(this));\n resize_controller_.reset(new PanelResizeController(this));\n}\n\nPanelManager::~PanelManager() {\n display_settings_provider_->RemoveDisplayAreaObserver(this);\n\n \/\/ Docked strip should be disposed explicitly before DisplaySettingsProvider\n \/\/ is gone since docked strip needs to remove the observer from\n \/\/ DisplaySettingsProvider.\n docked_strip_.reset();\n}\n\nvoid PanelManager::OnDisplayAreaChanged(const gfx::Rect& display_area) {\n if (display_area == display_area_)\n return;\n display_area_ = display_area;\n\n gfx::Rect docked_strip_bounds = display_area;\n docked_strip_bounds.set_x(display_area.x() + kPanelStripLeftMargin);\n docked_strip_bounds.set_width(display_area.width() -\n kPanelStripLeftMargin - kPanelStripRightMargin);\n docked_strip_->SetDisplayArea(docked_strip_bounds);\n\n detached_strip_->SetDisplayArea(display_area);\n}\n\nvoid PanelManager::OnFullScreenModeChanged(bool is_full_screen) {\n docked_strip_->OnFullScreenModeChanged(is_full_screen);\n}\n\nint PanelManager::GetMaxPanelWidth() const {\n return static_cast<int>(display_area_.width() * kPanelMaxWidthFactor);\n}\n\nint PanelManager::GetMaxPanelHeight() const {\n return display_area_.height() * kPanelMaxHeightFactor;\n}\n\nPanel* PanelManager::CreatePanel(Browser* browser) {\n \/\/ Need to sync the display area if no panel is present. This is because:\n \/\/ 1) Display area is not initialized until first panel is created.\n \/\/ 2) On windows, display settings notification is tied to a window. When\n \/\/ display settings are changed at the time that no panel exists, we do\n \/\/ not receive any notification.\n if (num_panels() == 0)\n display_settings_provider_->OnDisplaySettingsChanged();\n\n int width = browser->override_bounds().width();\n int height = browser->override_bounds().height();\n Panel* panel = new Panel(browser, gfx::Size(width, height));\n docked_strip_->AddPanel(panel, PanelStrip::DEFAULT_POSITION);\n docked_strip_->UpdatePanelOnStripChange(panel);\n\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_PANEL_ADDED,\n content::Source<Panel>(panel),\n content::NotificationService::NoDetails());\n\n if (num_panels() == 1) {\n display_settings_provider_->AddFullScreenObserver(this);\n }\n\n return panel;\n}\n\nvoid PanelManager::OnPanelClosed(Panel* panel) {\n if (num_panels() == 1) {\n display_settings_provider_->RemoveFullScreenObserver(this);\n }\n\n drag_controller_->OnPanelClosed(panel);\n resize_controller_->OnPanelClosed(panel);\n panel->panel_strip()->RemovePanel(panel);\n\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_PANEL_CLOSED,\n content::Source<Panel>(panel),\n content::NotificationService::NoDetails());\n}\n\nvoid PanelManager::StartDragging(Panel* panel,\n const gfx::Point& mouse_location) {\n drag_controller_->StartDragging(panel, mouse_location);\n}\n\nvoid PanelManager::Drag(const gfx::Point& mouse_location) {\n drag_controller_->Drag(mouse_location);\n}\n\nvoid PanelManager::EndDragging(bool cancelled) {\n drag_controller_->EndDragging(cancelled);\n}\n\nvoid PanelManager::StartResizingByMouse(Panel* panel,\n const gfx::Point& mouse_location,\n panel::ResizingSides sides) {\n if (panel->CanResizeByMouse() != panel::NOT_RESIZABLE &&\n sides != panel::RESIZE_NONE)\n resize_controller_->StartResizing(panel, mouse_location, sides);\n}\n\nvoid PanelManager::ResizeByMouse(const gfx::Point& mouse_location) {\n if (resize_controller_->IsResizing())\n resize_controller_->Resize(mouse_location);\n}\n\nvoid PanelManager::EndResizingByMouse(bool cancelled) {\n if (resize_controller_->IsResizing()) {\n Panel* resized_panel = resize_controller_->EndResizing(cancelled);\n if (!cancelled && resized_panel->panel_strip())\n resized_panel->panel_strip()->RefreshLayout();\n }\n}\n\nvoid PanelManager::OnPanelExpansionStateChanged(Panel* panel) {\n \/\/ For panels outside of the docked strip changing state is a no-op.\n \/\/ But since this method may be called for panels in other strips\n \/\/ we need to check this condition.\n if (panel->panel_strip() == docked_strip_.get())\n docked_strip_->OnPanelExpansionStateChanged(panel);\n\n}\n\nvoid PanelManager::OnWindowAutoResized(Panel* panel,\n const gfx::Size& preferred_window_size) {\n DCHECK(auto_sizing_enabled_);\n panel->panel_strip()->ResizePanelWindow(panel, preferred_window_size);\n}\n\nvoid PanelManager::ResizePanel(Panel* panel, const gfx::Size& new_size) {\n PanelStrip* panel_strip = panel->panel_strip();\n if (!panel_strip)\n return;\n panel_strip->ResizePanelWindow(panel, new_size);\n panel->SetAutoResizable(false);\n}\n\nvoid PanelManager::OnPanelResizedByMouse(Panel* panel,\n const gfx::Rect& new_bounds) {\n panel->panel_strip()->OnPanelResizedByMouse(panel, new_bounds);\n}\n\nvoid PanelManager::MovePanelToStrip(\n Panel* panel,\n PanelStrip::Type new_layout,\n PanelStrip::PositioningMask positioning_mask) {\n DCHECK(panel);\n PanelStrip* current_strip = panel->panel_strip();\n DCHECK(current_strip);\n DCHECK_NE(current_strip->type(), new_layout);\n current_strip->RemovePanel(panel);\n\n PanelStrip* target_strip = NULL;\n switch (new_layout) {\n case PanelStrip::DETACHED:\n target_strip = detached_strip_.get();\n break;\n case PanelStrip::DOCKED:\n target_strip = docked_strip_.get();\n break;\n default:\n NOTREACHED();\n }\n\n target_strip->AddPanel(panel, positioning_mask);\n target_strip->UpdatePanelOnStripChange(panel);\n}\n\nbool PanelManager::ShouldBringUpTitlebars(int mouse_x, int mouse_y) const {\n return docked_strip_->ShouldBringUpTitlebars(mouse_x, mouse_y);\n}\n\nvoid PanelManager::BringUpOrDownTitlebars(bool bring_up) {\n docked_strip_->BringUpOrDownTitlebars(bring_up);\n}\n\nBrowserWindow* PanelManager::GetNextBrowserWindowToActivate(\n Panel* panel) const {\n \/\/ Find the last active browser window that is not minimized.\n BrowserList::const_reverse_iterator iter = BrowserList::begin_last_active();\n BrowserList::const_reverse_iterator end = BrowserList::end_last_active();\n for (; (iter != end); ++iter) {\n Browser* browser = *iter;\n if (panel->browser() != browser && !browser->window()->IsMinimized())\n return browser->window();\n }\n\n return NULL;\n}\n\nvoid PanelManager::CloseAll() {\n DCHECK(!drag_controller_->IsDragging());\n\n detached_strip_->CloseAll();\n docked_strip_->CloseAll();\n}\n\nint PanelManager::num_panels() const {\n return detached_strip_->num_panels() + docked_strip_->num_panels();\n}\n\nstd::vector<Panel*> PanelManager::panels() const {\n std::vector<Panel*> panels;\n for (DetachedPanelStrip::Panels::const_iterator iter =\n detached_strip_->panels().begin();\n iter != detached_strip_->panels().end(); ++iter)\n panels.push_back(*iter);\n for (DockedPanelStrip::Panels::const_iterator iter =\n docked_strip_->panels().begin();\n iter != docked_strip_->panels().end(); ++iter)\n panels.push_back(*iter);\n return panels;\n}\n\nvoid PanelManager::SetMouseWatcher(PanelMouseWatcher* watcher) {\n panel_mouse_watcher_.reset(watcher);\n}\n\nvoid PanelManager::OnPanelAnimationEnded(Panel* panel) {\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_PANEL_BOUNDS_ANIMATIONS_FINISHED,\n content::Source<Panel>(panel),\n content::NotificationService::NoDetails());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"profilecontainer.h\"\n#include \"profilebuttons.h\"\n#include \"profiletranslation.h\"\n\n#include <DuiButton>\n#include <DuiSlider>\n#include <DuiLabel>\n#include <DuiLayout>\n#include <DuiImage>\n#include <DuiGridLayoutPolicy>\n#include <DuiStylableWidget>\n#include <QDebug>\n\nnamespace ProfileApplet{\n const int sliderMin = 0;\n const int sliderMax = 100;\n}\n\nProfileContainer::ProfileContainer(int id, const QString &title, DuiWidget *parent) :\n DuiContainer(title, parent),\n slider(NULL),\n level(-2),\n profileId(id)\n{\n qDebug() << \"ProfileContainer::ProfileContainer()\" << title;\n\n \/\/ TODO: hardcoded silent value!!\n if(profileId != 1) {\n slider = new DuiSlider(this, \"continuous\");\n slider->setOrientation(Qt::Horizontal);\n slider->setRange(ProfileApplet::sliderMin, ProfileApplet::sliderMax);\n slider->setThumbLabelVisible(false);\n connect(slider, SIGNAL(valueChanged(int)), this, SIGNAL(sliderValueChanged(int)));\n }\n\n button = new DuiButton(DcpProfile::VibrationText, this);\n button->setCheckable(true);\n button->setMaximumHeight(36);\n setVibration(true);\n connect(button, SIGNAL(toggled(bool)), this, SIGNAL(vibrationChanged(bool)));\n\n setLayout();\n}\n\nProfileContainer::~ProfileContainer()\n{\n}\n\nvoid ProfileContainer::setLayout()\n{\n DuiLayout *layout = new DuiLayout();\n\n DuiGridLayoutPolicy *landscapePolicy = new DuiGridLayoutPolicy(layout);\n \/\/landscapePolicy->setObjectName(\"profileContainerLayout.Landscape\");\n layout->setLandscapePolicy(landscapePolicy); \/\/ ownership transferred\n\n DuiGridLayoutPolicy *portraitPolicy = new DuiGridLayoutPolicy(layout);\n \/\/portraitPolicy->setObjectName(\"profileContainerLayout.Portrait\");\n layout->setPortraitPolicy(portraitPolicy); \/\/ ownership transferred\n\n\n DuiImage* img = NULL;\n QGraphicsLayoutItem* item = NULL;\n\n if(slider)\n {\n img = new DuiImage(\"icon-m-volume-off\", this);\n item = slider;\n qDebug() << \"slider height\" << slider->size().height();\n slider->setMaximumHeight(32);\n }\n else\n {\n img = new DuiImage(\"icon-m-volume\", this);\n item = new DuiLabel(DcpProfile::NoRingingText, this);\n }\n img->setObjectName(\"speakerIcon\");\n\n landscapePolicy->setColumnFixedWidth(0, img->imageSize().width());\n portraitPolicy->setColumnFixedWidth(0, img->imageSize().width());\n landscapePolicy->setRowFixedHeight(0, img->imageSize().height());\n portraitPolicy->setRowFixedHeight(0, img->imageSize().height());\n\n \/\/ set objects\n landscapePolicy->addItemAtPosition(img, 0, 0);\n portraitPolicy->addItemAtPosition(img, 0, 0);\n landscapePolicy->addItemAtPosition(item, 0, 1);\n portraitPolicy->addItemAtPosition(item, 0, 1);\n landscapePolicy->addItemAtPosition(button, 1, 0, 1, 2);\n portraitPolicy->addItemAtPosition(button, 1, 0, 1, 2);\n\n landscapePolicy->setSpacing(5);\n portraitPolicy->setSpacing(5);\n\n DuiStylableWidget *layoutWidget = new DuiStylableWidget();\n layoutWidget->setLayout(layout);\n layoutWidget->setObjectName(\"profileContainerLayout\");\n\n setCentralWidget(layoutWidget);\n}\n\nvoid ProfileContainer::setLevel(int value)\n{\n qDebug() << \"ProfileContainer::setLevel for \" << title() << \":\" << value << \"(old:\" << level << \")\";\n if(!slider || value == level)\n return;\n\n level = value;\n if(ProfileApplet::sliderMin < level && ProfileApplet::sliderMax >= level)\n {\n slider->setValue(level);\n qDebug() << \"ProfileContainer::setLevel done:\" << slider->value();\n }\n qDebug() << \"ProfileContainer::setLevel done:\" << slider->value();\n}\n\nvoid ProfileContainer::setVibration(bool enabled)\n{\n qDebug() << \"ProfileContainer::setVibration for \" << title() << \":\" << enabled;\n button->setChecked(enabled);\n}\n\nint ProfileContainer::id()\n{\n return profileId;\n}\n<commit_msg>Icons switched to correct places<commit_after>#include \"profilecontainer.h\"\n#include \"profilebuttons.h\"\n#include \"profiletranslation.h\"\n\n#include <DuiButton>\n#include <DuiSlider>\n#include <DuiLabel>\n#include <DuiLayout>\n#include <DuiImage>\n#include <DuiGridLayoutPolicy>\n#include <DuiStylableWidget>\n#include <QDebug>\n\nnamespace ProfileApplet{\n const int sliderMin = 0;\n const int sliderMax = 100;\n}\n\nProfileContainer::ProfileContainer(int id, const QString &title, DuiWidget *parent) :\n DuiContainer(title, parent),\n slider(NULL),\n level(-2),\n profileId(id)\n{\n qDebug() << \"ProfileContainer::ProfileContainer()\" << title;\n\n \/\/ TODO: hardcoded silent value!!\n if(profileId != 1) {\n slider = new DuiSlider(this, \"continuous\");\n slider->setOrientation(Qt::Horizontal);\n slider->setRange(ProfileApplet::sliderMin, ProfileApplet::sliderMax);\n slider->setThumbLabelVisible(false);\n connect(slider, SIGNAL(valueChanged(int)), this, SIGNAL(sliderValueChanged(int)));\n }\n\n button = new DuiButton(DcpProfile::VibrationText, this);\n button->setCheckable(true);\n button->setMaximumHeight(36);\n setVibration(true);\n connect(button, SIGNAL(toggled(bool)), this, SIGNAL(vibrationChanged(bool)));\n\n setLayout();\n}\n\nProfileContainer::~ProfileContainer()\n{\n}\n\nvoid ProfileContainer::setLayout()\n{\n DuiLayout *layout = new DuiLayout();\n\n DuiGridLayoutPolicy *landscapePolicy = new DuiGridLayoutPolicy(layout);\n \/\/landscapePolicy->setObjectName(\"profileContainerLayout.Landscape\");\n layout->setLandscapePolicy(landscapePolicy); \/\/ ownership transferred\n\n DuiGridLayoutPolicy *portraitPolicy = new DuiGridLayoutPolicy(layout);\n \/\/portraitPolicy->setObjectName(\"profileContainerLayout.Portrait\");\n layout->setPortraitPolicy(portraitPolicy); \/\/ ownership transferred\n\n\n DuiImage* img = NULL;\n QGraphicsLayoutItem* item = NULL;\n\n if(slider)\n {\n img = new DuiImage(\"icon-m-volume\", this);\n item = slider;\n qDebug() << \"slider height\" << slider->size().height();\n slider->setMaximumHeight(32);\n }\n else\n {\n img = new DuiImage(\"icon-m-volume-off\", this);\n item = new DuiLabel(DcpProfile::NoRingingText, this);\n }\n img->setObjectName(\"speakerIcon\");\n\n landscapePolicy->setColumnFixedWidth(0, img->imageSize().width());\n portraitPolicy->setColumnFixedWidth(0, img->imageSize().width());\n landscapePolicy->setRowFixedHeight(0, img->imageSize().height());\n portraitPolicy->setRowFixedHeight(0, img->imageSize().height());\n\n \/\/ set objects\n landscapePolicy->addItemAtPosition(img, 0, 0);\n portraitPolicy->addItemAtPosition(img, 0, 0);\n landscapePolicy->addItemAtPosition(item, 0, 1);\n portraitPolicy->addItemAtPosition(item, 0, 1);\n landscapePolicy->addItemAtPosition(button, 1, 0, 1, 2);\n portraitPolicy->addItemAtPosition(button, 1, 0, 1, 2);\n\n landscapePolicy->setSpacing(5);\n portraitPolicy->setSpacing(5);\n\n DuiStylableWidget *layoutWidget = new DuiStylableWidget();\n layoutWidget->setLayout(layout);\n layoutWidget->setObjectName(\"profileContainerLayout\");\n\n setCentralWidget(layoutWidget);\n}\n\nvoid ProfileContainer::setLevel(int value)\n{\n qDebug() << \"ProfileContainer::setLevel for \" << title() << \":\" << value << \"(old:\" << level << \")\";\n if(!slider || value == level)\n return;\n\n level = value;\n if(ProfileApplet::sliderMin < level && ProfileApplet::sliderMax >= level)\n {\n slider->setValue(level);\n qDebug() << \"ProfileContainer::setLevel done:\" << slider->value();\n }\n qDebug() << \"ProfileContainer::setLevel done:\" << slider->value();\n}\n\nvoid ProfileContainer::setVibration(bool enabled)\n{\n qDebug() << \"ProfileContainer::setVibration for \" << title() << \":\" << enabled;\n button->setChecked(enabled);\n}\n\nint ProfileContainer::id()\n{\n return profileId;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 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 \"chrome\/common\/sandbox_init_wrapper.h\"\n\n#include \"base\/command_line.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/sandbox_mac.h\"\n\nbool SandboxInitWrapper::InitializeSandbox(const CommandLine& command_line,\n const std::string& process_type) {\n if (command_line.HasSwitch(switches::kNoSandbox))\n return true;\n\n sandbox::SandboxProcessType sandbox_process_type;\n FilePath allowed_dir; \/\/ Empty by default.\n\n if (process_type.empty()) {\n \/\/ Browser process isn't sandboxed.\n return true;\n } else if (process_type == switches::kRendererProcess) {\n \/\/ Renderer process sandbox.\n sandbox_process_type = sandbox::SANDBOX_TYPE_RENDERER;\n } else if (process_type == switches::kExtensionProcess) {\n \/\/ Extension process sandbox.\n sandbox_process_type = sandbox::SANDBOX_TYPE_RENDERER;\n } else if (process_type == switches::kUtilityProcess) {\n \/\/ Utility process sandbox.\n sandbox_process_type = sandbox::SANDBOX_TYPE_UTILITY;\n allowed_dir = FilePath::FromWStringHack(\n command_line.GetSwitchValue(switches::kUtilityProcessAllowedDir));\n } else if (process_type == switches::kWorkerProcess) {\n \/\/ Worker process sandbox.\n sandbox_process_type = sandbox::SANDBOX_TYPE_WORKER;\n } else if ((process_type == switches::kNaClProcess) ||\n (process_type == switches::kPluginProcess) ||\n (process_type == switches::kProfileImportProcess)) {\n return true;\n } else {\n \/\/ Failsafe: If you hit an unreached here, is your new process type in need\n \/\/ of sandboxing?\n NOTREACHED();\n return true;\n }\n\n \/\/ Warm up APIs before turning on the sandbox.\n sandbox::SandboxWarmup();\n\n \/\/ Actually sandbox the process.\n return sandbox::EnableSandbox(sandbox_process_type, allowed_dir);\n}\n<commit_msg>Small cleanup to Mac Sandbox code.<commit_after>\/\/ 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 \"chrome\/common\/sandbox_init_wrapper.h\"\n\n#include \"base\/command_line.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/sandbox_mac.h\"\n\nbool SandboxInitWrapper::InitializeSandbox(const CommandLine& command_line,\n const std::string& process_type) {\n if (command_line.HasSwitch(switches::kNoSandbox))\n return true;\n\n sandbox::SandboxProcessType sandbox_process_type;\n FilePath allowed_dir; \/\/ Empty by default.\n\n if (process_type.empty()) {\n \/\/ Browser process isn't sandboxed.\n return true;\n } else if (process_type == switches::kRendererProcess) {\n \/\/ Renderer process sandbox.\n sandbox_process_type = sandbox::SANDBOX_TYPE_RENDERER;\n } else if (process_type == switches::kExtensionProcess) {\n \/\/ Extension processes are just renderers [they use RenderMain()] with a\n \/\/ different set of command line flags.\n \/\/ If we ever get here it means something has changed in regards\n \/\/ to the extension process mechanics and we should probably reexamine\n \/\/ how we sandbox extension processes since they are no longer identical\n \/\/ to renderers.\n NOTREACHED();\n return true;\n } else if (process_type == switches::kUtilityProcess) {\n \/\/ Utility process sandbox.\n sandbox_process_type = sandbox::SANDBOX_TYPE_UTILITY;\n allowed_dir = FilePath::FromWStringHack(\n command_line.GetSwitchValue(switches::kUtilityProcessAllowedDir));\n } else if (process_type == switches::kWorkerProcess) {\n \/\/ Worker process sandbox.\n sandbox_process_type = sandbox::SANDBOX_TYPE_WORKER;\n } else if ((process_type == switches::kNaClProcess) ||\n (process_type == switches::kPluginProcess) ||\n (process_type == switches::kProfileImportProcess)) {\n return true;\n } else {\n \/\/ Failsafe: If you hit an unreached here, is your new process type in need\n \/\/ of sandboxing?\n NOTREACHED();\n return true;\n }\n\n \/\/ Warm up APIs before turning on the sandbox.\n sandbox::SandboxWarmup();\n\n \/\/ Actually sandbox the process.\n return sandbox::EnableSandbox(sandbox_process_type, allowed_dir);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>remove static OUStrings from static_initialization_and_destruction chain<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"base\/message_loop.h\"\n#include \"base\/process_util.h\"\n#include \"base\/test\/multiprocess_test.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"ipc\/ipc_channel.h\"\n#include \"ipc\/ipc_switches.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/multiprocess_func_list.h\"\n\n\/\/ TODO(port): Bring up this test this on other platforms.\n#if defined(OS_POSIX)\n\nusing base::ProcessHandle;\n\nconst char kRendererTestChannelName[] = \"test\";\n\nextern int RendererMain(const MainFunctionParams& parameters);\n\n\/\/ TODO(port): The IPC Channel tests have a class with extremely similar\n\/\/ functionality, we should combine them.\nclass RendererMainTest : public base::MultiProcessTest {\n protected:\n RendererMainTest() {}\n\n \/\/ Create a new MessageLoopForIO For each test.\n virtual void SetUp();\n virtual void TearDown();\n\n \/\/ Spawns a child process of the specified type\n base::ProcessHandle SpawnChild(const std::string& procname,\n IPC::Channel* channel);\n\n \/\/ Created around each test instantiation.\n MessageLoopForIO *message_loop_;\n};\n\nvoid RendererMainTest::SetUp() {\n MultiProcessTest::SetUp();\n\n \/\/ Construct a fresh IO Message loop for the duration of each test.\n message_loop_ = new MessageLoopForIO();\n}\n\nvoid RendererMainTest::TearDown() {\n delete message_loop_;\n message_loop_ = NULL;\n\n MultiProcessTest::TearDown();\n}\n\nProcessHandle RendererMainTest::SpawnChild(const std::string& procname,\n IPC::Channel* channel) {\n base::file_handle_mapping_vector fds_to_map;\n const int ipcfd = channel->GetClientFileDescriptor();\n if (ipcfd > -1) {\n fds_to_map.push_back(std::pair<int,int>(ipcfd, 3));\n }\n\n return MultiProcessTest::SpawnChild(procname, fds_to_map, false);\n}\n\n\/\/ Listener class that kills the message loop when it connects.\nclass SuicidalListener : public IPC::Channel::Listener {\n public:\n explicit SuicidalListener(bool* suicide_success)\n : suicide_success_(suicide_success) {}\n\n void OnChannelConnected(int32 peer_pid) {\n *suicide_success_ = true;\n MessageLoop::current()->Quit();\n }\n\n void OnMessageReceived(const IPC::Message& message) {\n \/\/ We shouldn't receive any messages\n ASSERT_TRUE(false);\n }\n\n \/\/ A flag that we set when we have successfully suicided.\n bool* suicide_success_;\n};\n\nMULTIPROCESS_TEST_MAIN(SimpleRenderer) {\n SandboxInitWrapper dummy_sandbox_init;\n CommandLine cl(*CommandLine::ForCurrentProcess());\n cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName);\n\n MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL);\n return RendererMain(dummy_params);\n}\n\nTEST_F(RendererMainTest, CreateDestroy) {\n bool suicide_success = false;\n SuicidalListener listener(&suicide_success);\n IPC::Channel control_channel(kRendererTestChannelName,\n IPC::Channel::MODE_SERVER,\n &listener);\n base::ProcessHandle renderer_pid = SpawnChild(\"SimpleRenderer\",\n &control_channel);\n\n ASSERT_TRUE(control_channel.Connect());\n\n \/\/ The SuicidalListener *should* cause the following MessageLoop run\n \/\/ to quit, but just in case it doesn't, insert a QuitTask at the back\n \/\/ of the queue.\n MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,\n TestTimeouts::action_timeout_ms());\n MessageLoop::current()->Run();\n ASSERT_TRUE(suicide_success);\n\n \/\/ The renderer should exit when we close the channel.\n control_channel.Close();\n\n EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid,\n TestTimeouts::action_timeout_ms()));\n}\n#endif \/\/ defined(OS_POSIX)\n<commit_msg>Revert most of my recent changes to RendererMainTest.<commit_after>\/\/ Copyright (c) 2010 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 \"base\/message_loop.h\"\n#include \"base\/process_util.h\"\n#include \"base\/test\/multiprocess_test.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"ipc\/ipc_channel.h\"\n#include \"ipc\/ipc_switches.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/multiprocess_func_list.h\"\n\n\/\/ TODO(port): Bring up this test this on other platforms.\n#if defined(OS_POSIX)\n\nusing base::ProcessHandle;\n\nconst char kRendererTestChannelName[] = \"test\";\n\nextern int RendererMain(const MainFunctionParams& parameters);\n\n\/\/ TODO(port): The IPC Channel tests have a class with extremely similar\n\/\/ functionality, we should combine them.\nclass RendererMainTest : public base::MultiProcessTest {\n protected:\n RendererMainTest() {}\n\n \/\/ Create a new MessageLoopForIO For each test.\n virtual void SetUp();\n virtual void TearDown();\n\n \/\/ Spawns a child process of the specified type\n base::ProcessHandle SpawnChild(const std::string& procname,\n IPC::Channel* channel);\n\n \/\/ Created around each test instantiation.\n MessageLoopForIO *message_loop_;\n};\n\nvoid RendererMainTest::SetUp() {\n MultiProcessTest::SetUp();\n\n \/\/ Construct a fresh IO Message loop for the duration of each test.\n message_loop_ = new MessageLoopForIO();\n}\n\nvoid RendererMainTest::TearDown() {\n delete message_loop_;\n message_loop_ = NULL;\n\n MultiProcessTest::TearDown();\n}\n\nProcessHandle RendererMainTest::SpawnChild(const std::string& procname,\n IPC::Channel* channel) {\n base::file_handle_mapping_vector fds_to_map;\n const int ipcfd = channel->GetClientFileDescriptor();\n if (ipcfd > -1) {\n fds_to_map.push_back(std::pair<int,int>(ipcfd, 3));\n }\n\n return MultiProcessTest::SpawnChild(procname, fds_to_map, false);\n}\n\n\/\/ Listener class that kills the message loop when it connects.\nclass SuicidalListener : public IPC::Channel::Listener {\n public:\n void OnChannelConnected(int32 peer_pid) {\n MessageLoop::current()->Quit();\n }\n\n void OnMessageReceived(const IPC::Message& message) {\n \/\/ We shouldn't receive any messages\n ASSERT_TRUE(false);\n }\n};\n\nMULTIPROCESS_TEST_MAIN(SimpleRenderer) {\n SandboxInitWrapper dummy_sandbox_init;\n CommandLine cl(*CommandLine::ForCurrentProcess());\n cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName);\n\n MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL);\n return RendererMain(dummy_params);\n}\n\nTEST_F(RendererMainTest, CreateDestroy) {\n SuicidalListener listener;\n IPC::Channel control_channel(kRendererTestChannelName,\n IPC::Channel::MODE_SERVER,\n &listener);\n base::ProcessHandle renderer_pid = SpawnChild(\"SimpleRenderer\",\n &control_channel);\n\n ASSERT_TRUE(control_channel.Connect());\n\n MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,\n TestTimeouts::action_timeout_ms());\n MessageLoop::current()->Run();\n\n \/\/ The renderer should exit when we close the channel.\n control_channel.Close();\n\n EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid,\n TestTimeouts::action_timeout_ms()));\n}\n#endif \/\/ defined(OS_POSIX)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/plot\/CPlotItem.cpp,v $\n\/\/ $Revision: 1.17 $\n\/\/ $Name: $\n\/\/ $Author: gauges $\n\/\/ $Date: 2007\/02\/12 20:54:09 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \"CPlotItem.h\"\n#include \"report\/CKeyFactory.h\"\n\nconst std::string CPlotItem::TypeName[] =\n {\n \"Unset\",\n \"2D Curve\",\n \"Histogram\",\n\n \"2D Plot\",\n \"SimWiz\",\n \"\"\n };\n\nconst char* CPlotItem::XMLType[] =\n {\n \"Unset\",\n \"Curve2D\",\n \"Histogram1DItem\",\n\n \"Plot2D\",\n \"SimWiz\",\n NULL\n };\n\nconst std::string CPlotItem::RecordingActivityName[] =\n {\n \"\",\n \"Before\",\n \"During\",\n \"\",\n \"After\"\n };\n\nconst char* CPlotItem::XMLRecordingActivity[] =\n {\n \"NotSet\",\n \"before\",\n \"during\",\n \"before&during\",\n \"after\",\n \"before&after\",\n \"during&after\",\n \"before&during&after\",\n NULL\n };\n\nCPlotItem::Type CPlotItem::TypeNameToEnum(const std::string & typeName) \/\/static\n{\n unsigned C_INT32 i = 0;\n while (TypeName[i] != typeName && TypeName[i] != \"\") i++;\n\n if (CPlotItem::TypeName[i] != \"\") return (CPlotItem::Type) i;\n else return CPlotItem::unset;\n}\n\nCPlotItem::CPlotItem(const std::string & name,\n const CCopasiContainer * pParent,\n const CPlotItem::Type & type):\n CCopasiParameterGroup(TypeName[type], pParent, \"PlotItem\"),\n mType(unset),\n mActivity(),\n mpXMLActivity(NULL)\n{\n \/\/setObjectName(TypeName[mType]); \/\/TODO\n setObjectName(name);\n setType(type); \/\/to create the parameters\n}\n\nCPlotItem::CPlotItem(const CPlotItem & src,\n const CCopasiContainer * pParent):\n CCopasiParameterGroup(src, pParent),\n mType(unset),\n mActivity(),\n mpXMLActivity(NULL),\n channels(src.getChannels())\n{\n \/*\n std::cout << \"Creating new PlotItem from Template: \" << this << std::endl;\n for(unsigned int counter=0; counter < src.getChannels().size(); counter++)\n {\n std::cout << \"Channel \" << counter << \": \" << src.getChannels()[counter] << std::endl;\n }\n for(unsigned int counter=0; counter < this->getChannels().size(); counter++)\n {\n std::cout << \"New Channel \" << counter << \": \" << this->getChannels()[counter] << std::endl;\n }\n *\/\n setType(src.mType);\n}\n\nvoid CPlotItem::setType(CPlotItem::Type type)\n{\n if (type == mType) return;\n if (mType != unset) clear();\n\n mType = type;\n\n \/\/create parameters\n if (type == curve2d)\n {\n assertParameter(\"Line type\", CCopasiParameter::UINT, (unsigned C_INT32) 0);\n }\n\n if (type == histoItem1d)\n {\n assertParameter(\"increment\", CCopasiParameter::DOUBLE, (C_FLOAT64) 0.1);\n }\n\n if (type == curve2d || type == histoItem1d)\n {\n mpXMLActivity =\n assertParameter(\"Recording Activity\", CCopasiParameter::STRING, std::string(\"during\"))->getValue().pSTRING;\n\n const char ** pActivity = XMLRecordingActivity;\n while (*pActivity && mpXMLActivity->compare(*pActivity))\n pActivity++;\n mActivity = (COutputInterface::Activity) (pActivity - XMLRecordingActivity);\n\n if (mActivity < COutputInterface::BEFORE ||\n (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER) < mActivity)\n {\n mActivity = COutputInterface:: DURING;\n * mpXMLActivity = XMLRecordingActivity[mActivity];\n }\n }\n\n if (type == plot2d)\n {\n assertParameter(\"log X\", CCopasiParameter::BOOL, false);\n assertParameter(\"log Y\", CCopasiParameter::BOOL, false);\n mpXMLActivity = NULL;\n mActivity = (COutputInterface::Activity) 0;\n }\n}\n\nCPlotItem::~CPlotItem()\n{}\n\nvoid CPlotItem::cleanup()\n{\n \/\/TODO: parametergroup cleanup\n}\n\nvoid CPlotItem::initObjects()\n{}\n\nconst CPlotItem::Type & CPlotItem::getType() const\n {return mType;}\n\nvoid CPlotItem::setActivity(const COutputInterface::Activity & activity)\n{\n switch (mType)\n {\n case curve2d:\n case histoItem1d:\n mActivity = activity;\n assert (COutputInterface::BEFORE <= mActivity &&\n mActivity <= (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER));\n * mpXMLActivity = XMLRecordingActivity[mActivity];\n break;\n\n default:\n mActivity = (COutputInterface::Activity) 0;\n break;\n }\n}\n\nconst COutputInterface::Activity & CPlotItem::getActivity() const\n {\n const char ** pActivity = XMLRecordingActivity;\n COutputInterface::Activity Activity;\n\n switch (mType)\n {\n case curve2d:\n case histoItem1d:\n if (!mpXMLActivity)\n const_cast<CPlotItem *>(this)->mpXMLActivity =\n getParameter(\"Recording Activity\")->getValue().pSTRING;\n\n while (*pActivity && mpXMLActivity->compare(*pActivity)) pActivity++;\n\n Activity =\n (COutputInterface::Activity) (pActivity - XMLRecordingActivity);\n\n if (Activity < COutputInterface::BEFORE ||\n (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER) < Activity)\n {\n Activity = COutputInterface::DURING;\n * mpXMLActivity = XMLRecordingActivity[Activity];\n }\n\n const_cast<CPlotItem *>(this)->mActivity = Activity;\n\n break;\n\n default:\n break;\n }\n\n return mActivity;\n }\n\nstd::vector<CPlotDataChannelSpec> & CPlotItem::getChannels()\n{return channels;}\n\nconst std::vector<CPlotDataChannelSpec> & CPlotItem::getChannels() const\n {return channels;}\n\nunsigned C_INT32 CPlotItem::getNumChannels() const\n {return channels.size();}\n\nvoid CPlotItem::addChannel(const CPlotDataChannelSpec & channel)\n{\n channels.push_back(channel);\n}\n\nconst std::string & CPlotItem::getTitle() const\n {\n return getObjectName();\n }\n\nvoid CPlotItem::setTitle(const std::string & title)\n{\n setObjectName(title);\n}\n<commit_msg>fixed #834. Default bin size for histogram is now 1.0<commit_after>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/plot\/CPlotItem.cpp,v $\n\/\/ $Revision: 1.18 $\n\/\/ $Name: $\n\/\/ $Author: ssahle $\n\/\/ $Date: 2007\/07\/10 08:54:07 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \"CPlotItem.h\"\n#include \"report\/CKeyFactory.h\"\n\nconst std::string CPlotItem::TypeName[] =\n {\n \"Unset\",\n \"2D Curve\",\n \"Histogram\",\n\n \"2D Plot\",\n \"SimWiz\",\n \"\"\n };\n\nconst char* CPlotItem::XMLType[] =\n {\n \"Unset\",\n \"Curve2D\",\n \"Histogram1DItem\",\n\n \"Plot2D\",\n \"SimWiz\",\n NULL\n };\n\nconst std::string CPlotItem::RecordingActivityName[] =\n {\n \"\",\n \"Before\",\n \"During\",\n \"\",\n \"After\"\n };\n\nconst char* CPlotItem::XMLRecordingActivity[] =\n {\n \"NotSet\",\n \"before\",\n \"during\",\n \"before&during\",\n \"after\",\n \"before&after\",\n \"during&after\",\n \"before&during&after\",\n NULL\n };\n\nCPlotItem::Type CPlotItem::TypeNameToEnum(const std::string & typeName) \/\/static\n{\n unsigned C_INT32 i = 0;\n while (TypeName[i] != typeName && TypeName[i] != \"\") i++;\n\n if (CPlotItem::TypeName[i] != \"\") return (CPlotItem::Type) i;\n else return CPlotItem::unset;\n}\n\nCPlotItem::CPlotItem(const std::string & name,\n const CCopasiContainer * pParent,\n const CPlotItem::Type & type):\n CCopasiParameterGroup(TypeName[type], pParent, \"PlotItem\"),\n mType(unset),\n mActivity(),\n mpXMLActivity(NULL)\n{\n \/\/setObjectName(TypeName[mType]); \/\/TODO\n setObjectName(name);\n setType(type); \/\/to create the parameters\n}\n\nCPlotItem::CPlotItem(const CPlotItem & src,\n const CCopasiContainer * pParent):\n CCopasiParameterGroup(src, pParent),\n mType(unset),\n mActivity(),\n mpXMLActivity(NULL),\n channels(src.getChannels())\n{\n \/*\n std::cout << \"Creating new PlotItem from Template: \" << this << std::endl;\n for(unsigned int counter=0; counter < src.getChannels().size(); counter++)\n {\n std::cout << \"Channel \" << counter << \": \" << src.getChannels()[counter] << std::endl;\n }\n for(unsigned int counter=0; counter < this->getChannels().size(); counter++)\n {\n std::cout << \"New Channel \" << counter << \": \" << this->getChannels()[counter] << std::endl;\n }\n *\/\n setType(src.mType);\n}\n\nvoid CPlotItem::setType(CPlotItem::Type type)\n{\n if (type == mType) return;\n if (mType != unset) clear();\n\n mType = type;\n\n \/\/create parameters\n if (type == curve2d)\n {\n assertParameter(\"Line type\", CCopasiParameter::UINT, (unsigned C_INT32) 0);\n }\n\n if (type == histoItem1d)\n {\n assertParameter(\"increment\", CCopasiParameter::DOUBLE, (C_FLOAT64) 1.0);\n }\n\n if (type == curve2d || type == histoItem1d)\n {\n mpXMLActivity =\n assertParameter(\"Recording Activity\", CCopasiParameter::STRING, std::string(\"during\"))->getValue().pSTRING;\n\n const char ** pActivity = XMLRecordingActivity;\n while (*pActivity && mpXMLActivity->compare(*pActivity))\n pActivity++;\n mActivity = (COutputInterface::Activity) (pActivity - XMLRecordingActivity);\n\n if (mActivity < COutputInterface::BEFORE ||\n (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER) < mActivity)\n {\n mActivity = COutputInterface:: DURING;\n * mpXMLActivity = XMLRecordingActivity[mActivity];\n }\n }\n\n if (type == plot2d)\n {\n assertParameter(\"log X\", CCopasiParameter::BOOL, false);\n assertParameter(\"log Y\", CCopasiParameter::BOOL, false);\n mpXMLActivity = NULL;\n mActivity = (COutputInterface::Activity) 0;\n }\n}\n\nCPlotItem::~CPlotItem()\n{}\n\nvoid CPlotItem::cleanup()\n{\n \/\/TODO: parametergroup cleanup\n}\n\nvoid CPlotItem::initObjects()\n{}\n\nconst CPlotItem::Type & CPlotItem::getType() const\n {return mType;}\n\nvoid CPlotItem::setActivity(const COutputInterface::Activity & activity)\n{\n switch (mType)\n {\n case curve2d:\n case histoItem1d:\n mActivity = activity;\n assert (COutputInterface::BEFORE <= mActivity &&\n mActivity <= (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER));\n * mpXMLActivity = XMLRecordingActivity[mActivity];\n break;\n\n default:\n mActivity = (COutputInterface::Activity) 0;\n break;\n }\n}\n\nconst COutputInterface::Activity & CPlotItem::getActivity() const\n {\n const char ** pActivity = XMLRecordingActivity;\n COutputInterface::Activity Activity;\n\n switch (mType)\n {\n case curve2d:\n case histoItem1d:\n if (!mpXMLActivity)\n const_cast<CPlotItem *>(this)->mpXMLActivity =\n getParameter(\"Recording Activity\")->getValue().pSTRING;\n\n while (*pActivity && mpXMLActivity->compare(*pActivity)) pActivity++;\n\n Activity =\n (COutputInterface::Activity) (pActivity - XMLRecordingActivity);\n\n if (Activity < COutputInterface::BEFORE ||\n (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER) < Activity)\n {\n Activity = COutputInterface::DURING;\n * mpXMLActivity = XMLRecordingActivity[Activity];\n }\n\n const_cast<CPlotItem *>(this)->mActivity = Activity;\n\n break;\n\n default:\n break;\n }\n\n return mActivity;\n }\n\nstd::vector<CPlotDataChannelSpec> & CPlotItem::getChannels()\n{return channels;}\n\nconst std::vector<CPlotDataChannelSpec> & CPlotItem::getChannels() const\n {return channels;}\n\nunsigned C_INT32 CPlotItem::getNumChannels() const\n {return channels.size();}\n\nvoid CPlotItem::addChannel(const CPlotDataChannelSpec & channel)\n{\n channels.push_back(channel);\n}\n\nconst std::string & CPlotItem::getTitle() const\n {\n return getObjectName();\n }\n\nvoid CPlotItem::setTitle(const std::string & title)\n{\n setObjectName(title);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$ \n\/\/\n\/\/ Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n\/\/ Test Lagrange interpolation\n\n#include \"..\/tests.h\"\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\n#include <base\/logstream.h>\n#include <base\/polynomial.h>\n#include <base\/quadrature_lib.h>\n\nusing namespace Polynomials;\n\nvoid check_interpolation (const std::vector<Polynomial<double> >& p,\n\t\t\t const std::vector<Point<1> >& x)\n{\n for (unsigned int i=0;i<p.size();++i)\n {\n deallog << i;\n for (unsigned int k=0;k<x.size();++k)\n\t{\n\t deallog << '.';\n\t const double y = p[i].value(x[k](0));\n\t if (i == k)\n\t {\n\t if (std::fabs(y-1.) > 2.e-10)\n\t\tdeallog << \"Error1 lg y=\" << std::log10(std::fabs(y-1.))\n\t\t\t<< std::endl;\n\t }\n\t else\n\t {\n\t if (std::fabs(y) > 2.e-10)\n\t\tdeallog << \"Error0 lg y=\" << std::log10(std::fabs(y))\n\t\t\t<< std::endl;\n\t }\n\t}\n deallog << std::endl;\n }\n}\n\n\nvoid\ncheck_poly (const Quadrature<1>& q)\n{\n deallog << \"Points: \" << q.n_quadrature_points << std::endl;\n std::vector<Polynomial<double> > p = Lagrange::generate_complete_basis(q.get_points());\n check_interpolation(p, q.get_points());\n}\n\n\nvoid\ncheck_lge (unsigned int n)\n{\n deallog << \"Points: \" << n+1 << std::endl;\n std::vector<Polynomial<double> > p = LagrangeEquidistant::generate_complete_basis(n);\n std::vector<Point<1> > x(n+1);\n const double h = 1.\/n;\n for (unsigned int i=0;i<=n;++i)\n x[i](0) = h*i;\n check_interpolation(p, x);\n}\n\n\nint main()\n{\n std::ofstream logfile(\"polynomial_lagrange.output\");\n logfile.precision(3);\n deallog.attach(logfile);\n deallog.depth_console(0);\n\/\/ deallog.threshold_double(1.e-10);\n \n QTrapez<1> trapez;\n QSimpson<1> simpson;\n QIterated<1> equi7(trapez, 6);\n QIterated<1> equi10(trapez, 9);\n\n QGauss<1> g2(2);\n QGauss<1> g3(3);\n QGauss<1> g7(7);\n QGauss<1> g10(10);\n\n QGaussLobatto<1> gl2(2);\n QGaussLobatto<1> gl3(3);\n QGaussLobatto<1> gl4(4);\n QGaussLobatto<1> gl5(5);\n QGaussLobatto<1> gl6(6);\n QGaussLobatto<1> gl7(7);\n QGaussLobatto<1> gl10(10);\n \n deallog.push(\"LagrangeEquidistant\");\n check_lge(6);\n check_lge(9);\n deallog.pop();\n deallog.push(\"Equidistant\");\n check_poly(trapez);\n check_poly(simpson);\n check_poly(equi7);\n check_poly(equi10);\n deallog.pop();\n deallog.push(\"Gauss\"); \n check_poly(g2);\n check_poly(g3);\n check_poly(g7);\n check_poly(g10);\n deallog.pop();\n deallog.push(\"GaussLobatto\"); \n check_poly(gl2);\n check_poly(gl3);\n check_poly(gl4);\n check_poly(gl5);\n check_poly(gl6);\n check_poly(gl7);\n check_poly(gl10);\n deallog.pop();\n}\n<commit_msg>Slightly relax tol to avoid Error0 for gcc2.95.3<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$ \n\/\/\n\/\/ Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n\/\/ Test Lagrange interpolation\n\n#include \"..\/tests.h\"\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\n#include <base\/logstream.h>\n#include <base\/polynomial.h>\n#include <base\/quadrature_lib.h>\n\nusing namespace Polynomials;\n\nvoid check_interpolation (const std::vector<Polynomial<double> >& p,\n\t\t\t const std::vector<Point<1> >& x)\n{\n for (unsigned int i=0;i<p.size();++i)\n {\n deallog << i;\n for (unsigned int k=0;k<x.size();++k)\n\t{\n\t deallog << '.';\n\t const double y = p[i].value(x[k](0));\n\t if (i == k)\n\t {\n\t if (std::fabs(y-1.) > 2.e-10)\n\t\tdeallog << \"Error1 lg y=\" << std::log10(std::fabs(y-1.))\n\t\t\t<< std::endl;\n\t }\n\t else\n\t {\n\t if (std::fabs(y) > 3.e-10)\n\t\tdeallog << \"Error0 lg y=\" << std::log10(std::fabs(y))\n\t\t\t<< std::endl;\n\t }\n\t}\n deallog << std::endl;\n }\n}\n\n\nvoid\ncheck_poly (const Quadrature<1>& q)\n{\n deallog << \"Points: \" << q.n_quadrature_points << std::endl;\n std::vector<Polynomial<double> > p = Lagrange::generate_complete_basis(q.get_points());\n check_interpolation(p, q.get_points());\n}\n\n\nvoid\ncheck_lge (unsigned int n)\n{\n deallog << \"Points: \" << n+1 << std::endl;\n std::vector<Polynomial<double> > p = LagrangeEquidistant::generate_complete_basis(n);\n std::vector<Point<1> > x(n+1);\n const double h = 1.\/n;\n for (unsigned int i=0;i<=n;++i)\n x[i](0) = h*i;\n check_interpolation(p, x);\n}\n\n\nint main()\n{\n std::ofstream logfile(\"polynomial_lagrange.output\");\n logfile.precision(3);\n deallog.attach(logfile);\n deallog.depth_console(0);\n\/\/ deallog.threshold_double(1.e-10);\n \n QTrapez<1> trapez;\n QSimpson<1> simpson;\n QIterated<1> equi7(trapez, 6);\n QIterated<1> equi10(trapez, 9);\n\n QGauss<1> g2(2);\n QGauss<1> g3(3);\n QGauss<1> g7(7);\n QGauss<1> g10(10);\n\n QGaussLobatto<1> gl2(2);\n QGaussLobatto<1> gl3(3);\n QGaussLobatto<1> gl4(4);\n QGaussLobatto<1> gl5(5);\n QGaussLobatto<1> gl6(6);\n QGaussLobatto<1> gl7(7);\n QGaussLobatto<1> gl10(10);\n \n deallog.push(\"LagrangeEquidistant\");\n check_lge(6);\n check_lge(9);\n deallog.pop();\n deallog.push(\"Equidistant\");\n check_poly(trapez);\n check_poly(simpson);\n check_poly(equi7);\n check_poly(equi10);\n deallog.pop();\n deallog.push(\"Gauss\"); \n check_poly(g2);\n check_poly(g3);\n check_poly(g7);\n check_poly(g10);\n deallog.pop();\n deallog.push(\"GaussLobatto\"); \n check_poly(gl2);\n check_poly(gl3);\n check_poly(gl4);\n check_poly(gl5);\n check_poly(gl6);\n check_poly(gl7);\n check_poly(gl10);\n deallog.pop();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ hash_join_test.cpp\n\/\/\n\/\/ Identification: tests\/executor\/hash_join_test.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"backend\/common\/types.h\"\n#include \"backend\/executor\/logical_tile.h\"\n#include \"backend\/executor\/logical_tile_factory.h\"\n#include \"backend\/executor\/hash_join_executor.h\"\n#include \"backend\/executor\/hash_executor.h\"\n#include \"backend\/expression\/abstract_expression.h\"\n#include \"backend\/expression\/tuple_value_expression.h\"\n#include \"backend\/expression\/expression_util.h\"\n#include \"backend\/planner\/hash_join_plan.h\"\n#include \"backend\/planner\/hash_plan.h\"\n#include \"backend\/storage\/data_table.h\"\n\n#include \"mock_executor.h\"\n#include \"executor\/executor_tests_util.h\"\n#include \"executor\/join_tests_util.h\"\n#include \"harness.h\"\n\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nnamespace peloton {\nnamespace test {\n\n\/\/ Basic Test\n\/\/ Single join clause, multiple tiles with same tuples per tile,\n\/\/ join on key (i.e. there will have at most one tuple for each different join key\nTEST(HashJoinTests, BasicTest) {\n\n expression::AbstractExpression *right_table_attr_1 =\n new expression::TupleValueExpression(1, 1);\n\n std::vector<std::unique_ptr<const expression::AbstractExpression> > hashkeys;\n hashkeys.emplace_back(right_table_attr_1);\n\n \/\/ Create hash plan node\n planner::HashPlan hash_plan_node(hashkeys);\n\n \/\/ Create the hash hash_join_executor\n executor::HashExecutor hash_executor(&hash_plan_node, nullptr);\n\n \/\/ Create hash join plan node.\n auto projection = JoinTestsUtil::CreateProjection();\n planner::HashJoinPlan hash_join_plan_node(nullptr, projection);\n\n \/\/ Create the hash join hash_join_executor\n executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr);\n\n MockExecutor left_executor;\n hash_join_executor.AddChild(&left_executor);\n hash_join_executor.AddChild(&hash_join_executor);\n\n EXPECT_CALL(left_executor, DInit()).WillOnce(Return(true));\n\n EXPECT_CALL(left_executor, DExecute())\n .WillOnce(Return(true))\n .WillOnce(Return(true));\n\n \/\/ Create a table and wrap it in logical tile\n size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;\n std::unique_ptr<storage::DataTable> left_table(\n ExecutorTestsUtil::CreateTable(tile_group_size));\n ExecutorTestsUtil::PopulateTable(left_table.get(), tile_group_size * 3, false,\n false, false);\n std::unique_ptr<storage::DataTable> right_table(\n ExecutorTestsUtil::CreateTable(tile_group_size));\n ExecutorTestsUtil::PopulateTable(right_table.get(), tile_group_size * 2,\n false, false, false);\n\n std::unique_ptr<executor::LogicalTile> left_logical_tile1(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0)));\n std::unique_ptr<executor::LogicalTile> left_logical_tile2(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1)));\n\n std::unique_ptr<executor::LogicalTile> right_logical_tile1(\n executor::LogicalTileFactory::WrapTileGroup(\n right_table->GetTileGroup(0)));\n std::unique_ptr<executor::LogicalTile> right_logical_tile2(\n executor::LogicalTileFactory::WrapTileGroup(\n right_table->GetTileGroup(1)));\n\n EXPECT_CALL(left_executor, GetOutput())\n .WillOnce(Return(left_logical_tile1.release()))\n .WillOnce(Return(left_logical_tile2.release()));\n\n \/\/ Run the hash_join_executor\n EXPECT_TRUE(hash_join_executor.Init());\n\n for (size_t tile_itr = 0; tile_itr < 2; tile_itr++)\n EXPECT_TRUE(hash_join_executor.Execute());\n\n EXPECT_FALSE(hash_join_executor.Execute());\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton\n<commit_msg>Finished basic hash join test<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ hash_join_test.cpp\n\/\/\n\/\/ Identification: tests\/executor\/hash_join_test.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"backend\/common\/types.h\"\n#include \"backend\/executor\/logical_tile.h\"\n#include \"backend\/executor\/logical_tile_factory.h\"\n#include \"backend\/executor\/hash_join_executor.h\"\n#include \"backend\/executor\/hash_executor.h\"\n#include \"backend\/expression\/abstract_expression.h\"\n#include \"backend\/expression\/tuple_value_expression.h\"\n#include \"backend\/expression\/expression_util.h\"\n#include \"backend\/planner\/hash_join_plan.h\"\n#include \"backend\/planner\/hash_plan.h\"\n#include \"backend\/storage\/data_table.h\"\n\n#include \"mock_executor.h\"\n#include \"executor\/executor_tests_util.h\"\n#include \"executor\/join_tests_util.h\"\n#include \"harness.h\"\n\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nnamespace peloton {\nnamespace test {\n\n\/\/ Basic Test\n\/\/ Single join clause, multiple tiles with same tuples per tile,\n\/\/ join on key (i.e. there will have at most one tuple for each different join key\nTEST(HashJoinTests, BasicTest) {\n\n expression::AbstractExpression *right_table_attr_1 =\n new expression::TupleValueExpression(1, 1);\n\n std::vector<std::unique_ptr<const expression::AbstractExpression> > hashkeys;\n hashkeys.emplace_back(right_table_attr_1);\n\n \/\/ Create hash plan node\n planner::HashPlan hash_plan_node(hashkeys);\n\n \/\/ Create the hash hash_join_executor\n executor::HashExecutor hash_executor(&hash_plan_node, nullptr);\n\n \/\/ Create hash join plan node.\n auto projection = JoinTestsUtil::CreateProjection();\n planner::HashJoinPlan hash_join_plan_node(nullptr, projection);\n\n \/\/ Create the hash join hash_join_executor\n executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr);\n\n MockExecutor left_executor, right_executor;\n hash_join_executor.AddChild(&left_executor);\n hash_join_executor.AddChild(&hash_executor);\n\n hash_executor.AddChild(&right_executor);\n\n EXPECT_CALL(left_executor, DInit())\n .WillOnce(Return(true));\n\n EXPECT_CALL(right_executor, DInit())\n .WillOnce(Return(true));\n\n EXPECT_CALL(left_executor, DExecute())\n .WillOnce(Return(true))\n .WillOnce(Return(true))\n .WillOnce(Return(false));\n\n EXPECT_CALL(right_executor, DExecute())\n .WillOnce(Return(true)) \/\/ Itr 1\n .WillOnce(Return(true))\n .WillOnce(Return(false));\n\n \/\/ Create a table and wrap it in logical tile\n size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;\n std::unique_ptr<storage::DataTable> left_table(\n ExecutorTestsUtil::CreateTable(tile_group_size));\n ExecutorTestsUtil::PopulateTable(left_table.get(), tile_group_size * 3, false,\n false, false);\n std::unique_ptr<storage::DataTable> right_table(\n ExecutorTestsUtil::CreateTable(tile_group_size));\n ExecutorTestsUtil::PopulateTable(right_table.get(), tile_group_size * 2,\n false, false, false);\n\n std::unique_ptr<executor::LogicalTile> left_logical_tile1(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0)));\n std::unique_ptr<executor::LogicalTile> left_logical_tile2(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1)));\n\n std::unique_ptr<executor::LogicalTile> right_logical_tile1(\n executor::LogicalTileFactory::WrapTileGroup(\n right_table->GetTileGroup(0)));\n std::unique_ptr<executor::LogicalTile> right_logical_tile2(\n executor::LogicalTileFactory::WrapTileGroup(\n right_table->GetTileGroup(1)));\n\n EXPECT_CALL(left_executor, GetOutput())\n .WillOnce(Return(left_logical_tile1.release()))\n .WillOnce(Return(left_logical_tile2.release()));\n\n EXPECT_CALL(right_executor, GetOutput())\n .WillOnce(Return(right_logical_tile1.release()))\n .WillOnce(Return(right_logical_tile2.release()));\n\n \/\/ Run the hash_join_executor\n EXPECT_TRUE(hash_join_executor.Init());\n\n for (size_t tile_itr = 0; tile_itr < 2; tile_itr++)\n EXPECT_TRUE(hash_join_executor.Execute());\n\n EXPECT_FALSE(hash_join_executor.Execute());\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"<commit_before>#include \"lunar_fiber.hpp\"\n\n#include <thread>\n\nvolatile int n = 0;\n\nvoid\nfunc1(void *arg)\n{\n printf(\"func1\\n\");\n\n n++;\n while(n != 2); \/\/ barrier\n\n int cnt = 0;\n int s = 0;\n timespec ts0;\n GETTIME(&ts0);\n for (;;) {\n void *data;\n if (lunar::pop_threadq_fiber(&data) == lunar::STRM_NO_MORE_DATA) {\n s++;\n lunar::select_fiber(nullptr, 0, nullptr, 0, true, 0);\n continue;\n }\n\n cnt++;\n if (cnt > 50000000) {\n timespec ts1;\n GETTIME(&ts1);\n TIMESPECSUB(&ts1, &ts0);\n printf(\"%lf [ops\/s], select = %lf\\n\",\n cnt \/ (ts1.tv_sec + ts1.tv_nsec * 1e-9),\n s \/ (ts1.tv_sec + ts1.tv_nsec * 1e-9));\n\n cnt = 0;\n GETTIME(&ts0);\n }\n }\n}\n\nvoid\nfunc2(void *arg)\n{\n printf(\"func2\\n\");\n \n n++;\n while(n != 2); \/\/ barrier\n \n auto fb = lunar::get_fiber(1);\n printf(\"fiber = %p\\n\", fb);\n \n for (;;) lunar::push_threadq_fast_unsafe_fiber(fb, nullptr);\n}\n\nvoid\nthread2()\n{\n lunar::init_fiber(2);\n lunar::spawn_fiber(func2);\n lunar::run_fiber();\n}\n\nvoid\nthread1()\n{\n lunar::init_fiber(1);\n lunar::spawn_fiber(func1);\n lunar::run_fiber();\n}\n\nint\nmain(int argc, char *argv[])\n{\n std::thread th1(thread1);\n std::thread th2(thread2);\n \n th1.join();\n th2.join();\n\n return 0;\n}<commit_msg>minor fix<commit_after>#include \"lunar_fiber.hpp\"\n\n#include <thread>\n\nvolatile int n = 0;\n\nvoid\nfunc1(void *arg)\n{\n n++;\n while(n != 2); \/\/ barrier\n\n int cnt = 0;\n int s = 0;\n timespec ts0;\n GETTIME(&ts0);\n for (;;) {\n void *data;\n if (lunar::pop_threadq_fiber(&data) == lunar::STRM_NO_MORE_DATA) {\n s++;\n lunar::select_fiber(nullptr, 0, nullptr, 0, true, 0);\n continue;\n }\n\n cnt++;\n if (cnt > 50000000) {\n timespec ts1;\n GETTIME(&ts1);\n TIMESPECSUB(&ts1, &ts0);\n auto sec = ts1.tv_sec + ts1.tv_nsec * 1e-9;\n\n printf(\"%lf [ops\/s], select = %lf\\n\",\n cnt \/ sec, s \/ sec);\n\n cnt = 0;\n s = 0;\n GETTIME(&ts0);\n }\n }\n}\n\nvoid\nfunc2(void *arg)\n{\n n++;\n while(n != 2); \/\/ barrier\n \n auto fb = lunar::get_fiber(1);\n for (;;) lunar::push_threadq_fast_unsafe_fiber(fb, nullptr);\n}\n\nvoid\nthread2()\n{\n lunar::init_fiber(2);\n lunar::spawn_fiber(func2);\n lunar::run_fiber();\n}\n\nvoid\nthread1()\n{\n lunar::init_fiber(1);\n lunar::spawn_fiber(func1);\n lunar::run_fiber();\n}\n\nint\nmain(int argc, char *argv[])\n{\n std::thread th1(thread1);\n std::thread th2(thread2);\n \n th1.join();\n th2.join();\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.\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#include \"OneMulti.h\"\n\nOneMulti::~OneMulti()\n{\n}\n\nunsigned int\nOneMulti::run()\n{\n if( disjCoresPreprocessing && !disjointCorePreprocessing() )\n return INCOHERENT;\n \n if( ub() == lb() )\n return OPTIMUM_FOUND;\n \n if( wasp::Options::stratification && solver.isWeighted( level() ) )\n return runWeighted();\n return runUnweighted();\n}\n\nunsigned int\nOneMulti::runUnweighted()\n{ \n trace_msg( weakconstraints, 1, \"Starting algorithm ONE\" );\n computeAssumptions(); \n \n initInUnsatCore(); \n\n solver.setComputeUnsatCores( true );\n solver.turnOffSimplifications();\n while( solver.solve( assumptions ) == INCOHERENT )\n { \n if( !foundUnsat() )\n return INCOHERENT;\n assumptions.clear();\n computeAssumptions(); \n }\n \n assert_msg( lb() == ub(), lb() << \" != \" << ub() );\n return OPTIMUM_FOUND;\n}\n\nunsigned int\nOneMulti::runWeighted()\n{ \n trace_msg( weakconstraints, 1, \"Starting algorithm ONE\" );\n \n preprocessingWeights();\n changeWeight();\n computeAssumptionsStratified(); \n \n initInUnsatCore();\n\n solver.setComputeUnsatCores( true );\n solver.turnOffSimplifications();\n\n while( true )\n {\n if( solver.solve( assumptions ) != INCOHERENT )\n {\n solver.unrollToZero();\n solver.clearConflictStatus();\n if( !changeWeight() )\n break;\n }\n else if( !foundUnsat() )\n return INCOHERENT;\n \n assumptions.clear();\n computeAssumptionsStratified();\n if( lb() == ub() )\n break;\n }\n\n assert_msg( lb() == ub(), lb() << \" != \" << ub() ); \n \n return OPTIMUM_FOUND;\n}\n\nbool\nOneMulti::processCoreOne(\n vector< Literal >& literals,\n vector< uint64_t >& weights,\n vector< Var >& newVars,\n uint64_t minWeight,\n unsigned int& n )\n{\n trace_msg( weakconstraints, 2, \"Processing core for algorithm One\" );\n \n bool trivial = false;\n Clause* clause = new Clause();\n unsigned int originalSize = solver.numberOfOptimizationLiterals( level() );\n for( unsigned int i = 0; i < originalSize; i++ )\n {\n OptimizationLiteralData& optLitData = solver.getOptimizationLiteral( level(), i ); \n if( optLitData.isRemoved() )\n continue;\n\n Literal lit = optLitData.lit;\n trace_msg( weakconstraints, 3, \"Considering literal \" << lit << \" - weight \" << optLitData.weight );\n Var v = lit.getVariable();\n if( visited( v ) )\n {\n trace_msg( weakconstraints, 4, \"is in unsat core\" );\n literals.push_back( lit.getOppositeLiteral() );\n weights.push_back( 1 );\n optLitData.remove();\n \n if( solver.isTrue( lit ) )\n trivial = true;\n \n if( !solver.isFalse( lit ) )\n clause->addLiteral( lit );\n \n if( optLitData.weight > minWeight )\n solver.addOptimizationLiteral( lit, optLitData.weight - minWeight, level(), true ); \n }\n }\n \n n = literals.size(); \n for( unsigned int i = 0; i < n - 1; i++ )\n {\n Var auxVar = addAuxVariable();\n solver.addOptimizationLiteral( Literal( auxVar, NEGATIVE ), minWeight, level(), true );\n newVars.push_back( auxVar );\n }\n \n for( int i = newVars.size() - 1; i >= 1; i-- )\n {\n Clause* c = new Clause();\n c->addLiteral( Literal( newVars[ i ], NEGATIVE ) );\n c->addLiteral( Literal( newVars[ i - 1 ], POSITIVE ) );\n solver.addClauseRuntime( c ); \n }\n \n if( trivial )\n {\n delete clause;\n return true;\n }\n\n return solver.addClauseRuntime( clause );\n}\n\nbool\nOneMulti::addAggregateOne(\n vector< Literal >& literals,\n vector< uint64_t >& weights,\n vector< Var >& bounds )\n{\n if( literals.size() == 1 )\n {\n trace_msg( weakconstraints, 2, \"Literal \" << literals[ 0 ] << \" is removed from assumptions. Nothing more to do\" );\n return true;\n }\n \n trace_msg( weakconstraints, 2, \"Adding aggregate from unsat core\" );\n MultiAggregate* multi = new MultiAggregate();\n assert(literals.size() == weights.size());\n for(unsigned int i = 0; i < literals.size(); i++)\n multi->addLiteral(literals[i], weights[i]);\n \n for(unsigned int i = 0; i < bounds.size(); i++)\n multi->addBound(Literal(bounds[i], POSITIVE),i+1);\n \n multi->finalizeNoBinaryClauses(solver);\n solver.attachMultiAggregate(*multi);\n solver.addMultiAggregate(multi);\n trace_msg( weakconstraints, 3, \"Adding \" << *multi );\n return true;\n}\n\nbool\nOneMulti::processCoreOne(\n vector< Literal >& literals,\n vector< uint64_t >& weights,\n uint64_t minWeight,\n unsigned int& n )\n{\n trace_msg( weakconstraints, 2, \"Processing core for algorithm One\" );\n \n bool trivial = false;\n Clause* clause = new Clause();\n unsigned int originalSize = solver.numberOfOptimizationLiterals( level() );\n for( unsigned int i = 0; i < originalSize; i++ )\n {\n OptimizationLiteralData& optLitData = solver.getOptimizationLiteral( level(), i ); \n if( optLitData.isRemoved() )\n continue;\n\n Literal lit = optLitData.lit;\n trace_msg( weakconstraints, 3, \"Considering literal \" << lit << \" - weight \" << optLitData.weight );\n Var v = lit.getVariable();\n if( visited( v ) )\n {\n trace_msg( weakconstraints, 4, \"is in unsat core\" );\n literals.push_back( lit );\n\/\/ weights.push_back( optLitData.weight );\n weights.push_back( 1 );\n optLitData.remove();\n \n if( solver.isTrue( lit ) )\n trivial = true;\n \n if( !solver.isFalse( lit ) )\n clause->addLiteral( lit );\n \n if( optLitData.weight > minWeight )\n solver.addOptimizationLiteral( lit, optLitData.weight - minWeight, level(), true ); \n }\n }\n \n n = literals.size();\n vector< Var > newVars;\n for( unsigned int i = 0; i < n - 1; i++ )\n {\n Var auxVar = addAuxVariable();\n literals.push_back( Literal( auxVar, POSITIVE ) );\n weights.push_back( 1 );\n solver.addOptimizationLiteral( Literal( auxVar, NEGATIVE ), minWeight, level(), true );\n newVars.push_back( auxVar );\n }\n \n for( int i = newVars.size() - 1; i >= 1; i-- )\n {\n Clause* c = new Clause();\n c->addLiteral( Literal( newVars[ i ], NEGATIVE ) );\n c->addLiteral( Literal( newVars[ i - 1 ], POSITIVE ) );\n solver.addClauseRuntime( c ); \n }\n \n if( trivial )\n {\n delete clause;\n return true;\n }\n\n return solver.addClauseRuntime( clause );\n}\n\nbool\nOneMulti::addAggregateOne(\n vector< Literal >& literals,\n vector< uint64_t >& weights,\n uint64_t bound )\n{\n if( literals.size() == 1 )\n {\n trace_msg( weakconstraints, 2, \"Literal \" << literals[ 0 ] << \" is removed from assumptions. Nothing more to do\" );\n return true;\n }\n \n trace_msg( weakconstraints, 2, \"Adding aggregate from unsat core\" );\n Var aggrId = addAuxVariable(); \n Aggregate* aggregate = createAggregate( aggrId, literals, weights ); \n if( !processAndAddAggregate( aggregate, bound ) )\n return false;\n \n assert( !solver.isTrue( aggrId ) );\n solver.addClauseRuntime( Literal( aggrId, NEGATIVE ) );\n assert( solver.isFalse( aggrId ) );\n return true;\n}\n\nbool\nOneMulti::foundUnsat()\n{\n ++numberOfCalls;\n \n const Clause* core = solver.getUnsatCore();\n assert( core != NULL );\n const Clause& unsatCore = *( core );\n \n \/\/The incoherence does not depend on weak constraints\n if( unsatCore.size() == 0 )\n return false; \n \n solver.clearConflictStatus();\n solver.unrollToZero();\n\n for( unsigned int i = 0; i < unsatCore.size(); i++ )\n visit( unsatCore[ i ].getVariable() );\n \n vector< Literal > literals;\n vector< uint64_t > weights;\n vector< Var > newVars;\n\n unsigned int n = 0;\n uint64_t minWeight = computeMinWeight();\n \n if( unsatCore.size() <= wasp::Options::multiThreshold )\n {\n if( !processCoreOne( literals, weights, minWeight, n ) || !addAggregateOne( literals, weights, n + 1 ) )\n return false;\n }\n else\n {\n if( !processCoreOne( literals, weights, newVars, minWeight, n ) || !addAggregateOne( literals, weights, newVars ) )\n return false;\n }\n incrementLb( minWeight );\n solver.foundLowerBound( lb() ); \n \n return true;\n}\n<commit_msg>Fixed bug in one-multi.<commit_after>\/*\n *\n * Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.\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#include \"OneMulti.h\"\n\nOneMulti::~OneMulti()\n{\n}\n\nunsigned int\nOneMulti::run()\n{\n if( disjCoresPreprocessing && !disjointCorePreprocessing() )\n return INCOHERENT;\n \n if( ub() == lb() )\n return OPTIMUM_FOUND;\n \n if( wasp::Options::stratification && solver.isWeighted( level() ) )\n return runWeighted();\n return runUnweighted();\n}\n\nunsigned int\nOneMulti::runUnweighted()\n{ \n trace_msg( weakconstraints, 1, \"Starting algorithm ONE\" );\n computeAssumptions(); \n \n initInUnsatCore(); \n\n solver.setComputeUnsatCores( true );\n solver.turnOffSimplifications();\n while( solver.solve( assumptions ) == INCOHERENT )\n { \n if( !foundUnsat() )\n return INCOHERENT;\n assumptions.clear();\n computeAssumptions(); \n }\n \n assert_msg( lb() == ub(), lb() << \" != \" << ub() );\n return OPTIMUM_FOUND;\n}\n\nunsigned int\nOneMulti::runWeighted()\n{ \n trace_msg( weakconstraints, 1, \"Starting algorithm ONE\" );\n \n preprocessingWeights();\n changeWeight();\n computeAssumptionsStratified(); \n \n initInUnsatCore();\n\n solver.setComputeUnsatCores( true );\n solver.turnOffSimplifications();\n\n while( true )\n {\n if( solver.solve( assumptions ) != INCOHERENT )\n {\n solver.unrollToZero();\n solver.clearConflictStatus();\n if( !changeWeight() )\n break;\n }\n else if( !foundUnsat() )\n return INCOHERENT;\n \n assumptions.clear();\n computeAssumptionsStratified();\n if( lb() == ub() )\n break;\n }\n\n assert_msg( lb() == ub(), lb() << \" != \" << ub() ); \n \n return OPTIMUM_FOUND;\n}\n\nbool\nOneMulti::processCoreOne(\n vector< Literal >& literals,\n vector< uint64_t >& weights,\n vector< Var >& newVars,\n uint64_t minWeight,\n unsigned int& n )\n{\n trace_msg( weakconstraints, 2, \"Processing core for algorithm One\" );\n \n bool trivial = false;\n Clause* clause = new Clause();\n unsigned int originalSize = solver.numberOfOptimizationLiterals( level() );\n for( unsigned int i = 0; i < originalSize; i++ )\n {\n OptimizationLiteralData& optLitData = solver.getOptimizationLiteral( level(), i ); \n if( optLitData.isRemoved() )\n continue;\n\n Literal lit = optLitData.lit;\n trace_msg( weakconstraints, 3, \"Considering literal \" << lit << \" - weight \" << optLitData.weight );\n Var v = lit.getVariable();\n if( visited( v ) )\n {\n trace_msg( weakconstraints, 4, \"is in unsat core\" );\n literals.push_back( lit.getOppositeLiteral() );\n weights.push_back( 1 );\n optLitData.remove();\n \n if( solver.isTrue( lit ) )\n trivial = true;\n \n if( !solver.isFalse( lit ) )\n clause->addLiteral( lit );\n \n if( optLitData.weight > minWeight )\n solver.addOptimizationLiteral( lit, optLitData.weight - minWeight, level(), true ); \n }\n }\n \n n = literals.size(); \n for( unsigned int i = 0; i < n - 1; i++ )\n {\n Var auxVar = addAuxVariable();\n solver.addOptimizationLiteral( Literal( auxVar, NEGATIVE ), minWeight, level(), true );\n newVars.push_back( auxVar );\n }\n \n for( int i = newVars.size() - 1; i >= 1; i-- )\n {\n Clause* c = new Clause();\n c->addLiteral( Literal( newVars[ i ], NEGATIVE ) );\n c->addLiteral( Literal( newVars[ i - 1 ], POSITIVE ) );\n solver.addClauseRuntime( c ); \n }\n \n if( trivial )\n {\n delete clause;\n return true;\n }\n\n return solver.addClauseRuntime( clause );\n}\n\nbool\nOneMulti::addAggregateOne(\n vector< Literal >& literals,\n vector< uint64_t >& weights,\n vector< Var >& bounds )\n{\n if( literals.size() == 1 )\n {\n trace_msg( weakconstraints, 2, \"Literal \" << literals[ 0 ] << \" is removed from assumptions. Nothing more to do\" );\n return true;\n }\n \n trace_msg( weakconstraints, 2, \"Adding aggregate from unsat core\" );\n MultiAggregate* multi = new MultiAggregate();\n assert(literals.size() == weights.size());\n for(unsigned int i = 0; i < literals.size(); i++)\n multi->addLiteral(literals[i], weights[i]);\n \n for(unsigned int i = 0; i < bounds.size(); i++)\n multi->addBound(Literal(bounds[i], POSITIVE),i+1);\n \n multi->finalizeNoBinaryClauses(solver);\n solver.attachMultiAggregate(*multi);\n solver.addMultiAggregate(multi);\n trace_msg( weakconstraints, 3, \"Adding \" << *multi );\n return true;\n}\n\nbool\nOneMulti::processCoreOne(\n vector< Literal >& literals,\n vector< uint64_t >& weights,\n uint64_t minWeight,\n unsigned int& n )\n{\n trace_msg( weakconstraints, 2, \"Processing core for algorithm One\" );\n \n bool trivial = false;\n Clause* clause = new Clause();\n unsigned int originalSize = solver.numberOfOptimizationLiterals( level() );\n for( unsigned int i = 0; i < originalSize; i++ )\n {\n OptimizationLiteralData& optLitData = solver.getOptimizationLiteral( level(), i ); \n if( optLitData.isRemoved() )\n continue;\n\n Literal lit = optLitData.lit;\n trace_msg( weakconstraints, 3, \"Considering literal \" << lit << \" - weight \" << optLitData.weight );\n Var v = lit.getVariable();\n if( visited( v ) )\n {\n trace_msg( weakconstraints, 4, \"is in unsat core\" );\n literals.push_back( lit );\n\/\/ weights.push_back( optLitData.weight );\n weights.push_back( 1 );\n optLitData.remove();\n \n if( solver.isTrue( lit ) )\n trivial = true;\n \n if( !solver.isFalse( lit ) )\n clause->addLiteral( lit );\n \n if( optLitData.weight > minWeight )\n solver.addOptimizationLiteral( lit, optLitData.weight - minWeight, level(), true ); \n }\n }\n \n n = literals.size();\n vector< Var > newVars;\n for( unsigned int i = 0; i < n - 1; i++ )\n {\n Var auxVar = addAuxVariable();\n literals.push_back( Literal( auxVar, POSITIVE ) );\n weights.push_back( 1 );\n solver.addOptimizationLiteral( Literal( auxVar, NEGATIVE ), minWeight, level(), true );\n newVars.push_back( auxVar );\n }\n \n for( int i = newVars.size() - 1; i >= 1; i-- )\n {\n Clause* c = new Clause();\n c->addLiteral( Literal( newVars[ i ], NEGATIVE ) );\n c->addLiteral( Literal( newVars[ i - 1 ], POSITIVE ) );\n solver.addClauseRuntime( c ); \n }\n \n if( trivial )\n {\n delete clause;\n return true;\n }\n\n return solver.addClauseRuntime( clause );\n}\n\nbool\nOneMulti::addAggregateOne(\n vector< Literal >& literals,\n vector< uint64_t >& weights,\n uint64_t bound )\n{\n if( literals.size() == 1 )\n {\n trace_msg( weakconstraints, 2, \"Literal \" << literals[ 0 ] << \" is removed from assumptions. Nothing more to do\" );\n return true;\n }\n \n trace_msg( weakconstraints, 2, \"Adding aggregate from unsat core\" );\n Var aggrId = addAuxVariable(); \n Aggregate* aggregate = createAggregate( aggrId, literals, weights ); \n if( !processAndAddAggregate( aggregate, bound ) )\n return false;\n \n assert( !solver.isTrue( aggrId ) );\n solver.addClauseRuntime( Literal( aggrId, NEGATIVE ) );\n assert( solver.isFalse( aggrId ) );\n return true;\n}\n\nbool\nOneMulti::foundUnsat()\n{\n ++numberOfCalls;\n \n const Clause* core = solver.getUnsatCore();\n assert( core != NULL );\n const Clause& unsatCore = *( core );\n \n \/\/The incoherence does not depend on weak constraints\n if( unsatCore.size() == 0 )\n return false; \n \n solver.clearConflictStatus();\n solver.unrollToZero();\n \n \n bool found = false;\n for( unsigned int i = 0; i < unsatCore.size(); i++ ) {\n if( solver.isFalse( unsatCore[ i ] ) && solver.getDecisionLevel( unsatCore[ i ] ) == 0 )\n {\n visit( unsatCore[ i ].getVariable() );\n found = true;\n }\n }\n\n if( !found )\n {\n for( unsigned int i = 0; i < unsatCore.size(); i++ )\n visit( unsatCore[ i ].getVariable() );\n }\n \n vector< Literal > literals;\n vector< uint64_t > weights;\n vector< Var > newVars;\n\n unsigned int n = 0;\n uint64_t minWeight = computeMinWeight();\n \n if( unsatCore.size() <= wasp::Options::multiThreshold )\n {\n if( !processCoreOne( literals, weights, minWeight, n ) || !addAggregateOne( literals, weights, n + 1 ) )\n return false;\n }\n else\n {\n if( !processCoreOne( literals, weights, newVars, minWeight, n ) || !addAggregateOne( literals, weights, newVars ) )\n return false;\n }\n incrementLb( minWeight );\n solver.foundLowerBound( lb() ); \n \n return true;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix merge error from r1055<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"stretch.h\"\n#include <algorithm>\n\n\/\/ NOTE: This is everything but beautyful code. Unfortunately, I can't come up with a better way\n\/\/ to solve this problem. If you know a more elegant solution, please contact me.\n\/\/ Even tough I tried my best to comment and explain as much as possible, I wouldn't recommend\n\/\/ spending more time in here than necessary.\n\nnamespace ncurses\n{\n Resize_data::Resize_data (\n const std::vector < std::shared_ptr < Element > >* elements,\n const std::shared_ptr < Window >& window,\n const std::shared_ptr < Orientation >& orientation\n ):\n window ( window ),\n elements ( elements ),\n already_used_length ( 0 )\n {\n \/\/ Create prefered_length_sum\n prefered_length_sum = 0;\n std::for_each ( elements->begin (), elements->end (),\n [ & ] ( std::shared_ptr < Element > element )\n { prefered_length_sum += orientation->get_prefered_length ( element ); } );\n\n \/\/ Create no_preference_element_count\n no_preference_element_count = std::count_if ( elements->begin (), elements->end (),\n [ & ] ( std::shared_ptr < Element > element )\n { return orientation->get_prefered_length ( element ) == 0; } );\n }\n\n void Stretch_layout::update_elements (\n const std::vector < std::shared_ptr < Element > >& elements,\n char key,\n const std::shared_ptr < Window >& window\n )\n {\n \/\/ We need an orientation for this to work\n if ( orientation.get () != nullptr )\n {\n \/\/ Only resize if we have to ( speeds it up a lot )\n if ( has_input_changed ( elements, window ) )\n resize ( elements, window );\n\n \/\/ This is something Stretch_layout::compress_window_dummies does\n \/\/ Look at if for more details\n if ( windows.size () != 0 )\n {\n \/\/ Indexes in elements correspond to indexes in windows\n for ( int i = 0; i < elements.size (); i++ )\n {\n elements.at ( i )->update ( key, windows.at ( i ) );\n }\n }\n }\n else\n {\n window->draw_string ( \"Missing Orientation!\" );\n window->refresh ();\n }\n }\n\n void Stretch_layout::set_orientation ( const std::shared_ptr < Orientation >& orientation )\n {\n this->orientation = orientation;\n }\n\n bool Stretch_layout::has_input_changed (\n const std::vector < std::shared_ptr < Element > >& elements,\n const std::shared_ptr < Window >& window\n )\n {\n \/\/ elements or something about the window has changed\n return (\n elements != last_elements ||\n window->get_x () != last_window.x ||\n window->get_y () != last_window.y ||\n window->get_width () != last_window.width||\n window->get_height () != last_window.height\n );\n }\n\n void Stretch_layout::resize (\n const std::vector < std::shared_ptr < Element > >& elements,\n const std::shared_ptr < Window >& window\n )\n {\n \/\/ Remove all old windows\n windows.clear ();\n Resize_data resize_data ( &elements, window, orientation );\n\n \/\/ Generate window_dummies\n std::vector < std::shared_ptr < Window_dummy > > window_dummies = generate_window_dummies ( resize_data );\n \/\/ Turn window_dummies into actual windows and put them into windows\n for ( auto it = window_dummies.begin (); it != window_dummies.end (); it++ )\n {\n std::shared_ptr < Window > element_window = std::make_shared < Window > (\n ( *it )->x,\n ( *it )->y,\n ( *it )->width,\n ( *it )->height\n );\n windows.push_back ( element_window );\n }\n }\n\n std::vector < std::shared_ptr < Window_dummy > > Stretch_layout::generate_window_dummies ( Resize_data& resize_data )\n {\n \/\/ Generate basic window_dummies, they might be longer than the available length\n std::vector < std::shared_ptr < Window_dummy > > window_dummies = generate_basic_window_dummies ( resize_data );\n \/\/ Now scale them down, if they are longer\n compress_window_dummies ( resize_data, window_dummies );\n \/\/ And distribut remaining length ( created by integer division errors )\n distribute_remaining_length ( resize_data, window_dummies );\n\n return window_dummies;\n }\n\n int Stretch_layout::generate_no_preference_length ( Resize_data& resize_data )\n {\n \/\/ If prefered_lengths are already longer than provided length, return average of prefered_lengths\n if ( resize_data.prefered_length_sum > orientation->get_primary_length ( resize_data.window ) )\n return resize_data.prefered_length_sum \/ ( resize_data.elements->size () - resize_data.no_preference_element_count );\n else\n \/\/ Return remaining length divided by no_preference_element_count\n return ( orientation->get_primary_length ( resize_data.window ) - resize_data.prefered_length_sum )\n \/ resize_data.no_preference_element_count;\n }\n\n std::vector < std::shared_ptr < Window_dummy > > Stretch_layout::generate_basic_window_dummies ( Resize_data& resize_data )\n {\n std::vector < std::shared_ptr < Window_dummy > > basic_dummies;\n int no_preference_length = generate_no_preference_length ( resize_data );\n\n for ( int i = 0; i < resize_data.elements->size (); i++ )\n {\n std::shared_ptr < Window_dummy > next_window_dummy = std::make_shared < Window_dummy > ();\n\n \/\/ Set secondary coordinate and length to the same as window's\n orientation->set_secondary_length ( next_window_dummy, orientation->get_secondary_length ( resize_data.window ) );\n orientation->set_secondary_coordinate ( next_window_dummy, orientation->get_secondary_coordinate ( resize_data.window ) );\n\n \/\/ Set primary coordinate to window's plus the already used length\n orientation->set_primary_coordinate ( next_window_dummy,\n orientation->get_primary_coordinate ( resize_data.window ) + resize_data.already_used_length );\n\n \/\/ If element has a preference, use it\n if ( orientation->get_prefered_length ( resize_data.elements->at ( i ) ) > 0 )\n orientation->set_primary_length ( next_window_dummy, orientation->get_prefered_length ( resize_data.elements->at ( i ) ) );\n else\n \/\/ Use the generated no_preference_length\n orientation->set_primary_length ( next_window_dummy, no_preference_length );\n\n \/\/ Add window_dummy's primary_length to already used length\n resize_data.already_used_length += orientation->get_primary_length ( next_window_dummy );\n basic_dummies.push_back ( next_window_dummy );\n }\n\n return basic_dummies;\n }\n\n void Stretch_layout::compress_window_dummies (\n Resize_data& resize_data,\n std::vector < std::shared_ptr < Window_dummy > >& window_dummies\n )\n {\n \/\/ If we need to compress the window_dummies\n if ( resize_data.already_used_length > orientation->get_primary_length ( resize_data.window ) )\n {\n \/\/ If there isn't evene enough space to show every single element, delete the window_dummies\n if ( orientation->get_primary_length( resize_data.window ) < resize_data.elements->size () )\n window_dummies.clear ();\n\n for ( auto it = window_dummies.begin (); it != window_dummies.end (); it++ )\n {\n \/\/ Set primary length to available length * percentage of already used length used by window_dummy\n orientation->set_primary_length ( *it,\n orientation->get_primary_length ( resize_data.window ) *\n ( ( float ) orientation->get_primary_length ( *it ) \/ resize_data.already_used_length ) );\n\n \/\/ Add new length to already used length\n resize_data.already_used_length += orientation->get_primary_length ( *it );\n }\n\n \/\/ Move the window_dummies to prevent overlap or free space\n for ( auto it = window_dummies.begin () + 1; it != window_dummies.end (); it++ )\n {\n orientation->set_primary_coordinate ( *it,\n orientation->get_primary_coordinate ( *( it - 1 ) ) +\n orientation->get_primary_length ( *( it - 1 ) )\n );\n }\n\n \/\/ Update already used length\n resize_data.already_used_length =\n orientation->get_primary_length ( window_dummies.back () ) +\n orientation->get_primary_coordinate ( window_dummies.back () ) -\n orientation->get_primary_coordinate ( window_dummies.front () );\n }\n }\n\n void Stretch_layout::distribute_remaining_length (\n Resize_data& resize_data,\n std::vector < std::shared_ptr < Window_dummy > >& window_dummies\n )\n {\n if ( !window_dummies.empty () )\n {\n int index = 0;\n \/\/ While there still is length to distribute\n while ( resize_data.already_used_length < orientation->get_primary_length ( resize_data.window ) )\n {\n if (\n \/\/ No prefered size\n orientation->get_prefered_length ( resize_data.elements->at ( index ) ) == 0 ||\n \/\/ No elements without preference\n resize_data.no_preference_element_count == 0 ||\n \/\/ Window is compressed\n orientation->get_primary_length ( window_dummies.at ( index ) ) <\n orientation->get_prefered_length ( resize_data.elements->at ( index ) )\n )\n {\n \/\/ Add one to primary_length\n orientation->set_primary_length ( window_dummies.at ( index ),\n orientation->get_primary_length ( window_dummies.at ( index ) ) + 1 );\n\n resize_data.already_used_length++;\n\n \/\/ Shift all windows after this one by one\n for ( int i = index + 1; i < window_dummies.size (); i++ )\n {\n orientation->set_primary_coordinate ( window_dummies.at ( i ),\n orientation->get_primary_coordinate ( window_dummies.at ( i ) ) + 1 );\n }\n }\n\n index++;\n if ( index == window_dummies.size () )\n index = 0;\n }\n }\n }\n}\n<commit_msg>Fix compiler warnings in ncurses::Stretch<commit_after>#include \"stretch.h\"\n#include <algorithm>\n\n\/\/ NOTE: This is everything but beautyful code. Unfortunately, I can't come up with a better way\n\/\/ to solve this problem. If you know a more elegant solution, please contact me.\n\/\/ Even tough I tried my best to comment and explain as much as possible, I wouldn't recommend\n\/\/ spending more time in here than necessary.\n\nnamespace ncurses\n{\n Resize_data::Resize_data (\n const std::vector < std::shared_ptr < Element > >* elements,\n const std::shared_ptr < Window >& window,\n const std::shared_ptr < Orientation >& orientation\n ):\n window ( window ),\n elements ( elements ),\n already_used_length ( 0 )\n {\n \/\/ Create prefered_length_sum\n prefered_length_sum = 0;\n std::for_each ( elements->begin (), elements->end (),\n [ & ] ( std::shared_ptr < Element > element )\n { prefered_length_sum += orientation->get_prefered_length ( element ); } );\n\n \/\/ Create no_preference_element_count\n no_preference_element_count = std::count_if ( elements->begin (), elements->end (),\n [ & ] ( std::shared_ptr < Element > element )\n { return orientation->get_prefered_length ( element ) == 0; } );\n }\n\n void Stretch_layout::update_elements (\n const std::vector < std::shared_ptr < Element > >& elements,\n char key,\n const std::shared_ptr < Window >& window\n )\n {\n \/\/ We need an orientation for this to work\n if ( orientation.get () != nullptr )\n {\n \/\/ Only resize if we have to ( speeds it up a lot )\n if ( has_input_changed ( elements, window ) )\n resize ( elements, window );\n\n \/\/ This is something Stretch_layout::compress_window_dummies does\n \/\/ Look at if for more details\n if ( windows.size () != 0 )\n {\n \/\/ Indexes in elements correspond to indexes in windows\n for ( size_t i = 0; i < elements.size (); i++ )\n {\n elements.at ( i )->update ( key, windows.at ( i ) );\n }\n }\n }\n else\n {\n window->draw_string ( \"Missing Orientation!\" );\n window->refresh ();\n }\n }\n\n void Stretch_layout::set_orientation ( const std::shared_ptr < Orientation >& orientation )\n {\n this->orientation = orientation;\n }\n\n bool Stretch_layout::has_input_changed (\n const std::vector < std::shared_ptr < Element > >& elements,\n const std::shared_ptr < Window >& window\n )\n {\n \/\/ elements or something about the window has changed\n return (\n elements != last_elements ||\n window->get_x () != last_window.x ||\n window->get_y () != last_window.y ||\n window->get_width () != last_window.width||\n window->get_height () != last_window.height\n );\n }\n\n void Stretch_layout::resize (\n const std::vector < std::shared_ptr < Element > >& elements,\n const std::shared_ptr < Window >& window\n )\n {\n \/\/ Remove all old windows\n windows.clear ();\n Resize_data resize_data ( &elements, window, orientation );\n\n \/\/ Generate window_dummies\n std::vector < std::shared_ptr < Window_dummy > > window_dummies = generate_window_dummies ( resize_data );\n \/\/ Turn window_dummies into actual windows and put them into windows\n for ( auto it = window_dummies.begin (); it != window_dummies.end (); it++ )\n {\n std::shared_ptr < Window > element_window = std::make_shared < Window > (\n ( *it )->x,\n ( *it )->y,\n ( *it )->width,\n ( *it )->height\n );\n windows.push_back ( element_window );\n }\n }\n\n std::vector < std::shared_ptr < Window_dummy > > Stretch_layout::generate_window_dummies ( Resize_data& resize_data )\n {\n \/\/ Generate basic window_dummies, they might be longer than the available length\n std::vector < std::shared_ptr < Window_dummy > > window_dummies = generate_basic_window_dummies ( resize_data );\n \/\/ Now scale them down, if they are longer\n compress_window_dummies ( resize_data, window_dummies );\n \/\/ And distribut remaining length ( created by integer division errors )\n distribute_remaining_length ( resize_data, window_dummies );\n\n return window_dummies;\n }\n\n int Stretch_layout::generate_no_preference_length ( Resize_data& resize_data )\n {\n \/\/ If prefered_lengths are already longer than provided length, return average of prefered_lengths\n if ( resize_data.prefered_length_sum > orientation->get_primary_length ( resize_data.window ) )\n return resize_data.prefered_length_sum \/ ( resize_data.elements->size () - resize_data.no_preference_element_count );\n else\n \/\/ Return remaining length divided by no_preference_element_count\n return ( orientation->get_primary_length ( resize_data.window ) - resize_data.prefered_length_sum )\n \/ resize_data.no_preference_element_count;\n }\n\n std::vector < std::shared_ptr < Window_dummy > > Stretch_layout::generate_basic_window_dummies ( Resize_data& resize_data )\n {\n std::vector < std::shared_ptr < Window_dummy > > basic_dummies;\n int no_preference_length = generate_no_preference_length ( resize_data );\n\n for ( size_t i = 0; i < resize_data.elements->size (); i++ )\n {\n std::shared_ptr < Window_dummy > next_window_dummy = std::make_shared < Window_dummy > ();\n\n \/\/ Set secondary coordinate and length to the same as window's\n orientation->set_secondary_length ( next_window_dummy, orientation->get_secondary_length ( resize_data.window ) );\n orientation->set_secondary_coordinate ( next_window_dummy, orientation->get_secondary_coordinate ( resize_data.window ) );\n\n \/\/ Set primary coordinate to window's plus the already used length\n orientation->set_primary_coordinate ( next_window_dummy,\n orientation->get_primary_coordinate ( resize_data.window ) + resize_data.already_used_length );\n\n \/\/ If element has a preference, use it\n if ( orientation->get_prefered_length ( resize_data.elements->at ( i ) ) > 0 )\n orientation->set_primary_length ( next_window_dummy, orientation->get_prefered_length ( resize_data.elements->at ( i ) ) );\n else\n \/\/ Use the generated no_preference_length\n orientation->set_primary_length ( next_window_dummy, no_preference_length );\n\n \/\/ Add window_dummy's primary_length to already used length\n resize_data.already_used_length += orientation->get_primary_length ( next_window_dummy );\n basic_dummies.push_back ( next_window_dummy );\n }\n\n return basic_dummies;\n }\n\n void Stretch_layout::compress_window_dummies (\n Resize_data& resize_data,\n std::vector < std::shared_ptr < Window_dummy > >& window_dummies\n )\n {\n \/\/ If we need to compress the window_dummies\n if ( resize_data.already_used_length > orientation->get_primary_length ( resize_data.window ) )\n {\n \/\/ If there isn't evene enough space to show every single element, delete the window_dummies\n if ( static_cast < size_t > ( orientation->get_primary_length( resize_data.window ) ) < resize_data.elements->size () )\n window_dummies.clear ();\n\n for ( auto it = window_dummies.begin (); it != window_dummies.end (); it++ )\n {\n \/\/ Set primary length to available length * percentage of already used length used by window_dummy\n orientation->set_primary_length ( *it,\n orientation->get_primary_length ( resize_data.window ) *\n ( ( float ) orientation->get_primary_length ( *it ) \/ resize_data.already_used_length ) );\n\n \/\/ Add new length to already used length\n resize_data.already_used_length += orientation->get_primary_length ( *it );\n }\n\n \/\/ Move the window_dummies to prevent overlap or free space\n for ( auto it = window_dummies.begin () + 1; it != window_dummies.end (); it++ )\n {\n orientation->set_primary_coordinate ( *it,\n orientation->get_primary_coordinate ( *( it - 1 ) ) +\n orientation->get_primary_length ( *( it - 1 ) )\n );\n }\n\n \/\/ Update already used length\n resize_data.already_used_length =\n orientation->get_primary_length ( window_dummies.back () ) +\n orientation->get_primary_coordinate ( window_dummies.back () ) -\n orientation->get_primary_coordinate ( window_dummies.front () );\n }\n }\n\n void Stretch_layout::distribute_remaining_length (\n Resize_data& resize_data,\n std::vector < std::shared_ptr < Window_dummy > >& window_dummies\n )\n {\n if ( !window_dummies.empty () )\n {\n size_t index = 0;\n \/\/ While there still is length to distribute\n while ( resize_data.already_used_length < orientation->get_primary_length ( resize_data.window ) )\n {\n if (\n \/\/ No prefered size\n orientation->get_prefered_length ( resize_data.elements->at ( index ) ) == 0 ||\n \/\/ No elements without preference\n resize_data.no_preference_element_count == 0 ||\n \/\/ Window is compressed\n orientation->get_primary_length ( window_dummies.at ( index ) ) <\n orientation->get_prefered_length ( resize_data.elements->at ( index ) )\n )\n {\n \/\/ Add one to primary_length\n orientation->set_primary_length ( window_dummies.at ( index ),\n orientation->get_primary_length ( window_dummies.at ( index ) ) + 1 );\n\n resize_data.already_used_length++;\n\n \/\/ Shift all windows after this one by one\n for ( size_t i = index + 1; i < window_dummies.size (); i++ )\n {\n orientation->set_primary_coordinate ( window_dummies.at ( i ),\n orientation->get_primary_coordinate ( window_dummies.at ( i ) ) + 1 );\n }\n }\n\n index++;\n if ( index == window_dummies.size () )\n index = 0;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * These codes are licensed under the Unlicense.\n * http:\/\/unlicense.org\n *\/\n\n#include <sstream>\n#include <tuple>\n\n#include <gtest\/gtest.h>\n\n#include <furfurylic\/commata\/primitive_parser.hpp>\n#include <furfurylic\/commata\/record_extractor.hpp>\n\n#include \"BaseTest.hpp\"\n\nusing namespace furfurylic::commata;\n\nstruct TestRecordExtractor :\n furfurylic::test::BaseTestWithParam<std::size_t>\n{};\n\nTEST_P(TestRecordExtractor, LeftmostKey)\n{\n const wchar_t* s = L\"key_a,key_b,value_a,value_b\\n\"\n L\"\\\"ka1\\\",kb1,va1,vb1\\r\\n\"\n L\"ka2,kb2,va2,vb2\\n\"\n L\"ka1,kb3,vb3,\\\"vb3\\\"\\r\";\n std::wstringbuf in(s);\n std::wstringbuf out;\n parse(&in, make_record_extractor(&out, L\"key_a\", L\"ka1\"), GetParam());\n ASSERT_EQ(L\"key_a,key_b,value_a,value_b\\n\"\n L\"\\\"ka1\\\",kb1,va1,vb1\\n\"\n L\"ka1,kb3,vb3,\\\"vb3\\\"\\n\",\n out.str());\n}\n\nTEST_P(TestRecordExtractor, InnerKey)\n{\n const char* s = \"\\r\\n\\n\"\n \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb01,va1,vb1\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\";\n std::stringbuf in(s);\n std::ostringstream out;\n parse(&in, make_record_extractor(out, \"key_b\",\n [](const char* first ,const char* last) {\n return std::string(first, last).substr(0, 3) == \"kb1\";\n }), GetParam());\n ASSERT_EQ(\"key_a,key_b,value_a,value_b\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\\n\",\n out.str());\n}\n\nTEST_P(TestRecordExtractor, NoSuchKey)\n{\n const char* s = \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb01,va1,vb1\\n\"\n \"ka2,kb12,va2,vb2\\n\";\n std::stringbuf in(s);\n std::stringbuf out;\n try {\n parse(&in, make_record_extractor(&out, \"key_c\", \"kc1\"), GetParam());\n FAIL();\n } catch (const record_extraction_error& e) {\n ASSERT_NE(e.get_physical_position(), nullptr);\n ASSERT_EQ(0U, e.get_physical_position()->first);\n std::string message(e.what());\n ASSERT_TRUE(message.find(\"key_c\") != std::string::npos);\n }\n}\n\nTEST_P(TestRecordExtractor, NoSuchField)\n{\n const char* s = \"key_a,key_b\\r\"\n \"k1\\r\"\n \"k0,k1,k2\\r\";\n std::stringbuf in(s);\n std::stringbuf out;\n ASSERT_TRUE(parse(&in,\n make_record_extractor(&out, \"key_b\", \"k1\"), GetParam()));\n ASSERT_EQ(\"key_a,key_b\\n\"\n \"k0,k1,k2\\n\",\n out.str());\n}\n\nINSTANTIATE_TEST_CASE_P(, TestRecordExtractor, testing::Values(1, 10, 1024));\n\nstruct TestRecordExtractorLimit :\n testing::TestWithParam<std::tuple<bool, std::size_t>>\n{};\n\nTEST_P(TestRecordExtractorLimit, Basics)\n{\n const auto includes_header = std::get<0>(GetParam());\n const auto max_record_num = std::get<1>(GetParam());\n const char* s = \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb1,va1,vb1\\r\"\n \"ka2,kb2,va2,vb2\\n\"\n \"ka1,kb3,vb3,vb3\\n\";\n std::stringbuf in(s);\n std::stringbuf out;\n const auto result = parse(&in, make_record_extractor(\n &out, \"key_a\", \"ka1\", includes_header, max_record_num), 2);\n ASSERT_EQ(max_record_num > 1, result);\n std::string expected;\n if (includes_header) {\n expected += \"key_a,key_b,value_a,value_b\\n\";\n }\n expected += \"ka1,kb1,va1,vb1\\n\";\n if (max_record_num > 1) {\n expected += \"ka1,kb3,vb3,vb3\\n\";\n }\n ASSERT_EQ(expected, out.str());\n}\n\nINSTANTIATE_TEST_CASE_P(, TestRecordExtractorLimit,\n testing::Combine(\n testing::Bool(),\n testing::Values(1, std::numeric_limits<std::size_t>::max())));\n\nstruct TestRecordExtractorLimit0 : furfurylic::test::BaseTest\n{};\n\nTEST_F(TestRecordExtractorLimit0, IncludeHeader)\n{\n const char* s = \"key_a,key_b,value_a,value_b\\r\"\n \"ka1,kb1,va1,\\\"vb1\\r\"; \/\/ Ill-formed row, but not parsed\n std::stringbuf in(s);\n std::stringbuf out;\n const auto result = parse(&in,\n make_record_extractor(&out, \"key_a\", \"ka1\", true, 0), 64);\n ASSERT_FALSE(result);\n std::string expected;\n ASSERT_EQ(\"key_a,key_b,value_a,value_b\\n\", out.str());\n}\n\nTEST_F(TestRecordExtractorLimit0, ExcludeHeaderNoSuchKey)\n{\n const char* s = \"key_a,key_b,value_a,value_b\\r\"\n \"ka1,kb1,va1,vb1\\r\";\n std::stringbuf in(s);\n std::stringbuf out;\n try {\n parse(&in, make_record_extractor(&out, \"key_A\", \"ka1\", false, 0), 64);\n FAIL();\n } catch (const record_extraction_error& e) {\n ASSERT_NE(e.get_physical_position(), nullptr);\n ASSERT_EQ(0U, e.get_physical_position()->first);\n }\n}\n\nstruct TestRecordExtractorIndexed : furfurylic::test::BaseTest\n{};\n\nTEST_F(TestRecordExtractorIndexed, Basics)\n{\n const char* s = \"\\r\\n\\n\"\n \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb01,va1,vb1\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\";\n std::stringbuf in(s);\n std::ostringstream out;\n parse(&in, make_record_extractor(out, 1,\n [](const char* first ,const char* last) {\n return std::string(first, last).substr(0, 3) == \"kb1\";\n }), 1024);\n ASSERT_EQ(\"key_a,key_b,value_a,value_b\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\\n\",\n out.str());\n}\n\nstruct FinalPredicateForValue final\n{\n bool operator()(const char* first ,const char* last) const\n {\n return std::string(first, last).substr(0, 3) == \"kb1\";\n }\n};\n\nstruct TestRecordExtractorFinalPredicateForValue : furfurylic::test::BaseTest\n{};\n\nTEST_F(TestRecordExtractorFinalPredicateForValue, Basics)\n{\n const char* s = \"\\r\\n\\n\"\n \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb01,va1,vb1\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\";\n std::stringbuf in(s);\n std::stringbuf out;\n parse(&in, make_record_extractor(&out, 1, FinalPredicateForValue()), 1024);\n ASSERT_EQ(\"key_a,key_b,value_a,value_b\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\\n\",\n out.str());\n}\n<commit_msg>Add a test that ensures record_extractor can handle wrapped-reference predicates<commit_after>\/**\n * These codes are licensed under the Unlicense.\n * http:\/\/unlicense.org\n *\/\n\n#include <sstream>\n#include <tuple>\n\n#include <gtest\/gtest.h>\n\n#include <furfurylic\/commata\/primitive_parser.hpp>\n#include <furfurylic\/commata\/record_extractor.hpp>\n\n#include \"BaseTest.hpp\"\n\nusing namespace furfurylic::commata;\n\nstruct TestRecordExtractor :\n furfurylic::test::BaseTestWithParam<std::size_t>\n{};\n\nTEST_P(TestRecordExtractor, LeftmostKey)\n{\n const wchar_t* s = L\"key_a,key_b,value_a,value_b\\n\"\n L\"\\\"ka1\\\",kb1,va1,vb1\\r\\n\"\n L\"ka2,kb2,va2,vb2\\n\"\n L\"ka1,kb3,vb3,\\\"vb3\\\"\\r\";\n std::wstringbuf in(s);\n std::wstringbuf out;\n parse(&in, make_record_extractor(&out, L\"key_a\", L\"ka1\"), GetParam());\n ASSERT_EQ(L\"key_a,key_b,value_a,value_b\\n\"\n L\"\\\"ka1\\\",kb1,va1,vb1\\n\"\n L\"ka1,kb3,vb3,\\\"vb3\\\"\\n\",\n out.str());\n}\n\nTEST_P(TestRecordExtractor, InnerKey)\n{\n const char* s = \"\\r\\n\\n\"\n \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb01,va1,vb1\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\";\n std::stringbuf in(s);\n std::ostringstream out;\n parse(&in, make_record_extractor(out, \"key_b\",\n [](const char* first ,const char* last) {\n return std::string(first, last).substr(0, 3) == \"kb1\";\n }), GetParam());\n ASSERT_EQ(\"key_a,key_b,value_a,value_b\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\\n\",\n out.str());\n}\n\nTEST_P(TestRecordExtractor, NoSuchKey)\n{\n const char* s = \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb01,va1,vb1\\n\"\n \"ka2,kb12,va2,vb2\\n\";\n std::stringbuf in(s);\n std::stringbuf out;\n try {\n parse(&in, make_record_extractor(&out, \"key_c\", \"kc1\"), GetParam());\n FAIL();\n } catch (const record_extraction_error& e) {\n ASSERT_NE(e.get_physical_position(), nullptr);\n ASSERT_EQ(0U, e.get_physical_position()->first);\n std::string message(e.what());\n ASSERT_TRUE(message.find(\"key_c\") != std::string::npos);\n }\n}\n\nTEST_P(TestRecordExtractor, NoSuchField)\n{\n const char* s = \"key_a,key_b\\r\"\n \"k1\\r\"\n \"k0,k1,k2\\r\";\n std::stringbuf in(s);\n std::stringbuf out;\n ASSERT_TRUE(parse(&in,\n make_record_extractor(&out, \"key_b\", \"k1\"), GetParam()));\n ASSERT_EQ(\"key_a,key_b\\n\"\n \"k0,k1,k2\\n\",\n out.str());\n}\n\nINSTANTIATE_TEST_CASE_P(, TestRecordExtractor, testing::Values(1, 10, 1024));\n\nstruct TestRecordExtractorLimit :\n testing::TestWithParam<std::tuple<bool, std::size_t>>\n{};\n\nTEST_P(TestRecordExtractorLimit, Basics)\n{\n const auto includes_header = std::get<0>(GetParam());\n const auto max_record_num = std::get<1>(GetParam());\n const char* s = \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb1,va1,vb1\\r\"\n \"ka2,kb2,va2,vb2\\n\"\n \"ka1,kb3,vb3,vb3\\n\";\n std::stringbuf in(s);\n std::stringbuf out;\n const auto result = parse(&in, make_record_extractor(\n &out, \"key_a\", \"ka1\", includes_header, max_record_num), 2);\n ASSERT_EQ(max_record_num > 1, result);\n std::string expected;\n if (includes_header) {\n expected += \"key_a,key_b,value_a,value_b\\n\";\n }\n expected += \"ka1,kb1,va1,vb1\\n\";\n if (max_record_num > 1) {\n expected += \"ka1,kb3,vb3,vb3\\n\";\n }\n ASSERT_EQ(expected, out.str());\n}\n\nINSTANTIATE_TEST_CASE_P(, TestRecordExtractorLimit,\n testing::Combine(\n testing::Bool(),\n testing::Values(1, std::numeric_limits<std::size_t>::max())));\n\nstruct TestRecordExtractorLimit0 : furfurylic::test::BaseTest\n{};\n\nTEST_F(TestRecordExtractorLimit0, IncludeHeader)\n{\n const char* s = \"key_a,key_b,value_a,value_b\\r\"\n \"ka1,kb1,va1,\\\"vb1\\r\"; \/\/ Ill-formed row, but not parsed\n std::stringbuf in(s);\n std::stringbuf out;\n const auto result = parse(&in,\n make_record_extractor(&out, \"key_a\", \"ka1\", true, 0), 64);\n ASSERT_FALSE(result);\n std::string expected;\n ASSERT_EQ(\"key_a,key_b,value_a,value_b\\n\", out.str());\n}\n\nTEST_F(TestRecordExtractorLimit0, ExcludeHeaderNoSuchKey)\n{\n const char* s = \"key_a,key_b,value_a,value_b\\r\"\n \"ka1,kb1,va1,vb1\\r\";\n std::stringbuf in(s);\n std::stringbuf out;\n try {\n parse(&in, make_record_extractor(&out, \"key_A\", \"ka1\", false, 0), 64);\n FAIL();\n } catch (const record_extraction_error& e) {\n ASSERT_NE(e.get_physical_position(), nullptr);\n ASSERT_EQ(0U, e.get_physical_position()->first);\n }\n}\n\nstruct TestRecordExtractorIndexed : furfurylic::test::BaseTest\n{};\n\nTEST_F(TestRecordExtractorIndexed, Basics)\n{\n const char* s = \"\\r\\n\\n\"\n \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb01,va1,vb1\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\";\n std::stringbuf in(s);\n std::ostringstream out;\n parse(&in, make_record_extractor(out, 1,\n [](const char* first ,const char* last) {\n return std::string(first, last).substr(0, 3) == \"kb1\";\n }), 1024);\n ASSERT_EQ(\"key_a,key_b,value_a,value_b\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\\n\",\n out.str());\n}\n\nstruct FinalPredicateForValue final\n{\n bool operator()(const char* first ,const char* last) const\n {\n return std::string(first, last).substr(0, 3) == \"kb1\";\n }\n};\n\nstruct TestRecordExtractorFinalPredicateForValue : furfurylic::test::BaseTest\n{};\n\nTEST_F(TestRecordExtractorFinalPredicateForValue, Basics)\n{\n const char* s = \"\\r\\n\\n\"\n \"key_a,key_b,value_a,value_b\\n\"\n \"ka1,kb01,va1,vb1\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\";\n std::stringbuf in(s);\n std::stringbuf out;\n parse(&in, make_record_extractor(&out, 1, FinalPredicateForValue()), 1024);\n ASSERT_EQ(\"key_a,key_b,value_a,value_b\\n\"\n \"ka2,kb12,va2,vb2\\n\"\n \"ka1,kb13,\\\"vb\\n3\\\",vb3\\n\",\n out.str());\n}\n\nstruct TestRecordExtractorReference : furfurylic::test::BaseTest\n{};\n\nTEST_F(TestRecordExtractorReference, Basics)\n{\n const char* s = \"instrument,type\\n\"\n \"viola,string\\n\"\n \"tuba,brass\\n\"\n \"clarinet,woodwind\\n\"\n \"koto,string\";\n std::stringbuf in(s);\n std::stringbuf out;\n\n const auto key_pred = [](auto begin, auto end) {\n return ((end - begin) >= 3) && (std::strncmp(begin, \"typ\", 3) == 0);\n };\n const auto value_pred = [](auto begin, auto end) {\n const std::string value(begin, end);\n return (value == \"brass\") || (value == \"woodwind\");\n };\n\n \/\/ Freaking VS2015 picks up parse's overload for reference_wrappers\n \/\/ and complain about ambiguity, so we squelch it by force with explicit\n \/\/ template arguments\n auto ex = make_record_extractor(\n &out, std::ref(key_pred), std::ref(value_pred));\n parse<std::char_traits<char>, decltype(ex)>(&in, std::move(ex));\n ASSERT_EQ(\"instrument,type\\n\"\n \"tuba,brass\\n\"\n \"clarinet,woodwind\\n\",\n out.str());\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_PRIM_META_REF_TYPE_HPP\n#define STAN_MATH_PRIM_META_REF_TYPE_HPP\n\n#include <stan\/math\/prim\/meta\/is_eigen.hpp>\n#include <stan\/math\/prim\/meta\/is_arena_matrix.hpp>\n#include <stan\/math\/prim\/meta\/is_vector.hpp>\n#include <stan\/math\/prim\/meta\/plain_type.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n\n#include <type_traits>\n\nnamespace stan {\n\n\/**\n * If the condition is true determines appropriate type for assigning expression\n * of given type to, to evaluate expensive expressions, but not make a copy if T\n * involves no calculations. This works similarly as `Eigen::Ref`. It also\n * handles rvalue references, so it can be used with perfect forwarding. If the\n * condition is false the expression will never be evaluated.\n *\n * Warning: if a variable of this type could be assigned a rvalue, make sure\n * template parameter `T` is of correct reference type (rvalue).\n * @tparam T type to determine reference for\n *\/\ntemplate <bool Condition, typename T, typename = void>\nstruct ref_type_if {\n using T_plain = plain_type_t<T>;\n using T_optionally_ref\n = std::conditional_t<std::is_rvalue_reference<T>::value,\n std::remove_reference_t<T>, const T&>;\n using type = std::conditional_t<\n Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain>>>::\n template match<std::decay_t<T>>::MatchAtCompileTime\n || !Condition,\n T_optionally_ref, T_plain>;\n};\n\ntemplate <bool Condition, typename T>\nstruct ref_type_if<Condition, T,\n require_t<bool_constant<!is_eigen<T>::value\n || is_arena_matrix<T>::value>>> {\n using type = std::conditional_t<std::is_rvalue_reference<T>::value,\n std::remove_reference_t<T>, const T&>;\n};\n\ntemplate <typename T>\nusing ref_type_t = typename ref_type_if<true, T>::type;\n\ntemplate <bool Condition, typename T>\nusing ref_type_if_t = typename ref_type_if<Condition, T>::type;\n\n\/**\n * Determines appropriate type for assigning expression of given type to, so\n * that the resulting type has directly accessible contiguous colum-major data,\n * which is needed to copy to OpenCL device for construction of matrix_cl.\n *\n * THis is similar to `ref_type` except this also copies expressions, which do\n * not have contiguous data (in both dimensions) or have row major storage\n * order.\n *\n * Warning: if a variable of this type could be assigned a rvalue, make sure\n * template parameter `T` is of correct reference type (rvalue).\n * @tparam T type to determine reference for\n *\/\ntemplate <typename T, typename = void>\nstruct ref_type_for_opencl {\n using T_val = std::remove_reference_t<T>;\n using T_plain_col_major = std::conditional_t<\n std::is_same<typename Eigen::internal::traits<T_val>::XprKind,\n Eigen::MatrixXpr>::value,\n Eigen::Matrix<value_type_t<T>, T_val::RowsAtCompileTime,\n T_val::ColsAtCompileTime>,\n Eigen::Array<value_type_t<T>, T_val::RowsAtCompileTime,\n T_val::ColsAtCompileTime>>;\n using T_optionally_ref\n = std::conditional_t<std::is_rvalue_reference<T>::value, T_val, const T&>;\n \/\/ Setting Outer stride of Ref to 0 (default) won't actually check that\n \/\/ expression has contiguous outer stride. Instead we need to check that\n \/\/ evaluator flags contain LinearAccessBit and PacketAccessBit.\n using type = std::conditional_t<\n Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain_col_major>>>::\n template match<T_val>::MatchAtCompileTime\n && (Eigen::internal::evaluator<T_val>::Flags & Eigen::LinearAccessBit)\n && (Eigen::internal::evaluator<T_val>::Flags\n & Eigen::PacketAccessBit),\n T_optionally_ref, T_plain_col_major>;\n};\n\ntemplate <typename T>\nstruct ref_type_for_opencl<T, require_not_eigen_t<T>> {\n using type = std::conditional_t<std::is_rvalue_reference<T>::value,\n std::remove_reference_t<T>, const T&>;\n};\n\ntemplate <typename T>\nusing ref_type_for_opencl_t = typename ref_type_for_opencl<T>::type;\n\n} \/\/ namespace stan\n\n#endif\n<commit_msg>fix ref_type_for_opencl to also use non-eigen version for arena_matrix<commit_after>#ifndef STAN_MATH_PRIM_META_REF_TYPE_HPP\n#define STAN_MATH_PRIM_META_REF_TYPE_HPP\n\n#include <stan\/math\/prim\/meta\/is_eigen.hpp>\n#include <stan\/math\/prim\/meta\/is_arena_matrix.hpp>\n#include <stan\/math\/prim\/meta\/is_vector.hpp>\n#include <stan\/math\/prim\/meta\/plain_type.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n\n#include <type_traits>\n\nnamespace stan {\n\n\/**\n * If the condition is true determines appropriate type for assigning expression\n * of given type to, to evaluate expensive expressions, but not make a copy if T\n * involves no calculations. This works similarly as `Eigen::Ref`. It also\n * handles rvalue references, so it can be used with perfect forwarding. If the\n * condition is false the expression will never be evaluated.\n *\n * Warning: if a variable of this type could be assigned a rvalue, make sure\n * template parameter `T` is of correct reference type (rvalue).\n * @tparam T type to determine reference for\n *\/\ntemplate <bool Condition, typename T, typename = void>\nstruct ref_type_if {\n using T_plain = plain_type_t<T>;\n using T_optionally_ref\n = std::conditional_t<std::is_rvalue_reference<T>::value,\n std::remove_reference_t<T>, const T&>;\n using type = std::conditional_t<\n Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain>>>::\n template match<std::decay_t<T>>::MatchAtCompileTime\n || !Condition,\n T_optionally_ref, T_plain>;\n};\n\ntemplate <bool Condition, typename T>\nstruct ref_type_if<Condition, T,\n require_t<bool_constant<!is_eigen<T>::value\n || is_arena_matrix<T>::value>>> {\n using type = std::conditional_t<std::is_rvalue_reference<T>::value,\n std::remove_reference_t<T>, const T&>;\n};\n\ntemplate <typename T>\nusing ref_type_t = typename ref_type_if<true, T>::type;\n\ntemplate <bool Condition, typename T>\nusing ref_type_if_t = typename ref_type_if<Condition, T>::type;\n\n\/**\n * Determines appropriate type for assigning expression of given type to, so\n * that the resulting type has directly accessible contiguous colum-major data,\n * which is needed to copy to OpenCL device for construction of matrix_cl.\n *\n * THis is similar to `ref_type` except this also copies expressions, which do\n * not have contiguous data (in both dimensions) or have row major storage\n * order.\n *\n * Warning: if a variable of this type could be assigned a rvalue, make sure\n * template parameter `T` is of correct reference type (rvalue).\n * @tparam T type to determine reference for\n *\/\ntemplate <typename T, typename = void>\nstruct ref_type_for_opencl {\n using T_val = std::remove_reference_t<T>;\n using T_plain_col_major = std::conditional_t<\n std::is_same<typename Eigen::internal::traits<T_val>::XprKind,\n Eigen::MatrixXpr>::value,\n Eigen::Matrix<value_type_t<T>, T_val::RowsAtCompileTime,\n T_val::ColsAtCompileTime>,\n Eigen::Array<value_type_t<T>, T_val::RowsAtCompileTime,\n T_val::ColsAtCompileTime>>;\n using T_optionally_ref\n = std::conditional_t<std::is_rvalue_reference<T>::value, T_val, const T&>;\n \/\/ Setting Outer stride of Ref to 0 (default) won't actually check that\n \/\/ expression has contiguous outer stride. Instead we need to check that\n \/\/ evaluator flags contain LinearAccessBit and PacketAccessBit.\n using type = std::conditional_t<\n Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain_col_major>>>::\n template match<T_val>::MatchAtCompileTime\n && (Eigen::internal::evaluator<T_val>::Flags & Eigen::LinearAccessBit)\n && (Eigen::internal::evaluator<T_val>::Flags\n & Eigen::PacketAccessBit),\n T_optionally_ref, T_plain_col_major>;\n};\n\ntemplate <typename T>\nstruct ref_type_for_opencl<T, require_t<bool_constant<!is_eigen<T>::value\n || is_arena_matrix<T>::value>>> {\n using type = std::conditional_t<std::is_rvalue_reference<T>::value,\n std::remove_reference_t<T>, const T&>;\n};\n\ntemplate <typename T>\nusing ref_type_for_opencl_t = typename ref_type_for_opencl<T>::type;\n\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright 2017 Centreon\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** For more information : contact@centreon.com\n*\/\n\n#include <arpa\/inet.h>\n#include <limits>\n#include <memory>\n#include <sstream>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/file\/cfile.hh\"\n#include \"com\/centreon\/broker\/file\/qt_fs_browser.hh\"\n#include \"com\/centreon\/broker\/file\/splitter.hh\"\n#include \"com\/centreon\/broker\/io\/exceptions\/shutdown.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n\nusing namespace com::centreon::broker;\nusing namespace com::centreon::broker::file;\n\n\/**\n * Build a new splitter.\n *\n * @param[in] path Base path to file.\n * @param[in] mode Ignored. Files will always be open\n * read\/write.\n * @param[in] file_factory fs_file_factory to work with single files.\n * @param[in] fs fs_browser object to manipulate file\n * system.\n * @param[in] max_file_size Maximum single file size.\n * @param[in] auto_delete True to delete file parts as they are\n * read.\n *\/\nsplitter::splitter(\n std::string const& path,\n fs_file::open_mode mode,\n fs_file_factory* file_factory,\n fs_browser* fs,\n long max_file_size,\n bool auto_delete)\n : _auto_delete(auto_delete),\n _base_path(path),\n _file_factory(file_factory),\n _fs(fs),\n _max_file_size(max_file_size) {\n (void)mode;\n\n \/\/ Set max file size.\n static long min_file_size(10000000);\n if (!_max_file_size) {\n _max_file_size = std::numeric_limits<long>::max();\n }\n else if (_max_file_size < min_file_size)\n _max_file_size = min_file_size;\n\n \/\/ Get IDs of already existing file parts.\n \/\/ XXX\n}\n\n\/**\n * Destructor.\n *\/\nsplitter::~splitter() {}\n\n\/**\n * Read data.\n *\n * @param[out] buffer Output buffer.\n * @param[in] max_size Maximum number of bytes that can be read.\n *\n * @return Number of bytes read.\n *\/\nlong splitter::read(void* buffer, long max_size) {\n \/\/ Check if we should read.\n if (!_rfile.data()) {\n \/\/ If read-ID equals write-ID, then we're finished.\n if (_rid >= _wid) {\n _wfile.clear();\n throw (io::exceptions::shutdown(true, true)\n << \"end of file\");\n }\n \/\/ Otherwise open next ID.\n _open_next_read();\n }\n\n \/\/ Seek to position.\n _rfile->seek(_roffset);\n\n \/\/ Read data.\n long rb;\n try {\n rb = _rfile->read(buffer, max_size);\n }\n catch (io::exceptions::shutdown const& e) {\n (void)e;\n if (_wid == _rid) {\n _rfile.clear();\n _wfile.clear();\n std::string file_path(_file_path(_rid));\n if (_auto_delete) {\n logging::info(logging::high) << \"file: end of last file '\"\n << file_path.c_str() << \"' reached, closing and erasing file\";\n ::remove(file_path.c_str());\n }\n else {\n logging::info(logging::high) << \"file: end of last file '\"\n << file_path.c_str() << \"' reached, closing but NOT erasing file\";\n }\n throw ;\n }\n _open_next_read();\n rb = _rfile->read(buffer, max_size);\n }\n\n \/\/ Process data.\n logging::debug(logging::low) << \"file: read \" << rb << \" bytes from '\"\n << _file_path(_rid).c_str() << \"'\";\n _roffset += rb;\n return (rb);\n}\n\n\/**\n * Throw an exception.\n *\n * @param[in] offset Unused.\n * @param[in] whence Unused.\n *\/\nvoid splitter::seek(long offset, fs_file::seek_whence whence) {\n (void)offset;\n (void)whence;\n throw (exceptions::msg() << \"cannot seek within a splitted file\");\n}\n\n\/**\n * Get current position.\n *\n * @return Current position in file.\n *\/\nlong splitter::tell() {\n return (_roffset);\n}\n\n\/**\n * Write data.\n *\n * @param[in] buffer Data.\n * @param[in] size Number of bytes in buffer.\n *\n * @return Number of bytes written.\n *\/\nlong splitter::write(void const* buffer, long size) {\n \/\/ Check that file should still be written to.\n if (_wfile.isNull())\n throw (io::exceptions::shutdown(true, true)\n << \"end of file\");\n\n \/\/ Seek to end of file if necessary.\n _wfile->seek(_woffset);\n\n \/\/ Debug message.\n logging::debug(logging::low) << \"file: write request of \"\n << size << \" bytes for '\" << _file_path(_wid).c_str() << \"'\";\n\n \/\/ Open new file if necessary.\n if ((_woffset + size) > _max_file_size)\n _open_next_write();\n\n \/\/ Write data.\n while (size > 0) {\n unsigned long wb(_wfile->write(buffer, size));\n size -= wb;\n _woffset += wb;\n buffer = static_cast<char const*>(buffer) + wb;\n }\n\n return (size);\n}\n\n\/**\n * Get the file path matching the ID.\n *\n * @param[in] id Current ID.\n *\/\nstd::string splitter::_file_path(int id) const {\n if (id) {\n std::ostringstream oss;\n oss << _base_path << id;\n return (oss.str());\n }\n else\n return (_base_path);\n}\n\n\/**\n * Open the next readable file.\n *\/\nvoid splitter::_open_next_read() {\n \/\/ Did we reached the write file ?\n _rfile.clear();\n ++_rid;\n if (_rid == _wid)\n _rfile = _wfile;\n else {\n \/\/ Open next file.\n std::string file_path(_file_path(_rid));\n {\n misc::shared_ptr<fs_file>\n new_file(_file_factory->new_fs_file(\n file_path,\n fs_file::open_read_write_no_create));\n _rfile = new_file;\n }\n }\n _roffset = 0;\n\n \/\/ Remove previous file.\n std::string file_path(_file_path(_rid - 1));\n if (_auto_delete) {\n logging::info(logging::high) << \"file: end of file '\"\n << file_path.c_str() << \"' reached, erasing file\";\n ::remove(file_path.c_str());\n }\n else {\n logging::info(logging::high) << \"file: end of file '\"\n << file_path.c_str() << \"' reached, NOT erasing file\";\n }\n\n return ;\n}\n\n\/**\n * Open the next writable file.\n *\/\nvoid splitter::_open_next_write() {\n \/\/ Open file.\n _wfile.clear();\n ++_wid;\n std::string file_path(_file_path(_wid));\n logging::info(logging::high) << \"file: opening new file '\"\n << file_path.c_str() << \"'\";\n {\n try {\n _wfile = _file_factory->new_fs_file(\n file_path,\n fs_file::open_read_write_no_create);\n }\n catch (exceptions::msg const& e) {\n _wfile = _file_factory->new_fs_file(\n file_path,\n fs_file::open_read_write_truncate);\n }\n }\n\n \/\/ Position.\n _wfile->seek(0, fs_file::seek_end);\n _woffset = _wfile->tell();\n\n if (_woffset < static_cast<long>(2 * sizeof(uint32_t))) {\n \/\/ Rewind to file beginning.\n _wfile->seek(0);\n\n \/\/ Write read offset.\n union {\n char bytes[2 * sizeof(uint32_t)];\n uint32_t integers[2];\n } header;\n header.integers[0] = 0;\n header.integers[1] = htonl(2 * sizeof(uint32_t));\n unsigned int size(0);\n while (size < sizeof(header))\n size += _wfile->write(header.bytes + size, sizeof(header) - size);\n\n \/\/ Set current offset.\n _woffset = 2 * sizeof(uint32_t);\n }\n\n return ;\n}\n\n\/**\n * Build a new default splitter.\n *\n * @param[in] path Path to file.\n * @param[in] mode Open mode (ignored).\n *\n * @return A new default splitter.\n *\/\nfs_file* splitter_factory::new_fs_file(\n std::string const& path,\n fs_file::open_mode mode) {\n return (new_cfile_splitter(path, mode));\n}\n\n\/**\n * Build a new cfile splitter.\n *\n * @param[in] path Path to file.\n * @param[in] mode Open mode (ignored).\n * @param[in] max_file_size Max single file size.\n * @param[in] auto_delete True to delete file parts as they are\n * read.\n *\n * @return A new cfile splitter.\n *\/\nsplitter* splitter_factory::new_cfile_splitter(\n std::string const& path,\n fs_file::open_mode mode,\n long max_file_size,\n bool auto_delete) {\n std::auto_ptr<fs_file_factory> f(new cfile_factory());\n std::auto_ptr<fs_browser> b(new qt_fs_browser());\n splitter* s(new splitter(\n path,\n mode,\n f.get(),\n b.get(),\n max_file_size,\n auto_delete));\n f.release();\n b.release();\n return (s);\n}\n<commit_msg>core: find current read and write file IDs in file::splitter.<commit_after>\/*\n** Copyright 2017 Centreon\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** For more information : contact@centreon.com\n*\/\n\n#include <arpa\/inet.h>\n#include <limits>\n#include <memory>\n#include <sstream>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/file\/cfile.hh\"\n#include \"com\/centreon\/broker\/file\/qt_fs_browser.hh\"\n#include \"com\/centreon\/broker\/file\/splitter.hh\"\n#include \"com\/centreon\/broker\/io\/exceptions\/shutdown.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n\nusing namespace com::centreon::broker;\nusing namespace com::centreon::broker::file;\n\n\/**\n * Build a new splitter.\n *\n * @param[in] path Base path to file.\n * @param[in] mode Ignored. Files will always be open\n * read\/write.\n * @param[in] file_factory fs_file_factory to work with single files.\n * @param[in] fs fs_browser object to manipulate file\n * system.\n * @param[in] max_file_size Maximum single file size.\n * @param[in] auto_delete True to delete file parts as they are\n * read.\n *\/\nsplitter::splitter(\n std::string const& path,\n fs_file::open_mode mode,\n fs_file_factory* file_factory,\n fs_browser* fs,\n long max_file_size,\n bool auto_delete)\n : _auto_delete(auto_delete),\n _base_path(path),\n _file_factory(file_factory),\n _fs(fs),\n _max_file_size(max_file_size),\n _rid(0),\n _roffset(0),\n _wid(0),\n _woffset(0) {\n (void)mode;\n\n \/\/ Set max file size.\n static long min_file_size(10000000);\n if (!_max_file_size) {\n _max_file_size = std::numeric_limits<long>::max();\n }\n else if (_max_file_size < min_file_size)\n _max_file_size = min_file_size;\n\n \/\/ Get IDs of already existing file parts. File parts are suffixed\n \/\/ with their order number. A file named \/var\/lib\/foo would have\n \/\/ parts named \/var\/lib\/foo, \/var\/lib\/foo1, \/var\/lib\/foo2, ...\n \/\/ in this order.\n std::string base_dir;\n std::string base_name;\n {\n size_t last_slash(_base_path.find_last_of('\/'));\n if (last_slash == std::string::npos) {\n base_dir = \".\";\n base_name = _base_path;\n }\n else {\n base_dir = _base_path.substr(0, last_slash).c_str();\n base_name = _base_path.substr(last_slash + 1).c_str();\n }\n }\n base_name.append(\"*\");\n fs_browser::entry_list parts(_fs->read_directory(\n base_dir,\n base_name));\n _rid = std::numeric_limits<int>::max();\n _wid = 0;\n for (fs_browser::entry_list::iterator\n it(parts.begin()),\n end(parts.end());\n it != end;\n ++it) {\n char const* ptr(it->c_str() + base_name.size());\n int val(0);\n if (*ptr) { \/\/ Not, empty, conversion needed.\n char* endptr(NULL);\n val = strtol(ptr, &endptr, 10);\n if (ptr && *ptr) \/\/ Invalid conversion.\n continue ;\n }\n\n if (val < _rid)\n _rid = val;\n if (val > _wid)\n _wid = val;\n }\n if (_rid == std::numeric_limits<int>::max())\n _rid = 0;\n\n \/\/ File IDs will be incremented when opening next files.\n --_rid;\n --_wid;\n}\n\n\/**\n * Destructor.\n *\/\nsplitter::~splitter() {}\n\n\/**\n * Read data.\n *\n * @param[out] buffer Output buffer.\n * @param[in] max_size Maximum number of bytes that can be read.\n *\n * @return Number of bytes read.\n *\/\nlong splitter::read(void* buffer, long max_size) {\n \/\/ Check if we should read.\n if (!_rfile.data()) {\n \/\/ If read-ID equals write-ID, then we're finished.\n if (_rid >= _wid) {\n _wfile.clear();\n throw (io::exceptions::shutdown(true, true)\n << \"end of file\");\n }\n \/\/ Otherwise open next ID.\n _open_next_read();\n }\n\n \/\/ Seek to position.\n _rfile->seek(_roffset);\n\n \/\/ Read data.\n long rb;\n try {\n rb = _rfile->read(buffer, max_size);\n }\n catch (io::exceptions::shutdown const& e) {\n (void)e;\n if (_wid == _rid) {\n _rfile.clear();\n _wfile.clear();\n std::string file_path(_file_path(_rid));\n if (_auto_delete) {\n logging::info(logging::high) << \"file: end of last file '\"\n << file_path.c_str() << \"' reached, closing and erasing file\";\n ::remove(file_path.c_str());\n }\n else {\n logging::info(logging::high) << \"file: end of last file '\"\n << file_path.c_str() << \"' reached, closing but NOT erasing file\";\n }\n throw ;\n }\n _open_next_read();\n rb = _rfile->read(buffer, max_size);\n }\n\n \/\/ Process data.\n logging::debug(logging::low) << \"file: read \" << rb << \" bytes from '\"\n << _file_path(_rid).c_str() << \"'\";\n _roffset += rb;\n return (rb);\n}\n\n\/**\n * Throw an exception.\n *\n * @param[in] offset Unused.\n * @param[in] whence Unused.\n *\/\nvoid splitter::seek(long offset, fs_file::seek_whence whence) {\n (void)offset;\n (void)whence;\n throw (exceptions::msg() << \"cannot seek within a splitted file\");\n}\n\n\/**\n * Get current position.\n *\n * @return Current position in file.\n *\/\nlong splitter::tell() {\n return (_roffset);\n}\n\n\/**\n * Write data.\n *\n * @param[in] buffer Data.\n * @param[in] size Number of bytes in buffer.\n *\n * @return Number of bytes written.\n *\/\nlong splitter::write(void const* buffer, long size) {\n \/\/ Check that file should still be written to.\n if (_wfile.isNull())\n throw (io::exceptions::shutdown(true, true)\n << \"end of file\");\n\n \/\/ Seek to end of file if necessary.\n _wfile->seek(_woffset);\n\n \/\/ Debug message.\n logging::debug(logging::low) << \"file: write request of \"\n << size << \" bytes for '\" << _file_path(_wid).c_str() << \"'\";\n\n \/\/ Open new file if necessary.\n if ((_woffset + size) > _max_file_size)\n _open_next_write();\n\n \/\/ Write data.\n while (size > 0) {\n unsigned long wb(_wfile->write(buffer, size));\n size -= wb;\n _woffset += wb;\n buffer = static_cast<char const*>(buffer) + wb;\n }\n\n return (size);\n}\n\n\/**\n * Get the file path matching the ID.\n *\n * @param[in] id Current ID.\n *\/\nstd::string splitter::_file_path(int id) const {\n if (id) {\n std::ostringstream oss;\n oss << _base_path << id;\n return (oss.str());\n }\n else\n return (_base_path);\n}\n\n\/**\n * Open the next readable file.\n *\/\nvoid splitter::_open_next_read() {\n \/\/ Did we reached the write file ?\n _rfile.clear();\n ++_rid;\n if (_rid == _wid)\n _rfile = _wfile;\n else {\n \/\/ Open next file.\n std::string file_path(_file_path(_rid));\n {\n misc::shared_ptr<fs_file>\n new_file(_file_factory->new_fs_file(\n file_path,\n fs_file::open_read_write_no_create));\n _rfile = new_file;\n }\n }\n _roffset = 0;\n\n \/\/ Remove previous file.\n std::string file_path(_file_path(_rid - 1));\n if (_auto_delete) {\n logging::info(logging::high) << \"file: end of file '\"\n << file_path.c_str() << \"' reached, erasing file\";\n ::remove(file_path.c_str());\n }\n else {\n logging::info(logging::high) << \"file: end of file '\"\n << file_path.c_str() << \"' reached, NOT erasing file\";\n }\n\n return ;\n}\n\n\/**\n * Open the next writable file.\n *\/\nvoid splitter::_open_next_write() {\n \/\/ Open file.\n _wfile.clear();\n ++_wid;\n std::string file_path(_file_path(_wid));\n logging::info(logging::high) << \"file: opening new file '\"\n << file_path.c_str() << \"'\";\n {\n try {\n _wfile = _file_factory->new_fs_file(\n file_path,\n fs_file::open_read_write_no_create);\n }\n catch (exceptions::msg const& e) {\n _wfile = _file_factory->new_fs_file(\n file_path,\n fs_file::open_read_write_truncate);\n }\n }\n\n \/\/ Position.\n _wfile->seek(0, fs_file::seek_end);\n _woffset = _wfile->tell();\n\n if (_woffset < static_cast<long>(2 * sizeof(uint32_t))) {\n \/\/ Rewind to file beginning.\n _wfile->seek(0);\n\n \/\/ Write read offset.\n union {\n char bytes[2 * sizeof(uint32_t)];\n uint32_t integers[2];\n } header;\n header.integers[0] = 0;\n header.integers[1] = htonl(2 * sizeof(uint32_t));\n unsigned int size(0);\n while (size < sizeof(header))\n size += _wfile->write(header.bytes + size, sizeof(header) - size);\n\n \/\/ Set current offset.\n _woffset = 2 * sizeof(uint32_t);\n }\n\n return ;\n}\n\n\/**\n * Build a new default splitter.\n *\n * @param[in] path Path to file.\n * @param[in] mode Open mode (ignored).\n *\n * @return A new default splitter.\n *\/\nfs_file* splitter_factory::new_fs_file(\n std::string const& path,\n fs_file::open_mode mode) {\n return (new_cfile_splitter(path, mode));\n}\n\n\/**\n * Build a new cfile splitter.\n *\n * @param[in] path Path to file.\n * @param[in] mode Open mode (ignored).\n * @param[in] max_file_size Max single file size.\n * @param[in] auto_delete True to delete file parts as they are\n * read.\n *\n * @return A new cfile splitter.\n *\/\nsplitter* splitter_factory::new_cfile_splitter(\n std::string const& path,\n fs_file::open_mode mode,\n long max_file_size,\n bool auto_delete) {\n std::auto_ptr<fs_file_factory> f(new cfile_factory());\n std::auto_ptr<fs_browser> b(new qt_fs_browser());\n splitter* s(new splitter(\n path,\n mode,\n f.get(),\n b.get(),\n max_file_size,\n auto_delete));\n f.release();\n b.release();\n return (s);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"label.h\"\n\n#include \"util\/geom.h\"\n#include \"glm\/gtx\/rotate_vector.hpp\"\n#include \"tangram.h\"\n\nnamespace Tangram {\n\nLabel::Label(Label::Transform _transform, glm::vec2 _size, Type _type, Options _options, LabelProperty::Anchor _anchor)\n : m_type(_type),\n m_transform(_transform),\n m_dim(_size),\n m_options(_options),\n m_anchorType(_anchor) {\n\n if (!m_options.collide || m_type == Type::debug){\n enterState(State::visible, 1.0);\n } else {\n m_state = State::wait_occ;\n m_transform.state.alpha = 0.0;\n }\n\n m_occludedLastFrame = false;\n m_occluded = false;\n m_parent = nullptr;\n}\n\nLabel::~Label() {}\n\nbool Label::updateScreenTransform(const glm::mat4& _mvp, const glm::vec2& _screenSize, bool _testVisibility) {\n\n glm::vec2 screenPosition;\n glm::vec2 rotation = {1, 0};\n bool clipped = false;\n\n switch (m_type) {\n case Type::debug:\n case Type::point:\n {\n screenPosition = worldToScreenSpace(_mvp, glm::vec4(m_transform.modelPosition1, 0.0, 1.0),\n _screenSize, clipped);\n\n if (_testVisibility && clipped) {\n return false;\n }\n\n screenPosition += m_anchor;\n\n break;\n }\n case Type::line:\n {\n \/\/ project label position from mercator world space to screen\n \/\/ coordinates\n glm::vec2 ap1 = worldToScreenSpace(_mvp, glm::vec4(m_transform.modelPosition1, 0.0, 1.0),\n _screenSize, clipped);\n glm::vec2 ap2 = worldToScreenSpace(_mvp, glm::vec4(m_transform.modelPosition2, 0.0, 1.0),\n _screenSize, clipped);\n\n \/\/ check whether the label is behind the camera using the\n \/\/ perspective division factor\n if (_testVisibility && clipped) {\n return false;\n }\n\n float length = glm::length(ap2 - ap1);\n\n float exceedHeuristic = 0.3; \/\/ default heuristic : 30%\n\n if (_testVisibility && (m_dim.x > length)) {\n float exceed = 1 - (length \/ m_dim.x);\n if (exceed > exceedHeuristic) {\n return false;\n }\n }\n\n screenPosition = (ap1 + ap2) * 0.5f;\n\n rotation = (ap1.x <= ap2.x ? ap2 - ap1 : ap1 - ap2) \/ length;\n\n break;\n }\n }\n\n glm::vec2 offset = rotateBy(m_options.offset, rotation);\n\n m_transform.state.screenPos = screenPosition + offset;\n m_transform.state.rotation = rotation;\n\n return true;\n}\n\nvoid Label::setParent(const Label& _parent, bool _definePriority) {\n m_parent = &_parent;\n\n glm::vec2 anchorDir = LabelProperty::anchorDirection(_parent.anchorType());\n glm::vec2 anchorOrigin = anchorDir * _parent.dimension() * 0.5f;\n applyAnchor(m_dim + _parent.dimension(), anchorOrigin, m_anchorType);\n\n if (_definePriority) {\n m_options.priority = _parent.options().priority + 0.5f;\n }\n\n m_options.offset += _parent.options().offset;\n}\n\nbool Label::offViewport(const glm::vec2& _screenSize) {\n const auto& quad = m_obb.getQuad();\n\n for (int i = 0; i < 4; ++i) {\n const auto& p = quad[i];\n if (p.x < _screenSize.x && p.y < _screenSize.y && p.x > 0 && p.y > 0) {\n return false;\n }\n }\n\n return true;\n}\n\nbool Label::canOcclude() {\n if (!m_options.collide) {\n return false;\n }\n\n int occludeFlags = (State::visible |\n State::wait_occ |\n State::skip_transition |\n State::fading_in |\n State::sleep |\n State::out_of_screen |\n State::dead);\n\n return (occludeFlags & m_state) && !(m_type == Type::debug);\n}\n\nbool Label::visibleState() const {\n int visibleFlags = (State::visible |\n State::fading_in |\n State::fading_out |\n State::skip_transition);\n\n return (visibleFlags & m_state);\n}\n\nvoid Label::skipTransitions() {\n enterState(State::skip_transition, 0.0);\n}\n\nglm::vec2 Label::center() const {\n return m_obb.getCentroid();\n}\n\nvoid Label::enterState(const State& _state, float _alpha) {\n if (m_state == State::dead) { return; }\n\n m_state = _state;\n setAlpha(_alpha);\n}\n\nvoid Label::setAlpha(float _alpha) {\n m_transform.state.alpha = CLAMP(_alpha, 0.0, 1.0);\n}\n\nvoid Label::resetState() {\n if (m_state == State::dead) { return; }\n\n m_occludedLastFrame = false;\n m_occluded = false;\n enterState(State::wait_occ, 0.0);\n}\n\nbool Label::update(const glm::mat4& _mvp, const glm::vec2& _screenSize, float _zoomFract, bool _allLabels) {\n\n m_occludedLastFrame = m_occluded;\n m_occluded = false;\n\n if (m_state == State::dead) {\n if (!_allLabels) {\n return false;\n } else {\n m_occluded = true;\n }\n }\n\n bool ruleSatisfied = updateScreenTransform(_mvp, _screenSize, !_allLabels);\n\n \/\/ one of the label rules has not been satisfied\n if (!ruleSatisfied) {\n enterState(State::sleep, 0.0);\n return false;\n }\n\n \/\/ update the view-space bouding box\n updateBBoxes(_zoomFract);\n\n \/\/ checks whether the label is out of the viewport\n if (offViewport(_screenSize)) {\n enterState(State::out_of_screen, 0.0);\n if (m_occludedLastFrame) {\n m_occluded = true;\n return false;\n }\n } else if (m_state == State::out_of_screen) {\n if (m_occludedLastFrame) {\n enterState(State::sleep, 0.0);\n } else {\n enterState(State::visible, 1.0);\n }\n }\n\n return true;\n}\n\nbool Label::evalState(const glm::vec2& _screenSize, float _dt) {\n\n \/\/ if (Tangram::getDebugFlag(DebugFlags::all_labels)) {\n \/\/ enterState(State::visible, 1.0);\n \/\/ return false;\n \/\/ }\n\n bool animate = false;\n\n switch (m_state) {\n case State::visible:\n if (m_occluded) {\n m_fade = FadeEffect(false, m_options.hideTransition.ease,\n m_options.hideTransition.time);\n enterState(State::fading_out, 1.0);\n animate = true;\n }\n break;\n case State::fading_in:\n if (m_occluded) {\n enterState(State::sleep, 0.0);\n \/\/ enterState(State::fading_out, m_transform.state.alpha);\n \/\/ animate = true;\n break;\n }\n setAlpha(m_fade.update(_dt));\n animate = true;\n if (m_fade.isFinished()) {\n enterState(State::visible, 1.0);\n }\n break;\n case State::fading_out:\n if (!m_occluded) {\n enterState(State::fading_in, m_transform.state.alpha);\n animate = true;\n break;\n }\n setAlpha(m_fade.update(_dt));\n animate = true;\n if (m_fade.isFinished()) {\n enterState(State::sleep, 0.0);\n }\n break;\n case State::wait_occ:\n if (m_occluded) {\n enterState(State::sleep, 0.0);\n } else {\n m_fade = FadeEffect(true, m_options.showTransition.ease,\n m_options.showTransition.time);\n enterState(State::fading_in, 0.0);\n animate = true;\n }\n break;\n case State::skip_transition:\n if (m_occluded) {\n enterState(State::sleep, 0.0);\n } else {\n enterState(State::visible, 1.0);\n }\n break;\n case State::sleep:\n if (!m_occluded) {\n m_fade = FadeEffect(true, m_options.showTransition.ease,\n m_options.showTransition.time);\n enterState(State::fading_in, 0.0);\n animate = true;\n }\n break;\n case State::dead:\n case State::out_of_screen:\n break;\n }\n\n return animate;\n}\n\n}\n<commit_msg>keep screen position center at world center (less sliding in tilted view)<commit_after>#include \"label.h\"\n\n#include \"util\/geom.h\"\n#include \"glm\/gtx\/rotate_vector.hpp\"\n#include \"tangram.h\"\n\nnamespace Tangram {\n\nLabel::Label(Label::Transform _transform, glm::vec2 _size, Type _type, Options _options, LabelProperty::Anchor _anchor)\n : m_type(_type),\n m_transform(_transform),\n m_dim(_size),\n m_options(_options),\n m_anchorType(_anchor) {\n\n if (!m_options.collide || m_type == Type::debug){\n enterState(State::visible, 1.0);\n } else {\n m_state = State::wait_occ;\n m_transform.state.alpha = 0.0;\n }\n\n m_occludedLastFrame = false;\n m_occluded = false;\n m_parent = nullptr;\n}\n\nLabel::~Label() {}\n\nbool Label::updateScreenTransform(const glm::mat4& _mvp, const glm::vec2& _screenSize, bool _testVisibility) {\n\n glm::vec2 screenPosition;\n glm::vec2 rotation = {1, 0};\n bool clipped = false;\n\n switch (m_type) {\n case Type::debug:\n case Type::point:\n {\n glm::vec2 p0 = m_transform.modelPosition1;\n\n screenPosition = worldToScreenSpace(_mvp, glm::vec4(p0, 0.0, 1.0),\n _screenSize, clipped);\n\n if (_testVisibility && clipped) {\n return false;\n }\n\n screenPosition += m_anchor;\n\n break;\n }\n case Type::line:\n {\n \/\/ project label position from mercator world space to screen\n \/\/ coordinates\n glm::vec2 p0 = m_transform.modelPosition1;\n glm::vec2 p2 = m_transform.modelPosition2;\n\n glm::vec2 ap0 = worldToScreenSpace(_mvp, glm::vec4(p0, 0.0, 1.0),\n _screenSize, clipped);\n glm::vec2 ap2 = worldToScreenSpace(_mvp, glm::vec4(p2, 0.0, 1.0),\n _screenSize, clipped);\n\n \/\/ check whether the label is behind the camera using the\n \/\/ perspective division factor\n if (_testVisibility && clipped) {\n return false;\n }\n\n float length = glm::length(ap2 - ap0);\n\n \/\/ default heuristic : allow label to be 30% wider than segment\n float minLength = m_dim.x * 0.7;\n\n if (_testVisibility && length < minLength) {\n return false;\n }\n\n glm::vec2 p1 = glm::vec2(p2 + p0) * 0.5f;\n\n glm::vec2 ap1 = worldToScreenSpace(_mvp, glm::vec4(p1, 0.0, 1.0),\n _screenSize, clipped);\n\n \/\/ Keep screen position center at world center (less sliding in tilted view)\n screenPosition = ap1;\n\n rotation = (ap0.x <= ap2.x ? ap2 - ap0 : ap0 - ap2) \/ length;\n\n break;\n }\n }\n\n glm::vec2 offset = rotateBy(m_options.offset, rotation);\n\n m_transform.state.screenPos = screenPosition + offset;\n m_transform.state.rotation = rotation;\n\n return true;\n}\n\nvoid Label::setParent(const Label& _parent, bool _definePriority) {\n m_parent = &_parent;\n\n glm::vec2 anchorDir = LabelProperty::anchorDirection(_parent.anchorType());\n glm::vec2 anchorOrigin = anchorDir * _parent.dimension() * 0.5f;\n applyAnchor(m_dim + _parent.dimension(), anchorOrigin, m_anchorType);\n\n if (_definePriority) {\n m_options.priority = _parent.options().priority + 0.5f;\n }\n\n m_options.offset += _parent.options().offset;\n}\n\nbool Label::offViewport(const glm::vec2& _screenSize) {\n const auto& quad = m_obb.getQuad();\n\n for (int i = 0; i < 4; ++i) {\n const auto& p = quad[i];\n if (p.x < _screenSize.x && p.y < _screenSize.y && p.x > 0 && p.y > 0) {\n return false;\n }\n }\n\n return true;\n}\n\nbool Label::canOcclude() {\n if (!m_options.collide) {\n return false;\n }\n\n int occludeFlags = (State::visible |\n State::wait_occ |\n State::skip_transition |\n State::fading_in |\n State::sleep |\n State::out_of_screen |\n State::dead);\n\n return (occludeFlags & m_state) && !(m_type == Type::debug);\n}\n\nbool Label::visibleState() const {\n int visibleFlags = (State::visible |\n State::fading_in |\n State::fading_out |\n State::skip_transition);\n\n return (visibleFlags & m_state);\n}\n\nvoid Label::skipTransitions() {\n enterState(State::skip_transition, 0.0);\n}\n\nglm::vec2 Label::center() const {\n return m_obb.getCentroid();\n}\n\nvoid Label::enterState(const State& _state, float _alpha) {\n if (m_state == State::dead) { return; }\n\n m_state = _state;\n setAlpha(_alpha);\n}\n\nvoid Label::setAlpha(float _alpha) {\n m_transform.state.alpha = CLAMP(_alpha, 0.0, 1.0);\n}\n\nvoid Label::resetState() {\n if (m_state == State::dead) { return; }\n\n m_occludedLastFrame = false;\n m_occluded = false;\n enterState(State::wait_occ, 0.0);\n}\n\nbool Label::update(const glm::mat4& _mvp, const glm::vec2& _screenSize, float _zoomFract, bool _allLabels) {\n\n m_occludedLastFrame = m_occluded;\n m_occluded = false;\n\n if (m_state == State::dead) {\n if (!_allLabels) {\n return false;\n } else {\n m_occluded = true;\n }\n }\n\n bool ruleSatisfied = updateScreenTransform(_mvp, _screenSize, !_allLabels);\n\n \/\/ one of the label rules has not been satisfied\n if (!ruleSatisfied) {\n enterState(State::sleep, 0.0);\n return false;\n }\n\n \/\/ update the view-space bouding box\n updateBBoxes(_zoomFract);\n\n \/\/ checks whether the label is out of the viewport\n if (offViewport(_screenSize)) {\n enterState(State::out_of_screen, 0.0);\n if (m_occludedLastFrame) {\n m_occluded = true;\n return false;\n }\n } else if (m_state == State::out_of_screen) {\n if (m_occludedLastFrame) {\n enterState(State::sleep, 0.0);\n } else {\n enterState(State::visible, 1.0);\n }\n }\n\n return true;\n}\n\nbool Label::evalState(const glm::vec2& _screenSize, float _dt) {\n\n \/\/ if (Tangram::getDebugFlag(DebugFlags::all_labels)) {\n \/\/ enterState(State::visible, 1.0);\n \/\/ return false;\n \/\/ }\n\n bool animate = false;\n\n switch (m_state) {\n case State::visible:\n if (m_occluded) {\n m_fade = FadeEffect(false, m_options.hideTransition.ease,\n m_options.hideTransition.time);\n enterState(State::fading_out, 1.0);\n animate = true;\n }\n break;\n case State::fading_in:\n if (m_occluded) {\n enterState(State::sleep, 0.0);\n \/\/ enterState(State::fading_out, m_transform.state.alpha);\n \/\/ animate = true;\n break;\n }\n setAlpha(m_fade.update(_dt));\n animate = true;\n if (m_fade.isFinished()) {\n enterState(State::visible, 1.0);\n }\n break;\n case State::fading_out:\n if (!m_occluded) {\n enterState(State::fading_in, m_transform.state.alpha);\n animate = true;\n break;\n }\n setAlpha(m_fade.update(_dt));\n animate = true;\n if (m_fade.isFinished()) {\n enterState(State::sleep, 0.0);\n }\n break;\n case State::wait_occ:\n if (m_occluded) {\n enterState(State::sleep, 0.0);\n } else {\n m_fade = FadeEffect(true, m_options.showTransition.ease,\n m_options.showTransition.time);\n enterState(State::fading_in, 0.0);\n animate = true;\n }\n break;\n case State::skip_transition:\n if (m_occluded) {\n enterState(State::sleep, 0.0);\n } else {\n enterState(State::visible, 1.0);\n }\n break;\n case State::sleep:\n if (!m_occluded) {\n m_fade = FadeEffect(true, m_options.showTransition.ease,\n m_options.showTransition.time);\n enterState(State::fading_in, 0.0);\n animate = true;\n }\n break;\n case State::dead:\n case State::out_of_screen:\n break;\n }\n\n return animate;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file Cosa\/Power.cpp\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2013-2015, Mikael Patel\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 * This file is part of the Arduino Che Cosa project.\n *\/\n\n#include \"Cosa\/Power.hh\"\n\n\/\/ Software disable low voltage detect (23 uA at 5 V)\n#define COSA_BOD_DISABLE\n\nuint8_t Power::s_mode = SLEEP_MODE_IDLE;\n\nvoid\nPower::sleep(uint8_t mode)\n{\n if (mode == POWER_SLEEP_MODE) mode = s_mode;\n set_sleep_mode(mode);\n sleep_enable();\n#if defined(COSA_BOD_DISABLE) && defined(BODS)\n MCUCR = _BV(BODS) | _BV(BODSE);\n MCUCR = _BV(BODS);\n#endif\n sleep_cpu();\n sleep_disable();\n}\n\nvoid\nPower::clock_prescale(uint8_t factor)\n{\n if (factor > 8) factor = 8;\n\n \/\/ Fix: RTC and other timer scaling\n synchronized {\n CLKPR = _BV(CLKPCE);\n CLKPR = factor;\n }\n}\n<commit_msg>Correct BOD setting for ATtinyX5.<commit_after>\/**\n * @file Cosa\/Power.cpp\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2013-2015, Mikael Patel\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 * This file is part of the Arduino Che Cosa project.\n *\/\n\n#include \"Cosa\/Power.hh\"\n\n\/\/ Software disable low voltage detect (23 uA at 5 V)\n#define COSA_BOD_DISABLE\n\nuint8_t Power::s_mode = SLEEP_MODE_IDLE;\n\nvoid\nPower::sleep(uint8_t mode)\n{\n if (mode == POWER_SLEEP_MODE) mode = s_mode;\n set_sleep_mode(mode);\n sleep_enable();\n#if defined(COSA_BOD_DISABLE) && defined(BODS)\n MCUCR |= _BV(BODS) | _BV(BODSE);\n MCUCR |= _BV(BODS);\n#endif\n sleep_cpu();\n sleep_disable();\n}\n\nvoid\nPower::clock_prescale(uint8_t factor)\n{\n if (factor > 8) factor = 8;\n\n \/\/ Fix: RTC and other timer scaling\n synchronized {\n CLKPR = _BV(CLKPCE);\n CLKPR = factor;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * (C) Copyright 2014 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\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 *\/\n\n#include <gst\/gst.h>\n\n#include \"logging.hpp\"\n\n#include <boost\/format.hpp>\n#include <boost\/log\/sinks\/text_file_backend.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/log\/expressions.hpp>\n#include <boost\/log\/attributes.hpp>\n#include <boost\/log\/sinks.hpp>\n#include <boost\/log\/sources\/channel_feature.hpp>\n#include <boost\/log\/sources\/channel_logger.hpp>\n#include <boost\/log\/support\/date_time.hpp>\n#include <boost\/log\/utility\/manipulators\/add_value.hpp>\n\nnamespace logging = boost::log;\nnamespace attrs = boost::log::attributes;\nnamespace src = boost::log::sources;\nnamespace sinks = boost::log::sinks;\nnamespace expr = boost::log::expressions;\nnamespace keywords = boost::log::keywords;\n\ntypedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;\n\nnamespace kurento\n{\n\n\/* kurento logging sinks *\/\nboost::shared_ptr< sink_t > system_sink;\n\nstatic std::string\ndebug_object (GObject *object)\n{\n if (object == NULL) {\n return \"\";\n }\n\n if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s:%s> \");\n fmt % (GST_OBJECT_PARENT (object) != NULL ? GST_OBJECT_NAME (GST_OBJECT_PARENT (\n object) ) : \"''\") % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s> \");\n fmt % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (G_IS_OBJECT (object) ) {\n boost::format fmt (\"<%s@%p> \");\n fmt % G_OBJECT_TYPE_NAME (object) % object;\n return fmt.str();\n }\n\n boost::format fmt (\"<%p> \");\n fmt % object;\n return fmt.str();\n}\n\nstatic std::string\nexpand_string (std::string str, int len)\n{\n std::string ret = str;\n int sp = len - str.size ();\n\n for (int i = sp; i > 0; i--) {\n str.append (\" \");\n }\n\n return str;\n}\n\nstatic severity_level\ngst_debug_level_to_severity_level (GstDebugLevel level)\n{\n switch (level) {\n case GST_LEVEL_ERROR:\n return error;\n\n case GST_LEVEL_WARNING:\n return warning;\n\n case GST_LEVEL_FIXME:\n return fixme;\n\n case GST_LEVEL_INFO:\n return info;\n\n case GST_LEVEL_DEBUG:\n return debug;\n\n case GST_LEVEL_LOG:\n return log;\n\n case GST_LEVEL_TRACE:\n return trace;\n\n default:\n return undefined;\n }\n}\n\nstatic void\nkms_log_function (GstDebugCategory *category, GstDebugLevel level,\n const gchar *file,\n const gchar *function, gint line, GObject *object,\n GstDebugMessage *message, gpointer user_data)\n{\n if (level > gst_debug_category_get_threshold (category) ) {\n return;\n }\n\n severity_level severity = gst_debug_level_to_severity_level (level);\n\n if (severity == undefined) {\n return;\n }\n\n BOOST_LOG_SEV (system_logger::get(), severity) <<\n logging::add_value (\"Category\", expand_string (category->name, 25) ) <<\n logging::add_value (\"FileName\",\n boost::filesystem::path (file).filename().string() ) <<\n logging::add_value (\"Line\", line) <<\n logging::add_value (\"Function\", function) <<\n logging::add_value (\"GObject\", debug_object (object) ) <<\n gst_debug_message_get (message);\n}\n\nvoid init_file_collecting (boost::shared_ptr< sink_t > sink,\n const std::string &path)\n{\n sink->locked_backend()->set_file_collector (sinks::file::make_collector (\n keywords::target = path,\n keywords::max_size = 16 * 1024 * 1024,\n keywords::min_free_space = 100 * 1024 * 1024\n ) );\n}\n\n\/* The formatting logic for the severity level *\/\ntemplate< typename CharT, typename TraitsT >\ninline std::basic_ostream< CharT, TraitsT > &operator<< (\n std::basic_ostream< CharT, TraitsT > &strm, severity_level lvl)\n{\n static const char *const str[] = {\n \"error\",\n \"warning\",\n \"fixme\",\n \"info\",\n \"debug\",\n \"log\",\n \"trace\",\n \"unknown\"\n };\n\n if (static_cast< std::size_t > (lvl) < (sizeof (str) \/ sizeof (*str) ) ) {\n strm << str[lvl];\n } else {\n strm << static_cast< int > (lvl);\n }\n\n return strm;\n}\n\nstatic void\nsystem_formatter (logging::record_view const &rec,\n logging::formatting_ostream &strm)\n{\n auto date_time_formatter = expr::stream\n << expr::format_date_time< boost::posix_time::ptime > (\"TimeStamp\",\n \"%Y-%m-%d %H:%M:%S,%f\");\n date_time_formatter (rec, strm) << \" \";\n strm << logging::extract< attrs::current_process_id::value_type > (\"ProcessID\",\n rec) << \" \";\n strm << \"[\" <<\n logging::extract< attrs::current_thread_id::value_type > (\"ThreadID\",\n rec) << \"] \";\n strm << logging::extract< severity_level > (\"Severity\", rec) << \" \";\n strm << logging::extract< std::string > (\"Category\", rec) << \" \";\n strm << logging::extract< std::string > (\"FileName\", rec) << \":\";\n strm << logging::extract< int > (\"Line\", rec) << \" \";\n strm << logging::extract< std::string > (\"Function\", rec) << \"() \";\n strm << logging::extract< std::string > (\"GObject\", rec) << \" \";\n strm << rec[expr::smessage];\n}\n\nbool\nkms_init_logging (const std::string &path)\n{\n gst_debug_remove_log_function_by_data (NULL);\n gst_debug_add_log_function (kms_log_function, NULL, NULL);\n\n boost::shared_ptr< logging::core > core = logging::core::get();\n\n boost::shared_ptr< sinks::text_file_backend > backend =\n boost::make_shared< sinks::text_file_backend > (\n keywords::file_name = path + \"\/\" + \"%Y%m%d_%H%M%S_%5N.log\",\n keywords::rotation_size = 5 * 1024 * 1024,\n keywords::time_based_rotation = sinks::file::rotation_at_time_point (12, 0, 0)\n );\n\n \/* Enable auto-flushing after each log record written *\/\n backend->auto_flush (true);\n\n \/* Wrap it into the frontend and register in the core. *\/\n \/* The backend requires synchronization in the frontend. *\/\n system_sink = boost::shared_ptr< sink_t > (new sink_t (backend) );\n\n \/*Set up filter to pass only records that have the necessary attributes *\/\n system_sink->set_filter (\n expr::has_attr< std::string > (\"Channel\") &&\n expr::attr< std::string > (\"Channel\") == \"system\"\n );\n\n \/* Set up where the rotated files will be stored *\/\n init_file_collecting (system_sink, path + \"\/logs\");\n\n \/* Upon restart, scan the directory for files matching the file_name pattern *\/\n system_sink->locked_backend()->scan_for_files();\n\n core->add_sink (system_sink);\n\n system_sink->set_formatter (&system_formatter);\n\n return true;\n}\n\n} \/* kurento *\/\n<commit_msg>logging.cpp: Fix severity indentation<commit_after>\/*\n * (C) Copyright 2014 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\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 *\/\n\n#include <gst\/gst.h>\n\n#include \"logging.hpp\"\n\n#include <boost\/format.hpp>\n#include <boost\/log\/sinks\/text_file_backend.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/log\/expressions.hpp>\n#include <boost\/log\/attributes.hpp>\n#include <boost\/log\/sinks.hpp>\n#include <boost\/log\/sources\/channel_feature.hpp>\n#include <boost\/log\/sources\/channel_logger.hpp>\n#include <boost\/log\/support\/date_time.hpp>\n#include <boost\/log\/utility\/manipulators\/add_value.hpp>\n\nnamespace logging = boost::log;\nnamespace attrs = boost::log::attributes;\nnamespace src = boost::log::sources;\nnamespace sinks = boost::log::sinks;\nnamespace expr = boost::log::expressions;\nnamespace keywords = boost::log::keywords;\n\ntypedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;\n\nnamespace kurento\n{\n\n\/* kurento logging sinks *\/\nboost::shared_ptr< sink_t > system_sink;\n\nstatic std::string\ndebug_object (GObject *object)\n{\n if (object == NULL) {\n return \"\";\n }\n\n if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s:%s> \");\n fmt % (GST_OBJECT_PARENT (object) != NULL ? GST_OBJECT_NAME (GST_OBJECT_PARENT (\n object) ) : \"''\") % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s> \");\n fmt % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (G_IS_OBJECT (object) ) {\n boost::format fmt (\"<%s@%p> \");\n fmt % G_OBJECT_TYPE_NAME (object) % object;\n return fmt.str();\n }\n\n boost::format fmt (\"<%p> \");\n fmt % object;\n return fmt.str();\n}\n\nstatic std::string\nexpand_string (std::string str, int len)\n{\n std::string ret = str;\n int sp = len - str.size ();\n\n for (int i = sp; i > 0; i--) {\n str.append (\" \");\n }\n\n return str;\n}\n\nstatic severity_level\ngst_debug_level_to_severity_level (GstDebugLevel level)\n{\n switch (level) {\n case GST_LEVEL_ERROR:\n return error;\n\n case GST_LEVEL_WARNING:\n return warning;\n\n case GST_LEVEL_FIXME:\n return fixme;\n\n case GST_LEVEL_INFO:\n return info;\n\n case GST_LEVEL_DEBUG:\n return debug;\n\n case GST_LEVEL_LOG:\n return log;\n\n case GST_LEVEL_TRACE:\n return trace;\n\n default:\n return undefined;\n }\n}\n\nstatic void\nkms_log_function (GstDebugCategory *category, GstDebugLevel level,\n const gchar *file,\n const gchar *function, gint line, GObject *object,\n GstDebugMessage *message, gpointer user_data)\n{\n if (level > gst_debug_category_get_threshold (category) ) {\n return;\n }\n\n severity_level severity = gst_debug_level_to_severity_level (level);\n\n if (severity == undefined) {\n return;\n }\n\n BOOST_LOG_SEV (system_logger::get(), severity) <<\n logging::add_value (\"Category\", expand_string (category->name, 25) ) <<\n logging::add_value (\"FileName\",\n boost::filesystem::path (file).filename().string() ) <<\n logging::add_value (\"Line\", line) <<\n logging::add_value (\"Function\", function) <<\n logging::add_value (\"GObject\", debug_object (object) ) <<\n gst_debug_message_get (message);\n}\n\nvoid init_file_collecting (boost::shared_ptr< sink_t > sink,\n const std::string &path)\n{\n sink->locked_backend()->set_file_collector (sinks::file::make_collector (\n keywords::target = path,\n keywords::max_size = 16 * 1024 * 1024,\n keywords::min_free_space = 100 * 1024 * 1024\n ) );\n}\n\n\/* The formatting logic for the severity level *\/\ntemplate< typename CharT, typename TraitsT >\ninline std::basic_ostream< CharT, TraitsT > &operator<< (\n std::basic_ostream< CharT, TraitsT > &strm, severity_level lvl)\n{\n static const char *const str[] = {\n \" error\",\n \"warning\",\n \" fixme\",\n \" info\",\n \" debug\",\n \" log\",\n \" trace\",\n \"unknown\"\n };\n\n if (static_cast< std::size_t > (lvl) < (sizeof (str) \/ sizeof (*str) ) ) {\n strm << str[lvl];\n } else {\n strm << static_cast< int > (lvl);\n }\n\n return strm;\n}\n\nstatic void\nsystem_formatter (logging::record_view const &rec,\n logging::formatting_ostream &strm)\n{\n auto date_time_formatter = expr::stream\n << expr::format_date_time< boost::posix_time::ptime > (\"TimeStamp\",\n \"%Y-%m-%d %H:%M:%S,%f\");\n date_time_formatter (rec, strm) << \" \";\n strm << logging::extract< attrs::current_process_id::value_type > (\"ProcessID\",\n rec) << \" \";\n strm << \"[\" <<\n logging::extract< attrs::current_thread_id::value_type > (\"ThreadID\",\n rec) << \"] \";\n strm << logging::extract< severity_level > (\"Severity\", rec) << \" \";\n strm << logging::extract< std::string > (\"Category\", rec) << \" \";\n strm << logging::extract< std::string > (\"FileName\", rec) << \":\";\n strm << logging::extract< int > (\"Line\", rec) << \" \";\n strm << logging::extract< std::string > (\"Function\", rec) << \"() \";\n strm << logging::extract< std::string > (\"GObject\", rec) << \" \";\n strm << rec[expr::smessage];\n}\n\nbool\nkms_init_logging (const std::string &path)\n{\n gst_debug_remove_log_function_by_data (NULL);\n gst_debug_add_log_function (kms_log_function, NULL, NULL);\n\n boost::shared_ptr< logging::core > core = logging::core::get();\n\n boost::shared_ptr< sinks::text_file_backend > backend =\n boost::make_shared< sinks::text_file_backend > (\n keywords::file_name = path + \"\/\" + \"%Y%m%d_%H%M%S_%5N.log\",\n keywords::rotation_size = 5 * 1024 * 1024,\n keywords::time_based_rotation = sinks::file::rotation_at_time_point (12, 0, 0)\n );\n\n \/* Enable auto-flushing after each log record written *\/\n backend->auto_flush (true);\n\n \/* Wrap it into the frontend and register in the core. *\/\n \/* The backend requires synchronization in the frontend. *\/\n system_sink = boost::shared_ptr< sink_t > (new sink_t (backend) );\n\n \/*Set up filter to pass only records that have the necessary attributes *\/\n system_sink->set_filter (\n expr::has_attr< std::string > (\"Channel\") &&\n expr::attr< std::string > (\"Channel\") == \"system\"\n );\n\n \/* Set up where the rotated files will be stored *\/\n init_file_collecting (system_sink, path + \"\/logs\");\n\n \/* Upon restart, scan the directory for files matching the file_name pattern *\/\n system_sink->locked_backend()->scan_for_files();\n\n core->add_sink (system_sink);\n\n system_sink->set_formatter (&system_formatter);\n\n return true;\n}\n\n} \/* kurento *\/\n<|endoftext|>"} {"text":"<commit_before>\n\n#include <iostream>\n\n#include \"storage\/Devices\/PartitionImpl.h\"\n#include \"storage\/Devices\/DiskImpl.h\"\n#include \"storage\/Devicegraph.h\"\n#include \"storage\/SystemInfo\/SystemInfo.h\"\n#include \"storage\/Utils\/SystemCmd.h\"\n#include \"storage\/Utils\/StorageDefines.h\"\n#include \"storage\/Utils\/StorageTmpl.h\"\n\n\nnamespace storage\n{\n\n using namespace std;\n\n\n const char* DeviceTraits<Partition>::classname = \"Partition\";\n\n\n Partition::Impl::Impl(const string& name, const Region& region, PartitionType type)\n\t: BlkDevice::Impl(name, region.to_kb(region.get_length())), region(region), type(type),\n\t id(ID_LINUX), boot(false)\n {\n }\n\n\n Partition::Impl::Impl(const xmlNode* node)\n\t: BlkDevice::Impl(node), region(), type(PRIMARY), id(ID_LINUX), boot(false)\n {\n\tstring tmp;\n\n\tgetChildValue(node, \"region\", region);\n\tif (getChildValue(node, \"type\", tmp))\n\t type = toValueWithFallback(tmp, PRIMARY);\n\tgetChildValue(node, \"id\", id);\n\tgetChildValue(node, \"boot\", boot);\n }\n\n\n void\n Partition::Impl::probe(SystemInfo& systeminfo)\n {\n\tBlkDevice::Impl::probe(systeminfo);\n\n\tconst Devicegraph* g = get_devicegraph();\n\n\tDevicegraph::Impl::vertex_descriptor v1 = g->get_impl().parent(get_vertex());\n\tDevicegraph::Impl::vertex_descriptor v2 = g->get_impl().parent(v1);\n\n\tstring pp_name = dynamic_cast<const BlkDevice*>(g->get_impl()[v2])->get_name();\n\n\tconst Parted& parted = systeminfo.getParted(pp_name);\n\tParted::Entry entry;\n\tif (!parted.getEntry(get_number(), entry))\n\t throw;\n\n\tid = entry.id;\n\tboot = entry.boot;\n }\n\n\n void\n Partition::Impl::save(xmlNode* node) const\n {\n\tBlkDevice::Impl::save(node);\n\n\tsetChildValue(node, \"region\", region);\n\tsetChildValue(node, \"type\", toString(type));\n\tsetChildValueIf(node, \"id\", id, id != 0);\n\tsetChildValueIf(node, \"boot\", boot, boot);\n }\n\n\n unsigned int\n Partition::Impl::get_number() const\n {\n\tstring::size_type pos = get_name().find_last_not_of(\"0123456789\");\n\treturn atoi(get_name().substr(pos + 1).c_str());\n }\n\n\n void\n Partition::Impl::set_size_k(unsigned long long size_k)\n {\n\tBlkDevice::Impl::set_size_k(size_k);\n\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tregion.set_length(get_size_k() * 1024 \/ disk->get_impl().get_geometry().cylinderSize());\n }\n\n\n void\n Partition::Impl::set_region(const Region& region)\n {\n\tImpl::region = region;\n\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tconst Geometry& geometry = disk->get_impl().get_geometry();\n\tif (region.get_block_size() != geometry.cylinderSize())\n\t ST_THROW(DifferentBlockSizes(region.get_block_size(), geometry.cylinderSize()));\n\n\tset_size_k(region.get_length() * disk->get_impl().get_geometry().cylinderSize() \/ 1024);\n }\n\n\n const PartitionTable*\n Partition::Impl::get_partition_table() const\n {\n\tDevicegraph::Impl::vertex_descriptor v = get_devicegraph()->get_impl().parent(get_vertex());\n\n\treturn to_partition_table(get_devicegraph()->get_impl()[v]);\n }\n\n\n void\n Partition::Impl::add_create_actions(Actiongraph::Impl& actiongraph) const\n {\n\tvector<Action::Base*> actions;\n\n\tactions.push_back(new Action::Create(get_sid()));\n\tactions.push_back(new Action::SetPartitionId(get_sid()));\n\n\tactiongraph.add_chain(actions);\n }\n\n\n void\n Partition::Impl::add_modify_actions(Actiongraph::Impl& actiongraph, const Device* lhs_base) const\n {\n\tconst Impl& lhs = dynamic_cast<const Impl&>(lhs_base->get_impl());\n\n\tif (get_type() != lhs.get_type())\n\t{\n\t throw runtime_error(\"cannot change partition type\");\n\t}\n\n\tif (get_region().get_start() != lhs.get_region().get_start())\n\t{\n\t throw runtime_error(\"cannot move partition\");\n\t}\n\n\tif (get_id() != lhs.get_id())\n\t{\n\t Action::Base* action = new Action::SetPartitionId(get_sid());\n\t actiongraph.add_vertex(action);\n\t}\n }\n\n\n void\n Partition::Impl::add_delete_actions(Actiongraph::Impl& actiongraph) const\n {\n\tvector<Action::Base*> actions;\n\n\tactions.push_back(new Action::Delete(get_sid()));\n\n\tactiongraph.add_chain(actions);\n }\n\n\n bool\n Partition::Impl::equal(const Device::Impl& rhs_base) const\n {\n\tconst Impl& rhs = dynamic_cast<const Impl&>(rhs_base);\n\n\tif (!BlkDevice::Impl::equal(rhs))\n\t return false;\n\n\treturn region == rhs.region && type == rhs.type && id == rhs.id && boot == rhs.boot;\n }\n\n\n void\n Partition::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const\n {\n\tconst Impl& rhs = dynamic_cast<const Impl&>(rhs_base);\n\n\tBlkDevice::Impl::log_diff(log, rhs);\n\n\tstorage::log_diff(log, \"region\", region, rhs.region);\n\tstorage::log_diff_enum(log, \"type\", type, rhs.type);\n\tstorage::log_diff_hex(log, \"id\", id, rhs.id);\n\tstorage::log_diff(log, \"boot\", boot, rhs.boot);\n }\n\n\n void\n Partition::Impl::print(std::ostream& out) const\n {\n\tBlkDevice::Impl::print(out);\n\n\tout << \" region:\" << get_region();\n }\n\n\n void\n Partition::Impl::process_udev_ids(vector<string>& udev_ids) const\n {\n\tconst Devicegraph* g = get_devicegraph();\n\n\tDevicegraph::Impl::vertex_descriptor v1 = g->get_impl().parent(get_vertex());\n\tDevicegraph::Impl::vertex_descriptor v2 = g->get_impl().parent(v1);\n\n\tconst Disk* disk = dynamic_cast<const Disk*>(g->get_impl()[v2]);\n\n\tdisk->get_impl().process_udev_ids(udev_ids);\n }\n\n\n bool\n Partition::Impl::cmp_lt_number(const Partition* lhs, const Partition* rhs)\n {\n\treturn lhs->get_number() < rhs->get_number();\n }\n\n\n Text\n Partition::Impl::do_create_text(bool doing) const\n {\n\treturn sformat(_(\"Create partition %1$s (%2$s)\"), get_name().c_str(), get_size_string().c_str());\n }\n\n\n void\n Partition::Impl::do_create() const\n {\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tstring cmd_line = PARTEDBIN \" -s \" + quote(disk->get_name()) + \" unit cyl mkpart \" +\n\t toString(get_type()) + \" \";\n\n\tif (get_type() != EXTENDED)\n\t{\n\t \/\/ TODO look at id\n\t cmd_line += \"ext2 \";\n\t}\n\n\tcmd_line += to_string(get_region().get_start()) + \" \" + to_string(get_region().get_end());\n\n\tcout << cmd_line << endl;\n\n\tSystemCmd cmd(cmd_line);\n\tif (cmd.retcode() != 0)\n\t throw runtime_error(\"create partition failed\");\n }\n\n\n Text\n Partition::Impl::do_set_id_text(bool doing) const\n {\n\tstring tmp = id_to_string(get_id());\n\n\tif (tmp.empty())\n\t return sformat(_(\"Set id of partition %1$s to 0x%2$02X\"), get_name().c_str(), get_id());\n\telse\n\t return sformat(_(\"Set id of partition %1$s to %2$s (0x%3$02X)\"), get_name().c_str(),\n\t\t\t tmp.c_str(), get_id());\n }\n\n\n void\n Partition::Impl::do_set_id() const\n {\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tstring cmd_line = PARTEDBIN \" -s \" + quote(disk->get_name()) + \" set \" +\n\t to_string(get_number()) + \" type \" + to_string(get_id());\n\tcout << cmd_line << endl;\n\n\tSystemCmd cmd(cmd_line);\n\tif (cmd.retcode() != 0)\n\t throw runtime_error(\"set partition id failed\");\n }\n\n\n Text\n Partition::Impl::do_delete_text(bool doing) const\n {\n\treturn sformat(_(\"Delete partition %1$s (%2$s)\"), get_name().c_str(),\n\t\t get_size_string().c_str());\n }\n\n\n void\n Partition::Impl::do_delete() const\n {\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tstring cmd_line = PARTEDBIN \" -s \" + disk->get_name() + \" rm \" + to_string(get_number());\n\tcout << cmd_line << endl;\n\n\tSystemCmd cmd(cmd_line);\n\tif (cmd.retcode() != 0)\n\t throw runtime_error(\"delete partition failed\");\n }\n\n\n namespace Action\n {\n\n\tText\n\tSetPartitionId::text(const Actiongraph::Impl& actiongraph, bool doing) const\n\t{\n\t const Partition* partition = to_partition(device_rhs(actiongraph));\n\t return partition->get_impl().do_set_id_text(doing);\n\t}\n\n\n\tvoid\n\tSetPartitionId::commit(const Actiongraph::Impl& actiongraph) const\n\t{\n\t const Partition* partition = to_partition(device_rhs(actiongraph));\n\t partition->get_impl().do_set_id();\n\t}\n\n }\n\n string\n id_to_string(unsigned int id)\n {\n\tswitch (id)\n\t{\n\t case ID_SWAP: return \"Linux Swap\";\n\t case ID_LINUX: return \"Linux\";\n\t case ID_LVM: return \"Linux LVM\";\n\t case ID_RAID: return \"Linux RAID\";\n\t}\n\n\treturn \"\";\n }\n\n}\n<commit_msg>- use new ST_THROW macro<commit_after>\n\n#include <iostream>\n\n#include \"storage\/Devices\/PartitionImpl.h\"\n#include \"storage\/Devices\/DiskImpl.h\"\n#include \"storage\/Devicegraph.h\"\n#include \"storage\/SystemInfo\/SystemInfo.h\"\n#include \"storage\/Utils\/SystemCmd.h\"\n#include \"storage\/Utils\/StorageDefines.h\"\n#include \"storage\/Utils\/StorageTmpl.h\"\n\n\nnamespace storage\n{\n\n using namespace std;\n\n\n const char* DeviceTraits<Partition>::classname = \"Partition\";\n\n\n Partition::Impl::Impl(const string& name, const Region& region, PartitionType type)\n\t: BlkDevice::Impl(name, region.to_kb(region.get_length())), region(region), type(type),\n\t id(ID_LINUX), boot(false)\n {\n }\n\n\n Partition::Impl::Impl(const xmlNode* node)\n\t: BlkDevice::Impl(node), region(), type(PRIMARY), id(ID_LINUX), boot(false)\n {\n\tstring tmp;\n\n\tgetChildValue(node, \"region\", region);\n\tif (getChildValue(node, \"type\", tmp))\n\t type = toValueWithFallback(tmp, PRIMARY);\n\tgetChildValue(node, \"id\", id);\n\tgetChildValue(node, \"boot\", boot);\n }\n\n\n void\n Partition::Impl::probe(SystemInfo& systeminfo)\n {\n\tBlkDevice::Impl::probe(systeminfo);\n\n\tconst Devicegraph* g = get_devicegraph();\n\n\tDevicegraph::Impl::vertex_descriptor v1 = g->get_impl().parent(get_vertex());\n\tDevicegraph::Impl::vertex_descriptor v2 = g->get_impl().parent(v1);\n\n\tstring pp_name = dynamic_cast<const BlkDevice*>(g->get_impl()[v2])->get_name();\n\n\tconst Parted& parted = systeminfo.getParted(pp_name);\n\tParted::Entry entry;\n\tif (!parted.getEntry(get_number(), entry))\n\t throw;\n\n\tid = entry.id;\n\tboot = entry.boot;\n }\n\n\n void\n Partition::Impl::save(xmlNode* node) const\n {\n\tBlkDevice::Impl::save(node);\n\n\tsetChildValue(node, \"region\", region);\n\tsetChildValue(node, \"type\", toString(type));\n\tsetChildValueIf(node, \"id\", id, id != 0);\n\tsetChildValueIf(node, \"boot\", boot, boot);\n }\n\n\n unsigned int\n Partition::Impl::get_number() const\n {\n\tstring::size_type pos = get_name().find_last_not_of(\"0123456789\");\n\treturn atoi(get_name().substr(pos + 1).c_str());\n }\n\n\n void\n Partition::Impl::set_size_k(unsigned long long size_k)\n {\n\tBlkDevice::Impl::set_size_k(size_k);\n\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tregion.set_length(get_size_k() * 1024 \/ disk->get_impl().get_geometry().cylinderSize());\n }\n\n\n void\n Partition::Impl::set_region(const Region& region)\n {\n\tImpl::region = region;\n\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tconst Geometry& geometry = disk->get_impl().get_geometry();\n\tif (region.get_block_size() != geometry.cylinderSize())\n\t ST_THROW(DifferentBlockSizes(region.get_block_size(), geometry.cylinderSize()));\n\n\tset_size_k(region.get_length() * disk->get_impl().get_geometry().cylinderSize() \/ 1024);\n }\n\n\n const PartitionTable*\n Partition::Impl::get_partition_table() const\n {\n\tDevicegraph::Impl::vertex_descriptor v = get_devicegraph()->get_impl().parent(get_vertex());\n\n\treturn to_partition_table(get_devicegraph()->get_impl()[v]);\n }\n\n\n void\n Partition::Impl::add_create_actions(Actiongraph::Impl& actiongraph) const\n {\n\tvector<Action::Base*> actions;\n\n\tactions.push_back(new Action::Create(get_sid()));\n\tactions.push_back(new Action::SetPartitionId(get_sid()));\n\n\tactiongraph.add_chain(actions);\n }\n\n\n void\n Partition::Impl::add_modify_actions(Actiongraph::Impl& actiongraph, const Device* lhs_base) const\n {\n\tconst Impl& lhs = dynamic_cast<const Impl&>(lhs_base->get_impl());\n\n\tif (get_type() != lhs.get_type())\n\t{\n\t throw runtime_error(\"cannot change partition type\");\n\t}\n\n\tif (get_region().get_start() != lhs.get_region().get_start())\n\t{\n\t throw runtime_error(\"cannot move partition\");\n\t}\n\n\tif (get_id() != lhs.get_id())\n\t{\n\t Action::Base* action = new Action::SetPartitionId(get_sid());\n\t actiongraph.add_vertex(action);\n\t}\n }\n\n\n void\n Partition::Impl::add_delete_actions(Actiongraph::Impl& actiongraph) const\n {\n\tvector<Action::Base*> actions;\n\n\tactions.push_back(new Action::Delete(get_sid()));\n\n\tactiongraph.add_chain(actions);\n }\n\n\n bool\n Partition::Impl::equal(const Device::Impl& rhs_base) const\n {\n\tconst Impl& rhs = dynamic_cast<const Impl&>(rhs_base);\n\n\tif (!BlkDevice::Impl::equal(rhs))\n\t return false;\n\n\treturn region == rhs.region && type == rhs.type && id == rhs.id && boot == rhs.boot;\n }\n\n\n void\n Partition::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const\n {\n\tconst Impl& rhs = dynamic_cast<const Impl&>(rhs_base);\n\n\tBlkDevice::Impl::log_diff(log, rhs);\n\n\tstorage::log_diff(log, \"region\", region, rhs.region);\n\tstorage::log_diff_enum(log, \"type\", type, rhs.type);\n\tstorage::log_diff_hex(log, \"id\", id, rhs.id);\n\tstorage::log_diff(log, \"boot\", boot, rhs.boot);\n }\n\n\n void\n Partition::Impl::print(std::ostream& out) const\n {\n\tBlkDevice::Impl::print(out);\n\n\tout << \" region:\" << get_region();\n }\n\n\n void\n Partition::Impl::process_udev_ids(vector<string>& udev_ids) const\n {\n\tconst Devicegraph* g = get_devicegraph();\n\n\tDevicegraph::Impl::vertex_descriptor v1 = g->get_impl().parent(get_vertex());\n\tDevicegraph::Impl::vertex_descriptor v2 = g->get_impl().parent(v1);\n\n\tconst Disk* disk = dynamic_cast<const Disk*>(g->get_impl()[v2]);\n\n\tdisk->get_impl().process_udev_ids(udev_ids);\n }\n\n\n bool\n Partition::Impl::cmp_lt_number(const Partition* lhs, const Partition* rhs)\n {\n\treturn lhs->get_number() < rhs->get_number();\n }\n\n\n Text\n Partition::Impl::do_create_text(bool doing) const\n {\n\treturn sformat(_(\"Create partition %1$s (%2$s)\"), get_name().c_str(), get_size_string().c_str());\n }\n\n\n void\n Partition::Impl::do_create() const\n {\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tstring cmd_line = PARTEDBIN \" -s \" + quote(disk->get_name()) + \" unit cyl mkpart \" +\n\t toString(get_type()) + \" \";\n\n\tif (get_type() != EXTENDED)\n\t{\n\t \/\/ TODO look at id\n\t cmd_line += \"ext2 \";\n\t}\n\n\tcmd_line += to_string(get_region().get_start()) + \" \" + to_string(get_region().get_end());\n\n\tcout << cmd_line << endl;\n\n\tSystemCmd cmd(cmd_line);\n\tif (cmd.retcode() != 0)\n\t ST_THROW(Exception(\"create partition failed\"));\n }\n\n\n Text\n Partition::Impl::do_set_id_text(bool doing) const\n {\n\tstring tmp = id_to_string(get_id());\n\n\tif (tmp.empty())\n\t return sformat(_(\"Set id of partition %1$s to 0x%2$02X\"), get_name().c_str(), get_id());\n\telse\n\t return sformat(_(\"Set id of partition %1$s to %2$s (0x%3$02X)\"), get_name().c_str(),\n\t\t\t tmp.c_str(), get_id());\n }\n\n\n void\n Partition::Impl::do_set_id() const\n {\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tstring cmd_line = PARTEDBIN \" -s \" + quote(disk->get_name()) + \" set \" +\n\t to_string(get_number()) + \" type \" + to_string(get_id());\n\tcout << cmd_line << endl;\n\n\tSystemCmd cmd(cmd_line);\n\tif (cmd.retcode() != 0)\n\t ST_THROW(Exception(\"set partition id failed\"));\n }\n\n\n Text\n Partition::Impl::do_delete_text(bool doing) const\n {\n\treturn sformat(_(\"Delete partition %1$s (%2$s)\"), get_name().c_str(),\n\t\t get_size_string().c_str());\n }\n\n\n void\n Partition::Impl::do_delete() const\n {\n\tconst PartitionTable* partitiontable = get_partition_table();\n\n\tconst Disk* disk = partitiontable->get_disk();\n\n\tstring cmd_line = PARTEDBIN \" -s \" + disk->get_name() + \" rm \" + to_string(get_number());\n\tcout << cmd_line << endl;\n\n\tSystemCmd cmd(cmd_line);\n\tif (cmd.retcode() != 0)\n\t ST_THROW(Exception(\"delete partition failed\"));\n }\n\n\n namespace Action\n {\n\n\tText\n\tSetPartitionId::text(const Actiongraph::Impl& actiongraph, bool doing) const\n\t{\n\t const Partition* partition = to_partition(device_rhs(actiongraph));\n\t return partition->get_impl().do_set_id_text(doing);\n\t}\n\n\n\tvoid\n\tSetPartitionId::commit(const Actiongraph::Impl& actiongraph) const\n\t{\n\t const Partition* partition = to_partition(device_rhs(actiongraph));\n\t partition->get_impl().do_set_id();\n\t}\n\n }\n\n string\n id_to_string(unsigned int id)\n {\n\tswitch (id)\n\t{\n\t case ID_SWAP: return \"Linux Swap\";\n\t case ID_LINUX: return \"Linux\";\n\t case ID_LVM: return \"Linux LVM\";\n\t case ID_RAID: return \"Linux RAID\";\n\t}\n\n\treturn \"\";\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <pddlparse\/detail\/normalization\/Reduction.h>\n\n#include <pddlparse\/AST.h>\n#include <pddlparse\/Exception.h>\n#include <pddlparse\/NormalizedAST.h>\n#include <pddlparse\/detail\/normalization\/AtomicFormula.h>\n#include <pddlparse\/detail\/normalization\/CollectFreeVariables.h>\n\nnamespace pddl\n{\nnamespace detail\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Reduction\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Forward declarations\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid eliminateImply(ast::Precondition &precondition);\nvoid negationNormalize(ast::Precondition &precondition);\nvoid eliminateForAll(ast::Precondition &precondition);\nvoid eliminateDoubleNegations(ast::Precondition &precondition);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid eliminateImply(ast::Precondition &precondition)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\teliminateImply(argument);\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\teliminateImply(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\teliminateImply(forAll->argument);\n\t\t};\n\n\tconst auto handleImply =\n\t\t[&](ast::ImplyPointer<ast::Precondition> &imply)\n\t\t{\n\t\t\teliminateImply(imply->argumentLeft);\n\t\t\teliminateImply(imply->argumentRight);\n\n\t\t\tast::Or<ast::Precondition>::Arguments arguments;\n\t\t\targuments.reserve(2);\n\t\t\targuments.emplace_back(std::make_unique<ast::Not<ast::Precondition>>(std::move(imply->argumentLeft)));\n\t\t\targuments.emplace_back(std::move(imply->argumentRight));\n\n\t\t\tprecondition = std::make_unique<ast::Or<ast::Precondition>>(std::move(arguments));\n\t\t};\n\n\tconst auto handleNot =\n\t\t[](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\teliminateImply(not_->argument);\n\t\t};\n\n\tconst auto handleOr =\n\t\t[](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\teliminateImply(argument);\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Negation-normalize an expression whose parent is a “not” expression\nvoid negationNormalizeNegated(ast::Precondition &precondition, ast::Precondition &parent)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[&](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tast::Or<ast::Precondition>::Arguments arguments;\n\t\t\targuments.reserve(and_->arguments.size());\n\n\t\t\t\/\/ Apply De Morgan\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\targuments.emplace_back(std::make_unique<ast::Not<ast::Precondition>>(std::move(argument)));\n\n\t\t\t\/\/ Finally, negation-normalize each argument\n\t\t\tfor (auto &argument : arguments)\n\t\t\t\tnegationNormalize(argument);\n\n\t\t\t\/\/ Replace the parent “not” containing this “and” with an “or” over the negated arguments\n\t\t\tparent = std::make_unique<ast::Or<ast::Precondition>>(std::move(arguments));\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\tnegationNormalize(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\tnegationNormalize(forAll->argument);\n\t\t};\n\n\tconst auto handleImply =\n\t\t[](ast::ImplyPointer<ast::Precondition> &)\n\t\t{\n\t\t\tthrow std::logic_error(\"precondition not ready for negation normalization (imply), please report to the bug tracker\");\n\t\t};\n\n\tconst auto handleNot =\n\t\t[&](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\tnegationNormalize(not_->argument);\n\n\t\t\t\/\/ As the parent contains the argument, the argument needs to be saved before overwriting the parent\n\t\t\t\/\/ TODO: check whether this workaround can be avoided\n\t\t\tauto argument = std::move(not_->argument);\n\t\t\tparent = std::move(argument);\n\t\t};\n\n\tconst auto handleOr =\n\t\t[&](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tast::And<ast::Precondition>::Arguments arguments;\n\t\t\targuments.reserve(or_->arguments.size());\n\n\t\t\t\/\/ Apply De Morgan\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\targuments.emplace_back(std::make_unique<ast::Not<ast::Precondition>>(std::move(argument)));\n\n\t\t\t\/\/ Finally, negation-normalize each argument\n\t\t\tfor (auto &argument : arguments)\n\t\t\t\tnegationNormalize(argument);\n\n\t\t\t\/\/ Replace the parent “not” containing this “or” with an “and” over the negated arguments\n\t\t\tparent = std::make_unique<ast::And<ast::Precondition>>(std::move(arguments));\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid negationNormalize(ast::Precondition &precondition)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\tnegationNormalize(argument);\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\tnegationNormalize(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\tnegationNormalize(forAll->argument);\n\t\t};\n\n\tconst auto handleImply =\n\t\t[](ast::ImplyPointer<ast::Precondition> &)\n\t\t{\n\t\t\tthrow std::logic_error(\"precondition not ready for negation normalization (imply), please report to the bug tracker\");\n\t\t};\n\n\tconst auto handleNot =\n\t\t[&](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\tnegationNormalizeNegated(not_->argument, precondition);\n\t\t};\n\n\tconst auto handleOr =\n\t\t[](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\tnegationNormalize(argument);\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid eliminateForAll(ast::Precondition &precondition)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\teliminateForAll(argument);\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\teliminateForAll(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[&](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\tauto negatedArgument = std::make_unique<ast::Not<ast::Precondition>>(std::move(forAll->argument));\n\t\t\tauto exists = std::make_unique<ast::Exists<ast::Precondition>>(std::move(forAll->parameters), std::move(negatedArgument));\n\n\t\t\tprecondition = std::make_unique<ast::Not<ast::Precondition>>(std::move(exists));\n\t\t};\n\n\tconst auto handleImply =\n\t\t[&](ast::ImplyPointer<ast::Precondition> &imply)\n\t\t{\n\t\t\teliminateForAll(imply->argumentLeft);\n\t\t\teliminateForAll(imply->argumentRight);\n\t\t};\n\n\tconst auto handleNot =\n\t\t[](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\teliminateForAll(not_->argument);\n\t\t};\n\n\tconst auto handleOr =\n\t\t[](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\teliminateForAll(argument);\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid eliminateDoubleNegations(ast::Precondition &precondition)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\teliminateDoubleNegations(argument);\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\teliminateDoubleNegations(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[&](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\teliminateDoubleNegations(forAll->argument);\n\t\t};\n\n\tconst auto handleImply =\n\t\t[&](ast::ImplyPointer<ast::Precondition> &imply)\n\t\t{\n\t\t\teliminateDoubleNegations(imply->argumentLeft);\n\t\t\teliminateDoubleNegations(imply->argumentRight);\n\t\t};\n\n\tconst auto handleNot =\n\t\t[&](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\teliminateDoubleNegations(not_->argument);\n\n\t\t\tif (not_->argument.is<ast::NotPointer<ast::Precondition>>())\n\t\t\t{\n\t\t\t\t\/\/ As the parent contains the argument, the argument needs to be saved before overwriting the parent\n\t\t\t\t\/\/ TODO: check whether this workaround can be avoided\n\t\t\t\tauto argument = std::move(not_->argument.get<ast::NotPointer<ast::Precondition>>());\n\t\t\t\tprecondition = std::move(argument);\n\t\t\t}\n\t\t};\n\n\tconst auto handleOr =\n\t\t[](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\teliminateDoubleNegations(argument);\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid reduce(ast::Precondition &precondition)\n{\n\t\/\/ Replace “imply” statements with disjunctions\n\teliminateImply(precondition);\n\n\t\/\/ Negation-normalize the precondition\n\tnegationNormalize(precondition);\n\n\t\/\/ Eliminate “forall” statements\n\teliminateForAll(precondition);\n\n\t\/\/ Eliminate double negations introduced by eliminating “forall” statements\n\teliminateDoubleNegations(precondition);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n}\n<commit_msg>Added missing recursion step in PDDL reduction.<commit_after>#include <pddlparse\/detail\/normalization\/Reduction.h>\n\n#include <pddlparse\/AST.h>\n#include <pddlparse\/Exception.h>\n#include <pddlparse\/NormalizedAST.h>\n#include <pddlparse\/detail\/normalization\/AtomicFormula.h>\n#include <pddlparse\/detail\/normalization\/CollectFreeVariables.h>\n\nnamespace pddl\n{\nnamespace detail\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Reduction\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Forward declarations\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid eliminateImply(ast::Precondition &precondition);\nvoid negationNormalize(ast::Precondition &precondition);\nvoid eliminateForAll(ast::Precondition &precondition);\nvoid eliminateDoubleNegations(ast::Precondition &precondition);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid eliminateImply(ast::Precondition &precondition)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\teliminateImply(argument);\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\teliminateImply(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\teliminateImply(forAll->argument);\n\t\t};\n\n\tconst auto handleImply =\n\t\t[&](ast::ImplyPointer<ast::Precondition> &imply)\n\t\t{\n\t\t\teliminateImply(imply->argumentLeft);\n\t\t\teliminateImply(imply->argumentRight);\n\n\t\t\tast::Or<ast::Precondition>::Arguments arguments;\n\t\t\targuments.reserve(2);\n\t\t\targuments.emplace_back(std::make_unique<ast::Not<ast::Precondition>>(std::move(imply->argumentLeft)));\n\t\t\targuments.emplace_back(std::move(imply->argumentRight));\n\n\t\t\tprecondition = std::make_unique<ast::Or<ast::Precondition>>(std::move(arguments));\n\t\t};\n\n\tconst auto handleNot =\n\t\t[](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\teliminateImply(not_->argument);\n\t\t};\n\n\tconst auto handleOr =\n\t\t[](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\teliminateImply(argument);\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Negation-normalize an expression whose parent is a “not” expression\nvoid negationNormalizeNegated(ast::Precondition &precondition, ast::Precondition &parent)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[&](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tast::Or<ast::Precondition>::Arguments arguments;\n\t\t\targuments.reserve(and_->arguments.size());\n\n\t\t\t\/\/ Apply De Morgan\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\targuments.emplace_back(std::make_unique<ast::Not<ast::Precondition>>(std::move(argument)));\n\n\t\t\t\/\/ Finally, negation-normalize each argument\n\t\t\tfor (auto &argument : arguments)\n\t\t\t\tnegationNormalize(argument);\n\n\t\t\t\/\/ Replace the parent “not” containing this “and” with an “or” over the negated arguments\n\t\t\tparent = std::make_unique<ast::Or<ast::Precondition>>(std::move(arguments));\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\tnegationNormalize(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\tnegationNormalize(forAll->argument);\n\t\t};\n\n\tconst auto handleImply =\n\t\t[](ast::ImplyPointer<ast::Precondition> &)\n\t\t{\n\t\t\tthrow std::logic_error(\"precondition not ready for negation normalization (imply), please report to the bug tracker\");\n\t\t};\n\n\tconst auto handleNot =\n\t\t[&](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\tnegationNormalize(not_->argument);\n\n\t\t\t\/\/ As the parent contains the argument, the argument needs to be saved before overwriting the parent\n\t\t\t\/\/ TODO: check whether this workaround can be avoided\n\t\t\tauto argument = std::move(not_->argument);\n\t\t\tparent = std::move(argument);\n\t\t};\n\n\tconst auto handleOr =\n\t\t[&](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tast::And<ast::Precondition>::Arguments arguments;\n\t\t\targuments.reserve(or_->arguments.size());\n\n\t\t\t\/\/ Apply De Morgan\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\targuments.emplace_back(std::make_unique<ast::Not<ast::Precondition>>(std::move(argument)));\n\n\t\t\t\/\/ Finally, negation-normalize each argument\n\t\t\tfor (auto &argument : arguments)\n\t\t\t\tnegationNormalize(argument);\n\n\t\t\t\/\/ Replace the parent “not” containing this “or” with an “and” over the negated arguments\n\t\t\tparent = std::make_unique<ast::And<ast::Precondition>>(std::move(arguments));\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid negationNormalize(ast::Precondition &precondition)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\tnegationNormalize(argument);\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\tnegationNormalize(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\tnegationNormalize(forAll->argument);\n\t\t};\n\n\tconst auto handleImply =\n\t\t[](ast::ImplyPointer<ast::Precondition> &)\n\t\t{\n\t\t\tthrow std::logic_error(\"precondition not ready for negation normalization (imply), please report to the bug tracker\");\n\t\t};\n\n\tconst auto handleNot =\n\t\t[&](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\tnegationNormalizeNegated(not_->argument, precondition);\n\t\t};\n\n\tconst auto handleOr =\n\t\t[](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\tnegationNormalize(argument);\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid eliminateForAll(ast::Precondition &precondition)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\teliminateForAll(argument);\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\teliminateForAll(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[&](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\teliminateForAll(forAll->argument);\n\n\t\t\tauto negatedArgument = std::make_unique<ast::Not<ast::Precondition>>(std::move(forAll->argument));\n\t\t\tauto exists = std::make_unique<ast::Exists<ast::Precondition>>(std::move(forAll->parameters), std::move(negatedArgument));\n\t\t\tprecondition = std::make_unique<ast::Not<ast::Precondition>>(std::move(exists));\n\t\t};\n\n\tconst auto handleImply =\n\t\t[&](ast::ImplyPointer<ast::Precondition> &imply)\n\t\t{\n\t\t\teliminateForAll(imply->argumentLeft);\n\t\t\teliminateForAll(imply->argumentRight);\n\t\t};\n\n\tconst auto handleNot =\n\t\t[](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\teliminateForAll(not_->argument);\n\t\t};\n\n\tconst auto handleOr =\n\t\t[](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\teliminateForAll(argument);\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid eliminateDoubleNegations(ast::Precondition &precondition)\n{\n\tconst auto handleAtomicFormula =\n\t\t[](ast::AtomicFormula &)\n\t\t{\n\t\t};\n\n\tconst auto handleAnd =\n\t\t[](ast::AndPointer<ast::Precondition> &and_)\n\t\t{\n\t\t\tfor (auto &argument : and_->arguments)\n\t\t\t\teliminateDoubleNegations(argument);\n\t\t};\n\n\tconst auto handleExists =\n\t\t[](ast::ExistsPointer<ast::Precondition> &exists)\n\t\t{\n\t\t\teliminateDoubleNegations(exists->argument);\n\t\t};\n\n\tconst auto handleForAll =\n\t\t[&](ast::ForAllPointer<ast::Precondition> &forAll)\n\t\t{\n\t\t\teliminateDoubleNegations(forAll->argument);\n\t\t};\n\n\tconst auto handleImply =\n\t\t[&](ast::ImplyPointer<ast::Precondition> &imply)\n\t\t{\n\t\t\teliminateDoubleNegations(imply->argumentLeft);\n\t\t\teliminateDoubleNegations(imply->argumentRight);\n\t\t};\n\n\tconst auto handleNot =\n\t\t[&](ast::NotPointer<ast::Precondition> ¬_)\n\t\t{\n\t\t\teliminateDoubleNegations(not_->argument);\n\n\t\t\tif (not_->argument.is<ast::NotPointer<ast::Precondition>>())\n\t\t\t{\n\t\t\t\t\/\/ As the parent contains the argument, the argument needs to be saved before overwriting the parent\n\t\t\t\t\/\/ TODO: check whether this workaround can be avoided\n\t\t\t\tauto argument = std::move(not_->argument.get<ast::NotPointer<ast::Precondition>>());\n\t\t\t\tprecondition = std::move(argument);\n\t\t\t}\n\t\t};\n\n\tconst auto handleOr =\n\t\t[](ast::OrPointer<ast::Precondition> &or_)\n\t\t{\n\t\t\tfor (auto &argument : or_->arguments)\n\t\t\t\teliminateDoubleNegations(argument);\n\t\t};\n\n\tprecondition.match(handleAtomicFormula, handleAnd, handleExists, handleForAll, handleImply, handleNot, handleOr);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid reduce(ast::Precondition &precondition)\n{\n\t\/\/ Replace “imply” statements with disjunctions\n\teliminateImply(precondition);\n\n\t\/\/ Negation-normalize the precondition\n\tnegationNormalize(precondition);\n\n\t\/\/ Eliminate “forall” statements\n\teliminateForAll(precondition);\n\n\t\/\/ Eliminate double negations introduced by eliminating “forall” statements\n\teliminateDoubleNegations(precondition);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>svl: convert DBG_ASSERTs in SvtCJKOptions<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: datwin.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 14:30:22 $\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 _SFXDATWIN_HXX\n#define _SFXDATWIN_HXX\n\n#ifndef _BRWBOX_HXX\n#include <brwbox.hxx>\n#endif\n\n#ifndef _BRWHEAD_HXX\n#include <brwhead.hxx>\n#endif\n\n#ifndef _TIMER_HXX \/\/autogen\n#include <vcl\/timer.hxx>\n#endif\n#ifndef _IMAGE_HXX \/\/autogen\n#include <vcl\/image.hxx>\n#endif\n#ifndef _LIST_HXX \/\/autogen\n#include <tools\/list.hxx>\n#endif\n#ifndef _TRANSFER_HXX\n#include \"transfer.hxx\"\n#endif\n\n\/\/===================================================================\n\n#define MIN_COLUMNWIDTH 2\n#define DRAG_CRITICAL 4\n\nDECLARE_LIST( RectangleList, Rectangle* );\n\n\/\/===================================================================\n\nclass ButtonFrame\n{\n Rectangle aRect;\n Rectangle aInnerRect;\n String aText;\n BOOL bPressed;\n BOOL bCurs;\n BOOL bAbbr;\n BOOL m_bDrawDisabled;\n\npublic:\n ButtonFrame( const Point& rPt, const Size& rSz,\n const String &rText,\n BOOL bPress = FALSE,\n BOOL bCursor = FALSE,\n BOOL bAbbreviate = TRUE,\n BOOL _bDrawDisabled = FALSE)\n :aRect( rPt, rSz )\n ,aInnerRect( Point( aRect.Left()+1, aRect.Top()+1 ),\n Size( aRect.GetWidth()-2, aRect.GetHeight()-2 ) )\n ,aText(rText)\n ,bPressed(bPress)\n ,bCurs(bCursor)\n ,bAbbr(bAbbreviate)\n ,m_bDrawDisabled(_bDrawDisabled)\n {\n }\n\n void Draw( OutputDevice& rDev );\n};\n\n\/\/===================================================================\n\nclass BrowserColumn\n{\n USHORT _nId;\n ULONG _nOriginalWidth;\n ULONG _nWidth;\n Image _aImage;\n String _aTitle;\n BOOL _bFrozen;\n HeaderBarItemBits _nFlags;\n\npublic:\n BrowserColumn( USHORT nItemId, const Image &rImage,\n const String& rTitle, ULONG nWidthPixel, const Fraction& rCurrentZoom,\n HeaderBarItemBits nFlags );\n\n USHORT GetId() const { return _nId; }\n\n ULONG Width() { return _nWidth; }\n Image& GetImage() { return _aImage; }\n String& Title() { return _aTitle; }\n HeaderBarItemBits& Flags() { return _nFlags; }\n\n BOOL IsFrozen() const { return _bFrozen; }\n void Freeze( BOOL bFreeze = TRUE ) { _bFrozen = bFreeze; }\n\n virtual void Draw( BrowseBox& rBox, OutputDevice& rDev,\n const Point& rPos, BOOL bCurs );\n\n void SetWidth(ULONG nNewWidthPixel, const Fraction& rCurrentZoom);\n void ZoomChanged(const Fraction& rNewZoom);\n};\n\n\/\/===================================================================\n\nclass BrowserDataWin\n :public Control\n ,public DragSourceHelper\n ,public DropTargetHelper\n{\nfriend class BrowseBox;\n BrowserHeader* pHeaderBar; \/\/ only for BROWSER_HEADERBAR_NEW\n Window* pEventWin; \/\/ Window of forwarded events\n ScrollBarBox* pCornerWin; \/\/ Window in the corner btw the ScrollBars\n BOOL* pDtorNotify;\n AutoTimer aMouseTimer; \/\/ recalls MouseMove on dragging out\n MouseEvent aRepeatEvt; \/\/ a MouseEvent to repeat\n Point aLastMousePos; \/\/ verhindert pseudo-MouseMoves\n\n String aRealRowCount; \/\/ zur Anzeige im VScrollBar\n\n RectangleList aInvalidRegion; \/\/ invalidated Rectangles during !UpdateMode\n FASTBOOL bInPaint; \/\/ TRUE while in Paint\n FASTBOOL bInCommand; \/\/ TRUE while in Command\n FASTBOOL bNoScrollBack; \/\/ nur vorwaerts scrollen\n FASTBOOL bNoHScroll; \/\/ kein horizontaler Scrollbar\n FASTBOOL bNoVScroll; \/\/ no vertical scrollbar\n FASTBOOL bAutoHScroll; \/\/ autohide horizontaler Scrollbar\n FASTBOOL bAutoVScroll; \/\/ autohide horizontaler Scrollbar\n FASTBOOL bUpdateMode; \/\/ nicht SV-UpdateMode wegen Invalidate()\n FASTBOOL bAutoSizeLastCol;\/\/ last column always fills up window\n FASTBOOL bHighlightAuto; \/\/ new auto-highlight by SetFont() etc.\n FASTBOOL bResizeOnPaint; \/\/ outstanding resize-event\n FASTBOOL bUpdateOnUnlock; \/\/ Update() while locked\n FASTBOOL bInUpdateScrollbars; \/\/ Rekursionsschutz\n FASTBOOL bHadRecursion; \/\/ Rekursion war aufgetreten\n FASTBOOL bOwnDataChangedHdl; \/\/ dont change colors in DataChanged\n FASTBOOL bCallingDropCallback; \/\/ we're in a callback to AcceptDrop or ExecuteDrop curently\n USHORT nUpdateLock; \/\/ lock count, dont call Control::Update()!\n short nCursorHidden; \/\/ new conuter for DoHide\/ShowCursor\n\n long m_nDragRowDividerLimit;\n long m_nDragRowDividerOffset;\n\npublic:\n BrowserDataWin( BrowseBox* pParent );\n ~BrowserDataWin();\n\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n virtual void Paint( const Rectangle& rRect );\n virtual void RequestHelp( const HelpEvent& rHEvt );\n virtual void Command( const CommandEvent& rEvt );\n virtual void MouseButtonDown( const MouseEvent& rEvt );\n virtual void MouseMove( const MouseEvent& rEvt );\n DECL_LINK( RepeatedMouseMove, void * );\n\n virtual void MouseButtonUp( const MouseEvent& rEvt );\n virtual void KeyInput( const KeyEvent& rEvt );\n virtual void Tracking( const TrackingEvent& rTEvt );\n\n \/\/ DropTargetHelper overridables\n virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );\n virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );\n\n \/\/ DragSourceHelper overridables\n virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel );\n\n\n BrowseEvent CreateBrowseEvent( const Point& rPosPixel );\n void Repaint();\n BrowseBox* GetParent() const\n { return (BrowseBox*) Window::GetParent(); }\n const String& GetRealRowCount() const { return aRealRowCount; }\n\n void SetUpdateMode( BOOL bMode );\n FASTBOOL GetUpdateMode() const { return bUpdateMode; }\n void EnterUpdateLock() { ++nUpdateLock; }\n void LeaveUpdateLock();\n void Update();\n void DoOutstandingInvalidations();\n void Invalidate();\n void Invalidate( const Rectangle& rRect );\n\nprotected:\n void StartRowDividerDrag( const Point& _rStartPos );\n BOOL ImplRowDividerHitTest( const BrowserMouseEvent& _rEvent );\n};\n\n\/\/-------------------------------------------------------------------\n\ninline void BrowserDataWin::Repaint()\n{\n if ( GetUpdateMode() )\n Update();\n Paint( Rectangle( Point(), GetOutputSizePixel() ) );\n}\n\n\/\/===================================================================\n\nclass BrowserScrollBar: public ScrollBar\n{\n ULONG _nTip;\n ULONG _nLastPos;\n BrowserDataWin* _pDataWin;\n\npublic:\n BrowserScrollBar( Window* pParent, WinBits nStyle,\n BrowserDataWin *pDataWin )\n : ScrollBar( pParent, nStyle ),\n _nTip( 0 ),\n _nLastPos( ULONG_MAX ),\n _pDataWin( pDataWin )\n {}\n \/\/ScrollBar( Window* pParent, const ResId& rResId );\n\n virtual void Tracking( const TrackingEvent& rTEvt );\n virtual void EndScroll();\n};\n\n\/\/===================================================================\n\nvoid InitSettings_Impl( Window *pWin,\n BOOL bFont = TRUE, BOOL bForeground = TRUE, BOOL bBackground = TRUE );\n\n\/\/===================================================================\n\n#ifdef DBG_MI\n\nvoid DoLog_Impl( const BrowseBox *pThis, const char *pWhat, const char *pWho );\n#define LOG(pThis,what,who) DoLog_Impl(pThis,what,who)\n\n#else\n\n#define LOG(pThis,what,who)\n\n#endif\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.10.62); FILE MERGED 2005\/11\/14 14:43:40 pl 1.10.62.2: #i55991# removed warnings 2005\/10\/25 17:37:23 pl 1.10.62.1: #i55991# removed warnings for linux platform<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: datwin.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 20:40:19 $\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 _SFXDATWIN_HXX\n#define _SFXDATWIN_HXX\n\n#ifndef _BRWBOX_HXX\n#include <brwbox.hxx>\n#endif\n\n#ifndef _BRWHEAD_HXX\n#include <brwhead.hxx>\n#endif\n\n#ifndef _TIMER_HXX \/\/autogen\n#include <vcl\/timer.hxx>\n#endif\n#ifndef _IMAGE_HXX \/\/autogen\n#include <vcl\/image.hxx>\n#endif\n#ifndef _LIST_HXX \/\/autogen\n#include <tools\/list.hxx>\n#endif\n#ifndef _TRANSFER_HXX\n#include \"transfer.hxx\"\n#endif\n\n\/\/===================================================================\n\n#define MIN_COLUMNWIDTH 2\n#define DRAG_CRITICAL 4\n\nDECLARE_LIST( RectangleList, Rectangle* )\n\n\/\/===================================================================\n\nclass ButtonFrame\n{\n Rectangle aRect;\n Rectangle aInnerRect;\n String aText;\n BOOL bPressed;\n BOOL bCurs;\n BOOL bAbbr;\n BOOL m_bDrawDisabled;\n\npublic:\n ButtonFrame( const Point& rPt, const Size& rSz,\n const String &rText,\n BOOL bPress = FALSE,\n BOOL bCursor = FALSE,\n BOOL bAbbreviate = TRUE,\n BOOL _bDrawDisabled = FALSE)\n :aRect( rPt, rSz )\n ,aInnerRect( Point( aRect.Left()+1, aRect.Top()+1 ),\n Size( aRect.GetWidth()-2, aRect.GetHeight()-2 ) )\n ,aText(rText)\n ,bPressed(bPress)\n ,bCurs(bCursor)\n ,bAbbr(bAbbreviate)\n ,m_bDrawDisabled(_bDrawDisabled)\n {\n }\n\n void Draw( OutputDevice& rDev );\n};\n\n\/\/===================================================================\n\nclass BrowserColumn\n{\n USHORT _nId;\n ULONG _nOriginalWidth;\n ULONG _nWidth;\n Image _aImage;\n String _aTitle;\n BOOL _bFrozen;\n HeaderBarItemBits _nFlags;\n\npublic:\n BrowserColumn( USHORT nItemId, const Image &rImage,\n const String& rTitle, ULONG nWidthPixel, const Fraction& rCurrentZoom,\n HeaderBarItemBits nFlags );\n virtual ~BrowserColumn();\n\n USHORT GetId() const { return _nId; }\n\n ULONG Width() { return _nWidth; }\n Image& GetImage() { return _aImage; }\n String& Title() { return _aTitle; }\n HeaderBarItemBits& Flags() { return _nFlags; }\n\n BOOL IsFrozen() const { return _bFrozen; }\n void Freeze( BOOL bFreeze = TRUE ) { _bFrozen = bFreeze; }\n\n virtual void Draw( BrowseBox& rBox, OutputDevice& rDev,\n const Point& rPos, BOOL bCurs );\n\n void SetWidth(ULONG nNewWidthPixel, const Fraction& rCurrentZoom);\n void ZoomChanged(const Fraction& rNewZoom);\n};\n\n\/\/===================================================================\n\nclass BrowserDataWin\n :public Control\n ,public DragSourceHelper\n ,public DropTargetHelper\n{\npublic:\n BrowserHeader* pHeaderBar; \/\/ only for BROWSER_HEADERBAR_NEW\n Window* pEventWin; \/\/ Window of forwarded events\n ScrollBarBox* pCornerWin; \/\/ Window in the corner btw the ScrollBars\n BOOL* pDtorNotify;\n AutoTimer aMouseTimer; \/\/ recalls MouseMove on dragging out\n MouseEvent aRepeatEvt; \/\/ a MouseEvent to repeat\n Point aLastMousePos; \/\/ verhindert pseudo-MouseMoves\n\n String aRealRowCount; \/\/ zur Anzeige im VScrollBar\n\n RectangleList aInvalidRegion; \/\/ invalidated Rectangles during !UpdateMode\n FASTBOOL bInPaint; \/\/ TRUE while in Paint\n FASTBOOL bInCommand; \/\/ TRUE while in Command\n FASTBOOL bNoScrollBack; \/\/ nur vorwaerts scrollen\n FASTBOOL bNoHScroll; \/\/ kein horizontaler Scrollbar\n FASTBOOL bNoVScroll; \/\/ no vertical scrollbar\n FASTBOOL bAutoHScroll; \/\/ autohide horizontaler Scrollbar\n FASTBOOL bAutoVScroll; \/\/ autohide horizontaler Scrollbar\n FASTBOOL bUpdateMode; \/\/ nicht SV-UpdateMode wegen Invalidate()\n FASTBOOL bAutoSizeLastCol;\/\/ last column always fills up window\n FASTBOOL bHighlightAuto; \/\/ new auto-highlight by SetFont() etc.\n FASTBOOL bResizeOnPaint; \/\/ outstanding resize-event\n FASTBOOL bUpdateOnUnlock; \/\/ Update() while locked\n FASTBOOL bInUpdateScrollbars; \/\/ Rekursionsschutz\n FASTBOOL bHadRecursion; \/\/ Rekursion war aufgetreten\n FASTBOOL bOwnDataChangedHdl; \/\/ dont change colors in DataChanged\n FASTBOOL bCallingDropCallback; \/\/ we're in a callback to AcceptDrop or ExecuteDrop curently\n USHORT nUpdateLock; \/\/ lock count, dont call Control::Update()!\n short nCursorHidden; \/\/ new conuter for DoHide\/ShowCursor\n\n long m_nDragRowDividerLimit;\n long m_nDragRowDividerOffset;\n\npublic:\n BrowserDataWin( BrowseBox* pParent );\n ~BrowserDataWin();\n\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n virtual void Paint( const Rectangle& rRect );\n virtual void RequestHelp( const HelpEvent& rHEvt );\n virtual void Command( const CommandEvent& rEvt );\n virtual void MouseButtonDown( const MouseEvent& rEvt );\n virtual void MouseMove( const MouseEvent& rEvt );\n DECL_LINK( RepeatedMouseMove, void * );\n\n virtual void MouseButtonUp( const MouseEvent& rEvt );\n virtual void KeyInput( const KeyEvent& rEvt );\n virtual void Tracking( const TrackingEvent& rTEvt );\n\n \/\/ DropTargetHelper overridables\n virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );\n virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );\n\n \/\/ DragSourceHelper overridables\n virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel );\n\n\n BrowseEvent CreateBrowseEvent( const Point& rPosPixel );\n void Repaint();\n BrowseBox* GetParent() const\n { return (BrowseBox*) Window::GetParent(); }\n const String& GetRealRowCount() const { return aRealRowCount; }\n\n void SetUpdateMode( BOOL bMode );\n FASTBOOL GetUpdateMode() const { return bUpdateMode; }\n void EnterUpdateLock() { ++nUpdateLock; }\n void LeaveUpdateLock();\n void Update();\n void DoOutstandingInvalidations();\n void Invalidate( USHORT nFlags = 0 );\n void Invalidate( const Rectangle& rRect, USHORT nFlags = 0 );\n void Invalidate( const Region& rRegion, USHORT nFlags = 0 )\n { Control::Invalidate( rRegion, nFlags ); }\n\nprotected:\n void StartRowDividerDrag( const Point& _rStartPos );\n BOOL ImplRowDividerHitTest( const BrowserMouseEvent& _rEvent );\n};\n\n\/\/-------------------------------------------------------------------\n\ninline void BrowserDataWin::Repaint()\n{\n if ( GetUpdateMode() )\n Update();\n Paint( Rectangle( Point(), GetOutputSizePixel() ) );\n}\n\n\/\/===================================================================\n\nclass BrowserScrollBar: public ScrollBar\n{\n ULONG _nTip;\n ULONG _nLastPos;\n BrowserDataWin* _pDataWin;\n\npublic:\n BrowserScrollBar( Window* pParent, WinBits nStyle,\n BrowserDataWin *pDataWin )\n : ScrollBar( pParent, nStyle ),\n _nTip( 0 ),\n _nLastPos( ULONG_MAX ),\n _pDataWin( pDataWin )\n {}\n \/\/ScrollBar( Window* pParent, const ResId& rResId );\n\n virtual void Tracking( const TrackingEvent& rTEvt );\n virtual void EndScroll();\n};\n\n\/\/===================================================================\n\nvoid InitSettings_Impl( Window *pWin,\n BOOL bFont = TRUE, BOOL bForeground = TRUE, BOOL bBackground = TRUE );\n\n\/\/===================================================================\n\n#ifdef DBG_MI\n\nvoid DoLog_Impl( const BrowseBox *pThis, const char *pWhat, const char *pWho );\n#define LOG(pThis,what,who) DoLog_Impl(pThis,what,who)\n\n#else\n\n#define LOG(pThis,what,who)\n\n#endif\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: macitem.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 15:59: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\n#ifndef _STREAM_HXX \/\/autogen\n#include <tools\/stream.hxx>\n#endif\n\n#ifndef GCC\n#pragma hdrstop\n#endif\n#define ITEMID_MACRO 0\n\n#include \"macitem.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nDBG_NAME(SvxMacroItem);\n\n\/\/ -----------------------------------------------------------------------\n\nTYPEINIT1_AUTOFACTORY(SvxMacroItem, SfxPoolItem);\n\n\/\/ -----------------------------------------------------------------------\n\n\nSjJSbxObjectBase::~SjJSbxObjectBase()\n{\n}\n\nSjJSbxObjectBase* SjJSbxObjectBase::Clone( void )\n{\n return NULL;\n}\n\nSvxMacro::SvxMacro( const String &rMacName, const String &rLanguage)\n : aMacName( rMacName ), aLibName( rLanguage),\n pFunctionObject(NULL), eType( EXTENDED_STYPE)\n{\n if (rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_STARBASIC))\n eType=STARBASIC;\n else if (rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_JAVASCRIPT))\n eType=JAVASCRIPT;\n}\n\n\nSvxMacro::~SvxMacro()\n{\n delete pFunctionObject;\n}\n\nString SvxMacro::GetLanguage()const\n{\n if(eType==STARBASIC)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_STARBASIC));\n }\n else if(eType==JAVASCRIPT)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_JAVASCRIPT));\n }\n else if(eType==EXTENDED_STYPE)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_SF));\n\n }\n return aLibName;\n}\n\n\n\nSvxMacro& SvxMacro::operator=( const SvxMacro& rBase )\n{\n if( this != &rBase )\n {\n aMacName = rBase.aMacName;\n aLibName = rBase.aLibName;\n delete pFunctionObject;\n pFunctionObject = rBase.pFunctionObject ? rBase.pFunctionObject->Clone() : NULL;\n eType = rBase.eType;\n }\n return *this;\n}\n\n\nSvxMacroTableDtor& SvxMacroTableDtor::operator=( const SvxMacroTableDtor& rTbl )\n{\n DelDtor();\n SvxMacro* pTmp = ((SvxMacroTableDtor&)rTbl).First();\n while( pTmp )\n {\n SvxMacro *pNew = new SvxMacro( *pTmp );\n Insert( rTbl.GetCurKey(), pNew );\n pTmp = ((SvxMacroTableDtor&)rTbl).Next();\n }\n return *this;\n}\n\n\nSvStream& SvxMacroTableDtor::Read( SvStream& rStrm, USHORT nVersion )\n{\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStrm >> nVersion;\n short nMacro;\n rStrm >> nMacro;\n\n for( short i = 0; i < nMacro; ++i )\n {\n USHORT nCurKey, eType = STARBASIC;\n String aLibName, aMacName;\n rStrm >> nCurKey;\n SfxPoolItem::readByteString(rStrm, aLibName);\n SfxPoolItem::readByteString(rStrm, aMacName);\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStrm >> eType;\n\n SvxMacro* pNew = new SvxMacro( aMacName, aLibName, (ScriptType)eType );\n\n SvxMacro *pOld = Get( nCurKey );\n if( pOld )\n {\n delete pOld;\n Replace( nCurKey, pNew );\n }\n else\n Insert( nCurKey, pNew );\n }\n return rStrm;\n}\n\n\nSvStream& SvxMacroTableDtor::Write( SvStream& rStream ) const\n{\n USHORT nVersion = SOFFICE_FILEFORMAT_31 == rStream.GetVersion()\n ? SVX_MACROTBL_VERSION31\n : SVX_MACROTBL_AKTVERSION;\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStream << nVersion;\n\n rStream << (USHORT)Count();\n\n SvxMacro* pMac = ((SvxMacroTableDtor*)this)->First();\n while( pMac && rStream.GetError() == SVSTREAM_OK )\n {\n rStream << (short)GetCurKey();\n SfxPoolItem::writeByteString(rStream, pMac->GetLibName());\n SfxPoolItem::writeByteString(rStream, pMac->GetMacName());\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStream << (USHORT)pMac->GetScriptType();\n pMac = ((SvxMacroTableDtor*)this)->Next();\n }\n return rStream;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxMacroTableDtor::DelDtor()\n{\n SvxMacro* pTmp = First();\n while( pTmp )\n {\n delete pTmp;\n pTmp = Next();\n }\n Clear();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nint SvxMacroItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n\n const SvxMacroTableDtor& rOwn = aMacroTable;\n const SvxMacroTableDtor& rOther = ( (SvxMacroItem&) rAttr ).aMacroTable;\n\n \/\/ Anzahl unterschiedlich => auf jeden Fall ungleich\n if ( rOwn.Count() != rOther.Count() )\n return FALSE;\n\n \/\/ einzeln verleichen; wegen Performance ist die Reihenfolge wichtig\n for ( USHORT nNo = 0; nNo < rOwn.Count(); ++nNo )\n {\n const SvxMacro *pOwnMac = rOwn.GetObject(nNo);\n const SvxMacro *pOtherMac = rOther.GetObject(nNo);\n if ( rOwn.GetKey(pOwnMac) != rOther.GetKey(pOtherMac) ||\n pOwnMac->GetLibName() != pOtherMac->GetLibName() ||\n pOwnMac->GetMacName() != pOtherMac->GetMacName() )\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxMacroItem::Clone( SfxItemPool* ) const\n{\n return new SvxMacroItem( *this );\n}\n\n\/\/------------------------------------------------------------------------\n\nSfxItemPresentation SvxMacroItem::GetPresentation\n(\n SfxItemPresentation ePres,\n SfxMapUnit eCoreUnit,\n SfxMapUnit ePresUnit,\n XubString& rText,\n const IntlWrapper *\n) const\n{\n\/*!!!\n SvxMacroTableDtor& rTbl = (SvxMacroTableDtor&)GetMacroTable();\n SvxMacro* pMac = rTbl.First();\n\n while ( pMac )\n {\n rText += pMac->GetLibName();\n rText += cpDelim;\n rText += pMac->GetMacName();\n pMac = rTbl.Next();\n if ( pMac )\n rText += cpDelim;\n }\n*\/\n rText.Erase();\n return SFX_ITEM_PRESENTATION_NONE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvStream& SvxMacroItem::Store( SvStream& rStrm , USHORT nItemVersion ) const\n{\n return aMacroTable.Write( rStrm );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxMacroItem::Create( SvStream& rStrm, USHORT nVersion ) const\n{\n SvxMacroItem* pAttr = new SvxMacroItem( Which() );\n pAttr->aMacroTable.Read( rStrm, nVersion );\n return pAttr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxMacroItem::SetMacro( USHORT nEvent, const SvxMacro& rMacro )\n{\n SvxMacro *pMacro;\n if ( 0 != (pMacro=aMacroTable.Get(nEvent)) )\n {\n delete pMacro;\n aMacroTable.Replace(nEvent, new SvxMacro( rMacro ) );\n }\n else\n aMacroTable.Insert(nEvent, new SvxMacro( rMacro ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SvxMacroItem::GetVersion( USHORT nFileFormatVersion ) const\n{\n return SOFFICE_FILEFORMAT_31 == nFileFormatVersion\n ? 0 : aMacroTable.GetVersion();\n}\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.5.60); FILE MERGED 2005\/11\/15 17:54:41 pl 1.5.60.1: #i55991# removed warnings<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: macitem.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 21:12:30 $\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 _STREAM_HXX \/\/autogen\n#include <tools\/stream.hxx>\n#endif\n\n#ifndef GCC\n#pragma hdrstop\n#endif\n#define ITEMID_MACRO 0\n\n#include \"macitem.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nDBG_NAME(SvxMacroItem);\n\n\/\/ -----------------------------------------------------------------------\n\nTYPEINIT1_AUTOFACTORY(SvxMacroItem, SfxPoolItem);\n\n\/\/ -----------------------------------------------------------------------\n\n\nSjJSbxObjectBase::~SjJSbxObjectBase()\n{\n}\n\nSjJSbxObjectBase* SjJSbxObjectBase::Clone( void )\n{\n return NULL;\n}\n\nSvxMacro::SvxMacro( const String &rMacName, const String &rLanguage)\n : aMacName( rMacName ), aLibName( rLanguage),\n pFunctionObject(NULL), eType( EXTENDED_STYPE)\n{\n if (rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_STARBASIC))\n eType=STARBASIC;\n else if (rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_JAVASCRIPT))\n eType=JAVASCRIPT;\n}\n\n\nSvxMacro::~SvxMacro()\n{\n delete pFunctionObject;\n}\n\nString SvxMacro::GetLanguage()const\n{\n if(eType==STARBASIC)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_STARBASIC));\n }\n else if(eType==JAVASCRIPT)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_JAVASCRIPT));\n }\n else if(eType==EXTENDED_STYPE)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_SF));\n\n }\n return aLibName;\n}\n\n\n\nSvxMacro& SvxMacro::operator=( const SvxMacro& rBase )\n{\n if( this != &rBase )\n {\n aMacName = rBase.aMacName;\n aLibName = rBase.aLibName;\n delete pFunctionObject;\n pFunctionObject = rBase.pFunctionObject ? rBase.pFunctionObject->Clone() : NULL;\n eType = rBase.eType;\n }\n return *this;\n}\n\n\nSvxMacroTableDtor& SvxMacroTableDtor::operator=( const SvxMacroTableDtor& rTbl )\n{\n DelDtor();\n SvxMacro* pTmp = ((SvxMacroTableDtor&)rTbl).First();\n while( pTmp )\n {\n SvxMacro *pNew = new SvxMacro( *pTmp );\n Insert( rTbl.GetCurKey(), pNew );\n pTmp = ((SvxMacroTableDtor&)rTbl).Next();\n }\n return *this;\n}\n\n\nSvStream& SvxMacroTableDtor::Read( SvStream& rStrm, USHORT nVersion )\n{\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStrm >> nVersion;\n short nMacro;\n rStrm >> nMacro;\n\n for( short i = 0; i < nMacro; ++i )\n {\n USHORT nCurKey, eType = STARBASIC;\n String aLibName, aMacName;\n rStrm >> nCurKey;\n SfxPoolItem::readByteString(rStrm, aLibName);\n SfxPoolItem::readByteString(rStrm, aMacName);\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStrm >> eType;\n\n SvxMacro* pNew = new SvxMacro( aMacName, aLibName, (ScriptType)eType );\n\n SvxMacro *pOld = Get( nCurKey );\n if( pOld )\n {\n delete pOld;\n Replace( nCurKey, pNew );\n }\n else\n Insert( nCurKey, pNew );\n }\n return rStrm;\n}\n\n\nSvStream& SvxMacroTableDtor::Write( SvStream& rStream ) const\n{\n USHORT nVersion = SOFFICE_FILEFORMAT_31 == rStream.GetVersion()\n ? SVX_MACROTBL_VERSION31\n : SVX_MACROTBL_AKTVERSION;\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStream << nVersion;\n\n rStream << (USHORT)Count();\n\n SvxMacro* pMac = ((SvxMacroTableDtor*)this)->First();\n while( pMac && rStream.GetError() == SVSTREAM_OK )\n {\n rStream << (short)GetCurKey();\n SfxPoolItem::writeByteString(rStream, pMac->GetLibName());\n SfxPoolItem::writeByteString(rStream, pMac->GetMacName());\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStream << (USHORT)pMac->GetScriptType();\n pMac = ((SvxMacroTableDtor*)this)->Next();\n }\n return rStream;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxMacroTableDtor::DelDtor()\n{\n SvxMacro* pTmp = First();\n while( pTmp )\n {\n delete pTmp;\n pTmp = Next();\n }\n Clear();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nint SvxMacroItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n\n const SvxMacroTableDtor& rOwn = aMacroTable;\n const SvxMacroTableDtor& rOther = ( (SvxMacroItem&) rAttr ).aMacroTable;\n\n \/\/ Anzahl unterschiedlich => auf jeden Fall ungleich\n if ( rOwn.Count() != rOther.Count() )\n return FALSE;\n\n \/\/ einzeln verleichen; wegen Performance ist die Reihenfolge wichtig\n for ( USHORT nNo = 0; nNo < rOwn.Count(); ++nNo )\n {\n const SvxMacro *pOwnMac = rOwn.GetObject(nNo);\n const SvxMacro *pOtherMac = rOther.GetObject(nNo);\n if ( rOwn.GetKey(pOwnMac) != rOther.GetKey(pOtherMac) ||\n pOwnMac->GetLibName() != pOtherMac->GetLibName() ||\n pOwnMac->GetMacName() != pOtherMac->GetMacName() )\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxMacroItem::Clone( SfxItemPool* ) const\n{\n return new SvxMacroItem( *this );\n}\n\n\/\/------------------------------------------------------------------------\n\nSfxItemPresentation SvxMacroItem::GetPresentation\n(\n SfxItemPresentation \/*ePres*\/,\n SfxMapUnit \/*eCoreUnit*\/,\n SfxMapUnit \/*ePresUnit*\/,\n XubString& rText,\n const IntlWrapper *\n) const\n{\n\/*!!!\n SvxMacroTableDtor& rTbl = (SvxMacroTableDtor&)GetMacroTable();\n SvxMacro* pMac = rTbl.First();\n\n while ( pMac )\n {\n rText += pMac->GetLibName();\n rText += cpDelim;\n rText += pMac->GetMacName();\n pMac = rTbl.Next();\n if ( pMac )\n rText += cpDelim;\n }\n*\/\n rText.Erase();\n return SFX_ITEM_PRESENTATION_NONE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvStream& SvxMacroItem::Store( SvStream& rStrm , USHORT ) const\n{\n return aMacroTable.Write( rStrm );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxMacroItem::Create( SvStream& rStrm, USHORT nVersion ) const\n{\n SvxMacroItem* pAttr = new SvxMacroItem( Which() );\n pAttr->aMacroTable.Read( rStrm, nVersion );\n return pAttr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxMacroItem::SetMacro( USHORT nEvent, const SvxMacro& rMacro )\n{\n SvxMacro *pMacro;\n if ( 0 != (pMacro=aMacroTable.Get(nEvent)) )\n {\n delete pMacro;\n aMacroTable.Replace(nEvent, new SvxMacro( rMacro ) );\n }\n else\n aMacroTable.Insert(nEvent, new SvxMacro( rMacro ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SvxMacroItem::GetVersion( USHORT nFileFormatVersion ) const\n{\n return SOFFICE_FILEFORMAT_31 == nFileFormatVersion\n ? 0 : aMacroTable.GetVersion();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cuiimapwnd.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 14:36:20 $\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_svx.hxx\"\n\n#ifdef SVX_DLLIMPLEMENTATION\n#undef SVX_DLLIMPLEMENTATION\n#endif\n\n#ifndef _URLOBJ_HXX \/\/autogen\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SV_HELP_HXX \/\/autogen\n#include <vcl\/help.hxx>\n#endif\n\n#ifndef _SFXSIDS_HRC\n#include <sfx2\/sfxsids.hrc> \/\/ SID_ATTR_MACROITEM\n#endif\n#define _ANIMATION\n\n#ifndef _MACROPG_HXX \/\/autogen\n#include <sfx2\/macropg.hxx>\n#endif\n#ifndef _GOODIES_IMAPRECT_HXX \/\/autogen\n#include <svtools\/imaprect.hxx>\n#endif\n#ifndef _GOODIES_IMAPCIRC_HXX \/\/autogen\n#include <svtools\/imapcirc.hxx>\n#endif\n#ifndef _GOODIES_IMAPPOLY_HXX \/\/autogen\n#include <svtools\/imappoly.hxx>\n#endif\n#ifndef _URLBMK_HXX \/\/autogen\n#include <svtools\/urlbmk.hxx>\n#endif\n\n#include <xoutbmp.hxx>\n#include <dialmgr.hxx>\n#include <dialogs.hrc>\n#include <svxids.hrc>\n#include <imapdlg.hrc>\n#include <imapwnd.hxx>\n#include \"svdpage.hxx\"\n#include \"svdorect.hxx\"\n#include \"svdocirc.hxx\"\n#include \"svdopath.hxx\"\n#include \"xfltrit.hxx\"\n#include \"svdpagv.hxx\"\n\n#ifndef SVTOOLS_URIHELPER_HXX\n#include <svtools\/urihelper.hxx>\n#endif\n#ifndef _SVX_FILLITEM_HXX \/\/autogen\n#include <xfillit.hxx>\n#endif\n#ifndef _SVX_XLINIIT_HXX \/\/autogen\n#include <xlineit.hxx>\n#endif\n\n#include <sot\/formats.hxx>\n\n#include \"cuiimapwnd.hxx\" \/\/CHINA001\n\n#ifdef MAC\n#define TRANSCOL Color( COL_LIGHTGRAY )\n#else\n#define TRANSCOL Color( COL_WHITE )\n#endif\n\n\/*************************************************************************\n|*\n|* URLDlg\n|*\n\\************************************************************************\/\n\nURLDlg::URLDlg( Window* pWindow, const String& rURL,\n const String& rDescription, const String& rTarget,\n const String& rName, TargetList& rTargetList ) :\n\n ModalDialog ( pWindow, SVX_RES( RID_SVXDLG_IMAPURL ) ),\n\n aFlURL ( this, SVX_RES( FL_URL ) ),\n aFtURL1 ( this, SVX_RES( FT_URL1 ) ),\n aEdtURL ( this, SVX_RES( EDT_URL ) ),\n aFtURLDescription ( this, SVX_RES( FT_URLDESCRIPTION ) ),\n aEdtURLDescription ( this, SVX_RES( EDT_URLDESCRIPTION ) ),\n aFtTarget ( this, SVX_RES( FT_TARGET ) ),\n aCbbTargets ( this, SVX_RES( CBB_TARGETS ) ),\n aFtName ( this, SVX_RES( FT_NAME ) ),\n aEdtName ( this, SVX_RES( EDT_NAME ) ),\n aBtnOk ( this, SVX_RES( BTN_OK ) ),\n aBtnCancel ( this, SVX_RES( BTN_CANCEL1 ) )\n\n{\n FreeResource();\n\n aEdtURL.SetText( rURL );\n aEdtURLDescription.SetText( rDescription );\n aEdtName.SetText( rName );\n\n for( String* pStr = rTargetList.First(); pStr; pStr = rTargetList.Next() )\n aCbbTargets.InsertEntry( *pStr );\n\n if( !rTarget.Len() )\n aCbbTargets.SetText( String::CreateFromAscii( \"_self\" ) );\n else\n aCbbTargets.SetText( rTarget );\n}\n<commit_msg>INTEGRATION: CWS impressalternativtext (1.8.6); FILE MERGED 2007\/05\/25 10:37:43 cl 1.8.6.2: #i68099# added description to ImageMapObj's 2007\/05\/24 13:38:17 cl 1.8.6.1: #i68099# added description to ImageMapObj's<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cuiimapwnd.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2007-06-26 13:49:48 $\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_svx.hxx\"\n\n#ifdef SVX_DLLIMPLEMENTATION\n#undef SVX_DLLIMPLEMENTATION\n#endif\n\n#ifndef _URLOBJ_HXX \/\/autogen\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SV_HELP_HXX \/\/autogen\n#include <vcl\/help.hxx>\n#endif\n\n#ifndef _SFXSIDS_HRC\n#include <sfx2\/sfxsids.hrc> \/\/ SID_ATTR_MACROITEM\n#endif\n#define _ANIMATION\n\n#ifndef _MACROPG_HXX \/\/autogen\n#include <sfx2\/macropg.hxx>\n#endif\n#ifndef _GOODIES_IMAPRECT_HXX \/\/autogen\n#include <svtools\/imaprect.hxx>\n#endif\n#ifndef _GOODIES_IMAPCIRC_HXX \/\/autogen\n#include <svtools\/imapcirc.hxx>\n#endif\n#ifndef _GOODIES_IMAPPOLY_HXX \/\/autogen\n#include <svtools\/imappoly.hxx>\n#endif\n#ifndef _URLBMK_HXX \/\/autogen\n#include <svtools\/urlbmk.hxx>\n#endif\n\n#include <xoutbmp.hxx>\n#include <dialmgr.hxx>\n#include <dialogs.hrc>\n#include <svxids.hrc>\n#include <imapdlg.hrc>\n#include <imapwnd.hxx>\n#include \"svdpage.hxx\"\n#include \"svdorect.hxx\"\n#include \"svdocirc.hxx\"\n#include \"svdopath.hxx\"\n#include \"xfltrit.hxx\"\n#include \"svdpagv.hxx\"\n\n#ifndef SVTOOLS_URIHELPER_HXX\n#include <svtools\/urihelper.hxx>\n#endif\n#ifndef _SVX_FILLITEM_HXX \/\/autogen\n#include <xfillit.hxx>\n#endif\n#ifndef _SVX_XLINIIT_HXX \/\/autogen\n#include <xlineit.hxx>\n#endif\n\n#include <sot\/formats.hxx>\n\n#include \"cuiimapwnd.hxx\" \/\/CHINA001\n\n#ifdef MAC\n#define TRANSCOL Color( COL_LIGHTGRAY )\n#else\n#define TRANSCOL Color( COL_WHITE )\n#endif\n\n\/*************************************************************************\n|*\n|* URLDlg\n|*\n\\************************************************************************\/\n\nURLDlg::URLDlg( Window* pWindow, const String& rURL, const String& rAlternativeText, const String& rDescription, const String& rTarget, const String& rName, TargetList& rTargetList )\n: ModalDialog( pWindow, SVX_RES( RID_SVXDLG_IMAPURL ) )\n, maFtURL( this, SVX_RES( FT_URL1 ) )\n, maEdtURL( this, SVX_RES( EDT_URL ) )\n, maFtTarget( this, SVX_RES( FT_TARGET ) )\n, maCbbTargets( this, SVX_RES( CBB_TARGETS ) )\n, maFtName( this, SVX_RES( FT_NAME ) )\n, maEdtName( this, SVX_RES( EDT_NAME ) )\n, maFtAlternativeText( this, SVX_RES( FT_URLDESCRIPTION ) )\n, maEdtAlternativeText( this, SVX_RES( EDT_URLDESCRIPTION ) )\n, maFtDescription( this, SVX_RES( FT_DESCRIPTION ) )\n, maEdtDescription( this, SVX_RES( EDT_DESCRIPTION ) )\n, maFlURL( this, SVX_RES( FL_URL ) )\n, maBtnHelp( this, SVX_RES( BTN_HELP1 ) )\n, maBtnOk( this, SVX_RES( BTN_OK1 ) )\n, maBtnCancel( this, SVX_RES( BTN_CANCEL1 ) )\n{\n FreeResource();\n\n maEdtURL.SetText( rURL );\n maEdtAlternativeText.SetText( rAlternativeText );\n maEdtDescription.SetText( rDescription );\n maEdtName.SetText( rName );\n\n for( String* pStr = rTargetList.First(); pStr; pStr = rTargetList.Next() )\n maCbbTargets.InsertEntry( *pStr );\n\n if( !rTarget.Len() )\n maCbbTargets.SetText( String::CreateFromAscii( \"_self\" ) );\n else\n maCbbTargets.SetText( rTarget );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\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: shapeimpl.hxx,v $\n * $Revision: 1.9 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_SHAPEIMPL_HXX\n#define _SVX_SHAPEIMPL_HXX\n\n#include <svx\/unoshape.hxx>\n\nclass SvGlobalName;\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxShapeCaption : public SvxShapeText\n{\npublic:\n SvxShapeCaption( SdrObject* pObj ) throw();\n virtual ~SvxShapeCaption() throw();\n};\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxOle2Shape : public SvxShape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n void resetModifiedState();\n\n const SvGlobalName GetClassName_Impl(rtl::OUString& rHexCLSID);\n\npublic:\n SvxOle2Shape( SdrObject* pObj ) throw();\n SvxOle2Shape( SdrObject* pObject, const SfxItemPropertyMap* pPropertySet ) throw ();\n virtual ~SvxOle2Shape() throw();\n\n sal_Bool createObject( const SvGlobalName &aClassName );\n\n sal_Bool createLink( const ::rtl::OUString& aLinkURL );\n\n \/\/ XInterface\n virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n};\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxPluginShape : public SvxOle2Shape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\npublic:\n SvxPluginShape( SdrObject* pObj ) throw();\n virtual ~SvxPluginShape() throw();\n\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aValues ) throw (::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void Create( SdrObject* pNewOpj, SvxDrawPage* pNewPage = NULL ) throw ();\n};\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxAppletShape : public SvxOle2Shape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\npublic:\n SvxAppletShape( SdrObject* pObj ) throw();\n virtual ~SvxAppletShape() throw();\n\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aValues ) throw (::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void Create( SdrObject* pNewOpj, SvxDrawPage* pNewPage = NULL ) throw ();\n};\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxFrameShape : public SvxOle2Shape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\npublic:\n SvxFrameShape( SdrObject* pObj ) throw();\n virtual ~SvxFrameShape() throw();\n\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aValues ) throw (::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void Create( SdrObject* pNewOpj, SvxDrawPage* pNewPage = NULL ) throw ();\n};\n\n\n\/\/ ====================================================================\n\nclass SvxTableShape : public SvxShape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void lock();\n virtual void unlock();\n\npublic:\n\n SvxTableShape( SdrObject* pObj ) throw();\n virtual ~SvxTableShape() throw();\n};\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS rptchart02 (1.7.344); FILE MERGED 2008\/04\/16 06:35:49 oj 1.7.344.2: RESYNC: (1.7-1.9); FILE MERGED 2008\/04\/03 13:25:31 oj 1.7.344.1: impl XInplaceClient at lightclient<commit_after>\/*************************************************************************\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: shapeimpl.hxx,v $\n * $Revision: 1.10 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_SHAPEIMPL_HXX\n#define _SVX_SHAPEIMPL_HXX\n\n#include <svx\/unoshape.hxx>\n\nclass SvGlobalName;\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxShapeCaption : public SvxShapeText\n{\npublic:\n SvxShapeCaption( SdrObject* pObj ) throw();\n virtual ~SvxShapeCaption() throw();\n};\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxPluginShape : public SvxOle2Shape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\npublic:\n SvxPluginShape( SdrObject* pObj ) throw();\n virtual ~SvxPluginShape() throw();\n\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aValues ) throw (::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void Create( SdrObject* pNewOpj, SvxDrawPage* pNewPage = NULL ) throw ();\n};\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxAppletShape : public SvxOle2Shape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\npublic:\n SvxAppletShape( SdrObject* pObj ) throw();\n virtual ~SvxAppletShape() throw();\n\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aValues ) throw (::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void Create( SdrObject* pNewOpj, SvxDrawPage* pNewPage = NULL ) throw ();\n};\n\n\/***********************************************************************\n* *\n***********************************************************************\/\n\nclass SvxFrameShape : public SvxOle2Shape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\npublic:\n SvxFrameShape( SdrObject* pObj ) throw();\n virtual ~SvxFrameShape() throw();\n\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aValues ) throw (::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void Create( SdrObject* pNewOpj, SvxDrawPage* pNewPage = NULL ) throw ();\n};\n\n\n\/\/ ====================================================================\n\nclass SvxTableShape : public SvxShape\n{\nprotected:\n \/\/ overide these for special property handling in subcasses. Return true if property is handled\n virtual bool setPropertyValueImpl( const SfxItemPropertyMap* pProperty, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual bool getPropertyValueImpl( const SfxItemPropertyMap* pProperty, ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void lock();\n virtual void unlock();\n\npublic:\n\n SvxTableShape( SdrObject* pObj ) throw();\n virtual ~SvxTableShape() throw();\n};\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"b9\/compiler\/Compiler.hpp\"\n#include \"b9\/ExecutionContext.hpp\"\n#include \"b9\/VirtualMachine.hpp\"\n#include \"b9\/compiler\/GlobalTypes.hpp\"\n#include \"b9\/compiler\/MethodBuilder.hpp\"\n#include \"b9\/instructions.hpp\"\n\n#include <dlfcn.h>\n#include <cassert>\n#include <cerrno>\n#include <cstddef>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nnamespace b9 {\n\nGlobalTypes::GlobalTypes(TR::TypeDictionary &td) {\n\n \/\/ Core Integer Types\n\n addressPtr = td.PointerTo(TR::Address);\n int64Ptr = td.PointerTo(TR::Int64);\n int32Ptr = td.PointerTo(TR::Int32);\n int16Ptr = td.PointerTo(TR::Int16);\n\n \/\/ Basic VM Data\n\n stackElement = td.toIlType<OMR::Om::RawValue>();\n stackElementPtr = td.PointerTo(stackElement);\n\n instruction = td.toIlType<RawInstruction>();\n instructionPtr = td.PointerTo(instruction);\n\n \/\/ VM Structures\n\n auto os = \"b9::OperandStack\";\n operandStack = td.DefineStruct(os);\n td.DefineField(os, \"top_\", stackElementPtr, OperandStackOffset::TOP);\n td.DefineField(os, \"stack_\", stackElementPtr, OperandStackOffset::STACK);\n td.CloseStruct(os);\n\n operandStackPtr = td.PointerTo(operandStack);\n\n auto ec = \"b9::ExecutionContext\";\n executionContext = td.DefineStruct(ec);\n \/\/ td.DefineField(ec, \"omContext\", ???, ExecutionContextOffset::OM_CONTEXT);\n td.DefineField(ec, \"stack_\", operandStack, ExecutionContextOffset::STACK);\n \/\/ td.DefineField(ec, \"programCounter\", ???,\n \/\/ ExecutionContextOffset::PROGRAM_COUNTER);\n td.CloseStruct(ec);\n\n executionContextPtr = td.PointerTo(executionContext);\n}\n\nCompiler::Compiler(VirtualMachine &virtualMachine, const Config &cfg)\n : typeDictionary_(),\n globalTypes_(typeDictionary_),\n virtualMachine_(virtualMachine),\n cfg_(cfg) {}\n\nJitFunction Compiler::generateCode(const std::size_t functionIndex) {\n const FunctionDef *function = virtualMachine_.getFunction(functionIndex);\n MethodBuilder methodBuilder(virtualMachine_, functionIndex);\n\n if (cfg_.debug)\n std::cout << \"MethodBuilder for function: \" << function->name\n << \" is constructed\" << std::endl;\n\n uint8_t *result = nullptr;\n auto rc = compileMethodBuilder(&methodBuilder, &result);\n\n if (rc != 0) {\n std::cout << \"Failed to compile function: \" << function->name\n << \" nargs: \" << function->nargs << std::endl;\n throw b9::CompilationException{\"IL generation failed\"};\n }\n\n if (cfg_.debug)\n std::cout << \"Compilation completed with return code: \" << rc\n << \", code address: \" << static_cast<void *>(result) << std::endl;\n\n return (JitFunction)result;\n}\n\n} \/\/ namespace b9\n<commit_msg>Fix lazyvmstate<commit_after>#include \"b9\/compiler\/Compiler.hpp\"\n#include \"b9\/ExecutionContext.hpp\"\n#include \"b9\/VirtualMachine.hpp\"\n#include \"b9\/compiler\/GlobalTypes.hpp\"\n#include \"b9\/compiler\/MethodBuilder.hpp\"\n#include \"b9\/instructions.hpp\"\n\n#include <dlfcn.h>\n#include <cassert>\n#include <cerrno>\n#include <cstddef>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nnamespace b9 {\n\nGlobalTypes::GlobalTypes(TR::TypeDictionary &td) {\n\n \/\/ Core Integer Types\n\n addressPtr = td.PointerTo(TR::Address);\n int64Ptr = td.PointerTo(TR::Int64);\n int32Ptr = td.PointerTo(TR::Int32);\n int16Ptr = td.PointerTo(TR::Int16);\n\n \/\/ Basic VM Data\n\n stackElement = td.toIlType<OMR::Om::RawValue>();\n stackElementPtr = td.PointerTo(stackElement);\n\n instruction = td.toIlType<RawInstruction>();\n instructionPtr = td.PointerTo(instruction);\n\n \/\/ VM Structures\n\n auto os = \"b9::OperandStack\";\n operandStack = td.DefineStruct(os);\n td.DefineField(os, \"top_\", td.PointerTo(stackElementPtr), OperandStackOffset::TOP);\n td.DefineField(os, \"stack_\", stackElementPtr, OperandStackOffset::STACK);\n td.CloseStruct(os);\n\n operandStackPtr = td.PointerTo(operandStack);\n\n auto ec = \"b9::ExecutionContext\";\n executionContext = td.DefineStruct(ec);\n \/\/ td.DefineField(ec, \"omContext\", ???, ExecutionContextOffset::OM_CONTEXT);\n td.DefineField(ec, \"stack_\", operandStack, ExecutionContextOffset::STACK);\n \/\/ td.DefineField(ec, \"programCounter\", ???,\n \/\/ ExecutionContextOffset::PROGRAM_COUNTER);\n td.CloseStruct(ec);\n\n executionContextPtr = td.PointerTo(executionContext);\n}\n\nCompiler::Compiler(VirtualMachine &virtualMachine, const Config &cfg)\n : typeDictionary_(),\n globalTypes_(typeDictionary_),\n virtualMachine_(virtualMachine),\n cfg_(cfg) {}\n\nJitFunction Compiler::generateCode(const std::size_t functionIndex) {\n const FunctionDef *function = virtualMachine_.getFunction(functionIndex);\n MethodBuilder methodBuilder(virtualMachine_, functionIndex);\n\n if (cfg_.debug)\n std::cout << \"MethodBuilder for function: \" << function->name\n << \" is constructed\" << std::endl;\n\n uint8_t *result = nullptr;\n auto rc = compileMethodBuilder(&methodBuilder, &result);\n\n if (rc != 0) {\n std::cout << \"Failed to compile function: \" << function->name\n << \" nargs: \" << function->nargs << std::endl;\n throw b9::CompilationException{\"IL generation failed\"};\n }\n\n if (cfg_.debug)\n std::cout << \"Compilation completed with return code: \" << rc\n << \", code address: \" << static_cast<void *>(result) << std::endl;\n\n return (JitFunction)result;\n}\n\n} \/\/ namespace b9\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fldlst.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2003-06-30 15:51:01 $\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\n#pragma hdrstop\n\n#include \"editsh.hxx\"\n#include \"doc.hxx\"\n\n#ifndef _DOCARY_HXX\n#include <docary.hxx>\n#endif\n#ifndef _FMTFLD_HXX \/\/autogen\n#include <fmtfld.hxx>\n#endif\n#ifndef _TXTFLD_HXX \/\/autogen\n#include <txtfld.hxx>\n#endif\n#include \"edimp.hxx\"\n#include \"expfld.hxx\"\n#include \"pam.hxx\"\n#include \"docfld.hxx\"\n#include \"ndtxt.hxx\"\n\n\n\/*--------------------------------------------------------------------\n Beschreibung: Sortieren der Input-Eintraege\n --------------------------------------------------------------------*\/\n\nSwInputFieldList::SwInputFieldList( SwEditShell* pShell, FASTBOOL bBuildTmpLst )\n : pSh(pShell)\n{\n \/\/ Hier die Liste aller Eingabefelder sortiert erstellen\n pSrtLst = new _SetGetExpFlds();\n\n SwNodes* pNds = &pSh->GetDoc()->GetNodes();\n const SwFldTypes& rFldTypes = *pSh->GetDoc()->GetFldTypes();\n const USHORT nSize = rFldTypes.Count();\n\n \/\/ Alle Typen abklappern\n\n for(USHORT i=0; i < nSize; ++i)\n {\n SwFieldType* pFldType = (SwFieldType*)rFldTypes[ i ];\n USHORT nType = pFldType->Which();\n\n if( RES_SETEXPFLD == nType || RES_INPUTFLD == nType || RES_DROPDOWN == nType )\n {\n SwClientIter aIter( *pFldType );\n for( SwFmtFld* pFld = (SwFmtFld*)aIter.First( TYPE(SwFmtFld) );\n pFld; pFld = (SwFmtFld*)aIter.Next() )\n\n {\n const SwTxtFld* pTxtFld = pFld->GetTxtFld();\n\n \/\/ nur InputFields und interaktive SetExpFlds bearbeiten\n \/\/ and DropDown fields\n if( !pTxtFld || ( RES_SETEXPFLD == nType &&\n !((SwSetExpField*)pFld->GetFld())->GetInputFlag()))\n continue;\n\n const SwTxtNode& rTxtNode = pTxtFld->GetTxtNode();\n if( rTxtNode.GetNodes().IsDocNodes() )\n {\n if( bBuildTmpLst )\n {\n VoidPtr pTmp = (VoidPtr)pTxtFld;\n aTmpLst.Insert( pTmp, aTmpLst.Count() );\n }\n else\n {\n SwNodeIndex aIdx( rTxtNode );\n _SetGetExpFld* pNew = new _SetGetExpFld(aIdx, pTxtFld );\n pSrtLst->Insert( pNew );\n }\n }\n }\n }\n }\n}\n\nSwInputFieldList::~SwInputFieldList()\n{\n delete pSrtLst;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Felder aus der Liste in sortierter Reihenfolge\n --------------------------------------------------------------------*\/\n\nUSHORT SwInputFieldList::Count() const\n{\n return pSrtLst->Count();\n}\n\n\nSwField* SwInputFieldList::GetField(USHORT nId)\n{\n const SwTxtFld* pTxtFld = (*pSrtLst)[ nId ]->GetFld();\n ASSERT( pTxtFld, \"kein TextFld\" );\n return (SwField*)pTxtFld->GetFld().GetFld();\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Cursor sichern\n --------------------------------------------------------------------*\/\n\nvoid SwInputFieldList::PushCrsr()\n{\n pSh->Push();\n pSh->ClearMark();\n}\n\nvoid SwInputFieldList::PopCrsr()\n{\n pSh->Pop(FALSE);\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Position eines Feldes ansteuern\n --------------------------------------------------------------------*\/\n\nvoid SwInputFieldList::GotoFieldPos(USHORT nId)\n{\n pSh->StartAllAction();\n (*pSrtLst)[ nId ]->GetPosOfContent( *pSh->GetCrsr()->GetPoint() );\n pSh->EndAllAction();\n}\n\n \/\/ vergleiche TmpLst mit akt Feldern. Alle neue kommen in die SortLst\n \/\/ damit sie geupdatet werden koennen. Returnt die Anzahl.\n \/\/ (Fuer Textbausteine: nur seine Input-Felder aktualisieren)\nUSHORT SwInputFieldList::BuildSortLst()\n{\n SwNodes* pNds = &pSh->GetDoc()->GetNodes();\n const SwFldTypes& rFldTypes = *pSh->GetDoc()->GetFldTypes();\n USHORT nSize = rFldTypes.Count();\n\n \/\/ Alle Typen abklappern\n\n for( USHORT i = 0; i < nSize; ++i )\n {\n SwFieldType* pFldType = (SwFieldType*)rFldTypes[ i ];\n USHORT nType = pFldType->Which();\n\n if( RES_SETEXPFLD == nType || RES_INPUTFLD == nType )\n {\n SwClientIter aIter( *pFldType );\n for( SwFmtFld* pFld = (SwFmtFld*)aIter.First( TYPE(SwFmtFld) );\n pFld; pFld = (SwFmtFld*)aIter.Next() )\n {\n const SwTxtFld* pTxtFld = pFld->GetTxtFld();\n\n \/\/ nur InputFields und interaktive SetExpFlds bearbeiten\n if( !pTxtFld || ( RES_SETEXPFLD == nType &&\n !((SwSetExpField*)pFld->GetFld())->GetInputFlag()))\n continue;\n\n const SwTxtNode& rTxtNode = pTxtFld->GetTxtNode();\n if( rTxtNode.GetNodes().IsDocNodes() )\n {\n VoidPtr pTmp = (VoidPtr)pTxtFld;\n \/\/ nicht in der TempListe vorhanden, also in die SortListe\n \/\/ aufnehemen\n USHORT nFndPos = aTmpLst.GetPos( pTmp );\n if( USHRT_MAX == nFndPos )\n {\n SwNodeIndex aIdx( rTxtNode );\n _SetGetExpFld* pNew = new _SetGetExpFld(aIdx, pTxtFld );\n pSrtLst->Insert( pNew );\n }\n else\n aTmpLst.Remove( nFndPos );\n }\n }\n }\n }\n\n \/\/ die Pointer werden nicht mehr gebraucht\n aTmpLst.Remove( 0, aTmpLst.Count() );\n return pSrtLst->Count();\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Alle Felder auerhalb von Selektionen aus Liste entfernen\n --------------------------------------------------------------------*\/\n\nvoid SwInputFieldList::RemoveUnselectedFlds()\n{\n _SetGetExpFlds* pNewLst = new _SetGetExpFlds();\n\n FOREACHPAM_START(pSh)\n {\n for (USHORT i = 0; i < Count();)\n {\n _SetGetExpFld* pFld = (*pSrtLst)[i];\n SwPosition aPos(*PCURCRSR->GetPoint());\n\n pFld->GetPos( aPos );\n\n if (aPos >= *PCURCRSR->Start() && aPos < *PCURCRSR->End())\n {\n \/\/ Feld innerhalb der Selektion\n pNewLst->Insert( (*pSrtLst)[i] );\n pSrtLst->Remove(i, 1);\n }\n else\n i++;\n }\n }\n FOREACHPAM_END()\n\n delete pSrtLst;\n pSrtLst = pNewLst;\n}\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.1174); FILE MERGED 2005\/09\/05 13:39:41 rt 1.3.1174.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fldlst.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 03:34:33 $\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\n#pragma hdrstop\n\n#include \"editsh.hxx\"\n#include \"doc.hxx\"\n\n#ifndef _DOCARY_HXX\n#include <docary.hxx>\n#endif\n#ifndef _FMTFLD_HXX \/\/autogen\n#include <fmtfld.hxx>\n#endif\n#ifndef _TXTFLD_HXX \/\/autogen\n#include <txtfld.hxx>\n#endif\n#include \"edimp.hxx\"\n#include \"expfld.hxx\"\n#include \"pam.hxx\"\n#include \"docfld.hxx\"\n#include \"ndtxt.hxx\"\n\n\n\/*--------------------------------------------------------------------\n Beschreibung: Sortieren der Input-Eintraege\n --------------------------------------------------------------------*\/\n\nSwInputFieldList::SwInputFieldList( SwEditShell* pShell, FASTBOOL bBuildTmpLst )\n : pSh(pShell)\n{\n \/\/ Hier die Liste aller Eingabefelder sortiert erstellen\n pSrtLst = new _SetGetExpFlds();\n\n SwNodes* pNds = &pSh->GetDoc()->GetNodes();\n const SwFldTypes& rFldTypes = *pSh->GetDoc()->GetFldTypes();\n const USHORT nSize = rFldTypes.Count();\n\n \/\/ Alle Typen abklappern\n\n for(USHORT i=0; i < nSize; ++i)\n {\n SwFieldType* pFldType = (SwFieldType*)rFldTypes[ i ];\n USHORT nType = pFldType->Which();\n\n if( RES_SETEXPFLD == nType || RES_INPUTFLD == nType || RES_DROPDOWN == nType )\n {\n SwClientIter aIter( *pFldType );\n for( SwFmtFld* pFld = (SwFmtFld*)aIter.First( TYPE(SwFmtFld) );\n pFld; pFld = (SwFmtFld*)aIter.Next() )\n\n {\n const SwTxtFld* pTxtFld = pFld->GetTxtFld();\n\n \/\/ nur InputFields und interaktive SetExpFlds bearbeiten\n \/\/ and DropDown fields\n if( !pTxtFld || ( RES_SETEXPFLD == nType &&\n !((SwSetExpField*)pFld->GetFld())->GetInputFlag()))\n continue;\n\n const SwTxtNode& rTxtNode = pTxtFld->GetTxtNode();\n if( rTxtNode.GetNodes().IsDocNodes() )\n {\n if( bBuildTmpLst )\n {\n VoidPtr pTmp = (VoidPtr)pTxtFld;\n aTmpLst.Insert( pTmp, aTmpLst.Count() );\n }\n else\n {\n SwNodeIndex aIdx( rTxtNode );\n _SetGetExpFld* pNew = new _SetGetExpFld(aIdx, pTxtFld );\n pSrtLst->Insert( pNew );\n }\n }\n }\n }\n }\n}\n\nSwInputFieldList::~SwInputFieldList()\n{\n delete pSrtLst;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Felder aus der Liste in sortierter Reihenfolge\n --------------------------------------------------------------------*\/\n\nUSHORT SwInputFieldList::Count() const\n{\n return pSrtLst->Count();\n}\n\n\nSwField* SwInputFieldList::GetField(USHORT nId)\n{\n const SwTxtFld* pTxtFld = (*pSrtLst)[ nId ]->GetFld();\n ASSERT( pTxtFld, \"kein TextFld\" );\n return (SwField*)pTxtFld->GetFld().GetFld();\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Cursor sichern\n --------------------------------------------------------------------*\/\n\nvoid SwInputFieldList::PushCrsr()\n{\n pSh->Push();\n pSh->ClearMark();\n}\n\nvoid SwInputFieldList::PopCrsr()\n{\n pSh->Pop(FALSE);\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Position eines Feldes ansteuern\n --------------------------------------------------------------------*\/\n\nvoid SwInputFieldList::GotoFieldPos(USHORT nId)\n{\n pSh->StartAllAction();\n (*pSrtLst)[ nId ]->GetPosOfContent( *pSh->GetCrsr()->GetPoint() );\n pSh->EndAllAction();\n}\n\n \/\/ vergleiche TmpLst mit akt Feldern. Alle neue kommen in die SortLst\n \/\/ damit sie geupdatet werden koennen. Returnt die Anzahl.\n \/\/ (Fuer Textbausteine: nur seine Input-Felder aktualisieren)\nUSHORT SwInputFieldList::BuildSortLst()\n{\n SwNodes* pNds = &pSh->GetDoc()->GetNodes();\n const SwFldTypes& rFldTypes = *pSh->GetDoc()->GetFldTypes();\n USHORT nSize = rFldTypes.Count();\n\n \/\/ Alle Typen abklappern\n\n for( USHORT i = 0; i < nSize; ++i )\n {\n SwFieldType* pFldType = (SwFieldType*)rFldTypes[ i ];\n USHORT nType = pFldType->Which();\n\n if( RES_SETEXPFLD == nType || RES_INPUTFLD == nType )\n {\n SwClientIter aIter( *pFldType );\n for( SwFmtFld* pFld = (SwFmtFld*)aIter.First( TYPE(SwFmtFld) );\n pFld; pFld = (SwFmtFld*)aIter.Next() )\n {\n const SwTxtFld* pTxtFld = pFld->GetTxtFld();\n\n \/\/ nur InputFields und interaktive SetExpFlds bearbeiten\n if( !pTxtFld || ( RES_SETEXPFLD == nType &&\n !((SwSetExpField*)pFld->GetFld())->GetInputFlag()))\n continue;\n\n const SwTxtNode& rTxtNode = pTxtFld->GetTxtNode();\n if( rTxtNode.GetNodes().IsDocNodes() )\n {\n VoidPtr pTmp = (VoidPtr)pTxtFld;\n \/\/ nicht in der TempListe vorhanden, also in die SortListe\n \/\/ aufnehemen\n USHORT nFndPos = aTmpLst.GetPos( pTmp );\n if( USHRT_MAX == nFndPos )\n {\n SwNodeIndex aIdx( rTxtNode );\n _SetGetExpFld* pNew = new _SetGetExpFld(aIdx, pTxtFld );\n pSrtLst->Insert( pNew );\n }\n else\n aTmpLst.Remove( nFndPos );\n }\n }\n }\n }\n\n \/\/ die Pointer werden nicht mehr gebraucht\n aTmpLst.Remove( 0, aTmpLst.Count() );\n return pSrtLst->Count();\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Alle Felder auerhalb von Selektionen aus Liste entfernen\n --------------------------------------------------------------------*\/\n\nvoid SwInputFieldList::RemoveUnselectedFlds()\n{\n _SetGetExpFlds* pNewLst = new _SetGetExpFlds();\n\n FOREACHPAM_START(pSh)\n {\n for (USHORT i = 0; i < Count();)\n {\n _SetGetExpFld* pFld = (*pSrtLst)[i];\n SwPosition aPos(*PCURCRSR->GetPoint());\n\n pFld->GetPos( aPos );\n\n if (aPos >= *PCURCRSR->Start() && aPos < *PCURCRSR->End())\n {\n \/\/ Feld innerhalb der Selektion\n pNewLst->Insert( (*pSrtLst)[i] );\n pSrtLst->Remove(i, 1);\n }\n else\n i++;\n }\n }\n FOREACHPAM_END()\n\n delete pSrtLst;\n pSrtLst = pNewLst;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>sw: redo check in SwFEShell::FindAnchorPos() a bit (related: fdo#87760)<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>WaE: -Wunused-variable<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>don't crash on layout of ooo55381-1.sxw<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#735657 Division or modulo by float zero<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>WaE: unsafe mix of type 'bool' and type 'sal_Bool' in operation<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>remove pointless forward moving of a table (bnc#706138)<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>fdo#79602: sw: fix text formatting of proportional line space < 100%<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#705747: Resource leak<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#1078451 Unchecked return value<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlfmte.cxx,v $\n *\n * $Revision: 1.46 $\n *\n * last change: $Author: rt $ $Date: 2006-12-01 15:58: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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_\n#include <com\/sun\/star\/text\/XTextDocument.hpp>\n#endif\n\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _XMLOFF_ATTRLIST_HXX\n#include <xmloff\/attrlist.hxx>\n#endif\n#ifndef _XMLITMPR_HXX\n#include \"xmlexpit.hxx\"\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLTEXTLISTAUTOSTYLEPOOL_HXX\n#include <xmloff\/XMLTextListAutoStylePool.hxx>\n#endif\n#ifndef _XMLOFF_XMLTEXTMASTERPAGEEXPORT\n#include <xmloff\/XMLTextMasterPageExport.hxx>\n#endif\n\n#ifndef _XMLOFF_TXTPRMAP_HXX\n#include <xmloff\/txtprmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLASTPLP_HXX\n#include <xmloff\/xmlaustp.hxx>\n#endif\n#ifndef _XMLOFF_FAMILIES_HXX_\n#include <xmloff\/families.hxx>\n#endif\n#ifndef _XMLOFF_PROGRESSBARHELPER_HXX\n#include <xmloff\/ProgressBarHelper.hxx>\n#endif\n\n#ifndef _FORMAT_HXX \/\/autogen wg. SwFmt\n#include <format.hxx>\n#endif\n#ifndef _FMTPDSC_HXX\n#include <fmtpdsc.hxx>\n#endif\n#ifndef _PAGEDESC_HXX\n#include <pagedesc.hxx>\n#endif\n#ifndef _UNOSTYLE_HXX\n#include <unostyle.hxx>\n#endif\n#ifndef _CELLATR_HXX\n#include <cellatr.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESUPPLIER_HPP_\n#include <com\/sun\/star\/drawing\/XDrawPageSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n#ifndef _SWSTYLENAMEMAPPER_HXX\n#include <SwStyleNameMapper.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::text;\nusing namespace ::com::sun::star::drawing;\nusing namespace ::com::sun::star::lang;\nusing namespace ::xmloff::token;\n\nvoid SwXMLExport::ExportFmt( const SwFmt& rFmt, enum XMLTokenEnum eFamily )\n{\n \/\/ <style:style ...>\n CheckAttrList();\n\n \/\/ style:family=\"...\"\n DBG_ASSERT( RES_FRMFMT==rFmt.Which(), \"frame format expected\" );\n if( RES_FRMFMT != rFmt.Which() )\n return;\n DBG_ASSERT( eFamily != XML_TOKEN_INVALID, \"family must be specified\" );\n \/\/ style:name=\"...\"\n sal_Bool bEncoded = sal_False;\n AddAttribute( XML_NAMESPACE_STYLE, XML_NAME, EncodeStyleName(\n rFmt.GetName(), &bEncoded ) );\n if( bEncoded )\n AddAttribute( XML_NAMESPACE_STYLE, XML_DISPLAY_NAME, rFmt.GetName() );\n\n\n if( eFamily != XML_TOKEN_INVALID )\n AddAttribute( XML_NAMESPACE_STYLE, XML_FAMILY, eFamily );\n\n \/\/ style:parent-style-name=\"...\" (if its not the default only)\n const SwFmt* pParent = rFmt.DerivedFrom();\n \/\/ Parent-Namen nur uebernehmen, wenn kein Default\n ASSERT( !pParent || pParent->IsDefault(), \"unexpected parent\" );\n\n ASSERT( USHRT_MAX == rFmt.GetPoolFmtId(), \"pool ids arent'supported\" );\n ASSERT( USHRT_MAX == rFmt.GetPoolHelpId(), \"help ids arent'supported\" );\n ASSERT( USHRT_MAX == rFmt.GetPoolHelpId() ||\n UCHAR_MAX == rFmt.GetPoolHlpFileId(), \"help file ids aren't supported\" );\n\n \/\/ style:master-page-name\n if( RES_FRMFMT == rFmt.Which() && XML_TABLE == eFamily )\n {\n const SfxPoolItem *pItem;\n if( SFX_ITEM_SET == rFmt.GetAttrSet().GetItemState( RES_PAGEDESC,\n sal_False, &pItem ) )\n {\n String sName;\n const SwPageDesc *pPageDesc =\n ((const SwFmtPageDesc *)pItem)->GetPageDesc();\n if( pPageDesc )\n SwStyleNameMapper::FillProgName(\n pPageDesc->GetName(),\n sName,\n GET_POOLID_PAGEDESC,\n sal_True);\n AddAttribute( XML_NAMESPACE_STYLE, XML_MASTER_PAGE_NAME,\n EncodeStyleName( sName ) );\n }\n }\n\n if( XML_TABLE_CELL == eFamily )\n {\n DBG_ASSERT(RES_FRMFMT == rFmt.Which(), \"only frame format\");\n\n const SfxPoolItem *pItem;\n if( SFX_ITEM_SET ==\n rFmt.GetAttrSet().GetItemState( RES_BOXATR_FORMAT,\n sal_False, &pItem ) )\n {\n sal_Int32 nFormat = (sal_Int32)\n ((const SwTblBoxNumFormat *)pItem)->GetValue();\n\n if ( (nFormat != -1) && (nFormat != NUMBERFORMAT_TEXT) )\n {\n \/\/ if we have a format, register and then export\n \/\/ (Careful: here we assume that data styles will be\n \/\/ written after cell styles)\n addDataStyle(nFormat);\n OUString sDataStyleName = getDataStyleName(nFormat);\n if( sDataStyleName.getLength() > 0 )\n AddAttribute( XML_NAMESPACE_STYLE, XML_DATA_STYLE_NAME,\n sDataStyleName );\n }\n }\n }\n\n {\n SvXMLElementExport aElem( *this, XML_NAMESPACE_STYLE, XML_STYLE,\n sal_True, sal_True );\n\n SvXMLItemMapEntriesRef xItemMap;\n XMLTokenEnum ePropToken = XML_TABLE_PROPERTIES;\n if( XML_TABLE == eFamily )\n {\n xItemMap = xTableItemMap;\n }\n else if( XML_TABLE_ROW == eFamily )\n {\n xItemMap = xTableRowItemMap;\n ePropToken = XML_TABLE_ROW_PROPERTIES;\n }\n else if( XML_TABLE_CELL == eFamily )\n {\n xItemMap = xTableCellItemMap;\n ePropToken = XML_TABLE_CELL_PROPERTIES;\n }\n\n if( xItemMap.Is() )\n {\n SvXMLExportItemMapper& rItemMapper = GetTableItemMapper();\n rItemMapper.setMapEntries( xItemMap );\n\n GetTableItemMapper().exportXML( *this,\n rFmt.GetAttrSet(),\n GetTwipUnitConverter(),\n ePropToken,\n XML_EXPORT_FLAG_IGN_WS );\n }\n }\n}\n\n\nvoid SwXMLExport::_ExportStyles( sal_Bool bUsed )\n{\n SvXMLExport::_ExportStyles( bUsed );\n\n \/\/ drawing defaults\n GetShapeExport()->ExportGraphicDefaults();\n\n#if SUPD <628 && !defined(TEST_MIB)\n GetTextParagraphExport()->SetProgress( IsShowProgress() ? 1 : 0 );\n#endif\n GetTextParagraphExport()->exportTextStyles( bUsed\n#if SUPD >627 || defined(TEST_MIB)\n ,IsShowProgress()\n#endif\n );\n#if SUPD <628 && !defined(TEST_MIB)\n GetTextParagraphExport()->SetProgress( 0 );\n#endif\n}\n\nvoid SwXMLExport::_ExportAutoStyles()\n{\n \/\/ The order in which styles are collected *MUST* be the same as\n \/\/ the order in which they are exported. Otherwise, caching will\n \/\/ fail.\n\n if( (getExportFlags() & (EXPORT_MASTERSTYLES|EXPORT_CONTENT)) != 0 )\n {\n if( (getExportFlags() & EXPORT_CONTENT) == 0 )\n {\n \/\/ only master pages are exported => styles for frames bound\n \/\/ to frames (but none for frames bound to pages) need to be\n \/\/ collected.\n GetTextParagraphExport()->collectFramesBoundToFrameAutoStyles();\n }\n else\n {\n \/\/ content (and optional master pages) are exported => styles\n \/\/ for frames bound to frame or to pages need to be\n \/\/ collected.\n GetTextParagraphExport()->collectFramesBoundToPageOrFrameAutoStyles(\n bShowProgress );\n }\n\n }\n\n \/\/ exported in _ExportMasterStyles\n if( (getExportFlags() & EXPORT_MASTERSTYLES) != 0 )\n GetPageExport()->collectAutoStyles( sal_False );\n\n \/\/ if we don't export styles (i.e. in content stream only, but not\n \/\/ in single-stream case), then we can save ourselves a bit of\n \/\/ work and memory by not collecting field masters\n if( (getExportFlags() & EXPORT_STYLES ) == 0 )\n GetTextParagraphExport()->exportUsedDeclarations( sal_False );\n\n \/\/ exported in _ExportContent\n if( (getExportFlags() & EXPORT_CONTENT) != 0 )\n {\n GetTextParagraphExport()->exportTrackedChanges( sal_True );\n Reference < XTextDocument > xTextDoc( GetModel(), UNO_QUERY );\n Reference < XText > xText = xTextDoc->getText();\n\n \/\/ collect form autostyle\n \/\/ (do this before collectTextAutoStyles, 'cause the shapes need the results of the work\n \/\/ done by examineForms)\n Reference<XDrawPageSupplier> xDrawPageSupplier( GetModel(), UNO_QUERY );\n if (xDrawPageSupplier.is() && GetFormExport().is())\n {\n Reference<XDrawPage> xPage = xDrawPageSupplier->getDrawPage();\n if (xPage.is())\n GetFormExport()->examineForms(xPage);\n }\n\n GetTextParagraphExport()->collectTextAutoStylesOptimized( bShowProgress );\n \/\/GetTextParagraphExport()->collectTextAutoStyles( xText, bShowProgress, sal_True, bPortions );\n }\n\n GetTextParagraphExport()->exportTextAutoStyles();\n GetShapeExport()->exportAutoStyles();\n if( (getExportFlags() & EXPORT_MASTERSTYLES) != 0 )\n GetPageExport()->exportAutoStyles();\n\n \/\/ we rely on data styles being written after cell styles in the\n \/\/ ExportFmt() method; so be careful when changing order.\n exportAutoDataStyles();\n\n sal_uInt16 nContentAutostyles = EXPORT_CONTENT | EXPORT_AUTOSTYLES;\n if ( ( getExportFlags() & nContentAutostyles ) == nContentAutostyles )\n GetFormExport()->exportAutoStyles();\n}\n\nXMLPageExport* SwXMLExport::CreatePageExport()\n{\n return new XMLTextMasterPageExport( *this );\n}\n\nvoid SwXMLExport::_ExportMasterStyles()\n{\n \/\/ export master styles\n GetPageExport()->exportMasterStyles( sal_False );\n}\n\n\/\/ ---------------------------------------------------------------------\nclass SwXMLAutoStylePoolP : public SvXMLAutoStylePoolP\n{\n SvXMLExport& rExport;\n const OUString sListStyleName;\n const OUString sMasterPageName;\n const OUString sCDATA;\n\nprotected:\n\n virtual void exportStyleAttributes(\n SvXMLAttributeList& rAttrList,\n sal_Int32 nFamily,\n const ::std::vector< XMLPropertyState >& rProperties,\n const SvXMLExportPropertyMapper& rPropExp\n , const SvXMLUnitConverter& rUnitConverter,\n const SvXMLNamespaceMap& rNamespaceMap\n ) const;\npublic:\n\n SwXMLAutoStylePoolP( SvXMLExport& rExport );\n virtual ~SwXMLAutoStylePoolP();\n};\n\nvoid SwXMLAutoStylePoolP::exportStyleAttributes(\n SvXMLAttributeList& rAttrList,\n sal_Int32 nFamily,\n const ::std::vector< XMLPropertyState >& rProperties,\n const SvXMLExportPropertyMapper& rPropExp\n , const SvXMLUnitConverter& rUnitConverter,\n const SvXMLNamespaceMap& rNamespaceMap\n ) const\n{\n SvXMLAutoStylePoolP::exportStyleAttributes( rAttrList, nFamily, rProperties, rPropExp, rUnitConverter, rNamespaceMap);\n\n if( XML_STYLE_FAMILY_TEXT_PARAGRAPH == nFamily )\n {\n for( ::std::vector< XMLPropertyState >::const_iterator\n aProperty = rProperties.begin();\n aProperty != rProperties.end();\n aProperty++ )\n {\n if (aProperty->mnIndex != -1) \/\/ #i26762#\n {\n switch( rPropExp.getPropertySetMapper()->\n GetEntryContextId( aProperty->mnIndex ) )\n {\n case CTF_NUMBERINGSTYLENAME:\n {\n OUString sStyleName;\n aProperty->maValue >>= sStyleName;\n if( sStyleName.getLength() )\n {\n OUString sTmp = rExport.GetTextParagraphExport()->GetListAutoStylePool().Find( sStyleName );\n if( sTmp.getLength() )\n sStyleName = sTmp;\n GetExport().AddAttribute( XML_NAMESPACE_STYLE,\n sListStyleName,\n GetExport().EncodeStyleName( sStyleName ) );\n }\n }\n break;\n case CTF_PAGEDESCNAME:\n {\n OUString sStyleName;\n aProperty->maValue >>= sStyleName;\n GetExport().AddAttribute( XML_NAMESPACE_STYLE,\n sMasterPageName,\n GetExport().EncodeStyleName( sStyleName ) );\n }\n break;\n }\n }\n }\n }\n}\n\nSwXMLAutoStylePoolP::SwXMLAutoStylePoolP(SvXMLExport& rExp ) :\n SvXMLAutoStylePoolP( rExp ),\n rExport( rExp ),\n sListStyleName( GetXMLToken( XML_LIST_STYLE_NAME ) ),\n sMasterPageName( GetXMLToken( XML_MASTER_PAGE_NAME ) ),\n sCDATA( GetXMLToken( XML_CDATA ) )\n{\n}\n\n\nSwXMLAutoStylePoolP::~SwXMLAutoStylePoolP()\n{\n}\n\nSvXMLAutoStylePoolP* SwXMLExport::CreateAutoStylePool()\n{\n return new SwXMLAutoStylePoolP( *this );\n}\n<commit_msg>INTEGRATION: CWS swwarnings (1.46.130); FILE MERGED 2007\/04\/11 07:03:11 tl 1.46.130.3: #i69287# warning-free code 2007\/03\/15 15:52:25 tl 1.46.130.2: #i69287# warning-free code 2007\/03\/09 14:34:51 ama 1.46.130.1: #i69287#: warning free code<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlfmte.cxx,v $\n *\n * $Revision: 1.47 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 10:10:47 $\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_sw.hxx\"\n\n\n#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_\n#include <com\/sun\/star\/text\/XTextDocument.hpp>\n#endif\n\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _XMLOFF_ATTRLIST_HXX\n#include <xmloff\/attrlist.hxx>\n#endif\n#ifndef _XMLITMPR_HXX\n#include \"xmlexpit.hxx\"\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLTEXTLISTAUTOSTYLEPOOL_HXX\n#include <xmloff\/XMLTextListAutoStylePool.hxx>\n#endif\n#ifndef _XMLOFF_XMLTEXTMASTERPAGEEXPORT\n#include <xmloff\/XMLTextMasterPageExport.hxx>\n#endif\n\n#ifndef _XMLOFF_TXTPRMAP_HXX\n#include <xmloff\/txtprmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLASTPLP_HXX\n#include <xmloff\/xmlaustp.hxx>\n#endif\n#ifndef _XMLOFF_FAMILIES_HXX_\n#include <xmloff\/families.hxx>\n#endif\n#ifndef _XMLOFF_PROGRESSBARHELPER_HXX\n#include <xmloff\/ProgressBarHelper.hxx>\n#endif\n\n#ifndef _FORMAT_HXX \/\/autogen wg. SwFmt\n#include <format.hxx>\n#endif\n#ifndef _FMTPDSC_HXX\n#include <fmtpdsc.hxx>\n#endif\n#ifndef _PAGEDESC_HXX\n#include <pagedesc.hxx>\n#endif\n#ifndef _UNOSTYLE_HXX\n#include <unostyle.hxx>\n#endif\n#ifndef _CELLATR_HXX\n#include <cellatr.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESUPPLIER_HPP_\n#include <com\/sun\/star\/drawing\/XDrawPageSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n#ifndef _SWSTYLENAMEMAPPER_HXX\n#include <SwStyleNameMapper.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::text;\nusing namespace ::com::sun::star::drawing;\nusing namespace ::com::sun::star::lang;\nusing namespace ::xmloff::token;\n\nvoid SwXMLExport::ExportFmt( const SwFmt& rFmt, enum XMLTokenEnum eFamily )\n{\n \/\/ <style:style ...>\n CheckAttrList();\n\n \/\/ style:family=\"...\"\n DBG_ASSERT( RES_FRMFMT==rFmt.Which(), \"frame format expected\" );\n if( RES_FRMFMT != rFmt.Which() )\n return;\n DBG_ASSERT( eFamily != XML_TOKEN_INVALID, \"family must be specified\" );\n \/\/ style:name=\"...\"\n sal_Bool bEncoded = sal_False;\n AddAttribute( XML_NAMESPACE_STYLE, XML_NAME, EncodeStyleName(\n rFmt.GetName(), &bEncoded ) );\n if( bEncoded )\n AddAttribute( XML_NAMESPACE_STYLE, XML_DISPLAY_NAME, rFmt.GetName() );\n\n\n if( eFamily != XML_TOKEN_INVALID )\n AddAttribute( XML_NAMESPACE_STYLE, XML_FAMILY, eFamily );\n\n#ifndef PRODUCT\n \/\/ style:parent-style-name=\"...\" (if its not the default only)\n const SwFmt* pParent = rFmt.DerivedFrom();\n \/\/ Parent-Namen nur uebernehmen, wenn kein Default\n ASSERT( !pParent || pParent->IsDefault(), \"unexpected parent\" );\n\n ASSERT( USHRT_MAX == rFmt.GetPoolFmtId(), \"pool ids arent'supported\" );\n ASSERT( USHRT_MAX == rFmt.GetPoolHelpId(), \"help ids arent'supported\" );\n ASSERT( USHRT_MAX == rFmt.GetPoolHelpId() ||\n UCHAR_MAX == rFmt.GetPoolHlpFileId(), \"help file ids aren't supported\" );\n#endif\n\n \/\/ style:master-page-name\n if( RES_FRMFMT == rFmt.Which() && XML_TABLE == eFamily )\n {\n const SfxPoolItem *pItem;\n if( SFX_ITEM_SET == rFmt.GetAttrSet().GetItemState( RES_PAGEDESC,\n sal_False, &pItem ) )\n {\n String sName;\n const SwPageDesc *pPageDesc =\n ((const SwFmtPageDesc *)pItem)->GetPageDesc();\n if( pPageDesc )\n SwStyleNameMapper::FillProgName(\n pPageDesc->GetName(),\n sName,\n nsSwGetPoolIdFromName::GET_POOLID_PAGEDESC,\n sal_True);\n AddAttribute( XML_NAMESPACE_STYLE, XML_MASTER_PAGE_NAME,\n EncodeStyleName( sName ) );\n }\n }\n\n if( XML_TABLE_CELL == eFamily )\n {\n DBG_ASSERT(RES_FRMFMT == rFmt.Which(), \"only frame format\");\n\n const SfxPoolItem *pItem;\n if( SFX_ITEM_SET ==\n rFmt.GetAttrSet().GetItemState( RES_BOXATR_FORMAT,\n sal_False, &pItem ) )\n {\n sal_Int32 nFormat = (sal_Int32)\n ((const SwTblBoxNumFormat *)pItem)->GetValue();\n\n if ( (nFormat != -1) && (nFormat != NUMBERFORMAT_TEXT) )\n {\n \/\/ if we have a format, register and then export\n \/\/ (Careful: here we assume that data styles will be\n \/\/ written after cell styles)\n addDataStyle(nFormat);\n OUString sDataStyleName = getDataStyleName(nFormat);\n if( sDataStyleName.getLength() > 0 )\n AddAttribute( XML_NAMESPACE_STYLE, XML_DATA_STYLE_NAME,\n sDataStyleName );\n }\n }\n }\n\n {\n SvXMLElementExport aElem( *this, XML_NAMESPACE_STYLE, XML_STYLE,\n sal_True, sal_True );\n\n SvXMLItemMapEntriesRef xItemMap;\n XMLTokenEnum ePropToken = XML_TABLE_PROPERTIES;\n if( XML_TABLE == eFamily )\n {\n xItemMap = xTableItemMap;\n }\n else if( XML_TABLE_ROW == eFamily )\n {\n xItemMap = xTableRowItemMap;\n ePropToken = XML_TABLE_ROW_PROPERTIES;\n }\n else if( XML_TABLE_CELL == eFamily )\n {\n xItemMap = xTableCellItemMap;\n ePropToken = XML_TABLE_CELL_PROPERTIES;\n }\n\n if( xItemMap.Is() )\n {\n SvXMLExportItemMapper& rItemMapper = GetTableItemMapper();\n rItemMapper.setMapEntries( xItemMap );\n\n GetTableItemMapper().exportXML( *this,\n rFmt.GetAttrSet(),\n GetTwipUnitConverter(),\n ePropToken,\n XML_EXPORT_FLAG_IGN_WS );\n }\n }\n}\n\n\nvoid SwXMLExport::_ExportStyles( sal_Bool bUsed )\n{\n SvXMLExport::_ExportStyles( bUsed );\n\n \/\/ drawing defaults\n GetShapeExport()->ExportGraphicDefaults();\n\n#if SUPD <628 && !defined(TEST_MIB)\n GetTextParagraphExport()->SetProgress( IsShowProgress() ? 1 : 0 );\n#endif\n GetTextParagraphExport()->exportTextStyles( bUsed\n#if SUPD >627 || defined(TEST_MIB)\n ,IsShowProgress()\n#endif\n );\n#if SUPD <628 && !defined(TEST_MIB)\n GetTextParagraphExport()->SetProgress( 0 );\n#endif\n}\n\nvoid SwXMLExport::_ExportAutoStyles()\n{\n \/\/ The order in which styles are collected *MUST* be the same as\n \/\/ the order in which they are exported. Otherwise, caching will\n \/\/ fail.\n\n if( (getExportFlags() & (EXPORT_MASTERSTYLES|EXPORT_CONTENT)) != 0 )\n {\n if( (getExportFlags() & EXPORT_CONTENT) == 0 )\n {\n \/\/ only master pages are exported => styles for frames bound\n \/\/ to frames (but none for frames bound to pages) need to be\n \/\/ collected.\n GetTextParagraphExport()->collectFramesBoundToFrameAutoStyles();\n }\n else\n {\n \/\/ content (and optional master pages) are exported => styles\n \/\/ for frames bound to frame or to pages need to be\n \/\/ collected.\n GetTextParagraphExport()->collectFramesBoundToPageOrFrameAutoStyles(\n bShowProgress );\n }\n\n }\n\n \/\/ exported in _ExportMasterStyles\n if( (getExportFlags() & EXPORT_MASTERSTYLES) != 0 )\n GetPageExport()->collectAutoStyles( sal_False );\n\n \/\/ if we don't export styles (i.e. in content stream only, but not\n \/\/ in single-stream case), then we can save ourselves a bit of\n \/\/ work and memory by not collecting field masters\n if( (getExportFlags() & EXPORT_STYLES ) == 0 )\n GetTextParagraphExport()->exportUsedDeclarations( sal_False );\n\n \/\/ exported in _ExportContent\n if( (getExportFlags() & EXPORT_CONTENT) != 0 )\n {\n GetTextParagraphExport()->exportTrackedChanges( sal_True );\n Reference < XTextDocument > xTextDoc( GetModel(), UNO_QUERY );\n Reference < XText > xText = xTextDoc->getText();\n\n \/\/ collect form autostyle\n \/\/ (do this before collectTextAutoStyles, 'cause the shapes need the results of the work\n \/\/ done by examineForms)\n Reference<XDrawPageSupplier> xDrawPageSupplier( GetModel(), UNO_QUERY );\n if (xDrawPageSupplier.is() && GetFormExport().is())\n {\n Reference<XDrawPage> xPage = xDrawPageSupplier->getDrawPage();\n if (xPage.is())\n GetFormExport()->examineForms(xPage);\n }\n\n GetTextParagraphExport()->collectTextAutoStylesOptimized( bShowProgress );\n \/\/GetTextParagraphExport()->collectTextAutoStyles( xText, bShowProgress, sal_True, bPortions );\n }\n\n GetTextParagraphExport()->exportTextAutoStyles();\n GetShapeExport()->exportAutoStyles();\n if( (getExportFlags() & EXPORT_MASTERSTYLES) != 0 )\n GetPageExport()->exportAutoStyles();\n\n \/\/ we rely on data styles being written after cell styles in the\n \/\/ ExportFmt() method; so be careful when changing order.\n exportAutoDataStyles();\n\n sal_uInt16 nContentAutostyles = EXPORT_CONTENT | EXPORT_AUTOSTYLES;\n if ( ( getExportFlags() & nContentAutostyles ) == nContentAutostyles )\n GetFormExport()->exportAutoStyles();\n}\n\nXMLPageExport* SwXMLExport::CreatePageExport()\n{\n return new XMLTextMasterPageExport( *this );\n}\n\nvoid SwXMLExport::_ExportMasterStyles()\n{\n \/\/ export master styles\n GetPageExport()->exportMasterStyles( sal_False );\n}\n\n\/\/ ---------------------------------------------------------------------\nclass SwXMLAutoStylePoolP : public SvXMLAutoStylePoolP\n{\n SvXMLExport& rExport;\n const OUString sListStyleName;\n const OUString sMasterPageName;\n const OUString sCDATA;\n\nprotected:\n\n virtual void exportStyleAttributes(\n SvXMLAttributeList& rAttrList,\n sal_Int32 nFamily,\n const ::std::vector< XMLPropertyState >& rProperties,\n const SvXMLExportPropertyMapper& rPropExp\n , const SvXMLUnitConverter& rUnitConverter,\n const SvXMLNamespaceMap& rNamespaceMap\n ) const;\npublic:\n\n SwXMLAutoStylePoolP( SvXMLExport& rExport );\n virtual ~SwXMLAutoStylePoolP();\n};\n\nvoid SwXMLAutoStylePoolP::exportStyleAttributes(\n SvXMLAttributeList& rAttrList,\n sal_Int32 nFamily,\n const ::std::vector< XMLPropertyState >& rProperties,\n const SvXMLExportPropertyMapper& rPropExp\n , const SvXMLUnitConverter& rUnitConverter,\n const SvXMLNamespaceMap& rNamespaceMap\n ) const\n{\n SvXMLAutoStylePoolP::exportStyleAttributes( rAttrList, nFamily, rProperties, rPropExp, rUnitConverter, rNamespaceMap);\n\n if( XML_STYLE_FAMILY_TEXT_PARAGRAPH == nFamily )\n {\n for( ::std::vector< XMLPropertyState >::const_iterator\n aProperty = rProperties.begin();\n aProperty != rProperties.end();\n aProperty++ )\n {\n if (aProperty->mnIndex != -1) \/\/ #i26762#\n {\n switch( rPropExp.getPropertySetMapper()->\n GetEntryContextId( aProperty->mnIndex ) )\n {\n case CTF_NUMBERINGSTYLENAME:\n {\n OUString sStyleName;\n aProperty->maValue >>= sStyleName;\n if( sStyleName.getLength() )\n {\n OUString sTmp = rExport.GetTextParagraphExport()->GetListAutoStylePool().Find( sStyleName );\n if( sTmp.getLength() )\n sStyleName = sTmp;\n GetExport().AddAttribute( XML_NAMESPACE_STYLE,\n sListStyleName,\n GetExport().EncodeStyleName( sStyleName ) );\n }\n }\n break;\n case CTF_PAGEDESCNAME:\n {\n OUString sStyleName;\n aProperty->maValue >>= sStyleName;\n GetExport().AddAttribute( XML_NAMESPACE_STYLE,\n sMasterPageName,\n GetExport().EncodeStyleName( sStyleName ) );\n }\n break;\n }\n }\n }\n }\n}\n\nSwXMLAutoStylePoolP::SwXMLAutoStylePoolP(SvXMLExport& rExp ) :\n SvXMLAutoStylePoolP( rExp ),\n rExport( rExp ),\n sListStyleName( GetXMLToken( XML_LIST_STYLE_NAME ) ),\n sMasterPageName( GetXMLToken( XML_MASTER_PAGE_NAME ) ),\n sCDATA( GetXMLToken( XML_CDATA ) )\n{\n}\n\n\nSwXMLAutoStylePoolP::~SwXMLAutoStylePoolP()\n{\n}\n\nSvXMLAutoStylePoolP* SwXMLExport::CreateAutoStylePool()\n{\n return new SwXMLAutoStylePoolP( *this );\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <stdarg.h>\n#include <errno.h>\n#include <string>\n#include <sstream>\n\n#include <iomanip>\n\n#include \"base\/buffer.h\"\n#include \"base\/stringutil.h\"\n\n#ifdef _WIN32\n\/\/ Function Cross-Compatibility\n#define strcasecmp _stricmp\n#endif\n\nunsigned int parseHex(const char *_szValue)\n{\n\tint Value = 0;\n\tsize_t Finish = strlen(_szValue);\n\tif (Finish > 8 ) { Finish = 8; }\n\n\tfor (size_t Count = 0; Count < Finish; Count++) {\n\t\tValue = (Value << 4);\n\t\tswitch( _szValue[Count] ) {\n\t\tcase '0': break;\n\t\tcase '1': Value += 1; break;\n\t\tcase '2': Value += 2; break;\n\t\tcase '3': Value += 3; break;\n\t\tcase '4': Value += 4; break;\n\t\tcase '5': Value += 5; break;\n\t\tcase '6': Value += 6; break;\n\t\tcase '7': Value += 7; break;\n\t\tcase '8': Value += 8; break;\n\t\tcase '9': Value += 9; break;\n\t\tcase 'A': Value += 10; break;\n\t\tcase 'a': Value += 10; break;\n\t\tcase 'B': Value += 11; break;\n\t\tcase 'b': Value += 11; break;\n\t\tcase 'C': Value += 12; break;\n\t\tcase 'c': Value += 12; break;\n\t\tcase 'D': Value += 13; break;\n\t\tcase 'd': Value += 13; break;\n\t\tcase 'E': Value += 14; break;\n\t\tcase 'e': Value += 14; break;\n\t\tcase 'F': Value += 15; break;\n\t\tcase 'f': Value += 15; break;\n\t\tdefault:\n\t\t\tValue = (Value >> 4);\n\t\t\tCount = Finish;\n\t\t}\n\t}\n\treturn Value;\n}\n\nvoid DataToHexString(const uint8 *data, size_t size, std::string *output) {\n\tBuffer buffer;\n\tfor (size_t i = 0; i < size; i++) {\n\t\tbuffer.Printf(\"%02x \", data[i]);\n\t\tif (i && !(i & 15))\n\t\t\tbuffer.Printf(\"\\n\");\n\t}\n\tbuffer.TakeAll(output);\n}\n\nstd::string StringFromFormat(const char* format, ...)\n{\n\tva_list args;\n\tchar *buf = NULL;\n\tstd::string temp = \"\";\n#ifdef _WIN32\n\tint required = 0;\n\n\tva_start(args, format);\n\trequired = _vscprintf(format, args);\n\tbuf = new char[required + 1];\n\tif(vsnprintf(buf, required, format, args) < 0)\n\t\tbuf[0] = '\\0';\n\tva_end(args);\n\n\tbuf[required] = '\\0';\n\ttemp = buf;\n\tdelete[] buf;\n#else\n\tva_start(args, format);\n\tif(vasprintf(&buf, format, args) < 0)\n\t\tbuf = NULL;\n\tva_end(args);\n\n\tif(buf != NULL) {\n\t\ttemp = buf;\n\t\tfree(buf);\n\t}\n#endif\n\treturn temp;\n}\n\nstd::string StringFromInt(int value)\n{\n\tchar temp[16];\n\tsprintf(temp, \"%i\", value);\n\treturn temp;\n}\n\nstd::string StringFromBool(bool value)\n{\n\treturn value ? \"True\" : \"False\";\n}\n\n\/\/ Turns \" hej \" into \"hej\". Also handles tabs.\nstd::string StripSpaces(const std::string &str)\n{\n\tconst size_t s = str.find_first_not_of(\" \\t\\r\\n\");\n\n\tif (str.npos != s)\n\t\treturn str.substr(s, str.find_last_not_of(\" \\t\\r\\n\") - s + 1);\n\telse\n\t\treturn \"\";\n}\n\n\/\/ \"\\\"hello\\\"\" is turned to \"hello\"\n\/\/ This one assumes that the string has already been space stripped in both\n\/\/ ends, as done by StripSpaces above, for example.\nstd::string StripQuotes(const std::string& s)\n{\n\tif (s.size() && '\\\"' == s[0] && '\\\"' == *s.rbegin())\n\t\treturn s.substr(1, s.size() - 2);\n\telse\n\t\treturn s;\n}\n\n\/\/ For Debugging. Read out an u8 array.\nstd::string ArrayToString(const uint8_t *data, uint32_t size, int line_len, bool spaces)\n{\n\tstd::ostringstream oss;\n\toss << std::setfill('0') << std::hex;\n\n\tfor (int line = 0; size; ++data, --size)\n\t{\n\t\toss << std::setw(2) << (int)*data;\n\t\tif (line_len == ++line)\n\t\t{\n\t\t\toss << '\\n';\n\t\t\tline = 0;\n\t\t}\n\t\telse if (spaces)\n\t\t\toss << ' ';\n\t}\n\n\treturn oss.str();\n}\n\nbool TryParse(const std::string &str, uint32_t *const output)\n{\n\tchar *endptr = NULL;\n\n\t\/\/ Holy crap this is ugly.\n\n\t\/\/ Reset errno to a value other than ERANGE\n\terrno = 0;\n\n\tunsigned long value = strtoul(str.c_str(), &endptr, 0);\n\n\tif (!endptr || *endptr)\n\t\treturn false;\n\n\tif (errno == ERANGE)\n\t\treturn false;\n\n\tif (ULONG_MAX > UINT_MAX) {\n#ifdef _MSC_VER\n#pragma warning (disable:4309)\n#endif\n\t\t\/\/ Note: The typecasts avoid GCC warnings when long is 32 bits wide.\n\t\tif (value >= static_cast<unsigned long>(0x100000000ull)\n\t\t\t&& value <= static_cast<unsigned long>(0xFFFFFFFF00000000ull))\n\t\t\treturn false;\n\t}\n\n\t*output = static_cast<uint32_t>(value);\n\treturn true;\n}\n\nbool TryParse(const std::string &str, bool *const output)\n{\n\tif (\"1\" == str || !strcasecmp(\"true\", str.c_str()))\n\t\t*output = true;\n\telse if (\"0\" == str || !strcasecmp(\"false\", str.c_str()))\n\t\t*output = false;\n\telse\n\t\treturn false;\n\n\treturn true;\n}\n\nvoid SplitString(const std::string& str, const char delim, std::vector<std::string>& output)\n{\n\tstd::istringstream iss(str);\n\toutput.resize(1);\n\n\twhile (std::getline(iss, *output.rbegin(), delim))\n\t\toutput.push_back(\"\");\n\n\toutput.pop_back();\n}\n<commit_msg>Buildfix for linux<commit_after>#include <string.h>\n#include <stdarg.h>\n#include <errno.h>\n#include <string>\n#include <sstream>\n#include <limits.h>\n\n#include <iomanip>\n\n#include \"base\/buffer.h\"\n#include \"base\/stringutil.h\"\n\n#ifdef _WIN32\n\/\/ Function Cross-Compatibility\n#define strcasecmp _stricmp\n#endif\n\nunsigned int parseHex(const char *_szValue)\n{\n\tint Value = 0;\n\tsize_t Finish = strlen(_szValue);\n\tif (Finish > 8 ) { Finish = 8; }\n\n\tfor (size_t Count = 0; Count < Finish; Count++) {\n\t\tValue = (Value << 4);\n\t\tswitch( _szValue[Count] ) {\n\t\tcase '0': break;\n\t\tcase '1': Value += 1; break;\n\t\tcase '2': Value += 2; break;\n\t\tcase '3': Value += 3; break;\n\t\tcase '4': Value += 4; break;\n\t\tcase '5': Value += 5; break;\n\t\tcase '6': Value += 6; break;\n\t\tcase '7': Value += 7; break;\n\t\tcase '8': Value += 8; break;\n\t\tcase '9': Value += 9; break;\n\t\tcase 'A': Value += 10; break;\n\t\tcase 'a': Value += 10; break;\n\t\tcase 'B': Value += 11; break;\n\t\tcase 'b': Value += 11; break;\n\t\tcase 'C': Value += 12; break;\n\t\tcase 'c': Value += 12; break;\n\t\tcase 'D': Value += 13; break;\n\t\tcase 'd': Value += 13; break;\n\t\tcase 'E': Value += 14; break;\n\t\tcase 'e': Value += 14; break;\n\t\tcase 'F': Value += 15; break;\n\t\tcase 'f': Value += 15; break;\n\t\tdefault:\n\t\t\tValue = (Value >> 4);\n\t\t\tCount = Finish;\n\t\t}\n\t}\n\treturn Value;\n}\n\nvoid DataToHexString(const uint8 *data, size_t size, std::string *output) {\n\tBuffer buffer;\n\tfor (size_t i = 0; i < size; i++) {\n\t\tbuffer.Printf(\"%02x \", data[i]);\n\t\tif (i && !(i & 15))\n\t\t\tbuffer.Printf(\"\\n\");\n\t}\n\tbuffer.TakeAll(output);\n}\n\nstd::string StringFromFormat(const char* format, ...)\n{\n\tva_list args;\n\tchar *buf = NULL;\n\tstd::string temp = \"\";\n#ifdef _WIN32\n\tint required = 0;\n\n\tva_start(args, format);\n\trequired = _vscprintf(format, args);\n\tbuf = new char[required + 1];\n\tif(vsnprintf(buf, required, format, args) < 0)\n\t\tbuf[0] = '\\0';\n\tva_end(args);\n\n\tbuf[required] = '\\0';\n\ttemp = buf;\n\tdelete[] buf;\n#else\n\tva_start(args, format);\n\tif(vasprintf(&buf, format, args) < 0)\n\t\tbuf = NULL;\n\tva_end(args);\n\n\tif(buf != NULL) {\n\t\ttemp = buf;\n\t\tfree(buf);\n\t}\n#endif\n\treturn temp;\n}\n\nstd::string StringFromInt(int value)\n{\n\tchar temp[16];\n\tsprintf(temp, \"%i\", value);\n\treturn temp;\n}\n\nstd::string StringFromBool(bool value)\n{\n\treturn value ? \"True\" : \"False\";\n}\n\n\/\/ Turns \" hej \" into \"hej\". Also handles tabs.\nstd::string StripSpaces(const std::string &str)\n{\n\tconst size_t s = str.find_first_not_of(\" \\t\\r\\n\");\n\n\tif (str.npos != s)\n\t\treturn str.substr(s, str.find_last_not_of(\" \\t\\r\\n\") - s + 1);\n\telse\n\t\treturn \"\";\n}\n\n\/\/ \"\\\"hello\\\"\" is turned to \"hello\"\n\/\/ This one assumes that the string has already been space stripped in both\n\/\/ ends, as done by StripSpaces above, for example.\nstd::string StripQuotes(const std::string& s)\n{\n\tif (s.size() && '\\\"' == s[0] && '\\\"' == *s.rbegin())\n\t\treturn s.substr(1, s.size() - 2);\n\telse\n\t\treturn s;\n}\n\n\/\/ For Debugging. Read out an u8 array.\nstd::string ArrayToString(const uint8_t *data, uint32_t size, int line_len, bool spaces)\n{\n\tstd::ostringstream oss;\n\toss << std::setfill('0') << std::hex;\n\n\tfor (int line = 0; size; ++data, --size)\n\t{\n\t\toss << std::setw(2) << (int)*data;\n\t\tif (line_len == ++line)\n\t\t{\n\t\t\toss << '\\n';\n\t\t\tline = 0;\n\t\t}\n\t\telse if (spaces)\n\t\t\toss << ' ';\n\t}\n\n\treturn oss.str();\n}\n\nbool TryParse(const std::string &str, uint32_t *const output)\n{\n\tchar *endptr = NULL;\n\n\t\/\/ Holy crap this is ugly.\n\n\t\/\/ Reset errno to a value other than ERANGE\n\terrno = 0;\n\n\tunsigned long value = strtoul(str.c_str(), &endptr, 0);\n\n\tif (!endptr || *endptr)\n\t\treturn false;\n\n\tif (errno == ERANGE)\n\t\treturn false;\n\n\tif (ULONG_MAX > UINT_MAX) {\n#ifdef _MSC_VER\n#pragma warning (disable:4309)\n#endif\n\t\t\/\/ Note: The typecasts avoid GCC warnings when long is 32 bits wide.\n\t\tif (value >= static_cast<unsigned long>(0x100000000ull)\n\t\t\t&& value <= static_cast<unsigned long>(0xFFFFFFFF00000000ull))\n\t\t\treturn false;\n\t}\n\n\t*output = static_cast<uint32_t>(value);\n\treturn true;\n}\n\nbool TryParse(const std::string &str, bool *const output)\n{\n\tif (\"1\" == str || !strcasecmp(\"true\", str.c_str()))\n\t\t*output = true;\n\telse if (\"0\" == str || !strcasecmp(\"false\", str.c_str()))\n\t\t*output = false;\n\telse\n\t\treturn false;\n\n\treturn true;\n}\n\nvoid SplitString(const std::string& str, const char delim, std::vector<std::string>& output)\n{\n\tstd::istringstream iss(str);\n\toutput.resize(1);\n\n\twhile (std::getline(iss, *output.rbegin(), delim))\n\t\toutput.push_back(\"\");\n\n\toutput.pop_back();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dbconfig.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 10:21:37 $\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_sw.hxx\"\n\n\n\n#ifndef _DBCONFIG_HXX\n#include <dbconfig.hxx>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include <com\/sun\/star\/uno\/Any.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _SWDBDATA_HXX\n#include <swdbdata.hxx>\n#endif\n\n#include <unomid.h>\n\nusing namespace utl;\nusing namespace rtl;\nusing namespace ::com::sun::star::uno;\n\n\/*--------------------------------------------------------------------\n Beschreibung: Ctor\n --------------------------------------------------------------------*\/\n\nconst Sequence<OUString>& SwDBConfig::GetPropertyNames()\n{\n static Sequence<OUString> aNames;\n if(!aNames.getLength())\n {\n static const char* aPropNames[] =\n {\n \"AddressBook\/DataSourceName\", \/\/ 0\n \"AddressBook\/Command\", \/\/ 1\n \"AddressBook\/CommandType\", \/\/ 2\n \"Bibliography\/CurrentDataSource\/DataSourceName\", \/\/ 4\n \"Bibliography\/CurrentDataSource\/Command\", \/\/ 5\n \"Bibliography\/CurrentDataSource\/CommandType\" \/\/ 6\n };\n const int nCount = sizeof(aPropNames)\/sizeof(const char*);\n aNames.realloc(nCount);\n OUString* pNames = aNames.getArray();\n for(int i = 0; i < nCount; i++)\n pNames[i] = OUString::createFromAscii(aPropNames[i]);\n }\n return aNames;\n}\n\/* -----------------------------06.09.00 16:44--------------------------------\n\n ---------------------------------------------------------------------------*\/\nSwDBConfig::SwDBConfig() :\n ConfigItem(C2U(\"Office.DataAccess\"),\n CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),\n pAdrImpl(0),\n pBibImpl(0)\n{\n};\n\/* -----------------------------06.09.00 16:50--------------------------------\n\n ---------------------------------------------------------------------------*\/\nSwDBConfig::~SwDBConfig()\n{\n delete pAdrImpl;\n delete pBibImpl;\n}\n\/* -----------------------------20.02.01 12:32--------------------------------\n\n ---------------------------------------------------------------------------*\/\nvoid SwDBConfig::Load()\n{\n const Sequence<OUString>& rNames = GetPropertyNames();\n if(!pAdrImpl)\n {\n\n pAdrImpl = new SwDBData;\n pAdrImpl->nCommandType = 0;\n pBibImpl = new SwDBData;\n pBibImpl->nCommandType = 0;\n }\n Sequence<Any> aValues = GetProperties(rNames);\n const Any* pValues = aValues.getConstArray();\n DBG_ASSERT(aValues.getLength() == rNames.getLength(), \"GetProperties failed\")\n if(aValues.getLength() == rNames.getLength())\n {\n for(int nProp = 0; nProp < rNames.getLength(); nProp++)\n {\n switch(nProp)\n {\n case 0: pValues[nProp] >>= pAdrImpl->sDataSource; break;\n case 1: pValues[nProp] >>= pAdrImpl->sCommand; break;\n case 2: pValues[nProp] >>= pAdrImpl->nCommandType; break;\n case 3: pValues[nProp] >>= pBibImpl->sDataSource; break;\n case 4: pValues[nProp] >>= pBibImpl->sCommand; break;\n case 5: pValues[nProp] >>= pBibImpl->nCommandType; break;\n }\n }\n }\n}\n\/* -----------------------------20.02.01 12:36--------------------------------\n\n ---------------------------------------------------------------------------*\/\nconst SwDBData& SwDBConfig::GetAddressSource()\n{\n if(!pAdrImpl)\n Load();\n return *pAdrImpl;\n}\n\/* -----------------29.11.2002 11:43-----------------\n *\n * --------------------------------------------------*\/\nconst SwDBData& SwDBConfig::GetBibliographySource()\n{\n if(!pBibImpl)\n Load();\n return *pBibImpl;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS impresstables2 (1.6.400); FILE MERGED 2007\/10\/11 23:55:38 cl 1.6.400.2: RESYNC: (1.6-1.7); FILE MERGED 2007\/10\/11 14:10:29 cl 1.6.400.1: #i68103# fixed namespace issues<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dbconfig.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 12:46:00 $\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_sw.hxx\"\n\n\n\n#ifndef _DBCONFIG_HXX\n#include <dbconfig.hxx>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include <com\/sun\/star\/uno\/Any.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _SWDBDATA_HXX\n#include <swdbdata.hxx>\n#endif\n\n#include <unomid.h>\n\nusing namespace utl;\nusing rtl::OUString;\nusing namespace com::sun::star::uno;\n\n\/*--------------------------------------------------------------------\n Beschreibung: Ctor\n --------------------------------------------------------------------*\/\n\nconst Sequence<OUString>& SwDBConfig::GetPropertyNames()\n{\n static Sequence<OUString> aNames;\n if(!aNames.getLength())\n {\n static const char* aPropNames[] =\n {\n \"AddressBook\/DataSourceName\", \/\/ 0\n \"AddressBook\/Command\", \/\/ 1\n \"AddressBook\/CommandType\", \/\/ 2\n \"Bibliography\/CurrentDataSource\/DataSourceName\", \/\/ 4\n \"Bibliography\/CurrentDataSource\/Command\", \/\/ 5\n \"Bibliography\/CurrentDataSource\/CommandType\" \/\/ 6\n };\n const int nCount = sizeof(aPropNames)\/sizeof(const char*);\n aNames.realloc(nCount);\n OUString* pNames = aNames.getArray();\n for(int i = 0; i < nCount; i++)\n pNames[i] = OUString::createFromAscii(aPropNames[i]);\n }\n return aNames;\n}\n\/* -----------------------------06.09.00 16:44--------------------------------\n\n ---------------------------------------------------------------------------*\/\nSwDBConfig::SwDBConfig() :\n ConfigItem(C2U(\"Office.DataAccess\"),\n CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),\n pAdrImpl(0),\n pBibImpl(0)\n{\n};\n\/* -----------------------------06.09.00 16:50--------------------------------\n\n ---------------------------------------------------------------------------*\/\nSwDBConfig::~SwDBConfig()\n{\n delete pAdrImpl;\n delete pBibImpl;\n}\n\/* -----------------------------20.02.01 12:32--------------------------------\n\n ---------------------------------------------------------------------------*\/\nvoid SwDBConfig::Load()\n{\n const Sequence<OUString>& rNames = GetPropertyNames();\n if(!pAdrImpl)\n {\n\n pAdrImpl = new SwDBData;\n pAdrImpl->nCommandType = 0;\n pBibImpl = new SwDBData;\n pBibImpl->nCommandType = 0;\n }\n Sequence<Any> aValues = GetProperties(rNames);\n const Any* pValues = aValues.getConstArray();\n DBG_ASSERT(aValues.getLength() == rNames.getLength(), \"GetProperties failed\")\n if(aValues.getLength() == rNames.getLength())\n {\n for(int nProp = 0; nProp < rNames.getLength(); nProp++)\n {\n switch(nProp)\n {\n case 0: pValues[nProp] >>= pAdrImpl->sDataSource; break;\n case 1: pValues[nProp] >>= pAdrImpl->sCommand; break;\n case 2: pValues[nProp] >>= pAdrImpl->nCommandType; break;\n case 3: pValues[nProp] >>= pBibImpl->sDataSource; break;\n case 4: pValues[nProp] >>= pBibImpl->sCommand; break;\n case 5: pValues[nProp] >>= pBibImpl->nCommandType; break;\n }\n }\n }\n}\n\/* -----------------------------20.02.01 12:36--------------------------------\n\n ---------------------------------------------------------------------------*\/\nconst SwDBData& SwDBConfig::GetAddressSource()\n{\n if(!pAdrImpl)\n Load();\n return *pAdrImpl;\n}\n\/* -----------------29.11.2002 11:43-----------------\n *\n * --------------------------------------------------*\/\nconst SwDBData& SwDBConfig::GetBibliographySource()\n{\n if(!pBibImpl)\n Load();\n return *pBibImpl;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Resolves: fdo#40717 ensure required settings and styles exist in paste doc<commit_after><|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This program 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\n\n#include \"Binding_BaseContext.h\"\n#include \"Binding_Base.h\"\n#include \"Binding_Vector.h\"\n#include \"PythonFactory.h\"\n#include \"PythonToSofa.inl\"\n\n#include <sofa\/defaulttype\/Vec3Types.h>\nusing namespace sofa::defaulttype;\n\n#include <sofa\/core\/ObjectFactory.h>\nusing namespace sofa::core;\n\n#include <sofa\/core\/objectmodel\/BaseContext.h>\nusing namespace sofa::core::objectmodel;\n\n#include <sofa\/simulation\/Node.h>\nusing namespace sofa::simulation;\nusing namespace sofa::defaulttype;\n\n\nstatic PyObject * BaseContext_setGravity(PyObject *self, PyObject * args)\n{\n BaseContext* obj = get_basecontext( self );\n PyPtr<Vector3>* pyVec;\n if (!PyArg_ParseTuple(args, \"O\",&pyVec)) {\n return NULL;\n }\n\n obj->setGravity(*pyVec->object);\n Py_RETURN_NONE;\n}\n\nstatic PyObject * BaseContext_getGravity(PyObject *self, PyObject * \/*args*\/)\n{\n BaseContext* obj = get_basecontext( self );\n return SP_BUILD_PYPTR(Vector3,Vector3,new Vector3(obj->getGravity()),true); \/\/ \"true\", because I manage the deletion myself\n}\n\nstatic PyObject * BaseContext_getTime(PyObject *self, PyObject * \/*args*\/)\n{\n BaseContext* obj = get_basecontext( self );\n return PyFloat_FromDouble(obj->getTime());\n}\n\nstatic PyObject * BaseContext_getDt(PyObject *self, PyObject * \/*args*\/)\n{\n BaseContext* obj = get_basecontext( self );\n return PyFloat_FromDouble(obj->getDt());\n}\n\nstatic PyObject * BaseContext_getRootContext(PyObject *self, PyObject * \/*args*\/)\n{\n BaseContext* obj = get_basecontext( self );\n return sofa::PythonFactory::toPython(obj->getRootContext());\n}\n\n\n\/\/\/ This function converts an PyObject into a sofa string.\n\/\/\/ string that can be safely parsed in helper::vector<int> or helper::vector<double>\nstatic std::ostream& pythonToSofaDataString(PyObject* value, std::ostream& out)\n{\n \/\/\/ String are just returned as string.\n if (PyString_Check(value))\n {\n return out << PyString_AsString(value) ;\n }\n\n\n if( PySequence_Check(value) )\n {\n \/\/\/ It is a sequence...so we can iterate over it.\n PyObject *iterator = PyObject_GetIter(value);\n if(iterator)\n {\n bool first = true;\n while(PyObject* next = PyIter_Next(iterator))\n {\n if(first) first = false;\n else out << ' ';\n\n pythonToSofaDataString(next, out);\n Py_DECREF(next);\n }\n Py_DECREF(iterator);\n\n if (PyErr_Occurred())\n {\n msg_error(\"SofaPython\") << \"error while iterating.\" << msgendl\n << PythonEnvironment::getStackAsString() ;\n }\n return out;\n }\n }\n\n\n \/\/\/ Check if the object has an explicit conversion to a Sofa path. If this is the case\n \/\/\/ we use it.\n if( PyObject_HasAttrString(value, \"getAsACreateObjectParameter\") ){\n PyObject* retvalue = PyObject_CallMethod(value, (char*)\"getAsACreateObjectParameter\", nullptr) ;\n return pythonToSofaDataString(retvalue, out);\n }\n\n \/\/\/ Default conversion for standard type:\n if( !(PyInt_Check(value) || PyLong_Check(value) || PyFloat_Check(value) || PyBool_Check(value) ))\n {\n msg_warning(\"SofaPython\") << \"You are trying to convert a non primitive type to Sofa using the 'str' operator.\" << msgendl\n << \"Automatic conversion is provided for: String, Integer, Long, Float and Bool and Sequences.\" << msgendl\n << \"Other objects should implement the method getAsACreateObjectParameter(). \" << msgendl\n << \"This function should return a string usable as a parameter in createObject().\" << msgendl\n << \"So to remove this message you must add a method getAsCreateObjectParameter(self) \"\n \"to the object you are passing the createObject function.\" << msgendl\n << PythonEnvironment::getStackAsString() ;\n }\n\n\n PyObject* tmpstr=PyObject_Str(value);\n out << PyString_AsString(tmpstr) ;\n Py_DECREF(tmpstr) ;\n return out ;\n}\n\n\n\/\/\/ object factory\nstatic PyObject * BaseContext_createObject_Impl(PyObject * self, PyObject * args, PyObject * kw, bool printWarnings)\n{\n BaseContext* context = get_basecontext( self );\n\n char *type;\n if (!PyArg_ParseTuple(args, \"s\",&type))\n {\n return NULL;\n }\n\n \/\/\/ temporarily, the name is set to the type name.\n \/\/\/ if a \"name\" parameter is provided, it will overwrite it.\n BaseObjectDescription desc(type,type);\n\n bool warning = printWarnings;\n if (kw && PyDict_Size(kw)>0)\n {\n PyObject* keys = PyDict_Keys(kw);\n PyObject* values = PyDict_Values(kw);\n for (int i=0; i<PyDict_Size(kw); i++)\n {\n PyObject *key = PyList_GetItem(keys,i);\n PyObject *value = PyList_GetItem(values,i);\n\n if( !strcmp( PyString_AsString(key), \"warning\") )\n {\n if PyBool_Check(value)\n warning = (value==Py_True);\n }\n else\n {\n std::stringstream s;\n pythonToSofaDataString(value, s) ;\n desc.setAttribute(PyString_AsString(key),s.str().c_str());\n }\n }\n Py_DecRef(keys);\n Py_DecRef(values);\n }\n\n BaseObject::SPtr obj = ObjectFactory::getInstance()->createObject(context,&desc);\n if (obj==0)\n {\n std::stringstream msg;\n msg << \"createObject: component '\" << desc.getName() << \"' of type '\" << desc.getAttribute(\"type\",\"\")<< \"' in node '\"<<context->getName()<<\"'\" ;\n for (std::vector< std::string >::const_iterator it = desc.getErrors().begin(); it != desc.getErrors().end(); ++it)\n msg << \" \" << *it << msgendl ;\n PyErr_SetString(PyExc_RuntimeError, msg.str().c_str()) ;\n return NULL;\n }\n\n\n if( warning )\n {\n for( auto it : desc.getAttributeMap() )\n {\n if (!it.second.isAccessed())\n {\n obj->serr <<\"Unused Attribute: \\\"\"<<it.first <<\"\\\" with value: \\\"\" <<(std::string)it.second<<\"\\\" (\" << obj->getPathName() << \")\" << obj->sendl;\n }\n }\n\n Node *node = static_cast<Node*>(context);\n if (node && node->isInitialized())\n msg_warning(node) << \"Sofa.Node.createObject(\"<<type<<\") called on a node(\"<<node->getName()<<\") that is already initialized\";\n }\n\n return sofa::PythonFactory::toPython(obj.get());\n}\n\nstatic PyObject * BaseContext_createObject(PyObject * self, PyObject * args, PyObject * kw)\n{\n return BaseContext_createObject_Impl( self, args, kw, true );\n}\n\nstatic PyObject * BaseContext_createObject_noWarning(PyObject * self, PyObject * args, PyObject * kw)\n{\n SP_MESSAGE_DEPRECATED(\"BaseContext_createObject_noWarning is deprecated, use the keyword warning=False in BaseContext_createObject instead.\")\n return BaseContext_createObject_Impl( self, args, kw, false );\n}\n\n\/\/\/ the complete relative path to the object must be given\n\/\/\/ returns None with a warning if the object is not found\nstatic PyObject * BaseContext_getObject(PyObject * self, PyObject * args, PyObject * kw)\n{\n BaseContext* context = get_basecontext( self );\n char *path;\n if (!PyArg_ParseTuple(args, \"s\",&path))\n {\n msg_warning(context)\n << \"BaseContext_getObject: wrong argument, should be a string with the complete relative path\" ;\n return NULL;\n }\n\n bool emitWarningMessage = true;\n if (kw && PyDict_Size(kw)>0)\n {\n PyObject* keys = PyDict_Keys(kw);\n PyObject* values = PyDict_Values(kw);\n for (int i=0; i<PyDict_Size(kw); i++)\n {\n PyObject *key = PyList_GetItem(keys,i);\n PyObject *value = PyList_GetItem(values,i);\n if( !strcmp(PyString_AsString(key),\"warning\") )\n {\n if PyBool_Check(value)\n emitWarningMessage = (value==Py_True);\n break;\n }\n }\n Py_DecRef(keys);\n Py_DecRef(values);\n }\n\n if (!context || !path)\n {\n PyErr_BadArgument();\n return NULL;\n }\n BaseObject::SPtr sptr;\n context->get<BaseObject>(sptr,path);\n if (!sptr)\n {\n msg_warning_when(context, emitWarningMessage)\n << \"BaseContext_getObject: component \"<< path <<\" not found (the complete relative path is needed)\" ;\n\n return NULL;\n }\n\n return sofa::PythonFactory::toPython(sptr.get());\n}\n\n\n\/\/\/ the complete relative path to the object must be given\n\/\/\/ returns None if the object is not found\nstatic PyObject * BaseContext_getObject_noWarning(PyObject * self, PyObject * args)\n{\n SP_MESSAGE_DEPRECATED(\"BaseContext_getObject_noWarning is deprecated, use the keyword warning=False in BaseContext_getObject instead.\")\n\n BaseContext* context = get_basecontext( self );\n char *path;\n if (!PyArg_ParseTuple(args, \"s\",&path))\n {\n return NULL;\n }\n if (!context || !path)\n {\n PyErr_BadArgument();\n return NULL;\n }\n BaseObject::SPtr sptr;\n context->get<BaseObject>(sptr,path);\n if (!sptr) Py_RETURN_NONE;\n\n return sofa::PythonFactory::toPython(sptr.get());\n}\n\n\/\/TODO(PR:304) do it or remove :)\n\/\/ @TODO: pass keyword arguments rather than optional arguments?\nstatic PyObject * BaseContext_getObjects(PyObject * self, PyObject * args)\n{\n BaseContext* context = get_basecontext( self );\n char* search_direction= NULL;\n char* type_name= NULL;\n char* name= NULL;\n if ( !PyArg_ParseTuple ( args, \"|sss\", &search_direction, &type_name, &name ) ) {\n PyErr_SetString(PyExc_TypeError, \"BaseContext_getObjects: wrong arguments! Expected format: getObjects ( OPTIONAL STRING searchDirection, OPTIONAL STRING typeName, OPTIONAL STRING name )\" );\n return NULL;\n }\n\n if (!context)\n {\n PyErr_BadArgument();\n return NULL;\n }\n\n sofa::core::objectmodel::BaseContext::SearchDirection search_direction_enum= sofa::core::objectmodel::BaseContext::Local;\n if ( search_direction )\n {\n std::string search_direction_str ( search_direction );\n if ( search_direction_str == \"SearchUp\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::SearchUp;\n }\n else if ( search_direction_str == \"Local\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::Local;\n }\n else if ( search_direction_str == \"SearchDown\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::SearchDown;\n }\n else if ( search_direction_str == \"SearchRoot\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::SearchRoot;\n }\n else if ( search_direction_str == \"SearchParents\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::SearchParents;\n }\n else\n {\n msg_warning(context) << \"BaseContext_getObjects: Invalid search direction, using 'Local'. Expected: 'SearchUp', 'Local', 'SearchDown', 'SearchRoot', or 'SearchParents'.\" ;\n }\n }\n\n sofa::helper::vector< boost::intrusive_ptr<BaseObject> > list;\n context->get<BaseObject>(&list,search_direction_enum);\n\n PyObject *pyList = PyList_New(0);\n for (size_t i=0; i<list.size(); i++)\n {\n BaseObject* o = list[i].get();\n\n if( !type_name || o->getClass()->hasParent( type_name ) )\n {\n if ( !name || name == o->getName() )\n {\n PyObject* obj=sofa::PythonFactory::toPython(o); \/\/ ref 1\n PyList_Append(pyList,obj); \/\/ ref 2\n Py_DECREF(obj); \/\/ ref 1 (now owned by list)\n }\n }\n }\n\n return pyList;\n}\n\nSP_CLASS_METHODS_BEGIN(BaseContext)\nSP_CLASS_METHOD(BaseContext,getRootContext)\nSP_CLASS_METHOD(BaseContext,getTime)\nSP_CLASS_METHOD(BaseContext,getDt)\nSP_CLASS_METHOD(BaseContext,getGravity)\nSP_CLASS_METHOD(BaseContext,setGravity)\nSP_CLASS_METHOD_KW(BaseContext,createObject)\nSP_CLASS_METHOD_KW(BaseContext,createObject_noWarning) \/\/ deprecated\nSP_CLASS_METHOD_KW(BaseContext,getObject)\nSP_CLASS_METHOD(BaseContext,getObject_noWarning) \/\/ deprecated\nSP_CLASS_METHOD(BaseContext,getObjects)\nSP_CLASS_METHODS_END\n\n\nstatic PyObject * BaseContext_getAttr_animate(PyObject *self, void*)\n{\n BaseContext* obj = get_basecontext( self );\n return PyBool_FromLong(obj->getAnimate());\n}\nstatic int BaseContext_setAttr_animate(PyObject *self, PyObject * args, void*)\n{\n BaseContext* obj = get_basecontext( self );\n if (!PyBool_Check(args))\n {\n PyErr_BadArgument();\n return -1;\n }\n obj->setAnimate(args==Py_True);\n return 0;\n}\n\nstatic PyObject * BaseContext_getAttr_active(PyObject *self, void*)\n{\n BaseContext* obj = get_basecontext( self );\n return PyBool_FromLong(obj->isActive());\n}\n\nstatic int BaseContext_setAttr_active(PyObject *self, PyObject * args, void*)\n{\n BaseContext* obj = get_basecontext( self );\n if (!PyBool_Check(args))\n {\n PyErr_BadArgument();\n return -1;\n }\n obj->setActive(args==Py_True);\n return 0;\n}\n\nSP_CLASS_ATTRS_BEGIN(BaseContext)\nSP_CLASS_ATTR(BaseContext,active)\nSP_CLASS_ATTR(BaseContext,animate)\nSP_CLASS_ATTRS_END\n\nSP_CLASS_TYPE_SPTR_ATTR(BaseContext,BaseContext,Base)\n<commit_msg>[SofaPython] Replace SP_MESSAGE_WARNING... with msg_warning<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This program 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 License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\n\n#include \"Binding_BaseContext.h\"\n#include \"Binding_Base.h\"\n#include \"Binding_Vector.h\"\n#include \"PythonFactory.h\"\n#include \"PythonToSofa.inl\"\n\n#include <sofa\/defaulttype\/Vec3Types.h>\nusing namespace sofa::defaulttype;\n\n#include <sofa\/core\/ObjectFactory.h>\nusing namespace sofa::core;\n\n#include <sofa\/core\/objectmodel\/BaseContext.h>\nusing namespace sofa::core::objectmodel;\n\n#include <sofa\/simulation\/Node.h>\nusing namespace sofa::simulation;\nusing namespace sofa::defaulttype;\n\n\nstatic PyObject * BaseContext_setGravity(PyObject *self, PyObject * args)\n{\n BaseContext* obj = get_basecontext( self );\n PyPtr<Vector3>* pyVec;\n if (!PyArg_ParseTuple(args, \"O\",&pyVec)) {\n return NULL;\n }\n\n obj->setGravity(*pyVec->object);\n Py_RETURN_NONE;\n}\n\nstatic PyObject * BaseContext_getGravity(PyObject *self, PyObject * \/*args*\/)\n{\n BaseContext* obj = get_basecontext( self );\n return SP_BUILD_PYPTR(Vector3,Vector3,new Vector3(obj->getGravity()),true); \/\/ \"true\", because I manage the deletion myself\n}\n\nstatic PyObject * BaseContext_getTime(PyObject *self, PyObject * \/*args*\/)\n{\n BaseContext* obj = get_basecontext( self );\n return PyFloat_FromDouble(obj->getTime());\n}\n\nstatic PyObject * BaseContext_getDt(PyObject *self, PyObject * \/*args*\/)\n{\n BaseContext* obj = get_basecontext( self );\n return PyFloat_FromDouble(obj->getDt());\n}\n\nstatic PyObject * BaseContext_getRootContext(PyObject *self, PyObject * \/*args*\/)\n{\n BaseContext* obj = get_basecontext( self );\n return sofa::PythonFactory::toPython(obj->getRootContext());\n}\n\n\n\/\/\/ This function converts an PyObject into a sofa string.\n\/\/\/ string that can be safely parsed in helper::vector<int> or helper::vector<double>\nstatic std::ostream& pythonToSofaDataString(PyObject* value, std::ostream& out)\n{\n \/\/\/ String are just returned as string.\n if (PyString_Check(value))\n {\n return out << PyString_AsString(value) ;\n }\n\n\n if( PySequence_Check(value) )\n {\n \/\/\/ It is a sequence...so we can iterate over it.\n PyObject *iterator = PyObject_GetIter(value);\n if(iterator)\n {\n bool first = true;\n while(PyObject* next = PyIter_Next(iterator))\n {\n if(first) first = false;\n else out << ' ';\n\n pythonToSofaDataString(next, out);\n Py_DECREF(next);\n }\n Py_DECREF(iterator);\n\n if (PyErr_Occurred())\n {\n msg_error(\"SofaPython\") << \"error while iterating.\" << msgendl\n << PythonEnvironment::getStackAsString() ;\n }\n return out;\n }\n }\n\n\n \/\/\/ Check if the object has an explicit conversion to a Sofa path. If this is the case\n \/\/\/ we use it.\n if( PyObject_HasAttrString(value, \"getAsACreateObjectParameter\") ){\n PyObject* retvalue = PyObject_CallMethod(value, (char*)\"getAsACreateObjectParameter\", nullptr) ;\n return pythonToSofaDataString(retvalue, out);\n }\n\n \/\/\/ Default conversion for standard type:\n if( !(PyInt_Check(value) || PyLong_Check(value) || PyFloat_Check(value) || PyBool_Check(value) ))\n {\n msg_warning(\"SofaPython\") << \"You are trying to convert a non primitive type to Sofa using the 'str' operator.\" << msgendl\n << \"Automatic conversion is provided for: String, Integer, Long, Float and Bool and Sequences.\" << msgendl\n << \"Other objects should implement the method getAsACreateObjectParameter(). \" << msgendl\n << \"This function should return a string usable as a parameter in createObject().\" << msgendl\n << \"So to remove this message you must add a method getAsCreateObjectParameter(self) \"\n \"to the object you are passing the createObject function.\" << msgendl\n << PythonEnvironment::getStackAsString() ;\n }\n\n\n PyObject* tmpstr=PyObject_Str(value);\n out << PyString_AsString(tmpstr) ;\n Py_DECREF(tmpstr) ;\n return out ;\n}\n\n\n\/\/\/ object factory\nstatic PyObject * BaseContext_createObject_Impl(PyObject * self, PyObject * args, PyObject * kw, bool printWarnings)\n{\n BaseContext* context = get_basecontext( self );\n\n char *type;\n if (!PyArg_ParseTuple(args, \"s\",&type))\n {\n return NULL;\n }\n\n \/\/\/ temporarily, the name is set to the type name.\n \/\/\/ if a \"name\" parameter is provided, it will overwrite it.\n BaseObjectDescription desc(type,type);\n\n bool warning = printWarnings;\n if (kw && PyDict_Size(kw)>0)\n {\n PyObject* keys = PyDict_Keys(kw);\n PyObject* values = PyDict_Values(kw);\n for (int i=0; i<PyDict_Size(kw); i++)\n {\n PyObject *key = PyList_GetItem(keys,i);\n PyObject *value = PyList_GetItem(values,i);\n\n if( !strcmp( PyString_AsString(key), \"warning\") )\n {\n if PyBool_Check(value)\n warning = (value==Py_True);\n }\n else\n {\n std::stringstream s;\n pythonToSofaDataString(value, s) ;\n desc.setAttribute(PyString_AsString(key),s.str().c_str());\n }\n }\n Py_DecRef(keys);\n Py_DecRef(values);\n }\n\n BaseObject::SPtr obj = ObjectFactory::getInstance()->createObject(context,&desc);\n if (obj==0)\n {\n std::stringstream msg;\n msg << \"createObject: component '\" << desc.getName() << \"' of type '\" << desc.getAttribute(\"type\",\"\")<< \"' in node '\"<<context->getName()<<\"'\" ;\n for (std::vector< std::string >::const_iterator it = desc.getErrors().begin(); it != desc.getErrors().end(); ++it)\n msg << \" \" << *it << msgendl ;\n PyErr_SetString(PyExc_RuntimeError, msg.str().c_str()) ;\n return NULL;\n }\n\n\n if( warning )\n {\n for( auto it : desc.getAttributeMap() )\n {\n if (!it.second.isAccessed())\n {\n obj->serr <<\"Unused Attribute: \\\"\"<<it.first <<\"\\\" with value: \\\"\" <<(std::string)it.second<<\"\\\" (\" << obj->getPathName() << \")\" << obj->sendl;\n }\n }\n\n Node *node = static_cast<Node*>(context);\n if (node && node->isInitialized())\n msg_warning(node) << \"Sofa.Node.createObject(\"<<type<<\") called on a node(\"<<node->getName()<<\") that is already initialized\";\n }\n\n return sofa::PythonFactory::toPython(obj.get());\n}\n\nstatic PyObject * BaseContext_createObject(PyObject * self, PyObject * args, PyObject * kw)\n{\n return BaseContext_createObject_Impl( self, args, kw, true );\n}\n\nstatic PyObject * BaseContext_createObject_noWarning(PyObject * self, PyObject * args, PyObject * kw)\n{\n BaseContext* context = get_basecontext( self );\n msg_deprecated(context)\n << \"BaseContext_createObject_noWarning is deprecated, use the keyword warning=False in BaseContext_createObject instead.\" ;\n\n return BaseContext_createObject_Impl( self, args, kw, false );\n}\n\n\/\/\/ the complete relative path to the object must be given\n\/\/\/ returns None with a warning if the object is not found\nstatic PyObject * BaseContext_getObject(PyObject * self, PyObject * args, PyObject * kw)\n{\n BaseContext* context = get_basecontext( self );\n char *path;\n if (!PyArg_ParseTuple(args, \"s\",&path))\n {\n msg_warning(context)\n << \"BaseContext_getObject: wrong argument, should be a string with the complete relative path\" ;\n return NULL;\n }\n\n bool emitWarningMessage = true;\n if (kw && PyDict_Size(kw)>0)\n {\n PyObject* keys = PyDict_Keys(kw);\n PyObject* values = PyDict_Values(kw);\n for (int i=0; i<PyDict_Size(kw); i++)\n {\n PyObject *key = PyList_GetItem(keys,i);\n PyObject *value = PyList_GetItem(values,i);\n if( !strcmp(PyString_AsString(key),\"warning\") )\n {\n if PyBool_Check(value)\n emitWarningMessage = (value==Py_True);\n break;\n }\n }\n Py_DecRef(keys);\n Py_DecRef(values);\n }\n\n if (!context || !path)\n {\n PyErr_BadArgument();\n return NULL;\n }\n BaseObject::SPtr sptr;\n context->get<BaseObject>(sptr,path);\n if (!sptr)\n {\n msg_warning_when(emitWarningMessage, context)\n << \"BaseContext_getObject: component \"<< path <<\" not found (the complete relative path is needed)\" ;\n\n return NULL;\n }\n\n return sofa::PythonFactory::toPython(sptr.get());\n}\n\n\n\/\/\/ the complete relative path to the object must be given\n\/\/\/ returns None if the object is not found\nstatic PyObject * BaseContext_getObject_noWarning(PyObject * self, PyObject * args)\n{\n BaseContext* context = get_basecontext( self );\n msg_deprecated(context)\n << \"BaseContext_getObject_noWarning is deprecated, use the keyword warning=False in BaseContext_getObject instead.\" ;\n\n char *path;\n if (!PyArg_ParseTuple(args, \"s\",&path))\n {\n return NULL;\n }\n if (!context || !path)\n {\n PyErr_BadArgument();\n return NULL;\n }\n BaseObject::SPtr sptr;\n context->get<BaseObject>(sptr,path);\n if (!sptr) Py_RETURN_NONE;\n\n return sofa::PythonFactory::toPython(sptr.get());\n}\n\n\/\/TODO(PR:304) do it or remove :)\n\/\/ @TODO: pass keyword arguments rather than optional arguments?\nstatic PyObject * BaseContext_getObjects(PyObject * self, PyObject * args)\n{\n BaseContext* context = get_basecontext( self );\n char* search_direction= NULL;\n char* type_name= NULL;\n char* name= NULL;\n if ( !PyArg_ParseTuple ( args, \"|sss\", &search_direction, &type_name, &name ) ) {\n PyErr_SetString(PyExc_TypeError, \"BaseContext_getObjects: wrong arguments! Expected format: getObjects ( OPTIONAL STRING searchDirection, OPTIONAL STRING typeName, OPTIONAL STRING name )\" );\n return NULL;\n }\n\n if (!context)\n {\n PyErr_BadArgument();\n return NULL;\n }\n\n sofa::core::objectmodel::BaseContext::SearchDirection search_direction_enum= sofa::core::objectmodel::BaseContext::Local;\n if ( search_direction )\n {\n std::string search_direction_str ( search_direction );\n if ( search_direction_str == \"SearchUp\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::SearchUp;\n }\n else if ( search_direction_str == \"Local\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::Local;\n }\n else if ( search_direction_str == \"SearchDown\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::SearchDown;\n }\n else if ( search_direction_str == \"SearchRoot\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::SearchRoot;\n }\n else if ( search_direction_str == \"SearchParents\" )\n {\n search_direction_enum= sofa::core::objectmodel::BaseContext::SearchParents;\n }\n else\n {\n msg_warning(context) << \"BaseContext_getObjects: Invalid search direction, using 'Local'. Expected: 'SearchUp', 'Local', 'SearchDown', 'SearchRoot', or 'SearchParents'.\" ;\n }\n }\n\n sofa::helper::vector< boost::intrusive_ptr<BaseObject> > list;\n context->get<BaseObject>(&list,search_direction_enum);\n\n PyObject *pyList = PyList_New(0);\n for (size_t i=0; i<list.size(); i++)\n {\n BaseObject* o = list[i].get();\n\n if( !type_name || o->getClass()->hasParent( type_name ) )\n {\n if ( !name || name == o->getName() )\n {\n PyObject* obj=sofa::PythonFactory::toPython(o); \/\/ ref 1\n PyList_Append(pyList,obj); \/\/ ref 2\n Py_DECREF(obj); \/\/ ref 1 (now owned by list)\n }\n }\n }\n\n return pyList;\n}\n\nSP_CLASS_METHODS_BEGIN(BaseContext)\nSP_CLASS_METHOD(BaseContext,getRootContext)\nSP_CLASS_METHOD(BaseContext,getTime)\nSP_CLASS_METHOD(BaseContext,getDt)\nSP_CLASS_METHOD(BaseContext,getGravity)\nSP_CLASS_METHOD(BaseContext,setGravity)\nSP_CLASS_METHOD_KW(BaseContext,createObject)\nSP_CLASS_METHOD_KW(BaseContext,createObject_noWarning) \/\/ deprecated\nSP_CLASS_METHOD_KW(BaseContext,getObject)\nSP_CLASS_METHOD(BaseContext,getObject_noWarning) \/\/ deprecated\nSP_CLASS_METHOD(BaseContext,getObjects)\nSP_CLASS_METHODS_END\n\n\nstatic PyObject * BaseContext_getAttr_animate(PyObject *self, void*)\n{\n BaseContext* obj = get_basecontext( self );\n return PyBool_FromLong(obj->getAnimate());\n}\nstatic int BaseContext_setAttr_animate(PyObject *self, PyObject * args, void*)\n{\n BaseContext* obj = get_basecontext( self );\n if (!PyBool_Check(args))\n {\n PyErr_BadArgument();\n return -1;\n }\n obj->setAnimate(args==Py_True);\n return 0;\n}\n\nstatic PyObject * BaseContext_getAttr_active(PyObject *self, void*)\n{\n BaseContext* obj = get_basecontext( self );\n return PyBool_FromLong(obj->isActive());\n}\n\nstatic int BaseContext_setAttr_active(PyObject *self, PyObject * args, void*)\n{\n BaseContext* obj = get_basecontext( self );\n if (!PyBool_Check(args))\n {\n PyErr_BadArgument();\n return -1;\n }\n obj->setActive(args==Py_True);\n return 0;\n}\n\nSP_CLASS_ATTRS_BEGIN(BaseContext)\nSP_CLASS_ATTR(BaseContext,active)\nSP_CLASS_ATTR(BaseContext,animate)\nSP_CLASS_ATTRS_END\n\nSP_CLASS_TYPE_SPTR_ATTR(BaseContext,BaseContext,Base)\n<|endoftext|>"} {"text":"<commit_before>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"AnnularMeshGenerator.h\"\n#include \"CastUniquePointer.h\"\n\n#include \"libmesh\/replicated_mesh.h\"\n#include \"libmesh\/face_quad4.h\"\n#include \"libmesh\/face_tri3.h\"\n\nregisterMooseObject(\"MooseApp\", AnnularMeshGenerator);\n\ntemplate <>\nInputParameters\nvalidParams<AnnularMeshGenerator>()\n{\n InputParameters params = validParams<MeshGenerator>();\n\n params.addRangeCheckedParam<unsigned int>(\n \"nr\", 1, \"nr>0\", \"Number of elements in the radial direction\");\n params.addRequiredRangeCheckedParam<unsigned int>(\n \"nt\", \"nt>0\", \"Number of elements in the angular direction\");\n params.addRequiredRangeCheckedParam<Real>(\n \"rmin\",\n \"rmin>=0.0\",\n \"Inner radius. If rmin=0 then a disc mesh (with no central hole) will be created.\");\n params.addRequiredParam<Real>(\"rmax\", \"Outer radius\");\n params.addParam<Real>(\"tmin\", 0.0, \"Minimum angle, measured anticlockwise from x axis\");\n params.addParam<Real>(\"tmax\",\n 2 * M_PI,\n \"Maximum angle, measured anticlockwise from x axis. If \"\n \"tmin=0 and tmax=2Pi an annular mesh is created. \"\n \"Otherwise, only a sector of an annulus is created\");\n params.addRangeCheckedParam<Real>(\n \"growth_r\", 1.0, \"growth_r>0.0\", \"The ratio of radial sizes of successive rings of elements\");\n params.addParam<SubdomainID>(\n \"quad_subdomain_id\", 0, \"The subdomain ID given to the QUAD4 elements\");\n params.addParam<SubdomainID>(\"tri_subdomain_id\",\n 1,\n \"The subdomain ID given to the TRI3 elements \"\n \"(these exist only if rmin=0, and they exist \"\n \"at the center of the disc\");\n params.addClassDescription(\"For rmin>0: creates an annular mesh of QUAD4 elements. For rmin=0: \"\n \"creates a disc mesh of QUAD4 and TRI3 elements. Boundary sidesets \"\n \"are created at rmax and rmin, and given these names. If tmin!=0 and \"\n \"tmax!=2Pi, a sector of an annulus or disc is created. In this case \"\n \"boundary sidesets are also created a tmin and tmax, and \"\n \"given these names\");\n\n return params;\n}\n\nAnnularMeshGenerator::AnnularMeshGenerator(const InputParameters & parameters)\n : MeshGenerator(parameters),\n _nr(getParam<unsigned int>(\"nr\")),\n _nt(getParam<unsigned int>(\"nt\")),\n _rmin(getParam<Real>(\"rmin\")),\n _rmax(getParam<Real>(\"rmax\")),\n _tmin(getParam<Real>(\"tmin\")),\n _tmax(getParam<Real>(\"tmax\")),\n _growth_r(getParam<Real>(\"growth_r\")),\n _len(_growth_r == 1.0 ? (_rmax - _rmin) \/ _nr\n : (_rmax - _rmin) * (1.0 - _growth_r) \/ (1.0 - std::pow(_growth_r, _nr))),\n _full_annulus(_tmin == 0.0 && _tmax == 2 * M_PI),\n _quad_subdomain_id(getParam<SubdomainID>(\"quad_subdomain_id\")),\n _tri_subdomain_id(getParam<SubdomainID>(\"tri_subdomain_id\"))\n{\n \/\/ catch likely user errors\n if (_rmax <= _rmin)\n mooseError(\"AnnularMesh: rmax must be greater than rmin\");\n if (_tmax <= _tmin)\n mooseError(\"AnnularMesh: tmax must be greater than tmin\");\n if (_tmax - _tmin > 2 * M_PI)\n mooseError(\"AnnularMesh: tmax - tmin must be <= 2 Pi\");\n if (_nt <= (_tmax - _tmin) \/ M_PI)\n mooseError(\"AnnularMesh: nt must be greater than (tmax - tmin) \/ Pi in order to avoid inverted \"\n \"elements\");\n if (_quad_subdomain_id == _tri_subdomain_id)\n mooseError(\"AnnularMesh: quad_subdomain_id must not equal tri_subdomain_id\");\n}\n\nstd::unique_ptr<MeshBase>\nAnnularMeshGenerator::generate()\n{\n std::unique_ptr<ReplicatedMesh> mesh = libmesh_make_unique<ReplicatedMesh>(comm(), 2);\n\n const Real dt = (_tmax - _tmin) \/ _nt;\n\n mesh->set_mesh_dimension(2);\n mesh->set_spatial_dimension(2);\n BoundaryInfo & boundary_info = mesh->get_boundary_info();\n\n const unsigned num_angular_nodes = (_full_annulus ? _nt : _nt + 1);\n const unsigned num_nodes =\n (_rmin > 0.0 ? (_nr + 1) * num_angular_nodes : _nr * num_angular_nodes + 1);\n const unsigned min_nonzero_layer_num = (_rmin > 0.0 ? 0 : 1);\n std::vector<Node *> nodes(num_nodes);\n unsigned node_id = 0;\n\n \/\/ add nodes at rmax that aren't yet connected to any elements\n Real current_r = _rmax;\n for (unsigned angle_num = 0; angle_num < num_angular_nodes; ++angle_num)\n {\n const Real angle = _tmin + angle_num * dt;\n const Real x = current_r * std::cos(angle);\n const Real y = current_r * std::sin(angle);\n nodes[node_id] = mesh->add_point(Point(x, y, 0.0), node_id);\n node_id++;\n }\n\n \/\/ add nodes at smaller radii, and connect them with elements\n for (unsigned layer_num = _nr; layer_num > min_nonzero_layer_num; --layer_num)\n {\n if (layer_num == 1)\n current_r = _rmin; \/\/ account for precision loss\n else\n current_r -= _len * std::pow(_growth_r, layer_num - 1);\n\n \/\/ add node at angle = _tmin\n nodes[node_id] = mesh->add_point(\n Point(current_r * std::cos(_tmin), current_r * std::sin(_tmin), 0.0), node_id);\n node_id++;\n for (unsigned angle_num = 1; angle_num < num_angular_nodes; ++angle_num)\n {\n const Real angle = _tmin + angle_num * dt;\n const Real x = current_r * std::cos(angle);\n const Real y = current_r * std::sin(angle);\n nodes[node_id] = mesh->add_point(Point(x, y, 0.0), node_id);\n Elem * elem = mesh->add_elem(new Quad4);\n elem->set_node(0) = nodes[node_id];\n elem->set_node(1) = nodes[node_id - 1];\n elem->set_node(2) = nodes[node_id - num_angular_nodes - 1];\n elem->set_node(3) = nodes[node_id - num_angular_nodes];\n elem->subdomain_id() = _quad_subdomain_id;\n node_id++;\n\n if (layer_num == _nr)\n \/\/ add outer boundary (boundary_id = 1)\n boundary_info.add_side(elem, 2, 1);\n if (layer_num == 1)\n \/\/ add inner boundary (boundary_id = 0)\n boundary_info.add_side(elem, 0, 0);\n if (!_full_annulus && angle_num == 1)\n \/\/ add tmin boundary (boundary_id = 2)\n boundary_info.add_side(elem, 1, 2);\n if (!_full_annulus && angle_num == num_angular_nodes - 1)\n \/\/ add tmin boundary (boundary_id = 3)\n boundary_info.add_side(elem, 3, 3);\n }\n if (_full_annulus)\n {\n \/\/ add element connecting to node at angle=0\n Elem * elem = mesh->add_elem(new Quad4);\n elem->set_node(0) = nodes[node_id - num_angular_nodes];\n elem->set_node(1) = nodes[node_id - 1];\n elem->set_node(2) = nodes[node_id - num_angular_nodes - 1];\n elem->set_node(3) = nodes[node_id - 2 * num_angular_nodes];\n elem->subdomain_id() = _quad_subdomain_id;\n\n if (layer_num == _nr)\n \/\/ add outer boundary (boundary_id = 1)\n boundary_info.add_side(elem, 2, 1);\n if (layer_num == 1)\n \/\/ add inner boundary (boundary_id = 0)\n boundary_info.add_side(elem, 0, 0);\n }\n }\n\n \/\/ add single node at origin, if relevant\n if (_rmin == 0.0)\n {\n nodes[node_id] = mesh->add_point(Point(0.0, 0.0, 0.0), node_id);\n boundary_info.add_node(node_id, 0); \/\/ boundary_id=0 is centre\n for (unsigned angle_num = 0; angle_num < num_angular_nodes - 1; ++angle_num)\n {\n Elem * elem = mesh->add_elem(new Tri3);\n elem->set_node(0) = nodes[node_id];\n elem->set_node(1) = nodes[node_id - num_angular_nodes + angle_num];\n elem->set_node(2) = nodes[node_id - num_angular_nodes + angle_num + 1];\n elem->subdomain_id() = _tri_subdomain_id;\n }\n if (_full_annulus)\n {\n Elem * elem = mesh->add_elem(new Tri3);\n elem->set_node(0) = nodes[node_id];\n elem->set_node(1) = nodes[node_id - 1];\n elem->set_node(2) = nodes[node_id - num_angular_nodes];\n elem->subdomain_id() = _tri_subdomain_id;\n }\n }\n\n boundary_info.sideset_name(0) = \"rmin\";\n boundary_info.sideset_name(1) = \"rmax\";\n boundary_info.nodeset_name(0) = \"rmin\";\n boundary_info.nodeset_name(1) = \"rmax\";\n if (!_full_annulus)\n {\n boundary_info.sideset_name(2) = \"tmin\";\n boundary_info.sideset_name(3) = \"tmax\";\n boundary_info.nodeset_name(2) = \"tmin\";\n boundary_info.nodeset_name(3) = \"tmax\";\n }\n\n mesh->prepare_for_use(false);\n\n return dynamic_pointer_cast<MeshBase>(mesh);\n}\n<commit_msg>AnnualMeshes can be DistributedMeshes<commit_after>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"AnnularMeshGenerator.h\"\n#include \"CastUniquePointer.h\"\n\n#include \"libmesh\/replicated_mesh.h\"\n#include \"libmesh\/face_quad4.h\"\n#include \"libmesh\/face_tri3.h\"\n\nregisterMooseObject(\"MooseApp\", AnnularMeshGenerator);\n\ntemplate <>\nInputParameters\nvalidParams<AnnularMeshGenerator>()\n{\n InputParameters params = validParams<MeshGenerator>();\n\n params.addRangeCheckedParam<unsigned int>(\n \"nr\", 1, \"nr>0\", \"Number of elements in the radial direction\");\n params.addRequiredRangeCheckedParam<unsigned int>(\n \"nt\", \"nt>0\", \"Number of elements in the angular direction\");\n params.addRequiredRangeCheckedParam<Real>(\n \"rmin\",\n \"rmin>=0.0\",\n \"Inner radius. If rmin=0 then a disc mesh (with no central hole) will be created.\");\n params.addRequiredParam<Real>(\"rmax\", \"Outer radius\");\n params.addParam<Real>(\"tmin\", 0.0, \"Minimum angle, measured anticlockwise from x axis\");\n params.addParam<Real>(\"tmax\",\n 2 * M_PI,\n \"Maximum angle, measured anticlockwise from x axis. If \"\n \"tmin=0 and tmax=2Pi an annular mesh is created. \"\n \"Otherwise, only a sector of an annulus is created\");\n params.addRangeCheckedParam<Real>(\n \"growth_r\", 1.0, \"growth_r>0.0\", \"The ratio of radial sizes of successive rings of elements\");\n params.addParam<SubdomainID>(\n \"quad_subdomain_id\", 0, \"The subdomain ID given to the QUAD4 elements\");\n params.addParam<SubdomainID>(\"tri_subdomain_id\",\n 1,\n \"The subdomain ID given to the TRI3 elements \"\n \"(these exist only if rmin=0, and they exist \"\n \"at the center of the disc\");\n params.addClassDescription(\"For rmin>0: creates an annular mesh of QUAD4 elements. For rmin=0: \"\n \"creates a disc mesh of QUAD4 and TRI3 elements. Boundary sidesets \"\n \"are created at rmax and rmin, and given these names. If tmin!=0 and \"\n \"tmax!=2Pi, a sector of an annulus or disc is created. In this case \"\n \"boundary sidesets are also created a tmin and tmax, and \"\n \"given these names\");\n\n return params;\n}\n\nAnnularMeshGenerator::AnnularMeshGenerator(const InputParameters & parameters)\n : MeshGenerator(parameters),\n _nr(getParam<unsigned int>(\"nr\")),\n _nt(getParam<unsigned int>(\"nt\")),\n _rmin(getParam<Real>(\"rmin\")),\n _rmax(getParam<Real>(\"rmax\")),\n _tmin(getParam<Real>(\"tmin\")),\n _tmax(getParam<Real>(\"tmax\")),\n _growth_r(getParam<Real>(\"growth_r\")),\n _len(_growth_r == 1.0 ? (_rmax - _rmin) \/ _nr\n : (_rmax - _rmin) * (1.0 - _growth_r) \/ (1.0 - std::pow(_growth_r, _nr))),\n _full_annulus(_tmin == 0.0 && _tmax == 2 * M_PI),\n _quad_subdomain_id(getParam<SubdomainID>(\"quad_subdomain_id\")),\n _tri_subdomain_id(getParam<SubdomainID>(\"tri_subdomain_id\"))\n{\n \/\/ catch likely user errors\n if (_rmax <= _rmin)\n mooseError(\"AnnularMesh: rmax must be greater than rmin\");\n if (_tmax <= _tmin)\n mooseError(\"AnnularMesh: tmax must be greater than tmin\");\n if (_tmax - _tmin > 2 * M_PI)\n mooseError(\"AnnularMesh: tmax - tmin must be <= 2 Pi\");\n if (_nt <= (_tmax - _tmin) \/ M_PI)\n mooseError(\"AnnularMesh: nt must be greater than (tmax - tmin) \/ Pi in order to avoid inverted \"\n \"elements\");\n if (_quad_subdomain_id == _tri_subdomain_id)\n mooseError(\"AnnularMesh: quad_subdomain_id must not equal tri_subdomain_id\");\n}\n\nstd::unique_ptr<MeshBase>\nAnnularMeshGenerator::generate()\n{\n \/\/ Have MOOSE construct the correct libMesh::Mesh object using Mesh block and CLI parameters.\n auto mesh = _mesh->buildMeshBaseObject();\n\n const Real dt = (_tmax - _tmin) \/ _nt;\n\n mesh->set_mesh_dimension(2);\n mesh->set_spatial_dimension(2);\n BoundaryInfo & boundary_info = mesh->get_boundary_info();\n\n const unsigned num_angular_nodes = (_full_annulus ? _nt : _nt + 1);\n const unsigned num_nodes =\n (_rmin > 0.0 ? (_nr + 1) * num_angular_nodes : _nr * num_angular_nodes + 1);\n const unsigned min_nonzero_layer_num = (_rmin > 0.0 ? 0 : 1);\n std::vector<Node *> nodes(num_nodes);\n unsigned node_id = 0;\n\n \/\/ add nodes at rmax that aren't yet connected to any elements\n Real current_r = _rmax;\n for (unsigned angle_num = 0; angle_num < num_angular_nodes; ++angle_num)\n {\n const Real angle = _tmin + angle_num * dt;\n const Real x = current_r * std::cos(angle);\n const Real y = current_r * std::sin(angle);\n nodes[node_id] = mesh->add_point(Point(x, y, 0.0), node_id);\n node_id++;\n }\n\n \/\/ add nodes at smaller radii, and connect them with elements\n for (unsigned layer_num = _nr; layer_num > min_nonzero_layer_num; --layer_num)\n {\n if (layer_num == 1)\n current_r = _rmin; \/\/ account for precision loss\n else\n current_r -= _len * std::pow(_growth_r, layer_num - 1);\n\n \/\/ add node at angle = _tmin\n nodes[node_id] = mesh->add_point(\n Point(current_r * std::cos(_tmin), current_r * std::sin(_tmin), 0.0), node_id);\n node_id++;\n for (unsigned angle_num = 1; angle_num < num_angular_nodes; ++angle_num)\n {\n const Real angle = _tmin + angle_num * dt;\n const Real x = current_r * std::cos(angle);\n const Real y = current_r * std::sin(angle);\n nodes[node_id] = mesh->add_point(Point(x, y, 0.0), node_id);\n Elem * elem = mesh->add_elem(new Quad4);\n elem->set_node(0) = nodes[node_id];\n elem->set_node(1) = nodes[node_id - 1];\n elem->set_node(2) = nodes[node_id - num_angular_nodes - 1];\n elem->set_node(3) = nodes[node_id - num_angular_nodes];\n elem->subdomain_id() = _quad_subdomain_id;\n node_id++;\n\n if (layer_num == _nr)\n \/\/ add outer boundary (boundary_id = 1)\n boundary_info.add_side(elem, 2, 1);\n if (layer_num == 1)\n \/\/ add inner boundary (boundary_id = 0)\n boundary_info.add_side(elem, 0, 0);\n if (!_full_annulus && angle_num == 1)\n \/\/ add tmin boundary (boundary_id = 2)\n boundary_info.add_side(elem, 1, 2);\n if (!_full_annulus && angle_num == num_angular_nodes - 1)\n \/\/ add tmin boundary (boundary_id = 3)\n boundary_info.add_side(elem, 3, 3);\n }\n if (_full_annulus)\n {\n \/\/ add element connecting to node at angle=0\n Elem * elem = mesh->add_elem(new Quad4);\n elem->set_node(0) = nodes[node_id - num_angular_nodes];\n elem->set_node(1) = nodes[node_id - 1];\n elem->set_node(2) = nodes[node_id - num_angular_nodes - 1];\n elem->set_node(3) = nodes[node_id - 2 * num_angular_nodes];\n elem->subdomain_id() = _quad_subdomain_id;\n\n if (layer_num == _nr)\n \/\/ add outer boundary (boundary_id = 1)\n boundary_info.add_side(elem, 2, 1);\n if (layer_num == 1)\n \/\/ add inner boundary (boundary_id = 0)\n boundary_info.add_side(elem, 0, 0);\n }\n }\n\n \/\/ add single node at origin, if relevant\n if (_rmin == 0.0)\n {\n nodes[node_id] = mesh->add_point(Point(0.0, 0.0, 0.0), node_id);\n boundary_info.add_node(node_id, 0); \/\/ boundary_id=0 is centre\n for (unsigned angle_num = 0; angle_num < num_angular_nodes - 1; ++angle_num)\n {\n Elem * elem = mesh->add_elem(new Tri3);\n elem->set_node(0) = nodes[node_id];\n elem->set_node(1) = nodes[node_id - num_angular_nodes + angle_num];\n elem->set_node(2) = nodes[node_id - num_angular_nodes + angle_num + 1];\n elem->subdomain_id() = _tri_subdomain_id;\n }\n if (_full_annulus)\n {\n Elem * elem = mesh->add_elem(new Tri3);\n elem->set_node(0) = nodes[node_id];\n elem->set_node(1) = nodes[node_id - 1];\n elem->set_node(2) = nodes[node_id - num_angular_nodes];\n elem->subdomain_id() = _tri_subdomain_id;\n }\n }\n\n boundary_info.sideset_name(0) = \"rmin\";\n boundary_info.sideset_name(1) = \"rmax\";\n boundary_info.nodeset_name(0) = \"rmin\";\n boundary_info.nodeset_name(1) = \"rmax\";\n if (!_full_annulus)\n {\n boundary_info.sideset_name(2) = \"tmin\";\n boundary_info.sideset_name(3) = \"tmax\";\n boundary_info.nodeset_name(2) = \"tmin\";\n boundary_info.nodeset_name(3) = \"tmax\";\n }\n\n mesh->prepare_for_use(false);\n\n return dynamic_pointer_cast<MeshBase>(mesh);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2004-present Facebook. All Rights Reserved.\n\n#include <array>\n\n#include <folly\/Memory.h>\n#include <folly\/io\/Cursor.h>\n#include <folly\/io\/IOBuf.h>\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n#include \"src\/ConnectionAutomaton.h\"\n#include \"src\/Frame.h\"\n#include \"src\/framed\/FramedDuplexConnection.h\"\n#include \"src\/framed\/FramedWriter.h\"\n#include \"test\/InlineConnection.h\"\n#include \"test\/ReactiveStreamsMocksCompat.h\"\n\nusing namespace ::testing;\nusing namespace ::reactivesocket;\n\nstatic std::unique_ptr<folly::IOBuf> makeInvalidFrameHeader() {\n \/\/ Create a header without the stream id\n folly::IOBufQueue queue(folly::IOBufQueue::cacheChainLength());\n queue.append(folly::IOBuf::create(FrameHeader::kSize - sizeof(StreamId)));\n\n folly::io::QueueAppender appender(&queue, \/* do not grow *\/ 0);\n appender.writeBE<uint16_t>(static_cast<uint16_t>(FrameType::REQUEST_N));\n appender.writeBE<uint16_t>(FrameFlags_EMPTY);\n return queue.move();\n }\n\nTEST(ConnectionAutomatonTest, InvalidFrameHeader) {\n auto automatonConnection = folly::make_unique<InlineConnection>();\n auto testConnection = folly::make_unique<InlineConnection>();\n\n automatonConnection->connectTo(*testConnection);\n\n auto framedAutomatonConnection = folly::make_unique<FramedDuplexConnection>(\n std::move(automatonConnection));\n\n auto framedTestConnection =\n folly::make_unique<FramedDuplexConnection>(std::move(testConnection));\n\n \/\/ Dump 1 invalid frame and expect an error\n\n auto inputSubscription = std::make_shared<MockSubscription>();\n\n Sequence s;\n\n EXPECT_CALL(*inputSubscription, request_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](size_t n) {\n framedTestConnection->getOutput()->onNext(makeInvalidFrameHeader());\n }));\n\n auto testOutputSubscriber = std::make_shared<MockSubscriber<std::unique_ptr<folly::IOBuf>>>();\n EXPECT_CALL(*testOutputSubscriber, onSubscribe_(_))\n .WillOnce(Invoke([&](std::shared_ptr<Subscription> subscription) {\n \/\/ allow receiving frames from the automaton\n subscription->request(std::numeric_limits<size_t>::max());\n }));\n EXPECT_CALL(*testOutputSubscriber, onNext_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](std::unique_ptr<folly::IOBuf>& frame) {\n auto frameType = FrameHeader::peekType(*frame);\n Frame_ERROR error;\n ASSERT_EQ(FrameType::ERROR, frameType);\n ASSERT_TRUE(error.deserializeFrom(std::move(frame)));\n ASSERT_EQ(\"invalid frame\", error.payload_.moveDataToString());\n }));\n EXPECT_CALL(*testOutputSubscriber, onComplete_()).Times(1).InSequence(s);\n EXPECT_CALL(*inputSubscription, cancel_()).Times(1).InSequence(s);\n\n framedTestConnection->setInput(testOutputSubscriber);\n framedTestConnection->getOutput()->onSubscribe(inputSubscription);\n\n auto connectionAutomaton = std::make_shared<ConnectionAutomaton>(\n std::move(framedAutomatonConnection),\n [](StreamId, std::unique_ptr<folly::IOBuf>) { return false; },\n nullptr,\n Stats::noop(),\n false);\n connectionAutomaton->connect();\n}\n\nstatic void terminateTest(bool inOnSubscribe, bool inOnNext, bool inOnComplete, bool inRequest) {\n auto automatonConnection = folly::make_unique<InlineConnection>();\n auto testConnection = folly::make_unique<InlineConnection>();\n\n automatonConnection->connectTo(*testConnection);\n\n auto framedAutomatonConnection = folly::make_unique<FramedDuplexConnection>(\n std::move(automatonConnection));\n\n auto framedTestConnection =\n folly::make_unique<FramedDuplexConnection>(std::move(testConnection));\n\n auto inputSubscription = std::make_shared<MockSubscription>();\n\n Sequence s;\n\n if (inOnSubscribe) {\n EXPECT_CALL(*inputSubscription, request_(_)).Times(0);\n } else {\n EXPECT_CALL(*inputSubscription, request_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](size_t n) {\n if (inRequest) {\n framedTestConnection->getOutput()->onComplete();\n } else {\n framedTestConnection->getOutput()->onNext(makeInvalidFrameHeader());\n }\n }));\n }\n\n auto testOutputSubscriber = std::make_shared<MockSubscriber<std::unique_ptr<folly::IOBuf>>>();\n EXPECT_CALL(*testOutputSubscriber, onSubscribe_(_))\n .WillOnce(Invoke([&](std::shared_ptr<Subscription> subscription) {\n if (inOnSubscribe) {\n subscription->cancel();\n } else {\n \/\/ allow receiving frames from the automaton\n subscription->request(std::numeric_limits<size_t>::max());\n }\n }));\n if (!inOnSubscribe && !inRequest) {\n EXPECT_CALL(*testOutputSubscriber, onNext_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](std::unique_ptr<folly::IOBuf>& frame) {\n if (inOnNext) {\n testOutputSubscriber->subscription()->cancel();\n }\n }));\n }\n EXPECT_CALL(*testOutputSubscriber, onComplete_()).InSequence(s)\n .WillOnce(Invoke([&]() {\n if (inOnComplete) {\n testOutputSubscriber->subscription()->cancel();\n }\n }));\n\n EXPECT_CALL(*inputSubscription, cancel_()).Times(1).InSequence(s);\n\n framedTestConnection->setInput(testOutputSubscriber);\n framedTestConnection->getOutput()->onSubscribe(inputSubscription);\n\n auto connectionAutomaton = std::make_shared<ConnectionAutomaton>(\n std::move(framedAutomatonConnection),\n [](StreamId, std::unique_ptr<folly::IOBuf>) { return false; },\n nullptr,\n Stats::noop(),\n false);\n connectionAutomaton->connect();\n}\n\nTEST(ConnectionAutomatonTest, CleanTerminateOnSubscribe) {\n terminateTest(true, false, false, false);\n}\n\nTEST(ConnectionAutomatonTest, CleanTerminateOnNext) {\n terminateTest(false, true, false, false);\n}\n\nTEST(ConnectionAutomatonTest, CleanTerminateOnComplete) {\n terminateTest(true, true, true, false);\n}\n\nTEST(ConnectionAutomatonTest, CleanTerminateRequest) {\n terminateTest(false, true, false, true);\n}\n\nTEST(ConnectionAutomatonTest, RefuseFrame) {\n auto automatonConnection = folly::make_unique<InlineConnection>();\n auto testConnection = folly::make_unique<InlineConnection>();\n\n automatonConnection->connectTo(*testConnection);\n\n auto framedAutomatonConnection = folly::make_unique<FramedDuplexConnection>(\n std::move(automatonConnection));\n\n auto framedTestConnection =\n folly::make_unique<FramedDuplexConnection>(std::move(testConnection));\n\n \/\/ dump 3 frames to ConnectionAutomaton\n \/\/ the first frame should be refused and the connection closed\n \/\/ the last 2 frames should be ignored\n \/\/ everything should die gracefully\n\n static const int streamId = 1;\n auto inputSubscription = std::make_shared<MockSubscription>();\n\n Sequence s;\n\n auto testOutputSubscriber = std::make_shared<MockSubscriber<std::unique_ptr<folly::IOBuf>>>();\n EXPECT_CALL(*testOutputSubscriber, onSubscribe_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](std::shared_ptr<Subscription> subscription) {\n \/\/ allow receiving frames from the automaton\n subscription->request(std::numeric_limits<size_t>::max());\n }));\n\n EXPECT_CALL(*inputSubscription, request_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](size_t n) {\n auto framedWriter = std::dynamic_pointer_cast<FramedWriter>(framedTestConnection->getOutput());\n CHECK(framedWriter);\n\n std::vector<std::unique_ptr<folly::IOBuf>> frames;\n frames.push_back(Frame_REQUEST_N(streamId, 1).serializeOut());\n frames.push_back(Frame_REQUEST_N(streamId + 1, 1).serializeOut());\n frames.push_back(Frame_REQUEST_N(streamId + 2, 1).serializeOut());\n\n framedWriter->onNextMultiple(std::move(frames));\n }));\n EXPECT_CALL(*testOutputSubscriber, onNext_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](std::unique_ptr<folly::IOBuf>& frame) {\n auto frameType = FrameHeader::peekType(*frame);\n ASSERT_EQ(FrameType::ERROR, frameType);\n }));\n EXPECT_CALL(*testOutputSubscriber, onComplete_()).Times(1).InSequence(s);\n EXPECT_CALL(*inputSubscription, cancel_()).Times(1).InSequence(s);\n\n framedTestConnection->setInput(testOutputSubscriber);\n framedTestConnection->getOutput()->onSubscribe(inputSubscription);\n\n auto connectionAutomaton = std::make_shared<ConnectionAutomaton>(\n std::move(framedAutomatonConnection),\n [](StreamId, std::unique_ptr<folly::IOBuf>) { return false; },\n nullptr,\n Stats::noop(),\n false);\n connectionAutomaton->connect();\n new int;\n}\n<commit_msg>disable Sequence in InvalidFrameHeader unit test<commit_after>\/\/ Copyright 2004-present Facebook. All Rights Reserved.\n\n#include <array>\n\n#include <folly\/Memory.h>\n#include <folly\/io\/Cursor.h>\n#include <folly\/io\/IOBuf.h>\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n#include \"src\/ConnectionAutomaton.h\"\n#include \"src\/Frame.h\"\n#include \"src\/framed\/FramedDuplexConnection.h\"\n#include \"src\/framed\/FramedWriter.h\"\n#include \"test\/InlineConnection.h\"\n#include \"test\/ReactiveStreamsMocksCompat.h\"\n\nusing namespace ::testing;\nusing namespace ::reactivesocket;\n\nstatic std::unique_ptr<folly::IOBuf> makeInvalidFrameHeader() {\n \/\/ Create a header without the stream id\n folly::IOBufQueue queue(folly::IOBufQueue::cacheChainLength());\n queue.append(folly::IOBuf::create(FrameHeader::kSize - sizeof(StreamId)));\n\n folly::io::QueueAppender appender(&queue, \/* do not grow *\/ 0);\n appender.writeBE<uint16_t>(static_cast<uint16_t>(FrameType::REQUEST_N));\n appender.writeBE<uint16_t>(FrameFlags_EMPTY);\n return queue.move();\n }\n\nTEST(ConnectionAutomatonTest, InvalidFrameHeader) {\n auto automatonConnection = folly::make_unique<InlineConnection>();\n auto testConnection = folly::make_unique<InlineConnection>();\n\n automatonConnection->connectTo(*testConnection);\n\n auto framedAutomatonConnection = folly::make_unique<FramedDuplexConnection>(\n std::move(automatonConnection));\n\n auto framedTestConnection =\n folly::make_unique<FramedDuplexConnection>(std::move(testConnection));\n\n \/\/ Dump 1 invalid frame and expect an error\n\n auto inputSubscription = std::make_shared<MockSubscription>();\n\n \/\/ TODO: enable Sequence..\n \/\/Sequence s;\n\n EXPECT_CALL(*inputSubscription, request_(_))\n\/\/ .InSequence(s)\n .WillOnce(Invoke([&](size_t n) {\n framedTestConnection->getOutput()->onNext(makeInvalidFrameHeader());\n }));\n\n auto testOutputSubscriber = std::make_shared<MockSubscriber<std::unique_ptr<folly::IOBuf>>>();\n EXPECT_CALL(*testOutputSubscriber, onSubscribe_(_))\n .WillOnce(Invoke([&](std::shared_ptr<Subscription> subscription) {\n \/\/ allow receiving frames from the automaton\n subscription->request(std::numeric_limits<size_t>::max());\n }));\n EXPECT_CALL(*testOutputSubscriber, onNext_(_))\n\/\/ .InSequence(s)\n .WillOnce(Invoke([&](std::unique_ptr<folly::IOBuf>& frame) {\n auto frameType = FrameHeader::peekType(*frame);\n Frame_ERROR error;\n ASSERT_EQ(FrameType::ERROR, frameType);\n ASSERT_TRUE(error.deserializeFrom(std::move(frame)));\n ASSERT_EQ(\"invalid frame\", error.payload_.moveDataToString());\n }));\n EXPECT_CALL(*testOutputSubscriber, onComplete_()).Times(1)\/*.InSequence(s)*\/;\n EXPECT_CALL(*inputSubscription, cancel_()).Times(1)\/*.InSequence(s)*\/;\n\n framedTestConnection->setInput(testOutputSubscriber);\n framedTestConnection->getOutput()->onSubscribe(inputSubscription);\n\n auto connectionAutomaton = std::make_shared<ConnectionAutomaton>(\n std::move(framedAutomatonConnection),\n [](StreamId, std::unique_ptr<folly::IOBuf>) { return false; },\n nullptr,\n Stats::noop(),\n false);\n connectionAutomaton->connect();\n}\n\nstatic void terminateTest(bool inOnSubscribe, bool inOnNext, bool inOnComplete, bool inRequest) {\n auto automatonConnection = folly::make_unique<InlineConnection>();\n auto testConnection = folly::make_unique<InlineConnection>();\n\n automatonConnection->connectTo(*testConnection);\n\n auto framedAutomatonConnection = folly::make_unique<FramedDuplexConnection>(\n std::move(automatonConnection));\n\n auto framedTestConnection =\n folly::make_unique<FramedDuplexConnection>(std::move(testConnection));\n\n auto inputSubscription = std::make_shared<MockSubscription>();\n\n Sequence s;\n\n if (inOnSubscribe) {\n EXPECT_CALL(*inputSubscription, request_(_)).Times(0);\n } else {\n EXPECT_CALL(*inputSubscription, request_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](size_t n) {\n if (inRequest) {\n framedTestConnection->getOutput()->onComplete();\n } else {\n framedTestConnection->getOutput()->onNext(makeInvalidFrameHeader());\n }\n }));\n }\n\n auto testOutputSubscriber = std::make_shared<MockSubscriber<std::unique_ptr<folly::IOBuf>>>();\n EXPECT_CALL(*testOutputSubscriber, onSubscribe_(_))\n .WillOnce(Invoke([&](std::shared_ptr<Subscription> subscription) {\n if (inOnSubscribe) {\n subscription->cancel();\n } else {\n \/\/ allow receiving frames from the automaton\n subscription->request(std::numeric_limits<size_t>::max());\n }\n }));\n if (!inOnSubscribe && !inRequest) {\n EXPECT_CALL(*testOutputSubscriber, onNext_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](std::unique_ptr<folly::IOBuf>& frame) {\n if (inOnNext) {\n testOutputSubscriber->subscription()->cancel();\n }\n }));\n }\n EXPECT_CALL(*testOutputSubscriber, onComplete_()).InSequence(s)\n .WillOnce(Invoke([&]() {\n if (inOnComplete) {\n testOutputSubscriber->subscription()->cancel();\n }\n }));\n\n EXPECT_CALL(*inputSubscription, cancel_()).Times(1).InSequence(s);\n\n framedTestConnection->setInput(testOutputSubscriber);\n framedTestConnection->getOutput()->onSubscribe(inputSubscription);\n\n auto connectionAutomaton = std::make_shared<ConnectionAutomaton>(\n std::move(framedAutomatonConnection),\n [](StreamId, std::unique_ptr<folly::IOBuf>) { return false; },\n nullptr,\n Stats::noop(),\n false);\n connectionAutomaton->connect();\n}\n\nTEST(ConnectionAutomatonTest, CleanTerminateOnSubscribe) {\n terminateTest(true, false, false, false);\n}\n\nTEST(ConnectionAutomatonTest, CleanTerminateOnNext) {\n terminateTest(false, true, false, false);\n}\n\nTEST(ConnectionAutomatonTest, CleanTerminateOnComplete) {\n terminateTest(true, true, true, false);\n}\n\nTEST(ConnectionAutomatonTest, CleanTerminateRequest) {\n terminateTest(false, true, false, true);\n}\n\nTEST(ConnectionAutomatonTest, RefuseFrame) {\n auto automatonConnection = folly::make_unique<InlineConnection>();\n auto testConnection = folly::make_unique<InlineConnection>();\n\n automatonConnection->connectTo(*testConnection);\n\n auto framedAutomatonConnection = folly::make_unique<FramedDuplexConnection>(\n std::move(automatonConnection));\n\n auto framedTestConnection =\n folly::make_unique<FramedDuplexConnection>(std::move(testConnection));\n\n \/\/ dump 3 frames to ConnectionAutomaton\n \/\/ the first frame should be refused and the connection closed\n \/\/ the last 2 frames should be ignored\n \/\/ everything should die gracefully\n\n static const int streamId = 1;\n auto inputSubscription = std::make_shared<MockSubscription>();\n\n Sequence s;\n\n auto testOutputSubscriber = std::make_shared<MockSubscriber<std::unique_ptr<folly::IOBuf>>>();\n EXPECT_CALL(*testOutputSubscriber, onSubscribe_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](std::shared_ptr<Subscription> subscription) {\n \/\/ allow receiving frames from the automaton\n subscription->request(std::numeric_limits<size_t>::max());\n }));\n\n EXPECT_CALL(*inputSubscription, request_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](size_t n) {\n auto framedWriter = std::dynamic_pointer_cast<FramedWriter>(framedTestConnection->getOutput());\n CHECK(framedWriter);\n\n std::vector<std::unique_ptr<folly::IOBuf>> frames;\n frames.push_back(Frame_REQUEST_N(streamId, 1).serializeOut());\n frames.push_back(Frame_REQUEST_N(streamId + 1, 1).serializeOut());\n frames.push_back(Frame_REQUEST_N(streamId + 2, 1).serializeOut());\n\n framedWriter->onNextMultiple(std::move(frames));\n }));\n EXPECT_CALL(*testOutputSubscriber, onNext_(_))\n .InSequence(s)\n .WillOnce(Invoke([&](std::unique_ptr<folly::IOBuf>& frame) {\n auto frameType = FrameHeader::peekType(*frame);\n ASSERT_EQ(FrameType::ERROR, frameType);\n }));\n EXPECT_CALL(*testOutputSubscriber, onComplete_()).Times(1).InSequence(s);\n EXPECT_CALL(*inputSubscription, cancel_()).Times(1).InSequence(s);\n\n framedTestConnection->setInput(testOutputSubscriber);\n framedTestConnection->getOutput()->onSubscribe(inputSubscription);\n\n auto connectionAutomaton = std::make_shared<ConnectionAutomaton>(\n std::move(framedAutomatonConnection),\n [](StreamId, std::unique_ptr<folly::IOBuf>) { return false; },\n nullptr,\n Stats::noop(),\n false);\n connectionAutomaton->connect();\n new int;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/base:$Id$\n\/\/ Author: Rene Brun 05\/02\/2007\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TVirtualStreamerInfo Abstract Interface class \/\/\n\/\/ \/\/\n\/\/ Abstract Interface describing Streamer information for one class. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TClass.h\"\n#include \"TVirtualMutex.h\"\n#include \"TInterpreter.h\"\n#include \"TVirtualStreamerInfo.h\"\n#include \"TPluginManager.h\"\n#include \"TStreamerElement.h\"\n#include \"TError.h\"\n\n\nTVirtualStreamerInfo *TVirtualStreamerInfo::fgInfoFactory = 0;\n\nBool_t TVirtualStreamerInfo::fgCanDelete = kTRUE;\nBool_t TVirtualStreamerInfo::fgOptimize = kTRUE;\nBool_t TVirtualStreamerInfo::fgStreamMemberWise = kTRUE;\n\nClassImp(TVirtualStreamerInfo)\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo::TVirtualStreamerInfo() : fOptimized(kFALSE), fIsBuilt(kFALSE)\n{\n \/\/ Default constructor.\n\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo::TVirtualStreamerInfo(TClass *cl)\n : TNamed(cl->GetName(),\"\"), fOptimized(kFALSE), fIsBuilt(kFALSE)\n{\n \/\/ Default constructor.\n\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo::TVirtualStreamerInfo(const TVirtualStreamerInfo& info)\n : TNamed(info), fOptimized(kFALSE), fIsBuilt(kFALSE)\n{ \n \/\/copy constructor\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo& TVirtualStreamerInfo::operator=(const TVirtualStreamerInfo& info)\n{\n \/\/assignment operator\n if(this!=&info) {\n TNamed::operator=(info);\n } \n return *this;\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo::~TVirtualStreamerInfo()\n{\n \/\/ Destructor\n\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualStreamerInfo::CanDelete()\n{\n \/\/ static function returning true if ReadBuffer can delete object\n return fgCanDelete;\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualStreamerInfo::CanOptimize()\n{\n \/\/ static function returning true if optimization can be on\n return fgOptimize;\n}\n\n\/\/______________________________________________________________________________\nconst char *TVirtualStreamerInfo::GetElementCounterStart(const char *dmTitle)\n{\n \/\/ Given a comment\/title declaring an array counter, for example:\n \/\/ \/\/[fArraySize] array of size fArraySize\n \/\/ return the start of the array dimension declaration start in the string\n \/\/ (so the location of the 'f'.\n\n for (const char *lbracket = dmTitle; *lbracket; ++lbracket) {\n \/\/ = ::strchr(dmTitle, '[');\n if ( (*lbracket) == '[' ) return lbracket;\n if ( (*lbracket) != '\/' && !isspace(*lbracket) ) {\n \/\/ Allow only comment delimiters and white spaces\n \/\/ before the array information.\n return 0;\n }\n }\n return 0;\n}\n\n\/\/______________________________________________________________________________\nTStreamerBasicType *TVirtualStreamerInfo::GetElementCounter(const char *countName, TClass *cl)\n{\n \/\/ Get pointer to a TStreamerBasicType in TClass *cl\n \/\/static function\n\n<<<<<<< HEAD\n const TObjArray *sinfos = cl->GetStreamerInfos();\n TVirtualStreamerInfo *info = (TVirtualStreamerInfo *)sinfos->At(cl->GetClassVersion());\n=======\n TVirtualStreamerInfo *info;\n {\n R__LOCKGUARD(gInterpreterMutex);\n TObjArray *sinfos = cl->GetStreamerInfos();\n info = (TVirtualStreamerInfo *)sinfos->At(cl->GetClassVersion());\n }\n>>>>>>> 55252ea... Protected threaded access to TClass::GetStreamerInfos()\n\n if (!info || !info->IsBuilt()) {\n \/\/ Even if the streamerInfo exist, it could still need to be 'build'\n \/\/ It is important to figure this out, because\n \/\/ a) if it is not build, we need to build\n \/\/ b) if is build, we should not build it (or we could end up in an\n \/\/ infinite loop, if the element and its counter are in the same\n \/\/ class!\n\n info = cl->GetStreamerInfo();\n }\n if (!info) return 0;\n TStreamerElement *element = (TStreamerElement *)info->GetElements()->FindObject(countName);\n if (!element) return 0;\n if (element->IsA() == TStreamerBasicType::Class()) return (TStreamerBasicType*)element;\n return 0;\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualStreamerInfo::GetStreamMemberWise()\n{\n \/\/ Return whether the TStreamerInfos will save the collections in\n \/\/ \"member-wise\" order whenever possible. The default is to store member-wise.\n \/\/ kTRUE indicates member-wise storing\n \/\/ kFALSE inddicates object-wise storing\n \/\/\n \/\/ A collection can be saved member wise when it contain is guaranteed to be\n \/\/ homogeneous. For example std::vector<THit> can be stored member wise,\n \/\/ while std::vector<THit*> can not (possible use of polymorphism).\n\n return fgStreamMemberWise;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualStreamerInfo::Optimize(Bool_t opt)\n{\n \/\/ This is a static function.\n \/\/ Set optimization option.\n \/\/ When this option is activated (default), consecutive data members\n \/\/ of the same type are merged into an array (faster).\n \/\/ Optimization must be off in TTree split mode.\n\n fgOptimize = opt;\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo *TVirtualStreamerInfo::Factory()\n{\n \/\/ Static function returning a pointer to a new TVirtualStreamerInfo object.\n \/\/ If the Info factory does not exist, it is created via the plugin manager.\n \/\/ In reality the factory is an empty TStreamerInfo object.\n\n if (!fgInfoFactory) {\n TPluginHandler *h;\n if ((h = gROOT->GetPluginManager()->FindHandler(\"TVirtualStreamerInfo\",\"TStreamerInfo\"))) {\n if (h->LoadPlugin() == -1) {\n ::Fatal(\"TVirtualStreamerInfo::Factory\",\n \"The plugin handler for TVirtualStreamerInfo was found but failed to load!\");\n } \n fgInfoFactory = (TVirtualStreamerInfo*) h->ExecPlugin(0);\n if (fgInfoFactory == 0) {\n ::Fatal(\"TVirtualStreamerInfo::Factory\",\n \"The plugin handler for TVirtualStreamerInfo was found but failed to create the factory object!\");\n }\n } else {\n TString filename(\"$ROOTSYS\/etc\/plugins\/TVirtualStreamerInfo\");\n gSystem->ExpandPathName(filename);\n if (gSystem->AccessPathName(filename)) { \n ::Fatal(\"TVirtualStreamerInfo::Factory\",\n \"Cannot find the plugin handler for TVirtualStreamerInfo! \"\n \"$ROOTSYS\/etc\/plugins\/TVirtualStreamerInfo does not exist \"\n \"or is inaccessible.\");\n } else {\n ::Fatal(\"TVirtualStreamerInfo::Factory\",\n \"Cannot find the plugin handler for TVirtualStreamerInfo! \"\n \"However $ROOTSYS\/etc\/plugins\/TVirtualStreamerInfo is accessible, \"\n \"Check the content of this directory!\");\n }\n }\n }\n\n return fgInfoFactory;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualStreamerInfo::SetCanDelete(Bool_t opt)\n{\n \/\/ This is a static function.\n \/\/ Set object delete option.\n \/\/ When this option is activated (default), ReadBuffer automatically\n \/\/ delete objects when a data member is a pointer to an object.\n \/\/ If your constructor is not presetting pointers to 0, you must\n \/\/ call this static function TStreamerInfo::SetCanDelete(kFALSE);\n\n fgCanDelete = opt;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualStreamerInfo::SetFactory(TVirtualStreamerInfo *factory)\n{\n \/\/static function: Set the StreamerInfo factory\n fgInfoFactory = factory;\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualStreamerInfo::SetStreamMemberWise(Bool_t enable)\n{\n \/\/ Set whether the TStreamerInfos will save the collections in\n \/\/ \"member-wise\" order whenever possible. The default is to store member-wise.\n \/\/ kTRUE indicates member-wise storing\n \/\/ kFALSE inddicates object-wise storing\n \/\/ This function returns the previous value of fgStreamMemberWise.\n\n \/\/ A collection can be saved member wise when it contain is guaranteed to be\n \/\/ homogeneous. For example std::vector<THit> can be stored member wise,\n \/\/ while std::vector<THit*> can not (possible use of polymorphism).\n\n Bool_t prev = fgStreamMemberWise;\n fgStreamMemberWise = enable;\n return prev;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualStreamerInfo::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TVirtualStreamerInfo.\n\n TNamed::Streamer(R__b);\n}\n<commit_msg>Finish conflict resolution<commit_after>\/\/ @(#)root\/base:$Id$\n\/\/ Author: Rene Brun 05\/02\/2007\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TVirtualStreamerInfo Abstract Interface class \/\/\n\/\/ \/\/\n\/\/ Abstract Interface describing Streamer information for one class. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TClass.h\"\n#include \"TVirtualMutex.h\"\n#include \"TInterpreter.h\"\n#include \"TVirtualStreamerInfo.h\"\n#include \"TPluginManager.h\"\n#include \"TStreamerElement.h\"\n#include \"TError.h\"\n\n\nTVirtualStreamerInfo *TVirtualStreamerInfo::fgInfoFactory = 0;\n\nBool_t TVirtualStreamerInfo::fgCanDelete = kTRUE;\nBool_t TVirtualStreamerInfo::fgOptimize = kTRUE;\nBool_t TVirtualStreamerInfo::fgStreamMemberWise = kTRUE;\n\nClassImp(TVirtualStreamerInfo)\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo::TVirtualStreamerInfo() : fOptimized(kFALSE), fIsBuilt(kFALSE)\n{\n \/\/ Default constructor.\n\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo::TVirtualStreamerInfo(TClass *cl)\n : TNamed(cl->GetName(),\"\"), fOptimized(kFALSE), fIsBuilt(kFALSE)\n{\n \/\/ Default constructor.\n\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo::TVirtualStreamerInfo(const TVirtualStreamerInfo& info)\n : TNamed(info), fOptimized(kFALSE), fIsBuilt(kFALSE)\n{ \n \/\/copy constructor\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo& TVirtualStreamerInfo::operator=(const TVirtualStreamerInfo& info)\n{\n \/\/assignment operator\n if(this!=&info) {\n TNamed::operator=(info);\n } \n return *this;\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo::~TVirtualStreamerInfo()\n{\n \/\/ Destructor\n\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualStreamerInfo::CanDelete()\n{\n \/\/ static function returning true if ReadBuffer can delete object\n return fgCanDelete;\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualStreamerInfo::CanOptimize()\n{\n \/\/ static function returning true if optimization can be on\n return fgOptimize;\n}\n\n\/\/______________________________________________________________________________\nconst char *TVirtualStreamerInfo::GetElementCounterStart(const char *dmTitle)\n{\n \/\/ Given a comment\/title declaring an array counter, for example:\n \/\/ \/\/[fArraySize] array of size fArraySize\n \/\/ return the start of the array dimension declaration start in the string\n \/\/ (so the location of the 'f'.\n\n for (const char *lbracket = dmTitle; *lbracket; ++lbracket) {\n \/\/ = ::strchr(dmTitle, '[');\n if ( (*lbracket) == '[' ) return lbracket;\n if ( (*lbracket) != '\/' && !isspace(*lbracket) ) {\n \/\/ Allow only comment delimiters and white spaces\n \/\/ before the array information.\n return 0;\n }\n }\n return 0;\n}\n\n\/\/______________________________________________________________________________\nTStreamerBasicType *TVirtualStreamerInfo::GetElementCounter(const char *countName, TClass *cl)\n{\n \/\/ Get pointer to a TStreamerBasicType in TClass *cl\n \/\/static function\n\n TVirtualStreamerInfo *info;\n {\n R__LOCKGUARD(gInterpreterMutex);\n const TObjArray *sinfos = cl->GetStreamerInfos();\n info = (TVirtualStreamerInfo *)sinfos->At(cl->GetClassVersion());\n }\n\n if (!info || !info->IsBuilt()) {\n \/\/ Even if the streamerInfo exist, it could still need to be 'build'\n \/\/ It is important to figure this out, because\n \/\/ a) if it is not build, we need to build\n \/\/ b) if is build, we should not build it (or we could end up in an\n \/\/ infinite loop, if the element and its counter are in the same\n \/\/ class!\n\n info = cl->GetStreamerInfo();\n }\n if (!info) return 0;\n TStreamerElement *element = (TStreamerElement *)info->GetElements()->FindObject(countName);\n if (!element) return 0;\n if (element->IsA() == TStreamerBasicType::Class()) return (TStreamerBasicType*)element;\n return 0;\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualStreamerInfo::GetStreamMemberWise()\n{\n \/\/ Return whether the TStreamerInfos will save the collections in\n \/\/ \"member-wise\" order whenever possible. The default is to store member-wise.\n \/\/ kTRUE indicates member-wise storing\n \/\/ kFALSE inddicates object-wise storing\n \/\/\n \/\/ A collection can be saved member wise when it contain is guaranteed to be\n \/\/ homogeneous. For example std::vector<THit> can be stored member wise,\n \/\/ while std::vector<THit*> can not (possible use of polymorphism).\n\n return fgStreamMemberWise;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualStreamerInfo::Optimize(Bool_t opt)\n{\n \/\/ This is a static function.\n \/\/ Set optimization option.\n \/\/ When this option is activated (default), consecutive data members\n \/\/ of the same type are merged into an array (faster).\n \/\/ Optimization must be off in TTree split mode.\n\n fgOptimize = opt;\n}\n\n\/\/______________________________________________________________________________\nTVirtualStreamerInfo *TVirtualStreamerInfo::Factory()\n{\n \/\/ Static function returning a pointer to a new TVirtualStreamerInfo object.\n \/\/ If the Info factory does not exist, it is created via the plugin manager.\n \/\/ In reality the factory is an empty TStreamerInfo object.\n\n if (!fgInfoFactory) {\n TPluginHandler *h;\n if ((h = gROOT->GetPluginManager()->FindHandler(\"TVirtualStreamerInfo\",\"TStreamerInfo\"))) {\n if (h->LoadPlugin() == -1) {\n ::Fatal(\"TVirtualStreamerInfo::Factory\",\n \"The plugin handler for TVirtualStreamerInfo was found but failed to load!\");\n } \n fgInfoFactory = (TVirtualStreamerInfo*) h->ExecPlugin(0);\n if (fgInfoFactory == 0) {\n ::Fatal(\"TVirtualStreamerInfo::Factory\",\n \"The plugin handler for TVirtualStreamerInfo was found but failed to create the factory object!\");\n }\n } else {\n TString filename(\"$ROOTSYS\/etc\/plugins\/TVirtualStreamerInfo\");\n gSystem->ExpandPathName(filename);\n if (gSystem->AccessPathName(filename)) { \n ::Fatal(\"TVirtualStreamerInfo::Factory\",\n \"Cannot find the plugin handler for TVirtualStreamerInfo! \"\n \"$ROOTSYS\/etc\/plugins\/TVirtualStreamerInfo does not exist \"\n \"or is inaccessible.\");\n } else {\n ::Fatal(\"TVirtualStreamerInfo::Factory\",\n \"Cannot find the plugin handler for TVirtualStreamerInfo! \"\n \"However $ROOTSYS\/etc\/plugins\/TVirtualStreamerInfo is accessible, \"\n \"Check the content of this directory!\");\n }\n }\n }\n\n return fgInfoFactory;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualStreamerInfo::SetCanDelete(Bool_t opt)\n{\n \/\/ This is a static function.\n \/\/ Set object delete option.\n \/\/ When this option is activated (default), ReadBuffer automatically\n \/\/ delete objects when a data member is a pointer to an object.\n \/\/ If your constructor is not presetting pointers to 0, you must\n \/\/ call this static function TStreamerInfo::SetCanDelete(kFALSE);\n\n fgCanDelete = opt;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualStreamerInfo::SetFactory(TVirtualStreamerInfo *factory)\n{\n \/\/static function: Set the StreamerInfo factory\n fgInfoFactory = factory;\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualStreamerInfo::SetStreamMemberWise(Bool_t enable)\n{\n \/\/ Set whether the TStreamerInfos will save the collections in\n \/\/ \"member-wise\" order whenever possible. The default is to store member-wise.\n \/\/ kTRUE indicates member-wise storing\n \/\/ kFALSE inddicates object-wise storing\n \/\/ This function returns the previous value of fgStreamMemberWise.\n\n \/\/ A collection can be saved member wise when it contain is guaranteed to be\n \/\/ homogeneous. For example std::vector<THit> can be stored member wise,\n \/\/ while std::vector<THit*> can not (possible use of polymorphism).\n\n Bool_t prev = fgStreamMemberWise;\n fgStreamMemberWise = enable;\n return prev;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualStreamerInfo::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TVirtualStreamerInfo.\n\n TNamed::Streamer(R__b);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <list>\n\nusing namespace std;\n\n\n\/\/list<int> foo1();\n\/\/list<double> foo2();\n\n\nvoid foo3(list<float>);\n<commit_msg>removal of accidentally added file<commit_after><|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * [ Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer) ]\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include <test\/unoapi_test.hxx>\n\n#include <com\/sun\/star\/sheet\/XSpreadsheetDocument.hpp>\n#include <com\/sun\/star\/sheet\/XSpreadsheet.hpp>\n#include <com\/sun\/star\/sheet\/XCellRangesQuery.hpp>\n#include <com\/sun\/star\/sheet\/XSheetCellRanges.hpp>\n#include <com\/sun\/star\/table\/CellAddress.hpp>\n#include <com\/sun\/star\/sheet\/CellFlags.hpp>\n\nusing namespace com::sun::star;\n\n\nnamespace ScCellRangeBase {\n\nclass ScXCellRangesQuery : public UnoApiTest\n{\npublic:\n ScXCellRangesQuery();\n\n uno::Reference<sheet::XCellRangesQuery> init();\n\n \/\/Testcases\n void testQueryColumnDifference();\n void testQueryContentDifference();\n void testQueryEmptyCells();\n void testQueryFormulaCells();\n void testQueryIntersection();\n void testQueryRowDifference();\n void testQueryVisibleCells();\n\n CPPUNIT_TEST_SUITE(ScXCellRangesQuery);\n CPPUNIT_TEST(testQueryColumnDifference);\n CPPUNIT_TEST(testQueryContentDifference);\n CPPUNIT_TEST(testQueryEmptyCells);\n \/\/looks broken\n \/\/CPPUNIT_TEST(testQueryFormulaCells);\n CPPUNIT_TEST(testQueryIntersection);\n CPPUNIT_TEST(testQueryRowDifference);\n CPPUNIT_TEST_SUITE_END();\n\n};\n\nScXCellRangesQuery::ScXCellRangesQuery()\n{\n\n}\n\nuno::Reference<sheet::XCellRangesQuery> ScXCellRangesQuery::init()\n{\n rtl::OUString aFileURL;\n const rtl::OUString aFileBase(RTL_CONSTASCII_USTRINGPARAM(\"xcellrangesquery.ods\"));\n createFileURL(aFileBase, aFileURL);\n std::cout << rtl::OUStringToOString(aFileURL, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n static uno::Reference< lang::XComponent > xComponent;\n if( !xComponent.is())\n xComponent = loadFromDesktop(aFileURL);\n uno::Reference< sheet::XSpreadsheetDocument> xDoc (xComponent, UNO_QUERY_THROW);\n uno::Reference< container::XIndexAccess > xIndex (xDoc->getSheets(), UNO_QUERY_THROW);\n uno::Reference< sheet::XSpreadsheet > xSheet( xIndex->getByIndex(0), UNO_QUERY_THROW);\n\n CPPUNIT_ASSERT_MESSAGE(\"Could not create interface of type XSpreadsheet\", xSheet.is());\n\n uno::Reference<sheet::XCellRangesQuery> xReturn(xSheet->getCellRangeByPosition(0,0,3,4), UNO_QUERY_THROW);\n\n CPPUNIT_ASSERT_MESSAGE(\"Could not create object of type XCellRangesQuery\", xReturn.is());\n return xReturn;\n}\n\nvoid ScXCellRangesQuery::testQueryColumnDifference()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.B1:C1,Sheet1.B3:C5\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryColumnDifferences(table::CellAddress(0, 1, 1));\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryColumnDifference: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryColumnDifference\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryContentDifference()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.B2:B3\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryContentCells(sheet::CellFlags::VALUE);\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryContentDifference: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryContentDifference\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryEmptyCells()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.A1:A5,Sheet1.B1:C1,Sheet1.B5,Sheet1.C3:C5,Sheet1.D1:D5\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryEmptyCells();\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryEmptyCells: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryEmptyCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryFormulaCells()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.C2\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryFormulaCells(sheet::CellFlags::FORMULA);\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryFormulaCells: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryFormulaCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryIntersection()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.D4:D5\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryIntersection(table::CellRangeAddress(0,3,3,7,7));\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryIntersection: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryFormulaCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryRowDifference()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.A2:A4,Sheet1.C2:D4\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryRowDifferences(table::CellAddress(0,1,1));\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryRowDifference: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryFormulaCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryVisibleCells()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.A2\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryVisibleCells();\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryVisibleCells: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryFormulaCells\", aResult == aExpected);\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(ScXCellRangesQuery);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>terminate xcellrangesquery correctly<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * [ Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer) ]\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include <test\/unoapi_test.hxx>\n\n#include <com\/sun\/star\/sheet\/XSpreadsheetDocument.hpp>\n#include <com\/sun\/star\/sheet\/XSpreadsheet.hpp>\n#include <com\/sun\/star\/sheet\/XCellRangesQuery.hpp>\n#include <com\/sun\/star\/sheet\/XSheetCellRanges.hpp>\n#include <com\/sun\/star\/table\/CellAddress.hpp>\n#include <com\/sun\/star\/sheet\/CellFlags.hpp>\n#include <com\/sun\/star\/util\/XCloseable.hpp>\n\nusing namespace com::sun::star;\n\n\nnamespace ScCellRangeBase {\n\n#define NUMBER_OF_TESTS 5\n\nclass ScXCellRangesQuery : public UnoApiTest\n{\npublic:\n\n virtual void setUp();\n virtual void tearDown();\n\n \/\/Testcases\n void testQueryColumnDifference();\n void testQueryContentDifference();\n void testQueryEmptyCells();\n void testQueryFormulaCells();\n void testQueryIntersection();\n void testQueryRowDifference();\n void testQueryVisibleCells();\n\n CPPUNIT_TEST_SUITE(ScXCellRangesQuery);\n CPPUNIT_TEST(testQueryColumnDifference);\n CPPUNIT_TEST(testQueryContentDifference);\n CPPUNIT_TEST(testQueryEmptyCells);\n \/\/looks broken\n \/\/CPPUNIT_TEST(testQueryFormulaCells);\n CPPUNIT_TEST(testQueryIntersection);\n CPPUNIT_TEST(testQueryRowDifference);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n uno::Reference<sheet::XCellRangesQuery> init();\n\n static int nTest;\n static uno::Reference< lang::XComponent > xComponent;\n};\n\nint ScXCellRangesQuery::nTest = 0;\nuno::Reference< lang::XComponent > ScXCellRangesQuery::xComponent;\n\nuno::Reference<sheet::XCellRangesQuery> ScXCellRangesQuery::init()\n{\n rtl::OUString aFileURL;\n const rtl::OUString aFileBase(RTL_CONSTASCII_USTRINGPARAM(\"xcellrangesquery.ods\"));\n createFileURL(aFileBase, aFileURL);\n std::cout << rtl::OUStringToOString(aFileURL, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n if( !xComponent.is())\n xComponent = loadFromDesktop(aFileURL);\n uno::Reference< sheet::XSpreadsheetDocument> xDoc (xComponent, UNO_QUERY_THROW);\n uno::Reference< container::XIndexAccess > xIndex (xDoc->getSheets(), UNO_QUERY_THROW);\n uno::Reference< sheet::XSpreadsheet > xSheet( xIndex->getByIndex(0), UNO_QUERY_THROW);\n\n CPPUNIT_ASSERT_MESSAGE(\"Could not create interface of type XSpreadsheet\", xSheet.is());\n\n uno::Reference<sheet::XCellRangesQuery> xReturn(xSheet->getCellRangeByPosition(0,0,3,4), UNO_QUERY_THROW);\n\n CPPUNIT_ASSERT_MESSAGE(\"Could not create object of type XCellRangesQuery\", xReturn.is());\n return xReturn;\n}\n\nvoid ScXCellRangesQuery::testQueryColumnDifference()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.B1:C1,Sheet1.B3:C5\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryColumnDifferences(table::CellAddress(0, 1, 1));\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryColumnDifference: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryColumnDifference\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryContentDifference()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.B2:B3\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryContentCells(sheet::CellFlags::VALUE);\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryContentDifference: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryContentDifference\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryEmptyCells()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.A1:A5,Sheet1.B1:C1,Sheet1.B5,Sheet1.C3:C5,Sheet1.D1:D5\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryEmptyCells();\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryEmptyCells: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryEmptyCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryFormulaCells()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.C2\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryFormulaCells(sheet::CellFlags::FORMULA);\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryFormulaCells: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryFormulaCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryIntersection()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.D4:D5\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryIntersection(table::CellRangeAddress(0,3,3,7,7));\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryIntersection: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryFormulaCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryRowDifference()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.A2:A4,Sheet1.C2:D4\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryRowDifferences(table::CellAddress(0,1,1));\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryRowDifference: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryFormulaCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::testQueryVisibleCells()\n{\n rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM(\"Sheet1.A2\"));\n uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();\n uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryVisibleCells();\n rtl::OUString aResult = xRanges->getRangeAddressesAsString();\n std::cout << \"testQueryVisibleCells: Result: \" << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;\n CPPUNIT_ASSERT_MESSAGE(\"testQueryFormulaCells\", aResult == aExpected);\n}\n\nvoid ScXCellRangesQuery::setUp()\n{\n nTest += 1;\n UnoApiTest::setUp();\n}\n\nvoid ScXCellRangesQuery::tearDown()\n{\n if (nTest == NUMBER_OF_TESTS)\n {\n uno::Reference< util::XCloseable > xCloseable(xComponent, UNO_QUERY_THROW);\n xCloseable->close( false );\n }\n\n UnoApiTest::tearDown();\n\n if (nTest == NUMBER_OF_TESTS)\n {\n mxDesktop->terminate();\n uno::Reference< lang::XComponent>(m_xContext, UNO_QUERY_THROW)->dispose();\n }\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(ScXCellRangesQuery);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#include <QtCore\/QVector>\n#include <QtCore\/QHash>\nvoid local_vector()\n{\n QVector<int> vec;\n for (int i = 0; i < 10; ++i) {\n vec << i; \/\/ Test #1: Warning\n vec.append(i); \/\/ Test #2: Warning\n }\n\n QVector<int> vec1;\n vec1.reserve(10);\n for (int i = 0; i < 10; ++i) {\n vec1 << i; \/\/ Test #3: No warning\n vec1.append(i); \/\/ Test #4: No warning\n }\n\n QVector<int> vec2;\n for (int i = 0; i < 10; ++i) {\n if (true) {\n vec1 << i; \/\/ Test #5: No warning\n vec1.append(i); \/\/ Test #6: No warning\n }\n }\n\n for (int i = 0; i < 10; ++i) {\n QVector<int> v;\n v << 1; \/\/ OK\n }\n}\n\nvoid non_local_vector(QVector<int> &vec)\n{\n \/\/ Test #7: No warning\n for (int i = 0; i < 10; ++i) {\n vec << i;\n }\n}\n\nbool returns_bool()\n{\n return true;\n}\n\nunsigned int returns_uint() { return 0; }\nint returns_int() { return 0; }\nlong long returns_long() { return 0; }\n\nvoid test_complex_expressions()\n{\n QVector<int> v;\n int a987r[10];\n for (int i = 0; a987r[i] == 1; ++i)\n v << i; \/\/ OK\n\n for (int i = 0; returns_bool(); ++i)\n v << i; \/\/ OK\n\n QVector<int> v2, v3;\n for (int i = 0; i < v2.size(); ++i)\n v3 << v3[i]; \/\/ Warning\n\n QVector<int> v4, v5;\n for (int i = 0; i < returns_uint(); ++i)\n v4 << v5[i]; \/\/ Warning\n\n QVector<int> v6, v7;\n for (int i = 0; i < returns_int(); ++i)\n v6 << v7[i]; \/\/ Warning\n\n QVector<int> v8, v9;\n for (int i = 0; i < returns_long(); ++i)\n v8 << v9[i]; \/\/ Warning\n}\n\nvoid test_nesting()\n{\n QVector<int> v;\n\n while (returns_bool()) {\n for (int i = 0; i < 10; ++i)\n v << i; \/\/ OK\n }\n\n while (returns_bool()) {\n QVector<int> v2;\n for (int i = 0; i < 10; ++i)\n v2 << i; \/\/ Warning\n }\n\n QVector<int> v3;\n \/\/ Too many levels, this is ok, unless all of the cond expressions where literals but that's unlikely\n for (int i = 0; i < 10; ++i) {\n for (int i = 0; i < 10; ++i) {\n for (int i = 0; i < 10; ++i) {\n for (int i = 0; i < 10; ++i) {\n v3 << i; \/\/ OK\n }\n }\n }\n }\n\n QVector<int> a,b,c,d,e;\n foreach (int i, a)\n foreach (int i2, b)\n c << 1; \/\/ OK\n\n\n\n}\n\nvoid test_misc()\n{\n QVector<int> v2;\n for (int i = 0; i < 10; ) {\n v2 << i; \/\/ OK\n }\n}\n\n\nclass B\n{\npublic:\n QVector<int> v;\n};\n\n\nclass A\n{\n A()\n {\n for (int i = 0; i < 10; ++i)\n v << i; \/\/ Warning\n\n for (int i = 0; i < 10; ++i)\n b.v << i; \/\/ OK\n }\n\n ~A()\n {\n for (int i = 0; i < 10; ++i)\n v << i; \/\/ Warning\n }\n\n void foo()\n {\n for (int i = 0; i < 10; ++i)\n v << i; \/\/ OK\n }\n\npublic:\n QVector<int> v;\n B b;\n};\n\nstruct Node\n{\n Node *next;\n int next2;\n};\n\nvoid testNode()\n{\n QVector<int> v, v2;\n Node *node;\n for (int i = 0; i < 10; node = node->next) \/\/ OK\n v << i;\n\n for (int i = 0; i < 10; i = i + 1) v << i; \/\/ Warning\n\n for (auto it = v2.cbegin(), e = v2.cend(); it != e; ++it)\n v << 0; \/\/ Warning\n\n for (auto it = v2.cbegin(), e = v2.cend(); it != e; it = it + 1)\n v << 0; \/\/ Warning\n\n for (int i = 0; i < 10; i = node->next2)\n v << i; \/\/ OK\n\n\n for (int i = 0; i < 10; ++i) {\n v << 1; \/\/ Warning\n v2 << 1; \/\/ Warning\n }\n\n for (int i = 0; i < 10; i = node->next2) {\n v.push_back(1); \/\/ OK\n v.push_back(1); \/\/ OK\n v2.push_back(1); \/\/ OK\n v2.push_back(1); \/\/ OK\n }\n}\n\n\nstruct testCTOR\n{\n testCTOR()\n {\n Node *node;\n for (int i = 0; i < 10; i = node->next2) {\n m_v << 1; \/\/ OK\n }\n }\n\n QVector<int> m_v;\n};\n\n\nvoid moreStuff()\n{\n QVector<int> v;\n for (int i = 0; ; ++i)\n v.push_back(1);\n\n QHash<int,int> h;\n QHashIterator<int,int> it(h);\n while (it.hasNext()) { \/\/ Ok\n v.push_back(1);\n }\n}\n\n\nvoid rangeLoop()\n{\n QVector<int> v1, v2;\n for (auto i : v1)\n v2.push_back(i);\n}\n\nstruct Foo\n{\n Foo ip() const;\n QList<Foo> addressEntries;\n};\n\nvoid testNesting2()\n{\n QList<Foo> result;\n QList<Foo> privs;\n foreach (const Foo &p, privs)\n foreach (const Foo &entry, privs)\n result += entry.ip();\n\n QVector<int> v2;\n for (int u = 0; u < 10; ++u) {\n for (int n = 0; n < 10; ++n) {\n v2.append(1);\n }\n }\n\n}\n<commit_msg>Add test-case for false positive<commit_after>#include <QtCore\/QVector>\n#include <QtCore\/QHash>\nvoid local_vector()\n{\n QVector<int> vec;\n for (int i = 0; i < 10; ++i) {\n vec << i; \/\/ Test #1: Warning\n vec.append(i); \/\/ Test #2: Warning\n }\n\n QVector<int> vec1;\n vec1.reserve(10);\n for (int i = 0; i < 10; ++i) {\n vec1 << i; \/\/ Test #3: No warning\n vec1.append(i); \/\/ Test #4: No warning\n }\n\n QVector<int> vec2;\n for (int i = 0; i < 10; ++i) {\n if (true) {\n vec1 << i; \/\/ Test #5: No warning\n vec1.append(i); \/\/ Test #6: No warning\n }\n }\n\n for (int i = 0; i < 10; ++i) {\n QVector<int> v;\n v << 1; \/\/ OK\n }\n}\n\nvoid non_local_vector(QVector<int> &vec)\n{\n \/\/ Test #7: No warning\n for (int i = 0; i < 10; ++i) {\n vec << i;\n }\n}\n\nbool returns_bool()\n{\n return true;\n}\n\nunsigned int returns_uint() { return 0; }\nint returns_int() { return 0; }\nlong long returns_long() { return 0; }\n\nvoid test_complex_expressions()\n{\n QVector<int> v;\n int a987r[10];\n for (int i = 0; a987r[i] == 1; ++i)\n v << i; \/\/ OK\n\n for (int i = 0; returns_bool(); ++i)\n v << i; \/\/ OK\n\n QVector<int> v2, v3;\n for (int i = 0; i < v2.size(); ++i)\n v3 << v3[i]; \/\/ Warning\n\n QVector<int> v4, v5;\n for (int i = 0; i < returns_uint(); ++i)\n v4 << v5[i]; \/\/ Warning\n\n QVector<int> v6, v7;\n for (int i = 0; i < returns_int(); ++i)\n v6 << v7[i]; \/\/ Warning\n\n QVector<int> v8, v9;\n for (int i = 0; i < returns_long(); ++i)\n v8 << v9[i]; \/\/ Warning\n}\n\nvoid test_nesting()\n{\n QVector<int> v;\n\n while (returns_bool()) {\n for (int i = 0; i < 10; ++i)\n v << i; \/\/ OK\n }\n\n while (returns_bool()) {\n QVector<int> v2;\n for (int i = 0; i < 10; ++i)\n v2 << i; \/\/ Warning\n }\n\n QVector<int> v3;\n \/\/ Too many levels, this is ok, unless all of the cond expressions where literals but that's unlikely\n for (int i = 0; i < 10; ++i) {\n for (int i = 0; i < 10; ++i) {\n for (int i = 0; i < 10; ++i) {\n for (int i = 0; i < 10; ++i) {\n v3 << i; \/\/ OK\n }\n }\n }\n }\n\n QVector<int> a,b,c,d,e;\n foreach (int i, a)\n foreach (int i2, b)\n c << 1; \/\/ OK\n\n\n\n}\n\nvoid test_misc()\n{\n QVector<int> v2;\n for (int i = 0; i < 10; ) {\n v2 << i; \/\/ OK\n }\n}\n\n\nclass B\n{\npublic:\n QVector<int> v;\n};\n\n\nclass A\n{\n A()\n {\n for (int i = 0; i < 10; ++i)\n v << i; \/\/ Warning\n\n for (int i = 0; i < 10; ++i)\n b.v << i; \/\/ OK\n }\n\n ~A()\n {\n for (int i = 0; i < 10; ++i)\n v << i; \/\/ Warning\n }\n\n void foo()\n {\n for (int i = 0; i < 10; ++i)\n v << i; \/\/ OK\n }\n\npublic:\n QVector<int> v;\n B b;\n};\n\nstruct Node\n{\n Node *next;\n int next2;\n};\n\nvoid testNode()\n{\n QVector<int> v, v2;\n Node *node;\n for (int i = 0; i < 10; node = node->next) \/\/ OK\n v << i;\n\n for (int i = 0; i < 10; i = i + 1) v << i; \/\/ Warning\n\n for (auto it = v2.cbegin(), e = v2.cend(); it != e; ++it)\n v << 0; \/\/ Warning\n\n for (auto it = v2.cbegin(), e = v2.cend(); it != e; it = it + 1)\n v << 0; \/\/ Warning\n\n for (int i = 0; i < 10; i = node->next2)\n v << i; \/\/ OK\n\n\n for (int i = 0; i < 10; ++i) {\n v << 1; \/\/ Warning\n v2 << 1; \/\/ Warning\n }\n\n for (int i = 0; i < 10; i = node->next2) {\n v.push_back(1); \/\/ OK\n v.push_back(1); \/\/ OK\n v2.push_back(1); \/\/ OK\n v2.push_back(1); \/\/ OK\n }\n}\n\n\nstruct testCTOR\n{\n testCTOR()\n {\n Node *node;\n for (int i = 0; i < 10; i = node->next2) {\n m_v << 1; \/\/ OK\n }\n }\n\n QVector<int> m_v;\n};\n\n\nvoid moreStuff()\n{\n QVector<int> v;\n for (int i = 0; ; ++i)\n v.push_back(1);\n\n QHash<int,int> h;\n QHashIterator<int,int> it(h);\n while (it.hasNext()) { \/\/ Ok\n v.push_back(1);\n }\n}\n\n\nvoid rangeLoop()\n{\n QVector<int> v1, v2;\n for (auto i : v1)\n v2.push_back(i);\n}\n\nstruct Foo\n{\n Foo ip() const;\n QList<Foo> addressEntries;\n};\n\nvoid testNesting2()\n{\n QList<Foo> result;\n QList<Foo> privs;\n foreach (const Foo &p, privs)\n foreach (const Foo &entry, privs)\n result += entry.ip();\n\n QVector<int> v2;\n for (int u = 0; u < 10; ++u) {\n for (int n = 0; n < 10; ++n) {\n v2.append(1);\n }\n }\n}\n\n#include <QtCore\/QQueue>\nvoid bug362943()\n{\n QVector<int> vect;\n QQueue<int> q;\n q.reserve(10);\n for (const int i: vect) {\n q << i;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011-2013 Blender 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#include \"tile.h\"\n\n#include \"util_algorithm.h\"\n#include \"util_types.h\"\n\nCCL_NAMESPACE_BEGIN\n\nTileManager::TileManager(bool progressive_, int num_samples_, int2 tile_size_, int start_resolution_,\n bool preserve_tile_device_, bool background_, TileOrder tile_order_, int num_devices_)\n{\n\tprogressive = progressive_;\n\ttile_size = tile_size_;\n\ttile_order = tile_order_;\n\tstart_resolution = start_resolution_;\n\tnum_devices = num_devices_;\n\tpreserve_tile_device = preserve_tile_device_;\n\tbackground = background_;\n\n\tBufferParams buffer_params;\n\treset(buffer_params, 0);\n}\n\nTileManager::~TileManager()\n{\n}\n\nvoid TileManager::reset(BufferParams& params_, int num_samples_)\n{\n\tparams = params_;\n\n\tint divider = 1;\n\tint w = params.width, h = params.height;\n\n\tif(start_resolution != INT_MAX) {\n\t\twhile(w*h > start_resolution*start_resolution) {\n\t\t\tw = max(1, w\/2); \n\t\t\th = max(1, h\/2); \n\n\t\t\tdivider *= 2;\n\t\t}\n\t}\n\n\tnum_samples = num_samples_;\n\n\tstate.buffer = BufferParams();\n\tstate.sample = -1;\n\tstate.num_tiles = 0;\n\tstate.num_rendered_tiles = 0;\n\tstate.num_samples = 0;\n\tstate.resolution_divider = divider;\n\tstate.tiles.clear();\n}\n\nvoid TileManager::set_samples(int num_samples_)\n{\n\tnum_samples = num_samples_;\n}\n\n\/* splits image into tiles and assigns equal amount of tiles to every render device *\/\nvoid TileManager::gen_tiles_global()\n{\n\tint resolution = state.resolution_divider;\n\tint image_w = max(1, params.width\/resolution);\n\tint image_h = max(1, params.height\/resolution);\n\n\tstate.tiles.clear();\n\n\tint tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)\/tile_size.x;\n\tint tile_h = (tile_size.y >= image_h)? 1: (image_h + tile_size.y - 1)\/tile_size.y;\n\n\tint num_logical_devices = preserve_tile_device? num_devices: 1;\n\tint num = min(image_h, num_logical_devices);\n\tint tile_index = 0;\n\n\tint tiles_per_device = (tile_w * tile_h + num - 1) \/ num;\n\tint cur_device = 0, cur_tiles = 0;\n\n\tfor(int tile_y = 0; tile_y < tile_h; tile_y++) {\n\t\tfor(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {\n\t\t\tint x = tile_x * tile_size.x;\n\t\t\tint y = tile_y * tile_size.y;\n\t\t\tint w = (tile_x == tile_w-1)? image_w - x: tile_size.x;\n\t\t\tint h = (tile_y == tile_h-1)? image_h - y: tile_size.y;\n\n\t\t\tstate.tiles.push_back(Tile(tile_index, x, y, w, h, cur_device));\n\t\t\tcur_tiles++;\n\n\t\t\tif(cur_tiles == tiles_per_device) {\n\t\t\t\tcur_tiles = 0;\n\t\t\t\tcur_device++;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/* slices image into as much pieces as how many devices are rendering this image *\/\nvoid TileManager::gen_tiles_sliced()\n{\n\tint resolution = state.resolution_divider;\n\tint image_w = max(1, params.width\/resolution);\n\tint image_h = max(1, params.height\/resolution);\n\n\tstate.tiles.clear();\n\n\tint num_logical_devices = preserve_tile_device? num_devices: 1;\n\tint num = min(image_h, num_logical_devices);\n\tint tile_index = 0;\n\n\tfor(int device = 0; device < num; device++) {\n\t\tint device_y = (image_h\/num)*device;\n\t\tint device_h = (device == num-1)? image_h - device*(image_h\/num): image_h\/num;\n\n\t\tint tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)\/tile_size.x;\n\t\tint tile_h = (tile_size.y >= device_h)? 1: (device_h + tile_size.y - 1)\/tile_size.y;\n\n\t\tfor(int tile_y = 0; tile_y < tile_h; tile_y++) {\n\t\t\tfor(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {\n\t\t\t\tint x = tile_x * tile_size.x;\n\t\t\t\tint y = tile_y * tile_size.y;\n\t\t\t\tint w = (tile_x == tile_w-1)? image_w - x: tile_size.x;\n\t\t\t\tint h = (tile_y == tile_h-1)? device_h - y: tile_size.y;\n\n\t\t\t\tstate.tiles.push_back(Tile(tile_index, x, y + device_y, w, h, device));\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TileManager::set_tiles()\n{\n\tint resolution = state.resolution_divider;\n\tint image_w = max(1, params.width\/resolution);\n\tint image_h = max(1, params.height\/resolution);\n\n\tif(background)\n\t\tgen_tiles_global();\n\telse\n\t\tgen_tiles_sliced();\n\n\tstate.num_tiles = state.tiles.size();\n\n\tstate.buffer.width = image_w;\n\tstate.buffer.height = image_h;\n\n\tstate.buffer.full_x = params.full_x\/resolution;\n\tstate.buffer.full_y = params.full_y\/resolution;\n\tstate.buffer.full_width = max(1, params.full_width\/resolution);\n\tstate.buffer.full_height = max(1, params.full_height\/resolution);\n}\n\nlist<Tile>::iterator TileManager::next_viewport_tile(int device)\n{\n\tlist<Tile>::iterator iter;\n\n\tint logical_device = preserve_tile_device? device: 0;\n\n\tfor(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {\n\t\tif(iter->device == logical_device && iter->rendering == false)\n\t\treturn iter;\n\t}\n\n\treturn state.tiles.end();\n}\n\nlist<Tile>::iterator TileManager::next_background_tile(int device, TileOrder tile_order)\n{\n\tlist<Tile>::iterator iter, best = state.tiles.end();\n\n\tint resolution = state.resolution_divider;\n\tint logical_device = preserve_tile_device? device: 0;\n\n\tint64_t cordx = max(1, params.width\/resolution);\n\tint64_t cordy = max(1, params.height\/resolution);\n\tint64_t mindist = INT_MAX;\n\t\n\tint64_t centx = cordx \/ 2, centy = cordy \/ 2;\n\n\tfor(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {\n\t\tif(iter->device == logical_device && iter->rendering == false) {\n\t\t\tTile &cur_tile = *iter;\n\t\t\t\n\t\t\tint64_t distx = cordx;\n\t\t\tint64_t disty = cordy;\n\t\t\t\n\t\t\tswitch (tile_order) {\n\t\t\t\tcase TILE_CENTER:\n\t\t\t\t\tdistx = centx - (cur_tile.x + cur_tile.w);\n\t\t\t\t\tdisty = centy - (cur_tile.y + cur_tile.h);\n\t\t\t\t\tdistx = (int64_t)sqrt((double)(distx * distx + disty * disty));\n\t\t\t\t\tbreak;\n\t\t\t\tcase TILE_RIGHT_TO_LEFT:\n\t\t\t\t\tdistx = cordx - cur_tile.x;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TILE_LEFT_TO_RIGHT:\n\t\t\t\t\tdistx = cordx + cur_tile.x;\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase TILE_TOP_TO_BOTTOM:\n\t\t\t\t\tdistx = cordx - cur_tile.y;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TILE_BOTTOM_TO_TOP:\n\t\t\t\t\tdistx = cordx + cur_tile.y;\n\t\t\t\t\tbreak; \n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(distx < mindist) {\n\t\t\t\tbest = iter;\n\t\t\t\tmindist = distx;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn best;\n}\n\nbool TileManager::next_tile(Tile& tile, int device)\n{\n\tlist<Tile>::iterator tile_it;\n\t\n\tif (background)\n\t\ttile_it = next_background_tile(device, tile_order);\n\telse\n\t\ttile_it = next_viewport_tile(device);\n\n\tif(tile_it != state.tiles.end()) {\n\t\ttile_it->rendering = true;\n\t\ttile = *tile_it;\n\t\tstate.num_rendered_tiles++;\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool TileManager::done()\n{\n\treturn (state.sample+state.num_samples >= num_samples && state.resolution_divider == 1);\n}\n\nbool TileManager::next()\n{\n\tif(done())\n\t\treturn false;\n\n\tif(progressive && state.resolution_divider > 1) {\n\t\tstate.sample = 0;\n\t\tstate.resolution_divider \/= 2;\n\t\tstate.num_samples = 1;\n\t\tset_tiles();\n\t}\n\telse {\n\t\tstate.sample++;\n\n\t\tif(progressive)\n\t\t\tstate.num_samples = 1;\n\t\telse\n\t\t\tstate.num_samples = num_samples;\n\n\t\tstate.resolution_divider = 1;\n\t\tset_tiles();\n\t}\n\n\treturn true;\n}\n\nCCL_NAMESPACE_END\n\n<commit_msg>Cycles: Center Tile order had a slight offset to the left.<commit_after>\/*\n * Copyright 2011-2013 Blender 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#include \"tile.h\"\n\n#include \"util_algorithm.h\"\n#include \"util_types.h\"\n\nCCL_NAMESPACE_BEGIN\n\nTileManager::TileManager(bool progressive_, int num_samples_, int2 tile_size_, int start_resolution_,\n bool preserve_tile_device_, bool background_, TileOrder tile_order_, int num_devices_)\n{\n\tprogressive = progressive_;\n\ttile_size = tile_size_;\n\ttile_order = tile_order_;\n\tstart_resolution = start_resolution_;\n\tnum_devices = num_devices_;\n\tpreserve_tile_device = preserve_tile_device_;\n\tbackground = background_;\n\n\tBufferParams buffer_params;\n\treset(buffer_params, 0);\n}\n\nTileManager::~TileManager()\n{\n}\n\nvoid TileManager::reset(BufferParams& params_, int num_samples_)\n{\n\tparams = params_;\n\n\tint divider = 1;\n\tint w = params.width, h = params.height;\n\n\tif(start_resolution != INT_MAX) {\n\t\twhile(w*h > start_resolution*start_resolution) {\n\t\t\tw = max(1, w\/2); \n\t\t\th = max(1, h\/2); \n\n\t\t\tdivider *= 2;\n\t\t}\n\t}\n\n\tnum_samples = num_samples_;\n\n\tstate.buffer = BufferParams();\n\tstate.sample = -1;\n\tstate.num_tiles = 0;\n\tstate.num_rendered_tiles = 0;\n\tstate.num_samples = 0;\n\tstate.resolution_divider = divider;\n\tstate.tiles.clear();\n}\n\nvoid TileManager::set_samples(int num_samples_)\n{\n\tnum_samples = num_samples_;\n}\n\n\/* splits image into tiles and assigns equal amount of tiles to every render device *\/\nvoid TileManager::gen_tiles_global()\n{\n\tint resolution = state.resolution_divider;\n\tint image_w = max(1, params.width\/resolution);\n\tint image_h = max(1, params.height\/resolution);\n\n\tstate.tiles.clear();\n\n\tint tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)\/tile_size.x;\n\tint tile_h = (tile_size.y >= image_h)? 1: (image_h + tile_size.y - 1)\/tile_size.y;\n\n\tint num_logical_devices = preserve_tile_device? num_devices: 1;\n\tint num = min(image_h, num_logical_devices);\n\tint tile_index = 0;\n\n\tint tiles_per_device = (tile_w * tile_h + num - 1) \/ num;\n\tint cur_device = 0, cur_tiles = 0;\n\n\tfor(int tile_y = 0; tile_y < tile_h; tile_y++) {\n\t\tfor(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {\n\t\t\tint x = tile_x * tile_size.x;\n\t\t\tint y = tile_y * tile_size.y;\n\t\t\tint w = (tile_x == tile_w-1)? image_w - x: tile_size.x;\n\t\t\tint h = (tile_y == tile_h-1)? image_h - y: tile_size.y;\n\n\t\t\tstate.tiles.push_back(Tile(tile_index, x, y, w, h, cur_device));\n\t\t\tcur_tiles++;\n\n\t\t\tif(cur_tiles == tiles_per_device) {\n\t\t\t\tcur_tiles = 0;\n\t\t\t\tcur_device++;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/* slices image into as much pieces as how many devices are rendering this image *\/\nvoid TileManager::gen_tiles_sliced()\n{\n\tint resolution = state.resolution_divider;\n\tint image_w = max(1, params.width\/resolution);\n\tint image_h = max(1, params.height\/resolution);\n\n\tstate.tiles.clear();\n\n\tint num_logical_devices = preserve_tile_device? num_devices: 1;\n\tint num = min(image_h, num_logical_devices);\n\tint tile_index = 0;\n\n\tfor(int device = 0; device < num; device++) {\n\t\tint device_y = (image_h\/num)*device;\n\t\tint device_h = (device == num-1)? image_h - device*(image_h\/num): image_h\/num;\n\n\t\tint tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)\/tile_size.x;\n\t\tint tile_h = (tile_size.y >= device_h)? 1: (device_h + tile_size.y - 1)\/tile_size.y;\n\n\t\tfor(int tile_y = 0; tile_y < tile_h; tile_y++) {\n\t\t\tfor(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {\n\t\t\t\tint x = tile_x * tile_size.x;\n\t\t\t\tint y = tile_y * tile_size.y;\n\t\t\t\tint w = (tile_x == tile_w-1)? image_w - x: tile_size.x;\n\t\t\t\tint h = (tile_y == tile_h-1)? device_h - y: tile_size.y;\n\n\t\t\t\tstate.tiles.push_back(Tile(tile_index, x, y + device_y, w, h, device));\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TileManager::set_tiles()\n{\n\tint resolution = state.resolution_divider;\n\tint image_w = max(1, params.width\/resolution);\n\tint image_h = max(1, params.height\/resolution);\n\n\tif(background)\n\t\tgen_tiles_global();\n\telse\n\t\tgen_tiles_sliced();\n\n\tstate.num_tiles = state.tiles.size();\n\n\tstate.buffer.width = image_w;\n\tstate.buffer.height = image_h;\n\n\tstate.buffer.full_x = params.full_x\/resolution;\n\tstate.buffer.full_y = params.full_y\/resolution;\n\tstate.buffer.full_width = max(1, params.full_width\/resolution);\n\tstate.buffer.full_height = max(1, params.full_height\/resolution);\n}\n\nlist<Tile>::iterator TileManager::next_viewport_tile(int device)\n{\n\tlist<Tile>::iterator iter;\n\n\tint logical_device = preserve_tile_device? device: 0;\n\n\tfor(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {\n\t\tif(iter->device == logical_device && iter->rendering == false)\n\t\treturn iter;\n\t}\n\n\treturn state.tiles.end();\n}\n\nlist<Tile>::iterator TileManager::next_background_tile(int device, TileOrder tile_order)\n{\n\tlist<Tile>::iterator iter, best = state.tiles.end();\n\n\tint resolution = state.resolution_divider;\n\tint logical_device = preserve_tile_device? device: 0;\n\n\tint64_t cordx = max(1, params.width\/resolution);\n\tint64_t cordy = max(1, params.height\/resolution);\n\tint64_t mindist = INT_MAX;\n\t\n\tint64_t centx = cordx \/ 2, centy = cordy \/ 2;\n\n\tfor(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {\n\t\tif(iter->device == logical_device && iter->rendering == false) {\n\t\t\tTile &cur_tile = *iter;\n\t\t\t\n\t\t\tint64_t distx = cordx;\n\t\t\tint64_t disty = cordy;\n\t\t\t\n\t\t\tswitch (tile_order) {\n\t\t\t\tcase TILE_CENTER:\n\t\t\t\t\tdistx = centx - (cur_tile.x + (cur_tile.w \/ 2));\n\t\t\t\t\tdisty = centy - (cur_tile.y + (cur_tile.h \/ 2));\n\t\t\t\t\tdistx = (int64_t)sqrt((double)(distx * distx + disty * disty));\n\t\t\t\t\tbreak;\n\t\t\t\tcase TILE_RIGHT_TO_LEFT:\n\t\t\t\t\tdistx = cordx - cur_tile.x;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TILE_LEFT_TO_RIGHT:\n\t\t\t\t\tdistx = cordx + cur_tile.x;\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase TILE_TOP_TO_BOTTOM:\n\t\t\t\t\tdistx = cordx - cur_tile.y;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TILE_BOTTOM_TO_TOP:\n\t\t\t\t\tdistx = cordx + cur_tile.y;\n\t\t\t\t\tbreak; \n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(distx < mindist) {\n\t\t\t\tbest = iter;\n\t\t\t\tmindist = distx;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn best;\n}\n\nbool TileManager::next_tile(Tile& tile, int device)\n{\n\tlist<Tile>::iterator tile_it;\n\t\n\tif (background)\n\t\ttile_it = next_background_tile(device, tile_order);\n\telse\n\t\ttile_it = next_viewport_tile(device);\n\n\tif(tile_it != state.tiles.end()) {\n\t\ttile_it->rendering = true;\n\t\ttile = *tile_it;\n\t\tstate.num_rendered_tiles++;\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool TileManager::done()\n{\n\treturn (state.sample+state.num_samples >= num_samples && state.resolution_divider == 1);\n}\n\nbool TileManager::next()\n{\n\tif(done())\n\t\treturn false;\n\n\tif(progressive && state.resolution_divider > 1) {\n\t\tstate.sample = 0;\n\t\tstate.resolution_divider \/= 2;\n\t\tstate.num_samples = 1;\n\t\tset_tiles();\n\t}\n\telse {\n\t\tstate.sample++;\n\n\t\tif(progressive)\n\t\t\tstate.num_samples = 1;\n\t\telse\n\t\t\tstate.num_samples = num_samples;\n\n\t\tstate.resolution_divider = 1;\n\t\tset_tiles();\n\t}\n\n\treturn true;\n}\n\nCCL_NAMESPACE_END\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \r\n#include <string> \r\n#include <fstream> \r\nusing namespace std;\r\n\r\ntemplate<typename T>\r\nstruct Node\r\n{\r\n\tT x;\r\n\tNode<T> * left;\r\n\tNode<T> * right;\r\n\tNode(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}\r\n};\r\n\r\ntemplate<typename T>\r\nclass Tree\r\n{\r\nprivate:\r\n\tNode<T> * root;\r\npublic:\r\n\tTree()\r\n\t{\r\n\t\troot = nullptr;\r\n\t}\r\n\r\n\t~Tree()\r\n\t{\r\n\t\tdeleteNode(root);\r\n\t}\r\n\r\n\tvoid deleteNode(Node<T> * node)\r\n\t{\r\n\t\tif (node == nullptr) return;\r\n\t\tdeleteNode(node->left);\r\n\t\tdeleteNode(node->right);\r\n\t\tdelete node;\r\n\t}\r\n\r\n\tT x_() const\r\n\t{\r\n\t\treturn root->x;\r\n\t}\r\n\r\n\tT left_() const\r\n\t{\r\n\t\treturn root->left->x;\r\n\t}\r\n\r\n\tT right_() const\r\n\t{\r\n\t\treturn root->right->;\r\n\t}\r\n\r\n\tNode<T> * root_() const\r\n\t{\r\n\t\treturn root;\r\n\t}\r\n\r\n\tvoid insert(const T& value)\r\n\t{\r\n\t\tinsert(root, value);\r\n\t}\r\n\r\n\tvoid insert(Node<T>* & node, const T& value)\r\n\t{\r\n\t\tif (node) {\r\n\t\t\tif (value < node->x) {\r\n\t\t\t\tinsert(node->left, value);\r\n\t\t\t}\r\n\t\t\telse if (value > node->x) {\r\n\t\t\t\tinsert(node->right, value);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tnode = new Node<T>(value);\r\n\t\t}\r\n\t}\r\n\r\n\tNode<T> * search(const T& x)const\r\n\t{\r\n\t\tNode<T> * curEl = root;\r\n\t\twhile (curEl != nullptr)\r\n\t\t{\r\n\t\t\tif (curEl->x == x)\r\n\t\t\t\tbreak;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (x > curEl->x)\r\n\t\t\t\t\tcurEl = curEl->right;\r\n\t\t\t\telse curEl = curEl->left;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn curEl;\r\n\t}\r\n\r\n\tvoid fIn(const string filename)\r\n\t{\r\n\t\tifstream fin;\r\n\t\tunsigned int k;\r\n\t\tfin.open(filename);\r\n\t\tif (!fin.is_open())\r\n\t\t\tcout << \"The file isn't find\" << endl;\r\n\t\telse\r\n\t\t{\r\n\t\t\tdeleteNode(root);\r\n\t\t\tif (fin.eof()) return;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tfin >> k;\r\n\t\t\t\tT newEl;\r\n\t\t\t\tfor (unsigned int i = 0; i < k; ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tfin >> newEl;\r\n\t\t\t\t\tinsert(newEl);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfin.close();\r\n\t\t}\r\n\t}\r\n\r\n\tunsigned int size(Node<T> * node)const\r\n\t{\r\n\t\tunsigned int size_ = 0;\r\n\t\tif (node != nullptr)\r\n\t\t\tsize_ = size(node->left) + 1 + size(node->right);\r\n\t\treturn size_;\r\n\t}\r\n\r\n\tvoid out_to_file(const string filename)const\r\n\t{\r\n\t\tofstream fout;\r\n\t\tfout.open(filename);\r\n\t\tif (!fout.is_open())\r\n\t\t\tcout << \"The file isn't find\" << endl;\r\n\t\telse\r\n\t\t{\r\n\t\t\tunsigned int size_ = size(root);\r\n\t\t\tif (size_ == 0)\r\n\t\t\t\treturn;\r\n\t\t\tfout << size_ << \"\\t\";\r\n\t\t\tfOut(root, fout);\r\n\t\t\tfout.close();\r\n\t\t}\r\n\t}\r\n\r\n\tvoid fOut(Node<T> * node, ostream&stream)const\r\n\t{\r\n\t\tif (node != nullptr)\r\n\t\t{\r\n\t\t\tfOut(node->left, stream);\r\n\t\t\tstream << node->x << \" \";\r\n\t\t\tfOut(node->right, stream);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid out(ostream & stream)const\r\n\t{\r\n\t\tOut(root, stream, 0);\r\n\t}\r\n\r\n\tvoid Out(Node<T> * node, ostream&stream, size_t level)const\r\n\t{\r\n\t\tNode<T> * curEl = node;\r\n\t\tif (curEl != nullptr)\r\n\t\t{\r\n\t\t\tOut(curEl->right, stream, level + 1);\r\n\t\t\tfor (unsigned int i = 0; i < level; ++i)\r\n\t\t\t\tstream << '-';\r\n\t\t\tstream << curEl->x << endl;\r\n\t\t\tOut(curEl->left, stream, level + 1);\r\n\t\t}\r\n\t}\r\n};\r\n<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> \r\n#include <string> \r\n#include <fstream> \r\nusing namespace std;\r\n\r\ntemplate<typename T>\r\nstruct Node\r\n{\r\n\tT x;\r\n\tNode<T> * left;\r\n\tNode<T> * right;\r\n\tNode(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}\r\n};\r\n\r\ntemplate<typename T>\r\nclass Tree\r\n{\r\nprivate:\r\n\tNode<T> * root;\r\npublic:\r\n\tTree()\r\n\t{\r\n\t\troot = nullptr;\r\n\t}\r\n\r\n\t~Tree()\r\n\t{\r\n\t\tdeleteNode(root);\r\n\t}\r\n\r\n\tvoid deleteNode(Node<T> * node)\r\n\t{\r\n\t\tif (node == nullptr) return;\r\n\t\tdeleteNode(node->left);\r\n\t\tdeleteNode(node->right);\r\n\t\tdelete node;\r\n\t}\r\n\r\n\tT x_() const\r\n\t{\r\n\t\treturn root->x;\r\n\t}\r\n\r\n\tT left_() const\r\n\t{\r\n\t\treturn root->left->x;\r\n\t}\r\n\r\n\tT right_() const\r\n\t{\r\n\t\treturn root->right->x;\r\n\t}\r\n\r\n\tNode<T> * root_() const\r\n\t{\r\n\t\treturn root;\r\n\t}\r\n\r\n\tvoid insert(const T& value)\r\n\t{\r\n\t\tinsert(root, value);\r\n\t}\r\n\r\n\tvoid insert(Node<T>* & node, const T& value)\r\n\t{\r\n\t\tif (node) {\r\n\t\t\tif (value < node->x) {\r\n\t\t\t\tinsert(node->left, value);\r\n\t\t\t}\r\n\t\t\telse if (value > node->x) {\r\n\t\t\t\tinsert(node->right, value);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tnode = new Node<T>(value);\r\n\t\t}\r\n\t}\r\n\r\n\tNode<T> * search(const T& x)const\r\n\t{\r\n\t\tNode<T> * curEl = root;\r\n\t\twhile (curEl != nullptr)\r\n\t\t{\r\n\t\t\tif (curEl->x == x)\r\n\t\t\t\tbreak;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (x > curEl->x)\r\n\t\t\t\t\tcurEl = curEl->right;\r\n\t\t\t\telse curEl = curEl->left;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn curEl;\r\n\t}\r\n\r\n\tvoid fIn(const string filename)\r\n\t{\r\n\t\tifstream fin;\r\n\t\tunsigned int k;\r\n\t\tfin.open(filename);\r\n\t\tif (!fin.is_open())\r\n\t\t\tcout << \"The file isn't find\" << endl;\r\n\t\telse\r\n\t\t{\r\n\t\t\tdeleteNode(root);\r\n\t\t\tif (fin.eof()) return;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tfin >> k;\r\n\t\t\t\tT newEl;\r\n\t\t\t\tfor (unsigned int i = 0; i < k; ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tfin >> newEl;\r\n\t\t\t\t\tinsert(newEl);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfin.close();\r\n\t\t}\r\n\t}\r\n\r\n\tunsigned int size(Node<T> * node)const\r\n\t{\r\n\t\tunsigned int size_ = 0;\r\n\t\tif (node != nullptr)\r\n\t\t\tsize_ = size(node->left) + 1 + size(node->right);\r\n\t\treturn size_;\r\n\t}\r\n\r\n\tvoid out_to_file(const string filename)const\r\n\t{\r\n\t\tofstream fout;\r\n\t\tfout.open(filename);\r\n\t\tif (!fout.is_open())\r\n\t\t\tcout << \"The file isn't find\" << endl;\r\n\t\telse\r\n\t\t{\r\n\t\t\tunsigned int size_ = size(root);\r\n\t\t\tif (size_ == 0)\r\n\t\t\t\treturn;\r\n\t\t\tfout << size_ << \"\\t\";\r\n\t\t\tfOut(root, fout);\r\n\t\t\tfout.close();\r\n\t\t}\r\n\t}\r\n\r\n\tvoid fOut(Node<T> * node, ostream&stream)const\r\n\t{\r\n\t\tif (node != nullptr)\r\n\t\t{\r\n\t\t\tfOut(node->left, stream);\r\n\t\t\tstream << node->x << \" \";\r\n\t\t\tfOut(node->right, stream);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid out(ostream & stream)const\r\n\t{\r\n\t\tOut(root, stream, 0);\r\n\t}\r\n\r\n\tvoid Out(Node<T> * node, ostream&stream, size_t level)const\r\n\t{\r\n\t\tNode<T> * curEl = node;\r\n\t\tif (curEl != nullptr)\r\n\t\t{\r\n\t\t\tOut(curEl->right, stream, level + 1);\r\n\t\t\tfor (unsigned int i = 0; i < level; ++i)\r\n\t\t\t\tstream << '-';\r\n\t\t\tstream << curEl->x << endl;\r\n\t\t\tOut(curEl->left, stream, level + 1);\r\n\t\t}\r\n\t}\r\n};\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlfonte.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 12:53:13 $\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_sc.hxx\"\n#ifdef PRECOMPILED\n#include \"filt_pch.hxx\"\n#endif\n\n\n#ifndef SC_ITEMS_HXX\n#include \"scitems.hxx\"\n#endif\n\n#include <svx\/eeitem.hxx>\n#define ITEMID_FIELD EE_FEATURE_FIELD\n\n#ifndef _XMLOFF_XMLFONTAUTOSTYLEPOOL_HXX\n#include <xmloff\/XMLFontAutoStylePool.hxx>\n#endif\n#ifndef _SVX_FONTITEM_HXX\n#include <svx\/fontitem.hxx>\n#endif\n#ifndef _EEITEM_HXX\n#include <svx\/eeitem.hxx>\n#endif\n#ifndef _MyEDITENG_HXX\n#include <svx\/editeng.hxx>\n#endif\n\n#ifndef SC_DOCUMENT_HXX\n#include \"document.hxx\"\n#endif\n#ifndef SC_SCDOCPOL_HXX\n#include \"docpool.hxx\"\n#endif\n#ifndef SC_XMLEXPRT_HXX\n#include \"xmlexprt.hxx\"\n#endif\n#ifndef SC_STLPOOL_HXX\n#include \"stlpool.hxx\"\n#endif\n#ifndef SC_SCATTR_HXX\n#include \"attrib.hxx\"\n#endif\n\nclass ScXMLFontAutoStylePool_Impl: public XMLFontAutoStylePool\n{\n void AddFontItems(sal_uInt16* pWhichIds, sal_uInt8 nIdCount, const SfxItemPool* pPool, const sal_Bool bExportDefaults);\n public:\n\n ScXMLFontAutoStylePool_Impl( ScXMLExport& rExport );\n\n};\n\nvoid ScXMLFontAutoStylePool_Impl::AddFontItems(sal_uInt16* pWhichIds, sal_uInt8 nIdCount, const SfxItemPool* pPool, const sal_Bool bExportDefaults)\n{\n const SfxPoolItem* pItem;\n for( sal_uInt16 i=0; i < nIdCount; ++i )\n {\n sal_uInt16 nWhichId(pWhichIds[i]);\n if (bExportDefaults && (0 != (pItem = &pPool->GetDefaultItem(nWhichId))))\n {\n const SvxFontItem *pFont((const SvxFontItem *)pItem);\n Add( pFont->GetFamilyName(), pFont->GetStyleName(),\n pFont->GetFamily(), pFont->GetPitch(),\n pFont->GetCharSet() );\n }\n sal_uInt16 nItems(pPool->GetItemCount( nWhichId ));\n for( sal_uInt16 j = 0; j < nItems; ++j )\n {\n if( 0 != (pItem = pPool->GetItem( nWhichId, j ) ) )\n {\n const SvxFontItem *pFont((const SvxFontItem *)pItem);\n Add( pFont->GetFamilyName(), pFont->GetStyleName(),\n pFont->GetFamily(), pFont->GetPitch(),\n pFont->GetCharSet() );\n }\n }\n }\n}\n\nScXMLFontAutoStylePool_Impl::ScXMLFontAutoStylePool_Impl(\n ScXMLExport& rExport ) :\n XMLFontAutoStylePool( rExport )\n{\n sal_uInt16 aWhichIds[3] = { ATTR_FONT, ATTR_CJK_FONT,\n ATTR_CTL_FONT };\n sal_uInt16 aEditWhichIds[3] = { EE_CHAR_FONTINFO, EE_CHAR_FONTINFO_CJK,\n EE_CHAR_FONTINFO_CTL };\n sal_uInt16 aPageWhichIds[4] = { ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERLEFT,\n ATTR_PAGE_HEADERRIGHT, ATTR_PAGE_FOOTERRIGHT };\n\n const SfxItemPool* pPool(rExport.GetDocument() ? rExport.GetDocument()->GetPool() : NULL);\n AddFontItems(aWhichIds, 3, pPool, sal_True);\n const SfxItemPool* pEditPool(rExport.GetDocument()->GetEditPool());\n AddFontItems(aEditWhichIds, 3, pEditPool, sal_False);\n\n SfxStyleSheetIterator* pItr(rExport.GetDocument() ? rExport.GetDocument()->GetStyleSheetPool()->CreateIterator(SFX_STYLE_FAMILY_PAGE, 0xFFFF) : NULL);\n if(pItr)\n {\n SfxStyleSheetBase* pStyle(pItr->First());\n SfxItemPool* pPageEditPool(EditEngine::CreatePool());\n EditEngine aEditEngine(pPageEditPool);\n while (pStyle)\n {\n const SfxItemPool& rPagePool(pStyle->GetPool().GetPool());\n for (sal_uInt8 j = 0; j < 4; ++j)\n {\n sal_uInt16 nPageWhichId(aPageWhichIds[j]);\n sal_uInt16 nPageHFItems(rPagePool.GetItemCount(nPageWhichId));\n const ScPageHFItem* pPageItem;\n for (sal_uInt16 k = 0; k < nPageHFItems; ++k)\n {\n if (0 != (pPageItem = static_cast<const ScPageHFItem*>(rPagePool.GetItem(nPageWhichId, k))))\n {\n const EditTextObject* pLeftArea(pPageItem->GetLeftArea());\n if (pLeftArea)\n {\n aEditEngine.SetText(*pLeftArea);\n AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);\n }\n const EditTextObject* pCenterArea(pPageItem->GetCenterArea());\n if (pCenterArea)\n {\n aEditEngine.SetText(*pCenterArea);\n AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);\n }\n const EditTextObject* pRightArea(pPageItem->GetRightArea());\n if (pRightArea)\n {\n aEditEngine.SetText(*pRightArea);\n AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);\n }\n }\n }\n }\n pStyle = pItr->Next();\n }\n }\n}\n\n\nXMLFontAutoStylePool* ScXMLExport::CreateFontAutoStylePool()\n{\n return new ScXMLFontAutoStylePool_Impl( *this );\n}\n<commit_msg>INTEGRATION: CWS calcwarnings (1.9.110); FILE MERGED 2006\/12\/13 10:30:19 nn 1.9.110.2: #i69284# warning-free: filter\/xml, unxlngi6 2006\/12\/01 13:29:19 nn 1.9.110.1: #i69284# warning-free: filter\/xml, wntmsci10<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlfonte.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: vg $ $Date: 2007-02-27 12:51:13 $\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_sc.hxx\"\n#ifdef PRECOMPILED\n#include \"filt_pch.hxx\"\n#endif\n\n\n#ifndef SC_ITEMS_HXX\n#include \"scitems.hxx\"\n#endif\n\n#include <svx\/eeitem.hxx>\n#define ITEMID_FIELD EE_FEATURE_FIELD\n\n#ifndef _XMLOFF_XMLFONTAUTOSTYLEPOOL_HXX\n#include <xmloff\/XMLFontAutoStylePool.hxx>\n#endif\n#ifndef _SVX_FONTITEM_HXX\n#include <svx\/fontitem.hxx>\n#endif\n#ifndef _EEITEM_HXX\n#include <svx\/eeitem.hxx>\n#endif\n#ifndef _MyEDITENG_HXX\n#include <svx\/editeng.hxx>\n#endif\n\n#ifndef SC_DOCUMENT_HXX\n#include \"document.hxx\"\n#endif\n#ifndef SC_SCDOCPOL_HXX\n#include \"docpool.hxx\"\n#endif\n#ifndef SC_XMLEXPRT_HXX\n#include \"xmlexprt.hxx\"\n#endif\n#ifndef SC_STLPOOL_HXX\n#include \"stlpool.hxx\"\n#endif\n#ifndef SC_SCATTR_HXX\n#include \"attrib.hxx\"\n#endif\n\nclass ScXMLFontAutoStylePool_Impl: public XMLFontAutoStylePool\n{\n void AddFontItems(sal_uInt16* pWhichIds, sal_uInt8 nIdCount, const SfxItemPool* pItemPool, const sal_Bool bExportDefaults);\n public:\n\n ScXMLFontAutoStylePool_Impl( ScXMLExport& rExport );\n\n};\n\nvoid ScXMLFontAutoStylePool_Impl::AddFontItems(sal_uInt16* pWhichIds, sal_uInt8 nIdCount, const SfxItemPool* pItemPool, const sal_Bool bExportDefaults)\n{\n const SfxPoolItem* pItem;\n for( sal_uInt16 i=0; i < nIdCount; ++i )\n {\n sal_uInt16 nWhichId(pWhichIds[i]);\n if (bExportDefaults && (0 != (pItem = &pItemPool->GetDefaultItem(nWhichId))))\n {\n const SvxFontItem *pFont((const SvxFontItem *)pItem);\n Add( pFont->GetFamilyName(), pFont->GetStyleName(),\n sal::static_int_cast<sal_Int16>(pFont->GetFamily()),\n sal::static_int_cast<sal_Int16>(pFont->GetPitch()),\n pFont->GetCharSet() );\n }\n sal_uInt16 nItems(pItemPool->GetItemCount( nWhichId ));\n for( sal_uInt16 j = 0; j < nItems; ++j )\n {\n if( 0 != (pItem = pItemPool->GetItem( nWhichId, j ) ) )\n {\n const SvxFontItem *pFont((const SvxFontItem *)pItem);\n Add( pFont->GetFamilyName(), pFont->GetStyleName(),\n sal::static_int_cast<sal_Int16>(pFont->GetFamily()),\n sal::static_int_cast<sal_Int16>(pFont->GetPitch()),\n pFont->GetCharSet() );\n }\n }\n }\n}\n\nScXMLFontAutoStylePool_Impl::ScXMLFontAutoStylePool_Impl(\n ScXMLExport& rExportP ) :\n XMLFontAutoStylePool( rExportP )\n{\n sal_uInt16 aWhichIds[3] = { ATTR_FONT, ATTR_CJK_FONT,\n ATTR_CTL_FONT };\n sal_uInt16 aEditWhichIds[3] = { EE_CHAR_FONTINFO, EE_CHAR_FONTINFO_CJK,\n EE_CHAR_FONTINFO_CTL };\n sal_uInt16 aPageWhichIds[4] = { ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERLEFT,\n ATTR_PAGE_HEADERRIGHT, ATTR_PAGE_FOOTERRIGHT };\n\n const SfxItemPool* pItemPool(rExportP.GetDocument() ? rExportP.GetDocument()->GetPool() : NULL);\n AddFontItems(aWhichIds, 3, pItemPool, sal_True);\n const SfxItemPool* pEditPool(rExportP.GetDocument()->GetEditPool());\n AddFontItems(aEditWhichIds, 3, pEditPool, sal_False);\n\n SfxStyleSheetIterator* pItr(rExportP.GetDocument() ? rExportP.GetDocument()->GetStyleSheetPool()->CreateIterator(SFX_STYLE_FAMILY_PAGE, 0xFFFF) : NULL);\n if(pItr)\n {\n SfxStyleSheetBase* pStyle(pItr->First());\n SfxItemPool* pPageEditPool(EditEngine::CreatePool());\n EditEngine aEditEngine(pPageEditPool);\n while (pStyle)\n {\n const SfxItemPool& rPagePool(pStyle->GetPool().GetPool());\n for (sal_uInt8 j = 0; j < 4; ++j)\n {\n sal_uInt16 nPageWhichId(aPageWhichIds[j]);\n sal_uInt16 nPageHFItems(rPagePool.GetItemCount(nPageWhichId));\n const ScPageHFItem* pPageItem;\n for (sal_uInt16 k = 0; k < nPageHFItems; ++k)\n {\n if (0 != (pPageItem = static_cast<const ScPageHFItem*>(rPagePool.GetItem(nPageWhichId, k))))\n {\n const EditTextObject* pLeftArea(pPageItem->GetLeftArea());\n if (pLeftArea)\n {\n aEditEngine.SetText(*pLeftArea);\n AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);\n }\n const EditTextObject* pCenterArea(pPageItem->GetCenterArea());\n if (pCenterArea)\n {\n aEditEngine.SetText(*pCenterArea);\n AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);\n }\n const EditTextObject* pRightArea(pPageItem->GetRightArea());\n if (pRightArea)\n {\n aEditEngine.SetText(*pRightArea);\n AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);\n }\n }\n }\n }\n pStyle = pItr->Next();\n }\n }\n}\n\n\nXMLFontAutoStylePool* ScXMLExport::CreateFontAutoStylePool()\n{\n return new ScXMLFontAutoStylePool_Impl( *this );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tabpages.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 13:15:52 $\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_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n#include \"global.hxx\"\n#include \"document.hxx\"\n#include \"attrib.hxx\"\n#include \"scresid.hxx\"\n#include \"sc.hrc\"\n\n#include \"attrdlg.hrc\"\n#include \"tabpages.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nstatic USHORT pProtectionRanges[] =\n{\n SID_SCATTR_PROTECTION,\n SID_SCATTR_PROTECTION,\n 0\n};\n\n\/\/========================================================================\n\/\/ Zellschutz-Tabpage:\n\/\/========================================================================\n\nScTabPageProtection::ScTabPageProtection( Window* pParent,\n const SfxItemSet& rCoreAttrs )\n : SfxTabPage ( pParent,\n ScResId( RID_SCPAGE_PROTECTION ),\n rCoreAttrs ),\n \/\/\n aFlProtect ( this, ScResId( FL_PROTECTION ) ),\n aBtnProtect ( this, ScResId( BTN_PROTECTED ) ),\n aBtnHideCell ( this, ScResId( BTN_HIDE_ALL ) ),\n aBtnHideFormula ( this, ScResId( BTN_HIDE_FORMULAR ) ),\n aTxtHint ( this, ScResId( FT_HINT ) ),\n aFlPrint ( this, ScResId( FL_PRINT ) ),\n aBtnHidePrint ( this, ScResId( BTN_HIDE_PRINT ) ),\n aTxtHint2 ( this, ScResId( FT_HINT2 ) )\n{\n \/\/ diese Page braucht ExchangeSupport\n SetExchangeSupport();\n\n \/\/ States werden in Reset gesetzt\n bTriEnabled = bDontCare = bProtect = bHideForm = bHideCell = bHidePrint = FALSE;\n\n aBtnProtect.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );\n aBtnHideCell.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );\n aBtnHideFormula.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );\n aBtnHidePrint.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );\n\n FreeResource();\n}\n\n\/\/ -----------------------------------------------------------------------\n\n__EXPORT ScTabPageProtection::~ScTabPageProtection()\n{\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT* __EXPORT ScTabPageProtection::GetRanges()\n{\n return pProtectionRanges;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScTabPageProtection::Create( Window* pParent,\n const SfxItemSet& rAttrSet )\n{\n return ( new ScTabPageProtection( pParent, rAttrSet ) );\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid __EXPORT ScTabPageProtection::Reset( const SfxItemSet& rCoreAttrs )\n{\n \/\/ Variablen initialisieren\n\n USHORT nWhich = GetWhich( SID_SCATTR_PROTECTION );\n const ScProtectionAttr* pProtAttr = NULL;\n SfxItemState eItemState = rCoreAttrs.GetItemState( nWhich, FALSE,\n (const SfxPoolItem**)&pProtAttr );\n\n \/\/ handelt es sich um ein Default-Item?\n if ( eItemState == SFX_ITEM_DEFAULT )\n pProtAttr = (const ScProtectionAttr*)&(rCoreAttrs.Get(nWhich));\n \/\/ bei SFX_ITEM_DONTCARE auf 0 lassen\n\n bTriEnabled = ( pProtAttr == NULL ); \/\/ TriState, wenn DontCare\n bDontCare = bTriEnabled;\n if (bTriEnabled)\n {\n \/\/ Defaults, die erscheinen wenn ein TriState weggeklickt wird:\n \/\/ (weil alles zusammen ein Attribut ist, kann auch nur alles zusammen\n \/\/ auf DontCare stehen - #38543#)\n bProtect = TRUE;\n bHideForm = bHideCell = bHidePrint = FALSE;\n }\n else\n {\n bProtect = pProtAttr->GetProtection();\n bHideCell = pProtAttr->GetHideCell();\n bHideForm = pProtAttr->GetHideFormula();\n bHidePrint = pProtAttr->GetHidePrint();\n }\n\n \/\/ Controls initialisieren\n\n aBtnProtect .EnableTriState( bTriEnabled );\n aBtnHideCell .EnableTriState( bTriEnabled );\n aBtnHideFormula .EnableTriState( bTriEnabled );\n aBtnHidePrint .EnableTriState( bTriEnabled );\n\n UpdateButtons();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL __EXPORT ScTabPageProtection::FillItemSet( SfxItemSet& rCoreAttrs )\n{\n BOOL bAttrsChanged = FALSE;\n USHORT nWhich = GetWhich( SID_SCATTR_PROTECTION );\n const SfxPoolItem* pOldItem = GetOldItem( rCoreAttrs, SID_SCATTR_PROTECTION );\n const SfxItemSet& rOldSet = GetItemSet();\n SfxItemState eItemState = rOldSet.GetItemState( nWhich, FALSE );\n ScProtectionAttr aProtAttr;\n\n if ( !bDontCare )\n {\n aProtAttr.SetProtection( bProtect );\n aProtAttr.SetHideCell( bHideCell );\n aProtAttr.SetHideFormula( bHideForm );\n aProtAttr.SetHidePrint( bHidePrint );\n\n if ( bTriEnabled )\n bAttrsChanged = TRUE; \/\/ DontCare -> richtiger Wert\n else\n bAttrsChanged = !pOldItem || !( aProtAttr == *(const ScProtectionAttr*)pOldItem );\n }\n\n \/\/--------------------------------------------------\n\n if ( bAttrsChanged )\n rCoreAttrs.Put( aProtAttr );\n else if ( eItemState == SFX_ITEM_DEFAULT )\n rCoreAttrs.ClearItem( nWhich );\n\n return bAttrsChanged;\n}\n\n\/\/------------------------------------------------------------------------\n\nint __EXPORT ScTabPageProtection::DeactivatePage( SfxItemSet* pSet )\n{\n if ( pSet )\n FillItemSet( *pSet );\n\n return LEAVE_PAGE;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScTabPageProtection, ButtonClickHdl, TriStateBox*, pBox )\n{\n TriState eState = pBox->GetState();\n if ( eState == STATE_DONTKNOW )\n bDontCare = TRUE; \/\/ alles zusammen auf DontCare\n else\n {\n bDontCare = FALSE; \/\/ DontCare ueberall aus\n BOOL bOn = ( eState == STATE_CHECK ); \/\/ ausgewaehlter Wert\n\n if ( pBox == &aBtnProtect )\n bProtect = bOn;\n else if ( pBox == &aBtnHideCell )\n bHideCell = bOn;\n else if ( pBox == &aBtnHideFormula )\n bHideForm = bOn;\n else if ( pBox == &aBtnHidePrint )\n bHidePrint = bOn;\n else\n DBG_ERRORFILE(\"falscher Button\");\n }\n\n UpdateButtons(); \/\/ TriState und Enable-Logik\n\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScTabPageProtection::UpdateButtons()\n{\n if ( bDontCare )\n {\n aBtnProtect.SetState( STATE_DONTKNOW );\n aBtnHideCell.SetState( STATE_DONTKNOW );\n aBtnHideFormula.SetState( STATE_DONTKNOW );\n aBtnHidePrint.SetState( STATE_DONTKNOW );\n }\n else\n {\n aBtnProtect.SetState( bProtect ? STATE_CHECK : STATE_NOCHECK );\n aBtnHideCell.SetState( bHideCell ? STATE_CHECK : STATE_NOCHECK );\n aBtnHideFormula.SetState( bHideForm ? STATE_CHECK : STATE_NOCHECK );\n aBtnHidePrint.SetState( bHidePrint ? STATE_CHECK : STATE_NOCHECK );\n }\n\n BOOL bEnable = ( aBtnHideCell.GetState() != STATE_CHECK );\n {\n aBtnProtect.Enable( bEnable );\n aBtnHideFormula.Enable( bEnable );\n }\n}\n<commit_msg>INTEGRATION: CWS calcwarnings (1.6.110); FILE MERGED 2006\/12\/12 17:03:07 nn 1.6.110.1: #i69284# warning-free: ui, unxlngi6<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tabpages.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2007-02-27 13:00:23 $\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_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n#include \"global.hxx\"\n#include \"document.hxx\"\n#include \"attrib.hxx\"\n#include \"scresid.hxx\"\n#include \"sc.hrc\"\n\n#include \"attrdlg.hrc\"\n#include \"tabpages.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nstatic USHORT pProtectionRanges[] =\n{\n SID_SCATTR_PROTECTION,\n SID_SCATTR_PROTECTION,\n 0\n};\n\n\/\/========================================================================\n\/\/ Zellschutz-Tabpage:\n\/\/========================================================================\n\nScTabPageProtection::ScTabPageProtection( Window* pParent,\n const SfxItemSet& rCoreAttrs )\n : SfxTabPage ( pParent,\n ScResId( RID_SCPAGE_PROTECTION ),\n rCoreAttrs ),\n \/\/\n aFlProtect ( this, ScResId( FL_PROTECTION ) ),\n aBtnHideCell ( this, ScResId( BTN_HIDE_ALL ) ),\n aBtnProtect ( this, ScResId( BTN_PROTECTED ) ),\n aBtnHideFormula ( this, ScResId( BTN_HIDE_FORMULAR ) ),\n aTxtHint ( this, ScResId( FT_HINT ) ),\n aFlPrint ( this, ScResId( FL_PRINT ) ),\n aBtnHidePrint ( this, ScResId( BTN_HIDE_PRINT ) ),\n aTxtHint2 ( this, ScResId( FT_HINT2 ) )\n{\n \/\/ diese Page braucht ExchangeSupport\n SetExchangeSupport();\n\n \/\/ States werden in Reset gesetzt\n bTriEnabled = bDontCare = bProtect = bHideForm = bHideCell = bHidePrint = FALSE;\n\n aBtnProtect.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );\n aBtnHideCell.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );\n aBtnHideFormula.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );\n aBtnHidePrint.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );\n\n FreeResource();\n}\n\n\/\/ -----------------------------------------------------------------------\n\n__EXPORT ScTabPageProtection::~ScTabPageProtection()\n{\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT* __EXPORT ScTabPageProtection::GetRanges()\n{\n return pProtectionRanges;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScTabPageProtection::Create( Window* pParent,\n const SfxItemSet& rAttrSet )\n{\n return ( new ScTabPageProtection( pParent, rAttrSet ) );\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid __EXPORT ScTabPageProtection::Reset( const SfxItemSet& rCoreAttrs )\n{\n \/\/ Variablen initialisieren\n\n USHORT nWhich = GetWhich( SID_SCATTR_PROTECTION );\n const ScProtectionAttr* pProtAttr = NULL;\n SfxItemState eItemState = rCoreAttrs.GetItemState( nWhich, FALSE,\n (const SfxPoolItem**)&pProtAttr );\n\n \/\/ handelt es sich um ein Default-Item?\n if ( eItemState == SFX_ITEM_DEFAULT )\n pProtAttr = (const ScProtectionAttr*)&(rCoreAttrs.Get(nWhich));\n \/\/ bei SFX_ITEM_DONTCARE auf 0 lassen\n\n bTriEnabled = ( pProtAttr == NULL ); \/\/ TriState, wenn DontCare\n bDontCare = bTriEnabled;\n if (bTriEnabled)\n {\n \/\/ Defaults, die erscheinen wenn ein TriState weggeklickt wird:\n \/\/ (weil alles zusammen ein Attribut ist, kann auch nur alles zusammen\n \/\/ auf DontCare stehen - #38543#)\n bProtect = TRUE;\n bHideForm = bHideCell = bHidePrint = FALSE;\n }\n else\n {\n bProtect = pProtAttr->GetProtection();\n bHideCell = pProtAttr->GetHideCell();\n bHideForm = pProtAttr->GetHideFormula();\n bHidePrint = pProtAttr->GetHidePrint();\n }\n\n \/\/ Controls initialisieren\n\n aBtnProtect .EnableTriState( bTriEnabled );\n aBtnHideCell .EnableTriState( bTriEnabled );\n aBtnHideFormula .EnableTriState( bTriEnabled );\n aBtnHidePrint .EnableTriState( bTriEnabled );\n\n UpdateButtons();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL __EXPORT ScTabPageProtection::FillItemSet( SfxItemSet& rCoreAttrs )\n{\n BOOL bAttrsChanged = FALSE;\n USHORT nWhich = GetWhich( SID_SCATTR_PROTECTION );\n const SfxPoolItem* pOldItem = GetOldItem( rCoreAttrs, SID_SCATTR_PROTECTION );\n const SfxItemSet& rOldSet = GetItemSet();\n SfxItemState eItemState = rOldSet.GetItemState( nWhich, FALSE );\n ScProtectionAttr aProtAttr;\n\n if ( !bDontCare )\n {\n aProtAttr.SetProtection( bProtect );\n aProtAttr.SetHideCell( bHideCell );\n aProtAttr.SetHideFormula( bHideForm );\n aProtAttr.SetHidePrint( bHidePrint );\n\n if ( bTriEnabled )\n bAttrsChanged = TRUE; \/\/ DontCare -> richtiger Wert\n else\n bAttrsChanged = !pOldItem || !( aProtAttr == *(const ScProtectionAttr*)pOldItem );\n }\n\n \/\/--------------------------------------------------\n\n if ( bAttrsChanged )\n rCoreAttrs.Put( aProtAttr );\n else if ( eItemState == SFX_ITEM_DEFAULT )\n rCoreAttrs.ClearItem( nWhich );\n\n return bAttrsChanged;\n}\n\n\/\/------------------------------------------------------------------------\n\nint __EXPORT ScTabPageProtection::DeactivatePage( SfxItemSet* pSetP )\n{\n if ( pSetP )\n FillItemSet( *pSetP );\n\n return LEAVE_PAGE;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScTabPageProtection, ButtonClickHdl, TriStateBox*, pBox )\n{\n TriState eState = pBox->GetState();\n if ( eState == STATE_DONTKNOW )\n bDontCare = TRUE; \/\/ alles zusammen auf DontCare\n else\n {\n bDontCare = FALSE; \/\/ DontCare ueberall aus\n BOOL bOn = ( eState == STATE_CHECK ); \/\/ ausgewaehlter Wert\n\n if ( pBox == &aBtnProtect )\n bProtect = bOn;\n else if ( pBox == &aBtnHideCell )\n bHideCell = bOn;\n else if ( pBox == &aBtnHideFormula )\n bHideForm = bOn;\n else if ( pBox == &aBtnHidePrint )\n bHidePrint = bOn;\n else\n DBG_ERRORFILE(\"falscher Button\");\n }\n\n UpdateButtons(); \/\/ TriState und Enable-Logik\n\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScTabPageProtection::UpdateButtons()\n{\n if ( bDontCare )\n {\n aBtnProtect.SetState( STATE_DONTKNOW );\n aBtnHideCell.SetState( STATE_DONTKNOW );\n aBtnHideFormula.SetState( STATE_DONTKNOW );\n aBtnHidePrint.SetState( STATE_DONTKNOW );\n }\n else\n {\n aBtnProtect.SetState( bProtect ? STATE_CHECK : STATE_NOCHECK );\n aBtnHideCell.SetState( bHideCell ? STATE_CHECK : STATE_NOCHECK );\n aBtnHideFormula.SetState( bHideForm ? STATE_CHECK : STATE_NOCHECK );\n aBtnHidePrint.SetState( bHidePrint ? STATE_CHECK : STATE_NOCHECK );\n }\n\n BOOL bEnable = ( aBtnHideCell.GetState() != STATE_CHECK );\n {\n aBtnProtect.Enable( bEnable );\n aBtnHideFormula.Enable( bEnable );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX64M\/RX71M\/RX651\/RX65N\/RX66T グループ・システム制御\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017, 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"RX600\/system.hpp\"\r\n\r\n#ifndef F_ICLK\r\n# error \"system_io.hpp requires F_ICLK to be defined\"\r\n#endif\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief systen_io クラス\r\n\t\t@param[in]\tBASE_CLOCK\tベース・クロック周波数(12MHz)\r\n\t\t@param[in]\tINTR_CLOCK\t内臓クロック周波数(240MHz)\r\n\t\t@param[in]\tEXT_CLOCK\t外部クロックに入力を行う場合「true」\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t BASE_CLOCK = 12000000, uint32_t INTR_CLOCK = 240000000,\r\n\t\tbool EXT_CLOCK = false>\r\n\tstruct system_io {\r\n\r\n\t\tstatic uint8_t clock_div_(uint32_t clk) noexcept\r\n\t\t{\r\n\t\t\tuint8_t div = 0;\r\n\t\t\twhile(clk < INTR_CLOCK) {\r\n\t\t\t\t++div;\r\n\t\t\t\tclk <<= 1;\r\n\t\t\t}\r\n\t\t\treturn div;\r\n\t\t}\r\n\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief システム・クロックの設定\r\n\t\t*\/\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\tstatic void setup_system_clock() noexcept\r\n\t\t{\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\r\n\r\n\t\t\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 1ms wait\r\n\t\t\t\/\/ メインクロック強制発振とドライブ能力設定\r\n\t\t\tuint8_t modrv2 = 0b11;\r\n\t\t\tif(BASE_CLOCK > 20000000) modrv2 = 0b00;\r\n\t\t\telse if(BASE_CLOCK > 16000000) modrv2 = 0b01;\r\n\t\t\telse if(BASE_CLOCK > 8000000) modrv2 = 0b10;\r\n\t\t\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(modrv2)\r\n\t\t\t\t\t\t | device::SYSTEM::MOFCR.MOSEL.b(EXT_CLOCK);\r\n\/\/\/\t\t\t\t\t\t device::SYSTEM::MOFCR.MOFXIN.b(1)\r\n\t\t\tdevice::SYSTEM::MOSCCR.MOSTP = 0;\t\t\/\/ メインクロック発振器動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm(\"nop\"); }\r\n\r\n\t\t\t\/\/ RX71M、240MHz 時の MEMWAIT はスーパーバイザモードでの設定が必須なので、\r\n\t\t\t\/\/ device::SYSTEM::MEMWAIT = 1; は、start.s で設定される。\r\n\r\n#if defined(SIG_RX65N)\r\n\t\t\tif(F_ICLK >= 120000000) { \/\/ 120MHz 以上の場合設定\r\n\t\t\t\tdevice::SYSTEM::ROMWT = 0b10;\r\n\t\t\t} else if(F_ICLK >= 100000000) {\r\n\t\t\t\tdevice::SYSTEM::ROMWT = 0b01;\r\n\t\t\t} else if(F_ICLK >= 50000000) {\r\n\t\t\t\tdevice::SYSTEM::ROMWT = 0b00;\r\n\t\t\t}\r\n#endif\r\n#if defined(SIG_RX66T)\r\n\t\t\tif(F_ICLK > 120000000) { \/\/ 120MHz 以上の場合設定\r\n\t\t\t\tdevice::SYSTEM::MEMWAIT = 1;\r\n\t\t\t}\r\n#endif\r\n\t\t\t\/\/ (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110\r\n\t\t\t\/\/ ... MAX x30.0\r\n\t\t\tuint32_t n = INTR_CLOCK * 2 \/ BASE_CLOCK;\r\n\t\t\tif(n < 20) n = 20;\r\n\t\t\telse if(n > 60) n = 60;\r\n\t\t\tn -= 20;\r\n\t\t\tdevice::SYSTEM::PLLCR.STC = n + 0b010011; \/\/ base 240MHz(12MHz)\r\n\t\t\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm(\"nop\"); }\r\n\r\n\t\t\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(F_FCLK))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(clock_div_(F_ICLK))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.BCK.b(clock_div_(F_BCLK))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(clock_div_(F_PCLKA))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(clock_div_(F_PCLKB))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKC.b(clock_div_(F_PCLKC))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(clock_div_(F_PCLKD));\r\n\t\t\tdevice::SYSTEM::SCKCR2.UCK = 0b0100; \/\/ USB Clock: 1\/5 (120\/5=24)\r\n\t\t\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\r\n\r\n\t\t\t\/\/ クロック関係書き込み不許可\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA500;\r\n\r\n#if defined(SIG_RX65N) || defined(SIG_RX66T)\r\n\t\t\t\/\/ ROM キャッシュを有効(標準)\r\n\t\t\tdevice::SYSTEM::ROMCE = 1;\r\n#endif\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t\/\/-------------------------------------------------------------\/\/\r\n\t\/*!\r\n\t\t@brief ソフト・リセットの起動\r\n\t*\/\r\n\t\/\/-------------------------------------------------------------\/\/\r\n\tinline void assert_soft_reset()\r\n\t{\r\n\t\tdevice::SYSTEM::PRCR = 0xA502;\r\n\t\tdevice::SYSTEM::SWRR = 0xA501;\r\n\t\tdevice::SYSTEM::PRCR = 0xA500;\r\n\t}\r\n}\r\n<commit_msg>fix: base clock divider for RX66T<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX64M\/RX71M\/RX651\/RX65N\/RX66T グループ・システム制御\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017, 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"RX600\/system.hpp\"\r\n\r\n#ifndef F_ICLK\r\n# error \"system_io.hpp requires F_ICLK to be defined\"\r\n#endif\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief systen_io クラス\r\n\t\t@param[in]\tBASE_CLOCK\tベース・クロック周波数(12MHz)\r\n\t\t@param[in]\tINTR_CLOCK\t内臓クロック周波数(240MHz)\r\n\t\t@param[in]\tEXT_CLOCK\t外部クロックに入力を行う場合「true」\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t BASE_CLOCK = 12000000, uint32_t INTR_CLOCK = 240000000, bool EXT_CLOCK = false>\r\n\tstruct system_io {\r\n\r\n\t\tstatic uint8_t clock_div_(uint32_t clk) noexcept\r\n\t\t{\r\n\t\t\tuint8_t div = 0;\r\n\t\t\twhile(clk < INTR_CLOCK) {\r\n\t\t\t\t++div;\r\n\t\t\t\tclk <<= 1;\r\n\t\t\t}\r\n\t\t\treturn div;\r\n\t\t}\r\n\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief システム・クロックの設定\r\n\t\t*\/\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\tstatic void setup_system_clock() noexcept\r\n\t\t{\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\r\n\r\n\t\t\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 1ms wait\r\n\t\t\t\/\/ メインクロック強制発振とドライブ能力設定\r\n\t\t\tuint8_t modrv2 = 0b11;\r\n\t\t\tif(BASE_CLOCK > 20000000) modrv2 = 0b00;\r\n\t\t\telse if(BASE_CLOCK > 16000000) modrv2 = 0b01;\r\n\t\t\telse if(BASE_CLOCK > 8000000) modrv2 = 0b10;\r\n\t\t\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(modrv2)\r\n\t\t\t\t\t\t | device::SYSTEM::MOFCR.MOSEL.b(EXT_CLOCK);\r\n\/\/\/\t\t\t\t\t\t device::SYSTEM::MOFCR.MOFXIN.b(1)\r\n\t\t\tdevice::SYSTEM::MOSCCR.MOSTP = 0;\t\t\/\/ メインクロック発振器動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm(\"nop\"); }\r\n\r\n\t\t\t\/\/ RX71M、240MHz 時の MEMWAIT はスーパーバイザモードでの設定が必須なので、\r\n\t\t\t\/\/ device::SYSTEM::MEMWAIT = 1; は、start.s で設定される。\r\n\r\n#if defined(SIG_RX65N)\r\n\t\t\tif(F_ICLK >= 120000000) { \/\/ 120MHz 以上の場合設定\r\n\t\t\t\tdevice::SYSTEM::ROMWT = 0b10;\r\n\t\t\t} else if(F_ICLK >= 100000000) {\r\n\t\t\t\tdevice::SYSTEM::ROMWT = 0b01;\r\n\t\t\t} else if(F_ICLK >= 50000000) {\r\n\t\t\t\tdevice::SYSTEM::ROMWT = 0b00;\r\n\t\t\t}\r\n#endif\r\n#if defined(SIG_RX66T)\r\n\t\t\tif(F_ICLK > 120000000) { \/\/ 120MHz 以上の場合設定\r\n\t\t\t\tdevice::SYSTEM::MEMWAIT = 1;\r\n\t\t\t}\r\n#endif\r\n\t\t\t\/\/ (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110\r\n\t\t\t\/\/ ... MAX x30.0\r\n\t\t\tuint32_t n = INTR_CLOCK * 2 \/ BASE_CLOCK;\r\n\t\t\tif(n < 20) n = 20;\r\n\t\t\telse if(n > 60) n = 60;\r\n\t\t\tn -= 20;\r\n\t\t\tdevice::SYSTEM::PLLCR.STC = n + 0b010011; \/\/ base x10\r\n\t\t\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm(\"nop\"); }\r\n\r\n\t\t\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(F_FCLK))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(clock_div_(F_ICLK))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.BCK.b(clock_div_(F_BCLK))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(clock_div_(F_PCLKA))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(clock_div_(F_PCLKB))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKC.b(clock_div_(F_PCLKC))\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(clock_div_(F_PCLKD));\r\n\t\t\tdevice::SYSTEM::SCKCR2.UCK = 0b0100; \/\/ USB Clock: 1\/5 (120\/5=24)\r\n\t\t\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\r\n\r\n\t\t\t\/\/ クロック関係書き込み不許可\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA500;\r\n\r\n#if defined(SIG_RX65N) || defined(SIG_RX66T)\r\n\t\t\t\/\/ ROM キャッシュを有効(標準)\r\n\t\t\tdevice::SYSTEM::ROMCE = 1;\r\n#endif\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t\/\/-------------------------------------------------------------\/\/\r\n\t\/*!\r\n\t\t@brief ソフト・リセットの起動\r\n\t*\/\r\n\t\/\/-------------------------------------------------------------\/\/\r\n\tinline void assert_soft_reset()\r\n\t{\r\n\t\tdevice::SYSTEM::PRCR = 0xA502;\r\n\t\tdevice::SYSTEM::SWRR = 0xA501;\r\n\t\tdevice::SYSTEM::PRCR = 0xA500;\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX64M システム制御 @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"RX64M\/system.hpp\"\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief systen_io クラス\r\n\t\t@param[in]\tbase_clock\tベース・クロック周波数(12MHz)\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t base_clock = 12000000>\r\n\tstruct system_io {\r\n\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief システム・クロックの設定\r\n\t\t*\/\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\tvoid setup_system_clock()\r\n\t\t{\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\r\n\r\n\t\t\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 1ms wait\r\n\t\t\t\/\/ メインクロック強制発振とドライブ能力設定\r\n\t\t\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)\r\n\t\t\t\t\t\t | device::SYSTEM::MOFCR.MOFXIN.b(1);\r\n\t\t\tdevice::SYSTEM::MOSCCR.MOSTP = 0;\t\t\/\/ メインクロック発振器動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\r\n\r\n\t\t\t\/\/ Base Clock 12MHz\r\n\t\t\tdevice::SYSTEM::PLLCR.STC = 0b010011;\t\t\/\/ PLL 10 倍(120MHz)\r\n\t\t\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm(\"nop\"); }\r\n\r\n\t\t\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(1) \/\/ 1\/2 (120\/2=60)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(0) \/\/ 1\/1 (120\/1=120)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.BCK.b(1) \/\/ 1\/2 (120\/2=60)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(0) \/\/ 1\/1 (120\/1=120)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(1) \/\/ 1\/2 (120\/2=60)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKC.b(1) \/\/ 1\/2 (120\/2=60)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(1); \/\/ 1\/2 (120\/2=60)\r\n\t\t\tdevice::SYSTEM::SCKCR2.UCK = 0b0100; \/\/ USB Clock: 1\/5 (120\/5=24)\r\n\t\t\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\r\n\t\t}\r\n\t};\r\n}\r\n<commit_msg>add init port func<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX64M システム制御 @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"RX64M\/system.hpp\"\r\n\r\nnamespace device {\r\n\r\n\t\/\/-------------------------------------------------------------\/\/\r\n\t\/*!\r\n\t\t@brief ポートの初期設定\r\n\t*\/\r\n\t\/\/-------------------------------------------------------------\/\/\r\n\tstatic void init_port()\r\n\t{\r\n\t\tPORT0::PCR = 0xff;\r\n\t\tPORT1::PCR = 0xff;\r\n\t\tPORT2::PCR = 0xff;\r\n\t\tPORT3::PCR = 0xff;\r\n\t\tPORT4::PCR = 0xff;\r\n\t\tPORT5::PCR = 0xff;\r\n\t\tPORT6::PCR = 0xff;\r\n\t\tPORT7::PCR = 0xff;\r\n\t\tPORT8::PCR = 0xff;\r\n\t\tPORT9::PCR = 0xff;\r\n\t\tPORTA::PCR = 0xff;\r\n\t\tPORTB::PCR = 0xff;\r\n\t\tPORTC::PCR = 0xff;\r\n\t\tPORTD::PCR = 0xff;\r\n\t\tPORTE::PCR = 0xff;\r\n\t\tPORTF::PCR = 0xff;\r\n\t\tPORTG::PCR = 0xff;\r\n\t\tPORTJ::PCR = 0xff;\r\n\t}\r\n\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief systen_io クラス\r\n\t\t@param[in]\tbase_clock\tベース・クロック周波数(12MHz)\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t base_clock = 12000000>\r\n\tstruct system_io {\r\n\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief システム・クロックの設定\r\n\t\t*\/\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\tstatic void setup_system_clock()\r\n\t\t{\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\r\n\r\n\t\t\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 1ms wait\r\n\t\t\t\/\/ メインクロック強制発振とドライブ能力設定\r\n\t\t\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)\r\n\t\t\t\t\t\t | device::SYSTEM::MOFCR.MOFXIN.b(1);\r\n\t\t\tdevice::SYSTEM::MOSCCR.MOSTP = 0;\t\t\/\/ メインクロック発振器動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\r\n\r\n\t\t\t\/\/ Base Clock 12MHz\r\n\t\t\tdevice::SYSTEM::PLLCR.STC = 0b010011;\t\t\/\/ PLL 10 倍(120MHz)\r\n\t\t\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm(\"nop\"); }\r\n\r\n\t\t\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(1) \/\/ 1\/2 (120\/2=60)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(0) \/\/ 1\/1 (120\/1=120)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.BCK.b(1) \/\/ 1\/2 (120\/2=60)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(0) \/\/ 1\/1 (120\/1=120)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(1) \/\/ 1\/2 (120\/2=60)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKC.b(1) \/\/ 1\/2 (120\/2=60)\r\n\t\t\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(1); \/\/ 1\/2 (120\/2=60)\r\n\t\t\tdevice::SYSTEM::SCKCR2.UCK = 0b0100; \/\/ USB Clock: 1\/5 (120\/5=24)\r\n\t\t\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\r\n\t\t}\r\n\t};\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"Map.h\"\n\nMap::Map(sf::Vector2f position, float length)\n{\n this->position = position;\n start = position - sf::Vector2f(length\/2.f, 0);\n end = position + sf::Vector2f(length\/2.f, 0);\n\n leftUnits.emplace_back();\n rightUnits.emplace_back();\n}\n\nMap::~Map()\n{\n}\n\nvoid Map::update(float dt)\n{\n for(Unit& unit : leftUnits)\n {\n if(unit.moving)\n unit.advancement += unit.speed*dt;\n else\n rightUnits.front().life = std::max(0.f, rightUnits.front().life-unit.damage*dt);\n }\n\n for(Unit& unit : rightUnits)\n {\n if(unit.moving)\n unit.advancement += unit.speed*dt;\n else\n leftUnits.front().life = std::max(0.f, leftUnits.front().life-unit.damage*dt);\n }\n\n std::sort(leftUnits.begin(), leftUnits.end(), [](const Unit& first, const Unit& second){return first.advancement > second.advancement;});\n std::sort(rightUnits.begin(), rightUnits.end(), [](const Unit& first, const Unit& second){return first.advancement > second.advancement;});\n\n for(Unit& unit : leftUnits)\n unit.moving = ((unit.advancement+rightUnits.front().advancement+unit.range) <= 1.f);\n\n for(Unit& unit : rightUnits)\n unit.moving = ((unit.advancement+leftUnits.front().advancement+unit.range) <= 1.f);\n\n for(auto it = leftUnits.begin(); it != leftUnits.end(); it++)\n {\n if(it->life <= 0)\n it = leftUnits.begin() + (std::distance(leftUnits.begin(), leftUnits.erase(it)) - 1);\n }\n\n for(auto it = rightUnits.begin(); it != rightUnits.end(); it++)\n {\n if(it->life <= 0)\n it = rightUnits.begin() + (std::distance(rightUnits.begin(), rightUnits.erase(it)) - 1);\n }\n\n leftUnitSpawnTime += dt;\n rightUnitSpawnTime += dt;\n\n if(leftUnitSpawnTime >= leftUnitRate)\n {\n leftUnits.emplace_back();\n leftUnitSpawnTime -= leftUnitRate;\n }\n\n if(rightUnitSpawnTime >= rightUnitRate)\n {\n rightUnits.emplace_back();\n rightUnitSpawnTime -= rightUnitRate;\n }\n}\n\nvoid Map::render(sf::RenderTarget& target)\n{\n for(Unit& unit : leftUnits)\n unit.render(target, start + (end-start)*unit.advancement);\n\n for(Unit& unit : rightUnits)\n unit.render(target, end - (end-start)*unit.advancement);\n}\n<commit_msg>fixed some shit<commit_after>#include \"Map.h\"\n\nMap::Map(sf::Vector2f position, float length)\n{\n this->position = position;\n start = position - sf::Vector2f(length\/2.f, 0);\n end = position + sf::Vector2f(length\/2.f, 0);\n\n leftUnits.emplace_back();\n rightUnits.emplace_back();\n}\n\nMap::~Map()\n{\n}\n\nvoid Map::update(float dt)\n{\n for(Unit& unit : leftUnits)\n {\n if(unit.moving)\n unit.advancement += unit.speed*dt;\n else\n rightUnits.front().life = std::max(0.f, rightUnits.front().life-unit.damage*dt);\n }\n\n for(Unit& unit : rightUnits)\n {\n if(unit.moving)\n unit.advancement += unit.speed*dt;\n else\n leftUnits.front().life = std::max(0.f, leftUnits.front().life-unit.damage*dt);\n }\n\n std::sort(leftUnits.begin(), leftUnits.end(), [](const Unit& first, const Unit& second){return first.advancement > second.advancement;});\n std::sort(rightUnits.begin(), rightUnits.end(), [](const Unit& first, const Unit& second){return first.advancement > second.advancement;});\n\n for(Unit& unit : leftUnits)\n unit.moving = (rightUnits.size() ? (unit.advancement+rightUnits.front().advancement+unit.range) <= 1.f : true);\n\n for(Unit& unit : rightUnits)\n unit.moving = (leftUnits.size() ? (unit.advancement+leftUnits.front().advancement+unit.range) <= 1.f : true);\n\n for(auto it = leftUnits.begin(); it != leftUnits.end(); it++)\n {\n if(it->life <= 0 || it->advancement >= 1)\n it = leftUnits.begin() + (std::distance(leftUnits.begin(), leftUnits.erase(it)) - 1);\n }\n\n for(auto it = rightUnits.begin(); it != rightUnits.end(); it++)\n {\n if(it->life <= 0 || it->advancement >= 1)\n it = rightUnits.begin() + (std::distance(rightUnits.begin(), rightUnits.erase(it)) - 1);\n }\n\n leftUnitSpawnTime += dt;\n rightUnitSpawnTime += dt;\n\n if(leftUnitSpawnTime >= leftUnitRate)\n {\n leftUnits.emplace_back();\n leftUnitSpawnTime -= leftUnitRate;\n }\n\n if(rightUnitSpawnTime >= rightUnitRate)\n {\n rightUnits.emplace_back();\n rightUnitSpawnTime -= rightUnitRate;\n }\n}\n\nvoid Map::render(sf::RenderTarget& target)\n{\n for(Unit& unit : leftUnits)\n unit.render(target, start + (end-start)*unit.advancement);\n\n for(Unit& unit : rightUnits)\n unit.render(target, end - (end-start)*unit.advancement);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"algorithm.h\"\n#include \"all.h\"\n\n#include <cstdio>\n#include \"benchmark.h\"\n\n#include <cstdlib>\n\n\nclass Test {\n\n static const size_t size = 1024 * 4;\n static const size_t n = 16;\n\n const size_t iterations = 10;\n\n float* input[n];\n float output[n];\n float* const_vector;\n\npublic:\n Test() {\n for (size_t i=0; i < n; i++) {\n input[i] = new float[size];\n initialize_vector(input[i]);\n }\n\n const_vector = new float[size];\n initialize_vector(const_vector);\n }\n\n ~Test() {\n for (size_t i=0; i < n; i++) {\n delete[] input[i];\n }\n\n delete[] const_vector;\n }\n\n void run() {\n\n test_scalar(\"scalar\", scalar_dist_vectors);\n test_scalar(\"SSE\", sse_dist_vector);\n\n test(\"SSE (custom)\", sse_dist_vector_many);\n }\n\nprivate:\n void initialize_vector(float* v) {\n for (size_t i=0; i < size; i++) {\n v[i] = (rand() % 1000)\/1000.0 - 0.5;\n }\n }\n\n template <typename FUNCTION>\n void test_scalar(const char* name, FUNCTION function) {\n \n auto fn = [this, function]() {\n dist_vector_many(function, size, const_vector, n, input, output);\n };\n\n BEST_TIME(\/**\/, fn(), name, iterations, size);\n }\n\n template <typename FUNCTION>\n void test(const char* name, FUNCTION dist_vector_many) {\n \n auto fn = [this, dist_vector_many]() {\n dist_vector_many(size, const_vector, n, input, output);\n };\n\n BEST_TIME(\/**\/, fn(), name, iterations, size);\n }\n};\n\nint main() {\n \n Test test;\n\n test.run();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>More flexible tests<commit_after>#include \"algorithm.h\"\n#include \"all.h\"\n\n#include \"benchmark.h\"\n\n#include <vector>\n#include <cstdlib>\n#include <cstdio>\n#include <cassert>\n\n\nclass Test {\n\n const size_t size;\n const size_t count;\n\n const size_t iterations = 10;\n\n float** input;\n float* output;\n float* const_vector;\n\npublic:\n Test(size_t size_, size_t count_) : size(size_), count(count_) {\n\n assert(size % 64 == 0);\n assert(count % 4 == 0);\n\n input = new float*[count];\n for (size_t i=0; i < count; i++) {\n input[i] = new float[size];\n initialize_vector(input[i]);\n }\n\n output = new float[count];\n const_vector = new float[size];\n initialize_vector(const_vector);\n }\n\n ~Test() {\n for (size_t i=0; i < count; i++) {\n delete[] input[i];\n }\n\n delete[] input;\n delete[] output;\n delete[] const_vector;\n }\n\n void run() {\n\n test_scalar(\"scalar\", scalar_dist_vectors);\n test_scalar(\"SSE\", sse_dist_vector);\n\n test(\"SSE (custom)\", sse_dist_vector_many);\n }\n\nprivate:\n void initialize_vector(float* v) {\n for (size_t i=0; i < size; i++) {\n v[i] = (rand() % 1000)\/1000.0 - 0.5;\n }\n }\n\n template <typename FUNCTION>\n void test_scalar(const char* name, FUNCTION function) {\n \n auto fn = [this, function]() {\n dist_vector_many(function, size, const_vector, count, input, output);\n };\n\n BEST_TIME(\/**\/, fn(), name, iterations, size);\n }\n\n template <typename FUNCTION>\n void test(const char* name, FUNCTION dist_vector_many) {\n \n auto fn = [this, dist_vector_many]() {\n dist_vector_many(size, const_vector, count, input, output);\n };\n\n BEST_TIME(\/**\/, fn(), name, iterations, size);\n }\n};\n\nint main() {\n \n size_t vector_count[] = {8, 16, 32, 64, 128, 256};\n size_t vector_size[] = {64, 128, 256, 512, 1024, 1024*4, 1024*8};\n\n for (size_t count: vector_count) {\n for (size_t size: vector_size) {\n printf(\"vector size=%lu, count=%lu\\n\", size, count);\n Test test(size, count);\n\n test.run();\n }\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/audio_device\/android\/audio_record_jni.h\"\n\n#include <android\/log.h>\n\n#include \"webrtc\/base\/arraysize.h\"\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/modules\/audio_device\/android\/audio_common.h\"\n\n#define TAG \"AudioRecordJni\"\n#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)\n#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)\n#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)\n#define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)\n#define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)\n\nnamespace webrtc {\n\n\/\/ Number of bytes per audio frame.\n\/\/ Example: 16-bit PCM in mono => 1*(16\/8)=2 [bytes\/frame]\nstatic const int kBytesPerFrame = kNumChannels * (kBitsPerSample \/ 8);\n\n\/\/ We are unable to obtain exact measurements of the hardware delay on Android.\n\/\/ Instead, a lower bound (based on measurements) is used.\n\/\/ TODO(henrika): is it possible to improve this?\nstatic const int kHardwareDelayInMilliseconds = 100;\n\nstatic JavaVM* g_jvm = NULL;\nstatic jobject g_context = NULL;\nstatic jclass g_audio_record_class = NULL;\n\nvoid AudioRecordJni::SetAndroidAudioDeviceObjects(void* jvm, void* env,\n void* context) {\n ALOGD(\"SetAndroidAudioDeviceObjects%s\", GetThreadInfo().c_str());\n\n CHECK(jvm);\n CHECK(env);\n CHECK(context);\n\n g_jvm = reinterpret_cast<JavaVM*>(jvm);\n JNIEnv* jni = GetEnv(g_jvm);\n CHECK(jni) << \"AttachCurrentThread must be called on this tread\";\n\n \/\/ Protect context from being deleted during garbage collection.\n g_context = NewGlobalRef(jni, reinterpret_cast<jobject>(context));\n\n \/\/ Load the locally-defined WebRtcAudioRecord class and create a new global\n \/\/ reference to it.\n jclass local_class = FindClass(\n jni, \"org\/webrtc\/voiceengine\/WebRtcAudioRecord\");\n g_audio_record_class = reinterpret_cast<jclass>(\n NewGlobalRef(jni, local_class));\n\n \/\/ Register native methods with the WebRtcAudioRecord class. These methods\n \/\/ are declared private native in WebRtcAudioRecord.java.\n JNINativeMethod native_methods[] = {\n {\"nativeCacheDirectBufferAddress\", \"(Ljava\/nio\/ByteBuffer;J)V\",\n reinterpret_cast<void*>(\n &webrtc::AudioRecordJni::CacheDirectBufferAddress)},\n {\"nativeDataIsRecorded\", \"(IJ)V\",\n reinterpret_cast<void*>(&webrtc::AudioRecordJni::DataIsRecorded)}};\n jni->RegisterNatives(g_audio_record_class,\n native_methods, arraysize(native_methods));\n CHECK_EXCEPTION(jni) << \"Error during RegisterNatives\";\n}\n\nvoid AudioRecordJni::ClearAndroidAudioDeviceObjects() {\n ALOGD(\"ClearAndroidAudioDeviceObjects%s\", GetThreadInfo().c_str());\n JNIEnv* jni = GetEnv(g_jvm);\n CHECK(jni) << \"AttachCurrentThread must be called on this tread\";\n jni->UnregisterNatives(g_audio_record_class);\n CHECK_EXCEPTION(jni) << \"Error during UnregisterNatives\";\n DeleteGlobalRef(jni, g_audio_record_class);\n g_audio_record_class = NULL;\n DeleteGlobalRef(jni, g_context);\n g_context = NULL;\n g_jvm = NULL;\n}\n\nAudioRecordJni::AudioRecordJni()\n : j_audio_record_(NULL),\n direct_buffer_address_(NULL),\n direct_buffer_capacity_in_bytes_(0),\n frames_per_buffer_(0),\n initialized_(false),\n recording_(false),\n audio_device_buffer_(NULL),\n sample_rate_hz_(0) {\n ALOGD(\"ctor%s\", GetThreadInfo().c_str());\n CHECK(HasDeviceObjects());\n CreateJavaInstance();\n \/\/ Detach from this thread since we want to use the checker to verify calls\n \/\/ from the Java based audio thread.\n thread_checker_java_.DetachFromThread();\n}\n\nAudioRecordJni::~AudioRecordJni() {\n ALOGD(\"~dtor%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n Terminate();\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jni->DeleteGlobalRef(j_audio_record_);\n j_audio_record_ = NULL;\n}\n\nint32_t AudioRecordJni::Init() {\n ALOGD(\"Init%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n return 0;\n}\n\nint32_t AudioRecordJni::Terminate() {\n ALOGD(\"Terminate%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n StopRecording();\n return 0;\n}\n\nint32_t AudioRecordJni::InitRecording() {\n ALOGD(\"InitRecording%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n DCHECK(!initialized_);\n DCHECK(!recording_);\n if (initialized_ || recording_) {\n return -1;\n }\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID initRecordingID = GetMethodID(\n jni, g_audio_record_class, \"InitRecording\", \"(I)I\");\n jint frames_per_buffer = jni->CallIntMethod(\n j_audio_record_, initRecordingID, sample_rate_hz_);\n CHECK_EXCEPTION(jni);\n if (frames_per_buffer < 0) {\n ALOGE(\"InitRecording failed!\");\n return -1;\n }\n frames_per_buffer_ = frames_per_buffer;\n ALOGD(\"frames_per_buffer: %d\", frames_per_buffer_);\n CHECK_EQ(direct_buffer_capacity_in_bytes_,\n frames_per_buffer_ * kBytesPerFrame);\n initialized_ = true;\n return 0;\n}\n\nint32_t AudioRecordJni::StartRecording() {\n ALOGD(\"StartRecording%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n DCHECK(initialized_);\n DCHECK(!recording_);\n if (!initialized_ || recording_) {\n return -1;\n }\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID startRecordingID = GetMethodID(\n jni, g_audio_record_class, \"StartRecording\", \"()Z\");\n jboolean res = jni->CallBooleanMethod(j_audio_record_, startRecordingID);\n CHECK_EXCEPTION(jni);\n if (!res) {\n ALOGE(\"StartRecording failed!\");\n return -1;\n }\n return 0;\n}\n\nint32_t AudioRecordJni::StopRecording() {\n ALOGD(\"StopRecording%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n if (!initialized_) {\n return 0;\n }\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID stopRecordingID = GetMethodID(\n jni, g_audio_record_class, \"StopRecording\", \"()Z\");\n jboolean res = jni->CallBooleanMethod(j_audio_record_, stopRecordingID);\n CHECK_EXCEPTION(jni);\n if (!res) {\n ALOGE(\"StopRecording failed!\");\n return -1;\n }\n \/\/ If we don't detach here, we will hit a DCHECK in OnDataIsRecorded() next\n \/\/ time StartRecording() is called since it will create a new Java thread.\n thread_checker_java_.DetachFromThread();\n initialized_ = false;\n recording_ = false;\n return 0;\n\n}\n\nint32_t AudioRecordJni::RecordingDelay(uint16_t& delayMS) const { \/\/ NOLINT\n \/\/ TODO(henrika): is it possible to improve this estimate?\n delayMS = kHardwareDelayInMilliseconds;\n return 0;\n}\n\nvoid AudioRecordJni::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {\n ALOGD(\"AttachAudioBuffer\");\n DCHECK(thread_checker_.CalledOnValidThread());\n audio_device_buffer_ = audioBuffer;\n sample_rate_hz_ = GetNativeSampleRate();\n ALOGD(\"SetRecordingSampleRate(%d)\", sample_rate_hz_);\n audio_device_buffer_->SetRecordingSampleRate(sample_rate_hz_);\n audio_device_buffer_->SetRecordingChannels(kNumChannels);\n}\n\nbool AudioRecordJni::BuiltInAECIsAvailable() const {\n ALOGD(\"BuiltInAECIsAvailable%s\", GetThreadInfo().c_str());\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID builtInAECIsAvailable = jni->GetStaticMethodID(\n g_audio_record_class, \"BuiltInAECIsAvailable\", \"()Z\");\n CHECK_EXCEPTION(jni);\n CHECK(builtInAECIsAvailable);\n jboolean hw_aec = jni->CallStaticBooleanMethod(g_audio_record_class,\n builtInAECIsAvailable);\n CHECK_EXCEPTION(jni);\n return hw_aec;\n}\n\nint32_t AudioRecordJni::EnableBuiltInAEC(bool enable) {\n ALOGD(\"EnableBuiltInAEC%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID enableBuiltInAEC = GetMethodID(\n jni, g_audio_record_class, \"EnableBuiltInAEC\", \"(Z)Z\");\n jboolean res = jni->CallBooleanMethod(\n j_audio_record_, enableBuiltInAEC, enable);\n CHECK_EXCEPTION(jni);\n if (!res) {\n ALOGE(\"EnableBuiltInAEC failed!\");\n return -1;\n }\n return 0;\n}\n\nvoid JNICALL AudioRecordJni::CacheDirectBufferAddress(\n JNIEnv* env, jobject obj, jobject byte_buffer, jlong nativeAudioRecord) {\n webrtc::AudioRecordJni* this_object =\n reinterpret_cast<webrtc::AudioRecordJni*> (nativeAudioRecord);\n this_object->OnCacheDirectBufferAddress(env, byte_buffer);\n}\n\nvoid AudioRecordJni::OnCacheDirectBufferAddress(\n JNIEnv* env, jobject byte_buffer) {\n ALOGD(\"OnCacheDirectBufferAddress\");\n DCHECK(thread_checker_.CalledOnValidThread());\n direct_buffer_address_ =\n env->GetDirectBufferAddress(byte_buffer);\n jlong capacity = env->GetDirectBufferCapacity(byte_buffer);\n ALOGD(\"direct buffer capacity: %lld\", capacity);\n direct_buffer_capacity_in_bytes_ = static_cast<int> (capacity);\n}\n\nvoid JNICALL AudioRecordJni::DataIsRecorded(\n JNIEnv* env, jobject obj, jint length, jlong nativeAudioRecord) {\n webrtc::AudioRecordJni* this_object =\n reinterpret_cast<webrtc::AudioRecordJni*> (nativeAudioRecord );\n this_object->OnDataIsRecorded(length);\n}\n\n\/\/ This method is called on a high-priority thread from Java. The name of\n\/\/ the thread is 'AudioRecordThread'.\nvoid AudioRecordJni::OnDataIsRecorded(int length) {\n DCHECK(thread_checker_java_.CalledOnValidThread());\n audio_device_buffer_->SetRecordedBuffer(direct_buffer_address_,\n frames_per_buffer_);\n \/\/ TODO(henrika): improve playout delay estimate.\n audio_device_buffer_->SetVQEData(0, kHardwareDelayInMilliseconds, 0);\n audio_device_buffer_->DeliverRecordedData();\n}\n\nbool AudioRecordJni::HasDeviceObjects() {\n return (g_jvm && g_context && g_audio_record_class);\n}\n\nvoid AudioRecordJni::CreateJavaInstance() {\n ALOGD(\"CreateJavaInstance\");\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID constructorID = GetMethodID(\n jni, g_audio_record_class, \"<init>\", \"(Landroid\/content\/Context;J)V\");\n j_audio_record_ = jni->NewObject(g_audio_record_class,\n constructorID,\n g_context,\n reinterpret_cast<intptr_t>(this));\n CHECK_EXCEPTION(jni) << \"Error during NewObject\";\n CHECK(j_audio_record_);\n j_audio_record_ = jni->NewGlobalRef(j_audio_record_);\n CHECK_EXCEPTION(jni) << \"Error during NewGlobalRef\";\n CHECK(j_audio_record_);\n}\n\nint AudioRecordJni::GetNativeSampleRate() {\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID getNativeSampleRate = GetMethodID(\n jni, g_audio_record_class, \"GetNativeSampleRate\", \"()I\");\n jint sample_rate_hz = jni->CallIntMethod(\n j_audio_record_, getNativeSampleRate);\n CHECK_EXCEPTION(jni);\n return sample_rate_hz;\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Fix problem where Android VoE can not record on multiple channels.<commit_after>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/audio_device\/android\/audio_record_jni.h\"\n\n#include <android\/log.h>\n\n#include \"webrtc\/base\/arraysize.h\"\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/modules\/audio_device\/android\/audio_common.h\"\n\n#define TAG \"AudioRecordJni\"\n#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)\n#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)\n#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)\n#define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)\n#define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)\n\nnamespace webrtc {\n\n\/\/ Number of bytes per audio frame.\n\/\/ Example: 16-bit PCM in mono => 1*(16\/8)=2 [bytes\/frame]\nstatic const int kBytesPerFrame = kNumChannels * (kBitsPerSample \/ 8);\n\n\/\/ We are unable to obtain exact measurements of the hardware delay on Android.\n\/\/ Instead, a lower bound (based on measurements) is used.\n\/\/ TODO(henrika): is it possible to improve this?\nstatic const int kHardwareDelayInMilliseconds = 100;\n\nstatic JavaVM* g_jvm = NULL;\nstatic jobject g_context = NULL;\nstatic jclass g_audio_record_class = NULL;\n\nvoid AudioRecordJni::SetAndroidAudioDeviceObjects(void* jvm, void* env,\n void* context) {\n ALOGD(\"SetAndroidAudioDeviceObjects%s\", GetThreadInfo().c_str());\n\n CHECK(jvm);\n CHECK(env);\n CHECK(context);\n\n g_jvm = reinterpret_cast<JavaVM*>(jvm);\n JNIEnv* jni = GetEnv(g_jvm);\n CHECK(jni) << \"AttachCurrentThread must be called on this tread\";\n\n \/\/ Protect context from being deleted during garbage collection.\n g_context = NewGlobalRef(jni, reinterpret_cast<jobject>(context));\n\n \/\/ Load the locally-defined WebRtcAudioRecord class and create a new global\n \/\/ reference to it.\n jclass local_class = FindClass(\n jni, \"org\/webrtc\/voiceengine\/WebRtcAudioRecord\");\n g_audio_record_class = reinterpret_cast<jclass>(\n NewGlobalRef(jni, local_class));\n\n \/\/ Register native methods with the WebRtcAudioRecord class. These methods\n \/\/ are declared private native in WebRtcAudioRecord.java.\n JNINativeMethod native_methods[] = {\n {\"nativeCacheDirectBufferAddress\", \"(Ljava\/nio\/ByteBuffer;J)V\",\n reinterpret_cast<void*>(\n &webrtc::AudioRecordJni::CacheDirectBufferAddress)},\n {\"nativeDataIsRecorded\", \"(IJ)V\",\n reinterpret_cast<void*>(&webrtc::AudioRecordJni::DataIsRecorded)}};\n jni->RegisterNatives(g_audio_record_class,\n native_methods, arraysize(native_methods));\n CHECK_EXCEPTION(jni) << \"Error during RegisterNatives\";\n}\n\nvoid AudioRecordJni::ClearAndroidAudioDeviceObjects() {\n ALOGD(\"ClearAndroidAudioDeviceObjects%s\", GetThreadInfo().c_str());\n JNIEnv* jni = GetEnv(g_jvm);\n CHECK(jni) << \"AttachCurrentThread must be called on this tread\";\n jni->UnregisterNatives(g_audio_record_class);\n CHECK_EXCEPTION(jni) << \"Error during UnregisterNatives\";\n DeleteGlobalRef(jni, g_audio_record_class);\n g_audio_record_class = NULL;\n DeleteGlobalRef(jni, g_context);\n g_context = NULL;\n g_jvm = NULL;\n}\n\nAudioRecordJni::AudioRecordJni()\n : j_audio_record_(NULL),\n direct_buffer_address_(NULL),\n direct_buffer_capacity_in_bytes_(0),\n frames_per_buffer_(0),\n initialized_(false),\n recording_(false),\n audio_device_buffer_(NULL),\n sample_rate_hz_(0) {\n ALOGD(\"ctor%s\", GetThreadInfo().c_str());\n CHECK(HasDeviceObjects());\n CreateJavaInstance();\n \/\/ Detach from this thread since we want to use the checker to verify calls\n \/\/ from the Java based audio thread.\n thread_checker_java_.DetachFromThread();\n}\n\nAudioRecordJni::~AudioRecordJni() {\n ALOGD(\"~dtor%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n Terminate();\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jni->DeleteGlobalRef(j_audio_record_);\n j_audio_record_ = NULL;\n}\n\nint32_t AudioRecordJni::Init() {\n ALOGD(\"Init%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n return 0;\n}\n\nint32_t AudioRecordJni::Terminate() {\n ALOGD(\"Terminate%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n StopRecording();\n return 0;\n}\n\nint32_t AudioRecordJni::InitRecording() {\n ALOGD(\"InitRecording%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n DCHECK(!initialized_);\n DCHECK(!recording_);\n if (initialized_ || recording_) {\n return -1;\n }\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID initRecordingID = GetMethodID(\n jni, g_audio_record_class, \"InitRecording\", \"(I)I\");\n jint frames_per_buffer = jni->CallIntMethod(\n j_audio_record_, initRecordingID, sample_rate_hz_);\n CHECK_EXCEPTION(jni);\n if (frames_per_buffer < 0) {\n ALOGE(\"InitRecording failed!\");\n return -1;\n }\n frames_per_buffer_ = frames_per_buffer;\n ALOGD(\"frames_per_buffer: %d\", frames_per_buffer_);\n CHECK_EQ(direct_buffer_capacity_in_bytes_,\n frames_per_buffer_ * kBytesPerFrame);\n initialized_ = true;\n return 0;\n}\n\nint32_t AudioRecordJni::StartRecording() {\n ALOGD(\"StartRecording%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n DCHECK(initialized_);\n DCHECK(!recording_);\n if (!initialized_ || recording_) {\n return -1;\n }\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID startRecordingID = GetMethodID(\n jni, g_audio_record_class, \"StartRecording\", \"()Z\");\n jboolean res = jni->CallBooleanMethod(j_audio_record_, startRecordingID);\n CHECK_EXCEPTION(jni);\n if (!res) {\n ALOGE(\"StartRecording failed!\");\n return -1;\n }\n recording_ = true;\n return 0;\n}\n\nint32_t AudioRecordJni::StopRecording() {\n ALOGD(\"StopRecording%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n if (!initialized_) {\n return 0;\n }\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID stopRecordingID = GetMethodID(\n jni, g_audio_record_class, \"StopRecording\", \"()Z\");\n jboolean res = jni->CallBooleanMethod(j_audio_record_, stopRecordingID);\n CHECK_EXCEPTION(jni);\n if (!res) {\n ALOGE(\"StopRecording failed!\");\n return -1;\n }\n \/\/ If we don't detach here, we will hit a DCHECK in OnDataIsRecorded() next\n \/\/ time StartRecording() is called since it will create a new Java thread.\n thread_checker_java_.DetachFromThread();\n initialized_ = false;\n recording_ = false;\n return 0;\n\n}\n\nint32_t AudioRecordJni::RecordingDelay(uint16_t& delayMS) const { \/\/ NOLINT\n \/\/ TODO(henrika): is it possible to improve this estimate?\n delayMS = kHardwareDelayInMilliseconds;\n return 0;\n}\n\nvoid AudioRecordJni::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {\n ALOGD(\"AttachAudioBuffer\");\n DCHECK(thread_checker_.CalledOnValidThread());\n audio_device_buffer_ = audioBuffer;\n sample_rate_hz_ = GetNativeSampleRate();\n ALOGD(\"SetRecordingSampleRate(%d)\", sample_rate_hz_);\n audio_device_buffer_->SetRecordingSampleRate(sample_rate_hz_);\n audio_device_buffer_->SetRecordingChannels(kNumChannels);\n}\n\nbool AudioRecordJni::BuiltInAECIsAvailable() const {\n ALOGD(\"BuiltInAECIsAvailable%s\", GetThreadInfo().c_str());\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID builtInAECIsAvailable = jni->GetStaticMethodID(\n g_audio_record_class, \"BuiltInAECIsAvailable\", \"()Z\");\n CHECK_EXCEPTION(jni);\n CHECK(builtInAECIsAvailable);\n jboolean hw_aec = jni->CallStaticBooleanMethod(g_audio_record_class,\n builtInAECIsAvailable);\n CHECK_EXCEPTION(jni);\n return hw_aec;\n}\n\nint32_t AudioRecordJni::EnableBuiltInAEC(bool enable) {\n ALOGD(\"EnableBuiltInAEC%s\", GetThreadInfo().c_str());\n DCHECK(thread_checker_.CalledOnValidThread());\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID enableBuiltInAEC = GetMethodID(\n jni, g_audio_record_class, \"EnableBuiltInAEC\", \"(Z)Z\");\n jboolean res = jni->CallBooleanMethod(\n j_audio_record_, enableBuiltInAEC, enable);\n CHECK_EXCEPTION(jni);\n if (!res) {\n ALOGE(\"EnableBuiltInAEC failed!\");\n return -1;\n }\n return 0;\n}\n\nvoid JNICALL AudioRecordJni::CacheDirectBufferAddress(\n JNIEnv* env, jobject obj, jobject byte_buffer, jlong nativeAudioRecord) {\n webrtc::AudioRecordJni* this_object =\n reinterpret_cast<webrtc::AudioRecordJni*> (nativeAudioRecord);\n this_object->OnCacheDirectBufferAddress(env, byte_buffer);\n}\n\nvoid AudioRecordJni::OnCacheDirectBufferAddress(\n JNIEnv* env, jobject byte_buffer) {\n ALOGD(\"OnCacheDirectBufferAddress\");\n DCHECK(thread_checker_.CalledOnValidThread());\n direct_buffer_address_ =\n env->GetDirectBufferAddress(byte_buffer);\n jlong capacity = env->GetDirectBufferCapacity(byte_buffer);\n ALOGD(\"direct buffer capacity: %lld\", capacity);\n direct_buffer_capacity_in_bytes_ = static_cast<int> (capacity);\n}\n\nvoid JNICALL AudioRecordJni::DataIsRecorded(\n JNIEnv* env, jobject obj, jint length, jlong nativeAudioRecord) {\n webrtc::AudioRecordJni* this_object =\n reinterpret_cast<webrtc::AudioRecordJni*> (nativeAudioRecord );\n this_object->OnDataIsRecorded(length);\n}\n\n\/\/ This method is called on a high-priority thread from Java. The name of\n\/\/ the thread is 'AudioRecordThread'.\nvoid AudioRecordJni::OnDataIsRecorded(int length) {\n DCHECK(thread_checker_java_.CalledOnValidThread());\n audio_device_buffer_->SetRecordedBuffer(direct_buffer_address_,\n frames_per_buffer_);\n \/\/ TODO(henrika): improve playout delay estimate.\n audio_device_buffer_->SetVQEData(0, kHardwareDelayInMilliseconds, 0);\n audio_device_buffer_->DeliverRecordedData();\n}\n\nbool AudioRecordJni::HasDeviceObjects() {\n return (g_jvm && g_context && g_audio_record_class);\n}\n\nvoid AudioRecordJni::CreateJavaInstance() {\n ALOGD(\"CreateJavaInstance\");\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID constructorID = GetMethodID(\n jni, g_audio_record_class, \"<init>\", \"(Landroid\/content\/Context;J)V\");\n j_audio_record_ = jni->NewObject(g_audio_record_class,\n constructorID,\n g_context,\n reinterpret_cast<intptr_t>(this));\n CHECK_EXCEPTION(jni) << \"Error during NewObject\";\n CHECK(j_audio_record_);\n j_audio_record_ = jni->NewGlobalRef(j_audio_record_);\n CHECK_EXCEPTION(jni) << \"Error during NewGlobalRef\";\n CHECK(j_audio_record_);\n}\n\nint AudioRecordJni::GetNativeSampleRate() {\n AttachThreadScoped ats(g_jvm);\n JNIEnv* jni = ats.env();\n jmethodID getNativeSampleRate = GetMethodID(\n jni, g_audio_record_class, \"GetNativeSampleRate\", \"()I\");\n jint sample_rate_hz = jni->CallIntMethod(\n j_audio_record_, getNativeSampleRate);\n CHECK_EXCEPTION(jni);\n return sample_rate_hz;\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008-2016 the MRtrix3 contributors\n * \n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n * \n * MRtrix 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 * For more details, see www.mrtrix.org\n * \n *\/\n\n\n#include \"command.h\"\n#include \"progressbar.h\"\n#include \"image.h\"\n#include \"algo\/threaded_copy.h\"\n#include \"dwi\/gradient.h\"\n#include \"dwi\/tensor.h\"\n\nusing namespace MR;\nusing namespace App;\nusing namespace std;\n\ntypedef float value_type;\nconst int default_iter = 2;\n\nvoid usage ()\n{\n ARGUMENTS \n + Argument (\"dwi\", \"the input dwi image.\").type_image_in ()\n + Argument (\"dt\", \"the output dt image.\").type_image_out ();\n\n OPTIONS \n + Option (\"mask\", \"only perform computation within the specified binary brain mask image.\")\n + Argument (\"image\").type_image_in()\n + Option (\"b0\", \"the output b0 image.\")\n + Argument (\"image\").type_image_out()\n + Option (\"dkt\", \"the output dkt image.\")\n + Argument (\"image\").type_image_out()\n + Option (\"iter\",\"number of iterative reweightings (default: 2); set to 0 for ordinary linear least squares.\")\n + Argument (\"integer\").type_integer (0, default_iter, 10)\n + DWI::GradImportOptions();\n \n AUTHOR = \"Ben Jeurissen (ben.jeurissen@uantwerpen.be)\";\n \n COPYRIGHT = \"Copyright (C) 2015 Vision Lab, University of Antwerp, Belgium. \"\n \"This is free software; see the source for copying conditions. \"\n \"There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\";\n \n DESCRIPTION\n + \"Diffusion (kurtosis) tensor estimation using iteratively reweighted linear least squares estimator.\";\n \n REFERENCES \n + \"Veraart, J.; Sijbers, J.; Sunaert, S.; Leemans, A. & Jeurissen, B. \" \/\/ Internal\n \"Weighted linear least squares estimation of diffusion MRI parameters: strengths, limitations, and pitfalls. \"\n \"NeuroImage, 2013, 81, 335-346\";\n}\n\ntemplate <class MASKType, class B0Type, class DKTType>\nclass Processor\n{\n public:\n Processor (const Eigen::MatrixXd& b, const int iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image) :\n mask_image (mask_image),\n b0_image (b0_image),\n dkt_image (dkt_image),\n dwi(b.rows()),\n p(b.cols()),\n w(b.rows()),\n work(b.cols(),b.cols()),\n llt(work.rows()),\n b(b),\n maxit(iter) { }\n\n template <class DWIType, class DTType>\n void operator() (DWIType& dwi_image, DTType& dt_image)\n {\n if (mask_image) {\n assign_pos_of (dwi_image, 0, 3).to (*mask_image);\n if (!mask_image->value())\n return;\n }\n \n for (auto l = Loop (3) (dwi_image); l; ++l)\n dwi[dwi_image.index(3)] = dwi_image.value();\n \n double small_intensity = 1.0e-6 * dwi.maxCoeff(); \n for (int i = 0; i < dwi.rows(); i++) {\n if (dwi[i] < small_intensity)\n dwi[i] = small_intensity;\n dwi[i] = std::log (dwi[i]);\n }\n \n work.setZero();\n work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose());\n p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*dwi);\n for (int it = 0; it < maxit; it++) {\n w = (b*p).array().exp();\n work.setZero();\n work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose()*w.asDiagonal());\n p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*w.asDiagonal()*dwi);\n }\n \n if (b0_image) {\n assign_pos_of (dwi_image, 0, 3).to (*b0_image);\n b0_image->value() = exp(p[6]);\n }\n \n for (auto l = Loop(3)(dt_image); l; ++l) {\n dt_image.value() = p[dt_image.index(3)];\n }\n \n if (dkt_image) {\n assign_pos_of (dwi_image, 0, 3).to (*dkt_image);\n double adc_sq = (p[0]+p[1]+p[2])*(p[0]+p[1]+p[2])\/9.0;\n for (auto l = Loop(3)(*dkt_image); l; ++l) {\n dkt_image->value() = p[dkt_image->index(3)+7]\/adc_sq;\n }\n }\n }\n\n private:\n copy_ptr<MASKType> mask_image;\n copy_ptr<B0Type> b0_image;\n copy_ptr<DKTType> dkt_image;\n Eigen::VectorXd dwi;\n Eigen::VectorXd p;\n Eigen::VectorXd w;\n Eigen::MatrixXd work;\n Eigen::LLT<Eigen::MatrixXd> llt;\n const Eigen::MatrixXd& b;\n const int maxit;\n};\n\ntemplate <class MASKType, class B0Type, class DKTType> \ninline Processor<MASKType, B0Type, DKTType> processor (const Eigen::MatrixXd& b, const int& iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image) {\n return { b, iter, mask_image, b0_image, dkt_image };\n}\n\nvoid run ()\n{\n auto dwi = Header::open (argument[0]).get_image<value_type>();\n auto grad = DWI::get_valid_DW_scheme (dwi.original_header());\n \n Image<bool>* mask = nullptr;\n auto opt = get_options (\"mask\");\n if (opt.size()) {\n mask = new Image<bool> (Image<bool>::open (opt[0][0]));\n check_dimensions (dwi, *mask, 0, 3);\n }\n \n auto iter = get_option_value (\"iter\", default_iter);\n\n auto header = dwi.original_header();\n header.datatype() = DataType::Float32;\n header.set_ndim (4);\n header.size(3) = 6;\n auto dt = Header::create (argument[1], header).get_image<value_type>();\n\n Image<value_type>* b0 = nullptr;\n opt = get_options (\"b0\");\n if (opt.size()) {\n header.set_ndim (3);\n b0 = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n }\n\n Image<value_type>* dkt = nullptr;\n opt = get_options (\"dkt\");\n if (opt.size()) {\n header.set_ndim (4);\n header.size(3) = 15;\n dkt = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n }\n \n Eigen::MatrixXd b = -DWI::grad2bmatrix<double> (grad, opt.size()>0);\n\n ThreadedLoop(\"computing tensors\", dwi, 0, 3).run (processor (b, iter, mask, b0, dkt), dwi, dt);\n}\n\n<commit_msg>dwi2tensor: Fixing up order of references block<commit_after>\/*\n * Copyright (c) 2008-2016 the MRtrix3 contributors\n * \n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n * \n * MRtrix 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 * For more details, see www.mrtrix.org\n * \n *\/\n\n\n#include \"command.h\"\n#include \"progressbar.h\"\n#include \"image.h\"\n#include \"algo\/threaded_copy.h\"\n#include \"dwi\/gradient.h\"\n#include \"dwi\/tensor.h\"\n\nusing namespace MR;\nusing namespace App;\nusing namespace std;\n\ntypedef float value_type;\nconst int default_iter = 2;\n\nvoid usage ()\n{\n\n REFERENCES\n + \"Veraart, J.; Sijbers, J.; Sunaert, S.; Leemans, A. & Jeurissen, B. \" \/\/ Internal\n \"Weighted linear least squares estimation of diffusion MRI parameters: strengths, limitations, and pitfalls. \"\n \"NeuroImage, 2013, 81, 335-346\";\n\n ARGUMENTS\n + Argument (\"dwi\", \"the input dwi image.\").type_image_in ()\n + Argument (\"dt\", \"the output dt image.\").type_image_out ();\n\n OPTIONS \n + Option (\"mask\", \"only perform computation within the specified binary brain mask image.\")\n + Argument (\"image\").type_image_in()\n + Option (\"b0\", \"the output b0 image.\")\n + Argument (\"image\").type_image_out()\n + Option (\"dkt\", \"the output dkt image.\")\n + Argument (\"image\").type_image_out()\n + Option (\"iter\",\"number of iterative reweightings (default: 2); set to 0 for ordinary linear least squares.\")\n + Argument (\"integer\").type_integer (0, default_iter, 10)\n + DWI::GradImportOptions();\n \n AUTHOR = \"Ben Jeurissen (ben.jeurissen@uantwerpen.be)\";\n \n COPYRIGHT = \"Copyright (C) 2015 Vision Lab, University of Antwerp, Belgium. \"\n \"This is free software; see the source for copying conditions. \"\n \"There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\";\n \n DESCRIPTION\n + \"Diffusion (kurtosis) tensor estimation using iteratively reweighted linear least squares estimator.\";\n}\n\ntemplate <class MASKType, class B0Type, class DKTType>\nclass Processor\n{\n public:\n Processor (const Eigen::MatrixXd& b, const int iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image) :\n mask_image (mask_image),\n b0_image (b0_image),\n dkt_image (dkt_image),\n dwi(b.rows()),\n p(b.cols()),\n w(b.rows()),\n work(b.cols(),b.cols()),\n llt(work.rows()),\n b(b),\n maxit(iter) { }\n\n template <class DWIType, class DTType>\n void operator() (DWIType& dwi_image, DTType& dt_image)\n {\n if (mask_image) {\n assign_pos_of (dwi_image, 0, 3).to (*mask_image);\n if (!mask_image->value())\n return;\n }\n \n for (auto l = Loop (3) (dwi_image); l; ++l)\n dwi[dwi_image.index(3)] = dwi_image.value();\n \n double small_intensity = 1.0e-6 * dwi.maxCoeff(); \n for (int i = 0; i < dwi.rows(); i++) {\n if (dwi[i] < small_intensity)\n dwi[i] = small_intensity;\n dwi[i] = std::log (dwi[i]);\n }\n \n work.setZero();\n work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose());\n p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*dwi);\n for (int it = 0; it < maxit; it++) {\n w = (b*p).array().exp();\n work.setZero();\n work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose()*w.asDiagonal());\n p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*w.asDiagonal()*dwi);\n }\n \n if (b0_image) {\n assign_pos_of (dwi_image, 0, 3).to (*b0_image);\n b0_image->value() = exp(p[6]);\n }\n \n for (auto l = Loop(3)(dt_image); l; ++l) {\n dt_image.value() = p[dt_image.index(3)];\n }\n \n if (dkt_image) {\n assign_pos_of (dwi_image, 0, 3).to (*dkt_image);\n double adc_sq = (p[0]+p[1]+p[2])*(p[0]+p[1]+p[2])\/9.0;\n for (auto l = Loop(3)(*dkt_image); l; ++l) {\n dkt_image->value() = p[dkt_image->index(3)+7]\/adc_sq;\n }\n }\n }\n\n private:\n copy_ptr<MASKType> mask_image;\n copy_ptr<B0Type> b0_image;\n copy_ptr<DKTType> dkt_image;\n Eigen::VectorXd dwi;\n Eigen::VectorXd p;\n Eigen::VectorXd w;\n Eigen::MatrixXd work;\n Eigen::LLT<Eigen::MatrixXd> llt;\n const Eigen::MatrixXd& b;\n const int maxit;\n};\n\ntemplate <class MASKType, class B0Type, class DKTType> \ninline Processor<MASKType, B0Type, DKTType> processor (const Eigen::MatrixXd& b, const int& iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image) {\n return { b, iter, mask_image, b0_image, dkt_image };\n}\n\nvoid run ()\n{\n auto dwi = Header::open (argument[0]).get_image<value_type>();\n auto grad = DWI::get_valid_DW_scheme (dwi.original_header());\n \n Image<bool>* mask = nullptr;\n auto opt = get_options (\"mask\");\n if (opt.size()) {\n mask = new Image<bool> (Image<bool>::open (opt[0][0]));\n check_dimensions (dwi, *mask, 0, 3);\n }\n \n auto iter = get_option_value (\"iter\", default_iter);\n\n auto header = dwi.original_header();\n header.datatype() = DataType::Float32;\n header.set_ndim (4);\n header.size(3) = 6;\n auto dt = Header::create (argument[1], header).get_image<value_type>();\n\n Image<value_type>* b0 = nullptr;\n opt = get_options (\"b0\");\n if (opt.size()) {\n header.set_ndim (3);\n b0 = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n }\n\n Image<value_type>* dkt = nullptr;\n opt = get_options (\"dkt\");\n if (opt.size()) {\n header.set_ndim (4);\n header.size(3) = 15;\n dkt = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n }\n \n Eigen::MatrixXd b = -DWI::grad2bmatrix<double> (grad, opt.size()>0);\n\n ThreadedLoop(\"computing tensors\", dwi, 0, 3).run (processor (b, iter, mask, b0, dkt), dwi, dt);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- llvm\/CodeGen\/MachineModuleInfo.cpp ----------------------*- C++ -*-===\/\/\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#include \"llvm\/CodeGen\/MachineModuleInfo.h\"\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Analysis\/ValueTracking.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/Dwarf.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/Streams.h\"\nusing namespace llvm;\nusing namespace llvm::dwarf;\n\n\/\/ Handle the Pass registration stuff necessary to use TargetData's.\nstatic RegisterPass<MachineModuleInfo>\nX(\"machinemoduleinfo\", \"Module Information\");\nchar MachineModuleInfo::ID = 0;\n\n\/\/===----------------------------------------------------------------------===\/\/\n \nMachineModuleInfo::MachineModuleInfo()\n: ImmutablePass(&ID)\n, LabelIDList()\n, FrameMoves()\n, LandingPads()\n, Personalities()\n, CallsEHReturn(0)\n, CallsUnwindInit(0)\n, DbgInfoAvailable(false)\n{\n \/\/ Always emit \"no personality\" info\n Personalities.push_back(NULL);\n}\nMachineModuleInfo::~MachineModuleInfo() {\n\n}\n\n\/\/\/ doInitialization - Initialize the state for a new module.\n\/\/\/\nbool MachineModuleInfo::doInitialization() {\n return false;\n}\n\n\/\/\/ doFinalization - Tear down the state after completion of a module.\n\/\/\/\nbool MachineModuleInfo::doFinalization() {\n return false;\n}\n\n\/\/\/ BeginFunction - Begin gathering function meta information.\n\/\/\/\nvoid MachineModuleInfo::BeginFunction(MachineFunction *MF) {\n \/\/ Coming soon.\n}\n\n\/\/\/ EndFunction - Discard function meta information.\n\/\/\/\nvoid MachineModuleInfo::EndFunction() {\n \/\/ Clean up frame info.\n FrameMoves.clear();\n \n \/\/ Clean up exception info.\n LandingPads.clear();\n TypeInfos.clear();\n FilterIds.clear();\n FilterEnds.clear();\n CallsEHReturn = 0;\n CallsUnwindInit = 0;\n}\n\n\/\/\/ AnalyzeModule - Scan the module for global debug information.\n\/\/\/\nvoid MachineModuleInfo::AnalyzeModule(Module &M) {\n \/\/ Insert functions in the llvm.used array into UsedFunctions.\n GlobalVariable *GV = M.getGlobalVariable(\"llvm.used\");\n if (!GV || !GV->hasInitializer()) return;\n\n \/\/ Should be an array of 'i8*'.\n ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());\n if (InitList == 0) return;\n\n for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {\n if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InitList->getOperand(i)))\n if (CE->getOpcode() == Instruction::BitCast)\n if (Function *F = dyn_cast<Function>(CE->getOperand(0)))\n UsedFunctions.insert(F);\n }\n}\n\n\/\/===-EH-------------------------------------------------------------------===\/\/\n\n\/\/\/ getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the\n\/\/\/ specified MachineBasicBlock.\nLandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo\n (MachineBasicBlock *LandingPad) {\n unsigned N = LandingPads.size();\n for (unsigned i = 0; i < N; ++i) {\n LandingPadInfo &LP = LandingPads[i];\n if (LP.LandingPadBlock == LandingPad)\n return LP;\n }\n \n LandingPads.push_back(LandingPadInfo(LandingPad));\n return LandingPads[N];\n}\n\n\/\/\/ addInvoke - Provide the begin and end labels of an invoke style call and\n\/\/\/ associate it with a try landing pad block.\nvoid MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,\n unsigned BeginLabel, unsigned EndLabel) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n LP.BeginLabels.push_back(BeginLabel);\n LP.EndLabels.push_back(EndLabel);\n}\n\n\/\/\/ addLandingPad - Provide the label of a try LandingPad block.\n\/\/\/\nunsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {\n unsigned LandingPadLabel = NextLabelID();\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n LP.LandingPadLabel = LandingPadLabel; \n return LandingPadLabel;\n}\n\n\/\/\/ addPersonality - Provide the personality function for the exception\n\/\/\/ information.\nvoid MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,\n Function *Personality) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n LP.Personality = Personality;\n\n for (unsigned i = 0; i < Personalities.size(); ++i)\n if (Personalities[i] == Personality)\n return;\n \n Personalities.push_back(Personality);\n}\n\n\/\/\/ addCatchTypeInfo - Provide the catch typeinfo for a landing pad.\n\/\/\/\nvoid MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,\n std::vector<GlobalVariable *> &TyInfo) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n for (unsigned N = TyInfo.size(); N; --N)\n LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));\n}\n\n\/\/\/ addFilterTypeInfo - Provide the filter typeinfo for a landing pad.\n\/\/\/\nvoid MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,\n std::vector<GlobalVariable *> &TyInfo) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n std::vector<unsigned> IdsInFilter(TyInfo.size());\n for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)\n IdsInFilter[I] = getTypeIDFor(TyInfo[I]);\n LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));\n}\n\n\/\/\/ addCleanup - Add a cleanup action for a landing pad.\n\/\/\/\nvoid MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n LP.TypeIds.push_back(0);\n}\n\n\/\/\/ TidyLandingPads - Remap landing pad labels and remove any deleted landing\n\/\/\/ pads.\nvoid MachineModuleInfo::TidyLandingPads() {\n for (unsigned i = 0; i != LandingPads.size(); ) {\n LandingPadInfo &LandingPad = LandingPads[i];\n LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);\n\n \/\/ Special case: we *should* emit LPs with null LP MBB. This indicates\n \/\/ \"nounwind\" case.\n if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {\n LandingPads.erase(LandingPads.begin() + i);\n continue;\n }\n\n for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {\n unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);\n unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);\n\n if (!BeginLabel || !EndLabel) {\n LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);\n LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);\n continue;\n }\n\n LandingPad.BeginLabels[j] = BeginLabel;\n LandingPad.EndLabels[j] = EndLabel;\n ++j;\n }\n\n \/\/ Remove landing pads with no try-ranges.\n if (LandingPads[i].BeginLabels.empty()) {\n LandingPads.erase(LandingPads.begin() + i);\n continue;\n }\n\n \/\/ If there is no landing pad, ensure that the list of typeids is empty.\n \/\/ If the only typeid is a cleanup, this is the same as having no typeids.\n if (!LandingPad.LandingPadBlock ||\n (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))\n LandingPad.TypeIds.clear();\n\n ++i;\n }\n}\n\n\/\/\/ getTypeIDFor - Return the type id for the specified typeinfo. This is \n\/\/\/ function wide.\nunsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {\n for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)\n if (TypeInfos[i] == TI) return i + 1;\n\n TypeInfos.push_back(TI);\n return TypeInfos.size();\n}\n\n\/\/\/ getFilterIDFor - Return the filter id for the specified typeinfos. This is\n\/\/\/ function wide.\nint MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {\n \/\/ If the new filter coincides with the tail of an existing filter, then\n \/\/ re-use the existing filter. Folding filters more than this requires\n \/\/ re-ordering filters and\/or their elements - probably not worth it.\n for (std::vector<unsigned>::iterator I = FilterEnds.begin(),\n E = FilterEnds.end(); I != E; ++I) {\n unsigned i = *I, j = TyIds.size();\n\n while (i && j)\n if (FilterIds[--i] != TyIds[--j])\n goto try_next;\n\n if (!j)\n \/\/ The new filter coincides with range [i, end) of the existing filter.\n return -(1 + i);\n\ntry_next:;\n }\n\n \/\/ Add the new filter.\n int FilterID = -(1 + FilterIds.size());\n FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);\n for (unsigned I = 0, N = TyIds.size(); I != N; ++I)\n FilterIds.push_back(TyIds[I]);\n FilterEnds.push_back(FilterIds.size());\n FilterIds.push_back(0); \/\/ terminator\n return FilterID;\n}\n\n\/\/\/ getPersonality - Return the personality function for the current function.\nFunction *MachineModuleInfo::getPersonality() const {\n \/\/ FIXME: Until PR1414 will be fixed, we're using 1 personality function per\n \/\/ function\n return !LandingPads.empty() ? LandingPads[0].Personality : NULL;\n}\n\n\/\/\/ getPersonalityIndex - Return unique index for current personality\n\/\/\/ function. NULL personality function should always get zero index.\nunsigned MachineModuleInfo::getPersonalityIndex() const {\n const Function* Personality = NULL;\n \n \/\/ Scan landing pads. If there is at least one non-NULL personality - use it.\n for (unsigned i = 0; i != LandingPads.size(); ++i)\n if (LandingPads[i].Personality) {\n Personality = LandingPads[i].Personality;\n break;\n }\n \n for (unsigned i = 0; i < Personalities.size(); ++i) {\n if (Personalities[i] == Personality)\n return i;\n }\n\n \/\/ This should never happen\n llvm_unreachable(\"Personality function should be set!\");\n return 0;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/ DebugLabelFolding pass - This pass prunes out redundant labels. This allows\n\/\/\/ a info consumer to determine if the range of two labels is empty, by seeing\n\/\/\/ if the labels map to the same reduced label.\n\nnamespace llvm {\n\nstruct DebugLabelFolder : public MachineFunctionPass {\n static char ID;\n DebugLabelFolder() : MachineFunctionPass(&ID) {}\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addPreservedID(MachineLoopInfoID);\n AU.addPreservedID(MachineDominatorsID);\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n virtual bool runOnMachineFunction(MachineFunction &MF);\n virtual const char *getPassName() const { return \"Label Folder\"; }\n};\n\nchar DebugLabelFolder::ID = 0;\n\nbool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {\n \/\/ Get machine module info.\n MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();\n if (!MMI) return false;\n \n \/\/ Track if change is made.\n bool MadeChange = false;\n \/\/ No prior label to begin.\n unsigned PriorLabel = 0;\n \n \/\/ Iterate through basic blocks.\n for (MachineFunction::iterator BB = MF.begin(), E = MF.end();\n BB != E; ++BB) {\n \/\/ Iterate through instructions.\n for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {\n \/\/ Is it a label.\n if (I->isDebugLabel() && !MMI->isDbgLabelUsed(I->getOperand(0).getImm())){\n \/\/ The label ID # is always operand #0, an immediate.\n unsigned NextLabel = I->getOperand(0).getImm();\n \n \/\/ If there was an immediate prior label.\n if (PriorLabel) {\n \/\/ Remap the current label to prior label.\n MMI->RemapLabel(NextLabel, PriorLabel);\n \/\/ Delete the current label.\n I = BB->erase(I);\n \/\/ Indicate a change has been made.\n MadeChange = true;\n continue;\n } else {\n \/\/ Start a new round.\n PriorLabel = NextLabel;\n }\n } else {\n \/\/ No consecutive labels.\n PriorLabel = 0;\n }\n \n ++I;\n }\n }\n \n return MadeChange;\n}\n\nFunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }\n\n}\n\n<commit_msg>use stripPointerCasts to simplify some code.<commit_after>\/\/===-- llvm\/CodeGen\/MachineModuleInfo.cpp ----------------------*- C++ -*-===\/\/\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#include \"llvm\/CodeGen\/MachineModuleInfo.h\"\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Analysis\/ValueTracking.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/Dwarf.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/Streams.h\"\nusing namespace llvm;\nusing namespace llvm::dwarf;\n\n\/\/ Handle the Pass registration stuff necessary to use TargetData's.\nstatic RegisterPass<MachineModuleInfo>\nX(\"machinemoduleinfo\", \"Module Information\");\nchar MachineModuleInfo::ID = 0;\n\n\/\/===----------------------------------------------------------------------===\/\/\n \nMachineModuleInfo::MachineModuleInfo()\n: ImmutablePass(&ID)\n, LabelIDList()\n, FrameMoves()\n, LandingPads()\n, Personalities()\n, CallsEHReturn(0)\n, CallsUnwindInit(0)\n, DbgInfoAvailable(false)\n{\n \/\/ Always emit \"no personality\" info\n Personalities.push_back(NULL);\n}\nMachineModuleInfo::~MachineModuleInfo() {\n\n}\n\n\/\/\/ doInitialization - Initialize the state for a new module.\n\/\/\/\nbool MachineModuleInfo::doInitialization() {\n return false;\n}\n\n\/\/\/ doFinalization - Tear down the state after completion of a module.\n\/\/\/\nbool MachineModuleInfo::doFinalization() {\n return false;\n}\n\n\/\/\/ BeginFunction - Begin gathering function meta information.\n\/\/\/\nvoid MachineModuleInfo::BeginFunction(MachineFunction *MF) {\n \/\/ Coming soon.\n}\n\n\/\/\/ EndFunction - Discard function meta information.\n\/\/\/\nvoid MachineModuleInfo::EndFunction() {\n \/\/ Clean up frame info.\n FrameMoves.clear();\n \n \/\/ Clean up exception info.\n LandingPads.clear();\n TypeInfos.clear();\n FilterIds.clear();\n FilterEnds.clear();\n CallsEHReturn = 0;\n CallsUnwindInit = 0;\n}\n\n\/\/\/ AnalyzeModule - Scan the module for global debug information.\n\/\/\/\nvoid MachineModuleInfo::AnalyzeModule(Module &M) {\n \/\/ Insert functions in the llvm.used array into UsedFunctions.\n GlobalVariable *GV = M.getGlobalVariable(\"llvm.used\");\n if (!GV || !GV->hasInitializer()) return;\n\n \/\/ Should be an array of 'i8*'.\n ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());\n if (InitList == 0) return;\n\n for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)\n if (Function *F =\n dyn_cast<Function>(InitList->getOperand(i)->stripPointerCasts()))\n UsedFunctions.insert(F);\n}\n\n\/\/===-EH-------------------------------------------------------------------===\/\/\n\n\/\/\/ getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the\n\/\/\/ specified MachineBasicBlock.\nLandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo\n (MachineBasicBlock *LandingPad) {\n unsigned N = LandingPads.size();\n for (unsigned i = 0; i < N; ++i) {\n LandingPadInfo &LP = LandingPads[i];\n if (LP.LandingPadBlock == LandingPad)\n return LP;\n }\n \n LandingPads.push_back(LandingPadInfo(LandingPad));\n return LandingPads[N];\n}\n\n\/\/\/ addInvoke - Provide the begin and end labels of an invoke style call and\n\/\/\/ associate it with a try landing pad block.\nvoid MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,\n unsigned BeginLabel, unsigned EndLabel) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n LP.BeginLabels.push_back(BeginLabel);\n LP.EndLabels.push_back(EndLabel);\n}\n\n\/\/\/ addLandingPad - Provide the label of a try LandingPad block.\n\/\/\/\nunsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {\n unsigned LandingPadLabel = NextLabelID();\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n LP.LandingPadLabel = LandingPadLabel; \n return LandingPadLabel;\n}\n\n\/\/\/ addPersonality - Provide the personality function for the exception\n\/\/\/ information.\nvoid MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,\n Function *Personality) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n LP.Personality = Personality;\n\n for (unsigned i = 0; i < Personalities.size(); ++i)\n if (Personalities[i] == Personality)\n return;\n \n Personalities.push_back(Personality);\n}\n\n\/\/\/ addCatchTypeInfo - Provide the catch typeinfo for a landing pad.\n\/\/\/\nvoid MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,\n std::vector<GlobalVariable *> &TyInfo) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n for (unsigned N = TyInfo.size(); N; --N)\n LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));\n}\n\n\/\/\/ addFilterTypeInfo - Provide the filter typeinfo for a landing pad.\n\/\/\/\nvoid MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,\n std::vector<GlobalVariable *> &TyInfo) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n std::vector<unsigned> IdsInFilter(TyInfo.size());\n for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)\n IdsInFilter[I] = getTypeIDFor(TyInfo[I]);\n LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));\n}\n\n\/\/\/ addCleanup - Add a cleanup action for a landing pad.\n\/\/\/\nvoid MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {\n LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);\n LP.TypeIds.push_back(0);\n}\n\n\/\/\/ TidyLandingPads - Remap landing pad labels and remove any deleted landing\n\/\/\/ pads.\nvoid MachineModuleInfo::TidyLandingPads() {\n for (unsigned i = 0; i != LandingPads.size(); ) {\n LandingPadInfo &LandingPad = LandingPads[i];\n LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);\n\n \/\/ Special case: we *should* emit LPs with null LP MBB. This indicates\n \/\/ \"nounwind\" case.\n if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {\n LandingPads.erase(LandingPads.begin() + i);\n continue;\n }\n\n for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {\n unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);\n unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);\n\n if (!BeginLabel || !EndLabel) {\n LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);\n LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);\n continue;\n }\n\n LandingPad.BeginLabels[j] = BeginLabel;\n LandingPad.EndLabels[j] = EndLabel;\n ++j;\n }\n\n \/\/ Remove landing pads with no try-ranges.\n if (LandingPads[i].BeginLabels.empty()) {\n LandingPads.erase(LandingPads.begin() + i);\n continue;\n }\n\n \/\/ If there is no landing pad, ensure that the list of typeids is empty.\n \/\/ If the only typeid is a cleanup, this is the same as having no typeids.\n if (!LandingPad.LandingPadBlock ||\n (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))\n LandingPad.TypeIds.clear();\n\n ++i;\n }\n}\n\n\/\/\/ getTypeIDFor - Return the type id for the specified typeinfo. This is \n\/\/\/ function wide.\nunsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {\n for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)\n if (TypeInfos[i] == TI) return i + 1;\n\n TypeInfos.push_back(TI);\n return TypeInfos.size();\n}\n\n\/\/\/ getFilterIDFor - Return the filter id for the specified typeinfos. This is\n\/\/\/ function wide.\nint MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {\n \/\/ If the new filter coincides with the tail of an existing filter, then\n \/\/ re-use the existing filter. Folding filters more than this requires\n \/\/ re-ordering filters and\/or their elements - probably not worth it.\n for (std::vector<unsigned>::iterator I = FilterEnds.begin(),\n E = FilterEnds.end(); I != E; ++I) {\n unsigned i = *I, j = TyIds.size();\n\n while (i && j)\n if (FilterIds[--i] != TyIds[--j])\n goto try_next;\n\n if (!j)\n \/\/ The new filter coincides with range [i, end) of the existing filter.\n return -(1 + i);\n\ntry_next:;\n }\n\n \/\/ Add the new filter.\n int FilterID = -(1 + FilterIds.size());\n FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);\n for (unsigned I = 0, N = TyIds.size(); I != N; ++I)\n FilterIds.push_back(TyIds[I]);\n FilterEnds.push_back(FilterIds.size());\n FilterIds.push_back(0); \/\/ terminator\n return FilterID;\n}\n\n\/\/\/ getPersonality - Return the personality function for the current function.\nFunction *MachineModuleInfo::getPersonality() const {\n \/\/ FIXME: Until PR1414 will be fixed, we're using 1 personality function per\n \/\/ function\n return !LandingPads.empty() ? LandingPads[0].Personality : NULL;\n}\n\n\/\/\/ getPersonalityIndex - Return unique index for current personality\n\/\/\/ function. NULL personality function should always get zero index.\nunsigned MachineModuleInfo::getPersonalityIndex() const {\n const Function* Personality = NULL;\n \n \/\/ Scan landing pads. If there is at least one non-NULL personality - use it.\n for (unsigned i = 0; i != LandingPads.size(); ++i)\n if (LandingPads[i].Personality) {\n Personality = LandingPads[i].Personality;\n break;\n }\n \n for (unsigned i = 0; i < Personalities.size(); ++i) {\n if (Personalities[i] == Personality)\n return i;\n }\n\n \/\/ This should never happen\n llvm_unreachable(\"Personality function should be set!\");\n return 0;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/ DebugLabelFolding pass - This pass prunes out redundant labels. This allows\n\/\/\/ a info consumer to determine if the range of two labels is empty, by seeing\n\/\/\/ if the labels map to the same reduced label.\n\nnamespace llvm {\n\nstruct DebugLabelFolder : public MachineFunctionPass {\n static char ID;\n DebugLabelFolder() : MachineFunctionPass(&ID) {}\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addPreservedID(MachineLoopInfoID);\n AU.addPreservedID(MachineDominatorsID);\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n virtual bool runOnMachineFunction(MachineFunction &MF);\n virtual const char *getPassName() const { return \"Label Folder\"; }\n};\n\nchar DebugLabelFolder::ID = 0;\n\nbool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {\n \/\/ Get machine module info.\n MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();\n if (!MMI) return false;\n \n \/\/ Track if change is made.\n bool MadeChange = false;\n \/\/ No prior label to begin.\n unsigned PriorLabel = 0;\n \n \/\/ Iterate through basic blocks.\n for (MachineFunction::iterator BB = MF.begin(), E = MF.end();\n BB != E; ++BB) {\n \/\/ Iterate through instructions.\n for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {\n \/\/ Is it a label.\n if (I->isDebugLabel() && !MMI->isDbgLabelUsed(I->getOperand(0).getImm())){\n \/\/ The label ID # is always operand #0, an immediate.\n unsigned NextLabel = I->getOperand(0).getImm();\n \n \/\/ If there was an immediate prior label.\n if (PriorLabel) {\n \/\/ Remap the current label to prior label.\n MMI->RemapLabel(NextLabel, PriorLabel);\n \/\/ Delete the current label.\n I = BB->erase(I);\n \/\/ Indicate a change has been made.\n MadeChange = true;\n continue;\n } else {\n \/\/ Start a new round.\n PriorLabel = NextLabel;\n }\n } else {\n \/\/ No consecutive labels.\n PriorLabel = 0;\n }\n \n ++I;\n }\n }\n \n return MadeChange;\n}\n\nFunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Author: Ben Lau (https:\/\/github.com\/benlau)\n#include <QCoreApplication>\n#include <QPointer>\n#include <QtCore>\n#include <QPair>\n#include <QQueue>\n#include \"systemdispatcher.h\"\n\nusing namespace AndroidNative;\n\nstatic QPointer<SystemDispatcher> m_instance;\n\nQString SystemDispatcher::ACTIVITY_RESUME_MESSAGE = \"Activity.onResume\";\nQString SystemDispatcher::ACTIVITY_RESULT_MESSAGE = \"Activity.onActivityResult\";\nstatic bool registerNativesCalled = false;\n\n#ifdef Q_OS_ANDROID\n#include <QAndroidJniObject>\n#include <QAndroidJniEnvironment>\n\n#define JCLASS_Name \"androidnative\/SystemDispatcher\"\n#define DISPATCH_SIGNATURE \"(Ljava\/lang\/String;Ljava\/util\/Map;)V\"\n#define EMIT_SIGNATURE \"(Ljava\/lang\/String;Ljava\/util\/Map;)V\"\n\nstatic QVariantMap createVariantMap(jobject data);\nstatic jobject createHashMap(const QVariantMap &data);\n\nstatic QVariant convertToQVariant(QAndroidJniObject value) {\n QVariant v;\n if (!value.isValid()) {\n return v;\n }\n\n QAndroidJniEnvironment env;\n\n jclass jclass_of_string = env->FindClass(\"java\/lang\/String\");\n jclass jclass_of_integer = env->FindClass(\"java\/lang\/Integer\");\n jclass jclass_of_boolean = env->FindClass(\"java\/lang\/Boolean\");\n jclass jclass_of_list = env->FindClass(\"java\/util\/List\");\n jclass jclass_of_map = env->FindClass(\"java\/util\/Map\");\n\n if (env->IsInstanceOf(value.object<jobject>(),jclass_of_boolean)) {\n v = QVariant::fromValue<bool>(value.callMethod<jboolean>(\"booleanValue\",\"()Z\"));\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_integer)) {\n v = value.callMethod<jint>(\"intValue\",\"()I\");\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_string)) {\n v = value.toString();\n } else if (env->IsInstanceOf(value.object<jobject>(), jclass_of_map)) {\n v = createVariantMap(value.object<jobject>());\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_list)) {\n QVariantList list;\n int count = value.callMethod<jint>(\"size\",\"()I\");\n for (int i = 0 ; i < count ; i++) {\n QAndroidJniObject item = value.callObjectMethod(\"get\",\"(I)Ljava\/lang\/Object;\",i);\n list.append(convertToQVariant(item));\n }\n v = list;\n }\n\n env->DeleteLocalRef(jclass_of_string);\n env->DeleteLocalRef(jclass_of_integer);\n env->DeleteLocalRef(jclass_of_boolean);\n env->DeleteLocalRef(jclass_of_list);\n env->DeleteLocalRef(jclass_of_map);\n\n return v;\n}\n\nstatic QVariantMap createVariantMap(jobject data) {\n QVariantMap res;\n\n QAndroidJniEnvironment env;\n \/* Reference : https:\/\/community.oracle.com\/thread\/1549999 *\/\n\n \/\/ Get the HashMap Class\n jclass jclass_of_hashmap = (env)->GetObjectClass(data);\n\n \/\/ Get link to Method \"entrySet\"\n jmethodID entrySetMethod = (env)->GetMethodID(jclass_of_hashmap, \"entrySet\", \"()Ljava\/util\/Set;\");\n\n \/\/ Invoke the \"entrySet\" method on the HashMap object\n jobject jobject_of_entryset = env->CallObjectMethod(data, entrySetMethod);\n\n \/\/ Get the Set Class\n jclass jclass_of_set = (env)->FindClass(\"java\/util\/Set\"); \/\/ Problem during compilation !!!!!\n\n if (jclass_of_set == 0) {\n qWarning() << \"java\/util\/Set lookup failed\\n\";\n return res;\n }\n\n \/\/ Get link to Method \"iterator\"\n jmethodID iteratorMethod = env->GetMethodID(jclass_of_set, \"iterator\", \"()Ljava\/util\/Iterator;\");\n\n \/\/ Invoke the \"iterator\" method on the jobject_of_entryset variable of type Set\n jobject jobject_of_iterator = env->CallObjectMethod(jobject_of_entryset, iteratorMethod);\n\n \/\/ Get the \"Iterator\" class\n jclass jclass_of_iterator = (env)->FindClass(\"java\/util\/Iterator\");\n\n \/\/ Get link to Method \"hasNext\"\n jmethodID hasNextMethod = env->GetMethodID(jclass_of_iterator, \"hasNext\", \"()Z\");\n\n jmethodID nextMethod = env->GetMethodID(jclass_of_iterator, \"next\", \"()Ljava\/lang\/Object;\");\n\n while (env->CallBooleanMethod(jobject_of_iterator, hasNextMethod) ) {\n jobject jEntry = env->CallObjectMethod(jobject_of_iterator,nextMethod);\n QAndroidJniObject entry = QAndroidJniObject(jEntry);\n QAndroidJniObject key = entry.callObjectMethod(\"getKey\",\"()Ljava\/lang\/Object;\");\n QAndroidJniObject value = entry.callObjectMethod(\"getValue\",\"()Ljava\/lang\/Object;\");\n QString k = key.toString();\n\n QVariant v = convertToQVariant(value);\n\n env->DeleteLocalRef(jEntry);\n\n if (v.isNull()) {\n continue;\n }\n\n res[k] = v;\n }\n\n if (env->ExceptionOccurred()) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n }\n\n env->DeleteLocalRef(jclass_of_hashmap);\n env->DeleteLocalRef(jobject_of_entryset);\n env->DeleteLocalRef(jclass_of_set);\n env->DeleteLocalRef(jobject_of_iterator);\n env->DeleteLocalRef(jclass_of_iterator);\n\n return res;\n}\n\nstatic jobject convertToJObject(QVariant v) {\n jobject res = 0;\n QAndroidJniEnvironment env;\n\n if (v.type() == QVariant::String) {\n QString str = v.toString();\n res = env->NewStringUTF(str.toLocal8Bit().data());\n } else if (v.type() == QVariant::Int) {\n jclass integerClass = env->FindClass(\"java\/lang\/Integer\");\n jmethodID integerConstructor = env->GetMethodID(integerClass, \"<init>\", \"(I)V\");\n\n res = env->NewObject(integerClass,integerConstructor,v.toInt());\n\n env->DeleteLocalRef(integerClass);\n } else if (v.type() == QVariant::Bool) {\n jclass booleanClass = env->FindClass(\"java\/lang\/Boolean\");\n jmethodID booleanConstructor = env->GetMethodID(booleanClass,\"<init>\",\"(Z)V\");\n\n res = env->NewObject(booleanClass,booleanConstructor,v.toBool());\n\n env->DeleteLocalRef(booleanClass);\n\n } else if (v.type() == QVariant::Map) {\n res = createHashMap(v.toMap());\n } else if (v.type() == QVariant::List){\n QVariantList list = v.value<QVariantList>();\n jclass arrayListClass = env->FindClass(\"java\/util\/ArrayList\");\n jmethodID init = env->GetMethodID(arrayListClass, \"<init>\", \"(I)V\");\n res = env->NewObject( arrayListClass, init, list.size());\n\n jmethodID add = env->GetMethodID( arrayListClass, \"add\",\n \"(Ljava\/lang\/Object;)Z\");\n\n for (int i = 0 ; i < list.size() ; i++) {\n jobject item = convertToJObject(list.at(i));\n env->CallBooleanMethod(res,add, item);\n env->DeleteLocalRef(item);\n }\n\n env->DeleteLocalRef(arrayListClass);\n } else {\n qWarning() << \"ANSystemDispatcher: Non-supported data type - \" << v.type();\n }\n return res;\n}\n\nstatic jobject createHashMap(const QVariantMap &data) {\n QAndroidJniEnvironment env;\n\n jclass mapClass = env->FindClass(\"java\/util\/HashMap\");\n\n if (mapClass == NULL) {\n qWarning() << \"Failed to find class\" << \"java\/util\/HashMap\";\n return NULL;\n }\n\n jsize map_len = data.size();\n\n jmethodID init = env->GetMethodID(mapClass, \"<init>\", \"(I)V\");\n jobject hashMap = env->NewObject( mapClass, init, map_len);\n\n jmethodID put = env->GetMethodID( mapClass, \"put\",\n \"(Ljava\/lang\/Object;Ljava\/lang\/Object;)Ljava\/lang\/Object;\");\n\n QMapIterator<QString, QVariant> iter(data);\n while (iter.hasNext()) {\n iter.next();\n\n QString key = iter.key();\n jstring jkey = env->NewStringUTF(key.toLocal8Bit().data());\n QVariant v = iter.value();\n jobject item = convertToJObject(v);\n\n if (item == 0) {\n continue;\n }\n\n env->CallObjectMethod(hashMap,put,jkey,item);\n env->DeleteLocalRef(item);\n env->DeleteLocalRef(jkey);\n }\n\n if (env->ExceptionOccurred()) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n }\n\n env->DeleteLocalRef(mapClass);\n\n return hashMap;\n}\n\nstatic void jniEmit(JNIEnv* env,jobject object,jstring name,jobject data) {\n Q_UNUSED(object);\n Q_UNUSED(env);\n\n QAndroidJniObject tmp(name);\n QString str = tmp.toString();\n\n QVariantMap map;\n\n if (data != 0) {\n map = createVariantMap(data);\n }\n\n if (m_instance.isNull()) {\n return;\n }\n\n QMetaObject::invokeMethod(m_instance.data(),\"dispatched\",Qt::AutoConnection,\n Q_ARG(QString, str),\n Q_ARG(QVariantMap,map));\n}\n\nstatic void printInstruction() {\n static bool printOnce = false;\n\n if (printOnce) {\n return;\n }\n printOnce = true;\n\n \/\/ BuildMyString.com generated code. Please enjoy your string responsibly.\n\n QString msg = \"Using SystemDispatcher in Android but SystemDispatcher::registerNatives() is never called. Instruction: \\r\\n\"\n \"https:\/\/github.com\/benlau\/androidnative.pri\/blob\/master\/docs\/installation.md\\r\\n\";\n\n qWarning() << msg;\n}\n#endif\n\nAndroidNative::SystemDispatcher::SystemDispatcher(QObject* parent) : QObject(parent)\n{\n}\n\nAndroidNative::SystemDispatcher::~SystemDispatcher()\n{\n}\n\nAndroidNative::SystemDispatcher *SystemDispatcher::instance()\n{\n if (!m_instance) {\n QCoreApplication* app = QCoreApplication::instance();\n m_instance = new SystemDispatcher(app);\n }\n return m_instance;\n}\n\nvoid AndroidNative::SystemDispatcher::dispatch(QString type, QVariantMap message)\n{\n Q_UNUSED(type);\n Q_UNUSED(message);\n\n#ifdef Q_OS_ANDROID\n if (!registerNativesCalled) {\n printInstruction();\n }\n\n QAndroidJniEnvironment env;\n\n jstring jType = env->NewStringUTF(type.toLocal8Bit().data());\n jobject jData = createHashMap(message);\n QAndroidJniObject::callStaticMethod<void>(JCLASS_Name, \"dispatch\",\n DISPATCH_SIGNATURE,\n jType,jData);\n env->DeleteLocalRef(jType);\n env->DeleteLocalRef(jData);\n\n#else\n static bool dispatching = false;\n static QQueue<QPair<QString,QVariantMap> > queue;\n\n\n if (dispatching) {\n queue.enqueue(QPair<QString,QVariantMap> (type,message) );\n return;\n }\n\n dispatching = true;\n emit dispatched(type,message);\n\n while (queue.size() > 0) {\n QPair<QString,QVariantMap> pair = queue.dequeue();\n emit dispatched(pair.first,pair.second);\n }\n dispatching = false;\n#endif\n}\n\nvoid AndroidNative::SystemDispatcher::loadClass(QString javaClassName)\n{\n QVariantMap message;\n message[\"className\"] = javaClassName;\n\n dispatch(\"androidnative.SystemDispatcher.loadClass\",message);\n}\n\nvoid AndroidNative::SystemDispatcher::registerNatives()\n{\n Q_UNUSED(registerNativesCalled);\n\n#ifdef Q_OS_ANDROID\n registerNativesCalled = true;\n\n QAndroidJniEnvironment env;\n jclass clazz = env->FindClass(JCLASS_Name);\n if (!clazz)\n {\n qCritical() << \"androidNative.SystemDispatcher Java class is not found. Please configure your build.gradle according to this instruction: \\r\\n\"\n \"https:\/\/github.com\/benlau\/androidnative.pri\/blob\/master\/docs\/installation.md\\r\\n\";\n if (env->ExceptionOccurred()) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n }\n return;\n }\n\n JNINativeMethod methods[] =\n {\n {\"jniEmit\", EMIT_SIGNATURE, (void *)&jniEmit},\n };\n\n int numMethods = sizeof(methods) \/ sizeof(methods[0]);\n if (env->RegisterNatives(clazz, methods, numMethods) < 0) {\n if (env->ExceptionOccurred()) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n qCritical() << \"Exception occurred!!!\";\n return;\n }\n }\n\n QAndroidJniObject::callStaticMethod<void>(JCLASS_Name, \"init\",\n \"()V\");\n#endif\n}\n<commit_msg>support for long,float and double data types in systemdispatcher<commit_after>\/\/ Author: Ben Lau (https:\/\/github.com\/benlau)\n#include <QCoreApplication>\n#include <QPointer>\n#include <QtCore>\n#include <QPair>\n#include <QQueue>\n#include \"systemdispatcher.h\"\n\nusing namespace AndroidNative;\n\nstatic QPointer<SystemDispatcher> m_instance;\n\nQString SystemDispatcher::ACTIVITY_RESUME_MESSAGE = \"Activity.onResume\";\nQString SystemDispatcher::ACTIVITY_RESULT_MESSAGE = \"Activity.onActivityResult\";\nstatic bool registerNativesCalled = false;\n\n#ifdef Q_OS_ANDROID\n#include <QAndroidJniObject>\n#include <QAndroidJniEnvironment>\n\n#define JCLASS_Name \"androidnative\/SystemDispatcher\"\n#define DISPATCH_SIGNATURE \"(Ljava\/lang\/String;Ljava\/util\/Map;)V\"\n#define EMIT_SIGNATURE \"(Ljava\/lang\/String;Ljava\/util\/Map;)V\"\n\nstatic QVariantMap createVariantMap(jobject data);\nstatic jobject createHashMap(const QVariantMap &data);\n\nstatic QVariant convertToQVariant(QAndroidJniObject value) {\n QVariant v;\n if (!value.isValid()) {\n return v;\n }\n\n QAndroidJniEnvironment env;\n\n jclass jclass_of_string = env->FindClass(\"java\/lang\/String\");\n jclass jclass_of_integer = env->FindClass(\"java\/lang\/Integer\");\n jclass jclass_of_long = env->FindClass(\"java\/lang\/Long\");\n jclass jclass_of_float = env->FindClass(\"java\/lang\/Float\");\n jclass jclass_of_double = env->FindClass(\"java\/lang\/Double\");\n jclass jclass_of_boolean = env->FindClass(\"java\/lang\/Boolean\");\n jclass jclass_of_list = env->FindClass(\"java\/util\/List\");\n jclass jclass_of_map = env->FindClass(\"java\/util\/Map\");\n\n if (env->IsInstanceOf(value.object<jobject>(),jclass_of_boolean)) {\n v = QVariant::fromValue<bool>(value.callMethod<jboolean>(\"booleanValue\",\"()Z\"));\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_integer)) {\n v = value.callMethod<jint>(\"intValue\",\"()I\");\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_string)) {\n v = value.toString();\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_long)) {\n v = value.callMethod<jlong>(\"longValue\",\"()J\");\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_float)) {\n v = value.callMethod<jfloat>(\"floatValue\",\"()F\");\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_double)) {\n v = value.callMethod<jdouble>(\"doubleValue\",\"()D\");\n } else if (env->IsInstanceOf(value.object<jobject>(), jclass_of_map)) {\n v = createVariantMap(value.object<jobject>());\n } else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_list)) {\n QVariantList list;\n int count = value.callMethod<jint>(\"size\",\"()I\");\n for (int i = 0 ; i < count ; i++) {\n QAndroidJniObject item = value.callObjectMethod(\"get\",\"(I)Ljava\/lang\/Object;\",i);\n list.append(convertToQVariant(item));\n }\n v = list;\n } else {\n qWarning() << \"value is not an instance of any of the handled jclass types\\n\";\n }\n\n env->DeleteLocalRef(jclass_of_string);\n env->DeleteLocalRef(jclass_of_integer);\n env->DeleteLocalRef(jclass_of_long);\n env->DeleteLocalRef(jclass_of_float);\n env->DeleteLocalRef(jclass_of_double);\n env->DeleteLocalRef(jclass_of_boolean);\n env->DeleteLocalRef(jclass_of_list);\n env->DeleteLocalRef(jclass_of_map);\n\n return v;\n}\n\nstatic QVariantMap createVariantMap(jobject data) {\n QVariantMap res;\n\n QAndroidJniEnvironment env;\n \/* Reference : https:\/\/community.oracle.com\/thread\/1549999 *\/\n\n \/\/ Get the HashMap Class\n jclass jclass_of_hashmap = (env)->GetObjectClass(data);\n\n \/\/ Get link to Method \"entrySet\"\n jmethodID entrySetMethod = (env)->GetMethodID(jclass_of_hashmap, \"entrySet\", \"()Ljava\/util\/Set;\");\n\n \/\/ Invoke the \"entrySet\" method on the HashMap object\n jobject jobject_of_entryset = env->CallObjectMethod(data, entrySetMethod);\n\n \/\/ Get the Set Class\n jclass jclass_of_set = (env)->FindClass(\"java\/util\/Set\"); \/\/ Problem during compilation !!!!!\n\n if (jclass_of_set == 0) {\n qWarning() << \"java\/util\/Set lookup failed\\n\";\n return res;\n }\n\n \/\/ Get link to Method \"iterator\"\n jmethodID iteratorMethod = env->GetMethodID(jclass_of_set, \"iterator\", \"()Ljava\/util\/Iterator;\");\n\n \/\/ Invoke the \"iterator\" method on the jobject_of_entryset variable of type Set\n jobject jobject_of_iterator = env->CallObjectMethod(jobject_of_entryset, iteratorMethod);\n\n \/\/ Get the \"Iterator\" class\n jclass jclass_of_iterator = (env)->FindClass(\"java\/util\/Iterator\");\n\n \/\/ Get link to Method \"hasNext\"\n jmethodID hasNextMethod = env->GetMethodID(jclass_of_iterator, \"hasNext\", \"()Z\");\n\n jmethodID nextMethod = env->GetMethodID(jclass_of_iterator, \"next\", \"()Ljava\/lang\/Object;\");\n\n while (env->CallBooleanMethod(jobject_of_iterator, hasNextMethod) ) {\n jobject jEntry = env->CallObjectMethod(jobject_of_iterator,nextMethod);\n QAndroidJniObject entry = QAndroidJniObject(jEntry);\n QAndroidJniObject key = entry.callObjectMethod(\"getKey\",\"()Ljava\/lang\/Object;\");\n QAndroidJniObject value = entry.callObjectMethod(\"getValue\",\"()Ljava\/lang\/Object;\");\n QString k = key.toString();\n\n QVariant v = convertToQVariant(value);\n\n env->DeleteLocalRef(jEntry);\n\n if (v.isNull()) {\n continue;\n }\n\n res[k] = v;\n }\n\n if (env->ExceptionOccurred()) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n }\n\n env->DeleteLocalRef(jclass_of_hashmap);\n env->DeleteLocalRef(jobject_of_entryset);\n env->DeleteLocalRef(jclass_of_set);\n env->DeleteLocalRef(jobject_of_iterator);\n env->DeleteLocalRef(jclass_of_iterator);\n\n return res;\n}\n\nstatic jobject convertToJObject(QVariant v) {\n jobject res = 0;\n QAndroidJniEnvironment env;\n\n if (v.type() == QVariant::String) {\n QString str = v.toString();\n res = env->NewStringUTF(str.toLocal8Bit().data());\n } else if (v.type() == QVariant::Int) {\n jclass integerClass = env->FindClass(\"java\/lang\/Integer\");\n jmethodID integerConstructor = env->GetMethodID(integerClass, \"<init>\", \"(I)V\");\n\n res = env->NewObject(integerClass,integerConstructor,v.toInt());\n\n env->DeleteLocalRef(integerClass);\n } else if (v.type() == QVariant::LongLong) {\n jclass longClass = env->FindClass(\"java\/lang\/Long\");\n jmethodID longConstructor = env->GetMethodID( longClass, \"<init>\", \"(J)V\");\n\n res = env->NewObject(longClass,longConstructor, v.toLongLong() );\n\n env->DeleteLocalRef(longClass);\n\n } else if (v.type() == QVariant::Double) {\n jclass doubleClass = env->FindClass(\"java\/lang\/Double\");\n jmethodID doubleConstructor = env->GetMethodID( doubleClass, \"<init>\", \"(D)V\");\n\n res = env->NewObject(doubleClass,doubleConstructor,v.toDouble());\n\n env->DeleteLocalRef(doubleClass);\n\n } else if (v.canConvert<float>()) {\n jclass floatClass = env->FindClass(\"java\/lang\/Float\");\n jmethodID floatConstructor = env->GetMethodID( floatClass, \"<init>\", \"(F)V\");\n\n res = env->NewObject(floatClass,floatConstructor,v.toFloat());\n\n env->DeleteLocalRef(floatClass);\n\n } else if (v.type() == QVariant::Bool) {\n jclass booleanClass = env->FindClass(\"java\/lang\/Boolean\");\n jmethodID booleanConstructor = env->GetMethodID(booleanClass,\"<init>\",\"(Z)V\");\n\n res = env->NewObject(booleanClass,booleanConstructor,v.toBool());\n\n env->DeleteLocalRef(booleanClass);\n\n } else if (v.type() == QVariant::Map) {\n res = createHashMap(v.toMap());\n } else if (v.type() == QVariant::List){\n QVariantList list = v.value<QVariantList>();\n jclass arrayListClass = env->FindClass(\"java\/util\/ArrayList\");\n jmethodID init = env->GetMethodID(arrayListClass, \"<init>\", \"(I)V\");\n res = env->NewObject( arrayListClass, init, list.size());\n\n jmethodID add = env->GetMethodID( arrayListClass, \"add\",\n \"(Ljava\/lang\/Object;)Z\");\n\n for (int i = 0 ; i < list.size() ; i++) {\n jobject item = convertToJObject(list.at(i));\n env->CallBooleanMethod(res,add, item);\n env->DeleteLocalRef(item);\n }\n\n env->DeleteLocalRef(arrayListClass);\n } else {\n qWarning() << \"ANSystemDispatcher: Non-supported data type - \" << v.type();\n }\n return res;\n}\n\nstatic jobject createHashMap(const QVariantMap &data) {\n QAndroidJniEnvironment env;\n\n jclass mapClass = env->FindClass(\"java\/util\/HashMap\");\n\n if (mapClass == NULL) {\n qWarning() << \"Failed to find class\" << \"java\/util\/HashMap\";\n return NULL;\n }\n\n jsize map_len = data.size();\n\n jmethodID init = env->GetMethodID(mapClass, \"<init>\", \"(I)V\");\n jobject hashMap = env->NewObject( mapClass, init, map_len);\n\n jmethodID put = env->GetMethodID( mapClass, \"put\",\n \"(Ljava\/lang\/Object;Ljava\/lang\/Object;)Ljava\/lang\/Object;\");\n\n QMapIterator<QString, QVariant> iter(data);\n while (iter.hasNext()) {\n iter.next();\n\n QString key = iter.key();\n jstring jkey = env->NewStringUTF(key.toLocal8Bit().data());\n QVariant v = iter.value();\n jobject item = convertToJObject(v);\n\n if (item == 0) {\n continue;\n }\n\n env->CallObjectMethod(hashMap,put,jkey,item);\n env->DeleteLocalRef(item);\n env->DeleteLocalRef(jkey);\n }\n\n if (env->ExceptionOccurred()) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n }\n\n env->DeleteLocalRef(mapClass);\n\n return hashMap;\n}\n\nstatic void jniEmit(JNIEnv* env,jobject object,jstring name,jobject data) {\n Q_UNUSED(object);\n Q_UNUSED(env);\n\n QAndroidJniObject tmp(name);\n QString str = tmp.toString();\n\n QVariantMap map;\n\n if (data != 0) {\n map = createVariantMap(data);\n }\n\n if (m_instance.isNull()) {\n return;\n }\n\n QMetaObject::invokeMethod(m_instance.data(),\"dispatched\",Qt::AutoConnection,\n Q_ARG(QString, str),\n Q_ARG(QVariantMap,map));\n}\n\nstatic void printInstruction() {\n static bool printOnce = false;\n\n if (printOnce) {\n return;\n }\n printOnce = true;\n\n \/\/ BuildMyString.com generated code. Please enjoy your string responsibly.\n\n QString msg = \"Using SystemDispatcher in Android but SystemDispatcher::registerNatives() is never called. Instruction: \\r\\n\"\n \"https:\/\/github.com\/benlau\/androidnative.pri\/blob\/master\/docs\/installation.md\\r\\n\";\n\n qWarning() << msg;\n}\n#endif\n\nAndroidNative::SystemDispatcher::SystemDispatcher(QObject* parent) : QObject(parent)\n{\n}\n\nAndroidNative::SystemDispatcher::~SystemDispatcher()\n{\n}\n\nAndroidNative::SystemDispatcher *SystemDispatcher::instance()\n{\n if (!m_instance) {\n QCoreApplication* app = QCoreApplication::instance();\n m_instance = new SystemDispatcher(app);\n }\n return m_instance;\n}\n\nvoid AndroidNative::SystemDispatcher::dispatch(QString type, QVariantMap message)\n{\n Q_UNUSED(type);\n Q_UNUSED(message);\n\n#ifdef Q_OS_ANDROID\n if (!registerNativesCalled) {\n printInstruction();\n }\n\n QAndroidJniEnvironment env;\n\n jstring jType = env->NewStringUTF(type.toLocal8Bit().data());\n jobject jData = createHashMap(message);\n QAndroidJniObject::callStaticMethod<void>(JCLASS_Name, \"dispatch\",\n DISPATCH_SIGNATURE,\n jType,jData);\n env->DeleteLocalRef(jType);\n env->DeleteLocalRef(jData);\n\n#else\n static bool dispatching = false;\n static QQueue<QPair<QString,QVariantMap> > queue;\n\n\n if (dispatching) {\n queue.enqueue(QPair<QString,QVariantMap> (type,message) );\n return;\n }\n\n dispatching = true;\n emit dispatched(type,message);\n\n while (queue.size() > 0) {\n QPair<QString,QVariantMap> pair = queue.dequeue();\n emit dispatched(pair.first,pair.second);\n }\n dispatching = false;\n#endif\n}\n\nvoid AndroidNative::SystemDispatcher::loadClass(QString javaClassName)\n{\n QVariantMap message;\n message[\"className\"] = javaClassName;\n\n dispatch(\"androidnative.SystemDispatcher.loadClass\",message);\n}\n\nvoid AndroidNative::SystemDispatcher::registerNatives()\n{\n Q_UNUSED(registerNativesCalled);\n\n#ifdef Q_OS_ANDROID\n registerNativesCalled = true;\n\n QAndroidJniEnvironment env;\n jclass clazz = env->FindClass(JCLASS_Name);\n if (!clazz)\n {\n qCritical() << \"androidNative.SystemDispatcher Java class is not found. Please configure your build.gradle according to this instruction: \\r\\n\"\n \"https:\/\/github.com\/benlau\/androidnative.pri\/blob\/master\/docs\/installation.md\\r\\n\";\n if (env->ExceptionOccurred()) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n }\n return;\n }\n\n JNINativeMethod methods[] =\n {\n {\"jniEmit\", EMIT_SIGNATURE, (void *)&jniEmit},\n };\n\n int numMethods = sizeof(methods) \/ sizeof(methods[0]);\n if (env->RegisterNatives(clazz, methods, numMethods) < 0) {\n if (env->ExceptionOccurred()) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n qCritical() << \"Exception occurred!!!\";\n return;\n }\n }\n\n QAndroidJniObject::callStaticMethod<void>(JCLASS_Name, \"init\",\n \"()V\");\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file populate_in_tuebingen_available.cc\n * \\author Dr. Johannes Ruscheinski\n *\n * A tool that adds a new \"SIG\" field to a MARC record if there are UB or IFK call numbers in a record.\n *\/\n\n\/*\n Copyright (C) 2015,2016, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (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. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <cstdlib>\n#include \"DirectoryEntry.h\"\n#include \"Leader.h\"\n#include \"MarcUtil.h\"\n#include \"MarcXmlWriter.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << progname << \" [--verbose] marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nstatic unsigned modified_record_count;\nstatic unsigned add_sig_count;\n\n\nbool ProcessRecord(MarcUtil::Record * const record, XmlWriter * const xml_writer, std::string * const \/*err_msg*\/) {\n std::vector <std::pair<size_t, size_t>> local_block_boundaries;\n record->findAllLocalDataBlocks(&local_block_boundaries);\n\n bool modified_record(false);\n const std::vector<std::string> &fields(record->getFields());\n for (const auto &block_start_and_end : local_block_boundaries) {\n std::vector <size_t> _852_field_indices;\n if (record->findFieldsInLocalBlock(\"852\", \"??\", block_start_and_end, &_852_field_indices) == 0)\n continue;\n for (const size_t _852_index : _852_field_indices) {\n const Subfields subfields1(fields[_852_index]);\n const std::string not_available_subfield(subfields1.getFirstSubfieldValue('z'));\n if (not_available_subfield == \"Kein Bestand am IfK; Nachweis für KrimDok\") {\n record->filterTags({\"SIG\"});\n record->write(xml_writer);\n return true;\n }\n\n const std::string isil_subfield(subfields1.getFirstSubfieldValue('a'));\n if (isil_subfield != \"DE-21\" and isil_subfield != \"DE-21-110\")\n continue;\n\n std::string detailed_availability;\n std::vector <size_t> _866_field_indices;\n if (record->findFieldsInLocalBlock(\"866\", \"30\", block_start_and_end, &_866_field_indices) > 0) {\n for (const size_t _866_index : _866_field_indices) {\n const Subfields subfields2(fields[_866_index]); \n const std::string subfield_a(subfields2.getFirstSubfieldValue('a'));\n if (not subfield_a.empty()) {\n if (not detailed_availability.empty())\n detailed_availability += \"; \";\n detailed_availability += subfield_a;\n const std::string subfield_z(subfields2.getFirstSubfieldValue('z'));\n if (not subfield_z.empty())\n detailed_availability += \" \" + subfield_z;\n }\n }\n }\n\n const std::string institution(isil_subfield == \"DE-21\" ? \"UB: \" : \"IFK: \");\n if (_852_index + 1 < block_start_and_end.second) {\n const Subfields subfields2(fields[_852_index + 1]);\n const std::string call_number_subfield(subfields2.getFirstSubfieldValue('c'));\n if (not call_number_subfield.empty()) {\n const std::string institution_and_call_number(institution + call_number_subfield);\n ++add_sig_count;\n modified_record = true;\n record->insertField(\"SIG\",\n \" \"\"\\x1F\"\"a\" + institution_and_call_number\n + (detailed_availability.empty() ? \"\" : \"(\" + detailed_availability + \")\"));\n }\n }\n break;\n }\n }\n\n if (modified_record)\n ++modified_record_count;\n\n record->write(xml_writer);\n return true;\n}\n\n\nvoid PopulateTheInTuebingenAvailableField(const bool verbose, File * const input, File * const output) {\n MarcXmlWriter xml_writer(output);\n\n std::string err_msg;\n if (not MarcUtil::ProcessRecords(input, ProcessRecord, &xml_writer , &err_msg))\n Error(\"error while processing records: \" + err_msg);\n\n if (verbose) {\n std::cout << \"Modified \" << modified_record_count << \" records.\\n\";\n std::cout << \"Added \" << add_sig_count << \" signature fields.\\n\";\n }\n}\n\n\nint main(int argc, char **argv) {\n progname = argv[0];\n\n if (argc != 3 and argc != 4)\n Usage();\n\n bool verbose;\n if (argc == 3)\n verbose = false;\n else { \/\/ argc == 4\n if (std::strcmp(argv[1], \"--verbose\") != 0)\n Usage();\n verbose = true;\n }\n\n const std::string marc_input_filename(argv[argc == 3 ? 1 : 2]);\n File marc_input(marc_input_filename, \"r\");\n if (not marc_input)\n Error(\"can't open \\\"\" + marc_input_filename + \"\\\" for reading!\");\n\n const std::string marc_output_filename(argv[argc == 3 ? 2 : 3]);\n File marc_output(marc_output_filename, \"w\");\n if (not marc_output)\n Error(\"can't open \\\"\" + marc_output_filename + \"\\\" for writing!\");\n\n PopulateTheInTuebingenAvailableField(verbose, &marc_input, &marc_output);\n}\n<commit_msg>Fixed two \"In Tübingen available\" bugs.<commit_after>\/** \\file populate_in_tuebingen_available.cc\n * \\author Dr. Johannes Ruscheinski\n *\n * A tool that adds a new \"SIG\" field to a MARC record if there are UB or IFK call numbers in a record.\n *\/\n\n\/*\n Copyright (C) 2015,2016, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (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. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <set>\n#include <cstdlib>\n#include \"DirectoryEntry.h\"\n#include \"HtmlUtil.h\"\n#include \"Leader.h\"\n#include \"MarcUtil.h\"\n#include \"MarcXmlWriter.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << progname << \" [--verbose] marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nstatic unsigned modified_record_count;\nstatic unsigned add_sig_count;\n\n\nbool ProcessRecord(MarcUtil::Record * const record, XmlWriter * const xml_writer, std::string * const \/*err_msg*\/) {\n record->setRecordWillBeWrittenAsXml(true);\n\n std::vector <std::pair<size_t, size_t>> local_block_boundaries;\n record->findAllLocalDataBlocks(&local_block_boundaries);\n\n bool modified_record(false);\n const std::vector<std::string> &fields(record->getFields());\n std::set<std::string> alread_seen_urls;\n for (const auto &block_start_and_end : local_block_boundaries) {\n std::vector <size_t> _852_field_indices;\n if (record->findFieldsInLocalBlock(\"852\", \"??\", block_start_and_end, &_852_field_indices) == 0)\n continue;\n for (const size_t _852_index : _852_field_indices) {\n const Subfields subfields1(fields[_852_index]);\n const std::string not_available_subfield(subfields1.getFirstSubfieldValue('z'));\n if (not_available_subfield == \"Kein Bestand am IfK; Nachweis für KrimDok\")\n continue;\n\n const std::string isil_subfield(subfields1.getFirstSubfieldValue('a'));\n if (isil_subfield != \"DE-21\" and isil_subfield != \"DE-21-110\")\n continue;\n\n std::string detailed_availability;\n std::vector <size_t> _866_field_indices;\n if (record->findFieldsInLocalBlock(\"866\", \"30\", block_start_and_end, &_866_field_indices) > 0) {\n for (const size_t _866_index : _866_field_indices) {\n const Subfields subfields2(fields[_866_index]); \n const std::string subfield_a(subfields2.getFirstSubfieldValue('a'));\n if (not subfield_a.empty()) {\n if (not detailed_availability.empty())\n detailed_availability += \"; \";\n detailed_availability += subfield_a;\n const std::string subfield_z(subfields2.getFirstSubfieldValue('z'));\n if (not subfield_z.empty())\n detailed_availability += \" \" + subfield_z;\n }\n }\n }\n\n const std::string institution(isil_subfield == \"DE-21\" ? \"UB: \" : \"IFK: \");\n if (_852_index + 1 < block_start_and_end.second) {\n const Subfields subfields2(fields[_852_index + 1]);\n const std::string call_number_subfield(subfields2.getFirstSubfieldValue('c'));\n if (not call_number_subfield.empty()) {\n const std::string institution_and_call_number(institution + call_number_subfield);\n ++add_sig_count;\n modified_record = true;\n record->insertField(\"SIG\",\n \" \"\"\\x1F\"\"a\" + institution_and_call_number\n + (detailed_availability.empty() ? \"\" : \"(\" + detailed_availability + \")\"));\n } else { \/\/ Look for a URL.\n std::vector <size_t> _856_field_indices;\n if (record->findFieldsInLocalBlock(\"856\", \"4 \", block_start_and_end, &_856_field_indices) > 0) {\n const Subfields subfields3(fields[_856_field_indices.front()]);\n if (subfields3.hasSubfield('u')) {\n const std::string url(subfields3.getFirstSubfieldValue('u'));\n if (alread_seen_urls.find(url) == alread_seen_urls.cend()) {\n alread_seen_urls.insert(url);\n std::string anchor(HtmlUtil::HtmlEscape(subfields3.getFirstSubfieldValue('x')));\n if (anchor.empty())\n anchor = \"Tübingen Online Resource\";\n record->insertField(\"SIG\", \"\\x1F\"\"a<a href=\\\"\" + url + \"\\\">\" + anchor + \"<\/a>\");\n }\n }\n }\n }\n }\n break;\n }\n }\n\n if (modified_record)\n ++modified_record_count;\n\n record->write(xml_writer);\n return true;\n}\n\n\nvoid PopulateTheInTuebingenAvailableField(const bool verbose, File * const input, File * const output) {\n MarcXmlWriter xml_writer(output);\n\n std::string err_msg;\n if (not MarcUtil::ProcessRecords(input, ProcessRecord, &xml_writer , &err_msg))\n Error(\"error while processing records: \" + err_msg);\n\n if (verbose) {\n std::cout << \"Modified \" << modified_record_count << \" records.\\n\";\n std::cout << \"Added \" << add_sig_count << \" signature fields.\\n\";\n }\n}\n\n\nint main(int argc, char **argv) {\n progname = argv[0];\n\n if (argc != 3 and argc != 4)\n Usage();\n\n bool verbose;\n if (argc == 3)\n verbose = false;\n else { \/\/ argc == 4\n if (std::strcmp(argv[1], \"--verbose\") != 0)\n Usage();\n verbose = true;\n }\n\n const std::string marc_input_filename(argv[argc == 3 ? 1 : 2]);\n File marc_input(marc_input_filename, \"r\");\n if (not marc_input)\n Error(\"can't open \\\"\" + marc_input_filename + \"\\\" for reading!\");\n\n const std::string marc_output_filename(argv[argc == 3 ? 2 : 3]);\n File marc_output(marc_output_filename, \"w\");\n if (not marc_output)\n Error(\"can't open \\\"\" + marc_output_filename + \"\\\" for writing!\");\n\n PopulateTheInTuebingenAvailableField(verbose, &marc_input, &marc_output);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"joystick.h\"\n\nusing namespace JoystickLibrary;\n\nconstexpr int NUMBER_BUTTONS = 11;\n\n\nXbox360Service::Xbox360Service(int number_joysticks) : JoystickService(number_joysticks)\n{\n this->valid_devices = {\n { 0x045E, 0x028E },\t\/\/ Microsoft Xbox 360 Controller\n { 0x045E, 0x0291 }, \/\/ Microsoft Xbox 360 Wireless Controller\n\t\t{ 0x0E6F, 0x0213 }\t\/\/ Afterglow AX.1 for Xbox 360\n };\n}\n\nXbox360Service::~Xbox360Service()\n{\n}\n\nbool Xbox360Service::GetLeftX(int joystickID, int& leftX)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n leftX = this->GetState(joystickID).lX;\n return true;\n}\n\nbool Xbox360Service::GetLeftY(int joystickID, int& leftY)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n leftY = -this->GetState(joystickID).lY;\n return true;\n}\n\nbool Xbox360Service::GetRightX(int joystickID, int& rightX)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n rightX = this->GetState(joystickID).lRx;\n return true;\n}\n\nbool Xbox360Service::GetRightY(int joystickID, int& rightY)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n rightY = -this->GetState(joystickID).lRy;\n return true;\n}\n\nbool Xbox360Service::GetLeftTrigger(int joystickID, int& leftTrigger)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n \/\/ triggers share the lZ field. left: [0, 100], right: [0, -100] \n int lz = this->GetState(joystickID).lZ;\n leftTrigger = (lz > 0) ? lz : 0;\n return true;\n}\n\nbool Xbox360Service::GetRightTrigger(int joystickID, int& rightTrigger)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n \/\/ triggers share the lZ field. left: [0, 100], right: [0, -100]\n int lz = this->GetState(joystickID).lZ;\n rightTrigger = (lz < 0) ? -lz : 0;\n return true;\n}\n\nbool Xbox360Service::GetDpad(int joystickID, POV& dpad)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n \/\/ POV values are done in 45 deg segments (0 is up) * 100.\n \/\/ i.e. straight right = 90 deg = 9000.\n \/\/ determine POV value by way of lookup table (divide by 4500)\n unsigned int povListIndex = jsMap[joystickID].state.rgdwPOV[0] \/ 4500;\n dpad = (povListIndex < povList.size()) ? povList[povListIndex] : POV::POV_NONE;\n return true;\n}\n\nbool Xbox360Service::GetButton(int joystickID, Xbox360Button button, bool& buttonVal)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n buttonVal = !!this->GetState(joystickID).rgbButtons[static_cast<int>(button)];\n return true;\n}\n\nbool Xbox360Service::GetButtons(int joystickID, std::map<Xbox360Button, bool>& buttons)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n buttons.clear();\n for (int i = 0; i < NUMBER_BUTTONS; i++)\n buttons[static_cast<Xbox360Button>(i)] = !!this->GetState(joystickID).rgbButtons[i];\n\n return true;\n}\n<commit_msg>fixed whitespace<commit_after>#include \"joystick.h\"\n\nusing namespace JoystickLibrary;\n\nconstexpr int NUMBER_BUTTONS = 11;\n\n\nXbox360Service::Xbox360Service(int number_joysticks) : JoystickService(number_joysticks)\n{\n this->valid_devices = {\n { 0x045E, 0x028E },\t\/\/ Microsoft Xbox 360 Controller\n { 0x045E, 0x0291 }, \/\/ Microsoft Xbox 360 Wireless Controller\n { 0x0E6F, 0x0213 }\t\/\/ Afterglow AX.1 for Xbox 360\n };\n}\n\nXbox360Service::~Xbox360Service()\n{\n}\n\nbool Xbox360Service::GetLeftX(int joystickID, int& leftX)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n leftX = this->GetState(joystickID).lX;\n return true;\n}\n\nbool Xbox360Service::GetLeftY(int joystickID, int& leftY)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n leftY = -this->GetState(joystickID).lY;\n return true;\n}\n\nbool Xbox360Service::GetRightX(int joystickID, int& rightX)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n rightX = this->GetState(joystickID).lRx;\n return true;\n}\n\nbool Xbox360Service::GetRightY(int joystickID, int& rightY)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n rightY = -this->GetState(joystickID).lRy;\n return true;\n}\n\nbool Xbox360Service::GetLeftTrigger(int joystickID, int& leftTrigger)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n \/\/ triggers share the lZ field. left: [0, 100], right: [0, -100] \n int lz = this->GetState(joystickID).lZ;\n leftTrigger = (lz > 0) ? lz : 0;\n return true;\n}\n\nbool Xbox360Service::GetRightTrigger(int joystickID, int& rightTrigger)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n \/\/ triggers share the lZ field. left: [0, 100], right: [0, -100]\n int lz = this->GetState(joystickID).lZ;\n rightTrigger = (lz < 0) ? -lz : 0;\n return true;\n}\n\nbool Xbox360Service::GetDpad(int joystickID, POV& dpad)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n \/\/ POV values are done in 45 deg segments (0 is up) * 100.\n \/\/ i.e. straight right = 90 deg = 9000.\n \/\/ determine POV value by way of lookup table (divide by 4500)\n unsigned int povListIndex = jsMap[joystickID].state.rgdwPOV[0] \/ 4500;\n dpad = (povListIndex < povList.size()) ? povList[povListIndex] : POV::POV_NONE;\n return true;\n}\n\nbool Xbox360Service::GetButton(int joystickID, Xbox360Button button, bool& buttonVal)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n buttonVal = !!this->GetState(joystickID).rgbButtons[static_cast<int>(button)];\n return true;\n}\n\nbool Xbox360Service::GetButtons(int joystickID, std::map<Xbox360Button, bool>& buttons)\n{\n if (!IsValidJoystickID(joystickID))\n return false;\n\n buttons.clear();\n for (int i = 0; i < NUMBER_BUTTONS; i++)\n buttons[static_cast<Xbox360Button>(i)] = !!this->GetState(joystickID).rgbButtons[i];\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev <vvasilev@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"BackendPasses.h\"\n\n#include \"llvm\/Analysis\/InlineCost.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/IPO\/InlinerPass.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include \"llvm\/PassManager.h\"\n\n#include \"clang\/Basic\/LangOptions.h\"\n#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Frontend\/CodeGenOptions.h\"\n\nusing namespace cling;\nusing namespace clang;\nusing namespace llvm;\n\nnamespace {\n\n class InlinerKeepDeadFunc: public Inliner {\n Inliner* m_Inliner; \/\/ the actual inliner\n static char ID; \/\/ Pass identification, replacement for typeid\n public:\n InlinerKeepDeadFunc():\n Inliner(ID), m_Inliner(0) { }\n InlinerKeepDeadFunc(Pass* I):\n Inliner(ID), m_Inliner((Inliner*)I) { }\n\n using llvm::Pass::doInitialization;\n bool doInitialization(CallGraph &CG) override {\n \/\/ Forward out Resolver now that we are registered.\n if (!m_Inliner->getResolver())\n m_Inliner->setResolver(getResolver());\n return m_Inliner->doInitialization(CG); \/\/ no Module modification\n }\n\n InlineCost getInlineCost(CallSite CS) override {\n return m_Inliner->getInlineCost(CS);\n }\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n m_Inliner->getAnalysisUsage(AU);\n }\n bool runOnSCC(CallGraphSCC &SCC) override {\n return m_Inliner->runOnSCC(SCC);\n }\n\n using llvm::Pass::doFinalization;\n \/\/ No-op: we need to keep the inlined functions for later use.\n bool doFinalization(CallGraph& \/*CG*\/) override {\n \/\/ Module is unchanged\n return false;\n }\n };\n} \/\/ end anonymous namespace\n\n\/\/ Pass registration. Luckily all known inliners depend on the same set\n\/\/ of passes.\nchar InlinerKeepDeadFunc::ID = 0;\n\n\nBackendPasses::BackendPasses(const CodeGenOptions &CGOpts,\n const TargetOptions &TOpts,\n const LangOptions &LOpts):\n m_CodeGenOptsVerifyModule(CGOpts.VerifyModule)\n{\n CreatePasses(CGOpts, TOpts, LOpts);\n}\n\n\nBackendPasses::~BackendPasses() {}\n\nvoid BackendPasses::CreatePasses(const CodeGenOptions &CGOpts,\n const TargetOptions &TOpts,\n const LangOptions &LOpts)\n{\n \/\/ From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses().\n\n unsigned OptLevel = CGOpts.OptimizationLevel;\n CodeGenOptions::InliningMethod Inlining = CGOpts.getInlining();\n\n \/\/ Handle disabling of LLVM optimization, where we want to preserve the\n \/\/ internal module before any optimization.\n if (CGOpts.DisableLLVMOpts) {\n OptLevel = 0;\n \/\/ Always keep at least ForceInline - NoInlining is deadly for libc++.\n \/\/ Inlining = CGOpts.NoInlining;\n }\n\n m_PMBuilder.reset(new PassManagerBuilder());\n m_PMBuilder->OptLevel = OptLevel;\n m_PMBuilder->SizeLevel = CGOpts.OptimizeSize;\n m_PMBuilder->BBVectorize = CGOpts.VectorizeBB;\n m_PMBuilder->SLPVectorize = CGOpts.VectorizeSLP;\n m_PMBuilder->LoopVectorize = CGOpts.VectorizeLoop;\n\n m_PMBuilder->DisableTailCalls = CGOpts.DisableTailCalls;\n m_PMBuilder->DisableUnitAtATime = !CGOpts.UnitAtATime;\n m_PMBuilder->DisableUnrollLoops = !CGOpts.UnrollLoops;\n m_PMBuilder->MergeFunctions = CGOpts.MergeFunctions;\n m_PMBuilder->RerollLoops = CGOpts.RerollLoops;\n\n\n switch (Inlining) {\n case CodeGenOptions::NoInlining: {\n assert(0 && \"libc++ requires at least OnlyAlwaysInlining!\");\n break;\n }\n case CodeGenOptions::NormalInlining: {\n m_PMBuilder->Inliner =\n new InlinerKeepDeadFunc(createFunctionInliningPass(OptLevel,\n CGOpts.OptimizeSize));\n break;\n }\n case CodeGenOptions::OnlyAlwaysInlining:\n \/\/ Respect always_inline.\n if (OptLevel == 0)\n \/\/ Do not insert lifetime intrinsics at -O0.\n m_PMBuilder->Inliner\n = new InlinerKeepDeadFunc(createAlwaysInlinerPass(false));\n else\n m_PMBuilder->Inliner\n = new InlinerKeepDeadFunc(createAlwaysInlinerPass());\n break;\n }\n\n \/\/ Set up the per-module pass manager.\n m_MPM.reset(new PassManager());\n m_MPM->add(new DataLayoutPass());\n \/\/m_MPM->add(createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));\n \/\/if (!CGOpts.RewriteMapFiles.empty())\n \/\/ addSymbolRewriterPass(CGOpts, m_MPM);\n if (CGOpts.VerifyModule)\n m_MPM->add(createDebugInfoVerifierPass());\n\n m_PMBuilder->populateModulePassManager(*m_MPM);\n}\n\nvoid BackendPasses::runOnModule(Module& M) {\n\n \/\/ Set up the per-function pass manager.\n FunctionPassManager FPM(&M);\n FPM.add(new DataLayoutPass());\n \/\/FPM.add(createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));\n if (m_CodeGenOptsVerifyModule)\n FPM.add(createVerifierPass());\n m_PMBuilder->populateFunctionPassManager(FPM);\n\n \/\/ Run the per-function passes on the module.\n FPM.doInitialization();\n for (auto&& I: M.functions())\n if (!I.isDeclaration())\n FPM.run(I);\n FPM.doFinalization();\n\n m_MPM->run(M);\n}\n<commit_msg>Reduce cling leakage to 0, according to valgrind.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev <vvasilev@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"BackendPasses.h\"\n\n#include \"llvm\/Analysis\/InlineCost.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/IPO\/InlinerPass.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include \"llvm\/PassManager.h\"\n\n#include \"clang\/Basic\/LangOptions.h\"\n#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Frontend\/CodeGenOptions.h\"\n\nusing namespace cling;\nusing namespace clang;\nusing namespace llvm;\n\nnamespace {\n\n class InlinerKeepDeadFunc: public Inliner {\n Inliner* m_Inliner; \/\/ the actual inliner\n static char ID; \/\/ Pass identification, replacement for typeid\n public:\n InlinerKeepDeadFunc():\n Inliner(ID), m_Inliner(0) { }\n InlinerKeepDeadFunc(Pass* I):\n Inliner(ID), m_Inliner((Inliner*)I) { }\n\n using llvm::Pass::doInitialization;\n bool doInitialization(CallGraph &CG) override {\n \/\/ Forward out Resolver now that we are registered.\n if (!m_Inliner->getResolver())\n m_Inliner->setResolver(getResolver());\n return m_Inliner->doInitialization(CG); \/\/ no Module modification\n }\n\n InlineCost getInlineCost(CallSite CS) override {\n return m_Inliner->getInlineCost(CS);\n }\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n m_Inliner->getAnalysisUsage(AU);\n }\n bool runOnSCC(CallGraphSCC &SCC) override {\n return m_Inliner->runOnSCC(SCC);\n }\n\n using llvm::Pass::doFinalization;\n \/\/ No-op: we need to keep the inlined functions for later use.\n bool doFinalization(CallGraph& \/*CG*\/) override {\n \/\/ Module is unchanged\n return false;\n }\n };\n} \/\/ end anonymous namespace\n\n\/\/ Pass registration. Luckily all known inliners depend on the same set\n\/\/ of passes.\nchar InlinerKeepDeadFunc::ID = 0;\n\n\nBackendPasses::BackendPasses(const CodeGenOptions &CGOpts,\n const TargetOptions &TOpts,\n const LangOptions &LOpts):\n m_CodeGenOptsVerifyModule(CGOpts.VerifyModule)\n{\n CreatePasses(CGOpts, TOpts, LOpts);\n}\n\n\nBackendPasses::~BackendPasses() {\n delete m_PMBuilder->Inliner;\n}\n\nvoid BackendPasses::CreatePasses(const CodeGenOptions &CGOpts,\n const TargetOptions &TOpts,\n const LangOptions &LOpts)\n{\n \/\/ From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses().\n\n unsigned OptLevel = CGOpts.OptimizationLevel;\n CodeGenOptions::InliningMethod Inlining = CGOpts.getInlining();\n\n \/\/ Handle disabling of LLVM optimization, where we want to preserve the\n \/\/ internal module before any optimization.\n if (CGOpts.DisableLLVMOpts) {\n OptLevel = 0;\n \/\/ Always keep at least ForceInline - NoInlining is deadly for libc++.\n \/\/ Inlining = CGOpts.NoInlining;\n }\n\n m_PMBuilder.reset(new PassManagerBuilder());\n m_PMBuilder->OptLevel = OptLevel;\n m_PMBuilder->SizeLevel = CGOpts.OptimizeSize;\n m_PMBuilder->BBVectorize = CGOpts.VectorizeBB;\n m_PMBuilder->SLPVectorize = CGOpts.VectorizeSLP;\n m_PMBuilder->LoopVectorize = CGOpts.VectorizeLoop;\n\n m_PMBuilder->DisableTailCalls = CGOpts.DisableTailCalls;\n m_PMBuilder->DisableUnitAtATime = !CGOpts.UnitAtATime;\n m_PMBuilder->DisableUnrollLoops = !CGOpts.UnrollLoops;\n m_PMBuilder->MergeFunctions = CGOpts.MergeFunctions;\n m_PMBuilder->RerollLoops = CGOpts.RerollLoops;\n\n\n switch (Inlining) {\n case CodeGenOptions::NoInlining: {\n assert(0 && \"libc++ requires at least OnlyAlwaysInlining!\");\n break;\n }\n case CodeGenOptions::NormalInlining: {\n m_PMBuilder->Inliner =\n new InlinerKeepDeadFunc(createFunctionInliningPass(OptLevel,\n CGOpts.OptimizeSize));\n break;\n }\n case CodeGenOptions::OnlyAlwaysInlining:\n \/\/ Respect always_inline.\n if (OptLevel == 0)\n \/\/ Do not insert lifetime intrinsics at -O0.\n m_PMBuilder->Inliner\n = new InlinerKeepDeadFunc(createAlwaysInlinerPass(false));\n else\n m_PMBuilder->Inliner\n = new InlinerKeepDeadFunc(createAlwaysInlinerPass());\n break;\n }\n\n \/\/ Set up the per-module pass manager.\n m_MPM.reset(new PassManager());\n m_MPM->add(new DataLayoutPass());\n \/\/m_MPM->add(createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));\n \/\/if (!CGOpts.RewriteMapFiles.empty())\n \/\/ addSymbolRewriterPass(CGOpts, m_MPM);\n if (CGOpts.VerifyModule)\n m_MPM->add(createDebugInfoVerifierPass());\n\n m_PMBuilder->populateModulePassManager(*m_MPM);\n}\n\nvoid BackendPasses::runOnModule(Module& M) {\n\n \/\/ Set up the per-function pass manager.\n FunctionPassManager FPM(&M);\n FPM.add(new DataLayoutPass());\n \/\/FPM.add(createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));\n if (m_CodeGenOptsVerifyModule)\n FPM.add(createVerifierPass());\n m_PMBuilder->populateFunctionPassManager(FPM);\n\n \/\/ Run the per-function passes on the module.\n FPM.doInitialization();\n for (auto&& I: M.functions())\n if (!I.isDeclaration())\n FPM.run(I);\n FPM.doFinalization();\n\n m_MPM->run(M);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2009 NVIDIA Corporation\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\/*! \\file device_malloc.inl\n * \\brief Inline file for device_malloc.h.\n *\/\n\n#include <thrust\/device_malloc.h>\n#include <thrust\/detail\/device\/cuda\/malloc.h>\n\nnamespace thrust\n{\n\nthrust::device_ptr<void> device_malloc(const std::size_t n)\n{\n return detail::device::cuda::malloc(n);\n} \/\/ end device_malloc()\n\ntemplate<typename T>\n thrust::device_ptr<T> device_malloc(const std::size_t n)\n{\n return thrust::device_malloc(n * sizeof(T));\n} \/\/ end device_malloc()\n\n} \/\/ end thrust\n\n<commit_msg>Work around a circular inclusion problem that was keeping trivial_tests\/device_malloc.cu from compiling.<commit_after>\/*\n * Copyright 2008-2009 NVIDIA Corporation\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\/*! \\file device_malloc.inl\n * \\brief Inline file for device_malloc.h.\n *\/\n\n\/\/ workaround a recursive #inclusion problem here\n\/\/ by providing a forward declaration of cuda::malloc\nnamespace thrust { namespace detail { namespace device { namespace cuda\n{\ninline device_ptr<void> malloc(const std::size_t n);\n}}}}\n\n#include <thrust\/device_malloc.h>\n#include <thrust\/detail\/device\/cuda\/malloc.h>\n\nnamespace thrust\n{\n\nthrust::device_ptr<void> device_malloc(const std::size_t n)\n{\n return thrust::detail::device::cuda::malloc(n);\n} \/\/ end device_malloc()\n\ntemplate<typename T>\n thrust::device_ptr<T> device_malloc(const std::size_t n)\n{\n return thrust::device_malloc(n * sizeof(T));\n} \/\/ end device_malloc()\n\n} \/\/ end thrust\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* gdscript_highlighter.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"gdscript_highlighter.h\"\n#include \"..\/gdscript_tokenizer.h\"\n#include \"editor\/editor_settings.h\"\n#include \"scene\/gui\/text_edit.h\"\n\ninline bool _is_symbol(CharType c) {\n\n\treturn is_symbol(c);\n}\n\nstatic bool _is_text_char(CharType c) {\n\n\treturn (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';\n}\n\nstatic bool _is_char(CharType c) {\n\n\treturn (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';\n}\n\nstatic bool _is_number(CharType c) {\n\treturn (c >= '0' && c <= '9');\n}\n\nstatic bool _is_hex_symbol(CharType c) {\n\treturn ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));\n}\n\nMap<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) {\n\tMap<int, TextEdit::HighlighterInfo> color_map;\n\n\tType next_type = NONE;\n\tType current_type = NONE;\n\tType previous_type = NONE;\n\n\tString previous_text = \"\";\n\tint previous_column = 0;\n\n\tbool prev_is_char = false;\n\tbool prev_is_number = false;\n\tbool in_keyword = false;\n\tbool in_word = false;\n\tbool in_function_name = false;\n\tbool in_variable_declaration = false;\n\tbool in_member_variable = false;\n\tbool in_node_path = false;\n\tbool is_hex_notation = false;\n\tbool expect_type = false;\n\tColor keyword_color;\n\tColor color;\n\n\tint in_region = text_editor->_is_line_in_region(p_line);\n\tint deregion = 0;\n\n\tconst Map<int, TextEdit::Text::ColorRegionInfo> cri_map = text_editor->_get_line_color_region_info(p_line);\n\tconst String &str = text_editor->get_line(p_line);\n\tColor prev_color;\n\tfor (int j = 0; j < str.length(); j++) {\n\t\tTextEdit::HighlighterInfo highlighter_info;\n\n\t\tif (deregion > 0) {\n\t\t\tderegion--;\n\t\t\tif (deregion == 0) {\n\t\t\t\tin_region = -1;\n\t\t\t}\n\t\t}\n\n\t\tif (deregion != 0) {\n\t\t\tif (color != prev_color) {\n\t\t\t\tprev_color = color;\n\t\t\t\thighlighter_info.color = color;\n\t\t\t\tcolor_map[j] = highlighter_info;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tcolor = font_color;\n\n\t\tbool is_char = _is_text_char(str[j]);\n\t\tbool is_symbol = _is_symbol(str[j]);\n\t\tbool is_number = _is_number(str[j]);\n\n\t\t\/\/ allow ABCDEF in hex notation\n\t\tif (is_hex_notation && (_is_hex_symbol(str[j]) || is_number)) {\n\t\t\tis_number = true;\n\t\t} else {\n\t\t\tis_hex_notation = false;\n\t\t}\n\n\t\t\/\/ check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation\n\t\tif ((str[j] == '.' || str[j] == 'x' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {\n\t\t\tis_number = true;\n\t\t\tis_symbol = false;\n\t\t\tis_char = false;\n\n\t\t\tif (str[j] == 'x' && str[j - 1] == '0') {\n\t\t\t\tis_hex_notation = true;\n\t\t\t}\n\t\t}\n\n\t\tif (!in_word && _is_char(str[j]) && !is_number) {\n\t\t\tin_word = true;\n\t\t}\n\n\t\tif ((in_keyword || in_word) && !is_hex_notation) {\n\t\t\tis_number = false;\n\t\t}\n\n\t\tif (is_symbol && str[j] != '.' && in_word) {\n\t\t\tin_word = false;\n\t\t}\n\n\t\tif (is_symbol && cri_map.has(j)) {\n\t\t\tconst TextEdit::Text::ColorRegionInfo &cri = cri_map[j];\n\n\t\t\tif (in_region == -1) {\n\t\t\t\tif (!cri.end) {\n\t\t\t\t\tin_region = cri.region;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tTextEdit::ColorRegion cr = text_editor->_get_color_region(cri.region);\n\t\t\t\tif (in_region == cri.region && !cr.line_only) { \/\/ignore otherwise\n\t\t\t\t\tif (cri.end || cr.eq) {\n\t\t\t\t\t\tderegion = cr.eq ? cr.begin_key.length() : cr.end_key.length();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!is_char) {\n\t\t\tin_keyword = false;\n\t\t}\n\n\t\tif (in_region == -1 && !in_keyword && is_char && !prev_is_char) {\n\n\t\t\tint to = j;\n\t\t\twhile (to < str.length() && _is_text_char(str[to]))\n\t\t\t\tto++;\n\n\t\t\tString word = str.substr(j, to - j);\n\t\t\tColor col = Color();\n\t\t\tif (text_editor->has_keyword_color(word)) {\n\t\t\t\tcol = text_editor->get_keyword_color(word);\n\t\t\t} else if (text_editor->has_member_color(word)) {\n\t\t\t\tcol = text_editor->get_member_color(word);\n\t\t\t\tfor (int k = j - 1; k >= 0; k--) {\n\t\t\t\t\tif (str[k] == '.') {\n\t\t\t\t\t\tcol = Color(); \/\/member indexing not allowed\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (str[k] > 32) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (col != Color()) {\n\t\t\t\tin_keyword = true;\n\t\t\t\tkeyword_color = col;\n\t\t\t}\n\t\t}\n\n\t\tif (!in_function_name && in_word && !in_keyword) {\n\n\t\t\tint k = j;\n\t\t\twhile (k < str.length() && !_is_symbol(str[k]) && str[k] != '\\t' && str[k] != ' ') {\n\t\t\t\tk++;\n\t\t\t}\n\n\t\t\t\/\/ check for space between name and bracket\n\t\t\twhile (k < str.length() && (str[k] == '\\t' || str[k] == ' ')) {\n\t\t\t\tk++;\n\t\t\t}\n\n\t\t\tif (str[k] == '(') {\n\t\t\t\tin_function_name = true;\n\t\t\t} else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_VAR)) {\n\t\t\t\tin_variable_declaration = true;\n\t\t\t}\n\t\t}\n\n\t\tif (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) {\n\t\t\tint k = j;\n\t\t\twhile (k > 0 && !_is_symbol(str[k]) && str[k] != '\\t' && str[k] != ' ') {\n\t\t\t\tk--;\n\t\t\t}\n\n\t\t\tif (str[k] == '.') {\n\t\t\t\tin_member_variable = true;\n\t\t\t}\n\t\t}\n\n\t\tif (is_symbol) {\n\t\t\tin_function_name = false;\n\t\t\tin_member_variable = false;\n\n\t\t\tif (expect_type && str[j] != ' ' && str[j] != '\\t' && str[j] != ':') {\n\t\t\t\texpect_type = false;\n\t\t\t}\n\t\t\tif (j > 0 && str[j] == '>' && str[j - 1] == '-') {\n\t\t\t\texpect_type = true;\n\t\t\t}\n\n\t\t\tif (in_variable_declaration || previous_text == \"(\" || previous_text == \",\") {\n\t\t\t\tint k = j;\n\t\t\t\t\/\/ Skip space\n\t\t\t\twhile (k < str.length() && (str[k] == '\\t' || str[k] == ' ')) {\n\t\t\t\t\tk++;\n\t\t\t\t}\n\n\t\t\t\tif (str[k] == ':') {\n\t\t\t\t\t\/\/ has type hint\n\t\t\t\t\texpect_type = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tin_variable_declaration = false;\n\t\t}\n\n\t\tif (!in_node_path && in_region == -1 && str[j] == '$') {\n\t\t\tin_node_path = true;\n\t\t} else if (in_region != -1 || (is_symbol && str[j] != '\/')) {\n\t\t\tin_node_path = false;\n\t\t}\n\n\t\tif (in_region >= 0) {\n\t\t\tnext_type = REGION;\n\t\t\tcolor = text_editor->_get_color_region(in_region).color;\n\t\t} else if (in_node_path) {\n\t\t\tnext_type = NODE_PATH;\n\t\t\tcolor = node_path_color;\n\t\t} else if (in_keyword) {\n\t\t\tnext_type = KEYWORD;\n\t\t\tcolor = keyword_color;\n\t\t} else if (in_member_variable) {\n\t\t\tnext_type = MEMBER;\n\t\t\tcolor = member_color;\n\t\t} else if (in_function_name) {\n\t\t\tnext_type = FUNCTION;\n\n\t\t\tif (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_FUNCTION)) {\n\t\t\t\tcolor = function_definition_color;\n\t\t\t} else {\n\t\t\t\tcolor = function_color;\n\t\t\t}\n\t\t} else if (is_symbol) {\n\t\t\tnext_type = SYMBOL;\n\t\t\tcolor = symbol_color;\n\t\t} else if (is_number) {\n\t\t\tnext_type = NUMBER;\n\t\t\tcolor = number_color;\n\t\t} else if (expect_type) {\n\t\t\tnext_type = TYPE;\n\t\t\tcolor = type_color;\n\t\t} else {\n\t\t\tnext_type = IDENTIFIER;\n\t\t}\n\n\t\tif (next_type != current_type) {\n\t\t\tif (current_type == NONE) {\n\t\t\t\tcurrent_type = next_type;\n\t\t\t} else {\n\t\t\t\tprevious_type = current_type;\n\t\t\t\tcurrent_type = next_type;\n\n\t\t\t\t\/\/ no need to store regions...\n\t\t\t\tif (previous_type == REGION) {\n\t\t\t\t\tprevious_text = \"\";\n\t\t\t\t\tprevious_column = j;\n\t\t\t\t} else {\n\t\t\t\t\tString text = str.substr(previous_column, j - previous_column).strip_edges();\n\t\t\t\t\tprevious_column = j;\n\n\t\t\t\t\t\/\/ ignore if just whitespace\n\t\t\t\t\tif (text != \"\") {\n\t\t\t\t\t\tprevious_text = text;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprev_is_char = is_char;\n\t\tprev_is_number = is_number;\n\n\t\tif (color != prev_color) {\n\t\t\tprev_color = color;\n\t\t\thighlighter_info.color = color;\n\t\t\tcolor_map[j] = highlighter_info;\n\t\t}\n\t}\n\treturn color_map;\n}\n\nString GDScriptSyntaxHighlighter::get_name() {\n\treturn \"GDScript\";\n}\n\nList<String> GDScriptSyntaxHighlighter::get_supported_languages() {\n\tList<String> languages;\n\tlanguages.push_back(\"GDScript\");\n\treturn languages;\n}\n\nvoid GDScriptSyntaxHighlighter::_update_cache() {\n\tfont_color = text_editor->get_color(\"font_color\");\n\tsymbol_color = text_editor->get_color(\"symbol_color\");\n\tfunction_color = text_editor->get_color(\"function_color\");\n\tnumber_color = text_editor->get_color(\"number_color\");\n\tmember_color = text_editor->get_color(\"member_variable_color\");\n\n\tEditorSettings *settings = EditorSettings::get_singleton();\n\tString text_editor_color_theme = settings->get(\"text_editor\/theme\/color_theme\");\n\n\tbool default_theme = text_editor_color_theme == \"Default\";\n\tbool dark_theme = settings->is_dark_theme();\n\n\tfunction_definition_color = Color::html(default_theme ? \"#01e1ff\" : dark_theme ? \"#01e1ff\" : \"#00a5ba\");\n\tnode_path_color = Color::html(default_theme ? \"#64c15a\" : dark_theme ? \"64c15a\" : \"#518b4b\");\n\n\tEDITOR_DEF(\"text_editor\/highlighting\/gdscript\/function_definition_color\", function_definition_color);\n\tEDITOR_DEF(\"text_editor\/highlighting\/gdscript\/node_path_color\", node_path_color);\n\tif (text_editor_color_theme == \"Adaptive\" || default_theme) {\n\t\tsettings->set_initial_value(\"text_editor\/highlighting\/gdscript\/function_definition_color\", function_definition_color, true);\n\t\tsettings->set_initial_value(\"text_editor\/highlighting\/gdscript\/node_path_color\", node_path_color, true);\n\t}\n\n\tfunction_definition_color = EDITOR_GET(\"text_editor\/highlighting\/gdscript\/function_definition_color\");\n\tnode_path_color = EDITOR_GET(\"text_editor\/highlighting\/gdscript\/node_path_color\");\n\ttype_color = EDITOR_GET(\"text_editor\/highlighting\/base_type_color\");\n}\n\nSyntaxHighlighter *GDScriptSyntaxHighlighter::create() {\n\treturn memnew(GDScriptSyntaxHighlighter);\n}\n<commit_msg>Fix types highlighting outside of function args and var declarations, issues 22029,21638<commit_after>\/*************************************************************************\/\n\/* gdscript_highlighter.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"gdscript_highlighter.h\"\n#include \"..\/gdscript_tokenizer.h\"\n#include \"editor\/editor_settings.h\"\n#include \"scene\/gui\/text_edit.h\"\n\ninline bool _is_symbol(CharType c) {\n\n\treturn is_symbol(c);\n}\n\nstatic bool _is_text_char(CharType c) {\n\n\treturn (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';\n}\n\nstatic bool _is_char(CharType c) {\n\n\treturn (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';\n}\n\nstatic bool _is_number(CharType c) {\n\treturn (c >= '0' && c <= '9');\n}\n\nstatic bool _is_hex_symbol(CharType c) {\n\treturn ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));\n}\n\nMap<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) {\n\tMap<int, TextEdit::HighlighterInfo> color_map;\n\n\tType next_type = NONE;\n\tType current_type = NONE;\n\tType previous_type = NONE;\n\n\tString previous_text = \"\";\n\tint previous_column = 0;\n\n\tbool prev_is_char = false;\n\tbool prev_is_number = false;\n\tbool in_keyword = false;\n\tbool in_word = false;\n\tbool in_function_name = false;\n\tbool in_variable_declaration = false;\n\tbool in_function_args = false;\n\tbool in_member_variable = false;\n\tbool in_node_path = false;\n\tbool is_hex_notation = false;\n\tbool expect_type = false;\n\tColor keyword_color;\n\tColor color;\n\n\tint in_region = text_editor->_is_line_in_region(p_line);\n\tint deregion = 0;\n\n\tconst Map<int, TextEdit::Text::ColorRegionInfo> cri_map = text_editor->_get_line_color_region_info(p_line);\n\tconst String &str = text_editor->get_line(p_line);\n\tColor prev_color;\n\tfor (int j = 0; j < str.length(); j++) {\n\t\tTextEdit::HighlighterInfo highlighter_info;\n\n\t\tif (deregion > 0) {\n\t\t\tderegion--;\n\t\t\tif (deregion == 0) {\n\t\t\t\tin_region = -1;\n\t\t\t}\n\t\t}\n\n\t\tif (deregion != 0) {\n\t\t\tif (color != prev_color) {\n\t\t\t\tprev_color = color;\n\t\t\t\thighlighter_info.color = color;\n\t\t\t\tcolor_map[j] = highlighter_info;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tcolor = font_color;\n\n\t\tbool is_char = _is_text_char(str[j]);\n\t\tbool is_symbol = _is_symbol(str[j]);\n\t\tbool is_number = _is_number(str[j]);\n\n\t\t\/\/ allow ABCDEF in hex notation\n\t\tif (is_hex_notation && (_is_hex_symbol(str[j]) || is_number)) {\n\t\t\tis_number = true;\n\t\t} else {\n\t\t\tis_hex_notation = false;\n\t\t}\n\n\t\t\/\/ check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation\n\t\tif ((str[j] == '.' || str[j] == 'x' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {\n\t\t\tis_number = true;\n\t\t\tis_symbol = false;\n\t\t\tis_char = false;\n\n\t\t\tif (str[j] == 'x' && str[j - 1] == '0') {\n\t\t\t\tis_hex_notation = true;\n\t\t\t}\n\t\t}\n\n\t\tif (!in_word && _is_char(str[j]) && !is_number) {\n\t\t\tin_word = true;\n\t\t}\n\n\t\tif ((in_keyword || in_word) && !is_hex_notation) {\n\t\t\tis_number = false;\n\t\t}\n\n\t\tif (is_symbol && str[j] != '.' && in_word) {\n\t\t\tin_word = false;\n\t\t}\n\n\t\tif (is_symbol && cri_map.has(j)) {\n\t\t\tconst TextEdit::Text::ColorRegionInfo &cri = cri_map[j];\n\n\t\t\tif (in_region == -1) {\n\t\t\t\tif (!cri.end) {\n\t\t\t\t\tin_region = cri.region;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tTextEdit::ColorRegion cr = text_editor->_get_color_region(cri.region);\n\t\t\t\tif (in_region == cri.region && !cr.line_only) { \/\/ignore otherwise\n\t\t\t\t\tif (cri.end || cr.eq) {\n\t\t\t\t\t\tderegion = cr.eq ? cr.begin_key.length() : cr.end_key.length();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!is_char) {\n\t\t\tin_keyword = false;\n\t\t}\n\n\t\tif (in_region == -1 && !in_keyword && is_char && !prev_is_char) {\n\n\t\t\tint to = j;\n\t\t\twhile (to < str.length() && _is_text_char(str[to]))\n\t\t\t\tto++;\n\n\t\t\tString word = str.substr(j, to - j);\n\t\t\tColor col = Color();\n\t\t\tif (text_editor->has_keyword_color(word)) {\n\t\t\t\tcol = text_editor->get_keyword_color(word);\n\t\t\t} else if (text_editor->has_member_color(word)) {\n\t\t\t\tcol = text_editor->get_member_color(word);\n\t\t\t\tfor (int k = j - 1; k >= 0; k--) {\n\t\t\t\t\tif (str[k] == '.') {\n\t\t\t\t\t\tcol = Color(); \/\/member indexing not allowed\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (str[k] > 32) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (col != Color()) {\n\t\t\t\tin_keyword = true;\n\t\t\t\tkeyword_color = col;\n\t\t\t}\n\t\t}\n\n\t\tif (!in_function_name && in_word && !in_keyword) {\n\n\t\t\tint k = j;\n\t\t\twhile (k < str.length() && !_is_symbol(str[k]) && str[k] != '\\t' && str[k] != ' ') {\n\t\t\t\tk++;\n\t\t\t}\n\n\t\t\t\/\/ check for space between name and bracket\n\t\t\twhile (k < str.length() && (str[k] == '\\t' || str[k] == ' ')) {\n\t\t\t\tk++;\n\t\t\t}\n\n\t\t\tif (str[k] == '(') {\n\t\t\t\tin_function_name = true;\n\t\t\t} else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_VAR)) {\n\t\t\t\tin_variable_declaration = true;\n\t\t\t}\n\t\t}\n\n\t\tif (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) {\n\t\t\tint k = j;\n\t\t\twhile (k > 0 && !_is_symbol(str[k]) && str[k] != '\\t' && str[k] != ' ') {\n\t\t\t\tk--;\n\t\t\t}\n\n\t\t\tif (str[k] == '.') {\n\t\t\t\tin_member_variable = true;\n\t\t\t}\n\t\t}\n\n\t\tif (is_symbol) {\n\n\t\t\tif (in_function_name) {\n\t\t\t\tin_function_args = true;\n\t\t\t}\n\n\t\t\tif (in_function_args && str[j] == ')') {\n\t\t\t\tin_function_args = false;\n\t\t\t}\n\n\t\t\tif (expect_type && prev_is_char) {\n\t\t\t\texpect_type = false;\n\t\t\t}\n\n\t\t\tif (j > 0 && str[j] == '>' && str[j - 1] == '-') {\n\t\t\t\texpect_type = true;\n\t\t\t}\n\n\t\t\tif (in_variable_declaration || in_function_args) {\n\t\t\t\tint k = j;\n\t\t\t\t\/\/ Skip space\n\t\t\t\twhile (k < str.length() && (str[k] == '\\t' || str[k] == ' ')) {\n\t\t\t\t\tk++;\n\t\t\t\t}\n\n\t\t\t\tif (str[k] == ':') {\n\t\t\t\t\t\/\/ has type hint\n\t\t\t\t\texpect_type = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tin_variable_declaration = false;\n\t\t\tin_function_name = false;\n\t\t\tin_member_variable = false;\n\t\t}\n\n\t\tif (!in_node_path && in_region == -1 && str[j] == '$') {\n\t\t\tin_node_path = true;\n\t\t} else if (in_region != -1 || (is_symbol && str[j] != '\/')) {\n\t\t\tin_node_path = false;\n\t\t}\n\n\t\tif (in_region >= 0) {\n\t\t\tnext_type = REGION;\n\t\t\tcolor = text_editor->_get_color_region(in_region).color;\n\t\t} else if (in_node_path) {\n\t\t\tnext_type = NODE_PATH;\n\t\t\tcolor = node_path_color;\n\t\t} else if (in_keyword) {\n\t\t\tnext_type = KEYWORD;\n\t\t\tcolor = keyword_color;\n\t\t} else if (in_member_variable) {\n\t\t\tnext_type = MEMBER;\n\t\t\tcolor = member_color;\n\t\t} else if (in_function_name) {\n\t\t\tnext_type = FUNCTION;\n\n\t\t\tif (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_FUNCTION)) {\n\t\t\t\tcolor = function_definition_color;\n\t\t\t} else {\n\t\t\t\tcolor = function_color;\n\t\t\t}\n\t\t} else if (is_symbol) {\n\t\t\tnext_type = SYMBOL;\n\t\t\tcolor = symbol_color;\n\t\t} else if (is_number) {\n\t\t\tnext_type = NUMBER;\n\t\t\tcolor = number_color;\n\t\t} else if (expect_type) {\n\t\t\tnext_type = TYPE;\n\t\t\tcolor = type_color;\n\t\t} else {\n\t\t\tnext_type = IDENTIFIER;\n\t\t}\n\n\t\tif (next_type != current_type) {\n\t\t\tif (current_type == NONE) {\n\t\t\t\tcurrent_type = next_type;\n\t\t\t} else {\n\t\t\t\tprevious_type = current_type;\n\t\t\t\tcurrent_type = next_type;\n\n\t\t\t\t\/\/ no need to store regions...\n\t\t\t\tif (previous_type == REGION) {\n\t\t\t\t\tprevious_text = \"\";\n\t\t\t\t\tprevious_column = j;\n\t\t\t\t} else {\n\t\t\t\t\tString text = str.substr(previous_column, j - previous_column).strip_edges();\n\t\t\t\t\tprevious_column = j;\n\n\t\t\t\t\t\/\/ ignore if just whitespace\n\t\t\t\t\tif (text != \"\") {\n\t\t\t\t\t\tprevious_text = text;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprev_is_char = is_char;\n\t\tprev_is_number = is_number;\n\n\t\tif (color != prev_color) {\n\t\t\tprev_color = color;\n\t\t\thighlighter_info.color = color;\n\t\t\tcolor_map[j] = highlighter_info;\n\t\t}\n\t}\n\treturn color_map;\n}\n\nString GDScriptSyntaxHighlighter::get_name() {\n\treturn \"GDScript\";\n}\n\nList<String> GDScriptSyntaxHighlighter::get_supported_languages() {\n\tList<String> languages;\n\tlanguages.push_back(\"GDScript\");\n\treturn languages;\n}\n\nvoid GDScriptSyntaxHighlighter::_update_cache() {\n\tfont_color = text_editor->get_color(\"font_color\");\n\tsymbol_color = text_editor->get_color(\"symbol_color\");\n\tfunction_color = text_editor->get_color(\"function_color\");\n\tnumber_color = text_editor->get_color(\"number_color\");\n\tmember_color = text_editor->get_color(\"member_variable_color\");\n\n\tEditorSettings *settings = EditorSettings::get_singleton();\n\tString text_editor_color_theme = settings->get(\"text_editor\/theme\/color_theme\");\n\n\tbool default_theme = text_editor_color_theme == \"Default\";\n\tbool dark_theme = settings->is_dark_theme();\n\n\tfunction_definition_color = Color::html(default_theme ? \"#01e1ff\" : dark_theme ? \"#01e1ff\" : \"#00a5ba\");\n\tnode_path_color = Color::html(default_theme ? \"#64c15a\" : dark_theme ? \"64c15a\" : \"#518b4b\");\n\n\tEDITOR_DEF(\"text_editor\/highlighting\/gdscript\/function_definition_color\", function_definition_color);\n\tEDITOR_DEF(\"text_editor\/highlighting\/gdscript\/node_path_color\", node_path_color);\n\tif (text_editor_color_theme == \"Adaptive\" || default_theme) {\n\t\tsettings->set_initial_value(\"text_editor\/highlighting\/gdscript\/function_definition_color\", function_definition_color, true);\n\t\tsettings->set_initial_value(\"text_editor\/highlighting\/gdscript\/node_path_color\", node_path_color, true);\n\t}\n\n\tfunction_definition_color = EDITOR_GET(\"text_editor\/highlighting\/gdscript\/function_definition_color\");\n\tnode_path_color = EDITOR_GET(\"text_editor\/highlighting\/gdscript\/node_path_color\");\n\ttype_color = EDITOR_GET(\"text_editor\/highlighting\/base_type_color\");\n}\n\nSyntaxHighlighter *GDScriptSyntaxHighlighter::create() {\n\treturn memnew(GDScriptSyntaxHighlighter);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ug_sampling_bias.h\"\n#include <iostream>\n#include <boost\/foreach.hpp>\n \n#ifdef HAVE_CURLPP\n#include <curlpp\/Options.hpp>\n#include <curlpp\/cURLpp.hpp>\n#include <curlpp\/Easy.hpp>\n#endif\n\nnamespace Moses\n{\n namespace bitext\n {\n using ugdiss::id_type;\n\n std::string \n query_bias_server(std::string const& url, std::string const& text)\n {\n \/\/ communicate with the bias server; resuts will be in ...\n std::ostringstream os; \n curlpp::Easy myRequest;\n std::string query = url+curlpp::escape(text);\n myRequest.setOpt(new curlpp::options::Url(query));\n curlpp::options::WriteStream ws(&os);\n myRequest.setOpt(ws); \/\/ Give it to your request\n myRequest.perform(); \/\/ This will output to os\n return os.str();\n }\n \n DocumentBias\n ::DocumentBias\n ( std::vector<id_type> const& sid2doc, \n std::map<std::string,id_type> const& docname2docid,\n std::string const& server_url, std::string const& text,\n std::ostream* log)\n : m_sid2docid(sid2doc)\n , m_bias(docname2docid.size(), 0)\n {\n std::string json = query_bias_server(server_url, text);\n init_from_json(json, docname2docid, log);\n }\n\n void \n DocumentBias\n ::init_from_json\n ( std::string const& json, std::map<std::string,id_type> const& docname2docid,\n std::ostream* log)\n { \/\/ poor man's special purpose json parser for responses from the \n \/\/ MMT bias server\n\t\n std::string d; float total = 0; std::map<std::string,float> bias; \n size_t i = 0; while (i < json.size() && json[i] != '\"') ++i;\n while (++i < json.size())\n\t{\n\t size_t k = i; while (i < json.size() && json[i] != '\"') ++i;\n\t if (i >= json.size()) break;\n\t float& f = bias[json.substr(k,i-k)];\n\t while (++i < json.size() && json[i] != ':');\n\t k = ++i; \n\t while (++i < json.size() && json[i] != ',' && json[i] != '}');\n\t total += (f = atof(json.substr(k, i-k).c_str()));\n\t k = ++i; while (i < json.size() && json[i] != '\"') ++i;\n\t}\n \n typedef std::pair<std::string const,float> item;\n if (total) { BOOST_FOREACH(item& x, bias) { x.second \/= total; } } \n if (log)\n\t{\n\t BOOST_FOREACH(item& x, bias) \n\t {\n\t std::map<std::string,id_type>::const_iterator m;\n\t m = docname2docid.find(x.first);\n\t int docid = m != docname2docid.end() ? m->second : -1;\n\t *log << \"CONTEXT SERVER RESPONSE \" \n\t\t << \"[\" << docid << \"] \"\n\t\t << x.first << \" \" << x.second << std::endl; \n\t }\n\t}\n init(bias, docname2docid);\n \n \/\/ using xmlrpc_parse_json didn't always work (parser errors)\n \/\/ xmlrpc_value* b = xmlrpc_parse_json(env ,buf.str().c_str());\n \/\/ std::cerr << \"|\" << buf.str() << \"|\" << std::endl; \n \/\/ \/\/ if (b == NULL) std::cerr << \"OOpS\" << std::endl; \n \/\/ xmlrpc_c::value_struct v(b); \/\/ = *b;\n \/\/ std::map<std::string, xmlrpc_c::value> const \n \/\/ \tbmap = static_cast<map<std::string, xmlrpc_c::value> >(v);\n \/\/ std::map<std::string, float> bias;\n \/\/ typedef std::map<std::string, xmlrpc_c::value>::value_type item;\n \/\/ float total = 0;\n \/\/ BOOST_FOREACH(item const& x, bmap)\n \/\/ \t{\n \/\/ \t total += bias[x.first] = xmlrpc_c::value_double(x.second);\n \/\/ \t}\n \/\/ typedef std::map<std::string, float>::value_type fitem;\n \/\/ BOOST_FOREACH(fitem const& x, bias)\n \/\/ \tstd::cerr << x.first << \" \" << x.second\/total << std::endl; \n \/\/ \/\/ delete b;\n }\n \n \n void \n DocumentBias\n ::init(std::map<std::string,float> const& biasmap,\n\t std::map<std::string,id_type> const& docname2docid)\n {\n typedef std::map<std::string, id_type>::value_type doc_record;\n float total = 0;\n BOOST_FOREACH(doc_record const& d, docname2docid)\n\t{\n\t std::map<std::string, float>::const_iterator m = biasmap.find(d.first);\n\t if (m != biasmap.end()) total += (m_bias[d.second] = m->second);\n\t }\n if (total) { BOOST_FOREACH(float& f, m_bias) f \/= total; }\n BOOST_FOREACH(doc_record const& d, docname2docid)\n\tstd::cerr << \"BIAS \" << d.first << \" \" << m_bias[d.second] << std::endl;\n }\n \n id_type \n DocumentBias\n ::GetClass(id_type const idx) const\n {\t\n return m_sid2docid.at(idx); \n }\n \n float \n DocumentBias\n ::operator[](id_type const idx) const \n { \n UTIL_THROW_IF2(idx >= m_sid2docid.size(), \n\t\t \"Out of bounds: \" << idx << \"\/\" << m_sid2docid.size());\n return m_bias[m_sid2docid[idx]];\n }\n\n size_t \n DocumentBias\n ::size() const \n { return m_sid2docid.size(); }\n\n\n\n SentenceBias\n ::SentenceBias(std::vector<float> const& bias) \n : m_bias(bias) { }\n\n SentenceBias\n ::SentenceBias(size_t const s) : m_bias(s) { }\n\n id_type \n SentenceBias\n ::GetClass(id_type idx) const { return idx; }\n\n float& \n SentenceBias\n ::operator[](id_type const idx) \n {\n UTIL_THROW_IF2(idx >= m_bias.size(), \"Out of bounds\");\n return m_bias[idx];\n }\n\n float \n SentenceBias\n ::operator[](id_type const idx) const \n { \n UTIL_THROW_IF2(idx >= m_bias.size(), \"Out of bounds\");\n return m_bias[idx];\n }\n \n size_t \n SentenceBias\n ::size() const { return m_bias.size(); }\n \n }\n}\n<commit_msg>Make sure things work when curl-based biasing is disabled.<commit_after>#include \"ug_sampling_bias.h\"\n#include <iostream>\n#include <boost\/foreach.hpp>\n \n#ifdef HAVE_CURLPP\n#include <curlpp\/Options.hpp>\n#include <curlpp\/cURLpp.hpp>\n#include <curlpp\/Easy.hpp>\n#endif\n\nnamespace Moses\n{\n namespace bitext\n {\n using ugdiss::id_type;\n\n#ifdef HAVE_CURLPP\n std::string \n query_bias_server(std::string const& url, std::string const& text)\n {\n \/\/ communicate with the bias server; resuts will be in ...\n std::ostringstream os; \n curlpp::Easy myRequest;\n std::string query = url+curlpp::escape(text);\n myRequest.setOpt(new curlpp::options::Url(query));\n curlpp::options::WriteStream ws(&os);\n myRequest.setOpt(ws); \/\/ Give it to your request\n myRequest.perform(); \/\/ This will output to os\n return os.str();\n }\n#endif\n\n DocumentBias\n ::DocumentBias\n ( std::vector<id_type> const& sid2doc, \n std::map<std::string,id_type> const& docname2docid,\n std::string const& server_url, std::string const& text,\n std::ostream* log)\n : m_sid2docid(sid2doc)\n , m_bias(docname2docid.size(), 0)\n {\n#ifdef HAVE_CURLPP\n std::string json = query_bias_server(server_url, text);\n init_from_json(json, docname2docid, log);\n#endif\n }\n\n void \n DocumentBias\n ::init_from_json\n ( std::string const& json, std::map<std::string,id_type> const& docname2docid,\n std::ostream* log)\n { \/\/ poor man's special purpose json parser for responses from the \n \/\/ MMT bias server\n\t\n std::string d; float total = 0; std::map<std::string,float> bias; \n size_t i = 0; while (i < json.size() && json[i] != '\"') ++i;\n while (++i < json.size())\n\t{\n\t size_t k = i; while (i < json.size() && json[i] != '\"') ++i;\n\t if (i >= json.size()) break;\n\t float& f = bias[json.substr(k,i-k)];\n\t while (++i < json.size() && json[i] != ':');\n\t k = ++i; \n\t while (++i < json.size() && json[i] != ',' && json[i] != '}');\n\t total += (f = atof(json.substr(k, i-k).c_str()));\n\t k = ++i; while (i < json.size() && json[i] != '\"') ++i;\n\t}\n \n typedef std::pair<std::string const,float> item;\n if (total) { BOOST_FOREACH(item& x, bias) { x.second \/= total; } } \n if (log)\n\t{\n\t BOOST_FOREACH(item& x, bias) \n\t {\n\t std::map<std::string,id_type>::const_iterator m;\n\t m = docname2docid.find(x.first);\n\t int docid = m != docname2docid.end() ? m->second : -1;\n\t *log << \"CONTEXT SERVER RESPONSE \" \n\t\t << \"[\" << docid << \"] \"\n\t\t << x.first << \" \" << x.second << std::endl; \n\t }\n\t}\n init(bias, docname2docid);\n \n \/\/ using xmlrpc_parse_json didn't always work (parser errors)\n \/\/ xmlrpc_value* b = xmlrpc_parse_json(env ,buf.str().c_str());\n \/\/ std::cerr << \"|\" << buf.str() << \"|\" << std::endl; \n \/\/ \/\/ if (b == NULL) std::cerr << \"OOpS\" << std::endl; \n \/\/ xmlrpc_c::value_struct v(b); \/\/ = *b;\n \/\/ std::map<std::string, xmlrpc_c::value> const \n \/\/ \tbmap = static_cast<map<std::string, xmlrpc_c::value> >(v);\n \/\/ std::map<std::string, float> bias;\n \/\/ typedef std::map<std::string, xmlrpc_c::value>::value_type item;\n \/\/ float total = 0;\n \/\/ BOOST_FOREACH(item const& x, bmap)\n \/\/ \t{\n \/\/ \t total += bias[x.first] = xmlrpc_c::value_double(x.second);\n \/\/ \t}\n \/\/ typedef std::map<std::string, float>::value_type fitem;\n \/\/ BOOST_FOREACH(fitem const& x, bias)\n \/\/ \tstd::cerr << x.first << \" \" << x.second\/total << std::endl; \n \/\/ \/\/ delete b;\n }\n\n void \n DocumentBias\n ::init(std::map<std::string,float> const& biasmap,\n\t std::map<std::string,id_type> const& docname2docid)\n {\n typedef std::map<std::string, id_type>::value_type doc_record;\n float total = 0;\n BOOST_FOREACH(doc_record const& d, docname2docid)\n\t{\n\t std::map<std::string, float>::const_iterator m = biasmap.find(d.first);\n\t if (m != biasmap.end()) total += (m_bias[d.second] = m->second);\n\t }\n if (total) { BOOST_FOREACH(float& f, m_bias) f \/= total; }\n BOOST_FOREACH(doc_record const& d, docname2docid)\n\tstd::cerr << \"BIAS \" << d.first << \" \" << m_bias[d.second] << std::endl;\n }\n \n id_type \n DocumentBias\n ::GetClass(id_type const idx) const\n {\t\n return m_sid2docid.at(idx); \n }\n \n float \n DocumentBias\n ::operator[](id_type const idx) const \n { \n UTIL_THROW_IF2(idx >= m_sid2docid.size(), \n\t\t \"Out of bounds: \" << idx << \"\/\" << m_sid2docid.size());\n return m_bias[m_sid2docid[idx]];\n }\n\n size_t \n DocumentBias\n ::size() const \n { return m_sid2docid.size(); }\n\n\n\n SentenceBias\n ::SentenceBias(std::vector<float> const& bias) \n : m_bias(bias) { }\n\n SentenceBias\n ::SentenceBias(size_t const s) : m_bias(s) { }\n\n id_type \n SentenceBias\n ::GetClass(id_type idx) const { return idx; }\n\n float& \n SentenceBias\n ::operator[](id_type const idx) \n {\n UTIL_THROW_IF2(idx >= m_bias.size(), \"Out of bounds\");\n return m_bias[idx];\n }\n\n float \n SentenceBias\n ::operator[](id_type const idx) const \n { \n UTIL_THROW_IF2(idx >= m_bias.size(), \"Out of bounds\");\n return m_bias[idx];\n }\n \n size_t \n SentenceBias\n ::size() const { return m_bias.size(); }\n \n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <iostream>\n#include <stdlib.h>\n\n#include \"Note.h\"\n#include \"VoiceProp.h\"\n#include \"Oto.h\"\n\n#define DEBUG true\n#define DEBUG_FULL false \/\/ enables debug output on every oto line, may result in a LOT of output\n\nusing namespace std;\n\nOto::Oto(std::string path) {\n\tfilePath = path;\n\topenFile();\n}\n\nOto::~Oto() { }\n\nvoid Oto::openFile() {\n\tstd::ifstream otoStream;\n\totoStream.open(filePath + \"\/oto.ini\");\n\t\n\tif (!otoStream) {\n\t\t\/\/TODO: fallback to default from config file\n\t\tcout << \"Error: Voicebank \\\"\" << filePath << \"\\\" not found or format unsupported. Stop.\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t\n\tif (otoStream.is_open()) {\n\t\tstd::string otoItem;\n\t\tunsigned int index = 0;\n\t\tvoices.resize(8192);\n\t\t\n\t\t\n\t\t\/\/ This was mostly ported from FVSS, there probably will be errors\n\t\t\/\/ Also needs error handling \n\t\twhile (getline(otoStream, otoItem)) {\n\t\t\tVoiceProp *vp = new VoiceProp();\n\t\t\t\n\t\t\t\/\/ needed because of newline fix\n\t\t\tstd::string item = otoItem;\n#if DEBUG_FULL\n\t\t\tclog << \"DEBUG_FULL: oto line \" << std::to_string(index) << \":\" << std::endl;\n\t\t\tclog << \"\t\" << item << std::endl;\n#endif\n\t\t\ttry {\n\t\t\t\t\/\/TODO: maybe remove newlines that get left behind\n\t\t\t\t\n\t\t\t\t\/\/ Get indexes from line\n\t\t\t\tint index1 = item.find('=');\n int index2 = item.find(\",\", index1 + 1);\n int index3 = item.find(\",\", index2 + 1);\n int index4 = item.find(\",\", index3 + 1);\n int index5 = item.find(\",\", index4 + 1);\n int index6 = item.find(\",\", index5 + 1);\n#if DEBUG_FULL \n\t\t\t\tclog << \"DEBUG_FULL: Printing all OTO content indexes\" << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index1) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index2) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index3) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index4) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index5) << std::endl;\n#endif\n\t\t\t\t\/\/ Chop up line into individual properties and add them to vp\n\t\t\t\tvp->fileName = item.substr(0, index1);\n\t\t\t\tvp->sampleName = item.substr(index1 + 1, index2 - index1 - 1);\n#if DEBUG_FULL\n\t\t\t\tclog << \"DEBUG_FULL: OTO fileName: \" << vp->fileName << std::endl;\n\t\t\t\tclog << \"DEBUG_FULL: OTO sampleName: \" << vp->sampleName << std::endl;\n#endif\n\t\t\t\tvp->start = std::stoi(item.substr(index2 + 1, index3 - index2 - 1));\n vp->consonant = std::stoi(item.substr(index3 + 1, index4 - index3 - 1));\n vp->end = std::stoi(item.substr(index4 + 1, index5 - index4 - 1));\n vp->preutterance = std::stoi(item.substr(index5 + 1, index6 - index5 - 1));\n vp->overlap = std::stoi(item.substr(index6 + 1));\n#if DEBUG_FULL\n\t\t\t\tclog << \"DEBUG_FULL: Printing all parsed OTO properties:\" << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->start) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->consonant) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->end) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->preutterance) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->overlap) << std::endl;\n#endif\t\t\t\t\n\t\t\t\t\/\/TODO: might need to remove newlines from FileName property\n\t\t\t\t\n\t\t\t\tif (voices.size() <= index) voices.resize(index + 129);\n\t\t\t\tvoices[index] = vp;\n#if DEBUG\t\t\t\t\n\t\t\t\t\/\/print the first 2 oto property lists\n\t\t\t\tif (index < 2) {\n\t\t\t\t\tclog << \"DEBUG: OTO data from entry \" << std::to_string(index);\n\t\t\t\t\tclog << \"fileName = \" << voices[index]->fileName << std::endl;\n\t\t\t\t\tclog << \"sampleName = \" << voices[index]->sampleName << std::endl;\n\t\t\t\t\tclog << \"start = \" << std::to_string(voices[index]->start) << std::endl;\n\t\t\t\t\tclog << \"consonant = \" << std::to_string(voices[index]->consonant) << std::endl;\n\t\t\t\t\tclog << \"end = \" << std::to_string(voices[index]->end) << std::endl;\n\t\t\t\t\tclog << \"preutterance = \" << std::to_string(voices[index]->preutterance) << std::endl;\n\t\t\t\t\tclog << \"overlap = \" << std::to_string(voices[index]->overlap) << std::endl;\n\t\t\t\t}\n#endif\n\t\t\t}\t\t\t\n\t\t\tcatch (...) { }\n\t\t\t\n\t\t\tindex++;\n\t\t}\n\t\tvoices.resize(index + 1);\n\t}\n}\n\n\/\/ This is broken...\nvoid Oto::getVPfromName(std::string smpName, VoiceProp *vp) {\n\tfor (int i = 0; i < voices.size(); i++) {\n\t\tif (voices[i]->sampleName == smpName || voices[i]->sampleName == smpName + \".wav\")\n\t\t\tvp = voices[i];\n\t}\n#if DEBUG\n\tclog << \"DEBUG: Note with content \\\"\" << smpName << \"\\\" doesn't exist in voicebank;\"\n\t\t<< \" using empty VoiceProp.\" << std::endl;\n#endif\n\tvp = new VoiceProp();\n}<commit_msg>Fixed VoiceProperties being stored as integers<commit_after>#include <string>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <iostream>\n#include <stdlib.h>\n\n#include \"Note.h\"\n#include \"VoiceProp.h\"\n#include \"Oto.h\"\n\n#define DEBUG true\n#define DEBUG_FULL false \/\/ enables debug output on every oto line, may result in a LOT of output\n\nusing namespace std;\n\nOto::Oto(std::string path) {\n\tfilePath = path;\n\topenFile();\n}\n\nOto::~Oto() { }\n\nvoid Oto::openFile() {\n\tstd::ifstream otoStream;\n\totoStream.open(filePath + \"\/oto.ini\");\n\t\n\tif (!otoStream) {\n\t\t\/\/TODO: fallback to default from config file\n\t\tcout << \"Error: Voicebank \\\"\" << filePath << \"\\\" not found or format unsupported. Stop.\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t\n\tif (otoStream.is_open()) {\n\t\tstd::string otoItem;\n\t\tunsigned int index = 0;\n\t\tvoices.resize(8192);\n\t\t\n\t\t\n\t\t\/\/ This was mostly ported from FVSS, there probably will be errors\n\t\t\/\/ Also needs error handling \n\t\twhile (getline(otoStream, otoItem)) {\n\t\t\tVoiceProp *vp = new VoiceProp();\n\t\t\t\n\t\t\t\/\/ needed because of newline fix\n\t\t\tstd::string item = otoItem;\n#if DEBUG_FULL\n\t\t\tclog << \"DEBUG_FULL: oto line \" << std::to_string(index) << \":\" << std::endl;\n\t\t\tclog << \"\t\" << item << std::endl;\n#endif\n\t\t\ttry {\n\t\t\t\t\/\/TODO: maybe remove newlines that get left behind\n\t\t\t\t\n\t\t\t\t\/\/ Get indexes from line\n\t\t\t\tint index1 = item.find('=');\n int index2 = item.find(\",\", index1 + 1);\n int index3 = item.find(\",\", index2 + 1);\n int index4 = item.find(\",\", index3 + 1);\n int index5 = item.find(\",\", index4 + 1);\n int index6 = item.find(\",\", index5 + 1);\n#if DEBUG_FULL \n\t\t\t\tclog << \"DEBUG_FULL: Printing all OTO content indexes\" << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index1) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index2) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index3) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index4) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(index5) << std::endl;\n#endif\n\t\t\t\t\/\/ Chop up line into individual properties and add them to vp\n\t\t\t\tvp->fileName = item.substr(0, index1);\n\t\t\t\tvp->sampleName = item.substr(index1 + 1, index2 - index1 - 1);\n#if DEBUG_FULL\n\t\t\t\tclog << \"DEBUG_FULL: OTO fileName: \" << vp->fileName << std::endl;\n\t\t\t\tclog << \"DEBUG_FULL: OTO sampleName: \" << vp->sampleName << std::endl;\n#endif\n\t\t\t\tvp->start = std::stod(item.substr(index2 + 1, index3 - index2 - 1));\n vp->consonant = std::stod(item.substr(index3 + 1, index4 - index3 - 1));\n vp->end = std::stod(item.substr(index4 + 1, index5 - index4 - 1));\n vp->preutterance = std::stod(item.substr(index5 + 1, index6 - index5 - 1));\n vp->overlap = std::stod(item.substr(index6 + 1));\n#if DEBUG_FULL\n\t\t\t\tclog << \"DEBUG_FULL: Printing all parsed OTO properties:\" << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->start) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->consonant) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->end) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->preutterance) << std::endl;\n\t\t\t\tclog << \"\t\" << std::to_string(vp->overlap) << std::endl;\n#endif\t\t\t\t\n\t\t\t\t\/\/TODO: might need to remove newlines from FileName property\n\t\t\t\t\n\t\t\t\tif (voices.size() <= index) voices.resize(index + 129);\n\t\t\t\tvoices[index] = vp;\n#if DEBUG\t\t\t\t\n\t\t\t\t\/\/print the first 2 oto property lists\n\t\t\t\tif (index < 2) {\n\t\t\t\t\tclog << \"DEBUG: OTO data from entry \" << std::to_string(index);\n\t\t\t\t\tclog << \"fileName = \" << voices[index]->fileName << std::endl;\n\t\t\t\t\tclog << \"sampleName = \" << voices[index]->sampleName << std::endl;\n\t\t\t\t\tclog << \"start = \" << std::to_string(voices[index]->start) << std::endl;\n\t\t\t\t\tclog << \"consonant = \" << std::to_string(voices[index]->consonant) << std::endl;\n\t\t\t\t\tclog << \"end = \" << std::to_string(voices[index]->end) << std::endl;\n\t\t\t\t\tclog << \"preutterance = \" << std::to_string(voices[index]->preutterance) << std::endl;\n\t\t\t\t\tclog << \"overlap = \" << std::to_string(voices[index]->overlap) << std::endl;\n\t\t\t\t}\n#endif\n\t\t\t}\t\t\t\n\t\t\tcatch (...) { }\n\t\t\t\n\t\t\tindex++;\n\t\t}\n\t\tvoices.resize(index + 1);\n\t}\n}\n\n\/\/ This is broken...\nvoid Oto::getVPfromName(std::string smpName, VoiceProp *vp) {\n\tfor (int i = 0; i < voices.size(); i++) {\n\t\tif (voices[i]->sampleName == smpName || voices[i]->sampleName == smpName + \".wav\")\n\t\t\tvp = voices[i];\n\t}\n#if DEBUG\n\tclog << \"DEBUG: Note with content \\\"\" << smpName << \"\\\" doesn't exist in voicebank;\"\n\t\t<< \" using empty VoiceProp.\" << std::endl;\n#endif\n\tvp = new VoiceProp();\n}<|endoftext|>"} {"text":"<commit_before>#include \"org\/xtreemfs\/client\/proxy.h\"\r\n#include \"policy_container.h\"\r\nusing namespace org::xtreemfs::client;\r\n\r\n#include \"org\/xtreemfs\/interfaces\/constants.h\"\r\n\r\n#include <errno.h>\r\n#ifdef _WIN32\r\n#include \"yield\/ipc\/sockets.h\"\r\n#define ETIMEDOUT WSAETIMEDOUT\r\n#endif\r\n\r\n\r\nProxy::Proxy( const YIELD::URI& uri, uint16_t default_oncrpc_port, uint16_t default_oncrpcs_port ) : uri( uri )\r\n{\r\n if ( strcmp( uri.getScheme(), org::xtreemfs::interfaces::ONCRPC_SCHEME ) == 0 || strcmp( uri.getScheme(), org::xtreemfs::interfaces::ONCRPCS_SCHEME ) == 0 )\r\n {\r\n if ( this->uri.getPort() == 0 )\r\n {\r\n if ( strcmp( this->uri.getScheme(), org::xtreemfs::interfaces::ONCRPC_SCHEME ) == 0 )\r\n this->uri.setPort( default_oncrpc_port );\r\n else if ( strcmp( this->uri.getScheme(), org::xtreemfs::interfaces::ONCRPCS_SCHEME ) == 0 )\r\n this->uri.setPort( default_oncrpcs_port );\r\n else\r\n YIELD::DebugBreak();\r\n }\r\n\r\n this->reconnect_tries_max = PROXY_DEFAULT_RECONNECT_TRIES_MAX;\r\n this->flags = PROXY_DEFAULT_FLAGS;\r\n this->peer_ip = 0;\r\n this->conn = 0;\r\n \r\n org::xtreemfs::interfaces::Exceptions().registerSerializableFactories( serializable_factories );\r\n }\r\n else\r\n throw YIELD::Exception( \"unknown URI scheme\" );\r\n}\r\n\r\nProxy::~Proxy()\r\n{\r\n delete conn;\r\n}\r\n\r\nvoid Proxy::handleEvent( YIELD::Event& ev )\r\n{\r\n switch ( ev.getTypeId() )\r\n {\r\n case TYPE_ID( YIELD::StageStartupEvent ):\r\n case TYPE_ID( YIELD::StageShutdownEvent ): YIELD::SharedObject::decRef( ev ); break;\r\n\r\n default:\r\n {\r\n switch ( ev.getGeneralType() )\r\n {\r\n case YIELD::RTTI::REQUEST:\r\n {\r\n YIELD::Request& req = static_cast<YIELD::Request&>( ev );\r\n if ( ( flags & PROXY_FLAG_PRINT_OPERATIONS ) == PROXY_FLAG_PRINT_OPERATIONS )\r\n {\r\n YIELD::PrettyPrintOutputStream pretty_print_output_stream( std::cout );\r\n pretty_print_output_stream.writeSerializable( YIELD::PrettyPrintOutputStream::Declaration( req.getTypeName() ), req );\r\n }\r\n\r\n try\r\n {\r\n YIELD::auto_SharedObject<org::xtreemfs::interfaces::UserCredentials> user_credentials = get_user_credentials();\r\n YIELD::ONCRPCRequest oncrpc_req( YIELD::SharedObject::incRef( req ), serializable_factories, user_credentials.get() ? org::xtreemfs::interfaces::ONCRPC_AUTH_FLAVOR : YIELD::ONCRPCRequest::AUTH_NONE, user_credentials.get() );\r\n\r\n uint64_t timeout_ms = req.getResponseTimeoutMS();\r\n uint64_t original_timeout_ms = timeout_ms;\r\n uint8_t reconnect_tries_left = reconnect_tries_max;\r\n\r\n if ( conn == NULL )\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n\r\n if ( timeout_ms == static_cast<uint64_t>( -1 ) ) \/\/ Blocking\r\n {\r\n YIELD::SocketLib::setBlocking( conn->getSocket() );\r\n\r\n for ( uint8_t serialize_tries = 0; serialize_tries < 2; serialize_tries++ ) \/\/ Try, allow for one reconnect, then try again\r\n {\r\n oncrpc_req.serialize( *conn );\r\n if ( conn->getStatus() == YIELD::SocketConnection::SCS_READY )\r\n {\r\n for ( uint8_t deserialize_tries = 0; deserialize_tries < 2; deserialize_tries++ )\r\n {\r\n oncrpc_req.deserialize( *conn );\r\n if ( conn->getStatus() == YIELD::SocketConnection::SCS_READY )\r\n {\r\n req.respond( static_cast<YIELD::Event&>( YIELD::SharedObject::incRef( *oncrpc_req.getInBody() ) ) );\r\n YIELD::SharedObject::decRef( req );\r\n return;\r\n }\r\n else if ( conn->getStatus() == YIELD::SocketConnection::SCS_CLOSED )\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n else\r\n YIELD::DebugBreak();\r\n }\r\n }\r\n else if ( conn->getStatus() == YIELD::SocketConnection::SCS_CLOSED )\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n else\r\n YIELD::DebugBreak();\r\n }\r\n }\r\n else \/\/ Non-blocking\/timed\r\n {\r\n YIELD::SocketLib::setNonBlocking( conn->getSocket() );\r\n\r\n bool have_written = false; \/\/ Use the variable so the read and write attempt loops can be combined and eliminate some code duplication\r\n\r\n while ( true ) \/\/ Loop for read and write attempts\r\n {\r\n if ( !have_written )\r\n oncrpc_req.serialize( *conn );\r\n else\r\n oncrpc_req.deserialize( *conn );\r\n\r\n \/\/ Use if statements instead of a switch so the break after a successful read will exit the loop\r\n if ( conn->getStatus() == YIELD::SocketConnection::SCS_READY )\r\n {\r\n if ( !have_written )\r\n have_written = true;\r\n else\r\n break;\r\n }\r\n else if ( conn->getStatus() == YIELD::SocketConnection::SCS_CLOSED )\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n else if ( timeout_ms > 0 )\r\n {\r\n bool enable_read = conn->getStatus() == YIELD::SocketConnection::SCS_BLOCKED_ON_READ;\r\n fd_event_queue.toggleSocketEvent( conn->getSocket(), conn, enable_read, !enable_read );\r\n double start_epoch_time_ms = YIELD::Time::getCurrentEpochTimeMS();\r\n YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( timeout_ms ) * NS_IN_MS ) );\r\n if ( fd_event )\r\n {\r\n if ( fd_event->error_code == 0 )\r\n timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentEpochTimeMS() - start_epoch_time_ms ), timeout_ms );\r\n else\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n }\r\n else\r\n throwExceptionEvent( new YIELD::PlatformExceptionEvent( ETIMEDOUT ) );\r\n }\r\n else\r\n throwExceptionEvent( new YIELD::PlatformExceptionEvent( ETIMEDOUT ) );\r\n }\r\n }\r\n }\r\n catch ( YIELD::ExceptionEvent* exc_ev )\r\n {\r\n req.respond( *exc_ev );\r\n YIELD::SharedObject::decRef( req );\r\n }\r\n }\r\n break;\r\n\r\n default: YIELD::DebugBreak(); break;\r\n }\r\n }\r\n break;\r\n }\r\n}\r\n\r\nuint8_t Proxy::reconnect( uint64_t timeout_ms, uint8_t reconnect_tries_left )\r\n{\r\n if ( peer_ip == 0 )\r\n {\r\n peer_ip = YIELD::SocketLib::resolveHost( uri.getHost() );\r\n if ( peer_ip == 0 && ( strcmp( uri.getHost(), \"localhost\" ) == 0 || strcmp( uri.getHost(), \"127.0.0.1\" ) == 0 ) )\r\n peer_ip = YIELD::SocketLib::resolveHost( YIELD::SocketLib::getLocalHostFQDN() );\r\n if ( peer_ip == 0 )\r\n throw new YIELD::PlatformExceptionEvent();\r\n }\r\n\r\n if ( conn != NULL ) \/\/ This is a reconnect, not the first connect\r\n {\r\n fd_event_queue.detachSocket( conn->getSocket(), conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n while ( reconnect_tries_left > 0 )\r\n {\r\n reconnect_tries_left--;\r\n\r\n\r\n \/\/ Create the conn object based on the URI type\r\n if ( strcmp( uri.getScheme(), \"oncrpc\" ) == 0 )\r\n conn = new YIELD::TCPConnection( peer_ip, uri.getPort(), NULL );\r\n else\r\n YIELD::DebugBreak();\r\n\r\n\r\n \/\/ Attach the socket to the fd_event_queue even if we're doing a blocking connect, in case a later read\/write is non-blocking\r\n fd_event_queue.attachSocket( conn->getSocket(), conn, false, false ); \/\/ Attach without read or write notifications enabled\r\n\r\n\r\n \/\/ Now try the actual connect\r\n if ( timeout_ms == static_cast<uint64_t>( -1 ) ) \/\/ Blocking\r\n {\r\n YIELD::SocketLib::setBlocking( conn->getSocket() );\r\n\r\n if ( conn->connect() == YIELD::SocketConnection::SCS_READY )\r\n return reconnect_tries_left;\r\n }\r\n else \/\/ Non-blocking\/timed\r\n {\r\n YIELD::SocketLib::setNonBlocking( conn->getSocket() );\r\n\r\n switch ( conn->connect() )\r\n {\r\n case YIELD::SocketConnection::SCS_READY: break;\r\n case YIELD::SocketConnection::SCS_BLOCKED_ON_WRITE:\r\n {\r\n fd_event_queue.toggleSocketEvent( conn->getSocket(), conn, false, true ); \/\/ Write readiness = the connect() operation is complete\r\n double start_epoch_time_ms = YIELD::Time::getCurrentEpochTimeMS();\r\n YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( timeout_ms ) * NS_IN_MS ) );\r\n if ( fd_event && fd_event->error_code == 0 &&\r\n conn->connect() == YIELD::SocketConnection::SCS_READY )\r\n {\r\n fd_event_queue.toggleSocketEvent( conn->getSocket(), conn, false, false );\r\n return reconnect_tries_left;\r\n }\r\n else\r\n {\r\n timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentEpochTimeMS() - start_epoch_time_ms ), timeout_ms );\r\n if ( timeout_ms == 0 ) { reconnect_tries_left = 0; break; }\r\n }\r\n }\r\n }\r\n }\r\n\r\n \/\/ Clear the connection state for the next try\r\n fd_event_queue.detachSocket( conn->getSocket(), conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n unsigned long error_code = YIELD::PlatformException::errno_();\r\n if ( error_code == 0 )\r\n error_code = ETIMEDOUT;\r\n throw new YIELD::PlatformExceptionEvent( error_code );\r\n}\r\n\r\nvoid Proxy::throwExceptionEvent( YIELD::ExceptionEvent* exc_ev )\r\n{\r\n if ( conn )\r\n {\r\n fd_event_queue.detachSocket( conn->getSocket(), conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n throw exc_ev;\r\n}\r\n<commit_msg>Proxy: Linux fix<commit_after>#include \"org\/xtreemfs\/client\/proxy.h\"\r\n#include \"policy_container.h\"\r\nusing namespace org::xtreemfs::client;\r\n\r\n#include \"org\/xtreemfs\/interfaces\/constants.h\"\r\n\r\n#include <errno.h>\r\n#ifdef _WIN32\r\n#include \"yield\/ipc\/sockets.h\"\r\n#define ETIMEDOUT WSAETIMEDOUT\r\n#endif\r\n\r\n\r\nProxy::Proxy( const YIELD::URI& uri, uint16_t default_oncrpc_port, uint16_t default_oncrpcs_port ) : uri( uri )\r\n{\r\n if ( strcmp( uri.getScheme(), org::xtreemfs::interfaces::ONCRPC_SCHEME ) == 0 || strcmp( uri.getScheme(), org::xtreemfs::interfaces::ONCRPCS_SCHEME ) == 0 )\r\n {\r\n if ( this->uri.getPort() == 0 )\r\n {\r\n if ( strcmp( this->uri.getScheme(), org::xtreemfs::interfaces::ONCRPC_SCHEME ) == 0 )\r\n this->uri.setPort( default_oncrpc_port );\r\n else if ( strcmp( this->uri.getScheme(), org::xtreemfs::interfaces::ONCRPCS_SCHEME ) == 0 )\r\n this->uri.setPort( default_oncrpcs_port );\r\n else\r\n YIELD::DebugBreak();\r\n }\r\n\r\n this->reconnect_tries_max = PROXY_DEFAULT_RECONNECT_TRIES_MAX;\r\n this->flags = PROXY_DEFAULT_FLAGS;\r\n this->peer_ip = 0;\r\n this->conn = 0;\r\n \r\n org::xtreemfs::interfaces::Exceptions().registerSerializableFactories( serializable_factories );\r\n }\r\n else\r\n throw YIELD::Exception( \"unknown URI scheme\" );\r\n}\r\n\r\nProxy::~Proxy()\r\n{\r\n delete conn;\r\n}\r\n\r\nvoid Proxy::handleEvent( YIELD::Event& ev )\r\n{\r\n switch ( ev.getTypeId() )\r\n {\r\n case TYPE_ID( YIELD::StageStartupEvent ):\r\n case TYPE_ID( YIELD::StageShutdownEvent ): YIELD::SharedObject::decRef( ev ); break;\r\n\r\n default:\r\n {\r\n switch ( ev.getGeneralType() )\r\n {\r\n case YIELD::RTTI::REQUEST:\r\n {\r\n YIELD::Request& req = static_cast<YIELD::Request&>( ev );\r\n if ( ( flags & PROXY_FLAG_PRINT_OPERATIONS ) == PROXY_FLAG_PRINT_OPERATIONS )\r\n {\r\n YIELD::PrettyPrintOutputStream pretty_print_output_stream( std::cout );\r\n pretty_print_output_stream.writeSerializable( YIELD::PrettyPrintOutputStream::Declaration( req.getTypeName() ), req );\r\n }\r\n\r\n try\r\n {\r\n YIELD::auto_SharedObject<org::xtreemfs::interfaces::UserCredentials> user_credentials = get_user_credentials();\r\n YIELD::ONCRPCRequest oncrpc_req( YIELD::SharedObject::incRef( req ), serializable_factories, user_credentials.get() ? org::xtreemfs::interfaces::ONCRPC_AUTH_FLAVOR : 0, user_credentials.get() );\r\n\r\n uint64_t timeout_ms = req.getResponseTimeoutMS();\r\n uint64_t original_timeout_ms = timeout_ms;\r\n uint8_t reconnect_tries_left = reconnect_tries_max;\r\n\r\n if ( conn == NULL )\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n\r\n if ( timeout_ms == static_cast<uint64_t>( -1 ) ) \/\/ Blocking\r\n {\r\n YIELD::SocketLib::setBlocking( conn->getSocket() );\r\n\r\n for ( uint8_t serialize_tries = 0; serialize_tries < 2; serialize_tries++ ) \/\/ Try, allow for one reconnect, then try again\r\n {\r\n oncrpc_req.serialize( *conn );\r\n if ( conn->getStatus() == YIELD::SocketConnection::SCS_READY )\r\n {\r\n for ( uint8_t deserialize_tries = 0; deserialize_tries < 2; deserialize_tries++ )\r\n {\r\n oncrpc_req.deserialize( *conn );\r\n if ( conn->getStatus() == YIELD::SocketConnection::SCS_READY )\r\n {\r\n req.respond( static_cast<YIELD::Event&>( YIELD::SharedObject::incRef( *oncrpc_req.getInBody() ) ) );\r\n YIELD::SharedObject::decRef( req );\r\n return;\r\n }\r\n else if ( conn->getStatus() == YIELD::SocketConnection::SCS_CLOSED )\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n else\r\n YIELD::DebugBreak();\r\n }\r\n }\r\n else if ( conn->getStatus() == YIELD::SocketConnection::SCS_CLOSED )\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n else\r\n YIELD::DebugBreak();\r\n }\r\n }\r\n else \/\/ Non-blocking\/timed\r\n {\r\n YIELD::SocketLib::setNonBlocking( conn->getSocket() );\r\n\r\n bool have_written = false; \/\/ Use the variable so the read and write attempt loops can be combined and eliminate some code duplication\r\n\r\n while ( true ) \/\/ Loop for read and write attempts\r\n {\r\n if ( !have_written )\r\n oncrpc_req.serialize( *conn );\r\n else\r\n oncrpc_req.deserialize( *conn );\r\n\r\n \/\/ Use if statements instead of a switch so the break after a successful read will exit the loop\r\n if ( conn->getStatus() == YIELD::SocketConnection::SCS_READY )\r\n {\r\n if ( !have_written )\r\n have_written = true;\r\n else\r\n break;\r\n }\r\n else if ( conn->getStatus() == YIELD::SocketConnection::SCS_CLOSED )\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n else if ( timeout_ms > 0 )\r\n {\r\n bool enable_read = conn->getStatus() == YIELD::SocketConnection::SCS_BLOCKED_ON_READ;\r\n fd_event_queue.toggleSocketEvent( conn->getSocket(), conn, enable_read, !enable_read );\r\n double start_epoch_time_ms = YIELD::Time::getCurrentEpochTimeMS();\r\n YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( timeout_ms ) * NS_IN_MS ) );\r\n if ( fd_event )\r\n {\r\n if ( fd_event->error_code == 0 )\r\n timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentEpochTimeMS() - start_epoch_time_ms ), timeout_ms );\r\n else\r\n reconnect_tries_left = reconnect( original_timeout_ms, reconnect_tries_left );\r\n }\r\n else\r\n throwExceptionEvent( new YIELD::PlatformExceptionEvent( ETIMEDOUT ) );\r\n }\r\n else\r\n throwExceptionEvent( new YIELD::PlatformExceptionEvent( ETIMEDOUT ) );\r\n }\r\n }\r\n }\r\n catch ( YIELD::ExceptionEvent* exc_ev )\r\n {\r\n req.respond( *exc_ev );\r\n YIELD::SharedObject::decRef( req );\r\n }\r\n }\r\n break;\r\n\r\n default: YIELD::DebugBreak(); break;\r\n }\r\n }\r\n break;\r\n }\r\n}\r\n\r\nuint8_t Proxy::reconnect( uint64_t timeout_ms, uint8_t reconnect_tries_left )\r\n{\r\n if ( peer_ip == 0 )\r\n {\r\n peer_ip = YIELD::SocketLib::resolveHost( uri.getHost() );\r\n if ( peer_ip == 0 && ( strcmp( uri.getHost(), \"localhost\" ) == 0 || strcmp( uri.getHost(), \"127.0.0.1\" ) == 0 ) )\r\n peer_ip = YIELD::SocketLib::resolveHost( YIELD::SocketLib::getLocalHostFQDN() );\r\n if ( peer_ip == 0 )\r\n throw new YIELD::PlatformExceptionEvent();\r\n }\r\n\r\n if ( conn != NULL ) \/\/ This is a reconnect, not the first connect\r\n {\r\n fd_event_queue.detachSocket( conn->getSocket(), conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n while ( reconnect_tries_left > 0 )\r\n {\r\n reconnect_tries_left--;\r\n\r\n\r\n \/\/ Create the conn object based on the URI type\r\n if ( strcmp( uri.getScheme(), \"oncrpc\" ) == 0 )\r\n conn = new YIELD::TCPConnection( peer_ip, uri.getPort(), NULL );\r\n else\r\n YIELD::DebugBreak();\r\n\r\n\r\n \/\/ Attach the socket to the fd_event_queue even if we're doing a blocking connect, in case a later read\/write is non-blocking\r\n fd_event_queue.attachSocket( conn->getSocket(), conn, false, false ); \/\/ Attach without read or write notifications enabled\r\n\r\n\r\n \/\/ Now try the actual connect\r\n if ( timeout_ms == static_cast<uint64_t>( -1 ) ) \/\/ Blocking\r\n {\r\n YIELD::SocketLib::setBlocking( conn->getSocket() );\r\n\r\n if ( conn->connect() == YIELD::SocketConnection::SCS_READY )\r\n return reconnect_tries_left;\r\n }\r\n else \/\/ Non-blocking\/timed\r\n {\r\n YIELD::SocketLib::setNonBlocking( conn->getSocket() );\r\n\r\n switch ( conn->connect() )\r\n {\r\n case YIELD::SocketConnection::SCS_READY: break;\r\n case YIELD::SocketConnection::SCS_BLOCKED_ON_WRITE:\r\n {\r\n fd_event_queue.toggleSocketEvent( conn->getSocket(), conn, false, true ); \/\/ Write readiness = the connect() operation is complete\r\n double start_epoch_time_ms = YIELD::Time::getCurrentEpochTimeMS();\r\n YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( timeout_ms ) * NS_IN_MS ) );\r\n if ( fd_event && fd_event->error_code == 0 &&\r\n conn->connect() == YIELD::SocketConnection::SCS_READY )\r\n {\r\n fd_event_queue.toggleSocketEvent( conn->getSocket(), conn, false, false );\r\n return reconnect_tries_left;\r\n }\r\n else\r\n {\r\n timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentEpochTimeMS() - start_epoch_time_ms ), timeout_ms );\r\n if ( timeout_ms == 0 ) { reconnect_tries_left = 0; break; }\r\n }\r\n }\r\n }\r\n }\r\n\r\n \/\/ Clear the connection state for the next try\r\n fd_event_queue.detachSocket( conn->getSocket(), conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n unsigned long error_code = YIELD::PlatformException::errno_();\r\n if ( error_code == 0 )\r\n error_code = ETIMEDOUT;\r\n throw new YIELD::PlatformExceptionEvent( error_code );\r\n}\r\n\r\nvoid Proxy::throwExceptionEvent( YIELD::ExceptionEvent* exc_ev )\r\n{\r\n if ( conn )\r\n {\r\n fd_event_queue.detachSocket( conn->getSocket(), conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n throw exc_ev;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <cassert>\n#include <cstdlib>\n#include <iostream>\n#include \"World.H\"\n#include \"Unit.H\"\n\n\/\/May not need this inclusion\n#include \"World2.C\"\n\n\nusing namespace std;\n\n\/* helper that you need to implement\n \n - move unit by current_speed * heading\n\n - units only collide with the map border\n \n - when units hit a wall they stop at the collision point (current_speed=0)\n and collision_hook is called with the previous speed and a vector of bools\n encoding the walls that were hit. This vector is used in collision_hook to\n implement bouncing by only changing the unit's heading, i.e. even when\n bouncing the unit stays at the collision location for the remainder of the\n simulation frame and only starts moving again in the following frame.\n\n - it is essential that units are located inside the map at all times. There\n can be no overlap. Ensure this property by clipping coordinates after\n moving.\n\n*\/\n\nvoid World::move_unit(Unit &u)\n{\n \/\/Take unit speed multiply by heading to get new position\n double futureX = u.pos.x + (u.current_speed*u.heading.x);\n double futureY = u.pos.y + (u.current_speed*u.heading.y); \n \/\/Extra space to leave for a collision. Compensates for rounding errors.\n double buffer = 0.1; \n \/\/Collision occured flag\n bool collision = false;\n bool collisions[4] = {false, false, false, false};\n \/\/double prev_speed = u.current_speed;\n\n \/\/Check to see if movement would result in a collision\n if(futureX+u.radius+buffer >= width) {\n \/\/Collision with Right wall\n futureX = width - u.radius - buffer;\n collision = true;\n collisions[1] = true;\n }\n if(futureX-u.radius-buffer <= 0) {\n \/\/Collision with Left wall\n futureX = u.radius + buffer;\n collision = true;\n collisions[3] = true;\n }\n if(futureY+u.radius+buffer >= height) {\n \/\/Collision with Bottom wall\n futureX = height - u.radius - buffer;\n collision = true;\n collisions[2] = true;\n }\n if(futureY-u.radius-buffer >= 0) {\n \/\/Collision with Top wall\n futureX = u.radius + buffer;\n collision = true; \n collisions[0] = true; \n }\n\n if(collision) {\n u.collision_hook(u.current_speed, collisions);\n u.current_speed = 0;\n } \n\n \/\/Update unit's position to new position\n u.pos = Vec2(futureX, futureY);\n\n}\n\n\n\/\/ returns policy name\nconst char *apol2str(AttackPolicy pol)\n{\n switch (pol) {\n case ATTACK_WEAKEST:\n return \"attack-weakest\";\n case ATTACK_CLOSEST:\n return \"attack-closest\";\n case ATTACK_MOST_DANGEROUS:\n return \"attack-most-dangerous\";\n }\n return \"?\";\n}\n\n\nWorld::~World()\n{\n \/\/ clean up\n \n \/\/ ... implement\n}\n\n\n\/\/ deducts hit points and calls attack_hook\n\nvoid World::attack(Unit &attacker, Unit &attacked)\n{\n \/\/Reduce attacked unit's health by attack strength of attacker\n attacked.hp -= (int)attacker.damage;\n\n \/\/Remove dead is handled by step in World2.C\n}\n\n\/\/ return a random position at which a circle of that radius fits\n\nVec2 World::rnd_pos(double radius) const\n{\n double slack = radius * 2;\n\n Vec2 p((width - 2*slack) * rnd01() + slack,\n (height - 2*slack) * rnd01() + slack);\n \n \/\/ assert circle in rectangle\n assert(p.x > radius && p.x < width - radius);\n assert(p.y > radius && p.y < height - radius);\n return p;\n}\n\n\n\/\/ return uniform random heading\n\/\/ length of vector = 1\nVec2 World::rnd_heading() const\n{\n \/\/ Generate random value between (0 and 2)*pi\n \/\/ This should preserve a uniform distribution as the 2*rnd01 \n \/\/ transforms from an infinite set of points\n double angle = (this->rnd01())*2; \n\n \/\/ create Vec2 object with x = cos(angle), y = sin(angle)\n return Vec2(cos(angle), sin(angle));\n}\n\n\/\/ mirror position with respect to map mid-point\nVec2 World::mirror(const Vec2 &pos) const\n{\n \/\/Create Mid-point coordinates\n double midX = width\/2;\n double midY = height\/2;\n double newX;\n double newY;\n double diff;\n\n \/\/Set new coordinate to position same distance from midpoint \n \/\/but on the other side of said midpoint\n if(pos.x >= midX) {\n diff = pos.x - midX;\n newX = midX - diff;\n } else {\n diff = midX - pos.x;\n newX = midX + diff;\n }\n if(pos.y >= midY){\n diff = pos.y - midY;\n newY = midY - diff;\n } else {\n diff = midY - pos.y;\n newY = midY + diff;\n }\n\n \/\/Create vector with new values and return it\n return Vec2(newX, newY);\n}\n\n\n\/\/ return squared distance between two unit centers\ndouble World::distance2(const Unit &u, const Unit &v)\n{\n return pow((v.pos.x - u.pos.x), 2) + pow((v.pos.y - u.pos.y), 2);\n}\n\n\/\/ return true iff u can attack v, i.e. distance of u's and v's centers is\n\/\/ less than u's attack distance plus v's radius\nbool World::can_attack(const Unit &u, const Unit &v)\n{\n double dist = sqrt(distance2(u, v));\n\n if(dist <= u.attack_radius + v.radius){\n return true;\n } else {\n return false; \n }\n}\n\n\/\/ populate a vector with enemy units that can be attacked by u;\n\/\/ clears vector first\nvoid World::enemies_within_attack_range(const Unit &u,\n vector<Unit*> &targets) const\n{\n targets.clear();\n\n \/\/Append all units to vector \n for(auto &unit : units) {\n if(can_attack(u, *unit)) {\n if(unit->team != u.team){\n targets.push_back(unit);\n }\n }\n }\n}\n\n\/\/ return a random unit that can be attacked by u with minimal hp_old value,\n\/\/ or 0 if none exists\nUnit *World::random_weakest_target(Unit &u) const\n{\n \/\/Create list of possible targets\n vector<Unit*> targets;\n enemies_within_attack_range(u, targets);\n\n \/\/If there are no available targets\n if(targets.size() ==0) {return 0;}\n\n \/\/Search for unit with lowest hp\n Unit * lowest = targets[0];\n for(auto &unit: targets) {\n if(unit->hp < lowest->hp){\n lowest = unit;\n }\n }\n\n return lowest;\n}\n\n\n\/\/ return a random unit that can be attacked by u with minimal distance to\n\/\/ u, or 0 if none exists\n\nUnit *World::random_closest_target(Unit &u) const\n{\n \/\/Create list of possible targets\n vector<Unit*> targets;\n enemies_within_attack_range(u, targets);\n\n \/\/If there are no available targets\n if(targets.size() == 0) {return 0;}\n\n \/\/Search for unit with lowest distance\n Unit * closest = targets[0];\n for(auto &unit: targets) {\n if(distance2(u, *unit) < distance2(u, *closest)){\n closest = unit;\n }\n }\n\n return closest;\n}\n\n\/\/ return a random unit that can be attacked by u with maximal damage\/hp_old\n\/\/ ratio, or 0 if none exists\nUnit *World::random_most_dangerous_target(Unit &u) const\n{\n \/\/Create list of possible targets\n vector<Unit*> targets;\n enemies_within_attack_range(u, targets);\n\n \/\/If there are no available targets\n if(targets.size() ==0) {return 0;}\n\n \/\/Search for unit with highest damage\n Unit * baddest = targets[0];\n for(auto &unit: targets) {\n if(unit->damage < baddest->damage){\n baddest = unit;\n }\n }\n\n return baddest;\n}\n\n\n\/\/ return score for red: 2 for win, 0 for loss, 1 for draw, -1 for game not\n\/\/ over yet\nint World::red_score() const\n{\n \/\/Flags for if red or blue units still exist\n bool red = false;\n bool blue = false;\n\n if (units.empty()) {\n return 1;\n }\n \n \/\/Check all remaining units for team affiliations\n for(auto &unit : units){\n if(unit->team == Team::BLUE){\n blue = true;\n }\n if(unit->team == Team::RED){\n red = true;\n }\n \/\/If there are at least one unit of each team game continues\n if(red && blue){return -1;} \n }\n \n \/\/If in all the remaining units, none are red loss\n if(!red) {\n return 0;\n } else {\n return 2; \/\/Otherwise return win!\n }\n\n\n}\n\n<commit_msg>Removed extra include of World2.C<commit_after>#include <cmath>\n#include <cassert>\n#include <cstdlib>\n#include <iostream>\n#include \"World.H\"\n#include \"Unit.H\"\n\nusing namespace std;\n\n\/* helper that you need to implement\n \n - move unit by current_speed * heading\n\n - units only collide with the map border\n \n - when units hit a wall they stop at the collision point (current_speed=0)\n and collision_hook is called with the previous speed and a vector of bools\n encoding the walls that were hit. This vector is used in collision_hook to\n implement bouncing by only changing the unit's heading, i.e. even when\n bouncing the unit stays at the collision location for the remainder of the\n simulation frame and only starts moving again in the following frame.\n\n - it is essential that units are located inside the map at all times. There\n can be no overlap. Ensure this property by clipping coordinates after\n moving.\n\n*\/\n\nvoid World::move_unit(Unit &u)\n{\n \/\/Take unit speed multiply by heading to get new position\n double futureX = u.pos.x + (u.current_speed*u.heading.x);\n double futureY = u.pos.y + (u.current_speed*u.heading.y); \n \/\/Extra space to leave for a collision. Compensates for rounding errors.\n double buffer = 0.1; \n \/\/Collision occured flag\n bool collision = false;\n bool collisions[4] = {false, false, false, false};\n \/\/double prev_speed = u.current_speed;\n\n \/\/Check to see if movement would result in a collision\n if(futureX+u.radius+buffer >= width) {\n \/\/Collision with Right wall\n futureX = width - u.radius - buffer;\n collision = true;\n collisions[1] = true;\n }\n if(futureX-u.radius-buffer <= 0) {\n \/\/Collision with Left wall\n futureX = u.radius + buffer;\n collision = true;\n collisions[3] = true;\n }\n if(futureY+u.radius+buffer >= height) {\n \/\/Collision with Bottom wall\n futureX = height - u.radius - buffer;\n collision = true;\n collisions[2] = true;\n }\n if(futureY-u.radius-buffer >= 0) {\n \/\/Collision with Top wall\n futureX = u.radius + buffer;\n collision = true; \n collisions[0] = true; \n }\n\n if(collision) {\n u.collision_hook(u.current_speed, collisions);\n u.current_speed = 0;\n } \n\n \/\/Update unit's position to new position\n u.pos = Vec2(futureX, futureY);\n\n}\n\n\n\/\/ returns policy name\nconst char *apol2str(AttackPolicy pol)\n{\n switch (pol) {\n case ATTACK_WEAKEST:\n return \"attack-weakest\";\n case ATTACK_CLOSEST:\n return \"attack-closest\";\n case ATTACK_MOST_DANGEROUS:\n return \"attack-most-dangerous\";\n }\n return \"?\";\n}\n\n\nWorld::~World()\n{\n \/\/ clean up\n \n \/\/ ... implement\n}\n\n\n\/\/ deducts hit points and calls attack_hook\n\nvoid World::attack(Unit &attacker, Unit &attacked)\n{\n \/\/Reduce attacked unit's health by attack strength of attacker\n attacked.hp -= (int)attacker.damage;\n\n \/\/Remove dead is handled by step in World2.C\n}\n\n\/\/ return a random position at which a circle of that radius fits\n\nVec2 World::rnd_pos(double radius) const\n{\n double slack = radius * 2;\n\n Vec2 p((width - 2*slack) * rnd01() + slack,\n (height - 2*slack) * rnd01() + slack);\n \n \/\/ assert circle in rectangle\n assert(p.x > radius && p.x < width - radius);\n assert(p.y > radius && p.y < height - radius);\n return p;\n}\n\n\n\/\/ return uniform random heading\n\/\/ length of vector = 1\nVec2 World::rnd_heading() const\n{\n \/\/ Generate random value between (0 and 2)*pi\n \/\/ This should preserve a uniform distribution as the 2*rnd01 \n \/\/ transforms from an infinite set of points\n double angle = (this->rnd01())*2; \n\n \/\/ create Vec2 object with x = cos(angle), y = sin(angle)\n return Vec2(cos(angle), sin(angle));\n}\n\n\/\/ mirror position with respect to map mid-point\nVec2 World::mirror(const Vec2 &pos) const\n{\n \/\/Create Mid-point coordinates\n double midX = width\/2;\n double midY = height\/2;\n double newX;\n double newY;\n double diff;\n\n \/\/Set new coordinate to position same distance from midpoint \n \/\/but on the other side of said midpoint\n if(pos.x >= midX) {\n diff = pos.x - midX;\n newX = midX - diff;\n } else {\n diff = midX - pos.x;\n newX = midX + diff;\n }\n if(pos.y >= midY){\n diff = pos.y - midY;\n newY = midY - diff;\n } else {\n diff = midY - pos.y;\n newY = midY + diff;\n }\n\n \/\/Create vector with new values and return it\n return Vec2(newX, newY);\n}\n\n\n\/\/ return squared distance between two unit centers\ndouble World::distance2(const Unit &u, const Unit &v)\n{\n return pow((v.pos.x - u.pos.x), 2) + pow((v.pos.y - u.pos.y), 2);\n}\n\n\/\/ return true iff u can attack v, i.e. distance of u's and v's centers is\n\/\/ less than u's attack distance plus v's radius\nbool World::can_attack(const Unit &u, const Unit &v)\n{\n double dist = sqrt(distance2(u, v));\n\n if(dist <= u.attack_radius + v.radius){\n return true;\n } else {\n return false; \n }\n}\n\n\/\/ populate a vector with enemy units that can be attacked by u;\n\/\/ clears vector first\nvoid World::enemies_within_attack_range(const Unit &u,\n vector<Unit*> &targets) const\n{\n targets.clear();\n\n \/\/Append all units to vector \n for(auto &unit : units) {\n if(can_attack(u, *unit)) {\n if(unit->team != u.team){\n targets.push_back(unit);\n }\n }\n }\n}\n\n\/\/ return a random unit that can be attacked by u with minimal hp_old value,\n\/\/ or 0 if none exists\nUnit *World::random_weakest_target(Unit &u) const\n{\n \/\/Create list of possible targets\n vector<Unit*> targets;\n enemies_within_attack_range(u, targets);\n\n \/\/If there are no available targets\n if(targets.size() ==0) {return 0;}\n\n \/\/Search for unit with lowest hp\n Unit * lowest = targets[0];\n for(auto &unit: targets) {\n if(unit->hp < lowest->hp){\n lowest = unit;\n }\n }\n\n return lowest;\n}\n\n\n\/\/ return a random unit that can be attacked by u with minimal distance to\n\/\/ u, or 0 if none exists\n\nUnit *World::random_closest_target(Unit &u) const\n{\n \/\/Create list of possible targets\n vector<Unit*> targets;\n enemies_within_attack_range(u, targets);\n\n \/\/If there are no available targets\n if(targets.size() == 0) {return 0;}\n\n \/\/Search for unit with lowest distance\n Unit * closest = targets[0];\n for(auto &unit: targets) {\n if(distance2(u, *unit) < distance2(u, *closest)){\n closest = unit;\n }\n }\n\n return closest;\n}\n\n\/\/ return a random unit that can be attacked by u with maximal damage\/hp_old\n\/\/ ratio, or 0 if none exists\nUnit *World::random_most_dangerous_target(Unit &u) const\n{\n \/\/Create list of possible targets\n vector<Unit*> targets;\n enemies_within_attack_range(u, targets);\n\n \/\/If there are no available targets\n if(targets.size() ==0) {return 0;}\n\n \/\/Search for unit with highest damage\n Unit * baddest = targets[0];\n for(auto &unit: targets) {\n if(unit->damage < baddest->damage){\n baddest = unit;\n }\n }\n\n return baddest;\n}\n\n\n\/\/ return score for red: 2 for win, 0 for loss, 1 for draw, -1 for game not\n\/\/ over yet\nint World::red_score() const\n{\n \/\/Flags for if red or blue units still exist\n bool red = false;\n bool blue = false;\n\n if (units.empty()) {\n return 1;\n }\n \n \/\/Check all remaining units for team affiliations\n for(auto &unit : units){\n if(unit->team == Team::BLUE){\n blue = true;\n }\n if(unit->team == Team::RED){\n red = true;\n }\n \/\/If there are at least one unit of each team game continues\n if(red && blue){return -1;} \n }\n \n \/\/If in all the remaining units, none are red loss\n if(!red) {\n return 0;\n } else {\n return 2; \/\/Otherwise return win!\n }\n\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: DbAdminImpl.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2005-03-10 16:48:36 $\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 EXPRESS 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): Ocke Janssen\n *\n *\n ************************************************************************\/\n\n#ifndef _DBAUI_DBADMINIMPL_HXX_\n#define _DBAUI_DBADMINIMPL_HXX_\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XNAMINGSERVICE_HPP_\n#include <com\/sun\/star\/uno\/XNamingService.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_\n#include <com\/sun\/star\/sdbc\/XConnection.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_\n#include <com\/sun\/star\/sdbc\/XDriver.hpp>\n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n#ifndef _DBAUI_DSNTYPES_HXX_\n#include \"dsntypes.hxx\"\n#endif\n#ifndef _SFXITEMSET_HXX\n#include <svtools\/itemset.hxx>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#endif\n\nclass Window;\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n class IItemSetHelper;\n \/\/========================================================================\n \/\/= ODbDataSourceAdministrationHelper\n \/\/========================================================================\n class ODbDataSourceAdministrationHelper\n {\n public:\n DECLARE_STL_MAP(sal_Int32, ::rtl::OUString, ::std::less< sal_Int32 >, MapInt2String);\n\n private:\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n m_xORB; \/\/\/ service factory\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >\n m_xDatabaseContext; \/\/\/ database context we're working in\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XNamingService >\n m_xDynamicContext; \/\/\/ just another interface of the context ...\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xDatasource;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > m_xModel;\n\n ::com::sun::star::uno::Any m_aDataSourceName;\n typedef ::std::set< ::rtl::OUString > StringSet;\n typedef StringSet::const_iterator ConstStringSetIterator;\n\n\n MapInt2String m_aDirectPropTranslator; \/\/\/ translating property id's into names (direct properties of a data source)\n MapInt2String m_aIndirectPropTranslator; \/\/\/ translating property id's into names (indirect properties of a data source)\n Window* m_pParent;\n IItemSetHelper* m_pItemSetHelper;\n public:\n\n ODbDataSourceAdministrationHelper(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB\n ,Window* _pParent\n ,IItemSetHelper* _pItemSetHelper);\n\n \/** translate the current dialog SfxItems into driver relevant PropertyValues\n @see successfullyConnected\n *\/\n sal_Bool getCurrentSettings(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDriverParams);\n\n \/** to be called if the settings got from getCurrentSettings have been used for successfully connecting\n @see getCurrentSettings\n *\/\n void successfullyConnected();\n\n \/\/\/ clear the password in the current data source's item set\n void clearPassword();\n\n inline ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const { return m_xORB; }\n\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > getDatabaseContext() const { return m_xDatabaseContext; }\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XNamingService > getDynamicContext() const { return m_xDynamicContext; }\n\n \/** creates a new connection. The caller is responsible to dispose it !!!!\n *\/\n ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection();\n\n \/** return the corresponding driver for the selected URL\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver();\n\n \/** returns the data source the dialog is currently working with\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getCurrentDataSource();\n\n \/\/ returns the Url of a database document\n String getDocumentUrl(SfxItemSet& _rDest);\n\n\n\n void setCurrentDataSourceName(const ::com::sun::star::uno::Any& _aDataSourceName);\n\n \/** extracts the connection type from the given set<p\/>\n The connection type is determined by the value of the DSN item, analyzed by the TypeCollection item.\n *\/\n DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const;\n\n \/** returns the connection URL\n @return\n The connection URL\n *\/\n String getConnectionURL() const;\n\n \/\/\/ fill the nescessary information from the url line\n void convertUrl(SfxItemSet& _rDest);\n\n const MapInt2String& getIndirectProperties() const { return m_aIndirectPropTranslator; }\n\n \/** translates properties of an UNO data source into SfxItems\n @param _rxSource\n The data source\n @param _rDest\n The item set to fill.\n *\/\n void translateProperties(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxSource,\n SfxItemSet& _rDest);\n\n \/** translate SfxItems into properties of an UNO data source\n @param _rSource\n The item set to read from.\n @param _rxDest\n The data source to fill.\n *\/\n void translateProperties(\n const SfxItemSet& _rSource,\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDest);\n\n sal_Bool saveChanges(const SfxItemSet& _rSource);\n protected:\n \/** fill a data source info array with the settings from a given item set\n *\/\n void fillDatasourceInfo(const SfxItemSet& _rSource, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo);\n\n \/\/\/ translate the given value into an SfxPoolItem, put this into the given set under the given id\n void implTranslateProperty(SfxItemSet& _rSet, sal_Int32 _nId, const ::com::sun::star::uno::Any& _rValue);\n\n \/\/\/ translate the given SfxPoolItem into an <type scope=\"com.sun.star.Any\">uno<\/type>\n ::com::sun::star::uno::Any implTranslateProperty(const SfxPoolItem* _pItem);\n\n \/\/\/ translate the given SfxPoolItem into an <type scope=\"com.sun.star.Any\">uno<\/type>, set it (under the given name) on the given property set\n void implTranslateProperty(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxSet, const ::rtl::OUString& _rName, const SfxPoolItem* _pItem);\n\n \/** check if the data source described by the given set needs authentication<p\/>\n The return value depends on the data source type only.\n *\/\n sal_Bool hasAuthentication(const SfxItemSet& _rSet) const;\n\n#ifdef DBG_UTIL\n ::rtl::OString translatePropertyId( sal_Int32 _nId );\n#endif\n };\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n#endif \/\/ _DBAUI_DBADMINIMPL_HXX_\n\n<commit_msg>INTEGRATION: CWS wizopendb (1.5.48); FILE MERGED 2005\/06\/06 10:40:39 fs 1.5.48.1: #i42477# allow the 'New Database' wizard to load existing documents<commit_after>\/*************************************************************************\n *\n * $RCSfile: DbAdminImpl.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2005-06-30 16:30:58 $\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 EXPRESS 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): Ocke Janssen\n *\n *\n ************************************************************************\/\n\n#ifndef _DBAUI_DBADMINIMPL_HXX_\n#define _DBAUI_DBADMINIMPL_HXX_\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XNAMINGSERVICE_HPP_\n#include <com\/sun\/star\/uno\/XNamingService.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_\n#include <com\/sun\/star\/sdbc\/XConnection.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_\n#include <com\/sun\/star\/sdbc\/XDriver.hpp>\n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n#ifndef _DBAUI_DSNTYPES_HXX_\n#include \"dsntypes.hxx\"\n#endif\n#ifndef _SFXITEMSET_HXX\n#include <svtools\/itemset.hxx>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#endif\n\nclass Window;\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n class IItemSetHelper;\n \/\/========================================================================\n \/\/= ODbDataSourceAdministrationHelper\n \/\/========================================================================\n class ODbDataSourceAdministrationHelper\n {\n public:\n DECLARE_STL_MAP(sal_Int32, ::rtl::OUString, ::std::less< sal_Int32 >, MapInt2String);\n\n private:\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n m_xORB; \/\/\/ service factory\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >\n m_xDatabaseContext; \/\/\/ database context we're working in\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XNamingService >\n m_xDynamicContext; \/\/\/ just another interface of the context ...\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xDatasource;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > m_xModel;\n\n ::com::sun::star::uno::Any m_aDataSourceOrName;\n typedef ::std::set< ::rtl::OUString > StringSet;\n typedef StringSet::const_iterator ConstStringSetIterator;\n\n\n MapInt2String m_aDirectPropTranslator; \/\/\/ translating property id's into names (direct properties of a data source)\n MapInt2String m_aIndirectPropTranslator; \/\/\/ translating property id's into names (indirect properties of a data source)\n Window* m_pParent;\n IItemSetHelper* m_pItemSetHelper;\n public:\n\n ODbDataSourceAdministrationHelper(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB\n ,Window* _pParent\n ,IItemSetHelper* _pItemSetHelper);\n\n \/** translate the current dialog SfxItems into driver relevant PropertyValues\n @see successfullyConnected\n *\/\n sal_Bool getCurrentSettings(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDriverParams);\n\n \/** to be called if the settings got from getCurrentSettings have been used for successfully connecting\n @see getCurrentSettings\n *\/\n void successfullyConnected();\n\n \/\/\/ clear the password in the current data source's item set\n void clearPassword();\n\n inline ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const { return m_xORB; }\n\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > getDatabaseContext() const { return m_xDatabaseContext; }\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XNamingService > getDynamicContext() const { return m_xDynamicContext; }\n\n \/** creates a new connection. The caller is responsible to dispose it !!!!\n *\/\n ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection();\n\n \/** return the corresponding driver for the selected URL\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver();\n\n \/** returns the data source the dialog is currently working with\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getCurrentDataSource();\n \/** returs the model we're currently working with\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > getCurrentModel();\n\n \/\/ returns the Url of a database document\n String getDocumentUrl(SfxItemSet& _rDest);\n\n void setDataSourceOrName( const ::com::sun::star::uno::Any& _rDataSourceOrName );\n\n \/** extracts the connection type from the given set<p\/>\n The connection type is determined by the value of the DSN item, analyzed by the TypeCollection item.\n *\/\n DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const;\n\n \/** returns the connection URL\n @return\n The connection URL\n *\/\n String getConnectionURL() const;\n\n \/\/\/ fill the nescessary information from the url line\n void convertUrl(SfxItemSet& _rDest);\n\n const MapInt2String& getIndirectProperties() const { return m_aIndirectPropTranslator; }\n\n \/** translates properties of an UNO data source into SfxItems\n @param _rxSource\n The data source\n @param _rDest\n The item set to fill.\n *\/\n void translateProperties(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxSource,\n SfxItemSet& _rDest);\n\n \/** translate SfxItems into properties of an UNO data source\n @param _rSource\n The item set to read from.\n @param _rxDest\n The data source to fill.\n *\/\n void translateProperties(\n const SfxItemSet& _rSource,\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDest);\n\n sal_Bool saveChanges(const SfxItemSet& _rSource);\n protected:\n \/** fill a data source info array with the settings from a given item set\n *\/\n void fillDatasourceInfo(const SfxItemSet& _rSource, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo);\n\n \/\/\/ translate the given value into an SfxPoolItem, put this into the given set under the given id\n void implTranslateProperty(SfxItemSet& _rSet, sal_Int32 _nId, const ::com::sun::star::uno::Any& _rValue);\n\n \/\/\/ translate the given SfxPoolItem into an <type scope=\"com.sun.star.Any\">uno<\/type>\n ::com::sun::star::uno::Any implTranslateProperty(const SfxPoolItem* _pItem);\n\n \/\/\/ translate the given SfxPoolItem into an <type scope=\"com.sun.star.Any\">uno<\/type>, set it (under the given name) on the given property set\n void implTranslateProperty(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxSet, const ::rtl::OUString& _rName, const SfxPoolItem* _pItem);\n\n \/** check if the data source described by the given set needs authentication<p\/>\n The return value depends on the data source type only.\n *\/\n sal_Bool hasAuthentication(const SfxItemSet& _rSet) const;\n\n#ifdef DBG_UTIL\n ::rtl::OString translatePropertyId( sal_Int32 _nId );\n#endif\n };\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n#endif \/\/ _DBAUI_DBADMINIMPL_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: GeneralUndo.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2007-07-06 08:22:49 $\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 DBAUI_GENERALUNDO_HXX\n#define DBAUI_GENERALUNDO_HXX\n\n#ifndef _UNDO_HXX\n#include <svtools\/undo.hxx>\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n\nnamespace dbaui\n{\n \/\/ ================================================================================================\n \/\/ SbaCommentUndoAction - Undo-Basisklasse fuer Aktionen, deren GetComment einen aus einer Sba-Ressource\n \/\/ geladenen String liefert\n\n class OCommentUndoAction : public SfxUndoAction\n {\n OModuleClient m_aModuleClient;\n\n protected:\n String m_strComment; \/\/ undo, redo comment\n\n public:\n TYPEINFO();\n OCommentUndoAction(USHORT nCommentID) { m_strComment = String(ModuleRes(nCommentID)); }\n\n virtual UniString GetComment() const { return m_strComment; }\n };\n}\n#endif \/\/ DBAUI_GENERALUNDO_HXX\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.162); FILE MERGED 2008\/03\/31 13:27:42 rt 1.5.162.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: GeneralUndo.hxx,v $\n * $Revision: 1.6 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef DBAUI_GENERALUNDO_HXX\n#define DBAUI_GENERALUNDO_HXX\n\n#ifndef _UNDO_HXX\n#include <svtools\/undo.hxx>\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n\nnamespace dbaui\n{\n \/\/ ================================================================================================\n \/\/ SbaCommentUndoAction - Undo-Basisklasse fuer Aktionen, deren GetComment einen aus einer Sba-Ressource\n \/\/ geladenen String liefert\n\n class OCommentUndoAction : public SfxUndoAction\n {\n OModuleClient m_aModuleClient;\n\n protected:\n String m_strComment; \/\/ undo, redo comment\n\n public:\n TYPEINFO();\n OCommentUndoAction(USHORT nCommentID) { m_strComment = String(ModuleRes(nCommentID)); }\n\n virtual UniString GetComment() const { return m_strComment; }\n };\n}\n#endif \/\/ DBAUI_GENERALUNDO_HXX\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: TokenWriter.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: oj $ $Date: 2001-03-27 06:57:57 $\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#ifndef DBAUI_TOKENWRITER_HXX\n#define DBAUI_TOKENWRITER_HXX\n\n#ifndef DBAUI_DATABASEEXPORT_HXX\n#include \"DExport.hxx\"\n#endif\n#ifndef _STREAM_HXX \/\/autogen\n#include <tools\/stream.hxx>\n#endif\n#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_\n#include <com\/sun\/star\/awt\/FontDescriptor.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_\n#include <com\/sun\/star\/sdb\/CommandType.hpp>\n#endif\n\nnamespace dbaui\n{\n \/\/ =========================================================================\n \/\/ ODatabaseImportExport Basisklasse f\"ur Import\/Export\n \/\/ =========================================================================\n class ODatabaseExport;\n class ODatabaseImportExport : public ::cppu::WeakImplHelper1< ::com::sun::star::lang::XEventListener>\n {\n void disposing();\n protected:\n SvStream* m_pStream;\n ::com::sun::star::awt::FontDescriptor m_aFont;\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xObject; \/\/ table\/query\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection; \/\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > m_xResultSet; \/\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow > m_xRow; \/\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > m_xResultSetMetaData; \/\/\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; \/\/ a number formatter working with the connection's NumberFormatsSupplier\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xFactory;\n\n ::rtl::OUString m_sName;\n ::rtl::OUString m_sDataSourceName;\n sal_Int32 m_nCommandType;\n sal_Bool m_bDisposeConnection;\n\n#if defined UNX || defined MAC\n static const char __FAR_DATA sNewLine;\n#else\n static const char __FAR_DATA sNewLine[];\n#endif\n ODatabaseExport* m_pReader;\n sal_Int32* m_pRowMarker; \/\/ wenn gesetzt, dann nur diese Rows kopieren\n\n \/\/ export data\n ODatabaseImportExport( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _aSeq,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const String& rExchange = String());\n\n \/\/ import data\n ODatabaseImportExport( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM)\n :m_xConnection(_rxConnection)\n ,m_pReader(NULL)\n ,m_pRowMarker(NULL)\n ,m_xFormatter(_rxNumberF)\n ,m_xFactory(_rM)\n ,m_nCommandType(::com::sun::star::sdb::CommandType::TABLE)\n ,m_bDisposeConnection(sal_False)\n {}\n\n virtual ~ODatabaseImportExport();\n public:\n void setStream(SvStream* _pStream){ m_pStream = _pStream; }\n\n virtual BOOL Write() = 0; \/\/ Export\n virtual BOOL Read() = 0; \/\/ Import\n\n void initialize();;\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n };\n\n \/\/ =========================================================================\n \/\/ RTF Im- und Export\n \/\/ =========================================================================\n\n class ORTFImportExport : public ODatabaseImportExport\n {\n\n public:\n \/\/ export data\n ORTFImportExport( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _aSeq,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const String& rExchange = String())\n : ODatabaseImportExport(_aSeq,_rM,_rxNumberF,rExchange) {};\n\n \/\/ import data\n ORTFImportExport( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM)\n : ODatabaseImportExport(_rxConnection,_rxNumberF,_rM)\n {}\n\n virtual BOOL Write();\n virtual BOOL Read();\n };\n \/\/ =========================================================================\n \/\/ HTML Im- und Export\n \/\/ =========================================================================\n #define SBA_HTML_FONTSIZES 7\n const sal_Int16 nIndentMax = 23;\n class OHTMLImportExport : public ODatabaseImportExport\n {\n \/\/ default HtmlFontSz[1-7]\n static const sal_Int16 nDefaultFontSize[SBA_HTML_FONTSIZES];\n \/\/ HtmlFontSz[1-7] in s*3.ini [user]\n static sal_Int16 nFontSize[SBA_HTML_FONTSIZES];\n static const sal_Int16 nCellSpacing;\n static const char __FAR_DATA sIndentSource[];\n char sIndent[nIndentMax+1];\n sal_Int16 m_nIndent;\n #if DBG_UTIL\n BOOL m_bCheckFont;\n #endif\n\n void WriteHeader();\n void WriteBody();\n void WriteTables();\n void WriteCell( sal_Int32 nFormat,sal_Int32 nWidthPixel,sal_Int32 nHeightPixel,const char* pChar,const String& rValue,const char* pHtmlTag);\n void IncIndent( sal_Int16 nVal );\n const char* GetIndentStr() { return sIndent; }\n void FontOn();\n inline void FontOff();\n\n public:\n \/\/ export data\n OHTMLImportExport( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _aSeq,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const String& rExchange = String());\n \/\/ import data\n OHTMLImportExport( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM)\n : ODatabaseImportExport(_rxConnection,_rxNumberF,_rM)\n {}\n\n virtual BOOL Write();\n virtual BOOL Read();\n\n };\n\n}\n#endif \/\/ DBAUI_TOKENWRITER_HXX\n\n\n\n<commit_msg>Removed extra semicolon<commit_after>\/*************************************************************************\n *\n * $RCSfile: TokenWriter.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2001-03-30 12:08:44 $\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#ifndef DBAUI_TOKENWRITER_HXX\n#define DBAUI_TOKENWRITER_HXX\n\n#ifndef DBAUI_DATABASEEXPORT_HXX\n#include \"DExport.hxx\"\n#endif\n#ifndef _STREAM_HXX \/\/autogen\n#include <tools\/stream.hxx>\n#endif\n#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_\n#include <com\/sun\/star\/awt\/FontDescriptor.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_\n#include <com\/sun\/star\/sdb\/CommandType.hpp>\n#endif\n\nnamespace dbaui\n{\n \/\/ =========================================================================\n \/\/ ODatabaseImportExport Basisklasse f\"ur Import\/Export\n \/\/ =========================================================================\n class ODatabaseExport;\n class ODatabaseImportExport : public ::cppu::WeakImplHelper1< ::com::sun::star::lang::XEventListener>\n {\n void disposing();\n protected:\n SvStream* m_pStream;\n ::com::sun::star::awt::FontDescriptor m_aFont;\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xObject; \/\/ table\/query\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection; \/\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > m_xResultSet; \/\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow > m_xRow; \/\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > m_xResultSetMetaData; \/\/\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; \/\/ a number formatter working with the connection's NumberFormatsSupplier\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xFactory;\n\n ::rtl::OUString m_sName;\n ::rtl::OUString m_sDataSourceName;\n sal_Int32 m_nCommandType;\n sal_Bool m_bDisposeConnection;\n\n#if defined UNX || defined MAC\n static const char __FAR_DATA sNewLine;\n#else\n static const char __FAR_DATA sNewLine[];\n#endif\n ODatabaseExport* m_pReader;\n sal_Int32* m_pRowMarker; \/\/ wenn gesetzt, dann nur diese Rows kopieren\n\n \/\/ export data\n ODatabaseImportExport( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _aSeq,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const String& rExchange = String());\n\n \/\/ import data\n ODatabaseImportExport( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM)\n :m_xConnection(_rxConnection)\n ,m_pReader(NULL)\n ,m_pRowMarker(NULL)\n ,m_xFormatter(_rxNumberF)\n ,m_xFactory(_rM)\n ,m_nCommandType(::com::sun::star::sdb::CommandType::TABLE)\n ,m_bDisposeConnection(sal_False)\n {}\n\n virtual ~ODatabaseImportExport();\n public:\n void setStream(SvStream* _pStream){ m_pStream = _pStream; }\n\n virtual BOOL Write() = 0; \/\/ Export\n virtual BOOL Read() = 0; \/\/ Import\n\n void initialize();\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n };\n\n \/\/ =========================================================================\n \/\/ RTF Im- und Export\n \/\/ =========================================================================\n\n class ORTFImportExport : public ODatabaseImportExport\n {\n\n public:\n \/\/ export data\n ORTFImportExport( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _aSeq,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const String& rExchange = String())\n : ODatabaseImportExport(_aSeq,_rM,_rxNumberF,rExchange) {};\n\n \/\/ import data\n ORTFImportExport( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM)\n : ODatabaseImportExport(_rxConnection,_rxNumberF,_rM)\n {}\n\n virtual BOOL Write();\n virtual BOOL Read();\n };\n \/\/ =========================================================================\n \/\/ HTML Im- und Export\n \/\/ =========================================================================\n #define SBA_HTML_FONTSIZES 7\n const sal_Int16 nIndentMax = 23;\n class OHTMLImportExport : public ODatabaseImportExport\n {\n \/\/ default HtmlFontSz[1-7]\n static const sal_Int16 nDefaultFontSize[SBA_HTML_FONTSIZES];\n \/\/ HtmlFontSz[1-7] in s*3.ini [user]\n static sal_Int16 nFontSize[SBA_HTML_FONTSIZES];\n static const sal_Int16 nCellSpacing;\n static const char __FAR_DATA sIndentSource[];\n char sIndent[nIndentMax+1];\n sal_Int16 m_nIndent;\n #if DBG_UTIL\n BOOL m_bCheckFont;\n #endif\n\n void WriteHeader();\n void WriteBody();\n void WriteTables();\n void WriteCell( sal_Int32 nFormat,sal_Int32 nWidthPixel,sal_Int32 nHeightPixel,const char* pChar,const String& rValue,const char* pHtmlTag);\n void IncIndent( sal_Int16 nVal );\n const char* GetIndentStr() { return sIndent; }\n void FontOn();\n inline void FontOff();\n\n public:\n \/\/ export data\n OHTMLImportExport( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _aSeq,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const String& rExchange = String());\n \/\/ import data\n OHTMLImportExport( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM)\n : ODatabaseImportExport(_rxConnection,_rxNumberF,_rM)\n {}\n\n virtual BOOL Write();\n virtual BOOL Read();\n\n };\n\n}\n#endif \/\/ DBAUI_TOKENWRITER_HXX\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/ Copyright (c) 2021 by ApexAI Inc. All rights reserved.\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\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"iceoryx_utils\/cxx\/deadline_timer.hpp\"\n#include \"iceoryx_utils\/internal\/posix_wrapper\/mutex.hpp\"\n#include \"test.hpp\"\n\n#include <atomic>\n#include <thread>\n\nusing namespace ::testing;\nusing namespace iox::units::duration_literals;\n\nclass Mutex_test : public Test\n{\n public:\n void SetUp() override\n {\n internal::CaptureStderr();\n }\n\n void TearDown() override\n {\n std::string output = internal::GetCapturedStderr();\n if (Test::HasFailure())\n {\n std::cout << output << std::endl;\n }\n }\n\n iox::posix::mutex sutNonRecursive{false};\n iox::posix::mutex sutRecursive{true};\n};\n\nTEST_F(Mutex_test, TryLockWithNoLock)\n{\n EXPECT_THAT(sutNonRecursive.try_lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n}\n\n\n#ifndef _WIN32\nTEST_F(Mutex_test, TryLockWithNonRecursiveLock)\n{\n EXPECT_THAT(sutNonRecursive.lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.try_lock(), Eq(false));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n}\n#endif\n\nTEST_F(Mutex_test, LockAndUnlock)\n{\n EXPECT_THAT(sutNonRecursive.lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n}\n\nTEST_F(Mutex_test, LockAndUnlockRepeatedly)\n{\n EXPECT_THAT(sutNonRecursive.lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n}\n\n#if !defined(_WIN32) || !defined(QNX) || !defined(QNX__) || !defined(__QNX__)\n\/\/ in qnx you can destroy a locked mutex, without error if the thread holding the lock is destructing it.\nTEST_F(Mutex_test, DestructorFailsOnLockedMutex)\n{\n std::string output = internal::GetCapturedStderr();\n std::set_terminate([]() { std::cout << \"\", std::abort(); });\n\n EXPECT_DEATH(\n {\n iox::posix::mutex mtx{false};\n mtx.lock();\n },\n \".*\");\n\n internal::CaptureStderr();\n}\n#endif\n\nTEST_F(Mutex_test, LockedMutexBlocks)\n{\n std::atomic_bool isLockFinished{false};\n sutNonRecursive.lock();\n\n std::thread lockThread([&] {\n sutNonRecursive.lock();\n isLockFinished.store(true);\n sutNonRecursive.unlock();\n });\n\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n EXPECT_THAT(isLockFinished.load(), Eq(false));\n\n sutNonRecursive.unlock();\n lockThread.join();\n\n EXPECT_THAT(isLockFinished.load(), Eq(true));\n}\n\nTEST_F(Mutex_test, TryLockWithRecursiveMutexWhenMutexLocked)\n{\n std::atomic_bool isTryLockSuccessful{true};\n sutRecursive.lock();\n\n std::thread lockThread([&] { isTryLockSuccessful = sutRecursive.try_lock(); });\n\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n\n EXPECT_THAT(isTryLockSuccessful.load(), Eq(false));\n\n sutRecursive.unlock();\n lockThread.join();\n}\n<commit_msg>iox-#495 add watchdog to mutext_test<commit_after>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/ Copyright (c) 2021 by ApexAI Inc. All rights reserved.\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\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"iceoryx_utils\/cxx\/deadline_timer.hpp\"\n#include \"iceoryx_utils\/internal\/posix_wrapper\/mutex.hpp\"\n#include \"test.hpp\"\n#include \"testutils\/watch_dog.hpp\"\n\n#include <atomic>\n#include <thread>\n\nusing namespace ::testing;\nusing namespace iox::units::duration_literals;\n\nclass Mutex_test : public Test\n{\n public:\n void SetUp() override\n {\n internal::CaptureStderr();\n m_deadlockWatchdog.watchAndActOnFailure([] { std::terminate(); });\n }\n\n void TearDown() override\n {\n std::string output = internal::GetCapturedStderr();\n if (Test::HasFailure())\n {\n std::cout << output << std::endl;\n }\n }\n\n iox::posix::mutex sutNonRecursive{false};\n iox::posix::mutex sutRecursive{true};\n iox::units::Duration m_watchdogTimeout = 5_s;\n Watchdog m_deadlockWatchdog{m_watchdogTimeout};\n};\n\nTEST_F(Mutex_test, TryLockWithNoLock)\n{\n EXPECT_THAT(sutNonRecursive.try_lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n}\n\n\n#ifndef _WIN32\nTEST_F(Mutex_test, TryLockWithNonRecursiveLock)\n{\n EXPECT_THAT(sutNonRecursive.lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.try_lock(), Eq(false));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n}\n#endif\n\nTEST_F(Mutex_test, LockAndUnlock)\n{\n EXPECT_THAT(sutNonRecursive.lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n}\n\nTEST_F(Mutex_test, LockAndUnlockRepeatedly)\n{\n EXPECT_THAT(sutNonRecursive.lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.lock(), Eq(true));\n EXPECT_THAT(sutNonRecursive.unlock(), Eq(true));\n}\n\n#if !defined(_WIN32) || !defined(QNX) || !defined(QNX__) || !defined(__QNX__)\n\/\/ in qnx you can destroy a locked mutex, without error if the thread holding the lock is destructing it.\nTEST_F(Mutex_test, DestructorFailsOnLockedMutex)\n{\n std::string output = internal::GetCapturedStderr();\n std::set_terminate([]() { std::cout << \"\", std::abort(); });\n\n EXPECT_DEATH(\n {\n iox::posix::mutex mtx{false};\n mtx.lock();\n },\n \".*\");\n\n internal::CaptureStderr();\n}\n#endif\n\nTEST_F(Mutex_test, LockedMutexBlocks)\n{\n std::atomic_bool isLockFinished{false};\n sutNonRecursive.lock();\n\n std::thread lockThread([&] {\n sutNonRecursive.lock();\n isLockFinished.store(true);\n sutNonRecursive.unlock();\n });\n\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n EXPECT_THAT(isLockFinished.load(), Eq(false));\n\n sutNonRecursive.unlock();\n lockThread.join();\n\n EXPECT_THAT(isLockFinished.load(), Eq(true));\n}\n\nTEST_F(Mutex_test, TryLockWithRecursiveMutexWhenMutexLocked)\n{\n std::atomic_bool isTryLockSuccessful{true};\n sutRecursive.lock();\n\n std::thread lockThread([&] { isTryLockSuccessful = sutRecursive.try_lock(); });\n\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n\n EXPECT_THAT(isTryLockSuccessful.load(), Eq(false));\n\n sutRecursive.unlock();\n lockThread.join();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include <ox\/std\/trace.hpp>\n\n#include \"ptr.hpp\"\n\nnamespace ox::ptrarith {\n\ntemplate<typename size_t, typename Item>\nclass __attribute__((packed)) NodeBuffer {\n\n\tpublic:\n\t\tstruct __attribute__((packed)) Header {\n\t\t\tox::LittleEndian<size_t> size = sizeof(Header); \/\/ capacity\n\t\t\tox::LittleEndian<size_t> bytesUsed = sizeof(Header);\n\t\t\tox::LittleEndian<size_t> firstItem = 0;\n\t\t};\n\n\t\tusing ItemPtr = Ptr<Item, size_t, sizeof(Header)>;\n\n\t\tclass Iterator {\n\t\t\tprivate:\n\t\t\t\tNodeBuffer *m_buffer = nullptr;\n\t\t\t\tItemPtr m_current;\n\t\t\t\tsize_t m_it = 0;\n\n\t\t\tpublic:\n\t\t\t\tIterator(NodeBuffer *buffer, ItemPtr current) {\n\t\t\t\t\tm_buffer = buffer;\n\t\t\t\t\tm_current = current;\n\t\t\t\t\toxTrace(\"ox::ptrarith::Iterator::start\") << current.offset();\n\t\t\t\t}\n\n\t\t\t\toperator const Item*() const {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\tItemPtr ptr() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\tItem *get() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\toperator ItemPtr() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\toperator Item*() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\tconst Item *operator->() const {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\tItem *operator->() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\t[[nodiscard]] bool valid() const noexcept {\n\t\t\t\t\treturn m_current.valid();\n\t\t\t\t}\n\n\t\t\t\tbool hasNext() {\n\t\t\t\t\tif (m_current.valid()) {\n\t\t\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::Iterator::hasNext::current\") << m_current.offset();\n\t\t\t\t\t\tauto next = m_buffer->next(m_current);\n\t\t\t\t\t\treturn next.valid() && m_buffer->firstItem() != next;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tvoid next() {\n\t\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::Iterator::next\") << m_it++;\n\t\t\t\t\tif (hasNext()) {\n\t\t\t\t\t\tm_current = m_buffer->next(m_current);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tm_current = nullptr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t};\n\n\t\tHeader m_header;\n\n\tpublic:\n\t\tNodeBuffer() = default;\n\n\t\tNodeBuffer(const NodeBuffer &other);\n\n\t\texplicit NodeBuffer(size_t size);\n\n\t\tconst Iterator iterator() const;\n\n\t\tIterator iterator();\n\n\t\tItemPtr firstItem();\n\n\t\tItemPtr lastItem();\n\n\t\t\/**\n\t\t * @return the data section of the given item\n\t\t *\/\n\t\ttemplate<typename T>\n\t\tPtr<T, size_t, sizeof(Item)> dataOf(ItemPtr);\n\n\t\t[[nodiscard]] ItemPtr prev(Item *item);\n\n\t\t[[nodiscard]] ItemPtr next(Item *item);\n\n\t\t[[nodiscard]] ItemPtr ptr(size_t offset);\n\n\t\t[[nodiscard]] ItemPtr ptr(void *item);\n\n\t\t[[nodiscard]] ItemPtr malloc(size_t size);\n\n\t\t[[nodiscard]] ox::Error free(ItemPtr item);\n\n\t\t[[nodiscard]] bool valid(size_t maxSize);\n\n\t\t\/**\n\t\t * Set size, capacity.\n\t\t *\/\n\t\t[[nodiscard]] ox::Error setSize(size_t size);\n\n\t\t\/**\n\t\t * Get size, capacity.\n\t\t * @return capacity\n\t\t *\/\n\t\tsize_t size();\n\n\t\t\/**\n\t\t * @return the bytes still available in this NodeBuffer\n\t\t *\/\n\t\tsize_t available();\n\n\t\t\/**\n\t\t * @return the actual number a bytes need to store the given number of\n\t\t * bytes\n\t\t *\/\n\t\tsize_t spaceNeeded(size_t size);\n\n\t\ttemplate<typename F>\n\t\tvoid compact(F cb = [](uint64_t, ItemPtr) {});\n\n\t\tvoid truncate();\n\n\tprivate:\n\t\tuint8_t *data();\n\n};\n\ntemplate<typename size_t, typename Item>\nNodeBuffer<size_t, Item>::NodeBuffer(size_t size) {\n\tm_header.size = size;\n}\n\ntemplate<typename size_t, typename Item>\nNodeBuffer<size_t, Item>::NodeBuffer(const NodeBuffer &other) {\n\tox_memcpy(this, &other, other.size());\n}\n\ntemplate<typename size_t, typename Item>\nconst typename NodeBuffer<size_t, Item>::Iterator NodeBuffer<size_t, Item>::iterator() const {\n\treturn Iterator(this, firstItem());\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::Iterator NodeBuffer<size_t, Item>::iterator() {\n\toxTrace(\"ox::ptrarith::NodeBuffer::iterator::size\") << m_header.size;\n\treturn Iterator(this, firstItem());\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::firstItem() {\n\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::firstItem\") << m_header.firstItem;\n\treturn ptr(m_header.firstItem);\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::lastItem() {\n\tauto first = ptr(m_header.firstItem);\n\tif (first.valid()) {\n\t\treturn prev(first);\n\t}\n\treturn nullptr;\n}\n\ntemplate<typename size_t, typename Item>\ntemplate<typename T>\nPtr<T, size_t, sizeof(Item)> NodeBuffer<size_t, Item>::dataOf(ItemPtr ip) {\n\tauto out = ip.template subPtr<T>(sizeof(Item));\n\toxAssert(out.size() == ip.size() - sizeof(Item), \"Sub Ptr has invalid size.\");\n\treturn out;\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::prev(Item *item) {\n\treturn ptr(item->prev);\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::next(Item *item) {\n\treturn ptr(item->next);\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::ptr(size_t itemOffset) {\n\t\/\/ make sure this can be read as an Item, and then use Item::size for the size\n\tstd::size_t itemSpace = m_header.size - itemOffset;\n\tauto item = reinterpret_cast<Item*>(reinterpret_cast<uint8_t*>(this) + itemOffset);\n\tif (itemOffset >= sizeof(Header) &&\n\t itemOffset + itemSpace <= size() &&\n\t itemSpace >= sizeof(Item) &&\n\t itemSpace >= item->fullSize()) {\n\t\treturn ItemPtr(this, m_header.size, itemOffset, item->fullSize());\n\t} else {\n\t\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::ptr::null\") << \"itemOffset:\" << itemOffset;\n\t\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::ptr::null\") << \"itemOffset >= sizeof(Header):\" << (itemOffset >= sizeof(Header));\n\t\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::ptr::null\") << \"itemSpace >= sizeof(Item):\" << (itemSpace >= sizeof(Item));\n\t\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::ptr::null\") << \"itemSpace >= item->fullSize():\" << (itemSpace >= item->fullSize());\n\t\treturn ItemPtr(this, m_header.size, 0, 0);\n\t}\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::malloc(size_t size) {\n\toxTrace(\"ox::ptrarith::NodeBuffer::malloc\") << \"Size:\" << size;\n\tsize_t fullSize = size + sizeof(Item);\n\tif (m_header.size - m_header.bytesUsed >= fullSize) {\n\t\tauto last = lastItem();\n\t\tsize_t addr = 0;\n\t\tif (last.valid()) {\n\t\t\taddr = last.offset() + last.size();\n\t\t} else {\n\t\t\t\/\/ there is no first item, so this must be the first item\n\t\t\tif (!m_header.firstItem) {\n\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc\") << \"No first item, initializing.\";\n\t\t\t\tm_header.firstItem = sizeof(m_header);\n\t\t\t\taddr = m_header.firstItem;\n\t\t\t}\n\t\t}\n\t\tauto out = ItemPtr(this, m_header.size, addr, fullSize);\n\t\tif (out.valid()) {\n\t\t\tnew (out) Item;\n\t\t\tout->setSize(size);\n\n\t\t\tauto first = firstItem();\n\t\t\tauto oldLast = last;\n\t\t\tout->next = first.offset();\n\t\t\tif (first.valid()) {\n\t\t\t\tfirst->prev = out.offset();\n\t\t\t} else {\n\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc::fail\") << \"NodeBuffer malloc failed due to invalid first element pointer.\";\n\t\t\t\treturn nullptr;\n\t\t\t}\n\n\t\t\tif (oldLast.valid()) {\n\t\t\t\tout->prev = oldLast.offset();\n\t\t\t\toldLast->next = out.offset();\n\t\t\t} else { \/\/ check to see if this is the first allocation\n\t\t\t\tif (out.offset() != first.offset()) {\n\t\t\t\t\t\/\/ if this is not the first allocation, there should be an oldLast\n\t\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc::fail\") << \"NodeBuffer malloc failed due to invalid last element pointer.\";\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\t\t\t\tout->prev = out.offset();\n\t\t\t}\n\t\t\tm_header.bytesUsed += out.size();\n\t\t} else {\n\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc::fail\") << \"Unknown\";\n\t\t\treturn nullptr;\n\t\t}\n\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc\") << \"Offset:\" << out.offset();\n\t\treturn out;\n\t}\n\toxTrace(\"ox::ptrarith::NodeBuffer::malloc::fail\") << \"Insufficient space:\" << fullSize << \"needed,\" << available() << \"available\";\n\treturn nullptr;\n}\n\ntemplate<typename size_t, typename Item>\nError NodeBuffer<size_t, Item>::free(ItemPtr item) {\n\toxTrace(\"ox::ptrarith::NodeBuffer::free\") << \"offset:\" << item.offset();\n\tauto prev = this->prev(item);\n\tauto next = this->next(item);\n\tif (prev.valid() && next.valid()) {\n\t\tif (next != item) {\n\t\t\tprev->next = next;\n\t\t\tnext->prev = prev;\n\t\t\tif (item.offset() == m_header.firstItem) {\n\t\t\t\tm_header.firstItem = next;\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ only one item, null out first\n\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::free\") << \"Nulling out firstItem.\";\n\t\t\tm_header.firstItem = 0;\n\t\t}\n\t} else {\n\t\tif (!prev.valid()) {\n\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::free::fail\") << \"NodeBuffer free failed due to invalid prev element pointer:\" << prev.offset();\n\t\t\treturn OxError(1);\n\t\t}\n\t\tif (!next.valid()) {\n\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::free::fail\") << \"NodeBuffer free failed due to invalid next element pointer:\" << next.offset();\n\t\t\treturn OxError(1);\n\t\t}\n\t}\n\tm_header.bytesUsed -= item.size();\n\treturn OxError(0);\n}\n\ntemplate<typename size_t, typename Item>\nError NodeBuffer<size_t, Item>::setSize(size_t size) {\n\toxTrace(\"ox::ptrarith::NodeBuffer::setSize\") << size;\n\tauto last = lastItem();\n\tauto end = last.valid() ? last.end() : sizeof(m_header);\n\toxTrace(\"ox::ptrarith::NodeBuffer::setSize\") << \"end:\" << end;\n\tif (end > size) {\n\t\treturn OxError(1);\n\t} else {\n\t\tm_header.size = size;\n\t\treturn OxError(0);\n\t}\n}\n\ntemplate<typename size_t, typename Item>\nsize_t NodeBuffer<size_t, Item>::size() {\n\treturn m_header.size;\n}\n\ntemplate<typename size_t, typename Item>\nbool NodeBuffer<size_t, Item>::valid(size_t maxSize) {\n\treturn m_header.size <= maxSize;\n}\n\ntemplate<typename size_t, typename Item>\nsize_t NodeBuffer<size_t, Item>::available() {\n\treturn m_header.size - m_header.bytesUsed;\n}\n\ntemplate<typename size_t, typename Item>\nsize_t NodeBuffer<size_t, Item>::spaceNeeded(size_t size) {\n\treturn sizeof(Item) + size;\n}\n\ntemplate<typename size_t, typename Item>\ntemplate<typename F>\nvoid NodeBuffer<size_t, Item>::compact(F cb) {\n\tauto src = firstItem();\n\tauto dest = ptr(sizeof(*this));\n\twhile (src.valid() && dest.valid() && dest.offset() < src.offset()) {\n\t\t\/\/ move node\n\t\tox_memcpy(dest, src, src.size());\n\t\tcb(src, dest);\n\t\t\/\/ update surrounding nodes\n\t\tauto prev = ptr(dest->prev);\n\t\tif (prev.valid()) {\n\t\t\tprev->next = dest;\n\t\t}\n\t\tauto next = ptr(dest->next);\n\t\tif (next.valid()) {\n\t\t\tnext->prev = dest;\n\t\t}\n\t\t\/\/ update iterators\n\t\tsrc = ptr(dest->next);\n\t\tdest = ptr(dest.offset() + dest.size());\n\t}\n}\n\ntemplate<typename size_t, typename Item>\nvoid NodeBuffer<size_t, Item>::truncate() {\n\tm_header.size = m_header.bytesUsed;\n}\n\ntemplate<typename size_t, typename Item>\nuint8_t *NodeBuffer<size_t, Item>::data() {\n\treturn reinterpret_cast<uint8_t*>(ptr(sizeof(*this)).get());\n}\n\n\ntemplate<typename size_t>\nstruct __attribute__((packed)) Item {\n\tpublic:\n\t\tox::LittleEndian<size_t> prev = 0;\n\t\tox::LittleEndian<size_t> next = 0;\n\n\tprivate:\n\t\tox::LittleEndian<size_t> m_size = sizeof(Item);\n\n\tpublic:\n\t\tsize_t size() const {\n\t\t\treturn m_size;\n\t\t}\n\n\t\tvoid setSize(size_t size) {\n\t\t\tm_size = size;\n\t\t}\n};\n\n}\n<commit_msg>[ox\/ptrarith] Fix NodeBuffer::compact to iterate over items when item already in correct location<commit_after>\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include <ox\/std\/trace.hpp>\n\n#include \"ptr.hpp\"\n\nnamespace ox::ptrarith {\n\ntemplate<typename size_t, typename Item>\nclass __attribute__((packed)) NodeBuffer {\n\n\tpublic:\n\t\tstruct __attribute__((packed)) Header {\n\t\t\tox::LittleEndian<size_t> size = sizeof(Header); \/\/ capacity\n\t\t\tox::LittleEndian<size_t> bytesUsed = sizeof(Header);\n\t\t\tox::LittleEndian<size_t> firstItem = 0;\n\t\t};\n\n\t\tusing ItemPtr = Ptr<Item, size_t, sizeof(Header)>;\n\n\t\tclass Iterator {\n\t\t\tprivate:\n\t\t\t\tNodeBuffer *m_buffer = nullptr;\n\t\t\t\tItemPtr m_current;\n\t\t\t\tsize_t m_it = 0;\n\n\t\t\tpublic:\n\t\t\t\tIterator(NodeBuffer *buffer, ItemPtr current) {\n\t\t\t\t\tm_buffer = buffer;\n\t\t\t\t\tm_current = current;\n\t\t\t\t\toxTrace(\"ox::ptrarith::Iterator::start\") << current.offset();\n\t\t\t\t}\n\n\t\t\t\toperator const Item*() const {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\tItemPtr ptr() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\tItem *get() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\toperator ItemPtr() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\toperator Item*() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\tconst Item *operator->() const {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\tItem *operator->() {\n\t\t\t\t\treturn m_current;\n\t\t\t\t}\n\n\t\t\t\t[[nodiscard]] bool valid() const noexcept {\n\t\t\t\t\treturn m_current.valid();\n\t\t\t\t}\n\n\t\t\t\tbool hasNext() {\n\t\t\t\t\tif (m_current.valid()) {\n\t\t\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::Iterator::hasNext::current\") << m_current.offset();\n\t\t\t\t\t\tauto next = m_buffer->next(m_current);\n\t\t\t\t\t\treturn next.valid() && m_buffer->firstItem() != next;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tvoid next() {\n\t\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::Iterator::next\") << m_it++;\n\t\t\t\t\tif (hasNext()) {\n\t\t\t\t\t\tm_current = m_buffer->next(m_current);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tm_current = nullptr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t};\n\n\t\tHeader m_header;\n\n\tpublic:\n\t\tNodeBuffer() = default;\n\n\t\tNodeBuffer(const NodeBuffer &other);\n\n\t\texplicit NodeBuffer(size_t size);\n\n\t\tconst Iterator iterator() const;\n\n\t\tIterator iterator();\n\n\t\tItemPtr firstItem();\n\n\t\tItemPtr lastItem();\n\n\t\t\/**\n\t\t * @return the data section of the given item\n\t\t *\/\n\t\ttemplate<typename T>\n\t\tPtr<T, size_t, sizeof(Item)> dataOf(ItemPtr);\n\n\t\t[[nodiscard]] ItemPtr prev(Item *item);\n\n\t\t[[nodiscard]] ItemPtr next(Item *item);\n\n\t\t[[nodiscard]] ItemPtr ptr(size_t offset);\n\n\t\t[[nodiscard]] ItemPtr ptr(void *item);\n\n\t\t[[nodiscard]] ItemPtr malloc(size_t size);\n\n\t\t[[nodiscard]] ox::Error free(ItemPtr item);\n\n\t\t[[nodiscard]] bool valid(size_t maxSize);\n\n\t\t\/**\n\t\t * Set size, capacity.\n\t\t *\/\n\t\t[[nodiscard]] ox::Error setSize(size_t size);\n\n\t\t\/**\n\t\t * Get size, capacity.\n\t\t * @return capacity\n\t\t *\/\n\t\tsize_t size();\n\n\t\t\/**\n\t\t * @return the bytes still available in this NodeBuffer\n\t\t *\/\n\t\tsize_t available();\n\n\t\t\/**\n\t\t * @return the actual number a bytes need to store the given number of\n\t\t * bytes\n\t\t *\/\n\t\tsize_t spaceNeeded(size_t size);\n\n\t\ttemplate<typename F>\n\t\tvoid compact(F cb = [](uint64_t, ItemPtr) {});\n\n\t\tvoid truncate();\n\n\tprivate:\n\t\tuint8_t *data();\n\n};\n\ntemplate<typename size_t, typename Item>\nNodeBuffer<size_t, Item>::NodeBuffer(size_t size) {\n\tm_header.size = size;\n}\n\ntemplate<typename size_t, typename Item>\nNodeBuffer<size_t, Item>::NodeBuffer(const NodeBuffer &other) {\n\tox_memcpy(this, &other, other.size());\n}\n\ntemplate<typename size_t, typename Item>\nconst typename NodeBuffer<size_t, Item>::Iterator NodeBuffer<size_t, Item>::iterator() const {\n\treturn Iterator(this, firstItem());\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::Iterator NodeBuffer<size_t, Item>::iterator() {\n\toxTrace(\"ox::ptrarith::NodeBuffer::iterator::size\") << m_header.size;\n\treturn Iterator(this, firstItem());\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::firstItem() {\n\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::firstItem\") << m_header.firstItem;\n\treturn ptr(m_header.firstItem);\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::lastItem() {\n\tauto first = ptr(m_header.firstItem);\n\tif (first.valid()) {\n\t\treturn prev(first);\n\t}\n\treturn nullptr;\n}\n\ntemplate<typename size_t, typename Item>\ntemplate<typename T>\nPtr<T, size_t, sizeof(Item)> NodeBuffer<size_t, Item>::dataOf(ItemPtr ip) {\n\tauto out = ip.template subPtr<T>(sizeof(Item));\n\toxAssert(out.size() == ip.size() - sizeof(Item), \"Sub Ptr has invalid size.\");\n\treturn out;\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::prev(Item *item) {\n\treturn ptr(item->prev);\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::next(Item *item) {\n\treturn ptr(item->next);\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::ptr(size_t itemOffset) {\n\t\/\/ make sure this can be read as an Item, and then use Item::size for the size\n\tstd::size_t itemSpace = m_header.size - itemOffset;\n\tauto item = reinterpret_cast<Item*>(reinterpret_cast<uint8_t*>(this) + itemOffset);\n\tif (itemOffset >= sizeof(Header) &&\n\t itemOffset + itemSpace <= size() &&\n\t itemSpace >= sizeof(Item) &&\n\t itemSpace >= item->fullSize()) {\n\t\treturn ItemPtr(this, m_header.size, itemOffset, item->fullSize());\n\t} else {\n\t\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::ptr::null\") << \"itemOffset:\" << itemOffset;\n\t\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::ptr::null\") << \"itemOffset >= sizeof(Header):\" << (itemOffset >= sizeof(Header));\n\t\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::ptr::null\") << \"itemSpace >= sizeof(Item):\" << (itemSpace >= sizeof(Item));\n\t\t\/\/oxTrace(\"ox::ptrarith::NodeBuffer::ptr::null\") << \"itemSpace >= item->fullSize():\" << (itemSpace >= item->fullSize());\n\t\treturn ItemPtr(this, m_header.size, 0, 0);\n\t}\n}\n\ntemplate<typename size_t, typename Item>\ntypename NodeBuffer<size_t, Item>::ItemPtr NodeBuffer<size_t, Item>::malloc(size_t size) {\n\toxTrace(\"ox::ptrarith::NodeBuffer::malloc\") << \"Size:\" << size;\n\tsize_t fullSize = size + sizeof(Item);\n\tif (m_header.size - m_header.bytesUsed >= fullSize) {\n\t\tauto last = lastItem();\n\t\tsize_t addr = 0;\n\t\tif (last.valid()) {\n\t\t\taddr = last.offset() + last.size();\n\t\t} else {\n\t\t\t\/\/ there is no first item, so this must be the first item\n\t\t\tif (!m_header.firstItem) {\n\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc\") << \"No first item, initializing.\";\n\t\t\t\tm_header.firstItem = sizeof(m_header);\n\t\t\t\taddr = m_header.firstItem;\n\t\t\t}\n\t\t}\n\t\tauto out = ItemPtr(this, m_header.size, addr, fullSize);\n\t\tif (out.valid()) {\n\t\t\tnew (out) Item;\n\t\t\tout->setSize(size);\n\n\t\t\tauto first = firstItem();\n\t\t\tauto oldLast = last;\n\t\t\tout->next = first.offset();\n\t\t\tif (first.valid()) {\n\t\t\t\tfirst->prev = out.offset();\n\t\t\t} else {\n\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc::fail\") << \"NodeBuffer malloc failed due to invalid first element pointer.\";\n\t\t\t\treturn nullptr;\n\t\t\t}\n\n\t\t\tif (oldLast.valid()) {\n\t\t\t\tout->prev = oldLast.offset();\n\t\t\t\toldLast->next = out.offset();\n\t\t\t} else { \/\/ check to see if this is the first allocation\n\t\t\t\tif (out.offset() != first.offset()) {\n\t\t\t\t\t\/\/ if this is not the first allocation, there should be an oldLast\n\t\t\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc::fail\") << \"NodeBuffer malloc failed due to invalid last element pointer.\";\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\t\t\t\tout->prev = out.offset();\n\t\t\t}\n\t\t\tm_header.bytesUsed += out.size();\n\t\t} else {\n\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc::fail\") << \"Unknown\";\n\t\t\treturn nullptr;\n\t\t}\n\t\toxTrace(\"ox::ptrarith::NodeBuffer::malloc\") << \"Offset:\" << out.offset();\n\t\treturn out;\n\t}\n\toxTrace(\"ox::ptrarith::NodeBuffer::malloc::fail\") << \"Insufficient space:\" << fullSize << \"needed,\" << available() << \"available\";\n\treturn nullptr;\n}\n\ntemplate<typename size_t, typename Item>\nError NodeBuffer<size_t, Item>::free(ItemPtr item) {\n\toxTrace(\"ox::ptrarith::NodeBuffer::free\") << \"offset:\" << item.offset();\n\tauto prev = this->prev(item);\n\tauto next = this->next(item);\n\tif (prev.valid() && next.valid()) {\n\t\tif (next != item) {\n\t\t\tprev->next = next;\n\t\t\tnext->prev = prev;\n\t\t\tif (item.offset() == m_header.firstItem) {\n\t\t\t\tm_header.firstItem = next;\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ only one item, null out first\n\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::free\") << \"Nulling out firstItem.\";\n\t\t\tm_header.firstItem = 0;\n\t\t}\n\t} else {\n\t\tif (!prev.valid()) {\n\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::free::fail\") << \"NodeBuffer free failed due to invalid prev element pointer:\" << prev.offset();\n\t\t\treturn OxError(1);\n\t\t}\n\t\tif (!next.valid()) {\n\t\t\toxTrace(\"ox::ptrarith::NodeBuffer::free::fail\") << \"NodeBuffer free failed due to invalid next element pointer:\" << next.offset();\n\t\t\treturn OxError(1);\n\t\t}\n\t}\n\tm_header.bytesUsed -= item.size();\n\treturn OxError(0);\n}\n\ntemplate<typename size_t, typename Item>\nError NodeBuffer<size_t, Item>::setSize(size_t size) {\n\toxTrace(\"ox::ptrarith::NodeBuffer::setSize\") << size;\n\tauto last = lastItem();\n\tauto end = last.valid() ? last.end() : sizeof(m_header);\n\toxTrace(\"ox::ptrarith::NodeBuffer::setSize\") << \"end:\" << end;\n\tif (end > size) {\n\t\treturn OxError(1);\n\t} else {\n\t\tm_header.size = size;\n\t\treturn OxError(0);\n\t}\n}\n\ntemplate<typename size_t, typename Item>\nsize_t NodeBuffer<size_t, Item>::size() {\n\treturn m_header.size;\n}\n\ntemplate<typename size_t, typename Item>\nbool NodeBuffer<size_t, Item>::valid(size_t maxSize) {\n\treturn m_header.size <= maxSize;\n}\n\ntemplate<typename size_t, typename Item>\nsize_t NodeBuffer<size_t, Item>::available() {\n\treturn m_header.size - m_header.bytesUsed;\n}\n\ntemplate<typename size_t, typename Item>\nsize_t NodeBuffer<size_t, Item>::spaceNeeded(size_t size) {\n\treturn sizeof(Item) + size;\n}\n\ntemplate<typename size_t, typename Item>\ntemplate<typename F>\nvoid NodeBuffer<size_t, Item>::compact(F cb) {\n\tauto src = firstItem();\n\tauto dest = ptr(sizeof(*this));\n\twhile (src.valid() && dest.valid() && dest.offset() <= src.offset()) {\n\t\t\/\/ move node\n\t\tox_memcpy(dest, src, src.size());\n\t\tcb(src, dest);\n\t\t\/\/ update surrounding nodes\n\t\tauto prev = ptr(dest->prev);\n\t\tif (prev.valid()) {\n\t\t\tprev->next = dest;\n\t\t}\n\t\tauto next = ptr(dest->next);\n\t\tif (next.valid()) {\n\t\t\tnext->prev = dest;\n\t\t}\n\t\t\/\/ update iterators\n\t\tsrc = ptr(dest->next);\n\t\tdest = ptr(dest.offset() + dest.size());\n\t}\n}\n\ntemplate<typename size_t, typename Item>\nvoid NodeBuffer<size_t, Item>::truncate() {\n\tm_header.size = m_header.bytesUsed;\n}\n\ntemplate<typename size_t, typename Item>\nuint8_t *NodeBuffer<size_t, Item>::data() {\n\treturn reinterpret_cast<uint8_t*>(ptr(sizeof(*this)).get());\n}\n\n\ntemplate<typename size_t>\nstruct __attribute__((packed)) Item {\n\tpublic:\n\t\tox::LittleEndian<size_t> prev = 0;\n\t\tox::LittleEndian<size_t> next = 0;\n\n\tprivate:\n\t\tox::LittleEndian<size_t> m_size = sizeof(Item);\n\n\tpublic:\n\t\tsize_t size() const {\n\t\t\treturn m_size;\n\t\t}\n\n\t\tvoid setSize(size_t size) {\n\t\t\tm_size = size;\n\t\t}\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, Baidu.com, Inc. 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 \"master\/workload_scheduler.h\"\n\n#include \"glog\/logging.h\"\n#include \"master\/tablet_manager.h\"\n\nDECLARE_double(tera_master_load_balance_size_ratio_trigger);\nDECLARE_double(tera_master_load_balance_qps_ratio_trigger);\nDECLARE_int32(tera_master_load_balance_qps_min_limit);\n\nnamespace tera {\nnamespace master {\n\nclass WorkloadGetter {\npublic:\n virtual int64_t operator() (const TabletNodePtr& tablet_node,\n const std::string& table_name = \"\") const = 0;\n virtual int64_t operator() (const TabletPtr& tablet) const = 0;\n virtual ~WorkloadGetter() {}\n};\n\nclass WorkloadComparator {\npublic:\n \/\/ Three-way comparison. Returns value:\n \/\/ < 0 iff \"a\" < \"b\",\n \/\/ == 0 iff \"a\" == \"b\",\n \/\/ > 0 iff \"a\" > \"b\"\n int Compare(const TabletNodePtr& a, const TabletNodePtr& b,\n const std::string& table_name) {\n if (!table_name.empty()) {\n uint64_t a_load = (*m_load_getter)(a, table_name);\n uint64_t b_load = (*m_load_getter)(b, table_name);\n if (a_load < b_load) {\n return -1;\n } else if (a_load > b_load) {\n return 1;\n }\n }\n\n uint64_t a_load = (*m_load_getter)(a);\n uint64_t b_load = (*m_load_getter)(b);\n if (a_load < b_load) {\n return -1;\n } else if (a_load > b_load) {\n return 1;\n } else if (m_next_comparator != NULL) {\n return m_next_comparator->Compare(a, b, table_name);\n } else {\n return 0;\n }\n }\n\n int Compare(const TabletPtr& a, const TabletPtr& b) {\n uint64_t a_load = (*m_load_getter)(a);\n uint64_t b_load = (*m_load_getter)(b);\n if (a_load < b_load) {\n return -1;\n } else if (a_load > b_load) {\n return 1;\n } else if (m_next_comparator != NULL) {\n return m_next_comparator->Compare(a, b);\n } else {\n return 0;\n }\n }\n\n WorkloadComparator(WorkloadGetter* load_getter,\n bool owns_load_getter = false,\n WorkloadComparator* next_comparator = NULL,\n bool owns_next_comparator = false)\n : m_load_getter(load_getter),\n m_owns_load_getter(owns_load_getter),\n m_next_comparator(next_comparator),\n m_owns_next_comparator(owns_next_comparator) {\n }\n\n virtual ~WorkloadComparator() {\n if (m_owns_next_comparator) {\n delete m_next_comparator;\n }\n if (m_owns_load_getter) {\n delete m_load_getter;\n }\n }\n\nprivate:\n WorkloadGetter* m_load_getter;\n bool m_owns_load_getter;\n WorkloadComparator* m_next_comparator;\n bool m_owns_next_comparator;\n};\n\nclass WorkloadLess {\npublic:\n bool operator() (const TabletNodePtr& a, const TabletNodePtr& b) {\n return m_comparator->Compare(a, b, m_table_name) < 0;\n }\n bool operator() (const TabletPtr& a, const TabletPtr& b) {\n return m_comparator->Compare(a, b) < 0;\n }\n WorkloadLess(WorkloadComparator* comparator, const std::string& table_name = \"\")\n : m_comparator(comparator), m_table_name(table_name) {}\nprivate:\n WorkloadComparator* m_comparator;\n std::string m_table_name;\n};\n\nclass WorkloadGreater {\npublic:\n bool operator() (const TabletNodePtr& a, const TabletNodePtr& b) {\n return m_comparator->Compare(a, b, m_table_name) > 0;\n }\n bool operator() (const TabletPtr& a, const TabletPtr& b) {\n return m_comparator->Compare(a, b) > 0;\n }\n WorkloadGreater(WorkloadComparator* comparator, const std::string& table_name = \"\")\n : m_comparator(comparator), m_table_name(table_name) {}\n\nprivate:\n WorkloadComparator* m_comparator;\n std::string m_table_name;\n};\n\nclass SizeGetter : public WorkloadGetter {\npublic:\n virtual int64_t operator() (const TabletNodePtr& tabletnode,\n const std::string& table_name = \"\") const {\n return tabletnode->GetSize(table_name);\n }\n virtual int64_t operator() (const TabletPtr& tablet) const {\n return tablet->GetDataSize();\n }\n virtual ~SizeGetter() {}\n};\n\nclass SizeComparator : public WorkloadComparator {\npublic:\n SizeComparator() : WorkloadComparator(&m_size_getter) {}\nprivate:\n SizeGetter m_size_getter;\n};\n\nclass QPSGetter : public WorkloadGetter {\npublic:\n virtual int64_t operator() (const TabletNodePtr& tabletnode,\n const std::string& table_name = \"\") const {\n return tabletnode->GetQps(table_name);\n }\n virtual int64_t operator() (const TabletPtr& tablet) const {\n return tablet->GetAverageCounter().read_rows();\n }\n virtual ~QPSGetter() {}\n};\n\nclass QPSComparator : public WorkloadComparator {\npublic:\n QPSComparator() : WorkloadComparator(&m_qps_getter) {}\nprivate:\n QPSGetter m_qps_getter;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SizeScheduler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SizeScheduler::FindBestNode(const std::vector<TabletNodePtr>& node_list,\n const std::string& table_name,\n size_t* best_index) {\n if (node_list.size() == 0) {\n return false;\n }\n\n SizeComparator comparator;\n *best_index = 0;\n for (size_t i = 1; i < node_list.size(); ++i) {\n int r = comparator.Compare(node_list[*best_index], node_list[i], table_name);\n if (r > 0) {\n *best_index = i;\n } else if (r < 0) {\n \/\/ do nothing\n } else if (node_list[*best_index]->GetAddr() <= m_last_choose_node\n && node_list[i]->GetAddr() > m_last_choose_node) {\n \/\/ round-robin\n *best_index = i;\n }\n }\n m_last_choose_node = node_list[*best_index]->GetAddr();\n VLOG(7) << \"[size-sched] best node = \" << m_last_choose_node;\n return true;\n}\n\nbool SizeScheduler::FindBestTablet(TabletNodePtr src_node, TabletNodePtr dst_node,\n const std::vector<TabletPtr>& tablet_list,\n const std::string& table_name,\n size_t* best_index) {\n VLOG(7) << \"[size-sched] FindBestTablet() \" << src_node->GetAddr()\n << \" -> \" << dst_node->GetAddr();\n\n SizeGetter size_getter;\n int64_t src_node_size = size_getter(src_node, table_name);\n int64_t dst_node_size = size_getter(dst_node, table_name);\n\n const double& size_ratio = FLAGS_tera_master_load_balance_size_ratio_trigger;\n if ((double)src_node_size < (double)dst_node_size * size_ratio) {\n VLOG(7) << \"[size-sched] size ratio not reach threshold: \" << src_node_size\n << \" : \" << dst_node_size;\n return false;\n }\n\n QPSGetter qps_getter;\n uint64_t src_node_qps = qps_getter(src_node, table_name);\n uint64_t dst_node_qps = qps_getter(dst_node, table_name);\n\n const double& qps_ratio = FLAGS_tera_master_load_balance_qps_ratio_trigger;\n if (dst_node_qps != 0\n && (double)src_node_qps * qps_ratio <= (double)dst_node_qps) {\n VLOG(7) << \"[size-sched] revert qps ratio reach threshold: \" << src_node_qps\n << \" : \" << dst_node_qps;\n return false;\n }\n\n int64_t ideal_move_size = (src_node_size - dst_node_size) \/ 2;\n VLOG(7) << \"[size-sched] size = \" << src_node_size << \" : \" << dst_node_size\n << \" qps = \" << src_node_qps << \" : \" << dst_node_qps\n << \" ideal_move_size = \" << ideal_move_size;\n\n int64_t best_tablet_index = -1;\n int64_t best_tablet_size = 0;\n int64_t best_tablet_qps = 0;\n for (size_t i = 0; i < tablet_list.size(); ++i) {\n TabletPtr tablet = tablet_list[i];\n int64_t size = size_getter(tablet);\n int64_t qps = qps_getter(tablet);\n if (size <= ideal_move_size\n && (dst_node_qps == 0 && qps == 0\n || (src_node_qps - qps) * qps_ratio > (dst_node_qps + qps))\n && (best_tablet_index == -1 || size > best_tablet_size)) {\n best_tablet_index = i;\n best_tablet_size = size;\n best_tablet_qps = qps;\n }\n }\n if (best_tablet_index == -1) {\n return false;\n }\n *best_index = best_tablet_index;\n TabletPtr best_tablet = tablet_list[best_tablet_index];\n VLOG(7) << \"[size-sched] best tablet = \" << best_tablet->GetPath()\n << \" size = \" << best_tablet_size\n << \" qps = \" << best_tablet_qps;\n return true;\n}\n\nvoid SizeScheduler::AscendingSort(std::vector<TabletNodePtr>& node_list,\n const std::string& table_name) {\n SizeComparator comparator;\n WorkloadLess less(&comparator, table_name);\n std::sort(node_list.begin(), node_list.end(), less);\n}\n\nvoid SizeScheduler::DescendingSort(std::vector<TabletNodePtr>& node_list,\n const std::string& table_name) {\n SizeComparator comparator;\n WorkloadGreater greater(&comparator, table_name);\n std::sort(node_list.begin(), node_list.end(), greater);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ QPSScheduler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool QPSScheduler::FindBestNode(const std::vector<TabletNodePtr>& node_list,\n const std::string& table_name,\n size_t* best_index) {\n if (node_list.size() == 0) {\n return false;\n }\n\n QPSComparator comparator;\n *best_index = 0;\n for (size_t i = 1; i < node_list.size(); ++i) {\n int r = comparator.Compare(node_list[*best_index], node_list[i], table_name);\n if (r > 0) {\n *best_index = i;\n } else if (r < 0) {\n \/\/ do nothing\n } else if (node_list[*best_index]->GetAddr() <= m_last_choose_node\n && node_list[i]->GetAddr() > m_last_choose_node) {\n \/\/ round-robin\n *best_index = i;\n }\n }\n m_last_choose_node = node_list[*best_index]->GetAddr();\n VLOG(7) << \"[QPS-sched] best node : \" << m_last_choose_node;\n return true;\n}\n\nbool QPSScheduler::FindBestTablet(TabletNodePtr src_node, TabletNodePtr dst_node,\n const std::vector<TabletPtr>& tablet_list,\n const std::string& table_name,\n size_t* best_index) {\n VLOG(7) << \"[QPS-sched] FindBestTablet() \" << src_node->GetAddr()\n << \" -> \" << dst_node->GetAddr();\n\n SizeGetter size_getter;\n QPSGetter qps_getter;\n int64_t src_node_qps = qps_getter(src_node, table_name);\n if (src_node_qps < FLAGS_tera_master_load_balance_qps_min_limit) {\n VLOG(7) << \"qps not reach min limit: \" << src_node_qps;\n return false;\n }\n\n int64_t dst_node_qps = qps_getter(dst_node, table_name);\n const double& qps_ratio = FLAGS_tera_master_load_balance_qps_ratio_trigger;\n if ((double)src_node_qps < (double)dst_node_qps * qps_ratio) {\n VLOG(7) << \"qps ratio not reach threshold: \" << src_node_qps\n << \" : \" << dst_node_qps;\n return false;\n }\n\n int64_t ideal_move_qps = (src_node_qps - dst_node_qps) \/ 2;\n VLOG(7) << \"[QPS-sched] qps = \" << src_node_qps << \" : \" << dst_node_qps\n << \" ideal_move_qps = \" << ideal_move_qps;\n\n int64_t best_tablet_index = -1;\n int64_t best_tablet_size = 0;\n int64_t best_tablet_qps = 0;\n for (size_t i = 0; i < tablet_list.size(); ++i) {\n TabletPtr tablet = tablet_list[i];\n int64_t size = size_getter(tablet);\n int64_t qps = qps_getter(tablet);\n if (qps <= ideal_move_qps\n && (best_tablet_index == -1 || qps > best_tablet_qps)) {\n best_tablet_index = i;\n best_tablet_size = size;\n best_tablet_qps = qps;\n }\n }\n if (best_tablet_index == -1) {\n return false;\n }\n if (best_tablet_qps == 0) {\n VLOG(7) << \"[QPS-sched] no need to move 0 QPS tablet\";\n return false;\n }\n *best_index = best_tablet_index;\n TabletPtr best_tablet = tablet_list[best_tablet_index];\n VLOG(7) << \"[QPS-sched] best tablet = \" << best_tablet->GetPath()\n << \" size = \" << best_tablet_size\n << \" qps = \" << best_tablet_qps;\n return true;\n}\n\nvoid QPSScheduler::AscendingSort(std::vector<TabletNodePtr>& node_list,\n const std::string& table_name) {\n QPSComparator comparator;\n WorkloadLess less(&comparator, table_name);\n std::sort(node_list.begin(), node_list.end(), less);\n}\n\nvoid QPSScheduler::DescendingSort(std::vector<TabletNodePtr>& node_list,\n const std::string& table_name) {\n QPSComparator comparator;\n WorkloadGreater greater(&comparator, table_name);\n std::sort(node_list.begin(), node_list.end(), greater);\n}\n\n} \/\/ namespace master\n} \/\/ namespace tera\n<commit_msg>load balance<commit_after>\/\/ Copyright (c) 2015, Baidu.com, Inc. 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 \"master\/workload_scheduler.h\"\n\n#include \"glog\/logging.h\"\n#include \"master\/tablet_manager.h\"\n\nDECLARE_double(tera_master_load_balance_size_ratio_trigger);\nDECLARE_double(tera_master_load_balance_qps_ratio_trigger);\nDECLARE_int32(tera_master_load_balance_qps_min_limit);\n\nnamespace tera {\nnamespace master {\n\nclass WorkloadGetter {\npublic:\n virtual int64_t operator() (const TabletNodePtr& tablet_node,\n const std::string& table_name = \"\") const = 0;\n virtual int64_t operator() (const TabletPtr& tablet) const = 0;\n virtual ~WorkloadGetter() {}\n};\n\nclass WorkloadComparator {\npublic:\n \/\/ Three-way comparison. Returns value:\n \/\/ < 0 iff \"a\" < \"b\",\n \/\/ == 0 iff \"a\" == \"b\",\n \/\/ > 0 iff \"a\" > \"b\"\n int Compare(const TabletNodePtr& a, const TabletNodePtr& b,\n const std::string& table_name) {\n if (!table_name.empty()) {\n uint64_t a_load = (*m_load_getter)(a, table_name);\n uint64_t b_load = (*m_load_getter)(b, table_name);\n if (a_load < b_load) {\n return -1;\n } else if (a_load > b_load) {\n return 1;\n }\n }\n\n uint64_t a_load = (*m_load_getter)(a);\n uint64_t b_load = (*m_load_getter)(b);\n if (a_load < b_load) {\n return -1;\n } else if (a_load > b_load) {\n return 1;\n } else if (m_next_comparator != NULL) {\n return m_next_comparator->Compare(a, b, table_name);\n } else {\n return 0;\n }\n }\n\n int Compare(const TabletPtr& a, const TabletPtr& b) {\n uint64_t a_load = (*m_load_getter)(a);\n uint64_t b_load = (*m_load_getter)(b);\n if (a_load < b_load) {\n return -1;\n } else if (a_load > b_load) {\n return 1;\n } else if (m_next_comparator != NULL) {\n return m_next_comparator->Compare(a, b);\n } else {\n return 0;\n }\n }\n\n WorkloadComparator(WorkloadGetter* load_getter,\n bool owns_load_getter = false,\n WorkloadComparator* next_comparator = NULL,\n bool owns_next_comparator = false)\n : m_load_getter(load_getter),\n m_owns_load_getter(owns_load_getter),\n m_next_comparator(next_comparator),\n m_owns_next_comparator(owns_next_comparator) {\n }\n\n virtual ~WorkloadComparator() {\n if (m_owns_next_comparator) {\n delete m_next_comparator;\n }\n if (m_owns_load_getter) {\n delete m_load_getter;\n }\n }\n\nprivate:\n WorkloadGetter* m_load_getter;\n bool m_owns_load_getter;\n WorkloadComparator* m_next_comparator;\n bool m_owns_next_comparator;\n};\n\nclass WorkloadLess {\npublic:\n bool operator() (const TabletNodePtr& a, const TabletNodePtr& b) {\n return m_comparator->Compare(a, b, m_table_name) < 0;\n }\n bool operator() (const TabletPtr& a, const TabletPtr& b) {\n return m_comparator->Compare(a, b) < 0;\n }\n WorkloadLess(WorkloadComparator* comparator, const std::string& table_name = \"\")\n : m_comparator(comparator), m_table_name(table_name) {}\nprivate:\n WorkloadComparator* m_comparator;\n std::string m_table_name;\n};\n\nclass WorkloadGreater {\npublic:\n bool operator() (const TabletNodePtr& a, const TabletNodePtr& b) {\n return m_comparator->Compare(a, b, m_table_name) > 0;\n }\n bool operator() (const TabletPtr& a, const TabletPtr& b) {\n return m_comparator->Compare(a, b) > 0;\n }\n WorkloadGreater(WorkloadComparator* comparator, const std::string& table_name = \"\")\n : m_comparator(comparator), m_table_name(table_name) {}\n\nprivate:\n WorkloadComparator* m_comparator;\n std::string m_table_name;\n};\n\nclass SizeGetter : public WorkloadGetter {\npublic:\n virtual int64_t operator() (const TabletNodePtr& tabletnode,\n const std::string& table_name = \"\") const {\n return tabletnode->GetSize(table_name);\n }\n virtual int64_t operator() (const TabletPtr& tablet) const {\n return tablet->GetDataSize();\n }\n virtual ~SizeGetter() {}\n};\n\nclass SizeComparator : public WorkloadComparator {\npublic:\n SizeComparator() : WorkloadComparator(&m_size_getter) {}\nprivate:\n SizeGetter m_size_getter;\n};\n\nclass QPSGetter : public WorkloadGetter {\npublic:\n virtual int64_t operator() (const TabletNodePtr& tabletnode,\n const std::string& table_name = \"\") const {\n return tabletnode->GetQps(table_name);\n }\n virtual int64_t operator() (const TabletPtr& tablet) const {\n return tablet->GetAverageCounter().read_rows();\n }\n virtual ~QPSGetter() {}\n};\n\nclass QPSComparator : public WorkloadComparator {\npublic:\n QPSComparator() : WorkloadComparator(&m_qps_getter) {}\nprivate:\n QPSGetter m_qps_getter;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SizeScheduler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SizeScheduler::FindBestNode(const std::vector<TabletNodePtr>& node_list,\n const std::string& table_name,\n size_t* best_index) {\n if (node_list.size() == 0) {\n return false;\n }\n\n SizeComparator comparator;\n *best_index = 0;\n for (size_t i = 1; i < node_list.size(); ++i) {\n int r = comparator.Compare(node_list[*best_index], node_list[i], table_name);\n if (r > 0) {\n *best_index = i;\n } else if (r < 0) {\n \/\/ do nothing\n } else if (node_list[*best_index]->GetAddr() <= m_last_choose_node\n && node_list[i]->GetAddr() > m_last_choose_node) {\n \/\/ round-robin\n *best_index = i;\n }\n }\n m_last_choose_node = node_list[*best_index]->GetAddr();\n VLOG(7) << \"[size-sched] best node = \" << m_last_choose_node;\n return true;\n}\n\nbool SizeScheduler::FindBestTablet(TabletNodePtr src_node, TabletNodePtr dst_node,\n const std::vector<TabletPtr>& tablet_list,\n const std::string& table_name,\n size_t* best_index) {\n VLOG(7) << \"[size-sched] FindBestTablet() \" << src_node->GetAddr()\n << \" -> \" << dst_node->GetAddr();\n\n SizeGetter size_getter;\n int64_t src_node_size = size_getter(src_node, table_name);\n int64_t dst_node_size = size_getter(dst_node, table_name);\n\n const double& size_ratio = FLAGS_tera_master_load_balance_size_ratio_trigger;\n if ((double)src_node_size < (double)dst_node_size * size_ratio) {\n VLOG(7) << \"[size-sched] size ratio not reach threshold: \" << src_node_size\n << \" : \" << dst_node_size;\n return false;\n }\n\n QPSGetter qps_getter;\n uint64_t src_node_qps = qps_getter(src_node, table_name);\n uint64_t dst_node_qps = qps_getter(dst_node, table_name);\n\n const double& qps_ratio = FLAGS_tera_master_load_balance_qps_ratio_trigger;\n if (dst_node_qps >= FLAGS_tera_master_load_balance_qps_min_limit\n && (double)src_node_qps * qps_ratio <= (double)dst_node_qps) {\n VLOG(7) << \"[size-sched] revert qps ratio reach threshold: \" << src_node_qps\n << \" : \" << dst_node_qps;\n return false;\n }\n\n int64_t ideal_move_size = (src_node_size - dst_node_size) \/ 2;\n VLOG(7) << \"[size-sched] size = \" << src_node_size << \" : \" << dst_node_size\n << \" qps = \" << src_node_qps << \" : \" << dst_node_qps\n << \" ideal_move_size = \" << ideal_move_size;\n\n int64_t best_tablet_index = -1;\n int64_t best_tablet_size = 0;\n int64_t best_tablet_qps = 0;\n for (size_t i = 0; i < tablet_list.size(); ++i) {\n TabletPtr tablet = tablet_list[i];\n int64_t size = size_getter(tablet);\n int64_t qps = qps_getter(tablet);\n if (size <= ideal_move_size\n && (dst_node_qps + qps < FLAGS_tera_master_load_balance_qps_min_limit\n || (src_node_qps - qps) * qps_ratio > (dst_node_qps + qps))\n && (best_tablet_index == -1 || size > best_tablet_size)) {\n best_tablet_index = i;\n best_tablet_size = size;\n best_tablet_qps = qps;\n }\n }\n if (best_tablet_index == -1) {\n return false;\n }\n *best_index = best_tablet_index;\n TabletPtr best_tablet = tablet_list[best_tablet_index];\n VLOG(7) << \"[size-sched] best tablet = \" << best_tablet->GetPath()\n << \" size = \" << best_tablet_size\n << \" qps = \" << best_tablet_qps;\n return true;\n}\n\nvoid SizeScheduler::AscendingSort(std::vector<TabletNodePtr>& node_list,\n const std::string& table_name) {\n SizeComparator comparator;\n WorkloadLess less(&comparator, table_name);\n std::sort(node_list.begin(), node_list.end(), less);\n}\n\nvoid SizeScheduler::DescendingSort(std::vector<TabletNodePtr>& node_list,\n const std::string& table_name) {\n SizeComparator comparator;\n WorkloadGreater greater(&comparator, table_name);\n std::sort(node_list.begin(), node_list.end(), greater);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ QPSScheduler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool QPSScheduler::FindBestNode(const std::vector<TabletNodePtr>& node_list,\n const std::string& table_name,\n size_t* best_index) {\n if (node_list.size() == 0) {\n return false;\n }\n\n QPSComparator comparator;\n *best_index = 0;\n for (size_t i = 1; i < node_list.size(); ++i) {\n int r = comparator.Compare(node_list[*best_index], node_list[i], table_name);\n if (r > 0) {\n *best_index = i;\n } else if (r < 0) {\n \/\/ do nothing\n } else if (node_list[*best_index]->GetAddr() <= m_last_choose_node\n && node_list[i]->GetAddr() > m_last_choose_node) {\n \/\/ round-robin\n *best_index = i;\n }\n }\n m_last_choose_node = node_list[*best_index]->GetAddr();\n VLOG(7) << \"[QPS-sched] best node : \" << m_last_choose_node;\n return true;\n}\n\nbool QPSScheduler::FindBestTablet(TabletNodePtr src_node, TabletNodePtr dst_node,\n const std::vector<TabletPtr>& tablet_list,\n const std::string& table_name,\n size_t* best_index) {\n VLOG(7) << \"[QPS-sched] FindBestTablet() \" << src_node->GetAddr()\n << \" -> \" << dst_node->GetAddr();\n\n SizeGetter size_getter;\n QPSGetter qps_getter;\n int64_t src_node_qps = qps_getter(src_node, table_name);\n if (src_node_qps < FLAGS_tera_master_load_balance_qps_min_limit) {\n VLOG(7) << \"qps not reach min limit: \" << src_node_qps;\n return false;\n }\n\n int64_t dst_node_qps = qps_getter(dst_node, table_name);\n const double& qps_ratio = FLAGS_tera_master_load_balance_qps_ratio_trigger;\n if ((double)src_node_qps < (double)dst_node_qps * qps_ratio) {\n VLOG(7) << \"qps ratio not reach threshold: \" << src_node_qps\n << \" : \" << dst_node_qps;\n return false;\n }\n\n int64_t ideal_move_qps = (src_node_qps - dst_node_qps) \/ 2;\n VLOG(7) << \"[QPS-sched] qps = \" << src_node_qps << \" : \" << dst_node_qps\n << \" ideal_move_qps = \" << ideal_move_qps;\n\n int64_t best_tablet_index = -1;\n int64_t best_tablet_size = 0;\n int64_t best_tablet_qps = 0;\n for (size_t i = 0; i < tablet_list.size(); ++i) {\n TabletPtr tablet = tablet_list[i];\n int64_t size = size_getter(tablet);\n int64_t qps = qps_getter(tablet);\n if (qps <= ideal_move_qps\n && (best_tablet_index == -1 || qps > best_tablet_qps)) {\n best_tablet_index = i;\n best_tablet_size = size;\n best_tablet_qps = qps;\n }\n }\n if (best_tablet_index == -1) {\n return false;\n }\n if (best_tablet_qps == 0) {\n VLOG(7) << \"[QPS-sched] no need to move 0 QPS tablet\";\n return false;\n }\n *best_index = best_tablet_index;\n TabletPtr best_tablet = tablet_list[best_tablet_index];\n VLOG(7) << \"[QPS-sched] best tablet = \" << best_tablet->GetPath()\n << \" size = \" << best_tablet_size\n << \" qps = \" << best_tablet_qps;\n return true;\n}\n\nvoid QPSScheduler::AscendingSort(std::vector<TabletNodePtr>& node_list,\n const std::string& table_name) {\n QPSComparator comparator;\n WorkloadLess less(&comparator, table_name);\n std::sort(node_list.begin(), node_list.end(), less);\n}\n\nvoid QPSScheduler::DescendingSort(std::vector<TabletNodePtr>& node_list,\n const std::string& table_name) {\n QPSComparator comparator;\n WorkloadGreater greater(&comparator, table_name);\n std::sort(node_list.begin(), node_list.end(), greater);\n}\n\n} \/\/ namespace master\n} \/\/ namespace tera\n<|endoftext|>"} {"text":"<commit_before>\/*!\r\n \\copyright (c) RDO-Team, 2011\r\n \\file main.cpp\r\n \\author (lord.tiran@gmail.com)\r\n \\date 26.10.2011\r\n \\brief RDO\r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#include <boost\/filesystem.hpp>\r\nnamespace fs = boost::filesystem;\r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"utils\/rdocommon.h\"\r\n#include \"repository\/rdorepository.h\"\r\n#include \"simulator\/service\/rdosimwin.h\"\r\n#include \"app\/rdo_console\/terminate_codes.h\"\r\n#include \"app\/rdo_console\/controller_console_options.h\"\r\n#include \"app\/rdo_console\/rdo_console_controller.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\n#define LOG_FILE_NAME \"log.txt\"\r\n\r\nstatic ruint g_exitCode = TERMINATION_NORMAL;\r\n\r\nint main(int argc, PTR(char) argv[])\r\n{\r\n\tRDOControllerConsoleOptions options_controller(argc, argv);\r\n\toptions_controller.parseOptions();\r\n\r\n\ttstring model_name;\r\n\toptions_controller.getModelName(model_name);\r\n\trbool model_exist = fs::exists(model_name);\r\n\r\n\tboost::filesystem::path path(model_name);\r\n\ttstring model_dir = path.parent_path().string();\r\n\r\n\tif (options_controller.helpQuery())\r\n\t{\r\n\t\treturn TERMINATION_NORMAL;\r\n\t}\r\n\telse if (!model_exist && !options_controller.helpQuery())\r\n\t{\r\n\t\tstd::cout << _T(\"Model does not exist\") << std::endl;\r\n\t\treturn TERMINATION_WITH_AN_ERROR_NO_MODEL;\r\n\t}\r\n\r\n\t\/\/ simulation\r\n\r\n\tRDOKernel::init();\r\n\tnew rdo::service::simulation::RDOThreadSimulator();\r\n\tnew rdo::repository::RDOThreadRepository();\r\n\r\n\tPTR(RDOStudioConsoleController) pAppController = new RDOStudioConsoleController();\r\n\tASSERT(pAppController);\r\n\r\n\trdo::repository::RDOThreadRepository::OpenFile data(model_name);\r\n\tpAppController->broadcastMessage(RDOThread::RT_STUDIO_MODEL_OPEN, &data);\r\n\tpAppController->broadcastMessage(RDOThread::RT_STUDIO_MODEL_BUILD );\r\n\r\n\tbool simulationSuccessfully = false;\r\n\r\n\tbool buildError = pAppController->buildError();\r\n\tif (buildError)\r\n\t{\r\n\t\tStringList buildList;\r\n\t\tpAppController->getBuildLogList(buildList);\r\n\r\n\t\ttstring fileName(model_dir + \"\/\" + LOG_FILE_NAME);\r\n\t\tboost::filesystem::remove(fileName);\r\n\t\tstd::ofstream stream(fileName.c_str(), std::ios::out);\r\n\r\n\t\tstream.clear();\r\n\t\tif (stream.fail()) {\r\n\t\t\treturn TERMINATION_WITH_APP_RUNTIME_ERROR;\r\n\t\t}\r\n\t\tsize_t counter = 0;\r\n\t\tsize_t size = buildList.size();\r\n\t\tfor (StringList::const_iterator it = buildList.begin(); it != buildList.end(); ++it)\r\n\t\t{\r\n\t\t\tstream << it->c_str();\r\n\t\t\tif (counter < size - 1)\r\n\t\t\t{\r\n\t\t\t\tstream << std::endl;\r\n\t\t\t}\r\n\t\t\t++counter;\r\n\t\t}\r\n\t\tstream.close();\r\n\r\n\t\tstd::cerr << _T(\"Build model error\") << std::endl;\r\n\t\tg_exitCode = TERMINATION_WITH_AN_ERROR_PARSE_ERROR;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tpAppController->broadcastMessage(RDOThread::RT_STUDIO_MODEL_RUN);\r\n\r\n\t\twhile (!pAppController->finished())\r\n\t\t{\r\n\t\t\tkernel->idle();\r\n\r\n\t\t\tif (pAppController->runtimeError())\r\n\t\t\t{\r\n\t\t\t\tstd::cout << _T(\"Run-time error\") << std::endl;\r\n\t\t\t\tg_exitCode = TERMINATION_WITH_AN_ERROR_RUNTIME_ERROR;\r\n\t\t\t}\r\n\t\t}\r\n\t\tsimulationSuccessfully = pAppController->simulationSuccessfully();\r\n\r\n\t\tRDOKernel::close();\r\n\t}\r\n\tif (simulationSuccessfully)\r\n\t{\r\n\t\tstd::cout << _T(\"Simulation finished successfully\") << std::endl;\r\n\t\tg_exitCode = TERMINATION_NORMAL;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstd::cout << _T(\"Simulation completed with errors\") << std::endl;\r\n\t}\r\n\treturn g_exitCode;\r\n}\r\n<commit_msg> - updated rdo_console app : updated log build messages in file code<commit_after>\/*!\r\n \\copyright (c) RDO-Team, 2011\r\n \\file main.cpp\r\n \\author (lord.tiran@gmail.com)\r\n \\date 26.10.2011\r\n \\brief RDO\r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#include <boost\/filesystem.hpp>\r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"utils\/rdocommon.h\"\r\n#include \"repository\/rdorepository.h\"\r\n#include \"simulator\/service\/rdosimwin.h\"\r\n#include \"app\/rdo_console\/terminate_codes.h\"\r\n#include \"app\/rdo_console\/controller_console_options.h\"\r\n#include \"app\/rdo_console\/rdo_console_controller.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nnamespace fs = boost::filesystem;\r\n\r\nconst tstring LOG_FILE_NAME = _T(\"log.txt\");\r\n\r\nstatic ruint g_exitCode = TERMINATION_NORMAL;\r\n\r\nint main(int argc, PTR(char) argv[])\r\n{\r\n\tRDOControllerConsoleOptions options_controller(argc, argv);\r\n\toptions_controller.parseOptions();\r\n\r\n\ttstring model_name;\r\n\toptions_controller.getModelName(model_name);\r\n\trbool model_exist = fs::exists(model_name);\r\n\r\n\tboost::filesystem::path path(model_name);\r\n\ttstring model_dir = path.parent_path().string();\r\n\r\n\tif (options_controller.helpQuery())\r\n\t{\r\n\t\treturn TERMINATION_NORMAL;\r\n\t}\r\n\telse if (!model_exist && !options_controller.helpQuery())\r\n\t{\r\n\t\tstd::cout << _T(\"Model does not exist\") << std::endl;\r\n\t\treturn TERMINATION_WITH_AN_ERROR_NO_MODEL;\r\n\t}\r\n\r\n\t\/\/ simulation\r\n\r\n\tRDOKernel::init();\r\n\tnew rdo::service::simulation::RDOThreadSimulator();\r\n\tnew rdo::repository::RDOThreadRepository();\r\n\r\n\tPTR(RDOStudioConsoleController) pAppController = new RDOStudioConsoleController();\r\n\tASSERT(pAppController);\r\n\r\n\trdo::repository::RDOThreadRepository::OpenFile data(model_name);\r\n\tpAppController->broadcastMessage(RDOThread::RT_STUDIO_MODEL_OPEN, &data);\r\n\tpAppController->broadcastMessage(RDOThread::RT_STUDIO_MODEL_BUILD );\r\n\r\n\tbool simulationSuccessfully = false;\r\n\r\n\tbool buildError = pAppController->buildError();\r\n\tif (buildError)\r\n\t{\r\n\t\tStringList buildList;\r\n\t\tpAppController->getBuildLogList(buildList);\r\n\r\n\t\ttstring fileName(model_dir + \"\/\" + LOG_FILE_NAME);\r\n\t\tboost::filesystem::remove(fileName);\r\n\t\tstd::ofstream stream(fileName.c_str(), std::ios::out);\r\n\r\n\t\tstream.clear();\r\n\t\tif (stream.fail()) {\r\n\t\t\treturn TERMINATION_WITH_APP_RUNTIME_ERROR;\r\n\t\t}\r\n\t\tfor (StringList::const_iterator it = buildList.begin(); it != buildList.end(); ++it)\r\n\t\t{\r\n\t\t\tstream << it->c_str() << std::endl;\r\n\t\t}\r\n\t\tstream.close();\r\n\r\n\t\tstd::cout << _T(\"Build model error\") << std::endl;\r\n\t\tg_exitCode = TERMINATION_WITH_AN_ERROR_PARSE_ERROR;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tpAppController->broadcastMessage(RDOThread::RT_STUDIO_MODEL_RUN);\r\n\r\n\t\twhile (!pAppController->finished())\r\n\t\t{\r\n\t\t\tkernel->idle();\r\n\r\n\t\t\tif (pAppController->runtimeError())\r\n\t\t\t{\r\n\t\t\t\tstd::cout << _T(\"Run-time error\") << std::endl;\r\n\t\t\t\tg_exitCode = TERMINATION_WITH_AN_ERROR_RUNTIME_ERROR;\r\n\t\t\t}\r\n\t\t}\r\n\t\tsimulationSuccessfully = pAppController->simulationSuccessfully();\r\n\r\n\t\tRDOKernel::close();\r\n\t}\r\n\tif (simulationSuccessfully)\r\n\t{\r\n\t\tstd::cout << _T(\"Simulation finished successfully\") << std::endl;\r\n\t\tg_exitCode = TERMINATION_NORMAL;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstd::cout << _T(\"Simulation completed with errors\") << std::endl;\r\n\t}\r\n\treturn g_exitCode;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood\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\n#ifndef __MEM_RUBY_SYSTEM_MACHINEID_HH__\n#define __MEM_RUBY_SYSTEM_MACHINEID_HH__\n\n#include <iostream>\n#include <string>\n\n#include \"base\/cprintf.hh\"\n#include \"mem\/protocol\/MachineType.hh\"\n\nstruct MachineID\n{\n MachineType type;\n \/\/! range: 0 ... number of this machine's components in system - 1\n uint32_t num;\n\n MachineType getType() const { return type; }\n uint32_t getNum() const { return num; }\n};\n\ninline std::string\nMachineIDToString(MachineID machine)\n{\n return csprintf(\"%s_%d\", MachineType_to_string(machine.type), machine.num);\n}\n\ninline bool\noperator==(const MachineID & obj1, const MachineID & obj2)\n{\n return (obj1.type == obj2.type && obj1.num == obj2.num);\n}\n\ninline bool\noperator!=(const MachineID & obj1, const MachineID & obj2)\n{\n return (obj1.type != obj2.type || obj1.num != obj2.num);\n}\n\n\/\/ Output operator declaration\nstd::ostream& operator<<(std::ostream& out, const MachineID& obj);\n\ninline std::ostream&\noperator<<(std::ostream& out, const MachineID& obj)\n{\n if ((obj.type < MachineType_NUM) && (obj.type >= MachineType_FIRST)) {\n out << MachineType_to_string(obj.type);\n } else {\n out << \"NULL\";\n }\n out << \"-\";\n out << obj.num;\n out << std::flush;\n return out;\n}\n\n#endif \/\/ __MEM_RUBY_SYSTEM_MACHINEID_HH__\n<commit_msg>Ruby: Fix compilation errors on gcc 4.7 and clang 3.2<commit_after>\/*\n * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood\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\n#ifndef __MEM_RUBY_SYSTEM_MACHINEID_HH__\n#define __MEM_RUBY_SYSTEM_MACHINEID_HH__\n\n#include <iostream>\n#include <string>\n\n#include \"base\/cprintf.hh\"\n#include \"mem\/protocol\/MachineType.hh\"\n\nstruct MachineID\n{\n MachineType type;\n \/\/! range: 0 ... number of this machine's components in system - 1\n NodeID num;\n\n MachineType getType() const { return type; }\n NodeID getNum() const { return num; }\n};\n\ninline std::string\nMachineIDToString(MachineID machine)\n{\n return csprintf(\"%s_%d\", MachineType_to_string(machine.type), machine.num);\n}\n\ninline bool\noperator==(const MachineID & obj1, const MachineID & obj2)\n{\n return (obj1.type == obj2.type && obj1.num == obj2.num);\n}\n\ninline bool\noperator!=(const MachineID & obj1, const MachineID & obj2)\n{\n return (obj1.type != obj2.type || obj1.num != obj2.num);\n}\n\n\/\/ Output operator declaration\nstd::ostream& operator<<(std::ostream& out, const MachineID& obj);\n\ninline std::ostream&\noperator<<(std::ostream& out, const MachineID& obj)\n{\n if ((obj.type < MachineType_NUM) && (obj.type >= MachineType_FIRST)) {\n out << MachineType_to_string(obj.type);\n } else {\n out << \"NULL\";\n }\n out << \"-\";\n out << obj.num;\n out << std::flush;\n return out;\n}\n\n#endif \/\/ __MEM_RUBY_SYSTEM_MACHINEID_HH__\n<|endoftext|>"} {"text":"<commit_before>#include \"mem\/st\/visitor\/XmlDumper.hpp\"\n\n\nnamespace mem { namespace st { namespace visitor {\n\n\nvoid\nXmlDumper::setup ()\n{\n *_out << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\";\n}\n\nbool\nXmlDumper::visit (st::Symbol* sym)\n{\n switch (sym->Kind())\n {\n case st::MetaKind::ARG:\n visitArgument(st::cast<st::Arg>(sym));\n break;\n\n case st::MetaKind::ARRAY_TYPE:\n visitArrayType(st::cast<st::ArrayType>(sym));\n break;\n\n case st::MetaKind::CLASS_TYPE:\n visitClass(st::cast<st::Class>(sym));\n break;\n\n case st::MetaKind::ENUM_TYPE:\n visitEnumType(st::cast<st::EnumType>(sym));\n break;\n\n case st::MetaKind::INT_CONSTANT:\n visitIntConstant(st::cast<st::IntConstant>(sym));\n break;\n\n case st::MetaKind::FIELD:\n visitField(st::cast<st::Field>(sym));\n break;\n\n case st::MetaKind::FUNCTION:\n visitFunction(st::cast<st::Func>(sym));\n break;\n\n case st::MetaKind::INT_TYPE:\n visitIntType(st::cast<st::IntType>(sym));\n break;\n\n case st::MetaKind::NAMESPACE:\n visitNamespace(st::cast<st::Namespace>(sym));\n break;\n\n case st::MetaKind::POINTER_TYPE:\n visitPointerType(st::cast<st::PointerType>(sym));\n break;\n\n case st::MetaKind::PRIMITIVE_TYPE:\n visitPrimitiveType(st::cast<st::PrimitiveType>(sym));\n break;\n\n case st::MetaKind::TUPLE_TYPE:\n visitTupleType(st::cast<st::TupleType>(sym));\n break;\n\n case st::MetaKind::VAR:\n visitVar(st::cast<st::Var>(sym));\n break;\n\n default:\n visitUnknown(sym);\n }\n\n return false;\n}\n\nvoid\nXmlDumper::visitChildren (st::Symbol* sym)\n{\n st::Symbol::SymbolCollectionIterator i;\n for (i=sym->Children().begin(); i != sym->Children().end(); ++i)\n {\n this->visit(i->second);\n }\n}\n\nbool\nXmlDumper::visitArgument (st::Arg* s)\n{\n *_out << \"<Argument name=\\\"\" + s->Name() + \"\\\"\";\n if (s->Type() != NULL)\n {\n *_out << \" type=\\\"\" + s->Type()->gQualifiedName() + \"\\\"\";\n }\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitArrayType (st::ArrayType* s)\n{\n *_out << \"<ArrayType name=\\\"\" + s->Name() + \"\\\"\";\n if (s->ItemType() != NULL)\n {\n *_out << \" base-type=\\\"\" + s->ItemType()->gQualifiedName() + \"\\\"\";\n }\n if (s->hasLength())\n {\n *_out << \" size=\\\"\" << s->ArrayLength() << \"\\\"\";\n }\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitEnumType (st::EnumType* e)\n{\n *_out << \"<EnumType name=\\\"\" + e->Name() + \"\\\"\";\n *_out << \" byte-size=\\\"\" << e->ByteSize() << \"\\\"\";\n *_out << \">\\n\";\n this->visitChildren(e);\n *_out << \"<\/EnumType>\";\n\n return true;\n}\n\nbool\nXmlDumper::visitClass (st::Class* cls_sym)\n{\n *_out << \"<ClassType name=\\\"\" + cls_sym->Name() + \"\\\"\";\n if (cls_sym->ParentClass() != NULL)\n {\n *_out << \" parent-class=\\\"\" + cls_sym->ParentClass()->gQualifiedName() + \"\\\"\";\n }\n if (cls_sym->DefaultCtor() != NULL)\n {\n *_out << \" default-ctor=\\\"\" << cls_sym->DefaultCtor()->gQualifiedName() << \"\\\"\";\n }\n *_out << \" absolute-field-count=\\\"\" << cls_sym->getAbsoluteFieldCount() << \"\\\"\";\n *_out << \" byte-size=\\\"\" << cls_sym->ByteSize() << \"\\\"\";\n *_out << \">\\n\";\n this->visitChildren(cls_sym);\n *_out << \"<\/ClassType>\";\n\n return true;\n}\n\nbool\nXmlDumper::visitField (st::Field* s)\n{\n *_out << \"<Field name=\\\"\" + s->Name() + \"\\\"\";\n if (s->Type() != NULL)\n {\n *_out << \" type=\\\"\" + s->Type()->gQualifiedName() + \"\\\"\";\n }\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitFunction (st::Func* func_sym)\n{\n *_out << \"<Function name=\\\"\" + func_sym->Name() + \"\\\"\";\n if (func_sym->ReturnType() != NULL)\n {\n *_out << \" return-type=\\\"\" + func_sym->ReturnType()->gQualifiedName() + \"\\\"\";\n }\n if (func_sym->Type() != NULL)\n {\n *_out << \" type=\\\"\" + func_sym->Type()->gQualifiedName() + \"\\\"\";\n }\n if (func_sym->IsVirtual())\n {\n *_out << \" virtual=\\\"true\\\"\";\n }\n *_out << \">\\n\";\n visitChildren(func_sym);\n *_out << \"<\/Function>\";\n\n return true;\n}\nbool\nXmlDumper::visitIntConstant (st::IntConstant* s)\n{\n *_out << \"<IntConstant name=\\\"\" << s->Name() << \"\\\"\";\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" signed=\\\"\" << (s->IsSigned() ? \"true\" : \"false\") << \"\\\"\";\n *_out << \" \/>\\n\";\n return true;\n}\n\nbool\nXmlDumper::visitIntType (st::IntType* s)\n{\n *_out << \"<IntType name=\\\"\" + s->Name() + \"\\\"\";\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitNamespace (st::Namespace* ns_sym)\n{\n *_out << \"<Namespace name=\\\"\" << ns_sym->Name() << \"\\\">\\n\";\n visitChildren(ns_sym);\n *_out << \"<\/Namespace>\";\n\n return true;\n}\n\nbool\nXmlDumper::visitPointerType (st::PointerType* s)\n{\n *_out << \"<PointerType name=\\\"\" + s->Name() + \"\\\"\";\n if (s->PointedType() != NULL)\n {\n *_out << \" base-type=\\\"\" + s->PointedType()->gQualifiedName() + \"\\\"\";\n }\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitPrimitiveType (st::PrimitiveType* s)\n{\n *_out << \"<PrimitiveType name=\\\"\" + s->Name() + \"\\\"\";\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitTupleType (st::TupleType* s)\n{\n *_out << \"<TupleType name=\\\"\" + s->Name() + \"\\\"\";\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n if (s->hasChildren())\n {\n *_out << \">\\n\";\n visitChildren(s);\n *_out << \"<\/TupleType>\\n\";\n }\n else\n {\n *_out << \" \/>\\n\";\n }\n\n return true;\n}\n\nbool\nXmlDumper::visitVar (st::Var* var_sym)\n{\n *_out << \"<Variable name=\\\"\" + var_sym->Name() + \"\\\"\";\n if (var_sym->Type() != NULL)\n {\n *_out << \" type=\\\"\" + var_sym->Type()->gQualifiedName() + \"\\\"\";\n }\n *_out << \" constant=\\\"\" << (var_sym->IsConstant() ? \"true\" : \"false\") << \"\\\"\";\n *_out << \" global=\\\"\" << (var_sym->IsGlobal() ? \"true\" : \"false\") << \"\\\"\";\n if (var_sym->ConstantValue() != NULL)\n {\n *_out << \" constant-value=\\\"\" << var_sym->ConstantValue()->gQualifiedName() << \"\\\"\";\n }\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitUnknown (st::Symbol* sym)\n{\n *_out << \"<Unknown name=\\\"\" + sym->Name() + \"\\\">\\n\";\n visitChildren(sym);\n *_out << \"<\/Unknown>\";\n\n return true;\n}\n\n\n} } }\n<commit_msg>Dump enum parent type in ST XML dump<commit_after>#include \"mem\/st\/visitor\/XmlDumper.hpp\"\n\n\nnamespace mem { namespace st { namespace visitor {\n\n\nvoid\nXmlDumper::setup ()\n{\n *_out << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\";\n}\n\nbool\nXmlDumper::visit (st::Symbol* sym)\n{\n switch (sym->Kind())\n {\n case st::MetaKind::ARG:\n visitArgument(st::cast<st::Arg>(sym));\n break;\n\n case st::MetaKind::ARRAY_TYPE:\n visitArrayType(st::cast<st::ArrayType>(sym));\n break;\n\n case st::MetaKind::CLASS_TYPE:\n visitClass(st::cast<st::Class>(sym));\n break;\n\n case st::MetaKind::ENUM_TYPE:\n visitEnumType(st::cast<st::EnumType>(sym));\n break;\n\n case st::MetaKind::INT_CONSTANT:\n visitIntConstant(st::cast<st::IntConstant>(sym));\n break;\n\n case st::MetaKind::FIELD:\n visitField(st::cast<st::Field>(sym));\n break;\n\n case st::MetaKind::FUNCTION:\n visitFunction(st::cast<st::Func>(sym));\n break;\n\n case st::MetaKind::INT_TYPE:\n visitIntType(st::cast<st::IntType>(sym));\n break;\n\n case st::MetaKind::NAMESPACE:\n visitNamespace(st::cast<st::Namespace>(sym));\n break;\n\n case st::MetaKind::POINTER_TYPE:\n visitPointerType(st::cast<st::PointerType>(sym));\n break;\n\n case st::MetaKind::PRIMITIVE_TYPE:\n visitPrimitiveType(st::cast<st::PrimitiveType>(sym));\n break;\n\n case st::MetaKind::TUPLE_TYPE:\n visitTupleType(st::cast<st::TupleType>(sym));\n break;\n\n case st::MetaKind::VAR:\n visitVar(st::cast<st::Var>(sym));\n break;\n\n default:\n visitUnknown(sym);\n }\n\n return false;\n}\n\nvoid\nXmlDumper::visitChildren (st::Symbol* sym)\n{\n st::Symbol::SymbolCollectionIterator i;\n for (i=sym->Children().begin(); i != sym->Children().end(); ++i)\n {\n this->visit(i->second);\n }\n}\n\nbool\nXmlDumper::visitArgument (st::Arg* s)\n{\n *_out << \"<Argument name=\\\"\" + s->Name() + \"\\\"\";\n if (s->Type() != NULL)\n {\n *_out << \" type=\\\"\" + s->Type()->gQualifiedName() + \"\\\"\";\n }\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitArrayType (st::ArrayType* s)\n{\n *_out << \"<ArrayType name=\\\"\" + s->Name() + \"\\\"\";\n if (s->ItemType() != NULL)\n {\n *_out << \" base-type=\\\"\" + s->ItemType()->gQualifiedName() + \"\\\"\";\n }\n if (s->hasLength())\n {\n *_out << \" size=\\\"\" << s->ArrayLength() << \"\\\"\";\n }\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitEnumType (st::EnumType* e)\n{\n *_out << \"<EnumType name=\\\"\" + e->Name() + \"\\\"\";\n *_out << \" byte-size=\\\"\" << e->ByteSize() << \"\\\"\";\n if (e->ParentType() != NULL)\n {\n *_out << \" parent-type=\\\"\" + e->ParentType()->gQualifiedName() + \"\\\"\";\n }\n *_out << \">\\n\";\n this->visitChildren(e);\n *_out << \"<\/EnumType>\";\n\n return true;\n}\n\nbool\nXmlDumper::visitClass (st::Class* cls_sym)\n{\n *_out << \"<ClassType name=\\\"\" + cls_sym->Name() + \"\\\"\";\n if (cls_sym->ParentClass() != NULL)\n {\n *_out << \" parent-class=\\\"\" + cls_sym->ParentClass()->gQualifiedName() + \"\\\"\";\n }\n if (cls_sym->DefaultCtor() != NULL)\n {\n *_out << \" default-ctor=\\\"\" << cls_sym->DefaultCtor()->gQualifiedName() << \"\\\"\";\n }\n *_out << \" absolute-field-count=\\\"\" << cls_sym->getAbsoluteFieldCount() << \"\\\"\";\n *_out << \" byte-size=\\\"\" << cls_sym->ByteSize() << \"\\\"\";\n *_out << \">\\n\";\n this->visitChildren(cls_sym);\n *_out << \"<\/ClassType>\";\n\n return true;\n}\n\nbool\nXmlDumper::visitField (st::Field* s)\n{\n *_out << \"<Field name=\\\"\" + s->Name() + \"\\\"\";\n if (s->Type() != NULL)\n {\n *_out << \" type=\\\"\" + s->Type()->gQualifiedName() + \"\\\"\";\n }\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitFunction (st::Func* func_sym)\n{\n *_out << \"<Function name=\\\"\" + func_sym->Name() + \"\\\"\";\n if (func_sym->ReturnType() != NULL)\n {\n *_out << \" return-type=\\\"\" + func_sym->ReturnType()->gQualifiedName() + \"\\\"\";\n }\n if (func_sym->Type() != NULL)\n {\n *_out << \" type=\\\"\" + func_sym->Type()->gQualifiedName() + \"\\\"\";\n }\n if (func_sym->IsVirtual())\n {\n *_out << \" virtual=\\\"true\\\"\";\n }\n *_out << \">\\n\";\n visitChildren(func_sym);\n *_out << \"<\/Function>\";\n\n return true;\n}\nbool\nXmlDumper::visitIntConstant (st::IntConstant* s)\n{\n *_out << \"<IntConstant name=\\\"\" << s->Name() << \"\\\"\";\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" signed=\\\"\" << (s->IsSigned() ? \"true\" : \"false\") << \"\\\"\";\n *_out << \" \/>\\n\";\n return true;\n}\n\nbool\nXmlDumper::visitIntType (st::IntType* s)\n{\n *_out << \"<IntType name=\\\"\" + s->Name() + \"\\\"\";\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitNamespace (st::Namespace* ns_sym)\n{\n *_out << \"<Namespace name=\\\"\" << ns_sym->Name() << \"\\\">\\n\";\n visitChildren(ns_sym);\n *_out << \"<\/Namespace>\";\n\n return true;\n}\n\nbool\nXmlDumper::visitPointerType (st::PointerType* s)\n{\n *_out << \"<PointerType name=\\\"\" + s->Name() + \"\\\"\";\n if (s->PointedType() != NULL)\n {\n *_out << \" base-type=\\\"\" + s->PointedType()->gQualifiedName() + \"\\\"\";\n }\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitPrimitiveType (st::PrimitiveType* s)\n{\n *_out << \"<PrimitiveType name=\\\"\" + s->Name() + \"\\\"\";\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitTupleType (st::TupleType* s)\n{\n *_out << \"<TupleType name=\\\"\" + s->Name() + \"\\\"\";\n *_out << \" byte-size=\\\"\" << s->ByteSize() << \"\\\"\";\n if (s->hasChildren())\n {\n *_out << \">\\n\";\n visitChildren(s);\n *_out << \"<\/TupleType>\\n\";\n }\n else\n {\n *_out << \" \/>\\n\";\n }\n\n return true;\n}\n\nbool\nXmlDumper::visitVar (st::Var* var_sym)\n{\n *_out << \"<Variable name=\\\"\" + var_sym->Name() + \"\\\"\";\n if (var_sym->Type() != NULL)\n {\n *_out << \" type=\\\"\" + var_sym->Type()->gQualifiedName() + \"\\\"\";\n }\n *_out << \" constant=\\\"\" << (var_sym->IsConstant() ? \"true\" : \"false\") << \"\\\"\";\n *_out << \" global=\\\"\" << (var_sym->IsGlobal() ? \"true\" : \"false\") << \"\\\"\";\n if (var_sym->ConstantValue() != NULL)\n {\n *_out << \" constant-value=\\\"\" << var_sym->ConstantValue()->gQualifiedName() << \"\\\"\";\n }\n *_out << \" \/>\\n\";\n\n return true;\n}\n\nbool\nXmlDumper::visitUnknown (st::Symbol* sym)\n{\n *_out << \"<Unknown name=\\\"\" + sym->Name() + \"\\\">\\n\";\n visitChildren(sym);\n *_out << \"<\/Unknown>\";\n\n return true;\n}\n\n\n} } }\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2016, Ford Motor Company\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 met:\n\n Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided with the\n distribution.\n\n Neither the name of the Ford Motor Company nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <cstring>\n#include <cstdio>\n#include <string>\n#include \"application_manager\/commands\/mobile\/on_system_request_notification.h\"\n#include \"interfaces\/MOBILE_API.h\"\n#include \"utils\/file_system.h\"\n#include \"application_manager\/application_manager_impl.h\"\n#include \"application_manager\/policies\/policy_handler.h\"\n\nnamespace application_manager {\n\nnamespace commands {\n\nnamespace mobile {\n\nOnSystemRequestNotification::OnSystemRequestNotification(\n const MessageSharedPtr& message)\n : CommandNotificationImpl(message) {}\n\nOnSystemRequestNotification::~OnSystemRequestNotification() {}\n\nvoid OnSystemRequestNotification::Run() {\n LOG4CXX_AUTO_TRACE(logger_);\n using namespace application_manager;\n using namespace mobile_apis;\n\n ApplicationSharedPtr app =\n ApplicationManagerImpl::instance()->application(connection_key());\n\n if (!app.valid()) {\n LOG4CXX_ERROR(logger_,\n \"Application with connection key \" << connection_key()\n << \" is not registered.\");\n return;\n }\n\n RequestType::eType request_type = static_cast<RequestType::eType>(\n (*message_)[strings::msg_params][strings::request_type].asInt());\n\n if (!policy::PolicyHandler::instance()->IsRequestTypeAllowed(\n app->mobile_app_id(), request_type)) {\n LOG4CXX_WARN(logger_,\n \"Request type \" << request_type\n << \" is not allowed by policies\");\n return;\n }\n\n if (RequestType::PROPRIETARY == request_type) {\n\/* According to requirements:\n \"If the requestType = PROPRIETARY, add to mobile API fileType = JSON\n If the requestType = HTTP, add to mobile API fileType = BINARY\"\n Also in Genivi SDL we don't save the PT to file - we put it directly in\n binary_data *\/\n\n#ifdef EXTENDED_POLICY\n const std::string filename =\n (*message_)[strings::msg_params][strings::file_name].asString();\n\n BinaryMessage binary_data;\n file_system::ReadBinaryFile(filename, binary_data);\n AddHeader(binary_data);\n (*message_)[strings::params][strings::binary_data] = binary_data;\n#endif\n (*message_)[strings::msg_params][strings::file_type] = FileType::JSON;\n } else if (RequestType::HTTP == request_type) {\n (*message_)[strings::msg_params][strings::file_type] = FileType::BINARY;\n }\n\n SendNotification();\n}\n\n#ifdef EXTENDED_POLICY\nvoid OnSystemRequestNotification::AddHeader(BinaryMessage& message) const {\n LOG4CXX_AUTO_TRACE(logger_);\n const int timeout = policy::PolicyHandler::instance()->TimeoutExchange();\n\n char size_str[24];\n\n if (0 > sprintf(size_str, \"%lu\", message.size())) {\n memset(size_str, 0, sizeof(size_str));\n }\n\n char timeout_str[24];\n if (0 > sprintf(timeout_str, \"%d\", timeout)) {\n memset(timeout_str, 0, sizeof(timeout_str));\n }\n\n const std::string header =\n\n \"{\"\n \" \\\"HTTPRequest\\\": {\"\n \"\\\"headers\\\": {\"\n \"\\\"ContentType\\\": \\\"application\/json\\\",\"\n \"\\\"ConnectTimeout\\\": \" + std::string(timeout_str) + \",\"\n \"\\\"DoOutput\\\": true,\"\n \"\\\"DoInput\\\": true,\"\n \"\\\"UseCaches\\\": false,\"\n \"\\\"RequestMethod\\\": \\\"POST\\\",\"\n \"\\\"ReadTimeout\\\":\" + std::string(timeout_str) + \",\"\n \"\\\"InstanceFollowRedirects\\\": false,\"\n \"\\\"charset\\\": \\\"utf-8\\\",\"\n \"\\\"Content_Length\\\": \" + std::string(size_str) +\n \"},\"\n \"\\\"body\\\": \\\"\" + std::string(message.begin(), message.end()) + \"\\\"\"\n \"}\"\n \"}\";\n\n message.clear();\n message.assign(header.begin(), header.end());\n\n LOG4CXX_DEBUG(\n logger_, \"Header added: \" << std::string(message.begin(), message.end()));\n}\n#endif\n\n} \/\/namespace mobile\n\n} \/\/ namespace commands\n\n} \/\/ namespace application_manager\n<commit_msg>Fixes build warning for 32-bit Ubuntu<commit_after>\/*\n Copyright (c) 2016, Ford Motor Company\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 met:\n\n Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided with the\n distribution.\n\n Neither the name of the Ford Motor Company nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <cstring>\n#include <cstdio>\n#include <string>\n#include \"application_manager\/commands\/mobile\/on_system_request_notification.h\"\n#include \"interfaces\/MOBILE_API.h\"\n#include \"utils\/file_system.h\"\n#include \"application_manager\/application_manager_impl.h\"\n#include \"application_manager\/policies\/policy_handler.h\"\n\nnamespace application_manager {\n\nnamespace commands {\n\nnamespace mobile {\n\nOnSystemRequestNotification::OnSystemRequestNotification(\n const MessageSharedPtr& message)\n : CommandNotificationImpl(message) {}\n\nOnSystemRequestNotification::~OnSystemRequestNotification() {}\n\nvoid OnSystemRequestNotification::Run() {\n LOG4CXX_AUTO_TRACE(logger_);\n using namespace application_manager;\n using namespace mobile_apis;\n\n ApplicationSharedPtr app =\n ApplicationManagerImpl::instance()->application(connection_key());\n\n if (!app.valid()) {\n LOG4CXX_ERROR(logger_,\n \"Application with connection key \" << connection_key()\n << \" is not registered.\");\n return;\n }\n\n RequestType::eType request_type = static_cast<RequestType::eType>(\n (*message_)[strings::msg_params][strings::request_type].asInt());\n\n if (!policy::PolicyHandler::instance()->IsRequestTypeAllowed(\n app->mobile_app_id(), request_type)) {\n LOG4CXX_WARN(logger_,\n \"Request type \" << request_type\n << \" is not allowed by policies\");\n return;\n }\n\n if (RequestType::PROPRIETARY == request_type) {\n\/* According to requirements:\n \"If the requestType = PROPRIETARY, add to mobile API fileType = JSON\n If the requestType = HTTP, add to mobile API fileType = BINARY\"\n Also in Genivi SDL we don't save the PT to file - we put it directly in\n binary_data *\/\n\n#ifdef EXTENDED_POLICY\n const std::string filename =\n (*message_)[strings::msg_params][strings::file_name].asString();\n\n BinaryMessage binary_data;\n file_system::ReadBinaryFile(filename, binary_data);\n AddHeader(binary_data);\n (*message_)[strings::params][strings::binary_data] = binary_data;\n#endif\n (*message_)[strings::msg_params][strings::file_type] = FileType::JSON;\n } else if (RequestType::HTTP == request_type) {\n (*message_)[strings::msg_params][strings::file_type] = FileType::BINARY;\n }\n\n SendNotification();\n}\n\n#ifdef EXTENDED_POLICY\nvoid OnSystemRequestNotification::AddHeader(BinaryMessage& message) const {\n LOG4CXX_AUTO_TRACE(logger_);\n const int timeout = policy::PolicyHandler::instance()->TimeoutExchange();\n\n char size_str[24];\n\n if (0 > sprintf(size_str, \"%zu\", static_cast<size_t>(message.size()))) {\n memset(size_str, 0, sizeof(size_str));\n }\n\n char timeout_str[24];\n if (0 > sprintf(timeout_str, \"%d\", timeout)) {\n memset(timeout_str, 0, sizeof(timeout_str));\n }\n\n const std::string header =\n\n \"{\"\n \" \\\"HTTPRequest\\\": {\"\n \"\\\"headers\\\": {\"\n \"\\\"ContentType\\\": \\\"application\/json\\\",\"\n \"\\\"ConnectTimeout\\\": \" + std::string(timeout_str) + \",\"\n \"\\\"DoOutput\\\": true,\"\n \"\\\"DoInput\\\": true,\"\n \"\\\"UseCaches\\\": false,\"\n \"\\\"RequestMethod\\\": \\\"POST\\\",\"\n \"\\\"ReadTimeout\\\":\" + std::string(timeout_str) + \",\"\n \"\\\"InstanceFollowRedirects\\\": false,\"\n \"\\\"charset\\\": \\\"utf-8\\\",\"\n \"\\\"Content_Length\\\": \" + std::string(size_str) +\n \"},\"\n \"\\\"body\\\": \\\"\" + std::string(message.begin(), message.end()) + \"\\\"\"\n \"}\"\n \"}\";\n\n message.clear();\n message.assign(header.begin(), header.end());\n\n LOG4CXX_DEBUG(\n logger_, \"Header added: \" << std::string(message.begin(), message.end()));\n}\n#endif\n\n} \/\/namespace mobile\n\n} \/\/ namespace commands\n\n} \/\/ namespace application_manager\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file llupdaterservice.cpp\n *\n * $LicenseInfo:firstyear=2010&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010, Linden Research, Inc.\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;\n * version 2.1 of the License only.\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 * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"linden_common.h\"\n#include <boost\/format.hpp>\n#include \"llhttpclient.h\"\n#include \"llupdatechecker.h\"\n\n\nclass LLUpdateChecker::Implementation:\n\tpublic LLHTTPClient::Responder\n{\npublic:\n\t\n\tImplementation(Client & client);\n\t~Implementation();\n\tvoid check(std::string const & host, std::string channel, std::string version);\n\t\n\t\/\/ Responder:\n\tvirtual void completed(U32 status,\n\t\t\t\t\t\t const std::string & reason,\n\t\t\t\t\t\t const LLSD& content);\n\tvirtual void error(U32 status, const std::string & reason);\n\t\nprivate:\n\tstd::string buildUrl(std::string const & host, std::string channel, std::string version);\n\t\n\tClient & mClient;\n\tLLHTTPClient mHttpClient;\n\tbool mInProgress;\n\tLLHTTPClient::ResponderPtr mMe;\n\tstd::string mVersion;\n\t\n\tLOG_CLASS(LLUpdateChecker::Implementation);\n};\n\n\n\n\/\/ LLUpdateChecker\n\/\/-----------------------------------------------------------------------------\n\n\nLLUpdateChecker::LLUpdateChecker(LLUpdateChecker::Client & client):\n\tmImplementation(new LLUpdateChecker::Implementation(client))\n{\n\t; \/\/ No op.\n}\n\n\nvoid LLUpdateChecker::check(std::string const & host, std::string channel, std::string version)\n{\n\tmImplementation->check(host, channel, version);\n}\n\n\n\n\/\/ LLUpdateChecker::Implementation\n\/\/-----------------------------------------------------------------------------\n\n\nLLUpdateChecker::Implementation::Implementation(LLUpdateChecker::Client & client):\n\tmClient(client),\n\tmInProgress(false),\n\tmMe(this)\n{\n\t; \/\/ No op.\n}\n\n\nLLUpdateChecker::Implementation::~Implementation()\n{\n\tmMe.reset(0);\n}\n\n\nvoid LLUpdateChecker::Implementation::check(std::string const & host, std::string channel, std::string version)\n{\n\t\/\/ llassert(!mInProgress);\n\t\t\n\tmInProgress = true;\n\tmVersion = version;\n\tstd::string checkUrl = buildUrl(host, channel, version);\n\tLL_INFOS(\"UpdateCheck\") << \"checking for updates at \" << checkUrl << llendl;\n\tmHttpClient.get(checkUrl, mMe);\n}\n\nvoid LLUpdateChecker::Implementation::completed(U32 status,\n\t\t\t\t\t\t\t const std::string & reason,\n\t\t\t\t\t\t\t const LLSD & content)\n{\n\tmInProgress = false;\n\t\n\tif(status != 200) {\n\t\tLL_WARNS(\"UpdateCheck\") << \"html error \" << status << \" (\" << reason << \")\" << llendl;\n\t\tmClient.error(reason);\n\t} else if(!content[\"valid\"].asBoolean()) {\n\t\tLL_INFOS(\"UpdateCheck\") << \"version invalid\" << llendl;\n\t\tmClient.requiredUpdate(content[\"latest_version\"].asString());\n\t} else if(content[\"latest_version\"].asString() != mVersion) {\n\t\tLL_INFOS(\"UpdateCheck\") << \"newer version \" << content[\"latest_version\"].asString() << \" available\" << llendl;\n\t\tmClient.optionalUpdate(content[\"latest_version\"].asString());\n\t} else {\n\t\tLL_INFOS(\"UpdateCheck\") << \"up to date\" << llendl;\n\t\tmClient.upToDate();\n\t}\n}\n\n\nvoid LLUpdateChecker::Implementation::error(U32 status, const std::string & reason)\n{\n\tmInProgress = false;\n\tLL_WARNS(\"UpdateCheck\") << \"update check failed; \" << reason << llendl;\n}\n\n\nstd::string LLUpdateChecker::Implementation::buildUrl(std::string const & host, std::string channel, std::string version)\n{\t\n\tstatic boost::format urlFormat(\"%s\/version\/%s\/%s\");\n\turlFormat % host % channel % version;\n\treturn urlFormat.str();\n}\n\n<commit_msg>fix quoting of url in version check.<commit_after>\/** \n * @file llupdaterservice.cpp\n *\n * $LicenseInfo:firstyear=2010&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010, Linden Research, Inc.\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;\n * version 2.1 of the License only.\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 * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"linden_common.h\"\n#include <boost\/format.hpp>\n#include \"llhttpclient.h\"\n#include \"llsd.h\"\n#include \"llupdatechecker.h\"\n#include \"lluri.h\"\n\n\nclass LLUpdateChecker::Implementation:\n\tpublic LLHTTPClient::Responder\n{\npublic:\n\t\n\tImplementation(Client & client);\n\t~Implementation();\n\tvoid check(std::string const & host, std::string channel, std::string version);\n\t\n\t\/\/ Responder:\n\tvirtual void completed(U32 status,\n\t\t\t\t\t\t const std::string & reason,\n\t\t\t\t\t\t const LLSD& content);\n\tvirtual void error(U32 status, const std::string & reason);\n\t\nprivate:\n\tstd::string buildUrl(std::string const & host, std::string channel, std::string version);\n\t\n\tClient & mClient;\n\tLLHTTPClient mHttpClient;\n\tbool mInProgress;\n\tLLHTTPClient::ResponderPtr mMe;\n\tstd::string mVersion;\n\t\n\tLOG_CLASS(LLUpdateChecker::Implementation);\n};\n\n\n\n\/\/ LLUpdateChecker\n\/\/-----------------------------------------------------------------------------\n\n\nLLUpdateChecker::LLUpdateChecker(LLUpdateChecker::Client & client):\n\tmImplementation(new LLUpdateChecker::Implementation(client))\n{\n\t; \/\/ No op.\n}\n\n\nvoid LLUpdateChecker::check(std::string const & host, std::string channel, std::string version)\n{\n\tmImplementation->check(host, channel, version);\n}\n\n\n\n\/\/ LLUpdateChecker::Implementation\n\/\/-----------------------------------------------------------------------------\n\n\nLLUpdateChecker::Implementation::Implementation(LLUpdateChecker::Client & client):\n\tmClient(client),\n\tmInProgress(false),\n\tmMe(this)\n{\n\t; \/\/ No op.\n}\n\n\nLLUpdateChecker::Implementation::~Implementation()\n{\n\tmMe.reset(0);\n}\n\n\nvoid LLUpdateChecker::Implementation::check(std::string const & host, std::string channel, std::string version)\n{\n\t\/\/ llassert(!mInProgress);\n\t\t\n\tmInProgress = true;\n\tmVersion = version;\n\tstd::string checkUrl = buildUrl(host, channel, version);\n\tLL_INFOS(\"UpdateCheck\") << \"checking for updates at \" << checkUrl << llendl;\n\tmHttpClient.get(checkUrl, mMe);\n}\n\nvoid LLUpdateChecker::Implementation::completed(U32 status,\n\t\t\t\t\t\t\t const std::string & reason,\n\t\t\t\t\t\t\t const LLSD & content)\n{\n\tmInProgress = false;\n\t\n\tif(status != 200) {\n\t\tLL_WARNS(\"UpdateCheck\") << \"html error \" << status << \" (\" << reason << \")\" << llendl;\n\t\tmClient.error(reason);\n\t} else if(!content[\"valid\"].asBoolean()) {\n\t\tLL_INFOS(\"UpdateCheck\") << \"version invalid\" << llendl;\n\t\tmClient.requiredUpdate(content[\"latest_version\"].asString());\n\t} else if(content[\"latest_version\"].asString() != mVersion) {\n\t\tLL_INFOS(\"UpdateCheck\") << \"newer version \" << content[\"latest_version\"].asString() << \" available\" << llendl;\n\t\tmClient.optionalUpdate(content[\"latest_version\"].asString());\n\t} else {\n\t\tLL_INFOS(\"UpdateCheck\") << \"up to date\" << llendl;\n\t\tmClient.upToDate();\n\t}\n}\n\n\nvoid LLUpdateChecker::Implementation::error(U32 status, const std::string & reason)\n{\n\tmInProgress = false;\n\tLL_WARNS(\"UpdateCheck\") << \"update check failed; \" << reason << llendl;\n}\n\n\nstd::string LLUpdateChecker::Implementation::buildUrl(std::string const & host, std::string channel, std::string version)\n{\t\n\tLLSD path;\n\tpath.append(\"version\");\n\tpath.append(channel);\n\tpath.append(version);\n\treturn LLURI::buildHTTP(host, path).asString();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 New Designs Unlimited, LLC\n * Opensource Automated License Plate Recognition [http:\/\/www.openalpr.com]\n *\n * This file is part of OpenAlpr.\n *\n * OpenAlpr is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License\n * version 3 as published by the Free Software Foundation\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 Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/calib3d\/calib3d.hpp>\n\n#include \"support\/filesystem.h\"\n#include \"..\/tclap\/CmdLine.h\"\n#include \"prewarp.h\"\n\n#include <sstream>\n\nusing namespace std;\nusing namespace cv;\n\nconst int INSTRUCTIONS_HEIGHT = 32;\n\n\nbool panning;\nbool left_clicking;\nPoint left_click_start;\nPoint left_click_cur;\n\n\nPoint lastPos;\n\nfloat w;\nfloat h;\nfloat panX = 0;\nfloat panY = 0;\nfloat rotationx = 0;\nfloat rotationy = 0;\nfloat rotationz = 0;\nfloat stretchX = 1.0;\nfloat dist = 1.0;\n\nMat imgOriginal;\nMat curWarpedImage;\n\nalpr::Config config(\"us\");\n\nconst string WINDOW_NAME = \"Adjust OpenALPR Perspective\";\n\nstring get_config()\n{\n stringstream output;\n output << \"planar,\" << std::fixed;\n output << w << \",\" << h << \",\";\n output << rotationx << \",\" << rotationy << \",\" << rotationz << \",\";\n output << stretchX << \",\" << dist << \",\";\n output << panX << \",\" << panY;\n \n return output.str();\n}\n\nvoid drawImage(Mat img)\n{ \n\n config.prewarp = get_config();\n alpr::PreWarp prewarp(&config);\n \n\n if (!left_clicking)\n {\n curWarpedImage = prewarp.warpImage(img);\n }\n\n \n Mat imgWithInstructions(curWarpedImage.rows + INSTRUCTIONS_HEIGHT, curWarpedImage.cols, curWarpedImage.type());\n \n curWarpedImage.copyTo(imgWithInstructions(Rect(0, INSTRUCTIONS_HEIGHT, curWarpedImage.cols, curWarpedImage.rows)));\n\n if (left_clicking)\n {\n Point start = left_click_start;\n Point end = left_click_cur;\n start.y += INSTRUCTIONS_HEIGHT;\n end.y += INSTRUCTIONS_HEIGHT;\n rectangle(imgWithInstructions, start, end, Scalar(255,0,255), 2);\n }\n \n rectangle(imgWithInstructions, Point(0,0), Point(curWarpedImage.cols, INSTRUCTIONS_HEIGHT), Scalar(255,255,255), -1);\n\n putText(imgWithInstructions, \"Press 'o' to output config to console.\", \n Point(5,25), FONT_HERSHEY_DUPLEX, 1.0, Scalar(0,0,0));\n \n \n imshow(WINDOW_NAME, imgWithInstructions);\n \n}\n\n\n\n\nvoid mouse_callback(int event, int x, int y, int flags, void* userdata)\n{\n y = y - INSTRUCTIONS_HEIGHT;\n if (y < 0)\n return;\n \n \n if (event == EVENT_RBUTTONDOWN)\n {\n lastPos.x = x;\n lastPos.y = y;\n panning = true;\n }\n if (event == EVENT_RBUTTONUP)\n {\n panning = false;\n drawImage(imgOriginal);\n }\n if (event == EVENT_MOUSEMOVE && panning)\n {\n int xdiff = x - lastPos.x;\n int ydiff = y - lastPos.y;\n panX -= xdiff;\n panY -= ydiff;\n \n lastPos.x = x;\n lastPos.y = y;\n \n \/\/ Reduce the computation by only doing it every 3rd pixel\n if (x % 3 == 0 && y % 3 == 0)\n {\n drawImage(imgOriginal);\n }\n }\n \n if (event == EVENT_LBUTTONDOWN)\n {\n left_click_start.x = x;\n left_click_start.y = y;\n left_clicking = true;\n }\n if (event == EVENT_LBUTTONUP)\n {\n left_clicking = false;\n drawImage(imgOriginal);\n }\n if (event == EVENT_MOUSEMOVE && left_clicking)\n {\n left_click_cur.x = x;\n \n float IDEAL_PLATE_RATIO = config.charWidthMM \/ config.charHeightMM;\n float curWidth = left_click_cur.x - left_click_start.x;\n \n left_click_cur.y = left_click_start.y + (IDEAL_PLATE_RATIO * curWidth);\n \n \/\/ Reduce the computation by only doing it every 3rd pixel\n if (x % 2 == 0 || y % 2 == 0)\n {\n drawImage(imgOriginal);\n }\n }\n \n}\n\nvoid ZChange(int pos, void* userdata)\n{\n \n rotationz = -((float)pos - 100) \/ 100.0;\n\n drawImage(imgOriginal);\n}\n\nvoid XChange(int pos, void* userdata)\n{\n \n rotationx = -((float)pos - 100) \/ 20000.0;\n \n drawImage(imgOriginal);\n}\n\n\nvoid YChange(int pos, void* userdata)\n{\n rotationy = ((float)pos - 100) \/ 20000.0;\n \n drawImage(imgOriginal);\n}\n\n\nvoid DistChange(int pos, void* userdata)\n{\n dist = 1.0 - ((float)pos - 100) \/ 200.0;\n \n drawImage(imgOriginal);\n}\n\nvoid StretchChange(int pos, void* userdata)\n{\n stretchX = 1.0 + ((float)pos - 100) \/ -200.0;\n \n drawImage(imgOriginal);\n}\n\n\nint value;\nvoid create_window()\n{\n namedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED);\n \n \n value = 100;\n panX = 0;\n panY = 0;\n\n XChange(100, NULL);\n YChange(100, NULL);\n ZChange(100, NULL);\n DistChange(100, NULL);\n \n \n createTrackbar( \"X\", WINDOW_NAME, &value, 200, XChange);\n createTrackbar( \"Y\", WINDOW_NAME, &value, 200, YChange);\n createTrackbar( \"Z\", WINDOW_NAME, &value, 200, ZChange);\n createTrackbar( \"W\", WINDOW_NAME, &value, 200, StretchChange);\n createTrackbar( \"D\", WINDOW_NAME, &value, 200, DistChange);\n\n \n setMouseCallback(WINDOW_NAME, mouse_callback, NULL);\n\n \n}\n\n\/*\n * \n *\/\nint main(int argc, char** argv) {\n\n\n string filename;\n string country;\n string config_path;\n string translate_config;\n int max_width;\n int max_height;\n\n TCLAP::CmdLine cmd(\"OpenAlpr Perspective Utility\", ' ', \"0.1\");\n\n TCLAP::UnlabeledValueArg<std::string> fileArg( \"image_file\", \"Image containing license plates\", true, \"\", \"image_file_path\" );\n\n TCLAP::ValueArg<std::string> countryCodeArg(\"c\",\"country\",\"Country code to identify (either us for USA or eu for Europe). Default=us\",false, \"us\" ,\"country_code\");\n \n TCLAP::ValueArg<std::string> configFileArg(\"\",\"config\",\"Path to the openalpr.conf file\",false, \"\" ,\"config_file\");\n \n TCLAP::ValueArg<std::string> translateTestArg(\"t\",\"test\",\"Test an image using the provided translation config\",false, \"\" ,\"prewarp config\");\n \n TCLAP::ValueArg<int> maxWidthArg(\"w\", \"maxwidth\", \"Max Width used for displaying image in this utility. Default=1280\",false, 1280 ,\"max width\");\n TCLAP::ValueArg<int> maxHeightArg(\"\", \"maxheight\", \"Max Height used for displaying image in this utility. Default=1024\",false, 1024 ,\"max height\");\n \n try\n {\n cmd.add( configFileArg );\n cmd.add( fileArg );\n cmd.add( countryCodeArg );\n cmd.add( translateTestArg );\n cmd.add( maxWidthArg );\n cmd.add( maxHeightArg );\n\n \n if (cmd.parse( argc, argv ) == false)\n {\n \/\/ Error occured while parsing. Exit now.\n return 1;\n }\n\n filename = fileArg.getValue();\n country = countryCodeArg.getValue();\n config_path = configFileArg.getValue();\n translate_config = translateTestArg.getValue();\n max_width = maxWidthArg.getValue();\n max_height = maxHeightArg.getValue();\n\n }\n catch (TCLAP::ArgException &e) \/\/ catch any exceptions\n {\n std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n return 1;\n }\n \n if (!alpr::fileExists(filename.c_str()))\n {\n cerr << \"Could not find image file: \" << filename << endl;\n }\n \n config = alpr::Config(country);\n \n panning = false;\n left_clicking = false;\n\n \n imgOriginal = imread(filename);\n \n if (imgOriginal.cols > max_width)\n {\n float aspect = max_width \/ ((float)imgOriginal.cols);\n float y = ((float)imgOriginal.rows) * aspect;\n \n resize(imgOriginal, imgOriginal, Size((int) max_width, (int) y));\n }\n if (imgOriginal.rows > max_height)\n {\n float aspect = max_height \/ ((float)imgOriginal.rows);\n float x = ((float)imgOriginal.cols) * aspect;\n \n resize(imgOriginal, imgOriginal, Size((int) x, (int) max_height));\n }\n \n w = imgOriginal.cols;\n h = imgOriginal.rows;\n \n create_window();\n \n \n if (translate_config != \"\")\n {\n int first_comma = translate_config.find(\",\");\n \n \n string name = translate_config.substr(0, first_comma);\n stringstream ss(translate_config.substr(first_comma + 1, translate_config.length()));\n \n ss >> w;\n ss.ignore();\n ss >> h;\n ss.ignore();\n ss >> rotationx;\n ss.ignore(); \/\/ Ignore comma\n ss >> rotationy;\n ss.ignore(); \/\/ Ignore comma\n ss >> rotationz;\n ss.ignore(); \/\/ Ignore comma\n ss >> stretchX;\n ss.ignore(); \/\/ Ignore comma\n ss >> dist;\n ss.ignore(); \/\/ Ignore comma\n ss >> panX;\n ss.ignore(); \/\/ Ignore comma\n ss >> panY;\n \n }\n\n float width_ratio = w \/ ((float)imgOriginal.cols);\n float height_ratio = h \/ ((float)imgOriginal.rows);\n w = imgOriginal.cols;\n h = imgOriginal.rows;\n rotationx *=width_ratio;\n rotationy *=width_ratio;\n panX \/= width_ratio;\n panY \/= height_ratio;\n\n drawImage(imgOriginal);\n\n \n while (true)\n {\n\n char c = waitKey(15);\n\n if (c == 'o')\n {\n cout << \"prewarp = \" << get_config() << endl;\n\n }\n }\n\n cvDestroyAllWindows();\n \n \n return 0;\n}\n\n<commit_msg>Fixed incorrect aspect ratio for plate overlay in calibrate utility<commit_after>\/*\n * Copyright (c) 2015 New Designs Unlimited, LLC\n * Opensource Automated License Plate Recognition [http:\/\/www.openalpr.com]\n *\n * This file is part of OpenAlpr.\n *\n * OpenAlpr is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License\n * version 3 as published by the Free Software Foundation\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 Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/calib3d\/calib3d.hpp>\n\n#include \"support\/filesystem.h\"\n#include \"..\/tclap\/CmdLine.h\"\n#include \"prewarp.h\"\n\n#include <sstream>\n\nusing namespace std;\nusing namespace cv;\n\nconst int INSTRUCTIONS_HEIGHT = 32;\n\n\nbool panning;\nbool left_clicking;\nPoint left_click_start;\nPoint left_click_cur;\n\n\nPoint lastPos;\n\nfloat w;\nfloat h;\nfloat panX = 0;\nfloat panY = 0;\nfloat rotationx = 0;\nfloat rotationy = 0;\nfloat rotationz = 0;\nfloat stretchX = 1.0;\nfloat dist = 1.0;\n\nMat imgOriginal;\nMat curWarpedImage;\n\nalpr::Config config(\"us\");\n\nconst string WINDOW_NAME = \"Adjust OpenALPR Perspective\";\n\nstring get_config()\n{\n stringstream output;\n output << \"planar,\" << std::fixed;\n output << w << \",\" << h << \",\";\n output << rotationx << \",\" << rotationy << \",\" << rotationz << \",\";\n output << stretchX << \",\" << dist << \",\";\n output << panX << \",\" << panY;\n \n return output.str();\n}\n\nvoid drawImage(Mat img)\n{ \n\n config.prewarp = get_config();\n alpr::PreWarp prewarp(&config);\n \n\n if (!left_clicking)\n {\n curWarpedImage = prewarp.warpImage(img);\n }\n\n \n Mat imgWithInstructions(curWarpedImage.rows + INSTRUCTIONS_HEIGHT, curWarpedImage.cols, curWarpedImage.type());\n \n curWarpedImage.copyTo(imgWithInstructions(Rect(0, INSTRUCTIONS_HEIGHT, curWarpedImage.cols, curWarpedImage.rows)));\n\n if (left_clicking)\n {\n Point start = left_click_start;\n Point end = left_click_cur;\n start.y += INSTRUCTIONS_HEIGHT;\n end.y += INSTRUCTIONS_HEIGHT;\n rectangle(imgWithInstructions, start, end, Scalar(255,0,255), 2);\n }\n \n rectangle(imgWithInstructions, Point(0,0), Point(curWarpedImage.cols, INSTRUCTIONS_HEIGHT), Scalar(255,255,255), -1);\n\n putText(imgWithInstructions, \"Press 'o' to output config to console.\", \n Point(5,25), FONT_HERSHEY_DUPLEX, 1.0, Scalar(0,0,0));\n \n \n imshow(WINDOW_NAME, imgWithInstructions);\n \n}\n\n\n\n\nvoid mouse_callback(int event, int x, int y, int flags, void* userdata)\n{\n y = y - INSTRUCTIONS_HEIGHT;\n if (y < 0)\n return;\n \n \n if (event == EVENT_RBUTTONDOWN)\n {\n lastPos.x = x;\n lastPos.y = y;\n panning = true;\n }\n if (event == EVENT_RBUTTONUP)\n {\n panning = false;\n drawImage(imgOriginal);\n }\n if (event == EVENT_MOUSEMOVE && panning)\n {\n int xdiff = x - lastPos.x;\n int ydiff = y - lastPos.y;\n panX -= xdiff;\n panY -= ydiff;\n \n lastPos.x = x;\n lastPos.y = y;\n \n \/\/ Reduce the computation by only doing it every 3rd pixel\n if (x % 3 == 0 && y % 3 == 0)\n {\n drawImage(imgOriginal);\n }\n }\n \n if (event == EVENT_LBUTTONDOWN)\n {\n left_click_start.x = x;\n left_click_start.y = y;\n left_clicking = true;\n }\n if (event == EVENT_LBUTTONUP)\n {\n left_clicking = false;\n drawImage(imgOriginal);\n }\n if (event == EVENT_MOUSEMOVE && left_clicking)\n {\n left_click_cur.x = x;\n \n float IDEAL_PLATE_RATIO = config.plateWidthMM \/ config.plateHeightMM;\n float curWidth = left_click_cur.x - left_click_start.x;\n \n left_click_cur.y = left_click_start.y + (curWidth \/ IDEAL_PLATE_RATIO );\n \n \/\/ Reduce the computation by only doing it every 3rd pixel\n if (x % 2 == 0 || y % 2 == 0)\n {\n drawImage(imgOriginal);\n }\n }\n \n}\n\nvoid ZChange(int pos, void* userdata)\n{\n \n rotationz = -((float)pos - 100) \/ 100.0;\n\n drawImage(imgOriginal);\n}\n\nvoid XChange(int pos, void* userdata)\n{\n \n rotationx = -((float)pos - 100) \/ 20000.0;\n \n drawImage(imgOriginal);\n}\n\n\nvoid YChange(int pos, void* userdata)\n{\n rotationy = ((float)pos - 100) \/ 20000.0;\n \n drawImage(imgOriginal);\n}\n\n\nvoid DistChange(int pos, void* userdata)\n{\n dist = 1.0 - ((float)pos - 100) \/ 200.0;\n \n drawImage(imgOriginal);\n}\n\nvoid StretchChange(int pos, void* userdata)\n{\n stretchX = 1.0 + ((float)pos - 100) \/ -200.0;\n \n drawImage(imgOriginal);\n}\n\n\nint value;\nvoid create_window()\n{\n namedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED);\n \n \n value = 100;\n panX = 0;\n panY = 0;\n\n XChange(100, NULL);\n YChange(100, NULL);\n ZChange(100, NULL);\n DistChange(100, NULL);\n \n \n createTrackbar( \"X\", WINDOW_NAME, &value, 200, XChange);\n createTrackbar( \"Y\", WINDOW_NAME, &value, 200, YChange);\n createTrackbar( \"Z\", WINDOW_NAME, &value, 200, ZChange);\n createTrackbar( \"W\", WINDOW_NAME, &value, 200, StretchChange);\n createTrackbar( \"D\", WINDOW_NAME, &value, 200, DistChange);\n\n \n setMouseCallback(WINDOW_NAME, mouse_callback, NULL);\n\n \n}\n\n\/*\n * \n *\/\nint main(int argc, char** argv) {\n\n\n string filename;\n string country;\n string config_path;\n string translate_config;\n int max_width;\n int max_height;\n\n TCLAP::CmdLine cmd(\"OpenAlpr Perspective Utility\", ' ', \"0.1\");\n\n TCLAP::UnlabeledValueArg<std::string> fileArg( \"image_file\", \"Image containing license plates\", true, \"\", \"image_file_path\" );\n\n TCLAP::ValueArg<std::string> countryCodeArg(\"c\",\"country\",\"Country code to identify (either us for USA or eu for Europe). Default=us\",false, \"us\" ,\"country_code\");\n \n TCLAP::ValueArg<std::string> configFileArg(\"\",\"config\",\"Path to the openalpr.conf file\",false, \"\" ,\"config_file\");\n \n TCLAP::ValueArg<std::string> translateTestArg(\"t\",\"test\",\"Test an image using the provided translation config\",false, \"\" ,\"prewarp config\");\n \n TCLAP::ValueArg<int> maxWidthArg(\"w\", \"maxwidth\", \"Max Width used for displaying image in this utility. Default=1280\",false, 1280 ,\"max width\");\n TCLAP::ValueArg<int> maxHeightArg(\"\", \"maxheight\", \"Max Height used for displaying image in this utility. Default=1024\",false, 1024 ,\"max height\");\n \n try\n {\n cmd.add( configFileArg );\n cmd.add( fileArg );\n cmd.add( countryCodeArg );\n cmd.add( translateTestArg );\n cmd.add( maxWidthArg );\n cmd.add( maxHeightArg );\n\n \n if (cmd.parse( argc, argv ) == false)\n {\n \/\/ Error occured while parsing. Exit now.\n return 1;\n }\n\n filename = fileArg.getValue();\n country = countryCodeArg.getValue();\n config_path = configFileArg.getValue();\n translate_config = translateTestArg.getValue();\n max_width = maxWidthArg.getValue();\n max_height = maxHeightArg.getValue();\n\n }\n catch (TCLAP::ArgException &e) \/\/ catch any exceptions\n {\n std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n return 1;\n }\n \n if (!alpr::fileExists(filename.c_str()))\n {\n cerr << \"Could not find image file: \" << filename << endl;\n }\n \n config = alpr::Config(country);\n \n panning = false;\n left_clicking = false;\n\n \n imgOriginal = imread(filename);\n \n if (imgOriginal.cols > max_width)\n {\n float aspect = max_width \/ ((float)imgOriginal.cols);\n float y = ((float)imgOriginal.rows) * aspect;\n \n resize(imgOriginal, imgOriginal, Size((int) max_width, (int) y));\n }\n if (imgOriginal.rows > max_height)\n {\n float aspect = max_height \/ ((float)imgOriginal.rows);\n float x = ((float)imgOriginal.cols) * aspect;\n \n resize(imgOriginal, imgOriginal, Size((int) x, (int) max_height));\n }\n \n w = imgOriginal.cols;\n h = imgOriginal.rows;\n \n create_window();\n \n \n if (translate_config != \"\")\n {\n int first_comma = translate_config.find(\",\");\n \n \n string name = translate_config.substr(0, first_comma);\n stringstream ss(translate_config.substr(first_comma + 1, translate_config.length()));\n \n ss >> w;\n ss.ignore();\n ss >> h;\n ss.ignore();\n ss >> rotationx;\n ss.ignore(); \/\/ Ignore comma\n ss >> rotationy;\n ss.ignore(); \/\/ Ignore comma\n ss >> rotationz;\n ss.ignore(); \/\/ Ignore comma\n ss >> stretchX;\n ss.ignore(); \/\/ Ignore comma\n ss >> dist;\n ss.ignore(); \/\/ Ignore comma\n ss >> panX;\n ss.ignore(); \/\/ Ignore comma\n ss >> panY;\n \n }\n\n float width_ratio = w \/ ((float)imgOriginal.cols);\n float height_ratio = h \/ ((float)imgOriginal.rows);\n w = imgOriginal.cols;\n h = imgOriginal.rows;\n rotationx *=width_ratio;\n rotationy *=width_ratio;\n panX \/= width_ratio;\n panY \/= height_ratio;\n\n drawImage(imgOriginal);\n\n \n while (true)\n {\n\n char c = waitKey(15);\n\n if (c == 'o')\n {\n cout << \"prewarp = \" << get_config() << endl;\n\n }\n }\n\n cvDestroyAllWindows();\n \n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\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 \"open_spiel\/algorithms\/state_distribution.h\"\n\n#include \"open_spiel\/abseil-cpp\/absl\/algorithm\/container.h\"\n#include \"open_spiel\/policy.h\"\n#include \"open_spiel\/spiel.h\"\n#include \"open_spiel\/spiel_utils.h\"\n\nnamespace open_spiel {\nnamespace algorithms {\nnamespace {\n\n\nvoid KuhnStateDistributionTest() {\n std::shared_ptr<const Game> game = LoadGame(\"kuhn_poker\");\n std::unique_ptr<State> state = game->NewInitialState();\n TabularPolicy uniform_policy = GetUniformPolicy(*game);\n\n \/\/ Construct the state 1b\n state->ApplyAction(0); \/\/ p0 card: jack\n state->ApplyAction(1); \/\/ p1 card: queen\n state->ApplyAction(1); \/\/ player 0 bet\n SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);\n SPIEL_CHECK_EQ(state->InformationStateString(), \"1b\");\n HistoryDistribution dist = GetStateDistribution(*state, &uniform_policy);\n\n SPIEL_CHECK_EQ(dist.first.size(), 2);\n SPIEL_CHECK_EQ(dist.second.size(), 2);\n\n \/\/ Check that sampled states have private cards jack and king for the opponent\n SPIEL_CHECK_TRUE(dist.first[0]->InformationStateString(0) == \"0b\" ||\n dist.first[0]->InformationStateString(0) == \"2b\");\n SPIEL_CHECK_TRUE(dist.first[1]->InformationStateString(0) == \"0b\" ||\n dist.first[1]->InformationStateString(0) == \"2b\");\n SPIEL_CHECK_NE(dist.first[0]->InformationStateString(0),\n dist.first[1]->InformationStateString(0));\n\n \/\/ Check that they are equally likely, and sum to 1\n SPIEL_CHECK_EQ(dist.second[0], 0.5);\n SPIEL_CHECK_EQ(dist.second[0], 0.5);\n}\n\nvoid CompareDists(const HistoryDistribution& lhs,\n const HistoryDistribution& rhs) {\n for (int i = 0; i < lhs.first.size(); ++i) {\n std::cerr << \"lhs[\" << i << \"]: \" << lhs.first[i]->HistoryString()\n << \", p: \" << lhs.second[i] << std::endl;\n std::cerr << \"rhs[\" << i << \"]: \" << rhs.first[i]->HistoryString()\n << \", p: \" << rhs.second[i] << std::endl;\n }\n for (int i = 0; i < lhs.first.size(); ++i) {\n for (int j = 0; j < rhs.first.size(); ++j) {\n if (lhs.first[i]->History() == rhs.first[j]->History()) {\n SPIEL_CHECK_FLOAT_EQ(lhs.second[i], rhs.second[j]);\n break;\n }\n }\n }\n}\n\nvoid LeducStateDistributionTest() {\n std::shared_ptr<const Game> game = LoadGame(\"leduc_poker\");\n std::unique_ptr<State> state = game->NewInitialState();\n TabularPolicy uniform_policy = GetUniformPolicy(*game);\n state->ApplyAction(0); \/\/ p0 card: jack of first suit\n state->ApplyAction(1); \/\/ p1 card: queen of first suit\n state->ApplyAction(1); \/\/ player 0 bet\n std::string info_state_string = state->InformationStateString();\n std::string state_history_string = state->HistoryString();\n SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);\n HistoryDistribution dist = GetStateDistribution(*state, &uniform_policy);\n HistoryDistribution incremental_dist = UpdateIncrementalStateDistribution(\n *state, &uniform_policy, \/*player_id=*\/1);\n std::cerr << \"Comparing dists 1...\" << std::endl;\n CompareDists(dist, incremental_dist);\n\n std::vector<double> correct_distribution(5, 0.2);\n SPIEL_CHECK_EQ(dist.first.size(), 5);\n SPIEL_CHECK_EQ(dist.second, correct_distribution);\n\n \/\/ Check that none of the states are equal, that one of them is equal to the\n \/\/ state used to generate the distribution, and that they are all equally\n \/\/ likely with probability 0.2.\n int state_matches = 0;\n for (int i = 0; i < dist.first.size(); ++i) {\n SPIEL_CHECK_EQ(dist.first[i]->InformationStateString(), info_state_string);\n if (dist.first[i]->HistoryString() == state_history_string) {\n state_matches++;\n }\n for (int j = i + 1; j < dist.first.size(); ++j) {\n SPIEL_CHECK_NE(dist.first[i]->HistoryString(),\n dist.first[j]->HistoryString());\n }\n }\n SPIEL_CHECK_EQ(state_matches, 1);\n\n \/\/ Now, it's a chance node...\n state->ApplyAction(state->LegalActions()[0]);\n incremental_dist =\n UpdateIncrementalStateDistribution(*state, &uniform_policy,\n \/*player_id=*\/1, incremental_dist);\n state->ApplyAction(state->LegalActions()[0]);\n dist = GetStateDistribution(*state, &uniform_policy);\n incremental_dist =\n UpdateIncrementalStateDistribution(*state, &uniform_policy,\n \/*player_id=*\/1, incremental_dist);\n std::cerr << \"Comparing dists 2...\" << std::endl;\n SPIEL_CHECK_FLOAT_EQ(absl::c_accumulate(dist.second, 0.), 1.);\n SPIEL_CHECK_FLOAT_EQ(absl::c_accumulate(incremental_dist.second, 0.), 1.);\n CompareDists(dist, incremental_dist);\n}\n\nconstexpr absl::string_view kHUNLGameString =\n (\"universal_poker(betting=limit,numPlayers=2,numRounds=4,stack=1200 \"\n \"1200,blind=50 100,firstPlayer=2 \"\n \"1,numSuits=4,numRanks=13,numHoleCards=2,numBoardCards=0 3 1 \"\n \"1,raiseSize=100 100 100 100)\");\n\nvoid HULIncrementalTest() {\n std::shared_ptr<const Game> game = LoadGame(std::string(kHUNLGameString));\n UniformPolicy policy;\n std::unique_ptr<State> state = game->NewInitialState();\n while (state->IsChanceNode()) state->ApplyAction(state->LegalActions()[0]);\n HistoryDistribution inc_dist =\n UpdateIncrementalStateDistribution(*state, &policy, \/*player_id=*\/0);\n SPIEL_CHECK_EQ(inc_dist.second.size(), 1225);\n SPIEL_CHECK_FLOAT_EQ(absl::c_accumulate(inc_dist.second, 0.), 1.);\n}\n\n\n} \/\/ namespace\n} \/\/ namespace algorithms\n} \/\/ namespace open_spiel\n\nnamespace algorithms = open_spiel::algorithms;\n\nint main(int argc, char** argv) {\n algorithms::KuhnStateDistributionTest();\n algorithms::LeducStateDistributionTest();\n algorithms::HULIncrementalTest();\n}\n<commit_msg>Fix state_distribution_test when ACPC is not enabled.<commit_after>\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\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 \"open_spiel\/algorithms\/state_distribution.h\"\n\n#include \"open_spiel\/abseil-cpp\/absl\/algorithm\/container.h\"\n#include \"open_spiel\/policy.h\"\n#include \"open_spiel\/spiel.h\"\n#include \"open_spiel\/spiel_utils.h\"\n\nnamespace open_spiel {\nnamespace algorithms {\nnamespace {\n\n\nvoid KuhnStateDistributionTest() {\n std::shared_ptr<const Game> game = LoadGame(\"kuhn_poker\");\n std::unique_ptr<State> state = game->NewInitialState();\n TabularPolicy uniform_policy = GetUniformPolicy(*game);\n\n \/\/ Construct the state 1b\n state->ApplyAction(0); \/\/ p0 card: jack\n state->ApplyAction(1); \/\/ p1 card: queen\n state->ApplyAction(1); \/\/ player 0 bet\n SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);\n SPIEL_CHECK_EQ(state->InformationStateString(), \"1b\");\n HistoryDistribution dist = GetStateDistribution(*state, &uniform_policy);\n\n SPIEL_CHECK_EQ(dist.first.size(), 2);\n SPIEL_CHECK_EQ(dist.second.size(), 2);\n\n \/\/ Check that sampled states have private cards jack and king for the opponent\n SPIEL_CHECK_TRUE(dist.first[0]->InformationStateString(0) == \"0b\" ||\n dist.first[0]->InformationStateString(0) == \"2b\");\n SPIEL_CHECK_TRUE(dist.first[1]->InformationStateString(0) == \"0b\" ||\n dist.first[1]->InformationStateString(0) == \"2b\");\n SPIEL_CHECK_NE(dist.first[0]->InformationStateString(0),\n dist.first[1]->InformationStateString(0));\n\n \/\/ Check that they are equally likely, and sum to 1\n SPIEL_CHECK_EQ(dist.second[0], 0.5);\n SPIEL_CHECK_EQ(dist.second[0], 0.5);\n}\n\nvoid CompareDists(const HistoryDistribution& lhs,\n const HistoryDistribution& rhs) {\n for (int i = 0; i < lhs.first.size(); ++i) {\n std::cerr << \"lhs[\" << i << \"]: \" << lhs.first[i]->HistoryString()\n << \", p: \" << lhs.second[i] << std::endl;\n std::cerr << \"rhs[\" << i << \"]: \" << rhs.first[i]->HistoryString()\n << \", p: \" << rhs.second[i] << std::endl;\n }\n for (int i = 0; i < lhs.first.size(); ++i) {\n for (int j = 0; j < rhs.first.size(); ++j) {\n if (lhs.first[i]->History() == rhs.first[j]->History()) {\n SPIEL_CHECK_FLOAT_EQ(lhs.second[i], rhs.second[j]);\n break;\n }\n }\n }\n}\n\nvoid LeducStateDistributionTest() {\n std::shared_ptr<const Game> game = LoadGame(\"leduc_poker\");\n std::unique_ptr<State> state = game->NewInitialState();\n TabularPolicy uniform_policy = GetUniformPolicy(*game);\n state->ApplyAction(0); \/\/ p0 card: jack of first suit\n state->ApplyAction(1); \/\/ p1 card: queen of first suit\n state->ApplyAction(1); \/\/ player 0 bet\n std::string info_state_string = state->InformationStateString();\n std::string state_history_string = state->HistoryString();\n SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);\n HistoryDistribution dist = GetStateDistribution(*state, &uniform_policy);\n HistoryDistribution incremental_dist = UpdateIncrementalStateDistribution(\n *state, &uniform_policy, \/*player_id=*\/1);\n std::cerr << \"Comparing dists 1...\" << std::endl;\n CompareDists(dist, incremental_dist);\n\n std::vector<double> correct_distribution(5, 0.2);\n SPIEL_CHECK_EQ(dist.first.size(), 5);\n SPIEL_CHECK_EQ(dist.second, correct_distribution);\n\n \/\/ Check that none of the states are equal, that one of them is equal to the\n \/\/ state used to generate the distribution, and that they are all equally\n \/\/ likely with probability 0.2.\n int state_matches = 0;\n for (int i = 0; i < dist.first.size(); ++i) {\n SPIEL_CHECK_EQ(dist.first[i]->InformationStateString(), info_state_string);\n if (dist.first[i]->HistoryString() == state_history_string) {\n state_matches++;\n }\n for (int j = i + 1; j < dist.first.size(); ++j) {\n SPIEL_CHECK_NE(dist.first[i]->HistoryString(),\n dist.first[j]->HistoryString());\n }\n }\n SPIEL_CHECK_EQ(state_matches, 1);\n\n \/\/ Now, it's a chance node...\n state->ApplyAction(state->LegalActions()[0]);\n incremental_dist =\n UpdateIncrementalStateDistribution(*state, &uniform_policy,\n \/*player_id=*\/1, incremental_dist);\n state->ApplyAction(state->LegalActions()[0]);\n dist = GetStateDistribution(*state, &uniform_policy);\n incremental_dist =\n UpdateIncrementalStateDistribution(*state, &uniform_policy,\n \/*player_id=*\/1, incremental_dist);\n std::cerr << \"Comparing dists 2...\" << std::endl;\n SPIEL_CHECK_FLOAT_EQ(absl::c_accumulate(dist.second, 0.), 1.);\n SPIEL_CHECK_FLOAT_EQ(absl::c_accumulate(incremental_dist.second, 0.), 1.);\n CompareDists(dist, incremental_dist);\n}\n\nconstexpr absl::string_view kHUNLGameString =\n (\"universal_poker(betting=limit,numPlayers=2,numRounds=4,stack=1200 \"\n \"1200,blind=50 100,firstPlayer=2 \"\n \"1,numSuits=4,numRanks=13,numHoleCards=2,numBoardCards=0 3 1 \"\n \"1,raiseSize=100 100 100 100)\");\n\nvoid HUNLIncrementalTest() {\n std::shared_ptr<const Game> game = LoadGame(std::string(kHUNLGameString));\n UniformPolicy policy;\n std::unique_ptr<State> state = game->NewInitialState();\n while (state->IsChanceNode()) state->ApplyAction(state->LegalActions()[0]);\n HistoryDistribution inc_dist =\n UpdateIncrementalStateDistribution(*state, &policy, \/*player_id=*\/0);\n SPIEL_CHECK_EQ(inc_dist.second.size(), 1225);\n SPIEL_CHECK_FLOAT_EQ(absl::c_accumulate(inc_dist.second, 0.), 1.);\n}\n\n\n} \/\/ namespace\n} \/\/ namespace algorithms\n} \/\/ namespace open_spiel\n\nnamespace algorithms = open_spiel::algorithms;\n\nint main(int argc, char** argv) {\n algorithms::KuhnStateDistributionTest();\n algorithms::LeducStateDistributionTest();\n\n \/\/ ACPC is an optional dependency. Only test HUNL if it is registered.\n if (open_spiel::IsGameRegistered(std::string(algorithms::kHUNLGameString))) {\n algorithms::HUNLIncrementalTest();\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>GPU Calc: Fix Not support multiple data types of KURT<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: basmethnode.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2004-10-22 14:01:40 $\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 SCRIPTING_BASMETHNODE_HXX\n#define SCRIPTING_BASMETHNODE_HXX\n\n#ifndef SCRIPTING_BCHOLDER_HXX\n#include \"bcholder.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_\n#include <com\/sun\/star\/script\/XInvocation.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SCRIPT_BROWSE_XBROWSENODE_HPP_\n#include <com\/sun\/star\/script\/browse\/XBrowseNode.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#endif\n\n#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_\n#include <comphelper\/proparrhlp.hxx>\n#endif\n#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_\n#include <comphelper\/propertycontainer.hxx>\n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include <cppuhelper\/implbase2.hxx>\n#endif\n\n\nclass SbMethod;\n\n\n\/\/.........................................................................\nnamespace basprov\n{\n\/\/.........................................................................\n\n \/\/ ----------------------------------------------------\n \/\/ class BasicMethodNodeImpl\n \/\/ ----------------------------------------------------\n\n typedef ::cppu::WeakImplHelper2<\n ::com::sun::star::script::browse::XBrowseNode,\n ::com::sun::star::script::XInvocation > BasicMethodNodeImpl_BASE;\n\n class BasicMethodNodeImpl : public BasicMethodNodeImpl_BASE,\n public ::scripting_helper::OBroadcastHelperHolder,\n public ::comphelper::OPropertyContainer,\n public ::comphelper::OPropertyArrayUsageHelper< BasicMethodNodeImpl >\n {\n private:\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;\n ::rtl::OUString m_sScriptingContext;\n SbMethod* m_pMethod;\n bool m_bIsAppScript;\n\n \/\/ properties\n ::rtl::OUString m_sURI;\n sal_Bool m_bEditable;\n\n protected:\n \/\/ OPropertySetHelper\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper( );\n\n \/\/ OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;\n\n public:\n BasicMethodNodeImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,\n const ::rtl::OUString& sScriptingContext,\n SbMethod* pMethod, bool isAppScript = true );\n virtual ~BasicMethodNodeImpl();\n\n \/\/ XInterface\n DECLARE_XINTERFACE()\n\n \/\/ XTypeProvider\n DECLARE_XTYPEPROVIDER()\n\n \/\/ XBrowseNode\n virtual ::rtl::OUString SAL_CALL getName( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > > SAL_CALL getChildNodes( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasChildNodes( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getType( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XInvocation\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess > SAL_CALL getIntrospection( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL invoke(\n const ::rtl::OUString& aFunctionName,\n const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aParams,\n ::com::sun::star::uno::Sequence< sal_Int16 >& aOutParamIndex,\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aOutParam )\n throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::script::CannotConvertException,\n ::com::sun::star::reflection::InvocationTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::script::CannotConvertException,\n ::com::sun::star::reflection::InvocationTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getValue( const ::rtl::OUString& aPropertyName )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasMethod( const ::rtl::OUString& aName )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasProperty( const ::rtl::OUString& aName )\n throw (::com::sun::star::uno::RuntimeException);\n };\n\n\/\/.........................................................................\n} \/\/ namespace basprov\n\/\/.........................................................................\n\n#endif \/\/ SCRIPTING_BASMETHNODE_HXX\n<commit_msg>INTEGRATION: CWS tbe15 (1.6.12); FILE MERGED 2004\/12\/03 16:23:07 tbe 1.6.12.1: #i38139# Tools\/Macro\/Run Macro freezes office when Basic macro is already running<commit_after>\/*************************************************************************\n *\n * $RCSfile: basmethnode.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2005-01-13 17:42:44 $\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 SCRIPTING_BASMETHNODE_HXX\n#define SCRIPTING_BASMETHNODE_HXX\n\n#ifndef SCRIPTING_BCHOLDER_HXX\n#include \"bcholder.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_\n#include <com\/sun\/star\/script\/XInvocation.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SCRIPT_BROWSE_XBROWSENODE_HPP_\n#include <com\/sun\/star\/script\/browse\/XBrowseNode.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#endif\n\n#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_\n#include <comphelper\/proparrhlp.hxx>\n#endif\n#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_\n#include <comphelper\/propertycontainer.hxx>\n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include <cppuhelper\/implbase2.hxx>\n#endif\n\n\nclass SbMethod;\n\n\n\/\/.........................................................................\nnamespace basprov\n{\n\/\/.........................................................................\n\n \/\/ ----------------------------------------------------\n \/\/ class BasicMethodNodeImpl\n \/\/ ----------------------------------------------------\n\n typedef ::cppu::WeakImplHelper2<\n ::com::sun::star::script::browse::XBrowseNode,\n ::com::sun::star::script::XInvocation > BasicMethodNodeImpl_BASE;\n\n class BasicMethodNodeImpl : public BasicMethodNodeImpl_BASE,\n public ::scripting_helper::OMutexHolder,\n public ::scripting_helper::OBroadcastHelperHolder,\n public ::comphelper::OPropertyContainer,\n public ::comphelper::OPropertyArrayUsageHelper< BasicMethodNodeImpl >\n {\n private:\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;\n ::rtl::OUString m_sScriptingContext;\n SbMethod* m_pMethod;\n bool m_bIsAppScript;\n\n \/\/ properties\n ::rtl::OUString m_sURI;\n sal_Bool m_bEditable;\n\n protected:\n \/\/ OPropertySetHelper\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper( );\n\n \/\/ OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;\n\n public:\n BasicMethodNodeImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,\n const ::rtl::OUString& sScriptingContext,\n SbMethod* pMethod, bool isAppScript = true );\n virtual ~BasicMethodNodeImpl();\n\n \/\/ XInterface\n DECLARE_XINTERFACE()\n\n \/\/ XTypeProvider\n DECLARE_XTYPEPROVIDER()\n\n \/\/ XBrowseNode\n virtual ::rtl::OUString SAL_CALL getName( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > > SAL_CALL getChildNodes( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasChildNodes( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getType( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XInvocation\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess > SAL_CALL getIntrospection( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL invoke(\n const ::rtl::OUString& aFunctionName,\n const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aParams,\n ::com::sun::star::uno::Sequence< sal_Int16 >& aOutParamIndex,\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aOutParam )\n throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::script::CannotConvertException,\n ::com::sun::star::reflection::InvocationTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::script::CannotConvertException,\n ::com::sun::star::reflection::InvocationTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getValue( const ::rtl::OUString& aPropertyName )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasMethod( const ::rtl::OUString& aName )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasProperty( const ::rtl::OUString& aName )\n throw (::com::sun::star::uno::RuntimeException);\n };\n\n\/\/.........................................................................\n} \/\/ namespace basprov\n\/\/.........................................................................\n\n#endif \/\/ SCRIPTING_BASMETHNODE_HXX\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2012.\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#include \"likely.hpp\"\n\n#include \"mtac\/BranchOptimizations.hpp\"\n#include \"mtac\/Function.hpp\"\n#include \"mtac\/ControlFlowGraph.hpp\"\n#include \"mtac\/Statement.hpp\"\n\nusing namespace eddic;\n\nbool mtac::optimize_branches::operator()(mtac::Function& function){\n bool optimized = false;\n \n for(auto& block : function){\n for(auto& statement : block->statements){\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){\n if(boost::get<int>(&*(*ptr)->arg1)){\n int value = boost::get<int>(*(*ptr)->arg1);\n\n if((*ptr)->op == mtac::Operator::IF_FALSE_UNARY){\n\n if(value == 0){\n auto goto_ = std::make_shared<mtac::Quadruple>((*ptr)->label(), mtac::Operator::GOTO);\n goto_->block = (*ptr)->block;\n\n statement = goto_;\n optimized = true;\n\n mtac::remove_edge(block, block->next);\n } else if(value == 1){\n mtac::remove_edge(block, (*ptr)->block);\n\n statement = std::make_shared<mtac::Quadruple>(mtac::Operator::NOP);\n optimized = true;\n }\n } else if((*ptr)->op == mtac::Operator::IF_UNARY){\n if(value == 0){\n mtac::remove_edge(block, (*ptr)->block);\n\n statement = std::make_shared<mtac::Quadruple>(mtac::Operator::NOP);\n optimized = true;\n } else if(value == 1){\n auto goto_ = std::make_shared<mtac::Quadruple>((*ptr)->label(), mtac::Operator::GOTO);\n goto_->block = (*ptr)->block;\n\n statement = goto_;\n optimized = true;\n\n mtac::remove_edge(block, block->next);\n }\n }\n }\n } \n }\n }\n\n return optimized;\n}\n<commit_msg>Fix bug: not all quadruple have their first arg set<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2012.\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#include \"likely.hpp\"\n\n#include \"mtac\/BranchOptimizations.hpp\"\n#include \"mtac\/Function.hpp\"\n#include \"mtac\/ControlFlowGraph.hpp\"\n#include \"mtac\/Statement.hpp\"\n\nusing namespace eddic;\n\nbool mtac::optimize_branches::operator()(mtac::Function& function){\n bool optimized = false;\n \n for(auto& block : function){\n for(auto& statement : block->statements){\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){\n if((*ptr)->op == mtac::Operator::IF_FALSE_UNARY && boost::get<int>(&*(*ptr)->arg1)){\n int value = boost::get<int>(*(*ptr)->arg1);\n\n if(value == 0){\n auto goto_ = std::make_shared<mtac::Quadruple>((*ptr)->label(), mtac::Operator::GOTO);\n goto_->block = (*ptr)->block;\n\n statement = goto_;\n optimized = true;\n\n mtac::remove_edge(block, block->next);\n } else if(value == 1){\n mtac::remove_edge(block, (*ptr)->block);\n\n statement = std::make_shared<mtac::Quadruple>(mtac::Operator::NOP);\n optimized = true;\n }\n } else if((*ptr)->op == mtac::Operator::IF_UNARY && boost::get<int>(&*(*ptr)->arg1)){\n int value = boost::get<int>(*(*ptr)->arg1);\n\n if(value == 0){\n mtac::remove_edge(block, (*ptr)->block);\n\n statement = std::make_shared<mtac::Quadruple>(mtac::Operator::NOP);\n optimized = true;\n } else if(value == 1){\n auto goto_ = std::make_shared<mtac::Quadruple>((*ptr)->label(), mtac::Operator::GOTO);\n goto_->block = (*ptr)->block;\n\n statement = goto_;\n optimized = true;\n\n mtac::remove_edge(block, block->next);\n }\n }\n } \n }\n }\n\n return optimized;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2016 musikcube team\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 are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdafx.h>\n#include \"Colors.h\"\n\nusing namespace cursespp;\n\n\/* if the terminal supports custom colors, these are the palette\nindicies we'll use to store them *\/\n#define COLOR_CUSTOM_WHITE 16\n#define COLOR_CUSTOM_BLUE 17\n#define COLOR_CUSTOM_RED 18\n#define COLOR_CUSTOM_YELLOW 19\n#define COLOR_CUSTOM_GREEN 20\n#define COLOR_CUSTOM_BLACK 21\n#define COLOR_CUSTOM_GREY 22\n#define COLOR_CUSTOM_SELECTED_LIST_ITEM_BG 23\n#define COLOR_CUSTOM_ORANGE 24\n#define COLOR_CUSTOM_DARK_RED 25\n\n\/* if we can't set custom colors, but we have the full 256 color\npalette, use ones that most closely match our desired colors *\/\n#define COLOR_256_GREEN 148\n#define COLOR_256_RED 167\n#define COLOR_256_DARK_RED 160\n#define COLOR_256_YELLOW 185\n#define COLOR_256_MEDIUM_GRAY 240\n#define COLOR_256_ORANGE 208 \n#define COLOR_256_BLUE 123 \n#define COLOR_256_OFFWHITE 251\n\n\/* vars that hold our actual color definitions. these may change\nlater during init if the terminal supports > 8 colors *\/\nstatic int white = COLOR_WHITE;\nstatic int blue = COLOR_BLUE;\nstatic int red = COLOR_RED;\nstatic int darkRed = COLOR_RED;\nstatic int yellow = COLOR_YELLOW;\nstatic int green = COLOR_GREEN;\nstatic int black = COLOR_BLACK;\nstatic int orange = COLOR_YELLOW;\nstatic int foreground = COLOR_WHITE;\nstatic int background = -1;\nstatic int selected = -1;\nstatic int grey = COLOR_WHITE;\n\n#define SCALE(x) ((x * 1000) \/ 255)\n\nstatic int initColor(int id, int r, int g, int b) {\n init_color(id, SCALE(r), SCALE(g), SCALE(b));\n return id;\n}\n\n\/* some terminals report custom colors are supported, and also\ndon't error when calling init_color(), but don't actually work. *\/\nstatic bool customColorsSupported() {\n if (COLORS <= 8) {\n return false;\n }\n\n#ifdef WIN32\n return true;\n#else\n const char* termEnv = std::getenv(\"TERM_PROGRAM\");\n std::string term;\n if (termEnv && strlen(termEnv)) {\n term = std::string(termEnv);\n }\n return term != \"Apple_Terminal\";\n#endif\n}\n\nColors::Colors() {\n}\n\nvoid Colors::Init(bool disableCustomColors) {\n start_color();\n use_default_colors();\n\n bool hasCustomColors = !disableCustomColors && customColorsSupported();\n\n \/* the default colors are a bit harsh for my taste, so\n let's use custom colors if the terminal supports it. in\n the future we'll allow users to configure this via setting *\/\n if (hasCustomColors) {\n if (can_change_color()) {\n red = initColor(COLOR_CUSTOM_RED, 220, 82, 86);\n darkRed = initColor(COLOR_CUSTOM_DARK_RED, 175, 66, 71);\n green = initColor(COLOR_CUSTOM_GREEN, 166, 226, 46);\n yellow = initColor(COLOR_CUSTOM_YELLOW, 230, 220, 116);\n selected = initColor(COLOR_CUSTOM_SELECTED_LIST_ITEM_BG, 66, 66, 56);\n grey = initColor(COLOR_CUSTOM_GREY, 128, 128, 128);\n orange = initColor(COLOR_CUSTOM_ORANGE, 255, 150, 32);\n blue = initColor(COLOR_CUSTOM_BLUE, 102, 217, 238);\n white = initColor(COLOR_CUSTOM_WHITE, 230, 230, 230);\n foreground = COLOR_CUSTOM_WHITE;\n }\n else {\n green = COLOR_256_GREEN;\n red = COLOR_256_RED;\n darkRed = COLOR_256_DARK_RED;\n yellow = COLOR_256_YELLOW;\n selected = COLOR_256_MEDIUM_GRAY;\n grey = COLOR_256_MEDIUM_GRAY;\n orange = COLOR_256_ORANGE; \n blue = COLOR_256_BLUE;\n white = COLOR_256_OFFWHITE;\n foreground = COLOR_256_OFFWHITE; \n }\n }\n\n init_pair(CURSESPP_SELECTED_LIST_ITEM, yellow, selected);\n init_pair(CURSESPP_HIGHLIGHTED_LIST_ITEM, black, green);\n init_pair(CURSESPP_HIGHLIGHTED_SELECTED_LIST_ITEM, black, yellow);\n init_pair(CURSESPP_LIST_ITEM_HEADER, green, background);\n\n init_pair(CURSESPP_DEFAULT_CONTENT_COLOR, foreground, background);\n init_pair(CURSESPP_DEFAULT_FRAME_COLOR, foreground, background);\n init_pair(CURSESPP_FOCUSED_FRAME_COLOR, red, background);\n\n init_pair(CURSESPP_TEXT_DEFAULT, white, background);\n init_pair(CURSESPP_TEXT_DISABLED, grey, background);\n init_pair(CURSESPP_TEXT_FOCUSED, red, background);\n init_pair(CURSESPP_TEXT_ACTIVE, green, background);\n init_pair(CURSESPP_TEXT_WARNING, yellow, background);\n init_pair(CURSESPP_TEXT_ERROR, red, background);\n init_pair(CURSESPP_TEXT_HIDDEN, black, background);\n init_pair(CURSESPP_TEXT_SEPARATOR, orange, background);\n\n init_pair(CURSESPP_BUTTON_NORMAL, black, yellow);\n init_pair(CURSESPP_BUTTON_NEGATIVE, white, red);\n init_pair(CURSESPP_BUTTON_HIGHLIGHTED, black, green);\n\n init_pair(CURSESPP_SHORTCUT_ROW_NORMAL, yellow, selected);\n init_pair(CURSESPP_SHORTCUT_ROW_FOCUSED, white, darkRed);\n\n init_pair(CURSESPP_OVERLAY_FRAME, blue, selected);\n init_pair(CURSESPP_OVERLAY_BACKGROUND, white, selected);\n}\n<commit_msg>More work on custom colors. Apple Terminal is now \"properly\" supported.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2016 musikcube team\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 are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdafx.h>\n#include \"Colors.h\"\n\nusing namespace cursespp;\n\n\/* if the terminal supports custom colors, these are the palette\nindicies we'll use to store them *\/\n#define COLOR_CUSTOM_WHITE 16\n#define COLOR_CUSTOM_BLUE 17\n#define COLOR_CUSTOM_RED 18\n#define COLOR_CUSTOM_YELLOW 19\n#define COLOR_CUSTOM_GREEN 20\n#define COLOR_CUSTOM_BLACK 21\n#define COLOR_CUSTOM_GREY 22\n#define COLOR_CUSTOM_SELECTED_LIST_ITEM_BG 23\n#define COLOR_CUSTOM_ORANGE 24\n#define COLOR_CUSTOM_DARK_RED 25\n\n\/* if we can't set custom colors, but we have the full 256 color\npalette, use ones that most closely match our desired colors *\/\n#define COLOR_256_GREEN 148\n#define COLOR_256_RED 167\n#define COLOR_256_DARK_RED 160\n#define COLOR_256_YELLOW 185\n#define COLOR_256_MEDIUM_GRAY 240\n#define COLOR_256_ORANGE 208\n#define COLOR_256_BLUE 123\n#define COLOR_256_OFFWHITE 251\n\n\/* vars that hold our actual color definitions. these may change\nlater during init if the terminal supports > 8 colors *\/\nstatic int white = COLOR_WHITE;\nstatic int blue = COLOR_BLUE;\nstatic int red = COLOR_RED;\nstatic int darkRed = COLOR_RED;\nstatic int yellow = COLOR_YELLOW;\nstatic int green = COLOR_GREEN;\nstatic int black = COLOR_BLACK;\nstatic int orange = COLOR_YELLOW;\nstatic int foreground = COLOR_WHITE;\nstatic int background = -1;\nstatic int selected = -1;\nstatic int grey = COLOR_WHITE;\n\n#define SCALE(x) ((x * 1000) \/ 255)\n\nstatic int initColor(int id, int r, int g, int b) {\n init_color(id, SCALE(r), SCALE(g), SCALE(b));\n return id;\n}\n\n\/* some terminals report custom colors are supported, and also\ndon't error when calling init_color(), but don't actually work. *\/\nstatic bool canChangeColors() {\n#ifdef __APPLE__\n const char* termEnv = std::getenv(\"TERM_PROGRAM\");\n std::string term;\n if (termEnv && strlen(termEnv)) {\n term = std::string(termEnv);\n if (term == \"Apple_Terminal\") {\n return false;\n }\n }\n return can_change_color();\n#else\n return can_change_color();\n#endif\n}\n\nColors::Colors() {\n}\n\nvoid Colors::Init(bool disableCustomColors) {\n start_color();\n use_default_colors();\n\n \/* the default colors are a bit harsh for my taste, so\n let's use custom colors if the terminal supports it. in\n the future we'll allow users to configure this via setting *\/\n if (!disableCustomColors && COLORS > 8) {\n if (canChangeColors()) {\n red = initColor(COLOR_CUSTOM_RED, 220, 82, 86);\n darkRed = initColor(COLOR_CUSTOM_DARK_RED, 175, 66, 71);\n green = initColor(COLOR_CUSTOM_GREEN, 166, 226, 46);\n yellow = initColor(COLOR_CUSTOM_YELLOW, 230, 220, 116);\n selected = initColor(COLOR_CUSTOM_SELECTED_LIST_ITEM_BG, 66, 66, 56);\n grey = initColor(COLOR_CUSTOM_GREY, 128, 128, 128);\n orange = initColor(COLOR_CUSTOM_ORANGE, 255, 150, 32);\n blue = initColor(COLOR_CUSTOM_BLUE, 102, 217, 238);\n white = initColor(COLOR_CUSTOM_WHITE, 230, 230, 230);\n foreground = COLOR_CUSTOM_WHITE;\n }\n else if (COLORS >= 256) {\n green = COLOR_256_GREEN;\n red = COLOR_256_RED;\n darkRed = COLOR_256_DARK_RED;\n yellow = COLOR_256_YELLOW;\n selected = COLOR_256_MEDIUM_GRAY;\n grey = COLOR_256_MEDIUM_GRAY;\n orange = COLOR_256_ORANGE;\n blue = COLOR_256_BLUE;\n white = COLOR_256_OFFWHITE;\n foreground = COLOR_256_OFFWHITE;\n }\n }\n\n init_pair(CURSESPP_SELECTED_LIST_ITEM, yellow, selected);\n init_pair(CURSESPP_HIGHLIGHTED_LIST_ITEM, black, green);\n init_pair(CURSESPP_HIGHLIGHTED_SELECTED_LIST_ITEM, black, yellow);\n init_pair(CURSESPP_LIST_ITEM_HEADER, green, background);\n\n init_pair(CURSESPP_DEFAULT_CONTENT_COLOR, foreground, background);\n init_pair(CURSESPP_DEFAULT_FRAME_COLOR, foreground, background);\n init_pair(CURSESPP_FOCUSED_FRAME_COLOR, red, background);\n\n init_pair(CURSESPP_TEXT_DEFAULT, white, background);\n init_pair(CURSESPP_TEXT_DISABLED, grey, background);\n init_pair(CURSESPP_TEXT_FOCUSED, red, background);\n init_pair(CURSESPP_TEXT_ACTIVE, green, background);\n init_pair(CURSESPP_TEXT_WARNING, yellow, background);\n init_pair(CURSESPP_TEXT_ERROR, red, background);\n init_pair(CURSESPP_TEXT_HIDDEN, black, background);\n init_pair(CURSESPP_TEXT_SEPARATOR, orange, background);\n\n init_pair(CURSESPP_BUTTON_NORMAL, black, yellow);\n init_pair(CURSESPP_BUTTON_NEGATIVE, white, red);\n init_pair(CURSESPP_BUTTON_HIGHLIGHTED, black, green);\n\n init_pair(CURSESPP_SHORTCUT_ROW_NORMAL, yellow, selected);\n init_pair(CURSESPP_SHORTCUT_ROW_FOCUSED, white, darkRed);\n\n init_pair(CURSESPP_OVERLAY_FRAME, blue, selected);\n init_pair(CURSESPP_OVERLAY_BACKGROUND, white, selected);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"layer_pool.h\"\n#include \"common\/math.hpp\"\n\nnamespace ncv\n{\n template\n <\n typename tscalar,\n typename tsize\n >\n static void _output(\n const tscalar* idata, tsize irows, tsize icols, tscalar alpha,\n tscalar* wdata, tscalar* sdata, tscalar* cdata, tscalar* odata)\n {\n const tsize orows = (irows + 1) \/ 2;\n const tsize ocols = (icols + 1) \/ 2;\n const tscalar ialpha = 1 \/ alpha;\n\n auto wmap = tensor::make_matrix(wdata, irows, icols);\n auto smap = tensor::make_matrix(sdata, orows, ocols);\n auto cmap = tensor::make_matrix(cdata, orows, ocols);\n auto omap = tensor::make_matrix(odata, orows, ocols);\n auto imap = tensor::make_matrix(idata, irows, icols);\n\n wmap = (imap.array() * alpha).exp();\n \n smap.setZero();\n\t\tcmap.setZero();\n\n for (tsize r = 0, rr = 0; r < irows; r ++, rr = r \/ 2)\n {\n for (tsize c = 0, cc = 0; c < icols; c ++, cc = c \/ 2)\n {\n smap(rr, cc) += wmap(r, c);\n\t\t\t\tcmap(rr, cc) += 1;\n }\n }\n \n omap = ialpha * (smap.array() \/ cmap.array()).log();\n }\n\n template\n <\n typename tscalar,\n typename tsize\n >\n static void _igrad(\n tscalar* idata, tsize irows, tsize icols,\n const tscalar* wdata, const tscalar* sdata, const tscalar*, const tscalar* gdata)\n {\n const tsize orows = (irows + 1) \/ 2;\n const tsize ocols = (icols + 1) \/ 2;\n\n auto wmap = tensor::make_matrix(wdata, irows, icols);\n auto smap = tensor::make_matrix(sdata, orows, ocols);\n auto gmap = tensor::make_matrix(gdata, orows, ocols);\n auto imap = tensor::make_matrix(idata, irows, icols);\n\n for (tsize r = 0, rr = 0; r < irows; r ++, rr = r \/ 2)\n {\n for (tsize c = 0, cc = 0; c < icols; c ++, cc = c \/ 2)\n {\n imap(r, c) = gmap(rr, cc) * wmap(r, c) \/ smap(rr, cc);\n }\n }\n }\n \n pool_layer_t::pool_layer_t(const string_t& parameters)\n : layer_t(parameters, \"pooling layer, parameters: alpha=[-100.0,+100.0]\"),\n m_alpha(math::clamp(text::from_params<scalar_t>(parameters, \"dims\", 0.1), -100.0, +100.0))\n {\n }\n\n size_t pool_layer_t::resize(const tensor_t& tensor)\n {\n const size_t idims = tensor.dims();\n const size_t irows = tensor.rows();\n const size_t icols = tensor.cols();\n\n const size_t odims = idims;\n const size_t orows = (irows + 1) \/ 2;\n const size_t ocols = (icols + 1) \/ 2;\n\n m_idata.resize(idims, irows, icols);\n m_odata.resize(odims, orows, ocols);\n\n m_wdata.resize(idims, irows, icols);\n m_sdata.resize(odims, orows, ocols);\n m_cdata.resize(odims, orows, ocols);\n\n return 0;\n }\n\n const tensor_t& pool_layer_t::output(const tensor_t& input)\n {\n assert(idims() == input.dims());\n assert(irows() <= input.rows());\n assert(icols() <= input.cols());\n\n m_idata.copy_from(input);\n\n for (size_t o = 0; o < odims(); o ++)\n {\n _output(m_idata.plane_data(o), irows(), icols(), m_alpha,\n m_wdata.plane_data(o),\n m_sdata.plane_data(o),\n\t\t\t\t m_cdata.plane_data(o),\n m_odata.plane_data(o));\n }\n\n return m_odata;\n }\n\n const tensor_t& pool_layer_t::igrad(const tensor_t& output)\n {\n assert(odims() == output.dims());\n assert(orows() == output.rows());\n assert(ocols() == output.cols());\n\n for (size_t o = 0; o < odims(); o ++)\n {\n _igrad(m_idata.plane_data(o), irows(), icols(),\n m_wdata.plane_data(o),\n m_sdata.plane_data(o),\n\t\t\t\t m_cdata.plane_data(o),\n output.plane_data(o));\n }\n\n return m_idata;\n }\n\n void pool_layer_t::pgrad(const tensor_t& output, scalar_t* gradient)\n {\n assert(odims() == output.dims());\n assert(orows() == output.rows());\n assert(ocols() == output.cols());\n }\n}\n\n\n<commit_msg>cleanup<commit_after>#include \"layer_pool.h\"\n#include \"common\/math.hpp\"\n\nnamespace ncv\n{\n template\n <\n typename tscalar,\n typename tsize\n >\n static void _output(\n const tscalar* idata, tsize irows, tsize icols, tscalar alpha,\n tscalar* wdata, tscalar* sdata, tscalar* cdata, tscalar* odata)\n {\n const tsize orows = (irows + 1) \/ 2;\n const tsize ocols = (icols + 1) \/ 2;\n const tscalar ialpha = 1 \/ alpha;\n\n auto wmap = tensor::make_matrix(wdata, irows, icols);\n auto smap = tensor::make_matrix(sdata, orows, ocols);\n auto cmap = tensor::make_matrix(cdata, orows, ocols);\n auto omap = tensor::make_matrix(odata, orows, ocols);\n auto imap = tensor::make_matrix(idata, irows, icols);\n\n wmap = (imap.array() * alpha).exp();\n \n smap.setZero();\n cmap.setZero();\n\n for (tsize r = 0, rr = 0; r < irows; r ++, rr = r \/ 2)\n {\n for (tsize c = 0, cc = 0; c < icols; c ++, cc = c \/ 2)\n {\n smap(rr, cc) += wmap(r, c);\n cmap(rr, cc) += 1;\n }\n }\n \n omap = ialpha * (smap.array() \/ cmap.array()).log();\n }\n\n template\n <\n typename tscalar,\n typename tsize\n >\n static void _igrad(\n tscalar* idata, tsize irows, tsize icols,\n const tscalar* wdata, const tscalar* sdata, const tscalar*, const tscalar* gdata)\n {\n const tsize orows = (irows + 1) \/ 2;\n const tsize ocols = (icols + 1) \/ 2;\n\n auto wmap = tensor::make_matrix(wdata, irows, icols);\n auto smap = tensor::make_matrix(sdata, orows, ocols);\n auto gmap = tensor::make_matrix(gdata, orows, ocols);\n auto imap = tensor::make_matrix(idata, irows, icols);\n\n for (tsize r = 0, rr = 0; r < irows; r ++, rr = r \/ 2)\n {\n for (tsize c = 0, cc = 0; c < icols; c ++, cc = c \/ 2)\n {\n imap(r, c) = gmap(rr, cc) * wmap(r, c) \/ smap(rr, cc);\n }\n }\n }\n \n pool_layer_t::pool_layer_t(const string_t& parameters)\n : layer_t(parameters, \"pooling layer, parameters: alpha=[-100.0,+100.0]\"),\n m_alpha(math::clamp(text::from_params<scalar_t>(parameters, \"dims\", 0.1), -100.0, +100.0))\n {\n }\n\n size_t pool_layer_t::resize(const tensor_t& tensor)\n {\n const size_t idims = tensor.dims();\n const size_t irows = tensor.rows();\n const size_t icols = tensor.cols();\n\n const size_t odims = idims;\n const size_t orows = (irows + 1) \/ 2;\n const size_t ocols = (icols + 1) \/ 2;\n\n m_idata.resize(idims, irows, icols);\n m_odata.resize(odims, orows, ocols);\n\n m_wdata.resize(idims, irows, icols);\n m_sdata.resize(odims, orows, ocols);\n m_cdata.resize(odims, orows, ocols);\n\n return 0;\n }\n\n const tensor_t& pool_layer_t::output(const tensor_t& input)\n {\n assert(idims() == input.dims());\n assert(irows() <= input.rows());\n assert(icols() <= input.cols());\n\n m_idata.copy_from(input);\n\n for (size_t o = 0; o < odims(); o ++)\n {\n _output(m_idata.plane_data(o), irows(), icols(), m_alpha,\n m_wdata.plane_data(o),\n m_sdata.plane_data(o),\n\t\t\t\t m_cdata.plane_data(o),\n m_odata.plane_data(o));\n }\n\n return m_odata;\n }\n\n const tensor_t& pool_layer_t::igrad(const tensor_t& output)\n {\n assert(odims() == output.dims());\n assert(orows() == output.rows());\n assert(ocols() == output.cols());\n\n for (size_t o = 0; o < odims(); o ++)\n {\n _igrad(m_idata.plane_data(o), irows(), icols(),\n m_wdata.plane_data(o),\n m_sdata.plane_data(o),\n\t\t\t\t m_cdata.plane_data(o),\n output.plane_data(o));\n }\n\n return m_idata;\n }\n\n void pool_layer_t::pgrad(const tensor_t& output, scalar_t* gradient)\n {\n assert(odims() == output.dims());\n assert(orows() == output.rows());\n assert(ocols() == output.cols());\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------\n\/\/ Copyright 2015 Ontario Institute for Cancer Research\n\/\/ Written by Jared Simpson (jared.simpson@oicr.on.ca)\n\/\/---------------------------------------------------------\n\/\/\n\/\/ nanopolish_squiggle_read -- Class holding a squiggle (event)\n\/\/ space nanopore read\n\/\/\n#include <algorithm>\n#include \"nanopolish_common.h\"\n#include \"nanopolish_squiggle_read.h\"\n#include \"src\/fast5.hpp\"\n\n\/\/\nSquiggleRead::SquiggleRead(const std::string& name, const std::string& path) :\n read_name(name),\n drift_correction_performed(false)\n{\n load_from_fast5(path);\n\n \/\/ perform drift correction and other scalings\n transform();\n}\n\nSquiggleRead::~SquiggleRead()\n{\n}\n\n\/\/ helper for get_closest_event_to\nint SquiggleRead::get_next_event(int start, int stop, int stride, uint32_t strand) const\n{\n while(start != stop) {\n \n int ei = base_to_event_map[start].indices[strand].start;\n if(ei != -1)\n return ei;\n start += stride;\n }\n return -1;\n}\n\n\/\/\nint SquiggleRead::get_closest_event_to(int k_idx, uint32_t strand) const\n{\n uint32_t k = pore_model[T_IDX].k;\n\n int stop_before = std::max(0, k_idx - 1000);\n int stop_after = std::min(k_idx + 1000, (int32_t)read_sequence.size() - (int32_t)k + 1);\n \n int event_before = get_next_event(k_idx, stop_before, -1, strand);\n int event_after = get_next_event(k_idx, stop_after, 1, strand);\n\n \/\/ TODO: better selection of \"best\" event to return\n if(event_before == -1)\n return event_after;\n return event_before;\n}\n\n\/\/\nvoid SquiggleRead::transform()\n{\n for (size_t si = 0; si < 2; ++si) {\n for(size_t ei = 0; ei < events[si].size(); ++ei) {\n\n SquiggleEvent& event = events[si][ei];\n\n \/\/ correct level by drift\n double time = event.start_time - events[si][0].start_time;\n event.mean -= (time * pore_model[si].drift);\n }\n }\n\n drift_correction_performed = true;\n}\n\n\/\/\nvoid SquiggleRead::load_from_fast5(const std::string& fast5_path)\n{\n fast5::File* f_p;\n this->fast5_path = fast5_path;\n\n f_p = new fast5::File(fast5_path);\n assert(f_p->is_open());\n\n \/\/ Check if an alternative analysis group is present in the read name\n int group_id = -1;\n \/*\n size_t bc_2d_pos = read_name.find(\"Basecall_2D\");\n if(bc_2d_pos != std::string::npos) {\n int ret = sscanf(read_name.substr(bc_2d_pos).c_str(), \"Basecall_2D_%03d_2d\", &group_id);\n } \n *\/\n \/\/ default to 0 group\n if(group_id == -1) {\n group_id = 0;\n }\n \n f_p->set_basecalled_group_id(group_id);\n\n \/\/ Automatically detect the read type from the name\n \/\/ Set the read type based on the suffix and load the sequence\n assert(!read_name.empty());\n if(ends_with(read_name, \"_template\")) {\n read_type = SRT_TEMPLATE;\n read_sequence = f_p->basecalled_1D(read_type);\n } else if(ends_with(read_name, \"_complement\")) {\n read_type = SRT_COMPLEMENT;\n read_sequence = f_p->basecalled_1D(read_type);\n } else {\n read_type = SRT_2D;\n read_sequence = f_p->basecalled_2D();\n }\n\n \/\/ Load PoreModel for both strands\n for (size_t si = 0; si < 2; ++si) {\n \n \/\/ Do we want to load this strand?\n if(! (read_type == SRT_2D || read_type == si) ) {\n continue;\n }\n\n \/\/ Load the pore model for this strand\n pore_model[si] = PoreModel( f_p, si );\n\n \/\/ initialize transition parameters\n parameters[si].initialize(pore_model[si].name);\n \n \/\/ Load the events for this strand\n std::vector<fast5::Event_Entry> f5_events = f_p->get_events(si);\n \n \/\/ copy events\n events[si].resize(f5_events.size());\n for(size_t ei = 0; ei < f5_events.size(); ++ei) {\n const fast5::Event_Entry& f5_event = f5_events[ei];\n events[si][ei] = { static_cast<float>(f5_event.mean), \n static_cast<float>(f5_event.stdv), \n static_cast<float>(f5_event.start), \n static_cast<float>(f5_event.length),\n static_cast<float>(log(f5_event.stdv)) };\n }\n\n \/\/ build the map from k-mers to events if this is a 1D read\n if(read_type != SRT_2D) {\n build_event_map_1d(f_p, si, f5_events);\n }\n }\n\n \/\/ Both strands need to be loaded before the 2D event map is built\n if(read_type == SRT_2D) {\n build_event_map_2d(f_p);\n }\n\n delete f_p;\n}\n\nvoid SquiggleRead::build_event_map_1d(fast5::File* f_p, uint32_t strand, std::vector<fast5::Event_Entry>& f5_events)\n{\n const uint32_t k = pore_model[T_IDX].k;\n assert(f5_events.size() == events[strand].size());\n\n \/\/ initialize - one entry per read kmer\n uint32_t n_read_kmers = read_sequence.size() - k + 1;\n base_to_event_map.resize(n_read_kmers);\n\n \/\/ The range for the first k-mer always starts at event 0\n assert(f5_events[0].move == 0);\n base_to_event_map[0].indices[strand].start = 0;\n\n size_t curr_k_idx = 0;\n for(size_t ei = 0; ei < f5_events.size(); ++ei) {\n const fast5::Event_Entry& f5_event = f5_events[ei];\n \n \/\/ Does this event correspond to a different k-mer than the previous one?\n if(f5_event.move > 0) {\n assert(ei != 0);\n\n \/\/ end the range for the current k-mer\n base_to_event_map[curr_k_idx].indices[strand].stop = ei - 1;\n curr_k_idx += f5_event.move;\n \n \/\/ start the range for the next kmer\n base_to_event_map[curr_k_idx].indices[strand].start = ei; \n }\n\n \/\/ ensure the traversal matches the read sequence\n assert(read_sequence.compare(curr_k_idx, k, f5_event.model_state) == 0);\n }\n}\n\nvoid SquiggleRead::build_event_map_2d(fast5::File* f_p)\n{\n \/\/\n \/\/ Build the map from read k-mers to events\n \/\/\n \n std::vector<fast5::Event_Alignment_Entry> event_alignments = f_p->get_event_alignments();\n assert(!read_sequence.empty());\n\n const uint32_t k = pore_model[T_IDX].k;\n assert(pore_model[C_IDX].k == k);\n\n uint32_t n_read_kmers = read_sequence.size() - k + 1;\n base_to_event_map.resize(n_read_kmers);\n\n uint32_t read_kidx = 0;\n\n \/\/ The alignment format in the fast5 file is slightly bizarre in that it is\n \/\/ (template_idx, complement_idx, kmer) tuples. Some read kmers may not have a\n \/\/ tuple and some might have multiple tuples. We need to use the read kmer\n \/\/ sequences to work out which read base each entry is referring to\n uint32_t start_ea_idx = 0;\n uint32_t end_ea_idx = 0;\n\n while(start_ea_idx < event_alignments.size()) {\n\nhack:\n uint32_t prev_kidx = read_kidx;\n\n \/\/ Advance the kmer index until we have found the read kmer\n \/\/ this tuple refers to\n while(read_kidx < n_read_kmers && \n strncmp(event_alignments[start_ea_idx].kmer, \n read_sequence.c_str() + read_kidx, k) != 0) {\n read_kidx += 1;\n }\n\n \/\/ In the most recent version of metrichor occasionally\n \/\/ a kmer will be present in the alignment table\n \/\/ that is not in the 2D read. This awful hack\n \/\/ will skip such k-mers. It is not a long-term\n \/\/ solution, only until metrichor is fixed.\n if(read_kidx - prev_kidx > 10) {\n start_ea_idx += 1;\n read_kidx = prev_kidx;\n goto hack;\n }\n\n \/\/ Advance the event alignment end index to the last tuple\n \/\/ with the same kmer as the start of this range\n end_ea_idx = start_ea_idx;\n while(end_ea_idx < event_alignments.size() &&\n strcmp(event_alignments[start_ea_idx].kmer,\n event_alignments[end_ea_idx].kmer) == 0) {\n end_ea_idx += 1;\n }\n\n \/\/printf(\"Base-to-event map kidx: %d %s event_tuple [%d %d]\\n\", read_kidx, read_sequence.substr(read_kidx, k).c_str(), start_ea_idx, end_ea_idx);\n EventRangeForBase& erfb = base_to_event_map[read_kidx];\n for(uint32_t i = start_ea_idx; i < end_ea_idx; ++i) {\n\n fast5::Event_Alignment_Entry& eae = event_alignments[i];\n \n for(uint32_t si = 0; si <= 1; ++si) {\n int incoming_idx = si == 0 ? eae.template_index : eae.complement_index;\n \n \/\/ no event for this strand, nothing to update\n if(incoming_idx == -1) {\n continue;\n }\n if(erfb.indices[si].start == -1) {\n erfb.indices[si].start = incoming_idx; \n }\n erfb.indices[si].stop = incoming_idx;\n\n assert(erfb.indices[si].start < (int)events[si].size());\n assert(erfb.indices[si].stop < (int)events[si].size());\n }\n }\n \/\/printf(\"\\t[%d %d] [%d %d]\\n\", erfb.indices[0].start, erfb.indices[0].stop, erfb.indices[1].start, erfb.indices[1].stop);\n start_ea_idx = end_ea_idx;\n }\n}\n\nvoid SquiggleRead::replace_models(const ModelMap& map) {\n \n for(size_t strand_idx = 0; strand_idx < NUM_STRANDS; ++strand_idx) {\n std::string curr_model = this->pore_model[strand_idx].name;\n auto model_iter = map.find(curr_model);\n if(model_iter != map.end()) {\n this->pore_model[strand_idx].update_states( model_iter->second );\n } else {\n fprintf(stderr, \"Error, alternative model %s not found\\n\", curr_model.c_str());\n exit(EXIT_FAILURE);\n }\n }\n}\n<commit_msg>do not try to replace the model if its not loaded<commit_after>\/\/---------------------------------------------------------\n\/\/ Copyright 2015 Ontario Institute for Cancer Research\n\/\/ Written by Jared Simpson (jared.simpson@oicr.on.ca)\n\/\/---------------------------------------------------------\n\/\/\n\/\/ nanopolish_squiggle_read -- Class holding a squiggle (event)\n\/\/ space nanopore read\n\/\/\n#include <algorithm>\n#include \"nanopolish_common.h\"\n#include \"nanopolish_squiggle_read.h\"\n#include \"src\/fast5.hpp\"\n\n\/\/\nSquiggleRead::SquiggleRead(const std::string& name, const std::string& path) :\n read_name(name),\n drift_correction_performed(false)\n{\n load_from_fast5(path);\n\n \/\/ perform drift correction and other scalings\n transform();\n}\n\nSquiggleRead::~SquiggleRead()\n{\n}\n\n\/\/ helper for get_closest_event_to\nint SquiggleRead::get_next_event(int start, int stop, int stride, uint32_t strand) const\n{\n while(start != stop) {\n \n int ei = base_to_event_map[start].indices[strand].start;\n if(ei != -1)\n return ei;\n start += stride;\n }\n return -1;\n}\n\n\/\/\nint SquiggleRead::get_closest_event_to(int k_idx, uint32_t strand) const\n{\n uint32_t k = pore_model[T_IDX].k;\n\n int stop_before = std::max(0, k_idx - 1000);\n int stop_after = std::min(k_idx + 1000, (int32_t)read_sequence.size() - (int32_t)k + 1);\n \n int event_before = get_next_event(k_idx, stop_before, -1, strand);\n int event_after = get_next_event(k_idx, stop_after, 1, strand);\n\n \/\/ TODO: better selection of \"best\" event to return\n if(event_before == -1)\n return event_after;\n return event_before;\n}\n\n\/\/\nvoid SquiggleRead::transform()\n{\n for (size_t si = 0; si < 2; ++si) {\n for(size_t ei = 0; ei < events[si].size(); ++ei) {\n\n SquiggleEvent& event = events[si][ei];\n\n \/\/ correct level by drift\n double time = event.start_time - events[si][0].start_time;\n event.mean -= (time * pore_model[si].drift);\n }\n }\n\n drift_correction_performed = true;\n}\n\n\/\/\nvoid SquiggleRead::load_from_fast5(const std::string& fast5_path)\n{\n fast5::File* f_p;\n this->fast5_path = fast5_path;\n\n f_p = new fast5::File(fast5_path);\n assert(f_p->is_open());\n\n \/\/ Check if an alternative analysis group is present in the read name\n int group_id = -1;\n \/*\n size_t bc_2d_pos = read_name.find(\"Basecall_2D\");\n if(bc_2d_pos != std::string::npos) {\n int ret = sscanf(read_name.substr(bc_2d_pos).c_str(), \"Basecall_2D_%03d_2d\", &group_id);\n } \n *\/\n \/\/ default to 0 group\n if(group_id == -1) {\n group_id = 0;\n }\n \n f_p->set_basecalled_group_id(group_id);\n\n \/\/ Automatically detect the read type from the name\n \/\/ Set the read type based on the suffix and load the sequence\n assert(!read_name.empty());\n if(ends_with(read_name, \"_template\")) {\n read_type = SRT_TEMPLATE;\n read_sequence = f_p->basecalled_1D(read_type);\n } else if(ends_with(read_name, \"_complement\")) {\n read_type = SRT_COMPLEMENT;\n read_sequence = f_p->basecalled_1D(read_type);\n } else {\n read_type = SRT_2D;\n read_sequence = f_p->basecalled_2D();\n }\n\n \/\/ Load PoreModel for both strands\n for (size_t si = 0; si < 2; ++si) {\n \n \/\/ Do we want to load this strand?\n if(! (read_type == SRT_2D || read_type == si) ) {\n continue;\n }\n\n \/\/ Load the pore model for this strand\n pore_model[si] = PoreModel( f_p, si );\n\n \/\/ initialize transition parameters\n parameters[si].initialize(pore_model[si].name);\n \n \/\/ Load the events for this strand\n std::vector<fast5::Event_Entry> f5_events = f_p->get_events(si);\n \n \/\/ copy events\n events[si].resize(f5_events.size());\n for(size_t ei = 0; ei < f5_events.size(); ++ei) {\n const fast5::Event_Entry& f5_event = f5_events[ei];\n events[si][ei] = { static_cast<float>(f5_event.mean), \n static_cast<float>(f5_event.stdv), \n static_cast<float>(f5_event.start), \n static_cast<float>(f5_event.length),\n static_cast<float>(log(f5_event.stdv)) };\n }\n\n \/\/ build the map from k-mers to events if this is a 1D read\n if(read_type != SRT_2D) {\n build_event_map_1d(f_p, si, f5_events);\n }\n }\n\n \/\/ Both strands need to be loaded before the 2D event map is built\n if(read_type == SRT_2D) {\n build_event_map_2d(f_p);\n }\n\n delete f_p;\n}\n\nvoid SquiggleRead::build_event_map_1d(fast5::File* f_p, uint32_t strand, std::vector<fast5::Event_Entry>& f5_events)\n{\n const uint32_t k = pore_model[T_IDX].k;\n assert(f5_events.size() == events[strand].size());\n\n \/\/ initialize - one entry per read kmer\n uint32_t n_read_kmers = read_sequence.size() - k + 1;\n base_to_event_map.resize(n_read_kmers);\n\n \/\/ The range for the first k-mer always starts at event 0\n assert(f5_events[0].move == 0);\n base_to_event_map[0].indices[strand].start = 0;\n\n size_t curr_k_idx = 0;\n for(size_t ei = 0; ei < f5_events.size(); ++ei) {\n const fast5::Event_Entry& f5_event = f5_events[ei];\n \n \/\/ Does this event correspond to a different k-mer than the previous one?\n if(f5_event.move > 0) {\n assert(ei != 0);\n\n \/\/ end the range for the current k-mer\n base_to_event_map[curr_k_idx].indices[strand].stop = ei - 1;\n curr_k_idx += f5_event.move;\n \n \/\/ start the range for the next kmer\n base_to_event_map[curr_k_idx].indices[strand].start = ei; \n }\n\n \/\/ ensure the traversal matches the read sequence\n assert(read_sequence.compare(curr_k_idx, k, f5_event.model_state) == 0);\n }\n}\n\nvoid SquiggleRead::build_event_map_2d(fast5::File* f_p)\n{\n \/\/\n \/\/ Build the map from read k-mers to events\n \/\/\n \n std::vector<fast5::Event_Alignment_Entry> event_alignments = f_p->get_event_alignments();\n assert(!read_sequence.empty());\n\n const uint32_t k = pore_model[T_IDX].k;\n assert(pore_model[C_IDX].k == k);\n\n uint32_t n_read_kmers = read_sequence.size() - k + 1;\n base_to_event_map.resize(n_read_kmers);\n\n uint32_t read_kidx = 0;\n\n \/\/ The alignment format in the fast5 file is slightly bizarre in that it is\n \/\/ (template_idx, complement_idx, kmer) tuples. Some read kmers may not have a\n \/\/ tuple and some might have multiple tuples. We need to use the read kmer\n \/\/ sequences to work out which read base each entry is referring to\n uint32_t start_ea_idx = 0;\n uint32_t end_ea_idx = 0;\n\n while(start_ea_idx < event_alignments.size()) {\n\nhack:\n uint32_t prev_kidx = read_kidx;\n\n \/\/ Advance the kmer index until we have found the read kmer\n \/\/ this tuple refers to\n while(read_kidx < n_read_kmers && \n strncmp(event_alignments[start_ea_idx].kmer, \n read_sequence.c_str() + read_kidx, k) != 0) {\n read_kidx += 1;\n }\n\n \/\/ In the most recent version of metrichor occasionally\n \/\/ a kmer will be present in the alignment table\n \/\/ that is not in the 2D read. This awful hack\n \/\/ will skip such k-mers. It is not a long-term\n \/\/ solution, only until metrichor is fixed.\n if(read_kidx - prev_kidx > 10) {\n start_ea_idx += 1;\n read_kidx = prev_kidx;\n goto hack;\n }\n\n \/\/ Advance the event alignment end index to the last tuple\n \/\/ with the same kmer as the start of this range\n end_ea_idx = start_ea_idx;\n while(end_ea_idx < event_alignments.size() &&\n strcmp(event_alignments[start_ea_idx].kmer,\n event_alignments[end_ea_idx].kmer) == 0) {\n end_ea_idx += 1;\n }\n\n \/\/printf(\"Base-to-event map kidx: %d %s event_tuple [%d %d]\\n\", read_kidx, read_sequence.substr(read_kidx, k).c_str(), start_ea_idx, end_ea_idx);\n EventRangeForBase& erfb = base_to_event_map[read_kidx];\n for(uint32_t i = start_ea_idx; i < end_ea_idx; ++i) {\n\n fast5::Event_Alignment_Entry& eae = event_alignments[i];\n \n for(uint32_t si = 0; si <= 1; ++si) {\n int incoming_idx = si == 0 ? eae.template_index : eae.complement_index;\n \n \/\/ no event for this strand, nothing to update\n if(incoming_idx == -1) {\n continue;\n }\n if(erfb.indices[si].start == -1) {\n erfb.indices[si].start = incoming_idx; \n }\n erfb.indices[si].stop = incoming_idx;\n\n assert(erfb.indices[si].start < (int)events[si].size());\n assert(erfb.indices[si].stop < (int)events[si].size());\n }\n }\n \/\/printf(\"\\t[%d %d] [%d %d]\\n\", erfb.indices[0].start, erfb.indices[0].stop, erfb.indices[1].start, erfb.indices[1].stop);\n start_ea_idx = end_ea_idx;\n }\n}\n\nvoid SquiggleRead::replace_models(const ModelMap& map) {\n \n for(size_t strand_idx = 0; strand_idx < NUM_STRANDS; ++strand_idx) {\n\n \/\/ only replace this model if the strand was loaded\n if(! (read_type == SRT_2D || read_type == strand_idx) ) {\n continue;\n }\n\n std::string curr_model = this->pore_model[strand_idx].name;\n auto model_iter = map.find(curr_model);\n if(model_iter != map.end()) {\n this->pore_model[strand_idx].update_states( model_iter->second );\n } else {\n fprintf(stderr, \"Error, alternative model %s not found\\n\", curr_model.c_str());\n exit(EXIT_FAILURE);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <map>\n#include <string>\n#include <set>\n#include <memory>\n#include <utility>\n#include <iostream>\n#include <uv.h>\n\n#include \"..\/log.h\"\n#include \"..\/message.h\"\n#include \"..\/helper\/common.h\"\n#include \"polling_iterator.h\"\n#include \"directory_record.h\"\n\nusing std::string;\nusing std::set;\nusing std::endl;\nusing std::move;\nusing std::shared_ptr;\n\nstruct FSReq {\n uv_fs_t req;\n\n ~FSReq() {\n uv_fs_req_cleanup(&req);\n }\n};\n\ninline bool ts_less_than(const uv_timespec_t &left, const uv_timespec_t &right)\n{\n return left.tv_sec < right.tv_sec ||\n (left.tv_sec == right.tv_sec && left.tv_nsec < right.tv_nsec);\n}\n\ninline EntryKind kind_from_stat(const uv_stat_t &st)\n{\n if (st.st_flags & S_IFDIR) return KIND_DIRECTORY;\n if (st.st_flags & S_IFREG) return KIND_FILE;\n return KIND_UNKNOWN;\n}\n\nDirectoryRecord::DirectoryRecord(string &&name) :\n parent{nullptr},\n name{move(name)},\n populated{false}\n{\n \/\/\n}\n\nstring DirectoryRecord::path() const\n{\n return parent == nullptr ? name : path_join(parent->path(), name);\n}\n\nvoid DirectoryRecord::scan(BoundPollingIterator *it)\n{\n FSReq scan_req;\n set<Entry> scanned_entries;\n\n string dir = path();\n int scan_err = uv_fs_scandir(nullptr, &scan_req.req, dir.c_str(), 0, nullptr);\n if (scan_err != 0) {\n LOGGER << \"Unable to scan directory \" << dir << \": \" << uv_strerror(scan_err) << \".\" << endl;\n return;\n }\n\n uv_dirent_t dirent;\n int next_err = uv_fs_scandir_next(&scan_req.req, &dirent);\n while (next_err == 0) {\n string entry_name(dirent.name);\n\n EntryKind entry_kind = KIND_UNKNOWN;\n if (dirent.type == UV_DIRENT_FILE) entry_kind = KIND_FILE;\n if (dirent.type == UV_DIRENT_DIR) entry_kind = KIND_DIRECTORY;\n\n it->push_entry(string(entry_name), entry_kind);\n if (populated) scanned_entries.emplace(move(entry_name), entry_kind);\n\n next_err = uv_fs_scandir_next(&scan_req.req, &dirent);\n }\n\n if (next_err != UV_EOF) {\n LOGGER << \"Unable to list entries in directory \" << dir << \": \" << uv_strerror(next_err) << \".\" << endl;\n } else {\n \/\/ Report entries that were present the last time we scanned this directory, but aren't included in this\n \/\/ scan.\n for (auto &previous : entries) {\n const string &previous_entry_name = previous.first;\n EntryKind previous_entry_kind = kind_from_stat(previous.second);\n Entry previous_entry(previous_entry_name, previous_entry_kind);\n\n if (scanned_entries.count(previous_entry) == 0) {\n entry_deleted(it, previous_entry_name, previous_entry_kind);\n }\n }\n }\n}\n\nvoid DirectoryRecord::entry(\n BoundPollingIterator *it,\n const string &entry_name,\n const string &entry_path,\n EntryKind scan_kind\n) {\n FSReq lstat_req;\n EntryKind previous_kind = scan_kind;\n EntryKind current_kind = scan_kind;\n\n int lstat_err = uv_fs_lstat(nullptr, &lstat_req.req, entry_path.c_str(), nullptr);\n if (lstat_err != 0 && lstat_err != UV_ENOENT && lstat_err != UV_EACCES) {\n LOGGER << \"Unable to stat \" << entry_path << \": \" << uv_strerror(lstat_err) << \".\" << endl;\n }\n\n auto previous = entries.find(entry_name);\n\n bool existed_before = previous != entries.end();\n bool exists_now = lstat_err == 0;\n\n if (existed_before) previous_kind = kind_from_stat(previous->second);\n if (exists_now) current_kind = kind_from_stat(lstat_req.req.statbuf);\n\n if (existed_before && exists_now) {\n \/\/ Modification or no change\n uv_stat_t &previous_stat = previous->second;\n uv_stat_t ¤t_stat = lstat_req.req.statbuf;\n\n \/\/ TODO consider modifications to mode or ownership bits?\n if (kinds_are_different(previous_kind, current_kind)) {\n entry_deleted(it, entry_path, previous_kind);\n entry_created(it, entry_path, current_kind);\n } else if (\n previous_stat.st_flags != current_stat.st_flags ||\n previous_stat.st_ino != current_stat.st_ino ||\n ts_less_than(previous_stat.st_mtim, current_stat.st_mtim) ||\n ts_less_than(previous_stat.st_ctim, current_stat.st_ctim)\n ) {\n entry_modified(it, entry_path, current_kind);\n }\n\n } else if (existed_before && !exists_now) {\n \/\/ Deletion\n\n entry_deleted(it, entry_path, previous_kind);\n\n } else if (!existed_before && exists_now) {\n \/\/ Creation\n\n if (kinds_are_different(scan_kind, current_kind)) {\n \/\/ Entry was created as a file, deleted, then recreated as a directory between scan() and entry()\n \/\/ (or vice versa)\n entry_created(it, entry_path, scan_kind);\n entry_deleted(it, entry_path, scan_kind);\n }\n entry_created(it, entry_path, current_kind);\n\n } else if (!existed_before && !exists_now) {\n \/\/ Entry was deleted between scan() and entry().\n \/\/ Emit a deletion and creation event pair. Note that the kinds will likely both be KIND_UNKNOWN.\n\n entry_created(it, entry_path, previous_kind);\n entry_deleted(it, entry_path, current_kind);\n\n }\n\n \/\/ Update entries with the latest stat information\n if (existed_before) entries.erase(previous);\n if (exists_now) entries.emplace(entry_name, lstat_req.req.statbuf);\n\n \/\/ Update subdirectories if this is or was a subdirectory\n auto dir = subdirectories.find(entry_name);\n if (current_kind != KIND_DIRECTORY && current_kind != KIND_UNKNOWN && dir != subdirectories.end()) {\n subdirectories.erase(dir);\n }\n if (current_kind == KIND_DIRECTORY) {\n if (dir == subdirectories.end()) {\n shared_ptr<DirectoryRecord> subdir(new DirectoryRecord(this, entry_name));\n subdirectories.emplace(entry_name, subdir);\n it->push_directory(subdir);\n } else {\n it->push_directory(dir->second);\n }\n }\n}\n\nvoid DirectoryRecord::entry_deleted(BoundPollingIterator *it, const string &entry_path, EntryKind kind)\n{\n if (!populated) return;\n\n it->get_buffer().deleted(string(entry_path), kind);\n}\n\nvoid DirectoryRecord::entry_created(BoundPollingIterator *it, const string &entry_path, EntryKind kind)\n{\n if (!populated) return;\n\n it->get_buffer().created(string(entry_path), kind);\n}\n\nvoid DirectoryRecord::entry_modified(BoundPollingIterator *it, const string &entry_path, EntryKind kind)\n{\n if (!populated) return;\n\n it->get_buffer().modified(string(entry_path), kind);\n}\n<commit_msg>Implement private DirectoryRecord constructor<commit_after>#include <map>\n#include <string>\n#include <set>\n#include <memory>\n#include <utility>\n#include <iostream>\n#include <uv.h>\n\n#include \"..\/log.h\"\n#include \"..\/message.h\"\n#include \"..\/helper\/common.h\"\n#include \"polling_iterator.h\"\n#include \"directory_record.h\"\n\nusing std::string;\nusing std::set;\nusing std::endl;\nusing std::move;\nusing std::shared_ptr;\n\nstruct FSReq {\n uv_fs_t req;\n\n ~FSReq() {\n uv_fs_req_cleanup(&req);\n }\n};\n\ninline bool ts_less_than(const uv_timespec_t &left, const uv_timespec_t &right)\n{\n return left.tv_sec < right.tv_sec ||\n (left.tv_sec == right.tv_sec && left.tv_nsec < right.tv_nsec);\n}\n\ninline EntryKind kind_from_stat(const uv_stat_t &st)\n{\n if (st.st_flags & S_IFDIR) return KIND_DIRECTORY;\n if (st.st_flags & S_IFREG) return KIND_FILE;\n return KIND_UNKNOWN;\n}\n\nDirectoryRecord::DirectoryRecord(string &&name) :\n parent{nullptr},\n name{move(name)},\n populated{false}\n{\n \/\/\n}\n\nstring DirectoryRecord::path() const\n{\n return parent == nullptr ? name : path_join(parent->path(), name);\n}\n\nvoid DirectoryRecord::scan(BoundPollingIterator *it)\n{\n FSReq scan_req;\n set<Entry> scanned_entries;\n\n string dir = path();\n int scan_err = uv_fs_scandir(nullptr, &scan_req.req, dir.c_str(), 0, nullptr);\n if (scan_err != 0) {\n LOGGER << \"Unable to scan directory \" << dir << \": \" << uv_strerror(scan_err) << \".\" << endl;\n return;\n }\n\n uv_dirent_t dirent;\n int next_err = uv_fs_scandir_next(&scan_req.req, &dirent);\n while (next_err == 0) {\n string entry_name(dirent.name);\n\n EntryKind entry_kind = KIND_UNKNOWN;\n if (dirent.type == UV_DIRENT_FILE) entry_kind = KIND_FILE;\n if (dirent.type == UV_DIRENT_DIR) entry_kind = KIND_DIRECTORY;\n\n it->push_entry(string(entry_name), entry_kind);\n if (populated) scanned_entries.emplace(move(entry_name), entry_kind);\n\n next_err = uv_fs_scandir_next(&scan_req.req, &dirent);\n }\n\n if (next_err != UV_EOF) {\n LOGGER << \"Unable to list entries in directory \" << dir << \": \" << uv_strerror(next_err) << \".\" << endl;\n } else {\n \/\/ Report entries that were present the last time we scanned this directory, but aren't included in this\n \/\/ scan.\n for (auto &previous : entries) {\n const string &previous_entry_name = previous.first;\n EntryKind previous_entry_kind = kind_from_stat(previous.second);\n Entry previous_entry(previous_entry_name, previous_entry_kind);\n\n if (scanned_entries.count(previous_entry) == 0) {\n entry_deleted(it, previous_entry_name, previous_entry_kind);\n }\n }\n }\n}\n\nvoid DirectoryRecord::entry(\n BoundPollingIterator *it,\n const string &entry_name,\n const string &entry_path,\n EntryKind scan_kind\n) {\n FSReq lstat_req;\n EntryKind previous_kind = scan_kind;\n EntryKind current_kind = scan_kind;\n\n int lstat_err = uv_fs_lstat(nullptr, &lstat_req.req, entry_path.c_str(), nullptr);\n if (lstat_err != 0 && lstat_err != UV_ENOENT && lstat_err != UV_EACCES) {\n LOGGER << \"Unable to stat \" << entry_path << \": \" << uv_strerror(lstat_err) << \".\" << endl;\n }\n\n auto previous = entries.find(entry_name);\n\n bool existed_before = previous != entries.end();\n bool exists_now = lstat_err == 0;\n\n if (existed_before) previous_kind = kind_from_stat(previous->second);\n if (exists_now) current_kind = kind_from_stat(lstat_req.req.statbuf);\n\n if (existed_before && exists_now) {\n \/\/ Modification or no change\n uv_stat_t &previous_stat = previous->second;\n uv_stat_t ¤t_stat = lstat_req.req.statbuf;\n\n \/\/ TODO consider modifications to mode or ownership bits?\n if (kinds_are_different(previous_kind, current_kind)) {\n entry_deleted(it, entry_path, previous_kind);\n entry_created(it, entry_path, current_kind);\n } else if (\n previous_stat.st_flags != current_stat.st_flags ||\n previous_stat.st_ino != current_stat.st_ino ||\n ts_less_than(previous_stat.st_mtim, current_stat.st_mtim) ||\n ts_less_than(previous_stat.st_ctim, current_stat.st_ctim)\n ) {\n entry_modified(it, entry_path, current_kind);\n }\n\n } else if (existed_before && !exists_now) {\n \/\/ Deletion\n\n entry_deleted(it, entry_path, previous_kind);\n\n } else if (!existed_before && exists_now) {\n \/\/ Creation\n\n if (kinds_are_different(scan_kind, current_kind)) {\n \/\/ Entry was created as a file, deleted, then recreated as a directory between scan() and entry()\n \/\/ (or vice versa)\n entry_created(it, entry_path, scan_kind);\n entry_deleted(it, entry_path, scan_kind);\n }\n entry_created(it, entry_path, current_kind);\n\n } else if (!existed_before && !exists_now) {\n \/\/ Entry was deleted between scan() and entry().\n \/\/ Emit a deletion and creation event pair. Note that the kinds will likely both be KIND_UNKNOWN.\n\n entry_created(it, entry_path, previous_kind);\n entry_deleted(it, entry_path, current_kind);\n\n }\n\n \/\/ Update entries with the latest stat information\n if (existed_before) entries.erase(previous);\n if (exists_now) entries.emplace(entry_name, lstat_req.req.statbuf);\n\n \/\/ Update subdirectories if this is or was a subdirectory\n auto dir = subdirectories.find(entry_name);\n if (current_kind != KIND_DIRECTORY && current_kind != KIND_UNKNOWN && dir != subdirectories.end()) {\n subdirectories.erase(dir);\n }\n if (current_kind == KIND_DIRECTORY) {\n if (dir == subdirectories.end()) {\n shared_ptr<DirectoryRecord> subdir(new DirectoryRecord(this, entry_name));\n subdirectories.emplace(entry_name, subdir);\n it->push_directory(subdir);\n } else {\n it->push_directory(dir->second);\n }\n }\n}\n\nDirectoryRecord::DirectoryRecord(DirectoryRecord *parent, const string &name) :\n parent{parent},\n name(move(name)),\n populated{false}\n{\n \/\/\n}\n\nvoid DirectoryRecord::entry_deleted(BoundPollingIterator *it, const string &entry_path, EntryKind kind)\n{\n if (!populated) return;\n\n it->get_buffer().deleted(string(entry_path), kind);\n}\n\nvoid DirectoryRecord::entry_created(BoundPollingIterator *it, const string &entry_path, EntryKind kind)\n{\n if (!populated) return;\n\n it->get_buffer().created(string(entry_path), kind);\n}\n\nvoid DirectoryRecord::entry_modified(BoundPollingIterator *it, const string &entry_path, EntryKind kind)\n{\n if (!populated) return;\n\n it->get_buffer().modified(string(entry_path), kind);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/foreach.hpp>\n\n#include \"script.h\"\n#include \"key.h\"\n\nusing namespace std;\n\n\/\/ Helpers:\nstatic std::vector<unsigned char>\nSerialize(const CScript& s)\n{\n std::vector<unsigned char> sSerialized(s);\n return sSerialized;\n}\n\nBOOST_AUTO_TEST_SUITE(sigopcount_tests)\n\nBOOST_AUTO_TEST_CASE(GetSigOpCount)\n{\n \/\/ Test CScript::GetSigOpCount()\n CScript s1;\n BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0);\n BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0);\n\n uint160 dummy;\n s1 << OP_1 << dummy << dummy << OP_2 << OP_CHECKMULTISIG;\n BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 2);\n s1 << OP_IF << OP_CHECKSIG << OP_ENDIF;\n BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 3);\n BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 21);\n\n CScript p2sh;\n p2sh.SetDestination(s1.GetID());\n CScript scriptSig;\n scriptSig << OP_0 << Serialize(s1);\n BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig), 3);\n\n std::vector<CKey> keys;\n for (int i = 0; i < 3; i++)\n {\n CKey k;\n k.MakeNewKey(true);\n keys.push_back(k);\n }\n CScript s2;\n s2.SetMultisig(1, keys);\n BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3);\n BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20);\n\n p2sh.SetDestination(s2.GetID());\n BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0);\n BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0);\n CScript scriptSig2;\n scriptSig2 << OP_1 << dummy << dummy << Serialize(s2);\n BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Delete sigopcount_tests.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <fnord-json\/json.h>\n#include \"reports\/TermInfoTableSink.h\"\n\nusing namespace fnord;\n\nnamespace cm {\n\nTermInfoTableSink::TermInfoTableSink(\n const String& output_file) :\n output_file_(output_file) {\n sstable_schema_.addColumn(\"related_terms\", 1, sstable::SSTableColumnType::STRING);\n}\n\nvoid TermInfoTableSink::open() {\n if (FileUtil::exists(output_file_ + \"~\")) {\n fnord::logInfo(\n \"cm.reportbuild\",\n \"Deleting orphaned temp file: $0\",\n output_file_ + \"~\");\n\n FileUtil::rm(output_file_ + \"~\");\n }\n\n fnord::logInfo(\n \"cm.reportbuild\",\n \"Opening output sstable: $0\",\n output_file_);\n\n sstable_writer_ = sstable::SSTableWriter::create(\n output_file_ + \"~\",\n sstable::IndexProvider{},\n nullptr,\n 0);\n}\n\nvoid TermInfoTableSink::addRow(\n const String& lang,\n const String& term,\n const HashMap<String, uint64_t>& related_terms) {\n auto key = lang + \"~\" + term;\n\n sstable::SSTableColumnWriter cols(&sstable_schema_);\n cols.addStringColumn(1, \"fnord\");\n sstable_writer_->appendRow(key, cols);\n}\n\nvoid TermInfoTableSink::close() {\n fnord::logInfo(\n \"cm.reportbuild\",\n \"Finalizing output sstable: $0\",\n output_file_);\n\n sstable_schema_.writeIndex(sstable_writer_.get());\n sstable_writer_->finalize();\n\n FileUtil::mv(output_file_ + \"~\", output_file_);\n}\n\nSet<String> TermInfoTableSink::outputFiles() {\n return Set<String> { output_file_ };\n}\n\n} \/\/ namespace cm\n\n<commit_msg>write similar terms to output table<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <fnord-json\/json.h>\n#include \"reports\/TermInfoTableSink.h\"\n\nusing namespace fnord;\n\nnamespace cm {\n\nTermInfoTableSink::TermInfoTableSink(\n const String& output_file) :\n output_file_(output_file) {\n sstable_schema_.addColumn(\"related_terms\", 1, sstable::SSTableColumnType::STRING);\n}\n\nvoid TermInfoTableSink::open() {\n if (FileUtil::exists(output_file_ + \"~\")) {\n fnord::logInfo(\n \"cm.reportbuild\",\n \"Deleting orphaned temp file: $0\",\n output_file_ + \"~\");\n\n FileUtil::rm(output_file_ + \"~\");\n }\n\n fnord::logInfo(\n \"cm.reportbuild\",\n \"Opening output sstable: $0\",\n output_file_);\n\n sstable_writer_ = sstable::SSTableWriter::create(\n output_file_ + \"~\",\n sstable::IndexProvider{},\n nullptr,\n 0);\n}\n\nvoid TermInfoTableSink::addRow(\n const String& lang,\n const String& term,\n const HashMap<String, uint64_t>& related_terms) {\n auto key = lang + \"~\" + term;\n\n String terms_str;\n for (const auto t : related_terms) {\n terms_str += StringUtil::format(\"$0:$1,\", t.first, t.second);\n }\n\n sstable::SSTableColumnWriter cols(&sstable_schema_);\n cols.addStringColumn(1, terms_str);\n sstable_writer_->appendRow(key, cols);\n}\n\nvoid TermInfoTableSink::close() {\n fnord::logInfo(\n \"cm.reportbuild\",\n \"Finalizing output sstable: $0\",\n output_file_);\n\n sstable_schema_.writeIndex(sstable_writer_.get());\n sstable_writer_->finalize();\n\n FileUtil::mv(output_file_ + \"~\", output_file_);\n}\n\nSet<String> TermInfoTableSink::outputFiles() {\n return Set<String> { output_file_ };\n}\n\n} \/\/ namespace cm\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017 ARM Limited.\n *\n * SPDX-License-Identifier: MIT\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\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell 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 all\n * 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 THE\n * SOFTWARE.\n *\/\n#include \"arm_compute\/runtime\/OMP\/OMPScheduler.h\"\n\n#include \"arm_compute\/core\/CPP\/ICPPKernel.h\"\n#include \"arm_compute\/core\/Error.h\"\n#include \"arm_compute\/core\/Helpers.h\"\n#include \"arm_compute\/core\/Utils.h\"\n\n#include <omp.h>\n\nusing namespace arm_compute;\n\nOMPScheduler &OMPScheduler::get()\n{\n static OMPScheduler scheduler;\n return scheduler;\n}\n\nOMPScheduler::OMPScheduler() \/\/ NOLINT\n : _num_threads(omp_get_max_threads())\n{\n}\n\nunsigned int OMPScheduler::num_threads() const\n{\n return _num_threads;\n}\n\nvoid OMPScheduler::set_num_threads(unsigned int num_threads)\n{\n const unsigned int num_cores = omp_get_max_threads();\n _num_threads = (num_threads == 0) ? num_cores : num_threads;\n}\n\nvoid OMPScheduler::schedule(ICPPKernel *kernel, unsigned int split_dimension)\n{\n ARM_COMPUTE_ERROR_ON_MSG(!kernel, \"The child class didn't set the kernel\");\n\n ThreadInfo info;\n info.cpu_info = _info;\n\n const Window &max_window = kernel->window();\n const unsigned int num_iterations = max_window.num_iterations(split_dimension);\n info.num_threads = std::min(num_iterations, _num_threads);\n\n if(!kernel->is_parallelisable() || info.num_threads == 1)\n {\n kernel->run(max_window, info);\n }\n else\n {\n #pragma omp parallel num_threads(info.num_threads)\n {\n #pragma omp for\n for(int t = 0; t < info.num_threads; ++t)\n {\n Window win = max_window.split_window(split_dimension, t, info.num_threads);\n info.thread_id = t;\n kernel->run(win, info);\n }\n }\n }\n}\n<commit_msg>Fix race condition on info.thread_id in OpenMP scheduler (#399)<commit_after>\/*\n * Copyright (c) 2017 ARM Limited.\n *\n * SPDX-License-Identifier: MIT\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\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell 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 all\n * 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 THE\n * SOFTWARE.\n *\/\n#include \"arm_compute\/runtime\/OMP\/OMPScheduler.h\"\n\n#include \"arm_compute\/core\/CPP\/ICPPKernel.h\"\n#include \"arm_compute\/core\/Error.h\"\n#include \"arm_compute\/core\/Helpers.h\"\n#include \"arm_compute\/core\/Utils.h\"\n\n#include <omp.h>\n\nusing namespace arm_compute;\n\nOMPScheduler &OMPScheduler::get()\n{\n static OMPScheduler scheduler;\n return scheduler;\n}\n\nOMPScheduler::OMPScheduler() \/\/ NOLINT\n : _num_threads(omp_get_max_threads())\n{\n}\n\nunsigned int OMPScheduler::num_threads() const\n{\n return _num_threads;\n}\n\nvoid OMPScheduler::set_num_threads(unsigned int num_threads)\n{\n const unsigned int num_cores = omp_get_max_threads();\n _num_threads = (num_threads == 0) ? num_cores : num_threads;\n}\n\nvoid OMPScheduler::schedule(ICPPKernel *kernel, unsigned int split_dimension)\n{\n ARM_COMPUTE_ERROR_ON_MSG(!kernel, \"The child class didn't set the kernel\");\n\n ThreadInfo info;\n info.cpu_info = _info;\n\n const Window &max_window = kernel->window();\n const unsigned int num_iterations = max_window.num_iterations(split_dimension);\n info.num_threads = std::min(num_iterations, _num_threads);\n\n if(!kernel->is_parallelisable() || info.num_threads == 1)\n {\n kernel->run(max_window, info);\n }\n else\n {\n #pragma omp parallel private(info) num_threads(info.num_threads)\n {\n const int tid = omp_get_thread_num();\n Window win = max_window.split_window(split_dimension, tid, info.num_threads);\n info.thread_id = tid;\n kernel->run(win, info);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"property_grid.h\"\n#include \"asset_browser.h\"\n#include \"core\/crc32.h\"\n#include \"editor\/world_editor.h\"\n#include \"engine\/engine.h\"\n#include \"engine\/property_descriptor.h\"\n#include \"ocornut-imgui\/imgui.h\"\n#include \"string_builder.h\"\n#include \"terrain_editor.h\"\n\n\nconst char* PropertyGrid::getComponentTypeName(Lumix::ComponentUID cmp) const\n{\n\tauto& engine = m_editor.getEngine();\n\tfor (int i = 0; i < engine.getComponentTypesCount(); ++i)\n\t{\n\t\tif (cmp.type ==\n\t\t\tLumix::crc32(engine.getComponentTypeID(i)))\n\t\t{\n\t\t\treturn engine.getComponentTypeName(i);\n\t\t}\n\t}\n\treturn \"Unknown\";\n}\n\n\n\nPropertyGrid::PropertyGrid(Lumix::WorldEditor& editor, AssetBrowser& asset_browser)\n\t: m_is_opened(true)\n\t, m_editor(editor)\n\t, m_asset_browser(asset_browser)\n{\n\tm_filter[0] = '\\0';\n\tm_terrain_editor = editor.getAllocator().newObject<TerrainEditor>(editor);\n}\n\n\nPropertyGrid::~PropertyGrid()\n{\n\tm_editor.getAllocator().deleteObject(m_terrain_editor);\n}\n\n\nbool PropertyGrid::getResourcePath(char* buf, int max_size, uint32_t resource_type)\n{\n\tImGui::InputText(\"Filter\", m_filter, sizeof(m_filter));\n\n\tauto type = m_asset_browser.getTypeFromResourceManagerType(resource_type);\n\tfor (auto unv : m_asset_browser.getResources(type))\n\t{\n\t\tif (m_filter[0] != '\\0' && strstr(unv.c_str(), m_filter) == nullptr) continue;\n\n\t\tif (ImGui::Selectable(unv.c_str(), false))\n\t\t{\n\t\t\tLumix::copyString(buf, max_size, unv.c_str());\n\t\t\tImGui::EndPopup();\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tImGui::EndPopup();\n\treturn false;\n}\n\n\nvoid PropertyGrid::showProperty(Lumix::IPropertyDescriptor& desc, int index, Lumix::ComponentUID cmp)\n{\n\tLumix::OutputBlob stream(m_editor.getAllocator());\n\tif (index < 0)\n\t\tdesc.get(cmp, stream);\n\telse\n\t\tdesc.get(cmp, index, stream);\n\tLumix::InputBlob tmp(stream);\n\n\tswitch (desc.getType())\n\t{\n\tcase Lumix::IPropertyDescriptor::DECIMAL:\n\t{\n\t\tfloat f;\n\t\ttmp.read(f);\n\t\tauto& d = static_cast<Lumix::IDecimalPropertyDescriptor&>(desc);\n\t\tif ((d.getMax() - d.getMin()) \/ d.getStep() <= 100)\n\t\t{\n\t\t\tif (ImGui::SliderFloat(desc.getName(), &f, d.getMin(), d.getMax()))\n\t\t\t{\n\t\t\t\tm_editor.setProperty(cmp.type, index, desc, &f, sizeof(f));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (ImGui::DragFloat(desc.getName(), &f, d.getStep(), d.getMin(), d.getMax()))\n\t\t\t{\n\t\t\t\tm_editor.setProperty(cmp.type, index, desc, &f, sizeof(f));\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::INTEGER:\n\t{\n\t\tint i;\n\t\ttmp.read(i);\n\t\tif (ImGui::DragInt(desc.getName(), &i))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &i, sizeof(i));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::BOOL:\n\t{\n\t\tbool b;\n\t\ttmp.read(b);\n\t\tif (ImGui::Checkbox(desc.getName(), &b))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &b, sizeof(b));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::COLOR:\n\t{\n\t\tLumix::Vec3 v;\n\t\ttmp.read(v);\n\t\tif (ImGui::ColorEdit3(desc.getName(), &v.x))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &v, sizeof(v));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::VEC3:\n\t{\n\t\tLumix::Vec3 v;\n\t\ttmp.read(v);\n\t\tif (ImGui::DragFloat3(desc.getName(), &v.x))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &v, sizeof(v));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::VEC4:\n\t{\n\t\tLumix::Vec4 v;\n\t\ttmp.read(v);\n\t\tif (ImGui::DragFloat4(desc.getName(), &v.x))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &v, sizeof(v));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::RESOURCE:\n\t{\n\t\tchar buf[1024];\n\t\tLumix::copyString(buf, sizeof(buf), (const char*)stream.getData());\n\t\tif (ImGui::InputText(\"\", buf, sizeof(buf)))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, buf, strlen(buf) + 1);\n\t\t}\n\t\tImGui::SameLine();\n\t\tif (ImGui::Button(\"Select\"))\n\t\t\tImGui::OpenPopup(\"SelectResourcePopup\");\n\t\tif (ImGui::BeginPopup(\"SelectResourcePopup\"))\n\t\t{\n\t\t\tauto& resource_descriptor = dynamic_cast<Lumix::ResourcePropertyDescriptorBase&>(desc);\n\t\t\tif (getResourcePath(buf, sizeof(buf), resource_descriptor.getResourceType()))\n\t\t\t{\n\t\t\t\tm_editor.setProperty(cmp.type, index, desc, buf, strlen(buf) + 1);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::STRING:\n\tcase Lumix::IPropertyDescriptor::FILE:\n\t{\n\t\tchar buf[1024];\n\t\tLumix::copyString(buf, sizeof(buf), (const char*)stream.getData());\n\t\tif (ImGui::InputText(desc.getName(), buf, sizeof(buf)))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, buf, strlen(buf) + 1);\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::ARRAY:\n\t\tshowArrayProperty(cmp, static_cast<Lumix::IArrayDescriptor&>(desc));\n\t\tbreak;\n\tdefault:\n\t\tASSERT(false);\n\t\tbreak;\n\t}\n}\n\n\nvoid PropertyGrid::showArrayProperty(Lumix::ComponentUID cmp, Lumix::IArrayDescriptor& desc)\n{\n\tif (!ImGui::CollapsingHeader(desc.getName(), nullptr, true, true)) return;\n\n\tint count = desc.getCount(cmp);\n\tif (ImGui::Button(\"Add\"))\n\t{\n\t\tdesc.addArrayItem(cmp, count);\n\t}\n\tcount = desc.getCount(cmp);\n\n\tfor (int i = 0; i < count; ++i)\n\t{\n\t\tchar tmp[10];\n\t\tLumix::toCString(i, tmp, sizeof(tmp));\n\t\tif (ImGui::TreeNode(tmp))\n\t\t{\n\t\t\tImGui::SameLine();\n\t\t\tif (ImGui::Button(\"Remove\"))\n\t\t\t{\n\t\t\t\tdesc.removeArrayItem(cmp, i);\n\t\t\t\t--i;\n\t\t\t\tcount = desc.getCount(cmp);\n\t\t\t\tImGui::TreePop();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < desc.getChildren().size(); ++j)\n\t\t\t{\n\t\t\t\tauto* child = desc.getChildren()[j];\n\t\t\t\tshowProperty(*child, i, cmp);\n\t\t\t}\n\t\t\tImGui::TreePop();\n\t\t}\n\t}\n}\n\n\nvoid PropertyGrid::showComponentProperties(Lumix::ComponentUID cmp)\n{\n\tif (!ImGui::CollapsingHeader(\n\t\tgetComponentTypeName(cmp), nullptr, true, true))\n\t\treturn;\n\tif (ImGui::Button(\n\t\tStringBuilder<30>(\"Remove component##\", cmp.type)))\n\t{\n\t\tm_editor.destroyComponent(cmp);\n\t\treturn;\n\t}\n\n\tauto& descs = m_editor.getEngine().getPropertyDescriptors(cmp.type);\n\n\tfor (auto* desc : descs)\n\t{\n\t\tshowProperty(*desc, -1, cmp);\n\t}\n\n\tif (cmp.type == Lumix::crc32(\"terrain\"))\n\t{\n\t\tm_terrain_editor->setComponent(cmp);\n\t\tm_terrain_editor->onGui();\n\t}\n}\n\n\nvoid PropertyGrid::showCoreProperties(Lumix::Entity entity)\n{\n\tchar name[256];\n\tconst char* tmp = m_editor.getUniverse()->getEntityName(entity);\n\tLumix::copyString(name, sizeof(name), tmp);\n\tif (ImGui::InputText(\"Name\", name, sizeof(name)))\n\t{\n\t\tm_editor.setEntityName(entity, name);\n\t}\n\n\tauto pos = m_editor.getUniverse()->getPosition(entity);\n\tif (ImGui::DragFloat3(\"Position\", &pos.x))\n\t{\n\t\tm_editor.setEntitiesPositions(&entity, &pos, 1);\n\t}\n\n\tauto rot = m_editor.getUniverse()->getRotation(entity);\n\tif (ImGui::DragFloat4(\"Rotation\", &rot.x))\n\t{\n\t\tm_editor.setEntitiesRotations(&entity, &rot, 1);\n\t}\n\n\tfloat scale = m_editor.getUniverse()->getScale(entity);\n\tif (ImGui::DragFloat(\"Scale\", &scale, 0.1f))\n\t{\n\t\tm_editor.setEntitiesScales(&entity, &scale, 1);\n\t}\n}\n\n\nvoid PropertyGrid::onGui()\n{\n\tif (!m_is_opened) return;\n\n\tauto& ents = m_editor.getSelectedEntities();\n\tif (ImGui::Begin(\"Properties\", &m_is_opened) && ents.size() == 1)\n\t{\n\t\tif (ImGui::Button(\"Add component\"))\n\t\t{\n\t\t\tImGui::OpenPopup(\"AddComponentPopup\");\n\t\t}\n\t\tif (ImGui::BeginPopup(\"AddComponentPopup\"))\n\t\t{\n\t\t\tfor (int i = 0;\n\t\t\t\ti < m_editor.getEngine().getComponentTypesCount();\n\t\t\t\t++i)\n\t\t\t{\n\t\t\t\tif (ImGui::Selectable(\n\t\t\t\t\tm_editor.getEngine().getComponentTypeName(i)))\n\t\t\t\t{\n\t\t\t\t\tm_editor.addComponent(Lumix::crc32(\n\t\t\t\t\t\tm_editor.getEngine().getComponentTypeID(i)));\n\t\t\t\t}\n\t\t\t}\n\t\t\tImGui::EndPopup();\n\t\t}\n\n\t\tshowCoreProperties(ents[0]);\n\n\t\tauto& cmps = m_editor.getComponents(ents[0]);\n\t\tfor (auto cmp : cmps)\n\t\t{\n\t\t\tshowComponentProperties(cmp);\n\t\t}\n\n\t}\n\tImGui::End();\n}\n\n\n<commit_msg>add\/remove array item in property grid goes through the undo system<commit_after>#include \"property_grid.h\"\n#include \"asset_browser.h\"\n#include \"core\/crc32.h\"\n#include \"editor\/world_editor.h\"\n#include \"engine\/engine.h\"\n#include \"engine\/property_descriptor.h\"\n#include \"ocornut-imgui\/imgui.h\"\n#include \"string_builder.h\"\n#include \"terrain_editor.h\"\n\n\nconst char* PropertyGrid::getComponentTypeName(Lumix::ComponentUID cmp) const\n{\n\tauto& engine = m_editor.getEngine();\n\tfor (int i = 0; i < engine.getComponentTypesCount(); ++i)\n\t{\n\t\tif (cmp.type ==\n\t\t\tLumix::crc32(engine.getComponentTypeID(i)))\n\t\t{\n\t\t\treturn engine.getComponentTypeName(i);\n\t\t}\n\t}\n\treturn \"Unknown\";\n}\n\n\n\nPropertyGrid::PropertyGrid(Lumix::WorldEditor& editor, AssetBrowser& asset_browser)\n\t: m_is_opened(true)\n\t, m_editor(editor)\n\t, m_asset_browser(asset_browser)\n{\n\tm_filter[0] = '\\0';\n\tm_terrain_editor = editor.getAllocator().newObject<TerrainEditor>(editor);\n}\n\n\nPropertyGrid::~PropertyGrid()\n{\n\tm_editor.getAllocator().deleteObject(m_terrain_editor);\n}\n\n\nbool PropertyGrid::getResourcePath(char* buf, int max_size, uint32_t resource_type)\n{\n\tImGui::InputText(\"Filter\", m_filter, sizeof(m_filter));\n\n\tauto type = m_asset_browser.getTypeFromResourceManagerType(resource_type);\n\tfor (auto unv : m_asset_browser.getResources(type))\n\t{\n\t\tif (m_filter[0] != '\\0' && strstr(unv.c_str(), m_filter) == nullptr) continue;\n\n\t\tif (ImGui::Selectable(unv.c_str(), false))\n\t\t{\n\t\t\tLumix::copyString(buf, max_size, unv.c_str());\n\t\t\tImGui::EndPopup();\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tImGui::EndPopup();\n\treturn false;\n}\n\n\nvoid PropertyGrid::showProperty(Lumix::IPropertyDescriptor& desc, int index, Lumix::ComponentUID cmp)\n{\n\tLumix::OutputBlob stream(m_editor.getAllocator());\n\tif (index < 0)\n\t\tdesc.get(cmp, stream);\n\telse\n\t\tdesc.get(cmp, index, stream);\n\tLumix::InputBlob tmp(stream);\n\n\tswitch (desc.getType())\n\t{\n\tcase Lumix::IPropertyDescriptor::DECIMAL:\n\t{\n\t\tfloat f;\n\t\ttmp.read(f);\n\t\tauto& d = static_cast<Lumix::IDecimalPropertyDescriptor&>(desc);\n\t\tif ((d.getMax() - d.getMin()) \/ d.getStep() <= 100)\n\t\t{\n\t\t\tif (ImGui::SliderFloat(desc.getName(), &f, d.getMin(), d.getMax()))\n\t\t\t{\n\t\t\t\tm_editor.setProperty(cmp.type, index, desc, &f, sizeof(f));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (ImGui::DragFloat(desc.getName(), &f, d.getStep(), d.getMin(), d.getMax()))\n\t\t\t{\n\t\t\t\tm_editor.setProperty(cmp.type, index, desc, &f, sizeof(f));\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::INTEGER:\n\t{\n\t\tint i;\n\t\ttmp.read(i);\n\t\tif (ImGui::DragInt(desc.getName(), &i))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &i, sizeof(i));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::BOOL:\n\t{\n\t\tbool b;\n\t\ttmp.read(b);\n\t\tif (ImGui::Checkbox(desc.getName(), &b))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &b, sizeof(b));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::COLOR:\n\t{\n\t\tLumix::Vec3 v;\n\t\ttmp.read(v);\n\t\tif (ImGui::ColorEdit3(desc.getName(), &v.x))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &v, sizeof(v));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::VEC3:\n\t{\n\t\tLumix::Vec3 v;\n\t\ttmp.read(v);\n\t\tif (ImGui::DragFloat3(desc.getName(), &v.x))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &v, sizeof(v));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::VEC4:\n\t{\n\t\tLumix::Vec4 v;\n\t\ttmp.read(v);\n\t\tif (ImGui::DragFloat4(desc.getName(), &v.x))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, &v, sizeof(v));\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::RESOURCE:\n\t{\n\t\tchar buf[1024];\n\t\tLumix::copyString(buf, sizeof(buf), (const char*)stream.getData());\n\t\tif (ImGui::InputText(\"\", buf, sizeof(buf)))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, buf, strlen(buf) + 1);\n\t\t}\n\t\tImGui::SameLine();\n\t\tif (ImGui::Button(\"Select\"))\n\t\t\tImGui::OpenPopup(\"SelectResourcePopup\");\n\t\tif (ImGui::BeginPopup(\"SelectResourcePopup\"))\n\t\t{\n\t\t\tauto& resource_descriptor = dynamic_cast<Lumix::ResourcePropertyDescriptorBase&>(desc);\n\t\t\tif (getResourcePath(buf, sizeof(buf), resource_descriptor.getResourceType()))\n\t\t\t{\n\t\t\t\tm_editor.setProperty(cmp.type, index, desc, buf, strlen(buf) + 1);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::STRING:\n\tcase Lumix::IPropertyDescriptor::FILE:\n\t{\n\t\tchar buf[1024];\n\t\tLumix::copyString(buf, sizeof(buf), (const char*)stream.getData());\n\t\tif (ImGui::InputText(desc.getName(), buf, sizeof(buf)))\n\t\t{\n\t\t\tm_editor.setProperty(cmp.type, index, desc, buf, strlen(buf) + 1);\n\t\t}\n\t\tbreak;\n\t}\n\tcase Lumix::IPropertyDescriptor::ARRAY:\n\t\tshowArrayProperty(cmp, static_cast<Lumix::IArrayDescriptor&>(desc));\n\t\tbreak;\n\tdefault:\n\t\tASSERT(false);\n\t\tbreak;\n\t}\n}\n\n\nvoid PropertyGrid::showArrayProperty(Lumix::ComponentUID cmp, Lumix::IArrayDescriptor& desc)\n{\n\tif (!ImGui::CollapsingHeader(desc.getName(), nullptr, true, true)) return;\n\n\tint count = desc.getCount(cmp);\n\tif (ImGui::Button(\"Add\"))\n\t{\n\t\tm_editor.addArrayPropertyItem(cmp, desc);\n\t}\n\tcount = desc.getCount(cmp);\n\n\tfor (int i = 0; i < count; ++i)\n\t{\n\t\tchar tmp[10];\n\t\tLumix::toCString(i, tmp, sizeof(tmp));\n\t\tif (ImGui::TreeNode(tmp))\n\t\t{\n\t\t\tImGui::SameLine();\n\t\t\tif (ImGui::Button(\"Remove\"))\n\t\t\t{\n\t\t\t\tm_editor.removeArrayPropertyItem(cmp, i, desc);\n\t\t\t\t--i;\n\t\t\t\tcount = desc.getCount(cmp);\n\t\t\t\tImGui::TreePop();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < desc.getChildren().size(); ++j)\n\t\t\t{\n\t\t\t\tauto* child = desc.getChildren()[j];\n\t\t\t\tshowProperty(*child, i, cmp);\n\t\t\t}\n\t\t\tImGui::TreePop();\n\t\t}\n\t}\n}\n\n\nvoid PropertyGrid::showComponentProperties(Lumix::ComponentUID cmp)\n{\n\tif (!ImGui::CollapsingHeader(\n\t\tgetComponentTypeName(cmp), nullptr, true, true))\n\t\treturn;\n\tif (ImGui::Button(\n\t\tStringBuilder<30>(\"Remove component##\", cmp.type)))\n\t{\n\t\tm_editor.destroyComponent(cmp);\n\t\treturn;\n\t}\n\n\tauto& descs = m_editor.getEngine().getPropertyDescriptors(cmp.type);\n\n\tfor (auto* desc : descs)\n\t{\n\t\tshowProperty(*desc, -1, cmp);\n\t}\n\n\tif (cmp.type == Lumix::crc32(\"terrain\"))\n\t{\n\t\tm_terrain_editor->setComponent(cmp);\n\t\tm_terrain_editor->onGui();\n\t}\n}\n\n\nvoid PropertyGrid::showCoreProperties(Lumix::Entity entity)\n{\n\tchar name[256];\n\tconst char* tmp = m_editor.getUniverse()->getEntityName(entity);\n\tLumix::copyString(name, sizeof(name), tmp);\n\tif (ImGui::InputText(\"Name\", name, sizeof(name)))\n\t{\n\t\tm_editor.setEntityName(entity, name);\n\t}\n\n\tauto pos = m_editor.getUniverse()->getPosition(entity);\n\tif (ImGui::DragFloat3(\"Position\", &pos.x))\n\t{\n\t\tm_editor.setEntitiesPositions(&entity, &pos, 1);\n\t}\n\n\tauto rot = m_editor.getUniverse()->getRotation(entity);\n\tif (ImGui::DragFloat4(\"Rotation\", &rot.x))\n\t{\n\t\tm_editor.setEntitiesRotations(&entity, &rot, 1);\n\t}\n\n\tfloat scale = m_editor.getUniverse()->getScale(entity);\n\tif (ImGui::DragFloat(\"Scale\", &scale, 0.1f))\n\t{\n\t\tm_editor.setEntitiesScales(&entity, &scale, 1);\n\t}\n}\n\n\nvoid PropertyGrid::onGui()\n{\n\tif (!m_is_opened) return;\n\n\tauto& ents = m_editor.getSelectedEntities();\n\tif (ImGui::Begin(\"Properties\", &m_is_opened) && ents.size() == 1)\n\t{\n\t\tif (ImGui::Button(\"Add component\"))\n\t\t{\n\t\t\tImGui::OpenPopup(\"AddComponentPopup\");\n\t\t}\n\t\tif (ImGui::BeginPopup(\"AddComponentPopup\"))\n\t\t{\n\t\t\tfor (int i = 0;\n\t\t\t\ti < m_editor.getEngine().getComponentTypesCount();\n\t\t\t\t++i)\n\t\t\t{\n\t\t\t\tif (ImGui::Selectable(\n\t\t\t\t\tm_editor.getEngine().getComponentTypeName(i)))\n\t\t\t\t{\n\t\t\t\t\tm_editor.addComponent(Lumix::crc32(\n\t\t\t\t\t\tm_editor.getEngine().getComponentTypeID(i)));\n\t\t\t\t}\n\t\t\t}\n\t\t\tImGui::EndPopup();\n\t\t}\n\n\t\tshowCoreProperties(ents[0]);\n\n\t\tauto& cmps = m_editor.getComponents(ents[0]);\n\t\tfor (auto cmp : cmps)\n\t\t{\n\t\t\tshowComponentProperties(cmp);\n\t\t}\n\n\t}\n\tImGui::End();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011-2015, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"SkeletonSubsystem.h\"\n#include \"SkeletonMappingKeys.h\"\n#include \"SubsystemObjectFactory.h\"\n#include \"SkeletonSubsystemObject.h\"\n\n#define base CSubsystem\n\n\/\/ Implementation\nCSkeletonSubsystem::CSkeletonSubsystem(const std::string &strName, core::log::Logger &logger)\n : base(strName, logger)\n{\n \/\/ Provide mapping keys to upper layer\n addContextMappingKey(\"Owner\");\n addContextMappingKey(\"Amend1\");\n addContextMappingKey(\"Amend2\");\n\n \/\/ Provide creators to upper layer\n addSubsystemObjectFactory(\n new TSubsystemObjectFactory<CSkeletonSubsystemObject>(\"Message\", 1 << ESkeletonOwner));\n}\n<commit_msg>remove base define<commit_after>\/*\n * Copyright (c) 2011-2015, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY 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\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"SkeletonSubsystem.h\"\n#include \"SkeletonMappingKeys.h\"\n#include \"SubsystemObjectFactory.h\"\n#include \"SkeletonSubsystemObject.h\"\n\n\/\/ Implementation\nCSkeletonSubsystem::CSkeletonSubsystem(const std::string &strName, core::log::Logger &logger)\n : CSubsystem(strName, logger)\n{\n \/\/ Provide mapping keys to upper layer\n addContextMappingKey(\"Owner\");\n addContextMappingKey(\"Amend1\");\n addContextMappingKey(\"Amend2\");\n\n \/\/ Provide creators to upper layer\n addSubsystemObjectFactory(\n new TSubsystemObjectFactory<CSkeletonSubsystemObject>(\"Message\", 1 << ESkeletonOwner));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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 \"skia\/ext\/bitmap_platform_device_linux.h\"\n\n#include \"skia\/ext\/bitmap_platform_device_data.h\"\n\n#include <cairo\/cairo.h>\n\nnamespace skia {\n\nnamespace {\n\nvoid LoadMatrixToContext(cairo_t* context, const SkMatrix& matrix) {\n cairo_matrix_t cairo_matrix;\n cairo_matrix_init(&cairo_matrix,\n SkScalarToFloat(matrix.getScaleX()),\n SkScalarToFloat(matrix.getSkewY()),\n SkScalarToFloat(matrix.getSkewX()),\n SkScalarToFloat(matrix.getScaleY()),\n SkScalarToFloat(matrix.getTranslateX()),\n SkScalarToFloat(matrix.getTranslateY()));\n cairo_set_matrix(context, &cairo_matrix);\n}\n\nvoid LoadClipToContext(cairo_t* context, const SkRegion& clip) {\n cairo_reset_clip(context);\n\n \/\/ TODO(brettw) support non-rect clips.\n SkIRect bounding = clip.getBounds();\n cairo_rectangle(context, bounding.fLeft, bounding.fTop,\n bounding.fRight - bounding.fLeft,\n bounding.fBottom - bounding.fTop);\n cairo_clip(context);\n}\n\n} \/\/ namespace\n\nSkDevice* BitmapPlatformDeviceFactory::newDevice(SkBitmap::Config config,\n int width, int height,\n bool isOpaque,\n bool isForLayer) {\n SkASSERT(config == SkBitmap::kARGB_8888_Config);\n return BitmapPlatformDevice::Create(width, height, isOpaque);\n}\n\nBitmapPlatformDevice::BitmapPlatformDeviceData::BitmapPlatformDeviceData(\n cairo_surface_t* surface)\n : surface_(surface),\n config_dirty_(true) { \/\/ Want to load the config next time.\n bitmap_context_ = cairo_create(surface);\n}\n\nBitmapPlatformDevice::BitmapPlatformDeviceData::~BitmapPlatformDeviceData() {\n cairo_destroy(bitmap_context_);\n cairo_surface_destroy(surface_);\n}\n\nvoid BitmapPlatformDevice::BitmapPlatformDeviceData::SetMatrixClip(\n const SkMatrix& transform,\n const SkRegion& region) {\n transform_ = transform;\n clip_region_ = region;\n config_dirty_ = true;\n}\n\nvoid BitmapPlatformDevice::BitmapPlatformDeviceData::LoadConfig() {\n if (!config_dirty_ || !bitmap_context_)\n return; \/\/ Nothing to do.\n config_dirty_ = false;\n\n \/\/ Load the identity matrix since this is what our clip is relative to.\n cairo_matrix_t cairo_matrix;\n cairo_matrix_init_identity(&cairo_matrix);\n cairo_set_matrix(bitmap_context_, &cairo_matrix);\n\n LoadClipToContext(bitmap_context_, clip_region_);\n LoadMatrixToContext(bitmap_context_, transform_);\n}\n\n\/\/ We use this static factory function instead of the regular constructor so\n\/\/ that we can create the pixel data before calling the constructor. This is\n\/\/ required so that we can call the base class' constructor with the pixel\n\/\/ data.\nBitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,\n bool is_opaque,\n cairo_surface_t* surface) {\n SkBitmap bitmap;\n bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height,\n cairo_image_surface_get_stride(surface));\n bitmap.setPixels(cairo_image_surface_get_data(surface));\n bitmap.setIsOpaque(is_opaque);\n\n \/\/ The device object will take ownership of the graphics context.\n return new BitmapPlatformDevice\n (bitmap, new BitmapPlatformDeviceData(surface));\n}\n\nBitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,\n bool is_opaque) {\n cairo_surface_t* surface =\n cairo_image_surface_create(CAIRO_FORMAT_ARGB32,\n width, height);\n\n BitmapPlatformDevice* device = Create(width, height, is_opaque, surface);\n\n#ifndef NDEBUG\n if (is_opaque) \/\/ Fill with bright bluish green\n device->eraseColor(SkColorSetARGB(255, 0, 255, 128));\n#endif\n\n return device;\n}\n\nBitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,\n bool is_opaque,\n uint8_t* data) {\n cairo_surface_t* surface = cairo_image_surface_create_for_data(\n data, CAIRO_FORMAT_ARGB32, width, height,\n cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width));\n\n return Create(width, height, is_opaque, surface);\n}\n\n\/\/ The device will own the bitmap, which corresponds to also owning the pixel\n\/\/ data. Therefore, we do not transfer ownership to the SkDevice's bitmap.\nBitmapPlatformDevice::BitmapPlatformDevice(\n const SkBitmap& bitmap,\n BitmapPlatformDeviceData* data)\n : PlatformDevice(bitmap),\n data_(data) {\n}\n\nBitmapPlatformDevice::BitmapPlatformDevice(\n const BitmapPlatformDevice& other)\n : PlatformDevice(const_cast<BitmapPlatformDevice&>(\n other).accessBitmap(true)),\n data_(other.data_) {\n}\n\nBitmapPlatformDevice::~BitmapPlatformDevice() {\n}\n\nSkDeviceFactory* BitmapPlatformDevice::getDeviceFactory() {\n return SkNEW(BitmapPlatformDeviceFactory);\n}\n\nbool BitmapPlatformDevice::IsVectorial() {\n return false;\n}\n\ncairo_t* BitmapPlatformDevice::beginPlatformPaint() {\n data_->LoadConfig();\n cairo_t* cairo = data_->bitmap_context();\n \/\/ Tell Cairo that we've (probably) modified its pixel buffer without\n \/\/ its knowledge.\n cairo_surface_mark_dirty(cairo_get_target(cairo));\n return cairo;\n}\n\nvoid BitmapPlatformDevice::setMatrixClip(const SkMatrix& transform,\n const SkRegion& region) {\n data_->SetMatrixClip(transform, region);\n}\n\nBitmapPlatformDevice& BitmapPlatformDevice::operator=(\n const BitmapPlatformDevice& other) {\n data_ = other.data_;\n return *this;\n}\n\n} \/\/ namespace skia\n<commit_msg>Flush the cairo surface before we try to write to it.<commit_after>\/\/ Copyright (c) 2010 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 \"skia\/ext\/bitmap_platform_device_linux.h\"\n\n#include \"skia\/ext\/bitmap_platform_device_data.h\"\n\n#include <cairo\/cairo.h>\n\nnamespace skia {\n\nnamespace {\n\nvoid LoadMatrixToContext(cairo_t* context, const SkMatrix& matrix) {\n cairo_matrix_t cairo_matrix;\n cairo_matrix_init(&cairo_matrix,\n SkScalarToFloat(matrix.getScaleX()),\n SkScalarToFloat(matrix.getSkewY()),\n SkScalarToFloat(matrix.getSkewX()),\n SkScalarToFloat(matrix.getScaleY()),\n SkScalarToFloat(matrix.getTranslateX()),\n SkScalarToFloat(matrix.getTranslateY()));\n cairo_set_matrix(context, &cairo_matrix);\n}\n\nvoid LoadClipToContext(cairo_t* context, const SkRegion& clip) {\n cairo_reset_clip(context);\n\n \/\/ TODO(brettw) support non-rect clips.\n SkIRect bounding = clip.getBounds();\n cairo_rectangle(context, bounding.fLeft, bounding.fTop,\n bounding.fRight - bounding.fLeft,\n bounding.fBottom - bounding.fTop);\n cairo_clip(context);\n}\n\n} \/\/ namespace\n\nSkDevice* BitmapPlatformDeviceFactory::newDevice(SkBitmap::Config config,\n int width, int height,\n bool isOpaque,\n bool isForLayer) {\n SkASSERT(config == SkBitmap::kARGB_8888_Config);\n return BitmapPlatformDevice::Create(width, height, isOpaque);\n}\n\nBitmapPlatformDevice::BitmapPlatformDeviceData::BitmapPlatformDeviceData(\n cairo_surface_t* surface)\n : surface_(surface),\n config_dirty_(true) { \/\/ Want to load the config next time.\n bitmap_context_ = cairo_create(surface);\n}\n\nBitmapPlatformDevice::BitmapPlatformDeviceData::~BitmapPlatformDeviceData() {\n cairo_destroy(bitmap_context_);\n cairo_surface_destroy(surface_);\n}\n\nvoid BitmapPlatformDevice::BitmapPlatformDeviceData::SetMatrixClip(\n const SkMatrix& transform,\n const SkRegion& region) {\n transform_ = transform;\n clip_region_ = region;\n config_dirty_ = true;\n}\n\nvoid BitmapPlatformDevice::BitmapPlatformDeviceData::LoadConfig() {\n if (!config_dirty_ || !bitmap_context_)\n return; \/\/ Nothing to do.\n config_dirty_ = false;\n\n \/\/ Load the identity matrix since this is what our clip is relative to.\n cairo_matrix_t cairo_matrix;\n cairo_matrix_init_identity(&cairo_matrix);\n cairo_set_matrix(bitmap_context_, &cairo_matrix);\n\n LoadClipToContext(bitmap_context_, clip_region_);\n LoadMatrixToContext(bitmap_context_, transform_);\n}\n\n\/\/ We use this static factory function instead of the regular constructor so\n\/\/ that we can create the pixel data before calling the constructor. This is\n\/\/ required so that we can call the base class' constructor with the pixel\n\/\/ data.\nBitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,\n bool is_opaque,\n cairo_surface_t* surface) {\n SkBitmap bitmap;\n bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height,\n cairo_image_surface_get_stride(surface));\n bitmap.setPixels(cairo_image_surface_get_data(surface));\n bitmap.setIsOpaque(is_opaque);\n\n \/\/ The device object will take ownership of the graphics context.\n return new BitmapPlatformDevice\n (bitmap, new BitmapPlatformDeviceData(surface));\n}\n\nBitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,\n bool is_opaque) {\n cairo_surface_t* surface =\n cairo_image_surface_create(CAIRO_FORMAT_ARGB32,\n width, height);\n\n BitmapPlatformDevice* device = Create(width, height, is_opaque, surface);\n\n#ifndef NDEBUG\n if (is_opaque) \/\/ Fill with bright bluish green\n device->eraseColor(SkColorSetARGB(255, 0, 255, 128));\n#endif\n\n return device;\n}\n\nBitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,\n bool is_opaque,\n uint8_t* data) {\n cairo_surface_t* surface = cairo_image_surface_create_for_data(\n data, CAIRO_FORMAT_ARGB32, width, height,\n cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width));\n\n return Create(width, height, is_opaque, surface);\n}\n\n\/\/ The device will own the bitmap, which corresponds to also owning the pixel\n\/\/ data. Therefore, we do not transfer ownership to the SkDevice's bitmap.\nBitmapPlatformDevice::BitmapPlatformDevice(\n const SkBitmap& bitmap,\n BitmapPlatformDeviceData* data)\n : PlatformDevice(bitmap),\n data_(data) {\n}\n\nBitmapPlatformDevice::BitmapPlatformDevice(\n const BitmapPlatformDevice& other)\n : PlatformDevice(const_cast<BitmapPlatformDevice&>(\n other).accessBitmap(true)),\n data_(other.data_) {\n}\n\nBitmapPlatformDevice::~BitmapPlatformDevice() {\n}\n\nSkDeviceFactory* BitmapPlatformDevice::getDeviceFactory() {\n return SkNEW(BitmapPlatformDeviceFactory);\n}\n\nbool BitmapPlatformDevice::IsVectorial() {\n return false;\n}\n\ncairo_t* BitmapPlatformDevice::beginPlatformPaint() {\n data_->LoadConfig();\n cairo_t* cairo = data_->bitmap_context();\n cairo_surface_t* surface = cairo_get_target(cairo);\n \/\/ Tell cairo to flush anything it has pending.\n cairo_surface_flush(surface);\n \/\/ Tell Cairo that we (probably) modified (actually, will modify) its pixel\n \/\/ buffer directly.\n cairo_surface_mark_dirty(surface);\n return cairo;\n}\n\nvoid BitmapPlatformDevice::setMatrixClip(const SkMatrix& transform,\n const SkRegion& region) {\n data_->SetMatrixClip(transform, region);\n}\n\nBitmapPlatformDevice& BitmapPlatformDevice::operator=(\n const BitmapPlatformDevice& other) {\n data_ = other.data_;\n return *this;\n}\n\n} \/\/ namespace skia\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: attributemap.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2006-12-13 15:12:49 $\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_slideshow.hxx\"\n\n\/\/ must be first\n#include <canvas\/debug.hxx>\n#include <canvas\/canvastools.hxx>\n\n#include \"attributemap.hxx\"\n#include \"tools.hxx\"\n\n\nnamespace slideshow\n{\n namespace internal\n {\n typedef ::canvas::tools::ValueMap< AttributeType > AnimateAttributeMap;\n\n AttributeType mapAttributeName( const ::rtl::OUString& rAttrName )\n {\n \/** Maps attribute name to AttributeType enum.\n\n String entries are all case-insensitive and MUST\n BE STORED lowercase.\n\n String entries MUST BE SORTED in ascending order!\n *\/\n static AnimateAttributeMap::MapEntry lcl_attributeMap[] =\n {\n { \"charcolor\", ATTRIBUTE_CHAR_COLOR },\n\n { \"charfontname\", ATTRIBUTE_CHAR_FONT_NAME },\n\n { \"charheight\", ATTRIBUTE_CHAR_HEIGHT },\n\n { \"charposture\", ATTRIBUTE_CHAR_POSTURE },\n\n \/\/ TODO(Q1): This should prolly be changed in PPT import\n \/\/ { \"charrotation\", ATTRIBUTE_CHAR_ROTATION },\n { \"charrotation\", ATTRIBUTE_ROTATE },\n\n { \"charunderline\", ATTRIBUTE_CHAR_UNDERLINE },\n\n { \"charweight\", ATTRIBUTE_CHAR_WEIGHT },\n\n { \"color\", ATTRIBUTE_COLOR },\n\n { \"dimcolor\", ATTRIBUTE_DIMCOLOR },\n\n { \"fillcolor\", ATTRIBUTE_FILL_COLOR },\n\n { \"fillstyle\", ATTRIBUTE_FILL_STYLE },\n\n { \"height\", ATTRIBUTE_HEIGHT },\n\n { \"linecolor\", ATTRIBUTE_LINE_COLOR },\n\n { \"linestyle\", ATTRIBUTE_LINE_STYLE },\n\n { \"opacity\", ATTRIBUTE_OPACITY },\n\n { \"rotate\", ATTRIBUTE_ROTATE },\n\n { \"skewx\", ATTRIBUTE_SKEW_X },\n\n { \"skewy\", ATTRIBUTE_SKEW_Y },\n\n { \"visibility\", ATTRIBUTE_VISIBILITY },\n\n { \"width\", ATTRIBUTE_WIDTH },\n\n { \"x\", ATTRIBUTE_POS_X },\n\n { \"y\", ATTRIBUTE_POS_Y }\n };\n\n static AnimateAttributeMap aMap( lcl_attributeMap,\n sizeof(lcl_attributeMap)\/sizeof(*lcl_attributeMap),\n false );\n\n AttributeType eAttributeType = ATTRIBUTE_INVALID;\n\n \/\/ determine the type from the attribute name\n if( !aMap.lookup( rAttrName,\n eAttributeType ) )\n {\n OSL_TRACE( \"mapAttributeName(): attribute name %s not found in map.\",\n ::rtl::OUStringToOString( rAttrName,\n RTL_TEXTENCODING_ASCII_US ).getStr() );\n return ATTRIBUTE_INVALID;\n }\n\n return eAttributeType;\n }\n\n }\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.74); FILE MERGED 2008\/03\/31 14:00:13 rt 1.7.74.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: attributemap.cxx,v $\n * $Revision: 1.8 $\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 * <http:\/\/www.openoffice.org\/license.html>\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_slideshow.hxx\"\n\n\/\/ must be first\n#include <canvas\/debug.hxx>\n#include <canvas\/canvastools.hxx>\n\n#include \"attributemap.hxx\"\n#include \"tools.hxx\"\n\n\nnamespace slideshow\n{\n namespace internal\n {\n typedef ::canvas::tools::ValueMap< AttributeType > AnimateAttributeMap;\n\n AttributeType mapAttributeName( const ::rtl::OUString& rAttrName )\n {\n \/** Maps attribute name to AttributeType enum.\n\n String entries are all case-insensitive and MUST\n BE STORED lowercase.\n\n String entries MUST BE SORTED in ascending order!\n *\/\n static AnimateAttributeMap::MapEntry lcl_attributeMap[] =\n {\n { \"charcolor\", ATTRIBUTE_CHAR_COLOR },\n\n { \"charfontname\", ATTRIBUTE_CHAR_FONT_NAME },\n\n { \"charheight\", ATTRIBUTE_CHAR_HEIGHT },\n\n { \"charposture\", ATTRIBUTE_CHAR_POSTURE },\n\n \/\/ TODO(Q1): This should prolly be changed in PPT import\n \/\/ { \"charrotation\", ATTRIBUTE_CHAR_ROTATION },\n { \"charrotation\", ATTRIBUTE_ROTATE },\n\n { \"charunderline\", ATTRIBUTE_CHAR_UNDERLINE },\n\n { \"charweight\", ATTRIBUTE_CHAR_WEIGHT },\n\n { \"color\", ATTRIBUTE_COLOR },\n\n { \"dimcolor\", ATTRIBUTE_DIMCOLOR },\n\n { \"fillcolor\", ATTRIBUTE_FILL_COLOR },\n\n { \"fillstyle\", ATTRIBUTE_FILL_STYLE },\n\n { \"height\", ATTRIBUTE_HEIGHT },\n\n { \"linecolor\", ATTRIBUTE_LINE_COLOR },\n\n { \"linestyle\", ATTRIBUTE_LINE_STYLE },\n\n { \"opacity\", ATTRIBUTE_OPACITY },\n\n { \"rotate\", ATTRIBUTE_ROTATE },\n\n { \"skewx\", ATTRIBUTE_SKEW_X },\n\n { \"skewy\", ATTRIBUTE_SKEW_Y },\n\n { \"visibility\", ATTRIBUTE_VISIBILITY },\n\n { \"width\", ATTRIBUTE_WIDTH },\n\n { \"x\", ATTRIBUTE_POS_X },\n\n { \"y\", ATTRIBUTE_POS_Y }\n };\n\n static AnimateAttributeMap aMap( lcl_attributeMap,\n sizeof(lcl_attributeMap)\/sizeof(*lcl_attributeMap),\n false );\n\n AttributeType eAttributeType = ATTRIBUTE_INVALID;\n\n \/\/ determine the type from the attribute name\n if( !aMap.lookup( rAttrName,\n eAttributeType ) )\n {\n OSL_TRACE( \"mapAttributeName(): attribute name %s not found in map.\",\n ::rtl::OUStringToOString( rAttrName,\n RTL_TEXTENCODING_ASCII_US ).getStr() );\n return ATTRIBUTE_INVALID;\n }\n\n return eAttributeType;\n }\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"slic3r\/Utils\/Bonjour.hpp\" \/\/ On Windows, boost needs to be included before wxWidgets headers\n\n#include \"BonjourDialog.hpp\"\n\n#include <set>\n#include <mutex>\n\n#include <wx\/sizer.h>\n#include <wx\/button.h>\n#include <wx\/listctrl.h>\n#include <wx\/stattext.h>\n#include <wx\/timer.h>\n#include <wx\/wupdlock.h>\n\n#include \"slic3r\/GUI\/GUI.hpp\"\n#include \"slic3r\/GUI\/GUI_App.hpp\"\n#include \"slic3r\/GUI\/I18N.hpp\"\n#include \"slic3r\/Utils\/Bonjour.hpp\"\n\nnamespace Slic3r {\n\n\nclass BonjourReplyEvent : public wxEvent\n{\npublic:\n\tBonjourReply reply;\n\n\tBonjourReplyEvent(wxEventType eventType, int winid, BonjourReply &&reply) :\n\t\twxEvent(winid, eventType),\n\t\treply(std::move(reply))\n\t{}\n\n\tvirtual wxEvent *Clone() const\n\t{\n\t\treturn new BonjourReplyEvent(*this);\n\t}\n};\n\nwxDEFINE_EVENT(EVT_BONJOUR_REPLY, BonjourReplyEvent);\n\nwxDECLARE_EVENT(EVT_BONJOUR_COMPLETE, wxCommandEvent);\nwxDEFINE_EVENT(EVT_BONJOUR_COMPLETE, wxCommandEvent);\n\nclass ReplySet: public std::set<BonjourReply> {};\n\nstruct LifetimeGuard\n{\n\tstd::mutex mutex;\n\tBonjourDialog *dialog;\n\n\tLifetimeGuard(BonjourDialog *dialog) : dialog(dialog) {}\n};\n\nBonjourDialog::BonjourDialog(wxWindow *parent, Slic3r::PrinterTechnology tech)\n\t: wxDialog(parent, wxID_ANY, _(L(\"Network lookup\")), wxDefaultPosition, wxDefaultSize, wxRESIZE_BORDER)\n\t, list(new wxListView(this, wxID_ANY))\n\t, replies(new ReplySet)\n\t, label(new wxStaticText(this, wxID_ANY, \"\"))\n\t, timer(new wxTimer())\n\t, timer_state(0)\n\t, tech(tech)\n{\n\tconst int em = GUI::wxGetApp().em_unit();\n\tlist->SetMinSize(wxSize(80 * em, 30 * em));\n\n\twxBoxSizer *vsizer = new wxBoxSizer(wxVERTICAL);\n\n\tvsizer->Add(label, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, em);\n\n\tlist->SetSingleStyle(wxLC_SINGLE_SEL);\n\tlist->SetSingleStyle(wxLC_SORT_DESCENDING);\n\tlist->AppendColumn(_(L(\"Address\")), wxLIST_FORMAT_LEFT, 5 * em);\n\tlist->AppendColumn(_(L(\"Hostname\")), wxLIST_FORMAT_LEFT, 10 * em);\n\tlist->AppendColumn(_(L(\"Service name\")), wxLIST_FORMAT_LEFT, 20 * em);\n\tif (tech == ptFFF) {\n\t\tlist->AppendColumn(_(L(\"OctoPrint version\")), wxLIST_FORMAT_LEFT, 5 * em);\n\t}\n\n\tvsizer->Add(list, 1, wxEXPAND | wxALL, em);\n\n\twxBoxSizer *button_sizer = new wxBoxSizer(wxHORIZONTAL);\n\tbutton_sizer->Add(new wxButton(this, wxID_OK, \"OK\"), 0, wxALL, em);\n\tbutton_sizer->Add(new wxButton(this, wxID_CANCEL, \"Cancel\"), 0, wxALL, em);\n\t\/\/ ^ Note: The Ok\/Cancel labels are translated by wxWidgets\n\n\tvsizer->Add(button_sizer, 0, wxALIGN_CENTER);\n\tSetSizerAndFit(vsizer);\n\n\tBind(EVT_BONJOUR_REPLY, &BonjourDialog::on_reply, this);\n\n\tBind(EVT_BONJOUR_COMPLETE, [this](wxCommandEvent &) {\n\t\tthis->timer_state = 0;\n\t});\n\n\tBind(wxEVT_TIMER, &BonjourDialog::on_timer, this);\n}\n\nBonjourDialog::~BonjourDialog()\n{\n\t\/\/ Needed bacuse of forward defs\n}\n\nbool BonjourDialog::show_and_lookup()\n{\n\tShow(); \/\/ Because we need GetId() to work before ShowModal()\n\n\ttimer->Stop();\n\ttimer->SetOwner(this);\n\ttimer_state = 1;\n\ttimer->Start(1000);\n\twxTimerEvent evt_dummy;\n\ton_timer(evt_dummy);\n\n\t\/\/ The background thread needs to queue messages for this dialog\n\t\/\/ and for that it needs a valid pointer to it (mandated by the wxWidgets API).\n\t\/\/ Here we put the pointer under a shared_ptr and protect it by a mutex,\n\t\/\/ so that both threads can access it safely.\n\tauto dguard = std::make_shared<LifetimeGuard>(this);\n\n\t\/\/ Note: More can be done here when we support discovery of hosts other than Octoprint and SL1\n\tBonjour::TxtKeys txt_keys { \"version\", \"model\" };\n\n\tbonjour = std::move(Bonjour(\"octoprint\")\n\t\t.set_txt_keys(std::move(txt_keys))\n\t\t.set_retries(3)\n\t\t.set_timeout(4)\n\t\t.on_reply([dguard](BonjourReply &&reply) {\n\t\t\tstd::lock_guard<std::mutex> lock_guard(dguard->mutex);\n\t\t\tauto dialog = dguard->dialog;\n\t\t\tif (dialog != nullptr) {\n\t\t\t\tauto evt = new BonjourReplyEvent(EVT_BONJOUR_REPLY, dialog->GetId(), std::move(reply));\n\t\t\t\twxQueueEvent(dialog, evt);\n\t\t\t}\n\t\t})\n\t\t.on_complete([dguard]() {\n\t\t\tstd::lock_guard<std::mutex> lock_guard(dguard->mutex);\n\t\t\tauto dialog = dguard->dialog;\n\t\t\tif (dialog != nullptr) {\n\t\t\t\tauto evt = new wxCommandEvent(EVT_BONJOUR_COMPLETE, dialog->GetId());\n\t\t\t\twxQueueEvent(dialog, evt);\n\t\t\t}\n\t\t})\n\t\t.lookup()\n\t);\n\n\tbool res = ShowModal() == wxID_OK && list->GetFirstSelected() >= 0;\n\t{\n\t\t\/\/ Tell the background thread the dialog is going away...\n\t\tstd::lock_guard<std::mutex> lock_guard(dguard->mutex);\n\t\tdguard->dialog = nullptr;\n\t}\n\treturn res;\n}\n\nwxString BonjourDialog::get_selected() const\n{\n\tauto sel = list->GetFirstSelected();\n\treturn sel >= 0 ? list->GetItemText(sel) : wxString();\n}\n\n\n\/\/ Private\n\nvoid BonjourDialog::on_reply(BonjourReplyEvent &e)\n{\n\tif (replies->find(e.reply) != replies->end()) {\n\t\t\/\/ We already have this reply\n\t\treturn;\n\t}\n\n\t\/\/ Filter replies based on selected technology\n\tconst auto model = e.reply.txt_data.find(\"model\");\n\tconst bool sl1 = model != e.reply.txt_data.end() && model->second == \"SL1\";\n\tif (tech == ptFFF && sl1 || tech == ptSLA && !sl1) {\n\t\treturn;\n\t}\n\n\treplies->insert(std::move(e.reply));\n\n\tauto selected = get_selected();\n\n\twxWindowUpdateLocker freeze_guard(this);\n\t(void)freeze_guard;\n\n\tlist->DeleteAllItems();\n\n\t\/\/ The whole list is recreated so that we benefit from it already being sorted in the set.\n\t\/\/ (And also because wxListView's sorting API is bananas.)\n\tfor (const auto &reply : *replies) {\n\t\tauto item = list->InsertItem(0, reply.full_address);\n\t\tlist->SetItem(item, 1, reply.hostname);\n\t\tlist->SetItem(item, 2, reply.service_name);\n\n\t\tif (tech == ptFFF) {\n\t\t\tconst auto it = reply.txt_data.find(\"version\");\n\t\t\tif (it != reply.txt_data.end()) {\n\t\t\t\tlist->SetItem(item, 3, GUI::from_u8(it->second));\n\t\t\t}\n\t\t}\n\t}\n\n\tconst int em = GUI::wxGetApp().em_unit();\n\n\tfor (int i = 0; i < list->GetColumnCount(); i++) {\n\t\tlist->SetColumnWidth(i, wxLIST_AUTOSIZE);\n\t\tif (list->GetColumnWidth(i) < 10 * em) { list->SetColumnWidth(i, 10 * em); }\n\t}\n\n\tif (!selected.IsEmpty()) {\n\t\t\/\/ Attempt to preserve selection\n\t\tauto hit = list->FindItem(-1, selected);\n\t\tif (hit >= 0) { list->SetItemState(hit, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); }\n\t}\n}\n\nvoid BonjourDialog::on_timer(wxTimerEvent &)\n{\n\tconst auto search_str = _(L(\"Searching for devices\"));\n\n\tif (timer_state > 0) {\n\t\tconst std::string dots(timer_state, '.');\n\t\tlabel->SetLabel(wxString::Format(\"%s %s\", search_str, dots));\n\t\ttimer_state = (timer_state) % 3 + 1;\n\t} else {\n\t\tlabel->SetLabel(wxString::Format(\"%s: %s\", search_str, _(L(\"Finished\"))+\".\"));\n\t\ttimer->Stop();\n\t}\n}\n\n\n}\n<commit_msg>BonjourDialog: Fix dialog flags<commit_after>#include \"slic3r\/Utils\/Bonjour.hpp\" \/\/ On Windows, boost needs to be included before wxWidgets headers\n\n#include \"BonjourDialog.hpp\"\n\n#include <set>\n#include <mutex>\n\n#include <wx\/sizer.h>\n#include <wx\/button.h>\n#include <wx\/listctrl.h>\n#include <wx\/stattext.h>\n#include <wx\/timer.h>\n#include <wx\/wupdlock.h>\n\n#include \"slic3r\/GUI\/GUI.hpp\"\n#include \"slic3r\/GUI\/GUI_App.hpp\"\n#include \"slic3r\/GUI\/I18N.hpp\"\n#include \"slic3r\/Utils\/Bonjour.hpp\"\n\nnamespace Slic3r {\n\n\nclass BonjourReplyEvent : public wxEvent\n{\npublic:\n\tBonjourReply reply;\n\n\tBonjourReplyEvent(wxEventType eventType, int winid, BonjourReply &&reply) :\n\t\twxEvent(winid, eventType),\n\t\treply(std::move(reply))\n\t{}\n\n\tvirtual wxEvent *Clone() const\n\t{\n\t\treturn new BonjourReplyEvent(*this);\n\t}\n};\n\nwxDEFINE_EVENT(EVT_BONJOUR_REPLY, BonjourReplyEvent);\n\nwxDECLARE_EVENT(EVT_BONJOUR_COMPLETE, wxCommandEvent);\nwxDEFINE_EVENT(EVT_BONJOUR_COMPLETE, wxCommandEvent);\n\nclass ReplySet: public std::set<BonjourReply> {};\n\nstruct LifetimeGuard\n{\n\tstd::mutex mutex;\n\tBonjourDialog *dialog;\n\n\tLifetimeGuard(BonjourDialog *dialog) : dialog(dialog) {}\n};\n\nBonjourDialog::BonjourDialog(wxWindow *parent, Slic3r::PrinterTechnology tech)\n\t: wxDialog(parent, wxID_ANY, _(L(\"Network lookup\")), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER)\n\t, list(new wxListView(this, wxID_ANY))\n\t, replies(new ReplySet)\n\t, label(new wxStaticText(this, wxID_ANY, \"\"))\n\t, timer(new wxTimer())\n\t, timer_state(0)\n\t, tech(tech)\n{\n\tconst int em = GUI::wxGetApp().em_unit();\n\tlist->SetMinSize(wxSize(80 * em, 30 * em));\n\n\twxBoxSizer *vsizer = new wxBoxSizer(wxVERTICAL);\n\n\tvsizer->Add(label, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, em);\n\n\tlist->SetSingleStyle(wxLC_SINGLE_SEL);\n\tlist->SetSingleStyle(wxLC_SORT_DESCENDING);\n\tlist->AppendColumn(_(L(\"Address\")), wxLIST_FORMAT_LEFT, 5 * em);\n\tlist->AppendColumn(_(L(\"Hostname\")), wxLIST_FORMAT_LEFT, 10 * em);\n\tlist->AppendColumn(_(L(\"Service name\")), wxLIST_FORMAT_LEFT, 20 * em);\n\tif (tech == ptFFF) {\n\t\tlist->AppendColumn(_(L(\"OctoPrint version\")), wxLIST_FORMAT_LEFT, 5 * em);\n\t}\n\n\tvsizer->Add(list, 1, wxEXPAND | wxALL, em);\n\n\twxBoxSizer *button_sizer = new wxBoxSizer(wxHORIZONTAL);\n\tbutton_sizer->Add(new wxButton(this, wxID_OK, \"OK\"), 0, wxALL, em);\n\tbutton_sizer->Add(new wxButton(this, wxID_CANCEL, \"Cancel\"), 0, wxALL, em);\n\t\/\/ ^ Note: The Ok\/Cancel labels are translated by wxWidgets\n\n\tvsizer->Add(button_sizer, 0, wxALIGN_CENTER);\n\tSetSizerAndFit(vsizer);\n\n\tBind(EVT_BONJOUR_REPLY, &BonjourDialog::on_reply, this);\n\n\tBind(EVT_BONJOUR_COMPLETE, [this](wxCommandEvent &) {\n\t\tthis->timer_state = 0;\n\t});\n\n\tBind(wxEVT_TIMER, &BonjourDialog::on_timer, this);\n}\n\nBonjourDialog::~BonjourDialog()\n{\n\t\/\/ Needed bacuse of forward defs\n}\n\nbool BonjourDialog::show_and_lookup()\n{\n\tShow(); \/\/ Because we need GetId() to work before ShowModal()\n\n\ttimer->Stop();\n\ttimer->SetOwner(this);\n\ttimer_state = 1;\n\ttimer->Start(1000);\n\twxTimerEvent evt_dummy;\n\ton_timer(evt_dummy);\n\n\t\/\/ The background thread needs to queue messages for this dialog\n\t\/\/ and for that it needs a valid pointer to it (mandated by the wxWidgets API).\n\t\/\/ Here we put the pointer under a shared_ptr and protect it by a mutex,\n\t\/\/ so that both threads can access it safely.\n\tauto dguard = std::make_shared<LifetimeGuard>(this);\n\n\t\/\/ Note: More can be done here when we support discovery of hosts other than Octoprint and SL1\n\tBonjour::TxtKeys txt_keys { \"version\", \"model\" };\n\n\tbonjour = std::move(Bonjour(\"octoprint\")\n\t\t.set_txt_keys(std::move(txt_keys))\n\t\t.set_retries(3)\n\t\t.set_timeout(4)\n\t\t.on_reply([dguard](BonjourReply &&reply) {\n\t\t\tstd::lock_guard<std::mutex> lock_guard(dguard->mutex);\n\t\t\tauto dialog = dguard->dialog;\n\t\t\tif (dialog != nullptr) {\n\t\t\t\tauto evt = new BonjourReplyEvent(EVT_BONJOUR_REPLY, dialog->GetId(), std::move(reply));\n\t\t\t\twxQueueEvent(dialog, evt);\n\t\t\t}\n\t\t})\n\t\t.on_complete([dguard]() {\n\t\t\tstd::lock_guard<std::mutex> lock_guard(dguard->mutex);\n\t\t\tauto dialog = dguard->dialog;\n\t\t\tif (dialog != nullptr) {\n\t\t\t\tauto evt = new wxCommandEvent(EVT_BONJOUR_COMPLETE, dialog->GetId());\n\t\t\t\twxQueueEvent(dialog, evt);\n\t\t\t}\n\t\t})\n\t\t.lookup()\n\t);\n\n\tbool res = ShowModal() == wxID_OK && list->GetFirstSelected() >= 0;\n\t{\n\t\t\/\/ Tell the background thread the dialog is going away...\n\t\tstd::lock_guard<std::mutex> lock_guard(dguard->mutex);\n\t\tdguard->dialog = nullptr;\n\t}\n\treturn res;\n}\n\nwxString BonjourDialog::get_selected() const\n{\n\tauto sel = list->GetFirstSelected();\n\treturn sel >= 0 ? list->GetItemText(sel) : wxString();\n}\n\n\n\/\/ Private\n\nvoid BonjourDialog::on_reply(BonjourReplyEvent &e)\n{\n\tif (replies->find(e.reply) != replies->end()) {\n\t\t\/\/ We already have this reply\n\t\treturn;\n\t}\n\n\t\/\/ Filter replies based on selected technology\n\tconst auto model = e.reply.txt_data.find(\"model\");\n\tconst bool sl1 = model != e.reply.txt_data.end() && model->second == \"SL1\";\n\tif (tech == ptFFF && sl1 || tech == ptSLA && !sl1) {\n\t\treturn;\n\t}\n\n\treplies->insert(std::move(e.reply));\n\n\tauto selected = get_selected();\n\n\twxWindowUpdateLocker freeze_guard(this);\n\t(void)freeze_guard;\n\n\tlist->DeleteAllItems();\n\n\t\/\/ The whole list is recreated so that we benefit from it already being sorted in the set.\n\t\/\/ (And also because wxListView's sorting API is bananas.)\n\tfor (const auto &reply : *replies) {\n\t\tauto item = list->InsertItem(0, reply.full_address);\n\t\tlist->SetItem(item, 1, reply.hostname);\n\t\tlist->SetItem(item, 2, reply.service_name);\n\n\t\tif (tech == ptFFF) {\n\t\t\tconst auto it = reply.txt_data.find(\"version\");\n\t\t\tif (it != reply.txt_data.end()) {\n\t\t\t\tlist->SetItem(item, 3, GUI::from_u8(it->second));\n\t\t\t}\n\t\t}\n\t}\n\n\tconst int em = GUI::wxGetApp().em_unit();\n\n\tfor (int i = 0; i < list->GetColumnCount(); i++) {\n\t\tlist->SetColumnWidth(i, wxLIST_AUTOSIZE);\n\t\tif (list->GetColumnWidth(i) < 10 * em) { list->SetColumnWidth(i, 10 * em); }\n\t}\n\n\tif (!selected.IsEmpty()) {\n\t\t\/\/ Attempt to preserve selection\n\t\tauto hit = list->FindItem(-1, selected);\n\t\tif (hit >= 0) { list->SetItemState(hit, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); }\n\t}\n}\n\nvoid BonjourDialog::on_timer(wxTimerEvent &)\n{\n\tconst auto search_str = _(L(\"Searching for devices\"));\n\n\tif (timer_state > 0) {\n\t\tconst std::string dots(timer_state, '.');\n\t\tlabel->SetLabel(wxString::Format(\"%s %s\", search_str, dots));\n\t\ttimer_state = (timer_state) % 3 + 1;\n\t} else {\n\t\tlabel->SetLabel(wxString::Format(\"%s: %s\", search_str, _(L(\"Finished\"))+\".\"));\n\t\ttimer->Stop();\n\t}\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fhe\/FHEContext.h>\n#include <fhe\/FHE.h>\n#include <fhe\/NumbTh.h>\n#include <fhe\/EncryptedArray.h>\n#include <utils\/FileUtils.hpp>\n#include <utils\/timer.hpp>\n#include <algebra\/NDSS.h>\n#include <thread>\n#include <atomic>\n#include <vector>\n\n#ifdef FHE_THREADS\nlong WORKER_NR = 8;\n#else \/\/ ifdef FHE_THREADS\nlong WORKER_NR = 1;\n#endif \/\/ ifdef FHE_THREAD\n\nstd::vector<MDL::EncVector>encrypt(const MDL::Matrix<long>& data,\n const FHEPubKey & pk,\n const EncryptedArray & ea,\n long rows_to_proces = 0)\n{\n MDL::Timer timer;\n std::vector<MDL::EncVector> ctxts(data.rows(), pk);\n std::vector<std::thread> workers;\n std::atomic<size_t> counter(0);\n\n rows_to_proces = rows_to_proces == 0 ? data.rows() : rows_to_proces;\n timer.start();\n\n for (long wr = 0; wr < WORKER_NR; wr++) {\n workers.push_back(std::move(std::thread([&data, &ea, &rows_to_proces,\n &counter, &ctxts]() {\n size_t next;\n\n while ((next = counter.fetch_add(1)) < rows_to_proces) {\n ctxts[next].pack(data[next], ea);\n }\n })));\n }\n\n for (auto && wr : workers) wr.join();\n timer.end();\n printf(\"Encrypt %ld data with %ld workers costed %f sec\\n\", rows_to_proces,\n WORKER_NR, timer.second());\n return ctxts;\n}\n\nMDL::EncVector mean(const std::vector<MDL::EncVector>& ctxts)\n{\n std::vector<std::thread> workers;\n std::vector<MDL::EncVector> partials(WORKER_NR, ctxts[0].getPubKey());\n std::atomic<size_t> counter(WORKER_NR);\n MDL::Timer timer;\n\n timer.start();\n\n for (long i = 0; i < WORKER_NR; i++) {\n partials[i] = ctxts[i];\n workers.push_back(std::move(std::thread([&counter, &ctxts]\n (MDL::EncVector& ct) {\n size_t next;\n\n while ((next = counter.fetch_add(1)) < ctxts.size()) {\n ct += ctxts[next];\n }\n }, std::ref(partials[i]))));\n }\n\n for (auto && wr : workers) {\n wr.join();\n }\n\n for (long i = 1; i < WORKER_NR; i++) {\n partials[0] += partials[i];\n }\n timer.end();\n printf(\"Mean %zd data with %ld workers costed %f sec\\n\", ctxts.size(),\n WORKER_NR, timer.second());\n return partials[0];\n}\n\nMDL::EncVector variance(std::vector<MDL::EncVector>& ctxts)\n{\n MDL::Timer timer;\n NTL::ZZX N(ctxts.size());\n std::atomic<size_t> counter(0);\n std::vector<std::thread> workers;\n\n timer.start();\n WORKER_NR = 1;\n auto sum_sq = mean(ctxts);\n sum_sq.square();\n MDL::Timer mult_timer;\n mult_timer.start();\n WORKER_NR = 8;\n\n for (long wr = 0; wr < WORKER_NR; wr++) {\n workers.push_back(std::move(std::thread([&ctxts, &counter]() {\n size_t next;\n\n while ((next = counter.fetch_add(1)) < ctxts.size()) {\n ctxts[next].square();\n }\n })));\n }\n\n for (auto && wr : workers) wr.join();\n mult_timer.end();\n printf(\"Square costed %f sec\\n\", mult_timer.second());\n WORKER_NR = 1;\n auto sq_sum = mean(ctxts);\n WORKER_NR = 8;\n sq_sum.multByConstant(N);\n sq_sum.addCtxt(sum_sq, true);\n timer.end();\n printf(\"Variance %zd data with %ld workers costed %f sec\\n\", ctxts.size(),\n WORKER_NR, timer.second());\n return sq_sum;\n}\n\nint main(int argc, char *argv[]) {\n long m, p, r, L;\n ArgMapping argmap;\n\n argmap.arg(\"m\", m, \"m\");\n argmap.arg(\"L\", L, \"L\");\n argmap.arg(\"p\", p, \"p\");\n argmap.arg(\"r\", r, \"r\");\n argmap.parse(argc, argv);\n\n FHEcontext context(m, p, r);\n buildModChain(context, L);\n FHESecKey sk(context);\n sk.GenSecKey(64);\n addSome1DMatrices(sk);\n FHEPubKey pk = sk;\n\n auto G = context.alMod.getFactorsOverZZ()[0];\n EncryptedArray ea(context, G);\n\n auto data = load_csv(\"adult.data\", 100);\n auto result = load_csv(\"adult_result\");\n auto ctxts = encrypt(data, pk, ea);\n\n \/\/ {\n \/\/ MDL::Vector<long> ret;\n \/\/ auto summaiton = mean(ctxts);\n \/\/ summaiton.unpack(ret, sk, ea);\n \/\/ std::cout << ret << std::endl;\n \/\/ std::cout << result[0] << std::endl;\n \/\/ }\n\n {\n MDL::Vector<long> ret;\n\n auto var = variance(ctxts);\n var.unpack(ret, sk, ea);\n std::cout << ret << std::endl;\n std::cout << result[1] << std::endl;\n }\n return 0;\n}\n<commit_msg>One core version variance<commit_after>#include <fhe\/FHEContext.h>\n#include <fhe\/FHE.h>\n#include <fhe\/NumbTh.h>\n#include <fhe\/EncryptedArray.h>\n#include <utils\/FileUtils.hpp>\n#include <utils\/timer.hpp>\n#include <algebra\/NDSS.h>\n#include <thread>\n#include <atomic>\n#include <vector>\n\n#ifdef FHE_THREADS\nlong WORKER_NR = 8;\n#else \/\/ ifdef FHE_THREADS\nlong WORKER_NR = 1;\n#endif \/\/ ifdef FHE_THREAD\n\nMDL::EncVector encrypt_variance(const MDL::Matrix<long>& data,\n const FHEPubKey & pk,\n const EncryptedArray & ea)\n{\n MDL::EncVector sq_sum(pk), sum_sq(pk);\n MDL::EncVector encRow(pk);\n NTL::ZZX N(data.rows());\n MDL::Timer timer;\n\n timer.start();\n\n for (size_t row = 0; row < data.rows(); row++) {\n encRow.pack(data[row], ea);\n\n if (row == 0) {\n sum_sq = encRow;\n encRow.square();\n sq_sum = encRow;\n } else {\n sum_sq += encRow;\n encRow.square();\n sq_sum += encRow;\n }\n }\n sq_sum.multByConstant(N);\n sq_sum -= sum_sq;\n timer.end();\n printf(\"Encrypt & Variance of %ld records costed %fs\\n\", data.rows(),\n timer.second());\n return sq_sum;\n}\n\nstd::vector<MDL::EncVector>encrypt(const MDL::Matrix<long>& data,\n const FHEPubKey & pk,\n const EncryptedArray & ea,\n long rows_to_proces = 0)\n{\n MDL::Timer timer;\n std::vector<MDL::EncVector> ctxts(data.rows(), pk);\n std::vector<std::thread> workers;\n std::atomic<size_t> counter(0);\n\n rows_to_proces = rows_to_proces == 0 ? data.rows() : rows_to_proces;\n timer.start();\n\n for (long wr = 0; wr < WORKER_NR; wr++) {\n workers.push_back(std::move(std::thread([&data, &ea, &rows_to_proces,\n &counter, &ctxts]() {\n size_t next;\n\n while ((next = counter.fetch_add(1)) < rows_to_proces) {\n ctxts[next].pack(data[next], ea);\n }\n })));\n }\n\n for (auto && wr : workers) wr.join();\n timer.end();\n printf(\"Encrypt %ld data with %ld workers costed %f sec\\n\", rows_to_proces,\n WORKER_NR, timer.second());\n return ctxts;\n}\n\nMDL::EncVector mean(const std::vector<MDL::EncVector>& ctxts)\n{\n std::vector<std::thread> workers;\n std::vector<MDL::EncVector> partials(WORKER_NR, ctxts[0].getPubKey());\n std::atomic<size_t> counter(WORKER_NR);\n MDL::Timer timer;\n\n timer.start();\n\n for (long i = 0; i < WORKER_NR; i++) {\n partials[i] = ctxts[i];\n workers.push_back(std::move(std::thread([&counter, &ctxts]\n (MDL::EncVector& ct) {\n size_t next;\n\n while ((next = counter.fetch_add(1)) < ctxts.size()) {\n ct += ctxts[next];\n }\n }, std::ref(partials[i]))));\n }\n\n for (auto && wr : workers) {\n wr.join();\n }\n\n for (long i = 1; i < WORKER_NR; i++) {\n partials[0] += partials[i];\n }\n timer.end();\n printf(\"Mean %zd data with %ld workers costed %f sec\\n\", ctxts.size(),\n WORKER_NR, timer.second());\n return partials[0];\n}\n\nMDL::EncVector variance(std::vector<MDL::EncVector>& ctxts)\n{\n MDL::Timer timer;\n NTL::ZZX N(ctxts.size());\n std::atomic<size_t> counter(0);\n std::vector<std::thread> workers;\n\n timer.start();\n WORKER_NR = 1;\n auto sum_sq = mean(ctxts);\n sum_sq.square();\n MDL::Timer mult_timer;\n mult_timer.start();\n WORKER_NR = 8;\n\n for (long wr = 0; wr < WORKER_NR; wr++) {\n workers.push_back(std::move(std::thread([&ctxts, &counter]() {\n size_t next;\n\n while ((next = counter.fetch_add(1)) < ctxts.size()) {\n ctxts[next].square();\n }\n })));\n }\n\n for (auto && wr : workers) wr.join();\n mult_timer.end();\n printf(\"Square costed %f sec\\n\", mult_timer.second());\n WORKER_NR = 1;\n auto sq_sum = mean(ctxts);\n WORKER_NR = 8;\n sq_sum.multByConstant(N);\n sq_sum.addCtxt(sum_sq, true);\n timer.end();\n printf(\"Variance %zd data with %ld workers costed %f sec\\n\", ctxts.size(),\n WORKER_NR, timer.second());\n return sq_sum;\n}\n\nint main(int argc, char *argv[]) {\n long m, p, r, L;\n ArgMapping argmap;\n\n argmap.arg(\"m\", m, \"m\");\n argmap.arg(\"L\", L, \"L\");\n argmap.arg(\"p\", p, \"p\");\n argmap.arg(\"r\", r, \"r\");\n argmap.parse(argc, argv);\n\n FHEcontext context(m, p, r);\n buildModChain(context, L);\n FHESecKey sk(context);\n sk.GenSecKey(64);\n addSome1DMatrices(sk);\n FHEPubKey pk = sk;\n\n auto G = context.alMod.getFactorsOverZZ()[0];\n EncryptedArray ea(context, G);\n\n auto data = load_csv(\"adult.data\", 100);\n auto result = load_csv(\"adult_result\");\n\n \/\/ auto ctxts = encrypt(data, pk, ea);\n\n \/\/ {\n \/\/ MDL::Vector<long> ret;\n \/\/ auto summaiton = mean(ctxts);\n \/\/ summaiton.unpack(ret, sk, ea);\n \/\/ std::cout << ret << std::endl;\n \/\/ std::cout << result[0] << std::endl;\n \/\/ }\n\n {\n MDL::Vector<long> ret;\n\n auto var = encrypt_variance(data, pk, ea);\n var.unpack(ret, sk, ea);\n std::cout << ret << std::endl;\n std::cout << result[1] << std::endl;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\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#include <string>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <nlohmann\/json.hpp>\n\n#include \"component_event.hpp\"\n#include \"data_item.hpp\"\n#include \"device.hpp\"\n#include \"json_printer.hpp\"\n#include \"globals.hpp\"\n#include \"checkpoint.hpp\"\n#include \"xml_parser.hpp\"\n#include \"xml_printer.hpp\"\n#include \"test_globals.hpp\"\n\nusing json = nlohmann::json;\nusing namespace std;\n\nnamespace mtconnect {\n namespace test {\n class JsonPrinterProbeTest : public CppUnit::TestFixture\n {\n CPPUNIT_TEST_SUITE(JsonPrinterProbeTest);\n CPPUNIT_TEST(testDeviceRootAndDescription);\n CPPUNIT_TEST(testTopLevelDataItems);\n CPPUNIT_TEST(testSubComponents);\n CPPUNIT_TEST_SUITE_END();\n \n public:\n void testDeviceRootAndDescription();\n void testTopLevelDataItems();\n void testSubComponents();\n\n void setUp();\n void tearDown();\n\n protected:\n std::unique_ptr<JsonPrinter> m_printer;\n std::vector<Device *> m_devices;\n \n std::unique_ptr<XmlParser> m_config;\n std::unique_ptr<XmlPrinter> m_xmlPrinter;\n };\n\n CPPUNIT_TEST_SUITE_REGISTRATION(JsonPrinterProbeTest);\n\n void JsonPrinterProbeTest::setUp()\n {\n m_xmlPrinter.reset(new XmlPrinter(\"1.5\"));\n m_printer.reset(new JsonPrinter(\"1.5\", true));\n \n m_config.reset(new XmlParser());\n m_devices = m_config->parseFile(\"..\/samples\/test_config.xml\", m_xmlPrinter.get());\n }\n\n void JsonPrinterProbeTest::tearDown()\n {\n m_config.reset();\n m_xmlPrinter.reset();\n m_printer.reset();\n m_devices.clear();\n }\n \n void JsonPrinterProbeTest::testDeviceRootAndDescription()\n {\n auto doc = m_printer->printProbe(123, 9999, 1, 1024, 10, m_devices);\n auto jdoc = json::parse(doc);\n auto it = jdoc.begin();\n CPPUNIT_ASSERT_EQUAL(string(\"MTConnectDevices\"), it.key());\n CPPUNIT_ASSERT_EQUAL(123, jdoc.at(\"\/MTConnectDevices\/Header\/@instanceId\"_json_pointer).get<int32_t>());\n CPPUNIT_ASSERT_EQUAL(9999, jdoc.at(\"\/MTConnectDevices\/Header\/@bufferSize\"_json_pointer).get<int32_t>());\n CPPUNIT_ASSERT_EQUAL(1024, jdoc.at(\"\/MTConnectDevices\/Header\/@assetBufferSize\"_json_pointer).get<int32_t>());\n CPPUNIT_ASSERT_EQUAL(10, jdoc.at(\"\/MTConnectDevices\/Header\/@assetCount\"_json_pointer).get<int32_t>());\n\n auto devices = jdoc.at(\"\/MTConnectDevices\/Devices\"_json_pointer);\n auto device = devices.at(0).at(\"\/Device\"_json_pointer);\n\n CPPUNIT_ASSERT_EQUAL(string(\"d\"), device.at(\"\/@id\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"LinuxCNC\"), device.at(\"\/@name\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"000\"), device.at(\"\/@uuid\"_json_pointer).get<string>());\n \n CPPUNIT_ASSERT_EQUAL(string(\"Linux CNC Device\"), device.at(\"\/Description\/#text\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"NIST\"), device.at(\"\/Description\/@manufacturer\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"1122\"), device.at(\"\/Description\/@serialNumber\"_json_pointer).get<string>());\n }\n \n void JsonPrinterProbeTest::testTopLevelDataItems()\n {\n auto doc = m_printer->printProbe(123, 9999, 1, 1024, 10, m_devices);\n \/\/cout << \"\\n\" << doc << endl;\n auto jdoc = json::parse(doc);\n auto devices = jdoc.at(\"\/MTConnectDevices\/Devices\"_json_pointer);\n auto device = devices.at(0).at(\"\/Device\"_json_pointer);\n \n auto dataItems = device.at(\"\/DataItems\"_json_pointer);\n CPPUNIT_ASSERT(dataItems.is_array());\n CPPUNIT_ASSERT_EQUAL(2ul, static_cast<unsigned long>(dataItems.size()));\n \n \/\/ Alarm event\n auto alarm = dataItems.at(0);\n CPPUNIT_ASSERT_EQUAL(string(\"ALARM\"), alarm.at(\"\/DataItem\/@type\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"EVENT\"), alarm.at(\"\/DataItem\/@category\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"a\"), alarm.at(\"\/DataItem\/@id\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"alarm\"), alarm.at(\"\/DataItem\/@name\"_json_pointer).get<string>());\n \n \/\/ Availability event\n auto avail = dataItems.at(1);\n CPPUNIT_ASSERT_EQUAL(string(\"AVAILABILITY\"), avail.at(\"\/DataItem\/@type\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"EVENT\"), avail.at(\"\/DataItem\/@category\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"avail\"), avail.at(\"\/DataItem\/@id\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"avail\"), avail.at(\"\/DataItem\/@name\"_json_pointer).get<string>());\n\n }\n \n void JsonPrinterProbeTest::testSubComponents()\n {\n auto doc = m_printer->printProbe(123, 9999, 1, 1024, 10, m_devices);\n cout << \"\\n\" << doc << endl;\n auto jdoc = json::parse(doc);\n auto devices = jdoc.at(\"\/MTConnectDevices\/Devices\"_json_pointer);\n auto device = devices.at(0).at(\"\/Device\"_json_pointer);\n\n auto components = device.at(\"\/Components\"_json_pointer);\n CPPUNIT_ASSERT(components.is_array());\n CPPUNIT_ASSERT_EQUAL(3ul, static_cast<unsigned long>(components.size()));\n\n auto axes = components.at(0);\n CPPUNIT_ASSERT(axes.is_object());\n CPPUNIT_ASSERT_EQUAL(string(\"Axes\"), axes.begin().key());\n CPPUNIT_ASSERT_EQUAL(string(\"axes\"), axes.at(\"\/Axes\/@id\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"Axes\"), axes.at(\"\/Axes\/@name\"_json_pointer).get<string>());\n\n auto subAxes = axes.at(\"\/Axes\/Components\"_json_pointer);\n CPPUNIT_ASSERT(subAxes.is_array());\n CPPUNIT_ASSERT_EQUAL(4ul, static_cast<unsigned long>(subAxes.size()));\n \n auto rotary = subAxes.at(0);\n CPPUNIT_ASSERT(rotary.is_object());\n auto rc = rotary.at(\"\/Rotary\"_json_pointer);\n CPPUNIT_ASSERT(rc.is_object());\n CPPUNIT_ASSERT_EQUAL(string(\"C\"), rc.at(\"\/@name\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"c\"), rc.at(\"\/@id\"_json_pointer).get<string>());\n \n auto dataItems = rc.at(\"\/DataItems\"_json_pointer);\n CPPUNIT_ASSERT(dataItems.is_array());\n \n auto ss = dataItems.at(0).at(\"\/DataItem\"_json_pointer);\n CPPUNIT_ASSERT(ss.is_object());\n CPPUNIT_ASSERT_EQUAL(string(\"SPINDLE_SPEED\"), ss.at(\"\/@type\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"REVOLUTION\/MINUTE\"), ss.at(\"\/@units\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"REVOLUTION\/MINUTE\"), ss.at(\"\/@nativeUnits\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"ACTUAL\"), ss.at(\"\/@subType\"_json_pointer).get<string>());\n \n auto source = ss.at(\"\/Source\"_json_pointer);\n CPPUNIT_ASSERT(source.is_object());\n \n CPPUNIT_ASSERT_EQUAL(string(\"spindle_speed\"), ss.at(\"\/Source\/#text\"_json_pointer).get<string>());\n\n }\n\n }\n}\n\n \n<commit_msg>Cleaned up size literal casting. Use constexpr to do conversion and _S for size_type cast.<commit_after>\/\/\n\/\/ Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\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#include <string>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <nlohmann\/json.hpp>\n\n#include \"component_event.hpp\"\n#include \"data_item.hpp\"\n#include \"device.hpp\"\n#include \"json_printer.hpp\"\n#include \"globals.hpp\"\n#include \"checkpoint.hpp\"\n#include \"xml_parser.hpp\"\n#include \"xml_printer.hpp\"\n#include \"test_globals.hpp\"\n\nusing json = nlohmann::json;\nusing namespace std;\n\nnamespace mtconnect {\n namespace test {\n constexpr nlohmann::json::size_type operator \"\" _S(unsigned long long v)\n { \n return static_cast<nlohmann::json::size_type>(v);\n }\n\n class JsonPrinterProbeTest : public CppUnit::TestFixture\n {\n CPPUNIT_TEST_SUITE(JsonPrinterProbeTest);\n CPPUNIT_TEST(testDeviceRootAndDescription);\n CPPUNIT_TEST(testTopLevelDataItems);\n CPPUNIT_TEST(testSubComponents);\n CPPUNIT_TEST_SUITE_END();\n \n public:\n void testDeviceRootAndDescription();\n void testTopLevelDataItems();\n void testSubComponents();\n\n void setUp();\n void tearDown();\n\n protected:\n std::unique_ptr<JsonPrinter> m_printer;\n std::vector<Device *> m_devices;\n \n std::unique_ptr<XmlParser> m_config;\n std::unique_ptr<XmlPrinter> m_xmlPrinter;\n };\n\n CPPUNIT_TEST_SUITE_REGISTRATION(JsonPrinterProbeTest);\n\n void JsonPrinterProbeTest::setUp()\n {\n m_xmlPrinter.reset(new XmlPrinter(\"1.5\"));\n m_printer.reset(new JsonPrinter(\"1.5\", true));\n \n m_config.reset(new XmlParser());\n m_devices = m_config->parseFile(\"..\/samples\/test_config.xml\", m_xmlPrinter.get());\n }\n\n void JsonPrinterProbeTest::tearDown()\n {\n m_config.reset();\n m_xmlPrinter.reset();\n m_printer.reset();\n m_devices.clear();\n }\n \n void JsonPrinterProbeTest::testDeviceRootAndDescription()\n {\n auto doc = m_printer->printProbe(123, 9999, 1, 1024, 10, m_devices);\n auto jdoc = json::parse(doc);\n auto it = jdoc.begin();\n CPPUNIT_ASSERT_EQUAL(string(\"MTConnectDevices\"), it.key());\n CPPUNIT_ASSERT_EQUAL(123, jdoc.at(\"\/MTConnectDevices\/Header\/@instanceId\"_json_pointer).get<int32_t>());\n CPPUNIT_ASSERT_EQUAL(9999, jdoc.at(\"\/MTConnectDevices\/Header\/@bufferSize\"_json_pointer).get<int32_t>());\n CPPUNIT_ASSERT_EQUAL(1024, jdoc.at(\"\/MTConnectDevices\/Header\/@assetBufferSize\"_json_pointer).get<int32_t>());\n CPPUNIT_ASSERT_EQUAL(10, jdoc.at(\"\/MTConnectDevices\/Header\/@assetCount\"_json_pointer).get<int32_t>());\n\n auto devices = jdoc.at(\"\/MTConnectDevices\/Devices\"_json_pointer);\n auto device = devices.at(0).at(\"\/Device\"_json_pointer);\n\n CPPUNIT_ASSERT_EQUAL(string(\"d\"), device.at(\"\/@id\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"LinuxCNC\"), device.at(\"\/@name\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"000\"), device.at(\"\/@uuid\"_json_pointer).get<string>());\n \n CPPUNIT_ASSERT_EQUAL(string(\"Linux CNC Device\"), device.at(\"\/Description\/#text\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"NIST\"), device.at(\"\/Description\/@manufacturer\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"1122\"), device.at(\"\/Description\/@serialNumber\"_json_pointer).get<string>());\n }\n \n void JsonPrinterProbeTest::testTopLevelDataItems()\n {\n auto doc = m_printer->printProbe(123, 9999, 1, 1024, 10, m_devices);\n \/\/cout << \"\\n\" << doc << endl;\n auto jdoc = json::parse(doc);\n auto devices = jdoc.at(\"\/MTConnectDevices\/Devices\"_json_pointer);\n auto device = devices.at(0).at(\"\/Device\"_json_pointer);\n \n auto dataItems = device.at(\"\/DataItems\"_json_pointer);\n CPPUNIT_ASSERT(dataItems.is_array());\n CPPUNIT_ASSERT_EQUAL(2_S, dataItems.size());\n \n \/\/ Alarm event\n auto alarm = dataItems.at(0);\n CPPUNIT_ASSERT_EQUAL(string(\"ALARM\"), alarm.at(\"\/DataItem\/@type\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"EVENT\"), alarm.at(\"\/DataItem\/@category\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"a\"), alarm.at(\"\/DataItem\/@id\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"alarm\"), alarm.at(\"\/DataItem\/@name\"_json_pointer).get<string>());\n \n \/\/ Availability event\n auto avail = dataItems.at(1);\n CPPUNIT_ASSERT_EQUAL(string(\"AVAILABILITY\"), avail.at(\"\/DataItem\/@type\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"EVENT\"), avail.at(\"\/DataItem\/@category\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"avail\"), avail.at(\"\/DataItem\/@id\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"avail\"), avail.at(\"\/DataItem\/@name\"_json_pointer).get<string>());\n\n }\n \n void JsonPrinterProbeTest::testSubComponents()\n {\n auto doc = m_printer->printProbe(123, 9999, 1, 1024, 10, m_devices);\n cout << \"\\n\" << doc << endl;\n auto jdoc = json::parse(doc);\n auto devices = jdoc.at(\"\/MTConnectDevices\/Devices\"_json_pointer);\n auto device = devices.at(0).at(\"\/Device\"_json_pointer);\n\n auto components = device.at(\"\/Components\"_json_pointer);\n CPPUNIT_ASSERT(components.is_array());\n CPPUNIT_ASSERT_EQUAL(3_S, components.size());\n\n auto axes = components.at(0);\n CPPUNIT_ASSERT(axes.is_object());\n CPPUNIT_ASSERT_EQUAL(string(\"Axes\"), axes.begin().key());\n CPPUNIT_ASSERT_EQUAL(string(\"axes\"), axes.at(\"\/Axes\/@id\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"Axes\"), axes.at(\"\/Axes\/@name\"_json_pointer).get<string>());\n\n auto subAxes = axes.at(\"\/Axes\/Components\"_json_pointer);\n CPPUNIT_ASSERT(subAxes.is_array());\n CPPUNIT_ASSERT_EQUAL(4_S, subAxes.size());\n \n auto rotary = subAxes.at(0);\n CPPUNIT_ASSERT(rotary.is_object());\n auto rc = rotary.at(\"\/Rotary\"_json_pointer);\n CPPUNIT_ASSERT(rc.is_object());\n CPPUNIT_ASSERT_EQUAL(string(\"C\"), rc.at(\"\/@name\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"c\"), rc.at(\"\/@id\"_json_pointer).get<string>());\n \n auto dataItems = rc.at(\"\/DataItems\"_json_pointer);\n CPPUNIT_ASSERT(dataItems.is_array());\n \n auto ss = dataItems.at(0).at(\"\/DataItem\"_json_pointer);\n CPPUNIT_ASSERT(ss.is_object());\n CPPUNIT_ASSERT_EQUAL(string(\"SPINDLE_SPEED\"), ss.at(\"\/@type\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"REVOLUTION\/MINUTE\"), ss.at(\"\/@units\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"REVOLUTION\/MINUTE\"), ss.at(\"\/@nativeUnits\"_json_pointer).get<string>());\n CPPUNIT_ASSERT_EQUAL(string(\"ACTUAL\"), ss.at(\"\/@subType\"_json_pointer).get<string>());\n \n auto source = ss.at(\"\/Source\"_json_pointer);\n CPPUNIT_ASSERT(source.is_object());\n \n CPPUNIT_ASSERT_EQUAL(string(\"spindle_speed\"), ss.at(\"\/Source\/#text\"_json_pointer).get<string>());\n\n }\n\n }\n}\n\n \n<|endoftext|>"} {"text":"<commit_before>#include \"CppUnitTest.h\"\n#include <algorithm>\n#include <sstream>\n#include <cctype>\n#include <string>\n#include <vector>\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\n\nnamespace algo\n{\n struct token\n {\n enum toktype { root_node, named_node, edge_name, horizontal_edge, ascending_edge_part, descending_edge_part, vertical_edge_part };\n toktype type;\n string name;\n };\n\n bool operator==(const token& lhs, const token& rhs)\n {\n return lhs.type == rhs.type\n && lhs.name == rhs.name;\n }\n\n struct ascii_tree\n {\n static vector<token> tokenize(const string& s)\n {\n vector<token> tokens;\n enum { none, open_square_brace, close_square_brace, asterisk, dash, name_char } prev = none;\n size_t marker = 0, marked_length = 0;\n\n for (size_t i = 0; i < s.size(); ++i)\n {\n auto ch = s[i];\n\n if (ch == '[')\n {\n prev = open_square_brace;\n }\n else if (ch == ']')\n {\n if (prev == asterisk)\n {\n tokens.emplace_back(token { token::root_node, \"\" });\n }\n else\n {\n tokens.emplace_back(token { token::named_node, s.substr(marker, marked_length) });\n }\n\n prev = close_square_brace;\n }\n else if (ch == '*')\n {\n prev = asterisk;\n }\n else if (ch == '-')\n {\n if (prev == name_char)\n {\n tokens.emplace_back(token { token::horizontal_edge, s.substr(marker, marked_length) });\n }\n\n prev = dash;\n }\n else if (ch == '\/')\n {\n tokens.emplace_back(token { token::ascending_edge_part, \"\" });\n }\n else if (ch == '\\\\')\n {\n tokens.emplace_back(token { token::descending_edge_part, \"\" });\n }\n else if (ch == '|')\n {\n tokens.emplace_back(token { token::vertical_edge_part, \"\" });\n }\n else if (isalnum(ch) || ch == '_')\n {\n if (prev != name_char)\n {\n marker = i;\n marked_length = 0;\n }\n\n prev = name_char;\n ++marked_length;\n }\n }\n\n if (prev == name_char)\n {\n tokens.emplace_back(token { token::edge_name, s.substr(marker, marked_length) });\n }\n\n return tokens;\n }\n };\n}\n\nnamespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework\n{\n template<>\n wstring ToString<algo::token::toktype>(const algo::token::toktype& type)\n {\n switch (type)\n {\n case algo::token::root_node:\n return L\"root_node\";\n case algo::token::named_node:\n return L\"named_node\";\n case algo::token::edge_name:\n return L\"edge_name\";\n case algo::token::horizontal_edge:\n return L\"horizontal_edge\";\n case algo::token::ascending_edge_part:\n return L\"ascending_edge_part\";\n case algo::token::descending_edge_part:\n return L\"descending_edge_part\";\n case algo::token::vertical_edge_part:\n return L\"vertical_edge_part\";\n default:\n return L\"unknown token\";\n }\n }\n}}}\n\nnamespace algo { namespace spec\n{\n\tTEST_CLASS(can_recognize_ascii_tree_tokens)\n\t{\n void tokens_should_match_(std::initializer_list<token> expected, vector<token>& actual)\n {\n auto mismatch_pair = std::mismatch(expected.begin(), expected.end(), actual.begin());\n\n if (mismatch_pair.first != expected.end() || mismatch_pair.second != actual.end())\n {\n wstring expectedName(mismatch_pair.first->name.begin(), mismatch_pair.first->name.end());\n wstring actualName(mismatch_pair.second->name.begin(), mismatch_pair.second->name.end());\n\n wstring message = L\"Expected: \" + ToString(mismatch_pair.first->type) + L\" \\\"\" + expectedName + L\"\\\" \"\n + L\"Actual: \" + ToString(mismatch_pair.second->type) + L\" \\\"\" + actualName + L\"\\\"\";\n\n Assert::Fail(message.c_str());\n }\n }\n\n public:\n\t\t\n TEST_METHOD(should_not_recognize_any_tokens_in_an_empty_string)\n {\n auto tokens = ascii_tree::tokenize(\"\");\n Assert::IsTrue(tokens.empty());\n }\n\n\t\tTEST_METHOD(should_recognize_a_root_node)\n\t\t{\n auto tokens = ascii_tree::tokenize(\"[*]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_root_node_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" [ * ]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_named_node)\n {\n const string all_chars = \"_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n auto tokens = ascii_tree::tokenize(\"[\" + all_chars + \"]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(all_chars.c_str(), tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_named_node_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" [ a ]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"a\");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" a \");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"\/\");\n Assert::AreEqual(token::ascending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_an_ascending_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" \/ \");\n Assert::AreEqual(token::ascending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"\\\\\");\n Assert::AreEqual(token::descending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_descending_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" \\\\ \");\n Assert::AreEqual(token::descending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"|\");\n Assert::AreEqual(token::vertical_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_vertical_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" | \");\n Assert::AreEqual(token::vertical_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"-a-\");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" - a - \");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[*][a]\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::named_node, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"[*]-a-\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::horizontal_edge, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"-a-[b]\");\n tokens_should_match_({ { token::horizontal_edge, \"a\" }, { token::named_node, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\\\\\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::descending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\/\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::ascending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]|\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::vertical_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"[*]a\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::edge_name, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_root_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a][*]\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::root_node, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a][b]\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::named_node, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"[a]-b-\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::horizontal_edge, \"b\" } }, tokens);\n }\n\n };\n}}\n<commit_msg>untabify<commit_after>#include \"CppUnitTest.h\"\n#include <algorithm>\n#include <sstream>\n#include <cctype>\n#include <string>\n#include <vector>\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\n\nnamespace algo\n{\n struct token\n {\n enum toktype { root_node, named_node, edge_name, horizontal_edge, ascending_edge_part, descending_edge_part, vertical_edge_part };\n toktype type;\n string name;\n };\n\n bool operator==(const token& lhs, const token& rhs)\n {\n return lhs.type == rhs.type\n && lhs.name == rhs.name;\n }\n\n struct ascii_tree\n {\n static vector<token> tokenize(const string& s)\n {\n vector<token> tokens;\n enum { none, open_square_brace, close_square_brace, asterisk, dash, name_char } prev = none;\n size_t marker = 0, marked_length = 0;\n\n for (size_t i = 0; i < s.size(); ++i)\n {\n auto ch = s[i];\n\n if (ch == '[')\n {\n prev = open_square_brace;\n }\n else if (ch == ']')\n {\n if (prev == asterisk)\n {\n tokens.emplace_back(token { token::root_node, \"\" });\n }\n else\n {\n tokens.emplace_back(token { token::named_node, s.substr(marker, marked_length) });\n }\n\n prev = close_square_brace;\n }\n else if (ch == '*')\n {\n prev = asterisk;\n }\n else if (ch == '-')\n {\n if (prev == name_char)\n {\n tokens.emplace_back(token { token::horizontal_edge, s.substr(marker, marked_length) });\n }\n\n prev = dash;\n }\n else if (ch == '\/')\n {\n tokens.emplace_back(token { token::ascending_edge_part, \"\" });\n }\n else if (ch == '\\\\')\n {\n tokens.emplace_back(token { token::descending_edge_part, \"\" });\n }\n else if (ch == '|')\n {\n tokens.emplace_back(token { token::vertical_edge_part, \"\" });\n }\n else if (isalnum(ch) || ch == '_')\n {\n if (prev != name_char)\n {\n marker = i;\n marked_length = 0;\n }\n\n prev = name_char;\n ++marked_length;\n }\n }\n\n if (prev == name_char)\n {\n tokens.emplace_back(token { token::edge_name, s.substr(marker, marked_length) });\n }\n\n return tokens;\n }\n };\n}\n\nnamespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework\n{\n template<>\n wstring ToString<algo::token::toktype>(const algo::token::toktype& type)\n {\n switch (type)\n {\n case algo::token::root_node:\n return L\"root_node\";\n case algo::token::named_node:\n return L\"named_node\";\n case algo::token::edge_name:\n return L\"edge_name\";\n case algo::token::horizontal_edge:\n return L\"horizontal_edge\";\n case algo::token::ascending_edge_part:\n return L\"ascending_edge_part\";\n case algo::token::descending_edge_part:\n return L\"descending_edge_part\";\n case algo::token::vertical_edge_part:\n return L\"vertical_edge_part\";\n default:\n return L\"unknown token\";\n }\n }\n}}}\n\nnamespace algo { namespace spec\n{\n TEST_CLASS(can_recognize_ascii_tree_tokens)\n {\n void tokens_should_match_(std::initializer_list<token> expected, vector<token>& actual)\n {\n auto mismatch_pair = std::mismatch(expected.begin(), expected.end(), actual.begin());\n\n if (mismatch_pair.first != expected.end() || mismatch_pair.second != actual.end())\n {\n wstring expectedName(mismatch_pair.first->name.begin(), mismatch_pair.first->name.end());\n wstring actualName(mismatch_pair.second->name.begin(), mismatch_pair.second->name.end());\n\n wstring message = L\"Expected: \" + ToString(mismatch_pair.first->type) + L\" \\\"\" + expectedName + L\"\\\" \"\n + L\"Actual: \" + ToString(mismatch_pair.second->type) + L\" \\\"\" + actualName + L\"\\\"\";\n\n Assert::Fail(message.c_str());\n }\n }\n\n public:\n \n TEST_METHOD(should_not_recognize_any_tokens_in_an_empty_string)\n {\n auto tokens = ascii_tree::tokenize(\"\");\n Assert::IsTrue(tokens.empty());\n }\n\n TEST_METHOD(should_recognize_a_root_node)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_root_node_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" [ * ]\");\n Assert::AreEqual(token::root_node, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_named_node)\n {\n const string all_chars = \"_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n auto tokens = ascii_tree::tokenize(\"[\" + all_chars + \"]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(all_chars.c_str(), tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_named_node_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" [ a ]\");\n Assert::AreEqual(token::named_node, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"a\");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_edge_name_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" a \");\n Assert::AreEqual(token::edge_name, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"\/\");\n Assert::AreEqual(token::ascending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_an_ascending_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" \/ \");\n Assert::AreEqual(token::ascending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"\\\\\");\n Assert::AreEqual(token::descending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_descending_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" \\\\ \");\n Assert::AreEqual(token::descending_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"|\");\n Assert::AreEqual(token::vertical_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_vertical_edge_part_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" | \");\n Assert::AreEqual(token::vertical_edge_part, tokens.front().type);\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"-a-\");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge_with_spaces)\n {\n auto tokens = ascii_tree::tokenize(\" - a - \");\n Assert::AreEqual(token::horizontal_edge, tokens.front().type);\n Assert::AreEqual(\"a\", tokens.front().name.c_str());\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[*][a]\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::named_node, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"[*]-a-\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::horizontal_edge, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_horizontal_edge_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"-a-[b]\");\n tokens_should_match_({ { token::horizontal_edge, \"a\" }, { token::named_node, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_descending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\\\\\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::descending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_an_ascending_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]\/\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::ascending_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_a_vertical_edge_part)\n {\n auto tokens = ascii_tree::tokenize(\"[*]|\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::vertical_edge_part, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_root_node_next_to_an_edge_name)\n {\n auto tokens = ascii_tree::tokenize(\"[*]a\");\n tokens_should_match_({ { token::root_node, \"\" }, { token::edge_name, \"a\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_root_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a][*]\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::root_node, \"\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_named_node)\n {\n auto tokens = ascii_tree::tokenize(\"[a][b]\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::named_node, \"b\" } }, tokens);\n }\n\n TEST_METHOD(should_recognize_a_named_node_next_to_a_horizontal_edge)\n {\n auto tokens = ascii_tree::tokenize(\"[a]-b-\");\n tokens_should_match_({ { token::named_node, \"a\" }, { token::horizontal_edge, \"b\" } }, tokens);\n }\n\n };\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: apinotifierimpl.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: jb $ $Date: 2002-02-11 13:47:53 $\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#include \"apinotifierimpl.hxx\"\n\n#ifndef CONFIGMGR_API_NODEACCESS_HXX_\n#include \"apinodeaccess.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGNODE_HXX_\n#include \"noderef.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGVALUEREF_HXX_\n#include \"valueref.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGNOTIFIER_HXX_\n#include \"confignotifier.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGEXCEPT_HXX_\n#include \"configexcept.hxx\"\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\nnamespace configmgr\n{\n namespace configapi\n {\n\/\/-----------------------------------------------------------------------------------\n namespace lang = css::lang;\n namespace util = css::util;\n namespace beans = css::beans;\n\n using uno::RuntimeException;\n using uno::Reference;\n\n using configuration::NodeRef;\n using configuration::ValueRef;\n using configuration::Tree;\n\n\n\/\/ Generic Notifier Support Implementations\n\/\/-----------------------------------------------------------------------------------\n\n\/\/\/ add a Listener to the notifier of a NodeAccess\ntemplate <class Listener>\ninline\nvoid genericAddListener(NodeAccess& rNode, const Reference< Listener >& xListener )\n{\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n aGuardedNotifier->add(rNode.getNodeRef(), xListener);\n}\n\n\/\/\/ remove a Listener from the notifier of a NodeAccess\ntemplate <class Listener>\ninline\nvoid genericRemoveListener(NodeAccess& rNode, const Reference< Listener >& xListener )\n{\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n aGuardedNotifier->remove(rNode.getNodeRef(), xListener);\n}\n\n\n\/** add a Listener for all or some children of a NodeAccess to its notifier\n <p> If the name given is empty, the listener will be added to all children of the node<\/p>\n @returns\n <TRUE\/> if the node was found, or the name was empty\n <FALSE\/> if the named node wasn't found\n*\/\ntemplate <class Listener>\ninline\nbool genericAddChildListener(NodeGroupInfoAccess& rNode, const Reference< Listener >& xListener, const OUString& sName )\n{\n using configuration::validateChildName;\n\n if (sName.getLength() != 0)\n {\n GuardedNodeDataAccess aGuardedNode( rNode ); \/\/ guard access to children\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n\n Tree aTree( aGuardedNode.getTree() );\n NodeRef aNode( aGuardedNode.getNode() );\n\n Name aChildName = validateChildName(sName,aTree,aNode);\n\n if (!aTree.hasChild(aNode,aChildName)) return false;\n\n aGuardedNotifier->addForOne(aNode, xListener, aChildName);\n }\n else\n {\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n\n aGuardedNotifier->addForAll(rNode.getNodeRef(), xListener);\n\n \/\/ always ok, as we addreess no specific NodeRef\n }\n return true;\n}\n\n\/** remove a Listener from all or some children of a NodeAccess to its notifier\n <p> If the name given is empty, the listener will be removed from any children of the node<\/p>\n @returns\n <TRUE\/> if the node was found, or the name was empty\n <FALSE\/> if the named node wasn't found\n*\/\ntemplate <class Listener>\ninline\nbool genericRemoveChildListener(NodeGroupInfoAccess& rNode, const Reference< Listener >& xListener, const OUString& sName )\n{\n using configuration::validateChildName;\n\n if (sName.getLength() != 0)\n {\n GuardedNodeDataAccess aGuardedNode( rNode ); \/\/ guard access to children\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n\n Tree aTree( aGuardedNode.getTree() );\n NodeRef aNode( aGuardedNode.getNode() );\n\n Name aChildName = validateChildName(sName,aTree,aNode);\n\n if (!aTree.hasChild(aNode,aChildName)) return false;\n\n aGuardedNotifier->removeForOne(aNode, xListener, aChildName);\n }\n else\n {\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n\n aGuardedNotifier->removeForAll(rNode.getNodeRef(), xListener);\n\n \/\/ always ok, as we addreess no specific NodeRef\n }\n return true;\n}\n\n\n\n\/\/ XComponent\n\/\/-----------------------------------------------------------------------------------\nvoid implAddListener(NodeAccess& rNode, const Reference< css::lang::XEventListener >& xListener )\n throw(RuntimeException)\n{\n genericAddListener(rNode,xListener);\n}\n\nvoid implRemoveListener(NodeAccess& rNode, const Reference< css::lang::XEventListener >& xListener )\n throw(RuntimeException)\n{\n genericRemoveListener(rNode,xListener);\n}\n\n\/\/ XContainer\n\/\/-----------------------------------------------------------------------------------\nvoid implAddListener(NodeAccess& rNode, const Reference< css::container::XContainerListener >& xListener )\n throw(RuntimeException)\n{\n genericAddListener(rNode,xListener);\n}\n\nvoid implRemoveListener(NodeAccess& rNode, const Reference< css::container::XContainerListener >& xListener )\n throw(RuntimeException)\n{\n genericRemoveListener(rNode,xListener);\n}\n\n\/\/ XChangesNotifier\n\/\/-----------------------------------------------------------------------------------\n\nvoid implAddListener(NodeAccess& rNode, const Reference< css::util::XChangesListener >& xListener )\n throw(RuntimeException)\n{\n genericAddListener(rNode,xListener);\n}\n\nvoid implRemoveListener(NodeAccess& rNode, const Reference< css::util::XChangesListener >& xListener )\n throw(RuntimeException)\n{\n genericRemoveListener(rNode,xListener);\n}\n\n\/\/ XMultiPropertySet\n\/\/-----------------------------------------------------------------------------------\n\nvoid implAddListener( NodeAccess& rNode, const uno::Reference< beans::XPropertiesChangeListener >& xListener, const uno::Sequence< OUString >& aPropertyNames )\n throw(uno::RuntimeException)\n{\n\n GuardedNotifier impl( rNode );\n\n \/\/ TODO: is an exception for unknown names allowed\/needed ?\n impl->add(rNode.getNodeRef(), xListener, aPropertyNames);\n}\n\n\nvoid implRemoveListener( NodeAccess& rNode, const uno::Reference< beans::XPropertiesChangeListener >& xListener )\n throw(uno::RuntimeException)\n{\n genericRemoveListener(rNode,xListener);\n}\n\n\/\/ XPropertySet (manages listeners associated with named child node)\n\/\/-----------------------------------------------------------------------------------\n\n\/\/ XPropertySet - VetoableChangeListeners\n\/\/-----------------------------------------------------------------------------------\n\nvoid implAddListener( NodeGroupInfoAccess& rNode, const uno::Reference< beans::XVetoableChangeListener >& xListener, const OUString& sPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n using namespace css::beans;\n try\n {\n if (!genericAddChildListener(rNode,xListener,sPropertyName))\n {\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot add listener - node not found !\")),\n rNode.getUnoInstance() );\n }\n }\n catch (configuration::InvalidName& ex)\n {\n ExceptionMapper e(ex);\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot add listener - node not found:\")) += ex.message(),\n rNode.getUnoInstance() );\n }\n catch (configuration::WrappedUnoException& ex)\n {\n throw css::lang::WrappedTargetException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: adding a listener failed: \")) += ex.message(),\n rNode.getUnoInstance(),\n ex.getAnyUnoException());\n }\n catch (configuration::Exception& ex)\n {\n ExceptionMapper e(ex);\n e.setContext( rNode.getUnoInstance() );\n e.unhandled();\n }\n\n}\n\n\nvoid implRemoveListener( NodeGroupInfoAccess& rNode, const uno::Reference< beans::XVetoableChangeListener >& xListener, const OUString& sPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n using namespace css::beans;\n try\n {\n if (!genericRemoveChildListener(rNode,xListener,sPropertyName))\n {\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot remove listener - node not found !\")),\n rNode.getUnoInstance() );\n }\n }\n catch (configuration::InvalidName& ex)\n {\n ExceptionMapper e(ex);\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot remove listener - node not found:\")) += ex.message(),\n rNode.getUnoInstance() );\n }\n catch (configuration::WrappedUnoException& ex)\n {\n throw css::lang::WrappedTargetException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: removing a listener failed: \")) += ex.message(),\n rNode.getUnoInstance(),\n ex.getAnyUnoException());\n }\n catch (configuration::Exception& ex)\n {\n ExceptionMapper e(ex);\n e.setContext( rNode.getUnoInstance() );\n e.unhandled();\n }\n}\n\n\/\/ XPropertySet - PropertyChangeListeners\n\/\/-----------------------------------------------------------------------------------\n\nvoid implAddListener( NodeGroupInfoAccess& rNode, const uno::Reference< beans::XPropertyChangeListener >& xListener, const OUString& sPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n using namespace css::beans;\n try\n {\n if (!genericAddChildListener(rNode,xListener,sPropertyName))\n {\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot add listener - node not found !\")),\n rNode.getUnoInstance() );\n }\n }\n catch (configuration::InvalidName& ex)\n {\n ExceptionMapper e(ex);\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot add listener - node not found:\")) += ex.message(),\n rNode.getUnoInstance() );\n }\n catch (configuration::WrappedUnoException& ex)\n {\n throw css::lang::WrappedTargetException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: adding a listener failed: \")) += ex.message(),\n rNode.getUnoInstance(),\n ex.getAnyUnoException());\n }\n catch (configuration::Exception& ex)\n {\n ExceptionMapper e(ex);\n e.setContext( rNode.getUnoInstance() );\n e.unhandled();\n }\n}\n\nvoid implRemoveListener( NodeGroupInfoAccess& rNode, const uno::Reference< beans::XPropertyChangeListener >& xListener, const OUString& sPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n using namespace css::beans;\n try\n {\n if (!genericRemoveChildListener(rNode,xListener,sPropertyName))\n {\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot remove listener - node not found !\")),\n rNode.getUnoInstance() );\n }\n }\n catch (configuration::InvalidName& ex)\n {\n ExceptionMapper e(ex);\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot remove listener - node not found:\")) += ex.message(),\n rNode.getUnoInstance() );\n }\n catch (configuration::WrappedUnoException& ex)\n {\n throw css::lang::WrappedTargetException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: removing a listener failed: \")) += ex.message(),\n rNode.getUnoInstance(),\n ex.getAnyUnoException());\n }\n catch (configuration::Exception& ex)\n {\n ExceptionMapper e(ex);\n e.setContext( rNode.getUnoInstance() );\n e.unhandled();\n }\n}\n\n\/\/-----------------------------------------------------------------------------------\n } \/\/ namespace configapi\n\n} \/\/ namespace configmgr\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.222); FILE MERGED 2005\/09\/05 17:03:30 rt 1.5.222.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: apinotifierimpl.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 03:08: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#include \"apinotifierimpl.hxx\"\n\n#ifndef CONFIGMGR_API_NODEACCESS_HXX_\n#include \"apinodeaccess.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGNODE_HXX_\n#include \"noderef.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGVALUEREF_HXX_\n#include \"valueref.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGNOTIFIER_HXX_\n#include \"confignotifier.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGEXCEPT_HXX_\n#include \"configexcept.hxx\"\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\nnamespace configmgr\n{\n namespace configapi\n {\n\/\/-----------------------------------------------------------------------------------\n namespace lang = css::lang;\n namespace util = css::util;\n namespace beans = css::beans;\n\n using uno::RuntimeException;\n using uno::Reference;\n\n using configuration::NodeRef;\n using configuration::ValueRef;\n using configuration::Tree;\n\n\n\/\/ Generic Notifier Support Implementations\n\/\/-----------------------------------------------------------------------------------\n\n\/\/\/ add a Listener to the notifier of a NodeAccess\ntemplate <class Listener>\ninline\nvoid genericAddListener(NodeAccess& rNode, const Reference< Listener >& xListener )\n{\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n aGuardedNotifier->add(rNode.getNodeRef(), xListener);\n}\n\n\/\/\/ remove a Listener from the notifier of a NodeAccess\ntemplate <class Listener>\ninline\nvoid genericRemoveListener(NodeAccess& rNode, const Reference< Listener >& xListener )\n{\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n aGuardedNotifier->remove(rNode.getNodeRef(), xListener);\n}\n\n\n\/** add a Listener for all or some children of a NodeAccess to its notifier\n <p> If the name given is empty, the listener will be added to all children of the node<\/p>\n @returns\n <TRUE\/> if the node was found, or the name was empty\n <FALSE\/> if the named node wasn't found\n*\/\ntemplate <class Listener>\ninline\nbool genericAddChildListener(NodeGroupInfoAccess& rNode, const Reference< Listener >& xListener, const OUString& sName )\n{\n using configuration::validateChildName;\n\n if (sName.getLength() != 0)\n {\n GuardedNodeDataAccess aGuardedNode( rNode ); \/\/ guard access to children\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n\n Tree aTree( aGuardedNode.getTree() );\n NodeRef aNode( aGuardedNode.getNode() );\n\n Name aChildName = validateChildName(sName,aTree,aNode);\n\n if (!aTree.hasChild(aNode,aChildName)) return false;\n\n aGuardedNotifier->addForOne(aNode, xListener, aChildName);\n }\n else\n {\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n\n aGuardedNotifier->addForAll(rNode.getNodeRef(), xListener);\n\n \/\/ always ok, as we addreess no specific NodeRef\n }\n return true;\n}\n\n\/** remove a Listener from all or some children of a NodeAccess to its notifier\n <p> If the name given is empty, the listener will be removed from any children of the node<\/p>\n @returns\n <TRUE\/> if the node was found, or the name was empty\n <FALSE\/> if the named node wasn't found\n*\/\ntemplate <class Listener>\ninline\nbool genericRemoveChildListener(NodeGroupInfoAccess& rNode, const Reference< Listener >& xListener, const OUString& sName )\n{\n using configuration::validateChildName;\n\n if (sName.getLength() != 0)\n {\n GuardedNodeDataAccess aGuardedNode( rNode ); \/\/ guard access to children\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n\n Tree aTree( aGuardedNode.getTree() );\n NodeRef aNode( aGuardedNode.getNode() );\n\n Name aChildName = validateChildName(sName,aTree,aNode);\n\n if (!aTree.hasChild(aNode,aChildName)) return false;\n\n aGuardedNotifier->removeForOne(aNode, xListener, aChildName);\n }\n else\n {\n GuardedNotifier aGuardedNotifier( rNode ); \/\/ guard the notifier\n\n aGuardedNotifier->removeForAll(rNode.getNodeRef(), xListener);\n\n \/\/ always ok, as we addreess no specific NodeRef\n }\n return true;\n}\n\n\n\n\/\/ XComponent\n\/\/-----------------------------------------------------------------------------------\nvoid implAddListener(NodeAccess& rNode, const Reference< css::lang::XEventListener >& xListener )\n throw(RuntimeException)\n{\n genericAddListener(rNode,xListener);\n}\n\nvoid implRemoveListener(NodeAccess& rNode, const Reference< css::lang::XEventListener >& xListener )\n throw(RuntimeException)\n{\n genericRemoveListener(rNode,xListener);\n}\n\n\/\/ XContainer\n\/\/-----------------------------------------------------------------------------------\nvoid implAddListener(NodeAccess& rNode, const Reference< css::container::XContainerListener >& xListener )\n throw(RuntimeException)\n{\n genericAddListener(rNode,xListener);\n}\n\nvoid implRemoveListener(NodeAccess& rNode, const Reference< css::container::XContainerListener >& xListener )\n throw(RuntimeException)\n{\n genericRemoveListener(rNode,xListener);\n}\n\n\/\/ XChangesNotifier\n\/\/-----------------------------------------------------------------------------------\n\nvoid implAddListener(NodeAccess& rNode, const Reference< css::util::XChangesListener >& xListener )\n throw(RuntimeException)\n{\n genericAddListener(rNode,xListener);\n}\n\nvoid implRemoveListener(NodeAccess& rNode, const Reference< css::util::XChangesListener >& xListener )\n throw(RuntimeException)\n{\n genericRemoveListener(rNode,xListener);\n}\n\n\/\/ XMultiPropertySet\n\/\/-----------------------------------------------------------------------------------\n\nvoid implAddListener( NodeAccess& rNode, const uno::Reference< beans::XPropertiesChangeListener >& xListener, const uno::Sequence< OUString >& aPropertyNames )\n throw(uno::RuntimeException)\n{\n\n GuardedNotifier impl( rNode );\n\n \/\/ TODO: is an exception for unknown names allowed\/needed ?\n impl->add(rNode.getNodeRef(), xListener, aPropertyNames);\n}\n\n\nvoid implRemoveListener( NodeAccess& rNode, const uno::Reference< beans::XPropertiesChangeListener >& xListener )\n throw(uno::RuntimeException)\n{\n genericRemoveListener(rNode,xListener);\n}\n\n\/\/ XPropertySet (manages listeners associated with named child node)\n\/\/-----------------------------------------------------------------------------------\n\n\/\/ XPropertySet - VetoableChangeListeners\n\/\/-----------------------------------------------------------------------------------\n\nvoid implAddListener( NodeGroupInfoAccess& rNode, const uno::Reference< beans::XVetoableChangeListener >& xListener, const OUString& sPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n using namespace css::beans;\n try\n {\n if (!genericAddChildListener(rNode,xListener,sPropertyName))\n {\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot add listener - node not found !\")),\n rNode.getUnoInstance() );\n }\n }\n catch (configuration::InvalidName& ex)\n {\n ExceptionMapper e(ex);\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot add listener - node not found:\")) += ex.message(),\n rNode.getUnoInstance() );\n }\n catch (configuration::WrappedUnoException& ex)\n {\n throw css::lang::WrappedTargetException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: adding a listener failed: \")) += ex.message(),\n rNode.getUnoInstance(),\n ex.getAnyUnoException());\n }\n catch (configuration::Exception& ex)\n {\n ExceptionMapper e(ex);\n e.setContext( rNode.getUnoInstance() );\n e.unhandled();\n }\n\n}\n\n\nvoid implRemoveListener( NodeGroupInfoAccess& rNode, const uno::Reference< beans::XVetoableChangeListener >& xListener, const OUString& sPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n using namespace css::beans;\n try\n {\n if (!genericRemoveChildListener(rNode,xListener,sPropertyName))\n {\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot remove listener - node not found !\")),\n rNode.getUnoInstance() );\n }\n }\n catch (configuration::InvalidName& ex)\n {\n ExceptionMapper e(ex);\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot remove listener - node not found:\")) += ex.message(),\n rNode.getUnoInstance() );\n }\n catch (configuration::WrappedUnoException& ex)\n {\n throw css::lang::WrappedTargetException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: removing a listener failed: \")) += ex.message(),\n rNode.getUnoInstance(),\n ex.getAnyUnoException());\n }\n catch (configuration::Exception& ex)\n {\n ExceptionMapper e(ex);\n e.setContext( rNode.getUnoInstance() );\n e.unhandled();\n }\n}\n\n\/\/ XPropertySet - PropertyChangeListeners\n\/\/-----------------------------------------------------------------------------------\n\nvoid implAddListener( NodeGroupInfoAccess& rNode, const uno::Reference< beans::XPropertyChangeListener >& xListener, const OUString& sPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n using namespace css::beans;\n try\n {\n if (!genericAddChildListener(rNode,xListener,sPropertyName))\n {\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot add listener - node not found !\")),\n rNode.getUnoInstance() );\n }\n }\n catch (configuration::InvalidName& ex)\n {\n ExceptionMapper e(ex);\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot add listener - node not found:\")) += ex.message(),\n rNode.getUnoInstance() );\n }\n catch (configuration::WrappedUnoException& ex)\n {\n throw css::lang::WrappedTargetException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: adding a listener failed: \")) += ex.message(),\n rNode.getUnoInstance(),\n ex.getAnyUnoException());\n }\n catch (configuration::Exception& ex)\n {\n ExceptionMapper e(ex);\n e.setContext( rNode.getUnoInstance() );\n e.unhandled();\n }\n}\n\nvoid implRemoveListener( NodeGroupInfoAccess& rNode, const uno::Reference< beans::XPropertyChangeListener >& xListener, const OUString& sPropertyName )\n throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n using namespace css::beans;\n try\n {\n if (!genericRemoveChildListener(rNode,xListener,sPropertyName))\n {\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot remove listener - node not found !\")),\n rNode.getUnoInstance() );\n }\n }\n catch (configuration::InvalidName& ex)\n {\n ExceptionMapper e(ex);\n throw UnknownPropertyException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: cannot remove listener - node not found:\")) += ex.message(),\n rNode.getUnoInstance() );\n }\n catch (configuration::WrappedUnoException& ex)\n {\n throw css::lang::WrappedTargetException(\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"Configuration: removing a listener failed: \")) += ex.message(),\n rNode.getUnoInstance(),\n ex.getAnyUnoException());\n }\n catch (configuration::Exception& ex)\n {\n ExceptionMapper e(ex);\n e.setContext( rNode.getUnoInstance() );\n e.unhandled();\n }\n}\n\n\/\/-----------------------------------------------------------------------------------\n } \/\/ namespace configapi\n\n} \/\/ namespace configmgr\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: providerfactory.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: jb $ $Date: 2001-05-18 16:16: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 EXPRESS 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#include <stdio.h>\n#ifndef _CONFIGMGR_PROVIDER_FACTORY_HXX_\n#include \"providerfactory.hxx\"\n#endif\n\n#ifndef _UNO_LBNAMES_H_\n#include <uno\/lbnames.h>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef CONFIGMGR_API_FACTORY_HXX_\n#include \"confapifactory.hxx\"\n#endif\n#ifndef CONFIGMGR_API_SVCCOMPONENT_HXX_\n#include \"confsvccomponent.hxx\"\n#endif\n#ifndef CONFIGMGR_BOOTSTRAP_HXX_\n#include \"bootstrap.hxx\"\n#endif\n\n\/\/ #include <com\/sun\/star\/lang\/XEventListener.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n\n#define THISREF() static_cast< ::cppu::OWeakObject* >(this)\n\n\n\/\/........................................................................\nnamespace configmgr\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::beans;\n using namespace ::cppu;\n using namespace ::osl;\n\n\n \/\/=======================================================================================\n \/\/= OProviderFactory\n \/\/=======================================================================================\n typedef ::cppu::WeakImplHelper1<XEventListener> XEventListener_BASE;\n class ODisposingListener : public XEventListener_BASE\n {\n OProviderFactory& m_aFactory;\n public:\n ODisposingListener(OProviderFactory& _aFactory):\n m_aFactory(_aFactory){}\n\n virtual void SAL_CALL disposing(com::sun::star::lang::EventObject const& rEvt) throw()\n {\n m_aFactory.disposing(rEvt);\n }\n ~ODisposingListener()\n {\n volatile int dummy = 0;\n }\n\n };\n \/\/---------------------------------------------------------------------------------------\n\n \/\/=======================================================================================\n \/\/= OProviderFactory\n \/\/=======================================================================================\n \/\/---------------------------------------------------------------------------------------\n OProviderFactory::OProviderFactory(const Reference< XMultiServiceFactory >& _rxORB, ProviderInstantiation _pObjectCreator)\n :m_pObjectCreator(_pObjectCreator)\n ,m_xORB(_rxORB)\n ,m_pPureSettings(NULL)\n {\n ODisposingListener *pListener = new ODisposingListener(*this);\n m_xEventListener = pListener;\n\n Reference<com::sun::star::lang::XComponent> xComponent(_rxORB, UNO_QUERY);\n if (xComponent.is())\n {\n xComponent->addEventListener(m_xEventListener);\n \/\/ CFG_TRACE_INFO(\"insert disposeListener.\");\n }\n }\n\n\/\/---------------------------------------------------------------------------------------\n OProviderFactory::~OProviderFactory()\n {\n delete m_pPureSettings;\n\n Reference<com::sun::star::lang::XComponent> xComponent(m_xORB, UNO_QUERY);\n if (xComponent.is())\n {\n xComponent->removeEventListener(m_xEventListener);\n }\n xComponent = xComponent.query(m_xDefaultProvider);\n if (xComponent.is())\n {\n xComponent->removeEventListener(m_xEventListener);\n }\n }\n\n \/\/---------------------------------------------------------------------------------------\n void OProviderFactory::ensureBootstrapSettings()\n {\n if (!m_pPureSettings)\n m_pPureSettings = new BootstrapSettings();\n }\n\n \/\/---------------------------------------------------------------------------------------\n static bool checkForOptions(const ConnectionSettings& _rSettings)\n {\n return _rSettings.hasLocale() ||\n _rSettings.hasAsyncSetting();\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::implGetProvider(const ConnectionSettings& _rSettings, sal_Bool _bCanReuse)\n {\n \/\/ the providers for the given session type\n UserSpecificProviders& rProviders = m_aProviders[_rSettings.getSessionType()];\n\n \/\/ the user to retrieve the provider for\n ::rtl::OUString sUser;\n if (_rSettings.hasUser())\n sUser = _rSettings.getUser();\n\n if (checkForOptions(_rSettings))\n _bCanReuse = false;\n\n Reference< XInterface > xReturn;\n if (_bCanReuse)\n {\n UserSpecificProvidersIterator aExistentProvider = rProviders.find(sUser);\n if (rProviders.end() != aExistentProvider)\n {\n \/\/ should check for differing parameters here\n xReturn = aExistentProvider->second;\n }\n }\n\n \/\/ #78409\n \/\/ if a provider is queried with a password, we always create a new instance for it,\n \/\/ as don't wan't to remember the passwords for the user.\n\n if (!xReturn.is())\n {\n \/\/ create and connect the provider (may still throw exceptions)\n xReturn = (*m_pObjectCreator)(m_xORB, _rSettings);\n\n \/\/ check for success\n if (!xReturn.is())\n {\n OSL_ENSURE(false, \"Object creator could not create provider, but returned NULL instead of throwing an exception\");\n sal_Char const sCannotCreate[] = \"Cannot create ConfigurationProvider. Unknown backend or factory error.\";\n \/\/ should become CannotLoadConfigurationException\n throw uno::Exception( OUString::createFromAscii(sCannotCreate), *this );\n }\n\n \/\/ remember it for later usage\n if (_bCanReuse)\n rProviders[sUser] = xReturn;\n }\n\n return xReturn;\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::implCreateProviderWithSettings(const ConnectionSettings& _rSettings, bool _bRequiresBootstrap, bool _bCanReuse)\n {\n try\n {\n return implGetProvider(_rSettings, _bCanReuse);\n }\n catch(uno::Exception& e)\n {\n if (_bRequiresBootstrap)\n {\n OSL_ASSERT(m_pPureSettings);\n raiseBootstrapException(*m_pPureSettings, *this);\n\n OSL_ASSERT(m_pPureSettings->status == BOOTSTRAP_DATA_OK);\n }\n\n sal_Char const sConnectionFailure[] = \"Cannot open Configuration: \";\n OUString const sFailure = OUString::createFromAscii(sConnectionFailure);\n e.Message = sFailure.concat(e.Message);\n throw;\n }\n }\n\n \/\/---------------------------------------------------------------------------------------\n void OProviderFactory::ensureDefaultProvider()\n {\n if (m_xDefaultProvider.is())\n return;\n\n ensureBootstrapSettings();\n\n m_xDefaultProvider = implCreateProviderWithSettings(m_pPureSettings->settings,true,true);\n\n \/\/ register disposing listener\n Reference<com::sun::star::lang::XComponent> xComponent(m_xDefaultProvider, UNO_QUERY);\n if (xComponent.is())\n {\n xComponent->addEventListener(m_xEventListener);\n }\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::createProvider()\n {\n MutexGuard aGuard(m_aMutex);\n ensureDefaultProvider();\n return m_xDefaultProvider;\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::createProviderWithArguments(const Sequence< Any >& _rArguments)\n {\n ConnectionSettings aSettings(_rArguments);\n return createProviderWithSettings( aSettings );\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::createProviderWithSettings(const ConnectionSettings& _rSettings)\n {\n MutexGuard aGuard(m_aMutex);\n\n ConnectionSettings aThisRoundSettings(_rSettings);\n\n \/\/ use bootstrap data if necessary\n bool bUseBootstrapData = !aThisRoundSettings.isComplete();\n\n \/\/ detect a plugin session. Can be specified only as argument\n sal_Bool bIsPluginSession = aThisRoundSettings.isPlugin();\n\n if (bIsPluginSession)\n {\n OSL_ENSURE(!aThisRoundSettings.isSourcePathValid(),\"Invalid Argument: No explicit source path should be specified for plugin session\");\n bUseBootstrapData = true;\n }\n\n \/\/ use bootstrap data if necessary\n if (bUseBootstrapData)\n {\n ensureBootstrapSettings();\n\n ConnectionSettings aMergedSettings = m_pPureSettings->settings;\n aMergedSettings.mergeOverrides(aThisRoundSettings);\n aMergedSettings.swap(aThisRoundSettings);\n }\n\n \/\/ if we have a plugin session, translate the session type into the one appliable.\n if (bIsPluginSession)\n {\n \/\/ try to create (or share) a local-session provider\n\n \/\/ For a plugin-local session, we need a valid update directory.\n \/\/ (We can't just rely on the session to fail if it is created with a valid source directory and an\n \/\/ invalid update directory. In such a scenario it will succeed to open, but not to update.)\n if (!m_pPureSettings->settings.isLocalSession())\n {\n const OUString sLocalSessionIdentifier = OUString::createFromAscii(LOCAL_SESSION_IDENTIFIER);\n\n \/\/ (We can't just rely on the session to fail if it is created with a valid source directory and an\n \/\/ invalid update directory. In such a scenario it will succeed to open, but not to update.)\n if (aThisRoundSettings.isComplete(sLocalSessionIdentifier) &&\n aThisRoundSettings.isUpdatePathValid())\n try\n {\n aThisRoundSettings.setSessionType(sLocalSessionIdentifier, Settings::SO_ADJUSTMENT);\n return implGetProvider(aThisRoundSettings,true);\n }\n catch(Exception&)\n {\n \/\/ allowed. The creation of the local provider may fail.\n }\n }\n \/\/ did not create the local session\n\n \/\/ -> create the original one\n if (m_pPureSettings->settings.isSessionTypeKnown())\n {\n OUString sOriginalType = m_pPureSettings->settings.getSessionType();\n aThisRoundSettings.setSessionType(sOriginalType, Settings::SO_ADJUSTMENT);\n }\n else\n {\n OUString const sPortalSessionIdentifier = OUString::createFromAscii(PORTAL_SESSION_IDENTIFIER);\n aThisRoundSettings.setSessionType(sPortalSessionIdentifier, Settings::SO_ADJUSTMENT);\n }\n }\n\n aThisRoundSettings.validate();\n OSL_ENSURE(aThisRoundSettings.isComplete(), \"Incomplete Data for creating a ConfigurationProvider\");\n\n Reference< XInterface > xProvider =\n implCreateProviderWithSettings( aThisRoundSettings,bUseBootstrapData,\n !aThisRoundSettings.hasPassword() );\n\n return xProvider;\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > SAL_CALL OProviderFactory::createInstance( ) throw(Exception, RuntimeException)\n {\n \/\/ default provider\n return createProvider();\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > SAL_CALL OProviderFactory::createInstanceWithArguments( const Sequence< Any >& _rArguments ) throw(Exception, RuntimeException)\n {\n return createProviderWithArguments(_rArguments);\n }\n\n \/\/=======================================================================================\n Reference< XSingleServiceFactory > SAL_CALL createProviderFactory(\n const Reference< XMultiServiceFactory > & rServiceManager,\n const OUString & rComponentName,\n ProviderInstantiation pCreateFunction,\n const Sequence< OUString > & rServiceNames\n )\n {\n return new OProviderFactory(rServiceManager, pCreateFunction);\n }\n\n void OProviderFactory::disposing(com::sun::star::lang::EventObject const& _rEvt) throw()\n {\n MutexGuard aGuard(m_aMutex);\n if (_rEvt.Source == m_xORB)\n {\n Reference<com::sun::star::lang::XComponent> xComponent(m_xDefaultProvider, UNO_QUERY);\n if (xComponent.is())\n {\n xComponent->removeEventListener(m_xEventListener);\n }\n m_xORB = NULL;\n m_xDefaultProvider = NULL;\n }\n else if (_rEvt.Source == m_xDefaultProvider)\n {\n m_xDefaultProvider = NULL;\n }\n else\n OSL_ENSURE(sal_False, \"unknown object disposed.\");\n }\n\n\/\/........................................................................\n} \/\/ namespace configmgr\n\/\/........................................................................\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.8 2001\/04\/03 16:33:58 jb\n * Local AdministrationProvider now mapped to Setup-session\n *\n * Revision 1.7 2001\/03\/21 12:15:40 jl\n * OSL_ENSHURE replaced by OSL_ENSURE\n *\n * Revision 1.6 2001\/01\/26 07:54:21 lla\n * #82734# disposing with lasy writing necessary\n *\n * Revision 1.5 2000\/12\/07 16:46:12 dg\n * #81469# incomplete adjustments to portal environment fixed\n *\n * Revision 1.4 2000\/12\/07 13:56:21 tlx\n * #81469#\n *\n * Revision 1.3 2000\/12\/03 17:12:52 dg\n * #81164# stdio missing\n *\n * Revision 1.2 2000\/12\/03 11:52:13 dg\n * #81164# invalid provider instantiation\n *\n * Revision 1.1 2000\/12\/01 13:53:17 fs\n * initial checkin - afctory for configuration provider(s)\n *\n *\n * Revision 1.0 30.11.00 19:05:35 fs\n ************************************************************************\/\n\n<commit_msg>#81412# Erroneous handling of default provider<commit_after>\/*************************************************************************\n *\n * $RCSfile: providerfactory.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: jb $ $Date: 2001-05-22 07:42:07 $\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 EXPRESS 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#include <stdio.h>\n#ifndef _CONFIGMGR_PROVIDER_FACTORY_HXX_\n#include \"providerfactory.hxx\"\n#endif\n\n#ifndef _UNO_LBNAMES_H_\n#include <uno\/lbnames.h>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef CONFIGMGR_API_FACTORY_HXX_\n#include \"confapifactory.hxx\"\n#endif\n#ifndef CONFIGMGR_API_SVCCOMPONENT_HXX_\n#include \"confsvccomponent.hxx\"\n#endif\n#ifndef CONFIGMGR_BOOTSTRAP_HXX_\n#include \"bootstrap.hxx\"\n#endif\n\n\/\/ #include <com\/sun\/star\/lang\/XEventListener.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n\n#define THISREF() static_cast< ::cppu::OWeakObject* >(this)\n\n\n\/\/........................................................................\nnamespace configmgr\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::beans;\n using namespace ::cppu;\n using namespace ::osl;\n\n\n \/\/=======================================================================================\n \/\/= OProviderFactory\n \/\/=======================================================================================\n typedef ::cppu::WeakImplHelper1<XEventListener> XEventListener_BASE;\n class ODisposingListener : public XEventListener_BASE\n {\n OProviderFactory& m_aFactory;\n public:\n ODisposingListener(OProviderFactory& _aFactory):\n m_aFactory(_aFactory){}\n\n virtual void SAL_CALL disposing(com::sun::star::lang::EventObject const& rEvt) throw()\n {\n m_aFactory.disposing(rEvt);\n }\n ~ODisposingListener()\n {\n volatile int dummy = 0;\n }\n\n };\n \/\/---------------------------------------------------------------------------------------\n\n \/\/=======================================================================================\n \/\/= OProviderFactory\n \/\/=======================================================================================\n \/\/---------------------------------------------------------------------------------------\n OProviderFactory::OProviderFactory(const Reference< XMultiServiceFactory >& _rxORB, ProviderInstantiation _pObjectCreator)\n :m_pObjectCreator(_pObjectCreator)\n ,m_xORB(_rxORB)\n ,m_pPureSettings(NULL)\n {\n ODisposingListener *pListener = new ODisposingListener(*this);\n m_xEventListener = pListener;\n\n Reference<com::sun::star::lang::XComponent> xComponent(_rxORB, UNO_QUERY);\n if (xComponent.is())\n {\n xComponent->addEventListener(m_xEventListener);\n \/\/ CFG_TRACE_INFO(\"insert disposeListener.\");\n }\n }\n\n\/\/---------------------------------------------------------------------------------------\n OProviderFactory::~OProviderFactory()\n {\n delete m_pPureSettings;\n\n Reference<com::sun::star::lang::XComponent> xComponent(m_xORB, UNO_QUERY);\n if (xComponent.is())\n {\n xComponent->removeEventListener(m_xEventListener);\n }\n xComponent = xComponent.query(m_xDefaultProvider);\n if (xComponent.is())\n {\n xComponent->removeEventListener(m_xEventListener);\n }\n }\n\n \/\/---------------------------------------------------------------------------------------\n void OProviderFactory::ensureBootstrapSettings()\n {\n if (!m_pPureSettings)\n m_pPureSettings = new BootstrapSettings();\n }\n\n \/\/---------------------------------------------------------------------------------------\n static bool checkForOptions(const ConnectionSettings& _rSettings)\n {\n return _rSettings.hasLocale() ||\n _rSettings.hasAsyncSetting();\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::implGetProvider(const ConnectionSettings& _rSettings, sal_Bool _bCanReuse)\n {\n \/\/ the providers for the given session type\n UserSpecificProviders& rProviders = m_aProviders[_rSettings.getSessionType()];\n\n \/\/ the user to retrieve the provider for\n ::rtl::OUString sUser;\n if (_rSettings.hasUser())\n sUser = _rSettings.getUser();\n\n if (checkForOptions(_rSettings))\n _bCanReuse = false;\n\n Reference< XInterface > xReturn;\n if (_bCanReuse)\n {\n UserSpecificProvidersIterator aExistentProvider = rProviders.find(sUser);\n if (rProviders.end() != aExistentProvider)\n {\n \/\/ should check for differing parameters here\n xReturn = aExistentProvider->second;\n }\n }\n\n \/\/ #78409\n \/\/ if a provider is queried with a password, we always create a new instance for it,\n \/\/ as don't wan't to remember the passwords for the user.\n\n if (!xReturn.is())\n {\n \/\/ create and connect the provider (may still throw exceptions)\n xReturn = (*m_pObjectCreator)(m_xORB, _rSettings);\n\n \/\/ check for success\n if (!xReturn.is())\n {\n OSL_ENSURE(false, \"Object creator could not create provider, but returned NULL instead of throwing an exception\");\n sal_Char const sCannotCreate[] = \"Cannot create ConfigurationProvider. Unknown backend or factory error.\";\n \/\/ should become CannotLoadConfigurationException\n throw uno::Exception( OUString::createFromAscii(sCannotCreate), *this );\n }\n\n \/\/ remember it for later usage\n if (_bCanReuse)\n rProviders[sUser] = xReturn;\n }\n\n return xReturn;\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::implCreateProviderWithSettings(const ConnectionSettings& _rSettings, bool _bRequiresBootstrap, bool _bCanReuse)\n {\n try\n {\n return implGetProvider(_rSettings, _bCanReuse);\n }\n catch(uno::Exception& e)\n {\n if (_bRequiresBootstrap)\n {\n OSL_ASSERT(m_pPureSettings);\n raiseBootstrapException(*m_pPureSettings, *this);\n\n OSL_ASSERT(m_pPureSettings->status == BOOTSTRAP_DATA_OK);\n }\n\n sal_Char const sConnectionFailure[] = \"Cannot open Configuration: \";\n OUString const sFailure = OUString::createFromAscii(sConnectionFailure);\n e.Message = sFailure.concat(e.Message);\n throw;\n }\n }\n\n \/\/---------------------------------------------------------------------------------------\n void OProviderFactory::ensureDefaultProvider()\n {\n if (m_xDefaultProvider.is())\n return;\n\n ensureBootstrapSettings();\n\n ConnectionSettings aThisRoundSettings(m_pPureSettings->settings);\n\n aThisRoundSettings.validate();\n OSL_ENSURE(aThisRoundSettings.isComplete(), \"Incomplete Data for creating a ConfigurationProvider\");\n\n m_xDefaultProvider = implCreateProviderWithSettings(aThisRoundSettings,true,true);\n\n \/\/ register disposing listener\n Reference<com::sun::star::lang::XComponent> xComponent(m_xDefaultProvider, UNO_QUERY);\n if (xComponent.is())\n {\n xComponent->addEventListener(m_xEventListener);\n }\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::createProvider()\n {\n MutexGuard aGuard(m_aMutex);\n ensureDefaultProvider();\n return m_xDefaultProvider;\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::createProviderWithArguments(const Sequence< Any >& _rArguments)\n {\n ConnectionSettings aSettings(_rArguments);\n return createProviderWithSettings( aSettings );\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > OProviderFactory::createProviderWithSettings(const ConnectionSettings& _rSettings)\n {\n MutexGuard aGuard(m_aMutex);\n\n ConnectionSettings aThisRoundSettings(_rSettings);\n\n \/\/ use bootstrap data if necessary\n bool bUseBootstrapData = !aThisRoundSettings.isComplete();\n\n \/\/ detect a plugin session. Can be specified only as argument\n sal_Bool bIsPluginSession = aThisRoundSettings.isPlugin();\n\n if (bIsPluginSession)\n {\n OSL_ENSURE(!aThisRoundSettings.isSourcePathValid(),\"Invalid Argument: No explicit source path should be specified for plugin session\");\n bUseBootstrapData = true;\n }\n\n \/\/ use bootstrap data if necessary\n if (bUseBootstrapData)\n {\n ensureBootstrapSettings();\n\n ConnectionSettings aMergedSettings = m_pPureSettings->settings;\n aMergedSettings.mergeOverrides(aThisRoundSettings);\n aMergedSettings.swap(aThisRoundSettings);\n }\n\n \/\/ if we have a plugin session, translate the session type into the one appliable.\n if (bIsPluginSession)\n {\n \/\/ try to create (or share) a local-session provider\n\n \/\/ For a plugin-local session, we need a valid update directory.\n \/\/ (We can't just rely on the session to fail if it is created with a valid source directory and an\n \/\/ invalid update directory. In such a scenario it will succeed to open, but not to update.)\n if (!m_pPureSettings->settings.isLocalSession())\n {\n const OUString sLocalSessionIdentifier = OUString::createFromAscii(LOCAL_SESSION_IDENTIFIER);\n\n \/\/ (We can't just rely on the session to fail if it is created with a valid source directory and an\n \/\/ invalid update directory. In such a scenario it will succeed to open, but not to update.)\n if (aThisRoundSettings.isComplete(sLocalSessionIdentifier) &&\n aThisRoundSettings.isUpdatePathValid())\n try\n {\n aThisRoundSettings.setSessionType(sLocalSessionIdentifier, Settings::SO_ADJUSTMENT);\n return implGetProvider(aThisRoundSettings,true);\n }\n catch(Exception&)\n {\n \/\/ allowed. The creation of the local provider may fail.\n }\n }\n \/\/ did not create the local session\n\n \/\/ -> create the original one\n if (m_pPureSettings->settings.isSessionTypeKnown())\n {\n OUString sOriginalType = m_pPureSettings->settings.getSessionType();\n aThisRoundSettings.setSessionType(sOriginalType, Settings::SO_ADJUSTMENT);\n }\n else\n {\n OUString const sPortalSessionIdentifier = OUString::createFromAscii(PORTAL_SESSION_IDENTIFIER);\n aThisRoundSettings.setSessionType(sPortalSessionIdentifier, Settings::SO_ADJUSTMENT);\n }\n }\n\n aThisRoundSettings.validate();\n OSL_ENSURE(aThisRoundSettings.isComplete(), \"Incomplete Data for creating a ConfigurationProvider\");\n\n Reference< XInterface > xProvider =\n implCreateProviderWithSettings( aThisRoundSettings,bUseBootstrapData,\n !aThisRoundSettings.hasPassword() );\n\n return xProvider;\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > SAL_CALL OProviderFactory::createInstance( ) throw(Exception, RuntimeException)\n {\n \/\/ default provider\n return createProvider();\n }\n\n \/\/---------------------------------------------------------------------------------------\n Reference< XInterface > SAL_CALL OProviderFactory::createInstanceWithArguments( const Sequence< Any >& _rArguments ) throw(Exception, RuntimeException)\n {\n return createProviderWithArguments(_rArguments);\n }\n\n \/\/=======================================================================================\n Reference< XSingleServiceFactory > SAL_CALL createProviderFactory(\n const Reference< XMultiServiceFactory > & rServiceManager,\n const OUString & rComponentName,\n ProviderInstantiation pCreateFunction,\n const Sequence< OUString > & rServiceNames\n )\n {\n return new OProviderFactory(rServiceManager, pCreateFunction);\n }\n\n void OProviderFactory::disposing(com::sun::star::lang::EventObject const& _rEvt) throw()\n {\n MutexGuard aGuard(m_aMutex);\n if (_rEvt.Source == m_xORB)\n {\n Reference<com::sun::star::lang::XComponent> xComponent(m_xDefaultProvider, UNO_QUERY);\n if (xComponent.is())\n {\n xComponent->removeEventListener(m_xEventListener);\n }\n m_xORB = NULL;\n m_xDefaultProvider = NULL;\n }\n else if (_rEvt.Source == m_xDefaultProvider)\n {\n m_xDefaultProvider = NULL;\n }\n else\n OSL_ENSURE(sal_False, \"unknown object disposed.\");\n }\n\n\/\/........................................................................\n} \/\/ namespace configmgr\n\/\/........................................................................\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.9 2001\/05\/18 16:16:52 jb\n * #81412# Cleaned up bootstrap settings handling; Added recognition of bootstrap errors\n *\n * Revision 1.8 2001\/04\/03 16:33:58 jb\n * Local AdministrationProvider now mapped to Setup-session\n *\n * Revision 1.7 2001\/03\/21 12:15:40 jl\n * OSL_ENSHURE replaced by OSL_ENSURE\n *\n * Revision 1.6 2001\/01\/26 07:54:21 lla\n * #82734# disposing with lasy writing necessary\n *\n * Revision 1.5 2000\/12\/07 16:46:12 dg\n * #81469# incomplete adjustments to portal environment fixed\n *\n * Revision 1.4 2000\/12\/07 13:56:21 tlx\n * #81469#\n *\n * Revision 1.3 2000\/12\/03 17:12:52 dg\n * #81164# stdio missing\n *\n * Revision 1.2 2000\/12\/03 11:52:13 dg\n * #81164# invalid provider instantiation\n *\n * Revision 1.1 2000\/12\/01 13:53:17 fs\n * initial checkin - afctory for configuration provider(s)\n *\n *\n * Revision 1.0 30.11.00 19:05:35 fs\n ************************************************************************\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: PColumn.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: oj $ $Date: 2002-07-05 06:58:32 $\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#ifndef _CONNECTIVITY_PCOLUMN_HXX_\n#define _CONNECTIVITY_PCOLUMN_HXX_\n\n#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_\n#include \"connectivity\/sdbcx\/VColumn.hxx\"\n#endif\n\nnamespace connectivity\n{\n namespace parse\n {\n class OParseColumn;\n\n typedef sdbcx::OColumn OParseColumn_BASE;\n typedef ::comphelper::OIdPropertyArrayUsageHelper<OParseColumn> OParseColumn_PROP;\n\n class OParseColumn : public OParseColumn_BASE,\n public OParseColumn_PROP\n {\n ::rtl::OUString m_aRealName;\n ::rtl::OUString m_aTableName;\n sal_Bool m_bFunction;\n sal_Bool m_bDbasePrecisionChanged;\n protected:\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n\n virtual ~OParseColumn();\n public:\n OParseColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase);\n OParseColumn(const ::rtl::OUString& _Name,\n const ::rtl::OUString& _TypeName,\n const ::rtl::OUString& _DefaultValue,\n sal_Int32 _IsNullable,\n sal_Int32 _Precision,\n sal_Int32 _Scale,\n sal_Int32 _Type,\n sal_Bool _IsAutoIncrement,\n sal_Bool _IsCurrency,\n sal_Bool _bCase);\n\n virtual void construct();\n\n void setRealName(const ::rtl::OUString& _rName) { m_aRealName = _rName; }\n void setTableName(const ::rtl::OUString& _rName) { m_aTableName = _rName; }\n void setFunction(sal_Bool _bFunction) { m_bFunction = _bFunction; }\n void setDbasePrecisionChanged(sal_Bool _bDbasePrecisionChanged) { m_bDbasePrecisionChanged = _bDbasePrecisionChanged; }\n\n ::rtl::OUString getRealName() const { return m_aRealName; }\n ::rtl::OUString getTableName() const { return m_aTableName; }\n sal_Bool getFunction() const { return m_bFunction; }\n sal_Bool getDbasePrecisionChanged() const { return m_bDbasePrecisionChanged; }\n };\n }\n}\n\n#endif \/\/_CONNECTIVITY_PCOLUMN_HXX_\n\n<commit_msg>INTEGRATION: CWS qrycomp (1.9.126); FILE MERGED 2003\/10\/30 14:13:31 oj 1.9.126.1: #i21791# changes for the querycomposer<commit_after>\/*************************************************************************\n *\n * $RCSfile: PColumn.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: vg $ $Date: 2003-12-16 12:26:58 $\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#ifndef _CONNECTIVITY_PCOLUMN_HXX_\n#define _CONNECTIVITY_PCOLUMN_HXX_\n\n#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_\n#include \"connectivity\/sdbcx\/VColumn.hxx\"\n#endif\n\nnamespace connectivity\n{\n namespace parse\n {\n class OParseColumn;\n\n typedef sdbcx::OColumn OParseColumn_BASE;\n typedef ::comphelper::OIdPropertyArrayUsageHelper<OParseColumn> OParseColumn_PROP;\n\n class OParseColumn : public OParseColumn_BASE,\n public OParseColumn_PROP\n {\n ::rtl::OUString m_aRealName;\n ::rtl::OUString m_aTableName;\n sal_Bool m_bFunction;\n sal_Bool m_bDbasePrecisionChanged;\n protected:\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n\n virtual ~OParseColumn();\n public:\n OParseColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase);\n OParseColumn(const ::rtl::OUString& _Name,\n const ::rtl::OUString& _TypeName,\n const ::rtl::OUString& _DefaultValue,\n sal_Int32 _IsNullable,\n sal_Int32 _Precision,\n sal_Int32 _Scale,\n sal_Int32 _Type,\n sal_Bool _IsAutoIncrement,\n sal_Bool _IsCurrency,\n sal_Bool _bCase);\n\n virtual void construct();\n\n void setRealName(const ::rtl::OUString& _rName) { m_aRealName = _rName; }\n void setTableName(const ::rtl::OUString& _rName) { m_aTableName = _rName; }\n void setFunction(sal_Bool _bFunction) { m_bFunction = _bFunction; }\n void setDbasePrecisionChanged(sal_Bool _bDbasePrecisionChanged) { m_bDbasePrecisionChanged = _bDbasePrecisionChanged; }\n\n ::rtl::OUString getRealName() const { return m_aRealName; }\n ::rtl::OUString getTableName() const { return m_aTableName; }\n sal_Bool getFunction() const { return m_bFunction; }\n sal_Bool getDbasePrecisionChanged() const { return m_bDbasePrecisionChanged; }\n };\n\n class OOrderColumn;\n\n typedef sdbcx::OColumn OOrderColumn_BASE;\n typedef ::comphelper::OIdPropertyArrayUsageHelper<OOrderColumn> OOrderColumn_PROP;\n\n class OOrderColumn : public OOrderColumn_BASE,\n public OOrderColumn_PROP\n {\n sal_Bool m_bAscending;\n sal_Bool m_bOrder;\n protected:\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n\n virtual ~OOrderColumn();\n public:\n OOrderColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase,sal_Bool _bAscending);\n OOrderColumn(const ::rtl::OUString& _Name,\n const ::rtl::OUString& _TypeName,\n const ::rtl::OUString& _DefaultValue,\n sal_Int32 _IsNullable,\n sal_Int32 _Precision,\n sal_Int32 _Scale,\n sal_Int32 _Type,\n sal_Bool _IsAutoIncrement,\n sal_Bool _IsCurrency,\n sal_Bool _bCase\n ,sal_Bool _bAscending);\n\n virtual void construct();\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);\n };\n }\n}\n\n#endif \/\/_CONNECTIVITY_PCOLUMN_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: YDriver.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 02:04:40 $\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 CONNECTIVITY_MYSQL_DRIVER_HXX\n#define CONNECTIVITY_MYSQL_DRIVER_HXX\n\n#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_\n#include <com\/sun\/star\/sdbc\/XDriver.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XDATADEFINITIONSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbcx\/XDataDefinitionSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _CPPUHELPER_COMPBASE3_HXX_\n#include <cppuhelper\/compbase3.hxx>\n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n#ifndef _COMPHELPER_BROADCASTHELPER_HXX_\n#include <comphelper\/broadcasthelper.hxx>\n#endif\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n\n\/\/........................................................................\nnamespace connectivity\n{\n\/\/........................................................................\n\n class OMetaConnection;\n\n namespace mysql\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriverDelegator_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception );\n\n typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::sdbc::XDriver\n , ::com::sun::star::sdbcx::XDataDefinitionSupplier\n , ::com::sun::star::lang::XServiceInfo\n > ODriverDelegator_BASE;\n\n typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,OMetaConnection*> TWeakConnectionPair;\n typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,TWeakConnectionPair> TWeakPair;\n typedef ::std::vector< TWeakPair > TWeakPairVector;\n DECLARE_STL_USTRINGACCESS_MAP(::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver >,TJDBCDrivers);\n\n\n \/** delegates all calls to the orignal driver and extend the existing one with the SDBCX layer.\n\n *\/\n class ODriverDelegator : public ::comphelper::OBaseMutex\n ,public ODriverDelegator_BASE\n {\n TJDBCDrivers m_aJdbcDrivers; \/\/ all jdbc drivers\n TWeakPairVector m_aConnections; \/\/ vector containing a list\n \/\/ of all the Connection objects\n \/\/ for this Driver\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > m_xODBCDriver;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;\n ::rtl::OUString m_sOldDriverClass;\n sal_Bool m_bUseOdbc;\n\n \/** load the driver we want to delegate.\n The <member>m_xODBCDriver<\/member> or <member>m_xDBCDriver<\/member> may be <NULL\/> if the driver could not be loaded.\n @param url\n The URL.\n @param info\n The property info contains which driver we have to delegate.\n @return\n The driver which was currently selected.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > loadDriver( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info );\n\n public:\n \/** creates a new delegator for a mysql driver\n *\/\n ODriverDelegator(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);\n\n \/\/ XServiceInfo\n DECLARE_SERVICE_INFO();\n static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XDriver\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getMajorVersion( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getMinorVersion( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XDataDefinitionSupplier\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& connection ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByURL( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n protected:\n \/\/\/ dtor\n virtual ~ODriverDelegator();\n \/\/ OComponentHelper\n virtual void SAL_CALL disposing(void);\n };\n }\n\n\/\/........................................................................\n} \/\/ namespace connectivity\n\/\/........................................................................\n#endif \/\/ CONNECTIVITY_MYSQL_DRIVER_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.276); FILE MERGED 2008\/04\/01 15:09:17 thb 1.6.276.3: #i85898# Stripping all external header guards 2008\/04\/01 10:53:41 thb 1.6.276.2: #i85898# Stripping all external header guards 2008\/03\/28 15:24:33 rt 1.6.276.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: YDriver.hxx,v $\n * $Revision: 1.7 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef CONNECTIVITY_MYSQL_DRIVER_HXX\n#define CONNECTIVITY_MYSQL_DRIVER_HXX\n\n#include <com\/sun\/star\/sdbc\/XDriver.hpp>\n#include <com\/sun\/star\/sdbcx\/XDataDefinitionSupplier.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <cppuhelper\/compbase3.hxx>\n#include <comphelper\/uno3.hxx>\n#include <comphelper\/stl_types.hxx>\n#include <comphelper\/broadcasthelper.hxx>\n#include \"connectivity\/CommonTools.hxx\"\n\n\/\/........................................................................\nnamespace connectivity\n{\n\/\/........................................................................\n\n class OMetaConnection;\n\n namespace mysql\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriverDelegator_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception );\n\n typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::sdbc::XDriver\n , ::com::sun::star::sdbcx::XDataDefinitionSupplier\n , ::com::sun::star::lang::XServiceInfo\n > ODriverDelegator_BASE;\n\n typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,OMetaConnection*> TWeakConnectionPair;\n typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,TWeakConnectionPair> TWeakPair;\n typedef ::std::vector< TWeakPair > TWeakPairVector;\n DECLARE_STL_USTRINGACCESS_MAP(::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver >,TJDBCDrivers);\n\n\n \/** delegates all calls to the orignal driver and extend the existing one with the SDBCX layer.\n\n *\/\n class ODriverDelegator : public ::comphelper::OBaseMutex\n ,public ODriverDelegator_BASE\n {\n TJDBCDrivers m_aJdbcDrivers; \/\/ all jdbc drivers\n TWeakPairVector m_aConnections; \/\/ vector containing a list\n \/\/ of all the Connection objects\n \/\/ for this Driver\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > m_xODBCDriver;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;\n ::rtl::OUString m_sOldDriverClass;\n sal_Bool m_bUseOdbc;\n\n \/** load the driver we want to delegate.\n The <member>m_xODBCDriver<\/member> or <member>m_xDBCDriver<\/member> may be <NULL\/> if the driver could not be loaded.\n @param url\n The URL.\n @param info\n The property info contains which driver we have to delegate.\n @return\n The driver which was currently selected.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > loadDriver( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info );\n\n public:\n \/** creates a new delegator for a mysql driver\n *\/\n ODriverDelegator(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);\n\n \/\/ XServiceInfo\n DECLARE_SERVICE_INFO();\n static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XDriver\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getMajorVersion( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getMinorVersion( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XDataDefinitionSupplier\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& connection ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByURL( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n protected:\n \/\/\/ dtor\n virtual ~ODriverDelegator();\n \/\/ OComponentHelper\n virtual void SAL_CALL disposing(void);\n };\n }\n\n\/\/........................................................................\n} \/\/ namespace connectivity\n\/\/........................................................................\n#endif \/\/ CONNECTIVITY_MYSQL_DRIVER_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ projection_sql_test.cpp\n\/\/\n\/\/ Identification: test\/sql\/projection_sql_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n\n#include \"sql\/testing_sql_util.h\"\n\n#include \"catalog\/catalog.h\"\n#include \"common\/harness.h\"\n#include \"concurrency\/transaction_manager_factory.h\"\n\nnamespace peloton {\nnamespace test {\n\nclass ProjectionSQLTests : public PelotonTest {\n public:\n ProjectionSQLTests() {\n auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();\n auto *txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n\n auto catalog = catalog::Catalog::GetInstance();\n catalog->Bootstrap();\n\n SetupTestTable();\n }\n\n ~ProjectionSQLTests() {\n auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();\n auto *txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n }\n\n void SetupTestTable() {\n TestingSQLUtil::ExecuteSQLQuery(\n \"CREATE TABLE test(a TINYINT, b SMALLINT, c INT, d BIGINT, e \"\n \"DECIMAL);\");\n\n \/\/ Insert tuples into table\n TestingSQLUtil::ExecuteSQLQuery(\n \"INSERT INTO test VALUES (1, 2, 3, 4, 5.0);\");\n }\n};\n\nTEST_F(ProjectionSQLTests, SimpleProjectionSQLTest) {\n \/\/ Test TINYINT\n std::string sql = \"SELECT a+a, a-a, a*a, a\/a, a+b, a+c, a+d, a+e FROM test\";\n std::vector<std::string> expected = {\"2|0|1|1|3|4|5|6\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n \/\/ Test SMALLINT\n sql = \"SELECT b+b, b-b, b*b, b\/b, b+a, b+c, b+d, b+e FROM test\";\n expected = {\"4|0|4|1|3|5|6|7\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n \/\/ Test INT\n sql = \"SELECT c+c, c-c, c*c, c\/c, c+a, c+b, c+d, c+e FROM test\";\n expected = {\"6|0|9|1|4|5|7|8\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n \/\/ Test BIGINT\n sql = \"SELECT d+d, d-d, d*d, d\/d, d+a, d+b, d+c, d+e FROM test\";\n expected = {\"8|0|16|1|5|6|7|9\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n \/\/ Test DECIMAL\n sql = \"SELECT e+e, e-e, e*e, e\/e, e+a, e+b, e+c, e+d FROM test\";\n expected = {\"10|0|25|1|6|7|8|9\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n}\n\nTEST_F(ProjectionSQLTests, ProjectionSQLTest) {\n std::string sql = \"SELECT a*5+b, -1+c, 6, a from test\";\n std::vector<std::string> expected = {\"7|2|6|1\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n sql = \"SELECT d+e*2.0, e, e+(2*c) from test\";\n expected = {\"14|5|11\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton\n<commit_msg>Fixed projection_sql_tests<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ projection_sql_test.cpp\n\/\/\n\/\/ Identification: test\/sql\/projection_sql_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n\n#include \"sql\/testing_sql_util.h\"\n\n#include \"catalog\/catalog.h\"\n#include \"common\/harness.h\"\n#include \"concurrency\/transaction_manager_factory.h\"\n\nnamespace peloton {\nnamespace test {\n\nclass ProjectionSQLTests : public PelotonTest {\n public:\n ProjectionSQLTests() {\n auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();\n auto *txn = txn_manager.BeginTransaction();\n auto catalog = catalog::Catalog::GetInstance();\n catalog->Bootstrap();\n catalog->CreateDatabase(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n SetupTestTable();\n }\n\n ~ProjectionSQLTests() {\n auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();\n auto *txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n }\n\n void SetupTestTable() {\n TestingSQLUtil::ExecuteSQLQuery(\n \"CREATE TABLE test(a TINYINT, b SMALLINT, c INT, d BIGINT, e \"\n \"DECIMAL);\");\n\n \/\/ Insert tuples into table\n TestingSQLUtil::ExecuteSQLQuery(\n \"INSERT INTO test VALUES (1, 2, 3, 4, 5.0);\");\n }\n};\n\nTEST_F(ProjectionSQLTests, SimpleProjectionSQLTest) {\n \/\/ Test TINYINT\n std::string sql = \"SELECT a+a, a-a, a*a, a\/a, a+b, a+c, a+d, a+e FROM test\";\n std::vector<std::string> expected = {\"2|0|1|1|3|4|5|6\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n \/\/ Test SMALLINT\n sql = \"SELECT b+b, b-b, b*b, b\/b, b+a, b+c, b+d, b+e FROM test\";\n expected = {\"4|0|4|1|3|5|6|7\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n \/\/ Test INT\n sql = \"SELECT c+c, c-c, c*c, c\/c, c+a, c+b, c+d, c+e FROM test\";\n expected = {\"6|0|9|1|4|5|7|8\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n \/\/ Test BIGINT\n sql = \"SELECT d+d, d-d, d*d, d\/d, d+a, d+b, d+c, d+e FROM test\";\n expected = {\"8|0|16|1|5|6|7|9\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n \/\/ Test DECIMAL\n sql = \"SELECT e+e, e-e, e*e, e\/e, e+a, e+b, e+c, e+d FROM test\";\n expected = {\"10|0|25|1|6|7|8|9\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n}\n\nTEST_F(ProjectionSQLTests, ProjectionSQLTest) {\n std::string sql = \"SELECT a*5+b, -1+c, 6, a from test\";\n std::vector<std::string> expected = {\"7|2|6|1\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n\n sql = \"SELECT d+e*2.0, e, e+(2*c) from test\";\n expected = {\"14|5|11\"};\n TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: PeptideBuilder_test.C,v 1.7 2004\/02\/13 17:00:22 anhi Exp $\n\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/STRUCTURE\/peptideBuilder.h>\n#include <vector>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(PeptideBuilder, \"$Id: PeptideBuilder_test.C,v 1.7 2004\/02\/13 17:00:22 anhi Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace BALL::Peptides;\n\nPeptideBuilder* pbptr = 0;\nCHECK(PeptideBuilder())\n\tpbptr = new PeptideBuilder;\n\tTEST_NOT_EQUAL(pbptr, 0)\nRESULT\t\t\t\t\t\t\t\t\n\nCHECK(~PeptideBuilder())\n\tdelete pbptr;\n\tpbptr = 0;\nRESULT\n\nAminoAcidDescriptor* aad = 0;\nCHECK(AminoAcidDescriptor())\n\taad = new AminoAcidDescriptor;\n\tTEST_NOT_EQUAL(aad,0)\nRESULT\n\nCHECK(~AminoAcidDescriptor())\n\tdelete aad;\n aad= 0; \nRESULT\n\nCHECK(AminoAcidDescriptor(const String& type, const Angle& phi,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst Angle& psi, const Angle& omega))\n\taad= new AminoAcidDescriptor(\"HIS\", Angle(M_PI, true), Angle(M_PI, true));\n\tTEST_NOT_EQUAL(aad, 0)\n\tTEST_EQUAL(aad->getType(), \"HIS\")\n\tTEST_EQUAL(aad->getPhi(), Angle(M_PI, true))\n\tTEST_EQUAL(aad->getPsi(), Angle(M_PI, true))\nRESULT\n\nAminoAcidDescriptor* aad2=0;\nCHECK(AminoAcidDescriptor(const AminoAcidDescriptor& aad))\n\taad2 = new AminoAcidDescriptor(*aad);\n\tTEST_NOT_EQUAL(aad2, 0)\n\tTEST_EQUAL(aad2->getType(), \"HIS\")\n\tTEST_EQUAL(aad2->getPhi(), Angle(M_PI, true))\n\tTEST_EQUAL(aad2->getPsi(), Angle(M_PI, true))\nRESULT\n\n\n\/\/\n\/\/ Tests for the complement get and set-methods\n\/\/\n\nCHECK(setAminoAcidType(const String& type))\n aad->setAminoAcidType(\"GLY\");\n\tTEST_EQUAL(aad->getType(),\"GLY\")\n aad2->setAminoAcidType(\"V\");\n\tTEST_EQUAL(aad2->getType(),\"VAL\")\nRESULT\n\nCHECK(setPhi(const Angle& phi))\n aad->setPhi(Angle(-47., false));\n\tTEST_EQUAL(aad->getPhi(), Angle(-47., false) )\n aad2->setPhi(Angle(-77., false));\n\tTEST_EQUAL(aad2->getPhi(), Angle(-77., false) )\nRESULT\n\nCHECK(setPsi(const Angle& phi))\n aad->setPsi(Angle(-58., false));\n\tTEST_EQUAL(aad->getPsi(), Angle(-58., false) )\n aad2->setPsi(Angle(8.15, false));\n\tTEST_EQUAL(aad2->getPsi(), Angle(8.15, false) )\nRESULT\n\nCHECK(setOmega(const Angle& phi))\n aad->setOmega(Angle(90., false));\n\tTEST_EQUAL(aad->getOmega(), Angle(90., false))\n aad2->setOmega(Angle(M_PI, true));\n\tTEST_EQUAL(aad2->getOmega(), Angle(180, false))\nRESULT\n\n\t\/*CHECK(~AminoAcidDescriptor()) used for the addAminoAcid()-Test\n\tdelete aad ;\n aad = 0; \n\tRESULT*\/\n\n\/\/\n\/\/ Tests of class PeptideBuilder \n\/\/\n\nPeptideBuilder* pb = 0;\nCHECK(PeptideBuilder())\n pb= new PeptideBuilder;\n\tTEST_NOT_EQUAL(pb, 0)\nRESULT\n\n\/\/\n\/\/CHECK(PeptideBuilder(const std::vector<AminoAcidDescriptor>& sequence)) later on\n\/\/\n\nCHECK(addAminoAcid(const String& type, const Angle& phi, const Angle& psi, const Angle& omega))\n pb->addAminoAcid(\"LEU\");\n pb->addAminoAcid(\"SER\",Angle(M_PI, true),Angle(M_PI, true));\n\tTEST_NOT_EQUAL(pb, 0)\nRESULT\n\nCHECK(addAminoAcid(const AminoAcidDescriptor& aad))\n pb->addAminoAcid(*aad);\n pb->addAminoAcid(*aad2);\n\tTEST_NOT_EQUAL(pb, 0)\nRESULT\n\nCHECK(setChainName(const String& name)\/getChainName())\n pb->setChainName(\"TestChainName\");\n\tTEST_EQUAL(pb->getChainName(),\"TestChainName\")\nRESULT\n\nCHECK(setProteinName(const String& name)\/getProteinName())\n\tpb->setProteinName(\"TestProteinName\");\n\tTEST_EQUAL(pb->getProteinName(),\"TestProteinName\")\nRESULT\n\nPeptideBuilder* pb2 = 0;\nCHECK(PeptideBuilder(const PeptideBuilder& pb))\n pb2= new PeptideBuilder(*pb);\n\tTEST_NOT_EQUAL(pb2, 0)\n\tTEST_EQUAL(pb2->getChainName(),\"TestChainName\")\n\tTEST_EQUAL(pb2->getProteinName(),\"TestProteinName\")\nRESULT\n\nPeptideBuilder* pb3=0;\nCHECK(PeptideBuilder(const std::vector<AminoAcidDescriptor>& sequence))\n std::vector<AminoAcidDescriptor> v;\n v.push_back(*aad);\n\tv.push_back(*aad2);\n pb3 = new PeptideBuilder(v);\n TEST_NOT_EQUAL(pb3, 0)\nRESULT\n\nCHECK(construct())\n\tProtein *prot=pb->construct();\n\tResidueIterator resIt;\n resIt = prot->beginResidue();\n\n\tPRECISION(1e-3)\n\tTEST_EQUAL(resIt->getName(), \"LEU\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));\n TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-58.,false));\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"SER\")\n TEST_REAL_EQUAL(fabs(resIt->getTorsionPhi().toRadian()), M_PI)\n\tTEST_REAL_EQUAL(fabs(resIt->getTorsionPsi().toRadian()), M_PI)\n ++resIt;\n\tPRECISION(2E-2)\n\tTEST_EQUAL(resIt->getName(), \"GLY\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-47, false))\n TEST_REAL_EQUAL(resIt->getTorsionPsi(), -1.01);\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"VAL\")\n TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-77., false));\n\tTEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(0, false));\n\t\n\tprot = pb3->construct();\n resIt = prot->beginResidue();\n\t\t\n\tTEST_EQUAL(resIt->getName(), \"GLY\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));\n TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-58.,false));\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"VAL\")\n TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-77.,false));\n\tTEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(0,false));\n\n\tPeptideBuilder pb4;\n\tpb4.addAminoAcid(\"PRO\");\n\tpb4.addAminoAcid(\"PRO\", Angle(-12., false), Angle(42, false));\n\tpb4.addAminoAcid(\"PRO\", Angle(28, false), Angle(33, false));\n\n\tprot = pb4.construct();\n\t\n resIt = prot->beginResidue();\n\n\tTEST_EQUAL(resIt->getName(), \"PRO\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));\n TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-80.,false));\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"PRO\")\n TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-12, false));\n\tTEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-80, false));\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"PRO\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(28,false));\n TEST_EQUAL(resIt->getTorsionPsi(), 0);\nRESULT\n\n\/\/empty sequence\nCHECK(construct())\n\tpb->construct();\n TEST_NOT_EQUAL(pb, 0)\nRESULT\n\nPeptideBuilder* pb4=0;\nCHECK(PeptideBuilder())\n pb4 = new PeptideBuilder(*pb);\n\tTEST_NOT_EQUAL(pb, 0)\nRESULT\n\n\/\/ Proline as first residue \nCHECK(~PeptideBuilder() throw())\n\tdelete pb;\n\tpb = 0;\n\tdelete pb2;\n pb2= 0; \n\tdelete pb3;\n pb3= 0; \n\tdelete pb4;\n pb4= 0; \nRESULT\n\nCHECK(~AminoAcidDescriptor() throw())\n\tdelete aad;\n aad = 0; \n\tdelete aad2;\n aad2= 0; \nRESULT\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<commit_msg>no message<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: PeptideBuilder_test.C,v 1.8 2004\/05\/10 13:19:22 amoll Exp $\n\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/STRUCTURE\/peptideBuilder.h>\n#include <BALL\/STRUCTURE\/fragmentDB.h>\n#include <vector>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(PeptideBuilder, \"$Id: PeptideBuilder_test.C,v 1.8 2004\/05\/10 13:19:22 amoll Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace BALL::Peptides;\n\nPeptideBuilder* pbptr = 0;\nCHECK(PeptideBuilder())\n\tpbptr = new PeptideBuilder;\n\tTEST_NOT_EQUAL(pbptr, 0)\nRESULT\t\t\t\t\t\t\t\t\n\nCHECK(~PeptideBuilder())\n\tdelete pbptr;\n\tpbptr = 0;\nRESULT\n\nAminoAcidDescriptor* aad = 0;\nCHECK(AminoAcidDescriptor())\n\taad = new AminoAcidDescriptor;\n\tTEST_NOT_EQUAL(aad,0)\nRESULT\n\nCHECK(~AminoAcidDescriptor())\n\tdelete aad;\n aad= 0; \nRESULT\n\nCHECK(AminoAcidDescriptor(const String& type, const Angle& phi,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst Angle& psi, const Angle& omega))\n\taad= new AminoAcidDescriptor(\"HIS\", Angle(M_PI, true), Angle(M_PI, true));\n\tTEST_NOT_EQUAL(aad, 0)\n\tTEST_EQUAL(aad->getType(), \"HIS\")\n\tTEST_EQUAL(aad->getPhi(), Angle(M_PI, true))\n\tTEST_EQUAL(aad->getPsi(), Angle(M_PI, true))\nRESULT\n\nAminoAcidDescriptor* aad2=0;\nCHECK(AminoAcidDescriptor(const AminoAcidDescriptor& aad))\n\taad2 = new AminoAcidDescriptor(*aad);\n\tTEST_NOT_EQUAL(aad2, 0)\n\tTEST_EQUAL(aad2->getType(), \"HIS\")\n\tTEST_EQUAL(aad2->getPhi(), Angle(M_PI, true))\n\tTEST_EQUAL(aad2->getPsi(), Angle(M_PI, true))\nRESULT\n\n\n\/\/\n\/\/ Tests for the complement get and set-methods\n\/\/\n\nCHECK(setAminoAcidType(const String& type))\n aad->setAminoAcidType(\"GLY\");\n\tTEST_EQUAL(aad->getType(),\"GLY\")\n aad2->setAminoAcidType(\"V\");\n\tTEST_EQUAL(aad2->getType(),\"VAL\")\nRESULT\n\nCHECK(setPhi(const Angle& phi))\n aad->setPhi(Angle(-47., false));\n\tTEST_EQUAL(aad->getPhi(), Angle(-47., false) )\n aad2->setPhi(Angle(-77., false));\n\tTEST_EQUAL(aad2->getPhi(), Angle(-77., false) )\nRESULT\n\nCHECK(setPsi(const Angle& phi))\n aad->setPsi(Angle(-58., false));\n\tTEST_EQUAL(aad->getPsi(), Angle(-58., false) )\n aad2->setPsi(Angle(8.15, false));\n\tTEST_EQUAL(aad2->getPsi(), Angle(8.15, false) )\nRESULT\n\nCHECK(setOmega(const Angle& phi))\n aad->setOmega(Angle(90., false));\n\tTEST_EQUAL(aad->getOmega(), Angle(90., false))\n aad2->setOmega(Angle(M_PI, true));\n\tTEST_EQUAL(aad2->getOmega(), Angle(180, false))\nRESULT\n\n\t\/*CHECK(~AminoAcidDescriptor()) used for the addAminoAcid()-Test\n\tdelete aad ;\n aad = 0; \n\tRESULT*\/\n\n\/\/\n\/\/ Tests of class PeptideBuilder \n\/\/\n\nPeptideBuilder* pb = 0;\nCHECK(PeptideBuilder())\n pb= new PeptideBuilder;\n\tTEST_NOT_EQUAL(pb, 0)\nRESULT\n\n\/\/\n\/\/CHECK(PeptideBuilder(const std::vector<AminoAcidDescriptor>& sequence)) later on\n\/\/\n\nCHECK(addAminoAcid(const String& type, const Angle& phi, const Angle& psi, const Angle& omega))\n pb->addAminoAcid(\"LEU\");\n pb->addAminoAcid(\"SER\",Angle(M_PI, true),Angle(M_PI, true));\n\tTEST_NOT_EQUAL(pb, 0)\nRESULT\n\nCHECK(addAminoAcid(const AminoAcidDescriptor& aad))\n pb->addAminoAcid(*aad);\n pb->addAminoAcid(*aad2);\n\tTEST_NOT_EQUAL(pb, 0)\nRESULT\n\nCHECK(setChainName(const String& name)\/getChainName())\n pb->setChainName(\"TestChainName\");\n\tTEST_EQUAL(pb->getChainName(),\"TestChainName\")\nRESULT\n\nCHECK(setProteinName(const String& name)\/getProteinName())\n\tpb->setProteinName(\"TestProteinName\");\n\tTEST_EQUAL(pb->getProteinName(),\"TestProteinName\")\nRESULT\n\nPeptideBuilder* pb2 = 0;\nCHECK(PeptideBuilder(const PeptideBuilder& pb))\n pb2= new PeptideBuilder(*pb);\n\tTEST_NOT_EQUAL(pb2, 0)\n\tTEST_EQUAL(pb2->getChainName(),\"TestChainName\")\n\tTEST_EQUAL(pb2->getProteinName(),\"TestProteinName\")\nRESULT\n\nPeptideBuilder* pb3=0;\nCHECK(PeptideBuilder(const std::vector<AminoAcidDescriptor>& sequence))\n std::vector<AminoAcidDescriptor> v;\n v.push_back(*aad);\n\tv.push_back(*aad2);\n pb3 = new PeptideBuilder(v);\n TEST_NOT_EQUAL(pb3, 0)\nRESULT\n\nFragmentDB db(\"\");\npb->setFragmentDB(&db);\npb3->setFragmentDB(&db);\n\nCHECK(construct())\n\tProtein *prot=pb->construct();\n\tTEST_NOT_EQUAL(prot, 0)\n\tResidueIterator resIt;\n resIt = prot->beginResidue();\n\n\tPRECISION(1e-3)\n\tTEST_EQUAL(resIt->getName(), \"LEU\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));\n TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-58.,false));\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"SER\")\n TEST_REAL_EQUAL(fabs(resIt->getTorsionPhi().toRadian()), M_PI)\n\tTEST_REAL_EQUAL(fabs(resIt->getTorsionPsi().toRadian()), M_PI)\n ++resIt;\n\tPRECISION(2E-2)\n\tTEST_EQUAL(resIt->getName(), \"GLY\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-47, false))\n TEST_REAL_EQUAL(resIt->getTorsionPsi(), -1.01);\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"VAL\")\n TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-77., false));\n\tTEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(0, false));\n\tdelete prot;\n\t\n\tprot = pb3->construct();\n\tTEST_NOT_EQUAL(prot, 0)\n resIt = prot->beginResidue();\n\t\t\n\tTEST_EQUAL(resIt->getName(), \"GLY\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));\n TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-58.,false));\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"VAL\")\n TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-77.,false));\n\tTEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(0,false));\n\n\tPeptideBuilder pb4;\n\tpb4.setFragmentDB(&db);\n\tpb4.addAminoAcid(\"PRO\");\n\tpb4.addAminoAcid(\"PRO\", Angle(-12., false), Angle(42, false));\n\tpb4.addAminoAcid(\"PRO\", Angle(28, false), Angle(33, false));\n\n\tdelete prot;\n\tprot = pb4.construct();\n\t\n resIt = prot->beginResidue();\n\n\tTEST_EQUAL(resIt->getName(), \"PRO\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));\n TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-80.,false));\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"PRO\")\n TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-12, false));\n\tTEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-80, false));\n ++resIt;\n\tTEST_EQUAL(resIt->getName(), \"PRO\")\n\tTEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(28,false));\n TEST_EQUAL(resIt->getTorsionPsi(), 0);\n\n\tdelete prot;\nRESULT\n\n\/\/empty sequence\nCHECK(construct())\n\tpb->construct();\n TEST_NOT_EQUAL(pb, 0)\nRESULT\n\nPeptideBuilder* pb4=0;\nCHECK(PeptideBuilder())\n pb4 = new PeptideBuilder(*pb);\n\tTEST_NOT_EQUAL(pb, 0)\nRESULT\n\n\/\/ Proline as first residue \nCHECK(~PeptideBuilder() throw())\n\tdelete pb;\n\tpb = 0;\n\tdelete pb2;\n pb2= 0; \n\tdelete pb3;\n pb3= 0; \n\tdelete pb4;\n pb4= 0; \nRESULT\n\nCHECK(~AminoAcidDescriptor() throw())\n\tdelete aad;\n aad = 0; \n\tdelete aad2;\n aad2= 0; \nRESULT\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (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. See the *\n * GNU 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 program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"processcontrol.h\"\n#include \"akdebug.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QTimer>\n#include <QtDebug>\n\n#ifdef Q_OS_UNIX\n#include <sys\/types.h>\n#include <signal.h>\n#endif\n\n#ifdef Q_OS_WINCE\n#include <windows.h>\n#endif\n\nusing namespace Akonadi;\n\nstatic const int s_maxCrashCount = 2;\n\nProcessControl::ProcessControl( QObject *parent )\n : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ),\n mRestartOnceOnExit( false )\n{\n connect( &mProcess, SIGNAL(error(QProcess::ProcessError)),\n this, SLOT(slotError(QProcess::ProcessError)) );\n connect( &mProcess, SIGNAL(finished(int,QProcess::ExitStatus)),\n this, SLOT(slotFinished(int,QProcess::ExitStatus)) );\n mProcess.setProcessChannelMode( QProcess::ForwardedChannels );\n}\n\nProcessControl::~ProcessControl()\n{\n stop();\n}\n\nvoid ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy )\n{\n mFailedToStart = false;\n\n mApplication = application;\n mArguments = arguments;\n mPolicy = policy;\n\n start();\n}\n\nvoid ProcessControl::setCrashPolicy( CrashPolicy policy )\n{\n mPolicy = policy;\n}\n\nvoid ProcessControl::stop()\n{\n if ( mProcess.state() != QProcess::NotRunning ) {\n mProcess.waitForFinished( 10000 );\n mProcess.terminate();\n }\n}\n\nvoid ProcessControl::slotError( QProcess::ProcessError error )\n{\n switch ( error ) {\n case QProcess::Crashed:\n mCrashCount++;\n \/\/ do nothing, we'll respawn in slotFinished\n break;\n case QProcess::FailedToStart:\n default:\n mFailedToStart = true;\n break;\n }\n\n qDebug( \"ProcessControl: Application '%s' stopped unexpectedly (%s)\",\n qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );\n}\n\nvoid ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus )\n{\n if ( exitStatus == QProcess::CrashExit ) {\n if ( mPolicy == RestartOnCrash ) {\n \/\/ don't try to start an unstartable application\n if ( !mFailedToStart && mCrashCount <= s_maxCrashCount ) {\n qDebug( \"Application '%s' crashed! %d restarts left.\", qPrintable( mApplication ), s_maxCrashCount - mCrashCount );\n start();\n emit restarted();\n } else {\n if ( mFailedToStart ) {\n qDebug( \"Application '%s' failed to start!\", qPrintable( mApplication ) );\n } else {\n qDebug( \"Application '%s' crashed too often. Giving up!\", qPrintable( mApplication ) );\n }\n mPolicy = StopOnCrash;\n emit unableToStart();\n return;\n }\n } else {\n qDebug( \"Application '%s' crashed. No restart!\", qPrintable( mApplication ) );\n }\n } else {\n if ( exitCode != 0 ) {\n qDebug( \"ProcessControl: Application '%s' returned with exit code %d (%s)\",\n qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) );\n#ifdef Q_OS_WINCE\n\t \/\/ If Akonadi server crashed clean the registry key for the local socket.\n\t \/\/ Qt insertes a regitsry key for each local socket opened and checks if a new\n\t \/\/ socket is opened if some other socket is already bind, if a appication\n\t \/\/ crashes the registru key is not deleted and no local socket can be opened\n\t \/\/ so try to delete the key if it fails once\n\t if ( mApplication == \"akonadiserver\" && exitCode == 1) {\n\t HKEY hKey;\n long rc = RegOpenKeyEx (HKEY_CURRENT_USER, TEXT(\"Software\\\\Trolltech\\\\Qt\\\\QLocalServer\"), 0, KEY_ALL_ACCESS, &hKey);\n\t if(rc != ERROR_SUCCESS ) {\n\t qWarning() << mApplication << \"Tried to open HKCU\\\\Software\\\\Trolltech\\\\Qt\\\\QLocalServer to delete Key Akonadi\";\n\t } else {\n\t rc = RegDeleteValue( hKey, TEXT(\"Akonadi\") );\n if(rc != ERROR_SUCCESS ) {\n qWarning() << mApplication << \"Could not delete HKCU\\\\Software\\\\Trolltech\\\\Qt\\\\QLocalServer\\\\Akonadi\";\n\t\t }\n\t }\n\t }\n#endif\n if ( mPolicy == RestartOnCrash ) {\n if ( mCrashCount > s_maxCrashCount ) {\n qWarning() << mApplication << \"crashed too often and will not be restarted!\";\n mPolicy = StopOnCrash;\n emit unableToStart();\n return;\n }\n ++mCrashCount;\n QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) );\n if ( !mFailedToStart ) { \/\/ don't try to start an unstartable application\n start();\n emit restarted();\n }\n }\n } else {\n if ( mRestartOnceOnExit ) {\n mRestartOnceOnExit = false;\n qDebug( \"Restarting application '%s'.\", qPrintable( mApplication ) );\n start();\n } else {\n qDebug( \"Application '%s' exited normally...\", qPrintable( mApplication ) );\n }\n }\n }\n}\n\nvoid ProcessControl::start()\n{\n#ifdef Q_OS_UNIX\n QString agentValgrind = getEnv( \"AKONADI_VALGRIND\" );\n if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) {\n\n mArguments.prepend( mApplication );\n const QString originalArguments = mArguments.join( QString::fromLocal8Bit( \" \" ) );\n mApplication = QString::fromLocal8Bit( \"valgrind\" );\n\n const QString valgrindSkin = getEnv( \"AKONADI_VALGRIND_SKIN\", QString::fromLocal8Bit( \"memcheck\" ) );\n mArguments.prepend( QLatin1String( \"--tool=\" ) + valgrindSkin );\n\n const QString valgrindOptions = getEnv( \"AKONADI_VALGRIND_OPTIONS\" );\n if ( !valgrindOptions.isEmpty() )\n mArguments = valgrindOptions.split( QLatin1Char(' '), QString::SkipEmptyParts ) << mArguments;\n\n qDebug();\n qDebug() << \"============================================================\";\n qDebug() << \"ProcessControl: Valgrinding process\" << originalArguments;\n if ( !valgrindSkin.isEmpty() )\n qDebug() << \"ProcessControl: Valgrind skin:\" << valgrindSkin;\n if ( !valgrindOptions.isEmpty() )\n qDebug() << \"ProcessControl: Additional Valgrind options:\" << valgrindOptions;\n qDebug() << \"============================================================\";\n qDebug();\n }\n#endif\n\n mProcess.start( mApplication, mArguments );\n if ( !mProcess.waitForStarted( ) ) {\n qDebug( \"ProcessControl: Unable to start application '%s' (%s)\",\n qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );\n emit unableToStart();\n return;\n }\n\n#ifdef Q_OS_UNIX\n else {\n QString agentDebug = QString::fromLocal8Bit( qgetenv( \"AKONADI_DEBUG_WAIT\" ) );\n pid_t pid = mProcess.pid();\n if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) {\n qDebug();\n qDebug() << \"============================================================\";\n qDebug() << \"ProcessControl: Suspending process\" << mApplication;\n qDebug() << \"'gdb --pid\" << pid << \"' to debug\";\n qDebug() << \"'kill -SIGCONT\" << pid << \"' to continue\";\n qDebug() << \"============================================================\";\n qDebug();\n kill( pid, SIGSTOP );\n }\n }\n#endif\n}\n\nvoid ProcessControl::resetCrashCount()\n{\n mCrashCount = 0;\n}\n\nbool ProcessControl::isRunning() const\n{\n return mProcess.state() != QProcess::NotRunning;\n}\n\n#include \"processcontrol.moc\"\n<commit_msg>Also match the process arguments when checking for the agent to valgrind.<commit_after>\/***************************************************************************\n * Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (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. See the *\n * GNU 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 program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"processcontrol.h\"\n#include \"akdebug.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QTimer>\n#include <QtDebug>\n\n#ifdef Q_OS_UNIX\n#include <sys\/types.h>\n#include <signal.h>\n#endif\n\n#ifdef Q_OS_WINCE\n#include <windows.h>\n#endif\n\nusing namespace Akonadi;\n\nstatic const int s_maxCrashCount = 2;\n\nProcessControl::ProcessControl( QObject *parent )\n : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ),\n mRestartOnceOnExit( false )\n{\n connect( &mProcess, SIGNAL(error(QProcess::ProcessError)),\n this, SLOT(slotError(QProcess::ProcessError)) );\n connect( &mProcess, SIGNAL(finished(int,QProcess::ExitStatus)),\n this, SLOT(slotFinished(int,QProcess::ExitStatus)) );\n mProcess.setProcessChannelMode( QProcess::ForwardedChannels );\n}\n\nProcessControl::~ProcessControl()\n{\n stop();\n}\n\nvoid ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy )\n{\n mFailedToStart = false;\n\n mApplication = application;\n mArguments = arguments;\n mPolicy = policy;\n\n start();\n}\n\nvoid ProcessControl::setCrashPolicy( CrashPolicy policy )\n{\n mPolicy = policy;\n}\n\nvoid ProcessControl::stop()\n{\n if ( mProcess.state() != QProcess::NotRunning ) {\n mProcess.waitForFinished( 10000 );\n mProcess.terminate();\n }\n}\n\nvoid ProcessControl::slotError( QProcess::ProcessError error )\n{\n switch ( error ) {\n case QProcess::Crashed:\n mCrashCount++;\n \/\/ do nothing, we'll respawn in slotFinished\n break;\n case QProcess::FailedToStart:\n default:\n mFailedToStart = true;\n break;\n }\n\n qDebug( \"ProcessControl: Application '%s' stopped unexpectedly (%s)\",\n qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );\n}\n\nvoid ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus )\n{\n if ( exitStatus == QProcess::CrashExit ) {\n if ( mPolicy == RestartOnCrash ) {\n \/\/ don't try to start an unstartable application\n if ( !mFailedToStart && mCrashCount <= s_maxCrashCount ) {\n qDebug( \"Application '%s' crashed! %d restarts left.\", qPrintable( mApplication ), s_maxCrashCount - mCrashCount );\n start();\n emit restarted();\n } else {\n if ( mFailedToStart ) {\n qDebug( \"Application '%s' failed to start!\", qPrintable( mApplication ) );\n } else {\n qDebug( \"Application '%s' crashed too often. Giving up!\", qPrintable( mApplication ) );\n }\n mPolicy = StopOnCrash;\n emit unableToStart();\n return;\n }\n } else {\n qDebug( \"Application '%s' crashed. No restart!\", qPrintable( mApplication ) );\n }\n } else {\n if ( exitCode != 0 ) {\n qDebug( \"ProcessControl: Application '%s' returned with exit code %d (%s)\",\n qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) );\n#ifdef Q_OS_WINCE\n\t \/\/ If Akonadi server crashed clean the registry key for the local socket.\n\t \/\/ Qt insertes a regitsry key for each local socket opened and checks if a new\n\t \/\/ socket is opened if some other socket is already bind, if a appication\n\t \/\/ crashes the registru key is not deleted and no local socket can be opened\n\t \/\/ so try to delete the key if it fails once\n\t if ( mApplication == \"akonadiserver\" && exitCode == 1) {\n\t HKEY hKey;\n long rc = RegOpenKeyEx (HKEY_CURRENT_USER, TEXT(\"Software\\\\Trolltech\\\\Qt\\\\QLocalServer\"), 0, KEY_ALL_ACCESS, &hKey);\n\t if(rc != ERROR_SUCCESS ) {\n\t qWarning() << mApplication << \"Tried to open HKCU\\\\Software\\\\Trolltech\\\\Qt\\\\QLocalServer to delete Key Akonadi\";\n\t } else {\n\t rc = RegDeleteValue( hKey, TEXT(\"Akonadi\") );\n if(rc != ERROR_SUCCESS ) {\n qWarning() << mApplication << \"Could not delete HKCU\\\\Software\\\\Trolltech\\\\Qt\\\\QLocalServer\\\\Akonadi\";\n\t\t }\n\t }\n\t }\n#endif\n if ( mPolicy == RestartOnCrash ) {\n if ( mCrashCount > s_maxCrashCount ) {\n qWarning() << mApplication << \"crashed too often and will not be restarted!\";\n mPolicy = StopOnCrash;\n emit unableToStart();\n return;\n }\n ++mCrashCount;\n QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) );\n if ( !mFailedToStart ) { \/\/ don't try to start an unstartable application\n start();\n emit restarted();\n }\n }\n } else {\n if ( mRestartOnceOnExit ) {\n mRestartOnceOnExit = false;\n qDebug( \"Restarting application '%s'.\", qPrintable( mApplication ) );\n start();\n } else {\n qDebug( \"Application '%s' exited normally...\", qPrintable( mApplication ) );\n }\n }\n }\n}\n\nstatic bool listContains( const QStringList &list, const QString &pattern )\n{\n foreach ( const QString &s, list ) {\n if ( s.contains( pattern ) )\n return true;\n }\n return false;\n}\n\nvoid ProcessControl::start()\n{\n#ifdef Q_OS_UNIX\n QString agentValgrind = getEnv( \"AKONADI_VALGRIND\" );\n if ( !agentValgrind.isEmpty() && (mApplication.contains( agentValgrind ) || listContains( mArguments, agentValgrind )) ) {\n\n mArguments.prepend( mApplication );\n const QString originalArguments = mArguments.join( QString::fromLocal8Bit( \" \" ) );\n mApplication = QString::fromLocal8Bit( \"valgrind\" );\n\n const QString valgrindSkin = getEnv( \"AKONADI_VALGRIND_SKIN\", QString::fromLocal8Bit( \"memcheck\" ) );\n mArguments.prepend( QLatin1String( \"--tool=\" ) + valgrindSkin );\n\n const QString valgrindOptions = getEnv( \"AKONADI_VALGRIND_OPTIONS\" );\n if ( !valgrindOptions.isEmpty() )\n mArguments = valgrindOptions.split( QLatin1Char(' '), QString::SkipEmptyParts ) << mArguments;\n\n qDebug();\n qDebug() << \"============================================================\";\n qDebug() << \"ProcessControl: Valgrinding process\" << originalArguments;\n if ( !valgrindSkin.isEmpty() )\n qDebug() << \"ProcessControl: Valgrind skin:\" << valgrindSkin;\n if ( !valgrindOptions.isEmpty() )\n qDebug() << \"ProcessControl: Additional Valgrind options:\" << valgrindOptions;\n qDebug() << \"============================================================\";\n qDebug();\n }\n#endif\n\n mProcess.start( mApplication, mArguments );\n if ( !mProcess.waitForStarted( ) ) {\n qDebug( \"ProcessControl: Unable to start application '%s' (%s)\",\n qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );\n emit unableToStart();\n return;\n }\n\n#ifdef Q_OS_UNIX\n else {\n QString agentDebug = QString::fromLocal8Bit( qgetenv( \"AKONADI_DEBUG_WAIT\" ) );\n pid_t pid = mProcess.pid();\n if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) {\n qDebug();\n qDebug() << \"============================================================\";\n qDebug() << \"ProcessControl: Suspending process\" << mApplication;\n qDebug() << \"'gdb --pid\" << pid << \"' to debug\";\n qDebug() << \"'kill -SIGCONT\" << pid << \"' to continue\";\n qDebug() << \"============================================================\";\n qDebug();\n kill( pid, SIGSTOP );\n }\n }\n#endif\n}\n\nvoid ProcessControl::resetCrashCount()\n{\n mCrashCount = 0;\n}\n\nbool ProcessControl::isRunning() const\n{\n return mProcess.state() != QProcess::NotRunning;\n}\n\n#include \"processcontrol.moc\"\n<|endoftext|>"} {"text":"<commit_before>#ifndef GF2_DEPTHIO_HPP\n#define GF2_DEPTHIO_HPP\n\n#include <string>\n#include <opencv2\/core.hpp>\n#include <opencv2\/imgproc.hpp>\n#include <opencv2\/highgui.hpp>\n#include \"Eigen\/Dense\"\n\nnamespace GF2 {\nnamespace io {\n\n\/*! \\brief Load a depth image stored as a .dat file.\n * Assumes, that first two int entries are height and width (in this order).\n * \\tparam FilePixelT The scalar format of the data file Concept: float.\n * \\tparam MatPixelT The output format of cv::Mat. Concept: ushort.\n * \\param[out] mat Output opencv matrix.\n * \\param[in] path File path to read from.\n * \\param[in] alpha Multiplier to apply to each read pixel.\n*\/\ntemplate <typename MatPixelT, typename FilePixelT> inline int\nloadDepthAsBinary( ::cv::Mat &mat, std::string path, float alpha = 1.f )\n{\n FILE *fp = fopen( path.c_str(), \"rb\" );\n if (!fp)\n {\n printf( \"loadDepthAsBinary failed, when opening %s\\n\", path.c_str() );\n return false;\n }\n\n int w,h, read_size = 0;\n read_size += fread( &h,sizeof(int),1,fp );\n read_size += fread( &w,sizeof(int),1,fp );\n if ( read_size != 2 )\n {\n std::cerr << \"[\" << __func__ << \"]: \" << \"w or h not read properly: \" << w << \", \" << h << std::endl;\n }\n\n FilePixelT *p_depth = new FilePixelT[ h * w ];\n\n read_size = fread( p_depth, sizeof(FilePixelT), w*h, fp );\n if ( read_size != w*h )\n std::cerr << \"[\" << __func__ << \"]: \" << \"read size != \" << w*h << std::endl;\n\n mat.create( h, w, CV_16UC1 );\n int p_depth_index = 0;\n for ( unsigned y = 0; y < mat.rows; ++y )\n {\n for ( unsigned x = 0; x < mat.cols; ++x, ++p_depth_index )\n {\n mat.at<MatPixelT>(y,x) = p_depth[ p_depth_index ] * alpha;\n }\n }\n\n fclose( fp );\n if ( p_depth )\n delete [] p_depth;\n\n return EXIT_SUCCESS;\n} \/\/...loadDepthAsBinary()\n\n\/*! \\brief Loads a raw, dat or png depth map, and outputs [mm] values.\n *\n * \\param[in] depth_path File path to read depth map from.\n * \\return OpenCV 2D matrix with ushort depth values in [mm].\n *\/\ncv::Mat\nloadDepth( std::string depth_path )\n{\n cv::Mat dep;\n if ( depth_path.find(\"raw\") != std::string::npos )\n {\n loadDepthAsBinary<ushort,ushort>( dep, depth_path, 1. );\n }\n else if ( depth_path.find(\"dat\") != std::string::npos )\n {\n \/\/ NYU, read float, and convert it to ushort\n loadDepthAsBinary<ushort,float>( dep, depth_path, 1000. );\n }\n else\n {\n dep = cv::imread( depth_path, cv::IMREAD_UNCHANGED );\n }\n\n return dep;\n} \/\/...loadDepth()\n\n\/\/ Aron's kinect calibration\n#define FX_D 588.486898\n#define FY_D 588.729416\n#define CX_D 314.509516\n#define CY_D 242.997237\n#define K1_D -0.094563\n#define K2_D 0.387595\n#define P1_D 0.000838\n#define P2_D 0.001505\n#define K3_D -0.494912\n#define ALPHA_D -0.002096\n\ntemplate <typename _Scalar>\nstruct Intrinsics\n{\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n typedef _Scalar Scalar;\n enum CALIB_ID { TIANJIAS, ARONS, \/*ARONS_WDISTORTION,*\/ RGBDEMOS };\n\n inline Intrinsics( CALIB_ID calib_id = ARONS )\n {\n switch ( calib_id )\n {\n case ARONS:\n _intrinsics << FX_D, 0., CX_D,\n 0., FY_D, CY_D,\n 0., 0., 1.;\n break;\n case TIANJIAS:\n _intrinsics << 5.1930334103339817e+02, 0., 3.2850951551345941e+02,\n 0., 5.1816401430246583e+02, 2.5282555217253503e+02,\n 0., 0., 1.;\n break;\n case RGBDEMOS:\n _intrinsics << 5.4013644168716110e+02, 0., 320.,\n 0., 5.4013644168716110e+02, 240.,\n 0., 0., 1.;\n break;\n }\n }\n\n inline Intrinsics( Scalar fx, Scalar fy, Scalar cx, Scalar cy )\n : _intrinsics( (Eigen::Matrix<Scalar,3,3>() <<\n fx, 0., cx,\n 0., fy, cy,\n 0., 0., 1.).finished() ) {}\n operator Eigen::Matrix<_Scalar,3,3>() { return _intrinsics; }\n protected:\n Eigen::Matrix<Scalar,3,3> _intrinsics;\n};\n\ntemplate <typename _Scalar> inline Eigen::Matrix<_Scalar,3,1>\npoint2To3D( Eigen::Matrix<_Scalar,2,1> const& pnt2, Eigen::Matrix<_Scalar,3,3> const& intrinsics )\n{\n return (Eigen::Matrix<_Scalar,3,1>() << (pnt2(0) - intrinsics(0,2)) \/ intrinsics(0,0), \/\/ (x - cx) \/ fx\n (pnt2(1) - intrinsics(1,2)) \/ intrinsics(1,1), \/\/ (y - cy) \/ fy\n 1.f ).finished();\n}\n\n\/*! \\brief Decides, if a depth map pixel is a valid 3D point.\n * \\return true, if depth > 20cm. (> 0.2)\n *\/\ntemplate <typename _Scalar>\ninline bool isValidDepth( _Scalar d )\n{\n if ( d > _Scalar(10.) ) std::cerr << \"[\" << __func__ << \"]: \" << \"Depth values are assumed to be between 0..10, and not \" << d << std::endl;\n\n return d > _Scalar(.2);\n}\n\n\/*! \\brief Merges a depth image and an optional rgb image to a point cloud.\n *\/\ntemplate <typename depT, typename _Scalar, typename _PclCloudT>\ninline int rgbd2PointCloud( _PclCloudT & pcl_cloud\n , cv::Mat const& dep\n , cv::Mat const& img\n , _Scalar const alpha = 1. \/ 1000.\n , Eigen::Matrix<_Scalar,3,3> const& intrinsics = Intrinsics<_Scalar>()\n , Eigen::Transform<_Scalar,3,Eigen::Affine> const* pose = NULL\n )\n{\n typedef Eigen::Matrix<_Scalar,3,1> Position;\n typedef typename _PclCloudT::PointType PclPointT;\n \/\/typedef typename _PointContainerT::value_type PointPrimitiveT;\n\n \/\/ check inputs to be the same size\n if ( !img.empty() )\n {\n if ( dep.size() != img.size() )\n {\n std::cerr << \"matsTo3D(): dep and rgb need the same size! \"\n << dep.rows << \"x\" << dep.cols << \", \"\n << img.rows << \"x\" << img.cols << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n \/\/ check image dimensions\n if ( (!img.empty()) && (img.channels() != 3) )\n {\n std::cerr << \"matsTo3D(): rgb should be 3 channels! \" << img.channels() << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ allocate ouptut\n \/\/points = PCloud::Ptr( new PCloud );\n\/\/ pcl_cloud.clear();\n\/\/ pcl_cloud.reserve( img.cols * img.rows );\n\n \/\/ point to read to, and insert\n Position pnt3D;\n uint32_t rgb = 128 << 16 | 128 << 8 | 128;\n\n Eigen::Matrix<_Scalar,3,3> rotation;\n Eigen::Matrix<_Scalar,3,1> translation;\n if ( pose )\n {\n rotation = pose->rotation();\n translation = pose->translation();\n }\n\n \/\/ copy inputs\n for ( int y = 0; y < dep.rows; ++y )\n {\n for ( int x = 0; x < dep.cols; ++x )\n {\n \/\/ read depth\n float depth = (_Scalar)dep.at<depT>( y,x ) * alpha;\n \/\/ check validity\n bool isValid = isValidDepth( depth );\n if ( !isValid )\n continue;\n\n \/\/ calculate point\n pnt3D = point2To3D( (Eigen::Matrix<_Scalar,2,1>() << x,y).finished(), intrinsics ) * depth;\n\n \/\/ apply pose\n if ( pose )\n pnt3D = rotation * pnt3D + translation;\n\n#if 0\n pcl_cloud.push_back( PointPrimitiveT( \/* pos: *\/ pnt3D, \/* dir: *\/ (Position()<<1.,1.,1.).finished()) );\n#else\n \/\/ convert\n PclPointT point;\n point.x = pnt3D( 0 );\n point.y = pnt3D( 1 );\n point.z = pnt3D( 2 );\n\n \/\/ add colour\n if ( !img.empty() )\n {\n rgb = (static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() + 2)) << 16 |\n static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() + 1)) << 8 |\n static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() )) );\n }\n point.rgb = *reinterpret_cast<float*>( &rgb );\n\n \/\/ add point\n pcl_cloud.push_back( point );\n#endif\n }\n }\n\n \/\/points->width = (int)points->points.size ();\n \/\/points->height = 1;\n\n return EXIT_SUCCESS;\n\n} \/\/ matsTo3D\n\n} \/\/...ns io\n} \/\/...ns GF2\n\n#endif \/\/ GF2_DEPTHIO_HPP\n<commit_msg>Fix wrong includes<commit_after>#ifndef GF2_DEPTHIO_HPP\n#define GF2_DEPTHIO_HPP\n\n#include <string>\n#include <opencv2\/core.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include \"Eigen\/Dense\"\n\nnamespace GF2 {\nnamespace io {\n\n\/*! \\brief Load a depth image stored as a .dat file.\n * Assumes, that first two int entries are height and width (in this order).\n * \\tparam FilePixelT The scalar format of the data file Concept: float.\n * \\tparam MatPixelT The output format of cv::Mat. Concept: ushort.\n * \\param[out] mat Output opencv matrix.\n * \\param[in] path File path to read from.\n * \\param[in] alpha Multiplier to apply to each read pixel.\n*\/\ntemplate <typename MatPixelT, typename FilePixelT> inline int\nloadDepthAsBinary( ::cv::Mat &mat, std::string path, float alpha = 1.f )\n{\n FILE *fp = fopen( path.c_str(), \"rb\" );\n if (!fp)\n {\n printf( \"loadDepthAsBinary failed, when opening %s\\n\", path.c_str() );\n return false;\n }\n\n int w,h, read_size = 0;\n read_size += fread( &h,sizeof(int),1,fp );\n read_size += fread( &w,sizeof(int),1,fp );\n if ( read_size != 2 )\n {\n std::cerr << \"[\" << __func__ << \"]: \" << \"w or h not read properly: \" << w << \", \" << h << std::endl;\n }\n\n FilePixelT *p_depth = new FilePixelT[ h * w ];\n\n read_size = fread( p_depth, sizeof(FilePixelT), w*h, fp );\n if ( read_size != w*h )\n std::cerr << \"[\" << __func__ << \"]: \" << \"read size != \" << w*h << std::endl;\n\n mat.create( h, w, CV_16UC1 );\n int p_depth_index = 0;\n for ( unsigned y = 0; y < mat.rows; ++y )\n {\n for ( unsigned x = 0; x < mat.cols; ++x, ++p_depth_index )\n {\n mat.at<MatPixelT>(y,x) = p_depth[ p_depth_index ] * alpha;\n }\n }\n\n fclose( fp );\n if ( p_depth )\n delete [] p_depth;\n\n return EXIT_SUCCESS;\n} \/\/...loadDepthAsBinary()\n\n\/*! \\brief Loads a raw, dat or png depth map, and outputs [mm] values.\n *\n * \\param[in] depth_path File path to read depth map from.\n * \\return OpenCV 2D matrix with ushort depth values in [mm].\n *\/\ncv::Mat\nloadDepth( std::string depth_path )\n{\n cv::Mat dep;\n if ( depth_path.find(\"raw\") != std::string::npos )\n {\n loadDepthAsBinary<ushort,ushort>( dep, depth_path, 1. );\n }\n else if ( depth_path.find(\"dat\") != std::string::npos )\n {\n \/\/ NYU, read float, and convert it to ushort\n loadDepthAsBinary<ushort,float>( dep, depth_path, 1000. );\n }\n else\n {\n dep = cv::imread( depth_path, cv::IMREAD_UNCHANGED );\n }\n\n return dep;\n} \/\/...loadDepth()\n\n\/\/ Aron's kinect calibration\n#define FX_D 588.486898\n#define FY_D 588.729416\n#define CX_D 314.509516\n#define CY_D 242.997237\n#define K1_D -0.094563\n#define K2_D 0.387595\n#define P1_D 0.000838\n#define P2_D 0.001505\n#define K3_D -0.494912\n#define ALPHA_D -0.002096\n\ntemplate <typename _Scalar>\nstruct Intrinsics\n{\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n typedef _Scalar Scalar;\n enum CALIB_ID { TIANJIAS, ARONS, \/*ARONS_WDISTORTION,*\/ RGBDEMOS };\n\n inline Intrinsics( CALIB_ID calib_id = ARONS )\n {\n switch ( calib_id )\n {\n case ARONS:\n _intrinsics << FX_D, 0., CX_D,\n 0., FY_D, CY_D,\n 0., 0., 1.;\n break;\n case TIANJIAS:\n _intrinsics << 5.1930334103339817e+02, 0., 3.2850951551345941e+02,\n 0., 5.1816401430246583e+02, 2.5282555217253503e+02,\n 0., 0., 1.;\n break;\n case RGBDEMOS:\n _intrinsics << 5.4013644168716110e+02, 0., 320.,\n 0., 5.4013644168716110e+02, 240.,\n 0., 0., 1.;\n break;\n }\n }\n\n inline Intrinsics( Scalar fx, Scalar fy, Scalar cx, Scalar cy )\n : _intrinsics( (Eigen::Matrix<Scalar,3,3>() <<\n fx, 0., cx,\n 0., fy, cy,\n 0., 0., 1.).finished() ) {}\n operator Eigen::Matrix<_Scalar,3,3>() { return _intrinsics; }\n protected:\n Eigen::Matrix<Scalar,3,3> _intrinsics;\n};\n\ntemplate <typename _Scalar> inline Eigen::Matrix<_Scalar,3,1>\npoint2To3D( Eigen::Matrix<_Scalar,2,1> const& pnt2, Eigen::Matrix<_Scalar,3,3> const& intrinsics )\n{\n return (Eigen::Matrix<_Scalar,3,1>() << (pnt2(0) - intrinsics(0,2)) \/ intrinsics(0,0), \/\/ (x - cx) \/ fx\n (pnt2(1) - intrinsics(1,2)) \/ intrinsics(1,1), \/\/ (y - cy) \/ fy\n 1.f ).finished();\n}\n\n\/*! \\brief Decides, if a depth map pixel is a valid 3D point.\n * \\return true, if depth > 20cm. (> 0.2)\n *\/\ntemplate <typename _Scalar>\ninline bool isValidDepth( _Scalar d )\n{\n if ( d > _Scalar(10.) ) std::cerr << \"[\" << __func__ << \"]: \" << \"Depth values are assumed to be between 0..10, and not \" << d << std::endl;\n\n return d > _Scalar(.2);\n}\n\n\/*! \\brief Merges a depth image and an optional rgb image to a point cloud.\n *\/\ntemplate <typename depT, typename _Scalar, typename _PclCloudT>\ninline int rgbd2PointCloud( _PclCloudT & pcl_cloud\n , cv::Mat const& dep\n , cv::Mat const& img\n , _Scalar const alpha = 1. \/ 1000.\n , Eigen::Matrix<_Scalar,3,3> const& intrinsics = Intrinsics<_Scalar>()\n , Eigen::Transform<_Scalar,3,Eigen::Affine> const* pose = NULL\n )\n{\n typedef Eigen::Matrix<_Scalar,3,1> Position;\n typedef typename _PclCloudT::PointType PclPointT;\n \/\/typedef typename _PointContainerT::value_type PointPrimitiveT;\n\n \/\/ check inputs to be the same size\n if ( !img.empty() )\n {\n if ( dep.size() != img.size() )\n {\n std::cerr << \"matsTo3D(): dep and rgb need the same size! \"\n << dep.rows << \"x\" << dep.cols << \", \"\n << img.rows << \"x\" << img.cols << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n \/\/ check image dimensions\n if ( (!img.empty()) && (img.channels() != 3) )\n {\n std::cerr << \"matsTo3D(): rgb should be 3 channels! \" << img.channels() << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ allocate ouptut\n \/\/points = PCloud::Ptr( new PCloud );\n\/\/ pcl_cloud.clear();\n\/\/ pcl_cloud.reserve( img.cols * img.rows );\n\n \/\/ point to read to, and insert\n Position pnt3D;\n uint32_t rgb = 128 << 16 | 128 << 8 | 128;\n\n Eigen::Matrix<_Scalar,3,3> rotation;\n Eigen::Matrix<_Scalar,3,1> translation;\n if ( pose )\n {\n rotation = pose->rotation();\n translation = pose->translation();\n }\n\n \/\/ copy inputs\n for ( int y = 0; y < dep.rows; ++y )\n {\n for ( int x = 0; x < dep.cols; ++x )\n {\n \/\/ read depth\n float depth = (_Scalar)dep.at<depT>( y,x ) * alpha;\n \/\/ check validity\n bool isValid = isValidDepth( depth );\n if ( !isValid )\n continue;\n\n \/\/ calculate point\n pnt3D = point2To3D( (Eigen::Matrix<_Scalar,2,1>() << x,y).finished(), intrinsics ) * depth;\n\n \/\/ apply pose\n if ( pose )\n pnt3D = rotation * pnt3D + translation;\n\n#if 0\n pcl_cloud.push_back( PointPrimitiveT( \/* pos: *\/ pnt3D, \/* dir: *\/ (Position()<<1.,1.,1.).finished()) );\n#else\n \/\/ convert\n PclPointT point;\n point.x = pnt3D( 0 );\n point.y = pnt3D( 1 );\n point.z = pnt3D( 2 );\n\n \/\/ add colour\n if ( !img.empty() )\n {\n rgb = (static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() + 2)) << 16 |\n static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() + 1)) << 8 |\n static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() )) );\n }\n point.rgb = *reinterpret_cast<float*>( &rgb );\n\n \/\/ add point\n pcl_cloud.push_back( point );\n#endif\n }\n }\n\n \/\/points->width = (int)points->points.size ();\n \/\/points->height = 1;\n\n return EXIT_SUCCESS;\n\n} \/\/ matsTo3D\n\n} \/\/...ns io\n} \/\/...ns GF2\n\n#endif \/\/ GF2_DEPTHIO_HPP\n<|endoftext|>"} {"text":"<commit_before>#include<bits\/stdc++.h>\nusing namespace std;\nint main(){\n\t\/\/freopen(\"1.in\",\"r\",stdin);\n\t\/\/freopen(\"1.out\",\"w\",stdout);\n int n=10;\/\/n 是人數\n while(cin>>n){\n int num[55]={1},list[55]={0};\/\/num 是紀錄用 \/\/list 為死亡順序 index 從一開始\n\t\tint j=0,number=0,s=0,t;\/\/number 是死亡人數,j 為報數用\n\t\tfor (int i=1;i<=n;i++)num[i]=1;\/\/重置狀態 1 為活者\n t=n;\n\t\twhile (number<n){\n for (int i=1;i<=n;i++){\n if (num[i]==1){\n j++;\n if (j==2){\/\/滿足自殺報數\n num[i]=0;\n\t\t\t\t\t\tlist[++s]=i; \n j=0;\n number++;\n }\n }\n }\n }\n\t\tcout<<list[t]<<endl;\n }\n}\n<commit_msg>Update 1004.cpp<commit_after>#include<bits\/stdc++.h>\nusing namespace std;\nint main(){\n\t\/\/freopen(\"1.in\",\"r\",stdin);\n\t\/\/freopen(\"1.out\",\"w\",stdout);\n int n=10;\/\/n 是人數\n while(cin>>n){\n int num[55]={1},list[55]={0};\/\/num 是紀錄用 \/\/list 為死亡順序 index 從一開始\n\tint j=0,number=0,s=0,t;\/\/number 是死亡人數,j 為報數用\n\tfor (int i=1;i<=n;i++)num[i]=1;\/\/重置狀態 1 為活者\n t=n;\n\twhile (number<n){\n for (int i=1;i<=n;i++){\n if (num[i]==1){\n j++;\n if (j==2){\/\/滿足自殺報數\n num[i]=0;\n\t\t\tlist[++s]=i; \n j=0;\n number++;\n }\n }\n }\n }\n\tcout<<list[t]<<endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SneezyMUD - All rights reserved, SneezyMUD Coding Team\n\/\/\n\/\/ cmd_rescue.cc\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"stdsneezy.h\"\n\nstatic int rescue(TBeing * caster, TBeing * victim, spellNumT skill)\n{\n TBeing *tmp_ch = NULL;\n int percent = 0;\n\n if (caster->getCombatMode() == ATTACK_BERSERK) {\n caster->sendTo(\"You are berserking! You can't focus enough to rescue anyone!\\n\\r\");\n return FALSE;\n }\n \n if (caster->checkPeaceful(\"No one should need rescuing here.\\n\\r\"))\n return FALSE;\n\n if (victim == caster) {\n caster->sendTo(\"What about fleeing instead?\\n\\r\");\n return FALSE;\n }\n if (dynamic_cast<TBeing *>(victim->riding)) {\n caster->sendTo(\"You can't rescue a mounted person!\\n\\r\");\n return FALSE;\n }\n if (victim->riding) {\n caster->sendTo(COLOR_MOBS, fmt(\"You can't rescue %s off of %s!\\n\\r\") % \n victim->getName() % victim->riding->getName());\n return FALSE;\n }\n if (!victim->isPc() && !victim->isPet(PETTYPE_PET | PETTYPE_CHARM | PETTYPE_THRALL)) {\n caster->sendTo(\"You can only rescue PCs or pets.\\n\\r\");\n return FALSE;\n }\n\n if (caster->fight() == victim) {\n caster->sendTo(\"How can you rescue someone you are trying to kill?\\n\\r\");\n return FALSE;\n }\n#if 0\n if (!caster->inGroup(*victim)) {\n act(\"You need to be a part of $S group to rescue $N.\", \n FALSE, caster, 0, victim, TO_CHAR);\n return FALSE;\n }\n#endif\n \n TThing *t;\n for (t = victim->roomp->getStuff(); t; t = t->nextThing, tmp_ch = NULL) {\n tmp_ch = dynamic_cast<TBeing *>(t);\n if (!tmp_ch)\n continue;\n if (tmp_ch->fight() == victim)\n break;\n }\n\n if (!tmp_ch) {\n act(\"But nobody is fighting $M?\", FALSE, caster, 0, victim, TO_CHAR);\n return FALSE;\n }\n\n \/\/ int level = caster->getSkillLevel(skill);\n int bKnown = caster->getSkillValue(skill);\n\n if (bSuccess(caster, bKnown + percent, skill)) {\n caster->sendTo(\"Banzai! To the rescue...\\n\\r\");\n act(\"You are rescued by $N, you are confused!\",\n FALSE, victim, 0, caster, TO_CHAR);\n act(\"$n heroically rescues $N.\", FALSE, caster, 0, victim, TO_NOTVICT);\n\n if (victim->fight() == tmp_ch)\n victim->stopFighting();\n if (tmp_ch->fight())\n tmp_ch->stopFighting();\n if (caster->fight())\n caster->stopFighting();\n\n caster->setCharFighting(tmp_ch);\n caster->setVictFighting(tmp_ch);\n\n victim->addToWait(combatRound(1));\n\n if (tmp_ch->GetMaxLevel() >= victim->GetMaxLevel()) {\n if (caster->getFactionTarget() != victim) {\n caster->reconcileHelp(victim, discArray[skill]->alignMod);\n caster->setFactionTarget(victim);\n } else {\n \/\/ rescuing over and over, or rescuing back and forth\n \/\/ let it help some but not as much\n caster->reconcileHelp(victim, discArray[skill]->alignMod\/4.0);\n }\n }\n return TRUE;\n } else {\n caster->sendTo(\"You fail the rescue.\\n\\r\");\n act(\"$n attempts to rescue you, but fails miserably.\",\n FALSE, caster, 0, victim, TO_VICT);\n act(\"$n attempts to rescue $N, but fails miserably.\",\n FALSE, caster, 0, victim, TO_NOTVICT);\n\n \/\/ start them fighting at least\n if (!caster->fight())\n caster->setCharFighting(tmp_ch);\n }\n return TRUE;\n}\n\nint TBeing::doRescue(const char *argument)\n{\n int rc;\n TBeing *victim;\n char name_buf[240];\n\n spellNumT skill = getSkillNum(SKILL_RESCUE);\n\n if (checkBusy())\n return FALSE;\n\n if (!doesKnowSkill(skill)) {\n sendTo(\"You know nothing about rescuing.\\n\\r\");\n return FALSE;\n }\n\n \/\/ Default to the first PC group member who is currently tanking, or the first mobile group member if no PC is.\n if (isAffected(AFF_GROUP) && (!argument || !*argument) && (followers || (master && master->followers))) {\n followData * tFData = (master ? master->followers : followers);\n TBeing * tRescueMe = NULL,\n * tMaybeMe = NULL;\n\n for (; tFData; tFData = tFData->next)\n if (tFData->follower && tFData->follower->isAffected(AFF_GROUP) && canSee(tFData->follower) && tFData->follower->fight() && (tFData->follower->fight()->fight() == tFData->follower) && (tFData->follower != this)) {\n if (tFData->follower->isPc()) {\n tRescueMe = tFData->follower;\n break;\n } else if (!tMaybeMe)\n tMaybeMe = tFData->follower;\n }\n\n if (!tRescueMe && tMaybeMe)\n tRescueMe = tMaybeMe;\n\n if (tRescueMe) {\n strcpy(name_buf, tRescueMe->name);\n\n while (strchr(name_buf, ' '))\n *strchr(name_buf, ' ') = '-';\n }\n } else\n strcpy(name_buf, argument);\n\n if (!(victim = get_char_room_vis(this, name_buf))) {\n sendTo(\"Whom do you want to rescue?\\n\\r\");\n return FALSE;\n }\n if (!sameRoom(*victim)) {\n sendTo(\"That person isn't around.\\n\\r\");\n return FALSE;\n }\n rc = rescue(this, victim, skill);\n if (rc)\n addSkillLag(skill, rc);\n if (IS_SET_DELETE(rc, DELETE_THIS))\n return DELETE_THIS;\n\n return rc;\n}\n\n<commit_msg>Modified the rescue code some more to pass the TBeing of the rescue target instead of the name of. Also changed it slighly so it can also be used to save the 'master' of the rescuer.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SneezyMUD - All rights reserved, SneezyMUD Coding Team\n\/\/\n\/\/ cmd_rescue.cc\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"stdsneezy.h\"\n\nstatic int rescue(TBeing * caster, TBeing * victim, spellNumT skill)\n{\n TBeing *tmp_ch = NULL;\n int percent = 0;\n\n if (caster->getCombatMode() == ATTACK_BERSERK) {\n caster->sendTo(\"You are berserking! You can't focus enough to rescue anyone!\\n\\r\");\n return FALSE;\n }\n \n if (caster->checkPeaceful(\"No one should need rescuing here.\\n\\r\"))\n return FALSE;\n\n if (victim == caster) {\n caster->sendTo(\"What about fleeing instead?\\n\\r\");\n return FALSE;\n }\n if (dynamic_cast<TBeing *>(victim->riding)) {\n caster->sendTo(\"You can't rescue a mounted person!\\n\\r\");\n return FALSE;\n }\n if (victim->riding) {\n caster->sendTo(COLOR_MOBS, fmt(\"You can't rescue %s off of %s!\\n\\r\") % \n victim->getName() % victim->riding->getName());\n return FALSE;\n }\n if (!victim->isPc() && !victim->isPet(PETTYPE_PET | PETTYPE_CHARM | PETTYPE_THRALL)) {\n caster->sendTo(\"You can only rescue PCs or pets.\\n\\r\");\n return FALSE;\n }\n\n if (caster->fight() == victim) {\n caster->sendTo(\"How can you rescue someone you are trying to kill?\\n\\r\");\n return FALSE;\n }\n#if 0\n if (!caster->inGroup(*victim)) {\n act(\"You need to be a part of $S group to rescue $N.\", \n FALSE, caster, 0, victim, TO_CHAR);\n return FALSE;\n }\n#endif\n \n TThing *t;\n for (t = victim->roomp->getStuff(); t; t = t->nextThing, tmp_ch = NULL) {\n tmp_ch = dynamic_cast<TBeing *>(t);\n if (!tmp_ch)\n continue;\n if (tmp_ch->fight() == victim)\n break;\n }\n\n if (!tmp_ch) {\n act(\"But nobody is fighting $M?\", FALSE, caster, 0, victim, TO_CHAR);\n return FALSE;\n }\n\n \/\/ int level = caster->getSkillLevel(skill);\n int bKnown = caster->getSkillValue(skill);\n\n if (bSuccess(caster, bKnown + percent, skill)) {\n caster->sendTo(\"Banzai! To the rescue...\\n\\r\");\n act(\"You are rescued by $N, you are confused!\",\n FALSE, victim, 0, caster, TO_CHAR);\n act(\"$n heroically rescues $N.\", FALSE, caster, 0, victim, TO_NOTVICT);\n\n if (victim->fight() == tmp_ch)\n victim->stopFighting();\n if (tmp_ch->fight())\n tmp_ch->stopFighting();\n if (caster->fight())\n caster->stopFighting();\n\n caster->setCharFighting(tmp_ch);\n caster->setVictFighting(tmp_ch);\n\n victim->addToWait(combatRound(1));\n\n if (tmp_ch->GetMaxLevel() >= victim->GetMaxLevel()) {\n if (caster->getFactionTarget() != victim) {\n caster->reconcileHelp(victim, discArray[skill]->alignMod);\n caster->setFactionTarget(victim);\n } else {\n \/\/ rescuing over and over, or rescuing back and forth\n \/\/ let it help some but not as much\n caster->reconcileHelp(victim, discArray[skill]->alignMod\/4.0);\n }\n }\n return TRUE;\n } else {\n caster->sendTo(\"You fail the rescue.\\n\\r\");\n act(\"$n attempts to rescue you, but fails miserably.\",\n FALSE, caster, 0, victim, TO_VICT);\n act(\"$n attempts to rescue $N, but fails miserably.\",\n FALSE, caster, 0, victim, TO_NOTVICT);\n\n \/\/ start them fighting at least\n if (!caster->fight())\n caster->setCharFighting(tmp_ch);\n }\n return TRUE;\n}\n\nint TBeing::doRescue(const char *argument)\n{\n int rc;\n TBeing *victim = NULL;\n char name_buf[240];\n\n spellNumT skill = getSkillNum(SKILL_RESCUE);\n\n if (checkBusy())\n return FALSE;\n\n if (!doesKnowSkill(skill)) {\n sendTo(\"You know nothing about rescuing.\\n\\r\");\n return FALSE;\n }\n\n \/\/ Default to the first PC group member who is currently tanking, or the first mobile group member if no PC is.\n if (isAffected(AFF_GROUP) && (!argument || !*argument) && (followers || (master && master->followers))) {\n followData * tFData = (master ? master->followers : followers);\n TBeing * tRescueMe = NULL,\n * tMaybeMe = NULL;\n\n if (master && master->isAffected(AFF_GROUP) && sameRoom(*master) && canSee(master) && master->fight() && (master->fight()->fight() == master))\n tRescueMe = master;\n else\n for (; tFData; tFData = tFData->next)\n if (tFData->follower && tFData->follower->isAffected(AFF_GROUP) && canSee(tFData->follower) && tFData->follower->fight() && (tFData->follower->fight()->fight() == tFData->follower) && (tFData->follower != this) && sameRoom(*tFData->follower)) {\n if (tFData->follower->isPc()) {\n tRescueMe = tFData->follower;\n break;\n } else if (!tMaybeMe)\n tMaybeMe = tFData->follower;\n }\n\n if (!tRescueMe && tMaybeMe)\n tRescueMe = tMaybeMe;\n\n victim = tRescueMe; \/\/ Since this is NULL'ed above we are safe doing this without a check.\n } else\n strcpy(name_buf, argument);\n\n if (!victim)\n if (!(victim = get_char_room_vis(this, name_buf))) {\n sendTo(\"Whom do you want to rescue?\\n\\r\");\n return FALSE;\n }\n\n if (!sameRoom(*victim)) {\n sendTo(\"That person isn't around.\\n\\r\");\n return FALSE;\n }\n\n rc = rescue(this, victim, skill);\n\n if (rc)\n addSkillLag(skill, rc);\n\n if (IS_SET_DELETE(rc, DELETE_THIS))\n return DELETE_THIS;\n\n return rc;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageToStructuredPoints.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkImageToStructuredPoints.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageToStructuredPoints::vtkImageToStructuredPoints()\n{\n this->Input = NULL;\n this->WholeImage = 1;\n this->InputMemoryLimit = 50000000; \/\/ A very big image indeed.\n this->SetSplitOrder(VTK_IMAGE_TIME_AXIS, VTK_IMAGE_Z_AXIS,\n\t\t VTK_IMAGE_Y_AXIS, VTK_IMAGE_X_AXIS);\n}\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageToStructuredPoints::~vtkImageToStructuredPoints()\n{\n}\n\n\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::Update()\n{\n int execute;\n \n \/\/ make sure input is available\n if ( !this->Input )\n {\n vtkErrorMacro(<< \"No input...can't execute!\");\n return;\n }\n\n execute = this->Input->GetPipelineMTime() > this->ExecuteTime\n || this->GetMTime() > this->ExecuteTime \n || this->Region.GetMTime() > this->ExecuteTime;\n \n if (execute)\n {\n vtkDebugMacro(<< \"Update: Condition satisfied, executeTime = \" \n << this->ExecuteTime\n << \", modifiedTime = \" << this->GetMTime() \n << \", input MTime = \" << this->Input->GetPipelineMTime()\n << \", released = \" << this->Output->GetDataReleased());\n \n if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);\n this->Output->Initialize(); \/\/clear output\n this->Execute();\n this->ExecuteTime.Modified();\n this->SetDataReleased(0);\n if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);\n }\n}\n\n\nvoid vtkImageToStructuredPoints::Execute()\n{\n vtkImageRegion *region = new vtkImageRegion;\n int regionBounds[8];\n int *dataBounds;\n int *bounds, dim[3];\n float aspectRatio[3] = {1.0, 1.0, 1.0};\n float origin[3];\n vtkStructuredPoints *output = this->GetOutput();\n \n \/\/ error checking\n if ( this->Input == NULL )\n {\n vtkErrorMacro(<<\"Execute:Please specify an input!\");\n return;\n }\n\n \/\/ Set the coordinate system of the region\n region->SetAxes(this->Region.GetAxes());\n \n \/\/ Fill in image information.\n this->Input->UpdateImageInformation(region);\n\n \/\/ Determine the bounds of the region we are converting\n if (this->WholeImage)\n {\n region->GetImageBounds3d(regionBounds);\n }\n else\n {\n this->Region.GetBounds3d(regionBounds);\n }\n regionBounds[6] = regionBounds[7] = this->Region.GetDefaultCoordinate3();\n region->SetBounds4d(regionBounds);\n\n \/\/ Update the data for the region.\n if ( region->GetVolume() < this->InputMemoryLimit)\n {\n this->Input->UpdateRegion(region);\n }\n if ( ! region->IsAllocated())\n {\n \/\/ We need to stream\n region->SetDataType(this->Input->GetDataType());\n region->Allocate();\n if ( ! region->IsAllocated())\n {\n vtkErrorMacro(<< \"Execute: Could not allocate region.\");\n return;\n }\n if ( ! this->SplitExecute(region))\n {\n vtkErrorMacro(<< \"Execute: Streaming Failed.\");\n return;\n }\n }\n\n \/\/ If data is not the same size as the region, we need to reformat.\n \/\/ Assume that relativeCoordinates == absoluteCoordinates.\n dataBounds = region->GetData()->GetBounds();\n if (dataBounds[0] != regionBounds[0] || dataBounds[1] != regionBounds[1] ||\n dataBounds[2] != regionBounds[2] || dataBounds[3] != regionBounds[3] ||\n dataBounds[4] != regionBounds[4] || dataBounds[5] != regionBounds[5] ||\n dataBounds[6] != regionBounds[6] || dataBounds[7] != regionBounds[7])\n {\n vtkImageRegion *temp = region;\n region = new vtkImageRegion;\n region->SetBounds4d(regionBounds);\n region->CopyRegionData(temp);\n temp->Delete();\n }\n \n \/\/ setup the structured points with the scalars\n bounds = region->GetBounds3d();\n region->GetAspectRatio3d(aspectRatio);\n origin[0] = (float)(bounds[0]); \n origin[1] = (float)(bounds[2]); \n origin[2] = (float)(bounds[4]);\n dim[0] = bounds[1] - bounds[0] + 1;\n dim[1] = bounds[3] - bounds[2] + 1;\n dim[2] = bounds[5] - bounds[4] + 1;\n output->SetDimensions(dim);\n output->SetAspectRatio(aspectRatio);\n output->SetOrigin(origin);\n output->GetPointData()->SetScalars(region->GetData()->GetScalars());\n\n \/\/ delete the temporary structures\n region->Delete();\n}\n\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This function is for streaming. It divides a region into two pieces,\n\/\/ An executes each one. The spliting logic is hardwired. First\n\/\/ the TIME axis is split then ZYX and COMPONENT axes are split.\nint vtkImageToStructuredPoints::SplitExecute(vtkImageRegion *outRegion)\n{\n int saveBounds[VTK_IMAGE_BOUNDS_DIMENSIONS];\n int splitBounds[VTK_IMAGE_BOUNDS_DIMENSIONS];\n int splitAxisIdx = 0;\n int splitAxis;\n int *splitAxes;\n int min, max;\n vtkImageRegion *inRegion;\n \n \/\/ Save the region state to restore later\n outRegion->GetBounds(saveBounds);\n \n \/\/ Split output into two pieces and update separately.\n inRegion = new vtkImageRegion;\n splitAxes = this->SplitOrder.GetAxes();\n vtkDebugMacro (\"Split order is: \" << splitAxes[0] << \", \" \n\t\t\t\t << splitAxes[1] << \", \" \n\t\t\t\t << splitAxes[2] << \", \" \n\t\t\t\t << splitAxes[3]);\n outRegion->GetBounds(splitBounds);\n vtkDebugMacro (<<\"Initial split region bounds are: \" <<\n splitBounds[0] << \", \" <<\n splitBounds[1] << \", \" <<\n splitBounds[2] << \", \" <<\n splitBounds[3] << \", \" <<\n splitBounds[4] << \", \" <<\n splitBounds[5] << \", \" <<\n splitBounds[6] << \", \" <<\n splitBounds[7]);\n\n while (splitBounds[splitAxes[splitAxisIdx] * 2] == splitBounds[splitAxes[splitAxisIdx] * 2 + 1])\n {\n ++splitAxisIdx;\n if (splitAxes[splitAxisIdx] >= VTK_IMAGE_DIMENSIONS)\n {\n vtkErrorMacro(<< \"SplitExecute: Cannot split one pixel.\");\n return 0;\n }\n }\n splitAxis = splitAxes[splitAxisIdx];\n min = splitBounds[splitAxis * 2];\n max = splitBounds[splitAxis * 2 + 1];\n \/\/ lower part\n splitBounds[splitAxis * 2 + 1] = (min + max) \/ 2;\n inRegion->SetBounds(splitBounds);\n outRegion->SetBounds(splitBounds);\n if ( inRegion->GetVolume() < this->InputMemoryLimit)\n {\n vtkDebugMacro (<<\"Updating Split Region: bounds are: \" <<\n splitBounds[0] << \", \" <<\n splitBounds[1] << \", \" <<\n splitBounds[2] << \", \" <<\n splitBounds[3] << \", \" <<\n splitBounds[4] << \", \" <<\n splitBounds[5]);\n this->Input->UpdateRegion(inRegion);\n }\n if (inRegion->IsAllocated())\n {\n outRegion->CopyRegionData(inRegion);\n inRegion->ReleaseData();\n }\n else\n {\n if ( ! this->SplitExecute(outRegion))\n {\n vtkErrorMacro(<< \"SplitExecute: Split failed.\");\n return 0;\n }\n }\n \/\/ upper part\n splitBounds[splitAxis * 2] = splitBounds[splitAxis * 2 + 1] + 1;\n splitBounds[splitAxis * 2 + 1] = max;\n inRegion->SetBounds(splitBounds);\n outRegion->SetBounds(splitBounds);\n if ( inRegion->GetVolume() < this->InputMemoryLimit)\n {\n vtkDebugMacro (<<\"Updating Split Region: bounds are: \" <<\n splitBounds[0] << \", \" <<\n splitBounds[1] << \", \" <<\n splitBounds[2] << \", \" <<\n splitBounds[3] << \", \" <<\n splitBounds[4] << \", \" <<\n splitBounds[5]);\n this->Input->UpdateRegion(inRegion);\n }\n if (inRegion->IsAllocated())\n {\n outRegion->CopyRegionData(inRegion);\n inRegion->ReleaseData();\n }\n else\n {\n if ( ! this->SplitExecute(outRegion))\n {\n vtkErrorMacro(<< \"SplitExecute: Split failed.\");\n return 0;\n }\n }\n \n \/\/ Clean up\n inRegion->Delete();\n outRegion->SetBounds(saveBounds);\n}\n\n \n<commit_msg>Fixed small bug. LARGE BUG STILL REMAINS. It assumes that coordinate system is ABSOLUTE!!!<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageToStructuredPoints.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkImageToStructuredPoints.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageToStructuredPoints::vtkImageToStructuredPoints()\n{\n this->Input = NULL;\n this->WholeImage = 1;\n this->InputMemoryLimit = 50000000; \/\/ A very big image indeed.\n this->SetSplitOrder(VTK_IMAGE_TIME_AXIS, VTK_IMAGE_Z_AXIS,\n\t\t VTK_IMAGE_Y_AXIS, VTK_IMAGE_X_AXIS);\n}\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageToStructuredPoints::~vtkImageToStructuredPoints()\n{\n}\n\n\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::Update()\n{\n int execute;\n \n \/\/ make sure input is available\n if ( !this->Input )\n {\n vtkErrorMacro(<< \"No input...can't execute!\");\n return;\n }\n\n execute = this->Input->GetPipelineMTime() > this->ExecuteTime\n || this->GetMTime() > this->ExecuteTime \n || this->Region.GetMTime() > this->ExecuteTime;\n \n if (execute)\n {\n vtkDebugMacro(<< \"Update: Condition satisfied, executeTime = \" \n << this->ExecuteTime\n << \", modifiedTime = \" << this->GetMTime() \n << \", input MTime = \" << this->Input->GetPipelineMTime()\n << \", released = \" << this->Output->GetDataReleased());\n \n if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);\n this->Output->Initialize(); \/\/clear output\n this->Execute();\n this->ExecuteTime.Modified();\n this->SetDataReleased(0);\n if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);\n }\n}\n\n\nvoid vtkImageToStructuredPoints::Execute()\n{\n vtkImageRegion *region = new vtkImageRegion;\n int regionBounds[8];\n int *dataBounds;\n int *bounds, dim[3];\n float aspectRatio[3] = {1.0, 1.0, 1.0};\n float origin[3];\n vtkStructuredPoints *output = this->GetOutput();\n \n \/\/ error checking\n if ( this->Input == NULL )\n {\n vtkErrorMacro(<<\"Execute:Please specify an input!\");\n return;\n }\n\n \/\/ Set the coordinate system of the region\n region->SetAxes(this->Region.GetAxes());\n \n \/\/ Fill in image information.\n this->Input->UpdateImageInformation(region);\n\n \/\/ Determine the bounds of the region we are converting\n if (this->WholeImage)\n {\n region->GetImageBounds3d(regionBounds);\n }\n else\n {\n this->Region.GetBounds3d(regionBounds);\n }\n regionBounds[6] = regionBounds[7] = this->Region.GetDefaultCoordinate3();\n region->SetBounds4d(regionBounds);\n\n \/\/ Update the data for the region.\n if ( region->GetVolume() < this->InputMemoryLimit)\n {\n this->Input->UpdateRegion(region);\n }\n if ( ! region->IsAllocated())\n {\n \/\/ We need to stream\n region->SetDataType(this->Input->GetDataType());\n region->Allocate();\n if ( ! region->IsAllocated())\n {\n vtkErrorMacro(<< \"Execute: Could not allocate region.\");\n return;\n }\n if ( ! this->SplitExecute(region))\n {\n vtkErrorMacro(<< \"Execute: Streaming Failed.\");\n return;\n }\n }\n\n \/\/ If data is not the same size as the region, we need to reformat.\n \/\/ Assume that relativeCoordinates == absoluteCoordinates.\n dataBounds = region->GetData()->GetBounds();\n if (dataBounds[0] != regionBounds[0] || dataBounds[1] != regionBounds[1] ||\n dataBounds[2] != regionBounds[2] || dataBounds[3] != regionBounds[3] ||\n dataBounds[4] != regionBounds[4] || dataBounds[5] != regionBounds[5] ||\n dataBounds[6] != regionBounds[6] || dataBounds[7] != regionBounds[7])\n {\n vtkImageRegion *temp = region;\n region = new vtkImageRegion;\n region->SetBounds4d(regionBounds);\n region->CopyRegionData(temp);\n temp->Delete();\n }\n \n \/\/ setup the structured points with the scalars\n bounds = region->GetBounds3d();\n region->GetAspectRatio3d(aspectRatio);\n origin[0] = (float)(bounds[0]) * aspectRatio[0]; \n origin[1] = (float)(bounds[2]) * aspectRatio[1]; \n origin[2] = (float)(bounds[4]) * aspectRatio[2];\n dim[0] = bounds[1] - bounds[0] + 1;\n dim[1] = bounds[3] - bounds[2] + 1;\n dim[2] = bounds[5] - bounds[4] + 1;\n output->SetDimensions(dim);\n output->SetAspectRatio(aspectRatio);\n output->SetOrigin(origin);\n output->GetPointData()->SetScalars(region->GetData()->GetScalars());\n\n \/\/ delete the temporary structures\n region->Delete();\n}\n\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This function is for streaming. It divides a region into two pieces,\n\/\/ An executes each one. The spliting logic is hardwired. First\n\/\/ the TIME axis is split then ZYX and COMPONENT axes are split.\nint vtkImageToStructuredPoints::SplitExecute(vtkImageRegion *outRegion)\n{\n int saveBounds[VTK_IMAGE_BOUNDS_DIMENSIONS];\n int splitBounds[VTK_IMAGE_BOUNDS_DIMENSIONS];\n int splitAxisIdx = 0;\n int splitAxis;\n int *splitAxes;\n int min, max;\n vtkImageRegion *inRegion;\n \n \/\/ Save the region state to restore later\n outRegion->GetBounds(saveBounds);\n \n \/\/ Split output into two pieces and update separately.\n inRegion = new vtkImageRegion;\n splitAxes = this->SplitOrder.GetAxes();\n vtkDebugMacro (\"Split order is: \" << splitAxes[0] << \", \" \n\t\t\t\t << splitAxes[1] << \", \" \n\t\t\t\t << splitAxes[2] << \", \" \n\t\t\t\t << splitAxes[3]);\n outRegion->GetBounds(splitBounds);\n vtkDebugMacro (<<\"Initial split region bounds are: \" <<\n splitBounds[0] << \", \" <<\n splitBounds[1] << \", \" <<\n splitBounds[2] << \", \" <<\n splitBounds[3] << \", \" <<\n splitBounds[4] << \", \" <<\n splitBounds[5] << \", \" <<\n splitBounds[6] << \", \" <<\n splitBounds[7]);\n\n splitAxis = splitAxes[splitAxisIdx];\n while (splitBounds[splitAxis * 2] == splitBounds[splitAxis * 2 + 1])\n {\n ++splitAxisIdx;\n if (splitAxisIdx >= VTK_IMAGE_DIMENSIONS)\n {\n vtkErrorMacro(<< \"SplitExecute: Cannot split one pixel.\");\n return 0;\n }\n splitAxis = splitAxes[splitAxisIdx];\n }\n min = splitBounds[splitAxis * 2];\n max = splitBounds[splitAxis * 2 + 1];\n \/\/ lower part\n splitBounds[splitAxis * 2 + 1] = (min + max) \/ 2;\n inRegion->SetBounds(splitBounds);\n outRegion->SetBounds(splitBounds);\n if ( inRegion->GetVolume() < this->InputMemoryLimit)\n {\n vtkDebugMacro (<<\"Updating Split Region: bounds are: \" <<\n splitBounds[0] << \", \" <<\n splitBounds[1] << \", \" <<\n splitBounds[2] << \", \" <<\n splitBounds[3] << \", \" <<\n splitBounds[4] << \", \" <<\n splitBounds[5]);\n this->Input->UpdateRegion(inRegion);\n }\n if (inRegion->IsAllocated())\n {\n outRegion->CopyRegionData(inRegion);\n inRegion->ReleaseData();\n }\n else\n {\n if ( ! this->SplitExecute(outRegion))\n {\n vtkErrorMacro(<< \"SplitExecute: Split failed.\");\n return 0;\n }\n }\n \/\/ upper part\n splitBounds[splitAxis * 2] = splitBounds[splitAxis * 2 + 1] + 1;\n splitBounds[splitAxis * 2 + 1] = max;\n inRegion->SetBounds(splitBounds);\n outRegion->SetBounds(splitBounds);\n if ( inRegion->GetVolume() < this->InputMemoryLimit)\n {\n vtkDebugMacro (<<\"Updating Split Region: bounds are: \" <<\n splitBounds[0] << \", \" <<\n splitBounds[1] << \", \" <<\n splitBounds[2] << \", \" <<\n splitBounds[3] << \", \" <<\n splitBounds[4] << \", \" <<\n splitBounds[5]);\n this->Input->UpdateRegion(inRegion);\n }\n if (inRegion->IsAllocated())\n {\n outRegion->CopyRegionData(inRegion);\n inRegion->ReleaseData();\n }\n else\n {\n if ( ! this->SplitExecute(outRegion))\n {\n vtkErrorMacro(<< \"SplitExecute: Split failed.\");\n return 0;\n }\n }\n \n \/\/ Clean up\n inRegion->Delete();\n outRegion->SetBounds(saveBounds);\n}\n\n \n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkProgrammableGlyphFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkProgrammableGlyphFilter.h\"\n#include \"vtkTransform.h\"\n#include \"vtkVectors.h\"\n#include \"vtkNormals.h\"\n#include \"vtkMath.h\"\n\n\/\/ Construct object with scaling on, scaling mode is by scalar value, \n\/\/ scale factor = 1.0, the range is (0,1), orient geometry is on, and\n\/\/ orientation is by vector. Clamping and indexing are turned off. No\n\/\/ initial sources are defined.\nvtkProgrammableGlyphFilter::vtkProgrammableGlyphFilter()\n{\n this->Source = NULL;\n\n this->GlyphMethod = NULL;\n this->GlyphMethodArgDelete = NULL;\n this->GlyphMethodArg = NULL;\n\n this->Point[0] = this->Point[1] = this->Point[2] = 0.0;\n this->PointId = -1;\n this->PointData = NULL;\n \n this->ColorMode = VTK_COLOR_BY_INPUT;\n}\n\nvtkProgrammableGlyphFilter::~vtkProgrammableGlyphFilter()\n{\n if ((this->GlyphMethodArg)&&(this->GlyphMethodArgDelete))\n {\n (*this->GlyphMethodArgDelete)(this->GlyphMethodArg);\n }\n\n this->SetSource(NULL);\n}\n\nvoid vtkProgrammableGlyphFilter::Execute()\n{\n vtkDataSet *input = this->GetInput();\n vtkPointData *inputPD = input->GetPointData();\n vtkCellData *inputCD = input->GetCellData();\n vtkPolyData *output = this->GetOutput();\n vtkPointData *outputPD = output->GetPointData();\n vtkCellData *outputCD = output->GetCellData();\n vtkPoints *newPts, *sourcePts;\n vtkScalars *ptScalars=NULL, *cellScalars=NULL;\n vtkScalars *inPtScalars, *inCellScalars;\n int numPts = input->GetNumberOfPoints();\n vtkPointData *sourcePD;\n vtkCellData *sourceCD;\n int numSourcePts, numSourceCells, ptOffset=0, scalarOffset;\n int cellId, ptId, id, i, idx, npts;\n vtkIdList *pts=vtkIdList::New();\n vtkIdList *cellPts;\n pts->Allocate(VTK_CELL_SIZE);\n vtkCell *cell;\n\n \/\/ Initialize\n vtkDebugMacro(<<\"Generating programmable glyphs!\");\n \n if ( numPts < 1 )\n {\n vtkErrorMacro(<<\"No input points to glyph\");\n }\n\n sourcePD = this->Source->GetPointData();\n sourceCD = this->Source->GetCellData();\n numSourcePts = this->Source->GetNumberOfPoints();\n numSourceCells = this->Source->GetNumberOfCells();\n\n outputPD->CopyScalarsOff(); \/\/'cause we control the coloring process\n outputCD->CopyScalarsOff();\n\n output->Allocate(numSourceCells*numPts,numSourceCells*numPts);\n outputPD->CopyAllocate(sourcePD, numSourcePts*numPts, numSourcePts*numPts);\n outputCD->CopyAllocate(sourceCD, numSourceCells*numPts, numSourceCells*numPts);\n newPts = vtkPoints::New();\n newPts->Allocate(numSourcePts*numPts);\n\n \/\/ figure out how to color the data and setup\n if ( this->ColorMode == VTK_COLOR_BY_INPUT )\n {\n if ( (inPtScalars = inputPD->GetScalars()) )\n {\n ptScalars = vtkScalars::New();\n ptScalars->Allocate(numSourcePts*numPts);\n }\n if ( (inCellScalars = inputCD->GetScalars()) )\n {\n cellScalars = vtkScalars::New();\n cellScalars->Allocate(numSourcePts*numPts);\n }\n }\n else \/\/ VTK_COLOR_BY_SOURCE\n {\n if ( (inPtScalars = sourcePD->GetScalars()) )\n {\n ptScalars = vtkScalars::New();\n ptScalars->Allocate(numSourcePts*numPts);\n }\n if ( (inCellScalars = sourceCD->GetScalars()) )\n {\n cellScalars = vtkScalars::New();\n cellScalars->Allocate(numSourcePts*numPts);\n }\n }\n\n \/\/ Loop over all points, invoking glyph method and Update(), then append output\n \/\/ of source to output of this filter.\n \/\/ \n this->Updating = 1; \/\/ to prevent infinite recursion\n this->PointData = input->GetPointData();\n for (this->PointId=0; this->PointId < numPts; this->PointId++)\n {\n if ( ! (this->PointId % 10000) ) \n {\n this->UpdateProgress ((float)this->PointId\/numPts);\n if (this->GetAbortExecute()) break;\n }\n\n input->GetPoint(this->PointId, this->Point);\n \n if ( this->GlyphMethod ) \n {\n (*this->GlyphMethod)(this->GlyphMethodArg);\n }\n \n if ( this->Source ) \n {\n this->Source->Update();\n \n sourcePts = this->Source->GetPoints();\n numSourcePts = this->Source->GetNumberOfPoints();\n numSourceCells = this->Source->GetNumberOfCells();\n sourcePD = this->Source->GetPointData();\n sourceCD = this->Source->GetCellData();\n\n \/\/ Copy all data from source to output.\n for (ptId=0; ptId < numSourcePts; ptId++)\n {\n id = newPts->InsertNextPoint(sourcePts->GetPoint(ptId));\n outputPD->CopyData(sourcePD, ptId, id);\n }\n \n for (cellId=0; cellId < numSourceCells; cellId++)\n {\n cell = this->Source->GetCell(cellId);\n cellPts = cell->GetPointIds();\n npts = cellPts->GetNumberOfIds();\n for (pts->Reset(), i=0; i < npts; i++) \n {\n pts->InsertId(i,cellPts->GetId(i) + ptOffset);\n }\n id = output->InsertNextCell(cell->GetCellType(),pts);\n outputCD->CopyData(sourceCD, cellId, id);\n }\n \n \/\/ If we're coloring the output with scalars, do that now\n if ( ptScalars )\n {\n for (ptId=0; ptId < numSourcePts; ptId++)\n {\n idx = (this->ColorMode == VTK_COLOR_BY_INPUT ? this->PointId : ptId);\n ptScalars->InsertNextScalar(inPtScalars->GetScalar(idx));\n }\n }\n else if ( cellScalars )\n {\n for (cellId=0; cellId < numSourceCells; cellId++)\n {\n idx = (this->ColorMode == VTK_COLOR_BY_INPUT ? this->PointId : cellId);\n cellScalars->InsertNextScalar(inCellScalars->GetScalar(idx));\n }\n }\n \n ptOffset += numSourcePts;\n \n }\/\/if a source is available\n } \/\/for all input points\n\n this->Updating = 0;\n \n pts->Delete();\n\n output->SetPoints(newPts);\n newPts->Delete();\n \n if ( ptScalars )\n {\n outputPD->SetScalars(ptScalars);\n ptScalars->Delete();\n }\n \n if ( cellScalars )\n {\n outputCD->SetScalars(cellScalars);\n cellScalars->Delete();\n }\n \n output->Squeeze();\n}\n\n\n\/\/ Override update method because execution can branch two ways (via Input \n\/\/ and Source).\nvoid vtkProgrammableGlyphFilter::Update()\n{\n \/\/ make sure input is available\n if ( this->Input == NULL || this->Source == NULL )\n {\n vtkErrorMacro(<< \"No input or source...can't execute!\");\n return;\n }\n\n \/\/ prevent chasing our tail\n if (this->Updating) return;\n\n this->Updating = 1;\n this->Input->Update();\n if ( this->Source ) this->Source->Update();\n this->Updating = 0;\n\n if (this->Input->GetMTime() > this->ExecuteTime || \n (this->Source && this->Source->GetMTime() > this->ExecuteTime) || \n this->GetMTime() > this->ExecuteTime )\n {\n if ( this->Input->GetDataReleased() ) this->Input->ForceUpdate();\n if ( this->Source && this->Source->GetDataReleased() ) \n this->Source->ForceUpdate();\n\n if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);\n this->Output->Initialize(); \/\/clear output\n \/\/ reset AbortExecute flag and Progress\n this->AbortExecute = 0;\n this->Progress = 0.0;\n this->Execute();\n this->ExecuteTime.Modified();\n if ( !this->AbortExecute ) this->UpdateProgress(1.0);\n this->SetDataReleased(0);\n if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);\n }\n\n if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();\n if ( this->Source && this->Source->ShouldIReleaseData() ) \n this->Source->ReleaseData();\n}\n\n\/\/ Specify function to be called before object executes.\nvoid vtkProgrammableGlyphFilter::SetGlyphMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->GlyphMethod || arg != this->GlyphMethodArg )\n {\n \/\/ delete the current arg if there is one and a delete meth\n if ((this->GlyphMethodArg)&&(this->GlyphMethodArgDelete))\n {\n (*this->GlyphMethodArgDelete)(this->GlyphMethodArg);\n }\n this->GlyphMethod = f;\n this->GlyphMethodArg = arg;\n this->Modified();\n }\n}\n\n\/\/ Set the arg delete method. This is used to free user memory.\nvoid vtkProgrammableGlyphFilter::SetGlyphMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->GlyphMethodArgDelete)\n {\n this->GlyphMethodArgDelete = f;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Return the method of coloring as a descriptive character string.\ninline char *vtkProgrammableGlyphFilter::GetColorModeAsString(void)\n{\n if ( this->ColorMode == VTK_COLOR_BY_INPUT )\n {\n return \"ColorByInput\";\n }\n else \n {\n return \"ColorBySource\";\n }\n}\n\nvoid vtkProgrammableGlyphFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataSetToPolyDataFilter::PrintSelf(os,indent);\n\n os << indent << \"Source: \" << (void *)this->Source << \"\\n\";\n\n os << indent << \"Color Mode: \" << this->GetColorModeAsString() << endl;\n\n if ( this->GlyphMethod )\n {\n os << indent << \"Glyph Method defined\\n\";\n }\n else\n {\n os << indent << \"No Glyph Method\\n\";\n }\n\n}\n<commit_msg>ERR: removed inline from GetColorModeAsString. Non portable for Sun \/opt\/..\/CC and HP compilers.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkProgrammableGlyphFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkProgrammableGlyphFilter.h\"\n#include \"vtkTransform.h\"\n#include \"vtkVectors.h\"\n#include \"vtkNormals.h\"\n#include \"vtkMath.h\"\n\n\/\/ Construct object with scaling on, scaling mode is by scalar value, \n\/\/ scale factor = 1.0, the range is (0,1), orient geometry is on, and\n\/\/ orientation is by vector. Clamping and indexing are turned off. No\n\/\/ initial sources are defined.\nvtkProgrammableGlyphFilter::vtkProgrammableGlyphFilter()\n{\n this->Source = NULL;\n\n this->GlyphMethod = NULL;\n this->GlyphMethodArgDelete = NULL;\n this->GlyphMethodArg = NULL;\n\n this->Point[0] = this->Point[1] = this->Point[2] = 0.0;\n this->PointId = -1;\n this->PointData = NULL;\n \n this->ColorMode = VTK_COLOR_BY_INPUT;\n}\n\nvtkProgrammableGlyphFilter::~vtkProgrammableGlyphFilter()\n{\n if ((this->GlyphMethodArg)&&(this->GlyphMethodArgDelete))\n {\n (*this->GlyphMethodArgDelete)(this->GlyphMethodArg);\n }\n\n this->SetSource(NULL);\n}\n\nvoid vtkProgrammableGlyphFilter::Execute()\n{\n vtkDataSet *input = this->GetInput();\n vtkPointData *inputPD = input->GetPointData();\n vtkCellData *inputCD = input->GetCellData();\n vtkPolyData *output = this->GetOutput();\n vtkPointData *outputPD = output->GetPointData();\n vtkCellData *outputCD = output->GetCellData();\n vtkPoints *newPts, *sourcePts;\n vtkScalars *ptScalars=NULL, *cellScalars=NULL;\n vtkScalars *inPtScalars, *inCellScalars;\n int numPts = input->GetNumberOfPoints();\n vtkPointData *sourcePD;\n vtkCellData *sourceCD;\n int numSourcePts, numSourceCells, ptOffset=0, scalarOffset;\n int cellId, ptId, id, i, idx, npts;\n vtkIdList *pts=vtkIdList::New();\n vtkIdList *cellPts;\n pts->Allocate(VTK_CELL_SIZE);\n vtkCell *cell;\n\n \/\/ Initialize\n vtkDebugMacro(<<\"Generating programmable glyphs!\");\n \n if ( numPts < 1 )\n {\n vtkErrorMacro(<<\"No input points to glyph\");\n }\n\n sourcePD = this->Source->GetPointData();\n sourceCD = this->Source->GetCellData();\n numSourcePts = this->Source->GetNumberOfPoints();\n numSourceCells = this->Source->GetNumberOfCells();\n\n outputPD->CopyScalarsOff(); \/\/'cause we control the coloring process\n outputCD->CopyScalarsOff();\n\n output->Allocate(numSourceCells*numPts,numSourceCells*numPts);\n outputPD->CopyAllocate(sourcePD, numSourcePts*numPts, numSourcePts*numPts);\n outputCD->CopyAllocate(sourceCD, numSourceCells*numPts, numSourceCells*numPts);\n newPts = vtkPoints::New();\n newPts->Allocate(numSourcePts*numPts);\n\n \/\/ figure out how to color the data and setup\n if ( this->ColorMode == VTK_COLOR_BY_INPUT )\n {\n if ( (inPtScalars = inputPD->GetScalars()) )\n {\n ptScalars = vtkScalars::New();\n ptScalars->Allocate(numSourcePts*numPts);\n }\n if ( (inCellScalars = inputCD->GetScalars()) )\n {\n cellScalars = vtkScalars::New();\n cellScalars->Allocate(numSourcePts*numPts);\n }\n }\n else \/\/ VTK_COLOR_BY_SOURCE\n {\n if ( (inPtScalars = sourcePD->GetScalars()) )\n {\n ptScalars = vtkScalars::New();\n ptScalars->Allocate(numSourcePts*numPts);\n }\n if ( (inCellScalars = sourceCD->GetScalars()) )\n {\n cellScalars = vtkScalars::New();\n cellScalars->Allocate(numSourcePts*numPts);\n }\n }\n\n \/\/ Loop over all points, invoking glyph method and Update(), then append output\n \/\/ of source to output of this filter.\n \/\/ \n this->Updating = 1; \/\/ to prevent infinite recursion\n this->PointData = input->GetPointData();\n for (this->PointId=0; this->PointId < numPts; this->PointId++)\n {\n if ( ! (this->PointId % 10000) ) \n {\n this->UpdateProgress ((float)this->PointId\/numPts);\n if (this->GetAbortExecute()) break;\n }\n\n input->GetPoint(this->PointId, this->Point);\n \n if ( this->GlyphMethod ) \n {\n (*this->GlyphMethod)(this->GlyphMethodArg);\n }\n \n if ( this->Source ) \n {\n this->Source->Update();\n \n sourcePts = this->Source->GetPoints();\n numSourcePts = this->Source->GetNumberOfPoints();\n numSourceCells = this->Source->GetNumberOfCells();\n sourcePD = this->Source->GetPointData();\n sourceCD = this->Source->GetCellData();\n\n \/\/ Copy all data from source to output.\n for (ptId=0; ptId < numSourcePts; ptId++)\n {\n id = newPts->InsertNextPoint(sourcePts->GetPoint(ptId));\n outputPD->CopyData(sourcePD, ptId, id);\n }\n \n for (cellId=0; cellId < numSourceCells; cellId++)\n {\n cell = this->Source->GetCell(cellId);\n cellPts = cell->GetPointIds();\n npts = cellPts->GetNumberOfIds();\n for (pts->Reset(), i=0; i < npts; i++) \n {\n pts->InsertId(i,cellPts->GetId(i) + ptOffset);\n }\n id = output->InsertNextCell(cell->GetCellType(),pts);\n outputCD->CopyData(sourceCD, cellId, id);\n }\n \n \/\/ If we're coloring the output with scalars, do that now\n if ( ptScalars )\n {\n for (ptId=0; ptId < numSourcePts; ptId++)\n {\n idx = (this->ColorMode == VTK_COLOR_BY_INPUT ? this->PointId : ptId);\n ptScalars->InsertNextScalar(inPtScalars->GetScalar(idx));\n }\n }\n else if ( cellScalars )\n {\n for (cellId=0; cellId < numSourceCells; cellId++)\n {\n idx = (this->ColorMode == VTK_COLOR_BY_INPUT ? this->PointId : cellId);\n cellScalars->InsertNextScalar(inCellScalars->GetScalar(idx));\n }\n }\n \n ptOffset += numSourcePts;\n \n }\/\/if a source is available\n } \/\/for all input points\n\n this->Updating = 0;\n \n pts->Delete();\n\n output->SetPoints(newPts);\n newPts->Delete();\n \n if ( ptScalars )\n {\n outputPD->SetScalars(ptScalars);\n ptScalars->Delete();\n }\n \n if ( cellScalars )\n {\n outputCD->SetScalars(cellScalars);\n cellScalars->Delete();\n }\n \n output->Squeeze();\n}\n\n\n\/\/ Override update method because execution can branch two ways (via Input \n\/\/ and Source).\nvoid vtkProgrammableGlyphFilter::Update()\n{\n \/\/ make sure input is available\n if ( this->Input == NULL || this->Source == NULL )\n {\n vtkErrorMacro(<< \"No input or source...can't execute!\");\n return;\n }\n\n \/\/ prevent chasing our tail\n if (this->Updating) return;\n\n this->Updating = 1;\n this->Input->Update();\n if ( this->Source ) this->Source->Update();\n this->Updating = 0;\n\n if (this->Input->GetMTime() > this->ExecuteTime || \n (this->Source && this->Source->GetMTime() > this->ExecuteTime) || \n this->GetMTime() > this->ExecuteTime )\n {\n if ( this->Input->GetDataReleased() ) this->Input->ForceUpdate();\n if ( this->Source && this->Source->GetDataReleased() ) \n this->Source->ForceUpdate();\n\n if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);\n this->Output->Initialize(); \/\/clear output\n \/\/ reset AbortExecute flag and Progress\n this->AbortExecute = 0;\n this->Progress = 0.0;\n this->Execute();\n this->ExecuteTime.Modified();\n if ( !this->AbortExecute ) this->UpdateProgress(1.0);\n this->SetDataReleased(0);\n if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);\n }\n\n if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();\n if ( this->Source && this->Source->ShouldIReleaseData() ) \n this->Source->ReleaseData();\n}\n\n\/\/ Specify function to be called before object executes.\nvoid vtkProgrammableGlyphFilter::SetGlyphMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->GlyphMethod || arg != this->GlyphMethodArg )\n {\n \/\/ delete the current arg if there is one and a delete meth\n if ((this->GlyphMethodArg)&&(this->GlyphMethodArgDelete))\n {\n (*this->GlyphMethodArgDelete)(this->GlyphMethodArg);\n }\n this->GlyphMethod = f;\n this->GlyphMethodArg = arg;\n this->Modified();\n }\n}\n\n\/\/ Set the arg delete method. This is used to free user memory.\nvoid vtkProgrammableGlyphFilter::SetGlyphMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->GlyphMethodArgDelete)\n {\n this->GlyphMethodArgDelete = f;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Return the method of coloring as a descriptive character string.\nchar *vtkProgrammableGlyphFilter::GetColorModeAsString(void)\n{\n if ( this->ColorMode == VTK_COLOR_BY_INPUT )\n {\n return \"ColorByInput\";\n }\n else \n {\n return \"ColorBySource\";\n }\n}\n\nvoid vtkProgrammableGlyphFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataSetToPolyDataFilter::PrintSelf(os,indent);\n\n os << indent << \"Source: \" << (void *)this->Source << \"\\n\";\n\n os << indent << \"Color Mode: \" << this->GetColorModeAsString() << endl;\n\n if ( this->GlyphMethod )\n {\n os << indent << \"Glyph Method defined\\n\";\n }\n else\n {\n os << indent << \"No Glyph Method\\n\";\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2017-2019 Baldur Karlsson\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\n#define CATCH_CONFIG_RUNNER\n#define CATCH_CONFIG_NOSTDOUT\n#include \"catch.hpp\"\n#include \"api\/replay\/renderdoc_replay.h\"\n#include \"serialise\/serialiser.h\"\n#include \"strings\/string_utils.h\"\n\n\/\/ since we force use of ToStr for everything and don't allow using catch's stringstream (so that\n\/\/ enums get forwarded to ToStr) we need to implement ToStr for one of Catch's structs.\ntemplate <>\nstd::string DoStringise(const Catch::SourceLineInfo &el)\n{\n return StringFormat::Fmt(\"%s:%zu\", el.file, el.line);\n}\n\nstruct AppVeyorListener : Catch::TestEventListenerBase\n{\n using TestEventListenerBase::TestEventListenerBase; \/\/ inherit constructor\n\n std::string errorList;\n double durationInSeconds = 0.0;\n\n struct TestCase\n {\n double durationInSeconds;\n bool passed;\n std::string errorList;\n std::string name;\n std::string filename;\n\n std::string MakeJSON();\n };\n\n std::vector<TestCase> m_testcases;\n\n virtual bool assertionEnded(Catch::AssertionStats const &assertionStats) override\n {\n Catch::TestEventListenerBase::assertionEnded(assertionStats);\n\n using namespace Catch;\n\n if(!assertionStats.assertionResult.isOk())\n {\n std::ostringstream msg;\n msg << \"-------------------------------------------------------------------------------\\n\";\n for(size_t i = 0; i < m_sectionStack.size(); i++)\n {\n if(i > 0)\n msg << \" > \";\n msg << m_sectionStack[i].name;\n msg << \"\\n\";\n }\n msg << \"-------------------------------------------------------------------------------\\n\";\n msg << assertionStats.assertionResult.getSourceInfo() << \": \";\n\n switch(assertionStats.assertionResult.getResultType())\n {\n case ResultWas::ExpressionFailed: msg << \"Failed\"; break;\n case ResultWas::ThrewException: msg << \"Threw exception\"; break;\n case ResultWas::FatalErrorCondition: msg << \"Fatal error'd\"; break;\n case ResultWas::DidntThrowException: msg << \"Didn't throw expected exception\"; break;\n case ResultWas::ExplicitFailure: msg << \"Explicitly failed\"; break;\n\n case ResultWas::Ok:\n case ResultWas::Info:\n case ResultWas::Warning:\n case ResultWas::Unknown:\n case ResultWas::FailureBit:\n case ResultWas::Exception: break;\n }\n\n if(assertionStats.infoMessages.size() >= 1)\n msg << \" with message(s):\";\n for(auto it = assertionStats.infoMessages.begin(); it != assertionStats.infoMessages.end(); ++it)\n msg << \"\\n\" << it->message;\n\n if(assertionStats.assertionResult.hasExpression())\n {\n msg << \"\\n \" << assertionStats.assertionResult.getExpressionInMacro()\n << \"\\nwith expansion:\\n \" << assertionStats.assertionResult.getExpandedExpression()\n << \"\\n\";\n }\n\n errorList += msg.str();\n }\n\n return true;\n }\n\n virtual void sectionEnded(Catch::SectionStats const §ionStats) override\n {\n durationInSeconds += sectionStats.durationInSeconds;\n\n Catch::TestEventListenerBase::sectionEnded(sectionStats);\n }\n\n virtual void testCaseEnded(Catch::TestCaseStats const &testCaseStats) override\n {\n m_testcases.push_back({\n durationInSeconds, testCaseStats.totals.assertions.allOk(), errorList,\n testCaseStats.testInfo.name, testCaseStats.testInfo.lineInfo.file,\n });\n\n errorList.clear();\n durationInSeconds = 0.0;\n\n Catch::TestEventListenerBase::testCaseEnded(testCaseStats);\n }\n\n \/\/ we dump all the test data at the end, because appveyor can't be trusted to get it right\n \/\/ incrementally. This means if the program crashes mid-run we don't get partial test output, but\n \/\/ it should at least by identified as an issue.\n virtual void testRunEnded(Catch::TestRunStats const &testRunStats) override\n {\n const char *url = Process::GetEnvVariable(\"APPVEYOR_API_URL\");\n\n if(url)\n {\n if(strncmp(url, \"http:\/\/\", 7))\n return;\n\n url += 7;\n\n const char *sep = strchr(url, ':');\n\n if(!sep)\n return;\n\n std::string hostname = std::string(url, sep);\n\n url = sep + 1;\n\n uint16_t port = 0;\n while(*url >= '0' && *url <= '9')\n {\n port *= 10;\n port += int((*url) - '0');\n url++;\n }\n\n Network::Socket *sock = Network::CreateClientSocket(hostname.c_str(), port, 10);\n\n if(sock)\n {\n std::string json;\n\n json += \"[\\n\";\n for(size_t i = 0; i < m_testcases.size(); i++)\n {\n json += m_testcases[i].MakeJSON();\n\n if(i + 1 < m_testcases.size())\n json += \",\";\n\n json += \"\\n\";\n }\n json += \"]\";\n\n std::string http;\n http += StringFormat::Fmt(\"POST \/api\/tests\/batch HTTP\/1.1\\r\\n\");\n http += StringFormat::Fmt(\"Host: %s\\r\\n\", hostname.c_str());\n http += \"Connection: close\\r\\n\";\n http += \"Content-Type: application\/json\\r\\n\";\n http += StringFormat::Fmt(\"Content-Length: %zu\\r\\n\", json.size());\n http += \"User-Agent: Catch.hpp appveyor updater\\r\\n\";\n http += \"\\r\\n\";\n http += json;\n\n sock->SendDataBlocking(http.c_str(), (uint32_t)http.size());\n }\n\n SAFE_DELETE(sock);\n }\n }\n};\n\nstatic std::string escape(const std::string &input)\n{\n std::string ret = input;\n size_t i = ret.find_first_of(\"\\\"\\n\\\\\", 0);\n while(i != std::string::npos)\n {\n if(ret[i] == '\"')\n ret.replace(i, 1, \"\\\\\\\"\");\n else if(ret[i] == '\\\\')\n ret.replace(i, 1, \"\\\\\\\\\");\n else if(ret[i] == '\\n')\n ret.replace(i, 1, \"\\\\n\");\n\n i = ret.find_first_of(\"\\\"\\n\\\\\", i + 2);\n }\n\n return ret;\n}\n\nstd::string AppVeyorListener::TestCase::MakeJSON()\n{\n std::string json;\n\n return StringFormat::Fmt(\n R\"({\n \"testName\": \"%s\",\n \"testFramework\": \"Catch.hpp\",\n \"fileName\": \"%s\",\n \"outcome\": \"%s\",\n \"durationMilliseconds\": \"%d\",\n \"ErrorMessage\": \"%s\",\n \"ErrorStackTrace\": \"\",\n \"StdOut\": \"\",\n \"StdErr\": \"\"\n})\",\n escape(name).c_str(), escape(filename).c_str(), passed ? \"Passed\" : \"Failed\",\n (int)RDCMAX(durationInSeconds * 1000.0, 0.0), escape(trim(errorList)).c_str());\n}\n\nCATCH_REGISTER_LISTENER(AppVeyorListener)\n\nclass LogOutputter : public std::stringbuf\n{\npublic:\n LogOutputter() {}\n virtual int sync() override\n {\n std::string msg = this->str();\n OSUtility::WriteOutput(OSUtility::Output_DebugMon, msg.c_str());\n OSUtility::WriteOutput(OSUtility::Output_StdOut, msg.c_str());\n this->str(\"\");\n return 0;\n }\n\n \/\/ force a sync on every output\n virtual std::streamsize xsputn(const char *s, std::streamsize n) override\n {\n std::streamsize ret = std::stringbuf::xsputn(s, n);\n sync();\n return ret;\n }\n};\n\nstd::ostream *catch_stream = NULL;\n\nnamespace Catch\n{\nstd::ostream &cout()\n{\n return *catch_stream;\n}\nstd::ostream &cerr()\n{\n return *catch_stream;\n}\nstd::ostream &clog()\n{\n return *catch_stream;\n}\n}\n\nextern \"C\" RENDERDOC_API int RENDERDOC_CC RENDERDOC_RunUnitTests(const rdcstr &command,\n const rdcarray<rdcstr> &args)\n{\n LogOutputter logbuf;\n std::ostream logstream(&logbuf);\n catch_stream = &logstream;\n\n Catch::Session session;\n\n session.configData().name = \"RenderDoc\";\n session.configData().shouldDebugBreak = OSUtility::DebuggerPresent();\n\n const char **argv = new const char *[args.size() + 1];\n argv[0] = command.c_str();\n for(size_t i = 0; i < args.size(); i++)\n argv[i + 1] = args[i].c_str();\n\n int ret = session.applyCommandLine(args.count() + 1, argv);\n\n delete[] argv;\n\n \/\/ command line error\n if(ret != 0)\n return ret;\n\n int numFailed = session.run();\n\n \/\/ Note that on unices only the lower 8 bits are usually used, clamping\n \/\/ the return value to 255 prevents false negative when some multiple\n \/\/ of 256 tests has failed\n return (numFailed < 0xff ? numFailed : 0xff);\n}<commit_msg>Don't compile Catch2 into release builds<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2017-2019 Baldur Karlsson\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\n#include \"common\/globalconfig.h\"\n\n#if ENABLED(ENABLE_UNIT_TESTS)\n\n#define CATCH_CONFIG_RUNNER\n#define CATCH_CONFIG_NOSTDOUT\n#include \"serialise\/serialiser.h\"\n#include \"strings\/string_utils.h\"\n#include \"catch.hpp\"\n\n\/\/ since we force use of ToStr for everything and don't allow using catch's stringstream (so that\n\/\/ enums get forwarded to ToStr) we need to implement ToStr for one of Catch's structs.\ntemplate <>\nstd::string DoStringise(const Catch::SourceLineInfo &el)\n{\n return StringFormat::Fmt(\"%s:%zu\", el.file, el.line);\n}\n\nstruct AppVeyorListener : Catch::TestEventListenerBase\n{\n using TestEventListenerBase::TestEventListenerBase; \/\/ inherit constructor\n\n std::string errorList;\n double durationInSeconds = 0.0;\n\n struct TestCase\n {\n double durationInSeconds;\n bool passed;\n std::string errorList;\n std::string name;\n std::string filename;\n\n std::string MakeJSON();\n };\n\n std::vector<TestCase> m_testcases;\n\n virtual bool assertionEnded(Catch::AssertionStats const &assertionStats) override\n {\n Catch::TestEventListenerBase::assertionEnded(assertionStats);\n\n using namespace Catch;\n\n if(!assertionStats.assertionResult.isOk())\n {\n std::ostringstream msg;\n msg << \"-------------------------------------------------------------------------------\\n\";\n for(size_t i = 0; i < m_sectionStack.size(); i++)\n {\n if(i > 0)\n msg << \" > \";\n msg << m_sectionStack[i].name;\n msg << \"\\n\";\n }\n msg << \"-------------------------------------------------------------------------------\\n\";\n msg << assertionStats.assertionResult.getSourceInfo() << \": \";\n\n switch(assertionStats.assertionResult.getResultType())\n {\n case ResultWas::ExpressionFailed: msg << \"Failed\"; break;\n case ResultWas::ThrewException: msg << \"Threw exception\"; break;\n case ResultWas::FatalErrorCondition: msg << \"Fatal error'd\"; break;\n case ResultWas::DidntThrowException: msg << \"Didn't throw expected exception\"; break;\n case ResultWas::ExplicitFailure: msg << \"Explicitly failed\"; break;\n\n case ResultWas::Ok:\n case ResultWas::Info:\n case ResultWas::Warning:\n case ResultWas::Unknown:\n case ResultWas::FailureBit:\n case ResultWas::Exception: break;\n }\n\n if(assertionStats.infoMessages.size() >= 1)\n msg << \" with message(s):\";\n for(auto it = assertionStats.infoMessages.begin(); it != assertionStats.infoMessages.end(); ++it)\n msg << \"\\n\" << it->message;\n\n if(assertionStats.assertionResult.hasExpression())\n {\n msg << \"\\n \" << assertionStats.assertionResult.getExpressionInMacro()\n << \"\\nwith expansion:\\n \" << assertionStats.assertionResult.getExpandedExpression()\n << \"\\n\";\n }\n\n errorList += msg.str();\n }\n\n return true;\n }\n\n virtual void sectionEnded(Catch::SectionStats const §ionStats) override\n {\n durationInSeconds += sectionStats.durationInSeconds;\n\n Catch::TestEventListenerBase::sectionEnded(sectionStats);\n }\n\n virtual void testCaseEnded(Catch::TestCaseStats const &testCaseStats) override\n {\n m_testcases.push_back({\n durationInSeconds, testCaseStats.totals.assertions.allOk(), errorList,\n testCaseStats.testInfo.name, testCaseStats.testInfo.lineInfo.file,\n });\n\n errorList.clear();\n durationInSeconds = 0.0;\n\n Catch::TestEventListenerBase::testCaseEnded(testCaseStats);\n }\n\n \/\/ we dump all the test data at the end, because appveyor can't be trusted to get it right\n \/\/ incrementally. This means if the program crashes mid-run we don't get partial test output, but\n \/\/ it should at least by identified as an issue.\n virtual void testRunEnded(Catch::TestRunStats const &testRunStats) override\n {\n const char *url = Process::GetEnvVariable(\"APPVEYOR_API_URL\");\n\n if(url)\n {\n if(strncmp(url, \"http:\/\/\", 7))\n return;\n\n url += 7;\n\n const char *sep = strchr(url, ':');\n\n if(!sep)\n return;\n\n std::string hostname = std::string(url, sep);\n\n url = sep + 1;\n\n uint16_t port = 0;\n while(*url >= '0' && *url <= '9')\n {\n port *= 10;\n port += int((*url) - '0');\n url++;\n }\n\n Network::Socket *sock = Network::CreateClientSocket(hostname.c_str(), port, 10);\n\n if(sock)\n {\n std::string json;\n\n json += \"[\\n\";\n for(size_t i = 0; i < m_testcases.size(); i++)\n {\n json += m_testcases[i].MakeJSON();\n\n if(i + 1 < m_testcases.size())\n json += \",\";\n\n json += \"\\n\";\n }\n json += \"]\";\n\n std::string http;\n http += StringFormat::Fmt(\"POST \/api\/tests\/batch HTTP\/1.1\\r\\n\");\n http += StringFormat::Fmt(\"Host: %s\\r\\n\", hostname.c_str());\n http += \"Connection: close\\r\\n\";\n http += \"Content-Type: application\/json\\r\\n\";\n http += StringFormat::Fmt(\"Content-Length: %zu\\r\\n\", json.size());\n http += \"User-Agent: Catch.hpp appveyor updater\\r\\n\";\n http += \"\\r\\n\";\n http += json;\n\n sock->SendDataBlocking(http.c_str(), (uint32_t)http.size());\n }\n\n SAFE_DELETE(sock);\n }\n }\n};\n\nstatic std::string escape(const std::string &input)\n{\n std::string ret = input;\n size_t i = ret.find_first_of(\"\\\"\\n\\\\\", 0);\n while(i != std::string::npos)\n {\n if(ret[i] == '\"')\n ret.replace(i, 1, \"\\\\\\\"\");\n else if(ret[i] == '\\\\')\n ret.replace(i, 1, \"\\\\\\\\\");\n else if(ret[i] == '\\n')\n ret.replace(i, 1, \"\\\\n\");\n\n i = ret.find_first_of(\"\\\"\\n\\\\\", i + 2);\n }\n\n return ret;\n}\n\nstd::string AppVeyorListener::TestCase::MakeJSON()\n{\n std::string json;\n\n return StringFormat::Fmt(\n R\"({\n \"testName\": \"%s\",\n \"testFramework\": \"Catch.hpp\",\n \"fileName\": \"%s\",\n \"outcome\": \"%s\",\n \"durationMilliseconds\": \"%d\",\n \"ErrorMessage\": \"%s\",\n \"ErrorStackTrace\": \"\",\n \"StdOut\": \"\",\n \"StdErr\": \"\"\n})\",\n escape(name).c_str(), escape(filename).c_str(), passed ? \"Passed\" : \"Failed\",\n (int)RDCMAX(durationInSeconds * 1000.0, 0.0), escape(trim(errorList)).c_str());\n}\n\nCATCH_REGISTER_LISTENER(AppVeyorListener)\n\nclass LogOutputter : public std::stringbuf\n{\npublic:\n LogOutputter() {}\n virtual int sync() override\n {\n std::string msg = this->str();\n OSUtility::WriteOutput(OSUtility::Output_DebugMon, msg.c_str());\n OSUtility::WriteOutput(OSUtility::Output_StdOut, msg.c_str());\n this->str(\"\");\n return 0;\n }\n\n \/\/ force a sync on every output\n virtual std::streamsize xsputn(const char *s, std::streamsize n) override\n {\n std::streamsize ret = std::stringbuf::xsputn(s, n);\n sync();\n return ret;\n }\n};\n\nstd::ostream *catch_stream = NULL;\n\nnamespace Catch\n{\nstd::ostream &cout()\n{\n return *catch_stream;\n}\nstd::ostream &cerr()\n{\n return *catch_stream;\n}\nstd::ostream &clog()\n{\n return *catch_stream;\n}\n}\n\nextern \"C\" RENDERDOC_API int RENDERDOC_CC RENDERDOC_RunUnitTests(const rdcstr &command,\n const rdcarray<rdcstr> &args)\n{\n LogOutputter logbuf;\n std::ostream logstream(&logbuf);\n catch_stream = &logstream;\n\n Catch::Session session;\n\n session.configData().name = \"RenderDoc\";\n session.configData().shouldDebugBreak = OSUtility::DebuggerPresent();\n\n const char **argv = new const char *[args.size() + 1];\n argv[0] = command.c_str();\n for(size_t i = 0; i < args.size(); i++)\n argv[i + 1] = args[i].c_str();\n\n int ret = session.applyCommandLine(args.count() + 1, argv);\n\n delete[] argv;\n\n \/\/ command line error\n if(ret != 0)\n return ret;\n\n int numFailed = session.run();\n\n \/\/ Note that on unices only the lower 8 bits are usually used, clamping\n \/\/ the return value to 255 prevents false negative when some multiple\n \/\/ of 256 tests has failed\n return (numFailed < 0xff ? numFailed : 0xff);\n}\n\n#else\n\n#include \"api\/replay\/renderdoc_replay.h\"\n\nextern \"C\" RENDERDOC_API int RENDERDOC_CC RENDERDOC_RunUnitTests(const rdcstr &command,\n const rdcarray<rdcstr> &args)\n{\n return 0;\n}\n\n#endif \/\/ ENABLED(ENABLE_UNIT_TESTS)\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <map>\n\n#include \"logging.h\"\n#include \"platform.h\"\n#include \"util_concurrency.h\"\n#include \"util\/pointer.h\"\n#include \"util\/posix.h\"\n\ntypedef std::map<file_watcher::Event, int> Counters;\n\nclass TestEventHandler : public file_watcher::EventHandler {\n public:\n explicit TestEventHandler(Counters* ctrs,\n FifoChannel<bool>* chan)\n : counters_(ctrs)\n , chan_(chan)\n , clear_(true) {}\n\n virtual ~TestEventHandler() {}\n\n virtual bool Handle(const std::string& \/*file_path*\/,\n file_watcher::Event event,\n bool* clear_handler) {\n (*counters_)[event]++;\n *clear_handler = clear_;\n chan_->Enqueue(true);\n return true;\n }\n\n Counters* counters_;\n FifoChannel<bool>* chan_;\n bool clear_;\n};\n\nclass T_FileWatcher : public ::testing::Test {\n protected:\n void SetUp() {\n counters_.clear();\n channel_ = new FifoChannel<bool>(10, 1);\n }\n\n Counters counters_;\n UniquePtr<FifoChannel<bool> > channel_;\n};\n\nTEST_F(T_FileWatcher, kModifiedEvent) {\n const std::string watched_file_name =\n GetCurrentWorkingDirectory() + \"\/file_watcher_test.txt\";\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());\n\n TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));\n watcher->RegisterHandler(watched_file_name, hd);\n\n EXPECT_TRUE(watcher->Start());\n\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n channel_->Dequeue();\n\n Counters::const_iterator it_mod = counters_.find(file_watcher::kModified);\n const int num_modifications = it_mod->second;\n EXPECT_EQ(1, num_modifications);\n\n watcher->Stop();\n}\n\nTEST_F(T_FileWatcher, kDeletedEvent) {\n const std::string watched_file_name =\n GetCurrentWorkingDirectory() + \"\/file_watcher_test2.txt\";\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());\n\n TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));\n watcher->RegisterHandler(watched_file_name, hd);\n\n EXPECT_TRUE(watcher->Start());\n\n unlink(watched_file_name.c_str());\n\n channel_->Dequeue();\n\n Counters::const_iterator it_del = counters_.find(file_watcher::kDeleted);\n const int num_deletions = it_del->second;\n EXPECT_EQ(1, num_deletions);\n\n watcher->Stop();\n}\n\nTEST_F(T_FileWatcher, kModifiedThenDeletedEvent) {\n const std::string watched_file_name =\n GetCurrentWorkingDirectory() + \"\/file_watcher_test.txt\";\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());\n\n TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));\n hd->clear_ = false;\n watcher->RegisterHandler(watched_file_name, hd);\n\n EXPECT_TRUE(watcher->Start());\n\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n channel_->Dequeue();\n\n hd->clear_ = true;\n\n Counters::const_iterator it_mod = counters_.find(file_watcher::kModified);\n const int num_modifications = it_mod->second;\n EXPECT_EQ(1, num_modifications);\n\n unlink(watched_file_name.c_str());\n\n channel_->Dequeue();\n\n Counters::const_iterator it_del = counters_.find(file_watcher::kDeleted);\n const int num_deletions = it_del->second;\n EXPECT_EQ(1, num_deletions);\n\n watcher->Stop();\n}\n<commit_msg>Disable FileWatcher tests on Linux until the inotify version is written<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <map>\n\n#include \"logging.h\"\n#include \"platform.h\"\n#include \"util_concurrency.h\"\n#include \"util\/pointer.h\"\n#include \"util\/posix.h\"\n\ntypedef std::map<file_watcher::Event, int> Counters;\n\nclass TestEventHandler : public file_watcher::EventHandler {\n public:\n explicit TestEventHandler(Counters* ctrs,\n FifoChannel<bool>* chan)\n : counters_(ctrs)\n , chan_(chan)\n , clear_(true) {}\n\n virtual ~TestEventHandler() {}\n\n virtual bool Handle(const std::string& \/*file_path*\/,\n file_watcher::Event event,\n bool* clear_handler) {\n (*counters_)[event]++;\n *clear_handler = clear_;\n chan_->Enqueue(true);\n return true;\n }\n\n Counters* counters_;\n FifoChannel<bool>* chan_;\n bool clear_;\n};\n\nclass T_FileWatcher : public ::testing::Test {\n protected:\n void SetUp() {\n counters_.clear();\n channel_ = new FifoChannel<bool>(10, 1);\n }\n\n Counters counters_;\n UniquePtr<FifoChannel<bool> > channel_;\n};\n\nTEST_F(T_FileWatcher, kModifiedEvent) {\n const std::string watched_file_name =\n GetCurrentWorkingDirectory() + \"\/file_watcher_test.txt\";\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());\n\n \/\/ TODO(radu): Remove this check when the Linux inotify version is added\n if (watcher.IsValid()) {\n TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));\n watcher->RegisterHandler(watched_file_name, hd);\n\n EXPECT_TRUE(watcher->Start());\n\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n channel_->Dequeue();\n\n Counters::const_iterator it_mod = counters_.find(file_watcher::kModified);\n const int num_modifications = it_mod->second;\n EXPECT_EQ(1, num_modifications);\n\n watcher->Stop();\n }\n}\n\nTEST_F(T_FileWatcher, kDeletedEvent) {\n const std::string watched_file_name =\n GetCurrentWorkingDirectory() + \"\/file_watcher_test2.txt\";\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());\n\n \/\/ TODO(radu): Remove this check when the Linux inotify version is added\n if (watcher.IsValid()) {\n TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));\n watcher->RegisterHandler(watched_file_name, hd);\n\n EXPECT_TRUE(watcher->Start());\n\n unlink(watched_file_name.c_str());\n\n channel_->Dequeue();\n\n Counters::const_iterator it_del = counters_.find(file_watcher::kDeleted);\n const int num_deletions = it_del->second;\n EXPECT_EQ(1, num_deletions);\n\n watcher->Stop();\n }\n}\n\nTEST_F(T_FileWatcher, kModifiedThenDeletedEvent) {\n const std::string watched_file_name =\n GetCurrentWorkingDirectory() + \"\/file_watcher_test.txt\";\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());\n\n \/\/ TODO(radu): Remove this check when the Linux inotify version is added\n if (watcher.IsValid()) {\n TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));\n hd->clear_ = false;\n watcher->RegisterHandler(watched_file_name, hd);\n\n EXPECT_TRUE(watcher->Start());\n\n SafeWriteToFile(\"test\", watched_file_name, 0600);\n\n channel_->Dequeue();\n\n hd->clear_ = true;\n\n Counters::const_iterator it_mod = counters_.find(file_watcher::kModified);\n const int num_modifications = it_mod->second;\n EXPECT_EQ(1, num_modifications);\n\n unlink(watched_file_name.c_str());\n\n channel_->Dequeue();\n\n Counters::const_iterator it_del = counters_.find(file_watcher::kDeleted);\n const int num_deletions = it_del->second;\n EXPECT_EQ(1, num_deletions);\n\n watcher->Stop();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ELEKTRON_H__\n#define ELEKTRON_H__\n\n#include \"WProgram.h\"\n\n#include <inttypes.h>\n\ntypedef struct machine_name_s {\n char name[11];\n uint8_t id;\n} machine_name_t;\n\ntypedef struct model_param_name_s {\n char name[4];\n uint8_t id;\n} model_param_name_t;\n\ntypedef struct model_to_param_names_s {\n uint8_t model;\n model_param_name_t *names;\n} model_to_param_names_t;\n\nclass ElektronHelper {\npublic:\n static uint16_t MDSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);\n static uint16_t MDDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);\n static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);\n static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);\n static uint16_t to16Bit7(uint8_t b1, uint8_t b2);\n static uint16_t to16Bit(uint8_t b1, uint8_t b2);\n static uint16_t to16Bit(uint8_t *b);\n static uint32_t to32Bit(uint8_t *b);\n static void from16Bit(uint16_t num, uint8_t *b);\n static void from32Bit(uint32_t num, uint8_t *b);\n static uint64_t to64Bit(uint8_t *b);\n static void from64Bit(uint64_t num, uint8_t *b);\n};\n\nclass DataEncoder {\npublic:\n uint8_t *data;\n uint8_t *ptr;\n uint16_t maxLen;\n\n virtual void init(uint8_t *_data, uint16_t _maxLen) {\n data = _data;\n maxLen = _maxLen;\n ptr = data;\n }\n \n virtual bool pack(uint8_t inb) {\n return false;\n }\n virtual uint16_t finish() {\n return 0;\n }\n#ifdef HOST_MIDIDUINO\n virtual ~DataEncoder() { };\n#endif\n};\n\nclass MNMDataToSysexEncoder : public DataEncoder {\n uint16_t retLen;\n uint16_t cnt7;\n\n uint8_t lastByte;\n uint8_t lastCnt;\n bool isFirstByte;\n \npublic:\n MNMDataToSysexEncoder(uint8_t *_sysex = NULL, uint16_t _sysexLen = 0) {\n init(_sysex, _sysexLen);\n }\n\n virtual void init(uint8_t *_sysex, uint16_t _sysexLen);\n bool encode7Bit(uint8_t inb);\n virtual bool pack(uint8_t inb);\n bool packLastByte();\n virtual uint16_t finish();\n};\n\nclass MNMSysexToDataEncoder : public DataEncoder {\npublic:\n uint16_t retLen;\n uint8_t cnt7;\n uint8_t repeat;\n uint16_t cnt;\n uint8_t bits;\n uint8_t tmpData[7];\n \n MNMSysexToDataEncoder(uint8_t *_data = NULL, uint16_t _maxLen = 0) {\n init(_data, _maxLen);\n }\n\n virtual void init(uint8_t *_data, uint16_t _maxLen);\n virtual bool pack(uint8_t inb);\n bool unpack8Bit();\n virtual uint16_t finish();\n};\n\n\n#endif \/* ELEKTRON_H__ *\/\n<commit_msg>split md machine and mnm machine names to save some bytes<commit_after>#ifndef ELEKTRON_H__\n#define ELEKTRON_H__\n\n#include \"WProgram.h\"\n\n#include <inttypes.h>\n\ntypedef struct mnm_machine_name_s {\n char name[11];\n uint8_t id;\n} mnm_machine_name_t;\n\ntypedef struct md_machine_name_s {\n char name[7];\n uint8_t id;\n} md_machine_name_t;\n\n\ntypedef struct model_param_name_s {\n char name[4];\n uint8_t id;\n} model_param_name_t;\n\ntypedef struct model_to_param_names_s {\n uint8_t model;\n model_param_name_t *names;\n} model_to_param_names_t;\n\nclass ElektronHelper {\npublic:\n static uint16_t MDSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);\n static uint16_t MDDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);\n static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);\n static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);\n static uint16_t to16Bit7(uint8_t b1, uint8_t b2);\n static uint16_t to16Bit(uint8_t b1, uint8_t b2);\n static uint16_t to16Bit(uint8_t *b);\n static uint32_t to32Bit(uint8_t *b);\n static void from16Bit(uint16_t num, uint8_t *b);\n static void from32Bit(uint32_t num, uint8_t *b);\n static uint64_t to64Bit(uint8_t *b);\n static void from64Bit(uint64_t num, uint8_t *b);\n};\n\nclass DataEncoder {\npublic:\n uint8_t *data;\n uint8_t *ptr;\n uint16_t maxLen;\n\n virtual void init(uint8_t *_data, uint16_t _maxLen) {\n data = _data;\n maxLen = _maxLen;\n ptr = data;\n }\n \n virtual bool pack(uint8_t inb) {\n return false;\n }\n virtual uint16_t finish() {\n return 0;\n }\n#ifdef HOST_MIDIDUINO\n virtual ~DataEncoder() { };\n#endif\n};\n\nclass MNMDataToSysexEncoder : public DataEncoder {\n uint16_t retLen;\n uint16_t cnt7;\n\n uint8_t lastByte;\n uint8_t lastCnt;\n bool isFirstByte;\n \npublic:\n MNMDataToSysexEncoder(uint8_t *_sysex = NULL, uint16_t _sysexLen = 0) {\n init(_sysex, _sysexLen);\n }\n\n virtual void init(uint8_t *_sysex, uint16_t _sysexLen);\n bool encode7Bit(uint8_t inb);\n virtual bool pack(uint8_t inb);\n bool packLastByte();\n virtual uint16_t finish();\n};\n\nclass MNMSysexToDataEncoder : public DataEncoder {\npublic:\n uint16_t retLen;\n uint8_t cnt7;\n uint8_t repeat;\n uint16_t cnt;\n uint8_t bits;\n uint8_t tmpData[7];\n \n MNMSysexToDataEncoder(uint8_t *_data = NULL, uint16_t _maxLen = 0) {\n init(_data, _maxLen);\n }\n\n virtual void init(uint8_t *_data, uint16_t _maxLen);\n virtual bool pack(uint8_t inb);\n bool unpack8Bit();\n virtual uint16_t finish();\n};\n\n\n#endif \/* ELEKTRON_H__ *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef ELEKTRON_H__\n#define ELEKTRON_H__\n\n#include \"WProgram.h\"\n\n#include <inttypes.h>\n\ntypedef struct machine_name_s {\n char name[11];\n uint8_t id;\n} machine_name_t;\n\ntypedef struct model_param_name_s {\n char name[4];\n uint8_t id;\n} model_param_name_t;\n\ntypedef struct model_to_param_names_s {\n uint8_t model;\n model_param_name_t *names;\n} model_to_param_names_t;\n\nclass ElektronHelper {\npublic:\n static uint16_t MDSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);\n static uint16_t MDDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);\n static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);\n static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);\n static uint16_t to16Bit7(uint8_t b1, uint8_t b2);\n static uint16_t to16Bit(uint8_t b1, uint8_t b2);\n static uint16_t to16Bit(uint8_t *b);\n static uint32_t to32Bit(uint8_t *b);\n static void from16Bit(uint16_t num, uint8_t *b);\n static void from32Bit(uint32_t num, uint8_t *b);\n static uint64_t to64Bit(uint8_t *b);\n static void from64Bit(uint64_t num, uint8_t *b);\n};\n\nclass DataEncoder {\npublic:\n uint8_t *data;\n uint8_t *ptr;\n uint16_t maxLen;\n\n virtual void init(uint8_t *_data, uint16_t _maxLen) {\n data = _data;\n maxLen = _maxLen;\n ptr = data;\n }\n \n virtual bool pack(uint8_t inb) = 0;\n virtual uint16_t finish() = 0;\n#ifdef HOST_MIDIDUINO\n virtual ~DataEncoder() { };\n#endif\n};\n\nclass MNMDataToSysexEncoder : public DataEncoder {\n uint16_t retLen;\n uint16_t cnt7;\n\n uint8_t lastByte;\n uint8_t lastCnt;\n bool isFirstByte;\n \npublic:\n MNMDataToSysexEncoder(uint8_t *_sysex = NULL, uint16_t _sysexLen = 0) {\n init(_sysex, _sysexLen);\n }\n\n virtual void init(uint8_t *_sysex, uint16_t _sysexLen);\n bool encode7Bit(uint8_t inb);\n virtual bool pack(uint8_t inb);\n bool packLastByte();\n virtual uint16_t finish();\n};\n\nclass MNMSysexToDataEncoder : public DataEncoder {\npublic:\n uint16_t retLen;\n uint8_t cnt7;\n uint8_t repeat;\n uint16_t cnt;\n uint8_t bits;\n uint8_t tmpData[7];\n \n MNMSysexToDataEncoder(uint8_t *_data = NULL, uint16_t _maxLen = 0) {\n init(_data, _maxLen);\n }\n\n virtual void init(uint8_t *_data, uint16_t _maxLen);\n virtual bool pack(uint8_t inb);\n bool unpack8Bit();\n virtual uint16_t finish();\n};\n\n\n#endif \/* ELEKTRON_H__ *\/\n<commit_msg>added virtual methods to Elektron<commit_after>#ifndef ELEKTRON_H__\n#define ELEKTRON_H__\n\n#include \"WProgram.h\"\n\n#include <inttypes.h>\n\ntypedef struct machine_name_s {\n char name[11];\n uint8_t id;\n} machine_name_t;\n\ntypedef struct model_param_name_s {\n char name[4];\n uint8_t id;\n} model_param_name_t;\n\ntypedef struct model_to_param_names_s {\n uint8_t model;\n model_param_name_t *names;\n} model_to_param_names_t;\n\nclass ElektronHelper {\npublic:\n static uint16_t MDSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);\n static uint16_t MDDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);\n static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);\n static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);\n static uint16_t to16Bit7(uint8_t b1, uint8_t b2);\n static uint16_t to16Bit(uint8_t b1, uint8_t b2);\n static uint16_t to16Bit(uint8_t *b);\n static uint32_t to32Bit(uint8_t *b);\n static void from16Bit(uint16_t num, uint8_t *b);\n static void from32Bit(uint32_t num, uint8_t *b);\n static uint64_t to64Bit(uint8_t *b);\n static void from64Bit(uint64_t num, uint8_t *b);\n};\n\nclass DataEncoder {\npublic:\n uint8_t *data;\n uint8_t *ptr;\n uint16_t maxLen;\n\n virtual void init(uint8_t *_data, uint16_t _maxLen) {\n data = _data;\n maxLen = _maxLen;\n ptr = data;\n }\n \n virtual bool pack(uint8_t inb) {\n return false;\n }\n virtual uint16_t finish() {\n return 0;\n }\n#ifdef HOST_MIDIDUINO\n virtual ~DataEncoder() { };\n#endif\n};\n\nclass MNMDataToSysexEncoder : public DataEncoder {\n uint16_t retLen;\n uint16_t cnt7;\n\n uint8_t lastByte;\n uint8_t lastCnt;\n bool isFirstByte;\n \npublic:\n MNMDataToSysexEncoder(uint8_t *_sysex = NULL, uint16_t _sysexLen = 0) {\n init(_sysex, _sysexLen);\n }\n\n virtual void init(uint8_t *_sysex, uint16_t _sysexLen);\n bool encode7Bit(uint8_t inb);\n virtual bool pack(uint8_t inb);\n bool packLastByte();\n virtual uint16_t finish();\n};\n\nclass MNMSysexToDataEncoder : public DataEncoder {\npublic:\n uint16_t retLen;\n uint8_t cnt7;\n uint8_t repeat;\n uint16_t cnt;\n uint8_t bits;\n uint8_t tmpData[7];\n \n MNMSysexToDataEncoder(uint8_t *_data = NULL, uint16_t _maxLen = 0) {\n init(_data, _maxLen);\n }\n\n virtual void init(uint8_t *_data, uint16_t _maxLen);\n virtual bool pack(uint8_t inb);\n bool unpack8Bit();\n virtual uint16_t finish();\n};\n\n\n#endif \/* ELEKTRON_H__ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by arssivka on 2\/24\/16.\n\/\/\n\n#include <rd\/hardware\/TypeDefinition.h>\n#include \"rd\/hardware\/Locomotion.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::Locomotion::Locomotion(boost::shared_ptr<Robot> robot)\n : m_meta_gait(new MetaGait), m_step_generator(new StepGenerator(robot, m_meta_gait.get())),\n m_joints(robot->getJoints()), m_clock(robot->getClock()), m_joint_keys(20), m_head_joint_keys(2),\n m_parameter_keys(PARAMETERS_COUNT), m_odometry_keys(ODOMETRY_COUNT), m_auto_apply_flag(false),\n m_auto_apply_worker(boost::bind(&rd::Locomotion::autoUpdater, this)), m_auto_update_sleep_time(0) {\n Gait default_gait(DEFAULT_GAIT);\n m_meta_gait->setStartGait(default_gait);\n m_meta_gait->setNewGaitTarget(default_gait);\n\n m_stance_joints_data = boost::make_shared<SensorData<double> >(*m_step_generator->getDefaultStance(DEFAULT_GAIT),\n m_clock->getTime());\n\n m_parameter_keys[X] = \"X\";\n m_parameter_keys[Y] = \"Y\";\n m_parameter_keys[THETA] = \"THETA\";\n m_parameter_keys[STEP_COUNT] = \"STEP_COUNT\";\n\n for (int i = 0; i < PARAMETERS_COUNT; ++i) {\n m_parameters_key_map.insert(std::make_pair(m_parameter_keys[i], i));\n }\n\n m_odometry_keys[X_OFFSET] = \"X_OFFSET\";\n m_odometry_keys[Y_OFFSET] = \"Y_OFFSET\";\n m_odometry_keys[ROTATION] = \"ROTATION\";\n \n for (int i = 0; i < 20; ++i) {\n const StringKeyVector& keys = m_joints->getKeys();\n m_joint_keys[i] = keys[StepGenerator::NB_WALKING_JOINTS[i]];\n }\n\n m_joint_keys.push_back(\"HEAD_PITCH\");\n m_joint_keys.push_back(\"HEAD_YAW\");\n\n int now = m_clock->getTime();\n m_positions_data = boost::make_shared<SensorData<double> >(m_joint_keys.size(), now);\n m_hardness_data = boost::make_shared<SensorData<double> >(m_joint_keys.size(), now);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst StringKeyVector& rd::Locomotion::getParameterKeys() const {\n return m_parameter_keys;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getSpeedParameters(const StringKeyVector& keys) {\n IntegerKeyVector keys_i(keys.size());\n for (int i = 0; i < keys.size(); ++i) {\n std::map<std::string, int>::const_iterator found = m_parameters_key_map.find(keys[i]);\n if (found == m_parameters_key_map.end())\n return boost::make_shared<SensorData<double> >();\n keys_i[i] = found->second;\n }\n return this->getSpeedParameters(keys_i);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getSpeedParameters(const IntegerKeyVector& keys) {\n SensorData<double>::Ptr data = boost::make_shared<SensorData<double> >(keys.size(), m_clock->getTime());\n boost::lock_guard<boost::mutex> lock(m_access);\n for (int i = 0; i < keys.size(); ++i) {\n switch (keys[i]) {\n case X:\n data->data[i] = m_x;\n break;\n case Y:\n data->data[i] = m_y;\n break;\n case THETA:\n data->data[i] = m_theta;\n break;\n case STEP_COUNT:\n data->data[i] = m_step_count;\n break;\n default:\n return boost::make_shared<SensorData<double> >();\n break;\n }\n }\n return data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setSpeedParameters(const StringKeyVector& keys, const ValuesVector& values) {\n IntegerKeyVector keys_i(keys.size());\n for (int i = 0; i < keys.size(); ++i) {\n const std::map<std::string, int>::const_iterator found = m_parameters_key_map.find(keys[i]);\n if (found == m_parameters_key_map.end())\n return;\n keys_i[i] = found->second;\n }\n this->setSpeedParameters(keys_i, values);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setSpeedParameters(const IntegerKeyVector& keys, const ValuesVector& values) {\n if (keys.empty() || keys.size() != values.size())\n return;\n boost::lock_guard<boost::mutex> lock(m_access);\n m_x = 0.0;\n m_y = 0.0;\n m_theta = 0.0;\n m_step_count = 0;\n for (int i = 0; i < keys.size(); ++i) {\n switch (keys[i]) {\n case X_OFFSET:\n m_x = values[i];\n break;\n case Y_OFFSET:\n m_y = values[i];\n break;\n case THETA:\n m_theta = values[i];\n break;\n case STEP_COUNT:\n m_step_count = (unsigned int) values[i];\n break;\n }\n }\n if (m_step_count > 0) {\n m_step_generator->takeSteps(m_x, m_y, m_theta, m_step_count);\n } else {\n m_step_generator->setSpeed(m_x, m_y, m_theta);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getOdometry() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return boost::make_shared<SensorData<double> >(m_step_generator->getOdometryUpdate(), m_clock->getTime());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::resetOdometry() {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_step_generator->resetOdometry(0.0, 0.0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setGaitParameters(const double stance_config[WP::LEN_STANCE_CONFIG],\n const double step_config[WP::LEN_STEP_CONFIG],\n const double zmp_config[WP::LEN_ZMP_CONFIG],\n const double joint_hack_config[WP::LEN_HACK_CONFIG],\n const double sensor_config[WP::LEN_SENSOR_CONFIG],\n const double stiffness_config[WP::LEN_STIFF_CONFIG],\n const double odo_config[WP::LEN_ODO_CONFIG],\n const double arm_config[WP::LEN_ARM_CONFIG]) {\n boost::lock_guard<boost::mutex> lock(m_access);\n Gait next_gait(stance_config, step_config, zmp_config, joint_hack_config,\n sensor_config, stiffness_config, odo_config, arm_config);\n m_meta_gait->setNewGaitTarget(next_gait);\n m_stance_joints_data = boost::make_shared<SensorData<double> >(*m_step_generator->getDefaultStance(next_gait),\n m_clock->getTime());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst StringKeyVector& rd::Locomotion::getJointKeys() const {\n return m_joint_keys;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::generateStep() {\n int now = m_clock->getTime();\n boost::lock_guard<boost::mutex> lock(m_access);\n double pitch_p = m_positions_data->data[20];\n double yaw_p = m_positions_data->data[21];\n double pitch_h = m_hardness_data->data[20];\n double yaw_h = m_hardness_data->data[21];\n m_positions_data = boost::make_shared<SensorData<double> >(m_joint_keys.size(), now);\n m_hardness_data = boost::make_shared<SensorData<double> >(m_joint_keys.size(), now);\n m_step_generator->tick_controller();\n const WalkLegsTuple& legs = m_step_generator->tick_legs();\n const WalkArmsTuple& arms = m_step_generator->tick_arms();\n const ValuesVector& lleg_joints = legs.get<LEFT_FOOT>().get<JOINT_INDEX>();\n const ValuesVector& rleg_joints = legs.get<RIGHT_FOOT>().get<JOINT_INDEX>();\n const ValuesVector& lleg_gains = legs.get<LEFT_FOOT>().get<STIFF_INDEX>();\n const ValuesVector& rleg_gains = legs.get<RIGHT_FOOT>().get<STIFF_INDEX>();\n const ValuesVector& larm_joints = arms.get<LEFT_FOOT>().get<JOINT_INDEX>();\n const ValuesVector& rarm_joints = arms.get<RIGHT_FOOT>().get<JOINT_INDEX>();\n const ValuesVector& larm_gains = arms.get<LEFT_FOOT>().get<STIFF_INDEX>();\n const ValuesVector& rarm_gains = arms.get<RIGHT_FOOT>().get<STIFF_INDEX>();\n std::copy(larm_gains.begin(), larm_gains.end(), m_hardness_data->data.begin() + 0);\n std::copy(lleg_gains.begin(), lleg_gains.end(), m_hardness_data->data.begin() + 4);\n std::copy(rleg_gains.begin(), rleg_gains.end(), m_hardness_data->data.begin() + 10);\n std::copy(rarm_gains.begin(), rarm_gains.end(), m_hardness_data->data.begin() + 16);\n m_hardness_data->data[20] = pitch_h;\n m_hardness_data->data[21] = yaw_h;\n std::copy(larm_joints.begin(), larm_joints.end(), m_positions_data->data.begin() + 0);\n std::copy(lleg_joints.begin(), lleg_joints.end(), m_positions_data->data.begin() + 4);\n std::copy(rleg_joints.begin(), rleg_joints.end(), m_positions_data->data.begin() + 10);\n std::copy(rarm_joints.begin(), rarm_joints.end(), m_positions_data->data.begin() + 16);\n m_positions_data->data[20] = pitch_p;\n m_positions_data->data[21] = yaw_p;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getPositions() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_positions_data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getHardness() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_hardness_data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool rd::Locomotion::isDone() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_step_generator->isDone();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst StringKeyVector& rd::Locomotion::getOdometryKeys() const {\n return m_odometry_keys;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::applyPositions() {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_joints->setHardness(m_joint_keys, m_hardness_data->data);\n m_joints->setPositions(m_joint_keys, m_positions_data->data);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getStanceJointData() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_stance_joints_data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setAutoApply(bool enable) {\n if (enable) {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_auto_apply_flag.store(true);\n m_auto_apply_cv.notify_one();\n } else {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_auto_apply_flag.store(false);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool rd::Locomotion::isAutoApplyEnabled() const {\n return m_auto_apply_flag.load();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::Locomotion::~Locomotion() {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_destroy.store(true);\n m_auto_apply_flag.store(true);\n m_auto_apply_cv.notify_one();\n m_auto_apply_worker.join();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::autoUpdater() {\n boost::mutex::scoped_lock lock(m_auto_apply_mut);\n while (!m_destroy.load()) {\n while (!m_auto_apply_flag.load()) m_auto_apply_cv.wait(lock);\n this->generateStep();\n this->applyPositions();\n usleep(m_auto_update_sleep_time.load());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setAutoApplyUSleepTime(useconds_t us) {\n m_auto_update_sleep_time.store(us);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuseconds_t rd::Locomotion::getAutoApplyUSleepTime() const {\n return m_auto_update_sleep_time.load();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setHeadPositions(double pitch, double yaw) {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_positions_data->data[20] = pitch;\n m_positions_data->data[21] = yaw;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setHeadHardness(double pitch, double yaw) {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_hardness_data->data[20] = pitch;\n m_hardness_data->data[21] = yaw;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getHeadPositions() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_positions_data;\/\/boost::make_shared<SensorData<double> >(m_head_positions, m_clock->getTime());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getHeadHardness() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_hardness_data;\/\/boost::make_shared<SensorData<double> >(m_head_hardness, m_clock->getTime());\n}\n<commit_msg>SOme locomotion fixes<commit_after>\/\/\n\/\/ Created by arssivka on 2\/24\/16.\n\/\/\n\n#include <rd\/hardware\/TypeDefinition.h>\n#include \"rd\/hardware\/Locomotion.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::Locomotion::Locomotion(boost::shared_ptr<Robot> robot)\n : m_meta_gait(new MetaGait), m_step_generator(new StepGenerator(robot, m_meta_gait.get())),\n m_joints(robot->getJoints()), m_clock(robot->getClock()), m_joint_keys(20), m_head_joint_keys(2),\n m_parameter_keys(PARAMETERS_COUNT), m_odometry_keys(ODOMETRY_COUNT), m_auto_apply_flag(false),\n m_auto_apply_worker(boost::bind(&rd::Locomotion::autoUpdater, this)), m_auto_update_sleep_time(0) {\n Gait default_gait(DEFAULT_GAIT);\n m_meta_gait->setStartGait(default_gait);\n m_meta_gait->setNewGaitTarget(default_gait);\n\n m_stance_joints_data = boost::make_shared<SensorData<double> >(*m_step_generator->getDefaultStance(DEFAULT_GAIT),\n m_clock->getTime());\n\n m_parameter_keys[X] = \"X\";\n m_parameter_keys[Y] = \"Y\";\n m_parameter_keys[THETA] = \"THETA\";\n m_parameter_keys[STEP_COUNT] = \"STEP_COUNT\";\n\n for (int i = 0; i < PARAMETERS_COUNT; ++i) {\n m_parameters_key_map.insert(std::make_pair(m_parameter_keys[i], i));\n }\n\n m_odometry_keys[X_OFFSET] = \"X_OFFSET\";\n m_odometry_keys[Y_OFFSET] = \"Y_OFFSET\";\n m_odometry_keys[ROTATION] = \"ROTATION\";\n \n for (int i = 0; i < 20; ++i) {\n const StringKeyVector& keys = m_joints->getKeys();\n m_joint_keys[i] = keys[StepGenerator::NB_WALKING_JOINTS[i]];\n }\n\n m_joint_keys.push_back(\"HEAD_PITCH\");\n m_joint_keys.push_back(\"HEAD_YAW\");\n\n int now = m_clock->getTime();\n m_positions_data = boost::make_shared<SensorData<double> >(m_joint_keys.size(), now);\n m_hardness_data = boost::make_shared<SensorData<double> >(m_joint_keys.size(), now);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst StringKeyVector& rd::Locomotion::getParameterKeys() const {\n return m_parameter_keys;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getSpeedParameters(const StringKeyVector& keys) {\n IntegerKeyVector keys_i(keys.size());\n for (int i = 0; i < keys.size(); ++i) {\n std::map<std::string, int>::const_iterator found = m_parameters_key_map.find(keys[i]);\n if (found == m_parameters_key_map.end())\n return boost::make_shared<SensorData<double> >();\n keys_i[i] = found->second;\n }\n return this->getSpeedParameters(keys_i);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getSpeedParameters(const IntegerKeyVector& keys) {\n SensorData<double>::Ptr data = boost::make_shared<SensorData<double> >(keys.size(), m_clock->getTime());\n boost::lock_guard<boost::mutex> lock(m_access);\n for (int i = 0; i < keys.size(); ++i) {\n switch (keys[i]) {\n case X:\n data->data[i] = m_x;\n break;\n case Y:\n data->data[i] = m_y;\n break;\n case THETA:\n data->data[i] = m_theta;\n break;\n case STEP_COUNT:\n data->data[i] = m_step_count;\n break;\n default:\n return boost::make_shared<SensorData<double> >();\n break;\n }\n }\n return data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setSpeedParameters(const StringKeyVector& keys, const ValuesVector& values) {\n IntegerKeyVector keys_i(keys.size());\n for (int i = 0; i < keys.size(); ++i) {\n const std::map<std::string, int>::const_iterator found = m_parameters_key_map.find(keys[i]);\n if (found == m_parameters_key_map.end())\n return;\n keys_i[i] = found->second;\n }\n this->setSpeedParameters(keys_i, values);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setSpeedParameters(const IntegerKeyVector& keys, const ValuesVector& values) {\n if (keys.empty() || keys.size() != values.size())\n return;\n boost::lock_guard<boost::mutex> lock(m_access);\n m_x = 0.0;\n m_y = 0.0;\n m_theta = 0.0;\n m_step_count = 0;\n for (int i = 0; i < keys.size(); ++i) {\n switch (keys[i]) {\n case X_OFFSET:\n m_x = values[i];\n break;\n case Y_OFFSET:\n m_y = values[i];\n break;\n case THETA:\n m_theta = values[i];\n break;\n case STEP_COUNT:\n m_step_count = (unsigned int) values[i];\n break;\n }\n }\n if (m_step_count > 0) {\n m_step_generator->takeSteps(m_x, m_y, m_theta, m_step_count);\n } else {\n m_step_generator->setSpeed(m_x, m_y, m_theta);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getOdometry() {\n boost::lock_guard<boost::mutex> lock(m_access);\n\n boost::detail::sp_if_not_array<rd::SensorData<double> >::type data = boost::make_shared<SensorData<double> >(m_step_generator->getOdometryUpdate(), m_clock->getTime());\n data->data[1] *= -1.0; \/\/ hack\n return data;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::resetOdometry() {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_step_generator->resetOdometry(0.0, 0.0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setGaitParameters(const double stance_config[WP::LEN_STANCE_CONFIG],\n const double step_config[WP::LEN_STEP_CONFIG],\n const double zmp_config[WP::LEN_ZMP_CONFIG],\n const double joint_hack_config[WP::LEN_HACK_CONFIG],\n const double sensor_config[WP::LEN_SENSOR_CONFIG],\n const double stiffness_config[WP::LEN_STIFF_CONFIG],\n const double odo_config[WP::LEN_ODO_CONFIG],\n const double arm_config[WP::LEN_ARM_CONFIG]) {\n boost::lock_guard<boost::mutex> lock(m_access);\n Gait next_gait(stance_config, step_config, zmp_config, joint_hack_config,\n sensor_config, stiffness_config, odo_config, arm_config);\n m_meta_gait->setNewGaitTarget(next_gait);\n m_stance_joints_data = boost::make_shared<SensorData<double> >(*m_step_generator->getDefaultStance(next_gait),\n m_clock->getTime());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst StringKeyVector& rd::Locomotion::getJointKeys() const {\n return m_joint_keys;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::generateStep() {\n int now = m_clock->getTime();\n boost::lock_guard<boost::mutex> lock(m_access);\n double pitch_p = m_positions_data->data[20];\n double yaw_p = m_positions_data->data[21];\n double pitch_h = m_hardness_data->data[20];\n double yaw_h = m_hardness_data->data[21];\n m_positions_data = boost::make_shared<SensorData<double> >(m_joint_keys.size(), now);\n m_hardness_data = boost::make_shared<SensorData<double> >(m_joint_keys.size(), now);\n m_meta_gait->tick_gait();\n m_step_generator->tick_controller();\n const WalkLegsTuple& legs = m_step_generator->tick_legs();\n const WalkArmsTuple& arms = m_step_generator->tick_arms();\n const ValuesVector& lleg_joints = legs.get<LEFT_FOOT>().get<JOINT_INDEX>();\n const ValuesVector& rleg_joints = legs.get<RIGHT_FOOT>().get<JOINT_INDEX>();\n const ValuesVector& lleg_gains = legs.get<LEFT_FOOT>().get<STIFF_INDEX>();\n const ValuesVector& rleg_gains = legs.get<RIGHT_FOOT>().get<STIFF_INDEX>();\n const ValuesVector& larm_joints = arms.get<LEFT_FOOT>().get<JOINT_INDEX>();\n const ValuesVector& rarm_joints = arms.get<RIGHT_FOOT>().get<JOINT_INDEX>();\n const ValuesVector& larm_gains = arms.get<LEFT_FOOT>().get<STIFF_INDEX>();\n const ValuesVector& rarm_gains = arms.get<RIGHT_FOOT>().get<STIFF_INDEX>();\n std::copy(larm_gains.begin(), larm_gains.end(), m_hardness_data->data.begin() + 0);\n std::copy(lleg_gains.begin(), lleg_gains.end(), m_hardness_data->data.begin() + 4);\n std::copy(rleg_gains.begin(), rleg_gains.end(), m_hardness_data->data.begin() + 10);\n std::copy(rarm_gains.begin(), rarm_gains.end(), m_hardness_data->data.begin() + 16);\n m_hardness_data->data[20] = pitch_h;\n m_hardness_data->data[21] = yaw_h;\n std::copy(larm_joints.begin(), larm_joints.end(), m_positions_data->data.begin() + 0);\n std::copy(lleg_joints.begin(), lleg_joints.end(), m_positions_data->data.begin() + 4);\n std::copy(rleg_joints.begin(), rleg_joints.end(), m_positions_data->data.begin() + 10);\n std::copy(rarm_joints.begin(), rarm_joints.end(), m_positions_data->data.begin() + 16);\n m_positions_data->data[20] = pitch_p;\n m_positions_data->data[21] = yaw_p;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getPositions() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_positions_data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getHardness() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_hardness_data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool rd::Locomotion::isDone() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_step_generator->isDone();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst StringKeyVector& rd::Locomotion::getOdometryKeys() const {\n return m_odometry_keys;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::applyPositions() {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_joints->setHardness(m_joint_keys, m_hardness_data->data);\n m_joints->setPositions(m_joint_keys, m_positions_data->data);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getStanceJointData() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_stance_joints_data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setAutoApply(bool enable) {\n if (enable) {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_auto_apply_flag.store(true);\n m_auto_apply_cv.notify_one();\n } else {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_auto_apply_flag.store(false);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool rd::Locomotion::isAutoApplyEnabled() const {\n return m_auto_apply_flag.load();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::Locomotion::~Locomotion() {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_destroy.store(true);\n m_auto_apply_flag.store(true);\n m_auto_apply_cv.notify_one();\n m_auto_apply_worker.join();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::autoUpdater() {\n boost::mutex::scoped_lock lock(m_auto_apply_mut);\n while (!m_destroy.load()) {\n while (!m_auto_apply_flag.load()) m_auto_apply_cv.wait(lock);\n this->generateStep();\n this->applyPositions();\n usleep(m_auto_update_sleep_time.load());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setAutoApplyUSleepTime(useconds_t us) {\n m_auto_update_sleep_time.store(us);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuseconds_t rd::Locomotion::getAutoApplyUSleepTime() const {\n return m_auto_update_sleep_time.load();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setHeadPositions(double pitch, double yaw) {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_positions_data->data[20] = pitch;\n m_positions_data->data[21] = yaw;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid rd::Locomotion::setHeadHardness(double pitch, double yaw) {\n boost::lock_guard<boost::mutex> lock(m_access);\n m_hardness_data->data[20] = pitch;\n m_hardness_data->data[21] = yaw;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getHeadPositions() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_positions_data;\/\/boost::make_shared<SensorData<double> >(m_head_positions, m_clock->getTime());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrd::SensorData<double>::Ptr rd::Locomotion::getHeadHardness() {\n boost::lock_guard<boost::mutex> lock(m_access);\n return m_hardness_data;\/\/boost::make_shared<SensorData<double> >(m_head_hardness, m_clock->getTime());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017 Hao Sun <sun.me.0207@gmail.com>\n * Copyright 2017 Zongyu Yin <alexyin1012@gmail.com>\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#include <ABELogger.h>\n#include <cstring>\n#include <malloc.h>\n#include <GL\/glew.h>\n#include \"ABETexture.h\"\n\n#define DDS_FILE_MAGIC \"DDS \"\n#define DDS_FOUR_CAPS_DXT1 0x31545844 \/\/ \"DXT1\" in ASCII.\n#define DDS_FOUR_CAPS_DXT3 0x33545844 \/\/ \"DXT3\" in ASCII.\n#define DDS_FOUR_CAPS_DXT5 0x35545844 \/\/ \"DXT5\" in ASCII.\n\nusing abege::ABETexture;\n\nvoid ABETexture::loadBMP(const char *imagePath) {\n\n LOGI(TAG, \"Reading image: \", imagePath);\n\n \/\/ Data read from the header of the BMP file.\n unsigned char header[54];\n unsigned int dataPos;\n unsigned int imageSize;\n unsigned int width, height;\n \/\/ Actual RGB data.\n unsigned char *data;\n\n \/\/ Open the file.\n FILE *file = fopen(imagePath, \"rb\");\n if (!file) {\n LOGE(TAG, \"Failed to open: \", imagePath);\n return;\n }\n\n \/\/ Read the header, i.e. the 54 first bytes.\n\n \/\/ If less than 54 bytes are read, problem.\n if (fread(header, 1, 54, file) != 54) {\n LOGE(TAG, \"Not a correct BMP file\");\n fclose(file);\n return;\n }\n \/\/ A BMP files always begins with \"BM\".\n if (header[0] != 'B' || header[1] != 'M') {\n LOGE(TAG, \"Not a correct BMP file.\");\n fclose(file);\n return;\n }\n \/\/ Make sure this is a 24bpp file.\n if (*(int*)&(header[0x1E]) != 0) {\n LOGE(TAG, \"Not a correct BMP file.\");\n fclose(file);\n return;\n }\n if (*(int*)&(header[0x1C]) != 24) {\n LOGE(TAG, \"Not a correct BMP file.\");\n fclose(file);\n return;\n }\n\n \/\/ Read the information about the image.\n dataPos = *(int*)&(header[0x0A]);\n imageSize = *(int*)&(header[0x22]);\n width = *(int*)&(header[0x12]);\n height = *(int*)&(header[0x16]);\n\n \/\/ Some BMP files are misformatted, guess missing information.\n if (imageSize == 0) {\n imageSize = width * height * 3;\n }\n\n data = new unsigned char[imageSize];\n\n \/\/ Read the actual data from the file into the buffer.\n fread(data, 1, imageSize, file);\n fclose(file);\n glGenTextures(1, &ID);\n\n \/\/ \"Bind\" the newly created texture : all future texture functions will modify this texture.\n glBindTexture(GL_TEXTURE_2D, ID);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);\n\n \/\/ OpenGL has now copied the data. Free our own version.\n delete[] data;\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n glGenerateMipmap(GL_TEXTURE_2D);\n}\n\nvoid ABETexture::loadDDS(const char *imagePath) {\n unsigned char header[124];\n\n FILE *fp;\n\n fp = fopen(imagePath, \"rb\");\n if (fp == NULL){\n LOGE(TAG, \"Failed to open image.\");\n return;\n }\n\n \/\/ Verify the type of the file.\n char magic[4];\n fread(magic, 1, 4, fp);\n if (strncmp(magic, DDS_FILE_MAGIC, 4) != 0) {\n fclose(fp);\n return;\n }\n\n \/\/ Get file header.\n fread(&header, 124, 1, fp);\n\n unsigned int height = *(unsigned int*)&(header[8]);\n unsigned int width = *(unsigned int*)&(header[12]);\n unsigned int linearSize = *(unsigned int*)&(header[16]);\n unsigned int mipMapCount = *(unsigned int*)&(header[24]);\n unsigned int fourCaps = *(unsigned int*)&(header[80]);\n\n\n unsigned char *buffer;\n unsigned int bufferSize;\n\n bufferSize = mipMapCount > 1 ? linearSize * 2 : linearSize;\n buffer = (unsigned char*)malloc(bufferSize * sizeof(unsigned char));\n fread(buffer, 1, bufferSize, fp);\n\n fclose(fp);\n\n unsigned int format;\n switch(fourCaps) {\n case DDS_FOUR_CAPS_DXT1:\n format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;\n break;\n case DDS_FOUR_CAPS_DXT3:\n format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\n break;\n case DDS_FOUR_CAPS_DXT5:\n format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;\n break;\n default:\n free(buffer);\n return;\n }\n\n \/\/ Create one OpenGL texture.\n glGenTextures(1, &ID);\n\n glBindTexture(GL_TEXTURE_2D, ID);\n glPixelStorei(GL_UNPACK_ALIGNMENT,1);\n\n unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;\n unsigned int offset = 0;\n\n \/\/ Load the mipmaps.\n for (unsigned int level = 0; level < mipMapCount && (width || height); ++level) {\n unsigned int size = ((width + 3) \/ 4) * ((height + 3) \/ 4) * blockSize;\n glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height,\n 0, size, buffer + offset);\n\n offset += size;\n width \/= 2;\n height \/= 2;\n\n if (width < 1) {\n width = 1;\n }\n if (height < 1) {\n height = 1;\n }\n }\n\n free(buffer);\n}\n<commit_msg>Remove redundancy.<commit_after>\/*\n * Copyright 2017 Hao Sun <sun.me.0207@gmail.com>\n * Copyright 2017 Zongyu Yin <alexyin1012@gmail.com>\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#include <ABELogger.h>\n#include <cstring>\n#include <malloc.h>\n#include <GL\/glew.h>\n#include \"ABETexture.h\"\n\n#define DDS_FILE_MAGIC \"DDS \"\n#define DDS_FOUR_CAPS_DXT1 0x31545844 \/\/ \"DXT1\" in ASCII.\n#define DDS_FOUR_CAPS_DXT3 0x33545844 \/\/ \"DXT3\" in ASCII.\n#define DDS_FOUR_CAPS_DXT5 0x35545844 \/\/ \"DXT5\" in ASCII.\n\nusing abege::ABETexture;\n\nvoid ABETexture::loadBMP(const char *imagePath) {\n LOGI(TAG, \"Reading image: \", imagePath);\n\n \/\/ Data read from the header of the BMP file.\n unsigned char header[54];\n unsigned int imageSize;\n unsigned int width, height;\n \/\/ Actual RGB data.\n unsigned char *data;\n\n \/\/ Open the file.\n FILE *file = fopen(imagePath, \"rb\");\n if (!file) {\n LOGE(TAG, \"Failed to open: \", imagePath);\n return;\n }\n\n \/\/ Read the header, i.e. the 54 first bytes.\n\n \/\/ If less than 54 bytes are read, problem.\n if (fread(header, 1, 54, file) != 54) {\n LOGE(TAG, \"Not a correct BMP file\");\n fclose(file);\n return;\n }\n \/\/ A BMP files always begins with \"BM\".\n if (header[0] != 'B' || header[1] != 'M') {\n LOGE(TAG, \"Not a correct BMP file.\");\n fclose(file);\n return;\n }\n \/\/ Make sure this is a 24bpp file.\n if (*(int*)&(header[0x1E]) != 0) {\n LOGE(TAG, \"Not a correct BMP file.\");\n fclose(file);\n return;\n }\n if (*(int*)&(header[0x1C]) != 24) {\n LOGE(TAG, \"Not a correct BMP file.\");\n fclose(file);\n return;\n }\n\n \/\/ Read the information about the image.\n imageSize = *(int*)&(header[0x22]);\n width = *(int*)&(header[0x12]);\n height = *(int*)&(header[0x16]);\n\n \/\/ Some BMP files are misformatted, guess missing information.\n if (imageSize == 0) {\n imageSize = width * height * 3;\n }\n\n data = new unsigned char[imageSize];\n\n \/\/ Read the actual data from the file into the buffer.\n fread(data, 1, imageSize, file);\n fclose(file);\n glGenTextures(1, &ID);\n\n \/\/ \"Bind\" the newly created texture : all future texture functions will modify this texture.\n glBindTexture(GL_TEXTURE_2D, ID);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);\n\n \/\/ OpenGL has now copied the data. Free our own version.\n delete[] data;\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n glGenerateMipmap(GL_TEXTURE_2D);\n}\n\nvoid ABETexture::loadDDS(const char *imagePath) {\n unsigned char header[124];\n\n FILE *fp;\n\n fp = fopen(imagePath, \"rb\");\n if (fp == NULL){\n LOGE(TAG, \"Failed to open image.\");\n return;\n }\n\n \/\/ Verify the type of the file.\n char magic[4];\n fread(magic, 1, 4, fp);\n if (strncmp(magic, DDS_FILE_MAGIC, 4) != 0) {\n fclose(fp);\n return;\n }\n\n \/\/ Get file header.\n fread(&header, 124, 1, fp);\n\n unsigned int height = *(unsigned int*)&(header[8]);\n unsigned int width = *(unsigned int*)&(header[12]);\n unsigned int linearSize = *(unsigned int*)&(header[16]);\n unsigned int mipMapCount = *(unsigned int*)&(header[24]);\n unsigned int fourCaps = *(unsigned int*)&(header[80]);\n\n\n unsigned char *buffer;\n unsigned int bufferSize;\n\n bufferSize = mipMapCount > 1 ? linearSize * 2 : linearSize;\n buffer = (unsigned char*)malloc(bufferSize * sizeof(unsigned char));\n fread(buffer, 1, bufferSize, fp);\n\n fclose(fp);\n\n unsigned int format;\n switch(fourCaps) {\n case DDS_FOUR_CAPS_DXT1:\n format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;\n break;\n case DDS_FOUR_CAPS_DXT3:\n format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\n break;\n case DDS_FOUR_CAPS_DXT5:\n format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;\n break;\n default:\n free(buffer);\n return;\n }\n\n \/\/ Create one OpenGL texture.\n glGenTextures(1, &ID);\n\n glBindTexture(GL_TEXTURE_2D, ID);\n glPixelStorei(GL_UNPACK_ALIGNMENT,1);\n\n unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;\n unsigned int offset = 0;\n\n \/\/ Load the mipmaps.\n for (unsigned int level = 0; level < mipMapCount && (width || height); ++level) {\n unsigned int size = ((width + 3) \/ 4) * ((height + 3) \/ 4) * blockSize;\n glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height,\n 0, size, buffer + offset);\n\n offset += size;\n width \/= 2;\n height \/= 2;\n\n if (width < 1) {\n width = 1;\n }\n if (height < 1) {\n height = 1;\n }\n }\n\n free(buffer);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ AudioFileSound.cpp\n\/\/ MWorksCore\n\/\/\n\/\/ Created by Christopher Stawarz on 8\/3\/21.\n\/\/\n\n#include \"AudioFileSound.hpp\"\n\n#include <AVFoundation\/AVAudioFile.h>\n#include <AVFoundation\/AVAudioMixerNode.h>\n\n\nBEGIN_NAMESPACE_MW\n\n\nconst std::string AudioFileSound::PATH(\"path\");\nconst std::string AudioFileSound::AMPLITUDE(\"amplitude\");\n\n\nvoid AudioFileSound::describeComponent(ComponentInfo &info) {\n AudioEngineSound::describeComponent(info);\n \n info.setSignature(\"sound\/audio_file\");\n \n info.addParameter(PATH);\n info.addParameter(AMPLITUDE, \"1.0\");\n}\n\n\nAudioFileSound::AudioFileSound(const ParameterValueMap ¶meters) :\n AudioEngineSound(parameters),\n path(pathFromParameterValue(variableOrText(parameters[PATH]))),\n amplitude(parameters[AMPLITUDE]),\n buffer(nil),\n playerNode(nil)\n{\n @autoreleasepool {\n auto fileURL = [NSURL fileURLWithPath:@(path.string().c_str()) isDirectory:NO];\n NSError *error = nil;\n auto file = [[AVAudioFile alloc] initForReading:fileURL error:&error];\n if (!file) {\n throw SimpleException(M_SYSTEM_MESSAGE_DOMAIN,\n \"Cannot open audio file\",\n error.localizedDescription.UTF8String);\n }\n \n buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:file.processingFormat\n frameCapacity:file.length];\n if (!buffer) {\n throw SimpleException(M_SYSTEM_MESSAGE_DOMAIN, \"Cannot create buffer for reading audio file\");\n }\n if (![file readIntoBuffer:buffer error:&error]) {\n throw SimpleException(M_SYSTEM_MESSAGE_DOMAIN,\n \"Cannot read audio file in to buffer\",\n error.localizedDescription.UTF8String);\n }\n \n playerNode = [[AVAudioPlayerNode alloc] init];\n \n unique_lock engineLock;\n auto engine = getEngine(engineLock);\n [engine attachNode:playerNode];\n [engine connect:playerNode to:engine.mainMixerNode format:nil];\n }\n}\n\n\nAudioFileSound::~AudioFileSound() {\n @autoreleasepool {\n playerNode = nil;\n buffer = nil;\n }\n}\n\n\nbool AudioFileSound::startPlaying() {\n \/\/ Reset the player node\n [playerNode stop];\n \n boost::weak_ptr<AudioFileSound> weakThis(component_shared_from_this<AudioFileSound>());\n auto completionHandler = [weakThis](AVAudioPlayerNodeCompletionCallbackType callbackType) {\n if (callbackType == AVAudioPlayerNodeCompletionDataPlayedBack) {\n if (auto sharedThis = weakThis.lock()) {\n lock_guard lock(sharedThis->mutex);\n sharedThis->didStopPlaying();\n }\n }\n };\n [playerNode scheduleBuffer:buffer\n atTime:nil\n options:0\n completionCallbackType:AVAudioPlayerNodeCompletionDataPlayedBack\n completionHandler:completionHandler];\n \n \/\/ TODO: support dynamic volume changes\n playerNode.volume = amplitude->getValue().getFloat();\n \n [playerNode play];\n return true;\n}\n\n\nbool AudioFileSound::stopPlaying() {\n [playerNode stop];\n return true;\n}\n\n\nbool AudioFileSound::beginPause() {\n [playerNode pause];\n return true;\n}\n\n\nbool AudioFileSound::endPause() {\n [playerNode play];\n return true;\n}\n\n\nEND_NAMESPACE_MW\n<commit_msg>Added some missing @autoreleasepool's to AudioFileSound methods<commit_after>\/\/\n\/\/ AudioFileSound.cpp\n\/\/ MWorksCore\n\/\/\n\/\/ Created by Christopher Stawarz on 8\/3\/21.\n\/\/\n\n#include \"AudioFileSound.hpp\"\n\n#include <AVFoundation\/AVAudioFile.h>\n#include <AVFoundation\/AVAudioMixerNode.h>\n\n\nBEGIN_NAMESPACE_MW\n\n\nconst std::string AudioFileSound::PATH(\"path\");\nconst std::string AudioFileSound::AMPLITUDE(\"amplitude\");\n\n\nvoid AudioFileSound::describeComponent(ComponentInfo &info) {\n AudioEngineSound::describeComponent(info);\n \n info.setSignature(\"sound\/audio_file\");\n \n info.addParameter(PATH);\n info.addParameter(AMPLITUDE, \"1.0\");\n}\n\n\nAudioFileSound::AudioFileSound(const ParameterValueMap ¶meters) :\n AudioEngineSound(parameters),\n path(pathFromParameterValue(variableOrText(parameters[PATH]))),\n amplitude(parameters[AMPLITUDE]),\n buffer(nil),\n playerNode(nil)\n{\n @autoreleasepool {\n auto fileURL = [NSURL fileURLWithPath:@(path.string().c_str()) isDirectory:NO];\n NSError *error = nil;\n auto file = [[AVAudioFile alloc] initForReading:fileURL error:&error];\n if (!file) {\n throw SimpleException(M_SYSTEM_MESSAGE_DOMAIN,\n \"Cannot open audio file\",\n error.localizedDescription.UTF8String);\n }\n \n buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:file.processingFormat\n frameCapacity:file.length];\n if (!buffer) {\n throw SimpleException(M_SYSTEM_MESSAGE_DOMAIN, \"Cannot create buffer for reading audio file\");\n }\n if (![file readIntoBuffer:buffer error:&error]) {\n throw SimpleException(M_SYSTEM_MESSAGE_DOMAIN,\n \"Cannot read audio file in to buffer\",\n error.localizedDescription.UTF8String);\n }\n \n playerNode = [[AVAudioPlayerNode alloc] init];\n \n unique_lock engineLock;\n auto engine = getEngine(engineLock);\n [engine attachNode:playerNode];\n [engine connect:playerNode to:engine.mainMixerNode format:nil];\n }\n}\n\n\nAudioFileSound::~AudioFileSound() {\n @autoreleasepool {\n playerNode = nil;\n buffer = nil;\n }\n}\n\n\nbool AudioFileSound::startPlaying() {\n @autoreleasepool {\n \/\/ Reset the player node\n [playerNode stop];\n \n boost::weak_ptr<AudioFileSound> weakThis(component_shared_from_this<AudioFileSound>());\n auto completionHandler = [weakThis](AVAudioPlayerNodeCompletionCallbackType callbackType) {\n if (callbackType == AVAudioPlayerNodeCompletionDataPlayedBack) {\n if (auto sharedThis = weakThis.lock()) {\n lock_guard lock(sharedThis->mutex);\n sharedThis->didStopPlaying();\n }\n }\n };\n [playerNode scheduleBuffer:buffer\n atTime:nil\n options:0\n completionCallbackType:AVAudioPlayerNodeCompletionDataPlayedBack\n completionHandler:completionHandler];\n \n \/\/ TODO: support dynamic volume changes\n playerNode.volume = amplitude->getValue().getFloat();\n \n [playerNode play];\n return true;\n }\n}\n\n\nbool AudioFileSound::stopPlaying() {\n @autoreleasepool {\n [playerNode stop];\n return true;\n }\n}\n\n\nbool AudioFileSound::beginPause() {\n @autoreleasepool {\n [playerNode pause];\n return true;\n }\n}\n\n\nbool AudioFileSound::endPause() {\n @autoreleasepool {\n [playerNode play];\n return true;\n }\n}\n\n\nEND_NAMESPACE_MW\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 PDFium 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\/\/ Original code copyright 2014 Foxit Software Inc. http:\/\/www.foxitsoftware.com\n\n#include \"core\/fpdfapi\/render\/cpdf_pagerendercache.h\"\n\n#include \"core\/fpdfapi\/page\/cpdf_page.h\"\n#include \"core\/fpdfapi\/page\/pageint.h\"\n#include \"core\/fpdfapi\/parser\/cpdf_document.h\"\n#include \"core\/fpdfapi\/render\/cpdf_rendercontext.h\"\n#include \"core\/fpdfapi\/render\/cpdf_renderstatus.h\"\n#include \"core\/fpdfapi\/render\/render_int.h\"\n\nstruct CACHEINFO {\n uint32_t time;\n CPDF_Stream* pStream;\n};\n\nextern \"C\" {\nstatic int compare(const void* data1, const void* data2) {\n return ((CACHEINFO*)data1)->time - ((CACHEINFO*)data2)->time;\n}\n} \/\/ extern \"C\"\n\nCPDF_PageRenderCache::CPDF_PageRenderCache(CPDF_Page* pPage)\n : m_pPage(pPage),\n m_pCurImageCacheEntry(nullptr),\n m_nTimeCount(0),\n m_nCacheSize(0),\n m_bCurFindCache(false) {}\n\nCPDF_PageRenderCache::~CPDF_PageRenderCache() {\n for (const auto& it : m_ImageCache)\n delete it.second;\n}\nvoid CPDF_PageRenderCache::CacheOptimization(int32_t dwLimitCacheSize) {\n if (m_nCacheSize <= (uint32_t)dwLimitCacheSize)\n return;\n\n size_t nCount = m_ImageCache.size();\n CACHEINFO* pCACHEINFO = FX_Alloc(CACHEINFO, nCount);\n size_t i = 0;\n for (const auto& it : m_ImageCache) {\n pCACHEINFO[i].time = it.second->GetTimeCount();\n pCACHEINFO[i++].pStream = it.second->GetStream();\n }\n FXSYS_qsort(pCACHEINFO, nCount, sizeof(CACHEINFO), compare);\n uint32_t nTimeCount = m_nTimeCount;\n\n \/\/ Check if time value is about to roll over and reset all entries.\n \/\/ The comparision is legal because uint32_t is an unsigned type.\n if (nTimeCount + 1 < nTimeCount) {\n for (i = 0; i < nCount; i++)\n m_ImageCache[pCACHEINFO[i].pStream]->m_dwTimeCount = i;\n m_nTimeCount = nCount;\n }\n\n i = 0;\n while (i + 15 < nCount)\n ClearImageCacheEntry(pCACHEINFO[i++].pStream);\n\n while (i < nCount && m_nCacheSize > (uint32_t)dwLimitCacheSize)\n ClearImageCacheEntry(pCACHEINFO[i++].pStream);\n\n FX_Free(pCACHEINFO);\n}\nvoid CPDF_PageRenderCache::ClearImageCacheEntry(CPDF_Stream* pStream) {\n auto it = m_ImageCache.find(pStream);\n if (it == m_ImageCache.end())\n return;\n\n m_nCacheSize -= it->second->EstimateSize();\n delete it->second;\n m_ImageCache.erase(it);\n}\nuint32_t CPDF_PageRenderCache::EstimateSize() {\n uint32_t dwSize = 0;\n for (const auto& it : m_ImageCache)\n dwSize += it.second->EstimateSize();\n\n m_nCacheSize = dwSize;\n return dwSize;\n}\nvoid CPDF_PageRenderCache::GetCachedBitmap(CPDF_Stream* pStream,\n CFX_DIBSource*& pBitmap,\n CFX_DIBSource*& pMask,\n uint32_t& MatteColor,\n bool bStdCS,\n uint32_t GroupFamily,\n bool bLoadMask,\n CPDF_RenderStatus* pRenderStatus,\n int32_t downsampleWidth,\n int32_t downsampleHeight) {\n CPDF_ImageCacheEntry* pEntry;\n const auto it = m_ImageCache.find(pStream);\n bool bFound = it != m_ImageCache.end();\n if (bFound)\n pEntry = it->second;\n else\n pEntry = new CPDF_ImageCacheEntry(m_pPage->m_pDocument, pStream);\n\n m_nTimeCount++;\n bool bAlreadyCached = pEntry->GetCachedBitmap(\n pBitmap, pMask, MatteColor, m_pPage->m_pPageResources, bStdCS,\n GroupFamily, bLoadMask, pRenderStatus, downsampleWidth, downsampleHeight);\n\n if (!bFound)\n m_ImageCache[pStream] = pEntry;\n\n if (!bAlreadyCached)\n m_nCacheSize += pEntry->EstimateSize();\n}\nbool CPDF_PageRenderCache::StartGetCachedBitmap(\n CPDF_Stream* pStream,\n bool bStdCS,\n uint32_t GroupFamily,\n bool bLoadMask,\n CPDF_RenderStatus* pRenderStatus,\n int32_t downsampleWidth,\n int32_t downsampleHeight) {\n const auto it = m_ImageCache.find(pStream);\n m_bCurFindCache = it != m_ImageCache.end();\n if (m_bCurFindCache) {\n m_pCurImageCacheEntry = it->second;\n } else {\n m_pCurImageCacheEntry =\n new CPDF_ImageCacheEntry(m_pPage->m_pDocument, pStream);\n }\n int ret = m_pCurImageCacheEntry->StartGetCachedBitmap(\n pRenderStatus->m_pFormResource, m_pPage->m_pPageResources, bStdCS,\n GroupFamily, bLoadMask, pRenderStatus, downsampleWidth, downsampleHeight);\n if (ret == 2)\n return true;\n\n m_nTimeCount++;\n if (!m_bCurFindCache)\n m_ImageCache[pStream] = m_pCurImageCacheEntry;\n\n if (!ret)\n m_nCacheSize += m_pCurImageCacheEntry->EstimateSize();\n\n return false;\n}\nbool CPDF_PageRenderCache::Continue(IFX_Pause* pPause) {\n int ret = m_pCurImageCacheEntry->Continue(pPause);\n if (ret == 2)\n return true;\n m_nTimeCount++;\n if (!m_bCurFindCache)\n m_ImageCache[m_pCurImageCacheEntry->GetStream()] = m_pCurImageCacheEntry;\n if (!ret)\n m_nCacheSize += m_pCurImageCacheEntry->EstimateSize();\n return false;\n}\nvoid CPDF_PageRenderCache::ResetBitmap(CPDF_Stream* pStream,\n const CFX_DIBitmap* pBitmap) {\n CPDF_ImageCacheEntry* pEntry;\n const auto it = m_ImageCache.find(pStream);\n if (it == m_ImageCache.end()) {\n if (!pBitmap)\n return;\n pEntry = new CPDF_ImageCacheEntry(m_pPage->m_pDocument, pStream);\n m_ImageCache[pStream] = pEntry;\n } else {\n pEntry = it->second;\n }\n m_nCacheSize -= pEntry->EstimateSize();\n pEntry->Reset(pBitmap);\n m_nCacheSize += pEntry->EstimateSize();\n}\nCPDF_ImageCacheEntry::CPDF_ImageCacheEntry(CPDF_Document* pDoc,\n CPDF_Stream* pStream)\n : m_dwTimeCount(0),\n m_pCurBitmap(nullptr),\n m_pCurMask(nullptr),\n m_MatteColor(0),\n m_pRenderStatus(nullptr),\n m_pDocument(pDoc),\n m_pStream(pStream),\n m_pCachedBitmap(nullptr),\n m_pCachedMask(nullptr),\n m_dwCacheSize(0) {}\nCPDF_ImageCacheEntry::~CPDF_ImageCacheEntry() {\n delete m_pCachedBitmap;\n delete m_pCachedMask;\n}\nvoid CPDF_ImageCacheEntry::Reset(const CFX_DIBitmap* pBitmap) {\n delete m_pCachedBitmap;\n m_pCachedBitmap = nullptr;\n if (pBitmap) {\n m_pCachedBitmap = pBitmap->Clone();\n }\n CalcSize();\n}\n\nstatic uint32_t FPDF_ImageCache_EstimateImageSize(const CFX_DIBSource* pDIB) {\n return pDIB && pDIB->GetBuffer()\n ? (uint32_t)pDIB->GetHeight() * pDIB->GetPitch() +\n (uint32_t)pDIB->GetPaletteSize() * 4\n : 0;\n}\nbool CPDF_ImageCacheEntry::GetCachedBitmap(CFX_DIBSource*& pBitmap,\n CFX_DIBSource*& pMask,\n uint32_t& MatteColor,\n CPDF_Dictionary* pPageResources,\n bool bStdCS,\n uint32_t GroupFamily,\n bool bLoadMask,\n CPDF_RenderStatus* pRenderStatus,\n int32_t downsampleWidth,\n int32_t downsampleHeight) {\n if (m_pCachedBitmap) {\n pBitmap = m_pCachedBitmap;\n pMask = m_pCachedMask;\n MatteColor = m_MatteColor;\n return true;\n }\n if (!pRenderStatus) {\n return false;\n }\n CPDF_RenderContext* pContext = pRenderStatus->GetContext();\n CPDF_PageRenderCache* pPageRenderCache = pContext->GetPageCache();\n m_dwTimeCount = pPageRenderCache->GetTimeCount();\n CPDF_DIBSource* pSrc = new CPDF_DIBSource;\n CPDF_DIBSource* pMaskSrc = nullptr;\n if (!pSrc->Load(m_pDocument, m_pStream, &pMaskSrc, &MatteColor,\n pRenderStatus->m_pFormResource, pPageResources, bStdCS,\n GroupFamily, bLoadMask)) {\n delete pSrc;\n pBitmap = nullptr;\n return false;\n }\n m_MatteColor = MatteColor;\n if (pSrc->GetPitch() * pSrc->GetHeight() < FPDF_HUGE_IMAGE_SIZE) {\n m_pCachedBitmap = pSrc->Clone();\n delete pSrc;\n } else {\n m_pCachedBitmap = pSrc;\n }\n if (pMaskSrc) {\n m_pCachedMask = pMaskSrc->Clone();\n delete pMaskSrc;\n }\n\n pBitmap = m_pCachedBitmap;\n pMask = m_pCachedMask;\n CalcSize();\n return false;\n}\nCFX_DIBSource* CPDF_ImageCacheEntry::DetachBitmap() {\n CFX_DIBSource* pDIBSource = m_pCurBitmap;\n m_pCurBitmap = nullptr;\n return pDIBSource;\n}\nCFX_DIBSource* CPDF_ImageCacheEntry::DetachMask() {\n CFX_DIBSource* pDIBSource = m_pCurMask;\n m_pCurMask = nullptr;\n return pDIBSource;\n}\nint CPDF_ImageCacheEntry::StartGetCachedBitmap(CPDF_Dictionary* pFormResources,\n CPDF_Dictionary* pPageResources,\n bool bStdCS,\n uint32_t GroupFamily,\n bool bLoadMask,\n CPDF_RenderStatus* pRenderStatus,\n int32_t downsampleWidth,\n int32_t downsampleHeight) {\n if (m_pCachedBitmap) {\n m_pCurBitmap = m_pCachedBitmap;\n m_pCurMask = m_pCachedMask;\n return 1;\n }\n if (!pRenderStatus) {\n return 0;\n }\n m_pRenderStatus = pRenderStatus;\n m_pCurBitmap = new CPDF_DIBSource;\n int ret =\n ((CPDF_DIBSource*)m_pCurBitmap)\n ->StartLoadDIBSource(m_pDocument, m_pStream, true, pFormResources,\n pPageResources, bStdCS, GroupFamily, bLoadMask);\n if (ret == 2) {\n return ret;\n }\n if (!ret) {\n delete m_pCurBitmap;\n m_pCurBitmap = nullptr;\n return 0;\n }\n ContinueGetCachedBitmap();\n return 0;\n}\n\nvoid CPDF_ImageCacheEntry::ContinueGetCachedBitmap() {\n m_MatteColor = ((CPDF_DIBSource*)m_pCurBitmap)->GetMatteColor();\n m_pCurMask = ((CPDF_DIBSource*)m_pCurBitmap)->DetachMask();\n CPDF_RenderContext* pContext = m_pRenderStatus->GetContext();\n CPDF_PageRenderCache* pPageRenderCache = pContext->GetPageCache();\n m_dwTimeCount = pPageRenderCache->GetTimeCount();\n m_pCachedBitmap = m_pCurBitmap;\n if (m_pCurMask)\n m_pCachedMask = m_pCurMask;\n else\n m_pCurMask = m_pCachedMask;\n CalcSize();\n}\n\nint CPDF_ImageCacheEntry::Continue(IFX_Pause* pPause) {\n int ret = ((CPDF_DIBSource*)m_pCurBitmap)->ContinueLoadDIBSource(pPause);\n if (ret == 2) {\n return ret;\n }\n if (!ret) {\n delete m_pCurBitmap;\n m_pCurBitmap = nullptr;\n return 0;\n }\n ContinueGetCachedBitmap();\n return 0;\n}\nvoid CPDF_ImageCacheEntry::CalcSize() {\n m_dwCacheSize = FPDF_ImageCache_EstimateImageSize(m_pCachedBitmap) +\n FPDF_ImageCache_EstimateImageSize(m_pCachedMask);\n}\n<commit_msg>Do not clone in CPDF_ImageCacheEntry::GetCachedBitmap<commit_after>\/\/ Copyright 2014 PDFium 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\/\/ Original code copyright 2014 Foxit Software Inc. http:\/\/www.foxitsoftware.com\n\n#include \"core\/fpdfapi\/render\/cpdf_pagerendercache.h\"\n\n#include \"core\/fpdfapi\/page\/cpdf_page.h\"\n#include \"core\/fpdfapi\/page\/pageint.h\"\n#include \"core\/fpdfapi\/parser\/cpdf_document.h\"\n#include \"core\/fpdfapi\/render\/cpdf_rendercontext.h\"\n#include \"core\/fpdfapi\/render\/cpdf_renderstatus.h\"\n#include \"core\/fpdfapi\/render\/render_int.h\"\n\nstruct CACHEINFO {\n uint32_t time;\n CPDF_Stream* pStream;\n};\n\nextern \"C\" {\nstatic int compare(const void* data1, const void* data2) {\n return ((CACHEINFO*)data1)->time - ((CACHEINFO*)data2)->time;\n}\n} \/\/ extern \"C\"\n\nCPDF_PageRenderCache::CPDF_PageRenderCache(CPDF_Page* pPage)\n : m_pPage(pPage),\n m_pCurImageCacheEntry(nullptr),\n m_nTimeCount(0),\n m_nCacheSize(0),\n m_bCurFindCache(false) {}\n\nCPDF_PageRenderCache::~CPDF_PageRenderCache() {\n for (const auto& it : m_ImageCache)\n delete it.second;\n}\nvoid CPDF_PageRenderCache::CacheOptimization(int32_t dwLimitCacheSize) {\n if (m_nCacheSize <= (uint32_t)dwLimitCacheSize)\n return;\n\n size_t nCount = m_ImageCache.size();\n CACHEINFO* pCACHEINFO = FX_Alloc(CACHEINFO, nCount);\n size_t i = 0;\n for (const auto& it : m_ImageCache) {\n pCACHEINFO[i].time = it.second->GetTimeCount();\n pCACHEINFO[i++].pStream = it.second->GetStream();\n }\n FXSYS_qsort(pCACHEINFO, nCount, sizeof(CACHEINFO), compare);\n uint32_t nTimeCount = m_nTimeCount;\n\n \/\/ Check if time value is about to roll over and reset all entries.\n \/\/ The comparision is legal because uint32_t is an unsigned type.\n if (nTimeCount + 1 < nTimeCount) {\n for (i = 0; i < nCount; i++)\n m_ImageCache[pCACHEINFO[i].pStream]->m_dwTimeCount = i;\n m_nTimeCount = nCount;\n }\n\n i = 0;\n while (i + 15 < nCount)\n ClearImageCacheEntry(pCACHEINFO[i++].pStream);\n\n while (i < nCount && m_nCacheSize > (uint32_t)dwLimitCacheSize)\n ClearImageCacheEntry(pCACHEINFO[i++].pStream);\n\n FX_Free(pCACHEINFO);\n}\nvoid CPDF_PageRenderCache::ClearImageCacheEntry(CPDF_Stream* pStream) {\n auto it = m_ImageCache.find(pStream);\n if (it == m_ImageCache.end())\n return;\n\n m_nCacheSize -= it->second->EstimateSize();\n delete it->second;\n m_ImageCache.erase(it);\n}\nuint32_t CPDF_PageRenderCache::EstimateSize() {\n uint32_t dwSize = 0;\n for (const auto& it : m_ImageCache)\n dwSize += it.second->EstimateSize();\n\n m_nCacheSize = dwSize;\n return dwSize;\n}\nvoid CPDF_PageRenderCache::GetCachedBitmap(CPDF_Stream* pStream,\n CFX_DIBSource*& pBitmap,\n CFX_DIBSource*& pMask,\n uint32_t& MatteColor,\n bool bStdCS,\n uint32_t GroupFamily,\n bool bLoadMask,\n CPDF_RenderStatus* pRenderStatus,\n int32_t downsampleWidth,\n int32_t downsampleHeight) {\n CPDF_ImageCacheEntry* pEntry;\n const auto it = m_ImageCache.find(pStream);\n bool bFound = it != m_ImageCache.end();\n if (bFound)\n pEntry = it->second;\n else\n pEntry = new CPDF_ImageCacheEntry(m_pPage->m_pDocument, pStream);\n\n m_nTimeCount++;\n bool bAlreadyCached = pEntry->GetCachedBitmap(\n pBitmap, pMask, MatteColor, m_pPage->m_pPageResources, bStdCS,\n GroupFamily, bLoadMask, pRenderStatus, downsampleWidth, downsampleHeight);\n\n if (!bFound)\n m_ImageCache[pStream] = pEntry;\n\n if (!bAlreadyCached)\n m_nCacheSize += pEntry->EstimateSize();\n}\nbool CPDF_PageRenderCache::StartGetCachedBitmap(\n CPDF_Stream* pStream,\n bool bStdCS,\n uint32_t GroupFamily,\n bool bLoadMask,\n CPDF_RenderStatus* pRenderStatus,\n int32_t downsampleWidth,\n int32_t downsampleHeight) {\n const auto it = m_ImageCache.find(pStream);\n m_bCurFindCache = it != m_ImageCache.end();\n if (m_bCurFindCache) {\n m_pCurImageCacheEntry = it->second;\n } else {\n m_pCurImageCacheEntry =\n new CPDF_ImageCacheEntry(m_pPage->m_pDocument, pStream);\n }\n int ret = m_pCurImageCacheEntry->StartGetCachedBitmap(\n pRenderStatus->m_pFormResource, m_pPage->m_pPageResources, bStdCS,\n GroupFamily, bLoadMask, pRenderStatus, downsampleWidth, downsampleHeight);\n if (ret == 2)\n return true;\n\n m_nTimeCount++;\n if (!m_bCurFindCache)\n m_ImageCache[pStream] = m_pCurImageCacheEntry;\n\n if (!ret)\n m_nCacheSize += m_pCurImageCacheEntry->EstimateSize();\n\n return false;\n}\nbool CPDF_PageRenderCache::Continue(IFX_Pause* pPause) {\n int ret = m_pCurImageCacheEntry->Continue(pPause);\n if (ret == 2)\n return true;\n m_nTimeCount++;\n if (!m_bCurFindCache)\n m_ImageCache[m_pCurImageCacheEntry->GetStream()] = m_pCurImageCacheEntry;\n if (!ret)\n m_nCacheSize += m_pCurImageCacheEntry->EstimateSize();\n return false;\n}\nvoid CPDF_PageRenderCache::ResetBitmap(CPDF_Stream* pStream,\n const CFX_DIBitmap* pBitmap) {\n CPDF_ImageCacheEntry* pEntry;\n const auto it = m_ImageCache.find(pStream);\n if (it == m_ImageCache.end()) {\n if (!pBitmap)\n return;\n pEntry = new CPDF_ImageCacheEntry(m_pPage->m_pDocument, pStream);\n m_ImageCache[pStream] = pEntry;\n } else {\n pEntry = it->second;\n }\n m_nCacheSize -= pEntry->EstimateSize();\n pEntry->Reset(pBitmap);\n m_nCacheSize += pEntry->EstimateSize();\n}\nCPDF_ImageCacheEntry::CPDF_ImageCacheEntry(CPDF_Document* pDoc,\n CPDF_Stream* pStream)\n : m_dwTimeCount(0),\n m_pCurBitmap(nullptr),\n m_pCurMask(nullptr),\n m_MatteColor(0),\n m_pRenderStatus(nullptr),\n m_pDocument(pDoc),\n m_pStream(pStream),\n m_pCachedBitmap(nullptr),\n m_pCachedMask(nullptr),\n m_dwCacheSize(0) {}\nCPDF_ImageCacheEntry::~CPDF_ImageCacheEntry() {\n delete m_pCachedBitmap;\n delete m_pCachedMask;\n}\nvoid CPDF_ImageCacheEntry::Reset(const CFX_DIBitmap* pBitmap) {\n delete m_pCachedBitmap;\n m_pCachedBitmap = nullptr;\n if (pBitmap) {\n m_pCachedBitmap = pBitmap->Clone();\n }\n CalcSize();\n}\n\nstatic uint32_t FPDF_ImageCache_EstimateImageSize(const CFX_DIBSource* pDIB) {\n return pDIB && pDIB->GetBuffer()\n ? (uint32_t)pDIB->GetHeight() * pDIB->GetPitch() +\n (uint32_t)pDIB->GetPaletteSize() * 4\n : 0;\n}\nbool CPDF_ImageCacheEntry::GetCachedBitmap(CFX_DIBSource*& pBitmap,\n CFX_DIBSource*& pMask,\n uint32_t& MatteColor,\n CPDF_Dictionary* pPageResources,\n bool bStdCS,\n uint32_t GroupFamily,\n bool bLoadMask,\n CPDF_RenderStatus* pRenderStatus,\n int32_t downsampleWidth,\n int32_t downsampleHeight) {\n if (m_pCachedBitmap) {\n pBitmap = m_pCachedBitmap;\n pMask = m_pCachedMask;\n MatteColor = m_MatteColor;\n return true;\n }\n if (!pRenderStatus) {\n return false;\n }\n CPDF_RenderContext* pContext = pRenderStatus->GetContext();\n CPDF_PageRenderCache* pPageRenderCache = pContext->GetPageCache();\n m_dwTimeCount = pPageRenderCache->GetTimeCount();\n CPDF_DIBSource* pSrc = new CPDF_DIBSource;\n CPDF_DIBSource* pMaskSrc = nullptr;\n if (!pSrc->Load(m_pDocument, m_pStream, &pMaskSrc, &MatteColor,\n pRenderStatus->m_pFormResource, pPageResources, bStdCS,\n GroupFamily, bLoadMask)) {\n delete pSrc;\n pBitmap = nullptr;\n return false;\n }\n m_MatteColor = MatteColor;\n m_pCachedBitmap = pSrc;\n if (pMaskSrc)\n m_pCachedMask = pMaskSrc;\n\n pBitmap = m_pCachedBitmap;\n pMask = m_pCachedMask;\n CalcSize();\n return false;\n}\n\nCFX_DIBSource* CPDF_ImageCacheEntry::DetachBitmap() {\n CFX_DIBSource* pDIBSource = m_pCurBitmap;\n m_pCurBitmap = nullptr;\n return pDIBSource;\n}\nCFX_DIBSource* CPDF_ImageCacheEntry::DetachMask() {\n CFX_DIBSource* pDIBSource = m_pCurMask;\n m_pCurMask = nullptr;\n return pDIBSource;\n}\nint CPDF_ImageCacheEntry::StartGetCachedBitmap(CPDF_Dictionary* pFormResources,\n CPDF_Dictionary* pPageResources,\n bool bStdCS,\n uint32_t GroupFamily,\n bool bLoadMask,\n CPDF_RenderStatus* pRenderStatus,\n int32_t downsampleWidth,\n int32_t downsampleHeight) {\n if (m_pCachedBitmap) {\n m_pCurBitmap = m_pCachedBitmap;\n m_pCurMask = m_pCachedMask;\n return 1;\n }\n if (!pRenderStatus) {\n return 0;\n }\n m_pRenderStatus = pRenderStatus;\n m_pCurBitmap = new CPDF_DIBSource;\n int ret =\n ((CPDF_DIBSource*)m_pCurBitmap)\n ->StartLoadDIBSource(m_pDocument, m_pStream, true, pFormResources,\n pPageResources, bStdCS, GroupFamily, bLoadMask);\n if (ret == 2) {\n return ret;\n }\n if (!ret) {\n delete m_pCurBitmap;\n m_pCurBitmap = nullptr;\n return 0;\n }\n ContinueGetCachedBitmap();\n return 0;\n}\n\nvoid CPDF_ImageCacheEntry::ContinueGetCachedBitmap() {\n m_MatteColor = ((CPDF_DIBSource*)m_pCurBitmap)->GetMatteColor();\n m_pCurMask = ((CPDF_DIBSource*)m_pCurBitmap)->DetachMask();\n CPDF_RenderContext* pContext = m_pRenderStatus->GetContext();\n CPDF_PageRenderCache* pPageRenderCache = pContext->GetPageCache();\n m_dwTimeCount = pPageRenderCache->GetTimeCount();\n m_pCachedBitmap = m_pCurBitmap;\n if (m_pCurMask)\n m_pCachedMask = m_pCurMask;\n else\n m_pCurMask = m_pCachedMask;\n CalcSize();\n}\n\nint CPDF_ImageCacheEntry::Continue(IFX_Pause* pPause) {\n int ret = ((CPDF_DIBSource*)m_pCurBitmap)->ContinueLoadDIBSource(pPause);\n if (ret == 2) {\n return ret;\n }\n if (!ret) {\n delete m_pCurBitmap;\n m_pCurBitmap = nullptr;\n return 0;\n }\n ContinueGetCachedBitmap();\n return 0;\n}\nvoid CPDF_ImageCacheEntry::CalcSize() {\n m_dwCacheSize = FPDF_ImageCache_EstimateImageSize(m_pCachedBitmap) +\n FPDF_ImageCache_EstimateImageSize(m_pCachedMask);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Application.h\"\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace node;\nusing namespace v8;\n\nnamespace node_iTunes {\n\nstatic Persistent<String> APPLICATION_CLASS_SYMBOL;\nstatic Persistent<String> HOST_SYMBOL;\nstatic Persistent<String> USERNAME_SYMBOL;\nstatic Persistent<String> PASSWORD_SYMBOL;\n\nstatic Persistent<Object> NEW_CHECKER;\n\nstruct create_connection_request {\n char* host;\n char* username;\n char* password;\n v8::Persistent<v8::Function> cb;\n iTunesApplication* iTunesRef;\n};\n\nstruct async_request {\n Persistent<Function> callback;\n Persistent<Object> thisRef;\n iTunesApplication *iTunesRef;\n void *result;\n};\n\n\/\/Persistent<FunctionTemplate> Application::constructor_template;\n\nvoid Application::Init(v8::Handle<Object> target) {\n HandleScope scope;\n\n \/\/ String Constants\n APPLICATION_CLASS_SYMBOL = NODE_PSYMBOL(\"Application\");\n HOST_SYMBOL = NODE_PSYMBOL(\"host\");\n USERNAME_SYMBOL = NODE_PSYMBOL(\"username\");\n PASSWORD_SYMBOL = NODE_PSYMBOL(\"password\");\n\n \/\/ This Object is used in the Application JS constructor to ensure that the\n \/\/ user isn't calling 'new Application', but rather '.createConnection()'.\n NEW_CHECKER = Persistent<Object>::New(Object::New());\n\n \/\/ Set up the 'Application' constructor template\n Local<FunctionTemplate> t = FunctionTemplate::New(New);\n application_constructor_template = Persistent<FunctionTemplate>::New(t);\n application_constructor_template->SetClassName(APPLICATION_CLASS_SYMBOL);\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"run\", GetVolume);\n NODE_SET_PROTOTYPE_METHOD(t, \"isRunning\", IsRunning);\n NODE_SET_PROTOTYPE_METHOD(t, \"quit\", Quit);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"add\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"backTrack\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"convert\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"fastForward\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"nextTrack\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"pause\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"playOnce\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"playpause\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"previousTrack\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"resume\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"rewind\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"stop\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"update\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"eject\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"subscribe\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"updateAllPodcasts\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"updatePodcast\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"openLocation\", GetVolume);\n NODE_SET_PROTOTYPE_METHOD(t, \"getCurrentTrack\", GetCurrentTrack);\n NODE_SET_PROTOTYPE_METHOD(t, \"getSelection\", GetSelection);\n NODE_SET_PROTOTYPE_METHOD(t, \"getVolume\", GetVolume);\n NODE_SET_PROTOTYPE_METHOD(t, \"setVolume\", SetVolume);\n\n NODE_SET_METHOD(target, \"createConnection\", CreateConnection);\n\n target->Set(APPLICATION_CLASS_SYMBOL, application_constructor_template->GetFunction());\n}\n\n\nApplication::Application() {\n}\n\nApplication::~Application() {\n if (iTunesRef) {\n [iTunesRef release];\n }\n iTunesRef = nil;\n}\n\nv8::Handle<Value> Application::New(const Arguments& args) {\n HandleScope scope;\n if (args.Length() != 1 || !NEW_CHECKER->StrictEquals(args[0]->ToObject())) {\n return ThrowException(Exception::TypeError(String::New(\"Use '.createConnection()' to get an Application instance\")));\n }\n\n Application* hw = new Application();\n hw->Wrap(args.This());\n return args.This();\n}\n\nv8::Handle<Value> Application::IsRunning(const Arguments& args) {\n HandleScope scope;\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n iTunesApplication* iTunes = it->iTunesRef;\n v8::Handle<v8::Boolean> result = v8::Boolean::New([iTunes isRunning]);\n return scope.Close(result);\n}\n\nv8::Handle<Value> Application::Quit(const Arguments& args) {\n HandleScope scope;\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n iTunesApplication* iTunes = it->iTunesRef;\n [iTunes quit];\n return Undefined();\n}\n\n\/\/ GetCurrentTrack \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nv8::Handle<Value> Application::GetCurrentTrack(const Arguments& args) {\n HandleScope scope;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(String::New(\"A callback function is required\")));\n }\n\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n\n async_request *ar = (async_request *)malloc(sizeof(struct async_request));\n ar->iTunesRef = it->iTunesRef;\n Local<Function> cb = Local<Function>::Cast(args[0]);\n ar->callback = Persistent<Function>::New(cb);\n ar->thisRef = Persistent<Object>::New(args.This());\n\n eio_custom(EIO_GetCurrentTrack, EIO_PRI_DEFAULT, EIO_AfterGetCurrentTrack, ar);\n ev_ref(EV_DEFAULT_UC);\n\n return scope.Close(Undefined());\n}\n\nint Application::EIO_GetCurrentTrack(eio_req *req) {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n async_request *ar = (async_request *)req->data;\n iTunesTrack *track = [[ar->iTunesRef currentTrack] get];\n [track retain];\n ar->result = (void *)track;\n [pool drain];\n return 0;\n}\n\nint Application::EIO_AfterGetCurrentTrack(eio_req *req) {\n HandleScope scope;\n ev_unref(EV_DEFAULT_UC);\n async_request *ar = (async_request *)req->data;\n\n TryCatch try_catch;\n v8::Handle<Value> argv[2];\n \/\/ TODO: Error Handling\n argv[0] = Null();\n argv[1] = Item::WrapInstance((iTunesItem *)ar->result);\n ar->callback->Call(ar->thisRef, 2, argv);\n\n if (try_catch.HasCaught()) {\n FatalException(try_catch);\n }\n\n ar->callback.Dispose();\n ar->thisRef.Dispose();\n free(ar);\n return 0;\n}\n\n\n\/\/ GetSelection \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nv8::Handle<Value> Application::GetSelection(const Arguments& args) {\n HandleScope scope;\n \/\/Application* it = ObjectWrap::Unwrap<Application>(args.This());\n \/\/iTunesApplication* iTunes = it->iTunesRef;\n \/\/SBElementArray* selection = [iTunes selection];\n \/\/NSArray* selection = [[iTunes selection] get];\n \/\/Local<Object> Track::WrapInstance\n return Undefined();\n}\n\n\/\/ GetVolume \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nv8::Handle<Value> Application::GetVolume(const Arguments& args) {\n HandleScope scope;\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n iTunesApplication* iTunes = it->iTunesRef;\n Local<Integer> result = Integer::New([iTunes soundVolume]);\n return scope.Close(result);\n}\n\n\/\/ SetVolume \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nv8::Handle<Value> Application::SetVolume(const Arguments& args) {\n HandleScope scope;\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n iTunesApplication* iTunes = it->iTunesRef;\n int val = args[0]->ToInteger()->Int32Value();\n [iTunes setSoundVolume:val];\n Local<Integer> result = Integer::New([iTunes soundVolume]);\n return scope.Close(result);\n}\n\n\/\/ Begins asynchronously creating a new Application instance. This should be\n\/\/ done on the thread pool, since the SBApplication constructor methods can\n\/\/ potentially block for a very long time (especially if a modal dialog is\n\/\/ raised for user credentials).\nv8::Handle<Value> Application::CreateConnection(const Arguments& args) {\n HandleScope scope;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(String::New(\"A callback function is required\")));\n }\n\n create_connection_request* ccr = (create_connection_request *) malloc(sizeof(struct create_connection_request));\n ccr->host = NULL;\n ccr->username = NULL;\n ccr->password = NULL;\n\n int cbIndex = 0;\n if (args[1]->IsFunction()) {\n cbIndex = 1;\n Local<Object> options = args[0]->ToObject();\n if (options->Has(HOST_SYMBOL)) {\n String::Utf8Value hostValue(options->Get(HOST_SYMBOL));\n char* hostStr = (char*)malloc(strlen(*hostValue) + 1);\n strcpy(hostStr, *hostValue);\n ccr->host = hostStr;\n } else {\n return ThrowException(Exception::TypeError(String::New(\"The 'host' property is required when an 'options' Object is given\")));\n }\n if (options->Has(USERNAME_SYMBOL)) {\n String::Utf8Value unValue(options->Get(USERNAME_SYMBOL));\n char* unStr = (char*)malloc(strlen(*unValue) + 1);\n strcpy(unStr, *unValue);\n ccr->username = unStr;\n }\n if (options->Has(PASSWORD_SYMBOL)) {\n String::Utf8Value pwValue(options->Get(PASSWORD_SYMBOL));\n char* pwStr = (char*)malloc(strlen(*pwValue) + 1);\n strcpy(pwStr, *pwValue);\n ccr->password = pwStr;\n }\n }\n Local<Function> cb = Local<Function>::Cast(args[cbIndex]);\n ccr->cb = Persistent<Function>::New(cb);\n\n eio_custom(EIO_CreateConnection, EIO_PRI_DEFAULT, EIO_AfterCreateConnection, ccr);\n ev_ref(EV_DEFAULT_UC);\n return Undefined();\n}\n\n\/\/ Creates the SBApplication instance. This is called on the thread pool since\n\/\/ it can block for a long time.\nint Application::EIO_CreateConnection (eio_req *req) {\n NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];\n struct create_connection_request * ccr = (struct create_connection_request *)req->data;\n if (ccr->host != NULL) {\n \/\/printf(\"host: %s\\n\", ccr->host);\n NSString* urlStr = @\"eppc:\/\/\";\n if (ccr->username != NULL && ccr->password != NULL) {\n \/\/printf(\"username: %s\\n\", ccr->username);\n \/\/printf(\"password: %s\\n\", ccr->password);\n NSString* unString = [NSString stringWithCString: ((const char*)ccr->username) encoding: NSUTF8StringEncoding ];\n urlStr = [urlStr stringByAppendingString: [unString stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding ]];\n urlStr = [urlStr stringByAppendingString: @\":\" ];\n NSString* pwString = [NSString stringWithCString: ((const char*)ccr->password) encoding: NSUTF8StringEncoding ];\n urlStr = [urlStr stringByAppendingString: [pwString stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding ]];\n urlStr = [urlStr stringByAppendingString: @\"@\" ];\n free(ccr->password);\n free(ccr->username);\n }\n urlStr = [urlStr stringByAppendingString: [NSString stringWithCString: ((const char*)ccr->host) encoding: NSUTF8StringEncoding ]];\n urlStr = [urlStr stringByAppendingString: @\"\/iTunes\" ];\n \/\/NSLog(@\"%@\", urlStr);\n NSURL* url = [NSURL URLWithString: urlStr];\n ccr->iTunesRef = [SBApplication applicationWithURL: url];\n free(ccr->host);\n } else {\n \/\/ If no 'options' object was provided, then simply connect to the local\n \/\/ iTunes installation. No credentials are required for this mode.\n ccr->iTunesRef = [SBApplication applicationWithBundleIdentifier:@\"com.apple.iTunes\"];\n }\n [pool drain];\n return 0;\n}\n\nint Application::EIO_AfterCreateConnection (eio_req *req) {\n HandleScope scope;\n ev_unref(EV_DEFAULT_UC);\n struct create_connection_request * ccr = (struct create_connection_request *)req->data;\n Local<Value> argv[2];\n argv[0] = Local<Value>::New(Null());\n\n \/\/ We need to create an instance of the JS 'Application' class\n v8::Handle<Value> constructor_args[1];\n constructor_args[0] = NEW_CHECKER;\n Local<Object> app = application_constructor_template->GetFunction()->NewInstance(1, constructor_args);\n Application* it = ObjectWrap::Unwrap<Application>(app);\n it->iTunesRef = ccr->iTunesRef;\n argv[1] = app;\n\n \/\/argv[2] = String::New(sr->name);\n TryCatch try_catch;\n ccr->cb->Call(Context::GetCurrent()->Global(), 2, argv);\n if (try_catch.HasCaught()) {\n FatalException(try_catch);\n }\n ccr->cb.Dispose();\n free(ccr);\n return 0;\n}\n\n} \/\/ namespace node_iTunes\n<commit_msg>`Application#getVolume()` is now async.<commit_after>#include \"Application.h\"\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace node;\nusing namespace v8;\n\nnamespace node_iTunes {\n\nstatic Persistent<String> APPLICATION_CLASS_SYMBOL;\nstatic Persistent<String> HOST_SYMBOL;\nstatic Persistent<String> USERNAME_SYMBOL;\nstatic Persistent<String> PASSWORD_SYMBOL;\n\nstatic Persistent<Object> NEW_CHECKER;\n\nstruct create_connection_request {\n char* host;\n char* username;\n char* password;\n v8::Persistent<v8::Function> cb;\n iTunesApplication* iTunesRef;\n};\n\nstruct async_request {\n Persistent<Function> callback;\n Persistent<Object> thisRef;\n iTunesApplication *iTunesRef;\n void *result;\n};\n\n\/\/Persistent<FunctionTemplate> Application::constructor_template;\n\nvoid Application::Init(v8::Handle<Object> target) {\n HandleScope scope;\n\n \/\/ String Constants\n APPLICATION_CLASS_SYMBOL = NODE_PSYMBOL(\"Application\");\n HOST_SYMBOL = NODE_PSYMBOL(\"host\");\n USERNAME_SYMBOL = NODE_PSYMBOL(\"username\");\n PASSWORD_SYMBOL = NODE_PSYMBOL(\"password\");\n\n \/\/ This Object is used in the Application JS constructor to ensure that the\n \/\/ user isn't calling 'new Application', but rather '.createConnection()'.\n NEW_CHECKER = Persistent<Object>::New(Object::New());\n\n \/\/ Set up the 'Application' constructor template\n Local<FunctionTemplate> t = FunctionTemplate::New(New);\n application_constructor_template = Persistent<FunctionTemplate>::New(t);\n application_constructor_template->SetClassName(APPLICATION_CLASS_SYMBOL);\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"run\", GetVolume);\n NODE_SET_PROTOTYPE_METHOD(t, \"isRunning\", IsRunning);\n NODE_SET_PROTOTYPE_METHOD(t, \"quit\", Quit);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"add\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"backTrack\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"convert\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"fastForward\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"nextTrack\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"pause\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"playOnce\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"playpause\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"previousTrack\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"resume\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"rewind\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"stop\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"update\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"eject\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"subscribe\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"updateAllPodcasts\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"updatePodcast\", GetVolume);\n \/\/NODE_SET_PROTOTYPE_METHOD(t, \"openLocation\", GetVolume);\n NODE_SET_PROTOTYPE_METHOD(t, \"getCurrentTrack\", GetCurrentTrack);\n NODE_SET_PROTOTYPE_METHOD(t, \"getSelection\", GetSelection);\n NODE_SET_PROTOTYPE_METHOD(t, \"getVolume\", GetVolume);\n NODE_SET_PROTOTYPE_METHOD(t, \"setVolume\", SetVolume);\n\n NODE_SET_METHOD(target, \"createConnection\", CreateConnection);\n\n target->Set(APPLICATION_CLASS_SYMBOL, application_constructor_template->GetFunction());\n}\n\n\nApplication::Application() {\n}\n\nApplication::~Application() {\n if (iTunesRef) {\n [iTunesRef release];\n }\n iTunesRef = nil;\n}\n\nv8::Handle<Value> Application::New(const Arguments& args) {\n HandleScope scope;\n if (args.Length() != 1 || !NEW_CHECKER->StrictEquals(args[0]->ToObject())) {\n return ThrowException(Exception::TypeError(String::New(\"Use '.createConnection()' to get an Application instance\")));\n }\n\n Application* hw = new Application();\n hw->Wrap(args.This());\n return args.This();\n}\n\nv8::Handle<Value> Application::IsRunning(const Arguments& args) {\n HandleScope scope;\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n iTunesApplication* iTunes = it->iTunesRef;\n v8::Handle<v8::Boolean> result = v8::Boolean::New([iTunes isRunning]);\n return scope.Close(result);\n}\n\nv8::Handle<Value> Application::Quit(const Arguments& args) {\n HandleScope scope;\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n iTunesApplication* iTunes = it->iTunesRef;\n [iTunes quit];\n return Undefined();\n}\n\n\/\/ GetCurrentTrack \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nv8::Handle<Value> Application::GetCurrentTrack(const Arguments& args) {\n HandleScope scope;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(String::New(\"A callback function is required\")));\n }\n\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n\n async_request *ar = (async_request *)malloc(sizeof(struct async_request));\n ar->iTunesRef = it->iTunesRef;\n Local<Function> cb = Local<Function>::Cast(args[0]);\n ar->callback = Persistent<Function>::New(cb);\n ar->thisRef = Persistent<Object>::New(args.This());\n\n eio_custom(EIO_GetCurrentTrack, EIO_PRI_DEFAULT, EIO_AfterGetCurrentTrack, ar);\n ev_ref(EV_DEFAULT_UC);\n\n return scope.Close(Undefined());\n}\n\nint Application::EIO_GetCurrentTrack(eio_req *req) {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n async_request *ar = (async_request *)req->data;\n iTunesTrack *track = [[ar->iTunesRef currentTrack] get];\n [track retain];\n ar->result = (void *)track;\n [pool drain];\n return 0;\n}\n\nint Application::EIO_AfterGetCurrentTrack(eio_req *req) {\n HandleScope scope;\n ev_unref(EV_DEFAULT_UC);\n async_request *ar = (async_request *)req->data;\n\n TryCatch try_catch;\n v8::Handle<Value> argv[2];\n \/\/ TODO: Error Handling\n argv[0] = Null();\n argv[1] = Item::WrapInstance((iTunesItem *)ar->result);\n ar->callback->Call(ar->thisRef, 2, argv);\n\n if (try_catch.HasCaught()) {\n FatalException(try_catch);\n }\n\n ar->callback.Dispose();\n ar->thisRef.Dispose();\n free(ar);\n return 0;\n}\n\n\n\/\/ GetSelection \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nv8::Handle<Value> Application::GetSelection(const Arguments& args) {\n HandleScope scope;\n \/\/Application* it = ObjectWrap::Unwrap<Application>(args.This());\n \/\/iTunesApplication* iTunes = it->iTunesRef;\n \/\/SBElementArray* selection = [iTunes selection];\n \/\/NSArray* selection = [[iTunes selection] get];\n \/\/Local<Object> Track::WrapInstance\n return Undefined();\n}\n\n\/\/ GetVolume \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nv8::Handle<Value> Application::GetVolume(const Arguments& args) {\n HandleScope scope;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(String::New(\"A callback function is required\")));\n }\n\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n\n async_request *ar = (async_request *)malloc(sizeof(struct async_request));\n ar->iTunesRef = it->iTunesRef;\n Local<Function> cb = Local<Function>::Cast(args[0]);\n ar->callback = Persistent<Function>::New(cb);\n ar->thisRef = Persistent<Object>::New(args.This());\n\n eio_custom(EIO_GetVolume, EIO_PRI_DEFAULT, EIO_AfterGetVolume, ar);\n ev_ref(EV_DEFAULT_UC);\n return scope.Close(Undefined());\n}\n\nint Application::EIO_GetVolume(eio_req *req) {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n async_request *ar = (async_request *)req->data;\n NSInteger vol = [ar->iTunesRef soundVolume];\n req->result = vol;\n [pool drain];\n return 0;\n}\n\nint Application::EIO_AfterGetVolume(eio_req *req) {\n HandleScope scope;\n ev_unref(EV_DEFAULT_UC);\n async_request *ar = (async_request *)req->data;\n\n TryCatch try_catch;\n v8::Handle<Value> argv[2];\n \/\/ TODO: Error Handling\n argv[0] = Null();\n argv[1] = Integer::New(req->result);\n ar->callback->Call(ar->thisRef, 2, argv);\n\n if (try_catch.HasCaught()) {\n FatalException(try_catch);\n }\n\n ar->callback.Dispose();\n ar->thisRef.Dispose();\n free(ar);\n return 0;\n}\n\n\/\/ SetVolume \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nv8::Handle<Value> Application::SetVolume(const Arguments& args) {\n HandleScope scope;\n Application* it = ObjectWrap::Unwrap<Application>(args.This());\n iTunesApplication* iTunes = it->iTunesRef;\n int val = args[0]->ToInteger()->Int32Value();\n [iTunes setSoundVolume:val];\n Local<Integer> result = Integer::New([iTunes soundVolume]);\n return scope.Close(result);\n}\n\n\/\/ Begins asynchronously creating a new Application instance. This should be\n\/\/ done on the thread pool, since the SBApplication constructor methods can\n\/\/ potentially block for a very long time (especially if a modal dialog is\n\/\/ raised for user credentials).\nv8::Handle<Value> Application::CreateConnection(const Arguments& args) {\n HandleScope scope;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(String::New(\"A callback function is required\")));\n }\n\n create_connection_request* ccr = (create_connection_request *) malloc(sizeof(struct create_connection_request));\n ccr->host = NULL;\n ccr->username = NULL;\n ccr->password = NULL;\n\n int cbIndex = 0;\n if (args[1]->IsFunction()) {\n cbIndex = 1;\n Local<Object> options = args[0]->ToObject();\n if (options->Has(HOST_SYMBOL)) {\n String::Utf8Value hostValue(options->Get(HOST_SYMBOL));\n char* hostStr = (char*)malloc(strlen(*hostValue) + 1);\n strcpy(hostStr, *hostValue);\n ccr->host = hostStr;\n } else {\n return ThrowException(Exception::TypeError(String::New(\"The 'host' property is required when an 'options' Object is given\")));\n }\n if (options->Has(USERNAME_SYMBOL)) {\n String::Utf8Value unValue(options->Get(USERNAME_SYMBOL));\n char* unStr = (char*)malloc(strlen(*unValue) + 1);\n strcpy(unStr, *unValue);\n ccr->username = unStr;\n }\n if (options->Has(PASSWORD_SYMBOL)) {\n String::Utf8Value pwValue(options->Get(PASSWORD_SYMBOL));\n char* pwStr = (char*)malloc(strlen(*pwValue) + 1);\n strcpy(pwStr, *pwValue);\n ccr->password = pwStr;\n }\n }\n Local<Function> cb = Local<Function>::Cast(args[cbIndex]);\n ccr->cb = Persistent<Function>::New(cb);\n\n eio_custom(EIO_CreateConnection, EIO_PRI_DEFAULT, EIO_AfterCreateConnection, ccr);\n ev_ref(EV_DEFAULT_UC);\n return Undefined();\n}\n\n\/\/ Creates the SBApplication instance. This is called on the thread pool since\n\/\/ it can block for a long time.\nint Application::EIO_CreateConnection (eio_req *req) {\n NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];\n struct create_connection_request * ccr = (struct create_connection_request *)req->data;\n if (ccr->host != NULL) {\n \/\/printf(\"host: %s\\n\", ccr->host);\n NSString* urlStr = @\"eppc:\/\/\";\n if (ccr->username != NULL && ccr->password != NULL) {\n \/\/printf(\"username: %s\\n\", ccr->username);\n \/\/printf(\"password: %s\\n\", ccr->password);\n NSString* unString = [NSString stringWithCString: ((const char*)ccr->username) encoding: NSUTF8StringEncoding ];\n urlStr = [urlStr stringByAppendingString: [unString stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding ]];\n urlStr = [urlStr stringByAppendingString: @\":\" ];\n NSString* pwString = [NSString stringWithCString: ((const char*)ccr->password) encoding: NSUTF8StringEncoding ];\n urlStr = [urlStr stringByAppendingString: [pwString stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding ]];\n urlStr = [urlStr stringByAppendingString: @\"@\" ];\n free(ccr->password);\n free(ccr->username);\n }\n urlStr = [urlStr stringByAppendingString: [NSString stringWithCString: ((const char*)ccr->host) encoding: NSUTF8StringEncoding ]];\n urlStr = [urlStr stringByAppendingString: @\"\/iTunes\" ];\n \/\/NSLog(@\"%@\", urlStr);\n NSURL* url = [NSURL URLWithString: urlStr];\n ccr->iTunesRef = [SBApplication applicationWithURL: url];\n free(ccr->host);\n } else {\n \/\/ If no 'options' object was provided, then simply connect to the local\n \/\/ iTunes installation. No credentials are required for this mode.\n ccr->iTunesRef = [SBApplication applicationWithBundleIdentifier:@\"com.apple.iTunes\"];\n }\n [pool drain];\n return 0;\n}\n\nint Application::EIO_AfterCreateConnection (eio_req *req) {\n HandleScope scope;\n ev_unref(EV_DEFAULT_UC);\n struct create_connection_request * ccr = (struct create_connection_request *)req->data;\n Local<Value> argv[2];\n argv[0] = Local<Value>::New(Null());\n\n \/\/ We need to create an instance of the JS 'Application' class\n v8::Handle<Value> constructor_args[1];\n constructor_args[0] = NEW_CHECKER;\n Local<Object> app = application_constructor_template->GetFunction()->NewInstance(1, constructor_args);\n Application* it = ObjectWrap::Unwrap<Application>(app);\n it->iTunesRef = ccr->iTunesRef;\n argv[1] = app;\n\n \/\/argv[2] = String::New(sr->name);\n TryCatch try_catch;\n ccr->cb->Call(Context::GetCurrent()->Global(), 2, argv);\n if (try_catch.HasCaught()) {\n FatalException(try_catch);\n }\n ccr->cb.Dispose();\n free(ccr);\n return 0;\n}\n\n} \/\/ namespace node_iTunes\n<|endoftext|>"} {"text":"<commit_before>\/*\n postmortem.c - output of debug info on sketch crash\n Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.\n This file is part of the esp8266 core for Arduino environment.\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n\n#include <stdint.h>\n#include <stddef.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include \"debug.h\"\n#include \"ets_sys.h\"\n#include \"user_interface.h\"\n#include \"esp8266_peri.h\"\n#include \"cont.h\"\n#include \"pgmspace.h\"\n#include \"gdb_hooks.h\"\n#include \"StackThunk.h\"\n\nextern \"C\" {\n\nextern void __real_system_restart_local();\n\n\/\/ These will be pointers to PROGMEM const strings\nstatic const char* s_panic_file = 0;\nstatic int s_panic_line = 0;\nstatic const char* s_panic_func = 0;\nstatic const char* s_panic_what = 0;\n\nstatic bool s_abort_called = false;\nstatic const char* s_unhandled_exception = NULL;\n\nvoid abort() __attribute__((noreturn));\nstatic void uart_write_char_d(char c);\nstatic void uart0_write_char_d(char c);\nstatic void uart1_write_char_d(char c);\nstatic void print_stack(uint32_t start, uint32_t end);\n\n\/\/ using numbers different from \"REASON_\" in user_interface.h (=0..6)\nenum rst_reason_sw\n{\n REASON_USER_SWEXCEPTION_RST = 254\n};\nstatic int s_user_reset_reason = REASON_DEFAULT_RST;\n\n\/\/ From UMM, the last caller of a malloc\/realloc\/calloc which failed:\nextern void *umm_last_fail_alloc_addr;\nextern int umm_last_fail_alloc_size;\n#if defined(DEBUG_ESP_OOM)\nextern const char *umm_last_fail_alloc_file;\nextern int umm_last_fail_alloc_line;\n#endif\n\nstatic void raise_exception() __attribute__((noreturn));\n\nextern void __custom_crash_callback( struct rst_info * rst_info, uint32_t stack, uint32_t stack_end ) {\n (void) rst_info;\n (void) stack;\n (void) stack_end;\n}\n\nextern void custom_crash_callback( struct rst_info * rst_info, uint32_t stack, uint32_t stack_end ) __attribute__ ((weak, alias(\"__custom_crash_callback\")));\n\n\n\/\/ Prints need to use our library function to allow for file and function\n\/\/ to be safely accessed from flash. This function encapsulates snprintf()\n\/\/ [which by definition will 0-terminate] and dumping to the UART\nstatic void ets_printf_P(const char *str, ...) {\n char destStr[160];\n char *c = destStr;\n va_list argPtr;\n va_start(argPtr, str);\n vsnprintf(destStr, sizeof(destStr), str, argPtr);\n va_end(argPtr);\n while (*c) {\n ets_putc(*(c++));\n }\n}\n\nvoid __wrap_system_restart_local() {\n register uint32_t sp asm(\"a1\");\n uint32_t sp_dump = sp;\n\n struct rst_info rst_info;\n memset(&rst_info, 0, sizeof(rst_info));\n if (s_user_reset_reason == REASON_DEFAULT_RST)\n {\n system_rtc_mem_read(0, &rst_info, sizeof(rst_info));\n if (rst_info.reason != REASON_SOFT_WDT_RST &&\n rst_info.reason != REASON_EXCEPTION_RST &&\n rst_info.reason != REASON_WDT_RST)\n {\n rst_info.reason = REASON_DEFAULT_RST;\n }\n }\n else\n rst_info.reason = s_user_reset_reason;\n\n ets_install_putc1(&uart_write_char_d);\n\n if (s_panic_line) {\n ets_printf_P(PSTR(\"\\nPanic %S:%d %S\"), s_panic_file, s_panic_line, s_panic_func);\n if (s_panic_what) {\n ets_printf_P(PSTR(\": Assertion '%S' failed.\"), s_panic_what);\n }\n ets_putc('\\n');\n }\n else if (s_unhandled_exception) {\n ets_printf_P(PSTR(\"\\nUnhandled C++ exception: %S\\n\"), s_unhandled_exception);\n }\n else if (s_abort_called) {\n ets_printf_P(PSTR(\"\\nAbort called\\n\"));\n }\n else if (rst_info.reason == REASON_EXCEPTION_RST) {\n ets_printf_P(PSTR(\"\\nException (%d):\\nepc1=0x%08x epc2=0x%08x epc3=0x%08x excvaddr=0x%08x depc=0x%08x\\n\"),\n rst_info.exccause, rst_info.epc1, rst_info.epc2, rst_info.epc3, rst_info.excvaddr, rst_info.depc);\n }\n else if (rst_info.reason == REASON_SOFT_WDT_RST) {\n ets_printf_P(PSTR(\"\\nSoft WDT reset\\n\"));\n }\n else {\n ets_printf_P(PSTR(\"\\nGeneric Reset\\n\"));\n }\n\n uint32_t cont_stack_start = (uint32_t) &(g_pcont->stack);\n uint32_t cont_stack_end = (uint32_t) g_pcont->stack_end;\n uint32_t stack_end;\n\n \/\/ amount of stack taken by interrupt or exception handler\n \/\/ and everything up to __wrap_system_restart_local\n \/\/ (determined empirically, might break)\n uint32_t offset = 0;\n if (rst_info.reason == REASON_SOFT_WDT_RST) {\n offset = 0x1b0;\n }\n else if (rst_info.reason == REASON_EXCEPTION_RST) {\n offset = 0x1a0;\n }\n else if (rst_info.reason == REASON_WDT_RST) {\n offset = 0x10;\n }\n\n ets_printf_P(PSTR(\"\\n>>>stack>>>\\n\"));\n\n if (sp_dump > stack_thunk_get_stack_bot() && sp_dump <= stack_thunk_get_stack_top()) {\n \/\/ BearSSL we dump the BSSL second stack and then reset SP back to the main cont stack\n ets_printf_P(PSTR(\"\\nctx: bearssl\\nsp: %08x end: %08x offset: %04x\\n\"), sp_dump, stack_thunk_get_stack_top(), offset);\n print_stack(sp_dump + offset, stack_thunk_get_stack_top());\n offset = 0; \/\/ No offset needed anymore, the exception info was stored in the bssl stack\n sp_dump = stack_thunk_get_cont_sp();\n }\n\n if (sp_dump > cont_stack_start && sp_dump < cont_stack_end) {\n ets_printf_P(PSTR(\"\\nctx: cont\\n\"));\n stack_end = cont_stack_end;\n }\n else {\n ets_printf_P(PSTR(\"\\nctx: sys\\n\"));\n stack_end = 0x3fffffb0;\n \/\/ it's actually 0x3ffffff0, but the stuff below ets_run\n \/\/ is likely not really relevant to the crash\n }\n\n ets_printf_P(PSTR(\"sp: %08x end: %08x offset: %04x\\n\"), sp_dump, stack_end, offset);\n\n print_stack(sp_dump + offset, stack_end);\n\n ets_printf_P(PSTR(\"<<<stack<<<\\n\"));\n\n \/\/ Use cap-X formatting to ensure the standard EspExceptionDecoder doesn't match the address\n if (umm_last_fail_alloc_addr) {\n#if defined(DEBUG_ESP_OOM)\n ets_printf_P(PSTR(\"\\nlast failed alloc call: %08X(%d)@%S:%d\\n\"),\n (uint32_t)umm_last_fail_alloc_addr, umm_last_fail_alloc_size,\n umm_last_fail_alloc_file, umm_last_fail_alloc_line);\n#else\n ets_printf_P(PSTR(\"\\nlast failed alloc call: %08X(%d)\\n\"), (uint32_t)umm_last_fail_alloc_addr, umm_last_fail_alloc_size);\n#endif\n }\n\n custom_crash_callback( &rst_info, sp_dump + offset, stack_end );\n\n ets_delay_us(10000);\n __real_system_restart_local();\n}\n\n\nstatic void print_stack(uint32_t start, uint32_t end) {\n for (uint32_t pos = start; pos < end; pos += 0x10) {\n uint32_t* values = (uint32_t*)(pos);\n\n \/\/ rough indicator: stack frames usually have SP saved as the second word\n bool looksLikeStackFrame = (values[2] == pos + 0x10);\n\n ets_printf_P(PSTR(\"%08x: %08x %08x %08x %08x %c\\n\"),\n pos, values[0], values[1], values[2], values[3], (looksLikeStackFrame)?'<':' ');\n }\n}\n\nstatic void uart_write_char_d(char c) {\n uart0_write_char_d(c);\n uart1_write_char_d(c);\n}\n\nstatic void uart0_write_char_d(char c) {\n while (((USS(0) >> USTXC) & 0xff)) { }\n\n if (c == '\\n') {\n USF(0) = '\\r';\n }\n USF(0) = c;\n}\n\nstatic void uart1_write_char_d(char c) {\n while (((USS(1) >> USTXC) & 0xff) >= 0x7e) { }\n\n if (c == '\\n') {\n USF(1) = '\\r';\n }\n USF(1) = c;\n}\n\nstatic void raise_exception() {\n if (gdb_present())\n __asm__ __volatile__ (\"syscall\"); \/\/ triggers GDB when enabled\n\n s_user_reset_reason = REASON_USER_SWEXCEPTION_RST;\n ets_printf_P(PSTR(\"\\nUser exception (panic\/abort\/assert)\"));\n __wrap_system_restart_local();\n\n while (1); \/\/ never reached, needed to satisfy \"noreturn\" attribute\n}\n\nvoid abort() {\n s_abort_called = true;\n raise_exception();\n}\n\nvoid __unhandled_exception(const char *str) {\n s_unhandled_exception = str;\n raise_exception();\n}\n\nvoid __assert_func(const char *file, int line, const char *func, const char *what) {\n s_panic_file = file;\n s_panic_line = line;\n s_panic_func = func;\n s_panic_what = what;\n gdb_do_break(); \/* if GDB is not present, this is a no-op *\/\n raise_exception();\n}\n\nvoid __panic_func(const char* file, int line, const char* func) {\n s_panic_file = file;\n s_panic_line = line;\n s_panic_func = func;\n s_panic_what = 0;\n gdb_do_break(); \/* if GDB is not present, this is a no-op *\/\n raise_exception();\n}\n\n};\n<commit_msg>Updated stack offsets for postmortem stack dump. Changed ets_putc to ets_uart_putc1 to better newline handling.<commit_after>\/*\n postmortem.c - output of debug info on sketch crash\n Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.\n This file is part of the esp8266 core for Arduino environment.\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n\n#include <stdint.h>\n#include <stddef.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include \"debug.h\"\n#include \"ets_sys.h\"\n#include \"user_interface.h\"\n#include \"esp8266_peri.h\"\n#include \"cont.h\"\n#include \"pgmspace.h\"\n#include \"gdb_hooks.h\"\n#include \"StackThunk.h\"\n\nextern \"C\" {\n\nextern void __real_system_restart_local();\n\n\/\/ These will be pointers to PROGMEM const strings\nstatic const char* s_panic_file = 0;\nstatic int s_panic_line = 0;\nstatic const char* s_panic_func = 0;\nstatic const char* s_panic_what = 0;\n\nstatic bool s_abort_called = false;\nstatic const char* s_unhandled_exception = NULL;\n\nvoid abort() __attribute__((noreturn));\nstatic void uart_write_char_d(char c);\nstatic void uart0_write_char_d(char c);\nstatic void uart1_write_char_d(char c);\nstatic void print_stack(uint32_t start, uint32_t end);\n\n\/\/ using numbers different from \"REASON_\" in user_interface.h (=0..6)\nenum rst_reason_sw\n{\n REASON_USER_SWEXCEPTION_RST = 254\n};\nstatic int s_user_reset_reason = REASON_DEFAULT_RST;\n\n\/\/ From UMM, the last caller of a malloc\/realloc\/calloc which failed:\nextern void *umm_last_fail_alloc_addr;\nextern int umm_last_fail_alloc_size;\n#if defined(DEBUG_ESP_OOM)\nextern const char *umm_last_fail_alloc_file;\nextern int umm_last_fail_alloc_line;\n#endif\n\nstatic void raise_exception() __attribute__((noreturn));\n\nextern void __custom_crash_callback( struct rst_info * rst_info, uint32_t stack, uint32_t stack_end ) {\n (void) rst_info;\n (void) stack;\n (void) stack_end;\n}\n\nextern void custom_crash_callback( struct rst_info * rst_info, uint32_t stack, uint32_t stack_end ) __attribute__ ((weak, alias(\"__custom_crash_callback\")));\n\n\n\/\/ Prints need to use our library function to allow for file and function\n\/\/ to be safely accessed from flash. This function encapsulates snprintf()\n\/\/ [which by definition will 0-terminate] and dumping to the UART\nstatic void ets_printf_P(const char *str, ...) {\n char destStr[160];\n char *c = destStr;\n va_list argPtr;\n va_start(argPtr, str);\n vsnprintf(destStr, sizeof(destStr), str, argPtr);\n va_end(argPtr);\n while (*c) {\n ets_uart_putc1(*(c++));\n }\n}\n\nvoid __wrap_system_restart_local() {\n register uint32_t sp asm(\"a1\");\n uint32_t sp_dump = sp;\n\n struct rst_info rst_info;\n memset(&rst_info, 0, sizeof(rst_info));\n if (s_user_reset_reason == REASON_DEFAULT_RST)\n {\n system_rtc_mem_read(0, &rst_info, sizeof(rst_info));\n if (rst_info.reason != REASON_SOFT_WDT_RST &&\n rst_info.reason != REASON_EXCEPTION_RST &&\n rst_info.reason != REASON_WDT_RST)\n {\n rst_info.reason = REASON_DEFAULT_RST;\n }\n }\n else\n rst_info.reason = s_user_reset_reason;\n\n ets_install_putc1(&uart_write_char_d);\n\n if (s_panic_line) {\n ets_printf_P(PSTR(\"\\nPanic %S:%d %S\"), s_panic_file, s_panic_line, s_panic_func);\n if (s_panic_what) {\n ets_printf_P(PSTR(\": Assertion '%S' failed.\"), s_panic_what);\n }\n ets_putc('\\n');\n }\n else if (s_unhandled_exception) {\n ets_printf_P(PSTR(\"\\nUnhandled C++ exception: %S\\n\"), s_unhandled_exception);\n }\n else if (s_abort_called) {\n ets_printf_P(PSTR(\"\\nAbort called\\n\"));\n }\n else if (rst_info.reason == REASON_EXCEPTION_RST) {\n ets_printf_P(PSTR(\"\\nException (%d):\\nepc1=0x%08x epc2=0x%08x epc3=0x%08x excvaddr=0x%08x depc=0x%08x\\n\"),\n rst_info.exccause, rst_info.epc1, rst_info.epc2, rst_info.epc3, rst_info.excvaddr, rst_info.depc);\n }\n else if (rst_info.reason == REASON_SOFT_WDT_RST) {\n ets_printf_P(PSTR(\"\\nSoft WDT reset\\n\"));\n }\n else {\n ets_printf_P(PSTR(\"\\nGeneric Reset\\n\"));\n }\n\n uint32_t cont_stack_start = (uint32_t) &(g_pcont->stack);\n uint32_t cont_stack_end = (uint32_t) g_pcont->stack_end;\n uint32_t stack_end;\n\n \/\/ amount of stack taken by interrupt or exception handler\n \/\/ and everything up to __wrap_system_restart_local\n \/\/ (determined empirically, might break)\n uint32_t offset = 0;\n if (rst_info.reason == REASON_SOFT_WDT_RST) {\n offset = 0x1a0;\n }\n else if (rst_info.reason == REASON_EXCEPTION_RST) {\n offset = 0x190;\n }\n else if (rst_info.reason == REASON_WDT_RST) {\n offset = 0x10;\n }\n\n ets_printf_P(PSTR(\"\\n>>>stack>>>\\n\"));\n\n if (sp_dump > stack_thunk_get_stack_bot() && sp_dump <= stack_thunk_get_stack_top()) {\n \/\/ BearSSL we dump the BSSL second stack and then reset SP back to the main cont stack\n ets_printf_P(PSTR(\"\\nctx: bearssl\\nsp: %08x end: %08x offset: %04x\\n\"), sp_dump, stack_thunk_get_stack_top(), offset);\n print_stack(sp_dump + offset, stack_thunk_get_stack_top());\n offset = 0; \/\/ No offset needed anymore, the exception info was stored in the bssl stack\n sp_dump = stack_thunk_get_cont_sp();\n }\n\n if (sp_dump > cont_stack_start && sp_dump < cont_stack_end) {\n ets_printf_P(PSTR(\"\\nctx: cont\\n\"));\n stack_end = cont_stack_end;\n }\n else {\n ets_printf_P(PSTR(\"\\nctx: sys\\n\"));\n stack_end = 0x3fffffb0;\n \/\/ it's actually 0x3ffffff0, but the stuff below ets_run\n \/\/ is likely not really relevant to the crash\n }\n\n ets_printf_P(PSTR(\"sp: %08x end: %08x offset: %04x\\n\"), sp_dump, stack_end, offset);\n\n print_stack(sp_dump + offset, stack_end);\n\n ets_printf_P(PSTR(\"<<<stack<<<\\n\"));\n\n \/\/ Use cap-X formatting to ensure the standard EspExceptionDecoder doesn't match the address\n if (umm_last_fail_alloc_addr) {\n#if defined(DEBUG_ESP_OOM)\n ets_printf_P(PSTR(\"\\nlast failed alloc call: %08X(%d)@%S:%d\\n\"),\n (uint32_t)umm_last_fail_alloc_addr, umm_last_fail_alloc_size,\n umm_last_fail_alloc_file, umm_last_fail_alloc_line);\n#else\n ets_printf_P(PSTR(\"\\nlast failed alloc call: %08X(%d)\\n\"), (uint32_t)umm_last_fail_alloc_addr, umm_last_fail_alloc_size);\n#endif\n }\n\n custom_crash_callback( &rst_info, sp_dump + offset, stack_end );\n\n ets_delay_us(10000);\n __real_system_restart_local();\n}\n\n\nstatic void print_stack(uint32_t start, uint32_t end) {\n for (uint32_t pos = start; pos < end; pos += 0x10) {\n uint32_t* values = (uint32_t*)(pos);\n\n \/\/ rough indicator: stack frames usually have SP saved as the second word\n bool looksLikeStackFrame = (values[2] == pos + 0x10);\n\n ets_printf_P(PSTR(\"%08x: %08x %08x %08x %08x %c\\n\"),\n pos, values[0], values[1], values[2], values[3], (looksLikeStackFrame)?'<':' ');\n }\n}\n\nstatic void uart_write_char_d(char c) {\n uart0_write_char_d(c);\n uart1_write_char_d(c);\n}\n\nstatic void uart0_write_char_d(char c) {\n while (((USS(0) >> USTXC) & 0xff)) { }\n\n if (c == '\\n') {\n USF(0) = '\\r';\n }\n USF(0) = c;\n}\n\nstatic void uart1_write_char_d(char c) {\n while (((USS(1) >> USTXC) & 0xff) >= 0x7e) { }\n\n if (c == '\\n') {\n USF(1) = '\\r';\n }\n USF(1) = c;\n}\n\nstatic void raise_exception() {\n if (gdb_present())\n __asm__ __volatile__ (\"syscall\"); \/\/ triggers GDB when enabled\n\n s_user_reset_reason = REASON_USER_SWEXCEPTION_RST;\n ets_printf_P(PSTR(\"\\nUser exception (panic\/abort\/assert)\"));\n __wrap_system_restart_local();\n\n while (1); \/\/ never reached, needed to satisfy \"noreturn\" attribute\n}\n\nvoid abort() {\n s_abort_called = true;\n raise_exception();\n}\n\nvoid __unhandled_exception(const char *str) {\n s_unhandled_exception = str;\n raise_exception();\n}\n\nvoid __assert_func(const char *file, int line, const char *func, const char *what) {\n s_panic_file = file;\n s_panic_line = line;\n s_panic_func = func;\n s_panic_what = what;\n gdb_do_break(); \/* if GDB is not present, this is a no-op *\/\n raise_exception();\n}\n\nvoid __panic_func(const char* file, int line, const char* func) {\n s_panic_file = file;\n s_panic_line = line;\n s_panic_func = func;\n s_panic_what = 0;\n gdb_do_break(); \/* if GDB is not present, this is a no-op *\/\n raise_exception();\n}\n\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"test\/test_syscoin_services.h\"\n#include \"utiltime.h\"\n#include \"rpcserver.h\"\n#include <boost\/test\/unit_test.hpp>\nBOOST_GLOBAL_FIXTURE( SyscoinTestingSetup );\n\nBOOST_FIXTURE_TEST_SUITE (syscoin_offer_tests, BasicSyscoinTestingSetup)\n\n\nBOOST_AUTO_TEST_CASE (generate_offernew)\n{\n\tUniValue r;\n\n\tGenerateBlocks(200);\n\tGenerateBlocks(200, \"node2\");\n\tGenerateBlocks(200, \"node3\");\n\n\tAliasNew(\"node1\", \"selleralias\", \"changeddata1\");\n\n\t\/\/ generate a good offer\n\tstring offerguid = OfferNew(\"node1\", \"selleralias\", \"category\", \"title\", \"100\", \"0.05\", \"description\", \"USD\");\n\n\t\/\/ should fail: generate an offer with unknown alias\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew fooalias category title 100 0.05 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with negative quantity\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title -1 0.05 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with zero quantity\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title 0 0.05 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with zero price\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title 100 0 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with negative price\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title 100 -0.05 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer too-large category\n\tstring s256bytes = \"SfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsDfdfddz\";\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias \" + s256bytes + \" title 100 0.05 description USD\"), runtime_error);\t\n\n\t\/\/ should fail: generate an offer too-large title\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category \" + s256bytes + \" 100 0.05 description USD\"), runtime_error);\t\n\n\t\/\/ should fail: generate an offer too-large description\n\tstring s1024bytes = \"asdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfssdsfsdfsdfsdfsdfsdsdfdfsdfsdfsdfsdz\";\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title 100 0.05 \" + s1024bytes + \" USD\"), runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE (generate_offerupdate)\n{\n\tUniValue r;\n\t\n\tGenerateBlocks(200);\n\tGenerateBlocks(200, \"node2\");\n\tGenerateBlocks(200, \"node3\");\n\n\tAliasNew(\"node1\", \"selleralias2\", \"changeddata1\");\n\n\t\/\/ generate a good offer\n\tstring offerguid = OfferNew(\"node1\", \"selleralias2\", \"category\", \"title\", \"100\", \"0.05\", \"description\", \"USD\");\n\n\t\/\/ perform a valid update\n\tOfferUpdate(\"node1\", \"selleralias2\", offerguid, \"category\", \"titlenew\", \"90\", \"0.15\", \"descriptionnew\");\n\n\t\/\/ should fail: offer cannot be updated by someone other than owner\n\tBOOST_CHECK_THROW(r = CallRPC(\"node2\", \"offerupdate selleralias2 \" + offerguid + \" category title 90 0.15 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with unknown alias\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate fooalias \" + offerguid + \" category title 90 0.15 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with negative quantity\n\t\/\/BOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category title -1 0.05 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with zero quantity\n\t\/\/BOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category title 0 0.05 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with zero price\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category title 90 0 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with negative price\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category title 90 -0.05 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer too-large category\n\tstring s256bytes = \"SfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsDfdfddz\";\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" \" + s256bytes + \" title 90 0.15 description\"), runtime_error);\t\n\n\t\/\/ should fail: generate an offer too-large title\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category \" + s256bytes + \" 90 0.15 description\"), runtime_error);\t\n\n\t\/\/ should fail: generate an offer too-large description\n\tstring s1024bytes = \"asdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfssdsfsdfsdfsdfsdfsdsdfdfsdfsdfsdfsdz\";\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category title 90 0.15 \" + s1024bytes), runtime_error);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END ()<commit_msg>updated offernew test<commit_after>#include \"test\/test_syscoin_services.h\"\n#include \"utiltime.h\"\n#include \"rpcserver.h\"\n#include <boost\/test\/unit_test.hpp>\nBOOST_GLOBAL_FIXTURE( SyscoinTestingSetup );\n\nBOOST_FIXTURE_TEST_SUITE (syscoin_offer_tests, BasicSyscoinTestingSetup)\n\n\nBOOST_AUTO_TEST_CASE (generate_offernew)\n{\n\tUniValue r;\n\n\tGenerateBlocks(200);\n\tGenerateBlocks(200, \"node2\");\n\tGenerateBlocks(200, \"node3\");\n\n\tAliasNew(\"node1\", \"selleralias\", \"changeddata1\");\n\n\t\/\/ generate a good offer\n\tstring offerguid = OfferNew(\"node1\", \"selleralias\", \"category\", \"title\", \"100\", \"0.05\", \"description\", \"USD\");\n\n\t\/\/ should fail: generate an offer with unknown alias\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew fooalias category title 100 0.05 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with negative quantity\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title -2 0.05 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with zero price\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title 100 0 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with negative price\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title 100 -0.05 description USD\"), runtime_error);\n\n\t\/\/ should fail: generate an offer too-large category\n\tstring s256bytes = \"SfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsDfdfddz\";\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias \" + s256bytes + \" title 100 0.05 description USD\"), runtime_error);\t\n\n\t\/\/ should fail: generate an offer too-large title\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category \" + s256bytes + \" 100 0.05 description USD\"), runtime_error);\t\n\n\t\/\/ should fail: generate an offer too-large description\n\tstring s1024bytes = \"asdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfssdsfsdfsdfsdfsdfsdsdfdfsdfsdfsdfsdz\";\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offernew selleralias category title 100 0.05 \" + s1024bytes + \" USD\"), runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE (generate_offerupdate)\n{\n\tUniValue r;\n\t\n\tGenerateBlocks(200);\n\tGenerateBlocks(200, \"node2\");\n\tGenerateBlocks(200, \"node3\");\n\n\tAliasNew(\"node1\", \"selleralias2\", \"changeddata1\");\n\n\t\/\/ generate a good offer\n\tstring offerguid = OfferNew(\"node1\", \"selleralias2\", \"category\", \"title\", \"100\", \"0.05\", \"description\", \"USD\");\n\n\t\/\/ perform a valid update\n\tOfferUpdate(\"node1\", \"selleralias2\", offerguid, \"category\", \"titlenew\", \"90\", \"0.15\", \"descriptionnew\");\n\n\t\/\/ should fail: offer cannot be updated by someone other than owner\n\tBOOST_CHECK_THROW(r = CallRPC(\"node2\", \"offerupdate selleralias2 \" + offerguid + \" category title 90 0.15 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with unknown alias\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate fooalias \" + offerguid + \" category title 90 0.15 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with zero price\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category title 90 0 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer with negative price\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category title 90 -0.05 description\"), runtime_error);\n\n\t\/\/ should fail: generate an offer too-large category\n\tstring s256bytes = \"SfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsDfdfddz\";\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" \" + s256bytes + \" title 90 0.15 description\"), runtime_error);\t\n\n\t\/\/ should fail: generate an offer too-large title\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category \" + s256bytes + \" 90 0.15 description\"), runtime_error);\t\n\n\t\/\/ should fail: generate an offer too-large description\n\tstring s1024bytes = \"asdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfssdsfsdfsdfsdfsdfsdsdfdfsdfsdfsdfsdz\";\n\tBOOST_CHECK_THROW(r = CallRPC(\"node1\", \"offerupdate selleralias2 \" + offerguid + \" category title 90 0.15 \" + s1024bytes), runtime_error);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END ()<|endoftext|>"} {"text":"<commit_before>#include <xercesc\/dom\/DOM.hpp>\n#include <xercesc\/sax\/HandlerBase.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/dom\/DOMDocument.hpp>\n#include <xercesc\/dom\/DOMDocumentType.hpp>\n#include <xercesc\/dom\/DOMElement.hpp>\n#include <xercesc\/dom\/DOMImplementation.hpp>\n#include <xercesc\/dom\/DOMImplementationLS.hpp>\n#include <xercesc\/dom\/DOMNodeIterator.hpp>\n#include <xercesc\/dom\/DOMNodeList.hpp>\n#include <xercesc\/dom\/DOMText.hpp>\n#include <xercesc\/dom\/DOMTreeWalker.hpp>\n#include <xercesc\/parsers\/XercesdomParser.hpp>\n#include <xercesc\/util\/XMLUni.hpp>\n\n#include <string>\n#include <stdexcept>\n\n#include <iostream>\n\nusing namespace std;\nusing namespace xercesc;\n\nclass SimpleErrorHandler : public ErrorHandler\n{\nprivate:\n\tvoid printError(const SAXParseException& ex)\n\t{\n\t\tchar* message = XMLString::transcode(ex.getMessage());\n\t\t\/\/fprintf(stderr, \"Error: Line %llu, column %llu: %s\\n\", ex.getColumnNumber(), ex.getLineNumber(), message);\n\t\tXMLString::release(&message);\n\t}\n\npublic:\n\tvoid error(const SAXParseException& ex)\n\t{\n\t\tprintError(ex);\n\t}\n\n\tvoid fatalError(const SAXParseException& ex)\n\t{\n\t\tprintError(ex);\n\t}\n\n\tvoid resetErrors()\n\t{\n\t}\n\n\tvoid warning(const SAXParseException& ex)\n\t{\n\t\tprintError(ex);\n\t}\n};\n\nint main(int argc, const char *argv[])\n{\n\tif (2 != argc)\n\t{\n\t\tfprintf(stderr, \"ERROR! Correct usage: ex2 <xml file>\\n\");\n\t\treturn -1;\n\t}\n\n\tXMLPlatformUtils::Initialize();\n\n\tXercesDOMParser *domParser = new XercesDOMParser();\n\tif (NULL == domParser->loadGrammar(\"measured-1-1-0.xsd\", Grammar::SchemaGrammarType))\n\t{\n\t\tfprintf(stderr, \"Unable to load schema measured-1-1-0.xsd\\n\");\n\t\treturn 0;\n\t}\n\n\tSimpleErrorHandler parserErrorHandler;\n\n\tdomParser->setErrorHandler(&parserErrorHandler);\n\tdomParser->setValidationScheme(XercesDOMParser::Val_Always);\n\tdomParser->setDoNamespaces(true);\n\tdomParser->setDoSchema(true);\n\t\/\/domParser->setValidationConstraintFatal(true);\n\n\tdomParser->parse(argv[1]);\n\tif (0 == domParser->getErrorCount())\n\t{\n\t\tfprintf(stderr, \"Validated sucessfully.\\n\");\n\t}\n\telse\n\t{\n\t\tfprintf(stderr, \"Validated NOT sucessfully.\\n\");\n\t}\n\n\tDOMDocument *document = domParser->getDocument();\n\tDOMElement *rootNode = document->getDocumentElement();\n\tDOMTreeWalker *treeWalker =\tdocument->createTreeWalker(rootNode, DOMNodeFilter::SHOW_ALL, NULL, true);\n\tDOMNode *currentNode = NULL;\n\n\tfor (currentNode = treeWalker->getCurrentNode(); currentNode != NULL; currentNode = treeWalker->nextNode())\n\t{\n\t\tstring str(XMLString::transcode(currentNode->getNodeName()));\n\t\tif (str.compare(\"amountOfPower\")==0)\n\t\t{\n\t\t\tchar * amountOfPowerValue = XMLString::transcode(currentNode->getAttributes()->getNamedItem(XMLString::transcode(\"value\"))->getNodeValue());\n\t\t\tchar * hour = XMLString::transcode(currentNode->getParentNode()->getAttributes()->getNamedItem(XMLString::transcode(\"hour\"))->getNodeValue());\n\t\t\tchar * date = XMLString::transcode(currentNode->getParentNode()->getParentNode()->getParentNode()->getAttributes()->getNamedItem(XMLString::transcode(\"date\"))->getNodeValue());\n\t\t\tfprintf(stdout, \"%s; %s; %s\\n\", date, hour, amountOfPowerValue);\n\t\t}\n\t}\n\n\tdelete domParser;\n\tXMLPlatformUtils::Terminate();\n\treturn 0;\n}\n<commit_msg>Added doxygen comments<commit_after>\/*\n * @file \tex2.cpp\n * @details \tThis file is the solution to exercise 2.\n * @author \tAlexander Rettkowski\n * @date \t29.04.2017\n *\/\n\n#include <xercesc\/dom\/DOM.hpp>\n#include <xercesc\/sax\/HandlerBase.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/dom\/DOMDocument.hpp>\n#include <xercesc\/dom\/DOMDocumentType.hpp>\n#include <xercesc\/dom\/DOMElement.hpp>\n#include <xercesc\/dom\/DOMImplementation.hpp>\n#include <xercesc\/dom\/DOMImplementationLS.hpp>\n#include <xercesc\/dom\/DOMNodeIterator.hpp>\n#include <xercesc\/dom\/DOMNodeList.hpp>\n#include <xercesc\/dom\/DOMText.hpp>\n#include <xercesc\/dom\/DOMTreeWalker.hpp>\n#include <xercesc\/parsers\/XercesdomParser.hpp>\n#include <xercesc\/util\/XMLUni.hpp>\n\n#include <string>\n#include <stdexcept>\n\n#include <iostream>\n\nusing namespace std;\nusing namespace xercesc;\n\nclass SimpleErrorHandler : public ErrorHandler\n{\nprivate:\n\t\/**\n \t * Prints an error message from an exception while parsing.\n \t * @param ex The caught exception.\n \t*\/\n\tvoid printError(const SAXParseException& ex)\n\t{\n\t\tchar* message = XMLString::transcode(ex.getMessage());\n\t\t\/\/fprintf(stderr, \"Error: Line %llu, column %llu: %s\\n\", ex.getColumnNumber(), ex.getLineNumber(), message);\n\t\tXMLString::release(&message);\n\t}\n\npublic:\n\tvoid error(const SAXParseException& ex)\n\t{\n\t\tprintError(ex);\n\t}\n\n\tvoid fatalError(const SAXParseException& ex)\n\t{\n\t\tprintError(ex);\n\t}\n\n\tvoid resetErrors()\n\t{\n\t}\n\n\tvoid warning(const SAXParseException& ex)\n\t{\n\t\tprintError(ex);\n\t}\n};\n\n\/**\n * The main function that reads in a file and processes it.\n * @param argc Number of command line arguments.\n * @param *argv a pointer to the array of command line arguments.\n *\/\nint main(int argc, const char *argv[])\n{\n\tif (2 != argc)\n\t{\n\t\tfprintf(stderr, \"ERROR! Correct usage: ex2 <xml file>\\n\");\n\t\treturn -1;\n\t}\n\n\tXMLPlatformUtils::Initialize();\n\n\tXercesDOMParser *domParser = new XercesDOMParser();\n\tif (NULL == domParser->loadGrammar(\"measured-1-1-0.xsd\", Grammar::SchemaGrammarType))\n\t{\n\t\tfprintf(stderr, \"Unable to load schema measured-1-1-0.xsd\\n\");\n\t\treturn 0;\n\t}\n\n\tSimpleErrorHandler parserErrorHandler;\n\n\tdomParser->setErrorHandler(&parserErrorHandler);\n\tdomParser->setValidationScheme(XercesDOMParser::Val_Always);\n\tdomParser->setDoNamespaces(true);\n\tdomParser->setDoSchema(true);\n\t\/\/domParser->setValidationConstraintFatal(true);\n\n\tdomParser->parse(argv[1]);\n\tif (0 == domParser->getErrorCount())\n\t{\n\t\tfprintf(stderr, \"Validated sucessfully.\\n\");\n\t}\n\telse\n\t{\n\t\tfprintf(stderr, \"Validated NOT sucessfully.\\n\");\n\t}\n\n\tDOMDocument *document = domParser->getDocument();\n\tDOMElement *rootNode = document->getDocumentElement();\n\tDOMTreeWalker *treeWalker =\tdocument->createTreeWalker(rootNode, DOMNodeFilter::SHOW_ALL, NULL, true);\n\tDOMNode *currentNode = NULL;\n\n\tfor (currentNode = treeWalker->getCurrentNode(); currentNode != NULL; currentNode = treeWalker->nextNode())\n\t{\n\t\tstring str(XMLString::transcode(currentNode->getNodeName()));\n\t\tif (str.compare(\"amountOfPower\")==0)\n\t\t{\n\t\t\tchar * amountOfPowerValue = XMLString::transcode(currentNode->getAttributes()->getNamedItem(XMLString::transcode(\"value\"))->getNodeValue());\n\t\t\tchar * hour = XMLString::transcode(currentNode->getParentNode()->getAttributes()->getNamedItem(XMLString::transcode(\"hour\"))->getNodeValue());\n\t\t\tchar * date = XMLString::transcode(currentNode->getParentNode()->getParentNode()->getParentNode()->getAttributes()->getNamedItem(XMLString::transcode(\"date\"))->getNodeValue());\n\t\t\tfprintf(stdout, \"%s; %s; %s\\n\", date, hour, amountOfPowerValue);\n\t\t}\n\t}\n\n\tdelete domParser;\n\tXMLPlatformUtils::Terminate();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\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#include \"modules\/canbus\/vehicle\/gem\/protocol\/wheel_speed_rpt_7a.h\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace apollo {\nnamespace canbus {\nnamespace gem {\n\nclass Wheelspeedrpt7aTest : public ::testing::Test {\n public:\n virtual void SetUp() {}\n};\n\nTEST_F(Wheelspeedrpt7aTest, reset) {\n Wheelspeedrpt7a wheelspeed;\n int32_t length = 8;\n ChassisDetail chassis_detail;\n uint8_t bytes[8] = {0, 0};\n\n bytes[0] = 0b11111100;\n bytes[1] = 0b11111110;\n bytes[2] = 0b11111110;\n bytes[3] = 0b11111110;\n bytes[4] = 0b11111110;\n bytes[5] = 0b11111110;\n bytes[6] = 0b11111110;\n bytes[7] = 0b11111110;\n\n wheelspeed.Parse(bytes, length, &chassis_detail);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_rear_right(), -2.58);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_rear_left(), -2.6);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_front_right(), -2.6);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_front_left(), -2.6);\n}\n\n} \/\/ namespace gem\n} \/\/ namespace canbus\n} \/\/ namespace apollo<commit_msg>modify test for wheel_speed_rpt_7a<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\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#include \"modules\/canbus\/vehicle\/gem\/protocol\/wheel_speed_rpt_7a.h\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace apollo {\nnamespace canbus {\nnamespace gem {\n\nclass Wheelspeedrpt7aTest : public ::testing::Test {\n public:\n virtual void SetUp() {}\n};\n\nTEST_F(Wheelspeedrpt7aTest, reset) {\n Wheelspeedrpt7a wheelspeed;\n int32_t length = 8;\n ChassisDetail chassis_detail;\n uint8_t bytes[8] = {0, 0};uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14}; \n\n wheelspeed.Parse(bytes, length, &chassis_detail);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_rear_right(), 258);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_rear_left(), 772);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_front_right(), 4370);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_front_left(), 4884);\n}\n\n} \/\/ namespace gem\n} \/\/ namespace canbus\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tルネサス RX 選択 @n\r\n\t\t\tCopyright 2016, 2017 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/byte_order.h\"\r\n#include \"common\/vect.h\"\r\n#include \"common\/delay.hpp\"\r\n\r\n#if defined(SIG_RX621)\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX621\/system.hpp\"\r\n#include \"RX621\/sci.hpp\"\r\n#include \"RX621\/icu.hpp\"\r\n\r\n#elif defined(SIG_RX24T)\r\n#include \"RX24T\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/dtc.hpp\"\r\n#include \"RX24T\/icu.hpp\"\r\n#include \"RX24T\/mtu3.hpp\"\r\n#include \"RX24T\/poe3.hpp\"\r\n#include \"RX24T\/tmr.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX24T\/sci.hpp\"\r\n#include \"RX24T\/riic.hpp\"\r\n#include \"RX24T\/rspi.hpp\"\r\n#include \"RX24T\/crc.hpp\"\r\n#include \"RX24T\/s12ad.hpp\"\r\n#include \"RX24T\/adc_io.hpp\"\r\n#include \"RX24T\/da.hpp\"\r\n#include \"RX24T\/cmpc.hpp\"\r\n#include \"RX24T\/doc.hpp\"\r\n#include \"RX24T\/port_map.hpp\"\r\n#include \"RX24T\/power_cfg.hpp\"\r\n#include \"RX24T\/icu_mgr.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n#include \"RX24T\/flash_io.hpp\"\r\n\r\n#elif defined(SIG_RX63T)\r\n#include \"RX63T\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX63T\/system.hpp\"\r\n#include \"RX63T\/sci.hpp\"\r\n#include \"RX63T\/icu.hpp\"\r\n#include \"RX63T\/port_map.hpp\"\r\n#include \"RX63T\/power_cfg.hpp\"\r\n#include \"RX63T\/icu_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX64M)\r\n#include \"RX64M\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX64M\/system.hpp\"\r\n#include \"RX64M\/bus.hpp\"\r\n#include \"RX64M\/mpc.hpp\"\r\n#include \"RX64M\/icu.hpp\"\r\n#include \"RX64M\/sci.hpp\"\r\n#include \"RX64M\/riic.hpp\"\r\n#include \"RX64M\/rspi.hpp\"\r\n#include \"RX64M\/port_map.hpp\"\r\n#include \"RX64M\/power_cfg.hpp\"\r\n#include \"RX64M\/icu_mgr.hpp\"\r\n#include \"RX64M\/sdhi.hpp\"\r\n#include \"RX64M\/s12adc.hpp\"\r\n#include \"RX64M\/adc_io.hpp\"\r\n#include \"RX64M\/sdram.hpp\"\r\n#include \"RX64M\/etherc.hpp\"\r\n#include \"RX64M\/edmac.hpp\"\r\n#include \"RX64M\/rtc.hpp\"\r\n#include \"RX64M\/rtc_io.hpp\"\r\n#include \"RX64M\/flash.hpp\"\r\n#include \"RX64M\/flash_io.hpp\"\r\n#include \"RX64M\/ether_io.hpp\"\r\n\r\n#else\r\n# error \"Requires SIG_XXX to be defined\"\r\n#endif\r\n<commit_msg>update include path for system_io<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tルネサス RX 選択 @n\r\n\t\t\tCopyright 2016, 2017 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/byte_order.h\"\r\n#include \"common\/vect.h\"\r\n#include \"common\/delay.hpp\"\r\n\r\n#if defined(SIG_RX621)\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX621\/system.hpp\"\r\n#include \"RX621\/sci.hpp\"\r\n#include \"RX621\/icu.hpp\"\r\n\r\n#elif defined(SIG_RX24T)\r\n#include \"RX24T\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/dtc.hpp\"\r\n#include \"RX24T\/icu.hpp\"\r\n#include \"RX24T\/mtu3.hpp\"\r\n#include \"RX24T\/poe3.hpp\"\r\n#include \"RX24T\/tmr.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX24T\/sci.hpp\"\r\n#include \"RX24T\/riic.hpp\"\r\n#include \"RX24T\/rspi.hpp\"\r\n#include \"RX24T\/crc.hpp\"\r\n#include \"RX24T\/s12ad.hpp\"\r\n#include \"RX24T\/adc_io.hpp\"\r\n#include \"RX24T\/da.hpp\"\r\n#include \"RX24T\/cmpc.hpp\"\r\n#include \"RX24T\/doc.hpp\"\r\n#include \"RX24T\/port_map.hpp\"\r\n#include \"RX24T\/power_cfg.hpp\"\r\n#include \"RX24T\/icu_mgr.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n#include \"RX24T\/flash_io.hpp\"\r\n\r\n#elif defined(SIG_RX63T)\r\n#include \"RX63T\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX63T\/system.hpp\"\r\n#include \"RX63T\/sci.hpp\"\r\n#include \"RX63T\/icu.hpp\"\r\n#include \"RX63T\/port_map.hpp\"\r\n#include \"RX63T\/power_cfg.hpp\"\r\n#include \"RX63T\/icu_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX64M)\r\n#include \"RX64M\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX64M\/system.hpp\"\r\n#include \"RX64M\/system_io.hpp\"\r\n#include \"RX64M\/bus.hpp\"\r\n#include \"RX64M\/mpc.hpp\"\r\n#include \"RX64M\/icu.hpp\"\r\n#include \"RX64M\/sci.hpp\"\r\n#include \"RX64M\/riic.hpp\"\r\n#include \"RX64M\/rspi.hpp\"\r\n#include \"RX64M\/port_map.hpp\"\r\n#include \"RX64M\/power_cfg.hpp\"\r\n#include \"RX64M\/icu_mgr.hpp\"\r\n#include \"RX64M\/sdhi.hpp\"\r\n#include \"RX64M\/s12adc.hpp\"\r\n#include \"RX64M\/adc_io.hpp\"\r\n#include \"RX64M\/sdram.hpp\"\r\n#include \"RX64M\/etherc.hpp\"\r\n#include \"RX64M\/edmac.hpp\"\r\n#include \"RX64M\/rtc.hpp\"\r\n#include \"RX64M\/rtc_io.hpp\"\r\n#include \"RX64M\/flash.hpp\"\r\n#include \"RX64M\/flash_io.hpp\"\r\n#include \"RX64M\/ether_io.hpp\"\r\n\r\n#else\r\n# error \"Requires SIG_XXX to be defined\"\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>#pragma comment(lib, \"Shlwapi.lib\")\n\n#include \"Observer.h\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <cwchar>\n#include <string>\n#include <utility>\n#include <functional>\n#include <concurrent_unordered_map.h>\n\n#include <Windows.h>\n#include <Shlwapi.h>\n#include \"bass.h\"\n#include \"bass_fx.h\"\n#include \"Hooker.h\"\n#include \"Server.h\"\n\nstd::shared_ptr<Observer> Observer::instance;\nstd::once_flag Observer::once_flag;\n\nBOOL WINAPI Observer::ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerReadFile.GetFunction()(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped))\n {\n return FALSE;\n }\n\n \/\/ osu! ̸(260 ̻) Ƿ,\n \/\/ szFilePath ̴ MAX_PATH ϰ ߰ Ҵϴ \n \/\/ GetFinalPathNameByHandle , szFilePath \\\\?\\D:\\Games\\osu!\\...\n wchar_t szFilePath[MAX_PATH];\n DWORD nFilePathLength = GetFinalPathNameByHandle(hFile, szFilePath, MAX_PATH, VOLUME_NAME_DOS);\n \/\/ д ũ ƴϰų, osu! ɷ ʰ Ÿ library ۾?\n if (nFilePathLength == 0 || nFilePathLength > MAX_PATH || lpNumberOfBytesRead == NULL)\n {\n return TRUE;\n }\n\n DWORD dwFilePosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - *lpNumberOfBytesRead;\n \/\/ д Ʈ ̰ պκ оٸ :\n \/\/ AudioFilename պκп \/ ڵ !\n if (wcsnicmp(L\".osu\", &szFilePath[nFilePathLength - 4], 4) == 0 && dwFilePosition == 0)\n {\n \/\/ strtok ҽ ϹǷ ϴ \n \/\/ .osu UTF-8(Multibyte) ڵ\n char *buffer = strdup((const char *) lpBuffer);\n for (char *line = strtok(buffer, \"\\n\"); line != NULL; line = strtok(NULL, \"\\n\"))\n {\n if (strnicmp(line, \"AudioFilename:\", 14) != 0)\n {\n continue;\n }\n\n \/\/ AudioFilename \n wchar_t szAudioFileName[MAX_PATH];\n mbstowcs(szAudioFileName, &line[14], MAX_PATH);\n StrTrim(szAudioFileName, L\" \\r\");\n\n \/\/ Ʈ ã\n wchar_t szAudioFilePath[MAX_PATH];\n wcscpy(szAudioFilePath, szFilePath);\n PathRemoveFileSpec(szAudioFilePath);\n PathCombine(szAudioFilePath, szAudioFilePath, szAudioFileName);\n\n \/\/ audioInfo ˻ ҹ ϹǷ Ȯ \n WIN32_FIND_DATA fdata;\n FindClose(FindFirstFile(szAudioFilePath, &fdata));\n PathRemoveFileSpec(szAudioFilePath);\n PathCombine(szAudioFilePath, szAudioFilePath, fdata.cFileName);\n\n \/\/ PathCombineW \\\\?\\(Long Unicode path prefix) ϴµ,\n \/\/ GetFinalPathNameByHandle 忡 ° ٽ ߰ؼ\n \/\/ ٲ ȥ \n wcscpy(szAudioFileName, szAudioFilePath);\n wcscpy(szAudioFilePath, L\"\\\\\\\\?\\\\\");\n wcscat(szAudioFilePath, szAudioFileName);\n\n \/\/ osu! Ʈ ٲ Ź Ʈ ʰ ijÿ ҷ⵵ \n \/\/ => Ʈ Ϻٴ ؾ\n self->audioInfo.insert({szAudioFilePath, szFilePath});\n break;\n }\n free(buffer);\n }\n \/\/ д Ʈ ϱ\n else\n {\n decltype(self->audioInfo)::iterator info;\n if ((info = self->audioInfo.find(szFilePath)) != self->audioInfo.end())\n {\n EnterCriticalSection(&self->hCritiaclSection);\n self->playing = {info->first.substr(4), info->second.substr(4)};\n LeaveCriticalSection(&self->hCritiaclSection);\n }\n }\n return TRUE;\n}\n\n\ninline long long GetSystemTimeAsFileTime()\n{\n \/*\n * Do not cast a pointer to a FILETIME structure to either a\n * ULARGE_INTEGER* or __int64* value because it can cause alignment faults on 64-bit Windows.\n * via http:\/\/technet.microsoft.com\/en-us\/library\/ms724284(v=vs.85).aspx\n *\/\n FILETIME ft;\n GetSystemTimeAsFileTime(&ft);\n return ((long long) ft.dwHighDateTime << 32) + ft.dwLowDateTime;\n}\n\nBOOL WINAPI Observer::BASS_ChannelPlay(DWORD handle, BOOL restart)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerBASS_ChannelPlay.GetFunction()(handle, restart))\n {\n return FALSE;\n }\n\n BASS_CHANNELINFO info;\n BASS_ChannelGetInfo(handle, &info);\n if (info.ctype & BASS_CTYPE_STREAM)\n {\n double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));\n float tempo = 0;\n BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, &tempo);\n self->Update(currentTime, tempo);\n }\n return TRUE;\n}\n\nBOOL WINAPI Observer::BASS_ChannelSetPosition(DWORD handle, QWORD pos, DWORD mode)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerBASS_ChannelSetPosition.GetFunction()(handle, pos, mode))\n {\n return FALSE;\n }\n\n BASS_CHANNELINFO info;\n BASS_ChannelGetInfo(handle, &info);\n if (info.ctype & BASS_CTYPE_STREAM)\n {\n double currentTime = BASS_ChannelBytes2Seconds(handle, pos);\n float tempo = 0;\n BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, &tempo);\n \/\/ !! pos ,\n \/\/ ϸ BASS_ChannelPlay Լ ȣǰ,\n \/\/ BASS_ChannelIsActive BASS_ACTIVE_PAUSED.\n if (BASS_ChannelIsActive(handle) == BASS_ACTIVE_PAUSED)\n {\n tempo = -100;\n }\n self->Update(currentTime, tempo);\n }\n return TRUE;\n}\n\nBOOL WINAPI Observer::BASS_ChannelSetAttribute(DWORD handle, DWORD attrib, float value)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerBASS_ChannelSetAttribute.GetFunction()(handle, attrib, value))\n {\n return FALSE;\n }\n\n BASS_CHANNELINFO info;\n BASS_ChannelGetInfo(handle, &info);\n if ((info.ctype & BASS_CTYPE_STREAM) && attrib == BASS_ATTRIB_TEMPO)\n {\n double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));\n self->Update(currentTime, value);\n }\n return TRUE;\n}\n\nBOOL WINAPI Observer::BASS_ChannelPause(DWORD handle)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerBASS_ChannelPause.GetFunction()(handle))\n {\n return FALSE;\n }\n\n BASS_CHANNELINFO info;\n BASS_ChannelGetInfo(handle, &info);\n if (info.ctype & BASS_CTYPE_STREAM)\n {\n double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));\n self->Update(currentTime, -100);\n }\n return TRUE;\n}\n\nvoid Observer::Update(double currentTime, float tempo)\n{\n Observer *self = Observer::GetInstance();\n wchar_t message[Server::nMessageLength];\n EnterCriticalSection(&self->hCritiaclSection);\n swprintf(message, L\"%llx|%s|%lf|%f|%s\\n\",\n GetSystemTimeAsFileTime(),\n self->playing.first.c_str(),\n currentTime,\n tempo,\n self->playing.second.c_str()\n );\n LeaveCriticalSection(&self->hCritiaclSection);\n Server::GetInstance()->PushMessage(message);\n}\n\nvoid Observer::Run()\n{\n this->hookerReadFile.Hook();\n\n this->hookerBASS_ChannelPlay.Hook();\n this->hookerBASS_ChannelSetPosition.Hook();\n this->hookerBASS_ChannelSetAttribute.Hook();\n this->hookerBASS_ChannelPause.Hook();\n}\n\nvoid Observer::Stop()\n{\n this->hookerBASS_ChannelPause.Unhook();\n this->hookerBASS_ChannelSetAttribute.Unhook();\n this->hookerBASS_ChannelSetPosition.Unhook();\n this->hookerBASS_ChannelPlay.Unhook();\n\n this->hookerReadFile.Unhook();\n}\n<commit_msg>Revert \"#31 해결\"<commit_after>#pragma comment(lib, \"Shlwapi.lib\")\n\n#include \"Observer.h\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <cwchar>\n#include <string>\n#include <utility>\n#include <functional>\n#include <concurrent_unordered_map.h>\n\n#include <Windows.h>\n#include <Shlwapi.h>\n#include \"bass.h\"\n#include \"bass_fx.h\"\n#include \"Hooker.h\"\n#include \"Server.h\"\n\nstd::shared_ptr<Observer> Observer::instance;\nstd::once_flag Observer::once_flag;\n\nBOOL WINAPI Observer::ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerReadFile.GetFunction()(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped))\n {\n return FALSE;\n }\n\n \/\/ osu! ̸(260 ̻) Ƿ,\n \/\/ szFilePath ̴ MAX_PATH ϰ ߰ Ҵϴ \n \/\/ GetFinalPathNameByHandle , szFilePath \\\\?\\D:\\Games\\osu!\\...\n wchar_t szFilePath[MAX_PATH];\n DWORD nFilePathLength = GetFinalPathNameByHandle(hFile, szFilePath, MAX_PATH, VOLUME_NAME_DOS);\n \/\/ д ũ ƴϰų, osu! ɷ ʰ Ÿ library ۾?\n if (nFilePathLength == 0 || nFilePathLength > MAX_PATH || lpNumberOfBytesRead == NULL)\n {\n return TRUE;\n }\n\n DWORD dwFilePosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - *lpNumberOfBytesRead;\n \/\/ д Ʈ ̰ պκ оٸ :\n \/\/ AudioFilename պκп \/ ڵ !\n if (wcsnicmp(L\".osu\", &szFilePath[nFilePathLength - 4], 4) == 0 && dwFilePosition == 0)\n {\n \/\/ strtok ҽ ϹǷ ϴ \n \/\/ .osu UTF-8(Multibyte) ڵ\n char *buffer = strdup((const char *) lpBuffer);\n for (char *line = strtok(buffer, \"\\n\"); line != NULL; line = strtok(NULL, \"\\n\"))\n {\n if (strnicmp(line, \"AudioFilename:\", 14) != 0)\n {\n continue;\n }\n\n \/\/ AudioFilename \n wchar_t szAudioFileName[MAX_PATH];\n mbstowcs(szAudioFileName, &line[14], MAX_PATH);\n StrTrim(szAudioFileName, L\" \\r\");\n\n \/\/ Ʈ ã\n wchar_t szAudioFilePath[MAX_PATH];\n wcscpy(szAudioFilePath, szFilePath);\n PathRemoveFileSpec(szAudioFilePath);\n PathCombine(szAudioFilePath, szAudioFilePath, szAudioFileName);\n\n \/\/ audioInfo ˻ ҹ ϹǷ Ȯ \n WIN32_FIND_DATA fdata;\n FindClose(FindFirstFile(szAudioFilePath, &fdata));\n PathRemoveFileSpec(szAudioFilePath);\n PathCombine(szAudioFilePath, szAudioFilePath, fdata.cFileName);\n\n \/\/ PathCombineW \\\\?\\(Long Unicode path prefix) ϴµ,\n \/\/ GetFinalPathNameByHandle 忡 ° ٽ ߰ؼ\n \/\/ ٲ ȥ \n wcscpy(szAudioFileName, szAudioFilePath);\n wcscpy(szAudioFilePath, L\"\\\\\\\\?\\\\\");\n wcscat(szAudioFilePath, szAudioFileName);\n\n \/\/ osu! Ʈ ٲ Ź Ʈ ʰ ijÿ ҷ⵵ \n \/\/ => Ʈ Ϻٴ ؾ\n self->audioInfo.insert({szAudioFilePath, szFilePath});\n break;\n }\n free(buffer);\n }\n \/\/ д Ʈ ϱ\n else\n {\n decltype(self->audioInfo)::iterator info;\n if ((info = self->audioInfo.find(szFilePath)) != self->audioInfo.end())\n {\n EnterCriticalSection(&self->hCritiaclSection);\n self->playing = {info->first.substr(4), info->second.substr(4)};\n LeaveCriticalSection(&self->hCritiaclSection);\n }\n }\n return TRUE;\n}\n\n\ninline long long GetSystemTimeAsFileTime()\n{\n \/*\n * Do not cast a pointer to a FILETIME structure to either a\n * ULARGE_INTEGER* or __int64* value because it can cause alignment faults on 64-bit Windows.\n * via http:\/\/technet.microsoft.com\/en-us\/library\/ms724284(v=vs.85).aspx\n *\/\n FILETIME ft;\n GetSystemTimeAsFileTime(&ft);\n return ((long long) ft.dwHighDateTime << 32) + ft.dwLowDateTime;\n}\n\nBOOL WINAPI Observer::BASS_ChannelPlay(DWORD handle, BOOL restart)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerBASS_ChannelPlay.GetFunction()(handle, restart))\n {\n return FALSE;\n }\n\n BASS_CHANNELINFO info;\n BASS_ChannelGetInfo(handle, &info);\n if (info.ctype & BASS_CTYPE_STREAM)\n {\n double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));\n float tempo; BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, &tempo);\n self->Update(currentTime, tempo);\n }\n return TRUE;\n}\n\nBOOL WINAPI Observer::BASS_ChannelSetPosition(DWORD handle, QWORD pos, DWORD mode)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerBASS_ChannelSetPosition.GetFunction()(handle, pos, mode))\n {\n return FALSE;\n }\n\n BASS_CHANNELINFO info;\n BASS_ChannelGetInfo(handle, &info);\n if (info.ctype & BASS_CTYPE_STREAM)\n {\n double currentTime = BASS_ChannelBytes2Seconds(handle, pos);\n float tempo; BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, &tempo);\n \/\/ !! pos ,\n \/\/ ϸ BASS_ChannelPlay Լ ȣǰ,\n \/\/ BASS_ChannelIsActive BASS_ACTIVE_PAUSED.\n if (BASS_ChannelIsActive(handle) == BASS_ACTIVE_PAUSED)\n {\n tempo = -100;\n }\n self->Update(currentTime, tempo);\n }\n return TRUE;\n}\n\nBOOL WINAPI Observer::BASS_ChannelSetAttribute(DWORD handle, DWORD attrib, float value)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerBASS_ChannelSetAttribute.GetFunction()(handle, attrib, value))\n {\n return FALSE;\n }\n\n BASS_CHANNELINFO info;\n BASS_ChannelGetInfo(handle, &info);\n if ((info.ctype & BASS_CTYPE_STREAM) && attrib == BASS_ATTRIB_TEMPO)\n {\n double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));\n self->Update(currentTime, value);\n }\n return TRUE;\n}\n\nBOOL WINAPI Observer::BASS_ChannelPause(DWORD handle)\n{\n Observer *self = Observer::GetInstance();\n if (!self->hookerBASS_ChannelPause.GetFunction()(handle))\n {\n return FALSE;\n }\n\n BASS_CHANNELINFO info;\n BASS_ChannelGetInfo(handle, &info);\n if (info.ctype & BASS_CTYPE_STREAM)\n {\n double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));\n self->Update(currentTime, -100);\n }\n return TRUE;\n}\n\nvoid Observer::Update(double currentTime, float tempo)\n{\n Observer *self = Observer::GetInstance();\n wchar_t message[Server::nMessageLength];\n EnterCriticalSection(&self->hCritiaclSection);\n swprintf(message, L\"%llx|%s|%lf|%f|%s\\n\",\n GetSystemTimeAsFileTime(),\n self->playing.first.c_str(),\n currentTime,\n tempo,\n self->playing.second.c_str()\n );\n LeaveCriticalSection(&self->hCritiaclSection);\n Server::GetInstance()->PushMessage(message);\n}\n\nvoid Observer::Run()\n{\n this->hookerReadFile.Hook();\n\n this->hookerBASS_ChannelPlay.Hook();\n this->hookerBASS_ChannelSetPosition.Hook();\n this->hookerBASS_ChannelSetAttribute.Hook();\n this->hookerBASS_ChannelPause.Hook();\n}\n\nvoid Observer::Stop()\n{\n this->hookerBASS_ChannelPause.Unhook();\n this->hookerBASS_ChannelSetAttribute.Unhook();\n this->hookerBASS_ChannelSetPosition.Unhook();\n this->hookerBASS_ChannelPlay.Unhook();\n\n this->hookerReadFile.Unhook();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ GPUUniform.h\n\/\/ G3MiOSSDK\n\/\/\n\/\/ Created by Jose Miguel SN on 05\/04\/13.\n\/\/\n\/\/\n\n#ifndef G3MiOSSDK_GPUUniform_h\n#define G3MiOSSDK_GPUUniform_h\n\n#include \"GL.hpp\"\n#include \"GLConstants.hpp\"\n#include \"IGLUniformID.hpp\"\n#include \"IStringBuilder.hpp\"\n#include \"GPUVariable.hpp\"\n\nclass GPUUniform;\n\nclass GPUUniformValue{\n const int _type;\n \n mutable GPUUniform* _uniform;\n \npublic:\n GPUUniformValue(int type):_type(type), _uniform(NULL){}\n int getType() const { return _type;}\n virtual ~GPUUniformValue(){}\n virtual void setUniform(GL* gl, const IGLUniformID* id) const = 0;\n virtual bool isEqualsTo(const GPUUniformValue* v) const = 0;\n virtual GPUUniformValue* deepCopy() const = 0;\n \n GPUUniform* getLinkedUniform() const { return _uniform;}\n \n virtual std::string description() const = 0;\n \n void linkToGPUUniform(GPUUniform* u) const{\n _uniform = u;\n }\n \n void unLinkToGPUUniform(){\n _uniform = NULL;\n }\n \n void setValueToLinkedUniform() const;\n \n virtual void setLastGPUUniformValue(GPUUniformValue* old){} \/\/Used with matrix transform value\n \n \n virtual void copyFrom(GPUUniformValue* v) = 0;\n \n \n virtual GPUUniformValue* copyOrCreate(GPUUniformValue* value){return value;}\n};\n\n\nclass GPUUniform: public GPUVariable{\n \nprotected:\n const IGLUniformID* _id;\n \n bool _dirty;\n GPUUniformValue* _value;\n const int _type;\npublic:\n \n virtual ~GPUUniform(){\n delete _id;\n delete _value;\n }\n \n GPUUniform(const std::string&name, IGLUniformID* id, int type):\n GPUVariable(name, UNIFORM),\n _id(id),\n _dirty(false),\n _value(NULL),\n _type(type){}\n \n const std::string getName() const{ return _name;}\n const IGLUniformID* getID() const{ return _id;}\n int getType() const{ return _type;}\n bool wasSet() const { return _value != NULL;}\n GPUUniformValue* getSetValue() const { return _value;}\n \n void unset(){\n if (_value != NULL){\n delete _value;\n _value = NULL;\n }\n _dirty = false;\n }\n \n void set(GPUUniformValue* v){\n if (_type != v->getType()){ \/\/type checking\n ILogger::instance()->logError(\"Attempting to set uniform \" + _name + \"with invalid value type.\");\n return;\n }\n if (_value == NULL || !_value->isEqualsTo(v)){\n _dirty = true;\n \n _value = v->copyOrCreate(_value);\n \n\/\/ if (_value == NULL){\n\/\/ _value = v->deepCopy();\n\/\/ } else{\n\/\/ v->setLastGPUUniformValue(_value); \/\/Multiply matrix when needed\n\/\/ _value->copyFrom(v);\n\/\/ }\n }\n }\n \n virtual void applyChanges(GL* gl){\n if (_dirty){\n _value->setUniform(gl, _id);\n _dirty = false;\n } else{\n if (_value == NULL){\n ILogger::instance()->logError(\"Uniform \" + _name + \" was not set.\");\n }\n }\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueBool:public GPUUniformValue{\npublic:\n bool _value;\n \n GPUUniformValueBool(bool b):GPUUniformValue(GLType::glBool()),_value(b){}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n _value? gl->uniform1i(id, 1) : gl->uniform1i(id, 0);\n }\n bool isEqualsTo(const GPUUniformValue* v) const{\n return _value == ((GPUUniformValueBool*)v)->_value;\n }\n GPUUniformValue* deepCopy() const{\n return new GPUUniformValueBool(_value);\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueBool(_value); \n } else{\n ((GPUUniformValueBool*)value)->_value = _value;\n return value;\n }\n }\n \n void copyFrom(GPUUniformValue* v){\n _value = ((GPUUniformValueBool*)v)->_value;\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Boolean: \");\n isb->addBool(_value);\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n};\nclass GPUUniformBool: public GPUUniform{\npublic:\n GPUUniformBool(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glBool()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueVec2Float:public GPUUniformValue{\npublic:\n double _x, _y;\n \n GPUUniformValueVec2Float(double x, double y):GPUUniformValue(GLType::glVec2Float()), _x(x),_y(y){}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n gl->uniform2f(id, (float)_x, (float)_y);\n }\n bool isEqualsTo(const GPUUniformValue* v) const{\n GPUUniformValueVec2Float *v2 = (GPUUniformValueVec2Float *)v;\n return (_x == v2->_x) && (_y == v2->_y);\n }\n GPUUniformValue* deepCopy() const{\n return new GPUUniformValueVec2Float(_x,_y);\n }\n \n void copyFrom(GPUUniformValue* v){\n _x = ((GPUUniformValueVec2Float*)v)->_x;\n _y = ((GPUUniformValueVec2Float*)v)->_y;\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueVec2Float(_x,_y);\n } else{\n ((GPUUniformValueVec2Float*)value)->_x = _x;\n ((GPUUniformValueVec2Float*)value)->_y = _y;\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Vec2Float: x:\");\n isb->addDouble(_x);\n isb->addString(\"y:\");\n isb->addDouble(_y);\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n};\nclass GPUUniformVec2Float: public GPUUniform{\npublic:\n GPUUniformVec2Float(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glVec2Float()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueVec4Float:public GPUUniformValue{\npublic:\n double _x, _y, _z, _w;\n \n GPUUniformValueVec4Float(double x, double y, double z, double w):\n GPUUniformValue(GLType::glVec4Float()),_x(x),_y(y), _z(z), _w(w){}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n gl->uniform4f(id, (float)_x, (float)_y, (float)_z, (float)_w);\n }\n bool isEqualsTo(const GPUUniformValue* v) const{\n GPUUniformValueVec4Float *v2 = (GPUUniformValueVec4Float *)v;\n return (_x == v2->_x) && (_y == v2->_y) && (_z == v2->_z) && (_w == v2->_w);\n }\n GPUUniformValue* deepCopy() const{\n return new GPUUniformValueVec4Float(_x,_y,_z,_w);\n }\n \n void copyFrom(GPUUniformValue* v){\n _x = ((GPUUniformValueVec4Float*)v)->_x;\n _y = ((GPUUniformValueVec4Float*)v)->_y;\n _z = ((GPUUniformValueVec4Float*)v)->_z;\n _w = ((GPUUniformValueVec4Float*)v)->_w;\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueVec4Float(_x,_y,_z,_w);\n } else{\n ((GPUUniformValueVec4Float*)value)->_x = _x;\n ((GPUUniformValueVec4Float*)value)->_y = _y;\n ((GPUUniformValueVec4Float*)value)->_z = _z;\n ((GPUUniformValueVec4Float*)value)->_w = _w;\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Vec4Float: x:\");\n isb->addDouble(_x);\n isb->addString(\"y:\");\n isb->addDouble(_y);\n isb->addString(\"z:\");\n isb->addDouble(_z);\n isb->addString(\"w:\");\n isb->addDouble(_w);\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n};\nclass GPUUniformVec4Float: public GPUUniform{\npublic:\n GPUUniformVec4Float(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glVec4Float()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueMatrix4FloatTransform:public GPUUniformValue{\n \n GPUUniformValueMatrix4FloatTransform(const GPUUniformValueMatrix4FloatTransform* that):\n GPUUniformValue(GLType::glMatrix4Float()),\n _m(MutableMatrix44D(that->_m)),\n _isTransform(that->_isTransform)\n {}\n \npublic:\n#ifdef C_CODE\n MutableMatrix44D _m;\n#endif\n#ifdef JAVA_CODE\n public MutableMatrix44D _m;\n#endif\n \n bool _isTransform;\n \n GPUUniformValueMatrix4FloatTransform(const MutableMatrix44D& m, bool isTransform):\n GPUUniformValue(GLType::glMatrix4Float()),_m(m), _isTransform(isTransform)\/*, _transformedMatrix(m)*\/{}\n \n void setLastGPUUniformValue(GPUUniformValue* old){\n if (_isTransform){\n if (old == NULL){\n ILogger::instance()->logError(\"Trying to apply transformation to matrix without previous value\");\n } else{\n const MutableMatrix44D* lastM = ((GPUUniformValueMatrix4FloatTransform*)old)->getValue();\n }\n }\n }\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n gl->uniformMatrix4fv(id, false, &_m);\n }\n \n bool isEqualsTo(const GPUUniformValue* v) const{\n GPUUniformValueMatrix4FloatTransform *v2 = (GPUUniformValueMatrix4FloatTransform *)v;\n return _m.isEqualsTo(v2->_m);\n }\n GPUUniformValue* deepCopy() const{\n return new GPUUniformValueMatrix4FloatTransform(this);\n }\n \n void copyFrom(GPUUniformValue* v){\n _m.copyValue( ((GPUUniformValueMatrix4FloatTransform*)v)->_m );\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueMatrix4FloatTransform(_m, _isTransform);\n } else{\n GPUUniformValueMatrix4FloatTransform* valueM = (GPUUniformValueMatrix4FloatTransform*)value;\n if (_isTransform){\n valueM->_m.copyValue(valueM->_m.multiply(_m));\n } else{\n valueM->_m.copyValue(_m);\n }\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Matrix44D.\");\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n \n const MutableMatrix44D* getValue() const{\n\/\/ return &_transformedMatrix;\n return &_m;\n }\n};\nclass GPUUniformMatrix4Float: public GPUUniform{\npublic:\n GPUUniformMatrix4Float(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glMatrix4Float()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueFloat:public GPUUniformValue{\npublic:\n double _value;\n \n GPUUniformValueFloat(double d):GPUUniformValue(GLType::glFloat()),_value(d){}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n gl->uniform1f(id, (float)_value);\n }\n bool isEqualsTo(const GPUUniformValue* v) const{\n GPUUniformValueFloat *v2 = (GPUUniformValueFloat *)v;\n return _value == v2->_value;\n }\n GPUUniformValue* deepCopy() const{\n return new GPUUniformValueFloat(_value);\n }\n \n void copyFrom(GPUUniformValue* v){\n _value = ((GPUUniformValueFloat*)v)->_value;\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueFloat(_value);\n } else{\n ((GPUUniformValueFloat*)value)->_value = _value;\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Float: \");\n isb->addDouble(_value);\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n};\nclass GPUUniformFloat: public GPUUniform{\npublic:\n GPUUniformFloat(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glFloat()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#endif\n<commit_msg>less virtual functions<commit_after>\/\/\n\/\/ GPUUniform.h\n\/\/ G3MiOSSDK\n\/\/\n\/\/ Created by Jose Miguel SN on 05\/04\/13.\n\/\/\n\/\/\n\n#ifndef G3MiOSSDK_GPUUniform_h\n#define G3MiOSSDK_GPUUniform_h\n\n#include \"GL.hpp\"\n#include \"GLConstants.hpp\"\n#include \"IGLUniformID.hpp\"\n#include \"IStringBuilder.hpp\"\n#include \"GPUVariable.hpp\"\n\nclass GPUUniform;\n\nclass GPUUniformValue{\n const int _type;\n \n mutable GPUUniform* _uniform;\n \npublic:\n GPUUniformValue(int type):_type(type), _uniform(NULL){}\n int getType() const { return _type;}\n virtual ~GPUUniformValue(){}\n virtual void setUniform(GL* gl, const IGLUniformID* id) const = 0;\n virtual bool isEqualsTo(const GPUUniformValue* v) const = 0;\n \n GPUUniform* getLinkedUniform() const { return _uniform;}\n \n virtual std::string description() const = 0;\n \n void linkToGPUUniform(GPUUniform* u) const{\n _uniform = u;\n }\n \n void unLinkToGPUUniform(){\n _uniform = NULL;\n }\n \n void setValueToLinkedUniform() const;\n \n virtual GPUUniformValue* copyOrCreate(GPUUniformValue* value){return value;}\n \n bool linkToGPUProgram(const GPUProgram* prog, int key) const{\n GPUUniform* u = prog->getGPUUniform(key);\n if (u == NULL){\n ILogger::instance()->logError(\"UNIFORM WITH KEY %d NOT FOUND\", key);\n return false;\n } else{\n _uniform = u;\n return true;\n }\n }\n};\n\n\nclass GPUUniform: public GPUVariable{\n \nprotected:\n const IGLUniformID* _id;\n \n bool _dirty;\n GPUUniformValue* _value;\n const int _type;\npublic:\n \n virtual ~GPUUniform(){\n delete _id;\n delete _value;\n }\n \n GPUUniform(const std::string&name, IGLUniformID* id, int type):\n GPUVariable(name, UNIFORM),\n _id(id),\n _dirty(false),\n _value(NULL),\n _type(type){}\n \n const std::string getName() const{ return _name;}\n const IGLUniformID* getID() const{ return _id;}\n int getType() const{ return _type;}\n bool wasSet() const { return _value != NULL;}\n GPUUniformValue* getSetValue() const { return _value;}\n \n void unset(){\n if (_value != NULL){\n delete _value;\n _value = NULL;\n }\n _dirty = false;\n }\n \n void set(GPUUniformValue* v){\n if (_type != v->getType()){ \/\/type checking\n ILogger::instance()->logError(\"Attempting to set uniform \" + _name + \"with invalid value type.\");\n return;\n }\n if (_value == NULL || !_value->isEqualsTo(v)){\n _dirty = true;\n _value = v->copyOrCreate(_value);\n }\n }\n \n virtual void applyChanges(GL* gl){\n if (_dirty){\n _value->setUniform(gl, _id);\n _dirty = false;\n } else{\n if (_value == NULL){\n ILogger::instance()->logError(\"Uniform \" + _name + \" was not set.\");\n }\n }\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueBool:public GPUUniformValue{\npublic:\n bool _value;\n \n GPUUniformValueBool(bool b):GPUUniformValue(GLType::glBool()),_value(b){}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n _value? gl->uniform1i(id, 1) : gl->uniform1i(id, 0);\n }\n bool isEqualsTo(const GPUUniformValue* v) const{\n return _value == ((GPUUniformValueBool*)v)->_value;\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueBool(_value); \n } else{\n ((GPUUniformValueBool*)value)->_value = _value;\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Boolean: \");\n isb->addBool(_value);\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n};\nclass GPUUniformBool: public GPUUniform{\npublic:\n GPUUniformBool(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glBool()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueVec2Float:public GPUUniformValue{\npublic:\n double _x, _y;\n \n GPUUniformValueVec2Float(double x, double y):GPUUniformValue(GLType::glVec2Float()), _x(x),_y(y){}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n gl->uniform2f(id, (float)_x, (float)_y);\n }\n bool isEqualsTo(const GPUUniformValue* v) const{\n GPUUniformValueVec2Float *v2 = (GPUUniformValueVec2Float *)v;\n return (_x == v2->_x) && (_y == v2->_y);\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueVec2Float(_x,_y);\n } else{\n ((GPUUniformValueVec2Float*)value)->_x = _x;\n ((GPUUniformValueVec2Float*)value)->_y = _y;\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Vec2Float: x:\");\n isb->addDouble(_x);\n isb->addString(\"y:\");\n isb->addDouble(_y);\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n};\nclass GPUUniformVec2Float: public GPUUniform{\npublic:\n GPUUniformVec2Float(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glVec2Float()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueVec4Float:public GPUUniformValue{\npublic:\n double _x, _y, _z, _w;\n \n GPUUniformValueVec4Float(double x, double y, double z, double w):\n GPUUniformValue(GLType::glVec4Float()),_x(x),_y(y), _z(z), _w(w){}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n gl->uniform4f(id, (float)_x, (float)_y, (float)_z, (float)_w);\n }\n bool isEqualsTo(const GPUUniformValue* v) const{\n GPUUniformValueVec4Float *v2 = (GPUUniformValueVec4Float *)v;\n return (_x == v2->_x) && (_y == v2->_y) && (_z == v2->_z) && (_w == v2->_w);\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueVec4Float(_x,_y,_z,_w);\n } else{\n ((GPUUniformValueVec4Float*)value)->_x = _x;\n ((GPUUniformValueVec4Float*)value)->_y = _y;\n ((GPUUniformValueVec4Float*)value)->_z = _z;\n ((GPUUniformValueVec4Float*)value)->_w = _w;\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Vec4Float: x:\");\n isb->addDouble(_x);\n isb->addString(\"y:\");\n isb->addDouble(_y);\n isb->addString(\"z:\");\n isb->addDouble(_z);\n isb->addString(\"w:\");\n isb->addDouble(_w);\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n};\nclass GPUUniformVec4Float: public GPUUniform{\npublic:\n GPUUniformVec4Float(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glVec4Float()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueMatrix4FloatTransform:public GPUUniformValue{\n \n GPUUniformValueMatrix4FloatTransform(const GPUUniformValueMatrix4FloatTransform* that):\n GPUUniformValue(GLType::glMatrix4Float()),\n _m(MutableMatrix44D(that->_m)),\n _isTransform(that->_isTransform)\n {}\n \npublic:\n#ifdef C_CODE\n MutableMatrix44D _m;\n#endif\n#ifdef JAVA_CODE\n public MutableMatrix44D _m;\n#endif\n \n bool _isTransform;\n \n GPUUniformValueMatrix4FloatTransform(const MutableMatrix44D& m, bool isTransform):\n GPUUniformValue(GLType::glMatrix4Float()),_m(m), _isTransform(isTransform)\/*, _transformedMatrix(m)*\/{}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n gl->uniformMatrix4fv(id, false, &_m);\n }\n \n bool isEqualsTo(const GPUUniformValue* v) const{\n GPUUniformValueMatrix4FloatTransform *v2 = (GPUUniformValueMatrix4FloatTransform *)v;\n return _m.isEqualsTo(v2->_m);\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueMatrix4FloatTransform(_m, _isTransform);\n } else{\n GPUUniformValueMatrix4FloatTransform* valueM = (GPUUniformValueMatrix4FloatTransform*)value;\n if (_isTransform){\n valueM->_m.copyValue(valueM->_m.multiply(_m));\n } else{\n valueM->_m.copyValue(_m);\n }\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Matrix44D.\");\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n \n const MutableMatrix44D* getValue() const{\n\/\/ return &_transformedMatrix;\n return &_m;\n }\n};\nclass GPUUniformMatrix4Float: public GPUUniform{\npublic:\n GPUUniformMatrix4Float(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glMatrix4Float()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass GPUUniformValueFloat:public GPUUniformValue{\npublic:\n double _value;\n \n GPUUniformValueFloat(double d):GPUUniformValue(GLType::glFloat()),_value(d){}\n \n void setUniform(GL* gl, const IGLUniformID* id) const{\n gl->uniform1f(id, (float)_value);\n }\n bool isEqualsTo(const GPUUniformValue* v) const{\n GPUUniformValueFloat *v2 = (GPUUniformValueFloat *)v;\n return _value == v2->_value;\n }\n \n GPUUniformValue* copyOrCreate(GPUUniformValue* value){\n if (value == NULL){\n return new GPUUniformValueFloat(_value);\n } else{\n ((GPUUniformValueFloat*)value)->_value = _value;\n return value;\n }\n }\n \n std::string description() const{\n IStringBuilder *isb = IStringBuilder::newStringBuilder();\n isb->addString(\"Uniform Value Float: \");\n isb->addDouble(_value);\n std::string s = isb->getString();\n delete isb;\n return s;\n }\n};\nclass GPUUniformFloat: public GPUUniform{\npublic:\n GPUUniformFloat(const std::string&name, IGLUniformID* id):GPUUniform(name,id, GLType::glFloat()){}\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"reGlobalsExtern.hpp\"\n#include \"dataObjChksum.hpp\"\n#include \"dataObjRsync.hpp\"\n#include \"objMetaOpr.hpp\"\n#include \"specColl.hpp\"\n#include \"dataObjOpr.hpp\"\n#include \"rsApiHandler.hpp\"\n#include \"modDataObjMeta.hpp\"\n#include \"getRemoteZoneResc.hpp\"\n\n#include \"irods_resource_redirect.hpp\"\n\nint\nrsDataObjRsync( rsComm_t *rsComm, dataObjInp_t *dataObjInp,\n msParamArray_t **outParamArray ) {\n int status;\n char *rsyncMode;\n char *remoteZoneOpr;\n int remoteFlag;\n rodsServerHost_t *rodsServerHost;\n specCollCache_t *specCollCache = NULL;\n\n *outParamArray = NULL;\n if ( dataObjInp == NULL ) {\n rodsLog( LOG_ERROR, \"rsDataObjRsync error. NULL input\" );\n return SYS_INTERNAL_NULL_INPUT_ERR;\n }\n\n rsyncMode = getValByKey( &dataObjInp->condInput, RSYNC_MODE_KW );\n if ( rsyncMode == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsDataObjRsync: RSYNC_MODE_KW input is missing\" );\n return USER_RSYNC_NO_MODE_INPUT_ERR;\n }\n\n if ( strcmp( rsyncMode, LOCAL_TO_IRODS ) == 0 ) {\n remoteZoneOpr = REMOTE_CREATE;\n }\n else {\n remoteZoneOpr = REMOTE_OPEN;\n }\n\n resolveLinkedPath( rsComm, dataObjInp->objPath, &specCollCache,\n &dataObjInp->condInput );\n if ( strcmp( rsyncMode, IRODS_TO_IRODS ) == 0 ) {\n if ( isLocalZone( dataObjInp->objPath ) == 0 ) {\n dataObjInp_t myDataObjInp;\n char *destObjPath;\n \/* source in a remote zone. try dest *\/\n destObjPath = getValByKey( &dataObjInp->condInput,\n RSYNC_DEST_PATH_KW );\n if ( destObjPath == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsDataObjRsync: RSYNC_DEST_PATH_KW input is missing for %s\",\n dataObjInp->objPath );\n return USER_RSYNC_NO_MODE_INPUT_ERR;\n }\n myDataObjInp = *dataObjInp;\n remoteZoneOpr = REMOTE_CREATE;\n rstrcpy( myDataObjInp.objPath, destObjPath, MAX_NAME_LEN );\n remoteFlag = getAndConnRemoteZone( rsComm, &myDataObjInp,\n &rodsServerHost, remoteZoneOpr );\n }\n else {\n remoteFlag = getAndConnRemoteZone( rsComm, dataObjInp,\n &rodsServerHost, remoteZoneOpr );\n }\n }\n else {\n remoteFlag = getAndConnRemoteZone( rsComm, dataObjInp, &rodsServerHost,\n remoteZoneOpr );\n }\n\n if ( remoteFlag < 0 ) {\n return remoteFlag;\n }\n else if ( remoteFlag == REMOTE_HOST ) {\n\n status = _rcDataObjRsync( rodsServerHost->conn, dataObjInp,\n outParamArray );\n return status;\n }\n\n if ( strcmp( rsyncMode, IRODS_TO_LOCAL ) == 0 ) {\n status = rsRsyncFileToData( rsComm, dataObjInp );\n }\n else if ( strcmp( rsyncMode, LOCAL_TO_IRODS ) == 0 ) {\n status = rsRsyncDataToFile( rsComm, dataObjInp );\n }\n else if ( strcmp( rsyncMode, IRODS_TO_IRODS ) == 0 ) {\n status = rsRsyncDataToData( rsComm, dataObjInp );\n }\n else {\n rodsLog( LOG_ERROR,\n \"rsDataObjRsync: rsyncMode %s not supported\" );\n return USER_RSYNC_NO_MODE_INPUT_ERR;\n }\n\n return status;\n}\n\nint\nrsRsyncDataToFile( rsComm_t *rsComm, dataObjInp_t *dataObjInp ) {\n int status;\n char *fileChksumStr = NULL;\n char *dataObjChksumStr = NULL;\n dataObjInfo_t *dataObjInfoHead = NULL;\n\n fileChksumStr = getValByKey( &dataObjInp->condInput, RSYNC_CHKSUM_KW );\n\n if ( fileChksumStr == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToFile: RSYNC_CHKSUM_KW input is missing for %s\",\n dataObjInp->objPath );\n return CHKSUM_EMPTY_IN_STRUCT_ERR;\n }\n\n status = _rsDataObjChksum( rsComm, dataObjInp, &dataObjChksumStr,\n &dataObjInfoHead );\n\n if ( status < 0 && status != CAT_NO_ACCESS_PERMISSION &&\n status != CAT_NO_ROWS_FOUND ) {\n \/* XXXXX CAT_NO_ACCESS_PERMISSION mean the chksum was calculated but\n * cannot be registered. But the chksum value is OK.\n *\/\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToFile: _rsDataObjChksum of %s error. status = %d\",\n dataObjInp->objPath, status );\n return status;\n }\n\n freeAllDataObjInfo( dataObjInfoHead );\n\n if ( dataObjChksumStr != NULL &&\n strcmp( dataObjChksumStr, fileChksumStr ) == 0 ) {\n free( dataObjChksumStr );\n return 0;\n }\n\n return SYS_SVR_TO_CLI_GET_ACTION;\n}\n\nint\nrsRsyncFileToData( rsComm_t *rsComm, dataObjInp_t *dataObjInp ) {\n int status;\n char *fileChksumStr = NULL;\n char *dataObjChksumStr = NULL;\n dataObjInfo_t *dataObjInfoHead = NULL;\n\n fileChksumStr = getValByKey( &dataObjInp->condInput, RSYNC_CHKSUM_KW );\n\n if ( fileChksumStr == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsRsyncFileToData: RSYNC_CHKSUM_KW input is missing\" );\n return CHKSUM_EMPTY_IN_STRUCT_ERR;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ determine the resource hierarchy if one is not provided\n if ( getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW ) == NULL ) {\n std::string hier;\n irods::error ret = irods::resolve_resource_hierarchy( irods::OPEN_OPERATION,\n rsComm, dataObjInp, hier );\n if ( !ret.ok() ) {\n std::stringstream msg;\n msg << __FUNCTION__;\n msg << \" :: failed in irods::resolve_resource_hierarchy for [\";\n msg << dataObjInp->objPath << \"]\";\n irods::log( PASSMSG( msg.str(), ret ) );\n return ret.code();\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ we resolved the redirect and have a host, set the hier str for subsequent\n \/\/ api calls, etc.\n addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() );\n\n } \/\/ if keyword\n\n status = _rsDataObjChksum( rsComm, dataObjInp, &dataObjChksumStr,\n &dataObjInfoHead );\n\n if ( status < 0 && status != CAT_NO_ACCESS_PERMISSION &&\n status != CAT_NO_ROWS_FOUND ) {\n \/* XXXXX CAT_NO_ACCESS_PERMISSION mean the chksum was calculated but\n * cannot be registered. But the chksum value is OK.\n *\/\n rodsLog( LOG_ERROR,\n \"rsRsyncFileToData: _rsDataObjChksum of %s error. status = %d\",\n dataObjInp->objPath, status );\n }\n\n freeAllDataObjInfo( dataObjInfoHead );\n\n if ( dataObjChksumStr != NULL &&\n strcmp( dataObjChksumStr, fileChksumStr ) == 0 ) {\n free( dataObjChksumStr );\n return 0;\n }\n return SYS_SVR_TO_CLI_PUT_ACTION;\n}\n\nint\nrsRsyncDataToData( rsComm_t *rsComm, dataObjInp_t *dataObjInp ) {\n int status;\n char *srcChksumStr = NULL;\n char *destChksumStr = NULL;\n dataObjCopyInp_t dataObjCopyInp;\n char *destObjPath;\n transferStat_t *transStat = NULL;\n\n \/* always have the FORCE flag on *\/\n addKeyVal( &dataObjInp->condInput, FORCE_FLAG_KW, \"\" );\n\n destObjPath = getValByKey( &dataObjInp->condInput, RSYNC_DEST_PATH_KW );\n if ( destObjPath == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToData: RSYNC_DEST_PATH_KW input is missing for %s\",\n dataObjInp->objPath );\n return USER_RSYNC_NO_MODE_INPUT_ERR;\n }\n\n memset( &dataObjCopyInp, 0, sizeof( dataObjCopyInp ) );\n rstrcpy( dataObjCopyInp.srcDataObjInp.objPath, dataObjInp->objPath,\n MAX_NAME_LEN );\n dataObjCopyInp.srcDataObjInp.dataSize = dataObjInp->dataSize;\n replDataObjInp( dataObjInp, &dataObjCopyInp.destDataObjInp );\n rstrcpy( dataObjCopyInp.destDataObjInp.objPath, destObjPath,\n MAX_NAME_LEN );\n\n \/* use rsDataObjChksum because the path could in in remote zone *\/\n status = rsDataObjChksum( rsComm, &dataObjCopyInp.srcDataObjInp,\n &srcChksumStr );\n\n if ( status < 0 &&\n ( status != CAT_NO_ACCESS_PERMISSION || srcChksumStr == NULL ) ) {\n \/* XXXXX CAT_NO_ACCESS_PERMISSION mean the chksum was calculated but\n * cannot be registered. But the chksum value is OK.\n *\/\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToData: _rsDataObjChksum error for %s, status = %d\",\n dataObjCopyInp.srcDataObjInp.objPath, status );\n clearKeyVal( &dataObjCopyInp.srcDataObjInp.condInput );\n return status;\n }\n\n \/* use rsDataObjChksum because the path could in in remote zone *\/\n status = rsDataObjChksum( rsComm, &dataObjCopyInp.destDataObjInp,\n &destChksumStr );\n\n if ( status < 0 && status != CAT_NO_ACCESS_PERMISSION &&\n status != CAT_NO_ROWS_FOUND ) {\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToData: _rsDataObjChksum error for %s, status = %d\",\n dataObjCopyInp.destDataObjInp.objPath, status );\n free( srcChksumStr );\n free( destChksumStr );\n clearKeyVal( &dataObjCopyInp.srcDataObjInp.condInput );\n clearKeyVal( &dataObjCopyInp.destDataObjInp.condInput );\n return status;\n }\n\n if ( destChksumStr != NULL && strcmp( srcChksumStr, destChksumStr ) == 0 ) {\n free( srcChksumStr );\n free( destChksumStr );\n clearKeyVal( &dataObjCopyInp.destDataObjInp.condInput );\n clearKeyVal( &dataObjCopyInp.srcDataObjInp.condInput );\n return 0;\n }\n\n addKeyVal( &dataObjCopyInp.destDataObjInp.condInput, REG_CHKSUM_KW,\n srcChksumStr );\n status = rsDataObjCopy( rsComm, &dataObjCopyInp, &transStat );\n free( transStat );\n free( srcChksumStr );\n free( destChksumStr );\n clearKeyVal( &dataObjCopyInp.destDataObjInp.condInput );\n clearKeyVal( &dataObjCopyInp.srcDataObjInp.condInput );\n\n if ( status >= 0 ) {\n return SYS_RSYNC_TARGET_MODIFIED;\n }\n else {\n return status;\n }\n}\n\n<commit_msg>[#2212] CID25831:<commit_after>#include \"reGlobalsExtern.hpp\"\n#include \"dataObjChksum.hpp\"\n#include \"dataObjRsync.hpp\"\n#include \"objMetaOpr.hpp\"\n#include \"specColl.hpp\"\n#include \"dataObjOpr.hpp\"\n#include \"rsApiHandler.hpp\"\n#include \"modDataObjMeta.hpp\"\n#include \"getRemoteZoneResc.hpp\"\n\n#include \"irods_resource_redirect.hpp\"\n\nint\nrsDataObjRsync( rsComm_t *rsComm, dataObjInp_t *dataObjInp,\n msParamArray_t **outParamArray ) {\n int status;\n char *rsyncMode;\n char *remoteZoneOpr;\n int remoteFlag;\n rodsServerHost_t *rodsServerHost;\n specCollCache_t *specCollCache = NULL;\n\n *outParamArray = NULL;\n if ( dataObjInp == NULL ) {\n rodsLog( LOG_ERROR, \"rsDataObjRsync error. NULL input\" );\n return SYS_INTERNAL_NULL_INPUT_ERR;\n }\n\n rsyncMode = getValByKey( &dataObjInp->condInput, RSYNC_MODE_KW );\n if ( rsyncMode == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsDataObjRsync: RSYNC_MODE_KW input is missing\" );\n return USER_RSYNC_NO_MODE_INPUT_ERR;\n }\n\n if ( strcmp( rsyncMode, LOCAL_TO_IRODS ) == 0 ) {\n remoteZoneOpr = REMOTE_CREATE;\n }\n else {\n remoteZoneOpr = REMOTE_OPEN;\n }\n\n resolveLinkedPath( rsComm, dataObjInp->objPath, &specCollCache,\n &dataObjInp->condInput );\n if ( strcmp( rsyncMode, IRODS_TO_IRODS ) == 0 ) {\n if ( isLocalZone( dataObjInp->objPath ) == 0 ) {\n dataObjInp_t myDataObjInp;\n char *destObjPath;\n \/* source in a remote zone. try dest *\/\n destObjPath = getValByKey( &dataObjInp->condInput,\n RSYNC_DEST_PATH_KW );\n if ( destObjPath == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsDataObjRsync: RSYNC_DEST_PATH_KW input is missing for %s\",\n dataObjInp->objPath );\n return USER_RSYNC_NO_MODE_INPUT_ERR;\n }\n myDataObjInp = *dataObjInp;\n remoteZoneOpr = REMOTE_CREATE;\n rstrcpy( myDataObjInp.objPath, destObjPath, MAX_NAME_LEN );\n remoteFlag = getAndConnRemoteZone( rsComm, &myDataObjInp,\n &rodsServerHost, remoteZoneOpr );\n }\n else {\n remoteFlag = getAndConnRemoteZone( rsComm, dataObjInp,\n &rodsServerHost, remoteZoneOpr );\n }\n }\n else {\n remoteFlag = getAndConnRemoteZone( rsComm, dataObjInp, &rodsServerHost,\n remoteZoneOpr );\n }\n\n if ( remoteFlag < 0 ) {\n return remoteFlag;\n }\n else if ( remoteFlag == REMOTE_HOST ) {\n\n status = _rcDataObjRsync( rodsServerHost->conn, dataObjInp,\n outParamArray );\n return status;\n }\n\n if ( strcmp( rsyncMode, IRODS_TO_LOCAL ) == 0 ) {\n status = rsRsyncFileToData( rsComm, dataObjInp );\n }\n else if ( strcmp( rsyncMode, LOCAL_TO_IRODS ) == 0 ) {\n status = rsRsyncDataToFile( rsComm, dataObjInp );\n }\n else if ( strcmp( rsyncMode, IRODS_TO_IRODS ) == 0 ) {\n status = rsRsyncDataToData( rsComm, dataObjInp );\n }\n else {\n rodsLog( LOG_ERROR,\n \"rsDataObjRsync: rsyncMode %s not supported\" );\n return USER_RSYNC_NO_MODE_INPUT_ERR;\n }\n\n return status;\n}\n\nint\nrsRsyncDataToFile( rsComm_t *rsComm, dataObjInp_t *dataObjInp ) {\n int status;\n char *fileChksumStr = NULL;\n char *dataObjChksumStr = NULL;\n dataObjInfo_t *dataObjInfoHead = NULL;\n\n fileChksumStr = getValByKey( &dataObjInp->condInput, RSYNC_CHKSUM_KW );\n\n if ( fileChksumStr == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToFile: RSYNC_CHKSUM_KW input is missing for %s\",\n dataObjInp->objPath );\n return CHKSUM_EMPTY_IN_STRUCT_ERR;\n }\n\n status = _rsDataObjChksum( rsComm, dataObjInp, &dataObjChksumStr,\n &dataObjInfoHead );\n\n if ( status < 0 && status != CAT_NO_ACCESS_PERMISSION &&\n status != CAT_NO_ROWS_FOUND ) {\n \/* XXXXX CAT_NO_ACCESS_PERMISSION mean the chksum was calculated but\n * cannot be registered. But the chksum value is OK.\n *\/\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToFile: _rsDataObjChksum of %s error. status = %d\",\n dataObjInp->objPath, status );\n return status;\n }\n\n freeAllDataObjInfo( dataObjInfoHead );\n\n if ( dataObjChksumStr != NULL &&\n strcmp( dataObjChksumStr, fileChksumStr ) == 0 ) {\n free( dataObjChksumStr );\n return 0;\n }\n\n return SYS_SVR_TO_CLI_GET_ACTION;\n}\n\nint\nrsRsyncFileToData( rsComm_t *rsComm, dataObjInp_t *dataObjInp ) {\n\n char * fileChksumStr = getValByKey( &dataObjInp->condInput, RSYNC_CHKSUM_KW );\n\n if ( fileChksumStr == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsRsyncFileToData: RSYNC_CHKSUM_KW input is missing\" );\n return CHKSUM_EMPTY_IN_STRUCT_ERR;\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ determine the resource hierarchy if one is not provided\n if ( getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW ) == NULL ) {\n std::string hier;\n irods::error ret = irods::resolve_resource_hierarchy( irods::OPEN_OPERATION,\n rsComm, dataObjInp, hier );\n if ( !ret.ok() ) {\n std::stringstream msg;\n msg << __FUNCTION__;\n msg << \" :: failed in irods::resolve_resource_hierarchy for [\";\n msg << dataObjInp->objPath << \"]\";\n irods::log( PASSMSG( msg.str(), ret ) );\n return ret.code();\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ we resolved the redirect and have a host, set the hier str for subsequent\n \/\/ api calls, etc.\n addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() );\n\n } \/\/ if keyword\n\n char *dataObjChksumStr = NULL;\n dataObjInfo_t *dataObjInfoHead = NULL;\n int status = _rsDataObjChksum( rsComm, dataObjInp, &dataObjChksumStr,\n &dataObjInfoHead );\n\n if ( status < 0 && status != CAT_NO_ACCESS_PERMISSION &&\n status != CAT_NO_ROWS_FOUND ) {\n \/* XXXXX CAT_NO_ACCESS_PERMISSION mean the chksum was calculated but\n * cannot be registered. But the chksum value is OK.\n *\/\n rodsLog( LOG_ERROR,\n \"rsRsyncFileToData: _rsDataObjChksum of %s error. status = %d\",\n dataObjInp->objPath, status );\n }\n\n freeAllDataObjInfo( dataObjInfoHead );\n\n if ( dataObjChksumStr != NULL &&\n strcmp( dataObjChksumStr, fileChksumStr ) == 0 ) {\n free( dataObjChksumStr );\n return 0;\n }\n free( dataObjChksumStr );\n return SYS_SVR_TO_CLI_PUT_ACTION;\n}\n\nint\nrsRsyncDataToData( rsComm_t *rsComm, dataObjInp_t *dataObjInp ) {\n int status;\n char *srcChksumStr = NULL;\n char *destChksumStr = NULL;\n dataObjCopyInp_t dataObjCopyInp;\n char *destObjPath;\n transferStat_t *transStat = NULL;\n\n \/* always have the FORCE flag on *\/\n addKeyVal( &dataObjInp->condInput, FORCE_FLAG_KW, \"\" );\n\n destObjPath = getValByKey( &dataObjInp->condInput, RSYNC_DEST_PATH_KW );\n if ( destObjPath == NULL ) {\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToData: RSYNC_DEST_PATH_KW input is missing for %s\",\n dataObjInp->objPath );\n return USER_RSYNC_NO_MODE_INPUT_ERR;\n }\n\n memset( &dataObjCopyInp, 0, sizeof( dataObjCopyInp ) );\n rstrcpy( dataObjCopyInp.srcDataObjInp.objPath, dataObjInp->objPath,\n MAX_NAME_LEN );\n dataObjCopyInp.srcDataObjInp.dataSize = dataObjInp->dataSize;\n replDataObjInp( dataObjInp, &dataObjCopyInp.destDataObjInp );\n rstrcpy( dataObjCopyInp.destDataObjInp.objPath, destObjPath,\n MAX_NAME_LEN );\n\n \/* use rsDataObjChksum because the path could in in remote zone *\/\n status = rsDataObjChksum( rsComm, &dataObjCopyInp.srcDataObjInp,\n &srcChksumStr );\n\n if ( status < 0 &&\n ( status != CAT_NO_ACCESS_PERMISSION || srcChksumStr == NULL ) ) {\n \/* XXXXX CAT_NO_ACCESS_PERMISSION mean the chksum was calculated but\n * cannot be registered. But the chksum value is OK.\n *\/\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToData: _rsDataObjChksum error for %s, status = %d\",\n dataObjCopyInp.srcDataObjInp.objPath, status );\n clearKeyVal( &dataObjCopyInp.srcDataObjInp.condInput );\n return status;\n }\n\n \/* use rsDataObjChksum because the path could in in remote zone *\/\n status = rsDataObjChksum( rsComm, &dataObjCopyInp.destDataObjInp,\n &destChksumStr );\n\n if ( status < 0 && status != CAT_NO_ACCESS_PERMISSION &&\n status != CAT_NO_ROWS_FOUND ) {\n rodsLog( LOG_ERROR,\n \"rsRsyncDataToData: _rsDataObjChksum error for %s, status = %d\",\n dataObjCopyInp.destDataObjInp.objPath, status );\n free( srcChksumStr );\n free( destChksumStr );\n clearKeyVal( &dataObjCopyInp.srcDataObjInp.condInput );\n clearKeyVal( &dataObjCopyInp.destDataObjInp.condInput );\n return status;\n }\n\n if ( destChksumStr != NULL && strcmp( srcChksumStr, destChksumStr ) == 0 ) {\n free( srcChksumStr );\n free( destChksumStr );\n clearKeyVal( &dataObjCopyInp.destDataObjInp.condInput );\n clearKeyVal( &dataObjCopyInp.srcDataObjInp.condInput );\n return 0;\n }\n\n addKeyVal( &dataObjCopyInp.destDataObjInp.condInput, REG_CHKSUM_KW,\n srcChksumStr );\n status = rsDataObjCopy( rsComm, &dataObjCopyInp, &transStat );\n free( transStat );\n free( srcChksumStr );\n free( destChksumStr );\n clearKeyVal( &dataObjCopyInp.destDataObjInp.condInput );\n clearKeyVal( &dataObjCopyInp.srcDataObjInp.condInput );\n\n if ( status >= 0 ) {\n return SYS_RSYNC_TARGET_MODIFIED;\n }\n else {\n return status;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Graphics\/CullingList.hpp>\n#include <Nazara\/Graphics\/Debug.hpp>\n\nnamespace Nz\n{\n\ttemplate<typename T>\n\tCullingList<T>::~CullingList()\n\t{\n\t\tOnCullingListRelease(this);\n\t}\n\n\ttemplate<typename T>\n\tstd::size_t CullingList<T>::Cull(const Frustumf& frustum, bool* forceInvalidation)\n\t{\n\t\tm_results.clear();\n\n\t\tbool forcedInvalidation = false;\n\n\t\tstd::size_t visibleHash = 0U;\n\n\t\tfor (NoTestVisibilityEntry& entry : m_noTestList)\n\t\t{\n\t\t\tm_results.push_back(entry.renderable);\n\t\t\tNz::HashCombine(visibleHash, entry.renderable);\n\n\t\t\tif (entry.forceInvalidation)\n\t\t\t{\n\t\t\t\tforcedInvalidation = true;\n\t\t\t\tentry.forceInvalidation = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (SphereVisibilityEntry& entry : m_sphereTestList)\n\t\t{\n\t\t\tif (frustum.Contains(entry.sphere))\n\t\t\t{\n\t\t\t\tm_results.push_back(entry.renderable);\n\t\t\t\tNz::HashCombine(visibleHash, entry.renderable);\n\n\t\t\t\tif (entry.forceInvalidation)\n\t\t\t\t{\n\t\t\t\t\tforcedInvalidation = true;\n\t\t\t\t\tentry.forceInvalidation = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (VolumeVisibilityEntry& entry : m_volumeTestList)\n\t\t{\n\t\t\tif (frustum.Contains(entry.volume))\n\t\t\t{\n\t\t\t\tm_results.push_back(entry.renderable);\n\t\t\t\tNz::HashCombine(visibleHash, entry.renderable);\n\n\t\t\t\tif (entry.forceInvalidation)\n\t\t\t\t{\n\t\t\t\t\tforcedInvalidation = true;\n\t\t\t\t\tentry.forceInvalidation = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (forceInvalidation)\n\t\t\t*forceInvalidation = forcedInvalidation;\n\n\t\treturn visibleHash;\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::NoTestEntry CullingList<T>::RegisterNoTest(const T* renderable)\n\t{\n\t\tNoTestEntry entry(this, m_noTestList.size());\n\t\tm_noTestList.emplace_back(NoTestVisibilityEntry{&entry, renderable, false}); \/\/< Address of entry will be updated when moving\n\n\t\treturn entry;\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::SphereEntry CullingList<T>::RegisterSphereTest(const T* renderable)\n\t{\n\t\tSphereEntry entry(this, m_sphereTestList.size());\n\t\tm_sphereTestList.emplace_back(SphereVisibilityEntry{Nz::Spheref(), &entry, renderable, false}); \/\/< Address of entry will be updated when moving\n\n\t\treturn entry;\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::VolumeEntry CullingList<T>::RegisterVolumeTest(const T* renderable)\n\t{\n\t\tVolumeEntry entry(this, m_volumeTestList.size());\n\t\tm_volumeTestList.emplace_back(VolumeVisibilityEntry{Nz::BoundingVolumef(), &entry, renderable, false}); \/\/< Address of entry will be updated when moving\n\n\t\treturn entry;\n\t}\n\n\t\/\/ Interface STD\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::iterator CullingList<T>::begin()\n\t{\n\t\treturn m_results.begin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_iterator CullingList<T>::begin() const\n\t{\n\t\treturn m_results.begin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_iterator CullingList<T>::cbegin() const\n\t{\n\t\treturn m_results.cbegin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_iterator CullingList<T>::cend() const\n\t{\n\t\treturn m_results.cend();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_reverse_iterator CullingList<T>::crbegin() const\n\t{\n\t\treturn m_results.crbegin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_reverse_iterator CullingList<T>::crend() const\n\t{\n\t\treturn m_results.crend();\n\t}\n\n\ttemplate<typename T>\n\tbool CullingList<T>::empty() const\n\t{\n\t\treturn m_results.empty();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::iterator CullingList<T>::end()\n\t{\n\t\treturn m_results.end();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_iterator CullingList<T>::end() const\n\t{\n\t\treturn m_results.end();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::reverse_iterator CullingList<T>::rbegin()\n\t{\n\t\treturn m_results.rbegin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_reverse_iterator CullingList<T>::rbegin() const\n\t{\n\t\treturn m_results.rbegin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::reverse_iterator CullingList<T>::rend()\n\t{\n\t\treturn m_results.rend();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_reverse_iterator CullingList<T>::rend() const\n\t{\n\t\treturn m_results.rend();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::size_type CullingList<T>::size() const\n\t{\n\t\treturn m_results.size();\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifyForceInvalidation(CullTest type, std::size_t index)\n\t{\n\t\tswitch (type)\n\t\t{\n\t\t\tcase CullTest::NoTest:\n\t\t\t{\n\t\t\t\tm_noTestList[index].forceInvalidation = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Sphere:\n\t\t\t{\n\t\t\t\tm_sphereTestList[index].forceInvalidation = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Volume:\n\t\t\t{\n\t\t\t\tm_volumeTestList[index].forceInvalidation = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tNazaraInternalError(\"Unhandled culltype\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifyMovement(CullTest type, std::size_t index, void* oldPtr, void* newPtr)\n\t{\n\t\tswitch (type)\n\t\t{\n\t\t\tcase CullTest::NoTest:\n\t\t\t{\n\t\t\t\tNoTestVisibilityEntry& entry = m_noTestList[index];\n\t\t\t\tNazaraAssert(entry.entry == oldPtr, \"Invalid entry\");\n\n\t\t\t\tentry.entry = static_cast<NoTestEntry*>(newPtr);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Sphere:\n\t\t\t{\n\t\t\t\tSphereVisibilityEntry& entry = m_sphereTestList[index];\n\t\t\t\tNazaraAssert(entry.entry == oldPtr, \"Invalid sphere entry\");\n\n\t\t\t\tentry.entry = static_cast<SphereEntry*>(newPtr);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Volume:\n\t\t\t{\n\t\t\t\tVolumeVisibilityEntry& entry = m_volumeTestList[index];\n\t\t\t\tNazaraAssert(entry.entry == oldPtr, \"Invalid volume entry\");\n\n\t\t\t\tentry.entry = static_cast<VolumeEntry*>(newPtr);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tNazaraInternalError(\"Unhandled culltype\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifyRelease(CullTest type, std::size_t index)\n\t{\n\t\tswitch (type)\n\t\t{\n\t\t\tcase CullTest::NoTest:\n\t\t\t{\n\t\t\t\tm_noTestList[index] = std::move(m_noTestList.back());\n\t\t\t\tm_noTestList[index].entry->UpdateIndex(index);\n\t\t\t\tm_noTestList.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Sphere:\n\t\t\t{\n\t\t\t\tm_sphereTestList[index] = std::move(m_sphereTestList.back());\n\t\t\t\tm_sphereTestList[index].entry->UpdateIndex(index);\n\t\t\t\tm_sphereTestList.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Volume:\n\t\t\t{\n\t\t\t\tm_volumeTestList[index] = std::move(m_volumeTestList.back());\n\t\t\t\tm_volumeTestList[index].entry->UpdateIndex(index);\n\t\t\t\tm_volumeTestList.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tNazaraInternalError(\"Unhandled culltype\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifySphereUpdate(std::size_t index, const Spheref& sphere)\n\t{\n\t\tm_sphereTestList[index].sphere = sphere;\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifyVolumeUpdate(std::size_t index, const BoundingVolumef& boundingVolume)\n\t{\n\t\tm_volumeTestList[index].volume = boundingVolume;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>::Entry<Type>::Entry() :\n\tm_parent(nullptr)\n\t{\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>::Entry<Type>::Entry(CullingList* parent, std::size_t index) :\n\tm_index(index),\n\tm_parent(parent)\n\t{\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>::Entry<Type>::Entry(Entry&& entry) :\n\tm_index(entry.m_index),\n\tm_parent(entry.m_parent)\n\t{\n\t\tif (m_parent)\n\t\t\tm_parent->NotifyMovement(Type, m_index, &entry, this);\n\n\t\tentry.m_parent = nullptr;\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>::Entry<Type>::~Entry()\n\t{\n\t\tif (m_parent)\n\t\t\tm_parent->NotifyRelease(Type, m_index);\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tvoid CullingList<T>::Entry<Type>::ForceInvalidation()\n\t{\n\t\tm_parent->NotifyForceInvalidation(Type, m_index);\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>* CullingList<T>::Entry<Type>::GetParent() const\n\t{\n\t\treturn m_parent;\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tvoid CullingList<T>::Entry<Type>::UpdateIndex(std::size_t index)\n\t{\n\t\tm_index = index;\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\ttypename CullingList<T>::Entry<Type>& CullingList<T>::Entry<Type>::operator=(Entry&& entry)\n\t{\n\t\tm_index = entry.m_index;\n\t\tm_parent = entry.m_parent;\n\t\tif (m_parent)\n\t\t\tm_parent->NotifyMovement(Type, m_index, &entry, this);\n\n\t\tentry.m_parent = nullptr;\n\n\t\treturn *this;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate<typename T>\n\tCullingList<T>::NoTestEntry::NoTestEntry() :\n\tEntry()\n\t{\n\t}\n\n\ttemplate<typename T>\n\tCullingList<T>::NoTestEntry::NoTestEntry(CullingList* parent, std::size_t index) :\n\tEntry(parent, index)\n\t{\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate<typename T>\n\tCullingList<T>::SphereEntry::SphereEntry() :\n\tEntry()\n\t{\n\t}\n\n\ttemplate<typename T>\n\tCullingList<T>::SphereEntry::SphereEntry(CullingList* parent, std::size_t index) :\n\tEntry(parent, index)\n\t{\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::SphereEntry::UpdateSphere(const Spheref& sphere)\n\t{\n\t\tm_parent->NotifySphereUpdate(m_index, sphere);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\ttemplate<typename T>\n\tCullingList<T>::VolumeEntry::VolumeEntry() :\n\tEntry()\n\t{\n\t}\n\n\ttemplate<typename T>\n\tCullingList<T>::VolumeEntry::VolumeEntry(CullingList* parent, std::size_t index) :\n\tEntry(parent, index)\n\t{\n\t}\n\n\ttemplate<typename T>\n\tvoid Nz::CullingList<T>::VolumeEntry::UpdateVolume(const BoundingVolumef& volume)\n\t{\n\t\tm_parent->NotifyVolumeUpdate(m_index, volume);\n\t}\n}\n\n#include <Nazara\/Graphics\/DebugOff.hpp>\n<commit_msg>Graphics\/CullingList: Fix some compilation errors<commit_after>\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Graphics\/CullingList.hpp>\n#include <Nazara\/Graphics\/Debug.hpp>\n\nnamespace Nz\n{\n\ttemplate<typename T>\n\tCullingList<T>::~CullingList()\n\t{\n\t\tOnCullingListRelease(this);\n\t}\n\n\ttemplate<typename T>\n\tstd::size_t CullingList<T>::Cull(const Frustumf& frustum, bool* forceInvalidation)\n\t{\n\t\tm_results.clear();\n\n\t\tbool forcedInvalidation = false;\n\n\t\tstd::size_t visibleHash = 0U;\n\n\t\tfor (NoTestVisibilityEntry& entry : m_noTestList)\n\t\t{\n\t\t\tm_results.push_back(entry.renderable);\n\t\t\tNz::HashCombine(visibleHash, entry.renderable);\n\n\t\t\tif (entry.forceInvalidation)\n\t\t\t{\n\t\t\t\tforcedInvalidation = true;\n\t\t\t\tentry.forceInvalidation = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (SphereVisibilityEntry& entry : m_sphereTestList)\n\t\t{\n\t\t\tif (frustum.Contains(entry.sphere))\n\t\t\t{\n\t\t\t\tm_results.push_back(entry.renderable);\n\t\t\t\tNz::HashCombine(visibleHash, entry.renderable);\n\n\t\t\t\tif (entry.forceInvalidation)\n\t\t\t\t{\n\t\t\t\t\tforcedInvalidation = true;\n\t\t\t\t\tentry.forceInvalidation = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (VolumeVisibilityEntry& entry : m_volumeTestList)\n\t\t{\n\t\t\tif (frustum.Contains(entry.volume))\n\t\t\t{\n\t\t\t\tm_results.push_back(entry.renderable);\n\t\t\t\tNz::HashCombine(visibleHash, entry.renderable);\n\n\t\t\t\tif (entry.forceInvalidation)\n\t\t\t\t{\n\t\t\t\t\tforcedInvalidation = true;\n\t\t\t\t\tentry.forceInvalidation = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (forceInvalidation)\n\t\t\t*forceInvalidation = forcedInvalidation;\n\n\t\treturn visibleHash;\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::NoTestEntry CullingList<T>::RegisterNoTest(const T* renderable)\n\t{\n\t\tNoTestEntry entry(this, m_noTestList.size());\n\t\tm_noTestList.emplace_back(NoTestVisibilityEntry{&entry, renderable, false}); \/\/< Address of entry will be updated when moving\n\n\t\treturn entry;\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::SphereEntry CullingList<T>::RegisterSphereTest(const T* renderable)\n\t{\n\t\tSphereEntry entry(this, m_sphereTestList.size());\n\t\tm_sphereTestList.emplace_back(SphereVisibilityEntry{Nz::Spheref(), &entry, renderable, false}); \/\/< Address of entry will be updated when moving\n\n\t\treturn entry;\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::VolumeEntry CullingList<T>::RegisterVolumeTest(const T* renderable)\n\t{\n\t\tVolumeEntry entry(this, m_volumeTestList.size());\n\t\tm_volumeTestList.emplace_back(VolumeVisibilityEntry{Nz::BoundingVolumef(), &entry, renderable, false}); \/\/< Address of entry will be updated when moving\n\n\t\treturn entry;\n\t}\n\n\t\/\/ Interface STD\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::iterator CullingList<T>::begin()\n\t{\n\t\treturn m_results.begin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_iterator CullingList<T>::begin() const\n\t{\n\t\treturn m_results.begin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_iterator CullingList<T>::cbegin() const\n\t{\n\t\treturn m_results.cbegin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_iterator CullingList<T>::cend() const\n\t{\n\t\treturn m_results.cend();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_reverse_iterator CullingList<T>::crbegin() const\n\t{\n\t\treturn m_results.crbegin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_reverse_iterator CullingList<T>::crend() const\n\t{\n\t\treturn m_results.crend();\n\t}\n\n\ttemplate<typename T>\n\tbool CullingList<T>::empty() const\n\t{\n\t\treturn m_results.empty();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::iterator CullingList<T>::end()\n\t{\n\t\treturn m_results.end();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_iterator CullingList<T>::end() const\n\t{\n\t\treturn m_results.end();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::reverse_iterator CullingList<T>::rbegin()\n\t{\n\t\treturn m_results.rbegin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_reverse_iterator CullingList<T>::rbegin() const\n\t{\n\t\treturn m_results.rbegin();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::reverse_iterator CullingList<T>::rend()\n\t{\n\t\treturn m_results.rend();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::const_reverse_iterator CullingList<T>::rend() const\n\t{\n\t\treturn m_results.rend();\n\t}\n\n\ttemplate<typename T>\n\ttypename CullingList<T>::ResultContainer::size_type CullingList<T>::size() const\n\t{\n\t\treturn m_results.size();\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifyForceInvalidation(CullTest type, std::size_t index)\n\t{\n\t\tswitch (type)\n\t\t{\n\t\t\tcase CullTest::NoTest:\n\t\t\t{\n\t\t\t\tm_noTestList[index].forceInvalidation = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Sphere:\n\t\t\t{\n\t\t\t\tm_sphereTestList[index].forceInvalidation = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Volume:\n\t\t\t{\n\t\t\t\tm_volumeTestList[index].forceInvalidation = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tNazaraInternalError(\"Unhandled culltype\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifyMovement(CullTest type, std::size_t index, void* oldPtr, void* newPtr)\n\t{\n\t\tswitch (type)\n\t\t{\n\t\t\tcase CullTest::NoTest:\n\t\t\t{\n\t\t\t\tNoTestVisibilityEntry& entry = m_noTestList[index];\n\t\t\t\tNazaraAssert(entry.entry == oldPtr, \"Invalid entry\");\n\n\t\t\t\tentry.entry = static_cast<NoTestEntry*>(newPtr);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Sphere:\n\t\t\t{\n\t\t\t\tSphereVisibilityEntry& entry = m_sphereTestList[index];\n\t\t\t\tNazaraAssert(entry.entry == oldPtr, \"Invalid sphere entry\");\n\n\t\t\t\tentry.entry = static_cast<SphereEntry*>(newPtr);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Volume:\n\t\t\t{\n\t\t\t\tVolumeVisibilityEntry& entry = m_volumeTestList[index];\n\t\t\t\tNazaraAssert(entry.entry == oldPtr, \"Invalid volume entry\");\n\n\t\t\t\tentry.entry = static_cast<VolumeEntry*>(newPtr);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tNazaraInternalError(\"Unhandled culltype\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifyRelease(CullTest type, std::size_t index)\n\t{\n\t\tswitch (type)\n\t\t{\n\t\t\tcase CullTest::NoTest:\n\t\t\t{\n\t\t\t\tm_noTestList[index] = std::move(m_noTestList.back());\n\t\t\t\tm_noTestList[index].entry->UpdateIndex(index);\n\t\t\t\tm_noTestList.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Sphere:\n\t\t\t{\n\t\t\t\tm_sphereTestList[index] = std::move(m_sphereTestList.back());\n\t\t\t\tm_sphereTestList[index].entry->UpdateIndex(index);\n\t\t\t\tm_sphereTestList.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CullTest::Volume:\n\t\t\t{\n\t\t\t\tm_volumeTestList[index] = std::move(m_volumeTestList.back());\n\t\t\t\tm_volumeTestList[index].entry->UpdateIndex(index);\n\t\t\t\tm_volumeTestList.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tNazaraInternalError(\"Unhandled culltype\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifySphereUpdate(std::size_t index, const Spheref& sphere)\n\t{\n\t\tm_sphereTestList[index].sphere = sphere;\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::NotifyVolumeUpdate(std::size_t index, const BoundingVolumef& boundingVolume)\n\t{\n\t\tm_volumeTestList[index].volume = boundingVolume;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>::Entry<Type>::Entry() :\n\tm_parent(nullptr)\n\t{\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>::Entry<Type>::Entry(CullingList* parent, std::size_t index) :\n\tm_index(index),\n\tm_parent(parent)\n\t{\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>::Entry<Type>::Entry(Entry&& entry) :\n\tm_index(entry.m_index),\n\tm_parent(entry.m_parent)\n\t{\n\t\tif (m_parent)\n\t\t\tm_parent->NotifyMovement(Type, m_index, &entry, this);\n\n\t\tentry.m_parent = nullptr;\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>::Entry<Type>::~Entry()\n\t{\n\t\tif (m_parent)\n\t\t\tm_parent->NotifyRelease(Type, m_index);\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tvoid CullingList<T>::Entry<Type>::ForceInvalidation()\n\t{\n\t\tm_parent->NotifyForceInvalidation(Type, m_index);\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tCullingList<T>* CullingList<T>::Entry<Type>::GetParent() const\n\t{\n\t\treturn m_parent;\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\tvoid CullingList<T>::Entry<Type>::UpdateIndex(std::size_t index)\n\t{\n\t\tm_index = index;\n\t}\n\n\ttemplate<typename T>\n\ttemplate<CullTest Type>\n\ttypename CullingList<T>::Entry<Type>& CullingList<T>::Entry<Type>::operator=(Entry&& entry)\n\t{\n\t\tm_index = entry.m_index;\n\t\tm_parent = entry.m_parent;\n\t\tif (m_parent)\n\t\t\tm_parent->NotifyMovement(Type, m_index, &entry, this);\n\n\t\tentry.m_parent = nullptr;\n\n\t\treturn *this;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate<typename T>\n\tCullingList<T>::NoTestEntry::NoTestEntry() :\n\tEntry<CullTest::NoTest>()\n\t{\n\t}\n\n\ttemplate<typename T>\n\tCullingList<T>::NoTestEntry::NoTestEntry(CullingList* parent, std::size_t index) :\n\tEntry<CullTest::NoTest>(parent, index)\n\t{\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate<typename T>\n\tCullingList<T>::SphereEntry::SphereEntry() :\n\tEntry<CullTest::Sphere>()\n\t{\n\t}\n\n\ttemplate<typename T>\n\tCullingList<T>::SphereEntry::SphereEntry(CullingList* parent, std::size_t index) :\n\tEntry<CullTest::Sphere>(parent, index)\n\t{\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::SphereEntry::UpdateSphere(const Spheref& sphere)\n\t{\n\t\tthis->m_parent->NotifySphereUpdate(this->m_index, sphere);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\ttemplate<typename T>\n\tCullingList<T>::VolumeEntry::VolumeEntry() :\n\tEntry<CullTest::Volume>()\n\t{\n\t}\n\n\ttemplate<typename T>\n\tCullingList<T>::VolumeEntry::VolumeEntry(CullingList* parent, std::size_t index) :\n\tEntry<CullTest::Volume>(parent, index)\n\t{\n\t}\n\n\ttemplate<typename T>\n\tvoid CullingList<T>::VolumeEntry::UpdateVolume(const BoundingVolumef& volume)\n\t{\n\t\tthis->m_parent->NotifyVolumeUpdate(this->m_index, volume);\n\t}\n}\n\n#include <Nazara\/Graphics\/DebugOff.hpp>\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file allocator_traits.hpp\n *\n * \\brief This header contains the trait type \\c allocator_traits that\n * determines or infers default values for the Allocator concept\n *\n * \\author Matthew Rodusek (matthew.rodusek@gmail.com)\n *\/\n#ifndef BIT_MEMORY_ALLOCATORS_ALLOCATOR_TRAITS_HPP\n#define BIT_MEMORY_ALLOCATORS_ALLOCATOR_TRAITS_HPP\n\n#include \"concepts\/Stateless.hpp\" \/\/ is_stateless\n#include \"concepts\/Allocator.hpp\" \/\/ is_allocator, allocator_has_allocate,\n#include \"concepts\/ExtendedAllocator.hpp\" \/\/ allocator_has_extended_try_allocate\n\n#include \"allocator_reference.hpp\" \/\/ allocator_reference\n#include \"allocator_info.hpp\" \/\/ allocator_info\n#include \"errors.hpp\" \/\/ get_out_of_memory_handler\n#include \"macros.hpp\" \/\/ BIT_MEMORY_UNUSED\n#include \"owner.hpp\" \/\/ owner\n\n#include <type_traits> \/\/ std::true_type, std::false_type, etc\n#include <cstddef> \/\/ std::size_t, std::ptrdiff_t\n#include <limits> \/\/ std::numeric_limits\n#include <memory> \/\/ std::addressof\n\nnamespace bit {\n namespace memory {\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \\brief The allocator_traits class template provides a standardized\n \/\/\/ way to access allocator functionality\n \/\/\/\n \/\/\/ This will infer defaults for any optional values that may not be\n \/\/\/ present in the allocator\n \/\/\/\n \/\/\/ \\tparam Allocator the allocator type. Must satisfy Allocator concept\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template<typename Allocator>\n class allocator_traits\n {\n\n static_assert( is_allocator<Allocator>::value, \"Allocator must be an Allocator\" );\n\n \/\/----------------------------------------------------------------------\n \/\/ Public Members\n \/\/----------------------------------------------------------------------\n public:\n\n using size_type = allocator_size_type_t<Allocator>;\n using difference_type = allocator_difference_type_t<Allocator>;\n using pointer = allocator_pointer_t<Allocator>;\n using const_pointer = allocator_const_pointer_t<Allocator>;\n\n using is_always_equal = allocator_is_always_equal<Allocator>;\n using is_stateless = is_stateless<Allocator>;\n using default_alignment = allocator_default_alignment<Allocator>;\n using max_alignment = allocator_max_alignment<Allocator>;\n using can_truncate_deallocations = allocator_can_truncate_deallocations<Allocator>;\n using knows_ownership = allocator_knows_ownership<Allocator>;\n\n \/\/----------------------------------------------------------------------\n \/\/ Allocation\n \/\/----------------------------------------------------------------------\n public:\n\n \/\/\/ \\brief Attempts to allocate memory of at least \\p size bytes,\n \/\/\/ aligned to \\p align boundary\n \/\/\/\n \/\/\/ On failure, this function returns \\p nullptr\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\return the pointer to the allocated memory\n static pointer try_allocate( Allocator& alloc,\n size_type size,\n size_type align ) noexcept;\n\n \/\/\/ \\brief Attempts to allocate memory of at least \\p size bytes,\n \/\/\/ aligned to \\p align boundary with an offset of \\p offset bytes\n \/\/\/\n \/\/\/ On failure, this function returns \\p nullptr\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\param offset the offset of the allocation\n \/\/\/ \\return the pointer to the allocated memory\n template<typename U = Allocator, typename = std::enable_if<is_extended_allocator<U>::value>>\n static pointer try_allocate( Allocator& alloc,\n size_type size,\n size_type align,\n size_type offset ) noexcept;\n\n \/\/\/ \\brief Allocates memory of at least \\p size bytes, aligned to \\p\n \/\/\/ align boundary\n \/\/\/\n \/\/\/ On failure, this function may throw or invoke the out_of_memory\n \/\/\/ handler before returning \\p nullptr\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\return the pointer to the allocated member\n static pointer allocate( Allocator& alloc,\n size_type size,\n size_type align );\n\n \/\/\/ \\brief Allocates memory of at least \\p size bytes, aligned to \\p\n \/\/\/ align boundary\n \/\/\/\n \/\/\/ On failure, this function may throw or invoke the out_of_memory\n \/\/\/ handler before returning \\p nullptr\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\param offset the offset of the allocation\n \/\/\/ \\return the pointer to the allocated member\n template<typename U = Allocator, typename = std::enable_if<allocator_has_extended_allocate<U>::value>>\n static pointer allocate( Allocator& alloc,\n size_type size,\n size_type align,\n size_type offset );\n\n \/\/----------------------------------------------------------------------\n \/\/ Deallocation\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\brief Deallocates a pointer previously allocated with \\p allocate\n \/\/\/ or try_allocate\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param p the pointer to deallocate\n \/\/\/ \\param size the size of the allocation\n static void deallocate( Allocator& alloc, pointer p, size_type size );\n\n \/\/----------------------------------------------------------------------\n \/\/ Observers\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\brief Checks if the given allocator is known to own the specified\n \/\/\/ pointer \\p p\n \/\/\/\n \/\/\/ \\note This directly invokes \\c alloc.owns(p) . It is undefined\n \/\/\/ behaviour to invoke this if \\c Allocator::owns is not\n \/\/\/ defined; branches should instead be taken by using\n \/\/\/ \\ref knows_ownership\n \/\/\/\n \/\/\/ \\param alloc the allocator\n \/\/\/ \\param p the pointer\n static bool owns( Allocator& alloc, const_pointer p ) noexcept;\n\n \/\/\/ \\brief Gets the name of the specified allocator\n \/\/\/\n \/\/\/ \\note Not all allocators are nameable or have a name specified.\n \/\/\/ For these allocators, the string returned is \"Unnamed\"\n \/\/\/\n \/\/\/ \\note The lifetime of the pointer returned is unmanaged, and is NOT\n \/\/\/ the responsibility of the caller to free.\n \/\/\/\n \/\/\/ \\param alloc the allocator to get the name of\n \/\/\/ \\return the name of the allocator\n static allocator_info info( const Allocator& alloc ) noexcept;\n\n \/\/----------------------------------------------------------------------\n \/\/ Capacity\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\brief Gets the maximum size allocateable from this allocator\n \/\/\/\n \/\/\/ \\note the max_size does not guarantee that the size is able to be\n \/\/\/ allocated at the time the value is queried; it just means that\n \/\/\/ it is the maximum size that the allocator is capable of\n \/\/\/ allocating from an empty state.\n \/\/\/\n \/\/\/ \\param alloc the allocator to get the max size from\n \/\/\/ \\return the amount of bytes available for the largest possible\n \/\/\/ allocation\n static size_type max_size( const Allocator& alloc ) noexcept;\n\n \/\/\/ \\brief Gets the minimum size allocateable from this allocator\n \/\/\/\n \/\/\/ \\note The default is 1, if this function is not defined\n \/\/\/\n \/\/\/ \\param alloc the allocator to get the min size from\n \/\/\/ \\return the minimum amount of bytes able to allocated\n static size_type min_size( const Allocator& alloc ) noexcept;\n\n \/\/----------------------------------------------------------------------\n \/\/ Private Implementation\n \/\/----------------------------------------------------------------------\n private:\n\n \/\/\/ \\{\n \/\/\/ \\brief Performs the allocation, either by calling\n \/\/\/ \\c Allocator::allocate, or by calling into\n \/\/\/ \\c Allocator::try_allocate and defining a boilerplate\n \/\/\/ allocate function\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\param offset the offset of the alignment\n \/\/\/ \\return the allocated pointer\n static pointer do_allocate( std::true_type, Allocator& alloc, size_type size, size_type align );\n static pointer do_allocate( std::false_type, Allocator& alloc, size_type size, size_type align );\n static pointer do_allocate( std::true_type, Allocator& alloc, size_type size, size_type align, size_type offset );\n static pointer do_allocate( std::false_type, Allocator& alloc, size_type size, size_type align, size_type offset );\n \/\/\/ \\}\n\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\{\n \/\/\/ \\brief Determines the max size of the allocator, either by\n \/\/\/ calling \\c Allocator::max_size, or by assuming\n \/\/\/ \\c std::numeric_limits<size_type>::max()\n \/\/\/\n \/\/\/ \\param alloc the allocator\n \/\/\/ \\return the max size\n static size_type do_max_size( std::true_type, const Allocator& alloc );\n static size_type do_max_size( std::false_type, const Allocator& alloc );\n \/\/\/ \\}\n\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\{\n \/\/\/ \\brief Determines the min size of an allocation, either by\n \/\/\/ calling \\c Allocator::min_size(), or by assuming\n \/\/\/ \\c 1\n \/\/\/\n \/\/\/ \\param alloc the allocator\n \/\/\/ \\return the max size\n static size_type do_min_size( std::true_type, const Allocator& alloc );\n static size_type do_min_size( std::false_type, const Allocator& alloc );\n \/\/\/ \\}\n\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\{\n \/\/\/ \\brief Determines the info for the allocator, either by calling\n \/\/\/ \\c Allocator::info or by assuming \"Unnamed\" for the name\n \/\/\/\n \/\/\/ \\param alloc the allocator\n \/\/\/ \\return the name of the allocator\n static allocator_info do_info( std::true_type, const Allocator& alloc );\n static allocator_info do_info( std::false_type, const Allocator& alloc );\n \/\/\/ \\}\n\n };\n\n template<typename Allocator>\n class allocator_traits<allocator_reference<Allocator>>\n : public allocator_traits<Allocator>\n {\n\n };\n\n } \/\/ namespace memory\n} \/\/ namespace bit\n\n#include \"detail\/allocator_traits.inl\"\n\n#endif \/* BIT_MEMORY_ALLOCATORS_ALLOCATOR_TRAITS_HPP *\/\n<commit_msg>Fixed failing gcc build<commit_after>\/**\n * \\file allocator_traits.hpp\n *\n * \\brief This header contains the trait type \\c allocator_traits that\n * determines or infers default values for the Allocator concept\n *\n * \\author Matthew Rodusek (matthew.rodusek@gmail.com)\n *\/\n#ifndef BIT_MEMORY_ALLOCATORS_ALLOCATOR_TRAITS_HPP\n#define BIT_MEMORY_ALLOCATORS_ALLOCATOR_TRAITS_HPP\n\n#include \"concepts\/Stateless.hpp\" \/\/ is_stateless\n#include \"concepts\/Allocator.hpp\" \/\/ is_allocator, allocator_has_allocate,\n#include \"concepts\/ExtendedAllocator.hpp\" \/\/ allocator_has_extended_try_allocate\n\n#include \"allocator_reference.hpp\" \/\/ allocator_reference\n#include \"allocator_info.hpp\" \/\/ allocator_info\n#include \"errors.hpp\" \/\/ get_out_of_memory_handler\n#include \"macros.hpp\" \/\/ BIT_MEMORY_UNUSED\n#include \"owner.hpp\" \/\/ owner\n\n#include <type_traits> \/\/ std::true_type, std::false_type, etc\n#include <cstddef> \/\/ std::size_t, std::ptrdiff_t\n#include <limits> \/\/ std::numeric_limits\n#include <memory> \/\/ std::addressof\n\nnamespace bit {\n namespace memory {\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ \\brief The allocator_traits class template provides a standardized\n \/\/\/ way to access allocator functionality\n \/\/\/\n \/\/\/ This will infer defaults for any optional values that may not be\n \/\/\/ present in the allocator\n \/\/\/\n \/\/\/ \\tparam Allocator the allocator type. Must satisfy Allocator concept\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template<typename Allocator>\n class allocator_traits\n {\n\n static_assert( is_allocator<Allocator>::value, \"Allocator must be an Allocator\" );\n\n \/\/----------------------------------------------------------------------\n \/\/ Public Members\n \/\/----------------------------------------------------------------------\n public:\n\n using size_type = allocator_size_type_t<Allocator>;\n using difference_type = allocator_difference_type_t<Allocator>;\n using pointer = allocator_pointer_t<Allocator>;\n using const_pointer = allocator_const_pointer_t<Allocator>;\n\n \/\/ qualified 'bit::memory::' to avoid '-fpermissive' errors with gcc\n using is_stateless = bit::memory::is_stateless<Allocator>;\n using is_always_equal = allocator_is_always_equal<Allocator>;\n using default_alignment = allocator_default_alignment<Allocator>;\n using max_alignment = allocator_max_alignment<Allocator>;\n using can_truncate_deallocations = allocator_can_truncate_deallocations<Allocator>;\n using knows_ownership = allocator_knows_ownership<Allocator>;\n\n \/\/----------------------------------------------------------------------\n \/\/ Allocation\n \/\/----------------------------------------------------------------------\n public:\n\n \/\/\/ \\brief Attempts to allocate memory of at least \\p size bytes,\n \/\/\/ aligned to \\p align boundary\n \/\/\/\n \/\/\/ On failure, this function returns \\p nullptr\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\return the pointer to the allocated memory\n static pointer try_allocate( Allocator& alloc,\n size_type size,\n size_type align ) noexcept;\n\n \/\/\/ \\brief Attempts to allocate memory of at least \\p size bytes,\n \/\/\/ aligned to \\p align boundary with an offset of \\p offset bytes\n \/\/\/\n \/\/\/ On failure, this function returns \\p nullptr\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\param offset the offset of the allocation\n \/\/\/ \\return the pointer to the allocated memory\n template<typename U = Allocator, typename = std::enable_if<is_extended_allocator<U>::value>>\n static pointer try_allocate( Allocator& alloc,\n size_type size,\n size_type align,\n size_type offset ) noexcept;\n\n \/\/\/ \\brief Allocates memory of at least \\p size bytes, aligned to \\p\n \/\/\/ align boundary\n \/\/\/\n \/\/\/ On failure, this function may throw or invoke the out_of_memory\n \/\/\/ handler before returning \\p nullptr\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\return the pointer to the allocated member\n static pointer allocate( Allocator& alloc,\n size_type size,\n size_type align );\n\n \/\/\/ \\brief Allocates memory of at least \\p size bytes, aligned to \\p\n \/\/\/ align boundary\n \/\/\/\n \/\/\/ On failure, this function may throw or invoke the out_of_memory\n \/\/\/ handler before returning \\p nullptr\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\param offset the offset of the allocation\n \/\/\/ \\return the pointer to the allocated member\n template<typename U = Allocator, typename = std::enable_if<allocator_has_extended_allocate<U>::value>>\n static pointer allocate( Allocator& alloc,\n size_type size,\n size_type align,\n size_type offset );\n\n \/\/----------------------------------------------------------------------\n \/\/ Deallocation\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\brief Deallocates a pointer previously allocated with \\p allocate\n \/\/\/ or try_allocate\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate from\n \/\/\/ \\param p the pointer to deallocate\n \/\/\/ \\param size the size of the allocation\n static void deallocate( Allocator& alloc, pointer p, size_type size );\n\n \/\/----------------------------------------------------------------------\n \/\/ Observers\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\brief Checks if the given allocator is known to own the specified\n \/\/\/ pointer \\p p\n \/\/\/\n \/\/\/ \\note This directly invokes \\c alloc.owns(p) . It is undefined\n \/\/\/ behaviour to invoke this if \\c Allocator::owns is not\n \/\/\/ defined; branches should instead be taken by using\n \/\/\/ \\ref knows_ownership\n \/\/\/\n \/\/\/ \\param alloc the allocator\n \/\/\/ \\param p the pointer\n static bool owns( Allocator& alloc, const_pointer p ) noexcept;\n\n \/\/\/ \\brief Gets the name of the specified allocator\n \/\/\/\n \/\/\/ \\note Not all allocators are nameable or have a name specified.\n \/\/\/ For these allocators, the string returned is \"Unnamed\"\n \/\/\/\n \/\/\/ \\note The lifetime of the pointer returned is unmanaged, and is NOT\n \/\/\/ the responsibility of the caller to free.\n \/\/\/\n \/\/\/ \\param alloc the allocator to get the name of\n \/\/\/ \\return the name of the allocator\n static allocator_info info( const Allocator& alloc ) noexcept;\n\n \/\/----------------------------------------------------------------------\n \/\/ Capacity\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\brief Gets the maximum size allocateable from this allocator\n \/\/\/\n \/\/\/ \\note the max_size does not guarantee that the size is able to be\n \/\/\/ allocated at the time the value is queried; it just means that\n \/\/\/ it is the maximum size that the allocator is capable of\n \/\/\/ allocating from an empty state.\n \/\/\/\n \/\/\/ \\param alloc the allocator to get the max size from\n \/\/\/ \\return the amount of bytes available for the largest possible\n \/\/\/ allocation\n static size_type max_size( const Allocator& alloc ) noexcept;\n\n \/\/\/ \\brief Gets the minimum size allocateable from this allocator\n \/\/\/\n \/\/\/ \\note The default is 1, if this function is not defined\n \/\/\/\n \/\/\/ \\param alloc the allocator to get the min size from\n \/\/\/ \\return the minimum amount of bytes able to allocated\n static size_type min_size( const Allocator& alloc ) noexcept;\n\n \/\/----------------------------------------------------------------------\n \/\/ Private Implementation\n \/\/----------------------------------------------------------------------\n private:\n\n \/\/\/ \\{\n \/\/\/ \\brief Performs the allocation, either by calling\n \/\/\/ \\c Allocator::allocate, or by calling into\n \/\/\/ \\c Allocator::try_allocate and defining a boilerplate\n \/\/\/ allocate function\n \/\/\/\n \/\/\/ \\param alloc the allocator to allocate\n \/\/\/ \\param size the size of the allocation\n \/\/\/ \\param align the alignment of the allocation\n \/\/\/ \\param offset the offset of the alignment\n \/\/\/ \\return the allocated pointer\n static pointer do_allocate( std::true_type, Allocator& alloc, size_type size, size_type align );\n static pointer do_allocate( std::false_type, Allocator& alloc, size_type size, size_type align );\n static pointer do_allocate( std::true_type, Allocator& alloc, size_type size, size_type align, size_type offset );\n static pointer do_allocate( std::false_type, Allocator& alloc, size_type size, size_type align, size_type offset );\n \/\/\/ \\}\n\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\{\n \/\/\/ \\brief Determines the max size of the allocator, either by\n \/\/\/ calling \\c Allocator::max_size, or by assuming\n \/\/\/ \\c std::numeric_limits<size_type>::max()\n \/\/\/\n \/\/\/ \\param alloc the allocator\n \/\/\/ \\return the max size\n static size_type do_max_size( std::true_type, const Allocator& alloc );\n static size_type do_max_size( std::false_type, const Allocator& alloc );\n \/\/\/ \\}\n\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\{\n \/\/\/ \\brief Determines the min size of an allocation, either by\n \/\/\/ calling \\c Allocator::min_size(), or by assuming\n \/\/\/ \\c 1\n \/\/\/\n \/\/\/ \\param alloc the allocator\n \/\/\/ \\return the max size\n static size_type do_min_size( std::true_type, const Allocator& alloc );\n static size_type do_min_size( std::false_type, const Allocator& alloc );\n \/\/\/ \\}\n\n \/\/----------------------------------------------------------------------\n\n \/\/\/ \\{\n \/\/\/ \\brief Determines the info for the allocator, either by calling\n \/\/\/ \\c Allocator::info or by assuming \"Unnamed\" for the name\n \/\/\/\n \/\/\/ \\param alloc the allocator\n \/\/\/ \\return the name of the allocator\n static allocator_info do_info( std::true_type, const Allocator& alloc );\n static allocator_info do_info( std::false_type, const Allocator& alloc );\n \/\/\/ \\}\n\n };\n\n template<typename Allocator>\n class allocator_traits<allocator_reference<Allocator>>\n : public allocator_traits<Allocator>\n {\n\n };\n\n } \/\/ namespace memory\n} \/\/ namespace bit\n\n#include \"detail\/allocator_traits.inl\"\n\n#endif \/* BIT_MEMORY_ALLOCATORS_ALLOCATOR_TRAITS_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: include\/eos\/morphablemodel\/io\/cvssp.hpp\n *\n * Copyright 2014, 2015 Patrik Huber\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#pragma once\n\n#ifndef EOS_IO_CVSSP_HPP\n#define EOS_IO_CVSSP_HPP\n\n#include \"eos\/morphablemodel\/MorphableModel.hpp\"\n\n#include \"opencv2\/core\/core.hpp\"\n\n#include <array>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\nnamespace eos {\nnamespace morphablemodel {\n\n\/\/ Forward declaration\nstd::vector<std::array<double, 2>> load_isomap(std::string isomap_file);\n\n\/**\n * Load a shape or color model from a .scm file containing\n * a Morphable Model in the Surrey format. CVSSP's software\n * internally trains and stores the model in this custom binary\n * format and this class provides means to load them.\n *\n * Note on multi-resolution models: The landmarks to vertex-id mapping is\n * always the same. The lowest resolution model has all the landmarks defined\n * and for the higher resolutions, the mesh is divided from that on.\n * Note: For new landmarks we add, this might not be the case if we add them\n * in the highest resolution model, so take care!\n *\n * The PCA basis matrix stored in the file and loaded is the orthogonal PCA basis, i.e. it is not normalised\n * by the eigenvalues.\n *\n * @param[in] model_filename A binary .scm-file containing the model.\n * @param[in] isomap_file An optional path to an isomap containing texture coordinates.\n * @return The Morphable Model loaded from the file.\n * @throws ...\n *\/\ninline MorphableModel load_scm_model(std::string model_filename, std::string isomap_file = std::string())\n{\n using cv::Mat;\n if (sizeof(unsigned int) != 4) \/\/ note\/todo: maybe use uint32 or similar instead? Yep, but still we could encounter endianness-trouble.\n {\n std::cout << \"Warning: We're reading 4 Bytes from the file but sizeof(unsigned int) != 4. Check the code\/behaviour.\" << std::endl;\n }\n if (sizeof(double) != 8)\n {\n std::cout << \"Warning: We're reading 8 Bytes from the file but sizeof(double) != 8. Check the code\/behaviour.\" << std::endl;\n }\n\n std::ifstream model_file(model_filename, std::ios::binary);\n if (!model_file)\n {\n const std::string msg(\"Unable to open model file: \" + model_filename);\n std::cout << msg << std::endl;\n throw std::runtime_error(msg);\n }\n\n \/\/ Reading the shape model\n \/\/ Read (reference?) num triangles and vertices\n unsigned int num_vertices = 0;\n unsigned int num_triangles = 0;\n model_file.read(reinterpret_cast<char*>(&num_vertices),\n 4); \/\/ 1 char = 1 byte. uint32=4bytes. float64=8bytes.\n model_file.read(reinterpret_cast<char*>(&num_triangles), 4);\n\n \/\/ Read triangles\n std::vector<std::array<int, 3>> triangle_list;\n\n triangle_list.resize(num_triangles);\n unsigned int v0, v1, v2;\n for (unsigned int i = 0; i < num_triangles; ++i)\n {\n v0 = v1 = v2 = 0;\n model_file.read(reinterpret_cast<char*>(&v0), 4); \/\/ would be nice to pass a &vector and do it in one\n model_file.read(reinterpret_cast<char*>(&v1), 4); \/\/ go, but didn't work. Maybe a cv::Mat would work?\n model_file.read(reinterpret_cast<char*>(&v2), 4);\n triangle_list[i][0] = v0;\n triangle_list[i][1] = v1;\n triangle_list[i][2] = v2;\n }\n\n \/\/ Read number of rows and columns of the shape projection matrix (pcaBasis)\n unsigned int num_shape_pca_coeffs = 0;\n unsigned int num_shape_dims = 0; \/\/ dimension of the shape vector (3*num_vertices)\n model_file.read(reinterpret_cast<char*>(&num_shape_pca_coeffs), 4);\n model_file.read(reinterpret_cast<char*>(&num_shape_dims), 4);\n\n if (3 * num_vertices != num_shape_dims)\n {\n std::cout << \"Warning: Number of shape dimensions is not equal to three times the number of \"\n \"vertices. Something will probably go wrong during the loading.\"\n << std::endl;\n }\n\n \/\/ Read shape projection matrix\n Mat orthonormal_pca_basis_shape(num_shape_dims, num_shape_pca_coeffs,\n CV_32FC1); \/\/ m x n (rows x cols) = numShapeDims x numShapePcaCoeffs\n std::cout << \"Loading shape PCA basis matrix with \" << orthonormal_pca_basis_shape.rows << \" rows and \"\n << orthonormal_pca_basis_shape.cols << \" cols.\" << std::endl;\n for (unsigned int col = 0; col < num_shape_pca_coeffs; ++col)\n {\n for (unsigned int row = 0; row < num_shape_dims; ++row)\n {\n double var = 0.0;\n model_file.read(reinterpret_cast<char*>(&var), 8);\n orthonormal_pca_basis_shape.at<float>(row, col) = static_cast<float>(var);\n }\n }\n\n \/\/ Read mean shape vector\n unsigned int mean_dims = 0; \/\/ dimension of the mean (3*num_vertices)\n model_file.read(reinterpret_cast<char*>(&mean_dims), 4);\n if (mean_dims != num_shape_dims)\n {\n std::cout << \"Warning: Number of shape dimensions is not equal to the number of dimensions of the \"\n \"mean. Something will probably go wrong during the loading.\"\n << std::endl;\n }\n Mat mean_shape(mean_dims, 1, CV_32FC1);\n unsigned int counter = 0;\n double vd0, vd1, vd2;\n for (unsigned int i = 0; i < mean_dims \/ 3; ++i)\n {\n vd0 = vd1 = vd2 = 0.0;\n model_file.read(reinterpret_cast<char*>(&vd0), 8);\n model_file.read(reinterpret_cast<char*>(&vd1), 8);\n model_file.read(reinterpret_cast<char*>(&vd2), 8);\n mean_shape.at<float>(counter, 0) = static_cast<float>(vd0);\n ++counter;\n mean_shape.at<float>(counter, 0) = static_cast<float>(vd1);\n ++counter;\n mean_shape.at<float>(counter, 0) = static_cast<float>(vd2);\n ++counter;\n }\n\n \/\/ Read shape eigenvalues\n unsigned int num_eigenvals_shape = 0;\n model_file.read(reinterpret_cast<char*>(&num_eigenvals_shape), 4);\n if (num_eigenvals_shape != num_shape_pca_coeffs)\n {\n std::cout << \"Warning: Number of coefficients in the PCA basis matrix is not equal to the number of \"\n \"eigenvalues. Something will probably go wrong during the loading.\"\n << std::endl;\n }\n Mat eigenvalues_shape(num_eigenvals_shape, 1, CV_32FC1);\n for (unsigned int i = 0; i < num_eigenvals_shape; ++i)\n {\n double var = 0.0;\n model_file.read(reinterpret_cast<char*>(&var), 8);\n eigenvalues_shape.at<float>(i, 0) = static_cast<float>(var);\n }\n\n \/\/ Todo: We should change these to read into an Eigen matrix directly, and not into a cv::Mat first.\n using RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n const Eigen::Map<RowMajorMatrixXf> orthonormal_pca_basis_shape_(orthonormal_pca_basis_shape.ptr<float>(),\n orthonormal_pca_basis_shape.rows,\n orthonormal_pca_basis_shape.cols);\n const Eigen::Map<RowMajorMatrixXf> eigenvalues_shape_(eigenvalues_shape.ptr<float>(),\n eigenvalues_shape.rows, eigenvalues_shape.cols);\n const Eigen::Map<RowMajorMatrixXf> mean_shape_(mean_shape.ptr<float>(), mean_shape.rows, mean_shape.cols);\n const PcaModel shape_model(mean_shape_, orthonormal_pca_basis_shape_, eigenvalues_shape_, triangle_list);\n\n \/\/ Reading the color model\n \/\/ Read number of rows and columns of projection matrix\n unsigned int num_color_pca_coeffs = 0;\n unsigned int num_color_dims = 0;\n model_file.read(reinterpret_cast<char*>(&num_color_pca_coeffs), 4);\n model_file.read(reinterpret_cast<char*>(&num_color_dims), 4);\n \/\/ Read color projection matrix\n Mat orthonormal_pca_basis_color(num_color_dims, num_color_pca_coeffs, CV_32FC1);\n std::cout << \"Loading color PCA basis matrix with \" << orthonormal_pca_basis_color.rows << \" rows and \"\n << orthonormal_pca_basis_color.cols << \" cols.\" << std::endl;\n for (unsigned int col = 0; col < num_color_pca_coeffs; ++col)\n {\n for (unsigned int row = 0; row < num_color_dims; ++row)\n {\n double var = 0.0;\n model_file.read(reinterpret_cast<char*>(&var), 8);\n orthonormal_pca_basis_color.at<float>(row, col) = static_cast<float>(var);\n }\n }\n\n \/\/ Read mean color vector\n unsigned int color_mean_dims = 0; \/\/ dimension of the mean (3*num_vertices)\n model_file.read(reinterpret_cast<char*>(&color_mean_dims), 4);\n Mat mean_color(color_mean_dims, 1, CV_32FC1);\n counter = 0;\n for (unsigned int i = 0; i < color_mean_dims \/ 3; ++i)\n {\n vd0 = vd1 = vd2 = 0.0;\n model_file.read(reinterpret_cast<char*>(&vd0),\n 8); \/\/ order in hdf5: RGB. Order in OCV: BGR. But order in vertex.color: RGB\n model_file.read(reinterpret_cast<char*>(&vd1), 8);\n model_file.read(reinterpret_cast<char*>(&vd2), 8);\n mean_color.at<float>(counter, 0) = static_cast<float>(vd0);\n ++counter;\n mean_color.at<float>(counter, 0) = static_cast<float>(vd1);\n ++counter;\n mean_color.at<float>(counter, 0) = static_cast<float>(vd2);\n ++counter;\n }\n\n \/\/ Read color eigenvalues\n unsigned int num_eigenvals_color = 0;\n model_file.read(reinterpret_cast<char*>(&num_eigenvals_color), 4);\n Mat eigenvalues_color(num_eigenvals_color, 1, CV_32FC1);\n for (unsigned int i = 0; i < num_eigenvals_color; ++i)\n {\n double var = 0.0;\n model_file.read(reinterpret_cast<char*>(&var), 8);\n eigenvalues_color.at<float>(i, 0) = static_cast<float>(var);\n }\n\n \/\/ Todo: We should change these to read into an Eigen matrix directly, and not into a cv::Mat first.\n const Eigen::Map<RowMajorMatrixXf> orthonormal_pca_basis_color_(orthonormal_pca_basis_color.ptr<float>(),\n orthonormal_pca_basis_color.rows,\n orthonormal_pca_basis_color.cols);\n const Eigen::Map<RowMajorMatrixXf> eigenvalues_color_(eigenvalues_color.ptr<float>(),\n eigenvalues_color.rows, eigenvalues_color.cols);\n const Eigen::Map<RowMajorMatrixXf> mean_color_(mean_color.ptr<float>(), mean_color.rows, mean_color.cols);\n const PcaModel color_model(mean_color_, orthonormal_pca_basis_color_, eigenvalues_color_, triangle_list);\n\n model_file.close();\n\n \/\/ Load the isomap with texture coordinates if a filename has been given:\n std::vector<std::array<double, 2>> tex_coords;\n if (!isomap_file.empty())\n {\n tex_coords = load_isomap(isomap_file);\n if (shape_model.get_data_dimension() \/ 3.0f != tex_coords.size())\n {\n const std::string error_msg(\"Error, wrong number of texture coordinates. Don't have the same \"\n \"number of texcoords than the shape model has vertices.\");\n std::cout << error_msg << std::endl;\n throw std::runtime_error(error_msg);\n }\n }\n\n return MorphableModel(shape_model, color_model, cpp17::nullopt, tex_coords);\n};\n\n\/**\n * Load a set of 2D texture coordinates pre-generated by the isomap algorithm.\n * After loading, we rescale the coordinates to [0, 1] x [0, 1].\n *\n * @param[in] isomap_file Path to an isomap file containing texture coordinates.\n * @return The 2D texture coordinates for every vertex.\n * @throws ...\n *\/\ninline std::vector<std::array<double, 2>> load_isomap(std::string isomap_file)\n{\n using std::string;\n std::vector<float> x_coords, y_coords;\n string line;\n std::ifstream file(isomap_file);\n if (!file)\n {\n const string error_msg(\"The isomap file could not be opened. Did you specify a correct filename? \" + isomap_file);\n throw std::runtime_error(error_msg);\n } else\n {\n while (getline(file, line))\n {\n std::istringstream iss(line);\n string x, y;\n iss >> x >> y;\n x_coords.push_back(std::stof(x));\n y_coords.push_back(std::stof(y));\n }\n file.close();\n }\n \/\/ Process the coordinates: Find the min\/max and rescale to [0, 1] x [0, 1]\n const auto min_max_x = std::minmax_element(begin(x_coords), end(x_coords)); \/\/ min_max_x is a pair, first=min, second=max\n const auto min_max_y = std::minmax_element(begin(y_coords), end(y_coords));\n\n std::vector<std::array<double, 2>> tex_coords;\n const float divisor_x = *min_max_x.second - *min_max_x.first;\n const float divisor_y = *min_max_y.second - *min_max_y.first;\n for (int i = 0; i < x_coords.size(); ++i)\n {\n tex_coords.push_back(std::array<double, 2>{\n (x_coords[i] - *min_max_x.first) \/ divisor_x,\n 1.0f - (y_coords[i] - *min_max_y.first) \/ divisor_y}); \/\/ We rescale to [0, 1] and at the same\n \/\/ time flip the y-coords (because in the\n \/\/ isomap, the coordinates are stored\n \/\/ upside-down).\n }\n\n return tex_coords;\n};\n\n} \/* namespace morphablemodel *\/\n} \/* namespace eos *\/\n\n#endif \/* EOS_IO_CVSSP_HPP *\/\n<commit_msg>Removed the cv::Mat dependency from io\/cvssp.hpp<commit_after>\/*\n * eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: include\/eos\/morphablemodel\/io\/cvssp.hpp\n *\n * Copyright 2014, 2015 Patrik Huber\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#pragma once\n\n#ifndef EOS_IO_CVSSP_HPP\n#define EOS_IO_CVSSP_HPP\n\n#include \"eos\/morphablemodel\/MorphableModel.hpp\"\n\n#include \"Eigen\/Core\"\n\n#include <array>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\nnamespace eos {\nnamespace morphablemodel {\n\n\/\/ Forward declaration\nstd::vector<std::array<double, 2>> load_isomap(std::string isomap_file);\n\n\/**\n * Load a shape or color model from a .scm file containing\n * a Morphable Model in the Surrey format. CVSSP's software\n * internally trains and stores the model in this custom binary\n * format and this class provides means to load them.\n *\n * Note on multi-resolution models: The landmarks to vertex-id mapping is\n * always the same. The lowest resolution model has all the landmarks defined\n * and for the higher resolutions, the mesh is divided from that on.\n * Note: For new landmarks we add, this might not be the case if we add them\n * in the highest resolution model, so take care!\n *\n * The PCA basis matrix stored in the file and loaded is the orthogonal PCA basis, i.e. it is not normalised\n * by the eigenvalues.\n *\n * @param[in] model_filename A binary .scm-file containing the model.\n * @param[in] isomap_file An optional path to an isomap containing texture coordinates.\n * @return The Morphable Model loaded from the file.\n * @throws ...\n *\/\ninline MorphableModel load_scm_model(std::string model_filename, std::string isomap_file = std::string())\n{\n using Eigen::MatrixXf;\n using Eigen::VectorXf;\n\n if (sizeof(unsigned int) != 4) \/\/ note\/todo: maybe use uint32 or similar instead? Yep, but still we could encounter endianness-trouble.\n {\n std::cout << \"Warning: We're reading 4 Bytes from the file but sizeof(unsigned int) != 4. Check the code\/behaviour.\" << std::endl;\n }\n if (sizeof(double) != 8)\n {\n std::cout << \"Warning: We're reading 8 Bytes from the file but sizeof(double) != 8. Check the code\/behaviour.\" << std::endl;\n }\n\n std::ifstream model_file(model_filename, std::ios::binary);\n if (!model_file)\n {\n const std::string msg(\"Unable to open model file: \" + model_filename);\n std::cout << msg << std::endl;\n throw std::runtime_error(msg);\n }\n\n \/\/ Reading the shape model\n \/\/ Read (reference?) num triangles and vertices\n unsigned int num_vertices = 0;\n unsigned int num_triangles = 0;\n model_file.read(reinterpret_cast<char*>(&num_vertices),\n 4); \/\/ 1 char = 1 byte. uint32=4bytes. float64=8bytes.\n model_file.read(reinterpret_cast<char*>(&num_triangles), 4);\n\n \/\/ Read triangles\n std::vector<std::array<int, 3>> triangle_list;\n\n triangle_list.resize(num_triangles);\n unsigned int v0, v1, v2;\n for (unsigned int i = 0; i < num_triangles; ++i)\n {\n v0 = v1 = v2 = 0;\n model_file.read(reinterpret_cast<char*>(&v0), 4); \/\/ would be nice to pass a &vector and do it in one\n model_file.read(reinterpret_cast<char*>(&v1), 4); \/\/ go, but didn't work. Maybe a cv::Mat would work?\n model_file.read(reinterpret_cast<char*>(&v2), 4);\n triangle_list[i][0] = v0;\n triangle_list[i][1] = v1;\n triangle_list[i][2] = v2;\n }\n\n \/\/ Read number of rows and columns of the shape projection matrix (pcaBasis)\n unsigned int num_shape_pca_coeffs = 0;\n unsigned int num_shape_dims = 0; \/\/ dimension of the shape vector (3*num_vertices)\n model_file.read(reinterpret_cast<char*>(&num_shape_pca_coeffs), 4);\n model_file.read(reinterpret_cast<char*>(&num_shape_dims), 4);\n\n if (3 * num_vertices != num_shape_dims)\n {\n std::cout << \"Warning: Number of shape dimensions is not equal to three times the number of \"\n \"vertices. Something will probably go wrong during the loading.\"\n << std::endl;\n }\n\n \/\/ Read shape projection matrix\n MatrixXf orthonormal_pca_basis_shape(\n num_shape_dims, num_shape_pca_coeffs); \/\/ m x n (rows x cols) = num_shape_dims x num_shape_pca_coeffs\n std::cout << \"Loading shape PCA basis matrix with \" << orthonormal_pca_basis_shape.rows() << \" rows and \"\n << orthonormal_pca_basis_shape.cols() << \" cols.\" << std::endl;\n for (unsigned int col = 0; col < num_shape_pca_coeffs; ++col)\n {\n for (unsigned int row = 0; row < num_shape_dims; ++row)\n {\n double var = 0.0;\n model_file.read(reinterpret_cast<char*>(&var), 8);\n orthonormal_pca_basis_shape(row, col) = static_cast<float>(var);\n }\n }\n\n \/\/ Read mean shape vector\n unsigned int mean_dims = 0; \/\/ dimension of the mean (3*num_vertices)\n model_file.read(reinterpret_cast<char*>(&mean_dims), 4);\n if (mean_dims != num_shape_dims)\n {\n std::cout << \"Warning: Number of shape dimensions is not equal to the number of dimensions of the \"\n \"mean. Something will probably go wrong during the loading.\"\n << std::endl;\n }\n VectorXf mean_shape(mean_dims);\n unsigned int counter = 0;\n double vd0, vd1, vd2;\n for (unsigned int i = 0; i < mean_dims \/ 3; ++i)\n {\n vd0 = vd1 = vd2 = 0.0;\n model_file.read(reinterpret_cast<char*>(&vd0), 8);\n model_file.read(reinterpret_cast<char*>(&vd1), 8);\n model_file.read(reinterpret_cast<char*>(&vd2), 8);\n mean_shape(counter) = static_cast<float>(vd0);\n ++counter;\n mean_shape(counter) = static_cast<float>(vd1);\n ++counter;\n mean_shape(counter) = static_cast<float>(vd2);\n ++counter;\n }\n\n \/\/ Read shape eigenvalues\n unsigned int num_eigenvals_shape = 0;\n model_file.read(reinterpret_cast<char*>(&num_eigenvals_shape), 4);\n if (num_eigenvals_shape != num_shape_pca_coeffs)\n {\n std::cout << \"Warning: Number of coefficients in the PCA basis matrix is not equal to the number of \"\n \"eigenvalues. Something will probably go wrong during the loading.\"\n << std::endl;\n }\n VectorXf eigenvalues_shape(num_eigenvals_shape);\n for (unsigned int i = 0; i < num_eigenvals_shape; ++i)\n {\n double var = 0.0;\n model_file.read(reinterpret_cast<char*>(&var), 8);\n eigenvalues_shape(i) = static_cast<float>(var);\n }\n\n const PcaModel shape_model(mean_shape, orthonormal_pca_basis_shape, eigenvalues_shape, triangle_list);\n\n \/\/ Reading the color model\n \/\/ Read number of rows and columns of projection matrix\n unsigned int num_color_pca_coeffs = 0;\n unsigned int num_color_dims = 0;\n model_file.read(reinterpret_cast<char*>(&num_color_pca_coeffs), 4);\n model_file.read(reinterpret_cast<char*>(&num_color_dims), 4);\n \/\/ Read color projection matrix\n MatrixXf orthonormal_pca_basis_color(num_color_dims, num_color_pca_coeffs);\n std::cout << \"Loading color PCA basis matrix with \" << orthonormal_pca_basis_color.rows() << \" rows and \"\n << orthonormal_pca_basis_color.cols() << \" cols.\" << std::endl;\n for (unsigned int col = 0; col < num_color_pca_coeffs; ++col)\n {\n for (unsigned int row = 0; row < num_color_dims; ++row)\n {\n double var = 0.0;\n model_file.read(reinterpret_cast<char*>(&var), 8);\n orthonormal_pca_basis_color(row, col) = static_cast<float>(var);\n }\n }\n\n \/\/ Read mean color vector\n unsigned int color_mean_dims = 0; \/\/ dimension of the mean (3*num_vertices)\n model_file.read(reinterpret_cast<char*>(&color_mean_dims), 4);\n VectorXf mean_color(color_mean_dims);\n counter = 0;\n for (unsigned int i = 0; i < color_mean_dims \/ 3; ++i)\n {\n vd0 = vd1 = vd2 = 0.0;\n model_file.read(reinterpret_cast<char*>(&vd0),\n 8); \/\/ order in hdf5: RGB. Order in OCV: BGR. But order in vertex.color: RGB\n model_file.read(reinterpret_cast<char*>(&vd1), 8);\n model_file.read(reinterpret_cast<char*>(&vd2), 8);\n mean_color(counter) = static_cast<float>(vd0);\n ++counter;\n mean_color(counter) = static_cast<float>(vd1);\n ++counter;\n mean_color(counter) = static_cast<float>(vd2);\n ++counter;\n }\n\n \/\/ Read color eigenvalues\n unsigned int num_eigenvals_color = 0;\n model_file.read(reinterpret_cast<char*>(&num_eigenvals_color), 4);\n VectorXf eigenvalues_color(num_eigenvals_color);\n for (unsigned int i = 0; i < num_eigenvals_color; ++i)\n {\n double var = 0.0;\n model_file.read(reinterpret_cast<char*>(&var), 8);\n eigenvalues_color(i) = static_cast<float>(var);\n }\n\n const PcaModel color_model(mean_color, orthonormal_pca_basis_color, eigenvalues_color, triangle_list);\n\n model_file.close();\n\n \/\/ Load the isomap with texture coordinates if a filename has been given:\n std::vector<std::array<double, 2>> tex_coords;\n if (!isomap_file.empty())\n {\n tex_coords = load_isomap(isomap_file);\n if (shape_model.get_data_dimension() \/ 3.0f != tex_coords.size())\n {\n const std::string error_msg(\"Error, wrong number of texture coordinates. Don't have the same \"\n \"number of texcoords than the shape model has vertices.\");\n std::cout << error_msg << std::endl;\n throw std::runtime_error(error_msg);\n }\n }\n\n return MorphableModel(shape_model, color_model, cpp17::nullopt, tex_coords);\n};\n\n\/**\n * Load a set of 2D texture coordinates pre-generated by the isomap algorithm.\n * After loading, we rescale the coordinates to [0, 1] x [0, 1].\n *\n * @param[in] isomap_file Path to an isomap file containing texture coordinates.\n * @return The 2D texture coordinates for every vertex.\n * @throws ...\n *\/\ninline std::vector<std::array<double, 2>> load_isomap(std::string isomap_file)\n{\n using std::string;\n std::vector<float> x_coords, y_coords;\n string line;\n std::ifstream file(isomap_file);\n if (!file)\n {\n const string error_msg(\"The isomap file could not be opened. Did you specify a correct filename? \" + isomap_file);\n throw std::runtime_error(error_msg);\n } else\n {\n while (getline(file, line))\n {\n std::istringstream iss(line);\n string x, y;\n iss >> x >> y;\n x_coords.push_back(std::stof(x));\n y_coords.push_back(std::stof(y));\n }\n file.close();\n }\n \/\/ Process the coordinates: Find the min\/max and rescale to [0, 1] x [0, 1]\n const auto min_max_x = std::minmax_element(begin(x_coords), end(x_coords)); \/\/ min_max_x is a pair, first=min, second=max\n const auto min_max_y = std::minmax_element(begin(y_coords), end(y_coords));\n\n std::vector<std::array<double, 2>> tex_coords;\n const float divisor_x = *min_max_x.second - *min_max_x.first;\n const float divisor_y = *min_max_y.second - *min_max_y.first;\n for (int i = 0; i < x_coords.size(); ++i)\n {\n tex_coords.push_back(std::array<double, 2>{\n (x_coords[i] - *min_max_x.first) \/ divisor_x,\n 1.0f - (y_coords[i] - *min_max_y.first) \/ divisor_y}); \/\/ We rescale to [0, 1] and at the same\n \/\/ time flip the y-coords (because in the\n \/\/ isomap, the coordinates are stored\n \/\/ upside-down).\n }\n\n return tex_coords;\n};\n\n} \/* namespace morphablemodel *\/\n} \/* namespace eos *\/\n\n#endif \/* EOS_IO_CVSSP_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\n#include <algorithms\/class_algorithm_status.h>\n#include <config\/enums.h>\n#include <h5pp\/h5pp.h>\n#include <string>\n#include <tools\/common\/io.h>\n#include <tools\/common\/log.h>\n#include <tools\/common\/prof.h>\n\nnamespace tools::common::io::h5attr {\n template<typename AttrType>\n void save_attr(h5pp::File &file, const AttrType &attrData, const std::string &attrName, const std::string &dsetPath, const std::string &dsetText) {\n tools::log->trace(\"Attribute -- {: <40} = {: <40} on dset: {}\", attrName, attrData, dsetPath);\n if(not file.linkExists(dsetPath)) file.writeDataset(dsetText, dsetPath);\n file.writeAttribute(attrData, attrName, dsetPath);\n }\n}\n\nnamespace tools::common::io::h5attr {\n void bootstrap_save_log(std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> &save_log, const h5pp::File &h5ppFile,\n const std::string &state_prefix) {\n if(save_log.empty()) {\n try {\n uint64_t step = 0;\n uint64_t iter = 0;\n if(h5ppFile.linkExists(\"common\/step\")) step = h5ppFile.readAttribute<uint64_t>(state_prefix, \"common\/step\");\n if(h5ppFile.linkExists(\"common\/iteration\")) iter = h5ppFile.readAttribute<uint64_t>(state_prefix, \"common\/iteration\");\n save_log[state_prefix] = std::make_pair(iter, step);\n\n } catch(const std::exception &ex) { tools::log->warn(\"Could not bootstrap save_log: {}\", ex.what()); }\n }\n }\n}\n\nvoid tools::common::io::h5attr::save_meta(h5pp::File &h5ppFile, const StorageLevel &storage_level, const StorageReason &storage_reason,\n const ModelType &model_type, size_t model_size, const AlgorithmType &algo_type, const std::string &state_name,\n const std::string &state_prefix, const std::string &model_prefix, const class_algorithm_status &status) {\n \/\/ Write metadata into \/common so that we can find state paths later.\n \/\/ Under \/common we have the following dummy datasets defining attributes which map state_prefix to useful information:\n \/\/\n \/\/ -- finished | true or 1 if state_prefix is finished\n \/\/ -- storage_level | state_prefix -> storage_level\n \/\/ -- storage_reason | state_prefix -> storage_reason\n \/\/ -- state_root | state_prefix -> state_root\n \/\/ -- hamiltonian | state_prefix -> path to hamiltonian table\n \/\/ -- mps_prefix | state_prefix -> mps_prefix\n \/\/ -- mpo_prefix | state_prefix -> mpo_prefix\n \/\/ -- model_type | state_prefix -> model_type\n \/\/ -- model_size | state_prefix -> model_size\n \/\/ -- algo_type | state_prefix -> algo_type\n \/\/ -- state_name | state_prefix -> state_name\n \/\/ -- iteration | state_prefix -> iteration\n \/\/ -- step | state_prefix -> step\n \/\/ -- position | state_prefix -> position of the mps\n\n \/\/ Checks if the current entries have already been written\n static std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> save_log;\n bootstrap_save_log(save_log, h5ppFile, state_prefix);\n\n auto save_point = std::make_pair(status.iter, status.step);\n if(save_log[state_prefix] == save_point) return;\n\n tools::common::profile::get_default_prof()[\"t_hdf\"]->tic();\n\n std::string storage_level_str(enum2str(storage_level));\n std::string storage_reason_str(enum2str(storage_reason));\n std::string model_name(enum2str(model_type));\n std::string algo_name(enum2str(algo_type));\n std::string state_root = algo_name + '\/' + state_name;\n std::string hamiltonian = model_prefix + \"\/hamiltonian\";\n std::string mpo_prefix = model_prefix + \"\/mpo\";\n std::string mps_prefix = state_prefix + \"\/mps\";\n\n save_attr(h5ppFile, status.algorithm_has_finished, state_prefix, \"common\/finished\", \"Maps state_prefix -> finished\");\n save_attr(h5ppFile, storage_level_str, state_prefix, \"common\/storage_level\", \"Maps state_prefix -> storage_level\");\n save_attr(h5ppFile, storage_reason_str, state_prefix, \"common\/storage_reason\", \"Maps state_prefix -> storage_reason\");\n save_attr(h5ppFile, state_root, state_prefix, \"common\/state_root\", \"Maps state_prefix -> state_root\");\n save_attr(h5ppFile, model_prefix, state_prefix, \"common\/model_prefix\", \"Maps state_prefix -> model_prefix\");\n save_attr(h5ppFile, hamiltonian, state_prefix, \"common\/hamiltonian\", \"Maps state_prefix -> hamiltonian\");\n save_attr(h5ppFile, mpo_prefix, state_prefix, \"common\/mpo_prefix\", \"Maps state_prefix -> mpo_prefix\");\n save_attr(h5ppFile, mps_prefix, state_prefix, \"common\/mps_prefix\", \"Maps state_prefix -> mps_prefix\");\n save_attr(h5ppFile, model_name, state_prefix, \"common\/model_type\", \"Maps state_prefix -> model_type\");\n save_attr(h5ppFile, model_size, state_prefix, \"common\/model_size\", \"Maps state_prefix -> model_size\");\n save_attr(h5ppFile, algo_name, state_prefix, \"common\/algo_type\", \"Maps state_prefix -> algo_type\");\n save_attr(h5ppFile, state_name, state_prefix, \"common\/state_name\", \"Maps state_prefix -> state_name\");\n save_attr(h5ppFile, status.iter, state_prefix, \"common\/iteration\", \"Maps state_prefix -> iteration\");\n save_attr(h5ppFile, status.step, state_prefix, \"common\/step\", \"Maps state_prefix -> step\");\n save_attr(h5ppFile, status.position, state_prefix, \"common\/position\", \"Maps state_prefix -> position\");\n save_log[state_prefix] = save_point;\n tools::common::profile::get_default_prof()[\"t_hdf\"]->toc();\n}\n<commit_msg>Improved logging<commit_after>\n#include <algorithms\/class_algorithm_status.h>\n#include <config\/enums.h>\n#include <h5pp\/h5pp.h>\n#include <string>\n#include <tools\/common\/io.h>\n#include <tools\/common\/log.h>\n#include <tools\/common\/prof.h>\n\nnamespace tools::common::io::h5attr {\n template<typename AttrType>\n void save_attr(h5pp::File &file, const AttrType &attrData, const std::string &attrName, const std::string &dsetPath, const std::string &dsetText) {\n tools::log->trace(\"Attribute -- {: <40} = {: <40} on dset: {}\", attrName, attrData, dsetPath);\n if(not file.linkExists(dsetPath)) file.writeDataset(dsetText, dsetPath);\n file.writeAttribute(attrData, attrName, dsetPath);\n }\n}\n\nnamespace tools::common::io::h5attr {\n void bootstrap_save_log(std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> &save_log, const h5pp::File &h5ppFile,\n const std::string &state_prefix) {\n if(save_log.empty()) {\n try {\n uint64_t step = 0;\n uint64_t iter = 0;\n if(h5ppFile.linkExists(\"common\/step\")) step = h5ppFile.readAttribute<uint64_t>(state_prefix, \"common\/step\");\n if(h5ppFile.linkExists(\"common\/iteration\")) iter = h5ppFile.readAttribute<uint64_t>(state_prefix, \"common\/iteration\");\n save_log[state_prefix] = std::make_pair(iter, step);\n\n } catch(const std::exception &ex) { tools::log->warn(\"Could not bootstrap save_log for {}: {}\", state_prefix, ex.what()); }\n }\n }\n}\n\nvoid tools::common::io::h5attr::save_meta(h5pp::File &h5ppFile, const StorageLevel &storage_level, const StorageReason &storage_reason,\n const ModelType &model_type, size_t model_size, const AlgorithmType &algo_type, const std::string &state_name,\n const std::string &state_prefix, const std::string &model_prefix, const class_algorithm_status &status) {\n \/\/ Write metadata into \/common so that we can find state paths later.\n \/\/ Under \/common we have the following dummy datasets defining attributes which map state_prefix to useful information:\n \/\/\n \/\/ -- finished | true or 1 if state_prefix is finished\n \/\/ -- storage_level | state_prefix -> storage_level\n \/\/ -- storage_reason | state_prefix -> storage_reason\n \/\/ -- state_root | state_prefix -> state_root\n \/\/ -- hamiltonian | state_prefix -> path to hamiltonian table\n \/\/ -- mps_prefix | state_prefix -> mps_prefix\n \/\/ -- mpo_prefix | state_prefix -> mpo_prefix\n \/\/ -- model_type | state_prefix -> model_type\n \/\/ -- model_size | state_prefix -> model_size\n \/\/ -- algo_type | state_prefix -> algo_type\n \/\/ -- state_name | state_prefix -> state_name\n \/\/ -- iteration | state_prefix -> iteration\n \/\/ -- step | state_prefix -> step\n \/\/ -- position | state_prefix -> position of the mps\n\n \/\/ Checks if the current entries have already been written\n static std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> save_log;\n bootstrap_save_log(save_log, h5ppFile, state_prefix);\n\n auto save_point = std::make_pair(status.iter, status.step);\n if(save_log[state_prefix] == save_point) return;\n\n tools::common::profile::get_default_prof()[\"t_hdf\"]->tic();\n\n std::string storage_level_str(enum2str(storage_level));\n std::string storage_reason_str(enum2str(storage_reason));\n std::string model_name(enum2str(model_type));\n std::string algo_name(enum2str(algo_type));\n std::string state_root = algo_name + '\/' + state_name;\n std::string hamiltonian = model_prefix + \"\/hamiltonian\";\n std::string mpo_prefix = model_prefix + \"\/mpo\";\n std::string mps_prefix = state_prefix + \"\/mps\";\n\n save_attr(h5ppFile, status.algorithm_has_finished, state_prefix, \"common\/finished\", \"Maps state_prefix -> finished\");\n save_attr(h5ppFile, storage_level_str, state_prefix, \"common\/storage_level\", \"Maps state_prefix -> storage_level\");\n save_attr(h5ppFile, storage_reason_str, state_prefix, \"common\/storage_reason\", \"Maps state_prefix -> storage_reason\");\n save_attr(h5ppFile, state_root, state_prefix, \"common\/state_root\", \"Maps state_prefix -> state_root\");\n save_attr(h5ppFile, model_prefix, state_prefix, \"common\/model_prefix\", \"Maps state_prefix -> model_prefix\");\n save_attr(h5ppFile, hamiltonian, state_prefix, \"common\/hamiltonian\", \"Maps state_prefix -> hamiltonian\");\n save_attr(h5ppFile, mpo_prefix, state_prefix, \"common\/mpo_prefix\", \"Maps state_prefix -> mpo_prefix\");\n save_attr(h5ppFile, mps_prefix, state_prefix, \"common\/mps_prefix\", \"Maps state_prefix -> mps_prefix\");\n save_attr(h5ppFile, model_name, state_prefix, \"common\/model_type\", \"Maps state_prefix -> model_type\");\n save_attr(h5ppFile, model_size, state_prefix, \"common\/model_size\", \"Maps state_prefix -> model_size\");\n save_attr(h5ppFile, algo_name, state_prefix, \"common\/algo_type\", \"Maps state_prefix -> algo_type\");\n save_attr(h5ppFile, state_name, state_prefix, \"common\/state_name\", \"Maps state_prefix -> state_name\");\n save_attr(h5ppFile, status.iter, state_prefix, \"common\/iteration\", \"Maps state_prefix -> iteration\");\n save_attr(h5ppFile, status.step, state_prefix, \"common\/step\", \"Maps state_prefix -> step\");\n save_attr(h5ppFile, status.position, state_prefix, \"common\/position\", \"Maps state_prefix -> position\");\n save_log[state_prefix] = save_point;\n tools::common::profile::get_default_prof()[\"t_hdf\"]->toc();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\nnamespace MATH_NAMESPACE\n{\nnamespace detail\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Convert float to unorm (cf. OpenGL 4.4, 2.3.4.1\n\/\/\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline uint32_t float_to_unorm(float f)\n{\n f = saturate(f);\n return static_cast<uint32_t>(f * static_cast<double>((1ULL << Bits) - 1));\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline float unorm_to_float(uint32_t u)\n{\n return static_cast<float>(u) \/ static_cast<double>((1ULL << Bits) - 1);\n}\n\n} \/\/ detail\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ unorm members\n\/\/\n\ntemplate <unsigned Bits>\nMATH_FUNC\nunorm<Bits>::unorm(float f)\n : value(detail::float_to_unorm<Bits>(f))\n{\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\nunorm<Bits>::operator value_type() const\n{\n return value;\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\nunorm<Bits>::operator float() const\n{\n return detail::unorm_to_float<Bits>(value);\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Comparisons\n\/\/\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator==(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) == static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator!=(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) != static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator<(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) < static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator<=(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) <= static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator>(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) > static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator>=(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) >= static_cast<T>(b);\n}\n\n} \/\/ MATH_NAMESPACE\n<commit_msg>Fix a typo<commit_after>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\nnamespace MATH_NAMESPACE\n{\nnamespace detail\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Convert float to unorm (cf. OpenGL 4.4, 2.3.4.1)\n\/\/\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline uint32_t float_to_unorm(float f)\n{\n f = saturate(f);\n return static_cast<uint32_t>(f * static_cast<double>((1ULL << Bits) - 1));\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline float unorm_to_float(uint32_t u)\n{\n return static_cast<float>(u) \/ static_cast<double>((1ULL << Bits) - 1);\n}\n\n} \/\/ detail\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ unorm members\n\/\/\n\ntemplate <unsigned Bits>\nMATH_FUNC\nunorm<Bits>::unorm(float f)\n : value(detail::float_to_unorm<Bits>(f))\n{\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\nunorm<Bits>::operator value_type() const\n{\n return value;\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\nunorm<Bits>::operator float() const\n{\n return detail::unorm_to_float<Bits>(value);\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Comparisons\n\/\/\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator==(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) == static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator!=(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) != static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator<(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) < static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator<=(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) <= static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator>(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) > static_cast<T>(b);\n}\n\ntemplate <unsigned Bits>\nMATH_FUNC\ninline bool operator>=(unorm<Bits> a, unorm<Bits> b)\n{\n using T = typename unorm<Bits>::value_type;\n\n return static_cast<T>(a) >= static_cast<T>(b);\n}\n\n} \/\/ MATH_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#ifndef __BSE_CXX_MODULE_H__\n#define __BSE_CXX_MODULE_H__\n\n#include <bse\/bsecxxbase.hh>\n#include <bse\/bseieee754.hh>\n\nnamespace Bse {\n\n\/* enums\/structures mirrored from bseengine.hh *\/\nenum ProcessCost {\n NORMAL,\n CHEAP,\n EXPENSIVE\n};\nstruct JStream {\n const float **values;\n uint n_connections;\n \/* private: *\/\n uint jcount; \/* reserved *\/\n};\nstruct IStream {\n const float *values;\n gboolean connected;\n};\nstruct OStream {\n float *values;\n gboolean connected;\n};\n\nclass Effect;\n\nclass SynthesisModule {\n template<class T, typename P> class ClosureP1; \/* 1-argument member function closure *\/\n BseModule *intern_module;\npublic:\n explicit SynthesisModule ();\n virtual ~SynthesisModule () = 0;\n virtual void reset () = 0;\n virtual void process (uint n_values) = 0;\n virtual const ProcessCost cost ();\n inline const IStream& istream (uint istream_index) const;\n inline const JStream& jstream (uint jstream_index) const;\n inline const OStream& ostream (uint ostream_index) const;\n void ostream_set (uint ostream_index,\n const float *values);\n const float* const_values (float value);\n inline const uint mix_freq () const;\n inline const uint block_size () const;\n inline guint64 tick_stamp ();\n inline BseModule* engine_module ();\n static inline int dtoi (double d) { return bse_dtoi (d); }\n static inline int ftoi (float f) { return bse_ftoi (f); }\n \/* member functions and closures *\/\n struct Closure {\n virtual void operator() (SynthesisModule*) = 0;\n virtual ~Closure () {}\n };\n \/* create a 1-argument member function closure, where C must be derived from SynthesisModule *\/\n template<class D, class C>\n static Closure* make_closure (void (C::*method) (D*),\n const D &data);\n \/* internal *\/\n void set_module (BseModule *module);\n \/* auto_update() trampoline *\/\npublic:\n typedef void (*AutoUpdate) (BseModule*, gpointer);\n struct AutoUpdateData {\n guint prop_id;\n double prop_value;\n \/* required by back propagation *\/\n guint64 tick_stamp;\n GParamSpec *pspec;\n Effect *effect;\n }; \n struct NeedAutoUpdateTag {};\npublic:\n template<class M, class P, class C> struct Trampoline {\n static void auto_update_accessor (BseModule*, gpointer);\n };\n \/* partial trampoline specializations *\/\n template<class M, class P> struct Trampoline<M,P,NeedAutoUpdateTag> {\n static void auto_update_accessor (BseModule*, gpointer);\n };\n template<class M, class P> struct Trampoline<M,P,void> {\n static void auto_update_accessor (BseModule*, gpointer);\n };\n};\n\n#define BSE_TYPE_EFFECT (BSE_CXX_TYPE_GET_REGISTERED (Bse, Effect))\nclass EffectBase : public CxxBase {};\nclass Effect : public EffectBase {\nprivate:\n guint64 last_module_update;\npublic:\n \/* BseObject functionality *\/\n explicit Effect ();\n void set_property (guint prop_id,\n const Value &value,\n GParamSpec *pspec);\n void get_property (guint prop_id,\n Value &value,\n GParamSpec *pspec);\n \/* BseSource accessors *\/\n bool is_prepared() const { return BSE_SOURCE_PREPARED (gobject()); }\n guint n_ichannels() const { return BSE_SOURCE_N_ICHANNELS (gobject()); }\n guint n_joint_ichannels() const { return BSE_SOURCE_N_JOINT_ICHANNELS (gobject()); }\n guint n_ochannels() const { return BSE_SOURCE_N_OCHANNELS (gobject()); }\n bool is_joint_ichannel (guint i) const { return BSE_SOURCE_IS_JOINT_ICHANNEL (gobject(), i); }\n guint ichannels_istream (guint i) const { return BSE_SOURCE_ICHANNEL_ISTREAM (gobject(), i); }\n guint ichannels_jstream (guint i) const { return BSE_SOURCE_ICHANNEL_JSTREAM (gobject(), i); }\n guint ochannels_ostream (guint i) const { return BSE_SOURCE_OCHANNEL_OSTREAM (gobject(), i); }\n const gchar* ichannel_ident (guint i) const { return BSE_SOURCE_ICHANNEL_IDENT (gobject(), i); }\n const gchar* ichannel_label (guint i) const { return BSE_SOURCE_ICHANNEL_LABEL (gobject(), i); }\n const gchar* ichannel_blurb (guint i) const { return BSE_SOURCE_ICHANNEL_BLURB (gobject(), i); }\n const gchar* ochannel_ident (guint i) const { return BSE_SOURCE_OCHANNEL_IDENT (gobject(), i); }\n const gchar* ochannel_label (guint i) const { return BSE_SOURCE_OCHANNEL_LABEL (gobject(), i); }\n const gchar* ochannel_blurb (guint i) const { return BSE_SOURCE_OCHANNEL_BLURB (gobject(), i); }\n virtual SynthesisModule* create_module (uint context_handle,\n BseTrans *trans) = 0;\n virtual SynthesisModule::\n Closure* make_module_config_closure () = 0;\n virtual SynthesisModule::\n AutoUpdate get_module_auto_update () = 0;\n void update_modules (BseTrans *trans = NULL);\n guint64 module_update_tick_stamp () { return last_module_update; }\n \/* prepare & dismiss pre and post invocation hooks *\/\n virtual void prepare1() { \/* override this to do something before parent class prepare *\/ }\n virtual void prepare2() { \/* override this to do something after parent class prepare *\/ }\n virtual void reset1() { \/* override this to do something before parent class dismiss *\/ }\n virtual void reset2() { \/* override this to do something after parent class dismiss *\/ }\n\n static void class_init (CxxBaseClass *klass);\nprotected:\n const BseModuleClass* create_engine_class (SynthesisModule *sample_module,\n int cost = -1,\n int n_istreams = -1,\n int n_jstreams = -1,\n int n_ostreams = -1);\n virtual BseModule* integrate_engine_module (uint context_handle,\n BseTrans *trans);\n virtual void dismiss_engine_module (BseModule *engine_module,\n guint context_handle,\n BseTrans *trans);\n uint block_size () const;\n uint max_block_size () const;\npublic: \/* FIXME: make this protected as soon as the modules have their own current_musical_tuning() accessor *\/\n Bse::MusicalTuning current_musical_tuning () const;\n};\n\/* implement Bse::Effect and Bse::SynthesisModule methods *\/\n#define BSE_EFFECT_INTEGRATE_MODULE(ObjectType,ModuleType,ParamType) \\\nBse::SynthesisModule* \\\ncreate_module (uint context_handle, \\\n BseTrans *trans) \\\n{ \\\n \/* check that 'this' is a ObjectType* *\/ \\\n (void) const_cast<ObjectType*> (this); \\\n \/* create a synthesis module *\/ \\\n return new ModuleType(); \\\n} \\\nBse::SynthesisModule::Closure* \\\nmake_module_config_closure() \\\n{ \\\n return SynthesisModule::make_closure (&ModuleType::config, ParamType (this)); \\\n} \\\nBse::SynthesisModule::AutoUpdate \\\nget_module_auto_update() \\\n{ \\\n return SynthesisModule::Trampoline<ModuleType,ParamType, \\\n ObjectType::AutoUpdateCategory>::auto_update_accessor; \\\n}\ntemplate<class M, class P>\nvoid\nSynthesisModule::Trampoline<M,P,SynthesisModule::NeedAutoUpdateTag>::\nauto_update_accessor (BseModule *bmodule, \/* Engine Thread *\/\n gpointer data)\n{\n M *m = static_cast<M*> (BSE_MODULE_GET_USER_DATA (bmodule));\n AutoUpdateData *au = static_cast<AutoUpdateData*> (data);\n typename P::IDType prop_id = static_cast<typename P::IDType> (au->prop_id);\n if (0) \/\/ check M::auto_update() member and prototype\n (void) static_cast<void (M::*) (typename P::IDType, double)> (&M::auto_update);\n m->auto_update (prop_id, au->prop_value);\n}\ntemplate<class M, class P>\nvoid\nSynthesisModule::Trampoline<M,P,void>::\nauto_update_accessor (BseModule *bmodule,\n gpointer data)\n{\n}\n\n\n\/* --- implementation details --- *\/\nnamespace externC { extern \"C\" {\nextern guint bse_engine_exvar_sample_freq;\nextern guint bse_engine_exvar_block_size;\nextern guint64 bse_module_tick_stamp (BseModule*);\n} }\ninline BseModule*\nSynthesisModule::engine_module ()\n{\n return intern_module;\n}\ninline const uint\nSynthesisModule::mix_freq () const\n{\n return externC::bse_engine_exvar_sample_freq;\n}\ninline const uint\nSynthesisModule::block_size () const\n{\n return externC::bse_engine_exvar_block_size;\n}\ninline guint64\nSynthesisModule::tick_stamp ()\n{\n return externC::bse_module_tick_stamp (engine_module());\n}\ninline const IStream&\nSynthesisModule::istream (uint istream_index) const\n{\n void *istreams = BSE_MODULE_GET_ISTREAMSP (intern_module);\n return reinterpret_cast<IStream*> (istreams)[istream_index];\n}\ninline const JStream&\nSynthesisModule::jstream (uint jstream_index) const\n{\n void *jstreams = BSE_MODULE_GET_JSTREAMSP (intern_module);\n return reinterpret_cast<JStream*> (jstreams)[jstream_index];\n}\ninline const OStream&\nSynthesisModule::ostream (uint ostream_index) const\n{\n void *ostreams = BSE_MODULE_GET_OSTREAMSP (intern_module);\n return reinterpret_cast<OStream*> (ostreams)[ostream_index];\n}\ntemplate<class T, typename P>\nclass SynthesisModule::ClosureP1 : public SynthesisModule::Closure {\n typedef void (T::*Member) (P*);\n Member func;\n P *data;\npublic:\n ClosureP1 (void (T::*f) (P*), P *p)\n : func (f), data (p)\n {\n assert_derived_from<T,SynthesisModule>();\n }\n void operator() (SynthesisModule *p)\n {\n T *t = static_cast<T*> (p);\n (t->*func) (data);\n }\n ~ClosureP1 ()\n {\n delete data;\n }\n};\ntemplate<class D, class C> SynthesisModule::Closure*\nSynthesisModule::make_closure (void (C::*method) (D*),\n const D &data)\n{\n D *d = new D (data);\n ClosureP1<C,D> *ac = new ClosureP1<C,D> (method, d);\n return ac;\n}\n\n} \/\/ Bse\n\n#endif \/* __BSE_CXX_MODULE_H__ *\/\n<commit_msg>BSE: use bseengine.hh symbols instead of duplicating header bits<commit_after>\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#ifndef __BSE_CXX_MODULE_H__\n#define __BSE_CXX_MODULE_H__\n\n#include <bse\/bsecxxbase.hh>\n#include <bse\/bseieee754.hh>\n#include <bse\/bseengine.hh>\n\nnamespace Bse {\n\n\/* enums\/structures mirrored from bseengine.hh *\/\nenum ProcessCost {\n NORMAL,\n CHEAP,\n EXPENSIVE\n};\nstruct JStream {\n const float **values;\n uint n_connections;\n \/* private: *\/\n uint jcount; \/* reserved *\/\n};\nstruct IStream {\n const float *values;\n gboolean connected;\n};\nstruct OStream {\n float *values;\n gboolean connected;\n};\n\nclass Effect;\n\nclass SynthesisModule {\n template<class T, typename P> class ClosureP1; \/* 1-argument member function closure *\/\n BseModule *intern_module;\npublic:\n explicit SynthesisModule ();\n virtual ~SynthesisModule () = 0;\n virtual void reset () = 0;\n virtual void process (uint n_values) = 0;\n virtual const ProcessCost cost ();\n inline const IStream& istream (uint istream_index) const;\n inline const JStream& jstream (uint jstream_index) const;\n inline const OStream& ostream (uint ostream_index) const;\n void ostream_set (uint ostream_index,\n const float *values);\n const float* const_values (float value);\n inline const uint mix_freq () const;\n inline const uint block_size () const;\n inline guint64 tick_stamp ();\n inline BseModule* engine_module ();\n static inline int dtoi (double d) { return bse_dtoi (d); }\n static inline int ftoi (float f) { return bse_ftoi (f); }\n \/* member functions and closures *\/\n struct Closure {\n virtual void operator() (SynthesisModule*) = 0;\n virtual ~Closure () {}\n };\n \/* create a 1-argument member function closure, where C must be derived from SynthesisModule *\/\n template<class D, class C>\n static Closure* make_closure (void (C::*method) (D*),\n const D &data);\n \/* internal *\/\n void set_module (BseModule *module);\n \/* auto_update() trampoline *\/\npublic:\n typedef void (*AutoUpdate) (BseModule*, gpointer);\n struct AutoUpdateData {\n guint prop_id;\n double prop_value;\n \/* required by back propagation *\/\n guint64 tick_stamp;\n GParamSpec *pspec;\n Effect *effect;\n }; \n struct NeedAutoUpdateTag {};\npublic:\n template<class M, class P, class C> struct Trampoline {\n static void auto_update_accessor (BseModule*, gpointer);\n };\n \/* partial trampoline specializations *\/\n template<class M, class P> struct Trampoline<M,P,NeedAutoUpdateTag> {\n static void auto_update_accessor (BseModule*, gpointer);\n };\n template<class M, class P> struct Trampoline<M,P,void> {\n static void auto_update_accessor (BseModule*, gpointer);\n };\n};\n\n#define BSE_TYPE_EFFECT (BSE_CXX_TYPE_GET_REGISTERED (Bse, Effect))\nclass EffectBase : public CxxBase {};\nclass Effect : public EffectBase {\nprivate:\n guint64 last_module_update;\npublic:\n \/* BseObject functionality *\/\n explicit Effect ();\n void set_property (guint prop_id,\n const Value &value,\n GParamSpec *pspec);\n void get_property (guint prop_id,\n Value &value,\n GParamSpec *pspec);\n \/* BseSource accessors *\/\n bool is_prepared() const { return BSE_SOURCE_PREPARED (gobject()); }\n guint n_ichannels() const { return BSE_SOURCE_N_ICHANNELS (gobject()); }\n guint n_joint_ichannels() const { return BSE_SOURCE_N_JOINT_ICHANNELS (gobject()); }\n guint n_ochannels() const { return BSE_SOURCE_N_OCHANNELS (gobject()); }\n bool is_joint_ichannel (guint i) const { return BSE_SOURCE_IS_JOINT_ICHANNEL (gobject(), i); }\n guint ichannels_istream (guint i) const { return BSE_SOURCE_ICHANNEL_ISTREAM (gobject(), i); }\n guint ichannels_jstream (guint i) const { return BSE_SOURCE_ICHANNEL_JSTREAM (gobject(), i); }\n guint ochannels_ostream (guint i) const { return BSE_SOURCE_OCHANNEL_OSTREAM (gobject(), i); }\n const gchar* ichannel_ident (guint i) const { return BSE_SOURCE_ICHANNEL_IDENT (gobject(), i); }\n const gchar* ichannel_label (guint i) const { return BSE_SOURCE_ICHANNEL_LABEL (gobject(), i); }\n const gchar* ichannel_blurb (guint i) const { return BSE_SOURCE_ICHANNEL_BLURB (gobject(), i); }\n const gchar* ochannel_ident (guint i) const { return BSE_SOURCE_OCHANNEL_IDENT (gobject(), i); }\n const gchar* ochannel_label (guint i) const { return BSE_SOURCE_OCHANNEL_LABEL (gobject(), i); }\n const gchar* ochannel_blurb (guint i) const { return BSE_SOURCE_OCHANNEL_BLURB (gobject(), i); }\n virtual SynthesisModule* create_module (uint context_handle,\n BseTrans *trans) = 0;\n virtual SynthesisModule::\n Closure* make_module_config_closure () = 0;\n virtual SynthesisModule::\n AutoUpdate get_module_auto_update () = 0;\n void update_modules (BseTrans *trans = NULL);\n guint64 module_update_tick_stamp () { return last_module_update; }\n \/* prepare & dismiss pre and post invocation hooks *\/\n virtual void prepare1() { \/* override this to do something before parent class prepare *\/ }\n virtual void prepare2() { \/* override this to do something after parent class prepare *\/ }\n virtual void reset1() { \/* override this to do something before parent class dismiss *\/ }\n virtual void reset2() { \/* override this to do something after parent class dismiss *\/ }\n\n static void class_init (CxxBaseClass *klass);\nprotected:\n const BseModuleClass* create_engine_class (SynthesisModule *sample_module,\n int cost = -1,\n int n_istreams = -1,\n int n_jstreams = -1,\n int n_ostreams = -1);\n virtual BseModule* integrate_engine_module (uint context_handle,\n BseTrans *trans);\n virtual void dismiss_engine_module (BseModule *engine_module,\n guint context_handle,\n BseTrans *trans);\n uint block_size () const;\n uint max_block_size () const;\npublic: \/* FIXME: make this protected as soon as the modules have their own current_musical_tuning() accessor *\/\n Bse::MusicalTuning current_musical_tuning () const;\n};\n\/* implement Bse::Effect and Bse::SynthesisModule methods *\/\n#define BSE_EFFECT_INTEGRATE_MODULE(ObjectType,ModuleType,ParamType) \\\nBse::SynthesisModule* \\\ncreate_module (uint context_handle, \\\n BseTrans *trans) \\\n{ \\\n \/* check that 'this' is a ObjectType* *\/ \\\n (void) const_cast<ObjectType*> (this); \\\n \/* create a synthesis module *\/ \\\n return new ModuleType(); \\\n} \\\nBse::SynthesisModule::Closure* \\\nmake_module_config_closure() \\\n{ \\\n return SynthesisModule::make_closure (&ModuleType::config, ParamType (this)); \\\n} \\\nBse::SynthesisModule::AutoUpdate \\\nget_module_auto_update() \\\n{ \\\n return SynthesisModule::Trampoline<ModuleType,ParamType, \\\n ObjectType::AutoUpdateCategory>::auto_update_accessor; \\\n}\ntemplate<class M, class P>\nvoid\nSynthesisModule::Trampoline<M,P,SynthesisModule::NeedAutoUpdateTag>::\nauto_update_accessor (BseModule *bmodule, \/* Engine Thread *\/\n gpointer data)\n{\n M *m = static_cast<M*> (BSE_MODULE_GET_USER_DATA (bmodule));\n AutoUpdateData *au = static_cast<AutoUpdateData*> (data);\n typename P::IDType prop_id = static_cast<typename P::IDType> (au->prop_id);\n if (0) \/\/ check M::auto_update() member and prototype\n (void) static_cast<void (M::*) (typename P::IDType, double)> (&M::auto_update);\n m->auto_update (prop_id, au->prop_value);\n}\ntemplate<class M, class P>\nvoid\nSynthesisModule::Trampoline<M,P,void>::\nauto_update_accessor (BseModule *bmodule,\n gpointer data)\n{\n}\n\n\n\/* --- implementation details --- *\/\ninline BseModule*\nSynthesisModule::engine_module ()\n{\n return intern_module;\n}\ninline const uint\nSynthesisModule::mix_freq () const\n{\n return bse_engine_sample_freq();\n}\ninline const uint\nSynthesisModule::block_size () const\n{\n return bse_engine_block_size();\n}\ninline guint64\nSynthesisModule::tick_stamp ()\n{\n return bse_module_tick_stamp (engine_module());\n}\ninline const IStream&\nSynthesisModule::istream (uint istream_index) const\n{\n void *istreams = BSE_MODULE_GET_ISTREAMSP (intern_module);\n return reinterpret_cast<IStream*> (istreams)[istream_index];\n}\ninline const JStream&\nSynthesisModule::jstream (uint jstream_index) const\n{\n void *jstreams = BSE_MODULE_GET_JSTREAMSP (intern_module);\n return reinterpret_cast<JStream*> (jstreams)[jstream_index];\n}\ninline const OStream&\nSynthesisModule::ostream (uint ostream_index) const\n{\n void *ostreams = BSE_MODULE_GET_OSTREAMSP (intern_module);\n return reinterpret_cast<OStream*> (ostreams)[ostream_index];\n}\ntemplate<class T, typename P>\nclass SynthesisModule::ClosureP1 : public SynthesisModule::Closure {\n typedef void (T::*Member) (P*);\n Member func;\n P *data;\npublic:\n ClosureP1 (void (T::*f) (P*), P *p)\n : func (f), data (p)\n {\n assert_derived_from<T,SynthesisModule>();\n }\n void operator() (SynthesisModule *p)\n {\n T *t = static_cast<T*> (p);\n (t->*func) (data);\n }\n ~ClosureP1 ()\n {\n delete data;\n }\n};\ntemplate<class D, class C> SynthesisModule::Closure*\nSynthesisModule::make_closure (void (C::*method) (D*),\n const D &data)\n{\n D *d = new D (data);\n ClosureP1<C,D> *ac = new ClosureP1<C,D> (method, d);\n return ac;\n}\n\n} \/\/ Bse\n\n#endif \/* __BSE_CXX_MODULE_H__ *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>sfx2: PVS-Studio V595 'm_pResMgr' pointer could be null<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ partlistvisitor.cpp\n\/\/ libmusicxml2\n\/\/\n\/\/ Created by Arshia Cont on 05\/01\/17.\n\/\/\n\/\/\n\n#include <algorithm>\n\n#include \"partlistvisitor.h\"\n\n#include \"rational.h\"\n#include \"xml_tree_browser.h\"\n#include \"tree_browser.h\"\n\nusing namespace std;\n\nnamespace MusicXML2\n{\n partlistvisitor::partlistvisitor() : fPartGroupIncrementer(0), staffCreatorCounter(1)\n {\n }\n \n \n partGroup* partlistvisitor::find_first_of_partID_inGroup(std::string partID)\n {\n \/\/ search if this part ID exists in any grouping\n \/\/ Guido Limitation: One \\accol tag per staff ONLY (for nested definitions)\n \/\/ IDEA: Treat the FIRST occurence of partID in grouping and get rid of it.\n std::map<int, partGroup>::iterator partGroupIt;\n for (partGroupIt=fPartGroups.begin();\n partGroupIt != fPartGroups.end();\n partGroupIt++)\n {\n if (partGroupIt->second.visited == false) {\n if (std::find(partGroupIt->second.partIDs.begin()\n , partGroupIt->second.partIDs.end(),\n partID) != partGroupIt->second.partIDs.end() )\n {\n \/\/ this partID is in group number partGroupIt->first\n \/\/cerr << \"\\t ID found in group \" << partGroupIt->first <<\" \"<<endl;\n break;\n \n }\n }\n }\n \n if (partGroupIt != fPartGroups.end())\n {\n return &partGroupIt->second;\n }\n \n return NULL;\n }\n \n void partlistvisitor::partID2range(partGroup &pGroup)\n {\n std::vector<int> staves;\n for (size_t i=0; i<pGroup.partIDs.size();i++)\n {\n staves.push_back(part2staffmap[pGroup.partIDs[i]]);\n }\n\t\tif (staves.empty()) return;\n\t\t\n std::vector<int>::iterator rangeEnd = std::max_element(staves.begin(), staves.end());\n std::vector<int>::iterator rangeBegin = std::min_element(staves.begin(), staves.begin());\n \n stringstream rangeStream;\n rangeStream << \"\\\"\" << (*rangeBegin) << \"-\" << (*rangeEnd) << \"\\\"\";\n pGroup.guidoRange = rangeStream.str();\n pGroup.guidoRangeStart = *rangeBegin;\n pGroup.guidoRangeStop = *rangeEnd;\n }\n \n bool partlistvisitor::checkLonelyBarFormat(int staffID)\n {\n std::map<int, partGroup>::iterator partGroupIt;\n for (partGroupIt=fPartGroups.begin();\n partGroupIt != fPartGroups.end();\n partGroupIt++)\n {\n if (partGroupIt->second.barlineGrouping == true)\n {\n \/\/ see if this staff is in range\n if ( (staffID>= partGroupIt->second.guidoRangeStart)&&(staffID<=partGroupIt->second.guidoRangeStop))\n {\n return false;\n }\n }\n }\n \n return true;\n }\n \n \/\/\/ Visitors\n \n void partlistvisitor::visitStart ( S_part_group& elt )\n {\n int partGroupNumber = elt->getAttributeIntValue(\"number\", 0);\n \/\/\/ IMPORTANT NOTE: the number attribute is NOT sequential and can be repeated! So we need to do further book-keeping.\n std::string partGroupType = elt->getAttributeValue(\"type\");\n \n if (partGroupType==\"start\")\n {\n int groupIndex = fPartGroupIncrementer;\n fPartGroups[groupIndex].xmlGroupNumber = partGroupNumber;\n if (elt->getValue(k_group_symbol)==\"bracket\")\n {\n fPartGroups[groupIndex].bracket = true;\n } else\n fPartGroups[groupIndex].bracket = false;\n \n if (elt->getValue(k_group_barline)==\"yes\")\n {\n fPartGroups[groupIndex].barlineGrouping = true;\n } else\n fPartGroups[groupIndex].barlineGrouping = false;\n \n \/\/ Add optional names\n fPartGroups[groupIndex].fGroupName = elt->getValue(k_group_name);\n fPartGroups[groupIndex].visited = false;\n \n fCurrentPartGroupIndex.push_back(groupIndex);\n fPartGroupIncrementer++;\n \/\/cerr << \"Started group \" << partGroupNumber << \" index \" << groupIndex<<\" (\" << fCurrentPartGroupIndex.size() << \")\" << endl;\n }else\n if (partGroupType==\"stop\")\n {\n \/\/ Erase the INDEX whose xmlGroupNumber is equal to partGroupNumber\n std::vector<int>::iterator ito;\n for (ito = fCurrentPartGroupIndex.begin(); ito < fCurrentPartGroupIndex.end(); ito++)\n {\n if (fPartGroups[*ito].xmlGroupNumber == partGroupNumber)\n break;\n }\n \n \/\/ Do Erase\n if (ito != fCurrentPartGroupIndex.end())\n {\n \/\/ calculate Guido Range and set\n partID2range(fPartGroups[*ito]);\n fCurrentPartGroupIndex.erase(ito);\n }else\n cerr << \"Something is really wrong in S_PART_GROUP visitor!\" << endl;\n }\n }\n \n void partlistvisitor::visitStart( S_score_part& elt)\n {\n std::string PartID = elt->getAttributeValue(\"id\");\n part2staffmap[PartID] = staffCreatorCounter;\n staffCreatorCounter++;\n \n fPartHeaders[PartID].fPartName = elt->getValue(k_part_name);\n fPartHeaders[PartID].fPartNameAbbr = elt->getValue(k_part_abbreviation);\n \n \/\/ add groupings if any\n if (fCurrentPartGroupIndex.size())\n {\n for (size_t ind=0; ind < fCurrentPartGroupIndex.size(); ind++)\n {\n fPartGroups[fCurrentPartGroupIndex[ind]].partIDs.push_back(PartID);\n }\n }\n }\n \n \n \n}\n<commit_msg>xml2guido: Fix accolade and barformat staff ranges<commit_after>\/\/\n\/\/ partlistvisitor.cpp\n\/\/ libmusicxml2\n\/\/\n\/\/ Created by Arshia Cont on 05\/01\/17.\n\/\/\n\/\/\n\n#include <algorithm>\n\n#include \"partlistvisitor.h\"\n\n#include \"rational.h\"\n#include \"xml_tree_browser.h\"\n#include \"tree_browser.h\"\n\nusing namespace std;\n\nnamespace MusicXML2\n{\n partlistvisitor::partlistvisitor() : fPartGroupIncrementer(0), staffCreatorCounter(1)\n {\n }\n \n \n partGroup* partlistvisitor::find_first_of_partID_inGroup(std::string partID)\n {\n \/\/ search if this part ID exists in any grouping\n \/\/ Guido Limitation: One \\accol tag per staff ONLY (for nested definitions)\n \/\/ IDEA: Treat the FIRST occurence of partID in grouping and get rid of it.\n std::map<int, partGroup>::iterator partGroupIt;\n for (partGroupIt=fPartGroups.begin();\n partGroupIt != fPartGroups.end();\n partGroupIt++)\n {\n if (partGroupIt->second.visited == false) {\n if (std::find(partGroupIt->second.partIDs.begin()\n , partGroupIt->second.partIDs.end(),\n partID) != partGroupIt->second.partIDs.end() )\n {\n \/\/ this partID is in group number partGroupIt->first\n \/\/cerr << \"\\t ID found in group \" << partGroupIt->first <<\" \"<<endl;\n break;\n \n }\n }\n }\n \n if (partGroupIt != fPartGroups.end())\n {\n return &partGroupIt->second;\n }\n \n return NULL;\n }\n \n void partlistvisitor::partID2range(partGroup &pGroup)\n {\n std::vector<int> staves;\n for (size_t i=0; i<pGroup.partIDs.size();i++)\n {\n staves.push_back(part2staffmap[pGroup.partIDs[i]]);\n }\n\t\tif (staves.empty()) return;\n\t\t\n std::vector<int>::iterator rangeEnd = std::max_element(staves.begin(), staves.end());\n std::vector<int>::iterator rangeBegin = std::min_element(staves.begin(), staves.begin());\n \n stringstream rangeStream;\n rangeStream << \"\\\"\" << (*rangeBegin)+1 << \"-\" << (*rangeEnd)+1 << \"\\\"\";\n pGroup.guidoRange = rangeStream.str();\n pGroup.guidoRangeStart = *rangeBegin +1;\n pGroup.guidoRangeStop = *rangeEnd +1;\n }\n \n bool partlistvisitor::checkLonelyBarFormat(int staffID)\n {\n std::map<int, partGroup>::iterator partGroupIt;\n for (partGroupIt=fPartGroups.begin();\n partGroupIt != fPartGroups.end();\n partGroupIt++)\n {\n if (partGroupIt->second.barlineGrouping == true)\n {\n \/\/ see if this staff is in range\n if ( (staffID>= partGroupIt->second.guidoRangeStart)&&(staffID<=partGroupIt->second.guidoRangeStop))\n {\n return false;\n }\n }\n }\n \n return true;\n }\n \n \/\/\/ Visitors\n \n void partlistvisitor::visitStart ( S_part_group& elt )\n {\n int partGroupNumber = elt->getAttributeIntValue(\"number\", 0);\n \/\/\/ IMPORTANT NOTE: the number attribute is NOT sequential and can be repeated! So we need to do further book-keeping.\n std::string partGroupType = elt->getAttributeValue(\"type\");\n \n if (partGroupType==\"start\")\n {\n int groupIndex = fPartGroupIncrementer;\n fPartGroups[groupIndex].xmlGroupNumber = partGroupNumber;\n if (elt->getValue(k_group_symbol)==\"bracket\")\n {\n fPartGroups[groupIndex].bracket = true;\n } else\n fPartGroups[groupIndex].bracket = false;\n \n if (elt->getValue(k_group_barline)==\"yes\")\n {\n fPartGroups[groupIndex].barlineGrouping = true;\n } else\n fPartGroups[groupIndex].barlineGrouping = false;\n \n \/\/ Add optional names\n fPartGroups[groupIndex].fGroupName = elt->getValue(k_group_name);\n fPartGroups[groupIndex].visited = false;\n \n fCurrentPartGroupIndex.push_back(groupIndex);\n fPartGroupIncrementer++;\n \/\/cerr << \"Started group \" << partGroupNumber << \" index \" << groupIndex<<\" (\" << fCurrentPartGroupIndex.size() << \")\" << endl;\n }else\n if (partGroupType==\"stop\")\n {\n \/\/ Erase the INDEX whose xmlGroupNumber is equal to partGroupNumber\n std::vector<int>::iterator ito;\n for (ito = fCurrentPartGroupIndex.begin(); ito < fCurrentPartGroupIndex.end(); ito++)\n {\n if (fPartGroups[*ito].xmlGroupNumber == partGroupNumber)\n break;\n }\n \n \/\/ Do Erase\n if (ito != fCurrentPartGroupIndex.end())\n {\n \/\/ calculate Guido Range and set\n partID2range(fPartGroups[*ito]);\n fCurrentPartGroupIndex.erase(ito);\n }else\n cerr << \"Something is really wrong in S_PART_GROUP visitor!\" << endl;\n }\n }\n \n void partlistvisitor::visitStart( S_score_part& elt)\n {\n std::string PartID = elt->getAttributeValue(\"id\");\n part2staffmap[PartID] = staffCreatorCounter;\n staffCreatorCounter++;\n \n fPartHeaders[PartID].fPartName = elt->getValue(k_part_name);\n fPartHeaders[PartID].fPartNameAbbr = elt->getValue(k_part_abbreviation);\n \n \/\/ add groupings if any\n if (fCurrentPartGroupIndex.size())\n {\n for (size_t ind=0; ind < fCurrentPartGroupIndex.size(); ind++)\n {\n fPartGroups[fCurrentPartGroupIndex[ind]].partIDs.push_back(PartID);\n }\n }\n }\n \n \n \n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * resourcegroupmanager_bind.cpp - bindings for Ogre::ResourceGroupManager\n ******************************************************************************\n * This file is part of\n * __ __ _ \n * \/ \/\/ \/_____ ____ (_)\n * \/ \/\/ \/\/ ___\/\/ __ \\ \/ \/ \n * \/ \/\/ \/\/ \/__ \/ \/_\/ \/\/ \/ \n * \/_\/\/_\/ \\___\/ \\____\/\/_\/ \n * \n * Low Level C Ogre Interface (llcoi)\n *\n * See http:\/\/code.google.com\/p\/llcoi\/ for more information.\n *\n * Copyright (c) 2011, Llcoi Team\n * \n * License: MIT\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 \"ogre_interface.h\"\n\n#include <OgreRoot.h>\n#include <OgreConfigFile.h>\n#include <OgreResourceManager.h>\n#include <OgreResourceGroupManager.h>\n#include <OgreResource.h>\n\n\nvoid setup_resources(const char* resources_cfg)\n{\n \/\/ set up resources\n \/\/ Load resource paths from config file\n Ogre::ConfigFile cf;\n cf.load(resources_cfg);\n \n \/\/ Go through all sections & settings in the file\n Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();\n \n Ogre::String secName, typeName, archName;\n while (seci.hasMoreElements())\n {\n secName = seci.peekNextKey();\n Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();\n Ogre::ConfigFile::SettingsMultiMap::iterator i;\n for (i = settings->begin(); i != settings->end(); ++i)\n {\n typeName = i->first;\n archName = i->second;\n Ogre::ResourceGroupManager::getSingleton().addResourceLocation(\n archName, typeName, secName);\n }\n }\n}\n\n\/\/ Ogre::ResourceGroupManager::addResourceLocation(std::string const&, std::string const&, std::string const&, bool)\nvoid add_resource_location(const char* location, const char* type, const char* group)\n{\n Ogre::ResourceGroupManager::getSingleton().addResourceLocation(location, type, group);\n}\n\n\/\/ Ogre::ResourceGroupManager::initialiseAllResourceGroups()\nvoid initialise_all_resourcegroups()\n{\n Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();\n}\n\n\n\/*\nOgre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME\nOgre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME\nOgre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME\nOgre::ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS\nOgre::ResourceGroupManager::ResourceDeclaration\nOgre::ResourceGroupManager::ResourceLocation\nOgre::ResourceGroupManager::ResourceGroupManager()\nOgre::ResourceGroupManager::~ResourceGroupManager()\nOgre::ResourceGroupManager::createResourceGroup(std::string const&, bool)\nOgre::ResourceGroupManager::initialiseResourceGroup(std::string const&)\nOgre::ResourceGroupManager::prepareResourceGroup(std::string const&, bool, bool)\nOgre::ResourceGroupManager::loadResourceGroup(std::string const&, bool, bool)\nOgre::ResourceGroupManager::unloadResourceGroup(std::string const&, bool)\nOgre::ResourceGroupManager::unloadUnreferencedResourcesInGroup(std::string const&, bool)\nOgre::ResourceGroupManager::clearResourceGroup(std::string const&)\nOgre::ResourceGroupManager::destroyResourceGroup(std::string const&)\nOgre::ResourceGroupManager::isResourceGroupInitialised(std::string const&)\nOgre::ResourceGroupManager::isResourceGroupLoaded(std::string const&)\nOgre::ResourceGroupManager::resourceGroupExists(std::string const&)\nOgre::ResourceGroupManager::removeResourceLocation(std::string const&, std::string const&)\nOgre::ResourceGroupManager::resourceLocationExists(std::string const&, std::string const&)\nOgre::ResourceGroupManager::declareResource(std::string const&, std::string const&, std::string const&, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&)\nOgre::ResourceGroupManager::declareResource(std::string const&, std::string const&, std::string const&, Ogre::ManualResourceLoader*, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&)\nOgre::ResourceGroupManager::undeclareResource(std::string const&, std::string const&)\nOgre::ResourceGroupManager::openResource(std::string const&, std::string const&, bool, Ogre::Resource*)\nOgre::ResourceGroupManager::openResources(std::string const&, std::string const&)\nOgre::ResourceGroupManager::listResourceNames(std::string const&, bool)\nOgre::ResourceGroupManager::listResourceFileInfo(std::string const&, bool)\nOgre::ResourceGroupManager::findResourceNames(std::string const&, std::string const&, bool)\nOgre::ResourceGroupManager::resourceExists(std::string const&, std::string const&)\nOgre::ResourceGroupManager::resourceExists(Ogre::ResourceGroupManager::ResourceGroup*, std::string const&)\nOgre::ResourceGroupManager::resourceExistsInAnyGroup(std::string const&)\nOgre::ResourceGroupManager::findGroupContainingResource(std::string const&)\nOgre::ResourceGroupManager::findResourceFileInfo(std::string const&, std::string const&, bool)\nOgre::ResourceGroupManager::resourceModifiedTime(std::string const&, std::string const&)\nOgre::ResourceGroupManager::listResourceLocations(std::string const&)\nOgre::ResourceGroupManager::findResourceLocation(std::string const&, std::string const&)\nOgre::ResourceGroupManager::resourceModifiedTime(Ogre::ResourceGroupManager::ResourceGroup*, std::string const&)\nOgre::ResourceGroupManager::createResource(std::string const&, std::string const&, bool, std::string const&)\nOgre::ResourceGroupManager::deleteResource(std::string const&, std::string const&, std::string const&)\nOgre::ResourceGroupManager::deleteMatchingResources(std::string const&, std::string const&, std::string const&)\nOgre::ResourceGroupManager::addResourceGroupListener(Ogre::ResourceGroupListener*)\nOgre::ResourceGroupManager::removeResourceGroupListener(Ogre::ResourceGroupListener*)\nOgre::ResourceGroupManager::setWorldResourceGroupName(std::string const&)\nOgre::ResourceGroupManager::getWorldResourceGroupName() const\nOgre::ResourceGroupManager::linkWorldGeometryToResourceGroup(std::string const&, std::string const&, Ogre::SceneManager*)\nOgre::ResourceGroupManager::unlinkWorldGeometryFromResourceGroup(std::string const&)\nOgre::ResourceGroupManager::isResourceGroupInGlobalPool(std::string const&)\nOgre::ResourceGroupManager::shutdownAll()\nOgre::ResourceGroupManager::_registerResourceManager(std::string const&, Ogre::ResourceManager*)\nOgre::ResourceGroupManager::_unregisterResourceManager(std::string const&)\nOgre::ResourceGroupManager::getResourceManagerIterator()\nOgre::ResourceGroupManager::_registerScriptLoader(Ogre::ScriptLoader*)\nOgre::ResourceGroupManager::_unregisterScriptLoader(Ogre::ScriptLoader*)\nOgre::ResourceGroupManager::_findScriptLoader(std::string const&)\nOgre::ResourceGroupManager::_getResourceManager(std::string const&)\nOgre::ResourceGroupManager::_notifyResourceCreated(Ogre::SharedPtr<Ogre::Resource>&)\nOgre::ResourceGroupManager::_notifyResourceRemoved(Ogre::SharedPtr<Ogre::Resource>&)\nOgre::ResourceGroupManager::_notifyResourceGroupChanged(std::string const&, Ogre::Resource*)\nOgre::ResourceGroupManager::_notifyAllResourcesRemoved(Ogre::ResourceManager*)\nOgre::ResourceGroupManager::_notifyWorldGeometryStageStarted(std::string const&)\nOgre::ResourceGroupManager::_notifyWorldGeometryStageEnded()\nOgre::ResourceGroupManager::getResourceGroups()\nOgre::ResourceGroupManager::getResourceDeclarationList(std::string const&)\nOgre::ResourceGroupManager::getResourceLocationList(std::string const&)\nOgre::ResourceGroupManager::setLoadingListener(Ogre::ResourceLoadingListener*)\nOgre::ResourceGroupManager::getLoadingListener()\nOgre::ResourceGroupManager::getSingleton()\nOgre::ResourceGroupManager::getSingletonPtr()\nOgre::ResourceGroupManager::ResourceDeclaration::~ResourceDeclaration()\nOgre::ResourceGroupManager::ResourceDeclaration::operator=(Ogre::ResourceGroupManager::ResourceDeclaration const&)\nOgre::ResourceGroupManager::ResourceDeclaration::ResourceDeclaration(Ogre::ResourceGroupManager::ResourceDeclaration const&)\nOgre::ResourceGroupManager::ResourceDeclaration::ResourceDeclaration()\nOgre::ResourceGroupManager::ResourceLocation::~ResourceLocation()\nOgre::ResourceGroupManager::ResourceLocation::operator=(Ogre::ResourceGroupManager::ResourceLocation const&)\nOgre::ResourceGroupManager::ResourceLocation::ResourceLocation(Ogre::ResourceGroupManager::ResourceLocation const&)\nOgre::ResourceGroupManager::ResourceLocation::ResourceLocation()\nOgre::ResourceGroupManager::ResourceGroup::~ResourceGroup()\nOgre::ResourceGroupManager::ResourceGroup::ResourceGroup()\nOgre::ResourceGroupManager::ResourceGroup::addToIndex(std::string const&, Ogre::Archive*)\nOgre::ResourceGroupManager::ResourceGroup::removeFromIndex(std::string const&, Ogre::Archive*)\nOgre::ResourceGroupManager::ResourceGroup::removeFromIndex(Ogre::Archive*)\n*\/\n<commit_msg>added access to some constants.<commit_after>\/******************************************************************************\n * resourcegroupmanager_bind.cpp - bindings for Ogre::ResourceGroupManager\n ******************************************************************************\n * This file is part of\n * __ __ _ \n * \/ \/\/ \/_____ ____ (_)\n * \/ \/\/ \/\/ ___\/\/ __ \\ \/ \/ \n * \/ \/\/ \/\/ \/__ \/ \/_\/ \/\/ \/ \n * \/_\/\/_\/ \\___\/ \\____\/\/_\/ \n * \n * Low Level C Ogre Interface (llcoi)\n *\n * See http:\/\/code.google.com\/p\/llcoi\/ for more information.\n *\n * Copyright (c) 2011, Llcoi Team\n * \n * License: MIT\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 \"ogre_interface.h\"\n\n#include <OgreRoot.h>\n#include <OgreConfigFile.h>\n#include <OgreResourceManager.h>\n#include <OgreResourceGroupManager.h>\n#include <OgreResource.h>\n\n\nvoid setup_resources(const char* resources_cfg)\n{\n \/\/ set up resources\n \/\/ Load resource paths from config file\n Ogre::ConfigFile cf;\n cf.load(resources_cfg);\n \n \/\/ Go through all sections & settings in the file\n Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();\n \n Ogre::String secName, typeName, archName;\n while (seci.hasMoreElements())\n {\n secName = seci.peekNextKey();\n Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();\n Ogre::ConfigFile::SettingsMultiMap::iterator i;\n for (i = settings->begin(); i != settings->end(); ++i)\n {\n typeName = i->first;\n archName = i->second;\n Ogre::ResourceGroupManager::getSingleton().addResourceLocation(\n archName, typeName, secName);\n }\n }\n}\n\n\/\/ Ogre::ResourceGroupManager::addResourceLocation(std::string const&, std::string const&, std::string const&, bool)\nvoid add_resource_location(const char* location, const char* type, const char* group)\n{\n Ogre::ResourceGroupManager::getSingleton().addResourceLocation(location, type, group);\n}\n\n\/\/ Ogre::ResourceGroupManager::initialiseAllResourceGroups()\nvoid initialise_all_resourcegroups()\n{\n Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();\n}\n\nconst char * resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME()\n{\n return Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str();\n}\n\nconst char * resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME()\n{\n return Ogre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME.c_str();\n}\n\nconst char * resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME()\n{\n return Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME.c_str();\n}\n\nsize_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS()\n{\n return Ogre::ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS;\n}\n\n\n\/*\nOgre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME\nOgre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME\nOgre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME\nOgre::ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS\nOgre::ResourceGroupManager::ResourceDeclaration\nOgre::ResourceGroupManager::ResourceLocation\nOgre::ResourceGroupManager::ResourceGroupManager()\nOgre::ResourceGroupManager::~ResourceGroupManager()\nOgre::ResourceGroupManager::createResourceGroup(std::string const&, bool)\nOgre::ResourceGroupManager::initialiseResourceGroup(std::string const&)\nOgre::ResourceGroupManager::prepareResourceGroup(std::string const&, bool, bool)\nOgre::ResourceGroupManager::loadResourceGroup(std::string const&, bool, bool)\nOgre::ResourceGroupManager::unloadResourceGroup(std::string const&, bool)\nOgre::ResourceGroupManager::unloadUnreferencedResourcesInGroup(std::string const&, bool)\nOgre::ResourceGroupManager::clearResourceGroup(std::string const&)\nOgre::ResourceGroupManager::destroyResourceGroup(std::string const&)\nOgre::ResourceGroupManager::isResourceGroupInitialised(std::string const&)\nOgre::ResourceGroupManager::isResourceGroupLoaded(std::string const&)\nOgre::ResourceGroupManager::resourceGroupExists(std::string const&)\nOgre::ResourceGroupManager::removeResourceLocation(std::string const&, std::string const&)\nOgre::ResourceGroupManager::resourceLocationExists(std::string const&, std::string const&)\nOgre::ResourceGroupManager::declareResource(std::string const&, std::string const&, std::string const&, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&)\nOgre::ResourceGroupManager::declareResource(std::string const&, std::string const&, std::string const&, Ogre::ManualResourceLoader*, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&)\nOgre::ResourceGroupManager::undeclareResource(std::string const&, std::string const&)\nOgre::ResourceGroupManager::openResource(std::string const&, std::string const&, bool, Ogre::Resource*)\nOgre::ResourceGroupManager::openResources(std::string const&, std::string const&)\nOgre::ResourceGroupManager::listResourceNames(std::string const&, bool)\nOgre::ResourceGroupManager::listResourceFileInfo(std::string const&, bool)\nOgre::ResourceGroupManager::findResourceNames(std::string const&, std::string const&, bool)\nOgre::ResourceGroupManager::resourceExists(std::string const&, std::string const&)\nOgre::ResourceGroupManager::resourceExists(Ogre::ResourceGroupManager::ResourceGroup*, std::string const&)\nOgre::ResourceGroupManager::resourceExistsInAnyGroup(std::string const&)\nOgre::ResourceGroupManager::findGroupContainingResource(std::string const&)\nOgre::ResourceGroupManager::findResourceFileInfo(std::string const&, std::string const&, bool)\nOgre::ResourceGroupManager::resourceModifiedTime(std::string const&, std::string const&)\nOgre::ResourceGroupManager::listResourceLocations(std::string const&)\nOgre::ResourceGroupManager::findResourceLocation(std::string const&, std::string const&)\nOgre::ResourceGroupManager::resourceModifiedTime(Ogre::ResourceGroupManager::ResourceGroup*, std::string const&)\nOgre::ResourceGroupManager::createResource(std::string const&, std::string const&, bool, std::string const&)\nOgre::ResourceGroupManager::deleteResource(std::string const&, std::string const&, std::string const&)\nOgre::ResourceGroupManager::deleteMatchingResources(std::string const&, std::string const&, std::string const&)\nOgre::ResourceGroupManager::addResourceGroupListener(Ogre::ResourceGroupListener*)\nOgre::ResourceGroupManager::removeResourceGroupListener(Ogre::ResourceGroupListener*)\nOgre::ResourceGroupManager::setWorldResourceGroupName(std::string const&)\nOgre::ResourceGroupManager::getWorldResourceGroupName() const\nOgre::ResourceGroupManager::linkWorldGeometryToResourceGroup(std::string const&, std::string const&, Ogre::SceneManager*)\nOgre::ResourceGroupManager::unlinkWorldGeometryFromResourceGroup(std::string const&)\nOgre::ResourceGroupManager::isResourceGroupInGlobalPool(std::string const&)\nOgre::ResourceGroupManager::shutdownAll()\nOgre::ResourceGroupManager::_registerResourceManager(std::string const&, Ogre::ResourceManager*)\nOgre::ResourceGroupManager::_unregisterResourceManager(std::string const&)\nOgre::ResourceGroupManager::getResourceManagerIterator()\nOgre::ResourceGroupManager::_registerScriptLoader(Ogre::ScriptLoader*)\nOgre::ResourceGroupManager::_unregisterScriptLoader(Ogre::ScriptLoader*)\nOgre::ResourceGroupManager::_findScriptLoader(std::string const&)\nOgre::ResourceGroupManager::_getResourceManager(std::string const&)\nOgre::ResourceGroupManager::_notifyResourceCreated(Ogre::SharedPtr<Ogre::Resource>&)\nOgre::ResourceGroupManager::_notifyResourceRemoved(Ogre::SharedPtr<Ogre::Resource>&)\nOgre::ResourceGroupManager::_notifyResourceGroupChanged(std::string const&, Ogre::Resource*)\nOgre::ResourceGroupManager::_notifyAllResourcesRemoved(Ogre::ResourceManager*)\nOgre::ResourceGroupManager::_notifyWorldGeometryStageStarted(std::string const&)\nOgre::ResourceGroupManager::_notifyWorldGeometryStageEnded()\nOgre::ResourceGroupManager::getResourceGroups()\nOgre::ResourceGroupManager::getResourceDeclarationList(std::string const&)\nOgre::ResourceGroupManager::getResourceLocationList(std::string const&)\nOgre::ResourceGroupManager::setLoadingListener(Ogre::ResourceLoadingListener*)\nOgre::ResourceGroupManager::getLoadingListener()\nOgre::ResourceGroupManager::getSingleton()\nOgre::ResourceGroupManager::getSingletonPtr()\nOgre::ResourceGroupManager::ResourceDeclaration::~ResourceDeclaration()\nOgre::ResourceGroupManager::ResourceDeclaration::operator=(Ogre::ResourceGroupManager::ResourceDeclaration const&)\nOgre::ResourceGroupManager::ResourceDeclaration::ResourceDeclaration(Ogre::ResourceGroupManager::ResourceDeclaration const&)\nOgre::ResourceGroupManager::ResourceDeclaration::ResourceDeclaration()\nOgre::ResourceGroupManager::ResourceLocation::~ResourceLocation()\nOgre::ResourceGroupManager::ResourceLocation::operator=(Ogre::ResourceGroupManager::ResourceLocation const&)\nOgre::ResourceGroupManager::ResourceLocation::ResourceLocation(Ogre::ResourceGroupManager::ResourceLocation const&)\nOgre::ResourceGroupManager::ResourceLocation::ResourceLocation()\nOgre::ResourceGroupManager::ResourceGroup::~ResourceGroup()\nOgre::ResourceGroupManager::ResourceGroup::ResourceGroup()\nOgre::ResourceGroupManager::ResourceGroup::addToIndex(std::string const&, Ogre::Archive*)\nOgre::ResourceGroupManager::ResourceGroup::removeFromIndex(std::string const&, Ogre::Archive*)\nOgre::ResourceGroupManager::ResourceGroup::removeFromIndex(Ogre::Archive*)\n*\/\n<|endoftext|>"} {"text":"<commit_before>#ifdef __APPLE__\r\n\t#include <Glut\/glut.h>\r\n#else\r\n #define FREEGLUT_STATIC\r\n #include <GL\/glut.h>\r\n#endif\r\n\r\n#include \"Robot\/BipodModel.h\"\r\n#include \"Robot\/PhaserModel.h\"\r\n#include \"Material\/MetalMaterial.h\"\r\n\r\nBipodModel::BipodModel(void)\r\n{\r\n teamNumber = new TeamNumberModel();\r\n material = (Material*)(new MetalMaterial());\r\n}\r\n\r\n\r\nvoid BipodModel::render(){\r\n\t\r\n\tTextureManager::getInstance()->enableTexture();\r\n\tglPushMatrix();\r\n\t\tglTranslatef(.8f, 0.0f, 1.0f);\r\n\t\tglRotatef(180,0,1,0);\r\n\t\tglScalef(.65f, .65f, .65f);\r\n\t\t\/\/first leg\r\n\t\tdrawLeg();\r\n\r\n\t\t\/\/second leg\r\n\t\tglTranslatef(0.0f, 0.0f, 1.0f);\r\n\t\tdrawLeg();\r\n\t\tglTranslatef(0.0f, 0.0f, -1.0f);\r\n\r\n\r\n\t\tglTranslatef(0.f, 1.3f, 0.f);\r\n\t\t\/\/rectangle\r\n\t\tglPushMatrix();\r\n\t\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"rustymetal.bmp\"));\r\n\t\t\tglBegin(GL_QUADS);\r\n\t\t\t\tglNormal3f(0.0f, 0.0f, -1.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.2f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.2f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\r\n\r\n\t\t\t\tglNormal3f(0.0f, 0.0f, 1.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.0f, 1.5f);\r\n\t\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.2f, 1.5f);\r\n\t\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.2f, 1.5f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 1.5f);\r\n\t\t\tglEnd();\r\n\t\r\n\t\t\tglBegin(GL_QUAD_STRIP);\r\n\t\t\t\tglNormal3f(-1.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 1.5f);\r\n\t\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.2f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.2f, 1.5f);\r\n\t\t\t\t\r\n\t\t\t\tglNormal3f(0.0f, 1.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.2f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.2f, 1.5f);\r\n\r\n\t\t\t\tglNormal3f(1.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.0f, 1.5f);\r\n\r\n\t\t\t\tglNormal3f(0.0f, -1.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 1.5f);\r\n\t\t\tglEnd();\r\n\t\tglPopMatrix();\r\n\tglPopMatrix();\r\n\tglTranslated(0,1,0);\r\n}\r\n\r\nvoid BipodModel::drawLeg(){\r\n\tGLUquadricObj *qbipod = gluNewQuadric();\r\n\tgluQuadricNormals(qbipod, GLU_SMOOTH);\r\n\tTextureManager::getInstance()->enableTexture();\r\n\tglPushMatrix();\r\n\t\tglTranslatef(0.25f,0.4f,0.25f);\r\n\t\tglPushMatrix();\r\n\t\t\t\/\/thigh\r\n\t\t\tglTranslatef(0.0f,1.0f,0.0f);\r\n\t\t\tglPushMatrix();\r\n\t\t\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"steel.bmp\"));\r\n\t\t\t\tgluQuadricTexture(qbipod,true);\r\n\r\n\t\t\t\tglRotatef(90, 0.0f, 1.0f, 0.0f);\r\n\t\t\t\tglRotatef(45, 1.0f, 0.0f, 0.0f);\r\n\t\t\t\tgluCylinder(qbipod, 0.1, 0.1, 0.6, 15, 15);\r\n\t\t\tglPopMatrix();\r\n\t\t\tglTranslatef(0.0f,-1.0f,0.0f);\r\n\r\n\t\t\t\/\/leg\r\n\t\t\tglPushMatrix();\r\n\t\t\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"steel.bmp\"));\r\n\t\t\t\tgluQuadricTexture(qbipod,true);\r\n\r\n\t\t\t\tglRotatef(90, 0.0f, 1.0f, 0.0f);\r\n\t\t\t\tglRotatef(-45, 1.0f, 0.0f, 0.0f);\r\n\t\t\t\tgluCylinder(qbipod, 0.1, 0.1, 0.6, 15, 15);\r\n\t\t\tglPopMatrix();\r\n\r\n\t\t\t\/\/knee\r\n\t\t\tglTranslatef(0.45f, 0.5f, 0.0f);\r\n\t\t\tglPushMatrix();\r\n\t\t\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"steel.bmp\"));\r\n\t\t\t\tgluQuadricTexture(qbipod,true);\r\n\r\n\t\t\t\tgluSphere(qbipod,0.15,15,15);\r\n\t\t\tglPopMatrix();\r\n\t\t\tglTranslatef(-0.45f, -0.5f, 0.0f);\r\n\t\tglPopMatrix();\r\n\t\tglTranslatef(-0.25f,-0.4f,-0.25f);\r\n\r\n\r\n\t\t\/\/feet\r\n\t\tglPushMatrix();\r\n\t\t\tglScalef(.5f,.5f,.5f);\r\n\t\t\tglRotatef(-90, 0.0f,1.0f, 0.0f);\r\n\t\t\tglRotatef(90, 1.0f,0.0f, 0.0f);\r\n\t\t\tteamNumber->render();\r\n\t\tglPopMatrix();\r\n\t\tTextureManager::getInstance()->enableTexture();\r\n\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"bipodf.bmp\"));\r\n\t\tglBegin(GL_QUADS);\r\n\t\t\tglNormal3f(0.0f, 0.0f, -1.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\tglVertex3f(0.0f, 0.5f, 0.0f);\r\n\t\t\tglTexCoord2f(0.5f, 1.0f);\r\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\r\n\r\n\t\t\tglNormal3f(0.0f, 0.0f, 1.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.5f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(1.0f, 0.0f, 0.5f);\r\n\t\t\tglTexCoord2f(0.5f, 1.0f);\r\n\t\t\tglVertex3f(0.5f, 0.5f, 0.5f);\r\n\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\tglVertex3f(0.0f, 0.5f, 0.5f);\r\n\t\tglEnd();\r\n\r\n\t\tglBegin(GL_QUAD_STRIP);\r\n\t\t\tglNormal3f(-1.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.5f);\r\n\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\tglVertex3f(0.0f, 0.5f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\tglVertex3f(0.0f, 0.5f, 0.5f);\r\n\r\n\t\t\tglNormal3f(0.0f, 1.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(0.5f, 0.5f, 0.5f);\r\n\r\n\t\t\tglNormal3f(1.0f, 1.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\tglVertex3f(1.0f, 0.0f, 0.5f);\r\n\r\n\t\t\tglNormal3f(0.0f, -1.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.5f);\r\n\t\tglEnd();\r\n\tglPopMatrix();\r\n\tgluDeleteQuadric(qbipod);\r\n}<commit_msg>small update to bipod<commit_after>#ifdef __APPLE__\r\n\t#include <Glut\/glut.h>\r\n#else\r\n #define FREEGLUT_STATIC\r\n #include <GL\/glut.h>\r\n#endif\r\n\r\n#include \"Robot\/BipodModel.h\"\r\n#include \"Robot\/PhaserModel.h\"\r\n#include \"Material\/MetalMaterial.h\"\r\n\r\nBipodModel::BipodModel(void)\r\n{\r\n teamNumber = new TeamNumberModel();\r\n material = (Material*)(new MetalMaterial());\r\n}\r\n\r\n\r\nvoid BipodModel::render(){\r\n\t\r\n\tTextureManager::getInstance()->enableTexture();\r\n\tglPushMatrix();\r\n\t\tglTranslatef(.8f, 0.0f, 1.0f);\r\n\t\tglRotatef(180,0,1,0);\r\n\t\tglScalef(.65f, .65f, .65f);\r\n\t\t\/\/first leg\r\n\t\tdrawLeg();\r\n\r\n\t\t\/\/second leg\r\n\t\tglTranslatef(0.0f, 0.0f, 1.0f);\r\n\t\tdrawLeg();\r\n\t\tglTranslatef(0.0f, 0.0f, -1.0f);\r\n\r\n\r\n\t\tglTranslatef(0.f, 1.3f, 0.f);\r\n\t\t\/\/rectangle\r\n\t\tglPushMatrix();\r\n\t\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"rustymetal.bmp\"));\r\n\t\t\tglBegin(GL_QUADS);\r\n\t\t\t\tglNormal3f(0.0f, 0.0f, -1.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.2f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.2f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\r\n\r\n\t\t\t\tglNormal3f(0.0f, 0.0f, 1.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.0f, 1.5f);\r\n\t\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.2f, 1.5f);\r\n\t\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.2f, 1.5f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 1.5f);\r\n\t\t\tglEnd();\r\n\t\r\n\t\t\tglBegin(GL_QUAD_STRIP);\r\n\t\t\t\tglNormal3f(-1.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 1.5f);\r\n\t\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.2f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.2f, 1.5f);\r\n\t\t\t\t\r\n\t\t\t\tglNormal3f(0.0f, 1.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.2f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.2f, 1.5f);\r\n\r\n\t\t\t\tglNormal3f(1.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\t\tglVertex3f(1.0f, 0.0f, 1.5f);\r\n\r\n\t\t\t\tglNormal3f(0.0f, -1.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\t\tglVertex3f(0.0f, 0.0f, 1.5f);\r\n\t\t\tglEnd();\r\n\t\tglPopMatrix();\r\n\tglPopMatrix();\r\n\tglTranslated(0,1,0);\r\n\tglDisable(GL_TEXTURE_2D);\r\n}\r\n\r\nvoid BipodModel::drawLeg(){\r\n\tGLUquadricObj *qbipod = gluNewQuadric();\r\n\tgluQuadricNormals(qbipod, GLU_SMOOTH);\r\n\tTextureManager::getInstance()->enableTexture();\r\n\tglPushMatrix();\r\n\t\tglTranslatef(0.25f,0.4f,0.25f);\r\n\t\tglPushMatrix();\r\n\t\t\t\/\/thigh\r\n\t\t\tglTranslatef(0.0f,1.0f,0.0f);\r\n\t\t\tglPushMatrix();\r\n\t\t\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"steel.bmp\"));\r\n\t\t\t\tgluQuadricTexture(qbipod,true);\r\n\r\n\t\t\t\tglRotatef(90, 0.0f, 1.0f, 0.0f);\r\n\t\t\t\tglRotatef(45, 1.0f, 0.0f, 0.0f);\r\n\t\t\t\tgluCylinder(qbipod, 0.1, 0.1, 0.6, 15, 15);\r\n\t\t\tglPopMatrix();\r\n\t\t\tglTranslatef(0.0f,-1.0f,0.0f);\r\n\r\n\t\t\t\/\/leg\r\n\t\t\tglPushMatrix();\r\n\t\t\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"steel.bmp\"));\r\n\t\t\t\tgluQuadricTexture(qbipod,true);\r\n\r\n\t\t\t\tglRotatef(90, 0.0f, 1.0f, 0.0f);\r\n\t\t\t\tglRotatef(-45, 1.0f, 0.0f, 0.0f);\r\n\t\t\t\tgluCylinder(qbipod, 0.1, 0.1, 0.6, 15, 15);\r\n\t\t\tglPopMatrix();\r\n\r\n\t\t\t\/\/knee\r\n\t\t\tglTranslatef(0.45f, 0.5f, 0.0f);\r\n\t\t\tglPushMatrix();\r\n\t\t\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"steel.bmp\"));\r\n\t\t\t\tgluQuadricTexture(qbipod,true);\r\n\r\n\t\t\t\tgluSphere(qbipod,0.15,15,15);\r\n\t\t\tglPopMatrix();\r\n\t\t\tglTranslatef(-0.45f, -0.5f, 0.0f);\r\n\t\tglPopMatrix();\r\n\t\tglTranslatef(-0.25f,-0.4f,-0.25f);\r\n\r\n\r\n\t\t\/\/feet\r\n\t\tglPushMatrix();\r\n\t\t\tglScalef(.5f,.5f,.5f);\r\n\t\t\tglRotatef(-90, 0.0f,1.0f, 0.0f);\r\n\t\t\tglRotatef(90, 1.0f,0.0f, 0.0f);\r\n\t\t\tteamNumber->render();\r\n\t\tglPopMatrix();\r\n\t\tTextureManager::getInstance()->enableTexture();\r\n\t\tglBindTexture(GL_TEXTURE_2D, TextureManager::getInstance()->getTextures(\"bipodf.bmp\"));\r\n\t\tglBegin(GL_QUADS);\r\n\t\t\tglNormal3f(0.0f, 0.0f, -1.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\tglVertex3f(0.0f, 0.5f, 0.0f);\r\n\t\t\tglTexCoord2f(0.5f, 1.0f);\r\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\r\n\r\n\t\t\tglNormal3f(0.0f, 0.0f, 1.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.5f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(1.0f, 0.0f, 0.5f);\r\n\t\t\tglTexCoord2f(0.5f, 1.0f);\r\n\t\t\tglVertex3f(0.5f, 0.5f, 0.5f);\r\n\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\tglVertex3f(0.0f, 0.5f, 0.5f);\r\n\t\tglEnd();\r\n\r\n\t\tglBegin(GL_QUAD_STRIP);\r\n\t\t\tglNormal3f(-1.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.5f);\r\n\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\tglVertex3f(0.0f, 0.5f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\tglVertex3f(0.0f, 0.5f, 0.5f);\r\n\r\n\t\t\tglNormal3f(0.0f, 1.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.5f, 0.5f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(0.5f, 0.5f, 0.5f);\r\n\r\n\t\t\tglNormal3f(1.0f, 1.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 1.0f);\r\n\t\t\tglVertex3f(1.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 1.0f);\r\n\t\t\tglVertex3f(1.0f, 0.0f, 0.5f);\r\n\r\n\t\t\tglNormal3f(0.0f, -1.0f, 0.0f);\r\n\t\t\tglTexCoord2f(0.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.0f);\r\n\t\t\tglTexCoord2f(1.0f, 0.0f);\r\n\t\t\tglVertex3f(0.0f, 0.0f, 0.5f);\r\n\t\tglEnd();\r\n\tglPopMatrix();\r\n\tgluDeleteQuadric(qbipod);\r\n}<|endoftext|>"} {"text":"<commit_before>#include \"common\/network\/dns_impl.h\"\n\n#include <netdb.h>\n#include <netinet\/in.h>\n#include <sys\/socket.h>\n\n#include <chrono>\n#include <cstdint>\n#include <list>\n#include <memory>\n#include <string>\n\n#include \"common\/common\/assert.h\"\n#include \"common\/common\/fmt.h\"\n#include \"common\/network\/address_impl.h\"\n#include \"common\/network\/utility.h\"\n\n#include \"ares.h\"\n\nnamespace Envoy {\nnamespace Network {\n\nDnsResolverImpl::DnsResolverImpl(\n Event::Dispatcher& dispatcher,\n const std::vector<Network::Address::InstanceConstSharedPtr>& resolvers)\n : dispatcher_(dispatcher),\n timer_(dispatcher.createTimer([this] { onEventCallback(ARES_SOCKET_BAD, 0); })) {\n ares_options options;\n\n initializeChannel(&options, 0);\n\n if (!resolvers.empty()) {\n std::vector<std::string> resolver_addrs;\n resolver_addrs.reserve(resolvers.size());\n for (const auto& resolver : resolvers) {\n \/\/ This should be an IP address (i.e. not a pipe).\n if (resolver->ip() == nullptr) {\n ares_destroy(channel_);\n throw EnvoyException(\n fmt::format(\"DNS resolver '{}' is not an IP address\", resolver->asString()));\n }\n \/\/ Note that the ip()->port() may be zero if the port is not fully specified by the\n \/\/ Address::Instance.\n \/\/ resolver->asString() is avoided as that format may be modified by custom\n \/\/ Address::Instance implementations in ways that make the <port> not a simple\n \/\/ integer. See https:\/\/github.com\/envoyproxy\/envoy\/pull\/3366.\n resolver_addrs.push_back(fmt::format(resolver->ip()->ipv6() ? \"[{}]:{}\" : \"{}:{}\",\n resolver->ip()->addressAsString(),\n resolver->ip()->port()));\n }\n const std::string resolvers_csv = StringUtil::join(resolver_addrs, \",\");\n int result = ares_set_servers_ports_csv(channel_, resolvers_csv.c_str());\n RELEASE_ASSERT(result == ARES_SUCCESS, \"\");\n }\n}\n\nDnsResolverImpl::~DnsResolverImpl() {\n timer_->disableTimer();\n ares_destroy(channel_);\n}\n\nvoid DnsResolverImpl::initializeChannel(ares_options* options, int optmask) {\n options->sock_state_cb = [](void* arg, int fd, int read, int write) {\n static_cast<DnsResolverImpl*>(arg)->onAresSocketStateChange(fd, read, write);\n };\n options->sock_state_cb_data = this;\n ares_init_options(&channel_, options, optmask | ARES_OPT_SOCK_STATE_CB);\n}\n\nvoid DnsResolverImpl::PendingResolution::onAresHostCallback(int status, int timeouts,\n hostent* hostent) {\n \/\/ We receive ARES_EDESTRUCTION when destructing with pending queries.\n if (status == ARES_EDESTRUCTION) {\n ASSERT(owned_);\n delete this;\n return;\n }\n if (!fallback_if_failed_) {\n completed_ = true;\n }\n\n std::list<Address::InstanceConstSharedPtr> address_list;\n if (status == ARES_SUCCESS) {\n if (hostent->h_addrtype == AF_INET) {\n for (int i = 0; hostent->h_addr_list[i] != nullptr; ++i) {\n ASSERT(hostent->h_length == sizeof(in_addr));\n sockaddr_in address;\n memset(&address, 0, sizeof(address));\n address.sin_family = AF_INET;\n address.sin_port = 0;\n address.sin_addr = *reinterpret_cast<in_addr*>(hostent->h_addr_list[i]);\n address_list.emplace_back(new Address::Ipv4Instance(&address));\n }\n } else if (hostent->h_addrtype == AF_INET6) {\n for (int i = 0; hostent->h_addr_list[i] != nullptr; ++i) {\n ASSERT(hostent->h_length == sizeof(in6_addr));\n sockaddr_in6 address;\n memset(&address, 0, sizeof(address));\n address.sin6_family = AF_INET6;\n address.sin6_port = 0;\n address.sin6_addr = *reinterpret_cast<in6_addr*>(hostent->h_addr_list[i]);\n address_list.emplace_back(new Address::Ipv6Instance(address));\n }\n }\n if (!address_list.empty()) {\n completed_ = true;\n }\n }\n\n if (timeouts > 0) {\n ENVOY_LOG(debug, \"DNS request timed out {} times\", timeouts);\n }\n\n if (completed_) {\n if (!cancelled_) {\n try {\n callback_(std::move(address_list));\n } catch (const EnvoyException& e) {\n ENVOY_LOG(critical, \"EnvoyException in c-ares callback\");\n dispatcher_.post([s = std::string(e.what())] { throw EnvoyException(s); });\n } catch (const std::exception& e) {\n ENVOY_LOG(critical, \"std::exception in c-ares callback\");\n dispatcher_.post([s = std::string(e.what())] { throw EnvoyException(s); });\n } catch (...) {\n ENVOY_LOG(critical, \"Unknown exception in c-ares callback\");\n dispatcher_.post([] { throw EnvoyException(\"unknown\"); });\n }\n }\n if (owned_) {\n delete this;\n return;\n }\n }\n\n if (!completed_ && fallback_if_failed_) {\n fallback_if_failed_ = false;\n getHostByName(AF_INET);\n \/\/ Note: Nothing can follow this call to getHostByName due to deletion of this\n \/\/ object upon synchronous resolution.\n return;\n }\n}\n\nvoid DnsResolverImpl::updateAresTimer() {\n \/\/ Update the timeout for events.\n timeval timeout;\n timeval* timeout_result = ares_timeout(channel_, nullptr, &timeout);\n if (timeout_result != nullptr) {\n const auto ms =\n std::chrono::milliseconds(timeout_result->tv_sec * 1000 + timeout_result->tv_usec \/ 1000);\n ENVOY_LOG(debug, \"Setting DNS resolution timer for {} milliseconds\", ms.count());\n timer_->enableTimer(ms);\n } else {\n timer_->disableTimer();\n }\n}\n\nvoid DnsResolverImpl::onEventCallback(int fd, uint32_t events) {\n const ares_socket_t read_fd = events & Event::FileReadyType::Read ? fd : ARES_SOCKET_BAD;\n const ares_socket_t write_fd = events & Event::FileReadyType::Write ? fd : ARES_SOCKET_BAD;\n ares_process_fd(channel_, read_fd, write_fd);\n updateAresTimer();\n}\n\nvoid DnsResolverImpl::onAresSocketStateChange(int fd, int read, int write) {\n updateAresTimer();\n auto it = events_.find(fd);\n \/\/ Stop tracking events for fd if no more state change events.\n if (read == 0 && write == 0) {\n if (it != events_.end()) {\n events_.erase(it);\n }\n return;\n }\n\n \/\/ If we weren't tracking the fd before, create a new FileEvent.\n if (it == events_.end()) {\n events_[fd] = dispatcher_.createFileEvent(\n fd, [this, fd](uint32_t events) { onEventCallback(fd, events); },\n Event::FileTriggerType::Level, Event::FileReadyType::Read | Event::FileReadyType::Write);\n }\n events_[fd]->setEnabled((read ? Event::FileReadyType::Read : 0) |\n (write ? Event::FileReadyType::Write : 0));\n}\n\nActiveDnsQuery* DnsResolverImpl::resolve(const std::string& dns_name,\n DnsLookupFamily dns_lookup_family, ResolveCb callback) {\n \/\/ TODO(hennna): Add DNS caching which will allow testing the edge case of a\n \/\/ failed initial call to getHostByName followed by a synchronous IPv4\n \/\/ resolution.\n std::unique_ptr<PendingResolution> pending_resolution(\n new PendingResolution(callback, dispatcher_, channel_, dns_name));\n if (dns_lookup_family == DnsLookupFamily::Auto) {\n pending_resolution->fallback_if_failed_ = true;\n }\n\n if (dns_lookup_family == DnsLookupFamily::V4Only) {\n pending_resolution->getHostByName(AF_INET);\n } else {\n pending_resolution->getHostByName(AF_INET6);\n }\n\n if (pending_resolution->completed_) {\n \/\/ Resolution does not need asynchronous behavior or network events. For\n \/\/ example, localhost lookup.\n return nullptr;\n } else {\n \/\/ Enable timer to wake us up if the request times out.\n updateAresTimer();\n\n \/\/ The PendingResolution will self-delete when the request completes\n \/\/ (including if cancelled or if ~DnsResolverImpl() happens).\n pending_resolution->owned_ = true;\n return pending_resolution.release();\n }\n}\n\nvoid DnsResolverImpl::PendingResolution::getHostByName(int family) {\n ares_gethostbyname(\n channel_, dns_name_.c_str(), family,\n [](void* arg, int status, int timeouts, hostent* hostent) {\n static_cast<PendingResolution*>(arg)->onAresHostCallback(status, timeouts, hostent);\n },\n this);\n}\n\n} \/\/ namespace Network\n} \/\/ namespace Envoy\n<commit_msg>downgrade dns log level (#7176)<commit_after>#include \"common\/network\/dns_impl.h\"\n\n#include <netdb.h>\n#include <netinet\/in.h>\n#include <sys\/socket.h>\n\n#include <chrono>\n#include <cstdint>\n#include <list>\n#include <memory>\n#include <string>\n\n#include \"common\/common\/assert.h\"\n#include \"common\/common\/fmt.h\"\n#include \"common\/network\/address_impl.h\"\n#include \"common\/network\/utility.h\"\n\n#include \"ares.h\"\n\nnamespace Envoy {\nnamespace Network {\n\nDnsResolverImpl::DnsResolverImpl(\n Event::Dispatcher& dispatcher,\n const std::vector<Network::Address::InstanceConstSharedPtr>& resolvers)\n : dispatcher_(dispatcher),\n timer_(dispatcher.createTimer([this] { onEventCallback(ARES_SOCKET_BAD, 0); })) {\n ares_options options;\n\n initializeChannel(&options, 0);\n\n if (!resolvers.empty()) {\n std::vector<std::string> resolver_addrs;\n resolver_addrs.reserve(resolvers.size());\n for (const auto& resolver : resolvers) {\n \/\/ This should be an IP address (i.e. not a pipe).\n if (resolver->ip() == nullptr) {\n ares_destroy(channel_);\n throw EnvoyException(\n fmt::format(\"DNS resolver '{}' is not an IP address\", resolver->asString()));\n }\n \/\/ Note that the ip()->port() may be zero if the port is not fully specified by the\n \/\/ Address::Instance.\n \/\/ resolver->asString() is avoided as that format may be modified by custom\n \/\/ Address::Instance implementations in ways that make the <port> not a simple\n \/\/ integer. See https:\/\/github.com\/envoyproxy\/envoy\/pull\/3366.\n resolver_addrs.push_back(fmt::format(resolver->ip()->ipv6() ? \"[{}]:{}\" : \"{}:{}\",\n resolver->ip()->addressAsString(),\n resolver->ip()->port()));\n }\n const std::string resolvers_csv = StringUtil::join(resolver_addrs, \",\");\n int result = ares_set_servers_ports_csv(channel_, resolvers_csv.c_str());\n RELEASE_ASSERT(result == ARES_SUCCESS, \"\");\n }\n}\n\nDnsResolverImpl::~DnsResolverImpl() {\n timer_->disableTimer();\n ares_destroy(channel_);\n}\n\nvoid DnsResolverImpl::initializeChannel(ares_options* options, int optmask) {\n options->sock_state_cb = [](void* arg, int fd, int read, int write) {\n static_cast<DnsResolverImpl*>(arg)->onAresSocketStateChange(fd, read, write);\n };\n options->sock_state_cb_data = this;\n ares_init_options(&channel_, options, optmask | ARES_OPT_SOCK_STATE_CB);\n}\n\nvoid DnsResolverImpl::PendingResolution::onAresHostCallback(int status, int timeouts,\n hostent* hostent) {\n \/\/ We receive ARES_EDESTRUCTION when destructing with pending queries.\n if (status == ARES_EDESTRUCTION) {\n ASSERT(owned_);\n delete this;\n return;\n }\n if (!fallback_if_failed_) {\n completed_ = true;\n }\n\n std::list<Address::InstanceConstSharedPtr> address_list;\n if (status == ARES_SUCCESS) {\n if (hostent->h_addrtype == AF_INET) {\n for (int i = 0; hostent->h_addr_list[i] != nullptr; ++i) {\n ASSERT(hostent->h_length == sizeof(in_addr));\n sockaddr_in address;\n memset(&address, 0, sizeof(address));\n address.sin_family = AF_INET;\n address.sin_port = 0;\n address.sin_addr = *reinterpret_cast<in_addr*>(hostent->h_addr_list[i]);\n address_list.emplace_back(new Address::Ipv4Instance(&address));\n }\n } else if (hostent->h_addrtype == AF_INET6) {\n for (int i = 0; hostent->h_addr_list[i] != nullptr; ++i) {\n ASSERT(hostent->h_length == sizeof(in6_addr));\n sockaddr_in6 address;\n memset(&address, 0, sizeof(address));\n address.sin6_family = AF_INET6;\n address.sin6_port = 0;\n address.sin6_addr = *reinterpret_cast<in6_addr*>(hostent->h_addr_list[i]);\n address_list.emplace_back(new Address::Ipv6Instance(address));\n }\n }\n if (!address_list.empty()) {\n completed_ = true;\n }\n }\n\n if (timeouts > 0) {\n ENVOY_LOG(debug, \"DNS request timed out {} times\", timeouts);\n }\n\n if (completed_) {\n if (!cancelled_) {\n try {\n callback_(std::move(address_list));\n } catch (const EnvoyException& e) {\n ENVOY_LOG(critical, \"EnvoyException in c-ares callback\");\n dispatcher_.post([s = std::string(e.what())] { throw EnvoyException(s); });\n } catch (const std::exception& e) {\n ENVOY_LOG(critical, \"std::exception in c-ares callback\");\n dispatcher_.post([s = std::string(e.what())] { throw EnvoyException(s); });\n } catch (...) {\n ENVOY_LOG(critical, \"Unknown exception in c-ares callback\");\n dispatcher_.post([] { throw EnvoyException(\"unknown\"); });\n }\n }\n if (owned_) {\n delete this;\n return;\n }\n }\n\n if (!completed_ && fallback_if_failed_) {\n fallback_if_failed_ = false;\n getHostByName(AF_INET);\n \/\/ Note: Nothing can follow this call to getHostByName due to deletion of this\n \/\/ object upon synchronous resolution.\n return;\n }\n}\n\nvoid DnsResolverImpl::updateAresTimer() {\n \/\/ Update the timeout for events.\n timeval timeout;\n timeval* timeout_result = ares_timeout(channel_, nullptr, &timeout);\n if (timeout_result != nullptr) {\n const auto ms =\n std::chrono::milliseconds(timeout_result->tv_sec * 1000 + timeout_result->tv_usec \/ 1000);\n ENVOY_LOG(trace, \"Setting DNS resolution timer for {} milliseconds\", ms.count());\n timer_->enableTimer(ms);\n } else {\n timer_->disableTimer();\n }\n}\n\nvoid DnsResolverImpl::onEventCallback(int fd, uint32_t events) {\n const ares_socket_t read_fd = events & Event::FileReadyType::Read ? fd : ARES_SOCKET_BAD;\n const ares_socket_t write_fd = events & Event::FileReadyType::Write ? fd : ARES_SOCKET_BAD;\n ares_process_fd(channel_, read_fd, write_fd);\n updateAresTimer();\n}\n\nvoid DnsResolverImpl::onAresSocketStateChange(int fd, int read, int write) {\n updateAresTimer();\n auto it = events_.find(fd);\n \/\/ Stop tracking events for fd if no more state change events.\n if (read == 0 && write == 0) {\n if (it != events_.end()) {\n events_.erase(it);\n }\n return;\n }\n\n \/\/ If we weren't tracking the fd before, create a new FileEvent.\n if (it == events_.end()) {\n events_[fd] = dispatcher_.createFileEvent(\n fd, [this, fd](uint32_t events) { onEventCallback(fd, events); },\n Event::FileTriggerType::Level, Event::FileReadyType::Read | Event::FileReadyType::Write);\n }\n events_[fd]->setEnabled((read ? Event::FileReadyType::Read : 0) |\n (write ? Event::FileReadyType::Write : 0));\n}\n\nActiveDnsQuery* DnsResolverImpl::resolve(const std::string& dns_name,\n DnsLookupFamily dns_lookup_family, ResolveCb callback) {\n \/\/ TODO(hennna): Add DNS caching which will allow testing the edge case of a\n \/\/ failed initial call to getHostByName followed by a synchronous IPv4\n \/\/ resolution.\n std::unique_ptr<PendingResolution> pending_resolution(\n new PendingResolution(callback, dispatcher_, channel_, dns_name));\n if (dns_lookup_family == DnsLookupFamily::Auto) {\n pending_resolution->fallback_if_failed_ = true;\n }\n\n if (dns_lookup_family == DnsLookupFamily::V4Only) {\n pending_resolution->getHostByName(AF_INET);\n } else {\n pending_resolution->getHostByName(AF_INET6);\n }\n\n if (pending_resolution->completed_) {\n \/\/ Resolution does not need asynchronous behavior or network events. For\n \/\/ example, localhost lookup.\n return nullptr;\n } else {\n \/\/ Enable timer to wake us up if the request times out.\n updateAresTimer();\n\n \/\/ The PendingResolution will self-delete when the request completes\n \/\/ (including if cancelled or if ~DnsResolverImpl() happens).\n pending_resolution->owned_ = true;\n return pending_resolution.release();\n }\n}\n\nvoid DnsResolverImpl::PendingResolution::getHostByName(int family) {\n ares_gethostbyname(\n channel_, dns_name_.c_str(), family,\n [](void* arg, int status, int timeouts, hostent* hostent) {\n static_cast<PendingResolution*>(arg)->onAresHostCallback(status, timeouts, hostent);\n },\n this);\n}\n\n} \/\/ namespace Network\n} \/\/ namespace Envoy\n<|endoftext|>"} {"text":"<commit_before>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\n * $Log$\n * Revision 1.4 2004\/05\/03 22:56:44 strk\n * leaks fixed, exception specification omitted.\n *\n * Revision 1.3 2004\/04\/19 16:14:52 strk\n * Some memory leaks plugged in noding algorithms.\n *\n * Revision 1.2 2004\/04\/16 12:48:07 strk\n * Leak fixes.\n *\n * Revision 1.1 2004\/03\/26 07:48:30 ybychkov\n * \"noding\" package ported (JTS 1.4)\n *\n *\n **********************************************************************\/\n\n\n#include \"..\/headers\/noding.h\"\n\nnamespace geos {\n\nMCQuadtreeNoder::MCQuadtreeNoder(){\n\tchains=new vector<indexMonotoneChain*>();\n\tindex=new STRtree();\n\tidCounter = 0;\n\tnOverlaps = 0;\n}\n\nMCQuadtreeNoder::~MCQuadtreeNoder(){\n\tfor (int i=0; i<chains->size(); i++)\n\t{\n\t\tdelete (*chains)[i];\n\t}\n\tdelete chains;\n\tdelete index;\n}\nvector<SegmentString*> *\nMCQuadtreeNoder::node(vector<SegmentString*> *inputSegStrings)\n{\n\tfor(int i=0; i<(int)inputSegStrings->size();i++) {\n\t\tadd((*inputSegStrings)[i]);\n\t}\n\tintersectChains();\n\t\/\/System.out.println(\"MCQuadtreeNoder: # chain overlaps = \" + nOverlaps);\n\tvector<SegmentString*> *nodedSegStrings=getNodedEdges(inputSegStrings);\n\treturn nodedSegStrings;\n}\n\nvoid MCQuadtreeNoder::intersectChains() {\n\tMonotoneChainOverlapAction *overlapAction = new SegmentOverlapAction(segInt);\n\tfor (int i=0; i<(int)chains->size();i++) {\n\t\tindexMonotoneChain *queryChain=(*chains)[i];\n\t\tvector<void*> *overlapChains =index->query(queryChain->getEnvelope());\n\t\tfor (int j=0; j<(int)overlapChains->size();j++) {\n\t\t\tindexMonotoneChain *testChain=(indexMonotoneChain*)(*overlapChains)[j];\n\t\t\t\/**\n\t\t\t* following test makes sure we only compare each pair of chains once\n\t\t\t* and that we don't compare a chain to itself\n\t\t\t*\/\n\t\t\tif (testChain->getId()>queryChain->getId()) {\n\t\t\t\tqueryChain->computeOverlaps(testChain, overlapAction);\n\t\t\t\tnOverlaps++;\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete overlapAction;\n}\n\nvoid MCQuadtreeNoder::add(SegmentString *segStr) {\n\tvector<indexMonotoneChain*> *segChains=MonotoneChainBuilder::getChains((CoordinateList*)segStr->getCoordinates(),segStr);\n\tfor (int i=0; i<(int)segChains->size();i++) {\n\t\tindexMonotoneChain *mc=(*segChains)[i];\n\t\tmc->setId(idCounter++);\n\t\tindex->insert(mc->getEnvelope(), mc);\n\t\tchains->push_back(mc);\n\t}\n\tdelete segChains;\n}\n\nMCQuadtreeNoder::SegmentOverlapAction::SegmentOverlapAction(nodingSegmentIntersector *newSi){\n\tsi=newSi;\n}\n\nvoid MCQuadtreeNoder::SegmentOverlapAction::overlap(indexMonotoneChain *mc1, int start1, indexMonotoneChain *mc2, int start2) {\n\tSegmentString *ss1=(SegmentString*) mc1->getContext();\n\tSegmentString *ss2=(SegmentString*) mc2->getContext();\n\tsi->processIntersections(ss1, start1, ss2, start2);\n}\n\n}\n\n<commit_msg>Fixed big leak in intersectChains()<commit_after>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\n * $Log$\n * Revision 1.5 2004\/05\/05 15:51:29 strk\n * Fixed big leak in intersectChains()\n *\n * Revision 1.4 2004\/05\/03 22:56:44 strk\n * leaks fixed, exception specification omitted.\n *\n * Revision 1.3 2004\/04\/19 16:14:52 strk\n * Some memory leaks plugged in noding algorithms.\n *\n * Revision 1.2 2004\/04\/16 12:48:07 strk\n * Leak fixes.\n *\n * Revision 1.1 2004\/03\/26 07:48:30 ybychkov\n * \"noding\" package ported (JTS 1.4)\n *\n *\n **********************************************************************\/\n\n\n#include \"..\/headers\/noding.h\"\n\nnamespace geos {\n\nMCQuadtreeNoder::MCQuadtreeNoder(){\n\tchains=new vector<indexMonotoneChain*>();\n\tindex=new STRtree();\n\tidCounter = 0;\n\tnOverlaps = 0;\n}\n\nMCQuadtreeNoder::~MCQuadtreeNoder(){\n\tfor (int i=0; i<chains->size(); i++)\n\t{\n\t\tdelete (*chains)[i];\n\t}\n\tdelete chains;\n\tdelete index;\n}\nvector<SegmentString*> *\nMCQuadtreeNoder::node(vector<SegmentString*> *inputSegStrings)\n{\n\tfor(int i=0; i<(int)inputSegStrings->size();i++) {\n\t\tadd((*inputSegStrings)[i]);\n\t}\n\tintersectChains();\n\t\/\/System.out.println(\"MCQuadtreeNoder: # chain overlaps = \" + nOverlaps);\n\tvector<SegmentString*> *nodedSegStrings=getNodedEdges(inputSegStrings);\n\treturn nodedSegStrings;\n}\n\nvoid MCQuadtreeNoder::intersectChains() {\n\tMonotoneChainOverlapAction *overlapAction = new SegmentOverlapAction(segInt);\n\tfor (int i=0; i<(int)chains->size();i++) {\n\t\tindexMonotoneChain *queryChain=(*chains)[i];\n\t\tvector<void*> *overlapChains =index->query(queryChain->getEnvelope());\n\t\tfor (int j=0; j<(int)overlapChains->size();j++) {\n\t\t\tindexMonotoneChain *testChain=(indexMonotoneChain*)(*overlapChains)[j];\n\t\t\t\/**\n\t\t\t* following test makes sure we only compare each pair of chains once\n\t\t\t* and that we don't compare a chain to itself\n\t\t\t*\/\n\t\t\tif (testChain->getId()>queryChain->getId()) {\n\t\t\t\tqueryChain->computeOverlaps(testChain, overlapAction);\n\t\t\t\tnOverlaps++;\n\t\t\t}\n\t\t}\n\t\tdelete overlapChains;\n\t}\n\n\tdelete overlapAction;\n}\n\nvoid MCQuadtreeNoder::add(SegmentString *segStr) {\n\tvector<indexMonotoneChain*> *segChains=MonotoneChainBuilder::getChains((CoordinateList*)segStr->getCoordinates(),segStr);\n\tfor (int i=0; i<(int)segChains->size();i++) {\n\t\tindexMonotoneChain *mc=(*segChains)[i];\n\t\tmc->setId(idCounter++);\n\t\tindex->insert(mc->getEnvelope(), mc);\n\t\tchains->push_back(mc);\n\t}\n\tdelete segChains;\n}\n\nMCQuadtreeNoder::SegmentOverlapAction::SegmentOverlapAction(nodingSegmentIntersector *newSi){\n\tsi=newSi;\n}\n\nvoid MCQuadtreeNoder::SegmentOverlapAction::overlap(indexMonotoneChain *mc1, int start1, indexMonotoneChain *mc2, int start2) {\n\tSegmentString *ss1=(SegmentString*) mc1->getContext();\n\tSegmentString *ss2=(SegmentString*) mc2->getContext();\n\tsi->processIntersections(ss1, start1, ss2, start2);\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ IEpigram.hpp\n\/\/ Jigidesign\n\/\/\n\/\/ Created by Steven Massey on 4\/28\/13.\n\/\/ Copyright (c) 2013 Jigidesign. All rights reserved.\n\/\/\n\n#ifndef Jigidesign_IEpigram_h\n#define Jigidesign_IEpigram_h\n\n\nstruct IIEpigramIn \/\/ : Jd::TypedT <c_jdTypeId::epigram>\n{\n\tstruct Payload\n\t{\n\t\tunion\n\t\t{\n\t\t\tconst unsigned char *\tbytes;\n\t\t\tconst void *\t\t\tdata;\n\t\t};\n\t\t\n\t\tsize_t\t\t\t\t\t\tsize;\n\t};\n\t\n\/\/\tvirtual const unsigned char *\t\/* payload *\/\t\tGetPayload\t\t\t(unsigned int * o_size) const = 0;\n\tvirtual Payload\t\t\t\t\t\t\t\t\t\tGetPayload\t\t\t() const = 0;\n};\n\n\nstruct IIEpigramOut : IIEpigramIn\n{\n\tvirtual void\t\t\t\t\t\t\t\t\t\tDeliver\t\t\t\t\t(const IIEpigramIn * i_epigram) = 0;\n\tvirtual void\t\t\t\t\t\t\t\t\t\tDeliver\t\t\t\t\t(const void * i_data, size_t i_size) = 0;\n};\n\ntypedef IIEpigramOut IIEpigram;\n\ntypedef IIEpigramOut * IEpigramOut;\ntypedef const IIEpigramIn * IEpigramIn;\n\ntypedef IIEpigram * IEpigram;\n\ntypedef const IIEpigramIn * EpDelivery;\ntypedef IIEpigram * EpReceiver;\n\n\n#endif\n<commit_msg>no message<commit_after>\/\/\n\/\/ IEpigram.hpp\n\/\/ Jigidesign\n\/\/\n\/\/ Created by Steven Massey on 4\/28\/13.\n\/\/ Copyright (c) 2013 Jigidesign. All rights reserved.\n\/\/\n\n#ifndef Jigidesign_IEpigram_h\n#define Jigidesign_IEpigram_h\n\n#include <stddef.h>\n\nstruct IIEpigramIn \/\/ : Jd::TypedT <c_jdTypeId::epigram>\n{\n\tstruct Payload\n\t{\n\t\tunion\n\t\t{\n\t\t\tconst unsigned char *\tbytes;\n\t\t\tconst void *\t\t\tdata;\n\t\t};\n\t\t\n\t\tsize_t\t\t\t\t\t\tsize;\n\t};\n\t\n\/\/\tvirtual const unsigned char *\t\/* payload *\/\t\tGetPayload\t\t\t(unsigned int * o_size) const = 0;\n\tvirtual Payload\t\t\t\t\t\t\t\t\t\tGetPayload\t\t\t() const = 0;\n};\n\n\nstruct IIEpigramOut : IIEpigramIn\n{\n\tvirtual void\t\t\t\t\t\t\t\t\t\tDeliver\t\t\t\t\t(const IIEpigramIn * i_epigram) = 0;\n\tvirtual void\t\t\t\t\t\t\t\t\t\tDeliver\t\t\t\t\t(const void * i_data, size_t i_size) = 0;\n};\n\ntypedef IIEpigramOut IIEpigram;\n\ntypedef IIEpigramOut * IEpigramOut;\ntypedef const IIEpigramIn * IEpigramIn;\n\ntypedef IIEpigram * IEpigram;\n\ntypedef const IIEpigramIn * EpDelivery;\ntypedef IIEpigram * EpReceiver;\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ WraithOne\n\/\/\/ www.Dark-Abyss.net\n\/\/\/\n\/\/\/ ZFX Action 2014\n\/\/\/\n\/\/\/ Theme: Career, Cell\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <Capp.h>\n\nbool Capp::InitSmuggler()\n{\n\t\/\/ Load Prisoner Image\n\tm_Smuggler = LoadImage(m_Renderer, \"Data\/GFX\/Smuggler.png\");\n\tif (m_Smuggler == nullptr)\n\t{\n\t\tShutdown();\n\n\t\treturn false;\n\t}\n\n\tSmuggler temp;\n\n\t\/\/ Smuggler 1\n\ttemp.dstRect =\t\t\t{621, 38, 32, 32};\n\ttemp.srcRect =\t\t\t{0, 0, 32, 32};\n\ttemp.rotation =\t\t\t0;\n\ttemp.lastDesisiontime =\t90;\n\ttemp.sellGoods =\t\tCigaretts;\n\tm_SmugglerList.push_back(temp);\n\n\t\/\/ Smuggler 2\n\ttemp.dstRect =\t\t\t{595, 140, 32, 32};\n\ttemp.srcRect =\t\t\t{0, 0, 32, 32};\n\ttemp.rotation =\t\t\t0;\n\ttemp.lastDesisiontime =\t0;\n\ttemp.sellGoods =\t\tNothing;\n\tm_SmugglerList.push_back(temp);\n\n\t\/\/ Smuggler 3\n\ttemp.dstRect =\t\t\t{724, 127, 32, 32};\n\ttemp.srcRect =\t\t\t{0, 0, 32, 32};\n\ttemp.rotation =\t\t\t0;\n\ttemp.lastDesisiontime =\t0;\n\ttemp.sellGoods =\t\tCocaine;\n\tm_SmugglerList.push_back(temp);\n\n\n\treturn true;\n}\n\nvoid Capp::UpdateSmuggler(unsigned int elapsedTime)\n{\n\tstd::vector<Smuggler>::iterator it;\n\tfor (it = m_SmugglerList.begin(); it < m_SmugglerList.end(); it++)\n\t{\n\t\tunsigned int time;\n\t\tif (it->lastDesisiontime < elapsedTime)\n\t\t{\n\t\t\ttime = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttime = it->lastDesisiontime - elapsedTime;\n\t\t}\n\t\tif (time >= 30000)\n\t\t{\n\t\t\tint randnr;\n\n\t\t\trandnr = rand() % 6 + 1;\n\t\t\tif (randnr == 0)\n\t\t\t\tit->sellGoods = Nothing;\n\t\t\tif (randnr == 1)\n\t\t\t\tit->sellGoods = Cigaretts;\n\t\t\tif (randnr == 2)\n\t\t\t\tit->sellGoods = Weed;\n\t\t\tif (randnr == 3)\n\t\t\t\tit->sellGoods = Cocaine;\n\t\t\tif (randnr == 4)\n\t\t\t\tit->sellGoods = Vodka;\n\t\t\tif (randnr == 5)\n\t\t\t\tit->sellGoods = Wisky;\n\n\t\t\tit->lastDesisiontime = elapsedTime;\n\t\t}\n\t}\n\n}\nvoid Capp::RenderSmuggler(unsigned int elapsedTime)\n{\n\tstd::vector<Smuggler>::iterator it;\n\tfor (it = m_SmugglerList.begin(); it < m_SmugglerList.end(); it++)\n\t{\n\t\tSDL_RenderCopyEx(m_Renderer, m_Smuggler, &it->srcRect, &it->dstRect, it->rotation, NULL, SDL_FLIP_NONE);\n\t}\n}<commit_msg>Updated<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ WraithOne\n\/\/\/ www.Dark-Abyss.net\n\/\/\/\n\/\/\/ ZFX Action 2014\n\/\/\/\n\/\/\/ Theme: Career, Cell\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <Capp.h>\n\nbool Capp::InitSmuggler()\n{\n\t\/\/ Load Prisoner Image\n\tm_Smuggler = LoadImage(m_Renderer, \"Data\/GFX\/Smuggler.png\");\n\tif (m_Smuggler == nullptr)\n\t{\n\t\tShutdown();\n\n\t\treturn false;\n\t}\n\n\tSmuggler temp;\n\n\t\/\/ Smuggler 1\n\ttemp.dstRect =\t\t\t{621, 38, 32, 32};\n\ttemp.sellRect =\t\t\t{590, 12, 90, 90};\n\ttemp.srcRect =\t\t\t{0, 0, 32, 32};\n\ttemp.rotation =\t\t\t90;\n\ttemp.lastDesisiontime =\t0;\n\ttemp.sellGoods =\t\tCigaretts;\n\tm_SmugglerList.push_back(temp);\n\n\t\/\/ Smuggler 2\n\ttemp.dstRect =\t\t\t{595, 140, 32, 32};\n\ttemp.sellRect =\t\t\t{567, 113, 90, 90};\n\ttemp.srcRect =\t\t\t{0, 0, 32, 32};\n\ttemp.rotation =\t\t\t0;\n\ttemp.lastDesisiontime =\t4000;\n\ttemp.sellGoods =\t\tNothing;\n\tm_SmugglerList.push_back(temp);\n\n\t\/\/ Smuggler 3\n\ttemp.dstRect =\t\t\t{724, 127, 32, 32};\n\ttemp.sellRect =\t\t\t{697,97,90,90};\n\ttemp.srcRect =\t\t\t{0, 0, 32, 32};\n\ttemp.rotation =\t\t\t0;\n\ttemp.lastDesisiontime =\t8000;\n\ttemp.sellGoods =\t\tCocaine;\n\tm_SmugglerList.push_back(temp);\n\n\n\treturn true;\n}\n\nvoid Capp::UpdateSmuggler(unsigned int elapsedTime)\n{\n\tstd::vector<Smuggler>::iterator it;\n\tunsigned int time = 0;\n\n\tfor (it = m_SmugglerList.begin(); it < m_SmugglerList.end(); it++)\n\t{\n\t\tif (it->lastDesisiontime == 0)\n\t\t{\n\t\t\tit->lastDesisiontime = elapsedTime;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttime = elapsedTime - it->lastDesisiontime;\n\t\t}\n\t\t\n\n \t\tif (time >= 10000)\n\t\t{\n\t\t\tint randnr;\n\n\t\t\trandnr = rand() % 6 + 1;\n\t\t\tif (randnr == 0)\n\t\t\t\tit->sellGoods = Nothing;\n\t\t\tif (randnr == 1)\n\t\t\t\tit->sellGoods = Cigaretts;\n\t\t\tif (randnr == 2)\n\t\t\t\tit->sellGoods = Marihuana;\n\t\t\tif (randnr == 3)\n\t\t\t\tit->sellGoods = Cocaine;\n\t\t\tif (randnr == 4)\n\t\t\t\tit->sellGoods = Vodka;\n\t\t\tif (randnr == 5)\n\t\t\t\tit->sellGoods = Wisky;\n\n\t\t\tit->lastDesisiontime = elapsedTime;\n\t\t}\n\t}\n\n}\nvoid Capp::RenderSmuggler(unsigned int elapsedTime)\n{\n\tstd::vector<Smuggler>::iterator it;\n\tfor (it = m_SmugglerList.begin(); it < m_SmugglerList.end(); it++)\n\t{\n\t\tSDL_RenderCopyEx(m_Renderer, m_Smuggler, &it->srcRect, &it->dstRect, it->rotation, NULL, SDL_FLIP_NONE);\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: rscpar.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: pl $ $Date: 2001-11-05 14:44:05 $\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#ifndef _RSCPAR_HXX\n#define _RSCPAR_HXX\n\n#ifndef _RSCTOOLS_HXX\n#include <rsctools.hxx>\n#endif\n#ifndef _RSCERROR_H\n#include <rscerror.h>\n#endif\n\n\/****************** C L A S S E S ****************************************\/\nclass RscTypCont;\nclass RscExpression;\n\/*********** R s c F i l e I n s t ***************************************\/\n\n#define READBUFFER_MAX 256\nclass RscFileInst\n{\n ERRTYPE aFirstError;\/\/ Erster Fehler\n USHORT nErrorLine; \/\/ Zeile des ersten Fehlers\n USHORT nErrorPos; \/\/ Position des ersten Fehlers\n BOOL bIncLine; \/\/ Muss Zeilennummer incrementiert werden\n USHORT nLineNo; \/\/ Zeile in der Eingabedatei\n ULONG lFileIndex; \/\/ Index auf Eingabedatei\n ULONG lSrcIndex; \/\/ Index auf Basisdatei\n FILE * fInputFile; \/\/ Eingabedatei\n char * pInput; \/\/ Lesepuffer\n USHORT nInputBufLen; \/\/ Laenge des Lesepuffers\n USHORT nInputPos; \/\/ Position im Lesepuffer\n USHORT nInputEndPos;\/\/ Ende im Lesepuffer\n char * pLine; \/\/ Zeile\n USHORT nLineBufLen;\/\/Lange des Zeilenpuffres\n USHORT nScanPos; \/\/ Position in der Zeile\n int cLastChar;\n BOOL bEof;\n\npublic:\n RscTypCont * pTypCont;\n void Init(); \/\/ ctor initialisieren\n RscFileInst( RscTypCont * pTC, ULONG lIndexSrc,\n ULONG lFileIndex, FILE * fFile );\n RscFileInst( RscTypCont * pTC, ULONG lIndexSrc,\n ULONG lFileIndex, const ByteString & );\n ~RscFileInst();\n BOOL IsEof() const { return bEof; }\n void SetFileIndex( ULONG lFIndex ) { lFileIndex = lFIndex; }\n ULONG GetFileIndex() { return( lFileIndex ); }\n ULONG GetSrcIndex() { return( lSrcIndex ); }\n void SetLineNo( USHORT nLine ) { nLineNo = nLine; }\n USHORT GetLineNo() { return( nLineNo ); }\n USHORT GetScanPos() { return( nScanPos ); }\n char * GetLine() { return( pLine ); }\n int GetChar();\n int GetFastChar() { return pLine[ nScanPos ] ?\n pLine[ nScanPos++ ] : GetChar();\n }\n void GetNewLine();\n \/\/ Fehlerbehandlung\n void SetError( ERRTYPE aError );\n ERRTYPE GetError() { return aFirstError; }\n USHORT GetErrorLine() { return nErrorLine; }\n USHORT GetErrorPos() { return nErrorPos; }\n};\n\n\/******************* F u n c t i o n *************************************\/\nvoid IncludeParser( RscFileInst * pFileInst );\nERRTYPE parser( RscFileInst * pFileInst );\nRscExpression * MacroParser( RscFileInst & rFileInst );\n\n#endif \/\/ _RSCPAR_HXX\n<commit_msg>INTEGRATION: CWS res32bit (1.3.150); FILE MERGED 2004\/10\/22 13:54:27 pl 1.3.150.1: #i34513# free rsc of 32 bit constraints<commit_after>\/*************************************************************************\n *\n * $RCSfile: rscpar.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2005-01-03 17:22:42 $\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#ifndef _RSCPAR_HXX\n#define _RSCPAR_HXX\n\n#ifndef _RSCTOOLS_HXX\n#include <rsctools.hxx>\n#endif\n#ifndef _RSCERROR_H\n#include <rscerror.h>\n#endif\n\n\/****************** C L A S S E S ****************************************\/\nclass RscTypCont;\nclass RscExpression;\n\/*********** R s c F i l e I n s t ***************************************\/\n\n#define READBUFFER_MAX 256\nclass RscFileInst\n{\n ERRTYPE aFirstError;\/\/ Erster Fehler\n sal_uInt32 nErrorLine; \/\/ Zeile des ersten Fehlers\n sal_uInt32 nErrorPos; \/\/ Position des ersten Fehlers\n BOOL bIncLine; \/\/ Muss Zeilennummer incrementiert werden\n sal_uInt32 nLineNo; \/\/ Zeile in der Eingabedatei\n ULONG lFileIndex; \/\/ Index auf Eingabedatei\n ULONG lSrcIndex; \/\/ Index auf Basisdatei\n FILE * fInputFile; \/\/ Eingabedatei\n char * pInput; \/\/ Lesepuffer\n sal_uInt32 nInputBufLen; \/\/ Laenge des Lesepuffers\n sal_uInt32 nInputPos; \/\/ Position im Lesepuffer\n sal_uInt32 nInputEndPos;\/\/ Ende im Lesepuffer\n char * pLine; \/\/ Zeile\n sal_uInt32 nLineBufLen;\/\/Lange des Zeilenpuffres\n sal_uInt32 nScanPos; \/\/ Position in der Zeile\n int cLastChar;\n BOOL bEof;\n\npublic:\n RscTypCont * pTypCont;\n void Init(); \/\/ ctor initialisieren\n RscFileInst( RscTypCont * pTC, ULONG lIndexSrc,\n ULONG lFileIndex, FILE * fFile );\n RscFileInst( RscTypCont * pTC, ULONG lIndexSrc,\n ULONG lFileIndex, const ByteString & );\n ~RscFileInst();\n BOOL IsEof() const { return bEof; }\n void SetFileIndex( ULONG lFIndex ) { lFileIndex = lFIndex; }\n ULONG GetFileIndex() { return( lFileIndex ); }\n ULONG GetSrcIndex() { return( lSrcIndex ); }\n void SetLineNo( sal_uInt32 nLine ) { nLineNo = nLine; }\n sal_uInt32 GetLineNo() { return( nLineNo ); }\n sal_uInt32 GetScanPos() { return( nScanPos ); }\n char * GetLine() { return( pLine ); }\n int GetChar();\n int GetFastChar() { return pLine[ nScanPos ] ?\n pLine[ nScanPos++ ] : GetChar();\n }\n void GetNewLine();\n \/\/ Fehlerbehandlung\n void SetError( ERRTYPE aError );\n ERRTYPE GetError() { return aFirstError; }\n sal_uInt32 GetErrorLine() { return nErrorLine; }\n sal_uInt32 GetErrorPos() { return nErrorPos; }\n};\n\n\/******************* F u n c t i o n *************************************\/\nvoid IncludeParser( RscFileInst * pFileInst );\nERRTYPE parser( RscFileInst * pFileInst );\nRscExpression * MacroParser( RscFileInst & rFileInst );\n\n#endif \/\/ _RSCPAR_HXX\n<|endoftext|>"} {"text":"<commit_before>#include \"planner_navigation_actions\/actionExecutorROSNavigation.h\"\n#include <pluginlib\/class_list_macros.h>\n\nPLUGINLIB_DECLARE_CLASS(planner_navigation_actions, action_executor_ros_navigation,\n planner_navigation_actions::ActionExecutorROSNavigation,\n continual_planning_executive::ActionExecutorInterface)\n\nnamespace planner_navigation_actions\n{\n\n void ActionExecutorROSNavigation::initialize(const std::deque<std::string> & arguments)\n {\n ActionExecutorActionlib<move_base_msgs::MoveBaseAction, move_base_msgs::MoveBaseGoal,\n move_base_msgs::MoveBaseResult>::initialize(arguments);\n\n if(arguments.size() < 3)\n return;\n\n bool parseStart = true;\n if(arguments[2] == \"goal\") {\n parseStart = false;\n } else {\n ROS_ASSERT(arguments[2] == \"start\");\n }\n\n unsigned int curArg = 3;\n while(curArg < arguments.size()) {\n if(arguments[curArg] == \"goal\") {\n parseStart = false;\n curArg++;\n continue;\n }\n ROS_ASSERT(arguments.size() > curArg + 2); \/\/ need to access curArg, curArg+1\n string pred = arguments[curArg];\n string setS = arguments[curArg + 1];\n bool set = false;\n if(setS == \"true\")\n set = true;\n else if(setS == \"false\")\n set = false;\n else\n ROS_ASSERT(false);\n if(parseStart)\n _startPredicates.push_back(std::make_pair(pred, set));\n else\n _goalPredicates.push_back(std::make_pair(pred, set));\n curArg += 2;\n }\n }\n\n bool ActionExecutorROSNavigation::fillGoal(move_base_msgs::MoveBaseGoal & goal,\n const DurativeAction & a, const SymbolicState & current)\n {\n \/\/ FIXME: don't get from state (very old), but the newest.\n \/\/ The frame_id should be a fixed frame anyways\n goal.target_pose.header.stamp = ros::Time::now();\n\n ROS_ASSERT(a.parameters.size() == 2);\n string targetName = a.parameters[1];\n\n \/\/ extract nicer + warn.\n Predicate p;\n p.parameters.push_back(targetName);\n p.name = \"frame-id\";\n if(!current.hasObjectFluent(p, &goal.target_pose.header.frame_id))\n return false;\n p.name = \"x\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.position.x))\n return false;\n p.name = \"y\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.position.y))\n return false;\n p.name = \"z\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.position.z))\n return false;\n p.name = \"qx\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.orientation.x))\n return false;\n p.name = \"qy\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.orientation.y))\n return false;\n p.name = \"qz\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.orientation.z))\n return false;\n p.name = \"qw\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.orientation.w))\n return false;\n\n ROS_INFO_STREAM(\"Created goal for ActionExecutorROSNavigation as: \" << goal);\n\n return true;\n }\n\n void ActionExecutorROSNavigation::updateState(const actionlib::SimpleClientGoalState & actionReturnState,\n const move_base_msgs::MoveBaseResult & result,\n const DurativeAction & a, SymbolicState & current)\n {\n if(actionReturnState == actionlib::SimpleClientGoalState::SUCCEEDED) {\n ROS_ASSERT(a.parameters.size() == 2);\n string startName = a.parameters[0];\n string targetName = a.parameters[1];\n for(std::vector<std::pair<std::string, bool> >::iterator it = _startPredicates.begin();\n it != _startPredicates.end(); it++) {\n current.setBooleanPredicate(it->first, startName, it->second);\n }\n for(std::vector<std::pair<std::string, bool> >::iterator it = _goalPredicates.begin();\n it != _goalPredicates.end(); it++) {\n current.setBooleanPredicate(it->first, targetName, it->second);\n }\n\n }\n }\n\n};\n\n<commit_msg>bugfix in actionExecutorROSNavigation<commit_after>#include \"planner_navigation_actions\/actionExecutorROSNavigation.h\"\n#include <pluginlib\/class_list_macros.h>\n\nPLUGINLIB_DECLARE_CLASS(planner_navigation_actions, action_executor_ros_navigation,\n planner_navigation_actions::ActionExecutorROSNavigation,\n continual_planning_executive::ActionExecutorInterface)\n\nnamespace planner_navigation_actions\n{\n\n void ActionExecutorROSNavigation::initialize(const std::deque<std::string> & arguments)\n {\n ActionExecutorActionlib<move_base_msgs::MoveBaseAction, move_base_msgs::MoveBaseGoal,\n move_base_msgs::MoveBaseResult>::initialize(arguments);\n\n if(arguments.size() < 3)\n return;\n\n bool parseStart = true;\n if(arguments[2] == \"goal\") {\n parseStart = false;\n } else {\n ROS_ASSERT(arguments[2] == \"start\");\n }\n\n unsigned int curArg = 3;\n while(curArg < arguments.size()) {\n if(arguments[curArg] == \"goal\") {\n parseStart = false;\n curArg++;\n continue;\n }\n ROS_ASSERT(arguments.size() >= curArg + 2); \/\/ need to access curArg, curArg+1\n string pred = arguments[curArg];\n string setS = arguments[curArg + 1];\n bool set = false;\n if(setS == \"true\")\n set = true;\n else if(setS == \"false\")\n set = false;\n else\n ROS_ASSERT(false);\n if(parseStart)\n _startPredicates.push_back(std::make_pair(pred, set));\n else\n _goalPredicates.push_back(std::make_pair(pred, set));\n curArg += 2;\n }\n }\n\n bool ActionExecutorROSNavigation::fillGoal(move_base_msgs::MoveBaseGoal & goal,\n const DurativeAction & a, const SymbolicState & current)\n {\n \/\/ FIXME: don't get from state (very old), but the newest.\n \/\/ The frame_id should be a fixed frame anyways\n goal.target_pose.header.stamp = ros::Time::now();\n\n ROS_ASSERT(a.parameters.size() == 2);\n string targetName = a.parameters[1];\n\n \/\/ extract nicer + warn.\n Predicate p;\n p.parameters.push_back(targetName);\n p.name = \"frame-id\";\n if(!current.hasObjectFluent(p, &goal.target_pose.header.frame_id))\n return false;\n p.name = \"x\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.position.x))\n return false;\n p.name = \"y\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.position.y))\n return false;\n p.name = \"z\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.position.z))\n return false;\n p.name = \"qx\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.orientation.x))\n return false;\n p.name = \"qy\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.orientation.y))\n return false;\n p.name = \"qz\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.orientation.z))\n return false;\n p.name = \"qw\";\n if(!current.hasNumericalFluent(p, &goal.target_pose.pose.orientation.w))\n return false;\n\n ROS_INFO_STREAM(\"Created goal for ActionExecutorROSNavigation as: \" << goal);\n\n return true;\n }\n\n void ActionExecutorROSNavigation::updateState(const actionlib::SimpleClientGoalState & actionReturnState,\n const move_base_msgs::MoveBaseResult & result,\n const DurativeAction & a, SymbolicState & current)\n {\n if(actionReturnState == actionlib::SimpleClientGoalState::SUCCEEDED) {\n ROS_ASSERT(a.parameters.size() == 2);\n string startName = a.parameters[0];\n string targetName = a.parameters[1];\n for(std::vector<std::pair<std::string, bool> >::iterator it = _startPredicates.begin();\n it != _startPredicates.end(); it++) {\n current.setBooleanPredicate(it->first, startName, it->second);\n }\n for(std::vector<std::pair<std::string, bool> >::iterator it = _goalPredicates.begin();\n it != _goalPredicates.end(); it++) {\n current.setBooleanPredicate(it->first, targetName, it->second);\n }\n\n }\n }\n\n};\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: detfunc.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: nn $ $Date: 2002-05-08 14:51:43 $\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_DETFUNC_HXX\n#define SC_DETFUNC_HXX\n\n#ifndef _GEN_HXX \/\/autogen\n#include <tools\/gen.hxx>\n#endif\n\n#ifndef _TOOLS_COLOR_HXX\n#include <tools\/color.hxx>\n#endif\n\nclass SdrObject;\nclass SdrPage;\nclass String;\n\nclass ScCommentData;\nclass ScDetectiveData;\nclass ScDocument;\nclass ScTripel;\nclass ScAddress;\nclass ScRange;\n\n#define SC_DET_MAXCIRCLE 1000\n\nenum ScDetectiveDelete { SC_DET_ALL, SC_DET_DETECTIVE, SC_DET_CIRCLES, SC_DET_COMMENTS, SC_DET_ARROWS };\n\nenum ScDetectiveObjType\n{\n SC_DETOBJ_NONE,\n SC_DETOBJ_ARROW,\n SC_DETOBJ_FROMOTHERTAB,\n SC_DETOBJ_TOOTHERTAB,\n SC_DETOBJ_CIRCLE\n};\n\nclass ScDetectiveFunc\n{\n static ColorData nArrowColor;\n static ColorData nErrorColor;\n static ColorData nCommentColor;\n static BOOL bColorsInitialized;\n\n ScDocument* pDoc;\n USHORT nTab;\n\n Point GetDrawPos( USHORT nCol, USHORT nRow, BOOL bArrow );\n BOOL HasArrow( USHORT nStartCol, USHORT nStartRow, USHORT nStartTab,\n USHORT nEndCol, USHORT nEndRow, USHORT nEndTab );\n\n void DeleteArrowsAt( USHORT nCol, USHORT nRow, BOOL bDestPnt );\n void DeleteBox( USHORT nCol1, USHORT nRow1, USHORT nCol2, USHORT nRow2 );\n\n BOOL HasError( const ScTripel& rStart, const ScTripel& rEnd, ScTripel& rErrPos );\n\n void FillAttributes( ScDetectiveData& rData );\n\n \/\/ called from DrawEntry\/DrawAlienEntry and InsertObject\n BOOL InsertArrow( USHORT nCol, USHORT nRow,\n USHORT nRefStartCol, USHORT nRefStartRow,\n USHORT nRefEndCol, USHORT nRefEndRow,\n BOOL bFromOtherTab, BOOL bRed,\n ScDetectiveData& rData );\n BOOL InsertToOtherTab( USHORT nStartCol, USHORT nStartRow,\n USHORT nEndCol, USHORT nEndRow, BOOL bRed,\n ScDetectiveData& rData );\n\n \/\/ DrawEntry \/ DrawAlienEntry check for existing arrows and errors\n BOOL DrawEntry( USHORT nCol, USHORT nRow, const ScTripel& rRefStart, const ScTripel& rRefEnd,\n ScDetectiveData& rData );\n BOOL DrawAlienEntry( const ScTripel& rRefStart, const ScTripel& rRefEnd,\n ScDetectiveData& rData );\n\n void DrawCircle( USHORT nCol, USHORT nRow, ScDetectiveData& rData );\n\n SdrObject* DrawCaption( USHORT nCol, USHORT nRow, const String& rText,\n ScCommentData& rData, SdrPage* pDestPage,\n BOOL bHasUserText, BOOL bLeft,\n const Rectangle& rVisible );\n\n USHORT InsertPredLevel( USHORT nCol, USHORT nRow, ScDetectiveData& rData, USHORT nLevel );\n USHORT InsertPredLevelArea( const ScTripel& rRefStart, const ScTripel& rRefEnd,\n ScDetectiveData& rData, USHORT nLevel );\n USHORT FindPredLevel( USHORT nCol, USHORT nRow, USHORT nLevel, USHORT nDeleteLevel );\n USHORT FindPredLevelArea( const ScTripel& rRefStart, const ScTripel& rRefEnd,\n USHORT nLevel, USHORT nDeleteLevel );\n\n USHORT InsertErrorLevel( USHORT nCol, USHORT nRow, ScDetectiveData& rData, USHORT nLevel );\n\n USHORT InsertSuccLevel( USHORT nCol1, USHORT nRow1, USHORT nCol2, USHORT nRow2,\n ScDetectiveData& rData, USHORT nLevel );\n USHORT FindSuccLevel( USHORT nCol1, USHORT nRow1, USHORT nCol2, USHORT nRow2,\n USHORT nLevel, USHORT nDeleteLevel );\n\n BOOL FindFrameForObject( SdrObject* pObject, ScRange& rRange );\n\n\npublic:\n ScDetectiveFunc(ScDocument* pDocument, USHORT nTable) : pDoc(pDocument),nTab(nTable) {}\n\n BOOL ShowSucc( USHORT nCol, USHORT nRow );\n BOOL ShowPred( USHORT nCol, USHORT nRow );\n BOOL ShowError( USHORT nCol, USHORT nRow );\n\n BOOL DeleteSucc( USHORT nCol, USHORT nRow );\n BOOL DeletePred( USHORT nCol, USHORT nRow );\n BOOL DeleteAll( ScDetectiveDelete eWhat );\n\n BOOL MarkInvalid(BOOL& rOverflow);\n\n SdrObject* ShowComment( USHORT nCol, USHORT nRow, BOOL bForce, SdrPage* pDestPage = NULL );\n SdrObject* ShowCommentUser( USHORT nCol, USHORT nRow, const String& rUserText,\n const Rectangle& rVisible, BOOL bLeft,\n BOOL bForce, SdrPage* pDestPage );\n BOOL HideComment( USHORT nCol, USHORT nRow );\n\n void UpdateAllComments(); \/\/ on all tables\n void UpdateAllArrowColors(); \/\/ on all tables\n\n static BOOL IsNonAlienArrow( SdrObject* pObject );\n\n ScDetectiveObjType GetDetectiveObjectType( SdrObject* pObject,\n ScAddress& rPosition, ScRange& rSource, BOOL& rRedLine );\n void InsertObject( ScDetectiveObjType eType, const ScAddress& rPosition,\n const ScRange& rSource, BOOL bRedLine );\n\n static ColorData GetArrowColor();\n static ColorData GetErrorColor();\n static ColorData GetCommentColor();\n static void InitializeColors();\n static BOOL IsColorsInitialized();\n};\n\n\n\n#endif\n<commit_msg>INTEGRATION: CWS rowlimit (1.6.310); FILE MERGED 2004\/02\/04 11:26:25 er 1.6.310.2: #i1967# replace ScTripel,ScRefTripel with ScAddress,ScRefAddress; get rid of some warnings 2004\/01\/12 17:14:56 er 1.6.310.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>\/*************************************************************************\n *\n * $RCSfile: detfunc.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 10:06:55 $\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_DETFUNC_HXX\n#define SC_DETFUNC_HXX\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _GEN_HXX \/\/autogen\n#include <tools\/gen.hxx>\n#endif\n\n#ifndef _TOOLS_COLOR_HXX\n#include <tools\/color.hxx>\n#endif\n\nclass SdrObject;\nclass SdrPage;\nclass String;\n\nclass ScCommentData;\nclass ScDetectiveData;\nclass ScDocument;\nclass ScAddress;\nclass ScRange;\n\n#define SC_DET_MAXCIRCLE 1000\n\nenum ScDetectiveDelete { SC_DET_ALL, SC_DET_DETECTIVE, SC_DET_CIRCLES, SC_DET_COMMENTS, SC_DET_ARROWS };\n\nenum ScDetectiveObjType\n{\n SC_DETOBJ_NONE,\n SC_DETOBJ_ARROW,\n SC_DETOBJ_FROMOTHERTAB,\n SC_DETOBJ_TOOTHERTAB,\n SC_DETOBJ_CIRCLE\n};\n\nclass ScDetectiveFunc\n{\n static ColorData nArrowColor;\n static ColorData nErrorColor;\n static ColorData nCommentColor;\n static BOOL bColorsInitialized;\n\n ScDocument* pDoc;\n SCTAB nTab;\n\n Point GetDrawPos( SCCOL nCol, SCROW nRow, BOOL bArrow );\n BOOL HasArrow( const ScAddress& rStart,\n SCCOL nEndCol, SCROW nEndRow, SCTAB nEndTab );\n\n void DeleteArrowsAt( SCCOL nCol, SCROW nRow, BOOL bDestPnt );\n void DeleteBox( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2 );\n\n BOOL HasError( const ScRange& rRange, ScAddress& rErrPos );\n\n void FillAttributes( ScDetectiveData& rData );\n\n \/\/ called from DrawEntry\/DrawAlienEntry and InsertObject\n BOOL InsertArrow( SCCOL nCol, SCROW nRow,\n SCCOL nRefStartCol, SCROW nRefStartRow,\n SCCOL nRefEndCol, SCROW nRefEndRow,\n BOOL bFromOtherTab, BOOL bRed,\n ScDetectiveData& rData );\n BOOL InsertToOtherTab( SCCOL nStartCol, SCROW nStartRow,\n SCCOL nEndCol, SCROW nEndRow, BOOL bRed,\n ScDetectiveData& rData );\n\n \/\/ DrawEntry \/ DrawAlienEntry check for existing arrows and errors\n BOOL DrawEntry( SCCOL nCol, SCROW nRow, const ScRange& rRef,\n ScDetectiveData& rData );\n BOOL DrawAlienEntry( const ScRange& rRef,\n ScDetectiveData& rData );\n\n void DrawCircle( SCCOL nCol, SCROW nRow, ScDetectiveData& rData );\n\n SdrObject* DrawCaption( SCCOL nCol, SCROW nRow, const String& rText,\n ScCommentData& rData, SdrPage* pDestPage,\n BOOL bHasUserText, BOOL bLeft,\n const Rectangle& rVisible );\n\n USHORT InsertPredLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel );\n USHORT InsertPredLevelArea( const ScRange& rRef,\n ScDetectiveData& rData, USHORT nLevel );\n USHORT FindPredLevel( SCCOL nCol, SCROW nRow, USHORT nLevel, USHORT nDeleteLevel );\n USHORT FindPredLevelArea( const ScRange& rRef,\n USHORT nLevel, USHORT nDeleteLevel );\n\n USHORT InsertErrorLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel );\n\n USHORT InsertSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2,\n ScDetectiveData& rData, USHORT nLevel );\n USHORT FindSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2,\n USHORT nLevel, USHORT nDeleteLevel );\n\n BOOL FindFrameForObject( SdrObject* pObject, ScRange& rRange );\n\n\npublic:\n ScDetectiveFunc(ScDocument* pDocument, SCTAB nTable) : pDoc(pDocument),nTab(nTable) {}\n\n BOOL ShowSucc( SCCOL nCol, SCROW nRow );\n BOOL ShowPred( SCCOL nCol, SCROW nRow );\n BOOL ShowError( SCCOL nCol, SCROW nRow );\n\n BOOL DeleteSucc( SCCOL nCol, SCROW nRow );\n BOOL DeletePred( SCCOL nCol, SCROW nRow );\n BOOL DeleteAll( ScDetectiveDelete eWhat );\n\n BOOL MarkInvalid(BOOL& rOverflow);\n\n SdrObject* ShowComment( SCCOL nCol, SCROW nRow, BOOL bForce, SdrPage* pDestPage = NULL );\n SdrObject* ShowCommentUser( SCCOL nCol, SCROW nRow, const String& rUserText,\n const Rectangle& rVisible, BOOL bLeft,\n BOOL bForce, SdrPage* pDestPage );\n BOOL HideComment( SCCOL nCol, SCROW nRow );\n\n void UpdateAllComments(); \/\/ on all tables\n void UpdateAllArrowColors(); \/\/ on all tables\n\n static BOOL IsNonAlienArrow( SdrObject* pObject );\n\n ScDetectiveObjType GetDetectiveObjectType( SdrObject* pObject,\n ScAddress& rPosition, ScRange& rSource, BOOL& rRedLine );\n void InsertObject( ScDetectiveObjType eType, const ScAddress& rPosition,\n const ScRange& rSource, BOOL bRedLine );\n\n static ColorData GetArrowColor();\n static ColorData GetErrorColor();\n static ColorData GetCommentColor();\n static void InitializeColors();\n static BOOL IsColorsInitialized();\n};\n\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef HUMLConfig_HPP\n#define HUMLConfig_HPP\n\n#include <string>\n#include <cstring>\n#include <cstdlib>\n#include <stdexcept>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <list>\n#include <vector>\n#include <cmath>\n#include <boost\/smart_ptr.hpp>\n#include <boost\/numeric\/ublas\/storage.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/format.hpp>\n#include <fstream>\n#include <eigen3\/Eigen\/Dense>\n\n#include \"..\/config\/config.hpp\"\n#include \"object.hpp\"\n\n\n\n\/** version of the library *\/\n#define HUML_VERSION_MAJOR 2\n#define HUML_VERSION_MINOR 0\n\n\n\/\/definition of the macro ASSERT\n#ifndef DEBUG\n #define ASSERT(x)\n#else\n #define ASSERT(x) \\\n if (! (x)) \\\n { \\\n cout << \"ERROR!! Assert \" << #x << \" failed\\n\"; \\\n cout << \" on line \" << __LINE__ << \"\\n\"; \\\n cout << \" in file \" << __FILE__ << \"\\n\"; \\\n }\n#endif\n\n\nusing namespace std;\nusing namespace Eigen;\n\n\/** This is the main namespace of the library *\/\nnamespace HUMotion{\n\ntypedef boost::shared_ptr<Object> objectPtr;\/**< shared pointer to an object in the scenario *\/\n\nconst double PHI = (-log(2.0)\/log(TB));\/**< parameter to control when the bounce posture is reached *\/\nconst double AP = 15.0*static_cast<double>(M_PI)\/180; \/**< aperture of the fingers when approaching to pick *\/\n\nconst int N_STEP_MIN = 5; \/\/ minimum number of steps\nconst int N_STEP_MAX = 100; \/\/ maximum number of steps\n\n\/** this struct defines the Denavit-Hartenberg kinematic parameters *\/\ntypedef struct{\n vector<double> d; \/**< distances between consecutive frames along the y axes in [mm] *\/\n vector<double> a; \/**< distances between concecutive frames along the z axes in [mm] *\/\n vector<double> alpha; \/**< angle around the x axes between consecutive z axes in [rad] *\/\n vector<double> theta; \/**< angle around the z axes between consecutive x axes in [rad] *\/\n} DHparameters;\n\n\/** this struct defines the barrett hand *\/\ntypedef struct{\n double maxAperture; \/**< [mm] max aperture of the hand in [mm] *\/\n double Aw; \/**< smallest distance between F1 and F2 in [mm] *\/\n double A1; \/**< length of the 1st part of the finger in [mm] *\/\n double A2; \/**< length of the first phalax in [mm] *\/\n double A3; \/**< length of the second phalax in [mm] *\/\n double D3; \/**< depth of the fingertip in [mm] *\/\n double phi2; \/**< angular displacement between the 1st part of the finger and the 1st phalax in [rad] *\/\n double phi3; \/**< angular displacement between the 1st and the 2nd phalax in [rad] *\/\n vector<int> rk; \/**< r parameters of the barrett hand *\/\n vector<int> jk; \/**< j parameters of the barrett hand *\/\n} BarrettHand;\n\n\/** this struct defines a human finger *\/\ntypedef struct{\n double ux; \/**< position of the finger with respect to the center of the palm along the x axis in [mm] *\/\n double uy; \/**< position of the finger with respect to the center of the palm along the y axis in [mm] *\/\n double uz; \/**< position of the finger with respect to the center of the palm along the z axis in [mm] *\/\n DHparameters finger_specs; \/**< the Denavit-Hartenberg parameters of the finger *\/\n} HumanFinger;\n\n\/** this struct defines a human thumb *\/\ntypedef struct{\n double uTx; \/**< position of the thumb with respect to the center of the palm along the x axis in [mm] *\/\n double uTy; \/**< position of the thumb with respect to the center of the palm along the y axis in [mm] *\/\n double uTz; \/**< position of the thumb with respect to the center of the palm along the z axis in [mm] *\/\n DHparameters thumb_specs; \/**< the Denavit-Hartenberg parameters of the thumb *\/\n} HumanThumb;\n\n\/** this struct defines a human hand *\/\ntypedef struct{\n vector<HumanFinger> fingers; \/**< fingers of the hand *\/\n HumanThumb thumb; \/**< thumb of the hand *\/\n double maxAperture; \/**< max aperture of the hand in [mm] *\/\n} HumanHand;\n\n\/** this struct defines the parameters of the movement *\/\ntypedef struct{\n int arm_code; \/**< the code of the arm: 0 = both arms, 1 = right arm, 2 = left arm *\/\n int hand_code;\/**< the code of the hand: 0 = human hand, 1 = barrett hand *\/\n int griptype; \/**< the type of the grip *\/\n string mov_infoline; \/**< description of the movement *\/\n double dHO;\/**< distanche hand-target*\/\n std::vector<double> finalHand;\/**< final posture of the hand *\/\n std::vector<double> target;\/**< target \/ location to reach: target(0)=x, target(1)=y, target(2)=z, target(3)=roll, target(4)=pitch, target(6)=yaw,*\/\n objectPtr obj; \/**< object involved in the movement. The info of the object have to be updated according to the selected movement *\/\n bool approach;\/**< true to use the approach options, false otherwise *\/\n bool retreat;\/**< true to use the retreat options, false otherwise *\/\n std::vector<double> pre_grasp_approach; \/**< (0)= x component, (1)= y component, (2)= z component, (3)= distance form the target*\/\n std::vector<double> post_grasp_retreat; \/**< (0)= x component, (1)= y component, (2)= z component, (3)= distance form the target*\/\n std::vector<double> pre_place_approach; \/**< (0)= x component, (1)= y component, (2)= z component, (3)= distance form the target*\/\n std::vector<double> post_place_retreat; \/**< (0)= x component, (1)= y component, (2)= z component, (3)= distance form the target*\/\n bool rand_init; \/**< true to select randon initialization in \"plan\" stages *\/\n bool use_move_plane; \/**< true to constrain the end-effector to move on a plane in move movements, false otherwise*\/\n std::vector<double> plane_params; \/**< plane cartesian parameters in move movements: a*x+b*y+c*z+d=0. a=plane_params(0), b=plane_params(1), c=plane_params(2), d=plane_params(3) *\/\n}mov_params;\n\/** this struct defines the boundary conditions of the movement*\/\ntypedef struct{\n vector<double> vel_0; \/**< initial velocity of the joints in [rad\/s] *\/\n vector<double> vel_f; \/**< final velocity of the joints in [rad\/s] *\/\n vector<double> acc_0; \/**< initial acceleration of the joints in [rad\/s²] *\/\n vector<double> acc_f; \/**< final acceleration of the joints in [rad\/s²] *\/\n} boundaryConditions;\n\n\/** this struct defines the tolerances that have to be set before planning the trajectory*\/\ntypedef struct{\n mov_params mov_specs; \/**< specifications of the movement *\/\n vector<double> tolsArm; \/**< radius of the spheres along the arm in [mm] *\/\n MatrixXd tolsHand; \/**< radius of the spheres along the fingers in [mm] *\/\n MatrixXd final_tolsObstacles; \/**< tolerances of the final posture against the obstacles in [mm] *\/\n vector< MatrixXd > singleArm_tolsTarget; \/**< tolerances of the trajectory against the target in [mm] *\/\n vector< MatrixXd > singleArm_tolsObstacles; \/**< tolerances of the trajectory against the obstacles in [mm] *\/\n double tolTarPos; \/**< tolerance of the final position of the hand against the target in [mm] *\/\n double tolTarOr; \/**< tolerance of the final orientation of the hand against the target in [mm] *\/\n boundaryConditions bounds; \/**< boundary condistions of the bounce problem *\/\n vector<double> vel_approach; \/**< velocity of the joints in [rad\/s] at the beginning of the approach stage *\/\n vector<double> acc_approach; \/**< acceleration of the joints in [rad\/s²] at the beginning of the approach stage *\/\n vector<double> lambda_final; \/**< weights for the final posture optimization *\/\n vector<double> lambda_bounce; \/**< weights for the bounce posture optimization *\/\n vector<double> w_max; \/**< maximum angular velocity for each joint [rad\/s] *\/\n bool obstacle_avoidance; \/**< true to avoid obstacle *\/\n bool target_avoidance; \/**< true to avoid the target during the motion *\/\n} huml_params;\n\n\/** This struct defines the result of the planned trajectory *\/\ntypedef struct{\n int mov_type;\/**< type of the planned movement *\/\n int status;\/**< status code of the planning *\/\n string status_msg;\/**< status message of the planning *\/\n string object_id;\/**< identity of the object involved in the movement *\/\n vector<MatrixXd> trajectory_stages;\/**< sequence of the trajectories *\/\n vector<MatrixXd> velocity_stages;\/**< sequence of the velocities *\/\n vector<MatrixXd> acceleration_stages;\/**< sequence of the accelerations *\/\n vector<double> time_steps; \/**< sequence of each time steps for each trajectory *\/\n vector<string> trajectory_descriptions;\/**< description of the trajectories *\/\n}planning_result;\n\n\n\n} \/\/ namespace HUMotion\n\n\n\n\n#endif \/\/ HUMLConfig_HPP\n<commit_msg>minor changes<commit_after>#ifndef HUMLConfig_HPP\n#define HUMLConfig_HPP\n\n#include <string>\n#include <cstring>\n#include <cstdlib>\n#include <stdexcept>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <list>\n#include <vector>\n#include <cmath>\n#include <boost\/smart_ptr.hpp>\n#include <boost\/numeric\/ublas\/storage.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/format.hpp>\n#include <fstream>\n#include <eigen3\/Eigen\/Dense>\n\n#include \"..\/config\/config.hpp\"\n#include \"object.hpp\"\n\n\n\n\/** version of the library *\/\n#define HUML_VERSION_MAJOR 2\n#define HUML_VERSION_MINOR 0\n\n\n\/\/definition of the macro ASSERT\n#ifndef DEBUG\n #define ASSERT(x)\n#else\n #define ASSERT(x) \\\n if (! (x)) \\\n { \\\n cout << \"ERROR!! Assert \" << #x << \" failed\\n\"; \\\n cout << \" on line \" << __LINE__ << \"\\n\"; \\\n cout << \" in file \" << __FILE__ << \"\\n\"; \\\n }\n#endif\n\n\nusing namespace std;\nusing namespace Eigen;\n\n\/** This is the main namespace of the library *\/\nnamespace HUMotion{\n\ntypedef boost::shared_ptr<Object> objectPtr;\/**< shared pointer to an object in the scenario *\/\n\nconst double PHI = (-log(2.0)\/log(TB));\/**< parameter to control when the bounce posture is reached *\/\nconst double AP = 15.0*static_cast<double>(M_PI)\/180; \/**< aperture of the fingers when approaching to pick *\/\n\nconst int N_STEP_MIN = 5; \/\/ minimum number of steps\nconst int N_STEP_MAX = 50; \/\/ maximum number of steps\n\n\/** this struct defines the Denavit-Hartenberg kinematic parameters *\/\ntypedef struct{\n vector<double> d; \/**< distances between consecutive frames along the y axes in [mm] *\/\n vector<double> a; \/**< distances between concecutive frames along the z axes in [mm] *\/\n vector<double> alpha; \/**< angle around the x axes between consecutive z axes in [rad] *\/\n vector<double> theta; \/**< angle around the z axes between consecutive x axes in [rad] *\/\n} DHparameters;\n\n\/** this struct defines the barrett hand *\/\ntypedef struct{\n double maxAperture; \/**< [mm] max aperture of the hand in [mm] *\/\n double Aw; \/**< smallest distance between F1 and F2 in [mm] *\/\n double A1; \/**< length of the 1st part of the finger in [mm] *\/\n double A2; \/**< length of the first phalax in [mm] *\/\n double A3; \/**< length of the second phalax in [mm] *\/\n double D3; \/**< depth of the fingertip in [mm] *\/\n double phi2; \/**< angular displacement between the 1st part of the finger and the 1st phalax in [rad] *\/\n double phi3; \/**< angular displacement between the 1st and the 2nd phalax in [rad] *\/\n vector<int> rk; \/**< r parameters of the barrett hand *\/\n vector<int> jk; \/**< j parameters of the barrett hand *\/\n} BarrettHand;\n\n\/** this struct defines a human finger *\/\ntypedef struct{\n double ux; \/**< position of the finger with respect to the center of the palm along the x axis in [mm] *\/\n double uy; \/**< position of the finger with respect to the center of the palm along the y axis in [mm] *\/\n double uz; \/**< position of the finger with respect to the center of the palm along the z axis in [mm] *\/\n DHparameters finger_specs; \/**< the Denavit-Hartenberg parameters of the finger *\/\n} HumanFinger;\n\n\/** this struct defines a human thumb *\/\ntypedef struct{\n double uTx; \/**< position of the thumb with respect to the center of the palm along the x axis in [mm] *\/\n double uTy; \/**< position of the thumb with respect to the center of the palm along the y axis in [mm] *\/\n double uTz; \/**< position of the thumb with respect to the center of the palm along the z axis in [mm] *\/\n DHparameters thumb_specs; \/**< the Denavit-Hartenberg parameters of the thumb *\/\n} HumanThumb;\n\n\/** this struct defines a human hand *\/\ntypedef struct{\n vector<HumanFinger> fingers; \/**< fingers of the hand *\/\n HumanThumb thumb; \/**< thumb of the hand *\/\n double maxAperture; \/**< max aperture of the hand in [mm] *\/\n} HumanHand;\n\n\/** this struct defines the parameters of the movement *\/\ntypedef struct{\n int arm_code; \/**< the code of the arm: 0 = both arms, 1 = right arm, 2 = left arm *\/\n int hand_code;\/**< the code of the hand: 0 = human hand, 1 = barrett hand *\/\n int griptype; \/**< the type of the grip *\/\n string mov_infoline; \/**< description of the movement *\/\n double dHO;\/**< distanche hand-target*\/\n std::vector<double> finalHand;\/**< final posture of the hand *\/\n std::vector<double> target;\/**< target \/ location to reach: target(0)=x, target(1)=y, target(2)=z, target(3)=roll, target(4)=pitch, target(6)=yaw,*\/\n objectPtr obj; \/**< object involved in the movement. The info of the object have to be updated according to the selected movement *\/\n bool approach;\/**< true to use the approach options, false otherwise *\/\n bool retreat;\/**< true to use the retreat options, false otherwise *\/\n std::vector<double> pre_grasp_approach; \/**< (0)= x component, (1)= y component, (2)= z component, (3)= distance form the target*\/\n std::vector<double> post_grasp_retreat; \/**< (0)= x component, (1)= y component, (2)= z component, (3)= distance form the target*\/\n std::vector<double> pre_place_approach; \/**< (0)= x component, (1)= y component, (2)= z component, (3)= distance form the target*\/\n std::vector<double> post_place_retreat; \/**< (0)= x component, (1)= y component, (2)= z component, (3)= distance form the target*\/\n bool rand_init; \/**< true to select randon initialization in \"plan\" stages *\/\n bool use_move_plane; \/**< true to constrain the end-effector to move on a plane in move movements, false otherwise*\/\n std::vector<double> plane_params; \/**< plane cartesian parameters in move movements: a*x+b*y+c*z+d=0. a=plane_params(0), b=plane_params(1), c=plane_params(2), d=plane_params(3) *\/\n}mov_params;\n\/** this struct defines the boundary conditions of the movement*\/\ntypedef struct{\n vector<double> vel_0; \/**< initial velocity of the joints in [rad\/s] *\/\n vector<double> vel_f; \/**< final velocity of the joints in [rad\/s] *\/\n vector<double> acc_0; \/**< initial acceleration of the joints in [rad\/s²] *\/\n vector<double> acc_f; \/**< final acceleration of the joints in [rad\/s²] *\/\n} boundaryConditions;\n\n\/** this struct defines the tolerances that have to be set before planning the trajectory*\/\ntypedef struct{\n mov_params mov_specs; \/**< specifications of the movement *\/\n vector<double> tolsArm; \/**< radius of the spheres along the arm in [mm] *\/\n MatrixXd tolsHand; \/**< radius of the spheres along the fingers in [mm] *\/\n MatrixXd final_tolsObstacles; \/**< tolerances of the final posture against the obstacles in [mm] *\/\n vector< MatrixXd > singleArm_tolsTarget; \/**< tolerances of the trajectory against the target in [mm] *\/\n vector< MatrixXd > singleArm_tolsObstacles; \/**< tolerances of the trajectory against the obstacles in [mm] *\/\n double tolTarPos; \/**< tolerance of the final position of the hand against the target in [mm] *\/\n double tolTarOr; \/**< tolerance of the final orientation of the hand against the target in [mm] *\/\n boundaryConditions bounds; \/**< boundary condistions of the bounce problem *\/\n vector<double> vel_approach; \/**< velocity of the joints in [rad\/s] at the beginning of the approach stage *\/\n vector<double> acc_approach; \/**< acceleration of the joints in [rad\/s²] at the beginning of the approach stage *\/\n vector<double> lambda_final; \/**< weights for the final posture optimization *\/\n vector<double> lambda_bounce; \/**< weights for the bounce posture optimization *\/\n vector<double> w_max; \/**< maximum angular velocity for each joint [rad\/s] *\/\n bool obstacle_avoidance; \/**< true to avoid obstacle *\/\n bool target_avoidance; \/**< true to avoid the target during the motion *\/\n} huml_params;\n\n\/** This struct defines the result of the planned trajectory *\/\ntypedef struct{\n int mov_type;\/**< type of the planned movement *\/\n int status;\/**< status code of the planning *\/\n string status_msg;\/**< status message of the planning *\/\n string object_id;\/**< identity of the object involved in the movement *\/\n vector<MatrixXd> trajectory_stages;\/**< sequence of the trajectories *\/\n vector<MatrixXd> velocity_stages;\/**< sequence of the velocities *\/\n vector<MatrixXd> acceleration_stages;\/**< sequence of the accelerations *\/\n vector<double> time_steps; \/**< sequence of each time steps for each trajectory *\/\n vector<string> trajectory_descriptions;\/**< description of the trajectories *\/\n}planning_result;\n\n\n\n} \/\/ namespace HUMotion\n\n\n\n\n#endif \/\/ HUMLConfig_HPP\n<|endoftext|>"} {"text":"<commit_before>\/* ux++ - ux implementation for C++ *\/\n\n\/* LICENSE - The MIT License (MIT)\n\nCopyright (c) 2013 Tomona Nanase\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef HANDLETYPE_HPP\n#define\tHANDLETYPE_HPP\n\nnamespace uxpp {\n\n \/**\n * 内部で扱われるハンドルのタイプを表す列挙体です。\n *\/\n enum class HandleType {\n \/**\n * ゼロのゲートを持ち、発音されないノートを表します。\n *\/\n zeroGate = 0,\n\n \/**\n * パートまたはマスターの各パラメータをリセットします。\n *\/\n reset = 1,\n\n \/**\n * ノートのエンベロープをサイレンス状態に移行させ、無音状態にします。\n *\/\n silence = 2,\n\n \/**\n * ノートのエンベロープをリリース状態に移行させます。\n *\/\n noteOff = 3,\n\n \/**\n * ボリューム (音量) を変更します。\n *\/\n volume = 4,\n\n \/**\n * パンポット (定位) を変更します。\n *\/\n panpot = 5,\n\n \/**\n * ビブラートに関するパラメータを設定します。\n *\/\n vibrate = 6,\n\n \/**\n * パートに波形を割り当てます。\n *\/\n waveform = 7,\n\n \/**\n * 波形のパラメータを編集します。\n *\/\n editWaveform = 8,\n \n \/**\n * パートの音量エンベロープを変更します。\n *\/\n envelope = 9,\n\n \/**\n * パートのファインチューン値を変更します。\n *\/\n fineTune = 10,\n\n \/**\n * パートの発音ノートキーをシフトします。\n *\/\n keyShift = 11,\n\n \/**\n * ポルタメント効果に関するパラメータを設定します。\n *\/\n portament = 12,\n\n \/**\n * パートを指定されたノートまたは周波数でアタック状態にします。\n *\/\n noteOn = 13,\n };\n \n const std::unordered_map<std::string, HandleType>\n HandleTypeString = {\n {\"zeroGate\", HandleType::zeroGate},\n {\"reset\", HandleType::reset},\n {\"silence\", HandleType::silence},\n {\"noteOff\", HandleType::noteOff},\n {\"volume\", HandleType::volume},\n {\"panpot\", HandleType::panpot},\n {\"vibrate\", HandleType::vibrate},\n {\"waveform\", HandleType::waveform},\n {\"editWaveform\", HandleType::editWaveform},\n {\"envelope\", HandleType::envelope},\n {\"fineTune\", HandleType::fineTune},\n {\"keyShift\", HandleType::keyShift},\n {\"portament\", HandleType::portament},\n {\"noteOn\", HandleType::noteOn},\n };\n}\n\n#endif\t\/* HANDLETYPE_HPP *\/\n\n<commit_msg>HandleType列挙体を改良<commit_after>\/* ux++ - ux implementation for C++ *\/\n\n\/* LICENSE - The MIT License (MIT)\n\nCopyright (c) 2013 Tomona Nanase\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef HANDLETYPE_HPP\n#define\tHANDLETYPE_HPP\n\n#include <unordered_map>\n#include <string>\n#include \"EnumBase.hpp\"\n\nusing namespace std;\n\nnamespace uxpp {\n\n \/**\n * 内部で扱われるハンドルのタイプを表す列挙体です。\n *\/\n class HandleType : public EnumBase {\n public:\n\n \/\/ <editor-fold desc=\"-- Enums --\">\n\n enum values {\n \/**\n * ゼロのゲートを持ち、発音されないノートを表します。\n *\/\n zeroGate = 0,\n\n \/**\n * パートまたはマスターの各パラメータをリセットします。\n *\/\n reset = 1,\n\n \/**\n * ノートのエンベロープをサイレンス状態に移行させ、無音状態にします。\n *\/\n silence = 2,\n\n \/**\n * ノートのエンベロープをリリース状態に移行させます。\n *\/\n noteOff = 3,\n\n \/**\n * ボリューム (音量) を変更します。\n *\/\n volume = 4,\n\n \/**\n * パンポット (定位) を変更します。\n *\/\n panpot = 5,\n\n \/**\n * ビブラートに関するパラメータを設定します。\n *\/\n vibrate = 6,\n\n \/**\n * パートに波形を割り当てます。\n *\/\n waveform = 7,\n\n \/**\n * 波形のパラメータを編集します。\n *\/\n editWaveform = 8,\n\n \/**\n * パートの音量エンベロープを変更します。\n *\/\n envelope = 9,\n\n \/**\n * パートのファインチューン値を変更します。\n *\/\n fineTune = 10,\n\n \/**\n * パートの発音ノートキーをシフトします。\n *\/\n keyShift = 11,\n\n \/**\n * ポルタメント効果に関するパラメータを設定します。\n *\/\n portament = 12,\n\n \/**\n * パートを指定されたノートまたは周波数でアタック状態にします。\n *\/\n noteOn = 13,\n };\n\n \/\/ <\/editor-fold>\n\n \/\/ <editor-fold desc=\"-- Methods --\">\n\n _key_exists_impl(HandleType);\n _value_exists_impl(HandleType);\n _toString_impl(HandleType); \n _tryParse_impl(HandleType);\n \/\/ <\/editor-fold>\n\n private:\n static const unordered_map<string, values> map;\n };\n\n const unordered_map<string, HandleType::values>\n HandleType::map = {\n {\"zeroGate\", zeroGate},\n {\"reset\", reset},\n {\"silence\", silence},\n {\"noteOff\", noteOff},\n {\"volume\", volume},\n {\"panpot\", panpot},\n {\"vibrate\", vibrate},\n {\"waveform\", waveform},\n {\"editWaveform\", editWaveform},\n {\"envelope\", envelope},\n {\"fineTune\", fineTune},\n {\"keyShift\", keyShift},\n {\"portament\", portament},\n {\"noteOn\", noteOn},\n };\n}\n\n#endif\t\/* HANDLETYPE_HPP *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ @file\n\/\/\/ @version 2.0\n\/\/\/ \n\/\/\/ @section LICENSE\n\/\/\/ \n\/\/\/ This program is free software; you can redistribute it and\/or modify it under\n\/\/\/ the terms of the BSD license: http:\/\/opensource.org\/licenses\/BSD-3-Clause\n\n#include \"Manager.h\"\n#include \"Mutex.h\"\n#include \"WorkerThread.h\"\n#include \"VideoClip.h\"\n\nnamespace theoraplayer\n{\n#ifdef _THREAD_NAMING\n\tstatic int threadCounter = 1;\n\tstatic theoraplayer::Mutex counterMutex;\n#endif\n\n\tWorkerThread::WorkerThread() : Thread(&WorkerThread::_work)\n\t{\n\t\tthis->clip = NULL;\n\t}\n\n\tWorkerThread::~WorkerThread()\n\t{\n\t}\n\n\tvoid WorkerThread::_work(Thread* thread)\n\t{\n\t\tWorkerThread* self = (WorkerThread*)thread;\n\t\tMutex::ScopeLock lock;\n#ifdef _THREAD_NAMING\n\t\t{\n\t\t\tlock.acquire(&counterMutex);\n\t\t\tchar name[64] = { 0 };\n\t\t\tsprintf(name, \"WorkerThread %d\", threadCounter++);\n\t\t\tpthread_setname_np(name);\n\t\t\tlock.release();\n\t\t}\n#endif\n\t\tbool decoded = false;\n\t\twhile (self->executing && self->isRunning())\n\t\t{\n\t\t\tself->clip = theoraplayer::manager->_requestWork(self);\n\t\t\tif (self->clip == NULL)\n\t\t\t{\n\t\t\t\tif (!self->executing || !self->isRunning()) \/\/ don't pause if a destruction was given\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tThread::sleep(100.0f);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlock.acquire(self->clip->threadAccessMutex);\n\t\t\t\/\/ if user requested seeking, do that then.\n\t\t\tif (self->clip->seekFrame >= 0)\n\t\t\t{\n\t\t\t\tself->clip->_executeSeek();\n\t\t\t}\n\t\t\tdecoded = self->clip->_decodeNextFrame();\n\t\t\t\/\/ TODOth - this is a potential hazard as assignedWorkerThread is set under a VideoManager::workMutex lock, but accessed here under a VideoClip::threadAccessMutex lock\n\t\t\tif (self->clip->assignedWorkerThread == self)\n\t\t\t{\n\t\t\t\tself->clip->assignedWorkerThread = NULL;\n\t\t\t\tself->clip = NULL;\n\t\t\t}\n\t\t\tlock.release();\n\t\t\tif (!decoded)\n\t\t\t{\n\t\t\t\tThread::sleep(1.0f); \/\/ this happens when the video frame queue is full.\n\t\t\t}\n\t\t}\n\t}\n\n}<commit_msg>- small Apple fix<commit_after>\/\/\/ @file\n\/\/\/ @version 2.0\n\/\/\/ \n\/\/\/ @section LICENSE\n\/\/\/ \n\/\/\/ This program is free software; you can redistribute it and\/or modify it under\n\/\/\/ the terms of the BSD license: http:\/\/opensource.org\/licenses\/BSD-3-Clause\n\n#ifndef _WIN32\n#include <unistd.h>\n#include <pthread.h>\n#endif\n\n#include \"Manager.h\"\n#include \"Mutex.h\"\n#include \"WorkerThread.h\"\n#include \"VideoClip.h\"\n\nnamespace theoraplayer\n{\n#ifdef _THREAD_NAMING\n\tstatic int threadCounter = 1;\n\tstatic theoraplayer::Mutex counterMutex;\n#endif\n\n\tWorkerThread::WorkerThread() : Thread(&WorkerThread::_work)\n\t{\n\t\tthis->clip = NULL;\n\t}\n\n\tWorkerThread::~WorkerThread()\n\t{\n\t}\n\n\tvoid WorkerThread::_work(Thread* thread)\n\t{\n\t\tWorkerThread* self = (WorkerThread*)thread;\n\t\tMutex::ScopeLock lock;\n#ifdef _THREAD_NAMING\n\t\t{\n\t\t\tlock.acquire(&counterMutex);\n\t\t\tchar name[64] = { 0 };\n\t\t\tsprintf(name, \"WorkerThread %d\", threadCounter++);\n\t\t\tpthread_setname_np(name);\n\t\t\tlock.release();\n\t\t}\n#endif\n\t\tbool decoded = false;\n\t\twhile (self->executing && self->isRunning())\n\t\t{\n\t\t\tself->clip = theoraplayer::manager->_requestWork(self);\n\t\t\tif (self->clip == NULL)\n\t\t\t{\n\t\t\t\tif (!self->executing || !self->isRunning()) \/\/ don't pause if a destruction was given\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tThread::sleep(100.0f);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlock.acquire(self->clip->threadAccessMutex);\n\t\t\t\/\/ if user requested seeking, do that then.\n\t\t\tif (self->clip->seekFrame >= 0)\n\t\t\t{\n\t\t\t\tself->clip->_executeSeek();\n\t\t\t}\n\t\t\tdecoded = self->clip->_decodeNextFrame();\n\t\t\t\/\/ TODOth - this is a potential hazard as assignedWorkerThread is set under a VideoManager::workMutex lock, but accessed here under a VideoClip::threadAccessMutex lock\n\t\t\tif (self->clip->assignedWorkerThread == self)\n\t\t\t{\n\t\t\t\tself->clip->assignedWorkerThread = NULL;\n\t\t\t\tself->clip = NULL;\n\t\t\t}\n\t\t\tlock.release();\n\t\t\tif (!decoded)\n\t\t\t{\n\t\t\t\tThread::sleep(1.0f); \/\/ this happens when the video frame queue is full.\n\t\t\t}\n\t\t}\n\t}\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/----------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2010, 2011, 2012 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/----------------------------------------------------------------------\n\n#include <deal.II\/base\/config.h>\n\n#include <iostream>\n\n#ifdef HAVE_LIBUMFPACK\nextern \"C\" {\n#include <umfpack.h>\n}\n#endif\n\n#if defined(DEAL_II_COMPILER_SUPPORTS_MPI)\n#include <mpi.h>\n#endif\n\n#ifdef DEAL_II_USE_TRILINOS\n# include <Trilinos_version.h>\n#endif\n\n#ifdef DEAL_II_USE_MUMPS\n# include <base\/utilities.h>\n# include <dmumps_c.h>\n#endif\n\n#ifdef DEAL_II_USE_PETSC\n# include <petscversion.h>\n#endif\n\n#ifdef DEAL_II_USE_SLEPC\n# include <slepcversion.h>\n#endif\n\n\nint main()\n{\n#ifdef HAVE_LIBBLAS\n std::cout << \"dealii-feature: BLAS=yes\" << std::endl;\n#endif\n\n#ifdef HAVE_LIBLAPACK\n std::cout << \"dealii-feature: LAPACK=yes\" << std::endl;\n#endif\n\n#ifdef HAVE_LIBUMFPACK\n std::cout << \"dealii-feature: UMFPACK=\"\n\t << UMFPACK_MAIN_VERSION << '.'\n\t << UMFPACK_SUB_VERSION << '.'\n\t << UMFPACK_SUBSUB_VERSION << std::endl;\n#endif\n\n#if defined(DEAL_II_COMPILER_SUPPORTS_MPI)\n# ifdef OMPI_MAJOR_VERSION\n std::cout << \"dealii-feature: MPI=OpenMPI \"\n\t << OMPI_MAJOR_VERSION << '.'\n\t << OMPI_MINOR_VERSION << '.'\n\t << OMPI_RELEASE_VERSION << std::endl;\n# else\n std::cout << \"dealii-feature: MPI=\"\n\t << MPI_VERSION << '.'\n\t << MPI_SUBVERSION << std::endl;\n# endif\n#endif\n\n#ifdef DEAL_II_USE_TRILINOS\n# ifdef TRILINOS_VERSION_STRING\n std::cout << \"dealii-feature: Trilinos=\" << TRILINOS_VERSION_STRING << std::endl;\n# else\n const unsigned int trilinos_subminor = TRILINOS_MAJOR_MINOR_VERSION % 100;\n const unsigned int trilinos_minor = (TRILINOS_MAJOR_MINOR_VERSION\/100) % 100;\n std::cout << \"dealii-feature: Trilinos=\"\n\t << TRILINOS_MAJOR_VERSION << '.'\n\t << trilinos_minor << '.'\n\t << trilinos_subminor << std::endl;\n# endif\n#endif\n\n#ifdef DEAL_II_USE_MUMPS\n std::cout << \"dealii-feature: MUMPS=yes\" << std::endl;\n#endif\n\n#ifdef DEAL_II_USE_PETSC\n std::cout << \"dealii-feature: PETSc=\"\n\t << PETSC_VERSION_MAJOR << '.'\n\t << PETSC_VERSION_MINOR << '.'\n\t << PETSC_VERSION_SUBMINOR << \"-p\"\n\t << PETSC_VERSION_PATCH << std::endl;\n#endif\n\n#ifdef DEAL_II_USE_SLEPC\n std::cout << \"dealii-feature: SLEPc=\"\n\t << SLEPC_VERSION_MAJOR << '.'\n\t << SLEPC_VERSION_MINOR << '.'\n\t << SLEPC_VERSION_SUBMINOR << \"-p\"\n\t << SLEPC_VERSION_PATCH << std::endl;\n#endif\n\n#if defined(HAVE_HSL_MA27) || defined(HAVE_HSL_MA47)\n std::cout << \"dealii-feature: HSL=\";\n#ifdef HAVE_HSL_MA27\n std::cout << \"MA27\";\n#endif\n#ifdef HAVE_HSL_MA47\n std::cout << \"MA47\";\n#endif\n std::cout << std::endl;\n#endif\n\n#ifdef DEAL_II_USE_P4EST\n std::cout << \"dealii-feature: P4est=yes\" << std::endl;\n#endif\n\n#ifdef DEAL_II_HAVE_HDF5\n std::cout << \"dealii-feature: HDF5=yes\" << std::endl;\n#endif\n\n#ifdef DEAL_II_HAVE_TECPLOT\n std::cout << \"dealii-feature: Tecplot=yes\" << std::endl;\n#endif\n \n#ifdef HAVE_LIBNETCDF\n std::cout << \"dealii-feature: NetCDF=yes\" << std::endl;\n#endif\n\n#ifdef HAVE_LIBZ\n std::cout << \"dealii-feature: LibZ=yes\" << std::endl;\n#endif\n\n#ifdef DEAL_II_DISABLE_PARSER\n std::cout << \"dealii-feature: parser=no\" << std::endl;\n#else\n std::cout << \"dealii-feature: parser=yes\" << std::endl;\n#endif\n \n}\n<commit_msg>Change OpenMPI output and add comment<commit_after>\/\/----------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2010, 2011, 2012 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/----------------------------------------------------------------------\n\n#include <deal.II\/base\/config.h>\n\n#include <iostream>\n\n#ifdef HAVE_LIBUMFPACK\nextern \"C\" {\n#include <umfpack.h>\n}\n#endif\n\n#if defined(DEAL_II_COMPILER_SUPPORTS_MPI)\n#include <mpi.h>\n#endif\n\n#ifdef DEAL_II_USE_TRILINOS\n# include <Trilinos_version.h>\n#endif\n\n#ifdef DEAL_II_USE_MUMPS\n# include <base\/utilities.h>\n# include <dmumps_c.h>\n#endif\n\n#ifdef DEAL_II_USE_PETSC\n# include <petscversion.h>\n#endif\n\n#ifdef DEAL_II_USE_SLEPC\n# include <slepcversion.h>\n#endif\n\n\/\/ Output configuration options from config.h.\n\/\/ The format of each line is\n\/\/\n\/\/ deal-feature: FEATURE=value\n\/\/\n\/\/ no spaces in any token!\n\nint main()\n{\n#ifdef HAVE_LIBBLAS\n std::cout << \"dealii-feature: BLAS=yes\" << std::endl;\n#endif\n\n#ifdef HAVE_LIBLAPACK\n std::cout << \"dealii-feature: LAPACK=yes\" << std::endl;\n#endif\n\n#ifdef HAVE_LIBUMFPACK\n std::cout << \"dealii-feature: UMFPACK=\"\n\t << UMFPACK_MAIN_VERSION << '.'\n\t << UMFPACK_SUB_VERSION << '.'\n\t << UMFPACK_SUBSUB_VERSION << std::endl;\n#endif\n\n#if defined(DEAL_II_COMPILER_SUPPORTS_MPI)\n# ifdef OMPI_MAJOR_VERSION\n std::cout << \"dealii-feature: MPI=OpenMPI-\"\n\t << OMPI_MAJOR_VERSION << '.'\n\t << OMPI_MINOR_VERSION << '.'\n\t << OMPI_RELEASE_VERSION << std::endl;\n# else\n std::cout << \"dealii-feature: MPI=\"\n\t << MPI_VERSION << '.'\n\t << MPI_SUBVERSION << std::endl;\n# endif\n#endif\n\n#ifdef DEAL_II_USE_TRILINOS\n# ifdef TRILINOS_VERSION_STRING\n std::cout << \"dealii-feature: Trilinos=\" << TRILINOS_VERSION_STRING << std::endl;\n# else\n const unsigned int trilinos_subminor = TRILINOS_MAJOR_MINOR_VERSION % 100;\n const unsigned int trilinos_minor = (TRILINOS_MAJOR_MINOR_VERSION\/100) % 100;\n std::cout << \"dealii-feature: Trilinos=\"\n\t << TRILINOS_MAJOR_VERSION << '.'\n\t << trilinos_minor << '.'\n\t << trilinos_subminor << std::endl;\n# endif\n#endif\n\n#ifdef DEAL_II_USE_MUMPS\n std::cout << \"dealii-feature: MUMPS=yes\" << std::endl;\n#endif\n\n#ifdef DEAL_II_USE_PETSC\n std::cout << \"dealii-feature: PETSc=\"\n\t << PETSC_VERSION_MAJOR << '.'\n\t << PETSC_VERSION_MINOR << '.'\n\t << PETSC_VERSION_SUBMINOR << \"-p\"\n\t << PETSC_VERSION_PATCH << std::endl;\n#endif\n\n#ifdef DEAL_II_USE_SLEPC\n std::cout << \"dealii-feature: SLEPc=\"\n\t << SLEPC_VERSION_MAJOR << '.'\n\t << SLEPC_VERSION_MINOR << '.'\n\t << SLEPC_VERSION_SUBMINOR << \"-p\"\n\t << SLEPC_VERSION_PATCH << std::endl;\n#endif\n\n#if defined(HAVE_HSL_MA27) || defined(HAVE_HSL_MA47)\n std::cout << \"dealii-feature: HSL=\";\n#ifdef HAVE_HSL_MA27\n std::cout << \"MA27\";\n#endif\n#ifdef HAVE_HSL_MA47\n std::cout << \"MA47\";\n#endif\n std::cout << std::endl;\n#endif\n\n#ifdef DEAL_II_USE_P4EST\n std::cout << \"dealii-feature: P4est=yes\" << std::endl;\n#endif\n\n#ifdef DEAL_II_HAVE_HDF5\n std::cout << \"dealii-feature: HDF5=yes\" << std::endl;\n#endif\n\n#ifdef DEAL_II_HAVE_TECPLOT\n std::cout << \"dealii-feature: Tecplot=yes\" << std::endl;\n#endif\n \n#ifdef HAVE_LIBNETCDF\n std::cout << \"dealii-feature: NetCDF=yes\" << std::endl;\n#endif\n\n#ifdef HAVE_LIBZ\n std::cout << \"dealii-feature: LibZ=yes\" << std::endl;\n#endif\n\n#ifdef DEAL_II_DISABLE_PARSER\n std::cout << \"dealii-feature: parser=no\" << std::endl;\n#else\n std::cout << \"dealii-feature: parser=yes\" << std::endl;\n#endif\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n *\n * @brief Tests for the Backend builder class\n *\n * @copyright BSD License (see doc\/COPYING or http:\/\/www.libelektra.org)\n *\n *\/\n\n#define ELEKTRA_PLUGINSPEC_WITH_COMPARE\n\n#include <backend.hpp>\n#include <backends.hpp>\n#include <plugindatabase.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <unordered_map>\n\n#include <gtest\/gtest.h>\n#include <kdb.hpp>\n\nstd::vector<std::string> getAllPlugins ()\n{\n\tusing namespace kdb;\n\tusing namespace kdb::tools;\n\tModulesPluginDatabase mpd;\n\tstd::vector<std::string> plugins = mpd.listAllPlugins ();\n\n\t\/\/ remove known problems\n\tplugins.erase (std::remove (plugins.begin (), plugins.end (), \"jni\"), plugins.end ());\n\tplugins.erase (std::remove (plugins.begin (), plugins.end (), \"crypto_gcrypt\"), plugins.end ());\n\tplugins.erase (std::remove (plugins.begin (), plugins.end (), \"crypto_openssl\"), plugins.end ());\n\treturn plugins;\n}\n\nclass AllPlugins : public ::testing::TestWithParam<std::string>\n{\nprotected:\n};\n\nTEST_P (AllPlugins, backend)\n{\n\tusing namespace kdb;\n\tusing namespace kdb::tools;\n\tstd::string p = GetParam ();\n\t\/\/ std::cout << p << std::endl;\n\n\ttry\n\t{\n\t\tBackend b;\n\t\tb.addPlugin (PluginSpec (p));\n\t}\n\tcatch (std::exception const & e)\n\t{\n\t\tEXPECT_TRUE (true) << p;\n\t}\n}\n\nTEST_P (AllPlugins, modules)\n{\n\tusing namespace kdb;\n\tusing namespace kdb::tools;\n\tstd::string p = GetParam ();\n\t\/\/ std::cout << p << std::endl;\n\n\ttry\n\t{\n\t\tModules m;\n\t\tm.load (p);\n\t}\n\tcatch (std::exception const & e)\n\t{\n\t\tEXPECT_TRUE (true) << p;\n\t}\n}\n\n\nINSTANTIATE_TEST_CASE_P (AllPlugins, AllPlugins, testing::ValuesIn (getAllPlugins ()));\n<commit_msg>crypto-plugin: remove crypto_botan from testkdb_allplugins<commit_after>\/**\n * @file\n *\n * @brief Tests for the Backend builder class\n *\n * @copyright BSD License (see doc\/COPYING or http:\/\/www.libelektra.org)\n *\n *\/\n\n#define ELEKTRA_PLUGINSPEC_WITH_COMPARE\n\n#include <backend.hpp>\n#include <backends.hpp>\n#include <plugindatabase.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <unordered_map>\n\n#include <gtest\/gtest.h>\n#include <kdb.hpp>\n\nstd::vector<std::string> getAllPlugins ()\n{\n\tusing namespace kdb;\n\tusing namespace kdb::tools;\n\tModulesPluginDatabase mpd;\n\tstd::vector<std::string> plugins = mpd.listAllPlugins ();\n\n\t\/\/ remove known problems\n\tplugins.erase (std::remove (plugins.begin (), plugins.end (), \"jni\"), plugins.end ());\n\tplugins.erase (std::remove (plugins.begin (), plugins.end (), \"crypto_gcrypt\"), plugins.end ());\n\tplugins.erase (std::remove (plugins.begin (), plugins.end (), \"crypto_openssl\"), plugins.end ());\n\tplugins.erase (std::remove (plugins.begin (), plugins.end (), \"crypto_botan\"), plugins.end ());\n\treturn plugins;\n}\n\nclass AllPlugins : public ::testing::TestWithParam<std::string>\n{\nprotected:\n};\n\nTEST_P (AllPlugins, backend)\n{\n\tusing namespace kdb;\n\tusing namespace kdb::tools;\n\tstd::string p = GetParam ();\n\t\/\/ std::cout << p << std::endl;\n\n\ttry\n\t{\n\t\tBackend b;\n\t\tb.addPlugin (PluginSpec (p));\n\t}\n\tcatch (std::exception const & e)\n\t{\n\t\tEXPECT_TRUE (true) << p;\n\t}\n}\n\nTEST_P (AllPlugins, modules)\n{\n\tusing namespace kdb;\n\tusing namespace kdb::tools;\n\tstd::string p = GetParam ();\n\t\/\/ std::cout << p << std::endl;\n\n\ttry\n\t{\n\t\tModules m;\n\t\tm.load (p);\n\t}\n\tcatch (std::exception const & e)\n\t{\n\t\tEXPECT_TRUE (true) << p;\n\t}\n}\n\n\nINSTANTIATE_TEST_CASE_P (AllPlugins, AllPlugins, testing::ValuesIn (getAllPlugins ()));\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*! @file\n @brief NET sample (GR-KAEDE) メイン @n\n\t\t\tCopyright 2017 Kunihito Hiramatsu\n @author 平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/cmt_io.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/rspi_io.hpp\"\n#include \"common\/sdc_io.hpp\"\n\n#include \"GR\/core\/ethernet.hpp\"\n#include \"GR\/core\/ethernet_server.hpp\"\n\nnamespace {\n\n\tclass cmt_task {\n\n\t\tvoid (*task_10ms_)();\n\n\t\tvolatile unsigned long millis_;\n\t\tvolatile unsigned long delay_;\n\t\tvolatile uint32_t millis10x_;\n\t\tvolatile uint32_t cmtdiv_;\n\n\tpublic:\n\t\tcmt_task() : task_10ms_(nullptr),\n\t\t\tmillis_(0), delay_(0), millis10x_(0), cmtdiv_(0) { }\n\n\t\tvoid operator() () {\n\t\t\t++millis_;\n\t\t\t++cmtdiv_;\n\t\t\tif(cmtdiv_ >= 10) {\n\t\t\t\tif(task_10ms_ != nullptr) (*task_10ms_)();\n\t\t\t\tcmtdiv_ = 0;\n\t\t\t\t++millis10x_;\n\t\t\t}\n\t\t\tif(delay_) {\n\t\t\t\t--delay_;\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tvoid set_task_10ms(void (*task)(void)) {\n\t\t\ttask_10ms_ = task;\n\t\t}\n\n\t\tvoid sync_100hz()\n\t\t{\n\t\t\tvolatile uint32_t tmp = millis10x_;\n\t\t\twhile(tmp == millis10x_) ;\n\t\t}\n\n\t\tvolatile unsigned long get_millis() const { return millis_; }\n\t\tvolatile unsigned long get_delay() const { return delay_; }\n\n\t\tvoid set_delay(volatile unsigned long n) { delay_ = n; }\n\t};\n\n\ttypedef device::cmt_io<device::CMT0, cmt_task> CMT0;\n\tCMT0\tcmt0_;\n\n\ttypedef utils::fifo<uint8_t, 2048> BUFFER;\n\ttypedef device::sci_io<device::SCI7, BUFFER, BUFFER> SCI;\n\tSCI\t\tsci_;\n\n\t\/\/ SDC 用 SPI 定義(RSPI)\n\ttypedef device::rspi_io<device::RSPI> SPI;\n\ttypedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT;\t\/\/\/< カード選択信号\n\ttypedef device::NULL_PORT SDC_POWER;\t\/\/\/< カード電源制御(常に電源ON)\n\ttypedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT;\t\/\/\/< カード検出\n\tSPI\t\tspi_;\n\n\ttypedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC;\n\tSDC\t\tsdc_(spi_, 20000000);\n\n\ttypedef utils::rtc_io RTC;\n\tRTC\t\trtc_;\n\n\tnet::ethernet ethernet_;\n\tnet::ethernet_server server_(ethernet_);\n}\n\nextern \"C\" {\n\n\t\/\/ Ethernet driver の割り込みタスク\n\tvoid INT_Excep_ICU_GROUPAL1(void);\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief システム・文字出力\n\t\t@param[in]\tch\t文字\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid sci_putch(char ch)\n\t{\n\t\tsci_.putch(ch);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief システム・文字列出力\n\t\t@param[in]\ts\t文字列\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid sci_puts(const char* s)\n\t{\n\t\tsci_.puts(s);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief システム・文字入力\n\t\t@return\t文字\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tchar sci_getch(void)\n\t{\n\t\treturn sci_.getch();\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief システム・文字列長の取得\n\t\t@return\t文字列長\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tuint16_t sci_length(void)\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief GMT 時間の取得\n\t\t@return GMT 時間\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\ttime_t get_time()\n\t{\n\t\ttime_t t = 0;\n\t\trtc_.get_time(t);\n\t\treturn t;\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へ初期化関数を提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t\t@return ステータス\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDSTATUS disk_initialize(BYTE drv) {\n\t\treturn sdc_.at_mmc().disk_initialize(drv);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へステータスを提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDSTATUS disk_status(BYTE drv) {\n\t\treturn sdc_.at_mmc().disk_status(drv);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へリード・セクターを提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t\t@param[out]\tbuff\tPointer to the data buffer to store read data\n\t\t@param[in]\tsector\tStart sector number (LBA)\n\t\t@param[in]\tcount\tSector count (1..128)\n\t\t@return リザルト\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdc_.at_mmc().disk_read(drv, buff, sector, count);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へライト・セクターを提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t\t@param[in]\tbuff\tPointer to the data to be written\t\n\t\t@param[in]\tsector\tStart sector number (LBA)\n\t\t@param[in]\tcount\tSector count (1..128)\n\t\t@return リザルト\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdc_.at_mmc().disk_write(drv, buff, sector, count);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へI\/O コントロールを提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t\t@param[in]\tctrl\tControl code\n\t\t@param[in]\tbuff\tBuffer to send\/receive control data\n\t\t@return リザルト\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {\n\t\treturn sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へ時間を提供\n\t\t@return FatFs 時間\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDWORD get_fattime(void) {\n\t\tauto t = get_time();\n\t\treturn utils::str::get_fattime(t);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tUTF-8 から ShiftJIS への変換\n\t\t@param[in]\tsrc\tUTF-8 文字列ソース\n\t\t@param[out]\tdst\tShiftJIS 文字列出力\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid utf8_to_sjis(const char* src, char* dst) {\n\t\tutils::str::utf8_to_sjis(src, dst);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tNET で必要なミリ秒タイマー\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tunsigned long millis(void)\n\t{\n\t\treturn cmt0_.at_task().get_millis();\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tNET で必要なミリ秒ディレイ\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid delay(unsigned long ms)\n\t{\n\t\tcmt0_.at_task().set_delay(ms);\n\t\twhile(cmt0_.at_task().get_delay() != 0) ;\t\t\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tNET で必要な10ミリ秒タスク登録\n\t\t@param[in]\ttask\t10ミリ秒毎に呼ばれるタスク\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid set_task_10ms(void (*task)(void)) {\n\t\tcmt0_.at_task().set_task_10ms(task);\n\t}\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tdevice::PORT3::PCR.B5 = 1; \/\/ P35(NMI) pull-up\n\n\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\n\n\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 1ms wait\n\t\/\/ メインクロック強制発振とドライブ能力設定\n\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)\n\t\t\t\t\t\t | device::SYSTEM::MOFCR.MOFXIN.b(1);\n\tdevice::SYSTEM::MOSCCR.MOSTP = 0;\t\t\/\/ メインクロック発振器動作\n\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\n\n\t\/\/ Base Clock 12MHz\n\t\/\/ PLLDIV: 1\/1, STC: 16 倍(198MHz)\n\tdevice::SYSTEM::PLLCR = device::SYSTEM::PLLCR.PLIDIV.b(0) |\n\t\t\t\t\t\t\tdevice::SYSTEM::PLLCR.STC.b(0b011111);\n\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\n\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2)\t\t\/\/ 1\/2 (198\/4=48)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(1)\t\t\/\/ 1\/2 (198\/2=96)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.BCK.b(2)\t\t\/\/ 1\/2 (198\/4=48)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(1)\t\t\/\/ 1\/2 (198\/2=96)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(2)\t\t\/\/ 1\/4 (198\/4=48)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKC.b(2)\t\t\/\/ 1\/4 (198\/4=48)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(2);\t\/\/ 1\/4 (198\/4=48)\n\tdevice::SYSTEM::SCKCR2 = device::SYSTEM::SCKCR2.UCK.b(0b0011) | 1; \/\/ USB Clock: 1\/4 (198\/4=48)\n\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\n\n\n\t{ \/\/ タイマー設定、1000Hz(1ms)\n\t\tuint8_t int_level = 1;\n\t\tcmt0_.start(1000, int_level);\n\t}\n\n\t{ \/\/ SCI 設定\n\t\tuint8_t int_level = 2;\n\t\tsci_.start(115200, int_level);\n\t}\n\n\t\/\/ SD カード・クラスの初期化\n\tsdc_.start();\n\n\n\t{ \/\/ インサーネット開始\n\t\tdevice::power_cfg::turn(device::peripheral::ETHERC0);\n\t\tdevice::port_map::turn(device::peripheral::ETHERC0);\n\n\t\tset_interrupt_task(INT_Excep_ICU_GROUPAL1, static_cast<uint32_t>(device::icu_t::VECTOR::GROUPAL1));\n\n\t\tethernet_.start();\n\n\t\tstatic const uint8_t mac[6] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };\n\n\t\tif(ethernet_.begin(mac) == 0) {\n\t\t\tutils::format(\"Ethernet Fail: begin (DHCP)...\\n\");\n\t\t\tutils::format(\"SetIP: \");\n\t\t\tnet::ip_address ipa(192, 168, 3, 20);\n\t\t\tethernet_.begin(mac, ipa);\n\t\t} else {\n\t\t\tutils::format(\"DHCP: \");\n\t\t}\n\n#if 0\n\t\tutils::format(\"SetIP: \");\n\t\t\tnet::ip_address ipa(192, 168, 1, 10);\n\t\t\tethernet_.begin(mac, ipa);\n\t\t}\n\t\tethernet_.localIP().print();\n\t\tutils::format(\"\\n\");\n#endif\n\n\t\tserver_.begin(80);\n\t\tutils::format(\"Start server: \");\n\t\tethernet_.get_local_ip().print();\n\t\tutils::format(\" port(%d)\\n\") % static_cast<int>(server_.get_port());\n\t}\n\n\tuint32_t cnt = 0;\n\twhile(1) {\n\t\tcmt0_.at_task().sync_100hz();\n\n\t\tethernet_.service();\n\n\n\n\n\n\t\t++cnt;\n\t\tif(cnt >= 30) {\n\t\t\tcnt = 0;\n\t\t}\n\t\tdevice::PORTC::PDR.B0 = 1; \/\/ GR-KAEDE LED0 output\n\t\tdevice::PORTC::PODR.B0 = (cnt < 10) ? 0 : 1;\n\t}\n}\n<commit_msg>update http server conection<commit_after>\/\/=====================================================================\/\/\n\/*! @file\n @brief NET sample (GR-KAEDE) メイン @n\n\t\t\tCopyright 2017 Kunihito Hiramatsu\n @author 平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/cmt_io.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/rspi_io.hpp\"\n#include \"common\/sdc_io.hpp\"\n\n#include \"GR\/core\/ethernet.hpp\"\n#include \"GR\/core\/ethernet_server.hpp\"\n#include \"GR\/core\/ethernet_client.hpp\"\n\nnamespace {\n\n\tclass cmt_task {\n\n\t\tvoid (*task_10ms_)();\n\n\t\tvolatile unsigned long millis_;\n\t\tvolatile unsigned long delay_;\n\t\tvolatile uint32_t millis10x_;\n\t\tvolatile uint32_t cmtdiv_;\n\n\tpublic:\n\t\tcmt_task() : task_10ms_(nullptr),\n\t\t\tmillis_(0), delay_(0), millis10x_(0), cmtdiv_(0) { }\n\n\t\tvoid operator() () {\n\t\t\t++millis_;\n\t\t\t++cmtdiv_;\n\t\t\tif(cmtdiv_ >= 10) {\n\t\t\t\tif(task_10ms_ != nullptr) (*task_10ms_)();\n\t\t\t\tcmtdiv_ = 0;\n\t\t\t\t++millis10x_;\n\t\t\t}\n\t\t\tif(delay_) {\n\t\t\t\t--delay_;\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tvoid set_task_10ms(void (*task)(void)) {\n\t\t\ttask_10ms_ = task;\n\t\t}\n\n\t\tvoid sync_100hz()\n\t\t{\n\t\t\tvolatile uint32_t tmp = millis10x_;\n\t\t\twhile(tmp == millis10x_) ;\n\t\t}\n\n\t\tvolatile unsigned long get_millis() const { return millis_; }\n\t\tvolatile unsigned long get_delay() const { return delay_; }\n\n\t\tvoid set_delay(volatile unsigned long n) { delay_ = n; }\n\t};\n\n\ttypedef device::cmt_io<device::CMT0, cmt_task> CMT0;\n\tCMT0\tcmt0_;\n\n\ttypedef utils::fifo<uint8_t, 2048> BUFFER;\n\ttypedef device::sci_io<device::SCI7, BUFFER, BUFFER> SCI;\n\tSCI\t\tsci_;\n\n\t\/\/ SDC 用 SPI 定義(RSPI)\n\ttypedef device::rspi_io<device::RSPI> SPI;\n\ttypedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT;\t\/\/\/< カード選択信号\n\ttypedef device::NULL_PORT SDC_POWER;\t\/\/\/< カード電源制御(常に電源ON)\n\ttypedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT;\t\/\/\/< カード検出\n\tSPI\t\tspi_;\n\n\ttypedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC;\n\tSDC\t\tsdc_(spi_, 20000000);\n\n\ttypedef utils::rtc_io RTC;\n\tRTC\t\trtc_;\n\n\tnet::ethernet ethernet_;\n\tnet::ethernet_server server_(ethernet_);\n\tnet::ethernet_client client_(ethernet_);\n}\n\nextern \"C\" {\n\n\t\/\/ Ethernet driver の割り込みタスク\n\tvoid INT_Excep_ICU_GROUPAL1(void);\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief システム・文字出力\n\t\t@param[in]\tch\t文字\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid sci_putch(char ch)\n\t{\n\t\tsci_.putch(ch);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief システム・文字列出力\n\t\t@param[in]\ts\t文字列\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid sci_puts(const char* s)\n\t{\n\t\tsci_.puts(s);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief システム・文字入力\n\t\t@return\t文字\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tchar sci_getch(void)\n\t{\n\t\treturn sci_.getch();\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief システム・文字列長の取得\n\t\t@return\t文字列長\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tuint16_t sci_length(void)\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief GMT 時間の取得\n\t\t@return GMT 時間\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\ttime_t get_time()\n\t{\n\t\ttime_t t = 0;\n\t\trtc_.get_time(t);\n\t\treturn t;\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へ初期化関数を提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t\t@return ステータス\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDSTATUS disk_initialize(BYTE drv) {\n\t\treturn sdc_.at_mmc().disk_initialize(drv);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へステータスを提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDSTATUS disk_status(BYTE drv) {\n\t\treturn sdc_.at_mmc().disk_status(drv);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へリード・セクターを提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t\t@param[out]\tbuff\tPointer to the data buffer to store read data\n\t\t@param[in]\tsector\tStart sector number (LBA)\n\t\t@param[in]\tcount\tSector count (1..128)\n\t\t@return リザルト\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdc_.at_mmc().disk_read(drv, buff, sector, count);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へライト・セクターを提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t\t@param[in]\tbuff\tPointer to the data to be written\t\n\t\t@param[in]\tsector\tStart sector number (LBA)\n\t\t@param[in]\tcount\tSector count (1..128)\n\t\t@return リザルト\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdc_.at_mmc().disk_write(drv, buff, sector, count);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へI\/O コントロールを提供\n\t\t@param[in]\tdrv\t\tPhysical drive nmuber (0)\n\t\t@param[in]\tctrl\tControl code\n\t\t@param[in]\tbuff\tBuffer to send\/receive control data\n\t\t@return リザルト\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {\n\t\treturn sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tFatFs へ時間を提供\n\t\t@return FatFs 時間\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tDWORD get_fattime(void) {\n\t\tauto t = get_time();\n\t\treturn utils::str::get_fattime(t);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tUTF-8 から ShiftJIS への変換\n\t\t@param[in]\tsrc\tUTF-8 文字列ソース\n\t\t@param[out]\tdst\tShiftJIS 文字列出力\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid utf8_to_sjis(const char* src, char* dst) {\n\t\tutils::str::utf8_to_sjis(src, dst);\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tNET で必要なミリ秒タイマー\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tunsigned long millis(void)\n\t{\n\t\treturn cmt0_.at_task().get_millis();\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tNET で必要なミリ秒ディレイ\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid delay(unsigned long ms)\n\t{\n\t\tcmt0_.at_task().set_delay(ms);\n\t\twhile(cmt0_.at_task().get_delay() != 0) ;\t\t\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\tNET で必要な10ミリ秒タスク登録\n\t\t@param[in]\ttask\t10ミリ秒毎に呼ばれるタスク\n\t *\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid set_task_10ms(void (*task)(void)) {\n\t\tcmt0_.at_task().set_task_10ms(task);\n\t}\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tdevice::PORT3::PCR.B5 = 1; \/\/ P35(NMI) pull-up\n\n\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\n\n\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 1ms wait\n\t\/\/ メインクロック強制発振とドライブ能力設定\n\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)\n\t\t\t\t\t\t | device::SYSTEM::MOFCR.MOFXIN.b(1);\n\tdevice::SYSTEM::MOSCCR.MOSTP = 0;\t\t\/\/ メインクロック発振器動作\n\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\n\n\t\/\/ Base Clock 12MHz\n\t\/\/ PLLDIV: 1\/1, STC: 16 倍(198MHz)\n\tdevice::SYSTEM::PLLCR = device::SYSTEM::PLLCR.PLIDIV.b(0) |\n\t\t\t\t\t\t\tdevice::SYSTEM::PLLCR.STC.b(0b011111);\n\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\n\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2)\t\t\/\/ 1\/2 (198\/4=48)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(1)\t\t\/\/ 1\/2 (198\/2=96)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.BCK.b(2)\t\t\/\/ 1\/2 (198\/4=48)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(1)\t\t\/\/ 1\/2 (198\/2=96)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(2)\t\t\/\/ 1\/4 (198\/4=48)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKC.b(2)\t\t\/\/ 1\/4 (198\/4=48)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(2);\t\/\/ 1\/4 (198\/4=48)\n\tdevice::SYSTEM::SCKCR2 = device::SYSTEM::SCKCR2.UCK.b(0b0011) | 1; \/\/ USB Clock: 1\/4 (198\/4=48)\n\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\n\n\n\t{ \/\/ タイマー設定、1000Hz(1ms)\n\t\tuint8_t int_level = 1;\n\t\tcmt0_.start(1000, int_level);\n\t}\n\n\t{ \/\/ SCI 設定\n\t\tuint8_t int_level = 2;\n\t\tsci_.start(115200, int_level);\n\t}\n\n\t\/\/ SD カード・クラスの初期化\n\tsdc_.start();\n\n\n\t{ \/\/ インサーネット開始\n\t\tdevice::power_cfg::turn(device::peripheral::ETHERC0);\n\t\tdevice::port_map::turn(device::peripheral::ETHERC0);\n\n\t\tset_interrupt_task(INT_Excep_ICU_GROUPAL1, static_cast<uint32_t>(device::icu_t::VECTOR::GROUPAL1));\n\n\t\tethernet_.start();\n\n\t\tstatic const uint8_t mac[6] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };\n\n\t\tif(ethernet_.begin(mac) == 0) {\n\t\t\tutils::format(\"Ethernet Fail: begin (DHCP)...\\n\");\n\t\t\tutils::format(\"SetIP: \");\n\t\t\tnet::ip_address ipa(192, 168, 3, 20);\n\t\t\tethernet_.begin(mac, ipa);\n\t\t} else {\n\t\t\tutils::format(\"DHCP: \");\n\t\t}\n\n#if 0\n\t\tutils::format(\"SetIP: \");\n\t\t\tnet::ip_address ipa(192, 168, 1, 10);\n\t\t\tethernet_.begin(mac, ipa);\n\t\t}\n\t\tethernet_.localIP().print();\n\t\tutils::format(\"\\n\");\n#endif\n\n\t\tserver_.begin(80);\n\t\tutils::format(\"Start server: \");\n\t\tethernet_.get_local_ip().print();\n\t\tutils::format(\" port(%d)\\n\") % static_cast<int>(server_.get_port());\n\t}\n\n\tuint32_t cnt = 0;\n\twhile(1) {\n\t\tcmt0_.at_task().sync_100hz();\n\n\t\tethernet_.service();\n\n\n\n\n\n\t\t++cnt;\n\t\tif(cnt >= 30) {\n\t\t\tcnt = 0;\n\t\t}\n\t\tdevice::PORTC::PDR.B0 = 1; \/\/ GR-KAEDE LED0 output\n\t\tdevice::PORTC::PODR.B0 = (cnt < 10) ? 0 : 1;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\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 \"contentitemspage.h\"\n#include \"utils.h\"\n\n#include <MApplication>\n#include <MAbstractCellCreator>\n#include <MImageWidget>\n#include <MLayout>\n#include <MLinearLayoutPolicy>\n#include <MList>\n#include <MListItem>\n#include <MProgressIndicator>\n\n#include <MBasicListItem>\n#include <MDetailedListItem>\n#include <MAdvancedListItem>\n\nclass BasicListItemCreator : public MAbstractCellCreator<MBasicListItem>\n{\npublic:\n BasicListItemCreator(MBasicListItem::ItemStyle style)\n : itemStyle(style),\n defaultImage(Utils::imagesDir() + \"DefaultAvatar.png\")\n {\n }\n\n MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {\n Q_UNUSED(index);\n MBasicListItem *cell = dynamic_cast<MBasicListItem*>(recycler.take(MBasicListItem::staticMetaObject.className()));\n \n if (cell == NULL) {\n cell = new MBasicListItem(itemStyle);\n if (MApplication::instance()->objectName() == \"widgetsgallery\") {\n cell->setStyleName(\"CommonBasicListItem\");\n } else {\n cell->setStyleName(\"CommonBasicListItemInverted\");\n }\n cell->setLayoutPosition(M::CenterPosition);\n }\n updateCell(index, cell);\n\n return cell;\n }\n\n void updateCell(const QModelIndex &index, MWidget *cell) const {\n MBasicListItem *item = dynamic_cast<MBasicListItem*>(cell);\n if (!item)\n return;\n\n switch (itemStyle) {\n case MBasicListItem::SingleTitle: {\n item->setTitle(index.data().toString());\n break;\n }\n case MBasicListItem::TitleWithSubtitle: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n break;\n }\n case MBasicListItem::IconWithTitle: {\n item->setTitle(index.data().toString());\n item->imageWidget()->setImage(defaultImage);\n break; \n }\n case MBasicListItem::IconWithTitleAndSubtitle: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n item->imageWidget()->setImage(defaultImage);\n break; \n }\n default:\n break;\n };\n\n }\n\nprivate:\n MBasicListItem::ItemStyle itemStyle;\n QImage defaultImage;\n};\n\n\nclass DetailedListItemCreator : public MAbstractCellCreator<MDetailedListItem>\n{\npublic:\n DetailedListItemCreator(MDetailedListItem::ItemStyle style)\n : itemStyle(style),\n defaultImage(Utils::imagesDir() + \"DefaultAvatar.png\")\n {\n }\n\n MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {\n Q_UNUSED(index);\n MDetailedListItem *cell = dynamic_cast<MDetailedListItem*>(recycler.take(MDetailedListItem::staticMetaObject.className()));\n \n if (cell == NULL) {\n cell = new MDetailedListItem(itemStyle);\n if (MApplication::instance()->objectName() == \"widgetsgallery\") {\n cell->setStyleName(\"CommonDetailedListItem\");\n } else {\n cell->setStyleName(\"CommonDetailedListItemInverted\");\n }\n cell->setLayoutPosition(M::CenterPosition);\n }\n updateCell(index, cell);\n\n return cell;\n }\n\n void updateCell(const QModelIndex &index, MWidget *cell) const {\n MDetailedListItem *item = dynamic_cast<MDetailedListItem*>(cell);\n if (!item)\n return;\n\n switch (itemStyle) {\n case MDetailedListItem::IconTitleSubtitleAndTwoSideIcons: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->sideBottomImageWidget()->setImage(defaultImage);\n break; \n }\n case MDetailedListItem::IconTitleSubtitleAndSideIconWithLabel: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n \/\/% \"Side\"\n item->setSideBottomTitle(qtTrId(\"xx_wg_contentitemspage_sidetitle\"));\n break; \n }\n case MDetailedListItem::ThumbnailTitleSubtitleAndTwoSideIcons: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->sideBottomImageWidget()->setImage(defaultImage);\n break; \n }\n case MDetailedListItem::ThumbnailTitleAndTwoSideIcons: {\n item->setTitle(index.data().toString());\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->sideBottomImageWidget()->setImage(defaultImage);\n break; \n }\n default:\n break;\n };\n\n }\n\nprivate:\n MDetailedListItem::ItemStyle itemStyle;\n QImage defaultImage;\n};\n\nclass AdvancedListItemCreator : public MAbstractCellCreator<MAdvancedListItem>\n{\npublic:\n AdvancedListItemCreator(MAdvancedListItem::ItemStyle style)\n : itemStyle(style),\n defaultImage(Utils::imagesDir() + \"DefaultAvatar.png\")\n {\n }\n\n MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {\n Q_UNUSED(index);\n MAdvancedListItem *cell = dynamic_cast<MAdvancedListItem*>(recycler.take(MAdvancedListItem::staticMetaObject.className()));\n\n if (cell == NULL) {\n cell = new MAdvancedListItem(itemStyle);\n if (MApplication::instance()->objectName() == \"widgetsgallery\") {\n cell->setStyleName(\"CommonAdvancedListItem\");\n } else {\n cell->setStyleName(\"CommonAdvancedListItemInverted\");\n }\n cell->setLayoutPosition(M::CenterPosition);\n }\n updateCell(index, cell);\n\n return cell;\n }\n\n void updateCell(const QModelIndex &index, MWidget *cell) const {\n MAdvancedListItem *item = dynamic_cast<MAdvancedListItem*>(cell);\n if (!item)\n return;\n\n switch (itemStyle) {\n case MAdvancedListItem::IconWithTitleProgressIndicatorAndTwoSideIcons: {\n item->setTitle(index.data().toString());\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->sideBottomImageWidget()->setImage(defaultImage);\n item->progressIndicator()->setValue(55);\n break;\n }\n case MAdvancedListItem::IconWithTitleProgressIndicatorAndTopSideIcon: {\n item->setTitle(index.data().toString());\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->progressIndicator()->setUnknownDuration(true);\n break;\n }\n default:\n break;\n };\n\n }\n\nprivate:\n MAdvancedListItem::ItemStyle itemStyle;\n QImage defaultImage;\n};\n\n\n\nclass ContentItemsPageModel : public QAbstractItemModel {\npublic:\n ContentItemsPageModel(QObject *parent, const QString &title)\n : QAbstractItemModel(parent),\n headerTitle(title)\n {\n }\n\n QModelIndex parent(const QModelIndex &child) const {\n Q_UNUSED(child);\n\n if (child.internalId() == 0)\n return index(0, 0);\n\n return QModelIndex();\n }\n\n QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const {\n if (parent.isValid())\n return createIndex(row, column, 0);\n else\n return createIndex(row, column, 1);\n }\n\n int rowCount(const QModelIndex &parent) const {\n if (parent.isValid())\n return 2;\n\n return 1;\n }\n\n int columnCount(const QModelIndex &parent) const {\n Q_UNUSED(parent);\n\n return 1;\n }\n\n QVariant data(const QModelIndex &index, int role) const {\n if (role == Qt::DisplayRole) {\n if (!index.parent().isValid())\n return QVariant::fromValue(headerTitle);\n else\n return QVariant::fromValue(QString(headerTitle + \" %1\").arg(index.row()));\n }\n\n return QVariant();\n }\n\nprivate:\n QString headerTitle;\n};\n\nContentItemsPage::ContentItemsPage()\n : TemplatePage(TemplatePage::ListsGridsAndPopups),\n contentItemLists(),\n policy(0)\n{\n}\n\nQString ContentItemsPage::timedemoTitle()\n{\n return \"ContentItems\";\n}\n\nvoid ContentItemsPage::createContent()\n{\n MApplicationPage::createContent();\n\n setStyleName(inv(\"CommonApplicationPage\"));\n\n QGraphicsWidget *panel = centralWidget();\n\n MLayout *layout = new MLayout(panel);\n layout->setContentsMargins(0, 0, 0, 0);\n panel->setLayout(layout);\n policy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n policy->setContentsMargins(0, 0, 0, 0);\n policy->setSpacing(0);\n\n populateLayout();\n\n retranslateUi();\n}\n\nvoid ContentItemsPage::populateLayout()\n{ \/\/Basic list items\n \/\/% \"Single Title\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_single_title\"), new BasicListItemCreator(MBasicListItem::SingleTitle)));\n \/\/% \"Title with Subtitle\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_title_with_subtitle\"), new BasicListItemCreator(MBasicListItem::TitleWithSubtitle)));\n \/\/% \"Icon with Title\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title\"), new BasicListItemCreator(MBasicListItem::IconWithTitle)));\n \/\/% \"Icon with Title and Subtitle\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_and_subtitle\"), new BasicListItemCreator(MBasicListItem::IconWithTitleAndSubtitle)));\n \n \/\/Detailed list items\n \/\/% \"Icon with Title Subtitle and Two Side Icons\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_subtitle_and_two_side_icons\"),\n new DetailedListItemCreator(MDetailedListItem::IconTitleSubtitleAndTwoSideIcons)));\n \/\/% \"Icon with Title Subtitle and Side Icon with Label\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_subtitle_and_side_icon_with_label\"),\n new DetailedListItemCreator(MDetailedListItem::IconTitleSubtitleAndSideIconWithLabel)));\n \/\/% \"Thumbnail with Title Subtitle and Two Side Icons\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_thumbnail_with_title_subtitle_and_two_side_icons\"),\n new DetailedListItemCreator(MDetailedListItem::ThumbnailTitleSubtitleAndTwoSideIcons)));\n \/\/% \"Thumbnail with Title and Two Side Icons\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_thumbnail_with_title_and_two_side_icons\"),\n new DetailedListItemCreator(MDetailedListItem::ThumbnailTitleAndTwoSideIcons)));\n \n \/\/Advanced list items\n \/\/% \"Icon with Title Progress Indicator and Two Side Icons\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_progress_indicator_and_two_side_icons\"),\n new AdvancedListItemCreator(MAdvancedListItem::IconWithTitleProgressIndicatorAndTwoSideIcons)));\n \/\/% \"Icon with Title Progress Indicator and Top Side Icon\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_progress_indicator_and_top_side_icon\"),\n new AdvancedListItemCreator(MAdvancedListItem::IconWithTitleProgressIndicatorAndTopSideIcon)));\n}\n\nMList *ContentItemsPage::createList(const QString &title, MCellCreator *creator)\n{\n QAbstractItemModel *model = new ContentItemsPageModel(this, title);\n model->setObjectName(\"contentItemsPageModel\");\n\n MList *list = new MList(centralWidget());\n list->setObjectName(\"list\");\n list->setStyleName(inv(\"CommonList\"));\n list->setCellCreator(creator);\n list->setItemModel(model);\n list->setShowGroups(true);\n policy->addItem(list, Qt::AlignCenter);\n\n return list;\n}\n\nvoid ContentItemsPage::retranslateUi()\n{\n \/\/% \"Content Items\"\n setTitle(qtTrId(\"xx_contentitemspage_title\"));\n if (!isContentCreated())\n return;\n \/\/ this file has no other calls to qtTrId() except for the title\n \/\/ at the moment. If more qtTrId() calls are needed they should\n \/\/ be added here.\n}\n<commit_msg>Changes: Add a sample to widgetsgallery how the label preferred line count infulences on list item height.<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\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 \"contentitemspage.h\"\n#include \"utils.h\"\n\n#include <MApplication>\n#include <MAbstractCellCreator>\n#include <MImageWidget>\n#include <MLayout>\n#include <MLinearLayoutPolicy>\n#include <MList>\n#include <MListItem>\n#include <MProgressIndicator>\n#include <MLabel>\n\n#include <MBasicListItem>\n#include <MDetailedListItem>\n#include <MAdvancedListItem>\n\n#include <QGraphicsGridLayout>\n\nnamespace {\n\n class CustomListItem : public MListItem\n {\n public:\n CustomListItem(QGraphicsItem *parent = 0) : MListItem(parent) {\n setObjectName(\"CommonLargePanel\");\n\n \/\/ Layout\n layoutGrid = new QGraphicsGridLayout(this);\n\n \/\/ Title\n titleLabel = new MLabel(this);\n titleLabel->setTextElide(true);\n titleLabel->setObjectName(\"CommonTitle\");\n\n \/\/ Subtitle\n subtitleLabel = new MLabel(this);\n subtitleLabel->setTextElide(true);\n subtitleLabel->setWordWrap(true);\n subtitleLabel->setPreferredLineCount(3);\n subtitleLabel->setObjectName(\"CommonSubTitle\");\n\n \/\/ Icon\n image = new MImageWidget(this);\n image->setObjectName(\"CommonMainIcon\");\n\n \/\/ Construct layout\n layoutGrid->addItem(image, 0, 0, 2, 1);\n layoutGrid->addItem(titleLabel, 0, 1);\n layoutGrid->addItem(subtitleLabel, 1, 1);\n }\n\n void setTitle(const QString &title)\n {\n titleLabel->setText(title);\n }\n\n void setSubtitle(const QString &subtitle)\n {\n subtitleLabel->setText(subtitle);\n }\n\n void setImage(const QImage &picture)\n {\n image->setImage(picture);\n }\n\n private:\n MLabel *titleLabel;\n MLabel *subtitleLabel;\n MImageWidget *image;\n QGraphicsGridLayout *layoutGrid;\n };\n\n class CustomListItemCreator : public MAbstractCellCreator<CustomListItem>\n {\n public:\n CustomListItemCreator()\n : defaultImage(Utils::imagesDir() + \"DefaultAvatar.png\")\n {\n veryLongSubtitle = \"This is multi-line elided text.\";\n\n for (int i = 10; i > 0; i--) {\n veryLongSubtitle += \" \" + veryLongSubtitle;\n }\n }\n\n MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {\n Q_UNUSED(index);\n CustomListItem *cell = dynamic_cast<CustomListItem*>(recycler.take(CustomListItem::staticMetaObject.className()));\n\n if (cell == NULL) {\n cell = new CustomListItem;\n if (MApplication::instance()->objectName() == \"widgetsgallery\") {\n cell->setStyleName(\"CommonBasicListItem\");\n } else {\n cell->setStyleName(\"CommonBasicListItemInverted\");\n }\n cell->setLayoutPosition(M::CenterPosition);\n }\n updateCell(index, cell);\n\n return cell;\n }\n\n void updateCell(const QModelIndex &index, MWidget *cell) const {\n CustomListItem *item = dynamic_cast<CustomListItem*>(cell);\n if (!item)\n return;\n\n item->setTitle(index.data().toString());\n item->setSubtitle(veryLongSubtitle);\n item->setImage(defaultImage);\n }\n\n private:\n QString veryLongSubtitle;\n QImage defaultImage;\n };\n\n class BasicListItemCreator : public MAbstractCellCreator<MBasicListItem>\n {\n public:\n BasicListItemCreator(MBasicListItem::ItemStyle style)\n : itemStyle(style),\n defaultImage(Utils::imagesDir() + \"DefaultAvatar.png\")\n {\n }\n\n MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {\n Q_UNUSED(index);\n MBasicListItem *cell = dynamic_cast<MBasicListItem*>(recycler.take(MBasicListItem::staticMetaObject.className()));\n\n if (cell == NULL) {\n cell = new MBasicListItem(itemStyle);\n if (MApplication::instance()->objectName() == \"widgetsgallery\") {\n cell->setStyleName(\"CommonBasicListItem\");\n } else {\n cell->setStyleName(\"CommonBasicListItemInverted\");\n }\n cell->setLayoutPosition(M::CenterPosition);\n }\n updateCell(index, cell);\n\n return cell;\n }\n\n void updateCell(const QModelIndex &index, MWidget *cell) const {\n MBasicListItem *item = dynamic_cast<MBasicListItem*>(cell);\n if (!item)\n return;\n\n switch (itemStyle) {\n case MBasicListItem::SingleTitle: {\n item->setTitle(index.data().toString());\n break;\n }\n case MBasicListItem::TitleWithSubtitle: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n break;\n }\n case MBasicListItem::IconWithTitle: {\n item->setTitle(index.data().toString());\n item->imageWidget()->setImage(defaultImage);\n break;\n }\n case MBasicListItem::IconWithTitleAndSubtitle: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n item->imageWidget()->setImage(defaultImage);\n break;\n }\n default:\n break;\n };\n\n }\n\n private:\n MBasicListItem::ItemStyle itemStyle;\n QImage defaultImage;\n };\n\n class DetailedListItemCreator : public MAbstractCellCreator<MDetailedListItem>\n {\n public:\n DetailedListItemCreator(MDetailedListItem::ItemStyle style)\n : itemStyle(style),\n defaultImage(Utils::imagesDir() + \"DefaultAvatar.png\")\n {\n }\n\n MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {\n Q_UNUSED(index);\n MDetailedListItem *cell = dynamic_cast<MDetailedListItem*>(recycler.take(MDetailedListItem::staticMetaObject.className()));\n\n if (cell == NULL) {\n cell = new MDetailedListItem(itemStyle);\n if (MApplication::instance()->objectName() == \"widgetsgallery\") {\n cell->setStyleName(\"CommonDetailedListItem\");\n } else {\n cell->setStyleName(\"CommonDetailedListItemInverted\");\n }\n cell->setLayoutPosition(M::CenterPosition);\n }\n updateCell(index, cell);\n\n return cell;\n }\n\n void updateCell(const QModelIndex &index, MWidget *cell) const {\n MDetailedListItem *item = dynamic_cast<MDetailedListItem*>(cell);\n if (!item)\n return;\n\n switch (itemStyle) {\n case MDetailedListItem::IconTitleSubtitleAndTwoSideIcons: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->sideBottomImageWidget()->setImage(defaultImage);\n break;\n }\n case MDetailedListItem::IconTitleSubtitleAndSideIconWithLabel: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n \/\/% \"Side\"\n item->setSideBottomTitle(qtTrId(\"xx_wg_contentitemspage_sidetitle\"));\n break;\n }\n case MDetailedListItem::ThumbnailTitleSubtitleAndTwoSideIcons: {\n item->setTitle(index.data().toString());\n \/\/% \"Subtitle\"\n item->setSubtitle(qtTrId(\"xx_wg_contentitemspage_subtitle\"));\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->sideBottomImageWidget()->setImage(defaultImage);\n break;\n }\n case MDetailedListItem::ThumbnailTitleAndTwoSideIcons: {\n item->setTitle(index.data().toString());\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->sideBottomImageWidget()->setImage(defaultImage);\n break;\n }\n default:\n break;\n };\n\n }\n\n private:\n MDetailedListItem::ItemStyle itemStyle;\n QImage defaultImage;\n };\n\n class AdvancedListItemCreator : public MAbstractCellCreator<MAdvancedListItem>\n {\n public:\n AdvancedListItemCreator(MAdvancedListItem::ItemStyle style)\n : itemStyle(style),\n defaultImage(Utils::imagesDir() + \"DefaultAvatar.png\")\n {\n }\n\n MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {\n Q_UNUSED(index);\n MAdvancedListItem *cell = dynamic_cast<MAdvancedListItem*>(recycler.take(MAdvancedListItem::staticMetaObject.className()));\n\n if (cell == NULL) {\n cell = new MAdvancedListItem(itemStyle);\n if (MApplication::instance()->objectName() == \"widgetsgallery\") {\n cell->setStyleName(\"CommonAdvancedListItem\");\n } else {\n cell->setStyleName(\"CommonAdvancedListItemInverted\");\n }\n cell->setLayoutPosition(M::CenterPosition);\n }\n updateCell(index, cell);\n\n return cell;\n }\n\n void updateCell(const QModelIndex &index, MWidget *cell) const {\n MAdvancedListItem *item = dynamic_cast<MAdvancedListItem*>(cell);\n if (!item)\n return;\n\n switch (itemStyle) {\n case MAdvancedListItem::IconWithTitleProgressIndicatorAndTwoSideIcons: {\n item->setTitle(index.data().toString());\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->sideBottomImageWidget()->setImage(defaultImage);\n item->progressIndicator()->setValue(55);\n break;\n }\n case MAdvancedListItem::IconWithTitleProgressIndicatorAndTopSideIcon: {\n item->setTitle(index.data().toString());\n item->imageWidget()->setImage(defaultImage);\n item->sideTopImageWidget()->setImage(defaultImage);\n item->progressIndicator()->setUnknownDuration(true);\n break;\n }\n default:\n break;\n };\n\n }\n\n private:\n MAdvancedListItem::ItemStyle itemStyle;\n QImage defaultImage;\n };\n\n}\n\nclass ContentItemsPageModel : public QAbstractItemModel {\npublic:\n ContentItemsPageModel(QObject *parent, const QString &title)\n : QAbstractItemModel(parent),\n headerTitle(title)\n {\n }\n\n QModelIndex parent(const QModelIndex &child) const {\n Q_UNUSED(child);\n\n if (child.internalId() == 0)\n return index(0, 0);\n\n return QModelIndex();\n }\n\n QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const {\n if (parent.isValid())\n return createIndex(row, column, 0);\n else\n return createIndex(row, column, 1);\n }\n\n int rowCount(const QModelIndex &parent) const {\n if (parent.isValid())\n return 2;\n\n return 1;\n }\n\n int columnCount(const QModelIndex &parent) const {\n Q_UNUSED(parent);\n\n return 1;\n }\n\n QVariant data(const QModelIndex &index, int role) const {\n if (role == Qt::DisplayRole) {\n if (!index.parent().isValid())\n return QVariant::fromValue(headerTitle);\n else\n return QVariant::fromValue(QString(headerTitle + \" %1\").arg(index.row()));\n }\n\n return QVariant();\n }\n\nprivate:\n QString headerTitle;\n};\n\nContentItemsPage::ContentItemsPage()\n : TemplatePage(TemplatePage::ListsGridsAndPopups),\n contentItemLists(),\n policy(0)\n{\n}\n\nQString ContentItemsPage::timedemoTitle()\n{\n return \"ContentItems\";\n}\n\nvoid ContentItemsPage::createContent()\n{\n MApplicationPage::createContent();\n\n setStyleName(inv(\"CommonApplicationPage\"));\n\n QGraphicsWidget *panel = centralWidget();\n\n MLayout *layout = new MLayout(panel);\n layout->setContentsMargins(0, 0, 0, 0);\n panel->setLayout(layout);\n policy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n policy->setContentsMargins(0, 0, 0, 0);\n policy->setSpacing(0);\n\n populateLayout();\n\n retranslateUi();\n}\n\nvoid ContentItemsPage::populateLayout()\n{ \/\/Basic list items\n \/\/% \"Single Title\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_single_title\"), new BasicListItemCreator(MBasicListItem::SingleTitle)));\n \/\/% \"Title with Subtitle\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_title_with_subtitle\"), new BasicListItemCreator(MBasicListItem::TitleWithSubtitle)));\n \/\/% \"Icon with Title\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title\"), new BasicListItemCreator(MBasicListItem::IconWithTitle)));\n \/\/% \"Icon with Title and Subtitle\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_and_subtitle\"), new BasicListItemCreator(MBasicListItem::IconWithTitleAndSubtitle)));\n \n \/\/Detailed list items\n \/\/% \"Icon with Title Subtitle and Two Side Icons\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_subtitle_and_two_side_icons\"),\n new DetailedListItemCreator(MDetailedListItem::IconTitleSubtitleAndTwoSideIcons)));\n \/\/% \"Icon with Title Subtitle and Side Icon with Label\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_subtitle_and_side_icon_with_label\"),\n new DetailedListItemCreator(MDetailedListItem::IconTitleSubtitleAndSideIconWithLabel)));\n \/\/% \"Thumbnail with Title Subtitle and Two Side Icons\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_thumbnail_with_title_subtitle_and_two_side_icons\"),\n new DetailedListItemCreator(MDetailedListItem::ThumbnailTitleSubtitleAndTwoSideIcons)));\n \/\/% \"Thumbnail with Title and Two Side Icons\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_thumbnail_with_title_and_two_side_icons\"),\n new DetailedListItemCreator(MDetailedListItem::ThumbnailTitleAndTwoSideIcons)));\n \n \/\/Advanced list items\n \/\/% \"Icon with Title Progress Indicator and Two Side Icons\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_progress_indicator_and_two_side_icons\"),\n new AdvancedListItemCreator(MAdvancedListItem::IconWithTitleProgressIndicatorAndTwoSideIcons)));\n \/\/% \"Icon with Title Progress Indicator and Top Side Icon\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_progress_indicator_and_top_side_icon\"),\n new AdvancedListItemCreator(MAdvancedListItem::IconWithTitleProgressIndicatorAndTopSideIcon)));\n\n \/\/% \"Icon with Title and Multiline Subtitle\"\n contentItemLists.append(createList(qtTrId(\"xx_wg_contentitemspage_icon_with_title_and_multiline_subtitle\"), new CustomListItemCreator));\n}\n\nMList *ContentItemsPage::createList(const QString &title, MCellCreator *creator)\n{\n QAbstractItemModel *model = new ContentItemsPageModel(this, title);\n model->setObjectName(\"contentItemsPageModel\");\n\n MList *list = new MList(centralWidget());\n list->setObjectName(\"list\");\n list->setStyleName(inv(\"CommonList\"));\n list->setCellCreator(creator);\n list->setItemModel(model);\n list->setShowGroups(true);\n policy->addItem(list, Qt::AlignCenter);\n\n return list;\n}\n\nvoid ContentItemsPage::retranslateUi()\n{\n \/\/% \"Content Items\"\n setTitle(qtTrId(\"xx_contentitemspage_title\"));\n if (!isContentCreated())\n return;\n \/\/ this file has no other calls to qtTrId() except for the title\n \/\/ at the moment. If more qtTrId() calls are needed they should\n \/\/ be added here.\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#ifndef __BH_JITK_BLOCK_HPP\n#define __BH_JITK_BLOCK_HPP\n\n#include <set>\n#include <vector>\n#include <iostream>\n#include <boost\/variant\/variant.hpp>\n#include <boost\/variant\/get.hpp>\n\n\n#include <bh_instruction.hpp>\n\nnamespace bohrium {\nnamespace jitk {\n\n\/* Design Overview\n\n A block can represent two things in Bohrium:\n * A for-loop, i.e. a traversal of arrays over an axis\/dimension (class LoopB)\n * A single instruction such as BH_ADD or BH_MULTIPLY (class InstrB)\n\n*\/\n\n\/\/ Forward declaration\nclass Block;\n\n\/\/ We use a shared pointer of an const instruction. The idea is to never change an instruction inplace\n\/\/ instead, create a whole new instruction.\ntypedef std::shared_ptr<const bh_instruction> InstrPtr;\n\n\/\/ Representation of a for-loop, which contains a list of nested loops (_block_list)\nclass LoopB {\npublic:\n \/\/ The rank of this loop block\n int rank;\n \/\/ List of sub-blocks\n std::vector <Block> _block_list;\n \/\/ Size of the loop\n int64_t size;\n \/\/ Sweep instructions within this loop\n std::set<InstrPtr> _sweeps;\n \/\/ New arrays within this loop\n std::set<bh_base *> _news;\n \/\/ Freed arrays within this loop\n std::set<bh_base *> _frees;\n \/\/ Is this loop and all its sub-blocks reshapable\n bool _reshapable = false;\n\n \/\/ Unique id of this block\n int _id;\n\n \/\/ Default Constructor\n LoopB() { static int id_count = 0; _id = id_count++; }\n\n void replaceInstr(InstrPtr subject, const bh_instruction &replacement);\n\n \/\/ Is this block innermost? (not counting instruction blocks)\n bool isInnermost() const;\n\n \/\/ Return all sub-blocks (incl. nested blocks)\n void getAllSubBlocks(std::vector<const LoopB *> &out) const;\n\n \/\/ Return all sub-blocks (excl. nested blocks)\n std::vector<const Block*> getLocalSubBlocks() const;\n\n \/\/ Return all instructions in the block (incl. nested blocks)\n void getAllInstr(std::vector<InstrPtr> &out) const;\n std::vector<InstrPtr> getAllInstr() const;\n\n \/\/ Return instructions in the block (excl. nested blocks)\n void getLocalInstr(std::vector<InstrPtr> &out) const;\n std::vector<InstrPtr> getLocalInstr() const;\n\n \/\/ Return all bases accessed by this block\n std::set<const bh_base*> getAllBases() const {\n std::set<const bh_base*> ret;\n for (InstrPtr instr: getAllInstr()) {\n std::set<const bh_base*> t = instr->get_bases();\n ret.insert(t.begin(), t.end());\n }\n return ret;\n }\n\n \/\/ Return all new arrays in this block (incl. nested blocks)\n void getAllNews(std::set<bh_base*> &out) const;\n std::set<bh_base*> getAllNews() const;\n\n \/\/ Return all freed arrays in this block (incl. nested blocks)\n void getAllFrees(std::set<bh_base*> &out) const;\n std::set<bh_base*> getAllFrees() const;\n\n \/\/ Return all local temporary arrays in this block (excl. nested blocks)\n \/\/ NB: The returned temporary arrays are the arrays that this block should declare\n void getLocalTemps(std::set<bh_base*> &out) const;\n std::set<bh_base*> getLocalTemps() const;\n\n \/\/ Return all temporary arrays in this block (incl. nested blocks)\n void getAllTemps(std::set<bh_base*> &out) const;\n std::set<bh_base*> getAllTemps() const;\n\n \/\/ Returns true when all instructions within the block is system or if the block is empty()\n bool isSystemOnly() const;\n\n \/\/ Validation check of this block\n bool validation() const;\n\n \/\/ Finds the block and instruction that accesses 'base' last. If 'base' is NULL, any data access\n \/\/ is accepted thus the last instruction is returned.\n \/\/ Returns the block and the index of the instruction (or NULL and -1 if not accessed)\n std::pair<LoopB*, int64_t> findLastAccessBy(const bh_base *base);\n\n \/\/ Insert the system instruction 'instr' after the instruction that accesses 'base' last.\n \/\/ If no instruction accesses 'base' we insert it after the last instruction.\n \/\/ NB: Force reshape the instruction to match the instructions accesses 'base' last.\n void insert_system_after(InstrPtr instr, const bh_base *base);\n\n \/\/ Pretty print this block\n std::string pprint(const char *newline=\"\\n\") const;\n\n \/\/ Equality test based on the unique ID\n bool operator==(const LoopB &loop_block) const {\n return this->_id == loop_block._id;\n }\n};\n\n\/\/ Representation of a single instruction\nclass InstrB {\npublic:\n InstrPtr instr;\n int rank;\n};\n\n\/\/ A block can represent a for-loop (LoopB) or an instruction (InstrB)\nclass Block {\nprivate:\n \/\/ This is the variant that contains either a LoopB or a InstrB.\n \/\/ Note, boost::blank is only used to catch programming errors\n boost::variant<boost::blank, LoopB, InstrB> _var;\n\npublic:\n\n \/\/ Default Constructor\n Block() {}\n\n \/\/ Loop Block Constructor\n explicit Block(const LoopB &loop_block) {\n assert(_var.which() == 0);\n _var = loop_block;\n }\n explicit Block(LoopB &&loop_block) {\n assert(_var.which() == 0);\n _var = loop_block;\n }\n\n \/\/ Instruction Block Constructor\n \/\/ Note, the rank is only to make pretty printing easier\n Block(const bh_instruction &instr, int rank) {\n assert(_var.which() == 0);\n InstrB _instr{std::make_shared<bh_instruction>(instr), rank};\n _var = std::move(_instr);\n }\n\n \/\/ Returns true if this block is an instruction block\n bool isInstr() const {\n return _var.which() == 2; \/\/ Notice, the third type in '_var' is 'InstrB'\n }\n\n \/\/ Retrieve the Loop Block\n LoopB &getLoop() {return boost::get<LoopB>(_var);}\n const LoopB &getLoop() const {return boost::get<LoopB>(_var);}\n\n \/\/ Retrieve the instruction within the instruction block\n const InstrPtr getInstr() const {return boost::get<InstrB>(_var).instr;}\n InstrPtr getInstr() {return boost::get<InstrB>(_var).instr;}\n void setInstr(const bh_instruction &instr) {\n assert(_var.which() == 0 or _var.which() == 2);\n boost::get<InstrB>(_var).instr.reset(new bh_instruction(instr));\n }\n\n \/\/ Return the rank of this block\n int rank() const {\n if (isInstr()) {\n return boost::get<InstrB>(_var).rank;\n } else {\n return getLoop().rank;\n }\n }\n\n \/\/ Validation check of this block\n bool validation() const;\n\n \/\/ Return all instructions in the block (incl. nested blocks)\n void getAllInstr(std::vector<InstrPtr> &out) const;\n std::vector<InstrPtr> getAllInstr() const;\n\n \/\/ Return all bases accessed by this block\n std::set<const bh_base*> getAllBases() const {\n std::set<const bh_base*> ret;\n for (InstrPtr instr: getAllInstr()) {\n std::set<const bh_base*> t = instr->get_bases();\n ret.insert(t.begin(), t.end());\n }\n return ret;\n }\n\n \/\/ Returns true when all instructions within this block is system or if the block is empty()\n bool isSystemOnly() const {\n if (isInstr()) {\n return bh_opcode_is_system(getInstr()->opcode);\n }\n for (const Block &b: getLoop()._block_list) {\n if (not b.isSystemOnly()) {\n return false;\n }\n }\n return true;\n }\n\n \/\/ Returns true when all instructions within this block is reshapable\n bool isReshapable() const {\n if (isInstr()) {\n return getInstr()->reshapable();\n } else {\n return getLoop()._reshapable;\n }\n }\n\n \/\/ Determines whether this block must be executed after 'other'\n bool depend_on(const Block &other) const {\n const std::vector<InstrPtr> this_instr_list = getAllInstr();\n const std::vector<InstrPtr> other_instr_list = other.getAllInstr();\n for (const InstrPtr this_instr: this_instr_list) {\n for (const InstrPtr other_instr: other_instr_list) {\n if (*this_instr != *other_instr and\n bh_instr_dependency(this_instr.get(), other_instr.get())) {\n return true;\n }\n }\n }\n return false;\n }\n\n \/\/ Pretty print this block\n std::string pprint(const char *newline=\"\\n\") const;\n};\n\n\/\/ Merge the two loop blocks, 'a' and 'b', in that order.\nLoopB merge(const LoopB &a, const LoopB &b);\n\n\/\/ Create a nested block based on 'instr_list' with the sets of new, free, and temp arrays given.\n\/\/ The dimensions from zero to 'rank-1' are ignored.\n\/\/ The 'size_of_rank_dim' specifies the size of the dimension 'rank'.\nBlock create_nested_block(const std::vector<InstrPtr> &instr_list, int rank, int64_t size_of_rank_dim);\n\n\/\/ Returns the blocks that can be parallelized in 'block' (incl. 'block' and its sub-blocks)\n\/\/ and the total amount of parallelism (in number of possible parallel threads)\nstd::pair<std::vector<const LoopB *>, uint64_t> find_threaded_blocks(const LoopB &block);\n\n\/\/ Merges the two blocks 'a' and 'a' (in that order) if they are fusible.\n\/\/ NB: 'a' or 'b' might be reshaped in order to make the merge legal\n\/\/ Returns the new block and a flag indicating whether the merge was performed\nstd::pair<Block, bool> merge_if_possible(const Block &a, const Block &b);\n\n\/\/Implements pprint of block\nstd::ostream& operator<<(std::ostream& out, const LoopB& b);\n\n\/\/Implements pprint of block\nstd::ostream& operator<<(std::ostream& out, const Block& b);\n\n\/\/Implements pprint of a vector of blocks\nstd::ostream& operator<<(std::ostream& out, const std::vector<Block>& b);\n\n} \/\/ jit\n} \/\/ bohrium\n\n\n#endif\n<commit_msg>jitk: added a missing include<commit_after>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#ifndef __BH_JITK_BLOCK_HPP\n#define __BH_JITK_BLOCK_HPP\n\n#include <set>\n#include <vector>\n#include <iostream>\n#include <memory>\n#include <boost\/variant\/variant.hpp>\n#include <boost\/variant\/get.hpp>\n\n\n#include <bh_instruction.hpp>\n\nnamespace bohrium {\nnamespace jitk {\n\n\/* Design Overview\n\n A block can represent two things in Bohrium:\n * A for-loop, i.e. a traversal of arrays over an axis\/dimension (class LoopB)\n * A single instruction such as BH_ADD or BH_MULTIPLY (class InstrB)\n\n*\/\n\n\/\/ Forward declaration\nclass Block;\n\n\/\/ We use a shared pointer of an const instruction. The idea is to never change an instruction inplace\n\/\/ instead, create a whole new instruction.\ntypedef std::shared_ptr<const bh_instruction> InstrPtr;\n\n\/\/ Representation of a for-loop, which contains a list of nested loops (_block_list)\nclass LoopB {\npublic:\n \/\/ The rank of this loop block\n int rank;\n \/\/ List of sub-blocks\n std::vector <Block> _block_list;\n \/\/ Size of the loop\n int64_t size;\n \/\/ Sweep instructions within this loop\n std::set<InstrPtr> _sweeps;\n \/\/ New arrays within this loop\n std::set<bh_base *> _news;\n \/\/ Freed arrays within this loop\n std::set<bh_base *> _frees;\n \/\/ Is this loop and all its sub-blocks reshapable\n bool _reshapable = false;\n\n \/\/ Unique id of this block\n int _id;\n\n \/\/ Default Constructor\n LoopB() { static int id_count = 0; _id = id_count++; }\n\n void replaceInstr(InstrPtr subject, const bh_instruction &replacement);\n\n \/\/ Is this block innermost? (not counting instruction blocks)\n bool isInnermost() const;\n\n \/\/ Return all sub-blocks (incl. nested blocks)\n void getAllSubBlocks(std::vector<const LoopB *> &out) const;\n\n \/\/ Return all sub-blocks (excl. nested blocks)\n std::vector<const Block*> getLocalSubBlocks() const;\n\n \/\/ Return all instructions in the block (incl. nested blocks)\n void getAllInstr(std::vector<InstrPtr> &out) const;\n std::vector<InstrPtr> getAllInstr() const;\n\n \/\/ Return instructions in the block (excl. nested blocks)\n void getLocalInstr(std::vector<InstrPtr> &out) const;\n std::vector<InstrPtr> getLocalInstr() const;\n\n \/\/ Return all bases accessed by this block\n std::set<const bh_base*> getAllBases() const {\n std::set<const bh_base*> ret;\n for (InstrPtr instr: getAllInstr()) {\n std::set<const bh_base*> t = instr->get_bases();\n ret.insert(t.begin(), t.end());\n }\n return ret;\n }\n\n \/\/ Return all new arrays in this block (incl. nested blocks)\n void getAllNews(std::set<bh_base*> &out) const;\n std::set<bh_base*> getAllNews() const;\n\n \/\/ Return all freed arrays in this block (incl. nested blocks)\n void getAllFrees(std::set<bh_base*> &out) const;\n std::set<bh_base*> getAllFrees() const;\n\n \/\/ Return all local temporary arrays in this block (excl. nested blocks)\n \/\/ NB: The returned temporary arrays are the arrays that this block should declare\n void getLocalTemps(std::set<bh_base*> &out) const;\n std::set<bh_base*> getLocalTemps() const;\n\n \/\/ Return all temporary arrays in this block (incl. nested blocks)\n void getAllTemps(std::set<bh_base*> &out) const;\n std::set<bh_base*> getAllTemps() const;\n\n \/\/ Returns true when all instructions within the block is system or if the block is empty()\n bool isSystemOnly() const;\n\n \/\/ Validation check of this block\n bool validation() const;\n\n \/\/ Finds the block and instruction that accesses 'base' last. If 'base' is NULL, any data access\n \/\/ is accepted thus the last instruction is returned.\n \/\/ Returns the block and the index of the instruction (or NULL and -1 if not accessed)\n std::pair<LoopB*, int64_t> findLastAccessBy(const bh_base *base);\n\n \/\/ Insert the system instruction 'instr' after the instruction that accesses 'base' last.\n \/\/ If no instruction accesses 'base' we insert it after the last instruction.\n \/\/ NB: Force reshape the instruction to match the instructions accesses 'base' last.\n void insert_system_after(InstrPtr instr, const bh_base *base);\n\n \/\/ Pretty print this block\n std::string pprint(const char *newline=\"\\n\") const;\n\n \/\/ Equality test based on the unique ID\n bool operator==(const LoopB &loop_block) const {\n return this->_id == loop_block._id;\n }\n};\n\n\/\/ Representation of a single instruction\nclass InstrB {\npublic:\n InstrPtr instr;\n int rank;\n};\n\n\/\/ A block can represent a for-loop (LoopB) or an instruction (InstrB)\nclass Block {\nprivate:\n \/\/ This is the variant that contains either a LoopB or a InstrB.\n \/\/ Note, boost::blank is only used to catch programming errors\n boost::variant<boost::blank, LoopB, InstrB> _var;\n\npublic:\n\n \/\/ Default Constructor\n Block() {}\n\n \/\/ Loop Block Constructor\n explicit Block(const LoopB &loop_block) {\n assert(_var.which() == 0);\n _var = loop_block;\n }\n explicit Block(LoopB &&loop_block) {\n assert(_var.which() == 0);\n _var = loop_block;\n }\n\n \/\/ Instruction Block Constructor\n \/\/ Note, the rank is only to make pretty printing easier\n Block(const bh_instruction &instr, int rank) {\n assert(_var.which() == 0);\n InstrB _instr{std::make_shared<bh_instruction>(instr), rank};\n _var = std::move(_instr);\n }\n\n \/\/ Returns true if this block is an instruction block\n bool isInstr() const {\n return _var.which() == 2; \/\/ Notice, the third type in '_var' is 'InstrB'\n }\n\n \/\/ Retrieve the Loop Block\n LoopB &getLoop() {return boost::get<LoopB>(_var);}\n const LoopB &getLoop() const {return boost::get<LoopB>(_var);}\n\n \/\/ Retrieve the instruction within the instruction block\n const InstrPtr getInstr() const {return boost::get<InstrB>(_var).instr;}\n InstrPtr getInstr() {return boost::get<InstrB>(_var).instr;}\n void setInstr(const bh_instruction &instr) {\n assert(_var.which() == 0 or _var.which() == 2);\n boost::get<InstrB>(_var).instr.reset(new bh_instruction(instr));\n }\n\n \/\/ Return the rank of this block\n int rank() const {\n if (isInstr()) {\n return boost::get<InstrB>(_var).rank;\n } else {\n return getLoop().rank;\n }\n }\n\n \/\/ Validation check of this block\n bool validation() const;\n\n \/\/ Return all instructions in the block (incl. nested blocks)\n void getAllInstr(std::vector<InstrPtr> &out) const;\n std::vector<InstrPtr> getAllInstr() const;\n\n \/\/ Return all bases accessed by this block\n std::set<const bh_base*> getAllBases() const {\n std::set<const bh_base*> ret;\n for (InstrPtr instr: getAllInstr()) {\n std::set<const bh_base*> t = instr->get_bases();\n ret.insert(t.begin(), t.end());\n }\n return ret;\n }\n\n \/\/ Returns true when all instructions within this block is system or if the block is empty()\n bool isSystemOnly() const {\n if (isInstr()) {\n return bh_opcode_is_system(getInstr()->opcode);\n }\n for (const Block &b: getLoop()._block_list) {\n if (not b.isSystemOnly()) {\n return false;\n }\n }\n return true;\n }\n\n \/\/ Returns true when all instructions within this block is reshapable\n bool isReshapable() const {\n if (isInstr()) {\n return getInstr()->reshapable();\n } else {\n return getLoop()._reshapable;\n }\n }\n\n \/\/ Determines whether this block must be executed after 'other'\n bool depend_on(const Block &other) const {\n const std::vector<InstrPtr> this_instr_list = getAllInstr();\n const std::vector<InstrPtr> other_instr_list = other.getAllInstr();\n for (const InstrPtr this_instr: this_instr_list) {\n for (const InstrPtr other_instr: other_instr_list) {\n if (*this_instr != *other_instr and\n bh_instr_dependency(this_instr.get(), other_instr.get())) {\n return true;\n }\n }\n }\n return false;\n }\n\n \/\/ Pretty print this block\n std::string pprint(const char *newline=\"\\n\") const;\n};\n\n\/\/ Merge the two loop blocks, 'a' and 'b', in that order.\nLoopB merge(const LoopB &a, const LoopB &b);\n\n\/\/ Create a nested block based on 'instr_list' with the sets of new, free, and temp arrays given.\n\/\/ The dimensions from zero to 'rank-1' are ignored.\n\/\/ The 'size_of_rank_dim' specifies the size of the dimension 'rank'.\nBlock create_nested_block(const std::vector<InstrPtr> &instr_list, int rank, int64_t size_of_rank_dim);\n\n\/\/ Returns the blocks that can be parallelized in 'block' (incl. 'block' and its sub-blocks)\n\/\/ and the total amount of parallelism (in number of possible parallel threads)\nstd::pair<std::vector<const LoopB *>, uint64_t> find_threaded_blocks(const LoopB &block);\n\n\/\/ Merges the two blocks 'a' and 'a' (in that order) if they are fusible.\n\/\/ NB: 'a' or 'b' might be reshaped in order to make the merge legal\n\/\/ Returns the new block and a flag indicating whether the merge was performed\nstd::pair<Block, bool> merge_if_possible(const Block &a, const Block &b);\n\n\/\/Implements pprint of block\nstd::ostream& operator<<(std::ostream& out, const LoopB& b);\n\n\/\/Implements pprint of block\nstd::ostream& operator<<(std::ostream& out, const Block& b);\n\n\/\/Implements pprint of a vector of blocks\nstd::ostream& operator<<(std::ostream& out, const std::vector<Block>& b);\n\n} \/\/ jit\n} \/\/ bohrium\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file tests.cpp\n * \\author Matt Hammerly\n * \\brief This file contains int main() which will run tests as they're written\n *\/\n#include <iostream>\n#include <cassert>\n#include \"Library.h\"\n#include \"Track.h\"\n#include \"Playlist.h\"\n#include \"tests.h\"\n\nusing std::cout; using std::endl;\n\n\/\/\/ File location of one track\nconst std::string track1 = \"\/home\/matt\/hdd\/dev\/cpp\/musicmanager\/test_data\/Gregory And The Hawk\/The Boats & Birds EP\/01 Boats & Birds.mp3\";\n\n\/\/\/ File location of another track\nconst std::string track2 = \"\/home\/matt\/hdd\/dev\/cpp\/musicmanager\/test_data\/Beirut\/The Flying Club Cup\/05 la banlieue.m4a\";\n\n\/\/\/ Title of one playlist\nconst std::string playlist1 = \"test1\";\n\n\/**\n * \\brief Main entry point of program, where tests will be run\n *\/\nint main()\n{\n\n Test_Library_Constructor();\n\n Test_Library_PrepareDatabase();\n\n Test_Library_DestroyDatabase();\n \n Test_Library_AddTrack();\n\n Test_Library_AddPlaylist();\n\n Test_Library_RemoveTrack();\n\n Test_Library_RemovePlaylist();\n\n Test_Playlist_Constructors();\n\n Test_Playlist_AppendTrack();\n\n \/\/ So I can poke around manually after running tests\n \/\/CLibrary library;\n \/\/library.PrepareDatabase();\n\n return 0;\n}\n\n\/**\n * \\brief I mean, there's constructor logic, let's test it.\n *\/\nvoid Test_Library_Constructor()\n{\n cout << \"Test_Library_Constructor... \";\n CLibrary library;\n assert(library.GetStatus() == CONNECTION_OK);\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure all expected database objects are created\n *\/\nvoid Test_Library_PrepareDatabase()\n{\n cout << \"Test_Library_PrepareDatabase... \";\n CLibrary library;\n\n library.PrepareDatabase();\n\n \/\/ We need the unwrapped connection object for arbitrary queries to test\n PGconn *conn = library.GetConnection();\n\n \/\/ Check to see if tables exist\n \/\/ Three rows should be returned; one for tracks, one for playlists, one for tracks_playlists\n PGresult* res_tables = PQexec(conn, \"SELECT table_name FROM information_schema.tables WHERE table_name IN ('tracks', 'playlists', 'tracks_playlists');\");\n assert(PQntuples(res_tables) == 3);\n PQclear(res_tables);\n\n \/\/ Check to see if the tracks_playlists_insert_func procedure exists\n PGresult* res_func = PQexec(conn, \"SELECT routine_name FROM information_schema.routines WHERE routine_name = 'tracks_playlists_insert_func';\");\n assert(PQntuples(res_func) == 1);\n PQclear(res_func);\n\n \/\/ Check to see if the tracks_playlists_insert_trg trigger exists\n \/\/ Two records should be returned; one for ON INSERT, one for ON DELETE\n PGresult* res_trg = PQexec(conn, \"SELECT trigger_name FROM information_schema.triggers WHERE trigger_name = 'tracks_playlists_insert_trg';\");\n assert(PQntuples(res_trg) == 2);\n PQclear(res_trg);\n\n \/\/ Check to see if the default library playlist was properly created\n PGresult *res_playlist = PQexec(conn, \"SELECT id, title, length FROM playlists WHERE id=1\");\n assert(PQntuples(res_playlist) == 1);\n PQclear(res_playlist);\n\n \/\/ clean up, I guess\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure database objects are deleted when asked\n *\/\nvoid Test_Library_DestroyDatabase()\n{\n cout << \"Test_Library_DestroyDatabase... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n library.DestroyDatabase();\n\n \/\/ We need the unwrapped connection object for arbitrary queries to test\n PGconn *conn = library.GetConnection();\n\n \/\/ Check to see if tables exist\n PGresult* res_tables = PQexec(conn, \"SELECT table_name FROM information_schema.tables WHERE table_name IN ('tracks', 'playlists', 'tracks_playlists');\");\n assert(PQntuples(res_tables) == 0);\n PQclear(res_tables);\n\n \/\/ Check to see if the tracks_playlists_insert_func procedure exists\n PGresult* res_func = PQexec(conn, \"SELECT routine_name FROM information_schema.routines WHERE routine_name = 'tracks_playlists_insert_func';\");\n assert(PQntuples(res_func) == 0);\n PQclear(res_func);\n\n \/\/ Check to see if the tracks_playlists_insert_trg trigger exists\n PGresult* res_trg = PQexec(conn, \"SELECT trigger_name FROM information_schema.triggers WHERE trigger_name = 'tracks_playlists_insert_trg';\");\n assert(PQntuples(res_trg) == 0);\n PQclear(res_trg);\n\n\n cout << \"OK\" << endl;\n\n}\n\n\/**\n * \\brief Ensure tracks can be added properly\n *\n * Maybe later I'll figure out how to verify that the date is correct\n *\/\nvoid Test_Library_AddTrack()\n{\n cout << \"Test_Library_AddTrack... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n std::string id = library.AddTrack(track1);\n\n \/\/ We need the unwrapped connection object for arbitrary queries to test\n PGconn* conn = library.GetConnection();\n\n std::string query = \"SELECT * FROM tracks WHERE id=\";\n\n \/\/ id should never not be a numeric string but safety first\n char escaped_id[30];\n PQescapeStringConn(conn, escaped_id, id.c_str(), 30, 0);\n query.append(escaped_id);\n\n PGresult* res = PQexec(conn, query.c_str());\n\n \/\/ Is there actually a row inserted with our id?\n std::string new_id(PQgetvalue(res, 0, 0));\n assert(new_id == id);\n\n \/\/ Is it the same one (same filepath) that we entered?\n std::string filepath(PQgetvalue(res, 0, 1));\n assert(filepath == track1);\n\n PQclear(res);\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure playlists can be added properly\n *\/\nvoid Test_Library_AddPlaylist()\n{\n cout << \"Test_Library_AddPlaylist... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n std::string id = library.AddPlaylist(playlist1);\n \n \/\/ We need the unwrapped connection object for arbitrary queries to test\n PGconn *conn = library.GetConnection();\n\n std::string query = \"SELECT * FROM playlists WHERE id=\";\n\n \/\/ id should never not be a numeric string but safety first\n char escaped_id[30];\n PQescapeStringConn(conn, escaped_id, id.c_str(), 30, 0);\n query.append(escaped_id);\n\n PGresult *res = PQexec(conn, query.c_str());\n\n \/\/ Is there actually a row inserted with our id?\n std::string new_id(PQgetvalue(res, 0, 0));\n assert(new_id == id);\n\n \/\/ Is it the same one (same title) that we entered?\n std::string title(PQgetvalue(res, 0, 1));\n assert(title == playlist1);\n\n PQclear(res);\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure tracks are removed from the database properly\n * This includes removal from all playlists they have been added to\n *\/\nvoid Test_Library_RemoveTrack()\n{\n cout << \"Test_Library_RemoveTrack... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n std::string track1_id = library.AddTrack(track1);\n std::string track2_id = library.AddTrack(track2);\n\n std::string playlist_id = library.AddPlaylist(\"test\");\n CPlaylist playlist(&library, playlist_id);\n playlist.AppendTrack(track1_id);\n playlist.AppendTrack(track2_id);\n\n PGconn *conn = library.GetConnection();\n\n std::string query = \"SELECT * FROM tracks_playlists WHERE track_id = \";\n char escaped_track1_id[30];\n char escaped_track2_id[30];\n PQescapeStringConn(conn, escaped_track1_id, track1_id.c_str(), 30, 0);\n PQescapeStringConn(conn, escaped_track2_id, track2_id.c_str(), 30, 0);\n\n std::string query1 = query + escaped_track1_id;\n std::string query2 = query + escaped_track2_id;\n PGresult *res1 = PQexec(conn, query1.c_str());\n PGresult *res2 = PQexec(conn, query2.c_str());\n\n assert(PQntuples(res1) == 2);\n assert(PQntuples(res2) == 2);\n\n PQclear(res1);\n PQclear(res2);\n\n library.RemoveTrack(track1_id);\n library.RemoveTrack(track2_id);\n\n std::string query3 = \"SELECT * FROM tracks WHERE id = \";\n query3.append(escaped_track1_id);\n std::string query4 = \"SELECT * FROM tracks WHERE id = \";\n query3.append(escaped_track2_id);\n PGresult *res3 = PQexec(conn, query3.c_str());\n PGresult *res4 = PQexec(conn, query4.c_str());\n\n res1 = PQexec(conn, query1.c_str());\n res2 = PQexec(conn, query2.c_str());\n\n assert(PQntuples(res1) == 0);\n assert(PQntuples(res2) == 0);\n assert(PQntuples(res3) == 0);\n assert(PQntuples(res4) == 0);\n\n PQclear(res1);\n PQclear(res2);\n PQclear(res3);\n PQclear(res4);\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\nvoid Test_Library_RemovePlaylist()\n{\n cout << \"Test_Library_RemovePlaylist... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n std::string track1_id = library.AddTrack(track1);\n std::string track2_id = library.AddTrack(track2);\n\n std::string playlist_id = library.AddPlaylist(\"test\");\n CPlaylist playlist(&library, playlist_id);\n playlist.AppendTrack(track1_id);\n playlist.AppendTrack(track2_id);\n\n PGconn *conn = library.GetConnection();\n\n std::string query = \"SELECT * FROM tracks_playlists WHERE playlist_id = \";\n char escaped_playlist_id[30];\n PQescapeStringConn(conn, escaped_playlist_id, playlist_id.c_str(), 30, 0);\n\n query.append(escaped_playlist_id);\n PGresult *res = PQexec(conn, query.c_str());\n\n assert(PQntuples(res) == 2);\n\n PQclear(res);\n\n library.RemovePlaylist(playlist_id);\n\n res = PQexec(conn, query.c_str());\n\n assert(PQntuples(res) == 0);\n\n PQclear(res);\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure playlist objects are constructed properly\n *\n * Note: This isn't done. Verify that non-empty playlists are properly\n * populated with Track objects when the Track class is implemented\n *\/\nvoid Test_Playlist_Constructors()\n{\n cout << \"Test_Playlist_Constructors... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n \/\/ Should create an empty playlist\n CPlaylist playlist(&library);\n assert(playlist.GetId() == \"temp\");\n assert(playlist.GetTitle() == \"working playlist\");\n assert(playlist.GetLength() == \"0\");\n assert(playlist.GetLibrary() == &library);\n\n \/\/ Should create an object for the default playlist in db\n CPlaylist playlist2(&library, \"1\");\n assert(playlist2.GetId() == \"1\");\n assert(playlist2.GetTitle() == \"library\");\n assert(playlist2.GetLength() == \"0\");\n assert(playlist2.GetLibrary() == &library);\n \n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure tracks can be properly appended to playlists\n *\n * Note: This isn't done. Verify that Track objects are properly appended\n * to their containers when the Track Class is implemented\n *\/\nvoid Test_Playlist_AppendTrack()\n{\n cout << \"Test_Playlist_AppendTrack... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n \/\/ Adding tracks that can be added to playlists\n std::string track1_id = library.AddTrack(track1);\n std::string track2_id = library.AddTrack(track2);\n\n CPlaylist db_playlist(&library, \"1\"); \/\/ a playlist from the database\n CPlaylist temp_playlist(&library); \/\/ a temp playlist not in the database\n\n std::string association1 = db_playlist.AppendTrack(track1_id);\n std::string association2 = db_playlist.AppendTrack(track2_id);\n\n std::string association3 = temp_playlist.AppendTrack(track1_id);\n std::string association4 = temp_playlist.AppendTrack(track2_id);\n\n assert(association3 == \"temp\");\n assert(association4 == \"temp\");\n\n \/\/ Insert logic to make sure Track objects were appropriately added to the container\n \/\/ for both playlists\n\n \/\/ Verify that the proper database records were created\n if (db_playlist.GetId() != \"temp\")\n {\n PGconn *conn = library.GetConnection();\n\n std::string query = \"SELECT id, playlist_id, track_id, position FROM tracks_playlists WHERE playlist_id = \";\n\n char escaped_playlist_id[30];\n PQescapeStringConn(conn, escaped_playlist_id, db_playlist.GetId().c_str(), 30, 0);\n\n query.append(escaped_playlist_id);\n\n PGresult *res = PQexec(conn, query.c_str());\n\n \/\/ 0 and 1 should be auto-created when tracks are added\n \/\/ 2 and 3 are the new records we just added\n std::string association1_id(PQgetvalue(res, 2, 0));\n std::string association1_playlist_id(PQgetvalue(res, 2, 1));\n std::string association1_track_id(PQgetvalue(res, 2, 2));\n std::string association1_position(PQgetvalue(res, 2, 3));\n std::string association2_id(PQgetvalue(res, 3, 0));\n std::string association2_playlist_id(PQgetvalue(res, 3, 1));\n std::string association2_track_id(PQgetvalue(res, 3, 2));\n std::string association2_position(PQgetvalue(res, 3, 3));\n\n assert(association1 == association1_id);\n assert(db_playlist.GetId() == association1_playlist_id);\n assert(track1_id == association1_track_id);\n assert(\"3\" == association1_position);\n assert(association2 == association2_id);\n assert(db_playlist.GetId() == association2_playlist_id);\n assert(track2_id == association2_track_id);\n assert(\"4\" == association2_position);\n \n PQclear(res);\n }\n else\n {\n assert(association1 == \"temp\");\n assert(association2 == \"temp\");\n }\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n<commit_msg>added a section to the library addtrack test<commit_after>\/**\n * \\file tests.cpp\n * \\author Matt Hammerly\n * \\brief This file contains int main() which will run tests as they're written\n *\/\n#include <iostream>\n#include <cassert>\n#include \"Library.h\"\n#include \"Track.h\"\n#include \"Playlist.h\"\n#include \"tests.h\"\n\nusing std::cout; using std::endl;\n\n\/\/\/ File location of one track\nconst std::string track1 = \"\/home\/matt\/hdd\/dev\/cpp\/musicmanager\/test_data\/Gregory And The Hawk\/The Boats & Birds EP\/01 Boats & Birds.mp3\";\n\n\/\/\/ File location of another track\nconst std::string track2 = \"\/home\/matt\/hdd\/dev\/cpp\/musicmanager\/test_data\/Beirut\/The Flying Club Cup\/05 la banlieue.m4a\";\n\n\/\/\/ Title of one playlist\nconst std::string playlist1 = \"test1\";\n\n\/**\n * \\brief Main entry point of program, where tests will be run\n *\/\nint main()\n{\n\n Test_Library_Constructor();\n\n Test_Library_PrepareDatabase();\n\n Test_Library_DestroyDatabase();\n \n Test_Library_AddTrack();\n\n Test_Library_AddPlaylist();\n\n Test_Library_RemoveTrack();\n\n Test_Library_RemovePlaylist();\n\n Test_Playlist_Constructors();\n\n Test_Playlist_AppendTrack();\n\n \/\/ So I can poke around manually after running tests\n \/\/CLibrary library;\n \/\/library.PrepareDatabase();\n\n return 0;\n}\n\n\/**\n * \\brief I mean, there's constructor logic, let's test it.\n *\/\nvoid Test_Library_Constructor()\n{\n cout << \"Test_Library_Constructor... \";\n CLibrary library;\n assert(library.GetStatus() == CONNECTION_OK);\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure all expected database objects are created\n *\/\nvoid Test_Library_PrepareDatabase()\n{\n cout << \"Test_Library_PrepareDatabase... \";\n CLibrary library;\n\n library.PrepareDatabase();\n\n \/\/ We need the unwrapped connection object for arbitrary queries to test\n PGconn *conn = library.GetConnection();\n\n \/\/ Check to see if tables exist\n \/\/ Three rows should be returned; one for tracks, one for playlists, one for tracks_playlists\n PGresult* res_tables = PQexec(conn, \"SELECT table_name FROM information_schema.tables WHERE table_name IN ('tracks', 'playlists', 'tracks_playlists');\");\n assert(PQntuples(res_tables) == 3);\n PQclear(res_tables);\n\n \/\/ Check to see if the tracks_playlists_insert_func procedure exists\n PGresult* res_func = PQexec(conn, \"SELECT routine_name FROM information_schema.routines WHERE routine_name = 'tracks_playlists_insert_func';\");\n assert(PQntuples(res_func) == 1);\n PQclear(res_func);\n\n \/\/ Check to see if the tracks_playlists_insert_trg trigger exists\n \/\/ Two records should be returned; one for ON INSERT, one for ON DELETE\n PGresult* res_trg = PQexec(conn, \"SELECT trigger_name FROM information_schema.triggers WHERE trigger_name = 'tracks_playlists_insert_trg';\");\n assert(PQntuples(res_trg) == 2);\n PQclear(res_trg);\n\n \/\/ Check to see if the default library playlist was properly created\n PGresult *res_playlist = PQexec(conn, \"SELECT id, title, length FROM playlists WHERE id=1\");\n assert(PQntuples(res_playlist) == 1);\n PQclear(res_playlist);\n\n \/\/ clean up, I guess\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure database objects are deleted when asked\n *\/\nvoid Test_Library_DestroyDatabase()\n{\n cout << \"Test_Library_DestroyDatabase... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n library.DestroyDatabase();\n\n \/\/ We need the unwrapped connection object for arbitrary queries to test\n PGconn *conn = library.GetConnection();\n\n \/\/ Check to see if tables exist\n PGresult* res_tables = PQexec(conn, \"SELECT table_name FROM information_schema.tables WHERE table_name IN ('tracks', 'playlists', 'tracks_playlists');\");\n assert(PQntuples(res_tables) == 0);\n PQclear(res_tables);\n\n \/\/ Check to see if the tracks_playlists_insert_func procedure exists\n PGresult* res_func = PQexec(conn, \"SELECT routine_name FROM information_schema.routines WHERE routine_name = 'tracks_playlists_insert_func';\");\n assert(PQntuples(res_func) == 0);\n PQclear(res_func);\n\n \/\/ Check to see if the tracks_playlists_insert_trg trigger exists\n PGresult* res_trg = PQexec(conn, \"SELECT trigger_name FROM information_schema.triggers WHERE trigger_name = 'tracks_playlists_insert_trg';\");\n assert(PQntuples(res_trg) == 0);\n PQclear(res_trg);\n\n\n cout << \"OK\" << endl;\n\n}\n\n\/**\n * \\brief Ensure tracks can be added properly\n *\n * Maybe later I'll figure out how to verify that the date is correct\n *\/\nvoid Test_Library_AddTrack()\n{\n cout << \"Test_Library_AddTrack... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n std::string id = library.AddTrack(track1);\n\n \/\/ We need the unwrapped connection object for arbitrary queries to test\n PGconn* conn = library.GetConnection();\n\n std::string query = \"SELECT * FROM tracks WHERE id=\";\n\n \/\/ id should never not be a numeric string but safety first\n char escaped_id[30];\n PQescapeStringConn(conn, escaped_id, id.c_str(), 30, 0);\n query.append(escaped_id);\n\n PGresult* res = PQexec(conn, query.c_str());\n\n \/\/ Is there actually a row inserted with our id?\n std::string new_id(PQgetvalue(res, 0, 0));\n assert(new_id == id);\n\n \/\/ Is it the same one (same filepath) that we entered?\n std::string filepath(PQgetvalue(res, 0, 1));\n assert(filepath == track1);\n\n PQclear(res);\n\n std::string query2 = \"SELECT * FROM tracks_playlists WHERE track_id = \" + id;\n res = PQexec(conn, query2.c_str());\n assert(PQntuples(res) == 1);\n\n PQclear(res);\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure playlists can be added properly\n *\/\nvoid Test_Library_AddPlaylist()\n{\n cout << \"Test_Library_AddPlaylist... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n std::string id = library.AddPlaylist(playlist1);\n \n \/\/ We need the unwrapped connection object for arbitrary queries to test\n PGconn *conn = library.GetConnection();\n\n std::string query = \"SELECT * FROM playlists WHERE id=\";\n\n \/\/ id should never not be a numeric string but safety first\n char escaped_id[30];\n PQescapeStringConn(conn, escaped_id, id.c_str(), 30, 0);\n query.append(escaped_id);\n\n PGresult *res = PQexec(conn, query.c_str());\n\n \/\/ Is there actually a row inserted with our id?\n std::string new_id(PQgetvalue(res, 0, 0));\n assert(new_id == id);\n\n \/\/ Is it the same one (same title) that we entered?\n std::string title(PQgetvalue(res, 0, 1));\n assert(title == playlist1);\n\n PQclear(res);\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure tracks are removed from the database properly\n * This includes removal from all playlists they have been added to\n *\/\nvoid Test_Library_RemoveTrack()\n{\n cout << \"Test_Library_RemoveTrack... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n std::string track1_id = library.AddTrack(track1);\n std::string track2_id = library.AddTrack(track2);\n\n std::string playlist_id = library.AddPlaylist(\"test\");\n CPlaylist playlist(&library, playlist_id);\n playlist.AppendTrack(track1_id);\n playlist.AppendTrack(track2_id);\n\n PGconn *conn = library.GetConnection();\n\n std::string query = \"SELECT * FROM tracks_playlists WHERE track_id = \";\n char escaped_track1_id[30];\n char escaped_track2_id[30];\n PQescapeStringConn(conn, escaped_track1_id, track1_id.c_str(), 30, 0);\n PQescapeStringConn(conn, escaped_track2_id, track2_id.c_str(), 30, 0);\n\n std::string query1 = query + escaped_track1_id;\n std::string query2 = query + escaped_track2_id;\n PGresult *res1 = PQexec(conn, query1.c_str());\n PGresult *res2 = PQexec(conn, query2.c_str());\n\n assert(PQntuples(res1) == 2);\n assert(PQntuples(res2) == 2);\n\n PQclear(res1);\n PQclear(res2);\n\n library.RemoveTrack(track1_id);\n library.RemoveTrack(track2_id);\n\n std::string query3 = \"SELECT * FROM tracks WHERE id = \";\n query3.append(escaped_track1_id);\n std::string query4 = \"SELECT * FROM tracks WHERE id = \";\n query3.append(escaped_track2_id);\n PGresult *res3 = PQexec(conn, query3.c_str());\n PGresult *res4 = PQexec(conn, query4.c_str());\n\n res1 = PQexec(conn, query1.c_str());\n res2 = PQexec(conn, query2.c_str());\n\n assert(PQntuples(res1) == 0);\n assert(PQntuples(res2) == 0);\n assert(PQntuples(res3) == 0);\n assert(PQntuples(res4) == 0);\n\n PQclear(res1);\n PQclear(res2);\n PQclear(res3);\n PQclear(res4);\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\nvoid Test_Library_RemovePlaylist()\n{\n cout << \"Test_Library_RemovePlaylist... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n std::string track1_id = library.AddTrack(track1);\n std::string track2_id = library.AddTrack(track2);\n\n std::string playlist_id = library.AddPlaylist(\"test\");\n CPlaylist playlist(&library, playlist_id);\n playlist.AppendTrack(track1_id);\n playlist.AppendTrack(track2_id);\n\n PGconn *conn = library.GetConnection();\n\n std::string query = \"SELECT * FROM tracks_playlists WHERE playlist_id = \";\n char escaped_playlist_id[30];\n PQescapeStringConn(conn, escaped_playlist_id, playlist_id.c_str(), 30, 0);\n\n query.append(escaped_playlist_id);\n PGresult *res = PQexec(conn, query.c_str());\n\n assert(PQntuples(res) == 2);\n\n PQclear(res);\n\n library.RemovePlaylist(playlist_id);\n\n res = PQexec(conn, query.c_str());\n\n assert(PQntuples(res) == 0);\n\n PQclear(res);\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure playlist objects are constructed properly\n *\n * Note: This isn't done. Verify that non-empty playlists are properly\n * populated with Track objects when the Track class is implemented\n *\/\nvoid Test_Playlist_Constructors()\n{\n cout << \"Test_Playlist_Constructors... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n \/\/ Should create an empty playlist\n CPlaylist playlist(&library);\n assert(playlist.GetId() == \"temp\");\n assert(playlist.GetTitle() == \"working playlist\");\n assert(playlist.GetLength() == \"0\");\n assert(playlist.GetLibrary() == &library);\n\n \/\/ Should create an object for the default playlist in db\n CPlaylist playlist2(&library, \"1\");\n assert(playlist2.GetId() == \"1\");\n assert(playlist2.GetTitle() == \"library\");\n assert(playlist2.GetLength() == \"0\");\n assert(playlist2.GetLibrary() == &library);\n \n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n\n\/**\n * \\brief Ensure tracks can be properly appended to playlists\n *\n * Note: This isn't done. Verify that Track objects are properly appended\n * to their containers when the Track Class is implemented\n *\/\nvoid Test_Playlist_AppendTrack()\n{\n cout << \"Test_Playlist_AppendTrack... \";\n CLibrary library;\n\n \/\/ Make sure all tables and such exist\n library.PrepareDatabase();\n\n \/\/ Adding tracks that can be added to playlists\n std::string track1_id = library.AddTrack(track1);\n std::string track2_id = library.AddTrack(track2);\n\n CPlaylist db_playlist(&library, \"1\"); \/\/ a playlist from the database\n CPlaylist temp_playlist(&library); \/\/ a temp playlist not in the database\n\n std::string association1 = db_playlist.AppendTrack(track1_id);\n std::string association2 = db_playlist.AppendTrack(track2_id);\n\n std::string association3 = temp_playlist.AppendTrack(track1_id);\n std::string association4 = temp_playlist.AppendTrack(track2_id);\n\n assert(association3 == \"temp\");\n assert(association4 == \"temp\");\n\n \/\/ Insert logic to make sure Track objects were appropriately added to the container\n \/\/ for both playlists\n\n \/\/ Verify that the proper database records were created\n if (db_playlist.GetId() != \"temp\")\n {\n PGconn *conn = library.GetConnection();\n\n std::string query = \"SELECT id, playlist_id, track_id, position FROM tracks_playlists WHERE playlist_id = \";\n\n char escaped_playlist_id[30];\n PQescapeStringConn(conn, escaped_playlist_id, db_playlist.GetId().c_str(), 30, 0);\n\n query.append(escaped_playlist_id);\n\n PGresult *res = PQexec(conn, query.c_str());\n\n \/\/ 0 and 1 should be auto-created when tracks are added\n \/\/ 2 and 3 are the new records we just added\n std::string association1_id(PQgetvalue(res, 2, 0));\n std::string association1_playlist_id(PQgetvalue(res, 2, 1));\n std::string association1_track_id(PQgetvalue(res, 2, 2));\n std::string association1_position(PQgetvalue(res, 2, 3));\n std::string association2_id(PQgetvalue(res, 3, 0));\n std::string association2_playlist_id(PQgetvalue(res, 3, 1));\n std::string association2_track_id(PQgetvalue(res, 3, 2));\n std::string association2_position(PQgetvalue(res, 3, 3));\n\n assert(association1 == association1_id);\n assert(db_playlist.GetId() == association1_playlist_id);\n assert(track1_id == association1_track_id);\n assert(\"3\" == association1_position);\n assert(association2 == association2_id);\n assert(db_playlist.GetId() == association2_playlist_id);\n assert(track2_id == association2_track_id);\n assert(\"4\" == association2_position);\n \n PQclear(res);\n }\n else\n {\n assert(association1 == \"temp\");\n assert(association2 == \"temp\");\n }\n\n library.DestroyDatabase();\n\n cout << \"OK\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 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 \"base\/idle_timer.h\"\n#include \"base\/message_loop.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing base::Time;\nusing base::TimeDelta;\nusing base::IdleTimer;\n\nnamespace {\n\n\/\/ We Mock the GetLastInputInfo function to return\n\/\/ the time stored here.\nstatic Time mock_timer_started;\n\nbool MockIdleTimeSource(int32 *milliseconds_interval_since_last_event) {\n TimeDelta delta = Time::Now() - mock_timer_started;\n *milliseconds_interval_since_last_event = \n static_cast<int32>(delta.InMilliseconds());\n return true;\n}\n\n\/\/ TestIdle task fires after 100ms of idle time.\nclass TestIdleTask : public IdleTimer {\n public:\n TestIdleTask(bool repeat)\n : IdleTimer(TimeDelta::FromMilliseconds(100), repeat),\n idle_counter_(0) {\n set_idle_time_source(MockIdleTimeSource);\n }\n\n int get_idle_counter() { return idle_counter_; }\n\n virtual void OnIdle() {\n idle_counter_++;\n }\n\n private:\n int idle_counter_;\n};\n\n\/\/ A task to help us quit the test.\nclass TestFinishedTask {\n public:\n TestFinishedTask() {}\n void Run() {\n MessageLoop::current()->Quit();\n }\n};\n\n\/\/ A timer which resets the idle clock.\nclass ResetIdleTask {\n public:\n ResetIdleTask() {}\n void Run() {\n mock_timer_started = Time::Now();\n }\n};\n\nclass IdleTimerTest : public testing::Test {\n private:\n \/\/ IdleTimer requires a UI message loop on the current thread.\n MessageLoopForUI message_loop_;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NoRepeat tests:\n\/\/ A non-repeating idle timer will fire once on idle, and\n\/\/ then will not fire again unless it goes non-idle first.\n\nTEST_F(IdleTimerTest, NoRepeatIdle) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Verify that we fired exactly once.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n base::OneShotTimer<TestFinishedTask> timer;\n timer.Start(TimeDelta::FromSeconds(1), &finish_task, &TestFinishedTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n EXPECT_EQ(test_task.get_idle_counter(), 1);\n}\n\nTEST_F(IdleTimerTest, NoRepeatFlipIdleOnce) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset once, idle after 500ms.\n \/\/ Verify that we fired exactly twice.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t1;\n t1.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::OneShotTimer<ResetIdleTask> t2;\n t2.Start(TimeDelta::FromMilliseconds(500), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n EXPECT_EQ(test_task.get_idle_counter(), 2);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3704\nTEST_F(IdleTimerTest, DISABLED_NoRepeatNotIdle) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset idle every 50ms.\n \/\/ Verify that we never fired.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::RepeatingTimer<ResetIdleTask> reset_timer;\n reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n\n MessageLoop::current()->Run();\n\n reset_timer.Stop();\n\n EXPECT_EQ(test_task.get_idle_counter(), 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Repeat tests:\n\/\/ A repeating idle timer will fire repeatedly on each interval, as long\n\/\/ as it has been idle. So, if the machine remains idle, it will continue\n\/\/ firing over and over.\n\nTEST_F(IdleTimerTest, Repeat) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1.05s.\n \/\/ Verify that we fired 10 times.\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n TestFinishedTask finish_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1050), &finish_task,\n &TestFinishedTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n \/\/ In a perfect world, the idle_counter should be 10. However,\n \/\/ since timers aren't guaranteed to fire perfectly, this can\n \/\/ be less. Just expect more than 5 and no more than 10.\n EXPECT_GT(test_task.get_idle_counter(), 5);\n EXPECT_LE(test_task.get_idle_counter(), 10);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3780\nTEST_F(IdleTimerTest, DISABLED_RepeatIdleReset) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a reset timer, which fires after 550ms\n \/\/ Verify that we fired 9 times.\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n ResetIdleTask reset_task;\n TestFinishedTask finish_task;\n\n base::OneShotTimer<TestFinishedTask> t1;\n t1.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::OneShotTimer<ResetIdleTask> t2;\n t2.Start(TimeDelta::FromMilliseconds(550), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n \/\/ In a perfect world, the idle_counter should be 9. However,\n \/\/ since timers aren't guaranteed to fire perfectly, this can\n \/\/ be less. Just expect more than 5 and no more than 9.\n EXPECT_GT(test_task.get_idle_counter(), 5);\n EXPECT_LE(test_task.get_idle_counter(), 9);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3704\nTEST_F(IdleTimerTest, DISABLED_RepeatNotIdle) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset idle every 50ms.\n \/\/ Verify that we never fired.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::RepeatingTimer<ResetIdleTask> reset_timer;\n reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n reset_timer.Stop();\n\n EXPECT_EQ(test_task.get_idle_counter(), 0);\n}\n\n} \/\/ namespace\n<commit_msg>Update idle timer test to use longer intervals.<commit_after>\/\/ Copyright (c) 2006-2008 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 \"base\/idle_timer.h\"\n#include \"base\/message_loop.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing base::Time;\nusing base::TimeDelta;\nusing base::IdleTimer;\n\n\n\/\/ If the timers fire too quickly, it can be tricky to make timer tests\n\/\/ reliable on all buildbots. This constant sets a minimum timer delta where\n\/\/ we expect that we should be able to reliably count timers without problems\n\/\/ due to slight clock\/scheduling variances.\nconst int kSafeTestIntervalMs = 500;\n\nnamespace {\n\n\/\/ We Mock the GetLastInputInfo function to return\n\/\/ the time stored here.\nstatic Time mock_timer_started;\n\nbool MockIdleTimeSource(int32 *milliseconds_interval_since_last_event) {\n TimeDelta delta = Time::Now() - mock_timer_started;\n *milliseconds_interval_since_last_event = \n static_cast<int32>(delta.InMilliseconds());\n return true;\n}\n\n\/\/ TestIdle task fires after 100ms of idle time.\nclass TestIdleTask : public IdleTimer {\n public:\n TestIdleTask(bool repeat)\n : IdleTimer(TimeDelta::FromMilliseconds(kSafeTestIntervalMs), repeat),\n idle_counter_(0) {\n set_idle_time_source(MockIdleTimeSource);\n }\n\n int get_idle_counter() { return idle_counter_; }\n\n virtual void OnIdle() {\n idle_counter_++;\n }\n\n private:\n int idle_counter_;\n};\n\n\/\/ A task to help us quit the test.\nclass TestFinishedTask {\n public:\n TestFinishedTask() {}\n void Run() {\n MessageLoop::current()->Quit();\n }\n};\n\n\/\/ A timer which resets the idle clock.\nclass ResetIdleTask {\n public:\n ResetIdleTask() {}\n void Run() {\n mock_timer_started = Time::Now();\n }\n};\n\nclass IdleTimerTest : public testing::Test {\n private:\n \/\/ IdleTimer requires a UI message loop on the current thread.\n MessageLoopForUI message_loop_;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NoRepeat tests:\n\/\/ A non-repeating idle timer will fire once on idle, and\n\/\/ then will not fire again unless it goes non-idle first.\n\nTEST_F(IdleTimerTest, NoRepeatIdle) {\n \/\/ Create an IdleTimer, which should fire once after 500ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Verify that we fired exactly once.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n base::OneShotTimer<TestFinishedTask> timer;\n timer.Start(TimeDelta::FromMilliseconds(2 * kSafeTestIntervalMs),\n &finish_task, &TestFinishedTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n EXPECT_EQ(test_task.get_idle_counter(), 1);\n}\n\nTEST_F(IdleTimerTest, NoRepeatFlipIdleOnce) {\n \/\/ Create an IdleTimer, which should fire once after 500ms.\n \/\/ Create a Quit timer which will fire after 5s.\n \/\/ Create a timer to reset once, idle after 2s.\n \/\/ Verify that we fired exactly twice.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t1;\n t1.Start(TimeDelta::FromMilliseconds(10 * kSafeTestIntervalMs), &finish_task,\n &TestFinishedTask::Run);\n \n base::OneShotTimer<ResetIdleTask> t2;\n t2.Start(TimeDelta::FromMilliseconds(4 * kSafeTestIntervalMs), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n EXPECT_EQ(test_task.get_idle_counter(), 2);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3704\nTEST_F(IdleTimerTest, DISABLED_NoRepeatNotIdle) {\n \/\/ Create an IdleTimer, which should fire once after 500ms.\n \/\/ Create a Quit timer which will fire after 5s.\n \/\/ Create a timer to reset idle every 50ms.\n \/\/ Verify that we never fired.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(10 * kSafeTestIntervalMs), &finish_task,\n &TestFinishedTask::Run);\n \n base::RepeatingTimer<ResetIdleTask> reset_timer;\n reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n\n MessageLoop::current()->Run();\n\n reset_timer.Stop();\n\n EXPECT_EQ(test_task.get_idle_counter(), 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Repeat tests:\n\/\/ A repeating idle timer will fire repeatedly on each interval, as long\n\/\/ as it has been idle. So, if the machine remains idle, it will continue\n\/\/ firing over and over.\n\nTEST_F(IdleTimerTest, Repeat) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 500ms.\n \/\/ Create a Quit timer which will fire after 1.5s.\n \/\/ Verify that we fired 2-3 times.\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n TestFinishedTask finish_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(kSafeTestIntervalMs * 3), &finish_task,\n &TestFinishedTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n \/\/ In a perfect world, the idle_counter should be 2. However,\n \/\/ due to timer 'slop', accept 2 or 3.\n EXPECT_GE(test_task.get_idle_counter(), 2);\n EXPECT_LE(test_task.get_idle_counter(), 3);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3780\nTEST_F(IdleTimerTest, RepeatIdleReset) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 500ms.\n \/\/ Create a Quit timer which will fire after 5s.\n \/\/ Create a reset timer, which fires after 2500ms\n \/\/ Verify that we fired 8-10 times.\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n ResetIdleTask reset_task;\n TestFinishedTask finish_task;\n\n base::OneShotTimer<TestFinishedTask> t1;\n t1.Start(TimeDelta::FromMilliseconds(10 * kSafeTestIntervalMs), &finish_task,\n &TestFinishedTask::Run);\n \n base::OneShotTimer<ResetIdleTask> t2;\n t2.Start(TimeDelta::FromMilliseconds(5 * kSafeTestIntervalMs), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n \/\/ In a perfect world, the idle_counter should be 9. However,\n \/\/ since timers aren't guaranteed to fire perfectly, this can\n \/\/ be less. Accept 8-10.\n EXPECT_GE(test_task.get_idle_counter(), 8);\n EXPECT_LE(test_task.get_idle_counter(), 10);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3704\nTEST_F(IdleTimerTest, DISABLED_RepeatNotIdle) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 500ms.\n \/\/ Create a Quit timer which will fire after 4s.\n \/\/ Create a timer to reset idle every 50ms.\n \/\/ Verify that we never fired.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(8 * kSafeTestIntervalMs), &finish_task,\n &TestFinishedTask::Run);\n \n base::RepeatingTimer<ResetIdleTask> reset_timer;\n reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n reset_timer.Stop();\n\n EXPECT_EQ(test_task.get_idle_counter(), 0);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*! @page timer MLPACK Timers\n\n@section timerintro Introduction\n\nMLPACK provides a simple timer interface for the timing of machine learning\nmethods. The results of any timers used during the program are displayed at\noutput by the mlpack::CLI object, when --verbose is given:\n\n@code\n$ allknn -r dataset.csv -n neighbors_out.csv -d distances_out.csv -k 5 -v\n<...>\n[INFO ] Program timers:\n[INFO ] computing_neighbors: 0.010650s\n[INFO ] loading_data: 0.002567s\n[INFO ] saving_data: 0.001115s\n[INFO ] total_time: 0.149816s\n[INFO ] tree_building: 0.000534s\n@endcode\n\n@section usingtimer Timer API\n\nThe mlpack::Timer class provides three simple methods:\n\n@code\nvoid Timer::Start(const char* name);\nvoid Timer::Stop(const char* name);\ntimeval Timer::Get(const char* name);\n@endcode\n\nEach timer is given a name, and is referenced by that name.\n\nA \"total_time\" timer is run by default for each MLPACK program.\n\n@section example Timer Example\n\nBelow is a very simple example of timer usage in code.\n\n@code\n#include <mlpack\/core.hpp>\n\nusing namespace mlpack;\n\nint main(int argc, char** argv)\n{\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Start a timer.\n Timer::Start(\"some_timer\");\n\n \/\/ Do some things.\n DoSomeStuff();\n\n \/\/ Stop the timer.\n Timer::Stop(\"some_timer\");\n}\n@endcode\n\nIf the --verbose flag was given to this executable, the resultant time that\n\"some_timer\" ran for would be shown.\n\n*\/\n<commit_msg>Add a note about running a timer multiple times.<commit_after>\/*! @page timer MLPACK Timers\n\n@section timerintro Introduction\n\nMLPACK provides a simple timer interface for the timing of machine learning\nmethods. The results of any timers used during the program are displayed at\noutput by the mlpack::CLI object, when --verbose is given:\n\n@code\n$ allknn -r dataset.csv -n neighbors_out.csv -d distances_out.csv -k 5 -v\n<...>\n[INFO ] Program timers:\n[INFO ] computing_neighbors: 0.010650s\n[INFO ] loading_data: 0.002567s\n[INFO ] saving_data: 0.001115s\n[INFO ] total_time: 0.149816s\n[INFO ] tree_building: 0.000534s\n@endcode\n\n@section usingtimer Timer API\n\nThe mlpack::Timer class provides three simple methods:\n\n@code\nvoid Timer::Start(const char* name);\nvoid Timer::Stop(const char* name);\ntimeval Timer::Get(const char* name);\n@endcode\n\nEach timer is given a name, and is referenced by that name. You can call \\c\nTimer::Start() and \\c Timer::Stop() multiple times for a particular timer name,\nand the result will be the sum of the runs of the timer. Note that \\c\nTimer::Stop() must be called before \\c Timer::Start() is called again.\n\nA \"total_time\" timer is run by default for each MLPACK program.\n\n@section example Timer Example\n\nBelow is a very simple example of timer usage in code.\n\n@code\n#include <mlpack\/core.hpp>\n\nusing namespace mlpack;\n\nint main(int argc, char** argv)\n{\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Start a timer.\n Timer::Start(\"some_timer\");\n\n \/\/ Do some things.\n DoSomeStuff();\n\n \/\/ Stop the timer.\n Timer::Stop(\"some_timer\");\n}\n@endcode\n\nIf the --verbose flag was given to this executable, the resultant time that\n\"some_timer\" ran for would be shown.\n\n*\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef R3_TSR_TSR_H_\n#define R3_TSR_TSR_H_\n\n#include \"..\/util\/RNG.hpp\"\n\n#include <Eigen\/Dense>\n#include <random>\n\nnamespace r3 {\nnamespace tsr {\n\nclass TSR\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n TSR(const Eigen::Isometry3d& T0_w,\n const Eigen::Matrix<double, 6, 2>& Bw,\n const Eigen::Isometry3d& Tw_e);\n\n TSR(const TSR&) = default;\n virtual ~TSR() = default;\n\n \/\/\/ Return a transform sampled from this TSR.\n \/\/\/\n \/\/\/ This function uses the provided RNG to create a sample `Tw_s` from the\n \/\/\/ `Bw` bounds matrix of this TSR, and returns the result:\n \/\/\/ `T0_w * Tw_s * Tw_e`.\n \/\/\/\n \/\/\/ \\param[in] rng Random number generator from which to sample\n \/\/\/ \\return a transform within the bounds of this TSR.\n const Eigen::Isometry3d sample(r3::util::RNG& rng);\n\n \/\/\/ Transformation from origin frame into \"wiggle\" frame.\n Eigen::Isometry3d mT0_w;\n\n \/\/\/ Bounds on \"wiggling\" in `x, y, z, roll, pitch, yaw`.\n Eigen::Matrix<double, 6, 2> mBw;\n\n \/\/\/ Transformation from \"wiggle\" frame into end frame.\n Eigen::Isometry3d mTw_e;\n};\n\n} \/\/ namespace tsr\n} \/\/ namespace r3\n\n#endif \/\/ R3_TSR_TSR_H_\n<commit_msg>Fixed rule-of-five constructors\/destructors\/assignments.<commit_after>#ifndef R3_TSR_TSR_H_\n#define R3_TSR_TSR_H_\n\n#include \"..\/util\/RNG.hpp\"\n\n#include <Eigen\/Dense>\n#include <random>\n\nnamespace r3 {\nnamespace tsr {\n\nclass TSR\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n TSR(const Eigen::Isometry3d& T0_w,\n const Eigen::Matrix<double, 6, 2>& Bw,\n const Eigen::Isometry3d& Tw_e);\n\n TSR(const TSR&) = default;\n TSR(TSR&& other) = default;\n TSR& operator=(const TSR& other) = default;\n TSR& operator=(TSR&& other) = default;\n virtual ~TSR() = default;\n\n \/\/\/ Return a transform sampled from this TSR.\n \/\/\/\n \/\/\/ This function uses the provided RNG to create a sample `Tw_s` from the\n \/\/\/ `Bw` bounds matrix of this TSR, and returns the result:\n \/\/\/ `T0_w * Tw_s * Tw_e`.\n \/\/\/\n \/\/\/ \\param[in] rng Random number generator from which to sample\n \/\/\/ \\return a transform within the bounds of this TSR.\n const Eigen::Isometry3d sample(r3::util::RNG& rng);\n\n \/\/\/ Transformation from origin frame into \"wiggle\" frame.\n Eigen::Isometry3d mT0_w;\n\n \/\/\/ Bounds on \"wiggling\" in `x, y, z, roll, pitch, yaw`.\n Eigen::Matrix<double, 6, 2> mBw;\n\n \/\/\/ Transformation from \"wiggle\" frame into end frame.\n Eigen::Isometry3d mTw_e;\n};\n\n} \/\/ namespace tsr\n} \/\/ namespace r3\n\n#endif \/\/ R3_TSR_TSR_H_\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- llvm-config.cpp - LLVM project configuration utility --------------===\/\/\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\/\/ This tool encapsulates information about an LLVM project configuration for\n\/\/ use by other project's build environments (to determine installed path,\n\/\/ available features, required libraries, etc.).\n\/\/\n\/\/ Note that although this tool *may* be used by some parts of LLVM's build\n\/\/ itself (i.e., the Makefiles use it to compute required libraries when linking\n\/\/ tools), this tool is primarily designed to support external projects.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Config\/llvm-config.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <cstdlib>\n#include <set>\n#include <vector>\n\nusing namespace llvm;\n\n\/\/ Include the build time variables we can report to the user. This is generated\n\/\/ at build time from the BuildVariables.inc.in file by the build system.\n#include \"BuildVariables.inc\"\n\n\/\/ Include the component table. This creates an array of struct\n\/\/ AvailableComponent entries, which record the component name, library name,\n\/\/ and required components for all of the available libraries.\n\/\/\n\/\/ Not all components define a library, we also use \"library groups\" as a way to\n\/\/ create entries for pseudo groups like x86 or all-targets.\n#include \"LibraryDependencies.inc\"\n\n\/\/\/ \\brief Traverse a single component adding to the topological ordering in\n\/\/\/ \\arg RequiredLibs.\n\/\/\/\n\/\/\/ \\param Name - The component to traverse.\n\/\/\/ \\param ComponentMap - A prebuilt map of component names to descriptors.\n\/\/\/ \\param VisitedComponents [in] [out] - The set of already visited components.\n\/\/\/ \\param RequiredLibs [out] - The ordered list of required libraries.\nstatic void VisitComponent(StringRef Name,\n const StringMap<AvailableComponent*> &ComponentMap,\n std::set<AvailableComponent*> &VisitedComponents,\n std::vector<StringRef> &RequiredLibs) {\n \/\/ Lookup the component.\n AvailableComponent *AC = ComponentMap.lookup(Name);\n assert(AC && \"Invalid component name!\");\n\n \/\/ Add to the visited table.\n if (!VisitedComponents.insert(AC).second) {\n \/\/ We are done if the component has already been visited.\n return;\n }\n\n \/\/ Otherwise, visit all the dependencies.\n for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {\n VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,\n RequiredLibs);\n }\n\n \/\/ Add to the required library list.\n if (AC->Library)\n RequiredLibs.push_back(AC->Library);\n}\n\n\/\/\/ \\brief Compute the list of required libraries for a given list of\n\/\/\/ components, in an order suitable for passing to a linker (that is, libraries\n\/\/\/ appear prior to their dependencies).\n\/\/\/\n\/\/\/ \\param Components - The names of the components to find libraries for.\n\/\/\/ \\param RequiredLibs [out] - On return, the ordered list of libraries that\n\/\/\/ are required to link the given components.\nvoid ComputeLibsForComponents(const std::vector<StringRef> &Components,\n std::vector<StringRef> &RequiredLibs) {\n std::set<AvailableComponent*> VisitedComponents;\n\n \/\/ Build a map of component names to information.\n StringMap<AvailableComponent*> ComponentMap;\n for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {\n AvailableComponent *AC = &AvailableComponents[i];\n ComponentMap[AC->Name] = AC;\n }\n\n \/\/ Visit the components.\n for (unsigned i = 0, e = Components.size(); i != e; ++i) {\n \/\/ Users are allowed to provide mixed case component names.\n std::string ComponentLower = Components[i].lower();\n\n \/\/ Validate that the user supplied a valid component name.\n if (!ComponentMap.count(ComponentLower)) {\n llvm::errs() << \"llvm-config: unknown component name: \" << Components[i]\n << \"\\n\";\n exit(1);\n }\n\n VisitComponent(ComponentLower, ComponentMap, VisitedComponents,\n RequiredLibs);\n }\n\n \/\/ The list is now ordered with leafs first, we want the libraries to printed\n \/\/ in the reverse order of dependency.\n std::reverse(RequiredLibs.begin(), RequiredLibs.end());\n}\n\n\/* *** *\/\n\nvoid usage() {\n errs() << \"\\\nusage: llvm-config <OPTION>... [<COMPONENT>...]\\n\\\n\\n\\\nGet various configuration information needed to compile programs which use\\n\\\nLLVM. Typically called from 'configure' scripts. Examples:\\n\\\n llvm-config --cxxflags\\n\\\n llvm-config --ldflags\\n\\\n llvm-config --libs engine bcreader scalaropts\\n\\\n\\n\\\nOptions:\\n\\\n --version Print LLVM version.\\n\\\n --prefix Print the installation prefix.\\n\\\n --src-root Print the source root LLVM was built from.\\n\\\n --obj-root Print the object root used to build LLVM.\\n\\\n --bindir Directory containing LLVM executables.\\n\\\n --includedir Directory containing LLVM headers.\\n\\\n --libdir Directory containing LLVM libraries.\\n\\\n --cppflags C preprocessor flags for files that include LLVM headers.\\n\\\n --cflags C compiler flags for files that include LLVM headers.\\n\\\n --cxxflags C++ compiler flags for files that include LLVM headers.\\n\\\n --ldflags Print Linker flags.\\n\\\n --libs Libraries needed to link against LLVM components.\\n\\\n --libnames Bare library names for in-tree builds.\\n\\\n --libfiles Fully qualified library filenames for makefile depends.\\n\\\n --components List of all possible components.\\n\\\n --targets-built List of all targets currently built.\\n\\\n --host-target Target triple used to configure LLVM.\\n\\\n --build-mode Print build mode of LLVM tree (e.g. Debug or Release).\\n\\\nTypical components:\\n\\\n all All LLVM libraries (default).\\n\\\n backend Either a native backend or the C backend.\\n\\\n engine Either a native JIT or a bitcode interpreter.\\n\";\n exit(1);\n}\n\n\/\/\/ \\brief Compute the path to the main executable.\nllvm::sys::Path GetExecutablePath(const char *Argv0) {\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void *P = (void*) (intptr_t) GetExecutablePath;\n return llvm::sys::Path::GetMainExecutable(Argv0, P);\n}\n\nint main(int argc, char **argv) {\n std::vector<StringRef> Components;\n bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;\n bool HasAnyOption = false;\n\n \/\/ llvm-config is designed to support being run both from a development tree\n \/\/ and from an installed path. We try and auto-detect which case we are in so\n \/\/ that we can report the correct information when run from a development\n \/\/ tree.\n bool IsInDevelopmentTree, DevelopmentTreeLayoutIsCMakeStyle;\n llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]).str());\n std::string CurrentExecPrefix;\n std::string ActiveObjRoot;\n\n \/\/ Create an absolute path, and pop up one directory (we expect to be inside a\n \/\/ bin dir).\n sys::fs::make_absolute(CurrentPath);\n CurrentExecPrefix = sys::path::parent_path(\n sys::path::parent_path(CurrentPath)).str();\n\n \/\/ Check to see if we are inside a development tree by comparing to possible\n \/\/ locations (prefix style or CMake style). This could be wrong in the face of\n \/\/ symbolic links, but is good enough.\n if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + \"\/\" + LLVM_BUILDMODE) {\n IsInDevelopmentTree = true;\n DevelopmentTreeLayoutIsCMakeStyle = false;\n\n \/\/ If we are in a development tree, then check if we are in a BuildTools\n \/\/ directory. This indicates we are built for the build triple, but we\n \/\/ always want to provide information for the host triple.\n if (sys::path::filename(LLVM_OBJ_ROOT) == \"BuildTools\") {\n ActiveObjRoot = sys::path::parent_path(LLVM_OBJ_ROOT);\n } else {\n ActiveObjRoot = LLVM_OBJ_ROOT;\n }\n } else if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + \"\/bin\") {\n IsInDevelopmentTree = true;\n DevelopmentTreeLayoutIsCMakeStyle = true;\n ActiveObjRoot = LLVM_OBJ_ROOT;\n } else {\n IsInDevelopmentTree = false;\n }\n\n \/\/ Compute various directory locations based on the derived location\n \/\/ information.\n std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;\n std::string ActiveIncludeOption;\n if (IsInDevelopmentTree) {\n ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + \"\/include\";\n ActivePrefix = CurrentExecPrefix;\n\n \/\/ CMake organizes the products differently than a normal prefix style\n \/\/ layout.\n if (DevelopmentTreeLayoutIsCMakeStyle) {\n ActiveBinDir = ActiveObjRoot + \"\/bin\/\" + LLVM_BUILDMODE;\n ActiveLibDir = ActiveObjRoot + \"\/lib\/\" + LLVM_BUILDMODE;\n } else {\n ActiveBinDir = ActiveObjRoot + \"\/\" + LLVM_BUILDMODE + \"\/bin\";\n ActiveLibDir = ActiveObjRoot + \"\/\" + LLVM_BUILDMODE + \"\/lib\";\n }\n\n \/\/ We need to include files from both the source and object trees.\n ActiveIncludeOption = (\"-I\" + ActiveIncludeDir + \" \" +\n \"-I\" + ActiveObjRoot + \"\/include\");\n } else {\n ActivePrefix = CurrentExecPrefix;\n ActiveIncludeDir = ActivePrefix + \"\/include\";\n ActiveBinDir = ActivePrefix + \"\/bin\";\n ActiveLibDir = ActivePrefix + \"\/lib\";\n ActiveIncludeOption = \"-I\" + ActiveIncludeDir;\n }\n\n raw_ostream &OS = outs();\n for (int i = 1; i != argc; ++i) {\n StringRef Arg = argv[i];\n\n if (Arg.startswith(\"-\")) {\n HasAnyOption = true;\n if (Arg == \"--version\") {\n OS << PACKAGE_VERSION << '\\n';\n } else if (Arg == \"--prefix\") {\n OS << ActivePrefix << '\\n';\n } else if (Arg == \"--bindir\") {\n OS << ActiveBinDir << '\\n';\n } else if (Arg == \"--includedir\") {\n OS << ActiveIncludeDir << '\\n';\n } else if (Arg == \"--libdir\") {\n OS << ActiveLibDir << '\\n';\n } else if (Arg == \"--cppflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\\n';\n } else if (Arg == \"--cflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\\n';\n } else if (Arg == \"--cxxflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\\n';\n } else if (Arg == \"--ldflags\") {\n OS << \"-L\" << ActiveLibDir << ' ' << LLVM_LDFLAGS\n << ' ' << LLVM_SYSTEM_LIBS << '\\n';\n } else if (Arg == \"--libs\") {\n PrintLibs = true;\n } else if (Arg == \"--libnames\") {\n PrintLibNames = true;\n } else if (Arg == \"--libfiles\") {\n PrintLibFiles = true;\n } else if (Arg == \"--components\") {\n for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {\n OS << ' ';\n OS << AvailableComponents[j].Name;\n }\n OS << '\\n';\n } else if (Arg == \"--targets-built\") {\n bool First = true;\n for (TargetRegistry::iterator I = TargetRegistry::begin(),\n E = TargetRegistry::end(); I != E; First = false, ++I) {\n if (!First)\n OS << ' ';\n OS << I->getName();\n }\n OS << '\\n';\n } else if (Arg == \"--host-target\") {\n OS << LLVM_DEFAULT_TARGET_TRIPLE << '\\n';\n } else if (Arg == \"--build-mode\") {\n OS << LLVM_BUILDMODE << '\\n';\n } else if (Arg == \"--obj-root\") {\n OS << LLVM_OBJ_ROOT << '\\n';\n } else if (Arg == \"--src-root\") {\n OS << LLVM_SRC_ROOT << '\\n';\n } else {\n usage();\n }\n } else {\n Components.push_back(Arg);\n }\n }\n\n if (!HasAnyOption)\n usage();\n\n if (PrintLibs || PrintLibNames || PrintLibFiles) {\n \/\/ If no components were specified, default to \"all\".\n if (Components.empty())\n Components.push_back(\"all\");\n\n \/\/ Construct the list of all the required libraries.\n std::vector<StringRef> RequiredLibs;\n ComputeLibsForComponents(Components, RequiredLibs);\n\n for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {\n StringRef Lib = RequiredLibs[i];\n if (i)\n OS << ' ';\n\n if (PrintLibNames) {\n OS << Lib;\n } else if (PrintLibFiles) {\n OS << ActiveLibDir << '\/' << Lib;\n } else if (PrintLibs) {\n \/\/ If this is a typical library name, include it using -l.\n if (Lib.startswith(\"lib\") && Lib.endswith(\".a\")) {\n OS << \"-l\" << Lib.slice(3, Lib.size()-2);\n continue;\n }\n\n \/\/ Otherwise, print the full path.\n OS << ActiveLibDir << '\/' << Lib;\n }\n }\n OS << '\\n';\n } else if (!Components.empty()) {\n errs() << \"llvm-config: error: components given, but unused\\n\\n\";\n usage();\n }\n\n return 0;\n}\n<commit_msg>llvm-config: Update help text for removal of \"backend\" pseudo component.<commit_after>\/\/===-- llvm-config.cpp - LLVM project configuration utility --------------===\/\/\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\/\/ This tool encapsulates information about an LLVM project configuration for\n\/\/ use by other project's build environments (to determine installed path,\n\/\/ available features, required libraries, etc.).\n\/\/\n\/\/ Note that although this tool *may* be used by some parts of LLVM's build\n\/\/ itself (i.e., the Makefiles use it to compute required libraries when linking\n\/\/ tools), this tool is primarily designed to support external projects.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Config\/llvm-config.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <cstdlib>\n#include <set>\n#include <vector>\n\nusing namespace llvm;\n\n\/\/ Include the build time variables we can report to the user. This is generated\n\/\/ at build time from the BuildVariables.inc.in file by the build system.\n#include \"BuildVariables.inc\"\n\n\/\/ Include the component table. This creates an array of struct\n\/\/ AvailableComponent entries, which record the component name, library name,\n\/\/ and required components for all of the available libraries.\n\/\/\n\/\/ Not all components define a library, we also use \"library groups\" as a way to\n\/\/ create entries for pseudo groups like x86 or all-targets.\n#include \"LibraryDependencies.inc\"\n\n\/\/\/ \\brief Traverse a single component adding to the topological ordering in\n\/\/\/ \\arg RequiredLibs.\n\/\/\/\n\/\/\/ \\param Name - The component to traverse.\n\/\/\/ \\param ComponentMap - A prebuilt map of component names to descriptors.\n\/\/\/ \\param VisitedComponents [in] [out] - The set of already visited components.\n\/\/\/ \\param RequiredLibs [out] - The ordered list of required libraries.\nstatic void VisitComponent(StringRef Name,\n const StringMap<AvailableComponent*> &ComponentMap,\n std::set<AvailableComponent*> &VisitedComponents,\n std::vector<StringRef> &RequiredLibs) {\n \/\/ Lookup the component.\n AvailableComponent *AC = ComponentMap.lookup(Name);\n assert(AC && \"Invalid component name!\");\n\n \/\/ Add to the visited table.\n if (!VisitedComponents.insert(AC).second) {\n \/\/ We are done if the component has already been visited.\n return;\n }\n\n \/\/ Otherwise, visit all the dependencies.\n for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {\n VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,\n RequiredLibs);\n }\n\n \/\/ Add to the required library list.\n if (AC->Library)\n RequiredLibs.push_back(AC->Library);\n}\n\n\/\/\/ \\brief Compute the list of required libraries for a given list of\n\/\/\/ components, in an order suitable for passing to a linker (that is, libraries\n\/\/\/ appear prior to their dependencies).\n\/\/\/\n\/\/\/ \\param Components - The names of the components to find libraries for.\n\/\/\/ \\param RequiredLibs [out] - On return, the ordered list of libraries that\n\/\/\/ are required to link the given components.\nvoid ComputeLibsForComponents(const std::vector<StringRef> &Components,\n std::vector<StringRef> &RequiredLibs) {\n std::set<AvailableComponent*> VisitedComponents;\n\n \/\/ Build a map of component names to information.\n StringMap<AvailableComponent*> ComponentMap;\n for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {\n AvailableComponent *AC = &AvailableComponents[i];\n ComponentMap[AC->Name] = AC;\n }\n\n \/\/ Visit the components.\n for (unsigned i = 0, e = Components.size(); i != e; ++i) {\n \/\/ Users are allowed to provide mixed case component names.\n std::string ComponentLower = Components[i].lower();\n\n \/\/ Validate that the user supplied a valid component name.\n if (!ComponentMap.count(ComponentLower)) {\n llvm::errs() << \"llvm-config: unknown component name: \" << Components[i]\n << \"\\n\";\n exit(1);\n }\n\n VisitComponent(ComponentLower, ComponentMap, VisitedComponents,\n RequiredLibs);\n }\n\n \/\/ The list is now ordered with leafs first, we want the libraries to printed\n \/\/ in the reverse order of dependency.\n std::reverse(RequiredLibs.begin(), RequiredLibs.end());\n}\n\n\/* *** *\/\n\nvoid usage() {\n errs() << \"\\\nusage: llvm-config <OPTION>... [<COMPONENT>...]\\n\\\n\\n\\\nGet various configuration information needed to compile programs which use\\n\\\nLLVM. Typically called from 'configure' scripts. Examples:\\n\\\n llvm-config --cxxflags\\n\\\n llvm-config --ldflags\\n\\\n llvm-config --libs engine bcreader scalaropts\\n\\\n\\n\\\nOptions:\\n\\\n --version Print LLVM version.\\n\\\n --prefix Print the installation prefix.\\n\\\n --src-root Print the source root LLVM was built from.\\n\\\n --obj-root Print the object root used to build LLVM.\\n\\\n --bindir Directory containing LLVM executables.\\n\\\n --includedir Directory containing LLVM headers.\\n\\\n --libdir Directory containing LLVM libraries.\\n\\\n --cppflags C preprocessor flags for files that include LLVM headers.\\n\\\n --cflags C compiler flags for files that include LLVM headers.\\n\\\n --cxxflags C++ compiler flags for files that include LLVM headers.\\n\\\n --ldflags Print Linker flags.\\n\\\n --libs Libraries needed to link against LLVM components.\\n\\\n --libnames Bare library names for in-tree builds.\\n\\\n --libfiles Fully qualified library filenames for makefile depends.\\n\\\n --components List of all possible components.\\n\\\n --targets-built List of all targets currently built.\\n\\\n --host-target Target triple used to configure LLVM.\\n\\\n --build-mode Print build mode of LLVM tree (e.g. Debug or Release).\\n\\\nTypical components:\\n\\\n all All LLVM libraries (default).\\n\\\n engine Either a native JIT or a bitcode interpreter.\\n\";\n exit(1);\n}\n\n\/\/\/ \\brief Compute the path to the main executable.\nllvm::sys::Path GetExecutablePath(const char *Argv0) {\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void *P = (void*) (intptr_t) GetExecutablePath;\n return llvm::sys::Path::GetMainExecutable(Argv0, P);\n}\n\nint main(int argc, char **argv) {\n std::vector<StringRef> Components;\n bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;\n bool HasAnyOption = false;\n\n \/\/ llvm-config is designed to support being run both from a development tree\n \/\/ and from an installed path. We try and auto-detect which case we are in so\n \/\/ that we can report the correct information when run from a development\n \/\/ tree.\n bool IsInDevelopmentTree, DevelopmentTreeLayoutIsCMakeStyle;\n llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]).str());\n std::string CurrentExecPrefix;\n std::string ActiveObjRoot;\n\n \/\/ Create an absolute path, and pop up one directory (we expect to be inside a\n \/\/ bin dir).\n sys::fs::make_absolute(CurrentPath);\n CurrentExecPrefix = sys::path::parent_path(\n sys::path::parent_path(CurrentPath)).str();\n\n \/\/ Check to see if we are inside a development tree by comparing to possible\n \/\/ locations (prefix style or CMake style). This could be wrong in the face of\n \/\/ symbolic links, but is good enough.\n if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + \"\/\" + LLVM_BUILDMODE) {\n IsInDevelopmentTree = true;\n DevelopmentTreeLayoutIsCMakeStyle = false;\n\n \/\/ If we are in a development tree, then check if we are in a BuildTools\n \/\/ directory. This indicates we are built for the build triple, but we\n \/\/ always want to provide information for the host triple.\n if (sys::path::filename(LLVM_OBJ_ROOT) == \"BuildTools\") {\n ActiveObjRoot = sys::path::parent_path(LLVM_OBJ_ROOT);\n } else {\n ActiveObjRoot = LLVM_OBJ_ROOT;\n }\n } else if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + \"\/bin\") {\n IsInDevelopmentTree = true;\n DevelopmentTreeLayoutIsCMakeStyle = true;\n ActiveObjRoot = LLVM_OBJ_ROOT;\n } else {\n IsInDevelopmentTree = false;\n }\n\n \/\/ Compute various directory locations based on the derived location\n \/\/ information.\n std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;\n std::string ActiveIncludeOption;\n if (IsInDevelopmentTree) {\n ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + \"\/include\";\n ActivePrefix = CurrentExecPrefix;\n\n \/\/ CMake organizes the products differently than a normal prefix style\n \/\/ layout.\n if (DevelopmentTreeLayoutIsCMakeStyle) {\n ActiveBinDir = ActiveObjRoot + \"\/bin\/\" + LLVM_BUILDMODE;\n ActiveLibDir = ActiveObjRoot + \"\/lib\/\" + LLVM_BUILDMODE;\n } else {\n ActiveBinDir = ActiveObjRoot + \"\/\" + LLVM_BUILDMODE + \"\/bin\";\n ActiveLibDir = ActiveObjRoot + \"\/\" + LLVM_BUILDMODE + \"\/lib\";\n }\n\n \/\/ We need to include files from both the source and object trees.\n ActiveIncludeOption = (\"-I\" + ActiveIncludeDir + \" \" +\n \"-I\" + ActiveObjRoot + \"\/include\");\n } else {\n ActivePrefix = CurrentExecPrefix;\n ActiveIncludeDir = ActivePrefix + \"\/include\";\n ActiveBinDir = ActivePrefix + \"\/bin\";\n ActiveLibDir = ActivePrefix + \"\/lib\";\n ActiveIncludeOption = \"-I\" + ActiveIncludeDir;\n }\n\n raw_ostream &OS = outs();\n for (int i = 1; i != argc; ++i) {\n StringRef Arg = argv[i];\n\n if (Arg.startswith(\"-\")) {\n HasAnyOption = true;\n if (Arg == \"--version\") {\n OS << PACKAGE_VERSION << '\\n';\n } else if (Arg == \"--prefix\") {\n OS << ActivePrefix << '\\n';\n } else if (Arg == \"--bindir\") {\n OS << ActiveBinDir << '\\n';\n } else if (Arg == \"--includedir\") {\n OS << ActiveIncludeDir << '\\n';\n } else if (Arg == \"--libdir\") {\n OS << ActiveLibDir << '\\n';\n } else if (Arg == \"--cppflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\\n';\n } else if (Arg == \"--cflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\\n';\n } else if (Arg == \"--cxxflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\\n';\n } else if (Arg == \"--ldflags\") {\n OS << \"-L\" << ActiveLibDir << ' ' << LLVM_LDFLAGS\n << ' ' << LLVM_SYSTEM_LIBS << '\\n';\n } else if (Arg == \"--libs\") {\n PrintLibs = true;\n } else if (Arg == \"--libnames\") {\n PrintLibNames = true;\n } else if (Arg == \"--libfiles\") {\n PrintLibFiles = true;\n } else if (Arg == \"--components\") {\n for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {\n OS << ' ';\n OS << AvailableComponents[j].Name;\n }\n OS << '\\n';\n } else if (Arg == \"--targets-built\") {\n bool First = true;\n for (TargetRegistry::iterator I = TargetRegistry::begin(),\n E = TargetRegistry::end(); I != E; First = false, ++I) {\n if (!First)\n OS << ' ';\n OS << I->getName();\n }\n OS << '\\n';\n } else if (Arg == \"--host-target\") {\n OS << LLVM_DEFAULT_TARGET_TRIPLE << '\\n';\n } else if (Arg == \"--build-mode\") {\n OS << LLVM_BUILDMODE << '\\n';\n } else if (Arg == \"--obj-root\") {\n OS << LLVM_OBJ_ROOT << '\\n';\n } else if (Arg == \"--src-root\") {\n OS << LLVM_SRC_ROOT << '\\n';\n } else {\n usage();\n }\n } else {\n Components.push_back(Arg);\n }\n }\n\n if (!HasAnyOption)\n usage();\n\n if (PrintLibs || PrintLibNames || PrintLibFiles) {\n \/\/ If no components were specified, default to \"all\".\n if (Components.empty())\n Components.push_back(\"all\");\n\n \/\/ Construct the list of all the required libraries.\n std::vector<StringRef> RequiredLibs;\n ComputeLibsForComponents(Components, RequiredLibs);\n\n for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {\n StringRef Lib = RequiredLibs[i];\n if (i)\n OS << ' ';\n\n if (PrintLibNames) {\n OS << Lib;\n } else if (PrintLibFiles) {\n OS << ActiveLibDir << '\/' << Lib;\n } else if (PrintLibs) {\n \/\/ If this is a typical library name, include it using -l.\n if (Lib.startswith(\"lib\") && Lib.endswith(\".a\")) {\n OS << \"-l\" << Lib.slice(3, Lib.size()-2);\n continue;\n }\n\n \/\/ Otherwise, print the full path.\n OS << ActiveLibDir << '\/' << Lib;\n }\n }\n OS << '\\n';\n } else if (!Components.empty()) {\n errs() << \"llvm-config: error: components given, but unused\\n\\n\";\n usage();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"platform.hpp\"\n\n#include <stdexcept>\n#include <string>\n\n\n#define xfatal(MSG) \\\n\tdo { \\\n\t\tthrow std::runtime_error(std::string(__FILE__) + \":\" + std::to_string(__LINE__) + \" in \" + \\\n\t\t STX_FUNCTION + \" : \" + MSG); \\\n\t} while(false)\n\n#ifdef STX_DEBUG_TOOLS\n\n#define xassert(TEST) \\\n\tdo { \\\n\t\tif(!(TEST)) { xfatal(#TEST); } \\\n\t} while(false)\n\n#define xassertmsg(TEST, MSG) \\\n\tdo { \\\n\t\tif(!(TEST)) { xfatal(#TEST + MSG); } \\\n\t} while(false)\n\n#else \/\/ defined(STX_DEBUG_TOOLS)\n\n#define xassert(TEST) \\\n\tdo { TEST; } while(false)\n#define xassertmsg(TEST, MSG) \\\n\tdo { TEST; } while(false)\n\n#endif \/\/ defined(STX_DEBUG_TOOLS)\n\n#if STX_DEBUG_TOOLS > 0\n\n#include \"logging.hpp\"\n\nnamespace stx {\n\n\/\/\/ A class used for debugging which checks whether a returned value was handled\ntemplate <typename T>\nclass important {\n\tT m_value;\n\tmutable bool m_handled;\n\npublic:\n\tconstexpr important(bool val) : m_value(val), m_handled(false) {}\n\n\t~important() noexcept {\n\t\tif(!m_handled) {\n\t\t\tstx::warn(\"Unhandled important value! (important function result not handled)\");\n\t\t}\n\t}\n\n\tconstexpr inline operator T() const noexcept {\n\t\tm_handled = true;\n\t\treturn m_value;\n\t}\n};\n\n} \/\/ namespace stx\n\n#else \/\/ STX_DEBUG_TOOLS > 0\n\nnamespace stx {\n\ntemplate <typename T>\nusing important = bool;\n\n} \/\/ namespace stx\n\n#endif \/\/ STX_DEBUG_TOOLS > 0\n<commit_msg>Fixed assert giving unused value warnings<commit_after>#pragma once\n\n#include \"platform.hpp\"\n\n#include <stdexcept>\n#include <string>\n\n\n#define xfatal(MSG) \\\n\tdo { \\\n\t\tthrow std::runtime_error(std::string(__FILE__) + \":\" + std::to_string(__LINE__) + \" in \" + \\\n\t\t STX_FUNCTION + \" : \" + MSG); \\\n\t} while(false)\n\n#ifdef STX_DEBUG_TOOLS\n\n#define xassert(TEST) \\\n\tdo { \\\n\t\tif(!(TEST)) { xfatal(#TEST); } \\\n\t} while(false)\n\n#define xassertmsg(TEST, MSG) \\\n\tdo { \\\n\t\tif(!(TEST)) { xfatal(#TEST + MSG); } \\\n\t} while(false)\n\n#else \/\/ defined(STX_DEBUG_TOOLS)\n\n#define xassert(TEST) \\\n\tdo { if(TEST); } while(false) \/\/ The if is necessary to supress warnings\n#define xassertmsg(TEST, MSG) \\\n\tdo { if(TEST); } while(false)\n\n#endif \/\/ defined(STX_DEBUG_TOOLS)\n\n#if STX_DEBUG_TOOLS > 0\n\n#include \"logging.hpp\"\n\nnamespace stx {\n\n\/\/\/ A class used for debugging which checks whether a returned value was handled\ntemplate <typename T>\nclass important {\n\tT m_value;\n\tmutable bool m_handled;\n\npublic:\n\ttemplate<typename Tx> constexpr\n\timportant(Tx&& val) : m_value(val), m_handled(false) {}\n\n\t~important() noexcept {\n\t\tif(!m_handled) {\n\t\t\tstx::warn(\"Unhandled important value! (important function result not handled)\");\n\t\t}\n\t}\n\n\tconstexpr inline\n\toperator T() const noexcept {\n\t\tm_handled = true;\n\t\treturn std::move(m_value);\n\t}\n};\n\n} \/\/ namespace stx\n\n#else \/\/ STX_DEBUG_TOOLS > 0\n\nnamespace stx {\n\ntemplate<typename T>\nusing important = T;\n\n} \/\/ namespace stx\n\n#endif \/\/ STX_DEBUG_TOOLS > 0\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <sal\/config.h>\n\n#include <boost\/noncopyable.hpp>\n#include <tools\/debug.hxx>\n#include <sal\/types.h>\n#include <vcl\/lstbox.hxx>\n#include <vcl\/toolbox.hxx>\n#include <vcl\/event.hxx>\n#include <sfx2\/app.hxx>\n#include <sfx2\/tbxctrl.hxx>\n#include <sfx2\/bindings.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/viewsh.hxx>\n#include <svl\/intitem.hxx>\n#include <svl\/eitem.hxx>\n#include <svtools\/stdctrl.hxx>\n#include <svl\/slstitm.hxx>\n#include <svl\/stritem.hxx>\n#include <svx\/dialmgr.hxx>\n#include <svx\/lboxctrl.hxx>\n#include <vcl\/mnemonic.hxx>\n#include <vcl\/settings.hxx>\n#include <tools\/urlobj.hxx>\n\n#include <svx\/svxids.hrc>\n#include <svx\/dialogs.hrc>\n\n#include \"lboxctrl.hrc\"\n\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::frame;\n\nclass SvxPopupWindowListBox;\n\n\n\nclass SvxPopupWindowListBox: public SfxPopupWindow, private boost::noncopyable\n{\n using FloatingWindow::StateChanged;\n\n ListBox * pListBox;\n ToolBox & rToolBox;\n bool bUserSel;\n sal_uInt16 nTbxId;\n OUString maCommandURL;\n \/\/ disallow copy-constructor and assignment-operator\n\n\/\/ SvxPopupWindowListBox( sal_uInt16 nSlotId, ToolBox& rTbx, sal_uInt16 nTbxItemId );\n\npublic:\n SvxPopupWindowListBox( sal_uInt16 nSlotId, const OUString& rCommandURL, sal_uInt16 nTbxId, ToolBox& rTbx );\n virtual ~SvxPopupWindowListBox();\n\n \/\/ SfxPopupWindow\n virtual SfxPopupWindow * Clone() const SAL_OVERRIDE;\n virtual void PopupModeEnd() SAL_OVERRIDE;\n virtual void StateChanged( sal_uInt16 nSID, SfxItemState eState,\n const SfxPoolItem* pState ) SAL_OVERRIDE;\n\n inline ListBox & GetListBox() { return *pListBox; }\n\n bool IsUserSelected() const { return bUserSel; }\n void SetUserSelected( bool bVal ) { bUserSel = bVal; }\n \/*virtual*\/Window* GetPreferredKeyInputWindow() SAL_OVERRIDE;\n};\n\n\n\nSvxPopupWindowListBox::SvxPopupWindowListBox( sal_uInt16 nSlotId, const OUString& rCommandURL, sal_uInt16 nId, ToolBox& rTbx ) :\n SfxPopupWindow( nSlotId, Reference< XFrame >(), SVX_RES( RID_SVXTBX_UNDO_REDO_CTRL ) ),\n rToolBox ( rTbx ),\n bUserSel ( false ),\n nTbxId ( nId ),\n maCommandURL( rCommandURL )\n{\n DBG_ASSERT( nSlotId == GetId(), \"id mismatch\" );\n pListBox = new ListBox( this, SVX_RES( LB_SVXTBX_UNDO_REDO_CTRL ) );\n FreeResource();\n pListBox->EnableMultiSelection( true, true );\n SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );\n AddStatusListener( rCommandURL );\n}\n\n\nSvxPopupWindowListBox::~SvxPopupWindowListBox()\n{\n delete pListBox;\n}\n\n\nSfxPopupWindow* SvxPopupWindowListBox::Clone() const\n{\n return new SvxPopupWindowListBox( GetId(), maCommandURL, nTbxId, rToolBox );\n}\n\n\nvoid SvxPopupWindowListBox::PopupModeEnd()\n{\n rToolBox.EndSelection();\n SfxPopupWindow::PopupModeEnd();\n \/\/FloatingWindow::PopupModeEnd();\n\n if( SfxViewShell::Current() )\n {\n Window* pShellWnd = SfxViewShell::Current()->GetWindow();\n if (pShellWnd)\n pShellWnd->GrabFocus();\n }\n}\n\n\nvoid SvxPopupWindowListBox::StateChanged(\n sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n rToolBox.EnableItem( nTbxId, ( SfxToolBoxControl::GetItemState( pState ) != SFX_ITEM_DISABLED) );\n SfxPopupWindow::StateChanged( nSID, eState, pState );\n}\n\nWindow* SvxPopupWindowListBox::GetPreferredKeyInputWindow()\n{\n \/\/ allows forwarding key events in the correct window\n \/\/ without setting the focus\n return pListBox->GetPreferredKeyInputWindow();\n}\n\n\n\nSvxListBoxControl::SvxListBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )\n :SfxToolBoxControl( nSlotId, nId, rTbx ),\n pPopupWin ( 0 )\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n rTbx.Invalidate();\n}\n\n\nSvxListBoxControl::~SvxListBoxControl()\n{\n}\n\n\nSfxPopupWindow* SvxListBoxControl::CreatePopupWindow()\n{\n OSL_FAIL( \"not implemented\" );\n return 0;\n}\n\n\nSfxPopupWindowType SvxListBoxControl::GetPopupWindowType() const\n{\n return SFX_POPUPWINDOW_ONTIMEOUT;\n}\n\n\nvoid SvxListBoxControl::StateChanged(\n sal_uInt16, SfxItemState, const SfxPoolItem* pState )\n{\n GetToolBox().EnableItem( GetId(),\n SFX_ITEM_DISABLED != GetItemState(pState) );\n}\n\n\nIMPL_LINK_NOARG(SvxListBoxControl, PopupModeEndHdl)\n{\n if( pPopupWin && 0 == pPopupWin->GetPopupModeFlags() &&\n pPopupWin->IsUserSelected() )\n {\n sal_uInt16 nCount = pPopupWin->GetListBox().GetSelectEntryCount();\n\n INetURLObject aObj( m_aCommandURL );\n\n Sequence< PropertyValue > aArgs( 1 );\n aArgs[0].Name = aObj.GetURLPath();\n aArgs[0].Value = makeAny( sal_Int16( nCount ));\n SfxToolBoxControl::Dispatch( m_aCommandURL, aArgs );\n }\n return 0;\n}\n\n\nvoid SvxListBoxControl::Impl_SetInfo( sal_uInt16 nCount )\n{\n DBG_ASSERT( pPopupWin, \"NULL pointer, PopupWindow missing\" );\n\n\/\/ ListBox &rListBox = pPopupWin->GetListBox();\n\n sal_uInt16 nId;\n if (nCount == 1)\n nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTION : RID_SVXSTR_NUM_REDO_ACTION;\n else\n nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS;\n\n aActionStr = SVX_RESSTR(nId);\n\n OUString aText = aActionStr.replaceAll(\"$(ARG1)\", OUString::number(nCount));\n pPopupWin->SetText(aText);\n}\n\n\nIMPL_LINK_NOARG(SvxListBoxControl, SelectHdl)\n{\n if (pPopupWin)\n {\n \/\/pPopupWin->SetUserSelected( false );\n\n ListBox &rListBox = pPopupWin->GetListBox();\n if (rListBox.IsTravelSelect())\n Impl_SetInfo( rListBox.GetSelectEntryCount() );\n else\n {\n pPopupWin->SetUserSelected( true );\n pPopupWin->EndPopupMode( 0 );\n }\n }\n return 0;\n}\n\n\n\nSFX_IMPL_TOOLBOX_CONTROL( SvxUndoRedoControl, SfxStringItem );\n\nSvxUndoRedoControl::SvxUndoRedoControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )\n : SvxListBoxControl( nSlotId, nId, rTbx )\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n rTbx.Invalidate();\n aDefaultText = MnemonicGenerator::EraseAllMnemonicChars( rTbx.GetItemText( nId ) );\n}\n\nSvxUndoRedoControl::~SvxUndoRedoControl()\n{\n}\n\nvoid SvxUndoRedoControl::StateChanged(\n sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n if ( nSID == SID_UNDO || nSID == SID_REDO )\n {\n if ( eState == SFX_ITEM_DISABLED )\n {\n ToolBox& rBox = GetToolBox();\n rBox.SetQuickHelpText( GetId(), aDefaultText );\n }\n else if ( pState && pState->ISA( SfxStringItem ) )\n {\n SfxStringItem& rItem = *(SfxStringItem *)pState;\n ToolBox& rBox = GetToolBox();\n OUString aQuickHelpText = MnemonicGenerator::EraseAllMnemonicChars( rItem.GetValue() );\n rBox.SetQuickHelpText( GetId(), aQuickHelpText );\n }\n SvxListBoxControl::StateChanged( nSID, eState, pState );\n }\n else\n {\n aUndoRedoList.clear();\n\n if ( pState && pState->ISA( SfxStringListItem ) )\n {\n SfxStringListItem &rItem = *(SfxStringListItem *)pState;\n\n const std::vector<OUString> &aLst = rItem.GetList();\n for( long nI = 0, nEnd = aLst.size(); nI < nEnd; ++nI )\n aUndoRedoList.push_back( aLst[nI] );\n }\n }\n}\n\nSfxPopupWindow* SvxUndoRedoControl::CreatePopupWindow()\n{\n DBG_ASSERT(( SID_UNDO == GetSlotId() || SID_REDO == GetSlotId() ), \"mismatching ids\" );\n\n if ( m_aCommandURL == \".uno:Undo\" )\n updateStatus( OUString( \".uno:GetUndoStrings\" ));\n else\n updateStatus( OUString( \".uno:GetRedoStrings\" ));\n\n ToolBox& rBox = GetToolBox();\n\n pPopupWin = new SvxPopupWindowListBox( GetSlotId(), m_aCommandURL, GetId(), rBox );\n pPopupWin->SetPopupModeEndHdl( LINK( this, SvxUndoRedoControl,\n PopupModeEndHdl ) );\n ListBox &rListBox = pPopupWin->GetListBox();\n rListBox.SetSelectHdl( LINK( this, SvxUndoRedoControl, SelectHdl ) );\n\n for( sal_uInt32 n = 0; n < aUndoRedoList.size(); n++ )\n rListBox.InsertEntry( aUndoRedoList[n] );\n\n rListBox.SelectEntryPos( 0 );\n aActionStr = SVX_RESSTR(SID_UNDO == GetSlotId() ?\n RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS);\n Impl_SetInfo( rListBox.GetSelectEntryCount() );\n\n \/\/ move focus in floating window without\n \/\/ closing it (GrabFocus() would close it!)\n pPopupWin->StartPopupMode( &rBox, FLOATWIN_POPUPMODE_GRABFOCUS );\n \/\/pPopupWin->GetListBox().GrabFocus();\n\n return pPopupWin;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>SvxPopupWindowListBox: avoid inheriting from boost::noncopyable two times<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <sal\/config.h>\n\n#include <boost\/noncopyable.hpp>\n#include <tools\/debug.hxx>\n#include <sal\/types.h>\n#include <vcl\/lstbox.hxx>\n#include <vcl\/toolbox.hxx>\n#include <vcl\/event.hxx>\n#include <sfx2\/app.hxx>\n#include <sfx2\/tbxctrl.hxx>\n#include <sfx2\/bindings.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/viewsh.hxx>\n#include <svl\/intitem.hxx>\n#include <svl\/eitem.hxx>\n#include <svtools\/stdctrl.hxx>\n#include <svl\/slstitm.hxx>\n#include <svl\/stritem.hxx>\n#include <svx\/dialmgr.hxx>\n#include <svx\/lboxctrl.hxx>\n#include <vcl\/mnemonic.hxx>\n#include <vcl\/settings.hxx>\n#include <tools\/urlobj.hxx>\n\n#include <svx\/svxids.hrc>\n#include <svx\/dialogs.hrc>\n\n#include \"lboxctrl.hrc\"\n\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::frame;\n\nclass SvxPopupWindowListBox;\n\n\n\nclass SvxPopupWindowListBox: public SfxPopupWindow\n{\n using FloatingWindow::StateChanged;\n\n ListBox * pListBox;\n ToolBox & rToolBox;\n bool bUserSel;\n sal_uInt16 nTbxId;\n OUString maCommandURL;\n \/\/ disallow copy-constructor and assignment-operator\n\n\/\/ SvxPopupWindowListBox( sal_uInt16 nSlotId, ToolBox& rTbx, sal_uInt16 nTbxItemId );\n\npublic:\n SvxPopupWindowListBox( sal_uInt16 nSlotId, const OUString& rCommandURL, sal_uInt16 nTbxId, ToolBox& rTbx );\n virtual ~SvxPopupWindowListBox();\n\n \/\/ SfxPopupWindow\n virtual SfxPopupWindow * Clone() const SAL_OVERRIDE;\n virtual void PopupModeEnd() SAL_OVERRIDE;\n virtual void StateChanged( sal_uInt16 nSID, SfxItemState eState,\n const SfxPoolItem* pState ) SAL_OVERRIDE;\n\n inline ListBox & GetListBox() { return *pListBox; }\n\n bool IsUserSelected() const { return bUserSel; }\n void SetUserSelected( bool bVal ) { bUserSel = bVal; }\n \/*virtual*\/Window* GetPreferredKeyInputWindow() SAL_OVERRIDE;\n};\n\n\n\nSvxPopupWindowListBox::SvxPopupWindowListBox( sal_uInt16 nSlotId, const OUString& rCommandURL, sal_uInt16 nId, ToolBox& rTbx ) :\n SfxPopupWindow( nSlotId, Reference< XFrame >(), SVX_RES( RID_SVXTBX_UNDO_REDO_CTRL ) ),\n rToolBox ( rTbx ),\n bUserSel ( false ),\n nTbxId ( nId ),\n maCommandURL( rCommandURL )\n{\n DBG_ASSERT( nSlotId == GetId(), \"id mismatch\" );\n pListBox = new ListBox( this, SVX_RES( LB_SVXTBX_UNDO_REDO_CTRL ) );\n FreeResource();\n pListBox->EnableMultiSelection( true, true );\n SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );\n AddStatusListener( rCommandURL );\n}\n\n\nSvxPopupWindowListBox::~SvxPopupWindowListBox()\n{\n delete pListBox;\n}\n\n\nSfxPopupWindow* SvxPopupWindowListBox::Clone() const\n{\n return new SvxPopupWindowListBox( GetId(), maCommandURL, nTbxId, rToolBox );\n}\n\n\nvoid SvxPopupWindowListBox::PopupModeEnd()\n{\n rToolBox.EndSelection();\n SfxPopupWindow::PopupModeEnd();\n \/\/FloatingWindow::PopupModeEnd();\n\n if( SfxViewShell::Current() )\n {\n Window* pShellWnd = SfxViewShell::Current()->GetWindow();\n if (pShellWnd)\n pShellWnd->GrabFocus();\n }\n}\n\n\nvoid SvxPopupWindowListBox::StateChanged(\n sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n rToolBox.EnableItem( nTbxId, ( SfxToolBoxControl::GetItemState( pState ) != SFX_ITEM_DISABLED) );\n SfxPopupWindow::StateChanged( nSID, eState, pState );\n}\n\nWindow* SvxPopupWindowListBox::GetPreferredKeyInputWindow()\n{\n \/\/ allows forwarding key events in the correct window\n \/\/ without setting the focus\n return pListBox->GetPreferredKeyInputWindow();\n}\n\n\n\nSvxListBoxControl::SvxListBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )\n :SfxToolBoxControl( nSlotId, nId, rTbx ),\n pPopupWin ( 0 )\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n rTbx.Invalidate();\n}\n\n\nSvxListBoxControl::~SvxListBoxControl()\n{\n}\n\n\nSfxPopupWindow* SvxListBoxControl::CreatePopupWindow()\n{\n OSL_FAIL( \"not implemented\" );\n return 0;\n}\n\n\nSfxPopupWindowType SvxListBoxControl::GetPopupWindowType() const\n{\n return SFX_POPUPWINDOW_ONTIMEOUT;\n}\n\n\nvoid SvxListBoxControl::StateChanged(\n sal_uInt16, SfxItemState, const SfxPoolItem* pState )\n{\n GetToolBox().EnableItem( GetId(),\n SFX_ITEM_DISABLED != GetItemState(pState) );\n}\n\n\nIMPL_LINK_NOARG(SvxListBoxControl, PopupModeEndHdl)\n{\n if( pPopupWin && 0 == pPopupWin->GetPopupModeFlags() &&\n pPopupWin->IsUserSelected() )\n {\n sal_uInt16 nCount = pPopupWin->GetListBox().GetSelectEntryCount();\n\n INetURLObject aObj( m_aCommandURL );\n\n Sequence< PropertyValue > aArgs( 1 );\n aArgs[0].Name = aObj.GetURLPath();\n aArgs[0].Value = makeAny( sal_Int16( nCount ));\n SfxToolBoxControl::Dispatch( m_aCommandURL, aArgs );\n }\n return 0;\n}\n\n\nvoid SvxListBoxControl::Impl_SetInfo( sal_uInt16 nCount )\n{\n DBG_ASSERT( pPopupWin, \"NULL pointer, PopupWindow missing\" );\n\n\/\/ ListBox &rListBox = pPopupWin->GetListBox();\n\n sal_uInt16 nId;\n if (nCount == 1)\n nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTION : RID_SVXSTR_NUM_REDO_ACTION;\n else\n nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS;\n\n aActionStr = SVX_RESSTR(nId);\n\n OUString aText = aActionStr.replaceAll(\"$(ARG1)\", OUString::number(nCount));\n pPopupWin->SetText(aText);\n}\n\n\nIMPL_LINK_NOARG(SvxListBoxControl, SelectHdl)\n{\n if (pPopupWin)\n {\n \/\/pPopupWin->SetUserSelected( false );\n\n ListBox &rListBox = pPopupWin->GetListBox();\n if (rListBox.IsTravelSelect())\n Impl_SetInfo( rListBox.GetSelectEntryCount() );\n else\n {\n pPopupWin->SetUserSelected( true );\n pPopupWin->EndPopupMode( 0 );\n }\n }\n return 0;\n}\n\n\n\nSFX_IMPL_TOOLBOX_CONTROL( SvxUndoRedoControl, SfxStringItem );\n\nSvxUndoRedoControl::SvxUndoRedoControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )\n : SvxListBoxControl( nSlotId, nId, rTbx )\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n rTbx.Invalidate();\n aDefaultText = MnemonicGenerator::EraseAllMnemonicChars( rTbx.GetItemText( nId ) );\n}\n\nSvxUndoRedoControl::~SvxUndoRedoControl()\n{\n}\n\nvoid SvxUndoRedoControl::StateChanged(\n sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n if ( nSID == SID_UNDO || nSID == SID_REDO )\n {\n if ( eState == SFX_ITEM_DISABLED )\n {\n ToolBox& rBox = GetToolBox();\n rBox.SetQuickHelpText( GetId(), aDefaultText );\n }\n else if ( pState && pState->ISA( SfxStringItem ) )\n {\n SfxStringItem& rItem = *(SfxStringItem *)pState;\n ToolBox& rBox = GetToolBox();\n OUString aQuickHelpText = MnemonicGenerator::EraseAllMnemonicChars( rItem.GetValue() );\n rBox.SetQuickHelpText( GetId(), aQuickHelpText );\n }\n SvxListBoxControl::StateChanged( nSID, eState, pState );\n }\n else\n {\n aUndoRedoList.clear();\n\n if ( pState && pState->ISA( SfxStringListItem ) )\n {\n SfxStringListItem &rItem = *(SfxStringListItem *)pState;\n\n const std::vector<OUString> &aLst = rItem.GetList();\n for( long nI = 0, nEnd = aLst.size(); nI < nEnd; ++nI )\n aUndoRedoList.push_back( aLst[nI] );\n }\n }\n}\n\nSfxPopupWindow* SvxUndoRedoControl::CreatePopupWindow()\n{\n DBG_ASSERT(( SID_UNDO == GetSlotId() || SID_REDO == GetSlotId() ), \"mismatching ids\" );\n\n if ( m_aCommandURL == \".uno:Undo\" )\n updateStatus( OUString( \".uno:GetUndoStrings\" ));\n else\n updateStatus( OUString( \".uno:GetRedoStrings\" ));\n\n ToolBox& rBox = GetToolBox();\n\n pPopupWin = new SvxPopupWindowListBox( GetSlotId(), m_aCommandURL, GetId(), rBox );\n pPopupWin->SetPopupModeEndHdl( LINK( this, SvxUndoRedoControl,\n PopupModeEndHdl ) );\n ListBox &rListBox = pPopupWin->GetListBox();\n rListBox.SetSelectHdl( LINK( this, SvxUndoRedoControl, SelectHdl ) );\n\n for( sal_uInt32 n = 0; n < aUndoRedoList.size(); n++ )\n rListBox.InsertEntry( aUndoRedoList[n] );\n\n rListBox.SelectEntryPos( 0 );\n aActionStr = SVX_RESSTR(SID_UNDO == GetSlotId() ?\n RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS);\n Impl_SetInfo( rListBox.GetSelectEntryCount() );\n\n \/\/ move focus in floating window without\n \/\/ closing it (GrabFocus() would close it!)\n pPopupWin->StartPopupMode( &rBox, FLOATWIN_POPUPMODE_GRABFOCUS );\n \/\/pPopupWin->GetListBox().GrabFocus();\n\n return pPopupWin;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tablink.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: kz $ $Date: 2005-01-13 18:57:31 $\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_TABLINK_HXX\n#define SC_TABLINK_HXX\n\n#ifndef INCLUDED_SCDLLAPI_H\n#include \"scdllapi.h\"\n#endif\n\n#ifndef SC_REFRESHTIMER_HXX\n#include \"refreshtimer.hxx\"\n#endif\n\n\/\/REMOVE #ifndef _EMBOBJ_HXX\n\/\/REMOVE #include <so3\/embobj.hxx>\n\/\/REMOVE #endif\n\n#ifndef _LNKBASE_HXX \/\/autogen\n#include <sfx2\/lnkbase.hxx>\n#endif\n\n#include <sfx2\/objsh.hxx>\n\/\/REMOVE #ifndef SO2_DECL_SVEMBEDDEDOBJECT_DEFINED\n\/\/REMOVE #define SO2_DECL_SVEMBEDDEDOBJECT_DEFINED\n\/\/REMOVE SO2_DECL_REF(SvEmbeddedObject)\n\/\/REMOVE #endif\n\nclass ScDocShell;\n\nclass ScTableLink : public ::sfx2::SvBaseLink, public ScRefreshTimer\n{\nprivate:\n ScDocShell* pDocShell; \/\/ Container\n String aFileName;\n String aFilterName;\n String aOptions;\n BOOL bInCreate;\n BOOL bInEdit;\n BOOL bAddUndo;\n BOOL bDoPaint;\n\npublic:\n TYPEINFO();\n ScTableLink( ScDocShell* pDocSh, const String& rFile,\n const String& rFilter, const String& rOpt, ULONG nRefresh );\n ScTableLink( SfxObjectShell* pShell, const String& rFile,\n const String& rFilter, const String& rOpt, ULONG nRefresh );\n virtual ~ScTableLink();\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* pNewOptions \/* = NULL *\/, ULONG nNewRefresh );\n void SetInCreate(BOOL bSet) { bInCreate = bSet; }\n void SetAddUndo(BOOL bSet) { bAddUndo = bSet; }\n void SetPaint(BOOL bSet) { bDoPaint = bSet; }\n\n const String& GetFileName() const { return aFileName; }\n const String& GetFilterName() const { return aFilterName; }\n const String& GetOptions() const { return aOptions; }\n\n BOOL IsUsed() const;\n\n DECL_LINK( RefreshHdl, ScTableLink* );\n\n};\n\n\nclass ScDocument;\nclass SfxMedium;\n\nclass SC_DLLPUBLIC ScDocumentLoader\n{\nprivate:\n ScDocShell* pDocShell;\n SfxObjectShellRef aRef;\n SfxMedium* pMedium;\n\npublic:\n ScDocumentLoader( const String& rFileName,\n String& rFilterName, String& rOptions,\n UINT32 nRekCnt = 0, BOOL bWithInteraction = FALSE );\n ~ScDocumentLoader();\n ScDocument* GetDocument();\n ScDocShell* GetDocShell() { return pDocShell; }\n BOOL IsError() const;\n String GetTitle() const;\n\n void ReleaseDocRef(); \/\/ without calling DoClose\n\n static String GetOptions( SfxMedium& rMedium );\n\n \/** Returns the filter name and options from a file name.\n @param bWithContent\n true = Tries to detect the filter by looking at the file contents.\n false = Detects filter by file name extension only (should be used in filter code only).\n @return TRUE if a filter could be found, FALSE otherwise. *\/\n static BOOL GetFilterName( const String& rFileName,\n String& rFilter, String& rOptions,\n BOOL bWithContent );\n\n static void RemoveAppPrefix( String& rFilterName );\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.13.192); FILE MERGED 2005\/09\/05 15:01:02 rt 1.13.192.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tablink.hxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 18:00:03 $\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_TABLINK_HXX\n#define SC_TABLINK_HXX\n\n#ifndef INCLUDED_SCDLLAPI_H\n#include \"scdllapi.h\"\n#endif\n\n#ifndef SC_REFRESHTIMER_HXX\n#include \"refreshtimer.hxx\"\n#endif\n\n\/\/REMOVE #ifndef _EMBOBJ_HXX\n\/\/REMOVE #include <so3\/embobj.hxx>\n\/\/REMOVE #endif\n\n#ifndef _LNKBASE_HXX \/\/autogen\n#include <sfx2\/lnkbase.hxx>\n#endif\n\n#include <sfx2\/objsh.hxx>\n\/\/REMOVE #ifndef SO2_DECL_SVEMBEDDEDOBJECT_DEFINED\n\/\/REMOVE #define SO2_DECL_SVEMBEDDEDOBJECT_DEFINED\n\/\/REMOVE SO2_DECL_REF(SvEmbeddedObject)\n\/\/REMOVE #endif\n\nclass ScDocShell;\n\nclass ScTableLink : public ::sfx2::SvBaseLink, public ScRefreshTimer\n{\nprivate:\n ScDocShell* pDocShell; \/\/ Container\n String aFileName;\n String aFilterName;\n String aOptions;\n BOOL bInCreate;\n BOOL bInEdit;\n BOOL bAddUndo;\n BOOL bDoPaint;\n\npublic:\n TYPEINFO();\n ScTableLink( ScDocShell* pDocSh, const String& rFile,\n const String& rFilter, const String& rOpt, ULONG nRefresh );\n ScTableLink( SfxObjectShell* pShell, const String& rFile,\n const String& rFilter, const String& rOpt, ULONG nRefresh );\n virtual ~ScTableLink();\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* pNewOptions \/* = NULL *\/, ULONG nNewRefresh );\n void SetInCreate(BOOL bSet) { bInCreate = bSet; }\n void SetAddUndo(BOOL bSet) { bAddUndo = bSet; }\n void SetPaint(BOOL bSet) { bDoPaint = bSet; }\n\n const String& GetFileName() const { return aFileName; }\n const String& GetFilterName() const { return aFilterName; }\n const String& GetOptions() const { return aOptions; }\n\n BOOL IsUsed() const;\n\n DECL_LINK( RefreshHdl, ScTableLink* );\n\n};\n\n\nclass ScDocument;\nclass SfxMedium;\n\nclass SC_DLLPUBLIC ScDocumentLoader\n{\nprivate:\n ScDocShell* pDocShell;\n SfxObjectShellRef aRef;\n SfxMedium* pMedium;\n\npublic:\n ScDocumentLoader( const String& rFileName,\n String& rFilterName, String& rOptions,\n UINT32 nRekCnt = 0, BOOL bWithInteraction = FALSE );\n ~ScDocumentLoader();\n ScDocument* GetDocument();\n ScDocShell* GetDocShell() { return pDocShell; }\n BOOL IsError() const;\n String GetTitle() const;\n\n void ReleaseDocRef(); \/\/ without calling DoClose\n\n static String GetOptions( SfxMedium& rMedium );\n\n \/** Returns the filter name and options from a file name.\n @param bWithContent\n true = Tries to detect the filter by looking at the file contents.\n false = Detects filter by file name extension only (should be used in filter code only).\n @return TRUE if a filter could be found, FALSE otherwise. *\/\n static BOOL GetFilterName( const String& rFileName,\n String& rFilter, String& rOptions,\n BOOL bWithContent );\n\n static void RemoveAppPrefix( String& rFilterName );\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: IDocumentOutlineNodes.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2008-02-26 10:28:14 $\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 IDOCUMENTOUTLINENODES_HXX_INCLUDED\n#define IDOCUMENTOUTLINENODES_HXX_INCLUDED\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#include <tools\/string.hxx>\n#include <vector>\nclass SwTxtNode;\n\n\/** Provides outline nodes of a document.\n*\/\nclass IDocumentOutlineNodes\n{\npublic:\n typedef ::std::vector< const SwTxtNode* > tSortedOutlineNodeList;\n\n virtual sal_Int32 getOutlineNodesCount() const = 0;\n\n virtual int getOutlineLevel( const sal_Int32 nIdx ) const = 0;\n virtual String getOutlineText( const sal_Int32 nIdx,\n const bool bWithNumber = true,\n const bool bWithSpacesForLevel = false ) const = 0;\n virtual SwTxtNode* getOutlineNode( const sal_Int32 nIdx ) const = 0;\n\n virtual void getOutlineNodes( IDocumentOutlineNodes::tSortedOutlineNodeList& orOutlineNodeList ) const = 0;\n\nprotected:\n virtual ~IDocumentOutlineNodes() {};\n};\n\n #endif \/\/ IDOCUMENTOUTLINENODES_HXX_INCLUDED\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.58); FILE MERGED 2008\/04\/01 15:56:05 thb 1.2.58.2: #i85898# Stripping all external header guards 2008\/03\/31 16:52:32 rt 1.2.58.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\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: IDocumentOutlineNodes.hxx,v $\n * $Revision: 1.3 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef IDOCUMENTOUTLINENODES_HXX_INCLUDED\n#define IDOCUMENTOUTLINENODES_HXX_INCLUDED\n\n#include <sal\/types.h>\n#include <tools\/string.hxx>\n#include <vector>\nclass SwTxtNode;\n\n\/** Provides outline nodes of a document.\n*\/\nclass IDocumentOutlineNodes\n{\npublic:\n typedef ::std::vector< const SwTxtNode* > tSortedOutlineNodeList;\n\n virtual sal_Int32 getOutlineNodesCount() const = 0;\n\n virtual int getOutlineLevel( const sal_Int32 nIdx ) const = 0;\n virtual String getOutlineText( const sal_Int32 nIdx,\n const bool bWithNumber = true,\n const bool bWithSpacesForLevel = false ) const = 0;\n virtual SwTxtNode* getOutlineNode( const sal_Int32 nIdx ) const = 0;\n\n virtual void getOutlineNodes( IDocumentOutlineNodes::tSortedOutlineNodeList& orOutlineNodeList ) const = 0;\n\nprotected:\n virtual ~IDocumentOutlineNodes() {};\n};\n\n #endif \/\/ IDOCUMENTOUTLINENODES_HXX_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: chpfld.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: mba $ $Date: 2002-05-27 14:32:25 $\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#ifdef PRECOMPILED\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#ifndef _COM_SUN_STAR_TEXT_CHAPTERFORMAT_HPP_\n#include <com\/sun\/star\/text\/ChapterFormat.hpp>\n#endif\n\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _FRAME_HXX\n#include <frame.hxx> \/\/ SwChapterFieldType::ChangeExpansion()\n#endif\n#ifndef _PAM_HXX\n#include <pam.hxx> \/\/ fuer GetBodyTxtNode\n#endif\n#ifndef _NDTXT_HXX\n#include <ndtxt.hxx>\n#endif\n#ifndef _CHPFLD_HXX\n#include <chpfld.hxx>\n#endif\n#ifndef _EXPFLD_HXX\n#include <expfld.hxx> \/\/ fuer GetBodyTxtNode\n#endif\n#ifndef _UNOFLDMID_H\n#include <unofldmid.h>\n#endif\n\nusing namespace ::com::sun::star;\n\n\/*--------------------------------------------------------------------\n Beschreibung: SwChapterFieldType\n --------------------------------------------------------------------*\/\n\n\nSwChapterFieldType::SwChapterFieldType()\n : SwFieldType( RES_CHAPTERFLD )\n{\n}\n\n\nSwFieldType* SwChapterFieldType::Copy() const\n{\n return new SwChapterFieldType();\n}\n\n\n\/*--------------------------------------------------------------------\n Beschreibung: Kapittelfeld\n --------------------------------------------------------------------*\/\n\n\nSwChapterField::SwChapterField(SwChapterFieldType* pTyp, sal_uInt32 nFmt)\n : SwField(pTyp, nFmt), nLevel( 0 )\n{}\n\n\nString SwChapterField::Expand() const\n{\n String sStr( sNumber );\n switch( GetFormat() )\n {\n case CF_TITLE: sStr = sTitle; break;\n\n case CF_NUMBER:\n case CF_NUM_TITLE: sStr.Insert( sPre, 0 );\n sStr += sPost;\n if( CF_NUM_TITLE == GetFormat() )\n sStr += sTitle;\n break;\n\n case CF_NUM_NOPREPST_TITLE: sStr += sTitle; break;\n }\n return sStr;\n}\n\n\nSwField* SwChapterField::Copy() const\n{\n SwChapterField *pTmp =\n new SwChapterField((SwChapterFieldType*)GetTyp(), GetFormat());\n pTmp->nLevel = nLevel;\n pTmp->sTitle = sTitle;\n pTmp->sNumber = sNumber;\n pTmp->sPost = sPost;\n pTmp->sPre = sPre;\n\n return pTmp;\n}\n\n\nvoid SwChapterField::ChangeExpansion( const SwFrm* pFrm,\n const SwTxtNode* pTxtNd,\n sal_Bool bSrchNum )\n{\n ASSERT( pFrm, \"in welchem Frame stehe ich denn?\" )\n SwDoc* pDoc = (SwDoc*)pTxtNd->GetDoc();\n SwPosition aPos( pDoc->GetNodes().GetEndOfContent() );\n\n if( pFrm->IsInDocBody() )\n aPos.nNode = *pTxtNd;\n else if( 0 == (pTxtNd = GetBodyTxtNode( *pDoc, aPos, *pFrm )) )\n \/\/ kein TxtNode (Formatierung Kopf\/Fusszeile)\n return;\n\n ASSERT( pTxtNd, \"Wo steht das Feld\" );\n pTxtNd = pTxtNd->FindOutlineNodeOfLevel( nLevel );\n if( pTxtNd )\n {\n if( bSrchNum )\n {\n const SwTxtNode* pONd = pTxtNd;\n do {\n if( pONd && pONd->GetTxtColl() )\n {\n BYTE nPrevLvl = nLevel;\n nLevel = GetRealLevel( pONd->GetTxtColl()->\n GetOutlineLevel() );\n if( nPrevLvl < nLevel )\n nLevel = nPrevLvl;\n else if( SVX_NUM_NUMBER_NONE != pDoc->GetOutlineNumRule()\n ->Get( nLevel ).GetNumberingType() )\n {\n pTxtNd = pONd;\n break;\n }\n\n if( !nLevel-- )\n break;\n pONd = pTxtNd->FindOutlineNodeOfLevel( nLevel );\n }\n else\n break;\n } while( sal_True );\n }\n\n const SwNodeNum& rNum = *pTxtNd->GetOutlineNum();\n \/\/ nur die Nummer besorgen, ohne Pre-\/Post-fixstrings\n sNumber = pDoc->GetOutlineNumRule()->MakeNumString( rNum, sal_False );\n\n if( NO_NUM > rNum.GetLevel() && !( NO_NUMLEVEL & rNum.GetLevel() ) )\n {\n const SwNumFmt& rNFmt = pDoc->GetOutlineNumRule()->Get( rNum.GetLevel() );\n sPost = rNFmt.GetSuffix();\n sPre = rNFmt.GetPrefix();\n }\n else\n sPost = aEmptyStr, sPre = aEmptyStr;\n\n sTitle = pTxtNd->GetExpandTxt();\n\n for( xub_StrLen i = 0; i < sTitle.Len(); ++i )\n if( ' ' > sTitle.GetChar( i ) )\n sTitle.Erase( i--, 1 );\n }\n else\n {\n sNumber = aEmptyStr;\n sTitle = aEmptyStr;\n sPost = aEmptyStr;\n sPre = aEmptyStr;\n }\n}\n\n\/*-----------------05.03.98 16:19-------------------\n\n--------------------------------------------------*\/\nBOOL SwChapterField::QueryValue( com::sun::star::uno::Any& rAny, BYTE nMId ) const\n{\n nMId &= ~CONVERT_TWIPS;\n switch( nMId )\n {\n case FIELD_PROP_BYTE1:\n rAny <<= (sal_Int8)nLevel;\n break;\n\n case FIELD_PROP_USHORT1:\n {\n sal_Int16 nRet;\n switch( GetFormat() )\n {\n case CF_NUMBER: nRet = text::ChapterFormat::NUMBER; break;\n case CF_TITLE: nRet = text::ChapterFormat::NAME; break;\n case CF_NUMBER_NOPREPST:\n nRet = text::ChapterFormat::DIGIT;\n break;\n case CF_NUM_NOPREPST_TITLE:\n nRet = text::ChapterFormat::NO_PREFIX_SUFFIX;\n break;\n case CF_NUM_TITLE:\n default: nRet = text::ChapterFormat::NAME_NUMBER;\n }\n rAny <<= nRet;\n }\n break;\n\n default:\n DBG_ERROR(\"illegal property\");\n }\n return sal_True;\n}\n\/*-----------------05.03.98 16:19-------------------\n\n--------------------------------------------------*\/\nBOOL SwChapterField::PutValue( const com::sun::star::uno::Any& rAny, BYTE nMId )\n{\n BOOL bRet = TRUE;\n nMId &= ~CONVERT_TWIPS;\n switch( nMId )\n {\n case FIELD_PROP_BYTE1:\n sal_Int8 nTmp;\n rAny >>= nTmp;\n if(nTmp >= 0 && nTmp < MAXLEVEL)\n nLevel = nTmp;\n else\n bRet = FALSE;\n break;\n\n case FIELD_PROP_USHORT1:\n {\n sal_Int16 nVal;\n rAny >>= nVal;\n switch( nVal )\n {\n case text::ChapterFormat::NAME: SetFormat(CF_TITLE); break;\n case text::ChapterFormat::NUMBER: SetFormat(CF_NUMBER); break;\n case text::ChapterFormat::NO_PREFIX_SUFFIX:\n SetFormat(CF_NUM_NOPREPST_TITLE);\n break;\n case text::ChapterFormat::DIGIT:\n SetFormat(CF_NUMBER_NOPREPST);\n break;\n \/\/case text::ChapterFormat::NAME_NUMBER:\n default: SetFormat(CF_NUM_TITLE);\n }\n }\n break;\n\n default:\n DBG_ERROR(\"illegal property\");\n bRet = FALSE;\n }\n return bRet;\n}\n<commit_msg>INTEGRATION: CWS os8 (1.5.148); FILE MERGED 2003\/04\/03 07:10:38 os 1.5.148.1: #108583# precompiled headers removed<commit_after>\/*************************************************************************\n *\n * $RCSfile: chpfld.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 14:04:28 $\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\n#pragma hdrstop\n\n#ifndef _COM_SUN_STAR_TEXT_CHAPTERFORMAT_HPP_\n#include <com\/sun\/star\/text\/ChapterFormat.hpp>\n#endif\n\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _FRAME_HXX\n#include <frame.hxx> \/\/ SwChapterFieldType::ChangeExpansion()\n#endif\n#ifndef _PAM_HXX\n#include <pam.hxx> \/\/ fuer GetBodyTxtNode\n#endif\n#ifndef _NDTXT_HXX\n#include <ndtxt.hxx>\n#endif\n#ifndef _CHPFLD_HXX\n#include <chpfld.hxx>\n#endif\n#ifndef _EXPFLD_HXX\n#include <expfld.hxx> \/\/ fuer GetBodyTxtNode\n#endif\n#ifndef _UNOFLDMID_H\n#include <unofldmid.h>\n#endif\n\nusing namespace ::com::sun::star;\n\n\/*--------------------------------------------------------------------\n Beschreibung: SwChapterFieldType\n --------------------------------------------------------------------*\/\n\n\nSwChapterFieldType::SwChapterFieldType()\n : SwFieldType( RES_CHAPTERFLD )\n{\n}\n\n\nSwFieldType* SwChapterFieldType::Copy() const\n{\n return new SwChapterFieldType();\n}\n\n\n\/*--------------------------------------------------------------------\n Beschreibung: Kapittelfeld\n --------------------------------------------------------------------*\/\n\n\nSwChapterField::SwChapterField(SwChapterFieldType* pTyp, sal_uInt32 nFmt)\n : SwField(pTyp, nFmt), nLevel( 0 )\n{}\n\n\nString SwChapterField::Expand() const\n{\n String sStr( sNumber );\n switch( GetFormat() )\n {\n case CF_TITLE: sStr = sTitle; break;\n\n case CF_NUMBER:\n case CF_NUM_TITLE: sStr.Insert( sPre, 0 );\n sStr += sPost;\n if( CF_NUM_TITLE == GetFormat() )\n sStr += sTitle;\n break;\n\n case CF_NUM_NOPREPST_TITLE: sStr += sTitle; break;\n }\n return sStr;\n}\n\n\nSwField* SwChapterField::Copy() const\n{\n SwChapterField *pTmp =\n new SwChapterField((SwChapterFieldType*)GetTyp(), GetFormat());\n pTmp->nLevel = nLevel;\n pTmp->sTitle = sTitle;\n pTmp->sNumber = sNumber;\n pTmp->sPost = sPost;\n pTmp->sPre = sPre;\n\n return pTmp;\n}\n\n\nvoid SwChapterField::ChangeExpansion( const SwFrm* pFrm,\n const SwTxtNode* pTxtNd,\n sal_Bool bSrchNum )\n{\n ASSERT( pFrm, \"in welchem Frame stehe ich denn?\" )\n SwDoc* pDoc = (SwDoc*)pTxtNd->GetDoc();\n SwPosition aPos( pDoc->GetNodes().GetEndOfContent() );\n\n if( pFrm->IsInDocBody() )\n aPos.nNode = *pTxtNd;\n else if( 0 == (pTxtNd = GetBodyTxtNode( *pDoc, aPos, *pFrm )) )\n \/\/ kein TxtNode (Formatierung Kopf\/Fusszeile)\n return;\n\n ASSERT( pTxtNd, \"Wo steht das Feld\" );\n pTxtNd = pTxtNd->FindOutlineNodeOfLevel( nLevel );\n if( pTxtNd )\n {\n if( bSrchNum )\n {\n const SwTxtNode* pONd = pTxtNd;\n do {\n if( pONd && pONd->GetTxtColl() )\n {\n BYTE nPrevLvl = nLevel;\n nLevel = GetRealLevel( pONd->GetTxtColl()->\n GetOutlineLevel() );\n if( nPrevLvl < nLevel )\n nLevel = nPrevLvl;\n else if( SVX_NUM_NUMBER_NONE != pDoc->GetOutlineNumRule()\n ->Get( nLevel ).GetNumberingType() )\n {\n pTxtNd = pONd;\n break;\n }\n\n if( !nLevel-- )\n break;\n pONd = pTxtNd->FindOutlineNodeOfLevel( nLevel );\n }\n else\n break;\n } while( sal_True );\n }\n\n const SwNodeNum& rNum = *pTxtNd->GetOutlineNum();\n \/\/ nur die Nummer besorgen, ohne Pre-\/Post-fixstrings\n sNumber = pDoc->GetOutlineNumRule()->MakeNumString( rNum, sal_False );\n\n if( NO_NUM > rNum.GetLevel() && !( NO_NUMLEVEL & rNum.GetLevel() ) )\n {\n const SwNumFmt& rNFmt = pDoc->GetOutlineNumRule()->Get( rNum.GetLevel() );\n sPost = rNFmt.GetSuffix();\n sPre = rNFmt.GetPrefix();\n }\n else\n sPost = aEmptyStr, sPre = aEmptyStr;\n\n sTitle = pTxtNd->GetExpandTxt();\n\n for( xub_StrLen i = 0; i < sTitle.Len(); ++i )\n if( ' ' > sTitle.GetChar( i ) )\n sTitle.Erase( i--, 1 );\n }\n else\n {\n sNumber = aEmptyStr;\n sTitle = aEmptyStr;\n sPost = aEmptyStr;\n sPre = aEmptyStr;\n }\n}\n\n\/*-----------------05.03.98 16:19-------------------\n\n--------------------------------------------------*\/\nBOOL SwChapterField::QueryValue( com::sun::star::uno::Any& rAny, BYTE nMId ) const\n{\n nMId &= ~CONVERT_TWIPS;\n switch( nMId )\n {\n case FIELD_PROP_BYTE1:\n rAny <<= (sal_Int8)nLevel;\n break;\n\n case FIELD_PROP_USHORT1:\n {\n sal_Int16 nRet;\n switch( GetFormat() )\n {\n case CF_NUMBER: nRet = text::ChapterFormat::NUMBER; break;\n case CF_TITLE: nRet = text::ChapterFormat::NAME; break;\n case CF_NUMBER_NOPREPST:\n nRet = text::ChapterFormat::DIGIT;\n break;\n case CF_NUM_NOPREPST_TITLE:\n nRet = text::ChapterFormat::NO_PREFIX_SUFFIX;\n break;\n case CF_NUM_TITLE:\n default: nRet = text::ChapterFormat::NAME_NUMBER;\n }\n rAny <<= nRet;\n }\n break;\n\n default:\n DBG_ERROR(\"illegal property\");\n }\n return sal_True;\n}\n\/*-----------------05.03.98 16:19-------------------\n\n--------------------------------------------------*\/\nBOOL SwChapterField::PutValue( const com::sun::star::uno::Any& rAny, BYTE nMId )\n{\n BOOL bRet = TRUE;\n nMId &= ~CONVERT_TWIPS;\n switch( nMId )\n {\n case FIELD_PROP_BYTE1:\n sal_Int8 nTmp;\n rAny >>= nTmp;\n if(nTmp >= 0 && nTmp < MAXLEVEL)\n nLevel = nTmp;\n else\n bRet = FALSE;\n break;\n\n case FIELD_PROP_USHORT1:\n {\n sal_Int16 nVal;\n rAny >>= nVal;\n switch( nVal )\n {\n case text::ChapterFormat::NAME: SetFormat(CF_TITLE); break;\n case text::ChapterFormat::NUMBER: SetFormat(CF_NUMBER); break;\n case text::ChapterFormat::NO_PREFIX_SUFFIX:\n SetFormat(CF_NUM_NOPREPST_TITLE);\n break;\n case text::ChapterFormat::DIGIT:\n SetFormat(CF_NUMBER_NOPREPST);\n break;\n \/\/case text::ChapterFormat::NAME_NUMBER:\n default: SetFormat(CF_NUM_TITLE);\n }\n }\n break;\n\n default:\n DBG_ERROR(\"illegal property\");\n bRet = FALSE;\n }\n return bRet;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2018 Intel Corporation \/\/\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#undef NDEBUG \/\/ do all assertions in this file\n\n\/\/ospray\n#include \"ospray\/camera\/Camera.h\"\n#include \"ospray\/common\/Data.h\"\n#include \"ospray\/lights\/Light.h\"\n#include \"ospray\/transferFunction\/TransferFunction.h\"\n\/\/mpiCommon\n#include \"mpiCommon\/MPICommon.h\"\n\/\/ospray_mpi\n#include \"mpi\/MPIDistributedDevice.h\"\n#include \"mpi\/fb\/DistributedFrameBuffer.h\"\n#include \"mpi\/render\/MPILoadBalancer.h\"\n\n\/\/distributed objects\n#include \"render\/distributed\/DistributedRaycast.h\"\n#include \"common\/DistributedModel.h\"\n\n#ifdef OPEN_MPI\n# include <thread>\n\/\/# define _GNU_SOURCE\n# include <sched.h>\n#endif\n\nnamespace ospray {\n namespace mpi {\n\n \/\/ Helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n template <typename OSPRAY_TYPE, typename API_TYPE>\n inline API_TYPE createLocalObject(const char *type)\n {\n auto *instance = OSPRAY_TYPE::createInstance(type);\n return (API_TYPE)instance;\n }\n\n template <typename OSPRAY_TYPE, typename API_TYPE>\n inline API_TYPE createDistributedObject(const char *type)\n {\n auto *instance = OSPRAY_TYPE::createInstance(type);\n instance->refInc();\n\n ObjectHandle handle;\n handle.assign(instance);\n\n return (API_TYPE)(int64)handle;\n }\n\n template <typename OSPRAY_TYPE>\n inline OSPRAY_TYPE& lookupDistributedObject(OSPObject obj)\n {\n auto &handle = reinterpret_cast<ObjectHandle&>(obj);\n auto *object = (OSPRAY_TYPE*)handle.lookup();\n\n if (!object)\n throw std::runtime_error(\"#dmpi: ObjectHandle doesn't exist!\");\n\n return *object;\n }\n\n template <typename OSPRAY_TYPE>\n inline OSPRAY_TYPE* lookupObject(OSPObject obj)\n {\n auto &handle = reinterpret_cast<ObjectHandle&>(obj);\n if (handle.defined()) {\n return (OSPRAY_TYPE*)handle.lookup();\n } else {\n return (OSPRAY_TYPE*)obj;\n }\n }\n\n static void embreeErrorFunc(void *, const RTCError code, const char* str)\n {\n postStatusMsg() << \"#osp: embree internal error \" << code << \" : \" << str;\n throw std::runtime_error(\"embree internal error '\" +std::string(str)+\"'\");\n }\n\n \/\/ MPIDistributedDevice definitions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MPIDistributedDevice::~MPIDistributedDevice()\n {\n if (shouldFinalizeMPI) {\n try {\n MPI_CALL(Finalize());\n } catch (...) {\n \/\/TODO: anything to do here? try-catch added to silence a warning...\n }\n }\n }\n\n void MPIDistributedDevice::commit()\n {\n if (!initialized) {\n int _ac = 1;\n const char *_av[] = {\"ospray_mpi_distributed_device\"};\n\n MPI_Comm *setComm = static_cast<MPI_Comm*>(getParamVoidPtr(\"worldCommunicator\", nullptr));\n shouldFinalizeMPI = mpicommon::init(&_ac, _av, setComm == nullptr);\n\n if (setComm) {\n MPI_CALL(Comm_dup(*setComm, &mpicommon::world.comm));\n MPI_CALL(Comm_rank(mpicommon::world.comm, &mpicommon::world.rank));\n MPI_CALL(Comm_size(mpicommon::world.comm, &mpicommon::world.size));\n }\n\n embreeDevice = rtcNewDevice(generateEmbreeDeviceCfg(*this).c_str());\n\n rtcDeviceSetErrorFunction2(embreeDevice, embreeErrorFunc, nullptr);\n\n RTCError erc = rtcDeviceGetError(embreeDevice);\n if (erc != RTC_NO_ERROR) {\n \/\/ why did the error function not get called !?\n postStatusMsg() << \"#osp:init: embree internal error number \" << erc;\n assert(erc == RTC_NO_ERROR);\n }\n\n initialized = true;\n }\n\n Device::commit();\n\n masterRank = getParam1i(\"masterRank\", 0);\n\n TiledLoadBalancer::instance =\n make_unique<staticLoadBalancer::Distributed>();\n }\n\n OSPFrameBuffer\n MPIDistributedDevice::frameBufferCreate(const vec2i &size,\n const OSPFrameBufferFormat mode,\n const uint32 channels)\n {\n const bool hasDepthBuffer = channels & OSP_FB_DEPTH;\n const bool hasAccumBuffer = channels & OSP_FB_ACCUM;\n const bool hasVarianceBuffer = channels & OSP_FB_VARIANCE;\n\n ObjectHandle handle;\n\n auto *instance = new DistributedFrameBuffer(size, handle, mode,\n hasDepthBuffer,\n hasAccumBuffer,\n hasVarianceBuffer,\n true);\n instance->refInc();\n\n handle.assign(instance);\n\n return (OSPFrameBuffer)(int64)handle;\n }\n\n\n const void*\n MPIDistributedDevice::frameBufferMap(OSPFrameBuffer _fb,\n OSPFrameBufferChannel channel)\n {\n if (!mpicommon::IamTheMaster())\n throw std::runtime_error(\"Can only map framebuffer on the master!\");\n\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n\n switch (channel) {\n case OSP_FB_COLOR: return fb.mapColorBuffer();\n case OSP_FB_DEPTH: return fb.mapDepthBuffer();\n default: return nullptr;\n }\n }\n\n void MPIDistributedDevice::frameBufferUnmap(const void *mapped,\n OSPFrameBuffer _fb)\n {\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n fb.unmap(mapped);\n }\n\n void MPIDistributedDevice::frameBufferClear(OSPFrameBuffer _fb,\n const uint32 fbChannelFlags)\n {\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n fb.clear(fbChannelFlags);\n }\n\n OSPModel MPIDistributedDevice::newModel()\n {\n auto *instance = new DistributedModel;\n instance->refInc();\n\n ObjectHandle handle;\n handle.assign(instance);\n\n return (OSPModel)(int64)handle;\n }\n\n void MPIDistributedDevice::commit(OSPObject _object)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->commit();\n }\n\n void MPIDistributedDevice::addGeometry(OSPModel _model,\n OSPGeometry _geometry)\n {\n auto &model = lookupDistributedObject<Model>(_model);\n auto *geom = lookupObject<Geometry>(_geometry);\n\n model.geometry.push_back(geom);\n }\n\n void MPIDistributedDevice::addVolume(OSPModel _model, OSPVolume _volume)\n {\n auto &model = lookupDistributedObject<Model>(_model);\n auto *volume = lookupObject<Volume>(_volume);\n\n model.volume.push_back(volume);\n }\n\n OSPData MPIDistributedDevice::newData(size_t nitems, OSPDataType format,\n const void *init, int flags)\n {\n auto *instance = new Data(nitems, format, init, flags);\n instance->refInc();\n return (OSPData)instance;\n }\n\n void MPIDistributedDevice::setVoidPtr(OSPObject _object,\n const char *bufName,\n void *v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::removeParam(OSPObject _object, const char *name)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->removeParam(name);\n }\n\n int MPIDistributedDevice::setRegion(OSPVolume _volume, const void *source,\n const vec3i &index, const vec3i &count)\n {\n auto *volume = (Volume*)_volume;\n return volume->setRegion(source, index, count);\n }\n\n void MPIDistributedDevice::setString(OSPObject _object,\n const char *bufName,\n const char *s)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(s);\n }\n\n int MPIDistributedDevice::loadModule(const char *name)\n {\n return loadLocalModule(name);\n }\n\n void MPIDistributedDevice::setFloat(OSPObject _object,\n const char *bufName,\n const float f)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(f);\n }\n\n void MPIDistributedDevice::setInt(OSPObject _object,\n const char *bufName,\n const int i)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(i);\n }\n\n void MPIDistributedDevice::setVec2f(OSPObject _object,\n const char *bufName,\n const vec2f &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setVec3f(OSPObject _object,\n const char *bufName,\n const vec3f &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setVec4f(OSPObject _object,\n const char *bufName,\n const vec4f &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setVec2i(OSPObject _object,\n const char *bufName,\n const vec2i &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setVec3i(OSPObject _object,\n const char *bufName,\n const vec3i &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setObject(OSPObject _object,\n const char *bufName,\n OSPObject _value)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n auto *value = lookupObject<ManagedObject>(_value);\n object->set(bufName, value);\n }\n\n OSPPixelOp MPIDistributedDevice::newPixelOp(const char *type)\n {\n return createDistributedObject<PixelOp, OSPPixelOp>(type);\n }\n\n void MPIDistributedDevice::setPixelOp(OSPFrameBuffer _fb, OSPPixelOp _op)\n {\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n auto &op = lookupDistributedObject<PixelOp>(_op);\n fb.pixelOp = op.createInstance(&fb, fb.pixelOp.ptr);\n }\n\n OSPRenderer MPIDistributedDevice::newRenderer(const char *type)\n {\n return createDistributedObject<Renderer, OSPRenderer>(type);\n }\n\n OSPCamera MPIDistributedDevice::newCamera(const char *type)\n {\n return createLocalObject<Camera, OSPCamera>(type);\n }\n\n OSPVolume MPIDistributedDevice::newVolume(const char *type)\n {\n return createLocalObject<Volume, OSPVolume>(type);\n }\n\n OSPGeometry MPIDistributedDevice::newGeometry(const char *type)\n {\n return createLocalObject<Geometry, OSPGeometry>(type);\n }\n\n OSPMaterial MPIDistributedDevice::newMaterial(OSPRenderer, const char *)\n {\n NOT_IMPLEMENTED;\n }\n\n OSPTransferFunction\n MPIDistributedDevice::newTransferFunction(const char *type)\n {\n return createLocalObject<TransferFunction,\n OSPTransferFunction>(type);\n }\n\n OSPLight MPIDistributedDevice::newLight(OSPRenderer _renderer,\n const char *type)\n {\n auto &renderer = lookupDistributedObject<Renderer>(_renderer);\n auto *light = renderer.createLight(type);\n\n if (light == nullptr)\n light = Light::createLight(type);\n\n if (light) {\n return (OSPLight)light;\n } else {\n return nullptr;\n }\n }\n\n void MPIDistributedDevice::removeGeometry(OSPModel _model,\n OSPGeometry _geometry)\n {\n auto &model = lookupDistributedObject<Model>(_model);\n auto *geom = lookupObject<Geometry>(_geometry);\n\n \/\/TODO: confirm this works?\n model.geometry.erase(std::remove(model.geometry.begin(),\n model.geometry.end(),\n Ref<Geometry>(geom)));\n }\n\n void MPIDistributedDevice::removeVolume(OSPModel _model, OSPVolume _volume)\n {\n auto &model = lookupDistributedObject<Model>(_model);\n auto *volume = lookupObject<Volume>(_volume);\n\n \/\/TODO: confirm this works?\n model.volume.erase(std::remove(model.volume.begin(),\n model.volume.end(),\n Ref<Volume>(volume)));\n }\n\n float MPIDistributedDevice::renderFrame(OSPFrameBuffer _fb,\n OSPRenderer _renderer,\n const uint32 fbChannelFlags)\n {\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n auto &renderer = lookupDistributedObject<Renderer>(_renderer);\n auto result = renderer.renderFrame(&fb, fbChannelFlags);\n mpicommon::world.barrier();\n return result;\n }\n\n void MPIDistributedDevice::release(OSPObject _obj)\n {\n if (!_obj) return;\n auto *obj = lookupObject<ManagedObject>(_obj);\n obj->refDec();\n }\n\n void MPIDistributedDevice::setMaterial(OSPGeometry, OSPMaterial)\n {\n NOT_IMPLEMENTED;\n }\n\n OSPTexture2D MPIDistributedDevice::newTexture2D(\n const vec2i &,\n const OSPTextureFormat,\n void *,\n const uint32\n )\n {\n NOT_IMPLEMENTED;\n }\n\n void MPIDistributedDevice::sampleVolume(float **,\n OSPVolume,\n const vec3f *,\n const size_t &)\n {\n NOT_IMPLEMENTED;\n }\n\n OSP_REGISTER_DEVICE(MPIDistributedDevice, mpi_distributed_device);\n OSP_REGISTER_DEVICE(MPIDistributedDevice, mpi_distributed);\n\n } \/\/ ::ospray::mpi\n} \/\/ ::ospray\n<commit_msg>Fix setString in MPI distributed device<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2018 Intel Corporation \/\/\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#undef NDEBUG \/\/ do all assertions in this file\n\n\/\/ospray\n#include \"ospray\/camera\/Camera.h\"\n#include \"ospray\/common\/Data.h\"\n#include \"ospray\/lights\/Light.h\"\n#include \"ospray\/transferFunction\/TransferFunction.h\"\n\/\/mpiCommon\n#include \"mpiCommon\/MPICommon.h\"\n\/\/ospray_mpi\n#include \"mpi\/MPIDistributedDevice.h\"\n#include \"mpi\/fb\/DistributedFrameBuffer.h\"\n#include \"mpi\/render\/MPILoadBalancer.h\"\n\n\/\/distributed objects\n#include \"render\/distributed\/DistributedRaycast.h\"\n#include \"common\/DistributedModel.h\"\n\n#ifdef OPEN_MPI\n# include <thread>\n\/\/# define _GNU_SOURCE\n# include <sched.h>\n#endif\n\nnamespace ospray {\n namespace mpi {\n\n \/\/ Helper functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n template <typename OSPRAY_TYPE, typename API_TYPE>\n inline API_TYPE createLocalObject(const char *type)\n {\n auto *instance = OSPRAY_TYPE::createInstance(type);\n return (API_TYPE)instance;\n }\n\n template <typename OSPRAY_TYPE, typename API_TYPE>\n inline API_TYPE createDistributedObject(const char *type)\n {\n auto *instance = OSPRAY_TYPE::createInstance(type);\n instance->refInc();\n\n ObjectHandle handle;\n handle.assign(instance);\n\n return (API_TYPE)(int64)handle;\n }\n\n template <typename OSPRAY_TYPE>\n inline OSPRAY_TYPE& lookupDistributedObject(OSPObject obj)\n {\n auto &handle = reinterpret_cast<ObjectHandle&>(obj);\n auto *object = (OSPRAY_TYPE*)handle.lookup();\n\n if (!object)\n throw std::runtime_error(\"#dmpi: ObjectHandle doesn't exist!\");\n\n return *object;\n }\n\n template <typename OSPRAY_TYPE>\n inline OSPRAY_TYPE* lookupObject(OSPObject obj)\n {\n auto &handle = reinterpret_cast<ObjectHandle&>(obj);\n if (handle.defined()) {\n return (OSPRAY_TYPE*)handle.lookup();\n } else {\n return (OSPRAY_TYPE*)obj;\n }\n }\n\n static void embreeErrorFunc(void *, const RTCError code, const char* str)\n {\n postStatusMsg() << \"#osp: embree internal error \" << code << \" : \" << str;\n throw std::runtime_error(\"embree internal error '\" +std::string(str)+\"'\");\n }\n\n \/\/ MPIDistributedDevice definitions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n MPIDistributedDevice::~MPIDistributedDevice()\n {\n if (shouldFinalizeMPI) {\n try {\n MPI_CALL(Finalize());\n } catch (...) {\n \/\/TODO: anything to do here? try-catch added to silence a warning...\n }\n }\n }\n\n void MPIDistributedDevice::commit()\n {\n if (!initialized) {\n int _ac = 1;\n const char *_av[] = {\"ospray_mpi_distributed_device\"};\n\n MPI_Comm *setComm = static_cast<MPI_Comm*>(getParamVoidPtr(\"worldCommunicator\", nullptr));\n shouldFinalizeMPI = mpicommon::init(&_ac, _av, setComm == nullptr);\n\n if (setComm) {\n MPI_CALL(Comm_dup(*setComm, &mpicommon::world.comm));\n MPI_CALL(Comm_rank(mpicommon::world.comm, &mpicommon::world.rank));\n MPI_CALL(Comm_size(mpicommon::world.comm, &mpicommon::world.size));\n }\n\n embreeDevice = rtcNewDevice(generateEmbreeDeviceCfg(*this).c_str());\n\n rtcDeviceSetErrorFunction2(embreeDevice, embreeErrorFunc, nullptr);\n\n RTCError erc = rtcDeviceGetError(embreeDevice);\n if (erc != RTC_NO_ERROR) {\n \/\/ why did the error function not get called !?\n postStatusMsg() << \"#osp:init: embree internal error number \" << erc;\n assert(erc == RTC_NO_ERROR);\n }\n\n initialized = true;\n }\n\n Device::commit();\n\n masterRank = getParam1i(\"masterRank\", 0);\n\n TiledLoadBalancer::instance =\n make_unique<staticLoadBalancer::Distributed>();\n }\n\n OSPFrameBuffer\n MPIDistributedDevice::frameBufferCreate(const vec2i &size,\n const OSPFrameBufferFormat mode,\n const uint32 channels)\n {\n const bool hasDepthBuffer = channels & OSP_FB_DEPTH;\n const bool hasAccumBuffer = channels & OSP_FB_ACCUM;\n const bool hasVarianceBuffer = channels & OSP_FB_VARIANCE;\n\n ObjectHandle handle;\n\n auto *instance = new DistributedFrameBuffer(size, handle, mode,\n hasDepthBuffer,\n hasAccumBuffer,\n hasVarianceBuffer,\n true);\n instance->refInc();\n\n handle.assign(instance);\n\n return (OSPFrameBuffer)(int64)handle;\n }\n\n\n const void*\n MPIDistributedDevice::frameBufferMap(OSPFrameBuffer _fb,\n OSPFrameBufferChannel channel)\n {\n if (!mpicommon::IamTheMaster())\n throw std::runtime_error(\"Can only map framebuffer on the master!\");\n\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n\n switch (channel) {\n case OSP_FB_COLOR: return fb.mapColorBuffer();\n case OSP_FB_DEPTH: return fb.mapDepthBuffer();\n default: return nullptr;\n }\n }\n\n void MPIDistributedDevice::frameBufferUnmap(const void *mapped,\n OSPFrameBuffer _fb)\n {\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n fb.unmap(mapped);\n }\n\n void MPIDistributedDevice::frameBufferClear(OSPFrameBuffer _fb,\n const uint32 fbChannelFlags)\n {\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n fb.clear(fbChannelFlags);\n }\n\n OSPModel MPIDistributedDevice::newModel()\n {\n auto *instance = new DistributedModel;\n instance->refInc();\n\n ObjectHandle handle;\n handle.assign(instance);\n\n return (OSPModel)(int64)handle;\n }\n\n void MPIDistributedDevice::commit(OSPObject _object)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->commit();\n }\n\n void MPIDistributedDevice::addGeometry(OSPModel _model,\n OSPGeometry _geometry)\n {\n auto &model = lookupDistributedObject<Model>(_model);\n auto *geom = lookupObject<Geometry>(_geometry);\n\n model.geometry.push_back(geom);\n }\n\n void MPIDistributedDevice::addVolume(OSPModel _model, OSPVolume _volume)\n {\n auto &model = lookupDistributedObject<Model>(_model);\n auto *volume = lookupObject<Volume>(_volume);\n\n model.volume.push_back(volume);\n }\n\n OSPData MPIDistributedDevice::newData(size_t nitems, OSPDataType format,\n const void *init, int flags)\n {\n auto *instance = new Data(nitems, format, init, flags);\n instance->refInc();\n return (OSPData)instance;\n }\n\n void MPIDistributedDevice::setVoidPtr(OSPObject _object,\n const char *bufName,\n void *v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::removeParam(OSPObject _object, const char *name)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->removeParam(name);\n }\n\n int MPIDistributedDevice::setRegion(OSPVolume _volume, const void *source,\n const vec3i &index, const vec3i &count)\n {\n auto *volume = (Volume*)_volume;\n return volume->setRegion(source, index, count);\n }\n\n void MPIDistributedDevice::setString(OSPObject _object,\n const char *bufName,\n const char *s)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(std::string(s));\n }\n\n int MPIDistributedDevice::loadModule(const char *name)\n {\n return loadLocalModule(name);\n }\n\n void MPIDistributedDevice::setFloat(OSPObject _object,\n const char *bufName,\n const float f)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(f);\n }\n\n void MPIDistributedDevice::setInt(OSPObject _object,\n const char *bufName,\n const int i)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(i);\n }\n\n void MPIDistributedDevice::setVec2f(OSPObject _object,\n const char *bufName,\n const vec2f &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setVec3f(OSPObject _object,\n const char *bufName,\n const vec3f &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setVec4f(OSPObject _object,\n const char *bufName,\n const vec4f &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setVec2i(OSPObject _object,\n const char *bufName,\n const vec2i &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setVec3i(OSPObject _object,\n const char *bufName,\n const vec3i &v)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n object->findParam(bufName, true)->set(v);\n }\n\n void MPIDistributedDevice::setObject(OSPObject _object,\n const char *bufName,\n OSPObject _value)\n {\n auto *object = lookupObject<ManagedObject>(_object);\n auto *value = lookupObject<ManagedObject>(_value);\n object->set(bufName, value);\n }\n\n OSPPixelOp MPIDistributedDevice::newPixelOp(const char *type)\n {\n return createDistributedObject<PixelOp, OSPPixelOp>(type);\n }\n\n void MPIDistributedDevice::setPixelOp(OSPFrameBuffer _fb, OSPPixelOp _op)\n {\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n auto &op = lookupDistributedObject<PixelOp>(_op);\n fb.pixelOp = op.createInstance(&fb, fb.pixelOp.ptr);\n }\n\n OSPRenderer MPIDistributedDevice::newRenderer(const char *type)\n {\n return createDistributedObject<Renderer, OSPRenderer>(type);\n }\n\n OSPCamera MPIDistributedDevice::newCamera(const char *type)\n {\n return createLocalObject<Camera, OSPCamera>(type);\n }\n\n OSPVolume MPIDistributedDevice::newVolume(const char *type)\n {\n return createLocalObject<Volume, OSPVolume>(type);\n }\n\n OSPGeometry MPIDistributedDevice::newGeometry(const char *type)\n {\n return createLocalObject<Geometry, OSPGeometry>(type);\n }\n\n OSPMaterial MPIDistributedDevice::newMaterial(OSPRenderer, const char *)\n {\n NOT_IMPLEMENTED;\n }\n\n OSPTransferFunction\n MPIDistributedDevice::newTransferFunction(const char *type)\n {\n return createLocalObject<TransferFunction,\n OSPTransferFunction>(type);\n }\n\n OSPLight MPIDistributedDevice::newLight(OSPRenderer _renderer,\n const char *type)\n {\n auto &renderer = lookupDistributedObject<Renderer>(_renderer);\n auto *light = renderer.createLight(type);\n\n if (light == nullptr)\n light = Light::createLight(type);\n\n if (light) {\n return (OSPLight)light;\n } else {\n return nullptr;\n }\n }\n\n void MPIDistributedDevice::removeGeometry(OSPModel _model,\n OSPGeometry _geometry)\n {\n auto &model = lookupDistributedObject<Model>(_model);\n auto *geom = lookupObject<Geometry>(_geometry);\n\n \/\/TODO: confirm this works?\n model.geometry.erase(std::remove(model.geometry.begin(),\n model.geometry.end(),\n Ref<Geometry>(geom)));\n }\n\n void MPIDistributedDevice::removeVolume(OSPModel _model, OSPVolume _volume)\n {\n auto &model = lookupDistributedObject<Model>(_model);\n auto *volume = lookupObject<Volume>(_volume);\n\n \/\/TODO: confirm this works?\n model.volume.erase(std::remove(model.volume.begin(),\n model.volume.end(),\n Ref<Volume>(volume)));\n }\n\n float MPIDistributedDevice::renderFrame(OSPFrameBuffer _fb,\n OSPRenderer _renderer,\n const uint32 fbChannelFlags)\n {\n auto &fb = lookupDistributedObject<FrameBuffer>(_fb);\n auto &renderer = lookupDistributedObject<Renderer>(_renderer);\n auto result = renderer.renderFrame(&fb, fbChannelFlags);\n mpicommon::world.barrier();\n return result;\n }\n\n void MPIDistributedDevice::release(OSPObject _obj)\n {\n if (!_obj) return;\n auto *obj = lookupObject<ManagedObject>(_obj);\n obj->refDec();\n }\n\n void MPIDistributedDevice::setMaterial(OSPGeometry, OSPMaterial)\n {\n NOT_IMPLEMENTED;\n }\n\n OSPTexture2D MPIDistributedDevice::newTexture2D(\n const vec2i &,\n const OSPTextureFormat,\n void *,\n const uint32\n )\n {\n NOT_IMPLEMENTED;\n }\n\n void MPIDistributedDevice::sampleVolume(float **,\n OSPVolume,\n const vec3f *,\n const size_t &)\n {\n NOT_IMPLEMENTED;\n }\n\n OSP_REGISTER_DEVICE(MPIDistributedDevice, mpi_distributed_device);\n OSP_REGISTER_DEVICE(MPIDistributedDevice, mpi_distributed);\n\n } \/\/ ::ospray::mpi\n} \/\/ ::ospray\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Appcelerator Titanium - licensed under the Apache Public License 2\n * see LICENSE in the root folder for details on the license.\n * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.\n *\/\n#include \"..\/ui_module.h\"\n#include <math.h>\n#define ID_INPUT_FIELD 101\n\nnamespace ti\n{\n\tstd::map<DWORD, Win32PopupDialog*> Win32PopupDialog::popups;\n\n\tclass DialogTemplate\n\t{\n\tpublic:\n\t\tLPCDLGTEMPLATE Template()\n\t\t{\n\t\t\treturn (LPCDLGTEMPLATE)&v[0];\n\t\t}\n\n\t\tvoid AlignToDword()\n\t\t{\n\t\t\tif (v.size() % 4) Write(NULL, 4 - (v.size() % 4));\n\t\t}\n\n\t\tvoid Write(LPCVOID pvWrite, DWORD cbWrite)\n\t\t{\n\t\t\tv.insert(v.end(), cbWrite, 0);\n\t\t\tif (pvWrite)\n\t\t\t{\n\t\t\t\tCopyMemory(&v[v.size() - cbWrite], pvWrite, cbWrite);\n\t\t\t}\n\t\t}\n\n\t\ttemplate<typename T> void Write(T t)\n\t\t{\n\t\t\tWrite(&t, sizeof(T));\n\t\t}\n\n\t\tvoid WriteString(LPCWSTR psz)\n\t\t{\n\t\t\tWrite(psz, (lstrlenW(psz) + 1) * sizeof(WCHAR));\n\t\t}\n\n\tprivate:\n\t\tstd::vector<BYTE> v;\n\t};\n\n\tWin32PopupDialog::Win32PopupDialog(HWND windowHandle) :\n\t\twindowHandle(windowHandle),\n\t\tshowInputText(false),\n\t\tshowCancelButton(false),\n\t\tresult(IDNO)\n\t{\n\t}\n\n\tWin32PopupDialog::~Win32PopupDialog()\n\t{\n\t}\n\n\tint Win32PopupDialog::Show()\n\t{\n\t\tpopups[GetCurrentThreadId()] = this;\n\t\tShowMessageBox(windowHandle);\n\n\t\treturn result;\n\t}\n\n\t\/*static*\/\n\tvoid Win32PopupDialog::HandleOKClick(HWND dialog)\n\t{\n\t\tTCHAR textEntered[MAX_INPUT_LENGTH];\n\t\tGetDlgItemText(dialog, ID_INPUT_FIELD, textEntered, MAX_INPUT_LENGTH);\n\n\t\tWin32PopupDialog* popupDialog = popups[GetCurrentThreadId()];\n\t\tif (popupDialog)\n\t\t{\n\t\t\tstd::wstring textEnteredW = textEntered;\n\t\t\tstd::string textEnteredU = ::WideToUTF8(textEnteredW);\n\t\t\tpopupDialog->inputText.clear();\n\t\t\tpopupDialog->inputText.append(textEnteredU);\n\t\t\tpopupDialog->result = IDOK;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"unable to find popup dialog for current thread\" << std::endl;\n\t\t}\n\t}\n\n\t\/*static*\/\n\tINT_PTR CALLBACK Win32PopupDialog::Callback(HWND dialog, UINT message, WPARAM wParam, LPARAM lParam)\n\t{\n\t\tswitch (message)\n\t\t{\n\t\t\tcase WM_INITDIALOG:\n\t\t\t{\n\t\t\t\tWin32PopupDialog* popupDialog = popups[GetCurrentThreadId()];\n\t\t\t\tHWND parentWindow = (popupDialog == NULL ? NULL : popupDialog->windowHandle);\n\t\t\t\tif (parentWindow == NULL)\n\t\t\t\t{\n\t\t\t\t\tparentWindow = GetDesktopWindow();\n\t\t\t\t}\n\n\t\t\t\tRECT parentRect, dialogRect;\n\t\t\t\tGetWindowRect(parentWindow, &parentRect);\n\t\t\t\tGetWindowRect(dialog, &dialogRect);\n\t\t\t\tint x = parentRect.left + (parentRect.right - parentRect.left) \/ 2;\n\t\t\t\tint y = parentRect.top + (parentRect.bottom - parentRect.top) \/ 2;\n\t\t\t\tx -= (dialogRect.right - dialogRect.left) \/ 2;\n\t\t\t\ty -= (dialogRect.bottom - dialogRect.top) \/ 2;\n\t\t\t\t\n\t\t\t\tSetWindowPos(dialog, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);\n\n\t\t\t\tif (popupDialog->showInputText)\n\t\t\t\t{\n\t\t\t\t\tif (GetDlgCtrlID((HWND) wParam) != ID_INPUT_FIELD)\n\t\t\t\t\t{\n\t\t\t\t\t\tHWND inputText = GetDlgItem(dialog, ID_INPUT_FIELD);\n\t\t\t\t\t\tSetFocus(inputText);\n\t\t\t\t\t\tSendMessage(inputText, EM_SETSEL,\n\t\t\t\t\t\t\t0, popupDialog->inputText.length());\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn TRUE;\n\t\t\t}\n\t\t\tcase WM_COMMAND:\n\t\t\t\tif(GET_WM_COMMAND_ID(wParam, lParam) == IDOK)\n\t\t\t\t{\n\t\t\t\t\tWin32PopupDialog::HandleOKClick(dialog);\n\t\t\t\t\tEndDialog(dialog, 0);\n\t\t\t\t}\n\t\t\t\telse if(GET_WM_COMMAND_ID(wParam, lParam) == IDCANCEL)\n\t\t\t\t{\n\t\t\t\t\tEndDialog(dialog, 0);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn FALSE;\n\t}\n\n\tint Win32PopupDialog::CountMatches(std::string& message, const char *token)\n\t{\n\t\tint matches = 0;\n\t\tsize_t pos = 0, tokenSize = strlen(token);\n\t\twhile (pos != std::string::npos) \n\t\t{\n\t\t\tpos = message.find(token, pos);\n\t\t\tif (pos != std::string::npos)\n\t\t\t{\n\t\t\t\tmatches++;\n\t\t\t\tpos += tokenSize;\n\t\t\t}\n\t\t}\n\t\treturn matches;\n\t}\n\t\n\tBOOL Win32PopupDialog::ShowMessageBox(HWND hwnd)\n\t{\n\t\tBOOL fSuccess = FALSE;\n\t\tHDC hdc = GetDC(hwnd);\n\n\t\tif (hdc)\n\t\t{\n\t\t\tNONCLIENTMETRICSW nonClientMetrics = { sizeof(NONCLIENTMETRICSW) };\n\t\t\tif (SystemParametersInfoW(\n\t\t\t\tSPI_GETNONCLIENTMETRICS, 0, &nonClientMetrics, 0))\n\t\t\t{\n\t\t\t\tDialogTemplate tmp;\n\t\t\t\tstd::wstring wideTitle(::UTF8ToWide(title));\n\t\t\t\tstd::wstring wideInputText;\n\t\t\t\tif (this->showInputText)\n\t\t\t\t\twideInputText.assign(::UTF8ToWide(inputText));\n\n\t\t\t\tint controlCount = 2;\t\/\/ at minimum, static label and OK button\n\t\t\t\tif (this->showCancelButton)\n\t\t\t\t\tcontrolCount++;\n\t\t\t\tif (this->showInputText)\n\t\t\t\t\tcontrolCount++;\n\n\t\t\t\tint messageLines = 0;\n\t\t\t\tint newlines = CountMatches(message, \"\\n\");\n\t\t\t\tint tabs = CountMatches(message, \"\\t\");\n\t\t\t\tint spaces = CountMatches(message, \" \");\n\n\t\t\t\tif (newlines == 0 && tabs == 0 && spaces == 0)\n\t\t\t\t{\n\t\t\t\t\tstd::string tempMessage(message);\n\t\t\t\t\tif (tempMessage.length() != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint insertAt = 60;\n\t\t\t\t\t\tint count = 0;\n\n\t\t\t\t\t\tstd::string::iterator it = tempMessage.begin();\n\t\t\t\t\t\tfor (; it < tempMessage.end(); it++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\tif (count == 60)\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\tcount = 0;\n\t\t\t\t\t\t\t\tmessage.insert(insertAt, \"\\n\");\n\t\t\t\t\t\t\t\tinsertAt += 60;\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}\n\t\t\t\t\n\t\t\t\tstd::wstring wideMessage(::UTF8ToWide(message));\n\t\t\t\tmessageLines = message.length() \/ 60;\n\t\t\t\tmessageLines += ((int) ceil((double)tabs \/ 14));\n\t\t\t\tmessageLines += newlines;\n\t\t\t\t\n\t\t\t\tif (tabs == 0 || newlines == 0)\n\t\t\t\t\tmessageLines++;\n\n\t\t\t\tint labelHeight = 14;\n\t\t\t\tint width = 200;\n\t\t\t\tint margin = 10;\n\t\t\t\tint buttonWidth = 50;\n\t\t\t\tint buttonHeight = 14;\n\t\t\t\tint inputHeight = 14;\n\t\t\t\tint messageHeight = (messageLines * 12) + (messageLines * margin);\n\t\t\t\tint height = messageHeight + 56;\n\t\t\t\t\n\t\t\t\tif (!this->showInputText)\n\t\t\t\t{\n\t\t\t\t\theight -= (inputHeight + margin);\n\t\t\t\t}\n\n\t\t\t\t\/\/ Write out the extended dialog template header\n\t\t\t\ttmp.Write<WORD>(1); \/\/ dialog version\n\t\t\t\ttmp.Write<WORD>(0xFFFF); \/\/ extended dialog template\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ help ID\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ extended style\n\t\t\t\ttmp.Write<DWORD>(WS_CAPTION | WS_BORDER | DS_ABSALIGN | DS_SETFONT);\n\t\t\t\ttmp.Write<WORD>(controlCount); \/\/ number of controls\n\t\t\t\ttmp.Write<WORD>(32); \/\/ X\n\t\t\t\ttmp.Write<WORD>(32); \/\/ Y\n\t\t\t\ttmp.Write<WORD>(width); \/\/ width\n\t\t\t\ttmp.Write<WORD>(height); \/\/ height\n\t\t\t\ttmp.WriteString(L\"\"); \/\/ no menu\n\t\t\t\ttmp.WriteString(L\"\"); \/\/ default dialog class\n\t\t\t\t\/\/tmp.WriteString(pszTitle); \/\/ title\n\t\t\t\ttmp.WriteString(wideTitle.c_str()); \/\/ title\n\n\t\t\t\t\/\/ Next comes the font description.\n\t\t\t\t\/\/ See text for discussion of fancy formula.\n\t\t\t\t\n\t\t\t\tif (nonClientMetrics.lfMessageFont.lfHeight < 0)\n\t\t\t\t{\n\t\t\t\t\tint dpi = GetDeviceCaps(hdc, LOGPIXELSY);\n\t\t\t\t\tnonClientMetrics.lfMessageFont.lfHeight =\n\t\t\t\t\t\t-MulDiv(nonClientMetrics.lfMessageFont.lfHeight, 72, dpi);\n\t\t\t\t}\n\t\t\t\ttmp.Write<WORD>((WORD)nonClientMetrics.lfMessageFont.lfHeight); \/\/ point\n\t\t\t\ttmp.Write<WORD>((WORD)nonClientMetrics.lfMessageFont.lfWeight); \/\/ weight\n\t\t\t\ttmp.Write<BYTE>(nonClientMetrics.lfMessageFont.lfItalic); \/\/ Italic\n\t\t\t\ttmp.Write<BYTE>(nonClientMetrics.lfMessageFont.lfCharSet); \/\/ CharSet\n\t\t\t\ttmp.WriteString(nonClientMetrics.lfMessageFont.lfFaceName);\n\n\t\t\t\t\/\/ First control - static label\n\t\t\t\ttmp.AlignToDword();\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ help id\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ window extended style\n\t\t\t\ttmp.Write<DWORD>(WS_CHILD | WS_VISIBLE | SS_LEFT); \/\/ style\n\t\t\t\ttmp.Write<WORD>(margin); \/\/ x\n\t\t\t\ttmp.Write<WORD>(margin); \/\/ y\n\t\t\t\ttmp.Write<WORD>(width - (2 * margin)); \/\/ width\n\t\t\t\t\/\/tmp.Write<WORD>(labelHeight); \/\/ height\n\t\t\t\ttmp.Write<WORD>(messageHeight); \/\/ height\n\t\t\t\ttmp.Write<DWORD>(-1); \/\/ control ID\n\t\t\t\ttmp.Write<DWORD>(0x0082FFFF); \/\/ static\n\t\t\t\t\/\/tmp.Write<DWORD>(SS_LEFT);\n\t\t\t\ttmp.WriteString(wideMessage.c_str()); \/\/ text\n\t\t\t\ttmp.Write<WORD>(0); \/\/ no extra data\n\n\t\t\t\t\/\/ Second control - the OK button.\n\t\t\t\ttmp.AlignToDword();\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ help id\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ window extended style\n\t\t\t\ttmp.Write<DWORD>(WS_CHILD | WS_VISIBLE | WS_GROUP | WS_TABSTOP | BS_DEFPUSHBUTTON); \/\/ style\n\t\t\t\ttmp.Write<WORD>(width - margin - buttonWidth); \/\/ x\n\t\t\t\ttmp.Write<WORD>(height - margin - buttonHeight); \/\/ y\n\t\t\t\ttmp.Write<WORD>(buttonWidth); \/\/ width\n\t\t\t\ttmp.Write<WORD>(buttonHeight); \/\/ height\n\t\t\t\ttmp.Write<DWORD>(IDOK); \/\/ control ID\n\t\t\t\ttmp.Write<DWORD>(0x0080FFFF); \/\/ button class atom\n\t\t\t\ttmp.WriteString(L\"OK\"); \/\/ text\n\t\t\t\ttmp.Write<WORD>(0); \/\/ no extra data\n\n\t\t\t\tif (this->showCancelButton)\n\t\t\t\t{\n\t\t\t\t\t\/\/ The Cancel button\n\t\t\t\t\ttmp.AlignToDword();\n\t\t\t\t\ttmp.Write<DWORD>(0); \/\/ help id\n\t\t\t\t\ttmp.Write<DWORD>(0); \/\/ window extended style\n\t\t\t\t\ttmp.Write<DWORD>(WS_CHILD | WS_VISIBLE | WS_GROUP | WS_TABSTOP | BS_DEFPUSHBUTTON); \/\/ style\n\t\t\t\t\ttmp.Write<WORD>(width - 2 * margin - 2 * buttonWidth); \/\/ x\n\t\t\t\t\ttmp.Write<WORD>(height - margin - buttonHeight); \/\/ y\n\t\t\t\t\ttmp.Write<WORD>(buttonWidth); \/\/ width\n\t\t\t\t\ttmp.Write<WORD>(buttonHeight); \/\/ height\n\t\t\t\t\ttmp.Write<DWORD>(IDCANCEL); \/\/ control ID\n\t\t\t\t\ttmp.Write<DWORD>(0x0080FFFF); \/\/ button class atom\n\t\t\t\t\ttmp.WriteString(L\"Cancel\"); \/\/ text\n\t\t\t\t\ttmp.Write<WORD>(0); \/\/ no extra data\n\t\t\t\t}\n\n\t\t\t\tif (this->showInputText)\n\t\t\t\t{\n\t\t\t\t\t\/\/ The input field\n\t\t\t\t\ttmp.AlignToDword();\n\t\t\t\t\ttmp.Write<DWORD>(0); \/\/ help id\n\t\t\t\t\ttmp.Write<DWORD>(0); \/\/ window extended style\n\t\t\t\t\ttmp.Write<DWORD>(ES_LEFT | WS_BORDER | WS_TABSTOP | WS_CHILD | WS_VISIBLE); \/\/ style\n\t\t\t\t\ttmp.Write<WORD>(margin); \/\/ x\n\t\t\t\t\ttmp.Write<WORD>(margin + labelHeight + margin); \/\/ y\n\t\t\t\t\ttmp.Write<WORD>(width - (2 * margin)); \/\/ width\n\t\t\t\t\ttmp.Write<WORD>(inputHeight); \/\/ height\n\t\t\t\t\ttmp.Write<DWORD>(ID_INPUT_FIELD); \/\/ control ID\n\t\t\t\t\ttmp.Write<DWORD>(0x0081FFFF); \/\/ edit class atom\n\t\t\t\t\ttmp.WriteString(wideInputText.c_str()); \/\/ text\n\t\t\t\t\ttmp.Write<WORD>(0); \/\/ no extra data\n\t\t\t\t}\n\n\t\t\t\t\/\/ Template is ready - go display it.\n\t\t\t\tfSuccess = DialogBoxIndirect(\n\t\t\t\t\tGetModuleHandle(NULL),\n\t\t\t\t\ttmp.Template(),\n\t\t\t\t\thwnd,\n\t\t\t\t\t&Win32PopupDialog::Callback) >= 0;\n\t\t\t}\n\t\t\tReleaseDC(NULL, hdc); \/\/ fixed 11 May\n\t\t}\n\t\treturn fSuccess;\n\t}\n}\n<commit_msg>Swap the OK and Cancel buttons on the Win32 prompt and confirm.<commit_after>\/**\n * Appcelerator Titanium - licensed under the Apache Public License 2\n * see LICENSE in the root folder for details on the license.\n * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.\n *\/\n#include \"..\/ui_module.h\"\n#include <math.h>\n#define ID_INPUT_FIELD 101\n\nnamespace ti\n{\n\tstd::map<DWORD, Win32PopupDialog*> Win32PopupDialog::popups;\n\n\tclass DialogTemplate\n\t{\n\tpublic:\n\t\tLPCDLGTEMPLATE Template()\n\t\t{\n\t\t\treturn (LPCDLGTEMPLATE)&v[0];\n\t\t}\n\n\t\tvoid AlignToDword()\n\t\t{\n\t\t\tif (v.size() % 4) Write(NULL, 4 - (v.size() % 4));\n\t\t}\n\n\t\tvoid Write(LPCVOID pvWrite, DWORD cbWrite)\n\t\t{\n\t\t\tv.insert(v.end(), cbWrite, 0);\n\t\t\tif (pvWrite)\n\t\t\t{\n\t\t\t\tCopyMemory(&v[v.size() - cbWrite], pvWrite, cbWrite);\n\t\t\t}\n\t\t}\n\n\t\ttemplate<typename T> void Write(T t)\n\t\t{\n\t\t\tWrite(&t, sizeof(T));\n\t\t}\n\n\t\tvoid WriteString(LPCWSTR psz)\n\t\t{\n\t\t\tWrite(psz, (lstrlenW(psz) + 1) * sizeof(WCHAR));\n\t\t}\n\n\tprivate:\n\t\tstd::vector<BYTE> v;\n\t};\n\n\tWin32PopupDialog::Win32PopupDialog(HWND windowHandle) :\n\t\twindowHandle(windowHandle),\n\t\tshowInputText(false),\n\t\tshowCancelButton(false),\n\t\tresult(IDNO)\n\t{\n\t}\n\n\tWin32PopupDialog::~Win32PopupDialog()\n\t{\n\t}\n\n\tint Win32PopupDialog::Show()\n\t{\n\t\tpopups[GetCurrentThreadId()] = this;\n\t\tShowMessageBox(windowHandle);\n\n\t\treturn result;\n\t}\n\n\t\/*static*\/\n\tvoid Win32PopupDialog::HandleOKClick(HWND dialog)\n\t{\n\t\tTCHAR textEntered[MAX_INPUT_LENGTH];\n\t\tGetDlgItemText(dialog, ID_INPUT_FIELD, textEntered, MAX_INPUT_LENGTH);\n\n\t\tWin32PopupDialog* popupDialog = popups[GetCurrentThreadId()];\n\t\tif (popupDialog)\n\t\t{\n\t\t\tstd::wstring textEnteredW = textEntered;\n\t\t\tstd::string textEnteredU = ::WideToUTF8(textEnteredW);\n\t\t\tpopupDialog->inputText.clear();\n\t\t\tpopupDialog->inputText.append(textEnteredU);\n\t\t\tpopupDialog->result = IDOK;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"unable to find popup dialog for current thread\" << std::endl;\n\t\t}\n\t}\n\n\t\/*static*\/\n\tINT_PTR CALLBACK Win32PopupDialog::Callback(HWND dialog, UINT message, WPARAM wParam, LPARAM lParam)\n\t{\n\t\tswitch (message)\n\t\t{\n\t\t\tcase WM_INITDIALOG:\n\t\t\t{\n\t\t\t\tWin32PopupDialog* popupDialog = popups[GetCurrentThreadId()];\n\t\t\t\tHWND parentWindow = (popupDialog == NULL ? NULL : popupDialog->windowHandle);\n\t\t\t\tif (parentWindow == NULL)\n\t\t\t\t{\n\t\t\t\t\tparentWindow = GetDesktopWindow();\n\t\t\t\t}\n\n\t\t\t\tRECT parentRect, dialogRect;\n\t\t\t\tGetWindowRect(parentWindow, &parentRect);\n\t\t\t\tGetWindowRect(dialog, &dialogRect);\n\t\t\t\tint x = parentRect.left + (parentRect.right - parentRect.left) \/ 2;\n\t\t\t\tint y = parentRect.top + (parentRect.bottom - parentRect.top) \/ 2;\n\t\t\t\tx -= (dialogRect.right - dialogRect.left) \/ 2;\n\t\t\t\ty -= (dialogRect.bottom - dialogRect.top) \/ 2;\n\t\t\t\t\n\t\t\t\tSetWindowPos(dialog, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);\n\n\t\t\t\tif (popupDialog->showInputText)\n\t\t\t\t{\n\t\t\t\t\tif (GetDlgCtrlID((HWND) wParam) != ID_INPUT_FIELD)\n\t\t\t\t\t{\n\t\t\t\t\t\tHWND inputText = GetDlgItem(dialog, ID_INPUT_FIELD);\n\t\t\t\t\t\tSetFocus(inputText);\n\t\t\t\t\t\tSendMessage(inputText, EM_SETSEL,\n\t\t\t\t\t\t\t0, popupDialog->inputText.length());\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn TRUE;\n\t\t\t}\n\t\t\tcase WM_COMMAND:\n\t\t\t\tif(GET_WM_COMMAND_ID(wParam, lParam) == IDOK)\n\t\t\t\t{\n\t\t\t\t\tWin32PopupDialog::HandleOKClick(dialog);\n\t\t\t\t\tEndDialog(dialog, 0);\n\t\t\t\t}\n\t\t\t\telse if(GET_WM_COMMAND_ID(wParam, lParam) == IDCANCEL)\n\t\t\t\t{\n\t\t\t\t\tEndDialog(dialog, 0);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn FALSE;\n\t}\n\n\tint Win32PopupDialog::CountMatches(std::string& message, const char *token)\n\t{\n\t\tint matches = 0;\n\t\tsize_t pos = 0, tokenSize = strlen(token);\n\t\twhile (pos != std::string::npos) \n\t\t{\n\t\t\tpos = message.find(token, pos);\n\t\t\tif (pos != std::string::npos)\n\t\t\t{\n\t\t\t\tmatches++;\n\t\t\t\tpos += tokenSize;\n\t\t\t}\n\t\t}\n\t\treturn matches;\n\t}\n\t\n\tBOOL Win32PopupDialog::ShowMessageBox(HWND hwnd)\n\t{\n\t\tBOOL fSuccess = FALSE;\n\t\tHDC hdc = GetDC(hwnd);\n\n\t\tif (hdc)\n\t\t{\n\t\t\tNONCLIENTMETRICSW nonClientMetrics = { sizeof(NONCLIENTMETRICSW) };\n\t\t\tif (SystemParametersInfoW(\n\t\t\t\tSPI_GETNONCLIENTMETRICS, 0, &nonClientMetrics, 0))\n\t\t\t{\n\t\t\t\tDialogTemplate tmp;\n\t\t\t\tstd::wstring wideTitle(::UTF8ToWide(title));\n\t\t\t\tstd::wstring wideInputText;\n\t\t\t\tif (this->showInputText)\n\t\t\t\t\twideInputText.assign(::UTF8ToWide(inputText));\n\n\t\t\t\tint controlCount = 2;\t\/\/ at minimum, static label and OK button\n\t\t\t\tif (this->showCancelButton)\n\t\t\t\t\tcontrolCount++;\n\t\t\t\tif (this->showInputText)\n\t\t\t\t\tcontrolCount++;\n\n\t\t\t\tint messageLines = 0;\n\t\t\t\tint newlines = CountMatches(message, \"\\n\");\n\t\t\t\tint tabs = CountMatches(message, \"\\t\");\n\t\t\t\tint spaces = CountMatches(message, \" \");\n\n\t\t\t\tif (newlines == 0 && tabs == 0 && spaces == 0)\n\t\t\t\t{\n\t\t\t\t\tstd::string tempMessage(message);\n\t\t\t\t\tif (tempMessage.length() != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint insertAt = 60;\n\t\t\t\t\t\tint count = 0;\n\n\t\t\t\t\t\tstd::string::iterator it = tempMessage.begin();\n\t\t\t\t\t\tfor (; it < tempMessage.end(); it++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\tif (count == 60)\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\tcount = 0;\n\t\t\t\t\t\t\t\tmessage.insert(insertAt, \"\\n\");\n\t\t\t\t\t\t\t\tinsertAt += 60;\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}\n\t\t\t\t\n\t\t\t\tstd::wstring wideMessage(::UTF8ToWide(message));\n\t\t\t\tmessageLines = message.length() \/ 60;\n\t\t\t\tmessageLines += ((int) ceil((double)tabs \/ 14));\n\t\t\t\tmessageLines += newlines;\n\t\t\t\t\n\t\t\t\tif (tabs == 0 || newlines == 0)\n\t\t\t\t\tmessageLines++;\n\n\t\t\t\tint labelHeight = 14;\n\t\t\t\tint width = 200;\n\t\t\t\tint margin = 10;\n\t\t\t\tint buttonWidth = 50;\n\t\t\t\tint buttonHeight = 14;\n\t\t\t\tint inputHeight = 14;\n\t\t\t\tint messageHeight = (messageLines * 12) + (messageLines * margin);\n\t\t\t\tint height = messageHeight + 56;\n\t\t\t\t\n\t\t\t\tif (!this->showInputText)\n\t\t\t\t{\n\t\t\t\t\theight -= (inputHeight + margin);\n\t\t\t\t}\n\n\t\t\t\t\/\/ Write out the extended dialog template header\n\t\t\t\ttmp.Write<WORD>(1); \/\/ dialog version\n\t\t\t\ttmp.Write<WORD>(0xFFFF); \/\/ extended dialog template\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ help ID\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ extended style\n\t\t\t\ttmp.Write<DWORD>(WS_CAPTION | WS_BORDER | DS_ABSALIGN | DS_SETFONT);\n\t\t\t\ttmp.Write<WORD>(controlCount); \/\/ number of controls\n\t\t\t\ttmp.Write<WORD>(32); \/\/ X\n\t\t\t\ttmp.Write<WORD>(32); \/\/ Y\n\t\t\t\ttmp.Write<WORD>(width); \/\/ width\n\t\t\t\ttmp.Write<WORD>(height); \/\/ height\n\t\t\t\ttmp.WriteString(L\"\"); \/\/ no menu\n\t\t\t\ttmp.WriteString(L\"\"); \/\/ default dialog class\n\t\t\t\t\/\/tmp.WriteString(pszTitle); \/\/ title\n\t\t\t\ttmp.WriteString(wideTitle.c_str()); \/\/ title\n\n\t\t\t\t\/\/ Next comes the font description.\n\t\t\t\t\/\/ See text for discussion of fancy formula.\n\t\t\t\t\n\t\t\t\tif (nonClientMetrics.lfMessageFont.lfHeight < 0)\n\t\t\t\t{\n\t\t\t\t\tint dpi = GetDeviceCaps(hdc, LOGPIXELSY);\n\t\t\t\t\tnonClientMetrics.lfMessageFont.lfHeight =\n\t\t\t\t\t\t-MulDiv(nonClientMetrics.lfMessageFont.lfHeight, 72, dpi);\n\t\t\t\t}\n\t\t\t\ttmp.Write<WORD>((WORD)nonClientMetrics.lfMessageFont.lfHeight); \/\/ point\n\t\t\t\ttmp.Write<WORD>((WORD)nonClientMetrics.lfMessageFont.lfWeight); \/\/ weight\n\t\t\t\ttmp.Write<BYTE>(nonClientMetrics.lfMessageFont.lfItalic); \/\/ Italic\n\t\t\t\ttmp.Write<BYTE>(nonClientMetrics.lfMessageFont.lfCharSet); \/\/ CharSet\n\t\t\t\ttmp.WriteString(nonClientMetrics.lfMessageFont.lfFaceName);\n\n\t\t\t\t\/\/ First control - static label\n\t\t\t\ttmp.AlignToDword();\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ help id\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ window extended style\n\t\t\t\ttmp.Write<DWORD>(WS_CHILD | WS_VISIBLE | SS_LEFT); \/\/ style\n\t\t\t\ttmp.Write<WORD>(margin); \/\/ x\n\t\t\t\ttmp.Write<WORD>(margin); \/\/ y\n\t\t\t\ttmp.Write<WORD>(width - (2 * margin)); \/\/ width\n\t\t\t\t\/\/tmp.Write<WORD>(labelHeight); \/\/ height\n\t\t\t\ttmp.Write<WORD>(messageHeight); \/\/ height\n\t\t\t\ttmp.Write<DWORD>(-1); \/\/ control ID\n\t\t\t\ttmp.Write<DWORD>(0x0082FFFF); \/\/ static\n\t\t\t\t\/\/tmp.Write<DWORD>(SS_LEFT);\n\t\t\t\ttmp.WriteString(wideMessage.c_str()); \/\/ text\n\t\t\t\ttmp.Write<WORD>(0); \/\/ no extra data\n\n\t\t\t\t\/\/ Second control - the OK button.\n\t\t\t\ttmp.AlignToDword();\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ help id\n\t\t\t\ttmp.Write<DWORD>(0); \/\/ window extended style\n\t\t\t\ttmp.Write<DWORD>(WS_CHILD | WS_VISIBLE | WS_GROUP | WS_TABSTOP | BS_DEFPUSHBUTTON); \/\/ style\n\t\t\t\ttmp.Write<WORD>(width - margin - buttonWidth); \/\/ x\n\t\t\t\ttmp.Write<WORD>(height - margin - buttonHeight); \/\/ y\n\t\t\t\ttmp.Write<WORD>(buttonWidth); \/\/ width\n\t\t\t\ttmp.Write<WORD>(buttonHeight); \/\/ height\n\t\t\t\ttmp.Write<DWORD>(IDCANCEL); \/\/ control ID\n\t\t\t\ttmp.Write<DWORD>(0x0080FFFF); \/\/ button class atom\n\t\t\t\ttmp.WriteString(L\"Cancel\"); \/\/ text\n\t\t\t\ttmp.Write<WORD>(0); \/\/ no extra data\n\n\t\t\t\tif (this->showCancelButton)\n\t\t\t\t{\n\t\t\t\t\t\/\/ The Cancel button\n\t\t\t\t\ttmp.AlignToDword();\n\t\t\t\t\ttmp.Write<DWORD>(0); \/\/ help id\n\t\t\t\t\ttmp.Write<DWORD>(0); \/\/ window extended style\n\t\t\t\t\ttmp.Write<DWORD>(WS_CHILD | WS_VISIBLE | WS_GROUP | WS_TABSTOP | BS_DEFPUSHBUTTON); \/\/ style\n\t\t\t\t\ttmp.Write<WORD>(width - 2 * margin - 2 * buttonWidth); \/\/ x\n\t\t\t\t\ttmp.Write<WORD>(height - margin - buttonHeight); \/\/ y\n\t\t\t\t\ttmp.Write<WORD>(buttonWidth); \/\/ width\n\t\t\t\t\ttmp.Write<WORD>(buttonHeight); \/\/ height\n\t\t\t\t\ttmp.Write<DWORD>(IDOK); \/\/ control ID\n\t\t\t\t\ttmp.Write<DWORD>(0x0080FFFF); \/\/ button class atom\n\t\t\t\t\ttmp.WriteString(L\"OK\"); \/\/ text\n\t\t\t\t\ttmp.Write<WORD>(0); \/\/ no extra data\n\t\t\t\t}\n\n\t\t\t\tif (this->showInputText)\n\t\t\t\t{\n\t\t\t\t\t\/\/ The input field\n\t\t\t\t\ttmp.AlignToDword();\n\t\t\t\t\ttmp.Write<DWORD>(0); \/\/ help id\n\t\t\t\t\ttmp.Write<DWORD>(0); \/\/ window extended style\n\t\t\t\t\ttmp.Write<DWORD>(ES_LEFT | WS_BORDER | WS_TABSTOP | WS_CHILD | WS_VISIBLE); \/\/ style\n\t\t\t\t\ttmp.Write<WORD>(margin); \/\/ x\n\t\t\t\t\ttmp.Write<WORD>(margin + labelHeight + margin); \/\/ y\n\t\t\t\t\ttmp.Write<WORD>(width - (2 * margin)); \/\/ width\n\t\t\t\t\ttmp.Write<WORD>(inputHeight); \/\/ height\n\t\t\t\t\ttmp.Write<DWORD>(ID_INPUT_FIELD); \/\/ control ID\n\t\t\t\t\ttmp.Write<DWORD>(0x0081FFFF); \/\/ edit class atom\n\t\t\t\t\ttmp.WriteString(wideInputText.c_str()); \/\/ text\n\t\t\t\t\ttmp.Write<WORD>(0); \/\/ no extra data\n\t\t\t\t}\n\n\t\t\t\t\/\/ Template is ready - go display it.\n\t\t\t\tfSuccess = DialogBoxIndirect(\n\t\t\t\t\tGetModuleHandle(NULL),\n\t\t\t\t\ttmp.Template(),\n\t\t\t\t\thwnd,\n\t\t\t\t\t&Win32PopupDialog::Callback) >= 0;\n\t\t\t}\n\t\t\tReleaseDC(NULL, hdc); \/\/ fixed 11 May\n\t\t}\n\t\treturn fSuccess;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\n#include <algorithm> \/\/ std::max\n\n#include \"api\/video\/video_bitrate_allocator.h\"\n#include \"common_types.h\" \/\/ NOLINT(build\/include)\n#include \"common_video\/libyuv\/include\/webrtc_libyuv.h\"\n#include \"modules\/video_coding\/encoded_frame.h\"\n#include \"modules\/video_coding\/include\/video_codec_interface.h\"\n#include \"modules\/video_coding\/utility\/default_video_bitrate_allocator.h\"\n#include \"modules\/video_coding\/utility\/quality_scaler.h\"\n#include \"modules\/video_coding\/video_coding_impl.h\"\n#include \"rtc_base\/checks.h\"\n#include \"rtc_base\/logging.h\"\n#include \"system_wrappers\/include\/clock.h\"\n\nnamespace webrtc {\nnamespace vcm {\n\nVideoSender::VideoSender(Clock* clock,\n EncodedImageCallback* post_encode_callback)\n : _encoder(nullptr),\n _mediaOpt(clock),\n _encodedFrameCallback(post_encode_callback, &_mediaOpt),\n post_encode_callback_(post_encode_callback),\n _codecDataBase(&_encodedFrameCallback),\n frame_dropper_enabled_(true),\n current_codec_(),\n encoder_params_({VideoBitrateAllocation(), 0, 0, 0}),\n encoder_has_internal_source_(false),\n next_frame_types_(1, kVideoFrameDelta) {\n _mediaOpt.Reset();\n \/\/ Allow VideoSender to be created on one thread but used on another, post\n \/\/ construction. This is currently how this class is being used by at least\n \/\/ one external project (diffractor).\n sequenced_checker_.Detach();\n}\n\nVideoSender::~VideoSender() {}\n\n\/\/ Register the send codec to be used.\nint32_t VideoSender::RegisterSendCodec(const VideoCodec* sendCodec,\n uint32_t numberOfCores,\n uint32_t maxPayloadSize) {\n RTC_DCHECK(sequenced_checker_.CalledSequentially());\n rtc::CritScope lock(&encoder_crit_);\n if (sendCodec == nullptr) {\n return VCM_PARAMETER_ERROR;\n }\n\n bool ret =\n _codecDataBase.SetSendCodec(sendCodec, numberOfCores, maxPayloadSize);\n\n \/\/ Update encoder regardless of result to make sure that we're not holding on\n \/\/ to a deleted instance.\n _encoder = _codecDataBase.GetEncoder();\n \/\/ Cache the current codec here so they can be fetched from this thread\n \/\/ without requiring the _sendCritSect lock.\n current_codec_ = *sendCodec;\n\n if (!ret) {\n RTC_LOG(LS_ERROR) << \"Failed to initialize set encoder with codec type '\"\n << sendCodec->codecType << \"'.\";\n return VCM_CODEC_ERROR;\n }\n\n \/\/ SetSendCodec succeeded, _encoder should be set.\n RTC_DCHECK(_encoder);\n\n int numLayers;\n if (sendCodec->codecType == kVideoCodecVP8) {\n numLayers = sendCodec->VP8().numberOfTemporalLayers;\n } else if (sendCodec->codecType == kVideoCodecVP9) {\n numLayers = sendCodec->VP9().numberOfTemporalLayers;\n } else if (sendCodec->codecType == kVideoCodecGeneric &&\n sendCodec->numberOfSimulcastStreams > 0) {\n \/\/ This is mainly for unit testing, disabling frame dropping.\n \/\/ TODO(sprang): Add a better way to disable frame dropping.\n numLayers = sendCodec->simulcastStream[0].numberOfTemporalLayers;\n } else {\n numLayers = 1;\n }\n\n \/\/ If we have screensharing and we have layers, we disable frame dropper.\n bool disable_frame_dropper =\n numLayers > 1 && sendCodec->mode == VideoCodecMode::kScreensharing;\n if (disable_frame_dropper) {\n _mediaOpt.EnableFrameDropper(false);\n } else if (frame_dropper_enabled_) {\n _mediaOpt.EnableFrameDropper(true);\n }\n\n {\n rtc::CritScope cs(¶ms_crit_);\n next_frame_types_.clear();\n next_frame_types_.resize(VCM_MAX(sendCodec->numberOfSimulcastStreams, 1),\n kVideoFrameKey);\n \/\/ Cache InternalSource() to have this available from IntraFrameRequest()\n \/\/ without having to acquire encoder_crit_ (avoid blocking on encoder use).\n encoder_has_internal_source_ = _encoder->InternalSource();\n }\n\n RTC_LOG(LS_VERBOSE) << \" max bitrate \" << sendCodec->maxBitrate\n << \" start bitrate \" << sendCodec->startBitrate\n << \" max frame rate \" << sendCodec->maxFramerate\n << \" max payload size \" << maxPayloadSize;\n _mediaOpt.SetEncodingData(sendCodec->maxBitrate * 1000,\n sendCodec->startBitrate * 1000,\n sendCodec->maxFramerate);\n return VCM_OK;\n}\n\n\/\/ Register an external decoder object.\n\/\/ This can not be used together with external decoder callbacks.\nvoid VideoSender::RegisterExternalEncoder(VideoEncoder* externalEncoder,\n bool internalSource \/*= false*\/) {\n RTC_DCHECK(sequenced_checker_.CalledSequentially());\n\n rtc::CritScope lock(&encoder_crit_);\n\n if (externalEncoder == nullptr) {\n _codecDataBase.DeregisterExternalEncoder();\n {\n \/\/ Make sure the VCM doesn't use the de-registered codec\n rtc::CritScope params_lock(¶ms_crit_);\n _encoder = nullptr;\n encoder_has_internal_source_ = false;\n }\n return;\n }\n _codecDataBase.RegisterExternalEncoder(externalEncoder,\n internalSource);\n}\n\nEncoderParameters VideoSender::UpdateEncoderParameters(\n const EncoderParameters& params,\n VideoBitrateAllocator* bitrate_allocator,\n uint32_t target_bitrate_bps) {\n uint32_t video_target_rate_bps = _mediaOpt.SetTargetRates(target_bitrate_bps);\n uint32_t input_frame_rate = _mediaOpt.InputFrameRate();\n if (input_frame_rate == 0)\n input_frame_rate = current_codec_.maxFramerate;\n\n VideoBitrateAllocation bitrate_allocation;\n \/\/ Only call allocators if bitrate > 0 (ie, not suspended), otherwise they\n \/\/ might cap the bitrate to the min bitrate configured.\n if (target_bitrate_bps > 0) {\n if (bitrate_allocator) {\n bitrate_allocation = bitrate_allocator->GetAllocation(\n video_target_rate_bps, input_frame_rate);\n } else {\n DefaultVideoBitrateAllocator default_allocator(current_codec_);\n bitrate_allocation = default_allocator.GetAllocation(\n video_target_rate_bps, input_frame_rate);\n }\n }\n EncoderParameters new_encoder_params = {bitrate_allocation, params.loss_rate,\n params.rtt, input_frame_rate};\n return new_encoder_params;\n}\n\nvoid VideoSender::UpdateChannelParameters(\n VideoBitrateAllocator* bitrate_allocator,\n VideoBitrateAllocationObserver* bitrate_updated_callback) {\n VideoBitrateAllocation target_rate;\n {\n rtc::CritScope cs(¶ms_crit_);\n encoder_params_ =\n UpdateEncoderParameters(encoder_params_, bitrate_allocator,\n encoder_params_.target_bitrate.get_sum_bps());\n target_rate = encoder_params_.target_bitrate;\n }\n if (bitrate_updated_callback && target_rate.get_sum_bps() > 0)\n bitrate_updated_callback->OnBitrateAllocationUpdated(target_rate);\n}\n\nint32_t VideoSender::SetChannelParameters(\n uint32_t target_bitrate_bps,\n uint8_t loss_rate,\n int64_t rtt,\n VideoBitrateAllocator* bitrate_allocator,\n VideoBitrateAllocationObserver* bitrate_updated_callback) {\n EncoderParameters encoder_params;\n encoder_params.loss_rate = loss_rate;\n encoder_params.rtt = rtt;\n encoder_params = UpdateEncoderParameters(encoder_params, bitrate_allocator,\n target_bitrate_bps);\n if (bitrate_updated_callback && target_bitrate_bps > 0) {\n bitrate_updated_callback->OnBitrateAllocationUpdated(\n encoder_params.target_bitrate);\n }\n\n bool encoder_has_internal_source;\n {\n rtc::CritScope cs(¶ms_crit_);\n encoder_params_ = encoder_params;\n encoder_has_internal_source = encoder_has_internal_source_;\n }\n\n \/\/ For encoders with internal sources, we need to tell the encoder directly,\n \/\/ instead of waiting for an AddVideoFrame that will never come (internal\n \/\/ source encoders don't get input frames).\n if (encoder_has_internal_source) {\n rtc::CritScope cs(&encoder_crit_);\n if (_encoder) {\n SetEncoderParameters(encoder_params, encoder_has_internal_source);\n }\n }\n\n return VCM_OK;\n}\n\nvoid VideoSender::SetEncoderParameters(EncoderParameters params,\n bool has_internal_source) {\n \/\/ |target_bitrate == 0 | means that the network is down or the send pacer is\n \/\/ full. We currently only report this if the encoder has an internal source.\n \/\/ If the encoder does not have an internal source, higher levels are expected\n \/\/ to not call AddVideoFrame. We do this since its unclear how current\n \/\/ encoder implementations behave when given a zero target bitrate.\n \/\/ TODO(perkj): Make sure all known encoder implementations handle zero\n \/\/ target bitrate and remove this check.\n if (!has_internal_source && params.target_bitrate.get_sum_bps() == 0)\n return;\n\n if (params.input_frame_rate == 0) {\n \/\/ No frame rate estimate available, use default.\n params.input_frame_rate = current_codec_.maxFramerate;\n }\n if (_encoder != nullptr)\n _encoder->SetEncoderParameters(params);\n}\n\n\/\/ Add one raw video frame to the encoder, blocking.\nint32_t VideoSender::AddVideoFrame(const VideoFrame& videoFrame,\n const CodecSpecificInfo* codecSpecificInfo) {\n EncoderParameters encoder_params;\n std::vector<FrameType> next_frame_types;\n bool encoder_has_internal_source = false;\n {\n rtc::CritScope lock(¶ms_crit_);\n encoder_params = encoder_params_;\n next_frame_types = next_frame_types_;\n encoder_has_internal_source = encoder_has_internal_source_;\n }\n rtc::CritScope lock(&encoder_crit_);\n if (_encoder == nullptr)\n return VCM_UNINITIALIZED;\n SetEncoderParameters(encoder_params, encoder_has_internal_source);\n if (_mediaOpt.DropFrame()) {\n RTC_LOG(LS_VERBOSE) << \"Drop Frame \"\n << \"target bitrate \"\n << encoder_params.target_bitrate.get_sum_bps()\n << \" loss rate \" << encoder_params.loss_rate << \" rtt \"\n << encoder_params.rtt << \" input frame rate \"\n << encoder_params.input_frame_rate;\n post_encode_callback_->OnDroppedFrame(\n EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);\n return VCM_OK;\n }\n \/\/ TODO(pbos): Make sure setting send codec is synchronized with video\n \/\/ processing so frame size always matches.\n if (!_codecDataBase.MatchesCurrentResolution(videoFrame.width(),\n videoFrame.height())) {\n RTC_LOG(LS_ERROR)\n << \"Incoming frame doesn't match set resolution. Dropping.\";\n return VCM_PARAMETER_ERROR;\n }\n VideoFrame converted_frame = videoFrame;\n const VideoFrameBuffer::Type buffer_type =\n converted_frame.video_frame_buffer()->type();\n const bool is_buffer_type_supported =\n buffer_type == VideoFrameBuffer::Type::kI420 ||\n (buffer_type == VideoFrameBuffer::Type::kNative &&\n _encoder->SupportsNativeHandle());\n if (!is_buffer_type_supported) {\n \/\/ This module only supports software encoding.\n \/\/ TODO(pbos): Offload conversion from the encoder thread.\n rtc::scoped_refptr<I420BufferInterface> converted_buffer(\n converted_frame.video_frame_buffer()->ToI420());\n\n if (!converted_buffer) {\n RTC_LOG(LS_ERROR) << \"Frame conversion failed, dropping frame.\";\n return VCM_PARAMETER_ERROR;\n }\n converted_frame = VideoFrame(converted_buffer,\n converted_frame.timestamp(),\n converted_frame.render_time_ms(),\n converted_frame.rotation());\n }\n int32_t ret =\n _encoder->Encode(converted_frame, codecSpecificInfo, next_frame_types);\n if (ret < 0) {\n RTC_LOG(LS_ERROR) << \"Failed to encode frame. Error code: \" << ret;\n return ret;\n }\n\n {\n rtc::CritScope lock(¶ms_crit_);\n \/\/ Change all keyframe requests to encode delta frames the next time.\n for (size_t i = 0; i < next_frame_types_.size(); ++i) {\n \/\/ Check for equality (same requested as before encoding) to not\n \/\/ accidentally drop a keyframe request while encoding.\n if (next_frame_types[i] == next_frame_types_[i])\n next_frame_types_[i] = kVideoFrameDelta;\n }\n }\n return VCM_OK;\n}\n\nint32_t VideoSender::IntraFrameRequest(size_t stream_index) {\n {\n rtc::CritScope lock(¶ms_crit_);\n if (stream_index >= next_frame_types_.size()) {\n return -1;\n }\n next_frame_types_[stream_index] = kVideoFrameKey;\n if (!encoder_has_internal_source_)\n return VCM_OK;\n }\n \/\/ TODO(pbos): Remove when InternalSource() is gone. Both locks have to be\n \/\/ held here for internal consistency, since _encoder could be removed while\n \/\/ not holding encoder_crit_. Checks have to be performed again since\n \/\/ params_crit_ was dropped to not cause lock-order inversions with\n \/\/ encoder_crit_.\n rtc::CritScope lock(&encoder_crit_);\n rtc::CritScope params_lock(¶ms_crit_);\n if (stream_index >= next_frame_types_.size())\n return -1;\n if (_encoder != nullptr && _encoder->InternalSource()) {\n \/\/ Try to request the frame if we have an external encoder with\n \/\/ internal source since AddVideoFrame never will be called.\n if (_encoder->RequestFrame(next_frame_types_) == WEBRTC_VIDEO_CODEC_OK) {\n \/\/ Try to remove just-performed keyframe request, if stream still exists.\n next_frame_types_[stream_index] = kVideoFrameDelta;\n }\n }\n return VCM_OK;\n}\n\nint32_t VideoSender::EnableFrameDropper(bool enable) {\n rtc::CritScope lock(&encoder_crit_);\n frame_dropper_enabled_ = enable;\n _mediaOpt.EnableFrameDropper(enable);\n return VCM_OK;\n}\n} \/\/ namespace vcm\n} \/\/ namespace webrtc\n<commit_msg>Add field trial for disabling FrameDropper.<commit_after>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\n#include <algorithm> \/\/ std::max\n\n#include \"api\/video\/video_bitrate_allocator.h\"\n#include \"common_types.h\" \/\/ NOLINT(build\/include)\n#include \"common_video\/libyuv\/include\/webrtc_libyuv.h\"\n#include \"modules\/video_coding\/encoded_frame.h\"\n#include \"modules\/video_coding\/include\/video_codec_interface.h\"\n#include \"modules\/video_coding\/utility\/default_video_bitrate_allocator.h\"\n#include \"modules\/video_coding\/utility\/quality_scaler.h\"\n#include \"modules\/video_coding\/video_coding_impl.h\"\n#include \"rtc_base\/checks.h\"\n#include \"rtc_base\/logging.h\"\n#include \"system_wrappers\/include\/clock.h\"\n#include \"system_wrappers\/include\/field_trial.h\"\n\nnamespace webrtc {\nnamespace vcm {\n\nnamespace {\n\nconstexpr char kFrameDropperFieldTrial[] = \"WebRTC-FrameDropper\";\n\n} \/\/ namespace\n\nVideoSender::VideoSender(Clock* clock,\n EncodedImageCallback* post_encode_callback)\n : _encoder(nullptr),\n _mediaOpt(clock),\n _encodedFrameCallback(post_encode_callback, &_mediaOpt),\n post_encode_callback_(post_encode_callback),\n _codecDataBase(&_encodedFrameCallback),\n frame_dropper_enabled_(true),\n current_codec_(),\n encoder_params_({VideoBitrateAllocation(), 0, 0, 0}),\n encoder_has_internal_source_(false),\n next_frame_types_(1, kVideoFrameDelta) {\n _mediaOpt.Reset();\n \/\/ Allow VideoSender to be created on one thread but used on another, post\n \/\/ construction. This is currently how this class is being used by at least\n \/\/ one external project (diffractor).\n sequenced_checker_.Detach();\n}\n\nVideoSender::~VideoSender() {}\n\n\/\/ Register the send codec to be used.\nint32_t VideoSender::RegisterSendCodec(const VideoCodec* sendCodec,\n uint32_t numberOfCores,\n uint32_t maxPayloadSize) {\n RTC_DCHECK(sequenced_checker_.CalledSequentially());\n rtc::CritScope lock(&encoder_crit_);\n if (sendCodec == nullptr) {\n return VCM_PARAMETER_ERROR;\n }\n\n bool ret =\n _codecDataBase.SetSendCodec(sendCodec, numberOfCores, maxPayloadSize);\n\n \/\/ Update encoder regardless of result to make sure that we're not holding on\n \/\/ to a deleted instance.\n _encoder = _codecDataBase.GetEncoder();\n \/\/ Cache the current codec here so they can be fetched from this thread\n \/\/ without requiring the _sendCritSect lock.\n current_codec_ = *sendCodec;\n\n if (!ret) {\n RTC_LOG(LS_ERROR) << \"Failed to initialize set encoder with codec type '\"\n << sendCodec->codecType << \"'.\";\n return VCM_CODEC_ERROR;\n }\n\n \/\/ SetSendCodec succeeded, _encoder should be set.\n RTC_DCHECK(_encoder);\n\n int numLayers;\n if (sendCodec->codecType == kVideoCodecVP8) {\n numLayers = sendCodec->VP8().numberOfTemporalLayers;\n } else if (sendCodec->codecType == kVideoCodecVP9) {\n numLayers = sendCodec->VP9().numberOfTemporalLayers;\n } else if (sendCodec->codecType == kVideoCodecGeneric &&\n sendCodec->numberOfSimulcastStreams > 0) {\n \/\/ This is mainly for unit testing, disabling frame dropping.\n \/\/ TODO(sprang): Add a better way to disable frame dropping.\n numLayers = sendCodec->simulcastStream[0].numberOfTemporalLayers;\n } else {\n numLayers = 1;\n }\n\n \/\/ If we have screensharing and we have layers, we disable frame dropper.\n const bool disable_frame_dropper =\n field_trial::IsDisabled(kFrameDropperFieldTrial) ||\n (numLayers > 1 && sendCodec->mode == VideoCodecMode::kScreensharing);\n if (disable_frame_dropper) {\n _mediaOpt.EnableFrameDropper(false);\n } else if (frame_dropper_enabled_) {\n _mediaOpt.EnableFrameDropper(true);\n }\n\n {\n rtc::CritScope cs(¶ms_crit_);\n next_frame_types_.clear();\n next_frame_types_.resize(VCM_MAX(sendCodec->numberOfSimulcastStreams, 1),\n kVideoFrameKey);\n \/\/ Cache InternalSource() to have this available from IntraFrameRequest()\n \/\/ without having to acquire encoder_crit_ (avoid blocking on encoder use).\n encoder_has_internal_source_ = _encoder->InternalSource();\n }\n\n RTC_LOG(LS_VERBOSE) << \" max bitrate \" << sendCodec->maxBitrate\n << \" start bitrate \" << sendCodec->startBitrate\n << \" max frame rate \" << sendCodec->maxFramerate\n << \" max payload size \" << maxPayloadSize;\n _mediaOpt.SetEncodingData(sendCodec->maxBitrate * 1000,\n sendCodec->startBitrate * 1000,\n sendCodec->maxFramerate);\n return VCM_OK;\n}\n\n\/\/ Register an external decoder object.\n\/\/ This can not be used together with external decoder callbacks.\nvoid VideoSender::RegisterExternalEncoder(VideoEncoder* externalEncoder,\n bool internalSource \/*= false*\/) {\n RTC_DCHECK(sequenced_checker_.CalledSequentially());\n\n rtc::CritScope lock(&encoder_crit_);\n\n if (externalEncoder == nullptr) {\n _codecDataBase.DeregisterExternalEncoder();\n {\n \/\/ Make sure the VCM doesn't use the de-registered codec\n rtc::CritScope params_lock(¶ms_crit_);\n _encoder = nullptr;\n encoder_has_internal_source_ = false;\n }\n return;\n }\n _codecDataBase.RegisterExternalEncoder(externalEncoder,\n internalSource);\n}\n\nEncoderParameters VideoSender::UpdateEncoderParameters(\n const EncoderParameters& params,\n VideoBitrateAllocator* bitrate_allocator,\n uint32_t target_bitrate_bps) {\n uint32_t video_target_rate_bps = _mediaOpt.SetTargetRates(target_bitrate_bps);\n uint32_t input_frame_rate = _mediaOpt.InputFrameRate();\n if (input_frame_rate == 0)\n input_frame_rate = current_codec_.maxFramerate;\n\n VideoBitrateAllocation bitrate_allocation;\n \/\/ Only call allocators if bitrate > 0 (ie, not suspended), otherwise they\n \/\/ might cap the bitrate to the min bitrate configured.\n if (target_bitrate_bps > 0) {\n if (bitrate_allocator) {\n bitrate_allocation = bitrate_allocator->GetAllocation(\n video_target_rate_bps, input_frame_rate);\n } else {\n DefaultVideoBitrateAllocator default_allocator(current_codec_);\n bitrate_allocation = default_allocator.GetAllocation(\n video_target_rate_bps, input_frame_rate);\n }\n }\n EncoderParameters new_encoder_params = {bitrate_allocation, params.loss_rate,\n params.rtt, input_frame_rate};\n return new_encoder_params;\n}\n\nvoid VideoSender::UpdateChannelParameters(\n VideoBitrateAllocator* bitrate_allocator,\n VideoBitrateAllocationObserver* bitrate_updated_callback) {\n VideoBitrateAllocation target_rate;\n {\n rtc::CritScope cs(¶ms_crit_);\n encoder_params_ =\n UpdateEncoderParameters(encoder_params_, bitrate_allocator,\n encoder_params_.target_bitrate.get_sum_bps());\n target_rate = encoder_params_.target_bitrate;\n }\n if (bitrate_updated_callback && target_rate.get_sum_bps() > 0)\n bitrate_updated_callback->OnBitrateAllocationUpdated(target_rate);\n}\n\nint32_t VideoSender::SetChannelParameters(\n uint32_t target_bitrate_bps,\n uint8_t loss_rate,\n int64_t rtt,\n VideoBitrateAllocator* bitrate_allocator,\n VideoBitrateAllocationObserver* bitrate_updated_callback) {\n EncoderParameters encoder_params;\n encoder_params.loss_rate = loss_rate;\n encoder_params.rtt = rtt;\n encoder_params = UpdateEncoderParameters(encoder_params, bitrate_allocator,\n target_bitrate_bps);\n if (bitrate_updated_callback && target_bitrate_bps > 0) {\n bitrate_updated_callback->OnBitrateAllocationUpdated(\n encoder_params.target_bitrate);\n }\n\n bool encoder_has_internal_source;\n {\n rtc::CritScope cs(¶ms_crit_);\n encoder_params_ = encoder_params;\n encoder_has_internal_source = encoder_has_internal_source_;\n }\n\n \/\/ For encoders with internal sources, we need to tell the encoder directly,\n \/\/ instead of waiting for an AddVideoFrame that will never come (internal\n \/\/ source encoders don't get input frames).\n if (encoder_has_internal_source) {\n rtc::CritScope cs(&encoder_crit_);\n if (_encoder) {\n SetEncoderParameters(encoder_params, encoder_has_internal_source);\n }\n }\n\n return VCM_OK;\n}\n\nvoid VideoSender::SetEncoderParameters(EncoderParameters params,\n bool has_internal_source) {\n \/\/ |target_bitrate == 0 | means that the network is down or the send pacer is\n \/\/ full. We currently only report this if the encoder has an internal source.\n \/\/ If the encoder does not have an internal source, higher levels are expected\n \/\/ to not call AddVideoFrame. We do this since its unclear how current\n \/\/ encoder implementations behave when given a zero target bitrate.\n \/\/ TODO(perkj): Make sure all known encoder implementations handle zero\n \/\/ target bitrate and remove this check.\n if (!has_internal_source && params.target_bitrate.get_sum_bps() == 0)\n return;\n\n if (params.input_frame_rate == 0) {\n \/\/ No frame rate estimate available, use default.\n params.input_frame_rate = current_codec_.maxFramerate;\n }\n if (_encoder != nullptr)\n _encoder->SetEncoderParameters(params);\n}\n\n\/\/ Add one raw video frame to the encoder, blocking.\nint32_t VideoSender::AddVideoFrame(const VideoFrame& videoFrame,\n const CodecSpecificInfo* codecSpecificInfo) {\n EncoderParameters encoder_params;\n std::vector<FrameType> next_frame_types;\n bool encoder_has_internal_source = false;\n {\n rtc::CritScope lock(¶ms_crit_);\n encoder_params = encoder_params_;\n next_frame_types = next_frame_types_;\n encoder_has_internal_source = encoder_has_internal_source_;\n }\n rtc::CritScope lock(&encoder_crit_);\n if (_encoder == nullptr)\n return VCM_UNINITIALIZED;\n SetEncoderParameters(encoder_params, encoder_has_internal_source);\n if (_mediaOpt.DropFrame()) {\n RTC_LOG(LS_VERBOSE) << \"Drop Frame \"\n << \"target bitrate \"\n << encoder_params.target_bitrate.get_sum_bps()\n << \" loss rate \" << encoder_params.loss_rate << \" rtt \"\n << encoder_params.rtt << \" input frame rate \"\n << encoder_params.input_frame_rate;\n post_encode_callback_->OnDroppedFrame(\n EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);\n return VCM_OK;\n }\n \/\/ TODO(pbos): Make sure setting send codec is synchronized with video\n \/\/ processing so frame size always matches.\n if (!_codecDataBase.MatchesCurrentResolution(videoFrame.width(),\n videoFrame.height())) {\n RTC_LOG(LS_ERROR)\n << \"Incoming frame doesn't match set resolution. Dropping.\";\n return VCM_PARAMETER_ERROR;\n }\n VideoFrame converted_frame = videoFrame;\n const VideoFrameBuffer::Type buffer_type =\n converted_frame.video_frame_buffer()->type();\n const bool is_buffer_type_supported =\n buffer_type == VideoFrameBuffer::Type::kI420 ||\n (buffer_type == VideoFrameBuffer::Type::kNative &&\n _encoder->SupportsNativeHandle());\n if (!is_buffer_type_supported) {\n \/\/ This module only supports software encoding.\n \/\/ TODO(pbos): Offload conversion from the encoder thread.\n rtc::scoped_refptr<I420BufferInterface> converted_buffer(\n converted_frame.video_frame_buffer()->ToI420());\n\n if (!converted_buffer) {\n RTC_LOG(LS_ERROR) << \"Frame conversion failed, dropping frame.\";\n return VCM_PARAMETER_ERROR;\n }\n converted_frame = VideoFrame(converted_buffer,\n converted_frame.timestamp(),\n converted_frame.render_time_ms(),\n converted_frame.rotation());\n }\n int32_t ret =\n _encoder->Encode(converted_frame, codecSpecificInfo, next_frame_types);\n if (ret < 0) {\n RTC_LOG(LS_ERROR) << \"Failed to encode frame. Error code: \" << ret;\n return ret;\n }\n\n {\n rtc::CritScope lock(¶ms_crit_);\n \/\/ Change all keyframe requests to encode delta frames the next time.\n for (size_t i = 0; i < next_frame_types_.size(); ++i) {\n \/\/ Check for equality (same requested as before encoding) to not\n \/\/ accidentally drop a keyframe request while encoding.\n if (next_frame_types[i] == next_frame_types_[i])\n next_frame_types_[i] = kVideoFrameDelta;\n }\n }\n return VCM_OK;\n}\n\nint32_t VideoSender::IntraFrameRequest(size_t stream_index) {\n {\n rtc::CritScope lock(¶ms_crit_);\n if (stream_index >= next_frame_types_.size()) {\n return -1;\n }\n next_frame_types_[stream_index] = kVideoFrameKey;\n if (!encoder_has_internal_source_)\n return VCM_OK;\n }\n \/\/ TODO(pbos): Remove when InternalSource() is gone. Both locks have to be\n \/\/ held here for internal consistency, since _encoder could be removed while\n \/\/ not holding encoder_crit_. Checks have to be performed again since\n \/\/ params_crit_ was dropped to not cause lock-order inversions with\n \/\/ encoder_crit_.\n rtc::CritScope lock(&encoder_crit_);\n rtc::CritScope params_lock(¶ms_crit_);\n if (stream_index >= next_frame_types_.size())\n return -1;\n if (_encoder != nullptr && _encoder->InternalSource()) {\n \/\/ Try to request the frame if we have an external encoder with\n \/\/ internal source since AddVideoFrame never will be called.\n if (_encoder->RequestFrame(next_frame_types_) == WEBRTC_VIDEO_CODEC_OK) {\n \/\/ Try to remove just-performed keyframe request, if stream still exists.\n next_frame_types_[stream_index] = kVideoFrameDelta;\n }\n }\n return VCM_OK;\n}\n\nint32_t VideoSender::EnableFrameDropper(bool enable) {\n rtc::CritScope lock(&encoder_crit_);\n frame_dropper_enabled_ = enable;\n _mediaOpt.EnableFrameDropper(enable);\n return VCM_OK;\n}\n} \/\/ namespace vcm\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2020 Google 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\n#include \"augmenter\/augmenter.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"protocol_buffer\/document.pb.h\"\n#include \"protocol_buffer\/documents.pb.h\"\n\nnamespace augmenter {\n\nbert_annotator::Documents construct_test_document() {\n bert_annotator::Documents documents;\n bert_annotator::Document* document = documents.add_documents();\n document->set_text(\"Text with some InterWordCapitalization\");\n bert_annotator::Token* token;\n token = document->add_token();\n token->set_start(0);\n token->set_end(3);\n token->set_word(\"Text\");\n token = document->add_token();\n token->set_start(5);\n token->set_end(8);\n token->set_word(\"with\");\n token = document->add_token();\n token->set_start(10);\n token->set_end(13);\n token->set_word(\"some\");\n token = document->add_token();\n token->set_start(15);\n token->set_end(37);\n token->set_word(\"InterWordCapitalization\");\n\n return documents;\n}\n\nTEST(AugmenterTest, AugmentsAreAdded) {\n bert_annotator::Documents documents = construct_test_document();\n Augmenter augmenter = Augmenter(documents);\n\n augmenter.lowercase(1.0);\n\n ASSERT_EQ(augmenter.get_documents().documents_size(), 2);\n}\n\nTEST(AugmenterTest, NoLowercasingForZeroPercent) {\n bert_annotator::Documents documents = construct_test_document();\n Augmenter augmenter = Augmenter(documents);\n\n augmenter.lowercase(0.0);\n\n ASSERT_STREQ(augmenter.get_documents().documents(0).text().c_str(),\n \"Text with some InterWordCapitalization\");\n}\n\nTEST(AugmenterTest, CompleteLowercasingForHundretPercent) {\n bert_annotator::Documents documents = construct_test_document();\n Augmenter augmenter = Augmenter(documents);\n\n augmenter.lowercase(1.0);\n\n ASSERT_STREQ(augmenter.get_documents().documents(1).text().c_str(),\n \"text with some interwordcapitalization\");\n}\n\nTEST(AugmenterTest, DontLowercaseNonTokens) {\n bert_annotator::Documents documents;\n bert_annotator::Document* document = documents.add_documents();\n document->set_text(\"[BOS] Text with some InterWordCapitalization [EOS]\");\n bert_annotator::Token* token;\n token = document->add_token();\n token->set_start(6);\n token->set_end(9);\n token->set_word(\"Text\");\n token = document->add_token();\n token->set_start(11);\n token->set_end(14);\n token->set_word(\"with\");\n token = document->add_token();\n token->set_start(16);\n token->set_end(19);\n token->set_word(\"some\");\n token = document->add_token();\n token->set_start(21);\n token->set_end(43);\n token->set_word(\"InterWordCapitalization\");\n Augmenter augmenter = Augmenter(documents);\n\n augmenter.lowercase(1.0);\n\n ASSERT_STREQ(augmenter.get_documents().documents(1).text().c_str(),\n \"[BOS] text with some interwordcapitalization [EOS]\");\n}\n\n} \/\/ namespace augmenter\n<commit_msg>Fixed typo<commit_after>\/\/\n\/\/ Copyright 2020 Google 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\n#include \"augmenter\/augmenter.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"protocol_buffer\/document.pb.h\"\n#include \"protocol_buffer\/documents.pb.h\"\n\nnamespace augmenter {\n\nbert_annotator::Documents construct_test_document() {\n bert_annotator::Documents documents;\n bert_annotator::Document* document = documents.add_documents();\n document->set_text(\"Text with some InterWordCapitalization\");\n bert_annotator::Token* token;\n token = document->add_token();\n token->set_start(0);\n token->set_end(3);\n token->set_word(\"Text\");\n token = document->add_token();\n token->set_start(5);\n token->set_end(8);\n token->set_word(\"with\");\n token = document->add_token();\n token->set_start(10);\n token->set_end(13);\n token->set_word(\"some\");\n token = document->add_token();\n token->set_start(15);\n token->set_end(37);\n token->set_word(\"InterWordCapitalization\");\n\n return documents;\n}\n\nTEST(AugmenterTest, AugmentsAreAdded) {\n bert_annotator::Documents documents = construct_test_document();\n Augmenter augmenter = Augmenter(documents);\n\n augmenter.lowercase(1.0);\n\n ASSERT_EQ(augmenter.get_documents().documents_size(), 2);\n}\n\nTEST(AugmenterTest, NoLowercasingForZeroPercent) {\n bert_annotator::Documents documents = construct_test_document();\n Augmenter augmenter = Augmenter(documents);\n\n augmenter.lowercase(0.0);\n\n ASSERT_STREQ(augmenter.get_documents().documents(0).text().c_str(),\n \"Text with some InterWordCapitalization\");\n}\n\nTEST(AugmenterTest, CompleteLowercasingForHundredPercent) {\n bert_annotator::Documents documents = construct_test_document();\n Augmenter augmenter = Augmenter(documents);\n\n augmenter.lowercase(1.0);\n\n ASSERT_STREQ(augmenter.get_documents().documents(1).text().c_str(),\n \"text with some interwordcapitalization\");\n}\n\nTEST(AugmenterTest, DontLowercaseNonTokens) {\n bert_annotator::Documents documents;\n bert_annotator::Document* document = documents.add_documents();\n document->set_text(\"[BOS] Text with some InterWordCapitalization [EOS]\");\n bert_annotator::Token* token;\n token = document->add_token();\n token->set_start(6);\n token->set_end(9);\n token->set_word(\"Text\");\n token = document->add_token();\n token->set_start(11);\n token->set_end(14);\n token->set_word(\"with\");\n token = document->add_token();\n token->set_start(16);\n token->set_end(19);\n token->set_word(\"some\");\n token = document->add_token();\n token->set_start(21);\n token->set_end(43);\n token->set_word(\"InterWordCapitalization\");\n Augmenter augmenter = Augmenter(documents);\n\n augmenter.lowercase(1.0);\n\n ASSERT_STREQ(augmenter.get_documents().documents(1).text().c_str(),\n \"[BOS] text with some interwordcapitalization [EOS]\");\n}\n\n} \/\/ namespace augmenter\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ Copyright 2017 Matt Kaes All Rights Reserved.\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#pragma once\n#include \"immintrin.h\" \/\/ AVX Intrinsics\n#include <cstring> \/\/ memset\n#include <intrin.h> \/\/ _BitScanForward\n\n\/\/ Make sure we are able to use AVX2\n#ifndef __AVX2__\n#ifdef _MSC_VER\n#warning \"AVX2 is not enabled. Please compile with \/arch:AVX2\"\n#else\n#error \"AVX2 is not enabled. Please compile with -mavx\"\n#endif\n#endif \/\/ !__AVX2__\n\n\/\/ This is important to make sure magic AVX alignment works\nstatic_assert(sizeof(int) == 4, \"unsigned != 4 bytes! Alignment issues for buckets will occur.\");\n\n\/\/ Turn Intel warnings into errors\n#pragma warning (error: 4752)\n\n#define _m_256i_IntPack(a) _mm256_set_epi32(a,a,a,a,a,a,a,a)\n#define AVX_Or(a, b)\n\n\n\/\/ Linear probing Vector Table for unsigned four byte words\n\/\/ Non-distructing variant\ntemplate <typename Value>\nclass VectorizedTable {\npublic:\n VectorizedTable()\n {\n m_valueHeap = nullptr;\n m_mm_keyHeap = nullptr;\n m_mm_statesHeap = nullptr;\n\n grow(MinCapacity);\n }\n\n ~VectorizedTable()\n {\n \/\/ Would just be faster to leak &| segfault\n delete[] m_valueHeap;\n _mm_free(m_mm_keyHeap);\n _mm_free(m_mm_statesHeap);\n }\n\n\n Value& add(int index, const Value& value)\n {\n \/\/ Catch the issue with repeat adds\n int slot = slotOf(hash(index));\n if (slot != -1)\n return m_valueHeap[slot] = value;\n\n return insert(hash(index), value);\n }\n\n bool containsKey(int index) const\n {\n return slotOf(hash(index)) != -1;\n }\n\n Value& at(int index)\n {\n int slot = slotOf(hash(index));\n\n if (slot != -1)\n return m_valueHeap[slot];\n else\n return insert(hash(index), Value());\n }\n\n const Value& operator[](int index) const\n {\n int slot = slotOf(hash(index));\n\n if (slot != -1)\n return m_valueHeap[slot];\n else\n return Value();\n }\n\n Value& operator[](int index)\n {\n return at(index);\n }\n\n void clear()\n {\n memset(m_mm_keyHeap, 0, m_capacity * sizeof(int));\n memset(m_mm_statesHeap, 0, m_capacity * sizeof(int));\n }\n\n int size()\n {\n return m_size;\n }\n\n int capacity()\n {\n return m_capacity;\n }\n\nprivate:\n int hash(int x) const {\n x = ((x >> 16) ^ x) * 0x45d9f3b;\n x = ((x >> 16) ^ x) * 0x45d9f3b;\n x = (x >> 16) ^ x;\n return x;\n }\n\n Value& insert(int hashIndex, const Value& value)\n {\n if (m_size >= m_capacity \/ GrowFactor)\n grow(m_capacity * GrowFactor);\n m_size++;\n\n int slot = openSlot(hashIndex);\n m_mm_keyHeap[slot] = hashIndex;\n m_mm_statesHeap[slot] = BucketState::InUse;\n return m_valueHeap[slot] = value;\n }\n\n int openSlot(int hashedIndex) const\n {\n \/\/ Create an InUse mask to see if a bucket is full\n const __m256i inuseMask = _m_256i_IntPack((int)BucketState::InUse);\n int bucketId = ((hashedIndex % m_capacity) \/ sizeof(__m256i) * sizeof(int)) \/ sizeof(int);\n const int bucketCount = m_capacity * sizeof(int) \/ sizeof(__m256i);\n const int bucketCountBits = bucketCount - 1;\n\n while (true)\n {\n \/\/ life finding\n const __m256i stateMask1 = _mm256_and_si256(byte1Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId], inuseMask));\n const __m256i stateMask2 = _mm256_and_si256(byte2Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 1], inuseMask));\n const __m256i stateMask3 = _mm256_and_si256(byte3Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 2], inuseMask));\n const __m256i stateMask4 = _mm256_and_si256(byte4Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 3], inuseMask));\n const int stateMap = ~_mm256_movemask_epi8(_mm256_or_si256(_mm256_or_si256(_mm256_or_si256(stateMask1, stateMask2), stateMask3), stateMask4));\n\n unsigned long lowestIndex;\n const long slotFound = _BitScanForward(&lowestIndex, stateMap);\n\n if (slotFound)\n return (bucketId << 3) + ((lowestIndex & 3) << 3) + (lowestIndex >> 2);\n\n \/\/ Next bucket.\n bucketId = (bucketId + 4) & (bucketCountBits);\n }\n }\n\n int slotOf(int hashedIndex) const\n {\n \/\/ Create an Empty mask to see if we can stop\n const __m256i emptyMask = _m_256i_IntPack((int)BucketState::Empty);\n const __m256i inuseMask = _m_256i_IntPack((int)BucketState::InUse);\n const __m256i indexMask = _m_256i_IntPack(hashedIndex);\n\n int bucketId = ((hashedIndex % m_capacity) \/ sizeof(__m256i) * sizeof(int)) \/ sizeof(int);\n const int bucketCount = m_capacity * sizeof(int) \/ sizeof(__m256i);\n const int bucketCountBits = bucketCount - 1;\n int emptyBucket = 0;\n\n while (true)\n {\n \/\/ Value finding\n const __m256i valueMask1 = _mm256_and_si256(byte1Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_keyHeap)[bucketId], indexMask));\n const __m256i valueMask2 = _mm256_and_si256(byte2Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_keyHeap)[bucketId + 1], indexMask));\n const __m256i valueMask3 = _mm256_and_si256(byte3Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_keyHeap)[bucketId + 2], indexMask));\n const __m256i valueMask4 = _mm256_and_si256(byte4Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_keyHeap)[bucketId + 3], indexMask));\n \n \/\/ life finding\n const __m256i stateMask1 = _mm256_and_si256(byte1Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId], inuseMask));\n const __m256i stateMask2 = _mm256_and_si256(byte2Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 1], inuseMask));\n const __m256i stateMask3 = _mm256_and_si256(byte3Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 2], inuseMask));\n const __m256i stateMask4 = _mm256_and_si256(byte4Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 3], inuseMask));\n\n \/\/ Back to scaler mode\n int valueMap = _mm256_movemask_epi8(_mm256_or_si256(_mm256_or_si256(_mm256_or_si256(valueMask1, valueMask2), valueMask3), valueMask4));\n const int stateMap = _mm256_movemask_epi8(_mm256_or_si256(_mm256_or_si256(_mm256_or_si256(stateMask1, stateMask2), stateMask3), stateMask4));\n\n \/\/ Wipe empty cells\n valueMap &= stateMap;\n\n unsigned long lowestIndex;\n const long foundValue = _BitScanForward(&lowestIndex, valueMap);\n\n if (foundValue)\n return (bucketId << 3) + ((lowestIndex & 3) << 3) + (lowestIndex >> 2);\n\n \/\/ Empty block found\n __m256i empty = _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId], emptyMask);\n empty = _mm256_or_si256(empty, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 1], emptyMask));\n empty = _mm256_or_si256(empty, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 2], emptyMask));\n empty = _mm256_or_si256(empty, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 3], emptyMask));\n\n if (_mm256_movemask_epi8(empty))\n return -1;\n\n bucketId = (bucketId + 4) & (bucketCountBits);\n }\n }\n\n void grow(int capacity)\n {\n \/\/ Keep a reference to the old pointers\n Value* oldValueHeap = m_valueHeap;\n int* oldKeyHeap = m_mm_keyHeap;\n BucketState* oldStatesHeap = m_mm_statesHeap;\n int oldCapacity = m_capacity;\n\n \/\/ Creating all of the objects\n m_size = 0;\n m_capacity = capacity;\n m_valueHeap = new Value[m_capacity];\n m_mm_keyHeap = (int*)_mm_malloc(m_capacity * sizeof(*m_mm_keyHeap), AVXAlignment);\n m_mm_statesHeap = (BucketState*)_mm_malloc(m_capacity * sizeof(*m_mm_statesHeap), AVXAlignment);\n\n clear();\n\n if (oldStatesHeap)\n {\n for (int i = 0; i < oldCapacity; i++)\n if (oldStatesHeap[i] == BucketState::InUse)\n insert(oldKeyHeap[i], oldValueHeap[i]);\n\n delete[] oldValueHeap;\n _mm_free(oldKeyHeap);\n _mm_free(oldStatesHeap);\n }\n }\n\n enum class BucketState : int\n {\n Empty = 0,\n InUse = 1,\n Dead = 2\n };\n\n Value* m_valueHeap;\n int* m_mm_keyHeap;\n BucketState* m_mm_statesHeap;\n\n int m_size;\n int m_capacity;\n\n const int AVXAlignment = 16;\n const int MinCapacity = 64;\n const int GrowFactor = 4;\n\n const __m256i byte1Mask = _m_256i_IntPack(0x000000FF);\n const __m256i byte2Mask = _m_256i_IntPack(0x0000FF00);\n const __m256i byte3Mask = _m_256i_IntPack(0x00FF0000);\n const __m256i byte4Mask = _m_256i_IntPack(0xFF000000);\n};<commit_msg>Clear Fix<commit_after>\/\/\/\n\/\/\/ Copyright 2017 Matt Kaes All Rights Reserved.\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#pragma once\n#include \"immintrin.h\" \/\/ AVX Intrinsics\n#include <cstring> \/\/ memset\n#include <intrin.h> \/\/ _BitScanForward\n\n\/\/ Make sure we are able to use AVX2\n#ifndef __AVX2__\n#ifdef _MSC_VER\n#warning \"AVX2 is not enabled. Please compile with \/arch:AVX2\"\n#else\n#error \"AVX2 is not enabled. Please compile with -mavx\"\n#endif\n#endif \/\/ !__AVX2__\n\n\/\/ This is important to make sure magic AVX alignment works\nstatic_assert(sizeof(int) == 4, \"unsigned != 4 bytes! Alignment issues for buckets will occur.\");\n\n\/\/ Turn Intel warnings into errors\n#pragma warning (error: 4752)\n\n#define _m_256i_IntPack(a) _mm256_set_epi32(a,a,a,a,a,a,a,a)\n#define AVX_Or(a, b)\n\n\n\/\/ Linear probing Vector Table for unsigned four byte words\n\/\/ Non-distructing variant\ntemplate <typename Value>\nclass VectorizedTable {\npublic:\n VectorizedTable()\n {\n m_valueHeap = nullptr;\n m_mm_keyHeap = nullptr;\n m_mm_statesHeap = nullptr;\n\n grow(MinCapacity);\n }\n\n ~VectorizedTable()\n {\n delete[] m_valueHeap;\n _mm_free(m_mm_keyHeap);\n _mm_free(m_mm_statesHeap);\n }\n\n\n Value& add(int index, const Value& value)\n {\n \/\/ Catch the issue with repeat adds\n int slot = slotOf(hash(index));\n if (slot != -1)\n return m_valueHeap[slot] = value;\n\n return insert(hash(index), value);\n }\n\n bool containsKey(int index) const\n {\n return slotOf(hash(index)) != -1;\n }\n\n Value& at(int index)\n {\n int slot = slotOf(hash(index));\n\n if (slot != -1)\n return m_valueHeap[slot];\n else\n return insert(hash(index), Value());\n }\n\n const Value& operator[](int index) const\n {\n int slot = slotOf(hash(index));\n\n if (slot != -1)\n return m_valueHeap[slot];\n else\n return Value();\n }\n\n Value& operator[](int index)\n {\n return at(index);\n }\n\n void clear()\n {\n m_size = 0;\n memset(m_mm_keyHeap, 0, m_capacity * sizeof(int));\n memset(m_mm_statesHeap, 0, m_capacity * sizeof(int));\n }\n\n int size()\n {\n return m_size;\n }\n\n int capacity()\n {\n return m_capacity;\n }\n\nprivate:\n int hash(int x) const {\n x = ((x >> 16) ^ x) * 0x45d9f3b;\n x = ((x >> 16) ^ x) * 0x45d9f3b;\n x = (x >> 16) ^ x;\n return x;\n }\n\n Value& insert(int hashIndex, const Value& value)\n {\n if (m_size >= m_capacity \/ GrowFactor)\n grow(m_capacity * GrowFactor);\n m_size++;\n\n int slot = openSlot(hashIndex);\n m_mm_keyHeap[slot] = hashIndex;\n m_mm_statesHeap[slot] = BucketState::InUse;\n return m_valueHeap[slot] = value;\n }\n\n int openSlot(int hashedIndex) const\n {\n \/\/ Create an InUse mask to see if a bucket is full\n const __m256i inuseMask = _m_256i_IntPack((int)BucketState::InUse);\n int bucketId = ((hashedIndex % m_capacity) \/ sizeof(__m256i) * sizeof(int)) \/ sizeof(int);\n const int bucketCount = m_capacity * sizeof(int) \/ sizeof(__m256i);\n const int bucketCountBits = bucketCount - 1;\n\n while (true)\n {\n \/\/ life finding\n const __m256i stateMask1 = _mm256_and_si256(byte1Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId], inuseMask));\n const __m256i stateMask2 = _mm256_and_si256(byte2Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 1], inuseMask));\n const __m256i stateMask3 = _mm256_and_si256(byte3Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 2], inuseMask));\n const __m256i stateMask4 = _mm256_and_si256(byte4Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 3], inuseMask));\n const int stateMap = ~_mm256_movemask_epi8(_mm256_or_si256(_mm256_or_si256(_mm256_or_si256(stateMask1, stateMask2), stateMask3), stateMask4));\n\n unsigned long lowestIndex;\n const long slotFound = _BitScanForward(&lowestIndex, stateMap);\n\n if (slotFound)\n return (bucketId << 3) + ((lowestIndex & 3) << 3) + (lowestIndex >> 2);\n\n \/\/ Next bucket.\n bucketId = (bucketId + 4) & (bucketCountBits);\n }\n }\n\n int slotOf(int hashedIndex) const\n {\n \/\/ Create an Empty mask to see if we can stop\n const __m256i emptyMask = _m_256i_IntPack((int)BucketState::Empty);\n const __m256i inuseMask = _m_256i_IntPack((int)BucketState::InUse);\n const __m256i indexMask = _m_256i_IntPack(hashedIndex);\n\n int bucketId = ((hashedIndex % m_capacity) \/ sizeof(__m256i) * sizeof(int)) \/ sizeof(int);\n const int bucketCount = m_capacity * sizeof(int) \/ sizeof(__m256i);\n const int bucketCountBits = bucketCount - 1;\n int emptyBucket = 0;\n\n while (true)\n {\n \/\/ Value finding\n const __m256i valueMask1 = _mm256_and_si256(byte1Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_keyHeap)[bucketId], indexMask));\n const __m256i valueMask2 = _mm256_and_si256(byte2Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_keyHeap)[bucketId + 1], indexMask));\n const __m256i valueMask3 = _mm256_and_si256(byte3Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_keyHeap)[bucketId + 2], indexMask));\n const __m256i valueMask4 = _mm256_and_si256(byte4Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_keyHeap)[bucketId + 3], indexMask));\n \n \/\/ life finding\n const __m256i stateMask1 = _mm256_and_si256(byte1Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId], inuseMask));\n const __m256i stateMask2 = _mm256_and_si256(byte2Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 1], inuseMask));\n const __m256i stateMask3 = _mm256_and_si256(byte3Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 2], inuseMask));\n const __m256i stateMask4 = _mm256_and_si256(byte4Mask, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 3], inuseMask));\n\n \/\/ Back to scaler mode\n int valueMap = _mm256_movemask_epi8(_mm256_or_si256(_mm256_or_si256(_mm256_or_si256(valueMask1, valueMask2), valueMask3), valueMask4));\n const int stateMap = _mm256_movemask_epi8(_mm256_or_si256(_mm256_or_si256(_mm256_or_si256(stateMask1, stateMask2), stateMask3), stateMask4));\n\n \/\/ Wipe empty cells\n valueMap &= stateMap;\n\n unsigned long lowestIndex;\n const long foundValue = _BitScanForward(&lowestIndex, valueMap);\n\n if (foundValue)\n return (bucketId << 3) + ((lowestIndex & 3) << 3) + (lowestIndex >> 2);\n\n \/\/ Empty block found\n __m256i empty = _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId], emptyMask);\n empty = _mm256_or_si256(empty, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 1], emptyMask));\n empty = _mm256_or_si256(empty, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 2], emptyMask));\n empty = _mm256_or_si256(empty, _mm256_cmpeq_epi32(((__m256i*)m_mm_statesHeap)[bucketId + 3], emptyMask));\n\n if (_mm256_movemask_epi8(empty))\n return -1;\n\n bucketId = (bucketId + 4) & (bucketCountBits);\n }\n }\n\n void grow(int capacity)\n {\n \/\/ Keep a reference to the old pointers\n Value* oldValueHeap = m_valueHeap;\n int* oldKeyHeap = m_mm_keyHeap;\n BucketState* oldStatesHeap = m_mm_statesHeap;\n int oldCapacity = m_capacity;\n\n \/\/ Creating all of the objects\n m_capacity = capacity;\n m_valueHeap = new Value[m_capacity];\n m_mm_keyHeap = (int*)_mm_malloc(m_capacity * sizeof(*m_mm_keyHeap), AVXAlignment);\n m_mm_statesHeap = (BucketState*)_mm_malloc(m_capacity * sizeof(*m_mm_statesHeap), AVXAlignment);\n\n clear();\n\n if (oldStatesHeap)\n {\n for (int i = 0; i < oldCapacity; i++)\n if (oldStatesHeap[i] == BucketState::InUse)\n insert(oldKeyHeap[i], oldValueHeap[i]);\n\n delete[] oldValueHeap;\n _mm_free(oldKeyHeap);\n _mm_free(oldStatesHeap);\n }\n }\n\n enum class BucketState : int\n {\n Empty = 0,\n InUse = 1,\n Dead = 2\n };\n\n Value* m_valueHeap;\n int* m_mm_keyHeap;\n BucketState* m_mm_statesHeap;\n\n int m_size;\n int m_capacity;\n\n const int AVXAlignment = 16;\n const int MinCapacity = 64;\n const int GrowFactor = 4;\n\n const __m256i byte1Mask = _m_256i_IntPack(0x000000FF);\n const __m256i byte2Mask = _m_256i_IntPack(0x0000FF00);\n const __m256i byte3Mask = _m_256i_IntPack(0x00FF0000);\n const __m256i byte4Mask = _m_256i_IntPack(0xFF000000);\n};<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlmeta.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 22:31:14 $\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_sw.hxx\"\n\n\n#include <hintids.hxx>\n\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_\n#include <com\/sun\/star\/document\/XDocumentInfoSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_\n#include <com\/sun\/star\/text\/XTextDocument.hpp>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLMETAI_HXX\n#include <xmloff\/xmlmetai.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLMETAE_HXX\n#include <xmloff\/xmlmetae.hxx>\n#endif\n#ifndef _SVX_LANGITEM_HXX\n#include <svx\/langitem.hxx>\n#endif\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include <xmloff\/xmluconv.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n\n#ifndef _DOCSTAT_HXX\n#include \"docstat.hxx\"\n#endif\n#ifndef _SWDOCSH_HXX\n#include \"docsh.hxx\"\n#endif\n#ifndef _DOC_HXX \/\/autogen wg. SwDoc\n#include <doc.hxx>\n#endif\n#ifndef _UNOOBJ_HXX\n#include <unoobj.hxx>\n#endif\n\n#ifndef _XMLIMP_HXX\n#include \"xmlimp.hxx\"\n#endif\n\n#ifndef _XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::text;\nusing namespace ::xmloff::token;\n\n\/\/ ---------------------------------------------------------------------\n\nSvXMLImportContext *SwXMLImport::CreateMetaContext(\n const OUString& rLocalName )\n{\n SvXMLImportContext *pContext = 0;\n\n if( !(IsStylesOnlyMode() || IsInsertMode()) )\n {\n pContext = new SfxXMLMetaContext( *this,\n XML_NAMESPACE_OFFICE, rLocalName,\n GetModel() );\n }\n\n if( !pContext )\n pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE,\n rLocalName );\n\n return pContext;\n}\n\n\/\/ ---------------------------------------------------------------------\n\nenum SvXMLTokenMapAttrs\n{\n XML_TOK_META_STAT_TABLE = 1,\n XML_TOK_META_STAT_IMAGE = 2,\n XML_TOK_META_STAT_OLE = 4,\n XML_TOK_META_STAT_PAGE = 8,\n XML_TOK_META_STAT_PARA = 16,\n XML_TOK_META_STAT_WORD = 32,\n XML_TOK_META_STAT_CHAR = 64,\n XML_TOK_META_STAT_END=XML_TOK_UNKNOWN\n};\n\nstatic __FAR_DATA SvXMLTokenMapEntry aMetaStatAttrTokenMap[] =\n{\n { XML_NAMESPACE_META, XML_TABLE_COUNT, XML_TOK_META_STAT_TABLE },\n { XML_NAMESPACE_META, XML_IMAGE_COUNT, XML_TOK_META_STAT_IMAGE },\n { XML_NAMESPACE_META, XML_OBJECT_COUNT, XML_TOK_META_STAT_OLE },\n { XML_NAMESPACE_META, XML_PARAGRAPH_COUNT, XML_TOK_META_STAT_PARA },\n { XML_NAMESPACE_META, XML_PAGE_COUNT, XML_TOK_META_STAT_PAGE },\n { XML_NAMESPACE_META, XML_WORD_COUNT, XML_TOK_META_STAT_WORD },\n { XML_NAMESPACE_META, XML_CHARACTER_COUNT, XML_TOK_META_STAT_CHAR },\n XML_TOKEN_MAP_END\n};\nvoid SwXMLImport::SetStatisticAttributes(\n const Reference< xml::sax::XAttributeList > & xAttrList)\n{\n if( IsStylesOnlyMode() || IsInsertMode() )\n return;\n\n SvXMLImport::SetStatisticAttributes(xAttrList);\n\n Reference<XUnoTunnel> xCrsrTunnel( GetTextImport()->GetCursor(),\n UNO_QUERY);\n ASSERT( xCrsrTunnel.is(), \"missing XUnoTunnel for Cursor\" );\n OTextCursorHelper *pTxtCrsr = (OTextCursorHelper*)xCrsrTunnel->getSomething(\n OTextCursorHelper::getUnoTunnelId() );\n ASSERT( pTxtCrsr, \"SwXTextCursor missing\" );\n SwDoc *pDoc = pTxtCrsr->GetDoc();\n SwDocStat aDocStat( pDoc->GetDocStat() );\n\n SvXMLTokenMap aTokenMap( aMetaStatAttrTokenMap );\n\n sal_uInt32 nTokens = 0;\n sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n for( sal_Int16 i=0; i < nAttrCount; i++ )\n {\n const OUString& rValue = xAttrList->getValueByIndex( i );\n sal_Int32 nValue;\n if( !GetMM100UnitConverter().convertNumber( nValue, rValue ) )\n continue;\n\n const OUString& rAttrName = xAttrList->getNameByIndex( i );\n OUString aLocalName;\n sal_uInt16 nPrefix =\n GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );\n\n sal_uInt32 nToken = aTokenMap.Get( nPrefix, aLocalName );\n switch( nToken )\n {\n case XML_TOK_META_STAT_TABLE:\n aDocStat.nTbl = (sal_uInt16)nValue;\n break;\n case XML_TOK_META_STAT_IMAGE:\n aDocStat.nGrf = (sal_uInt16)nValue;\n break;\n case XML_TOK_META_STAT_OLE:\n aDocStat.nOLE = (sal_uInt16)nValue;\n break;\n case XML_TOK_META_STAT_PAGE:\n aDocStat.nPage = (sal_uInt32)nValue;\n break;\n case XML_TOK_META_STAT_PARA:\n aDocStat.nPara = (sal_uInt32)nValue;\n break;\n case XML_TOK_META_STAT_WORD:\n aDocStat.nWord = (sal_uInt32)nValue;\n break;\n case XML_TOK_META_STAT_CHAR:\n aDocStat.nChar = (sal_uInt32)nValue;\n break;\n default:\n nToken = 0;\n }\n nTokens |= nToken;\n }\n\n if( 127 == nTokens )\n aDocStat.bModified = sal_False;\n if( nTokens )\n pDoc->SetDocStat( aDocStat );\n\n \/\/ set progress bar reference to #paragraphs. If not available,\n \/\/ use #pages*10, or guesstimate 250 paragraphs. Additionally\n \/\/ guesstimate PROGRESS_BAR_STEPS each for meta+settings, styles,\n \/\/ and autostyles.\n sal_Int32 nProgressReference = 250;\n if( nTokens & XML_TOK_META_STAT_PARA )\n nProgressReference = (sal_Int32)aDocStat.nPara;\n else if ( nTokens & XML_TOK_META_STAT_PAGE )\n nProgressReference = 10 * (sal_Int32)aDocStat.nPage;\n ProgressBarHelper* pProgress = GetProgressBarHelper();\n pProgress->SetReference( nProgressReference + 3*PROGRESS_BAR_STEP );\n pProgress->SetValue( 0 );\n}\n\n\/\/ ---------------------------------------------------------------------\n\nvoid SwXMLExport::_ExportMeta()\n{\n SvXMLExport::_ExportMeta();\n\n if( !IsBlockMode() )\n {\n OUStringBuffer aOut(16);\n\n Reference < XTextDocument > xTextDoc( GetModel(), UNO_QUERY );\n Reference < XText > xText = xTextDoc->getText();\n Reference<XUnoTunnel> xTextTunnel( xText, UNO_QUERY);\n ASSERT( xTextTunnel.is(), \"missing XUnoTunnel for Cursor\" );\n if( !xTextTunnel.is() )\n return;\n\n SwXText *pText = (SwXText *)xTextTunnel->getSomething(\n SwXText::getUnoTunnelId() );\n ASSERT( pText, \"SwXText missing\" );\n if( !pText )\n return;\n\n SwDocStat aDocStat( pText->GetDoc()->GetDocStat() );\n aOut.append( (sal_Int32)aDocStat.nTbl );\n AddAttribute( XML_NAMESPACE_META, XML_TABLE_COUNT,\n aOut.makeStringAndClear() );\n aOut.append( (sal_Int32)aDocStat.nGrf );\n AddAttribute( XML_NAMESPACE_META, XML_IMAGE_COUNT,\n aOut.makeStringAndClear() );\n aOut.append( (sal_Int32)aDocStat.nOLE );\n AddAttribute( XML_NAMESPACE_META, XML_OBJECT_COUNT,\n aOut.makeStringAndClear() );\n if( aDocStat.nPage )\n {\n aOut.append( (sal_Int32)aDocStat.nPage );\n AddAttribute( XML_NAMESPACE_META, XML_PAGE_COUNT,\n aOut.makeStringAndClear() );\n }\n aOut.append( (sal_Int32)aDocStat.nPara );\n AddAttribute( XML_NAMESPACE_META, XML_PARAGRAPH_COUNT,\n aOut.makeStringAndClear() );\n aOut.append( (sal_Int32)aDocStat.nWord );\n AddAttribute( XML_NAMESPACE_META, XML_WORD_COUNT,\n aOut.makeStringAndClear() );\n aOut.append( (sal_Int32)aDocStat.nChar );\n AddAttribute( XML_NAMESPACE_META, XML_CHARACTER_COUNT,\n aOut.makeStringAndClear() );\n SvXMLElementExport aElem( *this, XML_NAMESPACE_META,\n XML_DOCUMENT_STATISTIC,\n sal_True, sal_True );\n\n if( IsShowProgress() )\n {\n ProgressBarHelper *pProgress = GetProgressBarHelper();\n pProgress->SetValue( pProgress->GetValue() + 2 );\n }\n }\n}\n\n<commit_msg>INTEGRATION: CWS rpt23fix01 (1.15.386); FILE MERGED 2007\/07\/13 10:03:57 ama 1.15.386.1: Fix #i78827#: DocFromModel instead from TxtCrsr<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlmeta.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: hr $ $Date: 2007-08-02 14:22:03 $\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_sw.hxx\"\n\n\n#include <hintids.hxx>\n\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_\n#include <com\/sun\/star\/document\/XDocumentInfoSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_\n#include <com\/sun\/star\/text\/XTextDocument.hpp>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLMETAI_HXX\n#include <xmloff\/xmlmetai.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLMETAE_HXX\n#include <xmloff\/xmlmetae.hxx>\n#endif\n#ifndef _SVX_LANGITEM_HXX\n#include <svx\/langitem.hxx>\n#endif\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include <xmloff\/xmluconv.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n\n#ifndef _DOCSTAT_HXX\n#include \"docstat.hxx\"\n#endif\n#ifndef _SWDOCSH_HXX\n#include \"docsh.hxx\"\n#endif\n#ifndef _DOC_HXX \/\/autogen wg. SwDoc\n#include <doc.hxx>\n#endif\n#ifndef _UNOOBJ_HXX\n#include <unoobj.hxx>\n#endif\n\n#ifndef _XMLIMP_HXX\n#include \"xmlimp.hxx\"\n#endif\n\n#ifndef _XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::text;\nusing namespace ::xmloff::token;\n\n\/\/ ---------------------------------------------------------------------\n\nSvXMLImportContext *SwXMLImport::CreateMetaContext(\n const OUString& rLocalName )\n{\n SvXMLImportContext *pContext = 0;\n\n if( !(IsStylesOnlyMode() || IsInsertMode()) )\n {\n pContext = new SfxXMLMetaContext( *this,\n XML_NAMESPACE_OFFICE, rLocalName,\n GetModel() );\n }\n\n if( !pContext )\n pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE,\n rLocalName );\n\n return pContext;\n}\n\n\/\/ ---------------------------------------------------------------------\n\nenum SvXMLTokenMapAttrs\n{\n XML_TOK_META_STAT_TABLE = 1,\n XML_TOK_META_STAT_IMAGE = 2,\n XML_TOK_META_STAT_OLE = 4,\n XML_TOK_META_STAT_PAGE = 8,\n XML_TOK_META_STAT_PARA = 16,\n XML_TOK_META_STAT_WORD = 32,\n XML_TOK_META_STAT_CHAR = 64,\n XML_TOK_META_STAT_END=XML_TOK_UNKNOWN\n};\n\nstatic __FAR_DATA SvXMLTokenMapEntry aMetaStatAttrTokenMap[] =\n{\n { XML_NAMESPACE_META, XML_TABLE_COUNT, XML_TOK_META_STAT_TABLE },\n { XML_NAMESPACE_META, XML_IMAGE_COUNT, XML_TOK_META_STAT_IMAGE },\n { XML_NAMESPACE_META, XML_OBJECT_COUNT, XML_TOK_META_STAT_OLE },\n { XML_NAMESPACE_META, XML_PARAGRAPH_COUNT, XML_TOK_META_STAT_PARA },\n { XML_NAMESPACE_META, XML_PAGE_COUNT, XML_TOK_META_STAT_PAGE },\n { XML_NAMESPACE_META, XML_WORD_COUNT, XML_TOK_META_STAT_WORD },\n { XML_NAMESPACE_META, XML_CHARACTER_COUNT, XML_TOK_META_STAT_CHAR },\n XML_TOKEN_MAP_END\n};\nvoid SwXMLImport::SetStatisticAttributes(\n const Reference< xml::sax::XAttributeList > & xAttrList)\n{\n if( IsStylesOnlyMode() || IsInsertMode() )\n return;\n\n SvXMLImport::SetStatisticAttributes(xAttrList);\n\n SwDoc *pDoc = SwImport::GetDocFromXMLImport( *this );\n SwDocStat aDocStat( pDoc->GetDocStat() );\n\n SvXMLTokenMap aTokenMap( aMetaStatAttrTokenMap );\n\n sal_uInt32 nTokens = 0;\n sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n for( sal_Int16 i=0; i < nAttrCount; i++ )\n {\n const OUString& rValue = xAttrList->getValueByIndex( i );\n sal_Int32 nValue;\n if( !GetMM100UnitConverter().convertNumber( nValue, rValue ) )\n continue;\n\n const OUString& rAttrName = xAttrList->getNameByIndex( i );\n OUString aLocalName;\n sal_uInt16 nPrefix =\n GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );\n\n sal_uInt32 nToken = aTokenMap.Get( nPrefix, aLocalName );\n switch( nToken )\n {\n case XML_TOK_META_STAT_TABLE:\n aDocStat.nTbl = (sal_uInt16)nValue;\n break;\n case XML_TOK_META_STAT_IMAGE:\n aDocStat.nGrf = (sal_uInt16)nValue;\n break;\n case XML_TOK_META_STAT_OLE:\n aDocStat.nOLE = (sal_uInt16)nValue;\n break;\n case XML_TOK_META_STAT_PAGE:\n aDocStat.nPage = (sal_uInt32)nValue;\n break;\n case XML_TOK_META_STAT_PARA:\n aDocStat.nPara = (sal_uInt32)nValue;\n break;\n case XML_TOK_META_STAT_WORD:\n aDocStat.nWord = (sal_uInt32)nValue;\n break;\n case XML_TOK_META_STAT_CHAR:\n aDocStat.nChar = (sal_uInt32)nValue;\n break;\n default:\n nToken = 0;\n }\n nTokens |= nToken;\n }\n\n if( 127 == nTokens )\n aDocStat.bModified = sal_False;\n if( nTokens )\n pDoc->SetDocStat( aDocStat );\n\n \/\/ set progress bar reference to #paragraphs. If not available,\n \/\/ use #pages*10, or guesstimate 250 paragraphs. Additionally\n \/\/ guesstimate PROGRESS_BAR_STEPS each for meta+settings, styles,\n \/\/ and autostyles.\n sal_Int32 nProgressReference = 250;\n if( nTokens & XML_TOK_META_STAT_PARA )\n nProgressReference = (sal_Int32)aDocStat.nPara;\n else if ( nTokens & XML_TOK_META_STAT_PAGE )\n nProgressReference = 10 * (sal_Int32)aDocStat.nPage;\n ProgressBarHelper* pProgress = GetProgressBarHelper();\n pProgress->SetReference( nProgressReference + 3*PROGRESS_BAR_STEP );\n pProgress->SetValue( 0 );\n}\n\n\/\/ ---------------------------------------------------------------------\n\nvoid SwXMLExport::_ExportMeta()\n{\n SvXMLExport::_ExportMeta();\n\n if( !IsBlockMode() )\n {\n OUStringBuffer aOut(16);\n\n Reference < XTextDocument > xTextDoc( GetModel(), UNO_QUERY );\n Reference < XText > xText = xTextDoc->getText();\n Reference<XUnoTunnel> xTextTunnel( xText, UNO_QUERY);\n ASSERT( xTextTunnel.is(), \"missing XUnoTunnel for Cursor\" );\n if( !xTextTunnel.is() )\n return;\n\n SwXText *pText = (SwXText *)xTextTunnel->getSomething(\n SwXText::getUnoTunnelId() );\n ASSERT( pText, \"SwXText missing\" );\n if( !pText )\n return;\n\n SwDocStat aDocStat( pText->GetDoc()->GetDocStat() );\n aOut.append( (sal_Int32)aDocStat.nTbl );\n AddAttribute( XML_NAMESPACE_META, XML_TABLE_COUNT,\n aOut.makeStringAndClear() );\n aOut.append( (sal_Int32)aDocStat.nGrf );\n AddAttribute( XML_NAMESPACE_META, XML_IMAGE_COUNT,\n aOut.makeStringAndClear() );\n aOut.append( (sal_Int32)aDocStat.nOLE );\n AddAttribute( XML_NAMESPACE_META, XML_OBJECT_COUNT,\n aOut.makeStringAndClear() );\n if( aDocStat.nPage )\n {\n aOut.append( (sal_Int32)aDocStat.nPage );\n AddAttribute( XML_NAMESPACE_META, XML_PAGE_COUNT,\n aOut.makeStringAndClear() );\n }\n aOut.append( (sal_Int32)aDocStat.nPara );\n AddAttribute( XML_NAMESPACE_META, XML_PARAGRAPH_COUNT,\n aOut.makeStringAndClear() );\n aOut.append( (sal_Int32)aDocStat.nWord );\n AddAttribute( XML_NAMESPACE_META, XML_WORD_COUNT,\n aOut.makeStringAndClear() );\n aOut.append( (sal_Int32)aDocStat.nChar );\n AddAttribute( XML_NAMESPACE_META, XML_CHARACTER_COUNT,\n aOut.makeStringAndClear() );\n SvXMLElementExport aElem( *this, XML_NAMESPACE_META,\n XML_DOCUMENT_STATISTIC,\n sal_True, sal_True );\n\n if( IsShowProgress() )\n {\n ProgressBarHelper *pProgress = GetProgressBarHelper();\n pProgress->SetValue( pProgress->GetValue() + 2 );\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: drformsh.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 12:27:14 $\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_sw.hxx\"\n\n\n\n#include <hintids.hxx>\n#ifndef _SVX_HLNKITEM_HXX \/\/autogen\n#include <svx\/hlnkitem.hxx>\n#endif\n#ifndef _SVDVIEW_HXX \/\/autogen\n#include <svx\/svdview.hxx>\n#endif\n#ifndef _SFX_WHITER_HXX \/\/autogen\n#include <svtools\/whiter.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SFXOBJFACE_HXX \/\/autogen\n#include <sfx2\/objface.hxx>\n#endif\n#ifndef _SFXAPP_HXX \/\/autogen\n#include <sfx2\/app.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX\n#include <sfx2\/viewfrm.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX\n#include <sfx2\/dispatch.hxx>\n#endif\n#ifndef _SVX_SRCHITEM_HXX\n#include <svx\/srchitem.hxx>\n#endif\n#ifndef _SVX_FMGLOB_HXX\n#include <svx\/fmglob.hxx>\n#endif\n#ifndef _SVDOUNO_HXX \/\/autogen\n#include <svx\/svdouno.hxx>\n#endif\n#ifndef _COM_SUN_STAR_FORM_FORMBUTTONTYPE_HPP_\n#include <com\/sun\/star\/form\/FormButtonType.hpp>\n#endif\n#ifndef _SVX_HTMLMODE_HXX\n#include <svx\/htmlmode.hxx>\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen\n#include <tools\/urlobj.hxx>\n#endif\n\n#include \"viewopt.hxx\"\n#include \"swmodule.hxx\"\n#include \"wrtsh.hxx\"\n#include \"cmdid.h\"\n#include \"globals.hrc\"\n#include \"helpid.h\"\n#include \"popup.hrc\"\n#include \"shells.hrc\"\n#include \"drwbassh.hxx\"\n#include \"drformsh.hxx\"\n#ifndef SVTOOLS_URIHELPER_HXX\n#include <svtools\/urihelper.hxx>\n#endif\n#ifndef _VIEW_HXX\n#include <view.hxx>\n#endif\n#ifndef _SFXDOCFILE_HXX\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef _SWDOCSH_HXX\n#include <docsh.hxx>\n#endif\n\n#define SwDrawFormShell\n#include \"itemdef.hxx\"\n#include \"swslots.hxx\"\n\n#include <unomid.h>\n\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\n\nSFX_IMPL_INTERFACE(SwDrawFormShell, SwDrawBaseShell, SW_RES(STR_SHELLNAME_DRAWFORM))\n{\n SFX_POPUPMENU_REGISTRATION(SW_RES(MN_DRAWFORM_POPUPMENU));\n SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_TEXT_TOOLBOX));\n}\n\n\nTYPEINIT1(SwDrawFormShell, SwDrawBaseShell)\n\n\nvoid SwDrawFormShell::Execute(SfxRequest &rReq)\n{\n SwWrtShell &rSh = GetShell();\n const SfxPoolItem* pItem = 0;\n const SfxItemSet *pArgs = rReq.GetArgs();\n\n switch ( rReq.GetSlot() )\n {\n case SID_HYPERLINK_SETLINK:\n {\n if(pArgs)\n pArgs->GetItemState(SID_HYPERLINK_SETLINK, sal_False, &pItem);\n if(pItem)\n {\n SdrView *pSdrView = rSh.GetDrawView();\n const SvxHyperlinkItem& rHLinkItem = *(const SvxHyperlinkItem *)pItem;\n bool bConvertToText = rHLinkItem.GetInsertMode() == HLINK_DEFAULT ||\n rHLinkItem.GetInsertMode() == HLINK_FIELD;\n const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList();\n if (rMarkList.GetMark(0))\n {\n SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetMarkedSdrObj());\n if (pUnoCtrl && FmFormInventor == pUnoCtrl->GetObjInventor())\n {\n if(bConvertToText)\n {\n \/\/remove object -> results in destruction of this!\n SwView& rTempView = GetView();\n rTempView.GetViewFrame()->GetDispatcher()->Execute(SID_DELETE, SFX_CALLMODE_SYNCHRON );\n rTempView.StopShellTimer();\n \/\/issue a new command to insert the link\n rTempView.GetViewFrame()->GetDispatcher()->Execute(\n SID_HYPERLINK_SETLINK, SFX_CALLMODE_ASYNCHRON, &rHLinkItem, 0);\n }\n else\n {\n uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel();\n\n ASSERT( xControlModel.is(), \"UNO-Control ohne Model\" );\n if( !xControlModel.is() )\n return;\n\n uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY);\n\n \/\/ Darf man eine URL an dem Objekt setzen?\n OUString sTargetURL( C2U( \"TargetURL\" ));\n uno::Reference< beans::XPropertySetInfo > xPropInfoSet = xPropSet->getPropertySetInfo();\n if( xPropInfoSet->hasPropertyByName( sTargetURL ))\n {\n beans::Property aProp = xPropInfoSet->getPropertyByName( sTargetURL );\n if( aProp.Name.getLength() )\n {\n uno::Any aTmp;\n \/\/ Ja!\n aTmp <<= OUString(rHLinkItem.GetName());\n xPropSet->setPropertyValue(C2U(\"Label\"), aTmp );\n\n SfxMedium* pMedium = GetView().GetDocShell()->GetMedium();\n INetURLObject aAbs;\n if( pMedium )\n aAbs = pMedium->GetURLObject();\n aTmp <<= OUString(URIHelper::SmartRel2Abs(aAbs, rHLinkItem.GetURL()));\n xPropSet->setPropertyValue( sTargetURL, aTmp );\n\n if( rHLinkItem.GetTargetFrame().Len() )\n {\n aTmp <<= OUString(rHLinkItem.GetTargetFrame());\n xPropSet->setPropertyValue( C2U(\"TargetFrame\"), aTmp );\n }\n\n\n form::FormButtonType eButtonType = form::FormButtonType_URL;\n aTmp.setValue( &eButtonType, ::getCppuType((const form::FormButtonType*)0));\n xPropSet->setPropertyValue( C2U(\"ButtonType\"), aTmp );\n }\n }\n }\n }\n }\n }\n }\n break;\n\n default:\n DBG_ASSERT(!this, \"falscher Dispatcher\");\n return;\n }\n}\n\nvoid SwDrawFormShell::GetState(SfxItemSet& rSet)\n{\n SwWrtShell &rSh = GetShell();\n SfxWhichIter aIter( rSet );\n sal_uInt16 nWhich = aIter.FirstWhich();\n\n while( nWhich )\n {\n switch( nWhich )\n {\n case SID_HYPERLINK_GETLINK:\n {\n SdrView* pSdrView = rSh.GetDrawViewWithValidMarkList();\n const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList();\n SvxHyperlinkItem aHLinkItem;\n if (rMarkList.GetMark(0))\n {\n SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetMarkedSdrObj());\n if (pUnoCtrl && FmFormInventor == pUnoCtrl->GetObjInventor())\n {\n uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel();\n\n ASSERT( xControlModel.is(), \"UNO-Control ohne Model\" );\n if( !xControlModel.is() )\n return;\n\n uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY);\n\n uno::Any aTmp;\n uno::Reference< beans::XPropertySetInfo > xInfo = xPropSet->getPropertySetInfo();\n if(xInfo->hasPropertyByName(C2U(\"ButtonType\" )))\n {\n form::FormButtonType eButtonType = form::FormButtonType_URL;\n aTmp = xPropSet->getPropertyValue( C2U(\"ButtonType\") );\n if( aTmp >>= eButtonType )\n {\n \/\/ Label\n if(xInfo->hasPropertyByName( C2U(\"Label\") ))\n {\n aTmp = xPropSet->getPropertyValue( C2U(\"Label\") );\n OUString sTmp;\n if( (aTmp >>= sTmp) && sTmp.getLength())\n {\n aHLinkItem.SetName(sTmp);\n }\n }\n\n \/\/ URL\n if(xInfo->hasPropertyByName( C2U(\"TargetURL\" )))\n {\n aTmp = xPropSet->getPropertyValue( C2U(\"TargetURL\") );\n OUString sTmp;\n if( (aTmp >>= sTmp) && sTmp.getLength())\n {\n aHLinkItem.SetURL(sTmp);\n }\n }\n\n \/\/ Target\n if(xInfo->hasPropertyByName( C2U(\"TargetFrame\") ))\n {\n aTmp = xPropSet->getPropertyValue( C2U(\"TargetFrame\") );\n OUString sTmp;\n if( (aTmp >>= sTmp) && sTmp.getLength())\n {\n aHLinkItem.SetTargetFrame(sTmp);\n }\n }\n aHLinkItem.SetInsertMode(HLINK_BUTTON);\n }\n }\n }\n }\n sal_uInt16 nHtmlMode = ::GetHtmlMode(GetView().GetDocShell());\n aHLinkItem.SetInsertMode((SvxLinkInsertMode)(aHLinkItem.GetInsertMode() |\n ((nHtmlMode & HTMLMODE_ON) != 0 ? HLINK_HTMLMODE : 0)));\n\n rSet.Put(aHLinkItem);\n }\n break;\n }\n nWhich = aIter.NextWhich();\n }\n}\n\n\nSwDrawFormShell::SwDrawFormShell(SwView &_rView) :\n SwDrawBaseShell(_rView)\n{\n SetHelpId(SW_DRAWFORMSHELL);\n GetShell().NoEdit(sal_True);\n SetName(String::CreateFromAscii(\"DrawForm\"));\n}\n\nSwDrawFormShell::~SwDrawFormShell()\n{\n}\n\n\n\n<commit_msg>INTEGRATION: CWS impresstables2 (1.14.82); FILE MERGED 2007\/10\/12 00:23:49 cl 1.14.82.2: RESYNC: (1.14-1.15); FILE MERGED 2007\/10\/11 14:18:39 cl 1.14.82.1: #i68103# fixed namespace issues<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: drformsh.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 12:53:55 $\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_sw.hxx\"\n\n\n\n#include <hintids.hxx>\n#ifndef _SVX_HLNKITEM_HXX \/\/autogen\n#include <svx\/hlnkitem.hxx>\n#endif\n#ifndef _SVDVIEW_HXX \/\/autogen\n#include <svx\/svdview.hxx>\n#endif\n#ifndef _SFX_WHITER_HXX \/\/autogen\n#include <svtools\/whiter.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SFXOBJFACE_HXX \/\/autogen\n#include <sfx2\/objface.hxx>\n#endif\n#ifndef _SFXAPP_HXX \/\/autogen\n#include <sfx2\/app.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX\n#include <sfx2\/viewfrm.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX\n#include <sfx2\/dispatch.hxx>\n#endif\n#ifndef _SVX_SRCHITEM_HXX\n#include <svx\/srchitem.hxx>\n#endif\n#ifndef _SVX_FMGLOB_HXX\n#include <svx\/fmglob.hxx>\n#endif\n#ifndef _SVDOUNO_HXX \/\/autogen\n#include <svx\/svdouno.hxx>\n#endif\n#ifndef _COM_SUN_STAR_FORM_FORMBUTTONTYPE_HPP_\n#include <com\/sun\/star\/form\/FormButtonType.hpp>\n#endif\n#ifndef _SVX_HTMLMODE_HXX\n#include <svx\/htmlmode.hxx>\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen\n#include <tools\/urlobj.hxx>\n#endif\n\n#include \"viewopt.hxx\"\n#include \"swmodule.hxx\"\n#include \"wrtsh.hxx\"\n#include \"cmdid.h\"\n#include \"globals.hrc\"\n#include \"helpid.h\"\n#include \"popup.hrc\"\n#include \"shells.hrc\"\n#include \"drwbassh.hxx\"\n#include \"drformsh.hxx\"\n#ifndef SVTOOLS_URIHELPER_HXX\n#include <svtools\/urihelper.hxx>\n#endif\n#ifndef _VIEW_HXX\n#include <view.hxx>\n#endif\n#ifndef _SFXDOCFILE_HXX\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef _SWDOCSH_HXX\n#include <docsh.hxx>\n#endif\n\n#define SwDrawFormShell\n#include \"itemdef.hxx\"\n#include \"swslots.hxx\"\n\n#include <unomid.h>\n\n\nusing namespace ::com::sun::star;\nusing ::rtl::OUString;\n\nSFX_IMPL_INTERFACE(SwDrawFormShell, SwDrawBaseShell, SW_RES(STR_SHELLNAME_DRAWFORM))\n{\n SFX_POPUPMENU_REGISTRATION(SW_RES(MN_DRAWFORM_POPUPMENU));\n SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_TEXT_TOOLBOX));\n}\n\n\nTYPEINIT1(SwDrawFormShell, SwDrawBaseShell)\n\n\nvoid SwDrawFormShell::Execute(SfxRequest &rReq)\n{\n SwWrtShell &rSh = GetShell();\n const SfxPoolItem* pItem = 0;\n const SfxItemSet *pArgs = rReq.GetArgs();\n\n switch ( rReq.GetSlot() )\n {\n case SID_HYPERLINK_SETLINK:\n {\n if(pArgs)\n pArgs->GetItemState(SID_HYPERLINK_SETLINK, sal_False, &pItem);\n if(pItem)\n {\n SdrView *pSdrView = rSh.GetDrawView();\n const SvxHyperlinkItem& rHLinkItem = *(const SvxHyperlinkItem *)pItem;\n bool bConvertToText = rHLinkItem.GetInsertMode() == HLINK_DEFAULT ||\n rHLinkItem.GetInsertMode() == HLINK_FIELD;\n const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList();\n if (rMarkList.GetMark(0))\n {\n SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetMarkedSdrObj());\n if (pUnoCtrl && FmFormInventor == pUnoCtrl->GetObjInventor())\n {\n if(bConvertToText)\n {\n \/\/remove object -> results in destruction of this!\n SwView& rTempView = GetView();\n rTempView.GetViewFrame()->GetDispatcher()->Execute(SID_DELETE, SFX_CALLMODE_SYNCHRON );\n rTempView.StopShellTimer();\n \/\/issue a new command to insert the link\n rTempView.GetViewFrame()->GetDispatcher()->Execute(\n SID_HYPERLINK_SETLINK, SFX_CALLMODE_ASYNCHRON, &rHLinkItem, 0);\n }\n else\n {\n uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel();\n\n ASSERT( xControlModel.is(), \"UNO-Control ohne Model\" );\n if( !xControlModel.is() )\n return;\n\n uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY);\n\n \/\/ Darf man eine URL an dem Objekt setzen?\n OUString sTargetURL( C2U( \"TargetURL\" ));\n uno::Reference< beans::XPropertySetInfo > xPropInfoSet = xPropSet->getPropertySetInfo();\n if( xPropInfoSet->hasPropertyByName( sTargetURL ))\n {\n beans::Property aProp = xPropInfoSet->getPropertyByName( sTargetURL );\n if( aProp.Name.getLength() )\n {\n uno::Any aTmp;\n \/\/ Ja!\n aTmp <<= OUString(rHLinkItem.GetName());\n xPropSet->setPropertyValue(C2U(\"Label\"), aTmp );\n\n SfxMedium* pMedium = GetView().GetDocShell()->GetMedium();\n INetURLObject aAbs;\n if( pMedium )\n aAbs = pMedium->GetURLObject();\n aTmp <<= OUString(URIHelper::SmartRel2Abs(aAbs, rHLinkItem.GetURL()));\n xPropSet->setPropertyValue( sTargetURL, aTmp );\n\n if( rHLinkItem.GetTargetFrame().Len() )\n {\n aTmp <<= OUString(rHLinkItem.GetTargetFrame());\n xPropSet->setPropertyValue( C2U(\"TargetFrame\"), aTmp );\n }\n\n\n form::FormButtonType eButtonType = form::FormButtonType_URL;\n aTmp.setValue( &eButtonType, ::getCppuType((const form::FormButtonType*)0));\n xPropSet->setPropertyValue( C2U(\"ButtonType\"), aTmp );\n }\n }\n }\n }\n }\n }\n }\n break;\n\n default:\n DBG_ASSERT(!this, \"falscher Dispatcher\");\n return;\n }\n}\n\nvoid SwDrawFormShell::GetState(SfxItemSet& rSet)\n{\n SwWrtShell &rSh = GetShell();\n SfxWhichIter aIter( rSet );\n sal_uInt16 nWhich = aIter.FirstWhich();\n\n while( nWhich )\n {\n switch( nWhich )\n {\n case SID_HYPERLINK_GETLINK:\n {\n SdrView* pSdrView = rSh.GetDrawViewWithValidMarkList();\n const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList();\n SvxHyperlinkItem aHLinkItem;\n if (rMarkList.GetMark(0))\n {\n SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetMarkedSdrObj());\n if (pUnoCtrl && FmFormInventor == pUnoCtrl->GetObjInventor())\n {\n uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel();\n\n ASSERT( xControlModel.is(), \"UNO-Control ohne Model\" );\n if( !xControlModel.is() )\n return;\n\n uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY);\n\n uno::Any aTmp;\n uno::Reference< beans::XPropertySetInfo > xInfo = xPropSet->getPropertySetInfo();\n if(xInfo->hasPropertyByName(C2U(\"ButtonType\" )))\n {\n form::FormButtonType eButtonType = form::FormButtonType_URL;\n aTmp = xPropSet->getPropertyValue( C2U(\"ButtonType\") );\n if( aTmp >>= eButtonType )\n {\n \/\/ Label\n if(xInfo->hasPropertyByName( C2U(\"Label\") ))\n {\n aTmp = xPropSet->getPropertyValue( C2U(\"Label\") );\n OUString sTmp;\n if( (aTmp >>= sTmp) && sTmp.getLength())\n {\n aHLinkItem.SetName(sTmp);\n }\n }\n\n \/\/ URL\n if(xInfo->hasPropertyByName( C2U(\"TargetURL\" )))\n {\n aTmp = xPropSet->getPropertyValue( C2U(\"TargetURL\") );\n OUString sTmp;\n if( (aTmp >>= sTmp) && sTmp.getLength())\n {\n aHLinkItem.SetURL(sTmp);\n }\n }\n\n \/\/ Target\n if(xInfo->hasPropertyByName( C2U(\"TargetFrame\") ))\n {\n aTmp = xPropSet->getPropertyValue( C2U(\"TargetFrame\") );\n OUString sTmp;\n if( (aTmp >>= sTmp) && sTmp.getLength())\n {\n aHLinkItem.SetTargetFrame(sTmp);\n }\n }\n aHLinkItem.SetInsertMode(HLINK_BUTTON);\n }\n }\n }\n }\n sal_uInt16 nHtmlMode = ::GetHtmlMode(GetView().GetDocShell());\n aHLinkItem.SetInsertMode((SvxLinkInsertMode)(aHLinkItem.GetInsertMode() |\n ((nHtmlMode & HTMLMODE_ON) != 0 ? HLINK_HTMLMODE : 0)));\n\n rSet.Put(aHLinkItem);\n }\n break;\n }\n nWhich = aIter.NextWhich();\n }\n}\n\n\nSwDrawFormShell::SwDrawFormShell(SwView &_rView) :\n SwDrawBaseShell(_rView)\n{\n SetHelpId(SW_DRAWFORMSHELL);\n GetShell().NoEdit(sal_True);\n SetName(String::CreateFromAscii(\"DrawForm\"));\n}\n\nSwDrawFormShell::~SwDrawFormShell()\n{\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * Copyright 2009-2015 Jörg Müller\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#include \"Exception.h\"\n#include \"IReader.h\"\n#include \"file\/File.h\"\n#include \"respec\/ChannelMapper.h\"\n#include \"fx\/Lowpass.h\"\n#include \"fx\/Highpass.h\"\n#include \"fx\/Envelope.h\"\n#include \"respec\/LinearResample.h\"\n#include \"fx\/Threshold.h\"\n#include \"fx\/Accumulator.h\"\n#include \"fx\/Sum.h\"\n#include \"generator\/Silence.h\"\n#include \"fx\/Limiter.h\"\n#include \"devices\/DeviceManager.h\"\n#include \"sequence\/Sequence.h\"\n#include \"file\/FileWriter.h\"\n#include \"devices\/ReadDevice.h\"\n#include \"plugin\/PluginManager.h\"\n#include \"devices\/DeviceManager.h\"\n#include \"devices\/IDeviceFactory.h\"\n#include \"devices\/NULLDevice.h\"\n\n#include <cassert>\n#include <cstring>\n#include <cmath>\n#include <sstream>\n\nusing namespace aud;\n\n#define AUD_CAPI_IMPLEMENTATION\n#include \"AUD_Special.h\"\n\nstatic inline AUD_Specs convSpecToC(aud::Specs specs)\n{\n\tAUD_Specs s;\n\ts.channels = static_cast<AUD_Channels>(specs.channels);\n\ts.rate = static_cast<AUD_SampleRate>(specs.rate);\n\treturn s;\n}\n\nstatic inline aud::Specs convCToSpec(AUD_Specs specs)\n{\n\taud::Specs s;\n\ts.channels = static_cast<Channels>(specs.channels);\n\ts.rate = static_cast<SampleRate>(specs.rate);\n\treturn s;\n}\n\nstatic inline AUD_DeviceSpecs convDSpecToC(aud::DeviceSpecs specs)\n{\n\tAUD_DeviceSpecs s;\n\ts.specs = convSpecToC(specs.specs);\n\ts.format = static_cast<AUD_SampleFormat>(specs.format);\n\treturn s;\n}\n\nstatic inline aud::DeviceSpecs convCToDSpec(AUD_DeviceSpecs specs)\n{\n\taud::DeviceSpecs s;\n\ts.specs = convCToSpec(specs.specs);\n\ts.format = static_cast<SampleFormat>(specs.format);\n\treturn s;\n}\n\nAUD_API AUD_SoundInfo AUD_getInfo(AUD_Sound* sound)\n{\n\tassert(sound);\n\n\tAUD_SoundInfo info;\n\tinfo.specs.channels = AUD_CHANNELS_INVALID;\n\tinfo.specs.rate = AUD_RATE_INVALID;\n\tinfo.length = 0.0f;\n\n\ttry\n\t{\n\t\tstd::shared_ptr<IReader> reader = (*sound)->createReader();\n\n\t\tif(reader.get())\n\t\t{\n\t\t\tinfo.specs = convSpecToC(reader->getSpecs());\n\t\t\tinfo.length = reader->getLength() \/ (float) info.specs.rate;\n\t\t}\n\t}\n\tcatch(Exception&)\n\t{\n\t}\n\n\treturn info;\n}\n\nAUD_API float* AUD_readSoundBuffer(const char* filename, float low, float high,\n\t\t\t\t\t\t float attack, float release, float threshold,\n\t\t\t\t\t\t int accumulate, int additive, int square,\n\t\t\t\t\t\t float sthreshold, double samplerate, int* length)\n{\n\tBuffer buffer;\n\tDeviceSpecs specs;\n\tspecs.channels = CHANNELS_MONO;\n\tspecs.rate = (SampleRate)samplerate;\n\tstd::shared_ptr<ISound> sound;\n\n\tstd::shared_ptr<ISound> file = std::shared_ptr<ISound>(new File(filename));\n\n\tint position = 0;\n\n\ttry\n\t{\n\t\tstd::shared_ptr<IReader> reader = file->createReader();\n\n\t\tSampleRate rate = reader->getSpecs().rate;\n\n\t\tsound = std::shared_ptr<ISound>(new ChannelMapper(file, specs));\n\n\t\tif(high < rate)\n\t\t\tsound = std::shared_ptr<ISound>(new Lowpass(sound, high));\n\t\tif(low > 0)\n\t\t\tsound = std::shared_ptr<ISound>(new Highpass(sound, low));\n\n\t\tsound = std::shared_ptr<ISound>(new Envelope(sound, attack, release, threshold, 0.1f));\n\t\tsound = std::shared_ptr<ISound>(new LinearResample(sound, specs));\n\n\t\tif(square)\n\t\t\tsound = std::shared_ptr<ISound>(new Threshold(sound, sthreshold));\n\n\t\tif(accumulate)\n\t\t\tsound = std::shared_ptr<ISound>(new Accumulator(sound, additive));\n\t\telse if(additive)\n\t\t\tsound = std::shared_ptr<ISound>(new Sum(sound));\n\n\t\treader = sound->createReader();\n\n\t\tif(!reader.get())\n\t\t\treturn nullptr;\n\n\t\tint len;\n\t\tbool eos;\n\t\tdo\n\t\t{\n\t\t\tlen = samplerate;\n\t\t\tbuffer.resize((position + len) * sizeof(float), true);\n\t\t\treader->read(len, eos, buffer.getBuffer() + position);\n\t\t\tposition += len;\n\t\t} while(!eos);\n\t}\n\tcatch(Exception&)\n\t{\n\t\treturn nullptr;\n\t}\n\n\tfloat * result = (float *)malloc(position * sizeof(float));\n\tstd::memcpy(result, buffer.getBuffer(), position * sizeof(float));\n\t*length = position;\n\treturn result;\n}\n\nstatic void pauseSound(AUD_Handle* handle)\n{\n\tassert(handle);\n\t(*handle)->pause();\n}\n\nAUD_API AUD_Handle* AUD_pauseAfter(AUD_Handle* handle, float seconds)\n{\n\tstd::shared_ptr<ISound> silence = std::shared_ptr<ISound>(new Silence);\n\tstd::shared_ptr<ISound> limiter = std::shared_ptr<ISound>(new Limiter(silence, 0, seconds));\n\n\tauto device = DeviceManager::getDevice();\n\n\tstd::lock_guard<ILockable> lock(*device);\n\n\ttry\n\t{\n\t\tAUD_Handle handle2 = device->play(limiter);\n\t\tif(handle2.get())\n\t\t{\n\t\t\thandle2->setStopCallback((stopCallback)pauseSound, handle);\n\t\t\treturn new AUD_Handle(handle2);\n\t\t}\n\t}\n\tcatch(Exception&)\n\t{\n\t}\n\n\treturn nullptr;\n}\n\nAUD_API int AUD_readSound(AUD_Sound* sound, float* buffer, int length, int samples_per_second, short* interrupt)\n{\n\tDeviceSpecs specs;\n\tfloat* buf;\n\tBuffer aBuffer;\n\n\tspecs.rate = RATE_INVALID;\n\tspecs.channels = CHANNELS_MONO;\n\tspecs.format = FORMAT_INVALID;\n\n\tstd::shared_ptr<IReader> reader = ChannelMapper(*sound, specs).createReader();\n\n\tspecs.specs = reader->getSpecs();\n\tint len;\n\tfloat samplejump = specs.rate \/ samples_per_second;\n\tfloat min, max, power, overallmax;\n\tbool eos;\n\n\toverallmax = 0;\n\n\tfor(int i = 0; i < length; i++)\n\t{\n\t\tlen = floor(samplejump * (i+1)) - floor(samplejump * i);\n\n\t\tif (*interrupt)\n\t\t\treturn 0;\n\n\t\taBuffer.assureSize(len * AUD_SAMPLE_SIZE(specs));\n\t\tbuf = aBuffer.getBuffer();\n\n\t\treader->read(len, eos, buf);\n\n\t\tmax = min = *buf;\n\t\tpower = *buf * *buf;\n\t\tfor(int j = 1; j < len; j++)\n\t\t{\n\t\t\tif(buf[j] < min)\n\t\t\t\tmin = buf[j];\n\t\t\tif(buf[j] > max)\n\t\t\t\tmax = buf[j];\n\t\t\tpower += buf[j] * buf[j];\n\t\t}\n\n\t\tbuffer[i * 3] = min;\n\t\tbuffer[i * 3 + 1] = max;\n\t\tbuffer[i * 3 + 2] = sqrt(power) \/ len;\n\n\t\tif(overallmax < max)\n\t\t\toverallmax = max;\n\t\tif(overallmax < -min)\n\t\t\toverallmax = -min;\n\n\t\tif(eos)\n\t\t{\n\t\t\tlength = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(overallmax > 1.0f)\n\t{\n\t\tfor(int i = 0; i < length * 3; i++)\n\t\t{\n\t\t\tbuffer[i] \/= overallmax;\n\t\t}\n\t}\n\n\treturn length;\n}\n\nAUD_API const char* AUD_mixdown(AUD_Sound* sound, unsigned int start, unsigned int length, unsigned int buffersize, const char* filename, AUD_DeviceSpecs specs, AUD_Container format, AUD_Codec codec, unsigned int bitrate)\n{\n\ttry\n\t{\n\t\tSequence* f = dynamic_cast<Sequence *>(sound->get());\n\n\t\tf->setSpecs(convCToSpec(specs.specs));\n\t\tstd::shared_ptr<IReader> reader = f->createQualityReader();\n\t\treader->seek(start);\n\t\tstd::shared_ptr<IWriter> writer = FileWriter::createWriter(filename, convCToDSpec(specs), static_cast<Container>(format), static_cast<Codec>(codec), bitrate);\n\t\tFileWriter::writeReader(reader, writer, length, buffersize);\n\n\t\treturn nullptr;\n\t}\n\tcatch(Exception& e)\n\t{\n\t\treturn e.getMessage().c_str();\n\t}\n}\n\nAUD_API const char* AUD_mixdown_per_channel(AUD_Sound* sound, unsigned int start, unsigned int length, unsigned int buffersize, const char* filename, AUD_DeviceSpecs specs, AUD_Container format, AUD_Codec codec, unsigned int bitrate)\n{\n\ttry\n\t{\n\t\tSequence* f = dynamic_cast<Sequence *>(sound->get());\n\n\t\tf->setSpecs(convCToSpec(specs.specs));\n\n\t\tstd::vector<std::shared_ptr<IWriter> > writers;\n\n\t\tint channels = specs.channels;\n\t\tspecs.channels = AUD_CHANNELS_MONO;\n\n\t\tfor(int i = 0; i < channels; i++)\n\t\t{\n\t\t\tstd::stringstream stream;\n\t\t\tstd::string fn = filename;\n\t\t\tsize_t index = fn.find_last_of('.');\n\t\t\tsize_t index_slash = fn.find_last_of('\/');\n\t\t\tsize_t index_backslash = fn.find_last_of('\\\\');\n\n\t\t\tif((index == std::string::npos) ||\n\t\t\t\t((index < index_slash) && (index_slash != std::string::npos)) ||\n\t\t\t\t((index < index_backslash) && (index_backslash != std::string::npos)))\n\t\t\t{\n\t\t\t\tstream << filename << \"_\" << (i + 1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstream << fn.substr(0, index) << \"_\" << (i + 1) << fn.substr(index);\n\t\t\t}\n\t\t\twriters.push_back(FileWriter::createWriter(stream.str(), convCToDSpec(specs), static_cast<Container>(format), static_cast<Codec>(codec), bitrate));\n\t\t}\n\n\t\tstd::shared_ptr<IReader> reader = f->createQualityReader();\n\t\treader->seek(start);\n\t\tFileWriter::writeReader(reader, writers, length, buffersize);\n\n\t\treturn nullptr;\n\t}\n\tcatch(Exception& e)\n\t{\n\t\treturn e.getMessage().c_str();\n\t}\n}\n\nAUD_API AUD_Device* AUD_openMixdownDevice(AUD_DeviceSpecs specs, AUD_Sound* sequencer, float volume, float start)\n{\n\ttry\n\t{\n\t\tReadDevice* device = new ReadDevice(convCToDSpec(specs));\n\t\tdevice->setQuality(true);\n\t\tdevice->setVolume(volume);\n\n\t\tdynamic_cast<Sequence *>(sequencer->get())->setSpecs(convCToSpec(specs.specs));\n\n\t\tAUD_Handle handle = device->play(*sequencer);\n\t\tif(handle.get())\n\t\t{\n\t\t\thandle->seek(start);\n\t\t}\n\n\t\treturn new AUD_Device(device);\n\t}\n\tcatch(Exception&)\n\t{\n\t\treturn nullptr;\n\t}\n}\n\nAUD_API void AUD_initOnce()\n{\n\tPluginManager::loadPlugins();\n\tNULLDevice::registerPlugin();\n}\n\nAUD_API void AUD_exitOnce()\n{\n}\n\nAUD_API AUD_Device* AUD_init(const char* device, AUD_DeviceSpecs specs, int buffersize, const char* name)\n{\n\ttry\n\t{\n\t\tstd::shared_ptr<IDeviceFactory> factory = DeviceManager::getDeviceFactory(device);\n\n\t\tif(factory)\n\t\t{\n\t\t\tfactory->setName(name);\n\t\t\tfactory->setBufferSize(buffersize);\n\t\t\tfactory->setSpecs(convCToDSpec(specs));\n\t\t\tauto device = factory->openDevice();\n\t\t\tDeviceManager::setDevice(device);\n\n\t\t\treturn new AUD_Device(device);\n\t\t}\n\t}\n\tcatch(Exception&)\n\t{\n\t}\n\treturn nullptr;\n}\n\nAUD_API void AUD_exit(AUD_Device* device)\n{\n\tdelete device;\n\tDeviceManager::releaseDevice();\n}\n\n\nAUD_API char** AUD_getDeviceNames()\n{\n\tstd::vector<std::string> v_names = DeviceManager::getAvailableDeviceNames();\n\tchar** names = (char**) malloc(sizeof(char*) * (v_names.size() + 1));\n\n\tfor(int i = 0; i < v_names.size(); i++)\n\t{\n\t\tstd::string name = v_names[i];\n\t\tnames[i] = (char*) malloc(sizeof(char) * (name.length() + 1));\n\t\tstrcpy(names[i], name.c_str());\n\t}\n\n\treturn names;\n}\n<commit_msg>Fixing error in last commit.<commit_after>\/*******************************************************************************\n * Copyright 2009-2015 Jörg Müller\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#include \"Exception.h\"\n#include \"IReader.h\"\n#include \"file\/File.h\"\n#include \"respec\/ChannelMapper.h\"\n#include \"fx\/Lowpass.h\"\n#include \"fx\/Highpass.h\"\n#include \"fx\/Envelope.h\"\n#include \"respec\/LinearResample.h\"\n#include \"fx\/Threshold.h\"\n#include \"fx\/Accumulator.h\"\n#include \"fx\/Sum.h\"\n#include \"generator\/Silence.h\"\n#include \"fx\/Limiter.h\"\n#include \"devices\/DeviceManager.h\"\n#include \"sequence\/Sequence.h\"\n#include \"file\/FileWriter.h\"\n#include \"devices\/ReadDevice.h\"\n#include \"plugin\/PluginManager.h\"\n#include \"devices\/DeviceManager.h\"\n#include \"devices\/IDeviceFactory.h\"\n#include \"devices\/NULLDevice.h\"\n\n#include <cassert>\n#include <cstring>\n#include <cmath>\n#include <sstream>\n\nusing namespace aud;\n\n#define AUD_CAPI_IMPLEMENTATION\n#include \"AUD_Special.h\"\n\nstatic inline AUD_Specs convSpecToC(aud::Specs specs)\n{\n\tAUD_Specs s;\n\ts.channels = static_cast<AUD_Channels>(specs.channels);\n\ts.rate = static_cast<AUD_SampleRate>(specs.rate);\n\treturn s;\n}\n\nstatic inline aud::Specs convCToSpec(AUD_Specs specs)\n{\n\taud::Specs s;\n\ts.channels = static_cast<Channels>(specs.channels);\n\ts.rate = static_cast<SampleRate>(specs.rate);\n\treturn s;\n}\n\nstatic inline AUD_DeviceSpecs convDSpecToC(aud::DeviceSpecs specs)\n{\n\tAUD_DeviceSpecs s;\n\ts.specs = convSpecToC(specs.specs);\n\ts.format = static_cast<AUD_SampleFormat>(specs.format);\n\treturn s;\n}\n\nstatic inline aud::DeviceSpecs convCToDSpec(AUD_DeviceSpecs specs)\n{\n\taud::DeviceSpecs s;\n\ts.specs = convCToSpec(specs.specs);\n\ts.format = static_cast<SampleFormat>(specs.format);\n\treturn s;\n}\n\nAUD_API AUD_SoundInfo AUD_getInfo(AUD_Sound* sound)\n{\n\tassert(sound);\n\n\tAUD_SoundInfo info;\n\tinfo.specs.channels = AUD_CHANNELS_INVALID;\n\tinfo.specs.rate = AUD_RATE_INVALID;\n\tinfo.length = 0.0f;\n\n\ttry\n\t{\n\t\tstd::shared_ptr<IReader> reader = (*sound)->createReader();\n\n\t\tif(reader.get())\n\t\t{\n\t\t\tinfo.specs = convSpecToC(reader->getSpecs());\n\t\t\tinfo.length = reader->getLength() \/ (float) info.specs.rate;\n\t\t}\n\t}\n\tcatch(Exception&)\n\t{\n\t}\n\n\treturn info;\n}\n\nAUD_API float* AUD_readSoundBuffer(const char* filename, float low, float high,\n\t\t\t\t\t\t float attack, float release, float threshold,\n\t\t\t\t\t\t int accumulate, int additive, int square,\n\t\t\t\t\t\t float sthreshold, double samplerate, int* length)\n{\n\tBuffer buffer;\n\tDeviceSpecs specs;\n\tspecs.channels = CHANNELS_MONO;\n\tspecs.rate = (SampleRate)samplerate;\n\tstd::shared_ptr<ISound> sound;\n\n\tstd::shared_ptr<ISound> file = std::shared_ptr<ISound>(new File(filename));\n\n\tint position = 0;\n\n\ttry\n\t{\n\t\tstd::shared_ptr<IReader> reader = file->createReader();\n\n\t\tSampleRate rate = reader->getSpecs().rate;\n\n\t\tsound = std::shared_ptr<ISound>(new ChannelMapper(file, specs));\n\n\t\tif(high < rate)\n\t\t\tsound = std::shared_ptr<ISound>(new Lowpass(sound, high));\n\t\tif(low > 0)\n\t\t\tsound = std::shared_ptr<ISound>(new Highpass(sound, low));\n\n\t\tsound = std::shared_ptr<ISound>(new Envelope(sound, attack, release, threshold, 0.1f));\n\t\tsound = std::shared_ptr<ISound>(new LinearResample(sound, specs));\n\n\t\tif(square)\n\t\t\tsound = std::shared_ptr<ISound>(new Threshold(sound, sthreshold));\n\n\t\tif(accumulate)\n\t\t\tsound = std::shared_ptr<ISound>(new Accumulator(sound, additive));\n\t\telse if(additive)\n\t\t\tsound = std::shared_ptr<ISound>(new Sum(sound));\n\n\t\treader = sound->createReader();\n\n\t\tif(!reader.get())\n\t\t\treturn nullptr;\n\n\t\tint len;\n\t\tbool eos;\n\t\tdo\n\t\t{\n\t\t\tlen = samplerate;\n\t\t\tbuffer.resize((position + len) * sizeof(float), true);\n\t\t\treader->read(len, eos, buffer.getBuffer() + position);\n\t\t\tposition += len;\n\t\t} while(!eos);\n\t}\n\tcatch(Exception&)\n\t{\n\t\treturn nullptr;\n\t}\n\n\tfloat * result = (float *)malloc(position * sizeof(float));\n\tstd::memcpy(result, buffer.getBuffer(), position * sizeof(float));\n\t*length = position;\n\treturn result;\n}\n\nstatic void pauseSound(AUD_Handle* handle)\n{\n\tassert(handle);\n\t(*handle)->pause();\n}\n\nAUD_API AUD_Handle* AUD_pauseAfter(AUD_Handle* handle, float seconds)\n{\n\tstd::shared_ptr<ISound> silence = std::shared_ptr<ISound>(new Silence);\n\tstd::shared_ptr<ISound> limiter = std::shared_ptr<ISound>(new Limiter(silence, 0, seconds));\n\n\tauto device = DeviceManager::getDevice();\n\n\tstd::lock_guard<ILockable> lock(*device);\n\n\ttry\n\t{\n\t\tAUD_Handle handle2 = device->play(limiter);\n\t\tif(handle2.get())\n\t\t{\n\t\t\thandle2->setStopCallback((stopCallback)pauseSound, handle);\n\t\t\treturn new AUD_Handle(handle2);\n\t\t}\n\t}\n\tcatch(Exception&)\n\t{\n\t}\n\n\treturn nullptr;\n}\n\nAUD_API int AUD_readSound(AUD_Sound* sound, float* buffer, int length, int samples_per_second, short* interrupt)\n{\n\tDeviceSpecs specs;\n\tfloat* buf;\n\tBuffer aBuffer;\n\n\tspecs.rate = RATE_INVALID;\n\tspecs.channels = CHANNELS_MONO;\n\tspecs.format = FORMAT_INVALID;\n\n\tstd::shared_ptr<IReader> reader = ChannelMapper(*sound, specs).createReader();\n\n\tspecs.specs = reader->getSpecs();\n\tint len;\n\tfloat samplejump = specs.rate \/ samples_per_second;\n\tfloat min, max, power, overallmax;\n\tbool eos;\n\n\toverallmax = 0;\n\n\tfor(int i = 0; i < length; i++)\n\t{\n\t\tlen = floor(samplejump * (i+1)) - floor(samplejump * i);\n\n\t\tif (*interrupt)\n\t\t\treturn 0;\n\n\t\taBuffer.assureSize(len * AUD_SAMPLE_SIZE(specs));\n\t\tbuf = aBuffer.getBuffer();\n\n\t\treader->read(len, eos, buf);\n\n\t\tmax = min = *buf;\n\t\tpower = *buf * *buf;\n\t\tfor(int j = 1; j < len; j++)\n\t\t{\n\t\t\tif(buf[j] < min)\n\t\t\t\tmin = buf[j];\n\t\t\tif(buf[j] > max)\n\t\t\t\tmax = buf[j];\n\t\t\tpower += buf[j] * buf[j];\n\t\t}\n\n\t\tbuffer[i * 3] = min;\n\t\tbuffer[i * 3 + 1] = max;\n\t\tbuffer[i * 3 + 2] = sqrt(power) \/ len;\n\n\t\tif(overallmax < max)\n\t\t\toverallmax = max;\n\t\tif(overallmax < -min)\n\t\t\toverallmax = -min;\n\n\t\tif(eos)\n\t\t{\n\t\t\tlength = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(overallmax > 1.0f)\n\t{\n\t\tfor(int i = 0; i < length * 3; i++)\n\t\t{\n\t\t\tbuffer[i] \/= overallmax;\n\t\t}\n\t}\n\n\treturn length;\n}\n\nAUD_API const char* AUD_mixdown(AUD_Sound* sound, unsigned int start, unsigned int length, unsigned int buffersize, const char* filename, AUD_DeviceSpecs specs, AUD_Container format, AUD_Codec codec, unsigned int bitrate)\n{\n\ttry\n\t{\n\t\tSequence* f = dynamic_cast<Sequence *>(sound->get());\n\n\t\tf->setSpecs(convCToSpec(specs.specs));\n\t\tstd::shared_ptr<IReader> reader = f->createQualityReader();\n\t\treader->seek(start);\n\t\tstd::shared_ptr<IWriter> writer = FileWriter::createWriter(filename, convCToDSpec(specs), static_cast<Container>(format), static_cast<Codec>(codec), bitrate);\n\t\tFileWriter::writeReader(reader, writer, length, buffersize);\n\n\t\treturn nullptr;\n\t}\n\tcatch(Exception& e)\n\t{\n\t\treturn e.getMessage().c_str();\n\t}\n}\n\nAUD_API const char* AUD_mixdown_per_channel(AUD_Sound* sound, unsigned int start, unsigned int length, unsigned int buffersize, const char* filename, AUD_DeviceSpecs specs, AUD_Container format, AUD_Codec codec, unsigned int bitrate)\n{\n\ttry\n\t{\n\t\tSequence* f = dynamic_cast<Sequence *>(sound->get());\n\n\t\tf->setSpecs(convCToSpec(specs.specs));\n\n\t\tstd::vector<std::shared_ptr<IWriter> > writers;\n\n\t\tint channels = specs.channels;\n\t\tspecs.channels = AUD_CHANNELS_MONO;\n\n\t\tfor(int i = 0; i < channels; i++)\n\t\t{\n\t\t\tstd::stringstream stream;\n\t\t\tstd::string fn = filename;\n\t\t\tsize_t index = fn.find_last_of('.');\n\t\t\tsize_t index_slash = fn.find_last_of('\/');\n\t\t\tsize_t index_backslash = fn.find_last_of('\\\\');\n\n\t\t\tif((index == std::string::npos) ||\n\t\t\t\t((index < index_slash) && (index_slash != std::string::npos)) ||\n\t\t\t\t((index < index_backslash) && (index_backslash != std::string::npos)))\n\t\t\t{\n\t\t\t\tstream << filename << \"_\" << (i + 1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstream << fn.substr(0, index) << \"_\" << (i + 1) << fn.substr(index);\n\t\t\t}\n\t\t\twriters.push_back(FileWriter::createWriter(stream.str(), convCToDSpec(specs), static_cast<Container>(format), static_cast<Codec>(codec), bitrate));\n\t\t}\n\n\t\tstd::shared_ptr<IReader> reader = f->createQualityReader();\n\t\treader->seek(start);\n\t\tFileWriter::writeReader(reader, writers, length, buffersize);\n\n\t\treturn nullptr;\n\t}\n\tcatch(Exception& e)\n\t{\n\t\treturn e.getMessage().c_str();\n\t}\n}\n\nAUD_API AUD_Device* AUD_openMixdownDevice(AUD_DeviceSpecs specs, AUD_Sound* sequencer, float volume, float start)\n{\n\ttry\n\t{\n\t\tReadDevice* device = new ReadDevice(convCToDSpec(specs));\n\t\tdevice->setQuality(true);\n\t\tdevice->setVolume(volume);\n\n\t\tdynamic_cast<Sequence *>(sequencer->get())->setSpecs(convCToSpec(specs.specs));\n\n\t\tAUD_Handle handle = device->play(*sequencer);\n\t\tif(handle.get())\n\t\t{\n\t\t\thandle->seek(start);\n\t\t}\n\n\t\treturn new AUD_Device(device);\n\t}\n\tcatch(Exception&)\n\t{\n\t\treturn nullptr;\n\t}\n}\n\nAUD_API void AUD_initOnce()\n{\n\tPluginManager::loadPlugins();\n\tNULLDevice::registerPlugin();\n}\n\nAUD_API void AUD_exitOnce()\n{\n}\n\nAUD_API AUD_Device* AUD_init(const char* device, AUD_DeviceSpecs specs, int buffersize, const char* name)\n{\n\ttry\n\t{\n\t\tstd::shared_ptr<IDeviceFactory> factory = DeviceManager::getDeviceFactory(device);\n\n\t\tif(factory)\n\t\t{\n\t\t\tfactory->setName(name);\n\t\t\tfactory->setBufferSize(buffersize);\n\t\t\tfactory->setSpecs(convCToDSpec(specs));\n\t\t\tauto device = factory->openDevice();\n\t\t\tDeviceManager::setDevice(device);\n\n\t\t\treturn new AUD_Device(device);\n\t\t}\n\t}\n\tcatch(Exception&)\n\t{\n\t}\n\treturn nullptr;\n}\n\nAUD_API void AUD_exit(AUD_Device* device)\n{\n\tdelete device;\n\tDeviceManager::releaseDevice();\n}\n\n\nAUD_API char** AUD_getDeviceNames()\n{\n\tstd::vector<std::string> v_names = DeviceManager::getAvailableDeviceNames();\n\tchar** names = (char**) malloc(sizeof(char*) * (v_names.size() + 1));\n\n\tfor(int i = 0; i < v_names.size(); i++)\n\t{\n\t\tstd::string name = v_names[i];\n\t\tnames[i] = (char*) malloc(sizeof(char) * (name.length() + 1));\n\t\tstrcpy(names[i], name.c_str());\n\t}\n\n\tnames[v_names.size()] = nullptr;\n\n\treturn names;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n@file\nIE to represent generic integral value\n\n@copyright Denis Priyomov 2016-2017\nDistributed under the MIT License\n(See accompanying file LICENSE or visit https:\/\/github.com\/cppden\/med)\n*\/\n\n#pragma once\n\n#include <type_traits>\n\n#include \"units.hpp\"\n#include \"ie_type.hpp\"\n#include \"name.hpp\"\n#include \"exception.hpp\"\n\n\nnamespace med {\n\n\/\/traits representing a fixed value of particular size (in bits\/bytes\/int)\n\/\/which is predefined during encode and decode\ntemplate <std::size_t VAL, typename T, class... EXT_TRAITS>\nstruct fixed : value_traits<T, EXT_TRAITS...>\n{\n\tstatic constexpr bool is_const = true;\n\tstatic constexpr typename value_traits<T, EXT_TRAITS...>::value_type value = VAL;\n};\n\n\/\/traits representing a fixed value with default\ntemplate <std::size_t VAL, class T, class... EXT_TRAITS>\nstruct defaults : value_traits<T, EXT_TRAITS...>\n{\n\tstatic constexpr typename value_traits<T, EXT_TRAITS...>::value_type default_value = VAL;\n};\n\n\/\/traits representing initialized value which is encoded with the fixed value\n\/\/but can have any value when decoded\ntemplate <std::size_t VAL, class T, class... EXT_TRAITS>\nstruct init : fixed<VAL, T, EXT_TRAITS...>\n{\n\tstatic constexpr bool is_const = false;\n};\n\nnamespace detail {\n\n\/**\n * plain numeric value\n *\/\ntemplate <class TRAITS>\nstruct numeric_value : IE<IE_VALUE>\n{\n\tusing traits = TRAITS;\n\tusing value_type = typename traits::value_type;\n\tusing base_t = numeric_value;\n\n\tvalue_type get() const { return get_encoded(); }\n\tauto set(value_type v) { return set_encoded(v); }\n\n\t\/\/NOTE: do not override!\n\tstatic constexpr bool is_const = false;\n\tvalue_type get_encoded() const { return m_value; }\n\tvoid set_encoded(value_type v) { m_value = v; m_set = true; }\n\tvoid clear() { m_set = false; }\n\tbool is_set() const { return m_set; }\n\texplicit operator bool() const { return is_set(); }\n\ttemplate <class... ARGS>\n\tvoid copy(base_t const& from, ARGS&&...) { m_value = from.m_value; m_set = from.m_set; }\n\n#if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ < 9)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmaybe-uninitialized\"\n#endif\n\tbool operator==(numeric_value const& rhs) const { return is_set() == rhs.is_set() && (!is_set() || get() == rhs.get()); }\n#if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ < 9)\n#pragma GCC diagnostic pop\n#endif\n\n\tbool operator!=(numeric_value const& rhs) const { return !this->operator==(rhs); }\n\nprivate:\n\tbool m_set{false};\n\tvalue_type m_value{};\n};\n\n\/**\n * plain fixed integral value\n * gives error if decoded value doesn't match the fixed one\n *\/\ntemplate <class TRAITS>\nstruct const_integer : IE<IE_VALUE>\n{\n\tusing traits = TRAITS;\n\tusing value_type = typename traits::value_type;\n\tusing base_t = const_integer;\n\tusing writable = numeric_value<traits>;\n\n\tstatic constexpr void clear() { }\n\tstatic constexpr value_type get() { return get_encoded(); }\n\n\n\t\/\/NOTE: do not override!\n\tstatic constexpr bool is_const = true;\n\texplicit operator bool() const { return is_set(); }\n\tstatic constexpr value_type get_encoded() { return traits::value; }\n\tstatic constexpr bool set_encoded(value_type v) { return traits::value == v; }\n\tstatic constexpr bool is_set() { return true; }\n\tstatic constexpr bool match(value_type v) { return traits::value == v; }\n\ttemplate <class... ARGS>\n\tstatic constexpr void copy(base_t const&, ARGS&&...){ }\n\n\tbool operator==(const_integer const&) const { return true; } \/\/equal to itself by definition\n\tbool operator!=(const_integer const&) const { return false; }\n};\n\n\/**\n * plain initialized\/set field\n * decoded even if doesn't match initial value\n *\/\ntemplate <class TRAITS>\nstruct init_integer : IE<IE_VALUE>\n{\n\tusing traits = TRAITS;\n\tusing value_type = typename traits::value_type;\n\tusing base_t = init_integer;\n\n\tstatic constexpr void clear() { }\n\texplicit operator bool() const { return is_set(); }\n\t\/\/NOTE: do not override!\n\tstatic constexpr bool is_const = true;\n\tstatic constexpr value_type get_encoded() { return traits::value; }\n\tstatic constexpr void set_encoded(value_type) { }\n\tstatic constexpr bool is_set() { return true; }\n\ttemplate <class... ARGS>\n\tstatic constexpr void copy(base_t const&, ARGS&&...){ }\n\tbool operator==(init_integer const&) const { return true; }\n\tbool operator!=(init_integer const&) const { return false; }\n};\n\n\/**\n * integer with a default value\n *\/\ntemplate <class TRAITS>\nstruct def_integer : numeric_value<TRAITS>\n{\n\tusing traits = TRAITS;\n\tusing value_type = typename traits::value_type;\n\tusing base_t = def_integer;\n\n\t\/\/NOTE: do not override!\n\tvalue_type get_encoded() const\n\t{\n\t\treturn this->is_set() ? numeric_value<TRAITS>::get_encoded() : traits::default_value;\n\t}\n};\n\n\n\/\/meta-function to select proper implementation of numeric value\ntemplate <class T, typename Enable = void>\nstruct value_selector;\n\ntemplate <class T>\nstruct value_selector<T,\n\tstd::enable_if_t<\n\t\tstd::is_same_v<typename T::value_type, std::remove_const_t<decltype(T::value)>>\n\t\t&& T::is_const\n\t>\n>\n{\n\tusing type = const_integer<T>;\n};\n\ntemplate <class T>\nstruct value_selector<T,\n\tstd::enable_if_t<\n\t\tstd::is_same_v<typename T::value_type, std::remove_const_t<decltype(T::value)>>\n\t\t&& !T::is_const\n\t>\n>\n{\n\tusing type = init_integer<T>;\n};\n\ntemplate <class T>\nstruct value_selector<T,\n\tstd::enable_if_t<\n\t\tstd::is_same_v<typename T::value_type, std::remove_const_t<decltype(T::default_value)>>\n\t>\n>\n{\n\tusing type = def_integer<T>;\n};\n\n\ntemplate <class T, class Enable, class... EXT_TRAITS>\nstruct value;\n\ntemplate <class T>\nstruct value<T, std::enable_if_t<is_value_traits<T>::value>>\n\t\t: value_selector<T>::type {};\n\ntemplate<class T, class... EXT_TRAITS>\nstruct value<T, std::enable_if_t<std::is_arithmetic_v<T>>, EXT_TRAITS...>\n\t\t: numeric_value<value_traits<T, EXT_TRAITS...>> {};\n\ntemplate<std::size_t N, class... EXT_TRAITS>\nstruct value<bytes<N>, void, EXT_TRAITS...>\n\t\t: numeric_value<value_traits<bytes<N>, EXT_TRAITS...>> {};\n\ntemplate<std::size_t N, class... EXT_TRAITS>\nstruct value<bits<N>, void, EXT_TRAITS...>\n\t\t: numeric_value<value_traits<bits<N>, EXT_TRAITS...>> {};\n\n} \/\/end: namespace detail\n\n\/**\n * generic value - a facade for numeric_values above\n *\/\ntemplate <class T, class... EXT_TRAITS>\nstruct value : detail::value<T, void, EXT_TRAITS...> {};\n\n} \/\/namespace med\n<commit_msg>fix builds<commit_after>\/**\n@file\nIE to represent generic integral value\n\n@copyright Denis Priyomov 2016-2017\nDistributed under the MIT License\n(See accompanying file LICENSE or visit https:\/\/github.com\/cppden\/med)\n*\/\n\n#pragma once\n\n#include <type_traits>\n\n#include \"units.hpp\"\n#include \"ie_type.hpp\"\n#include \"name.hpp\"\n#include \"exception.hpp\"\n\n\nnamespace med {\n\n\/\/traits representing a fixed value of particular size (in bits\/bytes\/int)\n\/\/which is predefined during encode and decode\ntemplate <std::size_t VAL, typename T, class... EXT_TRAITS>\nstruct fixed : value_traits<T, EXT_TRAITS...>\n{\n\tstatic constexpr bool is_const = true;\n\tstatic constexpr typename value_traits<T, EXT_TRAITS...>::value_type value = VAL;\n};\n\n\/\/traits representing a fixed value with default\ntemplate <std::size_t VAL, class T, class... EXT_TRAITS>\nstruct defaults : value_traits<T, EXT_TRAITS...>\n{\n\tstatic constexpr typename value_traits<T, EXT_TRAITS...>::value_type default_value = VAL;\n};\n\n\/\/traits representing initialized value which is encoded with the fixed value\n\/\/but can have any value when decoded\ntemplate <std::size_t VAL, class T, class... EXT_TRAITS>\nstruct init : fixed<VAL, T, EXT_TRAITS...>\n{\n\tstatic constexpr bool is_const = false;\n};\n\nnamespace detail {\n\n\/**\n * plain numeric value\n *\/\ntemplate <class TRAITS>\nstruct numeric_value : IE<IE_VALUE>\n{\n\tusing traits = TRAITS;\n\tusing value_type = typename traits::value_type;\n\tusing base_t = numeric_value;\n\n\tvalue_type get() const { return get_encoded(); }\n\tauto set(value_type v) { return set_encoded(v); }\n\n\t\/\/NOTE: do not override!\n\tstatic constexpr bool is_const = false;\n\tvalue_type get_encoded() const { return m_value; }\n\tvoid set_encoded(value_type v) { m_value = v; m_set = true; }\n\tvoid clear() { m_set = false; }\n\tbool is_set() const { return m_set; }\n\texplicit operator bool() const { return is_set(); }\n\ttemplate <class... ARGS>\n\tvoid copy(base_t const& from, ARGS&&...) { m_value = from.m_value; m_set = from.m_set; }\n\n#if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ < 9)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmaybe-uninitialized\"\n#endif\n\n\tbool operator==(numeric_value const& rhs) const { return is_set() == rhs.is_set() && (!is_set() || get() == rhs.get()); }\n\n#if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ < 9)\n#pragma GCC diagnostic pop\n#endif\n\n\tbool operator!=(numeric_value const& rhs) const { return !this->operator==(rhs); }\n\nprivate:\n\tbool m_set{false};\n\tvalue_type m_value{};\n};\n\n\/**\n * plain fixed integral value\n * gives error if decoded value doesn't match the fixed one\n *\/\ntemplate <class TRAITS>\nstruct const_integer : IE<IE_VALUE>\n{\n\tusing traits = TRAITS;\n\tusing value_type = typename traits::value_type;\n\tusing base_t = const_integer;\n\tusing writable = numeric_value<traits>;\n\n\tstatic constexpr void clear() { }\n\tstatic constexpr value_type get() { return get_encoded(); }\n\n\n\t\/\/NOTE: do not override!\n\tstatic constexpr bool is_const = true;\n\texplicit operator bool() const { return is_set(); }\n\tstatic constexpr value_type get_encoded() { return traits::value; }\n\tstatic constexpr bool set_encoded(value_type v) { return traits::value == v; }\n\tstatic constexpr bool is_set() { return true; }\n\tstatic constexpr bool match(value_type v) { return traits::value == v; }\n\ttemplate <class... ARGS>\n\tstatic constexpr void copy(base_t const&, ARGS&&...){ }\n\n\tbool operator==(const_integer const&) const { return true; } \/\/equal to itself by definition\n\tbool operator!=(const_integer const&) const { return false; }\n};\n\n\/**\n * plain initialized\/set field\n * decoded even if doesn't match initial value\n *\/\ntemplate <class TRAITS>\nstruct init_integer : IE<IE_VALUE>\n{\n\tusing traits = TRAITS;\n\tusing value_type = typename traits::value_type;\n\tusing base_t = init_integer;\n\n\tstatic constexpr void clear() { }\n\texplicit operator bool() const { return is_set(); }\n\t\/\/NOTE: do not override!\n\tstatic constexpr bool is_const = true;\n\tstatic constexpr value_type get_encoded() { return traits::value; }\n\tstatic constexpr void set_encoded(value_type) { }\n\tstatic constexpr bool is_set() { return true; }\n\ttemplate <class... ARGS>\n\tstatic constexpr void copy(base_t const&, ARGS&&...){ }\n\tbool operator==(init_integer const&) const { return true; }\n\tbool operator!=(init_integer const&) const { return false; }\n};\n\n\/**\n * integer with a default value\n *\/\ntemplate <class TRAITS>\nstruct def_integer : numeric_value<TRAITS>\n{\n\tusing traits = TRAITS;\n\tusing value_type = typename traits::value_type;\n\tusing base_t = def_integer;\n\n\t\/\/NOTE: do not override!\n\tvalue_type get_encoded() const\n\t{\n\t\treturn this->is_set() ? numeric_value<TRAITS>::get_encoded() : traits::default_value;\n\t}\n};\n\n\n\/\/meta-function to select proper implementation of numeric value\ntemplate <class T, typename Enable = void>\nstruct value_selector;\n\ntemplate <class T>\nstruct value_selector<T,\n\tstd::enable_if_t<\n\t\tstd::is_same_v<typename T::value_type, std::remove_const_t<decltype(T::value)>>\n\t\t&& T::is_const\n\t>\n>\n{\n\tusing type = const_integer<T>;\n};\n\ntemplate <class T>\nstruct value_selector<T,\n\tstd::enable_if_t<\n\t\tstd::is_same_v<typename T::value_type, std::remove_const_t<decltype(T::value)>>\n\t\t&& !T::is_const\n\t>\n>\n{\n\tusing type = init_integer<T>;\n};\n\ntemplate <class T>\nstruct value_selector<T,\n\tstd::enable_if_t<\n\t\tstd::is_same_v<typename T::value_type, std::remove_const_t<decltype(T::default_value)>>\n\t>\n>\n{\n\tusing type = def_integer<T>;\n};\n\n\ntemplate <class T, class Enable, class... EXT_TRAITS>\nstruct value;\n\ntemplate <class T>\nstruct value<T, std::enable_if_t<is_value_traits<T>::value>>\n\t\t: value_selector<T>::type {};\n\ntemplate<class T, class... EXT_TRAITS>\nstruct value<T, std::enable_if_t<std::is_arithmetic_v<T>>, EXT_TRAITS...>\n\t\t: numeric_value<value_traits<T, EXT_TRAITS...>> {};\n\ntemplate<std::size_t N, class... EXT_TRAITS>\nstruct value<bytes<N>, void, EXT_TRAITS...>\n\t\t: numeric_value<value_traits<bytes<N>, EXT_TRAITS...>> {};\n\ntemplate<std::size_t N, class... EXT_TRAITS>\nstruct value<bits<N>, void, EXT_TRAITS...>\n\t\t: numeric_value<value_traits<bits<N>, EXT_TRAITS...>> {};\n\n} \/\/end: namespace detail\n\n\/**\n * generic value - a facade for numeric_values above\n *\/\ntemplate <class T, class... EXT_TRAITS>\nstruct value : detail::value<T, void, EXT_TRAITS...> {};\n\n} \/\/namespace med\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * xmlparser.cpp\n *****************************************************************************\n * Copyright (C) 2004 the VideoLAN team\n * $Id$\n *\n * Authors: Cyril Deguet <asmax@via.ecp.fr>\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; 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"xmlparser.hpp\"\n#include \"..\/src\/os_factory.hpp\"\n#include <vlc_url.h>\n\n#include <sys\/stat.h>\n#include <vlc_fs.h>\n\nXMLParser::XMLParser( intf_thread_t *pIntf, const std::string &rFileName )\n : SkinObject( pIntf ), m_pXML( NULL ), m_pReader( NULL ), m_pStream( NULL )\n{\n m_pXML = xml_Create( pIntf );\n if( !m_pXML )\n {\n msg_Err( getIntf(), \"cannot initialize xml\" );\n return;\n }\n\n LoadCatalog();\n\n char *psz_uri = vlc_path2uri( rFileName.c_str(), NULL );\n m_pStream = stream_UrlNew( pIntf, psz_uri );\n free( psz_uri );\n if( !m_pStream )\n {\n msg_Err( getIntf(), \"failed to open %s for reading\",\n rFileName.c_str() );\n return;\n }\n\n m_pReader = xml_ReaderCreate( m_pXML, m_pStream );\n if( !m_pReader )\n {\n msg_Err( getIntf(), \"failed to open %s for parsing\",\n rFileName.c_str() );\n return;\n }\n\n xml_ReaderUseDTD( m_pReader );\n}\n\n\nXMLParser::~XMLParser()\n{\n if( m_pReader ) xml_ReaderDelete( m_pReader );\n if( m_pXML ) xml_Delete( m_pXML );\n if( m_pStream ) stream_Delete( m_pStream );\n}\n\n\nvoid XMLParser::LoadCatalog()\n{\n \/\/ Get the resource path and look for the DTD\n OSFactory *pOSFactory = OSFactory::instance( getIntf() );\n const std::list<std::string> &resPath = pOSFactory->getResourcePath();\n const std::string &sep = pOSFactory->getDirSeparator();\n std::list<std::string>::const_iterator it;\n\n struct stat statBuf;\n\n \/\/ Try to load the catalog first (needed at least on win32 where\n \/\/ we don't have a default catalog)\n for( it = resPath.begin(); it != resPath.end(); ++it )\n {\n std::string catalog_path = (*it) + sep + \"skin.catalog\";\n if( !vlc_stat( catalog_path.c_str(), &statBuf ) )\n {\n msg_Dbg( getIntf(), \"Using catalog %s\", catalog_path.c_str() );\n xml_CatalogLoad( m_pXML, catalog_path.c_str() );\n break;\n }\n }\n if( it == resPath.end() )\n {\n \/\/ Ok, try the default one\n xml_CatalogLoad( m_pXML, NULL );\n }\n\n for( it = resPath.begin(); it != resPath.end(); ++it )\n {\n std::string path = (*it) + sep + \"skin.dtd\";\n if( !vlc_stat( path.c_str(), &statBuf ) )\n {\n \/\/ DTD found\n msg_Dbg( getIntf(), \"using DTD %s\", path.c_str() );\n\n \/\/ Add an entry in the default catalog\n xml_CatalogAdd( m_pXML, \"public\",\n \"-\/\/VideoLAN\/\/DTD VLC Skins V\"\n SKINS_DTD_VERSION \"\/\/EN\", path.c_str() );\n break;\n }\n }\n if( it == resPath.end() )\n {\n msg_Err( getIntf(), \"cannot find the skins DTD\");\n }\n}\n\nbool XMLParser::parse()\n{\n const char *node;\n int type;\n\n if( !m_pReader ) return false;\n\n m_errors = false;\n\n while( (type = xml_ReaderNextNode( m_pReader, &node )) > 0 )\n {\n if( m_errors ) return false;\n\n switch( type )\n {\n case XML_READER_STARTELEM:\n {\n \/\/ Read the attributes\n AttrList_t attributes;\n const char *name, *value;\n while( (name = xml_ReaderNextAttr( m_pReader, &value )) != NULL )\n attributes[strdup(name)] = strdup(value);\n\n handleBeginElement( node, attributes );\n\n std::map<const char*, const char*, ltstr> ::iterator it =\n attributes.begin();\n while( it != attributes.end() )\n {\n free( (char *)it->first );\n free( (char *)it->second );\n ++it;\n }\n break;\n }\n\n \/\/ End element\n case XML_READER_ENDELEM:\n {\n handleEndElement( node );\n break;\n }\n }\n }\n return (type == 0 && !m_errors );\n}\n<commit_msg>skins2: uninitialized member (cid #1346980)<commit_after>\/*****************************************************************************\n * xmlparser.cpp\n *****************************************************************************\n * Copyright (C) 2004 the VideoLAN team\n * $Id$\n *\n * Authors: Cyril Deguet <asmax@via.ecp.fr>\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; 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"xmlparser.hpp\"\n#include \"..\/src\/os_factory.hpp\"\n#include <vlc_url.h>\n\n#include <sys\/stat.h>\n#include <vlc_fs.h>\n\nXMLParser::XMLParser( intf_thread_t *pIntf, const std::string &rFileName )\n : SkinObject( pIntf ), m_pXML( NULL ), m_pReader( NULL ), m_pStream( NULL )\n{\n m_errors = false;\n m_pXML = xml_Create( pIntf );\n if( !m_pXML )\n {\n msg_Err( getIntf(), \"cannot initialize xml\" );\n return;\n }\n\n LoadCatalog();\n\n char *psz_uri = vlc_path2uri( rFileName.c_str(), NULL );\n m_pStream = stream_UrlNew( pIntf, psz_uri );\n free( psz_uri );\n if( !m_pStream )\n {\n msg_Err( getIntf(), \"failed to open %s for reading\",\n rFileName.c_str() );\n return;\n }\n\n m_pReader = xml_ReaderCreate( m_pXML, m_pStream );\n if( !m_pReader )\n {\n msg_Err( getIntf(), \"failed to open %s for parsing\",\n rFileName.c_str() );\n return;\n }\n\n xml_ReaderUseDTD( m_pReader );\n}\n\n\nXMLParser::~XMLParser()\n{\n if( m_pReader ) xml_ReaderDelete( m_pReader );\n if( m_pXML ) xml_Delete( m_pXML );\n if( m_pStream ) stream_Delete( m_pStream );\n}\n\n\nvoid XMLParser::LoadCatalog()\n{\n \/\/ Get the resource path and look for the DTD\n OSFactory *pOSFactory = OSFactory::instance( getIntf() );\n const std::list<std::string> &resPath = pOSFactory->getResourcePath();\n const std::string &sep = pOSFactory->getDirSeparator();\n std::list<std::string>::const_iterator it;\n\n struct stat statBuf;\n\n \/\/ Try to load the catalog first (needed at least on win32 where\n \/\/ we don't have a default catalog)\n for( it = resPath.begin(); it != resPath.end(); ++it )\n {\n std::string catalog_path = (*it) + sep + \"skin.catalog\";\n if( !vlc_stat( catalog_path.c_str(), &statBuf ) )\n {\n msg_Dbg( getIntf(), \"Using catalog %s\", catalog_path.c_str() );\n xml_CatalogLoad( m_pXML, catalog_path.c_str() );\n break;\n }\n }\n if( it == resPath.end() )\n {\n \/\/ Ok, try the default one\n xml_CatalogLoad( m_pXML, NULL );\n }\n\n for( it = resPath.begin(); it != resPath.end(); ++it )\n {\n std::string path = (*it) + sep + \"skin.dtd\";\n if( !vlc_stat( path.c_str(), &statBuf ) )\n {\n \/\/ DTD found\n msg_Dbg( getIntf(), \"using DTD %s\", path.c_str() );\n\n \/\/ Add an entry in the default catalog\n xml_CatalogAdd( m_pXML, \"public\",\n \"-\/\/VideoLAN\/\/DTD VLC Skins V\"\n SKINS_DTD_VERSION \"\/\/EN\", path.c_str() );\n break;\n }\n }\n if( it == resPath.end() )\n {\n msg_Err( getIntf(), \"cannot find the skins DTD\");\n }\n}\n\nbool XMLParser::parse()\n{\n const char *node;\n int type;\n\n if( !m_pReader ) return false;\n\n m_errors = false;\n\n while( (type = xml_ReaderNextNode( m_pReader, &node )) > 0 )\n {\n if( m_errors ) return false;\n\n switch( type )\n {\n case XML_READER_STARTELEM:\n {\n \/\/ Read the attributes\n AttrList_t attributes;\n const char *name, *value;\n while( (name = xml_ReaderNextAttr( m_pReader, &value )) != NULL )\n attributes[strdup(name)] = strdup(value);\n\n handleBeginElement( node, attributes );\n\n std::map<const char*, const char*, ltstr> ::iterator it =\n attributes.begin();\n while( it != attributes.end() )\n {\n free( (char *)it->first );\n free( (char *)it->second );\n ++it;\n }\n break;\n }\n\n \/\/ End element\n case XML_READER_ENDELEM:\n {\n handleEndElement( node );\n break;\n }\n }\n }\n return (type == 0 && !m_errors );\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ddb.hpp \n\n Main include file.\n\n Part of Disc Data Base.\n\n Copyright (c) 2010 Wincent Balin\n\n Based upon ddb.pl, created years before and serving faithfully until today.\n\n Uses SQLite database version 3.\n\n Published under MIT license. See LICENSE file for further information.\n*\/\n\n#ifndef DDB_HPP\n#define DDB_HPP\n\n#include <string>\n\n#include <sqlite3.h>\n\n\nusing namespace std;\n\n\/\/ Name of the database\n#define DATABASE_NAME \"discdb\"\n\n\/\/ Name of the table\n#define TABLE_NAME \"ddb\"\n\n\n\nclass DDB\n{\npublic:\n DDB(int argc, char** argv);\n ~DDB(void);\n bool run(void);\n \/\/ Constants\n const static char* discdb_schema;\nprivate:\n bool is_discdb(void);\n bool is_disc_present(string& name);\n bool is_directory(string& filename);\n inline bool add_disc(void);\n inline bool remove_disc(void);\n inline bool list_contents(void);\n inline bool list_discs(void);\n inline bool list_directories(void);\n inline bool list_files(void);\n inline bool initialize_database(void);\n inline bool search_text(void);\n void print_help(void);\n void msg(int min_verbosity, const char* message);\n \/\/ Database handle\n sqlite3* db;\n \/\/ Configuration flags\n string db_filename;\n string disc_name;\n string argument;\n bool do_initialize;\n bool do_add;\n bool do_list;\n bool do_remove;\n bool directories_only;\n int verbosity;\n};\n\n\n\/\/ discdb schema\nconst char* DDB::discdb_schema =\n \"CREATE TABLE \"TABLE_NAME\" \"\n \"(directory TEXT NOT NULL, file TEXT, disc TEXT NOT NULL)\";\n\n\n\n#endif \/* DDB_HPP *\/\n<commit_msg>Small code style update<commit_after>\/**\n ddb.hpp\n\n Main include file.\n\n Part of Disc Data Base.\n\n Copyright (c) 2010 Wincent Balin\n\n Based upon ddb.pl, created years before and serving faithfully until today.\n\n Uses SQLite database version 3.\n\n Published under MIT license. See LICENSE file for further information.\n*\/\n\n#ifndef DDB_HPP\n#define DDB_HPP\n\n#include <string>\n\n#include <sqlite3.h>\n\n\nusing namespace std;\n\n\/\/ Name of the database\n#define DATABASE_NAME \"discdb\"\n\n\/\/ Name of the table\n#define TABLE_NAME \"ddb\"\n\n\n\nclass DDB\n{\npublic:\n DDB(int argc, char** argv);\n ~DDB(void);\n bool run(void);\n \/\/ Constants\n const static char* discdb_schema;\nprivate:\n bool is_discdb(void);\n bool is_disc_present(string& name);\n bool is_directory(string& filename);\n inline bool add_disc(void);\n inline bool remove_disc(void);\n inline bool list_contents(void);\n inline bool list_discs(void);\n inline bool list_directories(void);\n inline bool list_files(void);\n inline bool initialize_database(void);\n inline bool search_text(void);\n void print_help(void);\n void msg(int min_verbosity, const char* message);\n \/\/ Database handle\n sqlite3* db;\n \/\/ Configuration flags\n string db_filename;\n string disc_name;\n string argument;\n bool do_initialize;\n bool do_add;\n bool do_list;\n bool do_remove;\n bool directories_only;\n int verbosity;\n};\n\n\n\/\/ discdb schema\nconst char* DDB::discdb_schema =\n \"CREATE TABLE \"TABLE_NAME\" \"\n \"(directory TEXT NOT NULL, file TEXT, disc TEXT NOT NULL)\";\n\n\n\n#endif \/* DDB_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>#include <b9\/ExecutionContext.hpp>\n#include <b9\/VirtualMachine.hpp>\n#include <b9\/compiler\/Compiler.hpp>\n\n#include <omrgc.h>\n#include <OMR\/Om\/Allocator.inl.hpp>\n#include <OMR\/Om\/ArrayBuffer.inl.hpp>\n#include <OMR\/Om\/ArrayBufferMap.inl.hpp>\n#include <OMR\/Om\/Map.inl.hpp>\n#include <OMR\/Om\/Object.inl.hpp>\n#include <OMR\/Om\/ObjectMap.inl.hpp>\n#include <OMR\/Om\/RootRef.inl.hpp>\n#include <OMR\/Om\/Value.hpp>\n#include \"Jit.hpp\"\n\n#include <sys\/time.h>\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <sstream>\n#include <string>\n\nnamespace b9 {\n\nExecutionContext::ExecutionContext(VirtualMachine &virtualMachine,\n const Config &cfg)\n : omContext_(virtualMachine.memoryManager()),\n virtualMachine_(&virtualMachine),\n cfg_(&cfg) {\n omContext().userRoots().push_back(\n [this](Om::Context &cx, Om::Visitor &v) { this->visit(cx, v); });\n}\n\nvoid ExecutionContext::reset() {\n stack_.reset();\n programCounter_ = 0;\n}\n\nOm::Value ExecutionContext::callJitFunction(JitFunction jitFunction,\n std::size_t nargs) {\n if (cfg_->verbose) {\n std::cout << \"Int: transition to jit: \" << jitFunction << std::endl;\n }\n\n Om::RawValue result = 0;\n\n if (cfg_->passParam) {\n switch (nargs) {\n case 0: {\n result = jitFunction(this);\n } break;\n case 1: {\n StackElement p1 = pop();\n result = jitFunction(this, p1.raw());\n } break;\n case 2: {\n StackElement p2 = pop();\n StackElement p1 = pop();\n result = jitFunction(this, p1.raw(), p2.raw());\n } break;\n case 3: {\n StackElement p3 = pop();\n StackElement p2 = pop();\n StackElement p1 = pop();\n result = (*jitFunction)(this, p1.raw(), p2.raw(), p3.raw());\n } break;\n default:\n throw std::runtime_error{\"Need to add handlers for more parameters\"};\n break;\n }\n } else {\n result = jitFunction(this);\n }\n\n return Om::Value(Om::FROM_RAW, result);\n}\n\nStackElement ExecutionContext::interpret(const std::size_t functionIndex) {\n auto function = virtualMachine_->getFunction(functionIndex);\n auto argsCount = function->nargs;\n auto jitFunction = virtualMachine_->getJitAddress(functionIndex);\n\n if (jitFunction) {\n return callJitFunction(jitFunction, argsCount);\n }\n\n \/\/ interpret the method otherwise\n const Instruction *instructionPointer = function->instructions.data();\n\n StackElement *args = stack_.top() - function->nargs;\n stack_.pushn(function->nregs);\n\n while (*instructionPointer != END_SECTION) {\n switch (instructionPointer->byteCode()) {\n case ByteCode::FUNCTION_CALL:\n doFunctionCall(instructionPointer->parameter());\n break;\n case ByteCode::FUNCTION_RETURN: {\n auto result = stack_.pop();\n stack_.restore(args);\n return result;\n break;\n }\n case ByteCode::PRIMITIVE_CALL:\n doPrimitiveCall(instructionPointer->parameter());\n break;\n case ByteCode::JMP:\n instructionPointer += instructionPointer->parameter();\n break;\n case ByteCode::DUPLICATE:\n doDuplicate();\n break;\n case ByteCode::DROP:\n doDrop();\n break;\n case ByteCode::PUSH_FROM_VAR:\n doPushFromVar(args, instructionPointer->parameter());\n break;\n case ByteCode::POP_INTO_VAR:\n \/\/ TODO bad name, push or pop?\n doPushIntoVar(args, instructionPointer->parameter());\n break;\n case ByteCode::INT_ADD:\n doIntAdd();\n break;\n case ByteCode::INT_SUB:\n doIntSub();\n break;\n case ByteCode::INT_MUL:\n doIntMul();\n break;\n case ByteCode::INT_DIV:\n doIntDiv();\n break;\n case ByteCode::INT_PUSH_CONSTANT:\n doIntPushConstant(instructionPointer->parameter());\n break;\n case ByteCode::INT_NOT:\n doIntNot();\n break;\n case ByteCode::INT_JMP_EQ:\n instructionPointer += doIntJmpEq(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_NEQ:\n instructionPointer += doIntJmpNeq(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_GT:\n instructionPointer += doIntJmpGt(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_GE:\n instructionPointer += doIntJmpGe(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_LT:\n instructionPointer += doIntJmpLt(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_LE:\n instructionPointer += doIntJmpLe(instructionPointer->parameter());\n break;\n case ByteCode::STR_PUSH_CONSTANT:\n doStrPushConstant(instructionPointer->parameter());\n break;\n case ByteCode::STR_JMP_EQ:\n \/\/ TODO\n break;\n case ByteCode::STR_JMP_NEQ:\n \/\/ TODO\n break;\n case ByteCode::NEW_OBJECT:\n doNewObject();\n break;\n case ByteCode::PUSH_FROM_OBJECT:\n doPushFromObject(OMR::Om::Id(instructionPointer->parameter()));\n break;\n case ByteCode::POP_INTO_OBJECT:\n doPopIntoObject(OMR::Om::Id(instructionPointer->parameter()));\n break;\n case ByteCode::CALL_INDIRECT:\n doCallIndirect();\n break;\n case ByteCode::SYSTEM_COLLECT:\n doSystemCollect();\n break;\n default:\n assert(false);\n break;\n }\n instructionPointer++;\n programCounter_++;\n }\n throw std::runtime_error(\"Reached end of function\");\n}\n\nvoid ExecutionContext::push(StackElement value) { stack_.push(value); }\n\nStackElement ExecutionContext::pop() { return stack_.pop(); }\n\nvoid ExecutionContext::doFunctionCall(Parameter value) {\n auto f = virtualMachine_->getFunction((std::size_t)value);\n auto result = interpret(value);\n push(result);\n}\n\nvoid ExecutionContext::doFunctionReturn(StackElement returnVal) {\n \/\/ TODO\n}\n\nvoid ExecutionContext::doPrimitiveCall(Parameter value) {\n PrimitiveFunction *primitive = virtualMachine_->getPrimitive(value);\n (*primitive)(this);\n}\n\nParameter ExecutionContext::doJmp(Parameter offset) { return offset; }\n\nvoid ExecutionContext::doDuplicate() {\n auto x = pop();\n push(x);\n push(x);\n}\n\nvoid ExecutionContext::doDrop() { stack_.pop(); }\n\nvoid ExecutionContext::doPushFromVar(StackElement *args, Parameter offset) {\n stack_.push(args[offset]);\n}\n\nvoid ExecutionContext::doPushIntoVar(StackElement *args, Parameter offset) {\n args[offset] = stack_.pop();\n}\n\nvoid ExecutionContext::doIntAdd() {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n StackElement result;\n result.setInteger(left + right);\n push(result);\n}\n\nvoid ExecutionContext::doIntSub() {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n StackElement result;\n result.setInteger(left - right);\n push(result);\n}\n\nvoid ExecutionContext::doIntMul() {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n StackElement result;\n result.setInteger(left * right);\n push(result);\n}\n\nvoid ExecutionContext::doIntDiv() {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n StackElement result;\n result.setInteger(left \/ right);\n push(result);\n}\n\nvoid ExecutionContext::doIntPushConstant(Parameter value) {\n stack_.push(StackElement().setInteger(value));\n}\n\nvoid ExecutionContext::doIntNot() {\n std::int32_t i = stack_.pop().getInteger();\n StackElement v;\n v.setInteger(!i);\n push(v);\n}\n\nParameter ExecutionContext::doIntJmpEq(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left == right) {\n return delta;\n }\n return 0;\n}\n\nParameter ExecutionContext::doIntJmpNeq(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left != right) {\n return delta;\n }\n return 0;\n}\n\nParameter ExecutionContext::doIntJmpGt(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left > right) {\n return delta;\n }\n return 0;\n}\n\n\/\/ ( left right -- )\nParameter ExecutionContext::doIntJmpGe(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left >= right) {\n return delta;\n }\n return 0;\n}\n\n\/\/ ( left right -- )\nParameter ExecutionContext::doIntJmpLt(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left < right) {\n return delta;\n }\n return 0;\n}\n\n\/\/ ( left right -- )\nParameter ExecutionContext::doIntJmpLe(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left <= right) {\n return delta;\n }\n return 0;\n}\n\n\/\/ ( -- string )\nvoid ExecutionContext::doStrPushConstant(Parameter param) {\n stack_.push(OMR::Om::Value().setInteger(param));\n}\n\n\/\/ ( -- object )\nvoid ExecutionContext::doNewObject() {\n auto ref = OMR::Om::Object::allocate(*this);\n stack_.push(OMR::Om::Value(ref));\n}\n\n\/\/ ( object -- value )\nvoid ExecutionContext::doPushFromObject(Om::Id slotId) {\n auto value = stack_.pop();\n if (!value.isPtr()) {\n throw std::runtime_error(\"Accessing non-object value as an object.\");\n }\n auto obj = value.getPtr<Om::Object>();\n Om::SlotDescriptor descriptor;\n auto found = Om::Object::lookup(*this, obj, slotId, descriptor);\n if (found) {\n Om::Value result;\n result = Om::Object::getValue(*this, obj, descriptor);\n stack_.push(result);\n } else {\n throw std::runtime_error(\"Accessing an object's field that doesn't exist.\");\n }\n}\n\n\/\/ ( object value -- )\nvoid ExecutionContext::doPopIntoObject(Om::Id slotId) {\n if (!stack_.peek().isPtr()) {\n throw std::runtime_error(\"Accessing non-object as an object\");\n }\n\n std::size_t offset = 0;\n auto object = stack_.pop().getPtr<Om::Object>();\n\n Om::SlotDescriptor descriptor;\n bool found = Om::Object::lookup(*this, object, slotId, descriptor);\n\n if (!found) {\n static constexpr Om::SlotType type(Om::Id(0), Om::CoreType::VALUE);\n\n Om::RootRef<Om::Object> root(*this, object);\n auto map = Om::Object::transition(*this, root, {{type, slotId}});\n assert(map != nullptr);\n\n \/\/ TODO: Get the descriptor fast after a single-slot transition.\n Om::Object::lookup(*this, object, slotId, descriptor);\n object = root.get();\n }\n\n auto val = pop();\n Om::Object::setValue(*this, object, descriptor, val);\n \/\/ TODO: Write barrier the object on store.\n}\n\nvoid ExecutionContext::doCallIndirect() {\n assert(0); \/\/ TODO: Implement call indirect\n}\n\nvoid ExecutionContext::doSystemCollect() {\n std::cout << \"SYSTEM COLLECT!!!\" << std::endl;\n OMR_GC_SystemCollect(omContext_.omrVmThread(), 0);\n}\n\n} \/\/ namespace b9\n<commit_msg>Dont pop while handling BC_DUPLICATE<commit_after>#include <b9\/ExecutionContext.hpp>\n#include <b9\/VirtualMachine.hpp>\n#include <b9\/compiler\/Compiler.hpp>\n\n#include <omrgc.h>\n#include <OMR\/Om\/Allocator.inl.hpp>\n#include <OMR\/Om\/ArrayBuffer.inl.hpp>\n#include <OMR\/Om\/ArrayBufferMap.inl.hpp>\n#include <OMR\/Om\/Map.inl.hpp>\n#include <OMR\/Om\/Object.inl.hpp>\n#include <OMR\/Om\/ObjectMap.inl.hpp>\n#include <OMR\/Om\/RootRef.inl.hpp>\n#include <OMR\/Om\/Value.hpp>\n#include \"Jit.hpp\"\n\n#include <sys\/time.h>\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <sstream>\n#include <string>\n\nnamespace b9 {\n\nExecutionContext::ExecutionContext(VirtualMachine &virtualMachine,\n const Config &cfg)\n : omContext_(virtualMachine.memoryManager()),\n virtualMachine_(&virtualMachine),\n cfg_(&cfg) {\n omContext().userRoots().push_back(\n [this](Om::Context &cx, Om::Visitor &v) { this->visit(cx, v); });\n}\n\nvoid ExecutionContext::reset() {\n stack_.reset();\n programCounter_ = 0;\n}\n\nOm::Value ExecutionContext::callJitFunction(JitFunction jitFunction,\n std::size_t nargs) {\n if (cfg_->verbose) {\n std::cout << \"Int: transition to jit: \" << jitFunction << std::endl;\n }\n\n Om::RawValue result = 0;\n\n if (cfg_->passParam) {\n switch (nargs) {\n case 0: {\n result = jitFunction(this);\n } break;\n case 1: {\n StackElement p1 = pop();\n result = jitFunction(this, p1.raw());\n } break;\n case 2: {\n StackElement p2 = pop();\n StackElement p1 = pop();\n result = jitFunction(this, p1.raw(), p2.raw());\n } break;\n case 3: {\n StackElement p3 = pop();\n StackElement p2 = pop();\n StackElement p1 = pop();\n result = (*jitFunction)(this, p1.raw(), p2.raw(), p3.raw());\n } break;\n default:\n throw std::runtime_error{\"Need to add handlers for more parameters\"};\n break;\n }\n } else {\n result = jitFunction(this);\n }\n\n return Om::Value(Om::FROM_RAW, result);\n}\n\nStackElement ExecutionContext::interpret(const std::size_t functionIndex) {\n auto function = virtualMachine_->getFunction(functionIndex);\n auto argsCount = function->nargs;\n auto jitFunction = virtualMachine_->getJitAddress(functionIndex);\n\n if (jitFunction) {\n return callJitFunction(jitFunction, argsCount);\n }\n\n \/\/ interpret the method otherwise\n const Instruction *instructionPointer = function->instructions.data();\n\n StackElement *args = stack_.top() - function->nargs;\n stack_.pushn(function->nregs);\n\n while (*instructionPointer != END_SECTION) {\n switch (instructionPointer->byteCode()) {\n case ByteCode::FUNCTION_CALL:\n doFunctionCall(instructionPointer->parameter());\n break;\n case ByteCode::FUNCTION_RETURN: {\n auto result = stack_.pop();\n stack_.restore(args);\n return result;\n break;\n }\n case ByteCode::PRIMITIVE_CALL:\n doPrimitiveCall(instructionPointer->parameter());\n break;\n case ByteCode::JMP:\n instructionPointer += instructionPointer->parameter();\n break;\n case ByteCode::DUPLICATE:\n doDuplicate();\n break;\n case ByteCode::DROP:\n doDrop();\n break;\n case ByteCode::PUSH_FROM_VAR:\n doPushFromVar(args, instructionPointer->parameter());\n break;\n case ByteCode::POP_INTO_VAR:\n \/\/ TODO bad name, push or pop?\n doPushIntoVar(args, instructionPointer->parameter());\n break;\n case ByteCode::INT_ADD:\n doIntAdd();\n break;\n case ByteCode::INT_SUB:\n doIntSub();\n break;\n case ByteCode::INT_MUL:\n doIntMul();\n break;\n case ByteCode::INT_DIV:\n doIntDiv();\n break;\n case ByteCode::INT_PUSH_CONSTANT:\n doIntPushConstant(instructionPointer->parameter());\n break;\n case ByteCode::INT_NOT:\n doIntNot();\n break;\n case ByteCode::INT_JMP_EQ:\n instructionPointer += doIntJmpEq(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_NEQ:\n instructionPointer += doIntJmpNeq(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_GT:\n instructionPointer += doIntJmpGt(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_GE:\n instructionPointer += doIntJmpGe(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_LT:\n instructionPointer += doIntJmpLt(instructionPointer->parameter());\n break;\n case ByteCode::INT_JMP_LE:\n instructionPointer += doIntJmpLe(instructionPointer->parameter());\n break;\n case ByteCode::STR_PUSH_CONSTANT:\n doStrPushConstant(instructionPointer->parameter());\n break;\n case ByteCode::STR_JMP_EQ:\n \/\/ TODO\n break;\n case ByteCode::STR_JMP_NEQ:\n \/\/ TODO\n break;\n case ByteCode::NEW_OBJECT:\n doNewObject();\n break;\n case ByteCode::PUSH_FROM_OBJECT:\n doPushFromObject(OMR::Om::Id(instructionPointer->parameter()));\n break;\n case ByteCode::POP_INTO_OBJECT:\n doPopIntoObject(OMR::Om::Id(instructionPointer->parameter()));\n break;\n case ByteCode::CALL_INDIRECT:\n doCallIndirect();\n break;\n case ByteCode::SYSTEM_COLLECT:\n doSystemCollect();\n break;\n default:\n assert(false);\n break;\n }\n instructionPointer++;\n programCounter_++;\n }\n throw std::runtime_error(\"Reached end of function\");\n}\n\nvoid ExecutionContext::push(StackElement value) { stack_.push(value); }\n\nStackElement ExecutionContext::pop() { return stack_.pop(); }\n\nvoid ExecutionContext::doFunctionCall(Parameter value) {\n auto f = virtualMachine_->getFunction((std::size_t)value);\n auto result = interpret(value);\n push(result);\n}\n\nvoid ExecutionContext::doFunctionReturn(StackElement returnVal) {\n \/\/ TODO\n}\n\nvoid ExecutionContext::doPrimitiveCall(Parameter value) {\n PrimitiveFunction *primitive = virtualMachine_->getPrimitive(value);\n (*primitive)(this);\n}\n\nParameter ExecutionContext::doJmp(Parameter offset) { return offset; }\n\nvoid ExecutionContext::doDuplicate() {\n push(stack_.peek());\n}\n\nvoid ExecutionContext::doDrop() { stack_.pop(); }\n\nvoid ExecutionContext::doPushFromVar(StackElement *args, Parameter offset) {\n stack_.push(args[offset]);\n}\n\nvoid ExecutionContext::doPushIntoVar(StackElement *args, Parameter offset) {\n args[offset] = stack_.pop();\n}\n\nvoid ExecutionContext::doIntAdd() {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n StackElement result;\n result.setInteger(left + right);\n push(result);\n}\n\nvoid ExecutionContext::doIntSub() {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n StackElement result;\n result.setInteger(left - right);\n push(result);\n}\n\nvoid ExecutionContext::doIntMul() {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n StackElement result;\n result.setInteger(left * right);\n push(result);\n}\n\nvoid ExecutionContext::doIntDiv() {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n StackElement result;\n result.setInteger(left \/ right);\n push(result);\n}\n\nvoid ExecutionContext::doIntPushConstant(Parameter value) {\n stack_.push(StackElement().setInteger(value));\n}\n\nvoid ExecutionContext::doIntNot() {\n std::int32_t i = stack_.pop().getInteger();\n StackElement v;\n v.setInteger(!i);\n push(v);\n}\n\nParameter ExecutionContext::doIntJmpEq(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left == right) {\n return delta;\n }\n return 0;\n}\n\nParameter ExecutionContext::doIntJmpNeq(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left != right) {\n return delta;\n }\n return 0;\n}\n\nParameter ExecutionContext::doIntJmpGt(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left > right) {\n return delta;\n }\n return 0;\n}\n\n\/\/ ( left right -- )\nParameter ExecutionContext::doIntJmpGe(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left >= right) {\n return delta;\n }\n return 0;\n}\n\n\/\/ ( left right -- )\nParameter ExecutionContext::doIntJmpLt(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left < right) {\n return delta;\n }\n return 0;\n}\n\n\/\/ ( left right -- )\nParameter ExecutionContext::doIntJmpLe(Parameter delta) {\n std::int32_t right = stack_.pop().getInteger();\n std::int32_t left = stack_.pop().getInteger();\n if (left <= right) {\n return delta;\n }\n return 0;\n}\n\n\/\/ ( -- string )\nvoid ExecutionContext::doStrPushConstant(Parameter param) {\n stack_.push(OMR::Om::Value().setInteger(param));\n}\n\n\/\/ ( -- object )\nvoid ExecutionContext::doNewObject() {\n auto ref = OMR::Om::Object::allocate(*this);\n stack_.push(OMR::Om::Value(ref));\n}\n\n\/\/ ( object -- value )\nvoid ExecutionContext::doPushFromObject(Om::Id slotId) {\n auto value = stack_.pop();\n if (!value.isPtr()) {\n throw std::runtime_error(\"Accessing non-object value as an object.\");\n }\n auto obj = value.getPtr<Om::Object>();\n Om::SlotDescriptor descriptor;\n auto found = Om::Object::lookup(*this, obj, slotId, descriptor);\n if (found) {\n Om::Value result;\n result = Om::Object::getValue(*this, obj, descriptor);\n stack_.push(result);\n } else {\n throw std::runtime_error(\"Accessing an object's field that doesn't exist.\");\n }\n}\n\n\/\/ ( object value -- )\nvoid ExecutionContext::doPopIntoObject(Om::Id slotId) {\n if (!stack_.peek().isPtr()) {\n throw std::runtime_error(\"Accessing non-object as an object\");\n }\n\n std::size_t offset = 0;\n auto object = stack_.pop().getPtr<Om::Object>();\n\n Om::SlotDescriptor descriptor;\n bool found = Om::Object::lookup(*this, object, slotId, descriptor);\n\n if (!found) {\n static constexpr Om::SlotType type(Om::Id(0), Om::CoreType::VALUE);\n\n Om::RootRef<Om::Object> root(*this, object);\n auto map = Om::Object::transition(*this, root, {{type, slotId}});\n assert(map != nullptr);\n\n \/\/ TODO: Get the descriptor fast after a single-slot transition.\n Om::Object::lookup(*this, object, slotId, descriptor);\n object = root.get();\n }\n\n auto val = pop();\n Om::Object::setValue(*this, object, descriptor, val);\n \/\/ TODO: Write barrier the object on store.\n}\n\nvoid ExecutionContext::doCallIndirect() {\n assert(0); \/\/ TODO: Implement call indirect\n}\n\nvoid ExecutionContext::doSystemCollect() {\n std::cout << \"SYSTEM COLLECT!!!\" << std::endl;\n OMR_GC_SystemCollect(omContext_.omrVmThread(), 0);\n}\n\n} \/\/ namespace b9\n<|endoftext|>"} {"text":"<commit_before>\/* -*-Mode: c++;-*-\n Copyright (c) 2004-2010 John Plevyak, All Rights Reserved\n*\/\n#include \"ifadefs.h\"\n#include \"fail.h\"\n#include \"ifa.h\"\n#include \"pattern.h\"\n#include \"prim.h\"\n#include \"if1.h\"\n#include \"builtin.h\"\n#include \"pdb.h\"\n#include \"fun.h\"\n#include \"pnode.h\"\n#include \"fa.h\"\n#include \"ast.h\"\n#include \"var.h\"\n#include \"dom.h\"\n\n\/*\n It is intended that this file contain 2 implementations, \n one based on the AVars and another based on Vars (post concretize_program()).\n Only the former is currently extent.\n*\/\n\nstatic int mark_live_again = 0;\n\nstatic void\nprint_dead(FA *fa) {\n int ndead_pnodes = 0, ndead_vars = 0;\n forv_Fun(f, fa->funs) {\n forv_PNode(p, f->fa_all_PNodes)\n if (!p->live) {\n ndead_pnodes++;\n printf(\"PNode %d DEAD\\n\", p->id);\n }\n forv_Var(v, f->fa_all_Vars)\n if (!v->live) {\n ndead_vars++;\n printf(\"Var %d:%d %s DEAD\\n\", v->sym->id, v->id, v->sym->name ? v->sym->name : \"\");\n }\n }\n printf(\"%d PNodes DEAD\\n\", ndead_pnodes);\n printf(\"%d Vars DEAD\\n\", ndead_vars);\n}\n\nstatic void\nmark_live_avar(AVar *av) {\n if (av->var->sym->is_fake)\n return;\n av->live = 1;\n av->var->live = 1;\n mark_live_again = 1;\n if (av->var->def)\n av->var->def->live = 1;\n forv_AVar(aav, av->backward) if (aav) {\n if (!aav->live) {\n Vec<Sym *> consts;\n if (constant_info(aav->var, consts) != 1)\n mark_live_avar(aav);\n }\n }\n}\n\nstatic void \nmark_live_avars(FA *fa) {\n forv_Fun(f, fa->funs) {\n forv_PNode(p, f->fa_all_PNodes) {\n \/\/ if a pnode is live, and it is not a function call, it's inputs (rvals) must be live\n if (p->live && !f->calls.get(p)) {\n forv_Var(v, p->rvals) {\n Vec<Sym *> consts;\n if (constant_info(v, consts) != 1) {\n form_AVarMapElem(x, v->avars) {\n AVar *av = x->value;\n if (!av->live) \n mark_live_avar(av);\n }\n }\n }\n }\n }\n forv_Var(v, f->fa_all_Vars) {\n form_AVarMapElem(x, v->avars) {\n \/\/ if an instance variable is live, then the containing object must be live\n AVar *av = x->value;\n if (!av->live) {\n forv_CreationSet(cs, *av->out) if (cs) {\n forv_AVar(iv, cs->vars) {\n if (iv->live && !av->live)\n mark_live_avar(av);\n }\n }\n }\n }\n }\n }\n}\n\nstatic bool\nforward_live(Var *v, int dist = 2) {\n if (dist < 0)\n return false;\n form_AVarMapElem(x, v->avars)\n forv_AVar(av, x->value->forward) if (av) {\n if (av->live)\n return true;\n if (forward_live(av->var, dist-1))\n return true;\n }\n return false;\n}\n\nstatic void \nmark_live_pnodes(FA *fa) {\n forv_Fun(f, fa->funs) {\n forv_PNode(p, f->fa_all_PNodes) {\n if (!p->live) {\n forv_Var(v, p->lvals)\n if (v->live)\n goto Live;\n if (p->code)\n switch (p->code->kind) {\n default: break;\n case Code_LABEL:\n if (p->cfg_pred.n != 1)\n forv_PNode(x, p->cfg_pred)\n if (x->live)\n goto Live;\n break;\n case Code_GOTO:\n if (p->cfg_succ[0]->cfg_pred.n != 1)\n forv_PNode(x, f->fa_all_PNodes) \/\/ potentially expensive\n if (x->live || x == f->exit)\n if (p->dom->is_dominated_by(x->dom)) \n goto Live;\n break;\n case Code_SEND:\n if (p->prim) {\n switch (p->prim->index) { \/\/ handle side effects\n default: break;\n case P_prim_reply:\n forv_Var(v, f->rets)\n if (v->live) \n goto Live;\n break;\n case P_prim_setter: {\n if (forward_live(p->tvals.v[0]))\n goto Live;\n break;\n }\n case P_prim_set_index_object: {\n if (forward_live(p->tvals.v[0]))\n goto Live;\n break;\n }\n }\n } else {\n Vec<Fun *> *calls = f->calls.get(p);\n if (calls)\n forv_Fun(x, *calls)\n if (x->live)\n goto Live;\n }\n break;\n case Code_IF:\n forv_PNode(x, f->fa_all_PNodes) \/\/ potentially expensive\n if (x->live)\n if (x->dom->is_dominated_by(p->dom))\n forv_PNode(s, p->cfg_succ)\n if (!x->dom->is_dominated_by(s->dom))\n goto Live;\n break;\n }\n continue; \/\/ handle fall through non-live\n Live:\n p->live = 1;\n f->live = 1;\n mark_live_again = 1;\n } else\n f->live = 1;\n }\n }\n}\n\nstatic void \nmark_initial_dead_and_alive(FA *fa, int init = 0) {\n forv_Fun(f, fa->funs) {\n f->live = init;\n forv_Var(v, f->fa_all_Vars) {\n v->live = init;\n for (int i = 0; i < v->avars.n; i++) \n if (v->avars[i].key)\n v->avars[i].value->live = false;\n if (v->type) { \/\/ mark all instance variables not live\n forv_CreationSet(cs, v->type->creators) if (cs) {\n forv_AVar(iv, cs->vars)\n iv->var->live = init;\n }\n }\n }\n forv_PNode(p, f->fa_all_PNodes) {\n p->live = init;\n if (p->code && p->code->kind == Code_SEND && p->prim && p->prim->index == P_prim_primitive) {\n cchar *name = p->code->rvals[1]->name;\n RegisteredPrim *rp = prim_get(name);\n if (rp && rp->is_visible)\n p->live = 1;\n }\n }\n }\n}\n\nvoid\nmark_live_types(FA *fa) {\n forv_CreationSet(cs, fa->css)\n cs->type->type_live = 0;\n forv_CreationSet(cs, fa->css)\n if (cs->type && cs->type->creators.n) {\n forv_CreationSet(x, cs->type->creators) {\n forv_AVar(av, x->defs) if (av)\n if (av->var->live && !cs->type->type_live)\n cs->type->type_live = 1;\n }\n }\n}\n\nint \nmark_live_code(FA *fa) {\n mark_initial_dead_and_alive(fa);\n do {\n mark_live_again = 0;\n mark_live_avars(fa);\n mark_live_pnodes(fa);\n } while (mark_live_again);\n mark_live_types(fa);\n if (ifa_verbose > 2)\n print_dead(fa);\n return 0;\n}\n\nvoid\nmark_live_funs(FA *fa) {\n forv_Fun(f, fa->funs)\n f->live = 0;\n if1->top->fun->live = 1;\n int changed = 1;\n while (changed) {\n changed = 0;\n forv_Fun(f, fa->funs) {\n if (f->live) {\n forv_PNode(p, f->fa_all_PNodes)\n if (p->live) {\n Vec<Fun *> *fns = f->calls.get(p);\n if (fns)\n forv_Fun(x, *fns) if (!x->live) {\n x->live = 1;\n changed = 1;\n }\n }\n }\n }\n }\n}\n\n\/*\n INCOMPLETE VAR BASED VERSION\n*\/\n\n#if 0\nstatic void \nmark_live_vars(FA *fa) {\n forv_Fun(f, fa->funs) {\n forv_PNode(p, f->fa_all_PNodes) {\n \/\/ if a pnode is live, it's inputs (rvals) must be live\n if (p->live) {\n forv_Var(v, p->rvals) {\n if (!v->live) {\n v->live = 1;\n mark_live_again = 1;\n }\n }\n }\n forv_Var(v, f->fa_all_Vars) {\n \/\/ if an instance variable is live, then the containing object must be live\n if (!v->live && v->type)\n forv_CreationSet(cs, v->type->creators) if (cs) {\n forv_AVar(iv, cs->vars) {\n if (iv->var->live) {\n v->live = 1;\n mark_live_again = 1;\n }\n }\n }\n }\n }\n }\n}\n\nstatic void\nmark_types_live(FA *fa) {\n forv_CreationSet(cs, fa->css)\n if (cs->type && cs->type->creators.n) {\n forv_CreationSet(x, cs->type->creators) {\n forv_AVar(av, x->defs) if (av)\n if (av->var->live)\n cs->type->type_live = 1;\n }\n }\n}\n\nstatic void \nmark_initial_dead_and_alive(FA *fa, int init = 0) {\n forv_Fun(f, fa->funs) {\n f->live = init;\n forv_Var(v, f->fa_all_Vars) {\n v->live = INIT;\n if (v->type) { \/\/ mark all instance variables not live\n forv_CreationSet(cs, v->type->creators) if (cs) {\n forv_AVar(iv, cs->vars)\n iv->var->live = init;\n }\n }\n }\n forv_PNode(p, f->fa_all_PNodes) {\n p->live = init;\n if (p->code && p->code->kind == Code_SEND && p->prim && p->prim->index == P_prim_primitive) {\n cchar *name = p->code->rvals[1]->name;\n RegisteredPrim *rp = pdb->fa->primitive_transfer_functions.get(name);\n if (rp && rp->is_visible)\n p->live = 1;\n }\n }\n }\n forv_CreationSet(cs, fa->css)\n cs->type->type_live = init;\n}\n\nint \nmark_dead_code(FA *fa) {\n mark_initial_dead_and_alive(fa);\n do {\n mark_live_again = 0;\n mark_live_vars(fa);\n mark_live_pnodes(fa);\n } while (mark_live_again);\n mark_types_live(fa);\n if (ifa_verbose > 2)\n print_dead(fa);\n return 0;\n}\n#endif\n<commit_msg>interm<commit_after>\/* -*-Mode: c++;-*-\n Copyright (c) 2004-2010 John Plevyak, All Rights Reserved\n*\/\n#include \"ifadefs.h\"\n#include \"fail.h\"\n#include \"ifa.h\"\n#include \"pattern.h\"\n#include \"prim.h\"\n#include \"if1.h\"\n#include \"builtin.h\"\n#include \"pdb.h\"\n#include \"fun.h\"\n#include \"pnode.h\"\n#include \"fa.h\"\n#include \"ast.h\"\n#include \"var.h\"\n#include \"dom.h\"\n\n\/*\n It is intended that this file contain 2 implementations, \n one based on the AVars and another based on Vars (post concretize_program()).\n Only the former is currently extent.\n*\/\n\nstatic int mark_live_again = 0;\n\nstatic void\nprint_dead(FA *fa) {\n int ndead_pnodes = 0, ndead_vars = 0;\n int nlive_pnodes = 0, nlive_vars = 0;\n forv_Fun(f, fa->funs) {\n forv_PNode(p, f->fa_all_PNodes)\n if (!p->live) {\n ndead_pnodes++;\n printf(\"PNode %d DEAD\\n\", p->id);\n } else nlive_pnodes++;\n forv_Var(v, f->fa_all_Vars)\n if (!v->live) {\n ndead_vars++;\n printf(\"Var %d:%d %s DEAD\\n\", v->sym->id, v->id, v->sym->name ? v->sym->name : \"\");\n } else nlive_vars++;\n }\n printf(\"%d PNodes DEAD\\n\", ndead_pnodes);\n printf(\"%d Vars DEAD\\n\", ndead_vars);\n printf(\"%d PNodes LIVE\\n\", nlive_pnodes);\n printf(\"%d Vars LIVE\\n\", nlive_vars);\n}\n\nstatic void\nmark_live_avar(AVar *av) {\n if (av->var->sym->is_fake)\n return;\n av->live = 1;\n av->var->live = 1;\n mark_live_again = 1;\n if (av->var->def)\n av->var->def->live = 1;\n forv_AVar(aav, av->backward) if (aav) {\n if (!aav->live) {\n Vec<Sym *> consts;\n if (constant_info(aav->var, consts) != 1)\n mark_live_avar(aav);\n }\n }\n}\n\nstatic void \nmark_live_avars(FA *fa) {\n forv_Fun(f, fa->funs) {\n forv_PNode(p, f->fa_all_PNodes) {\n \/\/ if a pnode is live, and it is not a function call, it's inputs (rvals) must be live\n if (p->live && !f->calls.get(p)) {\n forv_Var(v, p->rvals) {\n Vec<Sym *> consts;\n if (constant_info(v, consts) != 1) {\n form_AVarMapElem(x, v->avars) {\n AVar *av = x->value;\n if (!av->live) \n mark_live_avar(av);\n }\n }\n }\n }\n }\n forv_Var(v, f->fa_all_Vars) {\n form_AVarMapElem(x, v->avars) {\n \/\/ if an instance variable is live, then the containing object must be live\n AVar *av = x->value;\n if (!av->live) {\n forv_CreationSet(cs, *av->out) if (cs) {\n forv_AVar(iv, cs->vars) {\n if (iv->live && !av->live)\n mark_live_avar(av);\n }\n }\n }\n }\n }\n }\n}\n\nstatic bool\nforward_live(Var *v, int dist = 2) {\n if (dist < 0)\n return false;\n form_AVarMapElem(x, v->avars)\n forv_AVar(av, x->value->forward) if (av) {\n if (av->live)\n return true;\n if (forward_live(av->var, dist-1))\n return true;\n }\n return false;\n}\n\nstatic void \nmark_live_pnodes(FA *fa) {\n forv_Fun(f, fa->funs) {\n forv_PNode(p, f->fa_all_PNodes) {\n if (!p->live) {\n forv_Var(v, p->lvals)\n if (v->live)\n goto Live;\n if (p->code)\n switch (p->code->kind) {\n default: break;\n case Code_LABEL:\n if (p->cfg_pred.n != 1)\n forv_PNode(x, p->cfg_pred)\n if (x->live)\n goto Live;\n break;\n case Code_GOTO:\n if (p->cfg_succ[0]->cfg_pred.n != 1)\n forv_PNode(x, f->fa_all_PNodes) \/\/ potentially expensive\n if (x->live || x == f->exit)\n if (p->dom->is_dominated_by(x->dom)) \n goto Live;\n break;\n case Code_SEND:\n if (p->prim) {\n switch (p->prim->index) { \/\/ handle side effects\n default: break;\n case P_prim_reply:\n forv_Var(v, f->rets)\n if (v->live) \n goto Live;\n break;\n case P_prim_setter: {\n if (forward_live(p->tvals.v[0]))\n goto Live;\n break;\n }\n case P_prim_set_index_object: {\n if (forward_live(p->tvals.v[0]))\n goto Live;\n break;\n }\n }\n } else {\n Vec<Fun *> *calls = f->calls.get(p);\n if (calls)\n forv_Fun(x, *calls)\n if (x->live)\n goto Live;\n }\n break;\n case Code_IF:\n forv_PNode(x, f->fa_all_PNodes) \/\/ potentially expensive\n if (x->live)\n if (x->dom->is_dominated_by(p->dom))\n forv_PNode(s, p->cfg_succ)\n if (!x->dom->is_dominated_by(s->dom))\n goto Live;\n break;\n }\n continue; \/\/ handle fall through non-live\n Live:\n p->live = 1;\n f->live = 1;\n mark_live_again = 1;\n } else\n f->live = 1;\n }\n }\n}\n\nstatic void \nmark_initial_dead_and_alive(FA *fa, int init = 0) {\n forv_Fun(f, fa->funs) {\n f->live = init;\n forv_Var(v, f->fa_all_Vars) {\n v->live = init;\n for (int i = 0; i < v->avars.n; i++) \n if (v->avars[i].key)\n v->avars[i].value->live = false;\n if (v->type) { \/\/ mark all instance variables not live\n forv_CreationSet(cs, v->type->creators) if (cs) {\n forv_AVar(iv, cs->vars)\n iv->var->live = init;\n }\n }\n }\n forv_PNode(p, f->fa_all_PNodes) {\n p->live = init;\n if (p->code && p->code->kind == Code_SEND && p->prim && p->prim->index == P_prim_primitive) {\n cchar *name = p->code->rvals[1]->name;\n RegisteredPrim *rp = prim_get(name);\n if (rp && rp->is_visible)\n p->live = 1;\n }\n }\n }\n}\n\nvoid\nmark_live_types(FA *fa) {\n forv_CreationSet(cs, fa->css)\n cs->type->type_live = 0;\n forv_CreationSet(cs, fa->css)\n if (cs->type && cs->type->creators.n) {\n forv_CreationSet(x, cs->type->creators) {\n forv_AVar(av, x->defs) if (av)\n if (av->var->live && !cs->type->type_live)\n cs->type->type_live = 1;\n }\n }\n}\n\nint \nmark_live_code(FA *fa) {\n mark_initial_dead_and_alive(fa);\n do {\n mark_live_again = 0;\n mark_live_avars(fa);\n mark_live_pnodes(fa);\n } while (mark_live_again);\n mark_live_types(fa);\n if (ifa_verbose > 2)\n print_dead(fa);\n return 0;\n}\n\nvoid\nmark_live_funs(FA *fa) {\n forv_Fun(f, fa->funs)\n f->live = 0;\n if1->top->fun->live = 1;\n int changed = 1;\n while (changed) {\n changed = 0;\n forv_Fun(f, fa->funs) {\n if (f->live) {\n forv_PNode(p, f->fa_all_PNodes)\n if (p->live) {\n Vec<Fun *> *fns = f->calls.get(p);\n if (fns)\n forv_Fun(x, *fns) if (!x->live) {\n x->live = 1;\n changed = 1;\n }\n }\n }\n }\n }\n}\n\n\/*\n INCOMPLETE VAR BASED VERSION\n*\/\n\n#if 0\nstatic void \nmark_live_vars(FA *fa) {\n forv_Fun(f, fa->funs) {\n forv_PNode(p, f->fa_all_PNodes) {\n \/\/ if a pnode is live, it's inputs (rvals) must be live\n if (p->live) {\n forv_Var(v, p->rvals) {\n if (!v->live) {\n v->live = 1;\n mark_live_again = 1;\n }\n }\n }\n forv_Var(v, f->fa_all_Vars) {\n \/\/ if an instance variable is live, then the containing object must be live\n if (!v->live && v->type)\n forv_CreationSet(cs, v->type->creators) if (cs) {\n forv_AVar(iv, cs->vars) {\n if (iv->var->live) {\n v->live = 1;\n mark_live_again = 1;\n }\n }\n }\n }\n }\n }\n}\n\nstatic void\nmark_types_live(FA *fa) {\n forv_CreationSet(cs, fa->css)\n if (cs->type && cs->type->creators.n) {\n forv_CreationSet(x, cs->type->creators) {\n forv_AVar(av, x->defs) if (av)\n if (av->var->live)\n cs->type->type_live = 1;\n }\n }\n}\n\nstatic void \nmark_initial_dead_and_alive(FA *fa, int init = 0) {\n forv_Fun(f, fa->funs) {\n f->live = init;\n forv_Var(v, f->fa_all_Vars) {\n v->live = INIT;\n if (v->type) { \/\/ mark all instance variables not live\n forv_CreationSet(cs, v->type->creators) if (cs) {\n forv_AVar(iv, cs->vars)\n iv->var->live = init;\n }\n }\n }\n forv_PNode(p, f->fa_all_PNodes) {\n p->live = init;\n if (p->code && p->code->kind == Code_SEND && p->prim && p->prim->index == P_prim_primitive) {\n cchar *name = p->code->rvals[1]->name;\n RegisteredPrim *rp = pdb->fa->primitive_transfer_functions.get(name);\n if (rp && rp->is_visible)\n p->live = 1;\n }\n }\n }\n forv_CreationSet(cs, fa->css)\n cs->type->type_live = init;\n}\n\nint \nmark_dead_code(FA *fa) {\n mark_initial_dead_and_alive(fa);\n do {\n mark_live_again = 0;\n mark_live_vars(fa);\n mark_live_pnodes(fa);\n } while (mark_live_again);\n mark_types_live(fa);\n if (ifa_verbose > 2)\n print_dead(fa);\n return 0;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 1998-1999 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * 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. 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, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#ifdef HAVE_CVS_IDENT\n#ident \"$Id: eval.cc,v 1.40 2006\/04\/10 00:37:42 steve Exp $\"\n#endif\n\n# include \"config.h\"\n\n# include <iostream>\n\n# include \"PExpr.h\"\n# include \"netlist.h\"\n# include \"netmisc.h\"\n# include \"compiler.h\"\n\nverinum* PExpr::eval_const(const Design*, NetScope*) const\n{\n return 0;\n}\n\nverinum* PEBinary::eval_const(const Design*des, NetScope*scope) const\n{\n verinum*l = left_->eval_const(des, scope);\n if (l == 0) return 0;\n verinum*r = right_->eval_const(des, scope);\n if (r == 0) {\n\t delete l;\n\t return 0;\n }\n verinum*res;\n\n switch (op_) {\n\t case '+': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t res = new verinum(*l + *r);\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '-': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t res = new verinum(*l - *r);\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '*': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t res = new verinum(*l * *r);\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '\/': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t long lv = l->as_long();\n\t\t long rv = r->as_long();\n\t\t res = new verinum(lv \/ rv, l->len());\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '%': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t long lv = l->as_long();\n\t\t long rv = r->as_long();\n\t\t res = new verinum(lv % rv, l->len());\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '>': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t long lv = l->as_long();\n\t\t long rv = r->as_long();\n\t\t res = new verinum(lv > rv, l->len());\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '<': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t long lv = l->as_long();\n\t\t long rv = r->as_long();\n\t\t res = new verinum(lv < rv, l->len());\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case 'l': { \/\/ left shift (<<)\n\t\tassert(r->is_defined());\n\t\tunsigned long rv = r->as_ulong();\n\t\tres = new verinum(verinum::V0, l->len());\n\t\tif (rv < res->len()) {\n\t\t unsigned cnt = res->len() - rv;\n\t\t for (unsigned idx = 0 ; idx < cnt ; idx += 1)\n\t\t\t res->set(idx+rv, l->get(idx));\n\t\t}\n\t\tbreak;\n\t }\n\t case 'r': { \/\/ right shift (>>)\n\t\tassert(r->is_defined());\n\t\tunsigned long rv = r->as_ulong();\n\t\tres = new verinum(verinum::V0, l->len());\n\t\tif (rv < res->len()) {\n\t\t unsigned cnt = res->len() - rv;\n\t\t for (unsigned idx = 0 ; idx < cnt ; idx += 1)\n\t\t\t res->set(idx, l->get(idx+rv));\n\t\t}\n\t\tbreak;\n\t }\n\n\t default:\n\t delete l;\n\t delete r;\n\t return 0;\n }\n\n delete l;\n delete r;\n return res;\n}\nverinum* PEConcat::eval_const(const Design*des, NetScope*scope) const\n{\n verinum*accum = parms_[0]->eval_const(des, scope);\n if (accum == 0)\n\t return 0;\n\n for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) {\n\t verinum*tmp = parms_[idx]->eval_const(des, scope);\n\t assert(tmp);\n\n\t *accum = concat(*accum, *tmp);\n\t delete tmp;\n }\n\n return accum;\n}\n\n\n\/*\n * Evaluate an identifier as a constant expression. This is only\n * possible if the identifier is that of a parameter.\n *\/\nverinum* PEIdent::eval_const(const Design*des, NetScope*scope) const\n{\n assert(scope);\n NetNet*net;\n NetMemory*mem;\n NetEvent*eve;\n const NetExpr*expr;\n\n\t\/\/ Handle the special case that this ident is a genvar\n\t\/\/ variable name. In that case, the genvar meaning preempts\n\t\/\/ everything and we just return that value immediately.\n if (scope->genvar_tmp\n\t && strcmp(path_.peek_tail_name(),scope->genvar_tmp) == 0) {\n\t return new verinum(scope->genvar_tmp_val);\n }\n\n NetScope*found_in = symbol_search(des, scope, path_,\n\t\t\t\t\tnet, mem, expr, eve);\n\n if (expr == 0)\n\t return 0;\n\n const NetEConst*eval = dynamic_cast<const NetEConst*>(expr);\n if (eval == 0) {\n\t cerr << get_line() << \": internal error: Unable to evaluate \"\n\t\t << \"constant expression (parameter=\" << path_\n\t\t << \"): \" << *expr << endl;\n\t return 0;\n }\n\n assert(eval);\n\n if (msb_ || lsb_)\n\t return 0;\n\n\n return new verinum(eval->value());\n}\n\nverinum* PEFNumber::eval_const(const Design*, NetScope*) const\n{\n long val = value_->as_long();\n return new verinum(val);\n}\n\nverinum* PENumber::eval_const(const Design*, NetScope*) const\n{\n return new verinum(value());\n}\n\nverinum* PEString::eval_const(const Design*, NetScope*) const\n{\n return new verinum(string(text_));\n}\n\nverinum* PETernary::eval_const(const Design*des, NetScope*scope) const\n{\n verinum*test = expr_->eval_const(des, scope);\n if (test == 0)\n\t return 0;\n\n verinum::V bit = test->get(0);\n delete test;\n switch (bit) {\n\t case verinum::V0:\n\t return fal_->eval_const(des, scope);\n\t case verinum::V1:\n\t return tru_->eval_const(des, scope);\n\t default:\n\t return 0;\n\t \/\/ XXXX It is possible to handle this case if both fal_\n\t \/\/ and tru_ are constant. Someday...\n }\n}\n\nverinum* PEUnary::eval_const(const Design*des, NetScope*scope) const\n{\n verinum*val = expr_->eval_const(des, scope);\n if (val == 0)\n\t return 0;\n\n switch (op_) {\n\t case '+':\n\t return val;\n\n\t case '-': {\n\t\t \/* We need to expand the value a bit if we are\n\t\t taking the 2's complement so that we are\n\t\t guaranteed to not overflow. *\/\n\t\tverinum tmp (0UL, val->len()+1);\n\t\tfor (unsigned idx = 0 ; idx < val->len() ; idx += 1)\n\t\t tmp.set(idx, val->get(idx));\n\n\t\t*val = v_not(tmp) + verinum(verinum::V1, 1);\n\t\tval->has_sign(true);\n\t\treturn val;\n\t }\n\n }\n\t delete val;\n return 0;\n}\n\n\n\/*\n * $Log: eval.cc,v $\n * Revision 1.40 2006\/04\/10 00:37:42 steve\n * Add support for generate loops w\/ wires and gates.\n *\n * Revision 1.39 2005\/12\/07 04:04:23 steve\n * Allow constant concat expressions.\n *\n * Revision 1.38 2005\/11\/27 17:01:57 steve\n * Fix for stubborn compiler.\n *\n * Revision 1.37 2005\/11\/27 05:56:20 steve\n * Handle bit select of parameter with ranges.\n *\n * Revision 1.36 2003\/06\/21 01:21:43 steve\n * Harmless fixup of warnings.\n *\n * Revision 1.35 2003\/04\/14 03:40:21 steve\n * Make some effort to preserve bits while\n * operating on constant values.\n *\n * Revision 1.34 2003\/03\/26 06:16:18 steve\n * Evaluate > and < in constant expressions.\n *\n * Revision 1.33 2003\/03\/10 23:40:53 steve\n * Keep parameter constants for the ivl_target API.\n *\n * Revision 1.32 2002\/10\/19 22:59:49 steve\n * Redo the parameter vector support to allow\n * parameter names in range expressions.\n *\n * Revision 1.31 2002\/10\/13 05:01:07 steve\n * More verbose eval_const assert message.\n *\n * Revision 1.30 2002\/08\/12 01:34:59 steve\n * conditional ident string using autoconfig.\n *\n * Revision 1.29 2002\/06\/07 02:57:54 steve\n * Simply give up on constants with indices.\n *\n * Revision 1.28 2002\/06\/06 18:57:04 steve\n * Better error for identifier index eval.\n *\n * Revision 1.27 2002\/05\/23 03:08:51 steve\n * Add language support for Verilog-2001 attribute\n * syntax. Hook this support into existing $attribute\n * handling, and add number and void value types.\n *\n * Add to the ivl_target API new functions for access\n * of complex attributes attached to gates.\n *\n * Revision 1.26 2001\/12\/29 22:10:10 steve\n * constant eval of arithmetic with x and z.\n *\n * Revision 1.25 2001\/12\/29 00:43:55 steve\n * Evaluate constant right shifts.\n *\n * Revision 1.24 2001\/12\/03 04:47:15 steve\n * Parser and pform use hierarchical names as hname_t\n * objects instead of encoded strings.\n *\n * Revision 1.23 2001\/11\/07 04:01:59 steve\n * eval_const uses scope instead of a string path.\n *\n * Revision 1.22 2001\/11\/06 06:11:55 steve\n * Support more real arithmetic in delay constants.\n *\n * Revision 1.21 2001\/07\/25 03:10:49 steve\n * Create a config.h.in file to hold all the config\n * junk, and support gcc 3.0. (Stephan Boettcher)\n *\n * Revision 1.20 2001\/02\/09 02:49:59 steve\n * Be more clear about scope of failure.\n *\n * Revision 1.19 2001\/01\/27 05:41:48 steve\n * Fix sign extension of evaluated constants. (PR#91)\n *\n * Revision 1.18 2001\/01\/14 23:04:56 steve\n * Generalize the evaluation of floating point delays, and\n * get it working with delay assignment statements.\n *\n * Allow parameters to be referenced by hierarchical name.\n *\n * Revision 1.17 2001\/01\/04 04:47:51 steve\n * Add support for << is signal indices.\n *\n * Revision 1.16 2000\/12\/10 22:01:36 steve\n * Support decimal constants in behavioral delays.\n *\n * Revision 1.15 2000\/09\/07 22:38:13 steve\n * Support unary + and - in constants.\n *\/\n\n<commit_msg> Error message if concat expression cannot evaluate.<commit_after>\/*\n * Copyright (c) 1998-1999 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * 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. 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, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#ifdef HAVE_CVS_IDENT\n#ident \"$Id: eval.cc,v 1.41 2006\/05\/17 16:49:30 steve Exp $\"\n#endif\n\n# include \"config.h\"\n\n# include <iostream>\n\n# include \"PExpr.h\"\n# include \"netlist.h\"\n# include \"netmisc.h\"\n# include \"compiler.h\"\n\nverinum* PExpr::eval_const(const Design*, NetScope*) const\n{\n return 0;\n}\n\nverinum* PEBinary::eval_const(const Design*des, NetScope*scope) const\n{\n verinum*l = left_->eval_const(des, scope);\n if (l == 0) return 0;\n verinum*r = right_->eval_const(des, scope);\n if (r == 0) {\n\t delete l;\n\t return 0;\n }\n verinum*res;\n\n switch (op_) {\n\t case '+': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t res = new verinum(*l + *r);\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '-': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t res = new verinum(*l - *r);\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '*': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t res = new verinum(*l * *r);\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '\/': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t long lv = l->as_long();\n\t\t long rv = r->as_long();\n\t\t res = new verinum(lv \/ rv, l->len());\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '%': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t long lv = l->as_long();\n\t\t long rv = r->as_long();\n\t\t res = new verinum(lv % rv, l->len());\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '>': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t long lv = l->as_long();\n\t\t long rv = r->as_long();\n\t\t res = new verinum(lv > rv, l->len());\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case '<': {\n\t\tif (l->is_defined() && r->is_defined()) {\n\t\t long lv = l->as_long();\n\t\t long rv = r->as_long();\n\t\t res = new verinum(lv < rv, l->len());\n\t\t} else {\n\t\t res = new verinum(verinum::Vx, l->len());\n\t\t}\n\t\tbreak;\n\t }\n\t case 'l': { \/\/ left shift (<<)\n\t\tassert(r->is_defined());\n\t\tunsigned long rv = r->as_ulong();\n\t\tres = new verinum(verinum::V0, l->len());\n\t\tif (rv < res->len()) {\n\t\t unsigned cnt = res->len() - rv;\n\t\t for (unsigned idx = 0 ; idx < cnt ; idx += 1)\n\t\t\t res->set(idx+rv, l->get(idx));\n\t\t}\n\t\tbreak;\n\t }\n\t case 'r': { \/\/ right shift (>>)\n\t\tassert(r->is_defined());\n\t\tunsigned long rv = r->as_ulong();\n\t\tres = new verinum(verinum::V0, l->len());\n\t\tif (rv < res->len()) {\n\t\t unsigned cnt = res->len() - rv;\n\t\t for (unsigned idx = 0 ; idx < cnt ; idx += 1)\n\t\t\t res->set(idx, l->get(idx+rv));\n\t\t}\n\t\tbreak;\n\t }\n\n\t default:\n\t delete l;\n\t delete r;\n\t return 0;\n }\n\n delete l;\n delete r;\n return res;\n}\nverinum* PEConcat::eval_const(const Design*des, NetScope*scope) const\n{\n verinum*accum = parms_[0]->eval_const(des, scope);\n if (accum == 0)\n\t return 0;\n\n for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) {\n\n\t verinum*tmp = parms_[idx]->eval_const(des, scope);\n\t if (tmp == 0) {\n\t\t cerr << get_line() << \": error: \"\n\t\t << \"Unable to evaluate constant expression in concat: \"\n\t\t << *parms_[idx] << endl;\n\t\t delete accum;\n\t\t return 0;\n\t }\n\t assert(tmp);\n\n\t *accum = concat(*accum, *tmp);\n\t delete tmp;\n }\n\n return accum;\n}\n\n\n\/*\n * Evaluate an identifier as a constant expression. This is only\n * possible if the identifier is that of a parameter.\n *\/\nverinum* PEIdent::eval_const(const Design*des, NetScope*scope) const\n{\n assert(scope);\n NetNet*net;\n NetMemory*mem;\n NetEvent*eve;\n const NetExpr*expr;\n\n\t\/\/ Handle the special case that this ident is a genvar\n\t\/\/ variable name. In that case, the genvar meaning preempts\n\t\/\/ everything and we just return that value immediately.\n if (scope->genvar_tmp\n\t && strcmp(path_.peek_tail_name(),scope->genvar_tmp) == 0) {\n\t return new verinum(scope->genvar_tmp_val);\n }\n\n NetScope*found_in = symbol_search(des, scope, path_,\n\t\t\t\t\tnet, mem, expr, eve);\n\n if (expr == 0)\n\t return 0;\n\n const NetEConst*eval = dynamic_cast<const NetEConst*>(expr);\n if (eval == 0) {\n\t cerr << get_line() << \": internal error: Unable to evaluate \"\n\t\t << \"constant expression (parameter=\" << path_\n\t\t << \"): \" << *expr << endl;\n\t return 0;\n }\n\n assert(eval);\n\n if (msb_ || lsb_)\n\t return 0;\n\n\n return new verinum(eval->value());\n}\n\nverinum* PEFNumber::eval_const(const Design*, NetScope*) const\n{\n long val = value_->as_long();\n return new verinum(val);\n}\n\nverinum* PENumber::eval_const(const Design*, NetScope*) const\n{\n return new verinum(value());\n}\n\nverinum* PEString::eval_const(const Design*, NetScope*) const\n{\n return new verinum(string(text_));\n}\n\nverinum* PETernary::eval_const(const Design*des, NetScope*scope) const\n{\n verinum*test = expr_->eval_const(des, scope);\n if (test == 0)\n\t return 0;\n\n verinum::V bit = test->get(0);\n delete test;\n switch (bit) {\n\t case verinum::V0:\n\t return fal_->eval_const(des, scope);\n\t case verinum::V1:\n\t return tru_->eval_const(des, scope);\n\t default:\n\t return 0;\n\t \/\/ XXXX It is possible to handle this case if both fal_\n\t \/\/ and tru_ are constant. Someday...\n }\n}\n\nverinum* PEUnary::eval_const(const Design*des, NetScope*scope) const\n{\n verinum*val = expr_->eval_const(des, scope);\n if (val == 0)\n\t return 0;\n\n switch (op_) {\n\t case '+':\n\t return val;\n\n\t case '-': {\n\t\t \/* We need to expand the value a bit if we are\n\t\t taking the 2's complement so that we are\n\t\t guaranteed to not overflow. *\/\n\t\tverinum tmp (0UL, val->len()+1);\n\t\tfor (unsigned idx = 0 ; idx < val->len() ; idx += 1)\n\t\t tmp.set(idx, val->get(idx));\n\n\t\t*val = v_not(tmp) + verinum(verinum::V1, 1);\n\t\tval->has_sign(true);\n\t\treturn val;\n\t }\n\n }\n\t delete val;\n return 0;\n}\n\n\n\/*\n * $Log: eval.cc,v $\n * Revision 1.41 2006\/05\/17 16:49:30 steve\n * Error message if concat expression cannot evaluate.\n *\n * Revision 1.40 2006\/04\/10 00:37:42 steve\n * Add support for generate loops w\/ wires and gates.\n *\n * Revision 1.39 2005\/12\/07 04:04:23 steve\n * Allow constant concat expressions.\n *\n * Revision 1.38 2005\/11\/27 17:01:57 steve\n * Fix for stubborn compiler.\n *\n * Revision 1.37 2005\/11\/27 05:56:20 steve\n * Handle bit select of parameter with ranges.\n *\n * Revision 1.36 2003\/06\/21 01:21:43 steve\n * Harmless fixup of warnings.\n *\n * Revision 1.35 2003\/04\/14 03:40:21 steve\n * Make some effort to preserve bits while\n * operating on constant values.\n *\n * Revision 1.34 2003\/03\/26 06:16:18 steve\n * Evaluate > and < in constant expressions.\n *\n * Revision 1.33 2003\/03\/10 23:40:53 steve\n * Keep parameter constants for the ivl_target API.\n *\n * Revision 1.32 2002\/10\/19 22:59:49 steve\n * Redo the parameter vector support to allow\n * parameter names in range expressions.\n *\n * Revision 1.31 2002\/10\/13 05:01:07 steve\n * More verbose eval_const assert message.\n *\n * Revision 1.30 2002\/08\/12 01:34:59 steve\n * conditional ident string using autoconfig.\n *\n * Revision 1.29 2002\/06\/07 02:57:54 steve\n * Simply give up on constants with indices.\n *\n * Revision 1.28 2002\/06\/06 18:57:04 steve\n * Better error for identifier index eval.\n *\n * Revision 1.27 2002\/05\/23 03:08:51 steve\n * Add language support for Verilog-2001 attribute\n * syntax. Hook this support into existing $attribute\n * handling, and add number and void value types.\n *\n * Add to the ivl_target API new functions for access\n * of complex attributes attached to gates.\n *\n * Revision 1.26 2001\/12\/29 22:10:10 steve\n * constant eval of arithmetic with x and z.\n *\n * Revision 1.25 2001\/12\/29 00:43:55 steve\n * Evaluate constant right shifts.\n *\n * Revision 1.24 2001\/12\/03 04:47:15 steve\n * Parser and pform use hierarchical names as hname_t\n * objects instead of encoded strings.\n *\n * Revision 1.23 2001\/11\/07 04:01:59 steve\n * eval_const uses scope instead of a string path.\n *\n * Revision 1.22 2001\/11\/06 06:11:55 steve\n * Support more real arithmetic in delay constants.\n *\n * Revision 1.21 2001\/07\/25 03:10:49 steve\n * Create a config.h.in file to hold all the config\n * junk, and support gcc 3.0. (Stephan Boettcher)\n *\n * Revision 1.20 2001\/02\/09 02:49:59 steve\n * Be more clear about scope of failure.\n *\n * Revision 1.19 2001\/01\/27 05:41:48 steve\n * Fix sign extension of evaluated constants. (PR#91)\n *\n * Revision 1.18 2001\/01\/14 23:04:56 steve\n * Generalize the evaluation of floating point delays, and\n * get it working with delay assignment statements.\n *\n * Allow parameters to be referenced by hierarchical name.\n *\n * Revision 1.17 2001\/01\/04 04:47:51 steve\n * Add support for << is signal indices.\n *\n * Revision 1.16 2000\/12\/10 22:01:36 steve\n * Support decimal constants in behavioral delays.\n *\n * Revision 1.15 2000\/09\/07 22:38:13 steve\n * Support unary + and - in constants.\n *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016-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#include \"DedupBlocksPass.h\"\n\n#include <boost\/optional.hpp>\n#include <iterator>\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"ControlFlow.h\"\n#include \"DexClass.h\"\n#include \"DexOutput.h\"\n#include \"DexUtil.h\"\n#include \"IRCode.h\"\n#include \"Transform.h\"\n#include \"Walkers.h\"\n\n\/*\n * This pass removes blocks that are duplicates in a method.\n *\n * If a method has multiple blocks with the same code and the same successors,\n * delete all but one of the blocks. Naming one of them the canonical block.\n *\n * Then, reroute all the predecessors of all the blocks to that canonical block.\n *\/\n\nnamespace {\n\nclass DedupBlocksImpl {\n public:\n DedupBlocksImpl(const std::vector<DexClass*>& scope,\n PassManager& mgr,\n const DedupBlocksPass::Config& config)\n : m_scope(scope), m_mgr(mgr), m_config(config) {}\n\n void run() {\n walk_methods(m_scope, [this](DexMethod* method) {\n if (m_config.method_black_list.count(method) != 0) {\n return;\n }\n\n IRCode* code = method->get_code();\n if (code == nullptr) {\n return;\n }\n code->build_cfg();\n\n duplicates_t dups = collect_duplicates(code);\n if (dups.size() > 0) {\n record_stats(dups);\n deduplicate(dups, method);\n }\n });\n report_stats();\n }\n\n private:\n using hash_t = uint64_t;\n using duplicates_t = std::unordered_map<hash_t, std::unordered_set<Block*>>;\n const char* METRIC_BLOCKS_REMOVED = \"blocks_removed\";\n const char* METRIC_ELIGIBLE_BLOCKS = \"eligible_blocks\";\n const std::vector<DexClass*>& m_scope;\n PassManager& m_mgr;\n const DedupBlocksPass::Config& m_config;\n\n \/\/ map from block size to number of blocks with that size\n std::unordered_map<size_t, size_t> m_dup_sizes;\n\n \/\/ Find blocks with the same exact code\n duplicates_t collect_duplicates(IRCode* code) {\n const auto& blocks = code->cfg().blocks();\n std::unordered_map<hash_t, std::unordered_set<Block*>> duplicates;\n\n int num_eligible_blocks = 0;\n for (Block* block : blocks) {\n if (has_opcodes(block) && should_remove(code->cfg(), block)) {\n duplicates[hash(block)].insert(block);\n ++num_eligible_blocks;\n }\n }\n m_mgr.incr_metric(METRIC_ELIGIBLE_BLOCKS, num_eligible_blocks);\n\n remove_singletons(duplicates);\n \/\/ the hash function isn't perfect, so check behind with an equals function\n remove_invalid_sets(code, duplicates);\n return duplicates;\n }\n\n \/\/ remove all but one of a duplicate set. Reroute the predecessors to the\n \/\/ canonical block\n void deduplicate(const duplicates_t& dups, DexMethod* method) {\n const auto& code = method->get_code();\n for (const auto& entry : dups) {\n std::unordered_set<Block*> blocks = entry.second;\n\n \/\/ canon is block with lowest id.\n Block* canon = nullptr;\n size_t canon_id = std::numeric_limits<size_t>::max();\n for (Block* block : blocks) {\n size_t id = block->id();\n if (id <= canon_id) {\n canon_id = id;\n canon = block;\n }\n }\n\n for (Block* block : blocks) {\n if (block->id() == canon_id) {\n \/\/ We remove the debug line information because it will be incorrect\n \/\/ for every block we reroute here. When there's no debug info,\n \/\/ the jvm will report the error on the closing brace of the function.\n \/\/ It's not perfect but it's better than incorrect information.\n code->remove_debug_line_info(canon);\n } else {\n transform::replace_block(code, block, canon);\n m_mgr.incr_metric(METRIC_BLOCKS_REMOVED, 1);\n }\n }\n }\n }\n\n void remove_invalid_sets(IRCode* code, duplicates_t& dups) {\n for (auto it = dups.begin(); it != dups.end();) {\n std::unordered_set<Block*> blocks = it->second;\n if (!all_equal(blocks) || conflicting_try_regions(code, blocks)) {\n it = dups.erase(it);\n } else {\n ++it;\n }\n }\n }\n\n static bool should_remove(const ControlFlowGraph& cfg, Block* block) {\n if (!has_opcodes(block)) {\n return false;\n }\n\n if (is_catch(block)) {\n \/\/ TODO. Should be possible. Skip now for simplicity\n return false;\n }\n\n \/\/ Deal with a verification error like this\n \/\/\n \/\/ A: new-instance v0\n \/\/ add-int v1, v2, v3 (this is here to clarify that A != C)\n \/\/ B: v0 <init>\n \/\/\n \/\/ ...\n \/\/\n \/\/ C: new-instance v0\n \/\/ D: v0 <init>\n \/\/\n \/\/ B == D. Coalesce!\n \/\/\n \/\/ A: new-instance v0\n \/\/ add-int v1, v2, v3\n \/\/ B: v0 <init>\n \/\/\n \/\/ C: new-instance v0\n \/\/ goto B\n \/\/\n \/\/ But the verifier doesn't like this. When it merges v0 on B,\n \/\/ it declares it to be a conflict because they were instantiated\n \/\/ on different lines.\n \/\/ See androidxref.com\/6.0.1_r10\/xref\/art\/runtime\/verifier\/reg_type.cc#684\n \/\/\n \/\/ It would be impossible to write this in java, but if you tried it would\n \/\/ look like this\n \/\/\n \/\/ if (someCondition) {\n \/\/ Foo a;\n \/\/ } else {\n \/\/ Foo b;\n \/\/ }\n \/\/ (a or b) = new Foo();\n \/\/\n \/\/ We try to avoid this situation by not considering blocks that call\n \/\/ constructors, but this isn't bulletproof. FIXME\n if (calls_constructor(block)) {\n return false;\n }\n\n \/\/ We can't replace blocks that are involved in a fallthrough because they\n \/\/ depend on their position in the list of instructions. Deduplicating\n \/\/ will involve sending control to a block in a different place.\n for (Block* pred : block->preds()) {\n if (!has_opcodes(pred)) {\n \/\/ Skip this case because it's complicated. It should be fixed by\n \/\/ upcoming changes to the CFG\n return false;\n }\n\n if (is_fallthrough(cfg, pred, block)) {\n return false;\n }\n }\n\n for (Block* succ : block->succs()) {\n if (is_fallthrough(cfg, block, succ)) {\n return false;\n }\n }\n\n return true;\n }\n\n static bool calls_constructor(Block* block) {\n for (const auto& mie : InstructionIterable(block)) {\n if (is_invoke(mie.insn->opcode()) && is_init(mie.insn->get_method())) {\n return true;\n }\n }\n return false;\n }\n\n \/\/ `pred` falls through to `succ` iff their connecting edge in the CFG is a\n \/\/ goto but `pred`'s last instruction isn't a goto\n static bool is_fallthrough(const ControlFlowGraph& cfg,\n Block* pred,\n Block* succ) {\n always_assert_log(has_opcodes(pred), \"need opcodes\");\n const auto& flags = cfg.edge(pred, succ);\n const auto& last_of_pred = last_opcode(pred);\n\n return flags[EDGE_GOTO] && !is_goto(last_of_pred->insn->opcode());\n }\n\n void record_stats(const duplicates_t& duplicates) {\n for (const auto& entry : duplicates) {\n bool first = true;\n bool same_size = true;\n size_t size = 0;\n for (Block* block : entry.second) {\n size_t this_size = num_opcodes(block);\n if (first) {\n size = this_size;\n first = false;\n } else if (size != this_size) {\n same_size = false;\n }\n }\n if (same_size && size > 0) {\n m_dup_sizes[size] += entry.second.size();\n }\n }\n }\n\n void report_stats() {\n TRACE(DEDUP_BLOCKS,\n 2,\n \"%d eligible_blocks\\n\",\n m_mgr.get_metric(METRIC_ELIGIBLE_BLOCKS));\n\n for (const auto& entry : m_dup_sizes) {\n TRACE(DEDUP_BLOCKS,\n 2,\n \"found %d duplicate blocks with %d instructions\\n\",\n entry.second,\n entry.first);\n }\n\n TRACE(DEDUP_BLOCKS,\n 1,\n \"%d blocks removed\\n\",\n m_mgr.get_metric(METRIC_BLOCKS_REMOVED));\n }\n\n \/\/ remove sets with only one block\n static void remove_singletons(duplicates_t& duplicates) {\n for (auto it = duplicates.begin(); it != duplicates.end();) {\n if (it->second.size() <= 1) {\n it = duplicates.erase(it);\n } else {\n ++it;\n }\n }\n }\n\n static boost::optional<MethodItemEntry&> last_opcode(Block* block) {\n for (auto it = block->rbegin(); it != block->rend(); it++) {\n if (it->type == MFLOW_OPCODE) {\n return *it;\n }\n }\n return boost::none;\n }\n\n static bool has_opcodes(Block* block) {\n const auto& it = InstructionIterable(block);\n return it.begin() != it.end();\n }\n\n static size_t num_opcodes(Block* block) {\n size_t result = 0;\n const auto& iterable = InstructionIterable(block);\n for (auto it = iterable.begin(); it != iterable.end(); it++) {\n result++;\n }\n return result;\n }\n\n \/\/ return true if all the blocks don't jump to the same catch handler (or no\n \/\/ catch handler at all)\n static bool conflicting_try_regions(IRCode* code,\n std::unordered_set<Block*> blocks) {\n MethodItemEntry* active_catch = nullptr;\n bool first = true;\n for (Block* b : blocks) {\n if (first) {\n first = false;\n active_catch = transform::find_active_catch(code, b->begin());\n } else {\n if (active_catch != transform::find_active_catch(code, b->begin())) {\n return true;\n }\n }\n }\n return false;\n }\n\n static bool all_equal(std::unordered_set<Block*> blocks) {\n Block* canon = nullptr;\n for (auto i = blocks.begin(); i != blocks.end(); i++) {\n if (canon == nullptr) {\n canon = *i;\n } else if (!equals(canon, *i)) {\n return false;\n }\n }\n return true;\n }\n\n \/\/ Structural equality of opcodes except branches targets are ignored\n \/\/ because they are unknown until we sync back to DexInstructions.\n \/\/\n \/\/ The blocks must also have the exact same successors\n static bool equals(Block* b1, Block* b2) {\n\n if (!same_successors(b1, b2)) {\n return false;\n }\n\n const auto& iterable1 = InstructionIterable(b1);\n const auto& iterable2 = InstructionIterable(b2);\n auto it1 = iterable1.begin();\n auto it2 = iterable2.begin();\n for (; it1 != iterable1.end() && it2 != iterable2.end(); it1++, it2++) {\n auto& mie1 = *it1;\n auto& mie2 = *it2;\n if (*mie1.insn != *mie2.insn) {\n return false;\n }\n }\n\n if (!(it1 == iterable1.end() && it2 == iterable2.end())) {\n \/\/ different lengths\n return false;\n }\n return true;\n }\n\n \/\/ FIXME: what if the successors are the same but the type of connecting\n \/\/ edges are different?\n \/\/ Like so:\n \/\/\n \/\/ B0: if-eqz v0, B3\n \/\/ B1: return\n \/\/ B2: if eqz v0, B1\n \/\/ B3: add-int v1, 1\n \/\/\n \/\/ B0's succs are B1 (fallthru) and B3 (branch)\n \/\/ B2's succs are B3 (fallthru) and B1 (branch)\n \/\/\n \/\/ Is this possible to write in java? (because java doesn't have gotos)\n static bool same_successors(Block* b1, Block* b2) {\n\n const auto& b1_succs = b1->succs();\n const auto& b2_succs = b2->succs();\n if (b1_succs.size() != b2_succs.size()) {\n return false;\n }\n for (Block* b1_succ : b1_succs) {\n if (std::find(b2_succs.begin(), b2_succs.end(), b1_succ) ==\n b2_succs.end()) {\n \/\/ b1 has a succ that b2 doesn't\n return false;\n }\n }\n return true;\n }\n\n static hash_t hash(Block* block) {\n hash_t result = 0;\n for (auto& mie : InstructionIterable(block)) {\n result ^= mie.insn->hash();\n }\n return result;\n }\n\n static void print_dups(duplicates_t dups) {\n TRACE(DEDUP_BLOCKS, 4, \"duplicate blocks set: {\\n\");\n for (const auto& entry : dups) {\n TRACE(DEDUP_BLOCKS, 4, \" hash = %lu\\n\", entry.first);\n for (Block* b : entry.second) {\n TRACE(DEDUP_BLOCKS, 4, \" block %d\\n\", b->id());\n for (const MethodItemEntry& mie : *b) {\n TRACE(DEDUP_BLOCKS, 4, \" %s\\n\", SHOW(mie));\n }\n }\n }\n TRACE(DEDUP_BLOCKS, 4, \"} end duplicate blocks set\\n\");\n }\n};\n}\n\nvoid DedupBlocksPass::run_pass(DexStoresVector& stores,\n ConfigFiles& \/* unused *\/,\n PassManager& mgr) {\n const auto& scope = build_class_scope(stores);\n DedupBlocksImpl impl(scope, mgr, m_config);\n impl.run();\n}\n\nstatic DedupBlocksPass s_pass;\n<commit_msg>Fix same successors but different edges<commit_after>\/**\n * Copyright (c) 2016-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#include \"DedupBlocksPass.h\"\n\n#include <boost\/optional.hpp>\n#include <iterator>\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"ControlFlow.h\"\n#include \"DexClass.h\"\n#include \"DexOutput.h\"\n#include \"DexUtil.h\"\n#include \"IRCode.h\"\n#include \"Transform.h\"\n#include \"Walkers.h\"\n\n\/*\n * This pass removes blocks that are duplicates in a method.\n *\n * If a method has multiple blocks with the same code and the same successors,\n * delete all but one of the blocks. Naming one of them the canonical block.\n *\n * Then, reroute all the predecessors of all the blocks to that canonical block.\n *\/\n\nnamespace {\n\nclass DedupBlocksImpl {\n public:\n DedupBlocksImpl(const std::vector<DexClass*>& scope,\n PassManager& mgr,\n const DedupBlocksPass::Config& config)\n : m_scope(scope), m_mgr(mgr), m_config(config) {}\n\n void run() {\n walk_methods(m_scope, [this](DexMethod* method) {\n if (m_config.method_black_list.count(method) != 0) {\n return;\n }\n\n IRCode* code = method->get_code();\n if (code == nullptr) {\n return;\n }\n code->build_cfg();\n\n duplicates_t dups = collect_duplicates(code);\n if (dups.size() > 0) {\n record_stats(dups);\n deduplicate(dups, method);\n }\n });\n report_stats();\n }\n\n private:\n using hash_t = uint64_t;\n using duplicates_t = std::unordered_map<hash_t, std::unordered_set<Block*>>;\n const char* METRIC_BLOCKS_REMOVED = \"blocks_removed\";\n const char* METRIC_ELIGIBLE_BLOCKS = \"eligible_blocks\";\n const std::vector<DexClass*>& m_scope;\n PassManager& m_mgr;\n const DedupBlocksPass::Config& m_config;\n\n \/\/ map from block size to number of blocks with that size\n std::unordered_map<size_t, size_t> m_dup_sizes;\n\n \/\/ Find blocks with the same exact code\n duplicates_t collect_duplicates(IRCode* code) {\n const auto& blocks = code->cfg().blocks();\n std::unordered_map<hash_t, std::unordered_set<Block*>> duplicates;\n\n int num_eligible_blocks = 0;\n for (Block* block : blocks) {\n if (has_opcodes(block) && should_remove(code->cfg(), block)) {\n duplicates[hash(block)].insert(block);\n ++num_eligible_blocks;\n }\n }\n m_mgr.incr_metric(METRIC_ELIGIBLE_BLOCKS, num_eligible_blocks);\n\n remove_singletons(duplicates);\n \/\/ the hash function isn't perfect, so check behind with an equals function\n remove_invalid_sets(code, duplicates);\n return duplicates;\n }\n\n \/\/ remove all but one of a duplicate set. Reroute the predecessors to the\n \/\/ canonical block\n void deduplicate(const duplicates_t& dups, DexMethod* method) {\n const auto& code = method->get_code();\n for (const auto& entry : dups) {\n std::unordered_set<Block*> blocks = entry.second;\n\n \/\/ canon is block with lowest id.\n Block* canon = nullptr;\n size_t canon_id = std::numeric_limits<size_t>::max();\n for (Block* block : blocks) {\n size_t id = block->id();\n if (id <= canon_id) {\n canon_id = id;\n canon = block;\n }\n }\n\n for (Block* block : blocks) {\n if (block->id() == canon_id) {\n \/\/ We remove the debug line information because it will be incorrect\n \/\/ for every block we reroute here. When there's no debug info,\n \/\/ the jvm will report the error on the closing brace of the function.\n \/\/ It's not perfect but it's better than incorrect information.\n code->remove_debug_line_info(canon);\n } else {\n transform::replace_block(code, block, canon);\n m_mgr.incr_metric(METRIC_BLOCKS_REMOVED, 1);\n }\n }\n }\n }\n\n void remove_invalid_sets(IRCode* code, duplicates_t& dups) {\n for (auto it = dups.begin(); it != dups.end();) {\n std::unordered_set<Block*> blocks = it->second;\n if (!all_equal(code->cfg(), blocks) ||\n conflicting_try_regions(code, blocks)) {\n it = dups.erase(it);\n } else {\n ++it;\n }\n }\n }\n\n static bool should_remove(const ControlFlowGraph& cfg, Block* block) {\n if (!has_opcodes(block)) {\n return false;\n }\n\n if (is_catch(block)) {\n \/\/ TODO. Should be possible. Skip now for simplicity\n return false;\n }\n\n \/\/ Deal with a verification error like this\n \/\/\n \/\/ A: new-instance v0\n \/\/ add-int v1, v2, v3 (this is here to clarify that A != C)\n \/\/ B: v0 <init>\n \/\/\n \/\/ ...\n \/\/\n \/\/ C: new-instance v0\n \/\/ D: v0 <init>\n \/\/\n \/\/ B == D. Coalesce!\n \/\/\n \/\/ A: new-instance v0\n \/\/ add-int v1, v2, v3\n \/\/ B: v0 <init>\n \/\/\n \/\/ C: new-instance v0\n \/\/ goto B\n \/\/\n \/\/ But the verifier doesn't like this. When it merges v0 on B,\n \/\/ it declares it to be a conflict because they were instantiated\n \/\/ on different lines.\n \/\/ See androidxref.com\/6.0.1_r10\/xref\/art\/runtime\/verifier\/reg_type.cc#684\n \/\/\n \/\/ It would be impossible to write this in java, but if you tried it would\n \/\/ look like this\n \/\/\n \/\/ if (someCondition) {\n \/\/ Foo a;\n \/\/ } else {\n \/\/ Foo b;\n \/\/ }\n \/\/ (a or b) = new Foo();\n \/\/\n \/\/ We try to avoid this situation by not considering blocks that call\n \/\/ constructors, but this isn't bulletproof. FIXME\n if (calls_constructor(block)) {\n return false;\n }\n\n \/\/ We can't replace blocks that are involved in a fallthrough because they\n \/\/ depend on their position in the list of instructions. Deduplicating\n \/\/ will involve sending control to a block in a different place.\n for (Block* pred : block->preds()) {\n if (!has_opcodes(pred)) {\n \/\/ Skip this case because it's complicated. It should be fixed by\n \/\/ upcoming changes to the CFG\n return false;\n }\n\n if (is_fallthrough(cfg, pred, block)) {\n return false;\n }\n }\n\n for (Block* succ : block->succs()) {\n if (is_fallthrough(cfg, block, succ)) {\n return false;\n }\n }\n\n return true;\n }\n\n static bool calls_constructor(Block* block) {\n for (const auto& mie : InstructionIterable(block)) {\n if (is_invoke(mie.insn->opcode()) && is_init(mie.insn->get_method())) {\n return true;\n }\n }\n return false;\n }\n\n \/\/ `pred` falls through to `succ` iff their connecting edge in the CFG is a\n \/\/ goto but `pred`'s last instruction isn't a goto\n static bool is_fallthrough(const ControlFlowGraph& cfg,\n Block* pred,\n Block* succ) {\n always_assert_log(has_opcodes(pred), \"need opcodes\");\n const auto& flags = cfg.edge(pred, succ);\n const auto& last_of_pred = last_opcode(pred);\n\n return flags[EDGE_GOTO] && !is_goto(last_of_pred->insn->opcode());\n }\n\n void record_stats(const duplicates_t& duplicates) {\n for (const auto& entry : duplicates) {\n bool first = true;\n bool same_size = true;\n size_t size = 0;\n for (Block* block : entry.second) {\n size_t this_size = num_opcodes(block);\n if (first) {\n size = this_size;\n first = false;\n } else if (size != this_size) {\n same_size = false;\n }\n }\n if (same_size && size > 0) {\n m_dup_sizes[size] += entry.second.size();\n }\n }\n }\n\n void report_stats() {\n TRACE(DEDUP_BLOCKS,\n 2,\n \"%d eligible_blocks\\n\",\n m_mgr.get_metric(METRIC_ELIGIBLE_BLOCKS));\n\n for (const auto& entry : m_dup_sizes) {\n TRACE(DEDUP_BLOCKS,\n 2,\n \"found %d duplicate blocks with %d instructions\\n\",\n entry.second,\n entry.first);\n }\n\n TRACE(DEDUP_BLOCKS,\n 1,\n \"%d blocks removed\\n\",\n m_mgr.get_metric(METRIC_BLOCKS_REMOVED));\n }\n\n \/\/ remove sets with only one block\n static void remove_singletons(duplicates_t& duplicates) {\n for (auto it = duplicates.begin(); it != duplicates.end();) {\n if (it->second.size() <= 1) {\n it = duplicates.erase(it);\n } else {\n ++it;\n }\n }\n }\n\n static boost::optional<MethodItemEntry&> last_opcode(Block* block) {\n for (auto it = block->rbegin(); it != block->rend(); it++) {\n if (it->type == MFLOW_OPCODE) {\n return *it;\n }\n }\n return boost::none;\n }\n\n static bool has_opcodes(Block* block) {\n const auto& it = InstructionIterable(block);\n return it.begin() != it.end();\n }\n\n static size_t num_opcodes(Block* block) {\n size_t result = 0;\n const auto& iterable = InstructionIterable(block);\n for (auto it = iterable.begin(); it != iterable.end(); it++) {\n result++;\n }\n return result;\n }\n\n \/\/ return true if all the blocks don't jump to the same catch handler (or no\n \/\/ catch handler at all)\n static bool conflicting_try_regions(IRCode* code,\n std::unordered_set<Block*> blocks) {\n MethodItemEntry* active_catch = nullptr;\n bool first = true;\n for (Block* b : blocks) {\n if (first) {\n first = false;\n active_catch = transform::find_active_catch(code, b->begin());\n } else {\n if (active_catch != transform::find_active_catch(code, b->begin())) {\n return true;\n }\n }\n }\n return false;\n }\n\n static bool all_equal(const ControlFlowGraph& cfg,\n std::unordered_set<Block*> blocks) {\n Block* canon = nullptr;\n for (auto i = blocks.begin(); i != blocks.end(); i++) {\n if (canon == nullptr) {\n canon = *i;\n } else if (!equals(cfg, canon, *i)) {\n return false;\n }\n }\n return true;\n }\n\n \/\/ Structural equality of opcodes except branches targets are ignored\n \/\/ because they are unknown until we sync back to DexInstructions.\n \/\/\n \/\/ The blocks must also have the exact same successors\n static bool equals(const ControlFlowGraph& cfg, Block* b1, Block* b2) {\n\n if (!same_successors(cfg, b1, b2)) {\n return false;\n }\n\n const auto& iterable1 = InstructionIterable(b1);\n const auto& iterable2 = InstructionIterable(b2);\n auto it1 = iterable1.begin();\n auto it2 = iterable2.begin();\n for (; it1 != iterable1.end() && it2 != iterable2.end(); it1++, it2++) {\n auto& mie1 = *it1;\n auto& mie2 = *it2;\n if (*mie1.insn != *mie2.insn) {\n return false;\n }\n }\n\n if (!(it1 == iterable1.end() && it2 == iterable2.end())) {\n \/\/ different lengths\n return false;\n }\n return true;\n }\n\n static bool same_successors(const ControlFlowGraph& cfg,\n Block* b1,\n Block* b2) {\n const auto& b1_succs = b1->succs();\n const auto& b2_succs = b2->succs();\n if (b1_succs.size() != b2_succs.size()) {\n return false;\n }\n for (Block* b1_succ : b1_succs) {\n const auto& in_b2 = std::find(b2_succs.begin(), b2_succs.end(), b1_succ);\n if (in_b2 == b2_succs.end()) {\n \/\/ b1 has a succ that b2 doesn't\n return false;\n }\n\n if (cfg.edge(b1, b1_succ) != cfg.edge(b2, *in_b2)) {\n \/\/ successors are the same but the type of connecting\n \/\/ edges are different.\n \/\/ Like so:\n \/\/\n \/\/ B0: if-eqz v0, B3\n \/\/ B1: return\n \/\/ B2: if eqz v0, B1\n \/\/ B3: add-int v1, 1\n \/\/\n \/\/ B0's succs are B1 (fallthru) and B3 (branch)\n \/\/ B2's succs are B3 (fallthru) and B1 (branch)\n return false;\n }\n }\n return true;\n }\n\n static hash_t hash(Block* block) {\n hash_t result = 0;\n for (auto& mie : InstructionIterable(block)) {\n result ^= mie.insn->hash();\n }\n return result;\n }\n\n static void print_dups(duplicates_t dups) {\n TRACE(DEDUP_BLOCKS, 4, \"duplicate blocks set: {\\n\");\n for (const auto& entry : dups) {\n TRACE(DEDUP_BLOCKS, 4, \" hash = %lu\\n\", entry.first);\n for (Block* b : entry.second) {\n TRACE(DEDUP_BLOCKS, 4, \" block %d\\n\", b->id());\n for (const MethodItemEntry& mie : *b) {\n TRACE(DEDUP_BLOCKS, 4, \" %s\\n\", SHOW(mie));\n }\n }\n }\n TRACE(DEDUP_BLOCKS, 4, \"} end duplicate blocks set\\n\");\n }\n};\n}\n\nvoid DedupBlocksPass::run_pass(DexStoresVector& stores,\n ConfigFiles& \/* unused *\/,\n PassManager& mgr) {\n const auto& scope = build_class_scope(stores);\n DedupBlocksImpl impl(scope, mgr, m_config);\n impl.run();\n}\n\nstatic DedupBlocksPass s_pass;\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <string>\n#include <atomic>\n#include <memory>\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <thread>\n#include <future>\n#include <iostream>\n#include \"concurrent.hpp\"\n\nnamespace {\n typedef std::chrono::steady_clock clock;\n\n \/\/ Random function from http:\/\/www2.research.att.com\/~bs\/C++0xFAQ.html#std-random\n int random_int(int low, int high) {\n using namespace std;\n static std::random_device rd; \/\/ Seed with a real random value, if available\n static default_random_engine engine{rd()};\n typedef uniform_int_distribution<int> Distribution;\n static Distribution distribution{};\n\n return distribution(engine, Distribution::param_type{low, high});\n }\n\n struct DummyObject { };\n\n\n\n \/\/ Verify clean destruction\n\n struct TrueAtExit {\n std::atomic<bool>* flag;\n explicit TrueAtExit(std::atomic<bool>* f) : flag(f) { flag->store(false); }\n bool value() { return *flag; }\n ~TrueAtExit() { flag->store(true); }\n \/\/ concurrent improvement from the original Herb Sutter example\n \/\/ Which would copy\/move the object into the concurrent wrapper\n \/\/ i.e the original concurrent wrapper could not use an object such as this (or a unique_ptr for that matter)\n TrueAtExit(const TrueAtExit&) = delete;\n TrueAtExit& operator=(const TrueAtExit&) = delete;\n };\n\n\n\n \/\/ Verify concurrent runs,. \"no\" delay for the caller. \n struct DelayedCaller {\n void DoDelayedCall() { std::this_thread::sleep_for(std::chrono::seconds(1)); }\n };\n\n \n \/\/ To verify that it is FIFO access\n class FlipOnce {\n std::atomic<size_t>* _stored_counter;\n std::atomic<size_t>* _stored_attempts;\n bool _is_flipped;\n size_t _counter;\n size_t _attempts;\n\n public:\n\n explicit FlipOnce(std::atomic<size_t>* c, std::atomic<size_t>* t)\n : _stored_counter(c), _stored_attempts(t)\n , _is_flipped(false), _counter(0), _attempts(0) { }\n\n ~FlipOnce() {\n (*_stored_counter) = _counter;\n (*_stored_attempts) = _attempts;\n }\n\n \/\/ Void flip will count up NON ATOMIC internal variables. They are non atomic to avoid \n \/\/ any kind of unforseen atomic synchronization. Only in the destructor will the values \n \/\/ be saved to the atomic storages\n void doFlip() {\n if (!_is_flipped) {\n std::this_thread::sleep_for(std::chrono::milliseconds(random_int(0, 1000)));\n _is_flipped = true;\n _counter++;\n }\n _attempts++;\n }\n };\n \n \n struct Animal { virtual std::string sound() = 0; };\n \n struct Dog : public Animal { \n std::string sound() override { return {\"Wof Wof\"};}\n };\n struct Cat : public Animal {\n std::string sound() override { return {\"Miauu Miauu\"};}\n };\n} \/\/ anonymous\n\nTEST(TestOfConcurrent, CompilerCheckForEmptyStruct) {\n concurrent<DummyObject> doNothing1{};\n concurrent<DummyObject> doNothing2;\n concurrent<DummyObject> doNothing3 = {};\n}\n\nTEST(TestOfConcurrent, CompilerCheckUniquePtrTest) {\n typedef std::unique_ptr<Animal> RaiiAnimal;\n concurrent<RaiiAnimal> animal1{new Dog};\n concurrent<RaiiAnimal> animal2{new Cat};\n\n auto make_sound = [](RaiiAnimal & animal) {\n return animal->sound();\n };\n EXPECT_EQ(\"Wof Wof\", animal1(make_sound).get());\n EXPECT_EQ(\"Miauu Miauu\", animal2(make_sound).get());\n}\n\n\n\nTEST(TestOfConcurrent, VerifyDestruction) {\n std::atomic<bool> flag{true};\n {\n concurrent<TrueAtExit> notifyAtExit1{&flag};\n EXPECT_FALSE(flag); \/\/ i.e. constructor has run\n }\n {\n EXPECT_TRUE(flag); \/\/ notifyAtExit destructor\n concurrent<TrueAtExit> notifyAtExit2 = {&flag};\n EXPECT_FALSE(flag);\n }\n EXPECT_TRUE(flag); \/\/ notifyAtExit destructor\n}\n\n\n\nTEST(TestOfConcurrent, VerifyFifoCalls) {\n\n concurrent<std::string> asyncString = {\"start\"};\n auto received = asyncString([](std::string & s) {\n s.append(\" received message\"); return std::string{s}; });\n\n auto clear = asyncString([](std::string & s) {\n s.clear(); return s; });\n\n EXPECT_EQ(\"start received message\", received.get());\n EXPECT_EQ(\"\", clear.get());\n\n std::string toCompare;\n for (size_t index = 0; index < 100000; ++index) {\n toCompare.append(std::to_string(index)).append(\" \");\n asyncString([ = ](std::string & s){s.append(std::to_string(index)).append(\" \");});\n }\n\n auto appended = asyncString([](const std::string & s) {\n return s; });\n EXPECT_EQ(appended.get(), toCompare);\n}\n\n\n\nTEST(TestOfConcurrent, VerifyImmediateReturnForSlowFunctionCalls) {\n auto start = clock::now();\n {\n concurrent<DelayedCaller> snail;\n for (size_t call = 0; call < 10; ++call) {\n snail([](DelayedCaller & slowRunner) {\n slowRunner.DoDelayedCall(); });\n }\n EXPECT_LT(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count(), 1);\n } \/\/ at destruction all 1 second calls will be executed before we quit\n\n EXPECT_TRUE(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count() >= 10); \/\/ \n}\n\n\n\nstd::future<void> DoAFlip(concurrent<FlipOnce>& flipper) {\n return flipper([] (FlipOnce & obj) {\n obj.doFlip(); });\n}\nTEST(TestOfConcurrent, IsConcurrentReallyAsyncWithFifoGuarantee__Wait1Minute) {\n auto start = clock::now();\n\n for (size_t howmanyflips = 0; howmanyflips < 60; ++howmanyflips) {\n std::atomic<size_t> count_of_flip{0};\n std::atomic<size_t> total_thread_access{0};\n {\n concurrent<FlipOnce> flipOnceObject{&count_of_flip, &total_thread_access};\n ASSERT_EQ(0, count_of_flip);\n auto try0 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try1 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try2 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try3 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try4 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try5 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try6 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try7 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try8 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try9 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n\n \/\/ scope exit. ALL jobs will be executed before this finished. \n \/\/This means that all 10 jobs in the loop must be done\n \/\/ all 10 will wait here till they are finished\n }\n auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start).count();\n std::cout << \"Run \" << howmanyflips << \", took: \" << total_time << \" milliseconds\" << std::endl;\n start = clock::now();\n ASSERT_EQ(1, count_of_flip);\n ASSERT_EQ(10, total_thread_access);\n }\n}\n\n<commit_msg>Improved test. Repeat the same but with atomics inside. It should be the same result<commit_after>#include <gtest\/gtest.h>\n#include <string>\n#include <atomic>\n#include <memory>\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <thread>\n#include <future>\n#include <cassert>\n#include <iostream>\n#include \"concurrent.hpp\"\n\nnamespace {\n typedef std::chrono::steady_clock clock;\n\n \/\/ Random function from http:\/\/www2.research.att.com\/~bs\/C++0xFAQ.html#std-random\n int random_int(int low, int high) {\n using namespace std;\n static std::random_device rd; \/\/ Seed with a real random value, if available\n static default_random_engine engine{rd()};\n typedef uniform_int_distribution<int> Distribution;\n static Distribution distribution{};\n\n return distribution(engine, Distribution::param_type{low, high});\n }\n\n struct DummyObject { };\n\n\n\n \/\/ Verify clean destruction\n\n struct TrueAtExit {\n std::atomic<bool>* flag;\n explicit TrueAtExit(std::atomic<bool>* f) : flag(f) { flag->store(false); }\n bool value() { return *flag; }\n ~TrueAtExit() { flag->store(true); }\n \/\/ concurrent improvement from the original Herb Sutter example\n \/\/ Which would copy\/move the object into the concurrent wrapper\n \/\/ i.e the original concurrent wrapper could not use an object such as this (or a unique_ptr for that matter)\n TrueAtExit(const TrueAtExit&) = delete;\n TrueAtExit& operator=(const TrueAtExit&) = delete;\n };\n\n\n\n \/\/ Verify concurrent runs,. \"no\" delay for the caller. \n struct DelayedCaller {\n void DoDelayedCall() { std::this_thread::sleep_for(std::chrono::seconds(1)); }\n };\n\n \n \/\/ To verify that it is FIFO access\n class FlipOnce {\n std::atomic<size_t>* _stored_counter;\n std::atomic<size_t>* _stored_attempts;\n bool _is_flipped;\n size_t _counter;\n size_t _attempts;\n\n public:\n\n explicit FlipOnce(std::atomic<size_t>* c, std::atomic<size_t>* t)\n : _stored_counter(c), _stored_attempts(t)\n , _is_flipped(false), _counter(0), _attempts(0) { }\n\n ~FlipOnce() {\n if (0 == *_stored_counter) {\n std::cout << \"FlipOnce was with no atomics in the doFlip operation \" << std::endl;\n (*_stored_counter) = _counter;\n (*_stored_attempts) = _attempts;\n } else {\n std::cout << \"FlipOnce was WITH atomics in the doFlipAtomic operation \" << std::endl;\n assert(0==_counter);\n assert(0==_attempts);\n }\n }\n\n \/\/ Void flip will count up NON ATOMIC internal variables. They are non atomic to avoid \n \/\/ any kind of unforseen atomic synchronization. Only in the destructor will the values \n \/\/ be saved to the atomic storages\n void doFlip() {\n if (!_is_flipped) {\n std::this_thread::sleep_for(std::chrono::milliseconds(random_int(0, 1000)));\n _is_flipped = true;\n _counter++;\n }\n _attempts++;\n }\n\n void doFlipAtomic() {\n if (!_is_flipped) {\n std::this_thread::sleep_for(std::chrono::milliseconds(random_int(0, 1000)));\n _is_flipped = true;\n (*_stored_counter)++;\n }\n (*_stored_attempts)++;\n }\n };\n \n \n struct Animal { virtual std::string sound() = 0; };\n \n struct Dog : public Animal { \n std::string sound() override { return {\"Wof Wof\"};}\n };\n struct Cat : public Animal {\n std::string sound() override { return {\"Miauu Miauu\"};}\n };\n} \/\/ anonymous\n\nTEST(TestOfConcurrent, CompilerCheckForEmptyStruct) {\n concurrent<DummyObject> doNothing1{};\n concurrent<DummyObject> doNothing2;\n concurrent<DummyObject> doNothing3 = {};\n}\n\nTEST(TestOfConcurrent, CompilerCheckUniquePtrTest) {\n typedef std::unique_ptr<Animal> RaiiAnimal;\n concurrent<RaiiAnimal> animal1{new Dog};\n concurrent<RaiiAnimal> animal2{new Cat};\n\n auto make_sound = [](RaiiAnimal & animal) {\n return animal->sound();\n };\n EXPECT_EQ(\"Wof Wof\", animal1(make_sound).get());\n EXPECT_EQ(\"Miauu Miauu\", animal2(make_sound).get());\n}\n\n\n\nTEST(TestOfConcurrent, VerifyDestruction) {\n std::atomic<bool> flag{true};\n {\n concurrent<TrueAtExit> notifyAtExit1{&flag};\n EXPECT_FALSE(flag); \/\/ i.e. constructor has run\n }\n {\n EXPECT_TRUE(flag); \/\/ notifyAtExit destructor\n concurrent<TrueAtExit> notifyAtExit2 = {&flag};\n EXPECT_FALSE(flag);\n }\n EXPECT_TRUE(flag); \/\/ notifyAtExit destructor\n}\n\n\n\nTEST(TestOfConcurrent, VerifyFifoCalls) {\n\n concurrent<std::string> asyncString = {\"start\"};\n auto received = asyncString([](std::string & s) {\n s.append(\" received message\"); return std::string{s}; });\n\n auto clear = asyncString([](std::string & s) {\n s.clear(); return s; });\n\n EXPECT_EQ(\"start received message\", received.get());\n EXPECT_EQ(\"\", clear.get());\n\n std::string toCompare;\n for (size_t index = 0; index < 100000; ++index) {\n toCompare.append(std::to_string(index)).append(\" \");\n asyncString([ = ](std::string & s){s.append(std::to_string(index)).append(\" \");});\n }\n\n auto appended = asyncString([](const std::string & s) {\n return s; });\n EXPECT_EQ(appended.get(), toCompare);\n}\n\n\n\nTEST(TestOfConcurrent, VerifyImmediateReturnForSlowFunctionCalls) {\n auto start = clock::now();\n {\n concurrent<DelayedCaller> snail;\n for (size_t call = 0; call < 10; ++call) {\n snail([](DelayedCaller & slowRunner) {\n slowRunner.DoDelayedCall(); });\n }\n EXPECT_LT(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count(), 1);\n } \/\/ at destruction all 1 second calls will be executed before we quit\n\n EXPECT_TRUE(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count() >= 10); \/\/ \n}\n\n\n\nstd::future<void> DoAFlip(concurrent<FlipOnce>& flipper) {\n return flipper([] (FlipOnce & obj) {\n obj.doFlip(); });\n}\nTEST(TestOfConcurrent, IsConcurrentReallyAsyncWithFifoGuarantee__Wait1Minute) {\n auto start = clock::now();\n\n for (size_t howmanyflips = 0; howmanyflips < 60; ++howmanyflips) {\n std::atomic<size_t> count_of_flip{0};\n std::atomic<size_t> total_thread_access{0};\n {\n concurrent<FlipOnce> flipOnceObject{&count_of_flip, &total_thread_access};\n ASSERT_EQ(0, count_of_flip);\n auto try0 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try1 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try2 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try3 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try4 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try5 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try6 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try7 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try8 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n auto try9 = std::async(std::launch::async, DoAFlip, std::ref(flipOnceObject));\n\n \/\/ scope exit. ALL jobs will be executed before this finished. \n \/\/This means that all 10 jobs in the loop must be done\n \/\/ all 10 will wait here till they are finished\n }\n auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start).count();\n std::cout << \"Run \" << howmanyflips << \", took: \" << total_time << \" milliseconds\" << std::endl;\n start = clock::now();\n ASSERT_EQ(1, count_of_flip);\n ASSERT_EQ(10, total_thread_access);\n }\n}\n\nstd::future<void> DoAFlipAtomic(concurrent<FlipOnce>& flipper) {\n return flipper([] (FlipOnce & obj) {\n obj.doFlipAtomic(); });\n}\nTEST(TestOfConcurrent, IsConcurrentReallyAsyncWithFifoGuarantee__AtomicInside_Wait1Minute) {\n auto start = clock::now();\n\n for (size_t howmanyflips = 0; howmanyflips < 60; ++howmanyflips) {\n std::atomic<size_t> count_of_flip{0};\n std::atomic<size_t> total_thread_access{0};\n {\n concurrent<FlipOnce> flipOnceObject{&count_of_flip, &total_thread_access};\n ASSERT_EQ(0, count_of_flip);\n auto try0 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try1 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try2 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try3 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try4 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try5 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try6 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try7 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try8 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n auto try9 = std::async(std::launch::async, DoAFlipAtomic, std::ref(flipOnceObject));\n\n \/\/ scope exit. ALL jobs will be executed before this finished. \n \/\/This means that all 10 jobs in the loop must be done\n \/\/ all 10 will wait here till they are finished\n }\n auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start).count();\n std::cout << \"Run 2: \" << howmanyflips << \", took: \" << total_time << \" milliseconds\" << std::endl;\n start = clock::now();\n ASSERT_EQ(1, count_of_flip);\n ASSERT_EQ(10, total_thread_access);\n }\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/test\/unit_test.hpp>\n#include <cinatra\/body_parser.hpp>\n\nusing namespace cinatra;\n\nBOOST_AUTO_TEST_CASE(urlencoded_body_parser_test)\n{\n CaseMap cm = urlencoded_body_parser(\"k%261=v%3d1&k%262=v%3d2\");\n BOOST_CHECK(cm[\"k%261\"] == \"v%3d1\");\n BOOST_CHECK(cm[\"k%262\"] == \"v%3d2\");\n}\n<commit_msg>fix test<commit_after>#include <boost\/test\/unit_test.hpp>\n#include <cinatra\/body_parser.hpp>\n\nusing namespace cinatra;\n\nBOOST_AUTO_TEST_CASE(urlencoded_body_parser_test)\n{\n CaseMap cm = urlencoded_body_parser(\"k%261=v%3d1&k%262=v%3d2\");\n BOOST_CHECK(cm[\"k&1\"] == \"v=1\");\n BOOST_CHECK(cm[\"k&2\"] == \"v=2\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n\n#include <iostream>\n#include <dgcrypto\/dgcrypto.hh>\n#include <rsa-crypt-lib\/rsa-crypt-lib.hh>\n\n\nTEST(RSACrypt, RsaKeysConstructor1024) {\n RsaKeys my_keys(512);\n EXPECT_GT(my_keys.totient(), my_keys.e());\n\n}\n\nTEST(RSACrypt, RsaDecodeEncode1) {\n RsaKeys my_keys(1024);\n \/\/std::cerr<<\"Encoded value\"<<my_keys.encode_result()<<std::endl;\n EXPECT_EQ(\"Hello my name is Rafa\", my_keys.decoded_result());\n}\n TEST(RSACrypt, RsaDecodeEncode2) {\n RsaKeys my_keys(1024);\n \/\/std::cerr<<\"Encoded value\"<<my_keys.encode_result()<<std::endl;\n \/\/std::cerr<<\"decoded result\"<<my_keys.decoded_result()<<std::endl;\n EXPECT_EQ(\"Hello my name is Rafa\", my_keys.decoded_result());\n}\n<commit_msg>Added tests for new encrypt\/decrypt functions<commit_after>#include <gtest\/gtest.h>\n\n#include <iostream>\n#include <dgcrypto\/dgcrypto.hh>\n#include <rsa-crypt-lib\/rsa-crypt-lib.hh>\n\n\nTEST(RSACrypt, RsaKeysConstructor1024) {\n RsaKeys my_keys(512);\n EXPECT_GT(my_keys.totient(), my_keys.e());\n}\nTEST(RSACrypt, RSAEncrypt){\n RsaKeys my_keys(512);\n std::string message = \"attack at dawn\";\n std::string encrypted = my_keys.encrypt_message(message);\n EXPECT_NE(message, encrypted);\n EXPECT_EQ(message, my_keys.decrypt_message(encrypted));\n}\n\nTEST(RSACrypt, RSAEncryptUpperCase){\n RsaKeys my_keys(512);\n std::string message = \"ATTACK AT DAWN\";\n std::string encrypted = my_keys.encrypt_message(message);\n EXPECT_NE(message, encrypted);\n EXPECT_EQ(message, my_keys.decrypt_message(encrypted));\n}\n\nTEST(RSACrypt, RSAOverflowTest){\n RsaKeys my_keys(512);\n std::string message = \"a\";\n for(int i = 0; i < 100; ++i){\n message += \"aaa\";\n std::string encrypted = my_keys.encrypt_message(message);\n EXPECT_EQ(message, my_keys.decrypt_message(encrypted));\n }\n}\nTEST(RSACrypt, RSAEncryptMonkeyTest){\n RsaKeys my_keys(512);\n std::string message = \"aaaaaaaaaaaaaaaaLONG ASS MSG FROM A MONKEYas;dlfjasd;fasdjgkasdfj 29835892069qf )@#(*%Y)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa asdfasdf sadfRO SALKFROO )(*&^)@#%& rolling face on keyboard asdfaskdfljasZBLAHABLHASDFfaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\n\n std::string encrypted = my_keys.encrypt_message(message);\n EXPECT_NE(message, encrypted);\n EXPECT_EQ(message, my_keys.decrypt_message(encrypted));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include \"..\/..\/cvmfs\/util.h\"\n#include \"testutil.h\"\n\n\nclass T_ManagedExec : public ::testing::Test {\n};\n\n\nTEST_F(T_ManagedExec, RunShell) {\n int fd_stdin;\n int fd_stdout;\n int fd_stderr;\n bool retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr);\n EXPECT_TRUE(retval);\n\n Pipe shell_pipe(fd_stdout, fd_stdin);\n const char *command = \"echo \\\"Hello World\\\"\\n\";\n retval = shell_pipe.Write(command, strlen(command));\n EXPECT_TRUE(retval);\n\n char buffer[20];\n retval = shell_pipe.Read(&buffer, 11);\n EXPECT_TRUE(retval);\n buffer[11] = '\\0';\n\n EXPECT_EQ(0, strncmp(\"Hello World\", buffer, 12));\n}\n\n\nTEST_F(T_ManagedExec, ExecuteBinaryDoubleFork) {\n int fd_stdin, fd_stdout, fd_stderr;\n pid_t child_pid;\n\n \/\/ find gdb in the $PATH of this system\n const std::string gdb = GetExecutablePath(\"gdb\");\n ASSERT_NE(\"\", gdb) << \"gdb not found, but needed by this test case\";\n\n \/\/ spawn detached (double forked) child process\n const bool double_fork = true;\n bool retval = ExecuteBinary(&fd_stdin,\n &fd_stdout,\n &fd_stderr,\n gdb,\n std::vector<std::string>(),\n double_fork,\n &child_pid);\n \/\/ check if process is running\n ASSERT_TRUE(retval);\n EXPECT_EQ(0, kill(child_pid, 0));\n\n \/\/ check that the PPID of the process is 1 (belongs to init)\n pid_t child_parent_pid = GetParentPid(child_pid);\n EXPECT_EQ(1, child_parent_pid);\n\n \/\/ tell the process to terminate\n Pipe shell_pipe(fd_stdout, fd_stdin);\n const char *quit = \"quit\\n\";\n retval = shell_pipe.Write(quit, strlen(quit));\n EXPECT_TRUE(retval);\n shell_pipe.Close();\n close(fd_stderr);\n\n \/\/ wait for the child process to terminate\n const unsigned int timeout = 1000;\n unsigned int counter = 0;\n while (counter < timeout && kill(child_pid, 0) == 0) {\n usleep(5000);\n ++counter;\n }\n EXPECT_LT(counter, timeout) << \"detached process did not terminate in time\";\n}\n\n\nTEST_F(T_ManagedExec, ExecuteBinaryAsChild) {\n int fd_stdin, fd_stdout, fd_stderr;\n pid_t child_pid;\n pid_t my_pid = getpid();\n\n \/\/ spawn a child process (not double forked)\n const bool double_fork = false;\n bool retval = ExecuteBinary(&fd_stdin,\n &fd_stdout,\n &fd_stderr,\n \"gdb\",\n std::vector<std::string>(),\n double_fork,\n &child_pid);\n\n \/\/ check that the process is running\n ASSERT_TRUE(retval);\n EXPECT_EQ(0, kill(child_pid, 0));\n\n \/\/ check that we are the parent of the spawned process\n pid_t child_parent_pid = GetParentPid(child_pid);\n EXPECT_EQ(my_pid, child_parent_pid);\n\n \/\/ tell the process to terminate\n Pipe shell_pipe(fd_stdout, fd_stdin);\n const char *quit = \"quit\\n\";\n retval = shell_pipe.Write(quit, strlen(quit));\n EXPECT_TRUE(retval);\n shell_pipe.Close();\n close(fd_stderr);\n\n \/\/ wait for the child process to terminate\n int statloc;\n retval = waitpid(child_pid, &statloc, 0);\n EXPECT_NE(-1, retval);\n}\n<commit_msg>add a method to discover a debugger<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include \"..\/..\/cvmfs\/util.h\"\n#include \"testutil.h\"\n\n\nclass T_ManagedExec : public ::testing::Test {\n protected:\n std::string GetDebugger() const {\n \/\/ check if we have a GDB installed\n const std::string gdb = GetExecutablePath(\"gdb\");\n if (!gdb.empty()) {\n return gdb;\n }\n\n \/\/ maybe we are on a recent OS X and we find LLDB?\n return GetExecutablePath(\"lldb\");\n }\n};\n\n\nTEST_F(T_ManagedExec, RunShell) {\n int fd_stdin;\n int fd_stdout;\n int fd_stderr;\n bool retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr);\n EXPECT_TRUE(retval);\n\n Pipe shell_pipe(fd_stdout, fd_stdin);\n const char *command = \"echo \\\"Hello World\\\"\\n\";\n retval = shell_pipe.Write(command, strlen(command));\n EXPECT_TRUE(retval);\n\n char buffer[20];\n retval = shell_pipe.Read(&buffer, 11);\n EXPECT_TRUE(retval);\n buffer[11] = '\\0';\n\n EXPECT_EQ(0, strncmp(\"Hello World\", buffer, 12));\n}\n\n\nTEST_F(T_ManagedExec, ExecuteBinaryDoubleFork) {\n int fd_stdin, fd_stdout, fd_stderr;\n pid_t child_pid;\n\n \/\/ find gdb in the $PATH of this system\n const std::string gdb = GetExecutablePath(\"gdb\");\n ASSERT_NE(\"\", gdb) << \"gdb not found, but needed by this test case\";\n\n \/\/ spawn detached (double forked) child process\n const bool double_fork = true;\n bool retval = ExecuteBinary(&fd_stdin,\n &fd_stdout,\n &fd_stderr,\n gdb,\n std::vector<std::string>(),\n double_fork,\n &child_pid);\n \/\/ check if process is running\n ASSERT_TRUE(retval);\n EXPECT_EQ(0, kill(child_pid, 0));\n\n \/\/ check that the PPID of the process is 1 (belongs to init)\n pid_t child_parent_pid = GetParentPid(child_pid);\n EXPECT_EQ(1, child_parent_pid);\n\n \/\/ tell the process to terminate\n Pipe shell_pipe(fd_stdout, fd_stdin);\n const char *quit = \"quit\\n\";\n retval = shell_pipe.Write(quit, strlen(quit));\n EXPECT_TRUE(retval);\n shell_pipe.Close();\n close(fd_stderr);\n\n \/\/ wait for the child process to terminate\n const unsigned int timeout = 1000;\n unsigned int counter = 0;\n while (counter < timeout && kill(child_pid, 0) == 0) {\n usleep(5000);\n ++counter;\n }\n EXPECT_LT(counter, timeout) << \"detached process did not terminate in time\";\n}\n\n\nTEST_F(T_ManagedExec, ExecuteBinaryAsChild) {\n int fd_stdin, fd_stdout, fd_stderr;\n pid_t child_pid;\n pid_t my_pid = getpid();\n\n \/\/ spawn a child process (not double forked)\n const bool double_fork = false;\n bool retval = ExecuteBinary(&fd_stdin,\n &fd_stdout,\n &fd_stderr,\n \"gdb\",\n std::vector<std::string>(),\n double_fork,\n &child_pid);\n\n \/\/ check that the process is running\n ASSERT_TRUE(retval);\n EXPECT_EQ(0, kill(child_pid, 0));\n\n \/\/ check that we are the parent of the spawned process\n pid_t child_parent_pid = GetParentPid(child_pid);\n EXPECT_EQ(my_pid, child_parent_pid);\n\n \/\/ tell the process to terminate\n Pipe shell_pipe(fd_stdout, fd_stdin);\n const char *quit = \"quit\\n\";\n retval = shell_pipe.Write(quit, strlen(quit));\n EXPECT_TRUE(retval);\n shell_pipe.Close();\n close(fd_stderr);\n\n \/\/ wait for the child process to terminate\n int statloc;\n retval = waitpid(child_pid, &statloc, 0);\n EXPECT_NE(-1, retval);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2008 Free Software Foundation, Inc.\n*\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n\n\n\n#include \"Timeval.h\"\n#include <iostream>\n#include <assert.h>\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n\tTimeval then(10000);\n\tassert(then.elapsed() == -10000);\n\tcerr << then << \" elapsed: \" << then.elapsed() << endl;\n\tdouble then_seconds = then.seconds();\n\tdouble last_now = Timeval().seconds();\n\tlong last_remaining = 10000;\n\tint loops = 0;\n\n\twhile (!then.passed()) {\n\t\tdouble tnow = Timeval().seconds();\n\t\tcerr << \"now: \" << tnow << \" then: \" << then << \" remaining: \" << then.remaining() << endl;\n\t\tassert(last_now <= tnow && last_remaining >= then.remaining());\n\t\tassert(then_seconds == then.seconds());\n\t\tusleep(500000);\n\t\tloops++;\n\t}\n\tcerr << \"now: \" << Timeval() << \" then: \" << then << \" remaining: \" << then.remaining() << endl;\n\tassert(then.remaining() <= 0);\n\tassert(loops >= 18);\n\n\tprintf(\"Done\\n\");\n}\n<commit_msg>tests: TimevalTest: refactor and avoid double comparison<commit_after>\/*\n* Copyright 2008 Free Software Foundation, Inc.\n*\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n\n\n\n#include \"Timeval.h\"\n#include <iostream>\n#include <assert.h>\n#include <sys\/time.h>\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n\tlong last_remaining = 10000;\n\tTimeval then(last_remaining);\n\tassert(then.elapsed() == -last_remaining);\n\tcerr << then << \" elapsed: \" << then.elapsed() << endl;\n\n\t\/* Check that last_remaining parameter affects setting time in the future *\/\n\tusleep(10000);\n\tdouble increased_time_secs = Timeval().seconds();\n\tassert(increased_time_secs <= then.seconds());\n\n\tstruct timespec invariant_time = then.timespec();\n\tint loops = 0;\n\n\twhile (!then.passed()) {\n\t\tstruct timespec tspecnow = then.timespec();\n\t\tcerr << \"now: \" << Timeval().seconds() << \" then: \" << then << \" remaining: \" << then.remaining() << endl;\n\t\tassert(last_remaining >= then.remaining());\n\t\tassert(tspecnow.tv_sec == invariant_time.tv_sec && tspecnow.tv_nsec == invariant_time.tv_nsec);\n\t\tusleep(500000);\n\t\tloops++;\n\t}\n\tcerr << \"now: \" << Timeval() << \" then: \" << then << \" remaining: \" << then.remaining() << endl;\n\tassert(then.remaining() <= 0);\n\tassert(loops >= 18);\n\n\tprintf(\"Done\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ting\/debug.hpp>\n#include <algorithm>\n#include <ting\/Buffer.hpp>\n\n#include \"..\/src\/cliser\/ServerThread.hpp\"\n#include \"..\/src\/cliser\/ClientThread.hpp\"\n\n\n\n\nnamespace{\nconst unsigned DMaxConnections = 63;\n\nconst ting::u32 DMaxCnt = 16384;\nconst ting::u16 DPort = 13666;\nconst char* DIpAddress = \"127.0.0.1\";\n}\n\n\n\nclass Connection : public cliser::Connection{\npublic:\n\n\tting::StaticBuffer<ting::u8, sizeof(ting::u32)> rbuf;\n\tting::Inited<unsigned, 0> rbufBytes;\n\n\tting::Inited<ting::u32, 0> cnt;\n\n\tting::Inited<ting::u32, 0> rcnt;\n\n\tting::Inited<bool, false> isConnected;\n\n\tConnection(){\n\/\/\t\tTRACE(<< \"Connection::\" << __func__ << \"(): invoked\" << std::endl)\n\t}\n\n\t~Connection(){\n\/\/\t\tTRACE(<< \"Connection::\" << __func__ << \"(): invoked\" << std::endl)\n\t}\n\n\tvoid SendPortion(){\n\t\tASSERT_INFO(this->cnt <= DMaxCnt, \"this->cnt = \" << this->cnt)\n\n\t\tif(this->cnt == DMaxCnt){\n\t\t\tif(this->rcnt == DMaxCnt){\n\t\t\t\tthis->Disconnect_ts();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tting::Array<ting::u8> buf(sizeof(ting::u32) * ( (std::min)(ting::u32((0xffff + 1) \/ sizeof(ting::u32)), DMaxCnt - this->cnt)) );\n\n\t\tASSERT(buf.Size() > 0)\n\n\t\tASSERT_INFO((buf.Size() % sizeof(ting::u32)) == 0, \"buf.Size() = \" << buf.Size() << \" (buf.Size() % sizeof(ting::u32)) = \" << (buf.Size() % sizeof(ting::u32)))\n\n\t\tfor(ting::u8* p = buf.Begin(); p != buf.End(); p += sizeof(ting::u32)){\n\t\t\tting::Serialize32(this->cnt, p);\n\t\t\t++this->cnt;\n\t\t}\n\n\t\tthis->Send_ts(buf);\n\t}\n\n\n\tvoid HandleReceivedData(const ting::Buffer<ting::u8>& d){\n\t\tfor(const ting::u8* p = d.Begin(); p != d.End(); ++p){\n\t\t\tthis->rbuf[this->rbufBytes] = *p;\n\t\t\t++this->rbufBytes;\n\n\t\t\tif(this->rbufBytes == this->rbuf.Size()){\n\t\t\t\tthis->rbufBytes = 0;\n\t\t\t\tting::u32 num = ting::Deserialize32(this->rbuf.Begin());\n\t\t\t\tASSERT_INFO_ALWAYS(this->rcnt == num, \"num = \" << num << \" rcnt = \" << this->rcnt)\n\t\t\t\t++this->rcnt;\n\t\t\t}\n\t\t}\n\n\t\tASSERT_INFO(this->rcnt <= DMaxCnt, \"this->rcnt = \" << this->rcnt)\n\n\t\tif(this->rcnt == DMaxCnt){\n\t\t\tif(this->cnt == DMaxCnt){\n\t\t\t\tthis->Disconnect_ts();\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\tstatic ting::Ref<Connection> New(){\n\t\treturn ting::Ref<Connection>(new Connection());\n\t}\n};\n\n\n\nclass Server : private cliser::Listener, public cliser::ServerThread{\npublic:\n\tServer() :\n\t\t\tcliser::Listener(),\n\t\t\tcliser::ServerThread(DPort, 2, this, true, 100)\n\t{}\n\n\t~Server(){\n\t\tASSERT_INFO_ALWAYS(this->numConnections == 0, \"this->numConnections = \" << this->numConnections)\n\t}\nprivate:\n\tting::Mutex numConsMut;\n\tting::Inited<unsigned, 0> numConnections;\n\t\n\t\/\/override\n\tting::Ref<cliser::Connection> CreateConnectionObject(){\n\t\treturn Connection::New();\n\t}\n\n\t\/\/override\n\tvoid OnConnected_ts(const ting::Ref<cliser::Connection>& c){\n\t\tTRACE_ALWAYS(<< \"Server::OnDisconnected_ts(): CONNECTED!!!\" << std::endl)\n\n\t\tting::Ref<Connection> conn = c.StaticCast<Connection>();\n\t\tASSERT_ALWAYS(!conn->isConnected)\n\t\tconn->isConnected = true;\n\n\t\t{\n\t\t\tting::Mutex::Guard mutexGuard(this->numConsMut);\n\t\t\t++(this->numConnections);\n\t\t\tASSERT_INFO_ALWAYS(this->numConnections <= 2 * DMaxConnections, \"this->numConnections = \" << this->numConnections)\n\t\t}\n\t\t\n\t\tTRACE_ALWAYS(<< \"Server: sending data\" << std::endl)\n\t\tc.StaticCast<Connection>()->SendPortion();\n\t}\n\n\t\/\/override\n\tvoid OnDisconnected_ts(const ting::Ref<cliser::Connection>& c){\n\t\tTRACE_ALWAYS(<< \"Server::OnDisconnected_ts(): DISCONNECTED!!!\" << std::endl)\n\n\t\tting::Ref<Connection> conn = c.StaticCast<Connection>();\n\t\tASSERT_INFO_ALWAYS(conn->isConnected, \"Server: disconnected non-connected connection\")\n\t\tconn->isConnected = false;\n\n\t\t{\n\t\t\tting::Mutex::Guard mutexGuard(this->numConsMut);\n\t\t\t--(this->numConnections);\n\t\t\tASSERT_INFO_ALWAYS(this->numConnections <= 2 * DMaxConnections, \"this->numConnections = \" << this->numConnections)\n\t\t}\n\t}\n\n\tclass HandleDataMessage : public ting::Message{\n\t\tting::Ref<Connection> conn;\n\tpublic:\n\t\tHandleDataMessage(const ting::Ref<Connection>& conn) :\n\t\t\t\tconn(conn)\n\t\t{}\n\n\t\t\/\/override\n\t\tvoid Handle(){\n\t\t\tif(ting::Array<ting::u8> d = this->conn->GetReceivedData_ts()){\n\t\t\t\tthis->conn->HandleReceivedData(d);\n\t\t\t}\n\t\t}\n\t};\n\n\t\/\/override\n\tbool OnDataReceived_ts(const ting::Ref<cliser::Connection>& c, const ting::Buffer<ting::u8>& d){\n\t\tTRACE_ALWAYS(<< \"Server: data received\" << std::endl)\n\t\tthis->PushMessage(\n\t\t\t\tting::Ptr<ting::Message>(\n\t\t\t\t\t\tnew HandleDataMessage(c.StaticCast<Connection>())\n\t\t\t\t\t)\n\t\t\t);\n\n\t\treturn false;\n\t}\n\n\t\/\/override\n\tvoid OnDataSent_ts(const ting::Ref<cliser::Connection>& c, unsigned numPacketsInQueue, bool addedToQueue){\n\t\tif(numPacketsInQueue >= 2)\n\t\t\treturn;\n\n\t\tTRACE_ALWAYS(<< \"Server: sending data\" << std::endl)\n\t\tc.StaticCast<Connection>()->SendPortion();\n\t}\n};\n\n\n\nclass Client : private cliser::Listener, public cliser::ClientThread{\npublic:\n\tClient() :\n\t\t\tcliser::Listener(),\n\t\t\tcliser::ClientThread(DMaxConnections, this) \/\/max connections\n\t{}\n\n\t~Client(){\n\t\tASSERT_INFO_ALWAYS(this->numConnections == 0, \"this->numConnections = \" << this->numConnections)\n\t}\n\nprivate:\n\tting::Mutex numConsMut;\n\tting::Inited<unsigned, 0> numConnections;\n\n\t\/\/override\n\tting::Ref<cliser::Connection> CreateConnectionObject(){\n\t\treturn Connection::New();\n\t}\n\n\t\/\/override\n\tvoid OnConnected_ts(const ting::Ref<cliser::Connection>& c){\n\t\tTRACE_ALWAYS(<< \"Client::OnConnected_ts(): CONNECTED!!!\" << std::endl)\n\n\t\t{\n\t\t\tting::Mutex::Guard mutexGuard(this->numConsMut);\n\t\t\t++(this->numConnections);\n\t\t\tASSERT_INFO_ALWAYS(this->numConnections <= DMaxConnections, \"this->numConnections = \" << this->numConnections)\n\t\t}\n\n\t\tting::Ref<Connection> conn = c.StaticCast<Connection>();\n\t\tASSERT_ALWAYS(!conn->isConnected)\n\t\tconn->isConnected = true;\n\n\t\tTRACE_ALWAYS(<< \"Client: sending data\" << std::endl)\n\t\tconn->SendPortion();\n\t}\n\n\t\/\/override\n\tvoid OnDisconnected_ts(const ting::Ref<cliser::Connection>& c){\n\t\tting::Ref<Connection> conn = c.StaticCast<Connection>();\n\t\t\n\t\tif(conn->isConnected){\n\t\t\tTRACE_ALWAYS(<< \"Client::OnDisconnected_ts(): DISCONNECTED!!!\" << std::endl)\n\n\t\t\tconn->isConnected = false;\n\n\t\t\t{\n\t\t\t\tting::Mutex::Guard mutexGuard(this->numConsMut);\n\t\t\t\t--(this->numConnections);\n\t\t\t\tASSERT_INFO_ALWAYS(this->numConnections <= DMaxConnections, \"this->numConnections = \" << this->numConnections)\n\t\t\t}\n\t\t}else{\n\t\t\t\/\/if we get here then it is a connect request failure\n\t\t\tASSERT_INFO_ALWAYS(false, \"Connection failed\")\n\t\t}\n\n\t\tthis->Connect_ts(ting::IPAddress(DIpAddress, DPort));\n\t}\n\n\t\/\/override\n\tbool OnDataReceived_ts(const ting::Ref<cliser::Connection>& c, const ting::Buffer<ting::u8>& d){\n\t\tting::Ref<Connection> con = c.StaticCast<Connection>();\n\n\t\tcon->HandleReceivedData(d);\n\t\tTRACE_ALWAYS(<< \"Client: data received\" << std::endl)\n\t\treturn true;\n\t}\n\n\t\/\/override\n\tvoid OnDataSent_ts(const ting::Ref<cliser::Connection>& c, unsigned numPacketsInQueue, bool addedToQueue){\n\t\tif(numPacketsInQueue >= 2)\n\t\t\treturn;\n\t\t\n\t\tTRACE_ALWAYS(<< \"Client: sending data\" << std::endl)\n\t\tc.StaticCast<Connection>()->SendPortion();\n\t}\n};\n\n\n\nint main(int argc, char *argv[]){\n\tTRACE_ALWAYS(<< \"Cliser test\" << std::endl)\n\n\tunsigned msec = 20000;\n\n\tif(argc >= 2){\n\t\tif(std::string(\"0\") == argv[1]){\n\t\t\tmsec = 0;\n\t\t}\n\t}\n\n\tting::SocketLib socketsLib;\n\n\tServer server;\n\tserver.Start();\n\n\tting::Thread::Sleep(100);\/\/give server thread some time to start waiting on the socket\n\n\tClient client;\n\tclient.Start();\n\n\tfor(unsigned i = 0; i < client.MaxConnections(); ++i){\n\t\tclient.Connect_ts(ting::IPAddress(DIpAddress, DPort));\n\t}\n\n\tif(msec == 0){\n\t\twhile(true){\n\t\t\tting::Thread::Sleep(1000000);\n\t\t}\n\t}else{\n\t\tting::Thread::Sleep(20000);\n\t}\n\n\tclient.PushQuitMessage();\n\tclient.Join();\n\n\tserver.PushQuitMessage();\n\tserver.Join();\n\n\treturn 0;\n}\n<commit_msg>logging corrected<commit_after>#include <ting\/debug.hpp>\n#include <algorithm>\n#include <ting\/Buffer.hpp>\n\n#include \"..\/src\/cliser\/ServerThread.hpp\"\n#include \"..\/src\/cliser\/ClientThread.hpp\"\n\n\n\n\nnamespace{\nconst unsigned DMaxConnections = 63;\n\nconst ting::u32 DMaxCnt = 16384;\nconst ting::u16 DPort = 13666;\nconst char* DIpAddress = \"127.0.0.1\";\n}\n\n\n\nclass Connection : public cliser::Connection{\npublic:\n\n\tting::StaticBuffer<ting::u8, sizeof(ting::u32)> rbuf;\n\tting::Inited<unsigned, 0> rbufBytes;\n\n\tting::Inited<ting::u32, 0> cnt;\n\n\tting::Inited<ting::u32, 0> rcnt;\n\n\tting::Inited<bool, false> isConnected;\n\n\tConnection(){\n\/\/\t\tTRACE(<< \"Connection::\" << __func__ << \"(): invoked\" << std::endl)\n\t}\n\n\t~Connection(){\n\/\/\t\tTRACE(<< \"Connection::\" << __func__ << \"(): invoked\" << std::endl)\n\t}\n\n\tvoid SendPortion(){\n\t\tASSERT_INFO(this->cnt <= DMaxCnt, \"this->cnt = \" << this->cnt)\n\n\t\tif(this->cnt == DMaxCnt){\n\t\t\tif(this->rcnt == DMaxCnt){\n\t\t\t\tthis->Disconnect_ts();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tting::Array<ting::u8> buf(sizeof(ting::u32) * ( (std::min)(ting::u32((0xffff + 1) \/ sizeof(ting::u32)), DMaxCnt - this->cnt)) );\n\n\t\tASSERT(buf.Size() > 0)\n\n\t\tASSERT_INFO((buf.Size() % sizeof(ting::u32)) == 0, \"buf.Size() = \" << buf.Size() << \" (buf.Size() % sizeof(ting::u32)) = \" << (buf.Size() % sizeof(ting::u32)))\n\n\t\tfor(ting::u8* p = buf.Begin(); p != buf.End(); p += sizeof(ting::u32)){\n\t\t\tting::Serialize32(this->cnt, p);\n\t\t\t++this->cnt;\n\t\t}\n\n\t\tthis->Send_ts(buf);\n\t}\n\n\n\tvoid HandleReceivedData(const ting::Buffer<ting::u8>& d){\n\t\tfor(const ting::u8* p = d.Begin(); p != d.End(); ++p){\n\t\t\tthis->rbuf[this->rbufBytes] = *p;\n\t\t\t++this->rbufBytes;\n\n\t\t\tif(this->rbufBytes == this->rbuf.Size()){\n\t\t\t\tthis->rbufBytes = 0;\n\t\t\t\tting::u32 num = ting::Deserialize32(this->rbuf.Begin());\n\t\t\t\tASSERT_INFO_ALWAYS(this->rcnt == num, \"num = \" << num << \" rcnt = \" << this->rcnt)\n\t\t\t\t++this->rcnt;\n\t\t\t}\n\t\t}\n\n\t\tASSERT_INFO(this->rcnt <= DMaxCnt, \"this->rcnt = \" << this->rcnt)\n\n\t\tif(this->rcnt == DMaxCnt){\n\t\t\tif(this->cnt == DMaxCnt){\n\t\t\t\tthis->Disconnect_ts();\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\tstatic ting::Ref<Connection> New(){\n\t\treturn ting::Ref<Connection>(new Connection());\n\t}\n};\n\n\n\nclass Server : private cliser::Listener, public cliser::ServerThread{\npublic:\n\tServer() :\n\t\t\tcliser::Listener(),\n\t\t\tcliser::ServerThread(DPort, 2, this, true, 100)\n\t{}\n\n\t~Server(){\n\t\tASSERT_INFO_ALWAYS(this->numConnections == 0, \"this->numConnections = \" << this->numConnections)\n\t}\nprivate:\n\tting::Mutex numConsMut;\n\tting::Inited<unsigned, 0> numConnections;\n\t\n\t\/\/override\n\tting::Ref<cliser::Connection> CreateConnectionObject(){\n\t\treturn Connection::New();\n\t}\n\n\t\/\/override\n\tvoid OnConnected_ts(const ting::Ref<cliser::Connection>& c){\n\t\tTRACE_ALWAYS(<< \"Server::\" << __func__ << \"(): CONNECTED!!!\" << std::endl)\n\n\t\tting::Ref<Connection> conn = c.StaticCast<Connection>();\n\t\tASSERT_ALWAYS(!conn->isConnected)\n\t\tconn->isConnected = true;\n\n\t\t{\n\t\t\tting::Mutex::Guard mutexGuard(this->numConsMut);\n\t\t\t++(this->numConnections);\n\t\t\tASSERT_INFO_ALWAYS(this->numConnections <= 2 * DMaxConnections, \"this->numConnections = \" << this->numConnections)\n\t\t}\n\t\t\n\t\tTRACE_ALWAYS(<< \"Server: sending data\" << std::endl)\n\t\tc.StaticCast<Connection>()->SendPortion();\n\t}\n\n\t\/\/override\n\tvoid OnDisconnected_ts(const ting::Ref<cliser::Connection>& c){\n\t\tTRACE_ALWAYS(<< \"Server::\" << __func__ << \"(): DISCONNECTED!!!\" << std::endl)\n\n\t\tting::Ref<Connection> conn = c.StaticCast<Connection>();\n\t\tASSERT_INFO_ALWAYS(conn->isConnected, \"Server: disconnected non-connected connection\")\n\t\tconn->isConnected = false;\n\n\t\t{\n\t\t\tting::Mutex::Guard mutexGuard(this->numConsMut);\n\t\t\t--(this->numConnections);\n\t\t\tASSERT_INFO_ALWAYS(this->numConnections <= 2 * DMaxConnections, \"this->numConnections = \" << this->numConnections)\n\t\t}\n\t}\n\n\tclass HandleDataMessage : public ting::Message{\n\t\tting::Ref<Connection> conn;\n\tpublic:\n\t\tHandleDataMessage(const ting::Ref<Connection>& conn) :\n\t\t\t\tconn(conn)\n\t\t{}\n\n\t\t\/\/override\n\t\tvoid Handle(){\n\t\t\tif(ting::Array<ting::u8> d = this->conn->GetReceivedData_ts()){\n\t\t\t\tthis->conn->HandleReceivedData(d);\n\t\t\t}\n\t\t}\n\t};\n\n\t\/\/override\n\tbool OnDataReceived_ts(const ting::Ref<cliser::Connection>& c, const ting::Buffer<ting::u8>& d){\n\t\tTRACE_ALWAYS(<< \"Server: data received\" << std::endl)\n\t\tthis->PushMessage(\n\t\t\t\tting::Ptr<ting::Message>(\n\t\t\t\t\t\tnew HandleDataMessage(c.StaticCast<Connection>())\n\t\t\t\t\t)\n\t\t\t);\n\n\t\treturn false;\n\t}\n\n\t\/\/override\n\tvoid OnDataSent_ts(const ting::Ref<cliser::Connection>& c, unsigned numPacketsInQueue, bool addedToQueue){\n\t\tif(numPacketsInQueue >= 2)\n\t\t\treturn;\n\n\t\tTRACE_ALWAYS(<< \"Server: sending data\" << std::endl)\n\t\tc.StaticCast<Connection>()->SendPortion();\n\t}\n};\n\n\n\nclass Client : private cliser::Listener, public cliser::ClientThread{\npublic:\n\tClient() :\n\t\t\tcliser::Listener(),\n\t\t\tcliser::ClientThread(DMaxConnections, this) \/\/max connections\n\t{}\n\n\t~Client(){\n\t\tASSERT_INFO_ALWAYS(this->numConnections == 0, \"this->numConnections = \" << this->numConnections)\n\t}\n\nprivate:\n\tting::Mutex numConsMut;\n\tting::Inited<unsigned, 0> numConnections;\n\n\t\/\/override\n\tting::Ref<cliser::Connection> CreateConnectionObject(){\n\t\treturn Connection::New();\n\t}\n\n\t\/\/override\n\tvoid OnConnected_ts(const ting::Ref<cliser::Connection>& c){\n\t\tTRACE_ALWAYS(<< \"Client::\" << __func__ << \"(): CONNECTED!!!\" << std::endl)\n\n\t\t{\n\t\t\tting::Mutex::Guard mutexGuard(this->numConsMut);\n\t\t\t++(this->numConnections);\n\t\t\tASSERT_INFO_ALWAYS(this->numConnections <= DMaxConnections, \"this->numConnections = \" << this->numConnections)\n\t\t}\n\n\t\tting::Ref<Connection> conn = c.StaticCast<Connection>();\n\t\tASSERT_ALWAYS(!conn->isConnected)\n\t\tconn->isConnected = true;\n\n\t\tTRACE_ALWAYS(<< \"Client: sending data\" << std::endl)\n\t\tconn->SendPortion();\n\t}\n\n\t\/\/override\n\tvoid OnDisconnected_ts(const ting::Ref<cliser::Connection>& c){\n\t\tting::Ref<Connection> conn = c.StaticCast<Connection>();\n\t\t\n\t\tif(conn->isConnected){\n\t\t\tTRACE_ALWAYS(<< \"Client::\" << __func__ << \"(): DISCONNECTED!!!\" << std::endl)\n\n\t\t\tconn->isConnected = false;\n\n\t\t\t{\n\t\t\t\tting::Mutex::Guard mutexGuard(this->numConsMut);\n\t\t\t\t--(this->numConnections);\n\t\t\t\tASSERT_INFO_ALWAYS(this->numConnections <= DMaxConnections, \"this->numConnections = \" << this->numConnections)\n\t\t\t}\n\t\t}else{\n\t\t\t\/\/if we get here then it is a connect request failure\n\t\t\tASSERT_INFO_ALWAYS(false, \"Connection failed\")\n\t\t}\n\n\t\tthis->Connect_ts(ting::IPAddress(DIpAddress, DPort));\n\t}\n\n\t\/\/override\n\tbool OnDataReceived_ts(const ting::Ref<cliser::Connection>& c, const ting::Buffer<ting::u8>& d){\n\t\tting::Ref<Connection> con = c.StaticCast<Connection>();\n\n\t\tcon->HandleReceivedData(d);\n\t\tTRACE_ALWAYS(<< \"Client: data received\" << std::endl)\n\t\treturn true;\n\t}\n\n\t\/\/override\n\tvoid OnDataSent_ts(const ting::Ref<cliser::Connection>& c, unsigned numPacketsInQueue, bool addedToQueue){\n\t\tif(numPacketsInQueue >= 2)\n\t\t\treturn;\n\t\t\n\t\tTRACE_ALWAYS(<< \"Client: sending data\" << std::endl)\n\t\tc.StaticCast<Connection>()->SendPortion();\n\t}\n};\n\n\n\nint main(int argc, char *argv[]){\n\tTRACE_ALWAYS(<< \"Cliser test\" << std::endl)\n\n\tunsigned msec = 20000;\n\n\tif(argc >= 2){\n\t\tif(std::string(\"0\") == argv[1]){\n\t\t\tmsec = 0;\n\t\t}\n\t}\n\n\tting::SocketLib socketsLib;\n\n\tServer server;\n\tserver.Start();\n\n\tting::Thread::Sleep(100);\/\/give server thread some time to start waiting on the socket\n\n\tClient client;\n\tclient.Start();\n\n\tfor(unsigned i = 0; i < client.MaxConnections(); ++i){\n\t\tclient.Connect_ts(ting::IPAddress(DIpAddress, DPort));\n\t}\n\n\tif(msec == 0){\n\t\twhile(true){\n\t\t\tting::Thread::Sleep(1000000);\n\t\t}\n\t}else{\n\t\tting::Thread::Sleep(20000);\n\t}\n\n\tclient.PushQuitMessage();\n\tclient.Join();\n\n\tserver.PushQuitMessage();\n\tserver.Join();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\r\n * @mainpage\tCOSSB(Component-based Open & Simple Service Broker)\r\n * @details\tCOSSB is a software framework to support IoT service interoperability among the networked devices or gadgets scattered in WLAN environment.\r\n *\/\r\n\r\n\r\n\/**\r\n * @file\t\tengine.hpp\r\n * @brief\t\tCOSSB Engine\r\n * @author\t\tByunghun Hwang<bhhwang@nsynapse.com>\r\n * @date \t\t2015. 6. 9\r\n * @details\tCOSSB Engine main routine\r\n *\/\r\n\r\n#include <iostream>\r\n#include <csignal>\r\n#include <cstdlib>\r\n#include <unistd.h>\r\n#include <popt.h>\r\n#include <memory>\r\n\r\n#include \"cossb.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace cossb;\r\n\r\n\r\n\/**\r\n * @brief\tdestroy main instance\r\n * @details\tIt will be called by SIGINT signal\r\n *\/\r\nvoid destroy()\r\n{\r\n\tmanager::component_manager::get()->destroy();\r\n\tbroker::component_broker::get()->destroy();\r\n}\r\n\r\n\/**\r\n * @brief\tSIGINT signal callback function\r\n * @details\tStop all services and destroy all instances\r\n *\/\r\nvoid sigc_interrupt(int param) { destroy();\texit(0); }\r\n\r\n\/**\r\n * @brief\tMain routine\r\n * @param\tcommand\r\n * @details\tStart with default components\r\n *\/\r\nint main(int argc, char* argv[])\r\n{\r\n\tsignal(SIGINT, sigc_interrupt);\r\n\r\n\tchar* config_file = nullptr;\r\n\tstruct poptOption optionTable[] = {\r\n\t\t\t{\"run\", 'r', POPT_ARG_NONE, 0, 'r', \"Run Engine with default configuration\", \"\"},\r\n\t\t\t{\"version\", 'v', POPT_ARG_NONE, 0, 'v', \"Version\", \"version\"},\r\n\t\t\t{\"config\", 'c', POPT_ARG_STRING, (void*)config_file, 'c', \"Open config file\", \"XML Config file\"},\r\n\t\t\t{\"debug\", 'd', POPT_ARG_NONE, 0, 'd', \"DEBUG mode\", \"\"},\r\n\t\t\tPOPT_AUTOHELP\r\n\t\t\tPOPT_TABLEEND\r\n\t};\r\n\tpoptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);\r\n\tpoptSetOtherOptionHelp(optionCon, \"<option>\");\r\n\r\n\tif(argc<2)\r\n\t{\r\n\t\tdestroy();\r\n\t\texit(0);\r\n\t}\r\n\r\n\tint opt = 0;\r\n\twhile((opt = poptGetNextOpt(optionCon))>=0)\r\n\t{\r\n\t\tswitch(opt)\r\n\t\t{\r\n\t\t\/\/ install components\r\n\t\tcase 'v':\r\n\t\t{\r\n\t\t\tstd::cout << COSSB_VERSION << \" (Released \" << __DATE__ << \" \" <<__TIME__ << \")\" << std::endl;\r\n\t\t\tdestroy();\r\n\t\t\texit(0);\r\n\r\n\t\t} break;\r\n\r\n\t\t\/\/load config file\r\n\t\tcase 'c':\r\n\t\t{\r\n\t\t\tstring config_file = (const char*)poptGetOptArg(optionCon);\r\n\t\t\tmanager::component_manager::get()->load_config(new config(config_file.c_str()));\r\n\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\t\/\/run in debug mode\r\n\t\tcase 'd':\r\n\t\t{\r\n\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase 'r':\r\n\t\t{\r\n\t\t\tmanager::component_manager::get()->load_config(new config(\"manifest.xml\"));\r\n\t\t\t\/\/manager::component_manager::get()\r\n\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tif (opt<-1)\r\n\t{\r\n\t\tcout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << \":\" << poptStrerror(opt) << endl;\r\n\t\tdestroy();\r\n\t\texit(0);\r\n\t}\r\n\r\n\tpause();\r\n\r\n\t\/\/notice, this function affects the checking memory leak, especially when you are using valgrind.\r\n\tpoptFreeContext(optionCon);\r\n\r\n\tdestroy();\r\n\texit(0);\r\n\r\n\treturn 0;\r\n}\r\n<commit_msg>clear un-necessary codes<commit_after>\/**\r\n * @mainpage\tCOSSB(Component-based Open & Simple Service Broker)\r\n * @details\tCOSSB is a software framework to support IoT service interoperability among the networked devices or gadgets scattered in WLAN environment.\r\n *\/\r\n\r\n\r\n\/**\r\n * @file\t\tengine.hpp\r\n * @brief\t\tCOSSB Engine\r\n * @author\t\tByunghun Hwang<bhhwang@nsynapse.com>\r\n * @date \t\t2015. 6. 9\r\n * @details\tCOSSB Engine main routine\r\n *\/\r\n\r\n#include <iostream>\r\n#include <csignal>\r\n#include <cstdlib>\r\n#include <unistd.h>\r\n#include <popt.h>\r\n#include <memory>\r\n\r\n#include \"cossb.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace cossb;\r\n\r\n\r\n\/**\r\n * @brief\tdestroy main instance\r\n * @details\tIt will be called by SIGINT signal\r\n *\/\r\nvoid destroy()\r\n{\r\n\tmanager::component_manager::get()->destroy();\r\n\tbroker::component_broker::get()->destroy();\r\n}\r\n\r\n\/**\r\n * @brief\tSIGINT signal callback function\r\n * @details\tStop all services and destroy all instances\r\n *\/\r\nvoid sigc_interrupt(int param) { destroy();\texit(0); }\r\n\r\n\/**\r\n * @brief\tMain routine\r\n * @param\tcommand\r\n * @details\tStart with default components\r\n *\/\r\nint main(int argc, char* argv[])\r\n{\r\n\tsignal(SIGINT, sigc_interrupt);\r\n\r\n\tchar* config_file = nullptr;\r\n\tstruct poptOption optionTable[] = {\r\n\t\t\t{\"run\", 'r', POPT_ARG_NONE, 0, 'r', \"Run Engine with default configuration\", \"\"},\r\n\t\t\t{\"version\", 'v', POPT_ARG_NONE, 0, 'v', \"Version\", \"version\"},\r\n\t\t\t{\"config\", 'c', POPT_ARG_STRING, (void*)config_file, 'c', \"Open configuration file\", \"XML Configuration file\"},\r\n\t\t\t{\"debug\", 'd', POPT_ARG_NONE, 0, 'd', \"DEBUG mode\", \"\"},\r\n\t\t\t{\"reset\", 'e', POPT_ARG_NONE, 0, 'e', \"Reset All system\", \"Clear and initialize the configurations\"},\r\n\t\t\tPOPT_AUTOHELP\r\n\t\t\tPOPT_TABLEEND\r\n\t};\r\n\tpoptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);\r\n\tpoptSetOtherOptionHelp(optionCon, \"<option>\");\r\n\r\n\tif(argc<2)\r\n\t{\r\n\t\tstd::cout << poptStrerror(POPT_ERROR_NOARG) << endl;\r\n\t\tdestroy();\r\n\t\texit(0);\r\n\t}\r\n\r\n\tint opt = 0;\r\n\twhile((opt = poptGetNextOpt(optionCon))>=0)\r\n\t{\r\n\t\tswitch(opt)\r\n\t\t{\r\n\t\t\/\/ install components\r\n\t\tcase 'v':\r\n\t\t{\r\n\t\t\tstd::cout << COSSB_VERSION << \" (Released \" << __DATE__ << \" \" <<__TIME__ << \")\" << std::endl;\r\n\t\t\tdestroy();\r\n\t\t\texit(0);\r\n\r\n\t\t} break;\r\n\r\n\t\t\/\/load configuration file\r\n\t\tcase 'c':\r\n\t\t{\r\n\t\t\tstring config_file = (const char*)poptGetOptArg(optionCon);\r\n\t\t\tmanager::component_manager::get()->load_config(new config(config_file.c_str()));\r\n\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\t\/\/run in debug mode\r\n\t\tcase 'd':\r\n\t\t{\r\n\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase 'r':\r\n\t\t{\r\n\t\t\tmanager::component_manager::get()->load_config(new config(\"manifest.xml\"));\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tif (opt<-1)\r\n\t{\r\n\t\tcout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << \":\" << poptStrerror(opt) << endl;\r\n\t\tdestroy();\r\n\t\texit(0);\r\n\t}\r\n\r\n\tpause();\r\n\r\n\t\/\/notice, this function affects the checking memory leak, especially when you are using valgrind.\r\n\tpoptFreeContext(optionCon);\r\n\r\n\tdestroy();\r\n\texit(0);\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * StellarLikeBlockchainExplorerAccountSynchronizer.cpp\n * ledger-core\n *\n * Created by Pierre Pollastri on 10\/07\/2019.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Ledger\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 all\n * 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 THE\n * SOFTWARE.\n *\n *\/\n\n#include \"StellarLikeBlockchainExplorerAccountSynchronizer.hpp\"\n\n#include <common\/AccountHelper.hpp>\n#include <wallet\/stellar\/StellarLikeAccount.hpp>\n\n\/**\n * Current version of the synchronization. Please keep this field up to date to ensure that we have proper migration\n * mechanism if the synchronizer needs to save more data in its state in the future (or modify current value). This\n * version allow smooth migration.\n *\/\nstatic const auto SYNCHRONIZATION_ALGORITHM_VERSION = 1;\n\nnamespace ledger {\n namespace core {\n\n StellarLikeBlockchainExplorerAccountSynchronizer::StellarLikeBlockchainExplorerAccountSynchronizer(\n const std::shared_ptr<WalletPool> &pool,\n const std::shared_ptr<StellarLikeBlockchainExplorer> &explorer) :\n DedicatedContext(pool->getDispatcher()->getSerialExecutionContext(\"stellar_like_account_synchronizer\")),\n _explorer(explorer),\n _database(pool->getDatabaseSessionPool()) {\n\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::reset(const std::shared_ptr<StellarLikeAccount> &account,\n const std::chrono::system_clock::time_point &toDate) {\n account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\")->editor()->clear();\n }\n\n std::shared_ptr<ProgressNotifier<BlockchainExplorerAccountSynchronizationResult>> StellarLikeBlockchainExplorerAccountSynchronizer::synchronize(\n const std::shared_ptr<StellarLikeAccount> &account) {\n if (_notifier != nullptr) {\n return _notifier;\n }\n _notifier = std::make_shared<ProgressNotifier<BlockchainExplorerAccountSynchronizationResult>>();\n synchronizeAccount(account);\n return _notifier;\n }\n\n bool StellarLikeBlockchainExplorerAccountSynchronizer::isSynchronizing() const {\n return _notifier != nullptr;\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr<StellarLikeAccount> &account) {\n auto self = shared_from_this();\n auto preferences = account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\");\n auto state = preferences\n ->template getObject<StellarLikeBlockchainExplorerAccountSynchronizer::SavedState>(\"state\")\n \/\/ provide default state if none exists yet\n .getValueOr(SavedState{});\n\n synchronizeAccount(account, state);\n }\n\n void\n StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr<StellarLikeAccount>& account,\n StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n auto address = account->getKeychain()->getAddress()->toString();\n auto self = shared_from_this();\n\n _explorer->getAccount(address)\n .onComplete(account->getContext(), [self, account, state = std::move(state)] (const Try<std::shared_ptr<stellar::Account>>& accountInfo) mutable {\n if (accountInfo.isFailure() && accountInfo.getFailure().getErrorCode() == api::ErrorCode::ACCOUNT_NOT_FOUND) {\n self->endSynchronization(state);\n } else if (accountInfo.isFailure()) {\n self->failSynchronization(accountInfo.getFailure());\n } else {\n soci::session sql(self->_database->getPool());\n account->updateAccountInfo(sql, *accountInfo.getValue());\n self->synchronizeTransactions(account, state);\n }\n });\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeTransactions(\n const std::shared_ptr<StellarLikeAccount> &account,\n StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n auto address = account->getKeychain()->getAddress()->toString();\n auto self = shared_from_this();\n \n _explorer->getTransactions(address, state.transactionPagingToken)\n .onComplete(account->getContext(), [self, account, state = std::move(state)] (const Try<stellar::TransactionVector>& txs) mutable {\n if (txs.isFailure()) {\n self->failSynchronization(txs.getFailure());\n } else {\n {\n soci::session sql(self->_database->getPool());\n soci::transaction tr(sql);\n\n for (const auto &tx : txs.getValue()) {\n auto const flag = account->putTransaction(sql, *tx);\n\n if (::ledger::core::account::isInsertedOperation(flag)) {\n ++state.insertedOperations;\n }\n\n state.lastBlockHeight = std::max(state.lastBlockHeight, tx->ledger);\n }\n tr.commit();\n }\n if (!txs.getValue().empty()) {\n state.transactionPagingToken = txs.getValue().back()->pagingToken;\n\n {\n auto preferences = account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\");\n preferences->editor()->putObject(\"state\", state)->commit();\n }\n \n self->synchronizeTransactions(account, state);\n } else {\n self->endSynchronization(state);\n }\n }\n });\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::endSynchronization(const StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n BlockchainExplorerAccountSynchronizationResult result;\n\n result.lastBlockHeight = state.lastBlockHeight;\n result.newOperations = state.insertedOperations;\n\n _notifier->success(std::move(result));\n _notifier = nullptr;\n }\n\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::failSynchronization(const Exception &ex) {\n _notifier->failure(ex);\n _notifier = nullptr;\n }\n }\n}\n<commit_msg>Log stellar transactions<commit_after>\/*\n *\n * StellarLikeBlockchainExplorerAccountSynchronizer.cpp\n * ledger-core\n *\n * Created by Pierre Pollastri on 10\/07\/2019.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Ledger\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 all\n * 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 THE\n * SOFTWARE.\n *\n *\/\n\n#include \"StellarLikeBlockchainExplorerAccountSynchronizer.hpp\"\n\n#include <common\/AccountHelper.hpp>\n#include <wallet\/stellar\/StellarLikeAccount.hpp>\n\n\/**\n * Current version of the synchronization. Please keep this field up to date to ensure that we have proper migration\n * mechanism if the synchronizer needs to save more data in its state in the future (or modify current value). This\n * version allow smooth migration.\n *\/\nstatic const auto SYNCHRONIZATION_ALGORITHM_VERSION = 1;\n\nnamespace ledger {\n namespace core {\n\n StellarLikeBlockchainExplorerAccountSynchronizer::StellarLikeBlockchainExplorerAccountSynchronizer(\n const std::shared_ptr<WalletPool> &pool,\n const std::shared_ptr<StellarLikeBlockchainExplorer> &explorer) :\n DedicatedContext(pool->getDispatcher()->getSerialExecutionContext(\"stellar_like_account_synchronizer\")),\n _explorer(explorer),\n _database(pool->getDatabaseSessionPool()) {\n\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::reset(const std::shared_ptr<StellarLikeAccount> &account,\n const std::chrono::system_clock::time_point &toDate) {\n account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\")->editor()->clear();\n }\n\n std::shared_ptr<ProgressNotifier<BlockchainExplorerAccountSynchronizationResult>> StellarLikeBlockchainExplorerAccountSynchronizer::synchronize(\n const std::shared_ptr<StellarLikeAccount> &account) {\n if (_notifier != nullptr) {\n return _notifier;\n }\n _notifier = std::make_shared<ProgressNotifier<BlockchainExplorerAccountSynchronizationResult>>();\n synchronizeAccount(account);\n return _notifier;\n }\n\n bool StellarLikeBlockchainExplorerAccountSynchronizer::isSynchronizing() const {\n return _notifier != nullptr;\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr<StellarLikeAccount> &account) {\n auto self = shared_from_this();\n auto preferences = account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\");\n auto state = preferences\n ->template getObject<StellarLikeBlockchainExplorerAccountSynchronizer::SavedState>(\"state\")\n \/\/ provide default state if none exists yet\n .getValueOr(SavedState{});\n\n synchronizeAccount(account, state);\n }\n\n void\n StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr<StellarLikeAccount>& account,\n StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n auto address = account->getKeychain()->getAddress()->toString();\n auto self = shared_from_this();\n\n _explorer->getAccount(address)\n .onComplete(account->getContext(), [self, account, state = std::move(state)] (const Try<std::shared_ptr<stellar::Account>>& accountInfo) mutable {\n if (accountInfo.isFailure() && accountInfo.getFailure().getErrorCode() == api::ErrorCode::ACCOUNT_NOT_FOUND) {\n self->endSynchronization(state);\n } else if (accountInfo.isFailure()) {\n self->failSynchronization(accountInfo.getFailure());\n } else {\n soci::session sql(self->_database->getPool());\n account->updateAccountInfo(sql, *accountInfo.getValue());\n self->synchronizeTransactions(account, state);\n }\n });\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeTransactions(\n const std::shared_ptr<StellarLikeAccount> &account,\n StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n auto address = account->getKeychain()->getAddress()->toString();\n auto self = shared_from_this();\n \n _explorer->getTransactions(address, state.transactionPagingToken)\n .onComplete(account->getContext(), [self, account, state = std::move(state)] (const Try<stellar::TransactionVector>& txs) mutable {\n if (txs.isFailure()) {\n self->failSynchronization(txs.getFailure());\n } else {\n {\n soci::session sql(self->_database->getPool());\n soci::transaction tr(sql);\n\n for (const auto &tx : txs.getValue()) {\n account->logger()->debug(\"XLM transaction hash: {}, paging_token: {}\", tx->hash, tx->pagingToken);\n auto const flag = account->putTransaction(sql, *tx);\n\n if (::ledger::core::account::isInsertedOperation(flag)) {\n ++state.insertedOperations;\n }\n\n state.lastBlockHeight = std::max(state.lastBlockHeight, tx->ledger);\n }\n tr.commit();\n }\n if (!txs.getValue().empty()) {\n state.transactionPagingToken = txs.getValue().back()->pagingToken;\n\n {\n auto preferences = account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\");\n preferences->editor()->putObject(\"state\", state)->commit();\n }\n \n self->synchronizeTransactions(account, state);\n } else {\n self->endSynchronization(state);\n }\n }\n });\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::endSynchronization(const StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n BlockchainExplorerAccountSynchronizationResult result;\n\n result.lastBlockHeight = state.lastBlockHeight;\n result.newOperations = state.insertedOperations;\n\n _notifier->success(std::move(result));\n _notifier = nullptr;\n }\n\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::failSynchronization(const Exception &ex) {\n _notifier->failure(ex);\n _notifier = nullptr;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * simple_testing.cpp\n *\n * Created on: Dec 21, 2012\n * Author: michael.hunter\n *\/\n#include \"simple_testing.hpp\"\n#include \"debug_new_and_delete.hpp\"\n\n#include <exception>\n#include <iostream>\n#include <time.h>\n#include <stdio.h>\n\nstd::vector<SimpleTest*>* SimpleTest::allTests = 0;\nstd::string* SimpleTest::lastFileName_ = 0;\n\nSimpleTest::SimpleTest(const char* testName, const char* fileName, int line)\n\t: isFailed_(false), testName_(testName), fileName_(fileName),\n\ttestStartLine_(line), passCount_(0), failCount_(0)\n{\n\tif (!allTests)\n\t\tallTests = new std::vector<SimpleTest*>();\n\tallTests->push_back(this);\n}\n\nvoid SimpleTest::checkMemory(int line)\n{\n\tswitch (checkConsistency()) {\n\tcase 1: fail(\"Heap corrupt\", line); break;\n\tcase 2: fail(\"Free header corrupt\", line); break;\n\tcase 3: fail(\"Free memory modified\", line); break;\n\t}\n\n\tif (isMultipleFree)\n\t\tfail(\"The same pointer has been freed twice\", line);\n}\n\nvoid SimpleTest::executeTest()\n{\n\ttry\n\t{\n\t\tif (!lastFileName_ || (*lastFileName_ != fileName_))\n\t\t{\n\t\t\tif (!lastFileName_)\n\t\t\t\tlastFileName_ = new std::string(fileName_);\n\t\t\telse\n\t\t\t\t*lastFileName_ = fileName_;\n\t\t\tstd::cout << \"-------------- \" << fileName_ << \"----------------\" << std::endl;\n\t\t}\n\t\tsize_t bytesBefore = bytesAllocatedCount;\n\t\tpassCount_ = 0;\n\t\tfailCount_ = 0;\n\t\trun();\n\t\tcheckMemory(testStartLine_);\n\t\tif (bytesBefore != bytesAllocatedCount)\n\t\t\tfail(\"Memory leak during test\", testStartLine_);\n\t\tstd::cout << testName_ << \": \" << passCount_ << \"\/\" << (passCount_ + failCount_) << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tfail(e.what(), testStartLine_);\n\t}\n\tcatch (...)\n\t{\n\t\tfail(\"Test threw an exception\", testStartLine_);\n\t}\n}\n\nint SimpleTest::runAllTests()\n{\n\tif (!allTests)\n\t{\n\t\tstd::cout << \"No Tests\" << std:: endl;\n\t\treturn 0;\n\t}\n\n\tstd::cout << \"Running \" << allTests->size() << \" tests\" << std:: endl;\n\tfor (auto test : *allTests)\n\t{\n\n\t\ttest->executeTest();\n\t\tif (test->isFailed_)\n\t\t\treturn 1;\n\t}\n\tstd::cout << \"All tests passed\" << std::endl;\n\treturn 0;\n}\n\nvoid SimpleTest::assert_(bool proposition, const char* msg, int line)\n{\n\tif (proposition)\n\t\tpass(msg);\n\telse\n\t\tfail(msg, line);\n}\n\nvoid SimpleTest::pass(const char* passText)\n{\n\tpassCount_ ++;\n\t\/\/std::cout << \"Passed: \" << passText << std::endl;\n}\n\nvoid SimpleTest::fail(const char* failText, int line)\n{\n\tisFailed_ = true;\n\tfailCount_ ++;\n#if _MSC_VER\n\tstd::cout << fileName_ << \"(\" << line << \"): error: \" << testName_ << \" failed: \" << failText << std::endl;\n#else\n\tstd::cout << fileName_ << \":\" << line << \": error: \" << testName_ << \" failed: \" << failText << std::endl;\n#endif\n}\n\nint main(int argc, char *argv[])\n{\n\tint result = SimpleTest::runAllTests();\n\n\tconst char* successFile = nullptr;\n\tfor (int i = 0; i < argc - 1; i ++)\n\t\tif (strcmp(argv[i], \"-s\") == 0)\n\t\t\tsuccessFile = argv[i+1];\n\n\tif (result == 0 && successFile)\n\t{\n\t\tstruct tm *current;\n\t\ttime_t now;\n\t\ttime(&now);\n\t\tcurrent = localtime(&now);\n\t\tFILE* fp = fopen(successFile, \"w\");\n\t\tfprintf(fp, \"Last successful build: %04u-%02i-%02i %02i:%02i:%02i\\n\",\n\t\t\tcurrent->tm_year + 1900,\n\t\t\tcurrent->tm_mon,\n\t\t\tcurrent->tm_mday,\n\t\t\tcurrent->tm_hour,\n\t\t\tcurrent->tm_min,\n\t\t\tcurrent->tm_sec\n\t\t\t);\n\t\tfclose(fp);\n\t}\n\n\treturn result;\n}\n<commit_msg>Report number of tests when successful<commit_after>\/*\n * simple_testing.cpp\n *\n * Created on: Dec 21, 2012\n * Author: michael.hunter\n *\/\n#include \"simple_testing.hpp\"\n#include \"debug_new_and_delete.hpp\"\n\n#include <exception>\n#include <iostream>\n#include <time.h>\n#include <stdio.h>\n\nstd::vector<SimpleTest*>* SimpleTest::allTests = 0;\nstd::string* SimpleTest::lastFileName_ = 0;\n\nSimpleTest::SimpleTest(const char* testName, const char* fileName, int line)\n\t: isFailed_(false), testName_(testName), fileName_(fileName),\n\ttestStartLine_(line), passCount_(0), failCount_(0)\n{\n\tif (!allTests)\n\t\tallTests = new std::vector<SimpleTest*>();\n\tallTests->push_back(this);\n}\n\nvoid SimpleTest::checkMemory(int line)\n{\n\tswitch (checkConsistency()) {\n\tcase 1: fail(\"Heap corrupt\", line); break;\n\tcase 2: fail(\"Free header corrupt\", line); break;\n\tcase 3: fail(\"Free memory modified\", line); break;\n\t}\n\n\tif (isMultipleFree)\n\t\tfail(\"The same pointer has been freed twice\", line);\n}\n\nvoid SimpleTest::executeTest()\n{\n\ttry\n\t{\n\t\tif (!lastFileName_ || (*lastFileName_ != fileName_))\n\t\t{\n\t\t\tif (!lastFileName_)\n\t\t\t\tlastFileName_ = new std::string(fileName_);\n\t\t\telse\n\t\t\t\t*lastFileName_ = fileName_;\n\t\t\tstd::cout << \"-------------- \" << fileName_ << \"----------------\" << std::endl;\n\t\t}\n\t\tsize_t bytesBefore = bytesAllocatedCount;\n\t\tpassCount_ = 0;\n\t\tfailCount_ = 0;\n\t\trun();\n\t\tcheckMemory(testStartLine_);\n\t\tif (bytesBefore != bytesAllocatedCount)\n\t\t\tfail(\"Memory leak during test\", testStartLine_);\n\t\tstd::cout << testName_ << \": \" << passCount_ << \"\/\" << (passCount_ + failCount_) << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tfail(e.what(), testStartLine_);\n\t}\n\tcatch (...)\n\t{\n\t\tfail(\"Test threw an exception\", testStartLine_);\n\t}\n}\n\nint SimpleTest::runAllTests()\n{\n\tif (!allTests)\n\t{\n\t\tstd::cout << \"No Tests\" << std:: endl;\n\t\treturn 0;\n\t}\n\n\tstd::cout << \"Running \" << allTests->size() << \" tests\" << std:: endl;\n\tfor (auto test : *allTests)\n\t{\n\n\t\ttest->executeTest();\n\t\tif (test->isFailed_)\n\t\t\treturn 1;\n\t}\n\tstd::cout << \"All \" << allTests->size() << \" tests passed\" << std::endl;\n\treturn 0;\n}\n\nvoid SimpleTest::assert_(bool proposition, const char* msg, int line)\n{\n\tif (proposition)\n\t\tpass(msg);\n\telse\n\t\tfail(msg, line);\n}\n\nvoid SimpleTest::pass(const char* passText)\n{\n\tpassCount_ ++;\n\t\/\/std::cout << \"Passed: \" << passText << std::endl;\n}\n\nvoid SimpleTest::fail(const char* failText, int line)\n{\n\tisFailed_ = true;\n\tfailCount_ ++;\n#if _MSC_VER\n\tstd::cout << fileName_ << \"(\" << line << \"): error: \" << testName_ << \" failed: \" << failText << std::endl;\n#else\n\tstd::cout << fileName_ << \":\" << line << \": error: \" << testName_ << \" failed: \" << failText << std::endl;\n#endif\n}\n\nint main(int argc, char *argv[])\n{\n\tint result = SimpleTest::runAllTests();\n\n\tconst char* successFile = nullptr;\n\tfor (int i = 0; i < argc - 1; i ++)\n\t\tif (strcmp(argv[i], \"-s\") == 0)\n\t\t\tsuccessFile = argv[i+1];\n\n\tif (result == 0 && successFile)\n\t{\n\t\tstruct tm *current;\n\t\ttime_t now;\n\t\ttime(&now);\n\t\tcurrent = localtime(&now);\n\t\tFILE* fp = fopen(successFile, \"w\");\n\t\tfprintf(fp, \"Last successful build: %04u-%02i-%02i %02i:%02i:%02i\\n\",\n\t\t\tcurrent->tm_year + 1900,\n\t\t\tcurrent->tm_mon,\n\t\t\tcurrent->tm_mday,\n\t\t\tcurrent->tm_hour,\n\t\t\tcurrent->tm_min,\n\t\t\tcurrent->tm_sec\n\t\t\t);\n\t\tfclose(fp);\n\t}\n\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ShaderNew.h\"\n#include \"DynamicTexture.h\"\n\n#include <GL\/GLee.h>\n#include <stdio.h>\n\nnamespace d2d\n{\n\n#define BUFFER_OFFSET(i) ((char *)NULL + (i))\n\nstatic const int ATTRIB_VERTEX = 0;\nstatic const int ATTRIB_TEXTCOORD = 1;\nstatic const int ATTRIB_COLOR = 2;\nstatic const int ATTRIB_ADDITIVE = 3;\n\nShaderNew* ShaderNew::m_instance = NULL;\n\nShaderNew* ShaderNew::Instance()\n{\n\tif (!m_instance)\n\t{\n\t\tm_instance = new ShaderNew();\n\t\tm_instance->load();\n\t}\n\treturn m_instance;\n}\n\nShaderNew::ShaderNew()\n{\n\tm_prog_curr = 0;\n\tm_prog_sprite = 0;\n\tm_prog_shape = 0;\n\n\tVertexBuffer = IndexBuffer = 0;\n\tm_sprite_count = 0;\n\tm_vb = NULL;\n\tm_tex = 0;\n\tm_fbo = 0;\n\n\tm_color = 0xffffffff;\n\tm_additive = 0;\n}\n\nvoid ShaderNew::SetSpriteColor(const Colorf& multi, const Colorf& add)\n{\n\t\/\/ ABGR\n\tm_color = ((int)(multi.a * 255 + 0.5f) << 24) | \n\t\t((int)(multi.b * 255 + 0.5f) << 16) | \n\t\t((int)(multi.g * 255 + 0.5f) << 8) | \n\t\t((int)(multi.r * 255 + 0.5f));\n\tm_additive = ((int)(add.a * 255 + 0.5f) << 24) | \n\t\t((int)(add.b * 255 + 0.5f) << 16) | \n\t\t((int)(add.g * 255 + 0.5f) << 8) | \n\t\t((int)(add.r * 255 + 0.5f));\n}\n\nvoid ShaderNew::SetShapeColor(const Colorf& col)\n{\n\tif (m_prog_curr == m_prog_shape) {\n\t\tglUniform4fv(m_col_loc, 1, (GLfloat*)(&col.r));\n\t}\n}\n\nvoid ShaderNew::sprite()\n{\n\tif (m_prog_curr != m_prog_sprite) {\n\t\tCommit();\n\n\t\tglEnable(GL_BLEND);\n\n\t\t\/\/ todo Դejoy2dõGL_ONE\n\t\t\/\/\t\tglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\t\tglUseProgram(m_prog_sprite);\n\t\tm_prog_curr = m_prog_sprite;\n\t}\n}\n\nvoid ShaderNew::shape()\n{\n\tif (m_prog_curr != m_prog_shape) {\n\t\tCommit();\n\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\t\tglUseProgram(m_prog_shape);\n\t\tm_prog_curr = m_prog_shape;\n\t}\n}\n\nvoid ShaderNew::null()\n{\n\tCommit();\n\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\tglUseProgram(0);\n\tm_prog_curr = 0;\n}\n\nvoid ShaderNew::release()\n{\n\tunload();\n}\n\nvoid ShaderNew::reload()\n{\n\tload();\n}\n\nvoid ShaderNew::SetTexture(int tex)\n{\n\tif (m_tex != tex) \n\t{\n\t\tCommit();\n\t\tm_tex = (GLuint)tex;\n\t\tglBindTexture(GL_TEXTURE_2D, m_tex);\n\t}\n}\n\nvoid ShaderNew::SetFBO(int fbo)\n{\n\tif (m_fbo != fbo) \n\t{\n\t\tCommit();\n\t\tm_fbo = (GLuint)fbo;\n\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);\n\t}\n}\n\nvoid ShaderNew::Draw(const float vb[16], int texid)\n{\n\tif (m_fbo == 1) {\n\t\tint zz = 0;\n\t}\n\n\tSetTexture(texid);\n\n\tCopyVertex(vb);\n\tif (++m_sprite_count >= MAX_COMMBINE) {\n\t\tCommit();\n\t}\n}\n\nvoid ShaderNew::Flush()\n{\n\tCommit();\n\n\tDynamicTexture::Instance()->DebugDraw();\n}\n\nvoid ShaderNew::load()\n{\n#if 0\n\t#define FLOAT_PRECISION \\\n\t\"#ifdef GL_FRAGMENT_PRECISION_HIGH \\n\" \\\n\t\"precision highp float; \\n\" \\\n\t\"#else \\n\" \\\n\t\"precision lowp float; \\n\" \\\n\t\"#endif \\n\"\n#else\n\t#define FLOAT_PRECISION \\\n\t\"precision lowp float; \\n\"\n#endif\n\n\tstatic const char * sprite_vs =\n\t\tFLOAT_PRECISION\n\t\t\"attribute vec4 position; \\n\"\n\t\t\"attribute vec2 texcoord; \\n\"\n\t\t\"attribute vec4 color; \\n\"\n\t\t\"attribute vec4 additive; \\n\"\n\t\t\"\\n\"\n\t\t\"varying vec2 v_texcoord; \\n\"\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"varying vec4 v_fragmentAddi; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\"\n\t\t\" gl_Position = position; \"\n \t\t\" v_fragmentColor = color \/ 255.0; \\n\"\n \t\t\" v_fragmentAddi = additive \/ 255.0; \\n\"\n\t\t\" v_texcoord = texcoord; \\n\"\n\t\t\"} \\n\"\n\t\t;\n\n\tstatic const char * sprite_fs =\n\t\tFLOAT_PRECISION\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"varying vec4 v_fragmentAddi; \\n\"\n\t\t\"varying vec2 v_texcoord; \\n\"\n\t\t\"uniform sampler2D texture0; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\" \n \t\t\" vec4 tmp = texture2D(texture0, v_texcoord); \\n\"\n \t\t\" gl_FragColor.xyz = tmp.xyz * v_fragmentColor.xyz; \\n\"\n \t\t\" gl_FragColor.w = tmp.w; \\n\"\n \t\t\" gl_FragColor *= v_fragmentColor.w; \\n\"\n \t\t\" gl_FragColor.xyz += v_fragmentAddi.xyz * tmp.w; \\n\"\n\t\t\"} \\n\"\n\t\t;\n\n\tstatic const char* font_fs = \n\t\tFLOAT_PRECISION\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"varying vec2 v_texcoord; \\n\"\n\t\t\"uniform sampler2D texture0; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\" \n\t\t\" float mask = texture2D(texture0, v_texcoord).a; \\n\"\n\t\t\" vec4 clr; \\n\"\n\t\t\" clr.rgb = vec3(1.0, 0.0, 0.0); \\n\"\n\t\t\" if (mask < 0.5)\t\t\t\t \\n\"\n\t\t\" clr.a = 0.0; \\n\"\n\t\t\" else \\n\"\n\t\t\" clr.a = 1.0; \\n\"\n\t\t\" gl_FragColor = clr; \\n\"\n\t\t\"} \\n\"\n\t\t;\n\n\tstatic const char * shape_vs =\n\t\tFLOAT_PRECISION\n\t\t\"uniform vec4 color; \\n\"\n\t\t\"\\n\"\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\"\n\t\t\" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; \"\n\t\t\" v_fragmentColor = color; \\n\"\n\t\t\"} \\n\"\n\t\t;\n\n\tstatic const char * shape_fs =\n\t\tFLOAT_PRECISION\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\" \n\t\t\" gl_FragColor = v_fragmentColor;\"\n\t\t\"} \\n\"\n\t\t;\n\n\n\tglEnable(GL_BLEND);\n\t\/\/ todo Դejoy2dõGL_ONE\n\t\/\/glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\tm_prog_sprite = InitShader(sprite_fs, sprite_vs);\n\tm_prog_shape = InitShader(shape_fs, shape_vs);\n\tm_prog_font = InitShader(font_fs, sprite_vs);\n\n\tInitBuffers();\n\n\t\/\/ bind attr\n\tm_col_loc = glGetUniformLocation(m_prog_shape, \"color\");\n\n\tm_vb = new float[SPRITE_FLOAT_NUM * MAX_COMMBINE];\n}\n\nvoid ShaderNew::unload()\n{\n\/\/ \tdelete m_instance;\n\/\/ \tm_instance = NULL;\n\n\t\/\/ todo others\n\tglDeleteBuffers(1, &VertexBuffer);\n\tglDeleteBuffers(1, &IndexBuffer);\n\n\tdelete[] m_vb;\n\tm_vb = NULL;\n}\n\nint ShaderNew::InitShader(const char *FS, const char *VS)\n{\n\tGLuint prog = glCreateProgram();\n\n\tGLuint fs = CompileShader(FS, GL_FRAGMENT_SHADER);\n\tif (fs == 0) {\n\t\treturn 0;\n\t} else {\n\t\tglAttachShader(prog, fs);\n\t}\n\n\tGLuint vs = CompileShader(VS, GL_VERTEX_SHADER);\n\tif (vs == 0) {\n\t\treturn 0;\n\t} else {\n\t\tglAttachShader(prog, vs);\n\t}\n\n \t\/\/ attr location\n \tglBindAttribLocation(prog, ATTRIB_VERTEX, \"position\");\n \tglBindAttribLocation(prog, ATTRIB_TEXTCOORD, \"texcoord\");\n \tglBindAttribLocation(prog, ATTRIB_COLOR, \"color\");\n \tglBindAttribLocation(prog, ATTRIB_ADDITIVE, \"additive\");\n\n\t\/\/ link\n\tGLint status;\n\tglLinkProgram(prog);\n\n\tglGetProgramiv(prog, GL_LINK_STATUS, &status);\n\tif (status == 0) {\n\t\treturn 0;\n\t}\n\n\t\/\/ detatch\n\tglDetachShader(prog, fs);\n\tglDeleteShader(fs);\n\tglDetachShader(prog, vs);\n\tglDeleteShader(vs);\n\n\treturn prog;\n}\n\nint ShaderNew::CompileShader(const char * source, int type)\n{\n\tGLint status;\n\n\tGLuint shader = glCreateShader(type);\n\tglShaderSource(shader, 1, &source, NULL);\n\tglCompileShader(shader);\n\n\tglGetShaderiv(shader, GL_COMPILE_STATUS, &status);\n\n\tif (status == GL_FALSE) {\n\t\tchar buf[1024];\n\t\tGLint len;\n\t\tglGetShaderInfoLog(shader, 1024, &len, buf);\n\n\t\tprintf(\"compile failed:%s\\n\"\n\t\t\t\"source:\\n %s\\n\",\n\t\t\tbuf, source);\n\t\tglDeleteShader(shader);\n\t\treturn 0;\n\t}\n\n\treturn shader;\t\n}\n\nvoid ShaderNew::InitBuffers()\n{\n\tglGenBuffers(1, &IndexBuffer);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer);\n\n\tsize_t size = MAX_COMMBINE * 6 * sizeof(GLushort);\n\tGLushort* idxs = new GLushort[size];\n\tint i;\n\tfor (i=0;i<MAX_COMMBINE;i++) \n\t{\n\t\tidxs[i*6] = i*4;\n\t\tidxs[i*6+1] = i*4+1;\n\t\tidxs[i*6+2] = i*4+2;\n\t\tidxs[i*6+3] = i*4;\n\t\tidxs[i*6+4] = i*4+2;\n\t\tidxs[i*6+5] = i*4+3;\n\t}\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, size, idxs, GL_STATIC_DRAW);\n\tdelete[] idxs;\n\n\tglGenBuffers(1, &VertexBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);\n}\n\nvoid ShaderNew::Commit()\n{\n\tif (m_sprite_count == 0) {\n\t\treturn;\n\t}\n\n\tif (m_fbo == 1) {\n\t\tint zz = 0;\n\t}\n\n\tsprite();\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, m_sprite_count * SPRITE_FLOAT_NUM * sizeof(float), &m_vb[0], GL_DYNAMIC_DRAW);\n\n\tglEnableVertexAttribArray(ATTRIB_VERTEX);\n\tglVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, GL_FALSE, SPRITE_FLOAT_NUM, BUFFER_OFFSET(0));\n\n\tglEnableVertexAttribArray(ATTRIB_TEXTCOORD);\n\tglVertexAttribPointer(ATTRIB_TEXTCOORD, 2, GL_FLOAT, GL_FALSE, SPRITE_FLOAT_NUM, BUFFER_OFFSET(8));\n\n\tglEnableVertexAttribArray(ATTRIB_COLOR);\n\tglVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_FALSE, SPRITE_FLOAT_NUM, BUFFER_OFFSET(16));\n\n\tglEnableVertexAttribArray(ATTRIB_ADDITIVE);\n\tglVertexAttribPointer(ATTRIB_ADDITIVE, 4, GL_UNSIGNED_BYTE, GL_FALSE, SPRITE_FLOAT_NUM, BUFFER_OFFSET(20)); \n\n\tglDrawElements(GL_TRIANGLES, 6 * m_sprite_count, GL_UNSIGNED_SHORT, 0);\n\n \tglBindBuffer(GL_ARRAY_BUFFER, 0);\n \tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n\tglDisableVertexAttribArray(ATTRIB_VERTEX);\n\tglDisableVertexAttribArray(ATTRIB_TEXTCOORD);\n\tglDisableVertexAttribArray(ATTRIB_COLOR);\n\tglDisableVertexAttribArray(ATTRIB_ADDITIVE);\n\n\tm_sprite_count = 0;\n}\n\nvoid ShaderNew::CopyVertex(const float vb[16])\n{\n\tfloat* ptr = m_vb + SPRITE_FLOAT_NUM * m_sprite_count;\n\tmemcpy(ptr, vb, 4 * sizeof(float));\n\tptr += 4;\n\tmemcpy(ptr, &m_color, sizeof(int));\n\tptr += 1;\n\tmemcpy(ptr, &m_additive, sizeof(int));\n\tptr += 1; \n\tmemcpy(ptr, &vb[4], 4 * sizeof(float));\n\tptr += 4;\n\tmemcpy(ptr, &m_color, sizeof(int));\n\tptr += 1;\n\tmemcpy(ptr, &m_additive, sizeof(int));\n\tptr += 1; \n\tmemcpy(ptr, &vb[8], 4 * sizeof(float));\n\tptr += 4;\n\tmemcpy(ptr, &m_color, sizeof(int));\n\tptr += 1;\n\tmemcpy(ptr, &m_additive, sizeof(int));\n\tptr += 1; \n\tmemcpy(ptr, &vb[12], 4 * sizeof(float));\n\tptr += 4;\n\tmemcpy(ptr, &m_color, sizeof(int));\n\tptr += 1; \n\tmemcpy(ptr, &m_additive, sizeof(int));\t\t\n}\n\n}<commit_msg>[FIXED] ShaderNew::Commit()中不应该切换shader<commit_after>#include \"ShaderNew.h\"\n#include \"DynamicTexture.h\"\n\n#include <GL\/GLee.h>\n#include <stdio.h>\n\nnamespace d2d\n{\n\n#define BUFFER_OFFSET(i) ((char *)NULL + (i))\n\nstatic const int ATTRIB_VERTEX = 0;\nstatic const int ATTRIB_TEXTCOORD = 1;\nstatic const int ATTRIB_COLOR = 2;\nstatic const int ATTRIB_ADDITIVE = 3;\n\nShaderNew* ShaderNew::m_instance = NULL;\n\nShaderNew* ShaderNew::Instance()\n{\n\tif (!m_instance)\n\t{\n\t\tm_instance = new ShaderNew();\n\t\tm_instance->load();\n\t}\n\treturn m_instance;\n}\n\nShaderNew::ShaderNew()\n{\n\tm_prog_curr = 0;\n\tm_prog_sprite = 0;\n\tm_prog_shape = 0;\n\n\tVertexBuffer = IndexBuffer = 0;\n\tm_sprite_count = 0;\n\tm_vb = NULL;\n\tm_tex = 0;\n\tm_fbo = 0;\n\n\tm_color = 0xffffffff;\n\tm_additive = 0;\n}\n\nvoid ShaderNew::SetSpriteColor(const Colorf& multi, const Colorf& add)\n{\n\t\/\/ ABGR\n\tm_color = ((int)(multi.a * 255 + 0.5f) << 24) | \n\t\t((int)(multi.b * 255 + 0.5f) << 16) | \n\t\t((int)(multi.g * 255 + 0.5f) << 8) | \n\t\t((int)(multi.r * 255 + 0.5f));\n\tm_additive = ((int)(add.a * 255 + 0.5f) << 24) | \n\t\t((int)(add.b * 255 + 0.5f) << 16) | \n\t\t((int)(add.g * 255 + 0.5f) << 8) | \n\t\t((int)(add.r * 255 + 0.5f));\n}\n\nvoid ShaderNew::SetShapeColor(const Colorf& col)\n{\n\tif (m_prog_curr == m_prog_shape) {\n\t\tglUniform4fv(m_col_loc, 1, (GLfloat*)(&col.r));\n\t}\n}\n\nvoid ShaderNew::sprite()\n{\n\tif (m_prog_curr != m_prog_sprite) {\n\t\tCommit();\n\n\t\tglEnable(GL_BLEND);\n\n\t\t\/\/ todo Դejoy2dõGL_ONE\n\t\t\/\/\t\tglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\t\tglUseProgram(m_prog_sprite);\n\t\tm_prog_curr = m_prog_sprite;\n\t}\n}\n\nvoid ShaderNew::shape()\n{\n\tif (m_prog_curr != m_prog_shape) {\n\t\tCommit();\n\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\t\tglUseProgram(m_prog_shape);\n\t\tm_prog_curr = m_prog_shape;\n\t}\n}\n\nvoid ShaderNew::null()\n{\n\tCommit();\n\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\tglUseProgram(0);\n\tm_prog_curr = 0;\n}\n\nvoid ShaderNew::release()\n{\n\tunload();\n}\n\nvoid ShaderNew::reload()\n{\n\tload();\n}\n\nvoid ShaderNew::SetTexture(int tex)\n{\n\tif (m_tex != tex) \n\t{\n\t\tCommit();\n\t\tm_tex = (GLuint)tex;\n\t\tglBindTexture(GL_TEXTURE_2D, m_tex);\n\t}\n}\n\nvoid ShaderNew::SetFBO(int fbo)\n{\n\tif (m_fbo != fbo) \n\t{\n\t\tCommit();\n\t\tm_fbo = (GLuint)fbo;\n\t\tglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);\n\t}\n}\n\nvoid ShaderNew::Draw(const float vb[16], int texid)\n{\n\tSetTexture(texid);\n\n\tCopyVertex(vb);\n\tif (++m_sprite_count >= MAX_COMMBINE) {\n\t\tCommit();\n\t}\n}\n\nvoid ShaderNew::Flush()\n{\n\tCommit();\n\n\tDynamicTexture::Instance()->DebugDraw();\n}\n\nvoid ShaderNew::load()\n{\n#if 0\n\t#define FLOAT_PRECISION \\\n\t\"#ifdef GL_FRAGMENT_PRECISION_HIGH \\n\" \\\n\t\"precision highp float; \\n\" \\\n\t\"#else \\n\" \\\n\t\"precision lowp float; \\n\" \\\n\t\"#endif \\n\"\n#else\n\t#define FLOAT_PRECISION \\\n\t\"precision lowp float; \\n\"\n#endif\n\n\tstatic const char * sprite_vs =\n\t\tFLOAT_PRECISION\n\t\t\"attribute vec4 position; \\n\"\n\t\t\"attribute vec2 texcoord; \\n\"\n\t\t\"attribute vec4 color; \\n\"\n\t\t\"attribute vec4 additive; \\n\"\n\t\t\"\\n\"\n\t\t\"varying vec2 v_texcoord; \\n\"\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"varying vec4 v_fragmentAddi; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\"\n\t\t\" gl_Position = position; \"\n \t\t\" v_fragmentColor = color \/ 255.0; \\n\"\n \t\t\" v_fragmentAddi = additive \/ 255.0; \\n\"\n\t\t\" v_texcoord = texcoord; \\n\"\n\t\t\"} \\n\"\n\t\t;\n\n\tstatic const char * sprite_fs =\n\t\tFLOAT_PRECISION\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"varying vec4 v_fragmentAddi; \\n\"\n\t\t\"varying vec2 v_texcoord; \\n\"\n\t\t\"uniform sampler2D texture0; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\" \n \t\t\" vec4 tmp = texture2D(texture0, v_texcoord); \\n\"\n \t\t\" gl_FragColor.xyz = tmp.xyz * v_fragmentColor.xyz; \\n\"\n \t\t\" gl_FragColor.w = tmp.w; \\n\"\n \t\t\" gl_FragColor *= v_fragmentColor.w; \\n\"\n \t\t\" gl_FragColor.xyz += v_fragmentAddi.xyz * tmp.w; \\n\"\n\t\t\"} \\n\"\n\t\t;\n\n\tstatic const char* font_fs = \n\t\tFLOAT_PRECISION\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"varying vec2 v_texcoord; \\n\"\n\t\t\"uniform sampler2D texture0; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\" \n\t\t\" float mask = texture2D(texture0, v_texcoord).a; \\n\"\n\t\t\" vec4 clr; \\n\"\n\t\t\" clr.rgb = vec3(1.0, 0.0, 0.0); \\n\"\n\t\t\" if (mask < 0.5)\t\t\t\t \\n\"\n\t\t\" clr.a = 0.0; \\n\"\n\t\t\" else \\n\"\n\t\t\" clr.a = 1.0; \\n\"\n\t\t\" gl_FragColor = clr; \\n\"\n\t\t\"} \\n\"\n\t\t;\n\n\tstatic const char * shape_vs =\n\t\tFLOAT_PRECISION\n\t\t\"uniform vec4 color; \\n\"\n\t\t\"\\n\"\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\"\n\t\t\" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; \"\n\t\t\" v_fragmentColor = color; \\n\"\n\t\t\"} \\n\"\n\t\t;\n\n\tstatic const char * shape_fs =\n\t\tFLOAT_PRECISION\n\t\t\"varying vec4 v_fragmentColor; \\n\"\n\t\t\"\\n\"\n\t\t\"void main() \\n\"\n\t\t\"{ \\n\" \n\t\t\" gl_FragColor = v_fragmentColor;\"\n\t\t\"} \\n\"\n\t\t;\n\n\n\tglEnable(GL_BLEND);\n\t\/\/ todo Դejoy2dõGL_ONE\n\t\/\/glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\tm_prog_sprite = InitShader(sprite_fs, sprite_vs);\n\tm_prog_shape = InitShader(shape_fs, shape_vs);\n\tm_prog_font = InitShader(font_fs, sprite_vs);\n\n\tInitBuffers();\n\n\t\/\/ bind attr\n\tm_col_loc = glGetUniformLocation(m_prog_shape, \"color\");\n\n\tm_vb = new float[SPRITE_FLOAT_NUM * MAX_COMMBINE];\n}\n\nvoid ShaderNew::unload()\n{\n\/\/ \tdelete m_instance;\n\/\/ \tm_instance = NULL;\n\n\t\/\/ todo others\n\tglDeleteBuffers(1, &VertexBuffer);\n\tglDeleteBuffers(1, &IndexBuffer);\n\n\tdelete[] m_vb;\n\tm_vb = NULL;\n}\n\nint ShaderNew::InitShader(const char *FS, const char *VS)\n{\n\tGLuint prog = glCreateProgram();\n\n\tGLuint fs = CompileShader(FS, GL_FRAGMENT_SHADER);\n\tif (fs == 0) {\n\t\treturn 0;\n\t} else {\n\t\tglAttachShader(prog, fs);\n\t}\n\n\tGLuint vs = CompileShader(VS, GL_VERTEX_SHADER);\n\tif (vs == 0) {\n\t\treturn 0;\n\t} else {\n\t\tglAttachShader(prog, vs);\n\t}\n\n \t\/\/ attr location\n \tglBindAttribLocation(prog, ATTRIB_VERTEX, \"position\");\n \tglBindAttribLocation(prog, ATTRIB_TEXTCOORD, \"texcoord\");\n \tglBindAttribLocation(prog, ATTRIB_COLOR, \"color\");\n \tglBindAttribLocation(prog, ATTRIB_ADDITIVE, \"additive\");\n\n\t\/\/ link\n\tGLint status;\n\tglLinkProgram(prog);\n\n\tglGetProgramiv(prog, GL_LINK_STATUS, &status);\n\tif (status == 0) {\n\t\treturn 0;\n\t}\n\n\t\/\/ detatch\n\tglDetachShader(prog, fs);\n\tglDeleteShader(fs);\n\tglDetachShader(prog, vs);\n\tglDeleteShader(vs);\n\n\treturn prog;\n}\n\nint ShaderNew::CompileShader(const char * source, int type)\n{\n\tGLint status;\n\n\tGLuint shader = glCreateShader(type);\n\tglShaderSource(shader, 1, &source, NULL);\n\tglCompileShader(shader);\n\n\tglGetShaderiv(shader, GL_COMPILE_STATUS, &status);\n\n\tif (status == GL_FALSE) {\n\t\tchar buf[1024];\n\t\tGLint len;\n\t\tglGetShaderInfoLog(shader, 1024, &len, buf);\n\n\t\tprintf(\"compile failed:%s\\n\"\n\t\t\t\"source:\\n %s\\n\",\n\t\t\tbuf, source);\n\t\tglDeleteShader(shader);\n\t\treturn 0;\n\t}\n\n\treturn shader;\t\n}\n\nvoid ShaderNew::InitBuffers()\n{\n\tglGenBuffers(1, &IndexBuffer);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer);\n\n\tsize_t size = MAX_COMMBINE * 6 * sizeof(GLushort);\n\tGLushort* idxs = new GLushort[size];\n\tint i;\n\tfor (i=0;i<MAX_COMMBINE;i++) \n\t{\n\t\tidxs[i*6] = i*4;\n\t\tidxs[i*6+1] = i*4+1;\n\t\tidxs[i*6+2] = i*4+2;\n\t\tidxs[i*6+3] = i*4;\n\t\tidxs[i*6+4] = i*4+2;\n\t\tidxs[i*6+5] = i*4+3;\n\t}\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, size, idxs, GL_STATIC_DRAW);\n\tdelete[] idxs;\n\n\tglGenBuffers(1, &VertexBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);\n}\n\nvoid ShaderNew::Commit()\n{\n\tif (m_sprite_count == 0) {\n\t\treturn;\n\t}\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, m_sprite_count * SPRITE_FLOAT_NUM * sizeof(float), &m_vb[0], GL_DYNAMIC_DRAW);\n\n\tglEnableVertexAttribArray(ATTRIB_VERTEX);\n\tglVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, GL_FALSE, SPRITE_FLOAT_NUM, BUFFER_OFFSET(0));\n\n\tglEnableVertexAttribArray(ATTRIB_TEXTCOORD);\n\tglVertexAttribPointer(ATTRIB_TEXTCOORD, 2, GL_FLOAT, GL_FALSE, SPRITE_FLOAT_NUM, BUFFER_OFFSET(8));\n\n\tglEnableVertexAttribArray(ATTRIB_COLOR);\n\tglVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_FALSE, SPRITE_FLOAT_NUM, BUFFER_OFFSET(16));\n\n\tglEnableVertexAttribArray(ATTRIB_ADDITIVE);\n\tglVertexAttribPointer(ATTRIB_ADDITIVE, 4, GL_UNSIGNED_BYTE, GL_FALSE, SPRITE_FLOAT_NUM, BUFFER_OFFSET(20)); \n\n\tglDrawElements(GL_TRIANGLES, 6 * m_sprite_count, GL_UNSIGNED_SHORT, 0);\n\n \tglBindBuffer(GL_ARRAY_BUFFER, 0);\n \tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n\tglDisableVertexAttribArray(ATTRIB_VERTEX);\n\tglDisableVertexAttribArray(ATTRIB_TEXTCOORD);\n\tglDisableVertexAttribArray(ATTRIB_COLOR);\n\tglDisableVertexAttribArray(ATTRIB_ADDITIVE);\n\n\tm_sprite_count = 0;\n}\n\nvoid ShaderNew::CopyVertex(const float vb[16])\n{\n\tfloat* ptr = m_vb + SPRITE_FLOAT_NUM * m_sprite_count;\n\tmemcpy(ptr, vb, 4 * sizeof(float));\n\tptr += 4;\n\tmemcpy(ptr, &m_color, sizeof(int));\n\tptr += 1;\n\tmemcpy(ptr, &m_additive, sizeof(int));\n\tptr += 1; \n\tmemcpy(ptr, &vb[4], 4 * sizeof(float));\n\tptr += 4;\n\tmemcpy(ptr, &m_color, sizeof(int));\n\tptr += 1;\n\tmemcpy(ptr, &m_additive, sizeof(int));\n\tptr += 1; \n\tmemcpy(ptr, &vb[8], 4 * sizeof(float));\n\tptr += 4;\n\tmemcpy(ptr, &m_color, sizeof(int));\n\tptr += 1;\n\tmemcpy(ptr, &m_additive, sizeof(int));\n\tptr += 1; \n\tmemcpy(ptr, &vb[12], 4 * sizeof(float));\n\tptr += 4;\n\tmemcpy(ptr, &m_color, sizeof(int));\n\tptr += 1; \n\tmemcpy(ptr, &m_additive, sizeof(int));\t\t\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2011 NVIDIA Corporation\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#include <thrust\/detail\/reference_base.h>\n#include <thrust\/detail\/type_traits.h>\n#include <thrust\/detail\/backend\/generic\/select_system.h>\n#include <thrust\/detail\/backend\/generic\/memory.h>\n#include <thrust\/iterator\/iterator_traits.h>\n#include <thrust\/swap.h>\n#include <iostream>\n\n#include <thrust\/system\/cpp\/detail\/tag.h>\n\nnamespace thrust\n{\nnamespace detail\n{\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n template<typename OtherElement, typename OtherPointer, typename OtherDerived>\n reference_base<Element,Pointer,Derived>\n ::reference_base(const reference_base<OtherElement,OtherPointer,OtherDerived> &other,\n typename thrust::detail::enable_if_convertible<\n typename reference_base<OtherElement,OtherPointer,OtherDerived>::pointer,\n pointer\n >::type *)\n : m_ptr(other.m_ptr)\n{}\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n reference_base<Element,Pointer,Derived>\n ::reference_base(const pointer &ptr)\n : m_ptr(ptr)\n{}\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::pointer\n reference_base<Element,Pointer,Derived>\n ::operator&() const\n{\n return m_ptr;\n} \/\/ end reference_base::operator&()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator=(const value_type &v)\n{\n assign_from(&v);\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator=()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator=(const reference_base &other)\n{\n assign_from(&other); \n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator=()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n template<typename OtherElement, typename OtherPointer, typename OtherDerived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator=(const reference_base<OtherElement,OtherPointer,OtherDerived> &other)\n{\n assign_from(&other);\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator=()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n reference_base<Element,Pointer,Derived>\n ::operator typename reference_base<Element,Pointer,Derived>::value_type () const\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::get_value;\n\n typedef typename thrust::iterator_space<pointer>::type space;\n\n return get_value(select_system(space()), m_ptr);\n} \/\/ end reference_base::operator value_type ()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n template<typename OtherPointer>\n void reference_base<Element,Pointer,Derived>\n ::assign_from(OtherPointer src)\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::assign_value;\n\n typedef typename thrust::iterator_space<pointer>::type space1;\n typedef typename thrust::iterator_space<OtherPointer>::type space2;\n\n assign_value(select_system(space1(), space2()), m_ptr, src);\n} \/\/ end assign_from()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n void reference_base<Element,Pointer,Derived>\n ::swap(derived_type &other)\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::iter_swap;\n\n typedef typename thrust::iterator_space<pointer>::type space;\n\n iter_swap(select_system(space(), space()), m_ptr, other.m_ptr);\n} \/\/ end reference_base::swap()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator++(void)\n{\n value_type temp = *this;\n ++temp;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator++()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::value_type\n reference_base<Element,Pointer,Derived>\n ::operator++(int)\n{\n value_type temp = *this;\n value_type result = temp++;\n *this = temp;\n return result;\n} \/\/ end reference_base::operator++()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator+=(const value_type &rhs)\n{\n value_type temp = *this;\n temp += rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator+=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator--(void)\n{\n value_type temp = *this;\n --temp;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator--()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::value_type\n reference_base<Element,Pointer,Derived>\n ::operator--(int)\n{\n value_type temp = *this;\n value_type result = temp--;\n *this = temp;\n return result;\n} \/\/ end reference_base::operator--()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator-=(const value_type &rhs)\n{\n value_type temp = *this;\n temp -= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator-=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator*=(const value_type &rhs)\n{\n value_type temp = *this;\n temp *= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator*=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator\/=(const value_type &rhs)\n{\n value_type temp = *this;\n temp \/= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator\/=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator%=(const value_type &rhs)\n{\n value_type temp = *this;\n temp %= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator%=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator<<=(const value_type &rhs)\n{\n value_type temp = *this;\n temp <<= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator<<=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator>>=(const value_type &rhs)\n{\n value_type temp = *this;\n temp >>= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator>>=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator&=(const value_type &rhs)\n{\n value_type temp = *this;\n temp &= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator&=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator|=(const value_type &rhs)\n{\n value_type temp = *this;\n temp |= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator|=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator^=(const value_type &rhs)\n{\n value_type temp = *this;\n temp ^= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator^=()\n\n \n} \/\/ end detail\n} \/\/ end thrust\n\n<commit_msg>Provide a specialization for is_convertible<reference_base<Element,Pointer,Derived>, Element><commit_after>\/*\n * Copyright 2008-2011 NVIDIA Corporation\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#include <thrust\/detail\/reference_base.h>\n#include <thrust\/detail\/type_traits.h>\n#include <thrust\/detail\/backend\/generic\/select_system.h>\n#include <thrust\/detail\/backend\/generic\/memory.h>\n#include <thrust\/iterator\/iterator_traits.h>\n#include <thrust\/swap.h>\n#include <iostream>\n\n#include <thrust\/system\/cpp\/detail\/tag.h>\n\nnamespace thrust\n{\nnamespace detail\n{\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n template<typename OtherElement, typename OtherPointer, typename OtherDerived>\n reference_base<Element,Pointer,Derived>\n ::reference_base(const reference_base<OtherElement,OtherPointer,OtherDerived> &other,\n typename thrust::detail::enable_if_convertible<\n typename reference_base<OtherElement,OtherPointer,OtherDerived>::pointer,\n pointer\n >::type *)\n : m_ptr(other.m_ptr)\n{}\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n reference_base<Element,Pointer,Derived>\n ::reference_base(const pointer &ptr)\n : m_ptr(ptr)\n{}\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::pointer\n reference_base<Element,Pointer,Derived>\n ::operator&() const\n{\n return m_ptr;\n} \/\/ end reference_base::operator&()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator=(const value_type &v)\n{\n assign_from(&v);\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator=()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator=(const reference_base &other)\n{\n assign_from(&other); \n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator=()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n template<typename OtherElement, typename OtherPointer, typename OtherDerived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator=(const reference_base<OtherElement,OtherPointer,OtherDerived> &other)\n{\n assign_from(&other);\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator=()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n reference_base<Element,Pointer,Derived>\n ::operator typename reference_base<Element,Pointer,Derived>::value_type () const\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::get_value;\n\n typedef typename thrust::iterator_space<pointer>::type space;\n\n return get_value(select_system(space()), m_ptr);\n} \/\/ end reference_base::operator value_type ()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n template<typename OtherPointer>\n void reference_base<Element,Pointer,Derived>\n ::assign_from(OtherPointer src)\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::assign_value;\n\n typedef typename thrust::iterator_space<pointer>::type space1;\n typedef typename thrust::iterator_space<OtherPointer>::type space2;\n\n assign_value(select_system(space1(), space2()), m_ptr, src);\n} \/\/ end assign_from()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n void reference_base<Element,Pointer,Derived>\n ::swap(derived_type &other)\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::iter_swap;\n\n typedef typename thrust::iterator_space<pointer>::type space;\n\n iter_swap(select_system(space(), space()), m_ptr, other.m_ptr);\n} \/\/ end reference_base::swap()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator++(void)\n{\n value_type temp = *this;\n ++temp;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator++()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::value_type\n reference_base<Element,Pointer,Derived>\n ::operator++(int)\n{\n value_type temp = *this;\n value_type result = temp++;\n *this = temp;\n return result;\n} \/\/ end reference_base::operator++()\n\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator+=(const value_type &rhs)\n{\n value_type temp = *this;\n temp += rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator+=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator--(void)\n{\n value_type temp = *this;\n --temp;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator--()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::value_type\n reference_base<Element,Pointer,Derived>\n ::operator--(int)\n{\n value_type temp = *this;\n value_type result = temp--;\n *this = temp;\n return result;\n} \/\/ end reference_base::operator--()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator-=(const value_type &rhs)\n{\n value_type temp = *this;\n temp -= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator-=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator*=(const value_type &rhs)\n{\n value_type temp = *this;\n temp *= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator*=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator\/=(const value_type &rhs)\n{\n value_type temp = *this;\n temp \/= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator\/=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator%=(const value_type &rhs)\n{\n value_type temp = *this;\n temp %= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator%=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator<<=(const value_type &rhs)\n{\n value_type temp = *this;\n temp <<= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator<<=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator>>=(const value_type &rhs)\n{\n value_type temp = *this;\n temp >>= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator>>=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator&=(const value_type &rhs)\n{\n value_type temp = *this;\n temp &= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator&=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator|=(const value_type &rhs)\n{\n value_type temp = *this;\n temp |= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator|=()\n\ntemplate<typename Element, typename Pointer, typename Derived>\n typename reference_base<Element,Pointer,Derived>::derived_type &\n reference_base<Element,Pointer,Derived>\n ::operator^=(const value_type &rhs)\n{\n value_type temp = *this;\n temp ^= rhs;\n *this = temp;\n return static_cast<derived_type&>(*this);\n} \/\/ end reference_base::operator^=()\n\n\/\/ XXX iterator_facade tries to instantiate the Reference\n\/\/ type when computing the answer to is_convertible<Reference,Value>\n\/\/ we can't do that at that point because reference\n\/\/ is not complete\n\/\/ WAR the problem by specializing is_convertible\ntemplate<typename Element, typename Pointer, typename Derived>\n struct is_convertible<reference_base<Element,Pointer,Derived>, Element>\n : thrust::detail::true_type\n{};\n\n \n} \/\/ end detail\n} \/\/ end thrust\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/eval\/eval\/value.h>\n#include <vespa\/eval\/eval\/value_codec.h>\n#include <vespa\/eval\/eval\/tensor_spec.h>\n#include <vespa\/eval\/tensor\/default_value_builder_factory.h>\n#include <vespa\/eval\/tensor\/mixed\/packed_mixed_tensor.h>\n#include <vespa\/eval\/tensor\/sparse\/sparse_tensor_value.h>\n#include <vespa\/eval\/tensor\/dense\/dense_tensor.h>\n#include <vespa\/vespalib\/gtest\/gtest.h>\n\nusing namespace vespalib;\nusing namespace vespalib::eval;\nusing namespace vespalib::tensor;\nusing namespace vespalib::eval::packed_mixed_tensor;\n\nValue::UP v_of(const TensorSpec &spec) {\n return value_from_spec(spec, DefaultValueBuilderFactory::get());\n}\n\nTEST(MakeInputTest, print_some_test_input) {\n auto dbl = v_of(TensorSpec(\"double\").add({}, 3.0));\n auto trivial = v_of(TensorSpec(\"tensor(x[1])\").add({{\"x\",0}}, 7.0));\n auto dense = v_of(TensorSpec(\"tensor<float>(x[2],y[3])\").add({{\"x\",1},{\"y\",2}}, 17.0));\n auto sparse = v_of(TensorSpec(\"tensor(x{},y{})\").add({{\"x\",\"foo\"},{\"y\",\"bar\"}}, 31.0));\n auto mixed = v_of(TensorSpec(\"tensor<float>(x[2],y{})\").add({{\"x\",1},{\"y\",\"quux\"}}, 42.0));\n\n EXPECT_TRUE(dynamic_cast<DoubleValue *>(dbl.get()));\n EXPECT_TRUE(dynamic_cast<DenseTensorView *>(trivial.get()));\n EXPECT_TRUE(dynamic_cast<DenseTensorView *>(dense.get()));\n EXPECT_TRUE(dynamic_cast<SparseTensorValue<double> *>(sparse.get()));\n EXPECT_TRUE(dynamic_cast<PackedMixedTensor *>(mixed.get()));\n\n EXPECT_EQ(dbl->as_double(), 3.0);\n EXPECT_EQ(trivial->cells().typify<double>()[0], 7.0);\n EXPECT_EQ(dense->cells().typify<float>()[5], 17.0);\n EXPECT_EQ(sparse->cells().typify<double>()[0], 31.0);\n EXPECT_EQ(mixed->cells().typify<float>()[1], 42.0);\n\n stringref y_look = \"bar\";\n stringref x_res = \"xxx\";\n auto view = sparse->index().create_view({1});\n view->lookup({&y_look});\n size_t ss = 12345;\n bool br = view->next_result({&x_res}, ss);\n EXPECT_TRUE(br);\n EXPECT_EQ(ss, 0);\n EXPECT_EQ(x_res, \"foo\");\n br = view->next_result({&x_res}, ss);\n EXPECT_FALSE(br);\n\n ss = 12345;\n view = mixed->index().create_view({});\n view->lookup({});\n br = view->next_result({&x_res}, ss);\n EXPECT_TRUE(br);\n EXPECT_EQ(ss, 0);\n EXPECT_EQ(x_res, \"quux\");\n}\n\nGTEST_MAIN_RUN_ALL_TESTS()\n<commit_msg>fix naming in test<commit_after>\/\/ Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/eval\/eval\/value.h>\n#include <vespa\/eval\/eval\/value_codec.h>\n#include <vespa\/eval\/eval\/tensor_spec.h>\n#include <vespa\/eval\/tensor\/default_value_builder_factory.h>\n#include <vespa\/eval\/tensor\/mixed\/packed_mixed_tensor.h>\n#include <vespa\/eval\/tensor\/sparse\/sparse_tensor_value.h>\n#include <vespa\/eval\/tensor\/dense\/dense_tensor.h>\n#include <vespa\/vespalib\/gtest\/gtest.h>\n\nusing namespace vespalib;\nusing namespace vespalib::eval;\nusing namespace vespalib::tensor;\nusing namespace vespalib::eval::packed_mixed_tensor;\n\nValue::UP v_of(const TensorSpec &spec) {\n return value_from_spec(spec, DefaultValueBuilderFactory::get());\n}\n\nTEST(DefaultValueBuilderFactoryTest, all_built_value_types_are_correct) {\n auto dbl = v_of(TensorSpec(\"double\").add({}, 3.0));\n auto trivial = v_of(TensorSpec(\"tensor(x[1])\").add({{\"x\",0}}, 7.0));\n auto dense = v_of(TensorSpec(\"tensor<float>(x[2],y[3])\").add({{\"x\",1},{\"y\",2}}, 17.0));\n auto sparse = v_of(TensorSpec(\"tensor(x{},y{})\").add({{\"x\",\"foo\"},{\"y\",\"bar\"}}, 31.0));\n auto mixed = v_of(TensorSpec(\"tensor<float>(x[2],y{})\").add({{\"x\",1},{\"y\",\"quux\"}}, 42.0));\n\n EXPECT_TRUE(dynamic_cast<DoubleValue *>(dbl.get()));\n EXPECT_TRUE(dynamic_cast<DenseTensorView *>(trivial.get()));\n EXPECT_TRUE(dynamic_cast<DenseTensorView *>(dense.get()));\n EXPECT_TRUE(dynamic_cast<SparseTensorValue<double> *>(sparse.get()));\n EXPECT_TRUE(dynamic_cast<PackedMixedTensor *>(mixed.get()));\n\n EXPECT_EQ(dbl->as_double(), 3.0);\n EXPECT_EQ(trivial->cells().typify<double>()[0], 7.0);\n EXPECT_EQ(dense->cells().typify<float>()[5], 17.0);\n EXPECT_EQ(sparse->cells().typify<double>()[0], 31.0);\n EXPECT_EQ(mixed->cells().typify<float>()[1], 42.0);\n\n stringref y_look = \"bar\";\n stringref x_res = \"xxx\";\n auto view = sparse->index().create_view({1});\n view->lookup({&y_look});\n size_t ss = 12345;\n bool br = view->next_result({&x_res}, ss);\n EXPECT_TRUE(br);\n EXPECT_EQ(ss, 0);\n EXPECT_EQ(x_res, \"foo\");\n br = view->next_result({&x_res}, ss);\n EXPECT_FALSE(br);\n\n ss = 12345;\n view = mixed->index().create_view({});\n view->lookup({});\n br = view->next_result({&x_res}, ss);\n EXPECT_TRUE(br);\n EXPECT_EQ(ss, 0);\n EXPECT_EQ(x_res, \"quux\");\n}\n\nGTEST_MAIN_RUN_ALL_TESTS()\n<|endoftext|>"} {"text":"<commit_before>\/\/ Ignore unused parameter warnings coming from cppuint headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n#include <libmesh\/equation_systems.h>\n#include <libmesh\/serial_mesh.h>\n#include <libmesh\/mesh_generation.h>\n#include <libmesh\/edge_edge2.h>\n#include <libmesh\/face_quad4.h>\n#include <libmesh\/dof_map.h>\n#include <libmesh\/linear_implicit_system.h>\n#include <libmesh\/mesh_refinement.h>\n\n#include \"test_comm.h\"\n\nusing namespace libMesh;\n\nclass MixedDimensionMeshTest : public CppUnit::TestCase {\n \/**\n * The goal of this test is to ensure that a 2D mesh with 1D elements overlapping\n * on the edge is consistent. That is, they share the same global node numbers and\n * the same dof numbers for a variable.\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MixedDimensionMeshTest );\n\n CPPUNIT_TEST( testMesh );\n CPPUNIT_TEST( testDofOrdering );\n CPPUNIT_TEST( testPointLocatorList );\n CPPUNIT_TEST( testPointLocatorTree );\n\n CPPUNIT_TEST_SUITE_END();\n\nprotected:\n\n SerialMesh* _mesh;\n\n void build_mesh()\n {\n _mesh = new SerialMesh(*TestCommWorld);\n\n \/*\n (0,1) (1,1)\n x---------------x\n | |\n | |\n | |\n | |\n | |\n x---------------x\n (0,0) (1,0)\n | |\n | |\n | |\n | |\n x---------------x\n (0,-1) (1,-1)\n *\/\n\n _mesh->set_mesh_dimension(2);\n\n _mesh->add_point( Point(0.0,-1.0), 4 );\n _mesh->add_point( Point(1.0,-1.0), 5 );\n _mesh->add_point( Point(1.0, 0.0), 1 );\n _mesh->add_point( Point(1.0, 1.0), 2 );\n _mesh->add_point( Point(0.0, 1.0), 3 );\n _mesh->add_point( Point(0.0, 0.0), 0 );\n\n {\n Elem* elem_top = _mesh->add_elem( new Quad4 );\n elem_top->set_node(0) = _mesh->node_ptr(0);\n elem_top->set_node(1) = _mesh->node_ptr(1);\n elem_top->set_node(2) = _mesh->node_ptr(2);\n elem_top->set_node(3) = _mesh->node_ptr(3);\n\n Elem* elem_bottom = _mesh->add_elem( new Quad4 );\n elem_bottom->set_node(0) = _mesh->node_ptr(4);\n elem_bottom->set_node(1) = _mesh->node_ptr(5);\n elem_bottom->set_node(2) = _mesh->node_ptr(1);\n elem_bottom->set_node(3) = _mesh->node_ptr(0);\n\n Elem* edge = _mesh->add_elem( new Edge2 );\n edge->set_node(0) = _mesh->node_ptr(0);\n edge->set_node(1) = _mesh->node_ptr(1);\n }\n\n \/\/ libMesh will renumber, but we numbered according to its scheme\n \/\/ anyway. We do this because when we call uniformly_refine subsequenly,\n \/\/ it's going use skip_renumber=false.\n _mesh->prepare_for_use(false \/*skip_renumber*\/);\n }\n\npublic:\n void setUp()\n {\n this->build_mesh();\n }\n\n void tearDown()\n {\n delete _mesh;\n }\n\n void testMesh()\n {\n \/\/ There'd better be 3 elements\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)3, _mesh->n_elem() );\n\n \/\/ There'd better be only 6 nodes\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)6, _mesh->n_nodes() );\n\n \/* The nodes for the EDGE2 element should have the same global ids\n as the bottom edge of the top QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(0)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(0)->node(1) );\n\n \/* The nodes for the EDGE2 element should have the same global ids\n as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(1)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(1)->node(2) );\n\n \/* The nodes for the bottom edge of the top QUAD4 element should have\n the same global ids as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(0), _mesh->elem(1)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(1), _mesh->elem(1)->node(2) );\n }\n\n void testDofOrdering()\n {\n EquationSystems es(*_mesh);\n es.add_system<LinearImplicitSystem>(\"TestDofSystem\");\n es.get_system(\"TestDofSystem\").add_variable(\"u\",FIRST);\n es.init();\n\n DofMap& dof_map = es.get_system(\"TestDofSystem\").get_dof_map();\n\n std::vector<dof_id_type> top_quad_dof_indices, bottom_quad_dof_indices, edge_dof_indices;\n\n dof_map.dof_indices( _mesh->elem(0), top_quad_dof_indices );\n dof_map.dof_indices( _mesh->elem(1), bottom_quad_dof_indices );\n dof_map.dof_indices( _mesh->elem(2), edge_dof_indices );\n\n \/* The dofs for the EDGE2 element should be the same\n as the bottom edge of the top QUAD4 dofs *\/\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], top_quad_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], top_quad_dof_indices[1] );\n\n \/* The dofs for the EDGE2 element should be the same\n as the top edge of the bottom QUAD4 dofs *\/\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], bottom_quad_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], bottom_quad_dof_indices[2] );\n\n \/* The nodes for the bottom edge of the top QUAD4 element should have\n the same global ids as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[0], bottom_quad_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[1], bottom_quad_dof_indices[2] );\n }\n\n void testPointLocatorList()\n {\n AutoPtr<PointLocatorBase> locator = PointLocatorBase::build(LIST,*_mesh);\n\n Point top_point(0.4, 0.5);\n const Elem* top_elem = (*locator)(top_point);\n CPPUNIT_ASSERT(top_elem);\n\n \/\/ We should have gotten back the top quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );\n\n Point bottom_point(0.5, -0.5);\n const Elem* bottom_elem = (*locator)(bottom_point);\n CPPUNIT_ASSERT(bottom_elem);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );\n }\n\n void testPointLocatorTree()\n {\n AutoPtr<PointLocatorBase> locator = _mesh->sub_point_locator();\n\n Point top_point(0.5, 0.5);\n const Elem* top_elem = (*locator)(top_point);\n CPPUNIT_ASSERT(top_elem);\n\n \/\/ We should have gotten back the top quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );\n\n Point bottom_point(0.5, -0.5);\n const Elem* bottom_elem = (*locator)(bottom_point);\n CPPUNIT_ASSERT(bottom_elem);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );\n }\n\n};\n\nclass MixedDimensionRefinedMeshTest : public MixedDimensionMeshTest {\n \/**\n * The goal of this test is the same as the previous, but now we do a\n * uniform refinement and make sure the result mesh is consistent. i.e.\n * the new node shared between the 1D elements is the same as the node\n * shared on the underlying quads, and so on.\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MixedDimensionRefinedMeshTest );\n\n CPPUNIT_TEST( testMesh );\n CPPUNIT_TEST( testDofOrdering );\n\n CPPUNIT_TEST_SUITE_END();\n\n \/\/ Yes, this is necesarry. Somewhere in those macros is a protected\/private\npublic:\n\n void setUp()\n {\n \/*\n\n 3-------10------2\n | | |\n | 5 | 6 |\n 8-------7-------9\n | | |\n | 3 | 4 |\n 0-------6-------1\n | | |\n | 9 | 10 |\n 13------12-------14\n | | |\n | 7 | 8 |\n 4-------11------5\n\n *\/\n this->build_mesh();\n#ifdef LIBMESH_ENABLE_AMR\n MeshRefinement(*_mesh).uniformly_refine(1);\n#endif\n }\n\n void testMesh()\n {\n#ifdef LIBMESH_ENABLE_AMR\n \/\/ We should have 13 total and 10 active elements.\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)13, _mesh->n_elem() );\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_active_elem() );\n\n \/\/ We should have 15 nodes\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)15, _mesh->n_nodes() );\n\n \/\/ EDGE2,id=11 should have same nodes of bottom of QUAD4, id=3\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(3)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(3)->node(1) );\n\n \/\/ EDGE2,id=12 should have same nodes of bottom of QUAD4, id=4\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(4)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(4)->node(1) );\n\n \/\/ EDGE2,id=11 should have same nodes of top of QUAD4, id=9\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(9)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(9)->node(2) );\n\n \/\/ EDGE2,id=12 should have same nodes of top of QUAD4, id=10\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(10)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(10)->node(2) );\n\n \/\/ Shared node between the EDGE2 elements should have the same global id\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(12)->node(0) );\n#endif\n }\n\n void testDofOrdering()\n {\n#ifdef LIBMESH_ENABLE_AMR\n EquationSystems es(*_mesh);\n es.add_system<LinearImplicitSystem>(\"TestDofSystem\");\n es.get_system(\"TestDofSystem\").add_variable(\"u\",FIRST);\n es.init();\n\n DofMap& dof_map = es.get_system(\"TestDofSystem\").get_dof_map();\n\n std::vector<dof_id_type> top_quad3_dof_indices, top_quad4_dof_indices;\n std::vector<dof_id_type> bottom_quad9_dof_indices, bottom_quad10_dof_indices;\n std::vector<dof_id_type> edge11_dof_indices, edge12_dof_indices;\n\n dof_map.dof_indices( _mesh->elem(3), top_quad3_dof_indices );\n dof_map.dof_indices( _mesh->elem(4), top_quad4_dof_indices );\n dof_map.dof_indices( _mesh->elem(9), bottom_quad9_dof_indices );\n dof_map.dof_indices( _mesh->elem(10), bottom_quad10_dof_indices );\n dof_map.dof_indices( _mesh->elem(11), edge11_dof_indices );\n dof_map.dof_indices( _mesh->elem(12), edge12_dof_indices );\n\n \/\/ EDGE2,id=11 should have same dofs as of bottom of QUAD4, id=3\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], top_quad3_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], top_quad3_dof_indices[1] );\n\n \/\/ EDGE2,id=12 should have same dofs of bottom of QUAD4, id=4\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], top_quad4_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], top_quad4_dof_indices[1] );\n\n \/\/ EDGE2,id=11 should have same dofs of top of QUAD4, id=9\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], bottom_quad9_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], bottom_quad9_dof_indices[2] );\n\n \/\/ EDGE2,id=12 should have same dofs of top of QUAD4, id=10\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], bottom_quad10_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], bottom_quad10_dof_indices[2] );\n\n \/\/EDGE2 elements should have same shared dof number\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], edge12_dof_indices[0] );\n#endif\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionMeshTest );\nCPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionRefinedMeshTest );\n<commit_msg>Actually test mixed dimension cases<commit_after>\/\/ Ignore unused parameter warnings coming from cppuint headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n#include <libmesh\/equation_systems.h>\n#include <libmesh\/serial_mesh.h>\n#include <libmesh\/mesh_generation.h>\n#include <libmesh\/edge_edge2.h>\n#include <libmesh\/face_quad4.h>\n#include <libmesh\/dof_map.h>\n#include <libmesh\/linear_implicit_system.h>\n#include <libmesh\/mesh_refinement.h>\n\n#include \"test_comm.h\"\n\nusing namespace libMesh;\n\nclass MixedDimensionMeshTest : public CppUnit::TestCase {\n \/**\n * The goal of this test is to ensure that a 2D mesh with 1D elements overlapping\n * on the edge is consistent. That is, they share the same global node numbers and\n * the same dof numbers for a variable.\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MixedDimensionMeshTest );\n\n CPPUNIT_TEST( testMesh );\n CPPUNIT_TEST( testDofOrdering );\n CPPUNIT_TEST( testPointLocatorList );\n CPPUNIT_TEST( testPointLocatorTree );\n\n CPPUNIT_TEST_SUITE_END();\n\nprotected:\n\n SerialMesh* _mesh;\n\n void build_mesh()\n {\n _mesh = new SerialMesh(*TestCommWorld);\n\n \/*\n (0,1) (1,1)\n x---------------x\n | |\n | |\n | |\n | |\n | |\n x---------------x\n (0,0) (1,0)\n | |\n | |\n | |\n | |\n x---------------x\n (0,-1) (1,-1)\n *\/\n\n _mesh->set_mesh_dimension(2);\n\n _mesh->add_point( Point(0.0,-1.0), 4 );\n _mesh->add_point( Point(1.0,-1.0), 5 );\n _mesh->add_point( Point(1.0, 0.0), 1 );\n _mesh->add_point( Point(1.0, 1.0), 2 );\n _mesh->add_point( Point(0.0, 1.0), 3 );\n _mesh->add_point( Point(0.0, 0.0), 0 );\n\n {\n Elem* elem_top = _mesh->add_elem( new Quad4 );\n elem_top->set_node(0) = _mesh->node_ptr(0);\n elem_top->set_node(1) = _mesh->node_ptr(1);\n elem_top->set_node(2) = _mesh->node_ptr(2);\n elem_top->set_node(3) = _mesh->node_ptr(3);\n\n Elem* elem_bottom = _mesh->add_elem( new Quad4 );\n elem_bottom->set_node(0) = _mesh->node_ptr(4);\n elem_bottom->set_node(1) = _mesh->node_ptr(5);\n elem_bottom->set_node(2) = _mesh->node_ptr(1);\n elem_bottom->set_node(3) = _mesh->node_ptr(0);\n\n Elem* edge = _mesh->add_elem( new Edge2 );\n edge->set_node(0) = _mesh->node_ptr(0);\n edge->set_node(1) = _mesh->node_ptr(1);\n\n \/\/ 2D elements will have subdomain id 0, this one will have 1\n edge->subdomain_id() = 1;\n }\n\n \/\/ libMesh will renumber, but we numbered according to its scheme\n \/\/ anyway. We do this because when we call uniformly_refine subsequenly,\n \/\/ it's going use skip_renumber=false.\n _mesh->prepare_for_use(false \/*skip_renumber*\/);\n }\n\npublic:\n void setUp()\n {\n this->build_mesh();\n }\n\n void tearDown()\n {\n delete _mesh;\n }\n\n void testMesh()\n {\n \/\/ There'd better be 3 elements\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)3, _mesh->n_elem() );\n\n \/\/ There'd better be only 6 nodes\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)6, _mesh->n_nodes() );\n\n \/* The nodes for the EDGE2 element should have the same global ids\n as the bottom edge of the top QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(0)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(0)->node(1) );\n\n \/* The nodes for the EDGE2 element should have the same global ids\n as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(1)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(1)->node(2) );\n\n \/* The nodes for the bottom edge of the top QUAD4 element should have\n the same global ids as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(0), _mesh->elem(1)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(1), _mesh->elem(1)->node(2) );\n }\n\n void testDofOrdering()\n {\n EquationSystems es(*_mesh);\n es.add_system<LinearImplicitSystem>(\"TestDofSystem\");\n es.get_system(\"TestDofSystem\").add_variable(\"u\",FIRST);\n es.init();\n\n DofMap& dof_map = es.get_system(\"TestDofSystem\").get_dof_map();\n\n std::vector<dof_id_type> top_quad_dof_indices, bottom_quad_dof_indices, edge_dof_indices;\n\n dof_map.dof_indices( _mesh->elem(0), top_quad_dof_indices );\n dof_map.dof_indices( _mesh->elem(1), bottom_quad_dof_indices );\n dof_map.dof_indices( _mesh->elem(2), edge_dof_indices );\n\n \/* The dofs for the EDGE2 element should be the same\n as the bottom edge of the top QUAD4 dofs *\/\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], top_quad_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], top_quad_dof_indices[1] );\n\n \/* The dofs for the EDGE2 element should be the same\n as the top edge of the bottom QUAD4 dofs *\/\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], bottom_quad_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], bottom_quad_dof_indices[2] );\n\n \/* The nodes for the bottom edge of the top QUAD4 element should have\n the same global ids as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[0], bottom_quad_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[1], bottom_quad_dof_indices[2] );\n }\n\n void testPointLocatorList()\n {\n AutoPtr<PointLocatorBase> locator = PointLocatorBase::build(LIST,*_mesh);\n\n Point top_point(0.4, 0.5);\n const Elem* top_elem = (*locator)(top_point);\n CPPUNIT_ASSERT(top_elem);\n\n \/\/ We should have gotten back the top quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );\n\n Point bottom_point(0.5, -0.5);\n const Elem* bottom_elem = (*locator)(bottom_point);\n CPPUNIT_ASSERT(bottom_elem);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );\n\n \/\/ Test getting back the edge\n {\n std::set<subdomain_id_type> subdomain_id; subdomain_id.insert(1);\n Point interface_point( 0.2, 0.0 );\n const Elem* interface_elem = (*locator)(interface_point, &subdomain_id);\n CPPUNIT_ASSERT(interface_elem);\n\n \/\/ We should have gotten back the overlapping edge element\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)2, interface_elem->id() );\n }\n }\n\n void testPointLocatorTree()\n {\n AutoPtr<PointLocatorBase> locator = _mesh->sub_point_locator();\n\n Point top_point(0.5, 0.5);\n const Elem* top_elem = (*locator)(top_point);\n CPPUNIT_ASSERT(top_elem);\n\n \/\/ We should have gotten back the top quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );\n\n Point bottom_point(0.5, -0.5);\n const Elem* bottom_elem = (*locator)(bottom_point);\n CPPUNIT_ASSERT(bottom_elem);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );\n\n \/\/ Test getting back the edge\n {\n std::set<subdomain_id_type> subdomain_id; subdomain_id.insert(1);\n Point interface_point( 0.5, 0.0 );\n const Elem* interface_elem = (*locator)(interface_point, &subdomain_id);\n CPPUNIT_ASSERT(interface_elem);\n\n \/\/ We should have gotten back the overlapping edge element\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)2, interface_elem->id() );\n }\n }\n\n};\n\nclass MixedDimensionRefinedMeshTest : public MixedDimensionMeshTest {\n \/**\n * The goal of this test is the same as the previous, but now we do a\n * uniform refinement and make sure the result mesh is consistent. i.e.\n * the new node shared between the 1D elements is the same as the node\n * shared on the underlying quads, and so on.\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MixedDimensionRefinedMeshTest );\n\n CPPUNIT_TEST( testMesh );\n CPPUNIT_TEST( testDofOrdering );\n\n CPPUNIT_TEST_SUITE_END();\n\n \/\/ Yes, this is necesarry. Somewhere in those macros is a protected\/private\npublic:\n\n void setUp()\n {\n \/*\n\n 3-------10------2\n | | |\n | 5 | 6 |\n 8-------7-------9\n | | |\n | 3 | 4 |\n 0-------6-------1\n | | |\n | 9 | 10 |\n 13------12-------14\n | | |\n | 7 | 8 |\n 4-------11------5\n\n *\/\n this->build_mesh();\n#ifdef LIBMESH_ENABLE_AMR\n MeshRefinement(*_mesh).uniformly_refine(1);\n#endif\n }\n\n void testMesh()\n {\n#ifdef LIBMESH_ENABLE_AMR\n \/\/ We should have 13 total and 10 active elements.\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)13, _mesh->n_elem() );\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_active_elem() );\n\n \/\/ We should have 15 nodes\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)15, _mesh->n_nodes() );\n\n \/\/ EDGE2,id=11 should have same nodes of bottom of QUAD4, id=3\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(3)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(3)->node(1) );\n\n \/\/ EDGE2,id=12 should have same nodes of bottom of QUAD4, id=4\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(4)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(4)->node(1) );\n\n \/\/ EDGE2,id=11 should have same nodes of top of QUAD4, id=9\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(9)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(9)->node(2) );\n\n \/\/ EDGE2,id=12 should have same nodes of top of QUAD4, id=10\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(10)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(10)->node(2) );\n\n \/\/ Shared node between the EDGE2 elements should have the same global id\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(12)->node(0) );\n#endif\n }\n\n void testDofOrdering()\n {\n#ifdef LIBMESH_ENABLE_AMR\n EquationSystems es(*_mesh);\n es.add_system<LinearImplicitSystem>(\"TestDofSystem\");\n es.get_system(\"TestDofSystem\").add_variable(\"u\",FIRST);\n es.init();\n\n DofMap& dof_map = es.get_system(\"TestDofSystem\").get_dof_map();\n\n std::vector<dof_id_type> top_quad3_dof_indices, top_quad4_dof_indices;\n std::vector<dof_id_type> bottom_quad9_dof_indices, bottom_quad10_dof_indices;\n std::vector<dof_id_type> edge11_dof_indices, edge12_dof_indices;\n\n dof_map.dof_indices( _mesh->elem(3), top_quad3_dof_indices );\n dof_map.dof_indices( _mesh->elem(4), top_quad4_dof_indices );\n dof_map.dof_indices( _mesh->elem(9), bottom_quad9_dof_indices );\n dof_map.dof_indices( _mesh->elem(10), bottom_quad10_dof_indices );\n dof_map.dof_indices( _mesh->elem(11), edge11_dof_indices );\n dof_map.dof_indices( _mesh->elem(12), edge12_dof_indices );\n\n \/\/ EDGE2,id=11 should have same dofs as of bottom of QUAD4, id=3\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], top_quad3_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], top_quad3_dof_indices[1] );\n\n \/\/ EDGE2,id=12 should have same dofs of bottom of QUAD4, id=4\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], top_quad4_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], top_quad4_dof_indices[1] );\n\n \/\/ EDGE2,id=11 should have same dofs of top of QUAD4, id=9\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], bottom_quad9_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], bottom_quad9_dof_indices[2] );\n\n \/\/ EDGE2,id=12 should have same dofs of top of QUAD4, id=10\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], bottom_quad10_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], bottom_quad10_dof_indices[2] );\n\n \/\/EDGE2 elements should have same shared dof number\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], edge12_dof_indices[0] );\n#endif\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionMeshTest );\nCPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionRefinedMeshTest );\n<|endoftext|>"} {"text":"<commit_before>#include <Bull\/Core\/Exception\/RuntimeError.hpp>\n#include <Bull\/Core\/FileSystem\/File.hpp>\n#include <Bull\/Core\/Log\/Log.hpp>\n\n#include <Bull\/Render\/Shader\/Shader.hpp>\n#include <Bull\/Render\/Context\/GlFunctions.hpp>\n\nnamespace Bull\n{\n unsigned int Shader::getMaxVertexAttribs()\n {\n int count;\n\n ensureContext();\n\n gl::getIntegerv(GL_MAX_VERTEX_ATTRIBS, &count);\n\n return static_cast<unsigned int>(count);\n }\n\n Shader::Shader() :\n m_program(gl::createProgram())\n {\n \/\/\/ Nothing\n }\n\n Shader::~Shader()\n {\n if(isValid())\n {\n gl::deleteProgram(m_program);\n }\n }\n\n bool Shader::create(const ShaderBinary& binary)\n {\n if(binary.isValid())\n {\n gl::programBinary(m_program, binary.format, binary.getBuffer(), binary.getCapacity());\n }\n\n return false;\n }\n\n bool Shader::attach(const ShaderStage& stage)\n {\n if(stage.isValid() && stage.isCompiled())\n {\n gl::attachShader(m_program, stage.getSystemHandler());\n\n return true;\n }\n\n return false;\n }\n\n bool Shader::attachFromPath(const Path& path, ShaderStageType::ShaderStageType type)\n {\n ShaderStage stage;\n ShaderStageParameters parameters;\n\n parameters.type = type;\n\n return stage.loadFromPath(path, parameters) && attach(stage);\n }\n\n bool Shader::attachFromStream(InStream& stream, ShaderStageType::ShaderStageType type)\n {\n ShaderStage stage;\n ShaderStageParameters parameters;\n\n parameters.type = type;\n\n return stage.loadFromStream(stream, parameters) && attach(stage);\n }\n\n bool Shader::attachFromMemory(const void* data, Index length, ShaderStageType::ShaderStageType type)\n {\n ShaderStage stage;\n ShaderStageParameters parameters;\n\n parameters.type = type;\n\n return stage.loadFromMemory(data, length, parameters) && attach(stage);\n }\n\n bool Shader::link()\n {\n if(isValid())\n {\n gl::linkProgram(m_program);\n\n if(!isLinked())\n {\n Log::get()->write(getErrorMessage(), Log::Level::Error);\n\n return false;\n }\n }\n\n return true;\n }\n\n void Shader::bind() const\n {\n if(isValid())\n {\n gl::useProgram(m_program);\n }\n }\n\n bool Shader::isValid() const\n {\n return gl::isProgram(m_program) == GL_TRUE;\n }\n\n bool Shader::isLinked() const\n {\n int status = 0;\n gl::getProgramiv(m_program, GL_LINK_STATUS, &status);\n\n return status == GL_TRUE;\n }\n\n bool Shader::setUniform(const String& name, int uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform1i)\n {\n gl::programUniform1i(m_program, location, uniform);\n }\n else\n {\n bind();\n\n gl::uniform1i(location, uniform);\n }\n\n return true;\n }\n\n bool Shader::setUniform(const String& name, unsigned int uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform1i)\n {\n gl::programUniform1i(m_program, location, uniform);\n }\n else\n {\n bind();\n\n gl::uniform1i(location, uniform);\n }\n\n return true;\n }\n\n bool Shader::setUniform(const String& name, float uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform1i)\n {\n gl::programUniform1f(m_program, location, uniform);\n }\n else\n {\n bind();\n\n gl::uniform1f(location, uniform);\n }\n\n return true;\n }\n\n bool Shader::setUniformColor(const String& name, const Color& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform4f)\n {\n gl::programUniform4f(m_program, location,\n static_cast<float>(uniform.red) \/ 255.f,\n static_cast<float>(uniform.green) \/ 255.f,\n static_cast<float>(uniform.blue) \/ 255.f,\n static_cast<float>(uniform.alpha) \/ 255.f);\n }\n else\n {\n bind();\n\n gl::uniform4f(location,\n static_cast<float>(uniform.red) \/ 255.f,\n static_cast<float>(uniform.green) \/ 255.f,\n static_cast<float>(uniform.blue) \/ 255.f,\n static_cast<float>(uniform.alpha) \/ 255.f);\n }\n\n return true;\n }\n\n bool Shader::setUniformVector(const String& name, const Vector<float, 2>& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform2f)\n {\n gl::programUniform2f(m_program, location, uniform.at(0), uniform.at(1));\n }\n else\n {\n bind();\n\n gl::uniform2f(location, uniform.at(0), uniform.at(1));\n }\n\n return true;\n }\n\n bool Shader::setUniformVector(const String& name, const Vector<float, 3>& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform3f)\n {\n gl::programUniform3f(m_program, location, uniform.at(0), uniform.at(1), uniform.at(2));\n }\n else\n {\n bind();\n\n gl::uniform3f(location, uniform.at(0), uniform.at(1), uniform.at(2));\n }\n\n return true;\n }\n\n bool Shader::setUniformVector(const String& name, const Vector<float, 4>& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform4f)\n {\n gl::programUniform4f(m_program, location, uniform.at(0), uniform.at(1), uniform.at(2), uniform.at(3));\n }\n else\n {\n bind();\n\n gl::uniform4f(location, uniform.at(0), uniform.at(1), uniform.at(2), uniform.at(3));\n }\n\n return true;\n }\n\n bool Shader::setUniformMatrix(const String& name, const Matrix4F& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniformMatrix4fv)\n {\n gl::programUniformMatrix4fv(m_program, location, 1, true, uniform.getPtr());\n }\n else\n {\n bind();\n\n gl::uniformMatrix4fv(location, 1, true, uniform.getPtr());\n }\n\n return true;\n }\n\n ShaderBinary Shader::getBinary() const\n {\n ShaderBinary binary;\n\n if(isValid() && isLinked())\n {\n int length;\n\n gl::getProgramiv(m_program, GL_PROGRAM_BINARY_LENGTH, &length);\n\n if(length)\n {\n binary.create(length);\n\n gl::getProgramBinary(getSystemHandler(), length, nullptr, &binary.format, &binary[0]);\n\n if(!binary.isValid())\n {\n throw RuntimeError(\"Failed to download program binary\");\n }\n }\n }\n\n return binary;\n }\n\n unsigned int Shader::getSystemHandler() const\n {\n return m_program;\n }\n\n String Shader::getErrorMessage() const\n {\n int capacity;\n String message;\n\n gl::getProgramiv(m_program, GL_INFO_LOG_LENGTH, &capacity);\n\n if(capacity)\n {\n message.setSize(static_cast<Index>(capacity));\n gl::getProgramInfoLog(m_program, capacity, nullptr, &message[0]);\n }\n\n return message;\n }\n\n int Shader::getUniformLocation(const String& name)\n {\n return gl::getUniformLocation(m_program, name.getBuffer());\n }\n}\n<commit_msg>[Render\/Shader] Implement loading from binary<commit_after>#include <Bull\/Core\/Exception\/RuntimeError.hpp>\n#include <Bull\/Core\/FileSystem\/File.hpp>\n#include <Bull\/Core\/Log\/Log.hpp>\n\n#include <Bull\/Render\/Shader\/Shader.hpp>\n#include <Bull\/Render\/Context\/GlFunctions.hpp>\n\nnamespace Bull\n{\n unsigned int Shader::getMaxVertexAttribs()\n {\n int count;\n\n ensureContext();\n\n gl::getIntegerv(GL_MAX_VERTEX_ATTRIBS, &count);\n\n return static_cast<unsigned int>(count);\n }\n\n Shader::Shader() :\n m_program(gl::createProgram())\n {\n \/\/\/ Nothing\n }\n\n Shader::~Shader()\n {\n if(isValid())\n {\n gl::deleteProgram(m_program);\n }\n }\n\n bool Shader::create(const ShaderBinary& binary)\n {\n if(binary.isValid())\n {\n gl::programBinary(m_program, binary.format, binary.getBuffer(), binary.getCapacity());\n }\n\n return false;\n }\n\n bool Shader::attach(const ShaderStage& stage)\n {\n if(stage.isValid() && stage.isCompiled())\n {\n gl::attachShader(m_program, stage.getSystemHandler());\n\n return true;\n }\n\n return false;\n }\n\n bool Shader::attachFromPath(const Path& path, ShaderStageType::ShaderStageType type)\n {\n ShaderStage stage;\n ShaderStageParameters parameters;\n\n parameters.type = type;\n\n return stage.loadFromPath(path, parameters) && attach(stage);\n }\n\n bool Shader::attachFromStream(InStream& stream, ShaderStageType::ShaderStageType type)\n {\n ShaderStage stage;\n ShaderStageParameters parameters;\n\n parameters.type = type;\n\n return stage.loadFromStream(stream, parameters) && attach(stage);\n }\n\n bool Shader::attachFromMemory(const void* data, Index length, ShaderStageType::ShaderStageType type)\n {\n ShaderStage stage;\n ShaderStageParameters parameters;\n\n parameters.type = type;\n\n return stage.loadFromMemory(data, length, parameters) && attach(stage);\n }\n\n bool Shader::loadFromBinary(const ShaderBinary& binary)\n {\n if(binary.isValid())\n {\n gl::programBinary(m_program, binary.format, binary.getBuffer(), binary.getCapacity());\n\n return true;\n }\n\n return false;\n }\n\n bool Shader::link()\n {\n if(isValid())\n {\n gl::linkProgram(m_program);\n\n if(!isLinked())\n {\n Log::get()->write(getErrorMessage(), Log::Level::Error);\n\n return false;\n }\n }\n\n return true;\n }\n\n void Shader::bind() const\n {\n if(isValid())\n {\n gl::useProgram(m_program);\n }\n }\n\n bool Shader::isValid() const\n {\n return gl::isProgram(m_program) == GL_TRUE;\n }\n\n bool Shader::isLinked() const\n {\n int status = 0;\n gl::getProgramiv(m_program, GL_LINK_STATUS, &status);\n\n return status == GL_TRUE;\n }\n\n bool Shader::setUniform(const String& name, int uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform1i)\n {\n gl::programUniform1i(m_program, location, uniform);\n }\n else\n {\n bind();\n\n gl::uniform1i(location, uniform);\n }\n\n return true;\n }\n\n bool Shader::setUniform(const String& name, unsigned int uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform1i)\n {\n gl::programUniform1i(m_program, location, uniform);\n }\n else\n {\n bind();\n\n gl::uniform1i(location, uniform);\n }\n\n return true;\n }\n\n bool Shader::setUniform(const String& name, float uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform1i)\n {\n gl::programUniform1f(m_program, location, uniform);\n }\n else\n {\n bind();\n\n gl::uniform1f(location, uniform);\n }\n\n return true;\n }\n\n bool Shader::setUniformColor(const String& name, const Color& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform4f)\n {\n gl::programUniform4f(m_program, location,\n static_cast<float>(uniform.red) \/ 255.f,\n static_cast<float>(uniform.green) \/ 255.f,\n static_cast<float>(uniform.blue) \/ 255.f,\n static_cast<float>(uniform.alpha) \/ 255.f);\n }\n else\n {\n bind();\n\n gl::uniform4f(location,\n static_cast<float>(uniform.red) \/ 255.f,\n static_cast<float>(uniform.green) \/ 255.f,\n static_cast<float>(uniform.blue) \/ 255.f,\n static_cast<float>(uniform.alpha) \/ 255.f);\n }\n\n return true;\n }\n\n bool Shader::setUniformVector(const String& name, const Vector<float, 2>& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform2f)\n {\n gl::programUniform2f(m_program, location, uniform.at(0), uniform.at(1));\n }\n else\n {\n bind();\n\n gl::uniform2f(location, uniform.at(0), uniform.at(1));\n }\n\n return true;\n }\n\n bool Shader::setUniformVector(const String& name, const Vector<float, 3>& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform3f)\n {\n gl::programUniform3f(m_program, location, uniform.at(0), uniform.at(1), uniform.at(2));\n }\n else\n {\n bind();\n\n gl::uniform3f(location, uniform.at(0), uniform.at(1), uniform.at(2));\n }\n\n return true;\n }\n\n bool Shader::setUniformVector(const String& name, const Vector<float, 4>& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniform4f)\n {\n gl::programUniform4f(m_program, location, uniform.at(0), uniform.at(1), uniform.at(2), uniform.at(3));\n }\n else\n {\n bind();\n\n gl::uniform4f(location, uniform.at(0), uniform.at(1), uniform.at(2), uniform.at(3));\n }\n\n return true;\n }\n\n bool Shader::setUniformMatrix(const String& name, const Matrix4F& uniform)\n {\n int location = getUniformLocation(name);\n\n if(location == -1)\n {\n return false;\n }\n\n if(gl::programUniformMatrix4fv)\n {\n gl::programUniformMatrix4fv(m_program, location, 1, true, uniform.getPtr());\n }\n else\n {\n bind();\n\n gl::uniformMatrix4fv(location, 1, true, uniform.getPtr());\n }\n\n return true;\n }\n\n ShaderBinary Shader::getBinary() const\n {\n ShaderBinary binary;\n\n if(isValid() && isLinked())\n {\n int length;\n\n gl::getProgramiv(m_program, GL_PROGRAM_BINARY_LENGTH, &length);\n\n if(length)\n {\n binary.create(length);\n\n gl::getProgramBinary(getSystemHandler(), length, nullptr, &binary.format, &binary[0]);\n\n if(!binary.isValid())\n {\n throw RuntimeError(\"Failed to download program binary\");\n }\n }\n }\n\n return binary;\n }\n\n unsigned int Shader::getSystemHandler() const\n {\n return m_program;\n }\n\n String Shader::getErrorMessage() const\n {\n int capacity;\n String message;\n\n gl::getProgramiv(m_program, GL_INFO_LOG_LENGTH, &capacity);\n\n if(capacity)\n {\n message.setSize(static_cast<Index>(capacity));\n gl::getProgramInfoLog(m_program, capacity, nullptr, &message[0]);\n }\n\n return message;\n }\n\n int Shader::getUniformLocation(const String& name)\n {\n return gl::getUniformLocation(m_program, name.getBuffer());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 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\/browser\/chromeos\/login\/owner_manager.h\"\n\n#include <cert.h>\n#include <keyhi.h>\n#include <keythi.h> \/\/ KeyType enum\n#include <pk11pub.h>\n#include <stdlib.h>\n\n#include <string>\n\n#include \"base\/crypto\/rsa_private_key.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/nss_util_internal.h\"\n#include \"base\/nss_util.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing ::base::RSAPrivateKey;\nusing ::testing::DoAll;\nusing ::testing::Invoke;\nusing ::testing::Return;\nusing ::testing::SetArgumentPointee;\nusing ::testing::_;\n\nnamespace chromeos {\n\nnamespace {\n\nclass MockKeyUtils : public OwnerKeyUtils {\n public:\n MockKeyUtils() {}\n ~MockKeyUtils() {}\n MOCK_METHOD0(GenerateKeyPair, RSAPrivateKey*());\n MOCK_METHOD1(ExportPublicKeyViaDbus, bool(RSAPrivateKey* pair));\n MOCK_METHOD2(ExportPublicKeyToFile, bool(RSAPrivateKey* pair,\n const FilePath& key_file));\n MOCK_METHOD2(ImportPublicKey, bool(const FilePath& key_file,\n std::vector<uint8>* output));\n MOCK_METHOD1(FindPrivateKey, RSAPrivateKey*(const std::vector<uint8>& key));\n MOCK_METHOD0(GetOwnerKeyFilePath, FilePath());\n private:\n DISALLOW_COPY_AND_ASSIGN(MockKeyUtils);\n};\n\nclass MockInjector : public OwnerKeyUtils::Factory {\n public:\n \/\/ Takes ownership of |mock|.\n explicit MockInjector(MockKeyUtils* mock) :\n transient_(mock),\n delete_transient_(true) {\n }\n\n virtual ~MockInjector() {\n if (delete_transient_)\n delete transient_;\n }\n\n \/\/ If this is called, its caller takes ownership of |transient_|.\n \/\/ If it's never called, |transient_| remains our problem.\n OwnerKeyUtils* CreateOwnerKeyUtils() {\n delete_transient_ = false;\n return transient_;\n }\n\n private:\n MockKeyUtils* transient_;\n bool delete_transient_;\n DISALLOW_COPY_AND_ASSIGN(MockInjector);\n};\n\nclass KeyUser : public OwnerManager::Delegate {\n public:\n explicit KeyUser(const OwnerManager::KeyOpCode expected)\n : expected_(expected) {\n }\n\n virtual ~KeyUser() {}\n\n void OnKeyOpComplete(const OwnerManager::KeyOpCode return_code,\n const std::string& payload) {\n MessageLoop::current()->Quit();\n EXPECT_EQ(expected_, return_code);\n }\n\n const OwnerManager::KeyOpCode expected_;\n private:\n DISALLOW_COPY_AND_ASSIGN(KeyUser);\n};\n\nstatic bool Win(RSAPrivateKey* key) {\n MessageLoop::current()->Quit();\n return true;\n}\n\nstatic bool Fail(RSAPrivateKey* key) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ anonymous namespace\n\nclass OwnerManagerTest : public ::testing::Test,\n public NotificationObserver {\n public:\n OwnerManagerTest()\n : message_loop_(MessageLoop::TYPE_UI),\n ui_thread_(ChromeThread::UI, &message_loop_),\n file_thread_(ChromeThread::FILE),\n success_expected_(false),\n quit_on_observe_(true),\n mock_(new MockKeyUtils),\n injector_(mock_) \/* injector_ takes ownership of mock_ *\/ {\n registrar_.Add(\n this,\n NotificationType::OWNER_KEY_FETCH_ATTEMPT_FAILED,\n NotificationService::AllSources());\n registrar_.Add(\n this,\n NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED,\n NotificationService::AllSources());\n }\n virtual ~OwnerManagerTest() {}\n\n virtual void SetUp() {\n base::OpenPersistentNSSDB(); \/\/ TODO(cmasone): use test DB instead\n fake_private_key_.reset(RSAPrivateKey::Create(256));\n ASSERT_TRUE(fake_private_key_->ExportPublicKey(&fake_public_key_));\n\n \/\/ Mimic ownership.\n ASSERT_TRUE(tmpdir_.CreateUniqueTempDir());\n ASSERT_TRUE(file_util::CreateTemporaryFileInDir(tmpdir_.path(), &tmpfile_));\n\n file_thread_.Start();\n OwnerKeyUtils::set_factory(&injector_);\n }\n\n virtual void TearDown() {\n OwnerKeyUtils::set_factory(NULL);\n }\n\n void StartUnowned() {\n file_util::Delete(tmpfile_, false);\n }\n\n void InjectKeys(OwnerManager* manager) {\n manager->public_key_ = fake_public_key_;\n manager->private_key_.reset(fake_private_key_.release());\n }\n\n \/\/ NotificationObserver implementation.\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED) {\n EXPECT_TRUE(success_expected_);\n if (quit_on_observe_)\n MessageLoop::current()->Quit();\n } else if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_FAILED) {\n EXPECT_FALSE(success_expected_);\n if (quit_on_observe_)\n MessageLoop::current()->Quit();\n }\n }\n\n void ExpectKeyFetchSuccess(bool should_succeed) {\n success_expected_ = should_succeed;\n }\n\n void SetQuitOnKeyFetch(bool should_quit) { quit_on_observe_ = should_quit; }\n\n ScopedTempDir tmpdir_;\n FilePath tmpfile_;\n\n MessageLoop message_loop_;\n ChromeThread ui_thread_;\n ChromeThread file_thread_;\n\n std::vector<uint8> fake_public_key_;\n scoped_ptr<RSAPrivateKey> fake_private_key_;\n\n NotificationRegistrar registrar_;\n bool success_expected_;\n bool quit_on_observe_;\n\n MockKeyUtils* mock_;\n MockInjector injector_;\n};\n\nTEST_F(OwnerManagerTest, LoadKeyUnowned) {\n StartUnowned();\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_FALSE(manager->StartLoadOwnerKeyAttempt());\n}\n\nTEST_F(OwnerManagerTest, LoadOwnerKeyFail) {\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))\n .WillOnce(Return(false))\n .RetiresOnSaturation();\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartLoadOwnerKeyAttempt());\n\n \/\/ Run remaining events, until ExportPublicKeyViaDbus().\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, LoadOwnerKey) {\n ExpectKeyFetchSuccess(true);\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))\n .WillOnce(DoAll(SetArgumentPointee<1>(fake_public_key_),\n Return(true)))\n .RetiresOnSaturation();\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartLoadOwnerKeyAttempt());\n\n \/\/ Run remaining events, until ExportPublicKeyViaDbus().\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, TakeOwnershipAlreadyOwned) {\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_FALSE(manager->StartTakeOwnershipAttempt());\n}\n\nTEST_F(OwnerManagerTest, KeyGenerationFail) {\n StartUnowned();\n\n EXPECT_CALL(*mock_, GenerateKeyPair())\n .WillOnce(Return(reinterpret_cast<RSAPrivateKey*>(NULL)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartTakeOwnershipAttempt());\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, KeyExportFail) {\n StartUnowned();\n\n EXPECT_CALL(*mock_, ExportPublicKeyViaDbus(fake_private_key_.get()))\n .WillOnce(Invoke(Fail))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GenerateKeyPair())\n .WillOnce(Return(fake_private_key_.release()))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartTakeOwnershipAttempt());\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, TakeOwnership) {\n StartUnowned();\n ExpectKeyFetchSuccess(true);\n\n EXPECT_CALL(*mock_, ExportPublicKeyViaDbus(fake_private_key_.get()))\n .WillOnce(Invoke(Win))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GenerateKeyPair())\n .WillOnce(Return(fake_private_key_.release()))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartTakeOwnershipAttempt());\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, NotYetOwnedVerify) {\n StartUnowned();\n\n \/\/ Since this shouldn't happen, don't want it to end the test if it does.\n SetQuitOnKeyFetch(false);\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n KeyUser delegate(OwnerManager::KEY_UNAVAILABLE);\n EXPECT_FALSE(manager->StartVerifyAttempt(\"\", \"\", &delegate));\n}\n\nTEST_F(OwnerManagerTest, AlreadyHaveKeysVerify) {\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n InjectKeys(manager.get());\n KeyUser delegate(OwnerManager::SUCCESS);\n EXPECT_TRUE(manager->StartVerifyAttempt(\"\", \"\", &delegate));\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, GetKeyFailDuringVerify) {\n ExpectKeyFetchSuccess(false);\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))\n .WillOnce(Return(false))\n .RetiresOnSaturation();\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n KeyUser delegate(OwnerManager::KEY_UNAVAILABLE);\n EXPECT_TRUE(manager->StartVerifyAttempt(\"\", \"\", &delegate));\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, GetKeyAndVerify) {\n ExpectKeyFetchSuccess(true);\n SetQuitOnKeyFetch(false);\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))\n .WillOnce(DoAll(SetArgumentPointee<1>(fake_public_key_),\n Return(true)))\n .RetiresOnSaturation();\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n KeyUser delegate(OwnerManager::SUCCESS);\n EXPECT_TRUE(manager->StartVerifyAttempt(\"\", \"\", &delegate));\n\n message_loop_.Run();\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Attempt to fix CrOS build after r56824 part 2.<commit_after>\/\/ Copyright (c) 2010 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\/browser\/chromeos\/login\/owner_manager.h\"\n\n#include <cert.h>\n#include <keyhi.h>\n#include <keythi.h> \/\/ KeyType enum\n#include <pk11pub.h>\n#include <stdlib.h>\n\n#include <string>\n\n#include \"base\/crypto\/rsa_private_key.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/nss_util_internal.h\"\n#include \"base\/nss_util.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/common\/notification_observer.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing ::base::RSAPrivateKey;\nusing ::testing::DoAll;\nusing ::testing::Invoke;\nusing ::testing::Return;\nusing ::testing::SetArgumentPointee;\nusing ::testing::_;\n\nnamespace chromeos {\n\nnamespace {\n\nclass MockKeyUtils : public OwnerKeyUtils {\n public:\n MockKeyUtils() {}\n ~MockKeyUtils() {}\n MOCK_METHOD0(GenerateKeyPair, RSAPrivateKey*());\n MOCK_METHOD1(ExportPublicKeyViaDbus, bool(RSAPrivateKey* pair));\n MOCK_METHOD2(ExportPublicKeyToFile, bool(RSAPrivateKey* pair,\n const FilePath& key_file));\n MOCK_METHOD2(ImportPublicKey, bool(const FilePath& key_file,\n std::vector<uint8>* output));\n MOCK_METHOD1(FindPrivateKey, RSAPrivateKey*(const std::vector<uint8>& key));\n MOCK_METHOD0(GetOwnerKeyFilePath, FilePath());\n private:\n DISALLOW_COPY_AND_ASSIGN(MockKeyUtils);\n};\n\nclass MockInjector : public OwnerKeyUtils::Factory {\n public:\n \/\/ Takes ownership of |mock|.\n explicit MockInjector(MockKeyUtils* mock) :\n transient_(mock),\n delete_transient_(true) {\n }\n\n virtual ~MockInjector() {\n if (delete_transient_)\n delete transient_;\n }\n\n \/\/ If this is called, its caller takes ownership of |transient_|.\n \/\/ If it's never called, |transient_| remains our problem.\n OwnerKeyUtils* CreateOwnerKeyUtils() {\n delete_transient_ = false;\n return transient_;\n }\n\n private:\n MockKeyUtils* transient_;\n bool delete_transient_;\n DISALLOW_COPY_AND_ASSIGN(MockInjector);\n};\n\nclass KeyUser : public OwnerManager::Delegate {\n public:\n explicit KeyUser(const OwnerManager::KeyOpCode expected)\n : expected_(expected) {\n }\n\n virtual ~KeyUser() {}\n\n void OnKeyOpComplete(const OwnerManager::KeyOpCode return_code,\n const std::string& payload) {\n MessageLoop::current()->Quit();\n EXPECT_EQ(expected_, return_code);\n }\n\n const OwnerManager::KeyOpCode expected_;\n private:\n DISALLOW_COPY_AND_ASSIGN(KeyUser);\n};\n\nstatic bool Win(RSAPrivateKey* key) {\n MessageLoop::current()->Quit();\n return true;\n}\n\nstatic bool Fail(RSAPrivateKey* key) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ anonymous namespace\n\nclass OwnerManagerTest : public ::testing::Test,\n public NotificationObserver {\n public:\n OwnerManagerTest()\n : message_loop_(MessageLoop::TYPE_UI),\n ui_thread_(ChromeThread::UI, &message_loop_),\n file_thread_(ChromeThread::FILE),\n success_expected_(false),\n quit_on_observe_(true),\n mock_(new MockKeyUtils),\n injector_(mock_) \/* injector_ takes ownership of mock_ *\/ {\n registrar_.Add(\n this,\n NotificationType::OWNER_KEY_FETCH_ATTEMPT_FAILED,\n NotificationService::AllSources());\n registrar_.Add(\n this,\n NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED,\n NotificationService::AllSources());\n }\n virtual ~OwnerManagerTest() {}\n\n virtual void SetUp() {\n base::OpenPersistentNSSDB(); \/\/ TODO(cmasone): use test DB instead\n fake_private_key_.reset(RSAPrivateKey::Create(256));\n ASSERT_TRUE(fake_private_key_->ExportPublicKey(&fake_public_key_));\n\n \/\/ Mimic ownership.\n ASSERT_TRUE(tmpdir_.CreateUniqueTempDir());\n ASSERT_TRUE(file_util::CreateTemporaryFileInDir(tmpdir_.path(), &tmpfile_));\n\n file_thread_.Start();\n OwnerKeyUtils::set_factory(&injector_);\n }\n\n virtual void TearDown() {\n OwnerKeyUtils::set_factory(NULL);\n }\n\n void StartUnowned() {\n file_util::Delete(tmpfile_, false);\n }\n\n void InjectKeys(OwnerManager* manager) {\n manager->public_key_ = fake_public_key_;\n manager->private_key_.reset(fake_private_key_.release());\n }\n\n \/\/ NotificationObserver implementation.\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED) {\n EXPECT_TRUE(success_expected_);\n if (quit_on_observe_)\n MessageLoop::current()->Quit();\n } else if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_FAILED) {\n EXPECT_FALSE(success_expected_);\n if (quit_on_observe_)\n MessageLoop::current()->Quit();\n }\n }\n\n void ExpectKeyFetchSuccess(bool should_succeed) {\n success_expected_ = should_succeed;\n }\n\n void SetQuitOnKeyFetch(bool should_quit) { quit_on_observe_ = should_quit; }\n\n ScopedTempDir tmpdir_;\n FilePath tmpfile_;\n\n MessageLoop message_loop_;\n ChromeThread ui_thread_;\n ChromeThread file_thread_;\n\n std::vector<uint8> fake_public_key_;\n scoped_ptr<RSAPrivateKey> fake_private_key_;\n\n NotificationRegistrar registrar_;\n bool success_expected_;\n bool quit_on_observe_;\n\n MockKeyUtils* mock_;\n MockInjector injector_;\n};\n\nTEST_F(OwnerManagerTest, LoadKeyUnowned) {\n StartUnowned();\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_FALSE(manager->StartLoadOwnerKeyAttempt());\n}\n\nTEST_F(OwnerManagerTest, LoadOwnerKeyFail) {\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))\n .WillOnce(Return(false))\n .RetiresOnSaturation();\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartLoadOwnerKeyAttempt());\n\n \/\/ Run remaining events, until ExportPublicKeyViaDbus().\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, LoadOwnerKey) {\n ExpectKeyFetchSuccess(true);\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))\n .WillOnce(DoAll(SetArgumentPointee<1>(fake_public_key_),\n Return(true)))\n .RetiresOnSaturation();\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartLoadOwnerKeyAttempt());\n\n \/\/ Run remaining events, until ExportPublicKeyViaDbus().\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, TakeOwnershipAlreadyOwned) {\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_FALSE(manager->StartTakeOwnershipAttempt());\n}\n\nTEST_F(OwnerManagerTest, KeyGenerationFail) {\n StartUnowned();\n\n EXPECT_CALL(*mock_, GenerateKeyPair())\n .WillOnce(Return(reinterpret_cast<RSAPrivateKey*>(NULL)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartTakeOwnershipAttempt());\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, KeyExportFail) {\n StartUnowned();\n\n EXPECT_CALL(*mock_, ExportPublicKeyViaDbus(fake_private_key_.get()))\n .WillOnce(Invoke(Fail))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GenerateKeyPair())\n .WillOnce(Return(fake_private_key_.release()))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartTakeOwnershipAttempt());\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, TakeOwnership) {\n StartUnowned();\n ExpectKeyFetchSuccess(true);\n\n EXPECT_CALL(*mock_, ExportPublicKeyViaDbus(fake_private_key_.get()))\n .WillOnce(Invoke(Win))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GenerateKeyPair())\n .WillOnce(Return(fake_private_key_.release()))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n EXPECT_TRUE(manager->StartTakeOwnershipAttempt());\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, NotYetOwnedVerify) {\n StartUnowned();\n\n \/\/ Since this shouldn't happen, don't want it to end the test if it does.\n SetQuitOnKeyFetch(false);\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n KeyUser delegate(OwnerManager::KEY_UNAVAILABLE);\n EXPECT_FALSE(manager->StartVerifyAttempt(\"\", \"\", &delegate));\n}\n\nTEST_F(OwnerManagerTest, AlreadyHaveKeysVerify) {\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n InjectKeys(manager.get());\n KeyUser delegate(OwnerManager::SUCCESS);\n EXPECT_TRUE(manager->StartVerifyAttempt(\"\", \"\", &delegate));\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, GetKeyFailDuringVerify) {\n ExpectKeyFetchSuccess(false);\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))\n .WillOnce(Return(false))\n .RetiresOnSaturation();\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n KeyUser delegate(OwnerManager::KEY_UNAVAILABLE);\n EXPECT_TRUE(manager->StartVerifyAttempt(\"\", \"\", &delegate));\n\n message_loop_.Run();\n}\n\nTEST_F(OwnerManagerTest, GetKeyAndVerify) {\n ExpectKeyFetchSuccess(true);\n SetQuitOnKeyFetch(false);\n\n EXPECT_CALL(*mock_, GetOwnerKeyFilePath())\n .WillRepeatedly(Return(tmpfile_));\n EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))\n .WillOnce(DoAll(SetArgumentPointee<1>(fake_public_key_),\n Return(true)))\n .RetiresOnSaturation();\n\n scoped_refptr<OwnerManager> manager(new OwnerManager);\n KeyUser delegate(OwnerManager::SUCCESS);\n EXPECT_TRUE(manager->StartVerifyAttempt(\"\", \"\", &delegate));\n\n message_loop_.Run();\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <atomic>\n#include <gtest\/gtest.h>\n#include \"..\/parallel_async.h\"\n#include \"..\/task.h\"\n\nclass ConsumerProducerTest : testing::Test { };\n\nTEST(ConsumerProducerTest, Test1)\n{\n\tconst size_t N = 100;\n\tstd::atomic<size_t> f;\n\tf = 0;\n\tauto task = asyncply::parallel_async(\n\t\t[&]()\n\t\t{\n\t\t\tfor (size_t i = 0; i < (N + 1); ++i)\n\t\t\t{\n\t\t\t\tf += i;\n\t\t\t}\n\t\t},\n\t\t[&]()\n\t\t{\n\t\t\tfor (size_t i = 0; i < N; ++i)\n\t\t\t{\n\t\t\t\tf -= i;\n\t\t\t}\n\t\t});\n\ttask->get();\n\tASSERT_EQ(f, N);\n}\n\n<commit_msg>comment tests<commit_after>#include <iostream>\n#include <vector>\n#include <atomic>\n#include <gtest\/gtest.h>\n#include \"..\/parallel_async.h\"\n#include \"..\/task.h\"\n\nclass ConsumerProducerTest : testing::Test { };\n\n#if 0\n\nTEST(ConsumerProducerTest, Test1)\n{\n\tconst size_t N = 100;\n\tstd::atomic<size_t> f;\n\tf = 0;\n\tauto task = asyncply::parallel_async(\n\t\t[&]()\n\t\t{\n\t\t\tfor (size_t i = 0; i < (N + 1); ++i)\n\t\t\t{\n\t\t\t\tf += i;\n\t\t\t}\n\t\t},\n\t\t[&]()\n\t\t{\n\t\t\tfor (size_t i = 0; i < N; ++i)\n\t\t\t{\n\t\t\t\tf -= i;\n\t\t\t}\n\t\t});\n\ttask->get();\n\tASSERT_EQ(f, N);\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The MIT License\n *\n * Copyright 2017-2018 Norwegian University of Technology\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\n#define BOOST_TEST_MODULE ControlledTemperature_Modeldescription_Test\n\n#include <string>\n#include <boost\/test\/unit_test.hpp>\n#include <fmicpp\/tools\/os_util.hpp>\n#include <fmicpp\/fmi2\/fmicpp.hpp>\n\n\nusing namespace std;\nusing namespace fmicpp::fmi2;\n\nconst string fmu_path = string(getenv(\"TEST_FMUs\"))\n + \"\/FMI_2.0\/CoSimulation\/\" + getOs() +\n \"\/20sim\/4.6.4.8004\/ControlledTemperature\/ControlledTemperature.fmu\";\n\n\nBOOST_AUTO_TEST_CASE(test1) {\n\n import::Fmu fmu(fmu_path);\n auto md = fmu.getModelDescription();\n auto md_cs = md.asCoSimulationModelDescription();\n\n BOOST_CHECK_EQUAL(\"2.0\", md.fmiVersion());\n BOOST_CHECK_EQUAL(\"ControlledTemperature\", md.modelName());\n\n BOOST_CHECK_EQUAL(\"{06c2700b-b39c-4895-9151-304ddde28443}\", md.guid());\n BOOST_CHECK_EQUAL(\"{06c2700b-b39c-4895-9151-304ddde28443}\", md_cs->guid());\n BOOST_CHECK_EQUAL(\"20-sim\", md.generationTool());\n BOOST_CHECK_EQUAL(\"20-sim\", md_cs->generationTool());\n\n BOOST_CHECK_EQUAL(true, md.supportsCoSimulation());\n BOOST_CHECK_EQUAL(false, md.supportsModelExchange());\n\n BOOST_CHECK_EQUAL(120, md.modelVariables().size());\n BOOST_CHECK_EQUAL(120, md_cs->modelVariables().size());\n\n auto heatCapatacity1 = md.getVariableByName(\"HeatCapacity1.T0\").asRealVariable();\n BOOST_CHECK_EQUAL(1, heatCapatacity1.getValueReference());\n BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getMin());\n BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getMax());\n BOOST_CHECK_EQUAL(298.0, *heatCapatacity1.getStart());\n BOOST_CHECK_EQUAL(\"starting temperature\", heatCapatacity1.getDescription());\n BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getQuantity());\n\n auto thermalConductor = md.getVariableByValueReference(12);\n BOOST_CHECK_EQUAL(\"TemperatureSource.T\", thermalConductor.getName());\n BOOST_CHECK(fmi2Variability::tunable == thermalConductor.getVariability());\n BOOST_CHECK(fmi2Causality::parameter == thermalConductor.getCausality());\n\n auto sourceFiles = md_cs->sourceFiles();\n BOOST_CHECK_EQUAL(10, sourceFiles.size());\n BOOST_CHECK_EQUAL(\"EulerAngles.c\", sourceFiles.at(0).name());\n\n auto outputs = md.modelStructure().outputs();\n BOOST_CHECK_EQUAL(2, outputs.size());\n BOOST_CHECK_EQUAL(115, outputs[0].index());\n BOOST_CHECK_EQUAL(116, outputs[1].index());\n\n}<commit_msg>add more tests<commit_after>\/*\n * The MIT License\n *\n * Copyright 2017-2018 Norwegian University of Technology\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\n#define BOOST_TEST_MODULE ControlledTemperature_Modeldescription_Test\n\n#include <string>\n#include <boost\/test\/unit_test.hpp>\n#include <fmicpp\/tools\/os_util.hpp>\n#include <fmicpp\/fmi2\/fmicpp.hpp>\n\n\nusing namespace std;\nusing namespace fmicpp::fmi2;\n\nconst string fmu_path = string(getenv(\"TEST_FMUs\"))\n + \"\/FMI_2.0\/CoSimulation\/\" + getOs() +\n \"\/20sim\/4.6.4.8004\/ControlledTemperature\/ControlledTemperature.fmu\";\n\n\nBOOST_AUTO_TEST_CASE(test1) {\n\n import::Fmu fmu(fmu_path);\n auto md = fmu.getModelDescription();\n auto md_cs = md.asCoSimulationModelDescription();\n\n BOOST_CHECK_EQUAL(\"2.0\", md.fmiVersion());\n BOOST_CHECK_EQUAL(\"ControlledTemperature\", md.modelName());\n\n BOOST_CHECK_EQUAL(\"{06c2700b-b39c-4895-9151-304ddde28443}\", md.guid());\n BOOST_CHECK_EQUAL(\"{06c2700b-b39c-4895-9151-304ddde28443}\", md_cs->guid());\n BOOST_CHECK_EQUAL(\"20-sim\", md.generationTool());\n BOOST_CHECK_EQUAL(\"20-sim\", md_cs->generationTool());\n\n BOOST_CHECK_EQUAL(true, md.supportsCoSimulation());\n BOOST_CHECK_EQUAL(false, md.supportsModelExchange());\n\n BOOST_CHECK_EQUAL(120, md.modelVariables().size());\n BOOST_CHECK_EQUAL(120, md_cs->modelVariables().size());\n\n auto heatCapatacity1 = md.getVariableByName(\"HeatCapacity1.T0\").asRealVariable();\n BOOST_CHECK_EQUAL(1, heatCapatacity1.getValueReference());\n BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getMin());\n BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getMax());\n BOOST_CHECK_EQUAL(298.0, *heatCapatacity1.getStart());\n BOOST_CHECK_EQUAL(\"starting temperature\", heatCapatacity1.getDescription());\n BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getQuantity());\n\n auto thermalConductor = md.getVariableByValueReference(12);\n BOOST_CHECK_EQUAL(\"TemperatureSource.T\", thermalConductor.getName());\n BOOST_CHECK(fmi2Variability::tunable == thermalConductor.getVariability());\n BOOST_CHECK(fmi2Causality::parameter == thermalConductor.getCausality());\n\n auto sourceFiles = md_cs->sourceFiles();\n BOOST_CHECK_EQUAL(10, sourceFiles.size());\n BOOST_CHECK_EQUAL(\"EulerAngles.c\", sourceFiles.at(0).name());\n\n auto outputs = md.modelStructure().outputs();\n BOOST_CHECK_EQUAL(2, outputs.size());\n BOOST_CHECK_EQUAL(115, outputs[0].index());\n BOOST_CHECK_EQUAL(116, outputs[1].index());\n\n auto de = md.defaultExperiment();\n BOOST_CHECK(de != nullptr);\n BOOST_CHECK_EQUAL(0.0, *de->startTime());\n BOOST_CHECK_EQUAL(20.0, *de->stopTime());\n BOOST_CHECK_EQUAL(1E-4, *de->stepSize());\n BOOST_CHECK_EQUAL(nullptr, de->tolerance());\n\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <cmath>\n#include \"..\/parallel.h\"\n#include \"..\/sequence.h\"\n#include \"..\/task.h\"\n\nint main(int, const char**)\n{\n\ttry\n\t{\n\t\tfor (int i = 0; i < 100; ++i)\n\t\t{\n\t\t\tstd::vector<asyncply::task_t< asyncply::task_t<double> > > vjobs;\n\t\t\tasyncply::_parallel(vjobs,\n\t\t\t\t[&]()\n\t\t\t\t{\n\t\t\t\t\treturn asyncply::sequence(7.0,\n\t\t\t\t\t\t[](double data)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn data + 3.0;\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[](double data)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn data + 4.0;\n\t\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\t[&]()\n\t\t\t\t{\n\t\t\t\t\treturn asyncply::sequence(9.0,\n\t\t\t\t\t\t[](double data)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn data + 5.0;\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[](double data)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn data + 4.0;\n\t\t\t\t\t\t});\n\t\t\t\t});\n\t\t\tdouble aggregation = 0.0;\n\t\t\tfor (auto& job : vjobs)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\t\/\/ double get get\n\t\t\t\t\tdouble partial = job->get()->get();\n\t\t\t\t\taggregation += partial;\n\t\t\t\t}\n\t\t\t\tcatch (std::exception& e)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"exception: \" << e.what() << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (std::abs(aggregation - 32.0) > 1e-3)\n\t\t\t{\n\t\t\t\tstd::cout << \"invalid total \" << aggregation << std::endl;\n\t\t\t\tthrow std::exception();\n\t\t\t}\n\t\t\t\/\/ std::cout << \"aggregation = \" << aggregation << std::endl;\n\t\t}\n\t\tstd::cout << \"result ok\" << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cout << \"general exception \" << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n<commit_msg>Update test_parallel_sequence.cpp<commit_after>#include <iostream>\n#include <vector>\n#include <cmath>\n#include \"..\/parallel.h\"\n#include \"..\/sequence.h\"\n#include \"..\/task.h\"\n#include <gtest\/gtest.h>\n\nclass ParallelSequenceTest : testing::Test\n{\n\n};\n\nTEST(ParallelSequenceTest, Test1)\n{\n\tstd::vector<asyncply::task_t< asyncply::task_t<double> > > vjobs;\n\tasyncply::_parallel(vjobs,\n\t\t[&]()\n\t\t{\n\t\t\treturn asyncply::sequence(7.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 3.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 4.0;\n\t\t\t\t});\n\t\t},\n\t\t[&]()\n\t\t{\n\t\t\treturn asyncply::sequence(9.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 5.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 4.0;\n\t\t\t\t});\n\t\t});\n\tdouble aggregation = 0.0;\n\tfor (auto& job : vjobs)\n\t{\n\t\ttry\n\t\t{\n\t\t\tdouble partial = job->get()->get();\n\t\t\taggregation += partial;\n\t\t}\n\t\tcatch (std::exception& e)\n\t\t{\n\t\t\tstd::cout << \"exception: \" << e.what() << std::endl;\n\t\t}\n\t}\n\tASSERT_EQ(aggregation, 32.0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Mescaline\/API.h\"\n#include \"Mescaline\/Audio\/Client.hpp\"\n#include \"Mescaline\/Audio\/IO\/Client.hpp\"\n#include \"Mescaline\/Audio\/IO\/JackDriver.hpp\"\n#include \"Mescaline\/Audio\/Group.hpp\"\n#include \"Mescaline\/Audio\/Synth.hpp\"\n#include \"Mescaline\/Audio\/SynthDef.hpp\"\n\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n\n#include \"lilv\/lilv.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/atom.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/forge.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/util.h\"\n\nclass MyLoader : public Mescaline::Audio::Plugin::StaticLoader\n{\npublic:\n MyLoader()\n : Mescaline::Audio::Plugin::StaticLoader(descriptorFunctions())\n {\n const char* bundlePath = getenv(\"MESCALINE_LV2_PATH\");\n if (bundlePath) {\n setenv(\"LV2_PATH\", bundlePath, 1);\n } else {\n setenv(\"LV2_PATH\", \"\/Users\/sk\/Library\/Audio\/Plug-Ins\/LV2\", 1);\n }\n }\n\n static Mescaline::Audio::Plugin::StaticLoader::DescriptorFunctionMap descriptorFunctions()\n {\n Mescaline::Audio::Plugin::StaticLoader::DescriptorFunctionMap dfs;\n extern const LV2_Descriptor* puesnada_sine_lv2_descriptor(uint32_t index);\n dfs[\"http:\/\/mescaline.puesnada.es\/lv2\/plugins\/sine\"] = puesnada_sine_lv2_descriptor;\n return dfs;\n }\n};\n\nclass MyEngine : public Mescaline::Audio::Engine\n{\npublic:\n MyEngine(MyLoader* loader)\n : Mescaline::Audio::Engine(loader)\n { }\n\n virtual void configure(const Mescaline::Audio::IO::Driver& driver)\n {\n Mescaline::Audio::Engine::configure(driver);\n\n \/\/ Create sine instance\n const Mescaline::Audio::Plugin::Manager::PluginHandle& def = env().plugins().lookup(\n \"http:\/\/mescaline.puesnada.es\/lv2\/plugins\/sine\" );\n Mescaline::Audio::Synth* synth = Mescaline::Audio::Synth::construct(env(), env().nextResourceId(), env().rootNode(), *def);\n env().rootNode()->addToTail(*synth);\n synth->mapOutput(0, env().audioBus(Mescaline::Audio::ResourceId(3)), Mescaline::Audio::kOut);\n\n\/\/ const Mescaline::Audio::SynthDef& scopeDef = environment()->lookupSynthDef(\"scope\");\n\/\/ Mescaline::Audio::Synth* scope = Mescaline::Audio::Synth::construct(*environment(), 2, environment()->rootNode(), scopeDef);\n\/\/ environment()->rootNode()->addToTail(*scope);\n\/\/ scope->mapInput(0, Mescaline::Audio::AudioBusId(Mescaline::Audio::AudioBusId::kOutput, 0), Mescaline::Audio::kIn);\n\/\/ m_scope = scope->synth<Mescaline::Audio::ScopeSynth>();\n }\n};\n\nusing namespace std;\n\nstruct Mescaline_Engine\n{\n Mescaline::Audio::Engine* m_engine;\n Mescaline::Audio::IO::Driver* m_audioDriver;\n};\n\nMescaline_Engine* Mescaline_Engine_new()\n{\n cout << \"Mescaline_Engine_new\" << endl;\n Mescaline_Engine* engine = new Mescaline_Engine;\n engine->m_engine = new MyEngine(new MyLoader());\n engine->m_audioDriver = new Mescaline::Audio::IO::JackDriver(engine->m_engine);\n return engine;\n}\n\nvoid Mescaline_Engine_free(Mescaline_Engine* engine)\n{\n cout << \"Mescaline_Engine_free\" << endl;\n Mescaline_Engine_stop(engine);\n delete engine->m_engine;\n delete engine->m_audioDriver;\n delete engine;\n}\n\nvoid Mescaline_Engine_start(Mescaline_Engine* engine)\n{\n cout << \"Mescaline_Engine_start\" << endl;\n engine->m_audioDriver->start();\n}\n\nvoid Mescaline_Engine_stop(Mescaline_Engine* engine)\n{\n cout << \"Mescaline_Engine_stop\" << endl;\n engine->m_audioDriver->stop();\n}\n\nLV2_URID Mescaline_Engine_mapUri(Mescaline_Engine* engine, const char* uri)\n{\n\treturn engine->m_engine->env().mapUri(uri);\n}\n\nconst char* Mescaline_Engine_unmapUri(Mescaline_Engine* engine, LV2_URID urid)\n{\n\treturn engine->m_engine->env().unmapUri(urid);\n}\n\nvoid Mescaline_Engine_request(Mescaline_Engine* engine, LV2_Atom* request, Mescaline_HandleResponse handler, void* handlerData)\n{\n engine->m_engine->env().request(request, handler, handlerData);\n}\n<commit_msg>Disable debug output<commit_after>#include \"Mescaline\/API.h\"\n#include \"Mescaline\/Audio\/Client.hpp\"\n#include \"Mescaline\/Audio\/IO\/Client.hpp\"\n#include \"Mescaline\/Audio\/IO\/JackDriver.hpp\"\n#include \"Mescaline\/Audio\/Group.hpp\"\n#include \"Mescaline\/Audio\/Synth.hpp\"\n#include \"Mescaline\/Audio\/SynthDef.hpp\"\n\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n\n#include \"lilv\/lilv.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/atom.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/forge.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/util.h\"\n\nclass MyLoader : public Mescaline::Audio::Plugin::StaticLoader\n{\npublic:\n MyLoader()\n : Mescaline::Audio::Plugin::StaticLoader(descriptorFunctions())\n {\n const char* bundlePath = getenv(\"MESCALINE_LV2_PATH\");\n if (bundlePath) {\n setenv(\"LV2_PATH\", bundlePath, 1);\n } else {\n setenv(\"LV2_PATH\", \"\/Users\/sk\/Library\/Audio\/Plug-Ins\/LV2\", 1);\n }\n }\n\n static Mescaline::Audio::Plugin::StaticLoader::DescriptorFunctionMap descriptorFunctions()\n {\n Mescaline::Audio::Plugin::StaticLoader::DescriptorFunctionMap dfs;\n extern const LV2_Descriptor* puesnada_sine_lv2_descriptor(uint32_t index);\n dfs[\"http:\/\/mescaline.puesnada.es\/lv2\/plugins\/sine\"] = puesnada_sine_lv2_descriptor;\n return dfs;\n }\n};\n\nclass MyEngine : public Mescaline::Audio::Engine\n{\npublic:\n MyEngine(MyLoader* loader)\n : Mescaline::Audio::Engine(loader)\n { }\n\n virtual void configure(const Mescaline::Audio::IO::Driver& driver)\n {\n Mescaline::Audio::Engine::configure(driver);\n\n \/\/ Create sine instance\n const Mescaline::Audio::Plugin::Manager::PluginHandle& def = env().plugins().lookup(\n \"http:\/\/mescaline.puesnada.es\/lv2\/plugins\/sine\" );\n Mescaline::Audio::Synth* synth = Mescaline::Audio::Synth::construct(env(), env().nextResourceId(), env().rootNode(), *def);\n env().rootNode()->addToTail(*synth);\n synth->mapOutput(0, env().audioBus(Mescaline::Audio::ResourceId(3)), Mescaline::Audio::kOut);\n\n\/\/ const Mescaline::Audio::SynthDef& scopeDef = environment()->lookupSynthDef(\"scope\");\n\/\/ Mescaline::Audio::Synth* scope = Mescaline::Audio::Synth::construct(*environment(), 2, environment()->rootNode(), scopeDef);\n\/\/ environment()->rootNode()->addToTail(*scope);\n\/\/ scope->mapInput(0, Mescaline::Audio::AudioBusId(Mescaline::Audio::AudioBusId::kOutput, 0), Mescaline::Audio::kIn);\n\/\/ m_scope = scope->synth<Mescaline::Audio::ScopeSynth>();\n }\n};\n\nusing namespace std;\n\nstruct Mescaline_Engine\n{\n Mescaline::Audio::Engine* m_engine;\n Mescaline::Audio::IO::Driver* m_audioDriver;\n};\n\nMescaline_Engine* Mescaline_Engine_new()\n{\n \/\/ cout << \"Mescaline_Engine_new\" << endl;\n Mescaline_Engine* engine = new Mescaline_Engine;\n engine->m_engine = new MyEngine(new MyLoader());\n engine->m_audioDriver = new Mescaline::Audio::IO::JackDriver(engine->m_engine);\n return engine;\n}\n\nvoid Mescaline_Engine_free(Mescaline_Engine* engine)\n{\n \/\/ cout << \"Mescaline_Engine_free\" << endl;\n Mescaline_Engine_stop(engine);\n delete engine->m_engine;\n delete engine->m_audioDriver;\n delete engine;\n}\n\nvoid Mescaline_Engine_start(Mescaline_Engine* engine)\n{\n \/\/ cout << \"Mescaline_Engine_start\" << endl;\n engine->m_audioDriver->start();\n}\n\nvoid Mescaline_Engine_stop(Mescaline_Engine* engine)\n{\n \/\/ cout << \"Mescaline_Engine_stop\" << endl;\n engine->m_audioDriver->stop();\n}\n\nLV2_URID Mescaline_Engine_mapUri(Mescaline_Engine* engine, const char* uri)\n{\n\treturn engine->m_engine->env().mapUri(uri);\n}\n\nconst char* Mescaline_Engine_unmapUri(Mescaline_Engine* engine, LV2_URID urid)\n{\n\treturn engine->m_engine->env().unmapUri(urid);\n}\n\nvoid Mescaline_Engine_request(Mescaline_Engine* engine, LV2_Atom* request, Mescaline_HandleResponse handler, void* handlerData)\n{\n engine->m_engine->env().request(request, handler, handlerData);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2008, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/PrimitiveEvaluator.h\"\n\nusing namespace IECore;\n\nPrimitiveEvaluator::CreatorMap &PrimitiveEvaluator::getCreateFns()\n{\n\tstatic CreatorMap *g_createFns = new CreatorMap();\n\tassert( g_createFns );\n\treturn *g_createFns;\n}\n\nvoid PrimitiveEvaluator::registerCreator( TypeId id, CreatorFn f )\n{\n\tassert( f );\n\t\n CreatorMap &createFns = getCreateFns();\n \n assert( createFns.find( id ) == createFns.end() );\n \n createFns.insert( CreatorMap::value_type( id, f) );\n}\n\nPrimitiveEvaluatorPtr PrimitiveEvaluator::create( ConstPrimitivePtr primitive )\n{\n\tassert( primitive );\n\t\n const CreatorMap &createFns = getCreateFns();\n \n CreatorMap::const_iterator it = createFns.find( primitive->typeId() );\n if (it == createFns.end())\n {\n return 0;\n }\n \n return (it->second)(primitive);\n}\n\nPrimitiveEvaluator::~PrimitiveEvaluator()\n{\n}\n\nPrimitiveEvaluator::Result::~Result()\n{\n}\n<commit_msg>Added assert<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2008, Image Engine Design Inc. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/PrimitiveEvaluator.h\"\n\nusing namespace IECore;\n\nPrimitiveEvaluator::CreatorMap &PrimitiveEvaluator::getCreateFns()\n{\n\tstatic CreatorMap *g_createFns = new CreatorMap();\n\tassert( g_createFns );\n\treturn *g_createFns;\n}\n\nvoid PrimitiveEvaluator::registerCreator( TypeId id, CreatorFn f )\n{\n\tassert( f );\n\tassert( f != &PrimitiveEvaluator::create );\n\t\n CreatorMap &createFns = getCreateFns();\n \n assert( createFns.find( id ) == createFns.end() );\n \n createFns.insert( CreatorMap::value_type( id, f) );\n}\n\nPrimitiveEvaluatorPtr PrimitiveEvaluator::create( ConstPrimitivePtr primitive )\n{\n\tassert( primitive );\n\t\n const CreatorMap &createFns = getCreateFns();\n \n CreatorMap::const_iterator it = createFns.find( primitive->typeId() );\n if (it == createFns.end())\n {\n return 0;\n }\n \n return (it->second)(primitive);\n}\n\nPrimitiveEvaluator::~PrimitiveEvaluator()\n{\n}\n\nPrimitiveEvaluator::Result::~Result()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @author Mohammad S. Babaei <info@babaei.net>\n * @version 0.1.0\n *\n * @section LICENSE\n *\n * (The MIT License)\n *\n * Copyright (c) 2016 Mohammad S. Babaei\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 * @section DESCRIPTION\n *\n * Main entry for the web application.\n *\/\n\n\n#include <csignal>\n#include <cstdlib>\n#if defined ( _WIN32 )\n#include <windows.h>\n#else\n#include <unistd.h>\n#endif \/\/ defined ( _WIN32 )\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/exception\/diagnostic_information.hpp>\n#include <boost\/filesystem\/exception.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/format.hpp>\n#include <Wt\/WServer>\n#if MAGICKPP_BACKEND == MAGICKPP_GM\n#include <GraphicsMagick\/Magick++.h>\n#elif MAGICKPP_BACKEND == MAGICKPP_IM\n#include <ImageMagick-6\/Magick++.h>\n#endif \/\/ MAGICKPP_BACKEND == MAGICKPP_GM\n#include <statgrab.h>\n#include <CoreLib\/CoreLib.hpp>\n#include <CoreLib\/Database.hpp>\n#include <CoreLib\/Exception.hpp>\n#include <CoreLib\/Log.hpp>\n#include <CoreLib\/make_unique.hpp>\n#include <CoreLib\/System.hpp>\n#include \"CgiRoot.hpp\"\n#include \"Exception.hpp\"\n#include \"Pool.hpp\"\n#include \"VersionInfo.hpp\"\n\nvoid Terminate [[noreturn]] (int signo);\nvoid InitializeDatabase();\n\n#if defined ( __unix__ )\nint main(int argc, char **argv, char **envp)\n#else\nint main(int argc, char **argv)\n#endif \/\/ defined ( __unix__ )\n{\n try {\n \/\/\/ Gracefully handling SIGTERM\n void (*prev_fn)(int);\n prev_fn = signal(SIGTERM, Terminate);\n if (prev_fn == SIG_IGN)\n signal(SIGTERM, SIG_IGN);\n\n\n \/\/\/ Extract the executable path and name\n boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>());\n if (argc > 0 && argv[0] != NULL)\n path = boost::filesystem::system_complete(boost::filesystem::path(argv[0]));\n std::string appId(path.filename().string());\n std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, \"\"));\n Service::Pool::Storage()->AppPath = appPath;\n\n\n \/\/\/ Force changing the current path to executable path\n boost::filesystem::current_path(appPath);\n\n\n \/\/\/ Initializing CoreLib\n CoreLib::CoreLibInitialize(argc, argv);\n\n\n \/\/\/ Initializing log system\n CoreLib::Log::Initialize(std::cout,\n (boost::filesystem::path(appPath)\n \/ boost::filesystem::path(\"..\")\n \/ boost::filesystem::path(\"log\")).string(),\n \"JobApplicationSystemServer\");\n\n\n \/\/\/ Acquiring process lock\n std::string lockId;\n#if defined ( __unix__ )\n int lock;\n lockId = (boost::filesystem::path(appPath)\n \/ boost::filesystem::path(\"..\")\n \/ boost::filesystem::path(\"tmp\")\n \/ (appId + \".lock\")).string();\n#elif defined ( _WIN32 )\n HANDLE lock;\n lockId = appId;\n#endif \/\/ defined ( __unix__ )\n\n\n \/\/\/ Logging application info\n LOG_INFO(\"Version Information\", \"\", \"BUILD_COMPILER \" VERSION_INFO_BUILD_COMPILER, \"BUILD_DATE \" VERSION_INFO_BUILD_DATE, \"BUILD_HOST \" VERSION_INFO_BUILD_HOST, \"BUILD_PROCESSOR \" VERSION_INFO_BUILD_PROCESSOR, \"BUILD_SYSTEM \" VERSION_INFO_BUILD_SYSTEM, \"PRODUCT_COMPANY_NAME \" VERSION_INFO_PRODUCT_COMPANY_NAME, \"PRODUCT_COPYRIGHT \" VERSION_INFO_PRODUCT_COPYRIGHT, \"PRODUCT_INTERNAL_NAME \" VERSION_INFO_PRODUCT_INTERNAL_NAME, \"PRODUCT_NAME \" VERSION_INFO_PRODUCT_NAME, \"PRODUCT_VERSION \" VERSION_INFO_PRODUCT_VERSION, \"PRODUCT_DESCRIPTION \" VERSION_INFO_PRODUCT_DESCRIPTION);\n\n\n if(!CoreLib::System::GetLock(lockId, lock)) {\n LOG_WARNING(\"Process is already running!\");\n } else {\n LOG_INFO(\"Got the process lock!\");\n }\n\n\n \/*! Initializing Magick++ or You'll crash HARD!! *\/\n Magick::InitializeMagick(*argv);\n\n\n \/\/\/ Initialize libstatgrab\n#if defined ( __unix__ )\n#if defined ( __FreeBSD__ )\n sg_init(1);\n#else\n sg_init(0);\n#endif \/\/ defined ( __FreeBSD__ )\n#elif defined ( _WIN32 )\n \/\/\/ In order to make it work, we have to call it twice\n sg_snapshot();\n sg_snapshot();\n#endif \/\/ defined ( __unix__ )\n \/\/\/ Drop setuid\/setgid privileges.\n if (sg_drop_privileges() != SG_ERROR_NONE) {\n LOG_ERROR(\"Error: Failed to drop privileges!\");\n }\n\n \/\/\/ Initialize the whole database\n InitializeDatabase();\n\n \/\/\/ Starting the server, otherwise going down\n LOG_INFO(\"Starting the server...\");\n Wt::WServer server(argv[0]);\n server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION);\n server.addEntryPoint(Wt::Application, Service::CgiRoot::CreateApplication, \"\", \"favicon.ico\");\n if (server.start()) {\n int sig = Wt::WServer::waitForShutdown();\n server.stop();\n\n#if defined ( __unix__ )\n \/\/\/ Experimental, UNIX only\n if (sig == SIGHUP)\n Wt::WServer::restart(argc, argv, envp);\n#endif \/\/ defined ( __unix__ )\n }\n\n\n \/\/\/ Shutdown libstatgrab before return\n sg_shutdown();\n }\n\n catch (Service::Exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (CoreLib::Exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (Wt::WServer::Exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex));\n }\n\n catch (std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(\"Unknown error!\");\n }\n\n return EXIT_SUCCESS;\n}\n\nvoid Terminate(int signo)\n{\n LOG_WARNING((boost::format(\"Terminating by signal %1%...\") % signo).str());\n exit(1);\n}\n\nvoid InitializeDatabase()\n{\n try {\n Service::Pool::Database()->RegisterTable(\"ROOT\", \"root\",\n \" username VARCHAR(16) NOT NULL PRIMARY KEY, \"\n \" email VARCHAR(254) NOT NULL UNIQUE, \"\n \" last_login_ip VARCHAR(15), \"\n \" last_login_location VARCHAR(96), \"\n \" last_login_rawtime VARCHAR(19), \"\n \" last_login_gdate VARCHAR(10), \"\n \" last_login_jdate VARCHAR(10), \"\n \" last_login_time VARCHAR(10), \"\n \" last_login_user_agent VARCHAR(256), \"\n \" last_login_referer VARCHAR(2083), \"\n \" pwd TEXT NOT NULL, \"\n \" recovery_pwd TEXT \");\n\n Service::Pool::Database()->RegisterTable(\"CONTACTS\", \"contacts\",\n \" recipient VARCHAR(64) NOT NULL PRIMARY KEY, \"\n \" email VARCHAR(254) NOT NULL \");\n\n Service::Pool::Database()->RegisterTable(\"SUBSCRIBERS\", \"subscribers\",\n \" email VARCHAR(254) NOT NULL PRIMARY KEY, \"\n \" uuid VARCHAR(36) NOT NULL UNIQUE \");\n\n Service::Pool::Database()->Initialize();\n\n cppdb::transaction guard(Service::Pool::Database()->Sql());\n\n cppdb::result r = Service::Pool::Database()->Sql()\n << (boost::format(\"SELECT username\"\n \" FROM %1% WHERE username=?;\")\n % Service::Pool::Database()->GetTableName(\"ROOT\")).str()\n << Service::Pool::Storage()->RootUsername() << cppdb::row;\n\n if (r.empty()) {\n Service::Pool::Database()->Insert(\"ROOT\", \"username, email, pwd\",\n {\n Service::Pool::Storage()->RootUsername(),\n Service::Pool::Storage()->RootInitialEmail(),\n Service::Pool::Storage()->RootInitialPassword()\n });\n\n guard.commit();\n } else {\n guard.rollback();\n }\n }\n\n catch (std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(\"Unknown error!\");\n }\n}\n\n<commit_msg>fixed sql init commands<commit_after>\/**\n * @file\n * @author Mohammad S. Babaei <info@babaei.net>\n * @version 0.1.0\n *\n * @section LICENSE\n *\n * (The MIT License)\n *\n * Copyright (c) 2016 Mohammad S. Babaei\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 * @section DESCRIPTION\n *\n * Main entry for the web application.\n *\/\n\n\n#include <csignal>\n#include <cstdlib>\n#if defined ( _WIN32 )\n#include <windows.h>\n#else\n#include <unistd.h>\n#endif \/\/ defined ( _WIN32 )\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/exception\/diagnostic_information.hpp>\n#include <boost\/filesystem\/exception.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/format.hpp>\n#include <Wt\/WServer>\n#if MAGICKPP_BACKEND == MAGICKPP_GM\n#include <GraphicsMagick\/Magick++.h>\n#elif MAGICKPP_BACKEND == MAGICKPP_IM\n#include <ImageMagick-6\/Magick++.h>\n#endif \/\/ MAGICKPP_BACKEND == MAGICKPP_GM\n#include <statgrab.h>\n#include <CoreLib\/CoreLib.hpp>\n#include <CoreLib\/Database.hpp>\n#include <CoreLib\/Exception.hpp>\n#include <CoreLib\/Log.hpp>\n#include <CoreLib\/make_unique.hpp>\n#include <CoreLib\/System.hpp>\n#include \"CgiRoot.hpp\"\n#include \"Exception.hpp\"\n#include \"Pool.hpp\"\n#include \"VersionInfo.hpp\"\n\nvoid Terminate [[noreturn]] (int signo);\nvoid InitializeDatabase();\n\n#if defined ( __unix__ )\nint main(int argc, char **argv, char **envp)\n#else\nint main(int argc, char **argv)\n#endif \/\/ defined ( __unix__ )\n{\n try {\n \/\/\/ Gracefully handling SIGTERM\n void (*prev_fn)(int);\n prev_fn = signal(SIGTERM, Terminate);\n if (prev_fn == SIG_IGN)\n signal(SIGTERM, SIG_IGN);\n\n\n \/\/\/ Extract the executable path and name\n boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>());\n if (argc > 0 && argv[0] != NULL)\n path = boost::filesystem::system_complete(boost::filesystem::path(argv[0]));\n std::string appId(path.filename().string());\n std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, \"\"));\n Service::Pool::Storage()->AppPath = appPath;\n\n\n \/\/\/ Force changing the current path to executable path\n boost::filesystem::current_path(appPath);\n\n\n \/\/\/ Initializing CoreLib\n CoreLib::CoreLibInitialize(argc, argv);\n\n\n \/\/\/ Initializing log system\n CoreLib::Log::Initialize(std::cout,\n (boost::filesystem::path(appPath)\n \/ boost::filesystem::path(\"..\")\n \/ boost::filesystem::path(\"log\")).string(),\n \"JobApplicationSystemServer\");\n\n\n \/\/\/ Acquiring process lock\n std::string lockId;\n#if defined ( __unix__ )\n int lock;\n lockId = (boost::filesystem::path(appPath)\n \/ boost::filesystem::path(\"..\")\n \/ boost::filesystem::path(\"tmp\")\n \/ (appId + \".lock\")).string();\n#elif defined ( _WIN32 )\n HANDLE lock;\n lockId = appId;\n#endif \/\/ defined ( __unix__ )\n\n\n \/\/\/ Logging application info\n LOG_INFO(\"Version Information\", \"\", \"BUILD_COMPILER \" VERSION_INFO_BUILD_COMPILER, \"BUILD_DATE \" VERSION_INFO_BUILD_DATE, \"BUILD_HOST \" VERSION_INFO_BUILD_HOST, \"BUILD_PROCESSOR \" VERSION_INFO_BUILD_PROCESSOR, \"BUILD_SYSTEM \" VERSION_INFO_BUILD_SYSTEM, \"PRODUCT_COMPANY_NAME \" VERSION_INFO_PRODUCT_COMPANY_NAME, \"PRODUCT_COPYRIGHT \" VERSION_INFO_PRODUCT_COPYRIGHT, \"PRODUCT_INTERNAL_NAME \" VERSION_INFO_PRODUCT_INTERNAL_NAME, \"PRODUCT_NAME \" VERSION_INFO_PRODUCT_NAME, \"PRODUCT_VERSION \" VERSION_INFO_PRODUCT_VERSION, \"PRODUCT_DESCRIPTION \" VERSION_INFO_PRODUCT_DESCRIPTION);\n\n\n if(!CoreLib::System::GetLock(lockId, lock)) {\n LOG_WARNING(\"Process is already running!\");\n } else {\n LOG_INFO(\"Got the process lock!\");\n }\n\n\n \/*! Initializing Magick++ or You'll crash HARD!! *\/\n Magick::InitializeMagick(*argv);\n\n\n \/\/\/ Initialize libstatgrab\n#if defined ( __unix__ )\n#if defined ( __FreeBSD__ )\n sg_init(1);\n#else\n sg_init(0);\n#endif \/\/ defined ( __FreeBSD__ )\n#elif defined ( _WIN32 )\n \/\/\/ In order to make it work, we have to call it twice\n sg_snapshot();\n sg_snapshot();\n#endif \/\/ defined ( __unix__ )\n \/\/\/ Drop setuid\/setgid privileges.\n if (sg_drop_privileges() != SG_ERROR_NONE) {\n LOG_ERROR(\"Error: Failed to drop privileges!\");\n }\n\n \/\/\/ Initialize the whole database\n InitializeDatabase();\n\n \/\/\/ Starting the server, otherwise going down\n LOG_INFO(\"Starting the server...\");\n Wt::WServer server(argv[0]);\n server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION);\n server.addEntryPoint(Wt::Application, Service::CgiRoot::CreateApplication, \"\", \"favicon.ico\");\n if (server.start()) {\n int sig = Wt::WServer::waitForShutdown();\n server.stop();\n\n#if defined ( __unix__ )\n \/\/\/ Experimental, UNIX only\n if (sig == SIGHUP)\n Wt::WServer::restart(argc, argv, envp);\n#endif \/\/ defined ( __unix__ )\n }\n\n\n \/\/\/ Shutdown libstatgrab before return\n sg_shutdown();\n }\n\n catch (Service::Exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (CoreLib::Exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (Wt::WServer::Exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex));\n }\n\n catch (std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(\"Unknown error!\");\n }\n\n return EXIT_SUCCESS;\n}\n\nvoid Terminate(int signo)\n{\n LOG_WARNING((boost::format(\"Terminating by signal %1%...\") % signo).str());\n exit(1);\n}\n\nvoid InitializeDatabase()\n{\n try {\n Service::Pool::Database()->RegisterTable(\"ROOT\", \"root\",\n \" username TEXT NOT NULL PRIMARY KEY, \"\n \" email TEXT NOT NULL UNIQUE, \"\n \" last_login_ip TEXT, \"\n \" last_login_location TEXT, \"\n \" last_login_rawtime TEXT, \"\n \" last_login_gdate TEXT, \"\n \" last_login_jdate TEXT, \"\n \" last_login_time TEXT, \"\n \" last_login_user_agent TEXT, \"\n \" last_login_referer TEXT, \"\n \" pwd TEXT NOT NULL, \"\n \" recovery_pwd TEXT \");\n\n Service::Pool::Database()->RegisterTable(\"CONTACTS\", \"contacts\",\n \" recipient TEXT NOT NULL PRIMARY KEY, \"\n \" email TEXT NOT NULL \");\n\n Service::Pool::Database()->RegisterTable(\"SUBSCRIBERS\", \"subscribers\",\n \" email TEXT NOT NULL PRIMARY KEY, \"\n \" uuid TEXT NOT NULL UNIQUE \");\n\n Service::Pool::Database()->Initialize();\n\n cppdb::transaction guard(Service::Pool::Database()->Sql());\n\n cppdb::result r = Service::Pool::Database()->Sql()\n << (boost::format(\"SELECT username\"\n \" FROM %1% WHERE username=?;\")\n % Service::Pool::Database()->GetTableName(\"ROOT\")).str()\n << Service::Pool::Storage()->RootUsername() << cppdb::row;\n\n if (r.empty()) {\n Service::Pool::Database()->Insert(\"ROOT\", \"username, email, pwd\",\n {\n Service::Pool::Storage()->RootUsername(),\n Service::Pool::Storage()->RootInitialEmail(),\n Service::Pool::Storage()->RootInitialPassword()\n });\n\n guard.commit();\n } else {\n guard.rollback();\n }\n }\n\n catch (std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(\"Unknown error!\");\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/ris_lib\/ris_resources_from_file.h\"\n#include \"..\/ris_lib\/ris_bundle_compression.h\"\n#include \"..\/ris_lib\/ris_writing_files.h\"\n#include \"..\/ris_lib\/template.h\"\n#include \"..\/ris_lib\/ris_resource_loader.h\"\n#include \"..\/ris_lib\/ris_default_or_from_file.h\"\n#include \"..\/ris_lib\/ris_resource_snapshot.h\"\n#include \"..\/ris_lib\/ris_late_context.h\"\n#include \"..\/ris_lib\/ris_late.h\"\n#include \"..\/ris_lib\/ris_resource_loader.h\"\n\n#include <iostream>\n#include <string>\n#include <stdexcept>\n#include <unordered_map>\n\n#include <boost\/filesystem.hpp>\n\nvoid print_usage() {\n std::cout\n << \"--- ris v0.3.0 ---\" << std::endl\n << \"a simple resource compiler for c++\" << std::endl\n << \"https:\/\/github.com\/d-led\/ris\" << std::endl\n << \"USAGE:\" << std::endl\n << \" ris <path_to>\/<resources>.[json\/yml\/yaml] [<template_overrides>.[json\/yml\/yaml]]\" << std::endl\n << \"Available algorithms: \" << ris::bundle_compression().available_algorithms() << std::endl;\n ;\n}\n\ntemplate <typename TResource>\nstd::string member_name(TResource const& res) {\n if (!res.member_name.empty())\n return res.member_name;\n return res.name;\n}\n\nvoid process(std::string const& path, std::string const& source_template) {\n auto full_path = absolute(boost::filesystem::path(path));\n full_path.make_preferred();\n std::cout << \"reading \" << full_path.generic_string() << std::endl;\n\n auto user_resources = ris::load_resources_from_file(path);\n auto lookup = user_resources.to_lookup();\n std::cout << \"read \" << user_resources.resources().resources.size() << \" resources\" << std::endl;\n\n auto compression = ris::bundle_compression();\n auto ris_res = ris::default_or_from_file<ris::Resource>(source_template);\n auto template_snapshot = ris::resource_snapshot(ris_res);\n bool any_with_compression = std::any_of(std::begin(user_resources.resources().resources),\n std::end(user_resources.resources().resources),\n [&compression](ris::resource const& res) {\n return compression.is_legal(res.compression);\n });\n\n ris::write_to_temp_first_then_move header([&ris_res, &template_snapshot, &user_resources,&lookup](std::ostream& s) {\n template_snapshot[\"namespace_name\"] = user_resources.namespace_();\n template_snapshot[\"class_name\"] = user_resources.class_();\n auto lazy = ris::get_context(template_snapshot);\n lazy\n .lazy(\"header\", [&lazy, &ris_res](std::ostream& s) {\n ris::render(ris_res.Get(\"header\"), lazy, s);\n })\n .lazy(\"header_declarations\", [&ris_res,&user_resources,&lazy](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy.lazy(\"resource_member_name\", [&resource](std::ostream& s){\n s << member_name(resource);\n });\n ris::render(ris_res.Get(\"header_single_declaration\"), lazy, s);\n }\n })\n .lazy(\"header_resource_names\", [&ris_res, &user_resources, &lazy](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy.lazy(\"resource_name\", [&resource](std::ostream& s){\n s << resource.name;\n });\n ris::render(ris_res.Get(\"header_single_resource_name\"), lazy, s);\n }\n })\n ;\n ris::render(\"{{header}}\", lazy, s);\n }, user_resources.header());\n header.start();\n\n ris::write_to_temp_first_then_move source([&](std::ostream& s) {\n template_snapshot[\"namespace_name\"] = user_resources.namespace_();\n template_snapshot[\"class_name\"] = user_resources.class_();\n auto lazy = ris::get_context(template_snapshot);\n lazy\n .lazy(\"source\", [&lazy, &ris_res](std::ostream& s) {\n ris::render(ris_res.Get(\"source\"), lazy, s);\n })\n .lazy(\"optional_compression_header\", [&](std::ostream& s) {\n if (any_with_compression)\n s << \"#include <bundle.hpp>\\n\";\n })\n .lazy(\"source_default_include\", [&](std::ostream& s) {\n s << \"#include \\\"\" << boost::filesystem::path(user_resources.header()).filename().generic_string() << \"\\\"\";\n })\n .lazy(\"source_definitions\", [&](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy\n .lazy(\"resource_member_name\", [&](std::ostream& s){\n s << member_name(resource);\n })\n .lazy(\"source_literal_bytes\", [&](std::ostream& s){\n static const unsigned MAX_IN_ONE_LINE = 100;\n std::string data = ris::resource_loader(resource, user_resources.base_path()).get();\n\n auto raw_size = data.size();\n\n if (compression.is_legal(resource.compression)) {\n data = compression.pack(resource.compression, data);\n auto new_size = data.size();\n std::cout << \"[\" << resource.compression << \"] \"\n << resource.name << \": \"\n << new_size << \"\/\" << raw_size\n << \" (\" << ((double)new_size \/ raw_size*100.0) << \"%)\" << std::endl;\n }\n\n int count = 0;\n\n for (char c : data) {\n if (count > MAX_IN_ONE_LINE - 1) {\n count = 0;\n }\n\n if (count == 0) {\n s << \"\\n \";\n }\n\n s << static_cast<short>(c) << \", \";\n\n count++;\n }\n })\n .lazy(\"source_return_literal\", [&](std::ostream& s) {\n if (compression.is_legal(resource.compression)) {\n ris::render(ris_res.Get(\"source_return_compressed_literal\"), lazy, s);\n }\n else {\n ris::render(ris_res.Get(\"source_return_plain_literal\"), lazy, s);\n }\n })\n ;\n ris::render(ris_res.Get(\"source_single_definition\"), lazy, s);\n }\n })\n .lazy(\"source_getters\", [&](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy\n .lazy(\"resource_name\", [&resource](std::ostream& s){\n s << resource.name;\n })\n .lazy(\"resource_member_name\", [&](std::ostream& s){\n s << member_name(resource);\n })\n ;\n ris::render(ris_res.Get(\"source_single_getter\"), lazy, s);\n }\n })\n ;\n ris::render(\"{{source}}\", lazy, s);\n }, user_resources.source());\n source.start();\n}\n\nint main(int argc, char ** argv) {\n std::string source_template;\n\n switch (argc) {\n case 3:\n source_template = argv[2];\n \/\/ fall through\n case 2:\n try {\n process(argv[1], source_template);\n }\n catch (std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n break;\n default:\n print_usage();\n }\n}\n<commit_msg>added a minimal YAML resource upon usage<commit_after>#include \"..\/ris_lib\/ris_resources_from_file.h\"\n#include \"..\/ris_lib\/ris_bundle_compression.h\"\n#include \"..\/ris_lib\/ris_writing_files.h\"\n#include \"..\/ris_lib\/template.h\"\n#include \"..\/ris_lib\/ris_resource_loader.h\"\n#include \"..\/ris_lib\/ris_default_or_from_file.h\"\n#include \"..\/ris_lib\/ris_resource_snapshot.h\"\n#include \"..\/ris_lib\/ris_late_context.h\"\n#include \"..\/ris_lib\/ris_late.h\"\n#include \"..\/ris_lib\/ris_resource_loader.h\"\n\n#include <iostream>\n#include <string>\n#include <stdexcept>\n#include <unordered_map>\n\n#include <boost\/filesystem.hpp>\n\nvoid print_usage() {\n std::cout\n << \"--- ris v0.3.0 ---\" << std::endl\n << \"a simple resource compiler for c++\" << std::endl\n << \"https:\/\/github.com\/d-led\/ris\" << std::endl\n << \"USAGE:\" << std::endl\n << \" ris <path_to>\/<resources>.[json\/yml\/yaml] [<template_overrides>.[json\/yml\/yaml]]\" << std::endl\n << \"Available algorithms: \" << ris::bundle_compression().available_algorithms() << std::endl\n << \"Minimal YAML resource file:\"\n <<\nR\"(\n#------------------------\nheader: \"res.h\"\nsource: \"res.cpp\"\n\nresources:\n -\n compression: \"LZ4F\"\n name: \"some_text\"\n source: \"some text\"\n source_type: \"string\"\n#------------------------\n)\" << std::endl\n ;\n}\n\ntemplate <typename TResource>\nstd::string member_name(TResource const& res) {\n if (!res.member_name.empty())\n return res.member_name;\n return res.name;\n}\n\nvoid process(std::string const& path, std::string const& source_template) {\n auto full_path = absolute(boost::filesystem::path(path));\n full_path.make_preferred();\n std::cout << \"reading \" << full_path.generic_string() << std::endl;\n\n auto user_resources = ris::load_resources_from_file(path);\n auto lookup = user_resources.to_lookup();\n std::cout << \"read \" << user_resources.resources().resources.size() << \" resources\" << std::endl;\n\n auto compression = ris::bundle_compression();\n auto ris_res = ris::default_or_from_file<ris::Resource>(source_template);\n auto template_snapshot = ris::resource_snapshot(ris_res);\n bool any_with_compression = std::any_of(std::begin(user_resources.resources().resources),\n std::end(user_resources.resources().resources),\n [&compression](ris::resource const& res) {\n return compression.is_legal(res.compression);\n });\n\n ris::write_to_temp_first_then_move header([&ris_res, &template_snapshot, &user_resources,&lookup](std::ostream& s) {\n template_snapshot[\"namespace_name\"] = user_resources.namespace_();\n template_snapshot[\"class_name\"] = user_resources.class_();\n auto lazy = ris::get_context(template_snapshot);\n lazy\n .lazy(\"header\", [&lazy, &ris_res](std::ostream& s) {\n ris::render(ris_res.Get(\"header\"), lazy, s);\n })\n .lazy(\"header_declarations\", [&ris_res,&user_resources,&lazy](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy.lazy(\"resource_member_name\", [&resource](std::ostream& s){\n s << member_name(resource);\n });\n ris::render(ris_res.Get(\"header_single_declaration\"), lazy, s);\n }\n })\n .lazy(\"header_resource_names\", [&ris_res, &user_resources, &lazy](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy.lazy(\"resource_name\", [&resource](std::ostream& s){\n s << resource.name;\n });\n ris::render(ris_res.Get(\"header_single_resource_name\"), lazy, s);\n }\n })\n ;\n ris::render(\"{{header}}\", lazy, s);\n }, user_resources.header());\n header.start();\n\n ris::write_to_temp_first_then_move source([&](std::ostream& s) {\n template_snapshot[\"namespace_name\"] = user_resources.namespace_();\n template_snapshot[\"class_name\"] = user_resources.class_();\n auto lazy = ris::get_context(template_snapshot);\n lazy\n .lazy(\"source\", [&lazy, &ris_res](std::ostream& s) {\n ris::render(ris_res.Get(\"source\"), lazy, s);\n })\n .lazy(\"optional_compression_header\", [&](std::ostream& s) {\n if (any_with_compression)\n s << \"#include <bundle.hpp>\\n\";\n })\n .lazy(\"source_default_include\", [&](std::ostream& s) {\n s << \"#include \\\"\" << boost::filesystem::path(user_resources.header()).filename().generic_string() << \"\\\"\";\n })\n .lazy(\"source_definitions\", [&](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy\n .lazy(\"resource_member_name\", [&](std::ostream& s){\n s << member_name(resource);\n })\n .lazy(\"source_literal_bytes\", [&](std::ostream& s){\n static const unsigned MAX_IN_ONE_LINE = 100;\n std::string data = ris::resource_loader(resource, user_resources.base_path()).get();\n\n auto raw_size = data.size();\n\n if (compression.is_legal(resource.compression)) {\n data = compression.pack(resource.compression, data);\n auto new_size = data.size();\n std::cout << \"[\" << resource.compression << \"] \"\n << resource.name << \": \"\n << new_size << \"\/\" << raw_size\n << \" (\" << ((double)new_size \/ raw_size*100.0) << \"%)\" << std::endl;\n }\n\n int count = 0;\n\n for (char c : data) {\n if (count > MAX_IN_ONE_LINE - 1) {\n count = 0;\n }\n\n if (count == 0) {\n s << \"\\n \";\n }\n\n s << static_cast<short>(c) << \", \";\n\n count++;\n }\n })\n .lazy(\"source_return_literal\", [&](std::ostream& s) {\n if (compression.is_legal(resource.compression)) {\n ris::render(ris_res.Get(\"source_return_compressed_literal\"), lazy, s);\n }\n else {\n ris::render(ris_res.Get(\"source_return_plain_literal\"), lazy, s);\n }\n })\n ;\n ris::render(ris_res.Get(\"source_single_definition\"), lazy, s);\n }\n })\n .lazy(\"source_getters\", [&](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy\n .lazy(\"resource_name\", [&resource](std::ostream& s){\n s << resource.name;\n })\n .lazy(\"resource_member_name\", [&](std::ostream& s){\n s << member_name(resource);\n })\n ;\n ris::render(ris_res.Get(\"source_single_getter\"), lazy, s);\n }\n })\n ;\n ris::render(\"{{source}}\", lazy, s);\n }, user_resources.source());\n source.start();\n}\n\nint main(int argc, char ** argv) {\n std::string source_template;\n\n switch (argc) {\n case 3:\n source_template = argv[2];\n \/\/ fall through\n case 2:\n try {\n process(argv[1], source_template);\n }\n catch (std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n break;\n default:\n print_usage();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>forall<&{{global_syncname}}>( {{inputsym}}.data, [=]({{tuple_type}}& {{tuple_name}}) {\n{{inner_code}}\n}<commit_msg>typo in code gen<commit_after>forall<&{{global_syncname}}>( {{inputsym}}.data, [=]({{tuple_type}}& {{tuple_name}}) {\n{{inner_code}}\n});<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include <cstdlib>\n#include <unistd.h>\n#include <pthread.h>\n#include <android\/window.h>\n#include \"EngineAndroid.hpp\"\n#include \"WindowResourceAndroid.hpp\"\n#include \"events\/EventDispatcher.hpp\"\n#include \"graphics\/opengl\/android\/RenderDeviceOGLAndroid.hpp\"\n#include \"thread\/Lock.hpp\"\n#include \"utils\/Errors.hpp\"\n\nstatic int looperCallback(int fd, int events, void* data)\n{\n if (events & ALOOPER_EVENT_INPUT)\n {\n char message;\n if (read(fd, &message, sizeof(message)) == -1)\n throw ouzel::SystemError(\"Failed to read from pipe\");\n\n ouzel::EngineAndroid* engineAndroid = static_cast<ouzel::EngineAndroid*>(data);\n engineAndroid->executeAll();\n }\n\n return 1;\n}\n\nnamespace ouzel\n{\n EngineAndroid::EngineAndroid(JavaVM* initJavaVM):\n javaVM(initJavaVM)\n {\n std::fill(std::begin(fd), std::end(fd), 0);\n\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n uriClass = jniEnv->FindClass(\"android\/net\/Uri\");\n uriClass = static_cast<jclass>(jniEnv->NewGlobalRef(uriClass));\n parseMethod = jniEnv->GetStaticMethodID(uriClass, \"parse\", \"(Ljava\/lang\/String;)Landroid\/net\/Uri;\");\n intentClass = jniEnv->FindClass(\"android\/content\/Intent\");\n intentClass = static_cast<jclass>(jniEnv->NewGlobalRef(intentClass));\n intentConstructor = jniEnv->GetMethodID(intentClass, \"<init>\", \"(Ljava\/lang\/String;Landroid\/net\/Uri;)V\");\n }\n\n EngineAndroid::~EngineAndroid()\n {\n if (updateThread.isJoinable()) updateThread.join();\n\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) == JNI_OK)\n {\n if (mainActivity) jniEnv->DeleteGlobalRef(mainActivity);\n if (androidWindow) jniEnv->DeleteGlobalRef(androidWindow);\n if (surface) jniEnv->DeleteGlobalRef(surface);\n if (intentClass) jniEnv->DeleteGlobalRef(intentClass);\n if (uriClass) jniEnv->DeleteGlobalRef(uriClass);\n }\n\n if (looper) ALooper_release(looper);\n if (fd[0]) close(fd[0]);\n if (fd[1]) close(fd[1]);\n }\n\n void EngineAndroid::onCreate(jobject initMainActivity)\n {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n mainActivity = jniEnv->NewGlobalRef(initMainActivity);\n\n jclass mainActivityClass = jniEnv->GetObjectClass(mainActivity);\n startActivityMethod = jniEnv->GetMethodID(mainActivityClass, \"startActivity\", \"(Landroid\/content\/Intent;)V\");\n\n \/\/ get resources\n jclass resourcesClass = jniEnv->FindClass(\"android\/content\/res\/Resources\");\n jmethodID getResourcesMethod = jniEnv->GetMethodID(mainActivityClass, \"getResources\", \"()Landroid\/content\/res\/Resources;\");\n jobject resourcesObject = jniEnv->CallObjectMethod(mainActivity, getResourcesMethod);\n jmethodID getConfigurationMethod = jniEnv->GetMethodID(resourcesClass, \"getConfiguration\", \"()Landroid\/content\/res\/Configuration;\");\n\n \/\/ get configuration\n configurationClass = jniEnv->FindClass(\"android\/content\/res\/Configuration\");\n jobject configurationObject = jniEnv->CallObjectMethod(resourcesObject, getConfigurationMethod);\n\n orientationField = jniEnv->GetFieldID(configurationClass, \"orientation\", \"I\");\n orientation = jniEnv->GetIntField(configurationObject, orientationField);\n\n \/\/ get asset manager\n jmethodID getAssetsMethod = jniEnv->GetMethodID(mainActivityClass, \"getAssets\", \"()Landroid\/content\/res\/AssetManager;\");\n jobject assetManagerObject = jniEnv->CallObjectMethod(mainActivity, getAssetsMethod);\n assetManager = AAssetManager_fromJava(jniEnv, assetManagerObject);\n\n \/\/ get window\n jmethodID getWindowMethod = jniEnv->GetMethodID(mainActivityClass, \"getWindow\", \"()Landroid\/view\/Window;\");\n androidWindow = jniEnv->CallObjectMethod(mainActivity, getWindowMethod);\n androidWindow = jniEnv->NewGlobalRef(androidWindow);\n\n jclass windowClass = jniEnv->FindClass(\"android\/view\/Window\");\n addFlagsMethod = jniEnv->GetMethodID(windowClass, \"addFlags\", \"(I)V\");\n clearFlagsMethod = jniEnv->GetMethodID(windowClass, \"clearFlags\", \"(I)V\");\n\n \/\/ File class\n jclass fileClass = jniEnv->FindClass(\"java\/io\/File\");\n jmethodID getAbsolutePathMethod = jniEnv->GetMethodID(fileClass, \"getAbsolutePath\", \"()Ljava\/lang\/String;\");\n\n \/\/ dataDir\n jmethodID getFilesDirMethod = jniEnv->GetMethodID(mainActivityClass, \"getFilesDir\", \"()Ljava\/io\/File;\");\n jobject filesDirFile = jniEnv->CallObjectMethod(mainActivity, getFilesDirMethod);\n\n jstring filesDirString = static_cast<jstring>(jniEnv->CallObjectMethod(filesDirFile, getAbsolutePathMethod));\n const char* filesDirCString = jniEnv->GetStringUTFChars(filesDirString, 0);\n filesDirectory = filesDirCString;\n jniEnv->ReleaseStringUTFChars(filesDirString, filesDirCString);\n\n \/\/ cacheDir\n jmethodID getCacheDirMethod = jniEnv->GetMethodID(mainActivityClass, \"getCacheDir\", \"()Ljava\/io\/File;\");\n jobject cacheDirFile = jniEnv->CallObjectMethod(mainActivity, getCacheDirMethod);\n\n jstring cacheDirString = static_cast<jstring>(jniEnv->CallObjectMethod(cacheDirFile, getAbsolutePathMethod));\n const char* cacheDirCString = jniEnv->GetStringUTFChars(cacheDirString, 0);\n cacheDirectory = cacheDirCString;\n jniEnv->ReleaseStringUTFChars(cacheDirString, cacheDirCString);\n\n \/\/ looper\n looper = ALooper_forThread(); \/\/ this is called on main thread, so it is safe to get the looper here\n ALooper_acquire(looper);\n pipe(fd);\n if (ALooper_addFd(looper, fd[0], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallback, this) != 1)\n throw SystemError(\"Failed to add looper file descriptor\");\n }\n\n void EngineAndroid::onSurfaceCreated(jobject newSurface)\n {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n if (surface) jniEnv->DeleteGlobalRef(surface);\n surface = jniEnv->NewGlobalRef(newSurface);\n\n if (active)\n {\n WindowResourceAndroid* windowAndroid = static_cast<WindowResourceAndroid*>(window.getResource());\n windowAndroid->handleSurfaceChange(surface);\n\n if (renderer)\n {\n graphics::RenderDevice* renderDevice = renderer->getDevice();\n if (renderDevice->getDriver() == graphics::Renderer::Driver::OPENGL)\n {\n graphics::RenderDeviceOGLAndroid* renderDeviceOGLAndroid = static_cast<graphics::RenderDeviceOGLAndroid*>(renderDevice);\n renderDeviceOGLAndroid->reload();\n }\n }\n }\n }\n\n void EngineAndroid::onConfigurationChanged(jobject newConfig)\n {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n jint newOrientation = jniEnv->GetIntField(newConfig, orientationField);\n\n if (orientation != newOrientation)\n {\n orientation = newOrientation;\n\n ouzel::Event event;\n event.type = ouzel::Event::Type::ORIENTATION_CHANGE;\n\n switch (orientation)\n {\n case ORIENTATION_PORTRAIT:\n event.systemEvent.orientation = ouzel::SystemEvent::Orientation::PORTRAIT;\n break;\n case ORIENTATION_LANDSCAPE:\n event.systemEvent.orientation = ouzel::SystemEvent::Orientation::LANDSCAPE;\n break;\n default:\n event.systemEvent.orientation = ouzel::SystemEvent::Orientation::UNKNOWN;\n break;\n }\n\n eventDispatcher.postEvent(event);\n }\n }\n\n void EngineAndroid::onSurfaceDestroyed()\n {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n if (surface)\n {\n jniEnv->DeleteGlobalRef(surface);\n surface = nullptr;\n }\n\n if (active)\n {\n WindowResourceAndroid* windowAndroid = static_cast<WindowResourceAndroid*>(window.getResource());\n windowAndroid->handleSurfaceDestroy();\n\n if (renderer)\n {\n graphics::RenderDevice* renderDevice = renderer->getDevice();\n if (renderDevice->getDriver() == graphics::Renderer::Driver::OPENGL)\n {\n graphics::RenderDeviceOGLAndroid* renderDeviceOGLAndroid = static_cast<graphics::RenderDeviceOGLAndroid*>(renderDevice);\n renderDeviceOGLAndroid->destroy();\n }\n }\n }\n }\n\n void EngineAndroid::run()\n {\n init();\n start();\n }\n\n void EngineAndroid::executeOnMainThread(const std::function<void(void)>& func)\n {\n {\n Lock lock(executeMutex);\n executeQueue.push(func);\n }\n\n char message = 1;\n if (write(fd[1], &message, sizeof(message)) == -1)\n throw SystemError(\"Failed to write to pipe\");\n }\n\n void EngineAndroid::openURL(const std::string& url)\n {\n executeOnMainThread([url, this]() {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n jstring actionString = jniEnv->NewStringUTF(\"android.intent.action.VIEW\");\n jstring urlString = jniEnv->NewStringUTF(url.c_str());\n jobject uri = jniEnv->CallStaticObjectMethod(uriClass, parseMethod, urlString);\n jobject intentObject = jniEnv->NewObject(intentClass, intentConstructor, actionString, uri);\n\n jniEnv->CallVoidMethod(mainActivity, startActivityMethod, intentObject);\n\n jniEnv->DeleteLocalRef(intentObject);\n jniEnv->DeleteLocalRef(uri);\n jniEnv->DeleteLocalRef(urlString);\n jniEnv->DeleteLocalRef(actionString);\n\n if (jniEnv->ExceptionCheck())\n {\n jniEnv->ExceptionClear();\n throw SystemError(\"Failed to open URL\");\n }\n });\n }\n\n void EngineAndroid::setScreenSaverEnabled(bool newScreenSaverEnabled)\n {\n Engine::setScreenSaverEnabled(newScreenSaverEnabled);\n\n executeOnMainThread([newScreenSaverEnabled, this]() {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n if (newScreenSaverEnabled)\n jniEnv->CallVoidMethod(androidWindow, clearFlagsMethod, AWINDOW_FLAG_KEEP_SCREEN_ON);\n else\n jniEnv->CallVoidMethod(androidWindow, addFlagsMethod, AWINDOW_FLAG_KEEP_SCREEN_ON);\n });\n }\n\n void EngineAndroid::executeAll()\n {\n std::function<void(void)> func;\n\n {\n Lock lock(executeMutex);\n\n if (!executeQueue.empty())\n {\n func = std::move(executeQueue.front());\n executeQueue.pop();\n }\n }\n\n if (func) func();\n }\n\n void EngineAndroid::main()\n {\n JNIEnv* jniEnv;\n JavaVMAttachArgs attachArgs;\n attachArgs.version = JNI_VERSION_1_6;\n attachArgs.name = nullptr; \/\/ thread name\n attachArgs.group = nullptr; \/\/ thread group\n if (javaVM->AttachCurrentThread(&jniEnv, &attachArgs) != JNI_OK)\n throw SystemError(\"Failed to attach current thread to Java VM\");\n\n Engine::main();\n\n if (javaVM->DetachCurrentThread() != JNI_OK)\n throw SystemError(\"Failed to detach current thread from Java VM\");\n }\n}\n<commit_msg>Remove unused pthread include<commit_after>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include <cstdlib>\n#include <unistd.h>\n#include <android\/window.h>\n#include \"EngineAndroid.hpp\"\n#include \"WindowResourceAndroid.hpp\"\n#include \"events\/EventDispatcher.hpp\"\n#include \"graphics\/opengl\/android\/RenderDeviceOGLAndroid.hpp\"\n#include \"thread\/Lock.hpp\"\n#include \"utils\/Errors.hpp\"\n\nstatic int looperCallback(int fd, int events, void* data)\n{\n if (events & ALOOPER_EVENT_INPUT)\n {\n char message;\n if (read(fd, &message, sizeof(message)) == -1)\n throw ouzel::SystemError(\"Failed to read from pipe\");\n\n ouzel::EngineAndroid* engineAndroid = static_cast<ouzel::EngineAndroid*>(data);\n engineAndroid->executeAll();\n }\n\n return 1;\n}\n\nnamespace ouzel\n{\n EngineAndroid::EngineAndroid(JavaVM* initJavaVM):\n javaVM(initJavaVM)\n {\n std::fill(std::begin(fd), std::end(fd), 0);\n\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n uriClass = jniEnv->FindClass(\"android\/net\/Uri\");\n uriClass = static_cast<jclass>(jniEnv->NewGlobalRef(uriClass));\n parseMethod = jniEnv->GetStaticMethodID(uriClass, \"parse\", \"(Ljava\/lang\/String;)Landroid\/net\/Uri;\");\n intentClass = jniEnv->FindClass(\"android\/content\/Intent\");\n intentClass = static_cast<jclass>(jniEnv->NewGlobalRef(intentClass));\n intentConstructor = jniEnv->GetMethodID(intentClass, \"<init>\", \"(Ljava\/lang\/String;Landroid\/net\/Uri;)V\");\n }\n\n EngineAndroid::~EngineAndroid()\n {\n if (updateThread.isJoinable()) updateThread.join();\n\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) == JNI_OK)\n {\n if (mainActivity) jniEnv->DeleteGlobalRef(mainActivity);\n if (androidWindow) jniEnv->DeleteGlobalRef(androidWindow);\n if (surface) jniEnv->DeleteGlobalRef(surface);\n if (intentClass) jniEnv->DeleteGlobalRef(intentClass);\n if (uriClass) jniEnv->DeleteGlobalRef(uriClass);\n }\n\n if (looper) ALooper_release(looper);\n if (fd[0]) close(fd[0]);\n if (fd[1]) close(fd[1]);\n }\n\n void EngineAndroid::onCreate(jobject initMainActivity)\n {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n mainActivity = jniEnv->NewGlobalRef(initMainActivity);\n\n jclass mainActivityClass = jniEnv->GetObjectClass(mainActivity);\n startActivityMethod = jniEnv->GetMethodID(mainActivityClass, \"startActivity\", \"(Landroid\/content\/Intent;)V\");\n\n \/\/ get resources\n jclass resourcesClass = jniEnv->FindClass(\"android\/content\/res\/Resources\");\n jmethodID getResourcesMethod = jniEnv->GetMethodID(mainActivityClass, \"getResources\", \"()Landroid\/content\/res\/Resources;\");\n jobject resourcesObject = jniEnv->CallObjectMethod(mainActivity, getResourcesMethod);\n jmethodID getConfigurationMethod = jniEnv->GetMethodID(resourcesClass, \"getConfiguration\", \"()Landroid\/content\/res\/Configuration;\");\n\n \/\/ get configuration\n configurationClass = jniEnv->FindClass(\"android\/content\/res\/Configuration\");\n jobject configurationObject = jniEnv->CallObjectMethod(resourcesObject, getConfigurationMethod);\n\n orientationField = jniEnv->GetFieldID(configurationClass, \"orientation\", \"I\");\n orientation = jniEnv->GetIntField(configurationObject, orientationField);\n\n \/\/ get asset manager\n jmethodID getAssetsMethod = jniEnv->GetMethodID(mainActivityClass, \"getAssets\", \"()Landroid\/content\/res\/AssetManager;\");\n jobject assetManagerObject = jniEnv->CallObjectMethod(mainActivity, getAssetsMethod);\n assetManager = AAssetManager_fromJava(jniEnv, assetManagerObject);\n\n \/\/ get window\n jmethodID getWindowMethod = jniEnv->GetMethodID(mainActivityClass, \"getWindow\", \"()Landroid\/view\/Window;\");\n androidWindow = jniEnv->CallObjectMethod(mainActivity, getWindowMethod);\n androidWindow = jniEnv->NewGlobalRef(androidWindow);\n\n jclass windowClass = jniEnv->FindClass(\"android\/view\/Window\");\n addFlagsMethod = jniEnv->GetMethodID(windowClass, \"addFlags\", \"(I)V\");\n clearFlagsMethod = jniEnv->GetMethodID(windowClass, \"clearFlags\", \"(I)V\");\n\n \/\/ File class\n jclass fileClass = jniEnv->FindClass(\"java\/io\/File\");\n jmethodID getAbsolutePathMethod = jniEnv->GetMethodID(fileClass, \"getAbsolutePath\", \"()Ljava\/lang\/String;\");\n\n \/\/ dataDir\n jmethodID getFilesDirMethod = jniEnv->GetMethodID(mainActivityClass, \"getFilesDir\", \"()Ljava\/io\/File;\");\n jobject filesDirFile = jniEnv->CallObjectMethod(mainActivity, getFilesDirMethod);\n\n jstring filesDirString = static_cast<jstring>(jniEnv->CallObjectMethod(filesDirFile, getAbsolutePathMethod));\n const char* filesDirCString = jniEnv->GetStringUTFChars(filesDirString, 0);\n filesDirectory = filesDirCString;\n jniEnv->ReleaseStringUTFChars(filesDirString, filesDirCString);\n\n \/\/ cacheDir\n jmethodID getCacheDirMethod = jniEnv->GetMethodID(mainActivityClass, \"getCacheDir\", \"()Ljava\/io\/File;\");\n jobject cacheDirFile = jniEnv->CallObjectMethod(mainActivity, getCacheDirMethod);\n\n jstring cacheDirString = static_cast<jstring>(jniEnv->CallObjectMethod(cacheDirFile, getAbsolutePathMethod));\n const char* cacheDirCString = jniEnv->GetStringUTFChars(cacheDirString, 0);\n cacheDirectory = cacheDirCString;\n jniEnv->ReleaseStringUTFChars(cacheDirString, cacheDirCString);\n\n \/\/ looper\n looper = ALooper_forThread(); \/\/ this is called on main thread, so it is safe to get the looper here\n ALooper_acquire(looper);\n pipe(fd);\n if (ALooper_addFd(looper, fd[0], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallback, this) != 1)\n throw SystemError(\"Failed to add looper file descriptor\");\n }\n\n void EngineAndroid::onSurfaceCreated(jobject newSurface)\n {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n if (surface) jniEnv->DeleteGlobalRef(surface);\n surface = jniEnv->NewGlobalRef(newSurface);\n\n if (active)\n {\n WindowResourceAndroid* windowAndroid = static_cast<WindowResourceAndroid*>(window.getResource());\n windowAndroid->handleSurfaceChange(surface);\n\n if (renderer)\n {\n graphics::RenderDevice* renderDevice = renderer->getDevice();\n if (renderDevice->getDriver() == graphics::Renderer::Driver::OPENGL)\n {\n graphics::RenderDeviceOGLAndroid* renderDeviceOGLAndroid = static_cast<graphics::RenderDeviceOGLAndroid*>(renderDevice);\n renderDeviceOGLAndroid->reload();\n }\n }\n }\n }\n\n void EngineAndroid::onConfigurationChanged(jobject newConfig)\n {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n jint newOrientation = jniEnv->GetIntField(newConfig, orientationField);\n\n if (orientation != newOrientation)\n {\n orientation = newOrientation;\n\n ouzel::Event event;\n event.type = ouzel::Event::Type::ORIENTATION_CHANGE;\n\n switch (orientation)\n {\n case ORIENTATION_PORTRAIT:\n event.systemEvent.orientation = ouzel::SystemEvent::Orientation::PORTRAIT;\n break;\n case ORIENTATION_LANDSCAPE:\n event.systemEvent.orientation = ouzel::SystemEvent::Orientation::LANDSCAPE;\n break;\n default:\n event.systemEvent.orientation = ouzel::SystemEvent::Orientation::UNKNOWN;\n break;\n }\n\n eventDispatcher.postEvent(event);\n }\n }\n\n void EngineAndroid::onSurfaceDestroyed()\n {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n if (surface)\n {\n jniEnv->DeleteGlobalRef(surface);\n surface = nullptr;\n }\n\n if (active)\n {\n WindowResourceAndroid* windowAndroid = static_cast<WindowResourceAndroid*>(window.getResource());\n windowAndroid->handleSurfaceDestroy();\n\n if (renderer)\n {\n graphics::RenderDevice* renderDevice = renderer->getDevice();\n if (renderDevice->getDriver() == graphics::Renderer::Driver::OPENGL)\n {\n graphics::RenderDeviceOGLAndroid* renderDeviceOGLAndroid = static_cast<graphics::RenderDeviceOGLAndroid*>(renderDevice);\n renderDeviceOGLAndroid->destroy();\n }\n }\n }\n }\n\n void EngineAndroid::run()\n {\n init();\n start();\n }\n\n void EngineAndroid::executeOnMainThread(const std::function<void(void)>& func)\n {\n {\n Lock lock(executeMutex);\n executeQueue.push(func);\n }\n\n char message = 1;\n if (write(fd[1], &message, sizeof(message)) == -1)\n throw SystemError(\"Failed to write to pipe\");\n }\n\n void EngineAndroid::openURL(const std::string& url)\n {\n executeOnMainThread([url, this]() {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n jstring actionString = jniEnv->NewStringUTF(\"android.intent.action.VIEW\");\n jstring urlString = jniEnv->NewStringUTF(url.c_str());\n jobject uri = jniEnv->CallStaticObjectMethod(uriClass, parseMethod, urlString);\n jobject intentObject = jniEnv->NewObject(intentClass, intentConstructor, actionString, uri);\n\n jniEnv->CallVoidMethod(mainActivity, startActivityMethod, intentObject);\n\n jniEnv->DeleteLocalRef(intentObject);\n jniEnv->DeleteLocalRef(uri);\n jniEnv->DeleteLocalRef(urlString);\n jniEnv->DeleteLocalRef(actionString);\n\n if (jniEnv->ExceptionCheck())\n {\n jniEnv->ExceptionClear();\n throw SystemError(\"Failed to open URL\");\n }\n });\n }\n\n void EngineAndroid::setScreenSaverEnabled(bool newScreenSaverEnabled)\n {\n Engine::setScreenSaverEnabled(newScreenSaverEnabled);\n\n executeOnMainThread([newScreenSaverEnabled, this]() {\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n throw SystemError(\"Failed to get JNI environment\");\n\n if (newScreenSaverEnabled)\n jniEnv->CallVoidMethod(androidWindow, clearFlagsMethod, AWINDOW_FLAG_KEEP_SCREEN_ON);\n else\n jniEnv->CallVoidMethod(androidWindow, addFlagsMethod, AWINDOW_FLAG_KEEP_SCREEN_ON);\n });\n }\n\n void EngineAndroid::executeAll()\n {\n std::function<void(void)> func;\n\n {\n Lock lock(executeMutex);\n\n if (!executeQueue.empty())\n {\n func = std::move(executeQueue.front());\n executeQueue.pop();\n }\n }\n\n if (func) func();\n }\n\n void EngineAndroid::main()\n {\n JNIEnv* jniEnv;\n JavaVMAttachArgs attachArgs;\n attachArgs.version = JNI_VERSION_1_6;\n attachArgs.name = nullptr; \/\/ thread name\n attachArgs.group = nullptr; \/\/ thread group\n if (javaVM->AttachCurrentThread(&jniEnv, &attachArgs) != JNI_OK)\n throw SystemError(\"Failed to attach current thread to Java VM\");\n\n Engine::main();\n\n if (javaVM->DetachCurrentThread() != JNI_OK)\n throw SystemError(\"Failed to detach current thread from Java VM\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Flax\/Fiber.h\"\n#include \"Flax\/RoundRobinScheduler.h\"\n\n#include <algorithm>\n#include <cassert>\n\nnamespace flax {\n\n#if FLAX_USE_SCHEDULER\n\/\/ static\nthread_local Fiber::SchedulerContainer Fiber::scheduler(std::make_unique<RoundRobinScheduler>());\n\n\/\/ static\nthread_local std::vector<Fiber*> Fiber::fibers;\n#endif \/\/ FLAX_USE_SCHEDULER\n\n\/\/ static\nthread_local Fiber* Fiber::activeFiber = nullptr;\n\n\/\/ static\nFiber& Fiber::getMainFiber() {\n static thread_local Fiber mainFiber(nullptr, \"Main Fiber\", true);\n assert(mainFiber.isValid() && !mainFiber.isFinished() && mainFiber.isMainFiber());\n\n return mainFiber;\n}\n\n\/\/ static\nstd::unique_ptr<Fiber> Fiber::create(const std::function<void()>& func, const std::string& name) {\n \/\/ Make sure the main fiber is initialized\n getMainFiber();\n\n std::unique_ptr<Fiber> newFiber(new Fiber(func, name, false));\n if (!newFiber->isValid()) {\n return nullptr;\n }\n\n return newFiber;\n}\n\n\/\/ static\nvoid Fiber::yieldTo(Fiber& fiber) {\n assert(fiber.isValid() && !fiber.isActive() && !fiber.isFinished());\n assert(activeFiber && activeFiber->isValid() && activeFiber->isActive());\n assert(&fiber != activeFiber);\n\n#if FLAX_USE_SCHEDULER\n scheduler->onFiberYieldedTo(&fiber);\n#endif \/\/ FLAX_USE_SCHEDULER\n\n FiberImpl& from = activeFiber->impl;\n FiberImpl& to = fiber.impl;\n activeFiber = &fiber;\n FiberImpl::swap(from, to);\n}\n\n#if FLAX_USE_SCHEDULER\n\/\/ static\nvoid Fiber::yield() {\n Fiber* nextFiber = scheduler->next();\n if (!nextFiber) {\n return;\n }\n\n assert(nextFiber->isValid() && !nextFiber->isActive() && !nextFiber->isFinished());\n assert(nextFiber != activeFiber);\n\n yieldTo(*nextFiber);\n}\n\n\/\/ static\nvoid Fiber::setScheduler(std::unique_ptr<Scheduler> newScheduler) {\n if (newScheduler) {\n scheduler = std::move(newScheduler);\n\n for (Fiber* fiber : fibers) {\n assert(fiber->isValid());\n scheduler->onFiberCreated(fiber);\n }\n }\n}\n#endif \/\/ FLAX_USE_SCHEDULER\n\n\/\/ static\nvoid Fiber::fiberMain(Fiber* fiber) {\n assert(fiber && fiber->isValid() && fiber->isActive() && !fiber->isFinished() && !fiber->isMainFiber() && fiber->function != nullptr);\n\n fiber->function();\n\n fiber->finish();\n#if FLAX_USE_SCHEDULER\n fiber->yield();\n#else\n fiber->yieldTo(getMainFiber());\n#endif \/\/ FLAX_USE_SCHEDULER\n\n assert(false); \/\/ Should never get here\n}\n\nFiber::Fiber(const std::function<void()>& func, const std::string& name, bool isMainFiber)\n : function(func), fiberName(name), mainFiber(isMainFiber), finished(false), impl(this, &Fiber::fiberMain, isMainFiber) {\n if (isMainFiber) {\n assert(isValid() && function == nullptr);\n activeFiber = this;\n }\n\n#if FLAX_USE_SCHEDULER\n if (isValid()) {\n fibers.push_back(this);\n scheduler->onFiberCreated(this);\n\n if (isMainFiber) {\n scheduler->onFiberYieldedTo(this);\n }\n }\n#endif \/\/ FLAX_USE_SCHEDULER\n}\n\nFiber::~Fiber() {\n assert(isActive() == isMainFiber());\n\n if (isValid() && !isFinished()) {\n finish();\n }\n}\n\nvoid Fiber::finish() {\n assert(isValid() && !isFinished());\n\n finished = true;\n\n#if FLAX_USE_SCHEDULER\n scheduler->onFiberFinished(this);\n fibers.erase(std::remove_if(fibers.begin(), fibers.end(), [this](const Fiber* fiber) { return fiber == this; }), fibers.end());\n#endif \/\/ FLAX_USE_SCHEDULER\n}\n\n} \/\/ namespace flax\n<commit_msg>When a new scheduler is set, let it know about the currently active fiber<commit_after>#include \"Flax\/Fiber.h\"\n#include \"Flax\/RoundRobinScheduler.h\"\n\n#include <algorithm>\n#include <cassert>\n\nnamespace flax {\n\n#if FLAX_USE_SCHEDULER\n\/\/ static\nthread_local Fiber::SchedulerContainer Fiber::scheduler(std::make_unique<RoundRobinScheduler>());\n\n\/\/ static\nthread_local std::vector<Fiber*> Fiber::fibers;\n#endif \/\/ FLAX_USE_SCHEDULER\n\n\/\/ static\nthread_local Fiber* Fiber::activeFiber = nullptr;\n\n\/\/ static\nFiber& Fiber::getMainFiber() {\n static thread_local Fiber mainFiber(nullptr, \"Main Fiber\", true);\n assert(mainFiber.isValid() && !mainFiber.isFinished() && mainFiber.isMainFiber());\n\n return mainFiber;\n}\n\n\/\/ static\nstd::unique_ptr<Fiber> Fiber::create(const std::function<void()>& func, const std::string& name) {\n \/\/ Make sure the main fiber is initialized\n getMainFiber();\n\n std::unique_ptr<Fiber> newFiber(new Fiber(func, name, false));\n if (!newFiber->isValid()) {\n return nullptr;\n }\n\n return newFiber;\n}\n\n\/\/ static\nvoid Fiber::yieldTo(Fiber& fiber) {\n assert(fiber.isValid() && !fiber.isActive() && !fiber.isFinished());\n assert(activeFiber && activeFiber->isValid() && activeFiber->isActive());\n assert(&fiber != activeFiber);\n\n#if FLAX_USE_SCHEDULER\n scheduler->onFiberYieldedTo(&fiber);\n#endif \/\/ FLAX_USE_SCHEDULER\n\n FiberImpl& from = activeFiber->impl;\n FiberImpl& to = fiber.impl;\n activeFiber = &fiber;\n FiberImpl::swap(from, to);\n}\n\n#if FLAX_USE_SCHEDULER\n\/\/ static\nvoid Fiber::yield() {\n Fiber* nextFiber = scheduler->next();\n if (!nextFiber) {\n return;\n }\n\n assert(nextFiber->isValid() && !nextFiber->isActive() && !nextFiber->isFinished());\n assert(nextFiber != activeFiber);\n\n yieldTo(*nextFiber);\n}\n\n\/\/ static\nvoid Fiber::setScheduler(std::unique_ptr<Scheduler> newScheduler) {\n if (newScheduler) {\n scheduler = std::move(newScheduler);\n\n for (Fiber* fiber : fibers) {\n assert(fiber->isValid());\n scheduler->onFiberCreated(fiber);\n }\n\n if (activeFiber) {\n scheduler->onFiberYieldedTo(activeFiber);\n }\n }\n}\n#endif \/\/ FLAX_USE_SCHEDULER\n\n\/\/ static\nvoid Fiber::fiberMain(Fiber* fiber) {\n assert(fiber && fiber->isValid() && fiber->isActive() && !fiber->isFinished() && !fiber->isMainFiber() && fiber->function != nullptr);\n\n fiber->function();\n\n fiber->finish();\n#if FLAX_USE_SCHEDULER\n fiber->yield();\n#else\n fiber->yieldTo(getMainFiber());\n#endif \/\/ FLAX_USE_SCHEDULER\n\n assert(false); \/\/ Should never get here\n}\n\nFiber::Fiber(const std::function<void()>& func, const std::string& name, bool isMainFiber)\n : function(func), fiberName(name), mainFiber(isMainFiber), finished(false), impl(this, &Fiber::fiberMain, isMainFiber) {\n if (isMainFiber) {\n assert(isValid() && function == nullptr);\n activeFiber = this;\n }\n\n#if FLAX_USE_SCHEDULER\n if (isValid()) {\n fibers.push_back(this);\n scheduler->onFiberCreated(this);\n\n if (isMainFiber) {\n scheduler->onFiberYieldedTo(this);\n }\n }\n#endif \/\/ FLAX_USE_SCHEDULER\n}\n\nFiber::~Fiber() {\n assert(isActive() == isMainFiber());\n\n if (isValid() && !isFinished()) {\n finish();\n }\n}\n\nvoid Fiber::finish() {\n assert(isValid() && !isFinished());\n\n finished = true;\n\n#if FLAX_USE_SCHEDULER\n scheduler->onFiberFinished(this);\n fibers.erase(std::remove_if(fibers.begin(), fibers.end(), [this](const Fiber* fiber) { return fiber == this; }), fibers.end());\n#endif \/\/ FLAX_USE_SCHEDULER\n}\n\n} \/\/ namespace flax\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Projectname: amos-ss16-proj5\n\/\/\n\/\/ Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5\n\/\/\n\/\/ This file is part of the AMOS Project 2016 @ FAU\n\/\/ (Friedrich-Alexander University Erlangen-Nürnberg)\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (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. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public\n\/\/ License along with this program. If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"detection.h\"\n#include \"people_detector.h\"\n#include \"vehicle_detector.h\"\n\nusing namespace std;\nusing namespace cv;\n\nvoid Detection::ProcessFrame(Image image) {\n\n PeopleDetector peopleDetector;\n VehicleDetector vehicleDetector;\n\n Mat resizedFrame = ResizeFrame(image.GetRGBImage());\n\n std::vector<Rect> detectedPeople = peopleDetector.Detect(&resizedFrame);\n std::vector<Rect> detectedVehicles = vehicleDetector.Detect(&resizedFrame);\n\n DisplayDetectedObjects(detectedPeople, detectedVehicles, &resizedFrame);\n}\n\nMat Detection::ResizeFrame(Mat *frame) {\n \/\/resize the image to width of 400px to reduce detection time and improve detection accuracy\n \/\/0.3125 is used because the test video is 1280 x 720, so the width resized images is 400px this has to be changed to our image size (best would be no hard coded scaling so other images sizes work too!)\n \/\/ TODO: dynamic risizeing depending on input (min width 400px)\n\n Mat resizedFrame;\n resize(*frame, resizedFrame, Size(0, 0), 0.3125, 0.3125, CV_INTER_AREA);\n return resizedFrame;\n}\n\nvoid Detection::DisplayDetectedObjects(std::vector<Rect> firstDetection, std::vector<Rect> secondDetection, Mat *frame) {\n \/\/add retangle for each Object in firstDetection\n for (int i=0; i<firstDetection.size(); i++) {\n Rect r = firstDetection[i];\n rectangle(*frame, r.tl(), r.br(), Scalar(0,255,0), 2);\n }\n\n \/\/add rectangle for each Object in secondDetection\n for (int i=0; i<secondDetection.size(); i++) {\n Rect r = secondDetection[i];\n rectangle(*frame, r.tl(), r.br(), Scalar(255,150,0), 2);\n }\n\n imshow(\"Camera stream\", *frame); \/\/ TODO: Use image_view class\n}\n<commit_msg>the wrong argument was given to ResizeFrame<commit_after>\/\/\n\/\/ Projectname: amos-ss16-proj5\n\/\/\n\/\/ Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5\n\/\/\n\/\/ This file is part of the AMOS Project 2016 @ FAU\n\/\/ (Friedrich-Alexander University Erlangen-Nürnberg)\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (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. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public\n\/\/ License along with this program. If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"detection.h\"\n#include \"people_detector.h\"\n#include \"vehicle_detector.h\"\n\nusing namespace std;\nusing namespace cv;\n\nvoid Detection::ProcessFrame(Image image) {\n\n PeopleDetector peopleDetector;\n VehicleDetector vehicleDetector;\n\n Mat frame = image.GetRGBImage();\n Mat resizedFrame = ResizeFrame(&frame);\n\n std::vector<Rect> detectedPeople = peopleDetector.Detect(&resizedFrame);\n std::vector<Rect> detectedVehicles = vehicleDetector.Detect(&resizedFrame);\n\n DisplayDetectedObjects(detectedPeople, detectedVehicles, &resizedFrame);\n}\n\nMat Detection::ResizeFrame(Mat *frame) {\n \/\/resize the image to width of 400px to reduce detection time and improve detection accuracy\n \/\/0.3125 is used because the test video is 1280 x 720, so the width resized images is 400px this has to be changed to our image size (best would be no hard coded scaling so other images sizes work too!)\n \/\/ TODO: dynamic risizeing depending on input (min width 400px)\n\n Mat resizedFrame;\n resize(*frame, resizedFrame, Size(0, 0), 0.3125, 0.3125, CV_INTER_AREA);\n return resizedFrame;\n}\n\nvoid Detection::DisplayDetectedObjects(std::vector<Rect> firstDetection, std::vector<Rect> secondDetection, Mat *frame) {\n \/\/add retangle for each Object in firstDetection\n for (int i=0; i<firstDetection.size(); i++) {\n Rect r = firstDetection[i];\n rectangle(*frame, r.tl(), r.br(), Scalar(0,255,0), 2);\n }\n\n \/\/add rectangle for each Object in secondDetection\n for (int i=0; i<secondDetection.size(); i++) {\n Rect r = secondDetection[i];\n rectangle(*frame, r.tl(), r.br(), Scalar(255,150,0), 2);\n }\n\n imshow(\"Camera stream\", *frame); \/\/ TODO: Use image_view class\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"breakout.h\"\n#include <QDesktopWidget>\n#include <QApplication>\n\nvoid center(QWidget& widget){\n int x,y;\n int screenWidth;\n int screenHeight;\n\n int WIDTH = 300;\n int HEIGHT = 400;\n\n QDesktopWidget *desktop = QApplication::desktop();\n\n screenWidth = desktop->width();\n screenHeight = desktop->height();\n\n x = (screenWidth - WIDTH)\/2;\n y = (screenHeight - HEIGHT)\/2;\n\n widget.setGeometry(x, y, WIDTH, HEIGHT);\n widget.setFixedSize(WIDTH, HEIGHT);\n}\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n\n Breakout window;\n\n window.setWindowTitle(\"Breakout\");\n window.show();\n center(window);\n\n return a.exec();\n}\n<commit_msg>Add comments<commit_after>#include \"breakout.h\"\n#include <QDesktopWidget>\n#include <QApplication>\n\n\/\/Function to center a QWidget relative to the users display and give the QWidget a fixed size\nvoid setup(QWidget& widget){\n int WIDTH = 300;\n int HEIGHT = 400;\n\n \/\/Create a QDesktopWidget object to get inforamtion about the userss desktop\n QDesktopWidget* desktop = QApplication::desktop();\n\n \/\/Reposition the QWidget in the middle of the user's desktop\n widget.setGeometry((desktop->width() - WIDTH)\/2, (desktop->height() - HEIGHT)\/2, WIDTH, HEIGHT);\n widget.setFixedSize(WIDTH, HEIGHT);\n}\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n\n Breakout window;\n\n window.setWindowTitle(\"Breakout\");\n window.show();\n setup(window);\n\n return a.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Genes\/Piece_Strength_Gene.h\"\n\n#include <array>\n#include <memory>\n#include <map>\n\n#include \"Genes\/Gene.h\"\n#include \"Game\/Piece.h\"\n#include \"Game\/Board.h\"\n#include \"Utility.h\"\n\nPiece_Strength_Gene::Piece_Strength_Gene() : piece_strength{}\n{\n}\n\nvoid Piece_Strength_Gene::reset_properties() const\n{\n for(auto piece_type : {PAWN, ROOK, KNIGHT, BISHOP, QUEEN, KING})\n {\n auto piece = Board::piece_instance(piece_type, WHITE);\n properties[std::string(1, piece->fen_symbol())] = piece_value(piece);\n }\n}\n\nvoid Piece_Strength_Gene::load_properties()\n{\n for(const auto& piece_score : properties)\n {\n Piece_Type piece;\n switch(piece_score.first[0])\n {\n case 'P':\n piece = PAWN;\n break;\n case 'R':\n piece = ROOK;\n break;\n case 'N':\n piece = KNIGHT;\n break;\n case 'B':\n piece = BISHOP;\n break;\n case 'Q':\n piece = QUEEN;\n break;\n case 'K':\n piece = KING;\n break;\n default:\n throw std::runtime_error(\"Unrecognized piece type: \" + piece_score.first);\n }\n piece_value(piece) = piece_score.second;\n }\n}\n\nvoid Piece_Strength_Gene::gene_specific_mutation()\n{\n for(auto& piece_score : piece_strength)\n {\n const double mean_number_of_mutations = 2.0;\n if(Random::success_probability(mean_number_of_mutations\/piece_strength.size()))\n {\n piece_score += Random::random_laplace(1.0);\n }\n }\n}\n\ndouble Piece_Strength_Gene::piece_value(Piece_Type type) const\n{\n return piece_strength[type];\n}\n\ndouble& Piece_Strength_Gene::piece_value(Piece_Type type)\n{\n return piece_strength[type];\n}\n\ndouble Piece_Strength_Gene::piece_value(const Piece* piece) const\n{\n if( ! piece)\n {\n return 0.0;\n }\n else\n {\n return piece_value(piece->type());\n }\n}\n\nstd::unique_ptr<Gene> Piece_Strength_Gene::duplicate() const\n{\n return std::make_unique<Piece_Strength_Gene>(*this);\n}\n\nstd::string Piece_Strength_Gene::name() const\n{\n return \"Piece Strength Gene\";\n}\n\ndouble Piece_Strength_Gene::score_board(const Board&, const Board&, size_t) const\n{\n return 0.0;\n}\n<commit_msg>Only mutate one piece strength per mutation<commit_after>#include \"Genes\/Piece_Strength_Gene.h\"\n\n#include <array>\n#include <memory>\n#include <map>\n\n#include \"Genes\/Gene.h\"\n#include \"Game\/Piece.h\"\n#include \"Game\/Board.h\"\n#include \"Utility.h\"\n\nPiece_Strength_Gene::Piece_Strength_Gene() : piece_strength{}\n{\n}\n\nvoid Piece_Strength_Gene::reset_properties() const\n{\n for(auto piece_type : {PAWN, ROOK, KNIGHT, BISHOP, QUEEN, KING})\n {\n auto piece = Board::piece_instance(piece_type, WHITE);\n properties[std::string(1, piece->fen_symbol())] = piece_value(piece);\n }\n}\n\nvoid Piece_Strength_Gene::load_properties()\n{\n for(const auto& piece_score : properties)\n {\n Piece_Type piece;\n switch(piece_score.first[0])\n {\n case 'P':\n piece = PAWN;\n break;\n case 'R':\n piece = ROOK;\n break;\n case 'N':\n piece = KNIGHT;\n break;\n case 'B':\n piece = BISHOP;\n break;\n case 'Q':\n piece = QUEEN;\n break;\n case 'K':\n piece = KING;\n break;\n default:\n throw std::runtime_error(\"Unrecognized piece type: \" + piece_score.first);\n }\n piece_value(piece) = piece_score.second;\n }\n}\n\nvoid Piece_Strength_Gene::gene_specific_mutation()\n{\n auto index = Random::random_integer(0, piece_strength.size() - 1);\n piece_strength[index] += Random::random_laplace(1.0);\n}\n\ndouble Piece_Strength_Gene::piece_value(Piece_Type type) const\n{\n return piece_strength[type];\n}\n\ndouble& Piece_Strength_Gene::piece_value(Piece_Type type)\n{\n return piece_strength[type];\n}\n\ndouble Piece_Strength_Gene::piece_value(const Piece* piece) const\n{\n if( ! piece)\n {\n return 0.0;\n }\n else\n {\n return piece_value(piece->type());\n }\n}\n\nstd::unique_ptr<Gene> Piece_Strength_Gene::duplicate() const\n{\n return std::make_unique<Piece_Strength_Gene>(*this);\n}\n\nstd::string Piece_Strength_Gene::name() const\n{\n return \"Piece Strength Gene\";\n}\n\ndouble Piece_Strength_Gene::score_board(const Board&, const Board&, size_t) const\n{\n return 0.0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/format.hpp\"\n\n#include \"IECore\/MPlayDisplayDriver.h\"\n#include \"IECore\/Exception.h\"\n#include \"IECore\/SimpleTypedData.h\"\n\nusing namespace std;\nusing namespace IECore;\nusing namespace Imath;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Header definitions required by imdisplay\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct MPlayDisplayDriver::ImageHeader\n{\n\tImageHeader( const V2i &resolution, size_t numPlanes )\n\t{\n\t\tmagicNumber = (('h'<<24)+('M'<<16)+('P'<<8)+'0');\n\t\txRes = resolution.x;\n\t\tyRes = resolution.y;\n\t\tdataType = 0; \/\/ floating point data\n\t\tnumChannels = 0; \/\/ multiplane\n\t\tmultiPlaneCount = numPlanes;\n\t\treserved[0] = 0;\n\t\treserved[1] = 0;\n\t}\n\t\n\tint\tmagicNumber;\n\tint\txRes;\n\tint\tyRes;\n\tint\tdataType;\n\tint\tnumChannels;\n\tint\tmultiPlaneCount;\n\tint\treserved[2];\n};\n\nstruct MPlayDisplayDriver::TileHeader\n{\n\t\/\/ this weird invalid tile header is used to signify that\n\t\/\/ we're about to send a plane.\n\tTileHeader( size_t planeIndex )\n\t{\n\t\tx0 = -1;\n\t\tx1 = planeIndex;\n\t\ty0 = 0;\n\t\ty1 = 0;\n\t}\n\t\n\tTileHeader( const Box2i &box )\n\t{\n\t\tx0 = box.min.x;\n\t\tx1 = box.max.x;\n\t\ty0 = box.min.y;\n\t\ty1 = box.max.y;\n\t}\n\t\n\tint\tx0, x1;\n\tint\ty0, y1;\n};\n\nstruct MPlayDisplayDriver::PlaneHeader\n{\n\tPlaneHeader( const Plane &plane, size_t index )\n\t{\n\t\tplaneIndex = index;\n\t\tnameLength = plane.name.size();\n\t\tdataType = 0; \/\/ floating point data\n\t\tnumChannels = plane.channelIndices.size();\n\t\treserved[0] = 0;\n\t\treserved[1] = 0;\n\t\treserved[2] = 0;\n\t\treserved[3] = 0;\n\t}\n\t\n\tint\tplaneIndex;\n\tint\tnameLength;\n\tint\tdataType;\n\tint\tnumChannels;\n\tint\treserved[4];\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ MPlayDisplayDriver implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nIE_CORE_DEFINERUNTIMETYPED( MPlayDisplayDriver );\n\nconst DisplayDriver::DisplayDriverDescription<MPlayDisplayDriver> MPlayDisplayDriver::g_description;\n\nMPlayDisplayDriver::MPlayDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, IECore::ConstCompoundDataPtr parameters )\n\t:\tDisplayDriver( displayWindow, dataWindow, channelNames, parameters )\n{\n\t\/\/ Sort out our flat list of channels into planes, based on common prefixes\n\tPlane *currentPlane = 0;\n\tfor( vector<string>::const_iterator cIt = channelNames.begin(); cIt != channelNames.end(); cIt++ )\n\t{\n\t\tsize_t separatorIndex = cIt->find( '.' );\n\t\tstring planeName;\n\t\tstring channelName = *cIt;\n\t\tif( separatorIndex != string::npos )\n\t\t{\n\t\t\tplaneName = string( *cIt, 0, separatorIndex );\n\t\t\tchannelName = string( *cIt, separatorIndex );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tplaneName = \"C\";\n\t\t}\n\t\t\n\t\tif( !m_planes.size() || m_planes.rbegin()->name != planeName )\n\t\t{\n\t\t\tm_planes.push_back( Plane( planeName ) );\n\t\t\tcurrentPlane = &(*m_planes.rbegin());\n\t\t}\n\t\tcurrentPlane->channelNames.push_back( channelName );\n\t\tcurrentPlane->channelIndices.push_back( cIt - channelNames.begin() );\n\t}\n\t\n\t\/\/ Validate that our planes match mplay requirements\n\tfor( vector<Plane>::const_iterator pIt = m_planes.begin(); pIt != m_planes.end(); pIt++ )\n\t{\n\t\tif(\n\t\t\tpIt->channelNames.size() != 1 &&\n\t\t\tpIt->channelNames.size() != 3 &&\n\t\t\tpIt->channelNames.size() != 4\n\t\t)\n\t\t{\n\t\t\tthrow Exception( \"MPlayDisplayDriver only supports 1, 3, and 4 channel images\" );\n\t\t}\n\t}\n\t\n\t\/\/ Construct a command line calling imdisplay, and open it as a pipe\n\tstd::string commandLine = \"imdisplay -f -p\";\n\t\n\tV2i origin = dataWindow.min - displayWindow.min;\n\tcommandLine += boost::str( boost::format( \" -o %d %d\" ) % origin.x % origin.y );\n\t\n\tV2i originalSize = displayWindow.size() + V2i( 1 );\n\tcommandLine += boost::str( boost::format( \" -Z %d %d\" ) % originalSize.x % originalSize.y );\n\t\t\t\n\tconst StringData *extraArguments = parameters->member<StringData>( \"imdisplayExtraArguments\" );\n\tif( extraArguments && extraArguments->readable().size() )\n\t{\n\t\tcommandLine += \" \" + extraArguments->readable();\n\t}\n\t\t\n\tm_imDisplayStdIn = popen( commandLine.c_str(), \"w\" );\n\n\t\/\/ Pipe out our image header\n\tImageHeader header( dataWindow.size() + V2i( 1 ), m_planes.size() );\n\tfwrite( &header, sizeof( ImageHeader ), 1, m_imDisplayStdIn );\n\t\n\t\/\/ Pipe out a header for each of our planes\n\tfor( vector<Plane>::const_iterator pIt = m_planes.begin(); pIt != m_planes.end(); pIt++ )\n\t{\n\t\tPlaneHeader planeHeader( *pIt, pIt - m_planes.begin() );\t\n\t\tfwrite( &planeHeader, sizeof( PlaneHeader ), 1, m_imDisplayStdIn );\n\t\tfwrite( &(pIt->name[0]), pIt->name.size(), 1, m_imDisplayStdIn );\n\t}\n\t\n}\n\nMPlayDisplayDriver::~MPlayDisplayDriver()\n{\n\t\/\/ in case imageClose() wasn't called for any reason.\n\tif( m_imDisplayStdIn )\n\t{\n\t\tpclose( m_imDisplayStdIn );\n\t}\n}\n\nbool MPlayDisplayDriver::scanLineOrderOnly() const\n{\n\treturn false;\n}\n\nvoid MPlayDisplayDriver::imageData( const Imath::Box2i &box, const float *data, size_t dataSize )\n{\t\n\tfor( size_t planeIndex = 0; planeIndex < m_planes.size(); planeIndex++ )\n\t{\n\t\tconst Plane &plane = m_planes[planeIndex];\n\t\n\t\tTileHeader planeHeader( planeIndex );\n\t\tfwrite( &planeHeader, sizeof( planeHeader ), 1, m_imDisplayStdIn );\n\t\n\t\tTileHeader tileHeader( box );\n\t\tfwrite( &tileHeader, sizeof( tileHeader ), 1, m_imDisplayStdIn );\n\t\t\n\t\tconst size_t numPixels = ( box.size().x + 1 ) * ( box.size().y + 1 );\n\t\tif( false && m_planes.size() == 1 )\n\t\t{\n\t\t\t\/\/ the data is already just as we need it, so we can just write it as-is\n\t\t\tfwrite( data, sizeof( float ), plane.channelIndices.size() * numPixels, m_imDisplayStdIn );\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ need to create interleaved data for the channels in the current plane\n\t\t\tstd::vector<float> planeData( plane.channelIndices.size() * numPixels );\n\t\t\tconst float *in = data;\n\t\t\tfloat *out = &planeData[0];\n\t\t\tconst size_t numInChannels = channelNames().size();\n\t\t\tconst size_t numOutChannels = plane.channelIndices.size();\n\t\t\t\t\t\t\t\t\t\n\t\t\tfor( size_t i=0; i<numPixels; ++i )\n\t\t\t{\n\t\t\t\tfor( size_t c=0; c<numOutChannels; ++c )\n\t\t\t\t{\n\t\t\t\t\t*out++ = in[plane.channelIndices[c]];\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tin += numInChannels;\n\t\t\t}\n\t\t\t\n\t\t\tfwrite( &planeData[0], sizeof( float ), planeData.size(), m_imDisplayStdIn );\n\t\t}\n\t}\n}\n\nvoid MPlayDisplayDriver::imageClose()\n{\n\tpclose( m_imDisplayStdIn );\n\tm_imDisplayStdIn = 0;\n}\n\n<commit_msg>Fixed problem when rendering crop regions with a non-zero origin.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. 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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/format.hpp\"\n\n#include \"IECore\/MPlayDisplayDriver.h\"\n#include \"IECore\/Exception.h\"\n#include \"IECore\/SimpleTypedData.h\"\n\nusing namespace std;\nusing namespace IECore;\nusing namespace Imath;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Header definitions required by imdisplay\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct MPlayDisplayDriver::ImageHeader\n{\n\tImageHeader( const V2i &resolution, size_t numPlanes )\n\t{\n\t\tmagicNumber = (('h'<<24)+('M'<<16)+('P'<<8)+'0');\n\t\txRes = resolution.x;\n\t\tyRes = resolution.y;\n\t\tdataType = 0; \/\/ floating point data\n\t\tnumChannels = 0; \/\/ multiplane\n\t\tmultiPlaneCount = numPlanes;\n\t\treserved[0] = 0;\n\t\treserved[1] = 0;\n\t}\n\t\n\tint\tmagicNumber;\n\tint\txRes;\n\tint\tyRes;\n\tint\tdataType;\n\tint\tnumChannels;\n\tint\tmultiPlaneCount;\n\tint\treserved[2];\n};\n\nstruct MPlayDisplayDriver::TileHeader\n{\n\t\/\/ this weird invalid tile header is used to signify that\n\t\/\/ we're about to send a plane.\n\tTileHeader( size_t planeIndex )\n\t{\n\t\tx0 = -1;\n\t\tx1 = planeIndex;\n\t\ty0 = 0;\n\t\ty1 = 0;\n\t}\n\t\n\tTileHeader( const Box2i &box )\n\t{\n\t\tx0 = box.min.x;\n\t\tx1 = box.max.x;\n\t\ty0 = box.min.y;\n\t\ty1 = box.max.y;\n\t}\n\t\n\tint\tx0, x1;\n\tint\ty0, y1;\n};\n\nstruct MPlayDisplayDriver::PlaneHeader\n{\n\tPlaneHeader( const Plane &plane, size_t index )\n\t{\n\t\tplaneIndex = index;\n\t\tnameLength = plane.name.size();\n\t\tdataType = 0; \/\/ floating point data\n\t\tnumChannels = plane.channelIndices.size();\n\t\treserved[0] = 0;\n\t\treserved[1] = 0;\n\t\treserved[2] = 0;\n\t\treserved[3] = 0;\n\t}\n\t\n\tint\tplaneIndex;\n\tint\tnameLength;\n\tint\tdataType;\n\tint\tnumChannels;\n\tint\treserved[4];\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ MPlayDisplayDriver implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nIE_CORE_DEFINERUNTIMETYPED( MPlayDisplayDriver );\n\nconst DisplayDriver::DisplayDriverDescription<MPlayDisplayDriver> MPlayDisplayDriver::g_description;\n\nMPlayDisplayDriver::MPlayDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, IECore::ConstCompoundDataPtr parameters )\n\t:\tDisplayDriver( displayWindow, dataWindow, channelNames, parameters )\n{\n\t\/\/ Sort out our flat list of channels into planes, based on common prefixes\n\tPlane *currentPlane = 0;\n\tfor( vector<string>::const_iterator cIt = channelNames.begin(); cIt != channelNames.end(); cIt++ )\n\t{\n\t\tsize_t separatorIndex = cIt->find( '.' );\n\t\tstring planeName;\n\t\tstring channelName = *cIt;\n\t\tif( separatorIndex != string::npos )\n\t\t{\n\t\t\tplaneName = string( *cIt, 0, separatorIndex );\n\t\t\tchannelName = string( *cIt, separatorIndex );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tplaneName = \"C\";\n\t\t}\n\t\t\n\t\tif( !m_planes.size() || m_planes.rbegin()->name != planeName )\n\t\t{\n\t\t\tm_planes.push_back( Plane( planeName ) );\n\t\t\tcurrentPlane = &(*m_planes.rbegin());\n\t\t}\n\t\tcurrentPlane->channelNames.push_back( channelName );\n\t\tcurrentPlane->channelIndices.push_back( cIt - channelNames.begin() );\n\t}\n\t\n\t\/\/ Validate that our planes match mplay requirements\n\tfor( vector<Plane>::const_iterator pIt = m_planes.begin(); pIt != m_planes.end(); pIt++ )\n\t{\n\t\tif(\n\t\t\tpIt->channelNames.size() != 1 &&\n\t\t\tpIt->channelNames.size() != 3 &&\n\t\t\tpIt->channelNames.size() != 4\n\t\t)\n\t\t{\n\t\t\tthrow Exception( \"MPlayDisplayDriver only supports 1, 3, and 4 channel images\" );\n\t\t}\n\t}\n\t\n\t\/\/ Construct a command line calling imdisplay, and open it as a pipe\n\tstd::string commandLine = \"imdisplay -f -p\";\n\t\n\tcommandLine += boost::str( boost::format( \" -o %d %d\" ) % displayWindow.min.x % displayWindow.min.y );\n\t\n\tV2i originalSize = displayWindow.size() + V2i( 1 );\n\tcommandLine += boost::str( boost::format( \" -Z %d %d\" ) % originalSize.x % originalSize.y );\n\t\t\t\n\tconst StringData *extraArguments = parameters->member<StringData>( \"imdisplayExtraArguments\" );\n\tif( extraArguments && extraArguments->readable().size() )\n\t{\n\t\tcommandLine += \" \" + extraArguments->readable();\n\t}\n\t\t\n\tm_imDisplayStdIn = popen( commandLine.c_str(), \"w\" );\n\n\t\/\/ Pipe out our image header\n\tImageHeader header( dataWindow.size() + V2i( 1 ), m_planes.size() );\n\tfwrite( &header, sizeof( ImageHeader ), 1, m_imDisplayStdIn );\n\t\n\t\/\/ Pipe out a header for each of our planes\n\tfor( vector<Plane>::const_iterator pIt = m_planes.begin(); pIt != m_planes.end(); pIt++ )\n\t{\n\t\tPlaneHeader planeHeader( *pIt, pIt - m_planes.begin() );\t\n\t\tfwrite( &planeHeader, sizeof( PlaneHeader ), 1, m_imDisplayStdIn );\n\t\tfwrite( &(pIt->name[0]), pIt->name.size(), 1, m_imDisplayStdIn );\n\t}\n\t\n}\n\nMPlayDisplayDriver::~MPlayDisplayDriver()\n{\n\t\/\/ in case imageClose() wasn't called for any reason.\n\tif( m_imDisplayStdIn )\n\t{\n\t\tpclose( m_imDisplayStdIn );\n\t}\n}\n\nbool MPlayDisplayDriver::scanLineOrderOnly() const\n{\n\treturn false;\n}\n\nvoid MPlayDisplayDriver::imageData( const Imath::Box2i &box, const float *data, size_t dataSize )\n{\t\n\tfor( size_t planeIndex = 0; planeIndex < m_planes.size(); planeIndex++ )\n\t{\n\t\tconst Plane &plane = m_planes[planeIndex];\n\t\n\t\tTileHeader planeHeader( planeIndex );\n\t\tfwrite( &planeHeader, sizeof( planeHeader ), 1, m_imDisplayStdIn );\n\t\n\t\tTileHeader tileHeader( box );\n\t\tfwrite( &tileHeader, sizeof( tileHeader ), 1, m_imDisplayStdIn );\n\t\t\n\t\tconst size_t numPixels = ( box.size().x + 1 ) * ( box.size().y + 1 );\n\t\tif( false && m_planes.size() == 1 )\n\t\t{\n\t\t\t\/\/ the data is already just as we need it, so we can just write it as-is\n\t\t\tfwrite( data, sizeof( float ), plane.channelIndices.size() * numPixels, m_imDisplayStdIn );\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ need to create interleaved data for the channels in the current plane\n\t\t\tstd::vector<float> planeData( plane.channelIndices.size() * numPixels );\n\t\t\tconst float *in = data;\n\t\t\tfloat *out = &planeData[0];\n\t\t\tconst size_t numInChannels = channelNames().size();\n\t\t\tconst size_t numOutChannels = plane.channelIndices.size();\n\t\t\t\t\t\t\t\t\t\n\t\t\tfor( size_t i=0; i<numPixels; ++i )\n\t\t\t{\n\t\t\t\tfor( size_t c=0; c<numOutChannels; ++c )\n\t\t\t\t{\n\t\t\t\t\t*out++ = in[plane.channelIndices[c]];\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tin += numInChannels;\n\t\t\t}\n\t\t\t\n\t\t\tfwrite( &planeData[0], sizeof( float ), planeData.size(), m_imDisplayStdIn );\n\t\t}\n\t}\n}\n\nvoid MPlayDisplayDriver::imageClose()\n{\n\tpclose( m_imDisplayStdIn );\n\tm_imDisplayStdIn = 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n * Origin: I.Belikov, CERN, Jouri.Belikov@cern.ch *\n ****************************************************************************\/\n\nInt_t AliTPCtest() {\n Int_t rc=0;\n\n\/\/Test TPC simulation\n gROOT->LoadMacro(\"$(ALICE_ROOT)\/macros\/grun.C\");\n grun();\n\n \n\nAliKalmanTrack::SetConvConst(1000\/0.299792458\/gAlice->Field()->SolenoidField());\n\n Int_t ver=gAlice->GetDetector(\"TPC\")->IsVersion();\n delete gAlice; gAlice=0;\n\n if ((ver!=1)&&(ver!=2)) {\n cerr<<\"Invalid TPC version: \"<<ver<<\" ! (must be 1 or 2)\\n\";\n return 12345;\n }\n\n if (ver==2) {\n gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCHits2Digits.C\");\n if (rc=AliTPCHits2Digits()) return rc;\n\n \/\/gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCDisplayDigits.C\");\n \/\/if (rc=AliTPCDisplayDigits(1,1)) return rc;\n }\n\n\n\/\/Test TPC reconstruction\n gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCFindClusters.C\");\n if (rc=AliTPCFindClusters()) return rc;\n\n \/\/gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCDisplayClusters.C\");\n \/\/if (rc=AliTPCDisplayClusters()) return rc;\n\n gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCFindTracks.C\");\n if (rc=AliTPCFindTracks()) return rc;\n\n gSystem->SetIncludePath(\"-I$ROOTSYS\/include -I$ALICE_ROOT\/include -I$ALICE_ROOT\/TPC -I$ALICE_ROOT\/CONTAINERS\");\n gROOT->ProcessLine(\".L $(ALICE_ROOT)\/TPC\/AliTPCComparison.C+\");\n if (rc=AliTPCComparison()) return rc;\n\n return rc;\n}\n\n<commit_msg>Recompilation of AliTPCComparison.C to avoid clashes between platforms<commit_after>\/****************************************************************************\n * Origin: I.Belikov, CERN, Jouri.Belikov@cern.ch *\n ****************************************************************************\/\n\nInt_t AliTPCtest() {\n Int_t rc=0;\n\n\/\/Test TPC simulation\n gROOT->LoadMacro(\"$(ALICE_ROOT)\/macros\/grun.C\");\n grun();\n\n \n\nAliKalmanTrack::SetConvConst(1000\/0.299792458\/gAlice->Field()->SolenoidField());\n\n Int_t ver=gAlice->GetDetector(\"TPC\")->IsVersion();\n delete gAlice; gAlice=0;\n\n if ((ver!=1)&&(ver!=2)) {\n cerr<<\"Invalid TPC version: \"<<ver<<\" ! (must be 1 or 2)\\n\";\n return 12345;\n }\n\n if (ver==2) {\n gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCHits2Digits.C\");\n if (rc=AliTPCHits2Digits()) return rc;\n\n \/\/gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCDisplayDigits.C\");\n \/\/if (rc=AliTPCDisplayDigits(1,1)) return rc;\n }\n\n\n\/\/Test TPC reconstruction\n gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCFindClusters.C\");\n if (rc=AliTPCFindClusters()) return rc;\n\n \/\/gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCDisplayClusters.C\");\n \/\/if (rc=AliTPCDisplayClusters()) return rc;\n\n gROOT->LoadMacro(\"$(ALICE_ROOT)\/TPC\/AliTPCFindTracks.C\");\n if (rc=AliTPCFindTracks()) return rc;\n\n gSystem->SetIncludePath(\"-I$ROOTSYS\/include -I$ALICE_ROOT\/include -I$ALICE_ROOT\/TPC -I$ALICE_ROOT\/CONTAINERS\");\n gROOT->ProcessLine(\".L $(ALICE_ROOT)\/TPC\/AliTPCComparison.C++\");\n if (rc=AliTPCComparison()) return rc;\n\n return rc;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n *\t notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *\t notice, this list of conditions and the following disclaimer in\n *\t the documentation and\/or other materials provided with the\n *\t distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *\t if any, must include the following acknowledgment: \n *\t\t \"This product includes software developed by the\n *\t\t Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *\t Alternately, this acknowledgment may appear in the software itself,\n *\t if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *\t not be used to endorse or promote products derived from this\n *\t software without prior written permission. For written \n *\t permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *\t nor may \"Apache\" appear in their name, without prior written\n *\t permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.\tIN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#include \"TraceListenerDefault.hpp\"\n\n\n\n#include <PlatformSupport\/PrintWriter.hpp>\n\n\n\n#include <DOMSupport\/DOMServices.hpp>\n\n\n\n#include <XPath\/NodeRefListBase.hpp>\n#include <XPath\/XPath.hpp>\n\n\n\n#include \"Constants.hpp\"\n#include \"ElemTextLiteral.hpp\"\n#include \"ElemTemplate.hpp\"\n#include \"GenerateEvent.hpp\"\n#include \"SelectionEvent.hpp\"\n#include \"StylesheetRoot.hpp\"\n#include \"TracerEvent.hpp\"\n\n\n\nTraceListenerDefault::TraceListenerDefault(\n\t\t\tPrintWriter&\tthePrintWriter,\n\t\t\tbool\t\t\ttraceTemplates,\n\t\t\tbool\t\t\ttraceElements,\n\t\t\tbool\t\t\ttraceGeneration,\n\t\t\tbool\t\t\ttraceSelection) :\n\tm_printWriter(thePrintWriter),\n\tm_traceTemplates(traceTemplates),\n\tm_traceElements(traceElements),\n\tm_traceGeneration(traceGeneration),\n\tm_traceSelection(traceSelection)\n{\n}\n\n\n\nTraceListenerDefault::~TraceListenerDefault()\n{\n}\n\n\n\nvoid\nTraceListenerDefault::trace(const TracerEvent&\tev)\n{\n\tswitch(ev.m_styleNode.getXSLToken())\n\t{\n\tcase Constants::ELEMNAME_TEXTLITERALRESULT:\n\t\tif(m_traceElements == true)\n\t\t{\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Line #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getLineNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Column #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getColumnNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\": \"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getElementName());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\" \"));\n\n\t\t\tconst ElemTextLiteral&\tetl = static_cast<const ElemTextLiteral&>(ev.m_styleNode);\n\n\t\t\tm_printWriter.println(c_wstr(etl.getText()), etl.getText().size());\n\t\t}\n\t\tbreak;\n\n\tcase Constants::ELEMNAME_TEMPLATE:\n\t\tif(m_traceTemplates == true || m_traceElements == true)\n\t\t{\n\t\t\tconst ElemTemplate&\t\tet = static_cast<const ElemTemplate&>(ev.m_styleNode);\n\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Line #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getLineNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Column #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getColumnNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\": \"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getElementName());\n\n\t\t\tconst XPath* const\ttheMatchPattern =\n\t\t\t\tet.getMatchPattern();\n\n\t\t\tif(0 != theMatchPattern)\n\t\t\t{\n\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\" match=\\\"\"));\n\t\t\t\tm_printWriter.print(theMatchPattern->getExpression().getCurrentPattern());\n\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"\\\" \"));\n\t\t\t}\n\n\t\t\tconst QName&\ttheName = et.getName();\n\n\t\t\tif(theName.isEmpty() == false)\n\t\t\t{\n\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"name=\\\"\"));\n\n\t\t\t\tconst XalanDOMString&\ttheNamespace =\n\t\t\t\t\ttheName.getNamespace();\n\n\t\t\t\tif (isEmpty(theNamespace) == false)\n\t\t\t\t{\n\t\t\t\t\tm_printWriter.print(theNamespace);\n\t\t\t\t\tm_printWriter.print(':');\n\t\t\t\t}\n\n\t\t\t\tm_printWriter.print(theName.getLocalPart());\n\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"\\\" \"));\n\t\t\t}\n\n\t\t\tm_printWriter.println();\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tif(m_traceElements == true)\n\t\t{\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Line #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getLineNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", Column #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getColumnNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\": \"));\n\t\t\tm_printWriter.println(ev.m_styleNode.getElementName());\n\t\t}\n\t\tbreak;\n\t}\n}\n\n\n\nvoid\nTraceListenerDefault::selected(const SelectionEvent&\tev)\n{\n if(m_traceSelection == true)\n {\n\t\tconst ElemTemplateElement&\tete = ev.m_styleNode;\n\n\t\tif(ev.m_styleNode.getLineNumber() == 0)\n\t\t{\n\t\t\t\/\/ You may not have line numbers if the selection is occuring from a\n\t\t\t\/\/ default template.\n\n\t\t\tElemTemplateElement* const\tparent = ete.getParentNodeElem();\n\n\t\t\tif(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRootRule())\n\t\t\t{\n\t\t\t\tm_printWriter.print(\"(default root rule) \");\n\t\t\t}\n\t\t\telse if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultTextRule())\n\t\t\t{\n\t\t\t\tm_printWriter.print(\"(default text rule) \");\n\t\t\t}\n\t\t\telse if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRule())\n\t\t\t{\n\t\t\t\tm_printWriter.print(\"(default rule) \");\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Line #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getLineNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Column #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getColumnNumber());\n\t\t\tm_printWriter.print(\", \");\n\t\t}\n\n\t\tm_printWriter.print(ete.getElementName());\n\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\tm_printWriter.print(ev.m_attributeName);\n\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"=\\\"\"));\n\t\tm_printWriter.print(ev.m_xpath.getExpression().getCurrentPattern());\n\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"\\\": \"));\n\n\t\tif(ev.m_selection->getType() == XObject::eTypeNodeSet)\n\t\t{\n\t\t\tm_printWriter.println();\n\n\t\t\tconst NodeRefListBase&\tnl = ev.m_selection->nodeset();\n\n\t\t\tconst unsigned int\tn = nl.getLength();\n\n\t\t\tif(n == 0)\n\t\t\t{\n\t\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\" [empty node list]\"));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor(unsigned int i = 0; i < n; i++)\n\t\t\t\t{\n\t\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\" \"));\n\t\t\t\t\tm_printWriter.println(DOMServices::getNodeData(*nl.item(i)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_printWriter.println(ev.m_selection->str());\n\t\t}\n }\n}\n\n\n\nvoid\nTraceListenerDefault::generated(const GenerateEvent&\tev)\n{\n\tif(m_traceGeneration == true)\n\t{\n\t\tswitch(ev.m_eventType)\n\t\t{\n\t\tcase GenerateEvent::EVENTTYPE_STARTDOCUMENT:\n\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\"STARTDOCUMENT\"));\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_ENDDOCUMENT:\n\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\"ENDDOCUMENT\"));\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_STARTELEMENT:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"STARTELEMENT: \"));\n\t\t\tm_printWriter.println(ev.m_name);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_ENDELEMENT:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"ENDELEMENT: \"));\n\t\t\tm_printWriter.println(ev.m_name);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_CHARACTERS:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"CHARACTERS: \"));\n\t\t\tm_printWriter.println(ev.m_characters);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_CDATA:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"CDATA: \"));\n\t\t\tm_printWriter.println(ev.m_characters);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_COMMENT:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"COMMENT: \"));\n\t\t\tm_printWriter.println(ev.m_data);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_PI:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"PI: \"));\n\t\t\tm_printWriter.print(ev.m_name);\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\t\tm_printWriter.println(ev.m_data);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_ENTITYREF:\n\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\"ENTITYREF: \"));\n\t\t\tm_printWriter.println(ev.m_name);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_IGNORABLEWHITESPACE:\n\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\"IGNORABLEWHITESPACE\"));\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<commit_msg>Fixed minor formatting glitch.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n *\t notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *\t notice, this list of conditions and the following disclaimer in\n *\t the documentation and\/or other materials provided with the\n *\t distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *\t if any, must include the following acknowledgment: \n *\t\t \"This product includes software developed by the\n *\t\t Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *\t Alternately, this acknowledgment may appear in the software itself,\n *\t if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *\t not be used to endorse or promote products derived from this\n *\t software without prior written permission. For written \n *\t permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *\t nor may \"Apache\" appear in their name, without prior written\n *\t permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.\tIN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#include \"TraceListenerDefault.hpp\"\n\n\n\n#include <PlatformSupport\/PrintWriter.hpp>\n\n\n\n#include <DOMSupport\/DOMServices.hpp>\n\n\n\n#include <XPath\/NodeRefListBase.hpp>\n#include <XPath\/XPath.hpp>\n\n\n\n#include \"Constants.hpp\"\n#include \"ElemTextLiteral.hpp\"\n#include \"ElemTemplate.hpp\"\n#include \"GenerateEvent.hpp\"\n#include \"SelectionEvent.hpp\"\n#include \"StylesheetRoot.hpp\"\n#include \"TracerEvent.hpp\"\n\n\n\nTraceListenerDefault::TraceListenerDefault(\n\t\t\tPrintWriter&\tthePrintWriter,\n\t\t\tbool\t\t\ttraceTemplates,\n\t\t\tbool\t\t\ttraceElements,\n\t\t\tbool\t\t\ttraceGeneration,\n\t\t\tbool\t\t\ttraceSelection) :\n\tm_printWriter(thePrintWriter),\n\tm_traceTemplates(traceTemplates),\n\tm_traceElements(traceElements),\n\tm_traceGeneration(traceGeneration),\n\tm_traceSelection(traceSelection)\n{\n}\n\n\n\nTraceListenerDefault::~TraceListenerDefault()\n{\n}\n\n\n\nvoid\nTraceListenerDefault::trace(const TracerEvent&\tev)\n{\n\tswitch(ev.m_styleNode.getXSLToken())\n\t{\n\tcase Constants::ELEMNAME_TEXTLITERALRESULT:\n\t\tif(m_traceElements == true)\n\t\t{\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Line #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getLineNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Column #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getColumnNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\": \"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getElementName());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\" \"));\n\n\t\t\tconst ElemTextLiteral&\tetl = static_cast<const ElemTextLiteral&>(ev.m_styleNode);\n\n\t\t\tm_printWriter.println(c_wstr(etl.getText()), etl.getText().size());\n\t\t}\n\t\tbreak;\n\n\tcase Constants::ELEMNAME_TEMPLATE:\n\t\tif(m_traceTemplates == true || m_traceElements == true)\n\t\t{\n\t\t\tconst ElemTemplate&\t\tet = static_cast<const ElemTemplate&>(ev.m_styleNode);\n\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Line #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getLineNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Column #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getColumnNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\": \"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getElementName());\n\n\t\t\tconst XPath* const\ttheMatchPattern =\n\t\t\t\tet.getMatchPattern();\n\n\t\t\tif(0 != theMatchPattern)\n\t\t\t{\n\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\" match=\\\"\"));\n\t\t\t\tm_printWriter.print(theMatchPattern->getExpression().getCurrentPattern());\n\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"\\\" \"));\n\t\t\t}\n\n\t\t\tconst QName&\ttheName = et.getName();\n\n\t\t\tif(theName.isEmpty() == false)\n\t\t\t{\n\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"name=\\\"\"));\n\n\t\t\t\tconst XalanDOMString&\ttheNamespace =\n\t\t\t\t\ttheName.getNamespace();\n\n\t\t\t\tif (isEmpty(theNamespace) == false)\n\t\t\t\t{\n\t\t\t\t\tm_printWriter.print(theNamespace);\n\t\t\t\t\tm_printWriter.print(':');\n\t\t\t\t}\n\n\t\t\t\tm_printWriter.print(theName.getLocalPart());\n\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"\\\" \"));\n\t\t\t}\n\n\t\t\tm_printWriter.println();\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tif(m_traceElements == true)\n\t\t{\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Line #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getLineNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", Column #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getColumnNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\": \"));\n\t\t\tm_printWriter.println(ev.m_styleNode.getElementName());\n\t\t}\n\t\tbreak;\n\t}\n}\n\n\n\nvoid\nTraceListenerDefault::selected(const SelectionEvent&\tev)\n{\n if(m_traceSelection == true)\n {\n\t\tconst ElemTemplateElement&\tete = ev.m_styleNode;\n\n\t\tif(ev.m_styleNode.getLineNumber() == 0)\n\t\t{\n\t\t\t\/\/ You may not have line numbers if the selection is occuring from a\n\t\t\t\/\/ default template.\n\n\t\t\tElemTemplateElement* const\tparent = ete.getParentNodeElem();\n\n\t\t\tif(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRootRule())\n\t\t\t{\n\t\t\t\tm_printWriter.print(\"(default root rule) \");\n\t\t\t}\n\t\t\telse if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultTextRule())\n\t\t\t{\n\t\t\t\tm_printWriter.print(\"(default text rule) \");\n\t\t\t}\n\t\t\telse if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRule())\n\t\t\t{\n\t\t\t\tm_printWriter.print(\"(default rule) \");\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Line #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getLineNumber());\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"Column #\"));\n\t\t\tm_printWriter.print(ev.m_styleNode.getColumnNumber());\n\t\t\tm_printWriter.print(\", \");\n\t\t}\n\n\t\tm_printWriter.print(ete.getElementName());\n\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\tm_printWriter.print(ev.m_attributeName);\n\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"=\\\"\"));\n\t\tm_printWriter.print(ev.m_xpath.getExpression().getCurrentPattern());\n\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"\\\": \"));\n\n\t\tif(ev.m_selection->getType() == XObject::eTypeNodeSet)\n\t\t{\n\t\t\tm_printWriter.println();\n\n\t\t\tconst NodeRefListBase&\tnl = ev.m_selection->nodeset();\n\n\t\t\tconst unsigned int\tn = nl.getLength();\n\n\t\t\tif(n == 0)\n\t\t\t{\n\t\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\" [empty node list]\"));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor(unsigned int i = 0; i < n; i++)\n\t\t\t\t{\n\t\t\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\" \"));\n\t\t\t\t\tm_printWriter.println(DOMServices::getNodeData(*nl.item(i)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_printWriter.println(ev.m_selection->str());\n\t\t}\n }\n}\n\n\n\nvoid\nTraceListenerDefault::generated(const GenerateEvent&\tev)\n{\n\tif(m_traceGeneration == true)\n\t{\n\t\tswitch(ev.m_eventType)\n\t\t{\n\t\tcase GenerateEvent::EVENTTYPE_STARTDOCUMENT:\n\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\"STARTDOCUMENT\"));\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_ENDDOCUMENT:\n\t\t\tm_printWriter.println();\n\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\"ENDDOCUMENT\"));\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_STARTELEMENT:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"STARTELEMENT: \"));\n\t\t\tm_printWriter.println(ev.m_name);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_ENDELEMENT:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"ENDELEMENT: \"));\n\t\t\tm_printWriter.println(ev.m_name);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_CHARACTERS:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"CHARACTERS: \"));\n\t\t\tm_printWriter.println(ev.m_characters);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_CDATA:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"CDATA: \"));\n\t\t\tm_printWriter.println(ev.m_characters);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_COMMENT:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"COMMENT: \"));\n\t\t\tm_printWriter.println(ev.m_data);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_PI:\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\"PI: \"));\n\t\t\tm_printWriter.print(ev.m_name);\n\t\t\tm_printWriter.print(XALAN_STATIC_UCODE_STRING(\", \"));\n\t\t\tm_printWriter.println(ev.m_data);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_ENTITYREF:\n\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\"ENTITYREF: \"));\n\t\t\tm_printWriter.println(ev.m_name);\n\t\t\tbreak;\n\n\t\tcase GenerateEvent::EVENTTYPE_IGNORABLEWHITESPACE:\n\t\t\tm_printWriter.println(XALAN_STATIC_UCODE_STRING(\"IGNORABLEWHITESPACE\"));\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * MeshGeneratorMarchingcube.cpp\n *\n * Created on: Jun 6, 2016\n * Author: hanyinbo\n *\/\n\n#include \"MeshGeneratorMarchingcube.h\"\n#include \"utils\/mesh\/MeshIO.h\"\n#include \"AppParams.h\"\n#include \"cuda\/CudaWrappers.h\"\n#include \"cuda\/CudaDeviceDataMan.h\"\n#include\"keyframeMan.h\"\nMeshGeneratorMarchingcube::MeshGeneratorMarchingcube() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nMeshGeneratorMarchingcube::~MeshGeneratorMarchingcube() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid MeshGeneratorMarchingcube::generateMesh()\n{\n\n\tcudaMarchingcube(AppParams::instance()->_switch_params.useRGBData ,\n\t\t\t300*AppParams::instance()->_volume_params.fVolumeMeterSize\/AppParams::instance()->_volume_params.nResolution);\n}\nbool MeshGeneratorMarchingcube::copyTrianglesToCPU()\n{\n\tMarchingcubeData marchingcube_data =CudaDeviceDataMan::instance()->_marchingcube_data;\n\tMarchingcubeData marchingcube_data_cpu;\n\tmarchingcube_data_cpu.init(CPU);\n\tmarchingcube_data_cpu.copyFrom(marchingcube_data);\n\tint triangle_num=marchingcube_data_cpu.triangleNums();\n\tcout << \"Marching Cubes triangles = \" <<triangle_num << std::endl;\n\tif (triangle_num == 0)\n\t{\n\t\treturn false;\n\t}\n\t_meshes.m_Vertices.resize( 3 * triangle_num);\n\tif (AppParams::instance()->_switch_params.useRGBData == true)\n\t{\n\t\t_meshes.m_Colors.resize(3* triangle_num);\n\t}\n\n\t\/\/float3* vc = (float3*) triangle;\n\tfor (unsigned int i = 0; i < triangle_num; i++) {\n\t\tTriangle* ptriangle=marchingcube_data_cpu.triangleData()+i;\n\t\t_meshes.m_Vertices[3*i] = ptriangle->v0.pos;\n\t\t_meshes.m_Vertices[3 * i + 1] = ptriangle->v1.pos;\n\t\t_meshes.m_Vertices[3 * i + 2] = ptriangle->v2.pos;\n\t\tif (AppParams::instance()->_switch_params.useRGBData == true)\n\t\t{\n\t\t\t_meshes.m_Colors[3 * i] = make_float4(ptriangle->v0.color.x,ptriangle->v0.color.y,ptriangle->v0.color.z, 1.0);\n\t\t\t_meshes.m_Colors[3 * i + 1] = make_float4(ptriangle->v1.color.x,ptriangle->v1.color.y,ptriangle->v1.color.z, 1.0);\n\t\t\t_meshes.m_Colors[3 * i + 2] = make_float4(ptriangle->v2.color.x,ptriangle->v2.color.y,ptriangle->v2.color.z, 1.0);\n\t\t}\n\t}\n\n\tmarchingcube_data_cpu.destroy();\n\treturn true;\n}\nbool MeshGeneratorMarchingcube::saveMesh(const string& filename)\n{\n\tif(false==copyTrianglesToCPU())\n\t{\n\t\tcout<<\"copy triangles to cpu failed\"<<endl;\n\t\treturn false;\n\n\t}\n\t\/\/create index buffer (required for merging the triangle soup)\n\t_meshes.m_FaceIndicesVertices.resize(_meshes.m_Vertices.size());\n\tfor (unsigned int i = 0; i < (unsigned int)_meshes.m_Vertices.size() \/ 3; i++) {\n\t\t_meshes.m_FaceIndicesVertices[i][0] = 3 * i + 0;\n\t\t_meshes.m_FaceIndicesVertices[i][1] = 3 * i + 1;\n\t\t_meshes.m_FaceIndicesVertices[i][2] = 3 * i + 2;\n\t}\n\tstd::cout << \"vertices:\\t\" << _meshes.m_Vertices.size() << std::endl;\n\tstd::cout << \"faces :\\t\" << _meshes.m_FaceIndicesVertices.size() << std::endl;\n\tstd::cout << \"merging close vertices... \";\n\t_meshes.mergeCloseVertices(0.0001f, true);\n\tstd::cout << \"done!\" << std::endl;\n\tstd::cout << \"vertices e:\\t\" << _meshes.m_Vertices.size() << std::endl;\n\tstd::cout << \"faces :\\t\" << _meshes.m_FaceIndicesVertices.size() << std::endl;\n\tstd::cout << \"removing duplicate faces... \";\n\t_meshes.removeDuplicateFaces();\n\tstd::cout << \"done!\" << std::endl;\n\t_meshes.computeVertexNormals();\n\tstd::cout << \"vertices :\\t\" << _meshes.m_Vertices.size() << std::endl;\n\tstd::cout << \"faces :\\t\" << _meshes.m_FaceIndicesVertices.size() << std::endl;\n\n\/\/\tm_meshData.applyTransform(transform);\n\n\tstd::cout << \"saving mesh (\" << filename << \") ...\";\n\tml::MeshIOf::saveToFile(filename, _meshes);\n\tstd::cout << \"done!\" << std::endl;\n\treturn 0;\/\/textureMesh(filename);\n}\n<commit_msg>Update MeshGeneratorMarchingcube.cpp<commit_after>\/*\n * MeshGeneratorMarchingcube.cpp\n *\n * Created on: Jun 6, 2016\n * Author: hanyinbo\n *\/\n\n#include \"MeshGeneratorMarchingcube.h\"\n#include \"utils\/mesh\/MeshIO.h\"\n#include \"AppParams.h\"\n#include \"cuda\/CudaWrappers.h\"\n#include \"cuda\/CudaDeviceDataMan.h\"\nMeshGeneratorMarchingcube::MeshGeneratorMarchingcube() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nMeshGeneratorMarchingcube::~MeshGeneratorMarchingcube() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid MeshGeneratorMarchingcube::generateMesh()\n{\n\n\tcudaMarchingcube(AppParams::instance()->_switch_params.useRGBData ,\n\t\t\t300*AppParams::instance()->_volume_params.fVolumeMeterSize\/AppParams::instance()->_volume_params.nResolution);\n}\nbool MeshGeneratorMarchingcube::copyTrianglesToCPU()\n{\n\tMarchingcubeData marchingcube_data =CudaDeviceDataMan::instance()->_marchingcube_data;\n\tMarchingcubeData marchingcube_data_cpu;\n\tmarchingcube_data_cpu.init(CPU);\n\tmarchingcube_data_cpu.copyFrom(marchingcube_data);\n\tint triangle_num=marchingcube_data_cpu.triangleNums();\n\tcout << \"Marching Cubes triangles = \" <<triangle_num << std::endl;\n\tif (triangle_num == 0)\n\t{\n\t\treturn false;\n\t}\n\t_meshes.m_Vertices.resize( 3 * triangle_num);\n\tif (AppParams::instance()->_switch_params.useRGBData == true)\n\t{\n\t\t_meshes.m_Colors.resize(3* triangle_num);\n\t}\n\n\t\/\/float3* vc = (float3*) triangle;\n\tfor (unsigned int i = 0; i < triangle_num; i++) {\n\t\tTriangle* ptriangle=marchingcube_data_cpu.triangleData()+i;\n\t\t_meshes.m_Vertices[3*i] = ptriangle->v0.pos;\n\t\t_meshes.m_Vertices[3 * i + 1] = ptriangle->v1.pos;\n\t\t_meshes.m_Vertices[3 * i + 2] = ptriangle->v2.pos;\n\t\tif (AppParams::instance()->_switch_params.useRGBData == true)\n\t\t{\n\t\t\t_meshes.m_Colors[3 * i] = make_float4(ptriangle->v0.color.x,ptriangle->v0.color.y,ptriangle->v0.color.z, 1.0);\n\t\t\t_meshes.m_Colors[3 * i + 1] = make_float4(ptriangle->v1.color.x,ptriangle->v1.color.y,ptriangle->v1.color.z, 1.0);\n\t\t\t_meshes.m_Colors[3 * i + 2] = make_float4(ptriangle->v2.color.x,ptriangle->v2.color.y,ptriangle->v2.color.z, 1.0);\n\t\t}\n\t}\n\n\tmarchingcube_data_cpu.destroy();\n\treturn true;\n}\nbool MeshGeneratorMarchingcube::saveMesh(const string& filename)\n{\n\tif(false==copyTrianglesToCPU())\n\t{\n\t\tcout<<\"copy triangles to cpu failed\"<<endl;\n\t\treturn false;\n\n\t}\n\t\/\/create index buffer (required for merging the triangle soup)\n\t_meshes.m_FaceIndicesVertices.resize(_meshes.m_Vertices.size());\n\tfor (unsigned int i = 0; i < (unsigned int)_meshes.m_Vertices.size() \/ 3; i++) {\n\t\t_meshes.m_FaceIndicesVertices[i][0] = 3 * i + 0;\n\t\t_meshes.m_FaceIndicesVertices[i][1] = 3 * i + 1;\n\t\t_meshes.m_FaceIndicesVertices[i][2] = 3 * i + 2;\n\t}\n\tstd::cout << \"vertices:\\t\" << _meshes.m_Vertices.size() << std::endl;\n\tstd::cout << \"faces :\\t\" << _meshes.m_FaceIndicesVertices.size() << std::endl;\n\tstd::cout << \"merging close vertices... \";\n\t_meshes.mergeCloseVertices(0.0001f, true);\n\tstd::cout << \"done!\" << std::endl;\n\tstd::cout << \"vertices e:\\t\" << _meshes.m_Vertices.size() << std::endl;\n\tstd::cout << \"faces :\\t\" << _meshes.m_FaceIndicesVertices.size() << std::endl;\n\tstd::cout << \"removing duplicate faces... \";\n\t_meshes.removeDuplicateFaces();\n\tstd::cout << \"done!\" << std::endl;\n\t_meshes.computeVertexNormals();\n\tstd::cout << \"vertices :\\t\" << _meshes.m_Vertices.size() << std::endl;\n\tstd::cout << \"faces :\\t\" << _meshes.m_FaceIndicesVertices.size() << std::endl;\n\n\/\/\tm_meshData.applyTransform(transform);\n\n\tstd::cout << \"saving mesh (\" << filename << \") ...\";\n\tml::MeshIOf::saveToFile(filename, _meshes);\n\tstd::cout << \"done!\" << std::endl;\n\treturn 0;\/\/textureMesh(filename);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2012, Paul Houx\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/*\n\tThis sample will show how to use the CameraStereo class to setup and render stereoscopic images.\n\tThe camera contains different matrices for the left and right eye of the viewer. By rendering the scene\n\ttwice, once for each eye, we can view the scene in 3D on monitors or televisions that support 3D.\n\n\tHere, we divide the window into a left and right half and render the scene to each half. This is called\n\tside-by-side stereoscopic and is supported by most 3D televisions. Simply connect your computer to\n\tsuch a television, run the sample in full screen and enable the TV's 3D mode.\n\n\tWhen creating your own stereoscopic application, be careful how you choose your focal length.\n\tAn excellent article can be found here:\n\thttp:\/\/paulbourke.net\/miscellaneous\/stereographics\/stereorender\/\n\n\tThe CameraStereo class is based on the Off-Axis method described in this article. \n*\/\n\n#include \"cinder\/app\/AppBasic.h\"\n\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/CameraStereoAutoFocuser.h\"\n#include \"cinder\/gl\/GlslProg.h\"\n#include \"cinder\/gl\/Vbo.h\"\n\n#include \"cinder\/Camera.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/MayaCamUI.h\"\n#include \"cinder\/Rand.h\"\n#include \"cinder\/TriMesh.h\"\n#include \"cinder\/ObjLoader.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nclass StereoscopicRenderingApp : public AppBasic {\npublic:\n\ttypedef enum { SET_FOCAL_LENGTH, SET_FOCUS, AUTO_FOCUS_SIMPLE, AUTO_FOCUS_DEPTH } AutoFocusMethod;\npublic:\n\tvoid prepareSettings( Settings *settings );\n\n\tvoid setup();\t\n\tvoid update();\n\tvoid draw();\n\n\tvoid mouseDown( MouseEvent event );\n\tvoid mouseDrag( MouseEvent event );\n\n\tvoid keyDown( KeyEvent event );\n\n\tvoid resize( ResizeEvent event );\nprivate:\n\tbool\t\t\tmIsStereo;\n\n\tAutoFocusMethod\tmFocusMethod;\n\n\tMayaCamUI\t\tmMayaCam;\n\tCameraStereo\tmCamera;\n\n\tgl::CameraStereoAutoFocuser\tmAF;\n\n\tgl::GlslProg\tmShader;\n\n\tgl::VboMesh\t\tmMesh;\n\tgl::VboMesh\t\tmNote;\n\n\tvoid render();\n};\n\nvoid StereoscopicRenderingApp::prepareSettings( Settings *settings )\n{\n\t\/\/ create a 16:9 window\n\tsettings->setWindowSize(960, 540);\n\tsettings->setTitle(\"Stereoscopic Rendering\");\n\n\t\/\/ allow high frame rates to test performance\n\tsettings->setFrameRate( 300.0f );\n}\n\nvoid StereoscopicRenderingApp::setup()\n{\n\t\/\/ enable stereoscopic rendering (press S to toggle)\n\tmIsStereo = true;\n\n\t\/\/ enable auto-focussing\n\tmFocusMethod = AUTO_FOCUS_DEPTH;\n\n\t\/\/ setup the camera\n\tmCamera.setEyePoint( Vec3f(0.2f, 1.3f, -11.5f) );\n\tmCamera.setCenterOfInterestPoint( Vec3f(0.5f, 1.5f, -0.1f) );\n\tmCamera.setFov( 60.0f );\n\n\tmMayaCam.setCurrentCam( mCamera );\n\n\ttry {\n\t\t\/\/ load shader(s)\n\t\tmShader = gl::GlslProg( loadAsset(\"shaders\/phong_vert.glsl\"), loadAsset(\"shaders\/phong_frag.glsl\") );\n\n\t\t\/\/ load model(s)\n\t\tTriMesh\t\tmesh;\n\n\t\tmesh.read( loadAsset(\"models\/trombone.msh\") );\n\t\tmMesh = gl::VboMesh( mesh );\n\t\t\n\t\tmesh.read( loadAsset(\"models\/note.msh\") );\n\t\tmNote = gl::VboMesh( mesh ); \n\t}\n\tcatch( const std::exception &e ) {\n\t\t\/\/ something went wrong, display error and quit\n\t\tconsole() << e.what() << std::endl;\n\t\tquit();\n\t}\n}\n\nvoid StereoscopicRenderingApp::update()\n{\n\tfloat d, f;\n\n\tswitch( mFocusMethod )\n\t{\n\tcase SET_FOCAL_LENGTH:\n\t\t\/\/ auto-focus by calculating distance to center of interest\n\t\td = (mCamera.getCenterOfInterestPoint() - mCamera.getEyePoint()).length();\n\t\tf = math<float>::min( 5.0f, d * 0.5f );\n\n\t\t\/\/ The setFocalLength() method will not change the eye separation distance, \n\t\t\/\/ which may cause the parallax effect to become uncomfortably big. \n\t\tmCamera.setFocalLength( f );\n\t\tmCamera.setEyeSeparation( 0.05f );\n\t\tbreak;\n\tcase SET_FOCUS:\n\t\t\/\/ auto-focus by calculating distance to center of interest\n\t\td = (mCamera.getCenterOfInterestPoint() - mCamera.getEyePoint()).length();\n\t\tf = math<float>::min( 5.0f, d * 0.5f );\n\n\t\t\/\/ The setFocus() method will automatically calculate a fitting value eye separation distance.\n\t\t\/\/ There is still no guarantee that the parallax effect stays within comfortable levels,\n\t\t\/\/ because there may be objects very near to the camera compared to the point we are looking at.\n\t\tmCamera.setFocus( f );\n\t\tbreak;\n\tcase AUTO_FOCUS_SIMPLE:\n\t\t\/\/ Here, we use the gl::CameraStereoAutoFocuser class to determine the best focal length,\n\t\t\/\/ based on the distance to the center of interest. This is very similar to the SET_FOCUS\n\t\t\/\/ method. Use the UP and DOWN keys to adjust the intensity of the parallax effect.\n\t\tmAF.autoFocus( mCamera, false );\n\t\tbreak;\n\tcase AUTO_FOCUS_DEPTH:\n\t\t\/\/ Here, we use the gl::CameraStereoAutoFocuser class to determine the best focal length,\n\t\t\/\/ based on the contents of the current depth buffer. This is by far the best method of\n\t\t\/\/ the four, because it guarantees the parallax effect will never be out of bounds.\n\t\t\/\/ Use the UP and DOWN keys to adjust the intensity of the parallax effect.\n\t\tmAF.autoFocus( mCamera, true );\n\t\tbreak;\n\t}\n}\n\nvoid StereoscopicRenderingApp::draw()\n{\n\t\/\/ gray background\n\tgl::clear( Color(0.8f, 0.8f, 0.8f) ); \n\n\t\/\/ enable 3D rendering\n\tgl::enableDepthRead();\n\tgl::enableDepthWrite();\n\tgl::pushMatrices();\n\n\t\/\/ stereoscopic rendering\n\tif( mIsStereo ) {\n\t\t\/\/ find dimensions of each viewport (side by side)\n\t\tint w = getWindowWidth();\n\t\tint h = getWindowHeight();\n\n\t\t\/\/ store current viewport\n\t\tglPushAttrib( GL_VIEWPORT_BIT );\n\n\t\t\/\/ draw to left half of window only\n\t\tgl::setViewport( Area(0, 0, w \/ 2, h) );\n\n\t\t\/\/ activate left camera\n\t\tmCamera.enableStereoLeft();\n\t\tgl::setMatrices( mCamera );\n\n\t\t\/\/ render scene\n\t\trender();\n\n\t\t\/\/ draw to right half of window only\n\t\tgl::setViewport( Area(w \/ 2, 0, w, h) );\n\n\t\t\/\/ activate right camera\n\t\tmCamera.enableStereoRight();\n\t\tgl::setMatrices( mCamera );\n\n\t\t\/\/ render scene\n\t\trender();\n\n\t\t\/\/ restore viewport\n\t\tglPopAttrib();\n\t} \n\telse {\n\t\t\/\/ activate mono camera\n\t\tmCamera.disableStereo();\n\t\tgl::setMatrices( mCamera );\n\n\t\t\/\/ render scene\n\t\trender();\n\t}\n\n\t\/\/ restore 2D\n\tgl::popMatrices();\n\tgl::disableDepthWrite();\n\tgl::disableDepthRead();\n}\n\nvoid StereoscopicRenderingApp::mouseDown( MouseEvent event )\n{\n\t\/\/ handle camera\n\tmMayaCam.mouseDown( event.getPos() );\n}\n\nvoid StereoscopicRenderingApp::mouseDrag( MouseEvent event )\n{\n\t\/\/ handle camera\n\tmMayaCam.mouseDrag( event.getPos(), event.isLeftDown(), event.isMiddleDown(), event.isRightDown() );\n\t\n\t\/\/ update stereoscopic camera\n\tmCamera.setEyePoint( mMayaCam.getCamera().getEyePoint() );\n\tmCamera.setCenterOfInterestPoint( mMayaCam.getCamera().getCenterOfInterestPoint() );\n}\n\nvoid StereoscopicRenderingApp::keyDown( KeyEvent event )\n{\n\tswitch( event.getCode() )\n\t{\n\tcase KeyEvent::KEY_ESCAPE:\n\t\tquit();\n\t\tbreak;\n\tcase KeyEvent::KEY_f:\n\t\t\/\/ toggle full screen\n\t\tsetFullScreen( ! isFullScreen() );\n\t\tbreak;\n\tcase KeyEvent::KEY_s:\n\t\t\/\/ toggle stereoscopic rendering\n\t\tmIsStereo = !mIsStereo;\n\t\tbreak;\n\tcase KeyEvent::KEY_v:\n\t\t\/\/ toggle vertical sync\n\t\tgl::enableVerticalSync( !gl::isVerticalSyncEnabled() );\n\t\tbreak;\n\tcase KeyEvent::KEY_1:\n\t\tmFocusMethod = SET_FOCAL_LENGTH;\n\t\tbreak;\n\tcase KeyEvent::KEY_2:\n\t\tmFocusMethod = SET_FOCUS;\n\t\tbreak;\n\tcase KeyEvent::KEY_3:\n\t\tmFocusMethod = AUTO_FOCUS_SIMPLE;\n\t\tbreak;\n\tcase KeyEvent::KEY_4:\n\t\tmFocusMethod = AUTO_FOCUS_DEPTH;\n\t\tbreak;\n\tcase KeyEvent::KEY_UP:\n\t\t\/\/ increase the parallax effect (towards negative parallax) \n\t\tif(mFocusMethod >= AUTO_FOCUS_SIMPLE)\n\t\t\tmAF.setAutoFocusDepth( mAF.getAutoFocusDepth() + 0.05f );\n\t\tbreak;\n\tcase KeyEvent::KEY_DOWN:\n\t\t\/\/ decrease the parallax effect (towards positive parallax) \n\t\tif(mFocusMethod >= AUTO_FOCUS_SIMPLE)\n\t\t\tmAF.setAutoFocusDepth( mAF.getAutoFocusDepth() - 0.05f );\n\t\tbreak;\n\tcase KeyEvent::KEY_SPACE:\n\t\t\/\/ reset the parallax effect to 'no parallax for the nearest object'\n\t\tmAF.setAutoFocusDepth( 1.0f );\n\t\tbreak;\n\t}\n}\n\nvoid StereoscopicRenderingApp::resize( ResizeEvent event )\n{\n\t\/\/ make sure the camera's aspect ratio remains correct\n\tmCamera.setAspectRatio( event.getAspectRatio() );\t\n\tmMayaCam.setCurrentCam( mCamera );\n}\n\nvoid StereoscopicRenderingApp::render()\n{\t\n\tfloat seconds = (float) getElapsedSeconds();\n\n\tif( mShader && mMesh && mNote ) {\n\t\t\/\/ enable phong shading\n\t\tmShader.bind();\t\n\t\t\n\t\t\/\/ draw trombone\n\t\tgl::pushModelView();\n\t\t{\n\t\t\tgl::color( Color(0.7f, 0.6f, 0.0f) );\n\t\t\tgl::rotate( Vec3f::yAxis() * 10.0f * seconds );\n\t\t\tgl::draw( mMesh );\n\n\t\t\t\/\/ reflection\n\t\t\tgl::scale( 1.0f, -1.0f, 1.0f );\n\t\t\tgl::draw( mMesh );\n\t\t}\n\t\tgl::popModelView();\t\n\n\t\t\/\/ draw animated notes\n\t\tRand rnd;\n\t\tfor(int i=-100; i<=100; ++i) {\n\t\t\trnd.seed(i);\n\n\t\t\tfloat t = rnd.nextFloat() * 200.0f + 2.0f * seconds;\n\t\t\tfloat r = rnd.nextFloat() * 360.0f + 60.0f * seconds;\n\t\t\tfloat z = fmodf( 5.0f * t, 200.0f ) - 100.0f;\t\t\n\n\t\t\tgl::pushModelView();\n\t\t\t{\n\t\t\t\tgl::color( Color( CM_HSV, rnd.nextFloat(), 1.0f, 1.0f ) );\n\n\t\t\t\tgl::pushModelView();\n\t\t\t\tgl::translate( i * 0.5f, 0.15f + 1.0f * math<float>::abs( sinf(3.0f * t) ), -z );\n\t\t\t\tgl::rotate( Vec3f::yAxis() * r );\n\t\t\t\tgl::draw( mNote );\n\t\t\t\tgl::popModelView();\n\t\t\t\t\n\t\t\t\t\/\/ reflection\n\t\t\t\tgl::pushModelView();\n\t\t\t\tgl::scale( 1.0f, -1.0f, 1.0f );\n\t\t\t\tgl::translate( i * 0.5f, 0.15f + 1.0f * math<float>::abs( sinf(3.0f * t) ), -z );\n\t\t\t\tgl::rotate( Vec3f::yAxis() * r );\n\t\t\t\tgl::draw( mNote );\n\t\t\t\tgl::popModelView();\n\t\t\t}\n\t\t\tgl::popModelView();\n\t\t}\n\n\t\tmShader.unbind();\n\t}\n\n\t\/\/ draw grid\n\tgl::color( Color(0.8f, 0.8f, 0.8f) );\n\tfor(int i=-100; i<=100; ++i) {\n\t\tgl::drawLine( Vec3f((float) i, 0, -100), Vec3f((float) i, 0, 100) );\n\t\tgl::drawLine( Vec3f(-100, 0, (float) i), Vec3f(100, 0, (float) i) );\n\t}\n\n\t\/\/ draw floor\n\tgl::enableAlphaBlending();\n\tgl::color( ColorA(1,1,1,0.75f) );\n\tgl::drawCube( Vec3f(0.0f, -0.5f, 0.0f), Vec3f(200.0f, 1.0f, 200.0f) );\n\tgl::disableAlphaBlending();\n}\n\nCINDER_APP_BASIC( StereoscopicRenderingApp, RendererGl )<commit_msg>Tweaks to the StereoscopicRendering sample.<commit_after>\/*\n Copyright (c) 2012, Paul Houx\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/*\n\tThis sample will show how to use the CameraStereo class to setup and render stereoscopic images.\n\tThe camera contains different matrices for the left and right eye of the viewer. By rendering the scene\n\ttwice, once for each eye, we can view the scene in 3D on monitors or televisions that support 3D.\n\n\tHere, we divide the window into a left and right half and render the scene to each half. This is called\n\tside-by-side stereoscopic and is supported by most 3D televisions. Simply connect your computer to\n\tsuch a television, run the sample in full screen and enable the TV's 3D mode.\n\n\tWhen creating your own stereoscopic application, be careful how you choose your focal length.\n\tAn excellent article can be found here:\n\thttp:\/\/paulbourke.net\/miscellaneous\/stereographics\/stereorender\/\n\n\tThe CameraStereo class is based on the Off-Axis method described in this article. \n*\/\n\n#include \"cinder\/app\/AppBasic.h\"\n\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/CameraStereoAutoFocuser.h\"\n#include \"cinder\/gl\/GlslProg.h\"\n#include \"cinder\/gl\/Vbo.h\"\n\n#include \"cinder\/Camera.h\"\n#include \"cinder\/Font.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/MayaCamUI.h\"\n#include \"cinder\/Rand.h\"\n#include \"cinder\/TriMesh.h\"\n#include \"cinder\/ObjLoader.h\"\n\n#include <boost\/format.hpp>\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nclass StereoscopicRenderingApp : public AppBasic {\npublic:\n\ttypedef enum { SET_FOCAL_LENGTH, SET_FOCUS, AUTO_FOCUS_SIMPLE, AUTO_FOCUS_DEPTH } AutoFocusMethod;\npublic:\n\tvoid prepareSettings( Settings *settings );\n\n\tvoid setup();\t\n\tvoid update();\n\tvoid draw();\n\n\tvoid mouseDown( MouseEvent event );\n\tvoid mouseDrag( MouseEvent event );\n\n\tvoid keyDown( KeyEvent event );\n\n\tvoid resize( ResizeEvent event );\nprivate:\n\tbool\t\t\tmIsStereo;\n\n\tAutoFocusMethod\tmFocusMethod;\n\n\tMayaCamUI\t\tmMayaCam;\n\tCameraStereo\tmCamera;\n\n\tgl::CameraStereoAutoFocuser\tmAF;\n\n\tgl::GlslProg\tmShader;\n\n\tgl::VboMesh\t\tmMesh;\n\tgl::VboMesh\t\tmNote;\n\n\tFont\t\t\tmFont;\n\n\tvoid render();\n\tvoid renderUI();\n};\n\nvoid StereoscopicRenderingApp::prepareSettings( Settings *settings )\n{\n\t\/\/ create a 16:9 window\n\tsettings->setWindowSize(960, 540);\n\tsettings->setTitle(\"Stereoscopic Rendering\");\n\n\t\/\/ allow high frame rates to test performance\n\tsettings->setFrameRate( 300.0f );\n}\n\nvoid StereoscopicRenderingApp::setup()\n{\n\t\/\/ enable stereoscopic rendering (press S to toggle)\n\tmIsStereo = true;\n\n\t\/\/ enable auto-focussing\n\tmFocusMethod = AUTO_FOCUS_DEPTH;\n\n\t\/\/ setup the camera\n\tmCamera.setEyePoint( Vec3f(0.2f, 1.3f, -11.5f) );\n\tmCamera.setCenterOfInterestPoint( Vec3f(0.5f, 1.5f, -0.1f) );\n\tmCamera.setFov( 60.0f );\n\n\tmMayaCam.setCurrentCam( mCamera );\n\n\ttry {\n\t\t\/\/ load shader(s)\n\t\tmShader = gl::GlslProg( loadAsset(\"shaders\/phong_vert.glsl\"), loadAsset(\"shaders\/phong_frag.glsl\") );\n\n\t\t\/\/ load model(s)\n\t\tTriMesh\t\tmesh;\n\n\t\tmesh.read( loadAsset(\"models\/trombone.msh\") );\n\t\tmMesh = gl::VboMesh( mesh );\n\t\t\n\t\tmesh.read( loadAsset(\"models\/note.msh\") );\n\t\tmNote = gl::VboMesh( mesh ); \n\t}\n\tcatch( const std::exception &e ) {\n\t\t\/\/ something went wrong, display error and quit\n\t\tconsole() << e.what() << std::endl;\n\t\tquit();\n\t}\n\n\tmFont = Font(\"Verdana\", 36.0f);\n}\n\nvoid StereoscopicRenderingApp::update()\n{\n\tfloat d, f;\n\n\tswitch( mFocusMethod )\n\t{\n\tcase SET_FOCAL_LENGTH:\n\t\t\/\/ auto-focus by calculating distance to center of interest\n\t\td = (mCamera.getCenterOfInterestPoint() - mCamera.getEyePoint()).length();\n\t\tf = math<float>::min( 5.0f, d * 0.5f );\n\n\t\t\/\/ The setFocalLength() method will not change the eye separation distance, \n\t\t\/\/ which may cause the parallax effect to become uncomfortably big. \n\t\tmCamera.setFocalLength( f );\n\t\tmCamera.setEyeSeparation( 0.05f );\n\t\tbreak;\n\tcase SET_FOCUS:\n\t\t\/\/ auto-focus by calculating distance to center of interest\n\t\td = (mCamera.getCenterOfInterestPoint() - mCamera.getEyePoint()).length();\n\t\tf = math<float>::min( 5.0f, d * 0.5f );\n\n\t\t\/\/ The setFocus() method will automatically calculate a fitting value eye separation distance.\n\t\t\/\/ There is still no guarantee that the parallax effect stays within comfortable levels,\n\t\t\/\/ because there may be objects very near to the camera compared to the point we are looking at.\n\t\tmCamera.setFocus( f );\n\t\tbreak;\n\tcase AUTO_FOCUS_SIMPLE:\n\t\t\/\/ Here, we use the gl::CameraStereoAutoFocuser class to determine the best focal length,\n\t\t\/\/ based on the distance to the center of interest. This is very similar to the SET_FOCUS\n\t\t\/\/ method. Use the UP and DOWN keys to adjust the intensity of the parallax effect.\n\t\tmAF.autoFocus( mCamera, false );\n\t\tbreak;\n\tcase AUTO_FOCUS_DEPTH:\n\t\t\/\/ Here, we use the gl::CameraStereoAutoFocuser class to determine the best focal length,\n\t\t\/\/ based on the contents of the current depth buffer. This is by far the best method of\n\t\t\/\/ the four, because it guarantees the parallax effect will never be out of bounds.\n\t\t\/\/ Use the UP and DOWN keys to adjust the intensity of the parallax effect.\n\t\tmAF.autoFocus( mCamera, true );\n\t\tbreak;\n\t}\n}\n\nvoid StereoscopicRenderingApp::draw()\n{\n\t\/\/ find dimensions of each viewport \n\tint w = getWindowWidth();\n\tint h = getWindowHeight();\n\n\t\/\/ gray background\n\tgl::clear( Color(0.8f, 0.8f, 0.8f) ); \n\n\t\/\/ enable 3D rendering\n\tgl::enableDepthRead();\n\tgl::enableDepthWrite();\n\tgl::pushMatrices();\n\n\t\/\/ stereoscopic rendering\n\tif( mIsStereo ) {\n\t\t\/\/ store current viewport\n\t\tglPushAttrib( GL_VIEWPORT_BIT );\n\n\t\t\/\/ draw to left half of window only\n\t\tgl::setViewport( Area(0, 0, w \/ 2, h) );\n\n\t\t\/\/ activate left camera\n\t\tmCamera.enableStereoLeft();\n\t\tgl::setMatrices( mCamera );\n\n\t\t\/\/ render scene\n\t\trender();\n\n\t\t\/\/ draw to right half of window only\n\t\tgl::setViewport( Area(w \/ 2, 0, w, h) );\n\n\t\t\/\/ activate right camera\n\t\tmCamera.enableStereoRight();\n\t\tgl::setMatrices( mCamera );\n\n\t\t\/\/ render scene\n\t\trender();\n\n\t\t\/\/ restore viewport\n\t\tglPopAttrib();\n\t} \n\telse {\n\t\t\/\/ activate mono camera\n\t\tmCamera.disableStereo();\n\t\tgl::setMatrices( mCamera );\n\n\t\t\/\/ render scene\n\t\trender();\n\t}\n\n\t\/\/ restore 2D\n\tgl::popMatrices();\n\tgl::disableDepthWrite();\n\tgl::disableDepthRead();\n\n\t\/\/ render 2D user interface\n\tif( mIsStereo )\n\t{\n\t\t\/\/ store current viewport\n\t\tglPushAttrib( GL_VIEWPORT_BIT );\n\n\t\t\/\/ draw to left half of window only\n\t\tgl::setViewport( Area(0, 0, w \/ 2, h) );\n\t\trenderUI();\n\n\t\t\/\/ draw to right half of window only\n\t\tgl::setViewport( Area(w \/ 2, 0, w, h) );\n\t\trenderUI();\n\n\t\t\/\/ restore viewport\n\t\tglPopAttrib();\n\t}\n\telse\n\t\trenderUI();\n}\n\nvoid StereoscopicRenderingApp::mouseDown( MouseEvent event )\n{\n\t\/\/ handle camera\n\tmMayaCam.mouseDown( event.getPos() );\n}\n\nvoid StereoscopicRenderingApp::mouseDrag( MouseEvent event )\n{\n\t\/\/ handle camera\n\tmMayaCam.mouseDrag( event.getPos(), event.isLeftDown(), event.isMiddleDown(), event.isRightDown() );\n\t\n\t\/\/ update stereoscopic camera\n\tmCamera.setEyePoint( mMayaCam.getCamera().getEyePoint() );\n\tmCamera.setCenterOfInterestPoint( mMayaCam.getCamera().getCenterOfInterestPoint() );\n}\n\nvoid StereoscopicRenderingApp::keyDown( KeyEvent event )\n{\n\tswitch( event.getCode() )\n\t{\n\tcase KeyEvent::KEY_ESCAPE:\n\t\tquit();\n\t\tbreak;\n\tcase KeyEvent::KEY_f:\n\t\t\/\/ toggle full screen\n\t\tsetFullScreen( ! isFullScreen() );\n\t\tbreak;\n\tcase KeyEvent::KEY_s:\n\t\t\/\/ toggle stereoscopic rendering\n\t\tmIsStereo = !mIsStereo;\n\t\tbreak;\n\tcase KeyEvent::KEY_v:\n\t\t\/\/ toggle vertical sync\n\t\tgl::enableVerticalSync( !gl::isVerticalSyncEnabled() );\n\t\tbreak;\n\tcase KeyEvent::KEY_1:\n\t\tmFocusMethod = SET_FOCAL_LENGTH;\n\t\tbreak;\n\tcase KeyEvent::KEY_2:\n\t\tmFocusMethod = SET_FOCUS;\n\t\tbreak;\n\tcase KeyEvent::KEY_3:\n\t\tmFocusMethod = AUTO_FOCUS_SIMPLE;\n\t\tbreak;\n\tcase KeyEvent::KEY_4:\n\t\tmFocusMethod = AUTO_FOCUS_DEPTH;\n\t\tbreak;\n\tcase KeyEvent::KEY_UP:\n\t\t\/\/ increase the parallax effect (towards negative parallax) \n\t\tif(mFocusMethod >= AUTO_FOCUS_SIMPLE)\n\t\t\tmAF.setAutoFocusDepth( mAF.getAutoFocusDepth() + 0.05f );\n\t\tbreak;\n\tcase KeyEvent::KEY_DOWN:\n\t\t\/\/ decrease the parallax effect (towards positive parallax) \n\t\tif(mFocusMethod >= AUTO_FOCUS_SIMPLE)\n\t\t\tmAF.setAutoFocusDepth( mAF.getAutoFocusDepth() - 0.05f );\n\t\tbreak;\n\tcase KeyEvent::KEY_SPACE:\n\t\t\/\/ reset the parallax effect to 'no parallax for the nearest object'\n\t\tmAF.setAutoFocusDepth( 1.0f );\n\t\tbreak;\n\tcase KeyEvent::KEY_LEFT:\n\t\t\/\/ reduce the auto focus speed\n\t\tmAF.setAutoFocusSpeed( mAF.getAutoFocusSpeed() - 0.01f );\n\t\tbreak;\n\tcase KeyEvent::KEY_RIGHT:\n\t\t\/\/ increase the auto focus speed\n\t\tmAF.setAutoFocusSpeed( mAF.getAutoFocusSpeed() + 0.01f );\n\t\tbreak;\n\t}\n}\n\nvoid StereoscopicRenderingApp::resize( ResizeEvent event )\n{\n\t\/\/ make sure the camera's aspect ratio remains correct\n\tmCamera.setAspectRatio( event.getAspectRatio() );\t\n\tmMayaCam.setCurrentCam( mCamera );\n}\n\nvoid StereoscopicRenderingApp::render()\n{\t\n\tfloat seconds = (float) getElapsedSeconds();\n\n\tif( mShader && mMesh && mNote ) {\n\t\t\/\/ enable phong shading\n\t\tmShader.bind();\t\n\t\t\n\t\t\/\/ draw trombone\n\t\tgl::pushModelView();\n\t\t{\n\t\t\tgl::color( Color(0.7f, 0.6f, 0.0f) );\n\t\t\tgl::rotate( Vec3f::yAxis() * 10.0f * seconds );\n\t\t\tgl::draw( mMesh );\n\n\t\t\t\/\/ reflection\n\t\t\tgl::scale( 1.0f, -1.0f, 1.0f );\n\t\t\tgl::draw( mMesh );\n\t\t}\n\t\tgl::popModelView();\t\n\n\t\t\/\/ draw animated notes\n\t\tRand rnd;\n\t\tfor(int i=-100; i<=100; ++i) {\n\t\t\trnd.seed(i);\n\n\t\t\tfloat t = rnd.nextFloat() * 200.0f + 2.0f * seconds;\n\t\t\tfloat r = rnd.nextFloat() * 360.0f + 60.0f * seconds;\n\t\t\tfloat z = fmodf( 5.0f * t, 200.0f ) - 100.0f;\t\t\n\n\t\t\tgl::pushModelView();\n\t\t\t{\n\t\t\t\tgl::color( Color( CM_HSV, rnd.nextFloat(), 1.0f, 1.0f ) );\n\n\t\t\t\tgl::pushModelView();\n\t\t\t\tgl::translate( i * 0.5f, 0.15f + 1.0f * math<float>::abs( sinf(3.0f * t) ), -z );\n\t\t\t\tgl::rotate( Vec3f::yAxis() * r );\n\t\t\t\tgl::draw( mNote );\n\t\t\t\tgl::popModelView();\n\t\t\t\t\n\t\t\t\t\/\/ reflection\n\t\t\t\tgl::pushModelView();\n\t\t\t\tgl::scale( 1.0f, -1.0f, 1.0f );\n\t\t\t\tgl::translate( i * 0.5f, 0.15f + 1.0f * math<float>::abs( sinf(3.0f * t) ), -z );\n\t\t\t\tgl::rotate( Vec3f::yAxis() * r );\n\t\t\t\tgl::draw( mNote );\n\t\t\t\tgl::popModelView();\n\t\t\t}\n\t\t\tgl::popModelView();\n\t\t}\n\n\t\tmShader.unbind();\n\t}\n\n\t\/\/ draw grid\n\tgl::color( Color(0.8f, 0.8f, 0.8f) );\n\tfor(int i=-100; i<=100; ++i) {\n\t\tgl::drawLine( Vec3f((float) i, 0, -100), Vec3f((float) i, 0, 100) );\n\t\tgl::drawLine( Vec3f(-100, 0, (float) i), Vec3f(100, 0, (float) i) );\n\t}\n\n\t\/\/ draw floor\n\tgl::enableAlphaBlending();\n\tgl::color( ColorA(1,1,1,0.75f) );\n\tgl::drawCube( Vec3f(0.0f, -0.5f, 0.0f), Vec3f(200.0f, 1.0f, 200.0f) );\n\tgl::disableAlphaBlending();\n}\n\nvoid StereoscopicRenderingApp::renderUI()\n{\t\n\tfloat w = (float) getWindowWidth() * 0.5f;\n\tfloat h = (float) getWindowHeight();\n\n\tboost::format fmt = boost::format( \"%.3f\\n%.3f\\n%.3f\\n%.3f\" ) % mCamera.getFocalLength() % mCamera.getEyeSeparation() % mAF.getAutoFocusDepth() % mAF.getAutoFocusSpeed();\n\n\tgl::enableAlphaBlending();\n\tgl::drawString( \"Focal Length:\\nEye Distance:\\nAuto Focus Depth:\\nAuto Focus Speed:\", Vec2f( w - 200.0f, h - 150.0f ), Color::black(), mFont );\n\tgl::drawStringRight( fmt.str(), Vec2f( w + 200.0f, h - 150.0f ), Color::black(), mFont );\n\tgl::disableAlphaBlending();\n}\n\nCINDER_APP_BASIC( StereoscopicRenderingApp, RendererGl )<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: CurrentMasterPagesSelector.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 14:43:25 $\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 SD_TOOLPANEL_CONTROLS_CURRENT_MASTER_PAGES_SELECTOR_HXX\n#define SD_TOOLPANEL_CONTROLS_CURRENT_MASTER_PAGES_SELECTOR_HXX\n\n#include \"MasterPagesSelector.hxx\"\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\nnamespace sd { namespace toolpanel { namespace controls {\n\n\nclass CurrentMasterPagesSelector\n : public MasterPagesSelector\n{\npublic:\n CurrentMasterPagesSelector (\n TreeNode* pParent,\n SdDrawDocument& rDocument,\n ViewShellBase& rBase,\n DrawViewShell& rViewShell);\n virtual ~CurrentMasterPagesSelector (void);\n\n virtual void LateInit (void);\n\n \/** Set the selection so that the master page is selected that is\n used by the currently selected page of the document in the\n center pane.\n *\/\n virtual void UpdateSelection (void);\n\n \/** Clear the list of currently used master pages and fill it\n with anew.\n *\/\n virtual void Fill (void);\n\nprivate:\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>\n mxListener;\n};\n\n} } } \/\/ end of namespace ::sd::toolpanel::controls\n\n#endif\n<commit_msg>INTEGRATION: CWS impress33 (1.2.220); FILE MERGED 2005\/02\/03 14:11:55 af 1.2.220.2: #i41507# Adaption to modifications in base class MasterPagesSelector. 2005\/02\/01 15:40:23 af 1.2.220.1: #i41507# Replaced references of master pages in MasterPageContainer by pointers into application document.<commit_after>\/*************************************************************************\n *\n * $RCSfile: CurrentMasterPagesSelector.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2005-02-16 16:59: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 SD_TOOLPANEL_CONTROLS_CURRENT_MASTER_PAGES_SELECTOR_HXX\n#define SD_TOOLPANEL_CONTROLS_CURRENT_MASTER_PAGES_SELECTOR_HXX\n\n#include \"MasterPagesSelector.hxx\"\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\nnamespace sd { namespace toolpanel { namespace controls {\n\n\n\/** Adaption of a value set control that shows previews of master pages that\n are currently used by the document of the application.\n\n It does not use the approach of the base class of storing tokens as item\n data in the value set that identify entries in the MasterPageContainer.\n Instead it stores pointers directly to master pages in the document.\n The base class is used to have access to the code that assigns master\n pages to the document.\n*\/\nclass CurrentMasterPagesSelector\n : public MasterPagesSelector\n{\npublic:\n CurrentMasterPagesSelector (\n TreeNode* pParent,\n SdDrawDocument& rDocument,\n ViewShellBase& rBase,\n DrawViewShell& rViewShell);\n virtual ~CurrentMasterPagesSelector (void);\n\n virtual void LateInit (void);\n\n \/** Set the selection so that the master page is selected that is\n used by the currently selected page of the document in the\n center pane.\n *\/\n virtual void UpdateSelection (void);\n\n \/** Clear the list of currently used master pages and fill it\n with anew.\n *\/\n virtual void Fill (void);\n virtual void Clear (void);\n\n virtual void InvalidatePreview (const SdPage* pPage);\n\nprotected:\n \/** Return the master page whose preview is currently selected in the\n value set control.\n @return\n The returned page belongs to the main document, not to the local\n document of the MasterPageContainer.\n *\/\n virtual SdPage* GetSelectedMasterPage (void);\n\n \/** For all currently used master pages a new preview is rendered and\n put into the value set control.\n *\/\n virtual void UpdateAllPreviews (void);\n virtual void UpdatePreview (USHORT nIndex);\n\nprivate:\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>\n mxListener;\n};\n\n} } } \/\/ end of namespace ::sd::toolpanel::controls\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Projectname: amos-ss16-proj5\n\/\/\n\/\/ Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5\n\/\/\n\/\/ This file is part of the AMOS Project 2016 @ FAU\n\/\/ (Friedrich-Alexander University Erlangen-Nürnberg)\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (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. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public\n\/\/ License along with this program. If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"detection.h\"\n#include \"element.h\"\n\n\nusing namespace std;\nusing namespace cv;\n\nDetection::Detection(Detector * people_detector, Detector * vehicle_detector) {\n\n people_detector_ = people_detector;\n vehicle_detector_ = vehicle_detector;\n image_view_ = new ImageView();\n}\n\nDetection::~Detection(){\n delete image_view_;\n image_view_ = NULL;\n}\n\nFrameDetectionData* Detection::ProcessFrame(Image * image) {\n\n Mat frame = image->GetRGBImage();\n Mat resized_frame = ResizeFrame(&frame);\n\n std::vector<Rect> detected_people = people_detector_->Detect(&resized_frame);\n std::vector<Rect> detected_vehicles = vehicle_detector_->Detect(&resized_frame);\n\n \/\/ write the detected people and vehicle data into frame detection data and return it\n \/\/ resize the position and the box of detected elements to real size again\n FrameDetectionData* detected_objects = new FrameDetectionData();\n std::vector<Element> people_elements;\n std::vector<Element> vehicle_elements;\n\n for(int i=0; i<detected_people.size(); i++) {\n\n Rect current_rec = detected_people.at(i);\n\n std::vector<int> position;\n std::vector<int> box;\n\n int pos_x_resized = current_rec.x\/0.3125;\n int pos_y_resized = current_rec.y\/0.3125;\n\n if(pos_x_resized < 0){\n pos_x_resized = 0;\n }\n if(pos_x_resized > image->GetImageWidth()){\n pos_x_resized = image->GetImageWidth();\n }\n\n if(pos_y_resized < 0){\n pos_y_resized = 0;\n }\n if(pos_y_resized > image->GetImageHeight()){\n pos_y_resized = image->GetImageHeight();\n }\n\n position.push_back(pos_x_resized);\n position.push_back(pos_y_resized);\n\n int box_width_resized = current_rec.width\/0.3125;\n int box_height_resized = current_rec.height\/0.3125;\n\n if((position.at(0) + box_width_resized) > image->GetImageWidth()){\n box_width_resized = image->GetImageWidth()-position.at(0);\n }\n if((position.at(1) + box_height_resized) > image->GetImageHeight()){\n box_height_resized = image->GetImageHeight()-position.at(1);\n }\n\n box.push_back(box_width_resized);\n box.push_back(box_height_resized);\n\n \/\/std::cout << \"Process Frame: position of elem: \" << position.at(0) << \" \" << position.at(1) << std::endl;\n \/\/std::cout << \"Process Frame: width and height: \" << box.at(0) << \" \" << box.at(1) << std::endl;\n\n Element current_elem(position, box);\n\n people_elements.push_back(current_elem);\n }\n\n detected_objects->AddElementsOfType(OBJECT_HUMAN, people_elements);\n\n for(int i=0; i<detected_vehicles.size(); i++) {\n\n Rect current_rec = detected_vehicles.at(i);\n\n std::vector<int> position;\n std::vector<int> box;\n\n position.push_back(current_rec.x\/0.3125);\n position.push_back(current_rec.y\/0.3125);\n\n box.push_back(current_rec.width\/0.3125);\n box.push_back(current_rec.height\/0.3125);\n\n Element current_elem(position, box);\n\n vehicle_elements.push_back(current_elem);\n }\n\n detected_objects->AddElementsOfType(OBJECT_VEHICLE, vehicle_elements);\n\n \/\/ display image and detections\n\n image_view_->ShowImageAndDetections(image, people_elements, vehicle_elements);\n\n return detected_objects;\n}\n\nMat Detection::ResizeFrame(Mat *frame) {\n \/\/resize the image to width of 400px to reduce detection time and improve detection accuracy\n \/\/0.3125 is used because the test video is 1280 x 720, so the width resized images is 400px this has to be changed to our image size (best would be no hard coded scaling so other images sizes work too!)\n \/\/ TODO: dynamic risizeing depending on input (min width 400px)\n\n Mat resized_frame;\n resize(*frame, resized_frame, Size(0, 0), 0.3125, 0.3125, CV_INTER_AREA);\n return resized_frame;\n}\n<commit_msg>implemnted method for function adjustContrastAndBrightness in class Detection<commit_after>\/\/\n\/\/ Projectname: amos-ss16-proj5\n\/\/\n\/\/ Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5\n\/\/\n\/\/ This file is part of the AMOS Project 2016 @ FAU\n\/\/ (Friedrich-Alexander University Erlangen-Nürnberg)\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (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. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public\n\/\/ License along with this program. If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"detection.h\"\n#include \"element.h\"\n\n\nusing namespace std;\nusing namespace cv;\n\nDetection::Detection(Detector * people_detector, Detector * vehicle_detector) {\n\n people_detector_ = people_detector;\n vehicle_detector_ = vehicle_detector;\n image_view_ = new ImageView();\n}\n\nDetection::~Detection(){\n delete image_view_;\n image_view_ = NULL;\n}\n\nFrameDetectionData* Detection::ProcessFrame(Image * image) {\n\n Mat frame = image->GetRGBImage();\n Mat resized_frame = ResizeFrame(&frame);\n\n std::vector<Rect> detected_people = people_detector_->Detect(&resized_frame);\n std::vector<Rect> detected_vehicles = vehicle_detector_->Detect(&resized_frame);\n\n \/\/ write the detected people and vehicle data into frame detection data and return it\n \/\/ resize the position and the box of detected elements to real size again\n FrameDetectionData* detected_objects = new FrameDetectionData();\n std::vector<Element> people_elements;\n std::vector<Element> vehicle_elements;\n\n for(int i=0; i<detected_people.size(); i++) {\n\n Rect current_rec = detected_people.at(i);\n\n std::vector<int> position;\n std::vector<int> box;\n\n int pos_x_resized = current_rec.x\/0.3125;\n int pos_y_resized = current_rec.y\/0.3125;\n\n if(pos_x_resized < 0){\n pos_x_resized = 0;\n }\n if(pos_x_resized > image->GetImageWidth()){\n pos_x_resized = image->GetImageWidth();\n }\n\n if(pos_y_resized < 0){\n pos_y_resized = 0;\n }\n if(pos_y_resized > image->GetImageHeight()){\n pos_y_resized = image->GetImageHeight();\n }\n\n position.push_back(pos_x_resized);\n position.push_back(pos_y_resized);\n\n int box_width_resized = current_rec.width\/0.3125;\n int box_height_resized = current_rec.height\/0.3125;\n\n if((position.at(0) + box_width_resized) > image->GetImageWidth()){\n box_width_resized = image->GetImageWidth()-position.at(0);\n }\n if((position.at(1) + box_height_resized) > image->GetImageHeight()){\n box_height_resized = image->GetImageHeight()-position.at(1);\n }\n\n box.push_back(box_width_resized);\n box.push_back(box_height_resized);\n\n \/\/std::cout << \"Process Frame: position of elem: \" << position.at(0) << \" \" << position.at(1) << std::endl;\n \/\/std::cout << \"Process Frame: width and height: \" << box.at(0) << \" \" << box.at(1) << std::endl;\n\n Element current_elem(position, box);\n\n people_elements.push_back(current_elem);\n }\n\n detected_objects->AddElementsOfType(OBJECT_HUMAN, people_elements);\n\n for(int i=0; i<detected_vehicles.size(); i++) {\n\n Rect current_rec = detected_vehicles.at(i);\n\n std::vector<int> position;\n std::vector<int> box;\n\n position.push_back(current_rec.x\/0.3125);\n position.push_back(current_rec.y\/0.3125);\n\n box.push_back(current_rec.width\/0.3125);\n box.push_back(current_rec.height\/0.3125);\n\n Element current_elem(position, box);\n\n vehicle_elements.push_back(current_elem);\n }\n\n detected_objects->AddElementsOfType(OBJECT_VEHICLE, vehicle_elements);\n\n \/\/ display image and detections\n\n image_view_->ShowImageAndDetections(image, people_elements, vehicle_elements);\n\n return detected_objects;\n}\n\nMat Detection::ResizeFrame(Mat *frame) {\n \/\/resize the image to width of 400px to reduce detection time and improve detection accuracy\n \/\/0.3125 is used because the test video is 1280 x 720, so the width resized images is 400px this has to be changed to our image size (best would be no hard coded scaling so other images sizes work too!)\n \/\/ TODO: dynamic risizeing depending on input (min width 400px)\n\n Mat resized_frame;\n resize(*frame, resized_frame, Size(0, 0), 0.3125, 0.3125, CV_INTER_AREA);\n return resized_frame;\n}\n\ncv::Mat adjustContrastAndBrightness(cv::Mat *frame, double contrastValue, int brightnessValue){\n Mat adjusted_image = Mat::zeros( frame->size(), frame->type() );\n for( int x = 0; x < frame->rows; x++ ){\n for( int y = 0; y < frame->cols; y++ ){\n \/\/ c: use all colours of RGB \/ BGR\n for( int c = 0; c < 3; c++ ){\n adjusted_image.at<Vec3b>(x,y)[c] = saturate_cast<uchar>(contrastValue* (frame->at<Vec3b>(x,y)[c])+ brightnessValue );\n }\n }\n }\n return adjusted_image;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <eosio\/chain\/fork_database.hpp>\n\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/member.hpp>\n#include <boost\/multi_index\/ordered_index.hpp>\n#include <boost\/multi_index\/hashed_index.hpp>\n#include <boost\/multi_index\/mem_fun.hpp>\n#include <boost\/multi_index\/composite_key.hpp>\n#include <fc\/io\/fstream.hpp>\n#include <fstream>\n\nnamespace eosio { namespace chain {\n using boost::multi_index_container;\n using namespace boost::multi_index;\n\n\n struct by_block_id;\n struct by_block_num;\n struct by_lib_block_num;\n struct by_prev;\n typedef multi_index_container<\n block_state_ptr,\n indexed_by<\n hashed_unique< tag<by_block_id>, member<block_header_state, block_id_type, &block_header_state::id>, std::hash<block_id_type>>,\n ordered_non_unique< tag<by_prev>, const_mem_fun<block_header_state, const block_id_type&, &block_header_state::prev> >,\n ordered_non_unique< tag<by_block_num>,\n composite_key< block_state,\n member<block_header_state,uint32_t,&block_header_state::block_num>,\n member<block_state,bool,&block_state::in_current_chain>\n >,\n composite_key_compare< std::less<uint32_t>, std::greater<bool> >\n >,\n ordered_non_unique< tag<by_lib_block_num>,\n composite_key< block_header_state,\n member<block_header_state,uint32_t,&block_header_state::dpos_irreversible_blocknum>,\n member<block_header_state,uint32_t,&block_header_state::bft_irreversible_blocknum>,\n member<block_header_state,uint32_t,&block_header_state::block_num>\n >,\n composite_key_compare< std::greater<uint32_t>, std::greater<uint32_t>, std::greater<uint32_t> >\n >\n >\n > fork_multi_index_type;\n\n\n struct fork_database_impl {\n fork_multi_index_type index;\n block_state_ptr head;\n fc::path datadir;\n };\n\n\n fork_database::fork_database( const fc::path& data_dir ):my( new fork_database_impl() ) {\n my->datadir = data_dir;\n\n if (!fc::is_directory(my->datadir))\n fc::create_directories(my->datadir);\n\n auto fork_db_dat = my->datadir \/ config::forkdb_filename;\n if( fc::exists( fork_db_dat ) ) {\n string content;\n fc::read_file_contents( fork_db_dat, content );\n\n fc::datastream<const char*> ds( content.data(), content.size() );\n unsigned_int size; fc::raw::unpack( ds, size );\n for( uint32_t i = 0, n = size.value; i < n; ++i ) {\n block_state s;\n fc::raw::unpack( ds, s );\n set( std::make_shared<block_state>( move( s ) ) );\n }\n block_id_type head_id;\n fc::raw::unpack( ds, head_id );\n\n my->head = get_block( head_id );\n\n fc::remove( fork_db_dat );\n }\n }\n\n void fork_database::close() {\n if( my->index.size() == 0 ) return;\n\n auto fork_db_dat = my->datadir \/ config::forkdb_filename;\n std::ofstream out( fork_db_dat.generic_string().c_str(), std::ios::out | std::ios::binary | std::ofstream::trunc );\n uint32_t num_blocks_in_fork_db = my->index.size();\n fc::raw::pack( out, unsigned_int{num_blocks_in_fork_db} );\n for( const auto& s : my->index ) {\n fc::raw::pack( out, *s );\n }\n if( my->head )\n fc::raw::pack( out, my->head->id );\n else\n fc::raw::pack( out, block_id_type() );\n\n \/\/\/ we don't normally indicate the head block as irreversible\n \/\/\/ we cannot normally prune the lib if it is the head block because\n \/\/\/ the next block needs to build off of the head block. We are exiting\n \/\/\/ now so we can prune this block as irreversible before exiting.\n auto lib = my->head->dpos_irreversible_blocknum;\n auto oldest = *my->index.get<by_block_num>().begin();\n if( oldest->block_num <= lib ) {\n prune( oldest );\n }\n\n my->index.clear();\n }\n\n fork_database::~fork_database() {\n close();\n }\n\n void fork_database::set( block_state_ptr s ) {\n auto result = my->index.insert( s );\n FC_ASSERT( s->id == s->header.id() );\n\n \/\/FC_ASSERT( s->block_num == s->header.block_num() );\n\n FC_ASSERT( result.second, \"unable to insert block state, duplicate state detected\" );\n if( !my->head ) {\n my->head = s;\n } else if( my->head->block_num < s->block_num ) {\n my->head = s;\n }\n }\n\n block_state_ptr fork_database::add( block_state_ptr n ) {\n auto inserted = my->index.insert(n);\n FC_ASSERT( inserted.second, \"duplicate block added?\" );\n\n my->head = *my->index.get<by_lib_block_num>().begin();\n\n auto lib = my->head->dpos_irreversible_blocknum;\n auto oldest = *my->index.get<by_block_num>().begin();\n\n if( oldest->block_num < lib ) {\n prune( oldest );\n }\n\n return n;\n }\n\n block_state_ptr fork_database::add( signed_block_ptr b, bool trust ) {\n FC_ASSERT( b, \"attempt to add null block\" );\n FC_ASSERT( my->head, \"no head block set\" );\n\n const auto& by_id_idx = my->index.get<by_block_id>();\n auto existing = by_id_idx.find( b->id() );\n FC_ASSERT( existing == by_id_idx.end(), \"we already know about this block\" );\n\n auto prior = by_id_idx.find( b->previous );\n FC_ASSERT( prior != by_id_idx.end(), \"unlinkable block\", (\"id\", b->id())(\"previous\", b->previous) );\n\n auto result = std::make_shared<block_state>( **prior, move(b), trust );\n FC_ASSERT( result );\n return add(result);\n }\n\n const block_state_ptr& fork_database::head()const { return my->head; }\n\n \/**\n * Given two head blocks, return two branches of the fork graph that\n * end with a common ancestor (same prior block)\n *\/\n pair< branch_type, branch_type > fork_database::fetch_branch_from( const block_id_type& first,\n const block_id_type& second )const {\n pair<branch_type,branch_type> result;\n auto first_branch = get_block(first);\n auto second_branch = get_block(second);\n\n while( first_branch->block_num > second_branch->block_num )\n {\n result.first.push_back(first_branch);\n first_branch = get_block( first_branch->header.previous );\n FC_ASSERT( first_branch );\n }\n\n while( second_branch->block_num > first_branch->block_num )\n {\n result.second.push_back( second_branch );\n second_branch = get_block( second_branch->header.previous );\n FC_ASSERT( second_branch );\n }\n\n while( first_branch->header.previous != second_branch->header.previous )\n {\n result.first.push_back(first_branch);\n result.second.push_back(second_branch);\n first_branch = get_block( first_branch->header.previous );\n second_branch = get_block( second_branch->header.previous );\n FC_ASSERT( first_branch && second_branch );\n }\n\n if( first_branch && second_branch )\n {\n result.first.push_back(first_branch);\n result.second.push_back(second_branch);\n }\n return result;\n } \/\/\/ fetch_branch_from\n\n \/\/\/ remove all of the invalid forks built of this id including this id\n void fork_database::remove( const block_id_type& id ) {\n vector<block_id_type> remove_queue{id};\n\n for( uint32_t i = 0; i < remove_queue.size(); ++i ) {\n auto itr = my->index.find( remove_queue[i] );\n if( itr != my->index.end() )\n my->index.erase(itr);\n\n auto& previdx = my->index.get<by_prev>();\n auto previtr = previdx.lower_bound(remove_queue[i]);\n while( previtr != previdx.end() && (*previtr)->header.previous == remove_queue[i] ) {\n remove_queue.push_back( (*previtr)->id );\n ++previtr;\n }\n }\n \/\/wdump((my->index.size()));\n my->head = *my->index.get<by_lib_block_num>().begin();\n }\n\n void fork_database::set_validity( const block_state_ptr& h, bool valid ) {\n if( !valid ) {\n remove( h->id );\n } else {\n \/\/\/ remove older than irreversible and mark block as valid\n h->validated = true;\n }\n }\n\n void fork_database::mark_in_current_chain( const block_state_ptr& h, bool in_current_chain ) {\n if( h->in_current_chain == in_current_chain )\n return;\n\n auto& by_id_idx = my->index.get<by_block_id>();\n auto itr = by_id_idx.find( h->id );\n FC_ASSERT( itr != by_id_idx.end(), \"could not find block in fork database\" );\n\n by_id_idx.modify( itr, [&]( auto& bsp ) { \/\/ Need to modify this way rather than directly so that Boost MultiIndex can re-sort\n bsp->in_current_chain = in_current_chain;\n });\n }\n\n void fork_database::prune( const block_state_ptr& h ) {\n auto num = h->block_num;\n\n auto& by_bn = my->index.get<by_block_num>();\n auto bni = by_bn.begin();\n while( bni != by_bn.end() && (*bni)->block_num < num ) {\n prune( *bni );\n bni = by_bn.begin();\n }\n\n auto itr = my->index.find( h->id );\n if( itr != my->index.end() ) {\n irreversible(*itr); \/\/XXX\n my->index.erase(itr);\n }\n\n auto& numidx = my->index.get<by_block_num>();\n auto nitr = numidx.lower_bound( num );\n while( nitr != numidx.end() && (*nitr)->block_num == num ) {\n auto itr_to_remove = nitr;\n ++nitr;\n auto id = (*itr_to_remove)->id;\n remove( id );\n }\n }\n\n block_state_ptr fork_database::get_block(const block_id_type& id)const {\n auto itr = my->index.find( id );\n if( itr != my->index.end() )\n return *itr;\n return block_state_ptr();\n }\n\n block_state_ptr fork_database::get_block_in_current_chain_by_num( uint32_t n )const {\n const auto& numidx = my->index.get<by_block_num>();\n auto nitr = numidx.lower_bound( n );\n \/\/ following asserts removed so null can be returned\n \/\/FC_ASSERT( nitr != numidx.end() && (*nitr)->block_num == n,\n \/\/ \"could not find block in fork database with block number ${block_num}\", (\"block_num\", n) );\n \/\/FC_ASSERT( (*nitr)->in_current_chain == true,\n \/\/ \"block (with block number ${block_num}) found in fork database is not in the current chain\", (\"block_num\", n) );\n if( nitr == numidx.end() || (*nitr)->block_num != n || (*nitr)->in_current_chain != true )\n return block_state_ptr();\n return *nitr;\n }\n\n void fork_database::add( const header_confirmation& c ) {\n auto b = get_block( c.block_id );\n FC_ASSERT( b, \"unable to find block id ${id}\", (\"id\",c.block_id));\n b->add_confirmation( c );\n\n if( b->bft_irreversible_blocknum < b->block_num &&\n b->confirmations.size() > ((b->active_schedule.producers.size() * 2) \/ 3) ) {\n set_bft_irreversible( c.block_id );\n }\n }\n\n \/**\n * This method will set this block as being BFT irreversible and will update\n * all blocks which build off of it to have the same bft_irb if their existing\n * bft irb is less than this block num.\n *\n * This will require a search over all forks\n *\/\n void fork_database::set_bft_irreversible( block_id_type id ) {\n auto& idx = my->index.get<by_block_id>();\n auto itr = idx.find(id);\n uint32_t block_num = (*itr)->block_num;\n idx.modify( itr, [&]( auto& bsp ) {\n bsp->bft_irreversible_blocknum = bsp->block_num;\n });\n\n \/** to prevent stack-overflow, we perform a bredth-first traversal of the\n * fork database. At each stage we iterate over the leafs from the prior stage\n * and find all nodes that link their previous. If we update the bft lib then we\n * add it to a queue for the next layer. This lambda takes one layer and returns\n * all block ids that need to be iterated over for next layer.\n *\/\n auto update = [&]( const vector<block_id_type>& in ) {\n vector<block_id_type> updated;\n\n for( const auto& i : in ) {\n auto& pidx = my->index.get<by_prev>();\n auto pitr = pidx.lower_bound( i );\n auto epitr = pidx.upper_bound( i );\n while( pitr != epitr ) {\n pidx.modify( pitr, [&]( auto& bsp ) {\n if( bsp->bft_irreversible_blocknum < block_num ) {\n bsp->bft_irreversible_blocknum = block_num;\n updated.push_back( bsp->id );\n }\n });\n ++pitr;\n }\n }\n return updated;\n };\n\n vector<block_id_type> queue{id};\n while( queue.size() ) {\n queue = update( queue );\n }\n }\n\n} } \/\/\/ eosio::chain\n<commit_msg>temporary change reverted #4196<commit_after>#include <eosio\/chain\/fork_database.hpp>\n\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/member.hpp>\n#include <boost\/multi_index\/ordered_index.hpp>\n#include <boost\/multi_index\/hashed_index.hpp>\n#include <boost\/multi_index\/mem_fun.hpp>\n#include <boost\/multi_index\/composite_key.hpp>\n#include <fc\/io\/fstream.hpp>\n#include <fstream>\n\nnamespace eosio { namespace chain {\n using boost::multi_index_container;\n using namespace boost::multi_index;\n\n\n struct by_block_id;\n struct by_block_num;\n struct by_lib_block_num;\n struct by_prev;\n typedef multi_index_container<\n block_state_ptr,\n indexed_by<\n hashed_unique< tag<by_block_id>, member<block_header_state, block_id_type, &block_header_state::id>, std::hash<block_id_type>>,\n ordered_non_unique< tag<by_prev>, const_mem_fun<block_header_state, const block_id_type&, &block_header_state::prev> >,\n ordered_non_unique< tag<by_block_num>,\n composite_key< block_state,\n member<block_header_state,uint32_t,&block_header_state::block_num>,\n member<block_state,bool,&block_state::in_current_chain>\n >,\n composite_key_compare< std::less<uint32_t>, std::greater<bool> >\n >,\n ordered_non_unique< tag<by_lib_block_num>,\n composite_key< block_header_state,\n member<block_header_state,uint32_t,&block_header_state::dpos_irreversible_blocknum>,\n member<block_header_state,uint32_t,&block_header_state::bft_irreversible_blocknum>,\n member<block_header_state,uint32_t,&block_header_state::block_num>\n >,\n composite_key_compare< std::greater<uint32_t>, std::greater<uint32_t>, std::greater<uint32_t> >\n >\n >\n > fork_multi_index_type;\n\n\n struct fork_database_impl {\n fork_multi_index_type index;\n block_state_ptr head;\n fc::path datadir;\n };\n\n\n fork_database::fork_database( const fc::path& data_dir ):my( new fork_database_impl() ) {\n my->datadir = data_dir;\n\n if (!fc::is_directory(my->datadir))\n fc::create_directories(my->datadir);\n\n auto fork_db_dat = my->datadir \/ config::forkdb_filename;\n if( fc::exists( fork_db_dat ) ) {\n string content;\n fc::read_file_contents( fork_db_dat, content );\n\n fc::datastream<const char*> ds( content.data(), content.size() );\n unsigned_int size; fc::raw::unpack( ds, size );\n for( uint32_t i = 0, n = size.value; i < n; ++i ) {\n block_state s;\n fc::raw::unpack( ds, s );\n set( std::make_shared<block_state>( move( s ) ) );\n }\n block_id_type head_id;\n fc::raw::unpack( ds, head_id );\n\n my->head = get_block( head_id );\n\n fc::remove( fork_db_dat );\n }\n }\n\n void fork_database::close() {\n if( my->index.size() == 0 ) return;\n\n auto fork_db_dat = my->datadir \/ config::forkdb_filename;\n std::ofstream out( fork_db_dat.generic_string().c_str(), std::ios::out | std::ios::binary | std::ofstream::trunc );\n uint32_t num_blocks_in_fork_db = my->index.size();\n fc::raw::pack( out, unsigned_int{num_blocks_in_fork_db} );\n for( const auto& s : my->index ) {\n fc::raw::pack( out, *s );\n }\n if( my->head )\n fc::raw::pack( out, my->head->id );\n else\n fc::raw::pack( out, block_id_type() );\n\n \/\/\/ we don't normally indicate the head block as irreversible\n \/\/\/ we cannot normally prune the lib if it is the head block because\n \/\/\/ the next block needs to build off of the head block. We are exiting\n \/\/\/ now so we can prune this block as irreversible before exiting.\n auto lib = my->head->dpos_irreversible_blocknum;\n auto oldest = *my->index.get<by_block_num>().begin();\n if( oldest->block_num <= lib ) {\n prune( oldest );\n }\n\n my->index.clear();\n }\n\n fork_database::~fork_database() {\n close();\n }\n\n void fork_database::set( block_state_ptr s ) {\n auto result = my->index.insert( s );\n FC_ASSERT( s->id == s->header.id() );\n\n \/\/FC_ASSERT( s->block_num == s->header.block_num() );\n\n FC_ASSERT( result.second, \"unable to insert block state, duplicate state detected\" );\n if( !my->head ) {\n my->head = s;\n } else if( my->head->block_num < s->block_num ) {\n my->head = s;\n }\n }\n\n block_state_ptr fork_database::add( block_state_ptr n ) {\n auto inserted = my->index.insert(n);\n FC_ASSERT( inserted.second, \"duplicate block added?\" );\n\n my->head = *my->index.get<by_lib_block_num>().begin();\n\n auto lib = my->head->dpos_irreversible_blocknum;\n auto oldest = *my->index.get<by_block_num>().begin();\n\n if( oldest->block_num < lib ) {\n prune( oldest );\n }\n\n return n;\n }\n\n block_state_ptr fork_database::add( signed_block_ptr b, bool trust ) {\n FC_ASSERT( b, \"attempt to add null block\" );\n FC_ASSERT( my->head, \"no head block set\" );\n\n const auto& by_id_idx = my->index.get<by_block_id>();\n auto existing = by_id_idx.find( b->id() );\n FC_ASSERT( existing == by_id_idx.end(), \"we already know about this block\" );\n\n auto prior = by_id_idx.find( b->previous );\n FC_ASSERT( prior != by_id_idx.end(), \"unlinkable block\", (\"id\", b->id())(\"previous\", b->previous) );\n\n auto result = std::make_shared<block_state>( **prior, move(b), trust );\n FC_ASSERT( result );\n return add(result);\n }\n\n const block_state_ptr& fork_database::head()const { return my->head; }\n\n \/**\n * Given two head blocks, return two branches of the fork graph that\n * end with a common ancestor (same prior block)\n *\/\n pair< branch_type, branch_type > fork_database::fetch_branch_from( const block_id_type& first,\n const block_id_type& second )const {\n pair<branch_type,branch_type> result;\n auto first_branch = get_block(first);\n auto second_branch = get_block(second);\n\n while( first_branch->block_num > second_branch->block_num )\n {\n result.first.push_back(first_branch);\n first_branch = get_block( first_branch->header.previous );\n FC_ASSERT( first_branch );\n }\n\n while( second_branch->block_num > first_branch->block_num )\n {\n result.second.push_back( second_branch );\n second_branch = get_block( second_branch->header.previous );\n FC_ASSERT( second_branch );\n }\n\n while( first_branch->header.previous != second_branch->header.previous )\n {\n result.first.push_back(first_branch);\n result.second.push_back(second_branch);\n first_branch = get_block( first_branch->header.previous );\n second_branch = get_block( second_branch->header.previous );\n FC_ASSERT( first_branch && second_branch );\n }\n\n if( first_branch && second_branch )\n {\n result.first.push_back(first_branch);\n result.second.push_back(second_branch);\n }\n return result;\n } \/\/\/ fetch_branch_from\n\n \/\/\/ remove all of the invalid forks built of this id including this id\n void fork_database::remove( const block_id_type& id ) {\n vector<block_id_type> remove_queue{id};\n\n for( uint32_t i = 0; i < remove_queue.size(); ++i ) {\n auto itr = my->index.find( remove_queue[i] );\n if( itr != my->index.end() )\n my->index.erase(itr);\n\n auto& previdx = my->index.get<by_prev>();\n auto previtr = previdx.lower_bound(remove_queue[i]);\n while( previtr != previdx.end() && (*previtr)->header.previous == remove_queue[i] ) {\n remove_queue.push_back( (*previtr)->id );\n ++previtr;\n }\n }\n \/\/wdump((my->index.size()));\n my->head = *my->index.get<by_lib_block_num>().begin();\n }\n\n void fork_database::set_validity( const block_state_ptr& h, bool valid ) {\n if( !valid ) {\n remove( h->id );\n } else {\n \/\/\/ remove older than irreversible and mark block as valid\n h->validated = true;\n }\n }\n\n void fork_database::mark_in_current_chain( const block_state_ptr& h, bool in_current_chain ) {\n if( h->in_current_chain == in_current_chain )\n return;\n\n auto& by_id_idx = my->index.get<by_block_id>();\n auto itr = by_id_idx.find( h->id );\n FC_ASSERT( itr != by_id_idx.end(), \"could not find block in fork database\" );\n\n by_id_idx.modify( itr, [&]( auto& bsp ) { \/\/ Need to modify this way rather than directly so that Boost MultiIndex can re-sort\n bsp->in_current_chain = in_current_chain;\n });\n }\n\n void fork_database::prune( const block_state_ptr& h ) {\n auto num = h->block_num;\n\n auto& by_bn = my->index.get<by_block_num>();\n auto bni = by_bn.begin();\n while( bni != by_bn.end() && (*bni)->block_num < num ) {\n prune( *bni );\n bni = by_bn.begin();\n }\n\n auto itr = my->index.find( h->id );\n if( itr != my->index.end() ) {\n irreversible(*itr);\n my->index.erase(itr);\n }\n\n auto& numidx = my->index.get<by_block_num>();\n auto nitr = numidx.lower_bound( num );\n while( nitr != numidx.end() && (*nitr)->block_num == num ) {\n auto itr_to_remove = nitr;\n ++nitr;\n auto id = (*itr_to_remove)->id;\n remove( id );\n }\n }\n\n block_state_ptr fork_database::get_block(const block_id_type& id)const {\n auto itr = my->index.find( id );\n if( itr != my->index.end() )\n return *itr;\n return block_state_ptr();\n }\n\n block_state_ptr fork_database::get_block_in_current_chain_by_num( uint32_t n )const {\n const auto& numidx = my->index.get<by_block_num>();\n auto nitr = numidx.lower_bound( n );\n \/\/ following asserts removed so null can be returned\n \/\/FC_ASSERT( nitr != numidx.end() && (*nitr)->block_num == n,\n \/\/ \"could not find block in fork database with block number ${block_num}\", (\"block_num\", n) );\n \/\/FC_ASSERT( (*nitr)->in_current_chain == true,\n \/\/ \"block (with block number ${block_num}) found in fork database is not in the current chain\", (\"block_num\", n) );\n if( nitr == numidx.end() || (*nitr)->block_num != n || (*nitr)->in_current_chain != true )\n return block_state_ptr();\n return *nitr;\n }\n\n void fork_database::add( const header_confirmation& c ) {\n auto b = get_block( c.block_id );\n FC_ASSERT( b, \"unable to find block id ${id}\", (\"id\",c.block_id));\n b->add_confirmation( c );\n\n if( b->bft_irreversible_blocknum < b->block_num &&\n b->confirmations.size() > ((b->active_schedule.producers.size() * 2) \/ 3) ) {\n set_bft_irreversible( c.block_id );\n }\n }\n\n \/**\n * This method will set this block as being BFT irreversible and will update\n * all blocks which build off of it to have the same bft_irb if their existing\n * bft irb is less than this block num.\n *\n * This will require a search over all forks\n *\/\n void fork_database::set_bft_irreversible( block_id_type id ) {\n auto& idx = my->index.get<by_block_id>();\n auto itr = idx.find(id);\n uint32_t block_num = (*itr)->block_num;\n idx.modify( itr, [&]( auto& bsp ) {\n bsp->bft_irreversible_blocknum = bsp->block_num;\n });\n\n \/** to prevent stack-overflow, we perform a bredth-first traversal of the\n * fork database. At each stage we iterate over the leafs from the prior stage\n * and find all nodes that link their previous. If we update the bft lib then we\n * add it to a queue for the next layer. This lambda takes one layer and returns\n * all block ids that need to be iterated over for next layer.\n *\/\n auto update = [&]( const vector<block_id_type>& in ) {\n vector<block_id_type> updated;\n\n for( const auto& i : in ) {\n auto& pidx = my->index.get<by_prev>();\n auto pitr = pidx.lower_bound( i );\n auto epitr = pidx.upper_bound( i );\n while( pitr != epitr ) {\n pidx.modify( pitr, [&]( auto& bsp ) {\n if( bsp->bft_irreversible_blocknum < block_num ) {\n bsp->bft_irreversible_blocknum = block_num;\n updated.push_back( bsp->id );\n }\n });\n ++pitr;\n }\n }\n return updated;\n };\n\n vector<block_id_type> queue{id};\n while( queue.size() ) {\n queue = update( queue );\n }\n }\n\n} } \/\/\/ eosio::chain\n<|endoftext|>"} {"text":"<commit_before>#include \"Connection.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <iostream>\n\nConnection::Connection(Driver* pDriver)\n : m_pDriver(pDriver)\n{\n}\n\nvoid Connection::handleMessage(std::string message) {\n m_pDriver->HandleMessage(\"12\");\n}\ncrow::json::wvalue Connection::GetPatientStatus() {\n return m_pDriver->GetPatientStatus();\n}\nvoid Connection::BolusDrug(std::string drugName, double concentration, double dose){\n m_pDriver->BolusDrug(drugName, concentration, dose);\n}\n\nvoid Connection::operator()()\n{\n SetRunning(true);\n\n crow::SimpleApp app;\n\n CROW_ROUTE(app, \"\/\")([this](){\n return \"BioGear Server by Screen Based Simulation Team\";\n });\n\n CROW_ROUTE(app, \"\/patient\/status\")\n .methods(\"GET\"_method)\n ([this](){\n crow::json::wvalue x = GetPatientStatus();\n return x;\n });\n\n CROW_ROUTE(app,\"\/patient\/injection\")\n .methods(\"POST\"_method)\n ([this](const crow::request& req){\n auto x = crow::json::load(req.body);\n if (!x)\n return crow::response(400);\n std::string drugName = x[\"drug_name\"].s();\n double concentration = x[\"concentration\"].d();\n double dose = x[\"dose\"].d();\n \n BolusDrug(drugName, concentration, dose);\n return crow::response{\"successful\"};\n });\n\n app.port(18080).multithreaded().run();\n \n}\n<commit_msg>change port to 23333<commit_after>#include \"Connection.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <iostream>\n\nConnection::Connection(Driver* pDriver)\n : m_pDriver(pDriver)\n{\n}\n\nvoid Connection::handleMessage(std::string message) {\n m_pDriver->HandleMessage(\"12\");\n}\ncrow::json::wvalue Connection::GetPatientStatus() {\n return m_pDriver->GetPatientStatus();\n}\nvoid Connection::BolusDrug(std::string drugName, double concentration, double dose){\n m_pDriver->BolusDrug(drugName, concentration, dose);\n}\n\nvoid Connection::operator()()\n{\n SetRunning(true);\n\n crow::SimpleApp app;\n\n CROW_ROUTE(app, \"\/\")([this](){\n return \"BioGear Server by Screen Based Simulation Team\";\n });\n\n CROW_ROUTE(app, \"\/patient\/status\")\n .methods(\"GET\"_method)\n ([this](){\n crow::json::wvalue x = GetPatientStatus();\n return x;\n });\n\n CROW_ROUTE(app,\"\/patient\/injection\")\n .methods(\"POST\"_method)\n ([this](const crow::request& req){\n auto x = crow::json::load(req.body);\n if (!x)\n return crow::response(400);\n std::string drugName = x[\"drug_name\"].s();\n double concentration = x[\"concentration\"].d();\n double dose = x[\"dose\"].d();\n \n BolusDrug(drugName, concentration, dose);\n return crow::response{\"successful\"};\n });\n\n app.port(23333).multithreaded().run();\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 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#include \"SysTimer_windows.h\"\n\n#include <intrin.h>\n\nstatic ULONGLONG win_cpu_time() {\n FILETIME createTime;\n FILETIME exitTime;\n FILETIME usrTime;\n FILETIME sysTime;\n if (0 == GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &sysTime, &usrTime)) {\n return 0;\n }\n ULARGE_INTEGER start_cpu_sys;\n ULARGE_INTEGER start_cpu_usr;\n start_cpu_sys.LowPart = sysTime.dwLowDateTime;\n start_cpu_sys.HighPart = sysTime.dwHighDateTime;\n start_cpu_usr.LowPart = usrTime.dwLowDateTime;\n start_cpu_usr.HighPart = usrTime.dwHighDateTime;\n return start_cpu_sys.QuadPart + start_cpu_usr.QuadPart;\n}\n\nvoid SysTimer::startCpu() {\n fStartCpu = win_cpu_time();\n}\n\ndouble SysTimer::endCpu() {\n ULONGLONG end_cpu = win_cpu_time();\n return static_cast<double>(end_cpu - fStartCpu) \/ 10000.0L;\n}\n\nstatic void wall_timestamp(LARGE_INTEGER* now) {\n _ReadWriteBarrier();\n if (0 == ::QueryPerformanceCounter(now)) {\n now->QuadPart = 0;\n }\n _ReadWriteBarrier();\n}\n\nvoid SysTimer::startWall() {\n wall_timestamp(&fStartWall);\n}\n\ndouble SysTimer::endWall() {\n LARGE_INTEGER end_wall;\n wall_timestamp(&end_wall);\n\n LARGE_INTEGER ticks_elapsed;\n ticks_elapsed.QuadPart = end_wall.QuadPart - fStartWall.QuadPart;\n\n LARGE_INTEGER frequency;\n if (0 == ::QueryPerformanceFrequency(&frequency)) {\n return 0.0L;\n } else {\n return static_cast<double>(ticks_elapsed.QuadPart)\n \/ static_cast<double>(frequency.QuadPart)\n * 1000.0L;\n }\n}\n<commit_msg>revert timer changes<commit_after>\/*\n * Copyright 2011 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#include \"SysTimer_windows.h\"\n\nstatic ULONGLONG win_cpu_time() {\n FILETIME createTime;\n FILETIME exitTime;\n FILETIME usrTime;\n FILETIME sysTime;\n if (0 == GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &sysTime, &usrTime)) {\n return 0;\n }\n ULARGE_INTEGER start_cpu_sys;\n ULARGE_INTEGER start_cpu_usr;\n start_cpu_sys.LowPart = sysTime.dwLowDateTime;\n start_cpu_sys.HighPart = sysTime.dwHighDateTime;\n start_cpu_usr.LowPart = usrTime.dwLowDateTime;\n start_cpu_usr.HighPart = usrTime.dwHighDateTime;\n return start_cpu_sys.QuadPart + start_cpu_usr.QuadPart;\n}\n\nvoid SysTimer::startWall() {\n if (0 == ::QueryPerformanceCounter(&fStartWall)) {\n fStartWall.QuadPart = 0;\n }\n}\nvoid SysTimer::startCpu() {\n fStartCpu = win_cpu_time();\n}\n\ndouble SysTimer::endCpu() {\n ULONGLONG end_cpu = win_cpu_time();\n return static_cast<double>(end_cpu - fStartCpu) \/ 10000.0L;\n}\ndouble SysTimer::endWall() {\n LARGE_INTEGER end_wall;\n if (0 == ::QueryPerformanceCounter(&end_wall)) {\n end_wall.QuadPart = 0;\n }\n\n LARGE_INTEGER ticks_elapsed;\n ticks_elapsed.QuadPart = end_wall.QuadPart - fStartWall.QuadPart;\n\n LARGE_INTEGER frequency;\n if (0 == ::QueryPerformanceFrequency(&frequency)) {\n return 0.0L;\n } else {\n return static_cast<double>(ticks_elapsed.QuadPart)\n \/ static_cast<double>(frequency.QuadPart)\n * 1000.0L;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2014, Susanne Jaeckel\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"LBattery.h\"\n#include \"LSession.h\"\n\nLBattery::LBattery(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){\n iconOld = -1;\n \/\/Setup the widget\n label = new QLabel(this);\n label->setScaledContents(true);\n \/\/label->setAlignment(Qt::AlignCenter);\n this->layout()->addWidget(label);\n \/\/Setup the timer\n timer = new QTimer();\n timer->setInterval(5000); \/\/update every 5 seconds\n connect(timer,SIGNAL(timeout()), this, SLOT(updateBattery()) );\n timer->start();\n QTimer::singleShot(0,this,SLOT(OrientationChange()) ); \/\/update the sizing\/icon\n}\n\nLBattery::~LBattery(){\n timer->stop();\n delete timer;\n}\n\nvoid LBattery::updateBattery(bool force){\n \/\/ Get current state of charge\n \/\/QStringList result = LUtils::getCmdOutput(\"\/usr\/sbin\/apm\", QStringList() << \"-al\");\n int charge = LOS::batteryCharge(); \/\/result.at(1).toInt();\n\/\/qDebug() << \"1: \" << result.at(0).toInt() << \" 2: \" << result.at(1).toInt();\n int icon = -1;\n if (charge > 90) { icon = 4; }\n else if (charge > 70) { icon = 3; }\n else if (charge > 20) { icon = 2; }\n else if (charge > 5) { icon = 1; }\n else if (charge > 0 ) { icon = 0; }\n if(LOS::batteryIsCharging()){ icon = icon+10; }\n \/\/icon = icon + result.at(0).toInt() * 10;\n if (icon != iconOld || force) {\n switch (icon) {\n case 0:\n label->setPixmap( LXDG::findIcon(\"battery-caution\", \"\").pixmap(label->size()) );\n break;\n case 1:\n label->setPixmap( LXDG::findIcon(\"battery-040\", \"\").pixmap(label->size()) );\n break;\n case 2:\n label->setPixmap( LXDG::findIcon(\"battery-060\", \"\").pixmap(label->size()) );\n break;\n case 3:\n label->setPixmap( LXDG::findIcon(\"battery-080\", \"\").pixmap(label->size()) );\n break;\n case 4:\n label->setPixmap( LXDG::findIcon(\"battery-100\", \"\").pixmap(label->size()) );\n break;\n case 10:\n label->setPixmap( LXDG::findIcon(\"battery-charging-caution\", \"\").pixmap(label->size()) );\n break;\n case 11:\n label->setPixmap( LXDG::findIcon(\"battery-charging-040\", \"\").pixmap(label->size()) );\n break;\n case 12:\n label->setPixmap( LXDG::findIcon(\"battery-charging-060\", \"\").pixmap(label->size()) );\n break;\n case 13:\n label->setPixmap( LXDG::findIcon(\"battery-charging-080\", \"\").pixmap(label->size()) );\n break;\n case 14:\n label->setPixmap( LXDG::findIcon(\"battery-charging\", \"\").pixmap(label->size()) );\n break;\n default:\n label->setPixmap( LXDG::findIcon(\"battery-missing\", \"\").pixmap(label->size()) );\n break;\n }\n if(icon<iconOld && icon==0){\n \/\/Play some audio warning chime when \n LSession::handle()->playAudioFile(LOS::LuminaShare()+\"low-battery.ogg\");\n }\n if(icon==0){ label->setStyleSheet(\"background: red;\"); }\n else{ label->setStyleSheet(\"background: transparent;\"); }\n iconOld = icon;\n\n }\n \/\/Now update the display\n QString tt;\n \/\/Make sure the tooltip can be properly translated as necessary (Ken Moore 5\/9\/14)\n if(icon > 9 && icon < 15){ tt = QString(tr(\"%1 % (Charging)\")).arg(QString::number(charge)); }\n else{ tt = QString( tr(\"%1 % (%2 Remaining)\") ).arg(QString::number(charge), getRemainingTime() ); }\n label->setToolTip(tt);\n}\n\nQString LBattery::getRemainingTime(){\n int secs = LOS::batterySecondsLeft();\n if(secs < 0){ return \"??\"; }\n QString rem; \/\/remaining\n if(secs > 3600){\n int hours = secs\/3600;\n rem.append( QString::number(hours)+\"h \");\n secs = secs - (hours*3600);\n }\n if(secs > 60){\n int min = secs\/60;\n rem.append( QString::number(min)+\"m \");\n secs = secs - (min*60);\n }\n if(secs > 0){\n rem.append(QString::number(secs)+\"s\");\n }\n return rem;\n}\n<commit_msg>Fix up the stylesheet for the battery monitor. Don't change any properties other than the background color based on battery level.<commit_after>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2014, Susanne Jaeckel\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"LBattery.h\"\n#include \"LSession.h\"\n\nLBattery::LBattery(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){\n iconOld = -1;\n \/\/Setup the widget\n label = new QLabel(this);\n label->setScaledContents(true);\n \/\/label->setAlignment(Qt::AlignCenter);\n this->layout()->addWidget(label);\n \/\/Setup the timer\n timer = new QTimer();\n timer->setInterval(5000); \/\/update every 5 seconds\n connect(timer,SIGNAL(timeout()), this, SLOT(updateBattery()) );\n timer->start();\n QTimer::singleShot(0,this,SLOT(OrientationChange()) ); \/\/update the sizing\/icon\n}\n\nLBattery::~LBattery(){\n timer->stop();\n delete timer;\n}\n\nvoid LBattery::updateBattery(bool force){\n \/\/ Get current state of charge\n \/\/QStringList result = LUtils::getCmdOutput(\"\/usr\/sbin\/apm\", QStringList() << \"-al\");\n int charge = LOS::batteryCharge(); \/\/result.at(1).toInt();\n\/\/qDebug() << \"1: \" << result.at(0).toInt() << \" 2: \" << result.at(1).toInt();\n int icon = -1;\n if (charge > 90) { icon = 4; }\n else if (charge > 70) { icon = 3; }\n else if (charge > 20) { icon = 2; }\n else if (charge > 5) { icon = 1; }\n else if (charge > 0 ) { icon = 0; }\n if(LOS::batteryIsCharging()){ icon = icon+10; }\n \/\/icon = icon + result.at(0).toInt() * 10;\n if (icon != iconOld || force) {\n switch (icon) {\n case 0:\n label->setPixmap( LXDG::findIcon(\"battery-caution\", \"\").pixmap(label->size()) );\n break;\n case 1:\n label->setPixmap( LXDG::findIcon(\"battery-040\", \"\").pixmap(label->size()) );\n break;\n case 2:\n label->setPixmap( LXDG::findIcon(\"battery-060\", \"\").pixmap(label->size()) );\n break;\n case 3:\n label->setPixmap( LXDG::findIcon(\"battery-080\", \"\").pixmap(label->size()) );\n break;\n case 4:\n label->setPixmap( LXDG::findIcon(\"battery-100\", \"\").pixmap(label->size()) );\n break;\n case 10:\n label->setPixmap( LXDG::findIcon(\"battery-charging-caution\", \"\").pixmap(label->size()) );\n break;\n case 11:\n label->setPixmap( LXDG::findIcon(\"battery-charging-040\", \"\").pixmap(label->size()) );\n break;\n case 12:\n label->setPixmap( LXDG::findIcon(\"battery-charging-060\", \"\").pixmap(label->size()) );\n break;\n case 13:\n label->setPixmap( LXDG::findIcon(\"battery-charging-080\", \"\").pixmap(label->size()) );\n break;\n case 14:\n label->setPixmap( LXDG::findIcon(\"battery-charging\", \"\").pixmap(label->size()) );\n break;\n default:\n label->setPixmap( LXDG::findIcon(\"battery-missing\", \"\").pixmap(label->size()) );\n break;\n }\n if(icon<iconOld && icon==0){\n \/\/Play some audio warning chime when \n LSession::handle()->playAudioFile(LOS::LuminaShare()+\"low-battery.ogg\");\n }\n if(icon==0){ label->setStyleSheet(\"QLabel{ background: red;}\"); }\n else{ label->setStyleSheet(\"QLabel{ background: transparent;}\"); }\n iconOld = icon;\n\n }\n \/\/Now update the display\n QString tt;\n \/\/Make sure the tooltip can be properly translated as necessary (Ken Moore 5\/9\/14)\n if(icon > 9 && icon < 15){ tt = QString(tr(\"%1 % (Charging)\")).arg(QString::number(charge)); }\n else{ tt = QString( tr(\"%1 % (%2 Remaining)\") ).arg(QString::number(charge), getRemainingTime() ); }\n label->setToolTip(tt);\n}\n\nQString LBattery::getRemainingTime(){\n int secs = LOS::batterySecondsLeft();\n if(secs < 0){ return \"??\"; }\n QString rem; \/\/remaining\n if(secs > 3600){\n int hours = secs\/3600;\n rem.append( QString::number(hours)+\"h \");\n secs = secs - (hours*3600);\n }\n if(secs > 60){\n int min = secs\/60;\n rem.append( QString::number(min)+\"m \");\n secs = secs - (min*60);\n }\n if(secs > 0){\n rem.append(QString::number(secs)+\"s\");\n }\n return rem;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Records For Living, Inc. 2004-2011. All rights reserved\n *\/\n#include\t\"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include\t<iostream>\n#include\t<sstream>\n\n#include\t\"Stroika\/Foundation\/Containers\/VectorUtils.h\"\n#include\t\"Stroika\/Foundation\/DataExchangeFormat\/JSON\/Reader.h\"\n#include\t\"Stroika\/Foundation\/DataExchangeFormat\/JSON\/Writer.h\"\n#include\t\"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include\t\"Stroika\/Foundation\/Memory\/VariantValue.h\"\n\n#include\t\"..\/TestHarness\/TestHarness.h\"\n\n\nusing\tnamespace\tStroika::Foundation;\n\nusing\tMemory::VariantValue;\n\n\n\n\n\/*\n * Validating JSON parse results:\n *\t\thttp:\/\/json.parser.online.fr\/\n *\/\n\n\n\n\n\n\n\nnamespace\t{\n\tvoid\tCheckMatchesExpected_WRITER_ (const VariantValue& v, const string& expected)\n\t\t{\n\t\t\tstringstream\tout;\n\t\t\tDataExchangeFormat::JSON::PrettyPrint (v, out);\n\t\t\tstring x = out.str ();\n\t\t\tfor (string::size_type i = 0; i < min (x.length (), expected.length ()); ++i) {\n\t\t\t\tif (x[i] != expected[i]) {\n\t\t\t\t\tVerifyTestResult (false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tVerifyTestResult (out.str () == expected);\n\t\t}\n\n\tvoid\tDoRegressionTests_Writer_ ()\n\t\t{\n\t\t\t{\n\t\t\t\tVariantValue\tv1 = L\"hello world\";\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"\\\"hello world\\\"\");\n\t\t\t}\n\t\t\t{\n\t\t\t\tVariantValue\tv1 =\t3;\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"3\");\n\t\t\t}\n\t\t\t{\n\t\t\t\tVariantValue\tv1 =\t4.7f;\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"4.7\");\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ array\n\t\t\t\tvector<VariantValue>\tv;\n\t\t\t\tv.push_back (3);\n\t\t\t\tv.push_back (7);\n\t\t\t\tv.push_back (L\"cookie\");\n\t\t\t\tVariantValue\tv1 =\tv;\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"[\\n 3,\\n 7,\\n \\\"cookie\\\"\\n]\");\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ object\n\t\t\t\tmap<wstring,VariantValue>\tv;\n\t\t\t\tv[L\"Arg1\"] = 32;\n\t\t\t\tv[L\"Arg2\"] = L\"Cookies\";\n\t\t\t\tv[L\"Arg3\"] = Containers::mkV<VariantValue> (19);\n\t\t\t\tVariantValue\tv1 =\tv;\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"{\\n \\\"Arg1\\\" : 32,\\n \\\"Arg2\\\" : \\\"Cookies\\\",\\n \\\"Arg3\\\" : [\\n 19\\n ]\\n}\");\n\t\t\t}\n\t\t}\n}\n\n\n\n\nnamespace\t{\n\tvoid\tCheckMatchesExpected_READER_ (const string& v, const VariantValue& expected)\n\t\t{\n\t\t\tstringstream\ttmp;\n\t\t\ttmp << v;\n\t\t\tVariantValue\tv1\t=\tDataExchangeFormat::JSON::Reader (tmp);\n\t\t\tVerifyTestResult (v1.GetType () == expected.GetType ());\n\t\t\tVerifyTestResult (v1 == expected);\n\t\t}\n\n\tvoid\tDoRegressionTests_Reader_ ()\n\t\t{\n\t\t\t{\n\t\t\t\tVariantValue\tv1 = L\"hello world\";\n\t\t\t\tCheckMatchesExpected_READER_ (\"\\\"hello world\\\"\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\tVariantValue\tv1 =\t3;\n\t\t\t\tCheckMatchesExpected_READER_ (\"3\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\tVariantValue\tv1 =\t4.7f;\n\t\t\t\tCheckMatchesExpected_READER_ (\"4.7\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ array\n\t\t\t\tvector<VariantValue>\tv;\n\t\t\t\tv.push_back (3);\n\t\t\t\tv.push_back (7);\n\t\t\t\tv.push_back (L\"cookie\");\n\t\t\t\tVariantValue\tv1 =\tv;\n\t\t\t\tCheckMatchesExpected_READER_ (\"[\\n 3,\\n 7,\\n \\\"cookie\\\"\\n]\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ object\n\t\t\t\tmap<wstring,VariantValue>\tv;\n\t\t\t\tv[L\"Arg1\"] = 32;\n\t\t\t\tv[L\"Arg2\"] = L\"Cookies\";\n\t\t\t\tv[L\"Arg3\"] = Containers::mkV<VariantValue> (19);\n\t\t\t\tVariantValue\tv1 =\tv;\n\t\t\t\tCheckMatchesExpected_READER_ (\"{\\n \\\"Arg1\\\" : 32,\\n \\\"Arg2\\\" : \\\"Cookies\\\",\\n \\\"Arg3\\\" : [\\n 19\\n ]\\n}\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ Bug found in another JSON reader (sent me by Ryan - 2011-07-27)\n\t\t\t\tconst\tstring\tkExample\t=\t\"{\\\"nav_items\\\":[{\\\"main_link\\\":{\\\"href\\\":\\\"\/about\/index.html\\\",\\\"text\\\":\\\"Who We Are\\\"},\\\"column\\\":[{\\\"link_list\\\":[{},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/company-management.html\\\",\\\"text\\\":\\\"Management\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/mission-statement.html\\\",\\\"text\\\":\\\"Mission\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/company-history.html\\\",\\\"text\\\":\\\" History\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/headquarters.html\\\",\\\"text\\\":\\\"Corporate Headquarters\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/diversity.html\\\",\\\"text\\\":\\\"Diversity\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/supplier-diversity.html\\\",\\\"text\\\":\\\"Supplier Diversity\\\"}}]}]},{\\\"main_link\\\":{\\\"href\\\":\\\"http:\/\/investor.compuware.com\\\",\\\"text\\\":\\\"Investor Relations\\\"}},{\\\"main_link\\\":{\\\"href\\\":\\\"\/about\/newsroom.html\\\",\\\"text\\\":\\\"News Room\\\"},\\\"column\\\":[{\\\"link_list\\\":[{},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/analyst-reports\\\",\\\"text\\\":\\\"Analyst Reports\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/awards-recognition.html\\\",\\\"text\\\":\\\"Awards and Recognition\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/blogs.html\\\",\\\"text\\\":\\\"Blog Home\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/press-analyst-contacts.html\\\",\\\"text\\\":\\\"Contact Us\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/customers.html\\\",\\\"text\\\":\\\"Customers\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/press-mentions\\\",\\\"text\\\":\\\"Press Mentions\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/press-releases\\\",\\\"text\\\":\\\"Press Releases\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/press-resources.html\\\",\\\"text\\\":\\\"Press Resources\\\"}}]}]},{\\\"main_link\\\":{\\\"href\\\":\\\"#top\\\",\\\"text\\\":\\\"Sponsorships\\\"},\\\"column\\\":[{\\\"link_list\\\":[{\\\"header\\\":{\\\"href\\\":\\\"\/about\/lemans-sponsorship.html\\\",\\\"text\\\":\\\"Le Mans\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/nhl-sponsorship.html\\\",\\\"text\\\":\\\"NHL\\\"}},{}]}]},{\\\"main_link\\\":{\\\"href\\\":\\\"\/about\/community-involvement.html\\\",\\\"text\\\":\\\"Community Involvement\\\"},\\\"column\\\":[{\\\"link_list\\\":[{\\\"header\\\":{\\\"href\\\":\\\"http:\/\/communityclicks.compuware.com\\\",\\\"text\\\":\\\"Community Clicks Blog\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"javascript:securenav('\/forms\/grant-eligibility-form.html')\\\",\\\"text\\\":\\\"Grant Eligibility Form\\\"}},{}]}]},{\\\"main_link\\\":{\\\"href\\\":\\\"\/government\/\\\",\\\"text\\\":\\\"Government\\\"}}]}\";\n\t\t\t\tstringstream\ttmp;\n\t\t\t\ttmp << kExample;\n\t\t\t\tVariantValue\tv1\t=\tDataExchangeFormat::JSON::Reader (tmp);\n\t\t\t\tVerifyTestResult (v1.GetType () == VariantValue::eMap);\n\t\t\t}\n\n\t\t}\n}\n\n\nnamespace\t{\n\n\tvoid\tDoRegressionTests_ ()\n\t\t{\n\t\t\tDoRegressionTests_Writer_ ();\n\t\t\tDoRegressionTests_Reader_ ();\n\t\t}\n}\n\n\n\n\n#if qOnlyOneMain\nextern int TestJSON ()\n#else\nint main (int argc, const char* argv[])\n#endif\n{\n\tStroika::TestHarness::Setup ();\n\tStroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n\treturn EXIT_SUCCESS;\n}\n\n<commit_msg>tweeked VariantValue regression tests (comparing for equal - now must avoid comparing 4.7f with 4.7 (effectively) for Eqaulity)<commit_after>\/*\n * Copyright(c) Records For Living, Inc. 2004-2011. All rights reserved\n *\/\n#include\t\"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include\t<iostream>\n#include\t<sstream>\n\n#include\t\"Stroika\/Foundation\/Containers\/VectorUtils.h\"\n#include\t\"Stroika\/Foundation\/DataExchangeFormat\/JSON\/Reader.h\"\n#include\t\"Stroika\/Foundation\/DataExchangeFormat\/JSON\/Writer.h\"\n#include\t\"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include\t\"Stroika\/Foundation\/Memory\/VariantValue.h\"\n\n#include\t\"..\/TestHarness\/TestHarness.h\"\n\n\nusing\tnamespace\tStroika::Foundation;\n\nusing\tMemory::VariantValue;\n\n\n\n\n\/*\n * Validating JSON parse results:\n *\t\thttp:\/\/json.parser.online.fr\/\n *\/\n\n\n\n\n\n\n\nnamespace\t{\n\tvoid\tCheckMatchesExpected_WRITER_ (const VariantValue& v, const string& expected)\n\t\t{\n\t\t\tstringstream\tout;\n\t\t\tDataExchangeFormat::JSON::PrettyPrint (v, out);\n\t\t\tstring x = out.str ();\n\t\t\tfor (string::size_type i = 0; i < min (x.length (), expected.length ()); ++i) {\n\t\t\t\tif (x[i] != expected[i]) {\n\t\t\t\t\tVerifyTestResult (false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tVerifyTestResult (out.str () == expected);\n\t\t}\n\n\tvoid\tDoRegressionTests_Writer_ ()\n\t\t{\n\t\t\t{\n\t\t\t\tVariantValue\tv1 = L\"hello world\";\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"\\\"hello world\\\"\");\n\t\t\t}\n\t\t\t{\n\t\t\t\tVariantValue\tv1 =\t3;\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"3\");\n\t\t\t}\n\t\t\t{\n\t\t\t\tVariantValue\tv1 =\t4.7;\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"4.7\");\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ array\n\t\t\t\tvector<VariantValue>\tv;\n\t\t\t\tv.push_back (3);\n\t\t\t\tv.push_back (7);\n\t\t\t\tv.push_back (L\"cookie\");\n\t\t\t\tVariantValue\tv1 =\tv;\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"[\\n 3,\\n 7,\\n \\\"cookie\\\"\\n]\");\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ object\n\t\t\t\tmap<wstring,VariantValue>\tv;\n\t\t\t\tv[L\"Arg1\"] = 32;\n\t\t\t\tv[L\"Arg2\"] = L\"Cookies\";\n\t\t\t\tv[L\"Arg3\"] = Containers::mkV<VariantValue> (19);\n\t\t\t\tVariantValue\tv1 =\tv;\n\t\t\t\tCheckMatchesExpected_WRITER_ (v1, \"{\\n \\\"Arg1\\\" : 32,\\n \\\"Arg2\\\" : \\\"Cookies\\\",\\n \\\"Arg3\\\" : [\\n 19\\n ]\\n}\");\n\t\t\t}\n\t\t}\n}\n\n\n\n\nnamespace\t{\n\tvoid\tCheckMatchesExpected_READER_ (const string& v, const VariantValue& expected)\n\t\t{\n\t\t\tstringstream\ttmp;\n\t\t\ttmp << v;\n\t\t\tVariantValue\tv1\t=\tDataExchangeFormat::JSON::Reader (tmp);\n\t\t\tVerifyTestResult (v1.GetType () == expected.GetType ());\n\t\t\tVerifyTestResult (v1 == expected);\n\t\t}\n\n\tvoid\tDoRegressionTests_Reader_ ()\n\t\t{\n\t\t\t{\n\t\t\t\tVariantValue\tv1 = L\"hello world\";\n\t\t\t\tCheckMatchesExpected_READER_ (\"\\\"hello world\\\"\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\tVariantValue\tv1 =\t3;\n\t\t\t\tCheckMatchesExpected_READER_ (\"3\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\tVariantValue\tv1 =\t4.7;\n\t\t\t\tCheckMatchesExpected_READER_ (\"4.7\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ array\n\t\t\t\tvector<VariantValue>\tv;\n\t\t\t\tv.push_back (3);\n\t\t\t\tv.push_back (7);\n\t\t\t\tv.push_back (L\"cookie\");\n\t\t\t\tVariantValue\tv1 =\tv;\n\t\t\t\tCheckMatchesExpected_READER_ (\"[\\n 3,\\n 7,\\n \\\"cookie\\\"\\n]\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ object\n\t\t\t\tmap<wstring,VariantValue>\tv;\n\t\t\t\tv[L\"Arg1\"] = 32;\n\t\t\t\tv[L\"Arg2\"] = L\"Cookies\";\n\t\t\t\tv[L\"Arg3\"] = Containers::mkV<VariantValue> (19);\n\t\t\t\tVariantValue\tv1 =\tv;\n\t\t\t\tCheckMatchesExpected_READER_ (\"{\\n \\\"Arg1\\\" : 32,\\n \\\"Arg2\\\" : \\\"Cookies\\\",\\n \\\"Arg3\\\" : [\\n 19\\n ]\\n}\", v1);\n\t\t\t}\n\t\t\t{\n\t\t\t\t\/\/ Bug found in another JSON reader (sent me by Ryan - 2011-07-27)\n\t\t\t\tconst\tstring\tkExample\t=\t\"{\\\"nav_items\\\":[{\\\"main_link\\\":{\\\"href\\\":\\\"\/about\/index.html\\\",\\\"text\\\":\\\"Who We Are\\\"},\\\"column\\\":[{\\\"link_list\\\":[{},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/company-management.html\\\",\\\"text\\\":\\\"Management\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/mission-statement.html\\\",\\\"text\\\":\\\"Mission\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/company-history.html\\\",\\\"text\\\":\\\" History\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/headquarters.html\\\",\\\"text\\\":\\\"Corporate Headquarters\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/diversity.html\\\",\\\"text\\\":\\\"Diversity\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/supplier-diversity.html\\\",\\\"text\\\":\\\"Supplier Diversity\\\"}}]}]},{\\\"main_link\\\":{\\\"href\\\":\\\"http:\/\/investor.compuware.com\\\",\\\"text\\\":\\\"Investor Relations\\\"}},{\\\"main_link\\\":{\\\"href\\\":\\\"\/about\/newsroom.html\\\",\\\"text\\\":\\\"News Room\\\"},\\\"column\\\":[{\\\"link_list\\\":[{},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/analyst-reports\\\",\\\"text\\\":\\\"Analyst Reports\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/awards-recognition.html\\\",\\\"text\\\":\\\"Awards and Recognition\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/blogs.html\\\",\\\"text\\\":\\\"Blog Home\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/press-analyst-contacts.html\\\",\\\"text\\\":\\\"Contact Us\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/customers.html\\\",\\\"text\\\":\\\"Customers\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/press-mentions\\\",\\\"text\\\":\\\"Press Mentions\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/press-releases\\\",\\\"text\\\":\\\"Press Releases\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/press-resources.html\\\",\\\"text\\\":\\\"Press Resources\\\"}}]}]},{\\\"main_link\\\":{\\\"href\\\":\\\"#top\\\",\\\"text\\\":\\\"Sponsorships\\\"},\\\"column\\\":[{\\\"link_list\\\":[{\\\"header\\\":{\\\"href\\\":\\\"\/about\/lemans-sponsorship.html\\\",\\\"text\\\":\\\"Le Mans\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"\/about\/nhl-sponsorship.html\\\",\\\"text\\\":\\\"NHL\\\"}},{}]}]},{\\\"main_link\\\":{\\\"href\\\":\\\"\/about\/community-involvement.html\\\",\\\"text\\\":\\\"Community Involvement\\\"},\\\"column\\\":[{\\\"link_list\\\":[{\\\"header\\\":{\\\"href\\\":\\\"http:\/\/communityclicks.compuware.com\\\",\\\"text\\\":\\\"Community Clicks Blog\\\"}},{\\\"header\\\":{\\\"href\\\":\\\"javascript:securenav('\/forms\/grant-eligibility-form.html')\\\",\\\"text\\\":\\\"Grant Eligibility Form\\\"}},{}]}]},{\\\"main_link\\\":{\\\"href\\\":\\\"\/government\/\\\",\\\"text\\\":\\\"Government\\\"}}]}\";\n\t\t\t\tstringstream\ttmp;\n\t\t\t\ttmp << kExample;\n\t\t\t\tVariantValue\tv1\t=\tDataExchangeFormat::JSON::Reader (tmp);\n\t\t\t\tVerifyTestResult (v1.GetType () == VariantValue::eMap);\n\t\t\t}\n\n\t\t}\n}\n\n\nnamespace\t{\n\n\tvoid\tDoRegressionTests_ ()\n\t\t{\n\t\t\tDoRegressionTests_Writer_ ();\n\t\t\tDoRegressionTests_Reader_ ();\n\t\t}\n}\n\n\n\n\n#if qOnlyOneMain\nextern int TestJSON ()\n#else\nint main (int argc, const char* argv[])\n#endif\n{\n\tStroika::TestHarness::Setup ();\n\tStroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n\treturn EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * timer.c\n *\n * Created: 1\/6\/2013 6:54:53 PM\n * Author: Collin Kidder\n *\/ \n\n#include \"timer.h\"\n\nvolatile int8_t tickReady;\nvolatile int8_t AgingTimer;\n\nvolatile void due_timer_interrupt();\n\n\/*\nMake the timer0 interrupt every specified number of microseconds\n*\/\nvoid setupTimer(long microSeconds) {\n\t\/\/Setup timer 0 to operate\n \/\/sam3x timer routine wants frequency instead of microseconds so a conversion is necessary\n uint32_t freq = 1000000ul \/ microSeconds;\n startTimer3(freq, due_timer_interrupt);\n}\n\nvolatile void due_timer_interrupt() {\n tickReady = true;\n AgingTimer++;\n}\n<commit_msg>Updated to use a different branch of the DueTimer library<commit_after>\/*\n * timer.c\n *\n * Created: 1\/6\/2013 6:54:53 PM\n * Author: Collin Kidder\n *\/ \n\n#include \"timer.h\"\n\nvolatile int8_t tickReady;\nvolatile int8_t AgingTimer;\n\nvoid due_timer_interrupt();\n\n\/*\nMake the timer0 interrupt every specified number of microseconds\n*\/\nvoid setupTimer(long microSeconds) {\n\t\/\/Setup timer 0 to operate\n \/\/sam3x timer routine wants frequency instead of microseconds so a conversion is necessary\n uint32_t freq = 1000000ul \/ microSeconds;\n Timer3.setFrequency(freq).attachInterrupt(due_timer_interrupt).start();\n \/\/startTimer3(freq, due_timer_interrupt);\n}\n\nvoid due_timer_interrupt() {\n tickReady = true;\n AgingTimer++;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file hmi.cpp\n * @brief The implementation of class HMI. \n * @author laicheng.zhang@itead.cc\n * @date 2015.04\n * \n * @par Copyright:\n * Copyright (c) 2015 ITEAD Intelligent Systems Co., Ltd. \\n\\n\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of\n * the License, or (at your option) any later version. \\n\\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\n#include \"hmi.h\"\nHMI::HMI(HMISerial &uart,uint32_t baud)\n{\n\tmy_uart = &uart; \n my_uart->begin(baud);\n setRxEmpty();\n}\n\t \nbool HMI::textEdit(char *text_id,char *value)\n{\n\t\/*t0.txt=\"abc\"*\/ \n\tchar cmd[50] = {0};\n\tstrcat(cmd,text_id);\n\tstrcat(cmd,\".txt=\\\"\");\n\tstrcat(cmd,value);\n\tstrcat(cmd,\"\\\"\");\n\tmy_uart->print(cmd);\n commandEnd();\n\t \n\tif (returnIsRight() == 0)\n\t\treturn true;\n else \n\t\treturn false;\t\n} \n\nbool HMI::pictureEdit(char *picture_id,uint32_t value)\n{\n\t\/*p0.pic=6*\/ \n\tchar cmd[50] = {0};\n\tchar valuetemp[25] = {0};\n\titoa(value,valuetemp,10);\n\tstrcat(cmd,picture_id);\n\tstrcat(cmd,\".pic=\");\n\tstrcat(cmd,valuetemp);\n\t\t\n\tmy_uart->print(cmd);\n\tcommandEnd();\n \n\tif (returnIsRight() == 0)\n\treturn true;\n\t\telse \n\treturn false;\t\n}\n\nbool HMI::progressBarEdit(char *bar_id,uint32_t value)\n{\n\tchar cmd[50] = {0};\n\tchar valuetemp[25] = {0};\n\titoa(value,valuetemp,10);\n\tstrcat(cmd,bar_id);\n\tstrcat(cmd,\".val=\");\n\tstrcat(cmd,valuetemp);\n\t\n\tmy_uart->print(cmd);\n\tcommandEnd();\n\t\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\t\t\t\t\n}\n\nbool HMI::cutPicture(char *picture_id,uint32_t value)\n{ \n\tchar cmd[50] = {0};\n\tchar valuetemp[25] = {0};\n\titoa(value,valuetemp,10);\n\tstrcat(cmd,picture_id);\n\tstrcat(cmd,\".pic=\");\n\tstrcat(cmd,valuetemp);\n \n\tmy_uart->print(cmd);\n\tcommandEnd();\n \n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\n}\n\nbool HMI::pageChange(uint32_t page_id)\n{ \n\tchar cmd[50] = {0};\n\tchar page_idtemp[25] = {0};\n\titoa(page_id,page_idtemp,10);\n\tstrcat(cmd,\"page\");\n\tstrcat(cmd,\" \");\n\tstrcat(cmd,page_idtemp);\n\tmy_uart->print(cmd);\n\t\n\tcommandEnd(); \n\tdelay(200);\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false; \t\t\n}\n\nvoid HMI::readLcdData(unsigned char *data_buffer)\n{ \n\tdelay(10);\n\tcleanBuffer();\n\tuint32_t i = 0;\n\twhile(my_uart->available() <= 0);\n\twhile(my_uart->available() > 0)\n\t{ \n\t\tdelay(3); \n\t\tbuffer[i] = (unsigned char)my_uart->read();\n\t\ti++;\n\t}\n\tif (buffer[0] == 0x70)\n\t{\n\t\tuint32_t j = 0;\n\t\tuint32_t k = 1;\n\t\tfor(j=0;j<strlen((char*)buffer)-4;)\n\t\t{\n\t\t\tdata_buffer[j]=buffer[k];\t\n\t\t\tj++;\n\t\t\tk++;\n\t\t}\t\t\t\n\t}\t\t\t\n}\n\nbool HMI::returnIsRight(void)\n{\n\tdelay(10);\n\tuint32_t tempid = 0;\n\tunsigned char temp[20] = {0};\n\tunsigned char temp1[4] = {0x01,0xFF,0xFF,0xFF};\n\t \n\ttempid = my_uart->available();\n\tuint32_t i = 0;\n\twhile(my_uart->available())\n\t{\n\t\ttemp[i] = (unsigned char)my_uart->read();\n\t\ti++;\n\t}\n\tif((tempid==4)&&(strncmp((char*)temp1,(char*)temp,4)==0))\n\t{ \n\t\treturn 0;\n\t}\n\telse\n\t{ \n\t\treturn -1;\n\t} \t\n}\n\nbool HMI::touchCalibration(void) \n{ \n\t\/*Serial.println(\"touch Calibration\");*\/\n\tmy_uart->print(\"touch_j\");\n\tcommandEnd(); \t\n\tdelay(5000);\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\n\t\t\n}\n\nbool HMI::disableTouchFocus(void) \n{ \n\t \/*Serial.println(\"disableTouchFocus\");*\/\n\tmy_uart->print(\"cle_c\");\n\tcommandEnd();\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\t\n}\n\nbool HMI::pauseSerialCommand(void) \n{ \n\t\/*Serial.println(\"pauseSerialCommand\");*\/\n\tmy_uart->print(\"com_stop\");\n\tcommandEnd();\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\t\t\n}\n\nbool HMI::recoverySerialCommand(void) \n{ \n\t\/*Serial.println(\"recoverySerialCommand\");*\/\n\tmy_uart->print(\"com_star\");\n\tcommandEnd();\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\t\n}\n\nbool HMI::emptySerialCommand(void) \n{ \n\t\/*Serial.println(\"emptySerialCommand\");*\/\n\tmy_uart->print(\"code_c\");\n\tcommandEnd();\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\n}\n\nuint32_t HMI::returnPageId(void) \n{ \n\tmy_uart->print(\"sendme\"); \n\tcommandEnd();\n\t\n\tdelay(50);\n\tunsigned char temp1[] = {0x66,0xFF,0xFF,0xFF};\n\tunsigned char temp[10] = {0};\n\tuint32_t j = 0;\n\twhile(my_uart->available() > 0)\n\t{\n\t\ttemp[j] = (unsigned char)my_uart->read();\n\t\tdelay(3);\n\t\tj++;\n\t}\n\t\n\tif(!strcmp((char*)temp1[0],(char*)temp[0]))\n\t{ \n\t\treturn (uint32_t)temp[1];\n\t}\t\n\telse \n\t\treturn -1;\t\t\n}\n\nvoid HMI::setRxEmpty(void)\n{\n\twhile(my_uart->available() > 0)\n\t{\n\t\tmy_uart->read();\n\t}\n}\n\nvoid HMI::cleanBuffer(void)\n{\n\tmemset(buffer,0,strlen((char*)buffer));\t\n}\n\nvoid HMI::commandEnd(void)\n{\n\tmy_uart->write(0xFF);\n my_uart->write(0xFF);\n my_uart->write(0xFF);\t\t\n}\n\n\n\n<commit_msg>Update hmi.cpp<commit_after>\/**\n * @file hmi.cpp\n * @brief The implementation of class HMI. \n * @author laicheng.zhang@itead.cc\n * @date 2015.04\n *\/\n\n#include \"hmi.h\"\nHMI::HMI(HMISerial &uart,uint32_t baud)\n{\n\tmy_uart = &uart; \n my_uart->begin(baud);\n setRxEmpty();\n}\n\t \nbool HMI::textEdit(char *text_id,char *value)\n{\n\t\/*t0.txt=\"abc\"*\/ \n\tchar cmd[50] = {0};\n\tstrcat(cmd,text_id);\n\tstrcat(cmd,\".txt=\\\"\");\n\tstrcat(cmd,value);\n\tstrcat(cmd,\"\\\"\");\n\tmy_uart->print(cmd);\n commandEnd();\n\t \n\tif (returnIsRight() == 0)\n\t\treturn true;\n else \n\t\treturn false;\t\n} \n\nbool HMI::pictureEdit(char *picture_id,uint32_t value)\n{\n\t\/*p0.pic=6*\/ \n\tchar cmd[50] = {0};\n\tchar valuetemp[25] = {0};\n\titoa(value,valuetemp,10);\n\tstrcat(cmd,picture_id);\n\tstrcat(cmd,\".pic=\");\n\tstrcat(cmd,valuetemp);\n\t\t\n\tmy_uart->print(cmd);\n\tcommandEnd();\n \n\tif (returnIsRight() == 0)\n\treturn true;\n\t\telse \n\treturn false;\t\n}\n\nbool HMI::progressBarEdit(char *bar_id,uint32_t value)\n{\n\tchar cmd[50] = {0};\n\tchar valuetemp[25] = {0};\n\titoa(value,valuetemp,10);\n\tstrcat(cmd,bar_id);\n\tstrcat(cmd,\".val=\");\n\tstrcat(cmd,valuetemp);\n\t\n\tmy_uart->print(cmd);\n\tcommandEnd();\n\t\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\t\t\t\t\n}\n\nbool HMI::cutPicture(char *picture_id,uint32_t value)\n{ \n\tchar cmd[50] = {0};\n\tchar valuetemp[25] = {0};\n\titoa(value,valuetemp,10);\n\tstrcat(cmd,picture_id);\n\tstrcat(cmd,\".pic=\");\n\tstrcat(cmd,valuetemp);\n \n\tmy_uart->print(cmd);\n\tcommandEnd();\n \n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\n}\n\nbool HMI::pageChange(uint32_t page_id)\n{ \n\tchar cmd[50] = {0};\n\tchar page_idtemp[25] = {0};\n\titoa(page_id,page_idtemp,10);\n\tstrcat(cmd,\"page\");\n\tstrcat(cmd,\" \");\n\tstrcat(cmd,page_idtemp);\n\tmy_uart->print(cmd);\n\t\n\tcommandEnd(); \n\tdelay(200);\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false; \t\t\n}\n\nvoid HMI::readLcdData(unsigned char *data_buffer)\n{ \n\tdelay(10);\n\tcleanBuffer();\n\tuint32_t i = 0;\n\twhile(my_uart->available() <= 0);\n\twhile(my_uart->available() > 0)\n\t{ \n\t\tdelay(3); \n\t\tbuffer[i] = (unsigned char)my_uart->read();\n\t\ti++;\n\t}\n\tif (buffer[0] == 0x70)\n\t{\n\t\tuint32_t j = 0;\n\t\tuint32_t k = 1;\n\t\tfor(j=0;j<strlen((char*)buffer)-4;)\n\t\t{\n\t\t\tdata_buffer[j]=buffer[k];\t\n\t\t\tj++;\n\t\t\tk++;\n\t\t}\t\t\t\n\t}\t\t\t\n}\n\nbool HMI::returnIsRight(void)\n{\n\tdelay(10);\n\tuint32_t tempid = 0;\n\tunsigned char temp[20] = {0};\n\tunsigned char temp1[4] = {0x01,0xFF,0xFF,0xFF};\n\t \n\ttempid = my_uart->available();\n\tuint32_t i = 0;\n\twhile(my_uart->available())\n\t{\n\t\ttemp[i] = (unsigned char)my_uart->read();\n\t\ti++;\n\t}\n\tif((tempid==4)&&(strncmp((char*)temp1,(char*)temp,4)==0))\n\t{ \n\t\treturn 0;\n\t}\n\telse\n\t{ \n\t\treturn -1;\n\t} \t\n}\n\nbool HMI::touchCalibration(void) \n{ \n\t\/*Serial.println(\"touch Calibration\");*\/\n\tmy_uart->print(\"touch_j\");\n\tcommandEnd(); \t\n\tdelay(5000);\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\n\t\t\n}\n\nbool HMI::disableTouchFocus(void) \n{ \n\t \/*Serial.println(\"disableTouchFocus\");*\/\n\tmy_uart->print(\"cle_c\");\n\tcommandEnd();\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\t\n}\n\nbool HMI::pauseSerialCommand(void) \n{ \n\t\/*Serial.println(\"pauseSerialCommand\");*\/\n\tmy_uart->print(\"com_stop\");\n\tcommandEnd();\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\t\t\n}\n\nbool HMI::recoverySerialCommand(void) \n{ \n\t\/*Serial.println(\"recoverySerialCommand\");*\/\n\tmy_uart->print(\"com_star\");\n\tcommandEnd();\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\t\n}\n\nbool HMI::emptySerialCommand(void) \n{ \n\t\/*Serial.println(\"emptySerialCommand\");*\/\n\tmy_uart->print(\"code_c\");\n\tcommandEnd();\n\tif (returnIsRight() == 0)\n\t\treturn true;\n\telse \n\t\treturn false;\n}\n\nuint32_t HMI::returnPageId(void) \n{ \n\tmy_uart->print(\"sendme\"); \n\tcommandEnd();\n\t\n\tdelay(50);\n\tunsigned char temp1[] = {0x66,0xFF,0xFF,0xFF};\n\tunsigned char temp[10] = {0};\n\tuint32_t j = 0;\n\twhile(my_uart->available() > 0)\n\t{\n\t\ttemp[j] = (unsigned char)my_uart->read();\n\t\tdelay(3);\n\t\tj++;\n\t}\n\t\n\tif(!strcmp((char*)temp1[0],(char*)temp[0]))\n\t{ \n\t\treturn (uint32_t)temp[1];\n\t}\t\n\telse \n\t\treturn -1;\t\t\n}\n\nvoid HMI::setRxEmpty(void)\n{\n\twhile(my_uart->available() > 0)\n\t{\n\t\tmy_uart->read();\n\t}\n}\n\nvoid HMI::cleanBuffer(void)\n{\n\tmemset(buffer,0,strlen((char*)buffer));\t\n}\n\nvoid HMI::commandEnd(void)\n{\n\tmy_uart->write(0xFF);\n my_uart->write(0xFF);\n my_uart->write(0xFF);\t\t\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The Descent map loader\n\/\/\n\/\/ NAME : Hog\n\/\/ PURPOSE : Providing a decoder and wrapper for the Descent .HOG format.\n\/\/ COPYRIGHT : (c) 2011 Sean Donnellan. All Rights Reserved.\n\/\/ AUTHORS : Sean Donnellan (darkdonno@gmail.com)\n\/\/ DESCRIPTION : A decoder for the HOG file format that is used by Parallax\n\/\/ Software in the computer game, Descent.\n\/\/\n\/\/ The file format is as follows:\n\/\/\n\/\/ - Magic number which is 3 bytes and corresponding to the\n\/\/ string \"DHF\"\n\n\/\/ - A series of files which are preceded by a short header,\n\/\/ which describes the name of the file and the numer of bytes.\n\/\/\n\/\/ | \"DHF\" - 3 bytes\n\/\/ |---------------- Start of the first file\n\/\/ | filename - 13 bytes\n\/\/ | size - 4 bytes\n\/\/ | data - the size of this part is by the size before it.\n\/\/ |---------------- The next header\/file comes straight after.\n\/\/ | filename - 13 bytes\n\/\/ | size - 4 bytes\n\/\/ | data - the size of this part is by the size before it.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/\/\/\n\/\/ Developer notes\n\/\/ Different file formats: http:\/\/www.descent2.com\/ddn\/kb\/files\/\n\/\/\n\/\/\/\/\/\n\n#include \"hogreader.hpp\"\n#include \"hogiterator.hpp\"\n#include \"rdl.hpp\"\n\n#include <memory>\n#include <iterator>\n#include <utility>\n#include <vector>\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef _MSC_VER\nstatic_assert(sizeof(uint8_t) == 1,\n \"The size of uint8_t is incorrect it must be 1-byte\");\nstatic_assert(sizeof(uint32_t) == 4,\n \"The size of uint32_t is incorrect it must be 4-bytes\");\nstatic_assert(sizeof(uint8_t) == sizeof(char),\n \"The size of a char must be 1-byte\");\n#endif\n\n\/\/ The 3-byte MAGIC number at the start of the file format used to identifiy the\n\/\/ file as being a Descent HOG file.\nstatic uint8_t magic[3] = {'D', 'H', 'F'};\n\nHogReader::iterator HogReader::begin()\n{\n \/\/ Sync back up to the start just after the magic number.\n if (IsValid())\n {\n fseek(myFile, sizeof(magic), SEEK_SET);\n if (fread(&myChildFile.name, 13, 1, myFile) != 1) HogReaderIterator();\n if (fread(&myChildFile.size, 4, 1, myFile) != 1) HogReaderIterator();\n }\n\n return HogReaderIterator(*this);\n}\n\nHogReader::iterator HogReader::end() { return HogReaderIterator(); }\n\nHogReader::HogReader(const char* filename) : myFile(nullptr)\n{\n myFile = fopen(filename, \"rb\");\n myChildFile.name[0] = '\\0';\n myChildFile.size = 0;\n if (!myFile) return;\n\n const size_t count = 1;\n if (fread(myHeader, sizeof(myHeader), count, myFile) != count)\n {\n myHeader[0] = '\\0'; \/\/ Failed to load.\n return;\n }\n\n \/\/ Read in the header for the first file.\n if (IsValid())\n {\n if (fread(&myChildFile.name, 13, 1, myFile) != 1) return;\n if (fread(&myChildFile.size, 4, 1, myFile) != 1) return;\n }\n}\n\nHogReader::~HogReader()\n{\n if (myFile) fclose(myFile);\n}\n\nbool HogReader::IsValid() const\n{\n if (!myFile) return false;\n return memcmp(myHeader, magic, 3) == 0;\n}\n\nbool HogReader::NextFile()\n{\n \/\/ Skip the current file.\n if (feof(myFile)) return false;\n\n if (!hasReadFile)\n {\n \/\/ The data for the current file has not been read so skip over the data\n \/\/ section\n \/\/ for the file.\n\n if (fseek(myFile, myChildFile.size, SEEK_CUR) != 0) return false;\n }\n\n \/\/ Read in the header for the next file.\n if (fread(&myChildFile.name, 13, 1, myFile) != 1) return false;\n if (fread(&myChildFile.size, 4, 1, myFile) != 1) return false;\n\n hasReadFile = false; \/\/ We haven't read the next file yet.\n return true;\n}\n\nconst char* HogReader::CurrentFileName() const { return myChildFile.name; }\n\nunsigned int HogReader::CurrentFileSize() const { return myChildFile.size; }\n\nstd::vector<uint8_t> HogReader::CurrentFile()\n{\n std::vector<uint8_t> fileData;\n\n \/\/ TODO: Allow this to seek-back and read it again.\n \/\/\n \/\/ For now ensure the current file hasn't been read yet.\n assert(!hasReadFile);\n\n \/\/ Skip the current file.\n if (feof(myFile)) return fileData;\n\n const unsigned int size = CurrentFileSize(); \/\/ Size in bytes\n fileData.resize(size);\n\n if (fread(fileData.data(), size, 1, myFile) != 1)\n {\n fileData.clear();\n }\n\n return fileData;\n}\n\n#include <string>\n#include <algorithm>\n\nint main(int argc, char* argv[])\n{\n if (argc != 2)\n {\n printf(\"usage: %s filename\\n\", argv[0]);\n return 1;\n }\n\n HogReader reader(argv[1]);\n if (!reader.IsValid())\n {\n fprintf(stderr, \"error to open the hog file\");\n return 1;\n }\n\n \/\/ File list.\n const bool listingAllFiles = false;\n if (listingAllFiles)\n {\n printf(\"Filename\\n\");\n printf(\"========\\n\");\n std::for_each(reader.begin(), reader.end(),\n [](HogReader::iterator::value_type n)\n { printf(\"%s %p\\n\", n.first, n.second); });\n }\n else\n {\n \/\/ Iterate over the file list and list all the files which do not\n \/\/ end in the 'rdl' file extension.\n const std::string extentionRdl(\".rdl\");\n std::for_each(reader.begin(), reader.end(),\n [&extentionRdl](HogReader::iterator::value_type n)\n {\n const std::string filename(n.first);\n if (!std::equal(extentionRdl.rbegin(), extentionRdl.rend(),\n filename.rbegin()))\n return;\n\n printf(\"%s %d\\n\", n.first, n.second->CurrentFileSize());\n const auto data = n.second->CurrentFile();\n RdlReader rdlReader(data);\n printf(\"Is valid RDL: %s\\n\", rdlReader.IsValid() ? \"Yes\" : \"No\");\n\n if (!rdlReader.IsValid()) return;\n\n const auto vertices = rdlReader.Vertices();\n printf(\"Vertex count: %d\\n\", vertices.size());\n std::for_each(vertices.begin(), vertices.end(),\n [](Vertex v)\n { printf(\"%16f %16f %16f\\n\", v.x, v.y, v.z); });\n\n\n exit(0);\n });\n }\n return 0;\n}\n<commit_msg>Changed over the main function to call DoStuff() which tries to parse the cubes in the RDL file.<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The Descent map loader\n\/\/\n\/\/ NAME : Hog\n\/\/ PURPOSE : Providing a decoder and wrapper for the Descent .HOG format.\n\/\/ COPYRIGHT : (c) 2011 Sean Donnellan. All Rights Reserved.\n\/\/ AUTHORS : Sean Donnellan (darkdonno@gmail.com)\n\/\/ DESCRIPTION : A decoder for the HOG file format that is used by Parallax\n\/\/ Software in the computer game, Descent.\n\/\/\n\/\/ The file format is as follows:\n\/\/\n\/\/ - Magic number which is 3 bytes and corresponding to the\n\/\/ string \"DHF\"\n\n\/\/ - A series of files which are preceded by a short header,\n\/\/ which describes the name of the file and the numer of bytes.\n\/\/\n\/\/ | \"DHF\" - 3 bytes\n\/\/ |---------------- Start of the first file\n\/\/ | filename - 13 bytes\n\/\/ | size - 4 bytes\n\/\/ | data - the size of this part is by the size before it.\n\/\/ |---------------- The next header\/file comes straight after.\n\/\/ | filename - 13 bytes\n\/\/ | size - 4 bytes\n\/\/ | data - the size of this part is by the size before it.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/\/\/\n\/\/ Developer notes\n\/\/ Different file formats: http:\/\/www.descent2.com\/ddn\/kb\/files\/\n\/\/\n\/\/\/\/\/\n\n#include \"hogreader.hpp\"\n#include \"hogiterator.hpp\"\n#include \"rdl.hpp\"\n\n#include <memory>\n#include <iterator>\n#include <utility>\n#include <vector>\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef _MSC_VER\nstatic_assert(sizeof(uint8_t) == 1,\n \"The size of uint8_t is incorrect it must be 1-byte\");\nstatic_assert(sizeof(uint32_t) == 4,\n \"The size of uint32_t is incorrect it must be 4-bytes\");\nstatic_assert(sizeof(uint8_t) == sizeof(char),\n \"The size of a char must be 1-byte\");\n#endif\n\n\/\/ The 3-byte MAGIC number at the start of the file format used to identifiy the\n\/\/ file as being a Descent HOG file.\nstatic uint8_t magic[3] = {'D', 'H', 'F'};\n\nHogReader::iterator HogReader::begin()\n{\n \/\/ Sync back up to the start just after the magic number.\n if (IsValid())\n {\n fseek(myFile, sizeof(magic), SEEK_SET);\n if (fread(&myChildFile.name, 13, 1, myFile) != 1) HogReaderIterator();\n if (fread(&myChildFile.size, 4, 1, myFile) != 1) HogReaderIterator();\n }\n\n return HogReaderIterator(*this);\n}\n\nHogReader::iterator HogReader::end() { return HogReaderIterator(); }\n\nHogReader::HogReader(const char* filename) : myFile(nullptr)\n{\n myFile = fopen(filename, \"rb\");\n myChildFile.name[0] = '\\0';\n myChildFile.size = 0;\n if (!myFile) return;\n\n const size_t count = 1;\n if (fread(myHeader, sizeof(myHeader), count, myFile) != count)\n {\n myHeader[0] = '\\0'; \/\/ Failed to load.\n return;\n }\n\n \/\/ Read in the header for the first file.\n if (IsValid())\n {\n if (fread(&myChildFile.name, 13, 1, myFile) != 1) return;\n if (fread(&myChildFile.size, 4, 1, myFile) != 1) return;\n }\n}\n\nHogReader::~HogReader()\n{\n if (myFile) fclose(myFile);\n}\n\nbool HogReader::IsValid() const\n{\n if (!myFile) return false;\n return memcmp(myHeader, magic, 3) == 0;\n}\n\nbool HogReader::NextFile()\n{\n \/\/ Skip the current file.\n if (feof(myFile)) return false;\n\n if (!hasReadFile)\n {\n \/\/ The data for the current file has not been read so skip over the data\n \/\/ section\n \/\/ for the file.\n\n if (fseek(myFile, myChildFile.size, SEEK_CUR) != 0) return false;\n }\n\n \/\/ Read in the header for the next file.\n if (fread(&myChildFile.name, 13, 1, myFile) != 1) return false;\n if (fread(&myChildFile.size, 4, 1, myFile) != 1) return false;\n\n hasReadFile = false; \/\/ We haven't read the next file yet.\n return true;\n}\n\nconst char* HogReader::CurrentFileName() const { return myChildFile.name; }\n\nunsigned int HogReader::CurrentFileSize() const { return myChildFile.size; }\n\nstd::vector<uint8_t> HogReader::CurrentFile()\n{\n std::vector<uint8_t> fileData;\n\n \/\/ TODO: Allow this to seek-back and read it again.\n \/\/\n \/\/ For now ensure the current file hasn't been read yet.\n assert(!hasReadFile);\n\n \/\/ Skip the current file.\n if (feof(myFile)) return fileData;\n\n const unsigned int size = CurrentFileSize(); \/\/ Size in bytes\n fileData.resize(size);\n\n if (fread(fileData.data(), size, 1, myFile) != 1)\n {\n fileData.clear();\n }\n\n return fileData;\n}\n\n#include <string>\n#include <algorithm>\n\nint main(int argc, char* argv[])\n{\n if (argc != 2)\n {\n printf(\"usage: %s filename\\n\", argv[0]);\n return 1;\n }\n\n HogReader reader(argv[1]);\n if (!reader.IsValid())\n {\n fprintf(stderr, \"error to open the hog file\");\n return 1;\n }\n\n \/\/ File list.\n const bool listingAllFiles = false;\n if (listingAllFiles)\n {\n printf(\"Filename\\n\");\n printf(\"========\\n\");\n std::for_each(reader.begin(), reader.end(),\n [](HogReader::iterator::value_type n)\n { printf(\"%s %p\\n\", n.first, n.second); });\n }\n else\n {\n \/\/ Iterate over the file list and list all the files which do not\n \/\/ end in the 'rdl' file extension.\n const std::string extentionRdl(\".rdl\");\n std::for_each(reader.begin(), reader.end(),\n [&extentionRdl](HogReader::iterator::value_type n)\n {\n const std::string filename(n.first);\n if (!std::equal(extentionRdl.rbegin(), extentionRdl.rend(),\n filename.rbegin()))\n return;\n\n printf(\"%s %d\\n\", n.first, n.second->CurrentFileSize());\n const auto data = n.second->CurrentFile();\n RdlReader rdlReader(data);\n printf(\"Is valid RDL: %s\\n\", rdlReader.IsValid() ? \"Yes\" : \"No\");\n\n if (!rdlReader.IsValid()) return;\n\n \/*\n \/\/ Print out the vertices.\n const auto vertices = rdlReader.Vertices();\n printf(\"Vertex count: %d\\n\", vertices.size());\n std::for_each(vertices.begin(), vertices.end(),\n [](Vertex v)\n { printf(\"%16f %16f %16f\\n\", v.x, v.y, v.z); });\n *\/\n rdlReader.DoStuff();\n\n exit(0);\n });\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\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#include \"ProgressDialogManager.h\"\n\n#include \"DataSource.h\"\n#include \"ModuleManager.h\"\n#include \"Operator.h\"\n\n#include <QCoreApplication>\n#include <QDialog>\n#include <QDialogButtonBox>\n#include <QMainWindow>\n#include <QMap>\n#include <QProgressBar>\n#include <QStatusBar>\n#include <QVBoxLayout>\n\n#include <cassert>\n#include <iostream>\n\nnamespace tomviz {\n\nProgressDialogManager::ProgressDialogManager(QMainWindow* mw)\n : Superclass(mw), mainWindow(mw)\n{\n ModuleManager& mm = ModuleManager::instance();\n QObject::connect(&mm, SIGNAL(dataSourceAdded(DataSource*)), this,\n SLOT(dataSourceAdded(DataSource*)));\n}\n\nProgressDialogManager::~ProgressDialogManager()\n{\n}\n\nvoid ProgressDialogManager::operationStarted()\n{\n QDialog* progressDialog = new QDialog(this->mainWindow);\n progressDialog->setAttribute(Qt::WA_DeleteOnClose);\n\n Operator* op = qobject_cast<Operator*>(this->sender());\n QObject::connect(op, &Operator::transformingDone, progressDialog,\n &QDialog::accept);\n\n \/\/ We have to check after we have connected to the signal as otherwise we\n \/\/ might miss the state transition as its occurring on another thread.\n if (op->isFinished()) {\n progressDialog->accept();\n progressDialog->deleteLater();\n return;\n }\n\n QLayout* layout = new QVBoxLayout();\n QWidget* progressWidget = op->getCustomProgressWidget(progressDialog);\n if (progressWidget == nullptr) {\n QProgressBar* progressBar = new QProgressBar(progressDialog);\n progressBar->setMinimum(0);\n progressBar->setMaximum(op->totalProgressSteps());\n progressWidget = progressBar;\n QObject::connect(op, &Operator::progressStepChanged, progressBar,\n &QProgressBar::setValue);\n QObject::connect(op, &Operator::totalProgressStepsChanged, progressBar,\n &QProgressBar::setMaximum);\n QObject::connect(op, &Operator::progressStepChanged, this,\n &ProgressDialogManager::operationProgress);\n QObject::connect(\n op, &Operator::progressMessageChanged,\n [progressDialog, op](const QString& message) {\n if (!message.isNull()) {\n QString title = QString(\"%1 Progress\").arg(op->label());\n if (!message.isEmpty()) {\n title = QString(\"%1 Progress - %2\").arg(op->label()).arg(message);\n }\n progressDialog->setWindowTitle(title);\n }\n });\n QObject::connect(progressDialog, &QDialog::rejected, [op]() {\n QObject::disconnect(op, &Operator::progressMessageChanged, nullptr,\n nullptr);\n });\n\n connect(op, &Operator::progressMessageChanged, this,\n &ProgressDialogManager::showStatusBarMessage);\n\n layout->addWidget(progressBar);\n }\n layout->addWidget(progressWidget);\n if (op->supportsCancelingMidTransform()) {\n \/\/ Unless the widget has custom progress handling, you can't cancel it.\n QDialogButtonBox* dialogButtons = new QDialogButtonBox(\n QDialogButtonBox::Cancel, Qt::Horizontal, progressDialog);\n layout->addWidget(dialogButtons);\n QObject::connect(dialogButtons, &QDialogButtonBox::rejected, op,\n &Operator::cancelTransform);\n QObject::connect(dialogButtons, &QDialogButtonBox::rejected, progressDialog,\n &QDialog::reject);\n }\n progressDialog->setWindowTitle(QString(\"%1 Progress\").arg(op->label()));\n progressDialog->setLayout(layout);\n progressDialog->adjustSize();\n \/\/ Increase size of dialog so we can see title, not sure there is a better\n \/\/ way.\n auto height = progressDialog->height();\n progressDialog->resize(500, height);\n progressDialog->show();\n QCoreApplication::processEvents();\n}\n\nvoid ProgressDialogManager::operatorAdded(Operator* op)\n{\n connect(op, &Operator::transformingStarted, this,\n &ProgressDialogManager::operationStarted,\n Qt::BlockingQueuedConnection);\n\n connect(op, &Operator::newChildDataSource, this,\n &ProgressDialogManager::dataSourceAdded);\n}\n\nvoid ProgressDialogManager::dataSourceAdded(DataSource* ds)\n{\n QObject::connect(ds, SIGNAL(operatorAdded(Operator*)), this,\n SLOT(operatorAdded(Operator*)));\n}\n\nvoid ProgressDialogManager::operationProgress(int)\n{\n \/\/ Probably not strictly neccessary in the long run where we have a background\n \/\/ thread, until then we need this call.\n QCoreApplication::processEvents();\n}\n\nvoid ProgressDialogManager::showStatusBarMessage(const QString& message)\n{\n this->mainWindow->statusBar()->showMessage(message, 3000);\n}\n}\n<commit_msg>Make closing the progress dialog the same as pressing Cancel<commit_after>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\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#include \"ProgressDialogManager.h\"\n\n#include \"DataSource.h\"\n#include \"ModuleManager.h\"\n#include \"Operator.h\"\n\n#include <QCoreApplication>\n#include <QDialog>\n#include <QDialogButtonBox>\n#include <QMainWindow>\n#include <QMap>\n#include <QProgressBar>\n#include <QStatusBar>\n#include <QVBoxLayout>\n\n#include <cassert>\n#include <iostream>\n\nnamespace tomviz {\n\nProgressDialogManager::ProgressDialogManager(QMainWindow* mw)\n : Superclass(mw), mainWindow(mw)\n{\n ModuleManager& mm = ModuleManager::instance();\n QObject::connect(&mm, SIGNAL(dataSourceAdded(DataSource*)), this,\n SLOT(dataSourceAdded(DataSource*)));\n}\n\nProgressDialogManager::~ProgressDialogManager()\n{\n}\n\nvoid ProgressDialogManager::operationStarted()\n{\n QDialog* progressDialog = new QDialog(this->mainWindow);\n progressDialog->setAttribute(Qt::WA_DeleteOnClose);\n\n Operator* op = qobject_cast<Operator*>(this->sender());\n QObject::connect(op, &Operator::transformingDone, progressDialog,\n &QDialog::accept);\n\n \/\/ We have to check after we have connected to the signal as otherwise we\n \/\/ might miss the state transition as its occurring on another thread.\n if (op->isFinished()) {\n progressDialog->accept();\n progressDialog->deleteLater();\n return;\n }\n\n QLayout* layout = new QVBoxLayout();\n QWidget* progressWidget = op->getCustomProgressWidget(progressDialog);\n if (progressWidget == nullptr) {\n QProgressBar* progressBar = new QProgressBar(progressDialog);\n progressBar->setMinimum(0);\n progressBar->setMaximum(op->totalProgressSteps());\n progressWidget = progressBar;\n QObject::connect(op, &Operator::progressStepChanged, progressBar,\n &QProgressBar::setValue);\n QObject::connect(op, &Operator::totalProgressStepsChanged, progressBar,\n &QProgressBar::setMaximum);\n QObject::connect(op, &Operator::progressStepChanged, this,\n &ProgressDialogManager::operationProgress);\n QObject::connect(\n op, &Operator::progressMessageChanged,\n [progressDialog, op](const QString& message) {\n if (!message.isNull()) {\n QString title = QString(\"%1 Progress\").arg(op->label());\n if (!message.isEmpty()) {\n title = QString(\"%1 Progress - %2\").arg(op->label()).arg(message);\n }\n progressDialog->setWindowTitle(title);\n }\n });\n QObject::connect(progressDialog, &QDialog::rejected, [op]() {\n QObject::disconnect(op, &Operator::progressMessageChanged, nullptr,\n nullptr);\n });\n\n connect(op, &Operator::progressMessageChanged, this,\n &ProgressDialogManager::showStatusBarMessage);\n\n layout->addWidget(progressBar);\n }\n layout->addWidget(progressWidget);\n if (op->supportsCancelingMidTransform()) {\n \/\/ Unless the widget has custom progress handling, you can't cancel it.\n QDialogButtonBox* dialogButtons = new QDialogButtonBox(\n QDialogButtonBox::Cancel, Qt::Horizontal, progressDialog);\n layout->addWidget(dialogButtons);\n QObject::connect(progressDialog, &QDialog::rejected, op,\n &Operator::cancelTransform);\n QObject::connect(dialogButtons, &QDialogButtonBox::rejected, progressDialog,\n &QDialog::reject);\n }\n progressDialog->setWindowTitle(QString(\"%1 Progress\").arg(op->label()));\n progressDialog->setLayout(layout);\n progressDialog->adjustSize();\n \/\/ Increase size of dialog so we can see title, not sure there is a better\n \/\/ way.\n auto height = progressDialog->height();\n progressDialog->resize(500, height);\n progressDialog->show();\n QCoreApplication::processEvents();\n}\n\nvoid ProgressDialogManager::operatorAdded(Operator* op)\n{\n connect(op, &Operator::transformingStarted, this,\n &ProgressDialogManager::operationStarted,\n Qt::BlockingQueuedConnection);\n\n connect(op, &Operator::newChildDataSource, this,\n &ProgressDialogManager::dataSourceAdded);\n}\n\nvoid ProgressDialogManager::dataSourceAdded(DataSource* ds)\n{\n QObject::connect(ds, SIGNAL(operatorAdded(Operator*)), this,\n SLOT(operatorAdded(Operator*)));\n}\n\nvoid ProgressDialogManager::operationProgress(int)\n{\n \/\/ Probably not strictly neccessary in the long run where we have a background\n \/\/ thread, until then we need this call.\n QCoreApplication::processEvents();\n}\n\nvoid ProgressDialogManager::showStatusBarMessage(const QString& message)\n{\n this->mainWindow->statusBar()->showMessage(message, 3000);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"abstractsessionitem.h\"\n#include <IrcSession>\n\nAbstractSessionItem::AbstractSessionItem(QObject *parent) :\n QObject(parent), m_session(0), m_current(false), m_highlighted(false), m_unread(false)\n{\n m_messages = new QStringListModel(this);\n m_formatter.setTimeStamp(true);\n}\n\nIrcSession* AbstractSessionItem::session() const\n{\n return m_session;\n}\n\nvoid AbstractSessionItem::setSession(IrcSession *session)\n{\n m_session = session;\n m_formatter.setHighlights(QStringList() << session->nickName());\n}\n\nQString AbstractSessionItem::title() const\n{\n return m_title;\n}\n\nvoid AbstractSessionItem::setTitle(const QString& title)\n{\n if (m_title != title)\n {\n m_title = title;\n emit titleChanged();\n }\n}\n\nQString AbstractSessionItem::subtitle() const\n{\n return m_subtitle;\n}\n\nvoid AbstractSessionItem::setSubtitle(const QString& subtitle)\n{\n if (m_subtitle != subtitle)\n {\n m_subtitle = subtitle;\n emit subtitleChanged();\n }\n}\n\nbool AbstractSessionItem::isCurrent() const\n{\n return m_current;\n}\n\nvoid AbstractSessionItem::setCurrent(bool current)\n{\n if (current)\n {\n setHighlighted(false);\n setUnread(0);\n }\n\n if (m_current != current)\n {\n m_current = current;\n emit currentChanged();\n }\n}\n\nbool AbstractSessionItem::isHighlighted() const\n{\n return m_highlighted;\n}\n\nvoid AbstractSessionItem::setHighlighted(bool highlighted)\n{\n if (!m_current && m_highlighted != highlighted)\n {\n m_highlighted = highlighted;\n emit highlightedChanged();\n }\n}\n\nint AbstractSessionItem::unread() const\n{\n return m_unread;\n}\n\nvoid AbstractSessionItem::setUnread(int unread)\n{\n if (!m_current && m_unread != unread)\n {\n m_unread = unread;\n emit unreadChanged();\n }\n}\n\nQStringList AbstractSessionItem::users() const\n{\n return m_users;\n}\n\nQObject* AbstractSessionItem::messages() const\n{\n return m_messages;\n}\n\nvoid AbstractSessionItem::addUser(const QString& user)\n{\n m_users.append(user);\n emit usersChanged();\n}\n\nvoid AbstractSessionItem::removeUser(const QString& user)\n{\n m_users.removeOne(user);\n emit usersChanged();\n}\n\nvoid AbstractSessionItem::receiveMessage(IrcMessage* message)\n{\n const int index = m_messages->rowCount();\n m_messages->insertRow(index);\n m_messages->setData(m_messages->index(index), m_formatter.formatMessage(message));\n}\n<commit_msg>qml ex: applied formatter colors<commit_after>#include \"abstractsessionitem.h\"\n#include <IrcSession>\n\nAbstractSessionItem::AbstractSessionItem(QObject *parent) :\n QObject(parent), m_session(0), m_current(false), m_highlighted(false), m_unread(false)\n{\n m_messages = new QStringListModel(this);\n m_formatter.setTimeStamp(true);\n m_formatter.setEventFormat(\"style='color:gray'\");\n m_formatter.setNoticeFormat(\"style='color:brown'\");\n m_formatter.setActionFormat(\"style='color:darkmagenta'\");\n m_formatter.setUnknownFormat(\"style='color:brown'\");\n m_formatter.setHighlightFormat(\"style='color:red'\");\n}\n\nIrcSession* AbstractSessionItem::session() const\n{\n return m_session;\n}\n\nvoid AbstractSessionItem::setSession(IrcSession *session)\n{\n m_session = session;\n m_formatter.setHighlights(QStringList() << session->nickName());\n}\n\nQString AbstractSessionItem::title() const\n{\n return m_title;\n}\n\nvoid AbstractSessionItem::setTitle(const QString& title)\n{\n if (m_title != title)\n {\n m_title = title;\n emit titleChanged();\n }\n}\n\nQString AbstractSessionItem::subtitle() const\n{\n return m_subtitle;\n}\n\nvoid AbstractSessionItem::setSubtitle(const QString& subtitle)\n{\n if (m_subtitle != subtitle)\n {\n m_subtitle = subtitle;\n emit subtitleChanged();\n }\n}\n\nbool AbstractSessionItem::isCurrent() const\n{\n return m_current;\n}\n\nvoid AbstractSessionItem::setCurrent(bool current)\n{\n if (current)\n {\n setHighlighted(false);\n setUnread(0);\n }\n\n if (m_current != current)\n {\n m_current = current;\n emit currentChanged();\n }\n}\n\nbool AbstractSessionItem::isHighlighted() const\n{\n return m_highlighted;\n}\n\nvoid AbstractSessionItem::setHighlighted(bool highlighted)\n{\n if (!m_current && m_highlighted != highlighted)\n {\n m_highlighted = highlighted;\n emit highlightedChanged();\n }\n}\n\nint AbstractSessionItem::unread() const\n{\n return m_unread;\n}\n\nvoid AbstractSessionItem::setUnread(int unread)\n{\n if (!m_current && m_unread != unread)\n {\n m_unread = unread;\n emit unreadChanged();\n }\n}\n\nQStringList AbstractSessionItem::users() const\n{\n return m_users;\n}\n\nQObject* AbstractSessionItem::messages() const\n{\n return m_messages;\n}\n\nvoid AbstractSessionItem::addUser(const QString& user)\n{\n m_users.append(user);\n emit usersChanged();\n}\n\nvoid AbstractSessionItem::removeUser(const QString& user)\n{\n m_users.removeOne(user);\n emit usersChanged();\n}\n\nvoid AbstractSessionItem::receiveMessage(IrcMessage* message)\n{\n const int index = m_messages->rowCount();\n m_messages->insertRow(index);\n m_messages->setData(m_messages->index(index), m_formatter.formatMessage(message));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2019 Google Inc.\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#include \"cleanup.hpp\"\n\n#include <blobs-ipmid\/blobs.hpp>\n\n#include <filesystem>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace ipmi_flash\n{\n\nstd::unique_ptr<blobs::GenericBlobInterface>\n FileCleanupHandler::CreateCleanupHandler(\n const std::string& blobId, const std::vector<std::string>& files)\n{\n return std::make_unique<FileCleanupHandler>(blobId, files);\n}\n\nbool FileCleanupHandler::canHandleBlob(const std::string& path)\n{\n return (path == supported);\n}\n\nstd::vector<std::string> FileCleanupHandler::getBlobIds()\n{\n return {supported};\n}\n\nbool FileCleanupHandler::commit(uint16_t session,\n const std::vector<uint8_t>& data)\n{\n namespace fs = std::filesystem;\n\n for (const auto& file : files)\n {\n helper->remove(file);\n }\n\n return true;\n}\n\n} \/\/ namespace ipmi_flash\n<commit_msg>cleanup: drop inclusion of unused filesystem header<commit_after>\/*\n * Copyright 2019 Google Inc.\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#include \"cleanup.hpp\"\n\n#include <blobs-ipmid\/blobs.hpp>\n\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace ipmi_flash\n{\n\nstd::unique_ptr<blobs::GenericBlobInterface>\n FileCleanupHandler::CreateCleanupHandler(\n const std::string& blobId, const std::vector<std::string>& files)\n{\n return std::make_unique<FileCleanupHandler>(blobId, files);\n}\n\nbool FileCleanupHandler::canHandleBlob(const std::string& path)\n{\n return (path == supported);\n}\n\nstd::vector<std::string> FileCleanupHandler::getBlobIds()\n{\n return {supported};\n}\n\nbool FileCleanupHandler::commit(uint16_t session,\n const std::vector<uint8_t>& data)\n{\n for (const auto& file : files)\n {\n helper->remove(file);\n }\n\n return true;\n}\n\n} \/\/ namespace ipmi_flash\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * Reverse Polish Notation calculator. *\n * Copyright (c) 2007-2008, Samuel Fredrickson <kinghajj@gmail.com> *\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 met: *\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 the *\n * documentation and\/or other materials provided with the distribution. *\n * *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY EXPRESS *\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY *\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *\n * SERVICES; 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 ANY WAY *\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH *\n * DAMAGE. *\n ******************************************************************************\/\n\n\/*******************************************************************************\n * Calculator.cpp - non-command Calculator methods. *\n ******************************************************************************\/\n\n#include \"rpn.h\"\n#include <boost\/tokenizer.hpp>\n#include <sstream>\nusing namespace boost;\nusing namespace std;\nusing namespace RPN;\n\nvoid Calculator::Eval(string s)\n{\n typedef tokenizer< char_separator<char> > Tokens;\n char_separator<char> sep(\" \\t\");\n Tokens tokens(s, sep);\n\n if(!HasStack()) return;\n\n for(Tokens::iterator tok = tokens.begin();\n tok != tokens.end() && status == Continue;\n ++tok)\n {\n Commands::iterator foundCommand = commands.find(*tok);\n Operators::iterator foundOperator = operators.find(*tok);\n Variables::iterator foundVariable = variables.find(*tok);\n istringstream iss(*tok);\n Value val;\n\n \/\/ if the token is a number, push it.\n if(iss >> val)\n CurrentStack().push_front(val);\n\n \/\/ if the token is a command, perform it.\n else if(foundCommand != commands.end())\n {\n const Command& command = (*foundCommand).second;\n vector<string> args;\n args.reserve(command.NumArgs());\n\n \/\/ collect a list of tokens that will be the arguments to the\n \/\/ command.\n while(tok != tokens.end() && args.size() != command.NumArgs())\n args.push_back(*++tok);\n\n \/\/ only perform a command if we can give it enough arguments.\n if(args.size() == command.NumArgs())\n command.Perform(*this, args);\n }\n\n \/\/ if the token is an operator and that stack has at least two items,\n \/\/ then perform that operator.\n else if(foundOperator != operators.end() && StackSize() > 1)\n {\n Value b = TopmostItem(); CurrentStack().pop_front();\n Value a = TopmostItem(); CurrentStack().pop_front();\n CurrentStack().push_front((*foundOperator).second(a, b));\n }\n\n \/\/ if the token is a variable, push the variable onto the stack.\n else if(foundVariable != variables.end())\n CurrentStack().push_front((*foundVariable).second);\n\n \/\/ otherwise, if the stack has at least one item, set a new variable \n \/\/ whose name is the token and value is the top item.\n else variables[*tok] = TopmostItem();\n }\n}\n\n\/\/ displays the top item of the stack if there is one.\n\/\/ I tried to write this as a friend operator<<(), but I got errors for\n\/\/ accessing private data, which is what friend functions are supposed to be\n\/\/ able to do!\nvoid Calculator::Display() const\n{\n Print(TopmostItem());\n}\n<commit_msg>Minor beautificaiton changes.<commit_after>\/*******************************************************************************\n * Reverse Polish Notation calculator. *\n * Copyright (c) 2007-2008, Samuel Fredrickson <kinghajj@gmail.com> *\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 met: *\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 the *\n * documentation and\/or other materials provided with the distribution. *\n * *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY EXPRESS *\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY *\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *\n * SERVICES; 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 ANY WAY *\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH *\n * DAMAGE. *\n ******************************************************************************\/\n\n\/*******************************************************************************\n * Calculator.cpp - non-command Calculator methods. *\n ******************************************************************************\/\n\n#include \"rpn.h\"\n#include <boost\/tokenizer.hpp>\n#include <sstream>\nusing namespace boost;\nusing namespace std;\nusing namespace RPN;\n\nvoid Calculator::Eval(string s)\n{\n typedef tokenizer< char_separator<char> > Tokens;\n char_separator<char> sep(\" \\t\");\n Tokens tokens(s, sep);\n\n if(!HasStack()) return;\n\n for(Tokens::iterator tok = tokens.begin();\n tok != tokens.end() && status == Continue;\n ++tok)\n {\n Commands::iterator foundCommand = commands.find(*tok);\n Operators::iterator foundOperator = operators.find(*tok);\n Variables::iterator foundVariable = variables.find(*tok);\n istringstream iss(*tok);\n Value val;\n\n \/\/ if the token is a number, push it.\n if(iss >> val)\n CurrentStack().push_front(val);\n\n \/\/ if the token is a command, perform it.\n else if(foundCommand != commands.end())\n {\n const Command& command = foundCommand->second;\n vector<string> args;\n args.reserve(command.NumArgs());\n\n \/\/ collect a list of tokens that will be the arguments to the\n \/\/ command.\n while(tok != tokens.end() && args.size() != command.NumArgs())\n args.push_back(*++tok);\n\n \/\/ only perform a command if we can give it enough arguments.\n if(args.size() == command.NumArgs())\n command.Perform(*this, args);\n }\n\n \/\/ if the token is an operator and that stack has at least two items,\n \/\/ then perform that operator.\n else if(foundOperator != operators.end() && StackSize() > 1)\n {\n Value b = TopmostItem(); CurrentStack().pop_front();\n Value a = TopmostItem(); CurrentStack().pop_front();\n CurrentStack().push_front(foundOperator->second(a, b));\n }\n\n \/\/ if the token is a variable, push the variable onto the stack.\n else if(foundVariable != variables.end())\n CurrentStack().push_front(foundVariable->second);\n\n \/\/ otherwise, if the stack has at least one item, set a new variable \n \/\/ whose name is the token and value is the top item.\n else variables[*tok] = TopmostItem();\n }\n}\n\n\/\/ displays the top item of the stack if there is one.\n\/\/ I tried to write this as a friend operator<<(), but I got errors for\n\/\/ accessing private data, which is what friend functions are supposed to be\n\/\/ able to do!\nvoid Calculator::Display() const\n{\n Print(TopmostItem());\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2007-2015 QReal Research Group\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 \"pointsQueueProcessor.h\"\n\nusing namespace utils::sensorsGraph;\n\nPointsQueueProcessor::PointsQueueProcessor(const qreal viewPortHeight, const qreal leftLimit)\n\t: mMinCurrent(0)\n\t, mMaxCurrent(1)\n\t, mNextToDraw(QPointF(0, -80))\n{\n\tsetViewParams(viewPortHeight, leftLimit);\n}\n\nPointsQueueProcessor::~PointsQueueProcessor()\n{\n\tmPointsQueue.clear();\n}\n\nvoid PointsQueueProcessor::addNewValue(const qreal newValue)\n{\n\tconst qreal oldMax = mMaxCurrent;\n\tconst qreal oldMin = mMinCurrent;\n\tif (newValue > mMaxCurrent) {\n\t\tmMaxCurrent = newValue;\n\t}\n\n\tif (newValue < mMinCurrent) {\n\t\tmMinCurrent = newValue;\n\t}\n\n\tif (oldMax != mMaxCurrent || oldMin != mMinCurrent) {\n\t\trecalcPointsQueue(oldMin, oldMax, mGraphHeight);\n\t}\n\n\tmNextToDraw.setY(absoluteValueToPoint(newValue));\n\tfilterLastValues();\n\tmPointsQueue.append(QPointF(0, absoluteValueToPoint(newValue)));\n}\n\nvoid PointsQueueProcessor::recalcPointsQueue(const qreal oldMin, const qreal oldMax, const qreal oldViewHeight)\n{\n\tqreal currentValue = 0;\n\tfor (int i = 0; i < mPointsQueue.size(); i++) {\n\t\tcurrentValue = pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, oldViewHeight);\n\t\tmPointsQueue[i].setY(absoluteValueToPoint(currentValue));\n\t}\n}\n\nvoid PointsQueueProcessor::filterLastValues()\n{\n\tif (mPointsQueue.size() < 2) {\n\t\treturn;\n\t}\n\n\tconst qreal filterPixelDiff = 2;\n\tif (qAbs(mPointsQueue.at(mPointsQueue.size() - 2).y() - mPointsQueue.last().y()) < filterPixelDiff) {\n\t\tmPointsQueue.removeLast();\n\t}\n}\n\nvoid PointsQueueProcessor::makeShiftLeft(const qreal step)\n{\n\tmPointsQueue.append(latestPosition());\n\tfor (int i = 0; i < mPointsQueue.size(); i++) {\n\t\tmPointsQueue[i].setX(mPointsQueue[i].x() - step);\n\t\tif (mPointsQueue[i].x() < mLeftLimit) {\n\t\t\tmPointsQueue.removeAt(i--);\n\t\t}\n\t}\n}\n\nqreal PointsQueueProcessor::absoluteValueToPoint(const qreal value) const\n{\n\tconst int verticalBounds = 10;\n\tconst int invertCoordSys = -1;\n\treturn ((value - mMinCurrent) \/ (mMaxCurrent - mMinCurrent) * mGraphHeight + verticalBounds) * invertCoordSys;\n}\n\nqreal PointsQueueProcessor::pointToAbsoluteValue(const qreal yValue) const\n{\n\treturn pointToAbsoluteValue(yValue, mMinCurrent, mMaxCurrent, mGraphHeight);\n}\n\nqreal PointsQueueProcessor::pointToAbsoluteValue(const qreal yValue, const qreal minValue\n\t\t, const qreal maxValue, const qreal graphHeight) const\n{\n\treturn (((maxValue - minValue) * (-yValue - 10)) \/ graphHeight) + minValue;\n}\n\nvoid PointsQueueProcessor::clearData()\n{\n\tmMinCurrent = 0;\n\tmMaxCurrent = 1;\n\tmPointsQueue.clear();\n}\n\nQPointF PointsQueueProcessor::latestPosition() const\n{\n\treturn mNextToDraw;\n}\n\nqreal PointsQueueProcessor::latestValue() const\n{\n\treturn pointToAbsoluteValue(mNextToDraw.y(), mMinCurrent, mMaxCurrent, mGraphHeight);\n}\n\nconst QList<QPointF> &PointsQueueProcessor::pointsBase() const\n{\n\treturn mPointsQueue;\n}\n\nvoid PointsQueueProcessor::checkPeaks()\n{\n\tconst qreal oldMin = mMinCurrent;\n\tconst qreal oldMax = mMaxCurrent;\n\n\tmMaxCurrent = std::numeric_limits<qreal>::min();\n\tmMinCurrent = std::numeric_limits<qreal>::max();\n\n\tfor (int i = 0; i < mPointsQueue.size(); i++) {\n\t\tif (pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, mGraphHeight) > mMaxCurrent) {\n\t\t\tmMaxCurrent = pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, mGraphHeight);\n\t\t}\n\t\tif (pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, mGraphHeight) < mMinCurrent) {\n\t\t\tmMinCurrent = pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, mGraphHeight);\n\t\t}\n\t}\n\n\trecalcPointsQueue(oldMin, oldMax, mGraphHeight);\n}\n\nQPointF PointsQueueProcessor::pointOfVerticalIntersection(const QPointF &position) const\n{\n\tif (mPointsQueue.isEmpty())\n\t\treturn QPointF(0, 0);\n\tconst qreal accuracyCoefficient = 2; \/\/ accuracy = diameter * accCoefficient\n\tconst qreal diameter = (mPointsQueue.last().x() - mPointsQueue.first().x()) \/ mPointsQueue.size();\n\n\tQPointF result;\n\tint leftBound = 0;\n\tint rightBound = mPointsQueue.size() - 1;\n\twhile (leftBound < rightBound) {\n\t\tint middleIndex = (rightBound + leftBound) \/ 2;\n\t\tresult = mPointsQueue.at(middleIndex);\n\t\tif (qAbs(result.x() - position.x()) < diameter * accuracyCoefficient) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (position.x() < result.x()) {\n\t\t\trightBound = middleIndex - 1;\n\t\t}\n\n\t\tif (position.x() > result.x()) {\n\t\t\tleftBound = middleIndex + 1;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nvoid PointsQueueProcessor::setViewParams(const qreal viewPortHeight, const qreal leftLimit)\n{\n\tconst qreal oldViewHeight = mGraphHeight;\n\tmGraphHeight = viewPortHeight;\n\trecalcPointsQueue(mMinCurrent, mMaxCurrent, oldViewHeight);\n\tmLeftLimit = leftLimit;\n}\n\nqreal PointsQueueProcessor::minLimit() const\n{\n\treturn mMinCurrent;\n}\n\nqreal PointsQueueProcessor::maxLimit() const\n{\n\treturn mMaxCurrent;\n}\n<commit_msg>Fixed #1636<commit_after>\/* Copyright 2007-2015 QReal Research Group\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 \"pointsQueueProcessor.h\"\n\nusing namespace utils::sensorsGraph;\n\nPointsQueueProcessor::PointsQueueProcessor(const qreal viewPortHeight, const qreal leftLimit)\n\t: mMinCurrent(0)\n\t, mMaxCurrent(1)\n\t, mNextToDraw(QPointF(0, -80))\n{\n\tsetViewParams(viewPortHeight, leftLimit);\n}\n\nPointsQueueProcessor::~PointsQueueProcessor()\n{\n\tmPointsQueue.clear();\n}\n\nvoid PointsQueueProcessor::addNewValue(const qreal newValue)\n{\n\tconst qreal oldMax = mMaxCurrent;\n\tconst qreal oldMin = mMinCurrent;\n\tif (newValue > mMaxCurrent) {\n\t\tmMaxCurrent = newValue;\n\t}\n\n\tif (newValue < mMinCurrent) {\n\t\tmMinCurrent = newValue;\n\t}\n\n\tif (oldMax != mMaxCurrent || oldMin != mMinCurrent) {\n\t\trecalcPointsQueue(oldMin, oldMax, mGraphHeight);\n\t}\n\n\tmNextToDraw.setY(absoluteValueToPoint(newValue));\n\tfilterLastValues();\n\tmPointsQueue.append(QPointF(0, absoluteValueToPoint(newValue)));\n}\n\nvoid PointsQueueProcessor::recalcPointsQueue(const qreal oldMin, const qreal oldMax, const qreal oldViewHeight)\n{\n\tqreal currentValue = 0;\n\tfor (int i = 0; i < mPointsQueue.size(); i++) {\n\t\tcurrentValue = pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, oldViewHeight);\n\t\tmPointsQueue[i].setY(absoluteValueToPoint(currentValue));\n\t}\n}\n\nvoid PointsQueueProcessor::filterLastValues()\n{\n\tif (mPointsQueue.size() < 2) {\n\t\treturn;\n\t}\n\n\tconst qreal filterPixelDiff = 2;\n\tif (qAbs(mPointsQueue.at(mPointsQueue.size() - 2).y() - mPointsQueue.last().y()) < filterPixelDiff) {\n\t\tmPointsQueue.removeLast();\n\t}\n}\n\nvoid PointsQueueProcessor::makeShiftLeft(const qreal step)\n{\n\tmPointsQueue.append(latestPosition());\n\tfor (int i = 0; i < mPointsQueue.size(); i++) {\n\t\tmPointsQueue[i].setX(mPointsQueue[i].x() - step);\n\t\tif (mPointsQueue[i].x() < mLeftLimit) {\n\t\t\tmPointsQueue.removeAt(i--);\n\t\t}\n\t}\n}\n\nqreal PointsQueueProcessor::absoluteValueToPoint(const qreal value) const\n{\n\tconst int verticalBounds = 10;\n\tconst int invertCoordSys = -1;\n\tif (qFuzzyCompare(mMaxCurrent, mMinCurrent)) {\n\t\treturn mNextToDraw.y();\n\t}\n\n\treturn ((value - mMinCurrent) \/ (mMaxCurrent - mMinCurrent) * mGraphHeight + verticalBounds) * invertCoordSys;\n}\n\nqreal PointsQueueProcessor::pointToAbsoluteValue(const qreal yValue) const\n{\n\treturn pointToAbsoluteValue(yValue, mMinCurrent, mMaxCurrent, mGraphHeight);\n}\n\nqreal PointsQueueProcessor::pointToAbsoluteValue(const qreal yValue, const qreal minValue\n\t\t, const qreal maxValue, const qreal graphHeight) const\n{\n\treturn (((maxValue - minValue) * (-yValue - 10)) \/ graphHeight) + minValue;\n}\n\nvoid PointsQueueProcessor::clearData()\n{\n\tmMinCurrent = 0;\n\tmMaxCurrent = 1;\n\tmPointsQueue.clear();\n}\n\nQPointF PointsQueueProcessor::latestPosition() const\n{\n\treturn mNextToDraw;\n}\n\nqreal PointsQueueProcessor::latestValue() const\n{\n\treturn pointToAbsoluteValue(mNextToDraw.y(), mMinCurrent, mMaxCurrent, mGraphHeight);\n}\n\nconst QList<QPointF> &PointsQueueProcessor::pointsBase() const\n{\n\treturn mPointsQueue;\n}\n\nvoid PointsQueueProcessor::checkPeaks()\n{\n\tconst qreal oldMin = mMinCurrent;\n\tconst qreal oldMax = mMaxCurrent;\n\n\tmMaxCurrent = std::numeric_limits<qreal>::min();\n\tmMinCurrent = std::numeric_limits<qreal>::max();\n\n\tfor (int i = 0; i < mPointsQueue.size(); i++) {\n\t\tif (pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, mGraphHeight) > mMaxCurrent) {\n\t\t\tmMaxCurrent = pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, mGraphHeight);\n\t\t}\n\t\tif (pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, mGraphHeight) < mMinCurrent) {\n\t\t\tmMinCurrent = pointToAbsoluteValue(mPointsQueue[i].y(), oldMin, oldMax, mGraphHeight);\n\t\t}\n\t}\n\n\trecalcPointsQueue(oldMin, oldMax, mGraphHeight);\n}\n\nQPointF PointsQueueProcessor::pointOfVerticalIntersection(const QPointF &position) const\n{\n\tif (mPointsQueue.isEmpty())\n\t\treturn QPointF(0, 0);\n\tconst qreal accuracyCoefficient = 2; \/\/ accuracy = diameter * accCoefficient\n\tconst qreal diameter = (mPointsQueue.last().x() - mPointsQueue.first().x()) \/ mPointsQueue.size();\n\n\tQPointF result;\n\tint leftBound = 0;\n\tint rightBound = mPointsQueue.size() - 1;\n\twhile (leftBound < rightBound) {\n\t\tint middleIndex = (rightBound + leftBound) \/ 2;\n\t\tresult = mPointsQueue.at(middleIndex);\n\t\tif (qAbs(result.x() - position.x()) < diameter * accuracyCoefficient) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (position.x() < result.x()) {\n\t\t\trightBound = middleIndex - 1;\n\t\t}\n\n\t\tif (position.x() > result.x()) {\n\t\t\tleftBound = middleIndex + 1;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nvoid PointsQueueProcessor::setViewParams(const qreal viewPortHeight, const qreal leftLimit)\n{\n\tconst qreal oldViewHeight = mGraphHeight;\n\tmGraphHeight = viewPortHeight;\n\trecalcPointsQueue(mMinCurrent, mMaxCurrent, oldViewHeight);\n\tmLeftLimit = leftLimit;\n}\n\nqreal PointsQueueProcessor::minLimit() const\n{\n\treturn mMinCurrent;\n}\n\nqreal PointsQueueProcessor::maxLimit() const\n{\n\treturn mMaxCurrent;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * (C) Copyright 2014 Kurento (http:\/\/kurento.org\/)\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#include \"logging.hpp\"\n\n#include <gst\/gst.h>\n\n#include <boost\/format.hpp>\n#include <boost\/log\/sinks\/text_file_backend.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/log\/expressions.hpp>\n#include <boost\/log\/attributes.hpp>\n#include <boost\/log\/sinks.hpp>\n#include <boost\/log\/sources\/channel_feature.hpp>\n#include <boost\/log\/sources\/channel_logger.hpp>\n#include <boost\/log\/support\/date_time.hpp>\n#include <boost\/log\/utility\/manipulators\/add_value.hpp>\n#include <sys\/types.h>\n#include <unistd.h>\n\n\nnamespace logging = boost::log;\nnamespace attrs = boost::log::attributes;\nnamespace src = boost::log::sources;\nnamespace sinks = boost::log::sinks;\nnamespace expr = boost::log::expressions;\nnamespace keywords = boost::log::keywords;\n\ntypedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;\n\nnamespace kurento\n{\n\n\/\/ ----------------------------------------------------------------------------\n\nGST_DEBUG_CATEGORY_STATIC (kms_glib_debug);\n\nstatic GstDebugLevel\ng_log_level_to_gst_debug_level (GLogLevelFlags log_level)\n{\n switch (log_level & G_LOG_LEVEL_MASK) {\n case G_LOG_LEVEL_ERROR: return GST_LEVEL_ERROR;\n case G_LOG_LEVEL_CRITICAL: return GST_LEVEL_ERROR;\n case G_LOG_LEVEL_WARNING: return GST_LEVEL_WARNING;\n case G_LOG_LEVEL_MESSAGE: return GST_LEVEL_FIXME;\n case G_LOG_LEVEL_INFO: return GST_LEVEL_INFO;\n case G_LOG_LEVEL_DEBUG: return GST_LEVEL_DEBUG;\n default: return GST_LEVEL_DEBUG;\n }\n}\n\n\/*\n * Based on the Glib 2.48.2 default message handler, g_log_default_handler()\n * https:\/\/github.com\/GNOME\/glib\/blob\/2.48.2\/glib\/gmessages.c#L1429\n *\n * NOTE: In Glib 2.50 they added a new logging mode, \"structured logging\", that\n * maybe we need to check out in the future.\n *\/\n\/* these are emitted by the default log handler *\/\n#define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)\n\/* these are filtered by G_MESSAGES_DEBUG by the default log handler *\/\n#define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)\nstatic void\nkms_glib_log_handler (const gchar *log_domain,\n GLogLevelFlags log_level,\n const gchar *message,\n gpointer unused_data)\n{\n const gchar *domains;\n\n if ((log_level & DEFAULT_LEVELS) || (log_level >> G_LOG_LEVEL_USER_SHIFT)) {\n goto emit;\n }\n\n domains = g_getenv (\"G_MESSAGES_DEBUG\");\n if (((log_level & INFO_LEVELS) == 0) ||\n domains == NULL ||\n (strcmp (domains, \"all\") != 0 && (!log_domain || !strstr (domains, log_domain))))\n {\n return;\n }\n\n emit:\n \/* we can be called externally with recursion for whatever reason *\/\n if (log_level & G_LOG_FLAG_RECURSION)\n {\n \/\/_g_log_fallback_handler (log_domain, log_level, message, unused_data);\n return;\n }\n\n\n \/\/ Forward Glib log messages through GStreamer logging\n\n GstDebugCategory *category = kms_glib_debug;\n GstDebugLevel level = g_log_level_to_gst_debug_level (log_level);\n const gchar *file = log_domain;\n const gchar *function = \"\";\n gint line = 0;\n GObject *object = NULL;\n\n if (!message) {\n gst_debug_log (category, level, file, function, line, object, \"%s\",\n \"(NULL) message\");\n } else {\n gst_debug_log (category, level, file, function, line, object, \"%s\",\n message);\n }\n}\n\nvoid\nkms_init_logging ()\n{\n \/\/ Forward Glib log messages through GStreamer logging\n GST_DEBUG_CATEGORY_INIT (kms_glib_debug, \"glib\", 0, \"Glib logging\");\n g_log_set_default_handler (kms_glib_log_handler, NULL);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n\/* kurento logging sinks *\/\nboost::shared_ptr< sink_t > system_sink;\n\nstatic std::string\ndebug_object (GObject *object)\n{\n if (object == nullptr) {\n return \"\";\n }\n\n if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s:%s> \");\n fmt %\n (GST_OBJECT_PARENT(object) != nullptr\n ? GST_OBJECT_NAME(GST_OBJECT_PARENT(object))\n : \"''\") %\n GST_OBJECT_NAME(object);\n return fmt.str();\n }\n\n if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s> \");\n fmt % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (G_IS_OBJECT (object) ) {\n boost::format fmt (\"<%s@%p> \");\n fmt % G_OBJECT_TYPE_NAME (object) % object;\n return fmt.str();\n }\n\n boost::format fmt (\"<%p> \");\n fmt % object;\n return fmt.str();\n}\n\nstatic std::string\nexpand_string (std::string str, int len)\n{\n std::string ret = str;\n int sp = len - str.size ();\n\n for (int i = sp; i > 0; i--) {\n str.append (\" \");\n }\n\n return str;\n}\n\nstatic severity_level\ngst_debug_level_to_severity_level (GstDebugLevel level)\n{\n switch (level) {\n case GST_LEVEL_ERROR: return error;\n case GST_LEVEL_WARNING: return warning;\n case GST_LEVEL_FIXME: return fixme;\n case GST_LEVEL_INFO: return info;\n case GST_LEVEL_DEBUG: return debug;\n case GST_LEVEL_LOG: return log;\n case GST_LEVEL_TRACE: return trace;\n default: return undefined;\n }\n}\n\nstatic void\nkms_log_function (GstDebugCategory *category, GstDebugLevel level,\n const gchar *file,\n const gchar *function, gint line, GObject *object,\n GstDebugMessage *message, gpointer user_data) G_GNUC_NO_INSTRUMENT;\n\nstatic void\nkms_log_function (GstDebugCategory *category, GstDebugLevel level,\n const gchar *file,\n const gchar *function, gint line, GObject *object,\n GstDebugMessage *message, gpointer user_data)\n{\n if (level > gst_debug_category_get_threshold (category) ) {\n return;\n }\n\n severity_level severity = gst_debug_level_to_severity_level (level);\n\n if (severity == undefined) {\n return;\n }\n\n BOOST_LOG_SEV (system_logger::get(), severity) <<\n logging::add_value (\"Category\", expand_string (category->name, 25) ) <<\n logging::add_value (\"FileName\",\n boost::filesystem::path (file).filename().string() ) <<\n logging::add_value (\"Line\", line) <<\n logging::add_value (\"Function\", function) <<\n logging::add_value (\"GObject\", debug_object (object) ) <<\n gst_debug_message_get (message);\n}\n\nvoid init_file_collecting (boost::shared_ptr< sink_t > sink,\n const std::string &path,\n int fileSize,\n int fileNumber)\n{\n sink->locked_backend()->set_file_collector (sinks::file::make_collector (\n keywords::target = path,\n keywords::max_size = (fileSize * fileNumber) * 1024 * 1024,\n keywords::min_free_space = fileSize * 1024 * 1024\n ) );\n}\n\n\/* The formatting logic for the severity level *\/\ntemplate< typename CharT, typename TraitsT >\ninline std::basic_ostream< CharT, TraitsT > &operator<< (\n std::basic_ostream< CharT, TraitsT > &strm, severity_level lvl)\n{\n static const char *const str[] = {\n \" error\",\n \"warning\",\n \" fixme\",\n \" info\",\n \" debug\",\n \" log\",\n \" trace\",\n \"unknown\"\n };\n\n if (static_cast< std::size_t > (lvl) < (sizeof (str) \/ sizeof (*str) ) ) {\n strm << str[lvl];\n } else {\n strm << static_cast< int > (lvl);\n }\n\n return strm;\n}\n\nstatic void\nsystem_formatter (logging::record_view const &rec,\n logging::formatting_ostream &strm)\n{\n auto date_time_formatter = expr::stream\n << expr::format_date_time< boost::posix_time::ptime > (\"TimeStamp\",\n \"%Y-%m-%dT%H:%M:%S,%f\");\n date_time_formatter (rec, strm) << \" \";\n strm << std::to_string (getpid() ) << \" \";\n strm << logging::extract< attrs::current_thread_id::value_type > (\"ThreadID\",\n rec) << \" \";\n strm << logging::extract< severity_level > (\"Severity\", rec) << \" \";\n strm << logging::extract< std::string > (\"Category\", rec) << \" \";\n strm << logging::extract< std::string > (\"FileName\", rec) << \":\";\n strm << logging::extract< int > (\"Line\", rec) << \" \";\n strm << logging::extract< std::string > (\"Function\", rec) << \"() \";\n strm << logging::extract< std::string > (\"GObject\", rec) << \" \";\n strm << rec[expr::smessage];\n}\n\nbool\nkms_init_logging_files (const std::string &path, int fileSize, int fileNumber)\n{\n gst_debug_remove_log_function (gst_debug_log_default);\n gst_debug_add_log_function(kms_log_function, nullptr, nullptr);\n\n boost::shared_ptr< logging::core > core = logging::core::get();\n\n boost::shared_ptr< sinks::text_file_backend > backend =\n boost::make_shared< sinks::text_file_backend > (\n keywords::file_name = path + \"\/\" + \"%Y-%m-%dT%H%M%S.%5N.pid\" +\n std::to_string (getpid() ) + \".log\",\n keywords::rotation_size = fileSize * 1024 * 1024,\n keywords::time_based_rotation = sinks::file::rotation_at_time_point (0, 0, 0)\n );\n\n \/* Enable auto-flushing after each log record written *\/\n backend->auto_flush (true);\n\n \/* Wrap it into the frontend and register in the core. *\/\n \/* The backend requires synchronization in the frontend. *\/\n system_sink = boost::shared_ptr< sink_t > (new sink_t (backend) );\n\n \/*Set up filter to pass only records that have the necessary attributes *\/\n system_sink->set_filter (\n expr::has_attr< std::string > (\"Channel\") &&\n expr::attr< std::string > (\"Channel\") == \"system\"\n );\n\n \/* Set up where the rotated files will be stored *\/\n init_file_collecting (system_sink, path, fileSize, fileNumber);\n\n \/* Upon restart, scan the directory for files matching the file_name pattern *\/\n system_sink->locked_backend()->scan_for_files();\n\n core->add_sink (system_sink);\n\n system_sink->set_formatter (&system_formatter);\n\n return true;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n} \/* kurento *\/\n<commit_msg>Logging: Fix NULL reference (use default value)<commit_after>\/*\n * (C) Copyright 2014 Kurento (http:\/\/kurento.org\/)\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#include \"logging.hpp\"\n\n#include <gst\/gst.h>\n\n#include <boost\/format.hpp>\n#include <boost\/log\/sinks\/text_file_backend.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/log\/expressions.hpp>\n#include <boost\/log\/attributes.hpp>\n#include <boost\/log\/sinks.hpp>\n#include <boost\/log\/sources\/channel_feature.hpp>\n#include <boost\/log\/sources\/channel_logger.hpp>\n#include <boost\/log\/support\/date_time.hpp>\n#include <boost\/log\/utility\/manipulators\/add_value.hpp>\n#include <sys\/types.h>\n#include <unistd.h>\n\n\nnamespace logging = boost::log;\nnamespace attrs = boost::log::attributes;\nnamespace src = boost::log::sources;\nnamespace sinks = boost::log::sinks;\nnamespace expr = boost::log::expressions;\nnamespace keywords = boost::log::keywords;\n\ntypedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;\n\nnamespace kurento\n{\n\n\/\/ ----------------------------------------------------------------------------\n\nGST_DEBUG_CATEGORY_STATIC (kms_glib_debug);\n\nstatic GstDebugLevel\ng_log_level_to_gst_debug_level (GLogLevelFlags log_level)\n{\n switch (log_level & G_LOG_LEVEL_MASK) {\n case G_LOG_LEVEL_ERROR: return GST_LEVEL_ERROR;\n case G_LOG_LEVEL_CRITICAL: return GST_LEVEL_ERROR;\n case G_LOG_LEVEL_WARNING: return GST_LEVEL_WARNING;\n case G_LOG_LEVEL_MESSAGE: return GST_LEVEL_FIXME;\n case G_LOG_LEVEL_INFO: return GST_LEVEL_INFO;\n case G_LOG_LEVEL_DEBUG: return GST_LEVEL_DEBUG;\n default: return GST_LEVEL_DEBUG;\n }\n}\n\n\/*\n * Based on the Glib 2.48.2 default message handler, g_log_default_handler()\n * https:\/\/github.com\/GNOME\/glib\/blob\/2.48.2\/glib\/gmessages.c#L1429\n *\n * NOTE: In Glib 2.50 they added a new logging mode, \"structured logging\", that\n * maybe we need to check out in the future.\n *\/\n\/* these are emitted by the default log handler *\/\n#define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)\n\/* these are filtered by G_MESSAGES_DEBUG by the default log handler *\/\n#define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)\nstatic void\nkms_glib_log_handler (const gchar *log_domain,\n GLogLevelFlags log_level,\n const gchar *message,\n gpointer unused_data)\n{\n const gchar *domains;\n\n if ((log_level & DEFAULT_LEVELS) || (log_level >> G_LOG_LEVEL_USER_SHIFT)) {\n goto emit;\n }\n\n domains = g_getenv (\"G_MESSAGES_DEBUG\");\n if (((log_level & INFO_LEVELS) == 0) ||\n domains == NULL ||\n (strcmp (domains, \"all\") != 0 && (!log_domain || !strstr (domains, log_domain))))\n {\n return;\n }\n\n emit:\n \/* we can be called externally with recursion for whatever reason *\/\n if (log_level & G_LOG_FLAG_RECURSION)\n {\n \/\/_g_log_fallback_handler (log_domain, log_level, message, unused_data);\n return;\n }\n\n\n \/\/ Forward Glib log messages through GStreamer logging\n\n GstDebugCategory *category = kms_glib_debug;\n GstDebugLevel level = g_log_level_to_gst_debug_level (log_level);\n const gchar *file = log_domain ? log_domain : \"(NULL domain)\";\n const gchar *function = \"\";\n gint line = 0;\n GObject *object = NULL;\n\n if (!message) {\n gst_debug_log (category, level, file, function, line, object, \"%s\",\n \"(NULL message)\");\n } else {\n gst_debug_log (category, level, file, function, line, object, \"%s\",\n message);\n }\n}\n\nvoid\nkms_init_logging ()\n{\n \/\/ Forward Glib log messages through GStreamer logging\n GST_DEBUG_CATEGORY_INIT (kms_glib_debug, \"glib\", 0, \"Glib logging\");\n g_log_set_default_handler (kms_glib_log_handler, NULL);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n\/* kurento logging sinks *\/\nboost::shared_ptr< sink_t > system_sink;\n\nstatic std::string\ndebug_object (GObject *object)\n{\n if (object == nullptr) {\n return \"\";\n }\n\n if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s:%s> \");\n fmt %\n (GST_OBJECT_PARENT(object) != nullptr\n ? GST_OBJECT_NAME(GST_OBJECT_PARENT(object))\n : \"''\") %\n GST_OBJECT_NAME(object);\n return fmt.str();\n }\n\n if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s> \");\n fmt % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (G_IS_OBJECT (object) ) {\n boost::format fmt (\"<%s@%p> \");\n fmt % G_OBJECT_TYPE_NAME (object) % object;\n return fmt.str();\n }\n\n boost::format fmt (\"<%p> \");\n fmt % object;\n return fmt.str();\n}\n\nstatic std::string\nexpand_string (std::string str, int len)\n{\n std::string ret = str;\n int sp = len - str.size ();\n\n for (int i = sp; i > 0; i--) {\n str.append (\" \");\n }\n\n return str;\n}\n\nstatic severity_level\ngst_debug_level_to_severity_level (GstDebugLevel level)\n{\n switch (level) {\n case GST_LEVEL_ERROR: return error;\n case GST_LEVEL_WARNING: return warning;\n case GST_LEVEL_FIXME: return fixme;\n case GST_LEVEL_INFO: return info;\n case GST_LEVEL_DEBUG: return debug;\n case GST_LEVEL_LOG: return log;\n case GST_LEVEL_TRACE: return trace;\n default: return undefined;\n }\n}\n\nstatic void\nkms_log_function (GstDebugCategory *category, GstDebugLevel level,\n const gchar *file,\n const gchar *function, gint line, GObject *object,\n GstDebugMessage *message, gpointer user_data) G_GNUC_NO_INSTRUMENT;\n\nstatic void\nkms_log_function (GstDebugCategory *category, GstDebugLevel level,\n const gchar *file,\n const gchar *function, gint line, GObject *object,\n GstDebugMessage *message, gpointer user_data)\n{\n if (level > gst_debug_category_get_threshold (category) ) {\n return;\n }\n\n severity_level severity = gst_debug_level_to_severity_level (level);\n\n if (severity == undefined) {\n return;\n }\n\n BOOST_LOG_SEV (system_logger::get(), severity) <<\n logging::add_value (\"Category\", expand_string (category->name, 25) ) <<\n logging::add_value (\"FileName\",\n boost::filesystem::path (file).filename().string() ) <<\n logging::add_value (\"Line\", line) <<\n logging::add_value (\"Function\", function) <<\n logging::add_value (\"GObject\", debug_object (object) ) <<\n gst_debug_message_get (message);\n}\n\nvoid init_file_collecting (boost::shared_ptr< sink_t > sink,\n const std::string &path,\n int fileSize,\n int fileNumber)\n{\n sink->locked_backend()->set_file_collector (sinks::file::make_collector (\n keywords::target = path,\n keywords::max_size = (fileSize * fileNumber) * 1024 * 1024,\n keywords::min_free_space = fileSize * 1024 * 1024\n ) );\n}\n\n\/* The formatting logic for the severity level *\/\ntemplate< typename CharT, typename TraitsT >\ninline std::basic_ostream< CharT, TraitsT > &operator<< (\n std::basic_ostream< CharT, TraitsT > &strm, severity_level lvl)\n{\n static const char *const str[] = {\n \" error\",\n \"warning\",\n \" fixme\",\n \" info\",\n \" debug\",\n \" log\",\n \" trace\",\n \"unknown\"\n };\n\n if (static_cast< std::size_t > (lvl) < (sizeof (str) \/ sizeof (*str) ) ) {\n strm << str[lvl];\n } else {\n strm << static_cast< int > (lvl);\n }\n\n return strm;\n}\n\nstatic void\nsystem_formatter (logging::record_view const &rec,\n logging::formatting_ostream &strm)\n{\n auto date_time_formatter = expr::stream\n << expr::format_date_time< boost::posix_time::ptime > (\"TimeStamp\",\n \"%Y-%m-%dT%H:%M:%S,%f\");\n date_time_formatter (rec, strm) << \" \";\n strm << std::to_string (getpid() ) << \" \";\n strm << logging::extract< attrs::current_thread_id::value_type > (\"ThreadID\",\n rec) << \" \";\n strm << logging::extract< severity_level > (\"Severity\", rec) << \" \";\n strm << logging::extract< std::string > (\"Category\", rec) << \" \";\n strm << logging::extract< std::string > (\"FileName\", rec) << \":\";\n strm << logging::extract< int > (\"Line\", rec) << \" \";\n strm << logging::extract< std::string > (\"Function\", rec) << \"() \";\n strm << logging::extract< std::string > (\"GObject\", rec) << \" \";\n strm << rec[expr::smessage];\n}\n\nbool\nkms_init_logging_files (const std::string &path, int fileSize, int fileNumber)\n{\n gst_debug_remove_log_function (gst_debug_log_default);\n gst_debug_add_log_function(kms_log_function, nullptr, nullptr);\n\n boost::shared_ptr< logging::core > core = logging::core::get();\n\n boost::shared_ptr< sinks::text_file_backend > backend =\n boost::make_shared< sinks::text_file_backend > (\n keywords::file_name = path + \"\/\" + \"%Y-%m-%dT%H%M%S.%5N.pid\" +\n std::to_string (getpid() ) + \".log\",\n keywords::rotation_size = fileSize * 1024 * 1024,\n keywords::time_based_rotation = sinks::file::rotation_at_time_point (0, 0, 0)\n );\n\n \/* Enable auto-flushing after each log record written *\/\n backend->auto_flush (true);\n\n \/* Wrap it into the frontend and register in the core. *\/\n \/* The backend requires synchronization in the frontend. *\/\n system_sink = boost::shared_ptr< sink_t > (new sink_t (backend) );\n\n \/*Set up filter to pass only records that have the necessary attributes *\/\n system_sink->set_filter (\n expr::has_attr< std::string > (\"Channel\") &&\n expr::attr< std::string > (\"Channel\") == \"system\"\n );\n\n \/* Set up where the rotated files will be stored *\/\n init_file_collecting (system_sink, path, fileSize, fileNumber);\n\n \/* Upon restart, scan the directory for files matching the file_name pattern *\/\n system_sink->locked_backend()->scan_for_files();\n\n core->add_sink (system_sink);\n\n system_sink->set_formatter (&system_formatter);\n\n return true;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n} \/* kurento *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"CurlClient.h\"\n\n#include \"BasicAuth.h\"\n\n#include <cstdio>\n#include <cstring>\n#include <cassert>\n#include <cctype>\n#include <iostream>\n#include <pthread.h>\n\nusing namespace std;\n\n#include <curl\/curl.h>\n\nclass CurlClient : public HTTPClient {\n public:\n CurlClient(const std::string & _interface, const std::string & _user_agent, bool _enable_cookies = true, bool _enable_keepalive = true)\n : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive),\n interface_name(_interface)\n {\n \n }\n CurlClient(const CurlClient & other) : HTTPClient(other),\n\t\t\t\t\t interface_name(other.interface_name)\n {\n \n }\n\n ~CurlClient() {\n if (curl) curl_easy_cleanup(curl);\n }\n\n HTTPResponse request(const HTTPRequest & req, const Authorization & auth) override;\n\n void clearCookies() override;\n \n protected:\n bool initialize();\n\n private:\n bool handleProgress(double dltotal, double dlnow, double ultotal, double ulnow);\n \n static size_t write_data_func(void * buffer, size_t size, size_t nmemb, void *userp);\n static size_t headers_func(void * buffer, size_t size, size_t nmemb, void *userp);\n static int progress_func(void * clientp, double dltotal, double dlnow, double ultotal, double ulnow);\n\n std::string interface_name;\n CURL * curl = 0;\n};\n\nbool\nCurlClient::initialize() {\n if (curl) {\n curl_easy_reset(curl);\n data_out.clear();\n data_out.shrink_to_fit();\n } else {\n curl = curl_easy_init();\n }\n \n assert(curl);\n\n if (curl) {\n#ifndef WIN32\n if (!interface_name.empty()) {\n int r = curl_easy_setopt(curl, CURLOPT_INTERFACE, interface_name.c_str());\n assert(r != CURLE_INTERFACE_FAILED);\n }\n#endif\n curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent.c_str());\n curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);\n curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_func);\n curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_func);\n curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headers_func);\n curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this);\n curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);\n curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);\n curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 600);\n \/\/ curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);\n if (!enable_keepalive) {\n curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);\n curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);\n }\n if (!cookie_jar.empty()) {\n curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_jar.c_str());\n curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_jar.c_str());\n } else if (enable_cookies) {\n curl_easy_setopt(curl, CURLOPT_COOKIEFILE, \"\");\n }\n \/\/ curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, 10);\n\n }\n\n return curl != 0;\n}\n\nHTTPResponse\nCurlClient::request(const HTTPRequest & req, const Authorization & auth) {\n if (req.getURI().empty()) {\n return HTTPResponse(0, \"empty URI\");\n }\n if (!initialize()) {\n return HTTPResponse(0, \"Unable to initialize client\");\n }\n\n \/\/ string ascii_uri = encodeIDN(uri);\n \/\/ if (ascii_uri.empty()) {\n \/\/ cerr << \"failed to convert url \" << uri << endl;\n \/\/ assert(0);\n \/\/ }\n \n struct curl_slist * headers = 0;\n if (req.getType() == HTTPRequest::POST) {\n data_out = req.getContent();\n\n if (!req.getContentType().empty()) {\n string h = \"Content-type: \";\n h += req.getContentType();\n headers = curl_slist_append(headers, h.c_str());\n }\n } else {\n data_out.clear();\n }\n\n const BasicAuth * basic = dynamic_cast<const BasicAuth *>(&auth);\n if (basic) {\n string s = basic->getUsername();\n s += ':';\n s += basic->getPassword();\n curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n curl_easy_setopt(curl, CURLOPT_USERPWD, s.c_str());\n } else {\n string auth_header = auth.createHeader();\n if (!auth_header.empty()) {\n string s = auth.getHeaderName();\n s += \": \";\n s += auth_header;\n headers = curl_slist_append(headers, s.c_str());\n }\n }\n\n for (auto & hd : req.getHeaders()) {\n string s = hd.first;\n s += \": \";\n s += hd.second;\n headers = curl_slist_append(headers, s.c_str());\n }\n\n HTTPResponse response;\n response.setCallback(callback);\n \n if (req.getType() == HTTPRequest::POST) {\n curl_easy_setopt(curl, CURLOPT_POST, 1);\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data_out.data());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data_out.size());\n } else {\n curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);\n }\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, req.getFollowLocation());\n curl_easy_setopt(curl, CURLOPT_URL, req.getURI().c_str());\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);\n curl_easy_setopt(curl, CURLOPT_TIMEOUT, req.getTimeout());\n curl_easy_setopt(curl, CURLOPT_HEADERDATA, &response);\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);\n if (!cookie_jar.empty()) {\n curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_jar.c_str());\n curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_jar.c_str());\n }\n\n CURLcode res = curl_easy_perform(curl);\n if (res == 0) {\n unsigned long a = 0;\n if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &a) == CURLE_OK) {\n response.setResultCode(a);\n }\n if (!req.getFollowLocation()) {\n char * ptr = 0;\n curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &ptr);\n if (ptr) {\n\tresponse.setRedirectUrl(ptr);\n }\n }\n } else {\n response.setErrorText(curl_easy_strerror(res));\n }\n\n if (headers) {\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, 0);\n curl_slist_free_all(headers);\n }\n \n return response;\n}\n\nbool\nCurlClient::handleProgress(double dltotal, double dlnow, double ultotal, double ulnow) {\n if (callback) {\n return callback->onIdle(true);\n }\n return true;\n}\n\nsize_t\nCurlClient::write_data_func(void * buffer, size_t size, size_t nmemb, void * userp) {\n size_t s = size * nmemb;\n#if 0\n CurlClient * client = static_cast<CurlClient *>(userp);\n assert(client);\n if (client->addToData((int)s, (char *)buffer)) {\n return s;\n } else {\n return 0;\n }\n#else\n \/\/ Content-Type: multipart\/x-mixed-replace; boundary=myboundary\n\t\t\t\t\t \n HTTPResponse * response = static_cast<HTTPResponse *>(userp);\n assert(response);\n if (response->getCallback()) {\n if (response->getCallback()->handleChunk(s, (const char *)buffer)) {\n return s;\n } else {\n return 0;\n }\n } else {\n response->appendContent(string((const char *)buffer, s));\n return s;\n }\n#endif\n}\n\n\/\/ bool\n\/\/ CurlClient::addToData(size_t len, const char * data) {\n\/\/ if (callback) {\n\/\/ return callback->handleChunk(len, data);\n\/\/ } else {\n\/\/ data_in += string(data, len);\n\/\/ return true;\n\/\/ } \n\/\/ }\n\nsize_t\nCurlClient::headers_func(void * buffer, size_t size, size_t nmemb, void *userp) {\n HTTPResponse * response = static_cast<HTTPResponse *>(userp);\n \n int result = 0;\n if (buffer) {\n string s((const char*)buffer, size * nmemb);\n int pos1 = 0;\n for ( ; pos1 < s.size() && s[pos1] != ':'; pos1++) { }\n int pos2 = s[pos1] == ':' ? pos1 + 1 : pos1;\n for (; pos2 < s.size() && isspace(s[pos2]); pos2++) { }\n int pos3 = s.size();\n for (; pos3 > 0 && isspace(s[pos3 - 1]); pos3--) { }\n std::string key = s.substr(0, pos1);\n std::string value = s.substr(pos2, pos3 - pos2);\n\n \/\/ cerr << \"got header: \" << key << \" \" << value << endl;\n\n if (response->getCallback()) {\n response->getCallback()->handleHeader(key, value);\n } else {\n response->addHeader(key, value);\n }\n result = size * nmemb;\n }\n return result; \n}\n\nint\nCurlClient::progress_func(void * clientp, double dltotal, double dlnow, double ultotal, double ulnow) {\n CurlClient * client = static_cast<CurlClient *>(clientp);\n assert(client);\n if (!client->handleProgress(dltotal, dlnow, ultotal, ulnow)) {\n return 1;\n } else {\n return 0;\n }\n}\n\n#ifndef __APPLE__\nstatic pthread_mutex_t *lockarray;\n\n#include <openssl\/crypto.h>\n\nstatic void lock_callback(int mode, int type, const char *file, int line) {\n (void)file;\n (void)line;\n if (mode & CRYPTO_LOCK) {\n pthread_mutex_lock(&(lockarray[type]));\n } else {\n pthread_mutex_unlock(&(lockarray[type]));\n }\n}\n \nstatic unsigned long thread_id(void) {\n unsigned long ret;\n \n#ifdef WIN32\n ret = (unsigned long)(pthread_self().p);\n#else\n ret=(unsigned long)pthread_self();\n#endif\n return(ret);\n}\n \nstatic void init_locks(void) {\n int i;\n \n lockarray=(pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() *\n\t\t\t\t\t sizeof(pthread_mutex_t));\n for (i=0; i<CRYPTO_num_locks(); i++) {\n pthread_mutex_init(&(lockarray[i]),NULL);\n }\n \n CRYPTO_set_id_callback((unsigned long (*)())thread_id);\n CRYPTO_set_locking_callback(lock_callback); \/\/ (void (*)())lock_callback);\n}\n \nstatic void kill_locks(void)\n{\n int i;\n \n CRYPTO_set_locking_callback(NULL);\n for (i=0; i<CRYPTO_num_locks(); i++)\n pthread_mutex_destroy(&(lockarray[i]));\n \n OPENSSL_free(lockarray);\n}\n#endif\n\n#if 0\n#include <gcrypt.h>\n#include <errno.h>\n#include <gnutls\/gnutls.h>\n\nGCRY_THREAD_OPTION_PTHREAD_IMPL;\n#endif\n\nvoid\nCurlClient::clearCookies() {\n if (curl) {\n curl_easy_setopt(curl, CURLOPT_URL, \"ALL\");\n }\n}\n\nstd::shared_ptr<HTTPClient>\nCurlClientFactory::createClient(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {\n return std::make_shared<CurlClient>(\"\", _user_agent, _enable_cookies, _enable_keepalive);\n}\n\nvoid\nCurlClientFactory::globalInit() {\n#ifndef __APPLE__\n#if 0\n gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);\n gnutls_global_init();\n#else\n init_locks();\n#endif\n#endif\n\n curl_global_init(CURL_GLOBAL_DEFAULT);\n\n#if 0\n thread_setup();\n#endif\n#if 0\n gnutls_global_init();\n#endif\n}\n\nvoid\nCurlClientFactory::globalCleanup() {\n curl_global_cleanup();\n#ifndef __APPLE__\n kill_locks();\n#endif\n}\n<commit_msg>refactor, don't use data_out<commit_after>#include \"CurlClient.h\"\n\n#include \"BasicAuth.h\"\n\n#include <cstdio>\n#include <cstring>\n#include <cassert>\n#include <cctype>\n#include <iostream>\n#include <pthread.h>\n\nusing namespace std;\n\n#include <curl\/curl.h>\n\nclass CurlClient : public HTTPClient {\n public:\n CurlClient(const std::string & _interface, const std::string & _user_agent, bool _enable_cookies = true, bool _enable_keepalive = true)\n : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive),\n interface_name(_interface)\n {\n \n }\n CurlClient(const CurlClient & other) : HTTPClient(other),\n\t\t\t\t\t interface_name(other.interface_name)\n {\n \n }\n\n ~CurlClient() {\n if (curl) curl_easy_cleanup(curl);\n }\n\n HTTPResponse request(const HTTPRequest & req, const Authorization & auth) override {\n if (req.getURI().empty()) {\n return HTTPResponse(0, \"empty URI\");\n }\n if (!initialize()) {\n return HTTPResponse(0, \"Unable to initialize client\");\n }\n\n \/\/ string ascii_uri = encodeIDN(uri);\n \/\/ if (ascii_uri.empty()) {\n \/\/ cerr << \"failed to convert url \" << uri << endl;\n \/\/ assert(0);\n \/\/ }\n\n struct curl_slist * headers = 0;\n if (req.getType() == HTTPRequest::POST) {\n if (!req.getContentType().empty()) {\n\tstring h = \"Content-type: \";\n\th += req.getContentType();\n\theaders = curl_slist_append(headers, h.c_str());\n }\n }\n \n const BasicAuth * basic = dynamic_cast<const BasicAuth *>(&auth);\n if (basic) {\n string s = basic->getUsername();\n s += ':';\n s += basic->getPassword();\n curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n curl_easy_setopt(curl, CURLOPT_USERPWD, s.c_str());\n } else {\n string auth_header = auth.createHeader();\n if (!auth_header.empty()) {\n\tstring s = auth.getHeaderName();\n\ts += \": \";\n\ts += auth_header;\n\theaders = curl_slist_append(headers, s.c_str());\n }\n }\n \n for (auto & hd : req.getHeaders()) {\n string s = hd.first;\n s += \": \";\n s += hd.second;\n headers = curl_slist_append(headers, s.c_str());\n }\n \n HTTPResponse response;\n response.setCallback(callback);\n \n if (req.getType() == HTTPRequest::POST) {\n curl_easy_setopt(curl, CURLOPT_POST, 1);\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req.getContent().size());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req.getContent().data());\n } else {\n curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);\n }\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, req.getFollowLocation());\n curl_easy_setopt(curl, CURLOPT_URL, req.getURI().c_str());\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);\n curl_easy_setopt(curl, CURLOPT_TIMEOUT, req.getTimeout());\n curl_easy_setopt(curl, CURLOPT_HEADERDATA, &response);\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);\n if (!cookie_jar.empty()) {\n curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_jar.c_str());\n curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_jar.c_str());\n } \n \n CURLcode res = curl_easy_perform(curl);\n if (res == 0) {\n unsigned long a = 0;\n if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &a) == CURLE_OK) {\n\tresponse.setResultCode(a);\n }\n if (!req.getFollowLocation()) {\n\tchar * ptr = 0;\n\tcurl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &ptr);\n\tif (ptr) {\n\t response.setRedirectUrl(ptr);\n\t}\n }\n } else {\n response.setErrorText(curl_easy_strerror(res));\n }\n \n if (headers) {\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, 0);\n curl_slist_free_all(headers);\n }\n \n return response;\n }\n \n void clearCookies() override {\n if (curl) {\n curl_easy_setopt(curl, CURLOPT_URL, \"ALL\"); \/\/ what does this do?\n }\n }\n \n protected:\n bool initialize() {\n if (curl) {\n curl_easy_reset(curl);\n } else {\n curl = curl_easy_init();\n }\n \n assert(curl);\n \n if (curl) {\n#ifndef WIN32\n if (!interface_name.empty()) {\n\tint r = curl_easy_setopt(curl, CURLOPT_INTERFACE, interface_name.c_str());\n\tassert(r != CURLE_INTERFACE_FAILED);\n }\n#endif\n curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent.c_str());\n curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);\n curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_func);\n curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_func);\n curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headers_func);\n curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this);\n curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);\n curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);\n curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 600);\n \/\/ curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);\n if (!enable_keepalive) {\n\tcurl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);\n\tcurl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);\n\t\/\/ curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, 10);\n }\n if (!cookie_jar.empty()) {\n\tcurl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_jar.c_str());\n\tcurl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_jar.c_str());\n } else if (enable_cookies) {\n\tcurl_easy_setopt(curl, CURLOPT_COOKIEFILE, \"\");\n }\n }\n \n return curl != 0;\n }\n\n private:\n bool handleProgress(double dltotal, double dlnow, double ultotal, double ulnow) {\n if (callback) {\n return callback->onIdle(true);\n }\n return true;\n }\n \n static size_t write_data_func(void * buffer, size_t size, size_t nmemb, void *userp);\n static size_t headers_func(void * buffer, size_t size, size_t nmemb, void *userp);\n static int progress_func(void * clientp, double dltotal, double dlnow, double ultotal, double ulnow);\n\n std::string interface_name;\n CURL * curl = 0;\n};\n\nsize_t\nCurlClient::write_data_func(void * buffer, size_t size, size_t nmemb, void * userp) {\n size_t s = size * nmemb;\n \/\/ Content-Type: multipart\/x-mixed-replace; boundary=myboundary\n\t\t\t\t\t \n HTTPResponse * response = static_cast<HTTPResponse *>(userp);\n assert(response);\n if (response->getCallback()) {\n if (response->getCallback()->handleChunk(s, (const char *)buffer)) {\n return s;\n } else {\n return 0;\n }\n } else {\n response->appendContent(string((const char *)buffer, s));\n return s;\n }\n}\n\nsize_t\nCurlClient::headers_func(void * buffer, size_t size, size_t nmemb, void *userp) {\n HTTPResponse * response = static_cast<HTTPResponse *>(userp);\n \n int result = 0;\n if (buffer) {\n string s((const char*)buffer, size * nmemb);\n int pos1 = 0;\n for ( ; pos1 < s.size() && s[pos1] != ':'; pos1++) { }\n int pos2 = s[pos1] == ':' ? pos1 + 1 : pos1;\n for (; pos2 < s.size() && isspace(s[pos2]); pos2++) { }\n int pos3 = s.size();\n for (; pos3 > 0 && isspace(s[pos3 - 1]); pos3--) { }\n std::string key = s.substr(0, pos1);\n std::string value = s.substr(pos2, pos3 - pos2);\n\n \/\/ cerr << \"got header: \" << key << \" \" << value << endl;\n\n if (response->getCallback()) {\n response->getCallback()->handleHeader(key, value);\n } else {\n response->addHeader(key, value);\n }\n result = size * nmemb;\n }\n return result; \n}\n\nint\nCurlClient::progress_func(void * clientp, double dltotal, double dlnow, double ultotal, double ulnow) {\n CurlClient * client = static_cast<CurlClient *>(clientp);\n assert(client);\n if (!client->handleProgress(dltotal, dlnow, ultotal, ulnow)) {\n return 1;\n } else {\n return 0;\n }\n}\n\n#ifndef __APPLE__\nstatic pthread_mutex_t *lockarray;\n\n#include <openssl\/crypto.h>\n\nstatic void lock_callback(int mode, int type, const char *file, int line) {\n (void)file;\n (void)line;\n if (mode & CRYPTO_LOCK) {\n pthread_mutex_lock(&(lockarray[type]));\n } else {\n pthread_mutex_unlock(&(lockarray[type]));\n }\n}\n \nstatic unsigned long thread_id(void) {\n unsigned long ret;\n \n#ifdef WIN32\n ret = (unsigned long)(pthread_self().p);\n#else\n ret=(unsigned long)pthread_self();\n#endif\n return(ret);\n}\n \nstatic void init_locks(void) {\n int i;\n \n lockarray=(pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() *\n\t\t\t\t\t sizeof(pthread_mutex_t));\n for (i=0; i<CRYPTO_num_locks(); i++) {\n pthread_mutex_init(&(lockarray[i]),NULL);\n }\n \n CRYPTO_set_id_callback((unsigned long (*)())thread_id);\n CRYPTO_set_locking_callback(lock_callback); \/\/ (void (*)())lock_callback);\n}\n \nstatic void kill_locks(void)\n{\n int i;\n \n CRYPTO_set_locking_callback(NULL);\n for (i=0; i<CRYPTO_num_locks(); i++)\n pthread_mutex_destroy(&(lockarray[i]));\n \n OPENSSL_free(lockarray);\n}\n#endif\n\n#if 0\n#include <gcrypt.h>\n#include <errno.h>\n#include <gnutls\/gnutls.h>\n\nGCRY_THREAD_OPTION_PTHREAD_IMPL;\n#endif\n\nstd::shared_ptr<HTTPClient>\nCurlClientFactory::createClient(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {\n return std::make_shared<CurlClient>(\"\", _user_agent, _enable_cookies, _enable_keepalive);\n}\n\nvoid\nCurlClientFactory::globalInit() {\n#ifndef __APPLE__\n#if 0\n gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);\n gnutls_global_init();\n#else\n init_locks();\n#endif\n#endif\n\n curl_global_init(CURL_GLOBAL_DEFAULT);\n\n#if 0\n thread_setup();\n#endif\n#if 0\n gnutls_global_init();\n#endif\n}\n\nvoid\nCurlClientFactory::globalCleanup() {\n curl_global_cleanup();\n#ifndef __APPLE__\n kill_locks();\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 The Imaging Source Europe 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\n#include \"DeviceInfo.h\"\n\n#include <cstring>\n#include <string>\n\nusing namespace tcam;\n\nDeviceInfo::DeviceInfo (const struct tcam_device_info& device_desc)\n : device(device_desc)\n{}\n\n\nDeviceInfo::DeviceInfo ()\n{\n device.type = TCAM_DEVICE_TYPE_UNKNOWN;\n\n memset(device.identifier, 0, sizeof(device.identifier));\n memset(device.name, 0, sizeof(device.name));\n memset(device.serial_number, 0, sizeof(device.serial_number));\n}\n\n\nDeviceInfo::DeviceInfo (const DeviceInfo& other)\n{\n this->device = other.device;\n}\n\n\nDeviceInfo& DeviceInfo::operator= (const DeviceInfo& other)\n{\n this->device = other.device;\n return *this;\n}\n\n\nstruct tcam_device_info DeviceInfo::get_info () const\n{\n return device;\n}\n\n\nstd::string DeviceInfo::get_name () const\n{\n return device.name;\n}\n\n\nstd::string DeviceInfo::get_serial () const\n{\n return device.serial_number;\n}\n\n\nstd::string DeviceInfo::get_identifier () const\n{\n return device.identifier;\n}\n\n\nenum TCAM_DEVICE_TYPE DeviceInfo::get_device_type () const\n{\n return device.type;\n}\n\n\nstd::string DeviceInfo::get_device_type_as_string () const\n{\n switch (device.type)\n {\n case TCAM_DEVICE_TYPE_V4L2:\n return \"V4L2\";\n case TCAM_DEVICE_TYPE_ARAVIS:\n return \"Aravis\";\n case TCAM_DEVICE_TYPE_LIBUSB:\n return \"LibUsb\";\n default:\n return \"Unknown\";\n }\n}\n<commit_msg>srcs: Make device type strings lower case<commit_after>\/*\n * Copyright 2014 The Imaging Source Europe 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\n#include \"DeviceInfo.h\"\n\n#include <cstring>\n#include <string>\n\nusing namespace tcam;\n\nDeviceInfo::DeviceInfo (const struct tcam_device_info& device_desc)\n : device(device_desc)\n{}\n\n\nDeviceInfo::DeviceInfo ()\n{\n device.type = TCAM_DEVICE_TYPE_UNKNOWN;\n\n memset(device.identifier, 0, sizeof(device.identifier));\n memset(device.name, 0, sizeof(device.name));\n memset(device.serial_number, 0, sizeof(device.serial_number));\n}\n\n\nDeviceInfo::DeviceInfo (const DeviceInfo& other)\n{\n this->device = other.device;\n}\n\n\nDeviceInfo& DeviceInfo::operator= (const DeviceInfo& other)\n{\n this->device = other.device;\n return *this;\n}\n\n\nstruct tcam_device_info DeviceInfo::get_info () const\n{\n return device;\n}\n\n\nstd::string DeviceInfo::get_name () const\n{\n return device.name;\n}\n\n\nstd::string DeviceInfo::get_serial () const\n{\n return device.serial_number;\n}\n\n\nstd::string DeviceInfo::get_identifier () const\n{\n return device.identifier;\n}\n\n\nenum TCAM_DEVICE_TYPE DeviceInfo::get_device_type () const\n{\n return device.type;\n}\n\n\nstd::string DeviceInfo::get_device_type_as_string () const\n{\n switch (device.type)\n {\n case TCAM_DEVICE_TYPE_V4L2:\n return \"v4l2\";\n case TCAM_DEVICE_TYPE_ARAVIS:\n return \"aravis\";\n case TCAM_DEVICE_TYPE_LIBUSB:\n return \"libusb\";\n default:\n return \"unknown\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 R. Thomas\n * Copyright 2017 Quarkslab\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 <iomanip>\n\n#ifdef __unix__\n #include <cxxabi.h>\n#endif\n\n#include \"LIEF\/exception.hpp\"\n\n#include \"LIEF\/visitors\/Hash.hpp\"\n\n#include \"LIEF\/ELF\/Symbol.hpp\"\n#include \"LIEF\/ELF\/EnumToString.hpp\"\n\n\nnamespace LIEF {\nnamespace ELF {\n\nSymbol::Symbol(void) :\n type_{ELF_SYMBOL_TYPES::STT_NOTYPE},\n binding_{SYMBOL_BINDINGS::STB_LOCAL},\n other_{0},\n shndx_{0},\n value_{0},\n size_{0},\n symbol_version_{nullptr}\n{}\n\n\nSymbol::~Symbol(void) = default;\n\nSymbol& Symbol::operator=(Symbol other) {\n this->swap(other);\n return *this;\n}\n\nSymbol::Symbol(const Symbol& other) : LIEF::Symbol{other},\n type_{other.type_},\n binding_{other.binding_},\n other_{other.other_},\n shndx_{other.shndx_},\n value_{other.value_},\n size_{other.size_},\n symbol_version_{nullptr}\n{}\n\n\nvoid Symbol::swap(Symbol& other) {\n std::swap(this->name_, other.name_);\n std::swap(this->type_, other.type_);\n std::swap(this->binding_, other.binding_);\n std::swap(this->other_, other.other_);\n std::swap(this->shndx_, other.shndx_);\n std::swap(this->value_, other.value_);\n std::swap(this->size_, other.size_);\n std::swap(this->symbol_version_, other.symbol_version_);\n}\n\nSymbol::Symbol(const Elf32_Sym* header) :\n LIEF::Symbol{},\n type_{static_cast<ELF_SYMBOL_TYPES>(header->st_info & 0x0f)},\n binding_{static_cast<SYMBOL_BINDINGS>(header->st_info >> 4)},\n other_{header->st_other},\n shndx_{header->st_shndx},\n value_{header->st_value},\n size_{header->st_size},\n symbol_version_{nullptr}\n{}\n\nSymbol::Symbol(const Elf64_Sym* header) :\n LIEF::Symbol{},\n type_{static_cast<ELF_SYMBOL_TYPES>(header->st_info & 0x0f)},\n binding_{static_cast<SYMBOL_BINDINGS>(header->st_info >> 4)},\n other_{header->st_other},\n shndx_{header->st_shndx},\n value_{header->st_value},\n size_{header->st_size},\n symbol_version_{nullptr}\n{}\n\n\nSymbol::Symbol(std::string name, ELF_SYMBOL_TYPES type, SYMBOL_BINDINGS binding,\n uint8_t other, uint16_t shndx,\n uint64_t value, uint64_t size) :\n LIEF::Symbol{name},\n type_{type},\n binding_{binding},\n other_{other},\n shndx_{shndx},\n value_{value},\n size_{size},\n symbol_version_{nullptr}\n{}\n\n\nELF_SYMBOL_TYPES Symbol::type(void) const {\n return this->type_;\n}\n\nSYMBOL_BINDINGS Symbol::binding(void) const {\n return this->binding_;\n}\n\nuint8_t Symbol::information(void) const {\n return static_cast<uint8_t>((static_cast<uint8_t>(this->binding_) << 4) | (static_cast<uint8_t>(this->type_) & 0x0f));\n}\n\nuint8_t Symbol::other(void) const {\n return this->other_;\n}\n\nuint16_t Symbol::section_idx(void) const {\n return this->shndx();\n}\n\nSection& Symbol::section(void) {\n if (this->section_ == nullptr) {\n throw not_found(\"No section associated with this symbol\");\n } else {\n return *this->section_;\n }\n}\n\nuint64_t Symbol::value(void) const {\n return this->value_;\n}\n\nuint64_t Symbol::size(void) const {\n return this->size_;\n}\n\nuint16_t Symbol::shndx(void) const {\n return this->shndx_;\n}\n\n\nbool Symbol::has_version(void) const {\n return this->symbol_version_ != nullptr;\n}\n\n\nconst SymbolVersion& Symbol::symbol_version(void) const {\n if (this->symbol_version_ != nullptr) {\n return *this->symbol_version_;\n } else {\n throw not_found(\"There is no symbol version associated with this symbol\");\n }\n}\n\nSymbolVersion& Symbol::symbol_version(void) {\n return const_cast<SymbolVersion&>(static_cast<const Symbol*>(this)->symbol_version());\n}\n\nvoid Symbol::type(ELF_SYMBOL_TYPES type) {\n this->type_ = type;\n}\n\nvoid Symbol::binding(SYMBOL_BINDINGS binding) {\n this->binding_ = binding;\n}\n\nvoid Symbol::other(uint8_t other) {\n this->other_ = other;\n}\n\nvoid Symbol::value(uint64_t value) {\n this->value_ = value;\n}\n\nvoid Symbol::size(uint64_t size) {\n this->size_ = size;\n}\n\n\nvoid Symbol::shndx(uint16_t idx) {\n this->shndx_ = idx;\n}\n\n\nvoid Symbol::information(uint8_t info) {\n this->binding_ = static_cast<SYMBOL_BINDINGS>(info >> 4);\n this->type_ = static_cast<ELF_SYMBOL_TYPES>(info & 0x0f);\n}\n\n\nstd::string Symbol::demangled_name(void) const {\n#if defined(__unix__)\n int status;\n const std::string& name = this->name().c_str();\n auto realname = abi::__cxa_demangle(name.c_str(), 0, 0, &status);\n\n if (status == 0) {\n return realname;\n } else {\n return name;\n }\n#else\n throw not_supported(\"Can't demangle name\");\n#endif\n}\n\nbool Symbol::is_exported(void) const {\n return ((this->binding() == SYMBOL_BINDINGS::STB_GLOBAL or\n this->binding() == SYMBOL_BINDINGS::STB_WEAK) and\n this->shndx() != SYMBOL_SECTION_INDEX::SHN_UNDEF);\n}\n\nvoid Symbol::set_exported(bool flag) {\n if (flag) {\n this->shndx(1);\n this->binding(SYMBOL_BINDINGS::STB_GLOBAL);\n } else {\n this->shndx(SYMBOL_SECTION_INDEX::SHN_UNDEF);\n this->binding(SYMBOL_BINDINGS::STB_LOCAL);\n }\n}\n\nbool Symbol::is_imported(void) const {\n return this->shndx() == SYMBOL_SECTION_INDEX::SHN_UNDEF;\n}\n\nvoid Symbol::set_imported(bool flag) {\n if (flag) {\n this->shndx(SYMBOL_SECTION_INDEX::SHN_UNDEF);\n } else {\n this->shndx(1);\n }\n}\n\n\n\nvoid Symbol::accept(Visitor& visitor) const {\n\n LIEF::Symbol::accept(visitor);\n\n visitor.visit(this->type());\n visitor.visit(this->binding());\n visitor.visit(this->information());\n visitor.visit(this->other());\n visitor.visit(this->section_idx());\n visitor.visit(this->value());\n visitor.visit(this->size());\n\n if(this->has_version()) {\n visitor(this->symbol_version());\n }\n}\n\nbool Symbol::operator==(const Symbol& rhs) const {\n size_t hash_lhs = Hash::hash(*this);\n size_t hash_rhs = Hash::hash(rhs);\n return hash_lhs == hash_rhs;\n}\n\nbool Symbol::operator!=(const Symbol& rhs) const {\n return not (*this == rhs);\n}\n\n\n\nstd::ostream& operator<<(std::ostream& os, const Symbol& entry) {\n\n std::string name;\n try {\n name = entry.demangled_name();\n } catch (const not_supported&) {\n name = entry.name();\n }\n os << std::hex;\n os << std::left\n << std::setw(30) << name\n << std::setw(10) << to_string(entry.type())\n << std::setw(10) << to_string(entry.binding())\n << std::setw(10) << entry.value()\n << std::setw(10) << entry.size();\n\n if (entry.has_version()) {\n os << std::setw(10) << entry.symbol_version();\n }\n\n return os;\n}\n}\n}\n<commit_msg>Enhance ELF symbol visibility<commit_after>\/* Copyright 2017 R. Thomas\n * Copyright 2017 Quarkslab\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 <iomanip>\n\n#ifdef __unix__\n #include <cxxabi.h>\n#endif\n\n#include \"LIEF\/exception.hpp\"\n\n#include \"LIEF\/visitors\/Hash.hpp\"\n\n#include \"LIEF\/ELF\/Symbol.hpp\"\n#include \"LIEF\/ELF\/EnumToString.hpp\"\n\n\nnamespace LIEF {\nnamespace ELF {\n\nSymbol::Symbol(void) :\n type_{ELF_SYMBOL_TYPES::STT_NOTYPE},\n binding_{SYMBOL_BINDINGS::STB_LOCAL},\n other_{0},\n shndx_{0},\n value_{0},\n size_{0},\n symbol_version_{nullptr}\n{}\n\n\nSymbol::~Symbol(void) = default;\n\nSymbol& Symbol::operator=(Symbol other) {\n this->swap(other);\n return *this;\n}\n\nSymbol::Symbol(const Symbol& other) : LIEF::Symbol{other},\n type_{other.type_},\n binding_{other.binding_},\n other_{other.other_},\n shndx_{other.shndx_},\n value_{other.value_},\n size_{other.size_},\n symbol_version_{nullptr}\n{}\n\n\nvoid Symbol::swap(Symbol& other) {\n std::swap(this->name_, other.name_);\n std::swap(this->type_, other.type_);\n std::swap(this->binding_, other.binding_);\n std::swap(this->other_, other.other_);\n std::swap(this->shndx_, other.shndx_);\n std::swap(this->value_, other.value_);\n std::swap(this->size_, other.size_);\n std::swap(this->symbol_version_, other.symbol_version_);\n}\n\nSymbol::Symbol(const Elf32_Sym* header) :\n LIEF::Symbol{},\n type_{static_cast<ELF_SYMBOL_TYPES>(header->st_info & 0x0f)},\n binding_{static_cast<SYMBOL_BINDINGS>(header->st_info >> 4)},\n other_{header->st_other},\n shndx_{header->st_shndx},\n value_{header->st_value},\n size_{header->st_size},\n symbol_version_{nullptr}\n{}\n\nSymbol::Symbol(const Elf64_Sym* header) :\n LIEF::Symbol{},\n type_{static_cast<ELF_SYMBOL_TYPES>(header->st_info & 0x0f)},\n binding_{static_cast<SYMBOL_BINDINGS>(header->st_info >> 4)},\n other_{header->st_other},\n shndx_{header->st_shndx},\n value_{header->st_value},\n size_{header->st_size},\n symbol_version_{nullptr}\n{}\n\n\nSymbol::Symbol(std::string name, ELF_SYMBOL_TYPES type, SYMBOL_BINDINGS binding,\n uint8_t other, uint16_t shndx,\n uint64_t value, uint64_t size) :\n LIEF::Symbol{name},\n type_{type},\n binding_{binding},\n other_{other},\n shndx_{shndx},\n value_{value},\n size_{size},\n symbol_version_{nullptr}\n{}\n\n\nELF_SYMBOL_TYPES Symbol::type(void) const {\n return this->type_;\n}\n\nSYMBOL_BINDINGS Symbol::binding(void) const {\n return this->binding_;\n}\n\nuint8_t Symbol::information(void) const {\n return static_cast<uint8_t>((static_cast<uint8_t>(this->binding_) << 4) | (static_cast<uint8_t>(this->type_) & 0x0f));\n}\n\nuint8_t Symbol::other(void) const {\n return this->other_;\n}\n\nuint16_t Symbol::section_idx(void) const {\n return this->shndx();\n}\n\nSection& Symbol::section(void) {\n if (this->section_ == nullptr) {\n throw not_found(\"No section associated with this symbol\");\n } else {\n return *this->section_;\n }\n}\n\nuint64_t Symbol::value(void) const {\n return this->value_;\n}\n\nuint64_t Symbol::size(void) const {\n return this->size_;\n}\n\nuint16_t Symbol::shndx(void) const {\n return this->shndx_;\n}\n\n\nbool Symbol::has_version(void) const {\n return this->symbol_version_ != nullptr;\n}\n\n\nconst SymbolVersion& Symbol::symbol_version(void) const {\n if (this->symbol_version_ != nullptr) {\n return *this->symbol_version_;\n } else {\n throw not_found(\"There is no symbol version associated with this symbol\");\n }\n}\n\nSymbolVersion& Symbol::symbol_version(void) {\n return const_cast<SymbolVersion&>(static_cast<const Symbol*>(this)->symbol_version());\n}\n\nvoid Symbol::type(ELF_SYMBOL_TYPES type) {\n this->type_ = type;\n}\n\nvoid Symbol::binding(SYMBOL_BINDINGS binding) {\n this->binding_ = binding;\n}\n\nvoid Symbol::other(uint8_t other) {\n this->other_ = other;\n}\n\nvoid Symbol::value(uint64_t value) {\n this->value_ = value;\n}\n\nvoid Symbol::size(uint64_t size) {\n this->size_ = size;\n}\n\n\nvoid Symbol::shndx(uint16_t idx) {\n this->shndx_ = idx;\n}\n\n\nvoid Symbol::information(uint8_t info) {\n this->binding_ = static_cast<SYMBOL_BINDINGS>(info >> 4);\n this->type_ = static_cast<ELF_SYMBOL_TYPES>(info & 0x0f);\n}\n\n\nstd::string Symbol::demangled_name(void) const {\n#if defined(__unix__)\n int status;\n const std::string& name = this->name().c_str();\n auto realname = abi::__cxa_demangle(name.c_str(), 0, 0, &status);\n\n if (status == 0) {\n return realname;\n } else {\n return name;\n }\n#else\n throw not_supported(\"Can't demangle name\");\n#endif\n}\n\nbool Symbol::is_exported(void) const {\n bool is_exported = this->shndx() != SYMBOL_SECTION_INDEX::SHN_UNDEF;\n is_exported = is_exported and this->value() != 0;\n is_exported = is_exported and (this->binding() == SYMBOL_BINDINGS::STB_GLOBAL or\n this->binding() == SYMBOL_BINDINGS::STB_WEAK);\n is_exported = is_exported and (this->type() == ELF_SYMBOL_TYPES::STT_FUNC or\n this->type() == ELF_SYMBOL_TYPES::STT_GNU_IFUNC or\n this->type() == ELF_SYMBOL_TYPES::STT_OBJECT);\n return is_exported;\n}\n\nvoid Symbol::set_exported(bool flag) {\n if (flag) {\n this->shndx(1);\n this->binding(SYMBOL_BINDINGS::STB_GLOBAL);\n } else {\n this->shndx(SYMBOL_SECTION_INDEX::SHN_UNDEF);\n this->binding(SYMBOL_BINDINGS::STB_LOCAL);\n }\n}\n\nbool Symbol::is_imported(void) const {\n bool is_imported = this->shndx() == SYMBOL_SECTION_INDEX::SHN_UNDEF;\n is_imported = is_imported and this->value() == 0;\n is_imported = is_imported and this->name().size() > 0;\n is_imported = is_imported and (this->binding() == SYMBOL_BINDINGS::STB_GLOBAL or\n this->binding() == SYMBOL_BINDINGS::STB_WEAK);\n is_imported = is_imported and (this->type() == ELF_SYMBOL_TYPES::STT_FUNC or\n this->type() == ELF_SYMBOL_TYPES::STT_GNU_IFUNC or\n this->type() == ELF_SYMBOL_TYPES::STT_OBJECT);\n return is_imported;\n}\n\nvoid Symbol::set_imported(bool flag) {\n if (flag) {\n this->shndx(SYMBOL_SECTION_INDEX::SHN_UNDEF);\n } else {\n this->shndx(1);\n }\n}\n\n\n\nvoid Symbol::accept(Visitor& visitor) const {\n\n LIEF::Symbol::accept(visitor);\n\n visitor.visit(this->type());\n visitor.visit(this->binding());\n visitor.visit(this->information());\n visitor.visit(this->other());\n visitor.visit(this->section_idx());\n visitor.visit(this->value());\n visitor.visit(this->size());\n\n if(this->has_version()) {\n visitor(this->symbol_version());\n }\n}\n\nbool Symbol::operator==(const Symbol& rhs) const {\n size_t hash_lhs = Hash::hash(*this);\n size_t hash_rhs = Hash::hash(rhs);\n return hash_lhs == hash_rhs;\n}\n\nbool Symbol::operator!=(const Symbol& rhs) const {\n return not (*this == rhs);\n}\n\n\n\nstd::ostream& operator<<(std::ostream& os, const Symbol& entry) {\n\n std::string name;\n try {\n name = entry.demangled_name();\n } catch (const not_supported&) {\n name = entry.name();\n }\n os << std::hex;\n os << std::left\n << std::setw(30) << name\n << std::setw(10) << to_string(entry.type())\n << std::setw(10) << to_string(entry.binding())\n << std::setw(10) << entry.value()\n << std::setw(10) << entry.size();\n\n if (entry.has_version()) {\n os << std::setw(10) << entry.symbol_version();\n }\n\n return os;\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--------------------- DispatchStage.cpp --------------------*- C++ -*-===\/\/\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\/\/\/ \\file\n\/\/\/\n\/\/\/ This file models the dispatch component of an instruction pipeline.\n\/\/\/\n\/\/\/ The DispatchStage is responsible for updating instruction dependencies\n\/\/\/ and communicating to the simulated instruction scheduler that an instruction\n\/\/\/ is ready to be scheduled for execution.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"DispatchStage.h\"\n#include \"Backend.h\"\n#include \"HWEventListener.h\"\n#include \"Scheduler.h\"\n#include \"llvm\/Support\/Debug.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"llvm-mca\"\n\nnamespace mca {\n\nvoid DispatchStage::notifyInstructionDispatched(const InstRef &IR,\n ArrayRef<unsigned> UsedRegs) {\n LLVM_DEBUG(dbgs() << \"[E] Instruction Dispatched: \" << IR << '\\n');\n Owner->notifyInstructionEvent(HWInstructionDispatchedEvent(IR, UsedRegs));\n}\n\nbool DispatchStage::checkPRF(const InstRef &IR) {\n SmallVector<unsigned, 4> RegDefs;\n for (const std::unique_ptr<WriteState> &RegDef :\n IR.getInstruction()->getDefs())\n RegDefs.emplace_back(RegDef->getRegisterID());\n\n const unsigned RegisterMask = PRF.isAvailable(RegDefs);\n \/\/ A mask with all zeroes means: register files are available.\n if (RegisterMask) {\n Owner->notifyStallEvent(HWStallEvent(HWStallEvent::RegisterFileStall, IR));\n return false;\n }\n\n return true;\n}\n\nbool DispatchStage::checkRCU(const InstRef &IR) {\n const unsigned NumMicroOps = IR.getInstruction()->getDesc().NumMicroOps;\n if (RCU.isAvailable(NumMicroOps))\n return true;\n Owner->notifyStallEvent(\n HWStallEvent(HWStallEvent::RetireControlUnitStall, IR));\n return false;\n}\n\nbool DispatchStage::checkScheduler(const InstRef &IR) {\n HWStallEvent::GenericEventType Event;\n const bool Ready = SC.canBeDispatched(IR, Event);\n if (!Ready)\n Owner->notifyStallEvent(HWStallEvent(Event, IR));\n return Ready;\n}\n\nvoid DispatchStage::updateRAWDependencies(ReadState &RS,\n const MCSubtargetInfo &STI) {\n SmallVector<WriteState *, 4> DependentWrites;\n\n collectWrites(DependentWrites, RS.getRegisterID());\n RS.setDependentWrites(DependentWrites.size());\n LLVM_DEBUG(dbgs() << \"Found \" << DependentWrites.size()\n << \" dependent writes\\n\");\n \/\/ We know that this read depends on all the writes in DependentWrites.\n \/\/ For each write, check if we have ReadAdvance information, and use it\n \/\/ to figure out in how many cycles this read becomes available.\n const ReadDescriptor &RD = RS.getDescriptor();\n if (!RD.HasReadAdvanceEntries) {\n for (WriteState *WS : DependentWrites)\n WS->addUser(&RS, \/* ReadAdvance *\/ 0);\n return;\n }\n\n const MCSchedModel &SM = STI.getSchedModel();\n const MCSchedClassDesc *SC = SM.getSchedClassDesc(RD.SchedClassID);\n for (WriteState *WS : DependentWrites) {\n unsigned WriteResID = WS->getWriteResourceID();\n int ReadAdvance = STI.getReadAdvanceCycles(SC, RD.UseIndex, WriteResID);\n WS->addUser(&RS, ReadAdvance);\n }\n \/\/ Prepare the set for another round.\n DependentWrites.clear();\n}\n\nvoid DispatchStage::dispatch(InstRef IR) {\n assert(!CarryOver && \"Cannot dispatch another instruction!\");\n Instruction &IS = *IR.getInstruction();\n const InstrDesc &Desc = IS.getDesc();\n const unsigned NumMicroOps = Desc.NumMicroOps;\n if (NumMicroOps > DispatchWidth) {\n assert(AvailableEntries == DispatchWidth);\n AvailableEntries = 0;\n CarryOver = NumMicroOps - DispatchWidth;\n } else {\n assert(AvailableEntries >= NumMicroOps);\n AvailableEntries -= NumMicroOps;\n }\n\n \/\/ A dependency-breaking instruction doesn't have to wait on the register\n \/\/ input operands, and it is often optimized at register renaming stage.\n \/\/ Update RAW dependencies if this instruction is not a dependency-breaking\n \/\/ instruction. A dependency-breaking instruction is a zero-latency\n \/\/ instruction that doesn't consume hardware resources.\n \/\/ An example of dependency-breaking instruction on X86 is a zero-idiom XOR.\n if (!Desc.isZeroLatency())\n for (std::unique_ptr<ReadState> &RS : IS.getUses())\n updateRAWDependencies(*RS, STI);\n\n \/\/ By default, a dependency-breaking zero-latency instruction is expected to\n \/\/ be optimized at register renaming stage. That means, no physical register\n \/\/ is allocated to the instruction.\n SmallVector<unsigned, 4> RegisterFiles(PRF.getNumRegisterFiles());\n for (std::unique_ptr<WriteState> &WS : IS.getDefs())\n PRF.addRegisterWrite(*WS, RegisterFiles, !Desc.isZeroLatency());\n\n \/\/ Reserve slots in the RCU, and notify the instruction that it has been\n \/\/ dispatched to the schedulers for execution.\n IS.dispatch(RCU.reserveSlot(IR, NumMicroOps));\n\n \/\/ Notify listeners of the \"instruction dispatched\" event.\n notifyInstructionDispatched(IR, RegisterFiles);\n}\n\nvoid DispatchStage::preExecute(const InstRef &IR) {\n AvailableEntries = CarryOver >= DispatchWidth ? 0 : DispatchWidth - CarryOver;\n CarryOver = CarryOver >= DispatchWidth ? CarryOver - DispatchWidth : 0U;\n}\n\nbool DispatchStage::execute(InstRef &IR) {\n const InstrDesc &Desc = IR.getInstruction()->getDesc();\n if (!isAvailable(Desc.NumMicroOps) || !canDispatch(IR))\n return false;\n dispatch(IR);\n return true;\n}\n\n#ifndef NDEBUG\nvoid DispatchStage::dump() const {\n PRF.dump();\n RCU.dump();\n}\n#endif\n} \/\/ namespace mca\n<commit_msg>[llvm-mca] Remove redundant call. NFC<commit_after>\/\/===--------------------- DispatchStage.cpp --------------------*- C++ -*-===\/\/\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\/\/\/ \\file\n\/\/\/\n\/\/\/ This file models the dispatch component of an instruction pipeline.\n\/\/\/\n\/\/\/ The DispatchStage is responsible for updating instruction dependencies\n\/\/\/ and communicating to the simulated instruction scheduler that an instruction\n\/\/\/ is ready to be scheduled for execution.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"DispatchStage.h\"\n#include \"Backend.h\"\n#include \"HWEventListener.h\"\n#include \"Scheduler.h\"\n#include \"llvm\/Support\/Debug.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"llvm-mca\"\n\nnamespace mca {\n\nvoid DispatchStage::notifyInstructionDispatched(const InstRef &IR,\n ArrayRef<unsigned> UsedRegs) {\n LLVM_DEBUG(dbgs() << \"[E] Instruction Dispatched: \" << IR << '\\n');\n Owner->notifyInstructionEvent(HWInstructionDispatchedEvent(IR, UsedRegs));\n}\n\nbool DispatchStage::checkPRF(const InstRef &IR) {\n SmallVector<unsigned, 4> RegDefs;\n for (const std::unique_ptr<WriteState> &RegDef :\n IR.getInstruction()->getDefs())\n RegDefs.emplace_back(RegDef->getRegisterID());\n\n const unsigned RegisterMask = PRF.isAvailable(RegDefs);\n \/\/ A mask with all zeroes means: register files are available.\n if (RegisterMask) {\n Owner->notifyStallEvent(HWStallEvent(HWStallEvent::RegisterFileStall, IR));\n return false;\n }\n\n return true;\n}\n\nbool DispatchStage::checkRCU(const InstRef &IR) {\n const unsigned NumMicroOps = IR.getInstruction()->getDesc().NumMicroOps;\n if (RCU.isAvailable(NumMicroOps))\n return true;\n Owner->notifyStallEvent(\n HWStallEvent(HWStallEvent::RetireControlUnitStall, IR));\n return false;\n}\n\nbool DispatchStage::checkScheduler(const InstRef &IR) {\n HWStallEvent::GenericEventType Event;\n const bool Ready = SC.canBeDispatched(IR, Event);\n if (!Ready)\n Owner->notifyStallEvent(HWStallEvent(Event, IR));\n return Ready;\n}\n\nvoid DispatchStage::updateRAWDependencies(ReadState &RS,\n const MCSubtargetInfo &STI) {\n SmallVector<WriteState *, 4> DependentWrites;\n\n collectWrites(DependentWrites, RS.getRegisterID());\n RS.setDependentWrites(DependentWrites.size());\n LLVM_DEBUG(dbgs() << \"Found \" << DependentWrites.size()\n << \" dependent writes\\n\");\n \/\/ We know that this read depends on all the writes in DependentWrites.\n \/\/ For each write, check if we have ReadAdvance information, and use it\n \/\/ to figure out in how many cycles this read becomes available.\n const ReadDescriptor &RD = RS.getDescriptor();\n if (!RD.HasReadAdvanceEntries) {\n for (WriteState *WS : DependentWrites)\n WS->addUser(&RS, \/* ReadAdvance *\/ 0);\n return;\n }\n\n const MCSchedModel &SM = STI.getSchedModel();\n const MCSchedClassDesc *SC = SM.getSchedClassDesc(RD.SchedClassID);\n for (WriteState *WS : DependentWrites) {\n unsigned WriteResID = WS->getWriteResourceID();\n int ReadAdvance = STI.getReadAdvanceCycles(SC, RD.UseIndex, WriteResID);\n WS->addUser(&RS, ReadAdvance);\n }\n}\n\nvoid DispatchStage::dispatch(InstRef IR) {\n assert(!CarryOver && \"Cannot dispatch another instruction!\");\n Instruction &IS = *IR.getInstruction();\n const InstrDesc &Desc = IS.getDesc();\n const unsigned NumMicroOps = Desc.NumMicroOps;\n if (NumMicroOps > DispatchWidth) {\n assert(AvailableEntries == DispatchWidth);\n AvailableEntries = 0;\n CarryOver = NumMicroOps - DispatchWidth;\n } else {\n assert(AvailableEntries >= NumMicroOps);\n AvailableEntries -= NumMicroOps;\n }\n\n \/\/ A dependency-breaking instruction doesn't have to wait on the register\n \/\/ input operands, and it is often optimized at register renaming stage.\n \/\/ Update RAW dependencies if this instruction is not a dependency-breaking\n \/\/ instruction. A dependency-breaking instruction is a zero-latency\n \/\/ instruction that doesn't consume hardware resources.\n \/\/ An example of dependency-breaking instruction on X86 is a zero-idiom XOR.\n if (!Desc.isZeroLatency())\n for (std::unique_ptr<ReadState> &RS : IS.getUses())\n updateRAWDependencies(*RS, STI);\n\n \/\/ By default, a dependency-breaking zero-latency instruction is expected to\n \/\/ be optimized at register renaming stage. That means, no physical register\n \/\/ is allocated to the instruction.\n SmallVector<unsigned, 4> RegisterFiles(PRF.getNumRegisterFiles());\n for (std::unique_ptr<WriteState> &WS : IS.getDefs())\n PRF.addRegisterWrite(*WS, RegisterFiles, !Desc.isZeroLatency());\n\n \/\/ Reserve slots in the RCU, and notify the instruction that it has been\n \/\/ dispatched to the schedulers for execution.\n IS.dispatch(RCU.reserveSlot(IR, NumMicroOps));\n\n \/\/ Notify listeners of the \"instruction dispatched\" event.\n notifyInstructionDispatched(IR, RegisterFiles);\n}\n\nvoid DispatchStage::preExecute(const InstRef &IR) {\n AvailableEntries = CarryOver >= DispatchWidth ? 0 : DispatchWidth - CarryOver;\n CarryOver = CarryOver >= DispatchWidth ? CarryOver - DispatchWidth : 0U;\n}\n\nbool DispatchStage::execute(InstRef &IR) {\n const InstrDesc &Desc = IR.getInstruction()->getDesc();\n if (!isAvailable(Desc.NumMicroOps) || !canDispatch(IR))\n return false;\n dispatch(IR);\n return true;\n}\n\n#ifndef NDEBUG\nvoid DispatchStage::dump() const {\n PRF.dump();\n RCU.dump();\n}\n#endif\n} \/\/ namespace mca\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n\n#include \"Zenderer\/Zenderer.hpp\"\n\nusing namespace zen;\n\n\/\/ Here's some perfect sample XML.\nstatic const char* SAMPLE_XML[] = {\n \"<entity type=\\\"QUAD\\\" name=\\\"generic\\\">\",\n \"<position x=\\\"100\\\" y=\\\"200\\\">\",\n \"<\/ >\",\n \"<texture>\",\n \"Tester.tga\",\n \"<\/ >\",\n \"<shader type=\\\"both\\\">\",\n \"<vshader>\",\n \"Tester.vs\",\n \"<\/ >\",\n \"<fshader>\",\n \"Tester.fs\",\n \"<\/ >\",\n \"<\/ >\",\n \"<\/ >\"\n};\n\n#if defined(ZEN_API) && !defined(_DEBUG) && !defined(ZENDERER_EXPORTS)\n #pragma comment(lib, \"Zenderer.lib\")\n#endif \/\/ ZEN_API\n\n\/\/ Windowed version for release builds.\n#ifndef _DEBUG\n int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPInst,\n LPSTR lpCmdLine, int nShowCmd)\n#else\n int main(int argc, char* argv[])\n#endif \/\/ _DEBUG\n{\n Init();\n\n asset::CAssetManager Manager; Manager.Init();\n gfx::CWindow Window(800, 600, \"Hello, Zenderer.\");\n\n Window.AttachAssetManager(Manager);\n Window.Init();\n\n sfx::CSound2D Sound;\n \/\/Sound.LoadFromFile(\"Crackle.wav\");\n\n color4f_t Teal(0.0, 1.0, 1.0, 1.0);\n\n gfxcore::CTexture* T = Manager.Create<gfxcore::CTexture>(\n string_t(\"sample.png\"));\n\n gfxcore::CVertexArray Vao;\n gfxcore::DrawBatch D;\n\n gfxcore::index_t i[] = {0, 1, 3, 3, 1, 2};\n\n D.Vertices = new gfxcore::vertex_t[4];\n D.vcount = 4;\n D.Indices = i;\n D.icount = 6;\n\n D.Vertices[0].position = math::vector_t(0, 0);\n D.Vertices[1].position = math::vector_t(T->GetWidth(), 0);\n D.Vertices[2].position = math::vector_t(T->GetWidth(), T->GetHeight());\n D.Vertices[3].position = math::vector_t(0, T->GetHeight());\n\n D.Vertices[0].tc = math::vector_t(1.0, 0.0);\n D.Vertices[1].tc = math::vector_t(1.0, 1.0);\n D.Vertices[2].tc = math::vector_t(0.0, 1.0);\n D.Vertices[3].tc = math::vector_t(0.0, 0.0);\n\n D.Vertices[0].color =\n D.Vertices[1].color =\n D.Vertices[2].color =\n D.Vertices[3].color = color4f_t(1, 1, 1, 1);\n\n Vao.Init();\n Vao.AddData(D);\n Vao.Offload();\n\n D.Vertices[0].position = math::vector_t(0, 0);\n D.Vertices[1].position = math::vector_t(800, 0);\n D.Vertices[2].position = math::vector_t(800, 600);\n D.Vertices[3].position = math::vector_t(0, 600);\n \n gfxcore::CVertexArray FS;\n FS.Init();\n FS.AddData(D);\n FS.Offload();\n\n D.Indices = nullptr;\n delete[] D.Vertices;\n D.vcount = D.icount = 0;\n\n gfx::CQuad Q(32, 32); \n Q.Create().Move(math::vector_t(100, 100));\n Q.SetColor(color4f_t(1));\n\n Window.ToggleVSYNC();\n util::CTimer Timer(60);\n\n gfxcore::CRenderer::EnableAlphaBlending();\n\n gfx::CLight L(Manager, gfx::LightType::ZEN_POINT, Window.GetHeight());\n L.Init();\n L.Enable();\n L.SetBrightness(0.5);\n L.SetColor(1.0, 1.0, 1.0);\n L.SetPosition(200, 100);\n L.Disable();\n\n gfx::CRenderTarget RT(800, 600);\n RT.Init();\n\n double x, y;\n\n while(Window.IsOpen())\n {\n Timer.Start();\n\n \/\/ Handle events\n glfwPollEvents();\n glfwGetCursorPos(Window.GetWindow(), &x, &y);\n\n \/\/ Game logic\n Sound.Update();\n\n RT.Bind();\n RT.Clear();\n T->Bind();\n gfxcore::CRenderer::GetDefaultEffect().Enable();\n gfxcore::CRenderer::GetDefaultEffect().SetParameter(\n \"mv\", math::matrix4x4_t::GetIdentityMatrix());\n Vao.Draw();\n gfxcore::CRenderer::GetDefaultEffect().Disable();\n T->Unbind();\n RT.Unbind();\n\n \/\/ Rendering\n Window.Clear(Teal);\n\n GL(glBindTexture(GL_TEXTURE_2D, RT.GetTexture()));\n gfxcore::CRenderer::GetDefaultEffect().Enable();\n gfxcore::CRenderer::GetDefaultEffect().SetParameter(\n \"mv\", math::matrix4x4_t::GetIdentityMatrix());\n FS.Draw();\n gfxcore::CRenderer::GetDefaultEffect().Disable();\n GL(glBindTexture(GL_TEXTURE_2D, 0));\n\n T->Bind();\n gfxcore::CRenderer::GetDefaultEffect().Enable();\n Vao.Draw();\n gfxcore::CRenderer::GetDefaultEffect().Disable();\n T->Unbind();\n\n Q.Move(x, y);\n Q.Draw();\n\n Window.Update();\n\n \/\/ Finalize\n Timer.Delay();\n }\n\n Vao.Destroy();\n\n Quit();\n\n return 0;\n}\n<commit_msg>FBO render test passed<commit_after>#include <algorithm>\n\n#include \"Zenderer\/Zenderer.hpp\"\n\nusing namespace zen;\n\n\/\/ Here's some perfect sample XML.\nstatic const char* SAMPLE_XML[] = {\n \"<entity type=\\\"QUAD\\\" name=\\\"generic\\\">\",\n \"<position x=\\\"100\\\" y=\\\"200\\\">\",\n \"<\/ >\",\n \"<texture>\",\n \"Tester.tga\",\n \"<\/ >\",\n \"<shader type=\\\"both\\\">\",\n \"<vshader>\",\n \"Tester.vs\",\n \"<\/ >\",\n \"<fshader>\",\n \"Tester.fs\",\n \"<\/ >\",\n \"<\/ >\",\n \"<\/ >\"\n};\n\n#if defined(ZEN_API) && !defined(_DEBUG) && !defined(ZENDERER_EXPORTS)\n #pragma comment(lib, \"Zenderer.lib\")\n#endif \/\/ ZEN_API\n\n\/\/ Windowed version for release builds.\n#ifndef _DEBUG\n int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPInst,\n LPSTR lpCmdLine, int nShowCmd)\n#else\n int main(int argc, char* argv[])\n#endif \/\/ _DEBUG\n{\n Init();\n\n asset::CAssetManager Manager; Manager.Init();\n gfx::CWindow Window(800, 600, \"Hello, Zenderer.\");\n\n Window.AttachAssetManager(Manager);\n Window.Init();\n\n sfx::CSound2D Sound;\n \/\/Sound.LoadFromFile(\"Crackle.wav\");\n\n color4f_t Teal(0.0, 1.0, 1.0, 1.0);\n\n gfxcore::CTexture* T = Manager.Create<gfxcore::CTexture>(\n string_t(\"sample.png\"));\n\n gfxcore::CVertexArray Vao;\n gfxcore::DrawBatch D;\n\n gfxcore::index_t i[] = {0, 1, 3, 3, 1, 2};\n\n D.Vertices = new gfxcore::vertex_t[4];\n D.vcount = 4;\n D.Indices = i;\n D.icount = 6;\n\n D.Vertices[0].position = math::vector_t(0, 0);\n D.Vertices[1].position = math::vector_t(T->GetWidth(), 0);\n D.Vertices[2].position = math::vector_t(T->GetWidth(), T->GetHeight());\n D.Vertices[3].position = math::vector_t(0, T->GetHeight());\n\n D.Vertices[0].tc = math::vector_t(0.0, 1.0);\n D.Vertices[1].tc = math::vector_t(1.0, 1.0);\n D.Vertices[2].tc = math::vector_t(1.0, 0.0);\n D.Vertices[3].tc = math::vector_t(0.0, 0.0);\n\n D.Vertices[0].color =\n D.Vertices[1].color =\n D.Vertices[2].color =\n D.Vertices[3].color = color4f_t(1, 1, 1, 1);\n\n Vao.Init();\n Vao.AddData(D);\n Vao.Offload();\n\n D.Vertices[0].position = math::vector_t(0, 0);\n D.Vertices[1].position = math::vector_t(800, 0);\n D.Vertices[2].position = math::vector_t(800, 600);\n D.Vertices[3].position = math::vector_t(0, 600);\n\n gfxcore::CVertexArray FS;\n FS.Init();\n FS.AddData(D);\n FS.Offload();\n\n D.Indices = nullptr;\n delete[] D.Vertices;\n D.vcount = D.icount = 0;\n\n gfx::CQuad Q(32, 32);\n Q.Create();\n Q.SetColor(color4f_t(1));\n\n Window.ToggleVSYNC();\n util::CTimer Timer(60);\n\n gfxcore::CRenderer::EnableAlphaBlending();\n\n gfx::CLight L(Manager, gfx::LightType::ZEN_POINT, Window.GetHeight());\n L.Init();\n L.Enable();\n L.SetBrightness(0.5);\n L.SetColor(1.0, 1.0, 1.0);\n L.SetPosition(200, 100);\n L.Disable();\n\n gfx::CRenderTarget RT(800, 600);\n RT.Init();\n\n double x, y;\n\n while(Window.IsOpen())\n {\n Timer.Start();\n\n \/\/ Handle events\n glfwPollEvents();\n glfwGetCursorPos(Window.GetWindow(), &x, &y);\n\n \/\/ Game logic\n Sound.Update();\n\n RT.Bind();\n RT.Clear();\n T->Bind();\n gfxcore::CRenderer::GetDefaultEffect().Enable();\n gfxcore::CRenderer::GetDefaultEffect().SetParameter(\n \"proj\", gfxcore::CRenderer::GetProjectionMatrix());\n gfxcore::CRenderer::GetDefaultEffect().SetParameter(\n \"mv\", math::matrix4x4_t::GetIdentityMatrix());\n Vao.Draw();\n gfxcore::CRenderer::GetDefaultEffect().Disable();\n T->Unbind();\n RT.Unbind();\n\n \/\/ Rendering\n Window.Clear(Teal);\n\n GL(glBindTexture(GL_TEXTURE_2D, RT.GetTexture()));\n gfxcore::CRenderer::GetDefaultEffect().Enable();\n FS.Draw();\n gfxcore::CRenderer::GetDefaultEffect().Disable();\n GL(glBindTexture(GL_TEXTURE_2D, 0));\n\n T->Bind();\n gfxcore::CRenderer::GetDefaultEffect().Enable();\n math::matrix4x4_t MV = math::matrix4x4_t::GetIdentityMatrix();\n MV[0][3] = 100.0;\n MV[1][3] = 100.0;\n gfxcore::CRenderer::GetDefaultEffect().SetParameter(\"mv\", MV);\n Vao.Draw();\n gfxcore::CRenderer::GetDefaultEffect().Disable();\n T->Unbind();\n\n Q.Move(x, y);\n Q.Draw();\n\n Window.Update();\n\n \/\/ Finalize\n Timer.Delay();\n }\n\n Vao.Destroy();\n\n Quit();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * FileSystem.cpp\r\n *\r\n * Created on: Jun 20, 2014\r\n * Author: Pimenta\r\n *\/\r\n\r\n\/\/ this\r\n#include \"FileSystem.hpp\"\r\n\r\n\/\/ standard\r\n#include <cstdlib>\r\n\r\nusing namespace std;\r\nusing namespace helpers;\r\n\r\nFileSystem::Folder FileSystem::rootFolder;\r\nuint32_t FileSystem::nextID;\r\nuint32_t FileSystem::localIP;\r\nset<uint32_t> FileSystem::storedFiles;\r\n\r\nFileSystem::File::File() : id(nextID++), size(0), peer1(localIP), peer2(0) {\r\n char tmp[25];\r\n sprintf(tmp, \"www\/files\/%08x\", id);\r\n rename(\"www\/files\/tmp\", tmp);\r\n FILE* fp = fopen(tmp, \"rb\");\r\n if (fp) {\r\n fseek(fp, 0, SEEK_END);\r\n size = ftell(fp);\r\n }\r\n fclose(fp);\r\n}\r\n\r\nvoid FileSystem::File::serialize(ByteQueue& data) {\r\n data.push((const void*)this, 16).push(author);\r\n}\r\n\r\nvoid FileSystem::File::deserialize(ByteQueue& data) {\r\n data.pop((void*)this, 16);\r\n author = data.pop<string>();\r\n}\r\n\r\nByteQueue FileSystem::File::read() {\r\n ByteQueue data;\r\n if (storedFiles.find(id) != storedFiles.end()) { \/\/ if the file is stored here\r\n data.resize(size);\r\n char tmp[25];\r\n sprintf(tmp, \"www\/files\/%08x\", id);\r\n FILE* fp = fopen(tmp, \"rb\");\r\n fread(data.ptr(), size, 1, fp);\r\n fclose(fp);\r\n }\r\n return data;\r\n}\r\n\r\nvoid FileSystem::File::erase() {\r\n char tmp[25];\r\n sprintf(tmp, \"www\/files\/%08x\", id);\r\n remove(tmp);\r\n}\r\n\r\nuint32_t FileSystem::Folder::getTotalFolders() {\r\n uint32_t total = subfolders.size();\r\n for (auto& kv : subfolders)\r\n total += kv.second.getTotalFolders();\r\n return total;\r\n}\r\n\r\nuint32_t FileSystem::Folder::getTotalFiles() {\r\n uint32_t total = 0;\r\n for (auto& kv : subfolders)\r\n total += kv.second.getTotalFiles();\r\n return total + files.size();\r\n}\r\n\r\nuint64_t FileSystem::Folder::getTotalSize() {\r\n int total = 0;\r\n for (auto& kv : subfolders)\r\n total += kv.second.getTotalSize();\r\n for (auto& kv : files)\r\n total += kv.second.size;\r\n return total;\r\n}\r\n\r\nFileSystem::Folder* FileSystem::Folder::findFolder(const string& subPath, Folder** parent) {\r\n if (!parsePath(subPath)) { \/\/ if the path is invalid\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = nullptr;\r\n return nullptr;\r\n }\r\n return findFolder_(subPath, parent);\r\n}\r\n\r\nFileSystem::File* FileSystem::Folder::findFile(const string& subPath, Folder** parent) {\r\n if (!parsePath(subPath)) { \/\/ if the path is invalid\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = nullptr;\r\n return nullptr;\r\n }\r\n return findFile_(subPath, parent);\r\n}\r\n\r\nFileSystem::Folder* FileSystem::Folder::findFirstBottomUp(const string& subPath, string& foundPath) {\r\n if (!parsePath(subPath)) { \/\/ if the path is invalid\r\n foundPath = \"\";\r\n return nullptr;\r\n }\r\n Folder* folder = findFirstBottomUp_(subPath, foundPath);\r\n \/\/ removing duplicated '\/'\r\n if (foundPath.size() > 2 && foundPath[0] == '\/' && foundPath[1] == '\/')\r\n foundPath = foundPath.substr(1, foundPath.size());\r\n return folder;\r\n}\r\n\r\nvoid FileSystem::Folder::serialize(ByteQueue& data) {\r\n data.push(uint32_t(subfolders.size()));\r\n for (auto& kv : subfolders) {\r\n data.push(kv.first);\r\n kv.second.serialize(data);\r\n }\r\n data.push(uint32_t(files.size()));\r\n for (auto& kv : files) {\r\n data.push(kv.first);\r\n kv.second.serialize(data);\r\n }\r\n}\r\n\r\nvoid FileSystem::Folder::deserialize(ByteQueue& data) {\r\n uint32_t subf_size = data.pop<uint32_t>();\r\n for (uint32_t i = 0; i < subf_size; i++) {\r\n string key = data.pop<string>();\r\n subfolders[key].deserialize(data);\r\n }\r\n uint32_t files_size = data.pop<uint32_t>();\r\n for (uint32_t i = 0; i < files_size; i++) {\r\n string key = data.pop<string>();\r\n files[key].deserialize(data);\r\n }\r\n}\r\n\r\nvoid FileSystem::Folder::eraseFiles() {\r\n for (auto& kv : subfolders)\r\n kv.second.eraseFiles();\r\n for (auto& kv : files)\r\n kv.second.erase();\r\n}\r\n\r\nFileSystem::Folder* FileSystem::Folder::findFolder_(const string& subPath, Folder** parent) {\r\n pair<string, string> brokenPath = extractFirst(subPath, '\/');\r\n if (brokenPath.second == \"\") { \/\/ if subPath is a folder name\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = this;\r\n auto folder = subfolders.find(brokenPath.first);\r\n if (folder == subfolders.end()) \/\/ if the folder was not found\r\n return nullptr;\r\n return &folder->second;\r\n }\r\n auto parentFolder = subfolders.find(brokenPath.first);\r\n if (parentFolder == subfolders.end()) { \/\/ if a parent folder was not found\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = nullptr;\r\n return nullptr;\r\n }\r\n \/\/ recursive call\r\n return parentFolder->second.findFolder_(brokenPath.second, parent);\r\n}\r\n\r\nFileSystem::File* FileSystem::Folder::findFile_(const string& subPath, Folder** parent) {\r\n pair<string, string> brokenPath = extractFirst(subPath, '\/');\r\n if (brokenPath.second == \"\") { \/\/ if supPath is a file name\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = this;\r\n auto file = files.find(brokenPath.first);\r\n if (file == files.end()) \/\/ if the file was not found\r\n return nullptr;\r\n return &file->second;\r\n }\r\n auto parentFolder = subfolders.find(brokenPath.first);\r\n if (parentFolder == subfolders.end()) { \/\/ if a parent folder was not found\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = nullptr;\r\n return nullptr;\r\n }\r\n \/\/ recursive call\r\n return parentFolder->second.findFile_(brokenPath.second, parent);\r\n}\r\n\r\nFileSystem::Folder* FileSystem::Folder::findFirstBottomUp_(const string& subPath, string& foundPath) {\r\n pair<string, string> brokenPath = extractFirst(subPath, '\/');\r\n if (brokenPath.second == \"\") { \/\/ if subPath is a folder name\r\n auto folder = subfolders.find(brokenPath.first);\r\n if (folder == subfolders.end()) \/\/ if the folder was not found\r\n return this;\r\n foundPath += brokenPath.first;\r\n return &folder->second;\r\n }\r\n auto parentFolder = subfolders.find(brokenPath.first);\r\n if (parentFolder == subfolders.end()) \/\/ if a parent folder was not found\r\n return this;\r\n foundPath += brokenPath.first;\r\n \/\/ recursive call\r\n return parentFolder->second.findFirstBottomUp_(brokenPath.second, foundPath);\r\n}\r\n\r\nvoid FileSystem::init(uint32_t localIP) {\r\n rootFolder.subfolders.clear();\r\n rootFolder.files.clear();\r\n FileSystem::localIP = localIP;\r\n nextID = 1;\r\n storedFiles.clear();\r\n#ifdef _WIN32\r\n system(\"rmdir \/Q \/S www\\\\files\");\r\n system(\"mkdir www\\\\files\");\r\n#else\r\n system(\"rm -rf www\/files\");\r\n system(\"mkdir www\/files\");\r\n#endif\r\n}\r\n\r\nByteQueue FileSystem::serialize() {\r\n ByteQueue data;\r\n rootFolder.serialize(data);\r\n return data;\r\n}\r\n\r\nvoid FileSystem::deserialize(ByteQueue& data) {\r\n rootFolder.deserialize(data);\r\n}\r\n\r\nbool FileSystem::parseName(const string& name) {\r\n static set<char> allowedChars;\r\n static StaticInitializer staticInitializar([&]() {\r\n for (char c = '0'; c <= '9'; c++)\r\n allowedChars.insert(c);\r\n for (char c = 'a'; c <= 'z'; c++)\r\n allowedChars.insert(c);\r\n for (char c = 'A'; c <= 'Z'; c++)\r\n allowedChars.insert(c);\r\n allowedChars.insert('_');\r\n allowedChars.insert('-');\r\n allowedChars.insert('+');\r\n allowedChars.insert('.');\r\n });\r\n if (!name.size()) \/\/ if the name is empty\r\n return false;\r\n for (int i = 0; i < int(name.size()); i++) { \/\/ check if all chars are allowed\r\n if (allowedChars.find(name[i]) == allowedChars.end())\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\nbool FileSystem::parsePath(const string& path) {\r\n if (!path.size()) \/\/ if the path is empty\r\n return false;\r\n list<string> atoms = explode(path, '\/');\r\n string reassembledPath;\r\n for (auto& folder : atoms) { \/\/ reassemble the exploded path\r\n if (!parseName(folder)) \/\/ if there is an invalid folder name\r\n return false;\r\n reassembledPath += '\/';\r\n reassembledPath += folder;\r\n }\r\n return reassembledPath == path;\r\n}\r\n\r\nFileSystem::Folder* FileSystem::createFolder(const string& fullPath) {\r\n Folder* parent;\r\n Folder* folder = rootFolder.findFolder(fullPath, &parent);\r\n if (!parent || folder) \/\/ if parent folder was not found or the folder exist\r\n return nullptr;\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n return &parent->subfolders[brokenPath.second];\r\n}\r\n\r\nFileSystem::Folder* FileSystem::retrieveFolder(const string& fullPath, string& foundPath) {\r\n foundPath = \"\/\";\r\n if (fullPath == \"\/\") \/\/ returning root folder\r\n return &rootFolder;\r\n return rootFolder.findFirstBottomUp(fullPath, foundPath);\r\n}\r\n\r\nFileSystem::Folder* FileSystem::updateFolder(const string& fullPath, const string& newName) {\r\n if (!parseName(newName)) \/\/ if the new name is invalid\r\n return nullptr;\r\n Folder* parent;\r\n Folder* folder = rootFolder.findFolder(fullPath, &parent);\r\n if (!parent || !folder) \/\/ if parent or folder doesn't exist\r\n return nullptr;\r\n string newNameWithSlash = string(\"\/\") + newName;\r\n \/\/ if the new folder already exist\r\n if (parent->subfolders.find(newNameWithSlash) != parent->subfolders.end())\r\n return nullptr;\r\n Folder* newFolder = &parent->subfolders[newNameWithSlash];\r\n newFolder->subfolders = folder->subfolders;\r\n newFolder->files = folder->files;\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n parent->subfolders.erase(brokenPath.second);\r\n return newFolder;\r\n}\r\n\r\nbool FileSystem::deleteFolder(const string& fullPath) {\r\n Folder* parent;\r\n Folder* folder = rootFolder.findFolder(fullPath, &parent);\r\n if (!parent || !folder) \/\/ if parent of folder doesn't exist\r\n return false;\r\n folder->eraseFiles();\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n parent->subfolders.erase(brokenPath.second);\r\n return true;\r\n}\r\n\r\nFileSystem::File* FileSystem::createFile(const string& fullPath, const string& author) {\r\n Folder* parent;\r\n File* file = rootFolder.findFile(fullPath, &parent);\r\n if (!parent || file) { \/\/ if parent folder was not found or the file exist\r\n remove(\"www\/files\/tmp\");\r\n return nullptr;\r\n }\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n file = &parent->files[brokenPath.second];\r\n file->author = author;\r\n storedFiles.insert(file->id);\r\n return file;\r\n}\r\n\r\nFileSystem::File* FileSystem::createFile(const string& fullPath, ByteQueue& info) {\r\n Folder* parent;\r\n File* file = rootFolder.findFile(fullPath, &parent);\r\n if (!parent || file) \/\/ if parent folder was not found or the file exist\r\n return nullptr;\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n file = &parent->files[brokenPath.second];\r\n file->deserialize(info);\r\n return file;\r\n}\r\n\r\nFileSystem::File* FileSystem::retrieveFile(const string& fullPath) {\r\n return rootFolder.findFile(fullPath);\r\n}\r\n\r\nFileSystem::File* FileSystem::updateFile(const string& fullPath, const string& newName) {\r\n if (!parseName(newName)) \/\/ if the new name is invalid\r\n return nullptr;\r\n Folder* parent;\r\n File* file = rootFolder.findFile(fullPath, &parent);\r\n if (!parent || !file) \/\/ if the parent folder or the file don't exist\r\n return nullptr;\r\n string newNameWithSlash = string(\"\/\") + newName;\r\n \/\/ if the new file already exist\r\n if (parent->files.find(newNameWithSlash) != parent->files.end())\r\n return nullptr;\r\n File* newFile = &parent->files[newNameWithSlash];\r\n *newFile = *file;\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n parent->files.erase(brokenPath.second);\r\n return newFile;\r\n}\r\n\r\nbool FileSystem::deleteFile(const string& fullPath) {\r\n Folder* parent;\r\n File* file = rootFolder.findFile(fullPath, &parent);\r\n if (!parent || !file) \/\/ if the parent folder or the file don't exist\r\n return false;\r\n file->erase();\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n parent->files.erase(brokenPath.second);\r\n return true;\r\n}\r\n\r\nuint32_t FileSystem::getTotalFolders() {\r\n return rootFolder.getTotalFolders();\r\n}\r\n\r\nuint32_t FileSystem::getTotalFiles() {\r\n return rootFolder.getTotalFiles();\r\n}\r\n\r\nuint64_t FileSystem::getTotalSize() {\r\n return rootFolder.getTotalSize();\r\n}\r\n\r\nByteQueue FileSystem::readFile(FILE* fp) {\r\n fseek(fp, 0, SEEK_END);\r\n size_t size = ftell(fp);\r\n fseek(fp, 0, SEEK_SET);\r\n ByteQueue data(size);\r\n fread(data.ptr(), size, 1, fp);\r\n return data;\r\n}\r\n<commit_msg>Fixing bug on file sync<commit_after>\/*\r\n * FileSystem.cpp\r\n *\r\n * Created on: Jun 20, 2014\r\n * Author: Pimenta\r\n *\/\r\n\r\n\/\/ this\r\n#include \"FileSystem.hpp\"\r\n\r\n\/\/ standard\r\n#include <cstdlib>\r\n\r\nusing namespace std;\r\nusing namespace helpers;\r\n\r\nFileSystem::Folder FileSystem::rootFolder;\r\nuint32_t FileSystem::nextID;\r\nuint32_t FileSystem::localIP;\r\nset<uint32_t> FileSystem::storedFiles;\r\n\r\nFileSystem::File::File() : id(nextID++), size(0), peer1(localIP), peer2(0) {\r\n char tmp[25];\r\n sprintf(tmp, \"www\/files\/%08x\", id);\r\n rename(\"www\/files\/tmp\", tmp);\r\n FILE* fp = fopen(tmp, \"rb\");\r\n if (fp) {\r\n fseek(fp, 0, SEEK_END);\r\n size = ftell(fp);\r\n fclose(fp);\r\n }\r\n}\r\n\r\nvoid FileSystem::File::serialize(ByteQueue& data) {\r\n data.push((const void*)this, 16).push(author);\r\n}\r\n\r\nvoid FileSystem::File::deserialize(ByteQueue& data) {\r\n data.pop((void*)this, 16);\r\n author = data.pop<string>();\r\n}\r\n\r\nByteQueue FileSystem::File::read() {\r\n ByteQueue data;\r\n if (storedFiles.find(id) != storedFiles.end()) { \/\/ if the file is stored here\r\n data.resize(size);\r\n char tmp[25];\r\n sprintf(tmp, \"www\/files\/%08x\", id);\r\n FILE* fp = fopen(tmp, \"rb\");\r\n fread(data.ptr(), size, 1, fp);\r\n fclose(fp);\r\n }\r\n return data;\r\n}\r\n\r\nvoid FileSystem::File::erase() {\r\n char tmp[25];\r\n sprintf(tmp, \"www\/files\/%08x\", id);\r\n remove(tmp);\r\n}\r\n\r\nuint32_t FileSystem::Folder::getTotalFolders() {\r\n uint32_t total = subfolders.size();\r\n for (auto& kv : subfolders)\r\n total += kv.second.getTotalFolders();\r\n return total;\r\n}\r\n\r\nuint32_t FileSystem::Folder::getTotalFiles() {\r\n uint32_t total = 0;\r\n for (auto& kv : subfolders)\r\n total += kv.second.getTotalFiles();\r\n return total + files.size();\r\n}\r\n\r\nuint64_t FileSystem::Folder::getTotalSize() {\r\n int total = 0;\r\n for (auto& kv : subfolders)\r\n total += kv.second.getTotalSize();\r\n for (auto& kv : files)\r\n total += kv.second.size;\r\n return total;\r\n}\r\n\r\nFileSystem::Folder* FileSystem::Folder::findFolder(const string& subPath, Folder** parent) {\r\n if (!parsePath(subPath)) { \/\/ if the path is invalid\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = nullptr;\r\n return nullptr;\r\n }\r\n return findFolder_(subPath, parent);\r\n}\r\n\r\nFileSystem::File* FileSystem::Folder::findFile(const string& subPath, Folder** parent) {\r\n if (!parsePath(subPath)) { \/\/ if the path is invalid\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = nullptr;\r\n return nullptr;\r\n }\r\n return findFile_(subPath, parent);\r\n}\r\n\r\nFileSystem::Folder* FileSystem::Folder::findFirstBottomUp(const string& subPath, string& foundPath) {\r\n if (!parsePath(subPath)) { \/\/ if the path is invalid\r\n foundPath = \"\";\r\n return nullptr;\r\n }\r\n Folder* folder = findFirstBottomUp_(subPath, foundPath);\r\n \/\/ removing duplicated '\/'\r\n if (foundPath.size() > 2 && foundPath[0] == '\/' && foundPath[1] == '\/')\r\n foundPath = foundPath.substr(1, foundPath.size());\r\n return folder;\r\n}\r\n\r\nvoid FileSystem::Folder::serialize(ByteQueue& data) {\r\n data.push(uint32_t(subfolders.size()));\r\n for (auto& kv : subfolders) {\r\n data.push(kv.first);\r\n kv.second.serialize(data);\r\n }\r\n data.push(uint32_t(files.size()));\r\n for (auto& kv : files) {\r\n data.push(kv.first);\r\n kv.second.serialize(data);\r\n }\r\n}\r\n\r\nvoid FileSystem::Folder::deserialize(ByteQueue& data) {\r\n uint32_t subf_size = data.pop<uint32_t>();\r\n for (uint32_t i = 0; i < subf_size; i++) {\r\n string key = data.pop<string>();\r\n subfolders[key].deserialize(data);\r\n }\r\n uint32_t files_size = data.pop<uint32_t>();\r\n for (uint32_t i = 0; i < files_size; i++) {\r\n string key = data.pop<string>();\r\n files[key].deserialize(data);\r\n }\r\n}\r\n\r\nvoid FileSystem::Folder::eraseFiles() {\r\n for (auto& kv : subfolders)\r\n kv.second.eraseFiles();\r\n for (auto& kv : files)\r\n kv.second.erase();\r\n}\r\n\r\nFileSystem::Folder* FileSystem::Folder::findFolder_(const string& subPath, Folder** parent) {\r\n pair<string, string> brokenPath = extractFirst(subPath, '\/');\r\n if (brokenPath.second == \"\") { \/\/ if subPath is a folder name\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = this;\r\n auto folder = subfolders.find(brokenPath.first);\r\n if (folder == subfolders.end()) \/\/ if the folder was not found\r\n return nullptr;\r\n return &folder->second;\r\n }\r\n auto parentFolder = subfolders.find(brokenPath.first);\r\n if (parentFolder == subfolders.end()) { \/\/ if a parent folder was not found\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = nullptr;\r\n return nullptr;\r\n }\r\n \/\/ recursive call\r\n return parentFolder->second.findFolder_(brokenPath.second, parent);\r\n}\r\n\r\nFileSystem::File* FileSystem::Folder::findFile_(const string& subPath, Folder** parent) {\r\n pair<string, string> brokenPath = extractFirst(subPath, '\/');\r\n if (brokenPath.second == \"\") { \/\/ if supPath is a file name\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = this;\r\n auto file = files.find(brokenPath.first);\r\n if (file == files.end()) \/\/ if the file was not found\r\n return nullptr;\r\n return &file->second;\r\n }\r\n auto parentFolder = subfolders.find(brokenPath.first);\r\n if (parentFolder == subfolders.end()) { \/\/ if a parent folder was not found\r\n if (parent) \/\/ if the parent folder was requested\r\n *parent = nullptr;\r\n return nullptr;\r\n }\r\n \/\/ recursive call\r\n return parentFolder->second.findFile_(brokenPath.second, parent);\r\n}\r\n\r\nFileSystem::Folder* FileSystem::Folder::findFirstBottomUp_(const string& subPath, string& foundPath) {\r\n pair<string, string> brokenPath = extractFirst(subPath, '\/');\r\n if (brokenPath.second == \"\") { \/\/ if subPath is a folder name\r\n auto folder = subfolders.find(brokenPath.first);\r\n if (folder == subfolders.end()) \/\/ if the folder was not found\r\n return this;\r\n foundPath += brokenPath.first;\r\n return &folder->second;\r\n }\r\n auto parentFolder = subfolders.find(brokenPath.first);\r\n if (parentFolder == subfolders.end()) \/\/ if a parent folder was not found\r\n return this;\r\n foundPath += brokenPath.first;\r\n \/\/ recursive call\r\n return parentFolder->second.findFirstBottomUp_(brokenPath.second, foundPath);\r\n}\r\n\r\nvoid FileSystem::init(uint32_t localIP) {\r\n rootFolder.subfolders.clear();\r\n rootFolder.files.clear();\r\n FileSystem::localIP = localIP;\r\n nextID = 1;\r\n storedFiles.clear();\r\n#ifdef _WIN32\r\n system(\"rmdir \/Q \/S www\\\\files\");\r\n system(\"mkdir www\\\\files\");\r\n#else\r\n system(\"rm -rf www\/files\");\r\n system(\"mkdir www\/files\");\r\n#endif\r\n}\r\n\r\nByteQueue FileSystem::serialize() {\r\n ByteQueue data;\r\n rootFolder.serialize(data);\r\n return data;\r\n}\r\n\r\nvoid FileSystem::deserialize(ByteQueue& data) {\r\n rootFolder.deserialize(data);\r\n}\r\n\r\nbool FileSystem::parseName(const string& name) {\r\n static set<char> allowedChars;\r\n static StaticInitializer staticInitializar([&]() {\r\n for (char c = '0'; c <= '9'; c++)\r\n allowedChars.insert(c);\r\n for (char c = 'a'; c <= 'z'; c++)\r\n allowedChars.insert(c);\r\n for (char c = 'A'; c <= 'Z'; c++)\r\n allowedChars.insert(c);\r\n allowedChars.insert('_');\r\n allowedChars.insert('-');\r\n allowedChars.insert('+');\r\n allowedChars.insert('.');\r\n });\r\n if (!name.size()) \/\/ if the name is empty\r\n return false;\r\n for (int i = 0; i < int(name.size()); i++) { \/\/ check if all chars are allowed\r\n if (allowedChars.find(name[i]) == allowedChars.end())\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\nbool FileSystem::parsePath(const string& path) {\r\n if (!path.size()) \/\/ if the path is empty\r\n return false;\r\n list<string> atoms = explode(path, '\/');\r\n string reassembledPath;\r\n for (auto& folder : atoms) { \/\/ reassemble the exploded path\r\n if (!parseName(folder)) \/\/ if there is an invalid folder name\r\n return false;\r\n reassembledPath += '\/';\r\n reassembledPath += folder;\r\n }\r\n return reassembledPath == path;\r\n}\r\n\r\nFileSystem::Folder* FileSystem::createFolder(const string& fullPath) {\r\n Folder* parent;\r\n Folder* folder = rootFolder.findFolder(fullPath, &parent);\r\n if (!parent || folder) \/\/ if parent folder was not found or the folder exist\r\n return nullptr;\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n return &parent->subfolders[brokenPath.second];\r\n}\r\n\r\nFileSystem::Folder* FileSystem::retrieveFolder(const string& fullPath, string& foundPath) {\r\n foundPath = \"\/\";\r\n if (fullPath == \"\/\") \/\/ returning root folder\r\n return &rootFolder;\r\n return rootFolder.findFirstBottomUp(fullPath, foundPath);\r\n}\r\n\r\nFileSystem::Folder* FileSystem::updateFolder(const string& fullPath, const string& newName) {\r\n if (!parseName(newName)) \/\/ if the new name is invalid\r\n return nullptr;\r\n Folder* parent;\r\n Folder* folder = rootFolder.findFolder(fullPath, &parent);\r\n if (!parent || !folder) \/\/ if parent or folder doesn't exist\r\n return nullptr;\r\n string newNameWithSlash = string(\"\/\") + newName;\r\n \/\/ if the new folder already exist\r\n if (parent->subfolders.find(newNameWithSlash) != parent->subfolders.end())\r\n return nullptr;\r\n Folder* newFolder = &parent->subfolders[newNameWithSlash];\r\n newFolder->subfolders = folder->subfolders;\r\n newFolder->files = folder->files;\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n parent->subfolders.erase(brokenPath.second);\r\n return newFolder;\r\n}\r\n\r\nbool FileSystem::deleteFolder(const string& fullPath) {\r\n Folder* parent;\r\n Folder* folder = rootFolder.findFolder(fullPath, &parent);\r\n if (!parent || !folder) \/\/ if parent of folder doesn't exist\r\n return false;\r\n folder->eraseFiles();\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n parent->subfolders.erase(brokenPath.second);\r\n return true;\r\n}\r\n\r\nFileSystem::File* FileSystem::createFile(const string& fullPath, const string& author) {\r\n Folder* parent;\r\n File* file = rootFolder.findFile(fullPath, &parent);\r\n if (!parent || file) { \/\/ if parent folder was not found or the file exist\r\n remove(\"www\/files\/tmp\");\r\n return nullptr;\r\n }\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n file = &parent->files[brokenPath.second];\r\n file->author = author;\r\n storedFiles.insert(file->id);\r\n return file;\r\n}\r\n\r\nFileSystem::File* FileSystem::createFile(const string& fullPath, ByteQueue& info) {\r\n Folder* parent;\r\n File* file = rootFolder.findFile(fullPath, &parent);\r\n if (!parent || file) \/\/ if parent folder was not found or the file exist\r\n return nullptr;\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n file = &parent->files[brokenPath.second];\r\n file->deserialize(info);\r\n return file;\r\n}\r\n\r\nFileSystem::File* FileSystem::retrieveFile(const string& fullPath) {\r\n return rootFolder.findFile(fullPath);\r\n}\r\n\r\nFileSystem::File* FileSystem::updateFile(const string& fullPath, const string& newName) {\r\n if (!parseName(newName)) \/\/ if the new name is invalid\r\n return nullptr;\r\n Folder* parent;\r\n File* file = rootFolder.findFile(fullPath, &parent);\r\n if (!parent || !file) \/\/ if the parent folder or the file don't exist\r\n return nullptr;\r\n string newNameWithSlash = string(\"\/\") + newName;\r\n \/\/ if the new file already exist\r\n if (parent->files.find(newNameWithSlash) != parent->files.end())\r\n return nullptr;\r\n File* newFile = &parent->files[newNameWithSlash];\r\n *newFile = *file;\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n parent->files.erase(brokenPath.second);\r\n return newFile;\r\n}\r\n\r\nbool FileSystem::deleteFile(const string& fullPath) {\r\n Folder* parent;\r\n File* file = rootFolder.findFile(fullPath, &parent);\r\n if (!parent || !file) \/\/ if the parent folder or the file don't exist\r\n return false;\r\n file->erase();\r\n pair<string, string> brokenPath = extractLast(fullPath, '\/');\r\n parent->files.erase(brokenPath.second);\r\n return true;\r\n}\r\n\r\nuint32_t FileSystem::getTotalFolders() {\r\n return rootFolder.getTotalFolders();\r\n}\r\n\r\nuint32_t FileSystem::getTotalFiles() {\r\n return rootFolder.getTotalFiles();\r\n}\r\n\r\nuint64_t FileSystem::getTotalSize() {\r\n return rootFolder.getTotalSize();\r\n}\r\n\r\nByteQueue FileSystem::readFile(FILE* fp) {\r\n fseek(fp, 0, SEEK_END);\r\n size_t size = ftell(fp);\r\n fseek(fp, 0, SEEK_SET);\r\n ByteQueue data(size);\r\n fread(data.ptr(), size, 1, fp);\r\n return data;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\nnamespace routing\n{\nnamespace transit\n{\ndouble constexpr kTransitMaxSpeedKMpH = 400.0;\n\/\/ @TODO(bykoianko, Zverik) Edge and gate weights should be always valid. This weights should come\n\/\/ from transit graph json. But now it's not so. |kTransitAverageSpeedMPS| should be used now only for\n\/\/ weight calculating at transit section generation stage and the constant should be removed later.\ndouble constexpr kTransitAverageSpeedMPS = 11.0;\n} \/\/ namespace transit\n} \/\/ namespace routing\n<commit_msg>Removing unused kTransitAverageSpeedMPS.<commit_after>#pragma once\n\nnamespace routing\n{\nnamespace transit\n{\ndouble constexpr kTransitMaxSpeedKMpH = 400.0;\n} \/\/ namespace transit\n} \/\/ namespace routing\n<|endoftext|>"} {"text":"<commit_before>#include \"riptide_controllers\/alignment_controller.h\"\n\n#undef debug\n#undef report\n#undef progress\n\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"alignment_controller\");\n AlignmentController ac;\n ros::spin();\n}\n\nvoid AlignmentController::UpdateError() {\n sample_duration = ros::Time::now() - sample_start;\n dt = sample_duration.toSec();\n\n d_y_error = (y_error - last_y_error) \/ dt;\n last_y_error = y_error;\n\n accel.data = y_pid.computeCommand(y_error, d_y_error, sample_duration);\n\n cmd_pub.publish(accel);\n sample_start = ros::Time::now();\n}\n\n\nAlignmentController::AlignmentController() {\n ros::NodeHandle ypid(\"sway_controller\");\n object_sub = nh.subscribe<riptide_msgs::ObjectData>(\"task\/gate\/object_data\", 1, &AlignmentController::ObjectCB, this);\n y_pid.init(ypid, false);\n\n cmd_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/y\", 1);\n sample_start = ros::Time::now();\n}\n\n\/\/ Subscribe to state\/vision\/gate\nvoid AlignmentController::ObjectCB(const riptide_msgs::ObjectData::ConstPtr &msg) {\n \/\/ Y axis in robot frame maps to X axis of camera frame\n y_error = msg->rel_pos.x;\n ROS_INFO(\"%f\", y_error);\n AlignmentController::UpdateError();\n}\n<commit_msg>Began adding depth command to alignment controller<commit_after>#include \"riptide_controllers\/alignment_controller.h\"\n\n#undef debug\n#undef report\n#undef progress\n\nstring[] tasks = {\"gate\", \"pole\"};\nint tindex = 0;\n\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"alignment_controller\");\n AlignmentController ac;\n ros::spin();\n}\n\nvoid AlignmentController::UpdateError() {\n sample_duration = ros::Time::now() - sample_start;\n dt = sample_duration.toSec();\n\n \/\/ We are trying to align: -error = target\n x_error = -x_target;\n y_error = -y_target;\n\n d_x_error = (x_error - last_x_error) \/ dt;\n d_y_error = (y_error - last_y_error) \/ dt;\n\n last_x_error = x_error;\n last_y_error = y_error;\n\n accel_x.data = x_pid.computeCommand(x_error, d_x_error, sample_duration);\n accel_y.data = y_pid.computeCommand(y_error, d_y_error, sample_duration);\n depth.data = d_error + current_depth;\n\n \/\/ Use depth controller to set\n d_pub.publish(depth);\n x_pub.publish(accel_x);\n y_pub.publish(accel_y);\n sample_start = ros::Time::now();\n}\n\n\nAlignmentController::AlignmentController() {\n ros::NodeHandle xpid(\"surge_controller\");\n ros::NodeHandle ypid(\"sway_controller\");\n object_sub = nh.subscribe<riptide_msgs::ObjectData>(\"task\/\" + tasks[tindex] + \"\/object_data\", 1, &AlignmentController::ObjectCB, this);\n depth_sub = nh.subscribe<riptide_msgs::Depth>(\"state\/depth\", 1, &AlignmentController::DepthCB, this);\n\n x_pid.init(xpid, false);\n y_pid.init(ypid, false);\n\n x_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/x\", 1);\n y_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/y\", 1);\n d_pub = nh.advertise<std_msgs::Float32>(\"command\/depth\", 1);\n\n sample_start = ros::Time::now();\n}\n\n\/\/ Subscribe to state\/vision\/<task>\/object_data to get relative position of task.\n\/\/ Task position is the setpoint\nvoid AlignmentController::ObjectCB(const riptide_msgs::ObjectData::ConstPtr &msg) {\n x_target = msg->rel_pos.x;\n y_target = msg->rel_pos.y;\n d_error = -msg->rel_pos.z;\n\n ROS_INFO(\"%f\", y_target);\n AlignmentController::UpdateError();\n}\n\n\/\/ Subscribe to state\/depth to update the target depth passed along to the depth controller\nvoid AlignmentController::DepthCB(const riptide_msgs::ObjectData::ConstPtr &msg) {\n \n}\n<|endoftext|>"} {"text":"<commit_before>#include \"riptide_controllers\/alignment_controller.h\"\n\n#undef debug\n#undef report\n#undef progress\n#define MAX_TASK_ID 1\n\nstring[] tasks = {\"gate\", \"pole\"};\nint current_task_id = 0;\n\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"alignment_controller\");\n AlignmentController ac;\n ros::spin();\n}\n\n\/\/ Function: UpdateError()\n\/\/ Computes and publishes new commands based on incoming alignment data and\n\/\/ target data. There is some clever stuff in here to deal with the two alignment\n\/\/ planes we deal in.\nvoid AlignmentController::UpdateError() {\n sample_duration = ros::Time::now() - sample_start;\n dt = sample_duration.toSec();\n\n error.y = (target.y - task.y);\n error_dot.y = (error.y - last_error.y) \/ dt;\n last_error.y = error.y;\n sway_cmd = y_pid.computeCommand(error.y, error_dot.y, sample_duration);\n\n \/\/ If we are aligning in the YZ plane (forward cam), then X acceleration is\n \/\/ dependent on bounding box width (approximation for distance from task), while\n \/\/ Z acceleration is determined by offset in the Z axis.\n \/\/ If we are aligning in the YX plane (downward cam), then Z acceleration is\n \/\/ dependent on boudning box width, while X acceleration is determined by offset\n \/\/ in the X axis.\n if (alignment_plane == AlignmentCommand.YZ) {\n error.z = (target.z - task.z);\n error.x = (target_bbox_width - task_bbox_width);\n } else if (alignment_plane == AlignmentCommand.YX) {\n error.z = (target_bbox_width - task_bbox_width);\n error.x = (target.x - task.x);\n }\n\n error_dot.x = (error.x - last_error.x) \/ dt;\n last_error.x = error.x;\n surge_cmd = x_pid.computeCommand(error.x, error_dot.x, sample_duration);\n\n error_dot.z = (error.z - last_error.z) \/ dt;\n last_error.z = error.z;\n heave_cmd = z_pid.computeCommand(error.z, error_dot.z, sample_duration);\n\n\n x_pub.publish(surge_cmd);\n y_pub.publish(sway_cmd);\n z_pub.publish(heave_cmd);\n\n sample_start = ros::Time::now();\n}\n\n\/\/ Constructor: AlignmentController()\nAlignmentController::AlignmentController() {\n ros::NodeHandle surge(\"surge_controller\");\n ros::NodeHandle sway(\"sway_controller\");\n ros::NodeHandle heave(\"heave_controller\");\n\n alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(\"task\/\" + tasks[current_task_id] + \"\/alignment\", 1, &AlignmentController::AlignmentCB, this);\n command_sub = nh.subscribe<riptide_msgs::AlignmentCommand>(\"command\/alignment\", 1, &AlignmentController::CommandCB, this);\n\n x_pid.init(surge, false);\n y_pid.init(sway, false);\n z_pid.init(heave, false);\n\n x_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/x\", 1);\n y_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/y\", 1);\n z_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/z\", 1);\n\n sample_start = ros::Time::now();\n}\n\n\/\/ Function: UpdateTaskID\n\/\/ Parameters: id - ID of the new task to subscribe to\n\/\/\nvoid AlignmentController::UpdateTaskID(int id) {\n \/\/ Validate id\n if (id >= 0 && id < MAX_TASK_ID) {\n alignment_sub.shutdown(); \/\/ Unsubscribe from old task topic\n alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(\"task\/\" + tasks[current_task_id] + \"\/alignment\", 1, &AlignmentController::AlignmentCB, this);\n current_task_id = id;\n }\n}\n\n\/\/ Function: AlignmentCB\n\/\/ Parameters: TaskAlignment msg\n\/\/ Subscribe to state\/vision\/<task>\/object_data to get relative position of task.\nvoid AlignmentController::AlignmentCB(const riptide_msgs::TaskAlignment::ConstPtr &msg) {\n task.x = msg.relative_pos.x;\n task.y = msg.relative_pos.y;\n task.z = msg.relative_pos.z;\n\n \/\/ Boudning box width is always captured by the Y coordinate of the bounding box vertices.\n \/\/ This is because we only care about the YZ (forward cam) and YX (downward cam)\n \/\/ planes\n task_bbox_width = abs(msg.bbox.top_left.y - msg.bbox.bottom_right.y);\n\n AlignmentController::UpdateError();\n}\n\n\/\/ Function: CommandCB\n\/\/ Parameters: AlignmentCommand msg\n\/\/ Subscribe to \/command\/alignment to get target alignment relative to task\nvoid AlignmentController::CommandCB(const riptide_msgs::AlignmentCommand::ConstPtr &cmd) {\n alignment_plane = cmd.alignment_plane;\n\n target.x = cmd.target_pos.x;\n target.y = cmd.target_pos.y;\n target.z = cmd.target_pos.z;\n\n target_bbox_width = cmd.bbox_width;\n\n if (cmd.task_id != current_task_id) {\n AlignmentController::UpdateTaskID(cmd.task_id);\n }\n\n AlignmentController::UpdateError();\n}\n<commit_msg>Require target before aligning<commit_after>#include \"riptide_controllers\/alignment_controller.h\"\n\n#undef debug\n#undef report\n#undef progress\n#define MAX_TASK_ID 1\n\nstring[] tasks = {\"gate\", \"pole\"};\nint current_task_id = 0;\n\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"alignment_controller\");\n AlignmentController ac;\n ros::spin();\n}\n\n\/\/ Function: UpdateError()\n\/\/ Computes and publishes new commands based on incoming alignment data and\n\/\/ target data. There is some clever stuff in here to deal with the two alignment\n\/\/ planes we deal in.\nvoid AlignmentController::UpdateError() {\n sample_duration = ros::Time::now() - sample_start;\n dt = sample_duration.toSec();\n\n error.y = (target.y - task.y);\n error_dot.y = (error.y - last_error.y) \/ dt;\n last_error.y = error.y;\n sway_cmd = y_pid.computeCommand(error.y, error_dot.y, sample_duration);\n\n \/\/ If we are aligning in the YZ plane (forward cam), then X acceleration is\n \/\/ dependent on bounding box width (approximation for distance from task), while\n \/\/ Z acceleration is determined by offset in the Z axis.\n \/\/ If we are aligning in the YX plane (downward cam), then Z acceleration is\n \/\/ dependent on boudning box width, while X acceleration is determined by offset\n \/\/ in the X axis.\n if (alignment_plane == AlignmentCommand.YZ) {\n error.z = (target.z - task.z);\n error.x = (target_bbox_width - task_bbox_width);\n } else if (alignment_plane == AlignmentCommand.YX) {\n error.z = (target_bbox_width - task_bbox_width);\n error.x = (target.x - task.x);\n }\n\n error_dot.x = (error.x - last_error.x) \/ dt;\n last_error.x = error.x;\n surge_cmd = x_pid.computeCommand(error.x, error_dot.x, sample_duration);\n\n error_dot.z = (error.z - last_error.z) \/ dt;\n last_error.z = error.z;\n heave_cmd = z_pid.computeCommand(error.z, error_dot.z, sample_duration);\n\n\n x_pub.publish(surge_cmd);\n y_pub.publish(sway_cmd);\n z_pub.publish(heave_cmd);\n\n sample_start = ros::Time::now();\n}\n\n\/\/ Constructor: AlignmentController()\nAlignmentController::AlignmentController() {\n ros::NodeHandle surge(\"surge_controller\");\n ros::NodeHandle sway(\"sway_controller\");\n ros::NodeHandle heave(\"heave_controller\");\n\n alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(\"task\/\" + tasks[current_task_id] + \"\/alignment\", 1, &AlignmentController::AlignmentCB, this);\n command_sub = nh.subscribe<riptide_msgs::AlignmentCommand>(\"command\/alignment\", 1, &AlignmentController::CommandCB, this);\n\n x_pid.init(surge, false);\n y_pid.init(sway, false);\n z_pid.init(heave, false);\n\n x_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/x\", 1);\n y_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/y\", 1);\n z_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/z\", 1);\n\n sample_start = ros::Time::now();\n}\n\n\/\/ Function: UpdateTaskID\n\/\/ Parameters: id - ID of the new task to subscribe to\n\/\/\nvoid AlignmentController::UpdateTaskID(int id) {\n \/\/ Validate id\n if (id >= 0 && id < MAX_TASK_ID) {\n alignment_sub.shutdown(); \/\/ Unsubscribe from old task topic\n alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(\"task\/\" + tasks[current_task_id] + \"\/alignment\", 1, &AlignmentController::AlignmentCB, this);\n current_task_id = id;\n }\n}\n\n\/\/ Function: AlignmentCB\n\/\/ Parameters: TaskAlignment msg\n\/\/ Subscribe to state\/vision\/<task>\/object_data to get relative position of task.\nvoid AlignmentController::AlignmentCB(const riptide_msgs::TaskAlignment::ConstPtr &msg) {\n if (pid_initialized) {\n task.x = msg.relative_pos.x;\n task.y = msg.relative_pos.y;\n task.z = msg.relative_pos.z;\n\n \/\/ Boudning box width is always captured by the Y coordinate of the bounding box vertices.\n \/\/ This is because we only care about the YZ (forward cam) and YX (downward cam)\n \/\/ planes\n task_bbox_width = abs(msg.bbox.top_left.y - msg.bbox.bottom_right.y);\n\n AlignmentController::UpdateError();\n }\n}\n\n\/\/ Function: CommandCB\n\/\/ Parameters: AlignmentCommand msg\n\/\/ Subscribe to \/command\/alignment to get target alignment relative to task\nvoid AlignmentController::CommandCB(const riptide_msgs::AlignmentCommand::ConstPtr &cmd) {\n alignment_plane = cmd.alignment_plane;\n\n target.x = cmd.target_pos.x;\n target.y = cmd.target_pos.y;\n target.z = cmd.target_pos.z;\n\n target_bbox_width = cmd.bbox_width;\n\n if (cmd.task_id != current_task_id) {\n AlignmentController::UpdateTaskID(cmd.task_id);\n }\n\n AlignmentController::UpdateError();\n\n if (!pid_initialized)\n pid_initialized = true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is 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\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/\/\/ \\author James Hughes\n\/\/\/ \\date September 2012\n\/\/\/ \\brief Not sure this file should go in Modules\/Render. But it is an \n\/\/\/ auxiliary file to the ViewScene render module.\n\n#include <QMouseEvent>\n#include <QWheelEvent>\n#include <QTimer>\n#include <Core\/Application\/Application.h>\n\n#include \"GLWidget.h\"\n\nusing namespace SCIRun::Gui;\nusing Spire::Vector2;\n\n\/\/------------------------------------------------------------------------------\nGLWidget::GLWidget(QtGLContext* context) :\n QGLWidget(context),\n mContext(new GLContext(this))\n{\n \/\/\/ \\todo Implement this intelligently. This function is called everytime\n \/\/\/ there is a new graphics context.\n std::vector<std::string> shaderSearchDirs;\n \n auto shadersInBinDirectory = SCIRun::Core::Application::Instance().executablePath() \/ \"Shaders\";\n shaderSearchDirs.push_back(shadersInBinDirectory.string());\n\n#ifdef SPIRE_USE_STD_THREADS\n mGraphics = std::shared_ptr<Spire::SCIRun::SRInterface>(\n new Spire::SCIRun::SRInterface(\n std::dynamic_pointer_cast<Spire::Context>(mContext),\n shaderSearchDirs, true));\n#else\n mGraphics = std::shared_ptr<Spire::SCIRun::SRInterface>(\n new Spire::SCIRun::SRInterface(\n std::dynamic_pointer_cast<Spire::Context>(mContext),\n shaderSearchDirs, false));\n mTimer = new QTimer(this);\n connect(mTimer, SIGNAL(timeout()), this, SLOT(updateRenderer()));\n mTimer->start(35);\n#endif\n\n \/\/\/ \\todo Where should we store common shader names?\n mGraphics->getStuPipe()->addPersistentShader(\n \"UniformColor\", \n { {\"UniformColor.vs\", Spire::StuInterface::VERTEX_SHADER}, \n {\"UniformColor.fs\", Spire::StuInterface::FRAGMENT_SHADER},\n });\n\n \/\/ We must disable auto buffer swap on the 'paintEvent'.\n setAutoBufferSwap(false);\n}\n\n\/\/------------------------------------------------------------------------------\nGLWidget::~GLWidget()\n{\n \/\/ Need to inform module that the context is being destroyed.\n if (mGraphics != nullptr)\n {\n std::cout << \"Terminating spire.\" << std::endl;\n mGraphics->terminate();\n mGraphics.reset();\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::initializeGL()\n{\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::mouseMoveEvent(QMouseEvent* event)\n{\n \/\/\/ \\todo Include specific button info.\n mGraphics->inputMouseMove(Vector2<int32_t>(event->x(), event->y()));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::mousePressEvent(QMouseEvent* event)\n{\n \/\/\/ \\todo Include specific button info.\n mGraphics->inputMouseDown(Vector2<int32_t>(event->x(), event->y()));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::mouseReleaseEvent(QMouseEvent* event)\n{\n \/\/\/ \\todo Include specific button info.\n mGraphics->inputMouseUp(Vector2<int32_t>(event->x(), event->y()));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::wheelEvent(QWheelEvent * event)\n{\n mGraphics->inputMouseWheel(event->delta());\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::resizeGL(int width, int height)\n{\n mGraphics->eventResize(static_cast<int32_t>(width),\n static_cast<int32_t>(height));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::updateRenderer()\n{\n mContext->makeCurrent();\n mGraphics->doFrame();\n mContext->swapBuffers();\n}\n\n\n<commit_msg>Removing initializer lists for MSVC.<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is 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\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/\/\/ \\author James Hughes\n\/\/\/ \\date September 2012\n\/\/\/ \\brief Not sure this file should go in Modules\/Render. But it is an \n\/\/\/ auxiliary file to the ViewScene render module.\n\n#include <QMouseEvent>\n#include <QWheelEvent>\n#include <QTimer>\n#include <Core\/Application\/Application.h>\n\n#include \"GLWidget.h\"\n\nusing namespace SCIRun::Gui;\nusing Spire::Vector2;\n\n\/\/------------------------------------------------------------------------------\nGLWidget::GLWidget(QtGLContext* context) :\n QGLWidget(context),\n mContext(new GLContext(this))\n{\n \/\/\/ \\todo Implement this intelligently. This function is called everytime\n \/\/\/ there is a new graphics context.\n std::vector<std::string> shaderSearchDirs;\n \n auto shadersInBinDirectory = SCIRun::Core::Application::Instance().executablePath() \/ \"Shaders\";\n shaderSearchDirs.push_back(shadersInBinDirectory.string());\n\n#ifdef SPIRE_USE_STD_THREADS\n mGraphics = std::shared_ptr<Spire::SCIRun::SRInterface>(\n new Spire::SCIRun::SRInterface(\n std::dynamic_pointer_cast<Spire::Context>(mContext),\n shaderSearchDirs, true));\n#else\n mGraphics = std::shared_ptr<Spire::SCIRun::SRInterface>(\n new Spire::SCIRun::SRInterface(\n std::dynamic_pointer_cast<Spire::Context>(mContext),\n shaderSearchDirs, false));\n mTimer = new QTimer(this);\n connect(mTimer, SIGNAL(timeout()), this, SLOT(updateRenderer()));\n mTimer->start(35);\n#endif\n\n \/\/\/ \\todo Where should we store common shader names?\n std::vector<std::tuple<std::string, Spire::StuInterface::SHADER_TYPES>> shaderFiles;\n shaderFiles.push_back(std::make_pair(\"UniformColor.vs\", Spire::StuInterface::VERTEX_SHADER));\n shaderFiles.push_back(std::make_pair(\"UniformColor.fs\", Spire::StuInterface::FRAGMENT_SHADER));\n\n mGraphics->getStuPipe()->addPersistentShader(\n \"UniformColor\", \n shaderFiles);\n\/\/ { {\"UniformColor.vs\", Spire::StuInterface::VERTEX_SHADER}, \n\/\/ {\"UniformColor.fs\", Spire::StuInterface::FRAGMENT_SHADER},\n\/\/ });\n\n \/\/ We must disable auto buffer swap on the 'paintEvent'.\n setAutoBufferSwap(false);\n}\n\n\/\/------------------------------------------------------------------------------\nGLWidget::~GLWidget()\n{\n \/\/ Need to inform module that the context is being destroyed.\n if (mGraphics != nullptr)\n {\n std::cout << \"Terminating spire.\" << std::endl;\n mGraphics->terminate();\n mGraphics.reset();\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::initializeGL()\n{\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::mouseMoveEvent(QMouseEvent* event)\n{\n \/\/\/ \\todo Include specific button info.\n mGraphics->inputMouseMove(Vector2<int32_t>(event->x(), event->y()));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::mousePressEvent(QMouseEvent* event)\n{\n \/\/\/ \\todo Include specific button info.\n mGraphics->inputMouseDown(Vector2<int32_t>(event->x(), event->y()));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::mouseReleaseEvent(QMouseEvent* event)\n{\n \/\/\/ \\todo Include specific button info.\n mGraphics->inputMouseUp(Vector2<int32_t>(event->x(), event->y()));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::wheelEvent(QWheelEvent * event)\n{\n mGraphics->inputMouseWheel(event->delta());\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::resizeGL(int width, int height)\n{\n mGraphics->eventResize(static_cast<int32_t>(width),\n static_cast<int32_t>(height));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid GLWidget::updateRenderer()\n{\n mContext->makeCurrent();\n mGraphics->doFrame();\n mContext->swapBuffers();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * =====================================================================================\n *\n * Filename: TGM_Tangram.cpp\n *\n * Description: \n *\n * Created: 08\/22\/2012 08:38:37 PM\n * Revision: none\n * Compiler: gcc\n *\n * Author: Jiantao Wu (), \n * Inistitution: Boston College\n *\n * =====================================================================================\n *\/\n\n#include <cstdio>\n#include <cstdlib>\n\n#include \"TGM_Array.h\"\n#include \"TGM_Parameters.h\"\n#include \"TGM_FragLenTable.h\"\n#include \"TGM_LibTable.h\"\n#include \"TGM_BamPair.h\"\n#include \"TGM_Detector.h\"\n#include \"TGM_Reference.h\"\n#include \"TGM_Aligner.h\"\n#include \"TGM_Printer.h\"\n\n#include \"api\/BamMultiReader.h\"\n\nusing namespace std;\nusing namespace Tangram;\nusing namespace BamTools;\n\nint main(int argc, char *argv[])\n{\n DetectPars detectPars;\n AlignerPars alignerPars;\n Parameters parameters(detectPars, alignerPars);\n parameters.Set((const char**) argv, argc);\n\n vector<string> filenames;\n parameters.SetBamFilenames(filenames);\n\n BamMultiReader bamMultiReader;\n bamMultiReader.Open(filenames);\n bamMultiReader.LocateIndexes();\n\n LibTable libTable;\n libTable.Read(detectPars.fpLibInput, detectPars.maxFragDiff);\n\n FragLenTable fragLenTable;\n fragLenTable.Read(detectPars.fpHistInput);\n\n parameters.ParseRangeStr(bamMultiReader);\n parameters.SetRange(bamMultiReader, libTable.GetFragLenMax());\n\n BamPairTable bamPairTable(libTable, fragLenTable, detectPars.minSoftSize, detectPars.minMQ, detectPars.spMinMQ);\n\n BamAlignment alignment;\n while(bamMultiReader.GetNextAlignment(alignment))\n {\n bamPairTable.Update(alignment);\n }\n\n fragLenTable.Destory();\n\n Detector detector(detectPars, libTable, bamPairTable);\n detector.Init();\n\n detector.CallEvents();\n\n const Reference* pRef = NULL;\n const Aligner* pAligner = NULL;\n\n Reference reference;\n Aligner aligner(detector, bamPairTable, alignerPars, reference, libTable);\n\n if (alignerPars.fpRefInput != NULL)\n {\n \/\/ always load the whole chromosome reference\n reference.Read(alignerPars.fpRefInput, detectPars.refID, -1, -1);\n reference.CreateFamilyToZA(*(libTable.GetSpecialRefNames()));\n\n aligner.Map();\n\n pRef = &reference;\n pAligner = &aligner;\n }\n\n Printer printer(&detector, detectPars, pAligner, pRef, libTable, bamPairTable);\n printer.Print();\n\n bamMultiReader.Close();\n return EXIT_SUCCESS;\n}\n\n<commit_msg>Change the process of locating the bam index files according to Derek's suggestion<commit_after>\/*\n * =====================================================================================\n *\n * Filename: TGM_Tangram.cpp\n *\n * Description: \n *\n * Created: 08\/22\/2012 08:38:37 PM\n * Revision: none\n * Compiler: gcc\n *\n * Author: Jiantao Wu (), \n * Inistitution: Boston College\n *\n * =====================================================================================\n *\/\n\n#include <cstdio>\n#include <cstdlib>\n\n#include \"TGM_Array.h\"\n#include \"TGM_Parameters.h\"\n#include \"TGM_FragLenTable.h\"\n#include \"TGM_LibTable.h\"\n#include \"TGM_BamPair.h\"\n#include \"TGM_Detector.h\"\n#include \"TGM_Reference.h\"\n#include \"TGM_Aligner.h\"\n#include \"TGM_Printer.h\"\n\n#include \"api\/BamMultiReader.h\"\n\nusing namespace std;\nusing namespace Tangram;\nusing namespace BamTools;\n\nint main(int argc, char *argv[])\n{\n \/\/ load the command line arguments\n DetectPars detectPars;\n AlignerPars alignerPars;\n Parameters parameters(detectPars, alignerPars);\n parameters.Set((const char**) argv, argc);\n\n \/\/ load the input bam file names\n vector<string> filenames;\n parameters.SetBamFilenames(filenames);\n\n \/\/ open the bam files with bam multi reader\n BamMultiReader bamMultiReader;\n bamMultiReader.Open(filenames);\n\n \/\/ make sure we have the index files at with the input bam files\n if (!bamMultiReader.LocateIndexes())\n {\n \/\/ fail to locate the index files\n \/\/ we need to create them if necessary\n if (!bamMultiReader.CreateIndexes()) \n TGM_ErrQuit(\"ERROR: Cannot locate or create the index files for the input bam files.\\n\");\n }\n\n \/\/ read the library information table\n LibTable libTable;\n libTable.Read(detectPars.fpLibInput, detectPars.maxFragDiff);\n\n \/\/ read the fragment length distribution table\n FragLenTable fragLenTable;\n fragLenTable.Read(detectPars.fpHistInput);\n\n \/\/ where should we start to call the SV events\n parameters.ParseRangeStr(bamMultiReader);\n parameters.SetRange(bamMultiReader, libTable.GetFragLenMax());\n\n BamPairTable bamPairTable(libTable, fragLenTable, detectPars.minSoftSize, detectPars.minMQ, detectPars.spMinMQ);\n\n \/\/ iterate through the bam files and fill the bam pair table\n BamAlignment alignment;\n while(bamMultiReader.GetNextAlignment(alignment))\n {\n bamPairTable.Update(alignment);\n }\n\n \/\/ clean the fragnment length table\n fragLenTable.Destory();\n\n \/\/ call the SV events with read-pair signal\n Detector detector(detectPars, libTable, bamPairTable);\n detector.Init();\n detector.CallEvents();\n\n const Reference* pRef = NULL;\n const Aligner* pAligner = NULL;\n\n Reference reference;\n Aligner aligner(detector, bamPairTable, alignerPars, reference, libTable);\n\n \/\/ call the SV events with split-read signal\n if (alignerPars.fpRefInput != NULL)\n {\n \/\/ always load the whole chromosome reference\n reference.Read(alignerPars.fpRefInput, detectPars.refID, -1, -1);\n reference.CreateFamilyToZA(*(libTable.GetSpecialRefNames()));\n\n aligner.Map();\n\n pRef = &reference;\n pAligner = &aligner;\n }\n\n \/\/ print out the events (vcf format)\n Printer printer(&detector, detectPars, pAligner, pRef, libTable, bamPairTable);\n printer.Print();\n\n \/\/ clean up and quit\n bamMultiReader.Close();\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nLibrary: IntersonArray\n\nCopyright Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved.\n\nLicensed under the Apache License, Version 2.0 ( the \"License\" );\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n#pragma unmanaged\n#include \"IntersonArrayCxxImagingContainer.h\"\n#include <iostream>\n#pragma managed\n\n#include <vcclr.h>\n#include <msclr\/marshal_cppstd.h>\n#include <msclr\/auto_gcroot.h>\n\n#using \"IntersonArray.dll\"\n\nnamespace IntersonArrayCxx\n{\n\nnamespace Imaging\n{\n\n\/\/\n\/\/ Begin Capture\n\/\/\nref class NewRFImageHandler\n{\npublic:\n\n typedef Container::NewRFImageCallbackType NewRFImageCallbackType;\n\n typedef IntersonArrayCxx::Imaging::Container::RFPixelType RFPixelType;\n typedef IntersonArrayCxx::Imaging::Container::RFImagePixelType RFImagePixelType;\n typedef cli::array< RFPixelType, 2 > RFArrayType;\n\n NewRFImageHandler( RFArrayType ^managedRFBuffer ):\n NewRFImageCallback( NULL ),\n NewRFImageCallbackClientData( NULL ),\n bufferWidth( Container::MAX_RFSAMPLES ),\n bufferHeight( Container::NBOFLINES ),\n NativeRFBuffer(new RFImagePixelType[Container::MAX_RFSAMPLES\n * Container::NBOFLINES] ),\n ManagedRFBuffer( managedRFBuffer )\n {\n }\n\n ~NewRFImageHandler()\n {\n delete [] NativeRFBuffer;\n }\n\n void HandleNewRFImage( IntersonArray::Imaging::Capture ^scan2D,\n System::EventArgs ^eventArgs )\n {\n if ( this->NewRFImageCallback != NULL )\n {\n for ( int ii = 0; ii < bufferHeight; ++ii )\n {\n for ( int jj = 0; jj < bufferWidth; ++jj )\n {\n this->NativeRFBuffer[bufferWidth * ii + jj] = (short)\n this->ManagedRFBuffer[ii, jj];\n }\n }\n this->NewRFImageCallback( this->NativeRFBuffer,\n this->NewRFImageCallbackClientData );\n }\n }\n\n void SetImageSize( int width, int height )\n {\n \/\/bufferWidth = width;\n \/\/bufferHeight = height;\n }\n\n void SetNewRFImageCallback( NewRFImageCallbackType callback,\n void *clientData )\n {\n this->NewRFImageCallback = callback;\n this->NewRFImageCallbackClientData = clientData;\n }\n\nprivate:\n NewRFImageCallbackType NewRFImageCallback;\n void * NewRFImageCallbackClientData;\n RFImagePixelType * NativeRFBuffer;\n RFArrayType ^ ManagedRFBuffer;\n int bufferWidth;\n int bufferHeight;\n};\n\n\nref class NewImageHandler\n{\npublic:\n typedef Container::NewImageCallbackType NewImageCallbackType;\n\n typedef IntersonArrayCxx::Imaging::Container::PixelType PixelType;\n typedef cli::array< byte, 2 > ArrayType;\n\n NewImageHandler( ArrayType ^managedBuffer ):\n NewImageCallback( NULL ),\n NewImageCallbackClientData( NULL ),\n bufferWidth( Container::MAX_SAMPLES ),\n bufferHeight( Container::NBOFLINES ),\n NativeBuffer( new PixelType[Container::MAX_SAMPLES *\n Container::NBOFLINES ] ),\n ManagedBuffer( managedBuffer )\n {\n std::cout << \"Conatiner NBOFLINES: \" << Container::NBOFLINES << std::endl;\n\n }\n\n ~NewImageHandler()\n {\n delete [] NativeBuffer;\n }\n\n void HandleNewImage( IntersonArray::Imaging::Capture ^scan2D,\n System::EventArgs ^eventArgs )\n {\n if ( this->NewImageCallback != NULL )\n {\n for ( int ii = 0; ii < bufferHeight; ++ii )\n {\n for ( int jj = 0; jj < bufferWidth; ++jj )\n {\n this->NativeBuffer[bufferWidth * ii + jj] =\n this->ManagedBuffer[ii, jj];\n }\n }\n this->NewImageCallback( this->NativeBuffer,\n this->NewImageCallbackClientData );\n }\n }\n\n void SetImageSize( int width, int height )\n {\n \/\/ bufferWidth = width;\n \/\/ bufferHeight = height;\n }\n\n void SetNewImageCallback( NewImageCallbackType callback,\n void *clientData )\n {\n this->NewImageCallback = callback;\n this->NewImageCallbackClientData = clientData;\n }\n\nprivate:\n NewImageCallbackType NewImageCallback;\n void * NewImageCallbackClientData;\n PixelType * NativeBuffer;\n ArrayType ^ ManagedBuffer;\n int bufferWidth;\n int bufferHeight;\n};\n\n\/\/ End Capture\n\nclass ContainerImpl\n{\npublic:\n typedef cli::array< Container::PixelType, 2 > ArrayType;\n typedef cli::array< Container::RFPixelType, 2 > RFArrayType;\n\n typedef Container::NewImageCallbackType NewImageCallbackType;\n typedef Container::NewRFImageCallbackType NewRFImageCallbackType;\n\n ContainerImpl()\n {\n WrappedScanConverter = gcnew IntersonArray::Imaging::ScanConverter();\n WrappedImageBuilding = gcnew IntersonArray::Imaging::ImageBuilding();\n WrappedCapture = gcnew IntersonArray::Imaging::Capture();\n\n Buffer = gcnew ArrayType( Container::NBOFLINES, Container::MAX_SAMPLES );\n Handler = gcnew NewImageHandler( Buffer );\n HandlerDelegate = gcnew\n IntersonArray::Imaging::Capture::NewImageHandler( Handler,\n & NewImageHandler::HandleNewImage );\n WrappedCapture->NewImageTick += HandlerDelegate;\n\n RFBuffer = gcnew RFArrayType(Container::NBOFLINES , Container::MAX_RFSAMPLES);\n RFHandler = gcnew NewRFImageHandler( RFBuffer );\n RFHandlerDelegate = gcnew\n IntersonArray::Imaging::Capture::NewImageHandler( RFHandler,\n & NewRFImageHandler::HandleNewRFImage );\n }\n\n ~ContainerImpl()\n {\n WrappedCapture->NewImageTick -= RFHandlerDelegate;\n WrappedCapture->NewImageTick -= HandlerDelegate;\n }\n\n bool GetCompound()\n {\n return WrappedScanConverter->Compound;\n }\n\n void SetCompound( bool value )\n {\n WrappedScanConverter->Compound = value;\n }\n\n bool GetDoubler()\n {\n return WrappedScanConverter->Doubler;\n }\n\n void SetDoubler( bool value )\n {\n WrappedScanConverter->Doubler = value;\n }\n\n int GetHeightScan() const\n {\n return WrappedScanConverter->HeightScan;\n }\n\n float GetMmPerPixel() const\n {\n return WrappedScanConverter->MmPerPixel;\n }\n\n double GetTrueDepth() const\n {\n return WrappedScanConverter->TrueDepth;\n }\n\n int GetWidthScan() const\n {\n return WrappedScanConverter->WidthScan;\n }\n\n int GetZeroOfYScale() const\n {\n return WrappedScanConverter->ZeroOfYScale;\n }\n\n Container::ScanConverterError HardInitScanConverter( int depth,\n int widthScan, int heightScan, int steering )\n {\n \n return static_cast< Container::ScanConverterError >(\n WrappedScanConverter->HardInitScanConverter( depth, widthScan,\n heightScan, steering, WrappedCapture.get(),\n WrappedImageBuilding.get() ) );\n }\n\n Container::ScanConverterError IdleInitScanConverter( int depth,\n int widthScan, int heightScan, short idleId, int idleSteering,\n bool idleDoubler, bool idleCompound, int idleCompoundAngle )\n {\n return static_cast< Container::ScanConverterError >(\n WrappedScanConverter->IdleInitScanConverter( depth, widthScan,\n heightScan, idleId, idleSteering, idleDoubler, idleCompound,\n idleCompoundAngle, WrappedImageBuilding.get() ) );\n }\n\n \/\/ \n \/\/ Begin Capture\n \/\/\n bool GetFrameAvg()\n {\n return WrappedCapture->FrameAvg;\n }\n\n void SetFrameAvg( bool value)\n {\n WrappedCapture->FrameAvg = value;\n }\n\n bool GetRFData()\n {\n return WrappedCapture->RFData;\n }\n\n void SetRFData( bool value )\n {\n if (value){\n this->hwControls->ReadFPGAVersion();\n }\n WrappedCapture->RFData = value;\n \/\/Set correct image handler\n if (value){\n WrappedCapture->NewImageTick -= HandlerDelegate;\n WrappedCapture->NewImageTick += RFHandlerDelegate;\n }\n else{\n WrappedCapture->NewImageTick -= RFHandlerDelegate;\n WrappedCapture->NewImageTick += HandlerDelegate;\n }\n }\n\n double GetScanOn()\n {\n return WrappedCapture->ScanOn;\n }\n\n void AbortScan()\n {\n WrappedCapture->AbortScan();\n }\n\n void DisposeScan()\n {\n WrappedCapture->DisposeScan();\n }\n\n void StartReadScan()\n {\n WrappedCapture->StartReadScan( (ArrayType ^)Buffer );\n }\n\n void StartRFReadScan()\n {\n WrappedCapture->StartRFReadScan( (RFArrayType ^)RFBuffer );\n }\n\n void StopReadScan()\n {\n WrappedCapture->StopReadScan();\n }\n\n void SetNewImageCallback( NewImageCallbackType callback,\n void *clientData = 0 )\n {\n this->Handler->SetNewImageCallback( callback, clientData );\n \n \/\/this->Handler->SetImageSize( this->GetWidthScan(),\n \/\/ this->GetHeightScan() );\n }\n\n void SetNewRFImageCallback( NewRFImageCallbackType callback,\n void *clientData = 0 )\n {\n this->RFHandler->SetNewRFImageCallback( callback, clientData );\n this->RFHandler->SetImageSize(Container::MAX_RFSAMPLES, Container::NBOFLINES);\n }\n void SetHWControls(IntersonArrayCxx::Controls::HWControls * controls)\n {\n this->hwControls = controls;\n }\n\n \/\/ \n \/\/ Begin Wrapped ImageBuilding\n \/\/\n\nprivate:\n IntersonArrayCxx::Controls::HWControls * hwControls;\n msclr::auto_gcroot< IntersonArray::Imaging::ScanConverter ^ >\n WrappedScanConverter;\n msclr::auto_gcroot< IntersonArray::Imaging::ImageBuilding ^ >\n WrappedImageBuilding;\n msclr::auto_gcroot< IntersonArray::Imaging::Capture ^ >\n WrappedCapture;\n\n gcroot< ArrayType ^ > Buffer;\n gcroot< RFArrayType ^ > RFBuffer;\n gcroot< NewImageHandler ^ > Handler;\n gcroot< NewRFImageHandler ^ > RFHandler;\n\n gcroot< IntersonArray::Imaging::Capture::NewImageHandler ^ >\n HandlerDelegate;\n gcroot< IntersonArray::Imaging::Capture::NewImageHandler ^ >\n RFHandlerDelegate;\n\n};\n\n\n#pragma unmanaged\n\nContainer\n::Container():\n Impl( new ContainerImpl() )\n{\n}\n\n\nContainer\n::~Container()\n{\n delete Impl;\n}\n\n\nbool\nContainer\n::GetCompound()\n{\n return Impl->GetCompound();\n}\n\n\nvoid\nContainer\n::SetCompound( bool value )\n{\n Impl->SetCompound( value );\n}\n\n\nbool\nContainer\n::GetDoubler()\n{\n return Impl->GetDoubler();\n}\n\n\nvoid\nContainer\n::SetDoubler( bool value )\n{\n Impl->SetDoubler( value );\n}\n\n\nint\nContainer\n::GetHeightScan() const\n{\n return Impl->GetHeightScan();\n}\n\n\nfloat\nContainer\n::GetMmPerPixel() const\n{\n return Impl->GetMmPerPixel();\n}\n\n\ndouble\nContainer\n::GetTrueDepth() const\n{\n return Impl->GetMmPerPixel();\n}\n\n\nint\nContainer\n::GetWidthScan() const\n{\n return Impl->GetWidthScan();\n}\n\n\nint\nContainer\n::GetZeroOfYScale() const\n{\n return Impl->GetZeroOfYScale();\n}\n\n\nContainer::ScanConverterError\nContainer\n::HardInitScanConverter( int depth, int widthScan, int heightScan,\n int steering )\n{\n return Impl->HardInitScanConverter( depth, widthScan, heightScan,\n steering );\n}\n\n\nContainer::ScanConverterError\nContainer\n::IdleInitScanConverter( int depth, int width, int height, short idleId,\n int idleSteering, bool idleDoubler, bool idleCompound,\n int idleCompoundAngle )\n{\n return Impl->IdleInitScanConverter( depth, width, height, idleId,\n idleSteering, idleDoubler, idleCompound, idleCompoundAngle );\n}\n\n\/\/\n\/\/ Begin Capture\n\/\/\nbool\nContainer\n::GetRFData()\n{\n return Impl->GetRFData();\n}\n\nvoid\nContainer\n::SetRFData( bool transferOn )\n{\n Impl->SetRFData( transferOn );\n}\n\n\nbool\nContainer\n::GetFrameAvg()\n{\n return Impl->GetFrameAvg();\n}\n\nvoid\nContainer\n::SetFrameAvg( bool doAveraging )\n{\n Impl->SetFrameAvg( doAveraging );\n}\n\n\nbool\nContainer\n::GetScanOn() const\n{\n return Impl->GetScanOn();\n}\n\n\nvoid\nContainer\n::AbortScan()\n{\n Impl->AbortScan();\n}\n\n\nvoid\nContainer\n::DisposeScan()\n{\n Impl->DisposeScan();\n}\n\n\nvoid\nContainer\n::StartReadScan()\n{\n Impl->StartReadScan();\n}\n\n\nvoid\nContainer\n::StartRFReadScan()\n{\n Impl->StartRFReadScan();\n}\n\n\nvoid\nContainer\n::StopReadScan()\n{\n Impl->StopReadScan();\n}\n\n\nvoid\nContainer\n::SetNewImageCallback( NewImageCallbackType callback,\n void *clientData )\n{\n Impl->SetNewImageCallback( callback, clientData );\n}\n\n\nvoid\nContainer\n::SetNewRFImageCallback( NewRFImageCallbackType callback,\n void *clientData )\n{\n Impl->SetNewRFImageCallback( callback, clientData );\n}\n\nvoid\nContainer\n::SetHWControls(IntersonArrayCxx::Controls::HWControls * controls)\n{\n Impl->SetHWControls(controls);\n}\n\n} \/\/ end namespace Imaging\n\n} \/\/ end namespace IntersonArrayCxx\n<commit_msg>Cleanup<commit_after>\/*=========================================================================\n\nLibrary: IntersonArray\n\nCopyright Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved.\n\nLicensed under the Apache License, Version 2.0 ( the \"License\" );\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n#pragma unmanaged\n#include \"IntersonArrayCxxImagingContainer.h\"\n#include <iostream>\n#pragma managed\n\n#include <vcclr.h>\n#include <msclr\/marshal_cppstd.h>\n#include <msclr\/auto_gcroot.h>\n\n#using \"IntersonArray.dll\"\n\nnamespace IntersonArrayCxx\n{\n\nnamespace Imaging\n{\n\n\/\/\n\/\/ Begin Capture\n\/\/\nref class NewRFImageHandler\n{\npublic:\n\n typedef Container::NewRFImageCallbackType NewRFImageCallbackType;\n\n typedef IntersonArrayCxx::Imaging::Container::RFPixelType RFPixelType;\n typedef IntersonArrayCxx::Imaging::Container::RFImagePixelType RFImagePixelType;\n typedef cli::array< RFPixelType, 2 > RFArrayType;\n\n NewRFImageHandler( RFArrayType ^managedRFBuffer ):\n NewRFImageCallback( NULL ),\n NewRFImageCallbackClientData( NULL ),\n bufferWidth( Container::MAX_RFSAMPLES ),\n bufferHeight( Container::NBOFLINES ),\n NativeRFBuffer(new RFImagePixelType[Container::MAX_RFSAMPLES\n * Container::NBOFLINES] ),\n ManagedRFBuffer( managedRFBuffer )\n {\n }\n\n ~NewRFImageHandler()\n {\n delete [] NativeRFBuffer;\n }\n\n void HandleNewRFImage( IntersonArray::Imaging::Capture ^scan2D,\n System::EventArgs ^eventArgs )\n {\n if ( this->NewRFImageCallback != NULL )\n {\n for ( int ii = 0; ii < bufferHeight; ++ii )\n {\n for ( int jj = 0; jj < bufferWidth; ++jj )\n {\n this->NativeRFBuffer[bufferWidth * ii + jj] = (short)\n this->ManagedRFBuffer[ii, jj];\n }\n }\n this->NewRFImageCallback( this->NativeRFBuffer,\n this->NewRFImageCallbackClientData );\n }\n }\n\n void SetNewRFImageCallback( NewRFImageCallbackType callback,\n void *clientData )\n {\n this->NewRFImageCallback = callback;\n this->NewRFImageCallbackClientData = clientData;\n }\n\nprivate:\n NewRFImageCallbackType NewRFImageCallback;\n void * NewRFImageCallbackClientData;\n RFImagePixelType * NativeRFBuffer;\n RFArrayType ^ ManagedRFBuffer;\n int bufferWidth;\n int bufferHeight;\n};\n\n\nref class NewImageHandler\n{\npublic:\n typedef Container::NewImageCallbackType NewImageCallbackType;\n\n typedef IntersonArrayCxx::Imaging::Container::PixelType PixelType;\n typedef cli::array< byte, 2 > ArrayType;\n\n NewImageHandler( ArrayType ^managedBuffer ):\n NewImageCallback( NULL ),\n NewImageCallbackClientData( NULL ),\n bufferWidth( Container::MAX_SAMPLES ),\n bufferHeight( Container::NBOFLINES ),\n NativeBuffer( new PixelType[Container::MAX_SAMPLES *\n Container::NBOFLINES ] ),\n ManagedBuffer( managedBuffer )\n {\n }\n\n ~NewImageHandler()\n {\n delete [] NativeBuffer;\n }\n\n void HandleNewImage( IntersonArray::Imaging::Capture ^scan2D,\n System::EventArgs ^eventArgs )\n {\n if ( this->NewImageCallback != NULL )\n {\n for ( int ii = 0; ii < bufferHeight; ++ii )\n {\n for ( int jj = 0; jj < bufferWidth; ++jj )\n {\n this->NativeBuffer[bufferWidth * ii + jj] =\n this->ManagedBuffer[ii, jj];\n }\n }\n this->NewImageCallback( this->NativeBuffer,\n this->NewImageCallbackClientData );\n }\n }\n\n\n void SetNewImageCallback( NewImageCallbackType callback,\n void *clientData )\n {\n this->NewImageCallback = callback;\n this->NewImageCallbackClientData = clientData;\n }\n\nprivate:\n NewImageCallbackType NewImageCallback;\n void * NewImageCallbackClientData;\n PixelType * NativeBuffer;\n ArrayType ^ ManagedBuffer;\n int bufferWidth;\n int bufferHeight;\n};\n\n\/\/ End Capture\n\nclass ContainerImpl\n{\npublic:\n typedef cli::array< Container::PixelType, 2 > ArrayType;\n typedef cli::array< Container::RFPixelType, 2 > RFArrayType;\n\n typedef Container::NewImageCallbackType NewImageCallbackType;\n typedef Container::NewRFImageCallbackType NewRFImageCallbackType;\n\n ContainerImpl()\n {\n WrappedScanConverter = gcnew IntersonArray::Imaging::ScanConverter();\n WrappedImageBuilding = gcnew IntersonArray::Imaging::ImageBuilding();\n WrappedCapture = gcnew IntersonArray::Imaging::Capture();\n\n Buffer = gcnew ArrayType( Container::NBOFLINES, Container::MAX_SAMPLES );\n Handler = gcnew NewImageHandler( Buffer );\n HandlerDelegate = gcnew\n IntersonArray::Imaging::Capture::NewImageHandler( Handler,\n & NewImageHandler::HandleNewImage );\n WrappedCapture->NewImageTick += HandlerDelegate;\n\n RFBuffer = gcnew RFArrayType(Container::NBOFLINES , Container::MAX_RFSAMPLES);\n RFHandler = gcnew NewRFImageHandler( RFBuffer );\n RFHandlerDelegate = gcnew\n IntersonArray::Imaging::Capture::NewImageHandler( RFHandler,\n & NewRFImageHandler::HandleNewRFImage );\n }\n\n ~ContainerImpl()\n {\n WrappedCapture->NewImageTick -= RFHandlerDelegate;\n WrappedCapture->NewImageTick -= HandlerDelegate;\n }\n\n bool GetCompound()\n {\n return WrappedScanConverter->Compound;\n }\n\n void SetCompound( bool value )\n {\n WrappedScanConverter->Compound = value;\n }\n\n bool GetDoubler()\n {\n return WrappedScanConverter->Doubler;\n }\n\n void SetDoubler( bool value )\n {\n WrappedScanConverter->Doubler = value;\n }\n\n int GetHeightScan() const\n {\n return WrappedScanConverter->HeightScan;\n }\n\n float GetMmPerPixel() const\n {\n return WrappedScanConverter->MmPerPixel;\n }\n\n double GetTrueDepth() const\n {\n return WrappedScanConverter->TrueDepth;\n }\n\n int GetWidthScan() const\n {\n return WrappedScanConverter->WidthScan;\n }\n\n int GetZeroOfYScale() const\n {\n return WrappedScanConverter->ZeroOfYScale;\n }\n\n Container::ScanConverterError HardInitScanConverter( int depth,\n int widthScan, int heightScan, int steering )\n {\n \n return static_cast< Container::ScanConverterError >(\n WrappedScanConverter->HardInitScanConverter( depth, widthScan,\n heightScan, steering, WrappedCapture.get(),\n WrappedImageBuilding.get() ) );\n }\n\n Container::ScanConverterError IdleInitScanConverter( int depth,\n int widthScan, int heightScan, short idleId, int idleSteering,\n bool idleDoubler, bool idleCompound, int idleCompoundAngle )\n {\n return static_cast< Container::ScanConverterError >(\n WrappedScanConverter->IdleInitScanConverter( depth, widthScan,\n heightScan, idleId, idleSteering, idleDoubler, idleCompound,\n idleCompoundAngle, WrappedImageBuilding.get() ) );\n }\n\n \/\/ \n \/\/ Begin Capture\n \/\/\n bool GetFrameAvg()\n {\n return WrappedCapture->FrameAvg;\n }\n\n void SetFrameAvg( bool value)\n {\n WrappedCapture->FrameAvg = value;\n }\n\n bool GetRFData()\n {\n return WrappedCapture->RFData;\n }\n\n void SetRFData( bool value )\n {\n if (value){\n this->hwControls->ReadFPGAVersion();\n }\n WrappedCapture->RFData = value;\n \/\/Set correct image handler\n if (value){\n WrappedCapture->NewImageTick -= HandlerDelegate;\n WrappedCapture->NewImageTick += RFHandlerDelegate;\n }\n else{\n WrappedCapture->NewImageTick -= RFHandlerDelegate;\n WrappedCapture->NewImageTick += HandlerDelegate;\n }\n }\n\n double GetScanOn()\n {\n return WrappedCapture->ScanOn;\n }\n\n void AbortScan()\n {\n WrappedCapture->AbortScan();\n }\n\n void DisposeScan()\n {\n WrappedCapture->DisposeScan();\n }\n\n void StartReadScan()\n {\n WrappedCapture->StartReadScan( (ArrayType ^)Buffer );\n }\n\n void StartRFReadScan()\n {\n WrappedCapture->StartRFReadScan( (RFArrayType ^)RFBuffer );\n }\n\n void StopReadScan()\n {\n WrappedCapture->StopReadScan();\n }\n\n void SetNewImageCallback( NewImageCallbackType callback,\n void *clientData = 0 )\n {\n this->Handler->SetNewImageCallback( callback, clientData );\n }\n\n void SetNewRFImageCallback( NewRFImageCallbackType callback,\n void *clientData = 0 )\n {\n this->RFHandler->SetNewRFImageCallback( callback, clientData );\n }\n void SetHWControls(IntersonArrayCxx::Controls::HWControls * controls)\n {\n this->hwControls = controls;\n }\n\n \/\/ \n \/\/ Begin Wrapped ImageBuilding\n \/\/\n\nprivate:\n IntersonArrayCxx::Controls::HWControls * hwControls;\n msclr::auto_gcroot< IntersonArray::Imaging::ScanConverter ^ >\n WrappedScanConverter;\n msclr::auto_gcroot< IntersonArray::Imaging::ImageBuilding ^ >\n WrappedImageBuilding;\n msclr::auto_gcroot< IntersonArray::Imaging::Capture ^ >\n WrappedCapture;\n\n gcroot< ArrayType ^ > Buffer;\n gcroot< RFArrayType ^ > RFBuffer;\n gcroot< NewImageHandler ^ > Handler;\n gcroot< NewRFImageHandler ^ > RFHandler;\n\n gcroot< IntersonArray::Imaging::Capture::NewImageHandler ^ >\n HandlerDelegate;\n gcroot< IntersonArray::Imaging::Capture::NewImageHandler ^ >\n RFHandlerDelegate;\n\n};\n\n\n#pragma unmanaged\n\nContainer\n::Container():\n Impl( new ContainerImpl() )\n{\n}\n\n\nContainer\n::~Container()\n{\n delete Impl;\n}\n\n\nbool\nContainer\n::GetCompound()\n{\n return Impl->GetCompound();\n}\n\n\nvoid\nContainer\n::SetCompound( bool value )\n{\n Impl->SetCompound( value );\n}\n\n\nbool\nContainer\n::GetDoubler()\n{\n return Impl->GetDoubler();\n}\n\n\nvoid\nContainer\n::SetDoubler( bool value )\n{\n Impl->SetDoubler( value );\n}\n\n\nint\nContainer\n::GetHeightScan() const\n{\n return Impl->GetHeightScan();\n}\n\n\nfloat\nContainer\n::GetMmPerPixel() const\n{\n return Impl->GetMmPerPixel();\n}\n\n\ndouble\nContainer\n::GetTrueDepth() const\n{\n return Impl->GetMmPerPixel();\n}\n\n\nint\nContainer\n::GetWidthScan() const\n{\n return Impl->GetWidthScan();\n}\n\n\nint\nContainer\n::GetZeroOfYScale() const\n{\n return Impl->GetZeroOfYScale();\n}\n\n\nContainer::ScanConverterError\nContainer\n::HardInitScanConverter( int depth, int widthScan, int heightScan,\n int steering )\n{\n return Impl->HardInitScanConverter( depth, widthScan, heightScan,\n steering );\n}\n\n\nContainer::ScanConverterError\nContainer\n::IdleInitScanConverter( int depth, int width, int height, short idleId,\n int idleSteering, bool idleDoubler, bool idleCompound,\n int idleCompoundAngle )\n{\n return Impl->IdleInitScanConverter( depth, width, height, idleId,\n idleSteering, idleDoubler, idleCompound, idleCompoundAngle );\n}\n\n\/\/\n\/\/ Begin Capture\n\/\/\nbool\nContainer\n::GetRFData()\n{\n return Impl->GetRFData();\n}\n\nvoid\nContainer\n::SetRFData( bool transferOn )\n{\n Impl->SetRFData( transferOn );\n}\n\n\nbool\nContainer\n::GetFrameAvg()\n{\n return Impl->GetFrameAvg();\n}\n\nvoid\nContainer\n::SetFrameAvg( bool doAveraging )\n{\n Impl->SetFrameAvg( doAveraging );\n}\n\n\nbool\nContainer\n::GetScanOn() const\n{\n return Impl->GetScanOn();\n}\n\n\nvoid\nContainer\n::AbortScan()\n{\n Impl->AbortScan();\n}\n\n\nvoid\nContainer\n::DisposeScan()\n{\n Impl->DisposeScan();\n}\n\n\nvoid\nContainer\n::StartReadScan()\n{\n Impl->StartReadScan();\n}\n\n\nvoid\nContainer\n::StartRFReadScan()\n{\n Impl->StartRFReadScan();\n}\n\n\nvoid\nContainer\n::StopReadScan()\n{\n Impl->StopReadScan();\n}\n\n\nvoid\nContainer\n::SetNewImageCallback( NewImageCallbackType callback,\n void *clientData )\n{\n Impl->SetNewImageCallback( callback, clientData );\n}\n\n\nvoid\nContainer\n::SetNewRFImageCallback( NewRFImageCallbackType callback,\n void *clientData )\n{\n Impl->SetNewRFImageCallback( callback, clientData );\n}\n\nvoid\nContainer\n::SetHWControls(IntersonArrayCxx::Controls::HWControls * controls)\n{\n Impl->SetHWControls(controls);\n}\n\n} \/\/ end namespace Imaging\n\n} \/\/ end namespace IntersonArrayCxx\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2013 - 2015 Nikita Batov, Kseniya Gonta and CyberTech Labs Ltd.\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 \"analogSensor.h\"\n\n#include <trikKernel\/configurer.h>\n#include <QsLog.h>\n\n#include \"i2cCommunicator.h\"\n#include \"configurerHelper.h\"\n\nusing namespace trikControl;\n\nAnalogSensor::AnalogSensor(const QString &port, const trikKernel::Configurer &configurer, I2cCommunicator &communicator)\n\t: mCommunicator(communicator)\n{\n\tmI2cCommandNumber = ConfigurerHelper::configureInt(configurer, mState, port, \"i2cCommandNumber\");\n\tmIRType = configurer.attributeByPort(port, \"type\") == \"SharpGP2\" ? Type::sharpGP2 : Type::analog;\n\t\/\/ We use linear subjection to normalize common analog sensor values:\n\t\/\/ normalizedValue = k * rawValue + b\n\t\/\/ To calculate k and b we need two raw values and two corresponding them normalized values.\n\n\t\/\/ We use hyperbolical subjection to normalize SharpGP2 sensor values:\n\t\/\/ normalizedValue = s \/ (rawValue + l) + n\n\t\/\/ To calculate s, l and n we need sensor readings at three distances.\n\n\tif (mIRType == Type::sharpGP2){\n\t\tcalculateLNS(port, configurer);\t\n\t} else {\n\t\tcalculateKB(port, configurer);\t\n\t}\n\tmState.ready();\n}\n\nAnalogSensor::Status AnalogSensor::status() const\n{\n\treturn DeviceInterface::combine(mCommunicator, mState.status());\n}\n\nint AnalogSensor::read()\n{\n\tconst auto raw = readRawData();\n\tif (mIRType == Type::sharpGP2) {\n\t\tconst auto quotient = raw + mL;\t\n const auto result = quotient != 0 ? mS \/ quotient + mN : 0;\n\t\treturn result;\t\n\t}\n\treturn mK * raw + mB;\n}\n\nint AnalogSensor::readRawData()\n{\n\tif (!mState.isReady() || mCommunicator.status() != DeviceInterface::Status::ready) {\n\t\treturn 0;\n\t}\n\n\tQByteArray command(1, '\\0');\n\tcommand[0] = static_cast<char>(mI2cCommandNumber & 0xFF);\n\n\treturn mCommunicator.read(command);\n}\n\nvoid AnalogSensor::calculateLNS(const QString &port, const trikKernel::Configurer &configurer)\n{\n\tQStringList result;\n\tfor (const QString &str : configurer.attributeByPort(port, \"values\").split(\")\")) {\n\t\tresult += str.mid(1).split(\";\");\n\t}\n\n\tconst int x1 = result[0].toInt();\n\tconst int y1 = result[1].toInt();\n\tconst int x2 = result[2].toInt();\n\tconst int y2 = result[3].toInt();\n\tconst int x3 = result[4].toInt();\n\tconst int y3 = result[5].toInt();\n\n\t\/\/ Counted from equations x1 = mS\/(y1 + mL) + mN, x2 = mS\/(y2 + mL) + mN, x3 = mS\/(y3 + mL) + mN \n\tmL = (-x1 * y1 * y3 - x3 * y2 * y3 + x3 * y1 * y3 + x1 * y1 * y2 + x2 * y2 * y3 - x2 * y1 * y2) \/ \n\t\t\t(x1 * y3 - x2 * y3 + x2 * y1 - x1 * y2 + x3 * y2 - x3 * y1);\n\tmS = (x1 - x2) * (y1 + mL) * (y2 + mL) \/ (y2 - y1);\n\tmN = x1 - mS \/ (y1 + mL);\t\n}\n\nvoid AnalogSensor::calculateKB(const QString &port, const trikKernel::Configurer &configurer)\n{\n\tconst int rawValue1 = ConfigurerHelper::configureInt(configurer, mState, port, \"rawValue1\");\n\tconst int rawValue2 = ConfigurerHelper::configureInt(configurer, mState, port, \"rawValue2\");\n\tconst int normalizedValue1 = ConfigurerHelper::configureInt(configurer, mState, port, \"normalizedValue1\");\n\tconst int normalizedValue2 = ConfigurerHelper::configureInt(configurer, mState, port, \"normalizedValue2\");\n\tif (rawValue1 == rawValue2) {\n\t\tQLOG_ERROR() << \"Sensor calibration error: rawValue1 = rawValue2!\";\n\t\tmState.fail();\n\t\tmK = 0;\n\t\tmB = 0;\n\t} else {\n\t\tmK = static_cast<qreal>(normalizedValue2 - normalizedValue1) \/ (rawValue2 - rawValue1);\n\t\tmB = normalizedValue1 - mK * rawValue1;\n\t}\n}\n<commit_msg>Some corrections<commit_after>\/* Copyright 2013 - 2015 Nikita Batov, Kseniya Gonta and CyberTech Labs Ltd.\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 \"analogSensor.h\"\n\n#include <trikKernel\/configurer.h>\n#include <QsLog.h>\n\n#include \"i2cCommunicator.h\"\n#include \"configurerHelper.h\"\n\nusing namespace trikControl;\n\nAnalogSensor::AnalogSensor(const QString &port, const trikKernel::Configurer &configurer, I2cCommunicator &communicator)\n\t: mCommunicator(communicator)\n{\n\tmI2cCommandNumber = ConfigurerHelper::configureInt(configurer, mState, port, \"i2cCommandNumber\");\n\tmIRType = configurer.attributeByPort(port, \"type\") == \"SharpGP2\" ? Type::sharpGP2 : Type::analog;\n\t\/\/ We use linear subjection to normalize common analog sensor values:\n\t\/\/ normalizedValue = k * rawValue + b\n\t\/\/ To calculate k and b we need two raw values and two corresponding them normalized values.\n\n\t\/\/ We use hyperbolical subjection to normalize SharpGP2 sensor values:\n\t\/\/ normalizedValue = s \/ (rawValue + l) + n\n\t\/\/ To calculate s, l and n we need sensor readings at three distances.\n\n\tif (mIRType == Type::sharpGP2){\n\t\tcalculateLNS(port, configurer);\t\n\t} else {\n\t\tcalculateKB(port, configurer);\t\n\t}\n\tmState.ready();\n}\n\nAnalogSensor::Status AnalogSensor::status() const\n{\n\treturn DeviceInterface::combine(mCommunicator, mState.status());\n}\n\nint AnalogSensor::read()\n{\n\tconst auto raw = readRawData();\n\tif (mIRType == Type::sharpGP2) {\n\t\tconst auto quotient = raw + mL;\t\n\t\tconst auto result = quotient != 0 ? mS \/ quotient + mN : 0;\n\t\treturn result;\t\n\t}\n\n\treturn mK * raw + mB;\n}\n\nint AnalogSensor::readRawData()\n{\n\tif (!mState.isReady() || mCommunicator.status() != DeviceInterface::Status::ready) {\n\t\treturn 0;\n\t}\n\n\tQByteArray command(1, '\\0');\n\tcommand[0] = static_cast<char>(mI2cCommandNumber & 0xFF);\n\n\treturn mCommunicator.read(command);\n}\n\nvoid AnalogSensor::calculateLNS(const QString &port, const trikKernel::Configurer &configurer)\n{\n\tQStringList result;\n\tfor (const QString &str : configurer.attributeByPort(port, \"values\").split(\")\")) {\n\t\tresult += str.mid(1).split(\";\");\n\t}\n\n\tconst int x1 = result[0].toInt();\n\tconst int y1 = result[1].toInt();\n\tconst int x2 = result[2].toInt();\n\tconst int y2 = result[3].toInt();\n\tconst int x3 = result[4].toInt();\n\tconst int y3 = result[5].toInt();\n\n\t\/\/ Counted from equations x1 = mS\/(y1 + mL) + mN, x2 = mS\/(y2 + mL) + mN, x3 = mS\/(y3 + mL) + mN \n\tmL = (-x1 * y1 * y3 - x3 * y2 * y3 + x3 * y1 * y3 + x1 * y1 * y2 + x2 * y2 * y3 - x2 * y1 * y2) \/ \n\t\t\t(x1 * y3 - x2 * y3 + x2 * y1 - x1 * y2 + x3 * y2 - x3 * y1);\n\tmS = (x1 - x2) * (y1 + mL) * (y2 + mL) \/ (y2 - y1);\n\tmN = x1 - mS \/ (y1 + mL);\t\n}\n\nvoid AnalogSensor::calculateKB(const QString &port, const trikKernel::Configurer &configurer)\n{\n\tconst int rawValue1 = ConfigurerHelper::configureInt(configurer, mState, port, \"rawValue1\");\n\tconst int rawValue2 = ConfigurerHelper::configureInt(configurer, mState, port, \"rawValue2\");\n\tconst int normalizedValue1 = ConfigurerHelper::configureInt(configurer, mState, port, \"normalizedValue1\");\n\tconst int normalizedValue2 = ConfigurerHelper::configureInt(configurer, mState, port, \"normalizedValue2\");\n\tif (rawValue1 == rawValue2) {\n\t\tQLOG_ERROR() << \"Sensor calibration error: rawValue1 = rawValue2!\";\n\t\tmState.fail();\n\t\tmK = 0;\n\t\tmB = 0;\n\t} else {\n\t\tmK = static_cast<qreal>(normalizedValue2 - normalizedValue1) \/ (rawValue2 - rawValue1);\n\t\tmB = normalizedValue1 - mK * rawValue1;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Author: Jakob Blomer CERN 07\/2018\n\n\/*************************************************************************\n * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/ clang-format off\n\/** \\class ROOT::RDF::RSqliteDS\n \\ingroup dataframe\n \\brief RDataFrame data source class for reading SQlite files.\n*\/\n\/\/ clang-format on\n\n#include <ROOT\/RSqliteDS.hxx>\n#include <ROOT\/RDFUtils.hxx>\n#include <ROOT\/RMakeUnique.hxx>\n\n#include <TError.h>\n\n#include <algorithm>\n#include <cstring>\n\nnamespace ROOT {\n\nnamespace RDF {\n\nRSqliteDS::RSqliteDS(std::string_view fileName, std::string_view query)\n : fDb(NULL)\n , fQuery(NULL)\n , fNRow(0)\n{\n int retval;\n\n retval = sqlite3_open_v2(std::string(fileName).c_str(), &fDb,\n SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX, NULL);\n if (retval != SQLITE_OK) SqliteError(retval);\n\n retval = sqlite3_prepare_v2(fDb, std::string(query).c_str(), -1, &fQuery, NULL);\n if (retval != SQLITE_OK) SqliteError(retval);\n\n int colCount = sqlite3_column_count(fQuery);\n retval = sqlite3_step(fQuery);\n if ((retval != SQLITE_ROW) && (retval != SQLITE_DONE)) SqliteError(retval);\n\n fValues.resize(colCount);\n for (int i = 0; i < colCount; ++i) {\n fColumnNames.emplace_back(sqlite3_column_name(fQuery, i));\n int type = SQLITE_NULL;\n \/\/ Try first with the declared column type and then with the dynamic type\n \/\/ for expressions\n std::string declType = sqlite3_column_decltype(fQuery, i);\n if (declType == \"INTEGER\") type = SQLITE_INTEGER;\n else if (declType == \"FLOAT\") type = SQLITE_FLOAT;\n else if (declType == \"TEXT\") type = SQLITE_TEXT;\n else if (declType == \"BLOB\") type = SQLITE_BLOB;\n else if (declType == \"NULL\" && retval == SQLITE_ROW) type = sqlite3_column_type(fQuery, i);\n\n switch (type) {\n case SQLITE_INTEGER:\n fColumnTypes.push_back(Types::kInteger);\n fValues[i].fType = Types::kInteger;\n fValues[i].fPtr = &fValues[i].fInteger;\n break;\n case SQLITE_FLOAT:\n fColumnTypes.push_back(Types::kReal);\n fValues[i].fType = Types::kReal;\n fValues[i].fPtr = &fValues[i].fReal;\n break;\n case SQLITE_TEXT:\n fColumnTypes.push_back(Types::kText);\n fValues[i].fType = Types::kText;\n fValues[i].fPtr = &fValues[i].fText;\n break;\n case SQLITE_BLOB:\n fColumnTypes.push_back(Types::kBlob);\n fValues[i].fType = Types::kBlob;\n fValues[i].fPtr = &fValues[i].fBlob;\n break;\n case SQLITE_NULL:\n \/\/ TODO: Null values in first rows are not well handled\n fColumnTypes.push_back(Types::kNull);\n fValues[i].fType = Types::kNull;\n fValues[i].fPtr = &fValues[i].fNull;\n break;\n default:\n throw std::runtime_error(\"Unhandled data type\");\n }\n }\n\n fTypeNames[Types::kInteger] = \"Long64_t\";\n fTypeNames[Types::kReal] = \"double\";\n fTypeNames[Types::kText] = \"std::string\";\n fTypeNames[Types::kBlob] = \"std::vector<unsigned char>\";\n fTypeNames[Types::kNull] = \"void *\";\n}\n\n\nRSqliteDS::~RSqliteDS()\n{\n sqlite3_finalize(fQuery);\n sqlite3_close_v2(fDb);\n}\n\n\nconst std::vector<std::string> &RSqliteDS::GetColumnNames() const\n{\n return fColumnNames;\n}\n\n\nRDataSource::Record_t RSqliteDS::GetColumnReadersImpl(std::string_view name, const std::type_info &ti)\n{\n const auto index = std::distance(fColumnNames.begin(), std::find(fColumnNames.begin(), fColumnNames.end(), name));\n Types type = fColumnTypes[index];\n\n if ((type == Types::kReal && typeid(double) != ti) ||\n (type == Types::kInteger && typeid(Long64_t) != ti) ||\n (type == Types::kText && typeid(std::string) != ti) ||\n (type == Types::kBlob && typeid(std::vector<unsigned char>) != ti) ||\n (type == Types::kNull && typeid(void *) != ti))\n {\n std::string errmsg = \"The type selected for column \\\"\";\n errmsg += name;\n errmsg += \"\\\" does not correspond to column type, which is \";\n errmsg += GetTypeName(name);\n throw std::runtime_error(errmsg);\n }\n\n fValues[index].fIsActive = true;\n std::vector<void *> result;\n result.push_back(&fValues[index].fPtr);\n return result;\n}\n\n\nstd::vector<std::pair<ULong64_t, ULong64_t>> RSqliteDS::GetEntryRanges()\n{\n std::vector<std::pair<ULong64_t, ULong64_t>> entryRanges;\n int retval = sqlite3_step(fQuery);\n switch (retval) {\n case SQLITE_DONE:\n return entryRanges;\n case SQLITE_ROW:\n entryRanges.emplace_back(fNRow, fNRow + 1);\n fNRow++;\n return entryRanges;\n default:\n SqliteError(retval);\n \/\/ Never here\n abort();\n }\n}\n\n\nstd::string RSqliteDS::GetTypeName(std::string_view colName) const\n{\n unsigned N = fColumnNames.size();\n\n for (unsigned i = 0; i < N; ++i) {\n if (colName == fColumnNames[i]) {\n return fTypeNames.at(fColumnTypes[i]);\n }\n }\n throw std::runtime_error(\"Unknown column: \" + std::string(colName));\n}\n\n\nbool RSqliteDS::HasColumn(std::string_view colName) const\n{\n return std::find(fColumnNames.begin(), fColumnNames.end(), colName) !=\n fColumnNames.end();\n}\n\n\nvoid RSqliteDS::Initialise() {\n fNRow = 0;\n int retval = sqlite3_reset(fQuery);\n if (retval != SQLITE_OK) throw std::runtime_error(\"SQlite error, reset\");\n}\n\n\nRDataFrame MakeSqliteDataFrame(std::string_view fileName, std::string_view query)\n{\n ROOT::RDataFrame tdf(std::make_unique<RSqliteDS>(fileName, query));\n return tdf;\n}\n\n\nbool RSqliteDS::SetEntry(unsigned int \/* slot *\/, ULong64_t entry)\n{\n R__ASSERT(entry + 1 == fNRow);\n unsigned N = fValues.size();\n for (unsigned i = 0; i < N; ++i) {\n if (!fValues[i].fIsActive) continue;\n\n int nbytes;\n switch (fValues[i].fType) {\n case Types::kInteger:\n fValues[i].fInteger = sqlite3_column_int64(fQuery, i);\n break;\n case Types::kReal:\n fValues[i].fReal = sqlite3_column_double(fQuery, i);\n break;\n case Types::kText:\n nbytes = sqlite3_column_bytes(fQuery, i);\n if (nbytes == 0) {\n fValues[i].fText = \"\";\n } else {\n fValues[i].fText = reinterpret_cast<const char *>(\n sqlite3_column_text(fQuery, i));\n }\n break;\n case Types::kBlob:\n nbytes = sqlite3_column_bytes(fQuery, i);\n fValues[i].fBlob.resize(nbytes);\n if (nbytes > 0) {\n std::memcpy(fValues[i].fBlob.data(), sqlite3_column_blob(fQuery, i), nbytes);\n }\n break;\n case Types::kNull:\n break;\n default:\n throw std::runtime_error(\"Unhandled column type\");\n }\n }\n return true;\n}\n\n\nvoid RSqliteDS::SetNSlots(unsigned int \/* nSlots *\/)\n{\n}\n\n\nvoid RSqliteDS::SqliteError(int errcode) {\n std::string errmsg = \"SQlite error: \";\n errmsg += sqlite3_errstr(errcode);\n throw std::runtime_error(errmsg);\n}\n\n} \/\/ ns RDF\n\n} \/\/ ns ROOT\n<commit_msg>[DF] Fix expression columns in SQlite data source<commit_after>\/\/ Author: Jakob Blomer CERN 07\/2018\n\n\/*************************************************************************\n * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/ clang-format off\n\/** \\class ROOT::RDF::RSqliteDS\n \\ingroup dataframe\n \\brief RDataFrame data source class for reading SQlite files.\n*\/\n\/\/ clang-format on\n\n#include <ROOT\/RSqliteDS.hxx>\n#include <ROOT\/RDFUtils.hxx>\n#include <ROOT\/RMakeUnique.hxx>\n\n#include <TError.h>\n\n#include <algorithm>\n#include <cstring>\n\nnamespace ROOT {\n\nnamespace RDF {\n\nRSqliteDS::RSqliteDS(std::string_view fileName, std::string_view query)\n : fDb(NULL)\n , fQuery(NULL)\n , fNRow(0)\n{\n int retval;\n\n retval = sqlite3_open_v2(std::string(fileName).c_str(), &fDb,\n SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX, NULL);\n if (retval != SQLITE_OK) SqliteError(retval);\n\n retval = sqlite3_prepare_v2(fDb, std::string(query).c_str(), -1, &fQuery, NULL);\n if (retval != SQLITE_OK) SqliteError(retval);\n\n int colCount = sqlite3_column_count(fQuery);\n retval = sqlite3_step(fQuery);\n if ((retval != SQLITE_ROW) && (retval != SQLITE_DONE)) SqliteError(retval);\n\n fValues.resize(colCount);\n for (int i = 0; i < colCount; ++i) {\n fColumnNames.emplace_back(sqlite3_column_name(fQuery, i));\n int type = SQLITE_NULL;\n \/\/ Try first with the declared column type and then with the dynamic type\n \/\/ for expressions\n const char *declTypeCstr = sqlite3_column_decltype(fQuery, i);\n if (declTypeCstr == NULL) {\n if (retval == SQLITE_ROW) type = sqlite3_column_type(fQuery, i);\n } else {\n std::string declType(declTypeCstr);\n if (declType == \"INTEGER\") type = SQLITE_INTEGER;\n else if (declType == \"FLOAT\") type = SQLITE_FLOAT;\n else if (declType == \"TEXT\") type = SQLITE_TEXT;\n else if (declType == \"BLOB\") type = SQLITE_BLOB;\n else throw std::runtime_error(\"Unexpected column decl type\");\n }\n\n switch (type) {\n case SQLITE_INTEGER:\n fColumnTypes.push_back(Types::kInteger);\n fValues[i].fType = Types::kInteger;\n fValues[i].fPtr = &fValues[i].fInteger;\n break;\n case SQLITE_FLOAT:\n fColumnTypes.push_back(Types::kReal);\n fValues[i].fType = Types::kReal;\n fValues[i].fPtr = &fValues[i].fReal;\n break;\n case SQLITE_TEXT:\n fColumnTypes.push_back(Types::kText);\n fValues[i].fType = Types::kText;\n fValues[i].fPtr = &fValues[i].fText;\n break;\n case SQLITE_BLOB:\n fColumnTypes.push_back(Types::kBlob);\n fValues[i].fType = Types::kBlob;\n fValues[i].fPtr = &fValues[i].fBlob;\n break;\n case SQLITE_NULL:\n \/\/ TODO: Null values in first rows are not well handled\n fColumnTypes.push_back(Types::kNull);\n fValues[i].fType = Types::kNull;\n fValues[i].fPtr = &fValues[i].fNull;\n break;\n default:\n throw std::runtime_error(\"Unhandled data type\");\n }\n }\n\n fTypeNames[Types::kInteger] = \"Long64_t\";\n fTypeNames[Types::kReal] = \"double\";\n fTypeNames[Types::kText] = \"std::string\";\n fTypeNames[Types::kBlob] = \"std::vector<unsigned char>\";\n fTypeNames[Types::kNull] = \"void *\";\n}\n\n\nRSqliteDS::~RSqliteDS()\n{\n sqlite3_finalize(fQuery);\n sqlite3_close_v2(fDb);\n}\n\n\nconst std::vector<std::string> &RSqliteDS::GetColumnNames() const\n{\n return fColumnNames;\n}\n\n\nRDataSource::Record_t RSqliteDS::GetColumnReadersImpl(std::string_view name, const std::type_info &ti)\n{\n const auto index = std::distance(fColumnNames.begin(), std::find(fColumnNames.begin(), fColumnNames.end(), name));\n Types type = fColumnTypes[index];\n\n if ((type == Types::kReal && typeid(double) != ti) ||\n (type == Types::kInteger && typeid(Long64_t) != ti) ||\n (type == Types::kText && typeid(std::string) != ti) ||\n (type == Types::kBlob && typeid(std::vector<unsigned char>) != ti) ||\n (type == Types::kNull && typeid(void *) != ti))\n {\n std::string errmsg = \"The type selected for column \\\"\";\n errmsg += name;\n errmsg += \"\\\" does not correspond to column type, which is \";\n errmsg += GetTypeName(name);\n throw std::runtime_error(errmsg);\n }\n\n fValues[index].fIsActive = true;\n std::vector<void *> result;\n result.push_back(&fValues[index].fPtr);\n return result;\n}\n\n\nstd::vector<std::pair<ULong64_t, ULong64_t>> RSqliteDS::GetEntryRanges()\n{\n std::vector<std::pair<ULong64_t, ULong64_t>> entryRanges;\n int retval = sqlite3_step(fQuery);\n switch (retval) {\n case SQLITE_DONE:\n return entryRanges;\n case SQLITE_ROW:\n entryRanges.emplace_back(fNRow, fNRow + 1);\n fNRow++;\n return entryRanges;\n default:\n SqliteError(retval);\n \/\/ Never here\n abort();\n }\n}\n\n\nstd::string RSqliteDS::GetTypeName(std::string_view colName) const\n{\n unsigned N = fColumnNames.size();\n\n for (unsigned i = 0; i < N; ++i) {\n if (colName == fColumnNames[i]) {\n return fTypeNames.at(fColumnTypes[i]);\n }\n }\n throw std::runtime_error(\"Unknown column: \" + std::string(colName));\n}\n\n\nbool RSqliteDS::HasColumn(std::string_view colName) const\n{\n return std::find(fColumnNames.begin(), fColumnNames.end(), colName) !=\n fColumnNames.end();\n}\n\n\nvoid RSqliteDS::Initialise() {\n fNRow = 0;\n int retval = sqlite3_reset(fQuery);\n if (retval != SQLITE_OK) throw std::runtime_error(\"SQlite error, reset\");\n}\n\n\nRDataFrame MakeSqliteDataFrame(std::string_view fileName, std::string_view query)\n{\n ROOT::RDataFrame tdf(std::make_unique<RSqliteDS>(fileName, query));\n return tdf;\n}\n\n\nbool RSqliteDS::SetEntry(unsigned int \/* slot *\/, ULong64_t entry)\n{\n R__ASSERT(entry + 1 == fNRow);\n unsigned N = fValues.size();\n for (unsigned i = 0; i < N; ++i) {\n if (!fValues[i].fIsActive) continue;\n\n int nbytes;\n switch (fValues[i].fType) {\n case Types::kInteger:\n fValues[i].fInteger = sqlite3_column_int64(fQuery, i);\n break;\n case Types::kReal:\n fValues[i].fReal = sqlite3_column_double(fQuery, i);\n break;\n case Types::kText:\n nbytes = sqlite3_column_bytes(fQuery, i);\n if (nbytes == 0) {\n fValues[i].fText = \"\";\n } else {\n fValues[i].fText = reinterpret_cast<const char *>(\n sqlite3_column_text(fQuery, i));\n }\n break;\n case Types::kBlob:\n nbytes = sqlite3_column_bytes(fQuery, i);\n fValues[i].fBlob.resize(nbytes);\n if (nbytes > 0) {\n std::memcpy(fValues[i].fBlob.data(), sqlite3_column_blob(fQuery, i), nbytes);\n }\n break;\n case Types::kNull:\n break;\n default:\n throw std::runtime_error(\"Unhandled column type\");\n }\n }\n return true;\n}\n\n\nvoid RSqliteDS::SetNSlots(unsigned int \/* nSlots *\/)\n{\n}\n\n\nvoid RSqliteDS::SqliteError(int errcode) {\n std::string errmsg = \"SQlite error: \";\n errmsg += sqlite3_errstr(errcode);\n throw std::runtime_error(errmsg);\n}\n\n} \/\/ ns RDF\n\n} \/\/ ns ROOT\n<|endoftext|>"} {"text":"<commit_before>\n\/****************************************************************************\n *\n * (c) 2009-2016 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n *\n * QGroundControl is licensed according to the terms in the file\n * COPYING.md in the root of the source code directory.\n *\n ****************************************************************************\/\n\n\n#include \"MissionCommandTree.h\"\n#include \"FactMetaData.h\"\n#include \"Vehicle.h\"\n#include \"FirmwarePluginManager.h\"\n#include \"QGCApplication.h\"\n#include \"QGroundControlQmlGlobal.h\"\n#include \"MissionCommandUIInfo.h\"\n#include \"MissionCommandList.h\"\n\n#include <QQmlEngine>\n\nMissionCommandTree::MissionCommandTree(QGCApplication* app, bool unitTest)\n : QGCTool(app)\n , _unitTest(unitTest)\n{\n}\n\nvoid MissionCommandTree::setToolbox(QGCToolbox* toolbox)\n{\n QGCTool::setToolbox(toolbox);\n\n#ifdef UNITTEST_BUILD\n if (_unitTest) {\n \/\/ Load unit testing tree\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoCommon.json\", true, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_FIXED_WING] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoFixedWing.json\", false, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_QUADROTOR] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoMultiRotor.json\", false, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_VTOL_QUADROTOR] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoVTOL.json\", false, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_SUBMARINE] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoSub.json\", false, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GROUND_ROVER] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoRover.json\", false, this);\n } else {\n#endif\n \/\/ Load all levels of hierarchy\n foreach (MAV_AUTOPILOT firmwareType, _toolbox->firmwarePluginManager()->knownFirmwareTypes()) {\n FirmwarePlugin* plugin = _toolbox->firmwarePluginManager()->firmwarePluginForAutopilot(firmwareType, MAV_TYPE_QUADROTOR);\n\n QList<MAV_TYPE> vehicleTypes;\n vehicleTypes << MAV_TYPE_GENERIC << MAV_TYPE_FIXED_WING << MAV_TYPE_QUADROTOR << MAV_TYPE_VTOL_QUADROTOR << MAV_TYPE_GROUND_ROVER << MAV_TYPE_SUBMARINE;\n\n foreach(MAV_TYPE vehicleType, vehicleTypes) {\n QString overrideFile = plugin->missionCommandOverrides(vehicleType);\n if (!overrideFile.isEmpty()) {\n _staticCommandTree[firmwareType][vehicleType] = new MissionCommandList(overrideFile, firmwareType == MAV_AUTOPILOT_GENERIC && vehicleType == MAV_TYPE_GENERIC \/* baseCommandList *\/, this);\n }\n }\n }\n#ifdef UNITTEST_BUILD\n }\n#endif\n}\n\nMAV_AUTOPILOT MissionCommandTree::_baseFirmwareType(MAV_AUTOPILOT firmwareType) const\n{\n if (qgcApp()->toolbox()->firmwarePluginManager()->knownFirmwareTypes().contains(firmwareType)) {\n return firmwareType;\n } else {\n return MAV_AUTOPILOT_GENERIC;\n }\n\n}\n\nMAV_TYPE MissionCommandTree::_baseVehicleType(MAV_TYPE mavType) const\n{\n if (QGCMAVLink::isFixedWing(mavType)) {\n return MAV_TYPE_FIXED_WING;\n } else if (QGCMAVLink::isMultiRotor(mavType)) {\n return MAV_TYPE_QUADROTOR;\n } else if (QGCMAVLink::isVTOL(mavType)) {\n return MAV_TYPE_VTOL_QUADROTOR;\n } else if (QGCMAVLink::isRover(mavType)) {\n return MAV_TYPE_GROUND_ROVER;\n } else if (QGCMAVLink::isSub(mavType)) {\n return MAV_TYPE_SUBMARINE;\n } else {\n return MAV_TYPE_GENERIC;\n }\n}\n\n\/\/\/ Add the next level of the hierarchy to a collapsed tree.\n\/\/\/ @param vehicle Collapsed tree is for this vehicle\n\/\/\/ @param cmdList List of mission commands to collapse into ui info\n\/\/\/ @param collapsedTree Tree we are collapsing into\nvoid MissionCommandTree::_collapseHierarchy(Vehicle* vehicle,\n const MissionCommandList* cmdList,\n QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n\n foreach (MAV_CMD command, cmdList->commandIds()) {\n MissionCommandUIInfo* uiInfo = cmdList->getUIInfo(command);\n if (uiInfo) {\n if (collapsedTree.contains(command)) {\n collapsedTree[command]->_overrideInfo(uiInfo);\n } else {\n collapsedTree[command] = new MissionCommandUIInfo(*uiInfo);\n }\n }\n }\n}\n\nvoid MissionCommandTree::_buildAvailableCommands(Vehicle* vehicle)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n\n if (_availableCommands.contains(baseFirmwareType) &&\n _availableCommands[baseFirmwareType].contains(baseVehicleType)) {\n \/\/ Available commands list already built\n return;\n }\n\n \/\/ Build new available commands list\n\n QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree = _availableCommands[baseFirmwareType][baseVehicleType];\n\n \/\/ Any Firmware, Any Vehicle\n _collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC], collapsedTree);\n\n \/\/ Any Firmware, Specific Vehicle\n if (baseVehicleType != MAV_TYPE_GENERIC) {\n _collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][baseVehicleType], collapsedTree);\n }\n\n \/\/ Known Firmware, Any Vehicle\n if (baseFirmwareType != MAV_AUTOPILOT_GENERIC) {\n _collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][MAV_TYPE_GENERIC], collapsedTree);\n\n \/\/ Known Firmware, Specific Vehicle\n if (baseVehicleType != MAV_TYPE_GENERIC) {\n _collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][baseVehicleType], collapsedTree);\n }\n }\n\n \/\/ Build category list\n QMapIterator<MAV_CMD, MissionCommandUIInfo*> iter(collapsedTree);\n while (iter.hasNext()) {\n iter.next();\n QString newCategory = iter.value()->category();\n if (!_availableCategories[baseFirmwareType][baseVehicleType].contains(newCategory)) {\n _availableCategories[baseFirmwareType][baseVehicleType].append(newCategory);\n }\n }\n}\n\nQStringList MissionCommandTree::_availableCategoriesForVehicle(Vehicle* vehicle)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n _buildAvailableCommands(vehicle);\n\n return _availableCategories[baseFirmwareType][baseVehicleType];\n}\n\nQString MissionCommandTree::friendlyName(MAV_CMD command)\n{\n MissionCommandList * commandList = _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];\n MissionCommandUIInfo* uiInfo = commandList->getUIInfo(command);\n\n return uiInfo->friendlyName();\n}\n\nQString MissionCommandTree::rawName(MAV_CMD command)\n{\n MissionCommandList * commandList = _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];\n MissionCommandUIInfo* uiInfo = commandList->getUIInfo(command);\n\n return uiInfo->rawName();\n}\n\nconst QList<MAV_CMD>& MissionCommandTree::allCommandIds(void) const\n{\n return _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC]->commandIds();\n}\n\nconst MissionCommandUIInfo* MissionCommandTree::getUIInfo(Vehicle* vehicle, MAV_CMD command)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n _buildAvailableCommands(vehicle);\n\n const QMap<MAV_CMD, MissionCommandUIInfo*>& infoMap = _availableCommands[baseFirmwareType][baseVehicleType];\n if (infoMap.contains(command)) {\n return infoMap[command];\n } else {\n return NULL;\n }\n}\n\nQVariantList MissionCommandTree::getCommandsForCategory(Vehicle* vehicle, const QString& category)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n _buildAvailableCommands(vehicle);\n\n QVariantList list;\n QMap<MAV_CMD, MissionCommandUIInfo*> commandMap = _availableCommands[baseFirmwareType][baseVehicleType];\n foreach (MAV_CMD command, commandMap.keys()) {\n MissionCommandUIInfo* uiInfo = commandMap[command];\n if (uiInfo->category() == category) {\n list.append(QVariant::fromValue(uiInfo));\n }\n }\n\n return list;\n}\n\nvoid MissionCommandTree::_baseVehicleInfo(Vehicle* vehicle, MAV_AUTOPILOT& baseFirmwareType, MAV_TYPE& baseVehicleType) const\n{\n if (vehicle) {\n baseFirmwareType = _baseFirmwareType(vehicle->firmwareType());\n baseVehicleType = _baseVehicleType(vehicle->vehicleType());\n } else {\n \/\/ No Vehicle means offline editing\n baseFirmwareType = _baseFirmwareType((MAV_AUTOPILOT)QGroundControlQmlGlobal::offlineEditingFirmwareType()->rawValue().toInt());\n baseVehicleType = _baseVehicleType((MAV_TYPE)QGroundControlQmlGlobal::offlineEditingVehicleType()->rawValue().toInt());\n }\n}\n<commit_msg>Fix crash on unknown command<commit_after>\n\/****************************************************************************\n *\n * (c) 2009-2016 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n *\n * QGroundControl is licensed according to the terms in the file\n * COPYING.md in the root of the source code directory.\n *\n ****************************************************************************\/\n\n\n#include \"MissionCommandTree.h\"\n#include \"FactMetaData.h\"\n#include \"Vehicle.h\"\n#include \"FirmwarePluginManager.h\"\n#include \"QGCApplication.h\"\n#include \"QGroundControlQmlGlobal.h\"\n#include \"MissionCommandUIInfo.h\"\n#include \"MissionCommandList.h\"\n\n#include <QQmlEngine>\n\nMissionCommandTree::MissionCommandTree(QGCApplication* app, bool unitTest)\n : QGCTool(app)\n , _unitTest(unitTest)\n{\n}\n\nvoid MissionCommandTree::setToolbox(QGCToolbox* toolbox)\n{\n QGCTool::setToolbox(toolbox);\n\n#ifdef UNITTEST_BUILD\n if (_unitTest) {\n \/\/ Load unit testing tree\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoCommon.json\", true, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_FIXED_WING] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoFixedWing.json\", false, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_QUADROTOR] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoMultiRotor.json\", false, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_VTOL_QUADROTOR] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoVTOL.json\", false, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_SUBMARINE] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoSub.json\", false, this);\n _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GROUND_ROVER] = new MissionCommandList(\":\/json\/unittest\/MavCmdInfoRover.json\", false, this);\n } else {\n#endif\n \/\/ Load all levels of hierarchy\n foreach (MAV_AUTOPILOT firmwareType, _toolbox->firmwarePluginManager()->knownFirmwareTypes()) {\n FirmwarePlugin* plugin = _toolbox->firmwarePluginManager()->firmwarePluginForAutopilot(firmwareType, MAV_TYPE_QUADROTOR);\n\n QList<MAV_TYPE> vehicleTypes;\n vehicleTypes << MAV_TYPE_GENERIC << MAV_TYPE_FIXED_WING << MAV_TYPE_QUADROTOR << MAV_TYPE_VTOL_QUADROTOR << MAV_TYPE_GROUND_ROVER << MAV_TYPE_SUBMARINE;\n\n foreach(MAV_TYPE vehicleType, vehicleTypes) {\n QString overrideFile = plugin->missionCommandOverrides(vehicleType);\n if (!overrideFile.isEmpty()) {\n _staticCommandTree[firmwareType][vehicleType] = new MissionCommandList(overrideFile, firmwareType == MAV_AUTOPILOT_GENERIC && vehicleType == MAV_TYPE_GENERIC \/* baseCommandList *\/, this);\n }\n }\n }\n#ifdef UNITTEST_BUILD\n }\n#endif\n}\n\nMAV_AUTOPILOT MissionCommandTree::_baseFirmwareType(MAV_AUTOPILOT firmwareType) const\n{\n if (qgcApp()->toolbox()->firmwarePluginManager()->knownFirmwareTypes().contains(firmwareType)) {\n return firmwareType;\n } else {\n return MAV_AUTOPILOT_GENERIC;\n }\n\n}\n\nMAV_TYPE MissionCommandTree::_baseVehicleType(MAV_TYPE mavType) const\n{\n if (QGCMAVLink::isFixedWing(mavType)) {\n return MAV_TYPE_FIXED_WING;\n } else if (QGCMAVLink::isMultiRotor(mavType)) {\n return MAV_TYPE_QUADROTOR;\n } else if (QGCMAVLink::isVTOL(mavType)) {\n return MAV_TYPE_VTOL_QUADROTOR;\n } else if (QGCMAVLink::isRover(mavType)) {\n return MAV_TYPE_GROUND_ROVER;\n } else if (QGCMAVLink::isSub(mavType)) {\n return MAV_TYPE_SUBMARINE;\n } else {\n return MAV_TYPE_GENERIC;\n }\n}\n\n\/\/\/ Add the next level of the hierarchy to a collapsed tree.\n\/\/\/ @param vehicle Collapsed tree is for this vehicle\n\/\/\/ @param cmdList List of mission commands to collapse into ui info\n\/\/\/ @param collapsedTree Tree we are collapsing into\nvoid MissionCommandTree::_collapseHierarchy(Vehicle* vehicle,\n const MissionCommandList* cmdList,\n QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n\n foreach (MAV_CMD command, cmdList->commandIds()) {\n MissionCommandUIInfo* uiInfo = cmdList->getUIInfo(command);\n if (uiInfo) {\n if (collapsedTree.contains(command)) {\n collapsedTree[command]->_overrideInfo(uiInfo);\n } else {\n collapsedTree[command] = new MissionCommandUIInfo(*uiInfo);\n }\n }\n }\n}\n\nvoid MissionCommandTree::_buildAvailableCommands(Vehicle* vehicle)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n\n if (_availableCommands.contains(baseFirmwareType) &&\n _availableCommands[baseFirmwareType].contains(baseVehicleType)) {\n \/\/ Available commands list already built\n return;\n }\n\n \/\/ Build new available commands list\n\n QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree = _availableCommands[baseFirmwareType][baseVehicleType];\n\n \/\/ Any Firmware, Any Vehicle\n _collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC], collapsedTree);\n\n \/\/ Any Firmware, Specific Vehicle\n if (baseVehicleType != MAV_TYPE_GENERIC) {\n _collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][baseVehicleType], collapsedTree);\n }\n\n \/\/ Known Firmware, Any Vehicle\n if (baseFirmwareType != MAV_AUTOPILOT_GENERIC) {\n _collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][MAV_TYPE_GENERIC], collapsedTree);\n\n \/\/ Known Firmware, Specific Vehicle\n if (baseVehicleType != MAV_TYPE_GENERIC) {\n _collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][baseVehicleType], collapsedTree);\n }\n }\n\n \/\/ Build category list\n QMapIterator<MAV_CMD, MissionCommandUIInfo*> iter(collapsedTree);\n while (iter.hasNext()) {\n iter.next();\n QString newCategory = iter.value()->category();\n if (!_availableCategories[baseFirmwareType][baseVehicleType].contains(newCategory)) {\n _availableCategories[baseFirmwareType][baseVehicleType].append(newCategory);\n }\n }\n}\n\nQStringList MissionCommandTree::_availableCategoriesForVehicle(Vehicle* vehicle)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n _buildAvailableCommands(vehicle);\n\n return _availableCategories[baseFirmwareType][baseVehicleType];\n}\n\nQString MissionCommandTree::friendlyName(MAV_CMD command)\n{\n MissionCommandList * commandList = _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];\n MissionCommandUIInfo* uiInfo = commandList->getUIInfo(command);\n\n if (uiInfo) {\n return uiInfo->friendlyName();\n } else {\n return QString(\"MAV_CMD(%1)\").arg((int)command);\n }\n}\n\nQString MissionCommandTree::rawName(MAV_CMD command)\n{\n MissionCommandList * commandList = _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];\n MissionCommandUIInfo* uiInfo = commandList->getUIInfo(command);\n\n if (uiInfo) {\n return uiInfo->rawName();\n } else {\n return QString(\"MAV_CMD(%1)\").arg((int)command);\n }\n}\n\nconst QList<MAV_CMD>& MissionCommandTree::allCommandIds(void) const\n{\n return _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC]->commandIds();\n}\n\nconst MissionCommandUIInfo* MissionCommandTree::getUIInfo(Vehicle* vehicle, MAV_CMD command)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n _buildAvailableCommands(vehicle);\n\n const QMap<MAV_CMD, MissionCommandUIInfo*>& infoMap = _availableCommands[baseFirmwareType][baseVehicleType];\n if (infoMap.contains(command)) {\n return infoMap[command];\n } else {\n return NULL;\n }\n}\n\nQVariantList MissionCommandTree::getCommandsForCategory(Vehicle* vehicle, const QString& category)\n{\n MAV_AUTOPILOT baseFirmwareType;\n MAV_TYPE baseVehicleType;\n\n _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);\n _buildAvailableCommands(vehicle);\n\n QVariantList list;\n QMap<MAV_CMD, MissionCommandUIInfo*> commandMap = _availableCommands[baseFirmwareType][baseVehicleType];\n foreach (MAV_CMD command, commandMap.keys()) {\n MissionCommandUIInfo* uiInfo = commandMap[command];\n if (uiInfo->category() == category) {\n list.append(QVariant::fromValue(uiInfo));\n }\n }\n\n return list;\n}\n\nvoid MissionCommandTree::_baseVehicleInfo(Vehicle* vehicle, MAV_AUTOPILOT& baseFirmwareType, MAV_TYPE& baseVehicleType) const\n{\n if (vehicle) {\n baseFirmwareType = _baseFirmwareType(vehicle->firmwareType());\n baseVehicleType = _baseVehicleType(vehicle->vehicleType());\n } else {\n \/\/ No Vehicle means offline editing\n baseFirmwareType = _baseFirmwareType((MAV_AUTOPILOT)QGroundControlQmlGlobal::offlineEditingFirmwareType()->rawValue().toInt());\n baseVehicleType = _baseVehicleType((MAV_TYPE)QGroundControlQmlGlobal::offlineEditingVehicleType()->rawValue().toInt());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"connection.h\"\n\nnamespace trikTelemetry {\n\nConnection::Connection(trikControl::Brick &brick)\n\t: trikKernel::Connection(trikKernel::Protocol::messageLength)\n\t, mBrick(brick)\n{\n}\n\nvoid Connection::processData(QByteArray const &data)\n{\n\tQString command(data);\n\n\tQString portsRequested(\"ports\");\n\tQString dataRequested(\"data\");\n\n\tQString answer;\n\n\tif (command.startsWith(dataRequested)) {\n\t\tanswer = \"data:\";\n\t\tanswer += \"analog:\";\n\t\tfor (QString port : mBrick.sensorPorts(trikControl::Sensor::analogSensor)) {\n\t\t\tanswer += port + \"=\" + QString::number(mBrick.sensor(port)->read()) + \":\";\n\t\t\tanswer += QString::number(mBrick.sensor(port)->readRawData()) + \",\";\n\t\t}\n\t\tanswer[answer.length() - 1] = ';';\n\t\tanswer += \"digital:\";\n\t\tfor (QString port : mBrick.sensorPorts(trikControl::Sensor::digitalSensor)) {\n\t\t\tanswer += port + \"=\" + QString::number(mBrick.sensor(port)->read()) + \":\";\n\t\t\tanswer += QString::number(mBrick.sensor(port)->readRawData()) + \",\";\n\t\t}\n\t\tanswer[answer.length() - 1] = ';';\n\t\tanswer += \"special:\";\n\t\tfor (QString port : mBrick.sensorPorts(trikControl::Sensor::specialSensor)) {\n\t\t\tanswer += port + \"=\" + QString::number(mBrick.sensor(port)->read()) + \":\";\n\t\t\tanswer += QString::number(mBrick.sensor(port)->readRawData()) + \",\";\n\t\t}\n\t\tanswer[answer.length() - 1] = ';';\n\t\tanswer += \"accelerometer:\" + serializeVector(mBrick.accelerometer()->read()) + \";\";\n\t\tanswer += \"gyroscope:\" + serializeVector(mBrick.gyroscope()->read());\n\t} else if (command.startsWith(portsRequested)) {\n\t\tanswer = \"ports:\";\n\t\tanswer += \"analog:\" + mBrick.sensorPorts(trikControl::Sensor::analogSensor).join(\",\") + \";\";\n\t\tanswer += \"digital:\" + mBrick.sensorPorts(trikControl::Sensor::digitalSensor).join(\",\") + \";\";\n\t\tanswer += \"special:\" + mBrick.sensorPorts(trikControl::Sensor::specialSensor).join(\",\");\n\t}\n\n\tsend(answer.toUtf8());\n}\n\nQString Connection::serializeVector(QVector<int> const &vector) {\n\tQString result = \"(\";\n\tfor (int coord : vector) {\n\t\tresult += QString::number(coord) + \",\";\n\t}\n\n\tresult[result.length() - 1] = ')';\n\treturn result;\n}\n\n}\n<commit_msg>protocol is expanded<commit_after>#include \"connection.h\"\n\nnamespace trikTelemetry {\n\nConnection::Connection(trikControl::Brick &brick)\n\t: trikKernel::Connection(trikKernel::Protocol::messageLength)\n\t, mBrick(brick)\n{\n}\n\nvoid Connection::processData(QByteArray const &data)\n{\n\tQString command(data);\n\n\tQString portsRequested(\"ports\");\n\tQString dataRequested(\"data\");\n\tQString singleSensorRequested(\"sensor:\");\n\tQString accelerometerRequested(\"AccelerometerPort\");\n\tQString gyroscopeRequested(\"GyroscopePort\");\n\n\tQString answer;\n\n\tif (command.startsWith(dataRequested)) {\n\t\tanswer = \"data:\";\n\t\tanswer += \"analog:\";\n\t\tfor (QString port : mBrick.sensorPorts(trikControl::Sensor::analogSensor)) {\n\t\t\tanswer += port + \"=\" + QString::number(mBrick.sensor(port)->read()) + \":\";\n\t\t\tanswer += QString::number(mBrick.sensor(port)->readRawData()) + \",\";\n\t\t}\n\t\tanswer[answer.length() - 1] = ';';\n\t\tanswer += \"digital:\";\n\t\tfor (QString port : mBrick.sensorPorts(trikControl::Sensor::digitalSensor)) {\n\t\t\tanswer += port + \"=\" + QString::number(mBrick.sensor(port)->read()) + \":\";\n\t\t\tanswer += QString::number(mBrick.sensor(port)->readRawData()) + \",\";\n\t\t}\n\t\tanswer[answer.length() - 1] = ';';\n\t\tanswer += \"special:\";\n\t\tfor (QString port : mBrick.sensorPorts(trikControl::Sensor::specialSensor)) {\n\t\t\tanswer += port + \"=\" + QString::number(mBrick.sensor(port)->read()) + \":\";\n\t\t\tanswer += QString::number(mBrick.sensor(port)->readRawData()) + \",\";\n\t\t}\n\t\tanswer[answer.length() - 1] = ';';\n\t\tanswer += \"accelerometer:\" + serializeVector(mBrick.accelerometer()->read()) + \";\";\n\t\tanswer += \"gyroscope:\" + serializeVector(mBrick.gyroscope()->read());\n\t} else if (command.startsWith(portsRequested)) {\n\t\tanswer = \"ports:\";\n\t\tanswer += \"analog:\" + mBrick.sensorPorts(trikControl::Sensor::analogSensor).join(\",\") + \";\";\n\t\tanswer += \"digital:\" + mBrick.sensorPorts(trikControl::Sensor::digitalSensor).join(\",\") + \";\";\n\t\tanswer += \"special:\" + mBrick.sensorPorts(trikControl::Sensor::specialSensor).join(\",\");\n\t} else if (command.startsWith(singleSensorRequested)) {\n\t\tanswer = command + \":\";\n\t\tcommand.remove(0, singleSensorRequested.length());\n\t\tif (command.startsWith(accelerometerRequested)) {\n\t\t\tint dimension = command.at(command.length() - 1).toAscii() - 'X';\n\t\t\tanswer += QString::number(mBrick.accelerometer()->read()[dimension]);\n\t\t} else if (command.startsWith(gyroscopeRequested)) {\n\t\t\tint dimension = command.at(command.length() - 1).toAscii() - 'X';\n\t\t\tanswer += QString::number(mBrick.gyroscope()->read()[dimension]);\n\t\t} else if (mBrick.sensorPorts(trikControl::Sensor::analogSensor).contains(command)\n\t\t\t\t|| mBrick.sensorPorts(trikControl::Sensor::digitalSensor).contains(command)\n\t\t\t\t|| mBrick.sensorPorts(trikControl::Sensor::specialSensor).contains(command)){\n\t\t\tanswer += QString::number(mBrick.sensor(command)->read());\n\t\t} else if (mBrick.encoderPorts().contains(command)) {\n\t\t\tanswer += QString::number(mBrick.encoder(command)->read());\n\t\t}\n\t}\n\n\tsend(answer.toUtf8());\n}\n\nQString Connection::serializeVector(QVector<int> const &vector) {\n\tQString result = \"(\";\n\tfor (int coord : vector) {\n\t\tresult += QString::number(coord) + \",\";\n\t}\n\n\tresult[result.length() - 1] = ')';\n\treturn result;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TaskPaneModule.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2007-04-03 15:55:41 $\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#include \"precompiled_sd.hxx\"\n\n#include \"TaskPaneModule.hxx\"\n#include \"ReadOnlyModeObserver.hxx\"\n#include \"framework\/FrameworkHelper.hxx\"\n\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/drawing\/framework\/XControllerManager.hpp>\n\n#include <comphelper\/processfactory.hxx>\n#include <cppuhelper\/compbase1.hxx>\n#include <boost\/enable_shared_from_this.hpp>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::drawing::framework;\nusing ::rtl::OUString;\nusing ::sd::framework::FrameworkHelper;\n\n\nnamespace sd { namespace framework {\n\nnamespace {\n\ntypedef ::cppu::WeakComponentImplHelper1 <\n ::com::sun::star::frame::XStatusListener\n > LocalReadOnlyModeObserverInterfaceBase;\n\n\/** This local class enables or disables the ResourceManager of a\n TaskPaneModule. It connects to a ReadOnlyModeObserver and is called\n when the state of the .uno:EditDoc command changes. When either the\n ResourceManager or the ReadOnlyModeObserver are disposed then the\n LocalReadOnlyModeObserver disposes itself. The link\n between the ResourceManager and the ReadOnlyModeObserver is removed and\n the ReadOnlyModeObserver typically looses its last reference and is\n destroyed.\n*\/\nclass LocalReadOnlyModeObserver\n : private MutexOwner,\n public LocalReadOnlyModeObserverInterfaceBase\n{\npublic:\n LocalReadOnlyModeObserver (\n const Reference<frame::XController>& rxController,\n const ::rtl::Reference<ResourceManager>& rpResourceManager)\n : MutexOwner(),\n LocalReadOnlyModeObserverInterfaceBase(maMutex),\n mpResourceManager(rpResourceManager),\n mpObserver(new ReadOnlyModeObserver(rxController))\n {\n mpObserver->AddStatusListener(this);\n\n Reference<lang::XComponent> xComponent (\n static_cast<XWeak*>(mpResourceManager.get()), UNO_QUERY);\n if (xComponent.is())\n xComponent->addEventListener(this);\n }\n\n ~LocalReadOnlyModeObserver (void)\n {\n }\n\n virtual void SAL_CALL disposing (void)\n {\n Reference<lang::XComponent> xComponent (static_cast<XWeak*>(mpObserver.get()), UNO_QUERY);\n if (xComponent.is())\n xComponent->dispose();\n\n xComponent = Reference<lang::XComponent>(\n static_cast<XWeak*>(mpResourceManager.get()), UNO_QUERY);\n if (xComponent.is())\n xComponent->removeEventListener(this);\n\n }\n\n virtual void SAL_CALL disposing (const com::sun::star::lang::EventObject& rEvent)\n throw(RuntimeException)\n {\n if (rEvent.Source == Reference<XInterface>(static_cast<XWeak*>(mpObserver.get())))\n {\n mpObserver = NULL;\n }\n else if (rEvent.Source == Reference<XInterface>(\n static_cast<XWeak*>(mpResourceManager.get())))\n {\n mpResourceManager = NULL;\n }\n dispose();\n }\n\n virtual void SAL_CALL statusChanged (const com::sun::star::frame::FeatureStateEvent& rEvent)\n throw(RuntimeException)\n {\n bool bReadWrite (true);\n if (rEvent.IsEnabled)\n rEvent.State >>= bReadWrite;\n\n if (bReadWrite)\n mpResourceManager->Enable();\n else\n mpResourceManager->Disable();\n }\n\nprivate:\n ::rtl::Reference<ResourceManager> mpResourceManager;\n ::rtl::Reference<ReadOnlyModeObserver> mpObserver;\n\n};\n}\n\n\n\n\n\/\/===== TaskPaneModule ====================================================\n\nvoid TaskPaneModule::Initialize (const Reference<frame::XController>& rxController)\n{\n ::rtl::Reference<ResourceManager> pResourceManager (\n new ResourceManager(\n rxController,\n FrameworkHelper::CreateResourceId(\n FrameworkHelper::msTaskPaneURL,\n FrameworkHelper::msRightPaneURL)));\n pResourceManager->AddActiveMainView(FrameworkHelper::msImpressViewURL);\n pResourceManager->AddActiveMainView(FrameworkHelper::msNotesViewURL);\n pResourceManager->AddActiveMainView(FrameworkHelper::msHandoutViewURL);\n pResourceManager->AddActiveMainView(FrameworkHelper::msSlideSorterURL);\n\n new LocalReadOnlyModeObserver(rxController, pResourceManager);\n\n try\n {\n \/\/ Create the TaskPaneService.\n Reference<lang::XMultiServiceFactory> xFactory (::comphelper::getProcessServiceFactory());\n const OUString sServiceName (::rtl::OUString::createFromAscii(\n \"com.sun.star.drawing.framework.TaskPaneService\"));\n Reference<XResourceController> xResourceController (\n xFactory->createInstance(sServiceName), UNO_QUERY_THROW);\n\n \/\/ Initialize it.\n Sequence<Any> aInitializationArguments(1);\n aInitializationArguments[0] = makeAny(rxController);\n Reference<lang::XInitialization> xInit (xResourceController, UNO_QUERY_THROW);\n xInit->initialize(aInitializationArguments);\n\n \/\/ Register it at the controller manager.\n Reference<XControllerManager> xControllerManager(rxController, UNO_QUERY_THROW);\n xControllerManager->registerResourceController(sServiceName, xResourceController);\n }\n catch (RuntimeException)\n {\n }\n}\n\n\n\n\n} } \/\/ end of namespace sd::framework\n<commit_msg>INTEGRATION: CWS presenterview (1.2.22); FILE MERGED 2007\/06\/19 08:27:38 af 1.2.22.1: #i18486# The task pane service is not used anymore.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TaskPaneModule.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2008-04-03 13:40:47 $\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#include \"precompiled_sd.hxx\"\n\n#include \"TaskPaneModule.hxx\"\n#include \"ReadOnlyModeObserver.hxx\"\n#include \"framework\/FrameworkHelper.hxx\"\n\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/drawing\/framework\/XControllerManager.hpp>\n\n#include <comphelper\/processfactory.hxx>\n#include <cppuhelper\/compbase1.hxx>\n#include <boost\/enable_shared_from_this.hpp>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::drawing::framework;\nusing ::rtl::OUString;\nusing ::sd::framework::FrameworkHelper;\n\n\nnamespace sd { namespace framework {\n\nnamespace {\n\ntypedef ::cppu::WeakComponentImplHelper1 <\n ::com::sun::star::frame::XStatusListener\n > LocalReadOnlyModeObserverInterfaceBase;\n\n\/** This local class enables or disables the ResourceManager of a\n TaskPaneModule. It connects to a ReadOnlyModeObserver and is called\n when the state of the .uno:EditDoc command changes. When either the\n ResourceManager or the ReadOnlyModeObserver are disposed then the\n LocalReadOnlyModeObserver disposes itself. The link\n between the ResourceManager and the ReadOnlyModeObserver is removed and\n the ReadOnlyModeObserver typically looses its last reference and is\n destroyed.\n*\/\nclass LocalReadOnlyModeObserver\n : private MutexOwner,\n public LocalReadOnlyModeObserverInterfaceBase\n{\npublic:\n LocalReadOnlyModeObserver (\n const Reference<frame::XController>& rxController,\n const ::rtl::Reference<ResourceManager>& rpResourceManager)\n : MutexOwner(),\n LocalReadOnlyModeObserverInterfaceBase(maMutex),\n mpResourceManager(rpResourceManager),\n mpObserver(new ReadOnlyModeObserver(rxController))\n {\n mpObserver->AddStatusListener(this);\n\n Reference<lang::XComponent> xComponent (\n static_cast<XWeak*>(mpResourceManager.get()), UNO_QUERY);\n if (xComponent.is())\n xComponent->addEventListener(this);\n }\n\n ~LocalReadOnlyModeObserver (void)\n {\n }\n\n virtual void SAL_CALL disposing (void)\n {\n Reference<lang::XComponent> xComponent (static_cast<XWeak*>(mpObserver.get()), UNO_QUERY);\n if (xComponent.is())\n xComponent->dispose();\n\n xComponent = Reference<lang::XComponent>(\n static_cast<XWeak*>(mpResourceManager.get()), UNO_QUERY);\n if (xComponent.is())\n xComponent->removeEventListener(this);\n\n }\n\n virtual void SAL_CALL disposing (const com::sun::star::lang::EventObject& rEvent)\n throw(RuntimeException)\n {\n if (rEvent.Source == Reference<XInterface>(static_cast<XWeak*>(mpObserver.get())))\n {\n mpObserver = NULL;\n }\n else if (rEvent.Source == Reference<XInterface>(\n static_cast<XWeak*>(mpResourceManager.get())))\n {\n mpResourceManager = NULL;\n }\n dispose();\n }\n\n virtual void SAL_CALL statusChanged (const com::sun::star::frame::FeatureStateEvent& rEvent)\n throw(RuntimeException)\n {\n bool bReadWrite (true);\n if (rEvent.IsEnabled)\n rEvent.State >>= bReadWrite;\n\n if (bReadWrite)\n mpResourceManager->Enable();\n else\n mpResourceManager->Disable();\n }\n\nprivate:\n ::rtl::Reference<ResourceManager> mpResourceManager;\n ::rtl::Reference<ReadOnlyModeObserver> mpObserver;\n\n};\n}\n\n\n\n\n\/\/===== TaskPaneModule ====================================================\n\nvoid TaskPaneModule::Initialize (const Reference<frame::XController>& rxController)\n{\n ::rtl::Reference<ResourceManager> pResourceManager (\n new ResourceManager(\n rxController,\n FrameworkHelper::CreateResourceId(\n FrameworkHelper::msTaskPaneURL,\n FrameworkHelper::msRightPaneURL)));\n pResourceManager->AddActiveMainView(FrameworkHelper::msImpressViewURL);\n pResourceManager->AddActiveMainView(FrameworkHelper::msNotesViewURL);\n pResourceManager->AddActiveMainView(FrameworkHelper::msHandoutViewURL);\n pResourceManager->AddActiveMainView(FrameworkHelper::msSlideSorterURL);\n\n new LocalReadOnlyModeObserver(rxController, pResourceManager);\n}\n\n\n\n\n} } \/\/ end of namespace sd::framework\n<|endoftext|>"} {"text":"<commit_before>#define ProofEventProc_cxx\n\/\/ The class definition in ProofEventProc.h has been generated automatically\n\/\/ by the ROOT utility TTree::MakeSelector(). This class is derived\n\/\/ from the ROOT class TSelector. For more information on the TSelector\n\/\/ framework see $ROOTSYS\/README\/README.SELECTOR or the ROOT User Manual.\n\n\/\/ The following methods are defined in this file:\n\/\/ Begin(): called everytime a loop on the tree starts,\n\/\/ a convenient place to create your histograms.\n\/\/ SlaveBegin(): called after Begin(), when on PROOF called only on the\n\/\/ slave servers.\n\/\/ Process(): called for each event, in this function you decide what\n\/\/ to read and fill your histograms.\n\/\/ SlaveTerminate: called at the end of the loop on the tree, when on PROOF\n\/\/ called only on the slave servers.\n\/\/ Terminate(): called at the end of the loop on the tree,\n\/\/ a convenient place to draw\/fit your histograms.\n\/\/\n\/\/ To use this file, try the following session on your Tree T:\n\/\/\n\/\/ Root > T->Process(\"ProofEventProc.C\")\n\/\/ Root > T->Process(\"ProofEventProc.C\",\"some options\")\n\/\/ Root > T->Process(\"ProofEventProc.C+\")\n\/\/\n\n#include \"ProofEventProc.h\"\n#include <TStyle.h>\n#include \"TCanvas.h\"\n#include \"TH1F.h\"\n#include \"TH1I.h\"\n\n\nvoid ProofEventProc::Begin(TTree *)\n{\n \/\/ The Begin() function is called at the start of the query.\n \/\/ When running with PROOF Begin() is only called on the client.\n \/\/ The tree argument is deprecated (on PROOF 0 is passed).\n\n TString option = GetOption();\n\n}\n\nvoid ProofEventProc::SlaveBegin(TTree *tree)\n{\n \/\/ The SlaveBegin() function is called after the Begin() function.\n \/\/ When running with PROOF SlaveBegin() is called on each slave server.\n \/\/ The tree argument is deprecated (on PROOF 0 is passed).\n\n Init(tree);\n\n \/\/ How much to read\n fFullRead = kFALSE;\n TNamed *nm = dynamic_cast<TNamed *>(fInput->FindObject(\"ProofEventProc_Read\"));\n if (nm && !strcmp(nm->GetTitle(), \"readall\"))\n fFullRead = kTRUE;\n Info(\"SlaveBegin\", \"'%s' reading\", (fFullRead ? \"full\" : \"optimized\"));\n\n TString option = GetOption();\n\n fPtHist = new TH1F(\"pt_dist\",\"p_{T} Distribution\",100,0,5);\n fPtHist->SetDirectory(0);\n fPtHist->GetXaxis()->SetTitle(\"p_{T}\");\n fPtHist->GetYaxis()->SetTitle(\"dN\/p_{T}dp_{T}\");\n\n fOutput->Add(fPtHist);\n\n fNTracksHist = new TH1I(\"ntracks_dist\",\"N_{Tracks} per Event Distribution\",5,0,5);\n fNTracksHist->SetDirectory(0);\n fNTracksHist->GetXaxis()->SetTitle(\"N_{Tracks}\");\n fNTracksHist->GetYaxis()->SetTitle(\"N_{Events}\");\n\n fOutput->Add(fNTracksHist);\n\n}\n\nBool_t ProofEventProc::Process(Long64_t entry)\n{\n \/\/ The Process() function is called for each entry in the tree (or possibly\n \/\/ keyed object in the case of PROOF) to be processed. The entry argument\n \/\/ specifies which entry in the currently loaded tree is to be processed.\n \/\/ It can be passed to either TTree::GetEntry() or TBranch::GetEntry()\n \/\/ to read either all or the required parts of the data. When processing\n \/\/ keyed objects with PROOF, the object is already loaded and is available\n \/\/ via the fObject pointer.\n \/\/\n \/\/ This function should contain the \"body\" of the analysis. It can contain\n \/\/ simple or elaborate selection criteria, run algorithms on the data\n \/\/ of the event and typically fill histograms.\n\n \/\/ WARNING when a selector is used with a TChain, you must use\n \/\/ the pointer to the current TTree to call GetEntry(entry).\n \/\/ The entry is always the local entry number in the current tree.\n \/\/ Assuming that fChain is the pointer to the TChain being processed,\n \/\/ use fChain->GetTree()->GetEntry(entry).\n\n if (fFullRead) {\n fChain->GetTree()->GetEntry(entry);\n } else {\n b_event_fNtrack->GetEntry(entry);\n }\n\n fNTracksHist->Fill(fNtrack);\n\n if (fNtrack > 0) {\n if (!fFullRead) b_fTracks->GetEntry(entry);\n for (Int_t j=0;j<fTracks->GetEntries();j++){\n Track *curtrack = dynamic_cast<Track*>(fTracks->At(j));\n fPtHist->Fill(curtrack->GetPt(),1.\/curtrack->GetPt());\n }\n fTracks->Clear(\"C\");\n }\n\n return kTRUE;\n}\n\nvoid ProofEventProc::SlaveTerminate()\n{\n \/\/ The SlaveTerminate() function is called after all entries or objects\n \/\/ have been processed. When running with PROOF SlaveTerminate() is called\n \/\/ on each slave server.\n\n}\n\nvoid ProofEventProc::Terminate()\n{\n \/\/ The Terminate() function is the last function to be called during\n \/\/ a query. It always runs on the client, it can be used to present\n \/\/ the results graphically or save the results to file.\n\n TCanvas* canvas = new TCanvas(\"can\",\"can\",800,600);\n canvas->SetBorderMode(0);\n canvas->SetLogy();\n TH1F* h = dynamic_cast<TH1F*>(fOutput->FindObject(\"pt_dist\"));\n if (h) h->DrawCopy();\n else Warning(\"Terminate\", \"no pt dist found\");\n\n}\n<commit_msg>Add missing protections to be able to run in a non-PROOF session<commit_after>#define ProofEventProc_cxx\n\/\/ The class definition in ProofEventProc.h has been generated automatically\n\/\/ by the ROOT utility TTree::MakeSelector(). This class is derived\n\/\/ from the ROOT class TSelector. For more information on the TSelector\n\/\/ framework see $ROOTSYS\/README\/README.SELECTOR or the ROOT User Manual.\n\n\/\/ The following methods are defined in this file:\n\/\/ Begin(): called everytime a loop on the tree starts,\n\/\/ a convenient place to create your histograms.\n\/\/ SlaveBegin(): called after Begin(), when on PROOF called only on the\n\/\/ slave servers.\n\/\/ Process(): called for each event, in this function you decide what\n\/\/ to read and fill your histograms.\n\/\/ SlaveTerminate: called at the end of the loop on the tree, when on PROOF\n\/\/ called only on the slave servers.\n\/\/ Terminate(): called at the end of the loop on the tree,\n\/\/ a convenient place to draw\/fit your histograms.\n\/\/\n\/\/ To use this file, try the following session on your Tree T:\n\/\/\n\/\/ Root > T->Process(\"ProofEventProc.C\")\n\/\/ Root > T->Process(\"ProofEventProc.C\",\"some options\")\n\/\/ Root > T->Process(\"ProofEventProc.C+\")\n\/\/\n\n#include \"ProofEventProc.h\"\n#include <TStyle.h>\n#include \"TCanvas.h\"\n#include \"TH1F.h\"\n#include \"TH1I.h\"\n\n\nvoid ProofEventProc::Begin(TTree *)\n{\n \/\/ The Begin() function is called at the start of the query.\n \/\/ When running with PROOF Begin() is only called on the client.\n \/\/ The tree argument is deprecated (on PROOF 0 is passed).\n\n TString option = GetOption();\n\n}\n\nvoid ProofEventProc::SlaveBegin(TTree *tree)\n{\n \/\/ The SlaveBegin() function is called after the Begin() function.\n \/\/ When running with PROOF SlaveBegin() is called on each slave server.\n \/\/ The tree argument is deprecated (on PROOF 0 is passed).\n\n Init(tree);\n\n \/\/ How much to read\n fFullRead = kFALSE;\n TNamed *nm = 0;\n if (fInput) \n nm = dynamic_cast<TNamed *>(fInput->FindObject(\"ProofEventProc_Read\"));\n if (nm && !strcmp(nm->GetTitle(), \"readall\"))\n fFullRead = kTRUE;\n Info(\"SlaveBegin\", \"'%s' reading\", (fFullRead ? \"full\" : \"optimized\"));\n\n TString option = GetOption();\n\n fPtHist = new TH1F(\"pt_dist\",\"p_{T} Distribution\",100,0,5);\n fPtHist->SetDirectory(0);\n fPtHist->GetXaxis()->SetTitle(\"p_{T}\");\n fPtHist->GetYaxis()->SetTitle(\"dN\/p_{T}dp_{T}\");\n\n fOutput->Add(fPtHist);\n\n fNTracksHist = new TH1I(\"ntracks_dist\",\"N_{Tracks} per Event Distribution\",5,0,5);\n fNTracksHist->SetDirectory(0);\n fNTracksHist->GetXaxis()->SetTitle(\"N_{Tracks}\");\n fNTracksHist->GetYaxis()->SetTitle(\"N_{Events}\");\n\n fOutput->Add(fNTracksHist);\n\n}\n\nBool_t ProofEventProc::Process(Long64_t entry)\n{\n \/\/ The Process() function is called for each entry in the tree (or possibly\n \/\/ keyed object in the case of PROOF) to be processed. The entry argument\n \/\/ specifies which entry in the currently loaded tree is to be processed.\n \/\/ It can be passed to either TTree::GetEntry() or TBranch::GetEntry()\n \/\/ to read either all or the required parts of the data. When processing\n \/\/ keyed objects with PROOF, the object is already loaded and is available\n \/\/ via the fObject pointer.\n \/\/\n \/\/ This function should contain the \"body\" of the analysis. It can contain\n \/\/ simple or elaborate selection criteria, run algorithms on the data\n \/\/ of the event and typically fill histograms.\n\n \/\/ WARNING when a selector is used with a TChain, you must use\n \/\/ the pointer to the current TTree to call GetEntry(entry).\n \/\/ The entry is always the local entry number in the current tree.\n \/\/ Assuming that fChain is the pointer to the TChain being processed,\n \/\/ use fChain->GetTree()->GetEntry(entry).\n\n if (fFullRead) {\n fChain->GetTree()->GetEntry(entry);\n } else {\n b_event_fNtrack->GetEntry(entry);\n }\n\n fNTracksHist->Fill(fNtrack);\n\n if (fNtrack > 0) {\n if (!fFullRead) b_fTracks->GetEntry(entry);\n for (Int_t j=0;j<fTracks->GetEntries();j++){\n Track *curtrack = dynamic_cast<Track*>(fTracks->At(j));\n if (curtrack)\n fPtHist->Fill(curtrack->GetPt(),1.\/curtrack->GetPt());\n }\n fTracks->Clear(\"C\");\n }\n\n return kTRUE;\n}\n\nvoid ProofEventProc::SlaveTerminate()\n{\n \/\/ The SlaveTerminate() function is called after all entries or objects\n \/\/ have been processed. When running with PROOF SlaveTerminate() is called\n \/\/ on each slave server.\n\n}\n\nvoid ProofEventProc::Terminate()\n{\n \/\/ The Terminate() function is the last function to be called during\n \/\/ a query. It always runs on the client, it can be used to present\n \/\/ the results graphically or save the results to file.\n\n TCanvas* canvas = new TCanvas(\"can\",\"can\",800,600);\n canvas->SetBorderMode(0);\n canvas->SetLogy();\n TH1F* h = dynamic_cast<TH1F*>(fOutput->FindObject(\"pt_dist\"));\n if (h) h->DrawCopy();\n else Warning(\"Terminate\", \"no pt dist found\");\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"value.h\"\n#include <vespa\/vespalib\/util\/compressor.h>\n#include <xxhash.h>\n\nusing vespalib::compression::compress;\nusing vespalib::compression::decompress;\n\nnamespace search::docstore {\n\nValue::Value()\n : _syncToken(0),\n _uncompressedCrc(0),\n _compressedSize(0),\n _uncompressedSize(0),\n _buf(),\n _compression(CompressionConfig::NONE)\n{}\n\nValue::Value(uint64_t syncToken)\n : _syncToken(syncToken),\n _uncompressedCrc(0),\n _compressedSize(0),\n _uncompressedSize(0),\n _buf(),\n _compression(CompressionConfig::NONE)\n{}\n\nValue::Value(const Value &rhs) = default;\n\nValue::~Value() = default;\n\nconst void *\nValue::get() const {\n return _buf ? _buf->get() : nullptr;\n}\n\nvoid\nValue::set(vespalib::DataBuffer &&buf, ssize_t len) {\n set(std::move(buf), len, CompressionConfig());\n}\n\nnamespace {\n\nvespalib::alloc::Alloc\ncompact(size_t sz, vespalib::alloc::Alloc buf) {\n if (vespalib::roundUp2inN(sz) < vespalib::roundUp2inN(buf.size())) {\n vespalib::alloc::Alloc shrunk = buf.create(sz);\n memcpy(shrunk.get(), buf.get(), sz);\n return shrunk;\n }\n return buf;\n}\n\n}\nvoid\nValue::set(vespalib::DataBuffer &&buf, ssize_t len, const CompressionConfig &compression) {\n assert(len < std::numeric_limits<uint32_t>::max());\n \/\/Underlying buffer must be identical to allow swap.\n vespalib::DataBuffer compressed(buf.getData(), 0u);\n vespalib::ConstBufferRef input(buf.getData(), len);\n CompressionConfig::Type type = compress(compression, input, compressed, true);\n _compressedSize = compressed.getDataLen();\n _compression = type;\n _uncompressedSize = len;\n _uncompressedCrc = XXH64(input.c_str(), input.size(), 0);\n _buf = std::make_shared<Alloc>(compact(_compressedSize,(buf.getData() == compressed.getData())\n ? std::move(buf).stealBuffer()\n : std::move(compressed).stealBuffer()));\n\n assert(((type == CompressionConfig::NONE) &&\n (len == ssize_t(_compressedSize))) ||\n ((type != CompressionConfig::NONE) &&\n (len > ssize_t(_compressedSize))));\n}\n\nValue::Result\nValue::decompressed() const {\n vespalib::DataBuffer uncompressed(_buf.get(), (size_t) 0);\n decompress(getCompression(), getUncompressedSize(), vespalib::ConstBufferRef(*this, size()), uncompressed, true);\n uint64_t crc = XXH64(uncompressed.getData(), uncompressed.getDataLen(), 0);\n return std::make_pair<vespalib::DataBuffer, bool>(std::move(uncompressed), crc == _uncompressedCrc);\n}\n\n}\n<commit_msg>Use 32M as mmap limit during decompression of documents<commit_after>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"value.h\"\n#include <vespa\/vespalib\/util\/compressor.h>\n#include <xxhash.h>\n\nusing vespalib::compression::compress;\nusing vespalib::compression::decompress;\n\nnamespace search::docstore {\n\nValue::Value()\n : _syncToken(0),\n _uncompressedCrc(0),\n _compressedSize(0),\n _uncompressedSize(0),\n _buf(),\n _compression(CompressionConfig::NONE)\n{}\n\nValue::Value(uint64_t syncToken)\n : _syncToken(syncToken),\n _uncompressedCrc(0),\n _compressedSize(0),\n _uncompressedSize(0),\n _buf(),\n _compression(CompressionConfig::NONE)\n{}\n\nValue::Value(const Value &rhs) = default;\n\nValue::~Value() = default;\n\nconst void *\nValue::get() const {\n return _buf ? _buf->get() : nullptr;\n}\n\nvoid\nValue::set(vespalib::DataBuffer &&buf, ssize_t len) {\n set(std::move(buf), len, CompressionConfig());\n}\n\nnamespace {\n\nvespalib::alloc::Alloc\ncompact(size_t sz, vespalib::alloc::Alloc buf) {\n if (vespalib::roundUp2inN(sz) < vespalib::roundUp2inN(buf.size())) {\n vespalib::alloc::Alloc shrunk = buf.create(sz);\n memcpy(shrunk.get(), buf.get(), sz);\n return shrunk;\n }\n return buf;\n}\n\n}\nvoid\nValue::set(vespalib::DataBuffer &&buf, ssize_t len, const CompressionConfig &compression) {\n assert(len < std::numeric_limits<uint32_t>::max());\n \/\/Underlying buffer must be identical to allow swap.\n vespalib::DataBuffer compressed(buf.getData(), 0u);\n vespalib::ConstBufferRef input(buf.getData(), len);\n CompressionConfig::Type type = compress(compression, input, compressed, true);\n _compressedSize = compressed.getDataLen();\n _compression = type;\n _uncompressedSize = len;\n _uncompressedCrc = XXH64(input.c_str(), input.size(), 0);\n _buf = std::make_shared<Alloc>(compact(_compressedSize,(buf.getData() == compressed.getData())\n ? std::move(buf).stealBuffer()\n : std::move(compressed).stealBuffer()));\n\n assert(((type == CompressionConfig::NONE) &&\n (len == ssize_t(_compressedSize))) ||\n ((type != CompressionConfig::NONE) &&\n (len > ssize_t(_compressedSize))));\n}\n\nValue::Result\nValue::decompressed() const {\n vespalib::DataBuffer uncompressed(0, 1, Alloc::alloc(0, 16 * vespalib::alloc::MemoryAllocator::HUGEPAGE_SIZE));\n decompress(getCompression(), getUncompressedSize(), vespalib::ConstBufferRef(*this, size()), uncompressed, true);\n uint64_t crc = XXH64(uncompressed.getData(), uncompressed.getDataLen(), 0);\n return std::make_pair<vespalib::DataBuffer, bool>(std::move(uncompressed), crc == _uncompressedCrc);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Example of analysis class for the H1 data using code generated by MakeProxy.\n\/\/ ===========================================================================\n\/\/\n\/\/ This file uses 4 large data sets from the H1 collaboration at DESY Hamburg.\n\/\/ One can access these data sets (277 MBytes) from the standard Root web site\n\/\/ at: ftp:\/\/root.cern.ch\/root\/h1analysis\/\n\/\/ The Physics plots below generated by this example cannot be produced when\n\/\/ using smaller data sets.\n\/\/\n\/\/ There are several ways to analyze data stored in a Root Tree\n\/\/ -Using TTree::Draw: This is very convenient and efficient for small tasks.\n\/\/ A TTree::Draw call produces one histogram at the time. The histogram\n\/\/ is automatically generated. The selection expression may be specified\n\/\/ in the command line.\n\/\/\n\/\/ -Using the TTreeViewer: This is a graphical interface to TTree::Draw\n\/\/ with the same functionality.\n\/\/\n\/\/ -Using the code generated by TTree::MakeClass: In this case, the user\n\/\/ creates an instance of the analysis class. He has the control over\n\/\/ the event loop and he can generate an unlimited number of histograms.\n\/\/\n\/\/ -Using the code generated by TTree::MakeSelector. Like for the code\n\/\/ generated by TTree::MakeClass, the user can do complex analysis.\n\/\/ However, he cannot control the event loop. The event loop is controlled\n\/\/ by TTree::Process called by the user. This solution is illustrated\n\/\/ by the current code. The advantage of this method is that it can be run\n\/\/ in a parallel environment using PROOF (the Parallel Root Facility).\n\/\/\n\/\/ A chain of 4 files (originally converted from PAW ntuples) is used\n\/\/ to illustrate the various ways to loop on Root data sets.\n\/\/ Each data set contains a Root Tree named \"h42\"\n\/\/\n\/\/ h1analysProxy.C can be used either via TTree::Draw:\n\/\/ h42->Draw(\"h1analysisProxy.C\");\n\/\/ or it can be used directly with TTree::MakeProxy, for example to generate a\n\/\/ shared library. TTree::MakeProxy will generate a TSelector skeleton that\n\/\/ include h1analysProxy.C:\n\/\/ h42->MakeProxy(\"h1sel\",\"h1analysisProxy.C\");\n\/\/ This produces one file: h1sel.h which does a #include \"h1analysProxy.C\"\n\/\/ The h1sel class is derived from the Root class TSelector and can then \n\/\/ be used as:\n\/\/ h42->Process(\"h1sel.h+\");\n\/\/\n\/\/ The following members functions are called by the TTree::Process functions.\n\/\/ h1analysProxy_Begin(): called everytime a loop on the tree starts.\n\/\/ a convenient place to create your histograms.\n\/\/ h1analysProxy_SlaveBegin():\n\/\/\n\/\/ h1analysProxy_Notify(): This function is called at the first entry of a new Tree\n\/\/ in a chain.\n\/\/ h1analysProxy_Process(): called to analyze each entry.\n\/\/\n\/\/ h1analysProxy_SlaveTerminate():\n\/\/\n\/\/ h1analysProxy_Terminate(): called at the end of a loop on a TTree.\n\/\/ a convenient place to draw\/fit your histograms.\n\/\/\n\/\/ To use this file, try the following session\n\/\/\n\/\/ Root > gROOT->Time(); \/\/will show RT & CPU time per command\n\/\/\n\/\/==> A- create a TChain with the 4 H1 data files\n\/\/ The chain can be created by executed the short macro h1chain.C below:\n\/\/ {\n\/\/ TChain chain(\"h42\");\n\/\/ chain.Add(\"$H1\/dstarmb.root\"); \/\/ 21330730 bytes 21920 events\n\/\/ chain.Add(\"$H1\/dstarp1a.root\"); \/\/ 71464503 bytes 73243 events\n\/\/ chain.Add(\"$H1\/dstarp1b.root\"); \/\/ 83827959 bytes 85597 events\n\/\/ chain.Add(\"$H1\/dstarp2.root\"); \/\/ 100675234 bytes 103053 events\n\/\/ \/\/where $H1 is a system symbol pointing to the H1 data directory.\n\/\/ }\n\/\/\n\/\/ Root > .x h1chain.C\n\/\/\n\/\/==> B- loop on all events\n\/\/ Root > chain.Draw(\"h1analysisProxy.C\")\n\/\/\n\/\/==> C- same as B, but in addition fill the event list with selected entries.\n\/\/ The event list is saved to a file \"elist.root\" by the Terminate function.\n\/\/ To see the list of selected events, you can do elist->Print(\"all\").\n\/\/ The selection function has selected 7525 events out of the 283813 events\n\/\/ in the chain of files. (2.65 per cent)\n\/\/ Root > chain.Draw(\"h1analysisProxy.C\",\"\",\"fillList\")\n\/\/\n\/\/==> D- Process only entries in the event list\n\/\/ The event list is read from the file in elist.root generated by step C\n\/\/ Root > chain.Draw(\"h1analysisProxy.C\",\"\",\"useList\")\n\/\/\/\/\n\/\/ The commands executed with the 3 different methods B,C and D\n\/\/ produce two canvases shown below:\n\/\/ begin_html <a href=\"gif\/h1analysis_dstar.gif\" >the Dstar plot<\/a> end_html\n\/\/ begin_html <a href=\"gif\/h1analysis_tau.gif\" >the Tau D0 plot<\/a> end_html\n\/\/\n\/\/Author; Philippe Canal from original h1analysis.C by Rene Brun\n\nTEventList *elist;\nBool_t useList, fillList;\nTH1F *hdmd;\nTH2F *h2;\n\n\/\/_____________________________________________________________________\nvoid h1analysisProxy_Begin(TTree * \/* tree *\/ )\n{\n\/\/ function called before starting the event loop\n\/\/ -it performs some cleanup\n\/\/ -it creates histograms\n\/\/ -it sets some initialisation for the event list\n\n \/\/print the option specified in the Process function.\n TString option = GetOption();\n printf(\"Starting (begin) h1analysis with process option: %s\\n\",option.Data());\n\n \/\/some cleanup in case this function had already been executed\n \/\/delete any previously generated histograms or functions\n gDirectory->Delete(\"hdmd\");\n gDirectory->Delete(\"h2*\");\n delete gROOT->GetFunction(\"f5\");\n delete gROOT->GetFunction(\"f2\");\n}\n\n\/\/_____________________________________________________________________\nvoid h1analysisProxy_SlaveBegin(TTree *tree)\n{\n\/\/ function called before starting the event loop\n\/\/ -it performs some cleanup\n\/\/ -it creates histograms\n\/\/ -it sets some initialisation for the event list\n\n \/\/initialize the Tree branch addresses\n Init(tree);\n\n \/\/print the option specified in the Process function.\n TString option = GetOption();\n printf(\"Starting (slave) h1analysis with process option: %s\\n\",option.Data());\n\n \/\/some cleanup in case this function had already been executed\n \/\/delete any previously generated histograms or functions\n gDirectory->Delete(\"hdmd\");\n gDirectory->Delete(\"h2*\");\n delete gROOT->GetFunction(\"f5\");\n delete gROOT->GetFunction(\"f2\");\n\n \/\/create histograms\n hdmd = new TH1F(\"hdmd\",\"dm_d\",40,0.13,0.17);\n h2 = new TH2F(\"h2\",\"ptD0 vs dm_d\",30,0.135,0.165,30,-3,6);\n\n fOutput->Add(hdmd);\n fOutput->Add(h2);\n\n \/\/process cases with event list\n fillList = kFALSE;\n useList = kFALSE;\n tree->SetEventList(0);\n delete gDirectory->GetList()->FindObject(\"elist\");\n\n \/\/ case when one creates\/fills the event list\n if (option.Contains(\"fillList\")) {\n fillList = kTRUE;\n elist = new TEventList(\"elist\",\"selection from Cut\",5000);\n } else elist = 0;\n\n \/\/ case when one uses the event list generated in a previous call\n if (option.Contains(\"useList\")) {\n useList = kTRUE;\n TFile f(\"elist.root\");\n elist = (TEventList*)f.Get(\"elist\");\n if (elist) elist->SetDirectory(0); \/\/otherwise the file destructor will delete elist\n tree->SetEventList(elist);\n }\n\n}\n\nDouble_t h1analysisProxy() {\n return 0;\n}\n\n\/\/_____________________________________________________________________\nBool_t h1analysisProxy_Process(Long64_t entry)\n{\n\/\/ entry is the entry number in the current Tree\n\/\/ Selection function to select D* and D0.\n\n \/\/in case one event list is given in input, the selection has already been done.\n if (!useList) {\n\n float f1 = md0_d;\n float f2 = md0_d-1.8646;\n bool test = TMath::Abs(md0_d-1.8646) >= 0.04;\n if (gDebug>0) fprintf(stderr,\"entry #%lld f1=%f f2=%f test=%d\\n\",\n fChain->GetReadEntry(),f1,f2,test);\n \n if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE;\n if (ptds_d <= 2.5) return kFALSE;\n if (TMath::Abs(etads_d) >= 1.5) return kFALSE;\n \n int cik = ik-1; \/\/original ik used f77 convention starting at 1\n int cipi = ipi-1; \/\/original ipi used f77 convention starting at 1\n \n f1 = nhitrp[cik];\n f2 = nhitrp[cipi];\n test = nhitrp[cik]*nhitrp[cipi] <= 1;\n if (gDebug>0) fprintf(stderr,\"entry #%lld f1=%f f2=%f test=%d\\n\",\n fChain->GetReadEntry(),f1,f2,test);\n \n if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE;\n if (rend[cik] -rstart[cik] <= 22) return kFALSE;\n if (rend[cipi]-rstart[cipi] <= 22) return kFALSE;\n if (nlhk[cik] <= 0.1) return kFALSE;\n if (nlhpi[cipi] <= 0.1) return kFALSE;\n \/\/ fix because read-only \n if (nlhpi[ipis-1] <= 0.1) return kFALSE;\n if (njets < 1) return kFALSE;\n \n }\n \/\/ if option fillList, fill the event list\n if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry));\n\n \/\/fill some histograms\n hdmd->Fill(dm_d);\n h2->Fill(dm_d,rpd0_t\/0.029979*1.8646\/ptd0_d);\n\n return kTRUE;\n}\n\n\n\/\/_____________________________________________________________________\nvoid h1analysisProxy_SlaveTerminate()\n{\n \/\/ nothing to be done\n printf(\"Terminate (slave) h1analysis\\n\");\n}\n\n\/\/_____________________________________________________________________\nvoid h1analysisProxy_Terminate()\n{\n printf(\"Terminate (final) h1analysis\\n\");\n\n \/\/ function called at the end of the event loop\n\n hdmd = dynamic_cast<TH1F*>(fOutput->FindObject(\"hdmd\"));\n h2 = dynamic_cast<TH2F*>(fOutput->FindObject(\"h2\"));\n\n if (hdmd == 0 || h2 == 0) {\n Error(\"Terminate\", \"hdmd = %p , h2 = %p\", hdmd, h2);\n return;\n }\n\n \/\/create the canvas for the h1analysis fit\n gStyle->SetOptFit();\n TCanvas *c1 = new TCanvas(\"c1\",\"h1analysis analysis\",10,10,800,600);\n c1->SetBottomMargin(0.15);\n hdmd->GetXaxis()->SetTitle(\"m_{K#pi#pi} - m_{K#pi}[GeV\/c^{2}]\");\n hdmd->GetXaxis()->SetTitleOffset(1.4);\n\n \/\/fit histogram hdmd with function f5 using the loglikelihood option\n TF1 *f5 = new TF1(\"f5\",fdm5,0.139,0.17,5);\n f5->SetParameters(1000000, .25, 2000, .1454, .001);\n hdmd->Fit(\"f5\",\"lr\");\n\n \/\/create the canvas for tau d0\n gStyle->SetOptFit(0);\n gStyle->SetOptStat(1100);\n TCanvas *c2 = new TCanvas(\"c2\",\"tauD0\",100,100,800,600);\n c2->SetGrid();\n c2->SetBottomMargin(0.15);\n\n \/\/ Project slices of 2-d histogram h2 along X , then fit each slice\n \/\/ with function f2 and make a histogram for each fit parameter\n \/\/ Note that the generated histograms are added to the list of objects\n \/\/ in the current directory.\n TF1 *f2 = new TF1(\"f2\",fdm2,0.139,0.17,2);\n f2->SetParameters(10000, 10);\n h2->FitSlicesX(f2,0,0,1,\"qln\");\n TH1D *h2_1 = (TH1D*)gDirectory->Get(\"h2_1\");\n h2_1->GetXaxis()->SetTitle(\"#tau[ps]\");\n h2_1->SetMarkerStyle(21);\n h2_1->Draw();\n c2->Update();\n TLine *line = new TLine(0,0,0,c2->GetUymax());\n line->Draw();\n\n \/\/save the event list to a Root file if one was produced\n if (fillList) {\n TFile efile(\"elist.root\",\"recreate\");\n elist->Write();\n }\n}\n<commit_msg>Fix arguments to FitSlicesX (fix #21519 to h1analysis.C)<commit_after>\/\/ Example of analysis class for the H1 data using code generated by MakeProxy.\n\/\/ ===========================================================================\n\/\/\n\/\/ This file uses 4 large data sets from the H1 collaboration at DESY Hamburg.\n\/\/ One can access these data sets (277 MBytes) from the standard Root web site\n\/\/ at: ftp:\/\/root.cern.ch\/root\/h1analysis\/\n\/\/ The Physics plots below generated by this example cannot be produced when\n\/\/ using smaller data sets.\n\/\/\n\/\/ There are several ways to analyze data stored in a Root Tree\n\/\/ -Using TTree::Draw: This is very convenient and efficient for small tasks.\n\/\/ A TTree::Draw call produces one histogram at the time. The histogram\n\/\/ is automatically generated. The selection expression may be specified\n\/\/ in the command line.\n\/\/\n\/\/ -Using the TTreeViewer: This is a graphical interface to TTree::Draw\n\/\/ with the same functionality.\n\/\/\n\/\/ -Using the code generated by TTree::MakeClass: In this case, the user\n\/\/ creates an instance of the analysis class. He has the control over\n\/\/ the event loop and he can generate an unlimited number of histograms.\n\/\/\n\/\/ -Using the code generated by TTree::MakeSelector. Like for the code\n\/\/ generated by TTree::MakeClass, the user can do complex analysis.\n\/\/ However, he cannot control the event loop. The event loop is controlled\n\/\/ by TTree::Process called by the user. This solution is illustrated\n\/\/ by the current code. The advantage of this method is that it can be run\n\/\/ in a parallel environment using PROOF (the Parallel Root Facility).\n\/\/\n\/\/ A chain of 4 files (originally converted from PAW ntuples) is used\n\/\/ to illustrate the various ways to loop on Root data sets.\n\/\/ Each data set contains a Root Tree named \"h42\"\n\/\/\n\/\/ h1analysProxy.C can be used either via TTree::Draw:\n\/\/ h42->Draw(\"h1analysisProxy.C\");\n\/\/ or it can be used directly with TTree::MakeProxy, for example to generate a\n\/\/ shared library. TTree::MakeProxy will generate a TSelector skeleton that\n\/\/ include h1analysProxy.C:\n\/\/ h42->MakeProxy(\"h1sel\",\"h1analysisProxy.C\");\n\/\/ This produces one file: h1sel.h which does a #include \"h1analysProxy.C\"\n\/\/ The h1sel class is derived from the Root class TSelector and can then \n\/\/ be used as:\n\/\/ h42->Process(\"h1sel.h+\");\n\/\/\n\/\/ The following members functions are called by the TTree::Process functions.\n\/\/ h1analysProxy_Begin(): called everytime a loop on the tree starts.\n\/\/ a convenient place to create your histograms.\n\/\/ h1analysProxy_SlaveBegin():\n\/\/\n\/\/ h1analysProxy_Notify(): This function is called at the first entry of a new Tree\n\/\/ in a chain.\n\/\/ h1analysProxy_Process(): called to analyze each entry.\n\/\/\n\/\/ h1analysProxy_SlaveTerminate():\n\/\/\n\/\/ h1analysProxy_Terminate(): called at the end of a loop on a TTree.\n\/\/ a convenient place to draw\/fit your histograms.\n\/\/\n\/\/ To use this file, try the following session\n\/\/\n\/\/ Root > gROOT->Time(); \/\/will show RT & CPU time per command\n\/\/\n\/\/==> A- create a TChain with the 4 H1 data files\n\/\/ The chain can be created by executed the short macro h1chain.C below:\n\/\/ {\n\/\/ TChain chain(\"h42\");\n\/\/ chain.Add(\"$H1\/dstarmb.root\"); \/\/ 21330730 bytes 21920 events\n\/\/ chain.Add(\"$H1\/dstarp1a.root\"); \/\/ 71464503 bytes 73243 events\n\/\/ chain.Add(\"$H1\/dstarp1b.root\"); \/\/ 83827959 bytes 85597 events\n\/\/ chain.Add(\"$H1\/dstarp2.root\"); \/\/ 100675234 bytes 103053 events\n\/\/ \/\/where $H1 is a system symbol pointing to the H1 data directory.\n\/\/ }\n\/\/\n\/\/ Root > .x h1chain.C\n\/\/\n\/\/==> B- loop on all events\n\/\/ Root > chain.Draw(\"h1analysisProxy.C\")\n\/\/\n\/\/==> C- same as B, but in addition fill the event list with selected entries.\n\/\/ The event list is saved to a file \"elist.root\" by the Terminate function.\n\/\/ To see the list of selected events, you can do elist->Print(\"all\").\n\/\/ The selection function has selected 7525 events out of the 283813 events\n\/\/ in the chain of files. (2.65 per cent)\n\/\/ Root > chain.Draw(\"h1analysisProxy.C\",\"\",\"fillList\")\n\/\/\n\/\/==> D- Process only entries in the event list\n\/\/ The event list is read from the file in elist.root generated by step C\n\/\/ Root > chain.Draw(\"h1analysisProxy.C\",\"\",\"useList\")\n\/\/\/\/\n\/\/ The commands executed with the 3 different methods B,C and D\n\/\/ produce two canvases shown below:\n\/\/ begin_html <a href=\"gif\/h1analysis_dstar.gif\" >the Dstar plot<\/a> end_html\n\/\/ begin_html <a href=\"gif\/h1analysis_tau.gif\" >the Tau D0 plot<\/a> end_html\n\/\/\n\/\/Author; Philippe Canal from original h1analysis.C by Rene Brun\n\nTEventList *elist;\nBool_t useList, fillList;\nTH1F *hdmd;\nTH2F *h2;\n\n\/\/_____________________________________________________________________\nvoid h1analysisProxy_Begin(TTree * \/* tree *\/ )\n{\n\/\/ function called before starting the event loop\n\/\/ -it performs some cleanup\n\/\/ -it creates histograms\n\/\/ -it sets some initialisation for the event list\n\n \/\/print the option specified in the Process function.\n TString option = GetOption();\n printf(\"Starting (begin) h1analysis with process option: %s\\n\",option.Data());\n\n \/\/some cleanup in case this function had already been executed\n \/\/delete any previously generated histograms or functions\n gDirectory->Delete(\"hdmd\");\n gDirectory->Delete(\"h2*\");\n delete gROOT->GetFunction(\"f5\");\n delete gROOT->GetFunction(\"f2\");\n}\n\n\/\/_____________________________________________________________________\nvoid h1analysisProxy_SlaveBegin(TTree *tree)\n{\n\/\/ function called before starting the event loop\n\/\/ -it performs some cleanup\n\/\/ -it creates histograms\n\/\/ -it sets some initialisation for the event list\n\n \/\/initialize the Tree branch addresses\n Init(tree);\n\n \/\/print the option specified in the Process function.\n TString option = GetOption();\n printf(\"Starting (slave) h1analysis with process option: %s\\n\",option.Data());\n\n \/\/some cleanup in case this function had already been executed\n \/\/delete any previously generated histograms or functions\n gDirectory->Delete(\"hdmd\");\n gDirectory->Delete(\"h2*\");\n delete gROOT->GetFunction(\"f5\");\n delete gROOT->GetFunction(\"f2\");\n\n \/\/create histograms\n hdmd = new TH1F(\"hdmd\",\"dm_d\",40,0.13,0.17);\n h2 = new TH2F(\"h2\",\"ptD0 vs dm_d\",30,0.135,0.165,30,-3,6);\n\n fOutput->Add(hdmd);\n fOutput->Add(h2);\n\n \/\/process cases with event list\n fillList = kFALSE;\n useList = kFALSE;\n tree->SetEventList(0);\n delete gDirectory->GetList()->FindObject(\"elist\");\n\n \/\/ case when one creates\/fills the event list\n if (option.Contains(\"fillList\")) {\n fillList = kTRUE;\n elist = new TEventList(\"elist\",\"selection from Cut\",5000);\n } else elist = 0;\n\n \/\/ case when one uses the event list generated in a previous call\n if (option.Contains(\"useList\")) {\n useList = kTRUE;\n TFile f(\"elist.root\");\n elist = (TEventList*)f.Get(\"elist\");\n if (elist) elist->SetDirectory(0); \/\/otherwise the file destructor will delete elist\n tree->SetEventList(elist);\n }\n\n}\n\nDouble_t h1analysisProxy() {\n return 0;\n}\n\n\/\/_____________________________________________________________________\nBool_t h1analysisProxy_Process(Long64_t entry)\n{\n\/\/ entry is the entry number in the current Tree\n\/\/ Selection function to select D* and D0.\n\n \/\/in case one event list is given in input, the selection has already been done.\n if (!useList) {\n\n float f1 = md0_d;\n float f2 = md0_d-1.8646;\n bool test = TMath::Abs(md0_d-1.8646) >= 0.04;\n if (gDebug>0) fprintf(stderr,\"entry #%lld f1=%f f2=%f test=%d\\n\",\n fChain->GetReadEntry(),f1,f2,test);\n \n if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE;\n if (ptds_d <= 2.5) return kFALSE;\n if (TMath::Abs(etads_d) >= 1.5) return kFALSE;\n \n int cik = ik-1; \/\/original ik used f77 convention starting at 1\n int cipi = ipi-1; \/\/original ipi used f77 convention starting at 1\n \n f1 = nhitrp[cik];\n f2 = nhitrp[cipi];\n test = nhitrp[cik]*nhitrp[cipi] <= 1;\n if (gDebug>0) fprintf(stderr,\"entry #%lld f1=%f f2=%f test=%d\\n\",\n fChain->GetReadEntry(),f1,f2,test);\n \n if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE;\n if (rend[cik] -rstart[cik] <= 22) return kFALSE;\n if (rend[cipi]-rstart[cipi] <= 22) return kFALSE;\n if (nlhk[cik] <= 0.1) return kFALSE;\n if (nlhpi[cipi] <= 0.1) return kFALSE;\n \/\/ fix because read-only \n if (nlhpi[ipis-1] <= 0.1) return kFALSE;\n if (njets < 1) return kFALSE;\n \n }\n \/\/ if option fillList, fill the event list\n if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry));\n\n \/\/fill some histograms\n hdmd->Fill(dm_d);\n h2->Fill(dm_d,rpd0_t\/0.029979*1.8646\/ptd0_d);\n\n return kTRUE;\n}\n\n\n\/\/_____________________________________________________________________\nvoid h1analysisProxy_SlaveTerminate()\n{\n \/\/ nothing to be done\n printf(\"Terminate (slave) h1analysis\\n\");\n}\n\n\/\/_____________________________________________________________________\nvoid h1analysisProxy_Terminate()\n{\n printf(\"Terminate (final) h1analysis\\n\");\n\n \/\/ function called at the end of the event loop\n\n hdmd = dynamic_cast<TH1F*>(fOutput->FindObject(\"hdmd\"));\n h2 = dynamic_cast<TH2F*>(fOutput->FindObject(\"h2\"));\n\n if (hdmd == 0 || h2 == 0) {\n Error(\"Terminate\", \"hdmd = %p , h2 = %p\", hdmd, h2);\n return;\n }\n\n \/\/create the canvas for the h1analysis fit\n gStyle->SetOptFit();\n TCanvas *c1 = new TCanvas(\"c1\",\"h1analysis analysis\",10,10,800,600);\n c1->SetBottomMargin(0.15);\n hdmd->GetXaxis()->SetTitle(\"m_{K#pi#pi} - m_{K#pi}[GeV\/c^{2}]\");\n hdmd->GetXaxis()->SetTitleOffset(1.4);\n\n \/\/fit histogram hdmd with function f5 using the loglikelihood option\n TF1 *f5 = new TF1(\"f5\",fdm5,0.139,0.17,5);\n f5->SetParameters(1000000, .25, 2000, .1454, .001);\n hdmd->Fit(\"f5\",\"lr\");\n\n \/\/create the canvas for tau d0\n gStyle->SetOptFit(0);\n gStyle->SetOptStat(1100);\n TCanvas *c2 = new TCanvas(\"c2\",\"tauD0\",100,100,800,600);\n c2->SetGrid();\n c2->SetBottomMargin(0.15);\n\n \/\/ Project slices of 2-d histogram h2 along X , then fit each slice\n \/\/ with function f2 and make a histogram for each fit parameter\n \/\/ Note that the generated histograms are added to the list of objects\n \/\/ in the current directory.\n TF1 *f2 = new TF1(\"f2\",fdm2,0.139,0.17,2);\n f2->SetParameters(10000, 10);\n h2->FitSlicesX(f2,0,-1,1,\"qln\");\n TH1D *h2_1 = (TH1D*)gDirectory->Get(\"h2_1\");\n h2_1->GetXaxis()->SetTitle(\"#tau[ps]\");\n h2_1->SetMarkerStyle(21);\n h2_1->Draw();\n c2->Update();\n TLine *line = new TLine(0,0,0,c2->GetUymax());\n line->Draw();\n\n \/\/save the event list to a Root file if one was produced\n if (fillList) {\n TFile efile(\"elist.root\",\"recreate\");\n elist->Write();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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 \"ui\/aura\/event_filter.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/compiler_specific.h\"\n#include \"ui\/aura\/desktop.h\"\n#include \"ui\/aura\/event.h\"\n#include \"ui\/aura\/test\/aura_test_base.h\"\n#include \"ui\/aura\/test\/event_generator.h\"\n#include \"ui\/aura\/test\/test_desktop_delegate.h\"\n#include \"ui\/aura\/test\/test_window_delegate.h\"\n\n#if defined(OS_WIN)\n\/\/ Windows headers define macros for these function names which screw with us.\n#if defined(CreateWindow)\n#undef CreateWindow\n#endif\n#endif\n\nnamespace aura {\nnamespace test {\n\ntypedef AuraTestBase EventFilterTest;\n\nclass TestEventFilterWindowDelegate : public TestWindowDelegate {\n public:\n TestEventFilterWindowDelegate()\n : key_event_count_(0),\n mouse_event_count_(0),\n touch_event_count_(0) {}\n virtual ~TestEventFilterWindowDelegate() {}\n\n void ResetCounts() {\n key_event_count_ = 0;\n mouse_event_count_ = 0;\n touch_event_count_ = 0;\n }\n\n int key_event_count() const { return key_event_count_; }\n int mouse_event_count() const { return mouse_event_count_; }\n int touch_event_count() const { return touch_event_count_; }\n\n \/\/ Overridden from TestWindowDelegate:\n virtual bool OnKeyEvent(KeyEvent* event) OVERRIDE {\n ++key_event_count_;\n return true;\n }\n virtual bool OnMouseEvent(MouseEvent* event) OVERRIDE {\n ++mouse_event_count_;\n return true;\n }\n virtual ui::TouchStatus OnTouchEvent(TouchEvent* event) OVERRIDE {\n ++touch_event_count_;\n return ui::TOUCH_STATUS_UNKNOWN;\n }\n\n private:\n int key_event_count_;\n int mouse_event_count_;\n int touch_event_count_;\n\n DISALLOW_COPY_AND_ASSIGN(TestEventFilterWindowDelegate);\n};\n\nWindow* CreateWindow(int id, Window* parent, WindowDelegate* delegate) {\n Window* window = new Window(delegate ? delegate : new TestWindowDelegate);\n window->set_id(id);\n window->Init();\n window->SetParent(parent);\n window->SetBounds(gfx::Rect(0, 0, 100, 100));\n window->Show();\n return window;\n}\n\nclass TestEventFilter : public EventFilter {\n public:\n explicit TestEventFilter(Window* owner)\n : EventFilter(owner),\n key_event_count_(0),\n mouse_event_count_(0),\n touch_event_count_(0),\n consumes_key_events_(false),\n consumes_mouse_events_(false),\n consumes_touch_events_(false) {\n }\n virtual ~TestEventFilter() {}\n\n void ResetCounts() {\n key_event_count_ = 0;\n mouse_event_count_ = 0;\n touch_event_count_ = 0;\n }\n\n int key_event_count() const { return key_event_count_; }\n int mouse_event_count() const { return mouse_event_count_; }\n int touch_event_count() const { return touch_event_count_; }\n\n void set_consumes_key_events(bool consumes_key_events) {\n consumes_key_events_ = consumes_key_events;\n }\n void set_consumes_mouse_events(bool consumes_mouse_events) {\n consumes_mouse_events_ = consumes_mouse_events;\n }\n void set_consumes_touch_events(bool consumes_touch_events) {\n consumes_touch_events_ = consumes_touch_events;\n }\n\n \/\/ Overridden from EventFilter:\n virtual bool PreHandleKeyEvent(Window* target, KeyEvent* event) OVERRIDE {\n ++key_event_count_;\n return consumes_key_events_;\n }\n virtual bool PreHandleMouseEvent(Window* target, MouseEvent* event) OVERRIDE {\n ++mouse_event_count_;\n return consumes_mouse_events_;\n }\n virtual ui::TouchStatus PreHandleTouchEvent(Window* target,\n TouchEvent* event) OVERRIDE {\n ++touch_event_count_;\n \/\/ TODO(sadrul): !\n return ui::TOUCH_STATUS_UNKNOWN;\n }\n\n private:\n int key_event_count_;\n int mouse_event_count_;\n int touch_event_count_;\n\n bool consumes_key_events_;\n bool consumes_mouse_events_;\n bool consumes_touch_events_;\n\n DISALLOW_COPY_AND_ASSIGN(TestEventFilter);\n};\n\n\/\/ Creates this hierarchy:\n\/\/\n\/\/ Desktop Window (EF)\n\/\/ +- w1 (EF)\n\/\/ +- w11\n\/\/ +- w111 (EF)\n\/\/ +- w1111 <-- target window\nTEST_F(EventFilterTest, Basic) {\n scoped_ptr<Window> w1(CreateWindow(1, Desktop::GetInstance(), NULL));\n scoped_ptr<Window> w11(CreateWindow(11, w1.get(), NULL));\n scoped_ptr<Window> w111(CreateWindow(111, w11.get(), NULL));\n TestEventFilterWindowDelegate* d1111 = new TestEventFilterWindowDelegate;\n scoped_ptr<Window> w1111(CreateWindow(1111, w111.get(), d1111));\n\n TestEventFilter* desktop_filter = new TestEventFilter(Desktop::GetInstance());\n TestEventFilter* w1_filter = new TestEventFilter(w1.get());\n TestEventFilter* w111_filter = new TestEventFilter(w111.get());\n Desktop::GetInstance()->SetEventFilter(desktop_filter);\n w1->SetEventFilter(w1_filter);\n w111->SetEventFilter(w111_filter);\n\n w1111->GetFocusManager()->SetFocusedWindow(w1111.get());\n\n \/\/ To start with, no one is going to consume any events. All three filters\n \/\/ and the w1111's delegate should receive the event.\n EventGenerator generator(w1111.get());\n generator.PressLeftButton();\n KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0);\n Desktop::GetInstance()->DispatchKeyEvent(&key_event);\n\n \/\/ TODO(sadrul): TouchEvent!\n EXPECT_EQ(1, desktop_filter->key_event_count());\n EXPECT_EQ(1, w1_filter->key_event_count());\n EXPECT_EQ(1, w111_filter->key_event_count());\n EXPECT_EQ(1, d1111->key_event_count());\n EXPECT_EQ(1, desktop_filter->mouse_event_count());\n EXPECT_EQ(1, w1_filter->mouse_event_count());\n EXPECT_EQ(1, w111_filter->mouse_event_count());\n EXPECT_EQ(1, d1111->mouse_event_count());\n EXPECT_EQ(0, desktop_filter->touch_event_count());\n EXPECT_EQ(0, w1_filter->touch_event_count());\n EXPECT_EQ(0, w111_filter->touch_event_count());\n EXPECT_EQ(0, d1111->touch_event_count());\n\n d1111->ResetCounts();\n desktop_filter->ResetCounts();\n w1_filter->ResetCounts();\n w111_filter->ResetCounts();\n\n \/\/ Now make w1's EF consume the event.\n w1_filter->set_consumes_key_events(true);\n w1_filter->set_consumes_mouse_events(true);\n\n generator.ReleaseLeftButton();\n Desktop::GetInstance()->DispatchKeyEvent(&key_event);\n\n \/\/ TODO(sadrul): TouchEvent!\n EXPECT_EQ(1, desktop_filter->key_event_count());\n EXPECT_EQ(1, w1_filter->key_event_count());\n EXPECT_EQ(0, w111_filter->key_event_count());\n EXPECT_EQ(0, d1111->key_event_count());\n EXPECT_EQ(1, desktop_filter->mouse_event_count());\n EXPECT_EQ(1, w1_filter->mouse_event_count());\n EXPECT_EQ(0, w111_filter->mouse_event_count());\n EXPECT_EQ(0, d1111->mouse_event_count());\n EXPECT_EQ(0, desktop_filter->touch_event_count());\n EXPECT_EQ(0, w1_filter->touch_event_count());\n EXPECT_EQ(0, w111_filter->touch_event_count());\n EXPECT_EQ(0, d1111->touch_event_count());\n}\n\n} \/\/ namespace test\n} \/\/ namespace aura\n\n<commit_msg>Fix aura bustage.<commit_after>\/\/ Copyright (c) 2011 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 \"ui\/aura\/event_filter.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/compiler_specific.h\"\n#include \"ui\/aura\/desktop.h\"\n#include \"ui\/aura\/event.h\"\n#include \"ui\/aura\/test\/aura_test_base.h\"\n#include \"ui\/aura\/test\/event_generator.h\"\n#include \"ui\/aura\/test\/test_desktop_delegate.h\"\n#include \"ui\/aura\/test\/test_window_delegate.h\"\n\n#if defined(OS_WIN)\n\/\/ Windows headers define macros for these function names which screw with us.\n#if defined(CreateWindow)\n#undef CreateWindow\n#endif\n#endif\n\nnamespace aura {\nnamespace test {\n\ntypedef AuraTestBase EventFilterTest;\n\nclass TestEventFilterWindowDelegate : public TestWindowDelegate {\n public:\n TestEventFilterWindowDelegate()\n : key_event_count_(0),\n mouse_event_count_(0),\n touch_event_count_(0) {}\n virtual ~TestEventFilterWindowDelegate() {}\n\n void ResetCounts() {\n key_event_count_ = 0;\n mouse_event_count_ = 0;\n touch_event_count_ = 0;\n }\n\n int key_event_count() const { return key_event_count_; }\n int mouse_event_count() const { return mouse_event_count_; }\n int touch_event_count() const { return touch_event_count_; }\n\n \/\/ Overridden from TestWindowDelegate:\n virtual bool OnKeyEvent(KeyEvent* event) OVERRIDE {\n ++key_event_count_;\n return true;\n }\n virtual bool OnMouseEvent(MouseEvent* event) OVERRIDE {\n ++mouse_event_count_;\n return true;\n }\n virtual ui::TouchStatus OnTouchEvent(TouchEvent* event) OVERRIDE {\n ++touch_event_count_;\n return ui::TOUCH_STATUS_UNKNOWN;\n }\n\n private:\n int key_event_count_;\n int mouse_event_count_;\n int touch_event_count_;\n\n DISALLOW_COPY_AND_ASSIGN(TestEventFilterWindowDelegate);\n};\n\nWindow* CreateWindow(int id, Window* parent, WindowDelegate* delegate) {\n Window* window = new Window(delegate ? delegate : new TestWindowDelegate);\n window->set_id(id);\n window->Init(ui::Layer::LAYER_HAS_TEXTURE);\n window->SetParent(parent);\n window->SetBounds(gfx::Rect(0, 0, 100, 100));\n window->Show();\n return window;\n}\n\nclass TestEventFilter : public EventFilter {\n public:\n explicit TestEventFilter(Window* owner)\n : EventFilter(owner),\n key_event_count_(0),\n mouse_event_count_(0),\n touch_event_count_(0),\n consumes_key_events_(false),\n consumes_mouse_events_(false),\n consumes_touch_events_(false) {\n }\n virtual ~TestEventFilter() {}\n\n void ResetCounts() {\n key_event_count_ = 0;\n mouse_event_count_ = 0;\n touch_event_count_ = 0;\n }\n\n int key_event_count() const { return key_event_count_; }\n int mouse_event_count() const { return mouse_event_count_; }\n int touch_event_count() const { return touch_event_count_; }\n\n void set_consumes_key_events(bool consumes_key_events) {\n consumes_key_events_ = consumes_key_events;\n }\n void set_consumes_mouse_events(bool consumes_mouse_events) {\n consumes_mouse_events_ = consumes_mouse_events;\n }\n void set_consumes_touch_events(bool consumes_touch_events) {\n consumes_touch_events_ = consumes_touch_events;\n }\n\n \/\/ Overridden from EventFilter:\n virtual bool PreHandleKeyEvent(Window* target, KeyEvent* event) OVERRIDE {\n ++key_event_count_;\n return consumes_key_events_;\n }\n virtual bool PreHandleMouseEvent(Window* target, MouseEvent* event) OVERRIDE {\n ++mouse_event_count_;\n return consumes_mouse_events_;\n }\n virtual ui::TouchStatus PreHandleTouchEvent(Window* target,\n TouchEvent* event) OVERRIDE {\n ++touch_event_count_;\n \/\/ TODO(sadrul): !\n return ui::TOUCH_STATUS_UNKNOWN;\n }\n\n private:\n int key_event_count_;\n int mouse_event_count_;\n int touch_event_count_;\n\n bool consumes_key_events_;\n bool consumes_mouse_events_;\n bool consumes_touch_events_;\n\n DISALLOW_COPY_AND_ASSIGN(TestEventFilter);\n};\n\n\/\/ Creates this hierarchy:\n\/\/\n\/\/ Desktop Window (EF)\n\/\/ +- w1 (EF)\n\/\/ +- w11\n\/\/ +- w111 (EF)\n\/\/ +- w1111 <-- target window\nTEST_F(EventFilterTest, Basic) {\n scoped_ptr<Window> w1(CreateWindow(1, Desktop::GetInstance(), NULL));\n scoped_ptr<Window> w11(CreateWindow(11, w1.get(), NULL));\n scoped_ptr<Window> w111(CreateWindow(111, w11.get(), NULL));\n TestEventFilterWindowDelegate* d1111 = new TestEventFilterWindowDelegate;\n scoped_ptr<Window> w1111(CreateWindow(1111, w111.get(), d1111));\n\n TestEventFilter* desktop_filter = new TestEventFilter(Desktop::GetInstance());\n TestEventFilter* w1_filter = new TestEventFilter(w1.get());\n TestEventFilter* w111_filter = new TestEventFilter(w111.get());\n Desktop::GetInstance()->SetEventFilter(desktop_filter);\n w1->SetEventFilter(w1_filter);\n w111->SetEventFilter(w111_filter);\n\n w1111->GetFocusManager()->SetFocusedWindow(w1111.get());\n\n \/\/ To start with, no one is going to consume any events. All three filters\n \/\/ and the w1111's delegate should receive the event.\n EventGenerator generator(w1111.get());\n generator.PressLeftButton();\n KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0);\n Desktop::GetInstance()->DispatchKeyEvent(&key_event);\n\n \/\/ TODO(sadrul): TouchEvent!\n EXPECT_EQ(1, desktop_filter->key_event_count());\n EXPECT_EQ(1, w1_filter->key_event_count());\n EXPECT_EQ(1, w111_filter->key_event_count());\n EXPECT_EQ(1, d1111->key_event_count());\n EXPECT_EQ(1, desktop_filter->mouse_event_count());\n EXPECT_EQ(1, w1_filter->mouse_event_count());\n EXPECT_EQ(1, w111_filter->mouse_event_count());\n EXPECT_EQ(1, d1111->mouse_event_count());\n EXPECT_EQ(0, desktop_filter->touch_event_count());\n EXPECT_EQ(0, w1_filter->touch_event_count());\n EXPECT_EQ(0, w111_filter->touch_event_count());\n EXPECT_EQ(0, d1111->touch_event_count());\n\n d1111->ResetCounts();\n desktop_filter->ResetCounts();\n w1_filter->ResetCounts();\n w111_filter->ResetCounts();\n\n \/\/ Now make w1's EF consume the event.\n w1_filter->set_consumes_key_events(true);\n w1_filter->set_consumes_mouse_events(true);\n\n generator.ReleaseLeftButton();\n Desktop::GetInstance()->DispatchKeyEvent(&key_event);\n\n \/\/ TODO(sadrul): TouchEvent!\n EXPECT_EQ(1, desktop_filter->key_event_count());\n EXPECT_EQ(1, w1_filter->key_event_count());\n EXPECT_EQ(0, w111_filter->key_event_count());\n EXPECT_EQ(0, d1111->key_event_count());\n EXPECT_EQ(1, desktop_filter->mouse_event_count());\n EXPECT_EQ(1, w1_filter->mouse_event_count());\n EXPECT_EQ(0, w111_filter->mouse_event_count());\n EXPECT_EQ(0, d1111->mouse_event_count());\n EXPECT_EQ(0, desktop_filter->touch_event_count());\n EXPECT_EQ(0, w1_filter->touch_event_count());\n EXPECT_EQ(0, w111_filter->touch_event_count());\n EXPECT_EQ(0, d1111->touch_event_count());\n}\n\n} \/\/ namespace test\n} \/\/ namespace aura\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\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: xpathapi.cxx,v $\n * $Revision: 1.7 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"xpathapi.hxx\"\n#include \"nodelist.hxx\"\n#include \"xpathobject.hxx\"\n#include \"..\/dom\/node.hxx\"\n\n#include <rtl\/ustrbuf.hxx>\n\n#include <libxml\/xmlerror.h>\n#include <libxml\/xpath.h>\n#include <libxml\/xpathInternals.h>\n\n#include <stdarg.h>\n#include <string.h>\n\n\nnamespace XPath\n{\n \/\/ factory\n Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr)\n {\n return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr)));\n }\n\n \/\/ ctor\n CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr)\n : m_aFactory(rSMgr)\n {\n }\n\n const char* CXPathAPI::aImplementationName = \"com.sun.star.comp.xml.xpath.XPathAPI\";\n const char* CXPathAPI::aSupportedServiceNames[] = {\n \"com.sun.star.xml.xpath.XPathAPI\",\n NULL\n };\n\n OUString CXPathAPI::_getImplementationName()\n {\n return OUString::createFromAscii(aImplementationName);\n }\n\n Sequence<OUString> CXPathAPI::_getSupportedServiceNames()\n {\n Sequence<OUString> aSequence;\n for (int i=0; aSupportedServiceNames[i]!=NULL; i++) {\n aSequence.realloc(i+1);\n aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i]));\n }\n return aSequence;\n }\n\n Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames()\n throw (RuntimeException)\n {\n return CXPathAPI::_getSupportedServiceNames();\n }\n\n OUString SAL_CALL CXPathAPI::getImplementationName()\n throw (RuntimeException)\n {\n return CXPathAPI::_getImplementationName();\n }\n\n sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName)\n throw (RuntimeException)\n {\n Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames();\n for (sal_Int32 i=0; i<supported.getLength(); i++)\n {\n if (supported[i] == aServiceName) return sal_True;\n }\n return sal_False;\n }\n\n \/\/ -------------------------------------------------------------------\n\n void SAL_CALL CXPathAPI::registerNS(\n const OUString& aPrefix,\n const OUString& aURI)\n throw (RuntimeException)\n {\n m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI));\n }\n\n void SAL_CALL CXPathAPI::unregisterNS(\n const OUString& aPrefix,\n const OUString& aURI)\n throw (RuntimeException)\n {\n if ((m_nsmap.find(aPrefix))->second.equals(aURI))\n m_nsmap.erase(aPrefix);\n }\n\n \/\/ register all namespaces stored in the namespace list for this object\n \/\/ with the current xpath evaluation context\n static void _registerNamespaces(\n xmlXPathContextPtr ctx,\n const nsmap_t& nsmap)\n {\n nsmap_t::const_iterator i = nsmap.begin();\n OString oprefix, ouri;\n xmlChar *p, *u;\n while (i != nsmap.end())\n {\n oprefix = OUStringToOString(i->first, RTL_TEXTENCODING_UTF8);\n ouri = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8);\n p = (xmlChar*)oprefix.getStr();\n u = (xmlChar*)ouri.getStr();\n xmlXPathRegisterNs(ctx, p, u);\n i++;\n }\n }\n\n \/\/ get all ns decls on a node (and parent nodes, if any) and register them\n static void _collectNamespaces(\n CXPathAPI* pAPI,\n const Reference< XNode >& namespaceNode)\n {\n \/\/ get namespace decls from node...\n xmlNodePtr pNode = DOM::CNode::getNodePtr(namespaceNode);\n while (pNode != 0) {\n xmlNsPtr curDef = pNode->nsDef;\n while (curDef != 0) {\n const xmlChar* xHref = curDef->href;\n OUString aURI((sal_Char*)xHref, strlen((char*)xHref), RTL_TEXTENCODING_UTF8);\n const xmlChar* xPre = curDef->prefix;\n OUString aPrefix((sal_Char*)xPre, strlen((char*)xPre), RTL_TEXTENCODING_UTF8);\n pAPI->registerNS(aPrefix, aURI);\n curDef = curDef->next;\n }\n pNode = pNode->parent;\n }\n }\n\n \/\/ register function and variable lookup functions with the current\n \/\/ xpath evaluation context\n static void _registerExtensions(\n xmlXPathContextPtr ctx,\n const extensions_t& extensions)\n {\n extensions_t::const_iterator i = extensions.begin();\n while (i != extensions.end())\n {\n Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle();\n if ( aHandle.functionLookupFunction != 0 )\n {\n xmlXPathRegisterFuncLookup(ctx,\n reinterpret_cast<xmlXPathFuncLookupFunc>(\n sal::static_int_cast<sal_IntPtr>(aHandle.functionLookupFunction)),\n reinterpret_cast<void*>(\n sal::static_int_cast<sal_IntPtr>(aHandle.functionData)));\n }\n if ( aHandle.variableLookupFunction != 0 )\n {\n xmlXPathRegisterVariableLookup(ctx,\n reinterpret_cast<xmlXPathVariableLookupFunc>(\n sal::static_int_cast<sal_IntPtr>(aHandle.variableLookupFunction)),\n reinterpret_cast<void*>(\n sal::static_int_cast<sal_IntPtr>(aHandle.variableData)));\n }\n i++;\n }\n }\n\n \/**\n * Use an XPath string to select a nodelist.\n *\/\n Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList(\n const Reference< XNode >& contextNode,\n const OUString& expr)\n throw (RuntimeException, XPathException)\n {\n Reference< XXPathObject > xobj = eval(contextNode, expr);\n return xobj->getNodeList();\n }\n\n \/**\n * same as selectNodeList but registers all name space decalratiosn found on namespaceNode\n *\/\n Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS(\n const Reference< XNode >& contextNode,\n const OUString& expr,\n const Reference< XNode >& namespaceNode)\n throw (RuntimeException, XPathException)\n {\n _collectNamespaces(this, namespaceNode);\n return selectNodeList(contextNode, expr);\n }\n\n \/**\n * Same as selectNodeList but returns the first node (if any)\n *\/\n Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode(\n const Reference< XNode >& contextNode,\n const OUString& expr)\n throw (RuntimeException, XPathException)\n {\n Reference< XNodeList > aList = selectNodeList(contextNode, expr);\n Reference< XNode > aNode = aList->item(0);\n return aNode;\n }\n\n \/**\n * Same as selectSingleNode but registers all namespaces declared on\n * namespaceNode\n *\/\n Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS(\n const Reference< XNode >& contextNode,\n const OUString& expr,\n const Reference< XNode >& namespaceNode )\n throw (RuntimeException, XPathException)\n {\n _collectNamespaces(this, namespaceNode);\n return selectSingleNode(contextNode, expr);\n }\n\n static OUString make_error_message(xmlErrorPtr pError)\n {\n ::rtl::OUStringBuffer buf;\n if (pError->message) {\n buf.appendAscii(pError->message);\n }\n int line = pError->line;\n if (line) {\n buf.appendAscii(\"Line: \");\n buf.append(static_cast<sal_Int32>(line));\n buf.appendAscii(\"\\n\");\n }\n int column = pError->int2;\n if (column) {\n buf.appendAscii(\"Column: \");\n buf.append(static_cast<sal_Int32>(column));\n buf.appendAscii(\"\\n\");\n }\n OUString msg = buf.makeStringAndClear();\n return msg;\n }\n\n extern \"C\" {\n\n static void generic_error_func(void *userData, const char *format, ...)\n {\n (void) userData;\n char str[1000];\n va_list args;\n\n va_start(args, format);\n vsnprintf(str, sizeof(str), format, args);\n va_end(args);\n\n ::rtl::OUStringBuffer buf(\n OUString::createFromAscii(\"libxml2 error:\\n\"));\n buf.appendAscii(str);\n OString msg = OUStringToOString(buf.makeStringAndClear(),\n RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, msg.getStr());\n }\n\n static void structured_error_func(void * userData, xmlErrorPtr error)\n {\n (void) userData;\n ::rtl::OUStringBuffer buf(\n OUString::createFromAscii(\"libxml2 error:\\n\"));\n if (error) {\n buf.append(make_error_message(error));\n } else {\n buf.append(OUString::createFromAscii(\"no error argument!\"));\n }\n OString msg = OUStringToOString(buf.makeStringAndClear(),\n RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, msg.getStr());\n }\n\n } \/\/ extern \"C\"\n\n \/**\n * evaluates an XPath string. relative XPath expressions are evaluated relative to\n * the context Node\n *\/\n Reference< XXPathObject > SAL_CALL CXPathAPI::eval(\n const Reference< XNode >& contextNode,\n const OUString& expr)\n throw (RuntimeException, XPathException)\n {\n xmlXPathContextPtr xpathCtx;\n xmlXPathObjectPtr xpathObj;\n\n \/\/ get the node and document\n xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode);\n xmlDocPtr pDoc = pNode->doc;\n\n \/* NB: workaround for #i87252#:\n libxml < 2.6.17 considers it an error if the context\n node is the empty document (i.e. its xpathCtx->doc has no\n children). libxml 2.6.17 does not consider it an error.\n Unfortunately, old libxml prints an error message to stderr,\n which (afaik) cannot be turned off in this case, so we handle it.\n *\/\n if (!pDoc->children) {\n throw XPathException();\n }\n\n \/* Create xpath evaluation context *\/\n xpathCtx = xmlXPathNewContext(pDoc);\n if (xpathCtx == NULL) throw XPathException();\n\n \/\/ set context node\n xpathCtx->node = pNode;\n \/\/ error handling\n xpathCtx->error = structured_error_func;\n xmlSetGenericErrorFunc(NULL, generic_error_func);\n\n \/\/ register namespaces and extension\n _registerNamespaces(xpathCtx, m_nsmap);\n _registerExtensions(xpathCtx, m_extensions);\n\n \/* run the query *\/\n OString o1 = OUStringToOString(expr, RTL_TEXTENCODING_UTF8);\n xmlChar *xStr = (xmlChar*)o1.getStr();\n if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) {\n \/\/ OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message);\n xmlXPathFreeContext(xpathCtx);\n throw XPathException();\n }\n xmlXPathFreeContext(xpathCtx);\n Reference< XXPathObject > aObj(new CXPathObject(xpathObj));\n return aObj;\n }\n\n \/**\n * same as eval but registers all namespace declarations found on namespaceNode\n *\/\n Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(\n const Reference< XNode >& contextNode,\n const OUString& expr,\n const Reference< XNode >& namespaceNode)\n throw (RuntimeException, XPathException)\n {\n _collectNamespaces(this, namespaceNode);\n return eval(contextNode, expr);\n }\n\n \/**\n * uses the service manager to create an instance of the service denoted by aName.\n * If the returned object implements the XXPathExtension interface, it is added to the list\n * of extensions that are used when evaluating XPath strings with this XPathAPI instance\n *\/\n void SAL_CALL CXPathAPI::registerExtension(\n const OUString& aName)\n throw (RuntimeException)\n {\n \/\/ get extension from service manager\n Reference< XXPathExtension > aExtension(m_aFactory->createInstance(aName), UNO_QUERY_THROW);\n m_extensions.push_back( aExtension );\n }\n\n \/**\n * registers the given extension instance to be used by XPath evaluations performed through this\n * XPathAPI instance\n *\/\n void SAL_CALL CXPathAPI::registerExtensionInstance(\n const Reference< XXPathExtension>& aExtension)\n throw (RuntimeException)\n {\n if (aExtension.is()) {\n m_extensions.push_back( aExtension );\n } else {\n throw RuntimeException();\n }\n }\n}\n<commit_msg>#i90484# Patch by pjanik for .Net2003 compiler<commit_after>\/*************************************************************************\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: xpathapi.cxx,v $\n * $Revision: 1.8 $\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 * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"xpathapi.hxx\"\n#include \"nodelist.hxx\"\n#include \"xpathobject.hxx\"\n#include \"..\/dom\/node.hxx\"\n\n#include <rtl\/ustrbuf.hxx>\n\n#include <libxml\/xmlerror.h>\n#include <libxml\/xpath.h>\n#include <libxml\/xpathInternals.h>\n\n#include <stdarg.h>\n#include <string.h>\n\n\nnamespace XPath\n{\n \/\/ factory\n Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr)\n {\n return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr)));\n }\n\n \/\/ ctor\n CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr)\n : m_aFactory(rSMgr)\n {\n }\n\n const char* CXPathAPI::aImplementationName = \"com.sun.star.comp.xml.xpath.XPathAPI\";\n const char* CXPathAPI::aSupportedServiceNames[] = {\n \"com.sun.star.xml.xpath.XPathAPI\",\n NULL\n };\n\n OUString CXPathAPI::_getImplementationName()\n {\n return OUString::createFromAscii(aImplementationName);\n }\n\n Sequence<OUString> CXPathAPI::_getSupportedServiceNames()\n {\n Sequence<OUString> aSequence;\n for (int i=0; aSupportedServiceNames[i]!=NULL; i++) {\n aSequence.realloc(i+1);\n aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i]));\n }\n return aSequence;\n }\n\n Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames()\n throw (RuntimeException)\n {\n return CXPathAPI::_getSupportedServiceNames();\n }\n\n OUString SAL_CALL CXPathAPI::getImplementationName()\n throw (RuntimeException)\n {\n return CXPathAPI::_getImplementationName();\n }\n\n sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName)\n throw (RuntimeException)\n {\n Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames();\n for (sal_Int32 i=0; i<supported.getLength(); i++)\n {\n if (supported[i] == aServiceName) return sal_True;\n }\n return sal_False;\n }\n\n \/\/ -------------------------------------------------------------------\n\n void SAL_CALL CXPathAPI::registerNS(\n const OUString& aPrefix,\n const OUString& aURI)\n throw (RuntimeException)\n {\n m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI));\n }\n\n void SAL_CALL CXPathAPI::unregisterNS(\n const OUString& aPrefix,\n const OUString& aURI)\n throw (RuntimeException)\n {\n if ((m_nsmap.find(aPrefix))->second.equals(aURI))\n m_nsmap.erase(aPrefix);\n }\n\n \/\/ register all namespaces stored in the namespace list for this object\n \/\/ with the current xpath evaluation context\n static void _registerNamespaces(\n xmlXPathContextPtr ctx,\n const nsmap_t& nsmap)\n {\n nsmap_t::const_iterator i = nsmap.begin();\n OString oprefix, ouri;\n xmlChar *p, *u;\n while (i != nsmap.end())\n {\n oprefix = OUStringToOString(i->first, RTL_TEXTENCODING_UTF8);\n ouri = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8);\n p = (xmlChar*)oprefix.getStr();\n u = (xmlChar*)ouri.getStr();\n xmlXPathRegisterNs(ctx, p, u);\n i++;\n }\n }\n\n \/\/ get all ns decls on a node (and parent nodes, if any) and register them\n static void _collectNamespaces(\n CXPathAPI* pAPI,\n const Reference< XNode >& namespaceNode)\n {\n \/\/ get namespace decls from node...\n xmlNodePtr pNode = DOM::CNode::getNodePtr(namespaceNode);\n while (pNode != 0) {\n xmlNsPtr curDef = pNode->nsDef;\n while (curDef != 0) {\n const xmlChar* xHref = curDef->href;\n OUString aURI((sal_Char*)xHref, strlen((char*)xHref), RTL_TEXTENCODING_UTF8);\n const xmlChar* xPre = curDef->prefix;\n OUString aPrefix((sal_Char*)xPre, strlen((char*)xPre), RTL_TEXTENCODING_UTF8);\n pAPI->registerNS(aPrefix, aURI);\n curDef = curDef->next;\n }\n pNode = pNode->parent;\n }\n }\n\n \/\/ register function and variable lookup functions with the current\n \/\/ xpath evaluation context\n static void _registerExtensions(\n xmlXPathContextPtr ctx,\n const extensions_t& extensions)\n {\n extensions_t::const_iterator i = extensions.begin();\n while (i != extensions.end())\n {\n Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle();\n if ( aHandle.functionLookupFunction != 0 )\n {\n xmlXPathRegisterFuncLookup(ctx,\n reinterpret_cast<xmlXPathFuncLookupFunc>(\n sal::static_int_cast<sal_IntPtr>(aHandle.functionLookupFunction)),\n reinterpret_cast<void*>(\n sal::static_int_cast<sal_IntPtr>(aHandle.functionData)));\n }\n if ( aHandle.variableLookupFunction != 0 )\n {\n xmlXPathRegisterVariableLookup(ctx,\n reinterpret_cast<xmlXPathVariableLookupFunc>(\n sal::static_int_cast<sal_IntPtr>(aHandle.variableLookupFunction)),\n reinterpret_cast<void*>(\n sal::static_int_cast<sal_IntPtr>(aHandle.variableData)));\n }\n i++;\n }\n }\n\n \/**\n * Use an XPath string to select a nodelist.\n *\/\n Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList(\n const Reference< XNode >& contextNode,\n const OUString& expr)\n throw (RuntimeException, XPathException)\n {\n Reference< XXPathObject > xobj = eval(contextNode, expr);\n return xobj->getNodeList();\n }\n\n \/**\n * same as selectNodeList but registers all name space decalratiosn found on namespaceNode\n *\/\n Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS(\n const Reference< XNode >& contextNode,\n const OUString& expr,\n const Reference< XNode >& namespaceNode)\n throw (RuntimeException, XPathException)\n {\n _collectNamespaces(this, namespaceNode);\n return selectNodeList(contextNode, expr);\n }\n\n \/**\n * Same as selectNodeList but returns the first node (if any)\n *\/\n Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode(\n const Reference< XNode >& contextNode,\n const OUString& expr)\n throw (RuntimeException, XPathException)\n {\n Reference< XNodeList > aList = selectNodeList(contextNode, expr);\n Reference< XNode > aNode = aList->item(0);\n return aNode;\n }\n\n \/**\n * Same as selectSingleNode but registers all namespaces declared on\n * namespaceNode\n *\/\n Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS(\n const Reference< XNode >& contextNode,\n const OUString& expr,\n const Reference< XNode >& namespaceNode )\n throw (RuntimeException, XPathException)\n {\n _collectNamespaces(this, namespaceNode);\n return selectSingleNode(contextNode, expr);\n }\n\n static OUString make_error_message(xmlErrorPtr pError)\n {\n ::rtl::OUStringBuffer buf;\n if (pError->message) {\n buf.appendAscii(pError->message);\n }\n int line = pError->line;\n if (line) {\n buf.appendAscii(\"Line: \");\n buf.append(static_cast<sal_Int32>(line));\n buf.appendAscii(\"\\n\");\n }\n int column = pError->int2;\n if (column) {\n buf.appendAscii(\"Column: \");\n buf.append(static_cast<sal_Int32>(column));\n buf.appendAscii(\"\\n\");\n }\n OUString msg = buf.makeStringAndClear();\n return msg;\n }\n\n extern \"C\" {\n\n static void generic_error_func(void *userData, const char *format, ...)\n {\n (void) userData;\n char str[1000];\n va_list args;\n\n va_start(args, format);\n#ifdef _WIN32\n#define vsnprintf _vsnprintf\n#endif\n vsnprintf(str, sizeof(str), format, args);\n va_end(args);\n\n ::rtl::OUStringBuffer buf(\n OUString::createFromAscii(\"libxml2 error:\\n\"));\n buf.appendAscii(str);\n OString msg = OUStringToOString(buf.makeStringAndClear(),\n RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, msg.getStr());\n }\n\n static void structured_error_func(void * userData, xmlErrorPtr error)\n {\n (void) userData;\n ::rtl::OUStringBuffer buf(\n OUString::createFromAscii(\"libxml2 error:\\n\"));\n if (error) {\n buf.append(make_error_message(error));\n } else {\n buf.append(OUString::createFromAscii(\"no error argument!\"));\n }\n OString msg = OUStringToOString(buf.makeStringAndClear(),\n RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, msg.getStr());\n }\n\n } \/\/ extern \"C\"\n\n \/**\n * evaluates an XPath string. relative XPath expressions are evaluated relative to\n * the context Node\n *\/\n Reference< XXPathObject > SAL_CALL CXPathAPI::eval(\n const Reference< XNode >& contextNode,\n const OUString& expr)\n throw (RuntimeException, XPathException)\n {\n xmlXPathContextPtr xpathCtx;\n xmlXPathObjectPtr xpathObj;\n\n \/\/ get the node and document\n xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode);\n xmlDocPtr pDoc = pNode->doc;\n\n \/* NB: workaround for #i87252#:\n libxml < 2.6.17 considers it an error if the context\n node is the empty document (i.e. its xpathCtx->doc has no\n children). libxml 2.6.17 does not consider it an error.\n Unfortunately, old libxml prints an error message to stderr,\n which (afaik) cannot be turned off in this case, so we handle it.\n *\/\n if (!pDoc->children) {\n throw XPathException();\n }\n\n \/* Create xpath evaluation context *\/\n xpathCtx = xmlXPathNewContext(pDoc);\n if (xpathCtx == NULL) throw XPathException();\n\n \/\/ set context node\n xpathCtx->node = pNode;\n \/\/ error handling\n xpathCtx->error = structured_error_func;\n xmlSetGenericErrorFunc(NULL, generic_error_func);\n\n \/\/ register namespaces and extension\n _registerNamespaces(xpathCtx, m_nsmap);\n _registerExtensions(xpathCtx, m_extensions);\n\n \/* run the query *\/\n OString o1 = OUStringToOString(expr, RTL_TEXTENCODING_UTF8);\n xmlChar *xStr = (xmlChar*)o1.getStr();\n if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) {\n \/\/ OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message);\n xmlXPathFreeContext(xpathCtx);\n throw XPathException();\n }\n xmlXPathFreeContext(xpathCtx);\n Reference< XXPathObject > aObj(new CXPathObject(xpathObj));\n return aObj;\n }\n\n \/**\n * same as eval but registers all namespace declarations found on namespaceNode\n *\/\n Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(\n const Reference< XNode >& contextNode,\n const OUString& expr,\n const Reference< XNode >& namespaceNode)\n throw (RuntimeException, XPathException)\n {\n _collectNamespaces(this, namespaceNode);\n return eval(contextNode, expr);\n }\n\n \/**\n * uses the service manager to create an instance of the service denoted by aName.\n * If the returned object implements the XXPathExtension interface, it is added to the list\n * of extensions that are used when evaluating XPath strings with this XPathAPI instance\n *\/\n void SAL_CALL CXPathAPI::registerExtension(\n const OUString& aName)\n throw (RuntimeException)\n {\n \/\/ get extension from service manager\n Reference< XXPathExtension > aExtension(m_aFactory->createInstance(aName), UNO_QUERY_THROW);\n m_extensions.push_back( aExtension );\n }\n\n \/**\n * registers the given extension instance to be used by XPath evaluations performed through this\n * XPathAPI instance\n *\/\n void SAL_CALL CXPathAPI::registerExtensionInstance(\n const Reference< XXPathExtension>& aExtension)\n throw (RuntimeException)\n {\n if (aExtension.is()) {\n m_extensions.push_back( aExtension );\n } else {\n throw RuntimeException();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nBy Vivek Dhiman \n*\/\n\n#include <cstdlib>\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <map>\n#include <utility> \/\/ for pairs\n#include <algorithm> \/\/ for swap\nusing namespace std;\n\nint main (int argc, char const *argv[]){\n \/\/************* make sure args are present:\n if (argc != 3){\n cout << \"ERROR: something wrong with the inputs\" << endl;\n cout << \"usage:\\n \" << argv[0] << \" networkEdgeIdMap.csv network.clusters newnetwork.clusters\" << endl;\n exit(1);\n } \n \/\/************* got the args\n clock_t begin = clock();\n \n \/\/************* start load edgelist\n ifstream inFile;\n inFile.open( argv[1] );\n if (!inFile) {\n cout << \"ERROR: unable to open input file\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ index should be iterator not integer????\n long long edgeId = 0;\n map<long long, pair<long long, long long> > edgeIdMap; \/\/ O(log n) access too slow? \n long long ni, nj;\n while (inFile >> ni >> nj >> edgeId){ \/\/ scan edgelist to populate \n edgeIdMap[edgeId] = make_pair(ni,nj);\n } \n inFile.close(); inFile.clear();\n \/\/************* end load edgelist\n \n \/\/************* loop over jaccards file and do the clustering\n \n ifstream jaccFile; \n jaccFile.open( argv[2] );\n if (!jaccFile) {\n cout << \"ERROR: unable to open jaccards file\" << endl;\n exit(1); \/\/ terminate with error\n } \n FILE * nwClusterFile = fopen( argv[3], \"w\" );\n string line;\n while (std::getline(jaccFile, line)){\n std::stringstream ss(line);\n while(ss >> edgeId){\n fprintf( nwClusterFile, \"%ld,%ld \", edgeIdMap[edgeId].first, edgeIdMap[edgeId].second);\n }\n fprintf( nwClusterFile, \"\\n\");\n } \n fclose(nwClusterFile);\n \/\/************* done looping over jaccards file\n jaccFile.close(); jaccFile.clear();\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n return 0;\n}\n<commit_msg>Update replaceEdgeIdByEdgNodes.cpp<commit_after>\/*\nBy Vivek Dhiman \n*\/\n\n#include <cstdlib>\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <map>\n#include <utility> \/\/ for pairs\n#include <algorithm> \/\/ for swap\nusing namespace std;\n\nint main (int argc, char const *argv[]){\n \/\/************* make sure args are present:\n if (argc != 4){\n cout << \"ERROR: something wrong with the inputs\" << endl;\n cout << \"usage:\\n \" << argv[0] << \" networkEdgeIdMap.csv network.clusters newnetwork.clusters\" << endl;\n exit(1);\n } \n \/\/************* got the args\n clock_t begin = clock();\n \n \/\/************* start load edgelist\n ifstream inFile;\n inFile.open( argv[1] );\n if (!inFile) {\n cout << \"ERROR: unable to open input file\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ index should be iterator not integer????\n long long edgeId = 0;\n map<long long, pair<long long, long long> > edgeIdMap; \/\/ O(log n) access too slow? \n long long ni, nj;\n while (inFile >> ni >> nj >> edgeId){ \/\/ scan edgelist to populate \n edgeIdMap[edgeId] = make_pair(ni,nj);\n } \n inFile.close(); inFile.clear();\n \/\/************* end load edgelist\n \n \/\/************* loop over jaccards file and do the clustering\n \n ifstream jaccFile; \n jaccFile.open( argv[2] );\n if (!jaccFile) {\n cout << \"ERROR: unable to open jaccards file\" << endl;\n exit(1); \/\/ terminate with error\n } \n FILE * nwClusterFile = fopen( argv[3], \"w\" );\n string line;\n while (std::getline(jaccFile, line)){\n std::stringstream ss(line);\n while(ss >> edgeId){\n fprintf( nwClusterFile, \"%ld,%ld \", edgeIdMap[edgeId].first, edgeIdMap[edgeId].second);\n }\n fprintf( nwClusterFile, \"\\n\");\n } \n fclose(nwClusterFile);\n \/\/************* done looping over jaccards file\n jaccFile.close(); jaccFile.clear();\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2016 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Graphics\/MaterialPipeline.hpp>\n\n#ifndef NAZARA_RENDERER_OPENGL\n#define NAZARA_RENDERER_OPENGL \/\/ Mandatory to include the OpenGL headers\n#endif\n\n#include <Nazara\/Renderer\/OpenGL.hpp>\n#include <Nazara\/Renderer\/UberShaderPreprocessor.hpp>\n#include <Nazara\/Graphics\/Debug.hpp>\n\nnamespace Nz\n{\n\tnamespace\n\t{\n\t\tconst UInt8 r_basicFragmentShader[] = {\n\t\t\t#include <Nazara\/Graphics\/Resources\/Shaders\/Basic\/core.frag.h>\n\t\t};\n\n\t\tconst UInt8 r_basicVertexShader[] = {\n\t\t\t#include <Nazara\/Graphics\/Resources\/Shaders\/Basic\/core.vert.h>\n\t\t};\n\n\t\tconst UInt8 r_phongLightingFragmentShader[] = {\n\t\t\t#include <Nazara\/Graphics\/Resources\/Shaders\/PhongLighting\/core.frag.h>\n\t\t};\n\n\t\tconst UInt8 r_phongLightingVertexShader[] = {\n\t\t\t#include <Nazara\/Graphics\/Resources\/Shaders\/PhongLighting\/core.vert.h>\n\t\t};\n\t}\n\n\t\/*!\n\t* \\ingroup graphics\n\t* \\class Nz::MaterialPipeline\n\t*\n\t* \\brief Graphics class used to contains all rendering states that are not allowed to change individually on rendering devices\n\t*\/\n\n\t\/*!\n\t* \\brief Returns a reference to a MaterialPipeline built with MaterialPipelineInfo\n\t*\n\t* This function is using a cache, calling it multiples times with the same MaterialPipelineInfo will returns references to a single MaterialPipeline\n\t*\n\t* \\param pipelineInfo Pipeline informations used to build\/retrieve a MaterialPipeline object\n\t*\/\n\tMaterialPipelineRef MaterialPipeline::GetPipeline(const MaterialPipelineInfo& pipelineInfo)\n\t{\n\t\tauto it = s_pipelineCache.find(pipelineInfo);\n\t\tif (it == s_pipelineCache.end())\n\t\t\tit = s_pipelineCache.insert(it, PipelineCache::value_type(pipelineInfo, New(pipelineInfo)));\n\n\t\treturn it->second;\n\t}\n\n\tvoid MaterialPipeline::GenerateRenderPipeline(UInt32 flags) const\n\t{\n\t\tNazaraAssert(m_pipelineInfo.uberShader, \"Material pipeline has no uber shader\");\n\n\t\tParameterList list;\n\t\tlist.SetParameter(\"ALPHA_MAPPING\", m_pipelineInfo.hasAlphaMap);\n\t\tlist.SetParameter(\"ALPHA_TEST\", m_pipelineInfo.alphaTest);\n\t\tlist.SetParameter(\"COMPUTE_TBNMATRIX\", m_pipelineInfo.hasNormalMap || m_pipelineInfo.hasHeightMap);\n\t\tlist.SetParameter(\"DIFFUSE_MAPPING\", m_pipelineInfo.hasDiffuseMap);\n\t\tlist.SetParameter(\"EMISSIVE_MAPPING\", m_pipelineInfo.hasEmissiveMap);\n\t\tlist.SetParameter(\"NORMAL_MAPPING\", m_pipelineInfo.hasNormalMap);\n\t\tlist.SetParameter(\"PARALLAX_MAPPING\", m_pipelineInfo.hasHeightMap);\n\t\tlist.SetParameter(\"SHADOW_MAPPING\", m_pipelineInfo.shadowReceive);\n\t\tlist.SetParameter(\"SPECULAR_MAPPING\", m_pipelineInfo.hasSpecularMap);\n\t\tlist.SetParameter(\"TEXTURE_MAPPING\", m_pipelineInfo.hasAlphaMap || m_pipelineInfo.hasDiffuseMap || m_pipelineInfo.hasEmissiveMap ||\n\t\t m_pipelineInfo.hasNormalMap || m_pipelineInfo.hasHeightMap || m_pipelineInfo.hasSpecularMap ||\n\t\t flags & ShaderFlags_TextureOverlay);\n\t\tlist.SetParameter(\"TRANSFORM\", true);\n\n\t\tlist.SetParameter(\"FLAG_BILLBOARD\", static_cast<bool>((flags & ShaderFlags_Billboard) != 0));\n\t\tlist.SetParameter(\"FLAG_DEFERRED\", static_cast<bool>((flags & ShaderFlags_Deferred) != 0));\n\t\tlist.SetParameter(\"FLAG_INSTANCING\", static_cast<bool>((flags & ShaderFlags_Instancing) != 0));\n\t\tlist.SetParameter(\"FLAG_TEXTUREOVERLAY\", static_cast<bool>((flags & ShaderFlags_TextureOverlay) != 0));\n\t\tlist.SetParameter(\"FLAG_VERTEXCOLOR\", static_cast<bool>((flags & ShaderFlags_VertexColor) != 0));\n\n\t\tInstance& instance = m_instances[flags];\n\t\tinstance.uberInstance = m_pipelineInfo.uberShader->Get(list);\n\n\t\tRenderPipelineInfo renderPipelineInfo;\n\t\tstatic_cast<RenderStates&>(renderPipelineInfo).operator=(m_pipelineInfo); \/\/ Not my proudest line\n\n\t\trenderPipelineInfo.shader = instance.uberInstance->GetShader();\n\n\t\tinstance.renderPipeline.Create(renderPipelineInfo);\n\n\t\t#define CacheUniform(name) instance.uniforms[MaterialUniform_##name] = renderPipelineInfo.shader->GetUniformLocation(\"Material\" #name)\n\n\t\tCacheUniform(AlphaMap);\n\t\tCacheUniform(AlphaThreshold);\n\t\tCacheUniform(Ambient);\n\t\tCacheUniform(Diffuse);\n\t\tCacheUniform(DiffuseMap);\n\t\tCacheUniform(EmissiveMap);\n\t\tCacheUniform(HeightMap);\n\t\tCacheUniform(NormalMap);\n\t\tCacheUniform(Shininess);\n\t\tCacheUniform(Specular);\n\t\tCacheUniform(SpecularMap);\n\n\t\t#undef CacheUniform\n\t}\n\n\tbool MaterialPipeline::Initialize()\n\t{\n\t\t\/\/ Basic shader\n\t\t{\n\t\t\tUberShaderPreprocessorRef uberShader = UberShaderPreprocessor::New();\n\n\t\t\tString fragmentShader(reinterpret_cast<const char*>(r_basicFragmentShader), sizeof(r_basicFragmentShader));\n\t\t\tString vertexShader(reinterpret_cast<const char*>(r_basicVertexShader), sizeof(r_basicVertexShader));\n\n\t\t\tuberShader->SetShader(ShaderStageType_Fragment, fragmentShader, \"FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING\");\n\t\t\tuberShader->SetShader(ShaderStageType_Vertex, vertexShader, \"FLAG_BILLBOARD FLAG_INSTANCING FLAG_VERTEXCOLOR TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH\");\n\n\t\t\tUberShaderLibrary::Register(\"Basic\", uberShader);\n\t\t}\n\n\t\t\/\/ PhongLighting shader\n\t\t{\n\t\t\tUberShaderPreprocessorRef uberShader = UberShaderPreprocessor::New();\n\n\t\t\tString fragmentShader(reinterpret_cast<const char*>(r_phongLightingFragmentShader), sizeof(r_phongLightingFragmentShader));\n\t\t\tString vertexShader(reinterpret_cast<const char*>(r_phongLightingVertexShader), sizeof(r_phongLightingVertexShader));\n\n\t\t\tuberShader->SetShader(ShaderStageType_Fragment, fragmentShader, \"FLAG_DEFERRED FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING EMISSIVE_MAPPING NORMAL_MAPPING PARALLAX_MAPPING SHADOW_MAPPING SPECULAR_MAPPING\");\n\t\t\tuberShader->SetShader(ShaderStageType_Vertex, vertexShader, \"FLAG_BILLBOARD FLAG_DEFERRED FLAG_INSTANCING FLAG_VERTEXCOLOR COMPUTE_TBNMATRIX PARALLAX_MAPPING SHADOW_MAPPING TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH\");\n\n\t\t\tUberShaderLibrary::Register(\"PhongLighting\", uberShader);\n\t\t}\n\n\t\t\/\/ Once the base shaders are registered, we can now set some default materials\n\t\tMaterialPipelineInfo pipelineInfo;\n\t\tpipelineInfo.uberShader = UberShaderLibrary::Get(\"Basic\");\n\n\t\t\/\/ Basic 2D - No depth write\/face culling\n\t\tpipelineInfo.depthWrite = false;\n\t\tpipelineInfo.faceCulling = false;\n\n\t\tMaterialPipelineLibrary::Register(\"Basic2D\", GetPipeline(pipelineInfo));\n\n\t\t\/\/ Translucent 2D - Alpha blending with no depth write\/face culling\n\t\tpipelineInfo.blending = true;\n\t\tpipelineInfo.depthWrite = false;\n\t\tpipelineInfo.faceCulling = false;\n\t\tpipelineInfo.dstBlend = BlendFunc_InvSrcAlpha;\n\t\tpipelineInfo.srcBlend = BlendFunc_SrcAlpha;\n\n\t\tMaterialPipelineLibrary::Register(\"Translucent2D\", GetPipeline(pipelineInfo));\n\n\t\treturn true;\n\t}\n\n\tvoid MaterialPipeline::Uninitialize()\n\t{\n\t\ts_pipelineCache.clear();\n\t\tUberShaderLibrary::Unregister(\"PhongLighting\");\n\t\tUberShaderLibrary::Unregister(\"Basic\");\n\t\tMaterialPipelineLibrary::Uninitialize();\n\t}\n\n\tMaterialPipelineLibrary::LibraryMap MaterialPipeline::s_library;\n\tMaterialPipeline::PipelineCache MaterialPipeline::s_pipelineCache;\n}<commit_msg>Graphics\/MaterialPipeline: Add Translucent3D pipeline<commit_after>\/\/ Copyright (C) 2016 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Graphics\/MaterialPipeline.hpp>\n\n#ifndef NAZARA_RENDERER_OPENGL\n#define NAZARA_RENDERER_OPENGL \/\/ Mandatory to include the OpenGL headers\n#endif\n\n#include <Nazara\/Renderer\/OpenGL.hpp>\n#include <Nazara\/Renderer\/UberShaderPreprocessor.hpp>\n#include <Nazara\/Graphics\/Debug.hpp>\n\nnamespace Nz\n{\n\tnamespace\n\t{\n\t\tconst UInt8 r_basicFragmentShader[] = {\n\t\t\t#include <Nazara\/Graphics\/Resources\/Shaders\/Basic\/core.frag.h>\n\t\t};\n\n\t\tconst UInt8 r_basicVertexShader[] = {\n\t\t\t#include <Nazara\/Graphics\/Resources\/Shaders\/Basic\/core.vert.h>\n\t\t};\n\n\t\tconst UInt8 r_phongLightingFragmentShader[] = {\n\t\t\t#include <Nazara\/Graphics\/Resources\/Shaders\/PhongLighting\/core.frag.h>\n\t\t};\n\n\t\tconst UInt8 r_phongLightingVertexShader[] = {\n\t\t\t#include <Nazara\/Graphics\/Resources\/Shaders\/PhongLighting\/core.vert.h>\n\t\t};\n\t}\n\n\t\/*!\n\t* \\ingroup graphics\n\t* \\class Nz::MaterialPipeline\n\t*\n\t* \\brief Graphics class used to contains all rendering states that are not allowed to change individually on rendering devices\n\t*\/\n\n\t\/*!\n\t* \\brief Returns a reference to a MaterialPipeline built with MaterialPipelineInfo\n\t*\n\t* This function is using a cache, calling it multiples times with the same MaterialPipelineInfo will returns references to a single MaterialPipeline\n\t*\n\t* \\param pipelineInfo Pipeline informations used to build\/retrieve a MaterialPipeline object\n\t*\/\n\tMaterialPipelineRef MaterialPipeline::GetPipeline(const MaterialPipelineInfo& pipelineInfo)\n\t{\n\t\tauto it = s_pipelineCache.find(pipelineInfo);\n\t\tif (it == s_pipelineCache.end())\n\t\t\tit = s_pipelineCache.insert(it, PipelineCache::value_type(pipelineInfo, New(pipelineInfo)));\n\n\t\treturn it->second;\n\t}\n\n\tvoid MaterialPipeline::GenerateRenderPipeline(UInt32 flags) const\n\t{\n\t\tNazaraAssert(m_pipelineInfo.uberShader, \"Material pipeline has no uber shader\");\n\n\t\tParameterList list;\n\t\tlist.SetParameter(\"ALPHA_MAPPING\", m_pipelineInfo.hasAlphaMap);\n\t\tlist.SetParameter(\"ALPHA_TEST\", m_pipelineInfo.alphaTest);\n\t\tlist.SetParameter(\"COMPUTE_TBNMATRIX\", m_pipelineInfo.hasNormalMap || m_pipelineInfo.hasHeightMap);\n\t\tlist.SetParameter(\"DIFFUSE_MAPPING\", m_pipelineInfo.hasDiffuseMap);\n\t\tlist.SetParameter(\"EMISSIVE_MAPPING\", m_pipelineInfo.hasEmissiveMap);\n\t\tlist.SetParameter(\"NORMAL_MAPPING\", m_pipelineInfo.hasNormalMap);\n\t\tlist.SetParameter(\"PARALLAX_MAPPING\", m_pipelineInfo.hasHeightMap);\n\t\tlist.SetParameter(\"SHADOW_MAPPING\", m_pipelineInfo.shadowReceive);\n\t\tlist.SetParameter(\"SPECULAR_MAPPING\", m_pipelineInfo.hasSpecularMap);\n\t\tlist.SetParameter(\"TEXTURE_MAPPING\", m_pipelineInfo.hasAlphaMap || m_pipelineInfo.hasDiffuseMap || m_pipelineInfo.hasEmissiveMap ||\n\t\t m_pipelineInfo.hasNormalMap || m_pipelineInfo.hasHeightMap || m_pipelineInfo.hasSpecularMap ||\n\t\t flags & ShaderFlags_TextureOverlay);\n\t\tlist.SetParameter(\"TRANSFORM\", true);\n\n\t\tlist.SetParameter(\"FLAG_BILLBOARD\", static_cast<bool>((flags & ShaderFlags_Billboard) != 0));\n\t\tlist.SetParameter(\"FLAG_DEFERRED\", static_cast<bool>((flags & ShaderFlags_Deferred) != 0));\n\t\tlist.SetParameter(\"FLAG_INSTANCING\", static_cast<bool>((flags & ShaderFlags_Instancing) != 0));\n\t\tlist.SetParameter(\"FLAG_TEXTUREOVERLAY\", static_cast<bool>((flags & ShaderFlags_TextureOverlay) != 0));\n\t\tlist.SetParameter(\"FLAG_VERTEXCOLOR\", static_cast<bool>((flags & ShaderFlags_VertexColor) != 0));\n\n\t\tInstance& instance = m_instances[flags];\n\t\tinstance.uberInstance = m_pipelineInfo.uberShader->Get(list);\n\n\t\tRenderPipelineInfo renderPipelineInfo;\n\t\tstatic_cast<RenderStates&>(renderPipelineInfo).operator=(m_pipelineInfo); \/\/ Not my proudest line\n\n\t\trenderPipelineInfo.shader = instance.uberInstance->GetShader();\n\n\t\tinstance.renderPipeline.Create(renderPipelineInfo);\n\n\t\t#define CacheUniform(name) instance.uniforms[MaterialUniform_##name] = renderPipelineInfo.shader->GetUniformLocation(\"Material\" #name)\n\n\t\tCacheUniform(AlphaMap);\n\t\tCacheUniform(AlphaThreshold);\n\t\tCacheUniform(Ambient);\n\t\tCacheUniform(Diffuse);\n\t\tCacheUniform(DiffuseMap);\n\t\tCacheUniform(EmissiveMap);\n\t\tCacheUniform(HeightMap);\n\t\tCacheUniform(NormalMap);\n\t\tCacheUniform(Shininess);\n\t\tCacheUniform(Specular);\n\t\tCacheUniform(SpecularMap);\n\n\t\t#undef CacheUniform\n\t}\n\n\tbool MaterialPipeline::Initialize()\n\t{\n\t\t\/\/ Basic shader\n\t\t{\n\t\t\tUberShaderPreprocessorRef uberShader = UberShaderPreprocessor::New();\n\n\t\t\tString fragmentShader(reinterpret_cast<const char*>(r_basicFragmentShader), sizeof(r_basicFragmentShader));\n\t\t\tString vertexShader(reinterpret_cast<const char*>(r_basicVertexShader), sizeof(r_basicVertexShader));\n\n\t\t\tuberShader->SetShader(ShaderStageType_Fragment, fragmentShader, \"FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING\");\n\t\t\tuberShader->SetShader(ShaderStageType_Vertex, vertexShader, \"FLAG_BILLBOARD FLAG_INSTANCING FLAG_VERTEXCOLOR TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH\");\n\n\t\t\tUberShaderLibrary::Register(\"Basic\", uberShader);\n\t\t}\n\n\t\t\/\/ PhongLighting shader\n\t\t{\n\t\t\tUberShaderPreprocessorRef uberShader = UberShaderPreprocessor::New();\n\n\t\t\tString fragmentShader(reinterpret_cast<const char*>(r_phongLightingFragmentShader), sizeof(r_phongLightingFragmentShader));\n\t\t\tString vertexShader(reinterpret_cast<const char*>(r_phongLightingVertexShader), sizeof(r_phongLightingVertexShader));\n\n\t\t\tuberShader->SetShader(ShaderStageType_Fragment, fragmentShader, \"FLAG_DEFERRED FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING EMISSIVE_MAPPING NORMAL_MAPPING PARALLAX_MAPPING SHADOW_MAPPING SPECULAR_MAPPING\");\n\t\t\tuberShader->SetShader(ShaderStageType_Vertex, vertexShader, \"FLAG_BILLBOARD FLAG_DEFERRED FLAG_INSTANCING FLAG_VERTEXCOLOR COMPUTE_TBNMATRIX PARALLAX_MAPPING SHADOW_MAPPING TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH\");\n\n\t\t\tUberShaderLibrary::Register(\"PhongLighting\", uberShader);\n\t\t}\n\n\t\t\/\/ Once the base shaders are registered, we can now set some default materials\n\t\tMaterialPipelineInfo pipelineInfo;\n\t\tpipelineInfo.uberShader = UberShaderLibrary::Get(\"Basic\");\n\n\t\t\/\/ Basic 2D - No depth write\/face culling\n\t\tpipelineInfo.depthWrite = false;\n\t\tpipelineInfo.faceCulling = false;\n\n\t\tMaterialPipelineLibrary::Register(\"Basic2D\", GetPipeline(pipelineInfo));\n\n\t\t\/\/ Translucent 2D - Alpha blending with no depth write\/face culling\n\t\tpipelineInfo.blending = true;\n\t\tpipelineInfo.depthWrite = false;\n\t\tpipelineInfo.faceCulling = false;\n\t\tpipelineInfo.dstBlend = BlendFunc_InvSrcAlpha;\n\t\tpipelineInfo.srcBlend = BlendFunc_SrcAlpha;\n\n\t\tMaterialPipelineLibrary::Register(\"Translucent2D\", GetPipeline(pipelineInfo));\n\n\t\t\/\/ Translucent 3D - Alpha blending with depth buffer and no depth write\/face culling\n\t\tpipelineInfo.blending = true;\n\t\tpipelineInfo.depthBuffer = true;\n\t\tpipelineInfo.depthWrite = false;\n\t\tpipelineInfo.faceCulling = false;\n\t\tpipelineInfo.dstBlend = BlendFunc_InvSrcAlpha;\n\t\tpipelineInfo.srcBlend = BlendFunc_SrcAlpha;\n\n\t\tMaterialPipelineLibrary::Register(\"Translucent3D\", GetPipeline(pipelineInfo));\n\n\t\treturn true;\n\t}\n\n\tvoid MaterialPipeline::Uninitialize()\n\t{\n\t\ts_pipelineCache.clear();\n\t\tUberShaderLibrary::Unregister(\"PhongLighting\");\n\t\tUberShaderLibrary::Unregister(\"Basic\");\n\t\tMaterialPipelineLibrary::Uninitialize();\n\t}\n\n\tMaterialPipelineLibrary::LibraryMap MaterialPipeline::s_library;\n\tMaterialPipeline::PipelineCache MaterialPipeline::s_pipelineCache;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.\n\n#include \"SamplerStateGL4.hpp\"\n#include \"ErrorChecker.hpp\"\n#include \"..\/Basic\/Unreachable.hpp\"\n#include \"Pomdog\/Graphics\/SamplerDescription.hpp\"\n#include \"Pomdog\/Utility\/Assert.hpp\"\n#include <algorithm>\n#include <utility>\n\nnamespace Pomdog {\nnamespace Detail {\nnamespace GL4 {\nnamespace {\n\nGLenum ToTextureAddressMode(TextureAddressMode address) noexcept\n{\n switch (address) {\n case TextureAddressMode::Clamp: return GL_CLAMP_TO_EDGE;\n case TextureAddressMode::Mirror: return GL_MIRRORED_REPEAT;\n case TextureAddressMode::Wrap: return GL_REPEAT;\n }\n POMDOG_UNREACHABLE(\"Unsupported texture address mode\");\n}\n\n} \/\/ unnamed namespace\n\nSamplerStateGL4::SamplerStateGL4(const SamplerDescription& description)\n{\n samplerObject = ([] {\n SamplerObjectGL4 sampler;\n glGenSamplers(1, sampler.Data());\n POMDOG_CHECK_ERROR_GL4(\"glGenSamplers\");\n return sampler;\n })();\n\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_WRAP_S, ToTextureAddressMode(description.AddressU));\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_WRAP_T, ToTextureAddressMode(description.AddressV));\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_WRAP_R, ToTextureAddressMode(description.AddressW));\n\n POMDOG_CHECK_ERROR_GL4(\"glSamplerParameteri\");\n\n switch (description.Filter) {\n case TextureFilter::Linear:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n break;\n case TextureFilter::Point:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n break;\n case TextureFilter::LinearMipPoint:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n break;\n case TextureFilter::PointMipLinear:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n break;\n case TextureFilter::MinLinearMagPointMipLinear:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n break;\n case TextureFilter::MinLinearMagPointMipPoint:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n break;\n case TextureFilter::MinPointMagLinearMipLinear:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n break;\n case TextureFilter::MinPointMagLinearMipPoint:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n break;\n case TextureFilter::Anisotropic:\n {\n \/\/\/@todo Not implemented:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n POMDOG_CHECK_ERROR_GL4(\"glSamplerParameteri\");\n\n POMDOG_ASSERT(1 <= description.MaxAnisotropy && description.MaxAnisotropy <= 16);\n\n GLfloat deviceMaxAnisotropy = 1.0f;\n\n glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &deviceMaxAnisotropy);\n POMDOG_CHECK_ERROR_GL4(\"glGetFloatv\");\n\n deviceMaxAnisotropy = std::min(deviceMaxAnisotropy,\n static_cast<decltype(deviceMaxAnisotropy)>(description.MaxAnisotropy));\n\n glSamplerParameterf(samplerObject->value, GL_TEXTURE_MAX_ANISOTROPY_EXT, deviceMaxAnisotropy);\n POMDOG_CHECK_ERROR_GL4(\"glSamplerParameterf\");\n }\n break;\n }\n\n {\n POMDOG_ASSERT(description.MinMipLevel <= description.MaxMipLevel);\n POMDOG_ASSERT(description.MaxMipLevel <= std::numeric_limits<GLfloat>::max());\n\n glSamplerParameterf(samplerObject->value, GL_TEXTURE_MIN_LOD, description.MaxMipLevel);\n glSamplerParameterf(samplerObject->value, GL_TEXTURE_MAX_LOD, description.MaxMipLevel);\n glSamplerParameterf(samplerObject->value, GL_TEXTURE_LOD_BIAS, description.MipMapLevelOfDetailBias);\n POMDOG_CHECK_ERROR_GL4(\"glSamplerParameterf\");\n }\n}\n\nSamplerStateGL4::~SamplerStateGL4()\n{\n if (samplerObject) {\n glDeleteSamplers(1, samplerObject->Data());\n POMDOG_CHECK_ERROR_GL4(\"glDeleteSamplers\");\n }\n}\n\nvoid SamplerStateGL4::Apply(int index)\n{\n static_assert(GL_TEXTURE19 == (GL_TEXTURE0 + 19), \"\");\n POMDOG_ASSERT(index >= 0);\n POMDOG_ASSERT(index <= 19);\n\n POMDOG_ASSERT(samplerObject);\n glBindSampler(index, samplerObject->value);\n POMDOG_CHECK_ERROR_GL4(\"glBindSampler\");\n}\n\n} \/\/ namespace GL4\n} \/\/ namespace Detail\n} \/\/ namespace Pomdog\n<commit_msg>Minor refactor<commit_after>\/\/ Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.\n\n#include \"SamplerStateGL4.hpp\"\n#include \"ErrorChecker.hpp\"\n#include \"..\/Basic\/Unreachable.hpp\"\n#include \"Pomdog\/Graphics\/SamplerDescription.hpp\"\n#include \"Pomdog\/Utility\/Assert.hpp\"\n#include <algorithm>\n#include <utility>\n\nnamespace Pomdog {\nnamespace Detail {\nnamespace GL4 {\nnamespace {\n\nGLenum ToTextureAddressMode(TextureAddressMode address) noexcept\n{\n switch (address) {\n case TextureAddressMode::Clamp: return GL_CLAMP_TO_EDGE;\n case TextureAddressMode::Mirror: return GL_MIRRORED_REPEAT;\n case TextureAddressMode::Wrap: return GL_REPEAT;\n }\n POMDOG_UNREACHABLE(\"Unsupported texture address mode\");\n}\n\n} \/\/ unnamed namespace\n\nSamplerStateGL4::SamplerStateGL4(const SamplerDescription& description)\n{\n samplerObject = ([] {\n SamplerObjectGL4 sampler;\n glGenSamplers(1, sampler.Data());\n POMDOG_CHECK_ERROR_GL4(\"glGenSamplers\");\n return sampler;\n })();\n\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_WRAP_S, ToTextureAddressMode(description.AddressU));\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_WRAP_T, ToTextureAddressMode(description.AddressV));\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_WRAP_R, ToTextureAddressMode(description.AddressW));\n\n POMDOG_CHECK_ERROR_GL4(\"glSamplerParameteri\");\n\n switch (description.Filter) {\n case TextureFilter::Linear:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n break;\n case TextureFilter::Point:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n break;\n case TextureFilter::LinearMipPoint:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n break;\n case TextureFilter::PointMipLinear:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n break;\n case TextureFilter::MinLinearMagPointMipLinear:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n break;\n case TextureFilter::MinLinearMagPointMipPoint:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n break;\n case TextureFilter::MinPointMagLinearMipLinear:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n break;\n case TextureFilter::MinPointMagLinearMipPoint:\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n break;\n case TextureFilter::Anisotropic: {\n \/\/ FIXME: Not implemented\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n glSamplerParameteri(samplerObject->value, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n POMDOG_CHECK_ERROR_GL4(\"glSamplerParameteri\");\n\n POMDOG_ASSERT(1 <= description.MaxAnisotropy && description.MaxAnisotropy <= 16);\n\n GLfloat deviceMaxAnisotropy = 1.0f;\n glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &deviceMaxAnisotropy);\n POMDOG_CHECK_ERROR_GL4(\"glGetFloatv\");\n\n deviceMaxAnisotropy = std::min(deviceMaxAnisotropy,\n static_cast<decltype(deviceMaxAnisotropy)>(description.MaxAnisotropy));\n\n glSamplerParameterf(samplerObject->value, GL_TEXTURE_MAX_ANISOTROPY_EXT, deviceMaxAnisotropy);\n POMDOG_CHECK_ERROR_GL4(\"glSamplerParameterf\");\n break;\n }\n }\n\n {\n POMDOG_ASSERT(description.MinMipLevel <= description.MaxMipLevel);\n POMDOG_ASSERT(description.MaxMipLevel <= std::numeric_limits<GLfloat>::max());\n\n glSamplerParameterf(samplerObject->value, GL_TEXTURE_MIN_LOD, description.MaxMipLevel);\n glSamplerParameterf(samplerObject->value, GL_TEXTURE_MAX_LOD, description.MaxMipLevel);\n glSamplerParameterf(samplerObject->value, GL_TEXTURE_LOD_BIAS, description.MipMapLevelOfDetailBias);\n POMDOG_CHECK_ERROR_GL4(\"glSamplerParameterf\");\n }\n}\n\nSamplerStateGL4::~SamplerStateGL4()\n{\n if (samplerObject) {\n glDeleteSamplers(1, samplerObject->Data());\n POMDOG_CHECK_ERROR_GL4(\"glDeleteSamplers\");\n }\n}\n\nvoid SamplerStateGL4::Apply(int index)\n{\n static_assert(GL_TEXTURE19 == (GL_TEXTURE0 + 19), \"\");\n POMDOG_ASSERT(index >= 0);\n POMDOG_ASSERT(index <= 19);\n\n POMDOG_ASSERT(samplerObject);\n glBindSampler(index, samplerObject->value);\n POMDOG_CHECK_ERROR_GL4(\"glBindSampler\");\n}\n\n} \/\/ namespace GL4\n} \/\/ namespace Detail\n} \/\/ namespace Pomdog\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE libraries and the Kate part.\n *\n * Copyright (C) 2001-2010 Christoph Cullmann <cullmann@kde.org>\n * Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>\n * Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk>\n * Copyright (C) 2007 Dominik Haumann <dhaumann kde org>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"katepartpluginmanager.h\"\n#include \"katepartpluginmanager.moc\"\n\n#include \"kateglobal.h\"\n\n#include <ktexteditor\/plugin.h>\n#include <ktexteditor\/document.h>\n#include <ktexteditor\/view.h>\n#include <kconfig.h>\n#include <kconfiggroup.h>\n#include <kxmlguifactory.h>\n#include <kplugininfo.h>\n\n#include <kservicetypetrader.h>\n#include <kdebug.h>\n\nKatePartPluginInfo::KatePartPluginInfo(KService::Ptr service)\n : m_pluginInfo(service)\n{\n}\n\nQString KatePartPluginInfo::saveName() const\n{\n QString saveName = m_pluginInfo.pluginName();\n if (saveName.isEmpty())\n saveName = service()->library();\n return saveName;\n}\n\nKatePartPluginManager::KatePartPluginManager()\n : QObject(),\n m_config(new KConfig(\"katepartpluginsrc\", KConfig::NoGlobals))\n{\n setupPluginList ();\n loadConfig ();\n}\n\nKatePartPluginManager::~KatePartPluginManager()\n{\n writeConfig();\n \/\/ than unload the plugins\n unloadAllPlugins ();\n delete m_config;\n m_config = 0;\n}\n\nKatePartPluginManager *KatePartPluginManager::self()\n{\n return KateGlobal::self()->pluginManager ();\n}\n\nvoid KatePartPluginManager::setupPluginList ()\n{\n KService::List traderList = KServiceTypeTrader::self()->\n query(\"KTextEditor\/Plugin\",\n \"([X-KDE-Version] >= 4.0) and ([X-KDE-Version] <= \" + QString(\"%1.%2\").arg(KDE::versionMajor()).arg(KDE::versionMinor()) + ')');\n\n foreach(const KService::Ptr &ptr, traderList)\n {\n KatePartPluginInfo info(ptr);\n\n info.load = false;\n info.plugin = 0L;\n\n m_pluginList.push_back (info);\n }\n}\n\nvoid KatePartPluginManager::addDocument(KTextEditor::Document *doc)\n{\n \/\/kDebug() << doc;\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load) {\n it->plugin->addDocument(doc);\n }\n }\n}\n\nvoid KatePartPluginManager::removeDocument(KTextEditor::Document *doc)\n{\n \/\/kDebug() << doc;\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load) {\n it->plugin->removeDocument(doc);\n }\n }\n}\n\nvoid KatePartPluginManager::addView(KTextEditor::View *view)\n{\n \/\/kDebug() << view;\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load) {\n it->plugin->addView(view);\n }\n }\n}\n\nvoid KatePartPluginManager::removeView(KTextEditor::View *view)\n{\n \/\/kDebug() << view;\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load) {\n it->plugin->removeView(view);\n }\n }\n}\n\nvoid KatePartPluginManager::loadConfig ()\n{\n \/\/ first: unload the plugins\n unloadAllPlugins ();\n\n KConfigGroup cg = KConfigGroup(m_config, \"Kate Part Plugins\");\n\n \/\/ disable all plugin if no config...\n foreach (const KatePartPluginInfo &plugin, m_pluginList) {\n bool enabledByDefault = plugin.isEnabledByDefault();\n plugin.load = cg.readEntry (plugin.saveName(), enabledByDefault);\n }\n\n loadAllPlugins();\n}\n\nvoid KatePartPluginManager::writeConfig()\n{\n KConfigGroup cg = KConfigGroup( m_config, \"Kate Part Plugins\" );\n foreach(const KatePartPluginInfo &it, m_pluginList)\n {\n cg.writeEntry (it.saveName(), it.load);\n }\n}\n\nvoid KatePartPluginManager::loadAllPlugins ()\n{\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load)\n {\n loadPlugin(*it);\n enablePlugin(*it);\n }\n }\n}\n\nvoid KatePartPluginManager::unloadAllPlugins ()\n{\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->plugin) {\n disablePlugin(*it);\n unloadPlugin(*it);\n }\n }\n}\n\nvoid KatePartPluginManager::loadPlugin (KatePartPluginInfo &item)\n{\n if (item.plugin) return;\n\n \/\/ make sure all dependencies are loaded beforehand\n QStringList openDependencies = item.dependencies();\n if ( !openDependencies.empty() )\n {\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if ( openDependencies.contains( it->saveName() ) )\n {\n loadPlugin( *it );\n openDependencies.removeAll( it->saveName() );\n }\n }\n Q_ASSERT( openDependencies.empty() );\n }\n\n item.plugin = item.service()->createInstance<KTextEditor::Plugin>(this);\n Q_ASSERT(item.plugin);\n item.load = (item.plugin != 0);\n}\n\nvoid KatePartPluginManager::unloadPlugin (KatePartPluginInfo &item)\n{\n if ( !item.plugin ) return;\n\n \/\/ make sure dependent plugins are unloaded beforehand\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if ( !it->plugin ) continue;\n\n if ( it->dependencies().contains( item.saveName() ) )\n {\n unloadPlugin( *it );\n }\n }\n\n delete item.plugin;\n item.plugin = 0L;\n item.load = false;\n}\n\nvoid KatePartPluginManager::enablePlugin (KatePartPluginInfo &item)\n{\n \/\/ plugin around at all?\n if (!item.plugin || !item.load)\n return;\n\n \/\/ register docs and views\n foreach (KTextEditor::Document *doc, KateGlobal::self()->documents()) {\n if (!doc)\n continue;\n\n foreach (KTextEditor::View *view, doc->views()) {\n if (!view)\n continue;\n\n KXMLGUIFactory *viewFactory = view->factory();\n if (viewFactory)\n viewFactory->removeClient(view);\n\n item.plugin->addView(view);\n\n if (viewFactory)\n viewFactory->addClient(view);\n }\n }\n}\n\nvoid KatePartPluginManager::disablePlugin (KatePartPluginInfo &item)\n{\n \/\/ plugin around at all?\n if (!item.plugin || !item.load)\n return;\n\n \/\/ de-register docs and views\n foreach (KTextEditor::Document *doc, KateGlobal::self()->documents()) {\n if (!doc)\n continue;\n\n foreach (KTextEditor::View *view, doc->views()) {\n if (!view)\n continue;\n\n KXMLGUIFactory *viewFactory = view->factory();\n if (viewFactory)\n viewFactory->removeClient(view);\n\n item.plugin->removeView(view);\n\n if (viewFactory)\n viewFactory->addClient(view);\n }\n }\n}\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n<commit_msg>don't assert here, we can handle this, the plugin is just not loaded then<commit_after>\/* This file is part of the KDE libraries and the Kate part.\n *\n * Copyright (C) 2001-2010 Christoph Cullmann <cullmann@kde.org>\n * Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>\n * Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk>\n * Copyright (C) 2007 Dominik Haumann <dhaumann kde org>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"katepartpluginmanager.h\"\n#include \"katepartpluginmanager.moc\"\n\n#include \"kateglobal.h\"\n\n#include <ktexteditor\/plugin.h>\n#include <ktexteditor\/document.h>\n#include <ktexteditor\/view.h>\n#include <kconfig.h>\n#include <kconfiggroup.h>\n#include <kxmlguifactory.h>\n#include <kplugininfo.h>\n\n#include <kservicetypetrader.h>\n#include <kdebug.h>\n\nKatePartPluginInfo::KatePartPluginInfo(KService::Ptr service)\n : m_pluginInfo(service)\n{\n}\n\nQString KatePartPluginInfo::saveName() const\n{\n QString saveName = m_pluginInfo.pluginName();\n if (saveName.isEmpty())\n saveName = service()->library();\n return saveName;\n}\n\nKatePartPluginManager::KatePartPluginManager()\n : QObject(),\n m_config(new KConfig(\"katepartpluginsrc\", KConfig::NoGlobals))\n{\n setupPluginList ();\n loadConfig ();\n}\n\nKatePartPluginManager::~KatePartPluginManager()\n{\n writeConfig();\n \/\/ than unload the plugins\n unloadAllPlugins ();\n delete m_config;\n m_config = 0;\n}\n\nKatePartPluginManager *KatePartPluginManager::self()\n{\n return KateGlobal::self()->pluginManager ();\n}\n\nvoid KatePartPluginManager::setupPluginList ()\n{\n KService::List traderList = KServiceTypeTrader::self()->\n query(\"KTextEditor\/Plugin\",\n \"([X-KDE-Version] >= 4.0) and ([X-KDE-Version] <= \" + QString(\"%1.%2\").arg(KDE::versionMajor()).arg(KDE::versionMinor()) + ')');\n\n foreach(const KService::Ptr &ptr, traderList)\n {\n KatePartPluginInfo info(ptr);\n\n info.load = false;\n info.plugin = 0L;\n\n m_pluginList.push_back (info);\n }\n}\n\nvoid KatePartPluginManager::addDocument(KTextEditor::Document *doc)\n{\n \/\/kDebug() << doc;\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load) {\n it->plugin->addDocument(doc);\n }\n }\n}\n\nvoid KatePartPluginManager::removeDocument(KTextEditor::Document *doc)\n{\n \/\/kDebug() << doc;\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load) {\n it->plugin->removeDocument(doc);\n }\n }\n}\n\nvoid KatePartPluginManager::addView(KTextEditor::View *view)\n{\n \/\/kDebug() << view;\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load) {\n it->plugin->addView(view);\n }\n }\n}\n\nvoid KatePartPluginManager::removeView(KTextEditor::View *view)\n{\n \/\/kDebug() << view;\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load) {\n it->plugin->removeView(view);\n }\n }\n}\n\nvoid KatePartPluginManager::loadConfig ()\n{\n \/\/ first: unload the plugins\n unloadAllPlugins ();\n\n KConfigGroup cg = KConfigGroup(m_config, \"Kate Part Plugins\");\n\n \/\/ disable all plugin if no config...\n foreach (const KatePartPluginInfo &plugin, m_pluginList) {\n bool enabledByDefault = plugin.isEnabledByDefault();\n plugin.load = cg.readEntry (plugin.saveName(), enabledByDefault);\n }\n\n loadAllPlugins();\n}\n\nvoid KatePartPluginManager::writeConfig()\n{\n KConfigGroup cg = KConfigGroup( m_config, \"Kate Part Plugins\" );\n foreach(const KatePartPluginInfo &it, m_pluginList)\n {\n cg.writeEntry (it.saveName(), it.load);\n }\n}\n\nvoid KatePartPluginManager::loadAllPlugins ()\n{\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->load)\n {\n loadPlugin(*it);\n enablePlugin(*it);\n }\n }\n}\n\nvoid KatePartPluginManager::unloadAllPlugins ()\n{\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if (it->plugin) {\n disablePlugin(*it);\n unloadPlugin(*it);\n }\n }\n}\n\nvoid KatePartPluginManager::loadPlugin (KatePartPluginInfo &item)\n{\n if (item.plugin) return;\n\n \/\/ make sure all dependencies are loaded beforehand\n QStringList openDependencies = item.dependencies();\n if ( !openDependencies.empty() )\n {\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if ( openDependencies.contains( it->saveName() ) )\n {\n loadPlugin( *it );\n openDependencies.removeAll( it->saveName() );\n }\n }\n Q_ASSERT( openDependencies.empty() );\n }\n\n \/\/ try to load, else reset load flag!\n item.plugin = item.service()->createInstance<KTextEditor::Plugin>(this);\n item.load = (item.plugin != 0);\n}\n\nvoid KatePartPluginManager::unloadPlugin (KatePartPluginInfo &item)\n{\n if ( !item.plugin ) return;\n\n \/\/ make sure dependent plugins are unloaded beforehand\n for (KatePartPluginList::iterator it = m_pluginList.begin();\n it != m_pluginList.end(); ++it)\n {\n if ( !it->plugin ) continue;\n\n if ( it->dependencies().contains( item.saveName() ) )\n {\n unloadPlugin( *it );\n }\n }\n\n delete item.plugin;\n item.plugin = 0L;\n item.load = false;\n}\n\nvoid KatePartPluginManager::enablePlugin (KatePartPluginInfo &item)\n{\n \/\/ plugin around at all?\n if (!item.plugin || !item.load)\n return;\n\n \/\/ register docs and views\n foreach (KTextEditor::Document *doc, KateGlobal::self()->documents()) {\n if (!doc)\n continue;\n\n foreach (KTextEditor::View *view, doc->views()) {\n if (!view)\n continue;\n\n KXMLGUIFactory *viewFactory = view->factory();\n if (viewFactory)\n viewFactory->removeClient(view);\n\n item.plugin->addView(view);\n\n if (viewFactory)\n viewFactory->addClient(view);\n }\n }\n}\n\nvoid KatePartPluginManager::disablePlugin (KatePartPluginInfo &item)\n{\n \/\/ plugin around at all?\n if (!item.plugin || !item.load)\n return;\n\n \/\/ de-register docs and views\n foreach (KTextEditor::Document *doc, KateGlobal::self()->documents()) {\n if (!doc)\n continue;\n\n foreach (KTextEditor::View *view, doc->views()) {\n if (!view)\n continue;\n\n KXMLGUIFactory *viewFactory = view->factory();\n if (viewFactory)\n viewFactory->removeClient(view);\n\n item.plugin->removeView(view);\n\n if (viewFactory)\n viewFactory->addClient(view);\n }\n }\n}\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n<|endoftext|>"} {"text":"<commit_before>\/* +---------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | https:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |\n | See: https:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See details in https:\/\/www.mrpt.org\/License |\n +---------------------------------------------------------------------------+\n *\/\n\n#include \"vision-precomp.h\" \/\/ Precompiled headers\n\n#include <mrpt\/core\/exceptions.h>\n#include <mrpt\/vision\/CFeatureLines.h>\n#include <mrpt\/vision\/utils.h>\n\n\/\/ Universal include for all versions of OpenCV\n#include <mrpt\/otherlibs\/do_opencv_includes.h>\n\nusing namespace mrpt::vision;\nusing namespace std;\n\n#if MRPT_HAS_OPENCV\n\nstatic void extractLines_CannyHough(\n\tconst cv::Mat& canny_image, const std::vector<cv::Vec2f> lines,\n\tstd::vector<cv::Vec4i>& segments, size_t threshold)\n{\n\t\/\/ Some variables to change the coordinate system from polar to cartesian\n\tdouble rho, theta;\n\tdouble cosTheta, sinTheta;\n\tdouble m, c, cMax;\n\n\t\/\/ Variables to define the two extreme points on the line, clipped on the\n\t\/\/ window The constraint is x <= xF\n\tint x, y, xF, yF;\n\n\tsegments.clear();\n\n\t\/\/ For each line\n\tfor (size_t n(0); n < lines.size(); ++n)\n\t{\n\t\t\/\/ OpenCV implements the Hough accumulator with theta from 0 to PI, thus\n\t\t\/\/ rho could be negative We want to always have rho >= 0\n\t\tif (lines[n][0] < 0)\n\t\t{\n\t\t\trho = -lines[n][0];\n\t\t\ttheta = lines[n][1] - CV_PI;\n\t\t}\n\t\telse\n\t\t{\n\t\t\trho = lines[n][0];\n\t\t\ttheta = lines[n][1];\n\t\t}\n\n\t\tif (rho == 0 && theta == 0)\n\t\t{ \/\/ That case appeared at least once, so a test is needed\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Since the step for theta in cv::HoughLines should not be too small,\n\t\t\/\/ theta should exactly be 0 (and the line vertical) when this condition\n\t\t\/\/ is true\n\t\tif (fabs(theta) < 0.00001)\n\t\t{\n\t\t\tx = xF = static_cast<int>(rho + 0.5);\n\t\t\ty = 0;\n\t\t\tyF = canny_image.rows - 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Get the (m, c) slope and y-intercept from (rho, theta), so that y\n\t\t\t\/\/ = mx + c <=> (x, y) is on the line\n\t\t\tcosTheta = cos(theta);\n\t\t\tsinTheta = sin(theta);\n\t\t\tm = -cosTheta \/ sinTheta; \/\/ We are certain that sinTheta != 0\n\t\t\tc = rho * (sinTheta - m * cosTheta);\n\n\t\t\t\/\/ Get the two extreme points (x, y) and (xF, xF) for the line\n\t\t\t\/\/ inside the window, using (m, c)\n\t\t\tif (c >= 0)\n\t\t\t{\n\t\t\t\tif (c < canny_image.rows)\n\t\t\t\t{\n\t\t\t\t\t\/\/ (x, y) is at the left of the window\n\t\t\t\t\tx = 0;\n\t\t\t\t\ty = static_cast<int>(c);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ (x, y) is at the bottom of the window\n\t\t\t\t\ty = canny_image.rows - 1;\n\t\t\t\t\tx = static_cast<int>((y - c) \/ m);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ (x, y) is at the top of the window\n\t\t\t\tx = static_cast<int>(-c \/ m);\n\t\t\t\ty = 0;\n\t\t\t}\n\t\t\t\/\/ Define the intersection with the right side of the window\n\t\t\tcMax = m * (canny_image.cols - 1) + c;\n\t\t\tif (cMax >= 0)\n\t\t\t{\n\t\t\t\tif (cMax < canny_image.rows)\n\t\t\t\t{\n\t\t\t\t\t\/\/ (xF, yF) is at the right of the window\n\t\t\t\t\txF = canny_image.cols - 1;\n\t\t\t\t\tyF = static_cast<int>(cMax);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ (xF, yF) is at the bottom of the window\n\t\t\t\t\tyF = canny_image.rows - 1;\n\t\t\t\t\txF = static_cast<int>((yF - c) \/ m);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ (xF, yF) is at the top of the window\n\t\t\t\txF = static_cast<int>(-c \/ m);\n\t\t\t\tyF = 0;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Going through the line using the Bresenham algorithm\n\t\t\/\/ dx1, dx2, dy1 and dy2 are increments that allow to be successful for\n\t\t\/\/ each of the 8 octants (possible directions while iterating)\n\t\tbool onSegment = false;\n\t\tint memory;\n\t\tint memoryX = 0, memoryY = 0;\n\t\tint xPrev = 0, yPrev = 0;\n\t\tsize_t nbPixels = 0;\n\n\t\tint w = xF - x;\n\t\tint h = yF - y;\n\t\tint dx1, dy1, dx2, dy2 = 0;\n\n\t\tint longest, shortest;\n\t\tint numerator;\n\n\t\tif (w < 0)\n\t\t{\n\t\t\tlongest = -w;\n\t\t\tdx1 = -1;\n\t\t\tdx2 = -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlongest = w;\n\t\t\tdx1 = 1;\n\t\t\tdx2 = 1;\n\t\t}\n\n\t\tif (h < 0)\n\t\t{\n\t\t\tshortest = -h;\n\t\t\tdy1 = -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tshortest = h;\n\t\t\tdy1 = 1;\n\t\t}\n\n\t\t\/\/ We want to know whether the direction is more horizontal or vertical,\n\t\t\/\/ and set the increments accordingly\n\t\tif (longest <= shortest)\n\t\t{\n\t\t\tmemory = longest;\n\t\t\tlongest = shortest;\n\t\t\tshortest = memory;\n\t\t\tdx2 = 0;\n\t\t\tif (h < 0)\n\t\t\t{\n\t\t\t\tdy2 = -1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdy2 = 1;\n\t\t\t}\n\t\t}\n\n\t\tnumerator = longest \/ 2;\n\n\t\t\/\/ cout << n << \" numerator \" << numerator << endl;\n\t\tfor (int i(0); i <= longest; ++i)\n\t\t{\n\t\t\t\/\/ For each pixel, we don't want to use a classic \"plot\", but to\n\t\t\t\/\/ look into canny_image for a black or white pixel\n\t\t\tif (onSegment)\n\t\t\t{\n\t\t\t\tif (canny_image.at<char>(y, x) == 0 || i == longest)\n\t\t\t\t{\n\t\t\t\t\t\/\/ We are leaving a segment\n\t\t\t\t\tonSegment = false;\n\t\t\t\t\tif (nbPixels >= threshold)\n\t\t\t\t\t{\n\t\t\t\t\t\tsegments.emplace_back(memoryX, memoryY, xPrev, yPrev);\n\t\t\t\t\t\t\/\/ cout << \"new segment \" << segments.back() << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ We are still on a segment\n\t\t\t\t\t++nbPixels;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (canny_image.at<char>(y, x) != 0)\n\t\t\t{\n\t\t\t\t\/\/ We are entering a segment, and keep this first position in\n\t\t\t\t\/\/ (memoryX, memoryY)\n\t\t\t\tonSegment = true;\n\t\t\t\tnbPixels = 0;\n\t\t\t\tmemoryX = x;\n\t\t\t\tmemoryY = y;\n\t\t\t}\n\n\t\t\t\/\/ xPrev and yPrev are used when leaving a segment, to keep in\n\t\t\t\/\/ memory the last pixel on it\n\t\t\txPrev = x;\n\t\t\tyPrev = y;\n\n\t\t\t\/\/ Next pixel using the condition of the Bresenham algorithm\n\t\t\tnumerator += shortest;\n\t\t\tif (numerator >= longest)\n\t\t\t{\n\t\t\t\tnumerator -= longest;\n\t\t\t\tx += dx1;\n\t\t\t\ty += dy1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx += dx2;\n\t\t\t\ty += dy2;\n\t\t\t}\n\t\t}\n\t}\n}\n#endif\n\nvoid CFeatureLines::extractLines(\n\tconst mrpt::img::CImage& img_in,\n\tstd::vector<std::array<int, 4>>& segments_out, size_t threshold,\n\tconst bool display)\n{\n#if MRPT_HAS_OPENCV\n\n\tusing namespace cv;\n\tusing namespace std;\n\tconst Mat image = img_in.asCvMat<Mat>(mrpt::img::SHALLOW_COPY);\n\n\t\/\/ Canny edge detector\n\tcv::Mat canny_img;\n\tint lowThreshold = 150;\n\t\/\/ int const max_lowThreshold = 100;\n\tint ratio = 3;\n\tint kernel_size = 3;\n\tcv::Canny(\n\t\timage, canny_img, lowThreshold, lowThreshold * ratio,\n\t\tkernel_size); \/\/ 250, 600 \/\/ CAUTION: Both thresholds depend on the\n\t\/\/ input image, they might be a bit hard to set because\n\t\/\/ they depend on the strength of the gradients\n\t\/\/ cv::namedWindow(\"Canny detector\", cv::WINDOW_AUTOSIZE);\n\t\/\/ cv::imshow(\"Canny detector\", canny_img);\n\t\/\/ cv::waitKey(0);\n\t\/\/ cv::destroyWindow(\"Canny detector\");\n\n\t\/\/ Get lines through the Hough transform\n\n\t\/\/ CvMat matCannyStub, *matCannyImg = (CvMat*)canny_img.getAs<IplImage>();\n\t\/\/ CV_CALL(matCannyImg = cvGetMat(canny_img.getAs<IplImage>(),\n\t\/\/ &matCannyStub));\n\n\tstd::vector<cv::Vec2f> lines;\n\tcv::HoughLines(\n\t\tcanny_img, lines, 1, CV_PI \/ 180.0,\n\t\tthreshold); \/\/ CAUTION: The last parameter depends on the input image,\n\t\/\/ it's the smallest number of pixels to consider a line in\n\t\/\/ the accumulator\n\t\/\/ double minLineLength=50, maxLineGap=5;\n\t\/\/ cv::HoughLinesP(canny_img, lines, 1, CV_PI \/ 180.0, threshold,\n\t\/\/ minLineLength, maxLineGap); \/\/ CAUTION: The last parameter depends on\n\t\/\/ the input image, it's the smallest number of pixels to consider a line\n\t\/\/ in the accumulator\n\t\/\/ std::cout << lines.size() << \" lines detected\" << std::endl;\n\n\t\/\/ Possible dilatation of the canny detector\n\t\/\/ Useful when the lines are thin and not perfectly straight\n\tcv::Mat filteredCanny;\n\t\/\/ Choose whether filtering the Canny or not, for thin and non-perfect edges\n\t\/*filteredCanny = canny_img.clone();*\/\n\tcv::dilate(canny_img, filteredCanny, cv::Mat());\n\t\/\/ cv::namedWindow(\"Filtered Canny detector\");\n\t\/\/ cv::imshow(\"Filtered Canny detector\", filteredCanny);\n\t\/\/ cv::waitKey(0);\n\t\/\/ cv::destroyWindow(\"Filtered Canny detector\");\n\n\t\/\/ Extracting segments (pairs of points) from the filtered Canny detector\n\t\/\/ And using the line parameters from lines\n\tstd::vector<cv::Vec4i> segments;\n\textractLines_CannyHough(filteredCanny, lines, segments, threshold);\n\n\t\/\/ Force the segments to have a predefined order (e1y <= e2y)\n\tfor (auto line = begin(segments); line != end(segments); ++line)\n\t\tif ((*line)[1] == (*line)[3])\n\t\t{\n\t\t\tif ((*line)[0] > (*line)[1])\n\t\t\t\t*line =\n\t\t\t\t\tcv::Vec4i((*line)[2], (*line)[3], (*line)[0], (*line)[1]);\n\t\t}\n\t\telse if ((*line)[1] < (*line)[3])\n\t\t\t*line = cv::Vec4i((*line)[2], (*line)[3], (*line)[0], (*line)[1]);\n\n\t\/\/ convert cv->STL:\n\tsegments_out.resize(segments.size());\n\tfor (unsigned i = 0; i < segments.size(); i++)\n\t\tfor (int k = 0; i < 4; k++) segments_out[i][k] = segments[i][k];\n\n\t\/\/ Display 2D segments\n\tif (display)\n\t{\n\t\tcv::Mat image_lines;\n\t\timage.convertTo(image_lines, CV_8UC1, 1.0 \/ 2);\n\t\tfor (auto line = begin(segments); line != end(segments); ++line)\n\t\t{\n\t\t\tcv::line(\n\t\t\t\timage_lines, cv::Point((*line)[0], (*line)[1]),\n\t\t\t\tcv::Point((*line)[2], (*line)[3]), cv::Scalar(255, 0, 255), 1);\n\t\t\tcv::circle(\n\t\t\t\timage_lines, cv::Point((*line)[0], (*line)[1]), 3,\n\t\t\t\tcv::Scalar(255, 0, 255), 3);\n\t\t\tcv::putText(\n\t\t\t\timage_lines, string(to_string(distance(begin(segments), line))),\n\t\t\t\tcv::Point(\n\t\t\t\t\t((*line)[0] + (*line)[2]) \/ 2,\n\t\t\t\t\t((*line)[1] + (*line)[3]) \/ 2),\n\t\t\t\t0, 1.2, cv::Scalar(200, 0, 0), 3);\n\t\t}\n\t\tcv::imshow(\"lines\", image_lines);\n\t\tcv::moveWindow(\"lines\", 20, 100 + 700);\n\t\tcv::waitKey(0);\n\t}\n#else\n\tTHROW_EXCEPTION(\"Requires building MRPT with OpenCV support\");\n#endif\n}\n<commit_msg>Fix obvious CFeatureLines warning<commit_after>\/* +---------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | https:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |\n | See: https:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See details in https:\/\/www.mrpt.org\/License |\n +---------------------------------------------------------------------------+\n *\/\n\n#include \"vision-precomp.h\" \/\/ Precompiled headers\n\n#include <mrpt\/core\/exceptions.h>\n#include <mrpt\/vision\/CFeatureLines.h>\n#include <mrpt\/vision\/utils.h>\n\n\/\/ Universal include for all versions of OpenCV\n#include <mrpt\/otherlibs\/do_opencv_includes.h>\n\nusing namespace mrpt::vision;\nusing namespace std;\n\n#if MRPT_HAS_OPENCV\n\nstatic void extractLines_CannyHough(\n\tconst cv::Mat& canny_image, const std::vector<cv::Vec2f> lines,\n\tstd::vector<cv::Vec4i>& segments, size_t threshold)\n{\n\t\/\/ Some variables to change the coordinate system from polar to cartesian\n\tdouble rho, theta;\n\tdouble cosTheta, sinTheta;\n\tdouble m, c, cMax;\n\n\t\/\/ Variables to define the two extreme points on the line, clipped on the\n\t\/\/ window The constraint is x <= xF\n\tint x, y, xF, yF;\n\n\tsegments.clear();\n\n\t\/\/ For each line\n\tfor (size_t n(0); n < lines.size(); ++n)\n\t{\n\t\t\/\/ OpenCV implements the Hough accumulator with theta from 0 to PI, thus\n\t\t\/\/ rho could be negative We want to always have rho >= 0\n\t\tif (lines[n][0] < 0)\n\t\t{\n\t\t\trho = -lines[n][0];\n\t\t\ttheta = lines[n][1] - CV_PI;\n\t\t}\n\t\telse\n\t\t{\n\t\t\trho = lines[n][0];\n\t\t\ttheta = lines[n][1];\n\t\t}\n\n\t\tif (rho == 0 && theta == 0)\n\t\t{ \/\/ That case appeared at least once, so a test is needed\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Since the step for theta in cv::HoughLines should not be too small,\n\t\t\/\/ theta should exactly be 0 (and the line vertical) when this condition\n\t\t\/\/ is true\n\t\tif (fabs(theta) < 0.00001)\n\t\t{\n\t\t\tx = xF = static_cast<int>(rho + 0.5);\n\t\t\ty = 0;\n\t\t\tyF = canny_image.rows - 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Get the (m, c) slope and y-intercept from (rho, theta), so that y\n\t\t\t\/\/ = mx + c <=> (x, y) is on the line\n\t\t\tcosTheta = cos(theta);\n\t\t\tsinTheta = sin(theta);\n\t\t\tm = -cosTheta \/ sinTheta; \/\/ We are certain that sinTheta != 0\n\t\t\tc = rho * (sinTheta - m * cosTheta);\n\n\t\t\t\/\/ Get the two extreme points (x, y) and (xF, xF) for the line\n\t\t\t\/\/ inside the window, using (m, c)\n\t\t\tif (c >= 0)\n\t\t\t{\n\t\t\t\tif (c < canny_image.rows)\n\t\t\t\t{\n\t\t\t\t\t\/\/ (x, y) is at the left of the window\n\t\t\t\t\tx = 0;\n\t\t\t\t\ty = static_cast<int>(c);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ (x, y) is at the bottom of the window\n\t\t\t\t\ty = canny_image.rows - 1;\n\t\t\t\t\tx = static_cast<int>((y - c) \/ m);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ (x, y) is at the top of the window\n\t\t\t\tx = static_cast<int>(-c \/ m);\n\t\t\t\ty = 0;\n\t\t\t}\n\t\t\t\/\/ Define the intersection with the right side of the window\n\t\t\tcMax = m * (canny_image.cols - 1) + c;\n\t\t\tif (cMax >= 0)\n\t\t\t{\n\t\t\t\tif (cMax < canny_image.rows)\n\t\t\t\t{\n\t\t\t\t\t\/\/ (xF, yF) is at the right of the window\n\t\t\t\t\txF = canny_image.cols - 1;\n\t\t\t\t\tyF = static_cast<int>(cMax);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ (xF, yF) is at the bottom of the window\n\t\t\t\t\tyF = canny_image.rows - 1;\n\t\t\t\t\txF = static_cast<int>((yF - c) \/ m);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ (xF, yF) is at the top of the window\n\t\t\t\txF = static_cast<int>(-c \/ m);\n\t\t\t\tyF = 0;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Going through the line using the Bresenham algorithm\n\t\t\/\/ dx1, dx2, dy1 and dy2 are increments that allow to be successful for\n\t\t\/\/ each of the 8 octants (possible directions while iterating)\n\t\tbool onSegment = false;\n\t\tint memory;\n\t\tint memoryX = 0, memoryY = 0;\n\t\tint xPrev = 0, yPrev = 0;\n\t\tsize_t nbPixels = 0;\n\n\t\tint w = xF - x;\n\t\tint h = yF - y;\n\t\tint dx1, dy1, dx2, dy2 = 0;\n\n\t\tint longest, shortest;\n\t\tint numerator;\n\n\t\tif (w < 0)\n\t\t{\n\t\t\tlongest = -w;\n\t\t\tdx1 = -1;\n\t\t\tdx2 = -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlongest = w;\n\t\t\tdx1 = 1;\n\t\t\tdx2 = 1;\n\t\t}\n\n\t\tif (h < 0)\n\t\t{\n\t\t\tshortest = -h;\n\t\t\tdy1 = -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tshortest = h;\n\t\t\tdy1 = 1;\n\t\t}\n\n\t\t\/\/ We want to know whether the direction is more horizontal or vertical,\n\t\t\/\/ and set the increments accordingly\n\t\tif (longest <= shortest)\n\t\t{\n\t\t\tmemory = longest;\n\t\t\tlongest = shortest;\n\t\t\tshortest = memory;\n\t\t\tdx2 = 0;\n\t\t\tif (h < 0)\n\t\t\t{\n\t\t\t\tdy2 = -1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdy2 = 1;\n\t\t\t}\n\t\t}\n\n\t\tnumerator = longest \/ 2;\n\n\t\t\/\/ cout << n << \" numerator \" << numerator << endl;\n\t\tfor (int i(0); i <= longest; ++i)\n\t\t{\n\t\t\t\/\/ For each pixel, we don't want to use a classic \"plot\", but to\n\t\t\t\/\/ look into canny_image for a black or white pixel\n\t\t\tif (onSegment)\n\t\t\t{\n\t\t\t\tif (canny_image.at<char>(y, x) == 0 || i == longest)\n\t\t\t\t{\n\t\t\t\t\t\/\/ We are leaving a segment\n\t\t\t\t\tonSegment = false;\n\t\t\t\t\tif (nbPixels >= threshold)\n\t\t\t\t\t{\n\t\t\t\t\t\tsegments.emplace_back(memoryX, memoryY, xPrev, yPrev);\n\t\t\t\t\t\t\/\/ cout << \"new segment \" << segments.back() << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ We are still on a segment\n\t\t\t\t\t++nbPixels;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (canny_image.at<char>(y, x) != 0)\n\t\t\t{\n\t\t\t\t\/\/ We are entering a segment, and keep this first position in\n\t\t\t\t\/\/ (memoryX, memoryY)\n\t\t\t\tonSegment = true;\n\t\t\t\tnbPixels = 0;\n\t\t\t\tmemoryX = x;\n\t\t\t\tmemoryY = y;\n\t\t\t}\n\n\t\t\t\/\/ xPrev and yPrev are used when leaving a segment, to keep in\n\t\t\t\/\/ memory the last pixel on it\n\t\t\txPrev = x;\n\t\t\tyPrev = y;\n\n\t\t\t\/\/ Next pixel using the condition of the Bresenham algorithm\n\t\t\tnumerator += shortest;\n\t\t\tif (numerator >= longest)\n\t\t\t{\n\t\t\t\tnumerator -= longest;\n\t\t\t\tx += dx1;\n\t\t\t\ty += dy1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx += dx2;\n\t\t\t\ty += dy2;\n\t\t\t}\n\t\t}\n\t}\n}\n#endif\n\nvoid CFeatureLines::extractLines(\n\tconst mrpt::img::CImage& img_in,\n\tstd::vector<std::array<int, 4>>& segments_out, size_t threshold,\n\tconst bool display)\n{\n#if MRPT_HAS_OPENCV\n\n\tusing namespace cv;\n\tusing namespace std;\n\tconst Mat image = img_in.asCvMat<Mat>(mrpt::img::SHALLOW_COPY);\n\n\t\/\/ Canny edge detector\n\tcv::Mat canny_img;\n\tint lowThreshold = 150;\n\t\/\/ int const max_lowThreshold = 100;\n\tint ratio = 3;\n\tint kernel_size = 3;\n\tcv::Canny(\n\t\timage, canny_img, lowThreshold, lowThreshold * ratio,\n\t\tkernel_size); \/\/ 250, 600 \/\/ CAUTION: Both thresholds depend on the\n\t\/\/ input image, they might be a bit hard to set because\n\t\/\/ they depend on the strength of the gradients\n\t\/\/ cv::namedWindow(\"Canny detector\", cv::WINDOW_AUTOSIZE);\n\t\/\/ cv::imshow(\"Canny detector\", canny_img);\n\t\/\/ cv::waitKey(0);\n\t\/\/ cv::destroyWindow(\"Canny detector\");\n\n\t\/\/ Get lines through the Hough transform\n\n\t\/\/ CvMat matCannyStub, *matCannyImg = (CvMat*)canny_img.getAs<IplImage>();\n\t\/\/ CV_CALL(matCannyImg = cvGetMat(canny_img.getAs<IplImage>(),\n\t\/\/ &matCannyStub));\n\n\tstd::vector<cv::Vec2f> lines;\n\tcv::HoughLines(\n\t\tcanny_img, lines, 1, CV_PI \/ 180.0,\n\t\tthreshold); \/\/ CAUTION: The last parameter depends on the input image,\n\t\/\/ it's the smallest number of pixels to consider a line in\n\t\/\/ the accumulator\n\t\/\/ double minLineLength=50, maxLineGap=5;\n\t\/\/ cv::HoughLinesP(canny_img, lines, 1, CV_PI \/ 180.0, threshold,\n\t\/\/ minLineLength, maxLineGap); \/\/ CAUTION: The last parameter depends on\n\t\/\/ the input image, it's the smallest number of pixels to consider a line\n\t\/\/ in the accumulator\n\t\/\/ std::cout << lines.size() << \" lines detected\" << std::endl;\n\n\t\/\/ Possible dilatation of the canny detector\n\t\/\/ Useful when the lines are thin and not perfectly straight\n\tcv::Mat filteredCanny;\n\t\/\/ Choose whether filtering the Canny or not, for thin and non-perfect edges\n\t\/*filteredCanny = canny_img.clone();*\/\n\tcv::dilate(canny_img, filteredCanny, cv::Mat());\n\t\/\/ cv::namedWindow(\"Filtered Canny detector\");\n\t\/\/ cv::imshow(\"Filtered Canny detector\", filteredCanny);\n\t\/\/ cv::waitKey(0);\n\t\/\/ cv::destroyWindow(\"Filtered Canny detector\");\n\n\t\/\/ Extracting segments (pairs of points) from the filtered Canny detector\n\t\/\/ And using the line parameters from lines\n\tstd::vector<cv::Vec4i> segments;\n\textractLines_CannyHough(filteredCanny, lines, segments, threshold);\n\n\t\/\/ Force the segments to have a predefined order (e1y <= e2y)\n\tfor (auto line = begin(segments); line != end(segments); ++line)\n\t\tif ((*line)[1] == (*line)[3])\n\t\t{\n\t\t\tif ((*line)[0] > (*line)[1])\n\t\t\t\t*line =\n\t\t\t\t\tcv::Vec4i((*line)[2], (*line)[3], (*line)[0], (*line)[1]);\n\t\t}\n\t\telse if ((*line)[1] < (*line)[3])\n\t\t\t*line = cv::Vec4i((*line)[2], (*line)[3], (*line)[0], (*line)[1]);\n\n\t\/\/ convert cv->STL:\n\tsegments_out.resize(segments.size());\n\tfor (unsigned i = 0; i < segments.size(); i++)\n\t\tfor (size_t k = 0; k < segments_out[i].size(); k++) segments_out[i][k] = segments[i][k];\n\n\t\/\/ Display 2D segments\n\tif (display)\n\t{\n\t\tcv::Mat image_lines;\n\t\timage.convertTo(image_lines, CV_8UC1, 1.0 \/ 2);\n\t\tfor (auto line = begin(segments); line != end(segments); ++line)\n\t\t{\n\t\t\tcv::line(\n\t\t\t\timage_lines, cv::Point((*line)[0], (*line)[1]),\n\t\t\t\tcv::Point((*line)[2], (*line)[3]), cv::Scalar(255, 0, 255), 1);\n\t\t\tcv::circle(\n\t\t\t\timage_lines, cv::Point((*line)[0], (*line)[1]), 3,\n\t\t\t\tcv::Scalar(255, 0, 255), 3);\n\t\t\tcv::putText(\n\t\t\t\timage_lines, string(to_string(distance(begin(segments), line))),\n\t\t\t\tcv::Point(\n\t\t\t\t\t((*line)[0] + (*line)[2]) \/ 2,\n\t\t\t\t\t((*line)[1] + (*line)[3]) \/ 2),\n\t\t\t\t0, 1.2, cv::Scalar(200, 0, 0), 3);\n\t\t}\n\t\tcv::imshow(\"lines\", image_lines);\n\t\tcv::moveWindow(\"lines\", 20, 100 + 700);\n\t\tcv::waitKey(0);\n\t}\n#else\n\tTHROW_EXCEPTION(\"Requires building MRPT with OpenCV support\");\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file RotatePath.hpp\n * @brief RotatePath class prototype.\n * @author zer0\n * @date 2017-07-31\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_FILESYSTEM_ROTATEPATH_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_FILESYSTEM_ROTATEPATH_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n#include <libtbag\/Err.hpp>\n#include <libtbag\/Unit.hpp>\n\n#include <libtbag\/debug\/Assert.hpp>\n#include <libtbag\/archive\/Archive.hpp>\n#include <libtbag\/string\/Environments.hpp>\n#include <libtbag\/filesystem\/details\/FsCommon.hpp>\n#include <libtbag\/filesystem\/File.hpp>\n#include <libtbag\/filesystem\/Path.hpp>\n#include <libtbag\/time\/TimePoint.hpp>\n\n#include <cassert>\n#include <string>\n#include <memory>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace filesystem {\n\n\/**\n * Condition check and data writer interface of RotatePath.\n *\n * @author zer0\n * @date 2017-10-21\n *\/\nstruct WriterInterface\n{\n using Err = libtbag::Err;\n\n WriterInterface() { \/* EMPTY. *\/ }\n virtual ~WriterInterface() { \/* EMPTY. *\/ }\n\n virtual bool ready() const = 0;\n virtual bool open(char const * path) = 0;\n virtual void flush() = 0;\n virtual void close() = 0;\n\n \/**\n * Write method.\n *\n * @param[in] buffer\n * If you want a wirte in file, this parameter is the source buffer.\n * @param[in] size\n * If you want a wirte in file, this parameter is the size of source buffer.\n * @param[out] written\n * If the function returns successfully, it returns the size written.\n *\n * @retval E_SUCCESS\n * @retval E_CONTINUE\n *\n * @retval E_EOPEN\n * @retval E_WRERR\n * @retval E_SMALLBUF\n * @retval E_UNKNOWN\n *\/\n virtual Err write(char const * buffer, int size, int * written) = 0;\n};\n\n\/**\n * Maximum file size check and writer.\n *\n * @author zer0\n * @date 2017-10-21\n *\/\nstruct MaxSizeWriter : public WriterInterface\n{\n using File = libtbag::filesystem::File;\n\n TBAG_CONSTEXPR static std::size_t const DEFAULT_MAX_SIZE = 1 * MEGA_BYTE_TO_BYTE;\n\n std::size_t max_size;\n File file;\n\n MaxSizeWriter(std::size_t size = DEFAULT_MAX_SIZE) : max_size(size)\n { \/* EMPTY. *\/ }\n\n virtual ~MaxSizeWriter()\n {\n if (ready()) {\n flush();\n close();\n }\n }\n\n virtual bool ready() const override\n {\n return file.isOpen();\n }\n\n virtual bool open(char const * path) override\n {\n using namespace libtbag::filesystem::details;\n if (file.open(path, File::Flags(FILE_OPEN_FLAG_WRITE_ONLY | FILE_OPEN_CREATE))) {\n file.seek(0);\n return true;\n }\n return false;\n }\n\n virtual void flush() override\n {\n \/\/ EMPTY.\n }\n\n virtual void close() override\n {\n file.close();\n }\n\n virtual Err write(char const * buffer, int size, int * written) override\n {\n assert(buffer != nullptr);\n assert(written != nullptr);\n\n if (!file.isOpen()) {\n return E_OPEN;\n }\n\n if (file.offset() >= max_size) {\n *written = 0;\n return E_SMALLBUF;\n }\n\n assert(file.offset() < max_size);\n auto const MAXIMUM_WRITE_SIZE = file.offset() + size;\n\n if (MAXIMUM_WRITE_SIZE == max_size) {\n *written = file.write(buffer, size);\n if (*written > 0 && *written == size) {\n return E_CONTINUE;\n } else {\n return E_WRERR;\n }\n\n } else if (MAXIMUM_WRITE_SIZE < max_size) {\n *written = file.write(buffer, size);\n if (*written > 0 && *written == size) {\n return E_SUCCESS;\n } else {\n return E_WRERR;\n }\n\n } else {\n assert(MAXIMUM_WRITE_SIZE > max_size);\n assert(max_size > file.offset());\n *written = file.write(buffer, max_size - file.offset());\n if (*written > 0) {\n return E_SMALLBUF;\n } else {\n return E_WRERR;\n }\n }\n\n TBAG_INACCESSIBLE_BLOCK_ASSERT();\n return E_UNKNOWN;\n }\n};\n\n\/**\n * Rules of redefine the path.\n *\n * @author zer0\n * @date 2017-11-20\n *\/\nstruct UpdaterInterface\n{\n UpdaterInterface() { \/* EMPTY. *\/ }\n virtual ~UpdaterInterface() { \/* EMPTY. *\/ }\n\n virtual Path update(Path const & prev) = 0;\n};\n\n\/**\n * Count based updater.\n *\n * @author zer0\n * @date 2017-11-20\n *\/\nstruct CounterUpdater : public UpdaterInterface\n{\n TBAG_CONSTEXPR static char const * const DEFAULT_PREFIX = \"\";\n TBAG_CONSTEXPR static char const * const DEFAULT_SUFFIX = \".log\";\n\n std::string prefix;\n std::string suffix;\n std::size_t count;\n\n CounterUpdater(std::string const & p = DEFAULT_PREFIX, std::string const & s = DEFAULT_SUFFIX, std::size_t c = 0)\n : prefix(p), suffix(s), count(c)\n { \/* EMPTY. *\/ }\n virtual ~CounterUpdater()\n { \/* EMPTY. *\/ }\n\n virtual Path update(Path const & prev) override\n {\n Path next;\n do {\n next = (prefix + std::to_string(count) + suffix);\n count++;\n } while (next.exists());\n return next;\n }\n};\n\n\/**\n * Time based updater.\n *\n * @author zer0\n * @date 2017-11-20\n *\/\nstruct TimeFormatUpdater : public UpdaterInterface\n{\n TBAG_CONSTEXPR static char const * const DEFAULT_TIME_FORMAT_STRING = \"$py$pm$pd_$ph$pi$ps.log\";\n\n std::string format;\n\n TimeFormatUpdater() : format(DEFAULT_TIME_FORMAT_STRING)\n { \/* EMPTY. *\/ }\n TimeFormatUpdater(std::string const & f) : format(f)\n { \/* EMPTY. *\/ }\n virtual ~TimeFormatUpdater()\n { \/* EMPTY. *\/ }\n\n virtual Path update(Path const & prev) override\n {\n return Path(libtbag::time::TimePoint::now().fformat(format));\n }\n\n \/**\n * @remarks\n * <pre>\n * \/prefix\/file.log -> \/prefix\/file-$py$pm$pdT$ph$pi$ps_$pl$pc.log\n * <\/pre>\n *\/\n static std::string getDefaultTimeFormatString(Path const & path)\n {\n std::string const PREFIX = path.getNameWithoutExtension();\n std::string const FORMAT = \"-$py$pm$pdT$ph$pi$ps_$pl$pc\";\n std::string const SUFFIX = path.getExtensionName();\n return (path.getParent() \/ (PREFIX + FORMAT + SUFFIX)).toString();\n }\n};\n\n\/**\n * Cleaning an expired path.\n *\n * @author zer0\n * @date 2019-07-08\n *\/\nstruct CleanerInterface\n{\n CleanerInterface() { \/* EMPTY. *\/ }\n virtual ~CleanerInterface() { \/* EMPTY. *\/ }\n\n virtual void clean(Path const & path) = 0;\n};\n\n\/**\n * Archiving an expired path.\n *\n * @author zer0\n * @date 2019-07-08\n *\/\nstruct ArchiveCleaner : public CleanerInterface\n{\n TBAG_CONSTEXPR static char const * const DEFAULT_ARCHIVE_SUFFIX = \".zip\";\n\n std::string archive_suffix;\n bool remove_source_file;\n\n ArchiveCleaner() : archive_suffix(DEFAULT_ARCHIVE_SUFFIX), remove_source_file(true)\n { \/* EMPTY. *\/ }\n ArchiveCleaner(std::string const & suffix) : archive_suffix(suffix), remove_source_file(true)\n { \/* EMPTY. *\/ }\n ArchiveCleaner(std::string const & suffix, bool remove) : archive_suffix(suffix), remove_source_file(remove)\n { \/* EMPTY. *\/ }\n virtual ~ArchiveCleaner()\n { \/* EMPTY. *\/ }\n\n virtual void clean(Path const & path) override\n {\n using namespace libtbag::archive;\n auto const success_count = compressArchive(path.toString() + archive_suffix,\n { path.toString() },\n getCompressFormatFromOutputFileName(archive_suffix));\n assert(success_count == 1);\n if (remove_source_file) {\n path.remove();\n }\n }\n};\n\n\/**\n * RotatePath class prototype.\n *\n * @author zer0\n * @date 2017-07-31\n *\n * @remarks\n * - absolute time.\n * - file size.\n *\/\nstruct TBAG_API RotatePath\n{\n using Environments = libtbag::string::Environments;\n\n using SharedWriter = std::shared_ptr<WriterInterface>;\n using SharedUpdater = std::shared_ptr<UpdaterInterface>;\n using SharedCleaner = std::shared_ptr<CleanerInterface>;\n\n struct InitParams\n {\n SharedWriter writer;\n SharedUpdater updater;\n SharedCleaner cleaner;\n };\n\n TBAG_CONSTEXPR static char const * const WRITER_KEY_SIZE = \"size\";\n TBAG_CONSTEXPR static char const * const UPDATER_KEY_COUNTER = \"counter\";\n TBAG_CONSTEXPR static char const * const UPDATER_KEY_TIME = \"time\";\n TBAG_CONSTEXPR static char const * const CLEANER_KEY_ARCHIVE = \"archive\";\n\n \/**\n * @remarks\n * Examples:\n * - size and counter: <code>size=1024m counter=\/prefix\/path\/log,.log,0<\/code>\n * - size and time and archive: <code>size=1024m time=\/prefix\/path\/file-$py$pm$pdT$ph$pi$ps.log archive=.zip<\/code>\n *\/\n static InitParams createParams(std::string const & arguments, Environments const & envs);\n static InitParams createParams(std::string const & arguments);\n\n Path path;\n\n SharedWriter writer;\n SharedUpdater updater;\n SharedCleaner cleaner;\n\n RotatePath();\n RotatePath(std::string const & arguments);\n\n explicit RotatePath(InitParams const & params);\n explicit RotatePath(Path const & p, InitParams const & params);\n explicit RotatePath(Path const & p);\n explicit RotatePath(Path const & p, SharedWriter const & w, SharedUpdater const & u);\n explicit RotatePath(SharedWriter const & w, SharedUpdater const & u);\n explicit RotatePath(Path const & p, SharedWriter const & w, SharedUpdater const & u, SharedCleaner const & c);\n explicit RotatePath(SharedWriter const & w, SharedUpdater const & u, SharedCleaner const & c);\n\n ~RotatePath();\n\n inline bool isReady() const TBAG_NOEXCEPT_SPECIFIER(\n TBAG_NOEXCEPT_OPERATOR((bool)writer) &&\n TBAG_NOEXCEPT_OPERATOR((bool)updater))\n { return writer && updater; }\n\n void init(std::string const & args, Environments const & envs);\n void init(std::string const & args);\n\n void update();\n void flush();\n\n Err write(char const * buffer, std::size_t size);\n};\n\n} \/\/ namespace filesystem\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_FILESYSTEM_ROTATEPATH_HPP__\n\n<commit_msg>Update MaxSizeWriter::open() method.<commit_after>\/**\n * @file RotatePath.hpp\n * @brief RotatePath class prototype.\n * @author zer0\n * @date 2017-07-31\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_FILESYSTEM_ROTATEPATH_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_FILESYSTEM_ROTATEPATH_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n#include <libtbag\/Err.hpp>\n#include <libtbag\/Unit.hpp>\n\n#include <libtbag\/debug\/Assert.hpp>\n#include <libtbag\/archive\/Archive.hpp>\n#include <libtbag\/string\/Environments.hpp>\n#include <libtbag\/filesystem\/details\/FsCommon.hpp>\n#include <libtbag\/filesystem\/File.hpp>\n#include <libtbag\/filesystem\/Path.hpp>\n#include <libtbag\/time\/TimePoint.hpp>\n\n#include <cassert>\n#include <string>\n#include <memory>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace filesystem {\n\n\/**\n * Condition check and data writer interface of RotatePath.\n *\n * @author zer0\n * @date 2017-10-21\n *\/\nstruct WriterInterface\n{\n using Err = libtbag::Err;\n\n WriterInterface() { \/* EMPTY. *\/ }\n virtual ~WriterInterface() { \/* EMPTY. *\/ }\n\n virtual bool ready() const = 0;\n virtual bool open(char const * path) = 0;\n virtual void flush() = 0;\n virtual void close() = 0;\n\n \/**\n * Write method.\n *\n * @param[in] buffer\n * If you want a wirte in file, this parameter is the source buffer.\n * @param[in] size\n * If you want a wirte in file, this parameter is the size of source buffer.\n * @param[out] written\n * If the function returns successfully, it returns the size written.\n *\n * @retval E_SUCCESS\n * @retval E_CONTINUE\n *\n * @retval E_EOPEN\n * @retval E_WRERR\n * @retval E_SMALLBUF\n * @retval E_UNKNOWN\n *\/\n virtual Err write(char const * buffer, int size, int * written) = 0;\n};\n\n\/**\n * Maximum file size check and writer.\n *\n * @author zer0\n * @date 2017-10-21\n *\/\nstruct MaxSizeWriter : public WriterInterface\n{\n using File = libtbag::filesystem::File;\n\n TBAG_CONSTEXPR static std::size_t const DEFAULT_MAX_SIZE = 1 * MEGA_BYTE_TO_BYTE;\n\n std::size_t max_size;\n File file;\n\n MaxSizeWriter(std::size_t size = DEFAULT_MAX_SIZE) : max_size(size)\n { \/* EMPTY. *\/ }\n\n virtual ~MaxSizeWriter()\n {\n if (ready()) {\n flush();\n close();\n }\n }\n\n virtual bool ready() const override\n {\n return file.isOpen();\n }\n\n virtual bool open(char const * path) override\n {\n auto const parent = Path(path).getParent();\n if (!parent.exists()) {\n parent.createDir();\n if (!parent.isDirectory()) {\n return false;\n }\n }\n using namespace libtbag::filesystem::details;\n if (file.open(path, File::Flags(FILE_OPEN_FLAG_WRITE_ONLY | FILE_OPEN_CREATE))) {\n file.seek(0);\n return true;\n }\n return false;\n }\n\n virtual void flush() override\n {\n \/\/ EMPTY.\n }\n\n virtual void close() override\n {\n file.close();\n }\n\n virtual Err write(char const * buffer, int size, int * written) override\n {\n assert(buffer != nullptr);\n assert(written != nullptr);\n\n if (!file.isOpen()) {\n return E_OPEN;\n }\n\n if (file.offset() >= max_size) {\n *written = 0;\n return E_SMALLBUF;\n }\n\n assert(file.offset() < max_size);\n auto const MAXIMUM_WRITE_SIZE = file.offset() + size;\n\n if (MAXIMUM_WRITE_SIZE == max_size) {\n *written = file.write(buffer, size);\n if (*written > 0 && *written == size) {\n return E_CONTINUE;\n } else {\n return E_WRERR;\n }\n\n } else if (MAXIMUM_WRITE_SIZE < max_size) {\n *written = file.write(buffer, size);\n if (*written > 0 && *written == size) {\n return E_SUCCESS;\n } else {\n return E_WRERR;\n }\n\n } else {\n assert(MAXIMUM_WRITE_SIZE > max_size);\n assert(max_size > file.offset());\n *written = file.write(buffer, max_size - file.offset());\n if (*written > 0) {\n return E_SMALLBUF;\n } else {\n return E_WRERR;\n }\n }\n\n TBAG_INACCESSIBLE_BLOCK_ASSERT();\n return E_UNKNOWN;\n }\n};\n\n\/**\n * Rules of redefine the path.\n *\n * @author zer0\n * @date 2017-11-20\n *\/\nstruct UpdaterInterface\n{\n UpdaterInterface() { \/* EMPTY. *\/ }\n virtual ~UpdaterInterface() { \/* EMPTY. *\/ }\n\n virtual Path update(Path const & prev) = 0;\n};\n\n\/**\n * Count based updater.\n *\n * @author zer0\n * @date 2017-11-20\n *\/\nstruct CounterUpdater : public UpdaterInterface\n{\n TBAG_CONSTEXPR static char const * const DEFAULT_PREFIX = \"\";\n TBAG_CONSTEXPR static char const * const DEFAULT_SUFFIX = \".log\";\n\n std::string prefix;\n std::string suffix;\n std::size_t count;\n\n CounterUpdater(std::string const & p = DEFAULT_PREFIX, std::string const & s = DEFAULT_SUFFIX, std::size_t c = 0)\n : prefix(p), suffix(s), count(c)\n { \/* EMPTY. *\/ }\n virtual ~CounterUpdater()\n { \/* EMPTY. *\/ }\n\n virtual Path update(Path const & prev) override\n {\n Path next;\n do {\n next = (prefix + std::to_string(count) + suffix);\n count++;\n } while (next.exists());\n return next;\n }\n};\n\n\/**\n * Time based updater.\n *\n * @author zer0\n * @date 2017-11-20\n *\/\nstruct TimeFormatUpdater : public UpdaterInterface\n{\n TBAG_CONSTEXPR static char const * const DEFAULT_TIME_FORMAT_STRING = \"$py$pm$pd_$ph$pi$ps.log\";\n\n std::string format;\n\n TimeFormatUpdater() : format(DEFAULT_TIME_FORMAT_STRING)\n { \/* EMPTY. *\/ }\n TimeFormatUpdater(std::string const & f) : format(f)\n { \/* EMPTY. *\/ }\n virtual ~TimeFormatUpdater()\n { \/* EMPTY. *\/ }\n\n virtual Path update(Path const & prev) override\n {\n return Path(libtbag::time::TimePoint::now().fformat(format));\n }\n\n \/**\n * @remarks\n * <pre>\n * \/prefix\/file.log -> \/prefix\/file-$py$pm$pdT$ph$pi$ps_$pl$pc.log\n * <\/pre>\n *\/\n static std::string getDefaultTimeFormatString(Path const & path)\n {\n std::string const PREFIX = path.getNameWithoutExtension();\n std::string const FORMAT = \"-$py$pm$pdT$ph$pi$ps_$pl$pc\";\n std::string const SUFFIX = path.getExtensionName();\n return (path.getParent() \/ (PREFIX + FORMAT + SUFFIX)).toString();\n }\n};\n\n\/**\n * Cleaning an expired path.\n *\n * @author zer0\n * @date 2019-07-08\n *\/\nstruct CleanerInterface\n{\n CleanerInterface() { \/* EMPTY. *\/ }\n virtual ~CleanerInterface() { \/* EMPTY. *\/ }\n\n virtual void clean(Path const & path) = 0;\n};\n\n\/**\n * Archiving an expired path.\n *\n * @author zer0\n * @date 2019-07-08\n *\/\nstruct ArchiveCleaner : public CleanerInterface\n{\n TBAG_CONSTEXPR static char const * const DEFAULT_ARCHIVE_SUFFIX = \".zip\";\n\n std::string archive_suffix;\n bool remove_source_file;\n\n ArchiveCleaner() : archive_suffix(DEFAULT_ARCHIVE_SUFFIX), remove_source_file(true)\n { \/* EMPTY. *\/ }\n ArchiveCleaner(std::string const & suffix) : archive_suffix(suffix), remove_source_file(true)\n { \/* EMPTY. *\/ }\n ArchiveCleaner(std::string const & suffix, bool remove) : archive_suffix(suffix), remove_source_file(remove)\n { \/* EMPTY. *\/ }\n virtual ~ArchiveCleaner()\n { \/* EMPTY. *\/ }\n\n virtual void clean(Path const & path) override\n {\n using namespace libtbag::archive;\n auto const success_count = compressArchive(path.toString() + archive_suffix,\n { path.toString() },\n getCompressFormatFromOutputFileName(archive_suffix));\n assert(success_count == 1);\n if (remove_source_file) {\n path.remove();\n }\n }\n};\n\n\/**\n * RotatePath class prototype.\n *\n * @author zer0\n * @date 2017-07-31\n *\n * @remarks\n * - absolute time.\n * - file size.\n *\/\nstruct TBAG_API RotatePath\n{\n using Environments = libtbag::string::Environments;\n\n using SharedWriter = std::shared_ptr<WriterInterface>;\n using SharedUpdater = std::shared_ptr<UpdaterInterface>;\n using SharedCleaner = std::shared_ptr<CleanerInterface>;\n\n struct InitParams\n {\n SharedWriter writer;\n SharedUpdater updater;\n SharedCleaner cleaner;\n };\n\n TBAG_CONSTEXPR static char const * const WRITER_KEY_SIZE = \"size\";\n TBAG_CONSTEXPR static char const * const UPDATER_KEY_COUNTER = \"counter\";\n TBAG_CONSTEXPR static char const * const UPDATER_KEY_TIME = \"time\";\n TBAG_CONSTEXPR static char const * const CLEANER_KEY_ARCHIVE = \"archive\";\n\n \/**\n * @remarks\n * Examples:\n * - size and counter: <code>size=1024m counter=\/prefix\/path\/log,.log,0<\/code>\n * - size and time and archive: <code>size=1024m time=\/prefix\/path\/file-$py$pm$pdT$ph$pi$ps.log archive=.zip<\/code>\n *\/\n static InitParams createParams(std::string const & arguments, Environments const & envs);\n static InitParams createParams(std::string const & arguments);\n\n Path path;\n\n SharedWriter writer;\n SharedUpdater updater;\n SharedCleaner cleaner;\n\n RotatePath();\n RotatePath(std::string const & arguments);\n\n explicit RotatePath(InitParams const & params);\n explicit RotatePath(Path const & p, InitParams const & params);\n explicit RotatePath(Path const & p);\n explicit RotatePath(Path const & p, SharedWriter const & w, SharedUpdater const & u);\n explicit RotatePath(SharedWriter const & w, SharedUpdater const & u);\n explicit RotatePath(Path const & p, SharedWriter const & w, SharedUpdater const & u, SharedCleaner const & c);\n explicit RotatePath(SharedWriter const & w, SharedUpdater const & u, SharedCleaner const & c);\n\n ~RotatePath();\n\n inline bool isReady() const TBAG_NOEXCEPT_SPECIFIER(\n TBAG_NOEXCEPT_OPERATOR((bool)writer) &&\n TBAG_NOEXCEPT_OPERATOR((bool)updater))\n { return writer && updater; }\n\n void init(std::string const & args, Environments const & envs);\n void init(std::string const & args);\n\n void update();\n void flush();\n\n Err write(char const * buffer, std::size_t size);\n};\n\n} \/\/ namespace filesystem\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_FILESYSTEM_ROTATEPATH_HPP__\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#pragma once\n\n#include <uavcan\/node\/abstract_node.hpp>\n#include <memory>\n#include \"..\/transport\/can\/can.hpp\"\n\n\nstruct TestNode : public uavcan::INode\n{\n uavcan::PoolAllocator<uavcan::MemPoolBlockSize * 8, uavcan::MemPoolBlockSize> pool;\n uavcan::PoolManager<1> poolmgr;\n uavcan::MarshalBufferProvider<> buffer_provider;\n uavcan::OutgoingTransferRegistry<8> otr;\n uavcan::Scheduler scheduler;\n\n TestNode(uavcan::ICanDriver& can_driver, uavcan::ISystemClock& clock_driver, uavcan::NodeID self_node_id)\n : otr(poolmgr)\n , scheduler(can_driver, poolmgr, clock_driver, otr)\n {\n poolmgr.addPool(&pool);\n setNodeID(self_node_id);\n }\n\n void registerInternalFailure(const char* msg)\n {\n std::cout << \"TestNode internal failure: \" << msg << std::endl;\n }\n\n uavcan::PoolManager<1>& getAllocator() { return poolmgr; }\n uavcan::Scheduler& getScheduler() { return scheduler; }\n const uavcan::Scheduler& getScheduler() const { return scheduler; }\n uavcan::IMarshalBufferProvider& getMarshalBufferProvider() { return buffer_provider; }\n};\n\n\nstruct PairableCanDriver : public uavcan::ICanDriver, public uavcan::ICanIface\n{\n uavcan::ISystemClock& clock;\n PairableCanDriver* other;\n std::queue<uavcan::CanFrame> read_queue;\n\n PairableCanDriver(uavcan::ISystemClock& clock)\n : clock(clock)\n , other(NULL)\n { }\n\n void linkTogether(PairableCanDriver* with)\n {\n this->other = with;\n with->other = this;\n }\n\n uavcan::ICanIface* getIface(int iface_index)\n {\n if (iface_index == 0)\n return this;\n return NULL;\n }\n\n int getNumIfaces() const { return 1; }\n\n int select(int& inout_write_iface_mask, int& inout_read_iface_mask, uavcan::MonotonicTime blocking_deadline)\n {\n assert(other);\n if (inout_read_iface_mask == 1)\n inout_read_iface_mask = read_queue.size() ? 1 : 0;\n\n if (inout_read_iface_mask || inout_write_iface_mask)\n return 1;\n\n while (clock.getMonotonic() < blocking_deadline)\n usleep(1000);\n\n return 0;\n }\n\n int send(const uavcan::CanFrame& frame, uavcan::MonotonicTime)\n {\n assert(other);\n other->read_queue.push(frame);\n return 1;\n }\n\n int receive(uavcan::CanFrame& out_frame, uavcan::MonotonicTime& out_ts_monotonic, uavcan::UtcTime& out_ts_utc)\n {\n assert(other);\n assert(read_queue.size());\n out_frame = read_queue.front();\n read_queue.pop();\n out_ts_monotonic = clock.getMonotonic();\n out_ts_utc = clock.getUtc();\n return 1;\n }\n\n int configureFilters(const uavcan::CanFilterConfig*, int) { return -1; }\n int getNumFilters() const { return 0; }\n uint64_t getNumErrors() const { return 0; }\n};\n\n\nstruct InterlinkedTestNodes\n{\n SystemClockDriver clock;\n PairableCanDriver can_a;\n PairableCanDriver can_b;\n TestNode a;\n TestNode b;\n\n InterlinkedTestNodes(uavcan::NodeID nid_first, uavcan::NodeID nid_second)\n : can_a(clock)\n , can_b(clock)\n , a(can_a, clock, nid_first)\n , b(can_b, clock, nid_second)\n {\n can_a.linkTogether(&can_b);\n }\n\n InterlinkedTestNodes()\n : can_a(clock)\n , can_b(clock)\n , a(can_a, clock, 1)\n , b(can_b, clock, 2)\n {\n can_a.linkTogether(&can_b);\n }\n\n int spinBoth(uavcan::MonotonicDuration duration)\n {\n const uavcan::MonotonicDuration duration_per_node = duration * 0.5;\n const int ret = a.spin(duration_per_node);\n if (ret < 0)\n return ret;\n return b.spin(duration_per_node);\n }\n};\n<commit_msg>Tests: fixed spin() for InterlinkedTestNodes<commit_after>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#pragma once\n\n#include <uavcan\/node\/abstract_node.hpp>\n#include <memory>\n#include \"..\/transport\/can\/can.hpp\"\n\n\nstruct TestNode : public uavcan::INode\n{\n uavcan::PoolAllocator<uavcan::MemPoolBlockSize * 8, uavcan::MemPoolBlockSize> pool;\n uavcan::PoolManager<1> poolmgr;\n uavcan::MarshalBufferProvider<> buffer_provider;\n uavcan::OutgoingTransferRegistry<8> otr;\n uavcan::Scheduler scheduler;\n\n TestNode(uavcan::ICanDriver& can_driver, uavcan::ISystemClock& clock_driver, uavcan::NodeID self_node_id)\n : otr(poolmgr)\n , scheduler(can_driver, poolmgr, clock_driver, otr)\n {\n poolmgr.addPool(&pool);\n setNodeID(self_node_id);\n }\n\n void registerInternalFailure(const char* msg)\n {\n std::cout << \"TestNode internal failure: \" << msg << std::endl;\n }\n\n uavcan::PoolManager<1>& getAllocator() { return poolmgr; }\n uavcan::Scheduler& getScheduler() { return scheduler; }\n const uavcan::Scheduler& getScheduler() const { return scheduler; }\n uavcan::IMarshalBufferProvider& getMarshalBufferProvider() { return buffer_provider; }\n};\n\n\nstruct PairableCanDriver : public uavcan::ICanDriver, public uavcan::ICanIface\n{\n uavcan::ISystemClock& clock;\n PairableCanDriver* other;\n std::queue<uavcan::CanFrame> read_queue;\n\n PairableCanDriver(uavcan::ISystemClock& clock)\n : clock(clock)\n , other(NULL)\n { }\n\n void linkTogether(PairableCanDriver* with)\n {\n this->other = with;\n with->other = this;\n }\n\n uavcan::ICanIface* getIface(int iface_index)\n {\n if (iface_index == 0)\n return this;\n return NULL;\n }\n\n int getNumIfaces() const { return 1; }\n\n int select(int& inout_write_iface_mask, int& inout_read_iface_mask, uavcan::MonotonicTime blocking_deadline)\n {\n assert(other);\n if (inout_read_iface_mask == 1)\n inout_read_iface_mask = read_queue.size() ? 1 : 0;\n\n if (inout_read_iface_mask || inout_write_iface_mask)\n return 1;\n\n while (clock.getMonotonic() < blocking_deadline)\n usleep(1000);\n\n return 0;\n }\n\n int send(const uavcan::CanFrame& frame, uavcan::MonotonicTime)\n {\n assert(other);\n other->read_queue.push(frame);\n return 1;\n }\n\n int receive(uavcan::CanFrame& out_frame, uavcan::MonotonicTime& out_ts_monotonic, uavcan::UtcTime& out_ts_utc)\n {\n assert(other);\n assert(read_queue.size());\n out_frame = read_queue.front();\n read_queue.pop();\n out_ts_monotonic = clock.getMonotonic();\n out_ts_utc = clock.getUtc();\n return 1;\n }\n\n int configureFilters(const uavcan::CanFilterConfig*, int) { return -1; }\n int getNumFilters() const { return 0; }\n uint64_t getNumErrors() const { return 0; }\n};\n\n\nstruct InterlinkedTestNodes\n{\n SystemClockDriver clock;\n PairableCanDriver can_a;\n PairableCanDriver can_b;\n TestNode a;\n TestNode b;\n\n InterlinkedTestNodes(uavcan::NodeID nid_first, uavcan::NodeID nid_second)\n : can_a(clock)\n , can_b(clock)\n , a(can_a, clock, nid_first)\n , b(can_b, clock, nid_second)\n {\n can_a.linkTogether(&can_b);\n }\n\n InterlinkedTestNodes()\n : can_a(clock)\n , can_b(clock)\n , a(can_a, clock, 1)\n , b(can_b, clock, 2)\n {\n can_a.linkTogether(&can_b);\n }\n\n int spinBoth(uavcan::MonotonicDuration duration)\n {\n assert(duration.isPositive());\n unsigned int nspins2 = duration.toMSec() \/ 2 + 1;\n assert(nspins2 > 0);\n while (nspins2 --> 0)\n {\n int ret = -1;\n ret = a.spin(uavcan::MonotonicDuration::fromMSec(1));\n if (ret < 0)\n return ret;\n ret = b.spin(uavcan::MonotonicDuration::fromMSec(1));\n if (ret < 0)\n return ret;\n }\n return 0;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"IndexWriter.h\"\n#include <fnord-fts\/AnalyzerAdapter.h>\n\nusing namespace fnord;\n\nnamespace cm {\n\nRefPtr<IndexWriter> IndexWriter::openIndex(\n const String& index_path,\n const String& conf_path) {\n if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {\n RAISEF(kIllegalArgumentError, \"invalid index path: $0\", index_path);\n }\n\n \/* set up feature schema *\/\n FeatureSchema feature_schema;\n feature_schema.registerFeature(\"shop_id\", 1, 1);\n feature_schema.registerFeature(\"category1\", 2, 1);\n feature_schema.registerFeature(\"category2\", 3, 1);\n feature_schema.registerFeature(\"category3\", 4, 1);\n feature_schema.registerFeature(\"title~de\", 5, 2);\n\n \/* open mdb *\/\n auto db_path = FileUtil::joinPaths(index_path, \"db\");\n FileUtil::mkdir_p(db_path);\n auto db = mdb::MDB::open(db_path);\n db->setMaxSize(1000000 * 512000);\n\n \/* open docs store *\/\n auto docs_path = FileUtil::joinPaths(index_path, \"docs\");\n FileUtil::mkdir_p(docs_path);\n RefPtr<DocStore> docs(new DocStore(docs_path));\n\n \/* open lucene *\/\n RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));\n auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);\n\n auto fts_path = FileUtil::joinPaths(index_path, \"fts\");\n auto fts =\n fts::newLucene<fts::IndexWriter>(\n fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),\n adapter,\n true,\n fts::IndexWriter::MaxFieldLengthLIMITED);\n\n return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, docs, fts));\n}\n\nIndexWriter::IndexWriter(\n FeatureSchema schema,\n RefPtr<mdb::MDB> db,\n RefPtr<DocStore> docs,\n std::shared_ptr<fts::IndexWriter> fts) :\n schema_(schema),\n db_(db),\n db_txn_(db_->startTransaction()),\n feature_idx_(new FeatureIndexWriter(&schema_)),\n fts_(fts) {}\n\n\nIndexWriter::~IndexWriter() {\n if (db_txn_.get()) {\n db_txn_->commit();\n }\n\n fts_->close();\n}\n\nvoid IndexWriter::updateDocument(const IndexRequest& index_request) {\n stat_documents_indexed_total_.incr(1);\n auto docid = index_request.item.docID();\n feature_idx_->updateDocument(index_request, db_txn_.get());\n auto doc = feature_idx_->findDocument(docid, db_txn_.get());\n rebuildFTS(doc);\n stat_documents_indexed_success_.incr(1);\n}\n\nvoid IndexWriter::commit() {\n db_txn_->commit();\n db_txn_ = db_->startTransaction();\n fts_->commit();\n}\n\nvoid IndexWriter::rebuildFTS(DocID docid) {\n auto doc = feature_idx_->findDocument(docid, db_txn_.get());\n rebuildFTS(doc);\n}\n\nvoid IndexWriter::rebuildFTS(RefPtr<Document> doc) {\n stat_documents_indexed_fts_.incr(1);\n auto fts_doc = fts::newLucene<fts::Document>();\n\n fnord::logDebug(\n \"cm.indexwriter\",\n \"Rebuilding FTS Index for docid=$0\",\n doc->docID().docid);\n\n HashMap<String, String> fts_fields_anal;\n for (const auto& f : doc->fields()) {\n\n \/* title~LANG *\/\n if (StringUtil::beginsWith(f.first, \"title~\")) {\n auto k = f.first;\n StringUtil::replaceAll(&k, \"title~\",\"title~\");\n fts_fields_anal[k] += \" \";\n fts_fields_anal[k] += f.second;\n }\n\n \/* description~LANG *\/\n if (StringUtil::beginsWith(f.first, \"description~\")) {\n auto k = f.first;\n StringUtil::replaceAll(&k, \"description~\",\"text~\");\n fts_fields_anal[k] += \" \";\n fts_fields_anal[k] += f.second;\n }\n\n \/* tags_as_text~LANG *\/\n if (StringUtil::beginsWith(f.first, \"tags_as_text~\")) {\n auto k = f.first;\n StringUtil::replaceAll(&k, \"tags_as_text~\",\"text~\");\n fts_fields_anal[k] += \" \";\n fts_fields_anal[k] += f.second;\n }\n\n }\n\n fts_doc->add(\n fts::newLucene<fts::Field>(\n L\"docid\",\n StringUtil::convertUTF8To16(doc->docID().docid),\n fts::Field::STORE_YES,\n fts::Field::INDEX_NO));\n\n for (const auto& f : fts_fields_anal) {\n fts_doc->add(\n fts::newLucene<fts::Field>(\n StringUtil::convertUTF8To16(f.first),\n StringUtil::convertUTF8To16(f.second),\n fts::Field::STORE_NO,\n fts::Field::INDEX_ANALYZED));\n }\n\n fts_->addDocument(fts_doc);\n}\n\nvoid IndexWriter::rebuildFTS() {\n \/\/docs_->listDocuments([this] (const DocID& docid) -> bool {\n \/\/ rebuildFTS(docid);\n \/\/ return true;\n \/\/});\n}\n\nRefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {\n return db_txn_;\n}\n\nvoid IndexWriter::exportStats(const String& prefix) {\n exportStat(\n StringUtil::format(\"$0\/documents_indexed_total\", prefix),\n &stat_documents_indexed_total_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n StringUtil::format(\"$0\/documents_indexed_success\", prefix),\n &stat_documents_indexed_success_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n StringUtil::format(\"$0\/documents_indexed_error\", prefix),\n &stat_documents_indexed_error_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n StringUtil::format(\"$0\/documents_indexed_fts\", prefix),\n &stat_documents_indexed_fts_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n}\n\n\n} \/\/ namespace cm\n<commit_msg>full index schema<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"IndexWriter.h\"\n#include <fnord-fts\/AnalyzerAdapter.h>\n\nusing namespace fnord;\n\nnamespace cm {\n\nRefPtr<IndexWriter> IndexWriter::openIndex(\n const String& index_path,\n const String& conf_path) {\n if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {\n RAISEF(kIllegalArgumentError, \"invalid index path: $0\", index_path);\n }\n\n \/* set up feature schema *\/\n FeatureSchema feature_schema;\n feature_schema.registerFeature(\"shop_id\", 1, 1);\n feature_schema.registerFeature(\"category1\", 2, 1);\n feature_schema.registerFeature(\"category2\", 3, 1);\n feature_schema.registerFeature(\"category3\", 4, 1);\n feature_schema.registerFeature(\"price_cents\", 8, 1);\n\n feature_schema.registerFeature(\"title~de\", 5, 2);\n feature_schema.registerFeature(\"description~de\", 6, 2);\n feature_schema.registerFeature(\"tags_as_text~de\", 7, 2);\n\n feature_schema.registerFeature(\"shop_rating_alt\", 9, 3);\n feature_schema.registerFeature(\"shop_products_count\", 10, 3);\n feature_schema.registerFeature(\"shop_orders_count\", 11, 3);\n feature_schema.registerFeature(\"shop_rating_count\", 12, 3);\n feature_schema.registerFeature(\"shop_rating_avg\", 13, 3);\n\n \/* open mdb *\/\n auto db_path = FileUtil::joinPaths(index_path, \"db\");\n FileUtil::mkdir_p(db_path);\n auto db = mdb::MDB::open(db_path);\n db->setMaxSize(1000000 * 512000);\n\n \/* open docs store *\/\n auto docs_path = FileUtil::joinPaths(index_path, \"docs\");\n FileUtil::mkdir_p(docs_path);\n RefPtr<DocStore> docs(new DocStore(docs_path));\n\n \/* open lucene *\/\n RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));\n auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);\n\n auto fts_path = FileUtil::joinPaths(index_path, \"fts\");\n auto fts =\n fts::newLucene<fts::IndexWriter>(\n fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),\n adapter,\n true,\n fts::IndexWriter::MaxFieldLengthLIMITED);\n\n return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, docs, fts));\n}\n\nIndexWriter::IndexWriter(\n FeatureSchema schema,\n RefPtr<mdb::MDB> db,\n RefPtr<DocStore> docs,\n std::shared_ptr<fts::IndexWriter> fts) :\n schema_(schema),\n db_(db),\n db_txn_(db_->startTransaction()),\n feature_idx_(new FeatureIndexWriter(&schema_)),\n fts_(fts) {}\n\n\nIndexWriter::~IndexWriter() {\n if (db_txn_.get()) {\n db_txn_->commit();\n }\n\n fts_->close();\n}\n\nvoid IndexWriter::updateDocument(const IndexRequest& index_request) {\n stat_documents_indexed_total_.incr(1);\n auto docid = index_request.item.docID();\n feature_idx_->updateDocument(index_request, db_txn_.get());\n auto doc = feature_idx_->findDocument(docid, db_txn_.get());\n rebuildFTS(doc);\n stat_documents_indexed_success_.incr(1);\n}\n\nvoid IndexWriter::commit() {\n db_txn_->commit();\n db_txn_ = db_->startTransaction();\n fts_->commit();\n}\n\nvoid IndexWriter::rebuildFTS(DocID docid) {\n auto doc = feature_idx_->findDocument(docid, db_txn_.get());\n rebuildFTS(doc);\n}\n\nvoid IndexWriter::rebuildFTS(RefPtr<Document> doc) {\n stat_documents_indexed_fts_.incr(1);\n auto fts_doc = fts::newLucene<fts::Document>();\n\n fnord::logDebug(\n \"cm.indexwriter\",\n \"Rebuilding FTS Index for docid=$0\",\n doc->docID().docid);\n\n HashMap<String, String> fts_fields_anal;\n for (const auto& f : doc->fields()) {\n\n \/* title~LANG *\/\n if (StringUtil::beginsWith(f.first, \"title~\")) {\n auto k = f.first;\n StringUtil::replaceAll(&k, \"title~\",\"title~\");\n fts_fields_anal[k] += \" \";\n fts_fields_anal[k] += f.second;\n }\n\n \/* description~LANG *\/\n if (StringUtil::beginsWith(f.first, \"description~\")) {\n auto k = f.first;\n StringUtil::replaceAll(&k, \"description~\",\"text~\");\n fts_fields_anal[k] += \" \";\n fts_fields_anal[k] += f.second;\n }\n\n \/* tags_as_text~LANG *\/\n if (StringUtil::beginsWith(f.first, \"tags_as_text~\")) {\n auto k = f.first;\n StringUtil::replaceAll(&k, \"tags_as_text~\",\"text~\");\n fts_fields_anal[k] += \" \";\n fts_fields_anal[k] += f.second;\n }\n\n }\n\n fts_doc->add(\n fts::newLucene<fts::Field>(\n L\"docid\",\n StringUtil::convertUTF8To16(doc->docID().docid),\n fts::Field::STORE_YES,\n fts::Field::INDEX_NO));\n\n for (const auto& f : fts_fields_anal) {\n fts_doc->add(\n fts::newLucene<fts::Field>(\n StringUtil::convertUTF8To16(f.first),\n StringUtil::convertUTF8To16(f.second),\n fts::Field::STORE_NO,\n fts::Field::INDEX_ANALYZED));\n }\n\n fts_->addDocument(fts_doc);\n}\n\nvoid IndexWriter::rebuildFTS() {\n \/\/docs_->listDocuments([this] (const DocID& docid) -> bool {\n \/\/ rebuildFTS(docid);\n \/\/ return true;\n \/\/});\n}\n\nRefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {\n return db_txn_;\n}\n\nvoid IndexWriter::exportStats(const String& prefix) {\n exportStat(\n StringUtil::format(\"$0\/documents_indexed_total\", prefix),\n &stat_documents_indexed_total_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n StringUtil::format(\"$0\/documents_indexed_success\", prefix),\n &stat_documents_indexed_success_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n StringUtil::format(\"$0\/documents_indexed_error\", prefix),\n &stat_documents_indexed_error_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n StringUtil::format(\"$0\/documents_indexed_fts\", prefix),\n &stat_documents_indexed_fts_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n}\n\n\n} \/\/ namespace cm\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Part of tivars_lib_cpp\n * (C) 2015-2019 Adrien \"Adriweb\" Bertrand\n * https:\/\/github.com\/adriweb\/tivars_lib_cpp\n * License: MIT\n *\/\n\n#include \"TypeHandlers.h\"\n#include \"..\/utils.h\"\n#include <unordered_map>\n#include <iostream>\n#include <iterator>\n#include <regex>\n#include <fstream>\n\nnamespace tivars\n{\n namespace TH_Tokenized\n {\n std::unordered_map<uint, std::vector<std::string>> tokens_BytesToName;\n std::unordered_map<std::string, uint> tokens_NameToBytes;\n uchar lengthOfLongestTokenName;\n std::vector<uchar> firstByteOfTwoByteTokens;\n const uint16_t squishedASMTokens[] = { 0xBB6D, 0xEF69, 0xEF7B }; \/\/ 83+\/84+, 84+CSE, CE\n }\n\n \/* TODO: handle TI-Innovator Send( exception for in-strings tokenization (=> not shortest tokens) *\/\n data_t TH_Tokenized::makeDataFromString(const std::string& str, const options_t& options)\n {\n (void)options;\n data_t data;\n\n \/\/ two bytes reserved for the size. Filled later\n data.push_back(0); data.push_back(0);\n\n const uchar maxTokSearchLen = std::min((uchar)str.length(), lengthOfLongestTokenName);\n\n bool isWithinString = false;\n\n for (uint strCursorPos = 0; strCursorPos < str.length(); strCursorPos++)\n {\n const std::string currChar = str.substr(strCursorPos, 1);\n if (currChar == \"\\\"\")\n {\n isWithinString = !isWithinString;\n } else if (currChar == \"\\n\" || currChar == \"→\")\n {\n isWithinString = false;\n }\n \/* isWithinString => minimum token length, otherwise maximal munch *\/\n for (uint currentLength = isWithinString ? 1 : maxTokSearchLen;\n isWithinString ? (currentLength <= maxTokSearchLen) : (currentLength > 0);\n currentLength += (isWithinString ? 1 : -1))\n {\n std::string currentSubString = str.substr(strCursorPos, currentLength);\n if (tokens_NameToBytes.count(currentSubString))\n {\n uint tokenValue = tokens_NameToBytes[currentSubString];\n if (tokenValue > 0xFF)\n {\n data.push_back((uchar)(tokenValue >> 8));\n }\n data.push_back((uchar)(tokenValue & 0xFF));\n strCursorPos += currentLength - 1;\n break;\n }\n }\n }\n\n uint actualDataLen = (uint) (data.size() - 2);\n data[0] = (uchar)(actualDataLen & 0xFF);\n data[1] = (uchar)((actualDataLen >> 8) & 0xFF);\n return data;\n }\n\n std::string TH_Tokenized::makeStringFromData(const data_t& data, const options_t& options)\n {\n const size_t dataSize = data.size();\n if (dataSize < 2)\n {\n throw std::invalid_argument(\"Invalid data array. Needs to contain at least 2 bytes (size fields)\");\n }\n\n uint langIdx = (uint)((has_option(options, \"lang\") && options.at(\"lang\") == LANG_FR) ? LANG_FR : LANG_EN);\n\n const int howManyBytes = (data[0] & 0xFF) + ((data[1] & 0xFF) << 8);\n if (howManyBytes != (int)dataSize - 2)\n {\n std::cerr << \"[Warning] Byte count (\" << (dataSize - 2) << \") and size field (\" << howManyBytes << \") mismatch!\";\n }\n\n if (howManyBytes >= 2 && dataSize >= 4)\n {\n const uint16_t twoFirstBytes = (uint16_t) ((data[3] & 0xFF) + ((data[2] & 0xFF) << 8));\n if (std::find(std::begin(squishedASMTokens), std::end(squishedASMTokens), twoFirstBytes) != std::end(squishedASMTokens))\n {\n return \"[Error] This is a squished ASM program - cannnot preview it!\";\n }\n }\n\n uint errCount = 0;\n std::string str;\n for (uint i = 2; i < (uint)dataSize; i++)\n {\n uint currentToken = data[i];\n uint nextToken = (i < dataSize-1) ? data[i+1] : (uint)-1;\n uint bytesKey = currentToken;\n if (is_in_vector(firstByteOfTwoByteTokens, (uchar)currentToken))\n {\n if (nextToken == (uint)-1)\n {\n std::cerr << \"[Warning] Encountered an unfinished two-byte token! Setting the second byte to 0x00\";\n nextToken = 0x00;\n }\n bytesKey = nextToken + (currentToken << 8);\n i++;\n }\n if (tokens_BytesToName.find(bytesKey) != tokens_BytesToName.end())\n {\n str += tokens_BytesToName[bytesKey][langIdx];\n } else {\n str += \" [???] \";\n errCount++;\n }\n }\n\n if (errCount > 0)\n {\n std::cerr << \"[Warning] \" << errCount << \" token(s) could not be detokenized (' [???] ' was used)!\";\n }\n\n if (has_option(options, \"prettify\") && options.at(\"prettify\") == 1)\n {\n str = std::regex_replace(str, std::regex(R\"(\\[?\\|?([a-z]+)\\]?)\"), \"$1\");\n }\n\n if (has_option(options, \"reindent\") && options.at(\"reindent\") == 1)\n {\n str = reindentCodeString(str);\n }\n\n return str;\n }\n\n std::string TH_Tokenized::reindentCodeString(const std::string& str_orig, const options_t& options)\n {\n int lang;\n if (has_option(options, \"lang\"))\n {\n lang = options.at(\"lang\");\n } else if (str_orig.size() > 1 && str_orig[0] == '.' && (str_orig[1] == '.' || ::isalpha(str_orig[1]))) {\n lang = PRGMLANG_AXE;\n } else if (str_orig.substr(0, sizeof(\"\\U0001D456\") - 1) == \"\\U0001D456\") {\n lang = PRGMLANG_ICE;\n } else {\n lang = PRGMLANG_BASIC;\n }\n\n std::string str(str_orig);\n\n str = std::regex_replace(str, std::regex(\"([^\\\\s])(Del|Eff)Var \"), \"$1\\n$2Var \");\n\n std::vector<std::string> lines_tmp = explode(str, '\\n');\n\n \/\/ Inplace-replace the appropriate \":\" by new-line chars (ie, by inserting the split string in the lines_tmp array)\n for (uint16_t idx = 0; idx < (uint16_t)lines_tmp.size(); idx++)\n {\n const auto line = lines_tmp[idx];\n bool isWithinString = false;\n for (uint16_t strIdx = 0; strIdx < (uint16_t)line.size(); strIdx++)\n {\n const auto currChar = line.substr(strIdx, 1);\n if (currChar == \":\" && !isWithinString)\n {\n lines_tmp[idx] = line.substr(0, strIdx); \/\/ replace \"old\" line by lhs\n lines_tmp.insert(lines_tmp.begin() + idx + 1, line.substr(strIdx + 1)); \/\/ inserting rhs\n break;\n } else if (currChar == \"\\\"\") {\n isWithinString = !isWithinString;\n } else if (currChar == \"\\n\" || currChar == \"→\") {\n isWithinString = false;\n }\n }\n }\n\n std::vector<std::pair<uint, std::string>> lines(lines_tmp.size()); \/\/ indent, text\n for (const auto& line : lines_tmp)\n {\n lines.emplace_back(0, line);\n }\n\n std::vector<std::string> increaseIndentAfter = { \"If\", \"For\", \"While\", \"Repeat\" };\n std::vector<std::string> decreaseIndentOfToken = { \"Then\", \"Else\", \"End\", \"ElseIf\", \"EndIf\", \"End!If\" };\n std::vector<std::string> closingTokens = { \"End\", \"EndIf\", \"End!If\" };\n uint nextIndent = 0;\n std::string oldFirstCommand, firstCommand;\n for (auto& line : lines)\n {\n oldFirstCommand = firstCommand;\n\n std::string trimmedLine = trim(line.second);\n if (trimmedLine.length() > 0) {\n char* trimmedLine_c = (char*) trimmedLine.c_str();\n firstCommand = strtok(trimmedLine_c, \" \");\n firstCommand = trim(firstCommand);\n trimmedLine = std::string(trimmedLine_c);\n trimmedLine_c = (char*) trimmedLine.c_str();\n if (firstCommand == trimmedLine)\n {\n firstCommand = strtok(trimmedLine_c, \"(\");\n firstCommand = trim(firstCommand);\n }\n } else {\n firstCommand = \"\";\n }\n\n line.first = nextIndent;\n\n if (is_in_vector(increaseIndentAfter, firstCommand))\n {\n nextIndent++;\n }\n if (line.first > 0 && is_in_vector(decreaseIndentOfToken, firstCommand))\n {\n line.first--;\n }\n if (nextIndent > 0 && (is_in_vector(closingTokens, firstCommand) || (oldFirstCommand == \"If\" && firstCommand != \"Then\" && lang != PRGMLANG_AXE && lang != PRGMLANG_ICE)))\n {\n nextIndent--;\n }\n }\n\n str = \"\";\n for (const auto& line : lines)\n {\n str += str_repeat(\" \", line.first * 3) + line.second + '\\n';\n }\n\n return ltrim(rtrim(str, \"\\t\\n\\r\\f\\v\"));\n }\n\n void TH_Tokenized::initTokens()\n {\n std::ifstream t(\"programs_tokens.csv\");\n std::string csvFileStr((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());\n\n if (csvFileStr.length() > 0)\n {\n std::vector<std::vector<std::string>> lines;\n ParseCSV(csvFileStr, lines);\n\n for (const auto& tokenInfo : lines)\n {\n uint bytes;\n if (tokenInfo[6] == \"2\") \/\/ number of bytes for the token\n {\n if (!is_in_vector(firstByteOfTwoByteTokens, hexdec(tokenInfo[7])))\n {\n firstByteOfTwoByteTokens.push_back(hexdec(tokenInfo[7]));\n }\n bytes = hexdec(tokenInfo[8]) + (hexdec(tokenInfo[7]) << 8);\n } else {\n bytes = hexdec(tokenInfo[7]);\n }\n tokens_BytesToName[bytes] = { tokenInfo[4], tokenInfo[5] }; \/\/ EN, FR\n tokens_NameToBytes[tokenInfo[4]] = bytes; \/\/ EN\n tokens_NameToBytes[tokenInfo[5]] = bytes; \/\/ FR\n uchar maxLenName = (uchar) std::max(tokenInfo[4].length(), tokenInfo[5].length());\n if (maxLenName > lengthOfLongestTokenName)\n {\n lengthOfLongestTokenName = maxLenName;\n }\n }\n } else {\n throw std::runtime_error(\"Could not open the tokens csv file\");\n }\n }\n\n}\n<commit_msg>[TH_Tokenized::makeStringFromData] fromRawBytes option<commit_after>\/*\n * Part of tivars_lib_cpp\n * (C) 2015-2019 Adrien \"Adriweb\" Bertrand\n * https:\/\/github.com\/adriweb\/tivars_lib_cpp\n * License: MIT\n *\/\n\n#include \"TypeHandlers.h\"\n#include \"..\/utils.h\"\n#include <unordered_map>\n#include <iostream>\n#include <iterator>\n#include <regex>\n#include <fstream>\n\nnamespace tivars\n{\n namespace TH_Tokenized\n {\n std::unordered_map<uint, std::vector<std::string>> tokens_BytesToName;\n std::unordered_map<std::string, uint> tokens_NameToBytes;\n uchar lengthOfLongestTokenName;\n std::vector<uchar> firstByteOfTwoByteTokens;\n const uint16_t squishedASMTokens[] = { 0xBB6D, 0xEF69, 0xEF7B }; \/\/ 83+\/84+, 84+CSE, CE\n }\n\n \/* TODO: handle TI-Innovator Send( exception for in-strings tokenization (=> not shortest tokens) *\/\n data_t TH_Tokenized::makeDataFromString(const std::string& str, const options_t& options)\n {\n (void)options;\n data_t data;\n\n \/\/ two bytes reserved for the size. Filled later\n data.push_back(0); data.push_back(0);\n\n const uchar maxTokSearchLen = std::min((uchar)str.length(), lengthOfLongestTokenName);\n\n bool isWithinString = false;\n\n for (uint strCursorPos = 0; strCursorPos < str.length(); strCursorPos++)\n {\n const std::string currChar = str.substr(strCursorPos, 1);\n if (currChar == \"\\\"\")\n {\n isWithinString = !isWithinString;\n } else if (currChar == \"\\n\" || currChar == \"→\")\n {\n isWithinString = false;\n }\n \/* isWithinString => minimum token length, otherwise maximal munch *\/\n for (uint currentLength = isWithinString ? 1 : maxTokSearchLen;\n isWithinString ? (currentLength <= maxTokSearchLen) : (currentLength > 0);\n currentLength += (isWithinString ? 1 : -1))\n {\n std::string currentSubString = str.substr(strCursorPos, currentLength);\n if (tokens_NameToBytes.count(currentSubString))\n {\n uint tokenValue = tokens_NameToBytes[currentSubString];\n if (tokenValue > 0xFF)\n {\n data.push_back((uchar)(tokenValue >> 8));\n }\n data.push_back((uchar)(tokenValue & 0xFF));\n strCursorPos += currentLength - 1;\n break;\n }\n }\n }\n\n uint actualDataLen = (uint) (data.size() - 2);\n data[0] = (uchar)(actualDataLen & 0xFF);\n data[1] = (uchar)((actualDataLen >> 8) & 0xFF);\n return data;\n }\n\n std::string TH_Tokenized::makeStringFromData(const data_t& data, const options_t& options)\n {\n const size_t dataSize = data.size();\n\n const bool fromRawBytes = has_option(options, \"fromRawBytes\") && options.at(\"fromRawBytes\") == 1;\n if (!fromRawBytes && dataSize < 2)\n {\n throw std::invalid_argument(\"Invalid data array. Needs to contain at least 2 bytes (size fields)\");\n }\n\n uint langIdx = (uint)((has_option(options, \"lang\") && options.at(\"lang\") == LANG_FR) ? LANG_FR : LANG_EN);\n\n const int howManyBytes = fromRawBytes ? (int)data.size() : ((data[0] & 0xFF) + ((data[1] & 0xFF) << 8));\n if (!fromRawBytes)\n {\n if (howManyBytes != (int)dataSize - 2)\n {\n std::cerr << \"[Warning] Byte count (\" << (dataSize - 2) << \") and size field (\" << howManyBytes << \") mismatch!\";\n }\n }\n\n if (!fromRawBytes && howManyBytes >= 2 && dataSize >= 4)\n {\n const uint16_t twoFirstBytes = (uint16_t) ((data[3] & 0xFF) + ((data[2] & 0xFF) << 8));\n if (std::find(std::begin(squishedASMTokens), std::end(squishedASMTokens), twoFirstBytes) != std::end(squishedASMTokens))\n {\n return \"[Error] This is a squished ASM program - cannnot preview it!\";\n }\n }\n\n uint errCount = 0;\n std::string str;\n for (uint i = fromRawBytes ? 0 : 2; i < (uint)dataSize; i++)\n {\n uint currentToken = data[i];\n uint nextToken = (i < dataSize-1) ? data[i+1] : (uint)-1;\n uint bytesKey = currentToken;\n if (is_in_vector(firstByteOfTwoByteTokens, (uchar)currentToken))\n {\n if (nextToken == (uint)-1)\n {\n std::cerr << \"[Warning] Encountered an unfinished two-byte token! Setting the second byte to 0x00\";\n nextToken = 0x00;\n }\n bytesKey = nextToken + (currentToken << 8);\n i++;\n }\n if (tokens_BytesToName.find(bytesKey) != tokens_BytesToName.end())\n {\n str += tokens_BytesToName[bytesKey][langIdx];\n } else {\n str += \" [???] \";\n errCount++;\n }\n }\n\n if (errCount > 0)\n {\n std::cerr << \"[Warning] \" << errCount << \" token(s) could not be detokenized (' [???] ' was used)!\";\n }\n\n if (has_option(options, \"prettify\") && options.at(\"prettify\") == 1)\n {\n str = std::regex_replace(str, std::regex(R\"(\\[?\\|?([a-z]+)\\]?)\"), \"$1\");\n }\n\n if (has_option(options, \"reindent\") && options.at(\"reindent\") == 1)\n {\n str = reindentCodeString(str);\n }\n\n return str;\n }\n\n std::string TH_Tokenized::reindentCodeString(const std::string& str_orig, const options_t& options)\n {\n int lang;\n if (has_option(options, \"lang\"))\n {\n lang = options.at(\"lang\");\n } else if (str_orig.size() > 1 && str_orig[0] == '.' && (str_orig[1] == '.' || ::isalpha(str_orig[1]))) {\n lang = PRGMLANG_AXE;\n } else if (str_orig.substr(0, sizeof(\"\\U0001D456\") - 1) == \"\\U0001D456\") {\n lang = PRGMLANG_ICE;\n } else {\n lang = PRGMLANG_BASIC;\n }\n\n std::string str(str_orig);\n\n str = std::regex_replace(str, std::regex(\"([^\\\\s])(Del|Eff)Var \"), \"$1\\n$2Var \");\n\n std::vector<std::string> lines_tmp = explode(str, '\\n');\n\n \/\/ Inplace-replace the appropriate \":\" by new-line chars (ie, by inserting the split string in the lines_tmp array)\n for (uint16_t idx = 0; idx < (uint16_t)lines_tmp.size(); idx++)\n {\n const auto line = lines_tmp[idx];\n bool isWithinString = false;\n for (uint16_t strIdx = 0; strIdx < (uint16_t)line.size(); strIdx++)\n {\n const auto currChar = line.substr(strIdx, 1);\n if (currChar == \":\" && !isWithinString)\n {\n lines_tmp[idx] = line.substr(0, strIdx); \/\/ replace \"old\" line by lhs\n lines_tmp.insert(lines_tmp.begin() + idx + 1, line.substr(strIdx + 1)); \/\/ inserting rhs\n break;\n } else if (currChar == \"\\\"\") {\n isWithinString = !isWithinString;\n } else if (currChar == \"\\n\" || currChar == \"→\") {\n isWithinString = false;\n }\n }\n }\n\n std::vector<std::pair<uint, std::string>> lines(lines_tmp.size()); \/\/ indent, text\n for (const auto& line : lines_tmp)\n {\n lines.emplace_back(0, line);\n }\n\n std::vector<std::string> increaseIndentAfter = { \"If\", \"For\", \"While\", \"Repeat\" };\n std::vector<std::string> decreaseIndentOfToken = { \"Then\", \"Else\", \"End\", \"ElseIf\", \"EndIf\", \"End!If\" };\n std::vector<std::string> closingTokens = { \"End\", \"EndIf\", \"End!If\" };\n uint nextIndent = 0;\n std::string oldFirstCommand, firstCommand;\n for (auto& line : lines)\n {\n oldFirstCommand = firstCommand;\n\n std::string trimmedLine = trim(line.second);\n if (trimmedLine.length() > 0) {\n char* trimmedLine_c = (char*) trimmedLine.c_str();\n firstCommand = strtok(trimmedLine_c, \" \");\n firstCommand = trim(firstCommand);\n trimmedLine = std::string(trimmedLine_c);\n trimmedLine_c = (char*) trimmedLine.c_str();\n if (firstCommand == trimmedLine)\n {\n firstCommand = strtok(trimmedLine_c, \"(\");\n firstCommand = trim(firstCommand);\n }\n } else {\n firstCommand = \"\";\n }\n\n line.first = nextIndent;\n\n if (is_in_vector(increaseIndentAfter, firstCommand))\n {\n nextIndent++;\n }\n if (line.first > 0 && is_in_vector(decreaseIndentOfToken, firstCommand))\n {\n line.first--;\n }\n if (nextIndent > 0 && (is_in_vector(closingTokens, firstCommand) || (oldFirstCommand == \"If\" && firstCommand != \"Then\" && lang != PRGMLANG_AXE && lang != PRGMLANG_ICE)))\n {\n nextIndent--;\n }\n }\n\n str = \"\";\n for (const auto& line : lines)\n {\n str += str_repeat(\" \", line.first * 3) + line.second + '\\n';\n }\n\n return ltrim(rtrim(str, \"\\t\\n\\r\\f\\v\"));\n }\n\n void TH_Tokenized::initTokens()\n {\n std::ifstream t(\"programs_tokens.csv\");\n std::string csvFileStr((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());\n\n if (csvFileStr.length() > 0)\n {\n std::vector<std::vector<std::string>> lines;\n ParseCSV(csvFileStr, lines);\n\n for (const auto& tokenInfo : lines)\n {\n uint bytes;\n if (tokenInfo[6] == \"2\") \/\/ number of bytes for the token\n {\n if (!is_in_vector(firstByteOfTwoByteTokens, hexdec(tokenInfo[7])))\n {\n firstByteOfTwoByteTokens.push_back(hexdec(tokenInfo[7]));\n }\n bytes = hexdec(tokenInfo[8]) + (hexdec(tokenInfo[7]) << 8);\n } else {\n bytes = hexdec(tokenInfo[7]);\n }\n tokens_BytesToName[bytes] = { tokenInfo[4], tokenInfo[5] }; \/\/ EN, FR\n tokens_NameToBytes[tokenInfo[4]] = bytes; \/\/ EN\n tokens_NameToBytes[tokenInfo[5]] = bytes; \/\/ FR\n uchar maxLenName = (uchar) std::max(tokenInfo[4].length(), tokenInfo[5].length());\n if (maxLenName > lengthOfLongestTokenName)\n {\n lengthOfLongestTokenName = maxLenName;\n }\n }\n } else {\n throw std::runtime_error(\"Could not open the tokens csv file\");\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014, Ford Motor Company\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 met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <sstream>\n\n#include \"transport_manager\/transport_adapter\/transport_adapter_impl.h\"\n#include \"transport_manager\/usb\/usb_device_scanner.h\"\n#include \"transport_manager\/usb\/usb_device.h\"\n#include \"transport_manager\/usb\/common.h\"\n\n#include \"utils\/logger.h\"\n\nnamespace transport_manager {\nnamespace transport_adapter {\n\nCREATE_LOGGERPTR_GLOBAL(logger_, \"UsbDeviceScanner\")\n\nclass AoaInitSequence : public UsbControlTransferSequence {\n public:\n AoaInitSequence();\n virtual ~AoaInitSequence() {\n }\n\n private:\n class AoaGetProtocolRequest;\n class AoaSendIdString;\n class AoaTurnIntoAccessoryMode;\n};\n\nvoid UsbDeviceScanner::OnDeviceArrived(PlatformUsbDevice* device) {\n LOG4CXX_AUTO_TRACE(logger_);\n if (IsAppleDevice(device)) {\n SupportedDeviceFound(device);\n } else {\n if (IsGoogleAccessory(device)) {\n SupportedDeviceFound(device);\n } else {\n TurnIntoAccessoryMode(device);\n }\n }\n}\n\nvoid UsbDeviceScanner::OnDeviceLeft(PlatformUsbDevice* device) {\n LOG4CXX_AUTO_TRACE(logger_);\n LOG4CXX_DEBUG(logger_, \"PlatformUsbDevice \" << device);\n bool list_changed = false;\n devices_mutex_.Acquire();\n for (Devices::iterator it = devices_.begin(); it != devices_.end(); ++it) {\n if (device == *it) {\n devices_.erase(it);\n list_changed = true;\n break;\n }\n }\n devices_mutex_.Release();\n if (list_changed) {\n UpdateList();\n }\n}\n\nUsbDeviceScanner::UsbDeviceScanner(TransportAdapterController* controller)\n : controller_(controller) {\n}\n\nUsbDeviceScanner::~UsbDeviceScanner() {\n}\n\nclass AoaInitSequence::AoaGetProtocolRequest : public UsbControlInTransfer {\n virtual ~AoaGetProtocolRequest() {\n }\n virtual RequestType Type() const {\n return VENDOR;\n }\n virtual uint8_t Request() const {\n return 51;\n }\n virtual uint16_t Value() const {\n return 0;\n }\n virtual uint16_t Index() const {\n return 0;\n }\n virtual uint16_t Length() const {\n return 2;\n }\n virtual bool OnCompleted(unsigned char* data) const {\n const int protocol_version = data[1] << 8 | data[0];\n LOG4CXX_DEBUG(logger_, \"AOA protocol version \" << protocol_version);\n if (protocol_version == 0) {\n \/\/ AOA protocol not supported\n return false;\n }\n return true;\n }\n};\n\nclass AoaInitSequence::AoaSendIdString : public UsbControlOutTransfer {\n public:\n AoaSendIdString(uint16_t index, const char* string, uint16_t length)\n : index_(index),\n string_(string),\n length_(length) {\n }\n\n private:\n virtual ~AoaSendIdString() {\n }\n virtual RequestType Type() const {\n return VENDOR;\n }\n virtual uint8_t Request() const {\n return 52;\n }\n virtual uint16_t Value() const {\n return 0;\n }\n virtual uint16_t Index() const {\n return index_;\n }\n virtual uint16_t Length() const {\n return length_;\n }\n virtual const char* Data() const {\n return string_;\n }\n uint16_t index_;\n const char* string_;\n uint16_t length_;\n};\n\nclass AoaInitSequence::AoaTurnIntoAccessoryMode : public UsbControlOutTransfer {\n virtual ~AoaTurnIntoAccessoryMode() {\n }\n virtual RequestType Type() const {\n return VENDOR;\n }\n virtual uint8_t Request() const {\n return 53;\n }\n virtual uint16_t Value() const {\n return 0;\n }\n virtual uint16_t Index() const {\n return 0;\n }\n virtual uint16_t Length() const {\n return 0;\n }\n virtual const char* Data() const {\n return 0;\n }\n};\n\nstatic char manufacturer[] = \"SDL\";\nstatic char model_name[] = \"Core\";\nstatic char description[] = \"SmartDeviceLink Core Component USB\";\nstatic char version[] = \"1.0\";\nstatic char uri[] = \"http:\/\/www.ford.com\";\nstatic char serial_num[] = \"N000000\";\n\nAoaInitSequence::AoaInitSequence()\n : UsbControlTransferSequence() {\n AddTransfer(new AoaGetProtocolRequest);\n AddTransfer(new AoaSendIdString(0, manufacturer, sizeof(manufacturer)));\n AddTransfer(new AoaSendIdString(1, model_name, sizeof(model_name)));\n AddTransfer(new AoaSendIdString(2, description, sizeof(description)));\n AddTransfer(new AoaSendIdString(3, version, sizeof(version)));\n AddTransfer(new AoaSendIdString(4, uri, sizeof(uri)));\n AddTransfer(new AoaSendIdString(5, serial_num, sizeof(serial_num)));\n AddTransfer(new AoaTurnIntoAccessoryMode);\n}\n\nvoid UsbDeviceScanner::TurnIntoAccessoryMode(PlatformUsbDevice* device) {\n LOG4CXX_AUTO_TRACE(logger_);\n LOG4CXX_DEBUG(logger_, \"PlatformUsbDevice: \" << device);\n GetUsbHandler()->StartControlTransferSequence(new AoaInitSequence, device);\n}\n\nvoid UsbDeviceScanner::SupportedDeviceFound(PlatformUsbDevice* device) {\n LOG4CXX_AUTO_TRACE(logger_);\n LOG4CXX_TRACE(logger_, \"PlatformUsbDevice: \" << device);\n\n devices_mutex_.Acquire();\n devices_.push_back(device);\n devices_mutex_.Release();\n LOG4CXX_DEBUG(\n logger_,\n \"USB device (bus number \" << static_cast<int>(device->bus_number())\n << \", address \" << static_cast<int>(device->address())\n << \") identified as: \" << device->GetManufacturer()\n << \", \" << device->GetProductName()\n << \", serial: \" << device->GetSerialNumber());\n UpdateList();\n}\n\nTransportAdapter::Error UsbDeviceScanner::Init() {\n return TransportAdapter::OK;\n}\n\nTransportAdapter::Error UsbDeviceScanner::Scan() {\n return TransportAdapter::OK;\n}\n\nvoid UsbDeviceScanner::UpdateList() {\n LOG4CXX_AUTO_TRACE(logger_);\n DeviceVector device_vector;\n devices_mutex_.Acquire();\n for (Devices::const_iterator it = devices_.begin(); it != devices_.end();\n ++it) {\n const std::string device_name = (*it)->GetManufacturer() + \" \"\n + (*it)->GetProductName();\n std::ostringstream oss;\n oss << (*it)->GetManufacturer() << \":\" << (*it)->GetProductName() << \":\"\n << (*it)->GetSerialNumber();\n const DeviceUID device_uid = oss.str();\n DeviceSptr device(new UsbDevice(*it, device_name, device_uid));\n device_vector.push_back(device);\n }\n devices_mutex_.Release();\n\n LOG4CXX_DEBUG(logger_, \"USB search done \" << device_vector.size());\n controller_->SearchDeviceDone(device_vector);\n}\n\nvoid UsbDeviceScanner::Terminate() {\n}\n\nbool UsbDeviceScanner::IsInitialised() const {\n return true;\n}\n\n} \/\/ namespace\n} \/\/ namespace\n<commit_msg>Modify usb_device_scanner.cc.<commit_after>\/*\n * Copyright (c) 2014, Ford Motor Company\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 met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <sstream>\n\n#include \"transport_manager\/transport_adapter\/transport_adapter_impl.h\"\n#include \"transport_manager\/usb\/usb_device_scanner.h\"\n#include \"transport_manager\/usb\/usb_device.h\"\n#include \"transport_manager\/usb\/common.h\"\n\n#include \"utils\/logger.h\"\n\nnamespace transport_manager {\nnamespace transport_adapter {\n\nCREATE_LOGGERPTR_GLOBAL(logger_, \"UsbDeviceScanner\")\n\nclass AoaInitSequence : public UsbControlTransferSequence {\n public:\n AoaInitSequence();\n virtual ~AoaInitSequence() {\n }\n\n private:\n class AoaGetProtocolRequest;\n class AoaSendIdString;\n class AoaTurnIntoAccessoryMode;\n};\n\nvoid UsbDeviceScanner::OnDeviceArrived(PlatformUsbDevice* device) {\n LOG4CXX_AUTO_TRACE(logger_);\n if (IsAppleDevice(device)) {\n SupportedDeviceFound(device);\n } else {\n if (IsGoogleAccessory(device)) {\n SupportedDeviceFound(device);\n } else {\n TurnIntoAccessoryMode(device);\n }\n }\n}\n\nvoid UsbDeviceScanner::OnDeviceLeft(PlatformUsbDevice* device) {\n LOG4CXX_AUTO_TRACE(logger_);\n LOG4CXX_DEBUG(logger_, \"PlatformUsbDevice \" << device);\n bool list_changed = false;\n devices_mutex_.Acquire();\n for (Devices::iterator it = devices_.begin(); it != devices_.end(); ++it) {\n if (device == *it) {\n devices_.erase(it);\n list_changed = true;\n break;\n }\n }\n devices_mutex_.Release();\n if (list_changed) {\n UpdateList();\n }\n}\n\nUsbDeviceScanner::UsbDeviceScanner(TransportAdapterController* controller)\n : controller_(controller) {\n}\n\nUsbDeviceScanner::~UsbDeviceScanner() {\n}\n\nclass AoaInitSequence::AoaGetProtocolRequest : public UsbControlInTransfer {\n virtual ~AoaGetProtocolRequest() {\n }\n virtual RequestType Type() const {\n return VENDOR;\n }\n virtual uint8_t Request() const {\n return 51;\n }\n virtual uint16_t Value() const {\n return 0;\n }\n virtual uint16_t Index() const {\n return 0;\n }\n virtual uint16_t Length() const {\n return 2;\n }\n virtual bool OnCompleted(unsigned char* data) const {\n const int protocol_version = data[1] << 8 | data[0];\n LOG4CXX_DEBUG(logger_, \"AOA protocol version \" << protocol_version);\n if (protocol_version == 0) {\n \/\/ AOA protocol not supported\n return false;\n }\n return true;\n }\n};\n\nclass AoaInitSequence::AoaSendIdString : public UsbControlOutTransfer {\n public:\n AoaSendIdString(uint16_t index, const char* string, uint16_t length)\n : index_(index),\n string_(string),\n length_(length) {\n }\n\n private:\n virtual ~AoaSendIdString() {\n }\n virtual RequestType Type() const {\n return VENDOR;\n }\n virtual uint8_t Request() const {\n return 52;\n }\n virtual uint16_t Value() const {\n return 0;\n }\n virtual uint16_t Index() const {\n return index_;\n }\n virtual uint16_t Length() const {\n return length_;\n }\n virtual const char* Data() const {\n return string_;\n }\n uint16_t index_;\n const char* string_;\n uint16_t length_;\n};\n\nclass AoaInitSequence::AoaTurnIntoAccessoryMode : public UsbControlOutTransfer {\n virtual ~AoaTurnIntoAccessoryMode() {\n }\n virtual RequestType Type() const {\n return VENDOR;\n }\n virtual uint8_t Request() const {\n return 53;\n }\n virtual uint16_t Value() const {\n return 0;\n }\n virtual uint16_t Index() const {\n return 0;\n }\n virtual uint16_t Length() const {\n return 0;\n }\n virtual const char* Data() const {\n return 0;\n }\n};\n\nstatic char manufacturer[] = \"SDL\";\nstatic char model_name[] = \"Core\";\nstatic char description[] = \"SmartDeviceLink Core Component USB\";\nstatic char version[] = \"1.0\";\nstatic char uri[] = \"http:\/\/www.smartdevicelink.org\";\nstatic char serial_num[] = \"N000000\";\n\nAoaInitSequence::AoaInitSequence()\n : UsbControlTransferSequence() {\n AddTransfer(new AoaGetProtocolRequest);\n AddTransfer(new AoaSendIdString(0, manufacturer, sizeof(manufacturer)));\n AddTransfer(new AoaSendIdString(1, model_name, sizeof(model_name)));\n AddTransfer(new AoaSendIdString(2, description, sizeof(description)));\n AddTransfer(new AoaSendIdString(3, version, sizeof(version)));\n AddTransfer(new AoaSendIdString(4, uri, sizeof(uri)));\n AddTransfer(new AoaSendIdString(5, serial_num, sizeof(serial_num)));\n AddTransfer(new AoaTurnIntoAccessoryMode);\n}\n\nvoid UsbDeviceScanner::TurnIntoAccessoryMode(PlatformUsbDevice* device) {\n LOG4CXX_AUTO_TRACE(logger_);\n LOG4CXX_DEBUG(logger_, \"PlatformUsbDevice: \" << device);\n GetUsbHandler()->StartControlTransferSequence(new AoaInitSequence, device);\n}\n\nvoid UsbDeviceScanner::SupportedDeviceFound(PlatformUsbDevice* device) {\n LOG4CXX_AUTO_TRACE(logger_);\n LOG4CXX_TRACE(logger_, \"PlatformUsbDevice: \" << device);\n\n devices_mutex_.Acquire();\n devices_.push_back(device);\n devices_mutex_.Release();\n LOG4CXX_DEBUG(\n logger_,\n \"USB device (bus number \" << static_cast<int>(device->bus_number())\n << \", address \" << static_cast<int>(device->address())\n << \") identified as: \" << device->GetManufacturer()\n << \", \" << device->GetProductName()\n << \", serial: \" << device->GetSerialNumber());\n UpdateList();\n}\n\nTransportAdapter::Error UsbDeviceScanner::Init() {\n return TransportAdapter::OK;\n}\n\nTransportAdapter::Error UsbDeviceScanner::Scan() {\n return TransportAdapter::OK;\n}\n\nvoid UsbDeviceScanner::UpdateList() {\n LOG4CXX_AUTO_TRACE(logger_);\n DeviceVector device_vector;\n devices_mutex_.Acquire();\n for (Devices::const_iterator it = devices_.begin(); it != devices_.end();\n ++it) {\n const std::string device_name = (*it)->GetManufacturer() + \" \"\n + (*it)->GetProductName();\n std::ostringstream oss;\n oss << (*it)->GetManufacturer() << \":\" << (*it)->GetProductName() << \":\"\n << (*it)->GetSerialNumber();\n const DeviceUID device_uid = oss.str();\n DeviceSptr device(new UsbDevice(*it, device_name, device_uid));\n device_vector.push_back(device);\n }\n devices_mutex_.Release();\n\n LOG4CXX_DEBUG(logger_, \"USB search done \" << device_vector.size());\n controller_->SearchDeviceDone(device_vector);\n}\n\nvoid UsbDeviceScanner::Terminate() {\n}\n\nbool UsbDeviceScanner::IsInitialised() const {\n return true;\n}\n\n} \/\/ namespace\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"types.hpp\"\n#include <CoreGraphics\/CoreGraphics.h>\n#include <thread>\n#include <vector>\n\nnamespace krbn {\nnamespace manipulator {\nclass modifier_flag_manager final {\npublic:\n modifier_flag_manager(void) {\n states_.resize(static_cast<size_t>(modifier_flag::end_));\n\n states_[static_cast<size_t>(modifier_flag::caps_lock)] = std::make_unique<state>(\"caps lock\", \"⇪\");\n states_[static_cast<size_t>(modifier_flag::left_control)] = std::make_unique<state>(\"control\", \"⌃\");\n states_[static_cast<size_t>(modifier_flag::left_shift)] = std::make_unique<state>(\"shift\", \"⇧\");\n states_[static_cast<size_t>(modifier_flag::left_option)] = std::make_unique<state>(\"option\", \"⌥\");\n states_[static_cast<size_t>(modifier_flag::left_command)] = std::make_unique<state>(\"command\", \"⌘\");\n states_[static_cast<size_t>(modifier_flag::right_control)] = std::make_unique<state>(\"control\", \"⌃\");\n states_[static_cast<size_t>(modifier_flag::right_shift)] = std::make_unique<state>(\"shift\", \"⇧\");\n states_[static_cast<size_t>(modifier_flag::right_option)] = std::make_unique<state>(\"option\", \"⌥\");\n states_[static_cast<size_t>(modifier_flag::right_command)] = std::make_unique<state>(\"command\", \"⌘\");\n states_[static_cast<size_t>(modifier_flag::fn)] = std::make_unique<state>(\"fn\", \"fn\");\n }\n\n void reset(void) {\n for (const auto& s : states_) {\n if (s) {\n s->reset();\n }\n }\n }\n\n void unlock(void) {\n for (const auto& s : states_) {\n if (s) {\n s->unlock();\n }\n }\n }\n\n enum class operation {\n increase,\n decrease,\n lock,\n unlock,\n toggle_lock,\n };\n\n void manipulate(modifier_flag k, operation operation) {\n auto i = static_cast<size_t>(k);\n if (states_[i]) {\n switch (operation) {\n case operation::increase:\n states_[i]->increase();\n break;\n case operation::decrease:\n states_[i]->decrease();\n break;\n case operation::lock:\n states_[i]->lock();\n break;\n case operation::unlock:\n states_[i]->unlock();\n break;\n case operation::toggle_lock:\n states_[i]->toggle_lock();\n break;\n }\n }\n }\n\n bool pressed(modifier_flag m) const {\n if (m == modifier_flag::zero) {\n return true;\n }\n\n auto i = static_cast<size_t>(m);\n if (i < states_.size() && states_[i]) {\n return states_[i]->pressed();\n }\n return false;\n }\n\n bool pressed(const std::vector<modifier_flag>& modifier_flags) const {\n \/\/ return true if all modifier flags are pressed.\n for (const auto& m : modifier_flags) {\n if (!pressed(m)) {\n return false;\n }\n }\n return true;\n }\n\n uint8_t get_hid_report_bits(void) const {\n uint8_t bits = 0;\n\n if (pressed(modifier_flag::left_control)) {\n bits |= (0x1 << 0);\n }\n if (pressed(modifier_flag::left_shift)) {\n bits |= (0x1 << 1);\n }\n if (pressed(modifier_flag::left_option)) {\n bits |= (0x1 << 2);\n }\n if (pressed(modifier_flag::left_command)) {\n bits |= (0x1 << 3);\n }\n if (pressed(modifier_flag::right_control)) {\n bits |= (0x1 << 4);\n }\n if (pressed(modifier_flag::right_shift)) {\n bits |= (0x1 << 5);\n }\n if (pressed(modifier_flag::right_option)) {\n bits |= (0x1 << 6);\n }\n if (pressed(modifier_flag::right_command)) {\n bits |= (0x1 << 7);\n }\n\n return bits;\n }\n\n IOOptionBits get_io_option_bits(key_code key_code) const {\n \/\/ OS X requires to set NX_NONCOALSESCEDMASK.\n IOOptionBits bits = NX_NONCOALSESCEDMASK;\n\n if (pressed(modifier_flag::caps_lock)) {\n bits |= NX_ALPHASHIFTMASK;\n }\n if (pressed(modifier_flag::left_control)) {\n bits |= NX_CONTROLMASK | NX_DEVICELCTLKEYMASK;\n }\n if (pressed(modifier_flag::right_control)) {\n bits |= NX_CONTROLMASK | NX_DEVICERCTLKEYMASK;\n }\n if (pressed(modifier_flag::left_shift)) {\n bits |= NX_SHIFTMASK | NX_DEVICELSHIFTKEYMASK;\n }\n if (pressed(modifier_flag::right_shift)) {\n bits |= NX_SHIFTMASK | NX_DEVICERSHIFTKEYMASK;\n }\n if (pressed(modifier_flag::left_option)) {\n bits |= NX_ALTERNATEMASK | NX_DEVICELALTKEYMASK;\n }\n if (pressed(modifier_flag::right_option)) {\n bits |= NX_ALTERNATEMASK | NX_DEVICERALTKEYMASK;\n }\n if (pressed(modifier_flag::left_command)) {\n bits |= NX_COMMANDMASK | NX_DEVICELCMDKEYMASK;\n }\n if (pressed(modifier_flag::right_command)) {\n bits |= NX_COMMANDMASK | NX_DEVICERCMDKEYMASK;\n }\n if (pressed(modifier_flag::fn)) {\n bits |= NX_SECONDARYFNMASK;\n }\n\n \/\/ Add NX_NUMERICPADMASK, NX_SECONDARYFNMASK by key_code.\n \/\/\n \/\/ Note:\n \/\/ Microsoft Remote Client will fail to treat shift-arrow keys unless these flags.\n \/\/ Alfred will fail f16 key as trigger key unless fn flag.\n\n switch (key_code) {\n case key_code::keypad_slash:\n case key_code::keypad_asterisk:\n case key_code::keypad_hyphen:\n case key_code::keypad_plus:\n case key_code::keypad_enter:\n case key_code::keypad_1:\n case key_code::keypad_2:\n case key_code::keypad_3:\n case key_code::keypad_4:\n case key_code::keypad_5:\n case key_code::keypad_6:\n case key_code::keypad_7:\n case key_code::keypad_8:\n case key_code::keypad_9:\n case key_code::keypad_0:\n case key_code::keypad_period:\n case key_code::keypad_equal_sign:\n case key_code::keypad_comma:\n bits |= NX_NUMERICPADMASK;\n break;\n\n case key_code::right_arrow:\n case key_code::left_arrow:\n case key_code::down_arrow:\n case key_code::up_arrow:\n bits |= NX_NUMERICPADMASK | NX_SECONDARYFNMASK;\n break;\n\n case key_code::f1:\n case key_code::f2:\n case key_code::f3:\n case key_code::f4:\n case key_code::f5:\n case key_code::f6:\n case key_code::f7:\n case key_code::f8:\n case key_code::f9:\n case key_code::f10:\n case key_code::f11:\n case key_code::f12:\n case key_code::f13:\n case key_code::f14:\n case key_code::f15:\n case key_code::f16:\n case key_code::f17:\n case key_code::f18:\n case key_code::f19:\n case key_code::f20:\n case key_code::f21:\n case key_code::f22:\n case key_code::f23:\n case key_code::f24:\n bits |= NX_SECONDARYFNMASK;\n break;\n\n default:\n break;\n }\n\n return bits;\n }\n\n CGEventFlags get_cg_event_flags_for_mouse_events(void) const {\n \/\/ The CGEventFlags and IOOptionBits are same for now.\n return get_io_option_bits(key_code::vk_none);\n }\n\nprivate:\n class state final {\n public:\n state(const std::string& name, const std::string& symbol) : name_(name),\n symbol_(symbol),\n count_(0),\n lock_count_(0) {}\n\n const std::string& get_name(void) const { return name_; }\n const std::string& get_symbol(void) const { return symbol_; }\n\n bool pressed(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n return (count_ + lock_count_) > 0;\n }\n\n void reset(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n count_ = 0;\n }\n\n void increase(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n ++count_;\n }\n\n void decrease(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n --count_;\n }\n\n void lock(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n lock_count_ = 1;\n }\n\n void unlock(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n lock_count_ = 0;\n }\n\n void toggle_lock(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n lock_count_ = lock_count_ == 0 ? 1 : 0;\n }\n\n private:\n std::string name_;\n std::string symbol_;\n int count_;\n int lock_count_;\n\n std::mutex mutex_;\n };\n\n std::vector<std::unique_ptr<state>> states_;\n};\n} \/\/ namespace manipulator\n} \/\/ namespace krbn\n<commit_msg>remove modifier_flag_manager.get_hid_report_bits,get_io_option_bits,get_cg_event_flags_for_mouse_events<commit_after>#pragma once\n\n#include \"types.hpp\"\n#include <CoreGraphics\/CoreGraphics.h>\n#include <thread>\n#include <vector>\n\nnamespace krbn {\nnamespace manipulator {\nclass modifier_flag_manager final {\npublic:\n modifier_flag_manager(void) {\n states_.resize(static_cast<size_t>(modifier_flag::end_));\n\n states_[static_cast<size_t>(modifier_flag::caps_lock)] = std::make_unique<state>(\"caps lock\", \"⇪\");\n states_[static_cast<size_t>(modifier_flag::left_control)] = std::make_unique<state>(\"control\", \"⌃\");\n states_[static_cast<size_t>(modifier_flag::left_shift)] = std::make_unique<state>(\"shift\", \"⇧\");\n states_[static_cast<size_t>(modifier_flag::left_option)] = std::make_unique<state>(\"option\", \"⌥\");\n states_[static_cast<size_t>(modifier_flag::left_command)] = std::make_unique<state>(\"command\", \"⌘\");\n states_[static_cast<size_t>(modifier_flag::right_control)] = std::make_unique<state>(\"control\", \"⌃\");\n states_[static_cast<size_t>(modifier_flag::right_shift)] = std::make_unique<state>(\"shift\", \"⇧\");\n states_[static_cast<size_t>(modifier_flag::right_option)] = std::make_unique<state>(\"option\", \"⌥\");\n states_[static_cast<size_t>(modifier_flag::right_command)] = std::make_unique<state>(\"command\", \"⌘\");\n states_[static_cast<size_t>(modifier_flag::fn)] = std::make_unique<state>(\"fn\", \"fn\");\n }\n\n void reset(void) {\n for (const auto& s : states_) {\n if (s) {\n s->reset();\n }\n }\n }\n\n void unlock(void) {\n for (const auto& s : states_) {\n if (s) {\n s->unlock();\n }\n }\n }\n\n enum class operation {\n increase,\n decrease,\n lock,\n unlock,\n toggle_lock,\n };\n\n void manipulate(modifier_flag k, operation operation) {\n auto i = static_cast<size_t>(k);\n if (states_[i]) {\n switch (operation) {\n case operation::increase:\n states_[i]->increase();\n break;\n case operation::decrease:\n states_[i]->decrease();\n break;\n case operation::lock:\n states_[i]->lock();\n break;\n case operation::unlock:\n states_[i]->unlock();\n break;\n case operation::toggle_lock:\n states_[i]->toggle_lock();\n break;\n }\n }\n }\n\n bool pressed(modifier_flag m) const {\n if (m == modifier_flag::zero) {\n return true;\n }\n\n auto i = static_cast<size_t>(m);\n if (i < states_.size() && states_[i]) {\n return states_[i]->pressed();\n }\n return false;\n }\n\n bool pressed(const std::vector<modifier_flag>& modifier_flags) const {\n \/\/ return true if all modifier flags are pressed.\n for (const auto& m : modifier_flags) {\n if (!pressed(m)) {\n return false;\n }\n }\n return true;\n }\n\nprivate:\n class state final {\n public:\n state(const std::string& name, const std::string& symbol) : name_(name),\n symbol_(symbol),\n count_(0),\n lock_count_(0) {}\n\n const std::string& get_name(void) const { return name_; }\n const std::string& get_symbol(void) const { return symbol_; }\n\n bool pressed(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n return (count_ + lock_count_) > 0;\n }\n\n void reset(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n count_ = 0;\n }\n\n void increase(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n ++count_;\n }\n\n void decrease(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n --count_;\n }\n\n void lock(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n lock_count_ = 1;\n }\n\n void unlock(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n lock_count_ = 0;\n }\n\n void toggle_lock(void) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n lock_count_ = lock_count_ == 0 ? 1 : 0;\n }\n\n private:\n std::string name_;\n std::string symbol_;\n int count_;\n int lock_count_;\n\n std::mutex mutex_;\n };\n\n std::vector<std::unique_ptr<state>> states_;\n};\n} \/\/ namespace manipulator\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"<commit_before>#include \"musicplayer.h\"\n#include \"musicplaylist.h\"\n#include \"musicsettingmanager.h\"\n#include \"musicconnectionpool.h\"\n#include \"musicnumberdefine.h\"\n\/\/\/qmmp incldue\n#include \"soundcore.h\"\n\/\/\/\n#include <qmath.h>\n\nMusicPlayer::MusicPlayer(QObject *parent)\n : QObject(parent)\n{\n m_playlist = nullptr;\n m_state = StoppedState;\n m_musicEnhanced = EnhancedOff;\n m_music = new SoundCore(this);\n m_posOnCircle = 0;\n m_volumeMusic3D = 0;\n m_balance = 0;\n m_duration = 0;\n m_tryTimes = 0;\n\n setEnaleEffect(false);\n\n connect(&m_timer, SIGNAL(timeout()), SLOT(update()));\n M_CONNECTION_PTR->setValue(getClassName(), this);\n}\n\nMusicPlayer::~MusicPlayer()\n{\n delete m_music;\n}\n\nQString MusicPlayer::getClassName()\n{\n return staticMetaObject.className();\n}\n\nMusicPlayer::State MusicPlayer::state() const\n{\n return m_state;\n}\n\nvoid MusicPlayer::setPlaylist(MusicPlaylist *playlist)\n{\n delete m_playlist;\n m_playlist = playlist;\n}\n\nMusicPlaylist *MusicPlayer::playlist() const\n{\n return m_playlist;\n}\n\nqint64 MusicPlayer::duration() const\n{\n return m_music->totalTime();\n}\n\nqint64 MusicPlayer::position() const\n{\n return m_music->elapsed();\n}\n\nvoid MusicPlayer::playNext()\n{\n int index = m_playlist->currentIndex();\n m_playlist->setCurrentIndex((++index >= m_playlist->mediaCount()) ? 0 : index);\n}\n\nvoid MusicPlayer::playPrevious()\n{\n int index = m_playlist->currentIndex();\n m_playlist->setCurrentIndex((--index < 0) ? 0 : index );\n}\n\nint MusicPlayer::volume() const\n{\n return isMuted() ? 0 : m_music->volume();\n}\n\nvoid MusicPlayer::setVolume(int volume)\n{\n m_volumeMusic3D = volume;\n m_music->setVolume(volume);\n}\n\nbool MusicPlayer::isMuted() const\n{\n return m_music->isMuted();\n}\n\nvoid MusicPlayer::setMuted(bool muted)\n{\n m_volumeMusic3D = muted ? 0 : m_music->volume();\n m_music->setMuted(muted);\n}\n\nvoid MusicPlayer::setPosition(qint64 position)\n{\n m_music->seek(position);\n}\n\nvoid MusicPlayer::setMusicEnhanced(Enhanced type)\n{\n m_musicEnhanced = type;\n\n if(m_musicEnhanced == Music3D)\n {\n m_volumeMusic3D = volume();\n }\n else if(m_musicEnhanced == EnhancedOff)\n {\n return;\n }\n else\n {\n m_music->setBalance(0);\n m_music->setVolume(m_volumeMusic3D, m_volumeMusic3D);\n m_music->setBalance(m_balance);\n setMusicEnhancedCase();\n }\n}\n\nMusicPlayer::Enhanced MusicPlayer::getMusicEnhanced() const\n{\n return m_musicEnhanced;\n}\n\nQStringList MusicPlayer::supportFormatsString()\n{\n return QStringList()<< \"mpc\" << \"wv\" << \"ogg\" << \"wav\" << \"au\" << \"snd\" << \"aif\" << \"aiff\" << \"8svx\"\n << \"sph\" << \"sf\" << \"voc\" << \"w64\" << \"cue\" << \"mp1\" << \"mp2\" << \"mp3\" << \"wav\"\n << \"ay\" << \"gms\" << \"gym\" << \"hes\" << \"kss\" << \"nsf\" << \"nsfe\" << \"sap\" << \"spc\"\n << \"vgm\" << \"vgz\" << \"flac\" << \"oga\" << \"ape\" << \"wma\" << \"ape\" << \"tta\" << \"m4a\"\n << \"ra\" << \"shn\" << \"vqf\" << \"ac3\" << \"mod\" << \"s3m\" << \"xm\" << \"it\" << \"669\"\n << \"amf\" << \"ams\" << \"dbm\" << \"dmf\" << \"dsm\" << \"far\" << \"mdl\" << \"med\" << \"mtm\"\n << \"okt\" << \"ptm\" << \"stm\" << \"ult\" << \"umx\" << \"mt2\" << \"psm\" << \"mdz\" << \"s3z\"\n << \"xmz\" << \"itz\" << \"mdr\" << \"s3r\" << \"xmr\" << \"itr\" << \"dgz\" << \"s3gz\" << \"xmgz\"\n << \"itgz\" << \"opus\" << \"mid\"\n#ifndef Q_OS_WIN\n << \"sid\" << \"mus\" << \"str\" << \"prg\" << \"P00\"\n#endif\n << \"aac\";\n}\n\nQStringList MusicPlayer::supportFormatsFilterString()\n{\n return QStringList()<< \"*.mpc\" << \"*.wv\" << \"*.ogg\" << \"*.wav\" << \"*.au\" << \"*.snd\" << \"*.aif\" << \"*.aiff\" << \"*.8svx\"\n << \"*.sph\" << \"*.sf\" << \"*.voc\" << \"*.w64\" << \"*.cue\" << \"*.mp1\" << \"*.mp2\" << \"*.mp3\" << \"*.wav\"\n << \"*.ay\" << \"*.gms\" << \"*.gym\" << \"*.hes\" << \"*.kss\" << \"*.nsf\" << \"*.nsfe\" << \"*.sap\" << \"*.spc\"\n << \"*.vgm\" << \"*.vgz\" << \"*.flac\" << \"*.oga\" << \"*.ape\" << \"*.wma\" << \"*.ape\" << \"*.tta\" << \"*.m4a\"\n << \"*.ra\" << \"*.shn\" << \"*.vqf\" << \"*.ac3\" << \"*.mod\" << \"*.s3m\" << \"*.xm\" << \"*.it\" << \"*.669\"\n << \"*.amf\" << \"*.ams\" << \"*.dbm\" << \"*.dmf\" << \"*.dsm\" << \"*.far\" << \"*.mdl\" << \"*.med\" << \"*.mtm\"\n << \"*.okt\" << \"*.ptm\" << \"*.stm\" << \"*.ult\" << \"*.umx\" << \"*.mt2\" << \"*.psm\" << \"*.mdz\" << \"*.s3z\"\n << \"*.xmz\" << \"*.itz\" << \"*.mdr\" << \"*.s3r\" << \"*.xmr\" << \"*.itr\" << \"*.dgz\" << \"*.s3gz\" << \"*.xmgz\"\n << \"*.itgz\" << \"*.opus\" << \"*.mid\"\n#ifndef Q_OS_WIN\n << \"*.sid\" << \"*.mus\" << \"*.str\" << \"*.prg\" << \"*.P00\"\n#endif\n << \"*.aac\";\n}\n\nQStringList MusicPlayer::supportFormatsFilterDialogString()\n{\n return QStringList()<< \"All File(*.*)\" << \"MusePack File(*.mpc)\" << \"WavPack File(*.wv)\" << \"Ogg Vorbis File(*.ogg)\"\n << \"PCM File(*.wav *.au *.snd *.aif *.aiff *.8svx *.sph *.sf *.voc *.w64)\"\n << \"CUE File(*.cue)\" << \"MPEG File(*.mp1 *.mp2 *.mp3 *.wav)\"\n << \"Game File(*.ay *.gms *.gym *.hes *.kss *.nsf *.nsfe *.sap *.spc *.vgm *.vgz)\"\n << \"FLAC File(*.flac *.oga)\" << \"Monkey's Audio File(*.ape)\"\n << \"Ogg Opus File(*.opus)\" << \"ADTS AAC File(*.aac)\" << \"MIDI File(*.mid)\"\n#ifndef Q_OS_WIN\n << \"SID File(*.sid *.mus *.str *.prg *.P00)\"\n#endif\n << \"FFmpeg File(*.wma *.ape *.tta *.m4a *.ra *.shn *.vqf *.ac3)\"\n << \"ModPlug File(*.mod *.s3m *.xm *.it *.669 *.amf *.ams *.dbm *.dmf *.dsm *.far,mdl *.med *.mtm \"\n \"*.okt *.ptm *.stm *.ult *.umx *.mt2 *.psm *.mdz *.s3z *.xmz *.itz *.mdr *.s3r *.xmr *.itr \"\n \"*.dgz *.s3gz *.xmgz *.itgz)\";\n}\n\nvoid MusicPlayer::play()\n{\n if(m_playlist->isEmpty())\n {\n m_state = StoppedState;\n return;\n }\n\n m_state = PlayingState;\n Qmmp::State state = m_music->state(); \/\/\/Get the current state of play\n if(m_currentMedia == m_playlist->currentMediaString() && state == Qmmp::Paused)\n {\n m_music->pause(); \/\/\/When the pause time for recovery\n m_timer.start(MT_S2MS);\n return;\n }\n\n m_currentMedia = m_playlist->currentMediaString();\n \/\/\/The current playback path\n if(!m_music->play(m_currentMedia))\n {\n m_state = StoppedState;\n return;\n }\n\n m_tryTimes = 0;\n m_timer.start(MT_S2MS);\n \/\/\/Every second emits a signal change information\n emit positionChanged(0);\n getCurrentDuration();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/Read the configuration settings for the sound\n int volume = M_SETTING_PTR->value(MusicSettingManager::VolumeChoiced).toInt();\n if(volume != -1)\n {\n setVolume(volume);\n }\n setSoundEffectVolume(M_SETTING_PTR->value(MusicSettingManager::EnhancedBalanceChoiced).toInt());\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n}\n\nvoid MusicPlayer::pause()\n{\n m_music->pause();\n m_timer.stop();\n m_state = PausedState;\n}\n\nvoid MusicPlayer::stop()\n{\n m_music->stop();\n m_timer.stop();\n m_state = StoppedState;\n}\n\nvoid MusicPlayer::setEqEffect(const MusicObject::MIntList &hz)\n{\n if(hz.count() != 11)\n {\n return;\n }\n\n EqSettings eq = m_music->eqSettings();\n eq.setPreamp(15 + hz[0]);\n eq.setEnabled(true);\n for(int i=0; i<EqSettings::EQ_BANDS_10; ++i)\n {\n eq.setGain(i, hz[i + 1]);\n }\n m_music->setEqSettings(eq);\n}\n\nvoid MusicPlayer::setEnaleEffect(bool enable)\n{\n if(enable == false)\n {\n setEqEffect(MusicObject::MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);\n }\n}\n\nvoid MusicPlayer::setEqInformation()\n{\n \/\/\/Read the equalizer parameters from a configuration file\n if(M_SETTING_PTR->value(MusicSettingManager::EqualizerEnableChoiced).toInt())\n {\n setEnaleEffect(true);\n QStringList eqValue = M_SETTING_PTR->value(MusicSettingManager::EqualizerValueChoiced).toString().split(',');\n if(eqValue.count() == 11)\n {\n MusicObject::MIntList hz;\n hz << eqValue[0].toInt() << eqValue[1].toInt() << eqValue[2].toInt()\n << eqValue[3].toInt() << eqValue[4].toInt() << eqValue[5].toInt()\n << eqValue[6].toInt() << eqValue[7].toInt() << eqValue[8].toInt()\n << eqValue[9].toInt() << eqValue[10].toInt();\n setEqEffect(hz);\n }\n }\n else\n {\n setEnaleEffect(false);\n }\n}\n\nvoid MusicPlayer::setSoundEffectVolume(int value)\n{\n m_balance = value;\n m_music->setBalance(value);\n}\n\nvoid MusicPlayer::removeCurrentMedia()\n{\n m_timer.stop();\n m_music->stop();\n}\n\nvoid MusicPlayer::update()\n{\n emit positionChanged( position() );\n\n if(m_musicEnhanced == Music3D && !m_music->isMuted())\n {\n \/\/\/3D music settings\n setEnaleEffect(false);\n m_posOnCircle += 0.5f;\n m_music->setVolume(abs(100 * cosf(m_posOnCircle)), abs(100 * sinf(m_posOnCircle * 0.5f)));\n }\n\n Qmmp::State state = m_music->state();\n if(state != Qmmp::Playing && state != Qmmp::Paused)\n {\n m_timer.stop();\n if(m_playlist->playbackMode() == MusicObject::MC_PlayOnce)\n {\n m_music->stop();\n emit positionChanged(0);\n emit stateChanged(StoppedState);\n return;\n }\n m_playlist->setCurrentIndex();\n if(m_playlist->playbackMode() == MusicObject::MC_PlayOrder &&\n m_playlist->currentIndex() == -1)\n {\n m_music->stop();\n emit positionChanged(0);\n emit stateChanged(StoppedState);\n return;\n }\n play();\n }\n}\n\nvoid MusicPlayer::getCurrentDuration()\n{\n qint64 dur = duration();\n if( (dur == 0 || m_duration == dur) && m_tryTimes++ < 10 )\n {\n QTimer::singleShot(50*MT_MS, this, SLOT(getCurrentDuration()));\n }\n else\n {\n emit durationChanged( m_duration = dur );\n }\n}\n\nvoid MusicPlayer::setMusicEnhancedCase()\n{\n switch(m_musicEnhanced)\n {\n case EnhancedOff:\n setEqEffect(MusicObject::MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);\n break;\n case MusicVocal:\n setEqEffect(MusicObject::MIntList()<< 0<< 0<< 4<< 1<< -5<< -1<< 2<< -2<< -4<< -4<< 0);\n break;\n case MusicNICAM:\n setEqEffect(MusicObject::MIntList()<< 6<<-12<<-12<< -9<< -6<< -3<<-12<< -9<< -6<< -3<<-12);\n break;\n case MusicSubwoofer:\n setEqEffect(MusicObject::MIntList()<< 6<< 6<<-10<<-10<< 0<< 0<< -3<< -5<< -7<< -9<<-11);\n break;\n default:\n break;\n }\n}\n<commit_msg>fix enhanced music off[333333]<commit_after>#include \"musicplayer.h\"\n#include \"musicplaylist.h\"\n#include \"musicsettingmanager.h\"\n#include \"musicconnectionpool.h\"\n#include \"musicnumberdefine.h\"\n\/\/\/qmmp incldue\n#include \"soundcore.h\"\n\/\/\/\n#include <qmath.h>\n\nMusicPlayer::MusicPlayer(QObject *parent)\n : QObject(parent)\n{\n m_playlist = nullptr;\n m_state = StoppedState;\n m_musicEnhanced = EnhancedOff;\n m_music = new SoundCore(this);\n m_posOnCircle = 0;\n m_volumeMusic3D = 0;\n m_balance = 0;\n m_duration = 0;\n m_tryTimes = 0;\n\n setEnaleEffect(false);\n\n connect(&m_timer, SIGNAL(timeout()), SLOT(update()));\n M_CONNECTION_PTR->setValue(getClassName(), this);\n}\n\nMusicPlayer::~MusicPlayer()\n{\n delete m_music;\n}\n\nQString MusicPlayer::getClassName()\n{\n return staticMetaObject.className();\n}\n\nMusicPlayer::State MusicPlayer::state() const\n{\n return m_state;\n}\n\nvoid MusicPlayer::setPlaylist(MusicPlaylist *playlist)\n{\n delete m_playlist;\n m_playlist = playlist;\n}\n\nMusicPlaylist *MusicPlayer::playlist() const\n{\n return m_playlist;\n}\n\nqint64 MusicPlayer::duration() const\n{\n return m_music->totalTime();\n}\n\nqint64 MusicPlayer::position() const\n{\n return m_music->elapsed();\n}\n\nvoid MusicPlayer::playNext()\n{\n int index = m_playlist->currentIndex();\n m_playlist->setCurrentIndex((++index >= m_playlist->mediaCount()) ? 0 : index);\n}\n\nvoid MusicPlayer::playPrevious()\n{\n int index = m_playlist->currentIndex();\n m_playlist->setCurrentIndex((--index < 0) ? 0 : index );\n}\n\nint MusicPlayer::volume() const\n{\n return isMuted() ? 0 : m_music->volume();\n}\n\nvoid MusicPlayer::setVolume(int volume)\n{\n m_volumeMusic3D = volume;\n m_music->setVolume(volume);\n}\n\nbool MusicPlayer::isMuted() const\n{\n return m_music->isMuted();\n}\n\nvoid MusicPlayer::setMuted(bool muted)\n{\n m_volumeMusic3D = muted ? 0 : m_music->volume();\n m_music->setMuted(muted);\n}\n\nvoid MusicPlayer::setPosition(qint64 position)\n{\n m_music->seek(position);\n}\n\nvoid MusicPlayer::setMusicEnhanced(Enhanced type)\n{\n m_musicEnhanced = type;\n\n if(m_musicEnhanced == Music3D)\n {\n m_volumeMusic3D = volume();\n }\n else\n {\n m_music->setBalance(0);\n m_music->setVolume(m_volumeMusic3D, m_volumeMusic3D);\n m_music->setBalance(m_balance);\n setMusicEnhancedCase();\n }\n}\n\nMusicPlayer::Enhanced MusicPlayer::getMusicEnhanced() const\n{\n return m_musicEnhanced;\n}\n\nQStringList MusicPlayer::supportFormatsString()\n{\n return QStringList()<< \"mpc\" << \"wv\" << \"ogg\" << \"wav\" << \"au\" << \"snd\" << \"aif\" << \"aiff\" << \"8svx\"\n << \"sph\" << \"sf\" << \"voc\" << \"w64\" << \"cue\" << \"mp1\" << \"mp2\" << \"mp3\" << \"wav\"\n << \"ay\" << \"gms\" << \"gym\" << \"hes\" << \"kss\" << \"nsf\" << \"nsfe\" << \"sap\" << \"spc\"\n << \"vgm\" << \"vgz\" << \"flac\" << \"oga\" << \"ape\" << \"wma\" << \"ape\" << \"tta\" << \"m4a\"\n << \"ra\" << \"shn\" << \"vqf\" << \"ac3\" << \"mod\" << \"s3m\" << \"xm\" << \"it\" << \"669\"\n << \"amf\" << \"ams\" << \"dbm\" << \"dmf\" << \"dsm\" << \"far\" << \"mdl\" << \"med\" << \"mtm\"\n << \"okt\" << \"ptm\" << \"stm\" << \"ult\" << \"umx\" << \"mt2\" << \"psm\" << \"mdz\" << \"s3z\"\n << \"xmz\" << \"itz\" << \"mdr\" << \"s3r\" << \"xmr\" << \"itr\" << \"dgz\" << \"s3gz\" << \"xmgz\"\n << \"itgz\" << \"opus\" << \"mid\"\n#ifndef Q_OS_WIN\n << \"sid\" << \"mus\" << \"str\" << \"prg\" << \"P00\"\n#endif\n << \"aac\";\n}\n\nQStringList MusicPlayer::supportFormatsFilterString()\n{\n return QStringList()<< \"*.mpc\" << \"*.wv\" << \"*.ogg\" << \"*.wav\" << \"*.au\" << \"*.snd\" << \"*.aif\" << \"*.aiff\" << \"*.8svx\"\n << \"*.sph\" << \"*.sf\" << \"*.voc\" << \"*.w64\" << \"*.cue\" << \"*.mp1\" << \"*.mp2\" << \"*.mp3\" << \"*.wav\"\n << \"*.ay\" << \"*.gms\" << \"*.gym\" << \"*.hes\" << \"*.kss\" << \"*.nsf\" << \"*.nsfe\" << \"*.sap\" << \"*.spc\"\n << \"*.vgm\" << \"*.vgz\" << \"*.flac\" << \"*.oga\" << \"*.ape\" << \"*.wma\" << \"*.ape\" << \"*.tta\" << \"*.m4a\"\n << \"*.ra\" << \"*.shn\" << \"*.vqf\" << \"*.ac3\" << \"*.mod\" << \"*.s3m\" << \"*.xm\" << \"*.it\" << \"*.669\"\n << \"*.amf\" << \"*.ams\" << \"*.dbm\" << \"*.dmf\" << \"*.dsm\" << \"*.far\" << \"*.mdl\" << \"*.med\" << \"*.mtm\"\n << \"*.okt\" << \"*.ptm\" << \"*.stm\" << \"*.ult\" << \"*.umx\" << \"*.mt2\" << \"*.psm\" << \"*.mdz\" << \"*.s3z\"\n << \"*.xmz\" << \"*.itz\" << \"*.mdr\" << \"*.s3r\" << \"*.xmr\" << \"*.itr\" << \"*.dgz\" << \"*.s3gz\" << \"*.xmgz\"\n << \"*.itgz\" << \"*.opus\" << \"*.mid\"\n#ifndef Q_OS_WIN\n << \"*.sid\" << \"*.mus\" << \"*.str\" << \"*.prg\" << \"*.P00\"\n#endif\n << \"*.aac\";\n}\n\nQStringList MusicPlayer::supportFormatsFilterDialogString()\n{\n return QStringList()<< \"All File(*.*)\" << \"MusePack File(*.mpc)\" << \"WavPack File(*.wv)\" << \"Ogg Vorbis File(*.ogg)\"\n << \"PCM File(*.wav *.au *.snd *.aif *.aiff *.8svx *.sph *.sf *.voc *.w64)\"\n << \"CUE File(*.cue)\" << \"MPEG File(*.mp1 *.mp2 *.mp3 *.wav)\"\n << \"Game File(*.ay *.gms *.gym *.hes *.kss *.nsf *.nsfe *.sap *.spc *.vgm *.vgz)\"\n << \"FLAC File(*.flac *.oga)\" << \"Monkey's Audio File(*.ape)\"\n << \"Ogg Opus File(*.opus)\" << \"ADTS AAC File(*.aac)\" << \"MIDI File(*.mid)\"\n#ifndef Q_OS_WIN\n << \"SID File(*.sid *.mus *.str *.prg *.P00)\"\n#endif\n << \"FFmpeg File(*.wma *.ape *.tta *.m4a *.ra *.shn *.vqf *.ac3)\"\n << \"ModPlug File(*.mod *.s3m *.xm *.it *.669 *.amf *.ams *.dbm *.dmf *.dsm *.far,mdl *.med *.mtm \"\n \"*.okt *.ptm *.stm *.ult *.umx *.mt2 *.psm *.mdz *.s3z *.xmz *.itz *.mdr *.s3r *.xmr *.itr \"\n \"*.dgz *.s3gz *.xmgz *.itgz)\";\n}\n\nvoid MusicPlayer::play()\n{\n if(m_playlist->isEmpty())\n {\n m_state = StoppedState;\n return;\n }\n\n m_state = PlayingState;\n Qmmp::State state = m_music->state(); \/\/\/Get the current state of play\n if(m_currentMedia == m_playlist->currentMediaString() && state == Qmmp::Paused)\n {\n m_music->pause(); \/\/\/When the pause time for recovery\n m_timer.start(MT_S2MS);\n return;\n }\n\n m_currentMedia = m_playlist->currentMediaString();\n \/\/\/The current playback path\n if(!m_music->play(m_currentMedia))\n {\n m_state = StoppedState;\n return;\n }\n\n m_tryTimes = 0;\n m_timer.start(MT_S2MS);\n \/\/\/Every second emits a signal change information\n emit positionChanged(0);\n getCurrentDuration();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/Read the configuration settings for the sound\n int volume = M_SETTING_PTR->value(MusicSettingManager::VolumeChoiced).toInt();\n if(volume != -1)\n {\n setVolume(volume);\n }\n setSoundEffectVolume(M_SETTING_PTR->value(MusicSettingManager::EnhancedBalanceChoiced).toInt());\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n}\n\nvoid MusicPlayer::pause()\n{\n m_music->pause();\n m_timer.stop();\n m_state = PausedState;\n}\n\nvoid MusicPlayer::stop()\n{\n m_music->stop();\n m_timer.stop();\n m_state = StoppedState;\n}\n\nvoid MusicPlayer::setEqEffect(const MusicObject::MIntList &hz)\n{\n if(hz.count() != 11)\n {\n return;\n }\n\n EqSettings eq = m_music->eqSettings();\n eq.setPreamp(15 + hz[0]);\n eq.setEnabled(true);\n for(int i=0; i<EqSettings::EQ_BANDS_10; ++i)\n {\n eq.setGain(i, hz[i + 1]);\n }\n m_music->setEqSettings(eq);\n}\n\nvoid MusicPlayer::setEnaleEffect(bool enable)\n{\n if(enable == false)\n {\n setEqEffect(MusicObject::MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);\n }\n}\n\nvoid MusicPlayer::setEqInformation()\n{\n \/\/\/Read the equalizer parameters from a configuration file\n if(M_SETTING_PTR->value(MusicSettingManager::EqualizerEnableChoiced).toInt())\n {\n setEnaleEffect(true);\n QStringList eqValue = M_SETTING_PTR->value(MusicSettingManager::EqualizerValueChoiced).toString().split(',');\n if(eqValue.count() == 11)\n {\n MusicObject::MIntList hz;\n hz << eqValue[0].toInt() << eqValue[1].toInt() << eqValue[2].toInt()\n << eqValue[3].toInt() << eqValue[4].toInt() << eqValue[5].toInt()\n << eqValue[6].toInt() << eqValue[7].toInt() << eqValue[8].toInt()\n << eqValue[9].toInt() << eqValue[10].toInt();\n setEqEffect(hz);\n }\n }\n else\n {\n setEnaleEffect(false);\n }\n}\n\nvoid MusicPlayer::setSoundEffectVolume(int value)\n{\n m_balance = value;\n m_music->setBalance(value);\n}\n\nvoid MusicPlayer::removeCurrentMedia()\n{\n m_timer.stop();\n m_music->stop();\n}\n\nvoid MusicPlayer::update()\n{\n emit positionChanged( position() );\n\n if(m_musicEnhanced == Music3D && !m_music->isMuted())\n {\n \/\/\/3D music settings\n setEnaleEffect(false);\n m_posOnCircle += 0.5f;\n m_music->setVolume(abs(100 * cosf(m_posOnCircle)), abs(100 * sinf(m_posOnCircle * 0.5f)));\n }\n\n Qmmp::State state = m_music->state();\n if(state != Qmmp::Playing && state != Qmmp::Paused)\n {\n m_timer.stop();\n if(m_playlist->playbackMode() == MusicObject::MC_PlayOnce)\n {\n m_music->stop();\n emit positionChanged(0);\n emit stateChanged(StoppedState);\n return;\n }\n m_playlist->setCurrentIndex();\n if(m_playlist->playbackMode() == MusicObject::MC_PlayOrder &&\n m_playlist->currentIndex() == -1)\n {\n m_music->stop();\n emit positionChanged(0);\n emit stateChanged(StoppedState);\n return;\n }\n play();\n }\n}\n\nvoid MusicPlayer::getCurrentDuration()\n{\n qint64 dur = duration();\n if( (dur == 0 || m_duration == dur) && m_tryTimes++ < 10 )\n {\n QTimer::singleShot(50*MT_MS, this, SLOT(getCurrentDuration()));\n }\n else\n {\n emit durationChanged( m_duration = dur );\n }\n}\n\nvoid MusicPlayer::setMusicEnhancedCase()\n{\n switch(m_musicEnhanced)\n {\n case EnhancedOff:\n setEqEffect(MusicObject::MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);\n break;\n case MusicVocal:\n setEqEffect(MusicObject::MIntList()<< 0<< 0<< 4<< 1<< -5<< -1<< 2<< -2<< -4<< -4<< 0);\n break;\n case MusicNICAM:\n setEqEffect(MusicObject::MIntList()<< 6<<-12<<-12<< -9<< -6<< -3<<-12<< -9<< -6<< -3<<-12);\n break;\n case MusicSubwoofer:\n setEqEffect(MusicObject::MIntList()<< 6<< 6<<-10<<-10<< 0<< 0<< -3<< -5<< -7<< -9<<-11);\n break;\n default:\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ MiniDatabuf.cpp\n\/\/\n\/\/ Copyright (c) 2006-2007 Virtual Terrain Project and Stefan Roettger\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#include \"MiniDatabuf.h\"\n#include \"vtLog.h\"\n#include \"Projections.h\"\n#include \"MathTypes.h\"\n#include \"FilePath.h\"\n\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <float.h>\n\n#define ERRORMSG() VTLOG1(\"Error!\")\n\nint MiniDatabuf::MAGIC=12640;\n\nunsigned short int MiniDatabuf::INTEL_CHECK=1;\n\n\/\/ default constructor\nMiniDatabuf::MiniDatabuf()\n {\n xsize=ysize=zsize=0;\n tsteps=0;\n type=0;\n\n swx=swy=0.0f;\n nwx=nwy=0.0f;\n nex=ney=0.0f;\n sex=sey=0.0f;\n h0=dh=0.0f;\n t0=dt=0.0f;\n\n scaling=1.0f;\n bias=0.0f;\n\n data=NULL;\n bytes=0;\n }\n\nMiniDatabuf::~MiniDatabuf()\n{\n\trelease();\n}\n\n\/\/ set the geographic extents\nvoid MiniDatabuf::set_extents(float left, float right, float bottom, float top)\n{\n\tswx = left;\n\tswy = bottom;\n\tnwx = left;\n\tnwy = top;\n\tsex = right;\n\tsey = bottom;\n\tnex = right;\n\tney = top;\n}\n\n\/\/ set the geographic extents in LLWGS84\n\/\/ not supported in vtb::MiniDatabuf, requires subclassing from libMini::databuf\nvoid MiniDatabuf::set_LLWGS84extents(float left, float right, float bottom, float top) {}\n\n\/\/ allocate a new memory chunk\nvoid MiniDatabuf::alloc(unsigned int xs,unsigned int ys,unsigned int zs,unsigned int ts,unsigned int ty)\n {\n unsigned int bs,cs;\n\n unsigned char *byteptr;\n short int *shortptr;\n float *floatptr;\n\n unsigned int count;\n\n if (ty==0) bs=1;\n else if (ty==1) bs=2;\n else if (ty==2) bs=4;\n else if (ty==3) bs=3;\n else if (ty==4) bs=3;\n else if (ty==5) bs=4;\n else if (ty==6) bs=4;\n else ERRORMSG();\n\n cs=xs*ys*zs*ts;\n bs*=cs;\n\n if (ty==4 || ty==6) bs\/=6;\n\n if ((data=malloc(bs))==NULL) ERRORMSG();\n\n if (ty==1)\n for (shortptr=(short int *)data,count=0; count<cs; count++) *shortptr++=0;\n else if (ty==2)\n for (floatptr=(float *)data,count=0; count<cs; count++) *floatptr++=0.0f;\n else\n for (byteptr=(unsigned char *)data,count=0; count<bs; count++) *byteptr++=0;\n\n bytes=bs;\n\n xsize=xs;\n ysize=ys;\n zsize=zs;\n tsteps=ts;\n type=ty;\n }\n\n\/\/ reset buffer\nvoid MiniDatabuf::reset()\n {\n data=NULL;\n bytes=0;\n }\n\n\/\/ release buffer\nvoid MiniDatabuf::release()\n {\n if (data!=NULL) free(data);\n\n data=NULL;\n bytes=0;\n }\n\n\/\/ data is saved in MSB format\nvoid MiniDatabuf::savedata(const char *filename)\n {\n FILE *file;\n\n if (data==NULL) return;\n\n if (bytes==0) ERRORMSG();\n\n if ((file=vtFileOpen(filename,\"wb\"))==NULL) ERRORMSG();\n\n \/\/ save magic identifier\n fprintf(file,\"MAGIC=%d\\n\",MAGIC);\n\n \/\/ save mandatory metadata\n fprintf(file,\"xsize=%d\\n\",xsize);\n fprintf(file,\"ysize=%d\\n\",ysize);\n fprintf(file,\"zsize=%d\\n\",zsize);\n fprintf(file,\"tsteps=%d\\n\",tsteps);\n fprintf(file,\"type=%d\\n\",type);\n\n \/\/ save optional metadata\n fprintf(file,\"swx=%f\\n\",swx);\n fprintf(file,\"swy=%f\\n\",swy);\n fprintf(file,\"nwx=%f\\n\",nwx);\n fprintf(file,\"nwy=%f\\n\",nwy);\n fprintf(file,\"nex=%f\\n\",nex);\n fprintf(file,\"ney=%f\\n\",ney);\n fprintf(file,\"sex=%f\\n\",sex);\n fprintf(file,\"sey=%f\\n\",sey);\n fprintf(file,\"h0=%f\\n\",h0);\n fprintf(file,\"dh=%f\\n\",dh);\n fprintf(file,\"t0=%f\\n\",t0);\n fprintf(file,\"dt=%f\\n\",dt);\n\n \/\/ save optional scaling\n fprintf(file,\"scaling=%f\\n\",scaling);\n fprintf(file,\"bias=%f\\n\",bias);\n\n \/\/ save length of data chunk\n fprintf(file,\"bytes=%u\\n\",bytes);\n\n \/\/ write zero byte\n fputc(0, file);\n\n \/\/ save data chunk\n if (*((unsigned char *)(&INTEL_CHECK))==0)\n {\n if (fwrite(data,bytes,1,file)!=1) ERRORMSG();\n fclose(file);\n }\n else\n {\n swapbytes();\n if (fwrite(data,bytes,1,file)!=1) ERRORMSG();\n swapbytes();\n\n fclose(file);\n }\n }\n\n\/\/ swap byte ordering between MSB and LSB\nvoid MiniDatabuf::swapbytes()\n {\n unsigned int i,b;\n\n unsigned char *ptr,tmp;\n\n if (type==0 || (type>=3 && type<=6)) return;\n\n if (type==1) b=2;\n else if (type==2) b=4;\n else ERRORMSG();\n\n if (bytes==0 || bytes%b!=0) ERRORMSG();\n\n ptr=(unsigned char *)data+bytes;\n\n while (ptr!=data)\n {\n ptr-=b;\n\n for (i=0; i<(b>>1); i++)\n {\n tmp=ptr[i];\n ptr[i]=ptr[b-1-i];\n ptr[b-1-i]=tmp;\n }\n }\n }\n\nbool WriteTilesetHeader(const char *filename, int cols, int rows, int lod0size,\n\t\t\t\t\t\tconst DRECT &area, const vtProjection &proj,\n\t\t\t\t\t\tfloat minheight, float maxheight,\n\t\t\t\t\t\tLODMap *lodmap)\n{\n\tFILE *fp = vtFileOpen(filename, \"wb\");\n\tif (!fp)\n\t\treturn false;\n\n\tfprintf(fp, \"[TilesetDescription]\\n\");\n\tfprintf(fp, \"Columns=%d\\n\", cols);\n\tfprintf(fp, \"Rows=%d\\n\", rows);\n\tfprintf(fp, \"LOD0_Size=%d\\n\", lod0size);\n\tfprintf(fp, \"Extent_Left=%.16lg\\n\", area.left);\n\tfprintf(fp, \"Extent_Right=%.16lg\\n\", area.right);\n\tfprintf(fp, \"Extent_Bottom=%.16lg\\n\", area.bottom);\n\tfprintf(fp, \"Extent_Top=%.16lg\\n\", area.top);\n\t\/\/ write CRS, but pretty it up a bit\n\tOGRSpatialReference *poSimpleClone = proj.Clone();\n\tpoSimpleClone->GetRoot()->StripNodes( \"AXIS\" );\n\tpoSimpleClone->GetRoot()->StripNodes( \"AUTHORITY\" );\n\tchar *wkt;\n\tpoSimpleClone->exportToWkt(&wkt);\n\tfprintf(fp, \"CRS=%s\\n\", wkt);\n\tOGRFree(wkt);\t\/\/ Free CRS\n\tdelete poSimpleClone;\n\n\t\/\/ For elevation tilesets, also write vertical extents\n\tif (minheight != INVALID_ELEVATION)\n\t{\n\t\tfprintf(fp, \"Elevation_Min=%.f\\n\", minheight);\n\t\tfprintf(fp, \"Elevation_Max=%.f\\n\", maxheight);\n\t}\n\n\tif (lodmap != NULL)\n\t{\n\t\tint mmin, mmax;\n\t\tfor (int i = 0; i < rows; i++)\n\t\t{\n\t\t\tfprintf(fp, \"RowLODs %2d:\", i);\n\t\t\tfor (int j = 0; j < cols; j++)\n\t\t\t{\n\t\t\t\tlodmap->get(j, i, mmin, mmax);\n\t\t\t\tfprintf(fp, \" %d\/%d\", mmin, mmax);\n\t\t\t}\n\t\t\tfprintf(fp, \"\\n\");\n\t\t}\n\t}\n\n \/\/ create a transformation that will map from the current projection to Lat\/Lon WGS84\n vtProjection proj_llwgs84;\n proj_llwgs84.SetWellKnownGeogCS(\"WGS84\");\n OCT *LLWGS84transform=CreateCoordTransform(&proj,&proj_llwgs84);\n\n \/\/ write center point of the tileset in Lat\/Lon WGS84\n \/\/ this is helpful for libMini to compute an approximate translation\n double cx=(area.left+area.right)\/2;\n double cy=(area.bottom+area.top)\/2;\n if (LLWGS84transform->Transform(1,&cx,&cy)==1)\n fprintf(fp, \"CenterPoint_LLWGS84=(%.16lg,%.16lg)\\n\",cx,cy);\n\n \/\/ write north point of the tileset in Lat\/Lon WGS84\n \/\/ this is helpful for libMini to compute an approximate rotation\n double nx=(area.left+area.right)\/2;\n double ny=area.top;\n if (LLWGS84transform->Transform(1,&nx,&ny)==1)\n fprintf(fp, \"NorthPoint_LLWGS84=(%.16lg,%.16lg)\\n\",nx,ny);\n\n \/\/ delete Lat\/Lon WGS84 transformation\n delete LLWGS84transform;\n\n\tfclose(fp);\n\n\treturn true;\n}\n<commit_msg>add more information for libMini to .ini<commit_after>\/\/\n\/\/ MiniDatabuf.cpp\n\/\/\n\/\/ Copyright (c) 2006-2007 Virtual Terrain Project and Stefan Roettger\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#include \"MiniDatabuf.h\"\n#include \"vtLog.h\"\n#include \"Projections.h\"\n#include \"MathTypes.h\"\n#include \"FilePath.h\"\n\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <float.h>\n\n#define ERRORMSG() VTLOG1(\"Error!\")\n\nint MiniDatabuf::MAGIC=12640;\n\nunsigned short int MiniDatabuf::INTEL_CHECK=1;\n\n\/\/ default constructor\nMiniDatabuf::MiniDatabuf()\n {\n xsize=ysize=zsize=0;\n tsteps=0;\n type=0;\n\n swx=swy=0.0f;\n nwx=nwy=0.0f;\n nex=ney=0.0f;\n sex=sey=0.0f;\n h0=dh=0.0f;\n t0=dt=0.0f;\n\n scaling=1.0f;\n bias=0.0f;\n\n data=NULL;\n bytes=0;\n }\n\nMiniDatabuf::~MiniDatabuf()\n{\n\trelease();\n}\n\n\/\/ set the geographic extents\nvoid MiniDatabuf::set_extents(float left, float right, float bottom, float top)\n{\n\tswx = left;\n\tswy = bottom;\n\tnwx = left;\n\tnwy = top;\n\tsex = right;\n\tsey = bottom;\n\tnex = right;\n\tney = top;\n}\n\n\/\/ set the geographic extents in LLWGS84\n\/\/ not supported in vtb::MiniDatabuf, requires subclassing from libMini::databuf\nvoid MiniDatabuf::set_LLWGS84extents(float left, float right, float bottom, float top) {}\n\n\/\/ allocate a new memory chunk\nvoid MiniDatabuf::alloc(unsigned int xs,unsigned int ys,unsigned int zs,unsigned int ts,unsigned int ty)\n {\n unsigned int bs,cs;\n\n unsigned char *byteptr;\n short int *shortptr;\n float *floatptr;\n\n unsigned int count;\n\n if (ty==0) bs=1;\n else if (ty==1) bs=2;\n else if (ty==2) bs=4;\n else if (ty==3) bs=3;\n else if (ty==4) bs=3;\n else if (ty==5) bs=4;\n else if (ty==6) bs=4;\n else ERRORMSG();\n\n cs=xs*ys*zs*ts;\n bs*=cs;\n\n if (ty==4 || ty==6) bs\/=6;\n\n if ((data=malloc(bs))==NULL) ERRORMSG();\n\n if (ty==1)\n for (shortptr=(short int *)data,count=0; count<cs; count++) *shortptr++=0;\n else if (ty==2)\n for (floatptr=(float *)data,count=0; count<cs; count++) *floatptr++=0.0f;\n else\n for (byteptr=(unsigned char *)data,count=0; count<bs; count++) *byteptr++=0;\n\n bytes=bs;\n\n xsize=xs;\n ysize=ys;\n zsize=zs;\n tsteps=ts;\n type=ty;\n }\n\n\/\/ reset buffer\nvoid MiniDatabuf::reset()\n {\n data=NULL;\n bytes=0;\n }\n\n\/\/ release buffer\nvoid MiniDatabuf::release()\n {\n if (data!=NULL) free(data);\n\n data=NULL;\n bytes=0;\n }\n\n\/\/ data is saved in MSB format\nvoid MiniDatabuf::savedata(const char *filename)\n {\n FILE *file;\n\n if (data==NULL) return;\n\n if (bytes==0) ERRORMSG();\n\n if ((file=vtFileOpen(filename,\"wb\"))==NULL) ERRORMSG();\n\n \/\/ save magic identifier\n fprintf(file,\"MAGIC=%d\\n\",MAGIC);\n\n \/\/ save mandatory metadata\n fprintf(file,\"xsize=%d\\n\",xsize);\n fprintf(file,\"ysize=%d\\n\",ysize);\n fprintf(file,\"zsize=%d\\n\",zsize);\n fprintf(file,\"tsteps=%d\\n\",tsteps);\n fprintf(file,\"type=%d\\n\",type);\n\n \/\/ save optional metadata\n fprintf(file,\"swx=%f\\n\",swx);\n fprintf(file,\"swy=%f\\n\",swy);\n fprintf(file,\"nwx=%f\\n\",nwx);\n fprintf(file,\"nwy=%f\\n\",nwy);\n fprintf(file,\"nex=%f\\n\",nex);\n fprintf(file,\"ney=%f\\n\",ney);\n fprintf(file,\"sex=%f\\n\",sex);\n fprintf(file,\"sey=%f\\n\",sey);\n fprintf(file,\"h0=%f\\n\",h0);\n fprintf(file,\"dh=%f\\n\",dh);\n fprintf(file,\"t0=%f\\n\",t0);\n fprintf(file,\"dt=%f\\n\",dt);\n\n \/\/ save optional scaling\n fprintf(file,\"scaling=%f\\n\",scaling);\n fprintf(file,\"bias=%f\\n\",bias);\n\n \/\/ save length of data chunk\n fprintf(file,\"bytes=%u\\n\",bytes);\n\n \/\/ write zero byte\n fputc(0, file);\n\n \/\/ save data chunk\n if (*((unsigned char *)(&INTEL_CHECK))==0)\n {\n if (fwrite(data,bytes,1,file)!=1) ERRORMSG();\n fclose(file);\n }\n else\n {\n swapbytes();\n if (fwrite(data,bytes,1,file)!=1) ERRORMSG();\n swapbytes();\n\n fclose(file);\n }\n }\n\n\/\/ swap byte ordering between MSB and LSB\nvoid MiniDatabuf::swapbytes()\n {\n unsigned int i,b;\n\n unsigned char *ptr,tmp;\n\n if (type==0 || (type>=3 && type<=6)) return;\n\n if (type==1) b=2;\n else if (type==2) b=4;\n else ERRORMSG();\n\n if (bytes==0 || bytes%b!=0) ERRORMSG();\n\n ptr=(unsigned char *)data+bytes;\n\n while (ptr!=data)\n {\n ptr-=b;\n\n for (i=0; i<(b>>1); i++)\n {\n tmp=ptr[i];\n ptr[i]=ptr[b-1-i];\n ptr[b-1-i]=tmp;\n }\n }\n }\n\nint mapEPSG2MINI(int epsgdatum)\n {\n static const int NAD27=1;\n static const int WGS72=2;\n static const int WGS84=3;\n static const int NAD83=4;\n static const int SPHERE=5;\n static const int ED50=6;\n static const int ED79=7;\n static const int OHD=8;\n\n switch (epsgdatum)\n {\n case 6608: return(NAD27);\n case 6322: return(WGS72);\n case 6326: return(WGS84);\n case 6269: return(NAD83);\n case 6230: return(ED50);\n case 6231: return(ED79);\n case 6135: return(OHD);\n }\n\n return(SPHERE);\n }\n\nbool WriteTilesetHeader(const char *filename, int cols, int rows, int lod0size,\n\t\t\t\t\t\tconst DRECT &area, const vtProjection &proj,\n\t\t\t\t\t\tfloat minheight, float maxheight,\n\t\t\t\t\t\tLODMap *lodmap)\n{\n\tFILE *fp = vtFileOpen(filename, \"wb\");\n\tif (!fp)\n\t\treturn false;\n\n\tfprintf(fp, \"[TilesetDescription]\\n\");\n\tfprintf(fp, \"Columns=%d\\n\", cols);\n\tfprintf(fp, \"Rows=%d\\n\", rows);\n\tfprintf(fp, \"LOD0_Size=%d\\n\", lod0size);\n\tfprintf(fp, \"Extent_Left=%.16lg\\n\", area.left);\n\tfprintf(fp, \"Extent_Right=%.16lg\\n\", area.right);\n\tfprintf(fp, \"Extent_Bottom=%.16lg\\n\", area.bottom);\n\tfprintf(fp, \"Extent_Top=%.16lg\\n\", area.top);\n\t\/\/ write CRS, but pretty it up a bit\n\tOGRSpatialReference *poSimpleClone = proj.Clone();\n\tpoSimpleClone->GetRoot()->StripNodes( \"AXIS\" );\n\tpoSimpleClone->GetRoot()->StripNodes( \"AUTHORITY\" );\n\tchar *wkt;\n\tpoSimpleClone->exportToWkt(&wkt);\n\tfprintf(fp, \"CRS=%s\\n\", wkt);\n\tOGRFree(wkt);\t\/\/ Free CRS\n\tdelete poSimpleClone;\n\n\t\/\/ For elevation tilesets, also write vertical extents\n\tif (minheight != INVALID_ELEVATION)\n\t{\n\t\tfprintf(fp, \"Elevation_Min=%.f\\n\", minheight);\n\t\tfprintf(fp, \"Elevation_Max=%.f\\n\", maxheight);\n\t}\n\n\tif (lodmap != NULL)\n\t{\n\t\tint mmin, mmax;\n\t\tfor (int i = 0; i < rows; i++)\n\t\t{\n\t\t\tfprintf(fp, \"RowLODs %2d:\", i);\n\t\t\tfor (int j = 0; j < cols; j++)\n\t\t\t{\n\t\t\t\tlodmap->get(j, i, mmin, mmax);\n\t\t\t\tfprintf(fp, \" %d\/%d\", mmin, mmax);\n\t\t\t}\n\t\t\tfprintf(fp, \"\\n\");\n\t\t}\n\t}\n\n \/\/ create a transformation that will map from the current projection to Lat\/Lon WGS84\n vtProjection proj_llwgs84;\n proj_llwgs84.SetWellKnownGeogCS(\"WGS84\");\n OCT *LLWGS84transform=CreateCoordTransform(&proj,&proj_llwgs84);\n\n \/\/ write center point of the tileset in Lat\/Lon WGS84\n \/\/ this is helpful for libMini to compute an approximate translation\n double cx=(area.left+area.right)\/2;\n double cy=(area.bottom+area.top)\/2;\n if (LLWGS84transform->Transform(1,&cx,&cy)==1)\n fprintf(fp, \"CenterPoint_LLWGS84=(%.16lg,%.16lg)\\n\",cx,cy);\n\n \/\/ write north point of the tileset in Lat\/Lon WGS84\n \/\/ this is helpful for libMini to compute an approximate rotation\n double nx=(area.left+area.right)\/2;\n double ny=area.top;\n if (LLWGS84transform->Transform(1,&nx,&ny)==1)\n fprintf(fp, \"NorthPoint_LLWGS84=(%.16lg,%.16lg)\\n\",nx,ny);\n\n \/\/ delete Lat\/Lon WGS84 transformation\n delete LLWGS84transform;\n\n \/\/ write Lat\/Lon info\n \/\/ this is helpful for libMini to easily identify geo-graphic coordinates\n int latlon=proj.IsGeographic();\n int llepsgdatum=proj.GetDatum();\n int lldatum=mapEPSG2MINI(llepsgdatum);\n fprintf(fp, \"CoordSys_LL=(%d,%d)\\n\",latlon,lldatum);\n\n \/\/ write UTM zone and datum\n \/\/ this is helpful for libMini to easily identify UTM coordinates\n int utmzone=proj.GetUTMZone();\n int utmepsgdatum=proj.GetDatum();\n int utmdatum=mapEPSG2MINI(utmepsgdatum);\n fprintf(fp, \"CoordSys_UTM=(%d,%d)\\n\",utmzone,utmdatum);\n\n fclose(fp);\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2008, 2009 Free Software Foundation, Inc.\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n\/\/#define NDEBUG\n#include \"radioInterface.h\"\n#include <Logger.h>\n\n\nGSM::Time VectorQueue::nextTime() const\n{\n GSM::Time retVal;\n ScopedLock lock(mLock);\n while (mQ.size()==0) mWriteSignal.wait(mLock);\n return mQ.top()->time();\n}\n\nradioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime)\n{\n ScopedLock lock(mLock);\n if ((mQ.size()==0)) {\n return NULL;\n }\n if (mQ.top()->time() < targTime) {\n radioVector* retVal = mQ.top();\n mQ.pop();\n return retVal;\n }\n return NULL;\n}\n\n\nradioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime)\n{\n ScopedLock lock(mLock);\n if ((mQ.size()==0)) {\n return NULL;\n }\n if (mQ.top()->time() == targTime) {\n radioVector* retVal = mQ.top();\n mQ.pop();\n return retVal;\n }\n return NULL;\n}\n\n\n\nRadioInterface::RadioInterface(RadioDevice *wRadio,\n int wReceiveOffset,\n\t\t\t int wRadioOversampling,\n\t\t\t int wTransceiverOversampling,\n\t\t\t GSM::Time wStartTime)\n\n{\n underrun = false;\n \n sendCursor = 0; \n rcvCursor = 0;\n mOn = false;\n \n mRadio = wRadio;\n receiveOffset = wReceiveOffset;\n samplesPerSymbol = wRadioOversampling;\n mClock.set(wStartTime);\n powerScaling = 1.0;\n loadTest = false;\n}\n\nRadioInterface::~RadioInterface(void) {\n if (rcvBuffer!=NULL) delete rcvBuffer;\n \/\/mReceiveFIFO.clear();\n}\n\ndouble RadioInterface::fullScaleInputValue(void) {\n return mRadio->fullScaleInputValue();\n}\n\ndouble RadioInterface::fullScaleOutputValue(void) {\n return mRadio->fullScaleOutputValue();\n}\n\n\nvoid RadioInterface::setPowerAttenuation(double dBAtten)\n{\n float HWdBAtten = mRadio->setTxGain(-dBAtten);\n dBAtten -= (-HWdBAtten);\n float linearAtten = powf(10.0F,0.1F*dBAtten);\n if (linearAtten < 1.0)\n powerScaling = 1.0;\n else\n powerScaling = 1.0\/sqrt(linearAtten);\n LOG(INFO) << \"setting HW gain to \" << HWdBAtten << \" and power scaling to \" << powerScaling;\n}\n\n\nshort *RadioInterface::radioifyVector(signalVector &wVector, short *retVector, double scale, bool zeroOut) \n{\n\n\n signalVector::iterator itr = wVector.begin();\n short *shortItr = retVector;\n if (zeroOut) {\n while (itr < wVector.end()) {\n *shortItr++ = 0;\n *shortItr++ = 0;\n itr++;\n }\n }\n else if (scale != 1.0) { \n while (itr < wVector.end()) {\n *shortItr++ = (short) (itr->real()*scale);\n *shortItr++ = (short) (itr->imag()*scale);\n itr++;\n }\n }\n else {\n while (itr < wVector.end()) {\n *shortItr++ = (short) (itr->real());\n *shortItr++ = (short) (itr->imag());\n itr++;\n }\n }\n\n return retVector;\n\n}\n\nvoid RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector)\n{\n \n signalVector::iterator itr = newVector.begin();\n short *shortItr = shortVector;\n while (itr < newVector.end()) {\n *itr++ = Complex<float>(*shortItr,*(shortItr+1));\n \/\/LOG(DEBUG) << (*(itr-1));\n shortItr += 2;\n }\n\n}\n\n\nbool started = false;\n\nvoid RadioInterface::pushBuffer(void) {\n\n if (sendCursor < 2*INCHUNK*samplesPerSymbol) return;\n\n \/\/ send resampleVector\n int samplesWritten = mRadio->writeSamples(sendBuffer,\n\t\t\t\t\t INCHUNK*samplesPerSymbol,\n\t\t\t\t\t &underrun,\n\t\t\t\t\t writeTimestamp); \n \/\/LOG(DEBUG) << \"writeTimestamp: \" << writeTimestamp << \", samplesWritten: \" << samplesWritten;\n \n writeTimestamp += (TIMESTAMP) samplesWritten;\n\n if (sendCursor > 2*samplesWritten) \n memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten));\n sendCursor = sendCursor - 2*samplesWritten;\n}\n\n\nvoid RadioInterface::pullBuffer(void)\n{\n \n bool localUnderrun;\n\n \/\/ receive receiveVector\n short* shortVector = rcvBuffer+rcvCursor; \n \/\/LOG(DEBUG) << \"Reading USRP samples at timestamp \" << readTimestamp;\n int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun);\n underrun |= localUnderrun;\n readTimestamp += (TIMESTAMP) samplesRead;\n while (samplesRead < OUTCHUNK*samplesPerSymbol) {\n int oldSamplesRead = samplesRead;\n samplesRead += mRadio->readSamples(shortVector+2*samplesRead,\n\t\t\t\t OUTCHUNK*samplesPerSymbol-samplesRead,\n\t\t\t\t &overrun,\n\t\t\t\t readTimestamp,\n\t\t\t\t &localUnderrun);\n underrun |= localUnderrun;\n readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);\n }\n \/\/LOG(DEBUG) << \"samplesRead \" << samplesRead;\n\n rcvCursor += samplesRead*2;\n\n}\n\nbool RadioInterface::tuneTx(double freq)\n{\n return mRadio->setTxFreq(freq);\n}\n\nbool RadioInterface::tuneRx(double freq)\n{\n return mRadio->setRxFreq(freq);\n}\n\n\nvoid RadioInterface::start()\n{\n LOG(INFO) << \"starting radio interface...\";\n mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,\n (void*)this);\n writeTimestamp = mRadio->initialWriteTimestamp();\n readTimestamp = mRadio->initialReadTimestamp();\n mRadio->start(); \n LOG(DEBUG) << \"Radio started\";\n mRadio->updateAlignment(writeTimestamp-10000); \n mRadio->updateAlignment(writeTimestamp-10000);\n\n sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol];\n rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol];\n \n mOn = true;\n\n}\n\nvoid *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)\n{\n while (1) {\n radioInterface->alignRadio();\n pthread_testcancel();\n }\n return NULL;\n}\n\nvoid RadioInterface::alignRadio() {\n sleep(60);\n mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);\n}\n\nvoid RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) {\n\n if (!mOn) return;\n\n radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst);\n\n sendCursor += (radioBurst.size()*2);\n\n pushBuffer();\n}\n\nvoid RadioInterface::driveReceiveRadio() {\n\n if (!mOn) return;\n\n if (mReceiveFIFO.size() > 8) return;\n\n pullBuffer();\n\n GSM::Time rcvClock = mClock.get();\n rcvClock.decTN(receiveOffset);\n unsigned tN = rcvClock.TN();\n int rcvSz = rcvCursor\/2;\n int readSz = 0;\n const int symbolsPerSlot = gSlotLen + 8;\n\n \/\/ while there's enough data in receive buffer, form received \n \/\/ GSM bursts and pass up to Transceiver\n \/\/ Using the 157-156-156-156 symbols per timeslot format.\n while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {\n signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);\n unRadioifyVector(rcvBuffer+readSz*2,rxVector);\n GSM::Time tmpTime = rcvClock;\n if (rcvClock.FN() >= 0) {\n \/\/LOG(DEBUG) << \"FN: \" << rcvClock.FN();\n radioVector *rxBurst = NULL;\n if (!loadTest)\n rxBurst = new radioVector(rxVector,tmpTime);\n else {\n\tif (tN % 4 == 0)\n\t rxBurst = new radioVector(*finalVec9,tmpTime);\n else\n rxBurst = new radioVector(*finalVec,tmpTime); \n }\n mReceiveFIFO.put(rxBurst); \n }\n mClock.incTN(); \n rcvClock.incTN();\n \/\/if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);\n \/\/LOG(DEBUG) << \"receiveFIFO: wrote radio vector at time: \" << mClock.get() << \", new size: \" << mReceiveFIFO.size() ;\n readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;\n rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;\n\n tN = rcvClock.TN();\n }\n\n if (readSz > 0) { \n memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz));\n rcvCursor = rcvCursor-2*readSz;\n }\n} \n \n<commit_msg>uhd: set attenuation relative to max RF gain<commit_after>\/*\n* Copyright 2008, 2009 Free Software Foundation, Inc.\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n\/\/#define NDEBUG\n#include \"radioInterface.h\"\n#include <Logger.h>\n\n\nGSM::Time VectorQueue::nextTime() const\n{\n GSM::Time retVal;\n ScopedLock lock(mLock);\n while (mQ.size()==0) mWriteSignal.wait(mLock);\n return mQ.top()->time();\n}\n\nradioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime)\n{\n ScopedLock lock(mLock);\n if ((mQ.size()==0)) {\n return NULL;\n }\n if (mQ.top()->time() < targTime) {\n radioVector* retVal = mQ.top();\n mQ.pop();\n return retVal;\n }\n return NULL;\n}\n\n\nradioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime)\n{\n ScopedLock lock(mLock);\n if ((mQ.size()==0)) {\n return NULL;\n }\n if (mQ.top()->time() == targTime) {\n radioVector* retVal = mQ.top();\n mQ.pop();\n return retVal;\n }\n return NULL;\n}\n\n\n\nRadioInterface::RadioInterface(RadioDevice *wRadio,\n int wReceiveOffset,\n\t\t\t int wRadioOversampling,\n\t\t\t int wTransceiverOversampling,\n\t\t\t GSM::Time wStartTime)\n\n{\n underrun = false;\n \n sendCursor = 0; \n rcvCursor = 0;\n mOn = false;\n \n mRadio = wRadio;\n receiveOffset = wReceiveOffset;\n samplesPerSymbol = wRadioOversampling;\n mClock.set(wStartTime);\n powerScaling = 1.0;\n loadTest = false;\n}\n\nRadioInterface::~RadioInterface(void) {\n if (rcvBuffer!=NULL) delete rcvBuffer;\n \/\/mReceiveFIFO.clear();\n}\n\ndouble RadioInterface::fullScaleInputValue(void) {\n return mRadio->fullScaleInputValue();\n}\n\ndouble RadioInterface::fullScaleOutputValue(void) {\n return mRadio->fullScaleOutputValue();\n}\n\n\nvoid RadioInterface::setPowerAttenuation(double dBAtten)\n{\n double HWatten = mRadio->setTxGain(mRadio->maxTxGain() - atten);\n atten -= (-HWatten);\n if (atten < 1.0)\n powerScaling = 1.0;\n else\n powerScaling = 1.0\/sqrt(linearAtten);\n LOG(INFO) << \"setting HW gain to \" << HWdBAtten << \" and power scaling to \" << powerScaling;\n}\n\n\nshort *RadioInterface::radioifyVector(signalVector &wVector, short *retVector, double scale, bool zeroOut) \n{\n\n\n signalVector::iterator itr = wVector.begin();\n short *shortItr = retVector;\n if (zeroOut) {\n while (itr < wVector.end()) {\n *shortItr++ = 0;\n *shortItr++ = 0;\n itr++;\n }\n }\n else if (scale != 1.0) { \n while (itr < wVector.end()) {\n *shortItr++ = (short) (itr->real()*scale);\n *shortItr++ = (short) (itr->imag()*scale);\n itr++;\n }\n }\n else {\n while (itr < wVector.end()) {\n *shortItr++ = (short) (itr->real());\n *shortItr++ = (short) (itr->imag());\n itr++;\n }\n }\n\n return retVector;\n\n}\n\nvoid RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector)\n{\n \n signalVector::iterator itr = newVector.begin();\n short *shortItr = shortVector;\n while (itr < newVector.end()) {\n *itr++ = Complex<float>(*shortItr,*(shortItr+1));\n \/\/LOG(DEBUG) << (*(itr-1));\n shortItr += 2;\n }\n\n}\n\n\nbool started = false;\n\nvoid RadioInterface::pushBuffer(void) {\n\n if (sendCursor < 2*INCHUNK*samplesPerSymbol) return;\n\n \/\/ send resampleVector\n int samplesWritten = mRadio->writeSamples(sendBuffer,\n\t\t\t\t\t INCHUNK*samplesPerSymbol,\n\t\t\t\t\t &underrun,\n\t\t\t\t\t writeTimestamp); \n \/\/LOG(DEBUG) << \"writeTimestamp: \" << writeTimestamp << \", samplesWritten: \" << samplesWritten;\n \n writeTimestamp += (TIMESTAMP) samplesWritten;\n\n if (sendCursor > 2*samplesWritten) \n memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten));\n sendCursor = sendCursor - 2*samplesWritten;\n}\n\n\nvoid RadioInterface::pullBuffer(void)\n{\n \n bool localUnderrun;\n\n \/\/ receive receiveVector\n short* shortVector = rcvBuffer+rcvCursor; \n \/\/LOG(DEBUG) << \"Reading USRP samples at timestamp \" << readTimestamp;\n int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun);\n underrun |= localUnderrun;\n readTimestamp += (TIMESTAMP) samplesRead;\n while (samplesRead < OUTCHUNK*samplesPerSymbol) {\n int oldSamplesRead = samplesRead;\n samplesRead += mRadio->readSamples(shortVector+2*samplesRead,\n\t\t\t\t OUTCHUNK*samplesPerSymbol-samplesRead,\n\t\t\t\t &overrun,\n\t\t\t\t readTimestamp,\n\t\t\t\t &localUnderrun);\n underrun |= localUnderrun;\n readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);\n }\n \/\/LOG(DEBUG) << \"samplesRead \" << samplesRead;\n\n rcvCursor += samplesRead*2;\n\n}\n\nbool RadioInterface::tuneTx(double freq)\n{\n return mRadio->setTxFreq(freq);\n}\n\nbool RadioInterface::tuneRx(double freq)\n{\n return mRadio->setRxFreq(freq);\n}\n\n\nvoid RadioInterface::start()\n{\n LOG(INFO) << \"starting radio interface...\";\n mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,\n (void*)this);\n writeTimestamp = mRadio->initialWriteTimestamp();\n readTimestamp = mRadio->initialReadTimestamp();\n mRadio->start(); \n LOG(DEBUG) << \"Radio started\";\n mRadio->updateAlignment(writeTimestamp-10000); \n mRadio->updateAlignment(writeTimestamp-10000);\n\n sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol];\n rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol];\n \n mOn = true;\n\n}\n\nvoid *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)\n{\n while (1) {\n radioInterface->alignRadio();\n pthread_testcancel();\n }\n return NULL;\n}\n\nvoid RadioInterface::alignRadio() {\n sleep(60);\n mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);\n}\n\nvoid RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) {\n\n if (!mOn) return;\n\n radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst);\n\n sendCursor += (radioBurst.size()*2);\n\n pushBuffer();\n}\n\nvoid RadioInterface::driveReceiveRadio() {\n\n if (!mOn) return;\n\n if (mReceiveFIFO.size() > 8) return;\n\n pullBuffer();\n\n GSM::Time rcvClock = mClock.get();\n rcvClock.decTN(receiveOffset);\n unsigned tN = rcvClock.TN();\n int rcvSz = rcvCursor\/2;\n int readSz = 0;\n const int symbolsPerSlot = gSlotLen + 8;\n\n \/\/ while there's enough data in receive buffer, form received \n \/\/ GSM bursts and pass up to Transceiver\n \/\/ Using the 157-156-156-156 symbols per timeslot format.\n while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {\n signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);\n unRadioifyVector(rcvBuffer+readSz*2,rxVector);\n GSM::Time tmpTime = rcvClock;\n if (rcvClock.FN() >= 0) {\n \/\/LOG(DEBUG) << \"FN: \" << rcvClock.FN();\n radioVector *rxBurst = NULL;\n if (!loadTest)\n rxBurst = new radioVector(rxVector,tmpTime);\n else {\n\tif (tN % 4 == 0)\n\t rxBurst = new radioVector(*finalVec9,tmpTime);\n else\n rxBurst = new radioVector(*finalVec,tmpTime); \n }\n mReceiveFIFO.put(rxBurst); \n }\n mClock.incTN(); \n rcvClock.incTN();\n \/\/if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);\n \/\/LOG(DEBUG) << \"receiveFIFO: wrote radio vector at time: \" << mClock.get() << \", new size: \" << mReceiveFIFO.size() ;\n readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;\n rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;\n\n tN = rcvClock.TN();\n }\n\n if (readSz > 0) { \n memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz));\n rcvCursor = rcvCursor-2*readSz;\n }\n} \n \n<|endoftext|>"} {"text":"<commit_before>\/** events.cc -*- C++ -*-\n Rémi Attab, 18 Apr 2014\n Copyright (c) 2014 Datacratic. All rights reserved.\n\n Publishable event implementation.\n\n*\/\n\n#include \"events.h\"\n#include \"soa\/service\/zmq_endpoint.h\"\n#include \"soa\/service\/zmq_named_pub_sub.h\"\n\nusing namespace std;\nusing namespace ML;\n\nnamespace RTBKIT {\n\n\n\/******************************************************************************\/\n\/* UTILS *\/\n\/******************************************************************************\/\n\nnamespace {\n\nstd::string publishTimestamp()\n{\n return Date::now().print(5);\n}\n\n} \/\/ namespace anonymous\n\n\n\/******************************************************************************\/\n\/* MATCHED WIN LOSS *\/\n\/******************************************************************************\/\n\nvoid\nMatchedWinLoss::\ninitFinishedInfo(const FinishedInfo& info)\n{\n auctionId = info.auctionId;\n impId = info.adSpotId;\n winPrice = info.winPrice;\n rawWinPrice = info.rawWinPrice;\n response = info.bid;\n requestStr = info.bidRequestStr;\n requestStrFormat = info.bidRequestStrFormat;\n request = info.bidRequest;\n meta = info.winMeta;\n augmentations = info.augmentations;\n}\n\nvoid\nMatchedWinLoss::\ninitMisc(const PostAuctionEvent& event)\n{\n uids = event.uids;\n timestamp = event.timestamp;\n}\n\nvoid\nMatchedWinLoss::\ninitMisc(Date timestamp, UserIds uids)\n{\n this->timestamp = timestamp;\n this->uids = std::move(uids);\n}\n\n\nMatchedWinLoss::\nMatchedWinLoss(\n Type type,\n Confidence confidence,\n const PostAuctionEvent& event,\n const FinishedInfo& info) :\n type(type), confidence(confidence)\n{\n initFinishedInfo(info);\n initMisc(event);\n}\n\n\nMatchedWinLoss::\n MatchedWinLoss(\n Type type,\n Confidence confidence,\n const FinishedInfo& info,\n Date timestamp,\n UserIds uids) :\n type(type), confidence(confidence)\n{\n initFinishedInfo(info);\n initMisc(timestamp, std::move(uids));\n}\n\n\n\nstd::string\nMatchedWinLoss::\ntypeString() const\n{\n switch (type) {\n case LateWin:\n case Win: return \"WIN\";\n case Loss: return \"LOSS\";\n }\n ExcAssert(false);\n}\n\nstd::string\nMatchedWinLoss::\nconfidenceString() const\n{\n switch (confidence) {\n case Inferred: return \"inferred\";\n case Guaranteed: return \"guaranteed\";\n }\n\n ExcAssert(false);\n}\n\nsize_t\nMatchedWinLoss::\nimpIndex() const\n{\n return request->findAdSpotIndex(impId);\n}\n\n\nvoid\nMatchedWinLoss::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"MATCHED\" + typeString(), \/\/ 0\n publishTimestamp(), \/\/ 1\n\n auctionId.toString(), \/\/ 2\n std::to_string(impIndex()), \/\/ 3\n response.agent, \/\/ 4\n response.account.at(1, \"\"), \/\/ 5\n\n winPrice.toString(), \/\/ 6\n response.price.maxPrice.toString(), \/\/ 7\n std::to_string(response.price.priority), \/\/ 8\n\n requestStr, \/\/ 9\n response.bidData, \/\/ 10\n response.meta, \/\/ 11\n\n \/\/ This is where things start to get weird.\n\n std::to_string(response.creativeId), \/\/ 12\n response.creativeName, \/\/ 13\n response.account.at(0, \"\"), \/\/ 14\n\n uids.toJsonStr(), \/\/ 15\n meta, \/\/ 16\n\n \/\/ And this is where we lose all pretenses of sanity.\n\n response.account.at(0, \"\"), \/\/ 17\n impId.toString(), \/\/ 18\n response.account.toString(), \/\/ 19\n\n \/\/ Ok back to sanity now.\n\n requestStrFormat, \/\/ 20\n rawWinPrice.toString() \/\/ 21\n );\n}\n\n\n\/******************************************************************************\/\n\/* MATCHED CAMPAIGN EVENT *\/\n\/******************************************************************************\/\n\nMatchedCampaignEvent::\nMatchedCampaignEvent(std::string label, const FinishedInfo& info) :\n label(std::move(label)),\n auctionId(info.auctionId),\n impId(info.adSpotId),\n account(info.bid.account),\n requestStr(info.bidRequestStr),\n request(info.bidRequest),\n requestStrFormat(info.bidRequestStrFormat),\n bid(info.bidToJson()),\n win(info.winToJson()),\n campaignEvents(info.campaignEvents.toJson()),\n visits(info.visitsToJson()),\n augmentations(info.augmentations)\n{\n auto it = std::find_if(info.campaignEvents.begin(), info.campaignEvents.end(),\n [&](const CampaignEvent& event) {\n return event.label_ == label;\n }\n );\n\n if(it != info.campaignEvents.end())\n timestamp = it->time_;\n}\nsize_t\nMatchedCampaignEvent::\nimpIndex() const\n{\n return request->findAdSpotIndex(impId);\n}\n\nvoid\nMatchedCampaignEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"MATCHED\" + label, \/\/ 0\n publishTimestamp(), \/\/ 1\n\n auctionId.toString(), \/\/ 2\n impId.toString(), \/\/ 3\n requestStr, \/\/ 4\n\n bid, \/\/ 5\n win, \/\/ 6\n campaignEvents, \/\/ 7\n visits, \/\/ 8\n\n account.at(0, \"\"), \/\/ 9\n account.at(1, \"\"), \/\/ 10\n account.toString(), \/\/ 11\n\n requestStrFormat \/\/ 12\n );\n}\n\n\n\/******************************************************************************\/\n\/* UNMATCHED EVENT *\/\n\/******************************************************************************\/\n\nUnmatchedEvent::\nUnmatchedEvent(std::string reason, PostAuctionEvent event) :\n reason(std::move(reason)),\n event(std::move(event))\n{}\n\nvoid\nUnmatchedEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"UNMATCHED\" + event.label, \/\/ 0\n publishTimestamp(), \/\/ 1\n\n reason, \/\/ 2\n event.auctionId.toString(), \/\/ 3\n event.adSpotId.toString(), \/\/ 4\n\n std::to_string(event.timestamp.secondsSinceEpoch()), \/\/ 5\n event.metadata.toJson() \/\/ 6\n );\n}\n\n\n\/******************************************************************************\/\n\/* POST AUCTION ERROR EVENT *\/\n\/******************************************************************************\/\n\n\nPostAuctionErrorEvent::\nPostAuctionErrorEvent(std::string key, std::string message) :\n key(std::move(key)), message(std::move(message))\n{}\n\nvoid\nPostAuctionErrorEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\"PAERROR\", publishTimestamp(), key, message);\n}\n\n\n} \/\/ namepsace RTBKIT\n<commit_msg>Update events.cc in order to log augmentation data<commit_after>\/** events.cc -*- C++ -*-\n Rémi Attab, 18 Apr 2014\n Copyright (c) 2014 Datacratic. All rights reserved.\n\n Publishable event implementation.\n\n*\/\n\n#include \"events.h\"\n#include \"soa\/service\/zmq_endpoint.h\"\n#include \"soa\/service\/zmq_named_pub_sub.h\"\n\nusing namespace std;\nusing namespace ML;\n\nnamespace RTBKIT {\n\n\n\/******************************************************************************\/\n\/* UTILS *\/\n\/******************************************************************************\/\n\nnamespace {\n\nstd::string publishTimestamp()\n{\n return Date::now().print(5);\n}\n\n} \/\/ namespace anonymous\n\n\n\/******************************************************************************\/\n\/* MATCHED WIN LOSS *\/\n\/******************************************************************************\/\n\nvoid\nMatchedWinLoss::\ninitFinishedInfo(const FinishedInfo& info)\n{\n auctionId = info.auctionId;\n impId = info.adSpotId;\n winPrice = info.winPrice;\n rawWinPrice = info.rawWinPrice;\n response = info.bid;\n requestStr = info.bidRequestStr;\n requestStrFormat = info.bidRequestStrFormat;\n request = info.bidRequest;\n meta = info.winMeta;\n augmentations = info.augmentations;\n}\n\nvoid\nMatchedWinLoss::\ninitMisc(const PostAuctionEvent& event)\n{\n uids = event.uids;\n timestamp = event.timestamp;\n}\n\nvoid\nMatchedWinLoss::\ninitMisc(Date timestamp, UserIds uids)\n{\n this->timestamp = timestamp;\n this->uids = std::move(uids);\n}\n\n\nMatchedWinLoss::\nMatchedWinLoss(\n Type type,\n Confidence confidence,\n const PostAuctionEvent& event,\n const FinishedInfo& info) :\n type(type), confidence(confidence)\n{\n initFinishedInfo(info);\n initMisc(event);\n}\n\n\nMatchedWinLoss::\n MatchedWinLoss(\n Type type,\n Confidence confidence,\n const FinishedInfo& info,\n Date timestamp,\n UserIds uids) :\n type(type), confidence(confidence)\n{\n initFinishedInfo(info);\n initMisc(timestamp, std::move(uids));\n}\n\n\n\nstd::string\nMatchedWinLoss::\ntypeString() const\n{\n switch (type) {\n case LateWin:\n case Win: return \"WIN\";\n case Loss: return \"LOSS\";\n }\n ExcAssert(false);\n}\n\nstd::string\nMatchedWinLoss::\nconfidenceString() const\n{\n switch (confidence) {\n case Inferred: return \"inferred\";\n case Guaranteed: return \"guaranteed\";\n }\n\n ExcAssert(false);\n}\n\nsize_t\nMatchedWinLoss::\nimpIndex() const\n{\n return request->findAdSpotIndex(impId);\n}\n\n\nvoid\nMatchedWinLoss::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"MATCHED\" + typeString(), \/\/ 0\n publishTimestamp(), \/\/ 1\n\n auctionId.toString(), \/\/ 2\n std::to_string(impIndex()), \/\/ 3\n response.agent, \/\/ 4\n response.account.at(1, \"\"), \/\/ 5\n\n winPrice.toString(), \/\/ 6\n response.price.maxPrice.toString(), \/\/ 7\n std::to_string(response.price.priority), \/\/ 8\n\n requestStr, \/\/ 9\n response.bidData, \/\/ 10\n response.meta, \/\/ 11\n\n \/\/ This is where things start to get weird.\n\n std::to_string(response.creativeId), \/\/ 12\n response.creativeName, \/\/ 13\n response.account.at(0, \"\"), \/\/ 14\n\n uids.toJsonStr(), \/\/ 15\n meta, \/\/ 16\n\n \/\/ And this is where we lose all pretenses of sanity.\n\n response.account.at(0, \"\"), \/\/ 17\n impId.toString(), \/\/ 18\n response.account.toString(), \/\/ 19\n\n \/\/ Ok back to sanity now.\n\n requestStrFormat, \/\/ 20\n rawWinPrice.toString(), \/\/ 21\n augmentations.toString()\n );\n}\n\n\n\/******************************************************************************\/\n\/* MATCHED CAMPAIGN EVENT *\/\n\/******************************************************************************\/\n\nMatchedCampaignEvent::\nMatchedCampaignEvent(std::string label, const FinishedInfo& info) :\n label(std::move(label)),\n auctionId(info.auctionId),\n impId(info.adSpotId),\n account(info.bid.account),\n requestStr(info.bidRequestStr),\n request(info.bidRequest),\n requestStrFormat(info.bidRequestStrFormat),\n bid(info.bidToJson()),\n win(info.winToJson()),\n campaignEvents(info.campaignEvents.toJson()),\n visits(info.visitsToJson()),\n augmentations(info.augmentations)\n{\n auto it = std::find_if(info.campaignEvents.begin(), info.campaignEvents.end(),\n [&](const CampaignEvent& event) {\n return event.label_ == label;\n }\n );\n\n if(it != info.campaignEvents.end())\n timestamp = it->time_;\n}\nsize_t\nMatchedCampaignEvent::\nimpIndex() const\n{\n return request->findAdSpotIndex(impId);\n}\n\nvoid\nMatchedCampaignEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"MATCHED\" + label, \/\/ 0\n publishTimestamp(), \/\/ 1\n\n auctionId.toString(), \/\/ 2\n impId.toString(), \/\/ 3\n requestStr, \/\/ 4\n\n bid, \/\/ 5\n win, \/\/ 6\n campaignEvents, \/\/ 7\n visits, \/\/ 8\n\n account.at(0, \"\"), \/\/ 9\n account.at(1, \"\"), \/\/ 10\n account.toString(), \/\/ 11\n\n requestStrFormat \/\/ 12\n );\n}\n\n\n\/******************************************************************************\/\n\/* UNMATCHED EVENT *\/\n\/******************************************************************************\/\n\nUnmatchedEvent::\nUnmatchedEvent(std::string reason, PostAuctionEvent event) :\n reason(std::move(reason)),\n event(std::move(event))\n{}\n\nvoid\nUnmatchedEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"UNMATCHED\" + event.label, \/\/ 0\n publishTimestamp(), \/\/ 1\n\n reason, \/\/ 2\n event.auctionId.toString(), \/\/ 3\n event.adSpotId.toString(), \/\/ 4\n\n std::to_string(event.timestamp.secondsSinceEpoch()), \/\/ 5\n event.metadata.toJson() \/\/ 6\n );\n}\n\n\n\/******************************************************************************\/\n\/* POST AUCTION ERROR EVENT *\/\n\/******************************************************************************\/\n\n\nPostAuctionErrorEvent::\nPostAuctionErrorEvent(std::string key, std::string message) :\n key(std::move(key)), message(std::move(message))\n{}\n\nvoid\nPostAuctionErrorEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\"PAERROR\", publishTimestamp(), key, message);\n}\n\n\n} \/\/ namepsace RTBKIT\n<|endoftext|>"} {"text":"<commit_before>\/** events.cc -*- C++ -*-\n Rémi Attab, 18 Apr 2014\n Copyright (c) 2014 Datacratic. All rights reserved.\n\n Publishable event implementation.\n\n*\/\n\n#include \"events.h\"\n#include \"soa\/service\/zmq_endpoint.h\"\n#include \"soa\/service\/zmq_named_pub_sub.h\"\n\nusing namespace std;\nusing namespace ML;\n\nnamespace RTBKIT {\n\n\n\/******************************************************************************\/\n\/* UTILS *\/\n\/******************************************************************************\/\n\nnamespace {\n\nstd::string publishTimestamp()\n{\n return Date::now().print(5);\n}\n\n} \/\/ namespace anonymous\n\n\n\/******************************************************************************\/\n\/* MATCHED WIN LOSS *\/\n\/******************************************************************************\/\n\nvoid\nMatchedWinLoss::\ninitFinishedInfo(const FinishedInfo& info)\n{\n auctionId = info.auctionId;\n impId = info.adSpotId;\n winPrice = info.winPrice;\n rawWinPrice = info.rawWinPrice;\n response = info.bid;\n requestStr = info.bidRequestStr;\n requestStrFormat = info.bidRequestStrFormat;\n request = info.bidRequest;\n meta = info.winMeta;\n augmentations = info.augmentations;\n}\n\nvoid\nMatchedWinLoss::\ninitMisc(const PostAuctionEvent& event)\n{\n uids = event.uids;\n timestamp = event.timestamp;\n}\n\nvoid\nMatchedWinLoss::\ninitMisc(Date timestamp, UserIds uids)\n{\n this->timestamp = timestamp;\n this->uids = std::move(uids);\n}\n\n\nMatchedWinLoss::\nMatchedWinLoss(\n Type type,\n Confidence confidence,\n const PostAuctionEvent& event,\n const FinishedInfo& info) :\n type(type), confidence(confidence)\n{\n initFinishedInfo(info);\n initMisc(event);\n}\n\n\nMatchedWinLoss::\n MatchedWinLoss(\n Type type,\n Confidence confidence,\n const FinishedInfo& info,\n Date timestamp,\n UserIds uids) :\n type(type), confidence(confidence)\n{\n initFinishedInfo(info);\n initMisc(timestamp, std::move(uids));\n}\n\n\n\nstd::string\nMatchedWinLoss::\ntypeString() const\n{\n switch (type) {\n case LateWin:\n case Win: return \"WIN\";\n case Loss: return \"LOSS\";\n }\n ExcAssert(false);\n}\n\nstd::string\nMatchedWinLoss::\nconfidenceString() const\n{\n switch (confidence) {\n case Inferred: return \"inferred\";\n case Guaranteed: return \"guaranteed\";\n }\n\n ExcAssert(false);\n}\n\nsize_t\nMatchedWinLoss::\nimpIndex() const\n{\n return request->findAdSpotIndex(impId);\n}\n\n\nvoid\nMatchedWinLoss::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"MATCHED\" + typeString(),\n publishTimestamp(),\n\n auctionId.toString(),\n std::to_string(impIndex()),\n request->findAdSpotIndex(impId),\n response.agent,\n response.account.at(1, \"\"),\n\n winPrice.toString(),\n response.price.maxPrice.toString(),\n std::to_string(response.price.priority),\n\n requestStr,\n response.bidData,\n response.meta,\n\n \/\/ This is where things start to get weird.\n\n std::to_string(response.creativeId),\n response.creativeName,\n response.account.at(0, \"\"),\n\n uids.toJsonStr(),\n meta,\n\n \/\/ And this is where we lose all pretenses of sanity.\n\n response.account.at(0, \"\"),\n impId.toString(),\n response.account.toString(),\n\n \/\/ Ok back to sanity now.\n\n requestStrFormat,\n rawWinPrice.toString()\n );\n}\n\nvoid\nMatchedWinLoss::\nsendAgentMessage(ZmqNamedClientBus& agents) const\n{\n std::string channel =\n type == LateWin ? \"LATEWIN\" : typeString();\n\n agents.sendMessage(\n response.agent,\n channel,\n timestamp,\n confidenceString(),\n\n auctionId.toString(),\n std::to_string(impIndex()),\n winPrice.toString(),\n\n requestStrFormat,\n requestStr,\n response.bidData,\n response.meta,\n augmentations.toJson()\n );\n}\n\n\n\/******************************************************************************\/\n\/* MATCHED CAMPAIGN EVENT *\/\n\/******************************************************************************\/\n\nMatchedCampaignEvent::\nMatchedCampaignEvent(std::string label, const FinishedInfo& info) :\n label(std::move(label)),\n auctionId(info.auctionId),\n impId(info.adSpotId),\n account(info.bid.account),\n requestStr(info.bidRequestStr),\n request(info.bidRequest),\n requestStrFormat(info.bidRequestStrFormat),\n bid(info.bidToJson()),\n win(info.winToJson()),\n campaignEvents(info.campaignEvents.toJson()),\n visits(info.visitsToJson()),\n augmentations(info.augmentations)\n{}\n\nsize_t\nMatchedCampaignEvent::\nimpIndex() const\n{\n return request->findAdSpotIndex(impId);\n}\n\nvoid\nMatchedCampaignEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"MATCHED\" + label,\n publishTimestamp(),\n\n auctionId.toString(),\n impId.toString(),\n requestStr,\n\n bid,\n win,\n campaignEvents,\n visits,\n\n account.at(0, \"\"),\n account.at(1, \"\"),\n account.toString(),\n\n requestStrFormat\n );\n}\n\nvoid\nMatchedCampaignEvent::\nsendAgentMessage(const std::string& agent, ZmqNamedClientBus& endpoint) const\n{\n endpoint.sendMessage(\n agent,\n \"CAMPAIGN_EVENT\",\n label,\n Date::now(),\n\n auctionId.toString(),\n impId.toString(),\n std::to_string(impIndex()),\n\n requestStrFormat,\n requestStr,\n augmentations.toJson(),\n\n bid,\n win,\n campaignEvents,\n visits\n );\n}\n\n\n\/******************************************************************************\/\n\/* UNMATCHED EVENT *\/\n\/******************************************************************************\/\n\nUnmatchedEvent::\nUnmatchedEvent(std::string reason, PostAuctionEvent event) :\n reason(std::move(reason)),\n event(std::move(event))\n{}\n\nvoid\nUnmatchedEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"UNMATCHED\" + event.label,\n publishTimestamp(),\n\n reason,\n event.auctionId.toString(),\n event.adSpotId.toString(),\n\n std::to_string(event.timestamp.secondsSinceEpoch()),\n event.metadata.toJson()\n );\n}\n\n\n\/******************************************************************************\/\n\/* POST AUCTION ERROR EVENT *\/\n\/******************************************************************************\/\n\n\nPostAuctionErrorEvent::\nPostAuctionErrorEvent(std::string key, std::string message) :\n key(std::move(key)), message(std::move(message))\n{}\n\nvoid\nPostAuctionErrorEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\"PAERROR\", publishTimestamp(), key, message);\n}\n\n\n} \/\/ namepsace RTBKIT\n<commit_msg>Fixed a slight mix up in the MATCHWIN events.<commit_after>\/** events.cc -*- C++ -*-\n Rémi Attab, 18 Apr 2014\n Copyright (c) 2014 Datacratic. All rights reserved.\n\n Publishable event implementation.\n\n*\/\n\n#include \"events.h\"\n#include \"soa\/service\/zmq_endpoint.h\"\n#include \"soa\/service\/zmq_named_pub_sub.h\"\n\nusing namespace std;\nusing namespace ML;\n\nnamespace RTBKIT {\n\n\n\/******************************************************************************\/\n\/* UTILS *\/\n\/******************************************************************************\/\n\nnamespace {\n\nstd::string publishTimestamp()\n{\n return Date::now().print(5);\n}\n\n} \/\/ namespace anonymous\n\n\n\/******************************************************************************\/\n\/* MATCHED WIN LOSS *\/\n\/******************************************************************************\/\n\nvoid\nMatchedWinLoss::\ninitFinishedInfo(const FinishedInfo& info)\n{\n auctionId = info.auctionId;\n impId = info.adSpotId;\n winPrice = info.winPrice;\n rawWinPrice = info.rawWinPrice;\n response = info.bid;\n requestStr = info.bidRequestStr;\n requestStrFormat = info.bidRequestStrFormat;\n request = info.bidRequest;\n meta = info.winMeta;\n augmentations = info.augmentations;\n}\n\nvoid\nMatchedWinLoss::\ninitMisc(const PostAuctionEvent& event)\n{\n uids = event.uids;\n timestamp = event.timestamp;\n}\n\nvoid\nMatchedWinLoss::\ninitMisc(Date timestamp, UserIds uids)\n{\n this->timestamp = timestamp;\n this->uids = std::move(uids);\n}\n\n\nMatchedWinLoss::\nMatchedWinLoss(\n Type type,\n Confidence confidence,\n const PostAuctionEvent& event,\n const FinishedInfo& info) :\n type(type), confidence(confidence)\n{\n initFinishedInfo(info);\n initMisc(event);\n}\n\n\nMatchedWinLoss::\n MatchedWinLoss(\n Type type,\n Confidence confidence,\n const FinishedInfo& info,\n Date timestamp,\n UserIds uids) :\n type(type), confidence(confidence)\n{\n initFinishedInfo(info);\n initMisc(timestamp, std::move(uids));\n}\n\n\n\nstd::string\nMatchedWinLoss::\ntypeString() const\n{\n switch (type) {\n case LateWin:\n case Win: return \"WIN\";\n case Loss: return \"LOSS\";\n }\n ExcAssert(false);\n}\n\nstd::string\nMatchedWinLoss::\nconfidenceString() const\n{\n switch (confidence) {\n case Inferred: return \"inferred\";\n case Guaranteed: return \"guaranteed\";\n }\n\n ExcAssert(false);\n}\n\nsize_t\nMatchedWinLoss::\nimpIndex() const\n{\n return request->findAdSpotIndex(impId);\n}\n\n\nvoid\nMatchedWinLoss::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"MATCHED\" + typeString(), \/\/ 0\n publishTimestamp(),\n\n auctionId.toString(), \/\/ 2\n std::to_string(impIndex()),\n response.agent,\n response.account.at(1, \"\"),\n\n winPrice.toString(), \/\/ 6\n response.price.maxPrice.toString(),\n std::to_string(response.price.priority),\n\n requestStr, \/\/ 9\n response.bidData,\n response.meta,\n\n \/\/ This is where things start to get weird.\n\n std::to_string(response.creativeId), \/\/ 12\n response.creativeName,\n response.account.at(0, \"\"),\n\n uids.toJsonStr(), \/\/ 15\n meta,\n\n \/\/ And this is where we lose all pretenses of sanity.\n\n response.account.at(0, \"\"), \/\/ 17\n impId.toString(),\n response.account.toString(),\n\n \/\/ Ok back to sanity now.\n\n requestStrFormat, \/\/ 20\n rawWinPrice.toString()\n );\n}\n\nvoid\nMatchedWinLoss::\nsendAgentMessage(ZmqNamedClientBus& agents) const\n{\n std::string channel =\n type == LateWin ? \"LATEWIN\" : typeString();\n\n agents.sendMessage(\n response.agent,\n channel,\n timestamp,\n confidenceString(),\n\n auctionId.toString(),\n std::to_string(impIndex()),\n winPrice.toString(),\n\n requestStrFormat,\n requestStr,\n response.bidData,\n response.meta,\n augmentations.toJson()\n );\n}\n\n\n\/******************************************************************************\/\n\/* MATCHED CAMPAIGN EVENT *\/\n\/******************************************************************************\/\n\nMatchedCampaignEvent::\nMatchedCampaignEvent(std::string label, const FinishedInfo& info) :\n label(std::move(label)),\n auctionId(info.auctionId),\n impId(info.adSpotId),\n account(info.bid.account),\n requestStr(info.bidRequestStr),\n request(info.bidRequest),\n requestStrFormat(info.bidRequestStrFormat),\n bid(info.bidToJson()),\n win(info.winToJson()),\n campaignEvents(info.campaignEvents.toJson()),\n visits(info.visitsToJson()),\n augmentations(info.augmentations)\n{}\n\nsize_t\nMatchedCampaignEvent::\nimpIndex() const\n{\n return request->findAdSpotIndex(impId);\n}\n\nvoid\nMatchedCampaignEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"MATCHED\" + label,\n publishTimestamp(),\n\n auctionId.toString(),\n impId.toString(),\n requestStr,\n\n bid,\n win,\n campaignEvents,\n visits,\n\n account.at(0, \"\"),\n account.at(1, \"\"),\n account.toString(),\n\n requestStrFormat\n );\n}\n\nvoid\nMatchedCampaignEvent::\nsendAgentMessage(const std::string& agent, ZmqNamedClientBus& endpoint) const\n{\n endpoint.sendMessage(\n agent,\n \"CAMPAIGN_EVENT\",\n label,\n Date::now(),\n\n auctionId.toString(),\n impId.toString(),\n std::to_string(impIndex()),\n\n requestStrFormat,\n requestStr,\n augmentations.toJson(),\n\n bid,\n win,\n campaignEvents,\n visits\n );\n}\n\n\n\/******************************************************************************\/\n\/* UNMATCHED EVENT *\/\n\/******************************************************************************\/\n\nUnmatchedEvent::\nUnmatchedEvent(std::string reason, PostAuctionEvent event) :\n reason(std::move(reason)),\n event(std::move(event))\n{}\n\nvoid\nUnmatchedEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\n \"UNMATCHED\" + event.label,\n publishTimestamp(),\n\n reason,\n event.auctionId.toString(),\n event.adSpotId.toString(),\n\n std::to_string(event.timestamp.secondsSinceEpoch()),\n event.metadata.toJson()\n );\n}\n\n\n\/******************************************************************************\/\n\/* POST AUCTION ERROR EVENT *\/\n\/******************************************************************************\/\n\n\nPostAuctionErrorEvent::\nPostAuctionErrorEvent(std::string key, std::string message) :\n key(std::move(key)), message(std::move(message))\n{}\n\nvoid\nPostAuctionErrorEvent::\npublish(ZmqNamedPublisher& logger) const\n{\n logger.publish(\"PAERROR\", publishTimestamp(), key, message);\n}\n\n\n} \/\/ namepsace RTBKIT\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: QueryTabWinUndoAct.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 16:26:17 $\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 DBAUI_OQueryTabWinUndoAct_HXX\n#include \"QueryTabWinUndoAct.hxx\"\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef DBAUI_QUERY_TABLEWINDOW_HXX\n#include \"QTableWindow.hxx\"\n#endif\n#ifndef DBAUI_QUERY_TABLEWINDOWDATA_HXX\n#include \"QTableWindowData.hxx\"\n#endif\n#ifndef DBAUI_TABLECONNECTION_HXX\n#include \"TableConnection.hxx\"\n#endif\n#ifndef DBAUI_TABLECONNECTIONDATA_HXX\n#include \"TableConnectionData.hxx\"\n#endif\n#ifndef DBAUI_QUERYDESIGNFIELDUNDOACT_HXX\n#include \"QueryDesignFieldUndoAct.hxx\"\n#endif\n#ifndef DBAUI_QUERYTABLEVIEW_HXX\n#include \"QueryTableView.hxx\"\n#endif\n\n\nusing namespace dbaui;\nDBG_NAME(OQueryDesignFieldUndoAct)\nOQueryDesignFieldUndoAct::OQueryDesignFieldUndoAct(OSelectionBrowseBox* pSelBrwBox, USHORT nCommentID)\n : OCommentUndoAction(nCommentID)\n , pOwner(pSelBrwBox)\n , m_nColumnPostion(BROWSER_INVALIDID)\n{\n DBG_CTOR(OQueryDesignFieldUndoAct,NULL);\n}\n\/\/ -----------------------------------------------------------------------------\nOQueryDesignFieldUndoAct::~OQueryDesignFieldUndoAct()\n{\n DBG_DTOR(OQueryDesignFieldUndoAct,NULL);\n pOwner = NULL;\n}\n\/\/ -----------------------------------------------------------------------------\n\nDBG_NAME(OQueryTabWinUndoAct )\n\/\/ ------------------------------------------------------------------------------------------------\nOQueryTabWinUndoAct::OQueryTabWinUndoAct(OQueryTableView* pOwner, USHORT nCommentID)\n :OQueryDesignUndoAction(pOwner, nCommentID)\n ,m_pTabWin(NULL)\n{\n DBG_CTOR(OQueryTabWinUndoAct ,NULL);\n}\n\/\/==============================================================================\nOQueryTabWinUndoAct::~OQueryTabWinUndoAct()\n{\n DBG_DTOR(OQueryTabWinUndoAct ,NULL);\n if (m_bOwnerOfObjects)\n { \/\/ wenn ich der alleinige Owner des Fenster bin, muss ich dafuer sorgen, dass es geloescht wird\n OSL_ENSURE(m_pTabWin != NULL, \"OQueryTabWinUndoAct::~OQueryTabWinUndoAct() : m_pTabWin sollte nicht NULL sein\");\n OSL_ENSURE(!m_pTabWin->IsVisible(), \"OQueryTabWinUndoAct::~OQueryTabWinUndoAct() : *m_pTabWin sollte nicht sichtbar sein\");\n\n delete m_pTabWin->GetData();\n if ( m_pTabWin )\n m_pTabWin->clearListBox();\n delete m_pTabWin;\n\n \/\/ und natuerlich auch die entsprechenden Connections\n ::std::vector<OTableConnection*>::iterator aIter = m_vTableConnection.begin();\n for(;aIter != m_vTableConnection.end();++aIter)\n {\n m_pOwner->DeselectConn(*aIter);\n delete (*aIter)->GetData();\n delete (*aIter);\n }\n m_vTableConnection.clear();\n }\n}\n\/\/------------------------------------------------------------------------------\nvoid OTabFieldCellModifiedUndoAct::Undo()\n{\n OSL_ENSURE(m_nColumnPostion != BROWSER_INVALIDID,\"Column position was not set add the undo action!\");\n OSL_ENSURE(m_nColumnPostion < pOwner->GetColumnCount(),\"Position outside the column count!\");\n if ( m_nColumnPostion != BROWSER_INVALIDID )\n {\n USHORT nColumnId = pOwner->GetColumnId(m_nColumnPostion);\n String strNext = pOwner->GetCellContents(m_nCellIndex, nColumnId);\n pOwner->SetCellContents(m_nCellIndex, nColumnId, m_strNextCellContents);\n m_strNextCellContents = strNext;\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OTabFieldSizedUndoAct::Undo()\n{\n OSL_ENSURE(m_nColumnPostion != BROWSER_INVALIDID,\"Column position was not set add the undo action!\");\n if ( m_nColumnPostion != BROWSER_INVALIDID )\n {\n USHORT nColumnId = pOwner->GetColumnId(m_nColumnPostion);\n long nNextWidth = pOwner->GetColumnWidth(nColumnId);\n pOwner->SetColWidth(nColumnId, m_nNextWidth);\n m_nNextWidth = nNextWidth;\n }\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OTabFieldMovedUndoAct::Undo()\n{\n OSL_ENSURE(m_nColumnPostion != BROWSER_INVALIDID,\"Column position was not set add the undo action!\");\n if ( m_nColumnPostion != BROWSER_INVALIDID )\n {\n sal_uInt16 nId = pDescr->GetColumnId();\n USHORT nOldPos = pOwner->GetColumnPos(nId);\n pOwner->SetColumnPos(nId,m_nColumnPostion);\n pOwner->ColumnMoved(nId,FALSE);\n m_nColumnPostion = nOldPos;\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n\n\n\n<commit_msg>INTEGRATION: CWS dba201b (1.8.146); FILE MERGED 2005\/09\/21 10:11:49 oj 1.8.146.2: RESYNC: (1.8-1.9); FILE MERGED 2005\/07\/06 10:36:26 oj 1.8.146.1: #123168# check if we are in undo mode<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: QueryTabWinUndoAct.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: hr $ $Date: 2005-09-23 12:43:27 $\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 DBAUI_OQueryTabWinUndoAct_HXX\n#include \"QueryTabWinUndoAct.hxx\"\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef DBAUI_QUERY_TABLEWINDOW_HXX\n#include \"QTableWindow.hxx\"\n#endif\n#ifndef DBAUI_QUERY_TABLEWINDOWDATA_HXX\n#include \"QTableWindowData.hxx\"\n#endif\n#ifndef DBAUI_TABLECONNECTION_HXX\n#include \"TableConnection.hxx\"\n#endif\n#ifndef DBAUI_TABLECONNECTIONDATA_HXX\n#include \"TableConnectionData.hxx\"\n#endif\n#ifndef DBAUI_QUERYDESIGNFIELDUNDOACT_HXX\n#include \"QueryDesignFieldUndoAct.hxx\"\n#endif\n#ifndef DBAUI_QUERYTABLEVIEW_HXX\n#include \"QueryTableView.hxx\"\n#endif\n\n\nusing namespace dbaui;\nDBG_NAME(OQueryDesignFieldUndoAct)\nOQueryDesignFieldUndoAct::OQueryDesignFieldUndoAct(OSelectionBrowseBox* pSelBrwBox, USHORT nCommentID)\n : OCommentUndoAction(nCommentID)\n , pOwner(pSelBrwBox)\n , m_nColumnPostion(BROWSER_INVALIDID)\n{\n DBG_CTOR(OQueryDesignFieldUndoAct,NULL);\n}\n\/\/ -----------------------------------------------------------------------------\nOQueryDesignFieldUndoAct::~OQueryDesignFieldUndoAct()\n{\n DBG_DTOR(OQueryDesignFieldUndoAct,NULL);\n pOwner = NULL;\n}\n\/\/ -----------------------------------------------------------------------------\n\nDBG_NAME(OQueryTabWinUndoAct )\n\/\/ ------------------------------------------------------------------------------------------------\nOQueryTabWinUndoAct::OQueryTabWinUndoAct(OQueryTableView* pOwner, USHORT nCommentID)\n :OQueryDesignUndoAction(pOwner, nCommentID)\n ,m_pTabWin(NULL)\n{\n DBG_CTOR(OQueryTabWinUndoAct ,NULL);\n}\n\/\/==============================================================================\nOQueryTabWinUndoAct::~OQueryTabWinUndoAct()\n{\n DBG_DTOR(OQueryTabWinUndoAct ,NULL);\n if (m_bOwnerOfObjects)\n { \/\/ wenn ich der alleinige Owner des Fenster bin, muss ich dafuer sorgen, dass es geloescht wird\n OSL_ENSURE(m_pTabWin != NULL, \"OQueryTabWinUndoAct::~OQueryTabWinUndoAct() : m_pTabWin sollte nicht NULL sein\");\n OSL_ENSURE(!m_pTabWin->IsVisible(), \"OQueryTabWinUndoAct::~OQueryTabWinUndoAct() : *m_pTabWin sollte nicht sichtbar sein\");\n\n delete m_pTabWin->GetData();\n if ( m_pTabWin )\n m_pTabWin->clearListBox();\n delete m_pTabWin;\n\n \/\/ und natuerlich auch die entsprechenden Connections\n ::std::vector<OTableConnection*>::iterator aIter = m_vTableConnection.begin();\n for(;aIter != m_vTableConnection.end();++aIter)\n {\n m_pOwner->DeselectConn(*aIter);\n delete (*aIter)->GetData();\n delete (*aIter);\n }\n m_vTableConnection.clear();\n }\n}\n\/\/------------------------------------------------------------------------------\nvoid OTabFieldCellModifiedUndoAct::Undo()\n{\n pOwner->EnterUndoMode();\n OSL_ENSURE(m_nColumnPostion != BROWSER_INVALIDID,\"Column position was not set add the undo action!\");\n OSL_ENSURE(m_nColumnPostion < pOwner->GetColumnCount(),\"Position outside the column count!\");\n if ( m_nColumnPostion != BROWSER_INVALIDID )\n {\n USHORT nColumnId = pOwner->GetColumnId(m_nColumnPostion);\n String strNext = pOwner->GetCellContents(m_nCellIndex, nColumnId);\n pOwner->SetCellContents(m_nCellIndex, nColumnId, m_strNextCellContents);\n m_strNextCellContents = strNext;\n }\n pOwner->LeaveUndoMode();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OTabFieldSizedUndoAct::Undo()\n{\n pOwner->EnterUndoMode();\n OSL_ENSURE(m_nColumnPostion != BROWSER_INVALIDID,\"Column position was not set add the undo action!\");\n if ( m_nColumnPostion != BROWSER_INVALIDID )\n {\n USHORT nColumnId = pOwner->GetColumnId(m_nColumnPostion);\n long nNextWidth = pOwner->GetColumnWidth(nColumnId);\n pOwner->SetColWidth(nColumnId, m_nNextWidth);\n m_nNextWidth = nNextWidth;\n }\n pOwner->LeaveUndoMode();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OTabFieldMovedUndoAct::Undo()\n{\n pOwner->EnterUndoMode();\n OSL_ENSURE(m_nColumnPostion != BROWSER_INVALIDID,\"Column position was not set add the undo action!\");\n if ( m_nColumnPostion != BROWSER_INVALIDID )\n {\n sal_uInt16 nId = pDescr->GetColumnId();\n USHORT nOldPos = pOwner->GetColumnPos(nId);\n pOwner->SetColumnPos(nId,m_nColumnPostion);\n pOwner->ColumnMoved(nId,FALSE);\n m_nColumnPostion = nOldPos;\n }\n pOwner->LeaveUndoMode();\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @brief Implementation of bridge.\n *\n * These utilities allow us to manage Postgres metadata.\n *\n * Copyright(c) 2015, CMU\n *\/\n\n#include <iostream>\n#include <assert.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"backend\/bridge\/ddl\/bridge.h\"\n#include \"backend\/common\/logger.h\"\n\n#include \"postgres.h\"\n#include \"c.h\"\n#include \"miscadmin.h\"\n#include \"access\/heapam.h\"\n#include \"access\/htup_details.h\"\n#include \"access\/xact.h\"\n#include \"catalog\/indexing.h\"\n#include \"catalog\/pg_attribute.h\"\n#include \"catalog\/pg_constraint.h\"\n#include \"catalog\/pg_class.h\"\n#include \"catalog\/pg_database.h\"\n#include \"catalog\/pg_namespace.h\"\n#include \"catalog\/pg_type.h\"\n#include \"common\/fe_memutils.h\"\n#include \"utils\/rel.h\"\n#include \"utils\/ruleutils.h\"\n#include \"utils\/builtins.h\"\n#include \"utils\/lsyscache.h\"\n#include \"utils\/snapmgr.h\"\n#include \"utils\/syscache.h\"\n#include \"parser\/parse_type.h\"\n\nnamespace peloton {\nnamespace bridge {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Getters\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Get the pg class tuple\n * @param tuple relevant tuple if it exists, NULL otherwise\n *\/\nHeapTuple Bridge::GetPGClassTupleForRelationOid(Oid relation_id) {\n Relation pg_class_rel;\n HeapTuple tuple = NULL;\n\n PelotonStartTransactionCommand();\n\n \/\/ Open pg_class table\n pg_class_rel = heap_open(RelationRelationId, AccessShareLock);\n\n \/\/ Search the pg_class table with given relation id\n tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relation_id));\n if (!HeapTupleIsValid(tuple)) {\n elog(DEBUG2, \"cache lookup failed for relation %u\", relation_id);\n \/\/ Don't break here, we need to close heap and commit.\n }\n\n heap_close(pg_class_rel, AccessShareLock);\n\n PelotonCommitTransactionCommand();\n\n return tuple;\n}\n\n\/**\n * @brief Get the pg class tuple\n * @param tuple relevant tuple if it exists, NULL otherwise\n *\/\nHeapTuple Bridge::GetPGClassTupleForRelationName(const char *relation_name) {\n Relation pg_class_rel;\n HeapTuple tuple = NULL;\n HeapScanDesc scan;\n\n PelotonStartTransactionCommand();\n\n \/\/ Open pg_class table\n pg_class_rel = heap_open(RelationRelationId, AccessShareLock);\n\n \/\/ Search the pg_class table with given relation name\n scan = heap_beginscan_catalog(pg_class_rel, 0, NULL);\n\n while (HeapTupleIsValid(tuple = heap_getnext(scan, ForwardScanDirection))) {\n Form_pg_class pgclass = (Form_pg_class)GETSTRUCT(tuple);\n\n if (pgclass->relnamespace == PG_PUBLIC_NAMESPACE) {\n if (strcmp(NameStr(pgclass->relname), relation_name) == 0) {\n \/\/ We need to end scan and close heap\n break;\n }\n }\n }\n\n heap_endscan(scan);\n heap_close(pg_class_rel, AccessShareLock);\n\n PelotonCommitTransactionCommand();\n\n return tuple;\n}\n\n\/**\n * @brief Getting the relation name\n * @param relation_id relation id\n * @return Tuple if valid relation_id, otherwise null\n *\/\nchar *Bridge::GetRelationName(Oid relation_id) {\n HeapTuple tuple;\n Form_pg_class pg_class;\n char *relation_name;\n\n tuple = GetPGClassTupleForRelationOid(relation_id);\n if (!HeapTupleIsValid(tuple)) {\n return NULL;\n }\n\n \/\/ Get relation name\n pg_class = (Form_pg_class)GETSTRUCT(tuple);\n relation_name = NameStr(pg_class->relname);\n\n return relation_name;\n}\n\n\/*\n * given a table name, look up the OID\n * @param table_name table name\n * @return relation id, if relation is valid, 0 otherewise\n *\/\nOid Bridge::GetRelationOid(const char *relation_name) {\n Oid relation_oid = InvalidOid;\n HeapTuple tuple;\n\n tuple = GetPGClassTupleForRelationName(relation_name);\n if (!HeapTupleIsValid(tuple)) {\n return InvalidOid;\n }\n\n \/\/ Get relation oid\n relation_oid = HeapTupleHeaderGetOid(tuple->t_data);\n\n return relation_oid;\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Catalog information\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Getting the number of attributes.\n * @param relation_id relation id\n * @return num_atts if valid relation_id, otherwise -1\n *\/\nint Bridge::GetNumberOfAttributes(Oid relation_id) {\n HeapTuple tuple;\n Form_pg_class pg_class;\n int num_atts = -1;\n\n tuple = GetPGClassTupleForRelationOid(relation_id);\n\n if (!HeapTupleIsValid(tuple)) {\n return num_atts;\n }\n\n pg_class = (Form_pg_class)GETSTRUCT(tuple);\n\n \/\/ Get number of attributes\n num_atts = pg_class->relnatts;\n\n return num_atts;\n}\n\n\/**\n * @brief Getting the number of tuples.\n * @param relation_id relation id\n * @return num_tuples if valid relation_id, otherwise -1\n *\/\nfloat Bridge::GetNumberOfTuples(Oid relation_id) {\n HeapTuple tuple;\n Form_pg_class pg_class;\n float num_tuples;\n\n tuple = GetPGClassTupleForRelationOid(relation_id);\n if (!HeapTupleIsValid(tuple)) {\n return -1;\n }\n pg_class = (Form_pg_class)GETSTRUCT(tuple);\n\n \/\/ Get number of tuples\n num_tuples = pg_class->reltuples;\n\n return num_tuples;\n}\n\n\/**\n * @brief Getting the current database Oid\n * @return MyDatabaseId\n *\/\nOid Bridge::GetCurrentDatabaseOid(void) { return MyDatabaseId; }\n\n\/**\n * @brief Printing the current database information out\n *\/\nOid Bridge::GetDbInfo(void) {\n printf(\"Mydatabase Id %u \\n\", MyDatabaseId);\n printf(\"MydatabaseTableSpace Id %u \\n\", MyDatabaseTableSpace);\n printf(\"Mydatabase path %s \\n\", DatabasePath);\n}\n\n\/**\n * @Determine whether table exists in the *current* database or not\n * @param table_name table name\n * @return true or false depending on whether table exists or not.\n *\/\nbool Bridge::RelationExists(const char *relation_name) {\n HeapTuple tuple;\n\n tuple = GetPGClassTupleForRelationName(relation_name);\n if (!HeapTupleIsValid(tuple)) {\n return false;\n }\n\n return true;\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Table lists\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Print all tables in *current* database using catalog table pg_class\n *\/\nvoid Bridge::GetTableList(bool catalog_only) {\n Relation pg_class_rel;\n HeapScanDesc scan;\n HeapTuple tuple;\n\n PelotonStartTransactionCommand();\n\n \/\/ Scan pg class table\n pg_class_rel = heap_open(RelationRelationId, AccessShareLock);\n scan = heap_beginscan_catalog(pg_class_rel, 0, NULL);\n\n while (HeapTupleIsValid(tuple = heap_getnext(scan, ForwardScanDirection))) {\n Form_pg_class pgclass = (Form_pg_class)GETSTRUCT(tuple);\n\n \/\/ Check if we only need catalog tables or not ?\n if (catalog_only == false) {\n elog(LOG, \"pgclass->relname :: %s \", NameStr(pgclass->relname));\n } else if (pgclass->relnamespace == PG_PUBLIC_NAMESPACE) {\n elog(LOG, \"pgclass->relname :: %s \", NameStr(pgclass->relname));\n }\n }\n\n heap_endscan(scan);\n heap_close(pg_class_rel, AccessShareLock);\n\n PelotonCommitTransactionCommand();\n}\n\n\/**\n * @brief Print all databases using catalog table pg_database\n *\/\nvoid Bridge::GetDatabaseList(void) {\n Relation pg_database_rel;\n HeapScanDesc scan;\n HeapTuple tup;\n\n PelotonStartTransactionCommand();\n\n \/\/ Scan pg database table\n pg_database_rel = heap_open(DatabaseRelationId, AccessShareLock);\n scan = heap_beginscan_catalog(pg_database_rel, 0, NULL);\n\n while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection))) {\n Form_pg_database pg_database = (Form_pg_database)GETSTRUCT(tup);\n Oid database_oid = HeapTupleHeaderGetOid(tup->t_data);\n elog(LOG, \"pgdatabase->datname :: %s oid %d \",\n NameStr(pg_database->datname), (int)database_oid);\n }\n\n heap_endscan(scan);\n heap_close(pg_database_rel, AccessShareLock);\n\n PelotonCommitTransactionCommand();\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Setters\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Setting the number of tuples.\n * @param relation_id relation id\n * @param num_tuples number of tuples\n *\/\nvoid Bridge::SetNumberOfTuples(Oid relation_id, float num_tuples) {\n assert(relation_id);\n\n Relation pg_class_rel;\n HeapTuple tuple;\n Form_pg_class pgclass;\n\n PelotonStartTransactionCommand();\n\n \/\/ Open target table in exclusive mode\n pg_class_rel = heap_open(RelationRelationId, RowExclusiveLock);\n tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relation_id));\n if (!HeapTupleIsValid(tuple)) {\n elog(DEBUG2, \"cache lookup failed for relation %u\", relation_id);\n }else{\n pgclass = (Form_pg_class) GETSTRUCT(tuple);\n pgclass->reltuples = (float4) num_tuples;\n pgclass->relpages = (int32) 1;\n\n \/\/ update tuple\n simple_heap_update(pg_class_rel, &tuple->t_self, tuple);\n\n \/* keep the catalog indexes up to date *\/\n CatalogUpdateIndexes(pg_class_rel, tuple);\n\n heap_freetuple(tuple);\n }\n\n heap_close(pg_class_rel, RowExclusiveLock);\n PelotonCommitTransactionCommand();\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Wrapper\n\/\/===--------------------------------------------------------------------===\/\/\n\nvoid Bridge::PelotonStartTransactionCommand(){\n StartTransactionCommand();\n}\n\nvoid Bridge::PelotonCommitTransactionCommand(){\n CommitTransactionCommand();\n SetCurrentResourceOwner();\n}\n\nvoid Bridge::SetCurrentResourceOwner(){\n \/\/ Set the resource owner\n CurrentResourceOwner = ResourceOwnerCreate(NULL, \"Peloton\");\n}\n\n} \/\/ namespace bridge\n} \/\/ namespace peloton\n<commit_msg>Added warning message for bridge function<commit_after>\/**\n * @brief Implementation of bridge.\n *\n * These utilities allow us to manage Postgres metadata.\n *\n * Copyright(c) 2015, CMU\n *\/\n\n#include <iostream>\n#include <assert.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"backend\/bridge\/ddl\/bridge.h\"\n#include \"backend\/common\/logger.h\"\n\n#include \"postgres.h\"\n#include \"c.h\"\n#include \"miscadmin.h\"\n#include \"access\/heapam.h\"\n#include \"access\/htup_details.h\"\n#include \"access\/xact.h\"\n#include \"catalog\/indexing.h\"\n#include \"catalog\/pg_attribute.h\"\n#include \"catalog\/pg_constraint.h\"\n#include \"catalog\/pg_class.h\"\n#include \"catalog\/pg_database.h\"\n#include \"catalog\/pg_namespace.h\"\n#include \"catalog\/pg_type.h\"\n#include \"common\/fe_memutils.h\"\n#include \"utils\/rel.h\"\n#include \"utils\/ruleutils.h\"\n#include \"utils\/builtins.h\"\n#include \"utils\/lsyscache.h\"\n#include \"utils\/snapmgr.h\"\n#include \"utils\/syscache.h\"\n#include \"parser\/parse_type.h\"\n\nnamespace peloton {\nnamespace bridge {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Getters\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Get the pg class tuple\n * @param tuple relevant tuple if it exists, NULL otherwise\n *\/\nHeapTuple Bridge::GetPGClassTupleForRelationOid(Oid relation_id) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n Relation pg_class_rel;\n HeapTuple tuple = NULL;\n\n PelotonStartTransactionCommand();\n\n \/\/ Open pg_class table\n pg_class_rel = heap_open(RelationRelationId, AccessShareLock);\n\n \/\/ Search the pg_class table with given relation id\n tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relation_id));\n if (!HeapTupleIsValid(tuple)) {\n elog(DEBUG2, \"cache lookup failed for relation %u\", relation_id);\n \/\/ Don't break here, we need to close heap and commit.\n }\n\n heap_close(pg_class_rel, AccessShareLock);\n\n PelotonCommitTransactionCommand();\n\n return tuple;\n}\n\n\/**\n * @brief Get the pg class tuple\n * @param tuple relevant tuple if it exists, NULL otherwise\n *\/\nHeapTuple Bridge::GetPGClassTupleForRelationName(const char *relation_name) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n Relation pg_class_rel;\n HeapTuple tuple = NULL;\n HeapScanDesc scan;\n\n PelotonStartTransactionCommand();\n\n \/\/ Open pg_class table\n pg_class_rel = heap_open(RelationRelationId, AccessShareLock);\n\n \/\/ Search the pg_class table with given relation name\n scan = heap_beginscan_catalog(pg_class_rel, 0, NULL);\n\n while (HeapTupleIsValid(tuple = heap_getnext(scan, ForwardScanDirection))) {\n Form_pg_class pgclass = (Form_pg_class)GETSTRUCT(tuple);\n\n if (pgclass->relnamespace == PG_PUBLIC_NAMESPACE) {\n if (strcmp(NameStr(pgclass->relname), relation_name) == 0) {\n \/\/ We need to end scan and close heap\n break;\n }\n }\n }\n\n heap_endscan(scan);\n heap_close(pg_class_rel, AccessShareLock);\n\n PelotonCommitTransactionCommand();\n\n return tuple;\n}\n\n\/**\n * @brief Getting the relation name\n * @param relation_id relation id\n * @return Tuple if valid relation_id, otherwise null\n *\/\nchar *Bridge::GetRelationName(Oid relation_id) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n HeapTuple tuple;\n Form_pg_class pg_class;\n char *relation_name;\n\n tuple = GetPGClassTupleForRelationOid(relation_id);\n if (!HeapTupleIsValid(tuple)) {\n return NULL;\n }\n\n \/\/ Get relation name\n pg_class = (Form_pg_class)GETSTRUCT(tuple);\n relation_name = NameStr(pg_class->relname);\n\n return relation_name;\n}\n\n\/*\n * given a table name, look up the OID\n * @param table_name table name\n * @return relation id, if relation is valid, 0 otherewise\n *\/\nOid Bridge::GetRelationOid(const char *relation_name) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n Oid relation_oid = InvalidOid;\n HeapTuple tuple;\n\n tuple = GetPGClassTupleForRelationName(relation_name);\n if (!HeapTupleIsValid(tuple)) {\n return InvalidOid;\n }\n\n \/\/ Get relation oid\n relation_oid = HeapTupleHeaderGetOid(tuple->t_data);\n\n return relation_oid;\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Catalog information\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Getting the number of attributes.\n * @param relation_id relation id\n * @return num_atts if valid relation_id, otherwise -1\n *\/\nint Bridge::GetNumberOfAttributes(Oid relation_id) {\n HeapTuple tuple;\n Form_pg_class pg_class;\n int num_atts = -1;\n\n tuple = GetPGClassTupleForRelationOid(relation_id);\n\n if (!HeapTupleIsValid(tuple)) {\n return num_atts;\n }\n\n pg_class = (Form_pg_class)GETSTRUCT(tuple);\n\n \/\/ Get number of attributes\n num_atts = pg_class->relnatts;\n\n return num_atts;\n}\n\n\/**\n * @brief Getting the number of tuples.\n * @param relation_id relation id\n * @return num_tuples if valid relation_id, otherwise -1\n *\/\nfloat Bridge::GetNumberOfTuples(Oid relation_id) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n HeapTuple tuple;\n Form_pg_class pg_class;\n float num_tuples;\n\n tuple = GetPGClassTupleForRelationOid(relation_id);\n if (!HeapTupleIsValid(tuple)) {\n return -1;\n }\n pg_class = (Form_pg_class)GETSTRUCT(tuple);\n\n \/\/ Get number of tuples\n num_tuples = pg_class->reltuples;\n\n return num_tuples;\n}\n\n\/**\n * @brief Getting the current database Oid\n * @return MyDatabaseId\n *\/\nOid Bridge::GetCurrentDatabaseOid(void) { return MyDatabaseId; }\n\n\/**\n * @brief Printing the current database information out\n *\/\nOid Bridge::GetDbInfo(void) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n printf(\"Mydatabase Id %u \\n\", MyDatabaseId);\n printf(\"MydatabaseTableSpace Id %u \\n\", MyDatabaseTableSpace);\n printf(\"Mydatabase path %s \\n\", DatabasePath);\n}\n\n\/**\n * @Determine whether table exists in the *current* database or not\n * @param table_name table name\n * @return true or false depending on whether table exists or not.\n *\/\nbool Bridge::RelationExists(const char *relation_name) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n HeapTuple tuple;\n\n tuple = GetPGClassTupleForRelationName(relation_name);\n if (!HeapTupleIsValid(tuple)) {\n return false;\n }\n\n return true;\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Table lists\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Print all tables in *current* database using catalog table pg_class\n *\/\nvoid Bridge::GetTableList(bool catalog_only) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n Relation pg_class_rel;\n HeapScanDesc scan;\n HeapTuple tuple;\n\n PelotonStartTransactionCommand();\n\n \/\/ Scan pg class table\n pg_class_rel = heap_open(RelationRelationId, AccessShareLock);\n scan = heap_beginscan_catalog(pg_class_rel, 0, NULL);\n\n while (HeapTupleIsValid(tuple = heap_getnext(scan, ForwardScanDirection))) {\n Form_pg_class pgclass = (Form_pg_class)GETSTRUCT(tuple);\n\n \/\/ Check if we only need catalog tables or not ?\n if (catalog_only == false) {\n elog(LOG, \"pgclass->relname :: %s \", NameStr(pgclass->relname));\n } else if (pgclass->relnamespace == PG_PUBLIC_NAMESPACE) {\n elog(LOG, \"pgclass->relname :: %s \", NameStr(pgclass->relname));\n }\n }\n\n heap_endscan(scan);\n heap_close(pg_class_rel, AccessShareLock);\n\n PelotonCommitTransactionCommand();\n}\n\n\/**\n * @brief Print all databases using catalog table pg_database\n *\/\nvoid Bridge::GetDatabaseList(void) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n Relation pg_database_rel;\n HeapScanDesc scan;\n HeapTuple tup;\n\n PelotonStartTransactionCommand();\n\n \/\/ Scan pg database table\n pg_database_rel = heap_open(DatabaseRelationId, AccessShareLock);\n scan = heap_beginscan_catalog(pg_database_rel, 0, NULL);\n\n while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection))) {\n Form_pg_database pg_database = (Form_pg_database)GETSTRUCT(tup);\n Oid database_oid = HeapTupleHeaderGetOid(tup->t_data);\n elog(LOG, \"pgdatabase->datname :: %s oid %d \",\n NameStr(pg_database->datname), (int)database_oid);\n }\n\n heap_endscan(scan);\n heap_close(pg_database_rel, AccessShareLock);\n\n PelotonCommitTransactionCommand();\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Setters\n\/\/===--------------------------------------------------------------------===\/\/\n\n\/**\n * @brief Setting the number of tuples.\n * @param relation_id relation id\n * @param num_tuples number of tuples\n *\/\nvoid Bridge::SetNumberOfTuples(Oid relation_id, float num_tuples) {\n LOG_WARN(\"Do not use bridge function in Peloton !!! \\n\");\n assert(relation_id);\n\n Relation pg_class_rel;\n HeapTuple tuple;\n Form_pg_class pgclass;\n\n PelotonStartTransactionCommand();\n\n \/\/ Open target table in exclusive mode\n pg_class_rel = heap_open(RelationRelationId, RowExclusiveLock);\n tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relation_id));\n if (!HeapTupleIsValid(tuple)) {\n elog(DEBUG2, \"cache lookup failed for relation %u\", relation_id);\n }else{\n pgclass = (Form_pg_class) GETSTRUCT(tuple);\n pgclass->reltuples = (float4) num_tuples;\n pgclass->relpages = (int32) 1;\n\n \/\/ update tuple\n simple_heap_update(pg_class_rel, &tuple->t_self, tuple);\n\n \/* keep the catalog indexes up to date *\/\n CatalogUpdateIndexes(pg_class_rel, tuple);\n\n heap_freetuple(tuple);\n }\n\n heap_close(pg_class_rel, RowExclusiveLock);\n PelotonCommitTransactionCommand();\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Wrapper\n\/\/===--------------------------------------------------------------------===\/\/\n\nvoid Bridge::PelotonStartTransactionCommand(){\n StartTransactionCommand();\n}\n\nvoid Bridge::PelotonCommitTransactionCommand(){\n CommitTransactionCommand();\n SetCurrentResourceOwner();\n}\n\nvoid Bridge::SetCurrentResourceOwner(){\n \/\/ Set the resource owner\n CurrentResourceOwner = ResourceOwnerCreate(NULL, \"Peloton\");\n}\n\n} \/\/ namespace bridge\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\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#pragma once\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wattributes\"\n#include <boost\/stacktrace.hpp>\n#pragma GCC diagnostic pop\n#include <common\/defines.hpp>\n#include <af\/defines.h>\n\n#include <cassert>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nclass AfError : public std::logic_error {\n std::string functionName;\n std::string fileName;\n int lineNumber;\n af_err error;\n boost::stacktrace::stacktrace st_;\n AfError();\n\n public:\n AfError(const char* const func, const char* const file, const int line,\n const char* const message, af_err err,\n boost::stacktrace::stacktrace st);\n\n AfError(std::string func, std::string file, const int line,\n const std::string& message, af_err err,\n boost::stacktrace::stacktrace st);\n\n AfError(const AfError& other) noexcept = delete;\n AfError(AfError&& other) noexcept = default;\n\n const std::string& getFunctionName() const noexcept;\n\n const std::string& getFileName() const noexcept;\n\n const boost::stacktrace::stacktrace& getStacktrace() const noexcept {\n return st_;\n };\n\n int getLine() const noexcept;\n\n af_err getError() const noexcept;\n\n virtual ~AfError() noexcept;\n};\n\n\/\/ TODO: Perhaps add a way to return supported types\nclass TypeError : public AfError {\n int argIndex;\n std::string errTypeName;\n TypeError();\n\n public:\n TypeError(const char* const func, const char* const file, const int line,\n const int index, const af_dtype type,\n const boost::stacktrace::stacktrace st);\n\n TypeError(TypeError&& other) noexcept = default;\n\n const std::string& getTypeName() const noexcept;\n\n int getArgIndex() const noexcept;\n\n ~TypeError() noexcept {}\n};\n\nclass ArgumentError : public AfError {\n int argIndex;\n std::string expected;\n ArgumentError();\n\n public:\n ArgumentError(const char* const func, const char* const file,\n const int line, const int index,\n const char* const expectString,\n const boost::stacktrace::stacktrace st);\n ArgumentError(ArgumentError&& other) noexcept = default;\n\n const std::string& getExpectedCondition() const noexcept;\n\n int getArgIndex() const noexcept;\n\n ~ArgumentError() noexcept {}\n};\n\nclass SupportError : public AfError {\n std::string backend;\n SupportError();\n\n public:\n SupportError(const char* const func, const char* const file, const int line,\n const char* const back,\n const boost::stacktrace::stacktrace st);\n SupportError(SupportError&& other) noexcept = default;\n\n ~SupportError() noexcept {}\n\n const std::string& getBackendName() const noexcept;\n};\n\nclass DimensionError : public AfError {\n int argIndex;\n std::string expected;\n DimensionError();\n\n public:\n DimensionError(const char* const func, const char* const file,\n const int line, const int index,\n const char* const expectString,\n const boost::stacktrace::stacktrace& st);\n DimensionError(DimensionError&& other) noexcept = default;\n\n const std::string& getExpectedCondition() const noexcept;\n\n int getArgIndex() const noexcept;\n\n ~DimensionError() noexcept {}\n};\n\naf_err processException();\n\naf_err set_global_error_string(const std::string& msg,\n af_err err = AF_ERR_UNKNOWN);\n\n#define DIM_ASSERT(INDEX, COND) \\\n do { \\\n if ((COND) == false) { \\\n throw DimensionError(__PRETTY_FUNCTION__, __AF_FILENAME__, \\\n __LINE__, INDEX, #COND, \\\n boost::stacktrace::stacktrace()); \\\n } \\\n } while (0)\n\n#define ARG_ASSERT(INDEX, COND) \\\n do { \\\n if ((COND) == false) { \\\n throw ArgumentError(__PRETTY_FUNCTION__, __AF_FILENAME__, \\\n __LINE__, INDEX, #COND, \\\n boost::stacktrace::stacktrace()); \\\n } \\\n } while (0)\n\n#define TYPE_ERROR(INDEX, type) \\\n do { \\\n throw TypeError(__PRETTY_FUNCTION__, __AF_FILENAME__, __LINE__, INDEX, \\\n type, boost::stacktrace::stacktrace()); \\\n } while (0)\n\n#define AF_ERROR(MSG, ERR_TYPE) \\\n do { \\\n throw AfError(__PRETTY_FUNCTION__, __AF_FILENAME__, __LINE__, MSG, \\\n ERR_TYPE, boost::stacktrace::stacktrace()); \\\n } while (0)\n\n#define AF_RETURN_ERROR(MSG, ERR_TYPE) \\\n do { \\\n std::stringstream s; \\\n s << \"Error in \" << __PRETTY_FUNCTION__ << \"\\n\" \\\n << \"In file \" << __AF_FILENAME__ << \":\" << __LINE__ << \": \" << MSG \\\n << \"\\n\" \\\n << boost::stacktrace::stacktrace(); \\\n return set_global_error_string(s.str(), ERR_TYPE); \\\n } while (0)\n\n#define TYPE_ASSERT(COND) \\\n do { \\\n if ((COND) == false) { \\\n AF_ERROR(\"Type mismatch inputs\", AF_ERR_DIFF_TYPE); \\\n } \\\n } while (0)\n\n#define AF_ASSERT(COND, MESSAGE) assert(MESSAGE&& COND)\n\n#define CATCHALL \\\n catch (...) { \\\n return processException(); \\\n }\n\n#define AF_CHECK(fn) \\\n do { \\\n af_err __err = fn; \\\n if (__err == AF_SUCCESS) break; \\\n throw AfError(__PRETTY_FUNCTION__, __AF_FILENAME__, __LINE__, \"\\n\", \\\n __err, boost::stacktrace::stacktrace()); \\\n } while (0)\n\nstatic const int MAX_ERR_SIZE = 1024;\nstd::string& get_global_error_string() noexcept;\n\nnamespace common {\n\nbool& is_stacktrace_enabled() noexcept;\n\n} \/\/ namespace common\n<commit_msg>Fix warning in older versions of boost stacktrace<commit_after>\/*******************************************************\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#pragma once\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wattributes\"\n#pragma GCC diagnostic ignored \"-Wparentheses\"\n#include <boost\/stacktrace.hpp>\n#pragma GCC diagnostic pop\n#include <common\/defines.hpp>\n#include <af\/defines.h>\n\n#include <cassert>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nclass AfError : public std::logic_error {\n std::string functionName;\n std::string fileName;\n int lineNumber;\n af_err error;\n boost::stacktrace::stacktrace st_;\n AfError();\n\n public:\n AfError(const char* const func, const char* const file, const int line,\n const char* const message, af_err err,\n boost::stacktrace::stacktrace st);\n\n AfError(std::string func, std::string file, const int line,\n const std::string& message, af_err err,\n boost::stacktrace::stacktrace st);\n\n AfError(const AfError& other) noexcept = delete;\n AfError(AfError&& other) noexcept = default;\n\n const std::string& getFunctionName() const noexcept;\n\n const std::string& getFileName() const noexcept;\n\n const boost::stacktrace::stacktrace& getStacktrace() const noexcept {\n return st_;\n };\n\n int getLine() const noexcept;\n\n af_err getError() const noexcept;\n\n virtual ~AfError() noexcept;\n};\n\n\/\/ TODO: Perhaps add a way to return supported types\nclass TypeError : public AfError {\n int argIndex;\n std::string errTypeName;\n TypeError();\n\n public:\n TypeError(const char* const func, const char* const file, const int line,\n const int index, const af_dtype type,\n const boost::stacktrace::stacktrace st);\n\n TypeError(TypeError&& other) noexcept = default;\n\n const std::string& getTypeName() const noexcept;\n\n int getArgIndex() const noexcept;\n\n ~TypeError() noexcept {}\n};\n\nclass ArgumentError : public AfError {\n int argIndex;\n std::string expected;\n ArgumentError();\n\n public:\n ArgumentError(const char* const func, const char* const file,\n const int line, const int index,\n const char* const expectString,\n const boost::stacktrace::stacktrace st);\n ArgumentError(ArgumentError&& other) noexcept = default;\n\n const std::string& getExpectedCondition() const noexcept;\n\n int getArgIndex() const noexcept;\n\n ~ArgumentError() noexcept {}\n};\n\nclass SupportError : public AfError {\n std::string backend;\n SupportError();\n\n public:\n SupportError(const char* const func, const char* const file, const int line,\n const char* const back,\n const boost::stacktrace::stacktrace st);\n SupportError(SupportError&& other) noexcept = default;\n\n ~SupportError() noexcept {}\n\n const std::string& getBackendName() const noexcept;\n};\n\nclass DimensionError : public AfError {\n int argIndex;\n std::string expected;\n DimensionError();\n\n public:\n DimensionError(const char* const func, const char* const file,\n const int line, const int index,\n const char* const expectString,\n const boost::stacktrace::stacktrace& st);\n DimensionError(DimensionError&& other) noexcept = default;\n\n const std::string& getExpectedCondition() const noexcept;\n\n int getArgIndex() const noexcept;\n\n ~DimensionError() noexcept {}\n};\n\naf_err processException();\n\naf_err set_global_error_string(const std::string& msg,\n af_err err = AF_ERR_UNKNOWN);\n\n#define DIM_ASSERT(INDEX, COND) \\\n do { \\\n if ((COND) == false) { \\\n throw DimensionError(__PRETTY_FUNCTION__, __AF_FILENAME__, \\\n __LINE__, INDEX, #COND, \\\n boost::stacktrace::stacktrace()); \\\n } \\\n } while (0)\n\n#define ARG_ASSERT(INDEX, COND) \\\n do { \\\n if ((COND) == false) { \\\n throw ArgumentError(__PRETTY_FUNCTION__, __AF_FILENAME__, \\\n __LINE__, INDEX, #COND, \\\n boost::stacktrace::stacktrace()); \\\n } \\\n } while (0)\n\n#define TYPE_ERROR(INDEX, type) \\\n do { \\\n throw TypeError(__PRETTY_FUNCTION__, __AF_FILENAME__, __LINE__, INDEX, \\\n type, boost::stacktrace::stacktrace()); \\\n } while (0)\n\n#define AF_ERROR(MSG, ERR_TYPE) \\\n do { \\\n throw AfError(__PRETTY_FUNCTION__, __AF_FILENAME__, __LINE__, MSG, \\\n ERR_TYPE, boost::stacktrace::stacktrace()); \\\n } while (0)\n\n#define AF_RETURN_ERROR(MSG, ERR_TYPE) \\\n do { \\\n std::stringstream s; \\\n s << \"Error in \" << __PRETTY_FUNCTION__ << \"\\n\" \\\n << \"In file \" << __AF_FILENAME__ << \":\" << __LINE__ << \": \" << MSG \\\n << \"\\n\" \\\n << boost::stacktrace::stacktrace(); \\\n return set_global_error_string(s.str(), ERR_TYPE); \\\n } while (0)\n\n#define TYPE_ASSERT(COND) \\\n do { \\\n if ((COND) == false) { \\\n AF_ERROR(\"Type mismatch inputs\", AF_ERR_DIFF_TYPE); \\\n } \\\n } while (0)\n\n#define AF_ASSERT(COND, MESSAGE) assert(MESSAGE&& COND)\n\n#define CATCHALL \\\n catch (...) { \\\n return processException(); \\\n }\n\n#define AF_CHECK(fn) \\\n do { \\\n af_err __err = fn; \\\n if (__err == AF_SUCCESS) break; \\\n throw AfError(__PRETTY_FUNCTION__, __AF_FILENAME__, __LINE__, \"\\n\", \\\n __err, boost::stacktrace::stacktrace()); \\\n } while (0)\n\nstatic const int MAX_ERR_SIZE = 1024;\nstd::string& get_global_error_string() noexcept;\n\nnamespace common {\n\nbool& is_stacktrace_enabled() noexcept;\n\n} \/\/ namespace common\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: convdiclist.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-04-27 16:06:23 $\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 _LINGUISTIC_CONVDICLIST_HXX_\n#define _LINGUISTIC_CONVDICLIST_HXX_\n\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XCONVERSIONDICTIONARYLIST_HPP_\n#include <com\/sun\/star\/linguistic2\/XConversionDictionaryList.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#ifndef _SVARRAY_HXX\n#include <svtools\/svarray.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen wg. DBG_ASSERT\n#include <tools\/debug.hxx>\n#endif\n\n#include \"misc.hxx\"\n#include \"lngopt.hxx\"\n\n\nclass ConvDicNameContainer;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ConvDicList :\n public cppu::WeakImplHelper3\n <\n ::com::sun::star::linguistic2::XConversionDictionaryList,\n ::com::sun::star::lang::XComponent,\n ::com::sun::star::lang::XServiceInfo\n >\n{\n\n class MyAppExitListener : public linguistic::AppExitListener\n {\n ConvDicList & rMyDicList;\n\n public:\n MyAppExitListener( ConvDicList &rDicList ) : rMyDicList( rDicList ) {}\n virtual void AtExit();\n };\n\n\n ::cppu::OInterfaceContainerHelper aEvtListeners;\n\n ConvDicNameContainer *pNameContainer;\n ::com::sun::star::uno::Reference<\n ::com::sun::star::container::XNameContainer > xNameContainer;\n\n MyAppExitListener *pExitListener;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::\n XTerminateListener > xExitListener;\n\n BOOL bDisposing;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n ConvDicList( const ConvDicList & );\n ConvDicList & operator = (const ConvDicList &);\n\n ConvDicNameContainer & GetNameContainer();\n\npublic:\n ConvDicList();\n virtual ~ConvDicList();\n\n \/\/ XConversionDictionaryList\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > SAL_CALL getDictionaryContainer( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XConversionDictionary > SAL_CALL addNewDictionary( const ::rtl::OUString& aName, const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nConversionDictionaryType ) throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL queryConversions( const ::rtl::OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nConversionDictionaryType, ::com::sun::star::linguistic2::ConversionDirection eDirection, sal_Int32 nTextConversionOptions ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL queryMaxCharCount( const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nConversionDictionaryType, ::com::sun::star::linguistic2::ConversionDirection eDirection ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XComponent\n virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n\n static inline ::rtl::OUString\n getImplementationName_Static() throw();\n static com::sun::star::uno::Sequence< ::rtl::OUString >\n getSupportedServiceNames_Static() throw();\n\n \/\/ non UNO-specific\n void FlushDics();\n};\n\ninline ::rtl::OUString ConvDicList::getImplementationName_Static() throw()\n{\n return A2OU( \"com.sun.star.lingu2.ConvDicList\" );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.52); FILE MERGED 2005\/09\/05 17:29:35 rt 1.2.52.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: convdiclist.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:49:07 $\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 _LINGUISTIC_CONVDICLIST_HXX_\n#define _LINGUISTIC_CONVDICLIST_HXX_\n\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XCONVERSIONDICTIONARYLIST_HPP_\n#include <com\/sun\/star\/linguistic2\/XConversionDictionaryList.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#ifndef _SVARRAY_HXX\n#include <svtools\/svarray.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen wg. DBG_ASSERT\n#include <tools\/debug.hxx>\n#endif\n\n#include \"misc.hxx\"\n#include \"lngopt.hxx\"\n\n\nclass ConvDicNameContainer;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ConvDicList :\n public cppu::WeakImplHelper3\n <\n ::com::sun::star::linguistic2::XConversionDictionaryList,\n ::com::sun::star::lang::XComponent,\n ::com::sun::star::lang::XServiceInfo\n >\n{\n\n class MyAppExitListener : public linguistic::AppExitListener\n {\n ConvDicList & rMyDicList;\n\n public:\n MyAppExitListener( ConvDicList &rDicList ) : rMyDicList( rDicList ) {}\n virtual void AtExit();\n };\n\n\n ::cppu::OInterfaceContainerHelper aEvtListeners;\n\n ConvDicNameContainer *pNameContainer;\n ::com::sun::star::uno::Reference<\n ::com::sun::star::container::XNameContainer > xNameContainer;\n\n MyAppExitListener *pExitListener;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::\n XTerminateListener > xExitListener;\n\n BOOL bDisposing;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n ConvDicList( const ConvDicList & );\n ConvDicList & operator = (const ConvDicList &);\n\n ConvDicNameContainer & GetNameContainer();\n\npublic:\n ConvDicList();\n virtual ~ConvDicList();\n\n \/\/ XConversionDictionaryList\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > SAL_CALL getDictionaryContainer( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XConversionDictionary > SAL_CALL addNewDictionary( const ::rtl::OUString& aName, const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nConversionDictionaryType ) throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL queryConversions( const ::rtl::OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nConversionDictionaryType, ::com::sun::star::linguistic2::ConversionDirection eDirection, sal_Int32 nTextConversionOptions ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL queryMaxCharCount( const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nConversionDictionaryType, ::com::sun::star::linguistic2::ConversionDirection eDirection ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XComponent\n virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n\n static inline ::rtl::OUString\n getImplementationName_Static() throw();\n static com::sun::star::uno::Sequence< ::rtl::OUString >\n getSupportedServiceNames_Static() throw();\n\n \/\/ non UNO-specific\n void FlushDics();\n};\n\ninline ::rtl::OUString ConvDicList::getImplementationName_Static() throw()\n{\n return A2OU( \"com.sun.star.lingu2.ConvDicList\" );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 - 2022 R. Thomas\n * Copyright 2017 - 2022 Quarkslab\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 <fstream>\n\n#include \"LIEF\/VDEX.hpp\"\n#include \"LIEF\/VDEX\/File.hpp\"\n#include \"LIEF\/DEX\/File.hpp\"\n\n#include \"LIEF\/OAT\/Binary.hpp\"\n#include \"LIEF\/OAT\/hash.hpp\"\n#include \"logging.hpp\"\n#include \"visitors\/json.hpp\"\n\n\nnamespace LIEF {\nnamespace OAT {\n\nBinary::Binary() = default;\nBinary::~Binary() = default;\n\nconst Header& Binary::header() const {\n return header_;\n}\n\nHeader& Binary::header() {\n return const_cast<Header&>(static_cast<const Binary*>(this)->header());\n}\n\nBinary::it_dex_files Binary::dex_files() {\n if (vdex_ != nullptr) {\n return vdex_->dex_files_;\n }\n return dex_files_;\n}\n\nBinary::it_const_dex_files Binary::dex_files() const {\n if (vdex_ != nullptr) {\n return vdex_->dex_files_;\n }\n return dex_files_;\n}\n\nBinary::it_oat_dex_files Binary::oat_dex_files() {\n return oat_dex_files_;\n}\n\nBinary::it_const_oat_dex_files Binary::oat_dex_files() const {\n return oat_dex_files_;\n}\n\n\nBinary::it_const_classes Binary::classes() const {\n return classes_list_;\n}\n\nBinary::it_classes Binary::classes() {\n return classes_list_;\n}\n\nbool Binary::has_class(const std::string& class_name) const {\n return classes_.find(DEX::Class::fullname_normalized(class_name)) != std::end(classes_);\n}\n\nconst Class* Binary::get_class(const std::string& class_name) const {\n auto it = classes_.find(DEX::Class::fullname_normalized(class_name));\n if (it == std::end(classes_)) {\n return nullptr;\n }\n return it->second;\n}\n\nClass* Binary::get_class(const std::string& class_name) {\n return const_cast<Class*>(static_cast<const Binary*>(this)->get_class(class_name));\n}\n\n\nconst Class* Binary::get_class(size_t index) const {\n if (index >= classes_.size()) {\n return nullptr;\n }\n\n const auto it = std::find_if(std::begin(classes_), std::end(classes_),\n [index] (const std::pair<std::string, Class*>& p) {\n return p.second->index() == index;\n });\n\n if (it == std::end(classes_)) {\n return nullptr;\n }\n return it->second;\n}\n\nClass* Binary::get_class(size_t index) {\n return const_cast<Class*>(static_cast<const Binary*>(this)->get_class(index));\n}\n\nBinary::it_const_methods Binary::methods() const {\n return methods_;\n}\n\nBinary::it_methods Binary::methods() {\n return methods_;\n}\n\nBinary::dex2dex_info_t Binary::dex2dex_info() const {\n dex2dex_info_t info;\n\n for (const DEX::File& dex_file : dex_files()) {\n info.emplace(&dex_file, dex_file.dex2dex_info());\n }\n return info;\n}\n\nstd::string Binary::dex2dex_json_info() {\n\n#if defined(LIEF_JSON_SUPPORT)\n json mapping = json::object();\n\n for (const DEX::File& dex_file : dex_files()) {\n json dex2dex = json::parse(dex_file.dex2dex_json_info());\n mapping[dex_file.name()] = dex2dex;\n }\n\n return mapping.dump();\n#else\n return \"\";\n#endif\n\n}\n\nvoid Binary::add_class(std::unique_ptr<Class> cls) {\n classes_.emplace(cls->fullname(), cls.get());\n classes_list_.push_back(std::move(cls));\n}\n\nvoid Binary::accept(Visitor& visitor) const {\n visitor.visit(*this);\n}\n\nbool Binary::operator==(const Binary& rhs) const {\n if (this == &rhs) {\n return true;\n }\n size_t hash_lhs = Hash::hash(*this);\n size_t hash_rhs = Hash::hash(rhs);\n return hash_lhs == hash_rhs;\n}\n\nbool Binary::operator!=(const Binary& rhs) const {\n return !(*this == rhs);\n}\n\nstd::ostream& operator<<(std::ostream& os, const Binary& binary) {\n\n os << \"Header\" << std::endl;\n os << \"======\" << std::endl;\n os << binary.header() << std::endl;\n\n if (binary.oat_dex_files().size() > 0) {\n os << \"Dex Files\" << std::endl;\n os << \"=========\" << std::endl;\n\n for (const DexFile& dex : binary.oat_dex_files()) {\n os << dex << std::endl;\n }\n }\n\n std::cout << \"Number of classes: \" << std::dec << binary.classes().size() << std::endl;\n std::cout << \"Number of methods: \" << std::dec << binary.methods().size() << std::endl;\n\n\n return os;\n}\n\n\n}\n}\n<commit_msg>Fix std::cout<commit_after>\/* Copyright 2017 - 2022 R. Thomas\n * Copyright 2017 - 2022 Quarkslab\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 <fstream>\n\n#include \"LIEF\/VDEX.hpp\"\n#include \"LIEF\/VDEX\/File.hpp\"\n#include \"LIEF\/DEX\/File.hpp\"\n\n#include \"LIEF\/OAT\/Binary.hpp\"\n#include \"LIEF\/OAT\/hash.hpp\"\n#include \"logging.hpp\"\n#include \"visitors\/json.hpp\"\n\n\nnamespace LIEF {\nnamespace OAT {\n\nBinary::Binary() = default;\nBinary::~Binary() = default;\n\nconst Header& Binary::header() const {\n return header_;\n}\n\nHeader& Binary::header() {\n return const_cast<Header&>(static_cast<const Binary*>(this)->header());\n}\n\nBinary::it_dex_files Binary::dex_files() {\n if (vdex_ != nullptr) {\n return vdex_->dex_files_;\n }\n return dex_files_;\n}\n\nBinary::it_const_dex_files Binary::dex_files() const {\n if (vdex_ != nullptr) {\n return vdex_->dex_files_;\n }\n return dex_files_;\n}\n\nBinary::it_oat_dex_files Binary::oat_dex_files() {\n return oat_dex_files_;\n}\n\nBinary::it_const_oat_dex_files Binary::oat_dex_files() const {\n return oat_dex_files_;\n}\n\n\nBinary::it_const_classes Binary::classes() const {\n return classes_list_;\n}\n\nBinary::it_classes Binary::classes() {\n return classes_list_;\n}\n\nbool Binary::has_class(const std::string& class_name) const {\n return classes_.find(DEX::Class::fullname_normalized(class_name)) != std::end(classes_);\n}\n\nconst Class* Binary::get_class(const std::string& class_name) const {\n auto it = classes_.find(DEX::Class::fullname_normalized(class_name));\n if (it == std::end(classes_)) {\n return nullptr;\n }\n return it->second;\n}\n\nClass* Binary::get_class(const std::string& class_name) {\n return const_cast<Class*>(static_cast<const Binary*>(this)->get_class(class_name));\n}\n\n\nconst Class* Binary::get_class(size_t index) const {\n if (index >= classes_.size()) {\n return nullptr;\n }\n\n const auto it = std::find_if(std::begin(classes_), std::end(classes_),\n [index] (const std::pair<std::string, Class*>& p) {\n return p.second->index() == index;\n });\n\n if (it == std::end(classes_)) {\n return nullptr;\n }\n return it->second;\n}\n\nClass* Binary::get_class(size_t index) {\n return const_cast<Class*>(static_cast<const Binary*>(this)->get_class(index));\n}\n\nBinary::it_const_methods Binary::methods() const {\n return methods_;\n}\n\nBinary::it_methods Binary::methods() {\n return methods_;\n}\n\nBinary::dex2dex_info_t Binary::dex2dex_info() const {\n dex2dex_info_t info;\n\n for (const DEX::File& dex_file : dex_files()) {\n info.emplace(&dex_file, dex_file.dex2dex_info());\n }\n return info;\n}\n\nstd::string Binary::dex2dex_json_info() {\n\n#if defined(LIEF_JSON_SUPPORT)\n json mapping = json::object();\n\n for (const DEX::File& dex_file : dex_files()) {\n json dex2dex = json::parse(dex_file.dex2dex_json_info());\n mapping[dex_file.name()] = dex2dex;\n }\n\n return mapping.dump();\n#else\n return \"\";\n#endif\n\n}\n\nvoid Binary::add_class(std::unique_ptr<Class> cls) {\n classes_.emplace(cls->fullname(), cls.get());\n classes_list_.push_back(std::move(cls));\n}\n\nvoid Binary::accept(Visitor& visitor) const {\n visitor.visit(*this);\n}\n\nbool Binary::operator==(const Binary& rhs) const {\n if (this == &rhs) {\n return true;\n }\n size_t hash_lhs = Hash::hash(*this);\n size_t hash_rhs = Hash::hash(rhs);\n return hash_lhs == hash_rhs;\n}\n\nbool Binary::operator!=(const Binary& rhs) const {\n return !(*this == rhs);\n}\n\nstd::ostream& operator<<(std::ostream& os, const Binary& binary) {\n\n os << \"Header\" << std::endl;\n os << \"======\" << std::endl;\n os << binary.header() << std::endl;\n\n if (binary.oat_dex_files().size() > 0) {\n os << \"Dex Files\" << std::endl;\n os << \"=========\" << std::endl;\n\n for (const DexFile& dex : binary.oat_dex_files()) {\n os << dex << std::endl;\n }\n }\n\n os << \"Number of classes: \" << std::dec << binary.classes().size() << std::endl;\n os << \"Number of methods: \" << std::dec << binary.methods().size() << std::endl;\n\n\n return os;\n}\n\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/@HEADER\n\/\/ ***************************************************\n\/\/\n\/\/ HPCG: High Performance Conjugate Gradient Benchmark\n\/\/\n\/\/ Contact:\n\/\/ Michael A. Heroux ( maherou@sandia.gov)\n\/\/ Jack Dongarra (dongarra@eecs.utk.edu)\n\/\/ Piotr Luszczek (luszczek@eecs.utk.edu)\n\/\/\n\/\/ ***************************************************\n\/\/@HEADER\n\n\/*!\n @file Output_File.hpp\n\n HPCG output file classes\n *\/\n\n#ifndef OUTPUTFILE_HPP\n#define OUTPUTFILE_HPP\n\n#include <list>\n#include <string>\n\n\/\/! The OutputFile class for the uniform collecting and reporting of performance data for HPCG\n\n\/*!\n\n The OutputFile class facilitates easy collecting and reporting of\n key-value-formatted data that can be then registered with the HPCG results\n collection website. The keys may have hierarchy key1::key2::key3=val with\n double colon :: as a seperator. A sample output may look like this (note how\n \"major\" and \"micro\" keys repeat with different ancestor keys):\n\n\\code\n\nversion=3.2.1alpha\nversion::major=3\nversion::minor=2\nversion::micro=1\nversion::release=alpha\naxis=xyz\naxis::major=x\naxis::minor=y\n\n\\endcode\n\n*\/\nclass OutputFile {\nprotected:\n std::list<OutputFile *> descendants; \/\/!< descendant elements\n std::string name; \/\/!< name of the benchmark\n std::string version; \/\/!< version of the benchmark\n std::string key; \/\/!< the key under which the element is stored\n std::string value; \/\/!< the value of the stored element\n std::string eol = \"\\n\"; \/\/!< end-of-line character sequence in the output file\n std::string keySeparator = \"::\"; \/\/!< character sequence to separate keys in the output file\n\n \/\/! Recursively generate output string from descendant list, and their descendants and so on\n std::string generateRecursive(std::string prefix);\n\npublic:\n static OutputFile * allocKeyVal(const std::string & key, const std::string & value);\n\n \/\/! Constructor: accepts name and version as strings that are used to create a file name for printing results.\n \/*!\n This constructor accepts and name and version number for the benchmark that\n are used to form a file name information for results that are generated by\n the generate() method.\n \\param name (in) string containing name of the benchmark\n \\param version (in) string containing the version of the benchmark\n *\/\n OutputFile(const std::string & name, const std::string & version);\n\n \/\/! Default constructor: no-arguments accepted, should be used for descendant nodes\n \/*!\n This no-argument constructor can be used for descendant nodes to provide\n key1::key2::key3=val output. Unlike the root node, descendant nodes do not\n have name and version but only store key-value pairs.\n *\/\n OutputFile(void);\n\n ~OutputFile();\n\n \/\/! Create and add a descendant element with value of type \"string\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, const std::string & value);\n\n \/\/! Create and add a descendant element with value of type \"double\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, double value);\n\n \/\/! Create and add a descendant element with value of type \"int\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, int value);\n\n#ifndef HPCG_NO_LONG_LONG\n \/\/! Create and add a descendant element with value of type \"long long\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, long long value);\n#endif\n\n \/\/! Create and add a descendant element with value of type \"size_t\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, size_t value);\n\n \/\/! Key-Value setter method\n \/*!\n Set the key and the value of this element.\n\n @param[in] key The key that identifies this element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void setKeyValue(const std::string & key, const std::string & value);\n\n \/\/! Get the element in the list with the given key or return NULL if not found\n OutputFile * get(const std::string & key);\n\n \/\/! Generate output string with results based on the stored key-value hierarchy\n std::string generate(void);\n};\n\n#endif \/\/ OUTPUTFILE_HPP\n<commit_msg>Fix spelling error<commit_after>\n\/\/@HEADER\n\/\/ ***************************************************\n\/\/\n\/\/ HPCG: High Performance Conjugate Gradient Benchmark\n\/\/\n\/\/ Contact:\n\/\/ Michael A. Heroux ( maherou@sandia.gov)\n\/\/ Jack Dongarra (dongarra@eecs.utk.edu)\n\/\/ Piotr Luszczek (luszczek@eecs.utk.edu)\n\/\/\n\/\/ ***************************************************\n\/\/@HEADER\n\n\/*!\n @file Output_File.hpp\n\n HPCG output file classes\n *\/\n\n#ifndef OUTPUTFILE_HPP\n#define OUTPUTFILE_HPP\n\n#include <list>\n#include <string>\n\n\/\/! The OutputFile class for the uniform collecting and reporting of performance data for HPCG\n\n\/*!\n\n The OutputFile class facilitates easy collecting and reporting of\n key-value-formatted data that can be then registered with the HPCG results\n collection website. The keys may have hierarchy key1::key2::key3=val with\n double colon :: as a separator. A sample output may look like this (note how\n \"major\" and \"micro\" keys repeat with different ancestor keys):\n\n\\code\n\nversion=3.2.1alpha\nversion::major=3\nversion::minor=2\nversion::micro=1\nversion::release=alpha\naxis=xyz\naxis::major=x\naxis::minor=y\n\n\\endcode\n\n*\/\nclass OutputFile {\nprotected:\n std::list<OutputFile *> descendants; \/\/!< descendant elements\n std::string name; \/\/!< name of the benchmark\n std::string version; \/\/!< version of the benchmark\n std::string key; \/\/!< the key under which the element is stored\n std::string value; \/\/!< the value of the stored element\n std::string eol = \"\\n\"; \/\/!< end-of-line character sequence in the output file\n std::string keySeparator = \"::\"; \/\/!< character sequence to separate keys in the output file\n\n \/\/! Recursively generate output string from descendant list, and their descendants and so on\n std::string generateRecursive(std::string prefix);\n\npublic:\n static OutputFile * allocKeyVal(const std::string & key, const std::string & value);\n\n \/\/! Constructor: accepts name and version as strings that are used to create a file name for printing results.\n \/*!\n This constructor accepts and name and version number for the benchmark that\n are used to form a file name information for results that are generated by\n the generate() method.\n \\param name (in) string containing name of the benchmark\n \\param version (in) string containing the version of the benchmark\n *\/\n OutputFile(const std::string & name, const std::string & version);\n\n \/\/! Default constructor: no-arguments accepted, should be used for descendant nodes\n \/*!\n This no-argument constructor can be used for descendant nodes to provide\n key1::key2::key3=val output. Unlike the root node, descendant nodes do not\n have name and version but only store key-value pairs.\n *\/\n OutputFile(void);\n\n ~OutputFile();\n\n \/\/! Create and add a descendant element with value of type \"string\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, const std::string & value);\n\n \/\/! Create and add a descendant element with value of type \"double\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, double value);\n\n \/\/! Create and add a descendant element with value of type \"int\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, int value);\n\n#ifndef HPCG_NO_LONG_LONG\n \/\/! Create and add a descendant element with value of type \"long long\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, long long value);\n#endif\n\n \/\/! Create and add a descendant element with value of type \"size_t\"\n \/*!\n Create and add a descendant element identified by \"key\" and associated with\n \"value\". The element is added at the end of a list of previously added\n elements.\n\n @param[in] key The key that identifies the added element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void add(const std::string & key, size_t value);\n\n \/\/! Key-Value setter method\n \/*!\n Set the key and the value of this element.\n\n @param[in] key The key that identifies this element and under which the element is stored\n @param[in] value The value stored by the element\n *\/\n void setKeyValue(const std::string & key, const std::string & value);\n\n \/\/! Get the element in the list with the given key or return NULL if not found\n OutputFile * get(const std::string & key);\n\n \/\/! Generate output string with results based on the stored key-value hierarchy\n std::string generate(void);\n};\n\n#endif \/\/ OUTPUTFILE_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"NetworkServer.hpp\"\n\nNetworkWorker* NetworkWorker::singleton = nullptr;\nNetworkWorker::NetworkWorker()\n{\n\tif(singleton) exit(-1);\n\tsingleton = this;\n}\n\nAnnVect3 NetworkWorker::getDistantPosition()\n{\n\treturn distantPosition;\n}\n\nvoid NetworkWorker::setLocalPositon(AnnVect3 position)\n{\n\tlocalPosiion = position;\n}\n\n\nNetworkServer::NetworkServer() : NetworkWorker(),\n\tport(ANVPORT)\n{\n\t\/\/Singleton check\n\n\n\tmyType = SERVER;\n\n\n}\n\nNetworkWorker* NetworkWorker::getSingleton()\n{\n\treturn singleton;\n}\n\nworkerType NetworkWorker::getType()\n{\n\treturn myType;\n}\n\n\nint NetworkServer::initialize(int port)\n{\n\tstd::stringstream ss;\n\tif(port < netNS::MIN_PORT)\n\t{\n\t\tAnnDebug() << \"Invalid port number\";\n\t\treturn netNS::NET_ERROR;\n\t}\n\t\/\/ ------ init network stuff -------\n\terror = net.createServer(port, netNS::UDP);\n\tif(error != netNS::NET_OK)\n\t{\n\t\tAnnDebug() << net.getError(error);\n\t\treturn netNS::NET_ERROR;\n\t}\n\n\tfor (int i=0; i<MAX_CLIENT; i++)\n\t{\n\t\tplayer[i].setConnected(false);\n\t\tplayer[i].setActive(false);\n\t}\n\n\tAnnDebug() << \"---- Server ----\";\n\tnet.getLocalIP(localIP);\n\tss << \"Server IP: \" << localIP;\n\tAnnDebug() << ss.str();\n\tss.str(\"\");\n\tss << \"Port: \" << port;\n\tAnnDebug() << ss.str();\n\treturn netNS::NET_OK;\n}\n\n\/\/ --- Do network communications ---\nvoid NetworkServer::communicate(float frameTime)\n{\n\t\/\/ communicate with client \n\tdoClientCommunication(); \n\t\/\/ Calculate elapsed time for network communications\n\tnetTime += frameTime;\n\tif(netTime < netNS::NET_TIMER)\n\t\treturn;\n\n\tnetTime -= netNS::NET_TIMER;\n\t\/\/ check for inactive clients, called every NET_TIMER seconds\n\tcheckNetworkTimeout(); \n}\n\n\/\/ --- Check for network timeout ---\n\nvoid NetworkServer::checkNetworkTimeout()\n{\n\tstd::stringstream ss;\n\tfor (int i=0; i<MAX_CLIENT; i++)\n\t{\n\t\tif (player[i].getConnected())\n\t\t{\n\t\t\tplayer[i].incTimeout();\n\t\t\t\/\/ if communication timout \n\t\t\tif (player[i].getTimeout() > netNS::MAX_ERRORS)\n\t\t\t{\n\t\t\t\tplayer[i].setActive(false);\n\t\t\t\tss << \"***** Player \" << i << \" disconnected. *****\";\n\t\t\t\tAnnDebug() << ss.str();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NetworkServer::doClientCommunication() \n{\n\tint playN;\n\tint size;\n\tprepareDataForClient(); \n\tfor (int i=0; i<MAX_CLIENT; i++)\n\t{\n\t\tsize = sizeof(toServerData);\n\t\tif(net.readData((char*) &toServerData, size, remoteIP, port) == netNS::NET_OK)\n\t\t{ \n\t\t\t\t\tAnnDebug() << \"Got \" << size << \" bytes from the network\";\n\t\t\tif(size > 0)\n\t\t\t{\n\t\t\t\t\/*AnnDebug() << \"there are things here...\";\n\t\t\t\t\/\/AnnDebug() << (char*) &toServerData;\n\t\t\t\tAnnDebug() << \"player n : \" << toServerData.playerN;\n\t\t\t\tAnnDebug() << \"x \" << toServerData.x;\n\t\t\t\tAnnDebug() << \"y \" << toServerData.y;\n\t\t\t\tAnnDebug() << \"z \" << toServerData.z;*\/\n\t\t\t\tplayN = toServerData.playerN;\n\t\t\t\tif (playN == 255)\n\t\t\t\t{\n\t\t\t\t\tclientWantToJoin(); \n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tAnnDebug() << \"got this : \" << toServerData.ClientPaddlePos;\n\t\t\t\t\tif (player[playN].getConnected())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (player[playN].getActive());\n\t\t\t\t\t\t\t\/\/player[playN].setButtons(toServerData.buttons);\n\t\t\t\t\t\tsize = sizeof(toClientData);\n\t\t\t\t\t\t\/\/ send player the latest game data\n\t\t\t\t\t\tnet.sendData((char*) &toClientData, size, player[i].getNetIP(), port);\n\t\t\t\t\t\tplayer[playN].setTimeout(0);\n\t\t\t\t\t\tplayer[playN].setCommWarnings(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse \/\/ No more incomming data ? break !!\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid NetworkServer::prepareDataForClient() \n{\n\t\/*for (int i=0; i<MAX_CLIENT; i++)\n\t{\n\t\ttoClientData.player[i].playerData = player[i].getNetData();\n\t}*\/\n\n\t\/\/toClientData.puckPosition = AnnVect3(5,5,5);\n\t\/\/toClientData.serverPaddlePos = AnnVect3(10, 10, 10);\n\ttoClientData.postition = AnnVect3(3,2,1);\n}\n\n\/\/========================================================================\n\/\/ Client is requesting to join game\n\/\/========================================================================\n\nvoid NetworkServer::clientWantToJoin()\n{\n\tstd::stringstream ss;\n\tint size;\n\tint status;\n\tconnectResponse.number = 255;\n\tif (playerCount == 0)\n\t{\n\t\troundOver = true; \/\/ this needs to reset the game states !! I don't know how :\/\n\t\t\/\/ score system goes here (TODO)\n\t}\n\tAnnDebug() << \"Player requesting to join.\";\n\t\/\/ find available player position to use\n\tfor(int i=0; i<MAX_CLIENT; i++) \/\/ search all player position\n\t{\n\t\tif (player[i].getConnected() == false) \/\/ if this position available\n\t\t{\n\t\t\tplayer[i].setConnected(true);\n\t\t\tplayer[i].setTimeout(0);\n\t\t\tplayer[i].setCommWarnings(0);\n\t\t\tplayer[i].setNetIP(remoteIP); \/\/ save player's IP\n\t\t\tplayer[i].setCommErrors(0); \/\/ clear old errors\n\t\t\t\/\/ send SERVER_ID adn player number to client\n\t\t\tstrcpy_s(connectResponse.response, netNS::SERVER_ID);\n\t\t\tconnectResponse.number = (UCHAR)i;\n\t\t\tsize = sizeof(connectResponse);\n\t\t\tstatus = net.sendData((char*) &connectResponse, size, remoteIP, port);\n\t\t\tif (status == netNS::NET_ERROR)\n\t\t\t{\n\t\t\t\tAnnDebug() << net.getError(status); \/\/ display error\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttoServerData.playerN = i; \/\/ clear join request from\n\t\t\t\t\t\t\t\t\t \/\/ input buffer\n\t\t\tss << \"Connected player as number: \" << i;\n\t\t\tAnnDebug() << ss.str(); \/\/ found available player\n\t\t\treturn;\n\t\t}\n\t}\n\t\/\/ send SERVER_FULL to client\n\tstrcpy_s(connectResponse.response, netNS::SERVER_FULL);\n\tsize = sizeof(connectResponse);\n\tstatus = net.sendData((char*)&connectResponse, size, remoteIP, port);\n\tAnnDebug() << \"server full.\";\n}\n\n\nvoid NetworkServer::update()\n{\n\tcountDownTimer = COUNT_DOWN;\n countDownOn = true;\n roundOver = false;\n\n\t\/\/ set the state to indicate new round\n toClientData.gameState |= ROUND_START_BIT;\n\n\tfloat frameTime = AnnEngine::Instance()->getTimeFromStartUp();\n\tcommunicate(frameTime);\n}\n\n\n<commit_msg>server side of sync test<commit_after>#include \"stdafx.h\"\n#include \"NetworkServer.hpp\"\n\nNetworkWorker* NetworkWorker::singleton = nullptr;\nNetworkWorker::NetworkWorker()\n{\n\tif(singleton) exit(-1);\n\tsingleton = this;\n}\n\nAnnVect3 NetworkWorker::getDistantPosition()\n{\n\treturn distantPosition;\n}\n\nvoid NetworkWorker::setLocalPositon(AnnVect3 position)\n{\n\tlocalPosiion = position;\n}\n\n\nNetworkServer::NetworkServer() : NetworkWorker(),\n\tport(ANVPORT)\n{\n\t\/\/Singleton check\n\n\n\tmyType = SERVER;\n\n\n}\n\nNetworkWorker* NetworkWorker::getSingleton()\n{\n\treturn singleton;\n}\n\nworkerType NetworkWorker::getType()\n{\n\treturn myType;\n}\n\n\nint NetworkServer::initialize(int port)\n{\n\tstd::stringstream ss;\n\tif(port < netNS::MIN_PORT)\n\t{\n\t\tAnnDebug() << \"Invalid port number\";\n\t\treturn netNS::NET_ERROR;\n\t}\n\t\/\/ ------ init network stuff -------\n\terror = net.createServer(port, netNS::UDP);\n\tif(error != netNS::NET_OK)\n\t{\n\t\tAnnDebug() << net.getError(error);\n\t\treturn netNS::NET_ERROR;\n\t}\n\n\tfor (int i=0; i<MAX_CLIENT; i++)\n\t{\n\t\tplayer[i].setConnected(false);\n\t\tplayer[i].setActive(false);\n\t}\n\n\tAnnDebug() << \"---- Server ----\";\n\tnet.getLocalIP(localIP);\n\tss << \"Server IP: \" << localIP;\n\tAnnDebug() << ss.str();\n\tss.str(\"\");\n\tss << \"Port: \" << port;\n\tAnnDebug() << ss.str();\n\treturn netNS::NET_OK;\n}\n\n\/\/ --- Do network communications ---\nvoid NetworkServer::communicate(float frameTime)\n{\n\t\/\/ communicate with client \n\tdoClientCommunication(); \n\t\/\/ Calculate elapsed time for network communications\n\tnetTime += frameTime;\n\tif(netTime < netNS::NET_TIMER)\n\t\treturn;\n\n\tnetTime -= netNS::NET_TIMER;\n\t\/\/ check for inactive clients, called every NET_TIMER seconds\n\tcheckNetworkTimeout(); \n}\n\n\/\/ --- Check for network timeout ---\n\nvoid NetworkServer::checkNetworkTimeout()\n{\n\tstd::stringstream ss;\n\tfor (int i=0; i<MAX_CLIENT; i++)\n\t{\n\t\tif (player[i].getConnected())\n\t\t{\n\t\t\tplayer[i].incTimeout();\n\t\t\t\/\/ if communication timout \n\t\t\tif (player[i].getTimeout() > netNS::MAX_ERRORS)\n\t\t\t{\n\t\t\t\tplayer[i].setActive(false);\n\t\t\t\tss << \"***** Player \" << i << \" disconnected. *****\";\n\t\t\t\tAnnDebug() << ss.str();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NetworkServer::doClientCommunication() \n{\n\tint playN;\n\tint size;\n\tprepareDataForClient(); \n\tfor (int i=0; i<MAX_CLIENT; i++)\n\t{\n\t\tsize = sizeof(toServerData);\n\t\tif(net.readData((char*) &toServerData, size, remoteIP, port) == netNS::NET_OK)\n\t\t{ \n\t\t\t\t\tAnnDebug() << \"Got \" << size << \" bytes from the network\";\n\t\t\tif(size > 0)\n\t\t\t{\n\t\t\t\t\/*AnnDebug() << \"there are things here...\";\n\t\t\t\t\/\/AnnDebug() << (char*) &toServerData;\n\t\t\t\tAnnDebug() << \"player n : \" << toServerData.playerN;\n\t\t\t\tAnnDebug() << \"x \" << toServerData.x;\n\t\t\t\tAnnDebug() << \"y \" << toServerData.y;\n\t\t\t\tAnnDebug() << \"z \" << toServerData.z;*\/\n\t\t\t\tplayN = toServerData.playerN;\n\t\t\t\tif (playN == 255)\n\t\t\t\t{\n\t\t\t\t\tclientWantToJoin(); \n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tAnnDebug() << \"got this : \" << toServerData.ClientPaddlePos;\n\t\t\t\t\tdistantPosition = toServerData.ClientPaddlePos;\n\t\t\t\t\tif (player[playN].getConnected())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (player[playN].getActive());\n\t\t\t\t\t\t\t\/\/player[playN].setButtons(toServerData.buttons);\n\t\t\t\t\t\tsize = sizeof(toClientData);\n\t\t\t\t\t\t\/\/ send player the latest game data\n\t\t\t\t\t\tnet.sendData((char*) &toClientData, size, player[i].getNetIP(), port);\n\t\t\t\t\t\tplayer[playN].setTimeout(0);\n\t\t\t\t\t\tplayer[playN].setCommWarnings(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse \/\/ No more incomming data ? break !!\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid NetworkServer::prepareDataForClient() \n{\n\t\/*for (int i=0; i<MAX_CLIENT; i++)\n\t{\n\t\ttoClientData.player[i].playerData = player[i].getNetData();\n\t}*\/\n\n\t\/\/toClientData.puckPosition = AnnVect3(5,5,5);\n\t\/\/toClientData.serverPaddlePos = AnnVect3(10, 10, 10);\n\ttoClientData.postition = localPosiion;\n}\n\n\/\/========================================================================\n\/\/ Client is requesting to join game\n\/\/========================================================================\n\nvoid NetworkServer::clientWantToJoin()\n{\n\tstd::stringstream ss;\n\tint size;\n\tint status;\n\tconnectResponse.number = 255;\n\tif (playerCount == 0)\n\t{\n\t\troundOver = true; \/\/ this needs to reset the game states !! I don't know how :\/\n\t\t\/\/ score system goes here (TODO)\n\t}\n\tAnnDebug() << \"Player requesting to join.\";\n\t\/\/ find available player position to use\n\tfor(int i=0; i<MAX_CLIENT; i++) \/\/ search all player position\n\t{\n\t\tif (player[i].getConnected() == false) \/\/ if this position available\n\t\t{\n\t\t\tplayer[i].setConnected(true);\n\t\t\tplayer[i].setTimeout(0);\n\t\t\tplayer[i].setCommWarnings(0);\n\t\t\tplayer[i].setNetIP(remoteIP); \/\/ save player's IP\n\t\t\tplayer[i].setCommErrors(0); \/\/ clear old errors\n\t\t\t\/\/ send SERVER_ID adn player number to client\n\t\t\tstrcpy_s(connectResponse.response, netNS::SERVER_ID);\n\t\t\tconnectResponse.number = (UCHAR)i;\n\t\t\tsize = sizeof(connectResponse);\n\t\t\tstatus = net.sendData((char*) &connectResponse, size, remoteIP, port);\n\t\t\tif (status == netNS::NET_ERROR)\n\t\t\t{\n\t\t\t\tAnnDebug() << net.getError(status); \/\/ display error\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttoServerData.playerN = i; \/\/ clear join request from\n\t\t\t\t\t\t\t\t\t \/\/ input buffer\n\t\t\tss << \"Connected player as number: \" << i;\n\t\t\tAnnDebug() << ss.str(); \/\/ found available player\n\t\t\treturn;\n\t\t}\n\t}\n\t\/\/ send SERVER_FULL to client\n\tstrcpy_s(connectResponse.response, netNS::SERVER_FULL);\n\tsize = sizeof(connectResponse);\n\tstatus = net.sendData((char*)&connectResponse, size, remoteIP, port);\n\tAnnDebug() << \"server full.\";\n}\n\n\nvoid NetworkServer::update()\n{\n\tcountDownTimer = COUNT_DOWN;\n countDownOn = true;\n roundOver = false;\n\n\t\/\/ set the state to indicate new round\n toClientData.gameState |= ROUND_START_BIT;\n\n\tfloat frameTime = AnnEngine::Instance()->getTimeFromStartUp();\n\tcommunicate(frameTime);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>we need to copy the formula cell as well<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Another Windows build fix - too much C++11 for MSVC 2012...<commit_after><|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Initial Developer of the Original Code is\n * Novell Inc.\n * Portions created by the Initial Developer are Copyright (C) 2010 the\n * Initial Developer. All Rights Reserved.\n *\n * Contributor(s): Amelia Wang <amwang@novell.com>\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\/\/------------------------------------------------------------------\n\n#include \"datafdlg.hxx\"\n#include \"scresid.hxx\"\n#include \"datafdlg.hrc\"\n#include \"viewdata.hxx\"\n\/\/#include \"document.hxx\"\n#include \"docsh.hxx\"\n#include \"refundo.hxx\"\n#include \"undodat.hxx\"\n\n#define HDL(hdl) LINK( this, ScDataFormDlg, hdl )\n\n\/\/zhangyun\nScDataFormDlg::ScDataFormDlg( Window* pParent, ScTabViewShell* pTabViewShellOri) :\n ModalDialog ( pParent, ScResId( RID_SCDLG_DATAFORM ) ),\n \/\/\n aBtnNew ( this, ScResId( BTN_DATAFORM_NEW ) ),\n aBtnDelete ( this, ScResId( BTN_DATAFORM_DELETE ) ),\n aBtnRestore ( this, ScResId( BTN_DATAFORM_RESTORE ) ),\n aBtnLast ( this, ScResId( BTN_DATAFORM_LAST ) ),\n aBtnNext ( this, ScResId( BTN_DATAFORM_NEXT ) ),\n aBtnClose ( this, ScResId( BTN_DATAFORM_CLOSE ) ),\n aSlider ( this, ScResId( WND_DATAFORM_SCROLLBAR ) ),\n aFixedText ( this, ScResId( LAB_DATAFORM_RECORDNO ) )\n{\n pTabViewShell = pTabViewShellOri;\n FreeResource();\n \/\/read header form current document, and add new controls\n DBG_ASSERT( pTabViewShell, \"pTabViewShell is NULL! :-\/\" );\n ScViewData* pViewData = pTabViewShell->GetViewData();\n\n pDoc = pViewData->GetDocument();\n if (pDoc)\n {\n ScRange aRange;\n pViewData->GetSimpleArea( aRange );\n ScAddress aStart = aRange.aStart;\n ScAddress aEnd = aRange.aEnd;\n\n nStartCol = aStart.Col();\n nEndCol = aEnd.Col();\n nStartRow = aStart.Row();\n nEndRow = aEnd.Row();\n\n nTab = pViewData->GetTabNo();\n \/\/if there is no selection\n if ((nStartCol == nEndCol) && (nStartRow == nEndRow))\n bNoSelection = TRUE;\n\n if (bNoSelection)\n {\n \/\/find last not blank cell in row\n for (int i=1;i<=MAX_DATAFORM_COLS;i++)\n {\n String aColName;\n nEndCol++;\n pDoc->GetString( nEndCol, nStartRow, nTab, aColName );\n int nColWidth = pDoc->GetColWidth( nEndCol, nTab );\n if ( aColName.Len() == 0 && nColWidth)\n {\n nEndCol--;\n break;\n }\n }\n\n \/\/find first not blank cell in row\n for (int i=1;i<=MAX_DATAFORM_COLS;i++)\n {\n String aColName;\n if (nStartCol <= 0)\n break;\n nStartCol--;\n\n pDoc->GetString( nStartCol, nStartRow, nTab, aColName );\n int nColWidth = pDoc->GetColWidth( nEndCol, nTab );\n if ( aColName.Len() == 0 && nColWidth)\n {\n nStartCol++;\n break;\n }\n }\n\n \/\/skip leading hide column\n for (int i=1;i<=MAX_DATAFORM_COLS;i++)\n {\n String aColName;\n int nColWidth = pDoc->GetColWidth( nStartCol, nTab );\n if (nColWidth)\n break;\n nStartCol++;\n }\n\n if (nEndCol < nStartCol)\n nEndCol = nStartCol;\n\n \/\/find last not blank cell in row\n for (int i=1;i<=MAX_DATAFORM_ROWS;i++)\n {\n String aColName;\n nEndRow++;\n pDoc->GetString( nStartCol, nEndRow, nTab, aColName );\n if ( aColName.Len() == 0 )\n {\n nEndRow--;\n break;\n }\n }\n\n \/\/find first not blank cell in row\n for (int i=1;i<=MAX_DATAFORM_ROWS;i++)\n {\n String aColName;\n if (nStartRow <= 0)\n break;\n nStartRow--;\n\n pDoc->GetString( nStartCol, nStartRow, nTab, aColName );\n if ( aColName.Len() == 0 )\n {\n nStartRow++;\n break;\n }\n }\n\n if (nEndRow < nStartRow)\n nEndRow = nStartRow;\n }\n\n aCurrentRow = nStartRow + 1;\n\n String aFieldName;\n\n int nTop = 12;\n\n Size nFixedSize(FIXED_WIDTH, CTRL_HEIGHT );\n Size nEditSize(EDIT_WIDTH, CTRL_HEIGHT );\n\n \/\/pFtArray = new FixedText(this);\n aColLength = nEndCol - nStartCol + 1;\n\n \/\/new the controls\n pFixedTexts = new FixedText*[aColLength];\n pEdits = new Edit*[aColLength];\n\n for(sal_uInt16 nIndex = 0; nIndex < aColLength; nIndex++)\n {\n pDoc->GetString( nIndex + nStartCol, nStartRow, nTab, aFieldName );\n int nColWidth = pDoc->GetColWidth( nIndex + nStartCol, nTab );\n if (nColWidth)\n {\n pFixedTexts[nIndex] = new FixedText(this);\n pEdits[nIndex] = new Edit(this, WB_BORDER);\n\n pFixedTexts[nIndex]->SetSizePixel(nFixedSize);\n pEdits[nIndex]->SetSizePixel(nEditSize);\n pFixedTexts[nIndex]->SetPosPixel(Point(FIXED_LEFT, nTop));\n pEdits[nIndex]->SetPosPixel(Point(EDIT_LEFT, nTop));\n \/\/pFixedTexts[nIndex]->SetText(String::CreateFromAscii(\"W4W-Filter Nr. \"));\n pFixedTexts[nIndex]->SetText(aFieldName);\n pFixedTexts[nIndex]->Show();\n pEdits[nIndex]->Show();\n\n nTop += LINE_HEIGHT;\n }\n else\n {\n pFixedTexts[nIndex] = NULL;\n pEdits[nIndex] = NULL;\n }\n pEdits[nIndex]->SetModifyHdl( HDL(Impl_DataModifyHdl) );\n }\n\n Size nDialogSize = this->GetSizePixel();\n if (nTop > nDialogSize.Height())\n {\n nDialogSize.setHeight(nTop);\n this->SetSizePixel(nDialogSize);\n }\n Size nScrollSize = aSlider.GetSizePixel();\n nScrollSize.setHeight(nDialogSize.Height()-20);\n aSlider.SetSizePixel(nScrollSize);\n }\n\n FillCtrls(aCurrentRow);\n\n aSlider.SetPageSize( 10 );\n aSlider.SetVisibleSize( 1 );\n aSlider.SetLineSize( 1 );\n aSlider.SetRange( Range( 0, nEndRow - nStartRow + 1) );\n aSlider.Show();\n\n aBtnNew.SetClickHdl ( HDL(Impl_NewHdl) );\n aBtnLast.SetClickHdl ( HDL(Impl_LastHdl) );\n aBtnNext.SetClickHdl ( HDL(Impl_NextHdl) );\n\n aBtnRestore.SetClickHdl ( HDL(Impl_RestoreHdl) );\n aBtnDelete.SetClickHdl ( HDL(Impl_DeleteHdl) );\n aBtnClose.SetClickHdl ( HDL(Impl_CloseHdl) );\n\n aSlider.SetEndScrollHdl( HDL( Impl_ScrollHdl ) );\n\n SetButtonState();\n\n \/\/end\n \/\/FreeResource();\n}\n\nScDataFormDlg::~ScDataFormDlg()\n{\n for(sal_uInt16 i = 0; i < aColLength; i++)\n {\n if (pEdits[i])\n delete pEdits[i];\n if (pFixedTexts[i])\n delete pFixedTexts[i];\n }\n if (pEdits)\n delete pEdits;\n if (pFixedTexts)\n delete pFixedTexts;\n}\n\nvoid ScDataFormDlg::FillCtrls(SCROW \/*nCurrentRow*\/)\n{\n \/\/ScViewData* pViewData = pTabViewShell->GetViewData();\n\n String aFieldName;\n for (sal_uInt16 i = 0; i < aColLength; ++i)\n {\n if (pEdits[i])\n {\n if (aCurrentRow<=nEndRow)\n {\n pDoc->GetString( i + nStartCol, aCurrentRow, nTab, aFieldName );\n pEdits[i]->SetText(aFieldName);\n }\n else\n pEdits[i]->SetText(String());\n }\n }\n char sRecordStr[256];\n if (aCurrentRow<=nEndRow)\n aFixedText.SetText(String::CreateFromAscii(sRecordStr));\n else\n aFixedText.SetText(String::CreateFromAscii(\"New Record\"));\n\n aSlider.SetThumbPos(aCurrentRow-nStartRow-1);\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_DataModifyHdl, Edit*, pEdit)\n{\n if ( pEdit->IsModified() )\n aBtnRestore.Enable( TRUE );\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_NewHdl, PushButton*, EMPTYARG )\n{\n ScViewData* pViewData = pTabViewShell->GetViewData();\n ScDocShell* pDocSh = pViewData->GetDocShell();\n if ( pDoc )\n {\n sal_Bool bHasData = sal_False;\n for(sal_uInt16 i = 0; i < aColLength; i++)\n if (pEdits[i])\n if ( pEdits[i]->GetText().Len() != 0 )\n {\n bHasData = sal_True;\n break;\n }\n\n if ( bHasData )\n {\n pTabViewShell->DataFormPutData( aCurrentRow , nStartRow , nStartCol , nEndRow , nEndCol , pEdits , aColLength );\n aCurrentRow++;\n if (aCurrentRow >= nEndRow + 2)\n {\n nEndRow ++ ;\n aSlider.SetRange( Range( 0, nEndRow - nStartRow + 1) );\n }\n SetButtonState();\n FillCtrls(aCurrentRow);\n pDocSh->SetDocumentModified();\n pDocSh->PostPaintGridAll();\n }\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_LastHdl, PushButton*, EMPTYARG )\n{\n if (pDoc)\n {\n if ( aCurrentRow > nStartRow +1 )\n aCurrentRow--;\n\n SetButtonState();\n FillCtrls(aCurrentRow);\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_NextHdl, PushButton*, EMPTYARG )\n{\n if (pDoc)\n {\n if ( aCurrentRow <= nEndRow)\n aCurrentRow++;\n\n SetButtonState();\n FillCtrls(aCurrentRow);\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_RestoreHdl, PushButton*, EMPTYARG )\n{\n if (pDoc)\n {\n FillCtrls(aCurrentRow);\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_DeleteHdl, PushButton*, EMPTYARG )\n{\n ScViewData* pViewData = pTabViewShell->GetViewData();\n ScDocShell* pDocSh = pViewData->GetDocShell();\n if (pDoc)\n {\n ScRange aRange(nStartCol, aCurrentRow, nTab, nEndCol, aCurrentRow, nTab);\n pDoc->DeleteRow(aRange);\n nEndRow--;\n\n SetButtonState();\n pDocSh->GetUndoManager()->Clear();\n\n FillCtrls(aCurrentRow);\n pDocSh->SetDocumentModified();\n pDocSh->PostPaintGridAll();\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_CloseHdl, PushButton*, EMPTYARG )\n{\n EndDialog( );\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_ScrollHdl, ScrollBar*, EMPTYARG )\n{\n long nOffset = aSlider.GetThumbPos();\n aCurrentRow = nStartRow + nOffset + 1;\n SetButtonState();\n FillCtrls(aCurrentRow);\n return 0;\n}\n\nvoid ScDataFormDlg::SetButtonState()\n{\n if ( aCurrentRow > nEndRow )\n {\n aBtnDelete.Enable( FALSE );\n aBtnLast.Enable( TRUE );\n aBtnNext.Enable( FALSE );\n }\n else\n {\n aBtnDelete.Enable( TRUE );\n aBtnNext.Enable( TRUE );\n }\n if ( 1 == aCurrentRow )\n aBtnLast.Enable( FALSE );\n\n aBtnRestore.Enable( FALSE );\n if ( pEdits )\n pEdits[0]->GrabFocus();\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Display correct record information in Data Form dialog. (fdo#32196)<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Initial Developer of the Original Code is\n * Novell Inc.\n * Portions created by the Initial Developer are Copyright (C) 2010 the\n * Initial Developer. All Rights Reserved.\n *\n * Contributor(s): Amelia Wang <amwang@novell.com>\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\/\/------------------------------------------------------------------\n\n#include \"datafdlg.hxx\"\n#include \"scresid.hxx\"\n#include \"datafdlg.hrc\"\n#include \"viewdata.hxx\"\n\/\/#include \"document.hxx\"\n#include \"docsh.hxx\"\n#include \"refundo.hxx\"\n#include \"undodat.hxx\"\n\n#include \"rtl\/ustrbuf.hxx\"\n\n#define HDL(hdl) LINK( this, ScDataFormDlg, hdl )\n\nusing ::rtl::OUStringBuffer;\n\n\/\/zhangyun\nScDataFormDlg::ScDataFormDlg( Window* pParent, ScTabViewShell* pTabViewShellOri) :\n ModalDialog ( pParent, ScResId( RID_SCDLG_DATAFORM ) ),\n \/\/\n aBtnNew ( this, ScResId( BTN_DATAFORM_NEW ) ),\n aBtnDelete ( this, ScResId( BTN_DATAFORM_DELETE ) ),\n aBtnRestore ( this, ScResId( BTN_DATAFORM_RESTORE ) ),\n aBtnLast ( this, ScResId( BTN_DATAFORM_LAST ) ),\n aBtnNext ( this, ScResId( BTN_DATAFORM_NEXT ) ),\n aBtnClose ( this, ScResId( BTN_DATAFORM_CLOSE ) ),\n aSlider ( this, ScResId( WND_DATAFORM_SCROLLBAR ) ),\n aFixedText ( this, ScResId( LAB_DATAFORM_RECORDNO ) )\n{\n pTabViewShell = pTabViewShellOri;\n FreeResource();\n \/\/read header form current document, and add new controls\n DBG_ASSERT( pTabViewShell, \"pTabViewShell is NULL! :-\/\" );\n ScViewData* pViewData = pTabViewShell->GetViewData();\n\n pDoc = pViewData->GetDocument();\n if (pDoc)\n {\n ScRange aRange;\n pViewData->GetSimpleArea( aRange );\n ScAddress aStart = aRange.aStart;\n ScAddress aEnd = aRange.aEnd;\n\n nStartCol = aStart.Col();\n nEndCol = aEnd.Col();\n nStartRow = aStart.Row();\n nEndRow = aEnd.Row();\n\n nTab = pViewData->GetTabNo();\n \/\/if there is no selection\n if ((nStartCol == nEndCol) && (nStartRow == nEndRow))\n bNoSelection = TRUE;\n\n if (bNoSelection)\n {\n \/\/find last not blank cell in row\n for (int i=1;i<=MAX_DATAFORM_COLS;i++)\n {\n String aColName;\n nEndCol++;\n pDoc->GetString( nEndCol, nStartRow, nTab, aColName );\n int nColWidth = pDoc->GetColWidth( nEndCol, nTab );\n if ( aColName.Len() == 0 && nColWidth)\n {\n nEndCol--;\n break;\n }\n }\n\n \/\/find first not blank cell in row\n for (int i=1;i<=MAX_DATAFORM_COLS;i++)\n {\n String aColName;\n if (nStartCol <= 0)\n break;\n nStartCol--;\n\n pDoc->GetString( nStartCol, nStartRow, nTab, aColName );\n int nColWidth = pDoc->GetColWidth( nEndCol, nTab );\n if ( aColName.Len() == 0 && nColWidth)\n {\n nStartCol++;\n break;\n }\n }\n\n \/\/skip leading hide column\n for (int i=1;i<=MAX_DATAFORM_COLS;i++)\n {\n String aColName;\n int nColWidth = pDoc->GetColWidth( nStartCol, nTab );\n if (nColWidth)\n break;\n nStartCol++;\n }\n\n if (nEndCol < nStartCol)\n nEndCol = nStartCol;\n\n \/\/find last not blank cell in row\n for (int i=1;i<=MAX_DATAFORM_ROWS;i++)\n {\n String aColName;\n nEndRow++;\n pDoc->GetString( nStartCol, nEndRow, nTab, aColName );\n if ( aColName.Len() == 0 )\n {\n nEndRow--;\n break;\n }\n }\n\n \/\/find first not blank cell in row\n for (int i=1;i<=MAX_DATAFORM_ROWS;i++)\n {\n String aColName;\n if (nStartRow <= 0)\n break;\n nStartRow--;\n\n pDoc->GetString( nStartCol, nStartRow, nTab, aColName );\n if ( aColName.Len() == 0 )\n {\n nStartRow++;\n break;\n }\n }\n\n if (nEndRow < nStartRow)\n nEndRow = nStartRow;\n }\n\n aCurrentRow = nStartRow + 1;\n\n String aFieldName;\n\n int nTop = 12;\n\n Size nFixedSize(FIXED_WIDTH, CTRL_HEIGHT );\n Size nEditSize(EDIT_WIDTH, CTRL_HEIGHT );\n\n \/\/pFtArray = new FixedText(this);\n aColLength = nEndCol - nStartCol + 1;\n\n \/\/new the controls\n pFixedTexts = new FixedText*[aColLength];\n pEdits = new Edit*[aColLength];\n\n for(sal_uInt16 nIndex = 0; nIndex < aColLength; nIndex++)\n {\n pDoc->GetString( nIndex + nStartCol, nStartRow, nTab, aFieldName );\n int nColWidth = pDoc->GetColWidth( nIndex + nStartCol, nTab );\n if (nColWidth)\n {\n pFixedTexts[nIndex] = new FixedText(this);\n pEdits[nIndex] = new Edit(this, WB_BORDER);\n\n pFixedTexts[nIndex]->SetSizePixel(nFixedSize);\n pEdits[nIndex]->SetSizePixel(nEditSize);\n pFixedTexts[nIndex]->SetPosPixel(Point(FIXED_LEFT, nTop));\n pEdits[nIndex]->SetPosPixel(Point(EDIT_LEFT, nTop));\n \/\/pFixedTexts[nIndex]->SetText(String::CreateFromAscii(\"W4W-Filter Nr. \"));\n pFixedTexts[nIndex]->SetText(aFieldName);\n pFixedTexts[nIndex]->Show();\n pEdits[nIndex]->Show();\n\n nTop += LINE_HEIGHT;\n }\n else\n {\n pFixedTexts[nIndex] = NULL;\n pEdits[nIndex] = NULL;\n }\n pEdits[nIndex]->SetModifyHdl( HDL(Impl_DataModifyHdl) );\n }\n\n Size nDialogSize = this->GetSizePixel();\n if (nTop > nDialogSize.Height())\n {\n nDialogSize.setHeight(nTop);\n this->SetSizePixel(nDialogSize);\n }\n Size nScrollSize = aSlider.GetSizePixel();\n nScrollSize.setHeight(nDialogSize.Height()-20);\n aSlider.SetSizePixel(nScrollSize);\n }\n\n FillCtrls(aCurrentRow);\n\n aSlider.SetPageSize( 10 );\n aSlider.SetVisibleSize( 1 );\n aSlider.SetLineSize( 1 );\n aSlider.SetRange( Range( 0, nEndRow - nStartRow + 1) );\n aSlider.Show();\n\n aBtnNew.SetClickHdl ( HDL(Impl_NewHdl) );\n aBtnLast.SetClickHdl ( HDL(Impl_LastHdl) );\n aBtnNext.SetClickHdl ( HDL(Impl_NextHdl) );\n\n aBtnRestore.SetClickHdl ( HDL(Impl_RestoreHdl) );\n aBtnDelete.SetClickHdl ( HDL(Impl_DeleteHdl) );\n aBtnClose.SetClickHdl ( HDL(Impl_CloseHdl) );\n\n aSlider.SetEndScrollHdl( HDL( Impl_ScrollHdl ) );\n\n SetButtonState();\n\n \/\/end\n \/\/FreeResource();\n}\n\nScDataFormDlg::~ScDataFormDlg()\n{\n for(sal_uInt16 i = 0; i < aColLength; i++)\n {\n if (pEdits[i])\n delete pEdits[i];\n if (pFixedTexts[i])\n delete pFixedTexts[i];\n }\n if (pEdits)\n delete pEdits;\n if (pFixedTexts)\n delete pFixedTexts;\n}\n\nvoid ScDataFormDlg::FillCtrls(SCROW \/*nCurrentRow*\/)\n{\n \/\/ScViewData* pViewData = pTabViewShell->GetViewData();\n\n String aFieldName;\n for (sal_uInt16 i = 0; i < aColLength; ++i)\n {\n if (pEdits[i])\n {\n if (aCurrentRow<=nEndRow)\n {\n pDoc->GetString( i + nStartCol, aCurrentRow, nTab, aFieldName );\n pEdits[i]->SetText(aFieldName);\n }\n else\n pEdits[i]->SetText(String());\n }\n }\n\n if (aCurrentRow <= nEndRow)\n {\n OUStringBuffer aBuf;\n aBuf.append(static_cast<sal_Int32>(aCurrentRow - nStartRow));\n aBuf.appendAscii(\" \/ \");\n aBuf.append(static_cast<sal_Int32>(nEndRow - nStartRow));\n aFixedText.SetText(aBuf.makeStringAndClear());\n }\n else\n aFixedText.SetText(String::CreateFromAscii(\"New Record\"));\n\n aSlider.SetThumbPos(aCurrentRow-nStartRow-1);\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_DataModifyHdl, Edit*, pEdit)\n{\n if ( pEdit->IsModified() )\n aBtnRestore.Enable( TRUE );\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_NewHdl, PushButton*, EMPTYARG )\n{\n ScViewData* pViewData = pTabViewShell->GetViewData();\n ScDocShell* pDocSh = pViewData->GetDocShell();\n if ( pDoc )\n {\n sal_Bool bHasData = sal_False;\n for(sal_uInt16 i = 0; i < aColLength; i++)\n if (pEdits[i])\n if ( pEdits[i]->GetText().Len() != 0 )\n {\n bHasData = sal_True;\n break;\n }\n\n if ( bHasData )\n {\n pTabViewShell->DataFormPutData( aCurrentRow , nStartRow , nStartCol , nEndRow , nEndCol , pEdits , aColLength );\n aCurrentRow++;\n if (aCurrentRow >= nEndRow + 2)\n {\n nEndRow ++ ;\n aSlider.SetRange( Range( 0, nEndRow - nStartRow + 1) );\n }\n SetButtonState();\n FillCtrls(aCurrentRow);\n pDocSh->SetDocumentModified();\n pDocSh->PostPaintGridAll();\n }\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_LastHdl, PushButton*, EMPTYARG )\n{\n if (pDoc)\n {\n if ( aCurrentRow > nStartRow +1 )\n aCurrentRow--;\n\n SetButtonState();\n FillCtrls(aCurrentRow);\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_NextHdl, PushButton*, EMPTYARG )\n{\n if (pDoc)\n {\n if ( aCurrentRow <= nEndRow)\n aCurrentRow++;\n\n SetButtonState();\n FillCtrls(aCurrentRow);\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_RestoreHdl, PushButton*, EMPTYARG )\n{\n if (pDoc)\n {\n FillCtrls(aCurrentRow);\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_DeleteHdl, PushButton*, EMPTYARG )\n{\n ScViewData* pViewData = pTabViewShell->GetViewData();\n ScDocShell* pDocSh = pViewData->GetDocShell();\n if (pDoc)\n {\n ScRange aRange(nStartCol, aCurrentRow, nTab, nEndCol, aCurrentRow, nTab);\n pDoc->DeleteRow(aRange);\n nEndRow--;\n\n SetButtonState();\n pDocSh->GetUndoManager()->Clear();\n\n FillCtrls(aCurrentRow);\n pDocSh->SetDocumentModified();\n pDocSh->PostPaintGridAll();\n }\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_CloseHdl, PushButton*, EMPTYARG )\n{\n EndDialog( );\n return 0;\n}\n\nIMPL_LINK( ScDataFormDlg, Impl_ScrollHdl, ScrollBar*, EMPTYARG )\n{\n long nOffset = aSlider.GetThumbPos();\n aCurrentRow = nStartRow + nOffset + 1;\n SetButtonState();\n FillCtrls(aCurrentRow);\n return 0;\n}\n\nvoid ScDataFormDlg::SetButtonState()\n{\n if ( aCurrentRow > nEndRow )\n {\n aBtnDelete.Enable( FALSE );\n aBtnLast.Enable( TRUE );\n aBtnNext.Enable( FALSE );\n }\n else\n {\n aBtnDelete.Enable( TRUE );\n aBtnNext.Enable( TRUE );\n }\n if ( 1 == aCurrentRow )\n aBtnLast.Enable( FALSE );\n\n aBtnRestore.Enable( FALSE );\n if ( pEdits )\n pEdits[0]->GrabFocus();\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inscodlg.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 14:06:33 $\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_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n\/\/------------------------------------------------------------------\n\n#include \"inscodlg.hxx\"\n#include \"scresid.hxx\"\n#include \"miscdlgs.hrc\"\n\n\n\/\/==================================================================\n\nBOOL ScInsertContentsDlg::bPreviousAllCheck = TRUE;\nUSHORT ScInsertContentsDlg::nPreviousChecks = (IDF_DATETIME | IDF_STRING |\n IDF_NOTE | IDF_FORMULA |\n IDF_ATTRIB | IDF_OBJECTS);\nUSHORT ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_NOFUNC;\nUSHORT ScInsertContentsDlg::nPreviousChecks2 = 0;\nUSHORT ScInsertContentsDlg::nPreviousMoveMode = INS_NONE; \/\/ enum InsCellCmd\n\n\/\/-----------------------------------------------------------------------\n\nScInsertContentsDlg::ScInsertContentsDlg( Window* pParent,\n USHORT nCheckDefaults,\n const String* pStrTitle )\n\n : ModalDialog ( pParent, ScResId( RID_SCDLG_INSCONT ) ),\n \/\/\n aBtnOk ( this, ScResId( BTN_OK ) ),\n aBtnCancel ( this, ScResId( BTN_CANCEL ) ),\n aBtnHelp ( this, ScResId( BTN_HELP ) ),\n aBtnInsAll ( this, ScResId( BTN_INSALL ) ),\n aBtnInsStrings ( this, ScResId( BTN_INSSTRINGS ) ),\n aBtnInsNumbers ( this, ScResId( BTN_INSNUMBERS ) ),\n aBtnInsDateTime ( this, ScResId( BTN_INSDATETIME ) ),\n aBtnInsFormulas ( this, ScResId( BTN_INSFORMULAS ) ),\n aBtnInsNotes ( this, ScResId( BTN_INSNOTES ) ),\n aBtnInsAttrs ( this, ScResId( BTN_INSATTRS ) ),\n aBtnInsObjects ( this, ScResId( BTN_INSOBJECTS ) ),\n aFlFrame ( this, ScResId( FL_FRAME ) ),\n aBtnSkipEmptyCells( this, ScResId(BTN_SKIP_EMPTY ) ),\n aBtnTranspose ( this, ScResId( BTN_TRANSPOSE ) ),\n aBtnLink ( this, ScResId( BTN_LINK ) ),\n aFlOptions ( this, ScResId( FL_OPTIONS ) ),\n aRbNoOp ( this, ScResId( BTN_OP_NOOP ) ),\n aRbAdd ( this, ScResId( BTN_OP_ADD ) ),\n aRbSub ( this, ScResId( BTN_OP_SUB ) ),\n aRbMul ( this, ScResId( BTN_OP_MUL ) ),\n aRbDiv ( this, ScResId( BTN_OP_DIV ) ),\n aFlOperation ( this, ScResId( FL_OPERATION ) ),\n aRbMoveNone ( this, ScResId( BTN_MV_NONE ) ),\n aRbMoveDown ( this, ScResId( BTN_MV_DOWN ) ),\n aRbMoveRight ( this, ScResId( BTN_MV_RIGHT ) ),\n aFlMove ( this, ScResId( FL_MOVE ) ),\n aFlSep1 ( this, ScResId( FL_SEP1 ) ),\n aFlSep2 ( this, ScResId( FL_SEP2 ) ),\n bOtherDoc ( FALSE ),\n bFillMode ( FALSE ),\n bChangeTrack ( FALSE ),\n bMoveDownDisabled( FALSE ),\n bMoveRightDisabled( FALSE )\n{\n if ( pStrTitle )\n SetText( *pStrTitle );\n\n if ( nCheckDefaults != 0 )\n {\n ScInsertContentsDlg::nPreviousChecks = nCheckDefaults;\n ScInsertContentsDlg::bPreviousAllCheck = FALSE;\n ScInsertContentsDlg::nPreviousChecks2 = 0;\n }\n\n aBtnInsAll.Check ( ScInsertContentsDlg::bPreviousAllCheck );\n aBtnInsStrings.Check ( IS_SET( IDF_STRING,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsNumbers.Check ( IS_SET( IDF_VALUE,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsDateTime.Check( IS_SET( IDF_DATETIME,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsFormulas.Check( IS_SET( IDF_FORMULA,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsNotes.Check ( IS_SET( IDF_NOTE,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsAttrs.Check ( IS_SET( IDF_ATTRIB,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsObjects.Check ( IS_SET( IDF_OBJECTS,\n ScInsertContentsDlg::nPreviousChecks ) );\n\n switch( ScInsertContentsDlg::nPreviousFormulaChecks )\n {\n case PASTE_NOFUNC: aRbNoOp.Check(TRUE); break;\n case PASTE_ADD: aRbAdd.Check(TRUE); break;\n case PASTE_SUB: aRbSub.Check(TRUE); break;\n case PASTE_MUL: aRbMul.Check(TRUE); break;\n case PASTE_DIV: aRbDiv.Check(TRUE); break;\n }\n\n switch( ScInsertContentsDlg::nPreviousMoveMode )\n {\n case INS_NONE: aRbMoveNone.Check(TRUE); break;\n case INS_CELLSDOWN: aRbMoveDown.Check(TRUE); break;\n case INS_CELLSRIGHT: aRbMoveRight.Check(TRUE); break;\n }\n\n aBtnSkipEmptyCells.Check( ( ScInsertContentsDlg::nPreviousChecks2 & INS_CONT_NOEMPTY ) != 0);\n aBtnTranspose.Check( ( ScInsertContentsDlg::nPreviousChecks2 & INS_CONT_TRANS ) != 0);\n aBtnLink.Check( ( ScInsertContentsDlg::nPreviousChecks2 & INS_CONT_LINK ) != 0);\n\n DisableChecks( aBtnInsAll.IsChecked() );\n\n aFlSep1.SetStyle( aFlSep1.GetStyle() | WB_VERT );\n aFlSep2.SetStyle( aFlSep2.GetStyle() | WB_VERT );\n\n aBtnInsAll.SetClickHdl( LINK( this, ScInsertContentsDlg, InsAllHdl ) );\n aBtnLink.SetClickHdl( LINK( this, ScInsertContentsDlg, LinkBtnHdl ) );\n\n \/\/-------------\n FreeResource();\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT ScInsertContentsDlg::GetInsContentsCmdBits() const\n{\n ScInsertContentsDlg::nPreviousChecks = 0;\n\n if ( aBtnInsStrings.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks = IDF_STRING;\n if ( aBtnInsNumbers.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks |= IDF_VALUE;\n if ( aBtnInsDateTime.IsChecked())\n ScInsertContentsDlg::nPreviousChecks |= IDF_DATETIME;\n if ( aBtnInsFormulas.IsChecked())\n ScInsertContentsDlg::nPreviousChecks |= IDF_FORMULA;\n if ( aBtnInsNotes.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks |= IDF_NOTE;\n if ( aBtnInsAttrs.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks |= IDF_ATTRIB;\n if ( aBtnInsObjects.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks |= IDF_OBJECTS;\n\n ScInsertContentsDlg::bPreviousAllCheck = aBtnInsAll.IsChecked();\n\n return ( (ScInsertContentsDlg::bPreviousAllCheck)\n ? IDF_ALL\n : ScInsertContentsDlg::nPreviousChecks );\n}\n\n\/\/------------------------------------------------------------------------\n\nInsCellCmd ScInsertContentsDlg::GetMoveMode()\n{\n if ( aRbMoveDown.IsChecked() )\n return INS_CELLSDOWN;\n if ( aRbMoveRight.IsChecked() )\n return INS_CELLSRIGHT;\n\n return INS_NONE;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertContentsDlg::DisableChecks( BOOL bInsAllChecked )\n{\n if ( bInsAllChecked )\n {\n aBtnInsStrings.Disable();\n aBtnInsNumbers.Disable();\n aBtnInsDateTime.Disable();\n aBtnInsFormulas.Disable();\n aBtnInsNotes.Disable();\n aBtnInsAttrs.Disable();\n aBtnInsObjects.Disable();\n }\n else\n {\n aBtnInsStrings.Enable();\n aBtnInsNumbers.Enable();\n aBtnInsDateTime.Enable();\n aBtnInsFormulas.Enable();\n aBtnInsNotes.Enable();\n aBtnInsAttrs.Enable();\n\n \/\/ \"Objects\" is disabled for \"Fill Tables\"\n if ( bFillMode )\n aBtnInsObjects.Disable();\n else\n aBtnInsObjects.Enable();\n }\n}\n\n\/\/ Link in anderes Dokument -> alles andere disabled\n\nvoid ScInsertContentsDlg::TestModes()\n{\n if ( bOtherDoc && aBtnLink.IsChecked() )\n {\n aBtnSkipEmptyCells.Disable();\n aBtnTranspose.Disable();\n aRbNoOp.Disable();\n aRbAdd.Disable();\n aRbSub.Disable();\n aRbMul.Disable();\n aRbDiv.Disable();\n aFlOperation.Disable();\n\n aRbMoveNone.Disable();\n aRbMoveDown.Disable();\n aRbMoveRight.Disable();\n aFlMove.Disable();\n\n aFlFrame.Disable();\n aBtnInsAll.Disable();\n DisableChecks(TRUE);\n }\n else\n {\n aBtnSkipEmptyCells.Enable();\n aBtnTranspose.Enable(!bFillMode);\n aRbNoOp.Enable();\n aRbAdd.Enable();\n aRbSub.Enable();\n aRbMul.Enable();\n aRbDiv.Enable();\n aFlOperation.Enable();\n\n aRbMoveNone.Enable(!bFillMode && !bChangeTrack && !(bMoveDownDisabled && bMoveRightDisabled));\n aRbMoveDown.Enable(!bFillMode && !bChangeTrack && !bMoveDownDisabled);\n aRbMoveRight.Enable(!bFillMode && !bChangeTrack && !bMoveRightDisabled);\n aFlMove.Enable(!bFillMode && !bChangeTrack && !(bMoveDownDisabled && bMoveRightDisabled));\n\n aFlFrame.Enable();\n aBtnInsAll.Enable();\n DisableChecks( aBtnInsAll.IsChecked() );\n }\n}\n\nvoid ScInsertContentsDlg::SetOtherDoc( BOOL bSet )\n{\n if ( bSet != bOtherDoc )\n {\n bOtherDoc = bSet;\n TestModes();\n if ( bSet )\n aRbMoveNone.Check(TRUE);\n }\n}\n\nvoid ScInsertContentsDlg::SetFillMode( BOOL bSet )\n{\n if ( bSet != bFillMode )\n {\n bFillMode = bSet;\n TestModes();\n if ( bSet )\n aRbMoveNone.Check(TRUE);\n }\n}\n\nvoid ScInsertContentsDlg::SetChangeTrack( BOOL bSet )\n{\n if ( bSet != bChangeTrack )\n {\n bChangeTrack = bSet;\n TestModes();\n if ( bSet )\n aRbMoveNone.Check(TRUE);\n }\n}\n\nvoid ScInsertContentsDlg::SetCellShiftDisabled( int nDisable )\n{\n BOOL bDown = ((nDisable & SC_CELL_SHIFT_DISABLE_DOWN) != 0);\n BOOL bRight = ((nDisable & SC_CELL_SHIFT_DISABLE_RIGHT) != 0);\n if ( bDown != bMoveDownDisabled || bRight != bMoveRightDisabled )\n {\n bMoveDownDisabled = bDown;\n bMoveRightDisabled = bRight;\n TestModes();\n if ( bMoveDownDisabled && aRbMoveDown.IsChecked() )\n aRbMoveNone.Check(TRUE);\n if ( bMoveRightDisabled && aRbMoveRight.IsChecked() )\n aRbMoveNone.Check(TRUE);\n }\n}\n\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScInsertContentsDlg, InsAllHdl, void*, EMPTY_ARG )\n{\n DisableChecks( aBtnInsAll.IsChecked() );\n\n return 0;\n}\n\nIMPL_LINK( ScInsertContentsDlg, LinkBtnHdl, void*, EMPTY_ARG )\n{\n TestModes();\n\n return 0;\n}\n\n__EXPORT ScInsertContentsDlg::~ScInsertContentsDlg()\n{\n ScInsertContentsDlg::nPreviousChecks2 = 0;\n if(aBtnSkipEmptyCells.IsChecked())\n ScInsertContentsDlg::nPreviousChecks2 |= INS_CONT_NOEMPTY;\n if( aBtnTranspose.IsChecked())\n ScInsertContentsDlg::nPreviousChecks2 |= INS_CONT_TRANS;\n if( aBtnLink.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks2 |= INS_CONT_LINK;\n\n if (!bFillMode) \/\/ im FillMode ist None gecheckt und alle 3 disabled\n {\n if ( aRbMoveNone.IsChecked() )\n ScInsertContentsDlg::nPreviousMoveMode = INS_NONE;\n else if ( aRbMoveDown.IsChecked() )\n ScInsertContentsDlg::nPreviousMoveMode = INS_CELLSDOWN;\n else if ( aRbMoveRight.IsChecked() )\n ScInsertContentsDlg::nPreviousMoveMode = INS_CELLSRIGHT;\n }\n}\n\nUSHORT ScInsertContentsDlg::GetFormulaCmdBits() const\n{\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_NOFUNC;\n if(aRbAdd.IsChecked())\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_ADD;\n else if(aRbSub.IsChecked())\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_SUB;\n else if(aRbMul.IsChecked())\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_MUL;\n else if(aRbDiv.IsChecked())\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_DIV;\n \/\/ Bits fuer Checkboxen ausblenden\n return ScInsertContentsDlg::nPreviousFormulaChecks;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS calcwarnings (1.6.110); FILE MERGED 2006\/12\/12 17:03:17 nn 1.6.110.2: #i69284# warning-free: ui, unxlngi6 2006\/12\/01 08:53:35 nn 1.6.110.1: #i69284# warning-free: ui, wntmsci10<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inscodlg.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2007-02-27 13:31: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_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n\/\/------------------------------------------------------------------\n\n#include \"inscodlg.hxx\"\n#include \"scresid.hxx\"\n#include \"miscdlgs.hrc\"\n\n\n\/\/==================================================================\n\nBOOL ScInsertContentsDlg::bPreviousAllCheck = TRUE;\nUSHORT ScInsertContentsDlg::nPreviousChecks = (IDF_DATETIME | IDF_STRING |\n IDF_NOTE | IDF_FORMULA |\n IDF_ATTRIB | IDF_OBJECTS);\nUSHORT ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_NOFUNC;\nUSHORT ScInsertContentsDlg::nPreviousChecks2 = 0;\nUSHORT ScInsertContentsDlg::nPreviousMoveMode = INS_NONE; \/\/ enum InsCellCmd\n\n\/\/-----------------------------------------------------------------------\n\nScInsertContentsDlg::ScInsertContentsDlg( Window* pParent,\n USHORT nCheckDefaults,\n const String* pStrTitle )\n\n : ModalDialog ( pParent, ScResId( RID_SCDLG_INSCONT ) ),\n \/\/\n aFlFrame ( this, ScResId( FL_FRAME ) ),\n aBtnInsAll ( this, ScResId( BTN_INSALL ) ),\n aBtnInsStrings ( this, ScResId( BTN_INSSTRINGS ) ),\n aBtnInsNumbers ( this, ScResId( BTN_INSNUMBERS ) ),\n aBtnInsDateTime ( this, ScResId( BTN_INSDATETIME ) ),\n aBtnInsFormulas ( this, ScResId( BTN_INSFORMULAS ) ),\n aBtnInsNotes ( this, ScResId( BTN_INSNOTES ) ),\n aBtnInsAttrs ( this, ScResId( BTN_INSATTRS ) ),\n aBtnInsObjects ( this, ScResId( BTN_INSOBJECTS ) ),\n aFlSep1 ( this, ScResId( FL_SEP1 ) ),\n aFlOptions ( this, ScResId( FL_OPTIONS ) ),\n aBtnSkipEmptyCells( this, ScResId(BTN_SKIP_EMPTY ) ),\n aBtnTranspose ( this, ScResId( BTN_TRANSPOSE ) ),\n aBtnLink ( this, ScResId( BTN_LINK ) ),\n aFlOperation ( this, ScResId( FL_OPERATION ) ),\n aRbNoOp ( this, ScResId( BTN_OP_NOOP ) ),\n aRbAdd ( this, ScResId( BTN_OP_ADD ) ),\n aRbSub ( this, ScResId( BTN_OP_SUB ) ),\n aRbMul ( this, ScResId( BTN_OP_MUL ) ),\n aRbDiv ( this, ScResId( BTN_OP_DIV ) ),\n aFlSep2 ( this, ScResId( FL_SEP2 ) ),\n aFlMove ( this, ScResId( FL_MOVE ) ),\n aRbMoveNone ( this, ScResId( BTN_MV_NONE ) ),\n aRbMoveDown ( this, ScResId( BTN_MV_DOWN ) ),\n aRbMoveRight ( this, ScResId( BTN_MV_RIGHT ) ),\n aBtnOk ( this, ScResId( BTN_OK ) ),\n aBtnCancel ( this, ScResId( BTN_CANCEL ) ),\n aBtnHelp ( this, ScResId( BTN_HELP ) ),\n bOtherDoc ( FALSE ),\n bFillMode ( FALSE ),\n bChangeTrack ( FALSE ),\n bMoveDownDisabled( FALSE ),\n bMoveRightDisabled( FALSE )\n{\n if ( pStrTitle )\n SetText( *pStrTitle );\n\n if ( nCheckDefaults != 0 )\n {\n ScInsertContentsDlg::nPreviousChecks = nCheckDefaults;\n ScInsertContentsDlg::bPreviousAllCheck = FALSE;\n ScInsertContentsDlg::nPreviousChecks2 = 0;\n }\n\n aBtnInsAll.Check ( ScInsertContentsDlg::bPreviousAllCheck );\n aBtnInsStrings.Check ( IS_SET( IDF_STRING,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsNumbers.Check ( IS_SET( IDF_VALUE,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsDateTime.Check( IS_SET( IDF_DATETIME,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsFormulas.Check( IS_SET( IDF_FORMULA,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsNotes.Check ( IS_SET( IDF_NOTE,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsAttrs.Check ( IS_SET( IDF_ATTRIB,\n ScInsertContentsDlg::nPreviousChecks ) );\n aBtnInsObjects.Check ( IS_SET( IDF_OBJECTS,\n ScInsertContentsDlg::nPreviousChecks ) );\n\n switch( ScInsertContentsDlg::nPreviousFormulaChecks )\n {\n case PASTE_NOFUNC: aRbNoOp.Check(TRUE); break;\n case PASTE_ADD: aRbAdd.Check(TRUE); break;\n case PASTE_SUB: aRbSub.Check(TRUE); break;\n case PASTE_MUL: aRbMul.Check(TRUE); break;\n case PASTE_DIV: aRbDiv.Check(TRUE); break;\n }\n\n switch( ScInsertContentsDlg::nPreviousMoveMode )\n {\n case INS_NONE: aRbMoveNone.Check(TRUE); break;\n case INS_CELLSDOWN: aRbMoveDown.Check(TRUE); break;\n case INS_CELLSRIGHT: aRbMoveRight.Check(TRUE); break;\n }\n\n aBtnSkipEmptyCells.Check( ( ScInsertContentsDlg::nPreviousChecks2 & INS_CONT_NOEMPTY ) != 0);\n aBtnTranspose.Check( ( ScInsertContentsDlg::nPreviousChecks2 & INS_CONT_TRANS ) != 0);\n aBtnLink.Check( ( ScInsertContentsDlg::nPreviousChecks2 & INS_CONT_LINK ) != 0);\n\n DisableChecks( aBtnInsAll.IsChecked() );\n\n aFlSep1.SetStyle( aFlSep1.GetStyle() | WB_VERT );\n aFlSep2.SetStyle( aFlSep2.GetStyle() | WB_VERT );\n\n aBtnInsAll.SetClickHdl( LINK( this, ScInsertContentsDlg, InsAllHdl ) );\n aBtnLink.SetClickHdl( LINK( this, ScInsertContentsDlg, LinkBtnHdl ) );\n\n \/\/-------------\n FreeResource();\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT ScInsertContentsDlg::GetInsContentsCmdBits() const\n{\n ScInsertContentsDlg::nPreviousChecks = 0;\n\n if ( aBtnInsStrings.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks = IDF_STRING;\n if ( aBtnInsNumbers.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks |= IDF_VALUE;\n if ( aBtnInsDateTime.IsChecked())\n ScInsertContentsDlg::nPreviousChecks |= IDF_DATETIME;\n if ( aBtnInsFormulas.IsChecked())\n ScInsertContentsDlg::nPreviousChecks |= IDF_FORMULA;\n if ( aBtnInsNotes.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks |= IDF_NOTE;\n if ( aBtnInsAttrs.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks |= IDF_ATTRIB;\n if ( aBtnInsObjects.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks |= IDF_OBJECTS;\n\n ScInsertContentsDlg::bPreviousAllCheck = aBtnInsAll.IsChecked();\n\n return ( (ScInsertContentsDlg::bPreviousAllCheck)\n ? IDF_ALL\n : ScInsertContentsDlg::nPreviousChecks );\n}\n\n\/\/------------------------------------------------------------------------\n\nInsCellCmd ScInsertContentsDlg::GetMoveMode()\n{\n if ( aRbMoveDown.IsChecked() )\n return INS_CELLSDOWN;\n if ( aRbMoveRight.IsChecked() )\n return INS_CELLSRIGHT;\n\n return INS_NONE;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertContentsDlg::DisableChecks( BOOL bInsAllChecked )\n{\n if ( bInsAllChecked )\n {\n aBtnInsStrings.Disable();\n aBtnInsNumbers.Disable();\n aBtnInsDateTime.Disable();\n aBtnInsFormulas.Disable();\n aBtnInsNotes.Disable();\n aBtnInsAttrs.Disable();\n aBtnInsObjects.Disable();\n }\n else\n {\n aBtnInsStrings.Enable();\n aBtnInsNumbers.Enable();\n aBtnInsDateTime.Enable();\n aBtnInsFormulas.Enable();\n aBtnInsNotes.Enable();\n aBtnInsAttrs.Enable();\n\n \/\/ \"Objects\" is disabled for \"Fill Tables\"\n if ( bFillMode )\n aBtnInsObjects.Disable();\n else\n aBtnInsObjects.Enable();\n }\n}\n\n\/\/ Link in anderes Dokument -> alles andere disabled\n\nvoid ScInsertContentsDlg::TestModes()\n{\n if ( bOtherDoc && aBtnLink.IsChecked() )\n {\n aBtnSkipEmptyCells.Disable();\n aBtnTranspose.Disable();\n aRbNoOp.Disable();\n aRbAdd.Disable();\n aRbSub.Disable();\n aRbMul.Disable();\n aRbDiv.Disable();\n aFlOperation.Disable();\n\n aRbMoveNone.Disable();\n aRbMoveDown.Disable();\n aRbMoveRight.Disable();\n aFlMove.Disable();\n\n aFlFrame.Disable();\n aBtnInsAll.Disable();\n DisableChecks(TRUE);\n }\n else\n {\n aBtnSkipEmptyCells.Enable();\n aBtnTranspose.Enable(!bFillMode);\n aRbNoOp.Enable();\n aRbAdd.Enable();\n aRbSub.Enable();\n aRbMul.Enable();\n aRbDiv.Enable();\n aFlOperation.Enable();\n\n aRbMoveNone.Enable(!bFillMode && !bChangeTrack && !(bMoveDownDisabled && bMoveRightDisabled));\n aRbMoveDown.Enable(!bFillMode && !bChangeTrack && !bMoveDownDisabled);\n aRbMoveRight.Enable(!bFillMode && !bChangeTrack && !bMoveRightDisabled);\n aFlMove.Enable(!bFillMode && !bChangeTrack && !(bMoveDownDisabled && bMoveRightDisabled));\n\n aFlFrame.Enable();\n aBtnInsAll.Enable();\n DisableChecks( aBtnInsAll.IsChecked() );\n }\n}\n\nvoid ScInsertContentsDlg::SetOtherDoc( BOOL bSet )\n{\n if ( bSet != bOtherDoc )\n {\n bOtherDoc = bSet;\n TestModes();\n if ( bSet )\n aRbMoveNone.Check(TRUE);\n }\n}\n\nvoid ScInsertContentsDlg::SetFillMode( BOOL bSet )\n{\n if ( bSet != bFillMode )\n {\n bFillMode = bSet;\n TestModes();\n if ( bSet )\n aRbMoveNone.Check(TRUE);\n }\n}\n\nvoid ScInsertContentsDlg::SetChangeTrack( BOOL bSet )\n{\n if ( bSet != bChangeTrack )\n {\n bChangeTrack = bSet;\n TestModes();\n if ( bSet )\n aRbMoveNone.Check(TRUE);\n }\n}\n\nvoid ScInsertContentsDlg::SetCellShiftDisabled( int nDisable )\n{\n BOOL bDown = ((nDisable & SC_CELL_SHIFT_DISABLE_DOWN) != 0);\n BOOL bRight = ((nDisable & SC_CELL_SHIFT_DISABLE_RIGHT) != 0);\n if ( bDown != bMoveDownDisabled || bRight != bMoveRightDisabled )\n {\n bMoveDownDisabled = bDown;\n bMoveRightDisabled = bRight;\n TestModes();\n if ( bMoveDownDisabled && aRbMoveDown.IsChecked() )\n aRbMoveNone.Check(TRUE);\n if ( bMoveRightDisabled && aRbMoveRight.IsChecked() )\n aRbMoveNone.Check(TRUE);\n }\n}\n\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScInsertContentsDlg, InsAllHdl, void*, EMPTYARG )\n{\n DisableChecks( aBtnInsAll.IsChecked() );\n\n return 0;\n}\n\nIMPL_LINK( ScInsertContentsDlg, LinkBtnHdl, void*, EMPTYARG )\n{\n TestModes();\n\n return 0;\n}\n\n__EXPORT ScInsertContentsDlg::~ScInsertContentsDlg()\n{\n ScInsertContentsDlg::nPreviousChecks2 = 0;\n if(aBtnSkipEmptyCells.IsChecked())\n ScInsertContentsDlg::nPreviousChecks2 |= INS_CONT_NOEMPTY;\n if( aBtnTranspose.IsChecked())\n ScInsertContentsDlg::nPreviousChecks2 |= INS_CONT_TRANS;\n if( aBtnLink.IsChecked() )\n ScInsertContentsDlg::nPreviousChecks2 |= INS_CONT_LINK;\n\n if (!bFillMode) \/\/ im FillMode ist None gecheckt und alle 3 disabled\n {\n if ( aRbMoveNone.IsChecked() )\n ScInsertContentsDlg::nPreviousMoveMode = INS_NONE;\n else if ( aRbMoveDown.IsChecked() )\n ScInsertContentsDlg::nPreviousMoveMode = INS_CELLSDOWN;\n else if ( aRbMoveRight.IsChecked() )\n ScInsertContentsDlg::nPreviousMoveMode = INS_CELLSRIGHT;\n }\n}\n\nUSHORT ScInsertContentsDlg::GetFormulaCmdBits() const\n{\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_NOFUNC;\n if(aRbAdd.IsChecked())\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_ADD;\n else if(aRbSub.IsChecked())\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_SUB;\n else if(aRbMul.IsChecked())\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_MUL;\n else if(aRbDiv.IsChecked())\n ScInsertContentsDlg::nPreviousFormulaChecks = PASTE_DIV;\n \/\/ Bits fuer Checkboxen ausblenden\n return ScInsertContentsDlg::nPreviousFormulaChecks;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: instbdlg.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2004-08-23 09:37:09 $\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#undef SC_DLLIMPLEMENTATION\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------\n\n#include <sfx2\/app.hxx>\n#include <sfx2\/docfile.hxx>\n#include <svtools\/ehdl.hxx>\n#include <svtools\/sfxecode.hxx>\n#include <vcl\/msgbox.hxx>\n\n#include \"global.hxx\"\n#include \"docsh.hxx\"\n#include \"viewdata.hxx\"\n#include \"scresid.hxx\"\n#include \"instbdlg.hrc\"\n#include \"globstr.hrc\"\n\n\n#define SC_INSTBDLG_CXX\n#include \"instbdlg.hxx\"\n\nconst long SC_DLG_BROWSE_OK = 0;\nconst long SC_DLG_BROWSE_CANCEL = 1;\n\n\/\/==================================================================\n\nScInsertTableDlg::ScInsertTableDlg( Window* pParent, ScViewData& rData, SCTAB nTabCount, bool bFromFile )\n\n : ModalDialog ( pParent, ScResId( RID_SCDLG_INSERT_TABLE ) ),\n \/\/\n aBtnBefore ( this, ScResId( RB_BEFORE ) ),\n aBtnBehind ( this, ScResId( RB_BEHIND ) ),\n aFlPos ( this, ScResId( FL_POSITION ) ),\n aFtCount ( this, ScResId( FT_COUNT ) ),\n aNfCount ( this, ScResId( NF_COUNT ) ),\n aFtName ( this, ScResId( FT_NAME ) ),\n aEdName ( this, ScResId( ED_TABNAME ) ),\n aLbTables ( this, ScResId( LB_TABLES ) ),\n aFtPath ( this, ScResId( FT_PATH ) ),\n aBtnBrowse ( this, ScResId( BTN_BROWSE ) ),\n aBtnLink ( this, ScResId( CB_LINK ) ),\n aFlTable ( this, ScResId( FL_TABLE ) ),\n aBtnNew ( this, ScResId( RB_NEW ) ),\n aBtnFromFile ( this, ScResId( RB_FROMFILE ) ),\n aBtnOk ( this, ScResId( BTN_OK ) ),\n aBtnCancel ( this, ScResId( BTN_CANCEL ) ),\n aBtnHelp ( this, ScResId( BTN_HELP ) ),\n rViewData ( rData ),\n rDoc ( *rData.GetDocument() ),\n pDocShTables ( NULL ),\n nSelTabIndex ( 0 ),\n nTableCount (nTabCount)\n{\n Init_Impl( bFromFile );\n FreeResource();\n}\n\n\/\/------------------------------------------------------------------------\n\n__EXPORT ScInsertTableDlg::~ScInsertTableDlg()\n{\n if (pDocShTables)\n pDocShTables->DoClose();\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::Init_Impl( bool bFromFile )\n{\n aBtnBrowse .SetClickHdl( LINK( this, ScInsertTableDlg, BrowseHdl_Impl ) );\n aBtnNew .SetClickHdl( LINK( this, ScInsertTableDlg, ChoiceHdl_Impl ) );\n aBtnFromFile .SetClickHdl( LINK( this, ScInsertTableDlg, ChoiceHdl_Impl ) );\n aLbTables .SetSelectHdl( LINK( this, ScInsertTableDlg, SelectHdl_Impl ) );\n aNfCount .SetModifyHdl( LINK( this, ScInsertTableDlg, CountHdl_Impl));\n aBtnOk .SetClickHdl( LINK( this, ScInsertTableDlg, DoEnterHdl ));\n aBtnBefore.Check();\n\n ScMarkData& rMark = rViewData.GetMarkData();\n SCTAB nTabSelCount = rMark.GetSelectCount();\n\n aNfCount.SetText( String::CreateFromInt32(nTableCount) );\n aNfCount.SetMax( MAXTAB - rDoc.GetTableCount() + 1 );\n\n if(nTableCount==1)\n {\n String aName;\n rDoc.CreateValidTabName( aName );\n aEdName.SetText( aName );\n }\n else\n {\n String aName=aFlTable.GetText();\n aName.AppendAscii(RTL_CONSTASCII_STRINGPARAM(\"...\"));\n aEdName.SetText( aName );\n aFtName.Disable();\n aEdName.Disable();\n }\n\n if( bFromFile )\n {\n aBtnFromFile.Check();\n SetFromTo_Impl();\n }\n else\n {\n aBtnNew.Check();\n SetNewTable_Impl();\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nshort __EXPORT ScInsertTableDlg::Execute()\n{\n \/\/ Parent fuer InsertDocumentDialog und Doc-Manager setzen:\n\n Window* pOldDefParent = Application::GetDefDialogParent();\n Application::SetDefDialogParent( this );\n\n bool bExecute = true;\n if( aBtnFromFile.IsChecked() )\n bExecute = BrowseHdl_Impl( &aBtnBrowse ) == SC_DLG_BROWSE_OK;\n\n short nRet = bExecute ? ModalDialog::Execute() : RET_CANCEL;\n\n Application::SetDefDialogParent( pOldDefParent );\n\n return nRet;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::SetNewTable_Impl()\n{\n if (aBtnNew.IsChecked() )\n {\n aNfCount .Enable();\n aFtCount .Enable();\n aLbTables .Disable();\n aFtPath .Disable();\n aBtnBrowse .Disable();\n aBtnLink .Disable();\n\n if(nTableCount==1)\n {\n aEdName.Enable();\n aFtName.Enable();\n }\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::SetFromTo_Impl()\n{\n if (aBtnFromFile.IsChecked() )\n {\n aEdName .Disable();\n aFtName .Disable();\n aFtCount .Disable();\n aNfCount .Disable();\n aLbTables .Enable();\n aFtPath .Enable();\n aBtnBrowse .Enable();\n aBtnLink .Enable();\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::FillTables_Impl( ScDocument* pSrcDoc )\n{\n aLbTables.SetUpdateMode( FALSE );\n aLbTables.Clear();\n\n if ( pSrcDoc )\n {\n SCTAB nCount = pSrcDoc->GetTableCount();\n String aName;\n\n for ( SCTAB i=0; i<nCount; i++ )\n {\n pSrcDoc->GetName( i, aName );\n aLbTables.InsertEntry( aName );\n }\n }\n\n aLbTables.SetUpdateMode( TRUE );\n\n if(aLbTables.GetEntryCount()==1)\n aLbTables.SelectEntryPos(0);\n}\n\n\/\/------------------------------------------------------------------------\n\nconst String* ScInsertTableDlg::GetFirstTable( USHORT* pN )\n{\n const String* pStr = NULL;\n\n if ( aBtnNew.IsChecked() )\n {\n aStrCurSelTable = aEdName.GetText();\n pStr = &aStrCurSelTable;\n }\n else if ( nSelTabIndex < aLbTables.GetSelectEntryCount() )\n {\n aStrCurSelTable = aLbTables.GetSelectEntry( 0 );\n pStr = &aStrCurSelTable;\n if ( pN )\n *pN = aLbTables.GetSelectEntryPos( 0 );\n nSelTabIndex = 1;\n }\n\n return pStr;\n}\n\n\/\/------------------------------------------------------------------------\n\nconst String* ScInsertTableDlg::GetNextTable( USHORT* pN )\n{\n const String* pStr = NULL;\n\n if ( !aBtnNew.IsChecked() && nSelTabIndex < aLbTables.GetSelectEntryCount() )\n {\n aStrCurSelTable = aLbTables.GetSelectEntry( nSelTabIndex );\n pStr = &aStrCurSelTable;\n if ( pN )\n *pN = aLbTables.GetSelectEntryPos( nSelTabIndex );\n nSelTabIndex++;\n }\n\n return pStr;\n}\n\n\n\/\/------------------------------------------------------------------------\n\/\/ Handler:\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScInsertTableDlg, CountHdl_Impl, NumericField*, EMPTYARG )\n{\n nTableCount = static_cast<SCTAB>(aNfCount.GetValue());\n if ( nTableCount==1)\n {\n String aName;\n rDoc.CreateValidTabName( aName );\n aEdName.SetText( aName );\n aFtName.Enable();\n aEdName.Enable();\n }\n else\n {\n String aName=aFlTable.GetText();\n aName.AppendAscii(RTL_CONSTASCII_STRINGPARAM(\"...\"));\n aEdName.SetText( aName );\n aFtName.Disable();\n aEdName.Disable();\n }\n\n DoEnable_Impl();\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\nIMPL_LINK( ScInsertTableDlg, ChoiceHdl_Impl, RadioButton*, EMPTYARG )\n{\n if ( aBtnNew.IsChecked() )\n SetNewTable_Impl();\n else\n SetFromTo_Impl();\n\n DoEnable_Impl();\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScInsertTableDlg, BrowseHdl_Impl, PushButton*, EMPTYARG )\n{\n \/\/ Dialog-Parent ist schon in Execute gesetzt worden\n\n SfxApplication* pApp = SFX_APP();\n SfxMedium* pMed = pApp->InsertDocumentDialog( 0, String::CreateFromAscii( ScDocShell::Factory().GetShortName() ) );\n\n if ( pMed )\n {\n \/\/ ERRCTX_SFX_OPENDOC -> \"Fehler beim Laden des Dokumentes\"\n SfxErrorContext aEc( ERRCTX_SFX_OPENDOC, pMed->GetName() );\n\n if (pDocShTables)\n pDocShTables->DoClose(); \/\/ delete passiert beim Zuweisen auf die Ref\n\n pMed->UseInteractionHandler( TRUE ); \/\/ to enable the filter options dialog\n\n pDocShTables = new ScDocShell;\n aDocShTablesRef = pDocShTables;\n\n Pointer aOldPtr( GetPointer() );\n SetPointer( Pointer( POINTER_WAIT ) );\n pDocShTables->DoLoad( pMed );\n SetPointer( aOldPtr );\n\n ULONG nErr = pDocShTables->GetErrorCode();\n if (nErr)\n ErrorHandler::HandleError( nErr ); \/\/ auch Warnings\n\n if ( !pDocShTables->GetError() ) \/\/ nur Errors\n {\n FillTables_Impl( pDocShTables->GetDocument() );\n aFtPath.SetText( pDocShTables->GetTitle( SFX_TITLE_FULLNAME ) );\n }\n else\n {\n pDocShTables->DoClose();\n aDocShTablesRef.Clear();\n pDocShTables = NULL;\n\n FillTables_Impl( NULL );\n aFtPath.SetText( EMPTY_STRING );\n }\n }\n\n DoEnable_Impl();\n return pMed ? SC_DLG_BROWSE_OK : SC_DLG_BROWSE_CANCEL;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScInsertTableDlg, SelectHdl_Impl, MultiListBox*, EMPTYARG )\n{\n DoEnable_Impl();\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::DoEnable_Impl()\n{\n if ( aBtnNew.IsChecked() || ( pDocShTables && aLbTables.GetSelectEntryCount() ) )\n aBtnOk.Enable();\n else\n aBtnOk.Disable();\n}\n\nIMPL_LINK( ScInsertTableDlg, DoEnterHdl, PushButton*, EMPTYARG )\n{\n if(nTableCount > 1 || rDoc.ValidTabName(aEdName.GetText()))\n {\n EndDialog(RET_OK);\n }\n else\n {\n String aErrMsg ( ScGlobal::GetRscString( STR_INVALIDTABNAME ) );\n USHORT nRet = ErrorBox( this,WinBits( WB_OK | WB_DEF_OK ),aErrMsg).Execute();\n }\n return 0;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.9.346); FILE MERGED 2005\/09\/05 15:06:32 rt 1.9.346.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: instbdlg.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:10:05 $\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#undef SC_DLLIMPLEMENTATION\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------\n\n#include <sfx2\/app.hxx>\n#include <sfx2\/docfile.hxx>\n#include <svtools\/ehdl.hxx>\n#include <svtools\/sfxecode.hxx>\n#include <vcl\/msgbox.hxx>\n\n#include \"global.hxx\"\n#include \"docsh.hxx\"\n#include \"viewdata.hxx\"\n#include \"scresid.hxx\"\n#include \"instbdlg.hrc\"\n#include \"globstr.hrc\"\n\n\n#define SC_INSTBDLG_CXX\n#include \"instbdlg.hxx\"\n\nconst long SC_DLG_BROWSE_OK = 0;\nconst long SC_DLG_BROWSE_CANCEL = 1;\n\n\/\/==================================================================\n\nScInsertTableDlg::ScInsertTableDlg( Window* pParent, ScViewData& rData, SCTAB nTabCount, bool bFromFile )\n\n : ModalDialog ( pParent, ScResId( RID_SCDLG_INSERT_TABLE ) ),\n \/\/\n aBtnBefore ( this, ScResId( RB_BEFORE ) ),\n aBtnBehind ( this, ScResId( RB_BEHIND ) ),\n aFlPos ( this, ScResId( FL_POSITION ) ),\n aFtCount ( this, ScResId( FT_COUNT ) ),\n aNfCount ( this, ScResId( NF_COUNT ) ),\n aFtName ( this, ScResId( FT_NAME ) ),\n aEdName ( this, ScResId( ED_TABNAME ) ),\n aLbTables ( this, ScResId( LB_TABLES ) ),\n aFtPath ( this, ScResId( FT_PATH ) ),\n aBtnBrowse ( this, ScResId( BTN_BROWSE ) ),\n aBtnLink ( this, ScResId( CB_LINK ) ),\n aFlTable ( this, ScResId( FL_TABLE ) ),\n aBtnNew ( this, ScResId( RB_NEW ) ),\n aBtnFromFile ( this, ScResId( RB_FROMFILE ) ),\n aBtnOk ( this, ScResId( BTN_OK ) ),\n aBtnCancel ( this, ScResId( BTN_CANCEL ) ),\n aBtnHelp ( this, ScResId( BTN_HELP ) ),\n rViewData ( rData ),\n rDoc ( *rData.GetDocument() ),\n pDocShTables ( NULL ),\n nSelTabIndex ( 0 ),\n nTableCount (nTabCount)\n{\n Init_Impl( bFromFile );\n FreeResource();\n}\n\n\/\/------------------------------------------------------------------------\n\n__EXPORT ScInsertTableDlg::~ScInsertTableDlg()\n{\n if (pDocShTables)\n pDocShTables->DoClose();\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::Init_Impl( bool bFromFile )\n{\n aBtnBrowse .SetClickHdl( LINK( this, ScInsertTableDlg, BrowseHdl_Impl ) );\n aBtnNew .SetClickHdl( LINK( this, ScInsertTableDlg, ChoiceHdl_Impl ) );\n aBtnFromFile .SetClickHdl( LINK( this, ScInsertTableDlg, ChoiceHdl_Impl ) );\n aLbTables .SetSelectHdl( LINK( this, ScInsertTableDlg, SelectHdl_Impl ) );\n aNfCount .SetModifyHdl( LINK( this, ScInsertTableDlg, CountHdl_Impl));\n aBtnOk .SetClickHdl( LINK( this, ScInsertTableDlg, DoEnterHdl ));\n aBtnBefore.Check();\n\n ScMarkData& rMark = rViewData.GetMarkData();\n SCTAB nTabSelCount = rMark.GetSelectCount();\n\n aNfCount.SetText( String::CreateFromInt32(nTableCount) );\n aNfCount.SetMax( MAXTAB - rDoc.GetTableCount() + 1 );\n\n if(nTableCount==1)\n {\n String aName;\n rDoc.CreateValidTabName( aName );\n aEdName.SetText( aName );\n }\n else\n {\n String aName=aFlTable.GetText();\n aName.AppendAscii(RTL_CONSTASCII_STRINGPARAM(\"...\"));\n aEdName.SetText( aName );\n aFtName.Disable();\n aEdName.Disable();\n }\n\n if( bFromFile )\n {\n aBtnFromFile.Check();\n SetFromTo_Impl();\n }\n else\n {\n aBtnNew.Check();\n SetNewTable_Impl();\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nshort __EXPORT ScInsertTableDlg::Execute()\n{\n \/\/ Parent fuer InsertDocumentDialog und Doc-Manager setzen:\n\n Window* pOldDefParent = Application::GetDefDialogParent();\n Application::SetDefDialogParent( this );\n\n bool bExecute = true;\n if( aBtnFromFile.IsChecked() )\n bExecute = BrowseHdl_Impl( &aBtnBrowse ) == SC_DLG_BROWSE_OK;\n\n short nRet = bExecute ? ModalDialog::Execute() : RET_CANCEL;\n\n Application::SetDefDialogParent( pOldDefParent );\n\n return nRet;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::SetNewTable_Impl()\n{\n if (aBtnNew.IsChecked() )\n {\n aNfCount .Enable();\n aFtCount .Enable();\n aLbTables .Disable();\n aFtPath .Disable();\n aBtnBrowse .Disable();\n aBtnLink .Disable();\n\n if(nTableCount==1)\n {\n aEdName.Enable();\n aFtName.Enable();\n }\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::SetFromTo_Impl()\n{\n if (aBtnFromFile.IsChecked() )\n {\n aEdName .Disable();\n aFtName .Disable();\n aFtCount .Disable();\n aNfCount .Disable();\n aLbTables .Enable();\n aFtPath .Enable();\n aBtnBrowse .Enable();\n aBtnLink .Enable();\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::FillTables_Impl( ScDocument* pSrcDoc )\n{\n aLbTables.SetUpdateMode( FALSE );\n aLbTables.Clear();\n\n if ( pSrcDoc )\n {\n SCTAB nCount = pSrcDoc->GetTableCount();\n String aName;\n\n for ( SCTAB i=0; i<nCount; i++ )\n {\n pSrcDoc->GetName( i, aName );\n aLbTables.InsertEntry( aName );\n }\n }\n\n aLbTables.SetUpdateMode( TRUE );\n\n if(aLbTables.GetEntryCount()==1)\n aLbTables.SelectEntryPos(0);\n}\n\n\/\/------------------------------------------------------------------------\n\nconst String* ScInsertTableDlg::GetFirstTable( USHORT* pN )\n{\n const String* pStr = NULL;\n\n if ( aBtnNew.IsChecked() )\n {\n aStrCurSelTable = aEdName.GetText();\n pStr = &aStrCurSelTable;\n }\n else if ( nSelTabIndex < aLbTables.GetSelectEntryCount() )\n {\n aStrCurSelTable = aLbTables.GetSelectEntry( 0 );\n pStr = &aStrCurSelTable;\n if ( pN )\n *pN = aLbTables.GetSelectEntryPos( 0 );\n nSelTabIndex = 1;\n }\n\n return pStr;\n}\n\n\/\/------------------------------------------------------------------------\n\nconst String* ScInsertTableDlg::GetNextTable( USHORT* pN )\n{\n const String* pStr = NULL;\n\n if ( !aBtnNew.IsChecked() && nSelTabIndex < aLbTables.GetSelectEntryCount() )\n {\n aStrCurSelTable = aLbTables.GetSelectEntry( nSelTabIndex );\n pStr = &aStrCurSelTable;\n if ( pN )\n *pN = aLbTables.GetSelectEntryPos( nSelTabIndex );\n nSelTabIndex++;\n }\n\n return pStr;\n}\n\n\n\/\/------------------------------------------------------------------------\n\/\/ Handler:\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScInsertTableDlg, CountHdl_Impl, NumericField*, EMPTYARG )\n{\n nTableCount = static_cast<SCTAB>(aNfCount.GetValue());\n if ( nTableCount==1)\n {\n String aName;\n rDoc.CreateValidTabName( aName );\n aEdName.SetText( aName );\n aFtName.Enable();\n aEdName.Enable();\n }\n else\n {\n String aName=aFlTable.GetText();\n aName.AppendAscii(RTL_CONSTASCII_STRINGPARAM(\"...\"));\n aEdName.SetText( aName );\n aFtName.Disable();\n aEdName.Disable();\n }\n\n DoEnable_Impl();\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\nIMPL_LINK( ScInsertTableDlg, ChoiceHdl_Impl, RadioButton*, EMPTYARG )\n{\n if ( aBtnNew.IsChecked() )\n SetNewTable_Impl();\n else\n SetFromTo_Impl();\n\n DoEnable_Impl();\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScInsertTableDlg, BrowseHdl_Impl, PushButton*, EMPTYARG )\n{\n \/\/ Dialog-Parent ist schon in Execute gesetzt worden\n\n SfxApplication* pApp = SFX_APP();\n SfxMedium* pMed = pApp->InsertDocumentDialog( 0, String::CreateFromAscii( ScDocShell::Factory().GetShortName() ) );\n\n if ( pMed )\n {\n \/\/ ERRCTX_SFX_OPENDOC -> \"Fehler beim Laden des Dokumentes\"\n SfxErrorContext aEc( ERRCTX_SFX_OPENDOC, pMed->GetName() );\n\n if (pDocShTables)\n pDocShTables->DoClose(); \/\/ delete passiert beim Zuweisen auf die Ref\n\n pMed->UseInteractionHandler( TRUE ); \/\/ to enable the filter options dialog\n\n pDocShTables = new ScDocShell;\n aDocShTablesRef = pDocShTables;\n\n Pointer aOldPtr( GetPointer() );\n SetPointer( Pointer( POINTER_WAIT ) );\n pDocShTables->DoLoad( pMed );\n SetPointer( aOldPtr );\n\n ULONG nErr = pDocShTables->GetErrorCode();\n if (nErr)\n ErrorHandler::HandleError( nErr ); \/\/ auch Warnings\n\n if ( !pDocShTables->GetError() ) \/\/ nur Errors\n {\n FillTables_Impl( pDocShTables->GetDocument() );\n aFtPath.SetText( pDocShTables->GetTitle( SFX_TITLE_FULLNAME ) );\n }\n else\n {\n pDocShTables->DoClose();\n aDocShTablesRef.Clear();\n pDocShTables = NULL;\n\n FillTables_Impl( NULL );\n aFtPath.SetText( EMPTY_STRING );\n }\n }\n\n DoEnable_Impl();\n return pMed ? SC_DLG_BROWSE_OK : SC_DLG_BROWSE_CANCEL;\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK( ScInsertTableDlg, SelectHdl_Impl, MultiListBox*, EMPTYARG )\n{\n DoEnable_Impl();\n return 0;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScInsertTableDlg::DoEnable_Impl()\n{\n if ( aBtnNew.IsChecked() || ( pDocShTables && aLbTables.GetSelectEntryCount() ) )\n aBtnOk.Enable();\n else\n aBtnOk.Disable();\n}\n\nIMPL_LINK( ScInsertTableDlg, DoEnterHdl, PushButton*, EMPTYARG )\n{\n if(nTableCount > 1 || rDoc.ValidTabName(aEdName.GetText()))\n {\n EndDialog(RET_OK);\n }\n else\n {\n String aErrMsg ( ScGlobal::GetRscString( STR_INVALIDTABNAME ) );\n USHORT nRet = ErrorBox( this,WinBits( WB_OK | WB_DEF_OK ),aErrMsg).Execute();\n }\n return 0;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <curl\/curl.h>\n# include <iostream>\n#include <stdio.h>\n\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <url\/params.hpp>\n#include <yadisk\/client.hpp>\n#include <boost\/algorithm\/string\/join.hpp>\n\n#include <sstream>\nusing std::stringstream;\n\n#include \"callbacks.hpp\"\n#include \"quote.hpp\"\n\nnamespace yadisk\n{\n static const std::string api_url = \"https:\/\/cloud-api.yandex.net\/v1\/disk\/resources\";\n\n Client::Client(string token_) : token{token_} {}\n \n auto Client::upload(url::path to, fs::path from, bool overwrite, std::list<string> fields) -> json {\n \t CURL *curl;\n \t\n \tstruct stat file_info;\n \n \tFILE *fd;\n \turl::params_t url_params;\n\tstruct curl_slist *header_list = nullptr;\n\tstd::string auth_header;\n\t \n \tfs::path p(fs::current_path());\n\turl_params[\"path\"] = quote(to.string(), curl);\n\turl_params[\"overwrite\"] = overwrite;\n\turl_params[\"fields\"] = boost::algorithm::join(fields, \",\");\n\tstd::string url = api_url + \"\/upload?\" + url_params.string();\n\t \n\tstruct curl_slist *head_list = nullptr;\n \tauth_head = \"Authorization: OAuth \" + token;\n\thead_list = curl_slist_append(head_list, auth_head.c_str());\n \n \tfd = fopen(\"C:\\\\file.txt\", \"w\"); \/\/открытие файла для загрузки\n \tif(!fd)\n \treturn 1; \/\/не может продолжить \n \t\/\/ получаем размер файла\n \tif(fstat(fileno(fd), &file_info)!=0;\n \treturn 1; \/* can't continue *\/ \n \n \tcurl = curl_easy_init();\n\t\/\/ if(curl) {\n \t\/\/выбор места для загрузки\n \tcurl_easy_setopt(curl, CURLOPT_URL,url.c_str());\n \tcurl_easy_setopt(curl, CURLOPT_READDATA, &response); \n \tcurl_easy_setopt(curl, CURLOPT_READFUNCTION, write<stringstream>);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, head_list);\n \tauto res = curl_easy_perform(curl);\n \tcurl_easy_cleanup(curl);\n \tif (res != CURLE_OK) return json();\n\tauto ans = json::parse(res);\n\treturn ans;\n \t \/\/загрузка по URL\n \tcurl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);\n \tcurl_easy_setopt(curl, CURLOPT_PUT, 1L);\n \t\/\/чтения файла \n \tcurl_easy_setopt(curl, CURLOPT_READDATA, fd);\n \t\/\/устанавливаем размер файла для отправки\n \tcurl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,(curl_off_t)file_info.st_size);\n \t\/\/для облегчения трассировки \n \tcurl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n \tauto response_code = curl_easy_perform(curl);\n\tcurl_slist_free_all(head_list);\n\tcurl_easy_cleanup(curl);\n\tif (response_code != CURLE_OK) return json();\n\tauto answer = json::parse(response_code);\n\treturn answer;\n \treturn 0; \n}\n}\n<commit_msg>Update client.cpp<commit_after>\n auto Client::upload(url::path to, fs::path from, bool overwrite, std::list<string> fields) -> json {\n \t CURL *curl;\n \t\n \tstruct stat file_info;\n \n \tFILE *fd;\n \turl::params_t url_params;\n\tstruct curl_slist *header_list = nullptr;\n\tstd::string auth_header;\n\t \n \tfs::path p(fs::current_path());\n\turl_params[\"path\"] = quote(to.string(), curl);\n\turl_params[\"overwrite\"] = overwrite;\n\turl_params[\"fields\"] = boost::algorithm::join(fields, \",\");\n\tstd::string url = api_url + \"\/upload?\" + url_params.string();\n\t \n\tstruct curl_slist *head_list = nullptr;\n \tauth_head = \"Authorization: OAuth \" + token;\n\thead_list = curl_slist_append(head_list, auth_head.c_str());\n \n \tfd = fopen(\"C:\\\\file.txt\", \"w\"); \/\/открытие файла для загрузки\n \tif(!fd)\n \treturn 1; \/\/не может продолжить \n \t\/\/ получаем размер файла\n \tif(fstat(fileno(fd), &file_info)!=0;\n \treturn 1; \/* can't continue *\/ \n \n \tcurl = curl_easy_init();\n\t\/\/ if(curl) {\n \t\/\/выбор места для загрузки\n \tcurl_easy_setopt(curl, CURLOPT_URL,url.c_str());\n \tcurl_easy_setopt(curl, CURLOPT_READDATA, &response); \n \tcurl_easy_setopt(curl, CURLOPT_READFUNCTION, write<stringstream>);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, head_list);\n \tauto res = curl_easy_perform(curl);\n \tcurl_easy_cleanup(curl);\n \treturn http_response_code == 200;\n\treturn ans;\n \t \/\/загрузка по URL\n \tcurl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);\n \tcurl_easy_setopt(curl, CURLOPT_PUT, 1L);\n \t\/\/чтения файла \n \tcurl_easy_setopt(curl, CURLOPT_READDATA, fd);\n \t\/\/устанавливаем размер файла для отправки\n \tcurl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,(curl_off_t)file_info.st_size);\n \t\/\/для облегчения трассировки \n \tcurl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n \tauto response_code = curl_easy_perform(curl);\n\tcurl_slist_free_all(head_list);\n\tcurl_easy_cleanup(curl);\n\tif (response_code != CURLE_OK) return json();\n\treturn http_response_code == 201;\n \treturn 0; \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file kmeans.cpp\n * @brief mex interface for kmeans\n * @author Kota Yamaguchi\n * @date 2011\n *\/\n#include \"mexopencv.hpp\"\nusing namespace std;\nusing namespace cv;\n\n\/** KMeans initalization types for option processing\n *\/\nconst ConstMap<std::string,int> Initialization = ConstMap<std::string,int>\n\t(\"Random\",KMEANS_RANDOM_CENTERS)\n\t(\"PP\",KMEANS_PP_CENTERS);\n\n\/**\n * Main entry called from Matlab\n * @param nlhs number of left-hand-side arguments\n * @param plhs pointers to mxArrays in the left-hand-side\n * @param nrhs number of right-hand-side arguments\n * @param prhs pointers to mxArrays in the right-hand-side\n *\/\nvoid mexFunction( int nlhs, mxArray *plhs[],\n int nrhs, const mxArray *prhs[] )\n{\n\t\/\/ Check the number of arguments\n\tif (nrhs<2 || ((nrhs%2)!=0) || nlhs>3)\n mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n \n\t\/\/ Argument vector\n\tvector<MxArray> rhs(prhs,prhs+nrhs);\n\tMat samples(rhs[0].toMat(CV_32F));\n\tint clusterCount = rhs[1].toInt();\n\tMat labels;\n\tTermCriteria criteria;\n\tint attempts=10;\n\tint flags = KMEANS_RANDOM_CENTERS;\n\tMat centers;\n\tfor (int i=2; i<nrhs; i+=2) {\n\t\tstring key = rhs[i].toString();\n\t\tif (key==\"InitialLabels\")\n\t\t\tlabels = rhs[i+1].toMat(CV_32S);\n\t\telse if (key==\"Criteria\")\n\t\t\tcriteria = rhs[i+1].toTermCriteria();\n\t\telse if (key==\"Attempts\")\n\t\t\tattempts = rhs[i+1].toInt();\n\t\telse if (key==\"Initialization\")\n\t\t\tflags = Initialization[rhs[i+1].toString()];\n\t\telse\n\t\t\tmexErrMsgIdAndTxt(\"mexopencv:error\",\"Unrecognized option\");\n\t}\n\tflags |= (labels.empty()) ? 0 : KMEANS_USE_INITIAL_LABELS;\n\t\n\t\/\/ Process\n\tdouble d = kmeans(samples, clusterCount, labels, criteria, attempts, flags,\n\t\tcenters);\n\tplhs[0] = MxArray(labels);\n\tif (nlhs>1)\n\t\tplhs[1] = MxArray(centers);\n\tif (nlhs>2)\n\t\tplhs[2] = MxArray(d);\n}\n<commit_msg>Fixed a version compatibility<commit_after>\/**\n * @file kmeans.cpp\n * @brief mex interface for kmeans\n * @author Kota Yamaguchi\n * @date 2011\n *\/\n#include \"mexopencv.hpp\"\nusing namespace std;\nusing namespace cv;\n\n\/** KMeans initalization types for option processing\n *\/\nconst ConstMap<std::string,int> Initialization = ConstMap<std::string,int>\n\t(\"Random\",KMEANS_RANDOM_CENTERS)\n\t(\"PP\",KMEANS_PP_CENTERS);\n\n\/**\n * Main entry called from Matlab\n * @param nlhs number of left-hand-side arguments\n * @param plhs pointers to mxArrays in the left-hand-side\n * @param nrhs number of right-hand-side arguments\n * @param prhs pointers to mxArrays in the right-hand-side\n *\/\nvoid mexFunction( int nlhs, mxArray *plhs[],\n int nrhs, const mxArray *prhs[] )\n{\n\t\/\/ Check the number of arguments\n\tif (nrhs<2 || ((nrhs%2)!=0) || nlhs>3)\n mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n \n\t\/\/ Argument vector\n\tvector<MxArray> rhs(prhs,prhs+nrhs);\n\tMat samples(rhs[0].toMat(CV_32F));\n\tint clusterCount = rhs[1].toInt();\n\tMat labels;\n\tTermCriteria criteria;\n\tint attempts=10;\n\tint flags = KMEANS_RANDOM_CENTERS;\n\tMat centers;\n\tfor (int i=2; i<nrhs; i+=2) {\n\t\tstring key = rhs[i].toString();\n\t\tif (key==\"InitialLabels\")\n\t\t\tlabels = rhs[i+1].toMat(CV_32S);\n\t\telse if (key==\"Criteria\")\n\t\t\tcriteria = rhs[i+1].toTermCriteria();\n\t\telse if (key==\"Attempts\")\n\t\t\tattempts = rhs[i+1].toInt();\n\t\telse if (key==\"Initialization\")\n\t\t\tflags = Initialization[rhs[i+1].toString()];\n\t\telse\n\t\t\tmexErrMsgIdAndTxt(\"mexopencv:error\",\"Unrecognized option\");\n\t}\n\tflags |= (labels.empty()) ? 0 : KMEANS_USE_INITIAL_LABELS;\n\t\n\t\/\/ Process\n#if CV_MINOR_VERSION >= 2\n\tdouble d = kmeans(samples, clusterCount, labels, criteria, attempts, flags,\n\t\tcenters);\n#else\n\tcenters = Mat(samples.rows,clusterCount,CV_32FC1);\n\tdouble d = kmeans(samples, clusterCount, labels, criteria, attempts, flags,\n\t\t¢ers);\n#endif\n\tplhs[0] = MxArray(labels);\n\tif (nlhs>1)\n\t\tplhs[1] = MxArray(centers);\n\tif (nlhs>2)\n\t\tplhs[2] = MxArray(d);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>App: [skip ci] implement the private class OriginExtension to simulate a geometric group behaviour<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"Atm_player.hpp\"\n\n\/* Add optional parameters for the state machine to begin()\n * Add extra initialization code\n *\/\n\nAtm_player& Atm_player::begin( int pin \/* = - 1 *\/ ) {\n \/\/ clang-format off\n const static state_t state_table[] PROGMEM = {\n \/* ON_ENTER ON_LOOP ON_EXIT EVT_START EVT_STOP EVT_TOGGLE EVT_TIMER EVT_EOPAT EVT_REPEAT ELSE *\/\n \/* IDLE *\/ ENT_IDLE, ATM_SLEEP, -1, START, -1, START, -1, -1, -1, -1,\n \/* START *\/ ENT_START, -1, -1, -1, -1, -1, -1, -1, -1, SOUND,\n \/* SOUND *\/ ENT_SOUND, -1, -1, -1, IDLE, IDLE, QUIET, -1, -1, -1,\n \/* QUIET *\/ ENT_QUIET, -1, -1, -1, IDLE, IDLE, NEXT, -1, -1, -1,\n \/* NEXT *\/ ENT_NEXT, -1, -1, -1, IDLE, IDLE, -1, REPEAT, -1, SOUND,\n \/* REPEAT *\/ ENT_REPEAT, -1, -1, -1, IDLE, IDLE, -1, -1, FINISH, START,\n \/* FINISH *\/ ENT_FINISH, -1, -1, -1, IDLE, -1, -1, -1, IDLE, START,\n };\n \/\/ clang-format on\n Machine::begin( state_table, ELSE );\n Atm_player::pin = pin;\n speed( 100 );\n pitch( 100 );\n repeat( 1 );\n return *this;\n}\n\n\/* Add C++ code for each event (input)\n * The code must return 1 if the event should be triggered\n *\/\n\nint Atm_player::event( int id ) {\n switch ( id ) {\n case EVT_START:\n return 0;\n case EVT_TIMER:\n return timer.expired( this );\n case EVT_EOPAT:\n return ( step * 6 ) >= patternsize;\n case EVT_REPEAT:\n return counter_repeat.expired();\n }\n return 0;\n}\n\n\/* Add C++ code for each action\n * This generates the 'output' for the state machine\n *\/\n\nvoid Atm_player::action( int id ) {\n switch ( id ) {\n case ENT_FINISH:\n push( connectors, ON_FINISH, 0, 0, 0 );\n return;\n case ENT_IDLE:\n if ( pin >= 0 ) noTone( pin );\n counter_repeat.set( repeatCount );\n return;\n case ENT_START:\n step = 0;\n counter_repeat.decrement();\n return;\n case ENT_SOUND:\n push( connectors, ON_NOTE, true, pattern[step * 3] * pitchFactor, 1 );\n if ( pin >= 0 ) tone( pin, pattern[step * 3] * pitchFactor );\n timer.set( pattern[step * 3 + 1] * speedFactor );\n return;\n case ENT_QUIET:\n push( connectors, ON_NOTE, false, pattern[step * 3] * pitchFactor, 0 );\n if ( pin >= 0 ) noTone( pin );\n timer.set( pattern[step * 3 + 2] * speedFactor );\n return;\n case ENT_NEXT:\n step++;\n return;\n case ENT_REPEAT:\n return;\n }\n}\n\n\/* How many times to repeat the pattern\n *\n *\/\n\nAtm_player& Atm_player::repeat( uint16_t v ) {\n counter_repeat.set( repeatCount = v );\n return *this;\n}\n\nAtm_player& Atm_player::speed( float v ) {\n speedFactor = 100 \/ v;\n return *this;\n}\n\nAtm_player& Atm_player::pitch( float v ) {\n pitchFactor = v \/ 100;\n return *this;\n}\n\n\/* Sets the pattern and pattern length (in bytes)\n *\n *\/\n\nAtm_player& Atm_player::play( int* pat, int patsize ) {\n pattern = pat;\n patternsize = patsize;\n counter_repeat.set( repeatCount );\n step = 0;\n return *this;\n}\n\nAtm_player& Atm_player::play( int freq, int period, int pause \/* = 0 *\/ ) {\n stub[0] = freq;\n stub[1] = period;\n stub[2] = pause;\n pattern = stub;\n patternsize = 6;\n step = 0;\n return *this;\n}\n\n\/* Optionally override the default trigger() method\n * Control what triggers your machine can and cannot process\n *\/\n\nAtm_player& Atm_player::trigger( int event ) {\n Machine::trigger( event );\n return *this;\n}\n\n\/* Optionally override the default state() method\n * Control what the machine returns when another process requests its state()\n *\/\n\nint Atm_player::state( void ) {\n return Machine::state();\n}\n\n\/* Nothing customizable below this line \n ************************************************************************************************\n*\/\n\n\/* onFinish() push connector variants ( slots 1, autostore 0, broadcast 0 )\n *\n * Usage in action() handler: push( connectors, ON_FINISH, 0, v, up)\n *\/\n\nAtm_player& Atm_player::onFinish( Machine& machine, int event ) { onPush( connectors, ON_FINISH, 0, 1, 1, 0, machine, event ); return *this; }\nAtm_player& Atm_player::onFinish( atm_cb_push_t callback, int idx ) { onPush( connectors, ON_FINISH, 0, 1, 1, 0, callback, idx ); return *this; }\n\n\/* onNote() push connector variants ( slots 2, autostore 0, broadcast 0 )\n *\n * Usage in action() handler: push( connectors, ON_NOTE, sub, v, up)\n *\/\n\nAtm_player& Atm_player::onNote( Machine& machine, int event ) { onPush( connectors, ON_NOTE, 0, 2, 1, 0, machine, event ); return *this; }\nAtm_player& Atm_player::onNote( atm_cb_push_t callback, int idx ) { onPush( connectors, ON_NOTE, 0, 2, 1, 0, callback, idx ); return *this; }\nAtm_player& Atm_player::onNote( int sub, Machine& machine, int event ) { onPush( connectors, ON_NOTE, sub, 2, 0, 0, machine, event ); return *this; }\nAtm_player& Atm_player::onNote( int sub, atm_cb_push_t callback, int idx ) { onPush( connectors, ON_NOTE, sub, 2, 0, 0, callback, idx ); return *this; }\n\n\n\/* State trace method\n * Sets the symbol table and the default logging method for serial monitoring\n *\/\n\nAtm_player& Atm_player::trace( Stream& stream ) {\n Machine::setTrace( &stream, atm_serial_debug::trace,\n \"PLAYER\\0EVT_START\\0EVT_STOP\\0EVT_TOGGLE\\0EVT_TIMER\\0EVT_EOPAT\\0EVT_REPEAT\\0ELSE\\0IDLE\\0START\\0SOUND\\0QUIET\\0NEXT\\0REPEAT\\0FINISH\" );\n return *this;\n}\n<commit_msg>begin() set player to play a 50ms 880hz tone by default<commit_after>#include \"Atm_player.hpp\"\n\n\/* Add optional parameters for the state machine to begin()\n * Add extra initialization code\n *\/\n\nAtm_player& Atm_player::begin( int pin \/* = - 1 *\/ ) {\n \/\/ clang-format off\n const static state_t state_table[] PROGMEM = {\n \/* ON_ENTER ON_LOOP ON_EXIT EVT_START EVT_STOP EVT_TOGGLE EVT_TIMER EVT_EOPAT EVT_REPEAT ELSE *\/\n \/* IDLE *\/ ENT_IDLE, ATM_SLEEP, -1, START, -1, START, -1, -1, -1, -1,\n \/* START *\/ ENT_START, -1, -1, -1, -1, -1, -1, -1, -1, SOUND,\n \/* SOUND *\/ ENT_SOUND, -1, -1, -1, IDLE, IDLE, QUIET, -1, -1, -1,\n \/* QUIET *\/ ENT_QUIET, -1, -1, -1, IDLE, IDLE, NEXT, -1, -1, -1,\n \/* NEXT *\/ ENT_NEXT, -1, -1, -1, IDLE, IDLE, -1, REPEAT, -1, SOUND,\n \/* REPEAT *\/ ENT_REPEAT, -1, -1, -1, IDLE, IDLE, -1, -1, FINISH, START,\n \/* FINISH *\/ ENT_FINISH, -1, -1, -1, IDLE, -1, -1, -1, IDLE, START,\n };\n \/\/ clang-format on\n Machine::begin( state_table, ELSE );\n Atm_player::pin = pin;\n speed( 100 );\n pitch( 100 );\n repeat( 1 );\n play( 880, 50 );\n return *this;\n}\n\n\/* Add C++ code for each event (input)\n * The code must return 1 if the event should be triggered\n *\/\n\nint Atm_player::event( int id ) {\n switch ( id ) {\n case EVT_START:\n return 0;\n case EVT_TIMER:\n return timer.expired( this );\n case EVT_EOPAT:\n return ( step * 6 ) >= patternsize;\n case EVT_REPEAT:\n return counter_repeat.expired();\n }\n return 0;\n}\n\n\/* Add C++ code for each action\n * This generates the 'output' for the state machine\n *\/\n\nvoid Atm_player::action( int id ) {\n switch ( id ) {\n case ENT_FINISH:\n push( connectors, ON_FINISH, 0, 0, 0 );\n return;\n case ENT_IDLE:\n if ( pin >= 0 ) noTone( pin );\n counter_repeat.set( repeatCount );\n return;\n case ENT_START:\n step = 0;\n counter_repeat.decrement();\n return;\n case ENT_SOUND:\n push( connectors, ON_NOTE, true, pattern[step * 3] * pitchFactor, 1 );\n if ( pin >= 0 ) tone( pin, pattern[step * 3] * pitchFactor );\n timer.set( pattern[step * 3 + 1] * speedFactor );\n return;\n case ENT_QUIET:\n push( connectors, ON_NOTE, false, pattern[step * 3] * pitchFactor, 0 );\n if ( pin >= 0 ) noTone( pin );\n timer.set( pattern[step * 3 + 2] * speedFactor );\n return;\n case ENT_NEXT:\n step++;\n return;\n case ENT_REPEAT:\n return;\n }\n}\n\n\/* How many times to repeat the pattern\n *\n *\/\n\nAtm_player& Atm_player::repeat( uint16_t v ) {\n counter_repeat.set( repeatCount = v );\n return *this;\n}\n\nAtm_player& Atm_player::speed( float v ) {\n speedFactor = 100 \/ v;\n return *this;\n}\n\nAtm_player& Atm_player::pitch( float v ) {\n pitchFactor = v \/ 100;\n return *this;\n}\n\n\/* Sets the pattern and pattern length (in bytes)\n *\n *\/\n\nAtm_player& Atm_player::play( int* pat, int patsize ) {\n pattern = pat;\n patternsize = patsize;\n counter_repeat.set( repeatCount );\n step = 0;\n return *this;\n}\n\nAtm_player& Atm_player::play( int freq, int period, int pause \/* = 0 *\/ ) {\n stub[0] = freq;\n stub[1] = period;\n stub[2] = pause;\n pattern = stub;\n patternsize = 6;\n step = 0;\n return *this;\n}\n\n\/* Optionally override the default trigger() method\n * Control what triggers your machine can and cannot process\n *\/\n\nAtm_player& Atm_player::trigger( int event ) {\n Machine::trigger( event );\n return *this;\n}\n\n\/* Optionally override the default state() method\n * Control what the machine returns when another process requests its state()\n *\/\n\nint Atm_player::state( void ) {\n return Machine::state();\n}\n\n\/* Nothing customizable below this line \n ************************************************************************************************\n*\/\n\n\/* onFinish() push connector variants ( slots 1, autostore 0, broadcast 0 )\n *\n * Usage in action() handler: push( connectors, ON_FINISH, 0, v, up)\n *\/\n\nAtm_player& Atm_player::onFinish( Machine& machine, int event ) { onPush( connectors, ON_FINISH, 0, 1, 1, 0, machine, event ); return *this; }\nAtm_player& Atm_player::onFinish( atm_cb_push_t callback, int idx ) { onPush( connectors, ON_FINISH, 0, 1, 1, 0, callback, idx ); return *this; }\n\n\/* onNote() push connector variants ( slots 2, autostore 0, broadcast 0 )\n *\n * Usage in action() handler: push( connectors, ON_NOTE, sub, v, up)\n *\/\n\nAtm_player& Atm_player::onNote( Machine& machine, int event ) { onPush( connectors, ON_NOTE, 0, 2, 1, 0, machine, event ); return *this; }\nAtm_player& Atm_player::onNote( atm_cb_push_t callback, int idx ) { onPush( connectors, ON_NOTE, 0, 2, 1, 0, callback, idx ); return *this; }\nAtm_player& Atm_player::onNote( int sub, Machine& machine, int event ) { onPush( connectors, ON_NOTE, sub, 2, 0, 0, machine, event ); return *this; }\nAtm_player& Atm_player::onNote( int sub, atm_cb_push_t callback, int idx ) { onPush( connectors, ON_NOTE, sub, 2, 0, 0, callback, idx ); return *this; }\n\n\n\/* State trace method\n * Sets the symbol table and the default logging method for serial monitoring\n *\/\n\nAtm_player& Atm_player::trace( Stream& stream ) {\n Machine::setTrace( &stream, atm_serial_debug::trace,\n \"PLAYER\\0EVT_START\\0EVT_STOP\\0EVT_TOGGLE\\0EVT_TIMER\\0EVT_EOPAT\\0EVT_REPEAT\\0ELSE\\0IDLE\\0START\\0SOUND\\0QUIET\\0NEXT\\0REPEAT\\0FINISH\" );\n return *this;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ AtomHandler for fluxbox\n\/\/ Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/ 2003 Simon Bowden (rathnor at users.sourceforge.net)\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: AtomHandler.hh,v 1.13 2004\/01\/09 02:06:55 fluxgen Exp $\n\n#ifndef ATOMHANDLER_HH\n#define ATOMHANDLER_HH\n\n#include <X11\/Xlib.h>\n\nclass FluxboxWindow;\nclass WinClient;\nclass BScreen;\n\nclass AtomHandler {\npublic:\n\n virtual ~AtomHandler() { }\n\n virtual void initForScreen(BScreen &screen) = 0;\n virtual void setupFrame(FluxboxWindow &win) = 0;\n virtual void setupClient(WinClient &winclient) = 0;\n\n virtual void updateClientList(BScreen &screen) = 0;\n virtual void updateWorkspaceNames(BScreen &screen) = 0;\n virtual void updateCurrentWorkspace(BScreen &screen) = 0;\n virtual void updateWorkspaceCount(BScreen &screen) = 0;\n\n virtual void updateFrameClose(FluxboxWindow &win) = 0;\n virtual void updateClientClose(WinClient &winclient) = 0;\n virtual void updateWorkspace(FluxboxWindow &win) = 0;\n virtual void updateState(FluxboxWindow &win) = 0;\n virtual void updateHints(FluxboxWindow &win) = 0;\n virtual void updateLayer(FluxboxWindow &win) = 0;\n\n virtual bool checkClientMessage(const XClientMessageEvent &ce, \n BScreen * screen, WinClient * const winclient) = 0;\n\n virtual bool propertyNotify(WinClient &winclient, Atom the_property) = 0;\n\n \/\/\/ should this object be updated or not?\n bool update() const { return m_update; }\nprotected:\n AtomHandler():m_update(true) { }\n\n void disableUpdate() { m_update = false; }\n void enableUpdate() { m_update = true; }\t\nprivate:\n bool m_update; \/\/\/< do we get update or not\n};\n\n#endif \/\/ ATOMHANDLER_HH\n<commit_msg>updateFocusedWindow, updateWorkarea<commit_after>\/\/ AtomHandler for fluxbox\n\/\/ Copyright (c) 2002-2004 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/ 2003-2004 Simon Bowden (rathnor at users.sourceforge.net)\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: AtomHandler.hh,v 1.14 2004\/01\/19 18:22:37 fluxgen Exp $\n\n#ifndef ATOMHANDLER_HH\n#define ATOMHANDLER_HH\n\n#include <X11\/Xlib.h>\n\nclass FluxboxWindow;\nclass WinClient;\nclass BScreen;\n\nclass AtomHandler {\npublic:\n\n virtual ~AtomHandler() { }\n\n virtual void initForScreen(BScreen &screen) = 0;\n virtual void setupFrame(FluxboxWindow &win) = 0;\n virtual void setupClient(WinClient &winclient) = 0;\n\n virtual void updateFocusedWindow(BScreen &screen, Window win) = 0; \n virtual void updateClientList(BScreen &screen) = 0;\n virtual void updateWorkspaceNames(BScreen &screen) = 0;\n virtual void updateCurrentWorkspace(BScreen &screen) = 0;\n virtual void updateWorkspaceCount(BScreen &screen) = 0;\n virtual void updateWorkarea(BScreen &screen) = 0;\n\n virtual void updateFrameClose(FluxboxWindow &win) = 0;\n virtual void updateClientClose(WinClient &winclient) = 0;\n virtual void updateWorkspace(FluxboxWindow &win) = 0;\n virtual void updateState(FluxboxWindow &win) = 0;\n virtual void updateHints(FluxboxWindow &win) = 0;\n virtual void updateLayer(FluxboxWindow &win) = 0;\n\n virtual bool checkClientMessage(const XClientMessageEvent &ce, \n BScreen * screen, WinClient * const winclient) = 0;\n\n virtual bool propertyNotify(WinClient &winclient, Atom the_property) = 0;\n\n \/\/\/ should this object be updated or not?\n bool update() const { return m_update; }\nprotected:\n AtomHandler():m_update(true) { }\n\n void disableUpdate() { m_update = false; }\n void enableUpdate() { m_update = true; }\t\nprivate:\n bool m_update; \/\/\/< do we get update or not\n};\n\n#endif \/\/ ATOMHANDLER_HH\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ local includes\n#include \"BasicSieve.h\"\n#include \"SievePrimes.h\"\n\n\/\/ ================================================================================================\n\/\/ Constructor\n\/\/ ================================================================================================\nBasicSieve::BasicSieve() : CalcMethod(), sieve(), sievePos(0), curr(1), currSqrt(1) {\n for(size_t i = 0; i < kNumSievePrimes; ++i)\n sieve.AddPrime(kSievePrimes[i]);\n\n primes.resize(kNumSievePrimes);\n for(size_t i = 0; i < kNumSievePrimes; ++i)\n primes[i] = kSievePrimes[i];\n\n NextNumber();\n}\n\n\/\/ ================================================================================================\n\/\/ Compute primes up to a limit\n\/\/ ================================================================================================\nvoid BasicSieve::ComputePrimes(U64 limit) {\n while(curr <= limit) {\n \/\/ Check to see if curr is prime\n bool isPrime = true;\n \/\/ We don't need to check the primes that went into the sieve\n for(size_t i = kNumSievePrimes; i < primes.size() && primes[i] <= currSqrt; ++i) {\n if(curr % primes[i] == 0) {\n isPrime = false;\n break;\n }\n }\n if(isPrime)\n primes.push_back(curr);\n\n NextNumber();\n }\n}\n\n\/\/ ================================================================================================\nvoid BasicSieve::NextNumber() {\n \/\/ Move on to the next number\n curr += sieve.Offset(sievePos);\n \/\/ Update the offset index\n if(++sievePos == sieve.NumOffsets())\n sievePos = 0;\n\n \/\/ Update the square root\n while(currSqrt * currSqrt <= curr)\n ++currSqrt;\n}\n\n<commit_msg>Checked one too many potential divisors<commit_after>\n\/\/ local includes\n#include \"BasicSieve.h\"\n#include \"SievePrimes.h\"\n\n\/\/ ================================================================================================\n\/\/ Constructor\n\/\/ ================================================================================================\nBasicSieve::BasicSieve() : CalcMethod(), sieve(), sievePos(0), curr(1), currSqrt(1) {\n for(size_t i = 0; i < kNumSievePrimes; ++i)\n sieve.AddPrime(kSievePrimes[i]);\n\n primes.resize(kNumSievePrimes);\n for(size_t i = 0; i < kNumSievePrimes; ++i)\n primes[i] = kSievePrimes[i];\n\n NextNumber();\n}\n\n\/\/ ================================================================================================\n\/\/ Compute primes up to a limit\n\/\/ ================================================================================================\nvoid BasicSieve::ComputePrimes(U64 limit) {\n while(curr <= limit) {\n \/\/ Check to see if curr is prime\n bool isPrime = true;\n \/\/ We don't need to check the primes that went into the sieve\n for(size_t i = kNumSievePrimes; i < primes.size() && primes[i] < currSqrt; ++i) {\n if(curr % primes[i] == 0) {\n isPrime = false;\n break;\n }\n }\n if(isPrime)\n primes.push_back(curr);\n\n NextNumber();\n }\n}\n\n\/\/ ================================================================================================\nvoid BasicSieve::NextNumber() {\n \/\/ Move on to the next number\n curr += sieve.Offset(sievePos);\n \/\/ Update the offset index\n if(++sievePos == sieve.NumOffsets())\n sievePos = 0;\n\n \/\/ Update the square root\n while(currSqrt * currSqrt <= curr)\n ++currSqrt;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"BenchmarkC.h\"\n#include <stdlib.h> \/* malloc, calloc, realloc, free *\/\n#include <cstddef> \/\/ std::size_t\n#include <iostream>\n\nBenchmarkC::BenchmarkC(const int runtime)\n\t: Benchmark(runtime) {\n}\n\nBenchmarkResults BenchmarkC::allocation() {\n\tstd::cout << \"C ALLOCATION\" << std::endl;\n\n\tsetStartTimer();\n\n\tint operations = 0;\n\twhile(!outOfTime()){\n\t\tmalloc(sizeof(int));\n\t\tmalloc(sizeof(bool));\n\t\tmalloc(sizeof(foo));\t\t\n\n\t\t++operations;\n\t}\n\n\tBenchmarkResults results = buildResults(operations, m_runtime, 0, 0);\n\t\n\tprintResults(results);\n\n\treturn results;\n}\n\n\/*\tTheres no way to benchmark only free calls.\n\tOne option could be allocate and store all pointers in a stack but then the benchmarking would be biased\n\tThe onyl thing we can do is allocate memory and then free it afterwards.\n\n*\/\nBenchmarkResults BenchmarkC::freeing() {\n\tstd::cout << \"C FREEING\" << std::endl;\n\n\tsetStartTimer();\n\tint * i;\n\tbool * b;\n\tfoo * f;\n\tstd::size_t operations = 0;\n\tdouble elapsedTime = 0;\n\twhile(elapsedTime < (m_runtime * 1e3)){\n\t\tif (operations % 2 == 0){\n\t\t\ti = (int*) malloc(sizeof(int));\n\t\t\tb = (bool*)malloc(sizeof(bool));\n\t\t\tf = (foo*) malloc(sizeof(foo));\t\n\n\t\t}else {\n\t\t\ttimespec before_free, after_free;\n\t\t\tsetTimer(before_free);\n\t\t\tfree(f);\n\t\t\tfree(b);\n\t\t\tfree(i);\n\t\t\tsetTimer(after_free);\n\t\t\telapsedTime += calculateElapsedTime(before_free, after_free);\n\t\t}\n\t\t++operations;\n\t}\n\n\tBenchmarkResults results = buildResults(operations\/2, m_runtime, 0, 0);\n\t\n\tprintResults(results);\n\n\treturn results;\n}\n\nBenchmarkResults BenchmarkC::read() {\n\treturn buildResults(0, 0, 0, 0);\n}\n\nBenchmarkResults BenchmarkC::write() {\n\treturn buildResults(0, 0, 0, 0);\n}\n\nBenchmarkResults BenchmarkC::all() {\n\treturn buildResults(0, 0, 0, 0);\n}<commit_msg>Added read benchmark<commit_after>#include \"BenchmarkC.h\"\n#include <stdlib.h> \/* malloc, calloc, realloc, free *\/\n#include <cstddef> \/\/ std::size_t\n#include <iostream>\n\nBenchmarkC::BenchmarkC(const int runtime)\n\t: Benchmark(runtime) {\n}\n\nBenchmarkResults BenchmarkC::allocation() {\n\tstd::cout << \"C ALLOCATION\" << std::endl;\n\n\tsetStartTimer();\n\n\tint operations = 0;\n\twhile(!outOfTime()){\n\t\tmalloc(sizeof(int));\n\t\tmalloc(sizeof(bool));\n\t\tmalloc(sizeof(foo));\t\t\n\n\t\t++operations;\n\t}\n\n\tBenchmarkResults results = buildResults(operations, m_runtime, 0, 0);\n\t\n\tprintResults(results);\n\n\treturn results;\n}\n\n\/*\tTheres no way to benchmark only free calls.\n\tOne option could be allocate and store all pointers in a stack but then the benchmarking would be biased\n\tThe onyl thing we can do is allocate memory and then free it afterwards.\n\n*\/\nBenchmarkResults BenchmarkC::freeing() {\n\tstd::cout << \"C FREEING\" << std::endl;\n\n\tsetStartTimer();\n\tint * i;\n\tbool * b;\n\tfoo * f;\n\tstd::size_t operations = 0;\n\tdouble elapsedTime = 0;\n\twhile(elapsedTime < (m_runtime * 1e3)){\n\t\tif (operations % 2 == 0){\n\t\t\ti = (int*) malloc(sizeof(int));\n\t\t\tb = (bool*)malloc(sizeof(bool));\n\t\t\tf = (foo*) malloc(sizeof(foo));\t\n\n\t\t}else {\n\t\t\ttimespec before_free, after_free;\n\t\t\tsetTimer(before_free);\n\t\t\tfree(f);\n\t\t\tfree(b);\n\t\t\tfree(i);\n\t\t\tsetTimer(after_free);\n\t\t\telapsedTime += calculateElapsedTime(before_free, after_free);\n\t\t}\n\t\t++operations;\n\t}\n\n\tBenchmarkResults results = buildResults(operations\/2, m_runtime, 0, 0);\n\t\n\tprintResults(results);\n\n\treturn results;\n}\n\nBenchmarkResults BenchmarkC::read() {\n\tstd::cout << \"C READ\" << std::endl;\n\n\tsetStartTimer();\n\n\tstd::size_t operations = 0;\n\tdouble elapsedTime = 0;\n\twhile(elapsedTime < (m_runtime * 1e3)){\n\t\tint * i = (int*) malloc(sizeof(int));\n\t\tbool * b = (bool*)malloc(sizeof(bool));\n\t\tfoo * f = (foo*) malloc(sizeof(foo));\t\n\n\t\ttimespec before_read, after_read;\n\t\tsetTimer(before_read);\n\t\tint i_value = *i;\n\t\tbool b_value = *b;\n\t\tfoo f_value = *f;\n\t\tsetTimer(after_read);\n\n\t\telapsedTime += calculateElapsedTime(before_read, after_read);\n\t\t++operations;\n\t}\n\n\tBenchmarkResults results = buildResults(operations\/2, m_runtime, 0, 0);\n\t\n\tprintResults(results);\n\n\treturn results;\n}\n\nBenchmarkResults BenchmarkC::write() {\n\treturn buildResults(0, 0, 0, 0);\n}\n\nBenchmarkResults BenchmarkC::all() {\n\treturn buildResults(0, 0, 0, 0);\n}<|endoftext|>"} {"text":"<commit_before>#include \"Connection.hpp\"\n\n#include <cmath>\n#include <utility>\n\n#include <QtWidgets\/QtWidgets>\n#include <QtGlobal>\n\n#include \"Node.hpp\"\n#include \"FlowScene.hpp\"\n#include \"FlowView.hpp\"\n\n#include \"NodeGeometry.hpp\"\n#include \"NodeGraphicsObject.hpp\"\n#include \"NodeDataModel.hpp\"\n\n#include \"ConnectionState.hpp\"\n#include \"ConnectionGeometry.hpp\"\n#include \"ConnectionGraphicsObject.hpp\"\n\nusing QtNodes::Connection;\nusing QtNodes::PortType;\nusing QtNodes::PortIndex;\nusing QtNodes::ConnectionState;\nusing QtNodes::Node;\nusing QtNodes::NodeData;\nusing QtNodes::NodeDataType;\nusing QtNodes::ConnectionGraphicsObject;\nusing QtNodes::ConnectionGeometry;\nusing QtNodes::TypeConverter;\n\nConnection::\nConnection(PortType portType,\n Node& node,\n PortIndex portIndex)\n : _uid(QUuid::createUuid())\n , _outPortIndex(INVALID)\n , _inPortIndex(INVALID)\n , _connectionState()\n{\n setNodeToPort(node, portType, portIndex);\n\n setRequiredPort(oppositePort(portType));\n}\n\n\nConnection::\nConnection(Node& nodeIn,\n PortIndex portIndexIn,\n Node& nodeOut,\n PortIndex portIndexOut,\n TypeConverter typeConverter)\n : _uid(QUuid::createUuid())\n , _outNode(&nodeOut)\n , _inNode(&nodeIn)\n , _outPortIndex(portIndexOut)\n , _inPortIndex(portIndexIn)\n , _connectionState()\n , _converter(std::move(typeConverter))\n{\n setNodeToPort(nodeIn, PortType::In, portIndexIn);\n setNodeToPort(nodeOut, PortType::Out, portIndexOut);\n}\n\n\nConnection::\n~Connection()\n{\n if (complete())\n {\n connectionMadeIncomplete(*this);\n }\n\n propagateEmptyData();\n\n if (_inNode)\n {\n _inNode->nodeGraphicsObject().update();\n }\n\n if (_outNode)\n {\n _outNode->nodeGraphicsObject().update();\n }\n}\n\n\nQJsonObject\nConnection::\nsave() const\n{\n QJsonObject connectionJson;\n\n if (_inNode && _outNode)\n {\n connectionJson[\"in_id\"] = _inNode->id().toString();\n connectionJson[\"in_index\"] = _inPortIndex;\n\n connectionJson[\"out_id\"] = _outNode->id().toString();\n connectionJson[\"out_index\"] = _outPortIndex;\n\n if (_converter)\n {\n auto getTypeJson = [this](PortType type)\n {\n QJsonObject typeJson;\n NodeDataType nodeType = this->dataType(type);\n typeJson[\"id\"] = nodeType.id;\n typeJson[\"name\"] = nodeType.name;\n\n return typeJson;\n };\n\n QJsonObject converterTypeJson;\n\n converterTypeJson[\"in\"] = getTypeJson(PortType::In);\n converterTypeJson[\"out\"] = getTypeJson(PortType::Out);\n\n connectionJson[\"converter\"] = converterTypeJson;\n }\n }\n\n return connectionJson;\n}\n\n\nQUuid\nConnection::\nid() const\n{\n return _uid;\n}\n\n\nbool\nConnection::\ncomplete() const\n{\n return _inNode != nullptr && _outNode != nullptr;\n}\n\n\nvoid\nConnection::\nsetRequiredPort(PortType dragging)\n{\n _connectionState.setRequiredPort(dragging);\n\n switch (dragging)\n {\n case PortType::Out:\n _outNode = nullptr;\n _outPortIndex = INVALID;\n break;\n\n case PortType::In:\n _inNode = nullptr;\n _inPortIndex = INVALID;\n break;\n\n default:\n break;\n }\n}\n\n\nPortType\nConnection::\nrequiredPort() const\n{\n return _connectionState.requiredPort();\n}\n\n\nvoid\nConnection::\nsetGraphicsObject(std::unique_ptr<ConnectionGraphicsObject>&& graphics)\n{\n _connectionGraphicsObject = std::move(graphics);\n\n \/\/ This function is only called when the ConnectionGraphicsObject\n \/\/ is newly created. At this moment both end coordinates are (0, 0)\n \/\/ in Connection G.O. coordinates. The position of the whole\n \/\/ Connection G. O. in scene coordinate system is also (0, 0).\n \/\/ By moving the whole object to the Node Port position\n \/\/ we position both connection ends correctly.\n\n if (requiredPort() != PortType::None)\n {\n\n PortType attachedPort = oppositePort(requiredPort());\n\n PortIndex attachedPortIndex = getPortIndex(attachedPort);\n\n auto node = getNode(attachedPort);\n\n QTransform nodeSceneTransform =\n node->nodeGraphicsObject().sceneTransform();\n\n QPointF pos = node->nodeGeometry().portScenePosition(attachedPortIndex,\n attachedPort,\n nodeSceneTransform);\n\n _connectionGraphicsObject->setPos(pos);\n }\n\n _connectionGraphicsObject->move();\n}\n\n\n\nPortIndex\nConnection::\ngetPortIndex(PortType portType) const\n{\n PortIndex result = INVALID;\n\n switch (portType)\n {\n case PortType::In:\n result = _inPortIndex;\n break;\n\n case PortType::Out:\n result = _outPortIndex;\n\n break;\n\n default:\n break;\n }\n\n return result;\n}\n\n\nvoid\nConnection::\nsetNodeToPort(Node& node,\n PortType portType,\n PortIndex portIndex)\n{\n bool wasIncomplete = !complete();\n\n auto& nodeWeak = getNode(portType);\n\n nodeWeak = &node;\n\n if (portType == PortType::Out)\n _outPortIndex = portIndex;\n else\n _inPortIndex = portIndex;\n\n _connectionState.setNoRequiredPort();\n\n updated(*this);\n if (complete() && wasIncomplete) {\n connectionCompleted(*this);\n }\n}\n\n\nvoid\nConnection::\nremoveFromNodes() const\n{\n if (_inNode)\n _inNode->nodeState().eraseConnection(PortType::In, _inPortIndex, id());\n\n if (_outNode)\n _outNode->nodeState().eraseConnection(PortType::Out, _outPortIndex, id());\n}\n\n\nConnectionGraphicsObject&\nConnection::\ngetConnectionGraphicsObject() const\n{\n return *_connectionGraphicsObject;\n}\n\n\nConnectionState&\nConnection::\nconnectionState()\n{\n return _connectionState;\n}\n\n\nConnectionState const&\nConnection::\nconnectionState() const\n{\n return _connectionState;\n}\n\n\nConnectionGeometry&\nConnection::\nconnectionGeometry()\n{\n return _connectionGeometry;\n}\n\n\nConnectionGeometry const&\nConnection::\nconnectionGeometry() const\n{\n return _connectionGeometry;\n}\n\n\nNode*\nConnection::\ngetNode(PortType portType) const\n{\n switch (portType)\n {\n case PortType::In:\n return _inNode;\n break;\n\n case PortType::Out:\n return _outNode;\n break;\n\n default:\n \/\/ not possible\n break;\n }\n return nullptr;\n}\n\n\nNode*&\nConnection::\ngetNode(PortType portType)\n{\n switch (portType)\n {\n case PortType::In:\n return _inNode;\n break;\n\n case PortType::Out:\n return _outNode;\n break;\n\n default:\n \/\/ not possible\n break;\n }\n Q_UNREACHABLE();\n}\n\n\nvoid\nConnection::\nclearNode(PortType portType)\n{\n if (complete())\n {\n connectionMadeIncomplete(*this);\n }\n\n getNode(portType) = nullptr;\n\n if (portType == PortType::In)\n _inPortIndex = INVALID;\n else\n _outPortIndex = INVALID;\n}\n\n\nNodeDataType\nConnection::\ndataType(PortType portType) const\n{\n if (_inNode && _outNode)\n {\n auto const & model = (portType == PortType::In) ?\n _inNode->nodeDataModel() :\n _outNode->nodeDataModel();\n PortIndex index = (portType == PortType::In) ? \n _inPortIndex :\n _outPortIndex;\n\n return model->dataType(portType, index);\n }\n else \n {\n Node* validNode;\n PortIndex index = INVALID;\n\n if ((validNode = _inNode))\n {\n index = _inPortIndex;\n portType = PortType::In;\n }\n else if ((validNode = _outNode))\n {\n index = _outPortIndex;\n portType = PortType::Out;\n }\n\n if (validNode)\n {\n auto const &model = validNode->nodeDataModel();\n\n return model->dataType(portType, index);\n }\n }\n\n Q_UNREACHABLE();\n}\n\n\nvoid\nConnection::\nsetTypeConverter(TypeConverter converter)\n{\n _converter = std::move(converter);\n}\n\n\nvoid\nConnection::\npropagateData(std::shared_ptr<NodeData> nodeData) const\n{\n if (_inNode)\n {\n if (_converter)\n {\n nodeData = _converter(nodeData);\n }\n\n _inNode->propagateData(nodeData, _inPortIndex);\n }\n}\n\n\nvoid\nConnection::\npropagateEmptyData() const\n{\n std::shared_ptr<NodeData> emptyData;\n\n propagateData(emptyData);\n}\n<commit_msg>Adjust the behavior of Connection's destructor (#308)<commit_after>#include \"Connection.hpp\"\n\n#include <cmath>\n#include <utility>\n\n#include <QtWidgets\/QtWidgets>\n#include <QtGlobal>\n\n#include \"Node.hpp\"\n#include \"FlowScene.hpp\"\n#include \"FlowView.hpp\"\n\n#include \"NodeGeometry.hpp\"\n#include \"NodeGraphicsObject.hpp\"\n#include \"NodeDataModel.hpp\"\n\n#include \"ConnectionState.hpp\"\n#include \"ConnectionGeometry.hpp\"\n#include \"ConnectionGraphicsObject.hpp\"\n\nusing QtNodes::Connection;\nusing QtNodes::PortType;\nusing QtNodes::PortIndex;\nusing QtNodes::ConnectionState;\nusing QtNodes::Node;\nusing QtNodes::NodeData;\nusing QtNodes::NodeDataType;\nusing QtNodes::ConnectionGraphicsObject;\nusing QtNodes::ConnectionGeometry;\nusing QtNodes::TypeConverter;\n\nConnection::\nConnection(PortType portType,\n Node& node,\n PortIndex portIndex)\n : _uid(QUuid::createUuid())\n , _outPortIndex(INVALID)\n , _inPortIndex(INVALID)\n , _connectionState()\n{\n setNodeToPort(node, portType, portIndex);\n\n setRequiredPort(oppositePort(portType));\n}\n\n\nConnection::\nConnection(Node& nodeIn,\n PortIndex portIndexIn,\n Node& nodeOut,\n PortIndex portIndexOut,\n TypeConverter typeConverter)\n : _uid(QUuid::createUuid())\n , _outNode(&nodeOut)\n , _inNode(&nodeIn)\n , _outPortIndex(portIndexOut)\n , _inPortIndex(portIndexIn)\n , _connectionState()\n , _converter(std::move(typeConverter))\n{\n setNodeToPort(nodeIn, PortType::In, portIndexIn);\n setNodeToPort(nodeOut, PortType::Out, portIndexOut);\n}\n\n\nConnection::\n~Connection()\n{\n if (complete())\n {\n connectionMadeIncomplete(*this);\n }\n\n if (_inNode)\n {\n _inNode->nodeGraphicsObject().update();\n }\n\n if (_outNode)\n {\n propagateEmptyData();\n _outNode->nodeGraphicsObject().update();\n }\n}\n\n\nQJsonObject\nConnection::\nsave() const\n{\n QJsonObject connectionJson;\n\n if (_inNode && _outNode)\n {\n connectionJson[\"in_id\"] = _inNode->id().toString();\n connectionJson[\"in_index\"] = _inPortIndex;\n\n connectionJson[\"out_id\"] = _outNode->id().toString();\n connectionJson[\"out_index\"] = _outPortIndex;\n\n if (_converter)\n {\n auto getTypeJson = [this](PortType type)\n {\n QJsonObject typeJson;\n NodeDataType nodeType = this->dataType(type);\n typeJson[\"id\"] = nodeType.id;\n typeJson[\"name\"] = nodeType.name;\n\n return typeJson;\n };\n\n QJsonObject converterTypeJson;\n\n converterTypeJson[\"in\"] = getTypeJson(PortType::In);\n converterTypeJson[\"out\"] = getTypeJson(PortType::Out);\n\n connectionJson[\"converter\"] = converterTypeJson;\n }\n }\n\n return connectionJson;\n}\n\n\nQUuid\nConnection::\nid() const\n{\n return _uid;\n}\n\n\nbool\nConnection::\ncomplete() const\n{\n return _inNode != nullptr && _outNode != nullptr;\n}\n\n\nvoid\nConnection::\nsetRequiredPort(PortType dragging)\n{\n _connectionState.setRequiredPort(dragging);\n\n switch (dragging)\n {\n case PortType::Out:\n _outNode = nullptr;\n _outPortIndex = INVALID;\n break;\n\n case PortType::In:\n _inNode = nullptr;\n _inPortIndex = INVALID;\n break;\n\n default:\n break;\n }\n}\n\n\nPortType\nConnection::\nrequiredPort() const\n{\n return _connectionState.requiredPort();\n}\n\n\nvoid\nConnection::\nsetGraphicsObject(std::unique_ptr<ConnectionGraphicsObject>&& graphics)\n{\n _connectionGraphicsObject = std::move(graphics);\n\n \/\/ This function is only called when the ConnectionGraphicsObject\n \/\/ is newly created. At this moment both end coordinates are (0, 0)\n \/\/ in Connection G.O. coordinates. The position of the whole\n \/\/ Connection G. O. in scene coordinate system is also (0, 0).\n \/\/ By moving the whole object to the Node Port position\n \/\/ we position both connection ends correctly.\n\n if (requiredPort() != PortType::None)\n {\n\n PortType attachedPort = oppositePort(requiredPort());\n\n PortIndex attachedPortIndex = getPortIndex(attachedPort);\n\n auto node = getNode(attachedPort);\n\n QTransform nodeSceneTransform =\n node->nodeGraphicsObject().sceneTransform();\n\n QPointF pos = node->nodeGeometry().portScenePosition(attachedPortIndex,\n attachedPort,\n nodeSceneTransform);\n\n _connectionGraphicsObject->setPos(pos);\n }\n\n _connectionGraphicsObject->move();\n}\n\n\n\nPortIndex\nConnection::\ngetPortIndex(PortType portType) const\n{\n PortIndex result = INVALID;\n\n switch (portType)\n {\n case PortType::In:\n result = _inPortIndex;\n break;\n\n case PortType::Out:\n result = _outPortIndex;\n\n break;\n\n default:\n break;\n }\n\n return result;\n}\n\n\nvoid\nConnection::\nsetNodeToPort(Node& node,\n PortType portType,\n PortIndex portIndex)\n{\n bool wasIncomplete = !complete();\n\n auto& nodeWeak = getNode(portType);\n\n nodeWeak = &node;\n\n if (portType == PortType::Out)\n _outPortIndex = portIndex;\n else\n _inPortIndex = portIndex;\n\n _connectionState.setNoRequiredPort();\n\n updated(*this);\n if (complete() && wasIncomplete) {\n connectionCompleted(*this);\n }\n}\n\n\nvoid\nConnection::\nremoveFromNodes() const\n{\n if (_inNode)\n _inNode->nodeState().eraseConnection(PortType::In, _inPortIndex, id());\n\n if (_outNode)\n _outNode->nodeState().eraseConnection(PortType::Out, _outPortIndex, id());\n}\n\n\nConnectionGraphicsObject&\nConnection::\ngetConnectionGraphicsObject() const\n{\n return *_connectionGraphicsObject;\n}\n\n\nConnectionState&\nConnection::\nconnectionState()\n{\n return _connectionState;\n}\n\n\nConnectionState const&\nConnection::\nconnectionState() const\n{\n return _connectionState;\n}\n\n\nConnectionGeometry&\nConnection::\nconnectionGeometry()\n{\n return _connectionGeometry;\n}\n\n\nConnectionGeometry const&\nConnection::\nconnectionGeometry() const\n{\n return _connectionGeometry;\n}\n\n\nNode*\nConnection::\ngetNode(PortType portType) const\n{\n switch (portType)\n {\n case PortType::In:\n return _inNode;\n break;\n\n case PortType::Out:\n return _outNode;\n break;\n\n default:\n \/\/ not possible\n break;\n }\n return nullptr;\n}\n\n\nNode*&\nConnection::\ngetNode(PortType portType)\n{\n switch (portType)\n {\n case PortType::In:\n return _inNode;\n break;\n\n case PortType::Out:\n return _outNode;\n break;\n\n default:\n \/\/ not possible\n break;\n }\n Q_UNREACHABLE();\n}\n\n\nvoid\nConnection::\nclearNode(PortType portType)\n{\n if (complete())\n {\n connectionMadeIncomplete(*this);\n }\n\n getNode(portType) = nullptr;\n\n if (portType == PortType::In)\n _inPortIndex = INVALID;\n else\n _outPortIndex = INVALID;\n}\n\n\nNodeDataType\nConnection::\ndataType(PortType portType) const\n{\n if (_inNode && _outNode)\n {\n auto const & model = (portType == PortType::In) ?\n _inNode->nodeDataModel() :\n _outNode->nodeDataModel();\n PortIndex index = (portType == PortType::In) ? \n _inPortIndex :\n _outPortIndex;\n\n return model->dataType(portType, index);\n }\n else \n {\n Node* validNode;\n PortIndex index = INVALID;\n\n if ((validNode = _inNode))\n {\n index = _inPortIndex;\n portType = PortType::In;\n }\n else if ((validNode = _outNode))\n {\n index = _outPortIndex;\n portType = PortType::Out;\n }\n\n if (validNode)\n {\n auto const &model = validNode->nodeDataModel();\n\n return model->dataType(portType, index);\n }\n }\n\n Q_UNREACHABLE();\n}\n\n\nvoid\nConnection::\nsetTypeConverter(TypeConverter converter)\n{\n _converter = std::move(converter);\n}\n\n\nvoid\nConnection::\npropagateData(std::shared_ptr<NodeData> nodeData) const\n{\n if (_inNode)\n {\n if (_converter)\n {\n nodeData = _converter(nodeData);\n }\n\n _inNode->propagateData(nodeData, _inPortIndex);\n }\n}\n\n\nvoid\nConnection::\npropagateEmptyData() const\n{\n std::shared_ptr<NodeData> emptyData;\n\n propagateData(emptyData);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ Name: DMAnalysis.cxx \/\/\n\/\/ \/\/\n\/\/ Creator: Andrew Hard \/\/\n\/\/ Email: ahard@cern.ch \/\/\n\/\/ Date: 15\/04\/2015 \/\/\n\/\/ \/\/\n\/\/ This namespace stores all of the global information for the H->gg + DM \/\/\n\/\/ search with 13 TeV data in 2015. It also has all of the includes that are \/\/\n\/\/ necessary for the analysis. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"DMAnalysis.h\"\n\n\/**\n -----------------------------------------------------------------------------\n Convert the DM sample name into a process name, a subset of the full name.\n @param modeName - the name of the DM production mode.\n @param processName - the name of the process.\n*\/\nTString DMAnalysis::getMediatorName(TString modeName) {\n if (modeName.Contains(\"shxx_gg\")) return \"shxx_gg\";\n else if (modeName.Contains(\"zphxx_gg\")) return \"zphxx_gg\";\n else if (modeName.Contains(\"zp2hdmxx_gg\")) return \"zp2hdmxx_gg\";\n else {\n std::cout << \"Analysis Error: no matching mediator name: \" \n\t << modeName << std::endl;\n exit(0);\n }\n}\n\n\/**\n -----------------------------------------------------------------------------\n Convert the DM sample name into a process name, a subset of the full name.\n @param modeName - the name of the DM production mode.\n @param processName - the name of the process.\n*\/\nTString DMAnalysis::getPrintMediatorName(TString modeName) {\n if (modeName.Contains(\"shxx_gg\")) return \"Scalar\";\n else if (modeName.Contains(\"zphxx_gg\")) return \"Z'\";\n else if (modeName.Contains(\"zp2hdmxx_gg\")) return \"Z_{2HDM}'\";\n else {\n std::cout << \"Analysis Error: no matching mediator name: \" \n\t << modeName << std::endl;\n exit(0);\n }\n}\n\n\/**\n -----------------------------------------------------------------------------\n Get a pretty LaTex formatted name for a variable.\n @param sampleName - The name of the sample.\n @returns - A LaTex formatted TString.\n*\/\nTString DMAnalysis::getPrintSampleName(Config *config, TString sampleName) {\n if (sampleName.EqualTo(\"gg\")) return \"#it{#gamma#gamma}\";\n else if (sampleName.EqualTo(\"gjet\")) return \"#it{#gamma}+jet\";\n else if (sampleName.EqualTo(\"SMHiggs\")) {\n return \"SM #it{H#rightarrow#gamma#gamma}\";\n }\n else if (sampleName.EqualTo(\"yy\")) return \"#it{#gamma#gamma}\";\n else if (sampleName.EqualTo(\"yjet\")) return \"#it{#gamma}+jet\";\n else if (sampleName.EqualTo(\"jj\")) return \"di-jet\";\n else if (sampleName.EqualTo(\"Zyy\")) return \"#it{Z#gamma#gamma}\";\n else if (sampleName.EqualTo(\"Wyy\")) return \"#it{W#gamma#gamma}\";\n else if (sampleName.EqualTo(\"Zy\")) return \"#it{Z#gamma}\";\n else if (sampleName.EqualTo(\"Wy\")) return \"#it{W#gamma}\";\n else if (sampleName.EqualTo(\"ttbar\")) return \"#it{t#bar{t}}\";\n else if (sampleName.EqualTo(\"diboson\")) return \"#it{WW}+#it{WZ}+#it{ZZ}\";\n else if (sampleName.EqualTo(\"ggH\")) {\n return \"#it{ggH(#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"VBF\")) {\n return \"#it{VBF (H#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"WH\")) {\n return \"#it{WH(#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"ZH\")) {\n return \"#it{ZH(#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"bbH\")) {\n return \"#it{b#bar{b}H(#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"ttH\")) {\n return \"#it{t#bar{t}H(#rightarrow#gamma#gamma)}\";\n }\n else if (DMAnalysis::isDMSample(config, sampleName)) {\n TString mediatorName = DMAnalysis::getMediatorName(sampleName);\n int mediatorMass = DMAnalysis::getMediatorMass(config, sampleName);\n TString medMassForm;\n if (mediatorName.EqualTo(\"shxx_gg\")) {\n medMassForm = Form(\"#it{m_{S}}=%dGeV\", mediatorMass);\n }\n else if (mediatorName.EqualTo(\"zphxx_gg\")) {\n medMassForm = Form(\"#it{m_{Z'}}=%dGeV\", mediatorMass);\n }\n else if (mediatorName.EqualTo(\"zp2hdmxx_gg\")) {\n medMassForm = Form(\"#it{m_{Z'}}=%dGeV\", mediatorMass);\n }\n \n int darkMatterMass = DMAnalysis::getDarkMatterMass(config, sampleName);\n TString darkMassForm;\n if (mediatorName.EqualTo(\"shxx_gg\")) {\n darkMassForm = Form(\"#it{m_{#chi}}=%dGeV\", darkMatterMass);\n }\n else if (mediatorName.EqualTo(\"zphxx_gg\")) {\n darkMassForm = Form(\"#it{m_{#chi}}=%dGeV\", darkMatterMass);\n }\n else if (mediatorName.EqualTo(\"zp2hdmxx_gg\")) {\n darkMassForm = Form(\"#it{m_{A}}=%dGeV\", darkMatterMass);\n }\n \/\/(DMAnalysis::getPrintMediatorName(sampleName)).Data(),\n TString newName = Form(\"%s %s\", medMassForm.Data(), darkMassForm.Data());\n return newName;\n }\n else return sampleName;\n}\n\n\/**\n -----------------------------------------------------------------------------\n Get a pretty LaTex formatted name for a variable.\n @param varName - The name of the variable in the file.\n @returns - A LaTex formatted TString.\n*\/\nTString DMAnalysis::getPrintVarName(TString varName) {\n varName.ToLower();\n varName = varName.ReplaceAll(\"anacut\", \"\");\n if (varName.EqualTo(\"ptyy\") || varName.EqualTo(\"diphotonpt\")) {\n return \"p_{T}^{#gamma#gamma} [GeV]\";\n }\n else if (varName.EqualTo(\"etmiss\")) return \"#slash{E}_{T} [GeV]\";\n else if (varName.EqualTo(\"ratioetmissptyy\")) {\n return \"#slash{E}_{T}\/p_{T}^{#gamma#gamma}\";\n }\n else if (varName.EqualTo(\"myy\")) return \"M_{#gamma#gamma} [GeV]\";\n else if (varName.Contains(\"atanratio\")) {\n return \"tan^{-1}(#slash{E}_{T}\/p_{T}^{#gamma#gamma})\";\n }\n else if (varName.EqualTo(\"sumsqrtetmissptyy\")) {\n return \"#sqrt{(p_{T}^{#gamma#gamma})^{2} + (#slash{E}_{T})^{2}} [GeV]\";\n }\n else if (varName.Contains(\"dphiyyetmiss\")) {\n return \"#Delta#phi(#gamma#gamma-#slash{E}_{T})\";\n }\n else if (varName.Contains(\"njets\")) return \"N_{Jets}\";\n else if (varName.Contains(\"nleptons\")) return \"N_{Leptons}\";\n else if (varName.Contains(\"p0\")) {\n if (varName.Contains(\"exp\")) return \"p_{0} exp.\";\n else if (varName.Contains(\"obs\")) return \"p_{0} obs.\";\n else return \"p_{0}\";\n }\n else if (varName.Contains(\"cl\")) {\n if (varName.Contains(\"exp\")) return \"#it{CL} exp.\";\n else if (varName.Contains(\"obs\")) return \"#it{CL} obs.\";\n else return \"#it{CL}\";\n }\n else return varName;\n}\n\n\/**\n -----------------------------------------------------------------------------\n Convert the DM sample name into a mediator mass.\n @param modeName - the name of the DM production mode.\n @returns - the mass of the mediator particle.\n*\/\nint DMAnalysis::getMediatorMass(Config *config, TString modeName) {\n std::vector<double> massList = config->getNumV(\"DMMediatorMasses\");\n for (int i_m = (int)massList.size()-1; i_m >= 0; i_m--) {\n if (modeName.Contains(Form(\"ms%d\",((int)massList[i_m]))) || \n\tmodeName.Contains(Form(\"mzp%d\",((int)massList[i_m])))) {\n return ((int)massList[i_m]);\n }\n }\n std::cout << \"Analysis Error: no matching mediator mass \"\n\t << modeName << std::endl;\n exit(0);\n}\n\n\/**\n -----------------------------------------------------------------------------\n Convert the DM sample name into a dark matter particle mass.\n @param modeName - the name of the DM production mode.\n @returns - the mass of the DM particle.\n*\/\nint DMAnalysis::getDarkMatterMass(Config *config, TString modeName) {\n std::vector<double> massList = config->getNumV(\"DMParticleMasses\");\n for (int i_m = (int)massList.size()-1; i_m >= 0; i_m--) {\n if (modeName.Contains(Form(\"mx%d\",((int)massList[i_m]))) || \n\tmodeName.Contains(Form(\"mA%d\",((int)massList[i_m])))) {\n return ((int)massList[i_m]);\n }\n }\n std::cout << \"Analysis Error: no matching DM mass\" \n\t << modeName << std::endl;\n exit(0);\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check if the sample is among those listed as a background sample.\n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample is a background sample.\n*\/\nbool DMAnalysis::isBkgSample(Config *config, TString sampleName) {\n std::vector<TString> bkgProcesses = config->getStrV(\"BkgProcesses\");\n for (int i_bkg = 0; i_bkg < (int)bkgProcesses.size(); i_bkg++) {\n if (sampleName.EqualTo(bkgProcesses[i_bkg])) return true;\n }\n return false;\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check if the sample is among those listed as a DM signal. \n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample is a DM signal sample.\n*\/\nbool DMAnalysis::isDMSample(Config *config, TString sampleName) {\n std::vector<TString> sigDMModes = config->getStrV(\"sigDMModes\");\n for (int i_DM = 0; i_DM < (int)sigDMModes.size(); i_DM++) {\n if (sampleName.EqualTo(sigDMModes[i_DM])) return true;\n }\n return false;\n}\n\n\/** \n -----------------------------------------------------------------------------\n Check if a sample is skimmed.\n @param config - The config file for the analysis settings.\n @param fileName - The name of the file.\n @returns - True iff the sample is skimmed.\n*\/\nbool DMAnalysis::isSkimmed(Config *config, TString fileName) {\n std::vector<TString> skimmedTags = config->getStrV(\"TagSkimmed\");\n std::vector<TString> unskimmedTags = config->getStrV(\"TagUnskimmed\");\n \n for (int i_s = 0; i_s < (int)skimmedTags.size(); i_s++) {\n if (fileName.Contains(skimmedTags[i_s])) {\n std::cout << \"DMAnalysis: Sample is skimmed.\" << std::endl;\n return true;\n }\n }\n \n for (int i_u = 0; i_u < (int)unskimmedTags.size(); i_u++) {\n if (fileName.Contains(unskimmedTags[i_u])) {\n std::cout << \"DMAnalysis: Sample is unskimmed.\" << std::endl;\n return false;\n }\n }\n \n \/\/ Exit with error message if tag has not been identified:\n std::cout << \"DMAnalysis: ERROR! Unidentified tag: \" << fileName << std::endl;\n exit(0);\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check if the sample is among those listed as a SM signal. \n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample is a SM signal sample.\n*\/\nbool DMAnalysis::isSMSample(Config *config, TString sampleName) {\n std::vector<TString> sigSMModes = config->getStrV(\"sigSMModes\");\n for (int i_SM = 0; i_SM < (int)sigSMModes.size(); i_SM++) {\n if (sampleName.EqualTo(sigSMModes[i_SM])) return true;\n }\n return false;\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check if the sample is among those listed as a DM or SM signal. \n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample is a DM or SM signal sample.\n*\/\nbool DMAnalysis::isSignalSample(Config *config, TString sampleName) {\n return (isSMSample(config, sampleName) || isDMSample(config, sampleName));\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check whether a sample should be weighted.\n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample has associated event weights.\n*\/\nbool DMAnalysis::isWeightedSample(Config *config, TString sampleName) {\n \/\/ First check if it is a SM or DM signal process:\n if (isDMSample(config, sampleName) || isSMSample(config, sampleName)) {\n return true;\n }\n \n \/\/ Finally, check if it is one of the other MC processes:\n std::vector<TString> BkgProcesses = config->getStrV(\"BkgProcesses\");\n for (int i_b = 0; i_b < (int)BkgProcesses.size(); i_b++) {\n if (sampleName.EqualTo(BkgProcesses[i_b])) return true;\n }\n return false;\n}\n\n\/** \n -----------------------------------------------------------------------------\n Convert the sample name to the corresponding file list.\n @param config - The config file for the analysis settings.\n @param name - The name of the sample.\n @returns - The file list location.\n*\/\nTString DMAnalysis::nameToFileList(Config *config, TString name) {\n \/\/ Create a new file list:\n TString newListName = Form(\"%s\/FileLists\/list_%s.txt\", \n\t\t\t (config->getStr(\"masterInput\")).Data(),\n\t\t\t name.Data());\n std::ofstream newFileList(newListName);\n \n \/\/ Use a format specifier for DM samples:\n if (isDMSample(config, name)) {\n TString MxAODName = config->getStr(\"MxAODForm_DM\");\n MxAODName = MxAODName.ReplaceAll(\"NAME\",name);\n newFileList << config->getStr(\"MxAODDirectoryMC\") << \"\/\" << MxAODName \n\t\t<< std::endl;\n }\n \/\/ Use MxAOD list in the settings file for SM Higgs, backgrounds, and data:\n else {\n std::vector<TString> listMxAODs\n = config->getStrV(Form(\"MxAODList_%s\", name.Data()));\n \/\/ loop over lines in the file, each of which is one contributing MxAOD:\n for (int i_m = 0; i_m < (int)listMxAODs.size(); i_m++) {\n TString directory = listMxAODs[i_m].Contains(\"data\") ? \n\tconfig->getStr(\"MxAODDirectoryData\") : \n\tconfig->getStr(\"MxAODDirectoryMC\");\n newFileList << directory << \"\/\" << listMxAODs[i_m] << std::endl;\n }\n }\n newFileList.close();\n return newListName;\n}\n<commit_msg>DMAnalysis creates file list dir<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ Name: DMAnalysis.cxx \/\/\n\/\/ \/\/\n\/\/ Creator: Andrew Hard \/\/\n\/\/ Email: ahard@cern.ch \/\/\n\/\/ Date: 15\/04\/2015 \/\/\n\/\/ \/\/\n\/\/ This namespace stores all of the global information for the H->gg + DM \/\/\n\/\/ search with 13 TeV data in 2015. It also has all of the includes that are \/\/\n\/\/ necessary for the analysis. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"DMAnalysis.h\"\n\n\/**\n -----------------------------------------------------------------------------\n Convert the DM sample name into a process name, a subset of the full name.\n @param modeName - the name of the DM production mode.\n @param processName - the name of the process.\n*\/\nTString DMAnalysis::getMediatorName(TString modeName) {\n if (modeName.Contains(\"shxx_gg\")) return \"shxx_gg\";\n else if (modeName.Contains(\"zphxx_gg\")) return \"zphxx_gg\";\n else if (modeName.Contains(\"zp2hdmxx_gg\")) return \"zp2hdmxx_gg\";\n else {\n std::cout << \"Analysis Error: no matching mediator name: \" \n\t << modeName << std::endl;\n exit(0);\n }\n}\n\n\/**\n -----------------------------------------------------------------------------\n Convert the DM sample name into a process name, a subset of the full name.\n @param modeName - the name of the DM production mode.\n @param processName - the name of the process.\n*\/\nTString DMAnalysis::getPrintMediatorName(TString modeName) {\n if (modeName.Contains(\"shxx_gg\")) return \"Scalar\";\n else if (modeName.Contains(\"zphxx_gg\")) return \"Z'\";\n else if (modeName.Contains(\"zp2hdmxx_gg\")) return \"Z_{2HDM}'\";\n else {\n std::cout << \"Analysis Error: no matching mediator name: \" \n\t << modeName << std::endl;\n exit(0);\n }\n}\n\n\/**\n -----------------------------------------------------------------------------\n Get a pretty LaTex formatted name for a variable.\n @param sampleName - The name of the sample.\n @returns - A LaTex formatted TString.\n*\/\nTString DMAnalysis::getPrintSampleName(Config *config, TString sampleName) {\n if (sampleName.EqualTo(\"gg\")) return \"#it{#gamma#gamma}\";\n else if (sampleName.EqualTo(\"gjet\")) return \"#it{#gamma}+jet\";\n else if (sampleName.EqualTo(\"SMHiggs\")) {\n return \"SM #it{H#rightarrow#gamma#gamma}\";\n }\n else if (sampleName.EqualTo(\"yy\")) return \"#it{#gamma#gamma}\";\n else if (sampleName.EqualTo(\"yjet\")) return \"#it{#gamma}+jet\";\n else if (sampleName.EqualTo(\"jj\")) return \"di-jet\";\n else if (sampleName.EqualTo(\"Zyy\")) return \"#it{Z#gamma#gamma}\";\n else if (sampleName.EqualTo(\"Wyy\")) return \"#it{W#gamma#gamma}\";\n else if (sampleName.EqualTo(\"Zy\")) return \"#it{Z#gamma}\";\n else if (sampleName.EqualTo(\"Wy\")) return \"#it{W#gamma}\";\n else if (sampleName.EqualTo(\"ttbar\")) return \"#it{t#bar{t}}\";\n else if (sampleName.EqualTo(\"diboson\")) return \"#it{WW}+#it{WZ}+#it{ZZ}\";\n else if (sampleName.EqualTo(\"ggH\")) {\n return \"#it{ggH(#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"VBF\")) {\n return \"#it{VBF (H#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"WH\")) {\n return \"#it{WH(#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"ZH\")) {\n return \"#it{ZH(#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"bbH\")) {\n return \"#it{b#bar{b}H(#rightarrow#gamma#gamma)}\";\n }\n else if (sampleName.EqualTo(\"ttH\")) {\n return \"#it{t#bar{t}H(#rightarrow#gamma#gamma)}\";\n }\n else if (DMAnalysis::isDMSample(config, sampleName)) {\n TString mediatorName = DMAnalysis::getMediatorName(sampleName);\n int mediatorMass = DMAnalysis::getMediatorMass(config, sampleName);\n TString medMassForm;\n if (mediatorName.EqualTo(\"shxx_gg\")) {\n medMassForm = Form(\"#it{m_{S}}=%dGeV\", mediatorMass);\n }\n else if (mediatorName.EqualTo(\"zphxx_gg\")) {\n medMassForm = Form(\"#it{m_{Z'}}=%dGeV\", mediatorMass);\n }\n else if (mediatorName.EqualTo(\"zp2hdmxx_gg\")) {\n medMassForm = Form(\"#it{m_{Z'}}=%dGeV\", mediatorMass);\n }\n \n int darkMatterMass = DMAnalysis::getDarkMatterMass(config, sampleName);\n TString darkMassForm;\n if (mediatorName.EqualTo(\"shxx_gg\")) {\n darkMassForm = Form(\"#it{m_{#chi}}=%dGeV\", darkMatterMass);\n }\n else if (mediatorName.EqualTo(\"zphxx_gg\")) {\n darkMassForm = Form(\"#it{m_{#chi}}=%dGeV\", darkMatterMass);\n }\n else if (mediatorName.EqualTo(\"zp2hdmxx_gg\")) {\n darkMassForm = Form(\"#it{m_{A}}=%dGeV\", darkMatterMass);\n }\n \/\/(DMAnalysis::getPrintMediatorName(sampleName)).Data(),\n TString newName = Form(\"%s %s\", medMassForm.Data(), darkMassForm.Data());\n return newName;\n }\n else return sampleName;\n}\n\n\/**\n -----------------------------------------------------------------------------\n Get a pretty LaTex formatted name for a variable.\n @param varName - The name of the variable in the file.\n @returns - A LaTex formatted TString.\n*\/\nTString DMAnalysis::getPrintVarName(TString varName) {\n varName.ToLower();\n varName = varName.ReplaceAll(\"anacut\", \"\");\n if (varName.EqualTo(\"ptyy\") || varName.EqualTo(\"diphotonpt\")) {\n return \"p_{T}^{#gamma#gamma} [GeV]\";\n }\n else if (varName.EqualTo(\"etmiss\")) return \"#slash{E}_{T} [GeV]\";\n else if (varName.EqualTo(\"ratioetmissptyy\")) {\n return \"#slash{E}_{T}\/p_{T}^{#gamma#gamma}\";\n }\n else if (varName.EqualTo(\"myy\")) return \"M_{#gamma#gamma} [GeV]\";\n else if (varName.Contains(\"atanratio\")) {\n return \"tan^{-1}(#slash{E}_{T}\/p_{T}^{#gamma#gamma})\";\n }\n else if (varName.EqualTo(\"sumsqrtetmissptyy\")) {\n return \"#sqrt{(p_{T}^{#gamma#gamma})^{2} + (#slash{E}_{T})^{2}} [GeV]\";\n }\n else if (varName.Contains(\"dphiyyetmiss\")) {\n return \"#Delta#phi(#gamma#gamma-#slash{E}_{T})\";\n }\n else if (varName.Contains(\"njets\")) return \"N_{Jets}\";\n else if (varName.Contains(\"nleptons\")) return \"N_{Leptons}\";\n else if (varName.Contains(\"p0\")) {\n if (varName.Contains(\"exp\")) return \"p_{0} exp.\";\n else if (varName.Contains(\"obs\")) return \"p_{0} obs.\";\n else return \"p_{0}\";\n }\n else if (varName.Contains(\"cl\")) {\n if (varName.Contains(\"exp\")) return \"#it{CL} exp.\";\n else if (varName.Contains(\"obs\")) return \"#it{CL} obs.\";\n else return \"#it{CL}\";\n }\n else return varName;\n}\n\n\/**\n -----------------------------------------------------------------------------\n Convert the DM sample name into a mediator mass.\n @param modeName - the name of the DM production mode.\n @returns - the mass of the mediator particle.\n*\/\nint DMAnalysis::getMediatorMass(Config *config, TString modeName) {\n std::vector<double> massList = config->getNumV(\"DMMediatorMasses\");\n for (int i_m = (int)massList.size()-1; i_m >= 0; i_m--) {\n if (modeName.Contains(Form(\"ms%d\",((int)massList[i_m]))) || \n\tmodeName.Contains(Form(\"mzp%d\",((int)massList[i_m])))) {\n return ((int)massList[i_m]);\n }\n }\n std::cout << \"Analysis Error: no matching mediator mass \"\n\t << modeName << std::endl;\n exit(0);\n}\n\n\/**\n -----------------------------------------------------------------------------\n Convert the DM sample name into a dark matter particle mass.\n @param modeName - the name of the DM production mode.\n @returns - the mass of the DM particle.\n*\/\nint DMAnalysis::getDarkMatterMass(Config *config, TString modeName) {\n std::vector<double> massList = config->getNumV(\"DMParticleMasses\");\n for (int i_m = (int)massList.size()-1; i_m >= 0; i_m--) {\n if (modeName.Contains(Form(\"mx%d\",((int)massList[i_m]))) || \n\tmodeName.Contains(Form(\"mA%d\",((int)massList[i_m])))) {\n return ((int)massList[i_m]);\n }\n }\n std::cout << \"Analysis Error: no matching DM mass\" \n\t << modeName << std::endl;\n exit(0);\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check if the sample is among those listed as a background sample.\n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample is a background sample.\n*\/\nbool DMAnalysis::isBkgSample(Config *config, TString sampleName) {\n std::vector<TString> bkgProcesses = config->getStrV(\"BkgProcesses\");\n for (int i_bkg = 0; i_bkg < (int)bkgProcesses.size(); i_bkg++) {\n if (sampleName.EqualTo(bkgProcesses[i_bkg])) return true;\n }\n return false;\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check if the sample is among those listed as a DM signal. \n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample is a DM signal sample.\n*\/\nbool DMAnalysis::isDMSample(Config *config, TString sampleName) {\n std::vector<TString> sigDMModes = config->getStrV(\"sigDMModes\");\n for (int i_DM = 0; i_DM < (int)sigDMModes.size(); i_DM++) {\n if (sampleName.EqualTo(sigDMModes[i_DM])) return true;\n }\n return false;\n}\n\n\/** \n -----------------------------------------------------------------------------\n Check if a sample is skimmed.\n @param config - The config file for the analysis settings.\n @param fileName - The name of the file.\n @returns - True iff the sample is skimmed.\n*\/\nbool DMAnalysis::isSkimmed(Config *config, TString fileName) {\n std::vector<TString> skimmedTags = config->getStrV(\"TagSkimmed\");\n std::vector<TString> unskimmedTags = config->getStrV(\"TagUnskimmed\");\n \n for (int i_s = 0; i_s < (int)skimmedTags.size(); i_s++) {\n if (fileName.Contains(skimmedTags[i_s])) {\n std::cout << \"DMAnalysis: Sample is skimmed.\" << std::endl;\n return true;\n }\n }\n \n for (int i_u = 0; i_u < (int)unskimmedTags.size(); i_u++) {\n if (fileName.Contains(unskimmedTags[i_u])) {\n std::cout << \"DMAnalysis: Sample is unskimmed.\" << std::endl;\n return false;\n }\n }\n \n \/\/ Exit with error message if tag has not been identified:\n std::cout << \"DMAnalysis: ERROR! Unidentified tag: \" << fileName << std::endl;\n exit(0);\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check if the sample is among those listed as a SM signal. \n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample is a SM signal sample.\n*\/\nbool DMAnalysis::isSMSample(Config *config, TString sampleName) {\n std::vector<TString> sigSMModes = config->getStrV(\"sigSMModes\");\n for (int i_SM = 0; i_SM < (int)sigSMModes.size(); i_SM++) {\n if (sampleName.EqualTo(sigSMModes[i_SM])) return true;\n }\n return false;\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check if the sample is among those listed as a DM or SM signal. \n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample is a DM or SM signal sample.\n*\/\nbool DMAnalysis::isSignalSample(Config *config, TString sampleName) {\n return (isSMSample(config, sampleName) || isDMSample(config, sampleName));\n}\n\n\/**\n -----------------------------------------------------------------------------\n Check whether a sample should be weighted.\n @param config - The config file for the analysis settings.\n @param sampleName - The name of the sample being used.\n @returns - True iff the sample has associated event weights.\n*\/\nbool DMAnalysis::isWeightedSample(Config *config, TString sampleName) {\n \/\/ First check if it is a SM or DM signal process:\n if (isDMSample(config, sampleName) || isSMSample(config, sampleName)) {\n return true;\n }\n \n \/\/ Finally, check if it is one of the other MC processes:\n std::vector<TString> BkgProcesses = config->getStrV(\"BkgProcesses\");\n for (int i_b = 0; i_b < (int)BkgProcesses.size(); i_b++) {\n if (sampleName.EqualTo(BkgProcesses[i_b])) return true;\n }\n return false;\n}\n\n\/** \n -----------------------------------------------------------------------------\n Convert the sample name to the corresponding file list.\n @param config - The config file for the analysis settings.\n @param name - The name of the sample.\n @returns - The file list location.\n*\/\nTString DMAnalysis::nameToFileList(Config *config, TString name) {\n \/\/ Check that directory exists for file lists:\n system(Form(\"mkdir -vp %s\/FileLists\",(config->getStr(\"masterInput\")).Data()));\n \/\/ Create a new file list:\n TString newListName = Form(\"%s\/FileLists\/list_%s.txt\", \n\t\t\t (config->getStr(\"masterInput\")).Data(),\n\t\t\t name.Data());\n std::ofstream newFileList(newListName);\n \n \/\/ Use a format specifier for DM samples:\n if (isDMSample(config, name)) {\n TString MxAODName = config->getStr(\"MxAODForm_DM\");\n MxAODName = MxAODName.ReplaceAll(\"NAME\",name);\n newFileList << config->getStr(\"MxAODDirectoryMC\") << \"\/\" << MxAODName \n\t\t<< std::endl;\n }\n \/\/ Use MxAOD list in the settings file for SM Higgs, backgrounds, and data:\n else {\n std::vector<TString> listMxAODs\n = config->getStrV(Form(\"MxAODList_%s\", name.Data()));\n \/\/ loop over lines in the file, each of which is one contributing MxAOD:\n for (int i_m = 0; i_m < (int)listMxAODs.size(); i_m++) {\n TString directory = listMxAODs[i_m].Contains(\"data\") ? \n\tconfig->getStr(\"MxAODDirectoryData\") : \n\tconfig->getStr(\"MxAODDirectoryMC\");\n newFileList << directory << \"\/\" << listMxAODs[i_m] << std::endl;\n }\n }\n newFileList.close();\n return newListName;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pch.h\"\r\n#include \"DspLimiter.h\"\r\n\r\nnamespace SaneAudioRenderer\r\n{\r\n namespace\r\n {\r\n const float slope = 1.0f - 1.0f \/ 20.0f; \/\/ 20:1 ratio\r\n\r\n template <typename T>\r\n T GetPeak(const T* data, size_t n)\r\n {\r\n T peak = 0;\r\n\r\n for (size_t i = 0; i < n; i++)\r\n peak = std::max(peak, std::abs(data[i]));\r\n\r\n return peak;\r\n }\r\n\r\n template <typename T>\r\n void ApplyLimiter(T* data, size_t n, T threshold)\r\n {\r\n for (size_t i = 0; i < n; i++)\r\n {\r\n T& sample = data[i];\r\n const T absSample = std::abs(sample);\r\n\r\n if (absSample > threshold)\r\n sample *= std::pow(threshold \/ absSample, slope);\r\n\r\n assert(std::abs(sample) <= 1);\r\n }\r\n }\r\n }\r\n\r\n void DspLimiter::Initialize(uint32_t rate, uint32_t channels, bool exclusive)\r\n {\r\n m_exclusive = exclusive;\r\n m_rate = rate;\r\n m_channels = channels;\r\n\r\n m_active = false;\r\n m_holdWindow = 0;\r\n m_peak = 0.0f;\r\n m_threshold = 0.0f;\r\n }\r\n\r\n bool DspLimiter::Active()\r\n {\r\n return m_active;\r\n }\r\n\r\n void DspLimiter::Process(DspChunk& chunk)\r\n {\r\n if (chunk.IsEmpty())\r\n return;\r\n\r\n if (!m_exclusive || (chunk.GetFormat() != DspFormat::Float &&\r\n chunk.GetFormat() != DspFormat::Double))\r\n {\r\n m_active = false;\r\n return;\r\n }\r\n\r\n m_active = true;\r\n\r\n \/\/ Analyze samples\r\n float peak;\r\n if (chunk.GetFormat() == DspFormat::Double)\r\n {\r\n double largePeak = GetPeak((double*)chunk.GetData(), chunk.GetSampleCount());\r\n peak = std::nexttoward((float)largePeak, largePeak);\r\n }\r\n else\r\n {\r\n assert(chunk.GetFormat() == DspFormat::Float);\r\n peak = GetPeak((float*)chunk.GetData(), chunk.GetSampleCount());\r\n }\r\n\r\n \/\/ Configure limiter\r\n if (peak > 1.0f)\r\n {\r\n if (m_holdWindow <= 0)\r\n {\r\n NewTreshold(std::max(peak, 1.4f));\r\n }\r\n else if (peak > m_peak)\r\n {\r\n NewTreshold(peak);\r\n }\r\n\r\n m_holdWindow = m_rate * m_channels * 10; \/\/ 10 seconds\r\n }\r\n\r\n \/\/ Apply limiter\r\n if (m_holdWindow > 0)\r\n {\r\n if (chunk.GetFormat() == DspFormat::Double)\r\n {\r\n ApplyLimiter<double>((double*)chunk.GetData(), chunk.GetSampleCount(), m_threshold);\r\n }\r\n else\r\n {\r\n assert(chunk.GetFormat() == DspFormat::Float);\r\n ApplyLimiter((float*)chunk.GetData(), chunk.GetSampleCount(), m_threshold);\r\n }\r\n\r\n m_holdWindow -= chunk.GetSampleCount();\r\n }\r\n }\r\n\r\n void DspLimiter::Finish(DspChunk& chunk)\r\n {\r\n Process(chunk);\r\n }\r\n\r\n void DspLimiter::NewTreshold(float peak)\r\n {\r\n m_peak = peak;\r\n m_threshold = std::pow(1.0f \/ peak, 1.0f \/ slope - 1.0f) - 0.0001f;\r\n DebugOut(\"DspLimiter active with\", m_peak, \"peak and\", m_threshold, \"threshold\");\r\n }\r\n}\r\n<commit_msg>Fix coverity scan warning<commit_after>#include \"pch.h\"\r\n#include \"DspLimiter.h\"\r\n\r\nnamespace SaneAudioRenderer\r\n{\r\n namespace\r\n {\r\n const float slope = 1.0f - 1.0f \/ 20.0f; \/\/ 20:1 ratio\r\n\r\n template <typename T>\r\n T GetPeak(const T* data, size_t n)\r\n {\r\n T peak = 0;\r\n\r\n for (size_t i = 0; i < n; i++)\r\n peak = std::max(peak, std::abs(data[i]));\r\n\r\n return peak;\r\n }\r\n\r\n template <typename T>\r\n void ApplyLimiter(T* data, size_t n, T threshold)\r\n {\r\n for (size_t i = 0; i < n; i++)\r\n {\r\n T& sample = data[i];\r\n const T absSample = std::abs(sample);\r\n\r\n if (absSample > threshold)\r\n sample *= std::pow(threshold \/ absSample, slope);\r\n\r\n assert(std::abs(sample) <= 1);\r\n }\r\n }\r\n }\r\n\r\n void DspLimiter::Initialize(uint32_t rate, uint32_t channels, bool exclusive)\r\n {\r\n m_exclusive = exclusive;\r\n m_rate = rate;\r\n m_channels = channels;\r\n\r\n m_active = false;\r\n m_holdWindow = 0;\r\n m_peak = 0.0f;\r\n m_threshold = 0.0f;\r\n }\r\n\r\n bool DspLimiter::Active()\r\n {\r\n return m_active;\r\n }\r\n\r\n void DspLimiter::Process(DspChunk& chunk)\r\n {\r\n if (chunk.IsEmpty())\r\n return;\r\n\r\n if (!m_exclusive || (chunk.GetFormat() != DspFormat::Float &&\r\n chunk.GetFormat() != DspFormat::Double))\r\n {\r\n m_active = false;\r\n return;\r\n }\r\n\r\n m_active = true;\r\n\r\n \/\/ Analyze samples\r\n float peak;\r\n if (chunk.GetFormat() == DspFormat::Double)\r\n {\r\n double largePeak = GetPeak((double*)chunk.GetData(), chunk.GetSampleCount());\r\n peak = std::nexttoward((float)largePeak, largePeak);\r\n }\r\n else\r\n {\r\n assert(chunk.GetFormat() == DspFormat::Float);\r\n peak = GetPeak((float*)chunk.GetData(), chunk.GetSampleCount());\r\n }\r\n\r\n \/\/ Configure limiter\r\n if (peak > 1.0f)\r\n {\r\n if (m_holdWindow <= 0)\r\n {\r\n NewTreshold(std::max(peak, 1.4f));\r\n }\r\n else if (peak > m_peak)\r\n {\r\n NewTreshold(peak);\r\n }\r\n\r\n m_holdWindow = (int64_t)m_rate * m_channels * 10; \/\/ 10 seconds\r\n }\r\n\r\n \/\/ Apply limiter\r\n if (m_holdWindow > 0)\r\n {\r\n if (chunk.GetFormat() == DspFormat::Double)\r\n {\r\n ApplyLimiter<double>((double*)chunk.GetData(), chunk.GetSampleCount(), m_threshold);\r\n }\r\n else\r\n {\r\n assert(chunk.GetFormat() == DspFormat::Float);\r\n ApplyLimiter((float*)chunk.GetData(), chunk.GetSampleCount(), m_threshold);\r\n }\r\n\r\n m_holdWindow -= chunk.GetSampleCount();\r\n }\r\n }\r\n\r\n void DspLimiter::Finish(DspChunk& chunk)\r\n {\r\n Process(chunk);\r\n }\r\n\r\n void DspLimiter::NewTreshold(float peak)\r\n {\r\n m_peak = peak;\r\n m_threshold = std::pow(1.0f \/ peak, 1.0f \/ slope - 1.0f) - 0.0001f;\r\n DebugOut(\"DspLimiter active with\", m_peak, \"peak and\", m_threshold, \"threshold\");\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"Game\/Clock.h\"\n\n#include <array>\n#include <chrono>\nusing namespace std::chrono_literals;\n#include <cassert>\n#include <limits>\n\n#include \"Game\/Board.h\"\n#include \"Game\/Game_Result.h\"\n\nClock::Clock(seconds duration_seconds,\n size_t moves_to_reset,\n seconds increment_seconds,\n Time_Reset_Method reset_method,\n Piece_Color starting_turn,\n std::chrono::system_clock::time_point previous_start_time) noexcept :\n timers({duration_seconds, duration_seconds}),\n initial_start_time(duration_seconds),\n increment_time({increment_seconds, increment_seconds}),\n move_count_reset(moves_to_reset),\n method_of_reset(reset_method),\n whose_turn(starting_turn),\n game_start_date_time(previous_start_time)\n{\n}\n\nGame_Result Clock::punch(const Board& board) noexcept\n{\n assert(clocks_running);\n\n if( ! is_in_use())\n {\n return {};\n }\n\n auto time_this_punch = std::chrono::steady_clock::now();\n\n auto player_index = static_cast<unsigned>(whose_turn);\n timers[player_index] -= (time_this_punch - time_previous_punch);\n\n if(++moves_to_reset_clocks[player_index] == move_count_reset)\n {\n if(method_of_reset == Time_Reset_Method::ADDITION)\n {\n timers[player_index] += initial_start_time;\n }\n else\n {\n timers[player_index] = initial_start_time;\n }\n moves_to_reset_clocks[player_index] = 0;\n }\n\n time_previous_punch = time_this_punch;\n timers[player_index] += increment_time[player_index];\n\n whose_turn = opposite(whose_turn);\n\n if(time_left(opposite(whose_turn)) < 0s)\n {\n if(board.enough_material_to_checkmate(whose_turn))\n {\n return Game_Result(whose_turn, Game_Result_Type::TIME_FORFEIT);\n }\n else\n {\n return Game_Result(Winner_Color::NONE, Game_Result_Type::TIME_EXPIRED_WITH_INSUFFICIENT_MATERIAL);\n }\n }\n else\n {\n return {};\n }\n}\n\nvoid Clock::unpunch() noexcept\n{\n moves_to_reset_clocks[static_cast<unsigned>(whose_turn)] -= 1;\n moves_to_reset_clocks[static_cast<unsigned>(opposite(whose_turn))] -= 1;\n punch({});\n}\n\nvoid Clock::stop() noexcept\n{\n auto time_stop = std::chrono::steady_clock::now();\n timers[static_cast<unsigned>(whose_turn)] -= (time_stop - time_previous_punch);\n clocks_running = false;\n}\n\nvoid Clock::start() noexcept\n{\n static const auto default_game_start_date_time = std::chrono::system_clock::time_point{};\n time_previous_punch = std::chrono::steady_clock::now();\n if(game_start_date_time == default_game_start_date_time)\n {\n game_start_date_time = std::chrono::system_clock::now();\n }\n clocks_running = true;\n}\n\nClock::seconds Clock::time_left(Piece_Color color) const noexcept\n{\n if( ! is_in_use())\n {\n return 0s;\n }\n\n if(whose_turn != color || ! clocks_running)\n {\n return timers[static_cast<unsigned>(color)];\n }\n else\n {\n auto now = std::chrono::steady_clock::now();\n return timers[static_cast<unsigned>(color)] - (now - time_previous_punch);\n }\n}\n\nsize_t Clock::moves_until_reset(Piece_Color color) const noexcept\n{\n if(move_count_reset > 0)\n {\n return move_count_reset - moves_to_reset_clocks[static_cast<unsigned>(color)];\n }\n else\n {\n return std::numeric_limits<int>::max();\n }\n}\n\nPiece_Color Clock::running_for() const noexcept\n{\n return whose_turn;\n}\n\nvoid Clock::set_time(Piece_Color player, seconds new_time_seconds) noexcept\n{\n timers[static_cast<unsigned>(player)] = new_time_seconds;\n\n \/\/ This function is called by GUI mediators, so the actual\n \/\/ start time will be during one of the first two calls\n \/\/ (first if the local player is white, second if black).\n if(++initial_time_set_count <= 2)\n {\n initial_start_time = std::max(new_time_seconds, initial_start_time);\n }\n time_previous_punch = std::chrono::steady_clock::now();\n}\n\nvoid Clock::set_increment(Piece_Color player, seconds new_increment_time_seconds) noexcept\n{\n increment_time[static_cast<unsigned>(player)] = new_increment_time_seconds;\n}\n\nvoid Clock::set_next_time_reset(size_t moves_to_reset) noexcept\n{\n if(moves_to_reset == 0)\n {\n move_count_reset = 0;\n }\n else\n {\n move_count_reset = moves_to_reset_clocks[static_cast<unsigned>(running_for())] + moves_to_reset;\n }\n}\n\nvoid Clock::set_reset_method(Time_Reset_Method method) noexcept\n{\n method_of_reset = method;\n}\n\nClock::seconds Clock::running_time_left() const noexcept\n{\n return time_left(running_for());\n}\n\nbool Clock::is_running() const noexcept\n{\n return clocks_running;\n}\n\nstd::chrono::system_clock::time_point Clock::game_start_date_and_time() const noexcept\n{\n return game_start_date_time;\n}\n\nsize_t Clock::moves_per_time_period() const noexcept\n{\n return move_count_reset;\n}\n\nTime_Reset_Method Clock::reset_mode() const noexcept\n{\n return method_of_reset;\n}\n\nClock::seconds Clock::initial_time() const noexcept\n{\n return initial_start_time;\n}\n\nClock::seconds Clock::increment(Piece_Color color) const noexcept\n{\n return increment_time[static_cast<unsigned>(color)];\n}\n\nbool Clock::is_in_use() const noexcept\n{\n return initial_start_time > 0s;\n}\n<commit_msg>Time only added to clock if time left after move<commit_after>#include \"Game\/Clock.h\"\n\n#include <array>\n#include <chrono>\nusing namespace std::chrono_literals;\n#include <cassert>\n#include <limits>\n\n#include \"Game\/Board.h\"\n#include \"Game\/Game_Result.h\"\n\nClock::Clock(seconds duration_seconds,\n size_t moves_to_reset,\n seconds increment_seconds,\n Time_Reset_Method reset_method,\n Piece_Color starting_turn,\n std::chrono::system_clock::time_point previous_start_time) noexcept :\n timers({duration_seconds, duration_seconds}),\n initial_start_time(duration_seconds),\n increment_time({increment_seconds, increment_seconds}),\n move_count_reset(moves_to_reset),\n method_of_reset(reset_method),\n whose_turn(starting_turn),\n game_start_date_time(previous_start_time)\n{\n}\n\nGame_Result Clock::punch(const Board& board) noexcept\n{\n assert(clocks_running);\n\n if( ! is_in_use())\n {\n return {};\n }\n\n auto time_this_punch = std::chrono::steady_clock::now();\n\n auto player_index = static_cast<unsigned>(whose_turn);\n timers[player_index] -= (time_this_punch - time_previous_punch);\n time_previous_punch = time_this_punch;\n whose_turn = opposite(whose_turn);\n\n if(time_left(opposite(whose_turn)) < 0s)\n {\n if(board.enough_material_to_checkmate(whose_turn))\n {\n return Game_Result(whose_turn, Game_Result_Type::TIME_FORFEIT);\n }\n else\n {\n return Game_Result(Winner_Color::NONE, Game_Result_Type::TIME_EXPIRED_WITH_INSUFFICIENT_MATERIAL);\n }\n }\n else\n {\n if(++moves_to_reset_clocks[player_index] == move_count_reset)\n {\n if(method_of_reset == Time_Reset_Method::ADDITION)\n {\n timers[player_index] += initial_start_time;\n }\n else\n {\n timers[player_index] = initial_start_time;\n }\n moves_to_reset_clocks[player_index] = 0;\n }\n timers[player_index] += increment_time[player_index];\n\n return {};\n }\n}\n\nvoid Clock::unpunch() noexcept\n{\n moves_to_reset_clocks[static_cast<unsigned>(whose_turn)] -= 1;\n moves_to_reset_clocks[static_cast<unsigned>(opposite(whose_turn))] -= 1;\n punch({});\n}\n\nvoid Clock::stop() noexcept\n{\n auto time_stop = std::chrono::steady_clock::now();\n timers[static_cast<unsigned>(whose_turn)] -= (time_stop - time_previous_punch);\n clocks_running = false;\n}\n\nvoid Clock::start() noexcept\n{\n static const auto default_game_start_date_time = std::chrono::system_clock::time_point{};\n time_previous_punch = std::chrono::steady_clock::now();\n if(game_start_date_time == default_game_start_date_time)\n {\n game_start_date_time = std::chrono::system_clock::now();\n }\n clocks_running = true;\n}\n\nClock::seconds Clock::time_left(Piece_Color color) const noexcept\n{\n if( ! is_in_use())\n {\n return 0s;\n }\n\n if(whose_turn != color || ! clocks_running)\n {\n return timers[static_cast<unsigned>(color)];\n }\n else\n {\n auto now = std::chrono::steady_clock::now();\n return timers[static_cast<unsigned>(color)] - (now - time_previous_punch);\n }\n}\n\nsize_t Clock::moves_until_reset(Piece_Color color) const noexcept\n{\n if(move_count_reset > 0)\n {\n return move_count_reset - moves_to_reset_clocks[static_cast<unsigned>(color)];\n }\n else\n {\n return std::numeric_limits<int>::max();\n }\n}\n\nPiece_Color Clock::running_for() const noexcept\n{\n return whose_turn;\n}\n\nvoid Clock::set_time(Piece_Color player, seconds new_time_seconds) noexcept\n{\n timers[static_cast<unsigned>(player)] = new_time_seconds;\n\n \/\/ This function is called by GUI mediators, so the actual\n \/\/ start time will be during one of the first two calls\n \/\/ (first if the local player is white, second if black).\n if(++initial_time_set_count <= 2)\n {\n initial_start_time = std::max(new_time_seconds, initial_start_time);\n }\n time_previous_punch = std::chrono::steady_clock::now();\n}\n\nvoid Clock::set_increment(Piece_Color player, seconds new_increment_time_seconds) noexcept\n{\n increment_time[static_cast<unsigned>(player)] = new_increment_time_seconds;\n}\n\nvoid Clock::set_next_time_reset(size_t moves_to_reset) noexcept\n{\n if(moves_to_reset == 0)\n {\n move_count_reset = 0;\n }\n else\n {\n move_count_reset = moves_to_reset_clocks[static_cast<unsigned>(running_for())] + moves_to_reset;\n }\n}\n\nvoid Clock::set_reset_method(Time_Reset_Method method) noexcept\n{\n method_of_reset = method;\n}\n\nClock::seconds Clock::running_time_left() const noexcept\n{\n return time_left(running_for());\n}\n\nbool Clock::is_running() const noexcept\n{\n return clocks_running;\n}\n\nstd::chrono::system_clock::time_point Clock::game_start_date_and_time() const noexcept\n{\n return game_start_date_time;\n}\n\nsize_t Clock::moves_per_time_period() const noexcept\n{\n return move_count_reset;\n}\n\nTime_Reset_Method Clock::reset_mode() const noexcept\n{\n return method_of_reset;\n}\n\nClock::seconds Clock::initial_time() const noexcept\n{\n return initial_start_time;\n}\n\nClock::seconds Clock::increment(Piece_Color color) const noexcept\n{\n return increment_time[static_cast<unsigned>(color)];\n}\n\nbool Clock::is_in_use() const noexcept\n{\n return initial_start_time > 0s;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * IpcChannel.cpp\n *\n * Created on: Feb 6, 2015\n * Author: Tim Nicholls, STFC Application Engineering\n *\/\n\n#include \"IpcChannel.h\"\n\nusing namespace FrameReceiver;\n\nIpcContext& IpcContext::Instance(void)\n{\n static IpcContext ipcContext;\n return ipcContext;\n}\n\nzmq::context_t& IpcContext::get(void)\n{\n return zmq_context_;\n}\n\nIpcContext::IpcContext(int io_threads) :\n zmq_context_(io_threads)\n{\n \/\/ std::cout << \"IpcContext constructor\" << std::endl;\n}\n\nIpcChannel::IpcChannel(int type) :\n context_(IpcContext::Instance()),\n socket_(context_.get(), type)\n{\n \/\/std::cout << \"IpcChannel constructor\" << std::endl;\n}\n\nIpcChannel::~IpcChannel()\n{\n \/\/td::cout << \"IpcChannel destructor\" << std::endl;\n}\n\nvoid IpcChannel::bind(const char* endpoint)\n{\n socket_.bind(endpoint);\n}\n\nvoid IpcChannel::bind(std::string& endpoint)\n{\n this->bind(endpoint.c_str());\n}\n\nvoid IpcChannel::connect(const char* endpoint)\n{\n socket_.connect(endpoint);\n}\n\nvoid IpcChannel::connect(std::string& endpoint)\n{\n this->connect(endpoint.c_str());\n}\n\nvoid IpcChannel::send(std::string& message_str)\n{\n size_t msg_size = message_str.size() + 1;\n zmq::message_t msg(msg_size);\n memcpy(msg.data(), message_str.data(), msg_size);\n socket_.send(msg);\n}\n\nvoid IpcChannel::send(const char* message)\n{\n size_t msg_size = strlen(message) + 1;\n zmq::message_t msg(msg_size);\n memcpy(msg.data(), message, msg_size);\n socket_.send(msg);\n\n}\n\nstd::string IpcChannel::recv(void)\n{\n zmq::message_t msg;\n socket_.recv(&msg);\n\n return std::string(reinterpret_cast<const char*>(msg.data()));\n}\n\nbool IpcChannel::poll(long timeout_ms)\n{\n zmq::pollitem_t pollitems[] = {{socket_, 0, ZMQ_POLLIN, 0}};\n\n zmq::poll(pollitems, 1, timeout_ms);\n\n return (pollitems[0].revents & ZMQ_POLLIN);\n\n}\n\n<commit_msg>Fixed recv() method to convert message to string of appropriate size<commit_after>\/*!\n * IpcChannel.cpp\n *\n * Created on: Feb 6, 2015\n * Author: Tim Nicholls, STFC Application Engineering\n *\/\n\n#include \"IpcChannel.h\"\n\nusing namespace FrameReceiver;\n\nIpcContext& IpcContext::Instance(void)\n{\n static IpcContext ipcContext;\n return ipcContext;\n}\n\nzmq::context_t& IpcContext::get(void)\n{\n return zmq_context_;\n}\n\nIpcContext::IpcContext(int io_threads) :\n zmq_context_(io_threads)\n{\n \/\/ std::cout << \"IpcContext constructor\" << std::endl;\n}\n\nIpcChannel::IpcChannel(int type) :\n context_(IpcContext::Instance()),\n socket_(context_.get(), type)\n{\n \/\/std::cout << \"IpcChannel constructor\" << std::endl;\n}\n\nIpcChannel::~IpcChannel()\n{\n \/\/td::cout << \"IpcChannel destructor\" << std::endl;\n}\n\nvoid IpcChannel::bind(const char* endpoint)\n{\n socket_.bind(endpoint);\n}\n\nvoid IpcChannel::bind(std::string& endpoint)\n{\n this->bind(endpoint.c_str());\n}\n\nvoid IpcChannel::connect(const char* endpoint)\n{\n socket_.connect(endpoint);\n}\n\nvoid IpcChannel::connect(std::string& endpoint)\n{\n this->connect(endpoint.c_str());\n}\n\nvoid IpcChannel::send(std::string& message_str)\n{\n size_t msg_size = message_str.size() + 1;\n zmq::message_t msg(msg_size);\n memcpy(msg.data(), message_str.data(), msg_size);\n socket_.send(msg);\n}\n\nvoid IpcChannel::send(const char* message)\n{\n size_t msg_size = strlen(message) + 1;\n zmq::message_t msg(msg_size);\n memcpy(msg.data(), message, msg_size);\n socket_.send(msg);\n\n}\n\nstd::string IpcChannel::recv(void)\n{\n zmq::message_t msg;\n socket_.recv(&msg);\n\n return std::string(reinterpret_cast<const char*>(msg.data()), msg.size());\n}\n\nbool IpcChannel::poll(long timeout_ms)\n{\n zmq::pollitem_t pollitems[] = {{socket_, 0, ZMQ_POLLIN, 0}};\n\n zmq::poll(pollitems, 1, timeout_ms);\n\n return (pollitems[0].revents & ZMQ_POLLIN);\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"MapManager.hpp\"\n\n#include <cstring>\n#include <cstdio>\n\nMapManager::MapManager(void) {\n unsigned int i, j;\n numLandmarks = 0;\n head = tail = NULL;\n for (i = 0; i < MAX_LMARKS; ++i)\n for (j = 0; j < MAX_LMARKS; ++j)\n weight[i][j] = 0;\n}\n\nMapManager::~MapManager(void) {\n destroyLandmarkList();\n}\n\nvoid MapManager::destroyLandmarkList(void) {\n landmarkStructType *x, *y = head;\n while (y != NULL) {\n x = y;\n y = y->next;\n delete x;\n }\n}\n\nint MapManager::insertLandmark(int index, char *name) {\n landmarkStructType *temp;\n\n \/\/ Is the name too long?\n if (strlen(name) > MAX_LMARK_NAME)\n return NAME_TOO_LONG;\n\n \/\/ Is the name repeated?\n for (temp = head; temp != NULL; temp = temp->next)\n if (strcmp(temp->name, name) == 0)\n return NAME_REPEATED;\n\n \/\/ Create a new index.\n temp = new landmarkStructType;\n temp->index = index;\n strcpy(temp->name, name);\n temp->next = NULL; \/\/ Always insert new nodes at the end.\n\n \/\/ Check if the linked list is empty.\n if (head == NULL) {\n \/\/ Linked list is empty.\n temp->prev = NULL;\n head = temp;\n tail = temp;\n } else {\n \/\/ No, insert new node at the tail.\n tail->next = temp;\n temp->prev = tail;\n tail = temp;\n }\n return SUCCESS;\n}\n\nchar *MapManager::getLandmarkName(unsigned int index) {\n landmarkStructType *x;\n\n if ((index > numLandmarks) || (index < 0))\n return NULL;\n\n for (x = head; x != NULL; x = x->next)\n if (x->index == index)\n return x->name;\n\n return NULL; \/\/ Not found. something is wrong.\n}\n\nint MapManager::getLandmarkIndex(char *name) {\n landmarkStructType *x;\n if (strlen(name) > MAX_LMARK_NAME)\n return -1;\n\n for (x = head; x != NULL; x = x->next)\n if (strcmp(x->name, name) == 0)\n return x->index;\n\n return LMARK_UNDEFINED; \/\/ Not found. something is wrong.\n}\n\nint MapManager::readInputFile(char *fname) {\n FILE *f = NULL;\n char temp, name[MAX_LMARK_NAME];\n unsigned int i, j;\n\n if ((f = fopen(fname, \"r\")) == NULL) {\n cerr << \"Could not open input file '\" << fname << \"'...\" << endl;\n return FAILED_TO_OPEN_FILE;\n }\n\n \/\/ Read in the landmark list.\n fscanf(f, \"%d\", &numLandmarks);\n if ((numLandmarks <= 0) || (numLandmarks > MAX_LMARKS)) {\n cout << \"Invalid number of landmarks: \" << numLandmarks << endl;\n return INVALID_NUM_LMARKS;\n }\n\n \/\/ Read in the landmark names.\n for (i = 0; i < numLandmarks; ++i) {\n \/\/ Ignore all preceding blank spaces.\n do {\n fscanf(f, \"%c\", &temp);\n } while (isspace(temp));\n\n \/\/ Start taking in the name.\n for (j = 0; j < MAX_LMARK_NAME; ++j) {\n fscanf(f, \"%c\", &name[j]);\n if (name[j] == '\"') {\n name[j] = '\\0'; \/\/ End of name.\n break;\n }\n }\n\n \/\/ Insert a new node.\n if (insertLandmark(i, name) == NAME_REPEATED) {\n destroyLandmarkList();\n return NAME_REPEATED;\n }\n }\n\n \/\/ Read in the adjacency matrix giving the inter-landmark weights.\n for (i = 0; i < numLandmarks; ++i)\n for (j = 0; j < numLandmarks; ++j) {\n fscanf(f, \"%d\", &weight[i][j]);\n if (weight[i][j] < 0) {\n destroyLandmarkList();\n return INVALID_EDGE_WEIGHT;\n }\n }\n\n fclose(f);\n return SUCCESS;\n}\n\nvoid MapManager::setWeight(int row, int col, int value) {\n weight[row][col] = value;\n}\n\nint MapManager::getNumLandmarks(void) {\n return numLandmarks;\n}\n\nint MapManager::getWeight(int row, int col) {\n return weight[row][col];\n}\n\nvoid MapManager::print() {\n landmarkStructType *x;\n unsigned int i, j;\n \n cout << \"Number of landmarks: \" << numLandmarks << endl;\n cout << \"List of landmarks: \" << endl;\n for (x = head; x != NULL; x = x->next)\n cout << \" \" << x->name << endl;\n cout << \"Inter-landmark weights: \" << endl;\n for (i = 0; i < numLandmarks; ++i) {\n for (j = 0; j < numLandmarks; ++j)\n cout << weight[i][j] << \" \";\n cout << endl;\n }\n}<commit_msg>Renamed constant.<commit_after>#include \"MapManager.hpp\"\n\n#include <cstring>\n#include <cstdio>\n\nMapManager::MapManager(void) {\n unsigned int i, j;\n numLandmarks = 0;\n head = tail = NULL;\n for (i = 0; i < MAX_LMARKS; ++i)\n for (j = 0; j < MAX_LMARKS; ++j)\n weight[i][j] = 0;\n}\n\nMapManager::~MapManager(void) {\n destroyLandmarkList();\n}\n\nvoid MapManager::destroyLandmarkList(void) {\n landmarkStructType *x, *y = head;\n while (y != NULL) {\n x = y;\n y = y->next;\n delete x;\n }\n}\n\nint MapManager::insertLandmark(int index, char *name) {\n landmarkStructType *temp;\n\n \/\/ Is the name too long?\n if (strlen(name) > MAX_LMARK_NAME)\n return NAME_TOO_LONG;\n\n \/\/ Is the name repeated?\n for (temp = head; temp != NULL; temp = temp->next)\n if (strcmp(temp->name, name) == 0)\n return NAME_REPEATED;\n\n \/\/ Create a new index.\n temp = new landmarkStructType;\n temp->index = index;\n strcpy(temp->name, name);\n temp->next = NULL; \/\/ Always insert new nodes at the end.\n\n \/\/ Check if the linked list is empty.\n if (head == NULL) {\n \/\/ Linked list is empty.\n temp->prev = NULL;\n head = temp;\n tail = temp;\n } else {\n \/\/ No, insert new node at the tail.\n tail->next = temp;\n temp->prev = tail;\n tail = temp;\n }\n return SUCCESS;\n}\n\nchar *MapManager::getLandmarkName(unsigned int index) {\n landmarkStructType *x;\n\n if ((index > numLandmarks) || (index < 0))\n return NULL;\n\n for (x = head; x != NULL; x = x->next)\n if (x->index == index)\n return x->name;\n\n return NULL; \/\/ Not found. something is wrong.\n}\n\nint MapManager::getLandmarkIndex(char *name) {\n landmarkStructType *x;\n if (strlen(name) > MAX_LMARK_NAME)\n return -1;\n\n for (x = head; x != NULL; x = x->next)\n if (strcmp(x->name, name) == 0)\n return x->index;\n\n return UNDEFINED_LMARK; \/\/ Not found. something is wrong.\n}\n\nint MapManager::readInputFile(char *fname) {\n FILE *f = NULL;\n char temp, name[MAX_LMARK_NAME];\n unsigned int i, j;\n\n if ((f = fopen(fname, \"r\")) == NULL) {\n cerr << \"Could not open input file '\" << fname << \"'...\" << endl;\n return FAILED_TO_OPEN_FILE;\n }\n\n \/\/ Read in the landmark list.\n fscanf(f, \"%d\", &numLandmarks);\n if ((numLandmarks <= 0) || (numLandmarks > MAX_LMARKS)) {\n cout << \"Invalid number of landmarks: \" << numLandmarks << endl;\n return INVALID_NUM_LMARKS;\n }\n\n \/\/ Read in the landmark names.\n for (i = 0; i < numLandmarks; ++i) {\n \/\/ Ignore all preceding blank spaces.\n do {\n fscanf(f, \"%c\", &temp);\n } while (isspace(temp));\n\n \/\/ Start taking in the name.\n for (j = 0; j < MAX_LMARK_NAME; ++j) {\n fscanf(f, \"%c\", &name[j]);\n if (name[j] == '\"') {\n name[j] = '\\0'; \/\/ End of name.\n break;\n }\n }\n\n \/\/ Insert a new node.\n if (insertLandmark(i, name) == NAME_REPEATED) {\n destroyLandmarkList();\n return NAME_REPEATED;\n }\n }\n\n \/\/ Read in the adjacency matrix giving the inter-landmark weights.\n for (i = 0; i < numLandmarks; ++i)\n for (j = 0; j < numLandmarks; ++j) {\n fscanf(f, \"%d\", &weight[i][j]);\n if (weight[i][j] < 0) {\n destroyLandmarkList();\n return INVALID_EDGE_WEIGHT;\n }\n }\n\n fclose(f);\n return SUCCESS;\n}\n\nvoid MapManager::setWeight(int row, int col, int value) {\n weight[row][col] = value;\n}\n\nint MapManager::getNumLandmarks(void) {\n return numLandmarks;\n}\n\nint MapManager::getWeight(int row, int col) {\n return weight[row][col];\n}\n\nvoid MapManager::print() {\n landmarkStructType *x;\n unsigned int i, j;\n \n cout << \"Number of landmarks: \" << numLandmarks << endl;\n cout << \"List of landmarks: \" << endl;\n for (x = head; x != NULL; x = x->next)\n cout << \" \" << x->name << endl;\n cout << \"Inter-landmark weights: \" << endl;\n for (i = 0; i < numLandmarks; ++i) {\n for (j = 0; j < numLandmarks; ++j)\n cout << weight[i][j] << \" \";\n cout << endl;\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2011-2012, 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 * $Id$\n *\n *\/\n\n#include <sensor_msgs\/PointCloud2.h>\n#include <pcl\/ros\/conversions.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/console\/print.h>\n#include <pcl\/console\/parse.h>\n#include <pcl\/console\/time.h>\n#include <pcl\/common\/transforms.h>\n#include <cmath>\n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nvoid\nprintHelp (int, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd <options>\\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -trans dx,dy,dz = the translation (default: \"); \n print_value (\"%0.1f, %0.1f, %0.1f\", 0, 0, 0); print_info (\")\\n\");\n print_info (\" -quat w,x,y,z = rotation as quaternion\\n\"); \n print_info (\" -axisangle ax,ay,az,theta = rotation in axis-angle form\\n\"); \n print_info (\" -scale x,y,z = scale each dimension with these values\\n\"); \n print_info (\" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\\n\");\n print_info (\" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\\n\");\n print_info (\" Note: If a rotation is not specified, it will default to no rotation.\\n\");\n print_info (\" If redundant or conflicting transforms are specified, then:\\n\");\n print_info (\" -axisangle will override -quat\\n\");\n print_info (\" -matrix (3x3) will take override -axisangle and -quat\\n\");\n print_info (\" -matrix (4x4) will take override all other arguments\\n\");\n\n}\n\nvoid \nprintElapsedTimeAndNumberOfPoints (double t, int w, int h = 1)\n{\n print_info (\"[done, \"); print_value (\"%g\", t); print_info (\" ms : \"); \n print_value (\"%d\", w*h); print_info (\" points]\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud) < 0)\n return (false);\n\n printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);\n\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\ntemplate <typename PointT> void\ntransformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,\n Eigen::Matrix4f &tform)\n{\n transformPointCloud (input, output, tform);\n}\n\ntemplate <> void\ntransformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output, \n Eigen::Matrix4f &tform)\n{\n transformPointCloudWithNormals (input, output, tform);\n}\n\ntemplate <> void\ntransformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input, \n PointCloud<PointXYZRGBNormal> & output, \n Eigen::Matrix4f &tform)\n{\n transformPointCloudWithNormals (input, output, tform);\n}\n\n\ntemplate <typename PointT> void\ntransformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,\n Eigen::Matrix4f &tform)\n{\n PointCloud<PointT> cloud;\n fromROSMsg (input, cloud);\n transformPointCloudHelper (cloud, cloud, tform);\n toROSMsg (cloud, output);\n}\n\nvoid\ntransformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,\n Eigen::Matrix4f &tform)\n{\n \/\/ Check for 'rgb' and 'normals' fields\n bool has_rgb = false;\n bool has_normals = false;\n for (size_t i = 0; i < input.fields.size (); ++i)\n {\n if (input.fields[i].name == \"rgb\")\n has_rgb = true;\n if (input.fields[i].name == \"normals\")\n has_normals = true;\n }\n\n \/\/ Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal\n if (!has_rgb && !has_normals)\n transformPointCloud2AsType<PointXYZ> (input, output, tform);\n else if (has_rgb && !has_normals)\n transformPointCloud2AsType<PointXYZRGB> (input, output, tform);\n else if (!has_rgb && has_normals)\n transformPointCloud2AsType<PointNormal> (input, output, tform);\n else \/\/ (has_rgb && has_normals)\n transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n Eigen::Matrix4f &tform)\n{\n TicToc tt;\n tt.tic ();\n \n print_highlight (\"Transforming \");\n\n transformPointCloud2 (*input, output, tform);\n\n printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n \n pcl::io::savePCDFile (filename, output);\n \n printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);\n}\n\ntemplate <typename T> void\ndivide (sensor_msgs::PointCloud2 &cloud, int field_offset, double divider)\n{\n T val;\n memcpy (&val, &cloud.data[field_offset], sizeof (T));\n val \/= T (divider);\n memcpy (&cloud.data[field_offset], &val, sizeof (T));\n}\n\nvoid\nscaleInPlace (sensor_msgs::PointCloud2 &cloud, double* divider)\n{\n \/\/ Obtain the x, y, and z indices\n int x_idx = pcl::getFieldIndex (cloud, \"x\");\n int y_idx = pcl::getFieldIndex (cloud, \"y\");\n int z_idx = pcl::getFieldIndex (cloud, \"z\");\n Eigen::Array3i xyz_offset (cloud.fields[x_idx].offset, cloud.fields[y_idx].offset, cloud.fields[z_idx].offset);\n \n for (uint32_t cp = 0; cp < cloud.width * cloud.height; ++cp)\n {\n assert (cloud.fields[x_idx].datatype == cloud.fields[y_idx].datatype == cloud.fields[z_idx].datatype); \/\/ Assume all 3 fields are the same (XYZ)\n switch (cloud.fields[x_idx].datatype)\n {\n case sensor_msgs::PointField::INT8:\n for (int i = 0; i < 3; ++i) divide<int8_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::UINT8:\n for (int i = 0; i < 3; ++i) divide<uint8_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::INT16:\n for (int i = 0; i < 3; ++i) divide<int16_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::UINT16:\n for (int i = 0; i < 3; ++i) divide<uint16_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::INT32:\n for (int i = 0; i < 3; ++i) divide<int32_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::UINT32:\n for (int i = 0; i < 3; ++i) divide<uint32_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::FLOAT32:\n for (int i = 0; i < 3; ++i) divide<float> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::FLOAT64:\n for (int i = 0; i < 3; ++i) divide<double> (cloud, xyz_offset[i], divider[i]);\n break;\n }\n xyz_offset += cloud.point_step;\n }\n}\n\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Transform a cloud. For more information, use: %s -h\\n\", argv[0]);\n\n bool help = false;\n parse_argument (argc, argv, \"-h\", help);\n if (argc < 3 || help)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector<int> p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Initialize the transformation matrix\n Eigen::Matrix4f tform; \n tform.setIdentity ();\n\n \/\/ Command line parsing\n float dx, dy, dz;\n std::vector<float> values;\n\n if (parse_3x_arguments (argc, argv, \"-trans\", dx, dy, dz) > -1)\n {\n tform (0, 3) = dx;\n tform (1, 3) = dy;\n tform (2, 3) = dz;\n }\n\n if (parse_x_arguments (argc, argv, \"-quat\", values) > -1)\n {\n if (values.size () == 4)\n {\n const float& x = values[0];\n const float& y = values[1];\n const float& z = values[2];\n const float& w = values[3];\n tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));\n }\n else\n {\n print_error (\"Wrong number of values given (%zu): \", values.size ());\n print_error (\"The quaternion specified with -quat must contain 4 elements (w,x,y,z).\\n\");\n }\n }\n\n if (parse_x_arguments (argc, argv, \"-axisangle\", values) > -1)\n {\n if (values.size () == 4)\n {\n const float& ax = values[0];\n const float& ay = values[1];\n const float& az = values[2];\n const float& theta = values[3];\n tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));\n }\n else\n {\n print_error (\"Wrong number of values given (%zu): \", values.size ());\n print_error (\"The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\\n\");\n }\n }\n\n if (parse_x_arguments (argc, argv, \"-matrix\", values) > -1)\n {\n if (values.size () == 9 || values.size () == 16)\n {\n int n = values.size () == 9 ? 3 : 4;\n for (int r = 0; r < n; ++r)\n for (int c = 0; c < n; ++c)\n tform (r, c) = values[n*r+c];\n }\n else\n {\n print_error (\"Wrong number of values given (%zu): \", values.size ());\n print_error (\"The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\\n\");\n }\n }\n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud)) \n return (-1);\n\n \/\/ Apply the transform\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, tform);\n\n \/\/ Check if a scaling parameter has been given\n double divider[3];\n if (parse_3x_arguments (argc, argv, \"-scale\", divider[0], divider[1], divider[2]) > -1)\n {\n print_highlight (\"Scaling XYZ data with the following values: %f, %f, %f\\n\", divider[0], divider[1], divider[2]);\n scaleInPlace (output, divider);\n }\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n\n<commit_msg>nm<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2011-2012, 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 * $Id$\n *\n *\/\n\n#include <sensor_msgs\/PointCloud2.h>\n#include <pcl\/ros\/conversions.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/console\/print.h>\n#include <pcl\/console\/parse.h>\n#include <pcl\/console\/time.h>\n#include <pcl\/common\/transforms.h>\n#include <cmath>\n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nvoid\nprintHelp (int, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd <options>\\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -trans dx,dy,dz = the translation (default: \"); \n print_value (\"%0.1f, %0.1f, %0.1f\", 0, 0, 0); print_info (\")\\n\");\n print_info (\" -quat w,x,y,z = rotation as quaternion\\n\"); \n print_info (\" -axisangle ax,ay,az,theta = rotation in axis-angle form\\n\"); \n print_info (\" -scale x,y,z = scale each dimension with these values\\n\"); \n print_info (\" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\\n\");\n print_info (\" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\\n\");\n print_info (\" Note: If a rotation is not specified, it will default to no rotation.\\n\");\n print_info (\" If redundant or conflicting transforms are specified, then:\\n\");\n print_info (\" -axisangle will override -quat\\n\");\n print_info (\" -matrix (3x3) will take override -axisangle and -quat\\n\");\n print_info (\" -matrix (4x4) will take override all other arguments\\n\");\n\n}\n\nvoid \nprintElapsedTimeAndNumberOfPoints (double t, int w, int h = 1)\n{\n print_info (\"[done, \"); print_value (\"%g\", t); print_info (\" ms : \"); \n print_value (\"%d\", w*h); print_info (\" points]\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud) < 0)\n return (false);\n\n printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);\n\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\ntemplate <typename PointT> void\ntransformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,\n Eigen::Matrix4f &tform)\n{\n transformPointCloud (input, output, tform);\n}\n\ntemplate <> void\ntransformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output, \n Eigen::Matrix4f &tform)\n{\n transformPointCloudWithNormals (input, output, tform);\n}\n\ntemplate <> void\ntransformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input, \n PointCloud<PointXYZRGBNormal> & output, \n Eigen::Matrix4f &tform)\n{\n transformPointCloudWithNormals (input, output, tform);\n}\n\n\ntemplate <typename PointT> void\ntransformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,\n Eigen::Matrix4f &tform)\n{\n PointCloud<PointT> cloud;\n fromROSMsg (input, cloud);\n transformPointCloudHelper (cloud, cloud, tform);\n toROSMsg (cloud, output);\n}\n\nvoid\ntransformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,\n Eigen::Matrix4f &tform)\n{\n \/\/ Check for 'rgb' and 'normals' fields\n bool has_rgb = false;\n bool has_normals = false;\n for (size_t i = 0; i < input.fields.size (); ++i)\n {\n if (input.fields[i].name == \"rgb\")\n has_rgb = true;\n if (input.fields[i].name == \"normals\")\n has_normals = true;\n }\n\n \/\/ Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal\n if (!has_rgb && !has_normals)\n transformPointCloud2AsType<PointXYZ> (input, output, tform);\n else if (has_rgb && !has_normals)\n transformPointCloud2AsType<PointXYZRGB> (input, output, tform);\n else if (!has_rgb && has_normals)\n transformPointCloud2AsType<PointNormal> (input, output, tform);\n else \/\/ (has_rgb && has_normals)\n transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n Eigen::Matrix4f &tform)\n{\n TicToc tt;\n tt.tic ();\n \n print_highlight (\"Transforming \");\n\n transformPointCloud2 (*input, output, tform);\n\n printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n \n pcl::io::savePCDFile (filename, output);\n \n printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);\n}\n\ntemplate <typename T> void\ndivide (sensor_msgs::PointCloud2 &cloud, int field_offset, double divider)\n{\n T val;\n memcpy (&val, &cloud.data[field_offset], sizeof (T));\n val \/= T (divider);\n memcpy (&cloud.data[field_offset], &val, sizeof (T));\n}\n\nvoid\nscaleInPlace (sensor_msgs::PointCloud2 &cloud, double* divider)\n{\n \/\/ Obtain the x, y, and z indices\n int x_idx = pcl::getFieldIndex (cloud, \"x\");\n int y_idx = pcl::getFieldIndex (cloud, \"y\");\n int z_idx = pcl::getFieldIndex (cloud, \"z\");\n Eigen::Array3i xyz_offset (cloud.fields[x_idx].offset, cloud.fields[y_idx].offset, cloud.fields[z_idx].offset);\n \n for (uint32_t cp = 0; cp < cloud.width * cloud.height; ++cp)\n {\n \/\/ Assume all 3 fields are the same (XYZ)\n assert ((cloud.fields[x_idx].datatype == cloud.fields[y_idx].datatype));\n assert ((cloud.fields[x_idx].datatype == cloud.fields[z_idx].datatype));\n switch (cloud.fields[x_idx].datatype)\n {\n case sensor_msgs::PointField::INT8:\n for (int i = 0; i < 3; ++i) divide<int8_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::UINT8:\n for (int i = 0; i < 3; ++i) divide<uint8_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::INT16:\n for (int i = 0; i < 3; ++i) divide<int16_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::UINT16:\n for (int i = 0; i < 3; ++i) divide<uint16_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::INT32:\n for (int i = 0; i < 3; ++i) divide<int32_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::UINT32:\n for (int i = 0; i < 3; ++i) divide<uint32_t> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::FLOAT32:\n for (int i = 0; i < 3; ++i) divide<float> (cloud, xyz_offset[i], divider[i]);\n break;\n case sensor_msgs::PointField::FLOAT64:\n for (int i = 0; i < 3; ++i) divide<double> (cloud, xyz_offset[i], divider[i]);\n break;\n }\n xyz_offset += cloud.point_step;\n }\n}\n\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Transform a cloud. For more information, use: %s -h\\n\", argv[0]);\n\n bool help = false;\n parse_argument (argc, argv, \"-h\", help);\n if (argc < 3 || help)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector<int> p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Initialize the transformation matrix\n Eigen::Matrix4f tform; \n tform.setIdentity ();\n\n \/\/ Command line parsing\n float dx, dy, dz;\n std::vector<float> values;\n\n if (parse_3x_arguments (argc, argv, \"-trans\", dx, dy, dz) > -1)\n {\n tform (0, 3) = dx;\n tform (1, 3) = dy;\n tform (2, 3) = dz;\n }\n\n if (parse_x_arguments (argc, argv, \"-quat\", values) > -1)\n {\n if (values.size () == 4)\n {\n const float& x = values[0];\n const float& y = values[1];\n const float& z = values[2];\n const float& w = values[3];\n tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));\n }\n else\n {\n print_error (\"Wrong number of values given (%zu): \", values.size ());\n print_error (\"The quaternion specified with -quat must contain 4 elements (w,x,y,z).\\n\");\n }\n }\n\n if (parse_x_arguments (argc, argv, \"-axisangle\", values) > -1)\n {\n if (values.size () == 4)\n {\n const float& ax = values[0];\n const float& ay = values[1];\n const float& az = values[2];\n const float& theta = values[3];\n tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));\n }\n else\n {\n print_error (\"Wrong number of values given (%zu): \", values.size ());\n print_error (\"The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\\n\");\n }\n }\n\n if (parse_x_arguments (argc, argv, \"-matrix\", values) > -1)\n {\n if (values.size () == 9 || values.size () == 16)\n {\n int n = values.size () == 9 ? 3 : 4;\n for (int r = 0; r < n; ++r)\n for (int c = 0; c < n; ++c)\n tform (r, c) = values[n*r+c];\n }\n else\n {\n print_error (\"Wrong number of values given (%zu): \", values.size ());\n print_error (\"The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\\n\");\n }\n }\n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud)) \n return (-1);\n\n \/\/ Apply the transform\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, tform);\n\n \/\/ Check if a scaling parameter has been given\n double divider[3];\n if (parse_3x_arguments (argc, argv, \"-scale\", divider[0], divider[1], divider[2]) > -1)\n {\n print_highlight (\"Scaling XYZ data with the following values: %f, %f, %f\\n\", divider[0], divider[1], divider[2]);\n scaleInPlace (output, divider);\n }\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2010 Collabora Multimedia.\n @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk>\n\n This library is free software; you can redistribute it and\/or modify\n it 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 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 Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"clock.h\"\n\n#include <QtCore\/QTime>\n#include <gst\/gstclock.h>\n#include <gst\/gstsystemclock.h>\n\nnamespace QGst {\n\nClockPtr Clock::systemClock()\n{\n return ClockPtr::wrap(gst_system_clock_obtain(), false);\n}\n\nClockTime Clock::clockTime() const\n{\n GstClockTime t = gst_clock_get_time(object<GstClock>());\n return t;\n}\n\nClockTime Clock::resolution() const\n{\n GstClockTime t = gst_clock_get_resolution(object<GstClock>());\n return t;\n}\n\nQTime Clock::time() const\n{\n return clockTime().toTime();\n}\n\n}\n<commit_msg>src\/QGst\/clock.cpp add #include <glib-object.h>, <gst\/gstconfig.h><commit_after>\/*\n Copyright (C) 2010 Collabora Multimedia.\n @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk>\n\n This library is free software; you can redistribute it and\/or modify\n it 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 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 Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"clock.h\"\n\n#include <QtCore\/QTime>\n#include <glib-object.h>\n#include <gst\/gstconfig.h>\n#include <gst\/gstclock.h>\n#include <gst\/gstsystemclock.h>\n\nnamespace QGst {\n\nClockPtr Clock::systemClock()\n{\n return ClockPtr::wrap(gst_system_clock_obtain(), false);\n}\n\nClockTime Clock::clockTime() const\n{\n GstClockTime t = gst_clock_get_time(object<GstClock>());\n return t;\n}\n\nClockTime Clock::resolution() const\n{\n GstClockTime t = gst_clock_get_resolution(object<GstClock>());\n return t;\n}\n\nQTime Clock::time() const\n{\n return clockTime().toTime();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <errno.h>\n#include <QApplication>\n#include <QFrame>\n#include <QTextCodec>\n\n#include \"..\/typedef.h\"\n#include \"..\/config.h\"\n#include \"..\/console.h\"\n#include \"..\/error.h\"\n#include \"..\/osd.h\"\n#include \"..\/pc60.h\"\n\n\/\/SDLMainとのコンフリクト解消\n#undef main\n\n#ifdef SDL_VIDEO_DRIVER_X11\n#include <X11\/Xlib.h>\n#endif\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ メイン\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main( int argc, char *argv[] )\n{\n#ifdef SDL_VIDEO_DRIVER_X11\n \/\/X11環境でSDLスレッドを使用するために必要。\n XInitThreads();\n#endif\n\n VM6 *P6Core = NULL;\t\t\t\/\/ オブジェクトポインタ\n VM6::ReturnCode Restart = VM6::Quit;\t\/\/ 再起動フラグ\n cConfig *Cfg = NULL;\t\t\t\/\/ 環境設定オブジェクト\n\n QApplication app(argc, argv);\n QTextCodec::setCodecForCStrings(QTextCodec::codecForName(\"UTF-8\"));\n\n setlocale(LC_ALL,\"Japanese\");\n\n \/\/ 環境変数設定(テスト用)\n \/\/\tputenv( \"SDL_VIDEODRIVER=windib\" );\n \/\/\tputenv( \"SDL_VIDEODRIVER=directx\" );\n \/\/\tputenv( \"SDL_AUDIODRIVER=dsound\" );\n\n\n \/\/ 二重起動禁止\n if( OSD_IsWorking() ) return FALSE;\n\n \/\/ 設定ファイルフォルダを作成\n if( !OSD_CreateConfigPath() ) return FALSE;\n\n \/\/ SDL初期化\n if( SDL_Init( SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ){\n Error::SetError( Error::LibInitFailed );\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );\n OSD_Finish();\t\/\/ 終了処理\n return FALSE;\n }\n\n \/\/ INIファイル読込み\n Cfg = new cConfig();\n if( !Cfg ){\n SDL_Quit();\t\t\/\/ SDLシャットダウン\n OSD_Finish();\t\/\/ 終了処理\n }\n if( !Cfg->Init() ){\n switch( Error::GetError() ){\n case Error::IniDefault:\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );\n Error::SetError( Error::NoError );\n break;\n\n default:\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );\n SDL_Quit();\t\t\t\t\/\/ SDLシャットダウン\n OSD_Finish();\t\t\t\/\/ 終了処理\n if( Cfg ) delete Cfg;\t\/\/ 環境設定オブジェクト開放\n return FALSE;\n }\n }\n\n \/\/ フォントファイルが無ければ作成する\n if( !OSD_FileExist( Cfg->GetFontFileH() ) ) OSD_CreateFont( Cfg->GetFontFileH(), NULL, FSIZE );\n if( !OSD_FileExist( Cfg->GetFontFileZ() ) ) OSD_CreateFont( NULL, Cfg->GetFontFileZ(), FSIZE );\n\n\n \/\/ P6オブジェクトを作成して実行\n do{\n Restart = VM6::Quit;\n\n \/\/ ROMファイル存在チェック&機種変更\n char RomSerch[PATH_MAX];\n int IniModel = Cfg->GetModel();\n sprintf( RomSerch, \"%s*.%2d\", Cfg->GetRomPath(), IniModel );\n if( !OSD_FileExist( RomSerch ) ){\n int models[] = { 60, 62, 66 };\n for( int i=0; i < COUNTOF(models); i++ ){\n sprintf( RomSerch, \"%s*.%2d\", Cfg->GetRomPath(), models[i] );\n if( OSD_FileExist( RomSerch ) ){\n Cfg->SetModel( models[i] );\n break;\n }\n }\n \/\/ ROMある?\n if( IniModel != Cfg->GetModel() ){\n Error::SetError( Error::RomChange );\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );\n Error::SetError( Error::NoError );\n }\n }\n\n \/\/ 機種別P6オブジェクト確保\n const char* iconRes = NULL;\n switch( Cfg->GetModel() ){\n case 62: P6Core = new VM62; iconRes = \":\/res\/PC-6001mk2.ico\"; break;\n case 66: P6Core = new VM66; iconRes = \":\/res\/PC-6601.ico\"; break;\n default: P6Core = new VM60; iconRes = \":\/res\/PC-6001.ico\";\n }\n\n \/\/ アイコン設定\n QImage icon = QImage(iconRes).convertToFormat(QImage::Format_RGB16);\n SDL_Surface *p6icon = SDL_CreateRGBSurfaceFrom( icon.bits(), icon.width(), icon.height(), icon.depth(), icon.bytesPerLine(), 0, 0, 0, 0 );\n SDL_WM_SetIcon( p6icon, icon.alphaChannel().bits() );\n SDL_FreeSurface( p6icon );\n\n \/\/ VMを初期化して実行\n if( P6Core->Init( Cfg ) ){\n switch( Restart ){\n case VM6::Doko:\t\t\/\/ どこでもLOAD?\n P6Core->DokoDemoLoad( Cfg->GetDokoFile() );\n break;\n\n case VM6::Replay:\t\/\/ リプレイ再生?\n {\n char temp[PATH_MAX];\n strncpy( temp, Cfg->GetDokoFile(), PATH_MAX );\n P6Core->DokoDemoLoad( temp );\n P6Core->REPLAY::StartReplay( temp );\n }\n break;\n\n default:\n break;\n }\n\n P6Core->Start();\n Restart = P6Core->EventLoop();\n P6Core->Stop();\n }else{\n \/\/ 失敗した場合\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );\n }\n\n \/\/ P6オブジェクトを開放\n if( P6Core ) delete P6Core;\n\n\n \/\/ 再起動ならばINIファイル再読込み\n if( Restart == VM6::Restart ){\n if( !Cfg->Init() ){\n Error::SetError( Error::IniDefault );\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );\n Error::SetError( Error::NoError );\n }\n }\n\n }while( Restart != VM6::Quit );\n\n\n\n \/\/ 環境設定オブジェクト開放\n if( Cfg ) delete Cfg;\n\n \/\/ SDLシャットダウン\n SDL_Quit();\n\n \/\/ 終了処理\n OSD_Finish();\n\n return TRUE;\n}\n<commit_msg>Fixed crash when QtSDK is not installed due to lack of qjpcodec4.dll.<commit_after>#include <stdlib.h>\n#include <errno.h>\n#include <QApplication>\n#include <QFrame>\n#include <QTextCodec>\n\n#include \"..\/typedef.h\"\n#include \"..\/config.h\"\n#include \"..\/console.h\"\n#include \"..\/error.h\"\n#include \"..\/osd.h\"\n#include \"..\/pc60.h\"\n\n\/\/SDLMainとのコンフリクト解消\n#undef main\n\n#ifdef SDL_VIDEO_DRIVER_X11\n#include <X11\/Xlib.h>\n#endif\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ メイン\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main( int argc, char *argv[] )\n{\n#ifdef SDL_VIDEO_DRIVER_X11\n \/\/X11環境でSDLスレッドを使用するために必要。\n XInitThreads();\n#endif\n\n VM6 *P6Core = NULL;\t\t\t\/\/ オブジェクトポインタ\n VM6::ReturnCode Restart = VM6::Quit;\t\/\/ 再起動フラグ\n cConfig *Cfg = NULL;\t\t\t\/\/ 環境設定オブジェクト\n\n QApplication app(argc, argv);\n QTextCodec::setCodecForCStrings(QTextCodec::codecForName(\"UTF-8\"));\n\n setlocale(LC_ALL,\"Japanese\");\n\n#ifdef WIN32\n \/\/ Windowsではアプリに同梱のqjpcodecs4.dllプラグインを読み込むため、そのパスを指定\n QApplication::addLibraryPath(qApp->applicationFilePath());\n#endif\n\n \/\/ 環境変数設定(テスト用)\n \/\/\tputenv( \"SDL_VIDEODRIVER=windib\" );\n \/\/\tputenv( \"SDL_VIDEODRIVER=directx\" );\n \/\/\tputenv( \"SDL_AUDIODRIVER=dsound\" );\n\n\n \/\/ 二重起動禁止\n if( OSD_IsWorking() ) return FALSE;\n\n \/\/ 設定ファイルフォルダを作成\n if( !OSD_CreateConfigPath() ) return FALSE;\n\n \/\/ SDL初期化\n if( SDL_Init( SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ){\n Error::SetError( Error::LibInitFailed );\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );\n OSD_Finish();\t\/\/ 終了処理\n return FALSE;\n }\n\n \/\/ INIファイル読込み\n Cfg = new cConfig();\n if( !Cfg ){\n SDL_Quit();\t\t\/\/ SDLシャットダウン\n OSD_Finish();\t\/\/ 終了処理\n }\n if( !Cfg->Init() ){\n switch( Error::GetError() ){\n case Error::IniDefault:\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );\n Error::SetError( Error::NoError );\n break;\n\n default:\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );\n SDL_Quit();\t\t\t\t\/\/ SDLシャットダウン\n OSD_Finish();\t\t\t\/\/ 終了処理\n if( Cfg ) delete Cfg;\t\/\/ 環境設定オブジェクト開放\n return FALSE;\n }\n }\n\n \/\/ フォントファイルが無ければ作成する\n if( !OSD_FileExist( Cfg->GetFontFileH() ) ) OSD_CreateFont( Cfg->GetFontFileH(), NULL, FSIZE );\n if( !OSD_FileExist( Cfg->GetFontFileZ() ) ) OSD_CreateFont( NULL, Cfg->GetFontFileZ(), FSIZE );\n\n\n \/\/ P6オブジェクトを作成して実行\n do{\n Restart = VM6::Quit;\n\n \/\/ ROMファイル存在チェック&機種変更\n char RomSerch[PATH_MAX];\n int IniModel = Cfg->GetModel();\n sprintf( RomSerch, \"%s*.%2d\", Cfg->GetRomPath(), IniModel );\n if( !OSD_FileExist( RomSerch ) ){\n int models[] = { 60, 62, 66 };\n for( int i=0; i < COUNTOF(models); i++ ){\n sprintf( RomSerch, \"%s*.%2d\", Cfg->GetRomPath(), models[i] );\n if( OSD_FileExist( RomSerch ) ){\n Cfg->SetModel( models[i] );\n break;\n }\n }\n \/\/ ROMある?\n if( IniModel != Cfg->GetModel() ){\n Error::SetError( Error::RomChange );\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );\n Error::SetError( Error::NoError );\n }\n }\n\n \/\/ 機種別P6オブジェクト確保\n const char* iconRes = NULL;\n switch( Cfg->GetModel() ){\n case 62: P6Core = new VM62; iconRes = \":\/res\/PC-6001mk2.ico\"; break;\n case 66: P6Core = new VM66; iconRes = \":\/res\/PC-6601.ico\"; break;\n default: P6Core = new VM60; iconRes = \":\/res\/PC-6001.ico\";\n }\n\n \/\/ アイコン設定\n QImage icon = QImage(iconRes).convertToFormat(QImage::Format_RGB16);\n SDL_Surface *p6icon = SDL_CreateRGBSurfaceFrom( icon.bits(), icon.width(), icon.height(), icon.depth(), icon.bytesPerLine(), 0, 0, 0, 0 );\n SDL_WM_SetIcon( p6icon, icon.alphaChannel().bits() );\n SDL_FreeSurface( p6icon );\n\n \/\/ VMを初期化して実行\n if( P6Core->Init( Cfg ) ){\n switch( Restart ){\n case VM6::Doko:\t\t\/\/ どこでもLOAD?\n P6Core->DokoDemoLoad( Cfg->GetDokoFile() );\n break;\n\n case VM6::Replay:\t\/\/ リプレイ再生?\n {\n char temp[PATH_MAX];\n strncpy( temp, Cfg->GetDokoFile(), PATH_MAX );\n P6Core->DokoDemoLoad( temp );\n P6Core->REPLAY::StartReplay( temp );\n }\n break;\n\n default:\n break;\n }\n\n P6Core->Start();\n Restart = P6Core->EventLoop();\n P6Core->Stop();\n }else{\n \/\/ 失敗した場合\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR );\n }\n\n \/\/ P6オブジェクトを開放\n if( P6Core ) delete P6Core;\n\n\n \/\/ 再起動ならばINIファイル再読込み\n if( Restart == VM6::Restart ){\n if( !Cfg->Init() ){\n Error::SetError( Error::IniDefault );\n OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING );\n Error::SetError( Error::NoError );\n }\n }\n\n }while( Restart != VM6::Quit );\n\n\n\n \/\/ 環境設定オブジェクト開放\n if( Cfg ) delete Cfg;\n\n \/\/ SDLシャットダウン\n SDL_Quit();\n\n \/\/ 終了処理\n OSD_Finish();\n\n return TRUE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pybulletphysics.h\"\n\nstatic void\nQuaternion_dealloc(bulletphysics_QuaternionObject* self)\n{\n delete(self->quaternion);\n self->ob_type->tp_free((PyObject*)self);\n}\n\nstatic PyObject*\nQuaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\n\tfloat x = 0.0;\n\tfloat y = 0.0;\n\tfloat z = 0.0;\n\tfloat w = 0.0;\n\tif (!PyArg_ParseTuple(args, \"ffff\", &x, &y, &z, &w)) {\n \treturn NULL;\n \t}\n\n bulletphysics_QuaternionObject *self = (bulletphysics_QuaternionObject *)type->tp_alloc(type, 0);\n if (self != NULL) {\n self->quaternion = new btQuaternion(x, y, z, w);\n }\n return (PyObject *)self;\n}\n\nPyTypeObject bulletphysics_QuaternionType = {\n PyObject_HEAD_INIT(NULL)\n 0, \/*ob_size*\/\n \"bulletphysics.Quaternion\", \/*tp_name*\/\n sizeof(bulletphysics_QuaternionObject), \/*tp_basicsize*\/\n 0, \/*tp_itemsize*\/\n (destructor)Quaternion_dealloc, \/*tp_dealloc*\/\n 0, \/*tp_print*\/\n 0, \/*tp_getattr*\/\n 0, \/*tp_setattr*\/\n 0, \/*tp_compare*\/\n 0, \/*tp_repr*\/\n 0, \/*tp_as_number*\/\n 0, \/*tp_as_sequence*\/\n 0, \/*tp_as_mapping*\/\n 0, \/*tp_hash *\/\n 0, \/*tp_call*\/\n 0, \/*tp_str*\/\n 0, \/*tp_getattro*\/\n 0, \/*tp_setattro*\/\n 0, \/*tp_as_buffer*\/\n Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, \/*tp_flags*\/\n \"Quaternion object\", \/* tp_doc *\/\n};\n\nPyObject *new_pyquaternion_from_quaternion(btQuaternion q) {\n bulletphysics_QuaternionObject *py_quaternion = (bulletphysics_QuaternionObject *)bulletphysics_QuaternionType.tp_alloc(&bulletphysics_QuaternionType, 0);\n if (py_quaternion) {\n py_quaternion->quaternion = new btQuaternion(q.getX(), q.getY(), q.getZ(), q.getW());\n Py_INCREF(py_quaternion);\n }\n return (PyObject *)py_quaternion;\n}\n\nstatic PyObject *\nQuaternion_getX(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n return PyFloat_FromDouble(self->quaternion->getX());\n}\n\nstatic PyObject *\nQuaternion_getY(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n return PyFloat_FromDouble(self->quaternion->getY());\n}\n\nstatic PyObject *\nQuaternion_getZ(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n return PyFloat_FromDouble(self->quaternion->getZ());\n}\n\nstatic PyObject *\nQuaternion_getW(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n return PyFloat_FromDouble(self->quaternion->getW());\n}\n\nstatic PyObject *\nQuaternion_getAxis(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n\treturn new_pyvector3_from_vector(self->quaternion->getAxis());\n}\n\nstatic PyObject *\nQuaternion_getAngle(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n\treturn PyFloat_FromDouble(self->quaternion->getAngle());\n}\n\nstatic PyMethodDef Quaternion_methods[] = {\n {\"getX\", (PyCFunction)Quaternion_getX, METH_VARARGS, NULL },\n {\"getY\", (PyCFunction)Quaternion_getY, METH_VARARGS, NULL },\n {\"getZ\", (PyCFunction)Quaternion_getZ, METH_VARARGS, NULL },\n {\"getW\", (PyCFunction)Quaternion_getW, METH_VARARGS, NULL },\n {\"getAxis\", (PyCFunction)Quaternion_getAxis, METH_VARARGS, NULL },\n {\"getAngle\", (PyCFunction)Quaternion_getAngle, METH_VARARGS, NULL },\n {NULL, NULL, 0, NULL}\n};\n\nvoid pybulletphysics_add_Quaternion(PyObject *module) {\n\tbulletphysics_QuaternionType.tp_methods = Quaternion_methods;\n\tbulletphysics_QuaternionType.tp_new = Quaternion_new;\n\n if (PyType_Ready(&bulletphysics_QuaternionType) < 0)\n return;\t\n\n\tPy_INCREF(&bulletphysics_QuaternionType);\n\n PyModule_AddObject(module, \"Quaternion\", (PyObject *)&bulletphysics_QuaternionType);\n}\n<commit_msg>added setRotation() to Quaternion<commit_after>#include \"pybulletphysics.h\"\n\nextern PyTypeObject bulletphysics_Vector3Type;\n\nstatic void\nQuaternion_dealloc(bulletphysics_QuaternionObject* self)\n{\n delete(self->quaternion);\n self->ob_type->tp_free((PyObject*)self);\n}\n\nstatic PyObject*\nQuaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\n\tfloat x = 0.0;\n\tfloat y = 0.0;\n\tfloat z = 0.0;\n\tfloat w = 0.0;\n\tif (!PyArg_ParseTuple(args, \"ffff\", &x, &y, &z, &w)) {\n \treturn NULL;\n \t}\n\n bulletphysics_QuaternionObject *self = (bulletphysics_QuaternionObject *)type->tp_alloc(type, 0);\n if (self != NULL) {\n self->quaternion = new btQuaternion(x, y, z, w);\n }\n return (PyObject *)self;\n}\n\nPyTypeObject bulletphysics_QuaternionType = {\n PyObject_HEAD_INIT(NULL)\n 0, \/*ob_size*\/\n \"bulletphysics.Quaternion\", \/*tp_name*\/\n sizeof(bulletphysics_QuaternionObject), \/*tp_basicsize*\/\n 0, \/*tp_itemsize*\/\n (destructor)Quaternion_dealloc, \/*tp_dealloc*\/\n 0, \/*tp_print*\/\n 0, \/*tp_getattr*\/\n 0, \/*tp_setattr*\/\n 0, \/*tp_compare*\/\n 0, \/*tp_repr*\/\n 0, \/*tp_as_number*\/\n 0, \/*tp_as_sequence*\/\n 0, \/*tp_as_mapping*\/\n 0, \/*tp_hash *\/\n 0, \/*tp_call*\/\n 0, \/*tp_str*\/\n 0, \/*tp_getattro*\/\n 0, \/*tp_setattro*\/\n 0, \/*tp_as_buffer*\/\n Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, \/*tp_flags*\/\n \"Quaternion object\", \/* tp_doc *\/\n};\n\nPyObject *new_pyquaternion_from_quaternion(btQuaternion q) {\n bulletphysics_QuaternionObject *py_quaternion = (bulletphysics_QuaternionObject *)bulletphysics_QuaternionType.tp_alloc(&bulletphysics_QuaternionType, 0);\n if (py_quaternion) {\n py_quaternion->quaternion = new btQuaternion(q.getX(), q.getY(), q.getZ(), q.getW());\n Py_INCREF(py_quaternion);\n }\n return (PyObject *)py_quaternion;\n}\n\nstatic PyObject *\nQuaternion_getX(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n return PyFloat_FromDouble(self->quaternion->getX());\n}\n\nstatic PyObject *\nQuaternion_getY(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n return PyFloat_FromDouble(self->quaternion->getY());\n}\n\nstatic PyObject *\nQuaternion_getZ(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n return PyFloat_FromDouble(self->quaternion->getZ());\n}\n\nstatic PyObject *\nQuaternion_getW(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n return PyFloat_FromDouble(self->quaternion->getW());\n}\n\nstatic PyObject *\nQuaternion_getAxis(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n\treturn new_pyvector3_from_vector(self->quaternion->getAxis());\n}\n\nstatic PyObject *\nQuaternion_getAngle(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n\treturn PyFloat_FromDouble(self->quaternion->getAngle());\n}\n\nstatic PyObject *\nQuaternion_setRotation(bulletphysics_QuaternionObject *self, PyObject *args, PyObject *kwds) {\n bulletphysics_Vector3Object *py_vector3 = NULL;\n float angle = 0.0;\n if (!PyArg_ParseTuple(args, \"Of\", &py_vector3, &angle)) {\n return NULL;\n }\n pybulletphysics_checktype(py_vector3, Vector3);\n\tself->quaternion->setRotation(*(py_vector3->vector), angle);\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyMethodDef Quaternion_methods[] = {\n {\"getX\", (PyCFunction)Quaternion_getX, METH_VARARGS, NULL },\n {\"getY\", (PyCFunction)Quaternion_getY, METH_VARARGS, NULL },\n {\"getZ\", (PyCFunction)Quaternion_getZ, METH_VARARGS, NULL },\n {\"getW\", (PyCFunction)Quaternion_getW, METH_VARARGS, NULL },\n {\"getAxis\", (PyCFunction)Quaternion_getAxis, METH_VARARGS, NULL },\n {\"getAngle\", (PyCFunction)Quaternion_getAngle, METH_VARARGS, NULL },\n {\"setRotation\", (PyCFunction)Quaternion_setRotation, METH_VARARGS, NULL },\n {NULL, NULL, 0, NULL}\n};\n\nvoid pybulletphysics_add_Quaternion(PyObject *module) {\n\tbulletphysics_QuaternionType.tp_methods = Quaternion_methods;\n\tbulletphysics_QuaternionType.tp_new = Quaternion_new;\n\n if (PyType_Ready(&bulletphysics_QuaternionType) < 0)\n return;\t\n\n\tPy_INCREF(&bulletphysics_QuaternionType);\n\n PyModule_AddObject(module, \"Quaternion\", (PyObject *)&bulletphysics_QuaternionType);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Rasterizer.hpp\"\n#include <cmath>\n#include <algorithm>\n#include <float.h>\n#include <cstdio>\n#include <cassert>\n#include \"stb_image.h\"\n\nusing std::modf;\n\nRasterizer::Rasterizer(void* pixels) :\nm_pixels(static_cast<unsigned*>(pixels))\n{\n int n;\n m_texture = stbi_load(\"texture.png\", &m_texx, &m_texy, &n, 3);\n m_mode = ERM_TEXTURES;\n}\n\nRasterizer::~Rasterizer()\n{\n stbi_image_free(m_texture);\n}\n\nstatic inline float crossProduct(float ax, float ay, float bx, float by)\n{\n return ax * by - ay * bx;\n}\n\nstatic inline int min(int a, int b, int c)\n{\n return std::min(a, std::min(b, c));\n}\n\nstatic inline int max(int a, int b, int c)\n{\n return std::max(a, std::max(b, c));\n}\n\nstatic inline void sepcolor(unsigned c, int& r, int& g, int& b)\n{\n r = (c >> 16) & 0xff;\n g = (c >> 8) & 0xff;\n b = (c >> 0) & 0xff;\n}\n\nstatic inline unsigned mix3colors(unsigned c1, float v1, unsigned c2, float v2, unsigned c3, float v3)\n{\n int r1, g1, b1;\n int r2, g2, b2;\n int r3, g3, b3;\n sepcolor(c1, r1, g1, b1);\n sepcolor(c2, r2, g2, b2);\n sepcolor(c3, r3, g3, b3);\n int rf = r1 * v1 + r2 * v2 + r3 * v3;\n int gf = g1 * v1 + g2 * v2 + g3 * v3;\n int bf = b1 * v1 + b2 * v2 + b3 * v3;\n return (rf << 16) + (gf << 8) + bf;\n}\n\nstatic inline unsigned mul2colors(unsigned c1, unsigned c2)\n{\n int r1, g1, b1;\n int r2, g2, b2;\n sepcolor(c1, r1, g1, b1);\n sepcolor(c2, r2, g2, b2);\n int rf = (r1 * r2) \/ 255;\n int gf = (g1 * g2) \/ 255;\n int bf = (b1 * b2) \/ 255;\n assert(0 <= rf && rf <= 255);\n assert(0 <= gf && gf <= 255);\n assert(0 <= bf && bf <= 255);\n return (rf << 16) + (gf << 8) + bf;\n}\n\nstatic void adjustToView(int& x1, int& y1, int& x2, int& y2)\n{\n x1 = std::max(0, std::min(x1, 640 - 1));\n y1 = std::max(0, std::min(y1, 480 - 1));\n x2 = std::max(0, std::min(x2, 640 - 1));\n y2 = std::max(0, std::min(y2, 480 - 1));\n}\n\nstatic unsigned rgbf(float r, float g, float b)\n{\n const int rf = std::max(0, std::min<int>(255, r * 255.f));\n const int gf = std::max(0, std::min<int>(255, g * 255.f));\n const int bf = std::max(0, std::min<int>(255, b * 255.f));\n return (rf << 16) + (gf << 8) + bf;\n}\n\nstatic float normalizeTCoords(float x)\n{\n float u;\n x = modf(x, &u);\n return std::fabs(x);\n}\n\nvoid Rasterizer::rasterize()\n{\n for(int i = 0; i < 640 * 480; ++i)\n m_depthbuffer[i] = FLT_MAX;\n\n for(int i = 0; i < 640 * 480; ++i)\n m_pixels[i] = 0x202020; \/\/very dark gray\n\n for(int i = 0; i < (int)m_vertices.size(); i += 3)\n {\n int x1 = m_vertices[i].x;\n int y1 = m_vertices[i].y;\n unsigned c1 = m_vertices[i].color;\n float d1 = m_vertices[i].depth;\n float u1 = m_vertices[i].u;\n float v1 = m_vertices[i].v;\n\n int x2 = m_vertices[i + 1].x;\n int y2 = m_vertices[i + 1].y;\n unsigned c2 = m_vertices[i + 1].color;\n float d2 = m_vertices[i + 1].depth;\n float u2 = m_vertices[i + 1].u;\n float v2 = m_vertices[i + 1].v;\n\n int x3 = m_vertices[i + 2].x;\n int y3 = m_vertices[i + 2].y;\n unsigned c3 = m_vertices[i + 2].color;\n float d3 = m_vertices[i + 2].depth;\n float u3 = m_vertices[i + 2].u;\n float v3 = m_vertices[i + 2].v;\n\n \/\/don't render triangles that might have been incorrectly\n \/\/casted due to being behind the camera\n if(d1 < 0.f || d2 < 0.f || d3 < 0.f)\n continue;\n\n int maxX = max(x1, x2, x3);\n int minX = min(x1, x2, x3);\n int maxY = max(y1, y2, y3);\n int minY = min(y1, y2, y3);\n\n\n \/\/clip\n adjustToView(minX, minY, maxX, maxY);\n\n for(int x = minX; x <= maxX; ++x)\n {\n for(int y = minY; y <= maxY; ++y)\n {\n const float w2 = crossProduct(x - x1, y - y1, x3 - x1, y3 - y1) \/ crossProduct(x2 - x1, y2 - y1, x3 - x1, y3 - y1);\n const float w3 = crossProduct(x2 - x1, y2 - y1, x - x1, y - y1) \/ crossProduct(x2 - x1, y2 - y1, x3 - x1, y3 - y1);\n if((w2 >= 0) && (w3 >= 0) && (w2 + w3 <= 1))\n {\n const float w1 = 1.f - w2 - w3;\n const float depth = d1 * w1 + d2 * w2 + d3 * w3;\n if(canSetPixel(x, y, depth))\n {\n const unsigned color = mix3colors(c1, w1, c2, w2, c3, w3);\n const float u = normalizeTCoords(u1 * w1 + u2 * w2 + u3 * w3);\n const float v = normalizeTCoords(v1 * w1 + v2 * w2 + v3 * w3);\n const unsigned texel = getTexel(u, v);\n switch(m_mode)\n {\n case ERM_COLORS:\n setPixel(x, y, color, depth);\n break;\n case ERM_TEXTURES:\n setPixel(x, y, texel, depth);\n break;\n case ERM_COLORS_TEXTURES:\n setPixel(x, y, mul2colors(color, texel), depth);\n break;\n case ERM_UV_RED_BLUE:\n setPixel(x, y, rgbf(u, 0.f, v), depth);\n break;\n }\/\/switch m_mode\n }\/\/can set pixel\n }\/\/inside\n }\/\/for y\n }\/\/for x\n }\/\/for each triangle\n}\n\nvoid Rasterizer::clear()\n{\n m_vertices.clear();\n}\n\nvoid Rasterizer::addVertex(int x, int y, unsigned color, float depth, float u, float v)\n{\n Vertex2 vert;\n vert.x = x;\n vert.y = y;\n vert.color = color;\n vert.depth = depth;\n vert.u = u;\n vert.v = v;\n m_vertices.push_back(vert);\n}\n\nbool Rasterizer::canSetPixel(int x, int y, float depth)\n{\n if(depth < 0.f)\n return false;\n\n assert(0 <= x && x < 640 && 0 <= y && y < 480);\n if(m_depthbuffer[x + y * 640] > depth)\n return true;\n\n return false;\n}\n\nvoid Rasterizer::setPixel(int x, int y, unsigned color, float depth)\n{\n assert(0 <= x && x < 640 && 0 <= y && y < 480);\n m_pixels[x + y * 640] = color;\n m_depthbuffer[x + y * 640] = depth;\n}\n\nunsigned Rasterizer::getTexel(float u, float v) const\n{\n const int x = std::max(0, std::min<int>(round(u * m_texx), m_texx - 1));\n const int y = std::max(0, std::min<int>(round(v * m_texy), m_texy - 1));\n const unsigned char * tex = &m_texture[3 * (x + m_texx * y)];\n return (tex[0] << 16) + (tex[1] << 8) + tex[2];\n}\n\nvoid Rasterizer::toggleRenderMode()\n{\n m_mode = (m_mode + 1) % ERENDER_MODE_COUNT;\n}\n<commit_msg>Added good pespective correct texturing.<commit_after>#include \"Rasterizer.hpp\"\n#include <cmath>\n#include <algorithm>\n#include <float.h>\n#include <cstdio>\n#include <cassert>\n#include \"stb_image.h\"\n\nusing std::modf;\n\nRasterizer::Rasterizer(void* pixels) :\nm_pixels(static_cast<unsigned*>(pixels))\n{\n int n;\n m_texture = stbi_load(\"texture.png\", &m_texx, &m_texy, &n, 3);\n m_mode = ERM_TEXTURES;\n}\n\nRasterizer::~Rasterizer()\n{\n stbi_image_free(m_texture);\n}\n\nstatic inline float crossProduct(float ax, float ay, float bx, float by)\n{\n return ax * by - ay * bx;\n}\n\nstatic inline int min(int a, int b, int c)\n{\n return std::min(a, std::min(b, c));\n}\n\nstatic inline int max(int a, int b, int c)\n{\n return std::max(a, std::max(b, c));\n}\n\nstatic inline void sepcolor(unsigned c, int& r, int& g, int& b)\n{\n r = (c >> 16) & 0xff;\n g = (c >> 8) & 0xff;\n b = (c >> 0) & 0xff;\n}\n\nstatic inline unsigned mix3colors(unsigned c1, float v1, unsigned c2, float v2, unsigned c3, float v3)\n{\n int r1, g1, b1;\n int r2, g2, b2;\n int r3, g3, b3;\n sepcolor(c1, r1, g1, b1);\n sepcolor(c2, r2, g2, b2);\n sepcolor(c3, r3, g3, b3);\n int rf = r1 * v1 + r2 * v2 + r3 * v3;\n int gf = g1 * v1 + g2 * v2 + g3 * v3;\n int bf = b1 * v1 + b2 * v2 + b3 * v3;\n return (rf << 16) + (gf << 8) + bf;\n}\n\nstatic inline unsigned mul2colors(unsigned c1, unsigned c2)\n{\n int r1, g1, b1;\n int r2, g2, b2;\n sepcolor(c1, r1, g1, b1);\n sepcolor(c2, r2, g2, b2);\n int rf = (r1 * r2) \/ 255;\n int gf = (g1 * g2) \/ 255;\n int bf = (b1 * b2) \/ 255;\n assert(0 <= rf && rf <= 255);\n assert(0 <= gf && gf <= 255);\n assert(0 <= bf && bf <= 255);\n return (rf << 16) + (gf << 8) + bf;\n}\n\nstatic void adjustToView(int& x1, int& y1, int& x2, int& y2)\n{\n x1 = std::max(0, std::min(x1, 640 - 1));\n y1 = std::max(0, std::min(y1, 480 - 1));\n x2 = std::max(0, std::min(x2, 640 - 1));\n y2 = std::max(0, std::min(y2, 480 - 1));\n}\n\nstatic unsigned rgbf(float r, float g, float b)\n{\n const int rf = std::max(0, std::min<int>(255, r * 255.f));\n const int gf = std::max(0, std::min<int>(255, g * 255.f));\n const int bf = std::max(0, std::min<int>(255, b * 255.f));\n return (rf << 16) + (gf << 8) + bf;\n}\n\nstatic float normalizeTCoords(float x)\n{\n float u;\n x = modf(x, &u);\n return std::fabs(x);\n}\n\nvoid Rasterizer::rasterize()\n{\n for(int i = 0; i < 640 * 480; ++i)\n m_depthbuffer[i] = FLT_MAX;\n\n for(int i = 0; i < 640 * 480; ++i)\n m_pixels[i] = 0x202020; \/\/very dark gray\n\n for(int i = 0; i < (int)m_vertices.size(); i += 3)\n {\n int x1 = m_vertices[i].x;\n int y1 = m_vertices[i].y;\n unsigned c1 = m_vertices[i].color;\n float d1 = m_vertices[i].depth;\n float u1 = m_vertices[i].u \/ d1;\n float v1 = m_vertices[i].v \/ d1;\n float d1i = 1.f \/ m_vertices[i].depth;\n\n int x2 = m_vertices[i + 1].x;\n int y2 = m_vertices[i + 1].y;\n unsigned c2 = m_vertices[i + 1].color;\n float d2 = m_vertices[i + 1].depth;\n float u2 = m_vertices[i + 1].u \/ d2;\n float v2 = m_vertices[i + 1].v \/ d2;\n float d2i = 1.f \/ m_vertices[i + 1].depth;\n\n int x3 = m_vertices[i + 2].x;\n int y3 = m_vertices[i + 2].y;\n unsigned c3 = m_vertices[i + 2].color;\n float d3 = m_vertices[i + 2].depth;\n float u3 = m_vertices[i + 2].u \/ d3;\n float v3 = m_vertices[i + 2].v \/ d3;\n float d3i = 1.f \/ m_vertices[i + 2].depth;\n\n \/\/don't render triangles that might have been incorrectly\n \/\/casted due to being behind the camera\n if(d1 < 0.f || d2 < 0.f || d3 < 0.f)\n continue;\n\n int maxX = max(x1, x2, x3);\n int minX = min(x1, x2, x3);\n int maxY = max(y1, y2, y3);\n int minY = min(y1, y2, y3);\n\n\n \/\/clip\n adjustToView(minX, minY, maxX, maxY);\n\n for(int x = minX; x <= maxX; ++x)\n {\n for(int y = minY; y <= maxY; ++y)\n {\n const float w2 = crossProduct(x - x1, y - y1, x3 - x1, y3 - y1) \/ crossProduct(x2 - x1, y2 - y1, x3 - x1, y3 - y1);\n const float w3 = crossProduct(x2 - x1, y2 - y1, x - x1, y - y1) \/ crossProduct(x2 - x1, y2 - y1, x3 - x1, y3 - y1);\n if((w2 >= 0) && (w3 >= 0) && (w2 + w3 <= 1))\n {\n const float w1 = 1.f - w2 - w3;\n const float depth = d1 * w1 + d2 * w2 + d3 * w3;\n const float depthi = d1i * w1 + d2i * w2 + d3i * w3;\n if(canSetPixel(x, y, depth))\n {\n const unsigned color = mix3colors(c1, w1, c2, w2, c3, w3);\n const float u = normalizeTCoords(u1 * w1 + u2 * w2 + u3 * w3);\n const float v = normalizeTCoords(v1 * w1 + v2 * w2 + v3 * w3);\n const unsigned texel = getTexel(u \/ depthi, v \/ depthi);\n switch(m_mode)\n {\n case ERM_COLORS:\n setPixel(x, y, color, depth);\n break;\n case ERM_TEXTURES:\n setPixel(x, y, texel, depth);\n break;\n case ERM_COLORS_TEXTURES:\n setPixel(x, y, mul2colors(color, texel), depth);\n break;\n case ERM_UV_RED_BLUE:\n setPixel(x, y, rgbf(u, 0.f, v), depth);\n break;\n }\/\/switch m_mode\n }\/\/can set pixel\n }\/\/inside\n }\/\/for y\n }\/\/for x\n }\/\/for each triangle\n}\n\nvoid Rasterizer::clear()\n{\n m_vertices.clear();\n}\n\nvoid Rasterizer::addVertex(int x, int y, unsigned color, float depth, float u, float v)\n{\n Vertex2 vert;\n vert.x = x;\n vert.y = y;\n vert.color = color;\n vert.depth = depth;\n vert.u = u;\n vert.v = v;\n m_vertices.push_back(vert);\n}\n\nbool Rasterizer::canSetPixel(int x, int y, float depth)\n{\n if(depth < 0.f)\n return false;\n\n assert(0 <= x && x < 640 && 0 <= y && y < 480);\n if(m_depthbuffer[x + y * 640] > depth)\n return true;\n\n return false;\n}\n\nvoid Rasterizer::setPixel(int x, int y, unsigned color, float depth)\n{\n assert(0 <= x && x < 640 && 0 <= y && y < 480);\n m_pixels[x + y * 640] = color;\n m_depthbuffer[x + y * 640] = depth;\n}\n\nunsigned Rasterizer::getTexel(float u, float v) const\n{\n const int x = std::max(0, std::min<int>(round(u * m_texx), m_texx - 1));\n const int y = std::max(0, std::min<int>(round(v * m_texy), m_texy - 1));\n const unsigned char * tex = &m_texture[3 * (x + m_texx * y)];\n return (tex[0] << 16) + (tex[1] << 8) + tex[2];\n}\n\nvoid Rasterizer::toggleRenderMode()\n{\n m_mode = (m_mode + 1) % ERENDER_MODE_COUNT;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SimpleIcon.h\"\n#include <graphics\/IconPack.h>\n#include <graphics\/Painter.h>\n\nnamespace MGUI\n{\n\nilixi::IconPack* SimpleIcon::__iconPack = NULL;\n\nSimpleIcon::SimpleIcon(Widget* parent)\n : Widget(parent),\n _image(NULL)\n{\n setConstraints(ilixi::FixedConstraint, ilixi::FixedConstraint);\n if (!__iconPack)\n __iconPack = new ilixi::IconPack(DATADIR\"\/theme\/IconPack.xml\");\n}\n\nSimpleIcon::~SimpleIcon()\n{\n delete _image;\n}\n\nilixi::Size\nSimpleIcon::preferredSize() const\n{\n return ilixi::Size(24, 24);\n}\n\nvoid\nSimpleIcon::setImage(const std::string& name)\n{\n if (_image)\n delete _image;\n _image = __iconPack->getIcon(name);\n update();\n}\n\nvoid\nSimpleIcon::compose(const ilixi::PaintEvent& event)\n{\n if (_image)\n {\n ilixi::Painter p(this);\n p.begin(event);\n p.drawImage(_image, 0, 0);\n p.end();\n }\n}\n\n} \/* namespace MGUI *\/\n<commit_msg>SimpleIcon: WakeUp main loop when image is set.<commit_after>#include \"SimpleIcon.h\"\n#include <core\/Engine.h>\n#include <graphics\/IconPack.h>\n#include <graphics\/Painter.h>\n\nnamespace MGUI\n{\n\nilixi::IconPack* SimpleIcon::__iconPack = NULL;\n\nSimpleIcon::SimpleIcon(Widget* parent)\n : Widget(parent),\n _image(NULL)\n{\n setConstraints(ilixi::FixedConstraint, ilixi::FixedConstraint);\n if (!__iconPack)\n __iconPack = new ilixi::IconPack(DATADIR\"\/theme\/IconPack.xml\");\n}\n\nSimpleIcon::~SimpleIcon()\n{\n delete _image;\n}\n\nilixi::Size\nSimpleIcon::preferredSize() const\n{\n return ilixi::Size(24, 24);\n}\n\nvoid\nSimpleIcon::setImage(const std::string& name)\n{\n if (_image)\n delete _image;\n _image = __iconPack->getIcon(name);\n ilixi::Engine::instance().wakeUp();\n update();\n}\n\nvoid\nSimpleIcon::compose(const ilixi::PaintEvent& event)\n{\n if (_image)\n {\n ilixi::Painter p(this);\n p.begin(event);\n p.drawImage(_image, 0, 0);\n p.end();\n }\n}\n\n} \/* namespace MGUI *\/\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 QReal Research Group\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 \"randomFunctionChecker.h\"\n\n#include <qrgui\/plugins\/pluginManager\/editorManagerInterface.h>\n#include <qrrepo\/repoApi.h>\n#include <qrtext\/languageToolboxInterface.h>\n#include <qrtext\/lua\/ast\/functionCall.h>\n#include <qrtext\/lua\/ast\/identifier.h>\n\n#include \"parts\/randomGeneratorPart.h\"\n\nusing namespace pioneer::lua;\n\nRandomFunctionChecker::RandomFunctionChecker(\n\t\tconst qrRepo::RepoApi &repo\n\t\t, const qReal::EditorManagerInterface &metamodel\n\t\t, qrtext::LanguageToolboxInterface &languageToolbox\n\t\t, RandomGeneratorPart &randomGeneratorPart)\n\t: mRepo(repo)\n\t, mMetamodel(metamodel)\n\t, mLanguageToolbox(languageToolbox)\n\t, mRandomGeneratorPart(randomGeneratorPart)\n{\n}\n\nvoid RandomFunctionChecker::checkNode(const qReal::Id &id)\n{\n\tif (mRandomGeneratorPart.isUsed()) {\n\t\t\/\/ No point to do expensive AST walk if RNG will be initialized anyway.\n\t\treturn;\n\t}\n\n\tconst auto properties = mMetamodel.propertyNames(id.type());\n\tfor (const auto &property : properties) {\n\t\tconst auto ast = mLanguageToolbox.parse(id, property, mRepo.stringProperty(id, property));\n\t\tcheckAst(ast);\n\t}\n}\n\nvoid RandomFunctionChecker::checkAst(QSharedPointer<qrtext::core::ast::Node> ast)\n{\n\tif (ast->is<qrtext::lua::ast::FunctionCall>()) {\n\t\tauto call = qrtext::as<qrtext::lua::ast::FunctionCall>(ast);\n\t\tif (call->function()->is<qrtext::lua::ast::Identifier>()) {\n\t\t\t\/\/ We don't support indirect function calls here, but upstream text language tools do not support them\n\t\t\t\/\/ anyways.\n\t\t\tauto idNode = qrtext::as<qrtext::lua::ast::Identifier>(call->function());\n\t\t\tif (idNode->name() == \"random\") {\n\t\t\t\tmRandomGeneratorPart.registerUsage();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const auto child : ast->children()) {\n\t\tcheckAst(child);\n\t}\n}\n<commit_msg>Fixed crash when there is a semantic error in property<commit_after>\/* Copyright 2017 QReal Research Group\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 \"randomFunctionChecker.h\"\n\n#include <qrgui\/plugins\/pluginManager\/editorManagerInterface.h>\n#include <qrrepo\/repoApi.h>\n#include <qrtext\/languageToolboxInterface.h>\n#include <qrtext\/lua\/ast\/functionCall.h>\n#include <qrtext\/lua\/ast\/identifier.h>\n\n#include \"parts\/randomGeneratorPart.h\"\n\nusing namespace pioneer::lua;\n\nRandomFunctionChecker::RandomFunctionChecker(\n\t\tconst qrRepo::RepoApi &repo\n\t\t, const qReal::EditorManagerInterface &metamodel\n\t\t, qrtext::LanguageToolboxInterface &languageToolbox\n\t\t, RandomGeneratorPart &randomGeneratorPart)\n\t: mRepo(repo)\n\t, mMetamodel(metamodel)\n\t, mLanguageToolbox(languageToolbox)\n\t, mRandomGeneratorPart(randomGeneratorPart)\n{\n}\n\nvoid RandomFunctionChecker::checkNode(const qReal::Id &id)\n{\n\tif (mRandomGeneratorPart.isUsed()) {\n\t\t\/\/ No point to do expensive AST walk if RNG will be initialized anyway.\n\t\treturn;\n\t}\n\n\tconst auto properties = mMetamodel.propertyNames(id.type());\n\tfor (const auto &property : properties) {\n\t\tconst auto ast = mLanguageToolbox.parse(id, property, mRepo.stringProperty(id, property));\n\t\tif (!ast.isNull()) {\n\t\t\tcheckAst(ast);\n\t\t}\n\t}\n}\n\nvoid RandomFunctionChecker::checkAst(QSharedPointer<qrtext::core::ast::Node> ast)\n{\n\tif (ast->is<qrtext::lua::ast::FunctionCall>()) {\n\t\tauto call = qrtext::as<qrtext::lua::ast::FunctionCall>(ast);\n\t\tif (call->function()->is<qrtext::lua::ast::Identifier>()) {\n\t\t\t\/\/ We don't support indirect function calls here, but upstream text language tools do not support them\n\t\t\t\/\/ anyways.\n\t\t\tauto idNode = qrtext::as<qrtext::lua::ast::Identifier>(call->function());\n\t\t\tif (idNode->name() == \"random\") {\n\t\t\t\tmRandomGeneratorPart.registerUsage();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const auto child : ast->children()) {\n\t\tcheckAst(child);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file Transition.hpp\n * @author Duncan Campbell\n * @version 1.0\n *\n * @section LICENSE\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Duncan Campbell\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 all\n * 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 THE\n * SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * This class represents a transition from one state to another state. A\n * transition is composed of a trigger and an action. A trigger represents the\n * condition under which the trigger will activate. An action will represent\n * the measures that are taken to transition over to the next state.\n *\/\n\n#include <functional>\n\nnamespace StateTrans\n{\n using Trigger = std::function<bool()>;\n using Action = std::function<void()>;\n\n class Transition\n {\n public:\n Transition();\n Transition(Trigger, Action);\n ~Transition();\n\n bool CheckTrigger();\n void ExecuteAction();\n\n Trigger GetTrigger() const;\n void SetTrigger(const Trigger&);\n\n Action GetAction() const;\n void SetAction(const Action&);\n\n private:\n Trigger trigger;\n Action action;\n };\n\n} \/\/ end namespace\n<commit_msg>Add in documentation for transitions<commit_after>\/**\n * @file Transition.hpp\n * @author Duncan Campbell\n * @version 1.0\n *\n * @section LICENSE\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Duncan Campbell\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 all\n * 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 THE\n * SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * This class represents a transition from one state to another state. A\n * transition is composed of a trigger and an action. A trigger represents the\n * condition under which the trigger will activate. An action will represent\n * the measures that are taken to transition over to the next state.\n *\/\n\n#include <functional>\n\nnamespace StateTrans\n{\n using Trigger = std::function<bool()>;\n using Action = std::function<void()>;\n\n class Transition\n {\n public:\n \/**\n * Constructor for Transitions that takes no arguments\n *\/\n Transition();\n\n \/**\n * Constructor for Transitions that takes a Trigger and an Action\n *\n * @param trigger Trigger for the transition\n *\n * @param action Action for the Transitions\n *\/\n Transition(Trigger, Action);\n\n \/**\n * Destructor for Transitions\n *\/\n ~Transition();\n\n \/**\n * Checks the current state of the trigger for the Transition\n *\n * @return State of the Trigger\n *\/\n bool CheckTrigger();\n\n \/**\n * Executes the action of the Transition\n *\/\n void ExecuteAction();\n\n \/**\n * Get the Trigger for the Transition\n *\n * @return Trigger of the Transition\n *\/\n Trigger GetTrigger() const;\n\n \/**\n * Set the Trigger for the Transition\n *\n * @param trigger Trigger to be set\n *\/\n void SetTrigger(const Trigger&);\n\n \/**\n * Get the Action for the Transition\n *\n * @return Action of the Transition\n *\/\n Action GetAction() const;\n\n \/**\n * Set the Action for the Transition\n *\n * @param action Action to be set\n *\/\n void SetAction(const Action&);\n\n private:\n Trigger trigger;\n Action action;\n };\n\n} \/\/ end namespace\n<|endoftext|>"} {"text":"<commit_before>#include <OpenGLView.h>\n#include <FWPlatformBase.h>\n#include <Message.h>\n#include <Logger.h>\n\n#include <sstream>\n\n#ifdef __APPLE__\n#include <OpenGLES\/ES3\/gl.h>\n#else\n#include <GLES3\/gl3.h>\n#include <EGL\/egl.h>\n#include <EGL\/eglext.h>\n#endif\n\nusing namespace std;\n\nvoid\nOpenGLView::initialize(FWPlatformBase * _platform) {\n FWViewBase::initialize(_platform);\n sendMessage(Message(Message::CREATE_OPENGL_VIEW, getId()));\n logical_width = int(_platform->getDisplayWidth() \/ _platform->getDisplayScale());\n logical_height = int(_platform->getDisplayHeight() \/ _platform->getDisplayScale());\n actual_width = _platform->getDisplayWidth();\n actual_height = _platform->getDisplayHeight(); \n}\n\nvoid\nOpenGLView::checkGLError() {\n GLenum errLast = GL_NO_ERROR;\n for (;;) {\n GLenum err = glGetError();\n if (err == GL_NO_ERROR) {\n return;\n }\n\n \/\/ normally the error is reset by the call to glGetError() but if\n \/\/ glGetError() itself returns an error, we risk looping forever here\n \/\/ so check that we get a different error than the last time\n if (err == errLast) {\n getPlatform().getLogger().println(\"OpenGL error state couldn't be reset.\");\n return;\n }\n\n errLast = err;\n\n ostringstream s;\n s << \"got OpenGL error \" << err;\n getPlatform().getLogger().println(s.str());\n }\n}\n<commit_msg>add parent id<commit_after>#include <OpenGLView.h>\n#include <FWPlatformBase.h>\n#include <Message.h>\n#include <Logger.h>\n\n#include <sstream>\n\n#ifdef __APPLE__\n#include <OpenGLES\/ES3\/gl.h>\n#else\n#include <GLES3\/gl3.h>\n#include <EGL\/egl.h>\n#include <EGL\/eglext.h>\n#endif\n\nusing namespace std;\n\nvoid\nOpenGLView::initialize(FWPlatformBase * _platform) {\n FWViewBase::initialize(_platform);\n sendMessage(Message(Message::CREATE_OPENGL_VIEW, getId(), getParentId()));\n logical_width = int(_platform->getDisplayWidth() \/ _platform->getDisplayScale());\n logical_height = int(_platform->getDisplayHeight() \/ _platform->getDisplayScale());\n actual_width = _platform->getDisplayWidth();\n actual_height = _platform->getDisplayHeight(); \n}\n\nvoid\nOpenGLView::checkGLError() {\n GLenum errLast = GL_NO_ERROR;\n for (;;) {\n GLenum err = glGetError();\n if (err == GL_NO_ERROR) {\n return;\n }\n\n \/\/ normally the error is reset by the call to glGetError() but if\n \/\/ glGetError() itself returns an error, we risk looping forever here\n \/\/ so check that we get a different error than the last time\n if (err == errLast) {\n getPlatform().getLogger().println(\"OpenGL error state couldn't be reset.\");\n return;\n }\n\n errLast = err;\n\n ostringstream s;\n s << \"got OpenGL error \" << err;\n getPlatform().getLogger().println(s.str());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RealPlayer.cpp\n\/\/ SDL_Checkers\n\/\/\n\/\/ Created by Jacky Chiu on 2016-03-02.\n\/\/ Copyright © 2016 Jacky Chiu. All rights reserved.\n\/\/\n\n#include \"..\/include\/RealPlayer.h\"\n#include \"..\/include\/GameState.h\"\n\nRealPlayer::RealPlayer(bool topSide, CheckersBoard *board, Button *buttons): Player(topSide, board, buttons){\n xLocation = 0, yLocation = 0;\n selectingState = false;\n currentPieceIndex = 0;\n}\n\nRealPlayer::~RealPlayer(){\n delete Board;\n Board = NULL;\n delete boardButtons;\n boardButtons = NULL;\n}\n\nbool RealPlayer::makeMove(SDL_Event* event){\n\n if (event->type == SDL_MOUSEBUTTONDOWN) {\n \n \/\/ Selecting state for inital piece \/\/\n if (!selectingState) {\n for (int index=0; index<TOTAL_BUTTONS; index++) {\n if (boardButtons[index].insideButton(BUTTON_HEIGHT,BUTTON_WIDTH)) {\n \/\/ Player selects a piece to move \/\/\n selectPiece(boardButtons[index].getButtonPointX()\/80, boardButtons[index].getButtonPointY()\/80);\n break;\n }\n }\n }\n \/\/ Selecting for the piece to be moved \/\/\n else{\n for (int index=0; index<TOTAL_BUTTONS; index++) {\n if (boardButtons[index].insideButton(BUTTON_HEIGHT,BUTTON_WIDTH)) {\n \/\/buttonIndex = index;\n \/\/ Player selects where the piece should move \/\/\n if (selectedLocationIsValid(boardButtons[index].getButtonPointX()\/80, boardButtons[index].getButtonPointY()\/80)) {\n movePiece(currentPieceIndex, boardButtons[index].getButtonPointX()\/80, boardButtons[index].getButtonPointY()\/80);\n Board->turnHighLightOff();\n return true;\n }\n else {\n selectingState = false;\n Board->turnHighLightOff();\n return false;\n }\n }\n }\n }\n }\n return false;\n}\n\nvoid RealPlayer::selectPiece(int x, int y){\n \/\/ SELECT PIECE \/\/\n \/\/ When a piece hasn't been selected yet, and the button currently selected doesn't have a piece inside \/\/\n switch (Board->virtualBoard[x][y]) {\n case EMPTY_PIECE:\n cout<<\"Selected button isn't a piece\"<<endl;\n break;\n case RED_PIECE:\n xLocation = x;\n yLocation = y;\n currentPieceIndex = pieceTeamIndexByXY(x, y);\n Board->turnHighLightOn(x, y);\n selectingState = true;\n cout << \"Selected piece is:\\t(\" << x << \", \" << y << \")\" <<endl;\n break;\n case BLACK_PIECE:\n cout<<\"Piece isn't apart of your team\"<<endl;\n break;\n default:\n break;\n }\n}\n\nbool RealPlayer::selectedLocationIsValid(int x, int y) {\n cout << \"Selected location is:\\t(\" << x << \", \" << y << \")\" <<endl;\n bool locationIsValid = false;\n \/\/ realPlayer select only works for (topside == false) \/\/\n if (Board->virtualBoard[x][y] == EMPTY_PIECE) {\n\n \/\/ case 1: moving in a 3x3 square centered at the origin \/\/\n if (abs(x - xLocation) == 1 && abs(y - yLocation) == 1) {\n\n \/\/ case 1.1: piece is a king \/\/\n if (team[currentPieceIndex].isKing()) {\n locationIsValid = true;\n }\n\n \/\/ case 1.2: piece isn't a king \/\/\n else if (yLocation - y == 1) {\n locationIsValid = true;\n }\n }\n\n \/\/ case 2: moving in a 5x5 square centered at the origin to kill a piece \/\/\n else if (abs(x - xLocation) == 2 && abs(y - yLocation) == 2 && Board->virtualBoard[(x + xLocation)\/2][(y + yLocation)\/2] == BLACK_PIECE) {\n\n \/\/ case 2.1: piece is a king \/\/\n if (team[currentPieceIndex].isKing()) {\n locationIsValid = true;\n }\n\n \/\/ case 2.2: piece isn't a king \/\/\n else if (yLocation - y == 2) {\n locationIsValid = true;\n }\n }\n }\n \/\/ case 3: selects own piece to switch selection \/\/\n else if(Board->virtualBoard[x][y] == RED_PIECE){\n selectPiece(x, y);\n locationIsValid = false;\n }\n if (!locationIsValid) {\n cout<<\"cant move here\"<<endl;\n }\n else{\n selectingState = false;\n }\n return locationIsValid;\n}\n<commit_msg>Fixed highlight not being activated when switched pieces<commit_after>\/\/\n\/\/ RealPlayer.cpp\n\/\/ SDL_Checkers\n\/\/\n\/\/ Created by Jacky Chiu on 2016-03-02.\n\/\/ Copyright © 2016 Jacky Chiu. All rights reserved.\n\/\/\n\n#include \"..\/include\/RealPlayer.h\"\n#include \"..\/include\/GameState.h\"\n\nRealPlayer::RealPlayer(bool topSide, CheckersBoard *board, Button *buttons): Player(topSide, board, buttons){\n xLocation = 0, yLocation = 0;\n selectingState = false;\n currentPieceIndex = 0;\n}\n\nRealPlayer::~RealPlayer(){\n delete Board;\n Board = NULL;\n delete boardButtons;\n boardButtons = NULL;\n}\n\nbool RealPlayer::makeMove(SDL_Event* event){\n\n if (event->type == SDL_MOUSEBUTTONDOWN) {\n \n \/\/ Selecting state for inital piece \/\/\n if (!selectingState) {\n for (int index=0; index<TOTAL_BUTTONS; index++) {\n if (boardButtons[index].insideButton(BUTTON_HEIGHT,BUTTON_WIDTH)) {\n \/\/ Player selects a piece to move \/\/\n selectPiece(boardButtons[index].getButtonPointX()\/80, boardButtons[index].getButtonPointY()\/80);\n break;\n }\n }\n }\n \/\/ Selecting for the piece to be moved \/\/\n else{\n for (int index=0; index<TOTAL_BUTTONS; index++) {\n if (boardButtons[index].insideButton(BUTTON_HEIGHT,BUTTON_WIDTH)) {\n \/\/buttonIndex = index;\n \/\/ Player selects where the piece should move \/\/\n if (selectedLocationIsValid(boardButtons[index].getButtonPointX()\/80, boardButtons[index].getButtonPointY()\/80)) {\n movePiece(currentPieceIndex, boardButtons[index].getButtonPointX()\/80, boardButtons[index].getButtonPointY()\/80);\n Board->turnHighLightOff();\n return true;\n }\n else {\n selectingState = false;\n return false;\n }\n }\n }\n }\n }\n return false;\n}\n\nvoid RealPlayer::selectPiece(int x, int y){\n \/\/ SELECT PIECE \/\/\n \/\/ When a piece hasn't been selected yet, and the button currently selected doesn't have a piece inside \/\/\n switch (Board->virtualBoard[x][y]) {\n case EMPTY_PIECE:\n cout<<\"Selected button isn't a piece\"<<endl;\n break;\n case RED_PIECE:\n xLocation = x;\n yLocation = y;\n currentPieceIndex = pieceTeamIndexByXY(x, y);\n Board->turnHighLightOn(x, y);\n selectingState = true;\n cout << \"Selected piece is:\\t(\" << x << \", \" << y << \")\" <<endl;\n break;\n case BLACK_PIECE:\n cout<<\"Piece isn't apart of your team\"<<endl;\n break;\n default:\n break;\n }\n}\n\nbool RealPlayer::selectedLocationIsValid(int x, int y) {\n cout << \"Selected location is:\\t(\" << x << \", \" << y << \")\" <<endl;\n bool locationIsValid = false;\n \/\/ realPlayer select only works for (topside == false) \/\/\n if (Board->virtualBoard[x][y] == EMPTY_PIECE) {\n\n \/\/ case 1: moving in a 3x3 square centered at the origin \/\/\n if (abs(x - xLocation) == 1 && abs(y - yLocation) == 1) {\n\n \/\/ case 1.1: piece is a king \/\/\n if (team[currentPieceIndex].isKing()) {\n locationIsValid = true;\n }\n\n \/\/ case 1.2: piece isn't a king \/\/\n else if (yLocation - y == 1) {\n locationIsValid = true;\n }\n }\n\n \/\/ case 2: moving in a 5x5 square centered at the origin to kill a piece \/\/\n else if (abs(x - xLocation) == 2 && abs(y - yLocation) == 2 && Board->virtualBoard[(x + xLocation)\/2][(y + yLocation)\/2] == BLACK_PIECE) {\n\n \/\/ case 2.1: piece is a king \/\/\n if (team[currentPieceIndex].isKing()) {\n locationIsValid = true;\n }\n\n \/\/ case 2.2: piece isn't a king \/\/\n else if (yLocation - y == 2) {\n locationIsValid = true;\n }\n }\n }\n \/\/ case 3: selects own piece to switch selection \/\/\n else if(Board->virtualBoard[x][y] == RED_PIECE){\n selectPiece(x, y);\n locationIsValid = false;\n }\n if (!locationIsValid) {\n cout<<\"cant move here\"<<endl;\n }\n return locationIsValid;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <SerialComm.h>\n\n#ifdef __AVR__\n\t#define PLATFORM_VSNPRINTF(...) vsnprintf_P(__VA_ARGS__)\n#else\n\t#define PLATFORM_VSNPRINTF(...) vsnprintf(__VA_ARGS__)\n#endif\n\n\nSerialComm::SerialComm(Stream &s, int stream_buffer_size)\n: m_serial(s)\n, m_already_asked(false)\n, m_stream_buffer_capacity(stream_buffer_size - 1)\n\/\/ \/\/ Benchmark:\n\/\/ \/\/ send a file of size 22846 bytes.\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity) \/\/ 6.41 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 15 \/ 16) \/\/ 6.21 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 14 \/ 16) \/\/ 6.18 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 13 \/ 16) \/\/ 6.13 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 12 \/ 16) \/\/ 6.02 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 11 \/ 16) \/\/ 6.02 s\n, m_stream_buffer_threshold(m_stream_buffer_capacity * 10 \/ 16) \/\/ 6.02 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 9 \/ 16) \/\/ 6.02 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 8 \/ 16) \/\/ 6.03 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 7 \/ 16) \/\/ 6.03 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 6 \/ 16) \/\/ 6.04 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 5 \/ 16) \/\/ 6.06 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 4 \/ 16) \/\/ 6.07 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 3 \/ 16) \/\/ 6.11 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 2 \/ 16) \/\/ 6.17 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 1 \/ 16) \/\/ 6.37 s\n\/\/, m_stream_buffer_threshold(1) \/\/ 22.81 s\n, m_stream_buffer_checkpoint(0)\n, m_stream_count(0)\n{\n\tif (streamBufferThreshold() == 0) {\n\t\tsetStreamBufferThreshold(streamBufferCapacity());\n\t}\n\twhile (serial().available()) {\n\t\tserial().read();\n\t}\n\tReady(F(\"XSVF\"));\n}\n\nSerialComm::~SerialComm()\n{\n}\n\nvoid SerialComm::ask_for_data()\n{\n\tif (!alreadyAsked()) {\n\t\tcheckAndRequestData(true);\n\t\tsetAlreadyAsked();\n\t}\n}\n\nvoid SerialComm::Important(const __FlashStringHelper *ifsh, ...)\n{\n\tva_list args;\n\tva_start(args, ifsh);\n\tPLATFORM_VSNPRINTF(formatBuffer(), S_FORMAT_BUFFER_SIZE,\n\t\t(const char *)ifsh, args);\n\tva_end(args);\n\n\tserial().print(F(\"!\"));\n\tserial().println(formatBuffer());\n}\n\nvoid SerialComm::ImportantBits(const __FlashStringHelper *msg, const uint8_t *pb,\n\tuint32_t count_bits)\n{\n\tuint32_t count_bytes = (count_bits + 7) >> 3;\n\tserial().print(msg);\n\tprint_bytes(pb, count_bytes);\n\tserial().print(F(\"\/\"));\n\tserial().print(count_bits);\n\tserial().println(F(\" bits\"));\n}\n\nvoid SerialComm::checkAndRequestData(bool force)\n{\n\tif (force ||\n\t streamCount() % streamBufferCapacity() == streamBufferCheckpoint()) {\n\t\tupdateCheckpoint();\n\t\tint n = force ? streamBufferCapacity() : streamBufferThreshold();\n\t\tsnprintf(sendMsg(), sizeofSendMsg(), \"S%-4d\", n);\n\t\tserial().print(F(\"\\r\\n\"));\n\t\tserial().println(sendMsg());\n\t\tif (DEBUG) {\n\t\t\t\/\/ Print this so that an interrupted line is\n\t\t\t\/\/ still recognized by the python script.\n\t\t\tserial().print(F(\"D. >>> \"));\n\t\t}\n\t}\n}\n\nint SerialComm::nextByte()\n{\n\t\/\/ Wait for TIMEOUT milliseconds if the buffer is empty.\n\t\/\/unsigned const int TIMEOUT = 1000; \/\/ milliseconds\n\tunsigned const int TIMEOUT = 3000; \/\/ milliseconds\n\tunsigned long end_time = millis() + TIMEOUT;\n while (serial().available() <= 0 && millis() < end_time) {\n }\n \/\/ Return an invalid instruction\n\tint c = -1;\n\tint n = serial().available();\n\tif (n > 0) {\n\t\tc = serial().read();\n\t\tincStreamCount();\n\t\tcheckAndRequestData();\n\t} else {\n\t\tImportant(F(\"count: %ld, threshold: %d, mod: %ld, avail: %d\"),\n\t\t\tstreamCount(), streamBufferThreshold(),\n\t\t\tstreamCount() % streamBufferCapacity(),\n\t\t\tn);\n\t}\n\n\treturn c;\n}\n\n\/\/ Not needed, left here as example.\n#if 0\nvoid SerialComm::CopyToFlashBuffer(const __FlashStringHelper *ifsh)\n{\n\tPGM_P p = reinterpret_cast<PGM_P>(ifsh);\n\t\/\/ Truncate message to the flash buffer size\n\tstrncpy_P(flashBuffer(), p, S_FLASH_BUFFER_SIZE);\n\n\t\/\/ Left here as example of use of pgm_read_byte().\n\t\/*\n\tchar *s = flashBuffer();\n\tchar c;\n\tuint32_t n = S_FLASH_BUFFER_SIZE;\n\twhile (n-- && (c = pgm_read_byte(p++))) {\n\t\t*s++ = c;\n\t}\n\tif (n) {\n\t\t*s = 0;\n\t} else {\n\t\t*--s = 0;\n\t}\n\t*\/\n}\n#endif\n\n#if DEBUG == 1\n\nvoid SerialComm::DebugStartMessage() const\n{\n\tserial().print(F(\"D\"));\n}\n\nvoid SerialComm::DebugContMessage(const __FlashStringHelper *ifsh, ...)\n{\n\tva_list args;\n\tva_start(args, ifsh);\n\tPLATFORM_VSNPRINTF(formatBuffer(), S_FORMAT_BUFFER_SIZE,\n\t\t(const char *)ifsh, args);\n\tva_end(args);\n\tserial().print(formatBuffer());\n}\n\nvoid SerialComm::Debug(const __FlashStringHelper *ifsh, ...)\n{\n\tva_list args;\n\tva_start(args, ifsh);\n\tPLATFORM_VSNPRINTF(formatBuffer(), S_FORMAT_BUFFER_SIZE,\n\t\t(const char *)ifsh, args);\n\tva_end(args);\n\tDebugStartMessage();\n\tserial().println(formatBuffer());\n}\n\nvoid SerialComm::DebugBytes(const __FlashStringHelper *s, const uint8_t *b,\n\tuint8_t n)\n{\n\tDebugStartMessage();\n\tserial().print(s);\n\tprint_bytes(b, n);\n\tserial().println();\n}\n\n#else\n\nvoid SerialComm::DebugStartMessage() const {}\nvoid SerialComm::DebugContMessage(const __FlashStringHelper *ifsh, ...) {}\nvoid SerialComm::Debug(const __FlashStringHelper *fmt, ...) {}\nvoid SerialComm::DebugBytes(const __FlashStringHelper *s, const uint8_t* p, uint8_t n) {}\n\n#endif\n\nvoid SerialComm::Ready(const __FlashStringHelper *message) const\n{\n\tserial().print(F(\"\\r\\nR\"));\n\tserial().println(message);\n}\n\nvoid SerialComm::Quit(int error_code, const __FlashStringHelper *message) const\n{\n\tserial().print(F(\"\\r\\nQ\"));\n\tserial().print(error_code);\n\tserial().print(F(\",\"));\n\tserial().println(message);\n}\n\nvoid SerialComm::print_bytes(const uint8_t *pb, uint32_t count, bool lf)\n{\n\tconst unsigned char *p = reinterpret_cast<const unsigned char *>(pb);\n\tchar *fmt_msg = \" %02X\";\n\tint fmt_msg_size = 3;\n\twhile (count) {\n\t\tchar *f = formatBuffer();\n\t\tint buf_size = S_FORMAT_BUFFER_SIZE;\n\t\twhile (count && buf_size > 6) {\n\t\t\tsnprintf(f, buf_size, fmt_msg, *p);\n\t\t\tp++;\n\t\t\tf += fmt_msg_size;\n\t\t\tbuf_size -= fmt_msg_size;\n\t\t\tcount--;\n\t\t}\n\t\tif (count && buf_size <= 6) {\n\t\t\tserial().print(formatBuffer());\n\t\t}\n\t}\n\tif (lf) {\n\t\tserial().println(formatBuffer());\n\t} else {\n\t\tserial().print(formatBuffer());\n\t}\n}\n\n<commit_msg>Fix a bug when printing a zero bits sequence<commit_after>\n#include <SerialComm.h>\n\n#ifdef __AVR__\n\t#define PLATFORM_VSNPRINTF(...) vsnprintf_P(__VA_ARGS__)\n#else\n\t#define PLATFORM_VSNPRINTF(...) vsnprintf(__VA_ARGS__)\n#endif\n\n\nSerialComm::SerialComm(Stream &s, int stream_buffer_size)\n: m_serial(s)\n, m_already_asked(false)\n, m_stream_buffer_capacity(stream_buffer_size - 1)\n\/\/ \/\/ Benchmark:\n\/\/ \/\/ send a file of size 22846 bytes.\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity) \/\/ 6.41 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 15 \/ 16) \/\/ 6.21 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 14 \/ 16) \/\/ 6.18 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 13 \/ 16) \/\/ 6.13 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 12 \/ 16) \/\/ 6.02 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 11 \/ 16) \/\/ 6.02 s\n, m_stream_buffer_threshold(m_stream_buffer_capacity * 10 \/ 16) \/\/ 6.02 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 9 \/ 16) \/\/ 6.02 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 8 \/ 16) \/\/ 6.03 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 7 \/ 16) \/\/ 6.03 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 6 \/ 16) \/\/ 6.04 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 5 \/ 16) \/\/ 6.06 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 4 \/ 16) \/\/ 6.07 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 3 \/ 16) \/\/ 6.11 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 2 \/ 16) \/\/ 6.17 s\n\/\/, m_stream_buffer_threshold(m_stream_buffer_capacity * 1 \/ 16) \/\/ 6.37 s\n\/\/, m_stream_buffer_threshold(1) \/\/ 22.81 s\n, m_stream_buffer_checkpoint(0)\n, m_stream_count(0)\n{\n\tif (streamBufferThreshold() == 0) {\n\t\tsetStreamBufferThreshold(streamBufferCapacity());\n\t}\n\twhile (serial().available()) {\n\t\tserial().read();\n\t}\n\tReady(F(\"XSVF\"));\n}\n\nSerialComm::~SerialComm()\n{\n}\n\nvoid SerialComm::ask_for_data()\n{\n\tif (!alreadyAsked()) {\n\t\tcheckAndRequestData(true);\n\t\tsetAlreadyAsked();\n\t}\n}\n\nvoid SerialComm::Important(const __FlashStringHelper *ifsh, ...)\n{\n\tva_list args;\n\tva_start(args, ifsh);\n\tPLATFORM_VSNPRINTF(formatBuffer(), S_FORMAT_BUFFER_SIZE,\n\t\t(const char *)ifsh, args);\n\tva_end(args);\n\n\tserial().print(F(\"!\"));\n\tserial().println(formatBuffer());\n}\n\nvoid SerialComm::ImportantBits(const __FlashStringHelper *msg, const uint8_t *pb,\n\tuint32_t count_bits)\n{\n\tuint32_t count_bytes = (count_bits + 7) >> 3;\n\tserial().print(msg);\n\tprint_bytes(pb, count_bytes);\n\tserial().print(F(\"\/\"));\n\tserial().print(count_bits);\n\tserial().println(F(\" bits\"));\n}\n\nvoid SerialComm::checkAndRequestData(bool force)\n{\n\tif (force ||\n\t streamCount() % streamBufferCapacity() == streamBufferCheckpoint()) {\n\t\tupdateCheckpoint();\n\t\tint n = force ? streamBufferCapacity() : streamBufferThreshold();\n\t\tsnprintf(sendMsg(), sizeofSendMsg(), \"S%-4d\", n);\n\t\tserial().print(F(\"\\r\\n\"));\n\t\tserial().println(sendMsg());\n\t\tif (DEBUG) {\n\t\t\t\/\/ Print this so that an interrupted line is\n\t\t\t\/\/ still recognized by the python script.\n\t\t\tserial().print(F(\"D. >>> \"));\n\t\t}\n\t}\n}\n\nint SerialComm::nextByte()\n{\n\t\/\/ Wait for TIMEOUT milliseconds if the buffer is empty.\n\t\/\/unsigned const int TIMEOUT = 1000; \/\/ milliseconds\n\tunsigned const int TIMEOUT = 3000; \/\/ milliseconds\n\tunsigned long end_time = millis() + TIMEOUT;\n while (serial().available() <= 0 && millis() < end_time) {\n }\n \/\/ Return an invalid instruction\n\tint c = -1;\n\tint n = serial().available();\n\tif (n > 0) {\n\t\tc = serial().read();\n\t\tincStreamCount();\n\t\tcheckAndRequestData();\n\t} else {\n\t\tImportant(F(\"count: %ld, threshold: %d, mod: %ld, avail: %d\"),\n\t\t\tstreamCount(), streamBufferThreshold(),\n\t\t\tstreamCount() % streamBufferCapacity(),\n\t\t\tn);\n\t}\n\n\treturn c;\n}\n\n\/\/ Not needed, left here as example.\n#if 0\nvoid SerialComm::CopyToFlashBuffer(const __FlashStringHelper *ifsh)\n{\n\tPGM_P p = reinterpret_cast<PGM_P>(ifsh);\n\t\/\/ Truncate message to the flash buffer size\n\tstrncpy_P(flashBuffer(), p, S_FLASH_BUFFER_SIZE);\n\n\t\/\/ Left here as example of use of pgm_read_byte().\n\t\/*\n\tchar *s = flashBuffer();\n\tchar c;\n\tuint32_t n = S_FLASH_BUFFER_SIZE;\n\twhile (n-- && (c = pgm_read_byte(p++))) {\n\t\t*s++ = c;\n\t}\n\tif (n) {\n\t\t*s = 0;\n\t} else {\n\t\t*--s = 0;\n\t}\n\t*\/\n}\n#endif\n\n#if DEBUG == 1\n\nvoid SerialComm::DebugStartMessage() const\n{\n\tserial().print(F(\"D\"));\n}\n\nvoid SerialComm::DebugContMessage(const __FlashStringHelper *ifsh, ...)\n{\n\tva_list args;\n\tva_start(args, ifsh);\n\tPLATFORM_VSNPRINTF(formatBuffer(), S_FORMAT_BUFFER_SIZE,\n\t\t(const char *)ifsh, args);\n\tva_end(args);\n\tserial().print(formatBuffer());\n}\n\nvoid SerialComm::Debug(const __FlashStringHelper *ifsh, ...)\n{\n\tva_list args;\n\tva_start(args, ifsh);\n\tPLATFORM_VSNPRINTF(formatBuffer(), S_FORMAT_BUFFER_SIZE,\n\t\t(const char *)ifsh, args);\n\tva_end(args);\n\tDebugStartMessage();\n\tserial().println(formatBuffer());\n}\n\nvoid SerialComm::DebugBytes(const __FlashStringHelper *s, const uint8_t *b,\n\tuint8_t n)\n{\n\tDebugStartMessage();\n\tserial().print(s);\n\tprint_bytes(b, n);\n\tserial().println();\n}\n\n#else\n\nvoid SerialComm::DebugStartMessage() const {}\nvoid SerialComm::DebugContMessage(const __FlashStringHelper *ifsh, ...) {}\nvoid SerialComm::Debug(const __FlashStringHelper *fmt, ...) {}\nvoid SerialComm::DebugBytes(const __FlashStringHelper *s, const uint8_t* p, uint8_t n) {}\n\n#endif\n\nvoid SerialComm::Ready(const __FlashStringHelper *message) const\n{\n\tserial().print(F(\"\\r\\nR\"));\n\tserial().println(message);\n}\n\nvoid SerialComm::Quit(int error_code, const __FlashStringHelper *message) const\n{\n\tserial().print(F(\"\\r\\nQ\"));\n\tserial().print(error_code);\n\tserial().print(F(\",\"));\n\tserial().println(message);\n}\n\nvoid SerialComm::print_bytes(const uint8_t *pb, uint32_t count, bool lf)\n{\n\tif (!count) {\n\t\tif (lf) {\n\t\t\tserial().println(F(\" \"));\n\t\t} else {\n\t\t\tserial().print(F(\" \"));\n\t\t}\n\t\treturn;\n\t}\n\tconst unsigned char *p = reinterpret_cast<const unsigned char *>(pb);\n\tchar *fmt_msg = \" %02X\";\n\tint fmt_msg_size = 3;\n\twhile (count) {\n\t\tchar *f = formatBuffer();\n\t\tint buf_size = S_FORMAT_BUFFER_SIZE;\n\t\twhile (count && buf_size > 6) {\n\t\t\tsnprintf(f, buf_size, fmt_msg, *p);\n\t\t\tp++;\n\t\t\tf += fmt_msg_size;\n\t\t\tbuf_size -= fmt_msg_size;\n\t\t\tcount--;\n\t\t}\n\t\tif (count && buf_size <= 6) {\n\t\t\tserial().print(formatBuffer());\n\t\t}\n\t}\n\tif (lf) {\n\t\tserial().println(formatBuffer());\n\t} else {\n\t\tserial().print(formatBuffer());\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n\n#include <eosio\/chain\/block_log.hpp>\n#include <eosio\/chain\/global_property_object.hpp>\n#include <eosio\/chain\/snapshot.hpp>\n#include <eosio\/testing\/tester.hpp>\n\n#include <boost\/mpl\/list.hpp>\n#include <boost\/test\/unit_test.hpp>\n\n#include <contracts.hpp>\n#include <snapshots.hpp>\n\nusing namespace eosio;\nusing namespace testing;\nusing namespace chain;\n\nvoid remove_existing_blocks(controller::config& config) {\n auto block_log_path = config.blocks_dir \/ \"blocks.log\";\n remove(block_log_path);\n auto block_index_path = config.blocks_dir \/ \"blocks.index\";\n remove(block_index_path);\n}\n\nBOOST_AUTO_TEST_SUITE(restart_chain_tests)\n\nBOOST_AUTO_TEST_CASE(test_existing_state_without_block_log)\n{\n tester chain;\n\n chain.create_account(N(snapshot));\n std::vector<signed_block_ptr> blocks;\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n\n tester other;\n for (auto new_block : blocks) {\n other.push_block(new_block);\n }\n blocks.clear();\n\n other.close();\n auto cfg = other.get_config();\n remove_existing_blocks(cfg);\n \/\/ restarting chain with no block log and no genesis\n other.open();\n\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n chain.control->abort_block();\n\n for (auto new_block : blocks) {\n other.push_block(new_block);\n }\n}\n\nBOOST_AUTO_TEST_CASE(test_restart_with_different_chain_id)\n{\n tester chain;\n\n chain.create_account(N(snapshot));\n std::vector<signed_block_ptr> blocks;\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n\n tester other;\n for (auto new_block : blocks) {\n other.push_block(new_block);\n }\n blocks.clear();\n\n other.close();\n genesis_state genesis;\n genesis.initial_timestamp = fc::time_point::from_iso_string(\"2020-01-01T00:00:00.999\");\n genesis.initial_key = eosio::testing::base_tester::get_public_key( config::system_account_name, \"active\" );\n fc::optional<chain_id_type> chain_id = genesis.compute_chain_id();\n BOOST_REQUIRE_EXCEPTION(other.open(chain_id), block_log_exception, fc_exception_message_starts_with(\"Controller configured with: \"));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Fixed expected exception.<commit_after>#include <sstream>\n\n#include <eosio\/chain\/block_log.hpp>\n#include <eosio\/chain\/global_property_object.hpp>\n#include <eosio\/chain\/snapshot.hpp>\n#include <eosio\/testing\/tester.hpp>\n\n#include <boost\/mpl\/list.hpp>\n#include <boost\/test\/unit_test.hpp>\n\n#include <contracts.hpp>\n#include <snapshots.hpp>\n\nusing namespace eosio;\nusing namespace testing;\nusing namespace chain;\n\nvoid remove_existing_blocks(controller::config& config) {\n auto block_log_path = config.blocks_dir \/ \"blocks.log\";\n remove(block_log_path);\n auto block_index_path = config.blocks_dir \/ \"blocks.index\";\n remove(block_index_path);\n}\n\nBOOST_AUTO_TEST_SUITE(restart_chain_tests)\n\nBOOST_AUTO_TEST_CASE(test_existing_state_without_block_log)\n{\n tester chain;\n\n chain.create_account(N(snapshot));\n std::vector<signed_block_ptr> blocks;\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n\n tester other;\n for (auto new_block : blocks) {\n other.push_block(new_block);\n }\n blocks.clear();\n\n other.close();\n auto cfg = other.get_config();\n remove_existing_blocks(cfg);\n \/\/ restarting chain with no block log and no genesis\n other.open();\n\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n chain.control->abort_block();\n\n for (auto new_block : blocks) {\n other.push_block(new_block);\n }\n}\n\nBOOST_AUTO_TEST_CASE(test_restart_with_different_chain_id)\n{\n tester chain;\n\n chain.create_account(N(snapshot));\n std::vector<signed_block_ptr> blocks;\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n blocks.push_back(chain.produce_block());\n\n tester other;\n for (auto new_block : blocks) {\n other.push_block(new_block);\n }\n blocks.clear();\n\n other.close();\n genesis_state genesis;\n genesis.initial_timestamp = fc::time_point::from_iso_string(\"2020-01-01T00:00:00.999\");\n genesis.initial_key = eosio::testing::base_tester::get_public_key( config::system_account_name, \"active\" );\n fc::optional<chain_id_type> chain_id = genesis.compute_chain_id();\n BOOST_REQUIRE_EXCEPTION(other.open(chain_id), chain_id_type_exception, fc_exception_message_starts_with(\"chain ID in state \"));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\n#include <QApplication>\n#include <QKeyEvent>\n#include <QPushButton>\n#include \"GLModelViewer.h\"\n#include \"GLModel.h\"\n#include \"GLShaderProgram.h\"\n#include \"Grid.h\"\n#include <iostream>\n#include <chrono>\n#include <sstream>\n#include <fstream>\n#include <Eigen\/Dense>\n#include \"Timer.h\"\n#include \"Projection.h\"\n#include \"Volumetric_helper.h\"\n\n\n\n\n\n#if 0\nvoid raycast_volume()\n{\n\ttimer.start();\n\n\tEigen::Vector3d origin = T.first.col(3).head<3>();\n\tEigen::Vector3d window_coord_norm;\n\n\tstd::vector<Eigen::Vector3d> output_cloud;\n\n\t\/\/ Sweep the volume looking for the zero crossing\n\tfor (int y = 0; y < window_height * 0.1; ++y)\n\t{\n\t\tstd::cout << \"Ray casting to image... \" << (double)y \/ window_height * 100 << \"%\" << std::endl;\n\n\t\tfor (int x = 0; x < window_width * 0.1; ++x)\n\t\t{\n\t\t\twindow_coord_norm.x() = ((double)x \/ window_width * 2.0) - 1.0;\n\t\t\twindow_coord_norm.y() = ((double)y \/ window_height * 2.0) - 1.0;\n\t\t\twindow_coord_norm.z() = origin.z() + near_plane;\n\t\t\tEigen::Vector3d direction = (window_coord_norm - origin).normalized();\n\n\t\t\tstd::vector<int> intersections = Grid::find_intersections(grid.data, volume_size, voxel_size, grid.transformation, origin, direction, near_plane, far_plane);\n\t\t\tGrid::sort_intersections(intersections, grid.data, origin);\n\n\t\t\tfor (int i = 1; i < intersections.size(); ++i)\n\t\t\t{\n\t\t\t\tconst Voxeld& prev = grid.data.at(i - 1);\n\t\t\t\tconst Voxeld& curr = grid.data.at(i);\n\n\t\t\t\tconst bool& same_sign = ((prev.tsdf < 0) == (curr.tsdf < 0));\n\n\t\t\t\tif (!same_sign)\t\t\/\/ it is a zero-crossing\n\t\t\t\t{\n\t\t\t\t\toutput_cloud.push_back(curr.point);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttimer.print_interval(\"Raycasting volume : \");\n\n\n\texport_obj(\"..\/..\/data\/output_cloud.obj\", output_cloud);\n}\n#endif\n\n\/\/ Usage: .\/Volumetricd.exe ..\/..\/data\/plane.obj 256 8 2 90\nint main(int argc, char **argv)\n{\n\tif (argc < 6)\n\t{\n\t\tstd::cerr << \"Missing parameters. Abort.\" \n\t\t\t<< std::endl\n\t\t\t<< \"Usage: .\/Volumetricd.exe ..\/..\/data\/monkey.obj 256 8 2 90\"\n\t\t\t<< std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tTimer timer;\n\tconst std::string filepath = argv[1];\n\tconst int vol_size = atoi(argv[2]);\n\tconst int vx_size = atoi(argv[3]);\n\tconst int cloud_count = atoi(argv[4]);\n\tconst int rot_interval = atoi(argv[5]);\n\n\tstd::pair<std::vector<double>, std::vector<double>> depth_buffer;\n\n\t\/\/\n\t\/\/ Projection and Modelview Matrices\n\t\/\/\n\tEigen::Matrix4d K = perspective_matrix(fov_y, aspect_ratio, near_plane, far_plane);\n\tstd::pair<Eigen::Matrix4d, Eigen::Matrix4d>\tT(Eigen::Matrix4d::Identity(), Eigen::Matrix4d::Identity());\n\n\n\t\/\/\n\t\/\/ Creating volume\n\t\/\/\n\tEigen::Vector3d voxel_size(vx_size, vx_size, vx_size);\n\tEigen::Vector3d volume_size(vol_size, vol_size, vol_size);\n\tEigen::Vector3d voxel_count(volume_size.x() \/ voxel_size.x(), volume_size.y() \/ voxel_size.y(), volume_size.z() \/ voxel_size.z());\n\t\/\/\n\tEigen::Affine3d grid_affine = Eigen::Affine3d::Identity();\n\tgrid_affine.translate(Eigen::Vector3d(0, 0, -256));\n\tgrid_affine.scale(Eigen::Vector3d(1, 1, -1));\t\/\/ z is negative inside of screen\n#if 0\n\tGrid grid(volume_size, voxel_size, grid_affine.matrix());\n\n\n\t\/\/\n\t\/\/ Importing .obj\n\t\/\/\n\ttimer.start();\n\tstd::vector<Eigen::Vector3d> points3DOrig, pointsTmp;\n\timport_obj(filepath, points3DOrig);\n\ttimer.print_interval(\"Importing monkey : \");\n\tstd::cout << \"Monkey point count : \" << points3DOrig.size() << std::endl;\n\n\t\/\/ \n\t\/\/ Translating and rotating monkey point cloud \n\tstd::pair<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3d>> cloud;\n\t\/\/\n\tEigen::Affine3d rotate = Eigen::Affine3d::Identity();\n\tEigen::Affine3d translate = Eigen::Affine3d::Identity();\n\ttranslate.translate(Eigen::Vector3d(0, 0, -256));\n\n\n\t\/\/ \n\t\/\/ Compute first cloud\n\t\/\/\n\tfor (Eigen::Vector3d p3d : points3DOrig)\n\t{\n\t\tEigen::Vector4d rot = translate.matrix() * rotate.matrix() * p3d.homogeneous();\n\t\trot \/= rot.w();\n\t\tcloud.first.push_back(rot.head<3>());\n\t}\n\t\/\/\n\t\/\/ Update grid with first cloud\n\t\/\/\n\ttimer.start();\n\tcreate_depth_buffer(depth_buffer.first, cloud.first, K, Eigen::Matrix4d::Identity(), far_plane);\n\ttimer.print_interval(\"CPU compute depth : \");\n\n\ttimer.start();\n\tupdate_volume(grid, depth_buffer.first, K, T.first);\n\ttimer.print_interval(\"CPU Update volume : \");\n\n\t\/\/\n\t\/\/ Compute next clouds\n\tEigen::Matrix4d cloud_mat = Eigen::Matrix4d::Identity();\n\tTimer iter_timer;\n\tfor (int i = 1; i < cloud_count; ++i)\n\t{\n\t\tstd::cout << std::endl << i << \" : \" << i * rot_interval << std::endl;\n\t\titer_timer.start();\n\n\t\t\/\/ Rotation matrix\n\t\trotate = Eigen::Affine3d::Identity();\n\t\trotate.rotate(Eigen::AngleAxisd(DegToRad(i * rot_interval), Eigen::Vector3d::UnitY()));\n\n\t\tcloud.second.clear();\n\t\tfor (Eigen::Vector3d p3d : points3DOrig)\n\t\t{\n\t\t\tEigen::Vector4d rot = translate.matrix() * rotate.matrix() * p3d.homogeneous();\n\t\t\trot \/= rot.w();\n\t\t\tcloud.second.push_back(rot.head<3>());\n\t\t}\n\n\t\t\/\/export_obj(\"..\/..\/data\/cloud_cpu_2.obj\", cloud.second);\n\n\t\ttimer.start();\n\t\tcreate_depth_buffer(depth_buffer.second, cloud.second, K, Eigen::Matrix4d::Identity(), far_plane);\n\t\ttimer.print_interval(\"Compute depth buffer: \");\n\n\t\t\/\/export_depth_buffer(\"..\/..\/data\/cpu_depth_buffer_2.obj\", depth_buffer.second);\n\n\t\ttimer.start();\n\t\tEigen::Matrix4d icp_mat;\n\t\tComputeRigidTransform(cloud.first, cloud.second, icp_mat);\n\t\ttimer.print_interval(\"Compute rigid transf: \");\n\n\t\t\/\/std::cout << std::fixed << std::endl << \"icp_mat \" << std::endl << icp_mat << std::endl;\n\n\t\t\/\/ accumulate matrix\n\t\tcloud_mat = cloud_mat * icp_mat;\n\n\t\t\/\/std::cout << std::fixed << std::endl << \"cloud_mat \" << std::endl << cloud_mat << std::endl;\n\n\t\ttimer.start();\n\t\t\/\/update_volume(grid, depth_buffer.second, K, cloud_mat.inverse());\n\t\tupdate_volume(grid, depth_buffer.second, K, cloud_mat.inverse());\n\t\ttimer.print_interval(\"Update volume : \");\n\n\n\t\t\/\/ copy second point cloud to first\n\t\tcloud.first = cloud.second;\n\t\t\/\/depth_buffer.first = depth_buffer.second;\n\n\t\titer_timer.print_interval(\"Iteration time : \");\n\t}\n\n\n\t\/\/std::cout << \"------- \/\/ --------\" << std::endl;\n\t\/\/for (int i = 0; i < grid.data.size(); ++i)\n\t\/\/{\n\t\/\/\tconst Eigen::Vector3d& point = grid.data[i].point;\n\n\t\/\/\tstd::cout << point.transpose() << \"\\t\\t\" << grid.data[i].tsdf << \" \" << grid.data[i].weight << std::endl;\n\t\/\/}\n\t\/\/std::cout << \"------- \/\/ --------\" << std::endl;\n\n\ttimer.start();\n\texport_volume(\"..\/..\/data\/grid_volume_cpu.obj\", grid.data);\n\ttimer.print_interval(\"Exporting volume : \");\n#endif\n\n\n\tQApplication app(argc, argv);\n\n#if 0\n\n\t\/\/\n\t\/\/ setup opengl viewer\n\t\/\/ \n\tGLModelViewer glwidget;\n\tglwidget.resize(640, 480);\n\tglwidget.setPerspective(60.0f, 0.1f, 1024.0f);\n\tglwidget.move(320, 0);\n\tglwidget.setWindowTitle(\"Point Cloud\");\n\tglwidget.setWeelSpeed(0.1f);\n\tglwidget.setDistance(-0.5f);\n\tglwidget.show();\n\n\n\ttimer.start();\n\tstd::vector<Eigen::Vector4f> points3DOrig;\n\timport_obj(filepath, points3DOrig);\n\ttimer.print_interval(\"Importing monkey : \");\n\tstd::cout << \"Monkey point count : \" << points3DOrig.size() << std::endl;\n\n\t\/\/\n\t\/\/ setup model\n\t\/\/ \n\tstd::shared_ptr<GLModel> cloud(new GLModel);\n\tcloud->initGL();\n\tcloud->setVertices(&points3DOrig[0][0], points3DOrig.size(), 4);\n\tcloud->setNormals(&points3DOrig[0][0], points3DOrig.size(), 4);\n\tcloud->transform().rotate(180, 0, 1, 0);\n\tglwidget.addModel(cloud);\n\n\n\t\/\/\n\t\/\/ setup kinect shader program\n\t\/\/ \n\tstd::shared_ptr<GLShaderProgram> kinectShaderProgram(new GLShaderProgram);\n\tif (kinectShaderProgram->build(\"color.vert\", \"color.frag\"))\n\t\tcloud->setShaderProgram(kinectShaderProgram);\n\n#else\n\n\n\t\/\/\n\t\/\/ setup opengl viewer\n\t\/\/ \n\tGLModelViewer glwidget;\n\tglwidget.resize(640, 480);\n\tglwidget.setPerspective(60.0f, 0.1f, 1024.0f);\n\tglwidget.move(320, 0);\n\tglwidget.setWindowTitle(\"Point Cloud\");\n\tglwidget.setWeelSpeed(0.1f);\n\tglwidget.setDistance(-0.5f);\n\tglwidget.show();\n\n\t\n\tEigen::Matrix4d to_origin = Eigen::Matrix4d::Identity();\n\tto_origin.col(3) << -(volume_size.x() \/ 2.0), -(volume_size.y() \/ 2.0), -(volume_size.z() \/ 2.0), 1.0;\t\/\/ set translate\n\n\n\tstd::vector<Eigen::Vector4f> vertices, colors;\n\n\tint i = 0;\n\tfor (int z = 0; z <= volume_size.z(); z += voxel_size.z())\n\t{\n\t\tfor (int y = 0; y <= volume_size.y(); y += voxel_size.y())\n\t\t{\n\t\t\tfor (int x = 0; x <= volume_size.x(); x += voxel_size.x(), i++)\n\t\t\t{\n\t\t\t\tEigen::Vector4d p = grid_affine.matrix() * to_origin * Eigen::Vector4d(x, y, z, 1);\n\t\t\t\tp \/= p.w();\n\t\t\t\tvertices.push_back(p.cast<float>());\n\n\t\t\t\tcolors.push_back(Eigen::Vector4f(1, 1, 0, 1));\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\n\t\/\/\n\t\/\/ setup model\n\t\/\/ \n\tstd::shared_ptr<GLModel> model(new GLModel);\n\tmodel->initGL();\n\tmodel->setVertices(&vertices[0][0], vertices.size(), 4);\n\tmodel->setColors(&colors[0][0], colors.size(), 4);\n\tglwidget.addModel(model);\n\n\n\t\/\/\n\t\/\/ setup kinect shader program\n\t\/\/ \n\tstd::shared_ptr<GLShaderProgram> kinectShaderProgram(new GLShaderProgram);\n\tif (kinectShaderProgram->build(\"color.vert\", \"color.frag\"))\n\t\tmodel->setShaderProgram(kinectShaderProgram);\n\n\n#endif\n\n\treturn app.exec();\n}\n\n\n\n<commit_msg>Viewing grid on screen<commit_after>\n#include <QApplication>\n#include <QKeyEvent>\n#include <QPushButton>\n#include \"GLModelViewer.h\"\n#include \"GLModel.h\"\n#include \"GLShaderProgram.h\"\n#include \"Grid.h\"\n#include <iostream>\n#include <chrono>\n#include <sstream>\n#include <fstream>\n#include <Eigen\/Dense>\n#include \"Timer.h\"\n#include \"Projection.h\"\n#include \"Volumetric_helper.h\"\n\n\n\n\n\n#if 0\nvoid raycast_volume()\n{\n\ttimer.start();\n\n\tEigen::Vector3d origin = T.first.col(3).head<3>();\n\tEigen::Vector3d window_coord_norm;\n\n\tstd::vector<Eigen::Vector3d> output_cloud;\n\n\t\/\/ Sweep the volume looking for the zero crossing\n\tfor (int y = 0; y < window_height * 0.1; ++y)\n\t{\n\t\tstd::cout << \"Ray casting to image... \" << (double)y \/ window_height * 100 << \"%\" << std::endl;\n\n\t\tfor (int x = 0; x < window_width * 0.1; ++x)\n\t\t{\n\t\t\twindow_coord_norm.x() = ((double)x \/ window_width * 2.0) - 1.0;\n\t\t\twindow_coord_norm.y() = ((double)y \/ window_height * 2.0) - 1.0;\n\t\t\twindow_coord_norm.z() = origin.z() + near_plane;\n\t\t\tEigen::Vector3d direction = (window_coord_norm - origin).normalized();\n\n\t\t\tstd::vector<int> intersections = Grid::find_intersections(grid.data, volume_size, voxel_size, grid.transformation, origin, direction, near_plane, far_plane);\n\t\t\tGrid::sort_intersections(intersections, grid.data, origin);\n\n\t\t\tfor (int i = 1; i < intersections.size(); ++i)\n\t\t\t{\n\t\t\t\tconst Voxeld& prev = grid.data.at(i - 1);\n\t\t\t\tconst Voxeld& curr = grid.data.at(i);\n\n\t\t\t\tconst bool& same_sign = ((prev.tsdf < 0) == (curr.tsdf < 0));\n\n\t\t\t\tif (!same_sign)\t\t\/\/ it is a zero-crossing\n\t\t\t\t{\n\t\t\t\t\toutput_cloud.push_back(curr.point);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttimer.print_interval(\"Raycasting volume : \");\n\n\n\texport_obj(\"..\/..\/data\/output_cloud.obj\", output_cloud);\n}\n#endif\n\n\/\/ Usage: .\/Volumetricd.exe ..\/..\/data\/plane.obj 256 8 2 90\nint main(int argc, char **argv)\n{\n\tif (argc < 6)\n\t{\n\t\tstd::cerr << \"Missing parameters. Abort.\" \n\t\t\t<< std::endl\n\t\t\t<< \"Usage: .\/Volumetricd.exe ..\/..\/data\/monkey.obj 256 8 2 90\"\n\t\t\t<< std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tTimer timer;\n\tconst std::string filepath = argv[1];\n\tconst int vol_size = atoi(argv[2]);\n\tconst int vx_size = atoi(argv[3]);\n\tconst int cloud_count = atoi(argv[4]);\n\tconst int rot_interval = atoi(argv[5]);\n\n\tstd::pair<std::vector<double>, std::vector<double>> depth_buffer;\n\n\t\/\/\n\t\/\/ Projection and Modelview Matrices\n\t\/\/\n\tEigen::Matrix4d K = perspective_matrix(fov_y, aspect_ratio, near_plane, far_plane);\n\tstd::pair<Eigen::Matrix4d, Eigen::Matrix4d>\tT(Eigen::Matrix4d::Identity(), Eigen::Matrix4d::Identity());\n\n\n\t\/\/\n\t\/\/ Creating volume\n\t\/\/\n\tEigen::Vector3d voxel_size(vx_size, vx_size, vx_size);\n\tEigen::Vector3d volume_size(vol_size, vol_size, vol_size);\n\tEigen::Vector3d voxel_count(volume_size.x() \/ voxel_size.x(), volume_size.y() \/ voxel_size.y(), volume_size.z() \/ voxel_size.z());\n\t\/\/\n\tEigen::Affine3d grid_affine = Eigen::Affine3d::Identity();\n\tgrid_affine.translate(Eigen::Vector3d(0, 0, -256));\n\tgrid_affine.scale(Eigen::Vector3d(1, 1, -1));\t\/\/ z is negative inside of screen\n\n\n\tGrid grid(volume_size, voxel_size, grid_affine.matrix());\n\n\n\t\/\/\n\t\/\/ Importing .obj\n\t\/\/\n\ttimer.start();\n\tstd::vector<Eigen::Vector3d> points3DOrig, pointsTmp;\n\timport_obj(filepath, points3DOrig);\n\ttimer.print_interval(\"Importing monkey : \");\n\tstd::cout << \"Monkey point count : \" << points3DOrig.size() << std::endl;\n\n\t\/\/ \n\t\/\/ Translating and rotating monkey point cloud \n\tstd::pair<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3d>> cloud;\n\t\/\/\n\tEigen::Affine3d rotate = Eigen::Affine3d::Identity();\n\tEigen::Affine3d translate = Eigen::Affine3d::Identity();\n\ttranslate.translate(Eigen::Vector3d(0, 0, -256));\n\n\n\t\/\/ \n\t\/\/ Compute first cloud\n\t\/\/\n\tfor (Eigen::Vector3d p3d : points3DOrig)\n\t{\n\t\tEigen::Vector4d rot = translate.matrix() * rotate.matrix() * p3d.homogeneous();\n\t\trot \/= rot.w();\n\t\tcloud.first.push_back(rot.head<3>());\n\t}\n\t\/\/\n\t\/\/ Update grid with first cloud\n\t\/\/\n\ttimer.start();\n\tcreate_depth_buffer(depth_buffer.first, cloud.first, K, Eigen::Matrix4d::Identity(), far_plane);\n\ttimer.print_interval(\"CPU compute depth : \");\n\n\ttimer.start();\n\tupdate_volume(grid, depth_buffer.first, K, T.first);\n\ttimer.print_interval(\"CPU Update volume : \");\n\n\t\/\/\n\t\/\/ Compute next clouds\n\tEigen::Matrix4d cloud_mat = Eigen::Matrix4d::Identity();\n\tTimer iter_timer;\n\tfor (int i = 1; i < cloud_count; ++i)\n\t{\n\t\tstd::cout << std::endl << i << \" : \" << i * rot_interval << std::endl;\n\t\titer_timer.start();\n\n\t\t\/\/ Rotation matrix\n\t\trotate = Eigen::Affine3d::Identity();\n\t\trotate.rotate(Eigen::AngleAxisd(DegToRad(i * rot_interval), Eigen::Vector3d::UnitY()));\n\n\t\tcloud.second.clear();\n\t\tfor (Eigen::Vector3d p3d : points3DOrig)\n\t\t{\n\t\t\tEigen::Vector4d rot = translate.matrix() * rotate.matrix() * p3d.homogeneous();\n\t\t\trot \/= rot.w();\n\t\t\tcloud.second.push_back(rot.head<3>());\n\t\t}\n\n\t\t\/\/export_obj(\"..\/..\/data\/cloud_cpu_2.obj\", cloud.second);\n\n\t\ttimer.start();\n\t\tcreate_depth_buffer(depth_buffer.second, cloud.second, K, Eigen::Matrix4d::Identity(), far_plane);\n\t\ttimer.print_interval(\"Compute depth buffer: \");\n\n\t\t\/\/export_depth_buffer(\"..\/..\/data\/cpu_depth_buffer_2.obj\", depth_buffer.second);\n\n\t\ttimer.start();\n\t\tEigen::Matrix4d icp_mat;\n\t\tComputeRigidTransform(cloud.first, cloud.second, icp_mat);\n\t\ttimer.print_interval(\"Compute rigid transf: \");\n\n\t\t\/\/std::cout << std::fixed << std::endl << \"icp_mat \" << std::endl << icp_mat << std::endl;\n\n\t\t\/\/ accumulate matrix\n\t\tcloud_mat = cloud_mat * icp_mat;\n\n\t\t\/\/std::cout << std::fixed << std::endl << \"cloud_mat \" << std::endl << cloud_mat << std::endl;\n\n\t\ttimer.start();\n\t\t\/\/update_volume(grid, depth_buffer.second, K, cloud_mat.inverse());\n\t\tupdate_volume(grid, depth_buffer.second, K, cloud_mat.inverse());\n\t\ttimer.print_interval(\"Update volume : \");\n\n\n\t\t\/\/ copy second point cloud to first\n\t\tcloud.first = cloud.second;\n\t\t\/\/depth_buffer.first = depth_buffer.second;\n\n\t\titer_timer.print_interval(\"Iteration time : \");\n\t}\n\n\n\t\/\/std::cout << \"------- \/\/ --------\" << std::endl;\n\t\/\/for (int i = 0; i < grid.data.size(); ++i)\n\t\/\/{\n\t\/\/\tconst Eigen::Vector3d& point = grid.data[i].point;\n\n\t\/\/\tstd::cout << point.transpose() << \"\\t\\t\" << grid.data[i].tsdf << \" \" << grid.data[i].weight << std::endl;\n\t\/\/}\n\t\/\/std::cout << \"------- \/\/ --------\" << std::endl;\n\n\/\/\ttimer.start();\n\/\/\texport_volume(\"..\/..\/data\/grid_volume_cpu.obj\", grid.data);\n\/\/\ttimer.print_interval(\"Exporting volume : \");\n\/\/\treturn 0;\n\n\n\tQApplication app(argc, argv);\n\n\t\/\/\n\t\/\/ setup opengl viewer\n\t\/\/ \n\tGLModelViewer glwidget;\n\tglwidget.resize(640, 480);\n\tglwidget.setPerspective(60.0f, 0.1f, 1024.0f);\n\tglwidget.move(320, 0);\n\tglwidget.setWindowTitle(\"Point Cloud\");\n\tglwidget.setWeelSpeed(0.1f);\n\tglwidget.setDistance(-0.5f);\n\tglwidget.show();\n\n\t\n\tEigen::Matrix4d to_origin = Eigen::Matrix4d::Identity();\n\tto_origin.col(3) << -(volume_size.x() \/ 2.0), -(volume_size.y() \/ 2.0), -(volume_size.z() \/ 2.0), 1.0;\t\/\/ set translate\n\n\n\tstd::vector<Eigen::Vector4f> vertices, colors;\n\n\tint i = 0;\n\tfor (int z = 0; z <= volume_size.z(); z += voxel_size.z())\n\t{\n\t\tfor (int y = 0; y <= volume_size.y(); y += voxel_size.y())\n\t\t{\n\t\t\tfor (int x = 0; x <= volume_size.x(); x += voxel_size.x(), i++)\n\t\t\t{\n\t\t\t\tconst float tsdf = grid.data.at(i).tsdf;\n\n\t\t\t\tif (tsdf > 0.1)\n\t\t\t\t{\n\t\t\t\t\tEigen::Vector4d p = grid_affine.matrix() * to_origin * Eigen::Vector4d(x, y, z, 1);\n\t\t\t\t\tp \/= p.w();\n\t\t\t\t\tvertices.push_back(p.cast<float>());\n\n\t\t\t\t\tcolors.push_back(Eigen::Vector4f(0, 1, 0, 1));\n\t\t\t\t}\n\t\t\t\telse if (tsdf < -0.1)\n\t\t\t\t{\n\t\t\t\t\tEigen::Vector4d p = grid_affine.matrix() * to_origin * Eigen::Vector4d(x, y, z, 1);\n\t\t\t\t\tp \/= p.w();\n\t\t\t\t\tvertices.push_back(p.cast<float>());\n\n\t\t\t\t\tcolors.push_back(Eigen::Vector4f(1, 0, 0, 1));\n\t\t\t\t}\n\n\n\t\t\t\tif (tsdf > -0.1 && tsdf < 0.1)\n\t\t\t\t{\n\t\t\t\t\t\n\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\n\t\/\/\n\t\/\/ setup model\n\t\/\/ \n\tstd::shared_ptr<GLModel> model(new GLModel);\n\tmodel->initGL();\n\tmodel->setVertices(&vertices[0][0], vertices.size(), 4);\n\tmodel->setColors(&colors[0][0], colors.size(), 4);\n\tglwidget.addModel(model);\n\n\n\t\/\/\n\t\/\/ setup kinect shader program\n\t\/\/ \n\tstd::shared_ptr<GLShaderProgram> kinectShaderProgram(new GLShaderProgram);\n\tif (kinectShaderProgram->build(\"color.vert\", \"color.frag\"))\n\t\tmodel->setShaderProgram(kinectShaderProgram);\n\n\treturn app.exec();\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_VALIDATION_HH\n#define DUNE_STUFF_VALIDATION_HH\n\n#include <ostream>\n#include <string>\n#include <boost\/format.hpp>\n\n#include <dune\/stuff\/common\/misc.hh>\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/common\/type_utils.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\n\/** \\brief Base class for all Validators\n * the idea is from dune-fem, only our class is an actual interface\n **\/\ntemplate <class T, class Derived>\nclass ValidatorInterface\n{\npublic:\n bool operator() (const T& value) const {\n return asImp()( value );\n }\n\n std::string msg() const {\n return asImp().msg();\n }\n void print(std::ostream& out) const {\n out << asImp().msg();\n }\nprotected:\n inline const Derived& asImp () const {\n return static_cast< const Derived& >( *this );\n }\n\n inline Derived& asImp () {\n return static_cast< Derived& >( *this );\n }\n};\n\n\/\/! a class usable as a default validator\ntemplate< class T >\nclass ValidateAny\n : public ValidatorInterface< T, ValidateAny< T > >\n{\n typedef ValidateAny< T > ThisType;\n typedef ValidatorInterface< T, ThisType > BaseType;\n\npublic:\n inline ValidateAny() {}\n inline ValidateAny(const ThisType&) {}\n\n inline bool operator()(const T&) const {\n return true;\n }\n\n std::string msg() const {\n return \"ValidateAny: all values should be valid... \\n\\n\";\n }\n};\n\n\n\/\/! validates arg iff in given list\ntemplate< class T, class ListImp = std::vector< T > >\nclass ValidateInList\n : public ValidatorInterface< T, ValidateInList< T, ListImp > >\n{\n typedef ValidateInList< T, ListImp > ThisType;\n typedef ValidatorInterface< T, ThisType > BaseType;\n typedef ListImp ListType;\n ListType valid_list_;\n\npublic:\n ValidateInList(const ListType& valid_list)\n : valid_list_(valid_list)\n {}\n\n inline bool operator()(const T& val) const {\n return std::find(valid_list_.begin(), valid_list_.end(), val) != valid_list_.end();\n }\n\n std::string msg() const {\n return \"ValidateInList: checked Parameter was not in valid list\\n\\n\";\n }\n};\n\n\/\/! validate arg iff less than value, obviously\ntemplate < class T >\nclass ValidateLess : public ValidatorInterface< T, ValidateLess< T > >\n{\npublic:\n ValidateLess(const T& baseval)\n : baseval_(baseval)\n {}\n inline bool operator()(const T& val) const {\n return baseval_ < val;\n }\n\n std::string msg() const {\n return (boost::format(\"given value was invalid: not less than %s\") % toString(baseval_)).str();\n }\nprivate:\n const T baseval_;\n};\n\n\/\/! validate arg iff greater than value, obviously\ntemplate < class T >\nclass ValidateGreater : public ValidatorInterface< T, ValidateGreater< T > >\n{\npublic:\n ValidateGreater(const T& baseval)\n : baseval_(baseval)\n {}\n inline bool operator()(const T& val) const {\n return baseval_ > val;\n }\n\n std::string msg() const {\n return (boost::format(\"given value was invalid: not greater than %s\") % toString(baseval_)).str();\n }\nprivate:\n const T baseval_;\n};\n\n\/\/! validate iff not Validator(arg)\ntemplate < class T, class Validator >\nclass ValidateInverse : public ValidatorInterface< T, ValidateInverse< T, Validator > >\n{\npublic:\n ValidateInverse(const Validator validator = Validator())\n : validator_(validator)\n {}\n ValidateInverse(const T arg)\n : validator_(Validator(arg))\n {}\n inline bool operator()(const T& val) const {\n return !validator_(val);\n }\n\n std::string msg() const {\n return \"Inverse condition failed: \" + validator_.msg();\n }\nprivate:\n const Validator validator_;\n};\n\n#define INVERSE_VALIDATE(V_NEW_NAME,V_BASE_NAME) \\\n template < class T> \\\n struct V_NEW_NAME : public ValidateInverse< T, V_BASE_NAME<T> >{ \\\n template <typename... Types> \\\n V_NEW_NAME(Types... args) \\\n : ValidateInverse< T,V_BASE_NAME<T> >(args...) \\\n {} \\\n }\n\nINVERSE_VALIDATE(ValidateNone,ValidateAny);\nINVERSE_VALIDATE(ValidateGreaterOrEqual,ValidateLess);\nINVERSE_VALIDATE(ValidateNotLess,ValidateLess);\n\n\/\/! validate arg iff arg \\in [min,max]\ntemplate < class T >\nclass ValidateInterval : public ValidatorInterface< T, ValidateInterval< T > >\n{\npublic:\n ValidateInterval(const T& min, const T& max)\n : min_(min)\n , max_(max)\n {}\n\n inline bool operator()(const T& val) const {\n const bool lowerOk = ValidateGreaterOrEqual<T> (val)(min_);\n const bool upperOk = ValidateGreaterOrEqual<T> (max_)(val);\n return lowerOk && upperOk;\n }\n\n std::string msg() const {\n return \"given value was invalid: value not in given interval\";\n }\nprivate:\n const T min_;\n const T max_;\n};\n\n\/\/! example partial specialisation\ntemplate <typename T>\nstruct Typename<ValidateAny<T> > {\n static std::string value() {\n return \"Dune::Stuff::Common::Parameter::ValidateAny<T>\";\n }\n};\n\n} \/\/end namesapce Common\n} \/\/end namesapce Stuff\n} \/\/end namesapce Dune\n\ntemplate < class T, class Validator >\nstd::ostream operator << ( std::ostream& out,\n const Dune::Stuff::Common::ValidatorInterface< T, Validator >& validator )\n{\n return out << validator.msg();\n}\n\n#endif \/\/ DUNE_STUFF_VALIDATION_HH\n<commit_msg>[parameter.validation] fix typo<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_VALIDATION_HH\n#define DUNE_STUFF_VALIDATION_HH\n\n#include <ostream>\n#include <string>\n#include <boost\/format.hpp>\n\n#include <dune\/stuff\/common\/misc.hh>\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/common\/type_utils.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\n\/** \\brief Base class for all Validators\n * the idea is from dune-fem, only our class is an actual interface\n **\/\ntemplate <class T, class Derived>\nclass ValidatorInterface\n{\npublic:\n bool operator() (const T& value) const {\n return asImp()( value );\n }\n\n std::string msg() const {\n return asImp().msg();\n }\n void print(std::ostream& out) const {\n out << asImp().msg();\n }\nprotected:\n inline const Derived& asImp () const {\n return static_cast< const Derived& >( *this );\n }\n\n inline Derived& asImp () {\n return static_cast< Derived& >( *this );\n }\n};\n\n\/\/! a class usable as a default validator\ntemplate< class T >\nclass ValidateAny\n : public ValidatorInterface< T, ValidateAny< T > >\n{\n typedef ValidateAny< T > ThisType;\n typedef ValidatorInterface< T, ThisType > BaseType;\n\npublic:\n inline ValidateAny() {}\n inline ValidateAny(const ThisType&) {}\n\n inline bool operator()(const T&) const {\n return true;\n }\n\n std::string msg() const {\n return \"ValidateAny: all values should be valid... \\n\\n\";\n }\n};\n\n\n\/\/! validates arg iff in given list\ntemplate< class T, class ListImp = std::vector< T > >\nclass ValidateInList\n : public ValidatorInterface< T, ValidateInList< T, ListImp > >\n{\n typedef ValidateInList< T, ListImp > ThisType;\n typedef ValidatorInterface< T, ThisType > BaseType;\n typedef ListImp ListType;\n ListType valid_list_;\n\npublic:\n ValidateInList(const ListType& valid_list)\n : valid_list_(valid_list)\n {}\n\n inline bool operator()(const T& val) const {\n return std::find(valid_list_.begin(), valid_list_.end(), val) != valid_list_.end();\n }\n\n std::string msg() const {\n return \"ValidateInList: checked Parameter was not in valid list\\n\\n\";\n }\n};\n\n\/\/! validate arg iff less than value, obviously\ntemplate < class T >\nclass ValidateLess : public ValidatorInterface< T, ValidateLess< T > >\n{\npublic:\n ValidateLess(const T& baseval)\n : baseval_(baseval)\n {}\n inline bool operator()(const T& val) const {\n return baseval_ < val;\n }\n\n std::string msg() const {\n return (boost::format(\"given value was invalid: not less than %s\") % toString(baseval_)).str();\n }\nprivate:\n const T baseval_;\n};\n\n\/\/! validate arg iff greater than value, obviously\ntemplate < class T >\nclass ValidateGreater : public ValidatorInterface< T, ValidateGreater< T > >\n{\npublic:\n ValidateGreater(const T& baseval)\n : baseval_(baseval)\n {}\n inline bool operator()(const T& val) const {\n return baseval_ > val;\n }\n\n std::string msg() const {\n return (boost::format(\"given value was invalid: not greater than %s\") % toString(baseval_)).str();\n }\nprivate:\n const T baseval_;\n};\n\n\/\/! validate iff not Validator(arg)\ntemplate < class T, class Validator >\nclass ValidateInverse : public ValidatorInterface< T, ValidateInverse< T, Validator > >\n{\npublic:\n ValidateInverse(const Validator validator = Validator())\n : validator_(validator)\n {}\n ValidateInverse(const T arg)\n : validator_(Validator(arg))\n {}\n inline bool operator()(const T& val) const {\n return !validator_(val);\n }\n\n std::string msg() const {\n return \"Inverse condition failed: \" + validator_.msg();\n }\nprivate:\n const Validator validator_;\n};\n\n#define INVERSE_VALIDATE(V_NEW_NAME,V_BASE_NAME) \\\n template < class T> \\\n struct V_NEW_NAME : public ValidateInverse< T, V_BASE_NAME<T> >{ \\\n template <typename... Types> \\\n V_NEW_NAME(Types... args) \\\n : ValidateInverse< T,V_BASE_NAME<T> >(args...) \\\n {} \\\n }\n\nINVERSE_VALIDATE(ValidateNone,ValidateAny);\nINVERSE_VALIDATE(ValidateGreaterOrEqual,ValidateLess);\nINVERSE_VALIDATE(ValidateNotLess,ValidateLess);\n\n\/\/! validate arg iff arg \\in [min,max]\ntemplate < class T >\nclass ValidateInterval : public ValidatorInterface< T, ValidateInterval< T > >\n{\npublic:\n ValidateInterval(const T& min, const T& max)\n : min_(min)\n , max_(max)\n {}\n\n inline bool operator()(const T& val) const {\n const bool lowerOk = ValidateGreaterOrEqual<T> (val)(min_);\n const bool upperOk = ValidateGreaterOrEqual<T> (max_)(val);\n return lowerOk && upperOk;\n }\n\n std::string msg() const {\n return \"given value was invalid: value not in given interval\";\n }\nprivate:\n const T min_;\n const T max_;\n};\n\n\/\/! example partial specialisation\ntemplate <typename T>\nstruct Typename<ValidateAny<T> > {\n static std::string value() {\n return \"Dune::Stuff::Common::Parameter::ValidateAny<T>\";\n }\n};\n\n} \/\/end namespace Common\n} \/\/end namespace Stuff\n} \/\/end namespace Dune\n\ntemplate < class T, class Validator >\nstd::ostream operator << ( std::ostream& out,\n const Dune::Stuff::Common::ValidatorInterface< T, Validator >& validator )\n{\n return out << validator.msg();\n}\n\n#endif \/\/ DUNE_STUFF_VALIDATION_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * protocol4_serial.cpp\r\n *\r\n * PROTOCOL4 protocol over serial port\r\n *\r\n * Created on: 2011-06-05\r\n * Author: Bernard\r\n *\/\r\n\r\n#include \"extdata.h\"\r\n#include \"avr_util.h\"\r\n#include \"protocol4_serial.h\"\r\n#include \"serial.h\"\r\n#include \"console.h\"\r\n#include \"strings.h\"\r\n#include \"pen_event.h\"\r\n#include \"wacom_usb.h\"\r\n#include <util\/delay.h>\r\n\r\n#include \"led.h\"\r\n\r\n#include <stdio.h>\r\n\r\n#define WACOM_PKGLEN_PROTOCOL4 \t \t7\r\n#define WACOM_PKGLEN_PROTOCOL4_TILT\t9\r\n\r\n#define TABLET_TYPE_UNSUPPORTED\t0\t\/\/ unknown\/undefined protocol 4 serial tablet\r\n#define TABLET_TYPE_ULTRAPAD\t1 \t\/\/ UD-*\r\n\t\t\t\t\t\/\/ Note: other tablets with Protocol 4 includes: PL-*,ET-*,CT-*,KT-*\r\n\r\n#define ROM_VERSION_UNSUPPORTED\t0\t\/\/ unknown\/undefined\/V1.1 or earlier\r\n#define ROM_VERSION_1_2\t\t2 \t\/\/ lots of UD-1218-R at version 1.2\r\n#define ROM_VERSION_1_3\t\t3 \t\/\/\r\n#define ROM_VERSION_1_4\t\t4 \t\/\/\r\n#define ROM_VERSION_1_5\t\t5 \t\/\/ tested with V1.5-4\r\n\r\nnamespace protocol4_serial\r\n{\r\n\tenum protocol4ControllerState\r\n\t{\r\n\t\tinitial,\t\/\/\r\n\t\tmodelversion,\t\/\/ \"~#UD-1212-R V1.5-4\\r\"\r\n\t\tpacket\r\n\t};\r\n\r\n\tuint8_t datalen = 0;\r\n\tuint8_t buffer[21];\r\n\r\n\tuint8_t packet_len;\r\n\r\n\tPen::PenEvent penEvent;\r\n\r\n\tprotocol4ControllerState itsCurState = packet;\r\n\r\n\tuint8_t tabletType;\r\n\tuint8_t romVersion;\r\n\r\n\tbool in_proximity;\r\n\tbool eraser_mode;\r\n\r\n\tvoid resetToolState()\r\n\t{\r\n\t\tin_proximity = false;\r\n\t\teraser_mode = false;\r\n\t}\r\n\r\n\tvoid initialState()\r\n\t{\r\n\t\t\/\/ attempt to reset the board to 9600 bauds\r\n\r\n\t\tserial::setNormalPortSpeed(); \/\/ 19200 baud\r\n\t\tserial::sendString(\"\\r\\r\\r\\r#\\r\"); \/\/ send a few \\r to make sure we are in sync\r\n\r\n\t\t\/\/ 10 ms delay\r\n\t\t_delay_ms(10);\r\n\r\n\t\tserial::setInitialPortSpeed(); \/\/ 9600 baud\r\n\t\tserial::sendString(\"\\r\\r\\r\\r#\\r\"); \/\/ send a few \\r to make sure we are in sync\r\n\r\n\t\t\/\/ 10 ms delay\r\n\t\t_delay_ms(10);\r\n\r\n\t\titsCurState = modelversion;\r\n\t\tserial::sendString(\"\\r\\r\\r\\r~#\"); \/\/ send a few \\r to make sure we are in sync\r\n\t\tdatalen = 0;\r\n\t}\r\n\r\n\tbool parse_modelversion()\r\n\t{\r\n\t\tif(datalen != 20)\r\n\t\t{\r\n\t\t\t\/\/ retry !\r\n\t\t\tinitialState();\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t\/\/ For now, only supports this \"rigid\" format:\r\n\t\t\/\/\r\n\t\t\/\/ \"~#UD-1212-R00 V1.5-4\" (ends with \/r)\r\n\r\n\r\n\t\tif(buffer[2] == 'U')\r\n\t\t{\r\n\t\t\ttabletType = TABLET_TYPE_ULTRAPAD;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttabletType = TABLET_TYPE_UNSUPPORTED;\r\n\t\t}\r\n\r\n\t\tif(buffer[15] != '1')\r\n\t\t{\r\n\t\t\ttabletType = TABLET_TYPE_UNSUPPORTED;\r\n\t\t}\r\n\r\n\t\tif(buffer[17] == '2')\r\n\t\t\tromVersion = ROM_VERSION_1_2;\r\n\t\telse if(buffer[17] == '3')\r\n\t\t\tromVersion = ROM_VERSION_1_3;\r\n\t\telse if(buffer[17] == '4')\r\n\t\t\tromVersion = ROM_VERSION_1_4;\r\n\t\telse if(buffer[17] == '5')\r\n\t\t\tromVersion = ROM_VERSION_1_5;\r\n\t\telse\r\n\t\t\tromVersion = TABLET_TYPE_UNSUPPORTED;\r\n\r\n\t\tif(console::console_enabled)\r\n\t\t{\r\n\t\t\tconsole::printP(STR_SERIAL_TABLET_);\r\n\t\t\tfor(uint8_t i=2;i<datalen;i++)\r\n\t\t\t\tconsole::print(buffer[i]);\r\n\t\t\tconsole::println();\r\n\r\n\t\t\tswitch(tabletType)\r\n\t\t\t{\r\n\t\t\t\tcase TABLET_TYPE_UNSUPPORTED:\r\n\t\t\t\t\tconsole::printP(STR_UNSUPPORTED);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase TABLET_TYPE_ULTRAPAD:\r\n\t\t\t\t\tconsole::printP(STR_ULTRAPAD);\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tconsole::printP(STR_ROM_VERSION);\r\n\r\n\t\t\tswitch(romVersion)\r\n\t\t\t{\r\n\t\t\t\tcase ROM_VERSION_UNSUPPORTED:\r\n\t\t\t\t\tconsole::printP(STR_UNSUPPORTED);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase ROM_VERSION_1_2:\r\n\t\t\t\t\tconsole::print(\"1.2\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase ROM_VERSION_1_3:\r\n\t\t\t\t\tconsole::print(\"1.3\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase ROM_VERSION_1_4:\r\n\t\t\t\t\tconsole::print(\"1.4\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase ROM_VERSION_1_5:\r\n\t\t\t\t\tconsole::print(\"1.5\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tconsole::println();\r\n\t\t}\r\n\r\n\t\t\/\/ event consumed\r\n\t\tdatalen = 0;\r\n\r\n\t\tif(romVersion == ROM_VERSION_UNSUPPORTED || tabletType == TABLET_TYPE_UNSUPPORTED)\r\n\t\t\treturn false;\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\t\/**\r\n\t * set port speed to 19200, set max resolution, set Pnp Off.\r\n\t *\/\r\n\tvoid enableFeatures()\r\n\t{\r\n\t\t\/*** Explanation of the bits\r\n\t\t *\r\n\t\t * F 2 0 3 C 8 1 0\r\n\t\t * 1111 0010 0000 0011 1100 1000 0001 0000\r\n\t\t *\r\n\t\t * 11 WACOM-IV\r\n\t\t * 11 19200 bauds (10 - 9600 bauds)\r\n\t\t * 00 None\r\n\t\t * 1 8 bits\r\n\t\t * 0 1 stop bit\r\n\t\t *\r\n\t\t * 00 no CTS\/DTR check (thus may not need to ground those pins, but it is \"better\" not to let input pins floating anyways.)\r\n\t\t * 00 suppressed\r\n\t\t * 0 binary output format\r\n\t\t * 0 absolute mode\r\n\t\t * 11 maximum (10 = 100pps)\r\n\t\t *\r\n\t\t * 11 max resolution (1270,1270) but 2540,2540 is set in the init string further down.\r\n\t\t * 0 upper left origin\r\n\t\t * 0 no out of range data\r\n\t\t * 10 CRLF line terminator\r\n\t\t * 0\r\n\t\t * 0 PnP Off (1 by default)\r\n\t\t *\r\n\t\t * 0 firm pressure sensitivity\r\n\t\t * 0 high reading height (8mm+)\r\n\t\t * 0 multi-device mode disabled\r\n\t\t * 1 tilt ON\r\n\t\t * 0 no MM command set\r\n\t\t * 0 Portrait MM961 orientation\r\n\t\t * 0 1234 - BitPad II cursor data\r\n\t\t * 0 remote mode OFF\r\n\t\t *\r\n\t\t * 000 - increment value (IN)\r\n\t\t * 00 - max pen reporting speed\r\n\t\t * 2540,2540 - dpi settings\r\n\t\t *\/\r\n\t\tserial::sendString(\"~*F203C810,000,00,2540,2540\\r\");\r\n\r\n\t\tif(romVersion >= ROM_VERSION_1_4)\r\n\t\t\tpacket_len = WACOM_PKGLEN_PROTOCOL4_TILT;\r\n\t\telse\r\n\t\t\tpacket_len = WACOM_PKGLEN_PROTOCOL4;\r\n\t}\r\n\r\n\tvoid onSerialByteReceived(uint8_t data)\r\n\t{\r\n\/\/\t\tconsole::print(' ');\r\n\/\/\t\tconsole::printHex(data, 2);\r\n\/\/\t\tconsole::print((char)data);\r\n\r\n\t\tswitch(itsCurState)\r\n\t\t{\r\n\t\t\tcase initial:\r\n\t\t\tcase modelversion:\r\n\t\t\t\tif(datalen == 0 && data != '~')\r\n\t\t\t\t\tbreak; \/\/ wait for first valid character\r\n\r\n\t\t\t\tif(datalen == 1 && data != '#')\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ restart the wait\r\n\t\t\t\t\tdatalen = 0;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif(data != '\\r')\r\n\t\t\t\t{\r\n\t\t\t\t\tif(datalen < 20)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbuffer[datalen] = data;\r\n\t\t\t\t\t\tdatalen++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ retry !\r\n\t\t\t\t\t\tinitialState();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif(parse_modelversion())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ change port speed, tilt and other thingy\r\n\t\t\t\t\t\tenableFeatures();\r\n\r\n\t\t\t\t\t\t\/\/ 10 ms delay\r\n\t\t\t\t\t\t_delay_ms(10);\r\n\r\n\t\t\t\t\t\tserial::setNormalPortSpeed(); \/\/ set serial port speed to 19200\r\n\r\n\t\t\t\t\t\t\/\/ test output max coords.\r\n\/\/\t\t\t\t\t\tserial::sendString(\"\\r\\r~C\\r\");\r\n\r\n\t\t\t\t\t\t\/\/ read back settings.\r\n\/\/\t\t\t\t\t\tserial::sendString(\"\\r\\r~R\\r\");\r\n\r\n\t\t\t\t\t\tserial::sendString(\"\\r\\rST\\r\"); \/\/ Start transmitting data\r\n\r\n\t\t\t\t\t\titsCurState = packet;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase packet:\r\n\t\t\t{\r\n\t\t\t\tif(data & 0x80)\r\n\t\t\t\t{\r\n\/\/\t\t\t\t\tconsole::println();\r\n\/\/\t\t\t\t\tconsole::print(\"*\");\r\n\r\n\t\t\t\t\tif(datalen > 0)\r\n\t\t\t\t\t\tconsole::print(\"(?!)\");\r\n\t\t\t\t\tdatalen = 0;\r\n\t\t\t\t}\r\n\t\t\t\telse if(datalen == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tconsole::println(\"(*!)\");\r\n\t\t\t\t\treturn;\t\t\/\/ wait for the first valid byte\r\n\t\t\t\t}\r\n\r\n\/\/\t\t\t\tconsole::printHex(data, 2);\r\n\r\n\t\t\t\tif(datalen < packet_len)\r\n\t\t\t\t{\r\n\t\t\t\t\tbuffer[datalen] = data;\r\n\t\t\t\t\tdatalen++;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif(datalen == packet_len)\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ event consumed\r\n\t\t\t\t\tdatalen = 0;\r\n\r\n\/\/\t\t\t\t\tconsole::println();\r\n\r\n\t\t\t\t\tpenEvent.proximity = (buffer[0] & 0x40)?1:0;\r\n\r\n\t\t\t\t\tpenEvent.x = buffer[2] |\r\n\t\t\t\t\t\t\t(((uint16_t) buffer[1] ) << 7) |\r\n\t\t\t\t\t\t\t(((uint16_t)(buffer[0] & 0x3) ) << 14);\r\n\r\n\t\t\t\t\tpenEvent.y = \t buffer[5] |\r\n\t\t\t\t\t\t\t(((uint16_t) buffer[4] ) << 7) |\r\n\t\t\t\t\t\t\t(((uint16_t)(buffer[3] & 0x3) ) << 14);\r\n\r\n\/\/\t\t\t\t\tconsole::print(\"...x=\");\r\n\/\/\t\t\t\t\tconsole::printNumber(penEvent.x);\r\n\/\/\t\t\t\t\tconsole::print(\"y=\");\r\n\/\/\t\t\t\t\tconsole::printNumber(penEvent.y);\r\n\r\n\r\n\t\t\t\t\t\/* pressure *\/\r\n\r\n\t\t\t\t\tpenEvent.pressure = \t(((uint16_t)(buffer[3] & 0x04)) >> 2) |\r\n\t\t\t\t\t\t\t\t(((uint16_t)(buffer[6] & 0x3F)) << 1);\r\n\r\n\t\t\t\t\tpenEvent.pressure |= (buffer[6] & 0x40) ? 0 : 0x80;\r\n\r\n\t\t\t\t\tpenEvent.is_mouse = buffer[0] & 0x20 ? 0 : 1; \/\/ == !stylus\r\n\r\n\t\t\t\t\t\/* buttons *\/\r\n\/\/\t\t\t\t\tuint8_t buttons = (buffer[3] >> 3) & 0x0F;\r\n\/\/\t\t\t\t\tconsole::print(\" - buttons: 0x\");\r\n\/\/\t\t\t\t\tconsole::printHex(buttons,1);\r\n\r\n\t\t\t\t\t\/* check which device (pen\/eraser) is being reported *\/\r\n\t\t\t\t\tbool curEvent_eraser = (buffer[3] & 0x20);\r\n\r\n\t\t\t\t\t\/\/ detect tool state\r\n\t\t\t\t\tif(!in_proximity)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(penEvent.proximity)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\/\/ entering proximity\r\n\t\t\t\t\t\t\tin_proximity = true;\r\n\r\n\t\t\t\t\t\t\tif(curEvent_eraser)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\teraser_mode = true;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\teraser_mode = false;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tconsole::printP(STR_ENTER_PROX);\r\n\t\t\t\t\t\t\tif(eraser_mode)\r\n\t\t\t\t\t\t\t\tconsole::printlnP(STR_ERASER);\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\tconsole::printlnP(STR_PEN);\r\n\t\t\t\t\t\t\tconsole::println();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if(!penEvent.proximity)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tconsole::printP(STR_EXIT_PROX);\r\n\t\t\t\t\t\tconsole::println();\r\n\t\t\t\t\t\tresetToolState();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpenEvent.eraser = eraser_mode;\r\n\r\n\t\t\t\t\tif(eraser_mode)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ no sideswitches with eraser\r\n\t\t\t\t\t\tpenEvent.button0 = 0;\r\n\t\t\t\t\t\tpenEvent.button1 = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tpenEvent.button0 = (buffer[3] & 0x10) ? 1:0; \/\/ sideswitch 1\r\n\t\t\t\t\t\tpenEvent.button1 = (buffer[3] & 0x20) ? 1:0; \/\/ sideswitch 2\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\/\/ tip\r\n\t\t\t\t\tpenEvent.touch = (buffer[3] & 0x08) ? 1:0; \/\/ shouldn't we look at the pressure instead?\r\n\r\n\t\t\t\t\t\/\/ TODO: understand the extra logic from the linux driver (wacserial.c)\r\n\r\n\t\t\t\t\t\/* check on previous proximity *\/\r\n\t\t\t\t\t\/* we might have been fooled by tip and second\r\n\t\t\t\t\t * sideswitch when it came into prox *\/\r\n\r\n\t\t\t\t\t\/* tilt mode *\/\r\n\t\t\t\t\tif (packet_len == WACOM_PKGLEN_PROTOCOL4_TILT)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tpenEvent.tilt_x = buffer[7] & 0x3F;\r\n\t\t\t\t\t\tpenEvent.tilt_y = buffer[8] & 0x3F;\r\n\t\t\t\t\t\tif (buffer[7] & 0x40) penEvent.tilt_x -= 64;\r\n\t\t\t\t\t\tif (buffer[8] & 0x40) penEvent.tilt_y -= 64;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpenEvent.rotation_z = 0;\r\n\r\n\/\/\t\t\t\t\tconsole::println();\r\n\r\n\t\t\t\t\tPen::input_pen_event(penEvent);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid init()\r\n\t{\r\n\t\tconsole::printP(STR_PROTOCOL4_SERIAL_INIT);\r\n\r\n\t\tresetToolState();\r\n\r\n\t\tserial::init(onSerialByteReceived);\r\n\r\n\t\tinitialState();\r\n\t}\r\n}\r\n<commit_msg>early support for ArtPadII<commit_after>\/*\r\n * protocol4_serial.cpp\r\n *\r\n * PROTOCOL4 protocol over serial port\r\n *\r\n * Created on: 2011-06-05\r\n * Author: Bernard\r\n *\/\r\n\r\n#include \"extdata.h\"\r\n#include \"avr_util.h\"\r\n#include \"protocol4_serial.h\"\r\n#include \"serial.h\"\r\n#include \"console.h\"\r\n#include \"strings.h\"\r\n#include \"pen_event.h\"\r\n#include \"wacom_usb.h\"\r\n#include <util\/delay.h>\r\n\r\n#include \"led.h\"\r\n\r\n#include <stdio.h>\r\n\r\n#define WACOM_PKGLEN_PROTOCOL4 \t \t7\r\n#define WACOM_PKGLEN_PROTOCOL4_TILT\t9\r\n\r\n#define TABLET_TYPE_UNSUPPORTED\t0\t\/\/ unknown\/undefined protocol 4 serial tablet\r\n#define TABLET_TYPE_ULTRAPAD\t1 \t\/\/ UD-*\r\n#define TABLET_TYPE_ARTPADII 2\t\/\/ KT-0405-R\r\n#define TABLET_TYPE_PENPARTNER 3\t\/\/ CT-0405-R\r\n\t\t\t\t\t\/\/ Note: other tablets with Protocol 4 includes: PL-*,ET-*\r\n\r\n#define ROM_VERSION_UNSUPPORTED\t0\t\/\/ unknown\/undefined\/V1.1 or earlier\r\n#define ROM_VERSION_1_2\t\t2 \t\/\/ lots of UD-1218-R at version 1.2\r\n#define ROM_VERSION_1_3\t\t3 \t\/\/\r\n#define ROM_VERSION_1_4\t\t4 \t\/\/\r\n#define ROM_VERSION_1_5\t\t5 \t\/\/ tested with V1.5-4\r\n\r\nnamespace protocol4_serial\r\n{\r\n\tenum protocol4ControllerState\r\n\t{\r\n\t\tinitial,\t\/\/\r\n\t\tmodelversion,\t\/\/ \"~#UD-1212-R V1.5-4\\r\"\r\n\t\tpacket\r\n\t};\r\n\r\n\tuint8_t datalen = 0;\r\n\tuint8_t buffer[21];\r\n\r\n\tuint8_t packet_len;\r\n\r\n\tPen::PenEvent penEvent;\r\n\r\n\tprotocol4ControllerState itsCurState = packet;\r\n\r\n\tuint8_t tabletType;\r\n\tuint8_t romVersion;\r\n\r\n\tbool in_proximity;\r\n\tbool eraser_mode;\r\n\r\n\tvoid resetToolState()\r\n\t{\r\n\t\tin_proximity = false;\r\n\t\teraser_mode = false;\r\n\t}\r\n\r\n\tvoid initialState()\r\n\t{\r\n\t\t\/\/ attempt to reset the board to 9600 bauds\r\n\r\n\t\tserial::setNormalPortSpeed(); \/\/ 19200 baud\r\n\t\tserial::sendString(\"\\r\\r\\r\\r#\\r\"); \/\/ send a few \\r to make sure we are in sync\r\n\r\n\t\t\/\/ 10 ms delay\r\n\t\t_delay_ms(10);\r\n\r\n\t\tserial::setInitialPortSpeed(); \/\/ 9600 baud\r\n\t\tserial::sendString(\"\\r\\r\\r\\r#\\r\"); \/\/ send a few \\r to make sure we are in sync\r\n\r\n\t\t\/\/ 10 ms delay\r\n\t\t_delay_ms(10);\r\n\r\n\t\titsCurState = modelversion;\r\n\t\tserial::sendString(\"\\r\\r\\r\\r~#\"); \/\/ send a few \\r to make sure we are in sync\r\n\t\tdatalen = 0;\r\n\t}\r\n\r\n\tbool parse_modelversion()\r\n\t{\r\n\t\tif(datalen != 20)\r\n\t\t{\r\n\t\t\t\/\/ retry !\r\n\t\t\tinitialState();\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t\/\/ For now, only supports this \"rigid\" format:\r\n\t\t\/\/\r\n\t\t\/\/ \"~#UD-1212-R00 V1.5-4\" (ends with \/r)\r\n\r\n\r\n\t\tif(buffer[2] == 'U')\r\n\t\t{\r\n\t\t\ttabletType = TABLET_TYPE_ULTRAPAD;\r\n\t\t}\r\n\t\telse if(buffer[2] == 'K')\r\n\t\t{\r\n\t\t\ttabletType = TABLET_TYPE_UNSUPPORTED; \/\/ ARTPADII is with ROM 1.3\r\n\t\t}\r\n\t\telse if(buffer[2] == 'C')\r\n\t\t{\r\n\t\t\ttabletType = TABLET_TYPE_PENPARTNER;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttabletType = TABLET_TYPE_UNSUPPORTED;\r\n\t\t}\r\n\r\n\t\tif(buffer[15] != '1')\r\n\t\t{\r\n\t\t\ttabletType = TABLET_TYPE_UNSUPPORTED;\r\n\t\t}\r\n\r\n\t\tif(buffer[17] == '2')\r\n\t\t\tromVersion = ROM_VERSION_1_2;\r\n\t\telse if(buffer[17] == '3')\r\n\t\t\tromVersion = ROM_VERSION_1_3;\r\n\t\telse if(buffer[17] == '4')\r\n\t\t\tromVersion = ROM_VERSION_1_4;\r\n\t\telse if(buffer[17] == '5')\r\n\t\t\tromVersion = ROM_VERSION_1_5;\r\n\t\telse\r\n\t\t\tromVersion = TABLET_TYPE_UNSUPPORTED;\r\n\r\n\t\tif(romVersion == ROM_VERSION_1_3 && buffer[2] == 'K')\r\n\t\t\ttabletType = TABLET_TYPE_ARTPADII;\r\n\r\n\t\tif(console::console_enabled)\r\n\t\t{\r\n\t\t\tconsole::printP(STR_SERIAL_TABLET_);\r\n\t\t\tfor(uint8_t i=2;i<datalen;i++)\r\n\t\t\t\tconsole::print(buffer[i]);\r\n\t\t\tconsole::println();\r\n\r\n\t\t\tswitch(tabletType)\r\n\t\t\t{\r\n\t\t\t\tcase TABLET_TYPE_UNSUPPORTED:\r\n\t\t\t\t\tconsole::printP(STR_UNSUPPORTED);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase TABLET_TYPE_ULTRAPAD:\r\n\t\t\t\t\tconsole::printP(STR_ULTRAPAD);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase TABLET_TYPE_ARTPADII:\r\n\t\t\t\t\tconsole::printP(STR_ARTPADII);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase TABLET_TYPE_PENPARTNER:\r\n\t\t\t\t\tconsole::printP(STR_PENPARTNER);\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tconsole::printP(STR_ROM_VERSION);\r\n\r\n\t\t\tswitch(romVersion)\r\n\t\t\t{\r\n\t\t\t\tcase ROM_VERSION_UNSUPPORTED:\r\n\t\t\t\t\tconsole::printP(STR_UNSUPPORTED);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase ROM_VERSION_1_2:\r\n\t\t\t\t\tconsole::print(\"1.2\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase ROM_VERSION_1_3:\r\n\t\t\t\t\tconsole::print(\"1.3\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase ROM_VERSION_1_4:\r\n\t\t\t\t\tconsole::print(\"1.4\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase ROM_VERSION_1_5:\r\n\t\t\t\t\tconsole::print(\"1.5\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tconsole::println();\r\n\t\t}\r\n\r\n\t\t\/\/ event consumed\r\n\t\tdatalen = 0;\r\n\r\n\t\tif(romVersion == ROM_VERSION_UNSUPPORTED || tabletType == TABLET_TYPE_UNSUPPORTED)\r\n\t\t\treturn false;\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\t\/**\r\n\t * set port speed to 19200, set max resolution, set Pnp Off.\r\n\t *\/\r\n\tvoid enableFeatures()\r\n\t{\r\n\t\t\/*** Explanation of the bits\r\n\t\t *\r\n\t\t * F 2 0 3 C 8 1 0\r\n\t\t * 1111 0010 0000 0011 1100 1000 0001 0000\r\n\t\t *\r\n\t\t * 11 WACOM-IV\r\n\t\t * 11 19200 bauds (10 - 9600 bauds)\r\n\t\t * 00 None\r\n\t\t * 1 8 bits\r\n\t\t * 0 1 stop bit\r\n\t\t *\r\n\t\t * 00 no CTS\/DTR check (thus may not need to ground those pins, but it is \"better\" not to let input pins floating anyways.)\r\n\t\t * 00 suppressed\r\n\t\t * 0 binary output format\r\n\t\t * 0 absolute mode\r\n\t\t * 11 maximum (10 = 100pps)\r\n\t\t *\r\n\t\t * 11 max resolution (1270,1270) but 2540,2540 is set in the init string further down.\r\n\t\t * 0 upper left origin\r\n\t\t * 0 no out of range data\r\n\t\t * 10 CRLF line terminator\r\n\t\t * 0\r\n\t\t * 0 PnP Off (1 by default)\r\n\t\t *\r\n\t\t * 0 firm pressure sensitivity\r\n\t\t * 0 high reading height (8mm+)\r\n\t\t * 0 multi-device mode disabled\r\n\t\t * 1 tilt ON\r\n\t\t * 0 no MM command set\r\n\t\t * 0 Portrait MM961 orientation\r\n\t\t * 0 1234 - BitPad II cursor data\r\n\t\t * 0 remote mode OFF\r\n\t\t *\r\n\t\t * 000 - increment value (IN)\r\n\t\t * 00 - max pen reporting speed\r\n\t\t * 2540,2540 - dpi settings\r\n\t\t *\/\r\n\t\tserial::sendString(\"~*F203C810,000,00,2540,2540\\r\");\r\n\r\n\t\tif(romVersion >= ROM_VERSION_1_4)\r\n\t\t\tpacket_len = WACOM_PKGLEN_PROTOCOL4_TILT;\r\n\t\telse\r\n\t\t\tpacket_len = WACOM_PKGLEN_PROTOCOL4;\r\n\t}\r\n\r\n\tvoid onSerialByteReceived(uint8_t data)\r\n\t{\r\n\/\/\t\tconsole::print(' ');\r\n\/\/\t\tconsole::printHex(data, 2);\r\n\/\/\t\tconsole::print((char)data);\r\n\r\n\t\tswitch(itsCurState)\r\n\t\t{\r\n\t\t\tcase initial:\r\n\t\t\tcase modelversion:\r\n\t\t\t\tif(datalen == 0 && data != '~')\r\n\t\t\t\t\tbreak; \/\/ wait for first valid character\r\n\r\n\t\t\t\tif(datalen == 1 && data != '#')\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ restart the wait\r\n\t\t\t\t\tdatalen = 0;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif(data != '\\r')\r\n\t\t\t\t{\r\n\t\t\t\t\tif(datalen < 20)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbuffer[datalen] = data;\r\n\t\t\t\t\t\tdatalen++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ retry !\r\n\t\t\t\t\t\tinitialState();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif(parse_modelversion())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ change port speed, tilt and other thingy\r\n\t\t\t\t\t\tenableFeatures();\r\n\r\n\t\t\t\t\t\t\/\/ 10 ms delay\r\n\t\t\t\t\t\t_delay_ms(10);\r\n\r\n\t\t\t\t\t\tserial::setNormalPortSpeed(); \/\/ set serial port speed to 19200\r\n\r\n\t\t\t\t\t\t\/\/ test output max coords.\r\n\/\/\t\t\t\t\t\tserial::sendString(\"\\r\\r~C\\r\");\r\n\r\n\t\t\t\t\t\t\/\/ read back settings.\r\n\/\/\t\t\t\t\t\tserial::sendString(\"\\r\\r~R\\r\");\r\n\r\n\t\t\t\t\t\tserial::sendString(\"\\r\\rST\\r\"); \/\/ Start transmitting data\r\n\r\n\t\t\t\t\t\titsCurState = packet;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase packet:\r\n\t\t\t{\r\n\t\t\t\tif(data & 0x80)\r\n\t\t\t\t{\r\n\/\/\t\t\t\t\tconsole::println();\r\n\/\/\t\t\t\t\tconsole::print(\"*\");\r\n\r\n\t\t\t\t\tif(datalen > 0)\r\n\t\t\t\t\t\tconsole::print(\"(?!)\");\r\n\t\t\t\t\tdatalen = 0;\r\n\t\t\t\t}\r\n\t\t\t\telse if(datalen == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tconsole::println(\"(*!)\");\r\n\t\t\t\t\treturn;\t\t\/\/ wait for the first valid byte\r\n\t\t\t\t}\r\n\r\n\/\/\t\t\t\tconsole::printHex(data, 2);\r\n\r\n\t\t\t\tif(datalen < packet_len)\r\n\t\t\t\t{\r\n\t\t\t\t\tbuffer[datalen] = data;\r\n\t\t\t\t\tdatalen++;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif(datalen == packet_len)\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ event consumed\r\n\t\t\t\t\tdatalen = 0;\r\n\r\n\/\/\t\t\t\t\tconsole::println();\r\n\r\n\t\t\t\t\tpenEvent.proximity = (buffer[0] & 0x40)?1:0;\r\n\r\n\t\t\t\t\tpenEvent.x = buffer[2] |\r\n\t\t\t\t\t\t\t(((uint16_t) buffer[1] ) << 7) |\r\n\t\t\t\t\t\t\t(((uint16_t)(buffer[0] & 0x3) ) << 14);\r\n\r\n\t\t\t\t\tpenEvent.y = \t buffer[5] |\r\n\t\t\t\t\t\t\t(((uint16_t) buffer[4] ) << 7) |\r\n\t\t\t\t\t\t\t(((uint16_t)(buffer[3] & 0x3) ) << 14);\r\n\r\n\/\/\t\t\t\t\tconsole::print(\"...x=\");\r\n\/\/\t\t\t\t\tconsole::printNumber(penEvent.x);\r\n\/\/\t\t\t\t\tconsole::print(\"y=\");\r\n\/\/\t\t\t\t\tconsole::printNumber(penEvent.y);\r\n\r\n\r\n\t\t\t\t\t\/* pressure *\/\r\n\r\n\t\t\t\t\tpenEvent.pressure = \t(((uint16_t)(buffer[3] & 0x04)) >> 2) |\r\n\t\t\t\t\t\t\t\t(((uint16_t)(buffer[6] & 0x3F)) << 1);\r\n\r\n\t\t\t\t\tpenEvent.pressure |= (buffer[6] & 0x40) ? 0 : 0x80;\r\n\r\n\t\t\t\t\tpenEvent.is_mouse = buffer[0] & 0x20 ? 0 : 1; \/\/ == !stylus\r\n\r\n\t\t\t\t\t\/* buttons *\/\r\n\/\/\t\t\t\t\tuint8_t buttons = (buffer[3] >> 3) & 0x0F;\r\n\/\/\t\t\t\t\tconsole::print(\" - buttons: 0x\");\r\n\/\/\t\t\t\t\tconsole::printHex(buttons,1);\r\n\r\n\t\t\t\t\t\/* check which device (pen\/eraser) is being reported *\/\r\n\t\t\t\t\tbool curEvent_eraser = (buffer[3] & 0x20);\r\n\r\n\t\t\t\t\t\/\/ detect tool state\r\n\t\t\t\t\tif(!in_proximity)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(penEvent.proximity)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\/\/ entering proximity\r\n\t\t\t\t\t\t\tin_proximity = true;\r\n\r\n\t\t\t\t\t\t\tif(curEvent_eraser)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\teraser_mode = true;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\teraser_mode = false;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tconsole::printP(STR_ENTER_PROX);\r\n\t\t\t\t\t\t\tif(eraser_mode)\r\n\t\t\t\t\t\t\t\tconsole::printlnP(STR_ERASER);\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\tconsole::printlnP(STR_PEN);\r\n\t\t\t\t\t\t\tconsole::println();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if(!penEvent.proximity)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tconsole::printP(STR_EXIT_PROX);\r\n\t\t\t\t\t\tconsole::println();\r\n\t\t\t\t\t\tresetToolState();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpenEvent.eraser = eraser_mode;\r\n\r\n\t\t\t\t\tif(eraser_mode)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ no sideswitches with eraser\r\n\t\t\t\t\t\tpenEvent.button0 = 0;\r\n\t\t\t\t\t\tpenEvent.button1 = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tpenEvent.button0 = (buffer[3] & 0x10) ? 1:0; \/\/ sideswitch 1\r\n\t\t\t\t\t\tpenEvent.button1 = (buffer[3] & 0x20) ? 1:0; \/\/ sideswitch 2\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\/\/ tip\r\n\t\t\t\t\tpenEvent.touch = (buffer[3] & 0x08) ? 1:0; \/\/ shouldn't we look at the pressure instead?\r\n\r\n\t\t\t\t\t\/\/ TODO: understand the extra logic from the linux driver (wacserial.c)\r\n\r\n\t\t\t\t\t\/* check on previous proximity *\/\r\n\t\t\t\t\t\/* we might have been fooled by tip and second\r\n\t\t\t\t\t * sideswitch when it came into prox *\/\r\n\r\n\t\t\t\t\t\/* tilt mode *\/\r\n\t\t\t\t\tif (packet_len == WACOM_PKGLEN_PROTOCOL4_TILT)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tpenEvent.tilt_x = buffer[7] & 0x3F;\r\n\t\t\t\t\t\tpenEvent.tilt_y = buffer[8] & 0x3F;\r\n\t\t\t\t\t\tif (buffer[7] & 0x40) penEvent.tilt_x -= 64;\r\n\t\t\t\t\t\tif (buffer[8] & 0x40) penEvent.tilt_y -= 64;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpenEvent.rotation_z = 0;\r\n\r\n\/\/\t\t\t\t\tconsole::println();\r\n\r\n\t\t\t\t\tPen::input_pen_event(penEvent);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid init()\r\n\t{\r\n\t\tconsole::printP(STR_PROTOCOL4_SERIAL_INIT);\r\n\r\n\t\tresetToolState();\r\n\r\n\t\tserial::init(onSerialByteReceived);\r\n\r\n\t\tinitialState();\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#define DMLC_ENABLE_STD_THREAD 0\n\n#pragma GCC optimize ( \"-Os\" )\n\n#include \"..\/xgboost\/src\/c_api\/c_api.cc\"\n#include \"..\/xgboost\/src\/data\/simple_csr_source.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/data.cc\"\n#include \"..\/xgboost\/src\/data\/data.cc\"\n#include \"..\/xgboost\/src\/logging.cc\"\n#include \"..\/xgboost\/rabit\/src\/c_api.cc\"\n#include \"..\/xgboost\/rabit\/src\/engine.cc\"\n#include \"..\/xgboost\/rabit\/src\/allreduce_base.cc\"\n#include \"..\/xgboost\/rabit\/src\/allreduce_robust.cc\"\n#include \"..\/xgboost\/src\/c_api\/c_api_error.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io\/local_filesys.cc\"\n#include \"..\/xgboost\/src\/learner.cc\"\n#include \"..\/xgboost\/src\/objective\/objective.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io\/input_split_base.cc\"\n#include \"..\/xgboost\/src\/common\/common.cc\"\n#include \"..\/xgboost\/src\/gbm\/gbm.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io\/recordio_split.cc\"\n#include \"..\/xgboost\/src\/metric\/metric.cc\"\n#include \"..\/xgboost\/src\/data\/simple_dmatrix.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io\/line_split.cc\"\n#include \"..\/xgboost\/src\/objective\/regression_obj.cc\"\n#include \"..\/xgboost\/src\/objective\/multiclass_obj.cc\"\n#include \"..\/xgboost\/src\/metric\/elementwise_metric.cc\"\n#include \"..\/xgboost\/src\/metric\/multiclass_metric.cc\"\n#include \"..\/xgboost\/src\/metric\/rank_metric.cc\"\n#include \"..\/xgboost\/src\/gbm\/gbtree.cc\"\n#include \"..\/xgboost\/src\/gbm\/gblinear.cc\"\n#include \"..\/xgboost\/src\/data\/sparse_page_raw_format.cc\"\n#include \"..\/xgboost\/src\/objective\/rank_obj.cc\"\n#include \"..\/xgboost\/src\/tree\/tree_updater.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_histmaker.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_colmaker.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_skmaker.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_prune.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_refresh.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_sync.cc\"\n#include \"..\/xgboost\/src\/tree\/tree_model.cc\"\n\n#include \"MMRF.hpp\"\n<commit_msg>#pragma GCC optimize ( \"-O2\" )<commit_after>#define DMLC_ENABLE_STD_THREAD 0\n\n#pragma GCC optimize ( \"-O2\" )\n\n#include \"..\/xgboost\/src\/c_api\/c_api.cc\"\n#include \"..\/xgboost\/src\/data\/simple_csr_source.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/data.cc\"\n#include \"..\/xgboost\/src\/data\/data.cc\"\n#include \"..\/xgboost\/src\/logging.cc\"\n#include \"..\/xgboost\/rabit\/src\/c_api.cc\"\n#include \"..\/xgboost\/rabit\/src\/engine.cc\"\n#include \"..\/xgboost\/rabit\/src\/allreduce_base.cc\"\n#include \"..\/xgboost\/rabit\/src\/allreduce_robust.cc\"\n#include \"..\/xgboost\/src\/c_api\/c_api_error.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io\/local_filesys.cc\"\n#include \"..\/xgboost\/src\/learner.cc\"\n#include \"..\/xgboost\/src\/objective\/objective.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io\/input_split_base.cc\"\n#include \"..\/xgboost\/src\/common\/common.cc\"\n#include \"..\/xgboost\/src\/gbm\/gbm.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io\/recordio_split.cc\"\n#include \"..\/xgboost\/src\/metric\/metric.cc\"\n#include \"..\/xgboost\/src\/data\/simple_dmatrix.cc\"\n#include \"..\/xgboost\/dmlc-core\/src\/io\/line_split.cc\"\n#include \"..\/xgboost\/src\/objective\/regression_obj.cc\"\n#include \"..\/xgboost\/src\/objective\/multiclass_obj.cc\"\n#include \"..\/xgboost\/src\/metric\/elementwise_metric.cc\"\n#include \"..\/xgboost\/src\/metric\/multiclass_metric.cc\"\n#include \"..\/xgboost\/src\/metric\/rank_metric.cc\"\n#include \"..\/xgboost\/src\/gbm\/gbtree.cc\"\n#include \"..\/xgboost\/src\/gbm\/gblinear.cc\"\n#include \"..\/xgboost\/src\/data\/sparse_page_raw_format.cc\"\n#include \"..\/xgboost\/src\/objective\/rank_obj.cc\"\n#include \"..\/xgboost\/src\/tree\/tree_updater.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_histmaker.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_colmaker.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_skmaker.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_prune.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_refresh.cc\"\n#include \"..\/xgboost\/src\/tree\/updater_sync.cc\"\n#include \"..\/xgboost\/src\/tree\/tree_model.cc\"\n\n#include \"MMRF.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file streaming_decision_tree.hpp\n * @author Ryan Curtin\n *\n * The core class for a streaming decision tree.\n *\/\n#ifndef __MLPACK_METHODS_HOEFFDING_TREES_STREAMING_DECISION_TREE_HPP\n#define __MLPACK_METHODS_HOEFFDING_TREES_STREAMING_DECISION_TREE_HPP\n\n#include <mlpack\/core.hpp>\n\nnamespace mlpack {\nnamespace tree {\n\ntemplate<\n typename SplitType,\n typename MatType = arma::mat\n>\nclass StreamingDecisionTree\n{\n public:\n StreamingDecisionTree(const MatType& data,\n const data::DatasetInfo& datasetInfo,\n const arma::Row<size_t>& labels,\n const size_t numClasses,\n const double confidence = 0.95,\n const size_t numSamples = 5000);\n\n StreamingDecisionTree(const data::DatasetInfo& datasetInfo,\n const size_t dimensionality,\n const size_t numClasses,\n const double confidence = 0.95,\n const size_t numSamples = 5000,\n std::unordered_map<size_t, std::pair<size_t, size_t>>*\n dimensionMappings = NULL);\n\n StreamingDecisionTree(const StreamingDecisionTree& other);\n\n size_t NumChildren() const { return children.size(); }\n StreamingDecisionTree& Child(const size_t i) { return children[i]; }\n const StreamingDecisionTree& Child(const size_t i) const { return children[i];\n}\n\n const SplitType& Split() const { return split; }\n\n template<typename VecType>\n void Train(const VecType& data, const size_t label);\n\n void Train(const MatType& data, const arma::Row<size_t>& labels);\n\n template<typename VecType>\n size_t Classify(const VecType& data);\n\n void Classify(const MatType& data, arma::Row<size_t>& predictions);\n\n size_t& MajorityClass() { return split.MajorityClass(); }\n\n \/\/ How do we encode the actual split itself?\n\n \/\/ that's just a split dimension and a rule (categorical or numeric)\n\n private:\n std::vector<StreamingDecisionTree> children;\n\n SplitType split;\n};\n\n} \/\/ namespace tree\n} \/\/ namespace mlpack\n\n\/\/ Include implementation.\n#include \"streaming_decision_tree_impl.hpp\"\n\n#endif\n<commit_msg>Add Serialize().<commit_after>\/**\n * @file streaming_decision_tree.hpp\n * @author Ryan Curtin\n *\n * The core class for a streaming decision tree.\n *\/\n#ifndef __MLPACK_METHODS_HOEFFDING_TREES_STREAMING_DECISION_TREE_HPP\n#define __MLPACK_METHODS_HOEFFDING_TREES_STREAMING_DECISION_TREE_HPP\n\n#include <mlpack\/core.hpp>\n\nnamespace mlpack {\nnamespace tree {\n\ntemplate<\n typename SplitType,\n typename MatType = arma::mat\n>\nclass StreamingDecisionTree\n{\n public:\n StreamingDecisionTree(const MatType& data,\n const data::DatasetInfo& datasetInfo,\n const arma::Row<size_t>& labels,\n const size_t numClasses,\n const double confidence = 0.95,\n const size_t numSamples = 5000);\n\n StreamingDecisionTree(const data::DatasetInfo& datasetInfo,\n const size_t dimensionality,\n const size_t numClasses,\n const double confidence = 0.95,\n const size_t numSamples = 5000,\n std::unordered_map<size_t, std::pair<size_t, size_t>>*\n dimensionMappings = NULL);\n\n StreamingDecisionTree(const StreamingDecisionTree& other);\n\n size_t NumChildren() const { return children.size(); }\n StreamingDecisionTree& Child(const size_t i) { return children[i]; }\n const StreamingDecisionTree& Child(const size_t i) const { return children[i];\n}\n\n const SplitType& Split() const { return split; }\n\n template<typename VecType>\n void Train(const VecType& data, const size_t label);\n\n void Train(const MatType& data, const arma::Row<size_t>& labels);\n\n template<typename VecType>\n size_t Classify(const VecType& data);\n\n void Classify(const MatType& data, arma::Row<size_t>& predictions);\n\n size_t& MajorityClass() { return split.MajorityClass(); }\n\n \/\/ How do we encode the actual split itself?\n\n \/\/ that's just a split dimension and a rule (categorical or numeric)\n\n template<typename Archive>\n void Serialize(Archive& ar, const unsigned int \/* version *\/)\n {\n ar & data::CreateNVP(split, \"split\");\n\n \/\/ar & data::CreateNVP(children, \"children\");\n }\n\n private:\n std::vector<StreamingDecisionTree> children;\n\n SplitType split;\n};\n\n} \/\/ namespace tree\n} \/\/ namespace mlpack\n\n\/\/ Include implementation.\n#include \"streaming_decision_tree_impl.hpp\"\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <ctime>\n#include <iostream>\n#include <cassert>\n#include <fcntl.h>\n#include <map>\n\n#include \"policy\/kasp.pb.h\"\n#include \"zone\/zonelist.pb.h\"\n#include \"keystate\/keystate.pb.h\"\n#include \"hsmkey\/hsmkey.pb.h\"\n\n#include \"enforcer\/enforcerdata.h\"\n#include \"enforcer\/enforcer.h\"\n\n\/\/ Interface of this cpp file is used by C code, we need to declare\n\/\/ extern \"C\" to prevent linking errors.\nextern \"C\" {\n#include \"enforcer\/enforce_task.h\"\n#include \"shared\/duration.h\"\n#include \"shared\/file.h\"\n}\n\n#include \"enforcer\/enforcerzone.h\"\n#include \"enforcer\/hsmkeyfactory.h\"\n\nstatic const char *enforce_task_str = \"enforce_task\";\n\ntime_t perform_enforce(int sockfd, engineconfig_type *config)\n{\n char buf[ODS_SE_MAXLINE];\n const char *datastore = config->datastore;\n int fd;\n\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n \/\/ Read the zonelist and policies in from the same directory as\n \/\/ the database, use serialized protocolbuffer for now, but switch\n \/\/ to using database table ASAP.\n\n bool bFailedToLoad = false;\n\n ::ods::kasp::KaspDocument *kaspDoc = new ::ods::kasp::KaspDocument;\n {\n std::string datapath(datastore);\n datapath += \".policy.pb\";\n int fd = open(datapath.c_str(),O_RDONLY);\n if (kaspDoc->ParseFromFileDescriptor(fd)) {\n ods_log_debug(\"[%s] policies have been loaded\",\n enforce_task_str);\n } else {\n ods_log_error(\"[%s] policies could not be loaded from \\\"%s\\\"\",\n enforce_task_str,datapath.c_str());\n bFailedToLoad = true;\n }\n close(fd);\n }\n\n ::ods::keystate::KeyStateDocument *keystateDoc =\n new ::ods::keystate::KeyStateDocument;\n {\n std::string datapath(datastore);\n datapath += \".keystate.pb\";\n int fd = open(datapath.c_str(),O_RDONLY);\n if (keystateDoc->ParseFromFileDescriptor(fd)) {\n ods_log_debug(\"[%s] keystates have been loaded\",\n enforce_task_str);\n } else {\n ods_log_error(\"[%s] keystates could not be loaded from \\\"%s\\\"\",\n enforce_task_str,datapath.c_str());\n }\n close(fd);\n }\n\n ::ods::hsmkey::HsmKeyDocument *hsmkeyDoc = \n new ::ods::hsmkey::HsmKeyDocument;\n {\n std::string datapath(datastore);\n datapath += \".hsmkey.pb\";\n int fd = open(datapath.c_str(),O_RDONLY);\n if (hsmkeyDoc->ParseFromFileDescriptor(fd)) {\n ods_log_debug(\"[%s] HSM key info list has been loaded\",\n enforce_task_str);\n } else {\n ods_log_error(\"[%s] HSM key info list could not be loaded from \\\"%s\\\"\",\n enforce_task_str,datapath.c_str());\n }\n close(fd);\n }\n \n \n if (bFailedToLoad) {\n delete kaspDoc;\n delete keystateDoc;\n delete hsmkeyDoc;\n ods_log_error(\"[%s] unable to continue\",\n enforce_task_str);\n return -1;\n }\n\n time_t t_when = time_now() + 1 * 365 * 24 * 60 * 60; \/\/ now + 1 year\n\n \/\/ Hook the key factory into the hsmkeyDoc list of pre-generated \n \/\/ cryptographic keys.\n HsmKeyFactoryPB keyfactory(hsmkeyDoc);\n \n \/\/ Go through all the zones and run the enforcer for every one of them.\n for (int z=0; z<keystateDoc->zones_size(); ++z) {\n\n const ::ods::keystate::EnforcerZone &ks_zone = keystateDoc->zones(z);\n\n const ::ods::kasp::KASP &kasp = kaspDoc->kasp();\n\n \/\/printf(\"%s\\n\",zone.name().c_str());\n\n const ::ods::kasp::Policy *policy = NULL;\n\n for (int p=0; p<kasp.policies_size(); ++p) {\n \/\/ lookup the policy associated with this zone\n \/\/ printf(\"%s\\n\",kasp.policies(p).name().c_str());\n if (kasp.policies(p).name() == ks_zone.policy()) {\n policy = &kasp.policies(p);\n ods_log_debug(\"[%s] policy %s found for zone %s\",\n enforce_task_str,policy->name().c_str(),\n ks_zone.name().c_str());\n break;\n }\n }\n\n if (policy == NULL) {\n ods_log_error(\"[%s] policy %s could not be found for zone %s\",\n enforce_task_str,ks_zone.policy().c_str(),\n ks_zone.name().c_str());\n ods_log_error(\"[%s] unable to enforce zone %s\",\n enforce_task_str,ks_zone.name().c_str());\n continue;\n }\n\n EnforcerZonePB enfZone(keystateDoc->mutable_zones(z), policy);\n\n time_t t_next = update(enfZone, time_now(), keyfactory);\n\n if (t_next == -1)\n continue;\n \n if (t_next < time_now()) {\n ods_log_error(\"[%s] enforcer asked to be scheduled in the past for \"\n \"zone %s\", enforce_task_str, ks_zone.name().c_str());\n continue;\n }\n\n \/\/ If this enforcer wants a reschedule earlier than currently\n \/\/ set, then use that.\n if (t_next < t_when) {\n t_when = t_next;\n std::cout << std::endl << \"Next update scheduled at \" <<\n ctime(&t_when) << std::endl;\n }\n }\n\n \/\/ Persist the keystate zones back to disk as they may have\n \/\/ been changed by the enforcer update\n if (keystateDoc->IsInitialized()) {\n std::string datapath(datastore);\n datapath += \".keystate.pb\";\n int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);\n if (keystateDoc->SerializeToFileDescriptor(fd)) {\n ods_log_debug(\"[%s] key states have been updated\",\n enforce_task_str);\n\n (void)snprintf(buf, ODS_SE_MAXLINE, \"update of key states completed.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n } else {\n (void)snprintf(buf, ODS_SE_MAXLINE, \"error: key states file could not be written.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n }\n close(fd);\n } else {\n (void)snprintf(buf, ODS_SE_MAXLINE, \"error: a message in the key states is missing mandatory information.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n }\n\n \/\/ Persist the hsmkey doc back to disk as it may have\n \/\/ been changed by the enforcer update\n if (hsmkeyDoc->IsInitialized()) {\n std::string datapath(datastore);\n datapath += \".hsmkey.pb\";\n int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);\n if (hsmkeyDoc->SerializeToFileDescriptor(fd)) {\n ods_log_debug(\"[%s] HSM keys have been updated\",\n enforce_task_str);\n \n (void)snprintf(buf, ODS_SE_MAXLINE, \"update of HSM keys completed.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n } else {\n (void)snprintf(buf, ODS_SE_MAXLINE, \"error: HSM keys file could not be written.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n }\n close(fd);\n } else {\n (void)snprintf(buf, ODS_SE_MAXLINE, \"error: a message in the HSM keys is missing mandatory information.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n }\n \n delete kaspDoc;\n delete keystateDoc;\n delete hsmkeyDoc;\n\n return t_when;\n}\n\nstatic task_type *\nenforce_task_perform(task_type *task)\n{\n time_t t_when = perform_enforce(-1, (engineconfig_type *)task->context);\n\n if (t_when == -1) {\n task_cleanup(task);\n return NULL;\n }\n\n\ttask->backoff = 0;\n task->when = time_now() + 60;\n return task;\n}\n\ntask_type *\nenforce_task(engineconfig_type *config)\n{\n task_id what = task_register(\"enforce\", \n \"enforce_task_perform\",\n enforce_task_perform);\n\treturn task_create(what, time_now(), \"all\", (void*)config);\n}\n<commit_msg>Layout cleanups<commit_after>#include <ctime>\n#include <iostream>\n#include <cassert>\n#include <fcntl.h>\n#include <map>\n\n#include \"policy\/kasp.pb.h\"\n#include \"zone\/zonelist.pb.h\"\n#include \"keystate\/keystate.pb.h\"\n#include \"hsmkey\/hsmkey.pb.h\"\n\n#include \"enforcer\/enforcerdata.h\"\n#include \"enforcer\/enforcer.h\"\n\n\/\/ Interface of this cpp file is used by C code, we need to declare\n\/\/ extern \"C\" to prevent linking errors.\nextern \"C\" {\n#include \"enforcer\/enforce_task.h\"\n#include \"shared\/duration.h\"\n#include \"shared\/file.h\"\n}\n\n#include \"enforcer\/enforcerzone.h\"\n#include \"enforcer\/hsmkeyfactory.h\"\n\nstatic const char *module_str = \"enforce_task\";\n\ntime_t perform_enforce(int sockfd, engineconfig_type *config)\n{\n char buf[ODS_SE_MAXLINE];\n const char *datastore = config->datastore;\n int fd;\n\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n \/\/ Read the zonelist and policies in from the same directory as\n \/\/ the database, use serialized protocolbuffer for now, but switch\n \/\/ to using database table ASAP.\n\n bool bFailedToLoad = false;\n\n ::ods::kasp::KaspDocument *kaspDoc = new ::ods::kasp::KaspDocument;\n {\n std::string datapath(datastore);\n datapath += \".policy.pb\";\n int fd = open(datapath.c_str(),O_RDONLY);\n if (kaspDoc->ParseFromFileDescriptor(fd)) {\n ods_log_debug(\"[%s] policies have been loaded\",\n module_str);\n } else {\n ods_log_error(\"[%s] policies could not be loaded from \\\"%s\\\"\",\n module_str,datapath.c_str());\n bFailedToLoad = true;\n }\n close(fd);\n }\n\n ::ods::keystate::KeyStateDocument *keystateDoc =\n new ::ods::keystate::KeyStateDocument;\n {\n std::string datapath(datastore);\n datapath += \".keystate.pb\";\n int fd = open(datapath.c_str(),O_RDONLY);\n if (keystateDoc->ParseFromFileDescriptor(fd)) {\n ods_log_debug(\"[%s] keystates have been loaded\",\n module_str);\n } else {\n ods_log_error(\"[%s] keystates could not be loaded from \\\"%s\\\"\",\n module_str,datapath.c_str());\n }\n close(fd);\n }\n\n ::ods::hsmkey::HsmKeyDocument *hsmkeyDoc = \n new ::ods::hsmkey::HsmKeyDocument;\n {\n std::string datapath(datastore);\n datapath += \".hsmkey.pb\";\n int fd = open(datapath.c_str(),O_RDONLY);\n if (hsmkeyDoc->ParseFromFileDescriptor(fd)) {\n ods_log_debug(\"[%s] HSM key list has been loaded\",\n module_str);\n } else {\n ods_log_error(\"[%s] HSM key list could not be loaded from \\\"%s\\\"\",\n module_str,datapath.c_str());\n }\n close(fd);\n }\n \n \n if (bFailedToLoad) {\n delete kaspDoc;\n delete keystateDoc;\n delete hsmkeyDoc;\n ods_log_error(\"[%s] unable to continue\",\n module_str);\n return -1;\n }\n\n time_t t_when = time_now() + 1 * 365 * 24 * 60 * 60; \/\/ now + 1 year\n\n \/\/ Hook the key factory into the hsmkeyDoc list of pre-generated \n \/\/ cryptographic keys.\n HsmKeyFactoryPB keyfactory(hsmkeyDoc);\n \n \/\/ Go through all the zones and run the enforcer for every one of them.\n for (int z=0; z<keystateDoc->zones_size(); ++z) {\n\n const ::ods::keystate::EnforcerZone &ks_zone = keystateDoc->zones(z);\n\n const ::ods::kasp::KASP &kasp = kaspDoc->kasp();\n\n \/\/printf(\"%s\\n\",zone.name().c_str());\n\n const ::ods::kasp::Policy *policy = NULL;\n\n for (int p=0; p<kasp.policies_size(); ++p) {\n \/\/ lookup the policy associated with this zone\n \/\/ printf(\"%s\\n\",kasp.policies(p).name().c_str());\n if (kasp.policies(p).name() == ks_zone.policy()) {\n policy = &kasp.policies(p);\n ods_log_debug(\"[%s] policy %s found for zone %s\",\n module_str,policy->name().c_str(),\n ks_zone.name().c_str());\n break;\n }\n }\n\n if (policy == NULL) {\n ods_log_error(\"[%s] policy %s could not be found for zone %s\",\n module_str,ks_zone.policy().c_str(),\n ks_zone.name().c_str());\n ods_log_error(\"[%s] unable to enforce zone %s\",\n module_str,ks_zone.name().c_str());\n continue;\n }\n\n EnforcerZonePB enfZone(keystateDoc->mutable_zones(z), policy);\n\n time_t t_next = update(enfZone, time_now(), keyfactory);\n\n if (t_next == -1)\n continue;\n \n if (t_next < time_now()) {\n ods_log_error(\"[%s] enforcer asked to be scheduled in the past for \"\n \"zone %s\", module_str, ks_zone.name().c_str());\n continue;\n }\n\n \/\/ If this enforcer wants a reschedule earlier than currently\n \/\/ set, then use that.\n if (t_next < t_when) {\n t_when = t_next;\n std::cout << std::endl << \"Next update scheduled at \" <<\n ctime(&t_when) << std::endl;\n }\n }\n\n \/\/ Persist the keystate zones back to disk as they may have\n \/\/ been changed by the enforcer update\n if (keystateDoc->IsInitialized()) {\n std::string datapath(datastore);\n datapath += \".keystate.pb\";\n int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);\n if (keystateDoc->SerializeToFileDescriptor(fd)) {\n ods_log_debug(\"[%s] key states have been updated\",\n module_str);\n\n (void)snprintf(buf, ODS_SE_MAXLINE,\n \"update of key states completed.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n } else {\n (void)snprintf(buf, ODS_SE_MAXLINE,\n \"error: key states file could not be written.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n }\n close(fd);\n } else {\n (void)snprintf(buf, ODS_SE_MAXLINE,\n \"error: a message in the key states is missing \"\n \"mandatory information.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n }\n\n \/\/ Persist the hsmkey doc back to disk as it may have\n \/\/ been changed by the enforcer update\n if (hsmkeyDoc->IsInitialized()) {\n std::string datapath(datastore);\n datapath += \".hsmkey.pb\";\n int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);\n if (hsmkeyDoc->SerializeToFileDescriptor(fd)) {\n ods_log_debug(\"[%s] HSM keys have been updated\",\n module_str);\n \n (void)snprintf(buf, ODS_SE_MAXLINE, \n \"update of HSM keys completed.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n } else {\n (void)snprintf(buf, ODS_SE_MAXLINE, \n \"error: HSM keys file could not be written.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n }\n close(fd);\n } else {\n (void)snprintf(buf, ODS_SE_MAXLINE, \n \"error: a message in the HSM keys is missing \"\n \"mandatory information.\\n\");\n ods_writen(sockfd, buf, strlen(buf));\n }\n \n delete kaspDoc;\n delete keystateDoc;\n delete hsmkeyDoc;\n\n return t_when;\n}\n\nstatic task_type *\nenforce_task_perform(task_type *task)\n{\n time_t t_when = perform_enforce(-1, (engineconfig_type *)task->context);\n\n if (t_when == -1) {\n task_cleanup(task);\n return NULL;\n }\n\n\ttask->backoff = 0;\n task->when = time_now() + 60;\n return task;\n}\n\ntask_type *\nenforce_task(engineconfig_type *config)\n{\n task_id what = task_register(\"enforce\", \n \"enforce_task_perform\",\n enforce_task_perform);\n\treturn task_create(what, time_now(), \"all\", (void*)config);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- LibCxxList.cpp ------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"LibCxx.h\"\n\n#include \"lldb\/Core\/ValueObject.h\"\n#include \"lldb\/Core\/ValueObjectConstResult.h\"\n#include \"lldb\/DataFormatters\/FormattersHelpers.h\"\n#include \"lldb\/Symbol\/ClangASTContext.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Utility\/DataBufferHeap.h\"\n#include \"lldb\/Utility\/Endian.h\"\n#include \"lldb\/Utility\/Status.h\"\n#include \"lldb\/Utility\/Stream.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\nusing namespace lldb_private::formatters;\n\nnamespace {\n\nclass ListEntry {\npublic:\n ListEntry() = default;\n ListEntry(ValueObjectSP entry_sp) : m_entry_sp(entry_sp) {}\n ListEntry(const ListEntry &rhs) = default;\n ListEntry(ValueObject *entry)\n : m_entry_sp(entry ? entry->GetSP() : ValueObjectSP()) {}\n\n ListEntry next() {\n static ConstString g_next(\"__next_\");\n\n if (!m_entry_sp)\n return ListEntry();\n return ListEntry(m_entry_sp->GetChildMemberWithName(g_next, true));\n }\n\n ListEntry prev() {\n static ConstString g_prev(\"__prev_\");\n\n if (!m_entry_sp)\n return ListEntry();\n return ListEntry(m_entry_sp->GetChildMemberWithName(g_prev, true));\n }\n\n uint64_t value() const {\n if (!m_entry_sp)\n return 0;\n return m_entry_sp->GetValueAsUnsigned(0);\n }\n\n bool null() { return (value() == 0); }\n\n explicit operator bool() { return GetEntry() && !null(); }\n\n ValueObjectSP GetEntry() { return m_entry_sp; }\n\n void SetEntry(ValueObjectSP entry) { m_entry_sp = entry; }\n\n bool operator==(const ListEntry &rhs) const { return value() == rhs.value(); }\n\n bool operator!=(const ListEntry &rhs) const { return !(*this == rhs); }\n\nprivate:\n ValueObjectSP m_entry_sp;\n};\n\nclass ListIterator {\npublic:\n ListIterator() = default;\n ListIterator(ListEntry entry) : m_entry(entry) {}\n ListIterator(ValueObjectSP entry) : m_entry(entry) {}\n ListIterator(const ListIterator &rhs) = default;\n ListIterator(ValueObject *entry) : m_entry(entry) {}\n\n ValueObjectSP value() { return m_entry.GetEntry(); }\n\n ValueObjectSP advance(size_t count) {\n if (count == 0)\n return m_entry.GetEntry();\n if (count == 1) {\n next();\n return m_entry.GetEntry();\n }\n while (count > 0) {\n next();\n count--;\n if (m_entry.null())\n return lldb::ValueObjectSP();\n }\n return m_entry.GetEntry();\n }\n\n bool operator==(const ListIterator &rhs) const {\n return (rhs.m_entry == m_entry);\n }\n\nprotected:\n void next() { m_entry = m_entry.next(); }\n\n void prev() { m_entry = m_entry.prev(); }\n\nprivate:\n ListEntry m_entry;\n};\n\nclass AbstractListFrontEnd : public SyntheticChildrenFrontEnd {\npublic:\n size_t GetIndexOfChildWithName(ConstString name) override {\n return ExtractIndexFromString(name.GetCString());\n }\n bool MightHaveChildren() override { return true; }\n bool Update() override;\n\nprotected:\n AbstractListFrontEnd(ValueObject &valobj)\n : SyntheticChildrenFrontEnd(valobj) {}\n\n size_t m_count;\n ValueObject *m_head;\n\n static constexpr bool g_use_loop_detect = true;\n size_t m_loop_detected; \/\/ The number of elements that have had loop detection\n \/\/ run over them.\n ListEntry m_slow_runner; \/\/ Used for loop detection\n ListEntry m_fast_runner; \/\/ Used for loop detection\n\n size_t m_list_capping_size;\n CompilerType m_element_type;\n std::map<size_t, ListIterator> m_iterators;\n\n bool HasLoop(size_t count);\n ValueObjectSP GetItem(size_t idx);\n};\n\nclass ForwardListFrontEnd : public AbstractListFrontEnd {\npublic:\n ForwardListFrontEnd(ValueObject &valobj);\n\n size_t CalculateNumChildren() override;\n ValueObjectSP GetChildAtIndex(size_t idx) override;\n bool Update() override;\n};\n\nclass ListFrontEnd : public AbstractListFrontEnd {\npublic:\n ListFrontEnd(lldb::ValueObjectSP valobj_sp);\n\n ~ListFrontEnd() override = default;\n\n size_t CalculateNumChildren() override;\n\n lldb::ValueObjectSP GetChildAtIndex(size_t idx) override;\n\n bool Update() override;\n\nprivate:\n lldb::addr_t m_node_address;\n ValueObject *m_tail;\n};\n\n} \/\/ end anonymous namespace\n\nbool AbstractListFrontEnd::Update() {\n m_loop_detected = 0;\n m_count = UINT32_MAX;\n m_head = nullptr;\n m_list_capping_size = 0;\n m_slow_runner.SetEntry(nullptr);\n m_fast_runner.SetEntry(nullptr);\n m_iterators.clear();\n\n if (m_backend.GetTargetSP())\n m_list_capping_size =\n m_backend.GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();\n if (m_list_capping_size == 0)\n m_list_capping_size = 255;\n\n CompilerType list_type = m_backend.GetCompilerType();\n if (list_type.IsReferenceType())\n list_type = list_type.GetNonReferenceType();\n\n if (list_type.GetNumTemplateArguments() == 0)\n return false;\n m_element_type = list_type.GetTypeTemplateArgument(0);\n\n return false;\n}\n\nbool AbstractListFrontEnd::HasLoop(size_t count) {\n if (!g_use_loop_detect)\n return false;\n \/\/ don't bother checking for a loop if we won't actually need to jump nodes\n if (m_count < 2)\n return false;\n\n if (m_loop_detected == 0) {\n \/\/ This is the first time we are being run (after the last update). Set up\n \/\/ the loop invariant for the first element.\n m_slow_runner = ListEntry(m_head).next();\n m_fast_runner = m_slow_runner.next();\n m_loop_detected = 1;\n }\n\n \/\/ Loop invariant:\n \/\/ Loop detection has been run over the first m_loop_detected elements. If\n \/\/ m_slow_runner == m_fast_runner then the loop has been detected after\n \/\/ m_loop_detected elements.\n const size_t steps_to_run = std::min(count, m_count);\n while (m_loop_detected < steps_to_run && m_slow_runner && m_fast_runner &&\n m_slow_runner != m_fast_runner) {\n\n m_slow_runner = m_slow_runner.next();\n m_fast_runner = m_fast_runner.next().next();\n m_loop_detected++;\n }\n if (count <= m_loop_detected)\n return false; \/\/ No loop in the first m_loop_detected elements.\n if (!m_slow_runner || !m_fast_runner)\n return false; \/\/ Reached the end of the list. Definitely no loops.\n return m_slow_runner == m_fast_runner;\n}\n\nValueObjectSP AbstractListFrontEnd::GetItem(size_t idx) {\n size_t advance = idx;\n ListIterator current(m_head);\n if (idx > 0) {\n auto cached_iterator = m_iterators.find(idx - 1);\n if (cached_iterator != m_iterators.end()) {\n current = cached_iterator->second;\n advance = 1;\n }\n }\n ValueObjectSP value_sp = current.advance(advance);\n m_iterators[idx] = current;\n return value_sp;\n}\n\nForwardListFrontEnd::ForwardListFrontEnd(ValueObject &valobj)\n : AbstractListFrontEnd(valobj) {\n Update();\n}\n\nsize_t ForwardListFrontEnd::CalculateNumChildren() {\n if (m_count != UINT32_MAX)\n return m_count;\n\n ListEntry current(m_head);\n m_count = 0;\n while (current && m_count < m_list_capping_size) {\n ++m_count;\n current = current.next();\n }\n return m_count;\n}\n\nValueObjectSP ForwardListFrontEnd::GetChildAtIndex(size_t idx) {\n if (idx >= CalculateNumChildren())\n return nullptr;\n\n if (!m_head)\n return nullptr;\n\n if (HasLoop(idx + 1))\n return nullptr;\n\n ValueObjectSP current_sp = GetItem(idx);\n if (!current_sp)\n return nullptr;\n\n current_sp = current_sp->GetChildAtIndex(1, true); \/\/ get the __value_ child\n if (!current_sp)\n return nullptr;\n\n \/\/ we need to copy current_sp into a new object otherwise we will end up with\n \/\/ all items named __value_\n DataExtractor data;\n Status error;\n current_sp->GetData(data, error);\n if (error.Fail())\n return nullptr;\n\n return CreateValueObjectFromData(llvm::formatv(\"[{0}]\", idx).str(), data,\n m_backend.GetExecutionContextRef(),\n m_element_type);\n}\n\nstatic ValueObjectSP GetValueOfCompressedPair(ValueObject &pair) {\n ValueObjectSP value = pair.GetChildMemberWithName(ConstString(\"__value_\"), true);\n if (! value) {\n \/\/ pre-r300140 member name\n value = pair.GetChildMemberWithName(ConstString(\"__first_\"), true);\n }\n return value;\n}\n\nbool ForwardListFrontEnd::Update() {\n AbstractListFrontEnd::Update();\n\n Status err;\n ValueObjectSP backend_addr(m_backend.AddressOf(err));\n if (err.Fail() || !backend_addr)\n return false;\n\n ValueObjectSP impl_sp(\n m_backend.GetChildMemberWithName(ConstString(\"__before_begin_\"), true));\n if (!impl_sp)\n return false;\n impl_sp = GetValueOfCompressedPair(*impl_sp);\n if (!impl_sp)\n return false;\n m_head = impl_sp->GetChildMemberWithName(ConstString(\"__next_\"), true).get();\n return false;\n}\n\nListFrontEnd::ListFrontEnd(lldb::ValueObjectSP valobj_sp)\n : AbstractListFrontEnd(*valobj_sp), m_node_address(), m_tail(nullptr) {\n if (valobj_sp)\n Update();\n}\n\nsize_t ListFrontEnd::CalculateNumChildren() {\n if (m_count != UINT32_MAX)\n return m_count;\n if (!m_head || !m_tail || m_node_address == 0)\n return 0;\n ValueObjectSP size_alloc(\n m_backend.GetChildMemberWithName(ConstString(\"__size_alloc_\"), true));\n if (size_alloc) {\n ValueObjectSP value = GetValueOfCompressedPair(*size_alloc);\n if (value) {\n m_count = value->GetValueAsUnsigned(UINT32_MAX);\n }\n }\n if (m_count != UINT32_MAX) {\n return m_count;\n } else {\n uint64_t next_val = m_head->GetValueAsUnsigned(0);\n uint64_t prev_val = m_tail->GetValueAsUnsigned(0);\n if (next_val == 0 || prev_val == 0)\n return 0;\n if (next_val == m_node_address)\n return 0;\n if (next_val == prev_val)\n return 1;\n uint64_t size = 2;\n ListEntry current(m_head);\n while (current.next() && current.next().value() != m_node_address) {\n size++;\n current = current.next();\n if (size > m_list_capping_size)\n break;\n }\n return m_count = (size - 1);\n }\n}\n\nlldb::ValueObjectSP ListFrontEnd::GetChildAtIndex(size_t idx) {\n static ConstString g_value(\"__value_\");\n static ConstString g_next(\"__next_\");\n\n if (idx >= CalculateNumChildren())\n return lldb::ValueObjectSP();\n\n if (!m_head || !m_tail || m_node_address == 0)\n return lldb::ValueObjectSP();\n\n if (HasLoop(idx + 1))\n return lldb::ValueObjectSP();\n\n ValueObjectSP current_sp = GetItem(idx);\n if (!current_sp)\n return lldb::ValueObjectSP();\n\n current_sp = current_sp->GetChildAtIndex(1, true); \/\/ get the __value_ child\n if (!current_sp)\n return lldb::ValueObjectSP();\n\n if (current_sp->GetName() == g_next) {\n ProcessSP process_sp(current_sp->GetProcessSP());\n if (!process_sp)\n return nullptr;\n\n \/\/ if we grabbed the __next_ pointer, then the child is one pointer deep-er\n lldb::addr_t addr = current_sp->GetParent()->GetPointerValue();\n addr = addr + 2 * process_sp->GetAddressByteSize();\n ExecutionContext exe_ctx(process_sp);\n current_sp =\n CreateValueObjectFromAddress(\"__value_\", addr, exe_ctx, m_element_type);\n }\n\n \/\/ we need to copy current_sp into a new object otherwise we will end up with\n \/\/ all items named __value_\n DataExtractor data;\n Status error;\n current_sp->GetData(data, error);\n if (error.Fail())\n return lldb::ValueObjectSP();\n\n StreamString name;\n name.Printf(\"[%\" PRIu64 \"]\", (uint64_t)idx);\n return CreateValueObjectFromData(name.GetString(), data,\n m_backend.GetExecutionContextRef(),\n m_element_type);\n}\n\nbool ListFrontEnd::Update() {\n AbstractListFrontEnd::Update();\n m_tail = nullptr;\n m_node_address = 0;\n\n Status err;\n ValueObjectSP backend_addr(m_backend.AddressOf(err));\n if (err.Fail() || !backend_addr)\n return false;\n m_node_address = backend_addr->GetValueAsUnsigned(0);\n if (!m_node_address || m_node_address == LLDB_INVALID_ADDRESS)\n return false;\n ValueObjectSP impl_sp(\n m_backend.GetChildMemberWithName(ConstString(\"__end_\"), true));\n if (!impl_sp)\n return false;\n m_head = impl_sp->GetChildMemberWithName(ConstString(\"__next_\"), true).get();\n m_tail = impl_sp->GetChildMemberWithName(ConstString(\"__prev_\"), true).get();\n return false;\n}\n\nSyntheticChildrenFrontEnd *formatters::LibcxxStdListSyntheticFrontEndCreator(\n CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) {\n return (valobj_sp ? new ListFrontEnd(valobj_sp) : nullptr);\n}\n\nSyntheticChildrenFrontEnd *\nformatters::LibcxxStdForwardListSyntheticFrontEndCreator(\n CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) {\n return valobj_sp ? new ForwardListFrontEnd(*valobj_sp) : nullptr;\n}\n<commit_msg>Check the result of creating a node from __next_ in the std::list formatter.<commit_after>\/\/===-- LibCxxList.cpp ------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"LibCxx.h\"\n\n#include \"lldb\/Core\/ValueObject.h\"\n#include \"lldb\/Core\/ValueObjectConstResult.h\"\n#include \"lldb\/DataFormatters\/FormattersHelpers.h\"\n#include \"lldb\/Symbol\/ClangASTContext.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Utility\/DataBufferHeap.h\"\n#include \"lldb\/Utility\/Endian.h\"\n#include \"lldb\/Utility\/Status.h\"\n#include \"lldb\/Utility\/Stream.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\nusing namespace lldb_private::formatters;\n\nnamespace {\n\nclass ListEntry {\npublic:\n ListEntry() = default;\n ListEntry(ValueObjectSP entry_sp) : m_entry_sp(entry_sp) {}\n ListEntry(const ListEntry &rhs) = default;\n ListEntry(ValueObject *entry)\n : m_entry_sp(entry ? entry->GetSP() : ValueObjectSP()) {}\n\n ListEntry next() {\n static ConstString g_next(\"__next_\");\n\n if (!m_entry_sp)\n return ListEntry();\n return ListEntry(m_entry_sp->GetChildMemberWithName(g_next, true));\n }\n\n ListEntry prev() {\n static ConstString g_prev(\"__prev_\");\n\n if (!m_entry_sp)\n return ListEntry();\n return ListEntry(m_entry_sp->GetChildMemberWithName(g_prev, true));\n }\n\n uint64_t value() const {\n if (!m_entry_sp)\n return 0;\n return m_entry_sp->GetValueAsUnsigned(0);\n }\n\n bool null() { return (value() == 0); }\n\n explicit operator bool() { return GetEntry() && !null(); }\n\n ValueObjectSP GetEntry() { return m_entry_sp; }\n\n void SetEntry(ValueObjectSP entry) { m_entry_sp = entry; }\n\n bool operator==(const ListEntry &rhs) const { return value() == rhs.value(); }\n\n bool operator!=(const ListEntry &rhs) const { return !(*this == rhs); }\n\nprivate:\n ValueObjectSP m_entry_sp;\n};\n\nclass ListIterator {\npublic:\n ListIterator() = default;\n ListIterator(ListEntry entry) : m_entry(entry) {}\n ListIterator(ValueObjectSP entry) : m_entry(entry) {}\n ListIterator(const ListIterator &rhs) = default;\n ListIterator(ValueObject *entry) : m_entry(entry) {}\n\n ValueObjectSP value() { return m_entry.GetEntry(); }\n\n ValueObjectSP advance(size_t count) {\n if (count == 0)\n return m_entry.GetEntry();\n if (count == 1) {\n next();\n return m_entry.GetEntry();\n }\n while (count > 0) {\n next();\n count--;\n if (m_entry.null())\n return lldb::ValueObjectSP();\n }\n return m_entry.GetEntry();\n }\n\n bool operator==(const ListIterator &rhs) const {\n return (rhs.m_entry == m_entry);\n }\n\nprotected:\n void next() { m_entry = m_entry.next(); }\n\n void prev() { m_entry = m_entry.prev(); }\n\nprivate:\n ListEntry m_entry;\n};\n\nclass AbstractListFrontEnd : public SyntheticChildrenFrontEnd {\npublic:\n size_t GetIndexOfChildWithName(ConstString name) override {\n return ExtractIndexFromString(name.GetCString());\n }\n bool MightHaveChildren() override { return true; }\n bool Update() override;\n\nprotected:\n AbstractListFrontEnd(ValueObject &valobj)\n : SyntheticChildrenFrontEnd(valobj) {}\n\n size_t m_count;\n ValueObject *m_head;\n\n static constexpr bool g_use_loop_detect = true;\n size_t m_loop_detected; \/\/ The number of elements that have had loop detection\n \/\/ run over them.\n ListEntry m_slow_runner; \/\/ Used for loop detection\n ListEntry m_fast_runner; \/\/ Used for loop detection\n\n size_t m_list_capping_size;\n CompilerType m_element_type;\n std::map<size_t, ListIterator> m_iterators;\n\n bool HasLoop(size_t count);\n ValueObjectSP GetItem(size_t idx);\n};\n\nclass ForwardListFrontEnd : public AbstractListFrontEnd {\npublic:\n ForwardListFrontEnd(ValueObject &valobj);\n\n size_t CalculateNumChildren() override;\n ValueObjectSP GetChildAtIndex(size_t idx) override;\n bool Update() override;\n};\n\nclass ListFrontEnd : public AbstractListFrontEnd {\npublic:\n ListFrontEnd(lldb::ValueObjectSP valobj_sp);\n\n ~ListFrontEnd() override = default;\n\n size_t CalculateNumChildren() override;\n\n lldb::ValueObjectSP GetChildAtIndex(size_t idx) override;\n\n bool Update() override;\n\nprivate:\n lldb::addr_t m_node_address;\n ValueObject *m_tail;\n};\n\n} \/\/ end anonymous namespace\n\nbool AbstractListFrontEnd::Update() {\n m_loop_detected = 0;\n m_count = UINT32_MAX;\n m_head = nullptr;\n m_list_capping_size = 0;\n m_slow_runner.SetEntry(nullptr);\n m_fast_runner.SetEntry(nullptr);\n m_iterators.clear();\n\n if (m_backend.GetTargetSP())\n m_list_capping_size =\n m_backend.GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();\n if (m_list_capping_size == 0)\n m_list_capping_size = 255;\n\n CompilerType list_type = m_backend.GetCompilerType();\n if (list_type.IsReferenceType())\n list_type = list_type.GetNonReferenceType();\n\n if (list_type.GetNumTemplateArguments() == 0)\n return false;\n m_element_type = list_type.GetTypeTemplateArgument(0);\n\n return false;\n}\n\nbool AbstractListFrontEnd::HasLoop(size_t count) {\n if (!g_use_loop_detect)\n return false;\n \/\/ don't bother checking for a loop if we won't actually need to jump nodes\n if (m_count < 2)\n return false;\n\n if (m_loop_detected == 0) {\n \/\/ This is the first time we are being run (after the last update). Set up\n \/\/ the loop invariant for the first element.\n m_slow_runner = ListEntry(m_head).next();\n m_fast_runner = m_slow_runner.next();\n m_loop_detected = 1;\n }\n\n \/\/ Loop invariant:\n \/\/ Loop detection has been run over the first m_loop_detected elements. If\n \/\/ m_slow_runner == m_fast_runner then the loop has been detected after\n \/\/ m_loop_detected elements.\n const size_t steps_to_run = std::min(count, m_count);\n while (m_loop_detected < steps_to_run && m_slow_runner && m_fast_runner &&\n m_slow_runner != m_fast_runner) {\n\n m_slow_runner = m_slow_runner.next();\n m_fast_runner = m_fast_runner.next().next();\n m_loop_detected++;\n }\n if (count <= m_loop_detected)\n return false; \/\/ No loop in the first m_loop_detected elements.\n if (!m_slow_runner || !m_fast_runner)\n return false; \/\/ Reached the end of the list. Definitely no loops.\n return m_slow_runner == m_fast_runner;\n}\n\nValueObjectSP AbstractListFrontEnd::GetItem(size_t idx) {\n size_t advance = idx;\n ListIterator current(m_head);\n if (idx > 0) {\n auto cached_iterator = m_iterators.find(idx - 1);\n if (cached_iterator != m_iterators.end()) {\n current = cached_iterator->second;\n advance = 1;\n }\n }\n ValueObjectSP value_sp = current.advance(advance);\n m_iterators[idx] = current;\n return value_sp;\n}\n\nForwardListFrontEnd::ForwardListFrontEnd(ValueObject &valobj)\n : AbstractListFrontEnd(valobj) {\n Update();\n}\n\nsize_t ForwardListFrontEnd::CalculateNumChildren() {\n if (m_count != UINT32_MAX)\n return m_count;\n\n ListEntry current(m_head);\n m_count = 0;\n while (current && m_count < m_list_capping_size) {\n ++m_count;\n current = current.next();\n }\n return m_count;\n}\n\nValueObjectSP ForwardListFrontEnd::GetChildAtIndex(size_t idx) {\n if (idx >= CalculateNumChildren())\n return nullptr;\n\n if (!m_head)\n return nullptr;\n\n if (HasLoop(idx + 1))\n return nullptr;\n\n ValueObjectSP current_sp = GetItem(idx);\n if (!current_sp)\n return nullptr;\n\n current_sp = current_sp->GetChildAtIndex(1, true); \/\/ get the __value_ child\n if (!current_sp)\n return nullptr;\n\n \/\/ we need to copy current_sp into a new object otherwise we will end up with\n \/\/ all items named __value_\n DataExtractor data;\n Status error;\n current_sp->GetData(data, error);\n if (error.Fail())\n return nullptr;\n\n return CreateValueObjectFromData(llvm::formatv(\"[{0}]\", idx).str(), data,\n m_backend.GetExecutionContextRef(),\n m_element_type);\n}\n\nstatic ValueObjectSP GetValueOfCompressedPair(ValueObject &pair) {\n ValueObjectSP value = pair.GetChildMemberWithName(ConstString(\"__value_\"), true);\n if (! value) {\n \/\/ pre-r300140 member name\n value = pair.GetChildMemberWithName(ConstString(\"__first_\"), true);\n }\n return value;\n}\n\nbool ForwardListFrontEnd::Update() {\n AbstractListFrontEnd::Update();\n\n Status err;\n ValueObjectSP backend_addr(m_backend.AddressOf(err));\n if (err.Fail() || !backend_addr)\n return false;\n\n ValueObjectSP impl_sp(\n m_backend.GetChildMemberWithName(ConstString(\"__before_begin_\"), true));\n if (!impl_sp)\n return false;\n impl_sp = GetValueOfCompressedPair(*impl_sp);\n if (!impl_sp)\n return false;\n m_head = impl_sp->GetChildMemberWithName(ConstString(\"__next_\"), true).get();\n return false;\n}\n\nListFrontEnd::ListFrontEnd(lldb::ValueObjectSP valobj_sp)\n : AbstractListFrontEnd(*valobj_sp), m_node_address(), m_tail(nullptr) {\n if (valobj_sp)\n Update();\n}\n\nsize_t ListFrontEnd::CalculateNumChildren() {\n if (m_count != UINT32_MAX)\n return m_count;\n if (!m_head || !m_tail || m_node_address == 0)\n return 0;\n ValueObjectSP size_alloc(\n m_backend.GetChildMemberWithName(ConstString(\"__size_alloc_\"), true));\n if (size_alloc) {\n ValueObjectSP value = GetValueOfCompressedPair(*size_alloc);\n if (value) {\n m_count = value->GetValueAsUnsigned(UINT32_MAX);\n }\n }\n if (m_count != UINT32_MAX) {\n return m_count;\n } else {\n uint64_t next_val = m_head->GetValueAsUnsigned(0);\n uint64_t prev_val = m_tail->GetValueAsUnsigned(0);\n if (next_val == 0 || prev_val == 0)\n return 0;\n if (next_val == m_node_address)\n return 0;\n if (next_val == prev_val)\n return 1;\n uint64_t size = 2;\n ListEntry current(m_head);\n while (current.next() && current.next().value() != m_node_address) {\n size++;\n current = current.next();\n if (size > m_list_capping_size)\n break;\n }\n return m_count = (size - 1);\n }\n}\n\nlldb::ValueObjectSP ListFrontEnd::GetChildAtIndex(size_t idx) {\n static ConstString g_value(\"__value_\");\n static ConstString g_next(\"__next_\");\n\n if (idx >= CalculateNumChildren())\n return lldb::ValueObjectSP();\n\n if (!m_head || !m_tail || m_node_address == 0)\n return lldb::ValueObjectSP();\n\n if (HasLoop(idx + 1))\n return lldb::ValueObjectSP();\n\n ValueObjectSP current_sp = GetItem(idx);\n if (!current_sp)\n return lldb::ValueObjectSP();\n\n current_sp = current_sp->GetChildAtIndex(1, true); \/\/ get the __value_ child\n if (!current_sp)\n return lldb::ValueObjectSP();\n\n if (current_sp->GetName() == g_next) {\n ProcessSP process_sp(current_sp->GetProcessSP());\n if (!process_sp)\n return lldb::ValueObjectSP();\n\n \/\/ if we grabbed the __next_ pointer, then the child is one pointer deep-er\n lldb::addr_t addr = current_sp->GetParent()->GetPointerValue();\n addr = addr + 2 * process_sp->GetAddressByteSize();\n ExecutionContext exe_ctx(process_sp);\n current_sp =\n CreateValueObjectFromAddress(\"__value_\", addr, exe_ctx, m_element_type);\n if (!current_sp)\n return lldb::ValueObjectSP();\n }\n\n \/\/ we need to copy current_sp into a new object otherwise we will end up with\n \/\/ all items named __value_\n DataExtractor data;\n Status error;\n current_sp->GetData(data, error);\n if (error.Fail())\n return lldb::ValueObjectSP();\n\n StreamString name;\n name.Printf(\"[%\" PRIu64 \"]\", (uint64_t)idx);\n return CreateValueObjectFromData(name.GetString(), data,\n m_backend.GetExecutionContextRef(),\n m_element_type);\n}\n\nbool ListFrontEnd::Update() {\n AbstractListFrontEnd::Update();\n m_tail = nullptr;\n m_node_address = 0;\n\n Status err;\n ValueObjectSP backend_addr(m_backend.AddressOf(err));\n if (err.Fail() || !backend_addr)\n return false;\n m_node_address = backend_addr->GetValueAsUnsigned(0);\n if (!m_node_address || m_node_address == LLDB_INVALID_ADDRESS)\n return false;\n ValueObjectSP impl_sp(\n m_backend.GetChildMemberWithName(ConstString(\"__end_\"), true));\n if (!impl_sp)\n return false;\n m_head = impl_sp->GetChildMemberWithName(ConstString(\"__next_\"), true).get();\n m_tail = impl_sp->GetChildMemberWithName(ConstString(\"__prev_\"), true).get();\n return false;\n}\n\nSyntheticChildrenFrontEnd *formatters::LibcxxStdListSyntheticFrontEndCreator(\n CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) {\n return (valobj_sp ? new ListFrontEnd(valobj_sp) : nullptr);\n}\n\nSyntheticChildrenFrontEnd *\nformatters::LibcxxStdForwardListSyntheticFrontEndCreator(\n CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) {\n return valobj_sp ? new ForwardListFrontEnd(*valobj_sp) : nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\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: Nathan Binkert\n *\/\n\n#ifndef __BASE_REFCNT_HH__\n#define __BASE_REFCNT_HH__\n\nclass RefCounted\n{\n private:\n int count;\n\n private:\n \/\/ Don't allow a default copy constructor or copy operator on\n \/\/ these objects because the default operation will copy the\n \/\/ reference count as well and we certainly don't want that.\n RefCounted(const RefCounted &);\n RefCounted &operator=(const RefCounted &);\n\n public:\n RefCounted() : count(0) {}\n virtual ~RefCounted() {}\n\n void incref() { ++count; }\n void decref() { if (--count <= 0) delete this; }\n};\n\ntemplate <class T>\nclass RefCountingPtr\n{\n protected:\n T *data;\n\n void copy(T *d)\n {\n data = d;\n if (data)\n data->incref();\n }\n void del()\n {\n if (data)\n data->decref();\n }\n void set(T *d)\n {\n if (data == d)\n return;\n\n del();\n copy(d);\n }\n\n\n public:\n RefCountingPtr() : data(0) {}\n RefCountingPtr(T *data) { copy(data); }\n RefCountingPtr(const RefCountingPtr &r) { copy(r.data); }\n ~RefCountingPtr() { del(); }\n\n T *operator->() { return data; }\n T &operator*() { return *data; }\n T *get() { return data; }\n\n const T *operator->() const { return data; }\n const T &operator*() const { return *data; }\n const T *get() const { return data; }\n\n const RefCountingPtr &operator=(T *p) { set(p); return *this; }\n const RefCountingPtr &operator=(const RefCountingPtr &r)\n { return operator=(r.data); }\n\n bool operator!() const { return data == 0; }\n operator bool() const { return data != 0; }\n};\n\ntemplate<class T>\nbool operator==(const RefCountingPtr<T> &l, const RefCountingPtr<T> &r)\n{ return l.get() == r.get(); }\n\ntemplate<class T>\nbool operator==(const RefCountingPtr<T> &l, const T *r)\n{ return l.get() == r; }\n\ntemplate<class T>\nbool operator==(const T *l, const RefCountingPtr<T> &r)\n{ return l == r.get(); }\n\ntemplate<class T>\nbool operator!=(const RefCountingPtr<T> &l, const RefCountingPtr<T> &r)\n{ return l.get() != r.get(); }\n\ntemplate<class T>\nbool operator!=(const RefCountingPtr<T> &l, const T *r)\n{ return l.get() != r; }\n\ntemplate<class T>\nbool operator!=(const T *l, const RefCountingPtr<T> &r)\n{ return l != r.get(); }\n\n#endif \/\/ __BASE_REFCNT_HH__\n<commit_msg>refcnt: Change things around so that we handle constness correctly. To use a non const pointer: typedef RefCountingPtr<Foo> FooPtr;<commit_after>\/*\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: Nathan Binkert\n *\/\n\n#ifndef __BASE_REFCNT_HH__\n#define __BASE_REFCNT_HH__\n\nclass RefCounted\n{\n private:\n mutable int count;\n\n private:\n \/\/ Don't allow a default copy constructor or copy operator on\n \/\/ these objects because the default operation will copy the\n \/\/ reference count as well and we certainly don't want that.\n RefCounted(const RefCounted &);\n RefCounted &operator=(const RefCounted &);\n\n public:\n RefCounted() : count(0) {}\n virtual ~RefCounted() {}\n\n void incref() { ++count; }\n void decref() { if (--count <= 0) delete this; }\n};\n\ntemplate <class T>\nclass RefCountingPtr\n{\n protected:\n T *data;\n\n void copy(T *d)\n {\n data = d;\n if (data)\n data->incref();\n }\n void del()\n {\n if (data)\n data->decref();\n }\n void set(T *d)\n {\n if (data == d)\n return;\n\n del();\n copy(d);\n }\n\n\n public:\n RefCountingPtr() : data(0) {}\n RefCountingPtr(T *data) { copy(data); }\n RefCountingPtr(const RefCountingPtr &r) { copy(r.data); }\n ~RefCountingPtr() { del(); }\n\n T *operator->() const { return data; }\n T &operator*() const { return *data; }\n T *get() const { return data; }\n\n const RefCountingPtr &operator=(T *p) { set(p); return *this; }\n const RefCountingPtr &operator=(const RefCountingPtr &r)\n { return operator=(r.data); }\n\n bool operator!() const { return data == 0; }\n operator bool() const { return data != 0; }\n};\n\ntemplate<class T>\nbool operator==(const RefCountingPtr<T> &l, const RefCountingPtr<T> &r)\n{ return l.get() == r.get(); }\n\ntemplate<class T>\nbool operator==(const RefCountingPtr<T> &l, const T *r)\n{ return l.get() == r; }\n\ntemplate<class T>\nbool operator==(const T *l, const RefCountingPtr<T> &r)\n{ return l == r.get(); }\n\ntemplate<class T>\nbool operator!=(const RefCountingPtr<T> &l, const RefCountingPtr<T> &r)\n{ return l.get() != r.get(); }\n\ntemplate<class T>\nbool operator!=(const RefCountingPtr<T> &l, const T *r)\n{ return l.get() != r; }\n\ntemplate<class T>\nbool operator!=(const T *l, const RefCountingPtr<T> &r)\n{ return l != r.get(); }\n\n#endif \/\/ __BASE_REFCNT_HH__\n<|endoftext|>"} {"text":"<commit_before>\/\/============================================================================\n\/\/ Name : benchpress.cpp\n\/\/ Author : Ulrik Kofoed Pedersen\n\/\/ Version :\n\/\/ Copyright : MIT. See LICENSE file.\n\/\/ Description : Use blosc with different algorithms to compress data from\n\/\/ datasets in an HDF5 file - and benchmark the performance\n\/\/============================================================================\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <sstream>\nusing namespace std;\n\n#include <blosc.h>\n#include <hdf5.h>\n#include <hdf5_hl.h>\n\n#include <boost\/program_options.hpp>\n#include <boost\/timer\/timer.hpp>\nnamespace po = boost::program_options;\n\nclass Image {\npublic:\n Image() : pdata(NULL), bytes(0), typesize(0){};\n Image(unsigned int width, unsigned int height, int bpp, void* pdata);\n Image(unsigned int nbytes, void* pdata);\n Image(const Image& src); \/\/ copy constructor\n void next(const Image& src); \/\/ Increment pointer to next image after src\n void next(); \/\/ Increment pointer to next image position\n \/\/ Operators\n Image& operator=( const Image& src );\n const void* data_ptr();\n unsigned int frame_bytes() {return this->bytes;}\n size_t get_typesize(){return this->typesize;}\nprivate:\n void * pdata;\n unsigned int bytes;\n size_t typesize;\n};\n\nvoid * read_dataset(const string& file_name,\n const string& dataset_name, vector<Image>& images);\nvector<string> &split_string(const string &s, char delim, vector<string> &elems);\n\nvector<string> &split_string(const string &s, char delim, vector<string> &elems) {\n stringstream ss(s);\n string item;\n while (getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n}\n\nvoid * read_dataset(const string& file_name,\n const string& dataset_name, vector<Image>& images)\n{\n herr_t herr;\n int rank=0;\n H5T_class_t class_id;\n size_t type_size;\n hid_t file;\n\n file = H5Fopen(file_name.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n\n herr = H5LTget_dataset_ndims(file, dataset_name.c_str(), &rank);\n hsize_t *dims = (hsize_t*)calloc(rank, sizeof(hsize_t));\n\n herr = H5LTget_dataset_info(file, dataset_name.c_str(), dims, &class_id, &type_size);\n\n unsigned int dset_pixels = 1;\n for (int i=0;i<rank; i++) dset_pixels *= dims[i];\n\n void * pdata = calloc(dset_pixels, type_size);\n herr = H5LTread_dataset_int(file, dataset_name.c_str(), (int*)pdata);\n\n \/\/ Create a list of images and push it to the user supplied 'images' vector\n unsigned int frame_pixels = 1;\n for (int i = 1; i<rank; i++) frame_pixels *= dims[i];\n Image img(frame_pixels * type_size, pdata);\n for (unsigned int i = 0; i<dims[0]; i++)\n {\n images.push_back(img);\n img.next();\n }\n\n free(dims);\n herr = H5Fclose(file);\n return pdata;\n}\n\n\nImage::Image(unsigned int width, unsigned int height, int bpp, void* pdata)\n : pdata(pdata), typesize(bpp)\n{\n this->bytes = width * height * bpp;\n}\n\nImage::Image(unsigned int nbytes, void* pdata)\n : pdata(pdata), bytes(nbytes), typesize(4)\n{\n}\n\nImage::Image(const Image& src)\n{\n this->bytes = src.bytes;\n this->pdata = src.pdata;\n this->typesize = src.typesize;\n}\n\nvoid Image::next(const Image& src)\n{\n this->pdata = (char*)(src.pdata) + src.bytes;\n}\n\nvoid Image::next()\n{\n this->next(*this);\n}\n\nImage& Image::operator=( const Image& src )\n{\n if (this != &src) {\n this->bytes = src.bytes;\n this->pdata = src.pdata;\n this->typesize = src.typesize;\n }\n return *this;\n}\n\nconst void* Image::data_ptr()\n{\n return this->pdata;\n}\n\n\nint main(int argc, char* argv[]) {\n int threads;\n int compress_level;\n int shuffle;\n string algorithm;\n po::options_description opt_desc(\"Available options\");\n po::variables_map var_map;\n const char * compression_algorithms = blosc_list_compressors();\n\n \/\/ Handle CLI options and arguments\n try {\n opt_desc.add_options()\n (\"help,h\", \"Show online help\")\n (\"algorithm,a\", po::value< string >(&algorithm)->default_value(\"blosclz\"), compression_algorithms)\n (\"threads,t\", po::value<int>(&threads)->default_value(1), \"Number of threads to use\")\n (\"level,l\", po::value<int>(&compress_level)->default_value(0), \"Compression level [0..9]\")\n (\"shuffle,s\", po::value<int>(&shuffle)->default_value(1), \"Precondition shuffle\")\n (\"list\", \"List available compression algorithms\")\n (\"file\", po::value< string >()->default_value(\"\"), \"Input file\")\n (\"dataset\", po::value<string>()->default_value(\"\"), \"Input dataset\")\n ;\n\n po::positional_options_description p;\n p.add(\"file\", 1); \/\/ Input file name\n p.add(\"dataset\", 1); \/\/ Input dataset (inside file)\n\n po::store(po::command_line_parser(argc, argv).options(opt_desc).positional(p).run(), var_map);\n po::notify(var_map);\n\n if (var_map.count(\"help\")) {\n cout << opt_desc << \"\\n\" << endl;\n return 1;\n }\n\n if (var_map.count(\"list\")) {\n vector<string> algo_list;\n split_string(string (compression_algorithms), ',', algo_list);\n cout << \"Available compression algorithms:\" << endl;\n vector<string>::iterator it;\n for (it = algo_list.begin(); it != algo_list.end(); ++it)\n {\n char * complib;\n char * complib_version;\n blosc_get_complib_info(const_cast<char*>( it->c_str() ), &complib, &complib_version);\n cout << \"\\t\" << it->c_str() << \"\\t\" << complib_version << \"\\t\" << complib << endl;\n free(complib); free(complib_version);\n }\n return -1;\n }\n\n cout << \"Reading from file: \" << var_map[\"file\"].as<string>() << endl;\n cout << \"Input dataset: \" << var_map[\"dataset\"].as<string>() << endl;\n }\n catch (std::exception& e) \/\/ Catch option parsing exceptions\n {\n cout << \"Option parsing exception: \" << endl;\n cout << \"\\t boost error: \\\"\" << e.what() << \"\\\"\" << endl;\n cout << \"\\n\" << opt_desc << endl;\n return 1;\n }\n\n \/\/ Read the input images from the file\/dataset and push\n \/\/ into the images vector\n vector<Image> images;\n void * pdata = read_dataset(var_map[\"file\"].as<string>(),\n var_map[\"dataset\"].as<string>(), images);\n\n cout << \"Number of images read: \" << images.size() << endl;\n\n \/\/ Initialise blosc and configure number of threads and algorithm\n blosc_init();\n blosc_set_nthreads(threads);\n blosc_set_compressor(algorithm.c_str());\n size_t dest_size = images[0].frame_bytes() + BLOSC_MAX_OVERHEAD;\n void * dest_buf = calloc(dest_size, sizeof(char));\n\n \/\/ Loop through the vector of frames, compress each one and time the loop.\n \/\/ The compressed data is not used - but the buffer is reused for next iteration\n vector<Image>::iterator it;\n for (it = images.begin(); it != images.end(); ++it)\n {\n boost::timer::auto_cpu_timer timer;\n \/\/cout << static_cast<const int*>(it->data_ptr())[0] << endl;\n int cbytes = blosc_compress(compress_level, shuffle,\n it->get_typesize(),it->frame_bytes(), it->data_ptr(),\n dest_buf, dest_size);\n double ratio = (double)cbytes\/(double)(it->frame_bytes());\n cout << \"ratio: \" << 1.\/ratio << \" (\" << cbytes << \"\/\" << it->frame_bytes() << \")\";\n cout << \" rate: \" << endl;\n }\n\n blosc_destroy();\n free (pdata);\n free(dest_buf);\n return 0;\n}\n<commit_msg>Adding summary report of performance at end of run<commit_after>\/\/============================================================================\n\/\/ Name : benchpress.cpp\n\/\/ Author : Ulrik Kofoed Pedersen\n\/\/ Version :\n\/\/ Copyright : MIT. See LICENSE file.\n\/\/ Description : Use blosc with different algorithms to compress data from\n\/\/ datasets in an HDF5 file - and benchmark the performance\n\/\/============================================================================\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <sstream>\nusing namespace std;\n\n#include <blosc.h>\n#include <hdf5.h>\n#include <hdf5_hl.h>\n\n#include <boost\/program_options.hpp>\n#include <boost\/timer\/timer.hpp>\nnamespace po = boost::program_options;\nusing boost::timer::cpu_timer;\nusing boost::timer::cpu_times;\nusing boost::timer::nanosecond_type;\n\nclass Image {\npublic:\n Image() : pdata(NULL), bytes(0), typesize(0){};\n Image(unsigned int width, unsigned int height, int bpp, void* pdata);\n Image(unsigned int nbytes, void* pdata);\n Image(const Image& src); \/\/ copy constructor\n void next(const Image& src); \/\/ Increment pointer to next image after src\n void next(); \/\/ Increment pointer to next image position\n \/\/ Operators\n Image& operator=( const Image& src );\n const void* data_ptr();\n unsigned int frame_bytes() {return this->bytes;}\n size_t get_typesize(){return this->typesize;}\nprivate:\n void * pdata;\n unsigned int bytes;\n size_t typesize;\n};\n\nvoid * read_dataset(const string& file_name,\n const string& dataset_name, vector<Image>& images);\nvector<string> &split_string(const string &s, char delim, vector<string> &elems);\n\nvector<string> &split_string(const string &s, char delim, vector<string> &elems) {\n stringstream ss(s);\n string item;\n while (getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n}\n\nvoid * read_dataset(const string& file_name,\n const string& dataset_name, vector<Image>& images)\n{\n herr_t herr;\n int rank=0;\n H5T_class_t class_id;\n size_t type_size;\n hid_t file;\n\n file = H5Fopen(file_name.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n\n herr = H5LTget_dataset_ndims(file, dataset_name.c_str(), &rank);\n hsize_t *dims = (hsize_t*)calloc(rank, sizeof(hsize_t));\n\n herr = H5LTget_dataset_info(file, dataset_name.c_str(), dims, &class_id, &type_size);\n\n unsigned int dset_pixels = 1;\n for (int i=0;i<rank; i++) dset_pixels *= dims[i];\n\n void * pdata = calloc(dset_pixels, type_size);\n herr = H5LTread_dataset_int(file, dataset_name.c_str(), (int*)pdata);\n\n \/\/ Create a list of images and push it to the user supplied 'images' vector\n unsigned int frame_pixels = 1;\n for (int i = 1; i<rank; i++) frame_pixels *= dims[i];\n Image img(frame_pixels * type_size, pdata);\n for (unsigned int i = 0; i<dims[0]; i++)\n {\n images.push_back(img);\n img.next();\n }\n\n free(dims);\n herr = H5Fclose(file);\n return pdata;\n}\n\n\nImage::Image(unsigned int width, unsigned int height, int bpp, void* pdata)\n : pdata(pdata), typesize(bpp)\n{\n this->bytes = width * height * bpp;\n}\n\nImage::Image(unsigned int nbytes, void* pdata)\n : pdata(pdata), bytes(nbytes), typesize(4)\n{\n}\n\nImage::Image(const Image& src)\n{\n this->bytes = src.bytes;\n this->pdata = src.pdata;\n this->typesize = src.typesize;\n}\n\nvoid Image::next(const Image& src)\n{\n this->pdata = (char*)(src.pdata) + src.bytes;\n}\n\nvoid Image::next()\n{\n this->next(*this);\n}\n\nImage& Image::operator=( const Image& src )\n{\n if (this != &src) {\n this->bytes = src.bytes;\n this->pdata = src.pdata;\n this->typesize = src.typesize;\n }\n return *this;\n}\n\nconst void* Image::data_ptr()\n{\n return this->pdata;\n}\n\n\nint main(int argc, char* argv[]) {\n int threads;\n int compress_level;\n int shuffle;\n string algorithm;\n po::options_description opt_desc(\"Available options\");\n po::variables_map var_map;\n const char * compression_algorithms = blosc_list_compressors();\n\n \/\/ Handle CLI options and arguments\n try {\n opt_desc.add_options()\n (\"help,h\", \"Show online help\")\n (\"algorithm,a\", po::value< string >(&algorithm)->default_value(\"blosclz\"), compression_algorithms)\n (\"threads,t\", po::value<int>(&threads)->default_value(1), \"Number of threads to use\")\n (\"level,l\", po::value<int>(&compress_level)->default_value(0), \"Compression level [0..9]\")\n (\"shuffle,s\", po::value<int>(&shuffle)->default_value(1), \"Precondition shuffle\")\n (\"list\", \"List available compression algorithms\")\n (\"file\", po::value< string >()->default_value(\"\"), \"Input file\")\n (\"dataset\", po::value<string>()->default_value(\"\"), \"Input dataset\")\n ;\n\n po::positional_options_description p;\n p.add(\"file\", 1); \/\/ Input file name\n p.add(\"dataset\", 1); \/\/ Input dataset (inside file)\n\n po::store(po::command_line_parser(argc, argv).options(opt_desc).positional(p).run(), var_map);\n po::notify(var_map);\n\n if (var_map.count(\"help\")) {\n cout << opt_desc << \"\\n\" << endl;\n return 1;\n }\n\n if (var_map.count(\"list\")) {\n vector<string> algo_list;\n split_string(string (compression_algorithms), ',', algo_list);\n cout << \"Available compression algorithms:\" << endl;\n vector<string>::iterator it;\n for (it = algo_list.begin(); it != algo_list.end(); ++it)\n {\n char * complib;\n char * complib_version;\n blosc_get_complib_info(const_cast<char*>( it->c_str() ), &complib, &complib_version);\n cout << \"\\t\" << it->c_str() << \"\\t\" << complib_version << \"\\t\" << complib << endl;\n free(complib); free(complib_version);\n }\n return -1;\n }\n\n cout << \"Reading from file: \" << var_map[\"file\"].as<string>() << endl;\n cout << \"Input dataset: \" << var_map[\"dataset\"].as<string>() << endl;\n }\n catch (std::exception& e) \/\/ Catch option parsing exceptions\n {\n cout << \"Option parsing exception: \" << endl;\n cout << \"\\t boost error: \\\"\" << e.what() << \"\\\"\" << endl;\n cout << \"\\n\" << opt_desc << endl;\n return 1;\n }\n\n \/\/ Read the input images from the file\/dataset and push\n \/\/ into the images vector\n vector<Image> images;\n void * pdata = read_dataset(var_map[\"file\"].as<string>(),\n var_map[\"dataset\"].as<string>(), images);\n\n cout << \"Number of images read: \" << images.size() << endl;\n\n \/\/ Initialise blosc and configure number of threads and algorithm\n blosc_init();\n blosc_set_nthreads(threads);\n blosc_set_compressor(algorithm.c_str());\n size_t dest_size = images[0].frame_bytes() + BLOSC_MAX_OVERHEAD;\n void * dest_buf = calloc(dest_size, sizeof(char));\n\n \/\/ Loop through the vector of frames, compress each one and time the loop.\n \/\/ The compressed data is not used - but the buffer is reused for next iteration\n vector<cpu_times> elapsed_times;\n cpu_timer timer;\n\n vector<Image>::iterator it;\n unsigned long total_cbytes = 0;\n for (it = images.begin(); it != images.end(); ++it)\n {\n \/\/cout << static_cast<const int*>(it->data_ptr())[0] << endl;\n int cbytes = blosc_compress(compress_level, shuffle,\n it->get_typesize(),it->frame_bytes(), it->data_ptr(),\n dest_buf, dest_size);\n total_cbytes += cbytes;\n double ratio = (double)cbytes\/(double)(it->frame_bytes());\n cout << \"ratio: \" << 1.\/ratio << \" (\" << cbytes << \"\/\" << it->frame_bytes() << \")\";\n cout << \" rate: \" << endl;\n\n cpu_times wus_times = timer.elapsed();\n elapsed_times.push_back(wus_times);\n cout << \"wall: \" << wus_times.wall\/1000000000. << endl;\n }\n timer.stop();\n cpu_times wus_final = timer.elapsed();\n\n double dset_megabyte = (images.size() * images[0].frame_bytes())\/(1024.*1024.);\n double comp_megabyte = total_cbytes\/(1024. * 1024.);\n double ratio = dset_megabyte\/comp_megabyte;\n double data_rate = dset_megabyte\/(wus_final.wall\/1000000000.);\n\n cout << \"Full dset time. Wall=\" << wus_final.wall\/1000000000.;\n cout << \" User: \" << wus_final.user\/1000000000.;\n cout << \" System: \" << wus_final.system\/1000000000. << endl;\n cout << \" dset: \" << dset_megabyte << \"MB comp: \" << comp_megabyte << \"MB\" << endl;\n cout << \"Ratio: \" << ratio << \" Data rate: \" << data_rate << \" MB\/s\" << endl;\n\n blosc_destroy();\n free (pdata);\n free(dest_buf);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mcc\/cfg\/static_call_graph.h\"\n\n#include <cassert>\n#include <iterator>\n#include <memory>\n#include <ostream>\n#include <typeinfo>\n#include <vector>\n\n#include \"mcc\/cfg\/set_helper.h\"\n#include \"mcc\/tac\/operator.h\"\n\nnamespace mcc {\nnamespace cfg {\n\nScg::Scg(mcc::tac::Tac &tac) {\n auto functionMap = tac.getFunctionMap();\n auto graphIndex = std::map<std::string, VertexDescriptor>();\n std::string currentFunctionName;\n\n for (auto function : *functionMap) {\n auto vt = boost::add_vertex(function.second, graph);\n graphIndex.insert(std::make_pair(function.second->getName(), vt));\n }\n\n for (auto triple : tac.codeLines) {\n auto line = *triple;\n if (typeid(line) == typeid(Label)) {\n auto label = std::static_pointer_cast<Label>(triple);\n if (label->isFunctionEntry()) {\n currentFunctionName = label->getName();\n }\n } else if (triple->getOperator().getType() == OperatorType::CALL) {\n auto &arg1 = *(triple->getArg1());\n\n if (typeid(arg1) == typeid(Label)) {\n auto callTarget = std::static_pointer_cast<Label>(triple->getArg1());\n auto targetName = callTarget->getName();\n boost::add_edge(graphIndex[currentFunctionName], graphIndex[targetName],\n graph);\n }\n }\n }\n}\n\nstd::string Scg::toDot() const {\n std::ostringstream out;\n auto name = boost::make_transform_value_property_map(\n Name{}, boost::get(boost::vertex_bundle, graph));\n boost::write_graphviz(out, graph, boost::make_label_writer(name));\n return out.str();\n}\n\nvoid Scg::storeDot(std::string fileName) const {\n std::ofstream outf(fileName);\n outf << toDot();\n}\n}\n}\n<commit_msg>Fixed SCG type ID check<commit_after>#include \"mcc\/cfg\/static_call_graph.h\"\n\n#include <cassert>\n#include <iterator>\n#include <memory>\n#include <ostream>\n#include <typeinfo>\n#include <vector>\n\n#include \"mcc\/cfg\/set_helper.h\"\n#include \"mcc\/tac\/operator.h\"\n#include \"mcc\/tac\/helper\/ast_converters.h\"\n\nnamespace mcc {\nnamespace cfg {\n\nScg::Scg(mcc::tac::Tac &tac) {\n auto functionMap = tac.getFunctionMap();\n auto graphIndex = std::map<std::string, VertexDescriptor>();\n std::string currentFunctionName;\n\n for (auto function : *functionMap) {\n auto vt = boost::add_vertex(function.second, graph);\n graphIndex.insert(std::make_pair(function.second->getName(), vt));\n }\n\n for (auto triple : tac.codeLines) {\n if (mcc::tac::helper::isType<Label>(triple)) {\n auto label = std::static_pointer_cast<Label>(triple);\n if (label->isFunctionEntry()) {\n currentFunctionName = label->getName();\n }\n } else if (triple->getOperator().getType() == OperatorType::CALL) {\n if (mcc::tac::helper::isType<Label>(triple->getArg1())) {\n auto callTarget = std::static_pointer_cast<Label>(triple->getArg1());\n auto targetName = callTarget->getName();\n boost::add_edge(graphIndex[currentFunctionName], graphIndex[targetName],\n graph);\n }\n }\n }\n}\n\nstd::string Scg::toDot() const {\n std::ostringstream out;\n auto name = boost::make_transform_value_property_map(\n Name{}, boost::get(boost::vertex_bundle, graph));\n boost::write_graphviz(out, graph, boost::make_label_writer(name));\n return out.str();\n}\n\nvoid Scg::storeDot(std::string fileName) const {\n std::ofstream outf(fileName);\n outf << toDot();\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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 \"media\/audio\/linux\/pulse_output.h\"\n\n#include \"base\/message_loop.h\"\n#include \"media\/audio\/audio_parameters.h\"\n#include \"media\/audio\/audio_util.h\"\n#include \"media\/audio\/linux\/audio_manager_linux.h\"\n#include \"media\/base\/data_buffer.h\"\n#include \"media\/base\/seekable_buffer.h\"\n\nstatic pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) {\n switch (bits_per_sample) {\n \/\/ Unsupported sample formats shown for reference. I am assuming we want\n \/\/ signed and little endian because that is what we gave to ALSA.\n case 8:\n return PA_SAMPLE_U8;\n \/\/ Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW\n case 16:\n return PA_SAMPLE_S16LE;\n \/\/ Also 16-bits: PA_SAMPLE_S16BE (big endian).\n case 24:\n return PA_SAMPLE_S24LE;\n \/\/ Also 24-bits: PA_SAMPLE_S24BE (big endian).\n \/\/ Other cases: PA_SAMPLE_24_32LE (in LSB of 32-bit field, little endian),\n \/\/ and PA_SAMPLE_24_32BE (in LSB of 32-bit field, big endian),\n case 32:\n return PA_SAMPLE_S32LE;\n \/\/ Also 32-bits: PA_SAMPLE_S32BE (big endian),\n \/\/ PA_SAMPLE_FLOAT32LE (floating point little endian),\n \/\/ and PA_SAMPLE_FLOAT32BE (floating point big endian).\n default:\n return PA_SAMPLE_INVALID;\n }\n}\n\nstatic pa_channel_position ChromiumToPAChannelPosition(Channels channel) {\n switch (channel) {\n \/\/ PulseAudio does not differentiate between left\/right and\n \/\/ stereo-left\/stereo-right, both translate to front-left\/front-right.\n case LEFT:\n case STEREO_LEFT:\n return PA_CHANNEL_POSITION_FRONT_LEFT;\n case RIGHT:\n case STEREO_RIGHT:\n return PA_CHANNEL_POSITION_FRONT_RIGHT;\n case CENTER:\n return PA_CHANNEL_POSITION_FRONT_CENTER;\n case LFE:\n return PA_CHANNEL_POSITION_LFE;\n case BACK_LEFT:\n return PA_CHANNEL_POSITION_REAR_LEFT;\n case BACK_RIGHT:\n return PA_CHANNEL_POSITION_REAR_RIGHT;\n case LEFT_OF_CENTER:\n return PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;\n case RIGHT_OF_CENTER:\n return PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;\n case BACK_CENTER:\n return PA_CHANNEL_POSITION_REAR_CENTER;\n case SIDE_LEFT:\n return PA_CHANNEL_POSITION_SIDE_LEFT;\n case SIDE_RIGHT:\n return PA_CHANNEL_POSITION_SIDE_RIGHT;\n case CHANNELS_MAX:\n return PA_CHANNEL_POSITION_INVALID;\n }\n NOTREACHED();\n}\n\nstatic pa_channel_map ChannelLayoutToPAChannelMap(\n ChannelLayout channel_layout) {\n \/\/ Initialize channel map.\n pa_channel_map channel_map;\n pa_channel_map_init(&channel_map);\n\n channel_map.channels = ChannelLayoutToChannelCount(channel_layout);\n\n \/\/ All channel maps have the same size array of channel positions.\n for (unsigned int channel = 0; channel != CHANNELS_MAX; ++channel) {\n int channel_position = kChannelOrderings[channel_layout][channel];\n if (channel_position > -1) {\n channel_map.map[channel_position] = ChromiumToPAChannelPosition(\n static_cast<Channels>(channel));\n } else {\n \/\/ PulseAudio expects unused channels in channel maps to be filled with\n \/\/ PA_CHANNEL_POSITION_MONO.\n channel_map.map[channel_position] = PA_CHANNEL_POSITION_MONO;\n }\n }\n\n \/\/ Fill in the rest of the unused channels.\n for (unsigned int channel = CHANNELS_MAX; channel != PA_CHANNELS_MAX;\n ++channel) {\n channel_map.map[channel] = PA_CHANNEL_POSITION_MONO;\n }\n\n return channel_map;\n}\n\nstatic size_t MicrosecondsToBytes(\n uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) {\n return microseconds * sample_rate * bytes_per_frame \/\n base::Time::kMicrosecondsPerSecond;\n}\n\nvoid PulseAudioOutputStream::ContextStateCallback(pa_context* context,\n void* state_addr) {\n pa_context_state_t* state = static_cast<pa_context_state_t*>(state_addr);\n *state = pa_context_get_state(context);\n}\n\nvoid PulseAudioOutputStream::WriteRequestCallback(\n pa_stream* playback_handle, size_t length, void* stream_addr) {\n PulseAudioOutputStream* stream =\n static_cast<PulseAudioOutputStream*>(stream_addr);\n\n DCHECK_EQ(stream->message_loop_, MessageLoop::current());\n\n stream->write_callback_handled_ = true;\n\n \/\/ Fulfill write request.\n stream->FulfillWriteRequest(length);\n}\n\nPulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params,\n AudioManagerLinux* manager,\n MessageLoop* message_loop)\n : channel_layout_(params.channel_layout),\n channel_count_(ChannelLayoutToChannelCount(channel_layout_)),\n sample_format_(BitsToPASampleFormat(params.bits_per_sample)),\n sample_rate_(params.sample_rate),\n bytes_per_frame_(params.channels * params.bits_per_sample \/ 8),\n manager_(manager),\n pa_context_(NULL),\n pa_mainloop_(NULL),\n playback_handle_(NULL),\n packet_size_(params.GetPacketSize()),\n frames_per_packet_(packet_size_ \/ bytes_per_frame_),\n client_buffer_(NULL),\n volume_(1.0f),\n stream_stopped_(true),\n write_callback_handled_(false),\n message_loop_(message_loop),\n ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),\n source_callback_(NULL) {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n DCHECK(manager_);\n\n \/\/ TODO(slock): Sanity check input values.\n}\n\nPulseAudioOutputStream::~PulseAudioOutputStream() {\n \/\/ All internal structures should already have been freed in Close(),\n \/\/ which calls AudioManagerLinux::Release which deletes this object.\n DCHECK(!playback_handle_);\n DCHECK(!pa_context_);\n DCHECK(!pa_mainloop_);\n}\n\nbool PulseAudioOutputStream::Open() {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n \/\/ TODO(slock): Possibly move most of this to an OpenPlaybackDevice function\n \/\/ in a new class 'pulse_util', like alsa_util.\n\n \/\/ Create a mainloop API and connect to the default server.\n pa_mainloop_ = pa_mainloop_new();\n pa_mainloop_api* pa_mainloop_api = pa_mainloop_get_api(pa_mainloop_);\n pa_context_ = pa_context_new(pa_mainloop_api, \"Chromium\");\n pa_context_state_t pa_context_state = PA_CONTEXT_UNCONNECTED;\n pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL);\n\n \/\/ Wait until PulseAudio is ready.\n pa_context_set_state_callback(pa_context_, &ContextStateCallback,\n &pa_context_state);\n while (pa_context_state != PA_CONTEXT_READY) {\n pa_mainloop_iterate(pa_mainloop_, 1, NULL);\n if (pa_context_state == PA_CONTEXT_FAILED ||\n pa_context_state == PA_CONTEXT_TERMINATED) {\n Reset();\n return false;\n }\n }\n\n \/\/ Set sample specifications.\n pa_sample_spec pa_sample_specifications;\n pa_sample_specifications.format = sample_format_;\n pa_sample_specifications.rate = sample_rate_;\n pa_sample_specifications.channels = channel_count_;\n\n \/\/ Get channel mapping and open playback stream.\n pa_channel_map* map = NULL;\n pa_channel_map source_channel_map = ChannelLayoutToPAChannelMap(\n channel_layout_);\n if (source_channel_map.channels != 0) {\n \/\/ The source data uses a supported channel map so we will use it rather\n \/\/ than the default channel map (NULL).\n map = &source_channel_map;\n }\n playback_handle_ = pa_stream_new(pa_context_, \"Playback\",\n &pa_sample_specifications, map);\n\n \/\/ Initialize client buffer.\n uint32 output_packet_size = frames_per_packet_ * bytes_per_frame_;\n client_buffer_.reset(new media::SeekableBuffer(0, output_packet_size));\n\n \/\/ Set write callback.\n pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this);\n\n \/\/ Set server-side buffer attributes.\n \/\/ (uint32_t)-1 is the default and recommended value from PulseAudio's\n \/\/ documentation, found at:\n \/\/ http:\/\/freedesktop.org\/software\/pulseaudio\/doxygen\/structpa__buffer__attr.html.\n pa_buffer_attr pa_buffer_attributes;\n pa_buffer_attributes.maxlength = static_cast<uint32_t>(-1);\n pa_buffer_attributes.tlength = output_packet_size;\n pa_buffer_attributes.prebuf = static_cast<uint32_t>(-1);\n pa_buffer_attributes.minreq = static_cast<uint32_t>(-1);\n pa_buffer_attributes.fragsize = static_cast<uint32_t>(-1);\n\n \/\/ Connect playback stream.\n pa_stream_connect_playback(playback_handle_, NULL,\n &pa_buffer_attributes,\n (pa_stream_flags_t)\n (PA_STREAM_INTERPOLATE_TIMING |\n PA_STREAM_ADJUST_LATENCY |\n PA_STREAM_AUTO_TIMING_UPDATE),\n NULL, NULL);\n\n if (!playback_handle_) {\n Reset();\n return false;\n }\n\n return true;\n}\n\nvoid PulseAudioOutputStream::Reset() {\n stream_stopped_ = true;\n\n \/\/ Close the stream.\n if (playback_handle_) {\n pa_stream_flush(playback_handle_, NULL, NULL);\n pa_stream_disconnect(playback_handle_);\n\n \/\/ Release PulseAudio structures.\n pa_stream_unref(playback_handle_);\n playback_handle_ = NULL;\n }\n if (pa_context_) {\n pa_context_unref(pa_context_);\n pa_context_ = NULL;\n }\n if (pa_mainloop_) {\n pa_mainloop_free(pa_mainloop_);\n pa_mainloop_ = NULL;\n }\n\n \/\/ Release internal buffer.\n client_buffer_.reset();\n}\n\nvoid PulseAudioOutputStream::Close() {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n Reset();\n\n \/\/ Signal to the manager that we're closed and can be removed.\n \/\/ This should be the last call in the function as it deletes \"this\".\n manager_->ReleaseOutputStream(this);\n}\n\nvoid PulseAudioOutputStream::WaitForWriteRequest() {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n if (stream_stopped_)\n return;\n\n \/\/ Iterate the PulseAudio mainloop. If PulseAudio doesn't request a write,\n \/\/ post a task to iterate the mainloop again.\n write_callback_handled_ = false;\n pa_mainloop_iterate(pa_mainloop_, 1, NULL);\n if (!write_callback_handled_) {\n message_loop_->PostTask(FROM_HERE, base::Bind(\n &PulseAudioOutputStream::WaitForWriteRequest,\n weak_factory_.GetWeakPtr()));\n }\n}\n\nbool PulseAudioOutputStream::BufferPacketFromSource() {\n uint32 buffer_delay = client_buffer_->forward_bytes();\n pa_usec_t pa_latency_micros;\n int negative;\n pa_stream_get_latency(playback_handle_, &pa_latency_micros, &negative);\n uint32 hardware_delay = MicrosecondsToBytes(pa_latency_micros,\n sample_rate_,\n bytes_per_frame_);\n \/\/ TODO(slock): Deal with negative latency (negative == 1). This has yet\n \/\/ to happen in practice though.\n scoped_refptr<media::DataBuffer> packet =\n new media::DataBuffer(packet_size_);\n size_t packet_size = RunDataCallback(packet->GetWritableData(),\n packet->GetBufferSize(),\n AudioBuffersState(buffer_delay,\n hardware_delay));\n\n if (packet_size == 0)\n return false;\n\n media::AdjustVolume(packet->GetWritableData(),\n packet_size,\n channel_count_,\n bytes_per_frame_ \/ channel_count_,\n volume_);\n packet->SetDataSize(packet_size);\n \/\/ Add the packet to the buffer.\n client_buffer_->Append(packet);\n return true;\n}\n\nvoid PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) {\n \/\/ If we have enough data to fulfill the request, we can finish the write.\n if (stream_stopped_)\n return;\n\n \/\/ Request more data from the source until we can fulfill the request or\n \/\/ fail to receive anymore data.\n bool buffering_successful = true;\n while (client_buffer_->forward_bytes() < requested_bytes &&\n buffering_successful) {\n buffering_successful = BufferPacketFromSource();\n }\n\n size_t bytes_written = 0;\n if (client_buffer_->forward_bytes() > 0) {\n \/\/ Try to fulfill the request by writing as many of the requested bytes to\n \/\/ the stream as we can.\n WriteToStream(requested_bytes, &bytes_written);\n }\n\n if (bytes_written < requested_bytes) {\n \/\/ We weren't able to buffer enough data to fulfill the request. Try to\n \/\/ fulfill the rest of the request later.\n message_loop_->PostTask(FROM_HERE, base::Bind(\n &PulseAudioOutputStream::FulfillWriteRequest,\n weak_factory_.GetWeakPtr(),\n requested_bytes - bytes_written));\n } else {\n \/\/ Continue playback.\n message_loop_->PostTask(FROM_HERE, base::Bind(\n &PulseAudioOutputStream::WaitForWriteRequest,\n weak_factory_.GetWeakPtr()));\n }\n}\n\nvoid PulseAudioOutputStream::WriteToStream(size_t bytes_to_write,\n size_t* bytes_written) {\n *bytes_written = 0;\n while (*bytes_written < bytes_to_write) {\n const uint8* chunk;\n size_t chunk_size;\n\n \/\/ Stop writing if there is no more data available.\n if (!client_buffer_->GetCurrentChunk(&chunk, &chunk_size))\n break;\n\n \/\/ Write data to stream.\n pa_stream_write(playback_handle_, chunk, chunk_size,\n NULL, 0LL, PA_SEEK_RELATIVE);\n client_buffer_->Seek(chunk_size);\n *bytes_written += chunk_size;\n }\n}\n\nvoid PulseAudioOutputStream::Start(AudioSourceCallback* callback) {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n CHECK(callback);\n source_callback_ = callback;\n\n \/\/ Clear buffer, it might still have data in it.\n client_buffer_->Clear();\n stream_stopped_ = false;\n\n \/\/ Start playback.\n message_loop_->PostTask(FROM_HERE, base::Bind(\n &PulseAudioOutputStream::WaitForWriteRequest,\n weak_factory_.GetWeakPtr()));\n}\n\nvoid PulseAudioOutputStream::Stop() {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n stream_stopped_ = true;\n}\n\nvoid PulseAudioOutputStream::SetVolume(double volume) {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n volume_ = static_cast<float>(volume);\n}\n\nvoid PulseAudioOutputStream::GetVolume(double* volume) {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n *volume = volume_;\n}\n\nuint32 PulseAudioOutputStream::RunDataCallback(\n uint8* dest, uint32 max_size, AudioBuffersState buffers_state) {\n if (source_callback_)\n return source_callback_->OnMoreData(this, dest, max_size, buffers_state);\n\n return 0;\n}\n<commit_msg>fixing the compilation problem when enable pulse for chrome. One compiling error is \"media\/audio\/linux\/pulse_output.cc:347:40: error: ‘Bind’ is not a member of 'base'\" Another is \"media\/audio\/linux\/pulse_output.cc:72: error: control reaches end of non-void function\"<commit_after>\/\/ Copyright (c) 2011 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 \"media\/audio\/linux\/pulse_output.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/message_loop.h\"\n#include \"media\/audio\/audio_parameters.h\"\n#include \"media\/audio\/audio_util.h\"\n#include \"media\/audio\/linux\/audio_manager_linux.h\"\n#include \"media\/base\/data_buffer.h\"\n#include \"media\/base\/seekable_buffer.h\"\n\nstatic pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) {\n switch (bits_per_sample) {\n \/\/ Unsupported sample formats shown for reference. I am assuming we want\n \/\/ signed and little endian because that is what we gave to ALSA.\n case 8:\n return PA_SAMPLE_U8;\n \/\/ Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW\n case 16:\n return PA_SAMPLE_S16LE;\n \/\/ Also 16-bits: PA_SAMPLE_S16BE (big endian).\n case 24:\n return PA_SAMPLE_S24LE;\n \/\/ Also 24-bits: PA_SAMPLE_S24BE (big endian).\n \/\/ Other cases: PA_SAMPLE_24_32LE (in LSB of 32-bit field, little endian),\n \/\/ and PA_SAMPLE_24_32BE (in LSB of 32-bit field, big endian),\n case 32:\n return PA_SAMPLE_S32LE;\n \/\/ Also 32-bits: PA_SAMPLE_S32BE (big endian),\n \/\/ PA_SAMPLE_FLOAT32LE (floating point little endian),\n \/\/ and PA_SAMPLE_FLOAT32BE (floating point big endian).\n default:\n return PA_SAMPLE_INVALID;\n }\n}\n\nstatic pa_channel_position ChromiumToPAChannelPosition(Channels channel) {\n switch (channel) {\n \/\/ PulseAudio does not differentiate between left\/right and\n \/\/ stereo-left\/stereo-right, both translate to front-left\/front-right.\n case LEFT:\n case STEREO_LEFT:\n return PA_CHANNEL_POSITION_FRONT_LEFT;\n case RIGHT:\n case STEREO_RIGHT:\n return PA_CHANNEL_POSITION_FRONT_RIGHT;\n case CENTER:\n return PA_CHANNEL_POSITION_FRONT_CENTER;\n case LFE:\n return PA_CHANNEL_POSITION_LFE;\n case BACK_LEFT:\n return PA_CHANNEL_POSITION_REAR_LEFT;\n case BACK_RIGHT:\n return PA_CHANNEL_POSITION_REAR_RIGHT;\n case LEFT_OF_CENTER:\n return PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;\n case RIGHT_OF_CENTER:\n return PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;\n case BACK_CENTER:\n return PA_CHANNEL_POSITION_REAR_CENTER;\n case SIDE_LEFT:\n return PA_CHANNEL_POSITION_SIDE_LEFT;\n case SIDE_RIGHT:\n return PA_CHANNEL_POSITION_SIDE_RIGHT;\n case CHANNELS_MAX:\n return PA_CHANNEL_POSITION_INVALID;\n }\n NOTREACHED() << \"Invalid channel \" << channel;\n return PA_CHANNEL_POSITION_INVALID;\n}\n\nstatic pa_channel_map ChannelLayoutToPAChannelMap(\n ChannelLayout channel_layout) {\n \/\/ Initialize channel map.\n pa_channel_map channel_map;\n pa_channel_map_init(&channel_map);\n\n channel_map.channels = ChannelLayoutToChannelCount(channel_layout);\n\n \/\/ All channel maps have the same size array of channel positions.\n for (unsigned int channel = 0; channel != CHANNELS_MAX; ++channel) {\n int channel_position = kChannelOrderings[channel_layout][channel];\n if (channel_position > -1) {\n channel_map.map[channel_position] = ChromiumToPAChannelPosition(\n static_cast<Channels>(channel));\n } else {\n \/\/ PulseAudio expects unused channels in channel maps to be filled with\n \/\/ PA_CHANNEL_POSITION_MONO.\n channel_map.map[channel_position] = PA_CHANNEL_POSITION_MONO;\n }\n }\n\n \/\/ Fill in the rest of the unused channels.\n for (unsigned int channel = CHANNELS_MAX; channel != PA_CHANNELS_MAX;\n ++channel) {\n channel_map.map[channel] = PA_CHANNEL_POSITION_MONO;\n }\n\n return channel_map;\n}\n\nstatic size_t MicrosecondsToBytes(\n uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) {\n return microseconds * sample_rate * bytes_per_frame \/\n base::Time::kMicrosecondsPerSecond;\n}\n\nvoid PulseAudioOutputStream::ContextStateCallback(pa_context* context,\n void* state_addr) {\n pa_context_state_t* state = static_cast<pa_context_state_t*>(state_addr);\n *state = pa_context_get_state(context);\n}\n\nvoid PulseAudioOutputStream::WriteRequestCallback(\n pa_stream* playback_handle, size_t length, void* stream_addr) {\n PulseAudioOutputStream* stream =\n static_cast<PulseAudioOutputStream*>(stream_addr);\n\n DCHECK_EQ(stream->message_loop_, MessageLoop::current());\n\n stream->write_callback_handled_ = true;\n\n \/\/ Fulfill write request.\n stream->FulfillWriteRequest(length);\n}\n\nPulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params,\n AudioManagerLinux* manager,\n MessageLoop* message_loop)\n : channel_layout_(params.channel_layout),\n channel_count_(ChannelLayoutToChannelCount(channel_layout_)),\n sample_format_(BitsToPASampleFormat(params.bits_per_sample)),\n sample_rate_(params.sample_rate),\n bytes_per_frame_(params.channels * params.bits_per_sample \/ 8),\n manager_(manager),\n pa_context_(NULL),\n pa_mainloop_(NULL),\n playback_handle_(NULL),\n packet_size_(params.GetPacketSize()),\n frames_per_packet_(packet_size_ \/ bytes_per_frame_),\n client_buffer_(NULL),\n volume_(1.0f),\n stream_stopped_(true),\n write_callback_handled_(false),\n message_loop_(message_loop),\n ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),\n source_callback_(NULL) {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n DCHECK(manager_);\n\n \/\/ TODO(slock): Sanity check input values.\n}\n\nPulseAudioOutputStream::~PulseAudioOutputStream() {\n \/\/ All internal structures should already have been freed in Close(),\n \/\/ which calls AudioManagerLinux::Release which deletes this object.\n DCHECK(!playback_handle_);\n DCHECK(!pa_context_);\n DCHECK(!pa_mainloop_);\n}\n\nbool PulseAudioOutputStream::Open() {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n \/\/ TODO(slock): Possibly move most of this to an OpenPlaybackDevice function\n \/\/ in a new class 'pulse_util', like alsa_util.\n\n \/\/ Create a mainloop API and connect to the default server.\n pa_mainloop_ = pa_mainloop_new();\n pa_mainloop_api* pa_mainloop_api = pa_mainloop_get_api(pa_mainloop_);\n pa_context_ = pa_context_new(pa_mainloop_api, \"Chromium\");\n pa_context_state_t pa_context_state = PA_CONTEXT_UNCONNECTED;\n pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL);\n\n \/\/ Wait until PulseAudio is ready.\n pa_context_set_state_callback(pa_context_, &ContextStateCallback,\n &pa_context_state);\n while (pa_context_state != PA_CONTEXT_READY) {\n pa_mainloop_iterate(pa_mainloop_, 1, NULL);\n if (pa_context_state == PA_CONTEXT_FAILED ||\n pa_context_state == PA_CONTEXT_TERMINATED) {\n Reset();\n return false;\n }\n }\n\n \/\/ Set sample specifications.\n pa_sample_spec pa_sample_specifications;\n pa_sample_specifications.format = sample_format_;\n pa_sample_specifications.rate = sample_rate_;\n pa_sample_specifications.channels = channel_count_;\n\n \/\/ Get channel mapping and open playback stream.\n pa_channel_map* map = NULL;\n pa_channel_map source_channel_map = ChannelLayoutToPAChannelMap(\n channel_layout_);\n if (source_channel_map.channels != 0) {\n \/\/ The source data uses a supported channel map so we will use it rather\n \/\/ than the default channel map (NULL).\n map = &source_channel_map;\n }\n playback_handle_ = pa_stream_new(pa_context_, \"Playback\",\n &pa_sample_specifications, map);\n\n \/\/ Initialize client buffer.\n uint32 output_packet_size = frames_per_packet_ * bytes_per_frame_;\n client_buffer_.reset(new media::SeekableBuffer(0, output_packet_size));\n\n \/\/ Set write callback.\n pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this);\n\n \/\/ Set server-side buffer attributes.\n \/\/ (uint32_t)-1 is the default and recommended value from PulseAudio's\n \/\/ documentation, found at:\n \/\/ http:\/\/freedesktop.org\/software\/pulseaudio\/doxygen\/structpa__buffer__attr.html.\n pa_buffer_attr pa_buffer_attributes;\n pa_buffer_attributes.maxlength = static_cast<uint32_t>(-1);\n pa_buffer_attributes.tlength = output_packet_size;\n pa_buffer_attributes.prebuf = static_cast<uint32_t>(-1);\n pa_buffer_attributes.minreq = static_cast<uint32_t>(-1);\n pa_buffer_attributes.fragsize = static_cast<uint32_t>(-1);\n\n \/\/ Connect playback stream.\n pa_stream_connect_playback(playback_handle_, NULL,\n &pa_buffer_attributes,\n (pa_stream_flags_t)\n (PA_STREAM_INTERPOLATE_TIMING |\n PA_STREAM_ADJUST_LATENCY |\n PA_STREAM_AUTO_TIMING_UPDATE),\n NULL, NULL);\n\n if (!playback_handle_) {\n Reset();\n return false;\n }\n\n return true;\n}\n\nvoid PulseAudioOutputStream::Reset() {\n stream_stopped_ = true;\n\n \/\/ Close the stream.\n if (playback_handle_) {\n pa_stream_flush(playback_handle_, NULL, NULL);\n pa_stream_disconnect(playback_handle_);\n\n \/\/ Release PulseAudio structures.\n pa_stream_unref(playback_handle_);\n playback_handle_ = NULL;\n }\n if (pa_context_) {\n pa_context_unref(pa_context_);\n pa_context_ = NULL;\n }\n if (pa_mainloop_) {\n pa_mainloop_free(pa_mainloop_);\n pa_mainloop_ = NULL;\n }\n\n \/\/ Release internal buffer.\n client_buffer_.reset();\n}\n\nvoid PulseAudioOutputStream::Close() {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n Reset();\n\n \/\/ Signal to the manager that we're closed and can be removed.\n \/\/ This should be the last call in the function as it deletes \"this\".\n manager_->ReleaseOutputStream(this);\n}\n\nvoid PulseAudioOutputStream::WaitForWriteRequest() {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n if (stream_stopped_)\n return;\n\n \/\/ Iterate the PulseAudio mainloop. If PulseAudio doesn't request a write,\n \/\/ post a task to iterate the mainloop again.\n write_callback_handled_ = false;\n pa_mainloop_iterate(pa_mainloop_, 1, NULL);\n if (!write_callback_handled_) {\n message_loop_->PostTask(FROM_HERE, base::Bind(\n &PulseAudioOutputStream::WaitForWriteRequest,\n weak_factory_.GetWeakPtr()));\n }\n}\n\nbool PulseAudioOutputStream::BufferPacketFromSource() {\n uint32 buffer_delay = client_buffer_->forward_bytes();\n pa_usec_t pa_latency_micros;\n int negative;\n pa_stream_get_latency(playback_handle_, &pa_latency_micros, &negative);\n uint32 hardware_delay = MicrosecondsToBytes(pa_latency_micros,\n sample_rate_,\n bytes_per_frame_);\n \/\/ TODO(slock): Deal with negative latency (negative == 1). This has yet\n \/\/ to happen in practice though.\n scoped_refptr<media::DataBuffer> packet =\n new media::DataBuffer(packet_size_);\n size_t packet_size = RunDataCallback(packet->GetWritableData(),\n packet->GetBufferSize(),\n AudioBuffersState(buffer_delay,\n hardware_delay));\n\n if (packet_size == 0)\n return false;\n\n media::AdjustVolume(packet->GetWritableData(),\n packet_size,\n channel_count_,\n bytes_per_frame_ \/ channel_count_,\n volume_);\n packet->SetDataSize(packet_size);\n \/\/ Add the packet to the buffer.\n client_buffer_->Append(packet);\n return true;\n}\n\nvoid PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) {\n \/\/ If we have enough data to fulfill the request, we can finish the write.\n if (stream_stopped_)\n return;\n\n \/\/ Request more data from the source until we can fulfill the request or\n \/\/ fail to receive anymore data.\n bool buffering_successful = true;\n while (client_buffer_->forward_bytes() < requested_bytes &&\n buffering_successful) {\n buffering_successful = BufferPacketFromSource();\n }\n\n size_t bytes_written = 0;\n if (client_buffer_->forward_bytes() > 0) {\n \/\/ Try to fulfill the request by writing as many of the requested bytes to\n \/\/ the stream as we can.\n WriteToStream(requested_bytes, &bytes_written);\n }\n\n if (bytes_written < requested_bytes) {\n \/\/ We weren't able to buffer enough data to fulfill the request. Try to\n \/\/ fulfill the rest of the request later.\n message_loop_->PostTask(FROM_HERE, base::Bind(\n &PulseAudioOutputStream::FulfillWriteRequest,\n weak_factory_.GetWeakPtr(),\n requested_bytes - bytes_written));\n } else {\n \/\/ Continue playback.\n message_loop_->PostTask(FROM_HERE, base::Bind(\n &PulseAudioOutputStream::WaitForWriteRequest,\n weak_factory_.GetWeakPtr()));\n }\n}\n\nvoid PulseAudioOutputStream::WriteToStream(size_t bytes_to_write,\n size_t* bytes_written) {\n *bytes_written = 0;\n while (*bytes_written < bytes_to_write) {\n const uint8* chunk;\n size_t chunk_size;\n\n \/\/ Stop writing if there is no more data available.\n if (!client_buffer_->GetCurrentChunk(&chunk, &chunk_size))\n break;\n\n \/\/ Write data to stream.\n pa_stream_write(playback_handle_, chunk, chunk_size,\n NULL, 0LL, PA_SEEK_RELATIVE);\n client_buffer_->Seek(chunk_size);\n *bytes_written += chunk_size;\n }\n}\n\nvoid PulseAudioOutputStream::Start(AudioSourceCallback* callback) {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n CHECK(callback);\n source_callback_ = callback;\n\n \/\/ Clear buffer, it might still have data in it.\n client_buffer_->Clear();\n stream_stopped_ = false;\n\n \/\/ Start playback.\n message_loop_->PostTask(FROM_HERE, base::Bind(\n &PulseAudioOutputStream::WaitForWriteRequest,\n weak_factory_.GetWeakPtr()));\n}\n\nvoid PulseAudioOutputStream::Stop() {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n stream_stopped_ = true;\n}\n\nvoid PulseAudioOutputStream::SetVolume(double volume) {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n volume_ = static_cast<float>(volume);\n}\n\nvoid PulseAudioOutputStream::GetVolume(double* volume) {\n DCHECK_EQ(message_loop_, MessageLoop::current());\n\n *volume = volume_;\n}\n\nuint32 PulseAudioOutputStream::RunDataCallback(\n uint8* dest, uint32 max_size, AudioBuffersState buffers_state) {\n if (source_callback_)\n return source_callback_->OnMoreData(this, dest, max_size, buffers_state);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 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 \"base\/logging.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_split.h\"\n#include \"base\/string_util.h\"\n#include \"media\/filters\/adaptive_demuxer.h\"\n\nnamespace media {\n\n\/\/\n\/\/ AdaptiveDemuxerStream\n\/\/\nAdaptiveDemuxerStream::AdaptiveDemuxerStream(\n StreamVector const& streams, int initial_stream)\n : streams_(streams), current_stream_index_(initial_stream),\n bitstream_converter_enabled_(false) {\n DCheckSanity();\n}\n\nvoid AdaptiveDemuxerStream::DCheckSanity() {\n \/\/ We only carry out sanity checks in debug mode.\n if (!logging::DEBUG_MODE)\n return;\n DCHECK(streams_[current_stream_index_].get());\n\n bool non_null_stream_seen = false;\n Type type;\n const MediaFormat* media_format = NULL;\n for (size_t i = 0; i < streams_.size(); ++i) {\n if (!streams_[i])\n continue;\n\n if (!non_null_stream_seen) {\n non_null_stream_seen = true;\n type = streams_[i]->type();\n media_format = &streams_[i]->media_format();\n } else {\n DCHECK_EQ(streams_[i]->type(), type);\n DCHECK(streams_[i]->media_format() == *media_format);\n }\n }\n}\n\nAdaptiveDemuxerStream::~AdaptiveDemuxerStream() {\n base::AutoLock auto_lock(lock_);\n current_stream_index_ = -1;\n streams_.clear();\n}\n\nDemuxerStream* AdaptiveDemuxerStream::current_stream() {\n base::AutoLock auto_lock(lock_);\n return streams_[current_stream_index_];\n}\n\nvoid AdaptiveDemuxerStream::Read(Callback1<Buffer*>::Type* read_callback) {\n current_stream()->Read(read_callback);\n}\n\nAVStream* AdaptiveDemuxerStream::GetAVStream() {\n return current_stream()->GetAVStream();\n}\n\nDemuxerStream::Type AdaptiveDemuxerStream::type() {\n return current_stream()->type();\n}\n\nconst MediaFormat& AdaptiveDemuxerStream::media_format() {\n return current_stream()->media_format();\n}\n\nvoid AdaptiveDemuxerStream::EnableBitstreamConverter() {\n {\n base::AutoLock auto_lock(lock_);\n bitstream_converter_enabled_ = true;\n }\n current_stream()->EnableBitstreamConverter();\n}\n\nvoid AdaptiveDemuxerStream::ChangeCurrentStream(int index) {\n bool needs_bitstream_converter_enabled;\n {\n base::AutoLock auto_lock(lock_);\n current_stream_index_ = index;\n DCHECK(streams_[current_stream_index_]);\n needs_bitstream_converter_enabled = bitstream_converter_enabled_;\n }\n if (needs_bitstream_converter_enabled)\n EnableBitstreamConverter();\n}\n\n\/\/\n\/\/ AdaptiveDemuxer\n\/\/\n\nAdaptiveDemuxer::AdaptiveDemuxer(DemuxerVector const& demuxers,\n int initial_audio_demuxer_index,\n int initial_video_demuxer_index)\n : demuxers_(demuxers),\n current_audio_demuxer_index_(initial_audio_demuxer_index),\n current_video_demuxer_index_(initial_video_demuxer_index) {\n DCHECK(!demuxers_.empty());\n DCHECK_GE(current_audio_demuxer_index_, -1);\n DCHECK_GE(current_video_demuxer_index_, -1);\n DCHECK_LT(current_audio_demuxer_index_, static_cast<int>(demuxers_.size()));\n DCHECK_LT(current_video_demuxer_index_, static_cast<int>(demuxers_.size()));\n DCHECK(current_audio_demuxer_index_ != -1 ||\n current_video_demuxer_index_ != -1);\n AdaptiveDemuxerStream::StreamVector audio_streams, video_streams;\n for (size_t i = 0; i < demuxers_.size(); ++i) {\n audio_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::AUDIO));\n video_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::VIDEO));\n }\n if (current_audio_demuxer_index_ >= 0) {\n audio_stream_ = new AdaptiveDemuxerStream(\n audio_streams, current_audio_demuxer_index_);\n }\n if (current_video_demuxer_index_ >= 0) {\n video_stream_ = new AdaptiveDemuxerStream(\n video_streams, current_video_demuxer_index_);\n }\n\n \/\/ TODO(fischman): any streams in the underlying demuxers that aren't being\n \/\/ consumed currently need to be sent to \/dev\/null or else FFmpegDemuxer will\n \/\/ hold data for them in memory, waiting for them to get drained by a\n \/\/ non-existent decoder.\n}\n\nAdaptiveDemuxer::~AdaptiveDemuxer() {}\n\nvoid AdaptiveDemuxer::ChangeCurrentDemuxer(int audio_index, int video_index) {\n \/\/ TODO(fischman): this is currently broken because when a new Demuxer is to\n \/\/ be used we need to set_host(host()) it, and we need to set_host(NULL) the\n \/\/ current Demuxer if it's no longer being used.\n \/\/ TODO(fischman): remember to Stop active demuxers that are being abandoned.\n base::AutoLock auto_lock(lock_);\n current_audio_demuxer_index_ = audio_index;\n current_video_demuxer_index_ = video_index;\n if (audio_stream_)\n audio_stream_->ChangeCurrentStream(audio_index);\n if (video_stream_)\n video_stream_->ChangeCurrentStream(video_index);\n}\n\nDemuxer* AdaptiveDemuxer::current_demuxer(DemuxerStream::Type type) {\n base::AutoLock auto_lock(lock_);\n switch (type) {\n case DemuxerStream::AUDIO:\n return (current_audio_demuxer_index_ < 0) ? NULL :\n demuxers_[current_audio_demuxer_index_];\n case DemuxerStream::VIDEO:\n return (current_video_demuxer_index_ < 0) ? NULL :\n demuxers_[current_video_demuxer_index_];\n default:\n LOG(DFATAL) << \"Unexpected type: \" << type;\n return NULL;\n }\n}\n\n\/\/ Helper class that wraps a FilterCallback and expects to get called a set\n\/\/ number of times, after which the wrapped callback is fired (and deleted).\nclass CountingCallback {\n public:\n CountingCallback(int count, FilterCallback* orig_cb)\n : remaining_count_(count), orig_cb_(orig_cb) {\n DCHECK_GT(remaining_count_, 0);\n DCHECK(orig_cb);\n }\n\n FilterCallback* GetACallback() {\n return NewCallback(this, &CountingCallback::OnChildCallbackDone);\n }\n\n private:\n void OnChildCallbackDone() {\n bool fire_orig_cb = false;\n {\n base::AutoLock auto_lock(lock_);\n if (--remaining_count_ == 0)\n fire_orig_cb = true;\n }\n if (fire_orig_cb) {\n orig_cb_->Run();\n delete this;\n }\n }\n\n base::Lock lock_;\n int remaining_count_;\n scoped_ptr<FilterCallback> orig_cb_;\n};\n\nvoid AdaptiveDemuxer::Stop(FilterCallback* callback) {\n Demuxer* audio = current_demuxer(DemuxerStream::AUDIO);\n Demuxer* video = current_demuxer(DemuxerStream::VIDEO);\n int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0);\n CountingCallback* wrapper = new CountingCallback(count, callback);\n if (audio)\n audio->Stop(wrapper->GetACallback());\n if (video && audio != video)\n video->Stop(wrapper->GetACallback());\n}\n\nvoid AdaptiveDemuxer::Seek(base::TimeDelta time, FilterCallback* callback) {\n Demuxer* audio = current_demuxer(DemuxerStream::AUDIO);\n Demuxer* video = current_demuxer(DemuxerStream::VIDEO);\n int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0);\n CountingCallback* wrapper = new CountingCallback(count, callback);\n if (audio)\n audio->Seek(time, wrapper->GetACallback());\n if (video && audio != video)\n video->Seek(time, wrapper->GetACallback());\n}\n\nvoid AdaptiveDemuxer::OnAudioRendererDisabled() {\n Demuxer* audio = current_demuxer(DemuxerStream::AUDIO);\n Demuxer* video = current_demuxer(DemuxerStream::VIDEO);\n if (audio) audio->OnAudioRendererDisabled();\n if (video && audio != video) video->OnAudioRendererDisabled();\n \/\/ TODO(fischman): propagate to other demuxers if\/when they're selected.\n}\n\nvoid AdaptiveDemuxer::set_host(FilterHost* filter_host) {\n Demuxer* audio = current_demuxer(DemuxerStream::AUDIO);\n Demuxer* video = current_demuxer(DemuxerStream::VIDEO);\n if (audio) audio->set_host(filter_host);\n if (video && audio != video) video->set_host(filter_host);\n}\n\nscoped_refptr<DemuxerStream> AdaptiveDemuxer::GetStream(\n DemuxerStream::Type type) {\n switch (type) {\n case DemuxerStream::AUDIO:\n return audio_stream_;\n case DemuxerStream::VIDEO:\n return video_stream_;\n default:\n LOG(DFATAL) << \"Unexpected type \" << type;\n return NULL;\n }\n}\n\n\/\/\n\/\/ AdaptiveDemuxerFactory\n\/\/\n\nAdaptiveDemuxerFactory::AdaptiveDemuxerFactory(\n DemuxerFactory* delegate_factory)\n : delegate_factory_(delegate_factory) {\n DCHECK(delegate_factory);\n}\n\nAdaptiveDemuxerFactory::~AdaptiveDemuxerFactory() {}\n\nDemuxerFactory* AdaptiveDemuxerFactory::Clone() const {\n return new AdaptiveDemuxerFactory(delegate_factory_->Clone());\n}\n\n\/\/ See AdaptiveDemuxerFactory's class-level comment for |url|'s format.\nbool ParseAdaptiveUrl(\n const std::string& url, int* audio_index, int* video_index,\n std::vector<std::string>* urls) {\n urls->clear();\n\n if (url.empty())\n return false;\n if (!StartsWithASCII(url, \"x-adaptive:\", false)) {\n return ParseAdaptiveUrl(\n \"x-adaptive:0:0:\" + url, audio_index, video_index, urls);\n }\n\n std::vector<std::string> parts;\n base::SplitStringDontTrim(url, ':', &parts);\n if (parts.size() < 4 ||\n parts[0] != \"x-adaptive\" ||\n !base::StringToInt(parts[1], audio_index) ||\n !base::StringToInt(parts[2], video_index) ||\n *audio_index < -1 || *video_index < -1) {\n return false;\n }\n\n std::string::size_type first_url_pos =\n parts[0].size() + 1 + parts[1].size() + 1 + parts[2].size() + 1;\n std::string urls_str = url.substr(first_url_pos);\n if (urls_str.empty())\n return false;\n base::SplitStringDontTrim(urls_str, '^', urls);\n if (urls->empty() ||\n *audio_index >= static_cast<int>(urls->size()) ||\n *video_index >= static_cast<int>(urls->size())) {\n return false;\n }\n\n return true;\n}\n\n\/\/ Wrapper for a BuildCallback which accumulates the Demuxer's returned by a\n\/\/ number of DemuxerFactory::Build() calls and eventually constructs an\n\/\/ AdaptiveDemuxer and returns it to the |orig_cb| (or errors out if any\n\/\/ individual Demuxer fails construction).\nclass DemuxerAccumulator {\n public:\n \/\/ Takes ownership of |orig_cb|.\n DemuxerAccumulator(int audio_index, int video_index,\n int count, DemuxerFactory::BuildCallback* orig_cb)\n : audio_index_(audio_index), video_index_(video_index),\n remaining_count_(count), orig_cb_(orig_cb),\n demuxers_(count, static_cast<Demuxer*>(NULL)),\n statuses_(count, PIPELINE_OK) {\n DCHECK_GT(remaining_count_, 0);\n DCHECK(orig_cb_.get());\n }\n\n DemuxerFactory::BuildCallback* GetNthCallback(int n) {\n return new IndividualCallback(this, n);\n }\n\n private:\n \/\/ Wrapper for a BuildCallback that can carry one extra piece of data: the\n \/\/ index of this callback in the original list of outstanding requests.\n struct IndividualCallback : public DemuxerFactory::BuildCallback {\n IndividualCallback(DemuxerAccumulator* accumulator, int index)\n : accumulator_(accumulator), index_(index) {}\n\n virtual void RunWithParams(const Tuple2<PipelineStatus, Demuxer*>& params) {\n accumulator_->Run(index_, params.a, params.b);\n }\n DemuxerAccumulator* accumulator_;\n int index_;\n };\n\n \/\/ When an individual callback is fired, it calls this method.\n void Run(int index, PipelineStatus status, Demuxer* demuxer) {\n bool fire_orig_cb = false;\n {\n base::AutoLock auto_lock(lock_);\n DCHECK(!demuxers_[index]);\n demuxers_[index] = demuxer;\n statuses_[index] = status;\n if (--remaining_count_ == 0)\n fire_orig_cb = true;\n }\n if (fire_orig_cb)\n DoneAccumulating();\n }\n\n void DoneAccumulating() {\n PipelineStatus overall_status = PIPELINE_OK;\n for (size_t i = 0; i < statuses_.size(); ++i) {\n if (statuses_[i] != PIPELINE_OK) {\n overall_status = statuses_[i];\n break;\n }\n }\n if (overall_status == PIPELINE_OK) {\n orig_cb_->Run(\n PIPELINE_OK,\n new AdaptiveDemuxer(demuxers_, audio_index_, video_index_));\n } else {\n orig_cb_->Run(overall_status, static_cast<Demuxer*>(NULL));\n }\n\n delete this;\n }\n\n \/\/ Self-delete in DoneAccumulating() only.\n ~DemuxerAccumulator() {}\n\n int audio_index_;\n int video_index_;\n int remaining_count_;\n scoped_ptr<DemuxerFactory::BuildCallback> orig_cb_;\n base::Lock lock_; \/\/ Guards vectors of results below.\n AdaptiveDemuxer::DemuxerVector demuxers_;\n std::vector<PipelineStatus> statuses_;\n\n DISALLOW_IMPLICIT_CONSTRUCTORS(DemuxerAccumulator);\n};\n\nvoid AdaptiveDemuxerFactory::Build(const std::string& url, BuildCallback* cb) {\n std::vector<std::string> urls;\n int audio_index, video_index;\n if (!ParseAdaptiveUrl(url, &audio_index, &video_index, &urls)) {\n cb->Run(Tuple2<PipelineStatus, Demuxer*>(\n DEMUXER_ERROR_COULD_NOT_OPEN, NULL));\n delete cb;\n return;\n }\n DemuxerAccumulator* accumulator = new DemuxerAccumulator(\n audio_index, video_index, urls.size(), cb);\n for (size_t i = 0; i < urls.size(); ++i)\n delegate_factory_->Build(urls[i], accumulator->GetNthCallback(i));\n}\n\n} \/\/ namespace media\n<commit_msg>Fix an uninitialized variable compiler warning on some systems. BUG=none TEST=none Review URL: http:\/\/codereview.chromium.org\/6677123<commit_after>\/\/ Copyright (c) 2011 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 \"base\/logging.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_split.h\"\n#include \"base\/string_util.h\"\n#include \"media\/filters\/adaptive_demuxer.h\"\n\nnamespace media {\n\n\/\/\n\/\/ AdaptiveDemuxerStream\n\/\/\nAdaptiveDemuxerStream::AdaptiveDemuxerStream(\n StreamVector const& streams, int initial_stream)\n : streams_(streams), current_stream_index_(initial_stream),\n bitstream_converter_enabled_(false) {\n DCheckSanity();\n}\n\nvoid AdaptiveDemuxerStream::DCheckSanity() {\n \/\/ We only carry out sanity checks in debug mode.\n if (!logging::DEBUG_MODE)\n return;\n DCHECK(streams_[current_stream_index_].get());\n\n bool non_null_stream_seen = false;\n Type type = DemuxerStream::UNKNOWN;\n const MediaFormat* media_format = NULL;\n for (size_t i = 0; i < streams_.size(); ++i) {\n if (!streams_[i])\n continue;\n\n if (!non_null_stream_seen) {\n non_null_stream_seen = true;\n type = streams_[i]->type();\n media_format = &streams_[i]->media_format();\n } else {\n DCHECK_EQ(streams_[i]->type(), type);\n DCHECK(streams_[i]->media_format() == *media_format);\n }\n }\n}\n\nAdaptiveDemuxerStream::~AdaptiveDemuxerStream() {\n base::AutoLock auto_lock(lock_);\n current_stream_index_ = -1;\n streams_.clear();\n}\n\nDemuxerStream* AdaptiveDemuxerStream::current_stream() {\n base::AutoLock auto_lock(lock_);\n return streams_[current_stream_index_];\n}\n\nvoid AdaptiveDemuxerStream::Read(Callback1<Buffer*>::Type* read_callback) {\n current_stream()->Read(read_callback);\n}\n\nAVStream* AdaptiveDemuxerStream::GetAVStream() {\n return current_stream()->GetAVStream();\n}\n\nDemuxerStream::Type AdaptiveDemuxerStream::type() {\n return current_stream()->type();\n}\n\nconst MediaFormat& AdaptiveDemuxerStream::media_format() {\n return current_stream()->media_format();\n}\n\nvoid AdaptiveDemuxerStream::EnableBitstreamConverter() {\n {\n base::AutoLock auto_lock(lock_);\n bitstream_converter_enabled_ = true;\n }\n current_stream()->EnableBitstreamConverter();\n}\n\nvoid AdaptiveDemuxerStream::ChangeCurrentStream(int index) {\n bool needs_bitstream_converter_enabled;\n {\n base::AutoLock auto_lock(lock_);\n current_stream_index_ = index;\n DCHECK(streams_[current_stream_index_]);\n needs_bitstream_converter_enabled = bitstream_converter_enabled_;\n }\n if (needs_bitstream_converter_enabled)\n EnableBitstreamConverter();\n}\n\n\/\/\n\/\/ AdaptiveDemuxer\n\/\/\n\nAdaptiveDemuxer::AdaptiveDemuxer(DemuxerVector const& demuxers,\n int initial_audio_demuxer_index,\n int initial_video_demuxer_index)\n : demuxers_(demuxers),\n current_audio_demuxer_index_(initial_audio_demuxer_index),\n current_video_demuxer_index_(initial_video_demuxer_index) {\n DCHECK(!demuxers_.empty());\n DCHECK_GE(current_audio_demuxer_index_, -1);\n DCHECK_GE(current_video_demuxer_index_, -1);\n DCHECK_LT(current_audio_demuxer_index_, static_cast<int>(demuxers_.size()));\n DCHECK_LT(current_video_demuxer_index_, static_cast<int>(demuxers_.size()));\n DCHECK(current_audio_demuxer_index_ != -1 ||\n current_video_demuxer_index_ != -1);\n AdaptiveDemuxerStream::StreamVector audio_streams, video_streams;\n for (size_t i = 0; i < demuxers_.size(); ++i) {\n audio_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::AUDIO));\n video_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::VIDEO));\n }\n if (current_audio_demuxer_index_ >= 0) {\n audio_stream_ = new AdaptiveDemuxerStream(\n audio_streams, current_audio_demuxer_index_);\n }\n if (current_video_demuxer_index_ >= 0) {\n video_stream_ = new AdaptiveDemuxerStream(\n video_streams, current_video_demuxer_index_);\n }\n\n \/\/ TODO(fischman): any streams in the underlying demuxers that aren't being\n \/\/ consumed currently need to be sent to \/dev\/null or else FFmpegDemuxer will\n \/\/ hold data for them in memory, waiting for them to get drained by a\n \/\/ non-existent decoder.\n}\n\nAdaptiveDemuxer::~AdaptiveDemuxer() {}\n\nvoid AdaptiveDemuxer::ChangeCurrentDemuxer(int audio_index, int video_index) {\n \/\/ TODO(fischman): this is currently broken because when a new Demuxer is to\n \/\/ be used we need to set_host(host()) it, and we need to set_host(NULL) the\n \/\/ current Demuxer if it's no longer being used.\n \/\/ TODO(fischman): remember to Stop active demuxers that are being abandoned.\n base::AutoLock auto_lock(lock_);\n current_audio_demuxer_index_ = audio_index;\n current_video_demuxer_index_ = video_index;\n if (audio_stream_)\n audio_stream_->ChangeCurrentStream(audio_index);\n if (video_stream_)\n video_stream_->ChangeCurrentStream(video_index);\n}\n\nDemuxer* AdaptiveDemuxer::current_demuxer(DemuxerStream::Type type) {\n base::AutoLock auto_lock(lock_);\n switch (type) {\n case DemuxerStream::AUDIO:\n return (current_audio_demuxer_index_ < 0) ? NULL :\n demuxers_[current_audio_demuxer_index_];\n case DemuxerStream::VIDEO:\n return (current_video_demuxer_index_ < 0) ? NULL :\n demuxers_[current_video_demuxer_index_];\n default:\n LOG(DFATAL) << \"Unexpected type: \" << type;\n return NULL;\n }\n}\n\n\/\/ Helper class that wraps a FilterCallback and expects to get called a set\n\/\/ number of times, after which the wrapped callback is fired (and deleted).\nclass CountingCallback {\n public:\n CountingCallback(int count, FilterCallback* orig_cb)\n : remaining_count_(count), orig_cb_(orig_cb) {\n DCHECK_GT(remaining_count_, 0);\n DCHECK(orig_cb);\n }\n\n FilterCallback* GetACallback() {\n return NewCallback(this, &CountingCallback::OnChildCallbackDone);\n }\n\n private:\n void OnChildCallbackDone() {\n bool fire_orig_cb = false;\n {\n base::AutoLock auto_lock(lock_);\n if (--remaining_count_ == 0)\n fire_orig_cb = true;\n }\n if (fire_orig_cb) {\n orig_cb_->Run();\n delete this;\n }\n }\n\n base::Lock lock_;\n int remaining_count_;\n scoped_ptr<FilterCallback> orig_cb_;\n};\n\nvoid AdaptiveDemuxer::Stop(FilterCallback* callback) {\n Demuxer* audio = current_demuxer(DemuxerStream::AUDIO);\n Demuxer* video = current_demuxer(DemuxerStream::VIDEO);\n int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0);\n CountingCallback* wrapper = new CountingCallback(count, callback);\n if (audio)\n audio->Stop(wrapper->GetACallback());\n if (video && audio != video)\n video->Stop(wrapper->GetACallback());\n}\n\nvoid AdaptiveDemuxer::Seek(base::TimeDelta time, FilterCallback* callback) {\n Demuxer* audio = current_demuxer(DemuxerStream::AUDIO);\n Demuxer* video = current_demuxer(DemuxerStream::VIDEO);\n int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0);\n CountingCallback* wrapper = new CountingCallback(count, callback);\n if (audio)\n audio->Seek(time, wrapper->GetACallback());\n if (video && audio != video)\n video->Seek(time, wrapper->GetACallback());\n}\n\nvoid AdaptiveDemuxer::OnAudioRendererDisabled() {\n Demuxer* audio = current_demuxer(DemuxerStream::AUDIO);\n Demuxer* video = current_demuxer(DemuxerStream::VIDEO);\n if (audio) audio->OnAudioRendererDisabled();\n if (video && audio != video) video->OnAudioRendererDisabled();\n \/\/ TODO(fischman): propagate to other demuxers if\/when they're selected.\n}\n\nvoid AdaptiveDemuxer::set_host(FilterHost* filter_host) {\n Demuxer* audio = current_demuxer(DemuxerStream::AUDIO);\n Demuxer* video = current_demuxer(DemuxerStream::VIDEO);\n if (audio) audio->set_host(filter_host);\n if (video && audio != video) video->set_host(filter_host);\n}\n\nscoped_refptr<DemuxerStream> AdaptiveDemuxer::GetStream(\n DemuxerStream::Type type) {\n switch (type) {\n case DemuxerStream::AUDIO:\n return audio_stream_;\n case DemuxerStream::VIDEO:\n return video_stream_;\n default:\n LOG(DFATAL) << \"Unexpected type \" << type;\n return NULL;\n }\n}\n\n\/\/\n\/\/ AdaptiveDemuxerFactory\n\/\/\n\nAdaptiveDemuxerFactory::AdaptiveDemuxerFactory(\n DemuxerFactory* delegate_factory)\n : delegate_factory_(delegate_factory) {\n DCHECK(delegate_factory);\n}\n\nAdaptiveDemuxerFactory::~AdaptiveDemuxerFactory() {}\n\nDemuxerFactory* AdaptiveDemuxerFactory::Clone() const {\n return new AdaptiveDemuxerFactory(delegate_factory_->Clone());\n}\n\n\/\/ See AdaptiveDemuxerFactory's class-level comment for |url|'s format.\nbool ParseAdaptiveUrl(\n const std::string& url, int* audio_index, int* video_index,\n std::vector<std::string>* urls) {\n urls->clear();\n\n if (url.empty())\n return false;\n if (!StartsWithASCII(url, \"x-adaptive:\", false)) {\n return ParseAdaptiveUrl(\n \"x-adaptive:0:0:\" + url, audio_index, video_index, urls);\n }\n\n std::vector<std::string> parts;\n base::SplitStringDontTrim(url, ':', &parts);\n if (parts.size() < 4 ||\n parts[0] != \"x-adaptive\" ||\n !base::StringToInt(parts[1], audio_index) ||\n !base::StringToInt(parts[2], video_index) ||\n *audio_index < -1 || *video_index < -1) {\n return false;\n }\n\n std::string::size_type first_url_pos =\n parts[0].size() + 1 + parts[1].size() + 1 + parts[2].size() + 1;\n std::string urls_str = url.substr(first_url_pos);\n if (urls_str.empty())\n return false;\n base::SplitStringDontTrim(urls_str, '^', urls);\n if (urls->empty() ||\n *audio_index >= static_cast<int>(urls->size()) ||\n *video_index >= static_cast<int>(urls->size())) {\n return false;\n }\n\n return true;\n}\n\n\/\/ Wrapper for a BuildCallback which accumulates the Demuxer's returned by a\n\/\/ number of DemuxerFactory::Build() calls and eventually constructs an\n\/\/ AdaptiveDemuxer and returns it to the |orig_cb| (or errors out if any\n\/\/ individual Demuxer fails construction).\nclass DemuxerAccumulator {\n public:\n \/\/ Takes ownership of |orig_cb|.\n DemuxerAccumulator(int audio_index, int video_index,\n int count, DemuxerFactory::BuildCallback* orig_cb)\n : audio_index_(audio_index), video_index_(video_index),\n remaining_count_(count), orig_cb_(orig_cb),\n demuxers_(count, static_cast<Demuxer*>(NULL)),\n statuses_(count, PIPELINE_OK) {\n DCHECK_GT(remaining_count_, 0);\n DCHECK(orig_cb_.get());\n }\n\n DemuxerFactory::BuildCallback* GetNthCallback(int n) {\n return new IndividualCallback(this, n);\n }\n\n private:\n \/\/ Wrapper for a BuildCallback that can carry one extra piece of data: the\n \/\/ index of this callback in the original list of outstanding requests.\n struct IndividualCallback : public DemuxerFactory::BuildCallback {\n IndividualCallback(DemuxerAccumulator* accumulator, int index)\n : accumulator_(accumulator), index_(index) {}\n\n virtual void RunWithParams(const Tuple2<PipelineStatus, Demuxer*>& params) {\n accumulator_->Run(index_, params.a, params.b);\n }\n DemuxerAccumulator* accumulator_;\n int index_;\n };\n\n \/\/ When an individual callback is fired, it calls this method.\n void Run(int index, PipelineStatus status, Demuxer* demuxer) {\n bool fire_orig_cb = false;\n {\n base::AutoLock auto_lock(lock_);\n DCHECK(!demuxers_[index]);\n demuxers_[index] = demuxer;\n statuses_[index] = status;\n if (--remaining_count_ == 0)\n fire_orig_cb = true;\n }\n if (fire_orig_cb)\n DoneAccumulating();\n }\n\n void DoneAccumulating() {\n PipelineStatus overall_status = PIPELINE_OK;\n for (size_t i = 0; i < statuses_.size(); ++i) {\n if (statuses_[i] != PIPELINE_OK) {\n overall_status = statuses_[i];\n break;\n }\n }\n if (overall_status == PIPELINE_OK) {\n orig_cb_->Run(\n PIPELINE_OK,\n new AdaptiveDemuxer(demuxers_, audio_index_, video_index_));\n } else {\n orig_cb_->Run(overall_status, static_cast<Demuxer*>(NULL));\n }\n\n delete this;\n }\n\n \/\/ Self-delete in DoneAccumulating() only.\n ~DemuxerAccumulator() {}\n\n int audio_index_;\n int video_index_;\n int remaining_count_;\n scoped_ptr<DemuxerFactory::BuildCallback> orig_cb_;\n base::Lock lock_; \/\/ Guards vectors of results below.\n AdaptiveDemuxer::DemuxerVector demuxers_;\n std::vector<PipelineStatus> statuses_;\n\n DISALLOW_IMPLICIT_CONSTRUCTORS(DemuxerAccumulator);\n};\n\nvoid AdaptiveDemuxerFactory::Build(const std::string& url, BuildCallback* cb) {\n std::vector<std::string> urls;\n int audio_index, video_index;\n if (!ParseAdaptiveUrl(url, &audio_index, &video_index, &urls)) {\n cb->Run(Tuple2<PipelineStatus, Demuxer*>(\n DEMUXER_ERROR_COULD_NOT_OPEN, NULL));\n delete cb;\n return;\n }\n DemuxerAccumulator* accumulator = new DemuxerAccumulator(\n audio_index, video_index, urls.size(), cb);\n for (size_t i = 0; i < urls.size(); ++i)\n delegate_factory_->Build(urls[i], accumulator->GetNthCallback(i));\n}\n\n} \/\/ namespace media\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: gcach_ftyp.hxx,v $\n *\n * $Revision: 1.39 $\n *\n * last change: $Author: hr $ $Date: 2007-07-31 16:09:30 $\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 _SV_GCACHFTYP_HXX\n#define _SV_GCACHFTYP_HXX\n\n#include <vcl\/glyphcache.hxx>\n#include <rtl\/textcvt.h>\n\n#include <ft2build.h>\n#include FT_FREETYPE_H\nclass FreetypeServerFont;\nstruct FT_GlyphRec_;\n\n\/\/ -----------------------------------------------------------------------\n\n\/\/ FtFontFile has the responsibility that a font file is only mapped once.\n\/\/ (#86621#) the old directly ft-managed solution caused it to be mapped\n\/\/ in up to nTTC*nSizes*nOrientation*nSynthetic times\nclass FtFontFile\n{\npublic:\n static FtFontFile* FindFontFile( const ::rtl::OString& rNativeFileName );\n\n bool Map();\n void Unmap();\n\n const unsigned char* GetBuffer() const { return mpFileMap; }\n int GetFileSize() const { return mnFileSize; }\n const ::rtl::OString* GetFileName() const { return &maNativeFileName; }\n int GetLangBoost() const { return mnLangBoost; }\n\nprivate:\n FtFontFile( const ::rtl::OString& rNativeFileName );\n\n const ::rtl::OString maNativeFileName;\n const unsigned char* mpFileMap;\n int mnFileSize;\n int mnRefCount;\n int mnLangBoost;\n};\n\n\/\/ -----------------------------------------------------------------------\n\n\/\/ FtFontInfo corresponds to an unscaled font face\nclass FtFontInfo\n{\npublic:\n FtFontInfo( const ImplDevFontAttributes&,\n const ::rtl::OString& rNativeFileName,\n int nFaceNum, sal_IntPtr nFontId, int nSynthetic,\n const ExtraKernInfo* );\n ~FtFontInfo();\n\n const unsigned char* GetTable( const char*, ULONG* pLength=0 ) const;\n\n FT_FaceRec_* GetFaceFT();\n void ReleaseFaceFT( FT_FaceRec_* );\n\n const ::rtl::OString* GetFontFileName() const { return mpFontFile->GetFileName(); }\n int GetFaceNum() const { return mnFaceNum; }\n int GetSynthetic() const { return mnSynthetic; }\n sal_IntPtr GetFontId() const { return mnFontId; }\n bool DontUseAntiAlias() const\n { return maDevFontAttributes.UseAntiAlias() == ANTIALIAS_FALSE; }\n bool DontUseEmbeddedBitmaps() const\n { return maDevFontAttributes.UseEmbeddedBitmap() == EMBEDDEDBITMAP_FALSE; }\n bool IsSymbolFont() const { return maDevFontAttributes.IsSymbolFont(); }\n const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; }\n\n void AnnounceFont( ImplDevFontList* );\n\n int GetGlyphIndex( sal_UCS4 cChar ) const;\n void CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const;\n\n bool HasExtraKerning() const;\n int GetExtraKernPairs( ImplKernPairData** ) const;\n int GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;\n\nprivate:\n FT_FaceRec_* maFaceFT;\n FtFontFile* mpFontFile;\n const int mnFaceNum;\n int mnRefCount;\n const int mnSynthetic;\n\n sal_IntPtr mnFontId;\n ImplDevFontAttributes maDevFontAttributes;\n\n \/\/ cache unicode->glyphid mapping because looking it up is expensive\n \/\/ TODO: change to hash_multimap when a use case requires a m:n mapping\n typedef ::std::hash_map<int,int> Int2IntMap;\n mutable Int2IntMap* mpChar2Glyph;\n mutable Int2IntMap* mpGlyph2Char;\n void InitHashes() const;\n\n const ExtraKernInfo* mpExtraKernInfo;\n};\n\n\/\/ these two inlines are very important for performance\n\ninline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const\n{\n if( !mpChar2Glyph )\n return -1;\n Int2IntMap::const_iterator it = mpChar2Glyph->find( cChar );\n if( it == mpChar2Glyph->end() )\n return -1;\n return it->second;\n}\n\ninline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const\n{\n if( !mpChar2Glyph )\n InitHashes();\n (*mpChar2Glyph)[ cChar ] = nIndex;\n (*mpGlyph2Char)[ nIndex ] = cChar;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nclass FreetypeManager\n{\npublic:\n FreetypeManager();\n ~FreetypeManager();\n\n long AddFontDir( const String& rUrlName );\n void AddFontFile( const rtl::OString& rNormalizedName,\n int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&,\n const ExtraKernInfo* );\n void AnnounceFonts( ImplDevFontList* ) const;\n void ClearFontList();\n\n FreetypeServerFont* CreateFont( const ImplFontSelectData& );\n\nprivate:\n typedef ::std::hash_map<sal_IntPtr,FtFontInfo*> FontList;\n FontList maFontList;\n\n sal_IntPtr mnMaxFontId;\n sal_IntPtr mnNextFontId;\n};\n\n\/\/ -----------------------------------------------------------------------\n\nclass FreetypeServerFont : public ServerFont\n{\npublic:\n FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* );\n virtual ~FreetypeServerFont();\n\n virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); }\n virtual int GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); }\n virtual bool TestFont() const;\n\n virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;\n\n virtual int GetGlyphIndex( sal_UCS4 ) const;\n int GetRawGlyphIndex( sal_UCS4 ) const;\n int FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const;\n\n virtual bool GetAntialiasAdvice( void ) const;\n virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;\n virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;\n virtual bool GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const;\n virtual int GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;\n virtual ULONG GetKernPairs( ImplKernPairData** ) const;\n\n const unsigned char* GetTable( const char* pName, ULONG* pLength )\n { return mpFontInfo->GetTable( pName, pLength ); }\n int GetEmUnits() const;\n const FT_Size_Metrics& GetMetricsFT() const { return maSizeFT->metrics; }\n\nprotected:\n friend class GlyphCache;\n\n int ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const;\n virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const;\n virtual ULONG GetFontCodeRanges( sal_uInt32* pCodes ) const;\n bool ApplyGSUB( const ImplFontSelectData& );\n virtual ServerFontLayoutEngine* GetLayoutEngine();\n\nprivate:\n int mnWidth;\n int mnPrioEmbedded;\n int mnPrioAntiAlias;\n FtFontInfo* mpFontInfo;\n FT_Int mnLoadFlags;\n double mfStretch;\n FT_FaceRec_* maFaceFT;\n FT_SizeRec_* maSizeFT;\n\n bool mbFaceOk;\n bool mbArtItalic;\n bool mbArtBold;\n bool mbUseGamma;\n\n typedef ::std::hash_map<int,int> GlyphSubstitution;\n GlyphSubstitution maGlyphSubstitution;\n rtl_UnicodeToTextConverter maRecodeConverter;\n\n ServerFontLayoutEngine* mpLayoutEngine;\n};\n\n\/\/ -----------------------------------------------------------------------\n\nclass ImplFTSFontData : public ImplFontData\n{\nprivate:\n FtFontInfo* mpFtFontInfo;\n enum { IFTSFONT_MAGIC = 0x1F150A1C };\n\npublic:\n ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& );\n\n FtFontInfo* GetFtFontInfo() const { return mpFtFontInfo; }\n\n virtual ImplFontEntry* CreateFontInstance( ImplFontSelectData& ) const;\n virtual ImplFontData* Clone() const { return new ImplFTSFontData( *this ); }\n virtual sal_IntPtr GetFontId() const { return mpFtFontInfo->GetFontId(); }\n\n static bool CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); }\n};\n\n\/\/ -----------------------------------------------------------------------\n\n#endif \/\/ _SV_GCACHFTYP_HXX\n<commit_msg>INTEGRATION: CWS cairotext01_DEV300 (1.39.180); FILE MERGED 2008\/02\/05 16:22:27 cmc 1.39.180.2: #i85470# need to have a consistent size set 2008\/01\/25 08:53:46 cmc 1.39.180.1: #i85470# render text with cairo when available<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: gcach_ftyp.hxx,v $\n *\n * $Revision: 1.40 $\n *\n * last change: $Author: obo $ $Date: 2008-03-26 08:26:40 $\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 _SV_GCACHFTYP_HXX\n#define _SV_GCACHFTYP_HXX\n\n#include <vcl\/glyphcache.hxx>\n#include <rtl\/textcvt.h>\n\n#include <ft2build.h>\n#include FT_FREETYPE_H\nclass FreetypeServerFont;\nstruct FT_GlyphRec_;\n\n\/\/ -----------------------------------------------------------------------\n\n\/\/ FtFontFile has the responsibility that a font file is only mapped once.\n\/\/ (#86621#) the old directly ft-managed solution caused it to be mapped\n\/\/ in up to nTTC*nSizes*nOrientation*nSynthetic times\nclass FtFontFile\n{\npublic:\n static FtFontFile* FindFontFile( const ::rtl::OString& rNativeFileName );\n\n bool Map();\n void Unmap();\n\n const unsigned char* GetBuffer() const { return mpFileMap; }\n int GetFileSize() const { return mnFileSize; }\n const ::rtl::OString* GetFileName() const { return &maNativeFileName; }\n int GetLangBoost() const { return mnLangBoost; }\n\nprivate:\n FtFontFile( const ::rtl::OString& rNativeFileName );\n\n const ::rtl::OString maNativeFileName;\n const unsigned char* mpFileMap;\n int mnFileSize;\n int mnRefCount;\n int mnLangBoost;\n};\n\n\/\/ -----------------------------------------------------------------------\n\n\/\/ FtFontInfo corresponds to an unscaled font face\nclass FtFontInfo\n{\npublic:\n FtFontInfo( const ImplDevFontAttributes&,\n const ::rtl::OString& rNativeFileName,\n int nFaceNum, sal_IntPtr nFontId, int nSynthetic,\n const ExtraKernInfo* );\n ~FtFontInfo();\n\n const unsigned char* GetTable( const char*, ULONG* pLength=0 ) const;\n\n FT_FaceRec_* GetFaceFT();\n void ReleaseFaceFT( FT_FaceRec_* );\n\n const ::rtl::OString* GetFontFileName() const { return mpFontFile->GetFileName(); }\n int GetFaceNum() const { return mnFaceNum; }\n int GetSynthetic() const { return mnSynthetic; }\n sal_IntPtr GetFontId() const { return mnFontId; }\n bool DontUseAntiAlias() const\n { return maDevFontAttributes.UseAntiAlias() == ANTIALIAS_FALSE; }\n bool DontUseEmbeddedBitmaps() const\n { return maDevFontAttributes.UseEmbeddedBitmap() == EMBEDDEDBITMAP_FALSE; }\n bool IsSymbolFont() const { return maDevFontAttributes.IsSymbolFont(); }\n const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; }\n\n void AnnounceFont( ImplDevFontList* );\n\n int GetGlyphIndex( sal_UCS4 cChar ) const;\n void CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const;\n\n bool HasExtraKerning() const;\n int GetExtraKernPairs( ImplKernPairData** ) const;\n int GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;\n\nprivate:\n FT_FaceRec_* maFaceFT;\n FtFontFile* mpFontFile;\n const int mnFaceNum;\n int mnRefCount;\n const int mnSynthetic;\n\n sal_IntPtr mnFontId;\n ImplDevFontAttributes maDevFontAttributes;\n\n \/\/ cache unicode->glyphid mapping because looking it up is expensive\n \/\/ TODO: change to hash_multimap when a use case requires a m:n mapping\n typedef ::std::hash_map<int,int> Int2IntMap;\n mutable Int2IntMap* mpChar2Glyph;\n mutable Int2IntMap* mpGlyph2Char;\n void InitHashes() const;\n\n const ExtraKernInfo* mpExtraKernInfo;\n};\n\n\/\/ these two inlines are very important for performance\n\ninline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const\n{\n if( !mpChar2Glyph )\n return -1;\n Int2IntMap::const_iterator it = mpChar2Glyph->find( cChar );\n if( it == mpChar2Glyph->end() )\n return -1;\n return it->second;\n}\n\ninline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const\n{\n if( !mpChar2Glyph )\n InitHashes();\n (*mpChar2Glyph)[ cChar ] = nIndex;\n (*mpGlyph2Char)[ nIndex ] = cChar;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nclass FreetypeManager\n{\npublic:\n FreetypeManager();\n ~FreetypeManager();\n\n long AddFontDir( const String& rUrlName );\n void AddFontFile( const rtl::OString& rNormalizedName,\n int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&,\n const ExtraKernInfo* );\n void AnnounceFonts( ImplDevFontList* ) const;\n void ClearFontList();\n\n FreetypeServerFont* CreateFont( const ImplFontSelectData& );\n\nprivate:\n typedef ::std::hash_map<sal_IntPtr,FtFontInfo*> FontList;\n FontList maFontList;\n\n sal_IntPtr mnMaxFontId;\n sal_IntPtr mnNextFontId;\n};\n\n\/\/ -----------------------------------------------------------------------\n\nclass FreetypeServerFont : public ServerFont\n{\npublic:\n FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* );\n virtual ~FreetypeServerFont();\n\n virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); }\n virtual int GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); }\n virtual bool TestFont() const;\n virtual void* GetFtFace() const;\n virtual int GetLoadFlags() const { return mnLoadFlags; }\n virtual bool NeedsArtificialBold() const { return mbArtBold; }\n virtual bool NeedsArtificialItalic() const { return mbArtItalic; }\n\n virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;\n\n virtual int GetGlyphIndex( sal_UCS4 ) const;\n int GetRawGlyphIndex( sal_UCS4 ) const;\n int FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const;\n\n virtual bool GetAntialiasAdvice( void ) const;\n virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;\n virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;\n virtual bool GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const;\n virtual int GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;\n virtual ULONG GetKernPairs( ImplKernPairData** ) const;\n\n const unsigned char* GetTable( const char* pName, ULONG* pLength )\n { return mpFontInfo->GetTable( pName, pLength ); }\n int GetEmUnits() const;\n const FT_Size_Metrics& GetMetricsFT() const { return maSizeFT->metrics; }\n\nprotected:\n friend class GlyphCache;\n\n int ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const;\n virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const;\n virtual ULONG GetFontCodeRanges( sal_uInt32* pCodes ) const;\n bool ApplyGSUB( const ImplFontSelectData& );\n virtual ServerFontLayoutEngine* GetLayoutEngine();\n\nprivate:\n int mnWidth;\n int mnPrioEmbedded;\n int mnPrioAntiAlias;\n FtFontInfo* mpFontInfo;\n FT_Int mnLoadFlags;\n double mfStretch;\n FT_FaceRec_* maFaceFT;\n FT_SizeRec_* maSizeFT;\n\n bool mbFaceOk;\n bool mbArtItalic;\n bool mbArtBold;\n bool mbUseGamma;\n\n typedef ::std::hash_map<int,int> GlyphSubstitution;\n GlyphSubstitution maGlyphSubstitution;\n rtl_UnicodeToTextConverter maRecodeConverter;\n\n ServerFontLayoutEngine* mpLayoutEngine;\n};\n\n\/\/ -----------------------------------------------------------------------\n\nclass ImplFTSFontData : public ImplFontData\n{\nprivate:\n FtFontInfo* mpFtFontInfo;\n enum { IFTSFONT_MAGIC = 0x1F150A1C };\n\npublic:\n ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& );\n\n FtFontInfo* GetFtFontInfo() const { return mpFtFontInfo; }\n\n virtual ImplFontEntry* CreateFontInstance( ImplFontSelectData& ) const;\n virtual ImplFontData* Clone() const { return new ImplFTSFontData( *this ); }\n virtual sal_IntPtr GetFontId() const { return mpFtFontInfo->GetFontId(); }\n\n static bool CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); }\n};\n\n\/\/ -----------------------------------------------------------------------\n\n#endif \/\/ _SV_GCACHFTYP_HXX\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\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 \"open_spiel\/algorithms\/evaluate_bots.h\"\n\n#include \"open_spiel\/spiel_bots.h\"\n\nnamespace open_spiel {\nnamespace {\n\nvoid BotTest_RandomVsRandom() {\n auto game = LoadGame(\"kuhn_poker\");\n auto bot0 = MakeUniformRandomBot(*game, Player{0}, \/*seed=*\/1234);\n auto bot1 = MakeUniformRandomBot(*game, Player{1}, \/*seed=*\/4321);\n constexpr int num_players = 2;\n std::vector<double> average_results(num_players);\n constexpr int num_iters = 100000;\n for (int iteration = 0; iteration < num_iters; ++iteration) {\n auto this_results =\n EvaluateBots(game->NewInitialState().get(), {bot0.get(), bot1.get()},\n \/*seed=*\/iteration);\n for (auto p = Player{0}; p < num_players; ++p) {\n average_results[p] += this_results[p];\n }\n }\n for (auto p = Player{0}; p < num_players; ++p) {\n average_results[p] \/= num_iters;\n }\n\n SPIEL_CHECK_FLOAT_NEAR(average_results[0], 0.125, 0.01);\n SPIEL_CHECK_FLOAT_NEAR(average_results[1], -0.125, 0.01);\n} \/\/ namespace\n\n} \/\/ namespace\n} \/\/ namespace open_spiel\n\nint main(int argc, char** argv) { open_spiel::BotTest_RandomVsRandom(); }\n<commit_msg>Remove a stray comment.<commit_after>\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\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 \"open_spiel\/algorithms\/evaluate_bots.h\"\n\n#include \"open_spiel\/spiel_bots.h\"\n\nnamespace open_spiel {\nnamespace {\n\nvoid BotTest_RandomVsRandom() {\n auto game = LoadGame(\"kuhn_poker\");\n auto bot0 = MakeUniformRandomBot(*game, Player{0}, \/*seed=*\/1234);\n auto bot1 = MakeUniformRandomBot(*game, Player{1}, \/*seed=*\/4321);\n constexpr int num_players = 2;\n std::vector<double> average_results(num_players);\n constexpr int num_iters = 100000;\n for (int iteration = 0; iteration < num_iters; ++iteration) {\n auto this_results =\n EvaluateBots(game->NewInitialState().get(), {bot0.get(), bot1.get()},\n \/*seed=*\/iteration);\n for (auto p = Player{0}; p < num_players; ++p) {\n average_results[p] += this_results[p];\n }\n }\n for (auto p = Player{0}; p < num_players; ++p) {\n average_results[p] \/= num_iters;\n }\n\n SPIEL_CHECK_FLOAT_NEAR(average_results[0], 0.125, 0.01);\n SPIEL_CHECK_FLOAT_NEAR(average_results[1], -0.125, 0.01);\n}\n\n} \/\/ namespace\n} \/\/ namespace open_spiel\n\nint main(int argc, char** argv) { open_spiel::BotTest_RandomVsRandom(); }\n<|endoftext|>"} {"text":"<commit_before>\/** iostream_combo.cc --- \n *\n * Copyright (C) 2012 Nil Geisweiller\n *\n * Authors: Nil Geisweiller <ngeiswei@gmail.com>\n * Matt Chapman <Matt@NinjitsuWeb.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"iostream_combo.h\"\n#include \"procedure_call.h\"\n#include <boost\/range\/algorithm\/find.hpp>\n\nnamespace opencog { namespace combo {\n\nusing namespace std;\nusing namespace boost;\n\n\/\/ uncomment this to output a negative literal !$n instead of not($n)\n#define ABBREVIATE_NEGATIVE_LITERAL\n\nostream& ostream_builtin(ostream& out, const builtin& h, format f)\n{\n switch(f) {\n case fmt::python:\n switch (h) {\n case id::null_vertex:\n return out << \"null_vertex\";\n case id::logical_and:\n return out << \"ands\";\n case id::logical_or:\n return out << \"ors\";\n case id::logical_not:\n return out << \"not\";\n case id::logical_true:\n return out << \"True\";\n case id::logical_false:\n return out << \"False\";\n default:\n return out << \"Builtin: \" << h << \" unknown\";\n }\n case fmt::combo:\n switch (h) {\n case id::null_vertex:\n return out << \"null_vertex\";\n case id::logical_and:\n return out << \"and\";\n case id::logical_or:\n return out << \"or\";\n case id::logical_not:\n return out << \"not\";\n case id::logical_true:\n return out << \"true\";\n case id::logical_false:\n return out << \"false\";\n case id::contin_if:\n return out << \"contin_if\";\n case id::boolean_if:\n return out << \"boolean_if\";\n case id::plus:\n return out << \"+\";\n case id::times:\n return out << \"*\";\n case id::div:\n return out << \"\/\";\n case id::log:\n return out << \"log\";\n case id::exp:\n return out << \"exp\";\n case id::sin:\n return out << \"sin\";\n case id::greater_than_zero:\n return out << \"0<\";\n case id::impulse:\n return out << \"impulse\";\n case id::rand:\n return out << \"rand\";\n default:\n return out << \"Builtin \" << h << \" unknown\";\n }\n default:\n return out << \"Format \" << f << \" unknown\";\n }\n}\n\nostream& ostream_argument(ostream& out, const argument& a, format f)\n{\n switch(f) {\n case fmt::python:\n if (a.is_negated()) \n return out << \"not(i[\" << -a.idx - 1 << \"]),\";\n return out << \"i[\" << a.idx - 1 << \"],\";\n case fmt::combo:\n#ifdef ABBREVIATE_NEGATIVE_LITERAL\n return ostream_abbreviate_literal(out, a);\n#else\n if (a.is_negated()) \n return out << \"not($\" << -a.idx << \")\";\n return out << \"$\" << a.idx << vm;\n#endif\n default:\n return out << \"Format \" << f << \"unknown\";\n } \n}\n\nostream& ostream_vertex(ostream& out, const vertex& v, format f)\n{\n if (const ann_type* z = get<ann_type>(&v))\n return out << (*z);\n if (const argument* a = get<argument>(&v))\n return ostream_argument(out, *a, f);\n if (const builtin* h = get<builtin>(&v))\n return ostream_builtin(out, *h, f);\n if (const wild_card* w = get<wild_card>(&v))\n return out << (*w);\n if (const action* act = get<action>(&v))\n return out << (*act);\n if (const builtin_action* aact = get<builtin_action>(&v))\n return out << (*aact);\n if (const perception* per = get<perception>(&v))\n return out << (*per);\n if (const indefinite_object*\n iot = get<indefinite_object>(&v))\n return out << (*iot);\n if (const message* m = get<message>(&v))\n return out << (*m);\n if (const definite_object* dot = get<definite_object>(&v))\n return out << (*dot);\n if (const action_symbol* as = get<action_symbol>(&v))\n return out << (*as);\n if (const procedure_call* cp = get<procedure_call>(&v))\n return out << (*cp);\n\n if (const enum_t* m = get<enum_t>(&v))\n return out << (*m);\n\n if (double x = get<contin_t>(v))\n return out << x;\n\n OC_ASSERT(false, \"Don't know how to print this type\");\n return out;\n}\n\nstd::ostream& ostream_combo_tree(std::ostream& out, const combo_tree ct, format f) {\n for (combo_tree::iterator it=ct.begin(); it!=ct.end(); ++it) {\n ostream_combo_it(out, it, f);\n it.skip_children();\n out << \" \";\n }\n return out;\n}\n \nstring ph2l(const string& ce, const vector<string>& labels)\n{\n \/\/\/ @todo the implementation could be done in 2 lines with\n \/\/\/ boost.regex with boost version 1.42 or above because then we\n \/\/\/ can use Formatter as callback, but we're stuck with boost 1.38\n \/\/\/ :-(\n string res;\n string match;\n bool matching = false;\n foreach(char c, ce) {\n if(!matching) {\n res += c;\n if(c == '$') \/\/ matching starts\n matching = true;\n } else {\n if(c == ' ' || c == ')' || c == '\\n') { \/\/matching ends\n res += labels[lexical_cast<arity_t>(match) - 1] + c;\n match.clear();\n matching = false;\n } else \/\/ matching goes\n match += c;\n }\n }\n \/\/ if a matching is going on flush to the result\n if(matching)\n res += labels[lexical_cast<arity_t>(match) - 1];\n return res;\n}\n\nstring l2ph(const string& ce, const vector<string>& labels)\n{\n \/\/\/ @todo the implementation could be done in 2 lines with\n \/\/\/ boost.regex with boost version 1.42 or above because then we\n \/\/\/ can use Formatter as callback, but we're stuck with boost 1.38\n \/\/\/ :-(\n string res;\n string match;\n bool matching = false;\n foreach(char c, ce) {\n if(!matching) {\n res += c;\n if(c == '$') \/\/ matching starts\n matching = true;\n } else {\n if(c == ' ' || c == ')' || c == '\\n') { \/\/matching ends\n auto found_it = find(labels, match);\n OC_ASSERT(found_it != labels.end(), \"No label %s matching\",\n match.c_str());\n arity_t idx = distance(labels.begin(), found_it) + 1;\n res += lexical_cast<string>(idx) + c;\n match.clear();\n matching = false;\n } else \/\/ matching goes\n match += c;\n }\n }\n \/\/ if a matching is going on flush to the result\n if(matching) {\n auto found_it = boost::find(labels, match);\n OC_ASSERT(found_it != labels.end(), \"No label %s matching\",\n match.c_str());\n arity_t idx = distance(labels.begin(), found_it) + 1;\n res += lexical_cast<string>(idx);\n }\n return res;\n}\n\nostream& operator<<(ostream& out, const ann_type& h)\n{\n switch (h.id) {\n case id::ann:\n return out << \"ann\";\n case id::ann_input:\n return out << \"$I\" << h.idx;\n case id::ann_node:\n return out << \"$N\" << h.idx;\n default:\n return out << \"ANN : UNKNOWN_HANDLE\";\n }\n}\n\nostream& operator<<(ostream& out, const builtin& h)\n{\n return ostream_builtin(out, h, fmt::combo);\n}\n\nostream& operator<<(ostream& out, const wild_card& w)\n{\n switch (w) {\n case id::asterisk:\n return out << \"_*_\";\n default:\n return out << \"WILD_CARD: UNKNOWN_HANDLE\";\n }\n}\n\nostream& ostream_abbreviate_literal(ostream& out, const argument& a) {\n if(a.is_negated()) {\n return out << \"!$\" << -a.idx;\n }\n return out << \"$\" << a.idx;\n}\n\nostream& operator<<(ostream& out, const argument& a)\n{\n return ostream_argument(out, a, fmt::combo);\n}\n\nostream& operator<<(ostream& out, const vertex& v)\n{\n return ostream_vertex(out, v, fmt::combo);\n}\n\n}} \/\/ ~namespaces combo opencog\n<commit_msg>combo: fix infinite recursion when printing vertexes.<commit_after>\/** iostream_combo.cc --- \n *\n * Copyright (C) 2012 Nil Geisweiller\n *\n * Authors: Nil Geisweiller <ngeiswei@gmail.com>\n * Matt Chapman <Matt@NinjitsuWeb.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"iostream_combo.h\"\n#include \"procedure_call.h\"\n#include <boost\/range\/algorithm\/find.hpp>\n\nnamespace opencog { namespace combo {\n\nusing namespace std;\nusing namespace boost;\n\n\/\/ uncomment this to output a negative literal !$n instead of not($n)\n#define ABBREVIATE_NEGATIVE_LITERAL\n\nostream& ostream_builtin(ostream& out, const builtin& h, format f)\n{\n switch(f) {\n case fmt::python:\n switch (h) {\n case id::null_vertex:\n return out << \"null_vertex\";\n case id::logical_and:\n return out << \"ands\";\n case id::logical_or:\n return out << \"ors\";\n case id::logical_not:\n return out << \"not\";\n case id::logical_true:\n return out << \"True\";\n case id::logical_false:\n return out << \"False\";\n default:\n return out << \"Builtin: \" << (unsigned) h << \" unknown\";\n }\n case fmt::combo:\n switch (h) {\n case id::null_vertex:\n return out << \"null_vertex\";\n case id::logical_and:\n return out << \"and\";\n case id::logical_or:\n return out << \"or\";\n case id::logical_not:\n return out << \"not\";\n case id::logical_true:\n return out << \"true\";\n case id::logical_false:\n return out << \"false\";\n case id::plus:\n return out << \"+\";\n case id::times:\n return out << \"*\";\n case id::div:\n return out << \"\/\";\n case id::log:\n return out << \"log\";\n case id::exp:\n return out << \"exp\";\n case id::sin:\n return out << \"sin\";\n case id::greater_than_zero:\n return out << \"0<\";\n case id::impulse:\n return out << \"impulse\";\n case id::rand:\n return out << \"rand\";\n\n case id::contin_if:\n return out << \"contin_if\";\n case id::boolean_if:\n return out << \"boolean_if\";\n case id::cond:\n return out << \"cond\";\n case id::equ:\n return out << \"equ\";\n default:\n return out << \"Builtin \" << (unsigned) h << \" unknown\";\n }\n default:\n return out << \"Format \" << f << \" unknown\";\n }\n}\n\nostream& ostream_argument(ostream& out, const argument& a, format f)\n{\n switch(f) {\n case fmt::python:\n if (a.is_negated()) \n return out << \"not(i[\" << -a.idx - 1 << \"]),\";\n return out << \"i[\" << a.idx - 1 << \"],\";\n case fmt::combo:\n#ifdef ABBREVIATE_NEGATIVE_LITERAL\n return ostream_abbreviate_literal(out, a);\n#else\n if (a.is_negated()) \n return out << \"not($\" << -a.idx << \")\";\n return out << \"$\" << a.idx << vm;\n#endif\n default:\n return out << \"Format \" << f << \"unknown\";\n } \n}\n\nostream& ostream_vertex(ostream& out, const vertex& v, format f)\n{\n \/\/ Handle the most likely types first.\n if (const argument* a = get<argument>(&v))\n return ostream_argument(out, *a, f);\n if (const builtin* h = get<builtin>(&v))\n return ostream_builtin(out, *h, f);\n if (const enum_t* m = get<enum_t>(&v))\n return out << m->getContent();\n\n \/\/ XXX ?? Ahem, won't calling out<<(*m) just lead to infinite\n \/\/ recursion ?? \n if (const ann_type* z = get<ann_type>(&v))\n return out << (*z);\n if (const wild_card* w = get<wild_card>(&v))\n return out << (*w);\n if (const action* act = get<action>(&v))\n return out << (*act);\n if (const builtin_action* aact = get<builtin_action>(&v))\n return out << (*aact);\n if (const perception* per = get<perception>(&v))\n return out << (*per);\n if (const indefinite_object* iot = get<indefinite_object>(&v))\n return out << (*iot);\n if (const message* m = get<message>(&v))\n return out << m->getContent();\n if (const definite_object* dot = get<definite_object>(&v))\n return out << (*dot);\n if (const action_symbol* as = get<action_symbol>(&v))\n return out << (*as);\n if (const procedure_call* cp = get<procedure_call>(&v))\n return out << (*cp);\n\n if (double x = get<contin_t>(v))\n return out << x;\n\n OC_ASSERT(false, \"Don't know how to print this type\");\n return out;\n}\n\nstd::ostream& ostream_combo_tree(std::ostream& out, const combo_tree ct, format f) {\n for (combo_tree::iterator it=ct.begin(); it!=ct.end(); ++it) {\n ostream_combo_it(out, it, f);\n it.skip_children();\n out << \" \";\n }\n return out;\n}\n \nstring ph2l(const string& ce, const vector<string>& labels)\n{\n \/\/\/ @todo the implementation could be done in 2 lines with\n \/\/\/ boost.regex with boost version 1.42 or above because then we\n \/\/\/ can use Formatter as callback, but we're stuck with boost 1.38\n \/\/\/ :-(\n string res;\n string match;\n bool matching = false;\n foreach(char c, ce) {\n if(!matching) {\n res += c;\n if(c == '$') \/\/ matching starts\n matching = true;\n } else {\n if(c == ' ' || c == ')' || c == '\\n') { \/\/matching ends\n res += labels[lexical_cast<arity_t>(match) - 1] + c;\n match.clear();\n matching = false;\n } else \/\/ matching goes\n match += c;\n }\n }\n \/\/ if a matching is going on flush to the result\n if(matching)\n res += labels[lexical_cast<arity_t>(match) - 1];\n return res;\n}\n\nstring l2ph(const string& ce, const vector<string>& labels)\n{\n \/\/\/ @todo the implementation could be done in 2 lines with\n \/\/\/ boost.regex with boost version 1.42 or above because then we\n \/\/\/ can use Formatter as callback, but we're stuck with boost 1.38\n \/\/\/ :-(\n string res;\n string match;\n bool matching = false;\n foreach(char c, ce) {\n if(!matching) {\n res += c;\n if(c == '$') \/\/ matching starts\n matching = true;\n } else {\n if(c == ' ' || c == ')' || c == '\\n') { \/\/matching ends\n auto found_it = find(labels, match);\n OC_ASSERT(found_it != labels.end(), \"No label %s matching\",\n match.c_str());\n arity_t idx = distance(labels.begin(), found_it) + 1;\n res += lexical_cast<string>(idx) + c;\n match.clear();\n matching = false;\n } else \/\/ matching goes\n match += c;\n }\n }\n \/\/ if a matching is going on flush to the result\n if(matching) {\n auto found_it = boost::find(labels, match);\n OC_ASSERT(found_it != labels.end(), \"No label %s matching\",\n match.c_str());\n arity_t idx = distance(labels.begin(), found_it) + 1;\n res += lexical_cast<string>(idx);\n }\n return res;\n}\n\nostream& operator<<(ostream& out, const ann_type& h)\n{\n switch (h.id) {\n case id::ann:\n return out << \"ann\";\n case id::ann_input:\n return out << \"$I\" << h.idx;\n case id::ann_node:\n return out << \"$N\" << h.idx;\n default:\n return out << \"ANN : UNKNOWN_HANDLE\";\n }\n}\n\nostream& operator<<(ostream& out, const builtin& h)\n{\n return ostream_builtin(out, h, fmt::combo);\n}\n\nostream& operator<<(ostream& out, const wild_card& w)\n{\n switch (w) {\n case id::asterisk:\n return out << \"_*_\";\n default:\n return out << \"WILD_CARD: UNKNOWN_HANDLE\";\n }\n}\n\nostream& ostream_abbreviate_literal(ostream& out, const argument& a) {\n if(a.is_negated()) {\n return out << \"!$\" << -a.idx;\n }\n return out << \"$\" << a.idx;\n}\n\nostream& operator<<(ostream& out, const argument& a)\n{\n return ostream_argument(out, a, fmt::combo);\n}\n\nostream& operator<<(ostream& out, const vertex& v)\n{\n return ostream_vertex(out, v, fmt::combo);\n}\n\n}} \/\/ ~namespaces combo opencog\n<|endoftext|>"} {"text":"<commit_before>#include \"file_system.hpp\"\n#include <windows.h>\n\nnamespace msrv {\n\nnamespace {\n\ninline int64_t makeInt64(DWORD high, DWORD low)\n{\n return (static_cast<int64_t>(high) << 32) | static_cast<int64_t>(low);\n}\n\ninline FileType getFileType(DWORD attributes)\n{\n return attributes & FILE_ATTRIBUTE_DIRECTORY\n ? FileType::DIRECTORY\n : FileType::REGULAR;\n}\n\ninline int64_t getUnixTimestamp(FILETIME time)\n{\n return makeInt64(time.dwHighDateTime, time.dwLowDateTime) \/ INT64_C(10000000) - INT64_C(11644473600);\n}\n\n}\n\nPath getModulePath(void* symbol)\n{\n ::HMODULE module;\n\n auto ret = ::GetModuleHandleExW(\n GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,\n reinterpret_cast<wchar_t*>(symbol),\n &module);\n\n throwIfFailed(\"GetModuleHandleExW\", ret != 0);\n\n Path::string_type path;\n path.resize(1024);\n auto size = ::GetModuleFileNameW(module, &path[0], path.length());\n throwIfFailed(\"GetModuleFileNameW\", size > 0 && size < path.length());\n\n path.resize(static_cast<size_t>(size));\n return Path(std::move(path));\n}\n\nFileHandle openFile(const Path&)\n{\n return FileHandle();\n}\n\nFileInfo queryFileInfo(FileHandle::Type handle)\n{\n ::BY_HANDLE_FILE_INFORMATION data;\n auto ret = ::GetFileInformationByHandle(handle, &data);\n throwIfFailed(\"GetFileInformationByHandle\", ret != 0);\n\n FileInfo info;\n info.inode = -1;\n info.size = makeInt64(data.nFileSizeHigh, data.nFileIndexLow);\n info.type = getFileType(data.dwFileAttributes);\n info.timestamp = getUnixTimestamp(data.ftLastWriteTime);\n return info;\n}\n\nFileInfo queryFileInfo(const Path& path)\n{\n ::WIN32_FILE_ATTRIBUTE_DATA data;\n auto ret = ::GetFileAttributesExW(path.native().c_str(), GetFileExInfoStandard, &data);\n throwIfFailed(\"GetFileAttributesExW\", ret != 0);\n\n FileInfo info;\n info.inode = -1;\n info.size = makeInt64(data.nFileSizeHigh, data.nFileSizeLow);\n info.type = getFileType(data.dwFileAttributes);\n info.timestamp = getUnixTimestamp(data.ftLastWriteTime);\n return info;\n}\n\nsize_t readFile(FileHandle::Type handle, void* buffer, size_t bytes)\n{\n DWORD bytesRead;\n auto ret = ::ReadFile(handle, buffer, static_cast<DWORD>(bytes), &bytesRead, nullptr);\n throwIfFailed(\"ReadFile\", ret != 0);\n return bytesRead;\n}\n\n\n}\n<commit_msg>implement openFile<commit_after>#include \"file_system.hpp\"\n#include <windows.h>\n\nnamespace msrv {\n\nnamespace {\n\ninline int64_t makeInt64(DWORD high, DWORD low)\n{\n return (static_cast<int64_t>(high) << 32) | static_cast<int64_t>(low);\n}\n\ninline FileType getFileType(DWORD attributes)\n{\n return attributes & FILE_ATTRIBUTE_DIRECTORY\n ? FileType::DIRECTORY\n : FileType::REGULAR;\n}\n\ninline int64_t getUnixTimestamp(FILETIME time)\n{\n return makeInt64(time.dwHighDateTime, time.dwLowDateTime) \/ INT64_C(10000000) - INT64_C(11644473600);\n}\n\n}\n\nPath getModulePath(void* symbol)\n{\n ::HMODULE module;\n\n auto ret = ::GetModuleHandleExW(\n GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,\n reinterpret_cast<wchar_t*>(symbol),\n &module);\n\n throwIfFailed(\"GetModuleHandleExW\", ret != 0);\n\n Path::string_type path;\n path.resize(1024);\n auto size = ::GetModuleFileNameW(module, &path[0], path.length());\n throwIfFailed(\"GetModuleFileNameW\", size > 0 && size < path.length());\n\n path.resize(static_cast<size_t>(size));\n return Path(std::move(path));\n}\n\nFileHandle openFile(const Path& path)\n{\n return FileHandle(::CreateFileW(\n path.c_str(),\n GENERIC_READ,\n FILE_SHARE_READ,\n nullptr,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n nullptr));\n}\n\nFileInfo queryFileInfo(FileHandle::Type handle)\n{\n ::BY_HANDLE_FILE_INFORMATION data;\n auto ret = ::GetFileInformationByHandle(handle, &data);\n throwIfFailed(\"GetFileInformationByHandle\", ret != 0);\n\n FileInfo info;\n info.inode = -1;\n info.size = makeInt64(data.nFileSizeHigh, data.nFileIndexLow);\n info.type = getFileType(data.dwFileAttributes);\n info.timestamp = getUnixTimestamp(data.ftLastWriteTime);\n return info;\n}\n\nFileInfo queryFileInfo(const Path& path)\n{\n ::WIN32_FILE_ATTRIBUTE_DATA data;\n auto ret = ::GetFileAttributesExW(path.native().c_str(), GetFileExInfoStandard, &data);\n throwIfFailed(\"GetFileAttributesExW\", ret != 0);\n\n FileInfo info;\n info.inode = -1;\n info.size = makeInt64(data.nFileSizeHigh, data.nFileSizeLow);\n info.type = getFileType(data.dwFileAttributes);\n info.timestamp = getUnixTimestamp(data.ftLastWriteTime);\n return info;\n}\n\nsize_t readFile(FileHandle::Type handle, void* buffer, size_t bytes)\n{\n DWORD bytesRead;\n auto ret = ::ReadFile(handle, buffer, static_cast<DWORD>(bytes), &bytesRead, nullptr);\n throwIfFailed(\"ReadFile\", ret != 0);\n return bytesRead;\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"bufferAgent.h\"\n\nusing boost::shared_ptr;\nusing boost::thread;\nusing boost::bind;\n\nusing std::string;\n\nnamespace veil {\nnamespace helpers {\n\nBufferAgent::BufferAgent(write_fun w, read_fun r)\n : m_agentActive(false),\n doWrite(w),\n doRead(r)\n{\n agentStart();\n}\nBufferAgent::~BufferAgent()\n{\n agentStop();\n}\n\nint BufferAgent::onOpen(std::string path, ffi_type ffi)\n{\n unique_lock guard(m_loopMutex);\n m_cacheMap.erase(ffi->fh);\n\n buffer_ptr lCache(new LockableCache());\n lCache->fileName = path;\n lCache->buffer = newFileCache();\n lCache->ffi = *ffi;\n\n m_cacheMap[ffi->fh] = lCache;\n\n return 0;\n}\n\nint BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi)\n{\n unique_lock guard(m_loopMutex);\n buffer_ptr wrapper = m_cacheMap[ffi->fh];\n guard.unlock();\n\n unique_lock buff_guard(wrapper->mutex);\n\n while(wrapper->buffer->byteSize() > 1024 * 1024 * 10) {\n guard.lock();\n m_jobQueue.push_front(ffi->fh);\n m_loopCond.notify_all();\n guard.unlock();\n wrapper->cond.wait(buff_guard);\n }\n\n wrapper->buffer->writeData(offset, buf);\n\n guard.lock();\n m_jobQueue.push_back(ffi->fh);\n m_loopCond.notify_all();\n\n return size;\n}\n\nint BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi)\n{\n boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex);\n return EOPNOTSUPP;\n}\n\nint BufferAgent::onFlush(std::string path, ffi_type ffi)\n{\n unique_lock guard(m_loopMutex);\n buffer_ptr wrapper = m_cacheMap[ffi->fh];\n guard.unlock();\n\n unique_lock buff_guard(wrapper->mutex);\n\n while(wrapper->buffer->blockCount() > 0) \n {\n block_ptr block = wrapper->buffer->removeOldestBlock();\n int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);\n if(res < 0)\n {\n while(wrapper->buffer->blockCount() > 0)\n {\n (void) wrapper->buffer->removeOldestBlock();\n }\n return res;\n }\n }\n\n guard.lock();\n m_jobQueue.remove(ffi->fh);\n\n return 0;\n}\n\nint BufferAgent::onRelease(std::string path, ffi_type ffi)\n{\n boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex);\n m_cacheMap.erase(ffi->fh);\n\n return 0;\n}\n\n\n\nvoid BufferAgent::agentStart(int worker_count)\n{\n m_workers.clear();\n m_agentActive = true;\n\n while(worker_count--)\n {\n m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::workerLoop, this))));\n }\n}\n\nvoid BufferAgent::agentStop()\n{\n m_agentActive = false;\n m_loopCond.notify_all();\n while(m_workers.size() > 0)\n {\n m_workers.back()->join();\n m_workers.pop_back();\n }\n}\n\nvoid BufferAgent::workerLoop()\n{\n unique_lock guard(m_loopMutex);\n while(m_agentActive)\n {\n while(m_jobQueue.empty() && m_agentActive)\n m_loopCond.wait(guard);\n\n if(!m_agentActive)\n return;\n\n fd_type file = m_jobQueue.front();\n buffer_ptr wrapper = m_cacheMap[file];\n m_jobQueue.pop_front();\n m_loopCond.notify_all();\n\n if(!wrapper)\n continue;\n\n \n {\n guard.unlock();\n block_ptr block;\n {\n unique_lock buff_guard(wrapper->mutex);\n block = wrapper->buffer->removeOldestBlock();\n } \n\n if(block) \n {\n int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);\n \n wrapper->cond.notify_all();\n }\n\n guard.lock();\n if(wrapper->buffer->blockCount() > 0)\n {\n m_jobQueue.push_back(file);\n }\n\n\n }\n \n\n }\n}\n\nboost::shared_ptr<FileCache> BufferAgent::newFileCache()\n{\n return boost::shared_ptr<FileCache>(new FileCache(500 * 1024));\n}\n\n} \/\/ namespace helpers \n} \/\/ namespace veil\n\n<commit_msg>VFS-292: debug<commit_after>#include \"bufferAgent.h\"\n\nusing boost::shared_ptr;\nusing boost::thread;\nusing boost::bind;\n\nusing std::string;\n\nnamespace veil {\nnamespace helpers {\n\nBufferAgent::BufferAgent(write_fun w, read_fun r)\n : m_agentActive(false),\n doWrite(w),\n doRead(r)\n{\n agentStart();\n}\nBufferAgent::~BufferAgent()\n{\n agentStop();\n}\n\nint BufferAgent::onOpen(std::string path, ffi_type ffi)\n{\n unique_lock guard(m_loopMutex);\n m_cacheMap.erase(ffi->fh);\n\n buffer_ptr lCache(new LockableCache());\n lCache->fileName = path;\n lCache->buffer = newFileCache();\n lCache->ffi = *ffi;\n\n m_cacheMap[ffi->fh] = lCache;\n\n return 0;\n}\n\nint BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi)\n{\n unique_lock guard(m_loopMutex);\n buffer_ptr wrapper = m_cacheMap[ffi->fh];\n guard.unlock();\n\n unique_lock buff_guard(wrapper->mutex);\n\n while(wrapper->buffer->byteSize() > 1024 * 1024 * 64) {\n guard.lock();\n m_jobQueue.push_front(ffi->fh);\n m_loopCond.notify_all();\n guard.unlock();\n wrapper->cond.wait(buff_guard);\n }\n\n wrapper->buffer->writeData(offset, buf);\n\n guard.lock();\n m_jobQueue.push_back(ffi->fh);\n m_loopCond.notify_all();\n\n return size;\n}\n\nint BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi)\n{\n boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex);\n return EOPNOTSUPP;\n}\n\nint BufferAgent::onFlush(std::string path, ffi_type ffi)\n{\n unique_lock guard(m_loopMutex);\n buffer_ptr wrapper = m_cacheMap[ffi->fh];\n guard.unlock();\n\n unique_lock buff_guard(wrapper->mutex);\n\n while(wrapper->buffer->blockCount() > 0) \n {\n block_ptr block = wrapper->buffer->removeOldestBlock();\n int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);\n if(res < 0)\n {\n while(wrapper->buffer->blockCount() > 0)\n {\n (void) wrapper->buffer->removeOldestBlock();\n }\n return res;\n }\n }\n\n guard.lock();\n m_jobQueue.remove(ffi->fh);\n\n return 0;\n}\n\nint BufferAgent::onRelease(std::string path, ffi_type ffi)\n{\n boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex);\n m_cacheMap.erase(ffi->fh);\n\n return 0;\n}\n\n\n\nvoid BufferAgent::agentStart(int worker_count)\n{\n m_workers.clear();\n m_agentActive = true;\n\n while(worker_count--)\n {\n m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::workerLoop, this))));\n }\n}\n\nvoid BufferAgent::agentStop()\n{\n m_agentActive = false;\n m_loopCond.notify_all();\n while(m_workers.size() > 0)\n {\n m_workers.back()->join();\n m_workers.pop_back();\n }\n}\n\nvoid BufferAgent::workerLoop()\n{\n unique_lock guard(m_loopMutex);\n while(m_agentActive)\n {\n while(m_jobQueue.empty() && m_agentActive)\n m_loopCond.wait(guard);\n\n if(!m_agentActive)\n return;\n\n fd_type file = m_jobQueue.front();\n buffer_ptr wrapper = m_cacheMap[file];\n m_jobQueue.pop_front();\n m_loopCond.notify_all();\n\n if(!wrapper)\n continue;\n\n \n {\n guard.unlock();\n block_ptr block;\n {\n unique_lock buff_guard(wrapper->mutex);\n block = wrapper->buffer->removeOldestBlock();\n } \n\n if(block) \n {\n int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);\n \n wrapper->cond.notify_all();\n }\n\n guard.lock();\n if(wrapper->buffer->blockCount() > 0)\n {\n m_jobQueue.push_back(file);\n }\n\n\n }\n \n\n }\n}\n\nboost::shared_ptr<FileCache> BufferAgent::newFileCache()\n{\n return boost::shared_ptr<FileCache>(new FileCache(1024 * 1024));\n}\n\n} \/\/ namespace helpers \n} \/\/ namespace veil\n\n<|endoftext|>"} {"text":"<commit_before>#include \"bufferAgent.h\"\n#include \"helpers\/storageHelperFactory.h\"\n#include \"glog\/logging.h\"\n\nusing boost::shared_ptr;\nusing boost::thread;\nusing boost::bind;\n\nusing std::string;\n\nnamespace veil {\nnamespace helpers {\n\nboost::recursive_mutex BufferAgent::m_bufferSizeMutex;\nvolatile size_t BufferAgent::m_rdBufferTotalSize;\nvolatile size_t BufferAgent::m_wrBufferTotalSize;\nrdbuf_size_mem_t BufferAgent::m_rdBufferSizeMem;\nwrbuf_size_mem_t BufferAgent::m_wrBufferSizeMem;\n\nBufferAgent::BufferAgent(write_fun w, read_fun r)\n : m_agentActive(false),\n doWrite(w),\n doRead(r)\n{\n agentStart(1);\n}\n\nBufferAgent::~BufferAgent()\n{\n agentStop();\n}\n\nvoid BufferAgent::updateWrBufferSize(fd_type key, size_t size)\n{\n unique_lock guard(m_bufferSizeMutex);\n wrbuf_size_mem_t::iterator it = m_wrBufferSizeMem.find(key);\n\n \/\/ If entry for this key doesn't exist, just create one\n if(it == m_wrBufferSizeMem.end()) {\n m_wrBufferSizeMem[key] = size;\n m_rdBufferTotalSize += size;\n } else {\n \/\/ If key exists, update total bytes size according to diff between last size and current \n if(size < it->second && (it->second - size) >= m_wrBufferTotalSize) {\n m_wrBufferTotalSize = 0;\n } else {\n m_wrBufferTotalSize += (size - it->second);\n }\n\n if(size == 0) {\n m_wrBufferSizeMem.erase(key);\n } else {\n m_wrBufferSizeMem[key] = size;\n }\n }\n}\n\nvoid BufferAgent::updateRdBufferSize(std::string key, size_t size) \n{\n unique_lock guard(m_bufferSizeMutex);\n rdbuf_size_mem_t::iterator it = m_rdBufferSizeMem.find(key);\n\n if(it == m_rdBufferSizeMem.end()) {\n m_rdBufferSizeMem[key] = size;\n m_rdBufferTotalSize += size;\n \/\/ If key exists, update total bytes size according to diff between last size and current \n } else {\n if(size < it->second && (it->second - size) >= m_rdBufferTotalSize) {\n m_rdBufferTotalSize = 0;\n } else {\n m_rdBufferTotalSize += (size - it->second);\n }\n\n if(size == 0) {\n m_rdBufferSizeMem.erase(key);\n } else {\n m_rdBufferSizeMem[key] = size;\n }\n }\n}\n\nsize_t BufferAgent::getWriteBufferSize()\n{\n unique_lock guard(m_bufferSizeMutex);\n return m_wrBufferTotalSize;\n}\n\nsize_t BufferAgent::getReadBufferSize()\n{\n unique_lock guard(m_bufferSizeMutex);\n return m_rdBufferTotalSize;\n} \n\nint BufferAgent::onOpen(std::string path, ffi_type ffi)\n{\n DLOG(INFO) << \"BufferAgent::onOpen(\" << path << \")\";\n \/\/ Initialize write buffer's holder\n {\n unique_lock guard(m_wrMutex);\n m_wrCacheMap.erase(ffi->fh);\n\n write_buffer_ptr lCache(new WriteCache());\n lCache->fileName = path;\n lCache->buffer = newFileCache(true);\n lCache->ffi = *ffi;\n\n m_wrCacheMap[ffi->fh] = lCache;\n }\n\n { \/\/ Initialize read buffer's holder\n unique_lock guard(m_rdMutex);\n read_cache_map_t::iterator it;\n if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) {\n it->second->openCount++;\n } else {\n read_buffer_ptr lCache(new ReadCache());\n lCache->fileName = path;\n lCache->openCount = 1;\n lCache->ffi = *ffi;\n lCache->buffer = newFileCache(false);\n\n m_rdCacheMap[path] = lCache;\n }\n\n \/\/ Prefetch first 512B block\n m_rdJobQueue.insert(PrefetchJob(path, 0, 512, ffi->fh));\n m_rdCond.notify_one();\n }\n\n return 0;\n}\n\nint BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi)\n{\n DLOG(INFO) << \"BufferAgent::onWrite(path: \" << path << \", size: \" << size << \", offset: \" << offset <<\")\";\n unique_lock guard(m_wrMutex);\n write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh];\n\n \/\/ If there was an error while sending cached data, return this error \n if(wrapper->lastError < 0) {\n wrapper->lastError = 0;\n return wrapper->lastError;\n }\n\n guard.unlock();\n\n {\n \/\/ If memory limit is exceeded, force flush\n if(wrapper->buffer->byteSize() > config::buffers::writeBufferPerFileSizeLimit ||\n getWriteBufferSize() > config::buffers::writeBufferGlobalSizeLimit) {\n DLOG(INFO) << \"Write Buffer memory limit exceeded, force flush\";\n if(int fRet = onFlush(path, ffi)) {\n return fRet;\n }\n }\n\n \/\/ If memory limit is still exceeded, send the block without using buffer\n if(wrapper->buffer->byteSize() > config::buffers::writeBufferPerFileSizeLimit ||\n getWriteBufferSize() > config::buffers::writeBufferGlobalSizeLimit) {\n return doWrite(path, buf, size, offset, ffi);\n }\n\n \/\/ Save the block in write buffer\n wrapper->buffer->writeData(offset, buf);\n updateWrBufferSize(ffi->fh, wrapper->buffer->byteSize());\n }\n \n unique_lock buffGuard(wrapper->mutex);\n guard.lock();\n if(!wrapper->opPending) \n {\n \/\/ Notify workers if needed\n wrapper->opPending = true;\n m_wrJobQueue.push_back(ffi->fh);\n m_wrCond.notify_one();\n }\n\n return size;\n}\n\nint BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi)\n{\n unique_lock guard(m_rdMutex);\n read_buffer_ptr wrapper = m_rdCacheMap[path];\n guard.unlock();\n\n { \n unique_lock buffGuard(wrapper->mutex);\n \n wrapper->lastBlock[ffi->fh] = offset;\n wrapper->blockSize = std::min((size_t) config::buffers::preferedBlockSize, (size_t) std::max(size, 2*wrapper->blockSize));\n }\n\n wrapper->buffer->readData(offset, size, buf);\n updateRdBufferSize(path, wrapper->buffer->byteSize());\n\n \/\/ If cached file block is not complete, read it from server and save to cache\n if(buf.size() < size) {\n\n string buf2;\n int ret = doRead(path, buf2, size - buf.size(), offset + buf.size(), &wrapper->ffi);\n if(ret < 0)\n return ret;\n\n wrapper->buffer->writeData(offset + buf.size(), buf2);\n\n buf += buf2;\n\n guard.lock();\n m_rdJobQueue.insert(PrefetchJob(wrapper->fileName, offset + buf.size() + config::buffers::preferedBlockSize, wrapper->blockSize, ffi->fh));\n guard.unlock();\n } else {\n string tmp;\n size_t prefSize = std::max(2*size, wrapper->blockSize);\n wrapper->buffer->readData(offset + size, prefSize, tmp);\n\n if(tmp.size() != prefSize) {\n guard.lock();\n m_rdJobQueue.insert(PrefetchJob(wrapper->fileName, offset + size + tmp.size(), wrapper->blockSize, ffi->fh));\n m_rdJobQueue.insert(PrefetchJob(wrapper->fileName, offset + size + tmp.size() + wrapper->blockSize, wrapper->blockSize, ffi->fh));\n guard.unlock();\n }\n }\n\n { \n unique_lock buffGuard(wrapper->mutex);\n if(offset + buf.size() > wrapper->endOfFile)\n wrapper->endOfFile = 0;\n }\n\n m_rdCond.notify_one();\n\n return buf.size();\n}\n\nint BufferAgent::onFlush(std::string path, ffi_type ffi)\n{\n unique_lock guard(m_wrMutex);\n write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh];\n guard.unlock();\n\n unique_lock sendGuard(wrapper->sendMutex);\n unique_lock buff_guard(wrapper->mutex);\n\n \/\/ Send all pending blocks to server\n while(wrapper->buffer->blockCount() > 0) \n {\n block_ptr block = wrapper->buffer->removeOldestBlock();\n uint64_t start = utils::mtime<uint64_t>();\n int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);\n uint64_t end = utils::mtime<uint64_t>();\n\n if(res < 0)\n {\n \/\/ Skip all blocks after receiving error\n while(wrapper->buffer->blockCount() > 0)\n {\n (void) wrapper->buffer->removeOldestBlock();\n }\n return res;\n } else if(res < block->data.size()) {\n \/\/ Send wasn't complete\n block->offset += res;\n block->data = block->data.substr(res);\n wrapper->buffer->insertBlock(*block);\n }\n }\n\n updateWrBufferSize(ffi->fh, wrapper->buffer->byteSize());\n\n guard.lock();\n m_wrJobQueue.remove(ffi->fh);\n\n return 0;\n}\n\nint BufferAgent::onRelease(std::string path, ffi_type ffi)\n{\n {\n unique_lock guard(m_wrMutex);\n \n m_wrCacheMap.erase(ffi->fh);\n m_wrJobQueue.remove(ffi->fh);\n }\n\n {\n unique_lock guard(m_rdMutex);\n\n read_cache_map_t::iterator it;\n if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) {\n it->second->openCount--;\n if(it->second->openCount <= 0) {\n m_rdCacheMap.erase(it);\n }\n }\n }\n\n return 0;\n}\n\n\n\nvoid BufferAgent::agentStart(int worker_count)\n{\n m_workers.clear();\n m_agentActive = true;\n\n while(worker_count--)\n {\n m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::writerLoop, this))));\n m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::readerLoop, this))));\n }\n}\n\nvoid BufferAgent::agentStop()\n{\n m_agentActive = false;\n m_wrCond.notify_all();\n m_rdCond.notify_all();\n\n while(m_workers.size() > 0)\n {\n m_workers.back()->join();\n m_workers.pop_back();\n }\n}\n\nvoid BufferAgent::readerLoop() \n{\n unique_lock guard(m_rdMutex);\n while(m_agentActive)\n {\n while(m_rdJobQueue.empty() && m_agentActive)\n m_rdCond.wait(guard);\n\n if(!m_agentActive)\n return;\n\n PrefetchJob job = *m_rdJobQueue.begin();\n read_buffer_ptr wrapper = m_rdCacheMap[job.fileName];\n m_rdJobQueue.erase(m_rdJobQueue.begin());\n m_rdCond.notify_one();\n\n if(!wrapper || wrapper->lastBlock[job.fh] + config::buffers::preferedBlockSize >= job.offset + job.size || (wrapper->endOfFile > 0 && wrapper->endOfFile <= job.offset))\n continue;\n\n guard.unlock();\n\n {\n\n string buff;\n wrapper->buffer->readData(job.offset, job.size, buff);\n if(buff.size() < job.size)\n {\n string tmp;\n off_t effectiveOffset = job.offset + buff.size();\n int ret = doRead(wrapper->fileName, tmp, job.size, effectiveOffset, &wrapper->ffi);\n LOG(INFO) << \"Job: offset: \" << job.offset << \" size: \" << job.size << \" ret: \" << ret;\n \n guard.lock();\n unique_lock buffGuard(wrapper->mutex);\n\n if(ret > 0 && tmp.size() >= ret) {\n wrapper->buffer->writeData(effectiveOffset, tmp);\n updateRdBufferSize(job.fileName, wrapper->buffer->byteSize());\n \/\/m_rdJobQueue.insert(PrefetchJob(job.fileName, effectiveOffset + ret, wrapper->blockSize, job.fh));\n } else if(ret == 0) {\n wrapper->endOfFile = std::max(wrapper->endOfFile, effectiveOffset);\n }\n\n wrapper->cond.notify_all();\n\n guard.unlock();\n }\n }\n\n guard.lock();\n }\n}\n\nvoid BufferAgent::writerLoop()\n{\n unique_lock guard(m_wrMutex);\n while(m_agentActive)\n {\n while(m_wrJobQueue.empty() && m_agentActive)\n m_wrCond.wait(guard);\n\n if(!m_agentActive)\n return;\n\n std::multiset<PrefetchJob, PrefetchJobCompare>::iterator it;\n\n fd_type file = m_wrJobQueue.front();\n write_buffer_ptr wrapper = m_wrCacheMap[file];\n m_wrJobQueue.pop_front();\n m_wrCond.notify_one();\n\n if(!wrapper)\n continue;\n\n guard.unlock();\n\n {\n unique_lock sendGuard(wrapper->sendMutex);\n\n block_ptr block;\n {\n unique_lock buff_guard(wrapper->mutex);\n block = wrapper->buffer->removeOldestBlock();\n } \n\n int writeRes;\n if(block) \n {\n uint64_t start = utils::mtime<uint64_t>();\n writeRes = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);\n uint64_t end = utils::mtime<uint64_t>();\n\n \/\/LOG(INFO) << \"Roundtrip: \" << (end - start) << \" for \" << block->data.size() << \" bytes\";\n \n wrapper->cond.notify_all();\n }\n\n {\n unique_lock buff_guard(wrapper->mutex);\n guard.lock();\n\n if(block) \n {\n if(writeRes < 0) \n {\n while(wrapper->buffer->blockCount() > 0) \n {\n wrapper->buffer->removeOldestBlock();\n }\n\n wrapper->lastError = writeRes;\n } \n else if(writeRes < block->data.size()) \n {\n block->offset += writeRes;\n block->data = block->data.substr(writeRes);\n wrapper->buffer->insertBlock(*block);\n }\n }\n\n if(wrapper->buffer->blockCount() > 0)\n {\n m_wrJobQueue.push_back(file);\n } \n else \n {\n wrapper->opPending = false;\n }\n\n updateWrBufferSize(file, wrapper->buffer->byteSize());\n } \n }\n \n wrapper->cond.notify_all();\n }\n}\n\nboost::shared_ptr<FileCache> BufferAgent::newFileCache(bool isBuffer)\n{\n return boost::shared_ptr<FileCache>(new FileCache(config::buffers::preferedBlockSize, isBuffer));\n}\n\n} \/\/ namespace helpers \n} \/\/ namespace veil\n\n<commit_msg>VFS-292: docs<commit_after>#include \"bufferAgent.h\"\n#include \"helpers\/storageHelperFactory.h\"\n#include \"glog\/logging.h\"\n\nusing boost::shared_ptr;\nusing boost::thread;\nusing boost::bind;\n\nusing std::string;\n\nnamespace veil {\nnamespace helpers {\n\nboost::recursive_mutex BufferAgent::m_bufferSizeMutex;\nvolatile size_t BufferAgent::m_rdBufferTotalSize;\nvolatile size_t BufferAgent::m_wrBufferTotalSize;\nrdbuf_size_mem_t BufferAgent::m_rdBufferSizeMem;\nwrbuf_size_mem_t BufferAgent::m_wrBufferSizeMem;\n\nBufferAgent::BufferAgent(write_fun w, read_fun r)\n : m_agentActive(false),\n doWrite(w),\n doRead(r)\n{\n agentStart(1);\n}\n\nBufferAgent::~BufferAgent()\n{\n agentStop();\n}\n\nvoid BufferAgent::updateWrBufferSize(fd_type key, size_t size)\n{\n unique_lock guard(m_bufferSizeMutex);\n wrbuf_size_mem_t::iterator it = m_wrBufferSizeMem.find(key);\n\n \/\/ If entry for this key doesn't exist, just create one\n if(it == m_wrBufferSizeMem.end()) {\n m_wrBufferSizeMem[key] = size;\n m_rdBufferTotalSize += size;\n } else {\n \/\/ If key exists, update total bytes size according to diff between last size and current \n if(size < it->second && (it->second - size) >= m_wrBufferTotalSize) {\n m_wrBufferTotalSize = 0;\n } else {\n m_wrBufferTotalSize += (size - it->second);\n }\n\n if(size == 0) {\n m_wrBufferSizeMem.erase(key);\n } else {\n m_wrBufferSizeMem[key] = size;\n }\n }\n}\n\nvoid BufferAgent::updateRdBufferSize(std::string key, size_t size) \n{\n unique_lock guard(m_bufferSizeMutex);\n rdbuf_size_mem_t::iterator it = m_rdBufferSizeMem.find(key);\n\n if(it == m_rdBufferSizeMem.end()) {\n m_rdBufferSizeMem[key] = size;\n m_rdBufferTotalSize += size;\n \/\/ If key exists, update total bytes size according to diff between last size and current \n } else {\n if(size < it->second && (it->second - size) >= m_rdBufferTotalSize) {\n m_rdBufferTotalSize = 0;\n } else {\n m_rdBufferTotalSize += (size - it->second);\n }\n\n if(size == 0) {\n m_rdBufferSizeMem.erase(key);\n } else {\n m_rdBufferSizeMem[key] = size;\n }\n }\n}\n\nsize_t BufferAgent::getWriteBufferSize()\n{\n unique_lock guard(m_bufferSizeMutex);\n return m_wrBufferTotalSize;\n}\n\nsize_t BufferAgent::getReadBufferSize()\n{\n unique_lock guard(m_bufferSizeMutex);\n return m_rdBufferTotalSize;\n} \n\nint BufferAgent::onOpen(std::string path, ffi_type ffi)\n{\n DLOG(INFO) << \"BufferAgent::onOpen(\" << path << \")\";\n \/\/ Initialize write buffer's holder\n {\n unique_lock guard(m_wrMutex);\n m_wrCacheMap.erase(ffi->fh);\n\n write_buffer_ptr lCache(new WriteCache());\n lCache->fileName = path;\n lCache->buffer = newFileCache(true);\n lCache->ffi = *ffi;\n\n m_wrCacheMap[ffi->fh] = lCache;\n }\n\n { \/\/ Initialize read buffer's holder\n unique_lock guard(m_rdMutex);\n read_cache_map_t::iterator it;\n if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) {\n it->second->openCount++;\n } else {\n read_buffer_ptr lCache(new ReadCache());\n lCache->fileName = path;\n lCache->openCount = 1;\n lCache->ffi = *ffi;\n lCache->buffer = newFileCache(false);\n\n m_rdCacheMap[path] = lCache;\n }\n\n \/\/ Prefetch first 512B block\n m_rdJobQueue.insert(PrefetchJob(path, 0, 512, ffi->fh));\n m_rdCond.notify_one();\n }\n\n return 0;\n}\n\nint BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi)\n{\n DLOG(INFO) << \"BufferAgent::onWrite(path: \" << path << \", size: \" << size << \", offset: \" << offset <<\")\";\n unique_lock guard(m_wrMutex);\n write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh];\n\n \/\/ If there was an error while sending cached data, return this error \n if(wrapper->lastError < 0) {\n wrapper->lastError = 0;\n return wrapper->lastError;\n }\n\n guard.unlock();\n\n {\n \/\/ If memory limit is exceeded, force flush\n if(wrapper->buffer->byteSize() > config::buffers::writeBufferPerFileSizeLimit ||\n getWriteBufferSize() > config::buffers::writeBufferGlobalSizeLimit) {\n DLOG(INFO) << \"Write Buffer memory limit exceeded, force flush\";\n if(int fRet = onFlush(path, ffi)) {\n return fRet;\n }\n }\n\n \/\/ If memory limit is still exceeded, send the block without using buffer\n if(wrapper->buffer->byteSize() > config::buffers::writeBufferPerFileSizeLimit ||\n getWriteBufferSize() > config::buffers::writeBufferGlobalSizeLimit) {\n return doWrite(path, buf, size, offset, ffi);\n }\n\n \/\/ Save the block in write buffer\n wrapper->buffer->writeData(offset, buf);\n updateWrBufferSize(ffi->fh, wrapper->buffer->byteSize());\n }\n \n unique_lock buffGuard(wrapper->mutex);\n guard.lock();\n if(!wrapper->opPending) \n {\n \/\/ Notify workers if needed\n wrapper->opPending = true;\n m_wrJobQueue.push_back(ffi->fh);\n m_wrCond.notify_one();\n }\n\n return size;\n}\n\nint BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi)\n{\n unique_lock guard(m_rdMutex);\n read_buffer_ptr wrapper = m_rdCacheMap[path];\n guard.unlock();\n\n { \n unique_lock buffGuard(wrapper->mutex);\n \n wrapper->lastBlock[ffi->fh] = offset;\n wrapper->blockSize = std::min((size_t) config::buffers::preferedBlockSize, (size_t) std::max(size, 2*wrapper->blockSize));\n }\n\n wrapper->buffer->readData(offset, size, buf);\n updateRdBufferSize(path, wrapper->buffer->byteSize());\n\n \/\/ If cached file block is not complete, read it from server and save to cache\n if(buf.size() < size) {\n\n string buf2;\n int ret = doRead(path, buf2, size - buf.size(), offset + buf.size(), &wrapper->ffi);\n if(ret < 0)\n return ret;\n\n wrapper->buffer->writeData(offset + buf.size(), buf2);\n\n buf += buf2;\n\n guard.lock();\n m_rdJobQueue.insert(PrefetchJob(wrapper->fileName, offset + buf.size() + config::buffers::preferedBlockSize, wrapper->blockSize, ffi->fh));\n guard.unlock();\n } else {\n string tmp;\n size_t prefSize = std::max(2*size, wrapper->blockSize);\n wrapper->buffer->readData(offset + size, prefSize, tmp);\n\n if(tmp.size() != prefSize) {\n guard.lock();\n m_rdJobQueue.insert(PrefetchJob(wrapper->fileName, offset + size + tmp.size(), wrapper->blockSize, ffi->fh));\n m_rdJobQueue.insert(PrefetchJob(wrapper->fileName, offset + size + tmp.size() + wrapper->blockSize, wrapper->blockSize, ffi->fh));\n guard.unlock();\n }\n }\n\n { \n unique_lock buffGuard(wrapper->mutex);\n if(offset + buf.size() > wrapper->endOfFile)\n wrapper->endOfFile = 0;\n }\n\n m_rdCond.notify_one();\n\n return buf.size();\n}\n\nint BufferAgent::onFlush(std::string path, ffi_type ffi)\n{\n unique_lock guard(m_wrMutex);\n write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh];\n guard.unlock();\n\n unique_lock sendGuard(wrapper->sendMutex);\n unique_lock buff_guard(wrapper->mutex);\n\n \/\/ Send all pending blocks to server\n while(wrapper->buffer->blockCount() > 0) \n {\n block_ptr block = wrapper->buffer->removeOldestBlock();\n uint64_t start = utils::mtime<uint64_t>();\n int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);\n uint64_t end = utils::mtime<uint64_t>();\n\n if(res < 0)\n {\n \/\/ Skip all blocks after receiving error\n while(wrapper->buffer->blockCount() > 0)\n {\n (void) wrapper->buffer->removeOldestBlock();\n }\n return res;\n } else if(res < block->data.size()) {\n \/\/ Send wasn't complete\n block->offset += res;\n block->data = block->data.substr(res);\n wrapper->buffer->insertBlock(*block);\n }\n }\n\n updateWrBufferSize(ffi->fh, wrapper->buffer->byteSize());\n\n guard.lock();\n m_wrJobQueue.remove(ffi->fh);\n\n return 0;\n}\n\nint BufferAgent::onRelease(std::string path, ffi_type ffi)\n{\n {\n unique_lock guard(m_wrMutex);\n \n m_wrCacheMap.erase(ffi->fh);\n m_wrJobQueue.remove(ffi->fh);\n }\n\n {\n unique_lock guard(m_rdMutex);\n\n read_cache_map_t::iterator it;\n if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) {\n it->second->openCount--;\n if(it->second->openCount <= 0) {\n m_rdCacheMap.erase(it);\n }\n }\n }\n\n return 0;\n}\n\n\n\nvoid BufferAgent::agentStart(int worker_count)\n{\n m_workers.clear();\n m_agentActive = true;\n\n while(worker_count--)\n {\n m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::writerLoop, this))));\n m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::readerLoop, this))));\n }\n}\n\nvoid BufferAgent::agentStop()\n{\n m_agentActive = false;\n m_wrCond.notify_all();\n m_rdCond.notify_all();\n\n while(m_workers.size() > 0)\n {\n m_workers.back()->join();\n m_workers.pop_back();\n }\n}\n\nvoid BufferAgent::readerLoop() \n{\n unique_lock guard(m_rdMutex);\n while(m_agentActive)\n {\n while(m_rdJobQueue.empty() && m_agentActive)\n m_rdCond.wait(guard);\n\n if(!m_agentActive)\n return;\n\n PrefetchJob job = *m_rdJobQueue.begin();\n read_buffer_ptr wrapper = m_rdCacheMap[job.fileName];\n m_rdJobQueue.erase(m_rdJobQueue.begin());\n m_rdCond.notify_one();\n\n if(!wrapper || wrapper->lastBlock[job.fh] + config::buffers::preferedBlockSize >= job.offset + job.size || (wrapper->endOfFile > 0 && wrapper->endOfFile <= job.offset))\n continue;\n\n guard.unlock();\n\n {\n\n string buff;\n wrapper->buffer->readData(job.offset, job.size, buff);\n if(buff.size() < job.size)\n {\n string tmp;\n off_t effectiveOffset = job.offset + buff.size();\n int ret = doRead(wrapper->fileName, tmp, job.size, effectiveOffset, &wrapper->ffi);\n LOG(INFO) << \"Job: offset: \" << job.offset << \" size: \" << job.size << \" ret: \" << ret;\n \n guard.lock();\n unique_lock buffGuard(wrapper->mutex);\n\n if(ret > 0 && tmp.size() >= ret) {\n wrapper->buffer->writeData(effectiveOffset, tmp);\n updateRdBufferSize(job.fileName, wrapper->buffer->byteSize());\n m_rdJobQueue.insert(PrefetchJob(job.fileName, effectiveOffset + ret, wrapper->blockSize, job.fh));\n } else if(ret == 0) {\n wrapper->endOfFile = std::max(wrapper->endOfFile, effectiveOffset);\n }\n\n wrapper->cond.notify_all();\n\n guard.unlock();\n }\n }\n\n guard.lock();\n }\n}\n\nvoid BufferAgent::writerLoop()\n{\n unique_lock guard(m_wrMutex);\n while(m_agentActive)\n {\n while(m_wrJobQueue.empty() && m_agentActive)\n m_wrCond.wait(guard);\n\n if(!m_agentActive)\n return;\n\n std::multiset<PrefetchJob, PrefetchJobCompare>::iterator it;\n\n fd_type file = m_wrJobQueue.front();\n write_buffer_ptr wrapper = m_wrCacheMap[file];\n m_wrJobQueue.pop_front();\n m_wrCond.notify_one();\n\n if(!wrapper)\n continue;\n\n guard.unlock();\n\n {\n unique_lock sendGuard(wrapper->sendMutex);\n\n block_ptr block;\n {\n unique_lock buff_guard(wrapper->mutex);\n block = wrapper->buffer->removeOldestBlock();\n } \n\n int writeRes;\n if(block) \n {\n uint64_t start = utils::mtime<uint64_t>();\n writeRes = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);\n uint64_t end = utils::mtime<uint64_t>();\n\n \/\/LOG(INFO) << \"Roundtrip: \" << (end - start) << \" for \" << block->data.size() << \" bytes\";\n \n wrapper->cond.notify_all();\n }\n\n {\n unique_lock buff_guard(wrapper->mutex);\n guard.lock();\n\n if(block) \n {\n if(writeRes < 0) \n {\n while(wrapper->buffer->blockCount() > 0) \n {\n wrapper->buffer->removeOldestBlock();\n }\n\n wrapper->lastError = writeRes;\n } \n else if(writeRes < block->data.size()) \n {\n block->offset += writeRes;\n block->data = block->data.substr(writeRes);\n wrapper->buffer->insertBlock(*block);\n }\n }\n\n if(wrapper->buffer->blockCount() > 0)\n {\n m_wrJobQueue.push_back(file);\n } \n else \n {\n wrapper->opPending = false;\n }\n\n updateWrBufferSize(file, wrapper->buffer->byteSize());\n } \n }\n \n wrapper->cond.notify_all();\n }\n}\n\nboost::shared_ptr<FileCache> BufferAgent::newFileCache(bool isBuffer)\n{\n return boost::shared_ptr<FileCache>(new FileCache(config::buffers::preferedBlockSize, isBuffer));\n}\n\n} \/\/ namespace helpers \n} \/\/ namespace veil\n\n<|endoftext|>"} {"text":"<commit_before>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n * Copyright (C) 2005 Refractions Research Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\/\n\n#include <geos\/opBuffer.h>\n\n#ifndef DEBUG\n#define DEBUG 0\n#endif\n\n\nnamespace geos {\n\nSubgraphDepthLocater::SubgraphDepthLocater(vector<BufferSubgraph*> *nsg):\n\tseg(new LineSegment()),\n\tsubgraphs(nsg)\n{\n\t\/\/seg=new LineSegment();\n\t\/\/cga=new RobustCGAlgorithms();\n\t\/\/subgraphs=newSubgraphs;\n}\n\nSubgraphDepthLocater::~SubgraphDepthLocater(){\n\tdelete seg;\n\t\/\/delete cga;\n}\n\nint\nSubgraphDepthLocater::getDepth(Coordinate &p)\n{\n\tvector<DepthSegment*> *stabbedSegments=findStabbedSegments(p);\n\t\/\/ if no segments on stabbing line subgraph must be outside all others->\n\tif ((int)stabbedSegments->size()==0)\n\t{\n\t\tdelete stabbedSegments;\n\t\treturn 0;\n\t}\n\tsort(stabbedSegments->begin(),stabbedSegments->end(),DepthSegmentLT);\n\tDepthSegment *ds=(*stabbedSegments)[0];\n\tint ret = ds->leftDepth;\n#if DEBUG\n\tcerr<<\"SubgraphDepthLocater::getDepth(\"<<p.toString()<<\"): \"<<ret<<endl;\n#endif\n\n\tvector<DepthSegment *>::iterator it;\n\tfor (it=stabbedSegments->begin(); it != stabbedSegments->end(); it++)\n\t\tdelete *it;\n\tdelete stabbedSegments;\n\n\treturn ret;\n}\n\n\/**\n* Finds all non-horizontal segments intersecting the stabbing line->\n* The stabbing line is the ray to the right of stabbingRayLeftPt->\n*\n* @param stabbingRayLeftPt the left-hand origin of the stabbing line\n* @return a List of {@link DepthSegments} intersecting the stabbing line\n*\/\nvector<DepthSegment*>* SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt){\n\tvector<DepthSegment*> *stabbedSegments=new vector<DepthSegment*>();\n\tfor (int i=0;i<(int)subgraphs->size();i++) {\n\t\tBufferSubgraph *bsg=(*subgraphs)[i];\n\t\tfindStabbedSegments(stabbingRayLeftPt, bsg->getDirectedEdges(), stabbedSegments);\n\t}\n\treturn stabbedSegments;\n}\n\n\/**\n* Finds all non-horizontal segments intersecting the stabbing line\n* in the list of dirEdges->\n* The stabbing line is the ray to the right of stabbingRayLeftPt->\n*\n* @param stabbingRayLeftPt the left-hand origin of the stabbing line\n* @param stabbedSegments the current list of {@link DepthSegments} intersecting the stabbing line\n*\/\nvoid SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,vector<DirectedEdge*> *dirEdges,vector<DepthSegment*> *stabbedSegments){\n\t\/**\n\t* Check all forward DirectedEdges only-> This is still general,\n\t* because each Edge has a forward DirectedEdge->\n\t*\/\n\tfor(int i=0;i<(int)dirEdges->size();i++) {\n\t\tDirectedEdge *de=(*dirEdges)[i];\n\t\tif (!de->isForward())\n\t\t\tcontinue;\n\t\tfindStabbedSegments(stabbingRayLeftPt, de, stabbedSegments);\n\t}\n}\n\n\/**\n * Finds all non-horizontal segments intersecting the stabbing line\n * in the input dirEdge->\n * The stabbing line is the ray to the right of stabbingRayLeftPt->\n *\n * @param stabbingRayLeftPt the left-hand origin of the stabbing line\n * @param stabbedSegments the current list of DepthSegments\n * intersecting the stabbing line\n *\/\nvoid\nSubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,DirectedEdge *dirEdge,vector<DepthSegment*> *stabbedSegments)\n{\n\tconst CoordinateSequence *pts=dirEdge->getEdge()->getCoordinates();\n\n\tfor (int i=0; i<pts->getSize()-1; i++) {\n\t\t\/\/seg->p0=pts->getAt(i);\n\t\t\/\/seg->p1=pts->getAt(i + 1);\n\n\t\tconst Coordinate *low=&(pts->getAt(i));\n\t\tconst Coordinate *high=&(pts->getAt(i+1));\n\t\tconst Coordinate *swap=NULL;\n\n#if DEBUG\n\tcerr<<\" SubgraphDepthLocater::findStabbedSegments: segment \"<<i<<\" (\"<<seg->toString()<<\") \";\n#endif\n\n\/\/\t\t\/\/ ensure segment always points upwards\n\/\/\t\t\/\/if (seg->p0.y > seg->p1.y)\n\/\/\t\t{\n\/\/\t\t\tseg->reverse();\n\/\/#if DEBUG\n\/\/\t\t\tcerr<<\" reverse (\"<<seg->toString()<<\") \";\n\/\/#endif\n\/\/\t\t}\n\n\t\t\/\/ skip segment if it is left of the stabbing line\n\t\t\/\/double maxx=max(seg->p0.x, seg->p1.x);\n\t\tdouble maxx=max(low->x, high->x);\n\t\tif (maxx < stabbingRayLeftPt.x)\n\t\t{\n#if DEBUG\n\t\t\tcerr<<\" segment is left to stabbing line, skipping \"<<endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ skip horizontal segments (there will be a non-horizontal\n\t\t\/\/ one carrying the same depth info\n\t\t\/\/if (seg->isHorizontal())\n\t\tif (low->y == high->y)\n\t\t{\n#if DEBUG\n\t\t\tcerr<<\" segment is horizontal, skipping \"<<endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ skip if segment is above or below stabbing line\n\t\t\/\/if (stabbingRayLeftPt.y < seg->p0.y ||\n\t\t\t\/\/stabbingRayLeftPt.y > seg->p1.y)\n\t\tif (stabbingRayLeftPt.y < low->y ||\n\t\t\tstabbingRayLeftPt.y > high->y)\n\t\t{\n#if DEBUG\n\t\t\tcerr<<\" segment above or below stabbing line, skipping \"<<endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ skip if stabbing ray is right of the segment\n\t\t\/\/if (CGAlgorithms::computeOrientation(seg->p0, seg->p1,\n\t\tif (CGAlgorithms::computeOrientation(*low, *high,\n\t\t\t\tstabbingRayLeftPt)==CGAlgorithms::RIGHT)\n\t\t{\n#if DEBUG\n\t\t\tcerr<<\" stabbing ray right of segment, skipping\"<<endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\/\/\t\t\/\/ stabbing line cuts this segment, so record it\n\/\/\t\tint depth=dirEdge->getDepth(Position::LEFT);\n\/\/\t\t\/\/ if segment direction was flipped, use RHS depth instead\n\/\/\t\tif (! (seg->p0==pts->getAt(i)))\n\/\/\t\t\tdepth=dirEdge->getDepth(Position::RIGHT);\n\t\tint depth = swap ?\n\t\t\tdirEdge->getDepth(Position::LEFT)\n\t\t\t:\n\t\t\tdirEdge->getDepth(Position::RIGHT);\n\n#if DEBUG\n\tcerr<<\" depth: \"<<depth<<endl;\n#endif\n\t\tseg->p0 = *low;\n\t\tseg->p1 = *high;\n\t\tDepthSegment *ds=new DepthSegment(seg, depth);\n\t\tstabbedSegments->push_back(ds);\n\t}\n}\n\nDepthSegment::DepthSegment(LineSegment *seg, int depth){\n\t\/\/ input seg is assumed to be normalized\n\tupwardSeg=new LineSegment(*seg);\n\t\/\/upwardSeg->normalize();\n\tleftDepth=depth;\n}\n\nDepthSegment::~DepthSegment(){\n\tdelete upwardSeg;\n}\n\/**\n* Defines a comparision operation on DepthSegments\n* which orders them left to right\n*\n* <pre>\n* DS1 < DS2 if DS1->seg is left of DS2->seg\n* DS1 > DS2 if DS1->seg is right of DS2->seg\n* <\/pre>\n*\n* @param obj\n* @return\n*\/\nint DepthSegment::compareTo(void* obj){\n\tDepthSegment *other=(DepthSegment*) obj;\n\t\/**\n\t* try and compute a determinate orientation for the segments->\n\t* Test returns 1 if other is left of this (i->e-> this > other)\n\t*\/\n\tint orientIndex=upwardSeg->orientationIndex(other->upwardSeg);\n\t\/**\n\t* If comparison between this and other is indeterminate,\n\t* try the opposite call order->\n\t* orientationIndex value is 1 if this is left of other,\n\t* so have to flip sign to get proper comparison value of\n\t* -1 if this is leftmost\n\t*\/\n\tif (orientIndex==0)\n\t\torientIndex=-1 * other->upwardSeg->orientationIndex(upwardSeg);\n\t\/\/ if orientation is determinate, return it\n\tif (orientIndex != 0)\n\t\treturn orientIndex;\n\t\/\/ otherwise, segs must be collinear - sort based on minimum X value\n\treturn compareX(upwardSeg, other->upwardSeg);\n}\n\n\/**\n* Compare two collinear segments for left-most ordering->\n* If segs are vertical, use vertical ordering for comparison->\n* If segs are equal, return 0->\n* Segments are assumed to be directed so that the second coordinate is >= to the first\n* (e->g-> up and to the right)->\n*\n* @param seg0 a segment to compare\n* @param seg1 a segment to compare\n* @return\n*\/\nint DepthSegment::compareX(LineSegment *seg0, LineSegment *seg1){\n\tint compare0=seg0->p0.compareTo(seg1->p0);\n\tif (compare0!=0)\n\t\treturn compare0;\n\treturn seg0->p1.compareTo(seg1->p1);\n\n}\n\nbool DepthSegmentLT(DepthSegment *first, DepthSegment *second) {\n\tif (first->compareTo(second)<0)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\n} \/\/ namespace geos\n\n\/**********************************************************************\n * $Log$\n * Revision 1.11 2005\/06\/27 21:58:31 strk\n * Bugfix in DepthSegmentLT as suggested by Graeme Hiebert\n *\n * Revision 1.10 2005\/06\/27 21:24:54 strk\n * Fixed bug just-introduced with optimization.\n *\n * Revision 1.9 2005\/06\/27 21:21:21 strk\n * Reduced Coordinate copies due to LineSegment overuse\n *\n * Revision 1.8 2005\/05\/23 15:13:00 strk\n * Added debugging output\n *\n * Revision 1.7 2005\/05\/20 16:15:41 strk\n * Code cleanups\n *\n * Revision 1.6 2005\/05\/19 10:29:28 strk\n * Removed some CGAlgorithms instances substituting them with direct calls\n * to the static functions. Interfaces accepting CGAlgorithms pointers kept\n * for backward compatibility but modified to make the argument optional.\n * Fixed a small memory leak in OffsetCurveBuilder::getRingCurve.\n * Inlined some smaller functions encountered during bug hunting.\n * Updated Copyright notices in the touched files.\n *\n * Revision 1.5 2004\/07\/08 19:34:49 strk\n * Mirrored JTS interface of CoordinateSequence, factory and\n * default implementations.\n * Added DefaultCoordinateSequenceFactory::instance() function.\n *\n * Revision 1.4 2004\/07\/02 13:28:28 strk\n * Fixed all #include lines to reflect headers layout change.\n * Added client application build tips in README.\n *\n * Revision 1.3 2004\/05\/05 12:29:44 strk\n * memleak fixed in ::getDepth\n *\n * Revision 1.2 2004\/05\/03 22:56:44 strk\n * leaks fixed, exception specification omitted.\n *\n * Revision 1.1 2004\/04\/10 08:40:01 ybychkov\n * \"operation\/buffer\" upgraded to JTS 1.4\n *\n *\n **********************************************************************\/\n\n<commit_msg>Fixed a bug introduced by LineSegment skip - made LineSegment skip a compile-time optione<commit_after>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n * Copyright (C) 2005 Refractions Research Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\/\n\n#include <geos\/opBuffer.h>\n\n#ifndef DEBUG\n#define DEBUG 0\n#endif\n\n\nnamespace geos {\n\nSubgraphDepthLocater::SubgraphDepthLocater(vector<BufferSubgraph*> *nsg):\n\tseg(new LineSegment()),\n\tsubgraphs(nsg)\n{\n\t\/\/seg=new LineSegment();\n\t\/\/cga=new RobustCGAlgorithms();\n\t\/\/subgraphs=newSubgraphs;\n}\n\nSubgraphDepthLocater::~SubgraphDepthLocater(){\n\tdelete seg;\n\t\/\/delete cga;\n}\n\nint\nSubgraphDepthLocater::getDepth(Coordinate &p)\n{\n\tvector<DepthSegment*> *stabbedSegments=findStabbedSegments(p);\n\t\/\/ if no segments on stabbing line subgraph must be outside all others->\n\tif ((int)stabbedSegments->size()==0)\n\t{\n\t\tdelete stabbedSegments;\n\t\treturn 0;\n\t}\n\tsort(stabbedSegments->begin(),stabbedSegments->end(),DepthSegmentLT);\n\tDepthSegment *ds=(*stabbedSegments)[0];\n\tint ret = ds->leftDepth;\n#if DEBUG\n\tcerr<<\"SubgraphDepthLocater::getDepth(\"<<p.toString()<<\"): \"<<ret<<endl;\n#endif\n\n\tvector<DepthSegment *>::iterator it;\n\tfor (it=stabbedSegments->begin(); it != stabbedSegments->end(); it++)\n\t\tdelete *it;\n\tdelete stabbedSegments;\n\n\treturn ret;\n}\n\n\/**\n* Finds all non-horizontal segments intersecting the stabbing line->\n* The stabbing line is the ray to the right of stabbingRayLeftPt->\n*\n* @param stabbingRayLeftPt the left-hand origin of the stabbing line\n* @return a List of {@link DepthSegments} intersecting the stabbing line\n*\/\nvector<DepthSegment*>* SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt){\n\tvector<DepthSegment*> *stabbedSegments=new vector<DepthSegment*>();\n\tfor (int i=0;i<(int)subgraphs->size();i++) {\n\t\tBufferSubgraph *bsg=(*subgraphs)[i];\n\t\tfindStabbedSegments(stabbingRayLeftPt, bsg->getDirectedEdges(), stabbedSegments);\n\t}\n\treturn stabbedSegments;\n}\n\n\/**\n* Finds all non-horizontal segments intersecting the stabbing line\n* in the list of dirEdges->\n* The stabbing line is the ray to the right of stabbingRayLeftPt->\n*\n* @param stabbingRayLeftPt the left-hand origin of the stabbing line\n* @param stabbedSegments the current list of {@link DepthSegments} intersecting the stabbing line\n*\/\nvoid SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,vector<DirectedEdge*> *dirEdges,vector<DepthSegment*> *stabbedSegments){\n\t\/**\n\t* Check all forward DirectedEdges only-> This is still general,\n\t* because each Edge has a forward DirectedEdge->\n\t*\/\n\tfor(int i=0;i<(int)dirEdges->size();i++) {\n\t\tDirectedEdge *de=(*dirEdges)[i];\n\t\tif (!de->isForward())\n\t\t\tcontinue;\n\t\tfindStabbedSegments(stabbingRayLeftPt, de, stabbedSegments);\n\t}\n}\n\n\/**\n * Finds all non-horizontal segments intersecting the stabbing line\n * in the input dirEdge->\n * The stabbing line is the ray to the right of stabbingRayLeftPt->\n *\n * @param stabbingRayLeftPt the left-hand origin of the stabbing line\n * @param stabbedSegments the current list of DepthSegments\n * intersecting the stabbing line\n *\/\nvoid\nSubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,DirectedEdge *dirEdge,vector<DepthSegment*> *stabbedSegments)\n{\n\tconst CoordinateSequence *pts=dirEdge->getEdge()->getCoordinates();\n\n\/\/ It seems that LineSegment is *very* slow... undef this\n\/\/ to see yourself\n#define SKIP_LS 1\n\n\tfor (int i=0; i<pts->getSize()-1; i++) {\n#ifndef SKIP_LS\n\t\tseg->p0=pts->getAt(i);\n\t\tseg->p1=pts->getAt(i + 1);\n#else\n\n\t\tconst Coordinate *low=&(pts->getAt(i));\n\t\tconst Coordinate *high=&(pts->getAt(i+1));\n\t\tconst Coordinate *swap=NULL;\n\n#endif\n\n#if DEBUG\n\tcerr<<\" SubgraphDepthLocater::findStabbedSegments: segment \"<<i<<\" (\"<<seg->toString()<<\") \";\n#endif\n\n#ifndef SKIP_LS\n\t\t\/\/ ensure segment always points upwards\n\t\t\/\/if (seg->p0.y > seg->p1.y)\n\t\t{\n\t\t\tseg->reverse();\n#if DEBUG\n\t\t\tcerr<<\" reverse (\"<<seg->toString()<<\") \";\n#endif\n\t\t}\n#else\n\t\tif (low->y > high->y)\n\t\t{\n\t\t\tswap=low;\n\t\t\tlow=high;\n\t\t\thigh=swap;\n\t\t}\n#endif\n\n\t\t\/\/ skip segment if it is left of the stabbing line\n\t\t\/\/ skip if segment is above or below stabbing line\n#ifndef SKIP_LS\n\t\tdouble maxx=max(seg->p0.x, seg->p1.x);\n#else\n\t\tdouble maxx=max(low->x, high->x);\n#endif\n\t\tif (maxx < stabbingRayLeftPt.x)\n\t\t{\n#if DEBUG\n\t\t\tcerr<<\" segment is left to stabbing line, skipping \"<<endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ skip horizontal segments (there will be a non-horizontal\n\t\t\/\/ one carrying the same depth info\n#ifndef SKIP_LS\n\t\tif (seg->isHorizontal())\n#else\n\t\tif (low->y == high->y)\n#endif\n\t\t{\n#if DEBUG\n\t\t\tcerr<<\" segment is horizontal, skipping \"<<endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ skip if segment is above or below stabbing line\n#ifndef SKIP_LS\n\t\tif (stabbingRayLeftPt.y < seg->p0.y ||\n\t\t\tstabbingRayLeftPt.y > seg->p1.y)\n#else\n\t\tif (stabbingRayLeftPt.y < low->y ||\n\t\t\tstabbingRayLeftPt.y > high->y)\n#endif\n\t\t{\n#if DEBUG\n\t\t\tcerr<<\" segment above or below stabbing line, skipping \"<<endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ skip if stabbing ray is right of the segment\n#ifndef SKIP_LS\n\t\tif (CGAlgorithms::computeOrientation(seg->p0, seg->p1,\n#else\n\t\tif (CGAlgorithms::computeOrientation(*low, *high,\n#endif\n\t\t\t\tstabbingRayLeftPt)==CGAlgorithms::RIGHT)\n\t\t{\n#if DEBUG\n\t\t\tcerr<<\" stabbing ray right of segment, skipping\"<<endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n#ifndef SKIP_LS\n\t\t\/\/ stabbing line cuts this segment, so record it\n\t\tint depth=dirEdge->getDepth(Position::LEFT);\n\t\t\/\/ if segment direction was flipped, use RHS depth instead\n\t\tif (! (seg->p0==pts->getAt(i)))\n\t\t\tdepth=dirEdge->getDepth(Position::RIGHT);\n#else\n\t\tint depth = swap ?\n\t\t\tdirEdge->getDepth(Position::RIGHT)\n\t\t\t:\n\t\t\tdirEdge->getDepth(Position::LEFT);\n#endif\n\n#if DEBUG\n\tcerr<<\" depth: \"<<depth<<endl;\n#endif\n\n#ifdef SKIP_LS\n\t\tseg->p0 = *low;\n\t\tseg->p1 = *high;\n#endif\n\t\tDepthSegment *ds=new DepthSegment(seg, depth);\n\t\tstabbedSegments->push_back(ds);\n\t}\n}\n\nDepthSegment::DepthSegment(LineSegment *seg, int depth){\n\t\/\/ input seg is assumed to be normalized\n\tupwardSeg=new LineSegment(*seg);\n\t\/\/upwardSeg->normalize();\n\tleftDepth=depth;\n}\n\nDepthSegment::~DepthSegment(){\n\tdelete upwardSeg;\n}\n\/**\n* Defines a comparision operation on DepthSegments\n* which orders them left to right\n*\n* <pre>\n* DS1 < DS2 if DS1->seg is left of DS2->seg\n* DS1 > DS2 if DS1->seg is right of DS2->seg\n* <\/pre>\n*\n* @param obj\n* @return\n*\/\nint DepthSegment::compareTo(void* obj){\n\tDepthSegment *other=(DepthSegment*) obj;\n\t\/**\n\t* try and compute a determinate orientation for the segments->\n\t* Test returns 1 if other is left of this (i->e-> this > other)\n\t*\/\n\tint orientIndex=upwardSeg->orientationIndex(other->upwardSeg);\n\t\/**\n\t* If comparison between this and other is indeterminate,\n\t* try the opposite call order->\n\t* orientationIndex value is 1 if this is left of other,\n\t* so have to flip sign to get proper comparison value of\n\t* -1 if this is leftmost\n\t*\/\n\tif (orientIndex==0)\n\t\torientIndex=-1 * other->upwardSeg->orientationIndex(upwardSeg);\n\t\/\/ if orientation is determinate, return it\n\tif (orientIndex != 0)\n\t\treturn orientIndex;\n\t\/\/ otherwise, segs must be collinear - sort based on minimum X value\n\treturn compareX(upwardSeg, other->upwardSeg);\n}\n\n\/**\n* Compare two collinear segments for left-most ordering->\n* If segs are vertical, use vertical ordering for comparison->\n* If segs are equal, return 0->\n* Segments are assumed to be directed so that the second coordinate is >= to the first\n* (e->g-> up and to the right)->\n*\n* @param seg0 a segment to compare\n* @param seg1 a segment to compare\n* @return\n*\/\nint DepthSegment::compareX(LineSegment *seg0, LineSegment *seg1){\n\tint compare0=seg0->p0.compareTo(seg1->p0);\n\tif (compare0!=0)\n\t\treturn compare0;\n\treturn seg0->p1.compareTo(seg1->p1);\n\n}\n\nbool DepthSegmentLT(DepthSegment *first, DepthSegment *second) {\n\tif (first->compareTo(second)<0)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\n} \/\/ namespace geos\n\n\/**********************************************************************\n * $Log$\n * Revision 1.12 2005\/06\/28 21:13:43 strk\n * Fixed a bug introduced by LineSegment skip - made LineSegment skip a compile-time optione\n *\n * Revision 1.11 2005\/06\/27 21:58:31 strk\n * Bugfix in DepthSegmentLT as suggested by Graeme Hiebert\n *\n * Revision 1.10 2005\/06\/27 21:24:54 strk\n * Fixed bug just-introduced with optimization.\n *\n * Revision 1.9 2005\/06\/27 21:21:21 strk\n * Reduced Coordinate copies due to LineSegment overuse\n *\n * Revision 1.8 2005\/05\/23 15:13:00 strk\n * Added debugging output\n *\n * Revision 1.7 2005\/05\/20 16:15:41 strk\n * Code cleanups\n *\n * Revision 1.6 2005\/05\/19 10:29:28 strk\n * Removed some CGAlgorithms instances substituting them with direct calls\n * to the static functions. Interfaces accepting CGAlgorithms pointers kept\n * for backward compatibility but modified to make the argument optional.\n * Fixed a small memory leak in OffsetCurveBuilder::getRingCurve.\n * Inlined some smaller functions encountered during bug hunting.\n * Updated Copyright notices in the touched files.\n *\n * Revision 1.5 2004\/07\/08 19:34:49 strk\n * Mirrored JTS interface of CoordinateSequence, factory and\n * default implementations.\n * Added DefaultCoordinateSequenceFactory::instance() function.\n *\n * Revision 1.4 2004\/07\/02 13:28:28 strk\n * Fixed all #include lines to reflect headers layout change.\n * Added client application build tips in README.\n *\n * Revision 1.3 2004\/05\/05 12:29:44 strk\n * memleak fixed in ::getDepth\n *\n * Revision 1.2 2004\/05\/03 22:56:44 strk\n * leaks fixed, exception specification omitted.\n *\n * Revision 1.1 2004\/04\/10 08:40:01 ybychkov\n * \"operation\/buffer\" upgraded to JTS 1.4\n *\n *\n **********************************************************************\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) Alex Nekipelov (alex@nekipelov.net)\n * License: MIT\n *\/\n\n\/\/ See http:\/\/tools.ietf.org\/search\/rfc7049\n\n#include <string.h>\n#include <endian.h>\n#include <stdint.h>\n\n#include \"cborprivate.h\"\n#include \"cborwriter.h\"\n\nstatic const int positiveIntegerStart = 0x00;\nstatic const int negativeIntegerStart = 0x20;\nstatic const int byteStringStart = 0x40;\nstatic const int utf8StringStart = 0x60;\nstatic const int arrayStart = 0x80;\nstatic const int mapStart = 0xa0;\nstatic const int taggedStart = 0xc0;\nstatic const int textBasedDateTime = taggedStart; \/\/ 0xc0\nstatic const int epochBasedDateTime = taggedStart + 1; \/\/ 0xc1\nstatic const int positiveBignum = taggedStart + 2; \/\/ 0xc2\nstatic const int negativeBignum = taggedStart + 3; \/\/ 0xc3\n\/\/...\nstatic const int simpleStart = 0xe0;\nstatic const int halfPrecisionFloat = simpleStart + 0x19; \/\/ 0xf9\nstatic const int singlePrecisionFloat = simpleStart + 0x1a; \/\/ 0xfa\nstatic const int doublePrecisionFloat = simpleStart + 0x1b; \/\/ 0xfb\n\nstatic void cborWriteInternal(std::vector<char> &buff, const CborValue &value);\n\nstatic void writeNull(std::vector<char> &buff)\n{\n const char nil = static_cast<char>(0xf6);\n buff.push_back(nil);\n}\n\nstatic void writeUndefined(std::vector<char> &buff)\n{\n const char undefined = static_cast<char>(0xf7);\n buff.push_back(undefined);\n}\n\nstatic void writeBool(std::vector<char> &buff, const CborValue &value)\n{\n const char trueValue = static_cast<char>(0xf5);\n const char falseValue = static_cast<char>(0xf4);\n\n if( value.toBool() )\n buff.push_back(trueValue);\n else\n buff.push_back(falseValue);\n}\n\nstatic void writeInteger(std::vector<char> &buff, uint64_t value, int type)\n{\n assert(type + 24 < 256);\n\n if( value < 24 )\n {\n uint8_t byte = type + value;\n\n buff.push_back(byte);\n }\n else if( value < 256 )\n {\n uint8_t bytes[2] = {static_cast<uint8_t>(type + 24), static_cast<uint8_t>(value)};\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else if( value < 65536 )\n {\n uint16_t ui16 = htobe16(value);\n uint8_t bytes[3] = {\n static_cast<uint8_t>(type + 25),\n static_cast<uint8_t>(ui16 & 0xff),\n static_cast<uint8_t>((ui16 & 0xff00) >> 8)\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else if( value < 4294967296LU )\n {\n uint32_t ui32 = htobe32(value);\n uint8_t bytes[5] = {\n static_cast<uint8_t>(type + 26),\n static_cast<uint8_t>(ui32 & 0xff),\n static_cast<uint8_t>((ui32 & 0xff00) >> 8),\n static_cast<uint8_t>((ui32 & 0xff0000) >> 16),\n static_cast<uint8_t>((ui32 & 0xff000000) >> 24)\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else\n {\n uint64_t ui64 = htobe64(value);\n uint8_t bytes[9] = {\n static_cast<uint8_t>(type + 27),\n static_cast<uint8_t>(ui64 & 0xff),\n static_cast<uint8_t>((ui64 & 0xff00) >> 8),\n static_cast<uint8_t>((ui64 & 0xff0000) >> 16),\n static_cast<uint8_t>((ui64 & 0xff000000) >> 24),\n static_cast<uint8_t>((ui64 & 0xff00000000UL) >> 32),\n static_cast<uint8_t>((ui64 & 0xff0000000000UL) >> 40),\n static_cast<uint8_t>((ui64 & 0xff000000000000UL) >> 48),\n static_cast<uint8_t>((ui64 & 0xff00000000000000UL) >> 56)\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n}\n\nstatic void writePositiveInteger(std::vector<char> &buff, const CborValue &value)\n{\n uint64_t i = value.toPositiveInteger();\n\n if( i > 0 )\n {\n writeInteger(buff, i, positiveIntegerStart);\n }\n else\n {\n const char zero = 0;\n buff.push_back(zero);\n }\n}\n\nstatic void writeNegativeInteger(std::vector<char> &buff, const CborValue &value)\n{\n uint64_t i = value.toNegativeInteger();\n\n if( i == 0 )\n {\n writeInteger(buff, 0xFFFFFFFFFFFFFFFF, negativeIntegerStart);\n }\n else\n {\n writeInteger(buff, i - 1, negativeIntegerStart);\n }\n}\n\nstatic void writeString(std::vector<char> &buff, const CborValue &value)\n{\n const std::string &s = value.toString();\n\n writeInteger(buff, s.size(), utf8StringStart);\n\n buff.insert(buff.end(), s.begin(), s.end());\n}\n\nstatic void writeByteString(std::vector<char> &buff, const CborValue &value)\n{\n const std::vector<char> &data = value.toByteString();\n\n writeInteger(buff, data.size(), byteStringStart);\n\n buff.insert(buff.end(), data.begin(), data.end());\n}\n\n\nstatic void writeDouble(std::vector<char> &buff, const CborValue &value)\n{\n double dv = value.toDouble();\n float fv = dv;\n\n if( fv == dv )\n {\n \/\/ Warning: code from MessagePack\n\n union {\n float f;\n uint32_t ui32;\n } buf = { fv };\n\n int i32 = buf.ui32;\n if ((i32 & 0x1FFF) == 0)\n {\n do\n {\n \/\/ IEEE 754 half-precision\n uint16_t s16 = (i32 >> 16) & 0x8000;\n int exponent = (i32 >> 23) & 0xff;\n int mantissa = i32 & 0x7fffff;\n\n if (exponent == 0 && mantissa == 0)\n {\n ;\n }\n else if (exponent >= 113 && exponent <= 142)\n {\n \/\/ normalized\n s16 += ((exponent - 112) << 10) + (mantissa >> 13);\n }\n else if (exponent >= 103 && exponent < 113)\n {\n \/\/ denorm, exp16 = 0\n if (mantissa & ((1 << (126 - exponent)) - 1))\n break; \/\/ loss of precision\n s16 += ((mantissa + 0x800000) >> (126 - exponent));\n }\n else if (exponent == 255 && mantissa == 0)\n {\n \/\/ Inf\n s16 += 0x7c00;\n }\n else\n {\n break; \/\/ loss of range\n }\n\n s16 = htobe16(s16);\n\n uint8_t bytes[3] = {\n halfPrecisionFloat,\n static_cast<uint8_t>(s16 & 0xff),\n static_cast<uint8_t>((s16 & 0xff00) >> 8)\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n return;\n } while(0);\n }\n\n\n \/\/ IEEE 754 single-precision\n buf.ui32 = htobe32(buf.ui32);\n\n uint8_t bytes[5] = {\n singlePrecisionFloat,\n static_cast<uint8_t>(buf.ui32 & 0xff),\n static_cast<uint8_t>((buf.ui32 & 0xff00) >> 8),\n static_cast<uint8_t>((buf.ui32 & 0xff0000) >> 16),\n static_cast<uint8_t>((buf.ui32 & 0xff000000) >> 24),\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else if( dv != dv )\n {\n \/\/ NaN\n uint8_t bytes[3] = {halfPrecisionFloat, 0x7e, 0x00};\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else\n {\n \/\/ IEEE 754 double-precision\n union {\n double dv;\n uint64_t ui64;\n } buf = { dv };\n\n buf.ui64 = htobe64(buf.ui64);\n\n uint8_t bytes[9] = {\n doublePrecisionFloat,\n static_cast<uint8_t>(buf.ui64 & 0xff),\n static_cast<uint8_t>((buf.ui64 & 0xff00) >> 8),\n static_cast<uint8_t>((buf.ui64 & 0xff0000) >> 16),\n static_cast<uint8_t>((buf.ui64 & 0xff000000) >> 24),\n static_cast<uint8_t>((buf.ui64 & 0xff00000000UL) >> 32),\n static_cast<uint8_t>((buf.ui64 & 0xff0000000000UL) >> 40),\n static_cast<uint8_t>((buf.ui64 & 0xff000000000000UL) >> 48),\n static_cast<uint8_t>((buf.ui64 & 0xff00000000000000UL) >> 56)\n };\n\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n}\n\nstatic void writeArray(std::vector<char> &buff, const CborValue &value)\n{\n const std::vector<CborValue> &arr = value.toArray();\n\n writeInteger(buff, arr.size(), arrayStart);\n\n for(size_t i = 0; i < arr.size(); ++i)\n {\n cborWriteInternal(buff, arr[i]);\n }\n}\n\nstatic void writeMap(std::vector<char> &buff, const CborValue &value)\n{\n const std::map<CborValue, CborValue> &map = value.toMap();\n std::map<CborValue, CborValue>::const_iterator it = map.begin();\n std::map<CborValue, CborValue>::const_iterator end = map.end();\n\n writeInteger(buff, map.size(), mapStart);\n\n for(; it != end; ++it)\n {\n cborWriteInternal(buff, it->first);\n cborWriteInternal(buff, it->second);\n }\n}\n\nstatic void writeBigInteger(std::vector<char> &buff, const CborValue &value)\n{\n CborValue::BigInteger bigInteger = value.toBigInteger();\n\n bool canBeWrittenAs64BitInteger = bigInteger.bigint.size() < 9;\n canBeWrittenAs64BitInteger = canBeWrittenAs64BitInteger || (\n bigInteger.bigint.size() == 9 &&\n bigInteger.bigint[8] == 0 &&\n bigInteger.bigint[7] == 0 &&\n bigInteger.bigint[6] == 0 &&\n bigInteger.bigint[5] == 0 &&\n bigInteger.bigint[4] == 0 &&\n bigInteger.bigint[3] == 0 &&\n bigInteger.bigint[2] == 0 &&\n bigInteger.bigint[1] == 0 &&\n bigInteger.bigint[0] == 1 &&\n bigInteger.positive == false);\n\n if(canBeWrittenAs64BitInteger)\n {\n \/\/ This number can be written as integer value.\n\n if( bigInteger.bigint.size() == 9 )\n {\n writeInteger(buff, 0xFFFFFFFFFFFFFFFF, negativeIntegerStart);\n }\n else\n {\n uint64_t ui = 0;\n\n for(size_t i = 0; i < bigInteger.bigint.size(); ++i)\n ui = bigInteger.bigint[i] + (ui << 8);\n\n if( bigInteger.positive)\n writeInteger(buff, ui, positiveIntegerStart);\n else\n writeInteger(buff, ui - 1, negativeIntegerStart);\n }\n }\n else\n {\n if( bigInteger.positive )\n {\n buff.push_back(static_cast<char>(positiveBignum));\n }\n else\n {\n buff.push_back(static_cast<char>(negativeBignum));\n\n for(size_t i = bigInteger.bigint.size(); i != 0 ; --i)\n {\n unsigned char c = bigInteger.bigint[i - 1];\n if( c != 0 )\n {\n bigInteger.bigint[i - 1] = c - 1u;\n break;\n }\n else\n {\n bigInteger.bigint[i - 1] = static_cast<char>(0xff);\n }\n }\n }\n\n writeByteString(buff, CborValue(bigInteger.bigint));\n }\n}\n\nstatic void cborWriteInternal(std::vector<char> &buff, const CborValue &value)\n{\n switch(value.type())\n {\n case CborValue::NullType:\n writeNull(buff);\n break;\n case CborValue::UndefinedType:\n writeUndefined(buff);\n break;\n case CborValue::BoolType:\n writeBool(buff, value);\n break;\n case CborValue::NegativeIntegerType:\n writeNegativeInteger(buff, value);\n break;\n case CborValue::PositiveIntegerType:\n writePositiveInteger(buff, value);\n break;\n case CborValue::DoubleType:\n writeDouble(buff, value);\n break;\n case CborValue::StringType:\n writeString(buff, value);\n break;\n case CborValue::ByteStringType:\n writeByteString(buff, value);\n break;\n case CborValue::ArrayType:\n writeArray(buff, value);\n break;\n case CborValue::MapType:\n writeMap(buff, value);\n break;\n case CborValue::BigIntegerType:\n writeBigInteger(buff, value);\n break;\n default:\n assert(false);\n std::cerr << \"Internal error: invalid type\" << std::endl;\n }\n}\n\nstd::vector<char> cborWrite(const CborValue &value)\n{\n std::vector<char> result;\n\n cborWriteInternal(result, value);\n return result;\n}\n\n<commit_msg>Missing header file<commit_after>\/*\n * Copyright (C) Alex Nekipelov (alex@nekipelov.net)\n * License: MIT\n *\/\n\n\/\/ See http:\/\/tools.ietf.org\/search\/rfc7049\n\n#include <string.h>\n#include <endian.h>\n#include <stdint.h>\n#include <iostream>\n\n#include \"cborprivate.h\"\n#include \"cborwriter.h\"\n\nstatic const int positiveIntegerStart = 0x00;\nstatic const int negativeIntegerStart = 0x20;\nstatic const int byteStringStart = 0x40;\nstatic const int utf8StringStart = 0x60;\nstatic const int arrayStart = 0x80;\nstatic const int mapStart = 0xa0;\nstatic const int taggedStart = 0xc0;\nstatic const int textBasedDateTime = taggedStart; \/\/ 0xc0\nstatic const int epochBasedDateTime = taggedStart + 1; \/\/ 0xc1\nstatic const int positiveBignum = taggedStart + 2; \/\/ 0xc2\nstatic const int negativeBignum = taggedStart + 3; \/\/ 0xc3\n\/\/...\nstatic const int simpleStart = 0xe0;\nstatic const int halfPrecisionFloat = simpleStart + 0x19; \/\/ 0xf9\nstatic const int singlePrecisionFloat = simpleStart + 0x1a; \/\/ 0xfa\nstatic const int doublePrecisionFloat = simpleStart + 0x1b; \/\/ 0xfb\n\nstatic void cborWriteInternal(std::vector<char> &buff, const CborValue &value);\n\nstatic void writeNull(std::vector<char> &buff)\n{\n const char nil = static_cast<char>(0xf6);\n buff.push_back(nil);\n}\n\nstatic void writeUndefined(std::vector<char> &buff)\n{\n const char undefined = static_cast<char>(0xf7);\n buff.push_back(undefined);\n}\n\nstatic void writeBool(std::vector<char> &buff, const CborValue &value)\n{\n const char trueValue = static_cast<char>(0xf5);\n const char falseValue = static_cast<char>(0xf4);\n\n if( value.toBool() )\n buff.push_back(trueValue);\n else\n buff.push_back(falseValue);\n}\n\nstatic void writeInteger(std::vector<char> &buff, uint64_t value, int type)\n{\n assert(type + 24 < 256);\n\n if( value < 24 )\n {\n uint8_t byte = type + value;\n\n buff.push_back(byte);\n }\n else if( value < 256 )\n {\n uint8_t bytes[2] = {static_cast<uint8_t>(type + 24), static_cast<uint8_t>(value)};\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else if( value < 65536 )\n {\n uint16_t ui16 = htobe16(value);\n uint8_t bytes[3] = {\n static_cast<uint8_t>(type + 25),\n static_cast<uint8_t>(ui16 & 0xff),\n static_cast<uint8_t>((ui16 & 0xff00) >> 8)\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else if( value < 4294967296LU )\n {\n uint32_t ui32 = htobe32(value);\n uint8_t bytes[5] = {\n static_cast<uint8_t>(type + 26),\n static_cast<uint8_t>(ui32 & 0xff),\n static_cast<uint8_t>((ui32 & 0xff00) >> 8),\n static_cast<uint8_t>((ui32 & 0xff0000) >> 16),\n static_cast<uint8_t>((ui32 & 0xff000000) >> 24)\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else\n {\n uint64_t ui64 = htobe64(value);\n uint8_t bytes[9] = {\n static_cast<uint8_t>(type + 27),\n static_cast<uint8_t>(ui64 & 0xff),\n static_cast<uint8_t>((ui64 & 0xff00) >> 8),\n static_cast<uint8_t>((ui64 & 0xff0000) >> 16),\n static_cast<uint8_t>((ui64 & 0xff000000) >> 24),\n static_cast<uint8_t>((ui64 & 0xff00000000UL) >> 32),\n static_cast<uint8_t>((ui64 & 0xff0000000000UL) >> 40),\n static_cast<uint8_t>((ui64 & 0xff000000000000UL) >> 48),\n static_cast<uint8_t>((ui64 & 0xff00000000000000UL) >> 56)\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n}\n\nstatic void writePositiveInteger(std::vector<char> &buff, const CborValue &value)\n{\n uint64_t i = value.toPositiveInteger();\n\n if( i > 0 )\n {\n writeInteger(buff, i, positiveIntegerStart);\n }\n else\n {\n const char zero = 0;\n buff.push_back(zero);\n }\n}\n\nstatic void writeNegativeInteger(std::vector<char> &buff, const CborValue &value)\n{\n uint64_t i = value.toNegativeInteger();\n\n if( i == 0 )\n {\n writeInteger(buff, 0xFFFFFFFFFFFFFFFF, negativeIntegerStart);\n }\n else\n {\n writeInteger(buff, i - 1, negativeIntegerStart);\n }\n}\n\nstatic void writeString(std::vector<char> &buff, const CborValue &value)\n{\n const std::string &s = value.toString();\n\n writeInteger(buff, s.size(), utf8StringStart);\n\n buff.insert(buff.end(), s.begin(), s.end());\n}\n\nstatic void writeByteString(std::vector<char> &buff, const CborValue &value)\n{\n const std::vector<char> &data = value.toByteString();\n\n writeInteger(buff, data.size(), byteStringStart);\n\n buff.insert(buff.end(), data.begin(), data.end());\n}\n\n\nstatic void writeDouble(std::vector<char> &buff, const CborValue &value)\n{\n double dv = value.toDouble();\n float fv = dv;\n\n if( fv == dv )\n {\n \/\/ Warning: code from MessagePack\n\n union {\n float f;\n uint32_t ui32;\n } buf = { fv };\n\n int i32 = buf.ui32;\n if ((i32 & 0x1FFF) == 0)\n {\n do\n {\n \/\/ IEEE 754 half-precision\n uint16_t s16 = (i32 >> 16) & 0x8000;\n int exponent = (i32 >> 23) & 0xff;\n int mantissa = i32 & 0x7fffff;\n\n if (exponent == 0 && mantissa == 0)\n {\n ;\n }\n else if (exponent >= 113 && exponent <= 142)\n {\n \/\/ normalized\n s16 += ((exponent - 112) << 10) + (mantissa >> 13);\n }\n else if (exponent >= 103 && exponent < 113)\n {\n \/\/ denorm, exp16 = 0\n if (mantissa & ((1 << (126 - exponent)) - 1))\n break; \/\/ loss of precision\n s16 += ((mantissa + 0x800000) >> (126 - exponent));\n }\n else if (exponent == 255 && mantissa == 0)\n {\n \/\/ Inf\n s16 += 0x7c00;\n }\n else\n {\n break; \/\/ loss of range\n }\n\n s16 = htobe16(s16);\n\n uint8_t bytes[3] = {\n halfPrecisionFloat,\n static_cast<uint8_t>(s16 & 0xff),\n static_cast<uint8_t>((s16 & 0xff00) >> 8)\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n return;\n } while(0);\n }\n\n\n \/\/ IEEE 754 single-precision\n buf.ui32 = htobe32(buf.ui32);\n\n uint8_t bytes[5] = {\n singlePrecisionFloat,\n static_cast<uint8_t>(buf.ui32 & 0xff),\n static_cast<uint8_t>((buf.ui32 & 0xff00) >> 8),\n static_cast<uint8_t>((buf.ui32 & 0xff0000) >> 16),\n static_cast<uint8_t>((buf.ui32 & 0xff000000) >> 24),\n };\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else if( dv != dv )\n {\n \/\/ NaN\n uint8_t bytes[3] = {halfPrecisionFloat, 0x7e, 0x00};\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n else\n {\n \/\/ IEEE 754 double-precision\n union {\n double dv;\n uint64_t ui64;\n } buf = { dv };\n\n buf.ui64 = htobe64(buf.ui64);\n\n uint8_t bytes[9] = {\n doublePrecisionFloat,\n static_cast<uint8_t>(buf.ui64 & 0xff),\n static_cast<uint8_t>((buf.ui64 & 0xff00) >> 8),\n static_cast<uint8_t>((buf.ui64 & 0xff0000) >> 16),\n static_cast<uint8_t>((buf.ui64 & 0xff000000) >> 24),\n static_cast<uint8_t>((buf.ui64 & 0xff00000000UL) >> 32),\n static_cast<uint8_t>((buf.ui64 & 0xff0000000000UL) >> 40),\n static_cast<uint8_t>((buf.ui64 & 0xff000000000000UL) >> 48),\n static_cast<uint8_t>((buf.ui64 & 0xff00000000000000UL) >> 56)\n };\n\n\n buff.insert(buff.end(), bytes, bytes + sizeof(bytes));\n }\n}\n\nstatic void writeArray(std::vector<char> &buff, const CborValue &value)\n{\n const std::vector<CborValue> &arr = value.toArray();\n\n writeInteger(buff, arr.size(), arrayStart);\n\n for(size_t i = 0; i < arr.size(); ++i)\n {\n cborWriteInternal(buff, arr[i]);\n }\n}\n\nstatic void writeMap(std::vector<char> &buff, const CborValue &value)\n{\n const std::map<CborValue, CborValue> &map = value.toMap();\n std::map<CborValue, CborValue>::const_iterator it = map.begin();\n std::map<CborValue, CborValue>::const_iterator end = map.end();\n\n writeInteger(buff, map.size(), mapStart);\n\n for(; it != end; ++it)\n {\n cborWriteInternal(buff, it->first);\n cborWriteInternal(buff, it->second);\n }\n}\n\nstatic void writeBigInteger(std::vector<char> &buff, const CborValue &value)\n{\n CborValue::BigInteger bigInteger = value.toBigInteger();\n\n bool canBeWrittenAs64BitInteger = bigInteger.bigint.size() < 9;\n canBeWrittenAs64BitInteger = canBeWrittenAs64BitInteger || (\n bigInteger.bigint.size() == 9 &&\n bigInteger.bigint[8] == 0 &&\n bigInteger.bigint[7] == 0 &&\n bigInteger.bigint[6] == 0 &&\n bigInteger.bigint[5] == 0 &&\n bigInteger.bigint[4] == 0 &&\n bigInteger.bigint[3] == 0 &&\n bigInteger.bigint[2] == 0 &&\n bigInteger.bigint[1] == 0 &&\n bigInteger.bigint[0] == 1 &&\n bigInteger.positive == false);\n\n if(canBeWrittenAs64BitInteger)\n {\n \/\/ This number can be written as integer value.\n\n if( bigInteger.bigint.size() == 9 )\n {\n writeInteger(buff, 0xFFFFFFFFFFFFFFFF, negativeIntegerStart);\n }\n else\n {\n uint64_t ui = 0;\n\n for(size_t i = 0; i < bigInteger.bigint.size(); ++i)\n ui = bigInteger.bigint[i] + (ui << 8);\n\n if( bigInteger.positive)\n writeInteger(buff, ui, positiveIntegerStart);\n else\n writeInteger(buff, ui - 1, negativeIntegerStart);\n }\n }\n else\n {\n if( bigInteger.positive )\n {\n buff.push_back(static_cast<char>(positiveBignum));\n }\n else\n {\n buff.push_back(static_cast<char>(negativeBignum));\n\n for(size_t i = bigInteger.bigint.size(); i != 0 ; --i)\n {\n unsigned char c = bigInteger.bigint[i - 1];\n if( c != 0 )\n {\n bigInteger.bigint[i - 1] = c - 1u;\n break;\n }\n else\n {\n bigInteger.bigint[i - 1] = static_cast<char>(0xff);\n }\n }\n }\n\n writeByteString(buff, CborValue(bigInteger.bigint));\n }\n}\n\nstatic void cborWriteInternal(std::vector<char> &buff, const CborValue &value)\n{\n switch(value.type())\n {\n case CborValue::NullType:\n writeNull(buff);\n break;\n case CborValue::UndefinedType:\n writeUndefined(buff);\n break;\n case CborValue::BoolType:\n writeBool(buff, value);\n break;\n case CborValue::NegativeIntegerType:\n writeNegativeInteger(buff, value);\n break;\n case CborValue::PositiveIntegerType:\n writePositiveInteger(buff, value);\n break;\n case CborValue::DoubleType:\n writeDouble(buff, value);\n break;\n case CborValue::StringType:\n writeString(buff, value);\n break;\n case CborValue::ByteStringType:\n writeByteString(buff, value);\n break;\n case CborValue::ArrayType:\n writeArray(buff, value);\n break;\n case CborValue::MapType:\n writeMap(buff, value);\n break;\n case CborValue::BigIntegerType:\n writeBigInteger(buff, value);\n break;\n default:\n assert(false);\n std::cerr << \"Internal error: invalid type\" << std::endl;\n }\n}\n\nstd::vector<char> cborWrite(const CborValue &value)\n{\n std::vector<char> result;\n\n cborWriteInternal(result, value);\n return result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ file: match.cpp\n\/\/\/ 括号匹配的检验\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <iostream>\n#include <iomanip> \/\/ for std::setw\n#include \"sqstack.h\"\n\nusing namespace std;\n\n\/\/\/\n\/\/\/ 输入一行字符串,检验其中括号是否匹配\n\/\/\/\nbool match(const char *expr)\n{\n \/\/ 匹配括号\n SqStack<char> s;\n InitStack(s);\n for(int i = 0; expr[i]; i++) {\n char c = expr[i];\n if(c=='(' || c=='[' || c=='{') {\n Push(s,c);\n } else if(c==')') {\n if(StackEmpty(s)) {\n cout << expr << endl;\n cout << setw(i+1) << '^' << \" : 多余的 )\" << endl;\n return false;\n }\n char b;\n Pop(s,b);\n if(b!='(') {\n cout << expr << endl;\n cout << setw(i+1) << '^' << \" : 匹配错误 )\" << endl;\n return false;\n }\n } else if(c==']') {\n if(StackEmpty(s)) {\n cout << expr << endl;\n cout << setw(i+1) << '^' << \" : 多余的 ]\" << endl;\n return false;\n }\n char b;\n Pop(s,b);\n if(b!='[') {\n cout << expr << endl;\n cout << setw(i+1) << '^' << \" : 匹配错误 ]\" << endl;\n return false;\n }\n } else if(c=='}') {\n if(StackEmpty(s)) {\n cout << expr << endl;\n cout << setw(i+1) << '^' << \" : 多余的 }\" << endl;\n return false;\n }\n char b;\n Pop(s,b);\n if(b!='{') {\n cout << expr << endl;\n cout << setw(i+1) << '^' << \" : 匹配错误 }\" << endl;\n return false;\n }\n }\n }\n\n \/\/ 若栈空,则匹配成功\n if(StackEmpty(s)) {\n cout << expr << endl;\n cout << \"匹配成功\" << endl;\n return true;\n } else {\n cout << expr << endl;\n cout << \"缺少右括号\" << endl;;\n return false;\n }\n}\n\n\nint main()\n{\n match(\"([]())\");\n match(\"[([][])]\");\n match(\"[([][]]\");\n match(\"[([][])])\");\n match(\"(([][])]\");\n \n return 0;\n}<commit_msg>Update match.cpp<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ file: match.cpp\n\/\/\/ 括号匹配的检验\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <iostream>\n#include \"sqstack.h\"\n\nusing namespace std;\n\n\/\/\/\n\/\/\/ 输入一行字符串,检验其中括号是否匹配\n\/\/\/\nbool match(const char *expr)\n{\n \/\/ 匹配括号\n SqStack<char> s;\n InitStack(s);\n for(int i = 0; expr[i]; i++) {\n char c = expr[i];\n if(c=='(' || c=='[' || c=='{') {\n \/\/ 左括号入栈\n Push(s,c);\n } else if(c==')' || c==']' || c=='}') {\n \/\/ 右括号与栈顶括号进行匹配\n if(StackEmpty(s)) return false; \/\/ 栈空则匹配失败\n \/\/ 出栈\n char b;\n Pop(s,b);\n \/\/ 匹配失败则返回\n if(( c==')' && b!='(' ) ||\n ( c==']' && b!='[' ) ||\n ( c=='{' &&b !='}' ))\n return false;\n }\n }\n\n \/\/ 若栈空,则匹配成功\n return StackEmpty(s);\n}\n\n\nint main()\n{\n const int N = 5;\n const char *expr[N] = {\n \"([]())\",\n \"[([][])]\",\n \"[([][]]\",\n \"[([][])])\",\n \"(([][])]\",\n };\n\n for(int i=0; i<N; i++) {\n cout << expr[i] << \" match = \"\n << boolalpha << match(expr[i]) << endl;\n }\n \n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ManifestDefines.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: mtg $ $Date: 2001-04-27 14:56:05 $\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): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _MANIFEST_DEFINES_HXX\n#define _MANIFEST_DEFINES_HXX\n\n#define ELEMENT_MANIFEST \"manifest:manifest\"\n#define ELEMENT_FILE_ENTRY \"manifest:file-entry\"\n#define ELEMENT_ENCRYPTION_DATA \"manifest:encryption-data\"\n#define ELEMENT_INITIALISATION_VECTOR \"manifest:initialisation-vector\"\n#define ATTRIBUTE_FULL_PATH \"manifest:full-path\"\n#define ATTRIBUTE_MEDIA_TYPE \"manifest:media-type\"\n#define ATTRIBUTE_ALGORITHM \"manifest:algorithm\"\n#define ATTRIBUTE_SALT \"manifest:salt\"\n#define ATTRIBUTE_ITERATION_COUNT \"manifest:iteration-count\"\n#define ATTRIBUTE_CDATA \"CDATA\"\n#define ATTRIBUTE_XMLNS \"xmlns:manifest\"\n#define MANIFEST_NAMESPACE \"http:\/\/openoffice.org\/2001\/manifest\"\n\n#endif\n<commit_msg>Update new defines to reflect new manifest file structure<commit_after>\/*************************************************************************\n *\n * $RCSfile: ManifestDefines.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: mtg $ $Date: 2001-05-08 13:53:48 $\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): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _MANIFEST_DEFINES_HXX\n#define _MANIFEST_DEFINES_HXX\n\n#define ELEMENT_MANIFEST \"manifest:manifest\"\n#define ATTRIBUTE_XMLNS \"xmlns:manifest\"\n#define MANIFEST_NAMESPACE \"http:\/\/openoffice.org\/2001\/manifest\"\n#define MANIFEST_DOCTYPE \"<!DOCTYPE manifest:manifest PUBLIC \\\"-\/\/OpenOffice.org\/\/DTD Manifest 1.0\/\/EN\\\" \\\"Manifest.dtd\\\">\"\n#define ATTRIBUTE_CDATA \"CDATA\"\n\n#define ELEMENT_FILE_ENTRY \"manifest:file-entry\"\n#define ATTRIBUTE_FULL_PATH \"manifest:full-path\"\n#define ATTRIBUTE_MEDIA_TYPE \"manifest:media-type\"\n#define ATTRIBUTE_SIZE \"manifest:size\"\n\n#define ELEMENT_ENCRYPTION_DATA \"manifest:encryption-data\"\n\n#define ELEMENT_ALGORITHM \"manifest:algorithm\"\n#define ATTRIBUTE_ALGORITHM_NAME \"manifest:algorithm-name\"\n#define ATTRIBUTE_INITIALISATION_VECTOR \"manifest:initialisation-vector\"\n\n#define ELEMENT_KEY_DERIVATION \"manifest:key-derivation\"\n#define ATTRIBUTE_KEY_DERIVATION_NAME \"manifest:key-derivation-name\"\n#define ATTRIBUTE_SALT \"manifest:salt\"\n#define ATTRIBUTE_ITERATION_COUNT \"manifest:iteration-count\"\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ literals\n\/\/\n\/\/ Created by Sunil on 2\/21\/17.\n\/\/ Copyright © 2017 Sunil. All rights reserved.\n\/\/\n\n#include <iostream>\n#include <string>\n\n#include \"Length.hpp\"\n\nusing namespace std;\n\nusing LengthDouble = Length<double>;\n\n\/\/ Ref: http:\/\/stackoverflow.com\/questions\/16596864\/c11-operator-with-double-parameter\n\/\/ The declaration of a literal operator shall have a parameter-declaration-clause e\n\/\/ quivalent to one of the following:\n\/\/\n\/\/ const char*\n\/\/ unsigned long long int\n\/\/ long double\n\/\/ char\n\/\/ wchar_t\n\/\/ char16_t\n\/\/ char32_t\n\/\/ const char*, std::size_t\n\/\/ const wchar_t*, std::size_t\n\/\/ const char16_t*, std::size_t\n\/\/ const char32_t*, std::size_t\n\nLengthDouble operator\"\" _km(long double value) {\n return LengthDouble(value, Distance::Kilometers);\n}\n\nLengthDouble operator\"\" _mi(long double value) {\n return LengthDouble(value, Distance::Miles);\n}\n\nint main(int argc, const char * argv[]) {\n auto a = Length<int>(30);\n auto b = Length<int>(10);\n Length<int> total = a + b;\n cout << total.getMiles() << endl;\n \n \/\/ why can't i perform direct + operator\n \/\/ auto t1 = 12.12_km + 23.23_mi;\n \/\/ Because of missing operator+ with move semantics.\n\n auto k = 12.12_km;\n auto l = 23.23_mi;\n auto t1 = k + l;\n cout << t1.getMiles() << endl;\n \n auto t2 = 12.12_km + 23.23_mi;\n cout << Length<>(23.23).getMiles() << endl;\n \n \n return 0;\n}\n<commit_msg>pushed pending changes<commit_after>\/\/\n\/\/ main.cpp\n\/\/ literals\n\/\/\n\/\/ Created by Sunil on 2\/21\/17.\n\/\/ Copyright © 2017 Sunil. All rights reserved.\n\/\/\n\n#include <iostream>\n#include <string>\n\n#include \"Length.hpp\"\n\nusing namespace std;\n\nusing LengthDouble = Length<double>;\n\n\/\/ Ref: http:\/\/stackoverflow.com\/questions\/16596864\/c11-operator-with-double-parameter\n\/\/ The declaration of a literal operator shall have a parameter-declaration-clause e\n\/\/ quivalent to one of the following:\n\/\/\n\/\/ const char*\n\/\/ unsigned long long int\n\/\/ long double\n\/\/ char\n\/\/ wchar_t\n\/\/ char16_t\n\/\/ char32_t\n\/\/ const char*, std::size_t\n\/\/ const wchar_t*, std::size_t\n\/\/ const char16_t*, std::size_t\n\/\/ const char32_t*, std::size_t\n\nLengthDouble operator\"\" _km(long double value) {\n return LengthDouble(value, Distance::Kilometers);\n}\n\nLengthDouble operator\"\" _mi(long double value) {\n return LengthDouble(value, Distance::Miles);\n}\n\nunsigned long long int operator\"\" _b(const char* bits) {\n unsigned acc = 0;\n while(*bits) {\n if (*bits == '1' || *bits == '0') {\n acc = (acc << 1) + (*bits-'0');\n } else {\n throw std::runtime_error(\"Invalid binary digits!\");\n }\n bits++;\n }\n return acc;\n}\n\nvoid increment(int& x) {\n ++x;\n}\n\ntemplate<typename T>\nfunction<void(void)> callback(std::function<void(T&)> f, T&& val) {\n auto k = [&]() {\n f(val);\n };\n return k;\n}\n\nint main(int argc, const char * argv[]) {\n auto a = Length<int>(30);\n auto b = Length<int>(10);\n Length<int> total = a + b;\n cout << total.getMiles() << endl;\n \n \/\/ why can't i perform direct + operator\n \/\/ auto t1 = 12.12_km + 23.23_mi;\n \/\/ Because of missing operator+ with move semantics.\n\n auto k = 12.12_km;\n auto l = 23.23_mi;\n auto t1 = k + l;\n cout << t1.getMiles() << endl;\n \n auto t2 = 12.12_km + 23.23_mi;\n cout << Length<>(23.23).getMiles() << endl;\n \n std::cout << \"Another example of user defined literal\" << endl;\n {\n auto acc = 1111_b;\n \/\/ auto acc2 = 1411_b; \/\/ runtime error\n cout << acc << endl;\n }\n \n std::cout << \"std::ref usage\" << endl;\n {\n int val = 34;\n int& rval = std::ref(val);\n rval = 45;\n cout << rval << \" \" << val << endl;\n \n int i = 9;\n auto f = std::bind(increment, std::ref(i));\n f();\n auto invoke = callback<int&>(increment, i);\n invoke();\n \n cout << i << endl;\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <chartsql\/qtree\/ChartStatementNode.h>\n\nusing namespace stx;\n\nnamespace csql {\n\nChartStatementNode::ChartStatementNode(const ChartStatementNode& other) {\n for (const auto& draw_stmt : other.draw_stmts_) {\n draw_stmts_.emplace_back(draw_stmt->deepCopy());\n }\n\n for (auto& stmt : draw_stmts_) {\n addChild(&stmt);\n }\n}\n\nChartStatementNode::ChartStatementNode(\n Vector<RefPtr<QueryTreeNode>> draw_stmts) :\n draw_stmts_(draw_stmts) {\n for (auto& stmt : draw_stmts_) {\n addChild(&stmt);\n }\n}\n\nRefPtr<QueryTreeNode> ChartStatementNode::deepCopy() const {\n return new ChartStatementNode(*this);\n}\n\n} \/\/ namespace csql\n<commit_msg>ChartStatementNode::toString<commit_after>\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <chartsql\/qtree\/ChartStatementNode.h>\n\nusing namespace stx;\n\nnamespace csql {\n\nChartStatementNode::ChartStatementNode(const ChartStatementNode& other) {\n for (const auto& draw_stmt : other.draw_stmts_) {\n draw_stmts_.emplace_back(draw_stmt->deepCopy());\n }\n\n for (auto& stmt : draw_stmts_) {\n addChild(&stmt);\n }\n}\n\nChartStatementNode::ChartStatementNode(\n Vector<RefPtr<QueryTreeNode>> draw_stmts) :\n draw_stmts_(draw_stmts) {\n for (auto& stmt : draw_stmts_) {\n addChild(&stmt);\n }\n}\n\nRefPtr<QueryTreeNode> ChartStatementNode::deepCopy() const {\n return new ChartStatementNode(*this);\n}\n\nString ChartStatementNode::toString() const {\n String str = \"(chart\";\n\n for (const auto& stmt : draw_stmts_) {\n str += stmt->toString();\n }\n\n str += \")\";\n return str;\n}\n\n} \/\/ namespace csql\n<|endoftext|>"} {"text":"<commit_before>#ifndef CDM_GTEST_HPP\n#define CDM_GTEST_HPP\n\n#include <silicium\/absolute_path.hpp>\n#include <silicium\/run_process.hpp>\n#include <silicium\/sink\/ostream_sink.hpp>\n\nnamespace cdm\n{\n\tstruct gtest_paths\n\t{\n\t\tSi::absolute_path include;\n\t\tSi::absolute_path library;\n\t\tSi::absolute_path library_main;\n\t};\n\n\tinline void copy_recursively(Si::absolute_path const &from, Si::absolute_path const &to)\n\t{\n\t\tauto output = Si::Sink<char, Si::success>::erase(Si::ostream_ref_sink(std::cerr));\n\t\tstd::vector<Si::noexcept_string> arguments = {\"-Rv\", from.c_str(), to.c_str()};\n\t\tif (Si::run_process(\"\/bin\/cp\", arguments, from.to_boost_path(), output) != 0)\n\t\t{\n\t\t\tthrow std::runtime_error(\"cp failed\");\n\t\t}\n\t}\n\n\tinline Si::error_or<gtest_paths> install_gtest(\n\t Si::absolute_path const >est_source,\n\t\tSi::absolute_path const &temporarily_writable,\n\t Si::absolute_path const &install_root)\n\t{\n\t\tSi::absolute_path const cmake_exe = *Si::absolute_path::create(\"\/usr\/bin\/cmake\");\n\t\tauto output = Si::Sink<char, Si::success>::erase(Si::ostream_ref_sink(std::cerr));\n\t\t{\n\t\t\tstd::vector<Si::noexcept_string> arguments;\n\t\t\targuments.push_back(gtest_source.c_str());\n\t\t\targuments.push_back((\"-DCMAKE_INSTALL_PREFIX=\" + install_root.to_boost_path().string()).c_str());\n\t\t\tint rc = Si::run_process(cmake_exe.to_boost_path(), arguments, temporarily_writable.to_boost_path(), output);\n\t\t\tassert(rc == 0);\n\t\t}\n\t\t{\n\t\t\tstd::vector<Si::noexcept_string> arguments;\n\t\t\targuments.push_back(\"--build\");\n\t\t\targuments.push_back(\".\");\n\t\t\tint rc = Si::run_process(cmake_exe.to_boost_path(), arguments, temporarily_writable.to_boost_path(), output);\n\t\t\tassert(rc == 0);\n\t\t}\n\t\tgtest_paths result;\n\t\tresult.include = install_root \/ *Si::path_segment::create(\"include\");\n\t\tauto lib_dir = install_root \/ *Si::path_segment::create(\"lib\");\n\t\tSi::recreate_directories(lib_dir);\n\t\tresult.library = lib_dir \/ *Si::path_segment::create(\"libgtest.a\");\n\t\tresult.library_main = lib_dir \/ *Si::path_segment::create(\"libgtest_main.a\");\n\n\t\tSi::throw_if_error(Si::copy(temporarily_writable \/ *Si::path_segment::create(\"libgtest.a\"), result.library));\n\t\tSi::throw_if_error(Si::copy(temporarily_writable \/ *Si::path_segment::create(\"libgtest_main.a\"), result.library_main));\n\t\tSi::remove_all(result.include).move_value();\n\t\tcopy_recursively(gtest_source \/ *Si::path_segment::create(\"include\") \/ *Si::path_segment::create(\"gtest\"), result.include);\n\n\t\treturn std::move(result);\n\t}\n}\n\n#endif\n<commit_msg>fix GCC release build<commit_after>#ifndef CDM_GTEST_HPP\n#define CDM_GTEST_HPP\n\n#include <silicium\/absolute_path.hpp>\n#include <silicium\/run_process.hpp>\n#include <silicium\/sink\/ostream_sink.hpp>\n\nnamespace cdm\n{\n\tstruct gtest_paths\n\t{\n\t\tSi::absolute_path include;\n\t\tSi::absolute_path library;\n\t\tSi::absolute_path library_main;\n\t};\n\n\tinline void copy_recursively(Si::absolute_path const &from, Si::absolute_path const &to)\n\t{\n\t\tauto output = Si::Sink<char, Si::success>::erase(Si::ostream_ref_sink(std::cerr));\n\t\tstd::vector<Si::noexcept_string> arguments = {\"-Rv\", from.c_str(), to.c_str()};\n\t\tif (Si::run_process(\"\/bin\/cp\", arguments, from.to_boost_path(), output) != 0)\n\t\t{\n\t\t\tthrow std::runtime_error(\"cp failed\");\n\t\t}\n\t}\n\n\tinline Si::error_or<gtest_paths> install_gtest(\n\t\tSi::absolute_path const >est_source,\n\t\tSi::absolute_path const &temporarily_writable,\n\t\tSi::absolute_path const &install_root)\n\t{\n\t\tSi::absolute_path const cmake_exe = *Si::absolute_path::create(\"\/usr\/bin\/cmake\");\n\t\tauto output = Si::Sink<char, Si::success>::erase(Si::ostream_ref_sink(std::cerr));\n\t\t{\n\t\t\tstd::vector<Si::noexcept_string> arguments;\n\t\t\targuments.push_back(gtest_source.c_str());\n\t\t\targuments.push_back((\"-DCMAKE_INSTALL_PREFIX=\" + install_root.to_boost_path().string()).c_str());\n\t\t\tint rc = Si::run_process(cmake_exe.to_boost_path(), arguments, temporarily_writable.to_boost_path(), output);\n\t\t\tif (rc != 0)\n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\"cmake configure failed\");\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tstd::vector<Si::noexcept_string> arguments;\n\t\t\targuments.push_back(\"--build\");\n\t\t\targuments.push_back(\".\");\n\t\t\tint rc = Si::run_process(cmake_exe.to_boost_path(), arguments, temporarily_writable.to_boost_path(), output);\n\t\t\tif (rc != 0)\n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\"cmake build failed\");\n\t\t\t}\n\t\t}\n\t\tgtest_paths result;\n\t\tresult.include = install_root \/ *Si::path_segment::create(\"include\");\n\t\tauto lib_dir = install_root \/ *Si::path_segment::create(\"lib\");\n\t\tSi::recreate_directories(lib_dir);\n\t\tresult.library = lib_dir \/ *Si::path_segment::create(\"libgtest.a\");\n\t\tresult.library_main = lib_dir \/ *Si::path_segment::create(\"libgtest_main.a\");\n\n\t\tSi::throw_if_error(Si::copy(temporarily_writable \/ *Si::path_segment::create(\"libgtest.a\"), result.library));\n\t\tSi::throw_if_error(Si::copy(temporarily_writable \/ *Si::path_segment::create(\"libgtest_main.a\"), result.library_main));\n\t\tSi::remove_all(result.include).move_value();\n\t\tcopy_recursively(gtest_source \/ *Si::path_segment::create(\"include\") \/ *Si::path_segment::create(\"gtest\"), result.include);\n\n\t\treturn std::move(result);\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n#include \"MethodDeclHandler.h\"\n\n#include <regex>\n\nnamespace typegrind\n{\n\n MethodDeclHandler::MethodDeclHandler(clang::Rewriter*& rewriter, MethodMatcher const& matchers)\n : mRewriter(rewriter)\n , mMatchers(matchers)\n {\n }\n\n clang::StringRef MethodDeclHandler::getID() const {\n return \"typegrind\";\n }\n\n void MethodDeclHandler::run(const clang::ast_matchers::MatchFinder::MatchResult &result)\n {\n const clang::CXXMethodDecl* decl = result.Nodes.getNodeAs<clang::CXXMethodDecl>(\"decl\");\n if(!decl) return;\n if (!decl->hasBody()) return;\n\n if(decl->getTemplateSpecializationKind() == clang::TSK_ImplicitInstantiation) return;\n\n \/\/llvm::outs() << decl->getNameInfo().getAsString() << \"\\n\";\n std::string prettyName;\n {\n llvm::raw_string_ostream prettyNameStream(prettyName);\n decl->getCanonicalDecl()->getNameForDiagnostic(prettyNameStream, clang::PrintingPolicy(result.Context->getPrintingPolicy()), true);\n prettyNameStream.flush();\n }\n\n if(!mMatchers.matches(prettyName)) return;\n\n \/\/if(mVisited.find(prettyName) != mVisited.end()) return;\n \/\/mVisited.insert(prettyName);\n\n clang::Stmt *funcBody = decl->getBody();\n mRewriter->InsertTextAfterToken(funcBody->getSourceRange().getBegin(), \" TYPEGRIND_METHOD_ENTER(\\\"\"+prettyName+\"\\\") \");\n\n \/\/ if constructor - initializer lists\n {\n const clang::CXXConstructorDecl* constrDecl = result.Nodes.getNodeAs<clang::CXXConstructorDecl>(\"decl\");\n if(constrDecl)\n {\n for(auto initer: constrDecl->inits())\n {\n if(!initer->isMemberInitializer()) continue;\n mRewriter->InsertTextAfterToken(initer->getLParenLoc(), \"TYPEGRIND_METHOD_INITIALIZER(\\\"\"+prettyName+\"\\\", (\");\n mRewriter->InsertTextBefore(initer->getRParenLoc(), \"))\");\n }\n }\n }\n }\n}\n<commit_msg>method matcher uses the new macro format, with the additional custom name and flags parameter<commit_after>\n#include \"MethodDeclHandler.h\"\n\n#include <regex>\n\nnamespace typegrind\n{\n\n MethodDeclHandler::MethodDeclHandler(clang::Rewriter*& rewriter, MethodMatcher const& matchers)\n : mRewriter(rewriter)\n , mMatchers(matchers)\n {\n }\n\n clang::StringRef MethodDeclHandler::getID() const {\n return \"typegrind\";\n }\n\n void MethodDeclHandler::run(const clang::ast_matchers::MatchFinder::MatchResult &result)\n {\n const clang::CXXMethodDecl* decl = result.Nodes.getNodeAs<clang::CXXMethodDecl>(\"decl\");\n if(!decl) return;\n if (!decl->hasBody()) return;\n\n if(decl->getTemplateSpecializationKind() == clang::TSK_ImplicitInstantiation) return;\n\n \/\/llvm::outs() << decl->getNameInfo().getAsString() << \"\\n\";\n std::string prettyName;\n {\n llvm::raw_string_ostream prettyNameStream(prettyName);\n decl->getCanonicalDecl()->getNameForDiagnostic(prettyNameStream, clang::PrintingPolicy(result.Context->getPrintingPolicy()), true);\n prettyNameStream.flush();\n }\n\n auto match = mMatchers.matches(prettyName);\n if(!match) return;\n\n \/\/if(mVisited.find(prettyName) != mVisited.end()) return;\n \/\/mVisited.insert(prettyName);\n\n clang::Stmt *funcBody = decl->getBody();\n mRewriter->InsertTextAfterToken(funcBody->getSourceRange().getBegin(), \" TYPEGRIND_METHOD_ENTER(\\\"\"+prettyName+\"\\\", \\\"\"+match->custom_name+\"\\\", \"+std::to_string(match->flags)+\") \");\n\n \/\/ if constructor - initializer lists\n {\n const clang::CXXConstructorDecl* constrDecl = result.Nodes.getNodeAs<clang::CXXConstructorDecl>(\"decl\");\n if(constrDecl)\n {\n for(auto initer: constrDecl->inits())\n {\n if(!initer->isMemberInitializer()) continue;\n mRewriter->InsertTextAfterToken(initer->getLParenLoc(), \"TYPEGRIND_METHOD_INITIALIZER(\\\"\"+prettyName+\"\\\", \\\"\"+match->custom_name+\"\\\", \"+std::to_string(match->flags)+\", (\");\n mRewriter->InsertTextBefore(initer->getRParenLoc(), \"))\");\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the clazy static checker.\n\n Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com\n Author: Sérgio Martins <sergio.martins@kdab.com>\n\n Copyright (C) 2015 Sergio Martins <smartins@kde.org>\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 License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"inefficientqlist.h\"\n#include \"Utils.h\"\n#include \"TemplateUtils.h\"\n#include \"checkmanager.h\"\n\n#include <clang\/AST\/Decl.h>\n#include <clang\/AST\/DeclCXX.h>\n#include <clang\/AST\/AST.h>\n#include <clang\/AST\/DeclTemplate.h>\n\nusing namespace clang;\nusing namespace std;\n\nenum IgnoreMode {\n None = 0,\n NonLocalVariable = 1,\n InFunctionWithSameReturnType = 2,\n IsAssignedTooInFunction = 4\n};\n\nInefficientQList::InefficientQList(const std::string &name, const clang::CompilerInstance &ci)\n : CheckBase(name, ci)\n{\n}\n\nstatic bool shouldIgnoreVariable(VarDecl *varDecl, int ignoreMode)\n{\n DeclContext *context = varDecl->getDeclContext();\n FunctionDecl *fDecl = context ? dyn_cast<FunctionDecl>(context) : nullptr;\n\n if (ignoreMode & NonLocalVariable) {\n if (!fDecl)\n return true;\n }\n\n if (ignoreMode & IsAssignedTooInFunction) {\n if (fDecl && fDecl->getReturnType() == varDecl->getType())\n return true;\n }\n\n if (ignoreMode & IsAssignedTooInFunction) {\n if (fDecl) {\n if (Utils::containsAssignment(fDecl->getBody(), varDecl))\n return true;\n }\n }\n\n return false;\n}\n\nvoid InefficientQList::VisitDecl(clang::Decl *decl)\n{\n VarDecl *varDecl = dyn_cast<VarDecl>(decl);\n if (!varDecl)\n return;\n\n QualType type = varDecl->getType();\n const Type *t = type.getTypePtrOrNull();\n if (!t)\n return;\n\n if (shouldIgnoreVariable(varDecl, NonLocalVariable | InFunctionWithSameReturnType | IsAssignedTooInFunction))\n return;\n\n CXXRecordDecl *recordDecl = t->getAsCXXRecordDecl();\n if (!recordDecl || recordDecl->getNameAsString() != \"QList\")\n return;\n\n const std::vector<clang::QualType> types = TemplateUtils::getTemplateArgumentsTypes(recordDecl);\n if (types.empty())\n return;\n QualType qt2 = types[0];\n const int size_of_void = 8 * 8; \/\/ 64 bits\n const int size_of_T = m_ci.getASTContext().getTypeSize(qt2);\n\n if (size_of_T > size_of_void) {\n string s = string(\"Use QVector instead of QList for type with size \" + to_string(size_of_T \/ 8) + \" bytes\");\n emitWarning(decl->getLocStart(), s.c_str());\n }\n}\n\nREGISTER_CHECK_WITH_FLAGS(\"inefficient-qlist\", InefficientQList, CheckLevel3)\n<commit_msg>inneficient-qlist: Don't hardcode 64-bit as the size of a pointer<commit_after>\/*\n This file is part of the clazy static checker.\n\n Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com\n Author: Sérgio Martins <sergio.martins@kdab.com>\n\n Copyright (C) 2015 Sergio Martins <smartins@kde.org>\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 License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"inefficientqlist.h\"\n#include \"Utils.h\"\n#include \"TypeUtils.h\"\n#include \"TemplateUtils.h\"\n#include \"checkmanager.h\"\n\n#include <clang\/AST\/Decl.h>\n#include <clang\/AST\/DeclCXX.h>\n#include <clang\/AST\/AST.h>\n#include <clang\/AST\/DeclTemplate.h>\n\nusing namespace clang;\nusing namespace std;\n\nenum IgnoreMode {\n None = 0,\n NonLocalVariable = 1,\n InFunctionWithSameReturnType = 2,\n IsAssignedTooInFunction = 4\n};\n\nInefficientQList::InefficientQList(const std::string &name, const clang::CompilerInstance &ci)\n : CheckBase(name, ci)\n{\n}\n\nstatic bool shouldIgnoreVariable(VarDecl *varDecl, int ignoreMode)\n{\n DeclContext *context = varDecl->getDeclContext();\n FunctionDecl *fDecl = context ? dyn_cast<FunctionDecl>(context) : nullptr;\n\n if (ignoreMode & NonLocalVariable) {\n if (!fDecl)\n return true;\n }\n\n if (ignoreMode & IsAssignedTooInFunction) {\n if (fDecl && fDecl->getReturnType() == varDecl->getType())\n return true;\n }\n\n if (ignoreMode & IsAssignedTooInFunction) {\n if (fDecl) {\n if (Utils::containsAssignment(fDecl->getBody(), varDecl))\n return true;\n }\n }\n\n return false;\n}\n\nvoid InefficientQList::VisitDecl(clang::Decl *decl)\n{\n VarDecl *varDecl = dyn_cast<VarDecl>(decl);\n if (!varDecl)\n return;\n\n QualType type = varDecl->getType();\n const Type *t = type.getTypePtrOrNull();\n if (!t)\n return;\n\n if (shouldIgnoreVariable(varDecl, NonLocalVariable | InFunctionWithSameReturnType | IsAssignedTooInFunction))\n return;\n\n CXXRecordDecl *recordDecl = t->getAsCXXRecordDecl();\n if (!recordDecl || recordDecl->getNameAsString() != \"QList\")\n return;\n\n const std::vector<clang::QualType> types = TemplateUtils::getTemplateArgumentsTypes(recordDecl);\n if (types.empty())\n return;\n QualType qt2 = types[0];\n if (!qt2.getTypePtrOrNull())\n return;\n\n const int size_of_ptr = TypeUtils::sizeOfPointer(m_ci, qt2); \/\/ in bits\n const int size_of_T = m_ci.getASTContext().getTypeSize(qt2);\n\n if (size_of_T > size_of_ptr) {\n string s = string(\"Use QVector instead of QList for type with size \" + to_string(size_of_T \/ 8) + \" bytes\");\n emitWarning(decl->getLocStart(), s.c_str());\n }\n}\n\nREGISTER_CHECK_WITH_FLAGS(\"inefficient-qlist\", InefficientQList, CheckLevel3)\n<|endoftext|>"} {"text":"<commit_before>\/**\n** Simple ROS Node\n**\/\n#include <ros\/ros.h>\n#include <fake_ar_publisher\/ARMarker.h>\n#include <myworkcell_core\/LocalizePart.h>\n#include <tf\/transform_listener.h>\n\n\nclass Localizer\n{\npublic:\n Localizer(ros::NodeHandle& nh)\n {\n ar_sub_ = nh.subscribe<fake_ar_publisher::ARMarker>(\"ar_pose_marker\", 1, \n &Localizer::visionCallback, this);\n\n server_ = nh.advertiseService(\"localize_part\", &Localizer::localizePart, this);\n }\n\n void visionCallback(const fake_ar_publisher::ARMarkerConstPtr& msg)\n {\n last_msg_ = msg;\n \/\/ROS_INFO_STREAM(last_msg_->pose.pose);\n }\n\n bool localizePart(myworkcell_core::LocalizePart::Request& req,\n myworkcell_core::LocalizePart::Response& res)\n {\n \/\/ Read last message\n fake_ar_publisher::ARMarkerConstPtr p = last_msg_;\n if (!p) return false; \t\n\n tf::Transform cam_to_target;\n tf::poseMsgToTF(p->pose.pose, cam_to_target);\n\n tf::StampedTransform req_to_cam;\n listener_.lookupTransform(req.base_frame, p->header.frame_id, ros::Time(0), req_to_cam);\n \n tf::Transform req_to_target;\n req_to_target = req_to_cam * cam_to_target;\n \n tf::poseTFToMsg(req_to_target, res.pose);\n return true;\n }\n\n ros::Subscriber ar_sub_;\n fake_ar_publisher::ARMarkerConstPtr last_msg_;\n ros::ServiceServer server_;\n tf::TransformListener listener_;\n};\n\n\nint main(int argc, char* argv[])\n{\n \/\/ This must be called before anything else ROS-related\n ros::init(argc, argv, \"vision_node\");\n\n \/\/ Create a ROS node handle\n ros::NodeHandle nh;\n\n \/\/ The Localizer class provides this node's ROS interfaces\n Localizer localizer(nh);\n\n ROS_INFO(\"Vision node starting\");\n\n \/\/ The Localizer class provides this node's ROS interfaces\n \tLocalizer localizer(nh);\n\n \t\/\/ROS_INFO(\"Vision node starting\");\n\n \t\/\/ Don't exit the program.\n \tros::spin();\n}\n\n<commit_msg>Added a library to 4.1 that will make it run properly.<commit_after>\/**\n** Simple ROS Node\n**\/\n#include <ros\/ros.h>\n#include <fake_ar_publisher\/ARMarker.h>\n#include <myworkcell_core\/LocalizePart.h>\n#include <tf\/transform_listener.h>\n#include <moveit\/move_group_interface\/move_group.h>\n\n\n\nclass Localizer\n{\npublic:\n Localizer(ros::NodeHandle& nh)\n {\n ar_sub_ = nh.subscribe<fake_ar_publisher::ARMarker>(\"ar_pose_marker\", 1, \n &Localizer::visionCallback, this);\n\n server_ = nh.advertiseService(\"localize_part\", &Localizer::localizePart, this);\n }\n\n void visionCallback(const fake_ar_publisher::ARMarkerConstPtr& msg)\n {\n last_msg_ = msg;\n \/\/ROS_INFO_STREAM(last_msg_->pose.pose);\n }\n\n bool localizePart(myworkcell_core::LocalizePart::Request& req,\n myworkcell_core::LocalizePart::Response& res)\n {\n \/\/ Read last message\n fake_ar_publisher::ARMarkerConstPtr p = last_msg_;\n if (!p) return false; \t\n\n tf::Transform cam_to_target;\n tf::poseMsgToTF(p->pose.pose, cam_to_target);\n\n tf::StampedTransform req_to_cam;\n listener_.lookupTransform(req.base_frame, p->header.frame_id, ros::Time(0), req_to_cam);\n \n tf::Transform req_to_target;\n req_to_target = req_to_cam * cam_to_target;\n \n tf::poseTFToMsg(req_to_target, res.pose);\n return true;\n }\n\n ros::Subscriber ar_sub_;\n fake_ar_publisher::ARMarkerConstPtr last_msg_;\n ros::ServiceServer server_;\n tf::TransformListener listener_;\n};\n\n\nint main(int argc, char* argv[])\n{\n \/\/ This must be called before anything else ROS-related\n ros::init(argc, argv, \"vision_node\");\n\n \/\/ Create a ROS node handle\n ros::NodeHandle nh;\n\n \/\/ The Localizer class provides this node's ROS interfaces\n Localizer localizer(nh);\n\n ROS_INFO(\"Vision node starting\");\n\n \/\/ Don't exit the program.\n ros::spin();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ 8\/31\/2017\n\/\/ Easy\n#include <iostream>\n\nusing namespace std;\n\nstruct ListNode {\n int val;\n ListNode *next;\n ListNode(int x): val(x), next(NULL) {}\n};\n\nListNode* removedups(ListNode *head) {\n if (head == NULL) return NULL;\n\n for (ListNode *prev = head, *cur = head->next; cur; cur = prev->next) {\n if (prev->val == cur->val) {\n prev->next = cur->next;\n delete cur;\n } else \n prev = cur;\n }\n\n return head;\n}\n\nint main()\n{\n ListNode *n1 = new ListNode(1);\n ListNode *n2 = new ListNode(1);\n ListNode *n3 = new ListNode(2);\n n1->next = n2;\n n2->next = n3;\n\n ListNode *head = removedups(n1);\n\n for (ListNode *n = head; n; n = n->next)\n cout << n->val << \" \";\n \n cout << endl;\n return 0;\n}\n<commit_msg>remove dup from slist-recursive<commit_after>\/\/ remove duplicates from sorted list\n\/\/ 8\/31\/2017\n\/\/ Easy\n#include <iostream>\n\nusing namespace std;\n\nstruct ListNode {\n int val;\n ListNode *next;\n ListNode(int x): val(x), next(NULL) {}\n};\n\nListNode* removedups(ListNode *head) {\n if (head == NULL) return NULL;\n\n for (ListNode *prev = head, *cur = head->next; cur; cur = prev->next) {\n if (prev->val == cur->val) {\n prev->next = cur->next;\n delete cur;\n } else \n prev = cur;\n }\n\n return head;\n}\n\nvoid recur(ListNode *prev, ListNode *cur) {\n if (!cur) return;\n\n if (prev->val == cur->val) {\n prev->next = cur->next;\n delete cur;\n recur(prev, prev->next);\n } else {\n recur(cur, cur->next);\n }\n}\n\n\/\/ recursive\nListNode *removedup2(ListNode *head) {\n if (!head) return NULL;\n\n ListNode dummy(head->val + 1);\n dummy.next = head;\n\n recur(&dummy, head);\n\n return dummy.next;\n}\n\nint main()\n{\n {\n ListNode *n1 = new ListNode(1);\n ListNode *n2 = new ListNode(1);\n ListNode *n3 = new ListNode(2);\n n1->next = n2;\n n2->next = n3;\n\n ListNode *head = removedups(n1);\n\n for (ListNode *n = head; n; n = n->next)\n cout << n->val << \" \";\n\n cout << endl;\n }\n\n {\n ListNode *n1 = new ListNode(1);\n ListNode *n2 = new ListNode(1);\n ListNode *n3 = new ListNode(2);\n n1->next = n2;\n n2->next = n3;\n\n ListNode *head = removedup2(n1);\n\n for (ListNode *n = head; n; n = n->next)\n cout << n->val << \" \";\n\n cout << endl;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"root_system.h\"\r\n#include \"general_utilities.h\"\r\n#include \"ocv_utilities.h\"\r\n#include \"root_image_preprocessor.h\"\r\n#include <opencv2\/opencv.hpp>\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ RootSystem::RootSystem()\r\n\/\/\r\n\/\/ Constructor to specify the image to compute the root system from.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\nRootSystem::RootSystem(Mat image)\r\n{\r\n\t_image = RootImagePreprocessor::prepareForAnalysis(image);\r\n\t_contour = RootImagePreprocessor::getRootContour();\r\n\t_skeleton = RootImagePreprocessor::getSkeleton();\r\n\r\n\t\/\/TODO_DESIGN: Calling getRootContour() is ugly as it depends on prepareForAnalysis to be called first. We may want to precompute the contours,\r\n\t\/\/ and pull some of the functionality from RootImagePreprocessor into OcvUtilities. For now, just leave it as is in order to finish first pass of trait computation.\r\n\r\n\t\/\/TODO_PERF: We may want to consider only iterating through the image once, and computing all of these in one pass. This would speed things up significantly\r\n\r\n\t\/\/TODO_ROBUST: Consider a set of defensive checks here to verify _image and _contour were constructed properly.\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ RootSystem::getImage()\r\n\/\/\r\n\/\/ Returns the image that we are operating on.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ncv::Mat RootSystem::getImage()\r\n{\r\n\treturn _image.clone();\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ bushiness()\r\n\/\/\r\n\/\/ Units: n \/ n\r\n\/\/\r\n\/\/ The ratio of the maximum to the median number of roots.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::bushiness()\r\n{\r\n\treturn maximumNumberOfRoots() \/ medianNumberOfRoots();\t\/\/TODO_ROBUST: Check for division by zero here and below.\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ convexArea()\r\n\/\/\r\n\/\/ Units: cm^2\r\n\/\/\r\n\/\/ The area of the convex hull that encompasses the root.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::convexArea()\r\n{\r\n\tvector<Point> hull;\r\n\tconvexHull(_contour, hull);\r\n\r\n\t\/\/TODO_ROBUST: Make a debugging flag to write out an image if the flag is turned on?\r\n\t\/\/drawContours(_image, vector<vector<Point>>(1, hull), 0, Scalar(255));\t\/\/ drawContours expects a vector of vectors, so we need to construct the expected type from our largest hull contour.\r\n\r\n\treturn contourArea(hull);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkDepth()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The number of pixels in the vertical direction from the upper-most network\r\n\/\/ pixel to the lower-most network pixel.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkDepth()\r\n{\r\n\tif (_contour.size() < 1)\r\n\t\treturn -1;\r\n\r\n\tint minY = _contour[0].y;\r\n\tint maxY = _contour[0].y;\r\n\r\n\tfor each (auto point in _contour)\r\n\t{\r\n\t\tif (point.y > maxY)\r\n\t\t\tmaxY = point.y;\r\n\t\tif (point.y < minY)\r\n\t\t\tminY = point.y;\r\n\t}\r\n\r\n\treturn maxY - minY;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkLengthDistribution()\r\n\/\/\r\n\/\/ Units: n \/ n\r\n\/\/\r\n\/\/ The fraction of network pixels found in the lower 2\/3 of the network. The\r\n\/\/ lower 2\/3 of the network is defined based on the network depth.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkLengthDistribution()\r\n{\r\n\tint lowerTwoThirdsStart = static_cast<int>(round(0.33 * networkDepth()));\t\/\/TODO: Network depth computation makes sense here only if the top of the image is where the network starts (true in current sample image case)\r\n\r\n\tdouble lowerTwoThirdsArea = 0;\r\n\r\n\tfor (int row = lowerTwoThirdsStart; row <= networkDepth(); ++row)\r\n\t{\r\n\t\tfor (int col = 0; col < _image.size().width; ++col)\r\n\t\t{\r\n\t\t\tif (OcvUtilities::isPointWhite(_image, Point(col, row)))\r\n\t\t\t{\r\n\t\t\t\tlowerTwoThirdsArea++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/TODO_ROBUST: Allow debugging image to be output.\r\n\t\/\/for (int col = 0; col < _image.size().width; ++col)\r\n\t\/\/{\r\n\t\/\/\t_image.at<uchar>(Point(col, lowerTwoThirdsStart)) = 255;\r\n\t\/\/\timshow(\"Lower Two-Thirds Line\", _image);\r\n\t\/\/}\r\n\r\n\treturn lowerTwoThirdsArea \/ networkArea();\t\/\/TODO_PERF: Don't iterate through 2\/3 of the image twice to compute this.\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ majorAxis()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The length of the major axis of the best fitting ellipse to the network.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::majorAxis()\r\n{\r\n\tRotatedRect bestFittingEllipse = fitEllipse(_contour);\r\n\r\n\treturn round(max(bestFittingEllipse.size.width, bestFittingEllipse.size.height));\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkWidth()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The number of pixels in the horizontal direction from the left-most network\r\n\/\/ pixel to the right-most network pixel. Only pixels lying in the same row are\r\n\/\/ considered.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkWidth()\r\n{\r\n\tif (_contour.size() < 1)\r\n\t\treturn -1;\r\n\r\n\tint minX = _contour[0].x;\r\n\tint maxX = _contour[0].x;\r\n\r\n\tfor each (auto point in _contour)\r\n\t{\r\n\t\tif (point.x > maxX)\r\n\t\t\tmaxX = point.x;\r\n\t\tif (point.x < minX)\r\n\t\t\tminX = point.x;\r\n\t}\r\n\r\n\treturn maxX - minX;\t\/\/TODO: Note that this does not assume that pixels are in the same row as specified in the comment above. We should confirm that this is the desired behavior.\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ maximumNumberOfRoots()\r\n\/\/\r\n\/\/ Units: n\r\n\/\/\r\n\/\/ After sorting the number of roots crossing a horizontal line from smallest to\r\n\/\/ largest, the maximum number is considered to be the 84th-percentile value\r\n\/\/ (one standard deviation).\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::maximumNumberOfRoots()\r\n{\r\n\tconst double PERCENTILE = 0.84;\r\n\r\n\tvector<int> numberOfRootsInRow = computeNumberOfRootsInRows();\r\n\r\n\tsort(numberOfRootsInRow.begin(), numberOfRootsInRow.end());\r\n\r\n\tint maximumIndex = static_cast<int>(round(PERCENTILE * numberOfRootsInRow.size()));\r\n\r\n\treturn numberOfRootsInRow[maximumIndex];\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ averageRootWidth()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The mean value of the root width estimation computed for all pixels of the\r\n\/\/ medial axis of the entire root system. This trait corresponds to diameter\r\n\/\/ of a root.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::averageRootWidth()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ medianNumberOfRoots()\r\n\/\/\r\n\/\/ Units: n\r\n\/\/\r\n\/\/ The result of a vertical line sweep in which the number of roots that crossed\r\n\/\/ a horizontal line was estimated, and then the median of all values for the\r\n\/\/ extent of the network was calculated.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::medianNumberOfRoots()\r\n{\r\n\treturn GeneralUtilities::computeMedian(computeNumberOfRootsInRows());\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ minorAxis()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The length of the minor axis of the best fitting ellipse to the network.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::minorAxis()\r\n{\r\n\tRotatedRect bestFittingEllipse = fitEllipse(_contour);\t\/\/TODO_PERF: Compute the best fitting ellipse only once.\r\n\r\n\treturn round(min(bestFittingEllipse.size.width, bestFittingEllipse.size.height));\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkArea()\r\n\/\/\r\n\/\/ Units: cm^2\r\n\/\/\r\n\/\/ The number of network pixels in the image.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkArea()\r\n{\r\n\tdouble networkArea = 0;\r\n\r\n\tMatIterator_<uchar> it, end;\r\n\tfor (it = _image.begin<uchar>(), end = _image.end<uchar>(); it != end; ++it)\r\n\t{\r\n\t\tif (*it == RootImagePreprocessor::getMaximumThresholdValue())\r\n\t\t{\r\n\t\t\tnetworkArea++;\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/TODO_DESIGN: Consider using countNonZero(_image) here, although may not be useful for images that have different threshold settings.\r\n\r\n\treturn networkArea;\t\/\/TODO_DESIGN: Is there a way we can use the contour rather than the entire image here?\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ perimeter()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The total number of network pixels connected to a background pixel (using a\r\n\/\/ 8-nearest neighbor neighborhood).\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::perimeter()\r\n{\r\n\tdouble perimeter = 0;\r\n\r\n\tfor (int row = 0; row < _image.size().height; ++row)\r\n\t{\r\n\t\tfor (int col = 0; col < _image.size().width; ++col)\r\n\t\t{\r\n\t\t\tif (OcvUtilities::isPointWhite(_image, Point(col, row)))\r\n\t\t\t{\r\n\t\t\t\tvector<Point> neighbors = OcvUtilities::getNeighboringPixels(_image, Point(col, row));\r\n\r\n\t\t\t\tbool allWhiteNeighbors = true;\r\n\t\t\t\t\r\n\t\t\t\tfor (vector<Point>::iterator it = neighbors.begin(); it != neighbors.end(); ++it)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (!OcvUtilities::isPointWhite(_image, *it))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tallWhiteNeighbors = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (allWhiteNeighbors)\r\n\t\t\t\t\tperimeter++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn perimeter;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ aspectRatio()\r\n\/\/\r\n\/\/ Units: cm\/cm\r\n\/\/\r\n\/\/ The ratio of the minor to the major axis of best fitting ellipse.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::aspectRatio()\r\n{\r\n\treturn minorAxis() \/ majorAxis();\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkSolidity()\r\n\/\/\r\n\/\/ Units: cm^2\/cm^2\r\n\/\/\r\n\/\/ The total network area divided by the network convex area.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkSolidity()\r\n{\r\n\treturn networkArea() \/ convexArea();\t\/\/TODO: networkArea is computed based on pixels, convexArea is computed based on the contour. This ratio might not be apples to apples...\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ specificRootLength()\r\n\/\/\r\n\/\/ Units: cm\/cm^3\r\n\/\/\r\n\/\/ Total network length divided by network volume. Volume is estimated as the sum\r\n\/\/ of cross-sectional areas for all pixels of the medial axis of the root system.\r\n\/\/ The total root length is the number of pixels in the medial axis of the root\r\n\/\/ system.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::specificRootLength()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkSurfaceArea()\r\n\/\/\r\n\/\/ Units: cm^2\r\n\/\/\r\n\/\/ The sum of the local surface area at each pixel of the network skeleton, as\r\n\/\/ approximated by a tubular shape whose radius is estimated from the image.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkSurfaceArea()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkLength()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The total number of pixels in the network skeleton.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkLength()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkVolume()\r\n\/\/\r\n\/\/ Units: cm^3\r\n\/\/\r\n\/\/ The sum of the local volume at each pixel of the network skeleton, as\r\n\/\/ approximated by a tubular shape whose radius is estimated from the image.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkVolume()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkWidthToDepthRatio()\r\n\/\/\r\n\/\/ Units: cm\/cm\r\n\/\/\r\n\/\/ The value of network width divided by the value of network depth.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkWidthToDepthRatio()\r\n{\r\n\treturn networkWidth() \/ networkDepth();\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ computeNumberOfRootsInRow()\r\n\/\/\r\n\/\/ Returns a list of integers corresponding to the number of roots that were found\r\n\/\/ in each row of the image. A root can be considered to be \"found\" when we find\r\n\/\/ a white pixel when the previous pixel was black.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\nvector<int> RootSystem::computeNumberOfRootsInRows(bool includeZeroes)\t\/\/TODO_PERF: Compute this only once, rather than once for both maxmimum and minimum.\r\n{\r\n\tvector<int> numberOfRootsInRows(_image.size().height);\r\n\r\n\tfor (int row = 0; row < _image.size().height; ++row)\r\n\t{\r\n\t\tfor (int col = 0; col < _image.size().width; ++col)\r\n\t\t{\r\n\t\t\t\/\/ If the current point is white, and the previous point was black, then we have found a new root.\r\n\t\t\tif (OcvUtilities::isPointWhite(_image, Point(col, row)) && !OcvUtilities::isPointWhite(_image, Point(col - 1, row)))\r\n\t\t\t{\r\n\t\t\t\tnumberOfRootsInRows[row]++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (numberOfRootsInRows[row] == 0)\t\/\/ It should be safe to assume that once we have hit a row with no roots, there will be no more roots below that row.\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\tif (!includeZeroes)\r\n\t{\r\n\t\t\/\/ Remove all zeroes from the list.\r\n\t\tnumberOfRootsInRows.erase(\r\n\t\t\tremove_if(numberOfRootsInRows.begin(), numberOfRootsInRows.end(), [](const int numberOfRootsInRow) { return numberOfRootsInRow == 0; } ),\r\n\t\t\tnumberOfRootsInRows.end()\r\n\t\t\t);\r\n\t}\r\n\r\n\treturn numberOfRootsInRows;\r\n}\r\n<commit_msg>Compute network length<commit_after>#include \"root_system.h\"\r\n#include \"general_utilities.h\"\r\n#include \"ocv_utilities.h\"\r\n#include \"root_image_preprocessor.h\"\r\n#include <opencv2\/opencv.hpp>\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ RootSystem::RootSystem()\r\n\/\/\r\n\/\/ Constructor to specify the image to compute the root system from.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\nRootSystem::RootSystem(Mat image)\r\n{\r\n\t_image = RootImagePreprocessor::prepareForAnalysis(image);\r\n\t_contour = RootImagePreprocessor::getRootContour();\r\n\t_skeleton = RootImagePreprocessor::getSkeleton();\r\n\r\n\t\/\/TODO_DESIGN: Calling getRootContour() is ugly as it depends on prepareForAnalysis to be called first. We may want to precompute the contours,\r\n\t\/\/ and pull some of the functionality from RootImagePreprocessor into OcvUtilities. For now, just leave it as is in order to finish first pass of trait computation.\r\n\r\n\t\/\/TODO_PERF: We may want to consider only iterating through the image once, and computing all of these in one pass. This would speed things up significantly\r\n\r\n\t\/\/TODO_ROBUST: Consider a set of defensive checks here to verify _image and _contour were constructed properly.\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ RootSystem::getImage()\r\n\/\/\r\n\/\/ Returns the image that we are operating on.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ncv::Mat RootSystem::getImage()\r\n{\r\n\treturn _image.clone();\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ bushiness()\r\n\/\/\r\n\/\/ Units: n \/ n\r\n\/\/\r\n\/\/ The ratio of the maximum to the median number of roots.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::bushiness()\r\n{\r\n\treturn maximumNumberOfRoots() \/ medianNumberOfRoots();\t\/\/TODO_ROBUST: Check for division by zero here and below.\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ convexArea()\r\n\/\/\r\n\/\/ Units: cm^2\r\n\/\/\r\n\/\/ The area of the convex hull that encompasses the root.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::convexArea()\r\n{\r\n\tvector<Point> hull;\r\n\tconvexHull(_contour, hull);\r\n\r\n\t\/\/TODO_ROBUST: Make a debugging flag to write out an image if the flag is turned on?\r\n\t\/\/drawContours(_image, vector<vector<Point>>(1, hull), 0, Scalar(255));\t\/\/ drawContours expects a vector of vectors, so we need to construct the expected type from our largest hull contour.\r\n\r\n\treturn contourArea(hull);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkDepth()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The number of pixels in the vertical direction from the upper-most network\r\n\/\/ pixel to the lower-most network pixel.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkDepth()\r\n{\r\n\tif (_contour.size() < 1)\r\n\t\treturn -1;\r\n\r\n\tint minY = _contour[0].y;\r\n\tint maxY = _contour[0].y;\r\n\r\n\tfor each (auto point in _contour)\r\n\t{\r\n\t\tif (point.y > maxY)\r\n\t\t\tmaxY = point.y;\r\n\t\tif (point.y < minY)\r\n\t\t\tminY = point.y;\r\n\t}\r\n\r\n\treturn maxY - minY;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkLengthDistribution()\r\n\/\/\r\n\/\/ Units: n \/ n\r\n\/\/\r\n\/\/ The fraction of network pixels found in the lower 2\/3 of the network. The\r\n\/\/ lower 2\/3 of the network is defined based on the network depth.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkLengthDistribution()\r\n{\r\n\tint lowerTwoThirdsStart = static_cast<int>(round(0.33 * networkDepth()));\t\/\/TODO: Network depth computation makes sense here only if the top of the image is where the network starts (true in current sample image case)\r\n\r\n\tdouble lowerTwoThirdsArea = 0;\r\n\r\n\tfor (int row = lowerTwoThirdsStart; row <= networkDepth(); ++row)\r\n\t{\r\n\t\tfor (int col = 0; col < _image.size().width; ++col)\r\n\t\t{\r\n\t\t\tif (OcvUtilities::isPointWhite(_image, Point(col, row)))\r\n\t\t\t{\r\n\t\t\t\tlowerTwoThirdsArea++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/TODO_ROBUST: Allow debugging image to be output.\r\n\t\/\/for (int col = 0; col < _image.size().width; ++col)\r\n\t\/\/{\r\n\t\/\/\t_image.at<uchar>(Point(col, lowerTwoThirdsStart)) = 255;\r\n\t\/\/\timshow(\"Lower Two-Thirds Line\", _image);\r\n\t\/\/}\r\n\r\n\treturn lowerTwoThirdsArea \/ networkArea();\t\/\/TODO_PERF: Don't iterate through 2\/3 of the image twice to compute this.\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ majorAxis()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The length of the major axis of the best fitting ellipse to the network.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::majorAxis()\r\n{\r\n\tRotatedRect bestFittingEllipse = fitEllipse(_contour);\r\n\r\n\treturn round(max(bestFittingEllipse.size.width, bestFittingEllipse.size.height));\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkWidth()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The number of pixels in the horizontal direction from the left-most network\r\n\/\/ pixel to the right-most network pixel. Only pixels lying in the same row are\r\n\/\/ considered.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkWidth()\r\n{\r\n\tif (_contour.size() < 1)\r\n\t\treturn -1;\r\n\r\n\tint minX = _contour[0].x;\r\n\tint maxX = _contour[0].x;\r\n\r\n\tfor each (auto point in _contour)\r\n\t{\r\n\t\tif (point.x > maxX)\r\n\t\t\tmaxX = point.x;\r\n\t\tif (point.x < minX)\r\n\t\t\tminX = point.x;\r\n\t}\r\n\r\n\treturn maxX - minX;\t\/\/TODO: Note that this does not assume that pixels are in the same row as specified in the comment above. We should confirm that this is the desired behavior.\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ maximumNumberOfRoots()\r\n\/\/\r\n\/\/ Units: n\r\n\/\/\r\n\/\/ After sorting the number of roots crossing a horizontal line from smallest to\r\n\/\/ largest, the maximum number is considered to be the 84th-percentile value\r\n\/\/ (one standard deviation).\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::maximumNumberOfRoots()\r\n{\r\n\tconst double PERCENTILE = 0.84;\r\n\r\n\tvector<int> numberOfRootsInRow = computeNumberOfRootsInRows();\r\n\r\n\tsort(numberOfRootsInRow.begin(), numberOfRootsInRow.end());\r\n\r\n\tint maximumIndex = static_cast<int>(round(PERCENTILE * numberOfRootsInRow.size()));\r\n\r\n\treturn numberOfRootsInRow[maximumIndex];\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ averageRootWidth()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The mean value of the root width estimation computed for all pixels of the\r\n\/\/ medial axis of the entire root system. This trait corresponds to diameter\r\n\/\/ of a root.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::averageRootWidth()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ medianNumberOfRoots()\r\n\/\/\r\n\/\/ Units: n\r\n\/\/\r\n\/\/ The result of a vertical line sweep in which the number of roots that crossed\r\n\/\/ a horizontal line was estimated, and then the median of all values for the\r\n\/\/ extent of the network was calculated.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::medianNumberOfRoots()\r\n{\r\n\treturn GeneralUtilities::computeMedian(computeNumberOfRootsInRows());\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ minorAxis()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The length of the minor axis of the best fitting ellipse to the network.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::minorAxis()\r\n{\r\n\tRotatedRect bestFittingEllipse = fitEllipse(_contour);\t\/\/TODO_PERF: Compute the best fitting ellipse only once.\r\n\r\n\treturn round(min(bestFittingEllipse.size.width, bestFittingEllipse.size.height));\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkArea()\r\n\/\/\r\n\/\/ Units: cm^2\r\n\/\/\r\n\/\/ The number of network pixels in the image.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkArea()\r\n{\r\n\treturn countNonZero(_image);\t\/\/TODO_DESIGN: Is there a way we can use the contour rather than the entire image here?\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ perimeter()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The total number of network pixels connected to a background pixel (using a\r\n\/\/ 8-nearest neighbor neighborhood).\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::perimeter()\r\n{\r\n\tdouble perimeter = 0;\r\n\r\n\tfor (int row = 0; row < _image.size().height; ++row)\r\n\t{\r\n\t\tfor (int col = 0; col < _image.size().width; ++col)\r\n\t\t{\r\n\t\t\tif (OcvUtilities::isPointWhite(_image, Point(col, row)))\r\n\t\t\t{\r\n\t\t\t\tvector<Point> neighbors = OcvUtilities::getNeighboringPixels(_image, Point(col, row));\r\n\r\n\t\t\t\tbool allWhiteNeighbors = true;\r\n\t\t\t\t\r\n\t\t\t\tfor (vector<Point>::iterator it = neighbors.begin(); it != neighbors.end(); ++it)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (!OcvUtilities::isPointWhite(_image, *it))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tallWhiteNeighbors = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (allWhiteNeighbors)\r\n\t\t\t\t\tperimeter++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn perimeter;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ aspectRatio()\r\n\/\/\r\n\/\/ Units: cm\/cm\r\n\/\/\r\n\/\/ The ratio of the minor to the major axis of best fitting ellipse.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::aspectRatio()\r\n{\r\n\treturn minorAxis() \/ majorAxis();\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkSolidity()\r\n\/\/\r\n\/\/ Units: cm^2\/cm^2\r\n\/\/\r\n\/\/ The total network area divided by the network convex area.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkSolidity()\r\n{\r\n\treturn networkArea() \/ convexArea();\t\/\/TODO: networkArea is computed based on pixels, convexArea is computed based on the contour. This ratio might not be apples to apples...\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ specificRootLength()\r\n\/\/\r\n\/\/ Units: cm\/cm^3\r\n\/\/\r\n\/\/ Total network length divided by network volume. Volume is estimated as the sum\r\n\/\/ of cross-sectional areas for all pixels of the medial axis of the root system.\r\n\/\/ The total root length is the number of pixels in the medial axis of the root\r\n\/\/ system.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::specificRootLength()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkSurfaceArea()\r\n\/\/\r\n\/\/ Units: cm^2\r\n\/\/\r\n\/\/ The sum of the local surface area at each pixel of the network skeleton, as\r\n\/\/ approximated by a tubular shape whose radius is estimated from the image.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkSurfaceArea()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkLength()\r\n\/\/\r\n\/\/ Units: cm\r\n\/\/\r\n\/\/ The total number of pixels in the network skeleton.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkLength()\r\n{\r\n\treturn countNonZero(_skeleton);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkVolume()\r\n\/\/\r\n\/\/ Units: cm^3\r\n\/\/\r\n\/\/ The sum of the local volume at each pixel of the network skeleton, as\r\n\/\/ approximated by a tubular shape whose radius is estimated from the image.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkVolume()\r\n{\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ networkWidthToDepthRatio()\r\n\/\/\r\n\/\/ Units: cm\/cm\r\n\/\/\r\n\/\/ The value of network width divided by the value of network depth.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\ndouble RootSystem::networkWidthToDepthRatio()\r\n{\r\n\treturn networkWidth() \/ networkDepth();\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ computeNumberOfRootsInRow()\r\n\/\/\r\n\/\/ Returns a list of integers corresponding to the number of roots that were found\r\n\/\/ in each row of the image. A root can be considered to be \"found\" when we find\r\n\/\/ a white pixel when the previous pixel was black.\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\nvector<int> RootSystem::computeNumberOfRootsInRows(bool includeZeroes)\t\/\/TODO_PERF: Compute this only once, rather than once for both maxmimum and minimum.\r\n{\r\n\tvector<int> numberOfRootsInRows(_image.size().height);\r\n\r\n\tfor (int row = 0; row < _image.size().height; ++row)\r\n\t{\r\n\t\tfor (int col = 0; col < _image.size().width; ++col)\r\n\t\t{\r\n\t\t\t\/\/ If the current point is white, and the previous point was black, then we have found a new root.\r\n\t\t\tif (OcvUtilities::isPointWhite(_image, Point(col, row)) && !OcvUtilities::isPointWhite(_image, Point(col - 1, row)))\r\n\t\t\t{\r\n\t\t\t\tnumberOfRootsInRows[row]++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (numberOfRootsInRows[row] == 0)\t\/\/ It should be safe to assume that once we have hit a row with no roots, there will be no more roots below that row.\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\tif (!includeZeroes)\r\n\t{\r\n\t\t\/\/ Remove all zeroes from the list.\r\n\t\tnumberOfRootsInRows.erase(\r\n\t\t\tremove_if(numberOfRootsInRows.begin(), numberOfRootsInRows.end(), [](const int numberOfRootsInRow) { return numberOfRootsInRow == 0; } ),\r\n\t\t\tnumberOfRootsInRows.end()\r\n\t\t\t);\r\n\t}\r\n\r\n\treturn numberOfRootsInRows;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SessionAsyncRProcess.cpp\n *\n * Copyright (C) 2009-19 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <session\/prefs\/UserPrefs.hpp>\n#include <session\/SessionConsoleProcess.hpp>\n#include <session\/SessionModuleContext.hpp>\n\n#include <core\/system\/Environment.hpp>\n#include <core\/system\/Process.hpp>\n\n#include <r\/RExec.hpp>\n\n#include <r\/session\/RSessionUtils.hpp>\n\n#include <session\/SessionAsyncRProcess.hpp>\n\nnamespace rstudio {\nnamespace session {\nnamespace async_r {\n\nAsyncRProcess::AsyncRProcess():\n isRunning_(false),\n terminationRequested_(false)\n{\n}\n\nvoid AsyncRProcess::start(const char* rCommand,\n core::system::Options environment,\n const core::FilePath& workingDir,\n AsyncRProcessOptions rOptions,\n std::vector<core::FilePath> rSourceFiles,\n const std::string& input)\n{\n \/\/ file paths to be used for IPC (if any) requested by child process\n ipcRequests_ = module_context::tempFile(\"rstudio-ipc-requests-\", \"rds\");\n ipcResponse_ = module_context::tempFile(\"rstudio-ipc-response-\", \"rds\");\n sharedSecret_ = core::system::generateUuid();\n \n \/\/ R binary\n core::FilePath rProgramPath;\n core::Error error = module_context::rScriptPath(&rProgramPath);\n if (error)\n {\n LOG_ERROR(error);\n onCompleted(EXIT_FAILURE);\n return;\n }\n \n \/\/ core R files for augmented async processes\n if (rOptions & R_PROCESS_AUGMENTED)\n {\n \/\/ R files we wish to source to provide functionality to async process\n const core::FilePath modulesPath =\n session::options().modulesRSourcePath();\n \n const core::FilePath rPath =\n session::options().coreRSourcePath();\n \n const core::FilePath rTools = rPath.childPath(\"Tools.R\");\n \n \/\/ insert at begin as Tools.R needs to be sourced first\n rSourceFiles.insert(rSourceFiles.begin(), rTools);\n }\n\n \/\/ args\n std::vector<std::string> args;\n args.push_back(\"--slave\");\n if (rOptions & R_PROCESS_VANILLA)\n args.push_back(\"--vanilla\");\n if (rOptions & R_PROCESS_NO_RDATA)\n {\n args.push_back(\"--no-save\");\n args.push_back(\"--no-restore\");\n }\n\n \/\/ for windows we need to forward setInternet2\n#ifdef _WIN32\n if (!r::session::utils::isR3_3() && prefs::userPrefs().useInternet2())\n args.push_back(\"--internet2\");\n#endif\n\n args.push_back(\"-e\");\n \n bool needsQuote = false;\n\n \/\/ On Windows, we turn the vector of strings into a single\n \/\/ string to send over the command line, so we must ensure\n \/\/ that the arguments following '-e' are quoted, so that\n \/\/ they are all interpretted as a single argument (rather\n \/\/ than multiple arguments) to '-e'.\n\n#ifdef _WIN32\n needsQuote = strlen(rCommand) > 0 && rCommand[0] != '\"';\n#endif\n\n std::stringstream command;\n if (needsQuote)\n command << \"\\\"\";\n\n std::string escapedCommand = rCommand;\n\n if (needsQuote)\n boost::algorithm::replace_all(escapedCommand, \"\\\"\", \"\\\\\\\"\");\n \n if (rSourceFiles.size())\n {\n \/\/ add in the r source files requested\n for (std::vector<core::FilePath>::const_iterator it = rSourceFiles.begin();\n it != rSourceFiles.end();\n ++it)\n {\n command << \"source('\" << it->absolutePath() << \"');\";\n }\n \n command << escapedCommand;\n }\n else\n {\n command << escapedCommand;\n }\n\n if (needsQuote)\n command << \"\\\"\";\n\n args.push_back(command.str());\n\n \/\/ options\n core::system::ProcessOptions options;\n options.terminateChildren = true;\n if (rOptions & R_PROCESS_REDIRECTSTDERR)\n options.redirectStdErrToStdOut = true;\n\n \/\/ if a working directory was specified, use it\n if (!workingDir.empty())\n {\n options.workingDir = workingDir;\n }\n\n \/\/ forward R_LIBS so the child process has access to the same libraries\n \/\/ we do\n core::system::Options childEnv;\n core::system::environment(&childEnv);\n std::string libPaths = module_context::libPathsString();\n if (!libPaths.empty())\n {\n core::system::setenv(&childEnv, \"R_LIBS\", libPaths);\n }\n \n \/\/ forward passed environment variables\n for (const core::system::Option& var : environment)\n {\n core::system::setenv(&childEnv, var.first, var.second);\n }\n \n \/\/ set environment variables used for IPC\n core::system::setenv(&childEnv, \"RSTUDIOAPI_IPC_REQUESTS_FILE\", ipcRequests_.absolutePath());\n core::system::setenv(&childEnv, \"RSTUDIOAPI_IPC_RESPONSE_FILE\", ipcResponse_.absolutePath());\n core::system::setenv(&childEnv, \"RSTUDIOAPI_IPC_SHARED_SECRET\", sharedSecret_);\n \n \/\/ update environment used for child process\n options.environment = childEnv;\n\n core::system::ProcessCallbacks cb;\n using namespace module_context;\n cb.onContinue = boost::bind(&AsyncRProcess::onContinue,\n AsyncRProcess::shared_from_this());\n cb.onStdout = boost::bind(&AsyncRProcess::onStdout,\n AsyncRProcess::shared_from_this(),\n _2);\n cb.onStderr = boost::bind(&AsyncRProcess::onStderr,\n AsyncRProcess::shared_from_this(),\n _2);\n cb.onExit = boost::bind(&AsyncRProcess::onProcessCompleted,\n AsyncRProcess::shared_from_this(),\n _1);\n cb.onStarted = boost::bind(&AsyncRProcess::onStarted,\n AsyncRProcess::shared_from_this(),\n _1);\n\n \/\/ forward input if requested\n input_ = input;\n\n error = module_context::processSupervisor().runProgram(\n rProgramPath.absolutePath(),\n args,\n options,\n cb);\n if (error)\n {\n LOG_ERROR(error);\n onCompleted(EXIT_FAILURE);\n }\n else\n {\n isRunning_ = true;\n }\n}\n\nvoid AsyncRProcess::onStarted(core::system::ProcessOperations& operations)\n{\n if (!input_.empty())\n {\n core::Error error = operations.writeToStdin(input_, true);\n if (error)\n {\n LOG_ERROR(error);\n error = operations.terminate();\n if (error)\n LOG_ERROR(error);\n }\n }\n}\n\nvoid AsyncRProcess::onStdout(const std::string& output)\n{\n \/\/ no-op stub for optional implementation by derived classees\n}\n\nvoid AsyncRProcess::onStderr(const std::string& output)\n{\n \/\/ no-op stub for optional implementation by derived classees\n}\n\nbool AsyncRProcess::onContinue()\n{\n if (terminationRequested_)\n return false;\n \n \/\/ check for request requiring a response\n if (ipcRequests_.exists())\n {\n core::Error error = r::exec::RFunction(\".rs.rstudioapi.processRequest\")\n .addParam(ipcRequests_.absolutePathNative())\n .addParam(ipcResponse_.absolutePathNative())\n .addParam(sharedSecret_)\n .call();\n\n if (error)\n {\n LOG_ERROR(error);\n return false;\n }\n }\n \n return true;\n}\n\nbool AsyncRProcess::terminationRequested()\n{\n return terminationRequested_;\n}\n\nvoid AsyncRProcess::onProcessCompleted(int exitStatus)\n{\n markCompleted();\n onCompleted(exitStatus);\n}\n\nbool AsyncRProcess::isRunning()\n{\n return isRunning_;\n}\n\nvoid AsyncRProcess::terminate()\n{\n terminationRequested_ = true;\n}\n\nvoid AsyncRProcess::markCompleted() \n{\n isRunning_ = false;\n}\n\nAsyncRProcess::~AsyncRProcess()\n{\n}\n\n} \/\/ namespace async_r\n} \/\/ namespace session\n} \/\/ namespace rstudio\n\n<commit_msg>remove leftover IPC request \/ response files on proc exit<commit_after>\/*\n * SessionAsyncRProcess.cpp\n *\n * Copyright (C) 2009-19 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <session\/prefs\/UserPrefs.hpp>\n#include <session\/SessionConsoleProcess.hpp>\n#include <session\/SessionModuleContext.hpp>\n\n#include <core\/system\/Environment.hpp>\n#include <core\/system\/Process.hpp>\n\n#include <r\/RExec.hpp>\n\n#include <r\/session\/RSessionUtils.hpp>\n\n#include <session\/SessionAsyncRProcess.hpp>\n\nnamespace rstudio {\nnamespace session {\nnamespace async_r {\n\nAsyncRProcess::AsyncRProcess():\n isRunning_(false),\n terminationRequested_(false)\n{\n}\n\nvoid AsyncRProcess::start(const char* rCommand,\n core::system::Options environment,\n const core::FilePath& workingDir,\n AsyncRProcessOptions rOptions,\n std::vector<core::FilePath> rSourceFiles,\n const std::string& input)\n{\n \/\/ file paths to be used for IPC (if any) requested by child process\n ipcRequests_ = module_context::tempFile(\"rstudio-ipc-requests-\", \"rds\");\n ipcResponse_ = module_context::tempFile(\"rstudio-ipc-response-\", \"rds\");\n sharedSecret_ = core::system::generateUuid();\n \n \/\/ R binary\n core::FilePath rProgramPath;\n core::Error error = module_context::rScriptPath(&rProgramPath);\n if (error)\n {\n LOG_ERROR(error);\n onCompleted(EXIT_FAILURE);\n return;\n }\n \n \/\/ core R files for augmented async processes\n if (rOptions & R_PROCESS_AUGMENTED)\n {\n \/\/ R files we wish to source to provide functionality to async process\n const core::FilePath modulesPath =\n session::options().modulesRSourcePath();\n \n const core::FilePath rPath =\n session::options().coreRSourcePath();\n \n const core::FilePath rTools = rPath.childPath(\"Tools.R\");\n \n \/\/ insert at begin as Tools.R needs to be sourced first\n rSourceFiles.insert(rSourceFiles.begin(), rTools);\n }\n\n \/\/ args\n std::vector<std::string> args;\n args.push_back(\"--slave\");\n if (rOptions & R_PROCESS_VANILLA)\n args.push_back(\"--vanilla\");\n if (rOptions & R_PROCESS_NO_RDATA)\n {\n args.push_back(\"--no-save\");\n args.push_back(\"--no-restore\");\n }\n\n \/\/ for windows we need to forward setInternet2\n#ifdef _WIN32\n if (!r::session::utils::isR3_3() && prefs::userPrefs().useInternet2())\n args.push_back(\"--internet2\");\n#endif\n\n args.push_back(\"-e\");\n \n bool needsQuote = false;\n\n \/\/ On Windows, we turn the vector of strings into a single\n \/\/ string to send over the command line, so we must ensure\n \/\/ that the arguments following '-e' are quoted, so that\n \/\/ they are all interpretted as a single argument (rather\n \/\/ than multiple arguments) to '-e'.\n\n#ifdef _WIN32\n needsQuote = strlen(rCommand) > 0 && rCommand[0] != '\"';\n#endif\n\n std::stringstream command;\n if (needsQuote)\n command << \"\\\"\";\n\n std::string escapedCommand = rCommand;\n\n if (needsQuote)\n boost::algorithm::replace_all(escapedCommand, \"\\\"\", \"\\\\\\\"\");\n \n if (rSourceFiles.size())\n {\n \/\/ add in the r source files requested\n for (std::vector<core::FilePath>::const_iterator it = rSourceFiles.begin();\n it != rSourceFiles.end();\n ++it)\n {\n command << \"source('\" << it->absolutePath() << \"');\";\n }\n \n command << escapedCommand;\n }\n else\n {\n command << escapedCommand;\n }\n\n if (needsQuote)\n command << \"\\\"\";\n\n args.push_back(command.str());\n\n \/\/ options\n core::system::ProcessOptions options;\n options.terminateChildren = true;\n if (rOptions & R_PROCESS_REDIRECTSTDERR)\n options.redirectStdErrToStdOut = true;\n\n \/\/ if a working directory was specified, use it\n if (!workingDir.empty())\n {\n options.workingDir = workingDir;\n }\n\n \/\/ forward R_LIBS so the child process has access to the same libraries\n \/\/ we do\n core::system::Options childEnv;\n core::system::environment(&childEnv);\n std::string libPaths = module_context::libPathsString();\n if (!libPaths.empty())\n {\n core::system::setenv(&childEnv, \"R_LIBS\", libPaths);\n }\n \n \/\/ forward passed environment variables\n for (const core::system::Option& var : environment)\n {\n core::system::setenv(&childEnv, var.first, var.second);\n }\n \n \/\/ set environment variables used for IPC\n core::system::setenv(&childEnv, \"RSTUDIOAPI_IPC_REQUESTS_FILE\", ipcRequests_.absolutePath());\n core::system::setenv(&childEnv, \"RSTUDIOAPI_IPC_RESPONSE_FILE\", ipcResponse_.absolutePath());\n core::system::setenv(&childEnv, \"RSTUDIOAPI_IPC_SHARED_SECRET\", sharedSecret_);\n \n \/\/ update environment used for child process\n options.environment = childEnv;\n\n core::system::ProcessCallbacks cb;\n using namespace module_context;\n cb.onContinue = boost::bind(&AsyncRProcess::onContinue,\n AsyncRProcess::shared_from_this());\n cb.onStdout = boost::bind(&AsyncRProcess::onStdout,\n AsyncRProcess::shared_from_this(),\n _2);\n cb.onStderr = boost::bind(&AsyncRProcess::onStderr,\n AsyncRProcess::shared_from_this(),\n _2);\n cb.onExit = boost::bind(&AsyncRProcess::onProcessCompleted,\n AsyncRProcess::shared_from_this(),\n _1);\n cb.onStarted = boost::bind(&AsyncRProcess::onStarted,\n AsyncRProcess::shared_from_this(),\n _1);\n\n \/\/ forward input if requested\n input_ = input;\n\n error = module_context::processSupervisor().runProgram(\n rProgramPath.absolutePath(),\n args,\n options,\n cb);\n if (error)\n {\n LOG_ERROR(error);\n onCompleted(EXIT_FAILURE);\n }\n else\n {\n isRunning_ = true;\n }\n}\n\nvoid AsyncRProcess::onStarted(core::system::ProcessOperations& operations)\n{\n if (!input_.empty())\n {\n core::Error error = operations.writeToStdin(input_, true);\n if (error)\n {\n LOG_ERROR(error);\n error = operations.terminate();\n if (error)\n LOG_ERROR(error);\n }\n }\n}\n\nvoid AsyncRProcess::onStdout(const std::string& output)\n{\n \/\/ no-op stub for optional implementation by derived classees\n}\n\nvoid AsyncRProcess::onStderr(const std::string& output)\n{\n \/\/ no-op stub for optional implementation by derived classees\n}\n\nbool AsyncRProcess::onContinue()\n{\n if (terminationRequested_)\n return false;\n \n \/\/ check for request requiring a response\n if (ipcRequests_.exists())\n {\n core::Error error = r::exec::RFunction(\".rs.rstudioapi.processRequest\")\n .addParam(ipcRequests_.absolutePathNative())\n .addParam(ipcResponse_.absolutePathNative())\n .addParam(sharedSecret_)\n .call();\n\n if (error)\n {\n LOG_ERROR(error);\n return false;\n }\n }\n \n return true;\n}\n\nbool AsyncRProcess::terminationRequested()\n{\n return terminationRequested_;\n}\n\nvoid AsyncRProcess::onProcessCompleted(int exitStatus)\n{\n markCompleted();\n ipcRequests_.removeIfExists();\n ipcResponse_.removeIfExists();\n onCompleted(exitStatus);\n}\n\nbool AsyncRProcess::isRunning()\n{\n return isRunning_;\n}\n\nvoid AsyncRProcess::terminate()\n{\n terminationRequested_ = true;\n}\n\nvoid AsyncRProcess::markCompleted() \n{\n isRunning_ = false;\n}\n\nAsyncRProcess::~AsyncRProcess()\n{\n}\n\n} \/\/ namespace async_r\n} \/\/ namespace session\n} \/\/ namespace rstudio\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SessionRPubs.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n\/\/ TODO: why is the id and continue url printed to the server err console?\n\n\/\/ TODO: test curl error reporting on osx\n\/\/ TODO: test chrome popup blocking\n\/\/ TODO: test on desktop\n\/\/ TODO: test all error state (correct dialog & window dismissal)\n\n\/\/ TODO: wininet ssl\n\/\/ TODO: sync function over to markup package\n\n#include \"SessionRPubs.hpp\"\n\n#include <boost\/bind.hpp>\n#include <boost\/utility.hpp>\n#include <boost\/format.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n\n#include <core\/Error.hpp>\n#include <core\/Exec.hpp>\n#include <core\/Log.hpp>\n#include <core\/Settings.hpp>\n\n#include <core\/text\/CsvParser.hpp>\n#include <core\/http\/Util.hpp>\n#include <core\/system\/Process.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n\n#include <session\/projects\/SessionProjects.hpp>\n\nusing namespace core ;\n\nnamespace session {\nnamespace modules { \nnamespace rpubs {\n\nnamespace {\n\n\/\/ we get a fresh settings object for each read or write so multiple\n\/\/ processes can all read and write without cache issues\nvoid getUploadIdSettings(Settings* pSettings)\n{\n FilePath rpubsUploadIds =\n module_context::scopedScratchPath().complete(\"rpubs_upload_ids\");\n Error error = pSettings->initialize(rpubsUploadIds);\n if (error)\n LOG_ERROR(error);\n}\n\nstd::string pathIdentifier(const FilePath& filePath)\n{\n \/\/ use a relative path if we are in a project\n std::string path;\n projects::ProjectContext& projectContext = projects::projectContext();\n if (projectContext.hasProject() &&\n filePath.isWithin(projectContext.directory()))\n {\n path = filePath.relativePath(projectContext.directory());\n }\n else\n {\n path = filePath.absolutePath();\n }\n\n \/\/ urlencode so we can use it as a key\n return http::util::urlEncode(path);\n}\n\nstd::string previousUploadId(const FilePath& filePath)\n{\n Settings settings;\n getUploadIdSettings(&settings);\n return settings.get(pathIdentifier(filePath));\n}\n\nvoid saveUploadId(const FilePath& filePath, const std::string& uploadId)\n{\n Settings settings;\n getUploadIdSettings(&settings);\n settings.set(pathIdentifier(filePath), uploadId);\n}\n\n\nclass RPubsUpload : boost::noncopyable,\n public boost::enable_shared_from_this<RPubsUpload>\n{\npublic:\n static boost::shared_ptr<RPubsUpload> create(const std::string& title,\n const FilePath& htmlFile)\n {\n boost::shared_ptr<RPubsUpload> pUpload(new RPubsUpload());\n pUpload->start(title, htmlFile);\n return pUpload;\n }\n\n virtual ~RPubsUpload()\n {\n }\n\n bool isRunning() const { return isRunning_; }\n\n void terminate()\n {\n terminationRequested_ = true;\n }\n\nprivate:\n RPubsUpload()\n : terminationRequested_(false), isRunning_(false)\n {\n }\n\n void start(const std::string& title, const FilePath& htmlFile)\n {\n using namespace core::string_utils;\n using namespace module_context;\n\n htmlFile_ = htmlFile;\n isRunning_ = true;\n\n \/\/ see if we already know of an upload id for this file\n std::string id = previousUploadId(htmlFile_);\n\n \/\/ R binary\n FilePath rProgramPath;\n Error error = rScriptPath(&rProgramPath);\n if (error)\n {\n terminateWithError(error);\n return;\n }\n\n \/\/ args\n std::vector<std::string> args;\n args.push_back(\"--slave\");\n args.push_back(\"--vanilla\");\n args.push_back(\"-e\");\n\n boost::format fmt(\n \"source(\\\"%1%\\\"); \"\n \"result <- rpubsUpload(\\\"%2%\\\", \\\"%3%\\\", %4%); \"\n \"utils::write.csv(as.data.frame(result), row.names=FALSE);\");\n\n FilePath modulesPath = session::options().modulesRSourcePath();;\n std::string scriptPath = utf8ToSystem(\n modulesPath.complete(\"SessionRPubs.R\").absolutePath());\n std::string htmlPath = utf8ToSystem(htmlFile.absolutePath());\n\n std::string escapedScriptPath = string_utils::jsLiteralEscape(scriptPath);\n std::string escapedTitle = string_utils::jsLiteralEscape(title);\n std::string escapedHtmlPath = string_utils::jsLiteralEscape(htmlPath);\n std::string escapedId = string_utils::jsLiteralEscape(id);\n\n std::string cmd = boost::str(fmt %\n escapedScriptPath % escapedTitle % escapedHtmlPath %\n (!escapedId.empty() ? \"\\\"\" + escapedId + \"\\\"\" : \"NULL\"));\n args.push_back(cmd);\n\n \/\/ options\n core::system::ProcessOptions options;\n options.terminateChildren = true;\n options.workingDir = htmlFile.parent();\n\n \/\/ callbacks\n core::system::ProcessCallbacks cb;\n cb.onContinue = boost::bind(&RPubsUpload::onContinue,\n RPubsUpload::shared_from_this());\n cb.onStdout = boost::bind(&RPubsUpload::onStdOut,\n RPubsUpload::shared_from_this(), _2);\n cb.onStderr = boost::bind(&RPubsUpload::onStdErr,\n RPubsUpload::shared_from_this(), _2);\n cb.onExit = boost::bind(&RPubsUpload::onCompleted,\n RPubsUpload::shared_from_this(), _1);\n\n \/\/ execute\n processSupervisor().runProgram(rProgramPath.absolutePath(),\n args,\n options,\n cb);\n }\n\n bool onContinue()\n {\n return !terminationRequested_;\n }\n\n void onStdOut(const std::string& output)\n {\n output_.append(output);\n }\n\n void onStdErr(const std::string& error)\n {\n error_.append(error);\n }\n\n\n void onCompleted(int exitStatus)\n {\n if (exitStatus == EXIT_SUCCESS)\n {\n Result result = parseOutput(output_);\n if (!result.empty())\n terminateWithResult(result);\n else\n terminateWithError(\"Unexpected output from upload: \" + output_);\n }\n else\n {\n terminateWithError(error_);\n }\n }\n\n void terminateWithError(const Error& error)\n {\n terminateWithError(error.summary());\n }\n\n void terminateWithError(const std::string& error)\n {\n terminateWithResult(Result(error));\n }\n\n struct Result\n {\n Result()\n {\n }\n\n Result(const std::string& error)\n : error(error)\n {\n }\n\n Result(const std::string& id, const std::string& continueUrl)\n : id(id), continueUrl(continueUrl)\n {\n }\n\n bool empty() const { return id.empty() && error.empty(); }\n\n std::string id;\n std::string continueUrl;\n std::string error;\n };\n\n void terminateWithResult(const Result& result)\n {\n isRunning_ = false;\n\n if (!result.id.empty())\n saveUploadId(htmlFile_, result.id);\n\n json::Object statusJson;\n statusJson[\"id\"] = result.id;\n statusJson[\"continueUrl\"] = result.continueUrl;\n statusJson[\"error\"] = result.error;\n ClientEvent event(client_events::kRPubsUploadStatus, statusJson);\n module_context::enqueClientEvent(event);\n }\n\n Result parseOutput(const std::string& output)\n {\n std::pair<std::vector<std::string>, std::string::const_iterator>\n line = text::parseCsvLine(output.begin(), output.end());\n if (!line.first.empty())\n {\n std::vector<std::string> headers = line.first;\n\n line = text::parseCsvLine(line.second, output.end());\n if (!line.first.empty())\n {\n std::vector<std::string> data = line.first;\n\n if (headers.size() == 1 &&\n data.size() == 1 &&\n headers[0] == \"error\")\n {\n return Result(data[0]);\n }\n else if (headers.size() == 2 &&\n data.size() == 2 &&\n headers[0] == \"id\" &&\n headers[1] == \"continueUrl\")\n {\n return Result(data[0], data[1]);\n }\n }\n }\n\n return Result();\n }\n\nprivate:\n FilePath htmlFile_;\n bool terminationRequested_;\n bool isRunning_;\n std::string output_;\n std::string error_;\n};\n\nboost::shared_ptr<RPubsUpload> s_pCurrentUpload;\n\nbool isUploadRunning()\n{\n return s_pCurrentUpload && s_pCurrentUpload->isRunning();\n}\n\nError rpubsUpload(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string title, htmlFile;\n Error error = json::readParams(request.params, &title, &htmlFile);\n if (error)\n return error;\n\n if (isUploadRunning())\n {\n pResponse->setResult(false);\n }\n else\n {\n FilePath filePath = module_context::resolveAliasedPath(htmlFile);\n s_pCurrentUpload = RPubsUpload::create(title, filePath);\n pResponse->setResult(true);\n }\n\n return Success();\n}\n\nError terminateRpubsUpload(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n if (isUploadRunning())\n s_pCurrentUpload->terminate();\n\n return Success();\n}\n\n} \/\/ anonymous namespace\n\n\nError initialize()\n{\n using boost::bind;\n using namespace module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"rpubs_upload\", rpubsUpload))\n (bind(registerRpcMethod, \"terminate_rpubs_upload\", terminateRpubsUpload))\n ;\n return initBlock.execute();\n}\n \n \n} \/\/ namespace rpubs\n} \/\/ namespace modules\n} \/\/ namesapce session\n\n<commit_msg>update todos<commit_after>\/*\n * SessionRPubs.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n\n\/\/ TODO: test curl error reporting on osx\n\/\/ TODO: test all error state (correct dialog & window dismissal)\n\n\/\/ TODO: sync function over to markup package\n\n#include \"SessionRPubs.hpp\"\n\n#include <boost\/bind.hpp>\n#include <boost\/utility.hpp>\n#include <boost\/format.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n\n#include <core\/Error.hpp>\n#include <core\/Exec.hpp>\n#include <core\/Log.hpp>\n#include <core\/Settings.hpp>\n\n#include <core\/text\/CsvParser.hpp>\n#include <core\/http\/Util.hpp>\n#include <core\/system\/Process.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n\n#include <session\/projects\/SessionProjects.hpp>\n\nusing namespace core ;\n\nnamespace session {\nnamespace modules { \nnamespace rpubs {\n\nnamespace {\n\n\/\/ we get a fresh settings object for each read or write so multiple\n\/\/ processes can all read and write without cache issues\nvoid getUploadIdSettings(Settings* pSettings)\n{\n FilePath rpubsUploadIds =\n module_context::scopedScratchPath().complete(\"rpubs_upload_ids\");\n Error error = pSettings->initialize(rpubsUploadIds);\n if (error)\n LOG_ERROR(error);\n}\n\nstd::string pathIdentifier(const FilePath& filePath)\n{\n \/\/ use a relative path if we are in a project\n std::string path;\n projects::ProjectContext& projectContext = projects::projectContext();\n if (projectContext.hasProject() &&\n filePath.isWithin(projectContext.directory()))\n {\n path = filePath.relativePath(projectContext.directory());\n }\n else\n {\n path = filePath.absolutePath();\n }\n\n \/\/ urlencode so we can use it as a key\n return http::util::urlEncode(path);\n}\n\nstd::string previousUploadId(const FilePath& filePath)\n{\n Settings settings;\n getUploadIdSettings(&settings);\n return settings.get(pathIdentifier(filePath));\n}\n\nvoid saveUploadId(const FilePath& filePath, const std::string& uploadId)\n{\n Settings settings;\n getUploadIdSettings(&settings);\n settings.set(pathIdentifier(filePath), uploadId);\n}\n\n\nclass RPubsUpload : boost::noncopyable,\n public boost::enable_shared_from_this<RPubsUpload>\n{\npublic:\n static boost::shared_ptr<RPubsUpload> create(const std::string& title,\n const FilePath& htmlFile)\n {\n boost::shared_ptr<RPubsUpload> pUpload(new RPubsUpload());\n pUpload->start(title, htmlFile);\n return pUpload;\n }\n\n virtual ~RPubsUpload()\n {\n }\n\n bool isRunning() const { return isRunning_; }\n\n void terminate()\n {\n terminationRequested_ = true;\n }\n\nprivate:\n RPubsUpload()\n : terminationRequested_(false), isRunning_(false)\n {\n }\n\n void start(const std::string& title, const FilePath& htmlFile)\n {\n using namespace core::string_utils;\n using namespace module_context;\n\n htmlFile_ = htmlFile;\n isRunning_ = true;\n\n \/\/ see if we already know of an upload id for this file\n std::string id = previousUploadId(htmlFile_);\n\n \/\/ R binary\n FilePath rProgramPath;\n Error error = rScriptPath(&rProgramPath);\n if (error)\n {\n terminateWithError(error);\n return;\n }\n\n \/\/ args\n std::vector<std::string> args;\n args.push_back(\"--slave\");\n args.push_back(\"--vanilla\");\n args.push_back(\"-e\");\n\n boost::format fmt(\n \"source(\\\"%1%\\\"); \"\n \"result <- rpubsUpload(\\\"%2%\\\", \\\"%3%\\\", %4%); \"\n \"utils::write.csv(as.data.frame(result), row.names=FALSE);\");\n\n FilePath modulesPath = session::options().modulesRSourcePath();;\n std::string scriptPath = utf8ToSystem(\n modulesPath.complete(\"SessionRPubs.R\").absolutePath());\n std::string htmlPath = utf8ToSystem(htmlFile.absolutePath());\n\n std::string escapedScriptPath = string_utils::jsLiteralEscape(scriptPath);\n std::string escapedTitle = string_utils::jsLiteralEscape(title);\n std::string escapedHtmlPath = string_utils::jsLiteralEscape(htmlPath);\n std::string escapedId = string_utils::jsLiteralEscape(id);\n\n std::string cmd = boost::str(fmt %\n escapedScriptPath % escapedTitle % escapedHtmlPath %\n (!escapedId.empty() ? \"\\\"\" + escapedId + \"\\\"\" : \"NULL\"));\n args.push_back(cmd);\n\n \/\/ options\n core::system::ProcessOptions options;\n options.terminateChildren = true;\n options.workingDir = htmlFile.parent();\n\n \/\/ callbacks\n core::system::ProcessCallbacks cb;\n cb.onContinue = boost::bind(&RPubsUpload::onContinue,\n RPubsUpload::shared_from_this());\n cb.onStdout = boost::bind(&RPubsUpload::onStdOut,\n RPubsUpload::shared_from_this(), _2);\n cb.onStderr = boost::bind(&RPubsUpload::onStdErr,\n RPubsUpload::shared_from_this(), _2);\n cb.onExit = boost::bind(&RPubsUpload::onCompleted,\n RPubsUpload::shared_from_this(), _1);\n\n \/\/ execute\n processSupervisor().runProgram(rProgramPath.absolutePath(),\n args,\n options,\n cb);\n }\n\n bool onContinue()\n {\n return !terminationRequested_;\n }\n\n void onStdOut(const std::string& output)\n {\n output_.append(output);\n }\n\n void onStdErr(const std::string& error)\n {\n error_.append(error);\n }\n\n\n void onCompleted(int exitStatus)\n {\n if (exitStatus == EXIT_SUCCESS)\n {\n Result result = parseOutput(output_);\n if (!result.empty())\n terminateWithResult(result);\n else\n terminateWithError(\"Unexpected output from upload: \" + output_);\n }\n else\n {\n terminateWithError(error_);\n }\n }\n\n void terminateWithError(const Error& error)\n {\n terminateWithError(error.summary());\n }\n\n void terminateWithError(const std::string& error)\n {\n terminateWithResult(Result(error));\n }\n\n struct Result\n {\n Result()\n {\n }\n\n Result(const std::string& error)\n : error(error)\n {\n }\n\n Result(const std::string& id, const std::string& continueUrl)\n : id(id), continueUrl(continueUrl)\n {\n }\n\n bool empty() const { return id.empty() && error.empty(); }\n\n std::string id;\n std::string continueUrl;\n std::string error;\n };\n\n void terminateWithResult(const Result& result)\n {\n isRunning_ = false;\n\n if (!result.id.empty())\n saveUploadId(htmlFile_, result.id);\n\n json::Object statusJson;\n statusJson[\"id\"] = result.id;\n statusJson[\"continueUrl\"] = result.continueUrl;\n statusJson[\"error\"] = result.error;\n ClientEvent event(client_events::kRPubsUploadStatus, statusJson);\n module_context::enqueClientEvent(event);\n }\n\n Result parseOutput(const std::string& output)\n {\n std::pair<std::vector<std::string>, std::string::const_iterator>\n line = text::parseCsvLine(output.begin(), output.end());\n if (!line.first.empty())\n {\n std::vector<std::string> headers = line.first;\n\n line = text::parseCsvLine(line.second, output.end());\n if (!line.first.empty())\n {\n std::vector<std::string> data = line.first;\n\n if (headers.size() == 1 &&\n data.size() == 1 &&\n headers[0] == \"error\")\n {\n return Result(data[0]);\n }\n else if (headers.size() == 2 &&\n data.size() == 2 &&\n headers[0] == \"id\" &&\n headers[1] == \"continueUrl\")\n {\n return Result(data[0], data[1]);\n }\n }\n }\n\n return Result();\n }\n\nprivate:\n FilePath htmlFile_;\n bool terminationRequested_;\n bool isRunning_;\n std::string output_;\n std::string error_;\n};\n\nboost::shared_ptr<RPubsUpload> s_pCurrentUpload;\n\nbool isUploadRunning()\n{\n return s_pCurrentUpload && s_pCurrentUpload->isRunning();\n}\n\nError rpubsUpload(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string title, htmlFile;\n Error error = json::readParams(request.params, &title, &htmlFile);\n if (error)\n return error;\n\n if (isUploadRunning())\n {\n pResponse->setResult(false);\n }\n else\n {\n FilePath filePath = module_context::resolveAliasedPath(htmlFile);\n s_pCurrentUpload = RPubsUpload::create(title, filePath);\n pResponse->setResult(true);\n }\n\n return Success();\n}\n\nError terminateRpubsUpload(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n if (isUploadRunning())\n s_pCurrentUpload->terminate();\n\n return Success();\n}\n\n} \/\/ anonymous namespace\n\n\nError initialize()\n{\n using boost::bind;\n using namespace module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"rpubs_upload\", rpubsUpload))\n (bind(registerRpcMethod, \"terminate_rpubs_upload\", terminateRpubsUpload))\n ;\n return initBlock.execute();\n}\n \n \n} \/\/ namespace rpubs\n} \/\/ namespace modules\n} \/\/ namesapce session\n\n<|endoftext|>"} {"text":"<commit_before>#include \"estimator\/dcm_attitude_estimator.hpp\"\n\n#include \"hal.h\"\n#include \"protocol\/messages.hpp\"\n\n#include \"unit_config.hpp\"\n\nDCMAttitudeEstimator::DCMAttitudeEstimator(Communicator& communicator)\n : dcm(Eigen::Matrix3f::Identity()),\n attitudeMessageStream(communicator, 100) {\n}\n\nattitude_estimate_t DCMAttitudeEstimator::update(gyroscope_reading_t& gyroReading, accelerometer_reading_t& accelReading) {\n Eigen::Vector3f gyro(gyroReading.axes.data());\n Eigen::Vector3f accel(accelReading.axes.data());\n\n float accWeight = 0.02f;\n palClearPad(GPIOE, GPIOE_LED4_BLUE);\n if(accel.norm() > 1.05 * 9.8 || accel.norm() < 0.95 * 9.8) {\n palSetPad(GPIOE, GPIOE_LED4_BLUE);\n accWeight = 0.0f;\n }\n\n accel.normalize();\n\n Eigen::Vector3f corr = Eigen::Vector3f::Zero();\n corr += gyro * unit_config::DT * (1.0f - accWeight);\n corr += dcm.col(2).cross(accel) * accWeight;\n\n Eigen::Matrix3f dcmStep;\n dcmStep << 1.0f, corr.z(), -corr.y(),\n -corr.z(), 1.0f, corr.x(),\n corr.y(), -corr.x(), 1.0f;\n\n dcm *= dcmStep;\n\n orthonormalize();\n\n attitude_estimate_t estimate {\n \/\/ TODO: Are these trig functions safe at extreme angles?\n .roll = -atan2f(dcm(2, 1), dcm(2, 2)) * dcm(0, 0) + atan2f(dcm(2, 0), dcm(2, 2)) * dcm(0, 1),\n .pitch = atan2f(dcm(2, 0), dcm(2, 2)) * dcm(1, 1) - atan2f(dcm(2, 1), dcm(2, 2)) * dcm(1, 0),\n .yaw = 0.0f, \/\/ atan2f(dcm(1, 1), dcm(0, 1)),\n .roll_vel = gyro.x(),\n .pitch_vel = gyro.y(),\n .yaw_vel = gyro.z()\n };\n\n if(attitudeMessageStream.ready()) {\n protocol::message::attitude_message_t m {\n .dcm = {\n \/\/ estimate.roll, estimate.pitch, estimate.yaw,\n \/\/ accel(0), accel(1), accel(2),\n \/\/ gyro(0), gyro(1), gyro(2),\n dcm(0, 0), dcm(0, 1), dcm(0, 2),\n dcm(1, 0), dcm(1, 1), dcm(1, 2),\n dcm(2, 0), dcm(2, 1), dcm(2, 2)\n }\n };\n\n attitudeMessageStream.publish(m);\n }\n\n return estimate;\n}\n\nvoid DCMAttitudeEstimator::orthonormalize() {\n \/\/ Make the i and j vectors orthogonal\n float error = dcm.row(0).dot(dcm.row(1));\n\n Eigen::Matrix3f corr = Eigen::Matrix3f::Zero();\n corr.row(0) = dcm.row(1) * (-error) \/ 2;\n corr.row(1) = dcm.row(0) * (-error) \/ 2;\n\n dcm.row(0) += corr.row(0);\n dcm.row(1) += corr.row(1);\n\n \/\/ Estimate k vector from corrected i and j vectors\n dcm.row(2) = dcm.row(0).cross(dcm.row(1));\n\n \/\/ Normalize all vectors\n dcm.rowwise().normalize();\n}\n<commit_msg>Final DCM fixes.<commit_after>#include \"estimator\/dcm_attitude_estimator.hpp\"\n\n#include \"hal.h\"\n#include \"protocol\/messages.hpp\"\n\n#include \"unit_config.hpp\"\n\nDCMAttitudeEstimator::DCMAttitudeEstimator(Communicator& communicator)\n : dcm(Eigen::Matrix3f::Identity()),\n attitudeMessageStream(communicator, 100) {\n}\n\nattitude_estimate_t DCMAttitudeEstimator::update(gyroscope_reading_t& gyroReading, accelerometer_reading_t& accelReading) {\n Eigen::Vector3f gyro(gyroReading.axes.data());\n Eigen::Vector3f accel(accelReading.axes.data());\n\n float accWeight = 0.02f;\n palClearPad(GPIOE, GPIOE_LED4_BLUE);\n if(accel.norm() > 1.05 * 9.8 || accel.norm() < 0.95 * 9.8) {\n palSetPad(GPIOE, GPIOE_LED4_BLUE);\n accWeight = 0.0f;\n }\n\n accel.normalize();\n\n Eigen::Vector3f corr = Eigen::Vector3f::Zero();\n corr += gyro * unit_config::DT * (1.0f - accWeight);\n corr -= dcm.col(2).cross(-accel) * accWeight;\n\n Eigen::Matrix3f dcmStep;\n dcmStep << 1.0f, corr.z(), -corr.y(),\n -corr.z(), 1.0f, corr.x(),\n corr.y(), -corr.x(), 1.0f;\n\n dcm = dcmStep * dcm;\n\n orthonormalize();\n\n attitude_estimate_t estimate {\n \/\/ TODO: Are these trig functions safe at extreme angles?\n .roll = -atan2f(dcm(2, 1), dcm(2, 2)) * dcm(0, 0) + atan2f(dcm(2, 0), dcm(2, 2)) * dcm(0, 1),\n .pitch = atan2f(dcm(2, 0), dcm(2, 2)) * dcm(1, 1) - atan2f(dcm(2, 1), dcm(2, 2)) * dcm(1, 0),\n .yaw = 0.0f, \/\/ atan2f(dcm(1, 1), dcm(0, 1)),\n .roll_vel = gyro.x(),\n .pitch_vel = gyro.y(),\n .yaw_vel = gyro.z()\n };\n\n if(attitudeMessageStream.ready()) {\n protocol::message::attitude_message_t m {\n .dcm = {\n \/\/ estimate.roll, estimate.pitch, estimate.yaw,\n \/\/ accel(0), accel(1), accel(2),\n \/\/ gyro(0), gyro(1), gyro(2),\n dcm(0, 0), dcm(0, 1), dcm(0, 2),\n dcm(1, 0), dcm(1, 1), dcm(1, 2),\n dcm(2, 0), dcm(2, 1), dcm(2, 2)\n }\n };\n\n attitudeMessageStream.publish(m);\n }\n\n return estimate;\n}\n\nvoid DCMAttitudeEstimator::orthonormalize() {\n \/\/ Make the i and j vectors orthogonal\n float error = dcm.row(0).dot(dcm.row(1));\n\n Eigen::Matrix3f corr = Eigen::Matrix3f::Zero();\n corr.row(0) = dcm.row(1) * (-error) \/ 2;\n corr.row(1) = dcm.row(0) * (-error) \/ 2;\n\n dcm.row(0) += corr.row(0);\n dcm.row(1) += corr.row(1);\n\n \/\/ Estimate k vector from corrected i and j vectors\n dcm.row(2) = dcm.row(0).cross(dcm.row(1));\n\n \/\/ Normalize all vectors\n dcm.rowwise().normalize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2014 John Manferdelli, All Rights Reserved.\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\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ or in the the file LICENSE-2.0.txt in the top level sourcedirectory\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\/\/ Project: New Cloudproxy Crypto\n\/\/ File: support_test.cc\n\n#include \"gtest\/gtest.h\"\n\n#include <gtest\/gtest.h>\n#include <gflags\/gflags.h>\n#include <stdio.h>\n#include <string>\n\n#include \"helpers.h\"\n\nbool readwritetest() {\n return true;\n}\n\nTEST(ReadWriteTest, ReadWriteTest) { EXPECT_TRUE(readwritetest()); }\n<commit_msg>test file<commit_after>\/\/\n\/\/ Copyright 2014 John Manferdelli, All Rights Reserved.\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\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ or in the the file LICENSE-2.0.txt in the top level sourcedirectory\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\/\/ Project: New Cloudproxy Crypto\n\/\/ File: support_test.cc\n\n#include \"gtest\/gtest.h\"\n\n#include <gtest\/gtest.h>\n#include <gflags\/gflags.h>\n#include <stdio.h>\n#include <string>\n\n#include \"helpers.h\"\n\nbool readwritetest() {\n string filename(\"\/tmp\/test1\");\n string in(\"12345\");\n string out;\n\n if (!WriteFile(filename, in)) {\n return false\n }\n if (!ReadFile(filename, &out)) {\n return false\n }\n if (out != in) {\n return false\n }\n return true;\n}\n\nTEST(ReadWriteTest, ReadWriteTest) { EXPECT_TRUE(readwritetest()); }\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the clazy static checker.\n\n Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com\n Author: Sérgio Martins <sergio.martins@kdab.com>\n\n Copyright (C) 2015 Sergio Martins <smartins@kde.org>\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 License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"missingtypeinfo.h\"\n#include \"Utils.h\"\n#include \"TemplateUtils.h\"\n#include \"TypeUtils.h\"\n#include \"QtUtils.h\"\n#include \"checkmanager.h\"\n\n#include <clang\/AST\/AST.h>\n#include <clang\/AST\/DeclTemplate.h>\n\n#include <sstream>\n\nusing namespace std;\nusing namespace clang;\n\nMissingTypeinfo::MissingTypeinfo(const std::string &name, const clang::CompilerInstance &ci)\n : CheckBase(name, ci)\n{\n}\n\nvoid MissingTypeinfo::VisitDecl(clang::Decl *decl)\n{\n \/\/ Catches QTypeInfo<Foo> to know type classification\n auto templateDef = dyn_cast<ClassTemplateSpecializationDecl>(decl);\n if (templateDef)\n registerQTypeInfo(templateDef);\n\n \/\/ Catches QList<Foo>\n ClassTemplateSpecializationDecl *tstdecl = TemplateUtils::templateDecl(decl);\n if (!tstdecl)\n return;\n\n const bool isQList = tstdecl->getName() == \"QList\";\n const bool isQVector = tstdecl->getName() == \"QVector\";\n\n if (!isQList && !isQVector)\n return;\n\n const TemplateArgumentList &tal = tstdecl->getTemplateArgs();\n\n if (tal.size() != 1) return;\n QualType qt2 = tal[0].getAsType();\n\n const Type *t = qt2.getTypePtrOrNull();\n CXXRecordDecl *record = t ? t->getAsCXXRecordDecl() : nullptr;\n if (!record || !record->getDefinition())\n return; \/\/ Don't crash if we only have a fwd decl\n\n const bool isCopyable = qt2.isTriviallyCopyableType(m_ci.getASTContext());\n const bool isTooBigForQList = QtUtils::isTooBigForQList(qt2, m_ci);\n\n if (isCopyable && (isQVector || (isQList && isTooBigForQList))) {\n if (m_typeInfos.count(record->getQualifiedNameAsString()) != 0)\n return;\n\n std::string typeName = record->getName();\n if (t->isRecordType() && !ignoreTypeInfo(typeName)) {\n std::string s;\n std::stringstream out;\n out << m_ci.getASTContext().getTypeSize(qt2)\/8;\n s = \"Missing Q_DECLARE_TYPEINFO: \" + typeName;\n emitWarning(decl->getLocStart(), s.c_str());\n emitWarning(record->getLocStart(), \"Type declared here:\", false);\n }\n }\n}\n\nvoid MissingTypeinfo::registerQTypeInfo(ClassTemplateSpecializationDecl *decl)\n{\n if (decl->getName() == \"QTypeInfo\") {\n auto &args = decl->getTemplateArgs();\n if (args.size() != 1)\n return;\n\n QualType qt = args[0].getAsType();\n const Type *t = qt.getTypePtrOrNull();\n CXXRecordDecl *recordDecl = t ? t->getAsCXXRecordDecl() : nullptr;\n if (recordDecl) {\n m_typeInfos.insert(recordDecl->getQualifiedNameAsString());\n }\n }\n}\n\nbool MissingTypeinfo::ignoreTypeInfo(const std::string &className) const\n{\n std::vector<std::string> primitives {\"QPair\", \"QTime\"}; \/\/ clazy bug\n return clazy_std::contains(primitives, className);\n}\n\n\nREGISTER_CHECK_WITH_FLAGS(\"missing-typeinfo\", MissingTypeinfo, CheckLevel3)\n<commit_msg>missing-type-info: Use TemplateUtils::getTemplateArgumentTypeStr()<commit_after>\/*\n This file is part of the clazy static checker.\n\n Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com\n Author: Sérgio Martins <sergio.martins@kdab.com>\n\n Copyright (C) 2015 Sergio Martins <smartins@kde.org>\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 License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"missingtypeinfo.h\"\n#include \"Utils.h\"\n#include \"TemplateUtils.h\"\n#include \"TypeUtils.h\"\n#include \"QtUtils.h\"\n#include \"checkmanager.h\"\n\n#include <clang\/AST\/AST.h>\n#include <clang\/AST\/DeclTemplate.h>\n\n#include <sstream>\n\nusing namespace std;\nusing namespace clang;\n\nMissingTypeinfo::MissingTypeinfo(const std::string &name, const clang::CompilerInstance &ci)\n : CheckBase(name, ci)\n{\n}\n\nvoid MissingTypeinfo::VisitDecl(clang::Decl *decl)\n{\n \/\/ Catches QTypeInfo<Foo> to know type classification\n auto templateDef = dyn_cast<ClassTemplateSpecializationDecl>(decl);\n if (templateDef)\n registerQTypeInfo(templateDef);\n\n \/\/ Catches QList<Foo>\n ClassTemplateSpecializationDecl *tstdecl = TemplateUtils::templateDecl(decl);\n if (!tstdecl)\n return;\n\n const bool isQList = tstdecl->getName() == \"QList\";\n const bool isQVector = tstdecl->getName() == \"QVector\";\n\n if (!isQList && !isQVector)\n return;\n\n const TemplateArgumentList &tal = tstdecl->getTemplateArgs();\n\n if (tal.size() != 1) return;\n QualType qt2 = tal[0].getAsType();\n\n const Type *t = qt2.getTypePtrOrNull();\n CXXRecordDecl *record = t ? t->getAsCXXRecordDecl() : nullptr;\n if (!record || !record->getDefinition())\n return; \/\/ Don't crash if we only have a fwd decl\n\n const bool isCopyable = qt2.isTriviallyCopyableType(m_ci.getASTContext());\n const bool isTooBigForQList = QtUtils::isTooBigForQList(qt2, m_ci);\n\n if (isCopyable && (isQVector || (isQList && isTooBigForQList))) {\n if (m_typeInfos.count(record->getQualifiedNameAsString()) != 0)\n return;\n\n std::string typeName = record->getName();\n if (t->isRecordType() && !ignoreTypeInfo(typeName)) {\n std::string s;\n std::stringstream out;\n out << m_ci.getASTContext().getTypeSize(qt2)\/8;\n s = \"Missing Q_DECLARE_TYPEINFO: \" + typeName;\n emitWarning(decl->getLocStart(), s.c_str());\n emitWarning(record->getLocStart(), \"Type declared here:\", false);\n }\n }\n}\n\nvoid MissingTypeinfo::registerQTypeInfo(ClassTemplateSpecializationDecl *decl)\n{\n if (decl->getName() == \"QTypeInfo\") {\n const string typeName = TemplateUtils::getTemplateArgumentTypeStr(decl, 0, lo(), \/**recordOnly=*\/true);\n if (!typeName.empty())\n m_typeInfos.insert(typeName);\n }\n}\n\nbool MissingTypeinfo::ignoreTypeInfo(const std::string &className) const\n{\n std::vector<std::string> primitives {\"QPair\", \"QTime\"}; \/\/ clazy bug\n return clazy_std::contains(primitives, className);\n}\n\n\nREGISTER_CHECK_WITH_FLAGS(\"missing-typeinfo\", MissingTypeinfo, CheckLevel3)\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include <ros\/ros.h>\n#include <geometry_msgs\/TransformStamped.h>\n#include <goal_sender_msgs\/ApplyGoals.h>\n#include <goal_sender_msgs\/GoalSequence.h>\n#include <tf2_ros\/transform_listener.h>\n\n\/**\n * Waypoint update service manager\n *\/\nclass WaypointManager\n{\npublic:\n bool operator()(goal_sender_msgs::ApplyGoals::Request& req,\n goal_sender_msgs::ApplyGoals::Response& res){\n return true;\n }\n\n goal_sender_msgs::GoalSequence get() const\n {\n return sequence_;\n }\n\n goal_sender_msgs::GoalSequence operator()() const\n {\n return get();\n }\n\nprivate:\n goal_sender_msgs::GoalSequence sequence_;\n};\n\n\/**\n * Tf lookup API\n *\/\nclass TfPositionManager\n{\npublic:\n TfPositionManager(tf2_ros::Buffer& tfBuffer)\n : buffer_ {tfBuffer}\n {\n }\n\n geometry_msgs::TransformStamped operator()(std::string parent, std::string child) const\n {\n return buffer_.lookupTransform(parent, child, ros::Time(0));\n }\n\nprivate:\n tf2_ros::Buffer& buffer_;\n};\n\nclass GoalSender\n{\npublic:\n GoalSender(WaypointManager point_manager,\n TfPositionManager lookupper)\n : point_manager_ {point_manager},\n lookupper_ {lookupper}\n {\n }\n\n void once()\n {\n }\n\nprivate:\n WaypointManager point_manager_;\n TfPositionManager lookupper_;\n};\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"goal_sender\");\n ros::NodeHandle nh {};\n\n WaypointManager point_manager {};\n ros::ServiceServer srv {\n nh.advertiseService<goal_sender_msgs::ApplyGoals::Request,\n goal_sender_msgs::ApplyGoals::Response>(\n \"apply_goals\", point_manager)};\n\n tf2_ros::Buffer tfBuffer;\n tf2_ros::TransformListener tfListener {tfBuffer};\n TfPositionManager lookupper {tfBuffer};\n\n GoalSender goal_sender {point_manager, lookupper};\n}\n<commit_msg>Implement waypoint manager and tf position manager<commit_after>#include <stdexcept>\n#include <string>\n\n#include <ros\/ros.h>\n#include <geometry_msgs\/Point.h>\n#include <geometry_msgs\/TransformStamped.h>\n#include <goal_sender_msgs\/ApplyGoals.h>\n#include <goal_sender_msgs\/GoalSequence.h>\n#include <tf2_ros\/transform_listener.h>\n\ninline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {\n const auto x {a.x - b.x};\n const auto y {a.y - b.y};\n return x*x + y*y;\n}\n\n\/**\n * Waypoint update service manager\n *\/\nclass WaypointManager\n{\npublic:\n bool operator()(goal_sender_msgs::ApplyGoals::Request& req,\n goal_sender_msgs::ApplyGoals::Response& res){\n return true;\n }\n\n const geometry_msgs::Point& point() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before point()\"};\n return now_goal->position;\n }\n\n double radius() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before radius()\"};\n return now_goal->radius;\n }\n\n bool next()\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before next()\"}; \/\/ wrong way.\n if (++now_goal == sequence_.waypoints.end())\n return false; \/\/ correct way: this is last one.\n return true;\n }\n\n bool is_end() const\n {\n return sequence_.waypoints.end() == now_goal;\n }\n\n [[deprecated]]\n const goal_sender_msgs::Waypoint& get() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before get()\"};\n return *now_goal;\n }\n\nprivate:\n goal_sender_msgs::GoalSequence sequence_;\n decltype(sequence_.waypoints)::iterator now_goal;\n};\n\n\/**\n * Tf lookup API\n *\/\nclass TfPositionManager\n{\npublic:\n TfPositionManager(tf2_ros::Buffer& tfBuffer)\n : buffer_ {tfBuffer}\n {\n }\n\n geometry_msgs::Point operator()(std::string parent, std::string child) const\n {\n const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};\n geometry_msgs::Point point;\n point.x = ts.transform.translation.x;\n point.y = ts.transform.translation.y;\n return point;\n }\n\nprivate:\n tf2_ros::Buffer& buffer_;\n};\n\nclass GoalSender\n{\npublic:\n GoalSender(WaypointManager point_manager,\n TfPositionManager lookupper)\n : point_manager_ {point_manager},\n lookupper_ {lookupper}\n {\n }\n\n void once()\n {\n if (point_manager_.is_end())\n return; \/\/ no work\n if (is_reach()) {\n point_manager_.next();\n }\n }\n\nprivate:\n bool is_reach() const\n {\n const auto robot_point {lookupper_(\"\/map\", \"\/base_link\")};\n const auto waypoint_point {point_manager_.point()};\n const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};\n\n const auto radius {point_manager_.radius()};\n const auto sqr_radius {radius * radius};\n\n if (sqr_distance < sqr_radius) \/\/ into valid range\n return true;\n return false;\n }\n\n WaypointManager point_manager_;\n TfPositionManager lookupper_;\n};\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"goal_sender\");\n ros::NodeHandle nh {};\n\n WaypointManager point_manager {};\n ros::ServiceServer srv {\n nh.advertiseService<goal_sender_msgs::ApplyGoals::Request,\n goal_sender_msgs::ApplyGoals::Response>(\n \"apply_goals\", point_manager)};\n\n tf2_ros::Buffer tfBuffer;\n tf2_ros::TransformListener tfListener {tfBuffer};\n TfPositionManager lookupper {tfBuffer};\n\n GoalSender goal_sender {point_manager, lookupper};\n\n ros::Rate rate {10};\n while (ros::ok()) {\n ros::spinOnce();\n goal_sender.once();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"DeviceRegistry.h\"\n#include \"register.h\"\n\nnamespace ZPUino {\n\n int DeviceRegistry::registerDevice(int slot) {\n if (slot>=MAX_SLOTS)\n return -2;\n if (m_sDeviceRegistry & (1<<slot))\n return -1;\n m_sDeviceRegistry |= (1<<slot);\n return 0;\n }\n\n uint8_t DeviceRegistry::scanDevice(unsigned vendor, unsigned product, int instance) {\n int i;\n for (i=0;i!=16;i++) {\n unsigned val = REGISTER(SYSCTLBASE,16+i);\n if (val!=0) {\n if (vendor!=VENDOR_ANY) {\n if (vendor != ((val>>8)&0xff))\n continue; \/* No match *\/\n }\n if (product!=PRODUCT_ANY) {\n if (product != (val&0xff))\n continue; \/* No match *\/\n }\n if (isRegistered(i))\n --instance; \/\/ Must decrement instance even for already-registered devices.\n continue;\n\n if (instance=0xff || --instance==0)\n return i;\n }\n }\n return NO_DEVICE;\n }\n\n int DeviceRegistry::getPPSInputPin(int masterslot, int offset)\n {\n return getPPSPin(masterslot,offset,16);\n }\n\n int DeviceRegistry::getPPSOutputPin(int masterslot, int offset)\n {\n return getPPSPin(masterslot,offset,0);\n }\n\n int DeviceRegistry::getPPSPin(int masterslot, int offset, int shift)\n {\n unsigned count = REGISTER(SYSCTLBASE, 32+shift);\n unsigned start = -1;\n register_t startreg = ®ISTER(SYSCTLBASE, 64);\n \n while(count--) {\n start++;\n unsigned val = *startreg++;\n unsigned char dev = (val>>shift)&0xff;\n if (dev!=masterslot) {\n continue;\n } else {\n int pin = (val>>(8+shift))&0xff;\n if (offset==0)\n return start;\n offset--;\n }\n }\n return -1;\n }\n\n uint32_t DeviceRegistry::m_sDeviceRegistry = 0;\n};\n<commit_msg>Fixed device scanner.<commit_after>#include \"DeviceRegistry.h\"\n#include \"register.h\"\n\nnamespace ZPUino {\n\n int DeviceRegistry::registerDevice(int slot) {\n if (slot>=MAX_SLOTS)\n return -2;\n if (m_sDeviceRegistry & (1<<slot))\n return -1;\n m_sDeviceRegistry |= (1<<slot);\n return 0;\n }\n\n uint8_t DeviceRegistry::scanDevice(unsigned vendor, unsigned product, int instance) {\n int i;\n for (i=0;i!=16;i++) {\n unsigned val = REGISTER(SYSCTLBASE,16+i);\n if (val!=0) {\n if (vendor!=VENDOR_ANY) {\n if (vendor != ((val>>8)&0xff))\n continue; \/* No match *\/\n }\n if (product!=PRODUCT_ANY) {\n if (product != (val&0xff))\n continue; \/* No match *\/\n }\n if (isRegistered(i))\n {\n --instance;\n continue;\n }\n\n if (instance==0xff || --instance==0)\n return i;\n }\n }\n return NO_DEVICE;\n }\n\n int DeviceRegistry::getPPSInputPin(int masterslot, int offset)\n {\n return getPPSPin(masterslot,offset,16);\n }\n\n int DeviceRegistry::getPPSOutputPin(int masterslot, int offset)\n {\n return getPPSPin(masterslot,offset,0);\n }\n\n int DeviceRegistry::getPPSPin(int masterslot, int offset, int shift)\n {\n unsigned count = REGISTER(SYSCTLBASE, 32+shift);\n unsigned start = -1;\n register_t startreg = ®ISTER(SYSCTLBASE, 64);\n \n while(count--) {\n start++;\n unsigned val = *startreg++;\n unsigned char dev = (val>>shift)&0xff;\n if (dev!=masterslot) {\n continue;\n } else {\n int pin = (val>>(8+shift))&0xff;\n if (offset==0)\n return start;\n offset--;\n }\n }\n return -1;\n }\n\n uint32_t DeviceRegistry::m_sDeviceRegistry = 0;\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n*\n* Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.\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#include \"MyPythonInterpreter.h\"\n#include <cstring>\nusing namespace std;\n#include \"..\/util\/WaspErrorMessage.h\"\n\n#ifdef ENABLE_PYTHON\n\nMyPythonInterpreter::MyPythonInterpreter(\n char* filename,\n string scriptDirectory,\n bool callPyFinalize_ ) : Interpreter(), callPyFinalize( callPyFinalize_ )\n{\n setenv( \"PYTHONPATH\", \".\", 1 );\n Py_Initialize();\n PyObject* pName = \n #ifdef PYTHON_THREE\n PyUnicode_FromString( filename );\n #else\n PyString_FromString( filename );\n #endif\n if( scriptDirectory != \"\" )\n {\n string s( \"import sys; sys.path.append('\" + scriptDirectory + \"')\" );\n PyRun_SimpleString( s.c_str() );\n }\n pModule = PyImport_Import( pName );\n Py_DECREF( pName );\n if( pModule == NULL )\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n string message = \"Module \" + string( filename ) + \" does not exist.\\n\"; \n WaspErrorMessage::errorGeneric( message );\n }\n}\n\nMyPythonInterpreter::~MyPythonInterpreter()\n{\n Py_XDECREF( pModule );\n if( callPyFinalize )\n Py_Finalize();\n}\n\nvoid\nMyPythonInterpreter::callListMethod(\n const string& method_name,\n const vector< int >& parameters,\n vector< int >& output )\n{\n if( pModule == NULL )\n return;\n PyObject* pFunc = PyObject_GetAttrString( pModule, method_name.c_str() );\n if( pFunc && PyCallable_Check( pFunc ) )\n {\n PyObject* pArgs = PyTuple_New( parameters.size() );\n for( unsigned int i = 0; i < parameters.size(); i++ )\n {\n PyObject* pParam = Py_BuildValue( \"i\", parameters[ i ] );\n PyTuple_SetItem( pArgs, i, pParam );\n }\n PyObject* result = PyObject_CallObject( pFunc, pArgs );\n if( result )\n {\n bool isInt = \n #ifdef PYTHON_THREE\n PyLong_Check( result );\n #else\n PyInt_Check( result );\n #endif\n if( PyList_Check( result ) )\n {\n int size = PyList_Size( result );\n for( int i = size - 1; i >= 0; i-- )\n {\n PyObject* item = PyList_GetItem( result, i ); \n bool isInt = \n #ifdef PYTHON_THREE\n PyLong_Check( item );\n #else\n PyInt_Check( item );\n #endif\n if( isInt )\n {\n int value = \n #ifdef PYTHON_THREE\n PyLong_AsLong( item );\n #else\n PyInt_AsLong( item );\n #endif\n output.push_back( value );\n }\n }\n Py_XDECREF( result );\n }\n else if( isInt )\n {\n int value = \n #ifdef PYTHON_THREE\n PyLong_AsLong( result );\n #else\n PyInt_AsLong( result );\n #endif\n output.push_back( value );\n }\n else if( PyErr_Occurred() )\n PyErr_Print();\n }\n else if( PyErr_Occurred() )\n PyErr_Print();\n Py_XDECREF( pArgs );\n }\n else\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n printf( \"Method %s not found\\n\", method_name.c_str() );\n }\n Py_XDECREF( pFunc );\n}\n\nvoid MyPythonInterpreter::callListMethod(\n const string& method_name,\n const vector< int >& parameters,\n vector< uint64_t >& output )\n{\n if( pModule == NULL )\n return;\n PyObject* pFunc = PyObject_GetAttrString( pModule,method_name.c_str() );\n if( pFunc && PyCallable_Check( pFunc ) )\n {\n PyObject* pArgs = PyTuple_New( parameters.size() );\n for( unsigned int i = 0; i < parameters.size(); i++ )\n {\n PyObject* pParam = Py_BuildValue( \"i\", parameters[ i ] );\n PyTuple_SetItem( pArgs, i, pParam );\n }\n PyObject* result = PyObject_CallObject( pFunc, pArgs );\n if( result )\n {\n bool isInt = PyLong_Check( result );\n if( PyList_Check( result ) )\n {\n int size = PyList_Size( result );\n for( int i = size - 1; i >= 0; i-- )\n {\n PyObject* item = PyList_GetItem( result, i );\n if( PyLong_Check( item ) )\n {\n uint64_t value = PyLong_AsUnsignedLongLongMask( item );\n output.push_back( value );\n }\n }\n Py_XDECREF( result );\n }\n else if( isInt )\n {\n uint64_t value =\n #ifdef PYTHON_THREE \n PyLong_AsUnsignedLongLongMask( result );\n #else\n PyInt_AsUnsignedLongLongMask( result );\n #endif\n output.push_back( value );\n }\n else if( PyErr_Occurred() )\n PyErr_Print();\n }\n else if( PyErr_Occurred() )\n PyErr_Print(); \n Py_XDECREF( pArgs );\n }\n else\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n printf(\"Method %s not found\\n\", method_name.c_str());\n }\n Py_XDECREF( pFunc ); \n}\n\nvoid MyPythonInterpreter::callVoidMethod(\n const string& method_name,\n int param1,\n const string& param2 )\n{\n if( pModule == NULL )\n return;\n PyObject* pFunc = PyObject_GetAttrString( pModule, method_name.c_str() );\n if( pFunc && PyCallable_Check( pFunc ) )\n {\n PyObject* pArgs = PyTuple_New( 2 );\n PyObject* param1_python = \n #ifdef PYTHON_THREE\n PyLong_FromSize_t( param1 );\n #else\n PyInt_FromSize_t( param1 );\n #endif\n\n PyObject* param2_python =\n #ifdef PYTHON_THREE\n PyUnicode_FromString( param2.c_str() );\n #else\n PyString_FromString( param2.c_str() );\n #endif\n\n PyTuple_SetItem( pArgs, 0, param1_python );\n PyTuple_SetItem( pArgs, 1, param2_python ); \n PyObject* result = PyObject_CallObject( pFunc, pArgs );\n if( result )\n Py_XDECREF( result );\n else if( PyErr_Occurred() )\n PyErr_Print();\n Py_XDECREF( pArgs );\n }\n else\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n printf( \"Method %s not found\\n\", method_name.c_str() );\n }\n Py_XDECREF( pFunc );\n}\n\nbool MyPythonInterpreter::checkMethod(\n const string& method_name ) const\n{\n bool res = false;\n if( pModule == NULL )\n return res;\n PyObject* pFunc = PyObject_GetAttrString( pModule, method_name.c_str() );\n if( pFunc && PyCallable_Check( pFunc ) )\n res = true;\n else if( PyErr_Occurred() )\n PyErr_Clear();\n \n Py_XDECREF( pFunc );\n return res;\n}\n\nvoid MyPythonInterpreter::addElementInMap(\n const string& map_name,\n const string& key,\n unsigned int value )\n{\n PyObject* pFunc = PyObject_GetAttrString( pModule, map_name.c_str() );\n if( pFunc )\n {\n PyObject* value_python = \n #ifdef PYTHON_THREE\n PyLong_FromSize_t( value );\n #else\n PyInt_FromSize_t( value );\n #endif\n\n char *cstr = new char[key.length() + 1];\n strcpy(cstr, key.c_str()); \n int res = PyMapping_SetItemString(pFunc, cstr, value_python);\n if( res == -1 || PyErr_Occurred() )\n PyErr_Print();\n delete [] cstr;\n }\n else\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n printf( \"Element %s not found\\n\", map_name.c_str() );\n }\n Py_XDECREF( pFunc );\n}\n\nbool MyPythonInterpreter::checkAttribute(\n const string& map_name ) const\n{\n bool res = false;\n if( pModule == NULL )\n return res;\n PyObject* pFunc = PyObject_GetAttrString( pModule, map_name.c_str() );\n if( pFunc )\n res = true;\n else if( PyErr_Occurred() )\n PyErr_Clear();\n \n Py_XDECREF( pFunc );\n return res;\n}\n\n#endif\n<commit_msg>Fixed bug of MyPythonInterpreter.<commit_after>\/*\n*\n* Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.\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#include \"MyPythonInterpreter.h\"\n#include <cstring>\nusing namespace std;\n#include \"..\/util\/WaspErrorMessage.h\"\n\n#ifdef ENABLE_PYTHON\n\nMyPythonInterpreter::MyPythonInterpreter(\n char* filename,\n string scriptDirectory,\n bool callPyFinalize_ ) : Interpreter(), callPyFinalize( callPyFinalize_ )\n{\n setenv( \"PYTHONPATH\", \".\", 1 );\n Py_Initialize();\n PyObject* pName =\n #ifdef PYTHON_THREE\n PyUnicode_FromString( filename );\n #else\n PyString_FromString( filename );\n #endif\n if( scriptDirectory != \"\" )\n {\n string s( \"import sys; sys.path.append('\" + scriptDirectory + \"')\" );\n PyRun_SimpleString( s.c_str() );\n }\n pModule = PyImport_Import( pName );\n Py_DECREF( pName );\n if( pModule == NULL )\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n string message = \"Module \" + string( filename ) + \" does not exist.\\n\";\n WaspErrorMessage::errorGeneric( message );\n }\n}\n\nMyPythonInterpreter::~MyPythonInterpreter()\n{\n if( callPyFinalize )\n Py_Finalize();\n}\n\nvoid\nMyPythonInterpreter::callListMethod(\n const string& method_name,\n const vector< int >& parameters,\n vector< int >& output )\n{\n if( pModule == NULL )\n return;\n PyObject* pFunc = PyObject_GetAttrString( pModule, method_name.c_str() );\n if( pFunc && PyCallable_Check( pFunc ) )\n {\n PyObject* pArgs = PyTuple_New( parameters.size() );\n for( unsigned int i = 0; i < parameters.size(); i++ )\n {\n PyObject* pParam = Py_BuildValue( \"i\", parameters[ i ] );\n PyTuple_SetItem( pArgs, i, pParam );\n }\n PyObject* result = PyObject_CallObject( pFunc, pArgs );\n if( result )\n {\n bool isInt =\n #ifdef PYTHON_THREE\n PyLong_Check( result );\n #else\n PyInt_Check( result );\n #endif\n if( PyList_Check( result ) )\n {\n int size = PyList_Size( result );\n for( int i = size - 1; i >= 0; i-- )\n {\n PyObject* item = PyList_GetItem( result, i );\n bool isInt =\n #ifdef PYTHON_THREE\n PyLong_Check( item );\n #else\n PyInt_Check( item );\n #endif\n if( isInt )\n {\n int value =\n #ifdef PYTHON_THREE\n PyLong_AsLong( item );\n #else\n PyInt_AsLong( item );\n #endif\n output.push_back( value );\n }\n }\n Py_XDECREF( result );\n }\n else if( isInt )\n {\n int value =\n #ifdef PYTHON_THREE\n PyLong_AsLong( result );\n #else\n PyInt_AsLong( result );\n #endif\n output.push_back( value );\n }\n else if( PyErr_Occurred() )\n PyErr_Print();\n }\n else if( PyErr_Occurred() )\n PyErr_Print();\n Py_XDECREF( pArgs );\n }\n else\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n printf( \"Method %s not found\\n\", method_name.c_str() );\n }\n Py_XDECREF( pFunc );\n}\n\nvoid MyPythonInterpreter::callListMethod(\n const string& method_name,\n const vector< int >& parameters,\n vector< uint64_t >& output )\n{\n if( pModule == NULL )\n return;\n PyObject* pFunc = PyObject_GetAttrString( pModule,method_name.c_str() );\n if( pFunc && PyCallable_Check( pFunc ) )\n {\n PyObject* pArgs = PyTuple_New( parameters.size() );\n for( unsigned int i = 0; i < parameters.size(); i++ )\n {\n PyObject* pParam = Py_BuildValue( \"i\", parameters[ i ] );\n PyTuple_SetItem( pArgs, i, pParam );\n }\n PyObject* result = PyObject_CallObject( pFunc, pArgs );\n if( result )\n {\n bool isInt = PyLong_Check( result );\n if( PyList_Check( result ) )\n {\n int size = PyList_Size( result );\n for( int i = size - 1; i >= 0; i-- )\n {\n PyObject* item = PyList_GetItem( result, i );\n if( PyLong_Check( item ) )\n {\n uint64_t value = PyLong_AsUnsignedLongLongMask( item );\n output.push_back( value );\n }\n }\n Py_XDECREF( result );\n }\n else if( isInt )\n {\n uint64_t value =\n #ifdef PYTHON_THREE\n PyLong_AsUnsignedLongLongMask( result );\n #else\n PyInt_AsUnsignedLongLongMask( result );\n #endif\n output.push_back( value );\n }\n else if( PyErr_Occurred() )\n PyErr_Print();\n }\n else if( PyErr_Occurred() )\n PyErr_Print();\n Py_XDECREF( pArgs );\n }\n else\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n printf(\"Method %s not found\\n\", method_name.c_str());\n }\n Py_XDECREF( pFunc );\n}\n\nvoid MyPythonInterpreter::callVoidMethod(\n const string& method_name,\n int param1,\n const string& param2 )\n{\n if( pModule == NULL )\n return;\n PyObject* pFunc = PyObject_GetAttrString( pModule, method_name.c_str() );\n if( pFunc && PyCallable_Check( pFunc ) )\n {\n PyObject* pArgs = PyTuple_New( 2 );\n PyObject* param1_python =\n #ifdef PYTHON_THREE\n PyLong_FromSize_t( param1 );\n #else\n PyInt_FromSize_t( param1 );\n #endif\n\n PyObject* param2_python =\n #ifdef PYTHON_THREE\n PyUnicode_FromString( param2.c_str() );\n #else\n PyString_FromString( param2.c_str() );\n #endif\n\n PyTuple_SetItem( pArgs, 0, param1_python );\n PyTuple_SetItem( pArgs, 1, param2_python );\n PyObject* result = PyObject_CallObject( pFunc, pArgs );\n if( result )\n Py_XDECREF( result );\n else if( PyErr_Occurred() )\n PyErr_Print();\n Py_XDECREF( pArgs );\n }\n else\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n printf( \"Method %s not found\\n\", method_name.c_str() );\n }\n Py_XDECREF( pFunc );\n}\n\nbool MyPythonInterpreter::checkMethod(\n const string& method_name ) const\n{\n bool res = false;\n if( pModule == NULL )\n return res;\n PyObject* pFunc = PyObject_GetAttrString( pModule, method_name.c_str() );\n if( pFunc && PyCallable_Check( pFunc ) )\n res = true;\n else if( PyErr_Occurred() )\n PyErr_Clear();\n\n Py_XDECREF( pFunc );\n return res;\n}\n\nvoid MyPythonInterpreter::addElementInMap(\n const string& map_name,\n const string& key,\n unsigned int value )\n{\n PyObject* pFunc = PyObject_GetAttrString( pModule, map_name.c_str() );\n if( pFunc )\n {\n PyObject* value_python =\n #ifdef PYTHON_THREE\n PyLong_FromSize_t( value );\n #else\n PyInt_FromSize_t( value );\n #endif\n\n char *cstr = new char[key.length() + 1];\n strcpy(cstr, key.c_str());\n int res = PyMapping_SetItemString(pFunc, cstr, value_python);\n if( res == -1 || PyErr_Occurred() )\n PyErr_Print();\n delete [] cstr;\n }\n else\n {\n if( PyErr_Occurred() )\n PyErr_Print();\n printf( \"Element %s not found\\n\", map_name.c_str() );\n }\n Py_XDECREF( pFunc );\n}\n\nbool MyPythonInterpreter::checkAttribute(\n const string& map_name ) const\n{\n bool res = false;\n if( pModule == NULL )\n return res;\n PyObject* pFunc = PyObject_GetAttrString( pModule, map_name.c_str() );\n if( pFunc )\n res = true;\n else if( PyErr_Occurred() )\n PyErr_Clear();\n\n Py_XDECREF( pFunc );\n return res;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgeoareamonitor_polling_p.h\"\n#include \"qgeocoordinate.h\"\n\nQTM_BEGIN_NAMESPACE\n\n#define UPDATE_INTERVAL_5S 5000\n\nQGeoAreaMonitorPolling::QGeoAreaMonitorPolling(QObject *parent) : QGeoAreaMonitor(parent)\n{\n insideArea = false;\n location = QGeoPositionInfoSource::createDefaultSource(this);\n if (location) {\n location->setUpdateInterval(UPDATE_INTERVAL_5S);\n connect(location, SIGNAL(positionUpdated(QGeoPositionInfo)),\n this, SLOT(positionUpdated(QGeoPositionInfo)));\n }\n}\n\nQGeoAreaMonitorPolling::~QGeoAreaMonitorPolling()\n{\n if (location)\n location->stopUpdates();\n}\n\nvoid QGeoAreaMonitorPolling::setCenter(const QGeoCoordinate& coordinate)\n{\n if (coordinate.isValid()) {\n QGeoAreaMonitor::setCenter(coordinate);\n checkStartStop();\n }\n}\n\nvoid QGeoAreaMonitorPolling::setRadius(qreal radius)\n{\n QGeoAreaMonitor::setRadius(radius);\n checkStartStop();\n}\n\nvoid QGeoAreaMonitorPolling::connectNotify(const char *signal)\n{\n if (signal == SIGNAL(areaEntered(QGeoPositionInfo)) ||\n signal == SIGNAL(areaExited(QGeoPositionInfo)))\n checkStartStop();\n}\n\nvoid QGeoAreaMonitorPolling::disconnectNotify(const char *signal)\n{\n if (signal == SIGNAL(areaEntered(QGeoPositionInfo)) ||\n signal == SIGNAL(areaExited(QGeoPositionInfo)))\n checkStartStop();\n}\n\nvoid QGeoAreaMonitorPolling::checkStartStop()\n{\n if (!location) return;\n\n if (QObject::receivers(SIGNAL(areaEntered(QGeoPositionInfo))) > 0 &&\n QObject::receivers(SIGNAL(areaExited(QGeoPositionInfo))) > 0 &&\n QGeoAreaMonitor::center().isValid() &&\n QGeoAreaMonitor::radius() > qreal(0.0)) {\n location->startUpdates();\n } else {\n location->stopUpdates();\n }\n}\n\nvoid QGeoAreaMonitorPolling::positionUpdated(const QGeoPositionInfo &info)\n{\n double distance = info.coordinate().distanceTo(QGeoAreaMonitor::center());\n\n if (distance <= QGeoAreaMonitor::radius()) {\n if (!insideArea)\n emit areaEntered(info);\n insideArea = true;\n } else if (insideArea) {\n emit areaExited(info);\n insideArea = false;\n }\n}\n\n#include \"moc_qgeoareamonitor_polling_p.cpp\"\nQTM_END_NAMESPACE\n<commit_msg>Fix to start\/stop logic in QGeoAreaMonitorPolling<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgeoareamonitor_polling_p.h\"\n#include \"qgeocoordinate.h\"\n\nQTM_BEGIN_NAMESPACE\n\n#define UPDATE_INTERVAL_5S 5000\n\nQGeoAreaMonitorPolling::QGeoAreaMonitorPolling(QObject *parent) : QGeoAreaMonitor(parent)\n{\n insideArea = false;\n location = QGeoPositionInfoSource::createDefaultSource(this);\n if (location) {\n location->setUpdateInterval(UPDATE_INTERVAL_5S);\n connect(location, SIGNAL(positionUpdated(QGeoPositionInfo)),\n this, SLOT(positionUpdated(QGeoPositionInfo)));\n }\n}\n\nQGeoAreaMonitorPolling::~QGeoAreaMonitorPolling()\n{\n if (location)\n location->stopUpdates();\n}\n\nvoid QGeoAreaMonitorPolling::setCenter(const QGeoCoordinate& coordinate)\n{\n if (coordinate.isValid()) {\n QGeoAreaMonitor::setCenter(coordinate);\n checkStartStop();\n }\n}\n\nvoid QGeoAreaMonitorPolling::setRadius(qreal radius)\n{\n QGeoAreaMonitor::setRadius(radius);\n checkStartStop();\n}\n\nvoid QGeoAreaMonitorPolling::connectNotify(const char *signal)\n{\n if (signal == SIGNAL(areaEntered(QGeoPositionInfo)) ||\n signal == SIGNAL(areaExited(QGeoPositionInfo)))\n checkStartStop();\n}\n\nvoid QGeoAreaMonitorPolling::disconnectNotify(const char *signal)\n{\n if (signal == SIGNAL(areaEntered(QGeoPositionInfo)) ||\n signal == SIGNAL(areaExited(QGeoPositionInfo)))\n checkStartStop();\n}\n\nvoid QGeoAreaMonitorPolling::checkStartStop()\n{\n if (!location) return;\n\n if ((QObject::receivers(SIGNAL(areaEntered(QGeoPositionInfo))) > 0 ||\n QObject::receivers(SIGNAL(areaExited(QGeoPositionInfo))) > 0) &&\n QGeoAreaMonitor::center().isValid() &&\n QGeoAreaMonitor::radius() > qreal(0.0)) {\n location->startUpdates();\n } else {\n location->stopUpdates();\n }\n}\n\nvoid QGeoAreaMonitorPolling::positionUpdated(const QGeoPositionInfo &info)\n{\n double distance = info.coordinate().distanceTo(QGeoAreaMonitor::center());\n\n if (distance <= QGeoAreaMonitor::radius()) {\n if (!insideArea)\n emit areaEntered(info);\n insideArea = true;\n } else if (insideArea) {\n emit areaExited(info);\n insideArea = false;\n }\n}\n\n#include \"moc_qgeoareamonitor_polling_p.cpp\"\nQTM_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\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 \"iceoryx_posh\/internal\/runtime\/message_queue_message.hpp\"\n\n#include <algorithm>\n\nnamespace iox\n{\nnamespace runtime\n{\nconst char MqMessage::m_separator = ',';\n\nMqMessage::MqMessage(const std::initializer_list<std::string>& msg) noexcept\n{\n for (auto element : msg)\n {\n addEntry(element);\n }\n}\n\nMqMessage::MqMessage(const std::string& msg) noexcept\n{\n setMessage(msg);\n}\n\nuint32_t MqMessage::getNumberOfElements() const noexcept\n{\n return m_numberOfElements;\n}\n\nstd::string MqMessage::getElementAtIndex(const uint32_t index) const noexcept\n{\n std::string messageRemainder(m_msg);\n size_t startPos = 0;\n size_t endPos = messageRemainder.find_first_of(m_separator, startPos);\n\n for (uint32_t counter = 0; endPos != std::string::npos; ++counter)\n {\n if (counter == index)\n {\n return messageRemainder.substr(startPos, endPos - startPos);\n }\n\n startPos = endPos + 1;\n endPos = messageRemainder.find_first_of(m_separator, startPos);\n }\n\n return std::string();\n}\n\nbool MqMessage::isValidEntry(const std::string& entry) const noexcept\n{\n if (entry.find(m_separator) != std::string::npos)\n {\n return false;\n }\n return true;\n}\n\nbool MqMessage::isValid() const noexcept\n{\n return m_isValid;\n}\n\nstd::string MqMessage::getMessage() const noexcept\n{\n return m_msg;\n}\n\nvoid MqMessage::setMessage(const std::string& msg) noexcept\n{\n clearMessage();\n\n m_msg = msg;\n if (m_msg.back() != m_separator && m_msg.size() > 0) \/\/\/ @todo shouldn't this be \"if (m_msg.size() == 0 || m_msg.back() != m_separator)\"???\n {\n m_isValid = false;\n }\n else\n {\n m_numberOfElements = static_cast<uint32_t>(\n std::count_if(m_msg.begin(), m_msg.end(), [&](char c) { return c == m_separator; }));\n }\n}\n\nvoid MqMessage::clearMessage() noexcept\n{\n m_msg.clear();\n m_numberOfElements = 0;\n m_isValid = true;\n}\n\nbool MqMessage::operator==(const MqMessage& rhs) const noexcept\n{\n return this->getMessage() == rhs.getMessage();\n}\n\n} \/\/ namespace runtime\n} \/\/ namespace iox\n<commit_msg>iox-#33 we have to first check if the message is not empty and then check the last character<commit_after>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\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 \"iceoryx_posh\/internal\/runtime\/message_queue_message.hpp\"\n\n#include <algorithm>\n\nnamespace iox\n{\nnamespace runtime\n{\nconst char MqMessage::m_separator = ',';\n\nMqMessage::MqMessage(const std::initializer_list<std::string>& msg) noexcept\n{\n for (auto element : msg)\n {\n addEntry(element);\n }\n}\n\nMqMessage::MqMessage(const std::string& msg) noexcept\n{\n setMessage(msg);\n}\n\nuint32_t MqMessage::getNumberOfElements() const noexcept\n{\n return m_numberOfElements;\n}\n\nstd::string MqMessage::getElementAtIndex(const uint32_t index) const noexcept\n{\n std::string messageRemainder(m_msg);\n size_t startPos = 0;\n size_t endPos = messageRemainder.find_first_of(m_separator, startPos);\n\n for (uint32_t counter = 0; endPos != std::string::npos; ++counter)\n {\n if (counter == index)\n {\n return messageRemainder.substr(startPos, endPos - startPos);\n }\n\n startPos = endPos + 1;\n endPos = messageRemainder.find_first_of(m_separator, startPos);\n }\n\n return std::string();\n}\n\nbool MqMessage::isValidEntry(const std::string& entry) const noexcept\n{\n if (entry.find(m_separator) != std::string::npos)\n {\n return false;\n }\n return true;\n}\n\nbool MqMessage::isValid() const noexcept\n{\n return m_isValid;\n}\n\nstd::string MqMessage::getMessage() const noexcept\n{\n return m_msg;\n}\n\nvoid MqMessage::setMessage(const std::string& msg) noexcept\n{\n clearMessage();\n\n m_msg = msg;\n if (!m_msg.empty() && m_msg.back() != m_separator)\n {\n m_isValid = false;\n }\n else\n {\n m_numberOfElements =\n static_cast<uint32_t>(std::count_if(m_msg.begin(), m_msg.end(), [&](char c) { return c == m_separator; }));\n }\n}\n\nvoid MqMessage::clearMessage() noexcept\n{\n m_msg.clear();\n m_numberOfElements = 0;\n m_isValid = true;\n}\n\nbool MqMessage::operator==(const MqMessage& rhs) const noexcept\n{\n return this->getMessage() == rhs.getMessage();\n}\n\n} \/\/ namespace runtime\n} \/\/ namespace iox\n<|endoftext|>"} {"text":"<commit_before>\/\/ To parse this JSON data, first install\n\/\/\n\/\/ Boost http:\/\/www.boost.org\n\/\/ json.hpp https:\/\/github.com\/nlohmann\/json\n\/\/\n\/\/ Then include this file, and then do\n\/\/\n\/\/ SPIInProperties.hpp data = nlohmann::json::parse(jsonString);\n\n#pragma once\n\n#include <nlohmann\/json.hpp>\n\nnamespace dai {\n\n\/**\n * Properties for SPIIn node\n *\/\nstruct SPIInProperties {\n \/**\n * Name of stream\n *\/\n std::string streamName;\n\n \/**\n * SPI bus to use\n *\/\n int busId;\n\n \/**\n * Maximum input data size\n *\/\n std::uint32_t maxDataSize = dai::XLINK_USB_BUFFER_MAX_SIZE;\n\n \/**\n * Number of frames in pool\n *\/\n std::uint32_t numFrames = 4;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(SPIInProperties, streamName, busId);\n\n} \/\/ namespace dai\n<commit_msg>Fix includes in SPIInProperties.hpp<commit_after>#pragma once\n\n#include <nlohmann\/json.hpp>\n\n#include \"depthai-shared\/xlink\/XLinkConstants.hpp\"\n\nnamespace dai {\n\n\/**\n * Properties for SPIIn node\n *\/\nstruct SPIInProperties {\n \/**\n * Name of stream\n *\/\n std::string streamName;\n\n \/**\n * SPI bus to use\n *\/\n int busId;\n\n \/**\n * Maximum input data size\n *\/\n std::uint32_t maxDataSize = dai::XLINK_USB_BUFFER_MAX_SIZE;\n\n \/**\n * Number of frames in pool\n *\/\n std::uint32_t numFrames = 4;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(SPIInProperties, streamName, busId, maxDataSize, numFrames);\n\n} \/\/ namespace dai\n<|endoftext|>"} {"text":"<commit_before>#include \"ASTImportSource.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n\nusing namespace clang;\n\nnamespace {\n class ClingASTImporter : public ASTImporter {\n private:\n cling::ASTImportSource& m_source;\n\n public:\n ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager,\n ASTContext &FromContext, FileManager &FromFileManager,\n bool MinimalImport, cling::ASTImportSource& source) : \n ASTImporter(ToContext, ToFileManager, FromContext,\n FromFileManager, MinimalImport), m_source(source) {}\n\n Decl *Imported(Decl *From, Decl *To) override {\n ASTImporter::Imported(From, To);\n\n \/\/ Put the name of the Decl imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n if (DeclContext *declContextParent = llvm::dyn_cast<DeclContext>(From)) {\n DeclContext *declContextChild = llvm::dyn_cast<DeclContext>(To);\n m_source.addToDeclContext(declContextChild, declContextParent); \n }\n \n return To;\n }\n\n };\n}\n\nnamespace cling {\n\n ASTImportSource::ASTImportSource(const cling::Interpreter *parent_interpreter,\n cling::Interpreter *child_interpreter) :\n m_parent_Interp(parent_interpreter), m_child_Interp(child_interpreter) {\n\n clang::DeclContext *parentTUDeclContext =\n clang::TranslationUnitDecl::castToDeclContext(\n m_parent_Interp->getCI()->getASTContext().getTranslationUnitDecl());\n\n clang::DeclContext *childTUDeclContext =\n clang::TranslationUnitDecl::castToDeclContext(\n m_child_Interp->getCI()->getASTContext().getTranslationUnitDecl());\n\n \/\/ Also keep in the map of Decl Contexts the Translation Unit Decl Context\n m_DeclContexts_map[childTUDeclContext] = parentTUDeclContext;\n }\n\n void ASTImportSource::ImportDecl(Decl *declToImport,\n ASTImporter &importer,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName,\n const DeclContext *childCurrentDeclContext) {\n\n \/\/ Don't do the import if we have a Function Template.\n \/\/ Not supported by clang.\n \/\/ FIXME: This is also a temporary check. Will be de-activated\n \/\/ once clang supports the import of function templates.\n if (declToImport->isFunctionOrFunctionTemplate() && declToImport->isTemplateDecl())\n return;\n\n if (Decl *importedDecl = importer.Import(declToImport)) {\n if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDecl)) {\n std::vector < NamedDecl * > declVector{importedNamedDecl};\n llvm::ArrayRef < NamedDecl * > FoundDecls(declVector);\n SetExternalVisibleDeclsForName(childCurrentDeclContext,\n importedNamedDecl->getDeclName(),\n FoundDecls);\n }\n \/\/ Put the name of the Decl imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n m_DeclName_map[childDeclName] = parentDeclName;\n }\n }\n\n void ASTImportSource::ImportDeclContext(DeclContext *declContextToImport,\n ASTImporter &importer,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName,\n const DeclContext *childCurrentDeclContext) {\n\n if (DeclContext *importedDeclContext = importer.ImportContext(declContextToImport)) {\n\n importedDeclContext->setHasExternalVisibleStorage(true);\n\n if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDeclContext)) {\n std::vector < NamedDecl * > declVector{importedNamedDecl};\n llvm::ArrayRef < NamedDecl * > FoundDecls(declVector);\n SetExternalVisibleDeclsForName(childCurrentDeclContext,\n importedNamedDecl->getDeclName(),\n FoundDecls);\n }\n \/\/ Put the name of the DeclContext imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n m_DeclName_map[childDeclName] = parentDeclName;\n\n \/\/ And also put the declaration context I found from the parent Interpreter\n \/\/ in the map of the child Interpreter to have it for the future.\n m_DeclContexts_map[importedDeclContext] = declContextToImport;\n }\n }\n\n bool ASTImportSource::Import(DeclContext::lookup_result lookup_result,\n ASTContext &from_ASTContext,\n ASTContext &to_ASTContext,\n const DeclContext *childCurrentDeclContext,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName) {\n\n \/\/ Prepare to import the Decl(Context) we found in the\n \/\/ child interpreter by getting the file managers from\n \/\/ each interpreter.\n FileManager &child_FM = m_child_Interp->getCI()->getFileManager();\n FileManager &parent_FM = m_parent_Interp->getCI()->getFileManager();\n\n \/\/ Cling's ASTImporter\n ClingASTImporter importer(to_ASTContext, child_FM,\n from_ASTContext, parent_FM,\n \/*MinimalImport : ON*\/ true, *this);\n\n for (DeclContext::lookup_iterator I = lookup_result.begin(),\n E = lookup_result.end();\n I != E; ++I) {\n \/\/ Check if this Name we are looking for is\n \/\/ a DeclContext (for example a Namespace, function etc.).\n if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) {\n\n ImportDeclContext(declContextToImport, importer, childDeclName,\n parentDeclName, childCurrentDeclContext);\n\n } else if (Decl *declToImport = llvm::dyn_cast<Decl>(*I)) {\n\n \/\/ else it is a Decl\n ImportDecl(declToImport, importer, childDeclName,\n parentDeclName, childCurrentDeclContext);\n }\n }\n return true;\n }\n\n \/\/\/\\brief This is the most important function of the class ASTImportSource\n \/\/\/ since from here initiates the lookup and import part of the missing\n \/\/\/ Decl(s) (Contexts).\n \/\/\/\n bool ASTImportSource::FindExternalVisibleDeclsByName(\n const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) {\n\n assert(childDeclName && \"Child Decl name is empty\");\n\n assert(childCurrentDeclContext->hasExternalVisibleStorage() &&\n \"DeclContext has no visible decls in storage\");\n\n \/\/Check if we have already found this declaration Name before\n DeclarationName parentDeclName;\n std::map<clang::DeclarationName,\n clang::DeclarationName>::iterator II = m_DeclName_map.find(childDeclName);\n if (II != m_DeclName_map.end()) {\n parentDeclName = II->second;\n } else {\n \/\/ Get the identifier info from the parent interpreter\n \/\/ for this Name.\n std::string name = childDeclName.getAsString();\n if (!name.empty()) {\n llvm::StringRef nameRef(name);\n IdentifierTable &parentIdentifierTable =\n m_parent_Interp->getCI()->getASTContext().Idents;\n IdentifierInfo &parentIdentifierInfo =\n parentIdentifierTable.get(nameRef);\n parentDeclName = DeclarationName(&parentIdentifierInfo);\n }\n }\n\n \/\/ Search in the map of the stored Decl Contexts for this\n \/\/ Decl Context.\n std::map<const clang::DeclContext *, clang::DeclContext *>::iterator I;\n \/\/ If childCurrentDeclContext was found before and is already in the map,\n \/\/ then do the lookup using the stored pointer.\n if ((I = m_DeclContexts_map.find(childCurrentDeclContext))\n != m_DeclContexts_map.end()) {\n DeclContext *parentDeclContext = I->second;\n\n Decl *fromDeclContext = Decl::castFromDeclContext(parentDeclContext);\n ASTContext &from_ASTContext = fromDeclContext->getASTContext();\n\n Decl *toDeclContext = Decl::castFromDeclContext(childCurrentDeclContext);\n ASTContext &to_ASTContext = toDeclContext->getASTContext();\n\n DeclContext::lookup_result lookup_result =\n parentDeclContext->lookup(parentDeclName);\n\n \/\/ Check if we found this Name in the parent interpreter\n if (!lookup_result.empty()) {\n \/\/ Do the import\n if (Import(lookup_result, from_ASTContext, to_ASTContext,\n childCurrentDeclContext, childDeclName, parentDeclName))\n return true;\n }\n }\n return false;\n }\n\n \/\/\/\\brief Make available to child all decls in parent's decl context\n \/\/\/ that corresponds to child decl context.\n void ASTImportSource::completeVisibleDeclsMap(\n const clang::DeclContext *childDeclContext) {\n assert (childDeclContext && \"No child decl context!\");\n\n if (!childDeclContext->hasExternalVisibleStorage())\n return;\n\n \/\/ Search in the map of the stored Decl Contexts for this\n \/\/ Decl Context.\n std::map<const clang::DeclContext *, clang::DeclContext *>::iterator I;\n \/\/ If childCurrentDeclContext was found before and is already in the map,\n \/\/ then do the lookup using the stored pointer.\n if ((I = m_DeclContexts_map.find(childDeclContext))\n != m_DeclContexts_map.end()) {\n\n DeclContext *parentDeclContext = I->second;\n\n Decl *fromDeclContext = Decl::castFromDeclContext(parentDeclContext);\n ASTContext &from_ASTContext = fromDeclContext->getASTContext();\n\n Decl *toDeclContext = Decl::castFromDeclContext(childDeclContext);\n ASTContext &to_ASTContext = toDeclContext->getASTContext();\n\n \/\/ Prepare to import the Decl(Context) we found in the\n \/\/ child interpreter by getting the file managers from\n \/\/ each interpreter.\n FileManager &child_FM = m_child_Interp->getCI()->getFileManager();\n FileManager &parent_FM = m_parent_Interp->getCI()->getFileManager();\n\n \/\/ Cling's ASTImporter\n ClingASTImporter importer(to_ASTContext, child_FM,\n from_ASTContext, parent_FM,\n \/*MinimalImport : ON*\/ true, *this);\n\n for (DeclContext::decl_iterator I_decl = parentDeclContext->decls_begin(),\n E_decl = parentDeclContext->decls_end(); I_decl != E_decl; ++I_decl) {\n if (NamedDecl* parentNamedDecl = llvm::dyn_cast<NamedDecl>(*I_decl)) {\n DeclarationName newDeclName = parentNamedDecl->getDeclName();\n ImportDecl(parentNamedDecl, importer, newDeclName, newDeclName,\n childDeclContext);\n }\n }\n\n const_cast<DeclContext *>(childDeclContext)->\n setHasExternalVisibleStorage(false);\n }\n }\n\n} \/\/ end namespace cling\n<commit_msg>Mark the external visibility of imported decls.<commit_after>#include \"ASTImportSource.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n\nusing namespace clang;\n\nnamespace {\n class ClingASTImporter : public ASTImporter {\n private:\n cling::ASTImportSource& m_source;\n\n public:\n ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager,\n ASTContext &FromContext, FileManager &FromFileManager,\n bool MinimalImport, cling::ASTImportSource& source) : \n ASTImporter(ToContext, ToFileManager, FromContext,\n FromFileManager, MinimalImport), m_source(source) {}\n\n Decl *Imported(Decl *From, Decl *To) override {\n ASTImporter::Imported(From, To);\n\n if (isa<TagDecl>(From)) {\n clang::TagDecl* toTagDecl = dyn_cast<TagDecl>(To);\n toTagDecl->setHasExternalVisibleStorage();\n }\n\n if (isa<NamespaceDecl>(From))\n {\n NamespaceDecl *to_namespace_decl = dyn_cast<NamespaceDecl>(To);\n to_namespace_decl->setHasExternalVisibleStorage();\n }\n \n if (isa<ObjCContainerDecl>(From))\n {\n ObjCContainerDecl *to_container_decl = dyn_cast<ObjCContainerDecl>(To);\n to_container_decl->setHasExternalLexicalStorage();\n to_container_decl->setHasExternalVisibleStorage();\n }\n\n \/\/ Put the name of the Decl imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n if (DeclContext *declContextParent = llvm::dyn_cast<DeclContext>(From)) {\n DeclContext *declContextChild = llvm::dyn_cast<DeclContext>(To);\n m_source.addToDeclContext(declContextChild, declContextParent); \n }\n\n return To;\n }\n\n };\n}\n\nnamespace cling {\n\n ASTImportSource::ASTImportSource(const cling::Interpreter *parent_interpreter,\n cling::Interpreter *child_interpreter) :\n m_parent_Interp(parent_interpreter), m_child_Interp(child_interpreter) {\n\n clang::DeclContext *parentTUDeclContext =\n clang::TranslationUnitDecl::castToDeclContext(\n m_parent_Interp->getCI()->getASTContext().getTranslationUnitDecl());\n\n clang::DeclContext *childTUDeclContext =\n clang::TranslationUnitDecl::castToDeclContext(\n m_child_Interp->getCI()->getASTContext().getTranslationUnitDecl());\n\n \/\/ Also keep in the map of Decl Contexts the Translation Unit Decl Context\n m_DeclContexts_map[childTUDeclContext] = parentTUDeclContext;\n }\n\n void ASTImportSource::ImportDecl(Decl *declToImport,\n ASTImporter &importer,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName,\n const DeclContext *childCurrentDeclContext) {\n\n \/\/ Don't do the import if we have a Function Template.\n \/\/ Not supported by clang.\n \/\/ FIXME: This is also a temporary check. Will be de-activated\n \/\/ once clang supports the import of function templates.\n if (declToImport->isFunctionOrFunctionTemplate() && declToImport->isTemplateDecl())\n return;\n \n \/\/cling::Interpreter::PushTransactionRAII RAII(parent_int);\n if (Decl *importedDecl = importer.Import(declToImport)) {\n if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDecl)) {\n std::vector < NamedDecl * > declVector{importedNamedDecl};\n llvm::ArrayRef < NamedDecl * > FoundDecls(declVector);\n SetExternalVisibleDeclsForName(childCurrentDeclContext,\n importedNamedDecl->getDeclName(),\n FoundDecls);\n }\n \/\/ Put the name of the Decl imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n m_DeclName_map[childDeclName] = parentDeclName;\n }\n }\n\n void ASTImportSource::ImportDeclContext(DeclContext *declContextToImport,\n ASTImporter &importer,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName,\n const DeclContext *childCurrentDeclContext) {\n\n if (DeclContext *importedDeclContext = importer.ImportContext(declContextToImport)) {\n\n importedDeclContext->setHasExternalVisibleStorage(true);\n\n if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDeclContext)) {\n std::vector < NamedDecl * > declVector{importedNamedDecl};\n llvm::ArrayRef < NamedDecl * > FoundDecls(declVector);\n SetExternalVisibleDeclsForName(childCurrentDeclContext,\n importedNamedDecl->getDeclName(),\n FoundDecls);\n }\n \/\/ Put the name of the DeclContext imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n m_DeclName_map[childDeclName] = parentDeclName;\n\n \/\/ And also put the declaration context I found from the parent Interpreter\n \/\/ in the map of the child Interpreter to have it for the future.\n m_DeclContexts_map[importedDeclContext] = declContextToImport;\n }\n }\n\n bool ASTImportSource::Import(DeclContext::lookup_result lookup_result,\n ASTContext &from_ASTContext,\n ASTContext &to_ASTContext,\n const DeclContext *childCurrentDeclContext,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName) {\n\n \/\/ Prepare to import the Decl(Context) we found in the\n \/\/ child interpreter by getting the file managers from\n \/\/ each interpreter.\n FileManager &child_FM = m_child_Interp->getCI()->getFileManager();\n FileManager &parent_FM = m_parent_Interp->getCI()->getFileManager();\n\n \/\/ Cling's ASTImporter\n ClingASTImporter importer(to_ASTContext, child_FM,\n from_ASTContext, parent_FM,\n \/*MinimalImport : ON*\/ true, *this);\n\n for (DeclContext::lookup_iterator I = lookup_result.begin(),\n E = lookup_result.end();\n I != E; ++I) {\n \/\/ Check if this Name we are looking for is\n \/\/ a DeclContext (for example a Namespace, function etc.).\n if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) {\n\n ImportDeclContext(declContextToImport, importer, childDeclName,\n parentDeclName, childCurrentDeclContext);\n\n } else if (Decl *declToImport = llvm::dyn_cast<Decl>(*I)) {\n\n \/\/ else it is a Decl\n ImportDecl(declToImport, importer, childDeclName,\n parentDeclName, childCurrentDeclContext);\n }\n }\n return true;\n }\n\n \/\/\/\\brief This is the most important function of the class ASTImportSource\n \/\/\/ since from here initiates the lookup and import part of the missing\n \/\/\/ Decl(s) (Contexts).\n \/\/\/\n bool ASTImportSource::FindExternalVisibleDeclsByName(\n const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) {\n\n assert(childDeclName && \"Child Decl name is empty\");\n\n assert(childCurrentDeclContext->hasExternalVisibleStorage() &&\n \"DeclContext has no visible decls in storage\");\n\n \/\/Check if we have already found this declaration Name before\n DeclarationName parentDeclName;\n std::map<clang::DeclarationName,\n clang::DeclarationName>::iterator II = m_DeclName_map.find(childDeclName);\n if (II != m_DeclName_map.end()) {\n parentDeclName = II->second;\n } else {\n \/\/ Get the identifier info from the parent interpreter\n \/\/ for this Name.\n std::string name = childDeclName.getAsString();\n if (!name.empty()) {\n llvm::StringRef nameRef(name);\n IdentifierTable &parentIdentifierTable =\n m_parent_Interp->getCI()->getASTContext().Idents;\n IdentifierInfo &parentIdentifierInfo =\n parentIdentifierTable.get(nameRef);\n parentDeclName = DeclarationName(&parentIdentifierInfo);\n }\n }\n\n \/\/ Search in the map of the stored Decl Contexts for this\n \/\/ Decl Context.\n std::map<const clang::DeclContext *, clang::DeclContext *>::iterator I;\n \/\/ If childCurrentDeclContext was found before and is already in the map,\n \/\/ then do the lookup using the stored pointer.\n if ((I = m_DeclContexts_map.find(childCurrentDeclContext))\n != m_DeclContexts_map.end()) {\n DeclContext *parentDeclContext = I->second;\n\n Decl *fromDeclContext = Decl::castFromDeclContext(parentDeclContext);\n ASTContext &from_ASTContext = fromDeclContext->getASTContext();\n\n Decl *toDeclContext = Decl::castFromDeclContext(childCurrentDeclContext);\n ASTContext &to_ASTContext = toDeclContext->getASTContext();\n\n DeclContext::lookup_result lookup_result =\n parentDeclContext->lookup(parentDeclName);\n\n \/\/ Check if we found this Name in the parent interpreter\n if (!lookup_result.empty()) {\n \/\/ Do the import\n if (Import(lookup_result, from_ASTContext, to_ASTContext,\n childCurrentDeclContext, childDeclName, parentDeclName))\n return true;\n }\n }\n return false;\n }\n\n \/\/\/\\brief Make available to child all decls in parent's decl context\n \/\/\/ that corresponds to child decl context.\n void ASTImportSource::completeVisibleDeclsMap(\n const clang::DeclContext *childDeclContext) {\n assert (childDeclContext && \"No child decl context!\");\n\n if (!childDeclContext->hasExternalVisibleStorage())\n return;\n\n \/\/ Search in the map of the stored Decl Contexts for this\n \/\/ Decl Context.\n std::map<const clang::DeclContext *, clang::DeclContext *>::iterator I;\n \/\/ If childCurrentDeclContext was found before and is already in the map,\n \/\/ then do the lookup using the stored pointer.\n if ((I = m_DeclContexts_map.find(childDeclContext))\n != m_DeclContexts_map.end()) {\n\n DeclContext *parentDeclContext = I->second;\n\n Decl *fromDeclContext = Decl::castFromDeclContext(parentDeclContext);\n ASTContext &from_ASTContext = fromDeclContext->getASTContext();\n\n Decl *toDeclContext = Decl::castFromDeclContext(childDeclContext);\n ASTContext &to_ASTContext = toDeclContext->getASTContext();\n\n \/\/ Prepare to import the Decl(Context) we found in the\n \/\/ child interpreter by getting the file managers from\n \/\/ each interpreter.\n FileManager &child_FM = m_child_Interp->getCI()->getFileManager();\n FileManager &parent_FM = m_parent_Interp->getCI()->getFileManager();\n\n \/\/ Cling's ASTImporter\n ClingASTImporter importer(to_ASTContext, child_FM,\n from_ASTContext, parent_FM,\n \/*MinimalImport : ON*\/ true, *this);\n\n StringRef filter = m_child_Interp->getCI()->getPreprocessor().getCodeCompletionFilter();\n for (DeclContext::decl_iterator I_decl = parentDeclContext->decls_begin(),\n E_decl = parentDeclContext->decls_end(); I_decl != E_decl; ++I_decl) {\n if (NamedDecl* parentNamedDecl = llvm::dyn_cast<NamedDecl>(*I_decl)) {\n \/\/ Filter using the stem from the input line\n DeclarationName newDeclName = parentNamedDecl->getDeclName();\n if (newDeclName.getAsIdentifierInfo()) {\n StringRef name = newDeclName.getAsIdentifierInfo()->getName();\n if (!name.empty() && name.startswith(filter))\n ImportDecl(parentNamedDecl, importer, newDeclName, newDeclName,\n childDeclContext);\n }\n }\n }\n\n const_cast<DeclContext *>(childDeclContext)->\n setHasExternalVisibleStorage(false);\n }\n }\n\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"<commit_before>\/*\n * (C) Copyright 2013 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\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 *\/\n\n#include <config.h>\n\n#include <glibmm.h>\n#include <fstream>\n#include <iostream>\n#include <boost\/filesystem.hpp>\n#include \"version.hpp\"\n#include <glib\/gstdio.h>\n#include <ftw.h>\n\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n#include <boost\/log\/utility\/setup\/common_attributes.hpp>\n\n#include \"TransportFactory.hpp\"\n\n#include <SignalHandler.hpp>\n#include <ServerMethods.hpp>\n#include <gst\/gst.h>\n\n#include <boost\/program_options.hpp>\n#include <boost\/exception\/diagnostic_information.hpp>\n\n#include \"logging.hpp\"\n#include \"modules.hpp\"\n\n#define GST_CAT_DEFAULT kurento_media_server\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaServer\"\n\nconst std::string DEFAULT_CONFIG_FILE = \"\/etc\/kurento\/kurento.conf.json\";\nconst std::string ENV_PREFIX = \"KURENTO_\";\n\nusing namespace ::kurento;\nnamespace logging = boost::log;\n\nGlib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create ();\n\nstatic std::shared_ptr<Transport>\nload_config (boost::property_tree::ptree &config, const std::string &file_name)\n{\n std::shared_ptr<Transport> transport;\n boost::filesystem::path configFilePath (file_name);\n GST_INFO (\"Reading configuration from: %s\", file_name.c_str () );\n\n try {\n boost::property_tree::read_json (file_name, config);\n } catch (boost::property_tree::ptree_error &e) {\n GST_ERROR (\"Error reading configuration: %s\", e.what() );\n std::cerr << \"Error reading configuration: \" << e.what() << std::endl;\n exit (1);\n }\n\n config.add (\"configPath\", configFilePath.parent_path().string() );\n\n GST_INFO (\"Configuration loaded successfully\");\n\n std::shared_ptr<ServerMethods> serverMethods (new ServerMethods (config) );\n\n try {\n transport = TransportFactory::create_transport (config, serverMethods);\n } catch (std::exception &e) {\n GST_ERROR (\"Error creating transport: %s\", e.what() );\n exit (1);\n }\n\n return transport;\n}\n\nstatic void\nsignal_handler (uint32_t signo)\n{\n static unsigned int __terminated = 0;\n\n switch (signo) {\n case SIGINT:\n case SIGTERM:\n if (__terminated == 0) {\n GST_DEBUG (\"Terminating.\");\n loop->quit ();\n }\n\n __terminated = 1;\n break;\n\n case SIGPIPE:\n GST_DEBUG (\"Ignore sigpipe signal\");\n break;\n\n case SIGSEGV:\n GST_DEBUG (\"Segmentation fault. Aborting process execution\");\n abort ();\n\n default:\n break;\n }\n}\n\nstatic void\nkms_init_dependencies (int argc, char **argv)\n{\n Glib::init();\n\n gst_init (&argc, &argv);\n\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n\n \/* Initialization routine to add commonly used *\/\n \/* attributes to the logging system *\/\n logging::add_common_attributes();\n}\n\nint\nmain (int argc, char **argv)\n{\n sigset_t mask;\n std::shared_ptr <SignalHandler> signalHandler;\n std::shared_ptr<Transport> transport;\n boost::property_tree::ptree config;\n std::string confFile;\n std::string path, logs_path;\n\n kms_init_dependencies (argc, argv);\n\n try {\n boost::program_options::options_description desc (\"kurento-media-server usage\");\n\n desc.add_options()\n (\"help,h\", \"Display this help message\")\n (\"version,v\", \"Display the version number\")\n (\"list,l\", \"Lists all available factories\")\n (\"modules-path,p\", boost::program_options::value<std::string>\n (&path), \"Path where kurento modules can be found\")\n (\"conf-file,f\", boost::program_options::value<std::string>\n (&confFile)->default_value (DEFAULT_CONFIG_FILE),\n \"Configuration file location\")\n (\"logs-path,d\", boost::program_options::value <std::string> (&logs_path),\n \"Path where debug files will be stored\");\n\n boost::program_options::command_line_parser clp (argc, argv);\n clp.options (desc).allow_unregistered();\n boost::program_options::variables_map vm;\n auto parsed = clp.run();\n boost::program_options::store (parsed, vm);\n\n boost::program_options::store (boost::program_options::parse_environment (desc,\n [&desc] (std::string & input) -> std::string {\n \/* Look for KURENTO_ prefix and change to lower case *\/\n if (input.find (ENV_PREFIX) == 0)\n {\n std::string aux = input.substr (ENV_PREFIX.size() );\n std::transform (aux.begin(), aux.end(), aux.begin(), [] (int c) -> int {\n return (c == '_') ? '-' : tolower (c);\n });\n\n if (!desc.find_nothrow (aux, false) ) {\n return \"\";\n }\n\n return aux;\n }\n\n\n return \"\";\n }), vm);\n\n boost::program_options::notify (vm);\n\n if (vm.count (\"logs-path\") ) {\n if (kms_init_logging (logs_path) ) {\n GST_DEBUG (\"Dumping logs to %s\", logs_path.c_str() );\n } else {\n GST_WARNING (\"Can no set debugging path %s\", logs_path.c_str() );\n }\n }\n\n if (vm.count (\"help\") ) {\n std::cout << desc << \"\\n\";\n exit (0);\n }\n\n if (vm.count (\"version\") || vm.count (\"list\") ) {\n \/\/ Disable log to just print version\n gst_debug_remove_log_function_by_data (NULL);\n }\n\n loadModules (path);\n\n if (vm.count (\"list\") ) {\n std::cout << \"Available factories:\" << std::endl;\n\n for (auto it : kurento::getModuleManager().getLoadedFactories() ) {\n std::cout << \"\\t\" << it.first << std::endl;\n }\n\n exit (0);\n }\n\n if (vm.count (\"version\") ) {\n print_version();\n exit (0);\n }\n\n } catch (boost::program_options::error &e) {\n std::cerr << \"Error : \" << e.what() << std::endl;\n exit (1);\n }\n\n \/* Install our signal handler *\/\n sigemptyset (&mask);\n sigaddset (&mask, SIGINT);\n sigaddset (&mask, SIGTERM);\n sigaddset (&mask, SIGSEGV);\n sigaddset (&mask, SIGPIPE);\n signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask,\n signal_handler) );\n\n GST_INFO (\"Kmsc version: %s\", get_version () );\n\n transport = load_config (config, confFile);\n\n \/* Start transport *\/\n transport->start ();\n\n GST_INFO (\"Mediaserver started\");\n\n loop->run ();\n\n transport->stop();\n\n GST_INFO (\"Mediaserver stopped\");\n\n return 0;\n}\n<commit_msg>Allow loading different config files for external modules<commit_after>\/*\n * (C) Copyright 2013 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\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 *\/\n\n#include <config.h>\n\n#include <queue>\n#include <boost\/foreach.hpp>\n\n#include <glibmm.h>\n#include <fstream>\n#include <iostream>\n#include <boost\/filesystem.hpp>\n#include \"version.hpp\"\n#include <glib\/gstdio.h>\n#include <ftw.h>\n\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n#include <boost\/log\/utility\/setup\/common_attributes.hpp>\n\n#include \"TransportFactory.hpp\"\n\n#include <SignalHandler.hpp>\n#include <ServerMethods.hpp>\n#include <gst\/gst.h>\n\n#include <boost\/program_options.hpp>\n#include <boost\/exception\/diagnostic_information.hpp>\n\n#include \"logging.hpp\"\n#include \"modules.hpp\"\n\n#define GST_CAT_DEFAULT kurento_media_server\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaServer\"\n\nconst std::string DEFAULT_CONFIG_FILE = \"\/etc\/kurento\/kurento.conf.json\";\nconst std::string ENV_PREFIX = \"KURENTO_\";\n\nusing namespace ::kurento;\nnamespace logging = boost::log;\n\nGlib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create ();\n\nstatic std::list<std::string>\nsplit (const std::string &s, char delim)\n{\n std::list<std::string> elems;\n std::stringstream ss (s);\n std::string item;\n\n while (std::getline (ss, item, delim) ) {\n elems.push_back (item);\n }\n\n return elems;\n}\n\nstatic void\nmergePropertyTrees (boost::property_tree::ptree &ptMerged,\n const boost::property_tree::ptree &rptSecond )\n{\n \/\/ Keep track of keys and values (subtrees) in second property tree\n std::queue<std::string> qKeys;\n std::queue<boost::property_tree::ptree> qValues;\n qValues.push ( rptSecond );\n\n \/\/ Iterate over second property tree\n while ( !qValues.empty() ) {\n \/\/ Setup keys and corresponding values\n boost::property_tree::ptree ptree = qValues.front();\n qValues.pop();\n std::string keychain;\n\n if ( !qKeys.empty() ) {\n keychain = qKeys.front();\n qKeys.pop();\n }\n\n BOOST_FOREACH ( const boost::property_tree::ptree::value_type & child, ptree ) {\n if ( child.second.size() == 0 ) {\n std::string s;\n\n if ( !keychain.empty() ) {\n s = keychain + \".\" + child.first.data();\n } else {\n s = child.first.data();\n }\n\n \/\/ Put into combined property tree\n ptMerged.put ( s, child.second.data() );\n } else {\n \/\/ Put keys (identifiers of subtrees) and all of its parents (where present)\n \/\/ aside for later iteration.\n if ( !keychain.empty() ) {\n qKeys.push ( keychain + \".\" + child.first.data() );\n } else {\n qKeys.push ( child.first.data() );\n }\n\n \/\/ Put values (the subtrees) aside, too\n qValues.push ( child.second );\n }\n }\n }\n}\n\nstatic void\nloadModulesConfigFromDir (boost::property_tree::ptree &config,\n const boost::filesystem::path &dir, const boost::filesystem::path &parentDir)\n{\n GST_INFO (\"Looking for config files in %s\", dir.string().c_str() );\n\n if (!boost::filesystem::is_directory (dir) ) {\n GST_WARNING (\"Unable to load config files from: %s, it is not a directory\",\n dir.string().c_str() );\n return;\n }\n\n boost::filesystem::directory_iterator end_itr;\n\n for ( boost::filesystem::directory_iterator itr ( dir ); itr != end_itr;\n ++itr ) {\n if (boost::filesystem::is_regular (*itr) ) {\n boost::filesystem::path extension = itr->path().extension();\n boost::filesystem::path extension2 = itr->path().stem().extension();\n std::string fileName = itr->path().filename().string();\n\n if (extension.string() == \".json\" && extension2.string() == \".conf\") {\n boost::property_tree::ptree moduleConfig;\n\n boost::property_tree::read_json (itr->path().string(), moduleConfig);\n\n moduleConfig.add (\"configPath\", itr->path().parent_path().string() );\n\n {\n boost::filesystem::path diffpath;\n\n boost::filesystem::path tmppath = itr->path().parent_path();\n\n while (tmppath != parentDir) {\n diffpath = tmppath.stem() \/ diffpath;\n tmppath = tmppath.parent_path();\n }\n\n tmppath = diffpath;\n\n boost::property_tree::ptree loadedConfig;\n std::string key = \"modules\";\n\n for (auto it = tmppath.begin(); it != tmppath.end(); it ++) {\n key += \".\" + it->string();\n }\n\n fileName = fileName.substr (0, fileName.size() - extension.string().size() );\n fileName = fileName.substr (0, fileName.size() - extension2.string().size() );\n\n key += \".\" + fileName;\n\n loadedConfig.put_child (key, moduleConfig);\n\n mergePropertyTrees (config, loadedConfig);\n }\n\n GST_INFO (\"Loaded module config from: %s\", itr->path().string().c_str() );\n }\n } else if (boost::filesystem::is_directory (*itr) ) {\n loadModulesConfigFromDir (config, itr->path(), parentDir);\n }\n }\n}\n\nstatic void\nloadModulesConfig (boost::property_tree::ptree &config,\n const boost::filesystem::path &configFilePath, std::string modulesConfigPath)\n{\n std::list <std::string> locations;\n\n if (modulesConfigPath.empty() ) {\n boost::filesystem::path modulesConfigDir = configFilePath.parent_path() \/\n \"modules\";\n\n modulesConfigPath = modulesConfigDir.string();\n }\n\n locations = split (modulesConfigPath, ':');\n\n for (std::string location : locations) {\n boost::filesystem::path dir (location);\n\n loadModulesConfigFromDir (config, dir, dir);\n }\n}\n\nstatic std::shared_ptr<Transport>\nload_config (boost::property_tree::ptree &config, const std::string &file_name,\n const std::string &modulesConfigPath)\n{\n std::shared_ptr<Transport> transport;\n boost::filesystem::path configFilePath (file_name);\n GST_INFO (\"Reading configuration from: %s\", file_name.c_str () );\n\n try {\n boost::property_tree::read_json (file_name, config);\n } catch (boost::property_tree::ptree_error &e) {\n GST_ERROR (\"Error reading configuration: %s\", e.what() );\n std::cerr << \"Error reading configuration: \" << e.what() << std::endl;\n exit (1);\n }\n\n loadModulesConfig (config, configFilePath, modulesConfigPath);\n\n config.add (\"configPath\", configFilePath.parent_path().string() );\n\n GST_INFO (\"Configuration loaded successfully\");\n\n std::ostringstream oss;\n boost::property_tree::write_json (oss, config, true);\n std::string jsonConfig = oss.str();\n\n GST_DEBUG (\"Effective loaded config:\\n%s\", jsonConfig.c_str() );\n\n std::shared_ptr<ServerMethods> serverMethods (new ServerMethods (config) );\n\n try {\n transport = TransportFactory::create_transport (config, serverMethods);\n } catch (std::exception &e) {\n GST_ERROR (\"Error creating transport: %s\", e.what() );\n exit (1);\n }\n\n return transport;\n}\n\nstatic void\nsignal_handler (uint32_t signo)\n{\n static unsigned int __terminated = 0;\n\n switch (signo) {\n case SIGINT:\n case SIGTERM:\n if (__terminated == 0) {\n GST_DEBUG (\"Terminating.\");\n loop->quit ();\n }\n\n __terminated = 1;\n break;\n\n case SIGPIPE:\n GST_DEBUG (\"Ignore sigpipe signal\");\n break;\n\n case SIGSEGV:\n GST_DEBUG (\"Segmentation fault. Aborting process execution\");\n abort ();\n\n default:\n break;\n }\n}\n\nstatic void\nkms_init_dependencies (int argc, char **argv)\n{\n Glib::init();\n\n gst_init (&argc, &argv);\n\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n\n \/* Initialization routine to add commonly used *\/\n \/* attributes to the logging system *\/\n logging::add_common_attributes();\n}\n\nint\nmain (int argc, char **argv)\n{\n sigset_t mask;\n std::shared_ptr <SignalHandler> signalHandler;\n std::shared_ptr<Transport> transport;\n boost::property_tree::ptree config;\n std::string confFile;\n std::string path, logs_path, modulesConfigPath;\n\n kms_init_dependencies (argc, argv);\n\n try {\n boost::program_options::options_description desc (\"kurento-media-server usage\");\n\n desc.add_options()\n (\"help,h\", \"Display this help message\")\n (\"version,v\", \"Display the version number\")\n (\"list,l\", \"Lists all available factories\")\n (\"modules-path,p\", boost::program_options::value<std::string>\n (&path), \"Path where kurento modules can be found\")\n (\"conf-file,f\", boost::program_options::value<std::string>\n (&confFile)->default_value (DEFAULT_CONFIG_FILE),\n \"Configuration file location\")\n (\"logs-path,d\", boost::program_options::value <std::string> (&logs_path),\n \"Path where debug files will be stored\")\n (\"modules-config-path,c\",\n boost::program_options::value <std::string> (&modulesConfigPath),\n \"Path where modules config files can be found\");\n\n boost::program_options::command_line_parser clp (argc, argv);\n clp.options (desc).allow_unregistered();\n boost::program_options::variables_map vm;\n auto parsed = clp.run();\n boost::program_options::store (parsed, vm);\n\n boost::program_options::store (boost::program_options::parse_environment (desc,\n [&desc] (std::string & input) -> std::string {\n \/* Look for KURENTO_ prefix and change to lower case *\/\n if (input.find (ENV_PREFIX) == 0)\n {\n std::string aux = input.substr (ENV_PREFIX.size() );\n std::transform (aux.begin(), aux.end(), aux.begin(), [] (int c) -> int {\n return (c == '_') ? '-' : tolower (c);\n });\n\n if (!desc.find_nothrow (aux, false) ) {\n return \"\";\n }\n\n return aux;\n }\n\n\n return \"\";\n }), vm);\n\n boost::program_options::notify (vm);\n\n if (vm.count (\"logs-path\") ) {\n if (kms_init_logging (logs_path) ) {\n GST_DEBUG (\"Dumping logs to %s\", logs_path.c_str() );\n } else {\n GST_WARNING (\"Can no set debugging path %s\", logs_path.c_str() );\n }\n }\n\n if (vm.count (\"help\") ) {\n std::cout << desc << \"\\n\";\n exit (0);\n }\n\n if (vm.count (\"version\") || vm.count (\"list\") ) {\n \/\/ Disable log to just print version\n gst_debug_remove_log_function_by_data (NULL);\n }\n\n loadModules (path);\n\n if (vm.count (\"list\") ) {\n std::cout << \"Available factories:\" << std::endl;\n\n for (auto it : kurento::getModuleManager().getLoadedFactories() ) {\n std::cout << \"\\t\" << it.first << std::endl;\n }\n\n exit (0);\n }\n\n if (vm.count (\"version\") ) {\n print_version();\n exit (0);\n }\n\n } catch (boost::program_options::error &e) {\n std::cerr << \"Error : \" << e.what() << std::endl;\n exit (1);\n }\n\n \/* Install our signal handler *\/\n sigemptyset (&mask);\n sigaddset (&mask, SIGINT);\n sigaddset (&mask, SIGTERM);\n sigaddset (&mask, SIGSEGV);\n sigaddset (&mask, SIGPIPE);\n signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask,\n signal_handler) );\n\n GST_INFO (\"Kmsc version: %s\", get_version () );\n\n transport = load_config (config, confFile, modulesConfigPath);\n\n \/* Start transport *\/\n transport->start ();\n\n GST_INFO (\"Mediaserver started\");\n\n loop->run ();\n\n transport->stop();\n\n GST_INFO (\"Mediaserver stopped\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * PrimeSieve.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\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, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n#include \"PrimeSieve.h\"\n#include \"defs.h\"\n#include \"ParallelPrimeSieve.h\"\n#include \"pmath.h\"\n#include \"ResetSieve.h\"\n#include \"PrimeNumberFinder.h\"\n#include \"PrimeNumberGenerator.h\"\n\n#include <stdexcept>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\nPrimeSieve::PrimeSieve() :\n startNumber_(0), stopNumber_(0),\n sieveSize_(defs::SIEVESIZE_PRIMENUMBERFINDER), flags_(COUNT_PRIMES),\n timeElapsed_(0.0) {\n parent_ = this;\n this->reset();\n}\n\n\/**\n * Is used by ParallelPrimeSieve which uses multiple PrimeSieve\n * objects and threads to sieve primes in parallel.\n * @see ParallelPrimeSieve::sieve()\n *\/\nPrimeSieve::PrimeSieve(uint64_t startNumber, uint64_t stopNumber, \n ParallelPrimeSieve* parent) :\n sieveSize_(parent->sieveSize_), flags_(parent->flags_), timeElapsed_(0.0),\n callback_imp(parent->callback_imp),\n callback_oop(parent->callback_oop),\n cbObj_(parent->cbObj_),\n parent_(parent) {\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->reset();\n}\n\nuint64_t PrimeSieve::getStartNumber() const {\n return startNumber_;\n}\n\nuint64_t PrimeSieve::getStopNumber() const {\n return stopNumber_;\n}\n\nuint32_t PrimeSieve::getSieveSize() const {\n return sieveSize_ \/ 1024;\n}\n\nuint32_t PrimeSieve::getFlags() const {\n return flags_;\n}\n\n\/**\n * Generate the prime numbers between startNumber and stopNumber and\n * call a callback function for each prime.\n *\/\nvoid PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,\n void (*callback)(uint64_t)) {\n if (callback == NULL)\n throw std::invalid_argument(\"callback must not be NULL\");\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->setFlags(CALLBACK_PRIMES_IMP);\n callback_imp = callback;\n this->sieve();\n}\n\n\/**\n * Generate the prime numbers between startNumber and stopNumber and\n * call an OOP style callback function for each prime.\n *\/\nvoid PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,\n void (*callback)(uint64_t, void*), void* cbObj) {\n if (callback == NULL)\n throw std::invalid_argument(\"callback must not be NULL\");\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->setFlags(CALLBACK_PRIMES_OOP);\n callback_oop = callback;\n cbObj_ = cbObj;\n this->sieve();\n}\n\n\/**\n * Get the count of prime numbers between startNumber and stopNumber.\n *\/\nuint64_t PrimeSieve::getPrimeCount(uint64_t startNumber, uint64_t stopNumber) {\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->setFlags(COUNT_PRIMES);\n this->sieve();\n return this->getPrimeCount();\n}\n\n\/**\n * Get the count of prime numbers between startNumber and stopNumber\n * after having called sieve().\n *\/\nuint64_t PrimeSieve::getPrimeCount() const {\n return counts_[0];\n}\n\n\/**\n * Get the count of twin primes between startNumber and stopNumber\n * after having called sieve().\n *\/\nuint64_t PrimeSieve::getTwinCount() const {\n return counts_[1];\n}\n\n\/**\n * Get the count of prime triplets between startNumber and stopNumber\n * after having called sieve().\n *\/\nuint64_t PrimeSieve::getTripletCount() const {\n return counts_[2];\n}\n\n\/**\n * Get the count of prime quadruplets between startNumber and\n * stopNumber after having called sieve().\n *\/\nuint64_t PrimeSieve::getQuadrupletCount() const {\n return counts_[3];\n}\n\n\/**\n * Get the count of prime quintuplets between startNumber and\n * stopNumber after having called sieve().\n *\/\nuint64_t PrimeSieve::getQuintupletCount() const {\n return counts_[4];\n}\n\n\/**\n * Get the count of prime sextuplets between startNumber and\n * stopNumber after having called sieve().\n *\/\nuint64_t PrimeSieve::getSextupletCount() const {\n return counts_[5];\n}\n\n\/**\n * Get the count of prime septuplets between startNumber and\n * stopNumber after having called sieve().\n *\/\nuint64_t PrimeSieve::getSeptupletCount() const {\n return counts_[6];\n}\n\n\/**\n * Get the count of prime numbers or prime k-tuplets between\n * startNumber and stopNumber after having called sieve().\n * e.g type = 0 for prime numbers,\n * type = 1 for twin primes,\n * type = 2 for prime triplets,\n * ...\n * @param type <= 7\n *\/\nuint64_t PrimeSieve::getCounts(uint32_t type) const {\n if (type >= COUNTS_SIZE)\n throw std::out_of_range(\"getCounts(uint32_t) type out of range\");\n return counts_[type];\n}\n\n\/**\n * Get the time elapsed in seconds of the last sieve session.\n *\/\ndouble PrimeSieve::getTimeElapsed() const {\n return timeElapsed_;\n}\n\n\/**\n * Set a start number for sieving.\n * @pre startNumber < (2^64-1) - (2^32-1) * 10\n *\/\nvoid PrimeSieve::setStartNumber(uint64_t startNumber) {\n \/\/ EratBig and EratMedium stopNumber limit\n if (startNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))\n throw std::invalid_argument(\"START must be < (2^64-1) - (2^32-1) * 10\");\n startNumber_ = startNumber;\n}\n\n\/**\n * Set a stop number for sieving.\n * @pre stopNumber < (2^64-1) - (2^32-1) * 10\n *\/\nvoid PrimeSieve::setStopNumber(uint64_t stopNumber) {\n \/\/ EratBig and EratMedium stopNumber limit\n if (stopNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))\n throw std::invalid_argument(\"STOP must be < (2^64-1) - (2^32-1) * 10\");\n stopNumber_ = stopNumber;\n}\n\n\/**\n * Set the size (in KiloBytes) of the sieve of Eratosthenes array.\n * The best performance is achieved with a sieve size that matches\n * the CPU's L1 cache size (usually 32 or 64 KB) when sieving < 10^14\n * and a sieve size of your CPU's L2 cache size above.\n *\n * Default sieveSize = 64 KiloBytes\n *\n * @pre sieveSize must be a power of 2,\n * sieveSize >= 1 KiloByte,\n * sieveSize <= 8192 KiloBytes.\n *\/\nvoid PrimeSieve::setSieveSize(uint32_t sieveSize) {\n \/\/ SieveOfEratosthenes lower sieve size limit AND \n \/\/ EratBig upper sieveSize limit\n if (sieveSize < 1 || sieveSize > 8192)\n throw std::invalid_argument(\"sieve size must be >= 1 and <= 8192 KiloBytes\");\n \/\/ EratBig requires a power of 2 sieve size\n if (!isPowerOf2(sieveSize))\n throw std::invalid_argument(\"sieve size must be a power of 2\");\n \/\/ convert to Bytes\n sieveSize_ = sieveSize * 1024;\n}\n\n\/**\n * Set the flags (settings) of PrimeSieve.\n * @param flags\n * COUNT_PRIMES OR (bitwise '|')\n * COUNT_TWINS OR\n * COUNT_TRIPLETS OR\n * COUNT_QUADRUPLETS OR\n * COUNT_QUINTUPLETS OR\n * COUNT_SEXTUPLETS OR\n * COUNT_SEPTUPLETS OR\n * PRINT_PRIMES OR\n * PRINT_TWINS OR\n * PRINT_TRIPLETS OR\n * PRINT_QUADRUPLETS OR\n * PRINT_QUINTUPLETS OR\n * PRINT_SEXTUPLETS OR\n * PRINT_SEPTUPLETS OR\n * PRINT_STATUS.\n *\/\nvoid PrimeSieve::setFlags(uint32_t flags) {\n flags_ = flags;\n}\n\nvoid PrimeSieve::reset() {\n segments_ = 0;\n for (uint32_t i = 0; i < COUNTS_SIZE; i++)\n counts_[i] = 0;\n status_ = -1.0;\n parent_->doStatus(0);\n}\n\n\/**\n * Print the status (in percent) of the sieving process\n * to the standard output.\n *\/\nvoid PrimeSieve::doStatus(uint64_t segment) {\n segments_ += segment;\n double old = status_;\n status_ = static_cast<double> (segments_) \/\n static_cast<double> (1 + stopNumber_ - startNumber_) * 100.0;\n if (static_cast<int> (status_) > 99)\n status_ = 100.0;\n if ((flags_ & PRINT_STATUS) &&\n static_cast<int> (status_) > static_cast<int> (old)) {\n std::cout << '\\r' << static_cast<int> (status_) << '%' << std::flush;\n }\n}\n\nvoid PrimeSieve::doSmallPrime(uint32_t low, uint32_t high, uint32_t type, \n std::string prime) {\n if (startNumber_ <= low && stopNumber_ >= high) {\n if (flags_ & (COUNT_PRIMES << type))\n counts_[type]++;\n if (flags_ & (PRINT_PRIMES << type))\n std::cout << prime << std::endl;\n else if (flags_ & CALLBACK_PRIMES_IMP)\n this->callback_imp(prime[0]-'0');\n else if (flags_ & CALLBACK_PRIMES_OOP)\n this->callback_oop(prime[0]-'0', cbObj_);\n }\n}\n\n\/**\n * Sieve the prime numbers and\/or prime k-tuplets between startNumber\n * and stopNumber.\n *\/\nvoid PrimeSieve::sieve() {\n if (stopNumber_ < startNumber_)\n throw std::invalid_argument(\"STOP must be >= START\");\n timeElapsed_ = static_cast<double> (std::clock());\n this->reset();\n\n \/\/ small primes have to be examined manually\n if (startNumber_ <= 5) {\n this->doSmallPrime(2, 2, 0, \"2\");\n this->doSmallPrime(3, 3, 0, \"3\");\n this->doSmallPrime(5, 5, 0, \"5\");\n this->doSmallPrime(3, 5, 1, \"(3, 5)\");\n this->doSmallPrime(5, 7, 1, \"(5, 7)\");\n this->doSmallPrime(5, 11, 2, \"(5, 7, 11)\");\n this->doSmallPrime(5, 13, 3, \"(5, 7, 11, 13)\");\n this->doSmallPrime(5, 17, 4, \"(5, 7, 11, 13, 17)\");\n }\n\n if (stopNumber_ >= 7) {\n \/\/ needed by primeNumberGenerator and primeNumberFinder to\n \/\/ reset their sieve arrays\n ResetSieve resetSieve(this);\n \/\/ used to sieve the prime numbers and prime k-tuplets between\n \/\/ startNumber_ and stopNumber_\n PrimeNumberFinder primeNumberFinder(this, resetSieve);\n\n if (isqrt(stopNumber_) > resetSieve.getEliminateUpTo()) {\n \/\/ used to generate the prime numbers up to sqrt(stopNumber_)\n \/\/ needed for sieving by primeNumberFinder\n PrimeNumberGenerator primeNumberGenerator(&primeNumberFinder);\n std::vector<uint32_t> primes16Bit;\n primes16Bit.push_back(3);\n uint32_t stop = isqrt(primeNumberGenerator.getStopNumber());\n uint32_t keep = isqrt(stop);\n \/\/ the following trial division algorithm is used to generate the\n \/\/ prime numbers up to stopNumber_^0.25 needed for sieving by\n \/\/ primeNumberGenerator. Although the algorithm is never\n \/\/ used > 65536 it finds the prime numbers up to 10^7 in 1 second\n \/\/ on an Intel Core i5-670 3.46GHz\n for (uint32_t n = 5; n <= stop; n += 2) {\n uint32_t s = isqrt(n);\n uint32_t i = 0;\n for (; primes16Bit[i] <= s && (n % primes16Bit[i]) != 0; i++)\n ;\n if (primes16Bit[i] > s) {\n if (primes16Bit[i] <= keep)\n primes16Bit.push_back(n);\n if (n > resetSieve.getEliminateUpTo())\n \/\/ generate the prime numbers up to n^2 and call\n \/\/ primeNumberFinder.sieve(p) for each generated prime\n primeNumberGenerator.sieve(n);\n }\n }\n primeNumberGenerator.finish();\n }\n primeNumberFinder.finish();\n }\n\n \/\/ set status_ to 100.0 (percent)\n parent_->doStatus(10);\n timeElapsed_ = (static_cast<double> (std::clock()) - timeElapsed_) \/\n static_cast<double> (CLOCKS_PER_SEC);\n}\n<commit_msg>ResetSieve API has changed<commit_after>\/*\n * PrimeSieve.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\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, either version 3 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. 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 <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n#include \"PrimeSieve.h\"\n#include \"defs.h\"\n#include \"ParallelPrimeSieve.h\"\n#include \"pmath.h\"\n#include \"ResetSieve.h\"\n#include \"PrimeNumberFinder.h\"\n#include \"PrimeNumberGenerator.h\"\n\n#include <stdexcept>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\nPrimeSieve::PrimeSieve() :\n startNumber_(0), stopNumber_(0),\n sieveSize_(defs::SIEVESIZE_PRIMENUMBERFINDER), flags_(COUNT_PRIMES),\n timeElapsed_(0.0) {\n parent_ = this;\n this->reset();\n}\n\n\/**\n * Is used by ParallelPrimeSieve which uses multiple PrimeSieve\n * objects and threads to sieve primes in parallel.\n * @see ParallelPrimeSieve::sieve()\n *\/\nPrimeSieve::PrimeSieve(uint64_t startNumber, uint64_t stopNumber, \n ParallelPrimeSieve* parent) :\n sieveSize_(parent->sieveSize_), flags_(parent->flags_), timeElapsed_(0.0),\n callback_imp(parent->callback_imp),\n callback_oop(parent->callback_oop),\n cbObj_(parent->cbObj_),\n parent_(parent) {\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->reset();\n}\n\nuint64_t PrimeSieve::getStartNumber() const {\n return startNumber_;\n}\n\nuint64_t PrimeSieve::getStopNumber() const {\n return stopNumber_;\n}\n\nuint32_t PrimeSieve::getSieveSize() const {\n return sieveSize_ \/ 1024;\n}\n\nuint32_t PrimeSieve::getFlags() const {\n return flags_;\n}\n\n\/**\n * Generate the prime numbers between startNumber and stopNumber and\n * call a callback function for each prime.\n *\/\nvoid PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,\n void (*callback)(uint64_t)) {\n if (callback == NULL)\n throw std::invalid_argument(\"callback must not be NULL\");\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->setFlags(CALLBACK_PRIMES_IMP);\n callback_imp = callback;\n this->sieve();\n}\n\n\/**\n * Generate the prime numbers between startNumber and stopNumber and\n * call an OOP style callback function for each prime.\n *\/\nvoid PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,\n void (*callback)(uint64_t, void*), void* cbObj) {\n if (callback == NULL)\n throw std::invalid_argument(\"callback must not be NULL\");\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->setFlags(CALLBACK_PRIMES_OOP);\n callback_oop = callback;\n cbObj_ = cbObj;\n this->sieve();\n}\n\n\/**\n * Get the count of prime numbers between startNumber and stopNumber.\n *\/\nuint64_t PrimeSieve::getPrimeCount(uint64_t startNumber, uint64_t stopNumber) {\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->setFlags(COUNT_PRIMES);\n this->sieve();\n return this->getPrimeCount();\n}\n\n\/**\n * Get the count of prime numbers between startNumber and stopNumber\n * after having called sieve().\n *\/\nuint64_t PrimeSieve::getPrimeCount() const {\n return counts_[0];\n}\n\n\/**\n * Get the count of twin primes between startNumber and stopNumber\n * after having called sieve().\n *\/\nuint64_t PrimeSieve::getTwinCount() const {\n return counts_[1];\n}\n\n\/**\n * Get the count of prime triplets between startNumber and stopNumber\n * after having called sieve().\n *\/\nuint64_t PrimeSieve::getTripletCount() const {\n return counts_[2];\n}\n\n\/**\n * Get the count of prime quadruplets between startNumber and\n * stopNumber after having called sieve().\n *\/\nuint64_t PrimeSieve::getQuadrupletCount() const {\n return counts_[3];\n}\n\n\/**\n * Get the count of prime quintuplets between startNumber and\n * stopNumber after having called sieve().\n *\/\nuint64_t PrimeSieve::getQuintupletCount() const {\n return counts_[4];\n}\n\n\/**\n * Get the count of prime sextuplets between startNumber and\n * stopNumber after having called sieve().\n *\/\nuint64_t PrimeSieve::getSextupletCount() const {\n return counts_[5];\n}\n\n\/**\n * Get the count of prime septuplets between startNumber and\n * stopNumber after having called sieve().\n *\/\nuint64_t PrimeSieve::getSeptupletCount() const {\n return counts_[6];\n}\n\n\/**\n * Get the count of prime numbers or prime k-tuplets between\n * startNumber and stopNumber after having called sieve().\n * e.g type = 0 for prime numbers,\n * type = 1 for twin primes,\n * type = 2 for prime triplets,\n * ...\n * @param type <= 7\n *\/\nuint64_t PrimeSieve::getCounts(uint32_t type) const {\n if (type >= COUNTS_SIZE)\n throw std::out_of_range(\"getCounts(uint32_t) type out of range\");\n return counts_[type];\n}\n\n\/**\n * Get the time elapsed in seconds of the last sieve session.\n *\/\ndouble PrimeSieve::getTimeElapsed() const {\n return timeElapsed_;\n}\n\n\/**\n * Set a start number for sieving.\n * @pre startNumber < (2^64-1) - (2^32-1) * 10\n *\/\nvoid PrimeSieve::setStartNumber(uint64_t startNumber) {\n \/\/ EratBig and EratMedium stopNumber limit\n if (startNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))\n throw std::invalid_argument(\"START must be < (2^64-1) - (2^32-1) * 10\");\n startNumber_ = startNumber;\n}\n\n\/**\n * Set a stop number for sieving.\n * @pre stopNumber < (2^64-1) - (2^32-1) * 10\n *\/\nvoid PrimeSieve::setStopNumber(uint64_t stopNumber) {\n \/\/ EratBig and EratMedium stopNumber limit\n if (stopNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))\n throw std::invalid_argument(\"STOP must be < (2^64-1) - (2^32-1) * 10\");\n stopNumber_ = stopNumber;\n}\n\n\/**\n * Set the size (in KiloBytes) of the sieve of Eratosthenes array.\n * The best performance is achieved with a sieve size that matches\n * the CPU's L1 cache size (usually 32 or 64 KB) when sieving < 10^14\n * and a sieve size of your CPU's L2 cache size above.\n *\n * Default sieveSize = 64 KiloBytes\n *\n * @pre sieveSize must be a power of 2,\n * sieveSize >= 1 KiloByte,\n * sieveSize <= 8192 KiloBytes.\n *\/\nvoid PrimeSieve::setSieveSize(uint32_t sieveSize) {\n \/\/ SieveOfEratosthenes lower sieve size limit AND \n \/\/ EratBig upper sieveSize limit\n if (sieveSize < 1 || sieveSize > 8192)\n throw std::invalid_argument(\"sieve size must be >= 1 and <= 8192 KiloBytes\");\n \/\/ EratBig requires a power of 2 sieve size\n if (!isPowerOf2(sieveSize))\n throw std::invalid_argument(\"sieve size must be a power of 2\");\n \/\/ convert to Bytes\n sieveSize_ = sieveSize * 1024;\n}\n\n\/**\n * Set the flags (settings) of PrimeSieve.\n * @param flags\n * COUNT_PRIMES OR (bitwise '|')\n * COUNT_TWINS OR\n * COUNT_TRIPLETS OR\n * COUNT_QUADRUPLETS OR\n * COUNT_QUINTUPLETS OR\n * COUNT_SEXTUPLETS OR\n * COUNT_SEPTUPLETS OR\n * PRINT_PRIMES OR\n * PRINT_TWINS OR\n * PRINT_TRIPLETS OR\n * PRINT_QUADRUPLETS OR\n * PRINT_QUINTUPLETS OR\n * PRINT_SEXTUPLETS OR\n * PRINT_SEPTUPLETS OR\n * PRINT_STATUS.\n *\/\nvoid PrimeSieve::setFlags(uint32_t flags) {\n flags_ = flags;\n}\n\nvoid PrimeSieve::reset() {\n segments_ = 0;\n for (uint32_t i = 0; i < COUNTS_SIZE; i++)\n counts_[i] = 0;\n status_ = -1.0;\n parent_->doStatus(0);\n}\n\n\/**\n * Print the status (in percent) of the sieving process\n * to the standard output.\n *\/\nvoid PrimeSieve::doStatus(uint64_t segment) {\n segments_ += segment;\n double old = status_;\n status_ = static_cast<double> (segments_) \/\n static_cast<double> (1 + stopNumber_ - startNumber_) * 100.0;\n if (static_cast<int> (status_) > 99)\n status_ = 100.0;\n if ((flags_ & PRINT_STATUS) &&\n static_cast<int> (status_) > static_cast<int> (old)) {\n std::cout << '\\r' << static_cast<int> (status_) << '%' << std::flush;\n }\n}\n\nvoid PrimeSieve::doSmallPrime(uint32_t low, uint32_t high, uint32_t type, \n std::string prime) {\n if (startNumber_ <= low && stopNumber_ >= high) {\n if (flags_ & (COUNT_PRIMES << type))\n counts_[type]++;\n if (flags_ & (PRINT_PRIMES << type))\n std::cout << prime << std::endl;\n else if (flags_ & CALLBACK_PRIMES_IMP)\n this->callback_imp(prime[0]-'0');\n else if (flags_ & CALLBACK_PRIMES_OOP)\n this->callback_oop(prime[0]-'0', cbObj_);\n }\n}\n\n\/**\n * Sieve the prime numbers and\/or prime k-tuplets between startNumber\n * and stopNumber.\n *\/\nvoid PrimeSieve::sieve() {\n if (stopNumber_ < startNumber_)\n throw std::invalid_argument(\"STOP must be >= START\");\n timeElapsed_ = static_cast<double> (std::clock());\n this->reset();\n\n \/\/ small primes have to be examined manually\n if (startNumber_ <= 5) {\n this->doSmallPrime(2, 2, 0, \"2\");\n this->doSmallPrime(3, 3, 0, \"3\");\n this->doSmallPrime(5, 5, 0, \"5\");\n this->doSmallPrime(3, 5, 1, \"(3, 5)\");\n this->doSmallPrime(5, 7, 1, \"(5, 7)\");\n this->doSmallPrime(5, 11, 2, \"(5, 7, 11)\");\n this->doSmallPrime(5, 13, 3, \"(5, 7, 11, 13)\");\n this->doSmallPrime(5, 17, 4, \"(5, 7, 11, 13, 17)\");\n }\n\n if (stopNumber_ >= 7) {\n \/\/ needed by primeNumberGenerator and primeNumberFinder to\n \/\/ reset their sieve arrays\n ResetSieve resetSieve(this);\n \/\/ used to sieve the prime numbers and prime k-tuplets between\n \/\/ startNumber_ and stopNumber_\n PrimeNumberFinder primeNumberFinder(this, resetSieve);\n\n if (isqrt(stopNumber_) > resetSieve.getLimit()) {\n \/\/ used to generate the prime numbers up to sqrt(stopNumber_)\n \/\/ needed for sieving by primeNumberFinder\n PrimeNumberGenerator primeNumberGenerator(&primeNumberFinder);\n std::vector<uint32_t> primes16Bit;\n primes16Bit.push_back(3);\n uint32_t stop = isqrt(primeNumberGenerator.getStopNumber());\n uint32_t keep = isqrt(stop);\n \/\/ the following trial division algorithm is used to generate the\n \/\/ prime numbers up to stopNumber_^0.25 needed for sieving by\n \/\/ primeNumberGenerator. Although the algorithm is never\n \/\/ used > 65536 it finds the prime numbers up to 10^7 in 1 second\n \/\/ on an Intel Core i5-670 3.46GHz\n for (uint32_t n = 5; n <= stop; n += 2) {\n uint32_t s = isqrt(n);\n uint32_t i = 0;\n for (; primes16Bit[i] <= s && (n % primes16Bit[i]) != 0; i++)\n ;\n if (primes16Bit[i] > s) {\n if (primes16Bit[i] <= keep)\n primes16Bit.push_back(n);\n if (n > resetSieve.getLimit())\n \/\/ generate the prime numbers up to n^2 and call\n \/\/ primeNumberFinder.sieve(p) for each generated prime\n primeNumberGenerator.sieve(n);\n }\n }\n primeNumberGenerator.finish();\n }\n primeNumberFinder.finish();\n }\n\n \/\/ set status_ to 100.0 (percent)\n parent_->doStatus(10);\n timeElapsed_ = (static_cast<double> (std::clock()) - timeElapsed_) \/\n static_cast<double> (CLOCKS_PER_SEC);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: EventThread.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: fs $ $Date: 2001-08-22 13:57:07 $\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 _FRM_EVENT_THREAD_HXX_\n#include \"EventThread.hxx\"\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::awt;\nusing namespace ::com::sun::star::lang;\n\nDBG_NAME( OComponentEventThread );\nOComponentEventThread::OComponentEventThread( ::cppu::OComponentHelper* pCompImpl ) :\n m_pCompImpl( pCompImpl )\n{\n DBG_CTOR( OComponentEventThread, NULL );\n\n increment(m_refCount);\n\n \/\/ Eine Referenz des Controls halten\n {\n InterfaceRef xIFace(static_cast<XWeak*>(pCompImpl));\n query_interface(xIFace, m_xComp);\n }\n\n \/\/ und uns an dem Control anmelden\n {\n Reference<XEventListener> xEvtLstnr = static_cast<XEventListener*>(this);\n m_xComp->addEventListener( xEvtLstnr );\n }\n\n decrement(m_refCount);\n}\n\nOComponentEventThread::~OComponentEventThread()\n{\n DBG_DTOR( OComponentEventThread, NULL );\n\n DBG_ASSERT( m_aEvents.size() == 0,\n \"OComponentEventThread::~OComponentEventThread: Kein dispose gerufen?\" );\n while (m_aEvents.size())\n delete *m_aEvents.erase(m_aEvents.begin());\n}\n\nAny SAL_CALL OComponentEventThread::queryInterface(const Type& _rType) throw (RuntimeException)\n{\n Any aReturn;\n\n aReturn = OWeakObject::queryInterface(_rType);\n\n if (!aReturn.hasValue())\n aReturn = ::cppu::queryInterface(_rType,\n static_cast<XEventListener*>(this)\n );\n\n return aReturn;\n}\n\nvoid OComponentEventThread::disposing( const EventObject& evt )\n{\n if( evt.Source == m_xComp )\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ Event-Listener abmelden\n Reference<XEventListener> xEvtLstnr = static_cast<XEventListener*>(this);\n m_xComp->removeEventListener( xEvtLstnr );\n\n \/\/ Event-Queue loeschen\n while (m_aEvents.size())\n delete *m_aEvents.erase(m_aEvents.begin());\n m_aControls.erase(m_aControls.begin(), m_aControls.end());\n m_aFlags.erase(m_aFlags.begin(), m_aFlags.end());\n\n \/\/ Das Control loslassen und pCompImpl auf 0 setzen, damit der\n \/\/ Thread weiss, dass er sich beenden soll.\n m_xComp = 0;\n m_pCompImpl = 0;\n\n \/\/ Den Thread aufwecken und beenden.\n m_aCond.set();\n terminate();\n }\n}\n\nvoid OComponentEventThread::addEvent( const EventObject* _pEvt, sal_Bool bFlag )\n{\n Reference<XControl> xTmp;\n addEvent( _pEvt, xTmp, bFlag );\n}\n\nvoid OComponentEventThread::addEvent( const EventObject* _pEvt,\n const Reference<XControl>& rControl,\n sal_Bool bFlag )\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ Daten in die Queue stellen\n m_aEvents.push_back( cloneEvent( _pEvt ) );\n\n Reference<XWeak> xWeakControl(rControl, UNO_QUERY);\n Reference<XAdapter> xControlAdapter = xWeakControl.is() ? xWeakControl->queryAdapter() : Reference<XAdapter>();\n m_aControls.push_back( xControlAdapter );\n\n m_aFlags.push_back( bFlag );\n\n \/\/ Thread aufwecken\n m_aCond.set();\n}\n\n\/\/---------------------------------------------------------------------\n\/\/--- 22.08.01 15:48:15 -----------------------------------------------\n\nvoid OComponentEventThread::implStarted( )\n{\n acquire( );\n}\n\n\/\/---------------------------------------------------------------------\n\/\/--- 22.08.01 15:48:16 -----------------------------------------------\n\nvoid OComponentEventThread::implTerminated( )\n{\n release( );\n}\n\n\/\/---------------------------------------------------------------------\n\/\/--- 22.08.01 15:47:31 -----------------------------------------------\n\nvoid SAL_CALL OComponentEventThread::kill()\n{\n OComponentEventThread_TBASE::kill();\n\n implTerminated( );\n}\n\n\/\/---------------------------------------------------------------------\n\/\/--- 22.08.01 15:47:33 -----------------------------------------------\n\nvoid SAL_CALL OComponentEventThread::onTerminated()\n{\n OComponentEventThread_TBASE::onTerminated();\n\n implTerminated( );\n}\n\nvoid OComponentEventThread::run()\n{\n implStarted( );\n\n \/\/ uns selbst festhalten, damit wir nicht geloescht werden,\n \/\/ wenn zwischendrinne mal ein dispose gerufen wird.\n InterfaceRef xThis(static_cast<XWeak*>(this));\n\n do\n {\n ::osl::MutexGuard aGuard(m_aMutex);\n\n while( m_aEvents.size() > 0 )\n {\n \/\/ Das Control holen und festhalten, damit es waehrend des\n \/\/ actionPerformed nicht geloescht werden kann.\n Reference<XComponent> xComp = m_xComp;\n ::cppu::OComponentHelper *pCompImpl = m_pCompImpl;\n\n EventObject* pEvt = *m_aEvents.erase( m_aEvents.begin() );\n Reference<XAdapter> xControlAdapter = *m_aControls.erase( m_aControls.begin() );\n sal_Bool bFlag = *m_aFlags.erase( m_aFlags.begin() );\n\n {\n MutexRelease aReleaseOnce(m_aMutex);\n \/\/ Weil ein queryHardRef eine Exception schmeissen kann sollte\n \/\/ es nicht bei gelocktem Mutex aufgerufen werden.\n Reference<XControl> xControl;\n if ( xControlAdapter.is() )\n query_interface(xControlAdapter->queryAdapted(), xControl);\n\n if( xComp.is() )\n processEvent( pCompImpl, pEvt, xControl, bFlag );\n }\n\n delete pEvt;\n };\n\n \/\/ Nach einem dispose kennen wir das Control nicht mehr. Dann darf\n \/\/ auch nicht gewartet werden.\n if( !m_xComp.is() )\n return;\n\n \/\/ Warte-Bedingung zuruecksetzen\n m_aCond.reset();\n {\n MutexRelease aReleaseOnce(m_aMutex);\n \/\/ und warten ... falls nicht zwischenzeitlich doch noch ein\n \/\/ Event eingetroffen ist.\n m_aCond.wait();\n }\n }\n while( sal_True );\n}\n\n\/\/.........................................................................\n} \/\/ namespace frm\n\/\/.........................................................................\n\n<commit_msg>compiler error was checked<commit_after>\/*************************************************************************\n *\n * $RCSfile: EventThread.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: avy $ $Date: 2001-08-23 15:23:12 $\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 _FRM_EVENT_THREAD_HXX_\n#include \"EventThread.hxx\"\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::awt;\nusing namespace ::com::sun::star::lang;\n\nDBG_NAME( OComponentEventThread )\nOComponentEventThread::OComponentEventThread( ::cppu::OComponentHelper* pCompImpl ) :\n m_pCompImpl( pCompImpl )\n{\n DBG_CTOR( OComponentEventThread, NULL );\n\n increment(m_refCount);\n\n \/\/ Eine Referenz des Controls halten\n {\n InterfaceRef xIFace(static_cast<XWeak*>(pCompImpl));\n query_interface(xIFace, m_xComp);\n }\n\n \/\/ und uns an dem Control anmelden\n {\n Reference<XEventListener> xEvtLstnr = static_cast<XEventListener*>(this);\n m_xComp->addEventListener( xEvtLstnr );\n }\n\n decrement(m_refCount);\n}\n\nOComponentEventThread::~OComponentEventThread()\n{\n DBG_DTOR( OComponentEventThread, NULL );\n\n DBG_ASSERT( m_aEvents.size() == 0,\n \"OComponentEventThread::~OComponentEventThread: Kein dispose gerufen?\" );\n while (m_aEvents.size())\n delete *m_aEvents.erase(m_aEvents.begin());\n}\n\nAny SAL_CALL OComponentEventThread::queryInterface(const Type& _rType) throw (RuntimeException)\n{\n Any aReturn;\n\n aReturn = OWeakObject::queryInterface(_rType);\n\n if (!aReturn.hasValue())\n aReturn = ::cppu::queryInterface(_rType,\n static_cast<XEventListener*>(this)\n );\n\n return aReturn;\n}\n\nvoid OComponentEventThread::disposing( const EventObject& evt )\n{\n if( evt.Source == m_xComp )\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ Event-Listener abmelden\n Reference<XEventListener> xEvtLstnr = static_cast<XEventListener*>(this);\n m_xComp->removeEventListener( xEvtLstnr );\n\n \/\/ Event-Queue loeschen\n while (m_aEvents.size())\n delete *m_aEvents.erase(m_aEvents.begin());\n m_aControls.erase(m_aControls.begin(), m_aControls.end());\n m_aFlags.erase(m_aFlags.begin(), m_aFlags.end());\n\n \/\/ Das Control loslassen und pCompImpl auf 0 setzen, damit der\n \/\/ Thread weiss, dass er sich beenden soll.\n m_xComp = 0;\n m_pCompImpl = 0;\n\n \/\/ Den Thread aufwecken und beenden.\n m_aCond.set();\n terminate();\n }\n}\n\nvoid OComponentEventThread::addEvent( const EventObject* _pEvt, sal_Bool bFlag )\n{\n Reference<XControl> xTmp;\n addEvent( _pEvt, xTmp, bFlag );\n}\n\nvoid OComponentEventThread::addEvent( const EventObject* _pEvt,\n const Reference<XControl>& rControl,\n sal_Bool bFlag )\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n\n \/\/ Daten in die Queue stellen\n m_aEvents.push_back( cloneEvent( _pEvt ) );\n\n Reference<XWeak> xWeakControl(rControl, UNO_QUERY);\n Reference<XAdapter> xControlAdapter = xWeakControl.is() ? xWeakControl->queryAdapter() : Reference<XAdapter>();\n m_aControls.push_back( xControlAdapter );\n\n m_aFlags.push_back( bFlag );\n\n \/\/ Thread aufwecken\n m_aCond.set();\n}\n\n\/\/---------------------------------------------------------------------\n\/\/--- 22.08.01 15:48:15 -----------------------------------------------\n\nvoid OComponentEventThread::implStarted( )\n{\n acquire( );\n}\n\n\/\/---------------------------------------------------------------------\n\/\/--- 22.08.01 15:48:16 -----------------------------------------------\n\nvoid OComponentEventThread::implTerminated( )\n{\n release( );\n}\n\n\/\/---------------------------------------------------------------------\n\/\/--- 22.08.01 15:47:31 -----------------------------------------------\n\nvoid SAL_CALL OComponentEventThread::kill()\n{\n OComponentEventThread_TBASE::kill();\n\n implTerminated( );\n}\n\n\/\/---------------------------------------------------------------------\n\/\/--- 22.08.01 15:47:33 -----------------------------------------------\n\nvoid SAL_CALL OComponentEventThread::onTerminated()\n{\n OComponentEventThread_TBASE::onTerminated();\n\n implTerminated( );\n}\n\nvoid OComponentEventThread::run()\n{\n implStarted( );\n\n \/\/ uns selbst festhalten, damit wir nicht geloescht werden,\n \/\/ wenn zwischendrinne mal ein dispose gerufen wird.\n InterfaceRef xThis(static_cast<XWeak*>(this));\n\n do\n {\n ::osl::MutexGuard aGuard(m_aMutex);\n\n while( m_aEvents.size() > 0 )\n {\n \/\/ Das Control holen und festhalten, damit es waehrend des\n \/\/ actionPerformed nicht geloescht werden kann.\n Reference<XComponent> xComp = m_xComp;\n ::cppu::OComponentHelper *pCompImpl = m_pCompImpl;\n\n EventObject* pEvt = *m_aEvents.erase( m_aEvents.begin() );\n Reference<XAdapter> xControlAdapter = *m_aControls.erase( m_aControls.begin() );\n sal_Bool bFlag = *m_aFlags.erase( m_aFlags.begin() );\n\n {\n MutexRelease aReleaseOnce(m_aMutex);\n \/\/ Weil ein queryHardRef eine Exception schmeissen kann sollte\n \/\/ es nicht bei gelocktem Mutex aufgerufen werden.\n Reference<XControl> xControl;\n if ( xControlAdapter.is() )\n query_interface(xControlAdapter->queryAdapted(), xControl);\n\n if( xComp.is() )\n processEvent( pCompImpl, pEvt, xControl, bFlag );\n }\n\n delete pEvt;\n };\n\n \/\/ Nach einem dispose kennen wir das Control nicht mehr. Dann darf\n \/\/ auch nicht gewartet werden.\n if( !m_xComp.is() )\n return;\n\n \/\/ Warte-Bedingung zuruecksetzen\n m_aCond.reset();\n {\n MutexRelease aReleaseOnce(m_aMutex);\n \/\/ und warten ... falls nicht zwischenzeitlich doch noch ein\n \/\/ Event eingetroffen ist.\n m_aCond.wait();\n }\n }\n while( sal_True );\n}\n\n\/\/.........................................................................\n} \/\/ namespace frm\n\/\/.........................................................................\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: interaction.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2003-03-25 18:19:39 $\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 __FRAMEWORK_DISPATCH_INTERACTION_HXX_\n#define __FRAMEWORK_DISPATCH_INTERACTION_HXX_\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONREQUEST_HPP_\n#include <com\/sun\/star\/task\/XInteractionRequest.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONCONTINUATION_HPP_\n#include <com\/sun\/star\/task\/XInteractionContinuation.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONABORT_HPP_\n#include <com\/sun\/star\/task\/XInteractionAbort.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONAPPROVE_HPP_\n#include <com\/sun\/star\/task\/XInteractionApprove.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONDISAPPROVE_HPP_\n#include <com\/sun\/star\/task\/XInteractionDisapprove.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONRETRY_HPP_\n#include <com\/sun\/star\/task\/XInteractionRetry.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_XINTERACTIONFILTERSELECT_HPP_\n#include <com\/sun\/star\/document\/XInteractionFilterSelect.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_NOSUCHFILTERREQUEST_HPP_\n#include <com\/sun\/star\/document\/NoSuchFilterRequest.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_AMBIGOUSFILTERREQUEST_HPP_\n#include <com\/sun\/star\/document\/AmbigousFilterRequest.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes of other projects\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ namespace\n\/\/_________________________________________________________________________________________________________________\n\nnamespace framework{\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ non exported const\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ non exported definitions\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ declarations\n\/\/_________________________________________________________________________________________________________________\n\n\/*-************************************************************************************************************\/\/**\n @short base for continuation classes\n @descr An interaction continuation could be used on XInteractionHandler\/XInteractionRequest\n to abort or react for it.\n Base functionality is everytime the same - handler mark right continuation by calling\n interface method \"select()\". User of interaction can detect it by testing c++ method \"isSelected()\"!\n Superclasses can add additional interfaces or methods to support additional features ...\n but selection of it is supported here!\n\n @implements XInterface\n XTypeProvider (supported by WeakImplHelper!)\n XInteractionContinuation\n\n @base WeakImplHelper1\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\ntemplate< class TContinuationType >\nclass ContinuationBase : public ::cppu::WeakImplHelper1< TContinuationType >\n{\n \/\/ c++ interface\n public:\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ initialize continuation with right start values\n \/\/---------------------------------------------------------------------------------------------------------\n ContinuationBase()\n : m_bSelected( sal_False )\n {\n }\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ was continuation selected by handler?\n \/\/---------------------------------------------------------------------------------------------------------\n sal_Bool isSelected() const\n {\n return m_bSelected;\n }\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ make using more then once possible\n \/\/---------------------------------------------------------------------------------------------------------\n void reset()\n {\n m_bSelected = sal_False;\n }\n\n \/\/ uno interface\n public:\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ called by handler to mark continuation as the only possible solution for started interaction\n \/\/---------------------------------------------------------------------------------------------------------\n virtual void SAL_CALL select() throw( ::com::sun::star::uno::RuntimeException )\n {\n m_bSelected = sal_True;\n }\n\n \/\/ member\n private:\n\n sal_Bool m_bSelected;\n\n}; \/\/ class ContinuationBase\n\n\/*-************************************************************************************************************\/\/**\n @short declaration of some simple continuations\n @descr These derived classes implements some simple continuations, which doesnt need and additional\n interfaces or methods. Her selected state is the only neccessary feature. User of it can\n distinguish by type between different functionality!\n\n @implements -\n\n @base ContinuationBase\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionAbort > ContinuationAbort;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionApprove > ContinuationApprove;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionDisapprove > ContinuationDisapprove;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionRetry > ContinuationRetry;\n\n\/*-************************************************************************************************************\/\/**\n @short declaration of special continuation for filter selection\n @descr Sometimes filter detection during loading document failed. Then we need a possibility\n to ask user for his decision. These continuation transport selected filter by user to\n code user of interaction.\n\n @attention This implementation could be used one times only. We don't support a resetable continuation yet!\n Why? Normaly interaction should show a filter selection dialog and ask user for his decision.\n He can select any filter - then instances of these class will be called by handler ... or user\n close dialog without any selection. Then another continuation should be slected by handler to\n abort continuations ... Retrying isn't very usefull here ... I think.\n\n @implements XInteractionFilterSelect\n\n @base ImplInheritanceHelper1\n ContinuationBase\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\nclass ContinuationFilterSelect : public ContinuationBase< ::com::sun::star::document::XInteractionFilterSelect >\n{\n \/\/ c++ interface\n public:\n ContinuationFilterSelect();\n\n \/\/ uno interface\n public:\n virtual void SAL_CALL setFilter( const ::rtl::OUString& sFilter ) throw( ::com::sun::star::uno::RuntimeException );\n virtual ::rtl::OUString SAL_CALL getFilter( ) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ member\n private:\n ::rtl::OUString m_sFilter;\n\n}; \/\/ class ContinuationFilterSelect\n\n\/*-************************************************************************************************************\/\/**\n @short special request for interaction to ask user for right filter\n @descr These helper can be used to ask user for right filter, if filter detection failed.\n It capsulate communication with any interaction handler and supports an easy\n access on interaction results for user of these class.\n Use it and forget complex mechanism of interaction ...\n\n @example RequestFilterSelect* pRequest = new RequestFilterSelect;\n Reference< XInteractionRequest > xRequest ( pRequest );\n xInteractionHandler->handle( xRequest );\n if( ! pRequest.isAbort() )\n {\n OUString sFilter = pRequest->getFilter();\n }\n\n @implements XInteractionRequest\n\n @base WeakImplHelper1\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\nclass RequestFilterSelect : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n \/\/ c++ interface\n public:\n RequestFilterSelect( const ::rtl::OUString& sURL );\n sal_Bool isAbort () const;\n ::rtl::OUString getFilter() const;\n\n \/\/ uno interface\n public:\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest () throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ member\n private:\n ::com::sun::star::uno::Any m_aRequest ;\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations;\n ContinuationAbort* m_pAbort ;\n ContinuationFilterSelect* m_pFilter ;\n\n}; \/\/ class RequestFilterSelect\n\n\/*-************************************************************************************************************\/\/**\n @short special request for interaction\n @descr User must decide between a preselected and another detected filter.\n It capsulate communication with any interaction handler and supports an easy\n access on interaction results for user of these class.\n\n @implements XInteractionRequest\n\n @base WeakImplHelper1\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\nclass RequestAmbigousFilter : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n \/\/ c++ interface\n public:\n RequestAmbigousFilter( const ::rtl::OUString& sURL ,\n const ::rtl::OUString& sSelectedFilter ,\n const ::rtl::OUString& sDetectedFilter );\n sal_Bool isAbort () const;\n ::rtl::OUString getFilter() const;\n\n \/\/ uno interface\n public:\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest () throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ member\n private:\n ::com::sun::star::uno::Any m_aRequest ;\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations;\n ContinuationAbort* m_pAbort ;\n ContinuationFilterSelect* m_pFilter ;\n\n}; \/\/ class RequestFilterSelect\n\n\/*-************************************************************************************************************\/\/**\n @short special request for interaction\n @descr User must decide between a preselected and another detected filter.\n It capsulate communication with any interaction handler and supports an easy\n access on interaction results for user of these class.\n\n @implements XInteractionRequest\n\n @base WeakImplHelper1\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\nclass InteractionRequest : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n \/\/ c++ interface\n public:\n InteractionRequest( const ::com::sun::star::uno::Any& aRequest ,\n const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > lContinuations )\n {\n m_aRequest = aRequest ;\n m_lContinuations = lContinuations;\n }\n\n \/\/ uno interface\n public:\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest()\n throw( ::com::sun::star::uno::RuntimeException )\n {\n return m_aRequest;\n }\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations()\n throw( ::com::sun::star::uno::RuntimeException )\n {\n return m_lContinuations;\n }\n\n \/\/ member\n private:\n ::com::sun::star::uno::Any m_aRequest ;\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations;\n\n}; \/\/ class RequestFilterSelect\n\n#endif \/\/ #define __FRAMEWORK_DISPATCH_INTERACTION_HXX_\n\n} \/\/ namespace framework\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.502); FILE MERGED 2005\/09\/05 13:04:40 rt 1.4.502.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: interaction.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 00:12: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#ifndef __FRAMEWORK_DISPATCH_INTERACTION_HXX_\n#define __FRAMEWORK_DISPATCH_INTERACTION_HXX_\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONREQUEST_HPP_\n#include <com\/sun\/star\/task\/XInteractionRequest.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONCONTINUATION_HPP_\n#include <com\/sun\/star\/task\/XInteractionContinuation.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONABORT_HPP_\n#include <com\/sun\/star\/task\/XInteractionAbort.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONAPPROVE_HPP_\n#include <com\/sun\/star\/task\/XInteractionApprove.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONDISAPPROVE_HPP_\n#include <com\/sun\/star\/task\/XInteractionDisapprove.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONRETRY_HPP_\n#include <com\/sun\/star\/task\/XInteractionRetry.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_XINTERACTIONFILTERSELECT_HPP_\n#include <com\/sun\/star\/document\/XInteractionFilterSelect.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_NOSUCHFILTERREQUEST_HPP_\n#include <com\/sun\/star\/document\/NoSuchFilterRequest.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_AMBIGOUSFILTERREQUEST_HPP_\n#include <com\/sun\/star\/document\/AmbigousFilterRequest.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes of other projects\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ namespace\n\/\/_________________________________________________________________________________________________________________\n\nnamespace framework{\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ non exported const\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ non exported definitions\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ declarations\n\/\/_________________________________________________________________________________________________________________\n\n\/*-************************************************************************************************************\/\/**\n @short base for continuation classes\n @descr An interaction continuation could be used on XInteractionHandler\/XInteractionRequest\n to abort or react for it.\n Base functionality is everytime the same - handler mark right continuation by calling\n interface method \"select()\". User of interaction can detect it by testing c++ method \"isSelected()\"!\n Superclasses can add additional interfaces or methods to support additional features ...\n but selection of it is supported here!\n\n @implements XInterface\n XTypeProvider (supported by WeakImplHelper!)\n XInteractionContinuation\n\n @base WeakImplHelper1\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\ntemplate< class TContinuationType >\nclass ContinuationBase : public ::cppu::WeakImplHelper1< TContinuationType >\n{\n \/\/ c++ interface\n public:\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ initialize continuation with right start values\n \/\/---------------------------------------------------------------------------------------------------------\n ContinuationBase()\n : m_bSelected( sal_False )\n {\n }\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ was continuation selected by handler?\n \/\/---------------------------------------------------------------------------------------------------------\n sal_Bool isSelected() const\n {\n return m_bSelected;\n }\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ make using more then once possible\n \/\/---------------------------------------------------------------------------------------------------------\n void reset()\n {\n m_bSelected = sal_False;\n }\n\n \/\/ uno interface\n public:\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ called by handler to mark continuation as the only possible solution for started interaction\n \/\/---------------------------------------------------------------------------------------------------------\n virtual void SAL_CALL select() throw( ::com::sun::star::uno::RuntimeException )\n {\n m_bSelected = sal_True;\n }\n\n \/\/ member\n private:\n\n sal_Bool m_bSelected;\n\n}; \/\/ class ContinuationBase\n\n\/*-************************************************************************************************************\/\/**\n @short declaration of some simple continuations\n @descr These derived classes implements some simple continuations, which doesnt need and additional\n interfaces or methods. Her selected state is the only neccessary feature. User of it can\n distinguish by type between different functionality!\n\n @implements -\n\n @base ContinuationBase\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionAbort > ContinuationAbort;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionApprove > ContinuationApprove;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionDisapprove > ContinuationDisapprove;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionRetry > ContinuationRetry;\n\n\/*-************************************************************************************************************\/\/**\n @short declaration of special continuation for filter selection\n @descr Sometimes filter detection during loading document failed. Then we need a possibility\n to ask user for his decision. These continuation transport selected filter by user to\n code user of interaction.\n\n @attention This implementation could be used one times only. We don't support a resetable continuation yet!\n Why? Normaly interaction should show a filter selection dialog and ask user for his decision.\n He can select any filter - then instances of these class will be called by handler ... or user\n close dialog without any selection. Then another continuation should be slected by handler to\n abort continuations ... Retrying isn't very usefull here ... I think.\n\n @implements XInteractionFilterSelect\n\n @base ImplInheritanceHelper1\n ContinuationBase\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\nclass ContinuationFilterSelect : public ContinuationBase< ::com::sun::star::document::XInteractionFilterSelect >\n{\n \/\/ c++ interface\n public:\n ContinuationFilterSelect();\n\n \/\/ uno interface\n public:\n virtual void SAL_CALL setFilter( const ::rtl::OUString& sFilter ) throw( ::com::sun::star::uno::RuntimeException );\n virtual ::rtl::OUString SAL_CALL getFilter( ) throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ member\n private:\n ::rtl::OUString m_sFilter;\n\n}; \/\/ class ContinuationFilterSelect\n\n\/*-************************************************************************************************************\/\/**\n @short special request for interaction to ask user for right filter\n @descr These helper can be used to ask user for right filter, if filter detection failed.\n It capsulate communication with any interaction handler and supports an easy\n access on interaction results for user of these class.\n Use it and forget complex mechanism of interaction ...\n\n @example RequestFilterSelect* pRequest = new RequestFilterSelect;\n Reference< XInteractionRequest > xRequest ( pRequest );\n xInteractionHandler->handle( xRequest );\n if( ! pRequest.isAbort() )\n {\n OUString sFilter = pRequest->getFilter();\n }\n\n @implements XInteractionRequest\n\n @base WeakImplHelper1\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\nclass RequestFilterSelect : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n \/\/ c++ interface\n public:\n RequestFilterSelect( const ::rtl::OUString& sURL );\n sal_Bool isAbort () const;\n ::rtl::OUString getFilter() const;\n\n \/\/ uno interface\n public:\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest () throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ member\n private:\n ::com::sun::star::uno::Any m_aRequest ;\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations;\n ContinuationAbort* m_pAbort ;\n ContinuationFilterSelect* m_pFilter ;\n\n}; \/\/ class RequestFilterSelect\n\n\/*-************************************************************************************************************\/\/**\n @short special request for interaction\n @descr User must decide between a preselected and another detected filter.\n It capsulate communication with any interaction handler and supports an easy\n access on interaction results for user of these class.\n\n @implements XInteractionRequest\n\n @base WeakImplHelper1\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\nclass RequestAmbigousFilter : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n \/\/ c++ interface\n public:\n RequestAmbigousFilter( const ::rtl::OUString& sURL ,\n const ::rtl::OUString& sSelectedFilter ,\n const ::rtl::OUString& sDetectedFilter );\n sal_Bool isAbort () const;\n ::rtl::OUString getFilter() const;\n\n \/\/ uno interface\n public:\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest () throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ member\n private:\n ::com::sun::star::uno::Any m_aRequest ;\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations;\n ContinuationAbort* m_pAbort ;\n ContinuationFilterSelect* m_pFilter ;\n\n}; \/\/ class RequestFilterSelect\n\n\/*-************************************************************************************************************\/\/**\n @short special request for interaction\n @descr User must decide between a preselected and another detected filter.\n It capsulate communication with any interaction handler and supports an easy\n access on interaction results for user of these class.\n\n @implements XInteractionRequest\n\n @base WeakImplHelper1\n\n @devstatus ready to use\n @threadsafe no (used on once position only!)\n*\/\/*-*************************************************************************************************************\/\nclass InteractionRequest : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n \/\/ c++ interface\n public:\n InteractionRequest( const ::com::sun::star::uno::Any& aRequest ,\n const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > lContinuations )\n {\n m_aRequest = aRequest ;\n m_lContinuations = lContinuations;\n }\n\n \/\/ uno interface\n public:\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest()\n throw( ::com::sun::star::uno::RuntimeException )\n {\n return m_aRequest;\n }\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations()\n throw( ::com::sun::star::uno::RuntimeException )\n {\n return m_lContinuations;\n }\n\n \/\/ member\n private:\n ::com::sun::star::uno::Any m_aRequest ;\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations;\n\n}; \/\/ class RequestFilterSelect\n\n#endif \/\/ #define __FRAMEWORK_DISPATCH_INTERACTION_HXX_\n\n} \/\/ namespace framework\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: connection.hpp 17 2005-03-08 23:58:43Z pavlenko $\n\n#ifndef CONNECTION_HPP\n#define CONNECTION_HPP\n\n#include <mapnik\/datasource.hpp>\n\nextern \"C\" \n{\n#include \"libpq-fe.h\"\n}\n\n#include \"resultset.hpp\"\n\nclass ResultSet;\nclass Connection\n{\n private:\n PGconn *conn_;\n int cursorId;\n bool closed_;\n public:\n Connection(std::string const& connection_str)\n :cursorId(0),\n closed_(false)\n {\n conn_=PQconnectdb(connection_str.c_str());\n if (PQstatus(conn_) != CONNECTION_OK)\n {\n std::ostringstream s(\"Postgis Plugin: PSQL error\");\n if (conn_ )\n {\n std::string msg = PQerrorMessage( conn_ );\n if ( ! msg.empty() )\n {\n s << \":\\n\" << msg.substr( 0, msg.size() - 1 );\n }\n } \n throw mapnik::datasource_exception( s.str() );\n }\n }\n \n bool execute(const std::string& sql) const\n {\n PGresult *result=PQexec(conn_,sql.c_str());\n bool ok=(result && PQresultStatus(result)==PGRES_COMMAND_OK);\n PQclear(result);\n return ok;\n }\n \n boost::shared_ptr<ResultSet> executeQuery(const std::string& sql,int type=0) const\n {\n PGresult *result=0;\n if (type==1)\n {\n result=PQexecParams(conn_,sql.c_str(),0,0,0,0,0,1);\n }\n else\n {\n result=PQexec(conn_,sql.c_str());\n }\n if(!result || PQresultStatus(result) != PGRES_TUPLES_OK)\n {\n std::ostringstream s(\"Postgis Plugin: PSQL error\");\n if (conn_ )\n {\n std::string msg = PQerrorMessage( conn_ );\n if ( ! msg.empty() )\n {\n s << \":\" << std::endl << msg.substr( 0, msg.size() - 1 );\n }\n \n s << std::endl << \"Full sql was: '\" + sql + \"'\" << std::endl;\n } \n throw mapnik::datasource_exception( s.str() );\n }\n\n return boost::shared_ptr<ResultSet>(new ResultSet(result));\n }\n \n std::string client_encoding() const\n {\n return PQparameterStatus(conn_,\"client_encoding\");\n }\n \n bool isOK() const\n {\n return (PQstatus(conn_)!=CONNECTION_BAD);\n }\n \n void close()\n {\n if (!closed_)\n {\n PQfinish(conn_);\n#ifdef MAPNIK_DEBUG\n std::clog << \"PostGIS: datasource closed, also closing connection - \" << conn_ << std::endl;\n#endif\n closed_ = true;\n }\n }\n \n std::string new_cursor_name()\n {\n std::ostringstream s;\n s << \"mapnik_\" << (cursorId++);\n return s.str();\n }\n \n ~Connection()\n {\n if (!closed_)\n {\n PQfinish(conn_);\n#ifdef MAPNIK_DEBUG\n std::clog << \"PostGIS: postgresql connection closed - \" << conn_ << std::endl;\n#endif\n closed_ = true;\n }\n }\n};\n\n#endif \/\/CONNECTION_HPP\n<commit_msg>+ reset head<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: connection.hpp 17 2005-03-08 23:58:43Z pavlenko $\n\n#ifndef CONNECTION_HPP\n#define CONNECTION_HPP\n\n#include <mapnik\/datasource.hpp>\n\nextern \"C\" \n{\n#include \"libpq-fe.h\"\n}\n\n#include \"resultset.hpp\"\n\nclass ResultSet;\nclass Connection\n{\n private:\n PGconn *conn_;\n int cursorId;\n bool closed_;\n public:\n Connection(std::string const& connection_str)\n :cursorId(0),\n closed_(false)\n {\n conn_=PQconnectdb(connection_str.c_str());\n if (PQstatus(conn_) != CONNECTION_OK)\n {\n std::ostringstream s(\"Postgis Plugin: PSQL error\");\n if (conn_ )\n {\n std::string msg = PQerrorMessage( conn_ );\n if ( ! msg.empty() )\n {\n s << \":\\n\" << msg.substr( 0, msg.size() - 1 );\n }\n } \n throw mapnik::datasource_exception( s.str() );\n }\n }\n \n bool execute(const std::string& sql) const\n {\n PGresult *result=PQexec(conn_,sql.c_str());\n bool ok=(result && PQresultStatus(result)==PGRES_COMMAND_OK);\n PQclear(result);\n return ok;\n }\n \n boost::shared_ptr<ResultSet> executeQuery(const std::string& sql,int type=0) const\n {\n PGresult *result=0;\n if (type==1)\n {\n result=PQexecParams(conn_,sql.c_str(),0,0,0,0,0,1);\n }\n else\n {\n result=PQexec(conn_,sql.c_str());\n }\n if(!result || PQresultStatus(result) != PGRES_TUPLES_OK)\n {\n std::ostringstream s(\"Postgis Plugin: PSQL error\");\n if (conn_ )\n {\n std::string msg = PQerrorMessage( conn_ );\n if ( ! msg.empty() )\n {\n s << \":\\n\" << msg.substr( 0, msg.size() - 1 );\n }\n \n s << \"\\nFull sql was: '\" << sql << \"'\\n\";\n } \n throw mapnik::datasource_exception( s.str() );\n }\n\n return boost::shared_ptr<ResultSet>(new ResultSet(result));\n }\n \n std::string client_encoding() const\n {\n return PQparameterStatus(conn_,\"client_encoding\");\n }\n \n bool isOK() const\n {\n return (PQstatus(conn_)!=CONNECTION_BAD);\n }\n \n void close()\n {\n if (!closed_)\n {\n PQfinish(conn_);\n#ifdef MAPNIK_DEBUG\n std::clog << \"PostGIS: datasource closed, also closing connection - \" << conn_ << std::endl;\n#endif\n closed_ = true;\n }\n }\n \n std::string new_cursor_name()\n {\n std::ostringstream s;\n s << \"mapnik_\" << (cursorId++);\n return s.str();\n }\n \n ~Connection()\n {\n if (!closed_)\n {\n PQfinish(conn_);\n#ifdef MAPNIK_DEBUG\n std::clog << \"PostGIS: postgresql connection closed - \" << conn_ << std::endl;\n#endif\n closed_ = true;\n }\n }\n};\n\n#endif \/\/CONNECTION_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*! \\file *\/\n\/* ************************************************************************\n * Copyright (c) 2021 Advanced Micro Devices, Inc.\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 * ************************************************************************ *\/\n\n#include \"bsrsm_device.h\"\n#include \"bsrsm_device_large.h\"\n#include \"definitions.h\"\n#include \"rocsparse_bsrsm.hpp\"\n#include \"utility.h\"\n\n#define LAUNCH_BSRSM_GTHR_DIM(bsize, wfsize, dim) \\\n hipLaunchKernelGGL((bsr_gather<wfsize, bsize \/ wfsize, dim>), \\\n dim3((wfsize * nnzb - 1) \/ bsize + 1), \\\n dim3(wfsize, bsize \/ wfsize), \\\n 0, \\\n stream, \\\n dir, \\\n nnzb, \\\n bsrsm_info->trmt_perm, \\\n bsr_val, \\\n bsrt_val, \\\n block_dim)\n\n#define LAUNCH_BSRSM_GTHR(bsize, wfsize, dim) \\\n if(dim <= 2) \\\n { \\\n LAUNCH_BSRSM_GTHR_DIM(bsize, 4, 2); \\\n } \\\n else if(dim <= 4) \\\n { \\\n LAUNCH_BSRSM_GTHR_DIM(bsize, 16, 4); \\\n } \\\n else if(wfsize == 32) \\\n { \\\n LAUNCH_BSRSM_GTHR_DIM(bsize, 16, 4); \\\n } \\\n else \\\n { \\\n LAUNCH_BSRSM_GTHR_DIM(bsize, 64, 8); \\\n }\n\ntemplate <unsigned int BLOCKSIZE, typename T, typename U>\n__launch_bounds__(BLOCKSIZE) __global__ void bsrsm_copy_scale(rocsparse_int m,\n rocsparse_int n,\n U alpha_device_host,\n const T* B,\n rocsparse_int ldb,\n T* X,\n rocsparse_int ldx)\n{\n auto alpha = load_scalar_device_host(alpha_device_host);\n\n bsrsm_copy_scale_device(m, n, alpha, B, ldb, X, ldx);\n}\n\ntemplate <unsigned int DIM_X, unsigned int DIM_Y, typename T, typename U>\n__launch_bounds__(DIM_X* DIM_Y) __global__ void bsrsm_transpose(rocsparse_int m,\n rocsparse_int n,\n U alpha_device_host,\n const T* __restrict__ A,\n rocsparse_int lda,\n T* __restrict__ B,\n rocsparse_int ldb)\n{\n auto alpha = load_scalar_device_host(alpha_device_host);\n\n dense_transpose_device<DIM_X, DIM_Y>(m, n, alpha, A, lda, B, ldb);\n}\n\ntemplate <typename T, typename U>\nrocsparse_status rocsparse_bsrsm_solve_template_large(rocsparse_handle handle,\n rocsparse_direction dir,\n rocsparse_operation trans_A,\n rocsparse_operation trans_X,\n rocsparse_int mb,\n rocsparse_int nrhs,\n rocsparse_int nnzb,\n U alpha,\n const rocsparse_mat_descr descr,\n const T* bsr_val,\n const rocsparse_int* bsr_row_ptr,\n const rocsparse_int* bsr_col_ind,\n rocsparse_int block_dim,\n rocsparse_mat_info info,\n const T* B,\n rocsparse_int ldb,\n T* X,\n rocsparse_int ldx,\n void* temp_buffer)\n{\n#define LAUNCH_LARGE_KERNEL(K_, M_, S_) \\\n dim3 bsrsm_blocks(((nrhs - 1) \/ NCOL + 1) * mb); \\\n dim3 bsrsm_threads(NCOL* M_); \\\n hipLaunchKernelGGL((K_<NCOL * M_, NCOL, S_>), \\\n bsrsm_blocks, \\\n bsrsm_threads, \\\n 0, \\\n stream, \\\n mb, \\\n nrhs, \\\n local_bsr_row_ptr, \\\n local_bsr_col_ind, \\\n local_bsr_val, \\\n block_dim, \\\n Xt, \\\n ldimX, \\\n done_array, \\\n bsrsm_info->row_map, \\\n info->zero_pivot, \\\n descr->base, \\\n descr->diag_type, \\\n dir);\n\n hipStream_t stream = handle->stream;\n\n \/\/ Buffer\n char* ptr = reinterpret_cast<char*>(temp_buffer);\n\n ptr += 256;\n\n \/\/ 16 columns per block seem to work very well\n static constexpr unsigned int NCOL = 16;\n\n int narrays = (nrhs - 1) \/ NCOL + 1;\n\n \/\/ done_array\n int* done_array = reinterpret_cast<int*>(ptr);\n ptr += sizeof(int) * ((mb * narrays - 1) \/ 256 + 1) * 256;\n\n \/\/ Temporary array to store transpose of X\n T* Xt = X;\n if(trans_X == rocsparse_operation_none)\n {\n Xt = reinterpret_cast<T*>(ptr);\n ptr += sizeof(T) * ((mb * block_dim * nrhs - 1) \/ 256 + 1) * 256;\n }\n\n \/\/ Initialize buffers\n RETURN_IF_HIP_ERROR(hipMemsetAsync(done_array, 0, sizeof(int) * mb * narrays, stream));\n\n rocsparse_trm_info bsrsm_info\n = (descr->fill_mode == rocsparse_fill_mode_upper)\n ? ((trans_A == rocsparse_operation_none) ? info->bsrsm_upper_info\n : info->bsrsmt_upper_info)\n : ((trans_A == rocsparse_operation_none) ? info->bsrsm_lower_info\n : info->bsrsmt_lower_info);\n\n \/\/ If diag type is unit, re-initialize zero pivot to remove structural zeros\n if(descr->diag_type == rocsparse_diag_type_unit)\n {\n rocsparse_int max = std::numeric_limits<rocsparse_int>::max();\n RETURN_IF_HIP_ERROR(hipMemcpyAsync(\n info->zero_pivot, &max, sizeof(rocsparse_int), hipMemcpyHostToDevice, stream));\n\n \/\/ Wait for device transfer to finish\n RETURN_IF_HIP_ERROR(hipStreamSynchronize(stream));\n }\n\n rocsparse_fill_mode fill_mode = descr->fill_mode;\n\n \/\/ Transpose X if X is not transposed yet to improve performance\n rocsparse_int ldimX = ldx;\n if(trans_X == rocsparse_operation_none)\n {\n \/\/ Leading dimension for transposed X\n ldimX = nrhs;\n\n#define BSRSM_DIM_X 32\n#define BSRSM_DIM_Y 8\n dim3 bsrsm_blocks((mb * block_dim - 1) \/ BSRSM_DIM_X + 1);\n dim3 bsrsm_threads(BSRSM_DIM_X * BSRSM_DIM_Y);\n\n hipLaunchKernelGGL((bsrsm_transpose<BSRSM_DIM_X, BSRSM_DIM_Y>),\n bsrsm_blocks,\n bsrsm_threads,\n 0,\n stream,\n mb * block_dim,\n nrhs,\n alpha,\n B,\n ldb,\n Xt,\n ldimX);\n#undef BSRSM_DIM_X\n#undef BSRSM_DIM_Y\n }\n else\n {\n \/\/ Copy B into X and scale it with alpha\n hipLaunchKernelGGL((bsrsm_copy_scale<1024>),\n dim3((mb * block_dim - 1) \/ 1024 + 1),\n dim3(1024),\n 0,\n stream,\n mb * block_dim,\n nrhs,\n alpha,\n B,\n ldb,\n X,\n ldx);\n }\n\n \/\/ Pointers to differentiate between transpose mode\n const rocsparse_int* local_bsr_row_ptr = bsr_row_ptr;\n const rocsparse_int* local_bsr_col_ind = bsr_col_ind;\n const T* local_bsr_val = bsr_val;\n\n \/\/ When computing transposed triangular solve, we first need to update the\n \/\/ transposed matrix values\n if(trans_A == rocsparse_operation_transpose)\n {\n T* bsrt_val = reinterpret_cast<T*>(ptr);\n\n LAUNCH_BSRSM_GTHR(256, 64, block_dim);\n\n local_bsr_row_ptr = bsrsm_info->trmt_row_ptr;\n local_bsr_col_ind = bsrsm_info->trmt_col_ind;\n local_bsr_val = bsrt_val;\n\n fill_mode = (fill_mode == rocsparse_fill_mode_lower) ? rocsparse_fill_mode_upper\n : rocsparse_fill_mode_lower;\n }\n\n \/\/ Determine gcnArch and ASIC revision\n int gcnArch = handle->properties.gcnArch;\n int asicRev = handle->asic_rev;\n\n \/\/ gfx908 A0\/1\n if(gcnArch == 908 && asicRev < 2)\n {\n if(fill_mode == rocsparse_fill_mode_upper)\n {\n LAUNCH_LARGE_KERNEL(bsrsm_upper_large_kernel, 16, true);\n }\n else\n {\n LAUNCH_LARGE_KERNEL(bsrsm_lower_large_kernel, 16, true);\n }\n }\n else\n {\n \/\/ Select tuned kernel\n unsigned int nbsr = std::max(4U, fnp2(block_dim));\n\n while(nbsr > 64)\n {\n nbsr >>= 1;\n }\n\n switch(nbsr)\n {\n#define DEFINE_CASE(i) \\\n case i: \\\n { \\\n if(fill_mode == rocsparse_fill_mode_upper) \\\n { \\\n LAUNCH_LARGE_KERNEL(bsrsm_upper_large_kernel, i, false); \\\n } \\\n else \\\n { \\\n LAUNCH_LARGE_KERNEL(bsrsm_lower_large_kernel, i, false); \\\n } \\\n break; \\\n }\n\n DEFINE_CASE(4);\n DEFINE_CASE(8);\n DEFINE_CASE(16);\n DEFINE_CASE(32);\n DEFINE_CASE(64);\n#undef DEFINE_CASE\n }\n }\n#undef LAUNCH_LARGE_KERNEL\n\n \/\/ Transpose X back if X was not initially transposed\n if(trans_X == rocsparse_operation_none)\n {\n#define BSRSM_DIM_X 32\n#define BSRSM_DIM_Y 8\n dim3 bsrsm_blocks((mb * block_dim - 1) \/ BSRSM_DIM_X + 1);\n dim3 bsrsm_threads(BSRSM_DIM_X * BSRSM_DIM_Y);\n\n hipLaunchKernelGGL((dense_transpose_back<BSRSM_DIM_X, BSRSM_DIM_Y>),\n bsrsm_blocks,\n bsrsm_threads,\n 0,\n stream,\n mb * block_dim,\n nrhs,\n Xt,\n ldimX,\n X,\n ldx);\n#undef BSRSM_DIM_X\n#undef BSRSM_DIM_Y\n }\n\n return rocsparse_status_success;\n}\n\n#define INSTANTIATE(real_type_, scalar_type_) \\\n template rocsparse_status rocsparse_bsrsm_solve_template_large( \\\n rocsparse_handle handle, \\\n rocsparse_direction dir, \\\n rocsparse_operation trans_A, \\\n rocsparse_operation trans_X, \\\n rocsparse_int mb, \\\n rocsparse_int nrhs, \\\n rocsparse_int nnzb, \\\n scalar_type_ alpha, \\\n const rocsparse_mat_descr descr, \\\n const real_type_* bsr_val, \\\n const rocsparse_int* bsr_row_ptr, \\\n const rocsparse_int* bsr_col_ind, \\\n rocsparse_int block_dim, \\\n rocsparse_mat_info info, \\\n const real_type_* B, \\\n rocsparse_int ldb, \\\n real_type_* X, \\\n rocsparse_int ldx, \\\n void* temp_buffer)\n\nINSTANTIATE(float, float);\nINSTANTIATE(float, const float*);\n\nINSTANTIATE(double, double);\nINSTANTIATE(double, const double*);\n\nINSTANTIATE(rocsparse_float_complex, rocsparse_float_complex);\nINSTANTIATE(rocsparse_float_complex, const rocsparse_float_complex*);\n\nINSTANTIATE(rocsparse_double_complex, rocsparse_double_complex);\nINSTANTIATE(rocsparse_double_complex, const rocsparse_double_complex*);\n#undef INSTANTIATE\n<commit_msg>navi21 fix for bsrsm (#237)<commit_after>\/*! \\file *\/\n\/* ************************************************************************\n * Copyright (c) 2021 Advanced Micro Devices, Inc.\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 * ************************************************************************ *\/\n\n#include \"bsrsm_device.h\"\n#include \"bsrsm_device_large.h\"\n#include \"definitions.h\"\n#include \"rocsparse_bsrsm.hpp\"\n#include \"utility.h\"\n\n#define LAUNCH_BSRSM_GTHR_DIM(bsize, wfsize, dim) \\\n hipLaunchKernelGGL((bsr_gather<wfsize, bsize \/ wfsize, dim>), \\\n dim3((wfsize * nnzb - 1) \/ bsize + 1), \\\n dim3(wfsize, bsize \/ wfsize), \\\n 0, \\\n stream, \\\n dir, \\\n nnzb, \\\n bsrsm_info->trmt_perm, \\\n bsr_val, \\\n bsrt_val, \\\n block_dim)\n\n#define LAUNCH_BSRSM_GTHR(bsize, wfsize, dim) \\\n if(dim <= 2) \\\n { \\\n LAUNCH_BSRSM_GTHR_DIM(bsize, 4, 2); \\\n } \\\n else if(dim <= 4) \\\n { \\\n LAUNCH_BSRSM_GTHR_DIM(bsize, 16, 4); \\\n } \\\n else if(wfsize == 32) \\\n { \\\n LAUNCH_BSRSM_GTHR_DIM(bsize, 16, 4); \\\n } \\\n else \\\n { \\\n LAUNCH_BSRSM_GTHR_DIM(bsize, 64, 8); \\\n }\n\ntemplate <unsigned int BLOCKSIZE, typename T, typename U>\n__launch_bounds__(BLOCKSIZE) __global__ void bsrsm_copy_scale(rocsparse_int m,\n rocsparse_int n,\n U alpha_device_host,\n const T* B,\n rocsparse_int ldb,\n T* X,\n rocsparse_int ldx)\n{\n auto alpha = load_scalar_device_host(alpha_device_host);\n\n bsrsm_copy_scale_device(m, n, alpha, B, ldb, X, ldx);\n}\n\ntemplate <unsigned int DIM_X, unsigned int DIM_Y, typename T, typename U>\n__launch_bounds__(DIM_X* DIM_Y) __global__ void bsrsm_transpose(rocsparse_int m,\n rocsparse_int n,\n U alpha_device_host,\n const T* __restrict__ A,\n rocsparse_int lda,\n T* __restrict__ B,\n rocsparse_int ldb)\n{\n auto alpha = load_scalar_device_host(alpha_device_host);\n\n dense_transpose_device<DIM_X, DIM_Y>(m, n, alpha, A, lda, B, ldb);\n}\n\ntemplate <typename T, typename U>\nrocsparse_status rocsparse_bsrsm_solve_template_large(rocsparse_handle handle,\n rocsparse_direction dir,\n rocsparse_operation trans_A,\n rocsparse_operation trans_X,\n rocsparse_int mb,\n rocsparse_int nrhs,\n rocsparse_int nnzb,\n U alpha,\n const rocsparse_mat_descr descr,\n const T* bsr_val,\n const rocsparse_int* bsr_row_ptr,\n const rocsparse_int* bsr_col_ind,\n rocsparse_int block_dim,\n rocsparse_mat_info info,\n const T* B,\n rocsparse_int ldb,\n T* X,\n rocsparse_int ldx,\n void* temp_buffer)\n{\n#define LAUNCH_LARGE_KERNEL(K_, M_, S_) \\\n dim3 bsrsm_blocks(((nrhs - 1) \/ NCOL + 1) * mb); \\\n dim3 bsrsm_threads(NCOL* M_); \\\n hipLaunchKernelGGL((K_<NCOL * M_, NCOL, S_>), \\\n bsrsm_blocks, \\\n bsrsm_threads, \\\n 0, \\\n stream, \\\n mb, \\\n nrhs, \\\n local_bsr_row_ptr, \\\n local_bsr_col_ind, \\\n local_bsr_val, \\\n block_dim, \\\n Xt, \\\n ldimX, \\\n done_array, \\\n bsrsm_info->row_map, \\\n info->zero_pivot, \\\n descr->base, \\\n descr->diag_type, \\\n dir);\n\n hipStream_t stream = handle->stream;\n\n \/\/ Buffer\n char* ptr = reinterpret_cast<char*>(temp_buffer);\n\n ptr += 256;\n\n \/\/ 16 columns per block seem to work very well\n static constexpr unsigned int NCOL = 16;\n\n int narrays = (nrhs - 1) \/ NCOL + 1;\n\n \/\/ done_array\n int* done_array = reinterpret_cast<int*>(ptr);\n ptr += sizeof(int) * ((mb * narrays - 1) \/ 256 + 1) * 256;\n\n \/\/ Temporary array to store transpose of X\n T* Xt = X;\n if(trans_X == rocsparse_operation_none)\n {\n Xt = reinterpret_cast<T*>(ptr);\n ptr += sizeof(T) * ((mb * block_dim * nrhs - 1) \/ 256 + 1) * 256;\n }\n\n \/\/ Initialize buffers\n RETURN_IF_HIP_ERROR(hipMemsetAsync(done_array, 0, sizeof(int) * mb * narrays, stream));\n\n rocsparse_trm_info bsrsm_info\n = (descr->fill_mode == rocsparse_fill_mode_upper)\n ? ((trans_A == rocsparse_operation_none) ? info->bsrsm_upper_info\n : info->bsrsmt_upper_info)\n : ((trans_A == rocsparse_operation_none) ? info->bsrsm_lower_info\n : info->bsrsmt_lower_info);\n\n \/\/ If diag type is unit, re-initialize zero pivot to remove structural zeros\n if(descr->diag_type == rocsparse_diag_type_unit)\n {\n rocsparse_int max = std::numeric_limits<rocsparse_int>::max();\n RETURN_IF_HIP_ERROR(hipMemcpyAsync(\n info->zero_pivot, &max, sizeof(rocsparse_int), hipMemcpyHostToDevice, stream));\n\n \/\/ Wait for device transfer to finish\n RETURN_IF_HIP_ERROR(hipStreamSynchronize(stream));\n }\n\n rocsparse_fill_mode fill_mode = descr->fill_mode;\n\n \/\/ Transpose X if X is not transposed yet to improve performance\n rocsparse_int ldimX = ldx;\n if(trans_X == rocsparse_operation_none)\n {\n \/\/ Leading dimension for transposed X\n ldimX = nrhs;\n\n#define BSRSM_DIM_X 32\n#define BSRSM_DIM_Y 8\n dim3 bsrsm_blocks((mb * block_dim - 1) \/ BSRSM_DIM_X + 1);\n dim3 bsrsm_threads(BSRSM_DIM_X * BSRSM_DIM_Y);\n\n hipLaunchKernelGGL((bsrsm_transpose<BSRSM_DIM_X, BSRSM_DIM_Y>),\n bsrsm_blocks,\n bsrsm_threads,\n 0,\n stream,\n mb * block_dim,\n nrhs,\n alpha,\n B,\n ldb,\n Xt,\n ldimX);\n#undef BSRSM_DIM_X\n#undef BSRSM_DIM_Y\n }\n else\n {\n \/\/ Copy B into X and scale it with alpha\n hipLaunchKernelGGL((bsrsm_copy_scale<1024>),\n dim3((mb * block_dim - 1) \/ 1024 + 1),\n dim3(1024),\n 0,\n stream,\n mb * block_dim,\n nrhs,\n alpha,\n B,\n ldb,\n X,\n ldx);\n }\n\n \/\/ Pointers to differentiate between transpose mode\n const rocsparse_int* local_bsr_row_ptr = bsr_row_ptr;\n const rocsparse_int* local_bsr_col_ind = bsr_col_ind;\n const T* local_bsr_val = bsr_val;\n\n \/\/ When computing transposed triangular solve, we first need to update the\n \/\/ transposed matrix values\n if(trans_A == rocsparse_operation_transpose)\n {\n T* bsrt_val = reinterpret_cast<T*>(ptr);\n\n LAUNCH_BSRSM_GTHR(256, 64, block_dim);\n\n local_bsr_row_ptr = bsrsm_info->trmt_row_ptr;\n local_bsr_col_ind = bsrsm_info->trmt_col_ind;\n local_bsr_val = bsrt_val;\n\n fill_mode = (fill_mode == rocsparse_fill_mode_lower) ? rocsparse_fill_mode_upper\n : rocsparse_fill_mode_lower;\n }\n\n \/\/ Determine gcnArch and ASIC revision\n int gcnArch = handle->properties.gcnArch;\n int asicRev = handle->asic_rev;\n int wfSize = handle->wavefront_size;\n\n \/\/ gfx908 A0\/1\n if(gcnArch == 908 && asicRev < 2)\n {\n if(fill_mode == rocsparse_fill_mode_upper)\n {\n LAUNCH_LARGE_KERNEL(bsrsm_upper_large_kernel, 16, true);\n }\n else\n {\n LAUNCH_LARGE_KERNEL(bsrsm_lower_large_kernel, 16, true);\n }\n }\n else\n {\n \/\/ Select tuned kernel\n unsigned int nbsr = std::max(4U, fnp2(block_dim));\n\n while(nbsr > wfSize)\n {\n nbsr >>= 1;\n }\n\n switch(nbsr)\n {\n#define DEFINE_CASE(i) \\\n case i: \\\n { \\\n if(fill_mode == rocsparse_fill_mode_upper) \\\n { \\\n LAUNCH_LARGE_KERNEL(bsrsm_upper_large_kernel, i, false); \\\n } \\\n else \\\n { \\\n LAUNCH_LARGE_KERNEL(bsrsm_lower_large_kernel, i, false); \\\n } \\\n break; \\\n }\n\n DEFINE_CASE(4);\n DEFINE_CASE(8);\n DEFINE_CASE(16);\n DEFINE_CASE(32);\n DEFINE_CASE(64);\n#undef DEFINE_CASE\n }\n }\n#undef LAUNCH_LARGE_KERNEL\n\n \/\/ Transpose X back if X was not initially transposed\n if(trans_X == rocsparse_operation_none)\n {\n#define BSRSM_DIM_X 32\n#define BSRSM_DIM_Y 8\n dim3 bsrsm_blocks((mb * block_dim - 1) \/ BSRSM_DIM_X + 1);\n dim3 bsrsm_threads(BSRSM_DIM_X * BSRSM_DIM_Y);\n\n hipLaunchKernelGGL((dense_transpose_back<BSRSM_DIM_X, BSRSM_DIM_Y>),\n bsrsm_blocks,\n bsrsm_threads,\n 0,\n stream,\n mb * block_dim,\n nrhs,\n Xt,\n ldimX,\n X,\n ldx);\n#undef BSRSM_DIM_X\n#undef BSRSM_DIM_Y\n }\n\n return rocsparse_status_success;\n}\n\n#define INSTANTIATE(real_type_, scalar_type_) \\\n template rocsparse_status rocsparse_bsrsm_solve_template_large( \\\n rocsparse_handle handle, \\\n rocsparse_direction dir, \\\n rocsparse_operation trans_A, \\\n rocsparse_operation trans_X, \\\n rocsparse_int mb, \\\n rocsparse_int nrhs, \\\n rocsparse_int nnzb, \\\n scalar_type_ alpha, \\\n const rocsparse_mat_descr descr, \\\n const real_type_* bsr_val, \\\n const rocsparse_int* bsr_row_ptr, \\\n const rocsparse_int* bsr_col_ind, \\\n rocsparse_int block_dim, \\\n rocsparse_mat_info info, \\\n const real_type_* B, \\\n rocsparse_int ldb, \\\n real_type_* X, \\\n rocsparse_int ldx, \\\n void* temp_buffer)\n\nINSTANTIATE(float, float);\nINSTANTIATE(float, const float*);\n\nINSTANTIATE(double, double);\nINSTANTIATE(double, const double*);\n\nINSTANTIATE(rocsparse_float_complex, rocsparse_float_complex);\nINSTANTIATE(rocsparse_float_complex, const rocsparse_float_complex*);\n\nINSTANTIATE(rocsparse_double_complex, rocsparse_double_complex);\nINSTANTIATE(rocsparse_double_complex, const rocsparse_double_complex*);\n#undef INSTANTIATE\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2008 by Frank Richter\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\n#include \"csplugincommon\/rendermanager\/autofx_reflrefr.h\"\n\n#include \"csutil\/cfgacc.h\"\n#include \"csutil\/objreg.h\"\n#include \"imap\/loader.h\"\n\nnamespace CS\n{\n namespace RenderManager\n {\n#define AFRRBPD AutoFX_ReflectRefract_Base::PersistentData\n \n AFRRBPD::PersistentData() :\n currentFrame (0),\n texCache (csimg2D, \"rgb8\", \/\/ @@@ FIXME: Use same format as main view ...\n\tCS_TEXTURE_3D | CS_TEXTURE_NOMIPMAPS | CS_TEXTURE_CLAMP\n\t | CS_TEXTURE_NPOTS | CS_TEXTURE_CLAMP | CS_TEXTURE_SCALE_UP,\n\t\"target\", 0,\n\tCS::Utility::ResourceCache::ReuseIfOnlyOneRef ()),\n texCacheDepth (csimg2D, \"d32\",\n\tCS_TEXTURE_3D | CS_TEXTURE_NOMIPMAPS | CS_TEXTURE_CLAMP\n\t | CS_TEXTURE_NPOTS | CS_TEXTURE_CLAMP | CS_TEXTURE_SCALE_UP,\n\t\"target\", 0,\n\tCS::Utility::ResourceCache::ReuseIfOnlyOneRef ())\n {\n }\n\n void AFRRBPD::Initialize (iObjectRegistry* objReg,\n\t\t RenderTreeBase::DebugPersistent& dbgPersist,\n\t\t PostEffectManager* postEffects)\n {\n dbgReflRefrTex = dbgPersist.RegisterDebugFlag (\"textures.reflrefr\");\n \n csRef<iShaderManager> shaderManager =\n\tcsQueryRegistry<iShaderManager> (objReg);\n \n iShaderVarStringSet* strings = shaderManager->GetSVNameStringset();\n svTexPlaneRefl = strings->Request (\"tex plane reflect\");\n svTexPlaneRefr = strings->Request (\"tex plane refract\");\n svTexPlaneReflDepth = strings->Request (\"tex plane reflect depth\");\n svTexPlaneRefrDepth = strings->Request (\"tex plane refract depth\");\n \n svPlaneRefl = strings->Request (\"plane reflection\");\n svClipPlaneReflRefr = strings->Request (\"clip plane reflection\");\n \n csConfigAccess config (objReg);\n resolutionReduceRefl = config->GetInt (\n\t\"RenderManager.Reflections.Downsample\", 1);\n resolutionReduceRefr = config->GetInt (\n\t\"RenderManager.Refractions.Downsample\", resolutionReduceRefl);\n texUpdateInterval = config->GetInt (\n\t\"RenderManager.Reflections.UpdateInterval\", 0);\n maxUpdatesPerFrame = config->GetInt (\n\t\"RenderManager.Reflections.MaxUpdatesPerFrame\", 0);\n mappingStretch = config->GetFloat (\n\t\"RenderManager.Reflections.MappingStretch\", 1.0f);\n cameraChangeThresh = config->GetFloat (\n\t\"RenderManager.Reflections.CameraChangeThreshold\", 0.01f);\n \n svReflXform = strings->Request (\"reflection coord xform\");\n reflXformSV.AttachNew (new csShaderVariable (svReflXform));\n screenFlipped = postEffects ? postEffects->ScreenSpaceYFlipped() : false;\n\t\n csRef<iGraphics3D> g3d = csQueryRegistry<iGraphics3D> (objReg);\n texCache.SetG3D (g3d);\n texCacheDepth.SetG3D (g3d);\n }\n\n void AFRRBPD::UpdateNewFrame ()\n {\n csTicks currentTicks = csGetTicks ();\n ReflRefrCache::GlobalIterator reflRefrIt (\n\treflRefrCache.GetIterator ());\n while (reflRefrIt.HasNext())\n {\n\tReflectRefractSVs& meshReflectRefract = reflRefrIt.NextNoAdvance();\n\t\/\/ Don't remove if update interval hasn't passed yet\n\tif ((texUpdateInterval > 0)\n\t && ((currentTicks - meshReflectRefract.lastUpdate) <=\n\t texUpdateInterval))\n\t{\n\t reflRefrIt.Next();\n\t continue;\n\t}\n\t\/\/ Don't remove if not in line for round-robin update\n\tif ((maxUpdatesPerFrame > 0)\n\t && (currentFrame - meshReflectRefract.lastUpdateFrame < \n\t ((reflRefrCache.GetSize()+maxUpdatesPerFrame-1) \/ maxUpdatesPerFrame)))\n\t{\n\t reflRefrIt.Next();\n\t continue;\n\t}\n\treflRefrCache.DeleteElement (reflRefrIt);\n }\n \n currentFrame++;\n updatesThisFrame = 0;\n \n texCache.AdvanceFrame (currentTicks);\n texCacheDepth.AdvanceFrame (currentTicks);\n }\n } \/\/ namespace RenderManager\n} \/\/ namespace CS\n<commit_msg>- Added CS_TEXTURE_NOFILTER flag to water depth texture. Fixes issues with pre-GF8 cards.<commit_after>\/*\n Copyright (C) 2008 by Frank Richter\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\n#include \"csplugincommon\/rendermanager\/autofx_reflrefr.h\"\n\n#include \"csutil\/cfgacc.h\"\n#include \"csutil\/objreg.h\"\n#include \"imap\/loader.h\"\n\nnamespace CS\n{\n namespace RenderManager\n {\n#define AFRRBPD AutoFX_ReflectRefract_Base::PersistentData\n \n AFRRBPD::PersistentData() :\n currentFrame (0),\n texCache (csimg2D, \"rgb8\", \/\/ @@@ FIXME: Use same format as main view ...\n\tCS_TEXTURE_3D | CS_TEXTURE_NOMIPMAPS | CS_TEXTURE_CLAMP\n\t | CS_TEXTURE_NPOTS | CS_TEXTURE_CLAMP | CS_TEXTURE_SCALE_UP,\n\t\"target\", 0,\n\tCS::Utility::ResourceCache::ReuseIfOnlyOneRef ()),\n texCacheDepth (csimg2D, \"d32\",\n\tCS_TEXTURE_3D | CS_TEXTURE_NOMIPMAPS | CS_TEXTURE_CLAMP\n\t | CS_TEXTURE_NPOTS | CS_TEXTURE_CLAMP | CS_TEXTURE_SCALE_UP | CS_TEXTURE_NOFILTER,\n\t\"target\", 0,\n\tCS::Utility::ResourceCache::ReuseIfOnlyOneRef ())\n {\n }\n\n void AFRRBPD::Initialize (iObjectRegistry* objReg,\n\t\t RenderTreeBase::DebugPersistent& dbgPersist,\n\t\t PostEffectManager* postEffects)\n {\n dbgReflRefrTex = dbgPersist.RegisterDebugFlag (\"textures.reflrefr\");\n \n csRef<iShaderManager> shaderManager =\n\tcsQueryRegistry<iShaderManager> (objReg);\n \n iShaderVarStringSet* strings = shaderManager->GetSVNameStringset();\n svTexPlaneRefl = strings->Request (\"tex plane reflect\");\n svTexPlaneRefr = strings->Request (\"tex plane refract\");\n svTexPlaneReflDepth = strings->Request (\"tex plane reflect depth\");\n svTexPlaneRefrDepth = strings->Request (\"tex plane refract depth\");\n \n svPlaneRefl = strings->Request (\"plane reflection\");\n svClipPlaneReflRefr = strings->Request (\"clip plane reflection\");\n \n csConfigAccess config (objReg);\n resolutionReduceRefl = config->GetInt (\n\t\"RenderManager.Reflections.Downsample\", 1);\n resolutionReduceRefr = config->GetInt (\n\t\"RenderManager.Refractions.Downsample\", resolutionReduceRefl);\n texUpdateInterval = config->GetInt (\n\t\"RenderManager.Reflections.UpdateInterval\", 0);\n maxUpdatesPerFrame = config->GetInt (\n\t\"RenderManager.Reflections.MaxUpdatesPerFrame\", 0);\n mappingStretch = config->GetFloat (\n\t\"RenderManager.Reflections.MappingStretch\", 1.0f);\n cameraChangeThresh = config->GetFloat (\n\t\"RenderManager.Reflections.CameraChangeThreshold\", 0.01f);\n \n svReflXform = strings->Request (\"reflection coord xform\");\n reflXformSV.AttachNew (new csShaderVariable (svReflXform));\n screenFlipped = postEffects ? postEffects->ScreenSpaceYFlipped() : false;\n\t\n csRef<iGraphics3D> g3d = csQueryRegistry<iGraphics3D> (objReg);\n texCache.SetG3D (g3d);\n texCacheDepth.SetG3D (g3d);\n }\n\n void AFRRBPD::UpdateNewFrame ()\n {\n csTicks currentTicks = csGetTicks ();\n ReflRefrCache::GlobalIterator reflRefrIt (\n\treflRefrCache.GetIterator ());\n while (reflRefrIt.HasNext())\n {\n\tReflectRefractSVs& meshReflectRefract = reflRefrIt.NextNoAdvance();\n\t\/\/ Don't remove if update interval hasn't passed yet\n\tif ((texUpdateInterval > 0)\n\t && ((currentTicks - meshReflectRefract.lastUpdate) <=\n\t texUpdateInterval))\n\t{\n\t reflRefrIt.Next();\n\t continue;\n\t}\n\t\/\/ Don't remove if not in line for round-robin update\n\tif ((maxUpdatesPerFrame > 0)\n\t && (currentFrame - meshReflectRefract.lastUpdateFrame < \n\t ((reflRefrCache.GetSize()+maxUpdatesPerFrame-1) \/ maxUpdatesPerFrame)))\n\t{\n\t reflRefrIt.Next();\n\t continue;\n\t}\n\treflRefrCache.DeleteElement (reflRefrIt);\n }\n \n currentFrame++;\n updatesThisFrame = 0;\n \n texCache.AdvanceFrame (currentTicks);\n texCacheDepth.AdvanceFrame (currentTicks);\n }\n } \/\/ namespace RenderManager\n} \/\/ namespace CS\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 2000-2017 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"cat_update.h\"\n\n#include \"extractors\/extractor.h\"\n#include \"progressinfo.h\"\n#include \"utility.h\"\n\n#include <wx\/config.h>\n#include <wx\/dialog.h>\n#include <wx\/intl.h>\n#include <wx\/listbox.h>\n#include <wx\/log.h>\n#include <wx\/stattext.h>\n#include <wx\/xrc\/xmlres.h>\n\n\nnamespace\n{\n\n\/** This class provides simple dialog that displays list\n * of changes made in the catalog.\n *\/\nclass MergeSummaryDialog : public wxDialog\n{\n public:\n MergeSummaryDialog(wxWindow *parent);\n ~MergeSummaryDialog();\n\n \/** Reads data from catalog and fill dialog's controls.\n \\param snew list of strings that are new to the catalog\n \\param sobsolete list of strings that no longer appear in the\n catalog (as compared to catalog's state before\n parsing sources).\n *\/\n void TransferTo(const wxArrayString& snew, \n const wxArrayString& sobsolete);\n};\n\n\nMergeSummaryDialog::MergeSummaryDialog(wxWindow *parent)\n{\n wxXmlResource::Get()->LoadDialog(this, parent, \"summary\");\n\n RestoreWindowState(this, wxDefaultSize, WinState_Size);\n CentreOnParent();\n}\n\n\nMergeSummaryDialog::~MergeSummaryDialog()\n{\n SaveWindowState(this, WinState_Size);\n}\n\n\nvoid MergeSummaryDialog::TransferTo(const wxArrayString& snew, const wxArrayString& sobsolete)\n{\n wxString sum;\n sum.Printf(_(\"(New: %i, obsolete: %i)\"),\n (int)snew.GetCount(), (int)sobsolete.GetCount());\n XRCCTRL(*this, \"items_count\", wxStaticText)->SetLabel(sum);\n\n wxListBox *listbox;\n size_t i;\n \n listbox = XRCCTRL(*this, \"new_strings\", wxListBox);\n for (i = 0; i < snew.GetCount(); i++)\n {\n listbox->Append(snew[i]);\n }\n\n listbox = XRCCTRL(*this, \"obsolete_strings\", wxListBox);\n for (i = 0; i < sobsolete.GetCount(); i++)\n {\n listbox->Append(sobsolete[i]);\n }\n}\n\n\ninline wxString ItemMergeSummary(const CatalogItemPtr& item)\n{\n wxString s = item->GetString();\n if ( item->HasPlural() )\n s += \"|\" + item->GetPluralString();\n if ( item->HasContext() )\n s += wxString::Format(\" [%s]\", item->GetContext());\n\n return s;\n}\n\n\/** Returns list of strings that are new in reference catalog\n (compared to this one) and that are not present in \\a refcat\n (i.e. are obsoleted).\n\n \\see ShowMergeSummary\n *\/\nvoid GetMergeSummary(CatalogPtr po, CatalogPtr refcat,\n wxArrayString& snew, wxArrayString& sobsolete)\n{\n wxASSERT( snew.empty() );\n wxASSERT( sobsolete.empty() );\n\n std::set<wxString> strsThis, strsRef;\n\n for (auto& i: po->items())\n strsThis.insert(ItemMergeSummary(i));\n for (auto& i: refcat->items())\n strsRef.insert(ItemMergeSummary(i));\n\n for (auto& i: strsThis)\n {\n if (strsRef.find(i) == strsRef.end())\n sobsolete.Add(i);\n }\n\n for (auto& i: strsRef)\n {\n if (strsThis.find(i) == strsThis.end())\n snew.Add(i);\n }\n}\n\n\/** Shows a dialog with merge summary.\n \\see GetMergeSummary, Merge\n\n \\return true if the merge was OK'ed by the user, false otherwise\n *\/\nbool ShowMergeSummary(wxWindow *parent, ProgressInfo *progress, CatalogPtr po, CatalogPtr refcat, bool *cancelledByUser)\n{\n if (cancelledByUser)\n *cancelledByUser = false;\n if (wxConfig::Get()->ReadBool(\"show_summary\", false))\n {\n wxArrayString snew, sobsolete;\n GetMergeSummary(po, refcat, snew, sobsolete);\n MergeSummaryDialog sdlg(parent);\n sdlg.TransferTo(snew, sobsolete);\n\n if (progress)\n progress->Hide();\n bool ok = (sdlg.ShowModal() == wxID_OK);\n if (progress)\n progress->Show();\n\n if (cancelledByUser)\n *cancelledByUser = !ok;\n return ok;\n }\n else\n return true;\n}\n\n} \/\/ anonymous namespace\n\n\nbool PerformUpdateFromSources(wxWindow *parent,\n CatalogPtr catalog,\n UpdateResultReason& reason,\n int flags)\n{\n const bool skipSummary = (flags & Update_DontShowSummary);\n\n ProgressInfo progress(parent, _(\"Updating catalog\"));\n\n reason = UpdateResultReason::Unspecified;\n if (!catalog->IsOk())\n return false;\n\n auto spec = catalog->GetSourceCodeSpec();\n if (!spec)\n {\n reason = UpdateResultReason::NoSourcesFound;\n return false;\n }\n\n CatalogPtr pot = nullptr;\n\n progress.UpdateMessage(_(\"Scanning files...\"));\n progress.PulseGauge();\n\n auto files = Extractor::CollectAllFiles(*spec);\n\n if (!files.empty())\n {\n TempDirectory tmpdir;\n auto potFile = Extractor::ExtractWithAll(tmpdir, *spec, files);\n if (!potFile.empty())\n {\n pot = std::make_shared<Catalog>(potFile, Catalog::CreationFlag_IgnoreHeader);\n if (!pot->IsOk())\n {\n wxLogError(_(\"Failed to load extracted catalog.\"));\n pot.reset();\n }\n }\n }\n else\n {\n reason = UpdateResultReason::NoSourcesFound;\n }\n\n if (progress.Cancelled())\n {\n reason = UpdateResultReason::CancelledByUser;\n return false;\n }\n\n if (!pot)\n return false;\n\n progress.UpdateMessage(_(\"Merging differences...\"));\n\n bool succ = false;\n bool cancelledByUser = false;\n if (skipSummary || ShowMergeSummary(parent, &progress, catalog, pot, &cancelledByUser))\n {\n succ = catalog->UpdateFromPOT(pot);\n }\n\n if (cancelledByUser)\n reason = UpdateResultReason::CancelledByUser;\n\n return succ;\n}\n\n\nbool PerformUpdateFromPOT(wxWindow *parent,\n CatalogPtr catalog,\n const wxString& pot_file,\n UpdateResultReason& reason)\n{\n reason = UpdateResultReason::Unspecified;\n if (!catalog->IsOk())\n return false;\n\n CatalogPtr pot = std::make_shared<Catalog>(pot_file, Catalog::CreationFlag_IgnoreTranslations);\n\n if (!pot->IsOk())\n {\n wxLogError(_(\"'%s' is not a valid POT file.\"), pot_file.c_str());\n return false;\n }\n\n bool cancelledByUser = false;\n if (ShowMergeSummary(parent, nullptr, catalog, pot, &cancelledByUser))\n {\n return catalog->UpdateFromPOT(pot);\n }\n else\n {\n if (cancelledByUser)\n reason = UpdateResultReason::CancelledByUser;\n return false;\n }\n}\n<commit_msg>More granular, better progress messages during update<commit_after>\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 2000-2017 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"cat_update.h\"\n\n#include \"extractors\/extractor.h\"\n#include \"progressinfo.h\"\n#include \"utility.h\"\n\n#include <wx\/config.h>\n#include <wx\/dialog.h>\n#include <wx\/intl.h>\n#include <wx\/listbox.h>\n#include <wx\/log.h>\n#include <wx\/stattext.h>\n#include <wx\/xrc\/xmlres.h>\n\n\nnamespace\n{\n\n\/** This class provides simple dialog that displays list\n * of changes made in the catalog.\n *\/\nclass MergeSummaryDialog : public wxDialog\n{\n public:\n MergeSummaryDialog(wxWindow *parent);\n ~MergeSummaryDialog();\n\n \/** Reads data from catalog and fill dialog's controls.\n \\param snew list of strings that are new to the catalog\n \\param sobsolete list of strings that no longer appear in the\n catalog (as compared to catalog's state before\n parsing sources).\n *\/\n void TransferTo(const wxArrayString& snew, \n const wxArrayString& sobsolete);\n};\n\n\nMergeSummaryDialog::MergeSummaryDialog(wxWindow *parent)\n{\n wxXmlResource::Get()->LoadDialog(this, parent, \"summary\");\n\n RestoreWindowState(this, wxDefaultSize, WinState_Size);\n CentreOnParent();\n}\n\n\nMergeSummaryDialog::~MergeSummaryDialog()\n{\n SaveWindowState(this, WinState_Size);\n}\n\n\nvoid MergeSummaryDialog::TransferTo(const wxArrayString& snew, const wxArrayString& sobsolete)\n{\n wxString sum;\n sum.Printf(_(\"(New: %i, obsolete: %i)\"),\n (int)snew.GetCount(), (int)sobsolete.GetCount());\n XRCCTRL(*this, \"items_count\", wxStaticText)->SetLabel(sum);\n\n wxListBox *listbox;\n size_t i;\n \n listbox = XRCCTRL(*this, \"new_strings\", wxListBox);\n for (i = 0; i < snew.GetCount(); i++)\n {\n listbox->Append(snew[i]);\n }\n\n listbox = XRCCTRL(*this, \"obsolete_strings\", wxListBox);\n for (i = 0; i < sobsolete.GetCount(); i++)\n {\n listbox->Append(sobsolete[i]);\n }\n}\n\n\ninline wxString ItemMergeSummary(const CatalogItemPtr& item)\n{\n wxString s = item->GetString();\n if ( item->HasPlural() )\n s += \"|\" + item->GetPluralString();\n if ( item->HasContext() )\n s += wxString::Format(\" [%s]\", item->GetContext());\n\n return s;\n}\n\n\/** Returns list of strings that are new in reference catalog\n (compared to this one) and that are not present in \\a refcat\n (i.e. are obsoleted).\n\n \\see ShowMergeSummary\n *\/\nvoid GetMergeSummary(CatalogPtr po, CatalogPtr refcat,\n wxArrayString& snew, wxArrayString& sobsolete)\n{\n wxASSERT( snew.empty() );\n wxASSERT( sobsolete.empty() );\n\n std::set<wxString> strsThis, strsRef;\n\n for (auto& i: po->items())\n strsThis.insert(ItemMergeSummary(i));\n for (auto& i: refcat->items())\n strsRef.insert(ItemMergeSummary(i));\n\n for (auto& i: strsThis)\n {\n if (strsRef.find(i) == strsRef.end())\n sobsolete.Add(i);\n }\n\n for (auto& i: strsRef)\n {\n if (strsThis.find(i) == strsThis.end())\n snew.Add(i);\n }\n}\n\n\/** Shows a dialog with merge summary.\n \\see GetMergeSummary, Merge\n\n \\return true if the merge was OK'ed by the user, false otherwise\n *\/\nbool ShowMergeSummary(wxWindow *parent, ProgressInfo *progress, CatalogPtr po, CatalogPtr refcat, bool *cancelledByUser)\n{\n if (cancelledByUser)\n *cancelledByUser = false;\n if (wxConfig::Get()->ReadBool(\"show_summary\", false))\n {\n wxArrayString snew, sobsolete;\n GetMergeSummary(po, refcat, snew, sobsolete);\n MergeSummaryDialog sdlg(parent);\n sdlg.TransferTo(snew, sobsolete);\n\n if (progress)\n progress->Hide();\n bool ok = (sdlg.ShowModal() == wxID_OK);\n if (progress)\n progress->Show();\n\n if (cancelledByUser)\n *cancelledByUser = !ok;\n return ok;\n }\n else\n return true;\n}\n\n} \/\/ anonymous namespace\n\n\nbool PerformUpdateFromSources(wxWindow *parent,\n CatalogPtr catalog,\n UpdateResultReason& reason,\n int flags)\n{\n const bool skipSummary = (flags & Update_DontShowSummary);\n\n ProgressInfo progress(parent, _(\"Updating catalog\"));\n\n reason = UpdateResultReason::Unspecified;\n if (!catalog->IsOk())\n return false;\n\n auto spec = catalog->GetSourceCodeSpec();\n if (!spec)\n {\n reason = UpdateResultReason::NoSourcesFound;\n return false;\n }\n\n CatalogPtr pot = nullptr;\n\n progress.PulseGauge();\n progress.UpdateMessage(_(\"Collecting source files...\"));\n\n auto files = Extractor::CollectAllFiles(*spec);\n\n progress.PulseGauge();\n progress.UpdateMessage(_(\"Extracting translatable strings...\"));\n\n if (!files.empty())\n {\n TempDirectory tmpdir;\n auto potFile = Extractor::ExtractWithAll(tmpdir, *spec, files);\n if (!potFile.empty())\n {\n pot = std::make_shared<Catalog>(potFile, Catalog::CreationFlag_IgnoreHeader);\n if (!pot->IsOk())\n {\n wxLogError(_(\"Failed to load extracted catalog.\"));\n pot.reset();\n }\n }\n }\n else\n {\n reason = UpdateResultReason::NoSourcesFound;\n }\n\n if (progress.Cancelled())\n {\n reason = UpdateResultReason::CancelledByUser;\n return false;\n }\n\n if (!pot)\n return false;\n\n progress.UpdateMessage(_(\"Merging differences...\"));\n\n bool succ = false;\n bool cancelledByUser = false;\n if (skipSummary || ShowMergeSummary(parent, &progress, catalog, pot, &cancelledByUser))\n {\n succ = catalog->UpdateFromPOT(pot);\n }\n\n if (cancelledByUser)\n reason = UpdateResultReason::CancelledByUser;\n\n return succ;\n}\n\n\nbool PerformUpdateFromPOT(wxWindow *parent,\n CatalogPtr catalog,\n const wxString& pot_file,\n UpdateResultReason& reason)\n{\n reason = UpdateResultReason::Unspecified;\n if (!catalog->IsOk())\n return false;\n\n CatalogPtr pot = std::make_shared<Catalog>(pot_file, Catalog::CreationFlag_IgnoreTranslations);\n\n if (!pot->IsOk())\n {\n wxLogError(_(\"'%s' is not a valid POT file.\"), pot_file.c_str());\n return false;\n }\n\n bool cancelledByUser = false;\n if (ShowMergeSummary(parent, nullptr, catalog, pot, &cancelledByUser))\n {\n return catalog->UpdateFromPOT(pot);\n }\n else\n {\n if (cancelledByUser)\n reason = UpdateResultReason::CancelledByUser;\n return false;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Scripting.h\"\n#include \"Log.h\"\n#include \"platform.h\"\n#include \"utils\/FileSystemUtil.h\"\n\nnamespace Scripting\n{\n int fireEvent(const std::string& eventName, const std::string& arg1, const std::string& arg2)\n {\n LOG(LogDebug) << \"fireEvent: \" << eventName << \" \" << arg1 << \" \" << arg2;\n\n std::list<std::string> scriptDirList;\n std::string test;\n\n \/\/ check in exepath\n test = Utils::FileSystem::getExePath() + \"\/scripts\/\" + eventName;\n if(Utils::FileSystem::exists(test))\n scriptDirList.push_back(test);\n\n \/\/ check in homepath\n test = Utils::FileSystem::getHomePath() + \"\/.emulationstation\/scripts\/\" + eventName;\n if(Utils::FileSystem::exists(test))\n scriptDirList.push_back(test);\n \/\/ loop over found script paths per event and over scripts found in eventName folder.\n for(std::list<std::string>::const_iterator dirIt = scriptDirList.cbegin(); dirIt != scriptDirList.cend(); ++dirIt) {\n std::list<std::string> scripts = Utils::FileSystem::getDirContent(*dirIt);\n for (std::list<std::string>::const_iterator it = scripts.cbegin(); it != scripts.cend(); ++it) {\n#ifndef WIN32 \/\/ osx \/ linux\n if (!Utils::FileSystem::isExecutable(*it)) {\n LOG(LogWarning) << *it << \" is not executable. Did you 'chmod u+x'?. Skipping this script.\";\n continue;\n }\n#endif\n std::string script = *it;\n if (arg1.length() > 0) {\n script += \" \\\"\" + arg1 + \"\\\"\";\n if (arg2.length() > 0) {\n script += \" \\\"\" + arg2 + \"\\\"\";\n }\n }\n LOG(LogDebug) << \" executing: \" << script;\n return runSystemCommand(script);\n }\n }\n }\n\n} \/\/ Scripting::\n<commit_msg>Fix to terminate execution of scripts if current script fails.<commit_after>#include \"Scripting.h\"\n#include \"Log.h\"\n#include \"platform.h\"\n#include \"utils\/FileSystemUtil.h\"\n\nnamespace Scripting\n{\n int fireEvent(const std::string& eventName, const std::string& arg1, const std::string& arg2)\n {\n LOG(LogDebug) << \"fireEvent: \" << eventName << \" \" << arg1 << \" \" << arg2;\n\n std::list<std::string> scriptDirList;\n std::string test;\n\n \/\/ check in exepath\n test = Utils::FileSystem::getExePath() + \"\/scripts\/\" + eventName;\n if(Utils::FileSystem::exists(test))\n scriptDirList.push_back(test);\n\n \/\/ check in homepath\n test = Utils::FileSystem::getHomePath() + \"\/.emulationstation\/scripts\/\" + eventName;\n if(Utils::FileSystem::exists(test))\n scriptDirList.push_back(test);\n int ret = 0;\n \/\/ loop over found script paths per event and over scripts found in eventName folder.\n for(std::list<std::string>::const_iterator dirIt = scriptDirList.cbegin(); dirIt != scriptDirList.cend(); ++dirIt) {\n std::list<std::string> scripts = Utils::FileSystem::getDirContent(*dirIt);\n for (std::list<std::string>::const_iterator it = scripts.cbegin(); it != scripts.cend(); ++it) {\n#ifndef WIN32 \/\/ osx \/ linux\n if (!Utils::FileSystem::isExecutable(*it)) {\n LOG(LogWarning) << *it << \" is not executable. Did you 'chmod u+x'?. Skipping this script.\";\n continue;\n }\n#endif\n std::string script = *it;\n if (arg1.length() > 0) {\n script += \" \\\"\" + arg1 + \"\\\"\";\n if (arg2.length() > 0) {\n script += \" \\\"\" + arg2 + \"\\\"\";\n }\n }\n LOG(LogDebug) << \"executing: \" << script;\n ret = runSystemCommand(script);\n if (ret != 0) {\n LOG(LogWarning) << script << \" failed with rc != 0. Skipping further processing of scripts.\";\n return ret;\n }\n }\n }\n return ret;\n }\n\n} \/\/ Scripting::\n<|endoftext|>"} {"text":"<commit_before>#ifndef MAKE_UNIQUE_HPP\n#define MAKE_UNIQUE_HPP\n\n#include <memory>\n\n#include \"namespace_utils.hpp\"\n\nBEGIN_NAMESPACE_ETL\n\nBEGIN_NAMESPACE_UTILS\n\ntemplate <typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args)\n{\n\treturn std::unique_ptr<T>(new T(std::forward<Args>(args)...));\n}\n\nEND_NAMESPACE_UTILS\n\nEND_NAMESPACE_ETL\n\n#endif \/\/ MAKE_UNIQUE_HPP\n<commit_msg>small correction<commit_after>#ifndef MAKE_UNIQUE_HPP\n#define MAKE_UNIQUE_HPP\n\n#include <memory>\n\n#include \"namespace_utils.hpp\"\n\nBEGIN_NAMESPACE_ETL\n\nBEGIN_NAMESPACE_UTILS\n\ntemplate<class T, class ... Args> std::unique_ptr<T> make_unique(Args&&... args)\n{\n\treturn std::unique_ptr<T>(new T(std::forward<Args>(args)...));\n}\n\nEND_NAMESPACE_UTILS\n\nEND_NAMESPACE_ETL\n\n#endif \/\/ MAKE_UNIQUE_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"clustering.hpp\"\n\n#include \"constant_series.hpp\"\n#include \"monomials.hpp\"\n#include \"nchoosek.hpp\"\n#include \"p_max_total.hpp\"\n\n\nnamespace fgt {\n\n\nnamespace {\n\n\ndouble ddist(const arma::rowvec& x, const arma::rowvec& y) {\n return arma::accu(arma::pow(x - y, 2));\n}\n}\n\n\nClustering::Clustering(const arma::mat& source, arma::uword K, double bandwidth,\n double epsilon)\n : m_source(source),\n m_K(K),\n m_indices(arma::zeros<arma::uvec>(source.n_rows)),\n m_centers(arma::zeros<arma::mat>(K, source.n_cols)),\n m_num_points(arma::zeros<arma::uvec>(K)),\n m_radii(K),\n m_rx(),\n m_bandwidth(bandwidth),\n m_epsilon(epsilon),\n m_p_max(0),\n m_constant_series() {}\n\n\nClustering::~Clustering() {}\n\n\narma::uword Clustering::choose_truncation_number(int dimensions,\n double bandwidth,\n double epsilon, double rx) {\n double r = std::min(std::sqrt(dimensions),\n bandwidth * std::sqrt(std::log(1 \/ epsilon)));\n double rx2 = rx * rx;\n double h2 = bandwidth * bandwidth;\n double error = 1;\n double temp = 1;\n int p = 0;\n\n while ((error > epsilon) and (p <= TruncationNumberUpperLimit)) {\n ++p;\n double b = std::min((rx + std::sqrt(rx2 + 2 * p * h2)) \/ 2, rx + r);\n double c = rx - b;\n temp *= 2 * rx * b \/ h2 \/ p;\n error = temp * std::exp(-c * c \/ h2);\n }\n\n return p;\n}\n\n\nvoid Clustering::cluster() {\n cluster_impl();\n m_p_max =\n choose_truncation_number(m_source.n_cols, m_bandwidth, m_epsilon, m_rx);\n m_constant_series = compute_constant_series(m_source.n_cols, m_p_max);\n}\n\n\narma::mat Clustering::compute_C(const arma::vec& q) const {\n arma::mat C = arma::zeros<arma::mat>(\n m_centers.n_rows, get_p_max_total(m_source.n_cols, m_p_max));\n std::vector<double> monomials(C.n_cols);\n double h2 = m_bandwidth * m_bandwidth;\n\n for (arma::uword i = 0; i < m_source.n_rows; ++i) {\n arma::uword k = m_indices(i);\n arma::rowvec dx = m_source.row(i) - m_centers.row(k);\n double distance2 = arma::accu(arma::pow(dx, 2));\n compute_monomials(dx \/ m_bandwidth, m_p_max, monomials);\n double f = q(i) * std::exp(-distance2 \/ h2);\n \/\/ TODO remove rowvec\n arma::rowvec center_monomials(monomials);\n C.row(k) += f * center_monomials;\n }\n\n arma::rowvec constant_series =\n compute_constant_series(m_source.n_cols, m_p_max);\n for (arma::uword i = 0; i < C.n_rows; ++i) {\n C.row(i) = C.row(i) % constant_series;\n }\n\n return C;\n}\n\n\nconst optional_arma_uword_t GonzalezClustering::DefaultStartingIndex = {false,\n 0};\n\n\nGonzalezClustering::GonzalezClustering(const arma::mat& source, int K,\n double bandwidth, double epsilon,\n optional_arma_uword_t starting_index)\n : Clustering(source, K, bandwidth, epsilon),\n m_starting_index(starting_index) {}\n\n\nvoid GonzalezClustering::cluster_impl() {\n arma::uword N = get_n_rows();\n arma::uword K = get_K();\n arma::uvec centers(K);\n arma::uvec cprev(N);\n arma::uvec cnext(N);\n arma::uvec far2c(K);\n arma::vec dist(N);\n\n arma::uword nc;\n if (m_starting_index.first) {\n nc = m_starting_index.second;\n } else {\n std::random_device rd;\n nc = rd() % N;\n }\n centers(0) = nc;\n\n for (arma::uword i = 0; i < N; ++i) {\n dist(i) =\n (i == nc) ? 0.0 : ddist(get_source_row(i), get_source_row(nc));\n cnext(i) = i + 1;\n cprev(i) = i - 1;\n }\n\n cnext(N - 1) = 0;\n cprev(0) = N - 1;\n\n nc = std::max_element(dist.begin(), dist.end()) - dist.begin();\n far2c(0) = nc;\n set_radius(0, dist(nc));\n\n for (int i = 1; i < K; ++i) {\n nc = far2c(get_radius_idxmax(i));\n\n centers(i) = nc;\n set_radius(i, 0.0);\n dist(nc) = 0.0;\n set_index(nc, i);\n far2c(i) = nc;\n\n cnext(cprev(nc)) = cnext(nc);\n cprev(cnext(nc)) = cprev(nc);\n cnext(nc) = nc;\n cprev(nc) = nc;\n\n for (int j = 0; j < i; ++j) {\n arma::uword ct_j = centers(j);\n double dc2cq = ddist(get_source_row(ct_j), get_source_row(nc)) \/ 4;\n if (dc2cq < get_radius(j)) {\n set_radius(j, 0.0);\n far2c(j) = ct_j;\n arma::uword k = cnext(ct_j);\n while (k != ct_j) {\n arma::uword nextk = cnext(k);\n double dist2c_k = dist(k);\n if (dc2cq < dist2c_k) {\n double dd =\n ddist(get_source_row(k), get_source_row(nc));\n if (dd < dist2c_k) {\n dist(k) = dd;\n set_index(k, i);\n if (get_radius(i) < dd) {\n set_radius(i, dd);\n far2c(i) = k;\n }\n cnext(cprev(k)) = nextk;\n cprev(nextk) = cprev(k);\n cnext(k) = cnext(nc);\n cprev(cnext(nc)) = k;\n cnext(nc) = k;\n cprev(k) = nc;\n } else if (get_radius(j) < dist2c_k) {\n set_radius(j, dist2c_k);\n far2c(j) = k;\n }\n } else if (get_radius(j) < dist2c_k) {\n set_radius(j, dist2c_k);\n far2c(j) = k;\n }\n k = nextk;\n }\n }\n }\n }\n\n set_radii(arma::sqrt(get_radii()));\n set_rx(get_max_radius());\n\n arma::mat center_coordinates(get_centers());\n for (arma::uword i = 0; i < N; ++i) {\n increment_num_points(get_index(i));\n center_coordinates.row(get_index(i)) += get_source_row(i);\n }\n set_centers(center_coordinates \/\n arma::repmat(get_num_points(), 1, get_d()));\n}\n}\n<commit_msg>Don't allocate a new arma rowvec every monomial<commit_after>#include \"clustering.hpp\"\n\n#include \"constant_series.hpp\"\n#include \"monomials.hpp\"\n#include \"nchoosek.hpp\"\n#include \"p_max_total.hpp\"\n\n\nnamespace fgt {\n\n\nnamespace {\n\n\ndouble ddist(const arma::rowvec& x, const arma::rowvec& y) {\n return arma::accu(arma::pow(x - y, 2));\n}\n}\n\n\nClustering::Clustering(const arma::mat& source, arma::uword K, double bandwidth,\n double epsilon)\n : m_source(source),\n m_K(K),\n m_indices(arma::zeros<arma::uvec>(source.n_rows)),\n m_centers(arma::zeros<arma::mat>(K, source.n_cols)),\n m_num_points(arma::zeros<arma::uvec>(K)),\n m_radii(K),\n m_rx(),\n m_bandwidth(bandwidth),\n m_epsilon(epsilon),\n m_p_max(0),\n m_constant_series() {}\n\n\nClustering::~Clustering() {}\n\n\narma::uword Clustering::choose_truncation_number(int dimensions,\n double bandwidth,\n double epsilon, double rx) {\n double r = std::min(std::sqrt(dimensions),\n bandwidth * std::sqrt(std::log(1 \/ epsilon)));\n double rx2 = rx * rx;\n double h2 = bandwidth * bandwidth;\n double error = 1;\n double temp = 1;\n int p = 0;\n\n while ((error > epsilon) and (p <= TruncationNumberUpperLimit)) {\n ++p;\n double b = std::min((rx + std::sqrt(rx2 + 2 * p * h2)) \/ 2, rx + r);\n double c = rx - b;\n temp *= 2 * rx * b \/ h2 \/ p;\n error = temp * std::exp(-c * c \/ h2);\n }\n\n return p;\n}\n\n\nvoid Clustering::cluster() {\n cluster_impl();\n m_p_max =\n choose_truncation_number(m_source.n_cols, m_bandwidth, m_epsilon, m_rx);\n m_constant_series = compute_constant_series(m_source.n_cols, m_p_max);\n}\n\n\narma::mat Clustering::compute_C(const arma::vec& q) const {\n arma::mat C = arma::zeros<arma::mat>(\n m_centers.n_rows, get_p_max_total(m_source.n_cols, m_p_max));\n std::vector<double> monomials(C.n_cols);\n double h2 = m_bandwidth * m_bandwidth;\n\n for (arma::uword i = 0; i < m_source.n_rows; ++i) {\n arma::uword k = m_indices(i);\n arma::rowvec dx = m_source.row(i) - m_centers.row(k);\n double distance2 = arma::accu(arma::pow(dx, 2));\n compute_monomials(dx \/ m_bandwidth, m_p_max, monomials);\n double f = q(i) * std::exp(-distance2 \/ h2);\n for (arma::uword j = 0; j < monomials.size(); ++j) {\n C(k, j) += f * monomials[j];\n }\n }\n\n arma::rowvec constant_series =\n compute_constant_series(m_source.n_cols, m_p_max);\n for (arma::uword i = 0; i < C.n_rows; ++i) {\n C.row(i) = C.row(i) % constant_series;\n }\n\n return C;\n}\n\n\nconst optional_arma_uword_t GonzalezClustering::DefaultStartingIndex = {false,\n 0};\n\n\nGonzalezClustering::GonzalezClustering(const arma::mat& source, int K,\n double bandwidth, double epsilon,\n optional_arma_uword_t starting_index)\n : Clustering(source, K, bandwidth, epsilon),\n m_starting_index(starting_index) {}\n\n\nvoid GonzalezClustering::cluster_impl() {\n arma::uword N = get_n_rows();\n arma::uword K = get_K();\n arma::uvec centers(K);\n arma::uvec cprev(N);\n arma::uvec cnext(N);\n arma::uvec far2c(K);\n arma::vec dist(N);\n\n arma::uword nc;\n if (m_starting_index.first) {\n nc = m_starting_index.second;\n } else {\n std::random_device rd;\n nc = rd() % N;\n }\n centers(0) = nc;\n\n for (arma::uword i = 0; i < N; ++i) {\n dist(i) =\n (i == nc) ? 0.0 : ddist(get_source_row(i), get_source_row(nc));\n cnext(i) = i + 1;\n cprev(i) = i - 1;\n }\n\n cnext(N - 1) = 0;\n cprev(0) = N - 1;\n\n nc = std::max_element(dist.begin(), dist.end()) - dist.begin();\n far2c(0) = nc;\n set_radius(0, dist(nc));\n\n for (int i = 1; i < K; ++i) {\n nc = far2c(get_radius_idxmax(i));\n\n centers(i) = nc;\n set_radius(i, 0.0);\n dist(nc) = 0.0;\n set_index(nc, i);\n far2c(i) = nc;\n\n cnext(cprev(nc)) = cnext(nc);\n cprev(cnext(nc)) = cprev(nc);\n cnext(nc) = nc;\n cprev(nc) = nc;\n\n for (int j = 0; j < i; ++j) {\n arma::uword ct_j = centers(j);\n double dc2cq = ddist(get_source_row(ct_j), get_source_row(nc)) \/ 4;\n if (dc2cq < get_radius(j)) {\n set_radius(j, 0.0);\n far2c(j) = ct_j;\n arma::uword k = cnext(ct_j);\n while (k != ct_j) {\n arma::uword nextk = cnext(k);\n double dist2c_k = dist(k);\n if (dc2cq < dist2c_k) {\n double dd =\n ddist(get_source_row(k), get_source_row(nc));\n if (dd < dist2c_k) {\n dist(k) = dd;\n set_index(k, i);\n if (get_radius(i) < dd) {\n set_radius(i, dd);\n far2c(i) = k;\n }\n cnext(cprev(k)) = nextk;\n cprev(nextk) = cprev(k);\n cnext(k) = cnext(nc);\n cprev(cnext(nc)) = k;\n cnext(nc) = k;\n cprev(k) = nc;\n } else if (get_radius(j) < dist2c_k) {\n set_radius(j, dist2c_k);\n far2c(j) = k;\n }\n } else if (get_radius(j) < dist2c_k) {\n set_radius(j, dist2c_k);\n far2c(j) = k;\n }\n k = nextk;\n }\n }\n }\n }\n\n set_radii(arma::sqrt(get_radii()));\n set_rx(get_max_radius());\n\n arma::mat center_coordinates(get_centers());\n for (arma::uword i = 0; i < N; ++i) {\n increment_num_points(get_index(i));\n center_coordinates.row(get_index(i)) += get_source_row(i);\n }\n set_centers(center_coordinates \/\n arma::repmat(get_num_points(), 1, get_d()));\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <algorithm>\n#include <iostream>\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-fts\/QueryAnalyzer.h\"\n#include \"fnord-fts\/GermanStemmer.h\"\n#include \"common.h\"\n\nusing namespace fnord;\n\nint main(int argc, const char** argv) {\n fnord::Application::init();\n fnord::Application::logToStderr();\n\n fnord::cli::FlagParser flags;\n\n flags.defineFlag(\n \"lang\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"language\",\n \"<lang>\");\n\n flags.defineFlag(\n \"stopwords\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"stopwords\",\n \"<path>\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.parseArgv(argc, argv);\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n auto lang = languageFromString(flags.getString(\"lang\"));\n\n fts::StopwordDictionary stopwords;\n if (flags.isSet(\"stopwords\")) {\n stopwords.loadStopwordFile(flags.getString(\"stopwords\"));\n } else {\n fnord::logWarning(\"cm-tokenize\", \"no stopword file provided\");\n }\n\n fnord::fts::SynonymDictionary synonyms;\n synonyms.addSynonym(Language::DE, \"mützen\", \"mütze\");\n synonyms.addSynonym(Language::DE, \"bänder\", \"band\");\n\n fnord::fts::GermanStemmer german_stemmer(\n \"conf\/hunspell_de.aff\",\n \"conf\/hunspell_de.dic\",\n \"conf\/hunspell_de.hyphen\",\n &synonyms);\n\n fts::QueryAnalyzer analyzer(&stopwords, &german_stemmer);\n for (String line; std::getline(std::cin, line); ) {\n Set<String> tokens;\n analyzer.analyze(lang, line, &tokens);\n fnord::iputs(\"\\ninput: $0\\noutput: $1\", line, tokens);\n }\n\n return 0;\n}\n\n<commit_msg>ignore utf8 dingbats in tokenization<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <algorithm>\n#include <iostream>\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-fts\/QueryAnalyzer.h\"\n#include \"fnord-fts\/GermanStemmer.h\"\n#include \"common.h\"\n\nusing namespace fnord;\n\nint main(int argc, const char** argv) {\n fnord::Application::init();\n fnord::Application::logToStderr();\n\n fnord::cli::FlagParser flags;\n\n flags.defineFlag(\n \"lang\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"language\",\n \"<lang>\");\n\n flags.defineFlag(\n \"stopwords\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"stopwords\",\n \"<path>\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.parseArgv(argc, argv);\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n auto lang = languageFromString(flags.getString(\"lang\"));\n\n fts::StopwordDictionary stopwords;\n if (flags.isSet(\"stopwords\")) {\n stopwords.loadStopwordFile(flags.getString(\"stopwords\"));\n } else {\n fnord::logWarning(\"cm-tokenize\", \"no stopword file provided\");\n }\n\n fnord::fts::SynonymDictionary synonyms;\n synonyms.addSynonym(Language::DE, \"mützen\", \"mütze\");\n synonyms.addSynonym(Language::DE, \"bänder\", \"band\");\n synonyms.addSynonym(Language::DE, \"girlanden\", \"girlande\");\n\n fnord::fts::GermanStemmer german_stemmer(\n \"conf\/hunspell_de.aff\",\n \"conf\/hunspell_de.dic\",\n \"conf\/hunspell_de.hyphen\",\n &synonyms);\n\n fts::QueryAnalyzer analyzer(&stopwords, &german_stemmer);\n for (String line; std::getline(std::cin, line); ) {\n Set<String> tokens;\n analyzer.analyze(lang, line, &tokens);\n fnord::iputs(\"\\ninput: $0\\noutput: $1\", line, tokens);\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef DISTRIBUTION_HPP\n#define DISTRIBUTION_HPP\n\n#include <random> \n\nclass Distribution {\npublic:\n virtual unsigned int nextTimeDelta (std::default_random_engine rng) = 0;\n};\n\nclass Geometric : public Distribution{\npublic:\n Geometric(std::string params) {\n\n p_ = std::stod(params);\n if (p_ <= 0 || p_ >= 1) {\n std::cerr << \"Geometric Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::geometric_distribution<int> distribution(p_);\n return (unsigned int)std::max(distribution(rng), 1);\n }\n\nprivate:\n double p_ = 0.0;\n};\n\nclass Exponential : public Distribution{\npublic:\n Exponential(std::string params) {\n\n lambda_ = std::stod(params);\n if (!lambda_) {\n std::cerr << \"Exponential Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n std::exponential_distribution<double> distribution(lambda_);\n return (unsigned int)std::max(distribution(rng), 1.0);\n }\n\nprivate:\n double lambda_ = 0.0;\n};\n\nclass Binomial : public Distribution {\npublic:\n Binomial (std::string params) {\n\n std::string delimiter = \",\";\n size_t pos = params.find(delimiter);\n t_ = (unsigned int) std::stoul(params.substr(0,pos));\n p_ = std::stod(params.substr(pos+1));\n if (p_ <= 0 || p_ >= 1) {\n std::cerr << \"Binomial Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::binomial_distribution<int> distribution(t_, p_);\n return (unsigned int)std::max(distribution(rng), 1);\n }\n\nprivate:\n unsigned int t_ = 0.0;\n double p_ = 0.0;\n};\n\nclass Cauchy : public Distribution {\npublic:\n Cauchy (std::string params) {\n\n std::string delimiter = \",\";\n size_t pos = params.find(delimiter);\n a_ = std::stod(params.substr(0,pos));\n b_ = std::stod(params.substr(pos+1));\n if (!a_ || !b_) {\n std::cerr << \"Cauchy Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::cauchy_distribution<double> distribution(a_, b_);\n return (unsigned int)std::max(distribution(rng), 1.0);\n }\n\nprivate:\n double a_ = 0.0, b_ = 0.0;\n};\n\nclass Chi_squared : public Distribution {\npublic:\n Chi_squared (std::string params) {\n\n n_ = std::stod(params);\n if (!n_) {\n std::cerr << \"Chi squared Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::chi_squared_distribution<double> distribution(n_);\n return (unsigned int)std::max(distribution(rng), 1.0);\n }\n\nprivate:\n double n_ = 0.0;\n};\n\nclass Discrete : public Distribution {\npublic:\n Discrete (std::string params) {\n\n std::string delimiter = \",\";\n size_t pos = params.find(delimiter);\n first_ = std::stod(params.substr(0,pos));\n last_ = std::stod(params.substr(pos+1));\n if (!first_ || !last_) {\n std::cerr << \"Discrete Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::discrete_distribution<int> distribution(first_, last_);\n return (unsigned int)std::max(distribution(rng), 1);\n }\n\nprivate:\n double first_ = 0.0, last_ = 0.0;\n};\n\n#endif\n<commit_msg>added new distribution<commit_after>#ifndef DISTRIBUTION_HPP\n#define DISTRIBUTION_HPP\n\n#include <random> \n\nclass Distribution {\npublic:\n virtual unsigned int nextTimeDelta (std::default_random_engine rng) = 0;\n};\n\nclass Geometric : public Distribution{\npublic:\n Geometric(std::string params) {\n\n p_ = std::stod(params);\n if (p_ <= 0 || p_ >= 1) {\n std::cerr << \"Geometric Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::geometric_distribution<int> distribution(p_);\n return (unsigned int)std::max(distribution(rng), 1);\n }\n\nprivate:\n double p_ = 0.0;\n};\n\nclass Exponential : public Distribution{\npublic:\n Exponential(std::string params) {\n\n lambda_ = std::stod(params);\n if (!lambda_) {\n std::cerr << \"Exponential Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n std::exponential_distribution<double> distribution(lambda_);\n return (unsigned int)std::max(distribution(rng), 1.0);\n }\n\nprivate:\n double lambda_ = 0.0;\n};\n\nclass Binomial : public Distribution {\npublic:\n Binomial (std::string params) {\n\n std::string delimiter = \",\";\n size_t pos = params.find(delimiter);\n t_ = (unsigned int) std::stoul(params.substr(0,pos));\n p_ = std::stod(params.substr(pos+1));\n if (p_ <= 0 || p_ >= 1) {\n std::cerr << \"Binomial Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\/* binomial distribution returns within range of (0,t), return value + 1 to void returning 0 *\/\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::binomial_distribution<int> distribution(t_, p_);\n return (unsigned int)std::max(distribution(rng), 1) + 1;\n }\n\nprivate:\n unsigned int t_ = 0.0;\n double p_ = 0.0;\n};\n\nclass Cauchy : public Distribution {\npublic:\n Cauchy (std::string params) {\n\n std::string delimiter = \",\";\n size_t pos = params.find(delimiter);\n a_ = std::stod(params.substr(0,pos));\n b_ = std::stod(params.substr(pos+1));\n if (!a_ || !b_) {\n std::cerr << \"Cauchy Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::cauchy_distribution<double> distribution(a_, b_);\n return (unsigned int)std::max(distribution(rng), 1.0);\n }\n\nprivate:\n double a_ = 0.0, b_ = 0.0;\n};\n\nclass Chi_squared : public Distribution {\npublic:\n Chi_squared (std::string params) {\n\n n_ = std::stod(params);\n if (!n_) {\n std::cerr << \"Chi Squared Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::chi_squared_distribution<double> distribution(n_);\n return (unsigned int)std::max(distribution(rng), 1.0);\n }\n\nprivate:\n double n_ = 0.0;\n};\n\nclass Discrete : public Distribution {\npublic:\n Discrete (std::string params) {\n\n std::string delimiter = \",\";\n size_t pos = params.find(delimiter);\n first_ = std::stod(params.substr(0,pos));\n last_ = std::stod(params.substr(pos+1));\n if (!first_ || !last_) {\n std::cerr << \"Discrete Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::discrete_distribution<int> distribution(first_, last_);\n return (unsigned int)std::max(distribution(rng), 1);\n }\n\nprivate:\n double first_ = 0.0, last_ = 0.0;\n};\n\nclass Fisher_f : public Distribution {\npublic:\n Fisher_f (std::string params) {\n\n std::string delimiter = \",\";\n size_t pos = params.find(delimiter);\n m_ = std::stod(params.substr(0,pos));\n n_ = std::stod(params.substr(pos+1));\n if (!m_ || !n_) {\n std::cerr << \"Fisher F Distribution: Invalid parameter.\" << std::endl;\n abort();\n }\n }\n\n unsigned int nextTimeDelta(std::default_random_engine rng) {\n\n std::fisher_f_distribution<double> distribution (m_, n_);\n return (unsigned int)std::max(distribution(rng), 1.0);\n }\n\nprivate:\n double m_ = 0.0, n_ = 0.0;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n#define LUABIND_BUILDING\n\n#include <luabind\/lua_include.hpp>\n\n#include <luabind\/luabind.hpp>\n#include <luabind\/class_info.hpp>\n#include <luabind\/detail\/class_registry.hpp>\n#include <luabind\/lua_argument_proxy.hpp>\n#include <luabind\/lua_iterator_proxy.hpp>\n#include <___unused.h>\n\n\/*\n#include <iostream>\n#define VERBOSE(X) std::cout << __FILE__ << \":\" << __LINE__ << \": \" << X << std::endl\n*\/\n#define VERBOSE(X)\n\nnamespace luabind\n{\n\tLUABIND_API class_info get_class_info(argument const& o)\n\t{\n\t\tlua_State* L = o.interpreter();\n detail::class_rep * crep = NULL;\n\n _unused(givenClassRep);\n\n\t\to.push(L);\n\t\tif (detail::is_class_rep(L, -1)) {\n\t\t\tVERBOSE(\"OK, got a class rep\");\n \/\/ OK, o is a class rep, now at the top of the stack\n\t\t\tcrep = static_cast<detail::class_rep *>(lua_touserdata(L, -1));\n\t\t\tlua_pop(L, 1);\n\t\t} else {\n\n\t\t\tVERBOSE(\"Not a class rep\");\n\t\t\tdetail::object_rep* obj = detail::get_instance(L, -1);\n\n\t\t\tif (!obj)\n\t\t\t{\n\t\t\t\tVERBOSE(\"Not a obj rep\");\n\t\t\t class_info result;\n\t\t\t result.name = lua_typename(L, lua_type(L, -1));\n\t\t\t lua_pop(L, 1);\n\t\t\t result.methods = newtable(L);\n\t\t\t result.attributes = newtable(L);\n\t\t\t return result;\n\t\t\t} else {\n\t\t lua_pop(L, 1);\n\t\t\t\t\/\/ OK, we were given an object - gotta get the crep.\n\t\t\t\tcrep = obj->crep();\n\t\t\t}\n\t\t}\n\t\tcrep->get_table(L);\n object table(from_stack(L, -1));\n lua_pop(L, 1);\n\n class_info result;\n result.name = crep->name();\n result.methods = newtable(L);\n result.attributes = newtable(L);\n\n std::size_t index = 1;\n\n for (iterator i(table), e; i != e; ++i)\n {\n if (type(*i) != LUA_TFUNCTION)\n continue;\n\n \/\/ We have to create a temporary `object` here, otherwise the proxy\n \/\/ returned by operator->() will mess up the stack. This is a known\n \/\/ problem that probably doesn't show up in real code very often.\n object member(*i);\n member.push(L);\n detail::stack_pop pop(L, 1);\n\n if (lua_tocfunction(L, -1) == &detail::property_tag)\n {\n result.attributes[index++] = i.key();\n }\n else\n {\n result.methods[i.key()] = *i;\n }\n }\n\n return result;\n\t}\n\n LUABIND_API object get_class_names(lua_State* L)\n {\n detail::class_registry* reg = detail::class_registry::get_registry(L);\n\n std::map<type_id, detail::class_rep*> const& classes = reg->get_classes();\n\n object result = newtable(L);\n std::size_t index = 1;\n\n for (std::map<type_id, detail::class_rep*>::const_iterator iter = classes.begin();\n iter != classes.end(); ++iter)\n {\n result[index++] = iter->second->name();\n }\n\n return result;\n }\n\n\tLUABIND_API void bind_class_info(lua_State* L)\n\t{\n\t\tmodule(L)\n\t\t[\n\t\t\tclass_<class_info>(\"class_info_data\")\n\t\t\t\t.def_readonly(\"name\", &class_info::name)\n\t\t\t\t.def_readonly(\"methods\", &class_info::methods)\n\t\t\t\t.def_readonly(\"attributes\", &class_info::attributes),\n\n def(\"class_info\", &get_class_info),\n def(\"class_names\", &get_class_names)\n\t\t];\n\t}\n}\n\n<commit_msg>Tiny change<commit_after>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n#define LUABIND_BUILDING\n\n#include <luabind\/lua_include.hpp>\n\n#include <luabind\/luabind.hpp>\n#include <luabind\/class_info.hpp>\n#include <luabind\/detail\/class_registry.hpp>\n#include <luabind\/lua_argument_proxy.hpp>\n#include <luabind\/lua_iterator_proxy.hpp>\n\n\/*\n#include <iostream>\n#define VERBOSE(X) std::cout << __FILE__ << \":\" << __LINE__ << \": \" << X << std::endl\n*\/\n#define VERBOSE(X)\n\nnamespace luabind\n{\n\tLUABIND_API class_info get_class_info(argument const& o)\n\t{\n\t\tlua_State* L = o.interpreter();\n detail::class_rep * crep = NULL;\n\n\t\to.push(L);\n\t\tif (detail::is_class_rep(L, -1)) {\n\t\t\tVERBOSE(\"OK, got a class rep\");\n \/\/ OK, o is a class rep, now at the top of the stack\n\t\t\tcrep = static_cast<detail::class_rep *>(lua_touserdata(L, -1));\n\t\t\tlua_pop(L, 1);\n\t\t} else {\n\n\t\t\tVERBOSE(\"Not a class rep\");\n\t\t\tdetail::object_rep* obj = detail::get_instance(L, -1);\n\n\t\t\tif (!obj)\n\t\t\t{\n\t\t\t\tVERBOSE(\"Not a obj rep\");\n\t\t\t class_info result;\n\t\t\t result.name = lua_typename(L, lua_type(L, -1));\n\t\t\t lua_pop(L, 1);\n\t\t\t result.methods = newtable(L);\n\t\t\t result.attributes = newtable(L);\n\t\t\t return result;\n\t\t\t} else {\n\t\t lua_pop(L, 1);\n\t\t\t\t\/\/ OK, we were given an object - gotta get the crep.\n\t\t\t\tcrep = obj->crep();\n\t\t\t}\n\t\t}\n\t\tcrep->get_table(L);\n object table(from_stack(L, -1));\n lua_pop(L, 1);\n\n class_info result;\n result.name = crep->name();\n result.methods = newtable(L);\n result.attributes = newtable(L);\n\n std::size_t index = 1;\n\n for (iterator i(table), e; i != e; ++i)\n {\n if (type(*i) != LUA_TFUNCTION)\n continue;\n\n \/\/ We have to create a temporary `object` here, otherwise the proxy\n \/\/ returned by operator->() will mess up the stack. This is a known\n \/\/ problem that probably doesn't show up in real code very often.\n object member(*i);\n member.push(L);\n detail::stack_pop pop(L, 1);\n\n if (lua_tocfunction(L, -1) == &detail::property_tag)\n {\n result.attributes[index++] = i.key();\n }\n else\n {\n result.methods[i.key()] = *i;\n }\n }\n\n return result;\n\t}\n\n LUABIND_API object get_class_names(lua_State* L)\n {\n detail::class_registry* reg = detail::class_registry::get_registry(L);\n\n std::map<type_id, detail::class_rep*> const& classes = reg->get_classes();\n\n object result = newtable(L);\n std::size_t index = 1;\n\n for (std::map<type_id, detail::class_rep*>::const_iterator iter = classes.begin();\n iter != classes.end(); ++iter)\n {\n result[index++] = iter->second->name();\n }\n\n return result;\n }\n\n\tLUABIND_API void bind_class_info(lua_State* L)\n\t{\n\t\tmodule(L)\n\t\t[\n\t\t\tclass_<class_info>(\"class_info_data\")\n\t\t\t\t.def_readonly(\"name\", &class_info::name)\n\t\t\t\t.def_readonly(\"methods\", &class_info::methods)\n\t\t\t\t.def_readonly(\"attributes\", &class_info::attributes),\n\n def(\"class_info\", &get_class_info),\n def(\"class_names\", &get_class_names)\n\t\t];\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n#define LUABIND_BUILDING\n\n#include <luabind\/lua_include.hpp>\n\n#include <luabind\/luabind.hpp>\n#include <luabind\/class_info.hpp>\n#include <luabind\/detail\/class_registry.hpp>\n\n\/*\n#include <iostream>\n#define VERBOSE(X) std::cout << __FILE__ << \":\" << __LINE__ << \": \" << X << std::endl\n*\/\n#define VERBOSE(X)\n\nnamespace luabind\n{\n\tLUABIND_API class_info get_class_info(argument const& o)\n\t{\n\t\tlua_State* L = o.interpreter();\n\t\tdetail::class_rep * crep = NULL;\n\t\tbool givenClassRep = false;\n\n\t\to.push(L);\n\t\tif (detail::is_class_rep(L, -1)) {\n\t\t\tVERBOSE(\"OK, got a class rep\");\n\t\t\t\/\/ OK, o is a class rep, now at the top of the stack\n\t\t\tgivenClassRep = true;\n\t\t\tcrep = static_cast<detail::class_rep *>(lua_touserdata(L, -1));\n\t\t\tlua_pop(L, 1);\n\t\t} else {\n\n\t\t\tVERBOSE(\"Not a class rep\");\n\t\t\tdetail::object_rep* obj = detail::get_instance(L, -1);\n\n\t\t\tif (!obj)\n\t\t\t{\n\t\t\t\tVERBOSE(\"Not a obj rep\");\n\t\t\t class_info result;\n\t\t\t result.name = lua_typename(L, lua_type(L, -1));\n\t\t\t lua_pop(L, 1);\n\t\t\t result.methods = newtable(L);\n\t\t\t result.attributes = newtable(L);\n\t\t\t return result;\n\t\t\t} else {\n\t\t lua_pop(L, 1);\n\t\t\t\t\/\/ OK, we were given an object - gotta get the crep.\n\t\t\t\tcrep = obj->crep();\n\t\t\t}\n\t\t}\n\t\tcrep->get_table(L);\n object table(from_stack(L, -1));\n lua_pop(L, 1);\n\n class_info result;\n result.name = crep->name();\n result.methods = newtable(L);\n result.attributes = newtable(L);\n\n std::size_t index = 1;\n\n for (iterator i(table), e; i != e; ++i)\n {\n if (type(*i) != LUA_TFUNCTION)\n continue;\n\n \/\/ We have to create a temporary `object` here, otherwise the proxy\n \/\/ returned by operator->() will mess up the stack. This is a known\n \/\/ problem that probably doesn't show up in real code very often.\n object member(*i);\n member.push(L);\n detail::stack_pop pop(L, 1);\n\n if (lua_tocfunction(L, -1) == &detail::property_tag)\n {\n result.attributes[index++] = i.key();\n }\n else\n {\n result.methods[i.key()] = *i;\n }\n }\n\n return result;\n\t}\n\n LUABIND_API object get_class_names(lua_State* L)\n {\n detail::class_registry* reg = detail::class_registry::get_registry(L);\n\n std::map<type_id, detail::class_rep*> const& classes = reg->get_classes();\n\n object result = newtable(L);\n std::size_t index = 1;\n\n for (std::map<type_id, detail::class_rep*>::const_iterator iter = classes.begin();\n iter != classes.end(); ++iter)\n {\n result[index++] = iter->second->name();\n }\n\n return result;\n }\n\n\tLUABIND_API void bind_class_info(lua_State* L)\n\t{\n\t\tmodule(L)\n\t\t[\n\t\t\tclass_<class_info>(\"class_info_data\")\n\t\t\t\t.def_readonly(\"name\", &class_info::name)\n\t\t\t\t.def_readonly(\"methods\", &class_info::methods)\n\t\t\t\t.def_readonly(\"attributes\", &class_info::attributes),\n\n def(\"class_info\", &get_class_info),\n def(\"class_names\", &get_class_names)\n\t\t];\n\t}\n}\n\n<commit_msg>Make bind_class_info idempotent (can call repeatedly without breaking)<commit_after>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is 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\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n#define LUABIND_BUILDING\n\n#include <luabind\/lua_include.hpp>\n\n#include <luabind\/luabind.hpp>\n#include <luabind\/class_info.hpp>\n#include <luabind\/detail\/class_registry.hpp>\n\n\/*\n#include <iostream>\n#define VERBOSE(X) std::cout << __FILE__ << \":\" << __LINE__ << \": \" << X << std::endl\n*\/\n#define VERBOSE(X)\n\nnamespace luabind\n{\n\tLUABIND_API class_info get_class_info(argument const& o)\n\t{\n\t\tlua_State* L = o.interpreter();\n\t\tdetail::class_rep * crep = NULL;\n\t\tbool givenClassRep = false;\n\n\t\to.push(L);\n\t\tif (detail::is_class_rep(L, -1)) {\n\t\t\tVERBOSE(\"OK, got a class rep\");\n\t\t\t\/\/ OK, o is a class rep, now at the top of the stack\n\t\t\tgivenClassRep = true;\n\t\t\tcrep = static_cast<detail::class_rep *>(lua_touserdata(L, -1));\n\t\t\tlua_pop(L, 1);\n\t\t} else {\n\n\t\t\tVERBOSE(\"Not a class rep\");\n\t\t\tdetail::object_rep* obj = detail::get_instance(L, -1);\n\n\t\t\tif (!obj)\n\t\t\t{\n\t\t\t\tVERBOSE(\"Not a obj rep\");\n\t\t\t class_info result;\n\t\t\t result.name = lua_typename(L, lua_type(L, -1));\n\t\t\t lua_pop(L, 1);\n\t\t\t result.methods = newtable(L);\n\t\t\t result.attributes = newtable(L);\n\t\t\t return result;\n\t\t\t} else {\n\t\t lua_pop(L, 1);\n\t\t\t\t\/\/ OK, we were given an object - gotta get the crep.\n\t\t\t\tcrep = obj->crep();\n\t\t\t}\n\t\t}\n\t\tcrep->get_table(L);\n object table(from_stack(L, -1));\n lua_pop(L, 1);\n\n class_info result;\n result.name = crep->name();\n result.methods = newtable(L);\n result.attributes = newtable(L);\n\n std::size_t index = 1;\n\n for (iterator i(table), e; i != e; ++i)\n {\n if (type(*i) != LUA_TFUNCTION)\n continue;\n\n \/\/ We have to create a temporary `object` here, otherwise the proxy\n \/\/ returned by operator->() will mess up the stack. This is a known\n \/\/ problem that probably doesn't show up in real code very often.\n object member(*i);\n member.push(L);\n detail::stack_pop pop(L, 1);\n\n if (lua_tocfunction(L, -1) == &detail::property_tag)\n {\n result.attributes[index++] = i.key();\n }\n else\n {\n result.methods[i.key()] = *i;\n }\n }\n\n return result;\n\t}\n\n LUABIND_API object get_class_names(lua_State* L)\n {\n detail::class_registry* reg = detail::class_registry::get_registry(L);\n\n std::map<type_id, detail::class_rep*> const& classes = reg->get_classes();\n\n object result = newtable(L);\n std::size_t index = 1;\n\n for (std::map<type_id, detail::class_rep*>::const_iterator iter = classes.begin();\n iter != classes.end(); ++iter)\n {\n result[index++] = iter->second->name();\n }\n\n return result;\n }\n\n\tLUABIND_API void bind_class_info(lua_State* L)\n\t{\n\t\tdetail::class_registry* reg = detail::class_registry::get_registry(L);\n\t\tif (reg->find_class(typeid(class_info))) {\n\t\t\t\/\/ We've already been registered!\n\t\t\treturn;\n\t\t}\n\n\t\tmodule(L)\n\t\t[\n\t\t\tclass_<class_info>(\"class_info_data\")\n\t\t\t\t.def_readonly(\"name\", &class_info::name)\n\t\t\t\t.def_readonly(\"methods\", &class_info::methods)\n\t\t\t\t.def_readonly(\"attributes\", &class_info::attributes),\n\n def(\"class_info\", &get_class_info),\n def(\"class_names\", &get_class_names)\n\t\t];\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/socket.h>\n\n#include \"utils.h\"\n#include \"cJSON.h\"\n\n#include \"client_http.h\"\n\n\/\/\n\/\/ Xapian http client\n\/\/\n\nHttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)\n\t: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)\n{\n\tparser.data = this;\n\thttp_parser_init(&parser, HTTP_REQUEST);\n\tLOG_CONN(this, \"Got connection (sock=%d), %d http client(s) connected.\\n\", sock, ++total_clients);\n}\n\n\nHttpClient::~HttpClient()\n{\n\ttotal_clients--;\n}\n\n\nvoid HttpClient::on_read(const char *buf, ssize_t received)\n{\t\n\tsize_t parsed = http_parser_execute(&parser, &settings, buf, received);\n\tif (parsed == received) {\n\t\tif (parser.state == 1 || parser.state == 18) { \/\/ dead or message_complete\n\t\t\ttry {\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"METHOD: %d\\n\", parser.method);\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"PATH: '%s'\\n\", repr(path).c_str());\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"BODY: '%s'\\n\", repr(body).c_str());\n\n\t\t\t\tstd::string content;\n\t\t\t\tcJSON *json = cJSON_Parse(body.c_str());\n\t\t\t\tcJSON *query = json ? cJSON_GetObjectItem(json, \"query\") : NULL;\n\t\t\t\tcJSON *term = query ? cJSON_GetObjectItem(query, \"term\") : NULL;\n\t\t\t\tcJSON *text = term ? cJSON_GetObjectItem(term, \"text\") : NULL;\n\n\t\t\t\tcJSON *root = cJSON_CreateObject();\n\t\t\t\tcJSON *response = cJSON_CreateObject();\n\t\t\t\tcJSON_AddItemToObject(root, \"response\", response);\n\t\t\t\tif (text) {\n\t\t\t\t\tcJSON_AddStringToObject(response, \"status\", \"OK\");\n\t\t\t\t\tcJSON_AddStringToObject(response, \"query\", text->valuestring);\n\t\t\t\t\tcJSON_AddStringToObject(response, \"title\", \"The title\");\n\t\t\t\t\tcJSON_AddNumberToObject(response, \"items\", 7);\n\t\t\t\t\tconst char *strings[7] = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"};\n\t\t\t\t\tcJSON *results = cJSON_CreateArray();\n\t\t\t\t\tcJSON_AddItemToObject(response, \"results\", results);\n\t\t\t\t\tfor (int i = 0; i < 7; i++) {\n\t\t\t\t\t\tcJSON *result = cJSON_CreateObject();\n\t\t\t\t\t\tcJSON_AddNumberToObject(result, \"id\", i);\n\t\t\t\t\t\tcJSON_AddStringToObject(result, \"name\", strings[i]);\n\t\t\t\t\t\tcJSON_AddItemToArray(results, result);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tLOG_HTTP_PROTO(\"Error before: [%s]\\n\", cJSON_GetErrorPtr());\n\t\t\t\t\tcJSON_AddStringToObject(response, \"status\", \"ERROR\");\n\t\t\t\t\tcJSON_AddStringToObject(response, \"message\", cJSON_GetErrorPtr());\n\t\t\t\t}\n\t\t\t\tcJSON_Delete(json);\n\n\t\t\t\tchar *out = cJSON_Print(root);\n\t\t\t\tcontent = out;\n\t\t\t\tcJSON_Delete(root);\n\t\t\t\tfree(out);\n\t\t\t\t\n\t\t\t\tchar tmp[20];\n\t\t\t\tstd::string http_response;\n\t\t\t\thttp_response += \"HTTP\/\";\n\t\t\t\tsprintf(tmp, \"%d.%d\", parser.http_major, parser.http_minor);\n\t\t\t\thttp_response += tmp;\n\t\t\t\thttp_response += \" 200 OK\\r\\n\";\n\t\t\t\thttp_response += \"Content-Type: application\/json\\r\\n\";\n\t\t\t\thttp_response += \"Content-Length: \";\n\t\t\t\tsprintf(tmp, \"%ld\", content.size());\n\t\t\t\thttp_response += tmp;\n\t\t\t\thttp_response += \"\\r\\n\";\n\t\t\t\twrite(http_response + \"\\r\\n\" + content);\n\t\t\t\tif (parser.state == 1) close();\n\t\t\t} catch (...) {\n\t\t\t\tLOG_ERR(this, \"ERROR!\\n\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tenum http_errno err = HTTP_PARSER_ERRNO(&parser);\n\t\tconst char *desc = http_errno_description(err);\n\t\tconst char *msg = err != HPE_OK ? desc : \"incomplete request\";\n\t\tLOG_HTTP_PROTO(this, msg);\n\t\t\/\/ Handle error. Just close the connection.\n\t\tdestroy();\n\t}\n}\n\n\n\/\/\n\/\/ HTTP parser callbacks.\n\/\/\n\nconst http_parser_settings HttpClient::settings = {\n\t.on_message_begin = HttpClient::on_info,\n\t.on_url = HttpClient::on_data,\n\t.on_status = HttpClient::on_data,\n\t.on_header_field = HttpClient::on_data,\n\t.on_header_value = HttpClient::on_data,\n\t.on_headers_complete = HttpClient::on_info,\n\t.on_body = HttpClient::on_data,\n\t.on_message_complete = HttpClient::on_info\n};\n\n\nint HttpClient::on_info(http_parser* p) {\n\tHttpClient *self = static_cast<HttpClient *>(p->data);\n\n\tLOG_HTTP_PROTO_PARSER(self, \"%3d. (INFO)\\n\", p->state);\n\n\tswitch (p->state) {\n\t\tcase 18: \/\/ message_complete\n\t\t\tbreak;\n\t\tcase 19: \/\/ message_begin\n\t\t\tself->path.clear();\n\t\t\tself->body.clear();\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\n\nint HttpClient::on_data(http_parser* p, const char *at, size_t length) {\n\tHttpClient *self = static_cast<HttpClient *>(p->data);\n\n\tLOG_HTTP_PROTO_PARSER(self, \"%3d. %s\\n\", p->state, repr(at, length).c_str());\n\n\tswitch (p->state) {\n\t\tcase 32: \/\/ path\n\t\t\tself->path = std::string(at, length);\n\t\t\tbreak;\n\t\tcase 62: \/\/ data\n\t\t\tself->body = std::string(at, length);\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Unformatted json returned<commit_after>#include <sys\/socket.h>\n\n#include \"utils.h\"\n#include \"cJSON.h\"\n\n#include \"client_http.h\"\n\n\/\/\n\/\/ Xapian http client\n\/\/\n\nHttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)\n\t: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)\n{\n\tparser.data = this;\n\thttp_parser_init(&parser, HTTP_REQUEST);\n\tLOG_CONN(this, \"Got connection (sock=%d), %d http client(s) connected.\\n\", sock, ++total_clients);\n}\n\n\nHttpClient::~HttpClient()\n{\n\ttotal_clients--;\n}\n\n\nvoid HttpClient::on_read(const char *buf, ssize_t received)\n{\t\n\tsize_t parsed = http_parser_execute(&parser, &settings, buf, received);\n\tif (parsed == received) {\n\t\tif (parser.state == 1 || parser.state == 18) { \/\/ dead or message_complete\n\t\t\ttry {\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"METHOD: %d\\n\", parser.method);\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"PATH: '%s'\\n\", repr(path).c_str());\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"BODY: '%s'\\n\", repr(body).c_str());\n\n\t\t\t\tstd::string content;\n\t\t\t\tcJSON *json = cJSON_Parse(body.c_str());\n\t\t\t\tcJSON *query = json ? cJSON_GetObjectItem(json, \"query\") : NULL;\n\t\t\t\tcJSON *term = query ? cJSON_GetObjectItem(query, \"term\") : NULL;\n\t\t\t\tcJSON *text = term ? cJSON_GetObjectItem(term, \"text\") : NULL;\n\n\t\t\t\tcJSON *root = cJSON_CreateObject();\n\t\t\t\tcJSON *response = cJSON_CreateObject();\n\t\t\t\tcJSON_AddItemToObject(root, \"response\", response);\n\t\t\t\tif (text) {\n\t\t\t\t\tcJSON_AddStringToObject(response, \"status\", \"OK\");\n\t\t\t\t\tcJSON_AddStringToObject(response, \"query\", text->valuestring);\n\t\t\t\t\tcJSON_AddStringToObject(response, \"title\", \"The title\");\n\t\t\t\t\tcJSON_AddNumberToObject(response, \"items\", 7);\n\t\t\t\t\tconst char *strings[7] = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"};\n\t\t\t\t\tcJSON *results = cJSON_CreateArray();\n\t\t\t\t\tcJSON_AddItemToObject(response, \"results\", results);\n\t\t\t\t\tfor (int i = 0; i < 7; i++) {\n\t\t\t\t\t\tcJSON *result = cJSON_CreateObject();\n\t\t\t\t\t\tcJSON_AddNumberToObject(result, \"id\", i);\n\t\t\t\t\t\tcJSON_AddStringToObject(result, \"name\", strings[i]);\n\t\t\t\t\t\tcJSON_AddItemToArray(results, result);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tLOG_HTTP_PROTO(\"Error before: [%s]\\n\", cJSON_GetErrorPtr());\n\t\t\t\t\tcJSON_AddStringToObject(response, \"status\", \"ERROR\");\n\t\t\t\t\tcJSON_AddStringToObject(response, \"message\", cJSON_GetErrorPtr());\n\t\t\t\t}\n\t\t\t\tcJSON_Delete(json);\n\n\t\t\t\tbool pretty = false;\n\t\t\t\tchar *out;\n\t\t\t\tif (pretty) {\n\t\t\t\t\tout = cJSON_Print(root);\n\t\t\t\t} else {\n\t\t\t\t\tout = cJSON_PrintUnformatted(root);\n\t\t\t\t}\n\t\t\t\tcontent = out;\n\t\t\t\tcJSON_Delete(root);\n\t\t\t\tfree(out);\n\t\t\t\t\n\t\t\t\tchar tmp[20];\n\t\t\t\tstd::string http_response;\n\t\t\t\thttp_response += \"HTTP\/\";\n\t\t\t\tsprintf(tmp, \"%d.%d\", parser.http_major, parser.http_minor);\n\t\t\t\thttp_response += tmp;\n\t\t\t\thttp_response += \" 200 OK\\r\\n\";\n\t\t\t\thttp_response += \"Content-Type: application\/json\\r\\n\";\n\t\t\t\thttp_response += \"Content-Length: \";\n\t\t\t\tsprintf(tmp, \"%ld\", content.size());\n\t\t\t\thttp_response += tmp;\n\t\t\t\thttp_response += \"\\r\\n\";\n\t\t\t\twrite(http_response + \"\\r\\n\" + content);\n\t\t\t\tif (parser.state == 1) close();\n\t\t\t} catch (...) {\n\t\t\t\tLOG_ERR(this, \"ERROR!\\n\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tenum http_errno err = HTTP_PARSER_ERRNO(&parser);\n\t\tconst char *desc = http_errno_description(err);\n\t\tconst char *msg = err != HPE_OK ? desc : \"incomplete request\";\n\t\tLOG_HTTP_PROTO(this, msg);\n\t\t\/\/ Handle error. Just close the connection.\n\t\tdestroy();\n\t}\n}\n\n\n\/\/\n\/\/ HTTP parser callbacks.\n\/\/\n\nconst http_parser_settings HttpClient::settings = {\n\t.on_message_begin = HttpClient::on_info,\n\t.on_url = HttpClient::on_data,\n\t.on_status = HttpClient::on_data,\n\t.on_header_field = HttpClient::on_data,\n\t.on_header_value = HttpClient::on_data,\n\t.on_headers_complete = HttpClient::on_info,\n\t.on_body = HttpClient::on_data,\n\t.on_message_complete = HttpClient::on_info\n};\n\n\nint HttpClient::on_info(http_parser* p) {\n\tHttpClient *self = static_cast<HttpClient *>(p->data);\n\n\tLOG_HTTP_PROTO_PARSER(self, \"%3d. (INFO)\\n\", p->state);\n\n\tswitch (p->state) {\n\t\tcase 18: \/\/ message_complete\n\t\t\tbreak;\n\t\tcase 19: \/\/ message_begin\n\t\t\tself->path.clear();\n\t\t\tself->body.clear();\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\n\nint HttpClient::on_data(http_parser* p, const char *at, size_t length) {\n\tHttpClient *self = static_cast<HttpClient *>(p->data);\n\n\tLOG_HTTP_PROTO_PARSER(self, \"%3d. %s\\n\", p->state, repr(at, length).c_str());\n\n\tswitch (p->state) {\n\t\tcase 32: \/\/ path\n\t\t\tself->path = std::string(at, length);\n\t\t\tbreak;\n\t\tcase 62: \/\/ data\n\t\t\tself->body = std::string(at, length);\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * 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\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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\nextern \"C\" {\n#include \"main\/macros.h\"\n#include \"brw_context.h\"\n#include \"brw_vs.h\"\n}\n#include \"brw_fs.h\"\n#include \"glsl\/ir_optimization.h\"\n#include \"glsl\/ir_print_visitor.h\"\n\nstruct gl_shader *\nbrw_new_shader(struct gl_context *ctx, GLuint name, GLuint type)\n{\n struct brw_shader *shader;\n\n shader = rzalloc(NULL, struct brw_shader);\n if (shader) {\n shader->base.Type = type;\n shader->base.Name = name;\n _mesa_init_shader(ctx, &shader->base);\n }\n\n return &shader->base;\n}\n\nstruct gl_shader_program *\nbrw_new_shader_program(struct gl_context *ctx, GLuint name)\n{\n struct gl_shader_program *prog = rzalloc(NULL, struct gl_shader_program);\n if (prog) {\n prog->Name = name;\n _mesa_init_shader_program(ctx, prog);\n }\n return prog;\n}\n\n\/**\n * Performs a compile of the shader stages even when we don't know\n * what non-orthogonal state will be set, in the hope that it reflects\n * the eventual NOS used, and thus allows us to produce link failures.\n *\/\nstatic bool\nbrw_shader_precompile(struct gl_context *ctx, struct gl_shader_program *prog)\n{\n struct brw_context *brw = brw_context(ctx);\n\n if (brw->precompile && !brw_fs_precompile(ctx, prog))\n return false;\n\n if (brw->precompile && !brw_vs_precompile(ctx, prog))\n return false;\n\n return true;\n}\n\nstatic void\nbrw_lower_packing_builtins(struct brw_context *brw,\n gl_shader_type shader_type,\n exec_list *ir)\n{\n int ops = LOWER_PACK_SNORM_2x16\n | LOWER_UNPACK_SNORM_2x16\n | LOWER_PACK_UNORM_2x16\n | LOWER_UNPACK_UNORM_2x16;\n\n if (brw->intel.gen >= 7) {\n \/* Gen7 introduced the f32to16 and f16to32 instructions, which can be\n * used to execute packHalf2x16 and unpackHalf2x16. For AOS code, no\n * lowering is needed. For SOA code, the Half2x16 ops must be\n * scalarized.\n *\/\n if (shader_type == MESA_SHADER_FRAGMENT) {\n ops |= LOWER_PACK_HALF_2x16_TO_SPLIT\n | LOWER_UNPACK_HALF_2x16_TO_SPLIT;\n }\n } else {\n ops |= LOWER_PACK_HALF_2x16\n | LOWER_UNPACK_HALF_2x16;\n }\n\n lower_packing_builtins(ir, ops);\n}\n\nGLboolean\nbrw_link_shader(struct gl_context *ctx, struct gl_shader_program *shProg)\n{\n struct brw_context *brw = brw_context(ctx);\n struct intel_context *intel = &brw->intel;\n unsigned int stage;\n\n for (stage = 0; stage < ARRAY_SIZE(shProg->_LinkedShaders); stage++) {\n struct brw_shader *shader =\n\t (struct brw_shader *)shProg->_LinkedShaders[stage];\n static const GLenum targets[] = {\n\t GL_VERTEX_PROGRAM_ARB,\n\t GL_FRAGMENT_PROGRAM_ARB,\n\t GL_GEOMETRY_PROGRAM_NV\n };\n\n if (!shader)\n\t continue;\n\n struct gl_program *prog =\n\t ctx->Driver.NewProgram(ctx, targets[stage], shader->base.Name);\n if (!prog)\n\treturn false;\n prog->Parameters = _mesa_new_parameter_list();\n\n if (stage == 0) {\n\t struct gl_vertex_program *vp = (struct gl_vertex_program *) prog;\n\t vp->UsesClipDistance = shProg->Vert.UsesClipDistance;\n }\n\n void *mem_ctx = ralloc_context(NULL);\n bool progress;\n\n if (shader->ir)\n\t ralloc_free(shader->ir);\n shader->ir = new(shader) exec_list;\n clone_ir_list(mem_ctx, shader->ir, shader->base.ir);\n\n \/* lower_packing_builtins() inserts arithmetic instructions, so it\n * must precede lower_instructions().\n *\/\n brw_lower_packing_builtins(brw, (gl_shader_type) stage, shader->ir);\n do_mat_op_to_vec(shader->ir);\n lower_instructions(shader->ir,\n\t\t\t MOD_TO_FRACT |\n\t\t\t DIV_TO_MUL_RCP |\n\t\t\t SUB_TO_ADD_NEG |\n\t\t\t EXP_TO_EXP2 |\n\t\t\t LOG_TO_LOG2);\n\n \/* Pre-gen6 HW can only nest if-statements 16 deep. Beyond this,\n * if-statements need to be flattened.\n *\/\n if (intel->gen < 6)\n\t lower_if_to_cond_assign(shader->ir, 16);\n\n do_lower_texture_projection(shader->ir);\n if (intel->gen < 8 && !intel->is_haswell)\n brw_lower_texture_gradients(shader->ir);\n do_vec_index_to_cond_assign(shader->ir);\n brw_do_cubemap_normalize(shader->ir);\n lower_noise(shader->ir);\n lower_quadop_vector(shader->ir, false);\n\n bool input = true;\n bool output = stage == MESA_SHADER_FRAGMENT;\n bool temp = stage == MESA_SHADER_FRAGMENT;\n bool uniform = false;\n\n bool lowered_variable_indexing =\n lower_variable_index_to_cond_assign(shader->ir,\n input, output, temp, uniform);\n\n if (unlikely((INTEL_DEBUG & DEBUG_PERF) && lowered_variable_indexing)) {\n perf_debug(\"Unsupported form of variable indexing in FS; falling \"\n \"back to very inefficient code generation\\n\");\n }\n\n \/* FINISHME: Do this before the variable index lowering. *\/\n lower_ubo_reference(&shader->base, shader->ir);\n\n do {\n\t progress = false;\n\n\t if (stage == MESA_SHADER_FRAGMENT) {\n\t brw_do_channel_expressions(shader->ir);\n\t brw_do_vector_splitting(shader->ir);\n\t }\n\n\t progress = do_lower_jumps(shader->ir, true, true,\n\t\t\t\t true, \/* main return *\/\n\t\t\t\t false, \/* continue *\/\n\t\t\t\t false \/* loops *\/\n\t\t\t\t ) || progress;\n\n\t progress = do_common_optimization(shader->ir, true, true, 32)\n\t || progress;\n } while (progress);\n\n \/* Make a pass over the IR to add state references for any built-in\n * uniforms that are used. This has to be done now (during linking).\n * Code generation doesn't happen until the first time this shader is\n * used for rendering. Waiting until then to generate the parameters is\n * too late. At that point, the values for the built-in uniforms won't\n * get sent to the shader.\n *\/\n foreach_list(node, shader->ir) {\n\t ir_variable *var = ((ir_instruction *) node)->as_variable();\n\n\t if ((var == NULL) || (var->mode != ir_var_uniform)\n\t || (strncmp(var->name, \"gl_\", 3) != 0))\n\t continue;\n\n\t const ir_state_slot *const slots = var->state_slots;\n\t assert(var->state_slots != NULL);\n\n\t for (unsigned int i = 0; i < var->num_state_slots; i++) {\n\t _mesa_add_state_reference(prog->Parameters,\n\t\t\t\t (gl_state_index *) slots[i].tokens);\n\t }\n }\n\n validate_ir_tree(shader->ir);\n\n reparent_ir(shader->ir, shader->ir);\n ralloc_free(mem_ctx);\n\n do_set_program_inouts(shader->ir, prog,\n\t\t\t shader->base.Type == GL_FRAGMENT_SHADER);\n\n prog->SamplersUsed = shader->base.active_samplers;\n _mesa_update_shader_textures_used(shProg, prog);\n\n _mesa_reference_program(ctx, &shader->base.Program, prog);\n\n brw_add_texrect_params(prog);\n\n \/* This has to be done last. Any operation that can cause\n * prog->ParameterValues to get reallocated (e.g., anything that adds a\n * program constant) has to happen before creating this linkage.\n *\/\n _mesa_associate_uniform_storage(ctx, shProg, prog->Parameters);\n\n _mesa_reference_program(ctx, &prog, NULL);\n\n if (ctx->Shader.Flags & GLSL_DUMP) {\n static const char *target_strings[]\n = { \"vertex\", \"fragment\", \"geometry\" };\n printf(\"\\n\");\n printf(\"GLSL IR for linked %s program %d:\\n\", target_strings[stage],\n shProg->Name);\n _mesa_print_ir(shader->base.ir, NULL);\n }\n }\n\n if (!brw_shader_precompile(ctx, shProg))\n return false;\n\n return true;\n}\n\n\nint\nbrw_type_for_base_type(const struct glsl_type *type)\n{\n switch (type->base_type) {\n case GLSL_TYPE_FLOAT:\n return BRW_REGISTER_TYPE_F;\n case GLSL_TYPE_INT:\n case GLSL_TYPE_BOOL:\n return BRW_REGISTER_TYPE_D;\n case GLSL_TYPE_UINT:\n return BRW_REGISTER_TYPE_UD;\n case GLSL_TYPE_ARRAY:\n return brw_type_for_base_type(type->fields.array);\n case GLSL_TYPE_STRUCT:\n case GLSL_TYPE_SAMPLER:\n \/* These should be overridden with the type of the member when\n * dereferenced into. BRW_REGISTER_TYPE_UD seems like a likely\n * way to trip up if we don't.\n *\/\n return BRW_REGISTER_TYPE_UD;\n case GLSL_TYPE_VOID:\n case GLSL_TYPE_ERROR:\n case GLSL_TYPE_INTERFACE:\n assert(!\"not reached\");\n break;\n }\n\n return BRW_REGISTER_TYPE_F;\n}\n\nuint32_t\nbrw_conditional_for_comparison(unsigned int op)\n{\n switch (op) {\n case ir_binop_less:\n return BRW_CONDITIONAL_L;\n case ir_binop_greater:\n return BRW_CONDITIONAL_G;\n case ir_binop_lequal:\n return BRW_CONDITIONAL_LE;\n case ir_binop_gequal:\n return BRW_CONDITIONAL_GE;\n case ir_binop_equal:\n case ir_binop_all_equal: \/* same as equal for scalars *\/\n return BRW_CONDITIONAL_Z;\n case ir_binop_nequal:\n case ir_binop_any_nequal: \/* same as nequal for scalars *\/\n return BRW_CONDITIONAL_NZ;\n default:\n assert(!\"not reached: bad operation for comparison\");\n return BRW_CONDITIONAL_NZ;\n }\n}\n\nuint32_t\nbrw_math_function(enum opcode op)\n{\n switch (op) {\n case SHADER_OPCODE_RCP:\n return BRW_MATH_FUNCTION_INV;\n case SHADER_OPCODE_RSQ:\n return BRW_MATH_FUNCTION_RSQ;\n case SHADER_OPCODE_SQRT:\n return BRW_MATH_FUNCTION_SQRT;\n case SHADER_OPCODE_EXP2:\n return BRW_MATH_FUNCTION_EXP;\n case SHADER_OPCODE_LOG2:\n return BRW_MATH_FUNCTION_LOG;\n case SHADER_OPCODE_POW:\n return BRW_MATH_FUNCTION_POW;\n case SHADER_OPCODE_SIN:\n return BRW_MATH_FUNCTION_SIN;\n case SHADER_OPCODE_COS:\n return BRW_MATH_FUNCTION_COS;\n case SHADER_OPCODE_INT_QUOTIENT:\n return BRW_MATH_FUNCTION_INT_DIV_QUOTIENT;\n case SHADER_OPCODE_INT_REMAINDER:\n return BRW_MATH_FUNCTION_INT_DIV_REMAINDER;\n default:\n assert(!\"not reached: unknown math function\");\n return 0;\n }\n}\n\nuint32_t\nbrw_texture_offset(ir_constant *offset)\n{\n assert(offset != NULL);\n\n signed char offsets[3];\n for (unsigned i = 0; i < offset->type->vector_elements; i++)\n offsets[i] = (signed char) offset->value.i[i];\n\n \/* Combine all three offsets into a single unsigned dword:\n *\n * bits 11:8 - U Offset (X component)\n * bits 7:4 - V Offset (Y component)\n * bits 3:0 - R Offset (Z component)\n *\/\n unsigned offset_bits = 0;\n for (unsigned i = 0; i < offset->type->vector_elements; i++) {\n const unsigned shift = 4 * (2 - i);\n offset_bits |= (offsets[i] << shift) & (0xF << shift);\n }\n return offset_bits;\n}\n<commit_msg>i965: Lower the 4x8 pack\/unpack operations<commit_after>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * 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\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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\nextern \"C\" {\n#include \"main\/macros.h\"\n#include \"brw_context.h\"\n#include \"brw_vs.h\"\n}\n#include \"brw_fs.h\"\n#include \"glsl\/ir_optimization.h\"\n#include \"glsl\/ir_print_visitor.h\"\n\nstruct gl_shader *\nbrw_new_shader(struct gl_context *ctx, GLuint name, GLuint type)\n{\n struct brw_shader *shader;\n\n shader = rzalloc(NULL, struct brw_shader);\n if (shader) {\n shader->base.Type = type;\n shader->base.Name = name;\n _mesa_init_shader(ctx, &shader->base);\n }\n\n return &shader->base;\n}\n\nstruct gl_shader_program *\nbrw_new_shader_program(struct gl_context *ctx, GLuint name)\n{\n struct gl_shader_program *prog = rzalloc(NULL, struct gl_shader_program);\n if (prog) {\n prog->Name = name;\n _mesa_init_shader_program(ctx, prog);\n }\n return prog;\n}\n\n\/**\n * Performs a compile of the shader stages even when we don't know\n * what non-orthogonal state will be set, in the hope that it reflects\n * the eventual NOS used, and thus allows us to produce link failures.\n *\/\nstatic bool\nbrw_shader_precompile(struct gl_context *ctx, struct gl_shader_program *prog)\n{\n struct brw_context *brw = brw_context(ctx);\n\n if (brw->precompile && !brw_fs_precompile(ctx, prog))\n return false;\n\n if (brw->precompile && !brw_vs_precompile(ctx, prog))\n return false;\n\n return true;\n}\n\nstatic void\nbrw_lower_packing_builtins(struct brw_context *brw,\n gl_shader_type shader_type,\n exec_list *ir)\n{\n int ops = LOWER_PACK_SNORM_2x16\n | LOWER_UNPACK_SNORM_2x16\n | LOWER_PACK_UNORM_2x16\n | LOWER_UNPACK_UNORM_2x16\n | LOWER_PACK_SNORM_4x8\n | LOWER_UNPACK_SNORM_4x8\n | LOWER_PACK_UNORM_4x8\n | LOWER_UNPACK_UNORM_4x8;\n\n if (brw->intel.gen >= 7) {\n \/* Gen7 introduced the f32to16 and f16to32 instructions, which can be\n * used to execute packHalf2x16 and unpackHalf2x16. For AOS code, no\n * lowering is needed. For SOA code, the Half2x16 ops must be\n * scalarized.\n *\/\n if (shader_type == MESA_SHADER_FRAGMENT) {\n ops |= LOWER_PACK_HALF_2x16_TO_SPLIT\n | LOWER_UNPACK_HALF_2x16_TO_SPLIT;\n }\n } else {\n ops |= LOWER_PACK_HALF_2x16\n | LOWER_UNPACK_HALF_2x16;\n }\n\n lower_packing_builtins(ir, ops);\n}\n\nGLboolean\nbrw_link_shader(struct gl_context *ctx, struct gl_shader_program *shProg)\n{\n struct brw_context *brw = brw_context(ctx);\n struct intel_context *intel = &brw->intel;\n unsigned int stage;\n\n for (stage = 0; stage < ARRAY_SIZE(shProg->_LinkedShaders); stage++) {\n struct brw_shader *shader =\n\t (struct brw_shader *)shProg->_LinkedShaders[stage];\n static const GLenum targets[] = {\n\t GL_VERTEX_PROGRAM_ARB,\n\t GL_FRAGMENT_PROGRAM_ARB,\n\t GL_GEOMETRY_PROGRAM_NV\n };\n\n if (!shader)\n\t continue;\n\n struct gl_program *prog =\n\t ctx->Driver.NewProgram(ctx, targets[stage], shader->base.Name);\n if (!prog)\n\treturn false;\n prog->Parameters = _mesa_new_parameter_list();\n\n if (stage == 0) {\n\t struct gl_vertex_program *vp = (struct gl_vertex_program *) prog;\n\t vp->UsesClipDistance = shProg->Vert.UsesClipDistance;\n }\n\n void *mem_ctx = ralloc_context(NULL);\n bool progress;\n\n if (shader->ir)\n\t ralloc_free(shader->ir);\n shader->ir = new(shader) exec_list;\n clone_ir_list(mem_ctx, shader->ir, shader->base.ir);\n\n \/* lower_packing_builtins() inserts arithmetic instructions, so it\n * must precede lower_instructions().\n *\/\n brw_lower_packing_builtins(brw, (gl_shader_type) stage, shader->ir);\n do_mat_op_to_vec(shader->ir);\n lower_instructions(shader->ir,\n\t\t\t MOD_TO_FRACT |\n\t\t\t DIV_TO_MUL_RCP |\n\t\t\t SUB_TO_ADD_NEG |\n\t\t\t EXP_TO_EXP2 |\n\t\t\t LOG_TO_LOG2);\n\n \/* Pre-gen6 HW can only nest if-statements 16 deep. Beyond this,\n * if-statements need to be flattened.\n *\/\n if (intel->gen < 6)\n\t lower_if_to_cond_assign(shader->ir, 16);\n\n do_lower_texture_projection(shader->ir);\n if (intel->gen < 8 && !intel->is_haswell)\n brw_lower_texture_gradients(shader->ir);\n do_vec_index_to_cond_assign(shader->ir);\n brw_do_cubemap_normalize(shader->ir);\n lower_noise(shader->ir);\n lower_quadop_vector(shader->ir, false);\n\n bool input = true;\n bool output = stage == MESA_SHADER_FRAGMENT;\n bool temp = stage == MESA_SHADER_FRAGMENT;\n bool uniform = false;\n\n bool lowered_variable_indexing =\n lower_variable_index_to_cond_assign(shader->ir,\n input, output, temp, uniform);\n\n if (unlikely((INTEL_DEBUG & DEBUG_PERF) && lowered_variable_indexing)) {\n perf_debug(\"Unsupported form of variable indexing in FS; falling \"\n \"back to very inefficient code generation\\n\");\n }\n\n \/* FINISHME: Do this before the variable index lowering. *\/\n lower_ubo_reference(&shader->base, shader->ir);\n\n do {\n\t progress = false;\n\n\t if (stage == MESA_SHADER_FRAGMENT) {\n\t brw_do_channel_expressions(shader->ir);\n\t brw_do_vector_splitting(shader->ir);\n\t }\n\n\t progress = do_lower_jumps(shader->ir, true, true,\n\t\t\t\t true, \/* main return *\/\n\t\t\t\t false, \/* continue *\/\n\t\t\t\t false \/* loops *\/\n\t\t\t\t ) || progress;\n\n\t progress = do_common_optimization(shader->ir, true, true, 32)\n\t || progress;\n } while (progress);\n\n \/* Make a pass over the IR to add state references for any built-in\n * uniforms that are used. This has to be done now (during linking).\n * Code generation doesn't happen until the first time this shader is\n * used for rendering. Waiting until then to generate the parameters is\n * too late. At that point, the values for the built-in uniforms won't\n * get sent to the shader.\n *\/\n foreach_list(node, shader->ir) {\n\t ir_variable *var = ((ir_instruction *) node)->as_variable();\n\n\t if ((var == NULL) || (var->mode != ir_var_uniform)\n\t || (strncmp(var->name, \"gl_\", 3) != 0))\n\t continue;\n\n\t const ir_state_slot *const slots = var->state_slots;\n\t assert(var->state_slots != NULL);\n\n\t for (unsigned int i = 0; i < var->num_state_slots; i++) {\n\t _mesa_add_state_reference(prog->Parameters,\n\t\t\t\t (gl_state_index *) slots[i].tokens);\n\t }\n }\n\n validate_ir_tree(shader->ir);\n\n reparent_ir(shader->ir, shader->ir);\n ralloc_free(mem_ctx);\n\n do_set_program_inouts(shader->ir, prog,\n\t\t\t shader->base.Type == GL_FRAGMENT_SHADER);\n\n prog->SamplersUsed = shader->base.active_samplers;\n _mesa_update_shader_textures_used(shProg, prog);\n\n _mesa_reference_program(ctx, &shader->base.Program, prog);\n\n brw_add_texrect_params(prog);\n\n \/* This has to be done last. Any operation that can cause\n * prog->ParameterValues to get reallocated (e.g., anything that adds a\n * program constant) has to happen before creating this linkage.\n *\/\n _mesa_associate_uniform_storage(ctx, shProg, prog->Parameters);\n\n _mesa_reference_program(ctx, &prog, NULL);\n\n if (ctx->Shader.Flags & GLSL_DUMP) {\n static const char *target_strings[]\n = { \"vertex\", \"fragment\", \"geometry\" };\n printf(\"\\n\");\n printf(\"GLSL IR for linked %s program %d:\\n\", target_strings[stage],\n shProg->Name);\n _mesa_print_ir(shader->base.ir, NULL);\n }\n }\n\n if (!brw_shader_precompile(ctx, shProg))\n return false;\n\n return true;\n}\n\n\nint\nbrw_type_for_base_type(const struct glsl_type *type)\n{\n switch (type->base_type) {\n case GLSL_TYPE_FLOAT:\n return BRW_REGISTER_TYPE_F;\n case GLSL_TYPE_INT:\n case GLSL_TYPE_BOOL:\n return BRW_REGISTER_TYPE_D;\n case GLSL_TYPE_UINT:\n return BRW_REGISTER_TYPE_UD;\n case GLSL_TYPE_ARRAY:\n return brw_type_for_base_type(type->fields.array);\n case GLSL_TYPE_STRUCT:\n case GLSL_TYPE_SAMPLER:\n \/* These should be overridden with the type of the member when\n * dereferenced into. BRW_REGISTER_TYPE_UD seems like a likely\n * way to trip up if we don't.\n *\/\n return BRW_REGISTER_TYPE_UD;\n case GLSL_TYPE_VOID:\n case GLSL_TYPE_ERROR:\n case GLSL_TYPE_INTERFACE:\n assert(!\"not reached\");\n break;\n }\n\n return BRW_REGISTER_TYPE_F;\n}\n\nuint32_t\nbrw_conditional_for_comparison(unsigned int op)\n{\n switch (op) {\n case ir_binop_less:\n return BRW_CONDITIONAL_L;\n case ir_binop_greater:\n return BRW_CONDITIONAL_G;\n case ir_binop_lequal:\n return BRW_CONDITIONAL_LE;\n case ir_binop_gequal:\n return BRW_CONDITIONAL_GE;\n case ir_binop_equal:\n case ir_binop_all_equal: \/* same as equal for scalars *\/\n return BRW_CONDITIONAL_Z;\n case ir_binop_nequal:\n case ir_binop_any_nequal: \/* same as nequal for scalars *\/\n return BRW_CONDITIONAL_NZ;\n default:\n assert(!\"not reached: bad operation for comparison\");\n return BRW_CONDITIONAL_NZ;\n }\n}\n\nuint32_t\nbrw_math_function(enum opcode op)\n{\n switch (op) {\n case SHADER_OPCODE_RCP:\n return BRW_MATH_FUNCTION_INV;\n case SHADER_OPCODE_RSQ:\n return BRW_MATH_FUNCTION_RSQ;\n case SHADER_OPCODE_SQRT:\n return BRW_MATH_FUNCTION_SQRT;\n case SHADER_OPCODE_EXP2:\n return BRW_MATH_FUNCTION_EXP;\n case SHADER_OPCODE_LOG2:\n return BRW_MATH_FUNCTION_LOG;\n case SHADER_OPCODE_POW:\n return BRW_MATH_FUNCTION_POW;\n case SHADER_OPCODE_SIN:\n return BRW_MATH_FUNCTION_SIN;\n case SHADER_OPCODE_COS:\n return BRW_MATH_FUNCTION_COS;\n case SHADER_OPCODE_INT_QUOTIENT:\n return BRW_MATH_FUNCTION_INT_DIV_QUOTIENT;\n case SHADER_OPCODE_INT_REMAINDER:\n return BRW_MATH_FUNCTION_INT_DIV_REMAINDER;\n default:\n assert(!\"not reached: unknown math function\");\n return 0;\n }\n}\n\nuint32_t\nbrw_texture_offset(ir_constant *offset)\n{\n assert(offset != NULL);\n\n signed char offsets[3];\n for (unsigned i = 0; i < offset->type->vector_elements; i++)\n offsets[i] = (signed char) offset->value.i[i];\n\n \/* Combine all three offsets into a single unsigned dword:\n *\n * bits 11:8 - U Offset (X component)\n * bits 7:4 - V Offset (Y component)\n * bits 3:0 - R Offset (Z component)\n *\/\n unsigned offset_bits = 0;\n for (unsigned i = 0; i < offset->type->vector_elements; i++) {\n const unsigned shift = 4 * (2 - i);\n offset_bits |= (offsets[i] << shift) & (0xF << shift);\n }\n return offset_bits;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>minor follow-up changes<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * CrissCross\n * A multi-purpose cross-platform library.\n *\n * A product of Uplink Laboratories.\n *\n * (c) 2006-2008 Steven Noonan.\n * Licensed under the New BSD License.\n *\n *\/\n\n#include <crisscross\/universal_include.h>\n#include <crisscross\/debug.h>\n#include <crisscross\/console.h>\n\nnamespace CrissCross\n{\n\tnamespace IO\n\t{\n\t\tConsole::Console ( bool _clearOnInit ):\n\t\tCoreIOWriter ( stdout, false, CC_LN_LF ),\n\t\tCoreIOReader ( stdin, false, CC_LN_LF )\n\t\t{\n\t\t#ifdef TARGET_OS_WINDOWS\n\t\t\tm_consoleAllocated = false;\n\t\t\tif ( AllocConsole () == TRUE )\n\t\t\t{\n\t\t\t\tm_consoleAllocated = true;\n\t\t\t\tint hCrt = _open_osfhandle ( ( intptr_t ) GetStdHandle ( STD_OUTPUT_HANDLE ), _O_TEXT );\n\t\t\t\tFILE *hf = _fdopen ( hCrt, \"w\" );\n\n\t\t\t\t*stdout = *hf;\n\t\t\t\tint i = setvbuf ( stdout, NULL, _IONBF, 0 );\n\n\t\t\t\thCrt =\n\t\t\t\t\t_open_osfhandle ( ( intptr_t ) GetStdHandle ( STD_ERROR_HANDLE ),\n\t\t\t\t\t\t\t\t\t _O_TEXT );\n\t\t\t\thf = _fdopen ( hCrt, \"w\" );\n\t\t\t\t*stderr = *hf;\n\t\t\t\ti = setvbuf ( stdout, NULL, _IONBF, 0 );\n\t\t\t}\n\n\t\t\tif ( _clearOnInit ) Clear();\n\n\t\t\tSetTitle ( CC_LIB_NAME \" \" CC_LIB_VERSION \" (Codename \" CC_LIB_CODENAME \")\" );\n #elif defined ( TARGET_OS_NDSFIRMWARE )\n irqInit();\n irqEnable(IRQ_VBLANK);\n videoSetMode(MODE_0_2D);\n videoSetModeSub(MODE_0_2D | DISPLAY_BG0_ACTIVE);\n vramSetBankC(VRAM_C_SUB_BG);\n\t SUB_BG0_CR = BG_MAP_BASE(31);\n\t BG_PALETTE_SUB[255] = RGB15(31,31,31);\n\t consoleInitDefault((u16*)SCREEN_BASE_BLOCK_SUB(31), (u16*)CHAR_BASE_BLOCK_SUB(0), 16);\n\t\t#endif\n\t\t#ifdef ENABLE_CREDITS\n #if defined ( TARGET_OS_NDSFIRMWARE )\n\t\t\tg_stdout->SetColour ( g_stdout->FG_GREEN | g_stdout->FG_INTENSITY );\n\t\t\tg_stdout->WriteLine ( \"Powered by \" CC_LIB_NAME \" v\" CC_LIB_VERSION );\n\t\t\tg_stdout->SetColour ( 0 );\n\t\t\tg_stdout->WriteLine ( CC_LIB_NDS_COPYRIGHT );\n\t\t\tg_stdout->WriteLine ();\n #else\n\t\t\tg_stdout->SetColour ( g_stdout->FG_GREEN | g_stdout->FG_INTENSITY );\n\t\t\tg_stdout->WriteLine ( \"Powered by \" CC_LIB_NAME \" \" CC_LIB_VERSION \" (Codename \" CC_LIB_CODENAME \")\\n \" CC_LIB_URL );\n\t\t\tg_stdout->SetColour ( 0 );\n\t\t\tg_stdout->WriteLine ( CC_LIB_COPYRIGHT );\n\t\t\tg_stdout->WriteLine ();\n #endif\n\t\t#endif\n\t\t}\n\n\t\tConsole::Console ( FILE * _outputBuffer, FILE *_inputBuffer ):\n\t\tCoreIOWriter ( _outputBuffer, false, CC_LN_LF ),\n\t\tCoreIOReader ( _inputBuffer, false, CC_LN_LF )\n\t\t{\n\t\t}\n\n\t\tConsole::~Console ()\n\t\t{\n\t\t\tSetColour ( 0 );\n\t\t#ifdef TARGET_OS_WINDOWS\n\t\t\tif ( m_consoleAllocated ) FreeConsole ();\n\t\t#endif\n\t\t}\n\n\t\tvoid\n\t\tConsole::SetColour ()\n\t\t{\n\t\t\tSetColour ( 0 );\n\t\t}\n\n\t\tvoid\n\t\tConsole::SetColour ( int _flags )\n\t\t{\n\t\t\tCoreAssert ( this != NULL );\n\n\t\t#if !defined ( ANSI_COLOUR ) && defined ( TARGET_OS_WINDOWS )\n\t\t\tHANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );\n\n\t\t\tif ( _flags == 0 )\n\t\t\t\tSetConsoleTextAttribute ( hConsole, FG_GRAY );\n\t\t\telse\n\t\t\t\tSetConsoleTextAttribute ( hConsole, _flags );\n\t\t#elif defined ( ANSI_COLOUR )\n\t\t\t\/\/ Reset colours to defaults.\n\t\t\tWrite ( \"\\033[39m\" );\n\n\t\t\tif ( _flags == 0 )\n\t\t\t\treturn;\n\n\t\t\tchar codes[16];\n\n\t\t\tsprintf ( codes, \"\\033[\" );\n\n\t\t\tif ( _flags & FG_INTENSITY )\n\t\t\t\tstrcat ( codes, \"1;\" );\n\t\t\tif ( _flags & FG_RED )\n\t\t\t\tstrcat ( codes, \"31;\" );\n\t\t\tif ( _flags & FG_GREEN )\n\t\t\t\tstrcat ( codes, \"32;\" );\n\t\t\tif ( _flags & FG_BROWN )\n\t\t\t\tstrcat ( codes, \"33;\" );\n\t\t\tif ( _flags & FG_BLUE )\n\t\t\t\tstrcat ( codes, \"34;\" );\n\t\t\tif ( _flags & FG_MAGENTA )\n\t\t\t\tstrcat ( codes, \"35;\" );\n\t\t\tif ( _flags & FG_CYAN )\n\t\t\t\tstrcat ( codes, \"36;\" );\n\t\t\tif ( _flags & FG_GRAY )\n\t\t\t\tstrcat ( codes, \"37;\" );\n\t\t\tif ( _flags & FG_WHITE )\n\t\t\t\tstrcat ( codes, \"39;\" );\n\n\t\t\t\/*\n\t\t\t TODO: Determine if there is an ANSI code for background color intensity.\n\t\t\t if ( _flags & BG_INTENSITY )\n\t\t\t strcat ( codes, \"???????\" );\n\t\t\t *\/\n\t\t\tif ( _flags & BG_RED )\n\t\t\t\tstrcat ( codes, \"41;\" );\n\t\t\tif ( _flags & BG_GREEN )\n\t\t\t\tstrcat ( codes, \"42;\" );\n\t\t\tif ( _flags & BG_BROWN )\n\t\t\t\tstrcat ( codes, \"43;\" );\n\t\t\tif ( _flags & BG_BLUE )\n\t\t\t\tstrcat ( codes, \"44;\" );\n\t\t\tif ( _flags & BG_MAGENTA )\n\t\t\t\tstrcat ( codes, \"45;\" );\n\t\t\tif ( _flags & BG_CYAN )\n\t\t\t\tstrcat ( codes, \"46;\" );\n\t\t\tif ( _flags & BG_WHITE )\n\t\t\t\tstrcat ( codes, \"47;\" );\n\n\t\t\tcodes[strlen ( codes ) - 1] = 'm';\n\n\t\t\tWrite ( \"%s\", codes );\n\t\t#endif\n\t\t}\n\n\t\tvoid\n\t\tConsole::SetTitle ( const char *_title )\n\t\t{\n\t\t#ifdef TARGET_OS_WINDOWS\n\t\t\tSetConsoleTitleA ( _title );\n\t\t#endif\n\t\t}\n\n\t\tvoid\n\t\tConsole::SetTitle ( std::string &_title )\n\t\t{\n\t\t\tSetTitle ( _title.c_str () );\n\t\t}\n\n\t\tvoid\n\t\tConsole::Clear ()\n\t\t{\n\t\t\tCoreAssert ( this != NULL );\n\n\t\t#if defined ( TARGET_OS_WINDOWS )\n\t\t\tCOORD coordScreen = { 0, 0 };\n\t\t\tDWORD cCharsWritten;\n\t\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\t\tDWORD dwConSize;\n\t\t\tHANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );\n\n\t\t\tGetConsoleScreenBufferInfo ( hConsole, &csbi );\n\t\t\tdwConSize = csbi.dwSize.X * csbi.dwSize.Y;\n\t\t\tFillConsoleOutputCharacter ( hConsole, TEXT ( ' ' ), dwConSize,\n\t\t\t\t\t\t\t\t\t\t coordScreen, &cCharsWritten );\n\t\t\tGetConsoleScreenBufferInfo ( hConsole, &csbi );\n\t\t\tFillConsoleOutputAttribute ( hConsole, csbi.wAttributes, dwConSize,\n\t\t\t\t\t\t\t\t\t\t coordScreen, &cCharsWritten );\n\t\t\tSetConsoleCursorPosition ( hConsole, coordScreen );\n\t\t#elif defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_LINUX ) || \\\n defined ( TARGET_OS_NDSFIRMWARE )\n\t\t\tWrite ( \"%s\", \"\\033[2J\" );\n\t\t#endif\n\t\t}\n\n\t\tvoid\n\t\tConsole::Flush ()\n\t\t{\n\t\t\tCoreIOReader::Flush();\n\t\t\tCoreIOWriter::Flush();\n\t\t}\n\n\t\tvoid\n\t\tConsole::MoveUp ( int _lines )\n\t\t{\n\t\t#if defined ( TARGET_OS_WINDOWS )\n\t\t\tCOORD coordScreen = { 0, 0 };\n\t\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\t\tHANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );\n\n\t\t\tGetConsoleScreenBufferInfo ( hConsole, &csbi );\n\t\t\tcoordScreen = csbi.dwCursorPosition;\n\t\t\tcoordScreen.Y -= (short)_lines;\n\t\t\tif ( coordScreen.Y < 0 ) coordScreen.Y = 0;\n\t\t\tSetConsoleCursorPosition ( hConsole, coordScreen );\n\t\t#elif defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_LINUX )\n\t\t\tWrite ( \"%s%d%s\", \"\\033[\", _lines, \"A\" );\n\t\t#endif\n\t\t}\n\n\t\tchar Console::ReadChar ()\n\t\t{\n\t\t\tchar _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%c\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tint Console::ReadInt ()\n\t\t{\n\t\t\tint _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%d\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tlong Console::ReadLong ()\n\t\t{\n\t\t\tlong _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%ld\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tfloat Console::ReadFloat ()\n\t\t{\n\t\t\tfloat _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%f\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tdouble Console::ReadDouble ()\n\t\t{\n\t\t\tdouble _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%lf\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tchar Console::ReadChar ( char _min, char _max )\n\t\t{\n\t\t\tchar _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%c\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tint Console::ReadInt ( int _min, int _max )\n\t\t{\n\t\t\tint _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%d\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tlong Console::ReadLong ( long _min, long _max )\n\t\t{\n\t\t\tlong _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%ld\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tfloat Console::ReadFloat ( float _min, float _max )\n\t\t{\n\t\t\tfloat _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%f\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tdouble Console::ReadDouble ( double _min, double _max )\n\t\t{\n\t\t\tdouble _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%lf\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tint Console::Seek ( cc_int64_t _position ) { return 0; }\n\t\tint Console::Forward ( cc_int64_t _position ) { return 0; }\n\t\tcc_int64_t Console::Length() { return 0; }\n\t\tint Console::Read ( char *_buffer, size_t _bufferLength, size_t _bufferIndex, size_t _count ) { return 0; }\n\t\tbool Console::EndOfFile () { return false; }\n\t}\n}\n<commit_msg>Reset fixed.<commit_after>\/*\n * CrissCross\n * A multi-purpose cross-platform library.\n *\n * A product of Uplink Laboratories.\n *\n * (c) 2006-2008 Steven Noonan.\n * Licensed under the New BSD License.\n *\n *\/\n\n#include <crisscross\/universal_include.h>\n#include <crisscross\/debug.h>\n#include <crisscross\/console.h>\n\nnamespace CrissCross\n{\n\tnamespace IO\n\t{\n\t\tConsole::Console ( bool _clearOnInit ):\n\t\tCoreIOWriter ( stdout, false, CC_LN_LF ),\n\t\tCoreIOReader ( stdin, false, CC_LN_LF )\n\t\t{\n\t\t#ifdef TARGET_OS_WINDOWS\n\t\t\tm_consoleAllocated = false;\n\t\t\tif ( AllocConsole () == TRUE )\n\t\t\t{\n\t\t\t\tm_consoleAllocated = true;\n\t\t\t\tint hCrt = _open_osfhandle ( ( intptr_t ) GetStdHandle ( STD_OUTPUT_HANDLE ), _O_TEXT );\n\t\t\t\tFILE *hf = _fdopen ( hCrt, \"w\" );\n\n\t\t\t\t*stdout = *hf;\n\t\t\t\tint i = setvbuf ( stdout, NULL, _IONBF, 0 );\n\n\t\t\t\thCrt =\n\t\t\t\t\t_open_osfhandle ( ( intptr_t ) GetStdHandle ( STD_ERROR_HANDLE ),\n\t\t\t\t\t\t\t\t\t _O_TEXT );\n\t\t\t\thf = _fdopen ( hCrt, \"w\" );\n\t\t\t\t*stderr = *hf;\n\t\t\t\ti = setvbuf ( stdout, NULL, _IONBF, 0 );\n\t\t\t}\n\n\t\t\tif ( _clearOnInit ) Clear();\n\n\t\t\tSetTitle ( CC_LIB_NAME \" \" CC_LIB_VERSION \" (Codename \" CC_LIB_CODENAME \")\" );\n #elif defined ( TARGET_OS_NDSFIRMWARE )\n irqInit();\n irqEnable(IRQ_VBLANK);\n videoSetMode(MODE_0_2D);\n videoSetModeSub(MODE_0_2D | DISPLAY_BG0_ACTIVE);\n vramSetBankC(VRAM_C_SUB_BG);\n\t SUB_BG0_CR = BG_MAP_BASE(31);\n\t BG_PALETTE_SUB[255] = RGB15(31,31,31);\n\t consoleInitDefault((u16*)SCREEN_BASE_BLOCK_SUB(31), (u16*)CHAR_BASE_BLOCK_SUB(0), 16);\n\t\t#endif\n\t\t#ifdef ENABLE_CREDITS\n #if defined ( TARGET_OS_NDSFIRMWARE )\n\t\t\tg_stdout->SetColour ( g_stdout->FG_GREEN | g_stdout->FG_INTENSITY );\n\t\t\tg_stdout->WriteLine ( \"Powered by \" CC_LIB_NAME \" v\" CC_LIB_VERSION );\n\t\t\tg_stdout->SetColour ( 0 );\n\t\t\tg_stdout->WriteLine ( CC_LIB_NDS_COPYRIGHT );\n\t\t\tg_stdout->WriteLine ();\n #else\n\t\t\tg_stdout->SetColour ( g_stdout->FG_GREEN | g_stdout->FG_INTENSITY );\n\t\t\tg_stdout->WriteLine ( \"Powered by \" CC_LIB_NAME \" \" CC_LIB_VERSION \" (Codename \" CC_LIB_CODENAME \")\\n \" CC_LIB_URL );\n\t\t\tg_stdout->SetColour ( 0 );\n\t\t\tg_stdout->WriteLine ( CC_LIB_COPYRIGHT );\n\t\t\tg_stdout->WriteLine ();\n #endif\n\t\t#endif\n\t\t}\n\n\t\tConsole::Console ( FILE * _outputBuffer, FILE *_inputBuffer ):\n\t\tCoreIOWriter ( _outputBuffer, false, CC_LN_LF ),\n\t\tCoreIOReader ( _inputBuffer, false, CC_LN_LF )\n\t\t{\n\t\t}\n\n\t\tConsole::~Console ()\n\t\t{\n\t\t\tSetColour ( 0 );\n\t\t#ifdef TARGET_OS_WINDOWS\n\t\t\tif ( m_consoleAllocated ) FreeConsole ();\n\t\t#endif\n\t\t}\n\n\t\tvoid\n\t\tConsole::SetColour ()\n\t\t{\n\t\t\tSetColour ( 0 );\n\t\t}\n\n\t\tvoid\n\t\tConsole::SetColour ( int _flags )\n\t\t{\n\t\t\tCoreAssert ( this != NULL );\n\n\t\t#if !defined ( ANSI_COLOUR ) && defined ( TARGET_OS_WINDOWS )\n\t\t\tHANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );\n\n\t\t\tif ( _flags == 0 )\n\t\t\t\tSetConsoleTextAttribute ( hConsole, FG_GRAY );\n\t\t\telse\n\t\t\t\tSetConsoleTextAttribute ( hConsole, _flags );\n\t\t#elif defined ( ANSI_COLOUR )\n\t\t\t\/\/ Reset colours to defaults.\n\t\t\tWrite ( \"\\033[0m\" );\n\n\t\t\tif ( _flags == 0 )\n\t\t\t\treturn;\n\n\t\t\tchar codes[16];\n\n\t\t\tsprintf ( codes, \"\\033[\" );\n\n\t\t\tif ( _flags & FG_INTENSITY )\n\t\t\t\tstrcat ( codes, \"1;\" );\n\t\t\tif ( _flags & FG_RED )\n\t\t\t\tstrcat ( codes, \"31;\" );\n\t\t\tif ( _flags & FG_GREEN )\n\t\t\t\tstrcat ( codes, \"32;\" );\n\t\t\tif ( _flags & FG_BROWN )\n\t\t\t\tstrcat ( codes, \"33;\" );\n\t\t\tif ( _flags & FG_BLUE )\n\t\t\t\tstrcat ( codes, \"34;\" );\n\t\t\tif ( _flags & FG_MAGENTA )\n\t\t\t\tstrcat ( codes, \"35;\" );\n\t\t\tif ( _flags & FG_CYAN )\n\t\t\t\tstrcat ( codes, \"36;\" );\n\t\t\tif ( _flags & FG_GRAY )\n\t\t\t\tstrcat ( codes, \"37;\" );\n\t\t\tif ( _flags & FG_WHITE )\n\t\t\t\tstrcat ( codes, \"39;\" );\n\n\t\t\t\/*\n\t\t\t TODO: Determine if there is an ANSI code for background color intensity.\n\t\t\t if ( _flags & BG_INTENSITY )\n\t\t\t strcat ( codes, \"???????\" );\n\t\t\t *\/\n\t\t\tif ( _flags & BG_RED )\n\t\t\t\tstrcat ( codes, \"41;\" );\n\t\t\tif ( _flags & BG_GREEN )\n\t\t\t\tstrcat ( codes, \"42;\" );\n\t\t\tif ( _flags & BG_BROWN )\n\t\t\t\tstrcat ( codes, \"43;\" );\n\t\t\tif ( _flags & BG_BLUE )\n\t\t\t\tstrcat ( codes, \"44;\" );\n\t\t\tif ( _flags & BG_MAGENTA )\n\t\t\t\tstrcat ( codes, \"45;\" );\n\t\t\tif ( _flags & BG_CYAN )\n\t\t\t\tstrcat ( codes, \"46;\" );\n\t\t\tif ( _flags & BG_WHITE )\n\t\t\t\tstrcat ( codes, \"47;\" );\n\n\t\t\tcodes[strlen ( codes ) - 1] = 'm';\n\n\t\t\tWrite ( \"%s\", codes );\n\t\t#endif\n\t\t}\n\n\t\tvoid\n\t\tConsole::SetTitle ( const char *_title )\n\t\t{\n\t\t#ifdef TARGET_OS_WINDOWS\n\t\t\tSetConsoleTitleA ( _title );\n\t\t#endif\n\t\t}\n\n\t\tvoid\n\t\tConsole::SetTitle ( std::string &_title )\n\t\t{\n\t\t\tSetTitle ( _title.c_str () );\n\t\t}\n\n\t\tvoid\n\t\tConsole::Clear ()\n\t\t{\n\t\t\tCoreAssert ( this != NULL );\n\n\t\t#if defined ( TARGET_OS_WINDOWS )\n\t\t\tCOORD coordScreen = { 0, 0 };\n\t\t\tDWORD cCharsWritten;\n\t\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\t\tDWORD dwConSize;\n\t\t\tHANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );\n\n\t\t\tGetConsoleScreenBufferInfo ( hConsole, &csbi );\n\t\t\tdwConSize = csbi.dwSize.X * csbi.dwSize.Y;\n\t\t\tFillConsoleOutputCharacter ( hConsole, TEXT ( ' ' ), dwConSize,\n\t\t\t\t\t\t\t\t\t\t coordScreen, &cCharsWritten );\n\t\t\tGetConsoleScreenBufferInfo ( hConsole, &csbi );\n\t\t\tFillConsoleOutputAttribute ( hConsole, csbi.wAttributes, dwConSize,\n\t\t\t\t\t\t\t\t\t\t coordScreen, &cCharsWritten );\n\t\t\tSetConsoleCursorPosition ( hConsole, coordScreen );\n\t\t#elif defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_LINUX ) || \\\n defined ( TARGET_OS_NDSFIRMWARE )\n\t\t\tWrite ( \"%s\", \"\\033[2J\" );\n\t\t#endif\n\t\t}\n\n\t\tvoid\n\t\tConsole::Flush ()\n\t\t{\n\t\t\tCoreIOReader::Flush();\n\t\t\tCoreIOWriter::Flush();\n\t\t}\n\n\t\tvoid\n\t\tConsole::MoveUp ( int _lines )\n\t\t{\n\t\t#if defined ( TARGET_OS_WINDOWS )\n\t\t\tCOORD coordScreen = { 0, 0 };\n\t\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\t\tHANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );\n\n\t\t\tGetConsoleScreenBufferInfo ( hConsole, &csbi );\n\t\t\tcoordScreen = csbi.dwCursorPosition;\n\t\t\tcoordScreen.Y -= (short)_lines;\n\t\t\tif ( coordScreen.Y < 0 ) coordScreen.Y = 0;\n\t\t\tSetConsoleCursorPosition ( hConsole, coordScreen );\n\t\t#elif defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_LINUX )\n\t\t\tWrite ( \"%s%d%s\", \"\\033[\", _lines, \"A\" );\n\t\t#endif\n\t\t}\n\n\t\tchar Console::ReadChar ()\n\t\t{\n\t\t\tchar _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%c\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tint Console::ReadInt ()\n\t\t{\n\t\t\tint _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%d\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tlong Console::ReadLong ()\n\t\t{\n\t\t\tlong _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%ld\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tfloat Console::ReadFloat ()\n\t\t{\n\t\t\tfloat _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%f\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tdouble Console::ReadDouble ()\n\t\t{\n\t\t\tdouble _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%lf\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\treturn _result;\n\t\t}\n\n\t\tchar Console::ReadChar ( char _min, char _max )\n\t\t{\n\t\t\tchar _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%c\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tint Console::ReadInt ( int _min, int _max )\n\t\t{\n\t\t\tint _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%d\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tlong Console::ReadLong ( long _min, long _max )\n\t\t{\n\t\t\tlong _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%ld\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tfloat Console::ReadFloat ( float _min, float _max )\n\t\t{\n\t\t\tfloat _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%f\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tdouble Console::ReadDouble ( double _min, double _max )\n\t\t{\n\t\t\tdouble _result = 0;\n\t\t\tfscanf ( m_fileInputPointer, \"%lf\", &_result );\n\t\t\tCoreIOReader::Flush();\n\t\t\tif ( ( _min && _max ) && ( _min < _max ) )\n\t\t\t{\n\t\t\t\tif ( _result < _min )\n\t\t\t\t\t_result = _min;\n\t\t\t\tif ( _result > _max )\n\t\t\t\t\t_result = _max;\n\t\t\t}\n\t\t\treturn _result;\n\t\t}\n\n\t\tint Console::Seek ( cc_int64_t _position ) { return 0; }\n\t\tint Console::Forward ( cc_int64_t _position ) { return 0; }\n\t\tcc_int64_t Console::Length() { return 0; }\n\t\tint Console::Read ( char *_buffer, size_t _bufferLength, size_t _bufferIndex, size_t _count ) { return 0; }\n\t\tbool Console::EndOfFile () { return false; }\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <algorithm>\n#include <sstream>\n#include <fstream>\n#include <cmath>\n#include \"display.hpp\"\n#include \"my_opengl.hpp\"\n#include \"bind.hpp\"\n#include \"math.hpp\"\n#include \"logic.hpp\"\n#include \"input.hpp\"\n\nstatic inline RenderContext contextFromFiles(std::string name)\n{\n std::stringstream vert;\n std::stringstream frag;\n\n vert << std::ifstream(\"shaders\/\" + name + \".vert\").rdbuf();\n frag << std::ifstream(\"shaders\/\" + name + \".frag\").rdbuf();\n return {Vao(), my_opengl::createProgram<2>({GL_VERTEX_SHADER, GL_FRAGMENT_SHADER},\n\t\t\t\t\t {vert.str(), frag.str()})};\n}\n\nDisplay::Display(Vect<2u, unsigned int> size, Logic &logic)\n : size(size), offset{0.0f, 0.0f}, scale{static_cast<float>(size[1]) \/ static_cast<float>(size[0]), 1.0f},\n worldRenderContext(contextFromFiles(\"basic\")),\n lightRenderContext(contextFromFiles(\"color\")),\n postProcessContext(contextFromFiles(\"multiply\")),\n fixtureBuffer(),\n lightBuffer(),\n cornerBuffer(),\n lightRenderTexture(size),\n worldRenderTexture(size),\n lights(),\n fpsCounter(),\n logic(logic)\n{\n {\n Bind<RenderContext> bind(worldRenderContext);\n float const data[12]{0.5f, 0.5f, 1.0f, 0.0f,\n\t0.0f, -0.7f, 1.0f, 1.0f,\n\t-0.5f, 0.5f, 0.0f, 1.0f};\n\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);\n glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), data, GL_STATIC_DRAW);\n glVertexAttribPointer(0, 2, GL_FLOAT, false, 4 * sizeof(float), nullptr);\n glVertexAttribPointer(1, 2, GL_FLOAT, false, 4 * sizeof(float), reinterpret_cast<void *>(2u * sizeof(float)));\n }\n {\n Bind<RenderContext> bind(lightRenderContext);\n\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glBindBuffer(GL_ARRAY_BUFFER, lightBuffer);\n glVertexAttribPointer(0, 2, GL_FLOAT, false, 6 * sizeof(float), nullptr);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 6 * sizeof(float), reinterpret_cast<void *>(2u * sizeof(float)));\n }\n {\n Bind<RenderContext> bind(postProcessContext);\n float const data[8]{0.0f, 0.0f,\n\t0.0f, 1.0f,\n\t1.0f, 0.0f,\n\t1.0f, 1.0f};\n\n glEnableVertexAttribArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, cornerBuffer);\n glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), data, GL_STATIC_DRAW);\n glVertexAttribPointer(0, 2, GL_FLOAT, false, 2 * sizeof(float), nullptr);\n }\n lights.push_back({{0.5f, 0.0f}, {1.0f, 0.5f, 1.0f, 1.0f}, 1.5f});\n lights.push_back({{-0.5f, 0.0f}, {0.0f, 1.0f, 0.5f, 1.0f}, 0.5f});\n}\n\nDisplay::~Display()\n{\n lights.clear();\n}\n\nvoid Display::setOffsetAndScale(Program program)\n{\n my_opengl::setUniform(offset, \"offset\", program);\n my_opengl::setUniform(scale, \"scale\", program);\n}\n\n\/\/TODO : optimize\nvoid Display::renderLights()\n{\n Bind<RenderContext> bind(lightRenderContext);\n float *data(new float[lights.size() * 6u * 3u * 20u]);\n unsigned int i(0);\n\n std::for_each(lights.begin(), lights.end(),\n\t\t[&data, &i](Light l)\n\t\t{\n\t\t for (unsigned int j(0); j < 20u; j++)\n\t\t {\n\t\t data[i++] = l.center[0];\n\t\t data[i++] = l.center[1];\n\t\t data[i++] = l.color[0];\n\t\t data[i++] = l.color[1];\n\t\t data[i++] = l.color[2];\n\t\t data[i++] = l.color[3];\n\t\t data[i++] = l.center[0] + cos(static_cast<float>(j) \/ 20.0f * M_PI * 2.0f) * l.radius;\n\t\t data[i++] = l.center[1] + sin(static_cast<float>(j) \/ 20.0f * M_PI * 2.0f) * l.radius;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = l.center[0] + cos(static_cast<float>(j + 1) \/ 20.0f * M_PI * 2.0f) * l.radius;\n\t\t data[i++] = l.center[1] + sin(static_cast<float>(j + 1) \/ 20.0f * M_PI * 2.0f) * l.radius;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t }\n\t\t});\n glBindBuffer(GL_ARRAY_BUFFER, lightBuffer);\n glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);\n delete [] data;\n setOffsetAndScale(lightRenderContext.program);\n glBindFramebuffer(GL_FRAMEBUFFER, lightRenderTexture.framebuffer);\n glClearColor(0.1f, 0.1f, 0.1f, 0.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND);\n glDrawArrays(GL_TRIANGLES, 0, i \/ 6u);\n glBindFramebuffer(GL_FRAMEBUFFER, 0);\n glDisable(GL_BLEND);\n}\n\nvoid Display::displayBots()\n{\n Bind<RenderContext> bind(worldRenderContext);\n float *data = new float[logic.getNanoBots().size() * 4 * 4 * 3];\n unsigned int i(0);\n\n for (unsigned int j(0); j < logic.getNanoBots().size(); j++)\n {\n Vect<2u, double> d(logic.getNanoBots()[j]->getSpeed().normalized() * 0.01);\n\n data[i++] = logic.getNanoBots()[j]->getPos()[0] + d[0];\n data[i++] = logic.getNanoBots()[j]->getPos()[1] + d[1];\n data[i++] = 1.0f;\n data[i++] = 1.0f;\n data[i++] = logic.getNanoBots()[j]->getPos()[0] + d[1] - d[0];\n data[i++] = logic.getNanoBots()[j]->getPos()[1] - d[0] - d[1];\n data[i++] = 0.0f;\n data[i++] = 1.0f;\n data[i++] = logic.getNanoBots()[j]->getPos()[0] - d[1] - d[0];\n data[i++] = logic.getNanoBots()[j]->getPos()[1] + d[0] - d[1];\n data[i++] = 1.0f;\n data[i++] = 0.0f;\n }\n glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);\n glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);\n delete [] data;\n setOffsetAndScale(worldRenderContext.program);\n glBindFramebuffer(GL_FRAMEBUFFER, worldRenderTexture.framebuffer);\n glClearColor(0.1f, 0.1f, 0.1f, 0.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND);\n glDrawArrays(GL_TRIANGLES, 0, i \/ 4);\n glBindFramebuffer(GL_FRAMEBUFFER, 0);\n glDisable(GL_BLEND);\n}\n\nvoid Display::displayMouseSelection()\n{\n if (!Callback::leftPressed)\n return;\n\n glClear(GL_COLOR_BUFFER_BIT);\n glLineWidth(30);\n glFlush();\n}\n\nvoid Display::postProcess()\n{\n Bind<RenderContext> bind(postProcessContext);\n\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, lightRenderTexture.texture);\n glActiveTexture(GL_TEXTURE1);\n glBindTexture(GL_TEXTURE_2D, worldRenderTexture.texture);\n my_opengl::setUniform(0u, \"lights\", postProcessContext.program);\n my_opengl::setUniform(1u, \"world\", postProcessContext.program);\n my_opengl::setUniform(Vect<2u, float>{1.0f, 1.0f} \/ Vect<2u, float>(size), \"step\", postProcessContext.program);\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n}\n\nvoid Display::render()\n{\n \/\/ lights[0].center += {-0.01, 0.01};\n \/\/ lights[0].center[0] -= 0.01;\n renderLights();\n displayBots();\n \/\/ TODO : good idea ?\n displayMouseSelection();\n postProcess();\n fpsCounter.tick();\n}\n<commit_msg>deisplay of drag select<commit_after>#include <iostream>\n#include <string>\n#include <algorithm>\n#include <sstream>\n#include <fstream>\n#include <cmath>\n#include \"display.hpp\"\n#include \"my_opengl.hpp\"\n#include \"bind.hpp\"\n#include \"math.hpp\"\n#include \"logic.hpp\"\n#include \"input.hpp\"\n\nstatic inline RenderContext contextFromFiles(std::string name)\n{\n std::stringstream vert;\n std::stringstream frag;\n\n vert << std::ifstream(\"shaders\/\" + name + \".vert\").rdbuf();\n frag << std::ifstream(\"shaders\/\" + name + \".frag\").rdbuf();\n return {Vao(), my_opengl::createProgram<2>({GL_VERTEX_SHADER, GL_FRAGMENT_SHADER},\n\t\t\t\t\t {vert.str(), frag.str()})};\n}\n\nDisplay::Display(Vect<2u, unsigned int> size, Logic &logic)\n : size(size), offset{0.0f, 0.0f}, scale{static_cast<float>(size[1]) \/ static_cast<float>(size[0]), 1.0f},\n worldRenderContext(contextFromFiles(\"basic\")),\n lightRenderContext(contextFromFiles(\"color\")),\n postProcessContext(contextFromFiles(\"multiply\")),\n fixtureBuffer(),\n lightBuffer(),\n cornerBuffer(),\n lightRenderTexture(size),\n worldRenderTexture(size),\n lights(),\n fpsCounter(),\n logic(logic)\n{\n {\n Bind<RenderContext> bind(worldRenderContext);\n \/\/ float const data[12]{0.5f, 0.5f, 1.0f, 0.0f,\n \/\/ \t0.0f, -0.7f, 1.0f, 1.0f,\n \/\/ \t-0.5f, 0.5f, 0.0f, 1.0f};\n \n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);\n \/\/ glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), data, GL_STATIC_DRAW);\n glVertexAttribPointer(0, 2, GL_FLOAT, false, 5 * sizeof(float), nullptr);\n glVertexAttribPointer(1, 3, GL_FLOAT, false, 5 * sizeof(float), reinterpret_cast<void *>(2u * sizeof(float)));\n }\n {\n Bind<RenderContext> bind(lightRenderContext);\n\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glBindBuffer(GL_ARRAY_BUFFER, lightBuffer);\n glVertexAttribPointer(0, 2, GL_FLOAT, false, 6 * sizeof(float), nullptr);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 6 * sizeof(float), reinterpret_cast<void *>(2u * sizeof(float)));\n }\n {\n Bind<RenderContext> bind(postProcessContext);\n float const data[8]{0.0f, 0.0f,\n\t0.0f, 1.0f,\n\t1.0f, 0.0f,\n\t1.0f, 1.0f};\n\n glEnableVertexAttribArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, cornerBuffer);\n glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), data, GL_STATIC_DRAW);\n glVertexAttribPointer(0, 2, GL_FLOAT, false, 2 * sizeof(float), nullptr);\n }\n lights.push_back({{0.5f, 0.0f}, {1.0f, 0.5f, 1.0f, 1.0f}, 1.5f});\n lights.push_back({{-0.5f, 0.0f}, {0.0f, 1.0f, 0.5f, 1.0f}, 0.5f});\n}\n\nDisplay::~Display()\n{\n lights.clear();\n}\n\nvoid Display::setOffsetAndScale(Program program)\n{\n my_opengl::setUniform(offset, \"offset\", program);\n my_opengl::setUniform(scale, \"scale\", program);\n}\n\n\/\/TODO : optimize\nvoid Display::renderLights()\n{\n Bind<RenderContext> bind(lightRenderContext);\n float *data(new float[lights.size() * 6u * 3u * 20u]);\n unsigned int i(0);\n\n std::for_each(lights.begin(), lights.end(),\n\t\t[&data, &i](Light l)\n\t\t{\n\t\t for (unsigned int j(0); j < 20u; j++)\n\t\t {\n\t\t data[i++] = l.center[0];\n\t\t data[i++] = l.center[1];\n\t\t data[i++] = l.color[0];\n\t\t data[i++] = l.color[1];\n\t\t data[i++] = l.color[2];\n\t\t data[i++] = l.color[3];\n\t\t data[i++] = l.center[0] + cos(static_cast<float>(j) \/ 20.0f * M_PI * 2.0f) * l.radius;\n\t\t data[i++] = l.center[1] + sin(static_cast<float>(j) \/ 20.0f * M_PI * 2.0f) * l.radius;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = l.center[0] + cos(static_cast<float>(j + 1) \/ 20.0f * M_PI * 2.0f) * l.radius;\n\t\t data[i++] = l.center[1] + sin(static_cast<float>(j + 1) \/ 20.0f * M_PI * 2.0f) * l.radius;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t data[i++] = 0.0f;\n\t\t }\n\t\t});\n glBindBuffer(GL_ARRAY_BUFFER, lightBuffer);\n glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);\n delete [] data;\n setOffsetAndScale(lightRenderContext.program);\n glBindFramebuffer(GL_FRAMEBUFFER, lightRenderTexture.framebuffer);\n glClearColor(0.1f, 0.1f, 0.1f, 0.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND);\n glDrawArrays(GL_TRIANGLES, 0, i \/ 6u);\n glBindFramebuffer(GL_FRAMEBUFFER, 0);\n glDisable(GL_BLEND);\n}\n\nvoid Display::displayBots()\n{\n Bind<RenderContext> bind(worldRenderContext);\n float *data = new float[logic.getNanoBots().size() * 4 * 5 * 3];\n unsigned int i(0);\n\n for (unsigned int j(0); j < logic.getNanoBots().size(); j++)\n {\n Vect<2u, double> d(logic.getNanoBots()[j]->getSpeed().normalized() * 0.01);\n\n data[i++] = logic.getNanoBots()[j]->getPos()[0] + d[0];\n data[i++] = logic.getNanoBots()[j]->getPos()[1] + d[1];\n data[i++] = 1.0f;\n data[i++] = 1.0f;\n data[i++] = 1.0f;\n data[i++] = logic.getNanoBots()[j]->getPos()[0] + d[1] - d[0];\n data[i++] = logic.getNanoBots()[j]->getPos()[1] - d[0] - d[1];\n data[i++] = 0.0f;\n data[i++] = 1.0f;\n data[i++] = 1.0f;\n data[i++] = logic.getNanoBots()[j]->getPos()[0] - d[1] - d[0];\n data[i++] = logic.getNanoBots()[j]->getPos()[1] + d[0] - d[1];\n data[i++] = 1.0f;\n data[i++] = 0.0f;\n data[i++] = 1.0f;\n }\n glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);\n glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);\n delete [] data;\n setOffsetAndScale(worldRenderContext.program);\n glBindFramebuffer(GL_FRAMEBUFFER, worldRenderTexture.framebuffer);\n \/\/ glClearColor(0.1f, 0.1f, 0.1f, 0.0f);\n \/\/ glClear(GL_COLOR_BUFFER_BIT);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND);\n glDrawArrays(GL_TRIANGLES, 0, i \/ 5);\n glBindFramebuffer(GL_FRAMEBUFFER, 0);\n glDisable(GL_BLEND);\n}\n\nvoid Display::displayMouseSelection()\n{\n Bind<RenderContext> bind(worldRenderContext);\n glBindFramebuffer(GL_FRAMEBUFFER, worldRenderTexture.framebuffer);\n glClearColor(0.1f, 0.1f, 0.1f, 0.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n if (!Callback::leftPressed)\n return;\n float data[4 * 5 * 4];\n unsigned int i(0);\n\n for (unsigned int j(0); j < 4; j++)\n {\n Vect<2u, double> d(logic.getNanoBots()[j]->getSpeed().normalized() * 0.01);\n\n data[i++] = (j == 1 || j == 2) ? Callback::dragOrigin[0] : Callback::pos[0];\n data[i++] = (j <= 1) ? Callback::dragOrigin[1] : Callback::pos[1];\n std::cout << Callback::dragOrigin[0] << std::endl;\n data[i++] = 1.0f;\n data[i++] = 1.0f;\n data[i++] = 1.0f;\n }\n glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);\n glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);\n setOffsetAndScale(worldRenderContext.program);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND);\n glDrawArrays(GL_LINE_LOOP, 0, 4);\n glBindFramebuffer(GL_FRAMEBUFFER, 0);\n glDisable(GL_BLEND);\n}\n\nvoid Display::postProcess()\n{\n Bind<RenderContext> bind(postProcessContext);\n\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, lightRenderTexture.texture);\n glActiveTexture(GL_TEXTURE1);\n glBindTexture(GL_TEXTURE_2D, worldRenderTexture.texture);\n my_opengl::setUniform(0u, \"lights\", postProcessContext.program);\n my_opengl::setUniform(1u, \"world\", postProcessContext.program);\n my_opengl::setUniform(Vect<2u, float>{1.0f, 1.0f} \/ Vect<2u, float>(size), \"step\", postProcessContext.program);\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n}\n\nvoid Display::render()\n{\n \/\/ lights[0].center += {-0.01, 0.01};\n \/\/ lights[0].center[0] -= 0.01;\n renderLights();\n displayMouseSelection();\n displayBots();\n \/\/ TODO : good idea ?\n postProcess();\n fpsCounter.tick();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include \"files.hpp\"\n#include \"vfs.hpp\"\n\nnamespace MgCore\n{\n\tstd::string read_file(std::string filename)\n {\n std::ifstream in(filename, std::ios::in | std::ios_base::ate);\n if (in) {\n std::string contents;\n contents.resize(in.tellg());\n in.seekg(0, std::ios::beg);\n in.read(&contents[0], contents.size());\n in.close();\n return contents;\n } else {\n return \"\";\n }\n }\n\n\tstd::string vfs_read_file(std::string filename)\n\t{\n\t\tttvfs::File *vf = VFS.GetFile( filename.c_str() );\n\n\t\tif ( vf && vf->open(\"r\") ) {\n\t\t\tstd::string contents;\n\t\t\tchar buff[vf->size()];\n\t\t\tsize_t len = vf->read(buff, sizeof(buff));\n\t\t\tvf->close();\n\t\t\tcontents = buff;\n\t\t\treturn contents;\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n<commit_msg>Simplified vfs_read_file.<commit_after>#include <fstream>\n#include \"files.hpp\"\n#include \"vfs.hpp\"\n\nnamespace MgCore\n{\n\tstd::string read_file(std::string filename)\n {\n std::ifstream in(filename, std::ios::in | std::ios_base::ate);\n if (in) {\n std::string contents;\n contents.resize(in.tellg());\n in.seekg(0, std::ios::beg);\n in.read(&contents[0], contents.size());\n in.close();\n return contents;\n } else {\n \treturn \"\";\n\t\t}\n\t}\n\n\tstd::string vfs_read_file(std::string filename)\n\t{\n\t\tttvfs::File *vf = VFS.GetFile( filename.c_str() );\n\n\t\tif ( vf && vf->open(\"r\") ) {\n\t\t\tstd::string contents;\n\t\t\tcontents.resize( vf->size() );\n\t\t\tvf->read(&contents[0], contents.size());\n\t\t\tvf->close();\n\t\t\treturn contents;\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: gcach_vdev.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hdu $ $Date: 2001-02-15 16:08:32 $\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#include <glyphcache.hxx>\n\n\/\/ -----------------------------------------------------------------------\n\nclass VirtDevServerFont : public ServerFont\n{\npublic:\n virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;\n virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;\n virtual bool GetGlyphOutline( int nGlyphIndex, PolyPolygon& ) const;\n\nprotected:\nfriend GlyphCache;\n static long FetchFontList( ImplDevFontList* );\n static void ClearFontList();\n\n static VirtDevServerFont* CreateFont( const ImplFontSelectData& );\n virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;\n virtual ULONG GetKernPairs( ImplKernPairData** ) const;\n\n virtual int GetGlyphIndex( sal_Unicode ) const;\n virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const;\n\nprivate:\n VirtDevServerFont( const ImplFontSelectData& );\n};\n\n\/\/ -----------------------------------------------------------------------\n<commit_msg>add GetAntialiasAdvice() and reformatting<commit_after>\/*************************************************************************\n *\n * $RCSfile: gcach_vdev.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hdu $ $Date: 2001-03-30 12:20:56 $\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#include <glyphcache.hxx>\n\n\/\/ -----------------------------------------------------------------------\n\nclass VirtDevServerFont : public ServerFont\n{\npublic:\n virtual bool GetAntialiasAdvice( void ) const;\n virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;\n virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;\n virtual bool GetGlyphOutline( int nGlyphIndex, PolyPolygon& ) const;\n\nprotected:\nfriend GlyphCache;\n static long FetchFontList( ImplDevFontList* );\n static void ClearFontList();\n\n static VirtDevServerFont* CreateFont( const ImplFontSelectData& );\n virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;\n virtual ULONG GetKernPairs( ImplKernPairData** ) const;\n\n virtual int GetGlyphIndex( sal_Unicode ) const;\n virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const;\n\nprivate:\n VirtDevServerFont( const ImplFontSelectData& );\n};\n\n\/\/ -----------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/\/====== Copyright (c) 2012, Valve Corporation, 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 met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/ Redistributions in binary form must reproduce the above copyright notice, \n\/\/ this list of conditions and the following disclaimer in the documentation \n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \n\/\/ THE POSSIBILITY OF SUCH DAMAGE.\n\/\/===========================================================================\/\/\n\n#include \"demofiledump.h\"\n\n\/\/ these settings cause it to output nothing\nbool g_bDumpGameEvents = false;\nbool g_bSupressFootstepEvents = true;\nbool g_bShowExtraPlayerInfoInGameEvents = false;\nbool g_bDumpDeaths = false;\nbool g_bSupressWarmupDeaths = true;\nbool g_bDumpStringTables = false;\nbool g_bDumpDataTables = false;\nbool g_bDumpPacketEntities = false;\nbool g_bDumpNetMessages = false;\n\nint main( int argc, char *argv[] )\n{\n\tCDemoFileDump DemoFileDump;\n\n\tif ( argc <= 1 )\n\t{\n\t\tprintf( \"demoinfogo filename.dem\\n\" );\n\t\tprintf( \"optional arguments:\\n\" \\\n\t\t\t\t\" -gameevents Dump out game events.\\n\" \\\n\t\t\t\t\" -nofootsteps Skip footstep events when dumping out game events.\\n\" \\\n\t\t\t\t\" Should be after -gameevents.\\n\" \\\n\t\t\t\t\" -extrainfo Show extra player info when dumping out game events.\\n\" \\\n\t\t\t\t\" Should be after -gameevents.\\n\" \\\n\t\t\t\t\" -deathscsv Dump out player death info in CSV form.\\n\" \\\n\t\t\t\t\" -nowarmup Skip deaths during warm up when dumping player deaths.\\n\" \\\n\t\t\t\t\" Should be after -deaths.\\n\" \\\n\t\t\t\t\" -stringtables Dump string tables.\\n\" \\\n\t\t\t\t\" -datatables Dump data tables. (send tables)\\n\" \\\n\t\t\t\t\" -packetentites Dump Packet Entities messages.\\n\" \\\n\t\t\t\t\" -netmessages Dump net messages that are not one of the above.\\n\" \\\n\t\t\t\t\"Note: by default everything is dumped out.\\n\" );\n\t\texit( 0 );\n\t}\n\n\tint nFileArgument = 1;\n\tif ( argc > 2 )\n\t{\n\t\tfor ( int i = 1; i < argc; i++ )\n\t\t{\n\t\t\t\/\/ arguments start with - or \/\n\t\t\tif ( argv[i][0] == '-' || argv[i][0] == '\/' )\n\t\t\t{\n\t\t\t\tif ( strcasecmp( &argv[i][1], \"gameevents\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpGameEvents = true;\n\t\t\t\t\tg_bSupressFootstepEvents = false;\n\t\t\t\t\tg_bShowExtraPlayerInfoInGameEvents = false;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"nofootsteps\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bSupressFootstepEvents = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"extrainfo\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bShowExtraPlayerInfoInGameEvents = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"deathscsv\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpDeaths = true;\n\t\t\t\t\tg_bSupressWarmupDeaths = false;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"nowarmup\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bSupressWarmupDeaths = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"stringtables\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpStringTables = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"datatables\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpDataTables = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"packetentities\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpPacketEntities = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"netmessages\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpNetMessages = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnFileArgument = i;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ default is to dump out everything\n\t\tg_bDumpGameEvents = true;\n\t\tg_bSupressFootstepEvents = false;\n\t\tg_bShowExtraPlayerInfoInGameEvents = true;\n\t\tg_bDumpDeaths = true;\n\t\tg_bSupressWarmupDeaths = false;\n\t\tg_bDumpStringTables = true;\n\t\tg_bDumpDataTables = true;\n\t\tg_bDumpPacketEntities = true;\n\t\tg_bDumpNetMessages = true;\n\t}\n\n\tif( DemoFileDump.Open( argv[ nFileArgument ] ) )\n\t{\n\t\tDemoFileDump.DoDump();\n\t}\n\n\treturn 1;\n}\n<commit_msg>Don't always return 1. Fixes #21<commit_after>\/\/====== Copyright (c) 2012, Valve Corporation, 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 met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/ Redistributions in binary form must reproduce the above copyright notice, \n\/\/ this list of conditions and the following disclaimer in the documentation \n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \n\/\/ THE POSSIBILITY OF SUCH DAMAGE.\n\/\/===========================================================================\/\/\n\n#include \"demofiledump.h\"\n\n\/\/ these settings cause it to output nothing\nbool g_bDumpGameEvents = false;\nbool g_bSupressFootstepEvents = true;\nbool g_bShowExtraPlayerInfoInGameEvents = false;\nbool g_bDumpDeaths = false;\nbool g_bSupressWarmupDeaths = true;\nbool g_bDumpStringTables = false;\nbool g_bDumpDataTables = false;\nbool g_bDumpPacketEntities = false;\nbool g_bDumpNetMessages = false;\n\nint main( int argc, char *argv[] )\n{\n\tCDemoFileDump DemoFileDump;\n\n\tif ( argc <= 1 )\n\t{\n\t\tprintf( \"demoinfogo filename.dem\\n\" );\n\t\tprintf( \"optional arguments:\\n\" \\\n\t\t\t\t\" -gameevents Dump out game events.\\n\" \\\n\t\t\t\t\" -nofootsteps Skip footstep events when dumping out game events.\\n\" \\\n\t\t\t\t\" Should be after -gameevents.\\n\" \\\n\t\t\t\t\" -extrainfo Show extra player info when dumping out game events.\\n\" \\\n\t\t\t\t\" Should be after -gameevents.\\n\" \\\n\t\t\t\t\" -deathscsv Dump out player death info in CSV form.\\n\" \\\n\t\t\t\t\" -nowarmup Skip deaths during warm up when dumping player deaths.\\n\" \\\n\t\t\t\t\" Should be after -deaths.\\n\" \\\n\t\t\t\t\" -stringtables Dump string tables.\\n\" \\\n\t\t\t\t\" -datatables Dump data tables. (send tables)\\n\" \\\n\t\t\t\t\" -packetentites Dump Packet Entities messages.\\n\" \\\n\t\t\t\t\" -netmessages Dump net messages that are not one of the above.\\n\" \\\n\t\t\t\t\"Note: by default everything is dumped out.\\n\" );\n\t\texit( 0 );\n\t}\n\n\tint nFileArgument = 1;\n\tif ( argc > 2 )\n\t{\n\t\tfor ( int i = 1; i < argc; i++ )\n\t\t{\n\t\t\t\/\/ arguments start with - or \/\n\t\t\tif ( argv[i][0] == '-' || argv[i][0] == '\/' )\n\t\t\t{\n\t\t\t\tif ( strcasecmp( &argv[i][1], \"gameevents\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpGameEvents = true;\n\t\t\t\t\tg_bSupressFootstepEvents = false;\n\t\t\t\t\tg_bShowExtraPlayerInfoInGameEvents = false;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"nofootsteps\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bSupressFootstepEvents = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"extrainfo\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bShowExtraPlayerInfoInGameEvents = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"deathscsv\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpDeaths = true;\n\t\t\t\t\tg_bSupressWarmupDeaths = false;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"nowarmup\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bSupressWarmupDeaths = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"stringtables\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpStringTables = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"datatables\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpDataTables = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"packetentities\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpPacketEntities = true;\n\t\t\t\t}\n\t\t\t\telse if ( strcasecmp( &argv[i][1], \"netmessages\" ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tg_bDumpNetMessages = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnFileArgument = i;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ default is to dump out everything\n\t\tg_bDumpGameEvents = true;\n\t\tg_bSupressFootstepEvents = false;\n\t\tg_bShowExtraPlayerInfoInGameEvents = true;\n\t\tg_bDumpDeaths = true;\n\t\tg_bSupressWarmupDeaths = false;\n\t\tg_bDumpStringTables = true;\n\t\tg_bDumpDataTables = true;\n\t\tg_bDumpPacketEntities = true;\n\t\tg_bDumpNetMessages = true;\n\t}\n\n\tif( DemoFileDump.Open( argv[ nFileArgument ] ) )\n\t{\n\t\tDemoFileDump.DoDump();\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\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#include <folly\/experimental\/coro\/detail\/Malloc.h>\n\n#include <folly\/BenchmarkUtil.h>\n\n#include <new>\n\nextern \"C\" {\n\nFOLLY_NOINLINE\nvoid* folly_coro_async_malloc(std::size_t size) {\n void* p = ::operator new(size);\n\n \/\/ Add this after the call to prevent the compiler from\n \/\/ turning the call to operator new() into a tailcall.\n folly::doNotOptimizeAway(p);\n\n return p;\n}\n\nFOLLY_NOINLINE\nvoid folly_coro_async_free(void* ptr, std::size_t size) {\n#if __cpp_sized_deallocation >= 201309\n ::operator delete(ptr, size);\n#else\n \/\/ sized delete is not available on iOS before 10.0\n (void)size;\n ::operator delete(ptr);\n#endif\n\n \/\/ Add this after the call to prevent the compiler from\n \/\/ turning the call to operator delete() into a tailcall.\n folly::doNotOptimizeAway(size);\n}\n} \/\/ extern \"C\"\n<commit_msg>let coro malloc\/free use wrappers<commit_after>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\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#include <folly\/experimental\/coro\/detail\/Malloc.h>\n\n#include <folly\/BenchmarkUtil.h>\n#include <folly\/lang\/New.h>\n\nextern \"C\" {\n\nFOLLY_NOINLINE\nvoid* folly_coro_async_malloc(std::size_t size) {\n auto p = folly::operator_new(size);\n\n \/\/ Add this after the call to prevent the compiler from\n \/\/ turning the call to operator new() into a tailcall.\n folly::doNotOptimizeAway(p);\n\n return p;\n}\n\nFOLLY_NOINLINE\nvoid folly_coro_async_free(void* ptr, std::size_t size) {\n folly::operator_delete(ptr, size);\n\n \/\/ Add this after the call to prevent the compiler from\n \/\/ turning the call to operator delete() into a tailcall.\n folly::doNotOptimizeAway(size);\n}\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/*\nMIT License\n\nCopyright(c) 2017 Jerzy Kasenberg\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files(the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n#include \"SpiFlashAnalyzerResults.h\"\n#include <AnalyzerHelpers.h>\n#include \"SpiFlashAnalyzer.h\"\n#include \"SpiFlashAnalyzerSettings.h\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include \"SpiFlash.h\"\n\nSpiFlashAnalyzerResults::SpiFlashAnalyzerResults(SpiFlashAnalyzer* analyzer, SpiFlashAnalyzerSettings* settings)\n\t: AnalyzerResults(),\n\tmSettings(settings),\n\tmAnalyzer(analyzer)\n{\n}\n\nSpiFlashAnalyzerResults::~SpiFlashAnalyzerResults()\n{\n}\n\nstatic int AddressBits(U32 addr)\n{\n\tif (addr < 0x100)\n\t\treturn 8;\n\telse if (addr < 0x10000)\n\t\treturn 16;\n\telse if (addr < 0x1000000)\n\t\treturn 24;\n\telse\n\t\treturn 32;\n}\n\nstatic std::string RegisterString(RegisterData *reg, U64 val, bool full = false)\n{\n\tstd::stringstream s;\n\n\tfor (size_t i = 0; i < reg->GetBitfieldCount(); ++i)\n\t{\n\t\tconst BitField &bitField = reg->at(i);\n\t\tU32 bitsValue = bitField.GetValue(val);\n\t\tif (bitsValue || full)\n\t\t\ts << (s.tellp() ? \" \" : \"\") << bitField.mFieldName << \"=\" << std::hex << bitsValue;\n\t}\n\treturn s.str();\n}\n\nvoid SpiFlashAnalyzerResults::AddRegisterResult(RegisterData *reg, U64 val, DisplayBase display_base)\n{\n\tchar number_str[128];\n\tAnalyzerHelpers::GetNumberString(val, display_base, 8, number_str, 128);\n\tAddResultString(number_str);\n\t\/\/ There is register assigned\n\tif (reg)\n\t{\n\t\tstd::string s = RegisterString(reg, val);\n\t\tif (s.size())\n\t\t\tAddResult(s);\n\t\tAddResult(RegisterString(reg, val, true));\n\t}\n}\n\nvoid SpiFlashAnalyzerResults::GenerateBubbleText(U64 frame_index, Channel& channel, DisplayBase display_base)\n{\n\tClearResultStrings();\n\tFrame frame = GetFrame(frame_index);\n\n\tchar number_str[128];\n\tchar number_str2[10];\n\tstd::stringstream fulls, shorts;\n\n\tif (frame.mType == FT_CMD && channel == mSettings->mChipSelect)\n\t{\n\t\tSpiCmdData *cmd = reinterpret_cast<SpiCmdData *>(frame.mData2);\n\t\tif (U64(cmd) > 0x100)\n\t\t{\n\t\t\tsize_t i;\n\t\t\tconst char *s[4] = { 0 };\n\t\t\tfor (i = 0; i < cmd->mNames.size(); ++i)\n\t\t\t\tAddResultString(cmd->mNames[i].c_str());\n\t\t\tif (cmd->mHasAddr)\n\t\t\t{\n\t\t\t\tU32 addr = U32(frame.mData1 >> 24);\n\t\t\t\ts[0] = \" A=\";\n\t\t\t\ts[1] = number_str;\n\t\t\t\tAnalyzerHelpers::GetNumberString(addr, Hexadecimal, AddressBits(addr), number_str, 128);\n\t\t\t}\n\t\t\tif (cmd->mCmdOp == OP_DATA_READ || cmd->mCmdOp == OP_DATA_WRITE)\n\t\t\t{\n\t\t\t\ts[2] = \" bytes:\";\n\t\t\t\ts[3] = number_str2;\n\t\t\t\tAnalyzerHelpers::GetNumberString(frame.mData1 & 0xFFFFFF, Decimal, 24, number_str2, 128);\n\t\t\t}\n\t\t\t\/\/ Add longest name with address and byte count if present\n\t\t\tAddResultString(cmd->mNames[i - 1].c_str(), s[0], s[1], s[2], s[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tAddResultString(\"??\");\n\t\t\tif (frame.mData2 != 0x100)\n\t\t\t{\n\t\t\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\t\t\tAddResultString(\"?? CMD=\", number_str);\n\t\t\t}\n\t\t}\n\t}\n\telse if (frame.mType == FT_CMD_BYTE && channel == mSettings->mMosi)\n\t{\n\t\tSpiCmdData *cmd = reinterpret_cast<SpiCmdData *>(frame.mData2);\n\t\tif (frame.mData2 == 0x100)\n\t\t\tAddResultString(\"?\"); \/\/ Not enough bits\n\t\telse if (frame.mData2 < 0x100)\n\t\t{\n\t\t\t\/\/ Normal byte and CMD=0xXX\n\t\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\t\tAddResultString(number_str);\n\t\t\tAnalyzerHelpers::GetNumberString(frame.mData2, Hexadecimal, 8, number_str, 128);\n\t\t\tAddResultString(\"CMD=\", number_str);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsize_t i;\n\t\t\tU8 b = cmd->GetCode();\n\t\t\tAnalyzerHelpers::GetNumberString(b, display_base, 8, number_str, 128);\n\t\t\tAddResultString(number_str);\n\t\t\tAnalyzerHelpers::GetNumberString(b, Hexadecimal, 8, number_str, 128);\n\t\t\tAddResultString(\"CMD=\", number_str);\n\t\t\tfor (i = 0; i < cmd->mNames.size(); ++i)\n\t\t\t\tAddResultString(cmd->mNames[i].c_str());\n\t\t\tAddResultString(cmd->mNames[i - 1].c_str(), \" CMD=\", number_str);\n\t\t}\n\t}\n\telse if (frame.mType == FT_OUT_ADDR24 && channel == mSettings->mMosi)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, Hexadecimal, AddressBits(U32(frame.mData1 >> 24)),\n\t\t\tnumber_str, 128);\n\t\tAddResultString(\"A\");\n\t\tAddResultString(number_str);\n\t\tAddResultString(\"A=\", number_str);\n\t}\n\telse if ((frame.mType == FT_OUT_BYTE || frame.mType == FT_IN_OUT) && channel == mSettings->mMosi)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, display_base, 8, number_str, 128);\n\t\tAddResultString(number_str);\n\t}\n\telse if (frame.mType == FT_IN_REG && channel == mSettings->mMiso)\n\t{\n\t\tAddRegisterResult(reinterpret_cast<RegisterData *>(frame.mData1), frame.mData2, display_base);\n\t}\n\telse if (frame.mType == FT_OUT_REG && channel == mSettings->mMosi)\n\t{\n\t\tAddRegisterResult(reinterpret_cast<RegisterData *>(frame.mData2), frame.mData1, display_base);\n\t}\n\telse if ((frame.mType == FT_M) && channel == mSettings->mMosi)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, display_base, 8, number_str, 128);\n\t\tAddResultString(\"M\");\n\t\tAddResultString(number_str);\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, Hexadecimal, 8, number_str, 128);\n\t\tAddResultString(\"M=\", number_str);\n\t}\n\telse if ((frame.mType == FT_IN_BYTE || frame.mType == FT_IN_OUT) && channel == mSettings->mMiso)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\tAddResultString(number_str);\n\t}\n\telse if (frame.mType == FT_DUMMY && channel == mSettings->mMosi)\n\t{\n\t\tAddResultString(\"x\");\n\t\tAddResultString(\"Dummy\");\n\t}\n}\n\nvoid SpiFlashAnalyzerResults::GenerateExportFile(const char* file, DisplayBase display_base, U32 export_type_user_id)\n{\n\tstd::ofstream file_stream(file, std::ios::out);\n\n\tU64 trigger_sample = mAnalyzer->GetTriggerSample();\n\tU32 sample_rate = mAnalyzer->GetSampleRate();\n\n\tfile_stream << \"Time [s],Value\" << std::endl;\n\n\tU64 num_frames = GetNumFrames();\n\tfor (U32 i = 0; i < num_frames; i++)\n\t{\n\t\tFrame frame = GetFrame(i);\n\n\t\tchar time_str[128];\n\t\tAnalyzerHelpers::GetTimeString(frame.mStartingSampleInclusive, trigger_sample, sample_rate, time_str, 128);\n\n\t\tchar number_str[128];\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, display_base, 8, number_str, 128);\n\n\t\tfile_stream << time_str << \",\" << number_str << std::endl;\n\n\t\tif (UpdateExportProgressAndCheckForCancel(i, num_frames) == true)\n\t\t{\n\t\t\tfile_stream.close();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tfile_stream.close();\n}\n\nvoid SpiFlashAnalyzerResults::GenerateFrameTabularText(U64 frame_index, DisplayBase display_base)\n{\n\tClearTabularText();\n\tFrame frame = GetFrame(frame_index);\n\n\tchar number_str[128];\n\tchar number_str2[10];\n\tif (frame.mType == FT_CMD)\n\t{\n\t\tSpiCmdData *cmd = reinterpret_cast<SpiCmdData *>(frame.mData2);\n\t\tif (U64(cmd) > 0x100)\n\t\t{\n\t\t\tconst char *s[4] = { 0 };\n\t\t\tif (cmd->mHasAddr)\n\t\t\t{\n\t\t\t\tU32 addr = U32(frame.mData1 >> 24);\n\t\t\t\ts[0] = \" A=\";\n\t\t\t\ts[1] = number_str;\n\t\t\t\tAnalyzerHelpers::GetNumberString(addr, Hexadecimal, AddressBits(addr), number_str, 128);\n\t\t\t}\n\t\t\tif (cmd->mCmdOp == OP_DATA_READ || cmd->mCmdOp == OP_DATA_WRITE)\n\t\t\t{\n\t\t\t\ts[2] = \" bytes:\";\n\t\t\t\ts[3] = number_str2;\n\t\t\t\tAnalyzerHelpers::GetNumberString(frame.mData1 & 0xFFFFFF, Decimal, 24, number_str2, 128);\n\t\t\t}\n\t\t\t\/\/ Add longest name with address and byte count if present\n\t\t\tAddTabularText(cmd->mNames.back().c_str(), s[0], s[1], s[2], s[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (frame.mData2 != 0x100)\n\t\t\t{\n\t\t\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\t\t\tAddTabularText(\"?? CMD=\", number_str);\n\t\t\t}\n\t\t}\n\t}\n\telse if (frame.mType == FT_OUT_ADDR24)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, Hexadecimal, AddressBits(U32(frame.mData1 >> 24)),\n\t\t\tnumber_str, 128);\n\t\tAddTabularText(\"A=\", number_str);\n\t}\n\telse if ((frame.mType == FT_OUT_BYTE || frame.mType == FT_IN_OUT))\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, display_base, 8, number_str, 128);\n\t\tAddTabularText(number_str);\n}\n\telse if ((frame.mType == FT_M))\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, Hexadecimal, 8, number_str, 128);\n\t\tAddTabularText(\"M=\", number_str);\n\t}\n\telse if ((frame.mType == FT_IN_BYTE || frame.mType == FT_IN_OUT))\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\tAddTabularText(number_str);\n\t}\n\telse if (frame.mType == FT_DUMMY)\n\t{\n\t\tAddTabularText(\"Dummy\");\n\t}\n}\n\nvoid SpiFlashAnalyzerResults::GeneratePacketTabularText(U64 packet_id, DisplayBase display_base)\n{\n\tClearResultStrings();\n\tAddResultString(\"not supported\");\n}\n\nvoid SpiFlashAnalyzerResults::GenerateTransactionTabularText(U64 transaction_id, DisplayBase display_base)\n{\n\tClearResultStrings();\n\tAddResultString(\"not supported\");\n}\n<commit_msg>Replace std::endl with '\\n' in export method<commit_after>\/*\nMIT License\n\nCopyright(c) 2017 Jerzy Kasenberg\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files(the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n#include \"SpiFlashAnalyzerResults.h\"\n#include <AnalyzerHelpers.h>\n#include \"SpiFlashAnalyzer.h\"\n#include \"SpiFlashAnalyzerSettings.h\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include \"SpiFlash.h\"\n\nSpiFlashAnalyzerResults::SpiFlashAnalyzerResults(SpiFlashAnalyzer* analyzer, SpiFlashAnalyzerSettings* settings)\n\t: AnalyzerResults(),\n\tmSettings(settings),\n\tmAnalyzer(analyzer)\n{\n}\n\nSpiFlashAnalyzerResults::~SpiFlashAnalyzerResults()\n{\n}\n\nstatic int AddressBits(U32 addr)\n{\n\tif (addr < 0x100)\n\t\treturn 8;\n\telse if (addr < 0x10000)\n\t\treturn 16;\n\telse if (addr < 0x1000000)\n\t\treturn 24;\n\telse\n\t\treturn 32;\n}\n\nstatic std::string RegisterString(RegisterData *reg, U64 val, bool full = false)\n{\n\tstd::stringstream s;\n\n\tfor (size_t i = 0; i < reg->GetBitfieldCount(); ++i)\n\t{\n\t\tconst BitField &bitField = reg->at(i);\n\t\tU32 bitsValue = bitField.GetValue(val);\n\t\tif (bitsValue || full)\n\t\t\ts << (s.tellp() ? \" \" : \"\") << bitField.mFieldName << \"=\" << std::hex << bitsValue;\n\t}\n\treturn s.str();\n}\n\nvoid SpiFlashAnalyzerResults::AddRegisterResult(RegisterData *reg, U64 val, DisplayBase display_base)\n{\n\tchar number_str[128];\n\tAnalyzerHelpers::GetNumberString(val, display_base, 8, number_str, 128);\n\tAddResultString(number_str);\n\t\/\/ There is register assigned\n\tif (reg)\n\t{\n\t\tstd::string s = RegisterString(reg, val);\n\t\tif (s.size())\n\t\t\tAddResult(s);\n\t\tAddResult(RegisterString(reg, val, true));\n\t}\n}\n\nvoid SpiFlashAnalyzerResults::GenerateBubbleText(U64 frame_index, Channel& channel, DisplayBase display_base)\n{\n\tClearResultStrings();\n\tFrame frame = GetFrame(frame_index);\n\n\tchar number_str[128];\n\tchar number_str2[10];\n\tstd::stringstream fulls, shorts;\n\n\tif (frame.mType == FT_CMD && channel == mSettings->mChipSelect)\n\t{\n\t\tSpiCmdData *cmd = reinterpret_cast<SpiCmdData *>(frame.mData2);\n\t\tif (U64(cmd) > 0x100)\n\t\t{\n\t\t\tsize_t i;\n\t\t\tconst char *s[4] = { 0 };\n\t\t\tfor (i = 0; i < cmd->mNames.size(); ++i)\n\t\t\t\tAddResultString(cmd->mNames[i].c_str());\n\t\t\tif (cmd->mHasAddr)\n\t\t\t{\n\t\t\t\tU32 addr = U32(frame.mData1 >> 24);\n\t\t\t\ts[0] = \" A=\";\n\t\t\t\ts[1] = number_str;\n\t\t\t\tAnalyzerHelpers::GetNumberString(addr, Hexadecimal, AddressBits(addr), number_str, 128);\n\t\t\t}\n\t\t\tif (cmd->mCmdOp == OP_DATA_READ || cmd->mCmdOp == OP_DATA_WRITE)\n\t\t\t{\n\t\t\t\ts[2] = \" bytes:\";\n\t\t\t\ts[3] = number_str2;\n\t\t\t\tAnalyzerHelpers::GetNumberString(frame.mData1 & 0xFFFFFF, Decimal, 24, number_str2, 128);\n\t\t\t}\n\t\t\t\/\/ Add longest name with address and byte count if present\n\t\t\tAddResultString(cmd->mNames[i - 1].c_str(), s[0], s[1], s[2], s[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tAddResultString(\"??\");\n\t\t\tif (frame.mData2 != 0x100)\n\t\t\t{\n\t\t\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\t\t\tAddResultString(\"?? CMD=\", number_str);\n\t\t\t}\n\t\t}\n\t}\n\telse if (frame.mType == FT_CMD_BYTE && channel == mSettings->mMosi)\n\t{\n\t\tSpiCmdData *cmd = reinterpret_cast<SpiCmdData *>(frame.mData2);\n\t\tif (frame.mData2 == 0x100)\n\t\t\tAddResultString(\"?\"); \/\/ Not enough bits\n\t\telse if (frame.mData2 < 0x100)\n\t\t{\n\t\t\t\/\/ Normal byte and CMD=0xXX\n\t\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\t\tAddResultString(number_str);\n\t\t\tAnalyzerHelpers::GetNumberString(frame.mData2, Hexadecimal, 8, number_str, 128);\n\t\t\tAddResultString(\"CMD=\", number_str);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsize_t i;\n\t\t\tU8 b = cmd->GetCode();\n\t\t\tAnalyzerHelpers::GetNumberString(b, display_base, 8, number_str, 128);\n\t\t\tAddResultString(number_str);\n\t\t\tAnalyzerHelpers::GetNumberString(b, Hexadecimal, 8, number_str, 128);\n\t\t\tAddResultString(\"CMD=\", number_str);\n\t\t\tfor (i = 0; i < cmd->mNames.size(); ++i)\n\t\t\t\tAddResultString(cmd->mNames[i].c_str());\n\t\t\tAddResultString(cmd->mNames[i - 1].c_str(), \" CMD=\", number_str);\n\t\t}\n\t}\n\telse if (frame.mType == FT_OUT_ADDR24 && channel == mSettings->mMosi)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, Hexadecimal, AddressBits(U32(frame.mData1 >> 24)),\n\t\t\tnumber_str, 128);\n\t\tAddResultString(\"A\");\n\t\tAddResultString(number_str);\n\t\tAddResultString(\"A=\", number_str);\n\t}\n\telse if ((frame.mType == FT_OUT_BYTE || frame.mType == FT_IN_OUT) && channel == mSettings->mMosi)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, display_base, 8, number_str, 128);\n\t\tAddResultString(number_str);\n\t}\n\telse if (frame.mType == FT_IN_REG && channel == mSettings->mMiso)\n\t{\n\t\tAddRegisterResult(reinterpret_cast<RegisterData *>(frame.mData1), frame.mData2, display_base);\n\t}\n\telse if (frame.mType == FT_OUT_REG && channel == mSettings->mMosi)\n\t{\n\t\tAddRegisterResult(reinterpret_cast<RegisterData *>(frame.mData2), frame.mData1, display_base);\n\t}\n\telse if ((frame.mType == FT_M) && channel == mSettings->mMosi)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, display_base, 8, number_str, 128);\n\t\tAddResultString(\"M\");\n\t\tAddResultString(number_str);\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, Hexadecimal, 8, number_str, 128);\n\t\tAddResultString(\"M=\", number_str);\n\t}\n\telse if ((frame.mType == FT_IN_BYTE || frame.mType == FT_IN_OUT) && channel == mSettings->mMiso)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\tAddResultString(number_str);\n\t}\n\telse if (frame.mType == FT_DUMMY && channel == mSettings->mMosi)\n\t{\n\t\tAddResultString(\"x\");\n\t\tAddResultString(\"Dummy\");\n\t}\n}\n\nvoid SpiFlashAnalyzerResults::GenerateExportFile(const char* file, DisplayBase display_base, U32 export_type_user_id)\n{\n\tstd::ofstream file_stream(file, std::ios::out);\n\n\tU64 trigger_sample = mAnalyzer->GetTriggerSample();\n\tU32 sample_rate = mAnalyzer->GetSampleRate();\n\n\tfile_stream << \"Time [s],Value\" << '\\n';\n\n\tU64 num_frames = GetNumFrames();\n\tfor (U32 i = 0; i < num_frames; i++)\n\t{\n\t\tFrame frame = GetFrame(i);\n\n\t\tchar time_str[128];\n\t\tAnalyzerHelpers::GetTimeString(frame.mStartingSampleInclusive, trigger_sample, sample_rate, time_str, 128);\n\n\t\tchar number_str[128];\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, display_base, 8, number_str, 128);\n\n\t\tfile_stream << time_str << \",\" << number_str << '\\n';\n\n\t\tif (UpdateExportProgressAndCheckForCancel(i, num_frames) == true)\n\t\t{\n\t\t\tfile_stream.close();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tfile_stream.close();\n}\n\nvoid SpiFlashAnalyzerResults::GenerateFrameTabularText(U64 frame_index, DisplayBase display_base)\n{\n\tClearTabularText();\n\tFrame frame = GetFrame(frame_index);\n\n\tchar number_str[128];\n\tchar number_str2[10];\n\tif (frame.mType == FT_CMD)\n\t{\n\t\tSpiCmdData *cmd = reinterpret_cast<SpiCmdData *>(frame.mData2);\n\t\tif (U64(cmd) > 0x100)\n\t\t{\n\t\t\tconst char *s[4] = { 0 };\n\t\t\tif (cmd->mHasAddr)\n\t\t\t{\n\t\t\t\tU32 addr = U32(frame.mData1 >> 24);\n\t\t\t\ts[0] = \" A=\";\n\t\t\t\ts[1] = number_str;\n\t\t\t\tAnalyzerHelpers::GetNumberString(addr, Hexadecimal, AddressBits(addr), number_str, 128);\n\t\t\t}\n\t\t\tif (cmd->mCmdOp == OP_DATA_READ || cmd->mCmdOp == OP_DATA_WRITE)\n\t\t\t{\n\t\t\t\ts[2] = \" bytes:\";\n\t\t\t\ts[3] = number_str2;\n\t\t\t\tAnalyzerHelpers::GetNumberString(frame.mData1 & 0xFFFFFF, Decimal, 24, number_str2, 128);\n\t\t\t}\n\t\t\t\/\/ Add longest name with address and byte count if present\n\t\t\tAddTabularText(cmd->mNames.back().c_str(), s[0], s[1], s[2], s[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (frame.mData2 != 0x100)\n\t\t\t{\n\t\t\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\t\t\tAddTabularText(\"?? CMD=\", number_str);\n\t\t\t}\n\t\t}\n\t}\n\telse if (frame.mType == FT_OUT_ADDR24)\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, Hexadecimal, AddressBits(U32(frame.mData1 >> 24)),\n\t\t\tnumber_str, 128);\n\t\tAddTabularText(\"A=\", number_str);\n\t}\n\telse if ((frame.mType == FT_OUT_BYTE || frame.mType == FT_IN_OUT))\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, display_base, 8, number_str, 128);\n\t\tAddTabularText(number_str);\n}\n\telse if ((frame.mType == FT_M))\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData1, Hexadecimal, 8, number_str, 128);\n\t\tAddTabularText(\"M=\", number_str);\n\t}\n\telse if ((frame.mType == FT_IN_BYTE || frame.mType == FT_IN_OUT))\n\t{\n\t\tAnalyzerHelpers::GetNumberString(frame.mData2, display_base, 8, number_str, 128);\n\t\tAddTabularText(number_str);\n\t}\n\telse if (frame.mType == FT_DUMMY)\n\t{\n\t\tAddTabularText(\"Dummy\");\n\t}\n}\n\nvoid SpiFlashAnalyzerResults::GeneratePacketTabularText(U64 packet_id, DisplayBase display_base)\n{\n\tClearResultStrings();\n\tAddResultString(\"not supported\");\n}\n\nvoid SpiFlashAnalyzerResults::GenerateTransactionTabularText(U64 transaction_id, DisplayBase display_base)\n{\n\tClearResultStrings();\n\tAddResultString(\"not supported\");\n}\n<|endoftext|>"} {"text":"<commit_before>class Solution {\npublic: \n vector<vector<int> > G;\n vector<int> vis;\n \n bool dfs(int u){\n vis[u]=-1;\n \n for(int i=0; i<G[u].size(); i++){\n int v=G[u][i];\n \n if(vis[v]<0){\n return false;\n }else if(!vis[v] && !dfs(v)){\n return false;\n }\n }\n vis[u]=1;\n \n return true;\n }\n bool topo(int n){\n for(int u=0; u<n; u++){\n if(!vis[u]){\n if(!dfs(u)){\n return false;\n }\n }\n }\n return true;\n }\n \n bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {\n \/\/ transfer the prerequisites to adjacent list graph representation\n int n=prerequisites.size();\n vis.assign(numCourses,0);\n \n G.assign(numCourses,vector<int>(0));\n \n for(int i=0; i<n; i++){\n G[prerequisites[i].second].push_back(prerequisites[i].first);\n }\n \n return topo(numCourses);\n }\n};<commit_msg>add ok course schedule 2<commit_after>class Solution {\npublic:\n vector<vector<int> > G;\n vector<int> vis;\n vector<int> res;\n int t;\n \n bool dfs(int u){\n vis[u]=-1;\n \n for(int i=0; i<G[u].size(); i++){\n int v=G[u][i];\n \n if(vis[v]<0){\n return false;\n }else if(!vis[v] && !dfs(v)){\n return false;\n }\n }\n vis[u]=1;\n res[--t]=u;\n \n return true;\n }\n bool topo(int n){\n t=n;\n for(int u=0; u<n; u++){\n if(!vis[u]){\n if(!dfs(u)){\n return false;\n }\n }\n }\n return true;\n }\n vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {\n G.assign(numCourses,vector<int>(0));\n vis.assign(numCourses,0);\n res.assign(numCourses,0);\n \n int m=prerequisites.size();\n for(int i=0; i<m; i++){\n G[prerequisites[i].second].push_back(prerequisites[i].first);\n }\n \n if(topo(numCourses)){\n return res;\n }\n return vector<int>();\n }\n};<|endoftext|>"} {"text":"<commit_before>\/** \\file add_oa_urls.cc\n * \\brief Add additional urls for oa_access of items\n * \\author Johannes Riedl\n *\/\n\n\/*\n Copyright (C) 2018, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (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. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <memory>\n#include <unordered_map>\n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"JSON.h\"\n#include \"MARC.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname \\\n << \" doi_to_url_map.json marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid CreateDoiToUrlMap(const std::string &map_filename, std::unordered_map<std::string, std::string> * const doi_to_url) {\n std::string json_document;\n if (not FileUtil::ReadString(map_filename, &json_document))\n LOG_ERROR(\"Could not read in \" + map_filename);\n \n JSON::Parser json_parser(json_document);\n std::shared_ptr<JSON::JSONNode> entries;\n if (not json_parser.parse(&entries))\n LOG_ERROR(\"Could not properly parse \\\"\" + map_filename + \": \" + json_parser.getErrorMessage());\n \n std::shared_ptr<JSON::ArrayNode> entry_array(JSON::JSONNode::CastToArrayNodeOrDie(\"\", entries));\n for (const auto &entry : *entry_array) {\n const std::string doi(LookupString(\"\/doi\", entry));\n const std::string url(LookupString(\"\/best_oa_location\/url\", entry));\n if (not (doi.empty() or url.empty()))\n doi_to_url->emplace(doi, url);\n else\n LOG_ERROR(\"Either doi or url missing\");\n }\n} \n\n\nbool AlreadyHasIdenticalUrl(const MARC::Record &record, const std::string &url) {\n for (const auto &field : record.getTagRange(\"856\")) {\n if (field.hasSubfieldWithValue('u', url))\n return true; \n }\n return false;\n}\n\n\nvoid Augment856(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,\n const std::unordered_map<std::string, std::string> &doi_to_url)\n {\n while (MARC::Record record = marc_reader->read()) {\n for (const auto &field : record.getTagRange(\"024\")) {\n if (field.hasSubfieldWithValue('2', \"doi\")) {\n const std::string doi(field.getFirstSubfieldWithCode('a'));\n const auto doi_and_url(doi_to_url.find(doi));\n if (doi_and_url != doi_to_url.cend()) {\n const std::string url(doi_and_url->second);\n if (not AlreadyHasIdenticalUrl(record, url))\n record.insertField(\"856\", { { 'u', url }, { 'z', \"unpaywall\" } });\n }\n }\n }\n marc_writer->write(record);\n }\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 4)\n Usage();\n \n std::unordered_map<std::string, std::string> doi_to_url;\n CreateDoiToUrlMap(argv[1], &doi_to_url);\n std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[2]));\n std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[3]));\n Augment856(marc_reader.get(), marc_writer.get(), doi_to_url);\n\n return EXIT_SUCCESS;\n}\n\n<commit_msg>Moving brace<commit_after>\/** \\file add_oa_urls.cc\n * \\brief Add additional urls for oa_access of items\n * \\author Johannes Riedl\n *\/\n\n\/*\n Copyright (C) 2018, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (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. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <memory>\n#include <unordered_map>\n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"JSON.h\"\n#include \"MARC.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname \\\n << \" doi_to_url_map.json marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid CreateDoiToUrlMap(const std::string &map_filename, std::unordered_map<std::string, std::string> * const doi_to_url) {\n std::string json_document;\n if (not FileUtil::ReadString(map_filename, &json_document))\n LOG_ERROR(\"Could not read in \" + map_filename);\n \n JSON::Parser json_parser(json_document);\n std::shared_ptr<JSON::JSONNode> entries;\n if (not json_parser.parse(&entries))\n LOG_ERROR(\"Could not properly parse \\\"\" + map_filename + \": \" + json_parser.getErrorMessage());\n \n std::shared_ptr<JSON::ArrayNode> entry_array(JSON::JSONNode::CastToArrayNodeOrDie(\"\", entries));\n for (const auto &entry : *entry_array) {\n const std::string doi(LookupString(\"\/doi\", entry));\n const std::string url(LookupString(\"\/best_oa_location\/url\", entry));\n if (not (doi.empty() or url.empty()))\n doi_to_url->emplace(doi, url);\n else\n LOG_ERROR(\"Either doi or url missing\");\n }\n} \n\n\nbool AlreadyHasIdenticalUrl(const MARC::Record &record, const std::string &url) {\n for (const auto &field : record.getTagRange(\"856\")) {\n if (field.hasSubfieldWithValue('u', url))\n return true; \n }\n return false;\n}\n\n\nvoid Augment856(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,\n const std::unordered_map<std::string, std::string> &doi_to_url)\n{\n while (MARC::Record record = marc_reader->read()) {\n for (const auto &field : record.getTagRange(\"024\")) {\n if (field.hasSubfieldWithValue('2', \"doi\")) {\n const std::string doi(field.getFirstSubfieldWithCode('a'));\n const auto doi_and_url(doi_to_url.find(doi));\n if (doi_and_url != doi_to_url.cend()) {\n const std::string url(doi_and_url->second);\n if (not AlreadyHasIdenticalUrl(record, url))\n record.insertField(\"856\", { { 'u', url }, { 'z', \"unpaywall\" } });\n }\n }\n }\n marc_writer->write(record);\n }\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 4)\n Usage();\n \n std::unordered_map<std::string, std::string> doi_to_url;\n CreateDoiToUrlMap(argv[1], &doi_to_url);\n std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[2]));\n std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[3]));\n Augment856(marc_reader.get(), marc_writer.get(), doi_to_url);\n\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"stdsneezy.h\"\n#include \"database.h\"\n#include \"shop.h\"\n#include \"shopowned.h\"\n\n\/\/ 1 loan per account\n\n\/\/ collection:\n\/\/ transfer from bank account?\n\/\/ transfer from shops\/corp\n\/\/ send out repo mobs\n\n\/\/ setrates <default> <prime> <term> default\n\/\/ profit_buy = defaulting rate, profit_sell=prime rate\n\n\/\/ setrates <X> <Y> <term> loanrate\n\/\/ X * (lvl ** Y)\n\ndouble getPenalty(unsigned int shop_nr, const sstring &name)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"select profit_buy from shopownedplayer where player='%s' and shop_nr=%i\", name.c_str(), shop_nr);\n \n if(db.fetchRow())\n return convertTo<double>(db[\"profit_buy\"]);\n else {\n db.query(\"select profit_buy from shopowned where shop_nr=%i\", shop_nr);\n\n if(db.fetchRow())\n return convertTo<double>(db[\"profit_buy\"]);\n }\n\n return shop_index[shop_nr].profit_buy;\n}\n\ndouble getRate(unsigned int shop_nr, const sstring &name)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"select profit_sell from shopownedplayer where player='%s' and shop_nr=%i\", name.c_str(), shop_nr);\n \n if(db.fetchRow())\n return convertTo<double>(db[\"profit_sell\"]);\n else {\n db.query(\"select profit_sell from shopowned where shop_nr=%i\", shop_nr);\n\n if(db.fetchRow())\n return convertTo<double>(db[\"profit_sell\"]);\n }\n\n return shop_index[shop_nr].profit_sell;\n}\n\nint getTerm(unsigned int shop_nr, const sstring &name)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"select max_num from shopownedplayer where player='%s' and shop_nr=%i\", name.c_str(), shop_nr);\n \n if(db.fetchRow())\n return convertTo<int>(db[\"max_num\"]);\n else {\n db.query(\"select term from shopownedloanrate where shop_nr=%i\", shop_nr);\n \n if(db.fetchRow())\n return convertTo<int>(db[\"term\"]);\n }\n\n return 12;\n}\n\n\n\n\/\/ granted = time_t value of real time that loan was granted\n\/\/ term = term in mud years\n\/\/ returns mud time that loan is due\ntime_info_data whenDue(time_t granted, int term)\n{\n time_info_data due;\n\n mudTimePassed(granted, BEGINNING_OF_TIME, &due);\n\n due.year += YEAR_ADJUST;\n due.year += term;\n \n return due;\n}\n\nint calcInterest(int amt, time_t granted, int term, float rate, float def_charge)\n{\n time_info_data due;\n\n mudTimePassed(time(NULL), granted, &due);\n due.year++;\n\n if(due.year > term) \/\/ overdue!\n amt += (int)((float) amt * def_charge);\n\n while(due.year--){\n amt += (int)((float) amt * rate);\n }\n\n return amt;\n}\n\n\nint loanShark(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *me, TObj *o)\n{\n unsigned int shop_nr;\n TDatabase db(DB_SNEEZY);\n time_info_data due;\n sstring buf;\n\n if(cmd != CMD_WHISPER && cmd != CMD_LIST && cmd != CMD_BUY &&\n cmd != CMD_MOB_GIVEN_COINS)\n return false;\n \n if(!(shop_nr=find_shop_nr(me->number)))\n return false;\n \n if(cmd==CMD_WHISPER)\n return shopWhisper(ch, me, shop_nr, arg);\n\n TShopOwned tso(shop_nr, me, ch);\n\n\n db.query(\"select x, y from shopownedloanrate where shop_nr=%i\",\n\t shop_nr);\n if(!db.fetchRow()){\n vlogf(LOG_DB, fmt(\"couldn't find loanrate table for shop %i\") % shop_nr);\n me->doTell(ch->getName(), \"Hm, I can't seem to find my paperwork!\");\n return false;\n }\n\n double X=convertTo<double>(db[\"x\"]);\n double Y=convertTo<double>(db[\"y\"]);\n int term=getTerm(shop_nr, ch->getName());\n int amt=(int)(pow(ch->GetMaxLevel(), X) \/ pow(50, X) * Y);\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(cmd==CMD_LIST){\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(sstring(arg)==\"loans\" && tso.hasAccess(SHOPACCESS_INFO)){\n db.query(\"select name, amt, granted_time, term, rate, default_charge from player p, shopownedloans l where p.id=l.player_id order by granted_time\");\n \n \n while(db.fetchRow()){\n\tdue=whenDue(convertTo<int>(db[\"granted_time\"]), convertTo<int>(db[\"term\"]));\n;\n\tme->doTell(ch->getName(),\n\t\t fmt(\"%s for %i talens at %.2f%c, due %s of %s, %d P.S\") %\n\t\t db[\"name\"] %\n\t\t convertTo<int>(db[\"amt\"]) %\n\t\t (convertTo<float>(db[\"rate\"]) * 100) % '%' %\n\t\t numberAsString(due.day) %\n\t\t month_name[due.month] %\n\t\t due.year);\n }\n } else if(sstring(arg)==\"repo\" && tso.hasAccess(SHOPACCESS_INFO)){\n me->doTell(ch->getName(), \n\t\t \"I have the following options for collecting on loans.\");\n me->doTell(ch->getName(), fmt(\"1.[1%c]) I can do a direct transfer from the debtors bank account.\") % '%');\n me->doTell(ch->getName(), fmt(\"2.[1%c]) I can do a direct transfer from the debtors corporate account.\") % '%');\n me->doTell(ch->getName(), fmt(\"3.[3%c]) I can do a direct transfer from the debtors shops.\") % '%');\n me->doTell(ch->getName(), fmt(\"4.[5%c]) I can repossess items from the debtors shops and give them to you.\") % '%');\n me->doTell(ch->getName(), fmt(\"5.[7%c]) I can repossess entire shops if need be.\") % '%');\n me->doTell(ch->getName(), fmt(\"6.[9%c]) I can send out a collection agent to collect the debt by force.\") % '%');\n me->doTell(ch->getName(), \"The cost of the collection method is a percent of the debt, as listed.\");\n me->doTell(ch->getName(), \"You will be charged even if the collection isn't successful.\");\n me->doTell(ch->getName(), \"Shops won't be repossessed unless the debt exceeds the value of the shop.\");\n me->doTell(ch->getName(), \"To use one of these collection methods, do 'buy repo <number> <playername>\");\n } else {\n db.query(\"select amt, granted_time, term, rate, default_charge from shopownedloans where player_id=%i\", ch->getPlayerID());\n \n if(db.fetchRow()){\n\tamt=convertTo<int>(db[\"amt\"]);\n\tdue=whenDue(convertTo<int>(db[\"granted_time\"]), convertTo<int>(db[\"term\"]));\n\t\n\tme->doTell(ch->getName(), fmt(\"You have a loan for %i talens, due on the %s day of %s, Year %d P.S.\") %\n\t\t amt %\n\t\t numberAsString(due.day) % \n\t\t month_name[due.month] %\n\t\t due.year);\n\t\n\tamt=calcInterest(amt, convertTo<int>(db[\"granted_time\"]),\n\t\t\t convertTo<int>(db[\"term\"]), convertTo<float>(db[\"rate\"]),\n\t\t\t convertTo<float>(db[\"default_charge\"]));\n\t\n\t\n\tme->doTell(ch->getName(), fmt(\"With interest, you owe %i talens.\") % amt);\n } else {\n\tme->doTell(ch->getName(), fmt(\"I can extend you a loan for %i talens.\") % amt);\n\tme->doTell(ch->getName(), fmt(\"A yearly cumulative interest rate of %.2f%c will apply.\") % \n\t\t (getRate(shop_nr, ch->getName()) * 100) % '%');\n\tme->doTell(ch->getName(), fmt(\"The term length I can offer is %i years.\") % term);\n\tme->doTell(ch->getName(), \"One mud year is about 2 weeks in real time.\");\n\tme->doTell(ch->getName(), fmt(\"If you default on the loan, you will be charged an additional %.2f%c.\") %\n\t\t (getPenalty(shop_nr, ch->getName()) * 100) % '%');\n\tme->doTell(ch->getName(), \"Do \\\"buy loan <amt>\\\" to take out the loan.\");\n }\n }\n return true;\n }\n\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(cmd==CMD_BUY){\n if(sstring(arg).word(0) == \"repo\" && tso.hasAccess(SHOPACCESS_OWNER)){\n db.query(\"select amt, granted_time, term, rate, default_charge from shopownedloans, player where player_id=id and lower(name)=lower('%s')\", sstring(arg).word(2).c_str());\n \n if(!db.fetchRow()){\n\tme->doTell(ch->getName(), \"I can't find a loan for that player.\");\n\treturn true;\n }\n\n \/\/ repo stuff here\n\n\n\n } else if(sstring(arg).word(0) == \"loan\"){ \n db.query(\"select 1 from shopownedloans where player_id=%i\", \n\t ch->getPlayerID());\n if(db.fetchRow()){\n\tme->doTell(ch->getName(), \"You already have a loan!\");\n\treturn true;\n }\n\n int loanamt=convertTo<int>(sstring(arg).word(1));\n \n if(loanamt > amt || loanamt <= 0){\n\tme->doTell(ch->getName(), fmt(\"You can't take out a loan for that much. The most I can give you is %i.\") % amt);\n\treturn true;\n }\n\n amt=loanamt;\n\n if(amt > me->getMoney()){\n\tme->doTell(ch->getName(), \"At the moment, I don't have the necessary capital to extend a loan to you.\");\n\treturn true;\n }\n\n db.query(\"insert into shopownedloans values (%i, %i, %i, %i, %i, %f, %f)\",\n\t shop_nr, ch->getPlayerID(), amt, time(NULL),\n\t term, getRate(shop_nr, ch->getName()), \n\t getPenalty(shop_nr, ch->getName()));\n\n\n me->giveMoney(ch, amt, GOLD_SHOP);\n buf = fmt(\"%s\/%d\") % SHOPFILE_PATH % shop_nr;\n me->saveItems(buf);\n\n\n me->doTell(ch->getName(), fmt(\"There you go. Remember, I need the money back, plus interest, within %i years.\") % term);\n me->doTell(ch->getName(), \"Do 'list' again at anytime to see how much you owe with interest included.\");\n me->doTell(ch->getName(), \"You can give me talens at any time to make a payment on your loan.\");\n \n shoplog(shop_nr, ch, me, \"talens\", -amt, \"loaning\");\n } else {\n me->doTell(ch->getName(), \"If you want to take out the loan, do \\\"buy loan <amount>\\\".\");\n }\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(cmd==CMD_MOB_GIVEN_COINS){\n int coins=(int) o;\n\n db.query(\"select amt, granted_time, term, rate, default_charge from shopownedloans where player_id=%i\", ch->getPlayerID());\n \n if(db.fetchRow()){\n int principle=convertTo<int>(db[\"amt\"]);\n amt=calcInterest(principle, convertTo<int>(db[\"granted_time\"]),\n\t\t convertTo<int>(db[\"term\"]), \n\t\t convertTo<float>(db[\"rate\"]),\n\t\t convertTo<float>(db[\"default_charge\"]));\n\n if(coins>=amt){\n\tme->doTell(ch->getName(), \"Alright, everything appears to be in order here. Consider your loan paid off!\");\n\tdb.query(\"delete from shopownedloans where player_id=%i\", ch->getPlayerID());\n\tshoplog(shop_nr, ch, me, \"talens\", coins, \"giving\");\n } else {\n\t\/\/ how much of the amount owed is the principle\n\tfloat perc=(float)principle \/ (float)amt;\n\tprinciple -= (int)(perc*coins);\n\n\tdb.query(\"update shopownedloans set amt=%i where player_id=%i\",\n\t\t principle, ch->getPlayerID());\n\n\tme->doTell(ch->getName(), fmt(\"Thanks for the payment. You paid down the principle by %i talens, the rest went to interest.\") % (int)(perc*coins));\n\n\tshoplog(shop_nr, ch, me, \"talens\", coins, \"giving\");\n }\n } else {\n me->doTell(ch->getName(), \"Uhh... thanks!\");\n }\n }\n\n\n buf = fmt(\"%s\/%d\") % SHOPFILE_PATH % shop_nr;\n me->saveItems(buf);\n\n return false;\n}\n<commit_msg>added amount currently owed to loan listing<commit_after>#include \"stdsneezy.h\"\n#include \"database.h\"\n#include \"shop.h\"\n#include \"shopowned.h\"\n\n\/\/ 1 loan per account\n\n\/\/ collection:\n\/\/ transfer from bank account?\n\/\/ transfer from shops\/corp\n\/\/ send out repo mobs\n\n\/\/ setrates <default> <prime> <term> default\n\/\/ profit_buy = defaulting rate, profit_sell=prime rate\n\n\/\/ setrates <X> <Y> <term> loanrate\n\/\/ X * (lvl ** Y)\n\ndouble getPenalty(unsigned int shop_nr, const sstring &name)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"select profit_buy from shopownedplayer where player='%s' and shop_nr=%i\", name.c_str(), shop_nr);\n \n if(db.fetchRow())\n return convertTo<double>(db[\"profit_buy\"]);\n else {\n db.query(\"select profit_buy from shopowned where shop_nr=%i\", shop_nr);\n\n if(db.fetchRow())\n return convertTo<double>(db[\"profit_buy\"]);\n }\n\n return shop_index[shop_nr].profit_buy;\n}\n\ndouble getRate(unsigned int shop_nr, const sstring &name)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"select profit_sell from shopownedplayer where player='%s' and shop_nr=%i\", name.c_str(), shop_nr);\n \n if(db.fetchRow())\n return convertTo<double>(db[\"profit_sell\"]);\n else {\n db.query(\"select profit_sell from shopowned where shop_nr=%i\", shop_nr);\n\n if(db.fetchRow())\n return convertTo<double>(db[\"profit_sell\"]);\n }\n\n return shop_index[shop_nr].profit_sell;\n}\n\nint getTerm(unsigned int shop_nr, const sstring &name)\n{\n TDatabase db(DB_SNEEZY);\n\n db.query(\"select max_num from shopownedplayer where player='%s' and shop_nr=%i\", name.c_str(), shop_nr);\n \n if(db.fetchRow())\n return convertTo<int>(db[\"max_num\"]);\n else {\n db.query(\"select term from shopownedloanrate where shop_nr=%i\", shop_nr);\n \n if(db.fetchRow())\n return convertTo<int>(db[\"term\"]);\n }\n\n return 12;\n}\n\n\n\n\/\/ granted = time_t value of real time that loan was granted\n\/\/ term = term in mud years\n\/\/ returns mud time that loan is due\ntime_info_data whenDue(time_t granted, int term)\n{\n time_info_data due;\n\n mudTimePassed(granted, BEGINNING_OF_TIME, &due);\n\n due.year += YEAR_ADJUST;\n due.year += term;\n \n return due;\n}\n\nint calcInterest(int amt, time_t granted, int term, float rate, float def_charge)\n{\n time_info_data due;\n\n mudTimePassed(time(NULL), granted, &due);\n due.year++;\n\n if(due.year > term) \/\/ overdue!\n amt += (int)((float) amt * def_charge);\n\n while(due.year--){\n amt += (int)((float) amt * rate);\n }\n\n return amt;\n}\n\n\nint loanShark(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *me, TObj *o)\n{\n unsigned int shop_nr;\n TDatabase db(DB_SNEEZY);\n time_info_data due;\n sstring buf;\n\n if(cmd != CMD_WHISPER && cmd != CMD_LIST && cmd != CMD_BUY &&\n cmd != CMD_MOB_GIVEN_COINS)\n return false;\n \n if(!(shop_nr=find_shop_nr(me->number)))\n return false;\n \n if(cmd==CMD_WHISPER)\n return shopWhisper(ch, me, shop_nr, arg);\n\n TShopOwned tso(shop_nr, me, ch);\n\n\n db.query(\"select x, y from shopownedloanrate where shop_nr=%i\",\n\t shop_nr);\n if(!db.fetchRow()){\n vlogf(LOG_DB, fmt(\"couldn't find loanrate table for shop %i\") % shop_nr);\n me->doTell(ch->getName(), \"Hm, I can't seem to find my paperwork!\");\n return false;\n }\n\n double X=convertTo<double>(db[\"x\"]);\n double Y=convertTo<double>(db[\"y\"]);\n int term=getTerm(shop_nr, ch->getName());\n int amt=(int)(pow(ch->GetMaxLevel(), X) \/ pow(50, X) * Y);\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(cmd==CMD_LIST){\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(sstring(arg)==\"loans\" && tso.hasAccess(SHOPACCESS_INFO)){\n db.query(\"select name, amt, granted_time, term, rate, default_charge from player p, shopownedloans l where p.id=l.player_id order by granted_time\");\n \n \n while(db.fetchRow()){\n\tdue=whenDue(convertTo<int>(db[\"granted_time\"]), convertTo<int>(db[\"term\"]));\n\t\n\tamt=calcInterest(amt, convertTo<int>(db[\"granted_time\"]),\n\t\t\t convertTo<int>(db[\"term\"]), \n\t\t\t convertTo<float>(db[\"rate\"]),\n\t\t\t convertTo<float>(db[\"default_charge\"]));\n\n\tme->doTell(ch->getName(), \n\t\t fmt(\"%s for %i talens at %.2f%c due %s of %s, %d P.S\") %\n\t\t db[\"name\"] % convertTo<int>(db[\"amt\"]) % \n\t\t (convertTo<float>(db[\"rate\"]) * 100) % '%' %\n\t\t numberAsString(due.day) % month_name[due.month] %\n\t\t due.year);\n\tme->doTell(ch->getName(),\n\t\t fmt(\"%s currently owes %i talens.\") %\n\t\t db[\"name\"] % amt);\n }\n } else if(sstring(arg)==\"repo\" && tso.hasAccess(SHOPACCESS_INFO)){\n me->doTell(ch->getName(), \n\t\t \"I have the following options for collecting on loans.\");\n me->doTell(ch->getName(), fmt(\"1.[1%c]) I can do a direct transfer from the debtors bank account.\") % '%');\n me->doTell(ch->getName(), fmt(\"2.[1%c]) I can do a direct transfer from the debtors corporate account.\") % '%');\n me->doTell(ch->getName(), fmt(\"3.[3%c]) I can do a direct transfer from the debtors shops.\") % '%');\n me->doTell(ch->getName(), fmt(\"4.[5%c]) I can repossess items from the debtors shops and give them to you.\") % '%');\n me->doTell(ch->getName(), fmt(\"5.[7%c]) I can repossess entire shops if need be.\") % '%');\n me->doTell(ch->getName(), fmt(\"6.[9%c]) I can send out a collection agent to collect the debt by force.\") % '%');\n me->doTell(ch->getName(), \"The cost of the collection method is a percent of the debt, as listed.\");\n me->doTell(ch->getName(), \"You will be charged even if the collection isn't successful.\");\n me->doTell(ch->getName(), \"Shops won't be repossessed unless the debt exceeds the value of the shop.\");\n me->doTell(ch->getName(), \"To use one of these collection methods, do 'buy repo <number> <playername>\");\n } else {\n db.query(\"select amt, granted_time, term, rate, default_charge from shopownedloans where player_id=%i\", ch->getPlayerID());\n \n if(db.fetchRow()){\n\tamt=convertTo<int>(db[\"amt\"]);\n\tdue=whenDue(convertTo<int>(db[\"granted_time\"]), convertTo<int>(db[\"term\"]));\n\t\n\tme->doTell(ch->getName(), fmt(\"You have a loan for %i talens, due on the %s day of %s, Year %d P.S.\") %\n\t\t amt %\n\t\t numberAsString(due.day) % \n\t\t month_name[due.month] %\n\t\t due.year);\n\t\n\tamt=calcInterest(amt, convertTo<int>(db[\"granted_time\"]),\n\t\t\t convertTo<int>(db[\"term\"]), convertTo<float>(db[\"rate\"]),\n\t\t\t convertTo<float>(db[\"default_charge\"]));\n\t\n\t\n\tme->doTell(ch->getName(), fmt(\"With interest, you owe %i talens.\") % amt);\n } else {\n\tme->doTell(ch->getName(), fmt(\"I can extend you a loan for %i talens.\") % amt);\n\tme->doTell(ch->getName(), fmt(\"A yearly cumulative interest rate of %.2f%c will apply.\") % \n\t\t (getRate(shop_nr, ch->getName()) * 100) % '%');\n\tme->doTell(ch->getName(), fmt(\"The term length I can offer is %i years.\") % term);\n\tme->doTell(ch->getName(), \"One mud year is about 2 weeks in real time.\");\n\tme->doTell(ch->getName(), fmt(\"If you default on the loan, you will be charged an additional %.2f%c.\") %\n\t\t (getPenalty(shop_nr, ch->getName()) * 100) % '%');\n\tme->doTell(ch->getName(), \"Do \\\"buy loan <amt>\\\" to take out the loan.\");\n }\n }\n return true;\n }\n\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(cmd==CMD_BUY){\n if(sstring(arg).word(0) == \"repo\" && tso.hasAccess(SHOPACCESS_OWNER)){\n db.query(\"select amt, granted_time, term, rate, default_charge from shopownedloans, player where player_id=id and lower(name)=lower('%s')\", sstring(arg).word(2).c_str());\n \n if(!db.fetchRow()){\n\tme->doTell(ch->getName(), \"I can't find a loan for that player.\");\n\treturn true;\n }\n\n \/\/ repo stuff here\n\n\n\n } else if(sstring(arg).word(0) == \"loan\"){ \n db.query(\"select 1 from shopownedloans where player_id=%i\", \n\t ch->getPlayerID());\n if(db.fetchRow()){\n\tme->doTell(ch->getName(), \"You already have a loan!\");\n\treturn true;\n }\n\n int loanamt=convertTo<int>(sstring(arg).word(1));\n \n if(loanamt > amt || loanamt <= 0){\n\tme->doTell(ch->getName(), fmt(\"You can't take out a loan for that much. The most I can give you is %i.\") % amt);\n\treturn true;\n }\n\n amt=loanamt;\n\n if(amt > me->getMoney()){\n\tme->doTell(ch->getName(), \"At the moment, I don't have the necessary capital to extend a loan to you.\");\n\treturn true;\n }\n\n db.query(\"insert into shopownedloans values (%i, %i, %i, %i, %i, %f, %f)\",\n\t shop_nr, ch->getPlayerID(), amt, time(NULL),\n\t term, getRate(shop_nr, ch->getName()), \n\t getPenalty(shop_nr, ch->getName()));\n\n\n me->giveMoney(ch, amt, GOLD_SHOP);\n buf = fmt(\"%s\/%d\") % SHOPFILE_PATH % shop_nr;\n me->saveItems(buf);\n\n\n me->doTell(ch->getName(), fmt(\"There you go. Remember, I need the money back, plus interest, within %i years.\") % term);\n me->doTell(ch->getName(), \"Do 'list' again at anytime to see how much you owe with interest included.\");\n me->doTell(ch->getName(), \"You can give me talens at any time to make a payment on your loan.\");\n \n shoplog(shop_nr, ch, me, \"talens\", -amt, \"loaning\");\n } else {\n me->doTell(ch->getName(), \"If you want to take out the loan, do \\\"buy loan <amount>\\\".\");\n }\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(cmd==CMD_MOB_GIVEN_COINS){\n int coins=(int) o;\n\n db.query(\"select amt, granted_time, term, rate, default_charge from shopownedloans where player_id=%i\", ch->getPlayerID());\n \n if(db.fetchRow()){\n int principle=convertTo<int>(db[\"amt\"]);\n amt=calcInterest(principle, convertTo<int>(db[\"granted_time\"]),\n\t\t convertTo<int>(db[\"term\"]), \n\t\t convertTo<float>(db[\"rate\"]),\n\t\t convertTo<float>(db[\"default_charge\"]));\n\n if(coins>=amt){\n\tme->doTell(ch->getName(), \"Alright, everything appears to be in order here. Consider your loan paid off!\");\n\tdb.query(\"delete from shopownedloans where player_id=%i\", ch->getPlayerID());\n\tshoplog(shop_nr, ch, me, \"talens\", coins, \"giving\");\n } else {\n\t\/\/ how much of the amount owed is the principle\n\tfloat perc=(float)principle \/ (float)amt;\n\tprinciple -= (int)(perc*coins);\n\n\tdb.query(\"update shopownedloans set amt=%i where player_id=%i\",\n\t\t principle, ch->getPlayerID());\n\n\tme->doTell(ch->getName(), fmt(\"Thanks for the payment. You paid down the principle by %i talens, the rest went to interest.\") % (int)(perc*coins));\n\n\tshoplog(shop_nr, ch, me, \"talens\", coins, \"giving\");\n }\n } else {\n me->doTell(ch->getName(), \"Uhh... thanks!\");\n }\n }\n\n\n buf = fmt(\"%s\/%d\") % SHOPFILE_PATH % shop_nr;\n me->saveItems(buf);\n\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <osg\/Geode>\n#include <osg\/Drawable>\n#include <osg\/BlendFunc>\n#include <osg\/StateSet>\n#include <osg\/Notify>\n#include <osg\/Viewport>\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/FileUtils>\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/Registry>\n#include <osgDB\/Input>\n#include <osgDB\/Output>\n\n#include <osgUtil\/CullVisitor>\n\nusing namespace osg;\nusing namespace osgDB;\n\n\nclass Logos: public osg::Drawable\n{\n public:\n enum RelativePosition{\n Center,\n UpperLeft,\n UpperRight,\n LowerLeft,\n LowerRight,\n UpperCenter,\n LowerCenter,\n last_position\n };\n\n struct logosCullCallback : public osg::DrawableCullCallback\n {\n virtual bool cull(osg::NodeVisitor *visitor, osg::Drawable* drawable, osg::State*) const\n {\n Logos *logos = dynamic_cast<Logos *>(drawable);\n if (!logos) return true;\n\n osgUtil::CullVisitor *cv = visitor->asCullVisitor();\n if (!cv) return true;\n\n osg::State* state = cv->getState();\n\n unsigned int contextID = state!=0 ? state->getContextID() : 0;\n if(contextID != logos->getContextID())\n {\n \/\/ logo not appropriate for window assigned to the cull visitor so cull it.\n return true;\n }\n\n osg::Viewport *vp = cv->getViewport();\n if( vp != NULL )\n {\n if( vp->width() != logos->getViewport()->width() ||\n vp->height() != logos->getViewport()->height() )\n {\n logos->getViewport()->setViewport( vp->x(), vp->y(), vp->width(), vp->height() );\n logos->dirtyDisplayList();\n }\n }\n return false;\n }\n };\n\n Logos()\n {\n osg::StateSet *sset = new osg::StateSet;\n osg::BlendFunc *transp = new osg::BlendFunc;\n transp->setFunction(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n sset->setAttribute( transp );\n sset->setMode( GL_BLEND, osg::StateAttribute::ON );\n sset->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF );\n sset->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OFF );\n#if 1\n \/\/ for now we'll crudely set the bin number to 100 to force it to draw later and ontop of the scene\n sset->setRenderBinDetails( 100 , \"RenderBin\" );\n#else\n sset->setRenderBinDetails( StateSet::TRANSPARENT_BIN + 1 , \"RenderBin\" );\n#endif\n setStateSet( sset );\n _viewport = new osg::Viewport;\n setCullCallback( new logosCullCallback );\n _contextID = 0;\n }\n\n Logos(const Logos& logo, const CopyOp& copyop=CopyOp::SHALLOW_COPY) :\n Drawable( logo, copyop ),\n _contextID(0) {}\n\n virtual Object* cloneType() const { return new Logos(); }\n virtual Object* clone( const CopyOp& copyop) const { return new Logos(*this, copyop ); }\n virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Logos*>(obj)!=NULL; }\n virtual const char* className() const { return \"Logos\"; }\n\n virtual void drawImplementation(osg::RenderInfo& renderInfo) const\n {\n #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GLES3_AVAILABLE) && !defined(OSG_GL3_AVAILABLE)\n\n if( renderInfo.getContextID() != _contextID )\n return;\n\n\n float vx = 0.0f;\n float vy = 0.0f;\n float vw = 1.0f;\n float vh = 1.0f;\n if (_viewport.valid())\n {\n vx = _viewport->x();\n vy = _viewport->y();\n vw = _viewport->width();\n vh = _viewport->height();\n }\n\n glMatrixMode( GL_PROJECTION );\n glPushMatrix();\n glLoadIdentity();\n glOrtho( 0.0, vw, 0.0, vh, -1.0, 1.0 );\n\n glMatrixMode( GL_MODELVIEW );\n glPushMatrix();\n glLoadIdentity();\n\n glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );\n\n Images::const_iterator p;\n float th = 0.0;\n for( p = _logos[Center].begin(); p != _logos[Center].end(); p++ )\n {\n th += (*p)->t();\n }\n\n float place[][4] = {\n { vw*0.5f, ((vh*0.5f) + th*0.5f), -0.5f, -1.0f },\n { vx, vh, 0.0f, -1.0f },\n { vw, vh, -1.0f, -1.0f },\n { vx, vy, 0.0f, 1.0f },\n { vw, vy, -1.0f, 1.0f },\n { vw*0.5f, vh , -0.5f, -1.0f },\n { vw*0.5f, 0.0f , -0.5f, 1.0f },\n };\n\n for( int i = Center; i < last_position; i++ )\n {\n if( _logos[i].size() != 0 )\n {\n float x = place[i][0];\n float y = place[i][1];\n float xi = place[i][2];\n float yi = place[i][3];\n for( p = _logos[i].begin(); p != _logos[i].end(); p++ )\n {\n osg::Image *img = (*p).get();\n glPixelStorei(GL_UNPACK_ALIGNMENT, img->getPacking());\n glPixelStorei(GL_UNPACK_ROW_LENGTH, img->getRowLength());\n x = place[i][0] + xi * img->s();\n if( i == Center || i == UpperLeft || i == UpperRight || i == UpperCenter)\n y += yi * img->t();\n glRasterPos2f( x, y );\n glDrawPixels( img->s(), img->t(), img->getPixelFormat(), img->getDataType(), img->data() );\n if( i == LowerLeft || i == LowerRight || i == LowerCenter)\n y += yi * img->t();\n }\n }\n }\n\n glPopMatrix();\n glMatrixMode( GL_PROJECTION );\n glPopMatrix();\n glMatrixMode( GL_MODELVIEW );\n #else\n OSG_NOTICE<<\"Warning: Logos::drawImplementation(..) not supported.\"<<std::endl;\n #endif\n }\n\n void addLogo( RelativePosition pos, std::string name )\n {\n osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile( name.c_str() );\n if( image.valid())\n {\n _logos[pos].push_back( image );\n }\n else\n {\n OSG_WARN<< \"Logos::addLogo image file not found : \" << name << \".\\n\";\n }\n }\n\n osg::Viewport *getViewport() { return _viewport.get(); }\n\n void setContextID( unsigned int id ) { _contextID = id; }\n unsigned int getContextID() { return _contextID; }\n\n bool hasLogos()\n {\n int n = 0;\n for( int i = Center; i < last_position; i++ )\n n += _logos[i].size();\n return (n != 0);\n }\n\n virtual osg::BoundingBox computeBoundingBox() const\n {\n return osg::BoundingBox( -1, -1, -1, 1, 1, 1);\n }\n\n protected:\n Logos& operator = (const Logos&) { return *this;}\n\n virtual ~Logos() {}\n private :\n typedef std::vector < osg::ref_ptr<osg::Image> > Images;\n\n Images _logos[last_position];\n osg::ref_ptr<osg::Viewport> _viewport;\n unsigned int _contextID;\n};\n\n\nclass LOGOReaderWriter : public osgDB::ReaderWriter\n{\n public:\n LOGOReaderWriter()\n {\n supportsExtension(\"logo\",\"Ascii logo placement format\");\n }\n\n virtual const char* className() const { return \"Logo Database Reader\/Writer\"; }\n\n virtual ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName = osgDB::findDataFile( file, options );\n if (fileName.empty())\n return ReadResult::FILE_NOT_FOUND;\n\n OSG_INFO<< \"ReaderWriterLOGO::readNode( \"<<fileName.c_str()<<\" )\\n\";\n\n std::string filePath = osgDB::getFilePath(fileName);\n if (!filePath.empty()) {\n OSG_DEBUG<< \"Adding : \" << filePath << \" to the file data path\\n\";\n osgDB::getDataFilePathList().push_back(filePath);\n }\n\n\n osg::ref_ptr<osg::Geode> geode = new osg::Geode;\n\n unsigned int screen = 0;\n\n Logos* ld = new Logos;\n ld->setContextID( screen );\n\n Logos::RelativePosition pos = Logos::LowerRight;\n\n\n std::ifstream fin(filePath.c_str());\n if (!fin) return NULL;\n\n while(fin)\n {\n std::string str;\n fin >> str;\n\n if( str == \"Center\" )\n pos = Logos::Center;\n else if( str == \"UpperLeft\" )\n pos = Logos::UpperLeft;\n else if( str == \"UpperRight\" )\n pos = Logos::UpperRight;\n else if( str == \"LowerLeft\" )\n pos = Logos::LowerLeft;\n else if( str == \"LowerRight\" )\n pos = Logos::LowerRight;\n else if( str == \"UpperCenter\" )\n pos = Logos::UpperCenter;\n else if( str == \"LowerCenter\" )\n pos = Logos::LowerCenter;\n else if( str == \"Camera\" )\n {\n int tn;\n fin >> tn;\n if (fin.fail())\n {\n OSG_WARN << \"Error... Camera requires an integer argument\\n\";\n break;\n }\n\n if (tn < 0)\n {\n OSG_WARN << \"Error... Camera requires an positive or null value argument\\n\";\n break;\n }\n\n unsigned int n = static_cast<unsigned int>(tn);\n if( screen != n )\n {\n screen = n;\n if( ld->hasLogos() )\n {\n geode->addDrawable( ld );\n ld = new Logos;\n ld->setContextID( screen );\n }\n else\n ld->setContextID( screen );\n }\n }\n else\n {\n if( str.length() )\n ld->addLogo( pos, str );\n }\n }\n\n if( ld->hasLogos() )\n geode->addDrawable( ld );\n\n geode->setCullingActive(false);\n return geode;\n }\n};\n\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(logo, LOGOReaderWriter)\n<commit_msg>Make the culling be disables at the drawable level not at the geode level<commit_after>#include <stdio.h>\n#include <osg\/Geode>\n#include <osg\/Drawable>\n#include <osg\/BlendFunc>\n#include <osg\/StateSet>\n#include <osg\/Notify>\n#include <osg\/Viewport>\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/FileUtils>\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/Registry>\n#include <osgDB\/Input>\n#include <osgDB\/Output>\n\n#include <osgUtil\/CullVisitor>\n\nusing namespace osg;\nusing namespace osgDB;\n\n\nclass Logos: public osg::Drawable\n{\n public:\n enum RelativePosition{\n Center,\n UpperLeft,\n UpperRight,\n LowerLeft,\n LowerRight,\n UpperCenter,\n LowerCenter,\n last_position\n };\n\n struct logosCullCallback : public osg::DrawableCullCallback\n {\n virtual bool cull(osg::NodeVisitor *visitor, osg::Drawable* drawable, osg::State*) const\n {\n Logos *logos = dynamic_cast<Logos *>(drawable);\n if (!logos) return true;\n\n osgUtil::CullVisitor *cv = visitor->asCullVisitor();\n if (!cv) return true;\n\n osg::State* state = cv->getState();\n\n unsigned int contextID = state!=0 ? state->getContextID() : 0;\n if(contextID != logos->getContextID())\n {\n \/\/ logo not appropriate for window assigned to the cull visitor so cull it.\n return true;\n }\n\n osg::Viewport *vp = cv->getViewport();\n if( vp != NULL )\n {\n if( vp->width() != logos->getViewport()->width() ||\n vp->height() != logos->getViewport()->height() )\n {\n logos->getViewport()->setViewport( vp->x(), vp->y(), vp->width(), vp->height() );\n logos->dirtyDisplayList();\n }\n }\n return false;\n }\n };\n\n Logos()\n {\n osg::StateSet *sset = new osg::StateSet;\n osg::BlendFunc *transp = new osg::BlendFunc;\n transp->setFunction(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n sset->setAttribute( transp );\n sset->setMode( GL_BLEND, osg::StateAttribute::ON );\n sset->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF );\n sset->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OFF );\n#if 1\n \/\/ for now we'll crudely set the bin number to 100 to force it to draw later and ontop of the scene\n sset->setRenderBinDetails( 100 , \"RenderBin\" );\n#else\n sset->setRenderBinDetails( StateSet::TRANSPARENT_BIN + 1 , \"RenderBin\" );\n#endif\n setStateSet( sset );\n _viewport = new osg::Viewport;\n setCullCallback( new logosCullCallback );\n _contextID = 0;\n }\n\n Logos(const Logos& logo, const CopyOp& copyop=CopyOp::SHALLOW_COPY) :\n Drawable( logo, copyop ),\n _contextID(0) {}\n\n virtual Object* cloneType() const { return new Logos(); }\n virtual Object* clone( const CopyOp& copyop) const { return new Logos(*this, copyop ); }\n virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Logos*>(obj)!=NULL; }\n virtual const char* className() const { return \"Logos\"; }\n\n virtual void drawImplementation(osg::RenderInfo& renderInfo) const\n {\n #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GLES3_AVAILABLE) && !defined(OSG_GL3_AVAILABLE)\n\n if( renderInfo.getContextID() != _contextID )\n return;\n\n\n float vx = 0.0f;\n float vy = 0.0f;\n float vw = 1.0f;\n float vh = 1.0f;\n if (_viewport.valid())\n {\n vx = _viewport->x();\n vy = _viewport->y();\n vw = _viewport->width();\n vh = _viewport->height();\n }\n\n glMatrixMode( GL_PROJECTION );\n glPushMatrix();\n glLoadIdentity();\n glOrtho( 0.0, vw, 0.0, vh, -1.0, 1.0 );\n\n glMatrixMode( GL_MODELVIEW );\n glPushMatrix();\n glLoadIdentity();\n\n glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );\n\n Images::const_iterator p;\n float th = 0.0;\n for( p = _logos[Center].begin(); p != _logos[Center].end(); p++ )\n {\n th += (*p)->t();\n }\n\n float place[][4] = {\n { vw*0.5f, ((vh*0.5f) + th*0.5f), -0.5f, -1.0f },\n { vx, vh, 0.0f, -1.0f },\n { vw, vh, -1.0f, -1.0f },\n { vx, vy, 0.0f, 1.0f },\n { vw, vy, -1.0f, 1.0f },\n { vw*0.5f, vh , -0.5f, -1.0f },\n { vw*0.5f, 0.0f , -0.5f, 1.0f },\n };\n\n for( int i = Center; i < last_position; i++ )\n {\n if( _logos[i].size() != 0 )\n {\n float x = place[i][0];\n float y = place[i][1];\n float xi = place[i][2];\n float yi = place[i][3];\n for( p = _logos[i].begin(); p != _logos[i].end(); p++ )\n {\n osg::Image *img = (*p).get();\n glPixelStorei(GL_UNPACK_ALIGNMENT, img->getPacking());\n glPixelStorei(GL_UNPACK_ROW_LENGTH, img->getRowLength());\n x = place[i][0] + xi * img->s();\n if( i == Center || i == UpperLeft || i == UpperRight || i == UpperCenter)\n y += yi * img->t();\n glRasterPos2f( x, y );\n glDrawPixels( img->s(), img->t(), img->getPixelFormat(), img->getDataType(), img->data() );\n if( i == LowerLeft || i == LowerRight || i == LowerCenter)\n y += yi * img->t();\n }\n }\n }\n\n glPopMatrix();\n glMatrixMode( GL_PROJECTION );\n glPopMatrix();\n glMatrixMode( GL_MODELVIEW );\n #else\n OSG_NOTICE<<\"Warning: Logos::drawImplementation(..) not supported.\"<<std::endl;\n #endif\n }\n\n void addLogo( RelativePosition pos, std::string name )\n {\n osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile( name.c_str() );\n if( image.valid())\n {\n _logos[pos].push_back( image );\n }\n else\n {\n OSG_WARN<< \"Logos::addLogo image file not found : \" << name << \".\\n\";\n }\n }\n\n osg::Viewport *getViewport() { return _viewport.get(); }\n\n void setContextID( unsigned int id ) { _contextID = id; }\n unsigned int getContextID() { return _contextID; }\n\n bool hasLogos()\n {\n int n = 0;\n for( int i = Center; i < last_position; i++ )\n n += _logos[i].size();\n return (n != 0);\n }\n\n virtual osg::BoundingBox computeBoundingBox() const\n {\n return osg::BoundingBox( -1, -1, -1, 1, 1, 1);\n }\n\n protected:\n Logos& operator = (const Logos&) { return *this;}\n\n virtual ~Logos() {}\n private :\n typedef std::vector < osg::ref_ptr<osg::Image> > Images;\n\n Images _logos[last_position];\n osg::ref_ptr<osg::Viewport> _viewport;\n unsigned int _contextID;\n};\n\n\nclass LOGOReaderWriter : public osgDB::ReaderWriter\n{\n public:\n LOGOReaderWriter()\n {\n supportsExtension(\"logo\",\"Ascii logo placement format\");\n }\n\n virtual const char* className() const { return \"Logo Database Reader\/Writer\"; }\n\n virtual ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName = osgDB::findDataFile( file, options );\n if (fileName.empty())\n return ReadResult::FILE_NOT_FOUND;\n\n OSG_INFO<< \"ReaderWriterLOGO::readNode( \"<<fileName.c_str()<<\" )\\n\";\n\n std::string filePath = osgDB::getFilePath(fileName);\n if (!filePath.empty()) {\n OSG_DEBUG<< \"Adding : \" << filePath << \" to the file data path\\n\";\n osgDB::getDataFilePathList().push_back(filePath);\n }\n\n\n osg::ref_ptr<osg::Geode> geode = new osg::Geode;\n\n unsigned int screen = 0;\n\n Logos* ld = new Logos;\n ld->setContextID( screen );\n\n Logos::RelativePosition pos = Logos::LowerRight;\n\n\n std::ifstream fin(filePath.c_str());\n if (!fin) return NULL;\n\n while(fin)\n {\n std::string str;\n fin >> str;\n\n if( str == \"Center\" )\n pos = Logos::Center;\n else if( str == \"UpperLeft\" )\n pos = Logos::UpperLeft;\n else if( str == \"UpperRight\" )\n pos = Logos::UpperRight;\n else if( str == \"LowerLeft\" )\n pos = Logos::LowerLeft;\n else if( str == \"LowerRight\" )\n pos = Logos::LowerRight;\n else if( str == \"UpperCenter\" )\n pos = Logos::UpperCenter;\n else if( str == \"LowerCenter\" )\n pos = Logos::LowerCenter;\n else if( str == \"Camera\" )\n {\n int tn;\n fin >> tn;\n if (fin.fail())\n {\n OSG_WARN << \"Error... Camera requires an integer argument\\n\";\n break;\n }\n\n if (tn < 0)\n {\n OSG_WARN << \"Error... Camera requires an positive or null value argument\\n\";\n break;\n }\n\n unsigned int n = static_cast<unsigned int>(tn);\n if( screen != n )\n {\n screen = n;\n if( ld->hasLogos() )\n {\n geode->addDrawable( ld );\n ld = new Logos;\n ld->setContextID( screen );\n }\n else\n ld->setContextID( screen );\n }\n }\n else\n {\n if( str.length() )\n ld->addLogo( pos, str );\n }\n }\n\n if( ld->hasLogos() )\n geode->addDrawable( ld );\n\n ld->setCullingActive(false);\n return geode;\n }\n};\n\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(logo, LOGOReaderWriter)\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"varint.hpp\"\n\n#include \"..\/base\/buffer_vector.hpp\"\n\n#include \"..\/std\/string.hpp\"\n#include \"..\/std\/vector.hpp\"\n\n\nnamespace rw\n{\n template <class TSink>\n void Write(TSink & sink, uint32_t i)\n {\n WriteVarUint(sink, i);\n }\n\n template <class TSource>\n void Read(TSource & src, uint32_t & i)\n {\n i = ReadVarUint<uint32_t>(src);\n }\n\n template <class TSink>\n void Write(TSink & sink, string const & s)\n {\n uint32_t const count = static_cast<uint32_t>(s.size());\n WriteVarUint(sink, count);\n if (!s.empty())\n sink.Write(&s[0], count);\n }\n\n template <class TSource>\n void Read(TSource & src, string & s)\n {\n uint32_t const count = ReadVarUint<uint32_t>(src);\n s.resize(count);\n if (count > 0)\n src.Read(&s[0], count);\n }\n\n namespace impl\n {\n template <class TSink, class TCont>\n void WriteCont(TSink & sink, TCont const & v)\n {\n uint32_t const count = static_cast<uint32_t>(v.size());\n WriteVarUint(sink, count);\n for (uint32_t i = 0; i < count; ++i)\n Write(sink, v[i]);\n }\n\n template <class TSource, class TCont>\n void ReadCont(TSource & src, TCont & v)\n {\n uint32_t const count = ReadVarUint<uint32_t>(src);\n v.resize(count);\n for (size_t i = 0; i < count; ++i)\n Read(src, v[i]);\n }\n }\n\n template <class TSink, class T>\n void Write(TSink & sink, vector<T> const & v)\n {\n impl::WriteCont(sink, v);\n }\n\n template <class TSource, class T>\n void Read(TSource & src, vector<T> & v)\n {\n impl::ReadCont(src, v);\n }\n\n template <class TSink, class T, size_t N>\n void Write(TSink & sink, buffer_vector<T, N> const & v)\n {\n impl::WriteCont(sink, v);\n }\n\n template <class TSource, class T, size_t N>\n void Read(TSource & src, buffer_vector<T, N> & v)\n {\n impl::ReadCont(src, v);\n }\n}\n<commit_msg>Add vector<uint8_t> serialization functions.<commit_after>#pragma once\n\n#include \"varint.hpp\"\n\n#include \"..\/base\/buffer_vector.hpp\"\n\n#include \"..\/std\/string.hpp\"\n#include \"..\/std\/vector.hpp\"\n\n\nnamespace rw\n{\n template <class TSink>\n void Write(TSink & sink, uint32_t i)\n {\n WriteVarUint(sink, i);\n }\n\n template <class TSource>\n void Read(TSource & src, uint32_t & i)\n {\n i = ReadVarUint<uint32_t>(src);\n }\n\n template <class TSink>\n void Write(TSink & sink, string const & s)\n {\n uint32_t const count = static_cast<uint32_t>(s.size());\n WriteVarUint(sink, count);\n if (!s.empty())\n sink.Write(&s[0], count);\n }\n\n template <class TSource>\n void Read(TSource & src, string & s)\n {\n uint32_t const count = ReadVarUint<uint32_t>(src);\n s.resize(count);\n if (count > 0)\n src.Read(&s[0], count);\n }\n\n namespace impl\n {\n template <class TSink, class TCont>\n void WriteCont(TSink & sink, TCont const & v)\n {\n uint32_t const count = static_cast<uint32_t>(v.size());\n WriteVarUint(sink, count);\n for (uint32_t i = 0; i < count; ++i)\n Write(sink, v[i]);\n }\n\n template <class TSource, class TCont>\n void ReadCont(TSource & src, TCont & v)\n {\n uint32_t const count = ReadVarUint<uint32_t>(src);\n v.resize(count);\n for (size_t i = 0; i < count; ++i)\n Read(src, v[i]);\n }\n }\n\n template <class TSink, class T>\n void Write(TSink & sink, vector<T> const & v)\n {\n impl::WriteCont(sink, v);\n }\n\n template <class TSource, class T>\n void Read(TSource & src, vector<T> & v)\n {\n impl::ReadCont(src, v);\n }\n\n template <class TSink, class T, size_t N>\n void Write(TSink & sink, buffer_vector<T, N> const & v)\n {\n impl::WriteCont(sink, v);\n }\n\n template <class TSource, class T, size_t N>\n void Read(TSource & src, buffer_vector<T, N> & v)\n {\n impl::ReadCont(src, v);\n }\n\n template <class TSource, class TCont>\n void ReadRaw(TSource & src, TCont & v)\n {\n STATIC_ASSERT(sizeof(typename TCont::value_type) == 1);\n\n uint32_t const count = ReadVarUint<uint32_t>(src);\n if (count > 0)\n {\n v.resize(count);\n src.Read(&v[0], count);\n }\n }\n\n template <class TSink, class TCont>\n void WriteRaw(TSink & sink, TCont const & v)\n {\n STATIC_ASSERT(sizeof(typename TCont::value_type) == 1);\n\n uint32_t const count = static_cast<uint32_t>(v.size());\n WriteVarUint(sink, count);\n\n if (count > 0)\n sink.Write(&v[0], count);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017 Xevo Inc.\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 met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <algorithm>\n\n#include \"application_manager\/commands\/hmi\/navi_set_video_config_request.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"utils\/shared_ptr.h\"\n#include \"smart_objects\/smart_object.h\"\n#include \"application_manager\/smart_object_keys.h\"\n#include \"application_manager\/commands\/command_request_test.h\"\n#include \"application_manager\/mock_application_manager.h\"\n#include \"application_manager\/hmi_interfaces.h\"\n#include \"application_manager\/mock_hmi_interface.h\"\n#include \"application_manager\/event_engine\/event.h\"\n#include \"application_manager\/mock_event_dispatcher.h\"\n\nnamespace test {\nnamespace components {\nnamespace commands_test {\nnamespace hmi_commands_test {\nnamespace navi_set_video_config_request {\n\nusing ::testing::_;\nusing ::testing::ReturnRef;\nnamespace am = ::application_manager;\nusing am::commands::MessageSharedPtr;\nusing am::commands::NaviSetVideoConfigRequest;\nusing am::event_engine::Event;\n\nnamespace {\nconst uint32_t kAppId = 1u;\nconst uint32_t kHmiAppId = 13u;\nconst hmi_apis::FunctionID::eType kEventID =\n hmi_apis::FunctionID::Navigation_SetVideoConfig;\n} \/\/ namespace\n\ntypedef SharedPtr<NaviSetVideoConfigRequest> NaviSetVideoConfigRequestPtr;\n\nclass NaviSetVideoConfigRequestTest\n : public CommandRequestTest<CommandsTestMocks::kIsNice> {\n public:\n NaviSetVideoConfigRequestTest() {\n mock_app_ptr_ = CreateMockApp();\n ON_CALL(app_mngr_, hmi_interfaces())\n .WillByDefault(ReturnRef(mock_hmi_interfaces_));\n ON_CALL(app_mngr_, application(_)).WillByDefault(Return(mock_app_ptr_));\n ON_CALL(app_mngr_, application_by_hmi_app(_))\n .WillByDefault(Return(mock_app_ptr_));\n ON_CALL(app_mngr_, event_dispatcher())\n .WillByDefault(ReturnRef(mock_event_dispatcher_));\n ON_CALL(*mock_app_ptr_, hmi_app_id()).WillByDefault(Return(kHmiAppId));\n }\n\n MOCK(am::MockHmiInterfaces) mock_hmi_interfaces_;\n MockAppPtr mock_app_ptr_;\n MockEventDispatcher mock_event_dispatcher_;\n};\n\nTEST_F(NaviSetVideoConfigRequestTest, OnEvent_SUCCESS) {\n MessageSharedPtr request_msg = CreateMessage();\n (*request_msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n\n NaviSetVideoConfigRequestPtr command =\n CreateCommand<NaviSetVideoConfigRequest>(request_msg);\n\n MessageSharedPtr event_msg = CreateMessage();\n (*event_msg)[am::strings::params][am::hmi_response::code] =\n hmi_apis::Common_Result::SUCCESS;\n Event event(kEventID);\n event.set_smart_object(*event_msg);\n\n std::vector<std::string> empty;\n EXPECT_CALL(\n app_mngr_,\n OnStreamingConfigured(\n kHmiAppId, protocol_handler::ServiceType::kMobileNav, true, empty))\n .Times(1);\n\n command->on_event(event);\n}\n\nstatic bool ValidateList(std::vector<std::string>& expected,\n std::vector<std::string>& actual) {\n std::sort(expected.begin(), expected.end());\n std::sort(actual.begin(), actual.end());\n return std::equal(expected.begin(), expected.end(), actual.begin());\n}\n\nTEST_F(NaviSetVideoConfigRequestTest, OnEvent_FAILURE) {\n MessageSharedPtr request_msg = CreateMessage();\n (*request_msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n (*request_msg)[am::strings::msg_params][am::strings::config] =\n smart_objects::SmartObject(smart_objects::SmartType_Array);\n (*request_msg)[am::strings::msg_params][am::strings::config]\n [am::strings::protocol] =\n hmi_apis::Common_VideoStreamingProtocol::RTP;\n (*request_msg)[am::strings::msg_params][am::strings::config]\n [am::strings::codec] =\n hmi_apis::Common_VideoStreamingCodec::H265;\n (*request_msg)[am::strings::msg_params][am::strings::config]\n [am::strings::height] = 640;\n (*request_msg)[am::strings::msg_params][am::strings::config]\n [am::strings::width] = 480;\n\n NaviSetVideoConfigRequestPtr command =\n CreateCommand<NaviSetVideoConfigRequest>(request_msg);\n\n MessageSharedPtr event_msg = CreateMessage();\n (*event_msg)[am::strings::params][am::hmi_response::code] =\n hmi_apis::Common_Result::REJECTED;\n\n (*event_msg)[am::strings::msg_params][am::strings::rejected_params] =\n smart_objects::SmartObject(smart_objects::SmartType_Array);\n (*event_msg)[am::strings::msg_params][am::strings::rejected_params][0] =\n \"codec\";\n (*event_msg)[am::strings::msg_params][am::strings::rejected_params][1] =\n \"protocol\";\n Event event(kEventID);\n event.set_smart_object(*event_msg);\n\n std::vector<std::string> rejected_params;\n EXPECT_CALL(\n app_mngr_,\n OnStreamingConfigured(\n kHmiAppId, protocol_handler::ServiceType::kMobileNav, false, _))\n .WillOnce(SaveArg<3>(&rejected_params));\n\n command->on_event(event);\n\n ASSERT_EQ(2u, rejected_params.size());\n std::vector<std::string> expected_list;\n expected_list.push_back(std::string(\"protocol\"));\n expected_list.push_back(std::string(\"codec\"));\n ASSERT_TRUE(ValidateList(expected_list, rejected_params));\n}\n\nTEST_F(NaviSetVideoConfigRequestTest, OnEvent_FAILURE_WithoutParams) {\n MessageSharedPtr request_msg = CreateMessage();\n (*request_msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n\n NaviSetVideoConfigRequestPtr command =\n CreateCommand<NaviSetVideoConfigRequest>(request_msg);\n\n MessageSharedPtr event_msg = CreateMessage();\n (*event_msg)[am::strings::params][am::hmi_response::code] =\n hmi_apis::Common_Result::REJECTED;\n\n Event event(kEventID);\n event.set_smart_object(*event_msg);\n\n std::vector<std::string> empty;\n EXPECT_CALL(\n app_mngr_,\n OnStreamingConfigured(\n kHmiAppId, protocol_handler::ServiceType::kMobileNav, false, empty))\n .WillOnce(Return());\n\n command->on_event(event);\n}\n\nTEST_F(NaviSetVideoConfigRequestTest, OnTimeout) {\n MessageSharedPtr request_msg = CreateMessage();\n (*request_msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n\n NaviSetVideoConfigRequestPtr command =\n CreateCommand<NaviSetVideoConfigRequest>(request_msg);\n\n std::vector<std::string> empty;\n EXPECT_CALL(\n app_mngr_,\n OnStreamingConfigured(\n kHmiAppId, protocol_handler::ServiceType::kMobileNav, false, empty))\n .WillOnce(Return());\n\n EXPECT_CALL(app_mngr_, TerminateRequest(_, _, _)).Times(1);\n\n command->onTimeOut();\n}\n\n} \/\/ namespace navi_set_video_config_request\n} \/\/ namespace hmi_commands_test\n} \/\/ namespace commands_test\n} \/\/ namespace components\n} \/\/ namespace test\n<commit_msg>Rename some test cases for better description<commit_after>\/*\n * Copyright (c) 2017 Xevo Inc.\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 met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <algorithm>\n\n#include \"application_manager\/commands\/hmi\/navi_set_video_config_request.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"utils\/shared_ptr.h\"\n#include \"smart_objects\/smart_object.h\"\n#include \"application_manager\/smart_object_keys.h\"\n#include \"application_manager\/commands\/command_request_test.h\"\n#include \"application_manager\/mock_application_manager.h\"\n#include \"application_manager\/hmi_interfaces.h\"\n#include \"application_manager\/mock_hmi_interface.h\"\n#include \"application_manager\/event_engine\/event.h\"\n#include \"application_manager\/mock_event_dispatcher.h\"\n\nnamespace test {\nnamespace components {\nnamespace commands_test {\nnamespace hmi_commands_test {\nnamespace navi_set_video_config_request {\n\nusing ::testing::_;\nusing ::testing::ReturnRef;\nnamespace am = ::application_manager;\nusing am::commands::MessageSharedPtr;\nusing am::commands::NaviSetVideoConfigRequest;\nusing am::event_engine::Event;\n\nnamespace {\nconst uint32_t kAppId = 1u;\nconst uint32_t kHmiAppId = 13u;\nconst hmi_apis::FunctionID::eType kEventID =\n hmi_apis::FunctionID::Navigation_SetVideoConfig;\n} \/\/ namespace\n\ntypedef SharedPtr<NaviSetVideoConfigRequest> NaviSetVideoConfigRequestPtr;\n\nclass NaviSetVideoConfigRequestTest\n : public CommandRequestTest<CommandsTestMocks::kIsNice> {\n public:\n NaviSetVideoConfigRequestTest() {\n mock_app_ptr_ = CreateMockApp();\n ON_CALL(app_mngr_, hmi_interfaces())\n .WillByDefault(ReturnRef(mock_hmi_interfaces_));\n ON_CALL(app_mngr_, application(_)).WillByDefault(Return(mock_app_ptr_));\n ON_CALL(app_mngr_, application_by_hmi_app(_))\n .WillByDefault(Return(mock_app_ptr_));\n ON_CALL(app_mngr_, event_dispatcher())\n .WillByDefault(ReturnRef(mock_event_dispatcher_));\n ON_CALL(*mock_app_ptr_, hmi_app_id()).WillByDefault(Return(kHmiAppId));\n }\n\n MOCK(am::MockHmiInterfaces) mock_hmi_interfaces_;\n MockAppPtr mock_app_ptr_;\n MockEventDispatcher mock_event_dispatcher_;\n};\n\nTEST_F(NaviSetVideoConfigRequestTest, OnEventWithSuccessResponse) {\n MessageSharedPtr request_msg = CreateMessage();\n (*request_msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n\n NaviSetVideoConfigRequestPtr command =\n CreateCommand<NaviSetVideoConfigRequest>(request_msg);\n\n MessageSharedPtr event_msg = CreateMessage();\n (*event_msg)[am::strings::params][am::hmi_response::code] =\n hmi_apis::Common_Result::SUCCESS;\n Event event(kEventID);\n event.set_smart_object(*event_msg);\n\n std::vector<std::string> empty;\n EXPECT_CALL(\n app_mngr_,\n OnStreamingConfigured(\n kHmiAppId, protocol_handler::ServiceType::kMobileNav, true, empty))\n .Times(1);\n\n command->on_event(event);\n}\n\nstatic bool ValidateList(std::vector<std::string>& expected,\n std::vector<std::string>& actual) {\n std::sort(expected.begin(), expected.end());\n std::sort(actual.begin(), actual.end());\n return std::equal(expected.begin(), expected.end(), actual.begin());\n}\n\nTEST_F(NaviSetVideoConfigRequestTest, OnEventWithRejectedResponse) {\n MessageSharedPtr request_msg = CreateMessage();\n (*request_msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n (*request_msg)[am::strings::msg_params][am::strings::config] =\n smart_objects::SmartObject(smart_objects::SmartType_Array);\n (*request_msg)[am::strings::msg_params][am::strings::config]\n [am::strings::protocol] =\n hmi_apis::Common_VideoStreamingProtocol::RTP;\n (*request_msg)[am::strings::msg_params][am::strings::config]\n [am::strings::codec] =\n hmi_apis::Common_VideoStreamingCodec::H265;\n (*request_msg)[am::strings::msg_params][am::strings::config]\n [am::strings::height] = 640;\n (*request_msg)[am::strings::msg_params][am::strings::config]\n [am::strings::width] = 480;\n\n NaviSetVideoConfigRequestPtr command =\n CreateCommand<NaviSetVideoConfigRequest>(request_msg);\n\n MessageSharedPtr event_msg = CreateMessage();\n (*event_msg)[am::strings::params][am::hmi_response::code] =\n hmi_apis::Common_Result::REJECTED;\n\n (*event_msg)[am::strings::msg_params][am::strings::rejected_params] =\n smart_objects::SmartObject(smart_objects::SmartType_Array);\n (*event_msg)[am::strings::msg_params][am::strings::rejected_params][0] =\n \"codec\";\n (*event_msg)[am::strings::msg_params][am::strings::rejected_params][1] =\n \"protocol\";\n Event event(kEventID);\n event.set_smart_object(*event_msg);\n\n std::vector<std::string> rejected_params;\n EXPECT_CALL(\n app_mngr_,\n OnStreamingConfigured(\n kHmiAppId, protocol_handler::ServiceType::kMobileNav, false, _))\n .WillOnce(SaveArg<3>(&rejected_params));\n\n command->on_event(event);\n\n ASSERT_EQ(2u, rejected_params.size());\n std::vector<std::string> expected_list;\n expected_list.push_back(std::string(\"protocol\"));\n expected_list.push_back(std::string(\"codec\"));\n ASSERT_TRUE(ValidateList(expected_list, rejected_params));\n}\n\nTEST_F(NaviSetVideoConfigRequestTest,\n OnEventWithRejectedResponseWithoutParams) {\n MessageSharedPtr request_msg = CreateMessage();\n (*request_msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n\n NaviSetVideoConfigRequestPtr command =\n CreateCommand<NaviSetVideoConfigRequest>(request_msg);\n\n MessageSharedPtr event_msg = CreateMessage();\n (*event_msg)[am::strings::params][am::hmi_response::code] =\n hmi_apis::Common_Result::REJECTED;\n\n Event event(kEventID);\n event.set_smart_object(*event_msg);\n\n std::vector<std::string> empty;\n EXPECT_CALL(\n app_mngr_,\n OnStreamingConfigured(\n kHmiAppId, protocol_handler::ServiceType::kMobileNav, false, empty))\n .WillOnce(Return());\n\n command->on_event(event);\n}\n\nTEST_F(NaviSetVideoConfigRequestTest, OnTimeout) {\n MessageSharedPtr request_msg = CreateMessage();\n (*request_msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n\n NaviSetVideoConfigRequestPtr command =\n CreateCommand<NaviSetVideoConfigRequest>(request_msg);\n\n std::vector<std::string> empty;\n EXPECT_CALL(\n app_mngr_,\n OnStreamingConfigured(\n kHmiAppId, protocol_handler::ServiceType::kMobileNav, false, empty))\n .WillOnce(Return());\n\n EXPECT_CALL(app_mngr_, TerminateRequest(_, _, _)).Times(1);\n\n command->onTimeOut();\n}\n\n} \/\/ namespace navi_set_video_config_request\n} \/\/ namespace hmi_commands_test\n} \/\/ namespace commands_test\n} \/\/ namespace components\n} \/\/ namespace test\n<|endoftext|>"} {"text":"<commit_before>\/\/ MFEM Example 1 - Parallel Version\n\/\/\n\/\/ Compile with: make ex1p\n\/\/\n\/\/ Sample runs: mpirun -np 4 ex1p -m ..\/data\/square-disc.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/star.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/star-mixed.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/escher.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/fichera.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/fichera-mixed.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/toroid-wedge.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/periodic-annulus-sector.msh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/periodic-torus-sector.msh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/square-disc-p2.vtk -o 2\n\/\/ mpirun -np 4 ex1p -m ..\/data\/square-disc-p3.mesh -o 3\n\/\/ mpirun -np 4 ex1p -m ..\/data\/square-disc-nurbs.mesh -o -1\n\/\/ mpirun -np 4 ex1p -m ..\/data\/star-mixed-p2.mesh -o 2\n\/\/ mpirun -np 4 ex1p -m ..\/data\/disc-nurbs.mesh -o -1\n\/\/ mpirun -np 4 ex1p -m ..\/data\/pipe-nurbs.mesh -o -1\n\/\/ mpirun -np 4 ex1p -m ..\/data\/ball-nurbs.mesh -o 2\n\/\/ mpirun -np 4 ex1p -m ..\/data\/fichera-mixed-p2.mesh -o 2\n\/\/ mpirun -np 4 ex1p -m ..\/data\/star-surf.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/square-disc-surf.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/inline-segment.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/amr-quad.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/amr-hex.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/mobius-strip.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/mobius-strip.mesh -o -1 -sc\n\/\/\n\/\/ Device sample runs:\n\/\/ mpirun -np 4 ex1p -pa -d cuda\n\/\/ mpirun -np 4 ex1p -pa -d occa-cuda\n\/\/ mpirun -np 4 ex1p -pa -d raja-omp\n\/\/ mpirun -np 4 ex1p -pa -d ceed-cpu\n\/\/ * mpirun -np 4 ex1p -pa -d ceed-cuda\n\/\/ mpirun -np 4 ex1p -pa -d ceed-cuda:\/gpu\/cuda\/shared\n\/\/ mpirun -np 4 ex1p -m ..\/data\/beam-tet.mesh -pa -d ceed-cpu\n\/\/\n\/\/ Description: This example is a copy of ex1 instrumented with Caliper.\n\/\/ Any option supported by the Caliper ConfigManager can be passed to the\n\/\/ code using a configuration string after -p or --caliper flag. For more\n\/\/ information, the users are referred to the Caliper documentation.\n\/\/ Examples:\n\/\/ mpirun -np 4 ex1p --caliper runtime-report\n\/\/ mpirun -np 4 ex1p --caliper runtime-report,mem.highwatermark,mpi-report\n\/\/\n\/\/The first run will return the default report and the second run will\n\/\/return in addition to the default output the memory high-water mark and time\n\/\/spent in MPI routines.\n\n\n#include \"mfem.hpp\"\n#include <fstream>\n#include <iostream>\n\nusing namespace std;\nusing namespace mfem;\n\nint main(int argc, char *argv[])\n{\n \/\/ 1. Initialize MPI.\n int num_procs, myid;\n MPI_Init(&argc, &argv);\n MPI_Comm_size(MPI_COMM_WORLD, &num_procs);\n MPI_Comm_rank(MPI_COMM_WORLD, &myid);\n \/\/ Define Caliper ConfigManager\n cali::ConfigManager mgr;\n \/\/ Caliper instrumentation\n MFEM_PERF_FUNCTION;\n\n \/\/ 2. Parse command-line options.\n const char *mesh_file = \"..\/..\/data\/star.mesh\";\n int order = 1;\n bool static_cond = false;\n bool pa = false;\n const char *device_config = \"cpu\";\n bool visualization = true;\n const char* cali_config = \"runtime-report\";\n\n OptionsParser args(argc, argv);\n args.AddOption(&mesh_file, \"-m\", \"--mesh\",\n \"Mesh file to use.\");\n args.AddOption(&order, \"-o\", \"--order\",\n \"Finite element order (polynomial degree) or -1 for\"\n \" isoparametric space.\");\n args.AddOption(&static_cond, \"-sc\", \"--static-condensation\", \"-no-sc\",\n \"--no-static-condensation\", \"Enable static condensation.\");\n args.AddOption(&pa, \"-pa\", \"--partial-assembly\", \"-no-pa\",\n \"--no-partial-assembly\", \"Enable Partial Assembly.\");\n args.AddOption(&device_config, \"-d\", \"--device\",\n \"Device configuration string, see Device::Configure().\");\n args.AddOption(&visualization, \"-vis\", \"--visualization\", \"-no-vis\",\n \"--no-visualization\",\n \"Enable or disable GLVis visualization.\");\n args.AddOption(&cali_config, \"-p\", \"--caliper\",\n \"Caliper configuration string.\");\n args.Parse();\n if (!args.Good())\n {\n if (myid == 0)\n {\n args.PrintUsage(cout);\n }\n MPI_Finalize();\n return 1;\n }\n if (myid == 0)\n {\n args.PrintOptions(cout);\n }\n\n \/\/ 3. Enable hardware devices such as GPUs, and programming models such as\n \/\/ CUDA, OCCA, RAJA and OpenMP based on command line options.\n Device device(device_config);\n if (myid == 0) { device.Print(); }\n\n \/\/Caliper configuration\n mgr.add(cali_config);\n mgr.start();\n\n \/\/ 4. Read the (serial) mesh from the given mesh file on all processors. We\n \/\/ can handle triangular, quadrilateral, tetrahedral, hexahedral, surface\n \/\/ and volume meshes with the same code.\n Mesh mesh(mesh_file, 1, 1);\n int dim = mesh.Dimension();\n\n \/\/ 5. Refine the serial mesh on all processors to increase the resolution. In\n \/\/ this example we do 'ref_levels' of uniform refinement. We choose\n \/\/ 'ref_levels' to be the largest number that gives a final mesh with no\n \/\/ more than 10,000 elements.\n {\n int ref_levels =\n (int)floor(log(10000.\/mesh.GetNE())\/log(2.)\/dim);\n for (int l = 0; l < ref_levels; l++)\n {\n mesh.UniformRefinement();\n }\n }\n\n \/\/ 6. Define a parallel mesh by a partitioning of the serial mesh. Refine\n \/\/ this mesh further in parallel to increase the resolution. Once the\n \/\/ parallel mesh is defined, the serial mesh can be deleted.\n ParMesh pmesh(MPI_COMM_WORLD, mesh);\n mesh.Clear();\n {\n int par_ref_levels = 2;\n for (int l = 0; l < par_ref_levels; l++)\n {\n pmesh.UniformRefinement();\n }\n }\n\n \/\/ 7. Define a parallel finite element space on the parallel mesh. Here we\n \/\/ use continuous Lagrange finite elements of the specified order. If\n \/\/ order < 1, we instead use an isoparametric\/isogeometric space.\n FiniteElementCollection *fec;\n bool delete_fec;\n if (order > 0)\n {\n fec = new H1_FECollection(order, dim);\n delete_fec = true;\n }\n else if (pmesh.GetNodes())\n {\n fec = pmesh.GetNodes()->OwnFEC();\n delete_fec = false;\n if (myid == 0)\n {\n cout << \"Using isoparametric FEs: \" << fec->Name() << endl;\n }\n }\n else\n {\n fec = new H1_FECollection(order = 1, dim);\n delete_fec = true;\n }\n ParFiniteElementSpace fespace(&pmesh, fec);\n HYPRE_Int size = fespace.GlobalTrueVSize();\n if (myid == 0)\n {\n cout << \"Number of finite element unknowns: \" << size << endl;\n }\n\n \/\/ 8. Determine the list of true (i.e. parallel conforming) essential\n \/\/ boundary dofs. In this example, the boundary conditions are defined\n \/\/ by marking all the boundary attributes from the mesh as essential\n \/\/ (Dirichlet) and converting them to a list of true dofs.\n Array<int> ess_tdof_list;\n if (pmesh.bdr_attributes.Size())\n {\n Array<int> ess_bdr(pmesh.bdr_attributes.Max());\n ess_bdr = 1;\n fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);\n }\n\n \/\/ 9. Set up the parallel linear form b(.) which corresponds to the\n \/\/ right-hand side of the FEM linear system, which in this case is\n \/\/ (1,phi_i) where phi_i are the basis functions in fespace.\n MFEM_PERF_BEGIN(\"Set up the linear form\");\n ParLinearForm b(&fespace);\n ConstantCoefficient one(1.0);\n b.AddDomainIntegrator(new DomainLFIntegrator(one));\n b.Assemble();\n MFEM_PERF_END(\"Set up the linear form\");\n\n \/\/ 10. Define the solution vector x as a parallel finite element grid function\n \/\/ corresponding to fespace. Initialize x with initial guess of zero,\n \/\/ which satisfies the boundary conditions.\n ParGridFunction x(&fespace);\n x = 0.0;\n\n \/\/ 11. Set up the parallel bilinear form a(.,.) on the finite element space\n \/\/ corresponding to the Laplacian operator -Delta, by adding the Diffusion\n \/\/ domain integrator.\n MFEM_PERF_BEGIN(\"Set up the bilinear form\");\n ParBilinearForm a(&fespace);\n if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }\n a.AddDomainIntegrator(new DiffusionIntegrator(one));\n\n \/\/ 12. Assemble the parallel bilinear form and the corresponding linear\n \/\/ system, applying any necessary transformations such as: parallel\n \/\/ assembly, eliminating boundary conditions, applying conforming\n \/\/ constraints for non-conforming AMR, static condensation, etc.\n if (static_cond) { a.EnableStaticCondensation(); }\n a.Assemble();\n\n OperatorPtr A;\n Vector B, X;\n a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);\n MFEM_PERF_END(\"Set up the bilinear form\");\n \/\/ 13. Solve the linear system A X = B.\n \/\/ * With full assembly, use the BoomerAMG preconditioner from hypre.\n \/\/ * With partial assembly, use Jacobi smoothing, for now.\n MFEM_PERF_BEGIN(\"Solve A X = B\");\n Solver *prec = NULL;\n if (pa)\n {\n if (UsesTensorBasis(fespace))\n {\n prec = new OperatorJacobiSmoother(a, ess_tdof_list);\n }\n }\n else\n {\n prec = new HypreBoomerAMG;\n }\n CGSolver cg(MPI_COMM_WORLD);\n cg.SetRelTol(1e-12);\n cg.SetMaxIter(2000);\n cg.SetPrintLevel(1);\n if (prec) { cg.SetPreconditioner(*prec); }\n cg.SetOperator(*A);\n cg.Mult(B, X);\n delete prec;\n MFEM_PERF_END(\"Solve A X = B\");\n \/\/ 14. Recover the parallel grid function corresponding to X. This is the\n \/\/ local finite element solution on each processor.\n a.RecoverFEMSolution(X, b, x);\n\n \/\/ 15. Save the refined mesh and the solution in parallel. This output can\n \/\/ be viewed later using GLVis: \"glvis -np <np> -m mesh -g sol\".\n MFEM_PERF_BEGIN(\"Save the results\");\n {\n ostringstream mesh_name, sol_name;\n mesh_name << \"mesh.\" << setfill('0') << setw(6) << myid;\n sol_name << \"sol.\" << setfill('0') << setw(6) << myid;\n\n ofstream mesh_ofs(mesh_name.str().c_str());\n mesh_ofs.precision(8);\n pmesh.Print(mesh_ofs);\n\n ofstream sol_ofs(sol_name.str().c_str());\n sol_ofs.precision(8);\n x.Save(sol_ofs);\n }\n MFEM_PERF_END(\"Save the results\");\n \/\/ 16. Send the solution by socket to a GLVis server.\n if (visualization)\n {\n char vishost[] = \"localhost\";\n int visport = 19916;\n socketstream sol_sock(vishost, visport);\n sol_sock << \"parallel \" << num_procs << \" \" << myid << \"\\n\";\n sol_sock.precision(8);\n sol_sock << \"solution\\n\" << pmesh << x << flush;\n }\n\n \/\/ 17. Free the used memory.\n if (delete_fec)\n {\n delete fec;\n }\n \/\/ Flush output before MPI_finalize\n mgr.flush();\n MPI_Finalize();\n\n return 0;\n}\n<commit_msg>Update examples\/caliper\/ex1p.cpp<commit_after>\/\/ MFEM Example 1 - Parallel Version\n\/\/\n\/\/ Compile with: make ex1p\n\/\/\n\/\/ Sample runs: mpirun -np 4 ex1p -m ..\/data\/square-disc.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/star.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/star-mixed.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/escher.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/fichera.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/fichera-mixed.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/toroid-wedge.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/periodic-annulus-sector.msh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/periodic-torus-sector.msh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/square-disc-p2.vtk -o 2\n\/\/ mpirun -np 4 ex1p -m ..\/data\/square-disc-p3.mesh -o 3\n\/\/ mpirun -np 4 ex1p -m ..\/data\/square-disc-nurbs.mesh -o -1\n\/\/ mpirun -np 4 ex1p -m ..\/data\/star-mixed-p2.mesh -o 2\n\/\/ mpirun -np 4 ex1p -m ..\/data\/disc-nurbs.mesh -o -1\n\/\/ mpirun -np 4 ex1p -m ..\/data\/pipe-nurbs.mesh -o -1\n\/\/ mpirun -np 4 ex1p -m ..\/data\/ball-nurbs.mesh -o 2\n\/\/ mpirun -np 4 ex1p -m ..\/data\/fichera-mixed-p2.mesh -o 2\n\/\/ mpirun -np 4 ex1p -m ..\/data\/star-surf.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/square-disc-surf.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/inline-segment.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/amr-quad.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/amr-hex.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/mobius-strip.mesh\n\/\/ mpirun -np 4 ex1p -m ..\/data\/mobius-strip.mesh -o -1 -sc\n\/\/\n\/\/ Device sample runs:\n\/\/ mpirun -np 4 ex1p -pa -d cuda\n\/\/ mpirun -np 4 ex1p -pa -d occa-cuda\n\/\/ mpirun -np 4 ex1p -pa -d raja-omp\n\/\/ mpirun -np 4 ex1p -pa -d ceed-cpu\n\/\/ * mpirun -np 4 ex1p -pa -d ceed-cuda\n\/\/ mpirun -np 4 ex1p -pa -d ceed-cuda:\/gpu\/cuda\/shared\n\/\/ mpirun -np 4 ex1p -m ..\/data\/beam-tet.mesh -pa -d ceed-cpu\n\/\/\n\/\/ Description: This example is a copy of ex1 instrumented with Caliper.\n\/\/ Any option supported by the Caliper ConfigManager can be passed to the\n\/\/ code using a configuration string after -p or --caliper flag. For more\n\/\/ information, the users are referred to the Caliper documentation.\n\/\/ Examples:\n\/\/ mpirun -np 4 ex1p --caliper runtime-report\n\/\/ mpirun -np 4 ex1p --caliper runtime-report,mem.highwatermark,mpi-report\n\/\/\n\/\/The first run will return the default report and the second run will\n\/\/return in addition to the default output the memory high-water mark and time\n\/\/spent in MPI routines.\n\n\n#include \"mfem.hpp\"\n#include <fstream>\n#include <iostream>\n\nusing namespace std;\nusing namespace mfem;\n\nint main(int argc, char *argv[])\n{\n \/\/ 1. Initialize MPI.\n int num_procs, myid;\n MPI_Init(&argc, &argv);\n MPI_Comm_size(MPI_COMM_WORLD, &num_procs);\n MPI_Comm_rank(MPI_COMM_WORLD, &myid);\n \/\/ Define Caliper ConfigManager\n cali::ConfigManager mgr;\n \/\/ Caliper instrumentation\n MFEM_PERF_FUNCTION;\n\n \/\/ 2. Parse command-line options.\n const char *mesh_file = \"..\/..\/data\/star.mesh\";\n int order = 1;\n bool static_cond = false;\n bool pa = false;\n const char *device_config = \"cpu\";\n bool visualization = true;\n const char* cali_config = \"runtime-report\";\n\n OptionsParser args(argc, argv);\n args.AddOption(&mesh_file, \"-m\", \"--mesh\",\n \"Mesh file to use.\");\n args.AddOption(&order, \"-o\", \"--order\",\n \"Finite element order (polynomial degree) or -1 for\"\n \" isoparametric space.\");\n args.AddOption(&static_cond, \"-sc\", \"--static-condensation\", \"-no-sc\",\n \"--no-static-condensation\", \"Enable static condensation.\");\n args.AddOption(&pa, \"-pa\", \"--partial-assembly\", \"-no-pa\",\n \"--no-partial-assembly\", \"Enable Partial Assembly.\");\n args.AddOption(&device_config, \"-d\", \"--device\",\n \"Device configuration string, see Device::Configure().\");\n args.AddOption(&visualization, \"-vis\", \"--visualization\", \"-no-vis\",\n \"--no-visualization\",\n \"Enable or disable GLVis visualization.\");\n args.AddOption(&cali_config, \"-p\", \"--caliper\",\n \"Caliper configuration string.\");\n args.Parse();\n if (!args.Good())\n {\n if (myid == 0)\n {\n args.PrintUsage(cout);\n }\n MPI_Finalize();\n return 1;\n }\n if (myid == 0)\n {\n args.PrintOptions(cout);\n }\n\n \/\/ 3. Enable hardware devices such as GPUs, and programming models such as\n \/\/ CUDA, OCCA, RAJA and OpenMP based on command line options.\n Device device(device_config);\n if (myid == 0) { device.Print(); }\n\n \/\/ Caliper configuration\n mgr.add(cali_config);\n mgr.start();\n\n \/\/ 4. Read the (serial) mesh from the given mesh file on all processors. We\n \/\/ can handle triangular, quadrilateral, tetrahedral, hexahedral, surface\n \/\/ and volume meshes with the same code.\n Mesh mesh(mesh_file, 1, 1);\n int dim = mesh.Dimension();\n\n \/\/ 5. Refine the serial mesh on all processors to increase the resolution. In\n \/\/ this example we do 'ref_levels' of uniform refinement. We choose\n \/\/ 'ref_levels' to be the largest number that gives a final mesh with no\n \/\/ more than 10,000 elements.\n {\n int ref_levels =\n (int)floor(log(10000.\/mesh.GetNE())\/log(2.)\/dim);\n for (int l = 0; l < ref_levels; l++)\n {\n mesh.UniformRefinement();\n }\n }\n\n \/\/ 6. Define a parallel mesh by a partitioning of the serial mesh. Refine\n \/\/ this mesh further in parallel to increase the resolution. Once the\n \/\/ parallel mesh is defined, the serial mesh can be deleted.\n ParMesh pmesh(MPI_COMM_WORLD, mesh);\n mesh.Clear();\n {\n int par_ref_levels = 2;\n for (int l = 0; l < par_ref_levels; l++)\n {\n pmesh.UniformRefinement();\n }\n }\n\n \/\/ 7. Define a parallel finite element space on the parallel mesh. Here we\n \/\/ use continuous Lagrange finite elements of the specified order. If\n \/\/ order < 1, we instead use an isoparametric\/isogeometric space.\n FiniteElementCollection *fec;\n bool delete_fec;\n if (order > 0)\n {\n fec = new H1_FECollection(order, dim);\n delete_fec = true;\n }\n else if (pmesh.GetNodes())\n {\n fec = pmesh.GetNodes()->OwnFEC();\n delete_fec = false;\n if (myid == 0)\n {\n cout << \"Using isoparametric FEs: \" << fec->Name() << endl;\n }\n }\n else\n {\n fec = new H1_FECollection(order = 1, dim);\n delete_fec = true;\n }\n ParFiniteElementSpace fespace(&pmesh, fec);\n HYPRE_Int size = fespace.GlobalTrueVSize();\n if (myid == 0)\n {\n cout << \"Number of finite element unknowns: \" << size << endl;\n }\n\n \/\/ 8. Determine the list of true (i.e. parallel conforming) essential\n \/\/ boundary dofs. In this example, the boundary conditions are defined\n \/\/ by marking all the boundary attributes from the mesh as essential\n \/\/ (Dirichlet) and converting them to a list of true dofs.\n Array<int> ess_tdof_list;\n if (pmesh.bdr_attributes.Size())\n {\n Array<int> ess_bdr(pmesh.bdr_attributes.Max());\n ess_bdr = 1;\n fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);\n }\n\n \/\/ 9. Set up the parallel linear form b(.) which corresponds to the\n \/\/ right-hand side of the FEM linear system, which in this case is\n \/\/ (1,phi_i) where phi_i are the basis functions in fespace.\n MFEM_PERF_BEGIN(\"Set up the linear form\");\n ParLinearForm b(&fespace);\n ConstantCoefficient one(1.0);\n b.AddDomainIntegrator(new DomainLFIntegrator(one));\n b.Assemble();\n MFEM_PERF_END(\"Set up the linear form\");\n\n \/\/ 10. Define the solution vector x as a parallel finite element grid function\n \/\/ corresponding to fespace. Initialize x with initial guess of zero,\n \/\/ which satisfies the boundary conditions.\n ParGridFunction x(&fespace);\n x = 0.0;\n\n \/\/ 11. Set up the parallel bilinear form a(.,.) on the finite element space\n \/\/ corresponding to the Laplacian operator -Delta, by adding the Diffusion\n \/\/ domain integrator.\n MFEM_PERF_BEGIN(\"Set up the bilinear form\");\n ParBilinearForm a(&fespace);\n if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }\n a.AddDomainIntegrator(new DiffusionIntegrator(one));\n\n \/\/ 12. Assemble the parallel bilinear form and the corresponding linear\n \/\/ system, applying any necessary transformations such as: parallel\n \/\/ assembly, eliminating boundary conditions, applying conforming\n \/\/ constraints for non-conforming AMR, static condensation, etc.\n if (static_cond) { a.EnableStaticCondensation(); }\n a.Assemble();\n\n OperatorPtr A;\n Vector B, X;\n a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);\n MFEM_PERF_END(\"Set up the bilinear form\");\n \/\/ 13. Solve the linear system A X = B.\n \/\/ * With full assembly, use the BoomerAMG preconditioner from hypre.\n \/\/ * With partial assembly, use Jacobi smoothing, for now.\n MFEM_PERF_BEGIN(\"Solve A X = B\");\n Solver *prec = NULL;\n if (pa)\n {\n if (UsesTensorBasis(fespace))\n {\n prec = new OperatorJacobiSmoother(a, ess_tdof_list);\n }\n }\n else\n {\n prec = new HypreBoomerAMG;\n }\n CGSolver cg(MPI_COMM_WORLD);\n cg.SetRelTol(1e-12);\n cg.SetMaxIter(2000);\n cg.SetPrintLevel(1);\n if (prec) { cg.SetPreconditioner(*prec); }\n cg.SetOperator(*A);\n cg.Mult(B, X);\n delete prec;\n MFEM_PERF_END(\"Solve A X = B\");\n \/\/ 14. Recover the parallel grid function corresponding to X. This is the\n \/\/ local finite element solution on each processor.\n a.RecoverFEMSolution(X, b, x);\n\n \/\/ 15. Save the refined mesh and the solution in parallel. This output can\n \/\/ be viewed later using GLVis: \"glvis -np <np> -m mesh -g sol\".\n MFEM_PERF_BEGIN(\"Save the results\");\n {\n ostringstream mesh_name, sol_name;\n mesh_name << \"mesh.\" << setfill('0') << setw(6) << myid;\n sol_name << \"sol.\" << setfill('0') << setw(6) << myid;\n\n ofstream mesh_ofs(mesh_name.str().c_str());\n mesh_ofs.precision(8);\n pmesh.Print(mesh_ofs);\n\n ofstream sol_ofs(sol_name.str().c_str());\n sol_ofs.precision(8);\n x.Save(sol_ofs);\n }\n MFEM_PERF_END(\"Save the results\");\n \/\/ 16. Send the solution by socket to a GLVis server.\n if (visualization)\n {\n char vishost[] = \"localhost\";\n int visport = 19916;\n socketstream sol_sock(vishost, visport);\n sol_sock << \"parallel \" << num_procs << \" \" << myid << \"\\n\";\n sol_sock.precision(8);\n sol_sock << \"solution\\n\" << pmesh << x << flush;\n }\n\n \/\/ 17. Free the used memory.\n if (delete_fec)\n {\n delete fec;\n }\n \/\/ Flush output before MPI_finalize\n mgr.flush();\n MPI_Finalize();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n @brief Implementation\n\n @date 2015\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\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\/\/ \thttp:\/\/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\/\/ Internal Includes\n#include \"TrackerRemoteFactory.h\"\n#include \"VRPNConnectionCollection.h\"\n#include <osvr\/Client\/ClientInterface.h>\n#include <osvr\/Util\/QuatlibInteropC.h>\n#include <osvr\/Util\/EigenInterop.h>\n#include <osvr\/Common\/PathTreeFull.h>\n#include <osvr\/Util\/ChannelCountC.h>\n#include <osvr\/Util\/UniquePtr.h>\n#include <osvr\/Common\/Transform.h>\n#include <osvr\/Common\/DecomposeOriginalSource.h>\n#include <osvr\/Common\/JSONTransformVisitor.h>\n#include \"PureClientContext.h\"\n#include \"InterfaceTree.h\"\n#include <osvr\/Util\/Verbosity.h>\n\n\/\/ Library\/third-party includes\n#include <vrpn_Tracker.h>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/any.hpp>\n#include <boost\/variant\/get.hpp>\n#include <json\/value.h>\n#include <json\/reader.h>\n\n\/\/ Standard includes\n\/\/ - none\n\nnamespace osvr {\nnamespace client {\n class VRPNTrackerHandler : public RemoteHandler {\n public:\n struct Options {\n Options()\n : reportPose(false), reportPosition(false),\n reportOrientation(false) {}\n bool reportPose;\n bool reportPosition;\n bool reportOrientation;\n };\n VRPNTrackerHandler(vrpn_ConnectionPtr const &conn, const char *src,\n Options const &options, common::Transform const &t,\n boost::optional<int> sensor, InterfaceList &ifaces)\n : m_remote(new vrpn_Tracker_Remote(src, conn.get())),\n m_transform(t), m_interfaces(ifaces), m_opts(options) {\n m_remote->register_change_handler(this, &VRPNTrackerHandler::handle,\n sensor.get_value_or(-1));\n OSVR_DEV_VERBOSE(\"Constructed a TrackerHandler for \"\n << src << \" sensor \" << sensor.get_value_or(-1));\n }\n virtual ~VRPNTrackerHandler() {}\n\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n static void VRPN_CALLBACK handle(void *userdata, vrpn_TRACKERCB info) {\n auto self = static_cast<VRPNTrackerHandler *>(userdata);\n self->m_handle(info);\n }\n virtual void update() { m_remote->mainloop(); }\n\n private:\n void m_handle(vrpn_TRACKERCB const &info) {\n OSVR_PoseReport report;\n report.sensor = info.sensor;\n OSVR_TimeValue timestamp;\n osvrStructTimevalToTimeValue(×tamp, &(info.msg_time));\n osvrQuatFromQuatlib(&(report.pose.rotation), info.quat);\n osvrVec3FromQuatlib(&(report.pose.translation), info.pos);\n Eigen::Matrix4d pose =\n m_transform.transform(util::fromPose(report.pose).matrix());\n util::toPose(pose, report.pose);\n\n if (m_opts.reportPose) {\n for (auto &iface : m_interfaces) {\n iface->triggerCallbacks(timestamp, report);\n }\n }\n\n if (m_opts.reportPosition) {\n OSVR_PositionReport positionReport;\n positionReport.sensor = info.sensor;\n positionReport.xyz = report.pose.translation;\n for (auto &iface : m_interfaces) {\n iface->triggerCallbacks(timestamp, positionReport);\n }\n }\n\n if (m_opts.reportOrientation) {\n OSVR_OrientationReport oriReport;\n oriReport.sensor = info.sensor;\n oriReport.rotation = report.pose.rotation;\n\n for (auto &iface : m_interfaces) {\n iface->triggerCallbacks(timestamp, oriReport);\n }\n }\n }\n unique_ptr<vrpn_Tracker_Remote> m_remote;\n common::Transform m_transform;\n InterfaceList &m_interfaces;\n Options m_opts;\n };\n\n TrackerRemoteFactory::TrackerRemoteFactory(\n VRPNConnectionCollection const &conns)\n : m_conns(conns) {}\n\n shared_ptr<RemoteHandler> TrackerRemoteFactory::\n operator()(common::OriginalSource const &source, InterfaceList &ifaces) {\n\n shared_ptr<RemoteHandler> ret;\n\n \/\/\/ @todo set this struct correctly from the descriptor, or perhaps\n \/\/\/ the path?\n VRPNTrackerHandler::Options opts;\n\n auto interfaceType = source.getInterfaceName();\n if (\"position\" == interfaceType) {\n opts.reportPosition = true;\n } else if (\"orientation\" == interfaceType) {\n opts.reportOrientation = true;\n } else {\n \/\/\/ pose and tracker both imply full reports (?)\n opts.reportOrientation = true;\n opts.reportPosition = true;\n opts.reportPose = true;\n }\n\n auto const &devElt = source.getDeviceElement();\n\n common::Transform xform{};\n if (source.hasTransform()) {\n Json::Value val;\n Json::Reader reader;\n if (reader.parse(source.getTransform(), val)) {\n common::JSONTransformVisitor xformParse(val);\n xform = xformParse.getTransform();\n }\n }\n\n \/\/\/ @todo find out why make_shared causes a crash here\n ret.reset(new VRPNTrackerHandler(\n m_conns.getConnection(devElt), devElt.getFullDeviceName().c_str(),\n opts, xform, source.getSensorNumber(), ifaces));\n return ret;\n }\n\n} \/\/ namespace client\n} \/\/ namespace osvr<commit_msg>Unregister callback in Tracker remote<commit_after>\/** @file\n @brief Implementation\n\n @date 2015\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\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\/\/ \thttp:\/\/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\/\/ Internal Includes\n#include \"TrackerRemoteFactory.h\"\n#include \"VRPNConnectionCollection.h\"\n#include <osvr\/Client\/ClientInterface.h>\n#include <osvr\/Util\/QuatlibInteropC.h>\n#include <osvr\/Util\/EigenInterop.h>\n#include <osvr\/Common\/PathTreeFull.h>\n#include <osvr\/Util\/ChannelCountC.h>\n#include <osvr\/Util\/UniquePtr.h>\n#include <osvr\/Common\/Transform.h>\n#include <osvr\/Common\/DecomposeOriginalSource.h>\n#include <osvr\/Common\/JSONTransformVisitor.h>\n#include \"PureClientContext.h\"\n#include \"InterfaceTree.h\"\n#include <osvr\/Util\/Verbosity.h>\n\n\/\/ Library\/third-party includes\n#include <vrpn_Tracker.h>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/any.hpp>\n#include <boost\/variant\/get.hpp>\n#include <json\/value.h>\n#include <json\/reader.h>\n\n\/\/ Standard includes\n\/\/ - none\n\nnamespace osvr {\nnamespace client {\n class VRPNTrackerHandler : public RemoteHandler {\n public:\n struct Options {\n Options()\n : reportPose(false), reportPosition(false),\n reportOrientation(false) {}\n bool reportPose;\n bool reportPosition;\n bool reportOrientation;\n };\n VRPNTrackerHandler(vrpn_ConnectionPtr const &conn, const char *src,\n Options const &options, common::Transform const &t,\n boost::optional<int> sensor, InterfaceList &ifaces)\n : m_remote(new vrpn_Tracker_Remote(src, conn.get())),\n m_transform(t), m_interfaces(ifaces), m_opts(options),\n m_sensor(sensor) {\n m_remote->register_change_handler(this, &VRPNTrackerHandler::handle,\n sensor.get_value_or(-1));\n OSVR_DEV_VERBOSE(\"Constructed a TrackerHandler for \"\n << src << \" sensor \" << sensor.get_value_or(-1));\n }\n virtual ~VRPNTrackerHandler() {\n m_remote->unregister_change_handler(\n this, &VRPNTrackerHandler::handle, m_sensor.get_value_or(-1));\n }\n\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n static void VRPN_CALLBACK handle(void *userdata, vrpn_TRACKERCB info) {\n auto self = static_cast<VRPNTrackerHandler *>(userdata);\n self->m_handle(info);\n }\n virtual void update() { m_remote->mainloop(); }\n\n private:\n void m_handle(vrpn_TRACKERCB const &info) {\n OSVR_PoseReport report;\n report.sensor = info.sensor;\n OSVR_TimeValue timestamp;\n osvrStructTimevalToTimeValue(×tamp, &(info.msg_time));\n osvrQuatFromQuatlib(&(report.pose.rotation), info.quat);\n osvrVec3FromQuatlib(&(report.pose.translation), info.pos);\n Eigen::Matrix4d pose =\n m_transform.transform(util::fromPose(report.pose).matrix());\n util::toPose(pose, report.pose);\n\n if (m_opts.reportPose) {\n for (auto &iface : m_interfaces) {\n iface->triggerCallbacks(timestamp, report);\n }\n }\n\n if (m_opts.reportPosition) {\n OSVR_PositionReport positionReport;\n positionReport.sensor = info.sensor;\n positionReport.xyz = report.pose.translation;\n for (auto &iface : m_interfaces) {\n iface->triggerCallbacks(timestamp, positionReport);\n }\n }\n\n if (m_opts.reportOrientation) {\n OSVR_OrientationReport oriReport;\n oriReport.sensor = info.sensor;\n oriReport.rotation = report.pose.rotation;\n\n for (auto &iface : m_interfaces) {\n iface->triggerCallbacks(timestamp, oriReport);\n }\n }\n }\n unique_ptr<vrpn_Tracker_Remote> m_remote;\n common::Transform m_transform;\n InterfaceList &m_interfaces;\n Options m_opts;\n boost::optional<int> m_sensor;\n };\n\n TrackerRemoteFactory::TrackerRemoteFactory(\n VRPNConnectionCollection const &conns)\n : m_conns(conns) {}\n\n shared_ptr<RemoteHandler> TrackerRemoteFactory::\n operator()(common::OriginalSource const &source, InterfaceList &ifaces) {\n\n shared_ptr<RemoteHandler> ret;\n\n \/\/\/ @todo set this struct correctly from the descriptor, or perhaps\n \/\/\/ the path?\n VRPNTrackerHandler::Options opts;\n\n auto interfaceType = source.getInterfaceName();\n if (\"position\" == interfaceType) {\n opts.reportPosition = true;\n } else if (\"orientation\" == interfaceType) {\n opts.reportOrientation = true;\n } else {\n \/\/\/ pose and tracker both imply full reports (?)\n opts.reportOrientation = true;\n opts.reportPosition = true;\n opts.reportPose = true;\n }\n\n auto const &devElt = source.getDeviceElement();\n\n common::Transform xform{};\n if (source.hasTransform()) {\n Json::Value val;\n Json::Reader reader;\n if (reader.parse(source.getTransform(), val)) {\n common::JSONTransformVisitor xformParse(val);\n xform = xformParse.getTransform();\n }\n }\n\n \/\/\/ @todo find out why make_shared causes a crash here\n ret.reset(new VRPNTrackerHandler(\n m_conns.getConnection(devElt), devElt.getFullDeviceName().c_str(),\n opts, xform, source.getSensorNumber(), ifaces));\n return ret;\n }\n\n} \/\/ namespace client\n} \/\/ namespace osvr<|endoftext|>"} {"text":"<commit_before>\/*\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 <iostream>\n#include <fstream>\n#include <iterator>\n#include <iomanip>\n\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent_info.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include \"libtorrent\/magnet_uri.hpp\"\n\n\nint main(int argc, char* argv[])\n{\n\tusing namespace libtorrent;\n\n\tif (argc != 2)\n\t{\n\t\tstd::cerr << \"usage: dump_torrent torrent-file\\n\";\n\t\treturn 1;\n\t}\n\n\tint size = file_size(argv[1]);\n\tif (size > 10 * 1000000)\n\t{\n\t\tstd::cerr << \"file too big (\" << size << \"), aborting\\n\";\n\t\treturn 1;\n\t}\n\tstd::vector<char> buf(size);\n\tstd::ifstream(argv[1], std::ios_base::binary).read(&buf[0], size);\n\tlazy_entry e;\n\tint ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);\n\n\tif (ret != 0)\n\t{\n\t\tstd::cerr << \"invalid bencoding: \" << ret << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::cout << \"\\n\\n----- raw info -----\\n\\n\";\n\tstd::cout << print_entry(e) << std::endl;\n\n\terror_code ec;\n\ttorrent_info t(e, ec);\n\tif (ec)\n\t{\n\t\tstd::cout << ec.message() << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ print info about torrent\n\tstd::cout << \"\\n\\n----- torrent file info -----\\n\\n\";\n\tstd::cout << \"nodes:\\n\";\n\ttypedef std::vector<std::pair<std::string, int> > node_vec;\n\tnode_vec const& nodes = t.nodes();\n\tfor (node_vec::const_iterator i = nodes.begin(), end(nodes.end());\n\t\ti != end; ++i)\n\t{\n\t\tstd::cout << i->first << \":\" << i->second << \"\\n\";\n\t}\n\tstd::cout << \"trackers:\\n\";\n\tfor (std::vector<announce_entry>::const_iterator i = t.trackers().begin();\n\t\ti != t.trackers().end(); ++i)\n\t{\n\t\tstd::cout << i->tier << \": \" << i->url << \"\\n\";\n\t}\n\n\tstd::cout << \"number of pieces: \" << t.num_pieces() << \"\\n\";\n\tstd::cout << \"piece length: \" << t.piece_length() << \"\\n\";\n\tchar ih[41];\n\tto_hex((char const*)&t.info_hash()[0], 20, ih);\n\tstd::cout << \"info hash: \" << ih << \"\\n\";\n\tstd::cout << \"comment: \" << t.comment() << \"\\n\";\n\tstd::cout << \"created by: \" << t.creator() << \"\\n\";\n\tstd::cout << \"magnet link: \" << make_magnet_uri(t) << \"\\n\";\n\tstd::cout << \"name: \" << t.name() << \"\\n\";\n\tstd::cout << \"files:\\n\";\n\tint index = 0;\n\tfor (torrent_info::file_iterator i = t.begin_files();\n\t\ti != t.end_files(); ++i, ++index)\n\t{\n\t\tint first = t.map_file(index, 0, 0).piece;\n\t\tint last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;\n\t\tstd::cout << \" \" << std::setw(11) << i->size\n\t\t\t<< \" \"\n\t\t\t<< (i->pad_file?'p':'-')\n\t\t\t<< (i->executable_attribute?'x':'-')\n\t\t\t<< (i->hidden_attribute?'h':'-')\n\t\t\t<< (i->symlink_attribute?'l':'-')\n\t\t\t<< \" \"\n\t\t\t<< \"[ \" << std::setw(4) << first << \", \" << std::setw(4) << last << \" ]\\t\"\n\t\t\t<< i->path;\n\t\tif (i->symlink_attribute)\n\t\t\tstd::cout << \" -> \" << i->symlink_path;\n\t\tstd::cout << std::endl;\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>replaced iostream in dump_torrent example<commit_after>\/*\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\/entry.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent_info.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include \"libtorrent\/magnet_uri.hpp\"\n\nint main(int argc, char* argv[])\n{\n\tusing namespace libtorrent;\n\n\tif (argc != 2)\n\t{\n\t\tfputs(\"usage: dump_torrent torrent-file\\n\", stderr);\n\t\treturn 1;\n\t}\n\n\tint size = file_size(argv[1]);\n\tif (size > 10 * 1000000)\n\t{\n\t\tfprintf(stderr, \"file too big (%d), aborting\\n\", size);\n\t\treturn 1;\n\t}\n\tstd::vector<char> buf(size);\n\tint ret = load_file(argv[1], buf);\n\tif (ret != 0)\n\t{\n\t\tfprintf(stderr, \"failed to load file: %d\\n\", ret);\n\t\treturn 1;\n\t}\n\tlazy_entry e;\n\tret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);\n\n\tif (ret != 0)\n\t{\n\t\tfprintf(stderr, \"invalid bencoding: %d\\n\", ret);\n\t\treturn 1;\n\t}\n\n\tprintf(\"\\n\\n----- raw info -----\\n\\n%s\\n\", print_entry(e).c_str());\n\n\terror_code ec;\n\ttorrent_info t(e, ec);\n\tif (ec)\n\t{\n\t\tfprintf(stderr, \"%s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n\n\t\/\/ print info about torrent\n\tprintf(\"\\n\\n----- torrent file info -----\\n\\n\"\n\t\t\"nodes:\\n\");\n\n\ttypedef std::vector<std::pair<std::string, int> > node_vec;\n\tnode_vec const& nodes = t.nodes();\n\tfor (node_vec::const_iterator i = nodes.begin(), end(nodes.end());\n\t\ti != end; ++i)\n\t{\n\t\tprintf(\"%s: %d\\n\", i->first.c_str(), i->second);\n\t}\n\tputs(\"trackers:\\n\");\n\tfor (std::vector<announce_entry>::const_iterator i = t.trackers().begin();\n\t\ti != t.trackers().end(); ++i)\n\t{\n\t\tprintf(\"%2d: %s\\n\", i->tier, i->url.c_str());\n\t}\n\n\tchar ih[41];\n\tto_hex((char const*)&t.info_hash()[0], 20, ih);\n\tprintf(\"number of pieces: %d\\n\"\n\t\t\"piece length: %d\\n\"\n\t\t\"info hash: %s\\n\"\n\t\t\"comment: %s\\n\"\n\t\t\"created by: %s\\n\"\n\t\t\"magnet link: %s\\n\"\n\t\t\"name: %s\\n\"\n\t\t\"files:\\n\"\n\t\t, t.num_pieces()\n\t\t, t.piece_length()\n\t\t, ih\n\t\t, t.comment().c_str()\n\t\t, t.creator().c_str()\n\t\t, make_magnet_uri(t).c_str()\n\t\t, t.name().c_str());\n\tint index = 0;\n\tfor (torrent_info::file_iterator i = t.begin_files();\n\t\ti != t.end_files(); ++i, ++index)\n\t{\n\t\tint first = t.map_file(index, 0, 0).piece;\n\t\tint last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;\n\t\tprintf(\" %11\"PRId64\" %c%c%c%c [ %4d, %4d ] %s %s%s\\n\"\n\t\t\t, i->size\n\t\t\t, (i->pad_file?'p':'-')\n\t\t\t, (i->executable_attribute?'x':'-')\n\t\t\t, (i->hidden_attribute?'h':'-')\n\t\t\t, (i->symlink_attribute?'l':'-')\n\t\t\t, first, last, i->path.c_str()\n\t\t\t, i->symlink_attribute ? \"-> \": \"\"\n\t\t\t, i->symlink_attribute ? i->symlink_path.c_str() : \"\");\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"logxx\/logxx.h\"\n#include \"dicom\/dicom.h\"\n#include \"dirent.h\"\n#include <fstream>\n\nstatic logxx::Log cLog(\"extractor\");\n\nstd::ostream& operator<<(std::ostream& s, const Dicom & d){\n s << d.GetId() << \",\" << d.GetDate() << \",\" << d.GetName() << \",\" << d.GetPet();\n return s;\n}\n\nint main(int argc, char **argv){\n\tS_LOG(\"main\");\n logxx::GlobalLogLevel(logxx::warning);\n if (argc < 2){\n log(logxx::error) << \"A path with dicom files should be specified\" << logxx::endl;\n return 1;\n } else {\n std::string path(argv[1]); \n if (path[path.length()-1] != '\/')\n path += '\/';\n \n std::string csvFile = path + \"out.csv\";\n std::ofstream out(csvFile);\n if (out.good()){\n DIR *dir;\n if ((dir = opendir (path.c_str())) != nullptr) {\n dirent *ent;\n while ((ent = readdir (dir)) != nullptr) {\n if (ent->d_type == DT_REG){\n std::string fName = ent->d_name;\n log(logxx::debug) << \"{\" << fName << \"}\" << logxx::endl;\n Dicom dicom(path + fName);\n if (dicom.Parse()){\n \/\/ cppcheck-suppress constStatement\n log(logxx::notice) << \"{\" << fName << \"} Parsed\" << logxx::endl;\n out << fName << \",\" << dicom << std::endl;\n\n } else {\n \/\/ cppcheck-suppress constStatement\n log(logxx::notice) << \"{\" << fName << \"} Not parsed\" << logxx::endl;\n }\n }\n }\n closedir (dir);\n } else {\n log(logxx::error) << \"Can't open path {\" << path << \"}\" << logxx::endl;\n return 1;\n }\n return 0;\n } else {\n log(logxx::error) << \"Can't open file {\" << csvFile << \"} for writing\" << logxx::endl;\n return 1;\n }\n }\n}\n<commit_msg>Tiny refactoring<commit_after>#include \"logxx\/logxx.h\"\n#include \"dicom\/dicom.h\"\n#include \"dirent.h\"\n#include <fstream>\n\nstatic logxx::Log cLog(\"extractor\");\n\nstd::ostream& operator<<(std::ostream& s, const Dicom & d){\n s << d.GetId() << \",\" << d.GetDate() << \",\" << d.GetName() << \",\" << d.GetPet();\n return s;\n}\n\nint main(int argc, char **argv){\n\tS_LOG(\"main\");\n logxx::GlobalLogLevel(logxx::warning);\n if (argc < 2){\n log(logxx::error) << \"A path with dicom files should be specified\" << logxx::endl;\n return 1;\n } else {\n std::string path(argv[1]); \n if (path[path.length()-1] != '\/')\n path += '\/';\n \n std::string csvFile = path + \"out.csv\";\n std::ofstream out(csvFile);\n if (out.good()){\n DIR *dir;\n if ((dir = opendir (path.c_str())) != nullptr) {\n dirent *ent;\n while ((ent = readdir (dir)) != nullptr) {\n if (ent->d_type == DT_REG){\n std::string fName = ent->d_name;\n log(logxx::debug) << \"{\" << fName << \"}\" << logxx::endl;\n Dicom dicom(path + fName);\n if (dicom.Parse()){\n \/\/ cppcheck-suppress constStatement\n log(logxx::notice) << \"{\" << fName << \"} Parsed\" << logxx::endl;\n out << fName << \",\" << dicom << std::endl;\n\n } else {\n \/\/ cppcheck-suppress constStatement\n log(logxx::notice) << \"{\" << fName << \"} Not parsed\" << logxx::endl;\n }\n }\n }\n closedir (dir);\n return 0;\n } else {\n log(logxx::error) << \"Can't open path {\" << path << \"}\" << logxx::endl;\n return 1;\n }\n } else {\n log(logxx::error) << \"Can't open file {\" << csvFile << \"} for writing\" << logxx::endl;\n return 1;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ctrcommon\/common.hpp>\r\n\r\n#include <sstream>\r\n#include <iomanip>\r\n\r\ntypedef enum {\r\n INSTALL,\r\n DELETE\r\n} Mode;\r\n\r\nint main(int argc, char **argv) {\r\n if(!platform_init()) {\r\n return 0;\r\n }\r\n\r\n std::vector<std::string> extensions;\r\n extensions.push_back(\"cia\");\r\n\r\n MediaType destination = SD;\r\n Mode mode = INSTALL;\r\n bool netInstall = false;\r\n u64 freeSpace = fs_get_free_space(destination);\r\n auto onLoop = [&]() {\r\n bool breakLoop = false;\r\n if(input_is_pressed(BUTTON_L)) {\r\n if(destination == SD) {\r\n destination = NAND;\r\n } else {\r\n destination = SD;\r\n }\r\n\r\n freeSpace = fs_get_free_space(destination);\r\n if(mode == DELETE) {\r\n breakLoop = true;\r\n }\r\n }\r\n\r\n if(input_is_pressed(BUTTON_R)) {\r\n if(mode == INSTALL) {\r\n mode = DELETE;\r\n } else {\r\n mode = INSTALL;\r\n }\r\n\r\n breakLoop = true;\r\n }\r\n\r\n if(input_is_pressed(BUTTON_Y)) {\r\n netInstall = true;\r\n breakLoop = true;\r\n }\r\n\r\n std::stringstream stream;\r\n stream << \"Free Space: \" << freeSpace << \" bytes (\" << std::fixed << std::setprecision(2) << freeSpace \/ 1024.0f \/ 1024.0f << \"MB)\" << \"\\n\";\r\n stream << \"Destination: \" << (destination == NAND ? \"NAND\" : \"SD\") << \", Mode: \" << (mode == INSTALL ? \"Install\" : \"Delete\") << \"\\n\";\r\n stream << \"L - Switch Destination, R - Switch Mode\" << \"\\n\";\r\n stream << \"Y - Receive an app over the network\" << \"\\n\";\r\n\r\n std::string str = stream.str();\r\n screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) \/ 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);\r\n\r\n return breakLoop;\r\n };\r\n\r\n auto onProgress = [&](int progress) {\r\n ui_display_progress(\"Installing\", \"Press B to cancel.\", true, progress);\r\n input_poll();\r\n return !input_is_pressed(BUTTON_B);\r\n };\r\n\r\n while(platform_is_running()) {\r\n std::string targetInstall;\r\n App targetDelete;\r\n bool obtained = false;\r\n if(mode == INSTALL) {\r\n obtained = ui_select_file(&targetInstall, \"sdmc:\", extensions, onLoop);\r\n } else if(mode == DELETE) {\r\n obtained = ui_select_app(&targetDelete, destination, onLoop);\r\n }\r\n\r\n if(netInstall) {\r\n netInstall = false;\r\n\r\n \/\/ Clear bottom screen on both buffers.\r\n screen_begin_draw(BOTTOM_SCREEN);\r\n screen_clear(0, 0, 0);\r\n screen_end_draw();\r\n screen_swap_buffers();\r\n\r\n screen_begin_draw(BOTTOM_SCREEN);\r\n screen_clear(0, 0, 0);\r\n screen_end_draw();\r\n screen_swap_buffers();\r\n\r\n RemoteFile file = ui_accept_remote_file();\r\n if(file.socket == -1) {\r\n continue;\r\n }\r\n\r\n std::stringstream confirmStream;\r\n confirmStream << \"Install the received application?\" << \"\\n\";\r\n confirmStream << \"Size: \" << file.fileSize << \" bytes (\" << std::fixed << std::setprecision(2) << file.fileSize \/ 1024.0f \/ 1024.0f << \"MB)\" << \"\\n\";\r\n if(ui_prompt(confirmStream.str(), true)) {\r\n int ret = app_install_socket(destination, file.socket, file.fileSize, onProgress);\r\n std::stringstream resultMsg;\r\n resultMsg << \"Install \";\r\n if(ret == 0) {\r\n resultMsg << \"succeeded!\";\r\n } else if(ret == -2) {\r\n resultMsg << \"cancelled!\";\r\n } else {\r\n resultMsg << \"failed! Error: 0x\" << std::hex << ret;\r\n }\r\n\r\n ui_prompt(resultMsg.str(), false);\r\n }\r\n\r\n socket_close(file.socket);\r\n continue;\r\n }\r\n\r\n if(obtained) {\r\n std::stringstream prompt;\r\n if(mode == INSTALL) {\r\n prompt << \"Install \";\r\n } else if(mode == DELETE) {\r\n prompt << \"Delete \";\r\n }\r\n\r\n prompt << \"the selected title?\";\r\n if(ui_prompt(prompt.str(), true)) {\r\n int ret = 0;\r\n if(mode == INSTALL) {\r\n ret = app_install_file(destination, targetInstall, onProgress);\r\n } else if(mode == DELETE) {\r\n ui_display_message(\"Deleting title...\");\r\n ret = app_delete(targetDelete);\r\n }\r\n\r\n std::stringstream resultMsg;\r\n if(mode == INSTALL) {\r\n resultMsg << \"Install \";\r\n } else if(mode == DELETE) {\r\n resultMsg << \"Delete \";\r\n }\r\n\r\n if(ret == 0) {\r\n resultMsg << \"succeeded!\";\r\n } else if(ret == -2) {\r\n resultMsg << \"cancelled!\";\r\n } else {\r\n resultMsg << \"failed! Error: 0x\" << std::hex << ret;\r\n }\r\n\r\n ui_prompt(resultMsg.str(), false);\r\n\r\n freeSpace = fs_get_free_space(destination);\r\n }\r\n }\r\n }\r\n\r\n platform_cleanup();\r\n return 0;\r\n}\r\n<commit_msg>Update for ctrcommon changes.<commit_after>#include <ctrcommon\/common.hpp>\r\n\r\n#include <sstream>\r\n#include <iomanip>\r\n#include <stdio.h>\r\n\r\ntypedef enum {\r\n INSTALL,\r\n DELETE\r\n} Mode;\r\n\r\nint main(int argc, char **argv) {\r\n if(!platform_init()) {\r\n return 0;\r\n }\r\n\r\n std::vector<std::string> extensions;\r\n extensions.push_back(\"cia\");\r\n\r\n MediaType destination = SD;\r\n Mode mode = INSTALL;\r\n bool netInstall = false;\r\n u64 freeSpace = fs_get_free_space(destination);\r\n auto onLoop = [&]() {\r\n bool breakLoop = false;\r\n if(input_is_pressed(BUTTON_L)) {\r\n if(destination == SD) {\r\n destination = NAND;\r\n } else {\r\n destination = SD;\r\n }\r\n\r\n freeSpace = fs_get_free_space(destination);\r\n if(mode == DELETE) {\r\n breakLoop = true;\r\n }\r\n }\r\n\r\n if(input_is_pressed(BUTTON_R)) {\r\n if(mode == INSTALL) {\r\n mode = DELETE;\r\n } else {\r\n mode = INSTALL;\r\n }\r\n\r\n breakLoop = true;\r\n }\r\n\r\n if(input_is_pressed(BUTTON_Y)) {\r\n netInstall = true;\r\n breakLoop = true;\r\n }\r\n\r\n std::stringstream stream;\r\n stream << \"Free Space: \" << freeSpace << \" bytes (\" << std::fixed << std::setprecision(2) << freeSpace \/ 1024.0f \/ 1024.0f << \"MB)\" << \"\\n\";\r\n stream << \"Destination: \" << (destination == NAND ? \"NAND\" : \"SD\") << \", Mode: \" << (mode == INSTALL ? \"Install\" : \"Delete\") << \"\\n\";\r\n stream << \"L - Switch Destination, R - Switch Mode\" << \"\\n\";\r\n stream << \"Y - Receive an app over the network\" << \"\\n\";\r\n\r\n std::string str = stream.str();\r\n screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) \/ 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);\r\n\r\n return breakLoop;\r\n };\r\n\r\n auto onProgress = [&](int progress) {\r\n ui_display_progress(\"Installing\", \"Press B to cancel.\", true, progress);\r\n input_poll();\r\n return !input_is_pressed(BUTTON_B);\r\n };\r\n\r\n while(platform_is_running()) {\r\n std::string targetInstall;\r\n App targetDelete;\r\n bool obtained = false;\r\n if(mode == INSTALL) {\r\n obtained = ui_select_file(&targetInstall, \"sdmc:\", extensions, onLoop);\r\n } else if(mode == DELETE) {\r\n obtained = ui_select_app(&targetDelete, destination, onLoop);\r\n }\r\n\r\n if(netInstall) {\r\n netInstall = false;\r\n\r\n \/\/ Clear bottom screen on both buffers.\r\n screen_begin_draw(BOTTOM_SCREEN);\r\n screen_clear(0, 0, 0);\r\n screen_end_draw();\r\n screen_swap_buffers();\r\n\r\n screen_begin_draw(BOTTOM_SCREEN);\r\n screen_clear(0, 0, 0);\r\n screen_end_draw();\r\n screen_swap_buffers();\r\n\r\n RemoteFile file = ui_accept_remote_file();\r\n if(file.fd == NULL) {\r\n continue;\r\n }\r\n\r\n std::stringstream confirmStream;\r\n confirmStream << \"Install the received application?\" << \"\\n\";\r\n confirmStream << \"Size: \" << file.fileSize << \" bytes (\" << std::fixed << std::setprecision(2) << file.fileSize \/ 1024.0f \/ 1024.0f << \"MB)\" << \"\\n\";\r\n if(ui_prompt(confirmStream.str(), true)) {\r\n int ret = app_install(destination, file.fd, file.fileSize, onProgress);\r\n std::stringstream resultMsg;\r\n resultMsg << \"Install \";\r\n if(ret == 0) {\r\n resultMsg << \"succeeded!\";\r\n } else if(ret == -2) {\r\n resultMsg << \"cancelled!\";\r\n } else {\r\n resultMsg << \"failed! Error: 0x\" << std::hex << ret;\r\n }\r\n\r\n ui_prompt(resultMsg.str(), false);\r\n }\r\n\r\n fclose(file.fd);\r\n continue;\r\n }\r\n\r\n if(obtained) {\r\n std::stringstream prompt;\r\n if(mode == INSTALL) {\r\n prompt << \"Install \";\r\n } else if(mode == DELETE) {\r\n prompt << \"Delete \";\r\n }\r\n\r\n prompt << \"the selected title?\";\r\n if(ui_prompt(prompt.str(), true)) {\r\n int ret = 0;\r\n if(mode == INSTALL) {\r\n ret = app_install_file(destination, targetInstall, onProgress);\r\n } else if(mode == DELETE) {\r\n ui_display_message(\"Deleting title...\");\r\n ret = app_delete(targetDelete);\r\n }\r\n\r\n std::stringstream resultMsg;\r\n if(mode == INSTALL) {\r\n resultMsg << \"Install \";\r\n } else if(mode == DELETE) {\r\n resultMsg << \"Delete \";\r\n }\r\n\r\n if(ret == 0) {\r\n resultMsg << \"succeeded!\";\r\n } else if(ret == -2) {\r\n resultMsg << \"cancelled!\";\r\n } else {\r\n resultMsg << \"failed! Error: 0x\" << std::hex << ret;\r\n }\r\n\r\n ui_prompt(resultMsg.str(), false);\r\n\r\n freeSpace = fs_get_free_space(destination);\r\n }\r\n }\r\n }\r\n\r\n platform_cleanup();\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*************** <auto-copyright.pl BEGIN do not edit this line> **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\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\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** <auto-copyright.pl END do not edit this line> ***************\/\n\n#include <vrj\/vrjConfig.h>\n\n#include <GL\/gl.h>\n\n#include <gmtl\/Math.h>\n#include <gmtl\/Matrix.h>\n#include <gmtl\/Generate.h>\n#include <gmtl\/Vec.h>\n\n#include <gadget\/Type\/Position\/PositionUnitConversion.h>\n\n#include <vrj\/Draw\/OGL\/GlDrawManager.h>\n#include <vrj\/Display\/DisplayManager.h>\n#include <vrj\/Display\/SurfaceViewport.h>\n\n#include \"WallTest.h\"\n\nusing namespace gmtl;\nusing namespace vrj;\n\nvoid WallTest::bufferPreDraw()\n{\n glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n}\n\nvoid WallTest::draw()\n{\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\n if(mUseLights){\n glEnable(GL_NORMALIZE);\n glEnable(GL_LIGHT0);\n glLightfv(GL_LIGHT0,GL_POSITION,mLightPosition.getData());\n glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.1f);\n glEnable(GL_COLOR_MATERIAL);\n glEnable(GL_LIGHTING);\n }\n else{\n glDisable(GL_LIGHTING);\n }\n\n glEnable(GL_DEPTH_TEST);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n \n DisplayManager* displayManager=vrj::GlDrawManager::instance()->getDisplayManager();\n std::vector<Display*> disps=displayManager->getAllDisplays();\n gmtl::Point3f ur,lr,ul,ll;\n\n int numSurfacesDrawn=0;\n float scale=gadget::PositionUnitConversion::ConvertToFeet;\n \n for(unsigned int i=0;i<disps.size();i++)\n {\n for (unsigned int v=0;v<disps[i]->getNumViewports();v++)\n {\n Viewport* viewport=disps[i]->getViewport(v);\n\n if (viewport->isSurface())\n {\n \/\/ Get a pointer to the surface\n SurfaceViewport* surface = dynamic_cast<SurfaceViewport*>(viewport);\n vprASSERT(surface!=NULL);\n\n surface->getCorners(ll,lr,ur,ul);\n\n ll=ll*scale;\n lr=lr*scale;\n ul=ul*scale;\n ur=ur*scale;\n\n drawWall(ll,lr,ul,ur);\n\n\t numSurfacesDrawn++;\n\t }\n }\n }\n\n if(numSurfacesDrawn==0)\n {\n drawC6();\n }\n}\n\nvoid WallTest::drawC6()\n{\n gmtl::Point3f ll,lr,ul,ur;\n\n \/\/ Floor\n ll=gmtl::Point3f(-5,0,-5);\n lr=gmtl::Point3f(5,0,-5);\n ur=gmtl::Point3f(5,0,5);\n ul=gmtl::Point3f(-5,0,5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Ceiling\n ll=gmtl::Point3f(-5,10,5);\n lr=gmtl::Point3f(5,10,5);\n ur=gmtl::Point3f(5,10,-5);\n ul=gmtl::Point3f(-5,10,-5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Front\n ll=gmtl::Point3f(-5,0,5);\n lr=gmtl::Point3f(5,0,5);\n ur=gmtl::Point3f(5,10,5);\n ul=gmtl::Point3f(-5,10,5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Back\n ll=gmtl::Point3f(5,0,-5);\n lr=gmtl::Point3f(-5,0,-5);\n ur=gmtl::Point3f(-5,10,-5);\n ul=gmtl::Point3f(5,10,-5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Left\n ll=gmtl::Point3f(-5,0,-5);\n lr=gmtl::Point3f(-5,0,5);\n ur=gmtl::Point3f(-5,10,5);\n ul=gmtl::Point3f(-5,10,-5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Right\n ll=gmtl::Point3f(5,0,5);\n lr=gmtl::Point3f(5,0,-5);\n ur=gmtl::Point3f(5,10,-5);\n ul=gmtl::Point3f(5,10,5);\n drawWall(ll,lr,ul,ur);\n}\n\nvoid WallTest::drawWall(gmtl::Point3f ll,gmtl::Point3f lr,gmtl::Point3f ul,gmtl::Point3f ur)\n{\n gmtl::Matrix44f rotate=calculateSurfaceRotation(ll,lr,ul,ur);\n gmtl::Vec3f origin=(ll+lr+ul+ur)\/4.0;\n gmtl::Vec3f scale(gmtl::length(lr-ll),gmtl::length(ur-lr),1);\n scale[2]=scale[0]; \/\/ To keep the cubes and tetrahedrons happy\n scale*=0.1f;\n \n glPushMatrix();\n glTranslatef(origin[0],origin[1],origin[2]);\n glMultMatrixf(rotate.getData());\n glPushMatrix();\n glScalef(scale[0],scale[1],scale[2]);\n drawGrid();\n if(mUseCubesOrTriangles)\n {\n drawCubeOrTriangle();\n }\n glPopMatrix();\n glRotatef(90,0,1,0);\n if(mUseCubes)\n {\n drawCubeLine();\n }\n glPopMatrix();\n}\n\ngmtl::Matrix44f WallTest::calculateSurfaceRotation(gmtl::Point3f ll,gmtl::Point3f lr,gmtl::Point3f ul,gmtl::Point3f ur)\n{\n \/\/ Find the base vectors for the surface axiis (in terms of the base coord system)\n \/\/ With z out, x to the right, and y up\n gmtl::Vec3f x_base, y_base, z_base;\n x_base = (lr-ll);\n y_base = (ur-lr);\n gmtl::cross( z_base, x_base, y_base);\n\n \/\/ They must be normalized\n gmtl::normalize(x_base); gmtl::normalize(y_base); gmtl::normalize(z_base);\n\n \/\/ Calculate the surfaceRotMat using law of cosines\n return gmtl::makeDirCos<gmtl::Matrix44f>(x_base,y_base,z_base);\n}\n\nvoid WallTest::preFrame()\n{\n if(mButton1->getData()==gadget::Digital::TOGGLE_ON)\n {\n mUseLights=!mUseLights;\n }\n\n if(mButton0->getData()==gadget::Digital::ON)\n {\n Matrix44f wandMatrix=mWand->getData();\n gmtl::setTrans(mLightPosition,wandMatrix);\n mLightPosition[3]=1;\n }\n else\n {\n mLightPosition=gmtl::Point4f(0,5,0,1);\n }\n\n if(mButton2->getData()==gadget::Digital::TOGGLE_ON)\n {\n mUseCubesOrTriangles=!mUseCubesOrTriangles;\n }\n\n if(mButton3->getData()==gadget::Digital::TOGGLE_ON)\n {\n mUseCubes=!mUseCubes;\n }\n}\n\nvoid WallTest::drawGrid()\n{\n glPushAttrib(GL_LIGHTING);\n glDisable(GL_LIGHTING);\n\n glLineWidth(2);\n \n glBegin(GL_LINES);\n\n float x;\n for(x=-5;x<=5;x+=0.5)\n {\n if(x==-2.5) glColor3f(0,1,1);\n else if(x==-2) glColor3f(1,1,0);\n else if(x==-1.5) glColor3f(1,0,1);\n else if(x==-1) glColor3f(1,0,0);\n else if(x==-0.5) glColor3f(0,1,0);\n else if(x==0) glColor3f(0,0,1);\n else if(x==0.5) glColor3f(0,1,0);\n else if(x==1) glColor3f(1,0,0);\n else if(x==1.5) glColor3f(1,0,1);\n else if(x==2) glColor3f(1,1,0);\n else if(x==2.5) glColor3f(0,1,1);\n else glColor3f(1,1,1);\n\n glVertex2f(x,-5);\n glVertex2f(x,5);\n\n glVertex2f(-5,x);\n glVertex2f(5,x);\n }\n\n glEnd();\n\n glColor3f(1,1,0);\n glBegin(GL_LINE_LOOP);\n for ( x = 0; x < Math::TWO_PI; x += Math::PI \/ 20.0 )\n {\n glVertex2f(sin(x)*5,cos(x)*5);\n }\n glEnd();\n\n glColor3f(0,1,1);\n glLineWidth(5);\n glBegin(GL_LINES);\n glVertex2f(-1,0);\n glVertex2f(1,0);\n glVertex2f(0,-1);\n glVertex2f(0,1);\n glEnd();\n glLineWidth(1);\n\n glPopAttrib();\n}\n\nvoid WallTest::drawCubeLine()\n{\n glColor3f(0,0,1);\n\t\n float x;\n for(x=-5;x<=25;x+=2.5)\n {\n glPushMatrix();\n glTranslatef(x,0,0);\n glScalef(0.25,0.25,0.25);\n drawCube();\n glPopMatrix();\n }\n}\n\nvoid WallTest::drawCube()\n{\n glBegin(GL_QUADS);\n \n glNormal3f(0,-1,0);\n glVertex3f(-1,-1,-1);\n glVertex3f(1,-1,-1);\n glVertex3f(1,-1,1);\n glVertex3f(-1,-1,1);\n\n glNormal3f(0,1,0);\n glVertex3f(-1,1,-1);\n glVertex3f(-1,1,1);\n glVertex3f(1,1,1);\n glVertex3f(1,1,-1);\n\n glNormal3f(-1,0,0);\n glVertex3f(-1,-1,-1);\n glVertex3f(-1,-1,1);\n glVertex3f(-1,1,1);\n glVertex3f(-1,1,-1);\n \n glNormal3f(1,0,0);\n glVertex3f(1,-1,-1);\n glVertex3f(1,1,-1);\n glVertex3f(1,1,1);\n glVertex3f(1,-1,1);\n\n glNormal3f(0,0,-1);\n glVertex3f(-1,-1,-1);\n glVertex3f(1,-1,-1);\n glVertex3f(1,1,-1);\n glVertex3f(-1,1,-1);\n \n glNormal3f(0,0,1);\n glVertex3f(-1,-1,1);\n glVertex3f(1,-1,1);\n glVertex3f(1,1,1);\n glVertex3f(-1,1,1);\n \n glEnd();\n}\n\nvoid WallTest::drawCubeOrTriangle()\n{\n vrj::Projection *currentProjection=vrj::GlDrawManager::instance()->currentUserData()->getProjection();\n int currentEye=currentProjection->getEye();\n\n glPushMatrix();\n \n if(currentEye==vrj::Projection::LEFT)\n {\n glTranslatef(1.5,0,0);\n glColor3f(1,0,0);\n drawCube();\n }\n else\n {\n glTranslatef(-1.5,0,0);\n glColor3f(0,1,0);\n\t \n glBegin(GL_TRIANGLES);\n glNormal3f(0,-1,0);\n glVertex3f(-1,-1,-1);\n glVertex3f(0,-1,1);\n glVertex3f(1,-1,-1);\n\n glNormal3f(0,1,0);\n glVertex3f(-1,-1,-1);\n glVertex3f(0,1,0);\n glVertex3f(0,-1,1);\n\n glNormal3f(0,1,0);\n glVertex3f(0,-1,1);\n glVertex3f(0,1,0);\n glVertex3f(1,-1,-1);\n\n glNormal3f(0,1,0);\n glVertex3f(1,-1,-1);\n glVertex3f(0,1,0);\n glVertex3f(-1,-1,-1);\n glEnd();\n }\n\n glPopMatrix();\n}\n<commit_msg>- Added in a workaround so that this will build against the head branch of GMTL.<commit_after>\/*************** <auto-copyright.pl BEGIN do not edit this line> **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\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\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** <auto-copyright.pl END do not edit this line> ***************\/\n\n#include <vrj\/vrjConfig.h>\n\n#include <GL\/gl.h>\n\n#include <gmtl\/Math.h>\n#include <gmtl\/Matrix.h>\n#include <gmtl\/Generate.h>\n#include <gmtl\/Vec.h>\n\n#include <gadget\/Type\/Position\/PositionUnitConversion.h>\n\n#include <vrj\/Draw\/OGL\/GlDrawManager.h>\n#include <vrj\/Display\/DisplayManager.h>\n#include <vrj\/Display\/SurfaceViewport.h>\n\n#include \"WallTest.h\"\n\nusing namespace gmtl;\nusing namespace vrj;\n\nvoid WallTest::bufferPreDraw()\n{\n glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n}\n\nvoid WallTest::draw()\n{\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\n if(mUseLights){\n glEnable(GL_NORMALIZE);\n glEnable(GL_LIGHT0);\n glLightfv(GL_LIGHT0,GL_POSITION,mLightPosition.getData());\n glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.1f);\n glEnable(GL_COLOR_MATERIAL);\n glEnable(GL_LIGHTING);\n }\n else{\n glDisable(GL_LIGHTING);\n }\n\n glEnable(GL_DEPTH_TEST);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n \n DisplayManager* displayManager=vrj::GlDrawManager::instance()->getDisplayManager();\n std::vector<Display*> disps=displayManager->getAllDisplays();\n gmtl::Point3f ur,lr,ul,ll;\n\n int numSurfacesDrawn=0;\n float scale=gadget::PositionUnitConversion::ConvertToFeet;\n \n for(unsigned int i=0;i<disps.size();i++)\n {\n for (unsigned int v=0;v<disps[i]->getNumViewports();v++)\n {\n Viewport* viewport=disps[i]->getViewport(v);\n\n if (viewport->isSurface())\n {\n \/\/ Get a pointer to the surface\n SurfaceViewport* surface = dynamic_cast<SurfaceViewport*>(viewport);\n vprASSERT(surface!=NULL);\n\n surface->getCorners(ll,lr,ur,ul);\n\n ll=ll*scale;\n lr=lr*scale;\n ul=ul*scale;\n ur=ur*scale;\n\n drawWall(ll,lr,ul,ur);\n\n\t numSurfacesDrawn++;\n\t }\n }\n }\n\n if(numSurfacesDrawn==0)\n {\n drawC6();\n }\n}\n\nvoid WallTest::drawC6()\n{\n gmtl::Point3f ll,lr,ul,ur;\n\n \/\/ Floor\n ll=gmtl::Point3f(-5,0,-5);\n lr=gmtl::Point3f(5,0,-5);\n ur=gmtl::Point3f(5,0,5);\n ul=gmtl::Point3f(-5,0,5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Ceiling\n ll=gmtl::Point3f(-5,10,5);\n lr=gmtl::Point3f(5,10,5);\n ur=gmtl::Point3f(5,10,-5);\n ul=gmtl::Point3f(-5,10,-5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Front\n ll=gmtl::Point3f(-5,0,5);\n lr=gmtl::Point3f(5,0,5);\n ur=gmtl::Point3f(5,10,5);\n ul=gmtl::Point3f(-5,10,5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Back\n ll=gmtl::Point3f(5,0,-5);\n lr=gmtl::Point3f(-5,0,-5);\n ur=gmtl::Point3f(-5,10,-5);\n ul=gmtl::Point3f(5,10,-5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Left\n ll=gmtl::Point3f(-5,0,-5);\n lr=gmtl::Point3f(-5,0,5);\n ur=gmtl::Point3f(-5,10,5);\n ul=gmtl::Point3f(-5,10,-5);\n drawWall(ll,lr,ul,ur);\n\n \/\/ Right\n ll=gmtl::Point3f(5,0,5);\n lr=gmtl::Point3f(5,0,-5);\n ur=gmtl::Point3f(5,10,-5);\n ul=gmtl::Point3f(5,10,5);\n drawWall(ll,lr,ul,ur);\n}\n\nvoid WallTest::drawWall(gmtl::Point3f ll,gmtl::Point3f lr,gmtl::Point3f ul,gmtl::Point3f ur)\n{\n gmtl::Matrix44f rotate=calculateSurfaceRotation(ll,lr,ul,ur);\n \/\/ FIXME: The following is a workaround for GMTL CVS Head's meta \n \/\/ programming. It should be removed as soon as the GMTL API\n \/\/ addresses this.\n gmtl::Vec3f origin = ll + lr + ul + ur;\n origin \/= 4.0;\n \/\/gmtl::Vec3f origin=(ll+lr+ul+ur)\/4.0;\n gmtl::Vec3f lr_ll = lr - ll;\n gmtl::Vec3f ur_lr = ur - lr;\n gmtl::Vec3f scale(gmtl::length(lr_ll), gmtl::length(ur_lr));\n scale[2]=scale[0]; \/\/ To keep the cubes and tetrahedrons happy\n scale*=0.1f;\n \n glPushMatrix();\n glTranslatef(origin[0],origin[1],origin[2]);\n glMultMatrixf(rotate.getData());\n glPushMatrix();\n glScalef(scale[0],scale[1],scale[2]);\n drawGrid();\n if(mUseCubesOrTriangles)\n {\n drawCubeOrTriangle();\n }\n glPopMatrix();\n glRotatef(90,0,1,0);\n if(mUseCubes)\n {\n drawCubeLine();\n }\n glPopMatrix();\n}\n\ngmtl::Matrix44f WallTest::calculateSurfaceRotation(gmtl::Point3f ll,gmtl::Point3f lr,gmtl::Point3f ul,gmtl::Point3f ur)\n{\n \/\/ Find the base vectors for the surface axiis (in terms of the base coord system)\n \/\/ With z out, x to the right, and y up\n gmtl::Vec3f x_base, y_base, z_base;\n x_base = (lr-ll);\n y_base = (ur-lr);\n gmtl::cross( z_base, x_base, y_base);\n\n \/\/ They must be normalized\n gmtl::normalize(x_base); gmtl::normalize(y_base); gmtl::normalize(z_base);\n\n \/\/ Calculate the surfaceRotMat using law of cosines\n return gmtl::makeDirCos<gmtl::Matrix44f>(x_base,y_base,z_base);\n}\n\nvoid WallTest::preFrame()\n{\n if(mButton1->getData()==gadget::Digital::TOGGLE_ON)\n {\n mUseLights=!mUseLights;\n }\n\n if(mButton0->getData()==gadget::Digital::ON)\n {\n Matrix44f wandMatrix=mWand->getData();\n gmtl::setTrans(mLightPosition,wandMatrix);\n mLightPosition[3]=1;\n }\n else\n {\n mLightPosition=gmtl::Point4f(0,5,0,1);\n }\n\n if(mButton2->getData()==gadget::Digital::TOGGLE_ON)\n {\n mUseCubesOrTriangles=!mUseCubesOrTriangles;\n }\n\n if(mButton3->getData()==gadget::Digital::TOGGLE_ON)\n {\n mUseCubes=!mUseCubes;\n }\n}\n\nvoid WallTest::drawGrid()\n{\n glPushAttrib(GL_LIGHTING);\n glDisable(GL_LIGHTING);\n\n glLineWidth(2);\n \n glBegin(GL_LINES);\n\n float x;\n for(x=-5;x<=5;x+=0.5)\n {\n if(x==-2.5) glColor3f(0,1,1);\n else if(x==-2) glColor3f(1,1,0);\n else if(x==-1.5) glColor3f(1,0,1);\n else if(x==-1) glColor3f(1,0,0);\n else if(x==-0.5) glColor3f(0,1,0);\n else if(x==0) glColor3f(0,0,1);\n else if(x==0.5) glColor3f(0,1,0);\n else if(x==1) glColor3f(1,0,0);\n else if(x==1.5) glColor3f(1,0,1);\n else if(x==2) glColor3f(1,1,0);\n else if(x==2.5) glColor3f(0,1,1);\n else glColor3f(1,1,1);\n\n glVertex2f(x,-5);\n glVertex2f(x,5);\n\n glVertex2f(-5,x);\n glVertex2f(5,x);\n }\n\n glEnd();\n\n glColor3f(1,1,0);\n glBegin(GL_LINE_LOOP);\n for ( x = 0; x < Math::TWO_PI; x += Math::PI \/ 20.0 )\n {\n glVertex2f(sin(x)*5,cos(x)*5);\n }\n glEnd();\n\n glColor3f(0,1,1);\n glLineWidth(5);\n glBegin(GL_LINES);\n glVertex2f(-1,0);\n glVertex2f(1,0);\n glVertex2f(0,-1);\n glVertex2f(0,1);\n glEnd();\n glLineWidth(1);\n\n glPopAttrib();\n}\n\nvoid WallTest::drawCubeLine()\n{\n glColor3f(0,0,1);\n\t\n float x;\n for(x=-5;x<=25;x+=2.5)\n {\n glPushMatrix();\n glTranslatef(x,0,0);\n glScalef(0.25,0.25,0.25);\n drawCube();\n glPopMatrix();\n }\n}\n\nvoid WallTest::drawCube()\n{\n glBegin(GL_QUADS);\n \n glNormal3f(0,-1,0);\n glVertex3f(-1,-1,-1);\n glVertex3f(1,-1,-1);\n glVertex3f(1,-1,1);\n glVertex3f(-1,-1,1);\n\n glNormal3f(0,1,0);\n glVertex3f(-1,1,-1);\n glVertex3f(-1,1,1);\n glVertex3f(1,1,1);\n glVertex3f(1,1,-1);\n\n glNormal3f(-1,0,0);\n glVertex3f(-1,-1,-1);\n glVertex3f(-1,-1,1);\n glVertex3f(-1,1,1);\n glVertex3f(-1,1,-1);\n \n glNormal3f(1,0,0);\n glVertex3f(1,-1,-1);\n glVertex3f(1,1,-1);\n glVertex3f(1,1,1);\n glVertex3f(1,-1,1);\n\n glNormal3f(0,0,-1);\n glVertex3f(-1,-1,-1);\n glVertex3f(1,-1,-1);\n glVertex3f(1,1,-1);\n glVertex3f(-1,1,-1);\n \n glNormal3f(0,0,1);\n glVertex3f(-1,-1,1);\n glVertex3f(1,-1,1);\n glVertex3f(1,1,1);\n glVertex3f(-1,1,1);\n \n glEnd();\n}\n\nvoid WallTest::drawCubeOrTriangle()\n{\n vrj::Projection *currentProjection=vrj::GlDrawManager::instance()->currentUserData()->getProjection();\n int currentEye=currentProjection->getEye();\n\n glPushMatrix();\n \n if(currentEye==vrj::Projection::LEFT)\n {\n glTranslatef(1.5,0,0);\n glColor3f(1,0,0);\n drawCube();\n }\n else\n {\n glTranslatef(-1.5,0,0);\n glColor3f(0,1,0);\n\t \n glBegin(GL_TRIANGLES);\n glNormal3f(0,-1,0);\n glVertex3f(-1,-1,-1);\n glVertex3f(0,-1,1);\n glVertex3f(1,-1,-1);\n\n glNormal3f(0,1,0);\n glVertex3f(-1,-1,-1);\n glVertex3f(0,1,0);\n glVertex3f(0,-1,1);\n\n glNormal3f(0,1,0);\n glVertex3f(0,-1,1);\n glVertex3f(0,1,0);\n glVertex3f(1,-1,-1);\n\n glNormal3f(0,1,0);\n glVertex3f(1,-1,-1);\n glVertex3f(0,1,0);\n glVertex3f(-1,-1,-1);\n glEnd();\n }\n\n glPopMatrix();\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <globjects\/Shader.h>\n\n#include <glbinding\/gl\/enum.h>\n#include <glbinding\/gl\/functions.h>\n#include <glbinding\/gl\/boolean.h>\n\n#include <globjects\/base\/AbstractStringSource.h>\n#include <globjects\/base\/StaticStringSource.h>\n#include <globjects\/base\/File.h>\n#include <globjects\/base\/StringTemplate.h>\n\n#include <globjects\/Program.h>\n#include <globjects\/ObjectVisitor.h>\n\n#include <globjects\/Resource.h>\n\n#include \"registry\/ImplementationRegistry.h\"\n#include \"implementations\/AbstractShadingLanguageIncludeImplementation.h\"\n\nusing namespace gl;\n\n\nnamespace\n{\n\n\nconst globjects::AbstractShadingLanguageIncludeImplementation & shadingLanguageIncludeImplementation()\n{\n return globjects::ImplementationRegistry::current().shadingLanguageIncludeImplementation();\n}\n\n\n} \/\/ namespace\n\n\nnamespace globjects\n{\n\n\nvoid Shader::hintIncludeImplementation(const IncludeImplementation impl)\n{\n ImplementationRegistry::current().initialize(impl);\n}\n\nstd::map<std::string, std::string> Shader::s_globalReplacements;\n\n\nShader::Shader(const GLenum type)\n: Object(std::unique_ptr<IDResource>(new ShaderResource(type)))\n, m_type(type)\n, m_source(nullptr)\n, m_compiled(false)\n, m_compilationFailed(false)\n{\n}\n\nShader::Shader(const GLenum type, AbstractStringSource * source, const IncludePaths & includePaths)\n: Shader(type)\n{\n setIncludePaths(includePaths);\n setSource(source);\n}\n\nstd::unique_ptr<StaticStringSource> Shader::sourceFromString(const std::string & sourceString)\n{\n return StaticStringSource::create(sourceString);\n}\n\nstd::unique_ptr<File> Shader::sourceFromFile(const std::string & filename)\n{\n return File::create(filename, false);\n}\n\nstd::unique_ptr<AbstractStringSource> Shader::applyGlobalReplacements(AbstractStringSource * source)\n{\n auto sourceTemplate = StringTemplate::create(source);\n\n for (const auto & pair : s_globalReplacements)\n {\n sourceTemplate->replace(pair.first, pair.second);\n }\n\n return std::unique_ptr<AbstractStringSource>(sourceTemplate.release());\n}\n\nShader::~Shader()\n{\n for (auto program : m_programs)\n {\n program->detach(this);\n }\n}\n\nvoid Shader::globalReplace(const std::string & search, const std::string & replacement)\n{\n s_globalReplacements[search] = replacement;\n}\n\nvoid Shader::globalReplace(const std::string & search, const int i)\n{\n globalReplace(search, std::to_string(i));\n}\n\nvoid Shader::clearGlobalReplacements()\n{\n s_globalReplacements.clear();\n}\n\nvoid Shader::accept(ObjectVisitor & visitor)\n{\n visitor.visitShader(this);\n}\n\nGLenum Shader::type() const\n{\n return m_type;\n}\n\nvoid Shader::setSource(AbstractStringSource * source)\n{\n if (source == m_source)\n return;\n\n if (m_source)\n m_source->deregisterListener(this);\n\n m_source = source;\n\n if (m_source)\n m_source->registerListener(this);\n\n updateSource();\n}\n\nconst AbstractStringSource* Shader::source() const\n{\n return m_source;\n}\n\nvoid Shader::notifyChanged(const Changeable *)\n{\n updateSource();\n}\n\nvoid Shader::updateSource()\n{\n shadingLanguageIncludeImplementation().updateSources(this);\n\n invalidate();\n}\n\nbool Shader::compile() const\n{\n if (m_compilationFailed)\n return false;\n\n shadingLanguageIncludeImplementation().compile(this);\n\n m_compiled = checkCompileStatus();\n\n m_compilationFailed = !m_compiled;\n\n changed();\n\n return m_compiled;\n}\n\nbool Shader::isCompiled() const\n{\n return m_compiled;\n}\n\nvoid Shader::invalidate()\n{\n m_compiled = false;\n m_compilationFailed = false;\n changed();\n}\n\nconst Shader::IncludePaths & Shader::includePaths() const\n{\n return m_includePaths;\n}\n\nvoid Shader::setIncludePaths(const std::vector<std::string> & includePaths)\n{\n m_includePaths = includePaths;\n\n invalidate();\n}\n\nGLint Shader::get(GLenum pname) const\n{\n GLint value = 0;\n glGetShaderiv(id(), pname, &value);\n\n return value;\n}\n\nstd::string Shader::getSource() const\n{\n GLint sourceLength = get(GL_SHADER_SOURCE_LENGTH);\n std::vector<char> source(sourceLength);\n\n glGetShaderSource(id(), sourceLength, nullptr, source.data());\n\n return std::string(source.data(), sourceLength);\n}\n\nbool Shader::checkCompileStatus() const\n{\n GLboolean status = static_cast<GLboolean>(get(GL_COMPILE_STATUS));\n\n if (status == GL_FALSE)\n {\n critical()\n << \"Compiler error:\" << std::endl\n << shaderString() << std::endl\n << infoLog();\n\n return false;\n }\n\n return true;\n}\n\nstd::string Shader::infoLog() const\n{\n GLsizei length = get(GL_INFO_LOG_LENGTH);\n std::vector<char> log(length);\n\n glGetShaderInfoLog(id(), length, &length, log.data());\n\n return std::string(log.data(), length);\n}\n\nstd::string Shader::shaderString() const\n{\n std::stringstream ss;\n\n ss << \"Shader(\" << typeString(m_type);\n\n std::string shortInfo = m_source->shortInfo();\n if (shortInfo.size() > 0)\n ss << \", \" << shortInfo;\n\n ss << \")\";\n\n return ss.str();\n}\n\nstd::string Shader::typeString() const\n{\n return typeString(m_type);\n}\n\nstd::string Shader::typeString(GLenum type)\n{\n switch (type)\n {\n case GL_GEOMETRY_SHADER:\n return \"GL_GEOMETRY_SHADER\";\n case GL_FRAGMENT_SHADER:\n return \"GL_FRAGMENT_SHADER\";\n case GL_VERTEX_SHADER:\n return \"GL_VERTEX_SHADER\";\n case GL_TESS_EVALUATION_SHADER:\n return \"GL_TESS_EVALUATION_SHADER\";\n case GL_TESS_CONTROL_SHADER:\n return \"GL_TESS_CONTROL_SHADER\";\n case GL_COMPUTE_SHADER:\n return \"GL_COMPUTE_SHADER\";\n default:\n return \"Unknown Shader Type\";\n }\n}\n\nGLenum Shader::objectType() const\n{\n return GL_SHADER;\n}\n\n\n} \/\/ namespace globjects\n<commit_msg>Fix shader deinitialization<commit_after>\n#include <globjects\/Shader.h>\n\n#include <glbinding\/gl\/enum.h>\n#include <glbinding\/gl\/functions.h>\n#include <glbinding\/gl\/boolean.h>\n\n#include <globjects\/base\/AbstractStringSource.h>\n#include <globjects\/base\/StaticStringSource.h>\n#include <globjects\/base\/File.h>\n#include <globjects\/base\/StringTemplate.h>\n\n#include <globjects\/Program.h>\n#include <globjects\/ObjectVisitor.h>\n\n#include <globjects\/Resource.h>\n\n#include \"registry\/ImplementationRegistry.h\"\n#include \"implementations\/AbstractShadingLanguageIncludeImplementation.h\"\n\nusing namespace gl;\n\n\nnamespace\n{\n\n\nconst globjects::AbstractShadingLanguageIncludeImplementation & shadingLanguageIncludeImplementation()\n{\n return globjects::ImplementationRegistry::current().shadingLanguageIncludeImplementation();\n}\n\n\n} \/\/ namespace\n\n\nnamespace globjects\n{\n\n\nvoid Shader::hintIncludeImplementation(const IncludeImplementation impl)\n{\n ImplementationRegistry::current().initialize(impl);\n}\n\nstd::map<std::string, std::string> Shader::s_globalReplacements;\n\n\nShader::Shader(const GLenum type)\n: Object(std::unique_ptr<IDResource>(new ShaderResource(type)))\n, m_type(type)\n, m_source(nullptr)\n, m_compiled(false)\n, m_compilationFailed(false)\n{\n}\n\nShader::Shader(const GLenum type, AbstractStringSource * source, const IncludePaths & includePaths)\n: Shader(type)\n{\n setIncludePaths(includePaths);\n setSource(source);\n}\n\nstd::unique_ptr<StaticStringSource> Shader::sourceFromString(const std::string & sourceString)\n{\n return StaticStringSource::create(sourceString);\n}\n\nstd::unique_ptr<File> Shader::sourceFromFile(const std::string & filename)\n{\n return File::create(filename, false);\n}\n\nstd::unique_ptr<AbstractStringSource> Shader::applyGlobalReplacements(AbstractStringSource * source)\n{\n auto sourceTemplate = StringTemplate::create(source);\n\n for (const auto & pair : s_globalReplacements)\n {\n sourceTemplate->replace(pair.first, pair.second);\n }\n\n return std::unique_ptr<AbstractStringSource>(sourceTemplate.release());\n}\n\nShader::~Shader()\n{\n while (!m_programs.empty())\n {\n (*m_programs.begin())->detach(this);\n }\n}\n\nvoid Shader::globalReplace(const std::string & search, const std::string & replacement)\n{\n s_globalReplacements[search] = replacement;\n}\n\nvoid Shader::globalReplace(const std::string & search, const int i)\n{\n globalReplace(search, std::to_string(i));\n}\n\nvoid Shader::clearGlobalReplacements()\n{\n s_globalReplacements.clear();\n}\n\nvoid Shader::accept(ObjectVisitor & visitor)\n{\n visitor.visitShader(this);\n}\n\nGLenum Shader::type() const\n{\n return m_type;\n}\n\nvoid Shader::setSource(AbstractStringSource * source)\n{\n if (source == m_source)\n return;\n\n if (m_source)\n m_source->deregisterListener(this);\n\n m_source = source;\n\n if (m_source)\n m_source->registerListener(this);\n\n updateSource();\n}\n\nconst AbstractStringSource* Shader::source() const\n{\n return m_source;\n}\n\nvoid Shader::notifyChanged(const Changeable *)\n{\n updateSource();\n}\n\nvoid Shader::updateSource()\n{\n shadingLanguageIncludeImplementation().updateSources(this);\n\n invalidate();\n}\n\nbool Shader::compile() const\n{\n if (m_compilationFailed)\n return false;\n\n shadingLanguageIncludeImplementation().compile(this);\n\n m_compiled = checkCompileStatus();\n\n m_compilationFailed = !m_compiled;\n\n changed();\n\n return m_compiled;\n}\n\nbool Shader::isCompiled() const\n{\n return m_compiled;\n}\n\nvoid Shader::invalidate()\n{\n m_compiled = false;\n m_compilationFailed = false;\n changed();\n}\n\nconst Shader::IncludePaths & Shader::includePaths() const\n{\n return m_includePaths;\n}\n\nvoid Shader::setIncludePaths(const std::vector<std::string> & includePaths)\n{\n m_includePaths = includePaths;\n\n invalidate();\n}\n\nGLint Shader::get(GLenum pname) const\n{\n GLint value = 0;\n glGetShaderiv(id(), pname, &value);\n\n return value;\n}\n\nstd::string Shader::getSource() const\n{\n GLint sourceLength = get(GL_SHADER_SOURCE_LENGTH);\n std::vector<char> source(sourceLength);\n\n glGetShaderSource(id(), sourceLength, nullptr, source.data());\n\n return std::string(source.data(), sourceLength);\n}\n\nbool Shader::checkCompileStatus() const\n{\n GLboolean status = static_cast<GLboolean>(get(GL_COMPILE_STATUS));\n\n if (status == GL_FALSE)\n {\n critical()\n << \"Compiler error:\" << std::endl\n << shaderString() << std::endl\n << infoLog();\n\n return false;\n }\n\n return true;\n}\n\nstd::string Shader::infoLog() const\n{\n GLsizei length = get(GL_INFO_LOG_LENGTH);\n std::vector<char> log(length);\n\n glGetShaderInfoLog(id(), length, &length, log.data());\n\n return std::string(log.data(), length);\n}\n\nstd::string Shader::shaderString() const\n{\n std::stringstream ss;\n\n ss << \"Shader(\" << typeString(m_type);\n\n std::string shortInfo = m_source->shortInfo();\n if (shortInfo.size() > 0)\n ss << \", \" << shortInfo;\n\n ss << \")\";\n\n return ss.str();\n}\n\nstd::string Shader::typeString() const\n{\n return typeString(m_type);\n}\n\nstd::string Shader::typeString(GLenum type)\n{\n switch (type)\n {\n case GL_GEOMETRY_SHADER:\n return \"GL_GEOMETRY_SHADER\";\n case GL_FRAGMENT_SHADER:\n return \"GL_FRAGMENT_SHADER\";\n case GL_VERTEX_SHADER:\n return \"GL_VERTEX_SHADER\";\n case GL_TESS_EVALUATION_SHADER:\n return \"GL_TESS_EVALUATION_SHADER\";\n case GL_TESS_CONTROL_SHADER:\n return \"GL_TESS_CONTROL_SHADER\";\n case GL_COMPUTE_SHADER:\n return \"GL_COMPUTE_SHADER\";\n default:\n return \"Unknown Shader Type\";\n }\n}\n\nGLenum Shader::objectType() const\n{\n return GL_SHADER;\n}\n\n\n} \/\/ namespace globjects\n<|endoftext|>"} {"text":"<commit_before>\n#include \"dwi\/shells.h\"\n\n#include \"file\/config.h\"\n\n\nnamespace MR\n{\n namespace DWI\n {\n\n\n\n using namespace App;\n\n const OptionGroup ShellOption = OptionGroup (\"DW Shell selection options\")\n + Option (\"shell\",\n \"specify one or more diffusion-weighted gradient shells to use during processing. \"\n \"The shell structure is determined automatically from the gradient encoding (either \"\n \"stored in the image header or provided using the -grad option); use this option to \"\n \"list the b-value(s) corresponding to the shell(s) that you wish to be used for \"\n \"processing.\"\n \"Note that some commands are incompatible with multiple shells, and will throw an \"\n \"error if you provide more than one b-value.\")\n + Argument (\"list\").type_sequence_int();\n\n\n\n \/\/ TODO Want to re-name this config option to BZeroThreshold\n const float bzero_threshold = File::Config::get_float (\"BValueThreshold\", 10.0);\n\n\n\n\n Shell::Shell (const Math::Matrix<float>& grad, const std::vector<size_t>& indices) :\n volumes (indices),\n mean (0.0),\n stdev (0.0),\n min (std::numeric_limits<float>::max()),\n max (0.0)\n {\n assert (volumes.size());\n for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) {\n const float b = grad (*i, 3);\n mean += b;\n min = std::min (min, b);\n max = std::max (min, b);\n }\n mean \/= float(volumes.size());\n for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++)\n stdev += Math::pow2 (grad (*i, 3) - mean);\n stdev = Math::sqrt (stdev \/ (volumes.size() - 1));\n }\n\n\n\n\n\n\n void Shells::select_shells (const bool keep_bzero, const bool force_single_shell)\n {\n\n \/\/ Easiest way to restrict processing to particular shells is to simply erase\n \/\/ the unwanted shells; makes it command independent\n\n BitSet to_retain (shells.size(), 0);\n if (keep_bzero && smallest().is_bzero())\n to_retain[0] = true;\n\n App::Options opt = App::get_options (\"shell\");\n if (opt.size()) {\n\n std::vector<int> desired_bvalues = opt[0][0];\n if (desired_bvalues.size() > 1 && !(desired_bvalues.front() == 0) && force_single_shell)\n throw Exception (\"Command not compatible with multiple non-zero b-shells\");\n\n for (std::vector<int>::const_iterator b = desired_bvalues.begin(); b != desired_bvalues.end(); ++b) {\n\n if (*b < 0)\n throw Exception (\"Cannot select shells corresponding to negative b-values\");\n\n \/\/ Automatically select a b=0 shell if the requested b-value is zero\n if (*b <= bzero_threshold) {\n\n if (smallest().is_bzero()) {\n to_retain[0] = true;\n DEBUG (\"User requested b-value \" + str(*b) + \"; got b=0 shell : \" + str(smallest().get_mean()) + \" +- \" + str(smallest().get_stdev()) + \" with \" + str(smallest().count()) + \" volumes\");\n } else {\n throw Exception (\"User selected b=0 shell, but no such data exists\");\n }\n\n } else {\n\n \/\/ First, see if the b-value lies within the range of one of the shells\n \/\/ If this doesn't occur, need to make a decision based on the shell distributions\n \/\/ Few ways this could be done:\n \/\/ * Compute number of standard deviations away from each shell mean, see if there's a clear winner\n \/\/ - Won't work if any of the standard deviations are zero\n \/\/ * Assume each is a Poisson distribution, see if there's a clear winner\n \/\/ Prompt warning if decision is slightly askew, exception if ambiguous\n bool shell_selected = false;\n for (size_t s = 0; s != shells.size(); ++s) {\n if ((*b >= shells[s].get_min()) && (*b <= shells[s].get_max())) {\n to_retain[s] = true;\n shell_selected = true;\n DEBUG (\"User requested b-value \" + str(*b) + \"; got shell \" + str(s) + \": \" + str(shells[s].get_mean()) + \" +- \" + str(shells[s].get_stdev()) + \" with \" + str(shells[s].count()) + \" volumes\");\n }\n }\n if (!shell_selected) {\n\n \/\/ First, check to see if all non-zero shells have a non-zero standard deviation\n bool zero_stdev = false;\n for (std::vector<Shell>::const_iterator s = shells.begin(); s != shells.end(); ++s) {\n if (!s->is_bzero() && !s->get_stdev()) {\n zero_stdev = true;\n break;\n }\n }\n\n size_t best_shell = 0;\n float best_num_stdevs = std::numeric_limits<float>::max();\n bool ambiguous = false;\n for (size_t s = 0; s != shells.size(); ++s) {\n const float num_stdev = Math::abs ((*b - shells[s].get_mean()) \/ (zero_stdev ? Math::sqrt (shells[s].get_mean()) : shells[s].get_stdev()));\n const bool within_range = (num_stdev < (zero_stdev ? 1.0 : 5.0));\n if (within_range) {\n if (!shell_selected) {\n best_shell = s;\n best_num_stdevs = num_stdev;\n } else {\n \/\/ More than one shell plausible; decide whether or not the decision is unambiguous\n if (num_stdev < 0.1 * best_num_stdevs) {\n best_shell = s;\n best_num_stdevs = num_stdev;\n } else if (num_stdev < 10.0 * best_num_stdevs) {\n ambiguous = true;\n } \/\/ No need to do anything if the existing selection is significantly better than this shell\n }\n }\n }\n\n if (ambiguous) {\n std::string bvalues;\n for (size_t s = 0; s != shells.size(); ++s) {\n if (bvalues.size())\n bvalues += \", \";\n bvalues += str(shells[s].get_mean()) + \" +- \" + str(shells[s].get_stdev());\n }\n throw Exception (\"Unable to robustly select desired shell b=\" + str(*b) + \" (detected shells are: \" + bvalues + \")\");\n }\n\n WARN (\"User requested shell b=\" + str(*b) + \"; have selected shell \" + str(shells[best_shell].get_mean()) + \" +- \" + str(shells[best_shell].get_stdev()));\n\n to_retain[best_shell] = true;\n\n }\n\n } \/\/ End checking to see if requested shell is b=0\n\n } \/\/ End looping over list of requested b-value shells\n\n } else {\n\n if (force_single_shell && !is_single_shell())\n WARN (\"Multiple non-zero b-value shells detected; automatically selecting b=\" + str(largest().get_mean()) + \" with \" + str(largest().count()) + \" volumes\");\n to_retain[shells.size()-1] = true;\n\n }\n\n if (to_retain.full()) {\n DEBUG (\"No DW shells to be removed\");\n return;\n }\n\n \/\/ Erase the unwanted shells\n std::vector<Shell> new_shells;\n for (size_t s = 0; s != shells.size(); ++s) {\n if (to_retain[s])\n new_shells.push_back (shells[s]);\n }\n shells.swap (new_shells);\n\n }\n\n\n\n\n\n\n void Shells::initialise (const Math::Matrix<float>& grad)\n {\n BValueList bvals (grad.column (3));\n std::vector<size_t> clusters (bvals.size(), 0);\n const size_t num_shells = clusterBvalues (bvals, clusters);\n\n INFO (\"Diffusion gradient encoding data clustered into \" + str(num_shells) + \" shells\");\n if ((num_shells < 1) || (num_shells > Math::sqrt (float(grad.rows()))))\n throw Exception (\"Gradient encoding matrix does not represent a HARDI sequence\");\n\n for (size_t shellIdx = 0; shellIdx <= num_shells; shellIdx++) {\n\n std::vector<size_t> volumes;\n for (size_t volumeIdx = 0; volumeIdx != clusters.size(); ++volumeIdx) {\n if (clusters[volumeIdx] == shellIdx)\n volumes.push_back (volumeIdx);\n }\n\n if (shellIdx) {\n shells.push_back (Shell (grad, volumes));\n } else if (volumes.size()) {\n std::string unassigned;\n for (size_t i = 0; i != volumes.size(); ++i) {\n if (unassigned.size())\n unassigned += \", \";\n unassigned += str(volumes[i]) + \" (\" + str(bvals[volumes[i]]) + \")\";\n }\n WARN (\"The following image volumes were not successfully assigned to a b-value shell:\");\n WARN (unassigned);\n }\n\n }\n\n std::sort (shells.begin(), shells.end());\n }\n\n\n\n\n size_t Shells::clusterBvalues (const BValueList& bvals, std::vector<size_t>& clusters) const\n {\n BitSet visited (bvals.size(), false);\n size_t clusterIdx = 0;\n\n for (size_t ii = 0; ii != bvals.size(); ii++) {\n if (!visited[ii]) {\n\n visited[ii] = true;\n const float b = bvals[ii];\n std::vector<size_t> neighborIdx;\n regionQuery (bvals, b, neighborIdx);\n\n if (b > bzero_threshold && neighborIdx.size() < DWI_SHELLS_MIN_LINKAGE) {\n\n clusters[ii] = 0;\n\n } else {\n\n clusters[ii] = ++clusterIdx;\n for (size_t i = 0; i < neighborIdx.size(); i++) {\n if (!visited[neighborIdx[i]]) {\n visited[neighborIdx[i]] = true;\n std::vector<size_t> neighborIdx2;\n regionQuery (bvals, bvals[neighborIdx[i]], neighborIdx2);\n if (neighborIdx2.size() >= DWI_SHELLS_MIN_LINKAGE)\n for (size_t j = 0; j != neighborIdx2.size(); j++)\n neighborIdx.push_back (neighborIdx2[j]);\n }\n if (clusters[neighborIdx[i]] == 0)\n clusters[neighborIdx[i]] = clusterIdx;\n }\n\n }\n\n }\n }\n\n clusterIdx = rejectSmallShells (bvals, clusters, clusterIdx);\n return clusterIdx;\n }\n\n\n\n void Shells::regionQuery (const BValueList& bvals, const float b, std::vector<size_t>& idx) const\n {\n for (size_t i = 0; i < bvals.size(); i++) {\n if (Math::abs (b - bvals[i]) < DWI_SHELLS_EPSILON)\n idx.push_back (i);\n }\n }\n\n\n\n size_t Shells::rejectSmallShells (const BValueList& bvals, std::vector<size_t>& clusters, const size_t max_index) const\n {\n \/\/ Count the number of volumes in each shell\n std::vector<size_t> counts (max_index + 1, 0);\n \/\/ Also need the mean b-value; don't want to reject b=0 due to having too few volumes\n std::vector<float> means (max_index + 1, 0.0);\n for (size_t vol = 0; vol != bvals.size(); ++vol) {\n const size_t shell = clusters[vol];\n ++counts[shell];\n means[shell] += bvals[vol];\n }\n \/\/ Generate a mapping from old shell index to new shell index\n \/\/ (if one shell is rejected, the indices of the shells above it need to decrease)\n std::vector<size_t> index_mapping (max_index + 1, 0);\n size_t new_index = 0;\n for (size_t shell = 1; shell <= max_index; ++shell) {\n means[shell] \/= float(counts[shell]);\n if ((means[shell] < bzero_threshold) || (counts[shell] >= DWI_SHELLS_MIN_DIRECTIONS))\n index_mapping[shell] = ++new_index;\n }\n \/\/ At least one shell rejected\n if (new_index != max_index) {\n \/\/ Re-map the shell indices; volumes belong to a rejected shell will be reset to an index of 0\n for (size_t i = 0; i != clusters.size(); ++i)\n clusters[i] = index_mapping[clusters[i]];\n }\n return max_index;\n }\n\n\n\n }\n}\n\n\n<commit_msg>DWI::Shells: update to option documentation<commit_after>\n#include \"dwi\/shells.h\"\n\n#include \"file\/config.h\"\n\n\nnamespace MR\n{\n namespace DWI\n {\n\n\n\n using namespace App;\n\n const OptionGroup ShellOption = OptionGroup (\"DW Shell selection options\")\n + Option (\"shell\",\n \"specify one or more diffusion-weighted gradient shells to use during \"\n \"processing, as a comma-separated list of the desired approximate b-values. \"\n \"Note that some commands are incompatible with multiple shells, and \"\n \"will throw an error if more than one b-value are provided.\")\n + Argument (\"list\").type_sequence_int();\n\n\n\n \/\/ TODO Want to re-name this config option to BZeroThreshold\n const float bzero_threshold = File::Config::get_float (\"BValueThreshold\", 10.0);\n\n\n\n\n Shell::Shell (const Math::Matrix<float>& grad, const std::vector<size_t>& indices) :\n volumes (indices),\n mean (0.0),\n stdev (0.0),\n min (std::numeric_limits<float>::max()),\n max (0.0)\n {\n assert (volumes.size());\n for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) {\n const float b = grad (*i, 3);\n mean += b;\n min = std::min (min, b);\n max = std::max (min, b);\n }\n mean \/= float(volumes.size());\n for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++)\n stdev += Math::pow2 (grad (*i, 3) - mean);\n stdev = Math::sqrt (stdev \/ (volumes.size() - 1));\n }\n\n\n\n\n\n\n void Shells::select_shells (const bool keep_bzero, const bool force_single_shell)\n {\n\n \/\/ Easiest way to restrict processing to particular shells is to simply erase\n \/\/ the unwanted shells; makes it command independent\n\n BitSet to_retain (shells.size(), 0);\n if (keep_bzero && smallest().is_bzero())\n to_retain[0] = true;\n\n App::Options opt = App::get_options (\"shell\");\n if (opt.size()) {\n\n std::vector<int> desired_bvalues = opt[0][0];\n if (desired_bvalues.size() > 1 && !(desired_bvalues.front() == 0) && force_single_shell)\n throw Exception (\"Command not compatible with multiple non-zero b-shells\");\n\n for (std::vector<int>::const_iterator b = desired_bvalues.begin(); b != desired_bvalues.end(); ++b) {\n\n if (*b < 0)\n throw Exception (\"Cannot select shells corresponding to negative b-values\");\n\n \/\/ Automatically select a b=0 shell if the requested b-value is zero\n if (*b <= bzero_threshold) {\n\n if (smallest().is_bzero()) {\n to_retain[0] = true;\n DEBUG (\"User requested b-value \" + str(*b) + \"; got b=0 shell : \" + str(smallest().get_mean()) + \" +- \" + str(smallest().get_stdev()) + \" with \" + str(smallest().count()) + \" volumes\");\n } else {\n throw Exception (\"User selected b=0 shell, but no such data exists\");\n }\n\n } else {\n\n \/\/ First, see if the b-value lies within the range of one of the shells\n \/\/ If this doesn't occur, need to make a decision based on the shell distributions\n \/\/ Few ways this could be done:\n \/\/ * Compute number of standard deviations away from each shell mean, see if there's a clear winner\n \/\/ - Won't work if any of the standard deviations are zero\n \/\/ * Assume each is a Poisson distribution, see if there's a clear winner\n \/\/ Prompt warning if decision is slightly askew, exception if ambiguous\n bool shell_selected = false;\n for (size_t s = 0; s != shells.size(); ++s) {\n if ((*b >= shells[s].get_min()) && (*b <= shells[s].get_max())) {\n to_retain[s] = true;\n shell_selected = true;\n DEBUG (\"User requested b-value \" + str(*b) + \"; got shell \" + str(s) + \": \" + str(shells[s].get_mean()) + \" +- \" + str(shells[s].get_stdev()) + \" with \" + str(shells[s].count()) + \" volumes\");\n }\n }\n if (!shell_selected) {\n\n \/\/ First, check to see if all non-zero shells have a non-zero standard deviation\n bool zero_stdev = false;\n for (std::vector<Shell>::const_iterator s = shells.begin(); s != shells.end(); ++s) {\n if (!s->is_bzero() && !s->get_stdev()) {\n zero_stdev = true;\n break;\n }\n }\n\n size_t best_shell = 0;\n float best_num_stdevs = std::numeric_limits<float>::max();\n bool ambiguous = false;\n for (size_t s = 0; s != shells.size(); ++s) {\n const float num_stdev = Math::abs ((*b - shells[s].get_mean()) \/ (zero_stdev ? Math::sqrt (shells[s].get_mean()) : shells[s].get_stdev()));\n const bool within_range = (num_stdev < (zero_stdev ? 1.0 : 5.0));\n if (within_range) {\n if (!shell_selected) {\n best_shell = s;\n best_num_stdevs = num_stdev;\n } else {\n \/\/ More than one shell plausible; decide whether or not the decision is unambiguous\n if (num_stdev < 0.1 * best_num_stdevs) {\n best_shell = s;\n best_num_stdevs = num_stdev;\n } else if (num_stdev < 10.0 * best_num_stdevs) {\n ambiguous = true;\n } \/\/ No need to do anything if the existing selection is significantly better than this shell\n }\n }\n }\n\n if (ambiguous) {\n std::string bvalues;\n for (size_t s = 0; s != shells.size(); ++s) {\n if (bvalues.size())\n bvalues += \", \";\n bvalues += str(shells[s].get_mean()) + \" +- \" + str(shells[s].get_stdev());\n }\n throw Exception (\"Unable to robustly select desired shell b=\" + str(*b) + \" (detected shells are: \" + bvalues + \")\");\n }\n\n WARN (\"User requested shell b=\" + str(*b) + \"; have selected shell \" + str(shells[best_shell].get_mean()) + \" +- \" + str(shells[best_shell].get_stdev()));\n\n to_retain[best_shell] = true;\n\n }\n\n } \/\/ End checking to see if requested shell is b=0\n\n } \/\/ End looping over list of requested b-value shells\n\n } else {\n\n if (force_single_shell && !is_single_shell())\n WARN (\"Multiple non-zero b-value shells detected; automatically selecting b=\" + str(largest().get_mean()) + \" with \" + str(largest().count()) + \" volumes\");\n to_retain[shells.size()-1] = true;\n\n }\n\n if (to_retain.full()) {\n DEBUG (\"No DW shells to be removed\");\n return;\n }\n\n \/\/ Erase the unwanted shells\n std::vector<Shell> new_shells;\n for (size_t s = 0; s != shells.size(); ++s) {\n if (to_retain[s])\n new_shells.push_back (shells[s]);\n }\n shells.swap (new_shells);\n\n }\n\n\n\n\n\n\n void Shells::initialise (const Math::Matrix<float>& grad)\n {\n BValueList bvals (grad.column (3));\n std::vector<size_t> clusters (bvals.size(), 0);\n const size_t num_shells = clusterBvalues (bvals, clusters);\n\n INFO (\"Diffusion gradient encoding data clustered into \" + str(num_shells) + \" shells\");\n if ((num_shells < 1) || (num_shells > Math::sqrt (float(grad.rows()))))\n throw Exception (\"Gradient encoding matrix does not represent a HARDI sequence\");\n\n for (size_t shellIdx = 0; shellIdx <= num_shells; shellIdx++) {\n\n std::vector<size_t> volumes;\n for (size_t volumeIdx = 0; volumeIdx != clusters.size(); ++volumeIdx) {\n if (clusters[volumeIdx] == shellIdx)\n volumes.push_back (volumeIdx);\n }\n\n if (shellIdx) {\n shells.push_back (Shell (grad, volumes));\n } else if (volumes.size()) {\n std::string unassigned;\n for (size_t i = 0; i != volumes.size(); ++i) {\n if (unassigned.size())\n unassigned += \", \";\n unassigned += str(volumes[i]) + \" (\" + str(bvals[volumes[i]]) + \")\";\n }\n WARN (\"The following image volumes were not successfully assigned to a b-value shell:\");\n WARN (unassigned);\n }\n\n }\n\n std::sort (shells.begin(), shells.end());\n }\n\n\n\n\n size_t Shells::clusterBvalues (const BValueList& bvals, std::vector<size_t>& clusters) const\n {\n BitSet visited (bvals.size(), false);\n size_t clusterIdx = 0;\n\n for (size_t ii = 0; ii != bvals.size(); ii++) {\n if (!visited[ii]) {\n\n visited[ii] = true;\n const float b = bvals[ii];\n std::vector<size_t> neighborIdx;\n regionQuery (bvals, b, neighborIdx);\n\n if (b > bzero_threshold && neighborIdx.size() < DWI_SHELLS_MIN_LINKAGE) {\n\n clusters[ii] = 0;\n\n } else {\n\n clusters[ii] = ++clusterIdx;\n for (size_t i = 0; i < neighborIdx.size(); i++) {\n if (!visited[neighborIdx[i]]) {\n visited[neighborIdx[i]] = true;\n std::vector<size_t> neighborIdx2;\n regionQuery (bvals, bvals[neighborIdx[i]], neighborIdx2);\n if (neighborIdx2.size() >= DWI_SHELLS_MIN_LINKAGE)\n for (size_t j = 0; j != neighborIdx2.size(); j++)\n neighborIdx.push_back (neighborIdx2[j]);\n }\n if (clusters[neighborIdx[i]] == 0)\n clusters[neighborIdx[i]] = clusterIdx;\n }\n\n }\n\n }\n }\n\n clusterIdx = rejectSmallShells (bvals, clusters, clusterIdx);\n return clusterIdx;\n }\n\n\n\n void Shells::regionQuery (const BValueList& bvals, const float b, std::vector<size_t>& idx) const\n {\n for (size_t i = 0; i < bvals.size(); i++) {\n if (Math::abs (b - bvals[i]) < DWI_SHELLS_EPSILON)\n idx.push_back (i);\n }\n }\n\n\n\n size_t Shells::rejectSmallShells (const BValueList& bvals, std::vector<size_t>& clusters, const size_t max_index) const\n {\n \/\/ Count the number of volumes in each shell\n std::vector<size_t> counts (max_index + 1, 0);\n \/\/ Also need the mean b-value; don't want to reject b=0 due to having too few volumes\n std::vector<float> means (max_index + 1, 0.0);\n for (size_t vol = 0; vol != bvals.size(); ++vol) {\n const size_t shell = clusters[vol];\n ++counts[shell];\n means[shell] += bvals[vol];\n }\n \/\/ Generate a mapping from old shell index to new shell index\n \/\/ (if one shell is rejected, the indices of the shells above it need to decrease)\n std::vector<size_t> index_mapping (max_index + 1, 0);\n size_t new_index = 0;\n for (size_t shell = 1; shell <= max_index; ++shell) {\n means[shell] \/= float(counts[shell]);\n if ((means[shell] < bzero_threshold) || (counts[shell] >= DWI_SHELLS_MIN_DIRECTIONS))\n index_mapping[shell] = ++new_index;\n }\n \/\/ At least one shell rejected\n if (new_index != max_index) {\n \/\/ Re-map the shell indices; volumes belong to a rejected shell will be reset to an index of 0\n for (size_t i = 0; i != clusters.size(); ++i)\n clusters[i] = index_mapping[clusters[i]];\n }\n return max_index;\n }\n\n\n\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/*\n* Covariant Script C\/C++ Native Interface\n* CNI's effect is to forward CovScript function call to C\/C++ function and need to cooperate with cs::native_interface to use.\n* Please do not bind a CNI directly to CovScript. CovScript can not directly identify a CNI.\n* CNI can recognize any form of C\/C++ functions, but please note that CNI does not support implicit conversion of parameter types.\n* To avoid compatibility issues, use CovScript built-in types as much as possible.\n* You can use the reference to modify the value of the CovScript passed parameters, but please note that this may cause an error because some of the variables in CovScript are protected.\n* To improve the efficiency of a function, you can use constant references instead of values. Please note that CNI does not currently support forwarding right-value references.\n* If you want to receive a variable parameter, just use cov::any as the argument type.\n* This program was written by Micheal Lee(mikecovlee@163.com)。\n*\/\n#include \"..\/include\/mozart\/bind.hpp\"\n#include \"..\/include\/mozart\/traits.hpp\"\n#include \".\/core.hpp\"\n#include \".\/arglist.hpp\"\nnamespace cs {\n\ttemplate<typename T>struct convert {\n\t\tstatic inline const T& get_val(cov::any& val)\n\t\t{\n\t\t\treturn val.const_val<T>();\n\t\t}\n\t};\n\ttemplate<typename T>struct convert<const T&> {\n\t\tstatic inline const T& get_val(cov::any& val)\n\t\t{\n\t\t\treturn val.const_val<T>();\n\t\t}\n\t};\n\ttemplate<typename T>struct convert<T&> {\n\t\tstatic inline T& get_val(cov::any& val)\n\t\t{\n\t\t\treturn val.val<T>(true);\n\t\t}\n\t};\n\ttemplate<>struct convert<const cov::any&> {\n\t\tstatic inline const cov::any& get_val(const cov::any& val)\n\t\t{\n\t\t\treturn val;\n\t\t}\n\t};\n\ttemplate<>struct convert<cov::any&> {\n\t\tstatic inline cov::any& get_val(cov::any& val)\n\t\t{\n\t\t\treturn val;\n\t\t}\n\t};\n\ttemplate<typename T,typename X>class cni_helper;\n\ttemplate<typename X>class cni_helper<void(*)(),X> {\n\t\tX mFunc;\n\tpublic:\n\t\tcni_helper()=delete;\n\t\tcni_helper(const cni_helper&)=default;\n\t\tcni_helper(const X& func):mFunc(func) {}\n\t\tcov::any call(array& args) const\n\t\t{\n\t\t\tif(!args.empty())\n\t\t\t\tthrow syntax_error(\"Wrong size of the arguments.Expected 0\");\n\t\t\tmFunc();\n\t\t\treturn cov::any::make<number>(0);\n\t\t}\n\t};\n\ttemplate<typename RetT,typename X>class cni_helper<RetT(*)(),X> {\n\t\tX mFunc;\n\tpublic:\n\t\tcni_helper()=delete;\n\t\tcni_helper(const cni_helper&)=default;\n\t\tcni_helper(const X& func):mFunc(func) {}\n\t\tcov::any call(array& args) const\n\t\t{\n\t\t\tif(!args.empty())\n\t\t\t\tthrow syntax_error(\"Wrong size of the arguments.Expected 0\");\n\t\t\treturn std::move(mFunc());\n\t\t}\n\t};\n\ttemplate<typename...ArgsT,typename X>\n\tclass cni_helper<void(*)(ArgsT...),X> {\n\t\tusing args_t=typename cov::type_list::make<ArgsT...>::result;\n\t\tX mFunc;\n\t\ttemplate<int...S>void _call(array& args,const cov::sequence<S...>&) const\n\t\t{\n\t\t\tmFunc(convert<ArgsT>::get_val(args.at(S))...);\n\t\t}\n\tpublic:\n\t\tcni_helper()=delete;\n\t\tcni_helper(const cni_helper&)=default;\n\t\tcni_helper(const X& func):mFunc(func) {}\n\t\tcov::any call(array& args) const\n\t\t{\n\t\t\targlist::check<ArgsT...>(args);\n\t\t\t_call(args,cov::make_sequence<cov::type_list::get_size<args_t>::result>::result);\n\t\t\treturn cov::any::make<number>(0);\n\t\t}\n\t};\n\ttemplate<typename RetT,typename...ArgsT,typename X>\n\tclass cni_helper<RetT(*)(ArgsT...),X> {\n\t\tusing args_t=typename cov::type_list::make<ArgsT...>::result;\n\t\tX mFunc;\n\t\ttemplate<int...S>RetT _call(array& args,const cov::sequence<S...>&) const\n\t\t{\n\t\t\treturn std::move(mFunc(convert<ArgsT>::get_val(args.at(S))...));\n\t\t}\n\tpublic:\n\t\tcni_helper()=delete;\n\t\tcni_helper(const cni_helper&)=default;\n\t\tcni_helper(const X& func):mFunc(func) {}\n\t\tcov::any call(array& args) const\n\t\t{\n\t\t\targlist::check<ArgsT...>(args);\n\t\t\treturn std::move(_call(args,cov::make_sequence<cov::type_list::get_size<args_t>::result>::result));\n\t\t}\n\t};\n\ttemplate<typename T>struct cni_modify {\n\t\tusing type=T;\n\t};\n\ttemplate<typename RetT,typename...ArgsT>struct cni_modify<RetT(ArgsT...)> {\n\t\tusing type=RetT(*)(ArgsT...);\n\t};\n\tclass cni final {\n\t\tclass cni_base {\n\t\tpublic:\n\t\t\tcni_base()=default;\n\t\t\tcni_base(const cni_base&)=default;\n\t\t\tvirtual ~cni_base()=default;\n\t\t\tvirtual cni_base* clone()=0;\n\t\t\tvirtual cov::any call(array&) const=0;\n\t\t};\n\t\ttemplate<typename T>class cni_holder final:public cni_base {\n\t\t\tcni_helper<typename cov::function_parser<T>::type::common_type,T> mCni;\n\t\tpublic:\n\t\t\tcni_holder()=delete;\n\t\t\tcni_holder(const cni_holder&)=default;\n\t\t\tcni_holder(const T& func):mCni(func) {}\n\t\t\tvirtual ~cni_holder()=default;\n\t\t\tvirtual cni_base* clone() override\n\t\t\t{\n\t\t\t\treturn new cni_holder(*this);\n\t\t\t}\n\t\t\tvirtual cov::any call(array& args) const override\n\t\t\t{\n\t\t\t\treturn mCni.call(args);\n\t\t\t}\n\t\t};\n\t\ttemplate<typename T>struct construct_helper {\n\t\t\ttemplate<typename X>static cni_base* construct(X&& val)\n\t\t\t{\n\t\t\t\treturn new cni_holder<T>(std::forward<X>(val));\n\t\t\t}\n\t\t};\n\t\tcni_base* mCni=nullptr;\n\tpublic:\n\t\tcni()=delete;\n\t\tcni(const cni& c):mCni(c.mCni->clone()) {}\n\t\ttemplate<typename T>cni(T&& val):mCni(construct_helper<typename cni_modify<typename cov::remove_reference<T>::type>::type>::construct(std::forward<T>(val))) {}\n\t\t~cni()\n\t\t{\n\t\t\tdelete mCni;\n\t\t}\n\t\tcov::any operator()(array& args) const\n\t\t{\n\t\t\treturn mCni->call(args);\n\t\t}\n\t};\n\ttemplate<>struct cni::construct_helper<const cni> {\n\t\tstatic cni_base* construct(const cni& c)\n\t\t{\n\t\t\treturn c.mCni->clone();\n\t\t}\n\t};\n\ttemplate<>struct cni::construct_helper<cni> {\n\t\tstatic cni_base* construct(const cni& c)\n\t\t{\n\t\t\treturn c.mCni->clone();\n\t\t}\n\t};\n}\n<commit_msg>重新改回std::function<commit_after>#pragma once\n\/*\n* Covariant Script C\/C++ Native Interface\n* CNI's effect is to forward CovScript function call to C\/C++ function and need to cooperate with cs::native_interface to use.\n* Please do not bind a CNI directly to CovScript. CovScript can not directly identify a CNI.\n* CNI can recognize any form of C\/C++ functions, but please note that CNI does not support implicit conversion of parameter types.\n* To avoid compatibility issues, use CovScript built-in types as much as possible.\n* You can use the reference to modify the value of the CovScript passed parameters, but please note that this may cause an error because some of the variables in CovScript are protected.\n* To improve the efficiency of a function, you can use constant references instead of values. Please note that CNI does not currently support forwarding right-value references.\n* If you want to receive a variable parameter, just use cov::any as the argument type.\n* This program was written by Micheal Lee(mikecovlee@163.com)。\n*\/\n#include \"..\/include\/mozart\/bind.hpp\"\n#include \"..\/include\/mozart\/traits.hpp\"\n#include \".\/core.hpp\"\n#include \".\/arglist.hpp\"\n#include <functional>\nnamespace cs {\n\ttemplate<typename T>struct convert {\n\t\tstatic inline const T& get_val(cov::any& val)\n\t\t{\n\t\t\treturn val.const_val<T>();\n\t\t}\n\t};\n\ttemplate<typename T>struct convert<const T&> {\n\t\tstatic inline const T& get_val(cov::any& val)\n\t\t{\n\t\t\treturn val.const_val<T>();\n\t\t}\n\t};\n\ttemplate<typename T>struct convert<T&> {\n\t\tstatic inline T& get_val(cov::any& val)\n\t\t{\n\t\t\treturn val.val<T>(true);\n\t\t}\n\t};\n\ttemplate<>struct convert<const cov::any&> {\n\t\tstatic inline const cov::any& get_val(const cov::any& val)\n\t\t{\n\t\t\treturn val;\n\t\t}\n\t};\n\ttemplate<>struct convert<cov::any&> {\n\t\tstatic inline cov::any& get_val(cov::any& val)\n\t\t{\n\t\t\treturn val;\n\t\t}\n\t};\n\ttemplate<typename T>class cni_helper;\n\ttemplate<>class cni_helper<void(*)()> {\n\t\tstd::function<void()> mFunc;\n\tpublic:\n\t\tcni_helper()=delete;\n\t\tcni_helper(const cni_helper&)=default;\n\t\tcni_helper(const std::function<void()>& func):mFunc(func) {}\n\t\tcov::any call(array& args) const\n\t\t{\n\t\t\tif(!args.empty())\n\t\t\t\tthrow syntax_error(\"Wrong size of the arguments.Expected 0\");\n\t\t\tmFunc();\n\t\t\treturn cov::any::make<number>(0);\n\t\t}\n\t};\n\ttemplate<typename RetT>class cni_helper<RetT(*)()> {\n\t\tstd::function<RetT()> mFunc;\n\tpublic:\n\t\tcni_helper()=delete;\n\t\tcni_helper(const cni_helper&)=default;\n\t\tcni_helper(const std::function<RetT()>& func):mFunc(func) {}\n\t\tcov::any call(array& args) const\n\t\t{\n\t\t\tif(!args.empty())\n\t\t\t\tthrow syntax_error(\"Wrong size of the arguments.Expected 0\");\n\t\t\treturn std::move(mFunc());\n\t\t}\n\t};\n\ttemplate<typename...ArgsT>\n\tclass cni_helper<void(*)(ArgsT...)> {\n\t\tusing args_t=typename cov::type_list::make<ArgsT...>::result;\n\t\tstd::function<void(ArgsT...)> mFunc;\n\t\ttemplate<int...S>void _call(array& args,const cov::sequence<S...>&) const\n\t\t{\n\t\t\tmFunc(convert<ArgsT>::get_val(args.at(S))...);\n\t\t}\n\tpublic:\n\t\tcni_helper()=delete;\n\t\tcni_helper(const cni_helper&)=default;\n\t\tcni_helper(const std::function<void(ArgsT...)>& func):mFunc(func) {}\n\t\tcov::any call(array& args) const\n\t\t{\n\t\t\targlist::check<ArgsT...>(args);\n\t\t\t_call(args,cov::make_sequence<cov::type_list::get_size<args_t>::result>::result);\n\t\t\treturn cov::any::make<number>(0);\n\t\t}\n\t};\n\ttemplate<typename RetT,typename...ArgsT>\n\tclass cni_helper<RetT(*)(ArgsT...)> {\n\t\tusing args_t=typename cov::type_list::make<ArgsT...>::result;\n\t\tstd::function<RetT(ArgsT...)> mFunc;\n\t\ttemplate<int...S>RetT _call(array& args,const cov::sequence<S...>&) const\n\t\t{\n\t\t\treturn std::move(mFunc(convert<ArgsT>::get_val(args.at(S))...));\n\t\t}\n\tpublic:\n\t\tcni_helper()=delete;\n\t\tcni_helper(const cni_helper&)=default;\n\t\tcni_helper(const std::function<RetT(ArgsT...)>& func):mFunc(func) {}\n\t\tcov::any call(array& args) const\n\t\t{\n\t\t\targlist::check<ArgsT...>(args);\n\t\t\treturn std::move(_call(args,cov::make_sequence<cov::type_list::get_size<args_t>::result>::result));\n\t\t}\n\t};\n\ttemplate<typename T>struct cni_modify {\n\t\tusing type=T;\n\t};\n\ttemplate<typename RetT,typename...ArgsT>struct cni_modify<RetT(ArgsT...)> {\n\t\tusing type=RetT(*)(ArgsT...);\n\t};\n\tclass cni final {\n\t\tclass cni_base {\n\t\tpublic:\n\t\t\tcni_base()=default;\n\t\t\tcni_base(const cni_base&)=default;\n\t\t\tvirtual ~cni_base()=default;\n\t\t\tvirtual cni_base* clone()=0;\n\t\t\tvirtual cov::any call(array&) const=0;\n\t\t};\n\t\ttemplate<typename T>class cni_holder final:public cni_base {\n\t\t\tcni_helper<typename cov::function_parser<T>::type::common_type> mCni;\n\t\tpublic:\n\t\t\tcni_holder()=delete;\n\t\t\tcni_holder(const cni_holder&)=default;\n\t\t\tcni_holder(const T& func):mCni(func) {}\n\t\t\tvirtual ~cni_holder()=default;\n\t\t\tvirtual cni_base* clone() override\n\t\t\t{\n\t\t\t\treturn new cni_holder(*this);\n\t\t\t}\n\t\t\tvirtual cov::any call(array& args) const override\n\t\t\t{\n\t\t\t\treturn mCni.call(args);\n\t\t\t}\n\t\t};\n\t\ttemplate<typename T>struct construct_helper {\n\t\t\ttemplate<typename X>static cni_base* construct(X&& val)\n\t\t\t{\n\t\t\t\treturn new cni_holder<T>(std::forward<X>(val));\n\t\t\t}\n\t\t};\n\t\tcni_base* mCni=nullptr;\n\tpublic:\n\t\tcni()=delete;\n\t\tcni(const cni& c):mCni(c.mCni->clone()) {}\n\t\ttemplate<typename T>cni(T&& val):mCni(construct_helper<typename cni_modify<typename cov::remove_reference<T>::type>::type>::construct(std::forward<T>(val))) {}\n\t\t~cni()\n\t\t{\n\t\t\tdelete mCni;\n\t\t}\n\t\tcov::any operator()(array& args) const\n\t\t{\n\t\t\treturn mCni->call(args);\n\t\t}\n\t};\n\ttemplate<>struct cni::construct_helper<const cni> {\n\t\tstatic cni_base* construct(const cni& c)\n\t\t{\n\t\t\treturn c.mCni->clone();\n\t\t}\n\t};\n\ttemplate<>struct cni::construct_helper<cni> {\n\t\tstatic cni_base* construct(const cni& c)\n\t\t{\n\t\t\treturn c.mCni->clone();\n\t\t}\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from\n * Numenta, Inc. a separate commercial license for this software code, the\n * following terms and conditions apply:\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 version 3 as\n * published by the Free Software Foundation.\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\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ---------------------------------------------------------------------\n *\/\n\n\/** @file \n * Templates implementation for class Grouper\n *\/\n\n#ifndef NTA_ZETA1_GROUPER_T_HPP\n#define NTA_ZETA1_GROUPER_T_HPP\n\n#ifdef NUPIC2\n#error \"Zeta1Grouper is used only by Zeta1Node, which is not part of NuPIC 2\"\n#endif\n\n\/\/----------------------------------------------------------------------\nnamespace nta {\n \n \/\/--------------------------------------------------------------------------------\n \/**\n * begin2 is not used: we do not output anything in learning mode.\n *\/\n template <typename InIter, typename OutIter>\n void Zeta1Grouper::learn(InIter begin1, OutIter, size_type baby_idx)\n {\n size_type winnerIndex = size_type(*begin1);\n tam_.learn(winnerIndex, baby_idx);\n }\n\n \/\/--------------------------------------------------------------------------------\n \/**\n * x is the output of the coincidence detector\n *\n * If using Time Based Inference ('tbi' set in the constructor), then the inference output\n * is computed by treating the Time Adjacency Matrix (tam) as a set of cell weights between\n * \"cells\" in each group. The intent here is to have the inference output for each group\n * increase in certainty as we see successive coincidence inputs that are in that group.\n *\n * For the TBI computation, each group is assigned 1 cell per coincidence in the\n * group. Each cell's output is updated after each time step based on the following\n * equation:\n * N \/\t\t \t \\\n * cellOut (t) = bottomUp * ( SUM | cellWeight * cellOut (t-1) | + A0 )\n * j j i=0 \\ ij i \/\n *\n * The net inference output for each group is then the max of all the cell outputs for\n * that group.\n * \n * Each group has it's own cellWeight matrix, which is produced by extracting the entries\n * from the TAM corresponding to the coincidences in that group, and then normalizing down\n * the columns so that the sum of the weights in each column is 1.\n *\n * The cellOuts for each group are kept unique from each other - when we have overlapping\n * groups for example, cell 0's output in group A will not necessarily be the same value\n * as cell 0's output in group B - this is because we only consider the contribution\n * from other cells *in the same group* when we peform the above cellOut computation.\n * \n * The A0 contribution can be considered as the likelihood that this cell is a start of\n * the group, or rather, it is the sum contribution from all the cells in the other\n * groups. Without this factor of course, none of the cell outputs would ever be non-zero.\n * In the end, the exact value chosen for A0 is immaterial since we are only looking at\n * the relative output strengths of each group.\n *\n * cellOut is a joint pdf over groups and coincidences.\n *\/\n template <typename InIter, typename OutIter>\n void Zeta1Grouper::tbiInfer(InIter x, InIter x_end, \n\t\t\t OutIter y, TBICellOutputsVec::iterator cellOuts)\n {\n using namespace std;\n\n { \/\/ Pre-conditions\n NTA_ASSERT(!tbiCellWeights_.empty())\n\t<< \"Grouper::tbiInfer: Cell weights not initialized\";\n } \/\/ End pre-conditions\n\n const value_type A0 = (value_type) 0.1;\n\n \/\/ Compute TBI output. \n OutIter y_begin = y;\n TBICellWeightsVec::iterator w = tbiCellWeights_.begin();\n Groups::const_iterator g = groups_.begin(), g_end = groups_.end(); \n size_type g_idx = 0;\n\n for (; g != g_end; ++g, ++w, ++cellOuts, ++y, ++g_idx) \n {\n\t\/\/ Compute the product of the cellWeights and the current \n\t\/\/ cell outputs.\n\t\/\/ w has size g->size X g->size\n\t\/\/ *cellOuts has size g->size (vector)\n\t\/\/ tbiBuffer_ is sized to be the size of the largest group\n\t\/\/ (only the first g->size positions are used here)\n\tw->rightVecProd(*cellOuts, tbiBuffer_);\n\n\t\/\/ Add A0 to each cell output and multiply by the bottom up input \n\tAGroup::const_iterator s = g->begin(), s_end = g->end();\n\tTBICellOutputs::iterator cell = cellOuts->begin();\n\tTBICellOutputs::const_iterator b = tbiBuffer_.begin();\n\tvalue_type maxCellOut = 0.0;\n\n\t\/\/ In case HOT is used, we need to convert the HOT state \n\t\/\/ index to its original coincidence. If HOT is not used, \n\t\/\/ getHOTCoincidence reduces to identity.\n\tfor (; s != s_end; ++s, ++b, ++cell) {\n\t size_type c = tam_.getHOTCoincidence(*s);\n\t *cell = (*b + A0) * (*(x + c));\n\t maxCellOut = max(*cell, maxCellOut);\n\t}\n\t\n\t*y = maxCellOut;\n } \n\n if(rescaleTBI_) {\n \/\/ Scale the group outputs so that the max is the same as the max of the inputs.\n \/\/ This preserves the relative strength between the group output and blank score\n \/\/ computed by the spatial pooler. \n value_type maxInValue = * std::max_element(x, x_end);\n if (maxInValue > (value_type) 0)\n normalize_max(y_begin, y_begin + groups_.size(), maxInValue);\n }\n }\n\n \/\/--------------------------------------------------------------------------------\n template <typename InIter, typename OutIter>\n void Zeta1Grouper::infer(InIter x, InIter x_end, OutIter y, size_type tbi_idx)\n {\n switch (mode_) { \n \n case maxProp:\n \/\/ For each row, find the max corresponding to a non-zero\n weights_.vecMaxAtNZ(x, y);\n break;\n \n case sumProp:\n weights_.rightVecProd(x, y);\n break;\n \n case tbi: \n {\n\tif (tbiCellWeights_.empty())\n\t tbi_create_();\n\n\ttbiInfer(x, x_end, y, tbiCellOutputs_[tbi_idx].begin());\n }\n break;\n } \/\/ switch mode\n } \n\n\n \/\/--------------------------------------------------------------------------------\n\n} \/\/ end namespace nta\n\n#endif \/\/ NTA_ZETA1_GROUPER_T_HPP\n<commit_msg>remove Zeta1Grouper header, not used in NUPIC2<commit_after><|endoftext|>"} {"text":"<commit_before>\nint main(int argc, char* argv[])\n{\n\n}<commit_msg>Add basic command line flag handling using cppassist\/cmdline<commit_after>#include <iostream>\n#include <string>\n\n#include <cppassist\/cmdline\/ArgumentParser.h>\n\n\nint main(int argc, char* argv[])\n{\n cppassist::ArgumentParser argParser;\n argParser.parse(argc, argv);\n\n auto inFileName = argParser.value(\"--input\");\n auto outFileName = argParser.value(\"--output\");\n\n auto outFileType = outFileName.substr(outFileName.find_last_of('.') + 1);\n\n auto fromGeneratedKernel = argParser.isSet(\"-k\");\n\n if (fromGeneratedKernel)\n {\n std::cout << \"Converting kernel \\\"\" << inFileName << \"\\\" to output file \\\"\" << outFileName << \"\\\" (type: \" << outFileType << \")\" <<std::endl;\n }\n else\n {\n std::cout << \"Using kernel description \\\"\" << inFileName << \"\\\" to generate kernel \\\"\" << outFileName << \"\\\" (type: \" << outFileType << \")\" << std::endl;\n }\n\n}<|endoftext|>"} {"text":"<commit_before>#define __STDC_FORMAT_MACROS\n\n#include <stdio.h>\n#include <iostream>\n#include <time.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <algorithm>\n\n#include <sinsp.h>\n#include \"lua_parser.h\"\n#include \"digwatch.h\"\n#include \"utils.h\"\n\n#include <unistd.h>\n#include <getopt.h>\n\nlua_parser* g_lua_parser;\n\nstatic void usage();\n\n\/\/\n\/\/ Program help\n\/\/\nstatic void usage()\n{\n printf(\n\t \"Usage: digwatch [options] [-p <output_format>] [filter]\\n\\n\"\n\t \"Options:\\n\"\n\t \" -h, --help Print this page\\n\"\n\t \" -M <num_seconds> Stop collecting after <num_seconds> reached.\\n\"\n\t \" -N Don't convert port numbers to names.\\n\"\n\t \" -n <num>, --numevents=<num>\\n\"\n\t \" Stop capturing after <num> events\\n\"\n\t \" -u <filename>, --user-parser <filename>\\n\"\n\t \" Name of lua file containing parser\\n\"\n\t \" -r <readfile>, --read=<readfile>\\n\"\n\t \" Read the events from <readfile>.\\n\"\n\t \" --unbuffered Turn off output buffering. This causes every single line\\n\"\n\t \" emitted by digwatch to be flushed, which generates higher CPU\\n\"\n\t \" usage but is useful when piping digwatch's output into another\\n\"\n\t \" process or into a script.\\n\"\n\t \"\\n\"\n );\n}\n\n\n\/\/\n\/\/ Event processing loop\n\/\/\ncaptureinfo do_inspect(sinsp* inspector,\n\t\t uint64_t cnt,\n\t\t int duration_to_tot,\n\t\t sinsp_evt_formatter* formatter)\n{\n\tcaptureinfo retval;\n\tint32_t res;\n\tsinsp_evt* ev;\n\tstring line;\n int duration_start = 0;\n\n\t\/\/\n\t\/\/ Loop through the events\n\t\/\/\n\tduration_start = ((double)clock()) \/ CLOCKS_PER_SEC;\n\twhile(1)\n\t{\n\t\tif(duration_to_tot > 0)\n\t\t{\n\t\t\tint duration_tot = ((double)clock()) \/ CLOCKS_PER_SEC - duration_start;\n\t\t\tif(duration_tot >= duration_to_tot)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(retval.m_nevts == cnt)\n\t\t{\n\t\t\t\/\/\n\t\t\t\/\/ End of capture, either because the user stopped it, or because\n\t\t\t\/\/ we reached the event count specified with -n.\n\t\t\t\/\/\n\t\t\tbreak;\n\t\t}\n\n\t\tres = inspector->next(&ev);\n\n\t\tif(res == SCAP_TIMEOUT)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\telse if(res == SCAP_EOF)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse if(res != SCAP_SUCCESS)\n\t\t{\n\t\t\t\/\/\n\t\t\t\/\/ Event read error.\n\t\t\t\/\/ Notify the chisels that we're exiting, and then die with an error.\n\t\t\t\/\/\n\t\t\tcerr << \"res = \" << res << endl;\n\t\t\tthrow sinsp_exception(inspector->getlasterr().c_str());\n\t\t}\n\n\t\tretval.m_nevts++;\n\n\t\tif(!inspector->is_debug_enabled() &&\n\t\t\tev->get_category() & EC_INTERNAL)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif(formatter->tostring(ev, &line))\n\t\t{\n\t\t\tcout << line;\n\t\t\tcout << endl;\n\t\t}\n\n\t}\n\n\treturn retval;\n}\n\n\/\/\n\/\/ ARGUMENT PARSING AND PROGRAM SETUP\n\/\/\ndigwatch_init_res digwatch_init(int argc, char **argv)\n{\n\tdigwatch_init_res res;\n\tsinsp* inspector = NULL;\n\tint op;\n\tuint64_t cnt = -1;\n\tsinsp_evt::param_fmt event_buffer_format = sinsp_evt::PF_NORMAL;\n\tint duration_to_tot = 0;\n\tcaptureinfo cinfo;\n\tstring output_format;\n\tint long_index = 0;\n\tstring user_parser;\n\n\tstatic struct option long_options[] =\n\t{\n\t\t{\"help\", no_argument, 0, 'h' },\n\t\t{\"numevents\", required_argument, 0, 'n' },\n\t\t{\"user-parser\", required_argument, 0, 'u' },\n\t\t{\"readfile\", required_argument, 0, 'r' },\n\t\t{\"unbuffered\", no_argument, 0, 0 },\n\t\t{0, 0, 0, 0}\n\t};\n\n\toutput_format = \"*%evt.num %evt.outputtime %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type %evt.info\";\n\n\ttry\n\t{\n\t\tinspector = new sinsp();\n\n\n\t\t\/\/\n\t\t\/\/ Parse the args\n\t\t\/\/\n\t\twhile((op = getopt_long(argc, argv,\n \"hM:Nn:r:u:\",\n long_options, &long_index)) != -1)\n\t\t{\n\t\t\tswitch(op)\n\t\t\t{\n\t\t\tcase 'h':\n\t\t\t\tusage();\n\t\t\t\tdelete inspector;\n\t\t\t\treturn digwatch_init_res(EXIT_SUCCESS);\n\t\t\tcase 'M':\n\t\t\t\tduration_to_tot = atoi(optarg);\n\t\t\t\tif(duration_to_tot <= 0)\n\t\t\t\t{\n\t\t\t\t\tthrow sinsp_exception(string(\"invalid duration\") + optarg);\n\t\t\t\t\tres.m_res = EXIT_FAILURE;\n\t\t\t\t\tgoto exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'N':\n\t\t\t\tinspector->set_hostname_and_port_resolution_mode(false);\n\t\t\t\tbreak;\n\t\t\tcase 'n':\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tcnt = sinsp_numparser::parseu64(optarg);\n\t\t\t\t}\n\t\t\t\tcatch(...)\n\t\t\t\t{\n\t\t\t\t\tthrow sinsp_exception(\"can't parse the -n argument, make sure it's a number\");\n\t\t\t\t}\n\n\t\t\t\tif(cnt <= 0)\n\t\t\t\t{\n\t\t\t\t\tthrow sinsp_exception(string(\"invalid event count \") + optarg);\n\t\t\t\t\tres.m_res = EXIT_FAILURE;\n\t\t\t\t\tgoto exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'u':\n\t\t\t\tuser_parser = optarg;\n\t\t\t\tbreak;\n\t\t\tcase '?':\n\t\t\t\tdelete inspector;\n\t\t\t\treturn digwatch_init_res(EXIT_FAILURE);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\n\t\tinspector->set_buffer_format(event_buffer_format);\n\n\t\tstring filter;\n\n\t\t\/\/\n\t\t\/\/ the filter is at the end of the command line\n\t\t\/\/\n\t\tif(optind < argc)\n\t\t{\n#ifdef HAS_FILTERING\n\t\t\tfor(int32_t j = optind ; j < argc; j++)\n\t\t\t{\n\t\t\t\tfilter += argv[j];\n\t\t\t\tif(j < argc - 1)\n\t\t\t\t{\n\t\t\t\t\tfilter += \" \";\n\t\t\t\t}\n\t\t\t}\n\n#else\n\t\t\tfprintf(stderr, \"filtering not compiled.\\n\");\n\t\t\tres.m_res = EXIT_FAILURE;\n\t\t\tgoto exit;\n#endif\n\t\t}\n\n\t\t\/\/\n\t\t\/\/ Create the event formatter\n\t\t\/\/\n\t\tsinsp_evt_formatter formatter(inspector, output_format);\n\n\t\tg_lua_parser = new lua_parser(inspector, user_parser);\n\n\t\tif(filter.size())\n\t\t{\n\t\t\tinspector->set_filter(filter);\n\t\t}\n\t\tinspector->open(\"\");\n\n\t\tcinfo = do_inspect(inspector,\n\t\t\t\t cnt,\n\t\t\t\t duration_to_tot,\n\t\t\t\t &formatter);\n\n\t\tinspector->close();\n\t}\n\tcatch(sinsp_exception& e)\n\t{\n\t\tcerr << e.what() << endl;\n\t\tres.m_res = EXIT_FAILURE;\n\t}\n\tcatch(...)\n\t{\n\t\tprintf(\"Exeception\\n\");\n\t\tres.m_res = EXIT_FAILURE;\n\t}\n\nexit:\n\n\tif(inspector)\n\t{\n\t\tdelete inspector;\n\t}\n\n\treturn res;\n}\n\n\/\/\n\/\/ MAIN\n\/\/\nint main(int argc, char **argv)\n{\n\tdigwatch_init_res res;\n\n\tres = digwatch_init(argc, argv);\n\n\treturn res.m_res;\n}\n<commit_msg>Pass filter object into sinsp::set_filter()<commit_after>#define __STDC_FORMAT_MACROS\n\n#include <stdio.h>\n#include <iostream>\n#include <time.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <algorithm>\n\n#include <sinsp.h>\n#include \"lua_parser.h\"\n#include \"digwatch.h\"\n#include \"utils.h\"\n\n#include <unistd.h>\n#include <getopt.h>\n\nlua_parser* g_lua_parser;\n\nstatic void usage();\n\n\/\/\n\/\/ Program help\n\/\/\nstatic void usage()\n{\n printf(\n\t \"Usage: digwatch [options] [-p <output_format>] [filter]\\n\\n\"\n\t \"Options:\\n\"\n\t \" -h, --help Print this page\\n\"\n\t \" -M <num_seconds> Stop collecting after <num_seconds> reached.\\n\"\n\t \" -N Don't convert port numbers to names.\\n\"\n\t \" -n <num>, --numevents=<num>\\n\"\n\t \" Stop capturing after <num> events\\n\"\n\t \" -u <filename>, --user-parser <filename>\\n\"\n\t \" Name of lua file containing parser\\n\"\n\t \" -r <readfile>, --read=<readfile>\\n\"\n\t \" Read the events from <readfile>.\\n\"\n\t \" --unbuffered Turn off output buffering. This causes every single line\\n\"\n\t \" emitted by digwatch to be flushed, which generates higher CPU\\n\"\n\t \" usage but is useful when piping digwatch's output into another\\n\"\n\t \" process or into a script.\\n\"\n\t \"\\n\"\n );\n}\n\n\n\/\/\n\/\/ Event processing loop\n\/\/\ncaptureinfo do_inspect(sinsp* inspector,\n\t\t uint64_t cnt,\n\t\t int duration_to_tot,\n\t\t sinsp_evt_formatter* formatter)\n{\n\tcaptureinfo retval;\n\tint32_t res;\n\tsinsp_evt* ev;\n\tstring line;\n int duration_start = 0;\n\n\t\/\/\n\t\/\/ Loop through the events\n\t\/\/\n\tduration_start = ((double)clock()) \/ CLOCKS_PER_SEC;\n\twhile(1)\n\t{\n\t\tif(duration_to_tot > 0)\n\t\t{\n\t\t\tint duration_tot = ((double)clock()) \/ CLOCKS_PER_SEC - duration_start;\n\t\t\tif(duration_tot >= duration_to_tot)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(retval.m_nevts == cnt)\n\t\t{\n\t\t\t\/\/\n\t\t\t\/\/ End of capture, either because the user stopped it, or because\n\t\t\t\/\/ we reached the event count specified with -n.\n\t\t\t\/\/\n\t\t\tbreak;\n\t\t}\n\n\t\tres = inspector->next(&ev);\n\n\t\tif(res == SCAP_TIMEOUT)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\telse if(res == SCAP_EOF)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse if(res != SCAP_SUCCESS)\n\t\t{\n\t\t\t\/\/\n\t\t\t\/\/ Event read error.\n\t\t\t\/\/ Notify the chisels that we're exiting, and then die with an error.\n\t\t\t\/\/\n\t\t\tcerr << \"res = \" << res << endl;\n\t\t\tthrow sinsp_exception(inspector->getlasterr().c_str());\n\t\t}\n\n\t\tretval.m_nevts++;\n\n\t\tif(!inspector->is_debug_enabled() &&\n\t\t\tev->get_category() & EC_INTERNAL)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif(formatter->tostring(ev, &line))\n\t\t{\n\t\t\tcout << line;\n\t\t\tcout << endl;\n\t\t}\n\n\t}\n\n\treturn retval;\n}\n\n\/\/\n\/\/ ARGUMENT PARSING AND PROGRAM SETUP\n\/\/\ndigwatch_init_res digwatch_init(int argc, char **argv)\n{\n\tdigwatch_init_res res;\n\tsinsp* inspector = NULL;\n\tint op;\n\tuint64_t cnt = -1;\n\tsinsp_evt::param_fmt event_buffer_format = sinsp_evt::PF_NORMAL;\n\tint duration_to_tot = 0;\n\tcaptureinfo cinfo;\n\tstring output_format;\n\tint long_index = 0;\n\tstring user_parser;\n\n\tstatic struct option long_options[] =\n\t{\n\t\t{\"help\", no_argument, 0, 'h' },\n\t\t{\"numevents\", required_argument, 0, 'n' },\n\t\t{\"user-parser\", required_argument, 0, 'u' },\n\t\t{\"readfile\", required_argument, 0, 'r' },\n\t\t{\"unbuffered\", no_argument, 0, 0 },\n\t\t{0, 0, 0, 0}\n\t};\n\n\toutput_format = \"*%evt.num %evt.outputtime %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type %evt.info\";\n\n\ttry\n\t{\n\t\tinspector = new sinsp();\n\n\n\t\t\/\/\n\t\t\/\/ Parse the args\n\t\t\/\/\n\t\twhile((op = getopt_long(argc, argv,\n \"hM:Nn:r:u:\",\n long_options, &long_index)) != -1)\n\t\t{\n\t\t\tswitch(op)\n\t\t\t{\n\t\t\tcase 'h':\n\t\t\t\tusage();\n\t\t\t\tdelete inspector;\n\t\t\t\treturn digwatch_init_res(EXIT_SUCCESS);\n\t\t\tcase 'M':\n\t\t\t\tduration_to_tot = atoi(optarg);\n\t\t\t\tif(duration_to_tot <= 0)\n\t\t\t\t{\n\t\t\t\t\tthrow sinsp_exception(string(\"invalid duration\") + optarg);\n\t\t\t\t\tres.m_res = EXIT_FAILURE;\n\t\t\t\t\tgoto exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'N':\n\t\t\t\tinspector->set_hostname_and_port_resolution_mode(false);\n\t\t\t\tbreak;\n\t\t\tcase 'n':\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tcnt = sinsp_numparser::parseu64(optarg);\n\t\t\t\t}\n\t\t\t\tcatch(...)\n\t\t\t\t{\n\t\t\t\t\tthrow sinsp_exception(\"can't parse the -n argument, make sure it's a number\");\n\t\t\t\t}\n\n\t\t\t\tif(cnt <= 0)\n\t\t\t\t{\n\t\t\t\t\tthrow sinsp_exception(string(\"invalid event count \") + optarg);\n\t\t\t\t\tres.m_res = EXIT_FAILURE;\n\t\t\t\t\tgoto exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'u':\n\t\t\t\tuser_parser = optarg;\n\t\t\t\tbreak;\n\t\t\tcase '?':\n\t\t\t\tdelete inspector;\n\t\t\t\treturn digwatch_init_res(EXIT_FAILURE);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\n\t\tinspector->set_buffer_format(event_buffer_format);\n\n\t\tstring filter;\n\n\t\t\/\/\n\t\t\/\/ the filter is at the end of the command line\n\t\t\/\/\n\t\tif(optind < argc)\n\t\t{\n#ifdef HAS_FILTERING\n\t\t\tfor(int32_t j = optind ; j < argc; j++)\n\t\t\t{\n\t\t\t\tfilter += argv[j];\n\t\t\t\tif(j < argc - 1)\n\t\t\t\t{\n\t\t\t\t\tfilter += \" \";\n\t\t\t\t}\n\t\t\t}\n\n#else\n\t\t\tfprintf(stderr, \"filtering not compiled.\\n\");\n\t\t\tres.m_res = EXIT_FAILURE;\n\t\t\tgoto exit;\n#endif\n\t\t}\n\n\t\t\/\/\n\t\t\/\/ Create the event formatter\n\t\t\/\/\n\t\tsinsp_evt_formatter formatter(inspector, output_format);\n\n\t\tg_lua_parser = new lua_parser(inspector, user_parser);\n\n\t\tinspector->set_filter(g_lua_parser->m_filter);\n\t\tinspector->open(\"\");\n\n\t\tcinfo = do_inspect(inspector,\n\t\t\t\t cnt,\n\t\t\t\t duration_to_tot,\n\t\t\t\t &formatter);\n\n\t\tinspector->close();\n\t}\n\tcatch(sinsp_exception& e)\n\t{\n\t\tcerr << e.what() << endl;\n\t\tres.m_res = EXIT_FAILURE;\n\t}\n\tcatch(...)\n\t{\n\t\tprintf(\"Exeception\\n\");\n\t\tres.m_res = EXIT_FAILURE;\n\t}\n\nexit:\n\n\tif(inspector)\n\t{\n\t\tdelete inspector;\n\t}\n\n\treturn res;\n}\n\n\/\/\n\/\/ MAIN\n\/\/\nint main(int argc, char **argv)\n{\n\tdigwatch_init_res res;\n\n\tres = digwatch_init(argc, argv);\n\n\treturn res.m_res;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Launch and manage FastCGI child processes.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"Stock.hxx\"\n#include \"Quark.hxx\"\n#include \"stock\/MapStock.hxx\"\n#include \"stock\/Class.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"child_stock.hxx\"\n#include \"child_manager.hxx\"\n#include \"spawn\/Prepared.hxx\"\n#include \"spawn\/ChildOptions.hxx\"\n#include \"spawn\/JailConfig.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"event\/Event.hxx\"\n#include \"event\/Callback.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include <daemon\/log.h>\n\n#include <glib.h>\n\n#include <assert.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <string.h>\n\n#ifdef __linux\n#include <sched.h>\n#endif\n\nstruct FcgiStock {\n StockMap *hstock;\n StockMap *child_stock;\n\n void FadeAll() {\n hstock_fade_all(*hstock);\n hstock_fade_all(*child_stock);\n }\n};\n\nstruct FcgiChildParams {\n const char *executable_path;\n\n ConstBuffer<const char *> args;\n\n const ChildOptions *options;\n\n FcgiChildParams(const char *_executable_path,\n ConstBuffer<const char *> _args,\n const ChildOptions &_options)\n :executable_path(_executable_path), args(_args),\n options(&_options) {}\n\n const char *GetStockKey(struct pool &pool) const;\n};\n\nstruct FcgiConnection final : PoolStockItem {\n JailParams jail_params;\n\n struct jail_config jail_config;\n\n StockItem *child = nullptr;\n\n int fd = -1;\n Event event;\n\n \/**\n * Is this a fresh connection to the FastCGI child process?\n *\/\n bool fresh;\n\n \/**\n * Shall the FastCGI child process be killed?\n *\/\n bool kill;\n\n \/**\n * Was the current request aborted by the fcgi_client caller?\n *\/\n bool aborted;\n\n explicit FcgiConnection(struct pool &_pool, CreateStockItem c)\n :PoolStockItem(_pool, c) {}\n\n gcc_pure\n const char *GetStockKey() const {\n return child_stock_item_key(child);\n }\n\n void EventCallback(evutil_socket_t fd, short events);\n\n \/* virtual methods from class StockItem *\/\n bool Borrow(gcc_unused void *ctx) override;\n bool Release(gcc_unused void *ctx) override;\n void Destroy(void *ctx) override;\n};\n\nconst char *\nFcgiChildParams::GetStockKey(struct pool &pool) const\n{\n const char *key = executable_path;\n\n for (auto i : args)\n key = p_strcat(&pool, key, \" \", i, nullptr);\n\n for (auto i : options->env)\n key = p_strcat(&pool, key, \"$\", i, nullptr);\n\n char options_buffer[4096];\n *options->MakeId(options_buffer) = 0;\n if (*options_buffer != 0)\n key = p_strcat(&pool, key, options_buffer, nullptr);\n\n return key;\n}\n\n\/*\n * libevent callback\n *\n *\/\n\ninline void\nFcgiConnection::EventCallback(evutil_socket_t _fd, short events)\n{\n assert(_fd == fd);\n\n if ((events & EV_TIMEOUT) == 0) {\n char buffer;\n ssize_t nbytes = recv(_fd, &buffer, sizeof(buffer), MSG_DONTWAIT);\n if (nbytes < 0)\n daemon_log(2, \"error on idle FastCGI connection '%s': %s\\n\",\n GetStockKey(), strerror(errno));\n else if (nbytes > 0)\n daemon_log(2, \"unexpected data from idle FastCGI connection '%s'\\n\",\n GetStockKey());\n }\n\n InvokeIdleDisconnect();\n pool_commit();\n}\n\n\/*\n * child_stock class\n *\n *\/\n\nstatic bool\nfcgi_child_stock_prepare(void *info, int fd,\n PreparedChildProcess &p, GError **error_r)\n{\n const auto ¶ms = *(const FcgiChildParams *)info;\n const ChildOptions &options = *params.options;\n\n p.stdin_fd = fd;\n\n \/* the FastCGI protocol defines a channel for stderr, so we could\n close its \"real\" stderr here, but many FastCGI applications\n don't use the FastCGI protocol to send error messages, so we\n just keep it open *\/\n\n int null_fd = open(\"\/dev\/null\", O_WRONLY|O_CLOEXEC|O_NOCTTY);\n if (null_fd >= 0)\n p.stdout_fd = null_fd;\n\n p.Append(params.executable_path);\n for (auto i : params.args)\n p.Append(i);\n\n return options.CopyTo(p, true, nullptr, error_r);\n}\n\nstatic const ChildStockClass fcgi_child_stock_class = {\n .shutdown_signal = SIGUSR1,\n .socket_type = nullptr,\n .prepare = fcgi_child_stock_prepare,\n};\n\n\/*\n * stock class\n *\n *\/\n\nstatic void\nfcgi_stock_create(void *ctx, struct pool &parent_pool, CreateStockItem c,\n const char *key, void *info,\n struct pool &caller_pool,\n gcc_unused struct async_operation_ref &async_ref)\n{\n FcgiStock *fcgi_stock = (FcgiStock *)ctx;\n FcgiChildParams *params = (FcgiChildParams *)info;\n\n assert(key != nullptr);\n assert(params != nullptr);\n assert(params->executable_path != nullptr);\n\n auto &pool = *pool_new_linear(&parent_pool, \"fcgi_connection\", 2048);\n auto *connection = NewFromPool<FcgiConnection>(pool, pool, c);\n\n const ChildOptions *const options = params->options;\n if (options->jail.enabled) {\n connection->jail_params.CopyFrom(pool, options->jail);\n\n if (!jail_config_load(&connection->jail_config,\n \"\/etc\/cm4all\/jailcgi\/jail.conf\", &pool)) {\n GError *error = g_error_new(fcgi_quark(), 0,\n \"Failed to load \/etc\/cm4all\/jailcgi\/jail.conf\");\n connection->InvokeCreateError(error);\n return;\n }\n } else\n connection->jail_params.enabled = false;\n\n GError *error = nullptr;\n connection->child = hstock_get_now(*fcgi_stock->child_stock, caller_pool,\n key, params, &error);\n if (connection->child == nullptr) {\n g_prefix_error(&error, \"failed to start to FastCGI server '%s': \",\n key);\n connection->InvokeCreateError(error);\n return;\n }\n\n connection->fd = child_stock_item_connect(connection->child, &error);\n if (connection->fd < 0) {\n g_prefix_error(&error, \"failed to connect to FastCGI server '%s': \",\n key);\n\n connection->kill = true;\n connection->InvokeCreateError(error);\n return;\n }\n\n connection->fresh = true;\n connection->kill = false;\n connection->aborted = false;\n\n connection->event.Set(connection->fd, EV_READ|EV_TIMEOUT,\n MakeEventCallback(FcgiConnection, EventCallback),\n connection);\n\n connection->InvokeCreateSuccess();\n}\n\nbool\nFcgiConnection::Borrow(gcc_unused void *ctx)\n{\n \/* check the connection status before using it, just in case the\n FastCGI server has decided to close the connection before\n fcgi_connection_event_callback() got invoked *\/\n char buffer;\n ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);\n if (nbytes > 0) {\n daemon_log(2, \"unexpected data from idle FastCGI connection '%s'\\n\",\n GetStockKey());\n return false;\n } else if (nbytes == 0) {\n \/* connection closed (not worth a log message) *\/\n return false;\n } else if (errno != EAGAIN) {\n daemon_log(2, \"error on idle FastCGI connection '%s': %s\\n\",\n GetStockKey(), strerror(errno));\n return false;\n }\n\n event.Delete();\n aborted = false;\n return true;\n}\n\nbool\nFcgiConnection::Release(gcc_unused void *ctx)\n{\n static constexpr struct timeval tv = {\n .tv_sec = 300,\n .tv_usec = 0,\n };\n\n fresh = false;\n event.Add(tv);\n return true;\n}\n\nvoid\nFcgiConnection::Destroy(void *ctx)\n{\n FcgiStock *fcgi_stock = (FcgiStock *)ctx;\n\n if (fd >= 0) {\n event.Delete();\n close(fd);\n }\n\n if (child != nullptr)\n child_stock_put(fcgi_stock->child_stock, child, kill);\n\n PoolStockItem::Destroy(ctx);\n}\n\nstatic constexpr StockClass fcgi_stock_class = {\n .create = fcgi_stock_create,\n};\n\n\n\/*\n * interface\n *\n *\/\n\nFcgiStock *\nfcgi_stock_new(struct pool *pool, unsigned limit, unsigned max_idle)\n{\n auto fcgi_stock = NewFromPool<FcgiStock>(*pool);\n fcgi_stock->child_stock = child_stock_new(pool, limit, max_idle,\n &fcgi_child_stock_class);\n fcgi_stock->hstock = hstock_new(*pool, fcgi_stock_class, fcgi_stock,\n limit, max_idle);\n\n return fcgi_stock;\n}\n\nvoid\nfcgi_stock_free(FcgiStock *fcgi_stock)\n{\n hstock_free(fcgi_stock->hstock);\n hstock_free(fcgi_stock->child_stock);\n}\n\nvoid\nfcgi_stock_fade_all(FcgiStock &fs)\n{\n fs.FadeAll();\n}\n\nStockItem *\nfcgi_stock_get(FcgiStock *fcgi_stock, struct pool *pool,\n const ChildOptions &options,\n const char *executable_path,\n ConstBuffer<const char *> args,\n GError **error_r)\n{\n auto params = NewFromPool<FcgiChildParams>(*pool, executable_path,\n args, options);\n\n return hstock_get_now(*fcgi_stock->hstock, *pool,\n params->GetStockKey(*pool), params,\n error_r);\n}\n\nint\nfcgi_stock_item_get_domain(gcc_unused const StockItem &item)\n{\n return AF_UNIX;\n}\n\nint\nfcgi_stock_item_get(const StockItem &item)\n{\n const auto *connection = (const FcgiConnection *)&item;\n\n assert(connection->fd >= 0);\n\n return connection->fd;\n}\n\nconst char *\nfcgi_stock_translate_path(const StockItem &item,\n const char *path, struct pool *pool)\n{\n const auto *connection = (const FcgiConnection *)&item;\n\n if (!connection->jail_params.enabled)\n \/* no JailCGI - application's namespace is the same as ours,\n no translation needed *\/\n return path;\n\n const char *jailed = jail_translate_path(&connection->jail_config, path,\n connection->jail_params.home_directory,\n pool);\n return jailed != nullptr ? jailed : path;\n}\n\nvoid\nfcgi_stock_put(FcgiStock *fcgi_stock, StockItem &item,\n bool destroy)\n{\n auto *connection = (FcgiConnection *)&item;\n\n if (connection->fresh && connection->aborted && destroy)\n \/* the fcgi_client caller has aborted the request before the\n first response on a fresh connection was received: better\n kill the child process, it may be failing on us\n completely *\/\n connection->kill = true;\n\n hstock_put(*fcgi_stock->hstock, connection->GetStockKey(),\n item, destroy);\n}\n\nvoid\nfcgi_stock_aborted(StockItem &item)\n{\n auto *connection = (FcgiConnection *)&item;\n\n connection->aborted = true;\n}\n<commit_msg>fcgi\/Stock: convert pointer to reference<commit_after>\/*\n * Launch and manage FastCGI child processes.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"Stock.hxx\"\n#include \"Quark.hxx\"\n#include \"stock\/MapStock.hxx\"\n#include \"stock\/Class.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"child_stock.hxx\"\n#include \"child_manager.hxx\"\n#include \"spawn\/Prepared.hxx\"\n#include \"spawn\/ChildOptions.hxx\"\n#include \"spawn\/JailConfig.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"event\/Event.hxx\"\n#include \"event\/Callback.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include <daemon\/log.h>\n\n#include <glib.h>\n\n#include <assert.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <string.h>\n\n#ifdef __linux\n#include <sched.h>\n#endif\n\nstruct FcgiStock {\n StockMap *hstock;\n StockMap *child_stock;\n\n void FadeAll() {\n hstock_fade_all(*hstock);\n hstock_fade_all(*child_stock);\n }\n};\n\nstruct FcgiChildParams {\n const char *executable_path;\n\n ConstBuffer<const char *> args;\n\n const ChildOptions &options;\n\n FcgiChildParams(const char *_executable_path,\n ConstBuffer<const char *> _args,\n const ChildOptions &_options)\n :executable_path(_executable_path), args(_args),\n options(_options) {}\n\n const char *GetStockKey(struct pool &pool) const;\n};\n\nstruct FcgiConnection final : PoolStockItem {\n JailParams jail_params;\n\n struct jail_config jail_config;\n\n StockItem *child = nullptr;\n\n int fd = -1;\n Event event;\n\n \/**\n * Is this a fresh connection to the FastCGI child process?\n *\/\n bool fresh;\n\n \/**\n * Shall the FastCGI child process be killed?\n *\/\n bool kill;\n\n \/**\n * Was the current request aborted by the fcgi_client caller?\n *\/\n bool aborted;\n\n explicit FcgiConnection(struct pool &_pool, CreateStockItem c)\n :PoolStockItem(_pool, c) {}\n\n gcc_pure\n const char *GetStockKey() const {\n return child_stock_item_key(child);\n }\n\n void EventCallback(evutil_socket_t fd, short events);\n\n \/* virtual methods from class StockItem *\/\n bool Borrow(gcc_unused void *ctx) override;\n bool Release(gcc_unused void *ctx) override;\n void Destroy(void *ctx) override;\n};\n\nconst char *\nFcgiChildParams::GetStockKey(struct pool &pool) const\n{\n const char *key = executable_path;\n\n for (auto i : args)\n key = p_strcat(&pool, key, \" \", i, nullptr);\n\n for (auto i : options.env)\n key = p_strcat(&pool, key, \"$\", i, nullptr);\n\n char options_buffer[4096];\n *options.MakeId(options_buffer) = 0;\n if (*options_buffer != 0)\n key = p_strcat(&pool, key, options_buffer, nullptr);\n\n return key;\n}\n\n\/*\n * libevent callback\n *\n *\/\n\ninline void\nFcgiConnection::EventCallback(evutil_socket_t _fd, short events)\n{\n assert(_fd == fd);\n\n if ((events & EV_TIMEOUT) == 0) {\n char buffer;\n ssize_t nbytes = recv(_fd, &buffer, sizeof(buffer), MSG_DONTWAIT);\n if (nbytes < 0)\n daemon_log(2, \"error on idle FastCGI connection '%s': %s\\n\",\n GetStockKey(), strerror(errno));\n else if (nbytes > 0)\n daemon_log(2, \"unexpected data from idle FastCGI connection '%s'\\n\",\n GetStockKey());\n }\n\n InvokeIdleDisconnect();\n pool_commit();\n}\n\n\/*\n * child_stock class\n *\n *\/\n\nstatic bool\nfcgi_child_stock_prepare(void *info, int fd,\n PreparedChildProcess &p, GError **error_r)\n{\n const auto ¶ms = *(const FcgiChildParams *)info;\n const ChildOptions &options = params.options;\n\n p.stdin_fd = fd;\n\n \/* the FastCGI protocol defines a channel for stderr, so we could\n close its \"real\" stderr here, but many FastCGI applications\n don't use the FastCGI protocol to send error messages, so we\n just keep it open *\/\n\n int null_fd = open(\"\/dev\/null\", O_WRONLY|O_CLOEXEC|O_NOCTTY);\n if (null_fd >= 0)\n p.stdout_fd = null_fd;\n\n p.Append(params.executable_path);\n for (auto i : params.args)\n p.Append(i);\n\n return options.CopyTo(p, true, nullptr, error_r);\n}\n\nstatic const ChildStockClass fcgi_child_stock_class = {\n .shutdown_signal = SIGUSR1,\n .socket_type = nullptr,\n .prepare = fcgi_child_stock_prepare,\n};\n\n\/*\n * stock class\n *\n *\/\n\nstatic void\nfcgi_stock_create(void *ctx, struct pool &parent_pool, CreateStockItem c,\n const char *key, void *info,\n struct pool &caller_pool,\n gcc_unused struct async_operation_ref &async_ref)\n{\n FcgiStock *fcgi_stock = (FcgiStock *)ctx;\n FcgiChildParams *params = (FcgiChildParams *)info;\n\n assert(key != nullptr);\n assert(params != nullptr);\n assert(params->executable_path != nullptr);\n\n auto &pool = *pool_new_linear(&parent_pool, \"fcgi_connection\", 2048);\n auto *connection = NewFromPool<FcgiConnection>(pool, pool, c);\n\n const ChildOptions &options = params->options;\n if (options.jail.enabled) {\n connection->jail_params.CopyFrom(pool, options.jail);\n\n if (!jail_config_load(&connection->jail_config,\n \"\/etc\/cm4all\/jailcgi\/jail.conf\", &pool)) {\n GError *error = g_error_new(fcgi_quark(), 0,\n \"Failed to load \/etc\/cm4all\/jailcgi\/jail.conf\");\n connection->InvokeCreateError(error);\n return;\n }\n } else\n connection->jail_params.enabled = false;\n\n GError *error = nullptr;\n connection->child = hstock_get_now(*fcgi_stock->child_stock, caller_pool,\n key, params, &error);\n if (connection->child == nullptr) {\n g_prefix_error(&error, \"failed to start to FastCGI server '%s': \",\n key);\n connection->InvokeCreateError(error);\n return;\n }\n\n connection->fd = child_stock_item_connect(connection->child, &error);\n if (connection->fd < 0) {\n g_prefix_error(&error, \"failed to connect to FastCGI server '%s': \",\n key);\n\n connection->kill = true;\n connection->InvokeCreateError(error);\n return;\n }\n\n connection->fresh = true;\n connection->kill = false;\n connection->aborted = false;\n\n connection->event.Set(connection->fd, EV_READ|EV_TIMEOUT,\n MakeEventCallback(FcgiConnection, EventCallback),\n connection);\n\n connection->InvokeCreateSuccess();\n}\n\nbool\nFcgiConnection::Borrow(gcc_unused void *ctx)\n{\n \/* check the connection status before using it, just in case the\n FastCGI server has decided to close the connection before\n fcgi_connection_event_callback() got invoked *\/\n char buffer;\n ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);\n if (nbytes > 0) {\n daemon_log(2, \"unexpected data from idle FastCGI connection '%s'\\n\",\n GetStockKey());\n return false;\n } else if (nbytes == 0) {\n \/* connection closed (not worth a log message) *\/\n return false;\n } else if (errno != EAGAIN) {\n daemon_log(2, \"error on idle FastCGI connection '%s': %s\\n\",\n GetStockKey(), strerror(errno));\n return false;\n }\n\n event.Delete();\n aborted = false;\n return true;\n}\n\nbool\nFcgiConnection::Release(gcc_unused void *ctx)\n{\n static constexpr struct timeval tv = {\n .tv_sec = 300,\n .tv_usec = 0,\n };\n\n fresh = false;\n event.Add(tv);\n return true;\n}\n\nvoid\nFcgiConnection::Destroy(void *ctx)\n{\n FcgiStock *fcgi_stock = (FcgiStock *)ctx;\n\n if (fd >= 0) {\n event.Delete();\n close(fd);\n }\n\n if (child != nullptr)\n child_stock_put(fcgi_stock->child_stock, child, kill);\n\n PoolStockItem::Destroy(ctx);\n}\n\nstatic constexpr StockClass fcgi_stock_class = {\n .create = fcgi_stock_create,\n};\n\n\n\/*\n * interface\n *\n *\/\n\nFcgiStock *\nfcgi_stock_new(struct pool *pool, unsigned limit, unsigned max_idle)\n{\n auto fcgi_stock = NewFromPool<FcgiStock>(*pool);\n fcgi_stock->child_stock = child_stock_new(pool, limit, max_idle,\n &fcgi_child_stock_class);\n fcgi_stock->hstock = hstock_new(*pool, fcgi_stock_class, fcgi_stock,\n limit, max_idle);\n\n return fcgi_stock;\n}\n\nvoid\nfcgi_stock_free(FcgiStock *fcgi_stock)\n{\n hstock_free(fcgi_stock->hstock);\n hstock_free(fcgi_stock->child_stock);\n}\n\nvoid\nfcgi_stock_fade_all(FcgiStock &fs)\n{\n fs.FadeAll();\n}\n\nStockItem *\nfcgi_stock_get(FcgiStock *fcgi_stock, struct pool *pool,\n const ChildOptions &options,\n const char *executable_path,\n ConstBuffer<const char *> args,\n GError **error_r)\n{\n auto params = NewFromPool<FcgiChildParams>(*pool, executable_path,\n args, options);\n\n return hstock_get_now(*fcgi_stock->hstock, *pool,\n params->GetStockKey(*pool), params,\n error_r);\n}\n\nint\nfcgi_stock_item_get_domain(gcc_unused const StockItem &item)\n{\n return AF_UNIX;\n}\n\nint\nfcgi_stock_item_get(const StockItem &item)\n{\n const auto *connection = (const FcgiConnection *)&item;\n\n assert(connection->fd >= 0);\n\n return connection->fd;\n}\n\nconst char *\nfcgi_stock_translate_path(const StockItem &item,\n const char *path, struct pool *pool)\n{\n const auto *connection = (const FcgiConnection *)&item;\n\n if (!connection->jail_params.enabled)\n \/* no JailCGI - application's namespace is the same as ours,\n no translation needed *\/\n return path;\n\n const char *jailed = jail_translate_path(&connection->jail_config, path,\n connection->jail_params.home_directory,\n pool);\n return jailed != nullptr ? jailed : path;\n}\n\nvoid\nfcgi_stock_put(FcgiStock *fcgi_stock, StockItem &item,\n bool destroy)\n{\n auto *connection = (FcgiConnection *)&item;\n\n if (connection->fresh && connection->aborted && destroy)\n \/* the fcgi_client caller has aborted the request before the\n first response on a fresh connection was received: better\n kill the child process, it may be failing on us\n completely *\/\n connection->kill = true;\n\n hstock_put(*fcgi_stock->hstock, connection->GetStockKey(),\n item, destroy);\n}\n\nvoid\nfcgi_stock_aborted(StockItem &item)\n{\n auto *connection = (FcgiConnection *)&item;\n\n connection->aborted = true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\n\/**\n * @copyright 2013 Couchbase, Inc.\n *\n * @author Filipe Manana <filipe@couchbase.com>\n * @author Aliaksey Kandratsenka <alk@tut.by> (small optimization)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * 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, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n **\/\n\n#include \"file_merger.h\"\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n\n\ntypedef struct {\n void *data;\n unsigned file;\n} record_t;\n\n#define FREE_RECORD(ctx, rec) \\\n do { \\\n (*(ctx)->free_record)((rec)->data, (ctx)->user_ctx); \\\n free((rec)); \\\n } while (0)\n\nstruct file_merger_ctx_t;\n\ntypedef struct {\n struct file_merger_ctx_t *ctx;\n record_t **data;\n unsigned count;\n} sorted_vector_t;\n\ntypedef struct file_merger_ctx_t {\n unsigned num_files;\n FILE **files;\n FILE *dest_file;\n file_merger_read_record_t read_record;\n file_merger_write_record_t write_record;\n file_merger_record_free_t free_record;\n file_merger_compare_records_t compare_records;\n file_merger_deduplicate_records_t dedup_records;\n file_merger_feed_record_t feed_record;\n void *user_ctx;\n sorted_vector_t sorted_vector;\n} file_merger_ctx_t;\n\n\nstatic int init_sorted_vector(sorted_vector_t *sorted_vector, unsigned max_elements, file_merger_ctx_t *ctx);\nstatic void sorted_vector_destroy(sorted_vector_t *sorted_vector);\nstatic void sorted_vector_pop(sorted_vector_t *sorted_vector,\n record_t ***records,\n size_t *n);\nstatic int sorted_vector_add(sorted_vector_t *sorted_vector, record_t *record);\n\nstatic file_merger_error_t do_merge_files(file_merger_ctx_t *ctx);\n\n\nfile_merger_error_t merge_files(const char *source_files[],\n unsigned num_files,\n const char *dest_file,\n file_merger_read_record_t read_record,\n file_merger_write_record_t write_record,\n file_merger_feed_record_t feed_record,\n file_merger_compare_records_t compare_records,\n file_merger_deduplicate_records_t dedup_records,\n file_merger_record_free_t free_record,\n int skip_writeback,\n void *user_ctx)\n{\n file_merger_ctx_t ctx;\n file_merger_error_t ret;\n unsigned i, j;\n\n if (num_files == 0) {\n return FILE_MERGER_ERROR_BAD_ARG;\n }\n\n ctx.num_files = num_files;\n ctx.read_record = read_record;\n ctx.write_record = write_record;\n ctx.free_record = free_record;\n ctx.compare_records = compare_records;\n ctx.user_ctx = user_ctx;\n ctx.feed_record = feed_record;\n ctx.dedup_records = dedup_records;\n\n if (feed_record && skip_writeback) {\n ctx.dest_file = NULL;\n } else {\n ctx.dest_file = fopen(dest_file, \"ab\");\n }\n\n if (!init_sorted_vector(&ctx.sorted_vector, num_files, &ctx)) {\n return FILE_MERGER_ERROR_ALLOC;\n }\n\n if (feed_record == NULL && ctx.dest_file == NULL) {\n sorted_vector_destroy(&ctx.sorted_vector);\n return FILE_MERGER_ERROR_OPEN_FILE;\n }\n\n ctx.files = (FILE **) malloc(sizeof(FILE *) * num_files);\n\n if (ctx.files == NULL) {\n sorted_vector_destroy(&ctx.sorted_vector);\n fclose(ctx.dest_file);\n return FILE_MERGER_ERROR_ALLOC;\n }\n\n for (i = 0; i < num_files; ++i) {\n ctx.files[i] = fopen(source_files[i], \"rb\");\n\n if (ctx.files[i] == NULL) {\n for (j = 0; j < i; ++j) {\n fclose(ctx.files[j]);\n }\n free(ctx.files);\n fclose(ctx.dest_file);\n sorted_vector_destroy(&ctx.sorted_vector);\n\n return FILE_MERGER_ERROR_OPEN_FILE;\n }\n }\n\n ret = do_merge_files(&ctx);\n\n for (i = 0; i < ctx.num_files; ++i) {\n if (ctx.files[i] != NULL) {\n fclose(ctx.files[i]);\n }\n }\n free(ctx.files);\n sorted_vector_destroy(&ctx.sorted_vector);\n if (ctx.dest_file) {\n fclose(ctx.dest_file);\n }\n\n return ret;\n}\n\n\nstatic file_merger_error_t do_merge_files(file_merger_ctx_t *ctx)\n{\n unsigned i;\n\n for (i = 0; i < ctx->num_files; ++i) {\n FILE *f = ctx->files[i];\n int record_len;\n void *record_data;\n record_t *record;\n\n record_len = (*ctx->read_record)(f, &record_data, ctx->user_ctx);\n\n if (record_len == 0) {\n fclose(f);\n ctx->files[i] = NULL;\n } else if (record_len < 0) {\n return (file_merger_error_t) record_len;\n } else {\n int rv;\n record = (record_t *) malloc(sizeof(*record));\n if (record == NULL) {\n return FILE_MERGER_ERROR_ALLOC;\n }\n record->data = record_data;\n record->file = i;\n rv = sorted_vector_add(&ctx->sorted_vector, record);\n if (!rv) {\n return FILE_MERGER_SORT_ERROR;\n }\n }\n }\n\n while (ctx->sorted_vector.count != 0) {\n record_t **records;\n size_t n;\n size_t i;\n void *record_data;\n int record_len;\n file_merger_error_t ret;\n\n \/* The head of the list is the required item which needs to be written\n * to the output destination records file.\n * For each duplicated item that is eliminated (elements of linked\n * list), we need to read one record from the same file as the\n * duplicated record came from and add them to the sort vector.\n *\/\n sorted_vector_pop(&ctx->sorted_vector, &records, &n);\n assert(records != NULL);\n assert(n != 0);\n\n if (ctx->feed_record) {\n ret = (*ctx->feed_record)(records[0]->data, ctx->user_ctx);\n if (ret != FILE_MERGER_SUCCESS) {\n FREE_RECORD(ctx, records[0]);\n return ret;\n }\n } else {\n assert(ctx->dest_file != NULL);\n }\n\n if (ctx->dest_file) {\n ret = (*ctx->write_record)(ctx->dest_file, records[0]->data, ctx->user_ctx);\n if (ret != FILE_MERGER_SUCCESS) {\n FREE_RECORD(ctx, records[0]);\n return ret;\n }\n }\n\n for (i = 0; i < n; i++) {\n record_len = (*ctx->read_record)(ctx->files[records[i]->file],\n &record_data,\n ctx->user_ctx);\n if (record_len == 0) {\n fclose(ctx->files[records[i]->file]);\n ctx->files[records[i]->file] = NULL;\n FREE_RECORD(ctx, records[i]);\n\n } else if (record_len < 0) {\n FREE_RECORD(ctx, records[i]);\n\n return (file_merger_error_t) record_len;\n } else {\n int rv;\n (*ctx->free_record)(records[i]->data, ctx->user_ctx);\n records[i]->data = record_data;\n rv = sorted_vector_add(&ctx->sorted_vector, records[i]);\n if (!rv) {\n return FILE_MERGER_SORT_ERROR;\n }\n }\n }\n\n free(records);\n }\n\n return FILE_MERGER_SUCCESS;\n}\n\n\nstatic int init_sorted_vector(sorted_vector_t *sorted_vector,\n unsigned max_elements,\n file_merger_ctx_t *ctx)\n{\n sorted_vector->data = (record_t **) malloc(sizeof(record_t *) * max_elements);\n if (sorted_vector->data == NULL) {\n return 0;\n }\n\n sorted_vector->count = 0;\n sorted_vector->ctx = ctx;\n\n return 1;\n}\n\n\nstatic void sorted_vector_destroy(sorted_vector_t *sorted_vector)\n{\n unsigned i;\n\n for (i = 0; i < sorted_vector->count; ++i) {\n FREE_RECORD(sorted_vector->ctx, sorted_vector->data[i]);\n }\n\n free(sorted_vector->data);\n}\n\n\n#define SORTED_VECTOR_CMP(h, a, b) \\\n (*(h)->ctx->compare_records)((a)->data, (b)->data, (h)->ctx->user_ctx)\n\nstatic void sorted_vector_pop(sorted_vector_t *sorted_vector,\n record_t ***records,\n size_t *n)\n{\n record_t *head;\n file_merger_record_t **duplicates;\n size_t i, j;\n\n if (sorted_vector->count == 0) {\n *records = NULL;\n *n = 0;\n return;\n }\n\n \/* For deduplication, return the list of records whose keys are equal.\n * Hence they can be eliminated from the sort vector and least element can\n * be picked for writing out to the output file.\n * *\/\n head = sorted_vector->data[0];\n\n for (i = 1; sorted_vector->ctx->dedup_records != NULL && i < sorted_vector->count; i++) {\n if (SORTED_VECTOR_CMP(sorted_vector, head, sorted_vector->data[i]) != 0) {\n break;\n }\n }\n\n *records = (record_t **) malloc(sizeof(record_t *) * i);\n memcpy(*records, sorted_vector->data, sizeof(record_t *) * i);\n *n = i;\n\n\n if (i > 1) {\n record_t *tmp;\n duplicates = (file_merger_record_t **) *records;\n j = sorted_vector->ctx->dedup_records(duplicates, i, sorted_vector->ctx->user_ctx);\n tmp = (*records)[0];\n (*records)[0] = (*records)[j];\n (*records)[j] = tmp;\n }\n\n sorted_vector->count -= i;\n memmove(sorted_vector->data + 0, sorted_vector->data + i,\n sizeof(sorted_vector->data[0]) * (sorted_vector->count));\n}\n\n\nstatic int sorted_vector_add(sorted_vector_t *sorted_vector, record_t *record)\n{\n unsigned l, r;\n\n if (sorted_vector->count == sorted_vector->ctx->num_files) {\n \/* sorted_vector full *\/\n return 0;\n }\n\n l = 0;\n r = sorted_vector->count;\n while (r - l > 1) {\n unsigned pos = (l + r) \/ 2;\n\n if (SORTED_VECTOR_CMP(sorted_vector, record, sorted_vector->data[pos]) < 0) {\n r = pos;\n } else {\n l = pos;\n }\n }\n\n if (l == 0 && r != 0) {\n if (SORTED_VECTOR_CMP(sorted_vector, record, sorted_vector->data[0]) < 0) {\n r = 0;\n }\n }\n\n if (r < sorted_vector->count) {\n memmove(sorted_vector->data + r + 1,\n sorted_vector->data + r,\n sizeof(sorted_vector->data[0]) * (sorted_vector->count - r));\n }\n\n sorted_vector->count += 1;\n\n sorted_vector->data[r] = record;\n\n return 1;\n}\n<commit_msg>MB-17154: Free records in file merger correctly<commit_after>\/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\n\/**\n * @copyright 2013 Couchbase, Inc.\n *\n * @author Filipe Manana <filipe@couchbase.com>\n * @author Aliaksey Kandratsenka <alk@tut.by> (small optimization)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * 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, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n **\/\n\n#include \"file_merger.h\"\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n\n\ntypedef struct {\n void *data;\n unsigned file;\n} record_t;\n\n#define FREE_RECORD(ctx, rec) \\\n do { \\\n (*(ctx)->free_record)((rec)->data, (ctx)->user_ctx); \\\n free((rec)); \\\n } while (0)\n\nstruct file_merger_ctx_t;\n\ntypedef struct {\n struct file_merger_ctx_t *ctx;\n record_t **data;\n unsigned count;\n} sorted_vector_t;\n\ntypedef struct file_merger_ctx_t {\n unsigned num_files;\n FILE **files;\n FILE *dest_file;\n file_merger_read_record_t read_record;\n file_merger_write_record_t write_record;\n file_merger_record_free_t free_record;\n file_merger_compare_records_t compare_records;\n file_merger_deduplicate_records_t dedup_records;\n file_merger_feed_record_t feed_record;\n void *user_ctx;\n sorted_vector_t sorted_vector;\n} file_merger_ctx_t;\n\n\nstatic int init_sorted_vector(sorted_vector_t *sorted_vector, unsigned max_elements, file_merger_ctx_t *ctx);\nstatic void sorted_vector_destroy(sorted_vector_t *sorted_vector);\nstatic void sorted_vector_pop(sorted_vector_t *sorted_vector,\n record_t ***records,\n size_t *n);\nstatic int sorted_vector_add(sorted_vector_t *sorted_vector, record_t *record);\n\nstatic file_merger_error_t do_merge_files(file_merger_ctx_t *ctx);\nstatic void free_all_records(file_merger_ctx_t *ctx, record_t **records,\n int offset, int num);\n\n\nfile_merger_error_t merge_files(const char *source_files[],\n unsigned num_files,\n const char *dest_file,\n file_merger_read_record_t read_record,\n file_merger_write_record_t write_record,\n file_merger_feed_record_t feed_record,\n file_merger_compare_records_t compare_records,\n file_merger_deduplicate_records_t dedup_records,\n file_merger_record_free_t free_record,\n int skip_writeback,\n void *user_ctx)\n{\n file_merger_ctx_t ctx;\n file_merger_error_t ret;\n unsigned i, j;\n\n if (num_files == 0) {\n return FILE_MERGER_ERROR_BAD_ARG;\n }\n\n ctx.num_files = num_files;\n ctx.read_record = read_record;\n ctx.write_record = write_record;\n ctx.free_record = free_record;\n ctx.compare_records = compare_records;\n ctx.user_ctx = user_ctx;\n ctx.feed_record = feed_record;\n ctx.dedup_records = dedup_records;\n\n if (feed_record && skip_writeback) {\n ctx.dest_file = NULL;\n } else {\n ctx.dest_file = fopen(dest_file, \"ab\");\n }\n\n if (!init_sorted_vector(&ctx.sorted_vector, num_files, &ctx)) {\n return FILE_MERGER_ERROR_ALLOC;\n }\n\n if (feed_record == NULL && ctx.dest_file == NULL) {\n sorted_vector_destroy(&ctx.sorted_vector);\n return FILE_MERGER_ERROR_OPEN_FILE;\n }\n\n ctx.files = (FILE **) malloc(sizeof(FILE *) * num_files);\n\n if (ctx.files == NULL) {\n sorted_vector_destroy(&ctx.sorted_vector);\n fclose(ctx.dest_file);\n return FILE_MERGER_ERROR_ALLOC;\n }\n\n for (i = 0; i < num_files; ++i) {\n ctx.files[i] = fopen(source_files[i], \"rb\");\n\n if (ctx.files[i] == NULL) {\n for (j = 0; j < i; ++j) {\n fclose(ctx.files[j]);\n }\n free(ctx.files);\n fclose(ctx.dest_file);\n sorted_vector_destroy(&ctx.sorted_vector);\n\n return FILE_MERGER_ERROR_OPEN_FILE;\n }\n }\n\n ret = do_merge_files(&ctx);\n\n for (i = 0; i < ctx.num_files; ++i) {\n if (ctx.files[i] != NULL) {\n fclose(ctx.files[i]);\n }\n }\n free(ctx.files);\n sorted_vector_destroy(&ctx.sorted_vector);\n if (ctx.dest_file) {\n fclose(ctx.dest_file);\n }\n\n return ret;\n}\n\n\nstatic file_merger_error_t do_merge_files(file_merger_ctx_t *ctx)\n{\n unsigned i;\n\n for (i = 0; i < ctx->num_files; ++i) {\n FILE *f = ctx->files[i];\n int record_len;\n void *record_data;\n record_t *record;\n\n record_len = (*ctx->read_record)(f, &record_data, ctx->user_ctx);\n\n if (record_len == 0) {\n fclose(f);\n ctx->files[i] = NULL;\n } else if (record_len < 0) {\n return (file_merger_error_t) record_len;\n } else {\n int rv;\n record = (record_t *) malloc(sizeof(*record));\n if (record == NULL) {\n return FILE_MERGER_ERROR_ALLOC;\n }\n record->data = record_data;\n record->file = i;\n rv = sorted_vector_add(&ctx->sorted_vector, record);\n if (!rv) {\n FREE_RECORD(ctx, record);\n return FILE_MERGER_SORT_ERROR;\n }\n }\n }\n\n while (ctx->sorted_vector.count != 0) {\n record_t **records;\n size_t n;\n size_t i;\n void *record_data;\n int record_len;\n file_merger_error_t ret;\n\n \/* The head of the list is the required item which needs to be written\n * to the output destination records file.\n * For each duplicated item that is eliminated (elements of linked\n * list), we need to read one record from the same file as the\n * duplicated record came from and add them to the sort vector.\n *\/\n sorted_vector_pop(&ctx->sorted_vector, &records, &n);\n assert(records != NULL);\n assert(n != 0);\n\n if (ctx->feed_record) {\n ret = (*ctx->feed_record)(records[0]->data, ctx->user_ctx);\n if (ret != FILE_MERGER_SUCCESS) {\n free_all_records(ctx, records, 0, n);\n return ret;\n }\n } else {\n assert(ctx->dest_file != NULL);\n }\n\n if (ctx->dest_file) {\n ret = (*ctx->write_record)(ctx->dest_file, records[0]->data, ctx->user_ctx);\n if (ret != FILE_MERGER_SUCCESS) {\n free_all_records(ctx, records, 0, n);\n return ret;\n }\n }\n\n for (i = 0; i < n; i++) {\n record_len = (*ctx->read_record)(ctx->files[records[i]->file],\n &record_data,\n ctx->user_ctx);\n if (record_len == 0) {\n fclose(ctx->files[records[i]->file]);\n ctx->files[records[i]->file] = NULL;\n FREE_RECORD(ctx, records[i]);\n\n } else if (record_len < 0) {\n free_all_records(ctx, records, i, n);\n return (file_merger_error_t) record_len;\n } else {\n int rv;\n (*ctx->free_record)(records[i]->data, ctx->user_ctx);\n records[i]->data = record_data;\n rv = sorted_vector_add(&ctx->sorted_vector, records[i]);\n if (!rv) {\n free_all_records(ctx, records, i, n);\n return FILE_MERGER_SORT_ERROR;\n }\n }\n }\n\n free(records);\n }\n\n return FILE_MERGER_SUCCESS;\n}\n\n\nstatic void free_all_records(file_merger_ctx_t *ctx, record_t **records,\n int offset, int num) {\n for (; offset < num; offset++) {\n FREE_RECORD(ctx, records[offset]);\n }\n free(records);\n}\n\n\nstatic int init_sorted_vector(sorted_vector_t *sorted_vector,\n unsigned max_elements,\n file_merger_ctx_t *ctx)\n{\n sorted_vector->data = (record_t **) malloc(sizeof(record_t *) * max_elements);\n if (sorted_vector->data == NULL) {\n return 0;\n }\n\n sorted_vector->count = 0;\n sorted_vector->ctx = ctx;\n\n return 1;\n}\n\n\nstatic void sorted_vector_destroy(sorted_vector_t *sorted_vector)\n{\n unsigned i;\n\n for (i = 0; i < sorted_vector->count; ++i) {\n FREE_RECORD(sorted_vector->ctx, sorted_vector->data[i]);\n }\n\n free(sorted_vector->data);\n}\n\n\n#define SORTED_VECTOR_CMP(h, a, b) \\\n (*(h)->ctx->compare_records)((a)->data, (b)->data, (h)->ctx->user_ctx)\n\nstatic void sorted_vector_pop(sorted_vector_t *sorted_vector,\n record_t ***records,\n size_t *n)\n{\n record_t *head;\n file_merger_record_t **duplicates;\n size_t i, j;\n\n if (sorted_vector->count == 0) {\n *records = NULL;\n *n = 0;\n return;\n }\n\n \/* For deduplication, return the list of records whose keys are equal.\n * Hence they can be eliminated from the sort vector and least element can\n * be picked for writing out to the output file.\n * *\/\n head = sorted_vector->data[0];\n\n for (i = 1; sorted_vector->ctx->dedup_records != NULL && i < sorted_vector->count; i++) {\n if (SORTED_VECTOR_CMP(sorted_vector, head, sorted_vector->data[i]) != 0) {\n break;\n }\n }\n\n *records = (record_t **) malloc(sizeof(record_t *) * i);\n memcpy(*records, sorted_vector->data, sizeof(record_t *) * i);\n *n = i;\n\n\n if (i > 1) {\n record_t *tmp;\n duplicates = (file_merger_record_t **) *records;\n j = sorted_vector->ctx->dedup_records(duplicates, i, sorted_vector->ctx->user_ctx);\n tmp = (*records)[0];\n (*records)[0] = (*records)[j];\n (*records)[j] = tmp;\n }\n\n sorted_vector->count -= i;\n memmove(sorted_vector->data + 0, sorted_vector->data + i,\n sizeof(sorted_vector->data[0]) * (sorted_vector->count));\n}\n\n\nstatic int sorted_vector_add(sorted_vector_t *sorted_vector, record_t *record)\n{\n unsigned l, r;\n\n if (sorted_vector->count == sorted_vector->ctx->num_files) {\n \/* sorted_vector full *\/\n return 0;\n }\n\n l = 0;\n r = sorted_vector->count;\n while (r - l > 1) {\n unsigned pos = (l + r) \/ 2;\n\n if (SORTED_VECTOR_CMP(sorted_vector, record, sorted_vector->data[pos]) < 0) {\n r = pos;\n } else {\n l = pos;\n }\n }\n\n if (l == 0 && r != 0) {\n if (SORTED_VECTOR_CMP(sorted_vector, record, sorted_vector->data[0]) < 0) {\n r = 0;\n }\n }\n\n if (r < sorted_vector->count) {\n memmove(sorted_vector->data + r + 1,\n sorted_vector->data + r,\n sizeof(sorted_vector->data[0]) * (sorted_vector->count - r));\n }\n\n sorted_vector->count += 1;\n\n sorted_vector->data[r] = record;\n\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * This file is part of CameraPlus.\n *\n * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.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 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\n#include \"filenaming.h\"\n#include <QDir>\n#include <QDate>\n#include <QFile>\n#include <QDeclarativeInfo>\n\n#define PATH QString(\"%1%2MyDocs%2cameraplus%2\").arg(QDir::homePath()).arg(QDir::separator())\n#define TEMP_PATH QString(\"%1%2MyDocs%2.cameraplus%2\").arg(QDir::homePath()).arg(QDir::separator())\n\nFileNaming::FileNaming(QObject *parent) :\n QObject(parent), m_index(-1) {\n\n}\n\nFileNaming::~FileNaming() {\n\n}\n\nQString FileNaming::imageSuffix() const {\n return m_image;\n}\n\nvoid FileNaming::setImageSuffix(const QString& suffix) {\n if (m_image != suffix) {\n m_image = suffix;\n emit imageSuffixChanged();\n }\n}\n\nQString FileNaming::videoSuffix() const {\n return m_video;\n}\n\nvoid FileNaming::setVideoSuffix(const QString& suffix) {\n if (m_video != suffix) {\n m_video = suffix;\n emit videoSuffixChanged();\n }\n}\n\nQString FileNaming::imageFileName() {\n return fileName(m_image);\n}\n\nQString FileNaming::videoFileName() {\n return fileName(m_video);\n}\n\nQString FileNaming::fileName(const QString& suffix) {\n QString path = FileNaming::path();\n QString date = QDate::currentDate().toString(\"yyyyMMdd\");\n QDir dir(path);\n\n if (suffix.isEmpty()) {\n return QString();\n }\n\n if (path.isEmpty()) {\n return QString();\n }\n\n if (date != m_date) {\n m_index = -1;\n m_date = date;\n }\n\n if (m_index == -1) {\n QStringList filters(QString(\"*%1_*\").arg(date));\n QStringList entries = dir.entryList(filters, QDir::Files, QDir::Name);\n if (entries.isEmpty()) {\n m_index = 0;\n }\n else {\n QString name = QFile(entries.last()).fileName();\n m_index = name.section('_', 1, 1).section('.', 0, 0).toInt();\n }\n }\n\n ++m_index;\n\n QString name = QString(\"%1%2_%3.%4\").arg(path).arg(date).arg(QString().sprintf(\"%03i\", m_index)).\n arg(suffix);\n\n if (QFile(name).exists()) {\n return QString();\n }\n\n return name;\n}\n\nQString FileNaming::path() {\n if (m_path.isEmpty()) {\n m_path = canonicalPath(PATH);\n }\n\n return m_path;\n}\n\nQString FileNaming::temporaryPath() {\n if (m_temp.isEmpty()) {\n m_temp = canonicalPath(TEMP_PATH);\n }\n\n return m_temp;\n}\n\nQString FileNaming::canonicalPath(const QString& path) {\n if (!QDir::root().mkpath(path)) {\n qmlInfo(this) << \"Failed to create path\" << path;\n return QString();\n }\n\n QString newPath = QFileInfo(path).canonicalFilePath();\n\n if (newPath.isEmpty()) {\n return newPath;\n }\n\n if (!newPath.endsWith(QDir::separator())) {\n newPath.append(QDir::separator());\n }\n\n return newPath;\n}\n\nQString FileNaming::temporaryVideoFileName() {\n QString path = temporaryPath();\n\n if (path.isEmpty()) {\n return path;\n }\n\n return QString(\"%1.cameraplus_video.tmp\").arg(path);\n}\n<commit_msg>Store captures underneath MyDocs\/DCIM<commit_after>\/*!\n * This file is part of CameraPlus.\n *\n * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.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 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\n#include \"filenaming.h\"\n#include <QDir>\n#include <QDate>\n#include <QFile>\n#include <QDeclarativeInfo>\n\n#define PATH QString(\"%1%2MyDocs%2DCIM%2\").arg(QDir::homePath()).arg(QDir::separator())\n#define TEMP_PATH QString(\"%1%2MyDocs%2.cameraplus%2\").arg(QDir::homePath()).arg(QDir::separator())\n\nFileNaming::FileNaming(QObject *parent) :\n QObject(parent), m_index(-1) {\n\n}\n\nFileNaming::~FileNaming() {\n\n}\n\nQString FileNaming::imageSuffix() const {\n return m_image;\n}\n\nvoid FileNaming::setImageSuffix(const QString& suffix) {\n if (m_image != suffix) {\n m_image = suffix;\n emit imageSuffixChanged();\n }\n}\n\nQString FileNaming::videoSuffix() const {\n return m_video;\n}\n\nvoid FileNaming::setVideoSuffix(const QString& suffix) {\n if (m_video != suffix) {\n m_video = suffix;\n emit videoSuffixChanged();\n }\n}\n\nQString FileNaming::imageFileName() {\n return fileName(m_image);\n}\n\nQString FileNaming::videoFileName() {\n return fileName(m_video);\n}\n\nQString FileNaming::fileName(const QString& suffix) {\n QString path = FileNaming::path();\n QString date = QDate::currentDate().toString(\"yyyyMMdd\");\n QDir dir(path);\n\n if (suffix.isEmpty()) {\n return QString();\n }\n\n if (path.isEmpty()) {\n return QString();\n }\n\n if (date != m_date) {\n m_index = -1;\n m_date = date;\n }\n\n if (m_index == -1) {\n QStringList filters(QString(\"*%1_*\").arg(date));\n QStringList entries = dir.entryList(filters, QDir::Files, QDir::Name);\n if (entries.isEmpty()) {\n m_index = 0;\n }\n else {\n QString name = QFile(entries.last()).fileName();\n m_index = name.section('_', 1, 1).section('.', 0, 0).toInt();\n }\n }\n\n ++m_index;\n\n QString name = QString(\"%1%2_%3.%4\").arg(path).arg(date).arg(QString().sprintf(\"%03i\", m_index)).\n arg(suffix);\n\n if (QFile(name).exists()) {\n return QString();\n }\n\n return name;\n}\n\nQString FileNaming::path() {\n if (m_path.isEmpty()) {\n m_path = canonicalPath(PATH);\n }\n\n return m_path;\n}\n\nQString FileNaming::temporaryPath() {\n if (m_temp.isEmpty()) {\n m_temp = canonicalPath(TEMP_PATH);\n }\n\n return m_temp;\n}\n\nQString FileNaming::canonicalPath(const QString& path) {\n if (!QDir::root().mkpath(path)) {\n qmlInfo(this) << \"Failed to create path\" << path;\n return QString();\n }\n\n QString newPath = QFileInfo(path).canonicalFilePath();\n\n if (newPath.isEmpty()) {\n return newPath;\n }\n\n if (!newPath.endsWith(QDir::separator())) {\n newPath.append(QDir::separator());\n }\n\n return newPath;\n}\n\nQString FileNaming::temporaryVideoFileName() {\n QString path = temporaryPath();\n\n if (path.isEmpty()) {\n return path;\n }\n\n return QString(\"%1.cameraplus_video.tmp\").arg(path);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <matrix.hpp>\n\n\tMatrix :: Matrix(){};\n\n\tMatrix :: Matrix(int a, int b)\n\t{\n\t\tcolumns = b;\n\t\tstrings = a;\n\t\tmatrix = new int*[a];\n\n\t\tfor (int i = 0; i < a; i++)\n\t\t{\n\t\t\tmatrix[i] = new int[b]{0};\n\t\t}\n\t};\n\n\t void Matrix :: print(void) const\n\t{\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < columns; j++)\n\t\t\t{\n\t\t\t\tcout << get(i, j) << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t\tcout << endl;\n\t};\n\n\tvoid Matrix :: input(string filen)\n\t{\n\t\tifstream file;\n\t\tfile.open(filen);\n\t\tif (file_is_open())\n\t\t\tcout <<\"error!\"<endl;\n\t\telse\n\t\t{\n\n\t\tmatrix[i] = new *int [strings];\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tmatrix[i] = new *int [columns];\n\t\t\tfor (int j = 0; j < columns; j++)\n\t\t\t{\n\t\t\t\tfile >> matrix[i][j];\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid Matrix :: set(int x, int y, int z)\n\t{\n\t\tmatrix[x][y] = z;\n\t};\n\n\tint Matrix :: get(int x, int y) const\n\t{\n\t\treturn matrix[x][y];\n\t};\n\n\tMatrix Matrix:: operator+ (Matrix a) const\n\t{\n\t\tMatrix c(strings, columns);\n\n\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < columns; j++)\n\t\t\t{\n\t\t\t\tc.set(i, j, a.get(i, j) + get(i, j));\n\t\t\t}\n\t\t}\n\t\treturn c;\n\t};\n\n\tMatrix Matrix :: operator* (Matrix a) const\n\t{\n\t\tMatrix c(strings, a.columns);\n\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < a.columns; j++)\n\t\t\t{\n\t\t\t\tint temp = 0;\n\t\t\t\tfor (int k = 0; k < strings; k++)\n\t\t\t\t{\n\t\t\t\t\ttemp += get(i, k) * a.get(k, j);\n\t\t\t\t}\n\t\t\t\tc.set(i, j, temp);\n\t\t\t}\n\t\t}\n\n\t\treturn c;\n\t};\n\n\tMatrix& Matrix :: operator= (Matrix &other) \n\t{\n\t\tif (this != &other)\n\t\t{\n\t\t\tfor (int i = 0; i < strings; i++)\n\t\t\t{\n\t\t\t\tdelete[] matrix[i];\n\t\t\t}\n\n\t\t\tdelete[] matrix;\n\n\t\t\tcolumns = other.columns;\n\t\t\tstrings = other.strings;\n\n\t\t\tmatrix = new int*[strings];\n\n\t\t\tfor (int i = 0; i < strings; i++)\n\t\t\t{\n\t\t\t\tmatrix[i] = new int[columns]{0};\n\t\t\t}\n\n\t\t\tmatrix = other.matrix;\n\t\t}\n\t\treturn *this;\n\t};\n\n\tbool Matrix :: operator== (Matrix &a) const\n\t{\n\t\tbool k = false;\n\n\t\tfor (int i = 0; i < strings; i++){\n\n\t\t\tfor (int j = 0; j < columns; j++){\n\n\t\t\t\tif (matrix[i][j] == a.matrix[i][j])\n\n\t\t\t\t\tk = true;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn k;\n\t}\n\n\tistream& operator>> (istream& infile, const Matrix& result)\n\n\t{\n\n\t\tfor (int i = 0; i < result.strings; i++)\n\n\t\t\tfor (int j = 0; j < result.columns; j++)\n\n\t\t\t\tinfile >> result.matrix[i][j];\n\n\t\treturn infile;\n\n\t}\n\n\t ostream& operator<< (ostream& os, const Matrix& a)\n\t{\n\t\tfor (int i = 0; i < a.strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < a.columns; j++)\n\t\t\t{\n\t\t\t\tos << a.matrix[i, j] << \" \";\n\t\t\t}\n\t\t\tos << endl;\n\t\t}\n\t\tos << endl;\n\t\treturn os;\n\t}\n\n\n\tMatrix :: ~Matrix()\n\t{\n\t\t\/*for (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tdelete[] matrix[i];\n\t\t}\n\n\t\tdelete[] matrix;*\/\n\t};\n};\n\n\n<commit_msg>Update matrix.cpp<commit_after>#include <matrix.hpp>\n\n\tMatrix :: Matrix(){};\n\n\tMatrix :: Matrix(int a, int b)\n\t{\n\t\tcolumns = b;\n\t\tstrings = a;\n\t\tmatrix = new int*[a];\n\n\t\tfor (int i = 0; i < a; i++)\n\t\t{\n\t\t\tmatrix[i] = new int[b]{0};\n\t\t}\n\t};\n\n\t void print(void) const\n\t{\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < columns; j++)\n\t\t\t{\n\t\t\t\tcout << get(i, j) << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t\tcout << endl;\n\t};\n\n\tvoid input(string filen)\n\t{\n\t\tifstream file;\n\t\tfile.open(filen);\n\t\tif (file_is_open())\n\t\t\tcout <<\"error!\"<endl;\n\t\telse\n\t\t{\n\n\t\tmatrix[i] = new *int [strings];\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tmatrix[i] = new *int [columns];\n\t\t\tfor (int j = 0; j < columns; j++)\n\t\t\t{\n\t\t\t\tfile >> matrix[i][j];\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid set(int x, int y, int z)\n\t{\n\t\tmatrix[x][y] = z;\n\t};\n\n\tint get(int x, int y) const\n\t{\n\t\treturn matrix[x][y];\n\t};\n\n\tMatrix Matrix:: operator+ (Matrix a) const\n\t{\n\t\tMatrix c(strings, columns);\n\n\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < columns; j++)\n\t\t\t{\n\t\t\t\tc.set(i, j, a.get(i, j) + get(i, j));\n\t\t\t}\n\t\t}\n\t\treturn c;\n\t};\n\n\tMatrix Matrix :: operator* (Matrix a) const\n\t{\n\t\tMatrix c(strings, a.columns);\n\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < a.columns; j++)\n\t\t\t{\n\t\t\t\tint temp = 0;\n\t\t\t\tfor (int k = 0; k < strings; k++)\n\t\t\t\t{\n\t\t\t\t\ttemp += get(i, k) * a.get(k, j);\n\t\t\t\t}\n\t\t\t\tc.set(i, j, temp);\n\t\t\t}\n\t\t}\n\n\t\treturn c;\n\t};\n\n\tMatrix& Matrix :: operator= (Matrix &other) \n\t{\n\t\tif (this != &other)\n\t\t{\n\t\t\tfor (int i = 0; i < strings; i++)\n\t\t\t{\n\t\t\t\tdelete[] matrix[i];\n\t\t\t}\n\n\t\t\tdelete[] matrix;\n\n\t\t\tcolumns = other.columns;\n\t\t\tstrings = other.strings;\n\n\t\t\tmatrix = new int*[strings];\n\n\t\t\tfor (int i = 0; i < strings; i++)\n\t\t\t{\n\t\t\t\tmatrix[i] = new int[columns]{0};\n\t\t\t}\n\n\t\t\tmatrix = other.matrix;\n\t\t}\n\t\treturn *this;\n\t};\n\n\tbool Matrix :: operator== (Matrix &a) const\n\t{\n\t\tbool k = false;\n\n\t\tfor (int i = 0; i < strings; i++){\n\n\t\t\tfor (int j = 0; j < columns; j++){\n\n\t\t\t\tif (matrix[i][j] == a.matrix[i][j])\n\n\t\t\t\t\tk = true;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn k;\n\t}\n\n\tistream& operator>> (istream& infile, const Matrix& result)\n\n\t{\n\n\t\tfor (int i = 0; i < result.strings; i++)\n\n\t\t\tfor (int j = 0; j < result.columns; j++)\n\n\t\t\t\tinfile >> result.matrix[i][j];\n\n\t\treturn infile;\n\n\t}\n\n\t ostream& operator<< (ostream& os, const Matrix& a)\n\t{\n\t\tfor (int i = 0; i < a.strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < a.columns; j++)\n\t\t\t{\n\t\t\t\tos << a.matrix[i, j] << \" \";\n\t\t\t}\n\t\t\tos << endl;\n\t\t}\n\t\tos << endl;\n\t\treturn os;\n\t}\n\n\n\tMatrix :: ~Matrix()\n\t{\n\t\t\/*for (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tdelete[] matrix[i];\n\t\t}\n\n\t\tdelete[] matrix;*\/\n\t};\n};\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file EMD.cpp\n * @brief mex interface for EMD\n * @author Kota Yamaguchi\n * @date 2011\n *\/\n#include \"mexopencv.hpp\"\nusing namespace std;\nusing namespace cv;\n\n\/**\n * Main entry called from Matlab\n * @param nlhs number of left-hand-side arguments\n * @param plhs pointers to mxArrays in the left-hand-side\n * @param nrhs number of right-hand-side arguments\n * @param prhs pointers to mxArrays in the right-hand-side\n *\/\nvoid mexFunction( int nlhs, mxArray *plhs[],\n int nrhs, const mxArray *prhs[] )\n{\n \/\/ Check the number of arguments\n if (nrhs<2 || (nrhs%2)!=0 || nlhs>3)\n mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n\n \/\/ Argument vector\n vector<MxArray> rhs(prhs,prhs+nrhs);\n \n \/\/ Option processing\n int distType = cv::DIST_L2;\n Mat cost;\n float lowerBound = 0;\n for (int i=2; i<nrhs; i+=2) {\n string key = rhs[i].toString();\n if (key==\"DistType\")\n distType = (rhs[i+1].isChar()) ?\n DistType[rhs[i+1].toString()] : rhs[i+1].toInt();\n else if (key==\"Cost\")\n cost = rhs[i+1].toMat();\n else if (key==\"LowerBound\")\n lowerBound = rhs[i+1].toDouble();\n else\n mexErrMsgIdAndTxt(\"mexopencv:error\",\"Unrecognized option\");\n }\n if (distType==cv::DIST_USER && cost.empty())\n mexErrMsgIdAndTxt(\"mexopencv:error\",\"Cost matrix empty\");\n \n \/\/ Process\n Mat signature1(rhs[0].toMat()), signature2(rhs[1].toMat()), flow;\n double d = EMD(signature1, signature2, distType, cost, &lowerBound, flow);\n plhs[0] = MxArray(d);\n if (nlhs>1)\n plhs[1] = MxArray(lowerBound);\n if (nlhs>2)\n plhs[2] = MxArray(flow);\n}\n<commit_msg>fix EMD in case user cost function is used<commit_after>\/**\n * @file EMD.cpp\n * @brief mex interface for EMD\n * @author Kota Yamaguchi\n * @date 2011\n *\/\n#include \"mexopencv.hpp\"\nusing namespace std;\nusing namespace cv;\n\n\/**\n * Main entry called from Matlab\n * @param nlhs number of left-hand-side arguments\n * @param plhs pointers to mxArrays in the left-hand-side\n * @param nrhs number of right-hand-side arguments\n * @param prhs pointers to mxArrays in the right-hand-side\n *\/\nvoid mexFunction( int nlhs, mxArray *plhs[],\n int nrhs, const mxArray *prhs[] )\n{\n \/\/ Check the number of arguments\n if (nrhs<2 || (nrhs%2)!=0 || nlhs>3)\n mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n\n \/\/ Argument vector\n vector<MxArray> rhs(prhs,prhs+nrhs);\n \n \/\/ Option processing\n int distType = cv::DIST_L2;\n Mat cost;\n float lowerBound = 0;\n for (int i=2; i<nrhs; i+=2) {\n string key = rhs[i].toString();\n if (key==\"DistType\")\n distType = (rhs[i+1].isChar()) ?\n DistType[rhs[i+1].toString()] : rhs[i+1].toInt();\n else if (key==\"Cost\")\n cost = rhs[i+1].toMat();\n else if (key==\"LowerBound\")\n lowerBound = rhs[i+1].toDouble();\n else\n mexErrMsgIdAndTxt(\"mexopencv:error\",\"Unrecognized option\");\n }\n if (distType==cv::DIST_USER && cost.empty())\n mexErrMsgIdAndTxt(\"mexopencv:error\",\"Cost matrix empty\");\n \n \/\/ Process\n Mat signature1(rhs[0].toMat()), signature2(rhs[1].toMat()), flow;\n double d;\n if (distType==cv::DIST_USER)\n {\n d = EMD(signature1, signature2, distType, cost);\n }\n else\n {\n d = EMD(signature1, signature2, distType, cost, &lowerBound, flow);\n }\n\t\n plhs[0] = MxArray(d);\n if (nlhs>1)\n plhs[1] = MxArray(lowerBound);\n if (nlhs>2)\n plhs[2] = MxArray(flow);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Torsten Rahn <tackat@kde.org>\n\/\/\n\n#include \"StarsPlugin.h\"\n\n#include <QtCore\/QRectF>\n#include <QtCore\/QSize>\n#include <QtCore\/QDateTime>\n#include \"MarbleDebug.h\"\n#include \"MarbleDirs.h\"\n#include \"MarbleDataFacade.h\"\n#include \"GeoPainter.h\"\n#include \"SunLocator.h\"\n#include \"ViewportParams.h\"\n#include \"MarbleWidget.h\"\n\nnamespace Marble\n{\n\nStarsPlugin::StarsPlugin()\n : m_isInitialized( false ),\n m_starsLoaded( false ),\n m_marbleWidget( 0 )\n{\n}\n\nQStringList StarsPlugin::backendTypes() const\n{\n return QStringList( \"stars\" );\n}\n\nQString StarsPlugin::renderPolicy() const\n{\n return QString( \"SPECIFIED_ALWAYS\" );\n}\n\nQStringList StarsPlugin::renderPosition() const\n{\n QStringList layers = QStringList() << \"STARS\" << \"ALWAYS_ON_TOP\";\n return layers;\n}\n\nQString StarsPlugin::name() const\n{\n return tr( \"Stars Plugin\" );\n}\n\nQString StarsPlugin::guiString() const\n{\n return tr( \"&Stars\" );\n}\n\nQString StarsPlugin::nameId() const\n{\n return QString( \"stars\" );\n}\n\nQString StarsPlugin::description() const\n{\n return tr( \"A plugin that shows the Starry Sky.\" );\n}\n\nQIcon StarsPlugin::icon () const\n{\n return QIcon();\n}\n\n\nvoid StarsPlugin::initialize ()\n{\n m_isInitialized = true;\n}\n\nbool StarsPlugin::isInitialized () const\n{\n return m_isInitialized;\n}\n\nvoid StarsPlugin::loadStars() {\n mDebug() << Q_FUNC_INFO;\n \/\/ Load star data\n m_stars.clear();\n\n QFile starFile( MarbleDirs::path( \"stars\/stars.dat\" ) );\n starFile.open( QIODevice::ReadOnly );\n QDataStream in( &starFile );\n\n \/\/ Read and check the header\n quint32 magic;\n in >> magic;\n if ( magic != 0x73746172 )\n return;\n\n \/\/ Read the version\n qint32 version;\n in >> version;\n if ( version > 001 ) {\n mDebug() << \"stars.dat: file too new.\";\n return;\n }\n double ra;\n double de;\n double mag;\n\n while ( !in.atEnd() ) {\n in >> ra;\n in >> de;\n in >> mag;\n StarPoint star( (qreal)(ra), (qreal)(de), (qreal)(mag) );\n m_stars << star;\n\/\/ mDebug() << \"RA:\" << ra << \"DE:\" << de << \"MAG:\" << mag;\n }\n m_starsLoaded = true;\n}\n\nbool StarsPlugin::render( GeoPainter *painter, ViewportParams *viewport,\n const QString& renderPos, GeoSceneLayer * layer )\n{\n Q_UNUSED( layer )\n\n if ( !(renderPos == \"STARS\" || renderPos == \"ALWAYS_ON_TOP\") ) {\n return true;\n }\n\n if( renderPos==\"STARS\" )\n {\n QString target = dataFacade()->target();\n\n \/\/ So far this starry sky plugin only supports displaying stars on earth.\n if ( target != \"earth\" ) {\n return true;\n }\n\n painter->save();\n\n painter->autoMapQuality();\n\n QPen starPen( Qt::NoPen );\n QBrush starBrush( Qt::white );\n\n painter->setPen( starPen );\n painter->setBrush( starBrush );\n\n QDateTime currentDateTime = dataFacade()->dateTime();\n\n qreal gmst = siderealTime( currentDateTime );\n qreal skyRotationAngle = gmst \/ 12.0 * M_PI;\n\n qreal centerLon, centerLat;\n viewport->centerCoordinates( centerLon, centerLat );\n\n Quaternion skyAxis;\n skyAxis.createFromEuler( -centerLat , centerLon + skyRotationAngle, 0.0 );\n\n matrix skyAxisMatrix;\n skyAxis.inverse().toMatrix( skyAxisMatrix );\n\n if ( !viewport->globeCoversViewport() && viewport->projection() == Spherical )\n {\n \/\/ Delayed initialization: \n \/\/ Load the star database only if the sky is actually being painted...\n if ( !m_starsLoaded ) {\n loadStars();\n m_starsLoaded = true;\n }\n \n int x, y;\n \n const qreal skyRadius = 0.6 * sqrt( (qreal)viewport->width() * viewport->width() + viewport->height() * viewport->height() );\n const qreal earthRadius = viewport->radius();\n\n QVector<StarPoint>::const_iterator i = m_stars.constBegin();\n QVector<StarPoint>::const_iterator itEnd = m_stars.constEnd();\n for (; i != itEnd; ++i)\n {\n Quaternion qpos = (*i).quaternion();\n \n qpos.rotateAroundAxis( skyAxisMatrix );\n \n if ( qpos.v[Q_Z] > 0 ) {\n continue;\n }\n\n qreal earthCenteredX = qpos.v[Q_X] * skyRadius;\n qreal earthCenteredY = qpos.v[Q_Y] * skyRadius;\n\n \/\/ Don't draw high placemarks (e.g. satellites) that aren't visible.\n if ( qpos.v[Q_Z] < 0\n && ( ( earthCenteredX * earthCenteredX\n + earthCenteredY * earthCenteredY )\n < earthRadius * earthRadius ) ) {\n continue;\n }\n \n \/\/ Let (x, y) be the position on the screen of the placemark..\n x = (int)(viewport->width() \/ 2 + skyRadius * qpos.v[Q_X]);\n y = (int)(viewport->height() \/ 2 - skyRadius * qpos.v[Q_Y]);\n \n \/\/ Skip placemarks that are outside the screen area\n if ( x < 0 || x >= viewport->width()\n \t\t || y < 0 || y >= viewport->height() )\n continue;\n \n qreal size;\n if ( (*i).magnitude() < -1 ) size = 6.5;\n else if ( (*i).magnitude() < 0 ) size = 5.5;\n else if ( (*i).magnitude() < 1 ) size = 4.5;\n else if ( (*i).magnitude() < 2 ) size = 4.0;\n else if ( (*i).magnitude() < 3 ) size = 3.0;\n else if ( (*i).magnitude() < 4 ) size = 2.0;\n else if ( (*i).magnitude() < 5 ) size = 1.0;\n else size = 0.5;\n painter->drawEllipse( QRectF( x, y, size, size ) );\n }\n }\n\n painter->restore();\n }\n\n if( renderPos == \"ALWAYS_ON_TOP\" )\n {\n m_marbleWidget = dynamic_cast<MarbleWidget*>( painter->device() );\n if( m_marbleWidget && m_marbleWidget->sunLocator()->getCentered() == true )\n {\n GeoDataCoordinates point( m_marbleWidget->sunLocator()->getLon(), m_marbleWidget->sunLocator()->getLat(), 0, GeoDataCoordinates::Degree );\n QImage image( MarbleDirs::path( \"svg\/sunshine.png\" ) );\n painter->drawImage( point, image.scaled( QSize( 30, 30 ) ) );\n }\n }\n\n return true;\n}\n\nqreal StarsPlugin::siderealTime( const QDateTime& localDateTime )\n{\n QDateTime utcDateTime = localDateTime.toTimeSpec ( Qt::UTC );\n qreal mjdUtc = (qreal)( utcDateTime.date().toJulianDay() );\n\n qreal offsetUtcSecs = -utcDateTime.time().secsTo( QTime( 00, 00 ) );\n qreal d_days = mjdUtc - 2451545.5;\n qreal d = d_days + ( offsetUtcSecs \/ ( 24.0 * 3600 ) );\n\n \/\/ Appendix A of USNO Circular No. 163 (1981):\n \/\/ Approximate value for Greenwich mean sidereal time in hours: \n \/\/ (Loss of precision: 0.1 secs per century)\n qreal gmst = 18.697374558 + 24.06570982441908 * d;\n\n \/\/ Range (0..24) for gmst: \n return gmst - (int)( gmst \/ 24.0 ) * 24.0; \n}\n\n}\n\nQ_EXPORT_PLUGIN2( StarsPlugin, Marble::StarsPlugin )\n\n#include \"StarsPlugin.moc\"\n<commit_msg>Remove \"Plugin\" from name. No other plugin has this as part of its name.<commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Torsten Rahn <tackat@kde.org>\n\/\/\n\n#include \"StarsPlugin.h\"\n\n#include <QtCore\/QRectF>\n#include <QtCore\/QSize>\n#include <QtCore\/QDateTime>\n#include \"MarbleDebug.h\"\n#include \"MarbleDirs.h\"\n#include \"MarbleDataFacade.h\"\n#include \"GeoPainter.h\"\n#include \"SunLocator.h\"\n#include \"ViewportParams.h\"\n#include \"MarbleWidget.h\"\n\nnamespace Marble\n{\n\nStarsPlugin::StarsPlugin()\n : m_isInitialized( false ),\n m_starsLoaded( false ),\n m_marbleWidget( 0 )\n{\n}\n\nQStringList StarsPlugin::backendTypes() const\n{\n return QStringList( \"stars\" );\n}\n\nQString StarsPlugin::renderPolicy() const\n{\n return QString( \"SPECIFIED_ALWAYS\" );\n}\n\nQStringList StarsPlugin::renderPosition() const\n{\n QStringList layers = QStringList() << \"STARS\" << \"ALWAYS_ON_TOP\";\n return layers;\n}\n\nQString StarsPlugin::name() const\n{\n return tr( \"Stars\" );\n}\n\nQString StarsPlugin::guiString() const\n{\n return tr( \"&Stars\" );\n}\n\nQString StarsPlugin::nameId() const\n{\n return QString( \"stars\" );\n}\n\nQString StarsPlugin::description() const\n{\n return tr( \"A plugin that shows the Starry Sky.\" );\n}\n\nQIcon StarsPlugin::icon () const\n{\n return QIcon();\n}\n\n\nvoid StarsPlugin::initialize ()\n{\n m_isInitialized = true;\n}\n\nbool StarsPlugin::isInitialized () const\n{\n return m_isInitialized;\n}\n\nvoid StarsPlugin::loadStars() {\n mDebug() << Q_FUNC_INFO;\n \/\/ Load star data\n m_stars.clear();\n\n QFile starFile( MarbleDirs::path( \"stars\/stars.dat\" ) );\n starFile.open( QIODevice::ReadOnly );\n QDataStream in( &starFile );\n\n \/\/ Read and check the header\n quint32 magic;\n in >> magic;\n if ( magic != 0x73746172 )\n return;\n\n \/\/ Read the version\n qint32 version;\n in >> version;\n if ( version > 001 ) {\n mDebug() << \"stars.dat: file too new.\";\n return;\n }\n double ra;\n double de;\n double mag;\n\n while ( !in.atEnd() ) {\n in >> ra;\n in >> de;\n in >> mag;\n StarPoint star( (qreal)(ra), (qreal)(de), (qreal)(mag) );\n m_stars << star;\n\/\/ mDebug() << \"RA:\" << ra << \"DE:\" << de << \"MAG:\" << mag;\n }\n m_starsLoaded = true;\n}\n\nbool StarsPlugin::render( GeoPainter *painter, ViewportParams *viewport,\n const QString& renderPos, GeoSceneLayer * layer )\n{\n Q_UNUSED( layer )\n\n if ( !(renderPos == \"STARS\" || renderPos == \"ALWAYS_ON_TOP\") ) {\n return true;\n }\n\n if( renderPos==\"STARS\" )\n {\n QString target = dataFacade()->target();\n\n \/\/ So far this starry sky plugin only supports displaying stars on earth.\n if ( target != \"earth\" ) {\n return true;\n }\n\n painter->save();\n\n painter->autoMapQuality();\n\n QPen starPen( Qt::NoPen );\n QBrush starBrush( Qt::white );\n\n painter->setPen( starPen );\n painter->setBrush( starBrush );\n\n QDateTime currentDateTime = dataFacade()->dateTime();\n\n qreal gmst = siderealTime( currentDateTime );\n qreal skyRotationAngle = gmst \/ 12.0 * M_PI;\n\n qreal centerLon, centerLat;\n viewport->centerCoordinates( centerLon, centerLat );\n\n Quaternion skyAxis;\n skyAxis.createFromEuler( -centerLat , centerLon + skyRotationAngle, 0.0 );\n\n matrix skyAxisMatrix;\n skyAxis.inverse().toMatrix( skyAxisMatrix );\n\n if ( !viewport->globeCoversViewport() && viewport->projection() == Spherical )\n {\n \/\/ Delayed initialization:\n \/\/ Load the star database only if the sky is actually being painted...\n if ( !m_starsLoaded ) {\n loadStars();\n m_starsLoaded = true;\n }\n\n int x, y;\n\n const qreal skyRadius = 0.6 * sqrt( (qreal)viewport->width() * viewport->width() + viewport->height() * viewport->height() );\n const qreal earthRadius = viewport->radius();\n\n QVector<StarPoint>::const_iterator i = m_stars.constBegin();\n QVector<StarPoint>::const_iterator itEnd = m_stars.constEnd();\n for (; i != itEnd; ++i)\n {\n Quaternion qpos = (*i).quaternion();\n\n qpos.rotateAroundAxis( skyAxisMatrix );\n\n if ( qpos.v[Q_Z] > 0 ) {\n continue;\n }\n\n qreal earthCenteredX = qpos.v[Q_X] * skyRadius;\n qreal earthCenteredY = qpos.v[Q_Y] * skyRadius;\n\n \/\/ Don't draw high placemarks (e.g. satellites) that aren't visible.\n if ( qpos.v[Q_Z] < 0\n && ( ( earthCenteredX * earthCenteredX\n + earthCenteredY * earthCenteredY )\n < earthRadius * earthRadius ) ) {\n continue;\n }\n\n \/\/ Let (x, y) be the position on the screen of the placemark..\n x = (int)(viewport->width() \/ 2 + skyRadius * qpos.v[Q_X]);\n y = (int)(viewport->height() \/ 2 - skyRadius * qpos.v[Q_Y]);\n\n \/\/ Skip placemarks that are outside the screen area\n if ( x < 0 || x >= viewport->width()\n \t\t || y < 0 || y >= viewport->height() )\n continue;\n\n qreal size;\n if ( (*i).magnitude() < -1 ) size = 6.5;\n else if ( (*i).magnitude() < 0 ) size = 5.5;\n else if ( (*i).magnitude() < 1 ) size = 4.5;\n else if ( (*i).magnitude() < 2 ) size = 4.0;\n else if ( (*i).magnitude() < 3 ) size = 3.0;\n else if ( (*i).magnitude() < 4 ) size = 2.0;\n else if ( (*i).magnitude() < 5 ) size = 1.0;\n else size = 0.5;\n painter->drawEllipse( QRectF( x, y, size, size ) );\n }\n }\n\n painter->restore();\n }\n\n if( renderPos == \"ALWAYS_ON_TOP\" )\n {\n m_marbleWidget = dynamic_cast<MarbleWidget*>( painter->device() );\n if( m_marbleWidget && m_marbleWidget->sunLocator()->getCentered() == true )\n {\n GeoDataCoordinates point( m_marbleWidget->sunLocator()->getLon(), m_marbleWidget->sunLocator()->getLat(), 0, GeoDataCoordinates::Degree );\n QImage image( MarbleDirs::path( \"svg\/sunshine.png\" ) );\n painter->drawImage( point, image.scaled( QSize( 30, 30 ) ) );\n }\n }\n\n return true;\n}\n\nqreal StarsPlugin::siderealTime( const QDateTime& localDateTime )\n{\n QDateTime utcDateTime = localDateTime.toTimeSpec ( Qt::UTC );\n qreal mjdUtc = (qreal)( utcDateTime.date().toJulianDay() );\n\n qreal offsetUtcSecs = -utcDateTime.time().secsTo( QTime( 00, 00 ) );\n qreal d_days = mjdUtc - 2451545.5;\n qreal d = d_days + ( offsetUtcSecs \/ ( 24.0 * 3600 ) );\n\n \/\/ Appendix A of USNO Circular No. 163 (1981):\n \/\/ Approximate value for Greenwich mean sidereal time in hours:\n \/\/ (Loss of precision: 0.1 secs per century)\n qreal gmst = 18.697374558 + 24.06570982441908 * d;\n\n \/\/ Range (0..24) for gmst:\n return gmst - (int)( gmst \/ 24.0 ) * 24.0;\n}\n\n}\n\nQ_EXPORT_PLUGIN2( StarsPlugin, Marble::StarsPlugin )\n\n#include \"StarsPlugin.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the µOS++ distribution.\n * (https:\/\/github.com\/micro-os-plus)\n * Copyright (c) 2015 Liviu Ionescu.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom\n * the Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#if defined(TRACE)\n\n#include <cmsis-plus\/os-app-config.h>\n#include <cmsis-plus\/diag\/trace.h>\n\n#include <cstdarg>\n#include <cstdio>\n#include <cstring>\n\n#ifndef OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE\n#define OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE (200)\n#endif\n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace os\n{\n namespace trace\n {\n \/\/ ----------------------------------------------------------------------\n\n void __attribute__((weak))\n initialize (void)\n {\n ;\n }\n\n \/**\n * @brief Write the given number of bytes to the trace output channel.\n * @return The number of characters actually written, or -1 if error.\n *\/\n ssize_t __attribute__((weak))\n write (const void* buf __attribute__((unused)), std::size_t nbyte)\n {\n return static_cast<ssize_t> (nbyte);\n }\n\n void __attribute__((weak))\n flush (void)\n {\n ;\n }\n\n \/\/ ----------------------------------------------------------------------\n\n int __attribute__((weak))\n printf (const char* format, ...)\n {\n std::va_list args;\n va_start(args, format);\n\n int ret = vprintf (format, args);\n\n va_end(args);\n return ret;\n }\n\n int __attribute__((weak))\n vprintf (const char* format, std::va_list args)\n {\n \/\/ Caution: allocated on the stack!\n char buf[OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE];\n\n \/\/ TODO: possibly rewrite it to no longer use newlib,\n \/\/ (although the nano version is no longer very heavy).\n\n \/\/ Print to the local buffer\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"\n int ret = ::vsnprintf (buf, sizeof(buf), format, args);\n#pragma GCC diagnostic pop\n if (ret > 0)\n {\n \/\/ Transfer the buffer to the device.\n ret = static_cast<int> (write (buf, static_cast<size_t> (ret)));\n }\n return ret;\n }\n\n int __attribute__((weak))\n puts (const char* s)\n {\n int ret = static_cast<int> (write (s, strlen (s)));\n if (ret > 0)\n {\n ret = static_cast<int> (write (\"\\n\", 1)); \/\/ Add a line terminator\n }\n if (ret > 0)\n {\n return ret;\n }\n else\n {\n return EOF;\n }\n }\n\n int __attribute__((weak))\n putchar (int c)\n {\n int ret = static_cast<int> (write (reinterpret_cast<const char*> (&c), 1));\n if (ret > 0)\n {\n return c;\n }\n else\n {\n return EOF;\n }\n }\n\n void __attribute__((weak))\n dump_args (int argc, char* argv[])\n {\n printf (\"main(argc=%d, argv=[\", argc);\n for (int i = 0; i < argc; ++i)\n {\n if (i != 0)\n {\n printf (\", \");\n }\n printf (\"\\\"%s\\\"\", argv[i]);\n }\n printf (\"]);\\n\");\n }\n\n } \/* namespace trace *\/\n} \/* namespace os *\/\n\n\/\/ ----------------------------------------------------------------------------\n\nusing namespace os;\n\n\/\/ These cannot be aliased, since they might be defined\n\/\/ in a different translation units (and usually they are).\n\nvoid __attribute__((weak))\ntrace_initialize (void)\n{\n trace::initialize ();\n}\n\nssize_t __attribute__((weak))\ntrace_write (const void* buf, std::size_t nbyte)\n{\n return trace::write (buf, nbyte);\n}\n\nvoid __attribute__((weak))\ntrace_flush (void)\n{\n return trace::flush ();\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n#if defined(__ARM_EABI__)\n\n\/\/ For embedded platforms, optimise with aliases.\n\/\/\n\/\/ Aliases can only refer symbols defined in the same translation unit\n\/\/ and C++ de-mangling must be done manually.\n\nint __attribute__((weak, alias (\"_ZN2os5trace6printfEPKcz\")))\ntrace_printf (const char* format, ...);\n\nint __attribute__((weak, alias (\"_ZN2os5trace7vprintfEPKcSt9__va_list\")))\ntrace_vprintf (const char* format, ...);\n\nint __attribute__((weak, alias(\"_ZN2os5trace4putsEPKc\")))\ntrace_puts (const char *s);\n\nint __attribute__((weak, alias(\"_ZN2os5trace7putcharEi\")))\ntrace_putchar (int c);\n\nvoid __attribute__((weak, alias(\"_ZN2os5trace9dump_argsEiPPc\")))\ntrace_dump_args (int argc, char* argv[]);\n\n#else\n\n\/\/ For non-embedded platforms, to remain compatible with OS X which does\n\/\/ not support aliases, redefine the C functions to call the C++ versions.\n\nint\ntrace_printf (const char* format, ...)\n{\n std::va_list args;\n va_start(args, format);\n\n int ret = trace::vprintf (format, args);\n\n va_end(args);\n return ret;\n}\n\nint\ntrace_vprintf (const char* format, va_list args)\n{\n return trace::vprintf (format, args);\n}\n\nint\ntrace_puts (const char* s)\n{\n return trace::puts (s);\n}\n\nint\ntrace_putchar (int c)\n{\n return trace::putchar (c);\n}\n\nvoid\ntrace_dump_args (int argc, char* argv[])\n{\n trace::dump_args (argc, argv);\n}\n\n#endif\n\n\/\/ ----------------------------------------------------------------------------\n\n#endif \/\/ defined(TRACE)\n<commit_msg>diag\/trace.cpp: puts accepts empty string<commit_after>\/*\n * This file is part of the µOS++ distribution.\n * (https:\/\/github.com\/micro-os-plus)\n * Copyright (c) 2015 Liviu Ionescu.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom\n * the Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#if defined(TRACE)\n\n#include <cmsis-plus\/os-app-config.h>\n#include <cmsis-plus\/diag\/trace.h>\n\n#include <cstdarg>\n#include <cstdio>\n#include <cstring>\n\n#ifndef OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE\n#define OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE (200)\n#endif\n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace os\n{\n namespace trace\n {\n \/\/ ----------------------------------------------------------------------\n\n void __attribute__((weak))\n initialize (void)\n {\n ;\n }\n\n \/**\n * @brief Write the given number of bytes to the trace output channel.\n * @return The number of characters actually written, or -1 if error.\n *\/\n ssize_t __attribute__((weak))\n write (const void* buf __attribute__((unused)), std::size_t nbyte)\n {\n return static_cast<ssize_t> (nbyte);\n }\n\n void __attribute__((weak))\n flush (void)\n {\n ;\n }\n\n \/\/ ----------------------------------------------------------------------\n\n int __attribute__((weak))\n printf (const char* format, ...)\n {\n std::va_list args;\n va_start(args, format);\n\n int ret = vprintf (format, args);\n\n va_end(args);\n return ret;\n }\n\n int __attribute__((weak))\n vprintf (const char* format, std::va_list args)\n {\n \/\/ Caution: allocated on the stack!\n char buf[OS_INTEGER_TRACE_PRINTF_TMP_ARRAY_SIZE];\n\n \/\/ TODO: possibly rewrite it to no longer use newlib,\n \/\/ (although the nano version is no longer very heavy).\n\n \/\/ Print to the local buffer\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"\n int ret = ::vsnprintf (buf, sizeof(buf), format, args);\n#pragma GCC diagnostic pop\n if (ret > 0)\n {\n \/\/ Transfer the buffer to the device.\n ret = static_cast<int> (write (buf, static_cast<size_t> (ret)));\n }\n return ret;\n }\n\n int __attribute__((weak))\n puts (const char* s)\n {\n int ret = static_cast<int> (write (s, strlen (s)));\n if (ret >= 0)\n {\n ret = static_cast<int> (write (\"\\n\", 1)); \/\/ Add a line terminator\n }\n if (ret > 0)\n {\n return ret;\n }\n else\n {\n return EOF;\n }\n }\n\n int __attribute__((weak))\n putchar (int c)\n {\n int ret = static_cast<int> (write (reinterpret_cast<const char*> (&c), 1));\n if (ret > 0)\n {\n return c;\n }\n else\n {\n return EOF;\n }\n }\n\n void __attribute__((weak))\n dump_args (int argc, char* argv[])\n {\n printf (\"main(argc=%d, argv=[\", argc);\n for (int i = 0; i < argc; ++i)\n {\n if (i != 0)\n {\n printf (\", \");\n }\n printf (\"\\\"%s\\\"\", argv[i]);\n }\n printf (\"]);\\n\");\n }\n\n } \/* namespace trace *\/\n} \/* namespace os *\/\n\n\/\/ ----------------------------------------------------------------------------\n\nusing namespace os;\n\n\/\/ These cannot be aliased, since they might be defined\n\/\/ in a different translation units (and usually they are).\n\nvoid __attribute__((weak))\ntrace_initialize (void)\n{\n trace::initialize ();\n}\n\nssize_t __attribute__((weak))\ntrace_write (const void* buf, std::size_t nbyte)\n{\n return trace::write (buf, nbyte);\n}\n\nvoid __attribute__((weak))\ntrace_flush (void)\n{\n return trace::flush ();\n}\n\n\/\/ ----------------------------------------------------------------------------\n\n#if defined(__ARM_EABI__)\n\n\/\/ For embedded platforms, optimise with aliases.\n\/\/\n\/\/ Aliases can only refer symbols defined in the same translation unit\n\/\/ and C++ de-mangling must be done manually.\n\nint __attribute__((weak, alias (\"_ZN2os5trace6printfEPKcz\")))\ntrace_printf (const char* format, ...);\n\nint __attribute__((weak, alias (\"_ZN2os5trace7vprintfEPKcSt9__va_list\")))\ntrace_vprintf (const char* format, ...);\n\nint __attribute__((weak, alias(\"_ZN2os5trace4putsEPKc\")))\ntrace_puts (const char *s);\n\nint __attribute__((weak, alias(\"_ZN2os5trace7putcharEi\")))\ntrace_putchar (int c);\n\nvoid __attribute__((weak, alias(\"_ZN2os5trace9dump_argsEiPPc\")))\ntrace_dump_args (int argc, char* argv[]);\n\n#else\n\n\/\/ For non-embedded platforms, to remain compatible with OS X which does\n\/\/ not support aliases, redefine the C functions to call the C++ versions.\n\nint\ntrace_printf (const char* format, ...)\n{\n std::va_list args;\n va_start(args, format);\n\n int ret = trace::vprintf (format, args);\n\n va_end(args);\n return ret;\n}\n\nint\ntrace_vprintf (const char* format, va_list args)\n{\n return trace::vprintf (format, args);\n}\n\nint\ntrace_puts (const char* s)\n{\n return trace::puts (s);\n}\n\nint\ntrace_putchar (int c)\n{\n return trace::putchar (c);\n}\n\nvoid\ntrace_dump_args (int argc, char* argv[])\n{\n trace::dump_args (argc, argv);\n}\n\n#endif\n\n\/\/ ----------------------------------------------------------------------------\n\n#endif \/\/ defined(TRACE)\n<|endoftext|>"} {"text":"<commit_before>#include \"Channel.hpp\"\n#include \"CMessage.hpp\"\n#include \"Network.hpp\"\n#include \"CDispatcher.hpp\"\n#include \"CLog.hpp\"\n\n#include \"fmt\/format.h\"\n\n\n#undef SendMessage \/\/ Windows at its finest\n\n\nChannel::Channel(ChannelId_t pawn_id, json &data) :\n\tm_PawnId(pawn_id)\n{\n\tm_Id = data[\"id\"].get<std::string>();\n\tm_Type = static_cast<Type>(data[\"type\"].get<int>());\n\tif (m_Type == Type::GUILD_TEXT) \/\/ is a guild channel\n\t{\n\t\tm_GuildId = data[\"guild_id\"].get<std::string>();\n\t\tm_Name = data[\"name\"].get<std::string>();\n\t\tjson &topic = data[\"topic\"];\n\t\tif (!topic.is_null())\n\t\t\tm_Topic = topic.get<std::string>();\n\t}\n}\n\nvoid Channel::SendMessage(std::string &&msg)\n{\n\tjson data = {\n\t\t{ \"content\", std::move(msg) }\n\t};\n\tNetwork::Get()->Http().Post(fmt::format(\"\/channels\/{}\/messages\", GetId()), data.dump());\n}\n\n\nvoid ChannelManager::Initialize()\n{\n\tassert(m_Initialized != m_InitValue);\n\n\tNetwork::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_CREATE, [](json &data)\n\t{\n\t\tChannelManager::Get()->AddChannel(data);\n\t});\n\n\tNetwork::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json &data)\n\t{\n\t\tfor (json &c : data[\"private_channels\"])\n\t\t\tAddChannel(c);\n\t\tm_Initialized++;\n\t});\n\n\t\/\/ GUILD_CREATE event seems to be always sent after READY event with all guilds the bot is in\n\tNetwork::Get()->WebSocket().RegisterEvent(WebSocket::Event::GUILD_CREATE, [this](json &data)\n\t{\n\t\tfor (json &c : data[\"channels\"])\n\t\t{\n\t\t\t\/\/ manually add guild_id to channel data\n\t\t\tc[\"guild_id\"] = data[\"id\"];\n\t\t\tAddChannel(c);\n\t\t}\n\t\tm_Initialized++;\n\t});\n\n\t\/\/ PAWN callbacks\n\tNetwork::Get()->WebSocket().RegisterEvent(WebSocket::Event::MESSAGE_CREATE, [this](json &data)\n\t{\n\t\tCMessage msg(data);\n\t\tChannel_t const &channel = FindChannelById(msg.GetChannelId());\n\t\tif (channel)\n\t\t{\n\t\t\tCDispatcher::Get()->Dispatch([this, msg, &channel]()\n\t\t\t{\n\t\t\t\t\/\/ forward DCC_OnChannelMessage(DCC_Channel:channel, const author[], const message[]);\n\t\t\t\tPawnCallbackManager::Get()->Call(\"DCC_OnChannelMessage\",\n\t\t\t\t\tchannel->GetPawnId(), msg.GetAuthor(), msg.GetContent());\n\t\t\t});\n\t\t}\n\t});\n}\n\nvoid ChannelManager::WaitForInitialization()\n{\n\twhile (m_Initialized != m_InitValue)\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(20));\n}\n\nvoid ChannelManager::AddChannel(json &data)\n{\n\tjson &type = data[\"type\"];\n\tif (!type.is_null() && type.get<std::string>() != \"text\")\n\t\treturn; \/\/ we're only interested in text channels\n\n\tChannelId_t id = 1;\n\twhile (m_Channels.find(id) != m_Channels.end())\n\t\t++id;\n\n\tm_Channels.emplace(id, Channel_t(new Channel(id, data)));\n}\n\nChannel_t const &ChannelManager::FindChannel(ChannelId_t id)\n{\n\tstatic Channel_t invalid_channel;\n\tauto it = m_Channels.find(id);\n\tif (it == m_Channels.end())\n\t\treturn invalid_channel;\n\treturn it->second;\n}\n\nChannel_t const &ChannelManager::FindChannelByName(std::string const &name)\n{\n\tstatic Channel_t invalid_channel;\n\tfor (auto const &c : m_Channels)\n\t{\n\t\tChannel_t const &channel = c.second;\n\t\tif (channel->GetName().compare(name) == 0)\n\t\t\treturn channel;\n\t}\n\treturn invalid_channel;\n}\n\nChannel_t const &ChannelManager::FindChannelById(Snowflake_t const &sfid)\n{\n\tstatic Channel_t invalid_channel;\n\tfor (auto const &c : m_Channels)\n\t{\n\t\tChannel_t const &channel = c.second;\n\t\tif (channel->GetId().compare(sfid) == 0)\n\t\t\treturn channel;\n\t}\n\treturn invalid_channel;\n}\n<commit_msg>fix channel type check<commit_after>#include \"Channel.hpp\"\n#include \"CMessage.hpp\"\n#include \"Network.hpp\"\n#include \"CDispatcher.hpp\"\n#include \"CLog.hpp\"\n\n#include \"fmt\/format.h\"\n\n\n#undef SendMessage \/\/ Windows at its finest\n\n\nChannel::Channel(ChannelId_t pawn_id, json &data) :\n\tm_PawnId(pawn_id)\n{\n\tm_Id = data[\"id\"].get<std::string>();\n\tm_Type = static_cast<Type>(data[\"type\"].get<int>());\n\tif (m_Type == Type::GUILD_TEXT) \/\/ is a guild channel\n\t{\n\t\tm_GuildId = data[\"guild_id\"].get<std::string>();\n\t\tm_Name = data[\"name\"].get<std::string>();\n\t\tjson &topic = data[\"topic\"];\n\t\tif (!topic.is_null())\n\t\t\tm_Topic = topic.get<std::string>();\n\t}\n}\n\nvoid Channel::SendMessage(std::string &&msg)\n{\n\tjson data = {\n\t\t{ \"content\", std::move(msg) }\n\t};\n\tNetwork::Get()->Http().Post(fmt::format(\"\/channels\/{}\/messages\", GetId()), data.dump());\n}\n\n\nvoid ChannelManager::Initialize()\n{\n\tassert(m_Initialized != m_InitValue);\n\n\tNetwork::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_CREATE, [](json &data)\n\t{\n\t\tChannelManager::Get()->AddChannel(data);\n\t});\n\n\tNetwork::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json &data)\n\t{\n\t\tfor (json &c : data[\"private_channels\"])\n\t\t\tAddChannel(c);\n\t\tm_Initialized++;\n\t});\n\n\t\/\/ GUILD_CREATE event seems to be always sent after READY event with all guilds the bot is in\n\tNetwork::Get()->WebSocket().RegisterEvent(WebSocket::Event::GUILD_CREATE, [this](json &data)\n\t{\n\t\tfor (json &c : data[\"channels\"])\n\t\t{\n\t\t\t\/\/ manually add guild_id to channel data\n\t\t\tc[\"guild_id\"] = data[\"id\"];\n\t\t\tAddChannel(c);\n\t\t}\n\t\tm_Initialized++;\n\t});\n\n\t\/\/ PAWN callbacks\n\tNetwork::Get()->WebSocket().RegisterEvent(WebSocket::Event::MESSAGE_CREATE, [this](json &data)\n\t{\n\t\tCMessage msg(data);\n\t\tChannel_t const &channel = FindChannelById(msg.GetChannelId());\n\t\tif (channel)\n\t\t{\n\t\t\tCDispatcher::Get()->Dispatch([this, msg, &channel]()\n\t\t\t{\n\t\t\t\t\/\/ forward DCC_OnChannelMessage(DCC_Channel:channel, const author[], const message[]);\n\t\t\t\tPawnCallbackManager::Get()->Call(\"DCC_OnChannelMessage\",\n\t\t\t\t\tchannel->GetPawnId(), msg.GetAuthor(), msg.GetContent());\n\t\t\t});\n\t\t}\n\t});\n}\n\nvoid ChannelManager::WaitForInitialization()\n{\n\twhile (m_Initialized != m_InitValue)\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(20));\n}\n\nvoid ChannelManager::AddChannel(json &data)\n{\n\tjson &type = data[\"type\"];\n\tif (!type.is_null())\n\t{\n\t\tChannel::Type ch_type = static_cast<Channel::Type>(type.get<int>());\n\t\tif (ch_type != Channel::Type::GUILD_TEXT\n\t\t\t&& ch_type != Channel::Type::DM\n\t\t\t&& ch_type != Channel::Type::GROUP_DM)\n\t\t{\n\t\t\treturn; \/\/ we're only interested in text channels\n\t\t}\n\t}\n\n\tChannelId_t id = 1;\n\twhile (m_Channels.find(id) != m_Channels.end())\n\t\t++id;\n\n\tm_Channels.emplace(id, Channel_t(new Channel(id, data)));\n}\n\nChannel_t const &ChannelManager::FindChannel(ChannelId_t id)\n{\n\tstatic Channel_t invalid_channel;\n\tauto it = m_Channels.find(id);\n\tif (it == m_Channels.end())\n\t\treturn invalid_channel;\n\treturn it->second;\n}\n\nChannel_t const &ChannelManager::FindChannelByName(std::string const &name)\n{\n\tstatic Channel_t invalid_channel;\n\tfor (auto const &c : m_Channels)\n\t{\n\t\tChannel_t const &channel = c.second;\n\t\tif (channel->GetName().compare(name) == 0)\n\t\t\treturn channel;\n\t}\n\treturn invalid_channel;\n}\n\nChannel_t const &ChannelManager::FindChannelById(Snowflake_t const &sfid)\n{\n\tstatic Channel_t invalid_channel;\n\tfor (auto const &c : m_Channels)\n\t{\n\t\tChannel_t const &channel = c.second;\n\t\tif (channel->GetId().compare(sfid) == 0)\n\t\t\treturn channel;\n\t}\n\treturn invalid_channel;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Setting env vars in aqua's InitSalMain should long be unnecessary<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: salinst.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: pluby $ $Date: 2000-11-19 02:37:03 $\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#include <stdio.h>\n\n#define _SV_SALINST_CXX\n\n#ifndef _SV_SALDATA_HXX\n#include <saldata.hxx>\n#endif\n#ifndef _SV_SALINST_HXX\n#include <salinst.hxx>\n#endif\n#ifndef _SV_SALFRAME_HXX\n#include <salframe.hxx>\n#endif\n#ifndef _SV_SALOBJ_HXX\n#include <salobj.hxx>\n#endif\n#ifndef _SV_SALSYS_H\n#include <salsys.hxx>\n#endif\n#ifndef _SV_VCLAPPLICATION_H\n#include <VCLApplication.h>\n#endif\n\n\/\/ =======================================================================\n\nvoid SalAbort( const XubString& rErrorText )\n{\n if( !rErrorText.Len() )\n fprintf( stderr, \"Application Error\" );\n else\n fprintf( stderr,\n ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() );\n abort();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid InitSalData()\n{\n SalData *pSalData = new SalData;\n SetSalData( pSalData );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid DeInitSalData()\n{\n SalData *pSalData = GetSalData();\n delete pSalData;\n SetSalData( NULL );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SetFilterCallback( void* pCallback, void* pInst )\n{\n SalData *pSalData = GetSalData();\n pSalData->mpFirstInstance->maInstData.mpFilterCallback = pCallback;\n pSalData->mpFirstInstance->maInstData.mpFilterInst = pInst;\n}\n\n\/\/ =======================================================================\n\nSalInstance* CreateSalInstance()\n{\n SalData* pSalData = GetSalData();\n SalInstance* pInst = new SalInstance;\n\n \/\/ init instance (only one instance in this version !!!)\n pSalData->mpFirstInstance = pInst;\n\n return pInst;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid DestroySalInstance( SalInstance* pInst )\n{\n delete pInst;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalInstance::SalInstance()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalInstance::~SalInstance()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvos::IMutex* SalInstance::GetYieldMutex()\n{\n return NULL;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nULONG SalInstance::ReleaseYieldMutex()\n{\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::AcquireYieldMutex( ULONG nCount )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::Yield( BOOL bWait )\n{\n \/\/ Start the event queue. Note that VCLApplication_run() will not return\n \/\/ until the application shuts down. On other platforms, this function\n \/\/ returns after each event is pulled off the event queue and dispatched.\n \/\/ Instead, we have enter this method only once and let VCLApplication_run\n \/\/ do all of the pulling and dispatching of events.\n VCLApplication_run();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL SalInstance::AnyInput( USHORT nType )\n{\n return FALSE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalFrame* SalInstance::CreateChildFrame( SystemParentData* pSystemParentData, ULONG nSalFrameStyle )\n{\n return NULL;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalFrame* SalInstance::CreateFrame( SalFrame* pParent, ULONG nSalFrameStyle )\n{\n SalFrame *pFrame = new SalFrame;\n\n pFrame->maFrameData.mpParent = pParent;\n\n \/\/ Create the native window\n pFrame->maFrameData.mhWnd = VCLWindow_new( nSalFrameStyle, NULL,\n pFrame, &(pFrame->maFrameData) );\n\n return pFrame;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DestroyFrame( SalFrame* pFrame )\n{\n delete ( pFrame );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalObject* SalInstance::CreateObject( SalFrame* pParent )\n{\n SalObject *pObject = new SalObject;\n\n pObject->maObjectData.mhWnd = pParent->maFrameData.mhWnd;\n\n return pObject;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DestroyObject( SalObject* pObject )\n{\n delete ( pObject );\n}\n\nvoid SalInstance::GetPrinterQueueInfo( ImplPrnQueueList* pList )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::GetPrinterQueueState( SalPrinterQueueInfo* pInfo )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DeletePrinterQueueInfo( SalPrinterQueueInfo* pInfo )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nXubString SalInstance::GetDefaultPrinter()\n{\n return XubString();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalInfoPrinter* SalInstance::CreateInfoPrinter( SalPrinterQueueInfo* pQueueInfo,\n ImplJobSetup* pSetupData )\n{\n return NULL;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DestroyInfoPrinter( SalInfoPrinter* pPrinter )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalSystem* SalInstance::CreateSystem()\n{\n return new SalSystem();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DestroySystem( SalSystem* pSystem )\n{\n delete pSystem;\n}\n<commit_msg>Implemented modal event loop to support modal dialog windows<commit_after>\/*************************************************************************\n *\n * $RCSfile: salinst.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: pluby $ $Date: 2000-11-20 05:44:22 $\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#include <stdio.h>\n\n#define _SV_SALINST_CXX\n\n#ifndef _SV_SALDATA_HXX\n#include <saldata.hxx>\n#endif\n#ifndef _SV_SALINST_HXX\n#include <salinst.hxx>\n#endif\n#ifndef _SV_SALFRAME_HXX\n#include <salframe.hxx>\n#endif\n#ifndef _SV_SALOBJ_HXX\n#include <salobj.hxx>\n#endif\n#ifndef _SV_SALSYS_HXX\n#include <salsys.hxx>\n#endif\n#ifndef _SV_DIALOG_HXX\n#include <dialog.hxx>\n#endif\n#ifndef _SV_VCLAPPLICATION_H\n#include <VCLApplication.h>\n#endif\n\n\/\/ =======================================================================\n\nvoid SalAbort( const XubString& rErrorText )\n{\n if( !rErrorText.Len() )\n fprintf( stderr, \"Application Error\" );\n else\n fprintf( stderr,\n ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() );\n abort();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid InitSalData()\n{\n SalData *pSalData = new SalData;\n SetSalData( pSalData );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid DeInitSalData()\n{\n SalData *pSalData = GetSalData();\n delete pSalData;\n SetSalData( NULL );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SetFilterCallback( void* pCallback, void* pInst )\n{\n SalData *pSalData = GetSalData();\n pSalData->mpFirstInstance->maInstData.mpFilterCallback = pCallback;\n pSalData->mpFirstInstance->maInstData.mpFilterInst = pInst;\n}\n\n\/\/ =======================================================================\n\nSalInstance* CreateSalInstance()\n{\n SalData* pSalData = GetSalData();\n SalInstance* pInst = new SalInstance;\n\n \/\/ init instance (only one instance in this version !!!)\n pSalData->mpFirstInstance = pInst;\n\n return pInst;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid DestroySalInstance( SalInstance* pInst )\n{\n delete pInst;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalInstance::SalInstance()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalInstance::~SalInstance()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvos::IMutex* SalInstance::GetYieldMutex()\n{\n return NULL;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nULONG SalInstance::ReleaseYieldMutex()\n{\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::AcquireYieldMutex( ULONG nCount )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::Yield( BOOL bWait )\n{\n ImplSVData* pSVData = ImplGetSVData();\n\n \/\/ Check if this is a request from a modal window\n if ( pSVData->maAppData.mnModalMode )\n {\n \/\/ If this is a request from a modal window, run a modal session.\n \/\/ Note that VCLApplication_runModalForWindow will not return until\n \/\/ the modal session has ended.\n Dialog *pDialog = pSVData->maWinData.mpLastExecuteDlg;\n if ( pDialog ) {\n SalFrame *pFrame = pDialog->ImplGetFrame();\n if ( pFrame && pFrame->maFrameData.mhWnd )\n VCLApplication_runModalForWindow( pFrame->maFrameData.mhWnd );\n }\n }\n else\n {\n \/\/ If this is not a request from a modal window, start the event queue.\n \/\/ Note that VCLApplication_run() will not return until the\n \/\/ application shuts down. On other platforms, this function returns\n \/\/ after each event is pulled off the event queue and dispatched.\n \/\/ Instead, we have enter this method only once and let\n \/\/ VCLApplication_run do all of the pulling and dispatching of events.\n VCLApplication_run();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL SalInstance::AnyInput( USHORT nType )\n{\n return FALSE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalFrame* SalInstance::CreateChildFrame( SystemParentData* pSystemParentData, ULONG nSalFrameStyle )\n{\n return NULL;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalFrame* SalInstance::CreateFrame( SalFrame* pParent, ULONG nSalFrameStyle )\n{\n SalFrame *pFrame = new SalFrame;\n\n pFrame->maFrameData.mpParent = pParent;\n\n \/\/ Create the native window\n pFrame->maFrameData.mhWnd = VCLWindow_new( nSalFrameStyle, NULL,\n pFrame, &(pFrame->maFrameData) );\n\n return pFrame;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DestroyFrame( SalFrame* pFrame )\n{\n delete ( pFrame );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalObject* SalInstance::CreateObject( SalFrame* pParent )\n{\n SalObject *pObject = new SalObject;\n\n pObject->maObjectData.mhWnd = pParent->maFrameData.mhWnd;\n\n return pObject;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DestroyObject( SalObject* pObject )\n{\n delete ( pObject );\n}\n\nvoid SalInstance::GetPrinterQueueInfo( ImplPrnQueueList* pList )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::GetPrinterQueueState( SalPrinterQueueInfo* pInfo )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DeletePrinterQueueInfo( SalPrinterQueueInfo* pInfo )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nXubString SalInstance::GetDefaultPrinter()\n{\n return XubString();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalInfoPrinter* SalInstance::CreateInfoPrinter( SalPrinterQueueInfo* pQueueInfo,\n ImplJobSetup* pSetupData )\n{\n return NULL;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DestroyInfoPrinter( SalInfoPrinter* pPrinter )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSalSystem* SalInstance::CreateSystem()\n{\n return new SalSystem();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SalInstance::DestroySystem( SalSystem* pSystem )\n{\n delete pSystem;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Use and distribution licensed under the Apache license version 2.\n *\n * See the COPYING file in the root project directory for full text.\n *\/\n\n#include <string.h>\n\n#include <iostream>\n\n#include <sqltoast\/sqltoast.h>\n\n#include \"measure.h\"\n#include \"printer.h\"\n\nusing namespace std;\n\nstruct parser {\n sqltoast::parse_options_t opts;\n sqltoast::parse_input_t subject;\n sqltoast::parse_result_t res;\n parser(sqltoast::parse_options_t& opts, const std::string &input) :\n opts(opts),\n subject(input.cbegin(), input.cend())\n {}\n void operator()() {\n res = sqltoast::parse(subject, opts);\n }\n};\n\nvoid usage(const char* prg_name) {\n cout << \"Usage: \" << prg_name << \" [--disable-timer] [--yaml] <SQL>\" << endl;\n cout << \" using libsqltoast version \" <<\n SQLTOAST_VERSION_MAJOR << '.' <<\n SQLTOAST_VERSION_MINOR << endl;\n}\n\nint main (int argc, char *argv[])\n{\n std::string input;\n bool disable_timer = false;\n bool use_yaml = false;\n\n for (int x = 1; x < argc; x++) {\n if (strcmp(argv[x], \"--disable-timer\") == 0) {\n disable_timer = true;\n continue;\n }\n if (strcmp(argv[x], \"--yaml\") == 0) {\n use_yaml = true;\n continue;\n }\n input.assign(argv[x]);\n break;\n }\n if (input.empty()) {\n usage(argv[0]);\n return 1;\n }\n\n sqltoast::parse_options_t opts = {sqltoast::SQL_DIALECT_ANSI_1992, false};\n parser p(opts, input);\n\n auto dur = measure<std::chrono::nanoseconds>::execution(p);\n sqltoaster::printer ptr(p.res, cout);\n if (use_yaml)\n ptr.set_yaml(cout);\n if (p.res.code == sqltoast::PARSE_OK) {\n cout << \"OK\";\n cout << ptr << std::endl;\n } else if (p.res.code == sqltoast::PARSE_INPUT_ERROR) {\n cout << \"Input error: \" << p.res.error << endl;\n } else {\n cout << \"Syntax error.\" << endl;\n cout << p.res.error << endl;\n }\n if (! disable_timer)\n cout << \"(took \" << dur << \" nanoseconds)\" << endl;\n return 0;\n}\n<commit_msg>Make std:: namespace explicit in sqltoaster\/main.cc<commit_after>\/*\n * Use and distribution licensed under the Apache license version 2.\n *\n * See the COPYING file in the root project directory for full text.\n *\/\n\n#include <string.h>\n\n#include <iostream>\n\n#include <sqltoast\/sqltoast.h>\n\n#include \"measure.h\"\n#include \"printer.h\"\n\nstruct parser {\n sqltoast::parse_options_t opts;\n sqltoast::parse_input_t subject;\n sqltoast::parse_result_t res;\n parser(sqltoast::parse_options_t& opts, const std::string &input) :\n opts(opts),\n subject(input.cbegin(), input.cend())\n {}\n void operator()() {\n res = sqltoast::parse(subject, opts);\n }\n};\n\nvoid usage(const char* prg_name) {\n std::cout << \"Usage: \" << prg_name <<\n \" [--disable-timer] [--yaml] <SQL>\" << std::endl;\n std::cout << \" using libsqltoast version \" <<\n SQLTOAST_VERSION_MAJOR << '.' <<\n SQLTOAST_VERSION_MINOR << std::endl;\n}\n\nint main (int argc, char *argv[])\n{\n std::string input;\n bool disable_timer = false;\n bool use_yaml = false;\n\n for (int x = 1; x < argc; x++) {\n if (strcmp(argv[x], \"--disable-timer\") == 0) {\n disable_timer = true;\n continue;\n }\n if (strcmp(argv[x], \"--yaml\") == 0) {\n use_yaml = true;\n continue;\n }\n input.assign(argv[x]);\n break;\n }\n if (input.empty()) {\n usage(argv[0]);\n return 1;\n }\n\n sqltoast::parse_options_t opts = {sqltoast::SQL_DIALECT_ANSI_1992, false};\n parser p(opts, input);\n\n auto dur = measure<std::chrono::nanoseconds>::execution(p);\n sqltoaster::printer ptr(p.res, std::cout);\n if (use_yaml)\n ptr.set_yaml(std::cout);\n if (p.res.code == sqltoast::PARSE_OK) {\n std::cout << \"OK\";\n std::cout << ptr << std::endl;\n } else if (p.res.code == sqltoast::PARSE_INPUT_ERROR) {\n std::cout << \"Input error: \" << p.res.error << std::endl;\n } else {\n std::cout << \"Syntax error.\" << std::endl;\n std::cout << p.res.error << std::endl;\n }\n if (! disable_timer)\n std::cout << \"(took \" << dur << \" nanoseconds)\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Contours.h\"\n#include \"OpenCV.h\"\n#include <nan.h>\n\n#include <iostream>\n\nNan::Persistent<FunctionTemplate> Contour::constructor;\n\nvoid Contour::Init(Local<Object> target) {\n Nan::HandleScope scope;\n\n \/\/ Class\/contructor\n Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Contour::New);\n constructor.Reset(ctor);\n ctor->InstanceTemplate()->SetInternalFieldCount(1);\n ctor->SetClassName(Nan::New(\"Contours\").ToLocalChecked());\n\n \/\/ Prototype\n \/\/ Local<ObjectTemplate> proto = constructor->PrototypeTemplate();\n Nan::SetPrototypeMethod(ctor, \"point\", Point);\n Nan::SetPrototypeMethod(ctor, \"points\", Points);\n Nan::SetPrototypeMethod(ctor, \"size\", Size);\n Nan::SetPrototypeMethod(ctor, \"cornerCount\", CornerCount);\n Nan::SetPrototypeMethod(ctor, \"area\", Area);\n Nan::SetPrototypeMethod(ctor, \"arcLength\", ArcLength);\n Nan::SetPrototypeMethod(ctor, \"approxPolyDP\", ApproxPolyDP);\n Nan::SetPrototypeMethod(ctor, \"convexHull\", ConvexHull);\n Nan::SetPrototypeMethod(ctor, \"boundingRect\", BoundingRect);\n Nan::SetPrototypeMethod(ctor, \"minAreaRect\", MinAreaRect);\n Nan::SetPrototypeMethod(ctor, \"fitEllipse\", FitEllipse);\n Nan::SetPrototypeMethod(ctor, \"isConvex\", IsConvex);\n Nan::SetPrototypeMethod(ctor, \"moments\", Moments);\n Nan::SetPrototypeMethod(ctor, \"hierarchy\", Hierarchy);\n Nan::SetPrototypeMethod(ctor, \"serialize\", Serialize);\n Nan::SetPrototypeMethod(ctor, \"deserialize\", Deserialize);\n target->Set(Nan::New(\"Contours\").ToLocalChecked(), ctor->GetFunction());\n};\n\nNAN_METHOD(Contour::New) {\n Nan::HandleScope scope;\n\n if (info.This()->InternalFieldCount() == 0) {\n Nan::ThrowTypeError(\"Cannot instantiate without new\");\n }\n\n Contour *contours;\n contours = new Contour;\n\n contours->Wrap(info.Holder());\n info.GetReturnValue().Set(info.Holder());\n}\n\nContour::Contour() :\n Nan::ObjectWrap() {\n}\n\nNAN_METHOD(Contour::Point) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n int index = info[1]->NumberValue();\n\n cv::Point point = self->contours[pos][index];\n\n Local<Object> data = Nan::New<Object>();\n data->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(point.x));\n data->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(point.y));\n\n info.GetReturnValue().Set(data);\n}\n\nNAN_METHOD(Contour::Points) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n std::vector<cv::Point> points = self->contours[pos];\n Local<Array> data = Nan::New<Array>(points.size());\n\n for (std::vector<int>::size_type i = 0; i != points.size(); i++) {\n Local<Object> point_data = Nan::New<Object>();\n point_data->Set(Nan::New<String>(\"x\").ToLocalChecked(), Nan::New<Number>(points[i].x));\n point_data->Set(Nan::New<String>(\"y\").ToLocalChecked(), Nan::New<Number>(points[i].y));\n\n data->Set(i, point_data);\n }\n\n info.GetReturnValue().Set(data);\n}\n\n\/\/ FIXME: this should better be called \"Length\" as ``Contours`` is an Array like\n\/\/ structure also, this would allow to use ``Size`` for the function returning\n\/\/ the number of corners in the contour for better consistency with OpenCV.\nNAN_METHOD(Contour::Size) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n\n info.GetReturnValue().Set(Nan::New<Number>(self->contours.size()));\n}\n\nNAN_METHOD(Contour::CornerCount) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n info.GetReturnValue().Set(Nan::New<Number>(self->contours[pos].size()));\n}\n\nNAN_METHOD(Contour::Area) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n \/\/ info.GetReturnValue().Set(Nan::New<Number>(contourArea(self->contours)));\n info.GetReturnValue().Set(Nan::New<Number>(contourArea(cv::Mat(self->contours[pos]))));\n}\n\nNAN_METHOD(Contour::ArcLength) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n bool isClosed = info[1]->BooleanValue();\n\n info.GetReturnValue().Set(Nan::New<Number>(arcLength(cv::Mat(self->contours[pos]), isClosed)));\n}\n\nNAN_METHOD(Contour::ApproxPolyDP) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n double epsilon = info[1]->NumberValue();\n bool isClosed = info[2]->BooleanValue();\n\n cv::Mat approxed;\n approxPolyDP(cv::Mat(self->contours[pos]), approxed, epsilon, isClosed);\n approxed.copyTo(self->contours[pos]);\n\n info.GetReturnValue().Set(Nan::Null());\n}\n\nNAN_METHOD(Contour::ConvexHull) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n\n int pos = info[0]->NumberValue();\n bool clockwise = info[1]->BooleanValue();\n\n cv::Mat hull;\n cv::convexHull(cv::Mat(self->contours[pos]), hull, clockwise);\n hull.copyTo(self->contours[pos]);\n\n info.GetReturnValue().Set(Nan::Null());\n}\n\nNAN_METHOD(Contour::BoundingRect) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n cv::Rect bounding = cv::boundingRect(cv::Mat(self->contours[pos]));\n Local<Object> rect = Nan::New<Object>();\n\n rect->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(bounding.x));\n rect->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(bounding.y));\n rect->Set(Nan::New(\"width\").ToLocalChecked(), Nan::New<Number>(bounding.width));\n rect->Set(Nan::New(\"height\").ToLocalChecked(), Nan::New<Number>(bounding.height));\n\n info.GetReturnValue().Set(rect);\n}\n\nNAN_METHOD(Contour::MinAreaRect) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n cv::RotatedRect minimum = cv::minAreaRect(cv::Mat(self->contours[pos]));\n\n Local<Object> rect = Nan::New<Object>();\n rect->Set(Nan::New(\"angle\").ToLocalChecked(), Nan::New<Number>(minimum.angle));\n\n Local<Object> size = Nan::New<Object>();\n size->Set(Nan::New(\"height\").ToLocalChecked(), Nan::New<Number>(minimum.size.height));\n size->Set(Nan::New(\"width\").ToLocalChecked(), Nan::New<Number>(minimum.size.width));\n rect->Set(Nan::New(\"size\").ToLocalChecked(), size);\n\n Local<Object> center = Nan::New<Object>();\n center->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(minimum.center.x));\n center->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(minimum.center.y));\n\n v8::Local<v8::Array> points = Nan::New<Array>(4);\n\n cv::Point2f rect_points[4];\n minimum.points(rect_points);\n\n for (unsigned int i=0; i<4; i++) {\n Local<Object> point = Nan::New<Object>();\n point->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(rect_points[i].x));\n point->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(rect_points[i].y));\n points->Set(i, point);\n }\n\n rect->Set(Nan::New(\"points\").ToLocalChecked(), points);\n\n info.GetReturnValue().Set(rect);\n}\n\nNAN_METHOD(Contour::FitEllipse) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n if (self->contours[pos].size() >= 5) { \/\/ Minimum number for an ellipse\n cv::RotatedRect ellipse = cv::fitEllipse(cv::Mat(self->contours[pos]));\n\n Local<Object> jsEllipse = Nan::New<Object>();\n jsEllipse->Set(Nan::New(\"angle\").ToLocalChecked(), Nan::New<Number>(ellipse.angle));\n\n Local<Object> size = Nan::New<Object>();\n size->Set(Nan::New(\"height\").ToLocalChecked(), Nan::New<Number>(ellipse.size.height));\n size->Set(Nan::New(\"width\").ToLocalChecked(), Nan::New<Number>(ellipse.size.width));\n jsEllipse->Set(Nan::New(\"size\").ToLocalChecked(), size);\n\n Local<Object> center = Nan::New<Object>();\n center->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(ellipse.center.x));\n center->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(ellipse.center.y));\n jsEllipse->Set(Nan::New(\"center\").ToLocalChecked(), center);\n\n info.GetReturnValue().Set(jsEllipse);\n }\n\n info.GetReturnValue().Set(Nan::Null());\n}\n\nNAN_METHOD(Contour::IsConvex) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n info.GetReturnValue().Set(Nan::New<Boolean>(isContourConvex(cv::Mat(self->contours[pos]))));\n}\n\nNAN_METHOD(Contour::Moments) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n \/\/ Get the moments\n cv::Moments mu = moments( self->contours[pos], false );\n\n Local<Object> res = Nan::New<Object>();\n\n res->Set(Nan::New(\"m00\").ToLocalChecked(), Nan::New<Number>(mu.m00));\n res->Set(Nan::New(\"m10\").ToLocalChecked(), Nan::New<Number>(mu.m10));\n res->Set(Nan::New(\"m01\").ToLocalChecked(), Nan::New<Number>(mu.m01));\n res->Set(Nan::New(\"m11\").ToLocalChecked(), Nan::New<Number>(mu.m11));\n\n info.GetReturnValue().Set(res);\n}\n\nNAN_METHOD(Contour::Hierarchy) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->IntegerValue();\n\n cv::Vec4i hierarchy = self->hierarchy[pos];\n\n Local<Array> res = Nan::New<Array>(4);\n\n res->Set(0, Nan::New<Number>(hierarchy[0]));\n res->Set(1, Nan::New<Number>(hierarchy[1]));\n res->Set(2, Nan::New<Number>(hierarchy[2]));\n res->Set(3, Nan::New<Number>(hierarchy[3]));\n\n info.GetReturnValue().Set(res);\n}\n\nNAN_METHOD(Contour::Serialize) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n\n Local<Array> contours_data = Nan::New<Array>(self->contours.size());\n\n for (std::vector<int>::size_type i = 0; i != self->contours.size(); i++) {\n std::vector<cv::Point> points = self->contours[i];\n Local<Array> contour_data = Nan::New<Array>(points.size());\n\n for (std::vector<int>::size_type j = 0; j != points.size(); j++) {\n Local<Array> point_data = Nan::New<Array>(2);\n point_data->Set(0, Nan::New<Number>(points[j].x));\n point_data->Set(1, Nan::New<Number>(points[j].y));\n\n contour_data->Set(j, point_data);\n }\n contours_data->Set(i, contour_data);\n }\n\n Local<Array> hierarchy_data = Nan::New<Array>(self->hierarchy.size());\n for (std::vector<int>::size_type i = 0; i != self->hierarchy.size(); i++) {\n Local<Array> contour_data = Nan::New<Array>(4);\n contour_data->Set(0, Nan::New<Number>(self->hierarchy[i][0]));\n contour_data->Set(1, Nan::New<Number>(self->hierarchy[i][1]));\n contour_data->Set(2, Nan::New<Number>(self->hierarchy[i][2]));\n contour_data->Set(3, Nan::New<Number>(self->hierarchy[i][3]));\n\n hierarchy_data->Set(i, contour_data);\n }\n\n Local<Object> data = Nan::New<Object>();\n data->Set(Nan::New<String>(\"contours\").ToLocalChecked(), contours_data);\n data->Set(Nan::New<String>(\"hierarchy\").ToLocalChecked(), hierarchy_data);\n\n info.GetReturnValue().Set(data);\n}\n\nNAN_METHOD(Contour::Deserialize) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n\n Local<Object> data = Local<Object>::Cast(info[0]);\n\n Local<Array> contours_data = Local<Array>::Cast(data->Get(Nan::New<String>(\"contours\").ToLocalChecked()));\n Local<Array> hierarchy_data = Local<Array>::Cast(data->Get(Nan::New<String>(\"hierarchy\").ToLocalChecked()));\n\n std::vector<std::vector<cv::Point> > contours_res;\n int contours_length = contours_data->Length();\n\n for (int i = 0; i < contours_length; i++) {\n Local<Array> contour_data = Local<Array>::Cast(contours_data->Get(i));\n std::vector<cv::Point> points;\n\n int contour_length = contour_data->Length();\n for (int j = 0; j < contour_length; j++) {\n Local<Array> point_data = Local<Array>::Cast(contour_data->Get(j));\n int x = point_data->Get(0)->IntegerValue();\n int y = point_data->Get(1)->IntegerValue();\n points.push_back(cv::Point(x, y));\n }\n\n contours_res.push_back(points);\n }\n\n std::vector<cv::Vec4i> hierarchy_res;\n int hierarchy_length = hierarchy_data->Length();\n\n for (int i = 0; i < hierarchy_length; i++) {\n Local<Array> contour_data = Local<Array>::Cast(hierarchy_data->Get(i));\n int a = contour_data->Get(0)->IntegerValue();\n int b = contour_data->Get(1)->IntegerValue();\n int c = contour_data->Get(2)->IntegerValue();\n int d = contour_data->Get(3)->IntegerValue();\n hierarchy_res.push_back(cv::Vec4i(a, b, c, d));\n }\n\n self->contours = contours_res;\n self->hierarchy = hierarchy_res;\n\n info.GetReturnValue().Set(Nan::Null());\n}\n<commit_msg>Add support for the 'Oriented' area flag in contourArea<commit_after>#include \"Contours.h\"\n#include \"OpenCV.h\"\n#include <nan.h>\n\n#include <iostream>\n\nNan::Persistent<FunctionTemplate> Contour::constructor;\n\nvoid Contour::Init(Local<Object> target) {\n Nan::HandleScope scope;\n\n \/\/ Class\/contructor\n Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Contour::New);\n constructor.Reset(ctor);\n ctor->InstanceTemplate()->SetInternalFieldCount(1);\n ctor->SetClassName(Nan::New(\"Contours\").ToLocalChecked());\n\n \/\/ Prototype\n \/\/ Local<ObjectTemplate> proto = constructor->PrototypeTemplate();\n Nan::SetPrototypeMethod(ctor, \"point\", Point);\n Nan::SetPrototypeMethod(ctor, \"points\", Points);\n Nan::SetPrototypeMethod(ctor, \"size\", Size);\n Nan::SetPrototypeMethod(ctor, \"cornerCount\", CornerCount);\n Nan::SetPrototypeMethod(ctor, \"area\", Area);\n Nan::SetPrototypeMethod(ctor, \"arcLength\", ArcLength);\n Nan::SetPrototypeMethod(ctor, \"approxPolyDP\", ApproxPolyDP);\n Nan::SetPrototypeMethod(ctor, \"convexHull\", ConvexHull);\n Nan::SetPrototypeMethod(ctor, \"boundingRect\", BoundingRect);\n Nan::SetPrototypeMethod(ctor, \"minAreaRect\", MinAreaRect);\n Nan::SetPrototypeMethod(ctor, \"fitEllipse\", FitEllipse);\n Nan::SetPrototypeMethod(ctor, \"isConvex\", IsConvex);\n Nan::SetPrototypeMethod(ctor, \"moments\", Moments);\n Nan::SetPrototypeMethod(ctor, \"hierarchy\", Hierarchy);\n Nan::SetPrototypeMethod(ctor, \"serialize\", Serialize);\n Nan::SetPrototypeMethod(ctor, \"deserialize\", Deserialize);\n target->Set(Nan::New(\"Contours\").ToLocalChecked(), ctor->GetFunction());\n};\n\nNAN_METHOD(Contour::New) {\n Nan::HandleScope scope;\n\n if (info.This()->InternalFieldCount() == 0) {\n Nan::ThrowTypeError(\"Cannot instantiate without new\");\n }\n\n Contour *contours;\n contours = new Contour;\n\n contours->Wrap(info.Holder());\n info.GetReturnValue().Set(info.Holder());\n}\n\nContour::Contour() :\n Nan::ObjectWrap() {\n}\n\nNAN_METHOD(Contour::Point) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n int index = info[1]->NumberValue();\n\n cv::Point point = self->contours[pos][index];\n\n Local<Object> data = Nan::New<Object>();\n data->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(point.x));\n data->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(point.y));\n\n info.GetReturnValue().Set(data);\n}\n\nNAN_METHOD(Contour::Points) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n std::vector<cv::Point> points = self->contours[pos];\n Local<Array> data = Nan::New<Array>(points.size());\n\n for (std::vector<int>::size_type i = 0; i != points.size(); i++) {\n Local<Object> point_data = Nan::New<Object>();\n point_data->Set(Nan::New<String>(\"x\").ToLocalChecked(), Nan::New<Number>(points[i].x));\n point_data->Set(Nan::New<String>(\"y\").ToLocalChecked(), Nan::New<Number>(points[i].y));\n\n data->Set(i, point_data);\n }\n\n info.GetReturnValue().Set(data);\n}\n\n\/\/ FIXME: this should better be called \"Length\" as ``Contours`` is an Array like\n\/\/ structure also, this would allow to use ``Size`` for the function returning\n\/\/ the number of corners in the contour for better consistency with OpenCV.\nNAN_METHOD(Contour::Size) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n\n info.GetReturnValue().Set(Nan::New<Number>(self->contours.size()));\n}\n\nNAN_METHOD(Contour::CornerCount) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n info.GetReturnValue().Set(Nan::New<Number>(self->contours[pos].size()));\n}\n\nNAN_METHOD(Contour::Area) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n bool orientation = (info.Length() > 1 && info[1]->BooleanValue());\n\n \/\/ info.GetReturnValue().Set(Nan::New<Number>(contourArea(self->contours)));\n info.GetReturnValue().Set(Nan::New<Number>(contourArea(cv::Mat(self->contours[pos]), orientation)));\n}\n\nNAN_METHOD(Contour::ArcLength) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n bool isClosed = info[1]->BooleanValue();\n\n info.GetReturnValue().Set(Nan::New<Number>(arcLength(cv::Mat(self->contours[pos]), isClosed)));\n}\n\nNAN_METHOD(Contour::ApproxPolyDP) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n double epsilon = info[1]->NumberValue();\n bool isClosed = info[2]->BooleanValue();\n\n cv::Mat approxed;\n approxPolyDP(cv::Mat(self->contours[pos]), approxed, epsilon, isClosed);\n approxed.copyTo(self->contours[pos]);\n\n info.GetReturnValue().Set(Nan::Null());\n}\n\nNAN_METHOD(Contour::ConvexHull) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n\n int pos = info[0]->NumberValue();\n bool clockwise = info[1]->BooleanValue();\n\n cv::Mat hull;\n cv::convexHull(cv::Mat(self->contours[pos]), hull, clockwise);\n hull.copyTo(self->contours[pos]);\n\n info.GetReturnValue().Set(Nan::Null());\n}\n\nNAN_METHOD(Contour::BoundingRect) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n cv::Rect bounding = cv::boundingRect(cv::Mat(self->contours[pos]));\n Local<Object> rect = Nan::New<Object>();\n\n rect->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(bounding.x));\n rect->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(bounding.y));\n rect->Set(Nan::New(\"width\").ToLocalChecked(), Nan::New<Number>(bounding.width));\n rect->Set(Nan::New(\"height\").ToLocalChecked(), Nan::New<Number>(bounding.height));\n\n info.GetReturnValue().Set(rect);\n}\n\nNAN_METHOD(Contour::MinAreaRect) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n cv::RotatedRect minimum = cv::minAreaRect(cv::Mat(self->contours[pos]));\n\n Local<Object> rect = Nan::New<Object>();\n rect->Set(Nan::New(\"angle\").ToLocalChecked(), Nan::New<Number>(minimum.angle));\n\n Local<Object> size = Nan::New<Object>();\n size->Set(Nan::New(\"height\").ToLocalChecked(), Nan::New<Number>(minimum.size.height));\n size->Set(Nan::New(\"width\").ToLocalChecked(), Nan::New<Number>(minimum.size.width));\n rect->Set(Nan::New(\"size\").ToLocalChecked(), size);\n\n Local<Object> center = Nan::New<Object>();\n center->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(minimum.center.x));\n center->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(minimum.center.y));\n\n v8::Local<v8::Array> points = Nan::New<Array>(4);\n\n cv::Point2f rect_points[4];\n minimum.points(rect_points);\n\n for (unsigned int i=0; i<4; i++) {\n Local<Object> point = Nan::New<Object>();\n point->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(rect_points[i].x));\n point->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(rect_points[i].y));\n points->Set(i, point);\n }\n\n rect->Set(Nan::New(\"points\").ToLocalChecked(), points);\n\n info.GetReturnValue().Set(rect);\n}\n\nNAN_METHOD(Contour::FitEllipse) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n if (self->contours[pos].size() >= 5) { \/\/ Minimum number for an ellipse\n cv::RotatedRect ellipse = cv::fitEllipse(cv::Mat(self->contours[pos]));\n\n Local<Object> jsEllipse = Nan::New<Object>();\n jsEllipse->Set(Nan::New(\"angle\").ToLocalChecked(), Nan::New<Number>(ellipse.angle));\n\n Local<Object> size = Nan::New<Object>();\n size->Set(Nan::New(\"height\").ToLocalChecked(), Nan::New<Number>(ellipse.size.height));\n size->Set(Nan::New(\"width\").ToLocalChecked(), Nan::New<Number>(ellipse.size.width));\n jsEllipse->Set(Nan::New(\"size\").ToLocalChecked(), size);\n\n Local<Object> center = Nan::New<Object>();\n center->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New<Number>(ellipse.center.x));\n center->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New<Number>(ellipse.center.y));\n jsEllipse->Set(Nan::New(\"center\").ToLocalChecked(), center);\n\n info.GetReturnValue().Set(jsEllipse);\n }\n\n info.GetReturnValue().Set(Nan::Null());\n}\n\nNAN_METHOD(Contour::IsConvex) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n info.GetReturnValue().Set(Nan::New<Boolean>(isContourConvex(cv::Mat(self->contours[pos]))));\n}\n\nNAN_METHOD(Contour::Moments) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->NumberValue();\n\n \/\/ Get the moments\n cv::Moments mu = moments( self->contours[pos], false );\n\n Local<Object> res = Nan::New<Object>();\n\n res->Set(Nan::New(\"m00\").ToLocalChecked(), Nan::New<Number>(mu.m00));\n res->Set(Nan::New(\"m10\").ToLocalChecked(), Nan::New<Number>(mu.m10));\n res->Set(Nan::New(\"m01\").ToLocalChecked(), Nan::New<Number>(mu.m01));\n res->Set(Nan::New(\"m11\").ToLocalChecked(), Nan::New<Number>(mu.m11));\n\n info.GetReturnValue().Set(res);\n}\n\nNAN_METHOD(Contour::Hierarchy) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n int pos = info[0]->IntegerValue();\n\n cv::Vec4i hierarchy = self->hierarchy[pos];\n\n Local<Array> res = Nan::New<Array>(4);\n\n res->Set(0, Nan::New<Number>(hierarchy[0]));\n res->Set(1, Nan::New<Number>(hierarchy[1]));\n res->Set(2, Nan::New<Number>(hierarchy[2]));\n res->Set(3, Nan::New<Number>(hierarchy[3]));\n\n info.GetReturnValue().Set(res);\n}\n\nNAN_METHOD(Contour::Serialize) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n\n Local<Array> contours_data = Nan::New<Array>(self->contours.size());\n\n for (std::vector<int>::size_type i = 0; i != self->contours.size(); i++) {\n std::vector<cv::Point> points = self->contours[i];\n Local<Array> contour_data = Nan::New<Array>(points.size());\n\n for (std::vector<int>::size_type j = 0; j != points.size(); j++) {\n Local<Array> point_data = Nan::New<Array>(2);\n point_data->Set(0, Nan::New<Number>(points[j].x));\n point_data->Set(1, Nan::New<Number>(points[j].y));\n\n contour_data->Set(j, point_data);\n }\n contours_data->Set(i, contour_data);\n }\n\n Local<Array> hierarchy_data = Nan::New<Array>(self->hierarchy.size());\n for (std::vector<int>::size_type i = 0; i != self->hierarchy.size(); i++) {\n Local<Array> contour_data = Nan::New<Array>(4);\n contour_data->Set(0, Nan::New<Number>(self->hierarchy[i][0]));\n contour_data->Set(1, Nan::New<Number>(self->hierarchy[i][1]));\n contour_data->Set(2, Nan::New<Number>(self->hierarchy[i][2]));\n contour_data->Set(3, Nan::New<Number>(self->hierarchy[i][3]));\n\n hierarchy_data->Set(i, contour_data);\n }\n\n Local<Object> data = Nan::New<Object>();\n data->Set(Nan::New<String>(\"contours\").ToLocalChecked(), contours_data);\n data->Set(Nan::New<String>(\"hierarchy\").ToLocalChecked(), hierarchy_data);\n\n info.GetReturnValue().Set(data);\n}\n\nNAN_METHOD(Contour::Deserialize) {\n Nan::HandleScope scope;\n\n Contour *self = Nan::ObjectWrap::Unwrap<Contour>(info.This());\n\n Local<Object> data = Local<Object>::Cast(info[0]);\n\n Local<Array> contours_data = Local<Array>::Cast(data->Get(Nan::New<String>(\"contours\").ToLocalChecked()));\n Local<Array> hierarchy_data = Local<Array>::Cast(data->Get(Nan::New<String>(\"hierarchy\").ToLocalChecked()));\n\n std::vector<std::vector<cv::Point> > contours_res;\n int contours_length = contours_data->Length();\n\n for (int i = 0; i < contours_length; i++) {\n Local<Array> contour_data = Local<Array>::Cast(contours_data->Get(i));\n std::vector<cv::Point> points;\n\n int contour_length = contour_data->Length();\n for (int j = 0; j < contour_length; j++) {\n Local<Array> point_data = Local<Array>::Cast(contour_data->Get(j));\n int x = point_data->Get(0)->IntegerValue();\n int y = point_data->Get(1)->IntegerValue();\n points.push_back(cv::Point(x, y));\n }\n\n contours_res.push_back(points);\n }\n\n std::vector<cv::Vec4i> hierarchy_res;\n int hierarchy_length = hierarchy_data->Length();\n\n for (int i = 0; i < hierarchy_length; i++) {\n Local<Array> contour_data = Local<Array>::Cast(hierarchy_data->Get(i));\n int a = contour_data->Get(0)->IntegerValue();\n int b = contour_data->Get(1)->IntegerValue();\n int c = contour_data->Get(2)->IntegerValue();\n int d = contour_data->Get(3)->IntegerValue();\n hierarchy_res.push_back(cv::Vec4i(a, b, c, d));\n }\n\n self->contours = contours_res;\n self->hierarchy = hierarchy_res;\n\n info.GetReturnValue().Set(Nan::Null());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#include \"XercesElementWrapper.hpp\"\n\n\n\n#include <xercesc\/dom\/DOMElement.hpp>\n\n\n\n#include <XalanDOM\/XalanAttr.hpp>\n\n\n\n#include <DOMSupport\/DOMServices.hpp>\n\n\n\n#include \"XercesWrapperHelper.hpp\"\n#include \"XercesWrapperNavigator.hpp\"\n#include \"XercesDOMWrapperException.hpp\"\n#include \"XercesDocumentWrapper.hpp\"\n\n\n\nXercesElementWrapper::XercesElementWrapper(\n\t\t\tconst DOMElement*\t\t\t\ttheXercesElement,\n\t\t\tconst XercesWrapperNavigator&\ttheNavigator) :\n\tXalanElement(),\n\tm_xercesNode(theXercesElement),\n\tm_navigator(theNavigator),\n\tm_children(theXercesElement->getChildNodes(),\n\t\t\t theNavigator),\n\tm_attributes(theXercesElement->getAttributes(),\n\t\t\t\t theNavigator)\n{\n\tassert(theXercesElement != 0);\n}\n\n\n\nXercesElementWrapper::~XercesElementWrapper()\n{\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getNodeName() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getNodeName());\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getNodeValue() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getNodeValue());\n}\n\n\n\nXercesElementWrapper::NodeType\nXercesElementWrapper::getNodeType() const\n{\n\treturn ELEMENT_NODE;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getParentNode() const\n{\n\treturn m_navigator.getParentNode(m_xercesNode);\n}\n\n\n\nconst XalanNodeList*\nXercesElementWrapper::getChildNodes() const\n{\n\treturn &m_children;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getFirstChild() const\n{\n\treturn m_navigator.getFirstChild(m_xercesNode);\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getLastChild() const\n{\n\treturn m_navigator.getLastChild(m_xercesNode);\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getPreviousSibling() const\n{\n\treturn m_navigator.getPreviousSibling(m_xercesNode);\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getNextSibling() const\n{\n\treturn m_navigator.getNextSibling(m_xercesNode);\n}\n\n\n\nconst XalanNamedNodeMap*\nXercesElementWrapper::getAttributes() const\n{\n\treturn &m_attributes;\n}\n\n\n\nXalanDocument*\nXercesElementWrapper::getOwnerDocument() const\n{\n\treturn m_navigator.getOwnerDocument();\n}\n\n\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\nXalanNode*\n#else\nXercesElementWrapper*\n#endif\nXercesElementWrapper::cloneNode(bool\t\/* deep *\/) const\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::NOT_SUPPORTED_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::insertBefore(\n\t\t\tXalanNode*\t\/* newChild *\/,\n\t\t\tXalanNode*\t\/* refChild *\/)\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::HIERARCHY_REQUEST_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::replaceChild(\n\t\t\tXalanNode*\t\/* newChild *\/,\n\t\t\tXalanNode*\t\/* oldChild *\/)\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::HIERARCHY_REQUEST_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::removeChild(XalanNode*\t\/* oldChild *\/)\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::HIERARCHY_REQUEST_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::appendChild(XalanNode*\t\/* newChild *\/)\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::HIERARCHY_REQUEST_ERR);\n\n\treturn 0;\n}\n\n\n\nbool\nXercesElementWrapper::hasChildNodes() const\n{\n\treturn m_xercesNode->hasChildNodes();\n}\n\n\n\nvoid\nXercesElementWrapper::setNodeValue(const XalanDOMString&\t\/* nodeValue *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nvoid\nXercesElementWrapper::normalize()\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nbool\nXercesElementWrapper::isSupported(\n\t\t\tconst XalanDOMString&\tfeature,\n\t\t\tconst XalanDOMString&\tversion) const\n{\n\treturn XercesWrapperHelper::isSupported(m_xercesNode, feature, version);\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getNamespaceURI() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getNamespaceURI());\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getPrefix() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getPrefix());\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getLocalName() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getLocalName());\n}\n\n\n\nvoid\nXercesElementWrapper::setPrefix(const XalanDOMString&\t\/* prefix *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nbool\nXercesElementWrapper::isIndexed() const\n{\n\treturn m_navigator.getOwnerDocument()->isIndexed();\n}\n\n\n\nunsigned long\nXercesElementWrapper::getIndex() const\n{\n\treturn m_navigator.getIndex();\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getTagName() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getTagName());\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getAttribute(const XalanDOMString&\t\tname) const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getAttribute(c_wstr(name)));\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::getAttributeNode(const XalanDOMString&\t\tname) const\n{\n#if defined(XALAN_OLD_STYLE_CASTS)\n\treturn (XalanAttr*)m_attributes.getNamedItem(name);\n#else\n\treturn static_cast<XalanAttr*>(m_attributes.getNamedItem(name));\n#endif\n}\n\n\n\nXalanNodeList*\nXercesElementWrapper::getElementsByTagName(const XalanDOMString&\t\/* name *\/) const\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::NOT_SUPPORTED_ERR);\n\n\treturn 0;\n}\n\n\n\nvoid\nXercesElementWrapper::setAttribute(\n\t\t\tconst XalanDOMString&\t\/* name *\/,\n\t\t\tconst XalanDOMString&\t\/* value *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::setAttributeNode(XalanAttr*\t\/* newAttr *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::removeAttributeNode(XalanAttr*\t\/* oldAttr *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nvoid\nXercesElementWrapper::removeAttribute(const XalanDOMString&\t\t\/* name *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getAttributeNS(\n\t\t\tconst XalanDOMString&\tnamespaceURI,\n\t\t\tconst XalanDOMString&\tlocalName) const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getAttributeNS(c_wstr(namespaceURI), c_wstr(localName)));\n}\n\n\n\nvoid\nXercesElementWrapper::setAttributeNS(\n\t\t\tconst XalanDOMString&\t\/* namespaceURI *\/,\n\t\t\tconst XalanDOMString&\t\/* qualifiedName *\/,\n\t\t\tconst XalanDOMString&\t\/* value *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nvoid\nXercesElementWrapper::removeAttributeNS(\n\t\t\tconst XalanDOMString&\t\/* namespaceURI *\/,\n\t\t\tconst XalanDOMString&\t\/* localName *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::getAttributeNodeNS(\n\t\t\tconst XalanDOMString&\tnamespaceURI,\n\t\t\tconst XalanDOMString&\tlocalName) const\n{\n\tDOMAttr* const\ttheAttrNode =\n\t\tm_xercesNode->getAttributeNodeNS(c_wstr(namespaceURI), c_wstr(localName));\n\n\treturn m_navigator.mapNode(theAttrNode);\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::setAttributeNodeNS(XalanAttr*\t\t\/* newAttr *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNodeList*\nXercesElementWrapper::getElementsByTagNameNS(\n\t\t\tconst XalanDOMString&\t\/* namespaceURI *\/,\n\t\t\tconst XalanDOMString&\t\/* localName *\/) const\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::NOT_SUPPORTED_ERR);\n\n\treturn 0;\n}\n<commit_msg>Added missing return statements.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights \n * 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 * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. 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\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS 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\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#include \"XercesElementWrapper.hpp\"\n\n\n\n#include <xercesc\/dom\/DOMElement.hpp>\n\n\n\n#include <XalanDOM\/XalanAttr.hpp>\n\n\n\n#include <DOMSupport\/DOMServices.hpp>\n\n\n\n#include \"XercesWrapperHelper.hpp\"\n#include \"XercesWrapperNavigator.hpp\"\n#include \"XercesDOMWrapperException.hpp\"\n#include \"XercesDocumentWrapper.hpp\"\n\n\n\nXercesElementWrapper::XercesElementWrapper(\n\t\t\tconst DOMElement*\t\t\t\ttheXercesElement,\n\t\t\tconst XercesWrapperNavigator&\ttheNavigator) :\n\tXalanElement(),\n\tm_xercesNode(theXercesElement),\n\tm_navigator(theNavigator),\n\tm_children(theXercesElement->getChildNodes(),\n\t\t\t theNavigator),\n\tm_attributes(theXercesElement->getAttributes(),\n\t\t\t\t theNavigator)\n{\n\tassert(theXercesElement != 0);\n}\n\n\n\nXercesElementWrapper::~XercesElementWrapper()\n{\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getNodeName() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getNodeName());\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getNodeValue() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getNodeValue());\n}\n\n\n\nXercesElementWrapper::NodeType\nXercesElementWrapper::getNodeType() const\n{\n\treturn ELEMENT_NODE;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getParentNode() const\n{\n\treturn m_navigator.getParentNode(m_xercesNode);\n}\n\n\n\nconst XalanNodeList*\nXercesElementWrapper::getChildNodes() const\n{\n\treturn &m_children;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getFirstChild() const\n{\n\treturn m_navigator.getFirstChild(m_xercesNode);\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getLastChild() const\n{\n\treturn m_navigator.getLastChild(m_xercesNode);\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getPreviousSibling() const\n{\n\treturn m_navigator.getPreviousSibling(m_xercesNode);\n}\n\n\n\nXalanNode*\nXercesElementWrapper::getNextSibling() const\n{\n\treturn m_navigator.getNextSibling(m_xercesNode);\n}\n\n\n\nconst XalanNamedNodeMap*\nXercesElementWrapper::getAttributes() const\n{\n\treturn &m_attributes;\n}\n\n\n\nXalanDocument*\nXercesElementWrapper::getOwnerDocument() const\n{\n\treturn m_navigator.getOwnerDocument();\n}\n\n\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\nXalanNode*\n#else\nXercesElementWrapper*\n#endif\nXercesElementWrapper::cloneNode(bool\t\/* deep *\/) const\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::NOT_SUPPORTED_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::insertBefore(\n\t\t\tXalanNode*\t\/* newChild *\/,\n\t\t\tXalanNode*\t\/* refChild *\/)\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::HIERARCHY_REQUEST_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::replaceChild(\n\t\t\tXalanNode*\t\/* newChild *\/,\n\t\t\tXalanNode*\t\/* oldChild *\/)\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::HIERARCHY_REQUEST_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::removeChild(XalanNode*\t\/* oldChild *\/)\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::HIERARCHY_REQUEST_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNode*\nXercesElementWrapper::appendChild(XalanNode*\t\/* newChild *\/)\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::HIERARCHY_REQUEST_ERR);\n\n\treturn 0;\n}\n\n\n\nbool\nXercesElementWrapper::hasChildNodes() const\n{\n\treturn m_xercesNode->hasChildNodes();\n}\n\n\n\nvoid\nXercesElementWrapper::setNodeValue(const XalanDOMString&\t\/* nodeValue *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nvoid\nXercesElementWrapper::normalize()\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nbool\nXercesElementWrapper::isSupported(\n\t\t\tconst XalanDOMString&\tfeature,\n\t\t\tconst XalanDOMString&\tversion) const\n{\n\treturn XercesWrapperHelper::isSupported(m_xercesNode, feature, version);\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getNamespaceURI() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getNamespaceURI());\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getPrefix() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getPrefix());\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getLocalName() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getLocalName());\n}\n\n\n\nvoid\nXercesElementWrapper::setPrefix(const XalanDOMString&\t\/* prefix *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nbool\nXercesElementWrapper::isIndexed() const\n{\n\treturn m_navigator.getOwnerDocument()->isIndexed();\n}\n\n\n\nunsigned long\nXercesElementWrapper::getIndex() const\n{\n\treturn m_navigator.getIndex();\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getTagName() const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getTagName());\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getAttribute(const XalanDOMString&\t\tname) const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getAttribute(c_wstr(name)));\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::getAttributeNode(const XalanDOMString&\t\tname) const\n{\n#if defined(XALAN_OLD_STYLE_CASTS)\n\treturn (XalanAttr*)m_attributes.getNamedItem(name);\n#else\n\treturn static_cast<XalanAttr*>(m_attributes.getNamedItem(name));\n#endif\n}\n\n\n\nXalanNodeList*\nXercesElementWrapper::getElementsByTagName(const XalanDOMString&\t\/* name *\/) const\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::NOT_SUPPORTED_ERR);\n\n\treturn 0;\n}\n\n\n\nvoid\nXercesElementWrapper::setAttribute(\n\t\t\tconst XalanDOMString&\t\/* name *\/,\n\t\t\tconst XalanDOMString&\t\/* value *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::setAttributeNode(XalanAttr*\t\/* newAttr *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::removeAttributeNode(XalanAttr*\t\/* oldAttr *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n\n\treturn 0;\n}\n\n\n\nvoid\nXercesElementWrapper::removeAttribute(const XalanDOMString&\t\t\/* name *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nconst XalanDOMString&\nXercesElementWrapper::getAttributeNS(\n\t\t\tconst XalanDOMString&\tnamespaceURI,\n\t\t\tconst XalanDOMString&\tlocalName) const\n{\n\treturn m_navigator.getPooledString(m_xercesNode->getAttributeNS(c_wstr(namespaceURI), c_wstr(localName)));\n}\n\n\n\nvoid\nXercesElementWrapper::setAttributeNS(\n\t\t\tconst XalanDOMString&\t\/* namespaceURI *\/,\n\t\t\tconst XalanDOMString&\t\/* qualifiedName *\/,\n\t\t\tconst XalanDOMString&\t\/* value *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nvoid\nXercesElementWrapper::removeAttributeNS(\n\t\t\tconst XalanDOMString&\t\/* namespaceURI *\/,\n\t\t\tconst XalanDOMString&\t\/* localName *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::getAttributeNodeNS(\n\t\t\tconst XalanDOMString&\tnamespaceURI,\n\t\t\tconst XalanDOMString&\tlocalName) const\n{\n\tDOMAttr* const\ttheAttrNode =\n\t\tm_xercesNode->getAttributeNodeNS(c_wstr(namespaceURI), c_wstr(localName));\n\n\treturn m_navigator.mapNode(theAttrNode);\n}\n\n\n\nXalanAttr*\nXercesElementWrapper::setAttributeNodeNS(XalanAttr*\t\t\/* newAttr *\/)\n{\n\tthrow XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);\n\n\treturn 0;\n}\n\n\n\nXalanNodeList*\nXercesElementWrapper::getElementsByTagNameNS(\n\t\t\tconst XalanDOMString&\t\/* namespaceURI *\/,\n\t\t\tconst XalanDOMString&\t\/* localName *\/) const\n{\n\tthrow XercesDOMWrapperException(XercesDOMWrapperException::NOT_SUPPORTED_ERR);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** Copyright (C) 2016, 2017 European Spallation Source ERIC *\/\n\n#include <gdgem\/srs\/SRSTime.h>\n#include <string>\n#include <test\/TestBase.h>\n#include <unistd.h>\n\nconstexpr float no_offset = 0.0;\nconstexpr float unit_slope = 1.0;\n\nclass SRSTimeTest : public TestBase {\nprotected:\n SRSTime *time;\n virtual void SetUp() { time = new SRSTime(); }\n virtual void TearDown() { delete time; }\n};\n\nTEST_F(SRSTimeTest, SettersGetters) {\n time->set_bc_clock(42.0);\n time->set_tac_slope(42.0);\n time->set_trigger_resolution_ns(42.0);\n time->set_target_resolution_ns(42.0);\n time->set_acquisition_window(1234);\n ASSERT_EQ(time->bc_clock(), 42.0);\n ASSERT_EQ(time->tac_slope(), 42.0);\n ASSERT_EQ(time->trigger_resolution_ns(), 42.0);\n ASSERT_EQ(time->target_resolution_ns(), 42.0);\n ASSERT_EQ(time->acquisition_window(), 1234);\n}\n\n\nTEST_F(SRSTimeTest, Eval) {\n ASSERT_EQ(time->target_resolution_ns(), 0.5);\n\n \/\/\/ \\todo should return 0.0 on zero input?\n MESSAGE() << \"Warning - timestamp_ns() might not be what we want!\\n\";\n ASSERT_EQ(time->timestamp_ns(0, 0, 0, no_offset, unit_slope), 1);\n\n \/\/\/ \\todo I think this should actually return 0.5 ?\n MESSAGE() << \"Warning - timestamp() might not be correct\\n\";\n ASSERT_EQ(time->timestamp(0, 0, 0, no_offset, unit_slope), 0);\n}\n\nTEST_F(SRSTimeTest, DebugString) {\n MESSAGE() << \"This is not a test, just calling the debug function\\n\";\n auto debugstr = time->debug();\n MESSAGE() << debugstr << \"\\n\";\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<commit_msg>added assert for internal_clock_period_ns()<commit_after>\/** Copyright (C) 2016, 2017 European Spallation Source ERIC *\/\n\n#include <gdgem\/srs\/SRSTime.h>\n#include <string>\n#include <test\/TestBase.h>\n#include <unistd.h>\n\nconstexpr float no_offset = 0.0;\nconstexpr float unit_slope = 1.0;\n\nclass SRSTimeTest : public TestBase {\nprotected:\n SRSTime *time;\n virtual void SetUp() { time = new SRSTime(); }\n virtual void TearDown() { delete time; }\n};\n\nTEST_F(SRSTimeTest, SettersGetters) {\n time->set_bc_clock(42.0);\n time->set_tac_slope(42.0);\n time->set_trigger_resolution_ns(42.0);\n time->set_target_resolution_ns(42.0);\n time->set_acquisition_window(1234);\n ASSERT_EQ(time->bc_clock(), 42.0);\n ASSERT_EQ(time->tac_slope(), 42.0);\n ASSERT_EQ(time->trigger_resolution_ns(), 42.0);\n ASSERT_EQ(time->target_resolution_ns(), 42.0);\n ASSERT_EQ(time->acquisition_window(), 1234);\n ASSERT_EQ(time->internal_clock_period_ns(), 25);\n}\n\n\nTEST_F(SRSTimeTest, Eval) {\n ASSERT_EQ(time->target_resolution_ns(), 0.5);\n\n \/\/\/ \\todo should return 0.0 on zero input?\n MESSAGE() << \"Warning - timestamp_ns() might not be what we want!\\n\";\n ASSERT_EQ(time->timestamp_ns(0, 0, 0, no_offset, unit_slope), 1);\n\n \/\/\/ \\todo I think this should actually return 0.5 ?\n MESSAGE() << \"Warning - timestamp() might not be correct\\n\";\n ASSERT_EQ(time->timestamp(0, 0, 0, no_offset, unit_slope), 0);\n}\n\nTEST_F(SRSTimeTest, DebugString) {\n MESSAGE() << \"This is not a test, just calling the debug function\\n\";\n auto debugstr = time->debug();\n MESSAGE() << debugstr << \"\\n\";\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"src\/file_utils.h\"\n#include \"src\/log.h\"\n#include \"src\/errors.h\"\n\n#include <wordexp.h>\n#include <fstream>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <pwd.h>\n\nLOG_DECLARE_NAMESPACE(\"file_utils\");\n\nnamespace CthunAgent {\nnamespace FileUtils {\n\n\/\/ HERE(ale): copied from Pegasus\n\nstd::string shellExpand(std::string txt) {\n \/\/ This will store the expansion outcome\n wordexp_t result;\n\n \/\/ Expand and check the success\n if (wordexp(txt.c_str(), &result, 0) != 0) {\n wordfree(&result);\n return \"\";\n }\n\n \/\/ Get the expanded text and free the memory\n std::string expanded_txt { result.we_wordv[0] };\n wordfree(&result);\n return expanded_txt;\n}\n\nbool fileExists(const std::string& file_path) {\n bool exists { false };\n if (file_path.empty()) {\n LOG_WARNING(\"file path is an empty string\");\n } else {\n std::ifstream file_stream { file_path };\n exists = file_stream.good();\n file_stream.close();\n }\n return exists;\n}\n\nvoid removeFile(const std::string& file_path) {\n if (FileUtils::fileExists(file_path)) {\n if (std::remove(file_path.c_str()) != 0) {\n throw file_error { \"failed to remove \" + file_path };\n }\n }\n}\n\nvoid streamToFile(const std::string& text,\n const std::string& file_path,\n std::ios_base::openmode mode) {\n std::ofstream ofs;\n ofs.open(file_path, mode);\n if (!ofs.is_open()) {\n throw file_error { \"failed to open \" + file_path };\n }\n ofs << text;\n}\n\nvoid writeToFile(const std::string& text, const std::string& file_path) {\n streamToFile(text, file_path, std::ofstream::out | std::ofstream::trunc);\n}\n\nbool createDirectory(const std::string& dirname) {\n boost::filesystem::path dir(dirname);\n if (boost::filesystem::create_directory(dir)) {\n return true;\n }\n\n return false;\n}\n\nstd::string readFileAsString(std::string path) {\n std::string content = \"\";\n\n if (!fileExists(path)) {\n return content;\n }\n\n std::ifstream file { path };\n std::string buffer;\n\n while (std::getline(file, buffer)) {\n content += buffer;\n content.push_back('\\n');\n }\n\n return content;\n}\n\n} \/\/ namespace FileUtils\n} \/\/ namespace CthunAgent\n<commit_msg>(CTH-125) Make streamToFile atomic<commit_after>#include \"src\/file_utils.h\"\n#include \"src\/log.h\"\n#include \"src\/errors.h\"\n\n#include <wordexp.h>\n#include <fstream>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <pwd.h>\n#include <stdio.h>\n\n\nLOG_DECLARE_NAMESPACE(\"file_utils\");\n\nnamespace CthunAgent {\nnamespace FileUtils {\n\n\/\/ HERE(ale): copied from Pegasus\n\nstd::string shellExpand(std::string txt) {\n \/\/ This will store the expansion outcome\n wordexp_t result;\n\n \/\/ Expand and check the success\n if (wordexp(txt.c_str(), &result, 0) != 0) {\n wordfree(&result);\n return \"\";\n }\n\n \/\/ Get the expanded text and free the memory\n std::string expanded_txt { result.we_wordv[0] };\n wordfree(&result);\n return expanded_txt;\n}\n\nbool fileExists(const std::string& file_path) {\n bool exists { false };\n if (file_path.empty()) {\n LOG_WARNING(\"file path is an empty string\");\n } else {\n std::ifstream file_stream { file_path };\n exists = file_stream.good();\n file_stream.close();\n }\n return exists;\n}\n\nvoid removeFile(const std::string& file_path) {\n if (FileUtils::fileExists(file_path)) {\n if (std::remove(file_path.c_str()) != 0) {\n throw file_error { \"failed to remove \" + file_path };\n }\n }\n}\n\nvoid streamToFile(const std::string& text,\n const std::string& file_path,\n std::ios_base::openmode mode) {\n std::ofstream ofs;\n std::string tmp_name = file_path + \"~\";\n ofs.open(tmp_name, mode);\n if (!ofs.is_open()) {\n throw file_error { \"failed to open \" + file_path };\n }\n ofs << text;\n ofs.close();\n rename(tmp_name.data(), file_path.data());\n}\n\nvoid writeToFile(const std::string& text, const std::string& file_path) {\n streamToFile(text, file_path, std::ofstream::out | std::ofstream::trunc);\n}\n\nbool createDirectory(const std::string& dirname) {\n boost::filesystem::path dir(dirname);\n if (boost::filesystem::create_directory(dir)) {\n return true;\n }\n\n return false;\n}\n\nstd::string readFileAsString(std::string path) {\n std::string content = \"\";\n\n if (!fileExists(path)) {\n return content;\n }\n\n std::ifstream file { path };\n std::string buffer;\n\n while (std::getline(file, buffer)) {\n content += buffer;\n content.push_back('\\n');\n }\n\n return content;\n}\n\n} \/\/ namespace FileUtils\n} \/\/ namespace CthunAgent\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n#include \"geometry\/symmetric_bilinear_form.hpp\"\n\n#include <string>\n\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/r3_element.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\nnamespace geometry {\nnamespace internal_symmetric_bilinear_form {\n\nusing quantities::Angle;\nusing quantities::ArcCos;\nusing quantities::Cos;\nusing quantities::Sqrt;\nusing quantities::si::Radian;\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>& SymmetricBilinearForm<Scalar, Frame>::\noperator+=(SymmetricBilinearForm const& right) {\n return *this = *this + right;\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>& SymmetricBilinearForm<Scalar, Frame>::\noperator-=(SymmetricBilinearForm const& right) {\n return *this = *this - right;\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>& SymmetricBilinearForm<Scalar, Frame>::\noperator*=(double const right) {\n return *this = *this * right;\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>& SymmetricBilinearForm<Scalar, Frame>::\noperator\/=(double const right) {\n return *this = *this \/ right;\n}\n\ntemplate<typename Scalar, typename Frame>\ntemplate<typename LScalar, typename RScalar>\nProduct<Scalar, Product<LScalar, RScalar>>\nSymmetricBilinearForm<Scalar, Frame>::operator()(\n Vector<LScalar, Frame> const& left,\n Vector<RScalar, Frame> const& right) const {\n return InnerProduct(left, *this * right);\n}\n\ntemplate<typename Scalar, typename Frame>\ntemplate<typename Eigenframe>\ntypename SymmetricBilinearForm<Scalar, Frame>::Eigensystem<Eigenframe>\nSymmetricBilinearForm<Scalar, Frame>::Diagonalize() const {\n R3x3Matrix<Scalar> const& A = matrix_;\n auto const I = R3x3Matrix<double>::Identity();\n\n \/\/ This algorithm follows\n \/\/ https:\/\/en.wikipedia.org\/wiki\/Eigenvalue_algorithm#3%C3%973_matrices which\n \/\/ gives closed-form formulæ for 3x3 matrices.\n Scalar const q = A.Trace() \/ 3;\n R3x3Matrix<Scalar> const A_minus_qI = A - q * I;\n Scalar const p = Sqrt((A_minus_qI * A_minus_qI).Trace() \/ 6);\n R3x3Matrix<double> const B = A_minus_qI \/ p;\n double const det_B = B.Determinant();\n Angle const θ = ArcCos(det_B * 0.5);\n double const β₀ = 2 * Cos(θ \/ 3);\n double const β₁ = 2 * Cos((θ + 2 * π * Radian) \/ 3);\n double const β₂ = 2 * Cos((θ + 4 * π * Radian) \/ 3);\n std::array<Scalar, 3> αs = {p * β₀ + q, p * β₁ + q, p * β₂ + q};\n std::sort(αs.begin(), αs.end());\n Scalar const& α₀ = αs[0];\n Scalar const& α₁ = αs[1];\n Scalar const& α₂ = αs[2];\n R3x3Matrix<Scalar> const A_minus_α₀I = A - α₀ * I;\n R3x3Matrix<Scalar> const A_minus_α₁I = A - α₁ * I;\n R3x3Matrix<Scalar> const A_minus_α₂I = A - α₂ * I;\n\n \/\/ The form in its diagonal basis.\n Scalar const zero;\n SymmetricBilinearForm<Scalar, Eigenframe> form(\n R3x3Matrix<Scalar>({ α₀, zero, zero},\n {zero, α₁, zero},\n {zero, zero, α₂}));\n\n \/\/ Use the Cayley-Hamilton theorem to efficiently find the eigenvectors. The\n \/\/ m matrices contain, in columns, eigenvector for the corresponding α.\n \/\/ However it's possible for a column to be identically 0. To deal with this\n \/\/ the call to PickEigenvector extracts the column with the largest norm.\n auto const m₀ = A_minus_α₁I * A_minus_α₂I;\n auto const m₁ = A_minus_α₂I * A_minus_α₀I;\n auto const m₂ = A_minus_α₀I * A_minus_α₁I;\n auto const v₀ = PickEigenvector(m₀);\n auto const v₁ = PickEigenvector(m₁);\n\n \/\/ The vectors (v₀, v₁, v₂) forms an orthonormal basis. Make sure that it is\n \/\/ direct.\n auto v₂ = PickEigenvector(m₂);\n if (R3x3Matrix(v₀, v₁, v₂).Determinant() < 0) {\n v₂ = -v₂;\n }\n Rotation<Frame, Eigenframe> const rotation{\n Vector<double, Frame>(v₀),\n Vector<double, Frame>(v₁),\n Bivector<double, Frame>(v₂)}; \/\/ This bivector is a bit dodgy.\n return {form, rotation};\n}\n\ntemplate<typename Scalar, typename Frame>\nvoid SymmetricBilinearForm<Scalar, Frame>::WriteToMessage(\n not_null<serialization::SymmetricBilinearForm*> message) const {\n Frame::WriteToMessage(message->mutable_frame());\n matrix_.WriteToMessage(message->mutable_matrix());\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>\nSymmetricBilinearForm<Scalar, Frame>::ReadFromMessage(\n serialization::SymmetricBilinearForm const& message) {\n Frame::ReadFromMessage(message.frame());\n return SymmetricBilinearForm(\n R3x3Matrix<Scalar>::ReadFromMessage(message.matrix()));\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>::SymmetricBilinearForm(\n R3x3Matrix<Scalar> const& matrix)\n : matrix_(matrix) {\n DCHECK_EQ(matrix_(0, 1), matrix_(1, 0));\n DCHECK_EQ(matrix_(0, 2), matrix_(2, 0));\n DCHECK_EQ(matrix_(1, 2), matrix_(2, 1));\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>::SymmetricBilinearForm(\n R3x3Matrix<Scalar>&& matrix)\n : matrix_(std::move(matrix)) {\n DCHECK_EQ(matrix_(0, 1), matrix_(1, 0));\n DCHECK_EQ(matrix_(0, 2), matrix_(2, 0));\n DCHECK_EQ(matrix_(1, 2), matrix_(2, 1));\n}\n\ntemplate<typename Scalar, typename Frame>\ntemplate<typename S>\nR3Element<double> SymmetricBilinearForm<Scalar, Frame>::PickEigenvector(\n R3x3Matrix<S> const& matrix) {\n static R3Element<double> const e₀{1, 0, 0};\n static R3Element<double> const e₁{0, 1, 0};\n static R3Element<double> const e₂{0, 0, 1};\n std::array<R3Element<S>, 3> vs = {matrix * e₀, matrix * e₁, matrix * e₂};\n std::sort(vs.begin(),\n vs.end(),\n [](R3Element<S> const& left, R3Element<S> const& right) {\n return left.Norm²() < right.Norm²();\n });\n return NormalizeOrZero(vs.back());\n}\n\ntemplate<typename Frame>\nSymmetricBilinearForm<double, Frame> const& InnerProductForm() {\n static auto const identity =\n SymmetricBilinearForm<double, Frame>(R3x3Matrix<double>::Identity());\n return identity;\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator+(\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator-(\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(-right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator+(\n SymmetricBilinearForm<Scalar, Frame> const& left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(left.matrix_ + right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator-(\n SymmetricBilinearForm<Scalar, Frame> const& left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(left.matrix_ - right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator*(\n double const left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(left * right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator*(\n SymmetricBilinearForm<Scalar, Frame> const& left,\n double const right) {\n return SymmetricBilinearForm<Scalar, Frame>(left.matrix_ * right);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator\/(\n SymmetricBilinearForm<Scalar, Frame> const& left,\n double const right) {\n return SymmetricBilinearForm<Scalar, Frame>(left.matrix_ \/ right);\n}\n\ntemplate<typename LScalar, typename RScalar, typename Frame>\nVector<Product<LScalar, RScalar>, Frame> operator*(\n SymmetricBilinearForm<LScalar, Frame> const& left,\n Vector<RScalar, Frame> const& right) {\n return Vector<Product<LScalar, RScalar>, Frame>(left.matrix_ *\n right.coordinates());\n}\n\ntemplate<typename LScalar, typename RScalar, typename Frame>\nVector<Product<LScalar, RScalar>, Frame> operator*(\n Vector<LScalar, Frame> const& left,\n SymmetricBilinearForm<RScalar, Frame> const& right) {\n return Vector<Product<LScalar, RScalar>, Frame>(left.coordinates() *\n right.matrix_);\n}\n\ntemplate<typename LScalar, typename RScalar, typename Frame>\nSymmetricBilinearForm<Product<LScalar, RScalar>, Frame> SymmetricProduct(\n Vector<LScalar, Frame> const& left,\n Vector<RScalar, Frame> const& right) {\n return SymmetricBilinearForm<Product<LScalar, RScalar>, Frame>(\n 0.5 * (KroneckerProduct(left.coordinates(), right.coordinates()) +\n KroneckerProduct(right.coordinates(), left.coordinates())));\n}\n\ntemplate<typename LScalar, typename RScalar, typename Frame>\nBivector<Product<LScalar, RScalar>, Frame> Anticommutator(\n SymmetricBilinearForm<LScalar, Frame> const& form,\n Bivector<RScalar, Frame> const& bivector) {\n return Bivector<Product<LScalar, RScalar>, Frame>(\n form.matrix_.Trace() * bivector.coordinates() -\n form.matrix_ * bivector.coordinates());\n}\n\ntemplate<typename Scalar, typename Frame>\nbool operator==(SymmetricBilinearForm<Scalar, Frame> const& left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return left.matrix_ == right.matrix_;\n}\n\ntemplate<typename Scalar, typename Frame>\nbool operator!=(SymmetricBilinearForm<Scalar, Frame> const& left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return left.matrix_ != right.matrix_;\n}\n\ntemplate<typename Scalar, typename Frame>\nstd::string DebugString(SymmetricBilinearForm<Scalar, Frame> const& form) {\n return DebugString(form.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nstd::ostream& operator<<(std::ostream& out,\n SymmetricBilinearForm<Scalar, Frame> const& form) {\n out << form.matrix_;\n return out;\n}\n\n} \/\/ namespace internal_symmetric_bilinear_form\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<commit_msg>Typo.<commit_after>\n#pragma once\n\n#include \"geometry\/symmetric_bilinear_form.hpp\"\n\n#include <string>\n\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/r3_element.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\nnamespace geometry {\nnamespace internal_symmetric_bilinear_form {\n\nusing quantities::Angle;\nusing quantities::ArcCos;\nusing quantities::Cos;\nusing quantities::Sqrt;\nusing quantities::si::Radian;\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>& SymmetricBilinearForm<Scalar, Frame>::\noperator+=(SymmetricBilinearForm const& right) {\n return *this = *this + right;\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>& SymmetricBilinearForm<Scalar, Frame>::\noperator-=(SymmetricBilinearForm const& right) {\n return *this = *this - right;\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>& SymmetricBilinearForm<Scalar, Frame>::\noperator*=(double const right) {\n return *this = *this * right;\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>& SymmetricBilinearForm<Scalar, Frame>::\noperator\/=(double const right) {\n return *this = *this \/ right;\n}\n\ntemplate<typename Scalar, typename Frame>\ntemplate<typename LScalar, typename RScalar>\nProduct<Scalar, Product<LScalar, RScalar>>\nSymmetricBilinearForm<Scalar, Frame>::operator()(\n Vector<LScalar, Frame> const& left,\n Vector<RScalar, Frame> const& right) const {\n return InnerProduct(left, *this * right);\n}\n\ntemplate<typename Scalar, typename Frame>\ntemplate<typename Eigenframe>\ntypename SymmetricBilinearForm<Scalar, Frame>::Eigensystem<Eigenframe>\nSymmetricBilinearForm<Scalar, Frame>::Diagonalize() const {\n R3x3Matrix<Scalar> const& A = matrix_;\n auto const I = R3x3Matrix<double>::Identity();\n\n \/\/ This algorithm follows\n \/\/ https:\/\/en.wikipedia.org\/wiki\/Eigenvalue_algorithm#3%C3%973_matrices which\n \/\/ gives closed-form formulæ for 3x3 matrices.\n Scalar const q = A.Trace() \/ 3;\n R3x3Matrix<Scalar> const A_minus_qI = A - q * I;\n Scalar const p = Sqrt((A_minus_qI * A_minus_qI).Trace() \/ 6);\n R3x3Matrix<double> const B = A_minus_qI \/ p;\n double const det_B = B.Determinant();\n Angle const θ = ArcCos(det_B * 0.5);\n double const β₀ = 2 * Cos(θ \/ 3);\n double const β₁ = 2 * Cos((θ + 2 * π * Radian) \/ 3);\n double const β₂ = 2 * Cos((θ + 4 * π * Radian) \/ 3);\n std::array<Scalar, 3> αs = {p * β₀ + q, p * β₁ + q, p * β₂ + q};\n std::sort(αs.begin(), αs.end());\n Scalar const& α₀ = αs[0];\n Scalar const& α₁ = αs[1];\n Scalar const& α₂ = αs[2];\n R3x3Matrix<Scalar> const A_minus_α₀I = A - α₀ * I;\n R3x3Matrix<Scalar> const A_minus_α₁I = A - α₁ * I;\n R3x3Matrix<Scalar> const A_minus_α₂I = A - α₂ * I;\n\n \/\/ The form in its diagonal basis.\n Scalar const zero;\n SymmetricBilinearForm<Scalar, Eigenframe> form(\n R3x3Matrix<Scalar>({ α₀, zero, zero},\n {zero, α₁, zero},\n {zero, zero, α₂}));\n\n \/\/ Use the Cayley-Hamilton theorem to efficiently find the eigenvectors. The\n \/\/ m matrices contain, in columns, eigenvectors for the corresponding α.\n \/\/ However it's possible for a column to be identically 0. To deal with this\n \/\/ the call to PickEigenvector extracts the column with the largest norm.\n auto const m₀ = A_minus_α₁I * A_minus_α₂I;\n auto const m₁ = A_minus_α₂I * A_minus_α₀I;\n auto const m₂ = A_minus_α₀I * A_minus_α₁I;\n auto const v₀ = PickEigenvector(m₀);\n auto const v₁ = PickEigenvector(m₁);\n\n \/\/ The vectors (v₀, v₁, v₂) forms an orthonormal basis. Make sure that it is\n \/\/ direct.\n auto v₂ = PickEigenvector(m₂);\n if (R3x3Matrix(v₀, v₁, v₂).Determinant() < 0) {\n v₂ = -v₂;\n }\n Rotation<Frame, Eigenframe> const rotation{\n Vector<double, Frame>(v₀),\n Vector<double, Frame>(v₁),\n Bivector<double, Frame>(v₂)}; \/\/ This bivector is a bit dodgy.\n return {form, rotation};\n}\n\ntemplate<typename Scalar, typename Frame>\nvoid SymmetricBilinearForm<Scalar, Frame>::WriteToMessage(\n not_null<serialization::SymmetricBilinearForm*> message) const {\n Frame::WriteToMessage(message->mutable_frame());\n matrix_.WriteToMessage(message->mutable_matrix());\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>\nSymmetricBilinearForm<Scalar, Frame>::ReadFromMessage(\n serialization::SymmetricBilinearForm const& message) {\n Frame::ReadFromMessage(message.frame());\n return SymmetricBilinearForm(\n R3x3Matrix<Scalar>::ReadFromMessage(message.matrix()));\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>::SymmetricBilinearForm(\n R3x3Matrix<Scalar> const& matrix)\n : matrix_(matrix) {\n DCHECK_EQ(matrix_(0, 1), matrix_(1, 0));\n DCHECK_EQ(matrix_(0, 2), matrix_(2, 0));\n DCHECK_EQ(matrix_(1, 2), matrix_(2, 1));\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame>::SymmetricBilinearForm(\n R3x3Matrix<Scalar>&& matrix)\n : matrix_(std::move(matrix)) {\n DCHECK_EQ(matrix_(0, 1), matrix_(1, 0));\n DCHECK_EQ(matrix_(0, 2), matrix_(2, 0));\n DCHECK_EQ(matrix_(1, 2), matrix_(2, 1));\n}\n\ntemplate<typename Scalar, typename Frame>\ntemplate<typename S>\nR3Element<double> SymmetricBilinearForm<Scalar, Frame>::PickEigenvector(\n R3x3Matrix<S> const& matrix) {\n static R3Element<double> const e₀{1, 0, 0};\n static R3Element<double> const e₁{0, 1, 0};\n static R3Element<double> const e₂{0, 0, 1};\n std::array<R3Element<S>, 3> vs = {matrix * e₀, matrix * e₁, matrix * e₂};\n std::sort(vs.begin(),\n vs.end(),\n [](R3Element<S> const& left, R3Element<S> const& right) {\n return left.Norm²() < right.Norm²();\n });\n return NormalizeOrZero(vs.back());\n}\n\ntemplate<typename Frame>\nSymmetricBilinearForm<double, Frame> const& InnerProductForm() {\n static auto const identity =\n SymmetricBilinearForm<double, Frame>(R3x3Matrix<double>::Identity());\n return identity;\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator+(\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator-(\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(-right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator+(\n SymmetricBilinearForm<Scalar, Frame> const& left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(left.matrix_ + right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator-(\n SymmetricBilinearForm<Scalar, Frame> const& left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(left.matrix_ - right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator*(\n double const left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return SymmetricBilinearForm<Scalar, Frame>(left * right.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator*(\n SymmetricBilinearForm<Scalar, Frame> const& left,\n double const right) {\n return SymmetricBilinearForm<Scalar, Frame>(left.matrix_ * right);\n}\n\ntemplate<typename Scalar, typename Frame>\nSymmetricBilinearForm<Scalar, Frame> operator\/(\n SymmetricBilinearForm<Scalar, Frame> const& left,\n double const right) {\n return SymmetricBilinearForm<Scalar, Frame>(left.matrix_ \/ right);\n}\n\ntemplate<typename LScalar, typename RScalar, typename Frame>\nVector<Product<LScalar, RScalar>, Frame> operator*(\n SymmetricBilinearForm<LScalar, Frame> const& left,\n Vector<RScalar, Frame> const& right) {\n return Vector<Product<LScalar, RScalar>, Frame>(left.matrix_ *\n right.coordinates());\n}\n\ntemplate<typename LScalar, typename RScalar, typename Frame>\nVector<Product<LScalar, RScalar>, Frame> operator*(\n Vector<LScalar, Frame> const& left,\n SymmetricBilinearForm<RScalar, Frame> const& right) {\n return Vector<Product<LScalar, RScalar>, Frame>(left.coordinates() *\n right.matrix_);\n}\n\ntemplate<typename LScalar, typename RScalar, typename Frame>\nSymmetricBilinearForm<Product<LScalar, RScalar>, Frame> SymmetricProduct(\n Vector<LScalar, Frame> const& left,\n Vector<RScalar, Frame> const& right) {\n return SymmetricBilinearForm<Product<LScalar, RScalar>, Frame>(\n 0.5 * (KroneckerProduct(left.coordinates(), right.coordinates()) +\n KroneckerProduct(right.coordinates(), left.coordinates())));\n}\n\ntemplate<typename LScalar, typename RScalar, typename Frame>\nBivector<Product<LScalar, RScalar>, Frame> Anticommutator(\n SymmetricBilinearForm<LScalar, Frame> const& form,\n Bivector<RScalar, Frame> const& bivector) {\n return Bivector<Product<LScalar, RScalar>, Frame>(\n form.matrix_.Trace() * bivector.coordinates() -\n form.matrix_ * bivector.coordinates());\n}\n\ntemplate<typename Scalar, typename Frame>\nbool operator==(SymmetricBilinearForm<Scalar, Frame> const& left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return left.matrix_ == right.matrix_;\n}\n\ntemplate<typename Scalar, typename Frame>\nbool operator!=(SymmetricBilinearForm<Scalar, Frame> const& left,\n SymmetricBilinearForm<Scalar, Frame> const& right) {\n return left.matrix_ != right.matrix_;\n}\n\ntemplate<typename Scalar, typename Frame>\nstd::string DebugString(SymmetricBilinearForm<Scalar, Frame> const& form) {\n return DebugString(form.matrix_);\n}\n\ntemplate<typename Scalar, typename Frame>\nstd::ostream& operator<<(std::ostream& out,\n SymmetricBilinearForm<Scalar, Frame> const& form) {\n out << form.matrix_;\n return out;\n}\n\n} \/\/ namespace internal_symmetric_bilinear_form\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>#include \"ossimCurlHttpRequest.h\"\n\nossimRefPtr<ossimWebResponse> ossimCurlHttpRequest::getResponse()\n{\n ossimRefPtr<ossimWebResponse> response;\n ossimString protocol = getUrl().getProtocol();\n if(!supportsProtocol(protocol))\n {\n return 0;\n }\n curl_easy_reset(m_curl);\n switch (m_methodType) \n {\n case ossimHttpRequest::HTTP_METHOD_GET:\n {\n ossimCurlHttpResponse* curlResponse = new ossimCurlHttpResponse();\n response = curlResponse;\n \n curl_easy_setopt(m_curl, CURLOPT_HEADERFUNCTION, curlWriteResponseHeader);\n curl_easy_setopt(m_curl, CURLOPT_HEADERDATA, (void*)response.get());\n curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, curlWriteResponseBody);\n curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, (void*)response.get());\n curl_easy_setopt(m_curl, CURLOPT_HEADER, 0); \n curl_easy_setopt(m_curl, CURLOPT_NOBODY, 0); \n \/\/curl_easy_setopt(m_curl, CURLOPT_CONNECT_ONLY, 1);\n \/\/ ossimKeywordlist::KeywordMap& headerMap = m_headerOptions.getMap();\n \/\/ struct curl_slist *headers=0; \/* init to NULL is important *\/\n ossimString range = m_headerOptions.find(\"Range\");\n range=range.substitute(\"bytes=\", \"\");\n curl_easy_setopt(m_curl, CURLOPT_RANGE, range.c_str());\n \/\/ ossimKeywordlist::KeywordMap::iterator iter = headerMap.begin();\n \/\/ while(iter != headerMap.end())\n \/\/ {\n \/\/ std::cout << ((*iter).first + \":\"+(*iter).second).c_str() << std::endl;\n \/\/ headers = curl_slist_append(headers, ((*iter).first + \":\"+(*iter).second).c_str());\n \/\/ ++iter;\n \/\/ }\n ossimString urlString = getUrl().toString();\n curl_easy_setopt(m_curl, CURLOPT_URL, urlString.c_str());\n \n \n if(protocol == \"https\")\n {\n curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);\/\/);\n curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 0L);\n }\n \n \n int rc = curl_easy_perform(m_curl);\n \n if(rc == CURLE_SSL_CONNECT_ERROR)\n {\n \/\/ try default if an error for SSL connect ocurred\n curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_SSLv3);\n rc = curl_easy_perform(m_curl);\n }\n bool result = (rc < 1);\n if(result)\n {\n curlResponse->convertHeaderStreamToKeywordlist();\n }\n else\n {\n m_lastError = curl_easy_strerror((CURLcode)rc);\n \/\/std::cout << curl_easy_strerror((CURLcode)rc) << std::endl;\n response = 0;\n }\n break;\n }\n \n default:\n break;\n }\n \n return response;\n}\n\nbool ossimCurlHttpRequest::supportsProtocol(const ossimString& protocol)const\n{\n bool result = false;\n if(protocol == \"http\")\n {\n result = true;\n }\n else if(protocol == \"https\")\n {\n curl_version_info_data * vinfo = curl_version_info( CURLVERSION_NOW ); \n if( vinfo->features & CURL_VERSION_SSL ) \n { \n result = true;\n } \n }\n return result;\n}\n\nint ossimCurlHttpRequest::curlWriteResponseBody(void *buffer, size_t size, size_t nmemb, void *stream)\n{\n ossimHttpResponse* cStream = static_cast<ossimHttpResponse*>(stream);\n\n if(cStream)\n {\n cStream->bodyStream().write((char*)buffer, nmemb*size);\n return nmemb*size;\n }\n \n return 0;\n}\n\nint ossimCurlHttpRequest::curlWriteResponseHeader(void *buffer, size_t size, size_t nmemb, void *stream)\n{\n ossimHttpResponse* cStream = static_cast<ossimHttpResponse*>(stream);\n if(cStream)\n {\n cStream->headerStream().write((char*)buffer, nmemb*size);\n return nmemb*size;\n }\n \n return 0;\n}\n\nossim_int64 ossimCurlHttpRequest::getContentLength()const\n{\n double contentLength=-1;\n curl_easy_reset(m_curl);\n\n ossimString urlString = getUrl().toString();\n ossimString protocol = getUrl().getProtocol();\n ossimRefPtr<ossimCurlHttpResponse> response = new ossimCurlHttpResponse();\n \n curl_easy_setopt(m_curl, CURLOPT_HEADERFUNCTION, curlWriteResponseHeader);\n curl_easy_setopt(m_curl, CURLOPT_HEADERDATA, (void*)response.get());\n curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, curlWriteResponseBody);\n curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, (void*)response.get());\n curl_easy_setopt(m_curl, CURLOPT_HEADER, 0); \n curl_easy_setopt(m_curl, CURLOPT_NOBODY, 1); \n curl_easy_setopt(m_curl, CURLOPT_RANGE, \"\");\n\n const ossimKeywordlist::KeywordMap& headerMap = m_headerOptions.getMap();\n struct curl_slist *headers=0; \/* init to NULL is important *\/\n \n ossimKeywordlist::KeywordMap::const_iterator iter = headerMap.begin();\n while(iter != headerMap.end())\n {\n\/\/ std::cout << ((*iter).first + \":\"+(*iter).second).c_str() << std::endl;\n headers = curl_slist_append(headers, ((*iter).first + \":\"+(*iter).second).c_str());\n ++iter;\n }\n curl_easy_setopt(m_curl, CURLOPT_URL, urlString.c_str());\n if(protocol == \"https\")\n {\n curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);\/\/);\n curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 0L);\n }\n int rc = curl_easy_perform(m_curl);\n \n \/\/rc = curl_easy_getinfo(m_curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &contentLength);\n if(rc == CURLE_SSL_CONNECT_ERROR)\n {\n \/\/ try default if an error for SSL connect ocurred\n curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_SSLv3);\n rc = curl_easy_perform(m_curl); \n }\n bool result = (rc < 1);\n if(result)\n {\n response->convertHeaderStreamToKeywordlist();\n rc = curl_easy_getinfo(m_curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &contentLength);\n \/\/if(rc>=1) contentLength = -1;\n \/\/ response->convertHeaderStreamToKeywordlist();\n \/\/std::cout << response->headerKwl() << \"\\n\";\n }\n else\n {\n m_lastError = curl_easy_strerror((CURLcode)rc);\n \/\/std::cout << curl_easy_strerror((CURLcode)rc) << std::endl;\n }\n\n return static_cast<ossim_int64> (contentLength);\n}\n\n<commit_msg>Added clearLastError<commit_after>#include \"ossimCurlHttpRequest.h\"\n\nossimRefPtr<ossimWebResponse> ossimCurlHttpRequest::getResponse()\n{\n ossimRefPtr<ossimWebResponse> response;\n ossimString protocol = getUrl().getProtocol();\n if(!supportsProtocol(protocol))\n {\n return 0;\n }\n curl_easy_reset(m_curl);\n clearLastError();\n switch (m_methodType) \n {\n case ossimHttpRequest::HTTP_METHOD_GET:\n {\n ossimCurlHttpResponse* curlResponse = new ossimCurlHttpResponse();\n response = curlResponse;\n \n curl_easy_setopt(m_curl, CURLOPT_HEADERFUNCTION, curlWriteResponseHeader);\n curl_easy_setopt(m_curl, CURLOPT_HEADERDATA, (void*)response.get());\n curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, curlWriteResponseBody);\n curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, (void*)response.get());\n curl_easy_setopt(m_curl, CURLOPT_HEADER, 0); \n curl_easy_setopt(m_curl, CURLOPT_NOBODY, 0); \n \/\/curl_easy_setopt(m_curl, CURLOPT_CONNECT_ONLY, 1);\n \/\/ ossimKeywordlist::KeywordMap& headerMap = m_headerOptions.getMap();\n \/\/ struct curl_slist *headers=0; \/* init to NULL is important *\/\n ossimString range = m_headerOptions.find(\"Range\");\n range=range.substitute(\"bytes=\", \"\");\n curl_easy_setopt(m_curl, CURLOPT_RANGE, range.c_str());\n \/\/ ossimKeywordlist::KeywordMap::iterator iter = headerMap.begin();\n \/\/ while(iter != headerMap.end())\n \/\/ {\n \/\/ std::cout << ((*iter).first + \":\"+(*iter).second).c_str() << std::endl;\n \/\/ headers = curl_slist_append(headers, ((*iter).first + \":\"+(*iter).second).c_str());\n \/\/ ++iter;\n \/\/ }\n ossimString urlString = getUrl().toString();\n curl_easy_setopt(m_curl, CURLOPT_URL, urlString.c_str());\n \n \n if(protocol == \"https\")\n {\n curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);\/\/);\n curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 0L);\n }\n \n \n int rc = curl_easy_perform(m_curl);\n \n if(rc == CURLE_SSL_CONNECT_ERROR)\n {\n \/\/ try default if an error for SSL connect ocurred\n curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_SSLv3);\n rc = curl_easy_perform(m_curl);\n }\n bool result = (rc < 1);\n if(result)\n {\n curlResponse->convertHeaderStreamToKeywordlist();\n }\n else\n {\n m_lastError = curl_easy_strerror((CURLcode)rc);\n \/\/std::cout << curl_easy_strerror((CURLcode)rc) << std::endl;\n response = 0;\n }\n break;\n }\n \n default:\n break;\n }\n \n return response;\n}\n\nbool ossimCurlHttpRequest::supportsProtocol(const ossimString& protocol)const\n{\n bool result = false;\n if(protocol == \"http\")\n {\n result = true;\n }\n else if(protocol == \"https\")\n {\n curl_version_info_data * vinfo = curl_version_info( CURLVERSION_NOW ); \n if( vinfo->features & CURL_VERSION_SSL ) \n { \n result = true;\n } \n }\n return result;\n}\n\nint ossimCurlHttpRequest::curlWriteResponseBody(void *buffer, size_t size, size_t nmemb, void *stream)\n{\n ossimHttpResponse* cStream = static_cast<ossimHttpResponse*>(stream);\n\n if(cStream)\n {\n cStream->bodyStream().write((char*)buffer, nmemb*size);\n return nmemb*size;\n }\n \n return 0;\n}\n\nint ossimCurlHttpRequest::curlWriteResponseHeader(void *buffer, size_t size, size_t nmemb, void *stream)\n{\n ossimHttpResponse* cStream = static_cast<ossimHttpResponse*>(stream);\n if(cStream)\n {\n cStream->headerStream().write((char*)buffer, nmemb*size);\n return nmemb*size;\n }\n \n return 0;\n}\n\nossim_int64 ossimCurlHttpRequest::getContentLength()const\n{\n double contentLength=-1;\n curl_easy_reset(m_curl);\n clearLastError();\n ossimString urlString = getUrl().toString();\n ossimString protocol = getUrl().getProtocol();\n ossimRefPtr<ossimCurlHttpResponse> response = new ossimCurlHttpResponse();\n \n curl_easy_setopt(m_curl, CURLOPT_HEADERFUNCTION, curlWriteResponseHeader);\n curl_easy_setopt(m_curl, CURLOPT_HEADERDATA, (void*)response.get());\n curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, curlWriteResponseBody);\n curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, (void*)response.get());\n curl_easy_setopt(m_curl, CURLOPT_HEADER, 0); \n curl_easy_setopt(m_curl, CURLOPT_NOBODY, 1); \n curl_easy_setopt(m_curl, CURLOPT_RANGE, \"\");\n\n const ossimKeywordlist::KeywordMap& headerMap = m_headerOptions.getMap();\n struct curl_slist *headers=0; \/* init to NULL is important *\/\n \n ossimKeywordlist::KeywordMap::const_iterator iter = headerMap.begin();\n while(iter != headerMap.end())\n {\n\/\/ std::cout << ((*iter).first + \":\"+(*iter).second).c_str() << std::endl;\n headers = curl_slist_append(headers, ((*iter).first + \":\"+(*iter).second).c_str());\n ++iter;\n }\n curl_easy_setopt(m_curl, CURLOPT_URL, urlString.c_str());\n if(protocol == \"https\")\n {\n curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);\/\/);\n curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 0L);\n }\n int rc = curl_easy_perform(m_curl);\n \n \/\/rc = curl_easy_getinfo(m_curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &contentLength);\n if(rc == CURLE_SSL_CONNECT_ERROR)\n {\n \/\/ try default if an error for SSL connect ocurred\n curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_SSLv3);\n rc = curl_easy_perform(m_curl); \n }\n bool result = (rc < 1);\n if(result)\n {\n response->convertHeaderStreamToKeywordlist();\n rc = curl_easy_getinfo(m_curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &contentLength);\n \/\/if(rc>=1) contentLength = -1;\n \/\/ response->convertHeaderStreamToKeywordlist();\n \/\/std::cout << response->headerKwl() << \"\\n\";\n }\n else\n {\n m_lastError = curl_easy_strerror((CURLcode)rc);\n \/\/std::cout << curl_easy_strerror((CURLcode)rc) << std::endl;\n }\n\n return static_cast<ossim_int64> (contentLength);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ bslh_siphashalgorithm.cpp -*-C++-*-\n#include <bslh_siphashalgorithm.h>\n\n#include <bsls_ident.h>\nBSLS_IDENT(\"$Id$ $CSID$\")\n\n#include <bsls_assert.h>\n#include <bsls_types.h>\n#include <bsls_platform.h>\n\n#include <algorithm>\n#include <stddef.h> \/\/ for 'size_t'\n#include <string.h>\n\n\/\/\/Changes\n\/\/\/-------\n\/\/ The third party code begins with the \"siphash.h\" header below, and continues\n\/\/ until the Bloomberg LP copyright banner below. Changes made to the original\n\/\/ code include:\n\/\/\n\/\/: 1 Adding BloombergLP and bslh namespaces\n\/\/:\n\/\/: 2 Renaming 'siphash' to 'SipHashAlgorithm'\n\/\/:\n\/\/: 3 White space to meet BDE standards.\n\/\/:\n\/\/: 4 Added initializer list to handle class member initializers removed from\n\/\/: the header\n\/\/:\n\/\/: 5 Added 'computeHash()' to handle explicit conversion removed from header.\n\/\/:\n\/\/: 6 Changed the constructor to accept a 'const char *'\n\/\/:\n\/\/: 7 Changed endianness check to use BDE-defined check\n\/\/:\n\/\/: 8 Removed unnamed namespace in favour of 'static'\n\/\/:\n\/\/: 9 Added function contracts\n\/\/:\n\/\/: 10 Added asserts to check passed pointers\n\/\/:\n\/\/: 11 Re-wrote unaligned reads to buffer data and then perform aligned reads\n\/\/: to prevent runtime errors in opt builds on Sun machines.\n\/\/\n\/\/\/Third Party Doc\n\/\/\/---------------\n\/\/------------------------------- siphash.h -----------------------------------\n\/\/\n\/\/ This software is in the public domain. The only restriction on its use is\n\/\/ that no one can remove it from the public domain by claiming ownership of\n\/\/ it, including the original authors.\n\/\/\n\/\/ There is no warranty of correctness on the software contained herein. Use\n\/\/ at your own risk.\n\/\/\n\/\/ Derived from:\n\/\/\n\/\/ SipHash reference C implementation\n\/\/\n\/\/ Written in 2012 by Jean-Philippe Aumasson <jeanphilippe.aumasson@gmail.com>\n\/\/ Daniel J. Bernstein <djb@cr.yp.to>\n\/\/\n\/\/ To the extent possible under law, the author(s) have dedicated all copyright\n\/\/ and related and neighboring rights to this software to the public domain\n\/\/ worldwide. This software is distributed without any warranty.\n\/\/\n\/\/ You should have received a copy of the CC0 Public Domain Dedication along\n\/\/ with this software. If not, see\n\/\/ <http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/>.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n\nnamespace BloombergLP {\n\nnamespace bslh {\n\ntypedef bsls::Types::Uint64 u64;\ntypedef unsigned int u32;\ntypedef unsigned char u8;\n\ninline\nstatic u64 rotl(u64 x, u64 b)\n \/\/ Return the bits of the specified 'x' rotated to the left by the\n \/\/ specified 'b' number of bits. Bits that are rotated off the end are\n \/\/ wrapped around to the beginning.\n{\n return (x << b) | (x >> (64 - b));\n}\n\ninline\nstatic void sipround(u64& v0, u64& v1, u64& v2, u64& v3)\n \/\/ Mix the specified 'v0', 'v1', 'v2', and 'v3' in a \"Sip Round\" as\n \/\/ described in the SipHash algorithm\n{\n v0 += v1;\n v1 = rotl(v1, 13);\n v1 ^= v0;\n v0 = rotl(v0, 32);\n v2 += v3;\n v3 = rotl(v3, 16);\n v3 ^= v2;\n v0 += v3;\n v3 = rotl(v3, 21);\n v3 ^= v0;\n v2 += v1;\n v1 = rotl(v1, 17);\n v1 ^= v2;\n v2 = rotl(v2, 32);\n}\n\ninline\nstatic u64 u8to64_le(const u8* p)\n \/\/ Return the 64-bit integer representation of the specified 'p' taking\n \/\/ into account endianness. Undefined unless 'p' points to at least one\n \/\/ byte of initialized memory.\n{\n BSLS_ASSERT(p);\n\n union { char bytes[8]; u64 ret; };\n#if defined(BSLS_PLATFORM_CPU_X86) || defined(BSLS_PLATFORM_CPU_X86_64)\n ret = *reinterpret_cast<const u64 *>(p); \/\/ Ignore alignment.\n#elif defined(BSLS_PLATFORM_IS_LITTLE_ENDIAN)\n memcpy(bytes, p, sizeof(bytes));\n#elif defined(BSLS_PLATFORM_CMP_SUN) \/\/ SUNPRO optimizes better this way?\n bytes[0] = p[7];\n bytes[1] = p[6];\n bytes[2] = p[5];\n bytes[3] = p[4];\n bytes[4] = p[3];\n bytes[5] = p[2];\n bytes[6] = p[1];\n bytes[7] = p[0];\n#else\n ret = u64(p[7]) << 56 | u64(p[6]) << 48 |\n u64(p[5]) << 40 | u64(p[4]) << 32 |\n u64(p[3]) << 24 | u64(p[2]) << 16 |\n u64(p[1]) << 8 | u64(p[0]);\n#endif\n return ret;\n}\n\n\nSipHashAlgorithm::SipHashAlgorithm(const char *seed)\n: d_v0(0x736f6d6570736575ULL)\n, d_v1(0x646f72616e646f6dULL)\n, d_v2(0x6c7967656e657261ULL)\n, d_v3(0x7465646279746573ULL)\n, d_bufSize(0)\n, d_totalLength(0)\n{\n BSLS_ASSERT(seed);\n\n#if defined(BSLS_PLATFORM_CPU_X86) || defined(BSLS_PLATFORM_CPU_X86_64)\n const u64 *aligned = reinterpret_cast<const u64 *>(seed);\n#else\n union { char bytes[16]; u64 aligned[2]; };\n memcpy(&bytes, seed, sizeof(bytes));\n#endif\n d_v0 ^= aligned[0];\n d_v1 ^= aligned[1];\n d_v2 ^= aligned[0];\n d_v3 ^= aligned[1];\n}\n\nvoid\nSipHashAlgorithm::operator()(const void *data, size_t numBytes)\n{\n BSLS_ASSERT(data);\n\n u8 const* in = static_cast<const u8*>(data);\n\n d_totalLength += numBytes;\n if (d_bufSize + numBytes < 8)\n {\n std::copy(in, in + numBytes, d_buf + d_bufSize);\n d_bufSize += numBytes;\n return; \/\/ RETURN\n }\n if (d_bufSize > 0)\n {\n size_t t = 8 - d_bufSize;\n std::copy(in, in+t, d_buf + d_bufSize);\n u64 m = u8to64_le( d_buf );\n d_v3 ^= m;\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n d_v0 ^= m;\n in += t;\n numBytes -= t;\n }\n d_bufSize = numBytes & 7;\n u8 const* const end = in + (numBytes - d_bufSize);\n for ( ; in != end; in += 8 )\n {\n u64 m = u8to64_le( in );\n d_v3 ^= m;\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n d_v0 ^= m;\n }\n std::copy(end, end + d_bufSize, d_buf);\n}\n\nSipHashAlgorithm::result_type SipHashAlgorithm::computeHash()\n{\n result_type b = static_cast<u64>(d_totalLength) << 56;\n switch(d_bufSize)\n {\n case 7:\n b |= static_cast<u64>(d_buf[6]) << 48;\n case 6:\n b |= static_cast<u64>(d_buf[5]) << 40;\n case 5:\n b |= static_cast<u64>(d_buf[4]) << 32;\n case 4:\n b |= static_cast<u64>(d_buf[3]) << 24;\n case 3:\n b |= static_cast<u64>(d_buf[2]) << 16;\n case 2:\n b |= static_cast<u64>(d_buf[1]) << 8;\n case 1:\n b |= static_cast<u64>(d_buf[0]);\n case 0:\n break;\n }\n d_v3 ^= b;\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n d_v0 ^= b;\n d_v2 ^= 0xff;\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n b = d_v0 ^ d_v1 ^ d_v2 ^ d_v3;\n return b;\n}\n\n} \/\/ close package namespace\n\n} \/\/ close enterprise namespace\n\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2014 Bloomberg Finance L.P.\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\/\/ ----------------------------- END-OF-FILE ----------------------------------\n\n<commit_msg>use bsls_byteorder instead of rolling our own<commit_after>\/\/ bslh_siphashalgorithm.cpp -*-C++-*-\n#include <bslh_siphashalgorithm.h>\n\n#include <bsls_ident.h>\nBSLS_IDENT(\"$Id$ $CSID$\")\n\n#include <bsls_assert.h>\n#include <bsls_types.h>\n#include <bsls_platform.h>\n#include <bsls_byteorder.h>\n\n#include <algorithm>\n#include <stddef.h> \/\/ for 'size_t'\n#include <string.h>\n\n\/\/\/Changes\n\/\/\/-------\n\/\/ The third party code begins with the \"siphash.h\" header below, and continues\n\/\/ until the Bloomberg LP copyright banner below. Changes made to the original\n\/\/ code include:\n\/\/\n\/\/: 1 Adding BloombergLP and bslh namespaces\n\/\/:\n\/\/: 2 Renaming 'siphash' to 'SipHashAlgorithm'\n\/\/:\n\/\/: 3 White space to meet BDE standards.\n\/\/:\n\/\/: 4 Added initializer list to handle class member initializers removed from\n\/\/: the header\n\/\/:\n\/\/: 5 Added 'computeHash()' to handle explicit conversion removed from header.\n\/\/:\n\/\/: 6 Changed the constructor to accept a 'const char *'\n\/\/:\n\/\/: 7 Changed endianness check to use BDE-defined check\n\/\/:\n\/\/: 8 Removed unnamed namespace in favour of 'static'\n\/\/:\n\/\/: 9 Added function contracts\n\/\/:\n\/\/: 10 Added asserts to check passed pointers\n\/\/:\n\/\/: 11 Re-wrote unaligned reads to buffer data and then perform aligned reads\n\/\/: to prevent runtime errors in opt builds on Sun machines.\n\/\/\n\/\/\/Third Party Doc\n\/\/\/---------------\n\/\/------------------------------- siphash.h -----------------------------------\n\/\/\n\/\/ This software is in the public domain. The only restriction on its use is\n\/\/ that no one can remove it from the public domain by claiming ownership of\n\/\/ it, including the original authors.\n\/\/\n\/\/ There is no warranty of correctness on the software contained herein. Use\n\/\/ at your own risk.\n\/\/\n\/\/ Derived from:\n\/\/\n\/\/ SipHash reference C implementation\n\/\/\n\/\/ Written in 2012 by Jean-Philippe Aumasson <jeanphilippe.aumasson@gmail.com>\n\/\/ Daniel J. Bernstein <djb@cr.yp.to>\n\/\/\n\/\/ To the extent possible under law, the author(s) have dedicated all copyright\n\/\/ and related and neighboring rights to this software to the public domain\n\/\/ worldwide. This software is distributed without any warranty.\n\/\/\n\/\/ You should have received a copy of the CC0 Public Domain Dedication along\n\/\/ with this software. If not, see\n\/\/ <http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/>.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n\nnamespace BloombergLP {\n\nnamespace bslh {\n\ntypedef bsls::Types::Uint64 u64;\ntypedef unsigned int u32;\ntypedef unsigned char u8;\n\ninline\nstatic u64 rotl(u64 x, u64 b)\n \/\/ Return the bits of the specified 'x' rotated to the left by the\n \/\/ specified 'b' number of bits. Bits that are rotated off the end are\n \/\/ wrapped around to the beginning.\n{\n return (x << b) | (x >> (64 - b));\n}\n\ninline\nstatic void sipround(u64& v0, u64& v1, u64& v2, u64& v3)\n \/\/ Mix the specified 'v0', 'v1', 'v2', and 'v3' in a \"Sip Round\" as\n \/\/ described in the SipHash algorithm\n{\n v0 += v1;\n v1 = rotl(v1, 13);\n v1 ^= v0;\n v0 = rotl(v0, 32);\n v2 += v3;\n v3 = rotl(v3, 16);\n v3 ^= v2;\n v0 += v3;\n v3 = rotl(v3, 21);\n v3 ^= v0;\n v2 += v1;\n v1 = rotl(v1, 17);\n v1 ^= v2;\n v2 = rotl(v2, 32);\n}\n\ninline\nstatic u64 u8to64_le(const u8* p)\n \/\/ Return the 64-bit integer representation of the specified 'p' taking\n \/\/ into account endianness. Undefined unless 'p' points to at least one\n \/\/ byte of initialized memory.\n{\n BSLS_ASSERT(p);\n\n#if defined(BSLS_PLATFORM_CPU_X86) || defined(BSLS_PLATFORM_CPU_X86_64)\n return *reinterpret_cast<const u64 *>(p); \/\/ Ignore alignment.\n#else\n u64 ret;\n memcpy(&ret, p, sizeof(ret));\n return(BSLS_BYTEORDER_LE_U64_TO_HOST(ret));\n#endif\n}\n\n\nSipHashAlgorithm::SipHashAlgorithm(const char *seed)\n: d_v0(0x736f6d6570736575ULL)\n, d_v1(0x646f72616e646f6dULL)\n, d_v2(0x6c7967656e657261ULL)\n, d_v3(0x7465646279746573ULL)\n, d_bufSize(0)\n, d_totalLength(0)\n{\n BSLS_ASSERT(seed);\n\n#if defined(BSLS_PLATFORM_CPU_X86) || defined(BSLS_PLATFORM_CPU_X86_64)\n const u64 *aligned = reinterpret_cast<const u64 *>(seed);\n#else\n u64 aligned[2];\n memcpy(&aligned, seed, sizeof(aligned));\n#endif\n d_v0 ^= aligned[0];\n d_v1 ^= aligned[1];\n d_v2 ^= aligned[0];\n d_v3 ^= aligned[1];\n}\n\nvoid\nSipHashAlgorithm::operator()(const void *data, size_t numBytes)\n{\n BSLS_ASSERT(data);\n\n u8 const* in = static_cast<const u8*>(data);\n\n d_totalLength += numBytes;\n if (d_bufSize + numBytes < 8)\n {\n std::copy(in, in + numBytes, d_buf + d_bufSize);\n d_bufSize += numBytes;\n return; \/\/ RETURN\n }\n if (d_bufSize > 0)\n {\n size_t t = 8 - d_bufSize;\n std::copy(in, in+t, d_buf + d_bufSize);\n u64 m = u8to64_le( d_buf );\n d_v3 ^= m;\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n d_v0 ^= m;\n in += t;\n numBytes -= t;\n }\n d_bufSize = numBytes & 7;\n u8 const* const end = in + (numBytes - d_bufSize);\n for ( ; in != end; in += 8 )\n {\n u64 m = u8to64_le( in );\n d_v3 ^= m;\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n d_v0 ^= m;\n }\n std::copy(end, end + d_bufSize, d_buf);\n}\n\nSipHashAlgorithm::result_type SipHashAlgorithm::computeHash()\n{\n result_type b = static_cast<u64>(d_totalLength) << 56;\n switch(d_bufSize)\n {\n case 7:\n b |= static_cast<u64>(d_buf[6]) << 48;\n case 6:\n b |= static_cast<u64>(d_buf[5]) << 40;\n case 5:\n b |= static_cast<u64>(d_buf[4]) << 32;\n case 4:\n b |= static_cast<u64>(d_buf[3]) << 24;\n case 3:\n b |= static_cast<u64>(d_buf[2]) << 16;\n case 2:\n b |= static_cast<u64>(d_buf[1]) << 8;\n case 1:\n b |= static_cast<u64>(d_buf[0]);\n case 0:\n break;\n }\n d_v3 ^= b;\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n d_v0 ^= b;\n d_v2 ^= 0xff;\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n sipround(d_v0, d_v1, d_v2, d_v3);\n b = d_v0 ^ d_v1 ^ d_v2 ^ d_v3;\n return b;\n}\n\n} \/\/ close package namespace\n\n} \/\/ close enterprise namespace\n\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2014 Bloomberg Finance L.P.\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\/\/ ----------------------------- END-OF-FILE ----------------------------------\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ bsls_outputredirector.cpp -*-C++-*-\n#include <bsls_outputredirector.h>\n\n#include <bsls_ident.h>\nBSLS_IDENT(\"$Id$ $CSID$\")\n\n#include <bsls_assert.h>\n#include <bsls_bsltestutil.h> \/\/ for testing only\n\n#include <algorithm>\n\n#include <stdlib.h>\n#include <string.h>\n\n#include <sys\/types.h> \/\/ 'struct stat': required on Sun and Windows only\n\n#if defined(BSLS_PLATFORM_OS_WINDOWS)\n# include <fcntl.h> \/\/ '_O_BINARY'\n# include <io.h> \/\/ '_dup2', '_dup', '_close'\n# define snprintf _snprintf\n#else\n# include <unistd.h>\n# include <stdint.h> \/\/ 'SIZE_MAX', cannot include on all Windows platforms\n# include <stdlib.h> \/\/ 'mkstemp'\n#endif\n\n#ifndef SIZE_MAX\n#define SIZE_MAX (static_cast<size_t>(-1))\n \/\/ 'SIZE_MAX' is only defined as part of C99, so it may not exist in some\n \/\/ pre-C++11 compilers.\n#endif\n\nnamespace BloombergLP {\nnamespace bsls {\n\n\/\/ PRIVATE MANIPULATORS\nvoid OutputRedirector::cleanup()\n{\n disable();\n cleanupFiles();\n}\n\nvoid OutputRedirector::cleanupFiles()\n{\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n _close(d_duplicatedOriginalFd);\n#else\n close(d_duplicatedOriginalFd);\n#endif\n\n d_duplicatedOriginalFd = -1;\n\n if (d_isFileCreatedFlag) {\n unlink(d_fileName);\n d_isFileCreatedFlag = false;\n }\n}\n\nbool OutputRedirector::generateTempFileName()\n{\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n char tmpPathBuf[k_PATH_BUFFER_SIZE];\n if (! GetTempPathA(k_PATH_BUFFER_SIZE, tmpPathBuf) ||\n ! GetTempFileNameA(tmpPathBuf, \"bsls\", 0, d_fileName)) {\n return false; \/\/ RETURN\n }\n#else\n static const char patternBuf[] = { \"\/tmp\/bslsXXXXXX\" };\n\n std::fill(d_fileName, d_fileName + sizeof(d_fileName), 0xa5);\n ::strncpy(d_fileName, patternBuf, sizeof(d_fileName));\n if ('\\0' != d_fileName[sizeof(d_fileName) - 1]) {\n return false; \/\/ RETURN\n }\n if (0 != ::strcmp(d_fileName, patternBuf)) {\n return false; \/\/ RETURN\n }\n\n const int fd = ::mkstemp(d_fileName);\n if (fd < 0) {\n \/\/ 'mkstemp' failed.\n\n return false; \/\/ RETURN\n }\n int rc = ::close(fd);\n if (0 != rc) {\n return false; \/\/ RETURN\n }\n if ('\\0' != d_fileName[sizeof(d_fileName) - 1]) {\n return false; \/\/ RETURN\n }\n#endif\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"\\tUsing '%s' as a base filename.\\n\",\n d_fileName);\n }\n return '\\0' != d_fileName[0]; \/\/ Ensure that 'd_fileName' is not empty\n}\n\n\/\/ CREATORS\nOutputRedirector::OutputRedirector(Stream which,\n bool verbose,\n bool veryVerbose)\n: d_stream(which)\n, d_isRedirectingFlag(false)\n, d_isFileCreatedFlag(false)\n, d_isOutputReadyFlag(false)\n, d_outputSize(0)\n, d_duplicatedOriginalFd(-1)\n, d_verbose(verbose)\n, d_veryVerbose(veryVerbose)\n{\n BSLS_ASSERT(which == e_STDOUT_STREAM || which == e_STDERR_STREAM);\n\n d_fileName[0] = '\\0';\n memset(&d_originalStat, 0, sizeof(struct stat));\n}\n\nOutputRedirector::~OutputRedirector()\n{\n cleanup();\n}\n\n\/\/ MANIPULATORS\nvoid OutputRedirector::disable()\n{\n if (!d_isRedirectingFlag) {\n return; \/\/ RETURN\n }\n\n d_isRedirectingFlag = false;\n\n fflush(redirectedStream());\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n const int status = _dup2(d_duplicatedOriginalFd,\n _fileno(redirectedStream()));\n#else\n const int status = dup2(d_duplicatedOriginalFd,\n fileno(redirectedStream()));\n#endif\n\n if (status < 0) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Bad 'dup2' status.\\n\",\n __LINE__);\n }\n cleanupFiles();\n abort();\n }\n}\n\nvoid OutputRedirector::enable()\n{\n if (d_isRedirectingFlag) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Warning \" __FILE__ \"(%d): Output already redirected\\n\",\n __LINE__);\n }\n\n return; \/\/ RETURN\n }\n\n \/\/ Retain information about original file descriptor for use in later\n \/\/ tests.\n\n const int originalFD = fileno(redirectedStream());\n\n BSLS_ASSERT(-1 != originalFD);\n BSLS_ASSERT(0 == fstat(originalFD, &d_originalStat));\n\n if (d_duplicatedOriginalFd == -1) {\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n d_duplicatedOriginalFd = _dup(originalFD);\n#else\n d_duplicatedOriginalFd = dup(originalFD);\n#endif\n }\n\n if (d_duplicatedOriginalFd < 0) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Bad 'dup' value.\\n\",\n __LINE__);\n }\n cleanup();\n abort();\n }\n\n if (!d_isFileCreatedFlag) {\n if (!generateTempFileName()) {\n\n \/\/ Get temp file name\n\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \"\n __FILE__\n \"(%d): Failed to get temp file name for capture\\n\",\n __LINE__);\n }\n cleanup();\n abort();\n }\n\n d_isFileCreatedFlag = true;\n }\n\n if (! freopen(d_fileName, \"w+\", redirectedStream())) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Failed to redirect stdout to\"\n \" temp file '%s'\\n\",\n __LINE__, d_fileName);\n }\n cleanup();\n abort();\n }\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n \/\/ In Windows, we need to convert the stream to binary mode because Windows\n \/\/ will automatically convert '\\n' to '\\r\\n' in text mode output. Normally\n \/\/ this would not be a problem, since the '\\r\\n' would be converted back to\n \/\/ '\\n' when we read the file. However, since we are using the size of the\n \/\/ written file to know how much to read, having extra characters will lead\n \/\/ to a faulty size reading.\n\n if (_setmode(_fileno(redirectedStream()), _O_BINARY) < 0) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Binary mode change failed.\\n\",\n __LINE__);\n }\n cleanup();\n abort();\n }\n#endif\n\n if (EOF == fflush(redirectedStream())) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Warning \" __FILE__ \"(%d): Error flushing stream\\n\",\n __LINE__);\n }\n }\n\n d_isRedirectingFlag = true;\n}\n\nbool OutputRedirector::load()\n{\n BSLS_ASSERT(d_isRedirectingFlag);\n\n if (ferror(redirectedStream()) != 0) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Stream has an error\\n\",\n __LINE__);\n }\n return false; \/\/ RETURN\n }\n\n const long tempOutputSize = ftell(redirectedStream());\n const long incremented = tempOutputSize + 1;\n\n if (tempOutputSize < 0 || incremented < 0) {\n \/\/ Protect against overflow or negative value\n\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Bad value from 'ftell': %ld\",\n incremented);\n }\n return false; \/\/ RETURN\n }\n\n \/\/ Conversion to 'unsigned long' is safe because 'incremented' > 0\n\n if (static_cast<unsigned long>(incremented) > SIZE_MAX) {\n \/\/ Our 'incremented' will not fit in a size_t, so it is too big for our\n \/\/ buffer.\n\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Bad value from 'ftell': %ld\",\n incremented);\n }\n return false; \/\/ RETURN\n }\n\n \/\/ Conversion to 'size_t' is safe because 'tempOutputSize' is nonnegative\n \/\/ and 'tempOutputSize'+1 is no larger than 'SIZE_MAX'.\n\n d_outputSize = static_cast<size_t>(tempOutputSize);\n\n if (static_cast<size_t>(incremented) > k_OUTPUT_REDIRECTOR_BUFFER_SIZE) {\n \/\/ Refuse to load output if it will not all fit in the scratch buffer,\n \/\/ INCLUDING the final null byte.\n\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \"\n __FILE__\n \"(%d): Captured output exceeds read buffer size\\n\",\n __LINE__);\n }\n d_outputSize = 0u;\n return false; \/\/ RETURN\n }\n\n rewind(redirectedStream());\n\n const long charsRead = fread(d_outputBuffer,\n sizeof(char),\n d_outputSize,\n redirectedStream());\n\n if (charsRead < 0 || static_cast<unsigned long>(charsRead)!=d_outputSize) {\n \/\/ We failed to read all output from the capture file.\n\n if (d_veryVerbose) {\n if (ferror(redirectedStream())) {\n \/\/ We encountered a file error, not 'EOF'.\n\n fprintf(nonRedirectedStream(),\n \"Error \"\n __FILE__\n \"(%d): Non-EOF error with file\\n\",\n __LINE__);\n }\n fprintf(nonRedirectedStream(),\n \"Error \"\n __FILE__\n \"(%d): Could not read all captured output\\n\",\n __LINE__);\n }\n\n if (charsRead < 0) {\n d_outputBuffer[0] = '\\0';\n } else if (static_cast<unsigned long>(charsRead) >= d_outputSize) {\n \/\/ This case should never happen. This assignment is safe because\n \/\/ the total buffer size is enough to hold 'd_outputSize' + 1.\n\n d_outputBuffer[d_outputSize] = '\\0';\n } else {\n d_outputBuffer[charsRead] = '\\0';\n }\n \/\/ ...to ensure that direct inspection of buffer does not overflow\n\n return false; \/\/ RETURN\n\n } else {\n \/\/ We have read all output from the capture file.\n\n d_outputBuffer[d_outputSize] = '\\0';\n }\n\n d_isOutputReadyFlag = true;\n\n return true;\n}\n\nvoid OutputRedirector::clear()\n{\n BSLS_ASSERT(d_isRedirectingFlag);\n\n d_outputSize = 0u;\n d_isOutputReadyFlag = false;\n d_outputBuffer[0] = '\\0';\n rewind(redirectedStream());\n}\n\n\/\/ ACCESSORS\nint OutputRedirector::compare(const char *expected) const\n{\n BSLS_ASSERT(expected);\n\n return compare(expected, strlen(expected));\n}\n\nint\nOutputRedirector::compare(const char *expected, size_t expectedLength) const\n{\n BSLS_ASSERT(expected || ! expectedLength);\n\n if (!d_isOutputReadyFlag) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): No captured output available\\n\",\n __LINE__);\n }\n return -1; \/\/ RETURN\n }\n\n \/\/ Use 'memcmp' instead of 'strncmp' to compare 'd_outputBuffer' to\n \/\/ 'expected', because 'expected' is allowed to contain embedded nulls.\n\n return static_cast<size_t>(d_outputSize) != expectedLength ||\n memcmp(d_outputBuffer, expected, expectedLength);\n}\n\nconst char *OutputRedirector::getOutput() const\n{\n return d_outputBuffer;\n}\n\nbool OutputRedirector::isOutputReady() const\n{\n return d_isOutputReadyFlag;\n}\n\nbool OutputRedirector::isRedirecting() const\n{\n return d_isRedirectingFlag;\n}\n\nFILE *OutputRedirector::nonRedirectedStream() const\n{\n \/\/ This should return the opposite values\n\n if (d_stream == e_STDOUT_STREAM) {\n return stderr; \/\/ RETURN\n } else {\n return stdout; \/\/ RETURN\n }\n}\n\nconst struct stat& OutputRedirector::originalStat() const\n{\n return d_originalStat;\n}\n\nsize_t OutputRedirector::outputSize() const\n{\n return d_outputSize;\n}\n\nFILE *OutputRedirector::redirectedStream() const\n{\n if (d_stream == e_STDOUT_STREAM) {\n return stdout; \/\/ RETURN\n } else {\n return stderr; \/\/ RETURN\n }\n}\n\nOutputRedirector::Stream OutputRedirector::redirectedStreamId() const\n{\n return d_stream;\n}\n\n} \/\/ close package namespace\n} \/\/ close enterprise namespace\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2013 Bloomberg Finance L.P.\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\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<commit_msg>bsls_outputredirector: lengthen temp name pattern, doc change<commit_after>\/\/ bsls_outputredirector.cpp -*-C++-*-\n#include <bsls_outputredirector.h>\n\n#include <bsls_ident.h>\nBSLS_IDENT(\"$Id$ $CSID$\")\n\n#include <bsls_assert.h>\n#include <bsls_bsltestutil.h> \/\/ for testing only\n\n#include <algorithm>\n\n#include <stdlib.h>\n#include <string.h>\n\n#include <sys\/types.h> \/\/ 'struct stat': required on Sun and Windows only\n\n#if defined(BSLS_PLATFORM_OS_WINDOWS)\n# include <fcntl.h> \/\/ '_O_BINARY'\n# include <io.h> \/\/ '_dup2', '_dup', '_close'\n# define snprintf _snprintf\n#else\n# include <unistd.h>\n# include <stdint.h> \/\/ 'SIZE_MAX', cannot include on all Windows platforms\n# include <stdlib.h> \/\/ 'mkstemp'\n#endif\n\n#ifndef SIZE_MAX\n#define SIZE_MAX (static_cast<size_t>(-1))\n \/\/ 'SIZE_MAX' is only defined as part of C99, so it may not exist in some\n \/\/ pre-C++11 compilers.\n#endif\n\nnamespace BloombergLP {\nnamespace bsls {\n\n\/\/ PRIVATE MANIPULATORS\nvoid OutputRedirector::cleanup()\n{\n disable();\n cleanupFiles();\n}\n\nvoid OutputRedirector::cleanupFiles()\n{\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n _close(d_duplicatedOriginalFd);\n#else\n close(d_duplicatedOriginalFd);\n#endif\n\n d_duplicatedOriginalFd = -1;\n\n if (d_isFileCreatedFlag) {\n unlink(d_fileName);\n d_isFileCreatedFlag = false;\n }\n}\n\nbool OutputRedirector::generateTempFileName()\n{\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n char tmpPathBuf[k_PATH_BUFFER_SIZE];\n if (! GetTempPathA(k_PATH_BUFFER_SIZE, tmpPathBuf) ||\n ! GetTempFileNameA(tmpPathBuf, \"bsls\", 0, d_fileName)) {\n return false; \/\/ RETURN\n }\n#else\n static const char patternBuf[] = { \"\/tmp\/bsls_outputredirector_XXXXXX\" };\n\n \/\/ Fill 'd_fileName' with garbage.\n\n std::fill(d_fileName, d_fileName + sizeof(d_fileName), 0xa5);\n\n \/\/ Copy in the pattern.\n\n ::strncpy(d_fileName, patternBuf, sizeof(d_fileName));\n if ('\\0' != d_fileName[sizeof(d_fileName) - 1]) {\n return false; \/\/ RETURN\n }\n if (0 != ::strcmp(d_fileName, patternBuf)) {\n return false; \/\/ RETURN\n }\n\n const int fd = ::mkstemp(d_fileName);\n if (fd < 0) {\n \/\/ 'mkstemp' failed.\n\n return false; \/\/ RETURN\n }\n int rc = ::close(fd);\n if (0 != rc) {\n return false; \/\/ RETURN\n }\n if ('\\0' != d_fileName[sizeof(d_fileName) - 1]) {\n return false; \/\/ RETURN\n }\n#endif\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"\\tUsing '%s' as a base filename.\\n\",\n d_fileName);\n }\n return '\\0' != d_fileName[0]; \/\/ Ensure that 'd_fileName' is not empty\n}\n\n\/\/ CREATORS\nOutputRedirector::OutputRedirector(Stream which,\n bool verbose,\n bool veryVerbose)\n: d_stream(which)\n, d_isRedirectingFlag(false)\n, d_isFileCreatedFlag(false)\n, d_isOutputReadyFlag(false)\n, d_outputSize(0)\n, d_duplicatedOriginalFd(-1)\n, d_verbose(verbose)\n, d_veryVerbose(veryVerbose)\n{\n BSLS_ASSERT(which == e_STDOUT_STREAM || which == e_STDERR_STREAM);\n\n d_fileName[0] = '\\0';\n memset(&d_originalStat, 0, sizeof(struct stat));\n}\n\nOutputRedirector::~OutputRedirector()\n{\n cleanup();\n}\n\n\/\/ MANIPULATORS\nvoid OutputRedirector::disable()\n{\n if (!d_isRedirectingFlag) {\n return; \/\/ RETURN\n }\n\n d_isRedirectingFlag = false;\n\n fflush(redirectedStream());\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n const int status = _dup2(d_duplicatedOriginalFd,\n _fileno(redirectedStream()));\n#else\n const int status = dup2(d_duplicatedOriginalFd,\n fileno(redirectedStream()));\n#endif\n\n if (status < 0) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Bad 'dup2' status.\\n\",\n __LINE__);\n }\n cleanupFiles();\n abort();\n }\n}\n\nvoid OutputRedirector::enable()\n{\n if (d_isRedirectingFlag) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Warning \" __FILE__ \"(%d): Output already redirected\\n\",\n __LINE__);\n }\n\n return; \/\/ RETURN\n }\n\n \/\/ Retain information about original file descriptor for use in later\n \/\/ tests.\n\n const int originalFD = fileno(redirectedStream());\n\n BSLS_ASSERT(-1 != originalFD);\n BSLS_ASSERT(0 == fstat(originalFD, &d_originalStat));\n\n if (d_duplicatedOriginalFd == -1) {\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n d_duplicatedOriginalFd = _dup(originalFD);\n#else\n d_duplicatedOriginalFd = dup(originalFD);\n#endif\n }\n\n if (d_duplicatedOriginalFd < 0) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Bad 'dup' value.\\n\",\n __LINE__);\n }\n cleanup();\n abort();\n }\n\n if (!d_isFileCreatedFlag) {\n if (!generateTempFileName()) {\n\n \/\/ Get temp file name\n\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \"\n __FILE__\n \"(%d): Failed to get temp file name for capture\\n\",\n __LINE__);\n }\n cleanup();\n abort();\n }\n\n d_isFileCreatedFlag = true;\n }\n\n if (! freopen(d_fileName, \"w+\", redirectedStream())) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Failed to redirect stdout to\"\n \" temp file '%s'\\n\",\n __LINE__, d_fileName);\n }\n cleanup();\n abort();\n }\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n \/\/ In Windows, we need to convert the stream to binary mode because Windows\n \/\/ will automatically convert '\\n' to '\\r\\n' in text mode output. Normally\n \/\/ this would not be a problem, since the '\\r\\n' would be converted back to\n \/\/ '\\n' when we read the file. However, since we are using the size of the\n \/\/ written file to know how much to read, having extra characters will lead\n \/\/ to a faulty size reading.\n\n if (_setmode(_fileno(redirectedStream()), _O_BINARY) < 0) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Binary mode change failed.\\n\",\n __LINE__);\n }\n cleanup();\n abort();\n }\n#endif\n\n if (EOF == fflush(redirectedStream())) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Warning \" __FILE__ \"(%d): Error flushing stream\\n\",\n __LINE__);\n }\n }\n\n d_isRedirectingFlag = true;\n}\n\nbool OutputRedirector::load()\n{\n BSLS_ASSERT(d_isRedirectingFlag);\n\n if (ferror(redirectedStream()) != 0) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): Stream has an error\\n\",\n __LINE__);\n }\n return false; \/\/ RETURN\n }\n\n const long tempOutputSize = ftell(redirectedStream());\n const long incremented = tempOutputSize + 1;\n\n if (tempOutputSize < 0 || incremented < 0) {\n \/\/ Protect against overflow or negative value\n\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Bad value from 'ftell': %ld\",\n incremented);\n }\n return false; \/\/ RETURN\n }\n\n \/\/ Conversion to 'unsigned long' is safe because 'incremented' > 0\n\n if (static_cast<unsigned long>(incremented) > SIZE_MAX) {\n \/\/ Our 'incremented' will not fit in a size_t, so it is too big for our\n \/\/ buffer.\n\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Bad value from 'ftell': %ld\",\n incremented);\n }\n return false; \/\/ RETURN\n }\n\n \/\/ Conversion to 'size_t' is safe because 'tempOutputSize' is nonnegative\n \/\/ and 'tempOutputSize'+1 is no larger than 'SIZE_MAX'.\n\n d_outputSize = static_cast<size_t>(tempOutputSize);\n\n if (static_cast<size_t>(incremented) > k_OUTPUT_REDIRECTOR_BUFFER_SIZE) {\n \/\/ Refuse to load output if it will not all fit in the scratch buffer,\n \/\/ INCLUDING the final null byte.\n\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \"\n __FILE__\n \"(%d): Captured output exceeds read buffer size\\n\",\n __LINE__);\n }\n d_outputSize = 0u;\n return false; \/\/ RETURN\n }\n\n rewind(redirectedStream());\n\n const long charsRead = fread(d_outputBuffer,\n sizeof(char),\n d_outputSize,\n redirectedStream());\n\n if (charsRead < 0 || static_cast<unsigned long>(charsRead)!=d_outputSize) {\n \/\/ We failed to read all output from the capture file.\n\n if (d_veryVerbose) {\n if (ferror(redirectedStream())) {\n \/\/ We encountered a file error, not 'EOF'.\n\n fprintf(nonRedirectedStream(),\n \"Error \"\n __FILE__\n \"(%d): Non-EOF error with file\\n\",\n __LINE__);\n }\n fprintf(nonRedirectedStream(),\n \"Error \"\n __FILE__\n \"(%d): Could not read all captured output\\n\",\n __LINE__);\n }\n\n if (charsRead < 0) {\n d_outputBuffer[0] = '\\0';\n } else if (static_cast<unsigned long>(charsRead) >= d_outputSize) {\n \/\/ This case should never happen. This assignment is safe because\n \/\/ the total buffer size is enough to hold 'd_outputSize' + 1.\n\n d_outputBuffer[d_outputSize] = '\\0';\n } else {\n d_outputBuffer[charsRead] = '\\0';\n }\n \/\/ ...to ensure that direct inspection of buffer does not overflow\n\n return false; \/\/ RETURN\n\n } else {\n \/\/ We have read all output from the capture file.\n\n d_outputBuffer[d_outputSize] = '\\0';\n }\n\n d_isOutputReadyFlag = true;\n\n return true;\n}\n\nvoid OutputRedirector::clear()\n{\n BSLS_ASSERT(d_isRedirectingFlag);\n\n d_outputSize = 0u;\n d_isOutputReadyFlag = false;\n d_outputBuffer[0] = '\\0';\n rewind(redirectedStream());\n}\n\n\/\/ ACCESSORS\nint OutputRedirector::compare(const char *expected) const\n{\n BSLS_ASSERT(expected);\n\n return compare(expected, strlen(expected));\n}\n\nint\nOutputRedirector::compare(const char *expected, size_t expectedLength) const\n{\n BSLS_ASSERT(expected || ! expectedLength);\n\n if (!d_isOutputReadyFlag) {\n if (d_veryVerbose) {\n fprintf(nonRedirectedStream(),\n \"Error \" __FILE__ \"(%d): No captured output available\\n\",\n __LINE__);\n }\n return -1; \/\/ RETURN\n }\n\n \/\/ Use 'memcmp' instead of 'strncmp' to compare 'd_outputBuffer' to\n \/\/ 'expected', because 'expected' is allowed to contain embedded nulls.\n\n return static_cast<size_t>(d_outputSize) != expectedLength ||\n memcmp(d_outputBuffer, expected, expectedLength);\n}\n\nconst char *OutputRedirector::getOutput() const\n{\n return d_outputBuffer;\n}\n\nbool OutputRedirector::isOutputReady() const\n{\n return d_isOutputReadyFlag;\n}\n\nbool OutputRedirector::isRedirecting() const\n{\n return d_isRedirectingFlag;\n}\n\nFILE *OutputRedirector::nonRedirectedStream() const\n{\n \/\/ This should return the opposite values\n\n if (d_stream == e_STDOUT_STREAM) {\n return stderr; \/\/ RETURN\n } else {\n return stdout; \/\/ RETURN\n }\n}\n\nconst struct stat& OutputRedirector::originalStat() const\n{\n return d_originalStat;\n}\n\nsize_t OutputRedirector::outputSize() const\n{\n return d_outputSize;\n}\n\nFILE *OutputRedirector::redirectedStream() const\n{\n if (d_stream == e_STDOUT_STREAM) {\n return stdout; \/\/ RETURN\n } else {\n return stderr; \/\/ RETURN\n }\n}\n\nOutputRedirector::Stream OutputRedirector::redirectedStreamId() const\n{\n return d_stream;\n}\n\n} \/\/ close package namespace\n} \/\/ close enterprise namespace\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2013 Bloomberg Finance L.P.\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\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Library\n Module: FeatEdge.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file\nor its contents may be copied, reproduced or altered in any way\nwithout the express written consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n#include <math.h>\n#include \"FeatEdge.hh\"\n#include \"vlMath.hh\"\n#include \"Polygon.hh\"\n#include \"FNormals.hh\"\n\n\/\/ Description:\n\/\/ Construct object with feature angle = 30; all types of edges extracted\n\/\/ and colored.\nvlFeatureEdges::vlFeatureEdges()\n{\n this->FeatureAngle = 30.0;\n this->BoundaryEdges = 1;\n this->FeatureEdges = 1;\n this->NonManifoldEdges = 1;\n this->Coloring = 1;\n}\n\n\/\/ Generate feature edges for mesh\nvoid vlFeatureEdges::Execute()\n{\n vlFloatPoints *newPts;\n vlFloatScalars *newScalars;\n vlCellArray *newLines;\n vlPolyData Mesh;\n int i, j, numNei, cellId;\n int numBEdges, numNonManifoldEdges, numFedges;\n float scalar, n[3], *x1, *x2, cosAngle;\n vlMath math;\n vlPolygon poly;\n int lineIds[2];\n int npts, pts[MAX_CELL_SIZE];\n vlCellArray *inPolys;\n vlFloatNormals *polyNormals;\n int numPts, nei;\n vlIdList edge(2), neighbors(MAX_CELL_SIZE);\n\n vlDebugMacro(<<\"Executing feature edges\");\n this->Initialize();\n\/\/\n\/\/ Check input\n\/\/\n if ( (numPts=this->Input->GetNumberOfPoints()) )\n {\n vlErrorMacro(<<\"No input data!\");\n return;\n }\n\n \/\/ build cell structure. Only operate with polygons.\n Mesh.SetPoints(this->Input->GetPoints());\n Mesh.SetPolys(this->Input->GetPolys());\n\/\/\n\/\/ Allocate storage for lines\/points\n\/\/\n newPts = new vlFloatPoints(numPts\/10,numPts); \/\/ arbitrary allocations size \n newScalars = new vlFloatScalars(numPts\/10,numPts);\n newLines = new vlCellArray(numPts\/10);\n\/\/\n\/\/ Loop over all polygons generating boundary, non-manifold, and feature edges\n\/\/\n if (this->BoundaryEdges || this->NonManifoldEdges || this->FeatureEdges) \n {\n if ( this->FeatureEdges ) \n { \n polyNormals = new vlFloatNormals(inPolys->GetNumberOfCells());\n\n for (cellId=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); \n cellId++)\n {\n poly.ComputeNormal(this->Input->GetPoints(),npts,pts,n);\n polyNormals->InsertNormal(cellId,n);\n }\n\n cosAngle = cos ((double) math.DegreesToRadians() * this->FeatureAngle);\n }\n\n numBEdges = numNonManifoldEdges = numFedges = 0;\n for (cellId=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); \n cellId++)\n {\n for (i=0; i < npts; i++) \n {\n edge.SetId(0,pts[i]);\n edge.SetId(1,pts[(i+1)%npts]);\n Mesh.GetCellNeighbors(cellId,edge,neighbors);\n\n if ( (numNei=neighbors.GetNumberOfIds()) < 1 && this->BoundaryEdges )\n {\n numBEdges++;\n scalar = 0.0;\n }\n else if ( numNei > 1 && this->NonManifoldEdges )\n {\n \/\/ check to make sure that this edge hasn't been created before\n for (j=0; j < numNei; j++)\n if ( neighbors.GetId(j) < cellId )\n break;\n if ( j >= numNei )\n {\n numNonManifoldEdges++;\n scalar = 0.33333;\n }\n }\n else if ( numNei == 1 && (nei=neighbors.GetId(0)) > cellId ) \n {\n if ( math.Dot(polyNormals->GetNormal(nei),polyNormals->GetNormal(cellId)) <= cosAngle ) \n {\n numFedges++;\n scalar = 0.66667;\n }\n else\n {\n continue;\n }\n }\n\n x1 = Mesh.GetPoint(edge.GetId(0));\n x2 = Mesh.GetPoint(edge.GetId(1));\n\n lineIds[0] = newPts->InsertNextPoint(x1);\n lineIds[1] = newPts->InsertNextPoint(x2);\n\n newLines->InsertNextCell(2,lineIds);\n\n newScalars->InsertScalar(lineIds[0], scalar);\n newScalars->InsertScalar(lineIds[1], scalar);\n }\n }\n vlDebugMacro(<<\"Created \" << numBEdges << \" boundary edges, \" <<\n numNonManifoldEdges << \" non-manifold edges, \" <<\n numFedges << \" feature edges\");\n if ( this->FeatureEdges ) delete polyNormals;\n }\n\/\/\n\/\/ Update ourselves.\n\/\/\n this->SetPoints(newPts);\n this->SetLines(newLines);\n if ( this->Coloring )\n this->PointData.SetScalars(newScalars);\n else\n delete newScalars;\n}\n\nvoid vlFeatureEdges::PrintSelf(ostream& os, vlIndent indent)\n{\n if (this->ShouldIPrint(vlFeatureEdges::GetClassName()))\n {\n vlPolyToPolyFilter::PrintSelf(os,indent);\n\n os << indent << \"Feature Angle: \" << this->FeatureAngle << \"\\n\";\n os << indent << \"BoundaryEdges: \" << (this->BoundaryEdges ? \"On\\n\" : \"Off\\n\");\n os << indent << \"FeatureEdges: \" << (this->FeatureEdges ? \"On\\n\" : \"Off\\n\"); \n os << indent << \"Non-Manifold Edges: \" << (this->NonManifoldEdges ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Coloring: \" << (this->Coloring ? \"On\\n\" : \"Off\\n\");\n }\n}\n\n<commit_msg>*** empty log message ***<commit_after>\/*=========================================================================\n\n Program: Visualization Library\n Module: FeatEdge.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file\nor its contents may be copied, reproduced or altered in any way\nwithout the express written consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n#include \"FeatEdge.hh\"\n#include \"vlMath.hh\"\n#include \"Polygon.hh\"\n#include \"FNormals.hh\"\n\n\/\/ Description:\n\/\/ Construct object with feature angle = 30; all types of edges extracted\n\/\/ and colored.\nvlFeatureEdges::vlFeatureEdges()\n{\n this->FeatureAngle = 30.0;\n this->BoundaryEdges = 1;\n this->FeatureEdges = 1;\n this->NonManifoldEdges = 1;\n this->Coloring = 1;\n}\n\n\/\/ Generate feature edges for mesh\nvoid vlFeatureEdges::Execute()\n{\n vlFloatPoints *newPts;\n vlFloatScalars *newScalars;\n vlCellArray *newLines;\n vlPolyData Mesh;\n int i, j, numNei, cellId;\n int numBEdges, numNonManifoldEdges, numFedges;\n float scalar, n[3], *x1, *x2, cosAngle;\n vlMath math;\n vlPolygon poly;\n int lineIds[2];\n int npts, *pts;\n vlCellArray *inPolys;\n vlFloatNormals *polyNormals;\n int numPts, nei;\n vlIdList neighbors(MAX_CELL_SIZE);\n int p1, p2;\n\n vlDebugMacro(<<\"Executing feature edges\");\n this->Initialize();\n\/\/\n\/\/ Check input\n\/\/\n if ( (numPts=this->Input->GetNumberOfPoints()) )\n {\n vlErrorMacro(<<\"No input data!\");\n return;\n }\n\n \/\/ build cell structure. Only operate with polygons.\n Mesh.SetPoints(this->Input->GetPoints());\n inPolys = this->Input->GetPolys();\n Mesh.SetPolys(inPolys);\n Mesh.BuildLinks();\n\/\/\n\/\/ Allocate storage for lines\/points\n\/\/\n newPts = new vlFloatPoints(numPts\/10,numPts); \/\/ arbitrary allocations size \n newScalars = new vlFloatScalars(numPts\/10,numPts);\n newLines = new vlCellArray(numPts\/10);\n\/\/\n\/\/ Loop over all polygons generating boundary, non-manifold, and feature edges\n\/\/\n if (this->BoundaryEdges || this->NonManifoldEdges || this->FeatureEdges) \n {\n if ( this->FeatureEdges ) \n { \n polyNormals = new vlFloatNormals(inPolys->GetNumberOfCells());\n\n for (cellId=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); \n cellId++)\n {\n poly.ComputeNormal(this->Input->GetPoints(),npts,pts,n);\n polyNormals->InsertNormal(cellId,n);\n }\n\n cosAngle = cos ((double) math.DegreesToRadians() * this->FeatureAngle);\n }\n\n numBEdges = numNonManifoldEdges = numFedges = 0;\n for (cellId=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); \n cellId++)\n {\n for (i=0; i < npts; i++) \n {\n p1 = pts[i];\n p2 = pts[(i+1)%npts];\n Mesh.GetCellEdgeNeighbors(cellId,p1,p2,neighbors);\n\n if ( (numNei=neighbors.GetNumberOfIds()) < 1 && this->BoundaryEdges )\n {\n numBEdges++;\n scalar = 0.0;\n }\n else if ( numNei > 1 && this->NonManifoldEdges )\n {\n \/\/ check to make sure that this edge hasn't been created before\n for (j=0; j < numNei; j++)\n if ( neighbors.GetId(j) < cellId )\n break;\n if ( j >= numNei )\n {\n numNonManifoldEdges++;\n scalar = 0.33333;\n }\n }\n else if ( numNei == 1 && (nei=neighbors.GetId(0)) > cellId ) \n {\n if ( math.Dot(polyNormals->GetNormal(nei),polyNormals->GetNormal(cellId)) <= cosAngle ) \n {\n numFedges++;\n scalar = 0.66667;\n }\n else\n {\n continue;\n }\n }\n\n x1 = Mesh.GetPoint(p1);\n x2 = Mesh.GetPoint(p2);\n\n lineIds[0] = newPts->InsertNextPoint(x1);\n lineIds[1] = newPts->InsertNextPoint(x2);\n\n newLines->InsertNextCell(2,lineIds);\n\n newScalars->InsertScalar(lineIds[0], scalar);\n newScalars->InsertScalar(lineIds[1], scalar);\n }\n }\n vlDebugMacro(<<\"Created \" << numBEdges << \" boundary edges, \" <<\n numNonManifoldEdges << \" non-manifold edges, \" <<\n numFedges << \" feature edges\");\n if ( this->FeatureEdges ) delete polyNormals;\n }\n\/\/\n\/\/ Update ourselves.\n\/\/\n this->SetPoints(newPts);\n this->SetLines(newLines);\n if ( this->Coloring )\n this->PointData.SetScalars(newScalars);\n else\n delete newScalars;\n}\n\nvoid vlFeatureEdges::PrintSelf(ostream& os, vlIndent indent)\n{\n if (this->ShouldIPrint(vlFeatureEdges::GetClassName()))\n {\n vlPolyToPolyFilter::PrintSelf(os,indent);\n\n os << indent << \"Feature Angle: \" << this->FeatureAngle << \"\\n\";\n os << indent << \"BoundaryEdges: \" << (this->BoundaryEdges ? \"On\\n\" : \"Off\\n\");\n os << indent << \"FeatureEdges: \" << (this->FeatureEdges ? \"On\\n\" : \"Off\\n\"); \n os << indent << \"Non-Manifold Edges: \" << (this->NonManifoldEdges ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Coloring: \" << (this->Coloring ? \"On\\n\" : \"Off\\n\");\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef GUI_HPP\n#define GUI_HPP\n#include <wx\/toplevel.h>\n#include \"MainFrame.hpp\"\n#include \"Notifier.hpp\"\n#include <string>\n#include <vector>\n#include <array>\n#include <stack>\n#include <mutex>\n\n\n#include \"Preset.hpp\"\n\nnamespace Slic3r { namespace GUI {\n\n\nclass App: public wxApp\n{\npublic:\n virtual bool OnInit() override;\n App() : wxApp() {}\n\n \/\/\/ Save position, size, and maximize state for a TopLevelWindow (includes Frames) by name in Settings.\n void save_window_pos(const wxTopLevelWindow* window, const wxString& name );\n\n \/\/\/ Move\/resize a named TopLevelWindow (includes Frames) from Settings\n void restore_window_pos(wxTopLevelWindow* window, const wxString& name );\n\n \/\/\/ Function to add callback functions to the idle loop stack.\n void CallAfter(std::function<void()> cb_function); \n\n\n void OnUnhandledException() override;\n\n std::vector<Presets> presets { preset_types, Presets() };\n std::array<wxString, preset_types> preset_ini { };\nprivate:\n std::unique_ptr<Notifier> notifier {nullptr};\n\n void load_presets();\n\n wxString datadir {\"\"};\n const std::string LogChannel {\"APP\"}; \/\/< Which log these messages should go to.\n\n \/\/\/ Lock to guard the callback stack\n std::mutex callback_register;\n \n \/\/\/ callbacks registered to run during idle event.\n std::stack<std::function<void()> > cb {};\n};\n\n\n\/\/\/ Quick reference to this app with its cast applied.\n#define SLIC3RAPP (dynamic_cast<App*>(wxTheApp))\n\n\n}} \/\/ namespace Slic3r::GUI\n#endif \/\/ GUI_HPP\n<commit_msg>Moved the basic preset store back to an array of vectors.<commit_after>#ifndef GUI_HPP\n#define GUI_HPP\n#include <wx\/toplevel.h>\n#include \"MainFrame.hpp\"\n#include \"Notifier.hpp\"\n#include <string>\n#include <vector>\n#include <array>\n#include <stack>\n#include <mutex>\n\n\n#include \"Preset.hpp\"\n\nnamespace Slic3r { namespace GUI {\n\n\nclass App: public wxApp\n{\npublic:\n virtual bool OnInit() override;\n App() : wxApp() {}\n\n \/\/\/ Save position, size, and maximize state for a TopLevelWindow (includes Frames) by name in Settings.\n void save_window_pos(const wxTopLevelWindow* window, const wxString& name );\n\n \/\/\/ Move\/resize a named TopLevelWindow (includes Frames) from Settings\n void restore_window_pos(wxTopLevelWindow* window, const wxString& name );\n\n \/\/\/ Function to add callback functions to the idle loop stack.\n void CallAfter(std::function<void()> cb_function); \n\n\n void OnUnhandledException() override;\n\n std::array<Presets, preset_types> presets { Presets() };\n std::array<wxString, preset_types> preset_ini { };\nprivate:\n std::unique_ptr<Notifier> notifier {nullptr};\n\n void load_presets();\n\n wxString datadir {\"\"};\n const std::string LogChannel {\"APP\"}; \/\/< Which log these messages should go to.\n\n \/\/\/ Lock to guard the callback stack\n std::mutex callback_register;\n \n \/\/\/ callbacks registered to run during idle event.\n std::stack<std::function<void()> > cb {};\n};\n\n\n\/\/\/ Quick reference to this app with its cast applied.\n#define SLIC3RAPP (dynamic_cast<App*>(wxTheApp))\n\n\n}} \/\/ namespace Slic3r::GUI\n#endif \/\/ GUI_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Gripper.cpp\r\n\r\n#include \"stdafx.h\"\r\n#include \"Gripper.h\"\r\n#include \"..\/interface\/HeeksColor.h\"\r\n\r\nstatic unsigned char circle[18] = {0x1c, 0x00, 0x63, 0x00, 0x41, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x41, 0x00, 0x63, 0x00, 0x1c, 0x00};\r\nstatic unsigned char translation_circle[30] = {0x00, 0x80, 0x01, 0xc0, 0x00, 0x80, 0x01, 0xc0, 0x06, 0x30, 0x04, 0x10, 0x28, 0x0a, 0x78, 0x0f, 0x28, 0x0a, 0x04, 0x10, 0x06, 0x30, 0x01, 0xc0, 0x00, 0x80, 0x01, 0xc0, 0x00, 0x80};\r\nstatic unsigned char rotation_circle[26] = {0x01, 0xc0, 0x06, 0x30, 0x04, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x10, 0x06, 0x31, 0x61, 0xc2, 0x60, 0x02, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0};\r\nstatic unsigned char rotation_object_circle[26] = {0x01, 0xc0, 0x06, 0xb0, 0x04, 0x90, 0x08, 0x88, 0x0f, 0xf8, 0x08, 0x88, 0x04, 0x90, 0x06, 0xb1, 0x61, 0xc2, 0x60, 0x02, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0};\r\nstatic unsigned char scale_circle[30] = {0x03, 0xe0, 0x0c, 0x18, 0x10, 0x04, 0x21, 0xc2, 0x26, 0x32, 0x44, 0x11, 0x48, 0x09, 0x48, 0x09, 0x48, 0x09, 0x44, 0x11, 0x26, 0x32, 0x21, 0xc2, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0};\r\nstatic unsigned char angle_circle[32] = {0x10, 0x04, 0x10, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x10, 0x04, 0x10, 0x02, 0x40, 0x03, 0xe0, 0x07, 0x70, 0x05, 0x50, 0x08, 0x88, 0x08, 0x88, 0x08, 0x08, 0x04, 0x10, 0x06, 0x30, 0x01, 0xc0};\r\n\r\nGripper::Gripper(const gp_Pnt& pos, const wxChar* str, EnumGripperType gripper_type){\r\n\tposition = pos;\r\n\tprompt = wxString(str);\r\n\tm_gripper_type = gripper_type;\r\n}\r\n\r\nvoid Gripper::glCommands(bool select, bool marked, bool no_color){\r\n\tif(!no_color){\r\n\t\twxGetApp().glColorEnsuringContrast(HeeksColor(0, 0, 0));\r\n\t}\r\n\tglRasterPos3d(position.X(), position.Y(), position.Z());\r\n\tswitch(m_gripper_type){\r\n\t\tcase GripperTypeTranslate:\r\n\t\t\tglBitmap(16, 15, 8, 7, 10.0, 0.0, translation_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeRotateObject:\r\n\t\t\tglBitmap(16, 13, 8, 4, 10.0, 0.0, rotation_object_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeRotate:\r\n\t\t\tglBitmap(16, 13, 8, 4, 10.0, 0.0, rotation_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeScale:\r\n\t\t\tglBitmap(16, 15, 8, 7, 10.0, 0.0, scale_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeAngle:\r\n\t\t\tglBitmap(14, 16, 9, 11, 10.0, 0.0, angle_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeStretch:\r\n\t\t\tglBitmap(9, 9, 4, 4, 10.0, 0.0, circle);\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tglBitmap(9, 9, 4, 4, 10.0, 0.0, circle);\r\n\t\t\tbreak;\r\n\t}\r\n}\r\n\r\nbool Gripper::ModifyByMatrix(const double *m){\r\n\tgp_Trsf mat = make_matrix(m);\r\n\tposition.Transform(mat);\r\n\treturn false;\r\n}\r\n<commit_msg>Fixed Issue 58: \t Grippers hard to pick I draw the grippers with a little cube for select mode.<commit_after>\/\/ Gripper.cpp\r\n\r\n#include \"stdafx.h\"\r\n#include \"Gripper.h\"\r\n#include \"..\/interface\/HeeksColor.h\"\r\n\r\nstatic unsigned char circle[18] = {0x1c, 0x00, 0x63, 0x00, 0x41, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x41, 0x00, 0x63, 0x00, 0x1c, 0x00};\r\nstatic unsigned char translation_circle[30] = {0x00, 0x80, 0x01, 0xc0, 0x00, 0x80, 0x01, 0xc0, 0x06, 0x30, 0x04, 0x10, 0x28, 0x0a, 0x78, 0x0f, 0x28, 0x0a, 0x04, 0x10, 0x06, 0x30, 0x01, 0xc0, 0x00, 0x80, 0x01, 0xc0, 0x00, 0x80};\r\nstatic unsigned char rotation_circle[26] = {0x01, 0xc0, 0x06, 0x30, 0x04, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x10, 0x06, 0x31, 0x61, 0xc2, 0x60, 0x02, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0};\r\nstatic unsigned char rotation_object_circle[26] = {0x01, 0xc0, 0x06, 0xb0, 0x04, 0x90, 0x08, 0x88, 0x0f, 0xf8, 0x08, 0x88, 0x04, 0x90, 0x06, 0xb1, 0x61, 0xc2, 0x60, 0x02, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0};\r\nstatic unsigned char scale_circle[30] = {0x03, 0xe0, 0x0c, 0x18, 0x10, 0x04, 0x21, 0xc2, 0x26, 0x32, 0x44, 0x11, 0x48, 0x09, 0x48, 0x09, 0x48, 0x09, 0x44, 0x11, 0x26, 0x32, 0x21, 0xc2, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0};\r\nstatic unsigned char angle_circle[32] = {0x10, 0x04, 0x10, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x10, 0x04, 0x10, 0x02, 0x40, 0x03, 0xe0, 0x07, 0x70, 0x05, 0x50, 0x08, 0x88, 0x08, 0x88, 0x08, 0x08, 0x04, 0x10, 0x06, 0x30, 0x01, 0xc0};\r\n\r\nGripper::Gripper(const gp_Pnt& pos, const wxChar* str, EnumGripperType gripper_type){\r\n\tposition = pos;\r\n\tprompt = wxString(str);\r\n\tm_gripper_type = gripper_type;\r\n}\r\n\r\nvoid Gripper::glCommands(bool select, bool marked, bool no_color){\r\n\tif(!no_color){\r\n\t\twxGetApp().glColorEnsuringContrast(HeeksColor(0, 0, 0));\r\n\t}\r\n\tif(select)\r\n\t{\r\n\t\tdouble s = 5.0 \/ wxGetApp().GetPixelScale();\r\n\t\tdouble p[8][3] = {\r\n\t\t\t-s, -s, -s,\r\n\t\t\ts, -s, -s,\r\n\t\t\ts, s, -s,\r\n\t\t\t-s, s, -s,\r\n\t\t\t-s, -s, s,\r\n\t\t\ts, -s, s,\r\n\t\t\ts, s, s,\r\n\t\t\t-s, s, s\r\n\t\t};\r\n\r\n\t\tfor(int i = 0; i<8; i++){\r\n\t\t\tp[i][0] += position.X();\r\n\t\t\tp[i][1] += position.Y();\r\n\t\t\tp[i][2] += position.Z();\r\n\t\t}\r\n\r\n\t\tglBegin(GL_TRIANGLES);\r\n\t\tglVertex3dv(p[0]);\r\n\t\tglVertex3dv(p[2]);\r\n\t\tglVertex3dv(p[1]);\r\n\t\tglVertex3dv(p[0]);\r\n\t\tglVertex3dv(p[3]);\r\n\t\tglVertex3dv(p[2]);\r\n\r\n\t\tglVertex3dv(p[0]);\r\n\t\tglVertex3dv(p[1]);\r\n\t\tglVertex3dv(p[5]);\r\n\t\tglVertex3dv(p[0]);\r\n\t\tglVertex3dv(p[5]);\r\n\t\tglVertex3dv(p[4]);\r\n\r\n\t\tglVertex3dv(p[3]);\r\n\t\tglVertex3dv(p[0]);\r\n\t\tglVertex3dv(p[4]);\r\n\t\tglVertex3dv(p[3]);\r\n\t\tglVertex3dv(p[4]);\r\n\t\tglVertex3dv(p[7]);\r\n\r\n\t\tglVertex3dv(p[4]);\r\n\t\tglVertex3dv(p[5]);\r\n\t\tglVertex3dv(p[6]);\r\n\t\tglVertex3dv(p[4]);\r\n\t\tglVertex3dv(p[6]);\r\n\t\tglVertex3dv(p[7]);\r\n\r\n\t\tglVertex3dv(p[3]);\r\n\t\tglVertex3dv(p[7]);\r\n\t\tglVertex3dv(p[6]);\r\n\t\tglVertex3dv(p[3]);\r\n\t\tglVertex3dv(p[6]);\r\n\t\tglVertex3dv(p[2]);\r\n\r\n\t\tglVertex3dv(p[2]);\r\n\t\tglVertex3dv(p[6]);\r\n\t\tglVertex3dv(p[5]);\r\n\t\tglVertex3dv(p[2]);\r\n\t\tglVertex3dv(p[5]);\r\n\t\tglVertex3dv(p[1]);\r\n\r\n\t\tglEnd();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tglRasterPos3d(position.X(), position.Y(), position.Z());\r\n\t\tswitch(m_gripper_type){\r\n\t\tcase GripperTypeTranslate:\r\n\t\t\tglBitmap(16, 15, 8, 7, 10.0, 0.0, translation_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeRotateObject:\r\n\t\t\tglBitmap(16, 13, 8, 4, 10.0, 0.0, rotation_object_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeRotate:\r\n\t\t\tglBitmap(16, 13, 8, 4, 10.0, 0.0, rotation_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeScale:\r\n\t\t\tglBitmap(16, 15, 8, 7, 10.0, 0.0, scale_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeAngle:\r\n\t\t\tglBitmap(14, 16, 9, 11, 10.0, 0.0, angle_circle);\r\n\t\t\tbreak;\r\n\t\tcase GripperTypeStretch:\r\n\t\t\tglBitmap(9, 9, 4, 4, 10.0, 0.0, circle);\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tglBitmap(9, 9, 4, 4, 10.0, 0.0, circle);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool Gripper::ModifyByMatrix(const double *m){\r\n\tgp_Trsf mat = make_matrix(m);\r\n\tposition.Transform(mat);\r\n\treturn false;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017-2021 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <chainparams.h>\n#include <index\/base.h>\n#include <node\/blockstorage.h>\n#include <node\/ui_interface.h>\n#include <shutdown.h>\n#include <tinyformat.h>\n#include <util\/syscall_sandbox.h>\n#include <util\/thread.h>\n#include <util\/translation.h>\n#include <validation.h> \/\/ For g_chainman\n#include <warnings.h>\n\nusing node::ReadBlockFromDisk;\n\nconstexpr uint8_t DB_BEST_BLOCK{'B'};\n\nconstexpr int64_t SYNC_LOG_INTERVAL = 30; \/\/ seconds\nconstexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL = 30; \/\/ seconds\n\ntemplate <typename... Args>\nstatic void FatalError(const char* fmt, const Args&... args)\n{\n std::string strMessage = tfm::format(fmt, args...);\n SetMiscWarning(Untranslated(strMessage));\n LogPrintf(\"*** %s\\n\", strMessage);\n AbortError(_(\"A fatal internal error occurred, see debug.log for details\"));\n StartShutdown();\n}\n\nBaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) :\n CDBWrapper(path, n_cache_size, f_memory, f_wipe, f_obfuscate)\n{}\n\nbool BaseIndex::DB::ReadBestBlock(CBlockLocator& locator) const\n{\n bool success = Read(DB_BEST_BLOCK, locator);\n if (!success) {\n locator.SetNull();\n }\n return success;\n}\n\nvoid BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator)\n{\n batch.Write(DB_BEST_BLOCK, locator);\n}\n\nBaseIndex::~BaseIndex()\n{\n Interrupt();\n Stop();\n}\n\nbool BaseIndex::Init()\n{\n CBlockLocator locator;\n if (!GetDB().ReadBestBlock(locator)) {\n locator.SetNull();\n }\n\n LOCK(cs_main);\n CChain& active_chain = m_chainstate->m_chain;\n if (locator.IsNull()) {\n SetBestBlockIndex(nullptr);\n } else {\n SetBestBlockIndex(m_chainstate->FindForkInGlobalIndex(locator));\n }\n m_synced = m_best_block_index.load() == active_chain.Tip();\n if (!m_synced) {\n bool prune_violation = false;\n if (!m_best_block_index) {\n \/\/ index is not built yet\n \/\/ make sure we have all block data back to the genesis\n prune_violation = m_chainstate->m_blockman.GetFirstStoredBlock(*active_chain.Tip()) != active_chain.Genesis();\n }\n \/\/ in case the index has a best block set and is not fully synced\n \/\/ check if we have the required blocks to continue building the index\n else {\n const CBlockIndex* block_to_test = m_best_block_index.load();\n if (!active_chain.Contains(block_to_test)) {\n \/\/ if the bestblock is not part of the mainchain, find the fork\n \/\/ and make sure we have all data down to the fork\n block_to_test = active_chain.FindFork(block_to_test);\n }\n const CBlockIndex* block = active_chain.Tip();\n prune_violation = true;\n \/\/ check backwards from the tip if we have all block data until we reach the indexes bestblock\n while (block_to_test && block && (block->nStatus & BLOCK_HAVE_DATA)) {\n if (block_to_test == block) {\n prune_violation = false;\n break;\n }\n \/\/ block->pprev must exist at this point, since block_to_test is part of the chain\n \/\/ and thus must be encountered when going backwards from the tip\n assert(block->pprev);\n block = block->pprev;\n }\n }\n if (prune_violation) {\n return InitError(strprintf(Untranslated(\"%s best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)\"), GetName()));\n }\n }\n return true;\n}\n\nstatic const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev, CChain& chain) EXCLUSIVE_LOCKS_REQUIRED(cs_main)\n{\n AssertLockHeld(cs_main);\n\n if (!pindex_prev) {\n return chain.Genesis();\n }\n\n const CBlockIndex* pindex = chain.Next(pindex_prev);\n if (pindex) {\n return pindex;\n }\n\n return chain.Next(chain.FindFork(pindex_prev));\n}\n\nvoid BaseIndex::ThreadSync()\n{\n SetSyscallSandboxPolicy(SyscallSandboxPolicy::TX_INDEX);\n const CBlockIndex* pindex = m_best_block_index.load();\n if (!m_synced) {\n auto& consensus_params = Params().GetConsensus();\n\n int64_t last_log_time = 0;\n int64_t last_locator_write_time = 0;\n while (true) {\n if (m_interrupt) {\n SetBestBlockIndex(pindex);\n \/\/ No need to handle errors in Commit. If it fails, the error will be already be\n \/\/ logged. The best way to recover is to continue, as index cannot be corrupted by\n \/\/ a missed commit to disk for an advanced index state.\n Commit();\n return;\n }\n\n {\n LOCK(cs_main);\n const CBlockIndex* pindex_next = NextSyncBlock(pindex, m_chainstate->m_chain);\n if (!pindex_next) {\n SetBestBlockIndex(pindex);\n m_synced = true;\n \/\/ No need to handle errors in Commit. See rationale above.\n Commit();\n break;\n }\n if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) {\n FatalError(\"%s: Failed to rewind index %s to a previous chain tip\",\n __func__, GetName());\n return;\n }\n pindex = pindex_next;\n }\n\n int64_t current_time = GetTime();\n if (last_log_time + SYNC_LOG_INTERVAL < current_time) {\n LogPrintf(\"Syncing %s with block chain from height %d\\n\",\n GetName(), pindex->nHeight);\n last_log_time = current_time;\n }\n\n if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) {\n SetBestBlockIndex(pindex);\n last_locator_write_time = current_time;\n \/\/ No need to handle errors in Commit. See rationale above.\n Commit();\n }\n\n CBlock block;\n if (!ReadBlockFromDisk(block, pindex, consensus_params)) {\n FatalError(\"%s: Failed to read block %s from disk\",\n __func__, pindex->GetBlockHash().ToString());\n return;\n }\n if (!WriteBlock(block, pindex)) {\n FatalError(\"%s: Failed to write block %s to index database\",\n __func__, pindex->GetBlockHash().ToString());\n return;\n }\n }\n }\n\n if (pindex) {\n LogPrintf(\"%s is enabled at height %d\\n\", GetName(), pindex->nHeight);\n } else {\n LogPrintf(\"%s is enabled\\n\", GetName());\n }\n}\n\nbool BaseIndex::Commit()\n{\n CDBBatch batch(GetDB());\n if (!CommitInternal(batch) || !GetDB().WriteBatch(batch)) {\n return error(\"%s: Failed to commit latest %s state\", __func__, GetName());\n }\n return true;\n}\n\nbool BaseIndex::CommitInternal(CDBBatch& batch)\n{\n LOCK(cs_main);\n \/\/ Don't commit anything if we haven't indexed any block yet\n \/\/ (this could happen if init is interrupted).\n if (m_best_block_index == nullptr) {\n return false;\n }\n GetDB().WriteBestBlock(batch, m_chainstate->m_chain.GetLocator(m_best_block_index));\n return true;\n}\n\nbool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip)\n{\n assert(current_tip == m_best_block_index);\n assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);\n\n \/\/ In the case of a reorg, ensure persisted block locator is not stale.\n \/\/ Pruning has a minimum of 288 blocks-to-keep and getting the index\n \/\/ out of sync may be possible but a users fault.\n \/\/ In case we reorg beyond the pruned depth, ReadBlockFromDisk would\n \/\/ throw and lead to a graceful shutdown\n SetBestBlockIndex(new_tip);\n if (!Commit()) {\n \/\/ If commit fails, revert the best block index to avoid corruption.\n SetBestBlockIndex(current_tip);\n return false;\n }\n\n return true;\n}\n\nvoid BaseIndex::BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex)\n{\n if (!m_synced) {\n return;\n }\n\n const CBlockIndex* best_block_index = m_best_block_index.load();\n if (!best_block_index) {\n if (pindex->nHeight != 0) {\n FatalError(\"%s: First block connected is not the genesis block (height=%d)\",\n __func__, pindex->nHeight);\n return;\n }\n } else {\n \/\/ Ensure block connects to an ancestor of the current best block. This should be the case\n \/\/ most of the time, but may not be immediately after the sync thread catches up and sets\n \/\/ m_synced. Consider the case where there is a reorg and the blocks on the stale branch are\n \/\/ in the ValidationInterface queue backlog even after the sync thread has caught up to the\n \/\/ new chain tip. In this unlikely event, log a warning and let the queue clear.\n if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) {\n LogPrintf(\"%s: WARNING: Block %s does not connect to an ancestor of \" \/* Continued *\/\n \"known best chain (tip=%s); not updating index\\n\",\n __func__, pindex->GetBlockHash().ToString(),\n best_block_index->GetBlockHash().ToString());\n return;\n }\n if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) {\n FatalError(\"%s: Failed to rewind index %s to a previous chain tip\",\n __func__, GetName());\n return;\n }\n }\n\n if (WriteBlock(*block, pindex)) {\n SetBestBlockIndex(pindex);\n } else {\n FatalError(\"%s: Failed to write block %s to index\",\n __func__, pindex->GetBlockHash().ToString());\n return;\n }\n}\n\nvoid BaseIndex::ChainStateFlushed(const CBlockLocator& locator)\n{\n if (!m_synced) {\n return;\n }\n\n const uint256& locator_tip_hash = locator.vHave.front();\n const CBlockIndex* locator_tip_index;\n {\n LOCK(cs_main);\n locator_tip_index = m_chainstate->m_blockman.LookupBlockIndex(locator_tip_hash);\n }\n\n if (!locator_tip_index) {\n FatalError(\"%s: First block (hash=%s) in locator was not found\",\n __func__, locator_tip_hash.ToString());\n return;\n }\n\n \/\/ This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail\n \/\/ immediately after the sync thread catches up and sets m_synced. Consider the case where\n \/\/ there is a reorg and the blocks on the stale branch are in the ValidationInterface queue\n \/\/ backlog even after the sync thread has caught up to the new chain tip. In this unlikely\n \/\/ event, log a warning and let the queue clear.\n const CBlockIndex* best_block_index = m_best_block_index.load();\n if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) {\n LogPrintf(\"%s: WARNING: Locator contains block (hash=%s) not on known best \" \/* Continued *\/\n \"chain (tip=%s); not writing index locator\\n\",\n __func__, locator_tip_hash.ToString(),\n best_block_index->GetBlockHash().ToString());\n return;\n }\n\n \/\/ No need to handle errors in Commit. If it fails, the error will be already be logged. The\n \/\/ best way to recover is to continue, as index cannot be corrupted by a missed commit to disk\n \/\/ for an advanced index state.\n Commit();\n}\n\nbool BaseIndex::BlockUntilSyncedToCurrentChain() const\n{\n AssertLockNotHeld(cs_main);\n\n if (!m_synced) {\n return false;\n }\n\n {\n \/\/ Skip the queue-draining stuff if we know we're caught up with\n \/\/ m_chain.Tip().\n LOCK(cs_main);\n const CBlockIndex* chain_tip = m_chainstate->m_chain.Tip();\n const CBlockIndex* best_block_index = m_best_block_index.load();\n if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) {\n return true;\n }\n }\n\n LogPrintf(\"%s: %s is catching up on block notifications\\n\", __func__, GetName());\n SyncWithValidationInterfaceQueue();\n return true;\n}\n\nvoid BaseIndex::Interrupt()\n{\n m_interrupt();\n}\n\nbool BaseIndex::Start(CChainState& active_chainstate)\n{\n m_chainstate = &active_chainstate;\n \/\/ Need to register this ValidationInterface before running Init(), so that\n \/\/ callbacks are not missed if Init sets m_synced to true.\n RegisterValidationInterface(this);\n if (!Init()) {\n return false;\n }\n\n m_thread_sync = std::thread(&util::TraceThread, GetName(), [this] { ThreadSync(); });\n return true;\n}\n\nvoid BaseIndex::Stop()\n{\n UnregisterValidationInterface(this);\n\n if (m_thread_sync.joinable()) {\n m_thread_sync.join();\n }\n}\n\nIndexSummary BaseIndex::GetSummary() const\n{\n IndexSummary summary{};\n summary.name = GetName();\n summary.synced = m_synced;\n summary.best_block_height = m_best_block_index ? m_best_block_index.load()->nHeight : 0;\n return summary;\n}\n\nvoid BaseIndex::SetBestBlockIndex(const CBlockIndex* block) {\n assert(!node::fPruneMode || AllowPrune());\n\n m_best_block_index = block;\n if (AllowPrune() && block) {\n node::PruneLockInfo prune_lock;\n prune_lock.height_first = block->nHeight;\n WITH_LOCK(::cs_main, m_chainstate->m_blockman.UpdatePruneLock(GetName(), prune_lock));\n }\n}\n<commit_msg>index: Don't commit a best block before indexing it during sync<commit_after>\/\/ Copyright (c) 2017-2021 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <chainparams.h>\n#include <index\/base.h>\n#include <node\/blockstorage.h>\n#include <node\/ui_interface.h>\n#include <shutdown.h>\n#include <tinyformat.h>\n#include <util\/syscall_sandbox.h>\n#include <util\/thread.h>\n#include <util\/translation.h>\n#include <validation.h> \/\/ For g_chainman\n#include <warnings.h>\n\nusing node::ReadBlockFromDisk;\n\nconstexpr uint8_t DB_BEST_BLOCK{'B'};\n\nconstexpr int64_t SYNC_LOG_INTERVAL = 30; \/\/ seconds\nconstexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL = 30; \/\/ seconds\n\ntemplate <typename... Args>\nstatic void FatalError(const char* fmt, const Args&... args)\n{\n std::string strMessage = tfm::format(fmt, args...);\n SetMiscWarning(Untranslated(strMessage));\n LogPrintf(\"*** %s\\n\", strMessage);\n AbortError(_(\"A fatal internal error occurred, see debug.log for details\"));\n StartShutdown();\n}\n\nBaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) :\n CDBWrapper(path, n_cache_size, f_memory, f_wipe, f_obfuscate)\n{}\n\nbool BaseIndex::DB::ReadBestBlock(CBlockLocator& locator) const\n{\n bool success = Read(DB_BEST_BLOCK, locator);\n if (!success) {\n locator.SetNull();\n }\n return success;\n}\n\nvoid BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator)\n{\n batch.Write(DB_BEST_BLOCK, locator);\n}\n\nBaseIndex::~BaseIndex()\n{\n Interrupt();\n Stop();\n}\n\nbool BaseIndex::Init()\n{\n CBlockLocator locator;\n if (!GetDB().ReadBestBlock(locator)) {\n locator.SetNull();\n }\n\n LOCK(cs_main);\n CChain& active_chain = m_chainstate->m_chain;\n if (locator.IsNull()) {\n SetBestBlockIndex(nullptr);\n } else {\n SetBestBlockIndex(m_chainstate->FindForkInGlobalIndex(locator));\n }\n m_synced = m_best_block_index.load() == active_chain.Tip();\n if (!m_synced) {\n bool prune_violation = false;\n if (!m_best_block_index) {\n \/\/ index is not built yet\n \/\/ make sure we have all block data back to the genesis\n prune_violation = m_chainstate->m_blockman.GetFirstStoredBlock(*active_chain.Tip()) != active_chain.Genesis();\n }\n \/\/ in case the index has a best block set and is not fully synced\n \/\/ check if we have the required blocks to continue building the index\n else {\n const CBlockIndex* block_to_test = m_best_block_index.load();\n if (!active_chain.Contains(block_to_test)) {\n \/\/ if the bestblock is not part of the mainchain, find the fork\n \/\/ and make sure we have all data down to the fork\n block_to_test = active_chain.FindFork(block_to_test);\n }\n const CBlockIndex* block = active_chain.Tip();\n prune_violation = true;\n \/\/ check backwards from the tip if we have all block data until we reach the indexes bestblock\n while (block_to_test && block && (block->nStatus & BLOCK_HAVE_DATA)) {\n if (block_to_test == block) {\n prune_violation = false;\n break;\n }\n \/\/ block->pprev must exist at this point, since block_to_test is part of the chain\n \/\/ and thus must be encountered when going backwards from the tip\n assert(block->pprev);\n block = block->pprev;\n }\n }\n if (prune_violation) {\n return InitError(strprintf(Untranslated(\"%s best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)\"), GetName()));\n }\n }\n return true;\n}\n\nstatic const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev, CChain& chain) EXCLUSIVE_LOCKS_REQUIRED(cs_main)\n{\n AssertLockHeld(cs_main);\n\n if (!pindex_prev) {\n return chain.Genesis();\n }\n\n const CBlockIndex* pindex = chain.Next(pindex_prev);\n if (pindex) {\n return pindex;\n }\n\n return chain.Next(chain.FindFork(pindex_prev));\n}\n\nvoid BaseIndex::ThreadSync()\n{\n SetSyscallSandboxPolicy(SyscallSandboxPolicy::TX_INDEX);\n const CBlockIndex* pindex = m_best_block_index.load();\n if (!m_synced) {\n auto& consensus_params = Params().GetConsensus();\n\n int64_t last_log_time = 0;\n int64_t last_locator_write_time = 0;\n while (true) {\n if (m_interrupt) {\n SetBestBlockIndex(pindex);\n \/\/ No need to handle errors in Commit. If it fails, the error will be already be\n \/\/ logged. The best way to recover is to continue, as index cannot be corrupted by\n \/\/ a missed commit to disk for an advanced index state.\n Commit();\n return;\n }\n\n {\n LOCK(cs_main);\n const CBlockIndex* pindex_next = NextSyncBlock(pindex, m_chainstate->m_chain);\n if (!pindex_next) {\n SetBestBlockIndex(pindex);\n m_synced = true;\n \/\/ No need to handle errors in Commit. See rationale above.\n Commit();\n break;\n }\n if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) {\n FatalError(\"%s: Failed to rewind index %s to a previous chain tip\",\n __func__, GetName());\n return;\n }\n pindex = pindex_next;\n }\n\n int64_t current_time = GetTime();\n if (last_log_time + SYNC_LOG_INTERVAL < current_time) {\n LogPrintf(\"Syncing %s with block chain from height %d\\n\",\n GetName(), pindex->nHeight);\n last_log_time = current_time;\n }\n\n if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) {\n SetBestBlockIndex(pindex->pprev);\n last_locator_write_time = current_time;\n \/\/ No need to handle errors in Commit. See rationale above.\n Commit();\n }\n\n CBlock block;\n if (!ReadBlockFromDisk(block, pindex, consensus_params)) {\n FatalError(\"%s: Failed to read block %s from disk\",\n __func__, pindex->GetBlockHash().ToString());\n return;\n }\n if (!WriteBlock(block, pindex)) {\n FatalError(\"%s: Failed to write block %s to index database\",\n __func__, pindex->GetBlockHash().ToString());\n return;\n }\n }\n }\n\n if (pindex) {\n LogPrintf(\"%s is enabled at height %d\\n\", GetName(), pindex->nHeight);\n } else {\n LogPrintf(\"%s is enabled\\n\", GetName());\n }\n}\n\nbool BaseIndex::Commit()\n{\n CDBBatch batch(GetDB());\n if (!CommitInternal(batch) || !GetDB().WriteBatch(batch)) {\n return error(\"%s: Failed to commit latest %s state\", __func__, GetName());\n }\n return true;\n}\n\nbool BaseIndex::CommitInternal(CDBBatch& batch)\n{\n LOCK(cs_main);\n \/\/ Don't commit anything if we haven't indexed any block yet\n \/\/ (this could happen if init is interrupted).\n if (m_best_block_index == nullptr) {\n return false;\n }\n GetDB().WriteBestBlock(batch, m_chainstate->m_chain.GetLocator(m_best_block_index));\n return true;\n}\n\nbool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip)\n{\n assert(current_tip == m_best_block_index);\n assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);\n\n \/\/ In the case of a reorg, ensure persisted block locator is not stale.\n \/\/ Pruning has a minimum of 288 blocks-to-keep and getting the index\n \/\/ out of sync may be possible but a users fault.\n \/\/ In case we reorg beyond the pruned depth, ReadBlockFromDisk would\n \/\/ throw and lead to a graceful shutdown\n SetBestBlockIndex(new_tip);\n if (!Commit()) {\n \/\/ If commit fails, revert the best block index to avoid corruption.\n SetBestBlockIndex(current_tip);\n return false;\n }\n\n return true;\n}\n\nvoid BaseIndex::BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex)\n{\n if (!m_synced) {\n return;\n }\n\n const CBlockIndex* best_block_index = m_best_block_index.load();\n if (!best_block_index) {\n if (pindex->nHeight != 0) {\n FatalError(\"%s: First block connected is not the genesis block (height=%d)\",\n __func__, pindex->nHeight);\n return;\n }\n } else {\n \/\/ Ensure block connects to an ancestor of the current best block. This should be the case\n \/\/ most of the time, but may not be immediately after the sync thread catches up and sets\n \/\/ m_synced. Consider the case where there is a reorg and the blocks on the stale branch are\n \/\/ in the ValidationInterface queue backlog even after the sync thread has caught up to the\n \/\/ new chain tip. In this unlikely event, log a warning and let the queue clear.\n if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) {\n LogPrintf(\"%s: WARNING: Block %s does not connect to an ancestor of \" \/* Continued *\/\n \"known best chain (tip=%s); not updating index\\n\",\n __func__, pindex->GetBlockHash().ToString(),\n best_block_index->GetBlockHash().ToString());\n return;\n }\n if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) {\n FatalError(\"%s: Failed to rewind index %s to a previous chain tip\",\n __func__, GetName());\n return;\n }\n }\n\n if (WriteBlock(*block, pindex)) {\n SetBestBlockIndex(pindex);\n } else {\n FatalError(\"%s: Failed to write block %s to index\",\n __func__, pindex->GetBlockHash().ToString());\n return;\n }\n}\n\nvoid BaseIndex::ChainStateFlushed(const CBlockLocator& locator)\n{\n if (!m_synced) {\n return;\n }\n\n const uint256& locator_tip_hash = locator.vHave.front();\n const CBlockIndex* locator_tip_index;\n {\n LOCK(cs_main);\n locator_tip_index = m_chainstate->m_blockman.LookupBlockIndex(locator_tip_hash);\n }\n\n if (!locator_tip_index) {\n FatalError(\"%s: First block (hash=%s) in locator was not found\",\n __func__, locator_tip_hash.ToString());\n return;\n }\n\n \/\/ This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail\n \/\/ immediately after the sync thread catches up and sets m_synced. Consider the case where\n \/\/ there is a reorg and the blocks on the stale branch are in the ValidationInterface queue\n \/\/ backlog even after the sync thread has caught up to the new chain tip. In this unlikely\n \/\/ event, log a warning and let the queue clear.\n const CBlockIndex* best_block_index = m_best_block_index.load();\n if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) {\n LogPrintf(\"%s: WARNING: Locator contains block (hash=%s) not on known best \" \/* Continued *\/\n \"chain (tip=%s); not writing index locator\\n\",\n __func__, locator_tip_hash.ToString(),\n best_block_index->GetBlockHash().ToString());\n return;\n }\n\n \/\/ No need to handle errors in Commit. If it fails, the error will be already be logged. The\n \/\/ best way to recover is to continue, as index cannot be corrupted by a missed commit to disk\n \/\/ for an advanced index state.\n Commit();\n}\n\nbool BaseIndex::BlockUntilSyncedToCurrentChain() const\n{\n AssertLockNotHeld(cs_main);\n\n if (!m_synced) {\n return false;\n }\n\n {\n \/\/ Skip the queue-draining stuff if we know we're caught up with\n \/\/ m_chain.Tip().\n LOCK(cs_main);\n const CBlockIndex* chain_tip = m_chainstate->m_chain.Tip();\n const CBlockIndex* best_block_index = m_best_block_index.load();\n if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) {\n return true;\n }\n }\n\n LogPrintf(\"%s: %s is catching up on block notifications\\n\", __func__, GetName());\n SyncWithValidationInterfaceQueue();\n return true;\n}\n\nvoid BaseIndex::Interrupt()\n{\n m_interrupt();\n}\n\nbool BaseIndex::Start(CChainState& active_chainstate)\n{\n m_chainstate = &active_chainstate;\n \/\/ Need to register this ValidationInterface before running Init(), so that\n \/\/ callbacks are not missed if Init sets m_synced to true.\n RegisterValidationInterface(this);\n if (!Init()) {\n return false;\n }\n\n m_thread_sync = std::thread(&util::TraceThread, GetName(), [this] { ThreadSync(); });\n return true;\n}\n\nvoid BaseIndex::Stop()\n{\n UnregisterValidationInterface(this);\n\n if (m_thread_sync.joinable()) {\n m_thread_sync.join();\n }\n}\n\nIndexSummary BaseIndex::GetSummary() const\n{\n IndexSummary summary{};\n summary.name = GetName();\n summary.synced = m_synced;\n summary.best_block_height = m_best_block_index ? m_best_block_index.load()->nHeight : 0;\n return summary;\n}\n\nvoid BaseIndex::SetBestBlockIndex(const CBlockIndex* block) {\n assert(!node::fPruneMode || AllowPrune());\n\n m_best_block_index = block;\n if (AllowPrune() && block) {\n node::PruneLockInfo prune_lock;\n prune_lock.height_first = block->nHeight;\n WITH_LOCK(::cs_main, m_chainstate->m_blockman.UpdatePruneLock(GetName(), prune_lock));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Ingen.\n * Copyright 2007-2011 David Robillard <http:\/\/drobilla.net>\n *\n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n *\n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for 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 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <signal.h>\n#include <stdlib.h>\n#include <time.h>\n\n#include <iostream>\n#include <string>\n\n#include <boost\/optional.hpp>\n\n#include <glibmm\/convert.h>\n#include <glibmm\/miscutils.h>\n#include <glibmm\/thread.h>\n\n#include \"raul\/Configuration.hpp\"\n#include \"raul\/Path.hpp\"\n#include \"raul\/SharedPtr.hpp\"\n#include \"raul\/Thread.hpp\"\n#include \"raul\/log.hpp\"\n\n#include \"serd\/serd.h\"\n#include \"sord\/sordmm.hpp\"\n\n#include \"ingen-config.h\"\n\n#include \"ingen\/EngineBase.hpp\"\n#include \"ingen\/EngineInterface.hpp\"\n#include \"serialisation\/Parser.hpp\"\n#include \"shared\/Configuration.hpp\"\n#include \"shared\/World.hpp\"\n#include \"shared\/runtime_paths.hpp\"\n#ifdef WITH_BINDINGS\n#include \"bindings\/ingen_bindings.hpp\"\n#endif\n\nusing namespace std;\nusing namespace Raul;\nusing namespace Ingen;\n\nstatic const timespec main_rate = { 0, 125000000 }; \/\/ 1\/8 second\n\nIngen::Shared::World* world = NULL;\n\nvoid\ningen_interrupt(int)\n{\n\tcout << \"ingen: Interrupted\" << endl;\n\tif (world->local_engine())\n\t\tworld->local_engine()->quit();\n\tdelete world;\n\texit(EXIT_FAILURE);\n}\n\nvoid\ningen_try(bool cond, const char* msg)\n{\n\tif (!cond) {\n\t\tcerr << \"ingen: Error: \" << msg << endl;\n\t\tdelete world;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\nint\nmain(int argc, char** argv)\n{\n\tShared::Configuration conf;\n\n\t\/\/ Parse command line options\n\ttry {\n\t\tconf.parse(argc, argv);\n\t} catch (std::exception& e) {\n\t\tcout << \"ingen: \" << e.what() << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ Verify option sanity\n\tif (argc <= 1) {\n\t\tconf.print_usage(\"ingen\", cout);\n\t\treturn EXIT_FAILURE;\n\t} else if (conf.option(\"help\").get_bool()) {\n\t\tconf.print_usage(\"ingen\", cout);\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\t\/\/ Set bundle path from executable location so resources can be found\n\tShared::set_bundle_path_from_code((void*)&main);\n\n\tSharedPtr<EngineInterface> engine_interface;\n\n\tGlib::thread_init();\n#if HAVE_SOUP\n\tg_type_init();\n#endif\n\n\tIngen::Shared::World* world = new Ingen::Shared::World(&conf, argc, argv);\n\n#if INGEN_JACK_SESSION\n\tif (conf.option(\"uuid\").get_string()) {\n\t\tworld->set_jack_uuid(conf.option(\"uuid\").get_string());\n\t}\n#endif\n\n\t\/\/ Run engine\n\tif (conf.option(\"engine\").get_bool()) {\n\t\tingen_try(world->load_module(\"engine\"),\n\t\t \"Unable to load engine module\");\n\n\t\tingen_try(world->local_engine(),\n\t\t \"Unable to create engine\");\n\n\t\tengine_interface = world->engine();\n\n\t\t\/\/ Not loading a GUI, load network engine interfaces\n\t\tif (!conf.option(\"gui\").get_bool()) {\n\t\t\t#ifdef HAVE_LIBLO\n\t\t\tingen_try(world->load_module(\"osc\"),\n\t\t\t \"Unable to load OSC module\");\n\t\t\t#endif\n\t\t\t#ifdef HAVE_SOUP\n\t\t\tingen_try(world->load_module(\"http\"),\n\t\t\t \"Unable to load HTTP module\");\n\t\t\t#endif\n\t\t}\n\t}\n\n\t\/\/ If we don't have a local engine interface (for GUI), use network\n\tif (!engine_interface) {\n\t\tconst char* const uri = conf.option(\"connect\").get_string();\n\t\tingen_try((engine_interface = world->interface(uri)),\n\t\t (string(\"Unable to create interface to `\") + uri + \"'\").c_str());\n\t}\n\n\t\/\/ Activate the engine, if we have one\n\tif (world->local_engine()) {\n\t\tingen_try(world->load_module(\"jack\"),\n\t\t \"Unable to load jack module\");\n\t}\n\n\tworld->set_engine(engine_interface);\n\n\t\/\/ Load a patch\n\tif (conf.option(\"load\").is_valid() && engine_interface) {\n\t\tboost::optional<Path> parent;\n\t\tboost::optional<Symbol> symbol;\n\t\tconst Raul::Atom& path_option = conf.option(\"path\");\n\n\t\tif (path_option.is_valid()) {\n\t\t\tif (Path::is_valid(path_option.get_string())) {\n\t\t\t\tconst Path p(path_option.get_string());\n\t\t\t\tif (!p.is_root()) {\n\t\t\t\t\tparent = p.parent();\n\t\t\t\t\tsymbol = p.symbol();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcerr << \"Invalid path given: '\" << path_option << endl;\n\t\t\t}\n\t\t}\n\n\t\tingen_try(world->load_module(\"serialisation\"),\n\t\t \"Unable to load serialisation module\");\n\n\t\tingen_try(world->parser(),\n\t\t \"Unable to create parser\");\n\n\t\tstring uri = conf.option(\"load\").get_string();\n\t\tif (!serd_uri_string_has_scheme((const uint8_t*)uri.c_str())) {\n\t\t\t\/\/ Does not start with legal URI scheme, assume path\n\t\t\turi = Glib::filename_to_uri(\n\t\t\t\t(Glib::path_is_absolute(uri))\n\t\t\t\t? uri\n\t\t\t\t: Glib::build_filename(Glib::get_current_dir(), uri));\n\t\t}\n\n\t\tengine_interface->get(\"ingen:plugins\");\n\t\tworld->parser()->parse_file(\n\t\t\tworld, engine_interface.get(), uri, parent, symbol);\n\t}\n\n\t\/\/ Load GUI\n\tif (conf.option(\"gui\").get_bool())\n\t\tingen_try(world->load_module(\"gui\"),\n\t\t \"Unable to load GUI module\");\n\n\t\/\/ Run a script\n\tif (conf.option(\"run\").is_valid()) {\n#ifdef WITH_BINDINGS\n\t\tingen_try(world->load_module(\"bindings\"),\n\t\t \"Unable to load bindings module\");\n\n\t\tworld->run(\"application\/x-python\", conf.option(\"run\").get_string());\n#else\n\t\tcerr << \"This build of ingen does not support scripting.\" << endl;\n#endif\n\n\t\/\/ Run main loop\n\t} else if (world->local_engine() && !conf.option(\"gui\").get_bool()) {\n\t\t\/\/ Set up signal handlers that will set quit_flag on interrupt\n\t\tsignal(SIGINT, ingen_interrupt);\n\t\tsignal(SIGTERM, ingen_interrupt);\n\n\t\t\/\/ Activate the enginie\n\t\tworld->local_engine()->activate();\n\n\t\t\/\/ Run engine main loop until interrupt\n\t\twhile (world->local_engine()->main_iteration()) {\n\t\t\tnanosleep(&main_rate, NULL);\n\t\t}\n\t\tinfo << \"Finished main loop\" << endl;\n\n\t\tworld->local_engine()->deactivate();\n\t}\n\n\t\/\/ Shut down\n\tif (world->local_engine())\n\t\tworld->local_engine()->deactivate();\n\n\tdelete world;\n\n\treturn 0;\n}\n\n<commit_msg>Initialise client module when necessary (partially fix OSC\/HTTP).<commit_after>\/* This file is part of Ingen.\n * Copyright 2007-2011 David Robillard <http:\/\/drobilla.net>\n *\n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n *\n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for 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 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <signal.h>\n#include <stdlib.h>\n#include <time.h>\n\n#include <iostream>\n#include <string>\n\n#include <boost\/optional.hpp>\n\n#include <glibmm\/convert.h>\n#include <glibmm\/miscutils.h>\n#include <glibmm\/thread.h>\n\n#include \"raul\/Configuration.hpp\"\n#include \"raul\/Path.hpp\"\n#include \"raul\/SharedPtr.hpp\"\n#include \"raul\/Thread.hpp\"\n#include \"raul\/log.hpp\"\n\n#include \"serd\/serd.h\"\n#include \"sord\/sordmm.hpp\"\n\n#include \"ingen-config.h\"\n\n#include \"ingen\/EngineBase.hpp\"\n#include \"ingen\/EngineInterface.hpp\"\n#include \"serialisation\/Parser.hpp\"\n#include \"shared\/Configuration.hpp\"\n#include \"shared\/World.hpp\"\n#include \"shared\/runtime_paths.hpp\"\n#ifdef WITH_BINDINGS\n#include \"bindings\/ingen_bindings.hpp\"\n#endif\n\nusing namespace std;\nusing namespace Raul;\nusing namespace Ingen;\n\nstatic const timespec main_rate = { 0, 125000000 }; \/\/ 1\/8 second\n\nIngen::Shared::World* world = NULL;\n\nvoid\ningen_interrupt(int)\n{\n\tcout << \"ingen: Interrupted\" << endl;\n\tif (world->local_engine())\n\t\tworld->local_engine()->quit();\n\tdelete world;\n\texit(EXIT_FAILURE);\n}\n\nvoid\ningen_try(bool cond, const char* msg)\n{\n\tif (!cond) {\n\t\tcerr << \"ingen: Error: \" << msg << endl;\n\t\tdelete world;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\nint\nmain(int argc, char** argv)\n{\n\tShared::Configuration conf;\n\n\t\/\/ Parse command line options\n\ttry {\n\t\tconf.parse(argc, argv);\n\t} catch (std::exception& e) {\n\t\tcout << \"ingen: \" << e.what() << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ Verify option sanity\n\tif (argc <= 1) {\n\t\tconf.print_usage(\"ingen\", cout);\n\t\treturn EXIT_FAILURE;\n\t} else if (conf.option(\"help\").get_bool()) {\n\t\tconf.print_usage(\"ingen\", cout);\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\t\/\/ Set bundle path from executable location so resources can be found\n\tShared::set_bundle_path_from_code((void*)&main);\n\n\tSharedPtr<EngineInterface> engine_interface;\n\n\tGlib::thread_init();\n#if HAVE_SOUP\n\tg_type_init();\n#endif\n\n\tIngen::Shared::World* world = new Ingen::Shared::World(&conf, argc, argv);\n\n#if INGEN_JACK_SESSION\n\tif (conf.option(\"uuid\").get_string()) {\n\t\tworld->set_jack_uuid(conf.option(\"uuid\").get_string());\n\t}\n#endif\n\n\t\/\/ Run engine\n\tif (conf.option(\"engine\").get_bool()) {\n\t\tingen_try(world->load_module(\"engine\"),\n\t\t \"Unable to load engine module\");\n\n\t\tingen_try(world->local_engine(),\n\t\t \"Unable to create engine\");\n\n\t\tengine_interface = world->engine();\n\n\t\t\/\/ Not loading a GUI, load network engine interfaces\n\t\tif (!conf.option(\"gui\").get_bool()) {\n\t\t\t#ifdef HAVE_LIBLO\n\t\t\tingen_try(world->load_module(\"osc\"),\n\t\t\t \"Unable to load OSC module\");\n\t\t\t#endif\n\t\t\t#ifdef HAVE_SOUP\n\t\t\tingen_try(world->load_module(\"http\"),\n\t\t\t \"Unable to load HTTP module\");\n\t\t\t#endif\n\t\t}\n\t}\n\n\t\/\/ If we don't have a local engine interface (for GUI), use network\n\tif (!engine_interface) {\n\t\tingen_try(world->load_module(\"client\"),\n\t\t \"Unable to load client module\");\n\t\tconst char* const uri = conf.option(\"connect\").get_string();\n\t\tingen_try((engine_interface = world->interface(uri)),\n\t\t (string(\"Unable to create interface to `\") + uri + \"'\").c_str());\n\t}\n\n\t\/\/ Activate the engine, if we have one\n\tif (world->local_engine()) {\n\t\tingen_try(world->load_module(\"jack\"),\n\t\t \"Unable to load jack module\");\n\t}\n\n\tworld->set_engine(engine_interface);\n\n\t\/\/ Load a patch\n\tif (conf.option(\"load\").is_valid() && engine_interface) {\n\t\tboost::optional<Path> parent;\n\t\tboost::optional<Symbol> symbol;\n\t\tconst Raul::Atom& path_option = conf.option(\"path\");\n\n\t\tif (path_option.is_valid()) {\n\t\t\tif (Path::is_valid(path_option.get_string())) {\n\t\t\t\tconst Path p(path_option.get_string());\n\t\t\t\tif (!p.is_root()) {\n\t\t\t\t\tparent = p.parent();\n\t\t\t\t\tsymbol = p.symbol();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcerr << \"Invalid path given: '\" << path_option << endl;\n\t\t\t}\n\t\t}\n\n\t\tingen_try(world->load_module(\"serialisation\"),\n\t\t \"Unable to load serialisation module\");\n\n\t\tingen_try(world->parser(),\n\t\t \"Unable to create parser\");\n\n\t\tstring uri = conf.option(\"load\").get_string();\n\t\tif (!serd_uri_string_has_scheme((const uint8_t*)uri.c_str())) {\n\t\t\t\/\/ Does not start with legal URI scheme, assume path\n\t\t\turi = Glib::filename_to_uri(\n\t\t\t\t(Glib::path_is_absolute(uri))\n\t\t\t\t? uri\n\t\t\t\t: Glib::build_filename(Glib::get_current_dir(), uri));\n\t\t}\n\n\t\tengine_interface->get(\"ingen:plugins\");\n\t\tworld->parser()->parse_file(\n\t\t\tworld, engine_interface.get(), uri, parent, symbol);\n\t}\n\n\t\/\/ Load GUI\n\tif (conf.option(\"gui\").get_bool())\n\t\tingen_try(world->load_module(\"gui\"),\n\t\t \"Unable to load GUI module\");\n\n\t\/\/ Run a script\n\tif (conf.option(\"run\").is_valid()) {\n#ifdef WITH_BINDINGS\n\t\tingen_try(world->load_module(\"bindings\"),\n\t\t \"Unable to load bindings module\");\n\n\t\tworld->run(\"application\/x-python\", conf.option(\"run\").get_string());\n#else\n\t\tcerr << \"This build of ingen does not support scripting.\" << endl;\n#endif\n\n\t\/\/ Run main loop\n\t} else if (world->local_engine() && !conf.option(\"gui\").get_bool()) {\n\t\t\/\/ Set up signal handlers that will set quit_flag on interrupt\n\t\tsignal(SIGINT, ingen_interrupt);\n\t\tsignal(SIGTERM, ingen_interrupt);\n\n\t\t\/\/ Activate the enginie\n\t\tworld->local_engine()->activate();\n\n\t\t\/\/ Run engine main loop until interrupt\n\t\twhile (world->local_engine()->main_iteration()) {\n\t\t\tnanosleep(&main_rate, NULL);\n\t\t}\n\t\tinfo << \"Finished main loop\" << endl;\n\n\t\tworld->local_engine()->deactivate();\n\t}\n\n\t\/\/ Shut down\n\tif (world->local_engine())\n\t\tworld->local_engine()->deactivate();\n\n\tdelete world;\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Accepts input with a list of urls and the included text, as:\n url1 word1 word2...\n url2 word1 word2...\n url3 ...\n ...\n\n And organizes them into a map of strings and heaps, the heap containing the\n all the urls in which that word occurs and their frequencies.\n*\/\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <unordered_map>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include \"Indexer.h\"\n\nusing namespace std;\n\nIndexer::Indexer(){}\n\nvoid Indexer::initializeIndex(){\n string url_line;\n string url;\n string word;\n istringstream ss;\n unordered_map<string, unsigned int> frequency;\n\n while (!cin.eof()) {\n\n \/\/ get url followed by all the words\n getline(cin, url_line);\n ss.str(url_line);\n ss >> url;\n\n while (ss >> word) {\n \/\/ count the frequency of each word\n if (frequency.find(word) == frequency.end()) {\n if (indexer.find(word) == indexer.end()) {\n URLheap heap;\n indexer[word] = heap;\n \/\/ make a new heap since the word is not in our indexer\n }\n frequency[word] = 1;\n } else {\n frequency[word] += 1;\n }\n }\n\n \/\/ add those frequency pairs to the wolrd indexer\n for (auto it = frequency.begin(); it != frequency.end(); it++) {\n indexer[it->first].push_back(pair<string, unsigned int>(url, it->second));\n push_heap(indexer[it->first].begin(), indexer[it->first].end(), index_sort());\n }\n\n url_line.clear();\n url.clear();\n ss.clear();\n frequency.clear();\n\n }\n}\n\nunordered_map<string, URLheap > Indexer::getIndexer(){\n return indexer;\n}\n\nvoid Indexer::toFile() {\n\tofstream mapFileStream;\n\tmapFileStream.open(\"mapFile.txt\");\n\tfor(auto it = indexer.begin(); it != indexer.end(); it++)\n\t{\n\t\tmapFileStream << it->first << \" \";\n\t\tfor(auto it2 = it->second.begin(); it2 != it->second.end(); it2++)\n\t\t{\n\t\t\tmapFileStream << it2->first << \" \" << it2->second << \" \";\n\t\t}\n\t\tmapFileStream << endl;\n\t}\n\tmapFileStream.close();\n}\n\n\/\/make_map() { }\n\/\/\n\/\/reduce_map() { }\n\/\/\n<commit_msg>Just added a file stream in Indexer<commit_after>\/*\n Accepts input with a list of urls and the included text, as:\n url1 word1 word2...\n url2 word1 word2...\n url3 ...\n ...\n\n And organizes them into a map of strings and heaps, the heap containing the\n all the urls in which that word occurs and their frequencies.\n*\/\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <unordered_map>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include \"Indexer.h\"\n\nusing namespace std;\n\nIndexer::Indexer(){}\n\nvoid Indexer::initializeIndex(){\n string url_line;\n string url;\n string word;\n istringstream ss;\n ifstream fs;\n fin.open(\".urlText.txt\")\n unordered_map<string, unsigned int> frequency;\n\n while (!fin.eof()) {\n\n \/\/ get url followed by all the words\n getline(fin, url_line);\n ss.str(url_line);\n ss >> url;\n\n while (ss >> word) {\n \/\/ count the frequency of each word\n if (frequency.find(word) == frequency.end()) {\n\t\t\/*\n if (indexer.find(word) == indexer.end()) {\n URLheap heap;\n indexer[word] = heap;\n \/\/ make a new heap since the word is not in our indexer\n }\n\t\t*\/\n frequency[word] = 1;\n } else {\n frequency[word] += 1;\n }\n }\n\n \/\/ add those frequency pairs to the wolrd indexer\n for (auto it = frequency.begin(); it != frequency.end(); it++) {\n indexer[it->first].push_back(pair<string, unsigned int>(url, it->second));\n push_heap(indexer[it->first].begin(), indexer[it->first].end(), index_sort());\n }\n\n url_line.clear();\n url.clear();\n ss.clear();\n frequency.clear();\n\n }\n}\n\nunordered_map<string, URLheap > Indexer::getIndexer(){\n return indexer;\n}\n\nvoid Indexer::toFile() {\n\tofstream mapFileStream;\n\tmapFileStream.open(\"mapFile.txt\");\n\tfor(auto it = indexer.begin(); it != indexer.end(); it++)\n\t{\n\t\tmapFileStream << it->first << \" \";\n\t\tfor(auto it2 = it->second.begin(); it2 != it->second.end(); it2++)\n\t\t{\n\t\t\tmapFileStream << it2->first << \" \" << it2->second << \" \";\n\t\t}\n\t\tmapFileStream << endl;\n\t}\n\tmapFileStream.close();\n}\n\n\/\/make_map() { }\n\/\/\n\/\/reduce_map() { }\n\/\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file LexLisp.cxx\n ** Lexer for Lisp.\n ** Written by Alexey Yutkin.\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <stdarg.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n\nstatic inline bool isLispoperator(char ch) {\n\tif (isascii(ch) && isalnum(ch))\n\t\treturn false;\n\tif (ch == '\\'' || ch == '(' || ch == ')' )\n\t\treturn true;\n\treturn false;\n}\n\nstatic inline bool isLispwordstart(char ch) {\n\treturn isascii(ch) && ch != ';' && !isspacechar(ch) && !isLispoperator(ch) &&\n\t\tch != '\\n' && ch != '\\r' && ch != '\\\"';\n}\n\n\nstatic void classifyWordLisp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {\n\tPLATFORM_ASSERT(end >= start);\n\tchar s[100];\n\tunsigned int i;\n\tbool digit_flag = true;\n\tfor (i = 0; (i < end - start + 1) && (i < 99); i++) {\n\t\ts[i] = styler[start + i];\n\t\ts[i + 1] = '\\0';\n\t\tif (!isdigit(s[i]) && (s[i] != '.')) digit_flag = false;\n\t}\n\tchar chAttr = SCE_LISP_IDENTIFIER;\n\n\tif(digit_flag) chAttr = SCE_LISP_NUMBER;\n\telse {\n\t\tif (keywords.InList(s)) {\n\t\t\tchAttr = SCE_LISP_KEYWORD;\n\t\t}\n\t}\n\tstyler.ColourTo(end, chAttr);\n\treturn;\n}\n\n\nstatic void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],\n Accessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\n\tstyler.StartAt(startPos);\n\n\tint state = initStyle;\n\tchar chNext = styler[startPos];\n\tunsigned int lengthDoc = startPos + length;\n\tstyler.StartSegment(startPos);\n\tfor (unsigned int i = startPos; i < lengthDoc; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\n\t\tif (styler.IsLeadByte(ch)) {\n\t\t\tchNext = styler.SafeGetCharAt(i + 2);\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (state == SCE_LISP_DEFAULT) {\n\t\t\tif (isLispwordstart(ch)) {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstate = SCE_LISP_IDENTIFIER;\n\t\t\t}\n\t\t\telse if (ch == ';') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstate = SCE_LISP_COMMENT;\n\t\t\t}\n\t\t\telse if (isLispoperator(ch) || ch=='\\'') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstyler.ColourTo(i, SCE_LISP_OPERATOR);\n\t\t\t}\n\t\t\telse if (ch == '\\\"') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstate = SCE_LISP_STRING;\n\t\t\t}\n\t\t} else if (state == SCE_LISP_IDENTIFIER) {\n\t\t\tif (!isLispwordstart(ch)) {\n\t\t\t\tclassifyWordLisp(styler.GetStartSegment(), i - 1, keywords, styler);\n\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t} \/*else*\/\n\t\t\tif (isLispoperator(ch) || ch=='\\'') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstyler.ColourTo(i, SCE_LISP_OPERATOR);\n\t\t\t}\n\n\t\t} else {\n\t\t\tif (state == SCE_LISP_COMMENT) {\n\t\t\t\tif (atEOL) {\n\t\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t\t}\n\t\t\t} else if (state == SCE_LISP_STRING) {\n\t\t\t\tif (ch == '\\\\') {\n\t\t\t\t\tif (chNext == '\\\"' || chNext == '\\'' || chNext == '\\\\') {\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\t\t\t\t}\n\t\t\t\t} else if (ch == '\\\"') {\n\t\t\t\t\tstyler.ColourTo(i, state);\n\t\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\tstyler.ColourTo(lengthDoc - 1, state);\n}\n\nstatic void FoldLispDoc(unsigned int startPos, int length, int \/* initStyle *\/, WordList *[],\n Accessor &styler) {\n\tunsigned int lengthDoc = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tchar chNext = styler[startPos];\n\tint styleNext = styler.StyleAt(startPos);\n\tfor (unsigned int i = startPos; i < lengthDoc; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint style = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (style == SCE_LISP_OPERATOR) {\n\t\t\tif (ch == '(') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == ')') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\t\tif (atEOL) {\n\t\t\tint lev = levelPrev;\n\t\t\tif (visibleChars == 0)\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\tif ((levelCurrent > levelPrev) && (visibleChars > 0))\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch))\n\t\t\tvisibleChars++;\n\t}\n\t\/\/ Fill in the real level of the next line, keeping the current flags as they will be filled in later\n\tint flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;\n\tstyler.SetLevel(lineCurrent, levelPrev | flagsNext);\n}\n\nstatic const char * const lispWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nLexerModule lmLISP(SCLEX_LISP, ColouriseLispDoc, \"lisp\", FoldLispDoc, lispWordListDesc);\n<commit_msg>Patch from Michael Goffioul to Lisp adds SYMBOL, SPECIAL, and MULTI_COMMENT states and a second keyword set.<commit_after>\/\/ Scintilla source code edit control\n\/** @file LexLisp.cxx\n ** Lexer for Lisp.\n ** Written by Alexey Yutkin.\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <stdarg.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n#include \"StyleContext.h\"\n\n#define SCE_LISP_CHARACTER 29\n#define SCE_LISP_MACRO 30\n#define SCE_LISP_MACRO_DISPATCH 31\n\nstatic inline bool isLispoperator(char ch) {\n\tif (isascii(ch) && isalnum(ch))\n\t\treturn false;\n\tif (ch == '\\'' || ch == '`' || ch == '(' || ch == ')' )\n\t\treturn true;\n\treturn false;\n}\n\nstatic inline bool isLispwordstart(char ch) {\n\treturn isascii(ch) && ch != ';' && !isspacechar(ch) && !isLispoperator(ch) &&\n\t\tch != '\\n' && ch != '\\r' && ch != '\\\"';\n}\n\n\nstatic void classifyWordLisp(unsigned int start, unsigned int end, WordList &keywords, WordList &keywords_kw, Accessor &styler) {\n\tPLATFORM_ASSERT(end >= start);\n\tchar s[100];\n\tunsigned int i;\n\tbool digit_flag = true;\n\tfor (i = 0; (i < end - start + 1) && (i < 99); i++) {\n\t\ts[i] = styler[start + i];\n\t\ts[i + 1] = '\\0';\n\t\tif (!isdigit(s[i]) && (s[i] != '.')) digit_flag = false;\n\t}\n\tchar chAttr = SCE_LISP_IDENTIFIER;\n\n\tif(digit_flag) chAttr = SCE_LISP_NUMBER;\n\telse {\n\t\tif (keywords.InList(s)) {\n\t\t\tchAttr = SCE_LISP_KEYWORD;\n\t\t} else if (keywords_kw.InList(s)) {\n\t\t\tchAttr = SCE_LISP_KEYWORD_KW;\n\t\t} else if ((s[0] == '*' && s[i-1] == '*') ||\n\t\t\t (s[0] == '+' && s[i-1] == '+')) {\n\t\t\tchAttr = SCE_LISP_SPECIAL;\n\t\t}\n\t}\n\tstyler.ColourTo(end, chAttr);\n\treturn;\n}\n\n\nstatic void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],\n Accessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\tWordList &keywords_kw = *keywordlists[1];\n\n\tstyler.StartAt(startPos);\n\n\tint state = initStyle, radix = -1;\n\tchar chNext = styler[startPos];\n\tunsigned int lengthDoc = startPos + length;\n\tstyler.StartSegment(startPos);\n\tfor (unsigned int i = startPos; i < lengthDoc; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\n\t\tif (styler.IsLeadByte(ch)) {\n\t\t\tchNext = styler.SafeGetCharAt(i + 2);\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (state == SCE_LISP_DEFAULT) {\n\t\t\tif (ch == '#') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tradix = -1;\n\t\t\t\tstate = SCE_LISP_MACRO_DISPATCH;\n\t\t\t} else if (isLispwordstart(ch)) {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstate = SCE_LISP_IDENTIFIER;\n\t\t\t}\n\t\t\telse if (ch == ';') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstate = SCE_LISP_COMMENT;\n\t\t\t}\n\t\t\telse if (isLispoperator(ch) || ch=='\\'') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstyler.ColourTo(i, SCE_LISP_OPERATOR);\n\t\t\t\tif (ch=='\\'' && isLispwordstart(chNext)) {\n\t\t\t\t\tstate = SCE_LISP_SYMBOL;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ch == '\\\"') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstate = SCE_LISP_STRING;\n\t\t\t}\n\t\t} else if (state == SCE_LISP_IDENTIFIER || state == SCE_LISP_SYMBOL) {\n\t\t\tif (!isLispwordstart(ch)) {\n\t\t\t\tif (state == SCE_LISP_IDENTIFIER) {\n\t\t\t\t\tclassifyWordLisp(styler.GetStartSegment(), i - 1, keywords, keywords_kw, styler);\n\t\t\t\t} else {\n\t\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\t}\n\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t} \/*else*\/\n\t\t\tif (isLispoperator(ch) || ch=='\\'') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstyler.ColourTo(i, SCE_LISP_OPERATOR);\n\t\t\t\tif (ch=='\\'' && isLispwordstart(chNext)) {\n\t\t\t\t\tstate = SCE_LISP_SYMBOL;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (state == SCE_LISP_MACRO_DISPATCH) {\n\t\t\tif (!isdigit(ch)) {\n\t\t\t\tif (ch != 'r' && ch != 'R' && (i - styler.GetStartSegment()) > 1) {\n\t\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t\t} else {\n\t\t\t\t\tswitch (ch) {\n\t\t\t\t\t\tcase '|': state = SCE_LISP_MULTI_COMMENT; break;\n\t\t\t\t\t\tcase 'o':\n\t\t\t\t\t\tcase 'O': radix = 8; state = SCE_LISP_MACRO; break;\n\t\t\t\t\t\tcase 'x':\n\t\t\t\t\t\tcase 'X': radix = 16; state = SCE_LISP_MACRO; break;\n\t\t\t\t\t\tcase 'b':\n\t\t\t\t\t\tcase 'B': radix = 2; state = SCE_LISP_MACRO; break;\n\t\t\t\t\t\tcase '\\\\': state = SCE_LISP_CHARACTER; break;\n\t\t\t\t\t\tcase ':':\n\t\t\t\t\t\tcase '-':\n\t\t\t\t\t\tcase '+': state = SCE_LISP_MACRO; break;\n\t\t\t\t\t\tcase '\\'': if (isLispwordstart(chNext)) {\n\t\t\t\t\t\t\t\t state = SCE_LISP_SPECIAL;\n\t\t\t\t\t\t\t } else {\n\t\t\t\t\t\t\t\t styler.ColourTo(i - 1, SCE_LISP_DEFAULT);\n\t\t\t\t\t\t\t\t styler.ColourTo(i, SCE_LISP_OPERATOR);\n\t\t\t\t\t\t\t\t state = SCE_LISP_DEFAULT;\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t break;\n\t\t\t\t\t\tdefault: if (isLispoperator(ch)) {\n\t\t\t\t\t\t\t\t styler.ColourTo(i - 1, SCE_LISP_DEFAULT);\n\t\t\t\t\t\t\t\t styler.ColourTo(i, SCE_LISP_OPERATOR);\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t state = SCE_LISP_DEFAULT;\n\t\t\t\t\t\t\t break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (state == SCE_LISP_MACRO) {\n\t\t\tif (isLispwordstart(ch) && (radix == -1 || IsADigit(ch, radix))) {\n\t\t\t\tstate = SCE_LISP_SPECIAL;\n\t\t\t} else {\n\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t}\n\t\t} else if (state == SCE_LISP_CHARACTER) {\n\t\t\tif (isLispoperator(ch)) {\n\t\t\t\tstyler.ColourTo(i, SCE_LISP_SPECIAL);\n\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t} else if (isLispwordstart(ch)) {\n\t\t\t\tstyler.ColourTo(i, SCE_LISP_SPECIAL);\n\t\t\t\tstate = SCE_LISP_SPECIAL;\n\t\t\t} else {\n\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t}\n\t\t} else if (state == SCE_LISP_SPECIAL) {\n\t\t\tif (!isLispwordstart(ch) || (radix != -1 && !IsADigit(ch, radix))) {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t}\n\t\t\tif (isLispoperator(ch) || ch=='\\'') {\n\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\tstyler.ColourTo(i, SCE_LISP_OPERATOR);\n\t\t\t\tif (ch=='\\'' && isLispwordstart(chNext)) {\n\t\t\t\t\tstate = SCE_LISP_SYMBOL;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (state == SCE_LISP_COMMENT) {\n\t\t\t\tif (atEOL) {\n\t\t\t\t\tstyler.ColourTo(i - 1, state);\n\t\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t\t}\n\t\t\t} else if (state == SCE_LISP_MULTI_COMMENT) {\n\t\t\t\tif (ch == '|' && chNext == '#') {\n\t\t\t\t\ti++;\n\t\t\t\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\t\t\t\tstyler.ColourTo(i, state);\n\t\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t\t}\n\t\t\t} else if (state == SCE_LISP_STRING) {\n\t\t\t\tif (ch == '\\\\') {\n\t\t\t\t\tif (chNext == '\\\"' || chNext == '\\'' || chNext == '\\\\') {\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\t\t\t\t}\n\t\t\t\t} else if (ch == '\\\"') {\n\t\t\t\t\tstyler.ColourTo(i, state);\n\t\t\t\t\tstate = SCE_LISP_DEFAULT;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\tstyler.ColourTo(lengthDoc - 1, state);\n}\n\nstatic void FoldLispDoc(unsigned int startPos, int length, int \/* initStyle *\/, WordList *[],\n Accessor &styler) {\n\tunsigned int lengthDoc = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tchar chNext = styler[startPos];\n\tint styleNext = styler.StyleAt(startPos);\n\tfor (unsigned int i = startPos; i < lengthDoc; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint style = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (style == SCE_LISP_OPERATOR) {\n\t\t\tif (ch == '(') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == ')') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\t\tif (atEOL) {\n\t\t\tint lev = levelPrev;\n\t\t\tif (visibleChars == 0)\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\tif ((levelCurrent > levelPrev) && (visibleChars > 0))\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch))\n\t\t\tvisibleChars++;\n\t}\n\t\/\/ Fill in the real level of the next line, keeping the current flags as they will be filled in later\n\tint flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;\n\tstyler.SetLevel(lineCurrent, levelPrev | flagsNext);\n}\n\nstatic const char * const lispWordListDesc[] = {\n\t\"Functions and special operators\",\n\t\"Keywords\",\n\t0\n};\n\nLexerModule lmLISP(SCLEX_LISP, ColouriseLispDoc, \"lisp\", FoldLispDoc, lispWordListDesc);\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016-2017, Pavel Korozevtsev.\n\n#include <arpa\/inet.h>\n#include <fcntl.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n\n#include <cstdio>\n#include <cstring>\n\n#include <algorithm>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"include\/log.hpp\"\n#include \"include\/socket.hpp\"\n#include \"include\/utils.hpp\"\n\nnamespace pkr {\n\nint set_nonblock(int fd) {\n int flags = 1;\n#ifdef O_NONBLOCK\n if ((flags = fcntl(fd, F_GETFL, 0)) == -1) {\n flags = 0;\n }\n return fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n#else\n return ioctl(fd, FIOBIO, &flags);\n#endif\n}\n\nDescriptorRef::DescriptorRef(const FileDescriptor& fd)\n : Handler{fd.handler} {}\n\nDescriptorHolder::DescriptorHolder(DescriptorHolder&& other)\n : Handler{std::move(other.handler)} {\n other.handler = -1;\n}\n\nDescriptorHolder::DescriptorHolder(int h)\n : Handler{h} {}\n\nFileDescriptor::FileDescriptor(int h)\n : Handler{h} {\n if (handler < 0) {\n log.error(\"Invalid fildes\");\n } else {\n set_nonblock(handler);\n }\n}\n\nFileDescriptor::FileDescriptor(FileDescriptor&& other)\n : Handler{std::move(other.handler)} {\n other.handler = -1;\n}\n\nFileDescriptor::FileDescriptor(DescriptorHolder&& other)\n : Handler{std::move(other.handler)} {\n other.handler = -1;\n}\n\nFileDescriptor::~FileDescriptor() {\n if (handler != -1) {\n close(handler);\n }\n}\n\nssize_t FileDescriptor::read(char* dest, ssize_t nbyte) {\n ssize_t sz = 0;\n ssize_t len;\n do {\n len = ::read(handler, dest + sz, nbyte - sz);\n if (len > 0) {\n sz += len;\n }\n } while (sz < nbyte && len > 0);\n return sz;\n}\n\nssize_t FileDescriptor::write(const char* buf, ssize_t nbyte) {\n ssize_t sz = 0;\n ssize_t len;\n do {\n len = ::write(handler, buf + sz, nbyte - sz);\n if (len > 0) {\n sz += len;\n }\n } while (sz < nbyte && len > 0);\n return sz;\n}\n\nstd::string read(FileDescriptor& fd, size_t nbyte) {\n std::vector<char> buf(nbyte);\n const auto len = fd.read(buf.data(), nbyte);\n if (len <= 0) {\n log.message(\"Unable to read from socket\");\n }\n return {buf.data(), buf.data() + len};\n}\n\nssize_t write(FileDescriptor& fd, string_view buf) {\n return fd.write(buf.data(), buf.size());\n}\n\nDescriptorHolder make_server_socket(Port port) {\n DescriptorHolder serv(socket(AF_INET, SOCK_STREAM, 0));\n sockaddr_in address;\n address.sin_addr.s_addr = htonl(INADDR_ANY);\n address.sin_family = AF_INET;\n address.sin_port = htons(port);\n auto try_bind = [&address, &serv] {\n return bind(serv.handler, reinterpret_cast<const sockaddr*>(&address),\n sizeof(address)) == 0;\n };\n enum { tries = 8 };\n for (int i = 0; i < tries && !try_bind(); ++i) {\n log.message(\"Unable to create server socket on port \" +\n std::to_string(port) + \" (bind failed): \" +\n Logger::errstr());\n address.sin_port = htons(++port);\n }\n if (listen(serv.handler, SOMAXCONN) < 0) {\n log.fatal_error(\"Unable to create server socket (listen failed): \" +\n Logger::errstr());\n } else {\n log.print(\"Server socket was bound to port \" + std::to_string(port));\n }\n return serv;\n}\n\nint accept_client_helper(int serv_sock_fd) {\n sockaddr_in client_address;\n socklen_t client_address_size = sizeof(client_address);\n const auto new_client_handler =\n ::accept(serv_sock_fd, reinterpret_cast<sockaddr*>(&client_address),\n &client_address_size);\n if (new_client_handler >= 0) {\n char ip[INET_ADDRSTRLEN];\n inet_ntop(AF_INET, &client_address.sin_addr, ip, sizeof(ip));\n log.access(ip, ntohs(client_address.sin_port));\n }\n return new_client_handler;\n}\n\nDescriptorHolder accept_client(DescriptorRef serv_sock) {\n return {accept_client_helper(serv_sock.handler)};\n}\n\nssize_t write_failure(Socket& cls, int status, string_view msg) {\n char headers[256];\n snprintf(headers, sizeof(headers), \"HTTP\/1.0 %d %s\\r\\n\", status,\n msg.to_string().c_str());\n return write(cls, {headers, strlen(headers)});\n}\n\nssize_t write_response(Socket& cls, int status, size_t file_size) {\n char headers[256];\n snprintf(headers, sizeof(headers),\n \"HTTP\/1.0 %d OK\\r\\n\"\n \"Content-Length: %lu\\r\\n\"\n \"\\r\\n\",\n status, file_size);\n return write(cls, {headers, strlen(headers)});\n}\n\n} \/\/ namespace pkr\n<commit_msg>%lu -> %zu for size_t<commit_after>\/\/ Copyright 2016-2017, Pavel Korozevtsev.\n\n#include <arpa\/inet.h>\n#include <fcntl.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n\n#include <cstdio>\n#include <cstring>\n\n#include <algorithm>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"include\/log.hpp\"\n#include \"include\/socket.hpp\"\n#include \"include\/utils.hpp\"\n\nnamespace pkr {\n\nint set_nonblock(int fd) {\n int flags = 1;\n#ifdef O_NONBLOCK\n if ((flags = fcntl(fd, F_GETFL, 0)) == -1) {\n flags = 0;\n }\n return fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n#else\n return ioctl(fd, FIOBIO, &flags);\n#endif\n}\n\nDescriptorRef::DescriptorRef(const FileDescriptor& fd)\n : Handler{fd.handler} {}\n\nDescriptorHolder::DescriptorHolder(DescriptorHolder&& other)\n : Handler{std::move(other.handler)} {\n other.handler = -1;\n}\n\nDescriptorHolder::DescriptorHolder(int h)\n : Handler{h} {}\n\nFileDescriptor::FileDescriptor(int h)\n : Handler{h} {\n if (handler < 0) {\n log.error(\"Invalid fildes\");\n } else {\n set_nonblock(handler);\n }\n}\n\nFileDescriptor::FileDescriptor(FileDescriptor&& other)\n : Handler{std::move(other.handler)} {\n other.handler = -1;\n}\n\nFileDescriptor::FileDescriptor(DescriptorHolder&& other)\n : Handler{std::move(other.handler)} {\n other.handler = -1;\n}\n\nFileDescriptor::~FileDescriptor() {\n if (handler != -1) {\n close(handler);\n }\n}\n\nssize_t FileDescriptor::read(char* dest, ssize_t nbyte) {\n ssize_t sz = 0;\n ssize_t len;\n do {\n len = ::read(handler, dest + sz, nbyte - sz);\n if (len > 0) {\n sz += len;\n }\n } while (sz < nbyte && len > 0);\n return sz;\n}\n\nssize_t FileDescriptor::write(const char* buf, ssize_t nbyte) {\n ssize_t sz = 0;\n ssize_t len;\n do {\n len = ::write(handler, buf + sz, nbyte - sz);\n if (len > 0) {\n sz += len;\n }\n } while (sz < nbyte && len > 0);\n return sz;\n}\n\nstd::string read(FileDescriptor& fd, size_t nbyte) {\n std::vector<char> buf(nbyte);\n const auto len = fd.read(buf.data(), nbyte);\n if (len <= 0) {\n log.message(\"Unable to read from socket\");\n }\n return {buf.data(), buf.data() + len};\n}\n\nssize_t write(FileDescriptor& fd, string_view buf) {\n return fd.write(buf.data(), buf.size());\n}\n\nDescriptorHolder make_server_socket(Port port) {\n DescriptorHolder serv(socket(AF_INET, SOCK_STREAM, 0));\n sockaddr_in address;\n address.sin_addr.s_addr = htonl(INADDR_ANY);\n address.sin_family = AF_INET;\n address.sin_port = htons(port);\n auto try_bind = [&address, &serv] {\n return bind(serv.handler, reinterpret_cast<const sockaddr*>(&address),\n sizeof(address)) == 0;\n };\n enum { tries = 8 };\n for (int i = 0; i < tries && !try_bind(); ++i) {\n log.message(\"Unable to create server socket on port \" +\n std::to_string(port) + \" (bind failed): \" +\n Logger::errstr());\n address.sin_port = htons(++port);\n }\n if (listen(serv.handler, SOMAXCONN) < 0) {\n log.fatal_error(\"Unable to create server socket (listen failed): \" +\n Logger::errstr());\n } else {\n log.print(\"Server socket was bound to port \" + std::to_string(port));\n }\n return serv;\n}\n\nint accept_client_helper(int serv_sock_fd) {\n sockaddr_in client_address;\n socklen_t client_address_size = sizeof(client_address);\n const auto new_client_handler =\n ::accept(serv_sock_fd, reinterpret_cast<sockaddr*>(&client_address),\n &client_address_size);\n if (new_client_handler >= 0) {\n char ip[INET_ADDRSTRLEN];\n inet_ntop(AF_INET, &client_address.sin_addr, ip, sizeof(ip));\n log.access(ip, ntohs(client_address.sin_port));\n }\n return new_client_handler;\n}\n\nDescriptorHolder accept_client(DescriptorRef serv_sock) {\n return {accept_client_helper(serv_sock.handler)};\n}\n\nssize_t write_failure(Socket& cls, int status, string_view msg) {\n char headers[256];\n snprintf(headers, sizeof(headers), \"HTTP\/1.0 %d %s\\r\\n\", status,\n msg.to_string().c_str());\n return write(cls, {headers, strlen(headers)});\n}\n\nssize_t write_response(Socket& cls, int status, size_t file_size) {\n char headers[256];\n snprintf(headers, sizeof(headers),\n \"HTTP\/1.0 %d OK\\r\\n\"\n \"Content-Length: %zu\\r\\n\"\n \"\\r\\n\",\n status, file_size);\n return write(cls, {headers, strlen(headers)});\n}\n\n} \/\/ namespace pkr\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint main(int argc, char const *argv[]) {\n\n\treturn 0;\n}\n<commit_msg>adding<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#define MX 3001\nusing namespace std;\nstd::vector<int> G[MX];\nint main(int argc, char const *argv[]) {\n\tint n,m;\n\tcin>>n>>m;\n\tfor(int i=0;i<m;i++){\n\t\tint x,y;\n\t\tcin>>x>>y;\n\t\tG[x].push_back(y);\n\t}\n\tfor(int i=1;i<=n;i++){\n\t\tfor(int j=1;j<=n;j++){\n\t\t\tif(i==j) continue;\n\t\t\tfor(int k=0;k<G[i].size();k++){\n\t\t\t\tif(G[i][k]!= &&)\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dsa_common.h\"\n\n#include \"console_logger.h\"\n\n#include <iostream>\n#include <memory>\n#include \"util\/date_time.h\"\n\nnamespace dsa {\n\nvoid ConsoleLogger::write_meta(std::ostream& stream, const char* level) {\n const string_& ts = DateTime::get_ts();\n \/\/ use a substring of the timestamp\n stream << '[' << level << string_(&ts[5], &ts[23]) << \"] \";\n}\n\nvoid ConsoleLogger::log(const string_& str, uint8_t lvl) {\n if ((lvl & filter) || level == Logger::ALL___) {\n std::cout << str;\n std::cout.flush();\n }\n}\n}\n<commit_msg>keep year in the logger timestamp<commit_after>#include \"dsa_common.h\"\n\n#include \"console_logger.h\"\n\n#include <iostream>\n#include <memory>\n#include \"util\/date_time.h\"\n\nnamespace dsa {\n\nvoid ConsoleLogger::write_meta(std::ostream& stream, const char* level) {\n const string_& ts = DateTime::get_ts();\n \/\/ use a substring of the timestamp\n stream << '[' << level << string_(&ts[0], &ts[23]) << \"] \";\n}\n\nvoid ConsoleLogger::log(const string_& str, uint8_t lvl) {\n if ((lvl & filter) || level == Logger::ALL___) {\n std::cout << str;\n std::cout.flush();\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Alexis Giraudet\n\/\/ Théo Cesbron\n\n#ifndef HASH_TABLE_HPP\n#define HASH_TABLE_HPP\n\n#include <functional>\n#include \"map.hpp\"\n\n\/**\n * Classe hash_table: table de hachage\n * Implémentation avec tableau de dictionnaires.\n**\/\ntemplate <typename K, typename V, int S>\nclass hash_table\n{\n private:\n map<K,V> *_dictionaries;\n std::hash<K> _hash_fn; \n \n public:\n hash_table();\n ~hash_table();\n void clear();\n bool contains_key(const K& key) const;\n bool contains_value(const V& value) const;\n V get(const K& key) const;\n V& get_ref(const K& key) const;\n bool is_empty() const;\n K* keys_array() const;\n std::ostream& print() const;\n std::ostream& print(std::ostream& os) const;\n bool put(const K& key, const V& value);\n bool remove(const K& key);\n int size() const;\n void to_list(std::list< std::pair<K,V> >& ls) const;\n V* values_array() const;\n};\n\ntemplate <typename K, typename V, int S>\nhash_table<K,V,S>::hash_table(): _dictionaries(0)\n{\n _dictionaries = new map<K,V>[S];\n}\n\ntemplate <typename K, typename V, int S>\nhash_table<K,V,S>::~hash_table()\n{\n delete[] _dictionaries;\n}\n\n\/**\n * Vide la table de hachage.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nvoid hash_table<K,V,S>::clear()\n{\n for(int i=0; i<S; i++)\n {\n _dictionaries[i].clear();\n }\n}\n\n\/**\n * Retourne vrai si la table de hachage contient la clef key, retourne faux dans le cas contraire.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::contains_key(const K& key) const\n{\n size_t i = _hash_fn(key)%S;\n return _dictionaries[i].contains_key(key);\n}\n\n\/**\n * Retourne vrai si la table de hachage contient la valeur value, retourne faux dans le cas contraire.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::contains_value(const V& value) const\n{\n for(int i=0; i<S; i++)\n {\n if(_dictionaries[i].contains_value(value))\n {\n return true;\n }\n }\n return false;\n}\n\n\/**\n * Retourne la valeur associée à la clef key si la table de hachage contient la clef key, lève une exception dans le cas contraire.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nV hash_table<K,V,S>::get(const K& key) const\n{\n size_t i = _hash_fn(key)%S;\n return _dictionaries[i].get(key);\n}\n\n\/**\n * Retourne la référence de la valeur associée à la clef key si la table de hachage contient la clef key, lève une exception dans le cas contraire.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nV& hash_table<K,V,S>::get_ref(const K& key) const\n{\n size_t i = _hash_fn(key)%S;\n return _dictionaries[i].get(key);\n}\n\n\/**\n * Retourne vrai si la table de hachage est vide, retourne faux dans le cas contraire.\n * O(1)\n**\/\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::is_empty() const\n{\n for(int i=0; i<S; i++)\n {\n if(!_dictionaries[i].is_empty())\n {\n return false;\n }\n }\n return true;\n}\n\n\/**\n * Retourne un tableau contenant toutes les clefs de la table de hachage.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nK* hash_table<K,V,S>::keys_array() const\n{\n K *res = new K[size()];\n int i=0;\n for(int j=0; j<S; j++)\n {\n K *tmp = _dictionaries[j].keys_array();\n for(int k=0; k<_dictionaries[j].size(); k++)\n {\n res[i] = tmp[k];\n i++;\n }\n delete[] tmp;\n }\n return res;\n}\n\n\/**\n * Affiche la table de hachage sur la sortie standard.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nstd::ostream& hash_table<K,V,S>::print() const\n{\n return print(std::cout);\n}\n\n\/**\n * Affiche la table de hachage sur la sortie os.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nstd::ostream& hash_table<K,V,S>::print(std::ostream& os) const\n{\n for(int i=0; i<S; i++)\n {\n os << _dictionaries[i];\n }\n return os;\n}\n\n\/**\n * Ajoute un nouveau couple clef\/valeur a la table de hachage si celle-ci ne contient pas la clef key, si la table de hachage contient la clef key alors la valeur associée à la clef sera remplacée par value.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::put(const K& key, const V& value)\n{\n size_t i = _hash_fn(key)%S;\n return _dictionaries[i].put(key,value);\n}\n\n\/**\n * Supprime le couple clef\/valeur associé à la clef key de la table de hachage.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::remove(const K& key)\n{\n size_t i = _hash_fn(key)%S;\n return _dictionaries[i].remove(key);\n}\n\n\/**\n * Retourne la taille de la table de hachage.\n * \n**\/\ntemplate <typename K, typename V, int S>\nint hash_table<K,V,S>::size() const\n{\n int res=0;\n for(int i=0; i<S; i++)\n {\n res += _dictionaries[i].size();\n }\n return res;\n}\n\ntemplate <typename K, typename V, int S>\nvoid hash_table<K,V,S>::to_list(std::list< std::pair<K,V> >& ls) const\n{\n for(int i=0; i<S; i++)\n {\n _dictionaries[i].to_list(ls);\n }\n}\n\n\/**\n * Retourne un tableau contenant toutes les valeurs de la table de hachage.\n * O(n)\n**\/\ntemplate <typename K, typename V, int S>\nV* hash_table<K,V,S>::values_array() const\n{\n V *res = new V[size()];\n int i=0;\n for(int j=0; j<S; j++)\n {\n V *tmp = _dictionaries[j].values_array();\n for(int k=0; k<_dictionaries[j].size(); k++)\n {\n res[i] = tmp[k];\n i++;\n }\n delete[] tmp;\n }\n return res;\n}\n\n\/**\n * Définition de l'opérateur << pour gérer les flux.\n**\/\ntemplate <typename K, typename V, int S>\nstd::ostream& operator<<(std::ostream& os, const hash_table<K,V,S>& m)\n{\n return m.print(os);\n}\n\n#endif\n<commit_msg>add doxigen and clear code<commit_after>\/*!\n * \\file hash_table.hpp\n * \\brief Classe hash_table\n * \\author Alexis Giraudet\n * \\author Théo Cesbron\n * \\version 1.0\n * \\date 18 avril 2014\n *\/\n\n#ifndef HASH_TABLE_HPP\n#define HASH_TABLE_HPP\n\n#include <functional>\n#include \"map.hpp\"\n\n\/*!\n * \\class map\n * \\brief Implémentation générique d'une table de hachage avec taleaux associatifs. K le type des clefs, V le type des valeurs et S le nombre de maps.\n *\/\ntemplate <typename K, typename V, int S>\nclass hash_table\n{\n private:\n map<K,V>* _data;\n std::hash<K> _hash_fn; \n \n public:\n \/*!\n * \\brief Constructeur. O(1)\n *\/\n hash_table();\n\n \/*!\n * \\brief Destructeur. O(n)\n *\/\n ~hash_table();\n\n \/*!\n * \\brief Vide la hash_table. O(n)\n *\/\n void clear();\n\n \/*!\n * \\brief Retourne vrai si la hash_table contient la clef key, retourne faux dans le cas contraire. O(n)\n * \\param key : la clef recherchée\n * \\return vrai si la hash_table contient la clef key, sinon faux\n *\/\n bool contains_key(const K& key) const;\n\n \/*!\n * \\brief Retourne vrai si la hash_table contient la valeur value, retourne faux dans le cas contraire. O(n)\n * \\param value : la valeur recherchée\n * \\return vrai si la hash_table contient la valeur value, sinon faux\n *\/\n bool contains_value(const V& value) const;\n\n \/*!\n * \\brief Retourne la valeur associée à la clef key si la hash_table contient la clef key, lève une exception dans le cas contraire. O(n)\n * \\param key : la clef\n * \\return la valeur associée à la clef key\n *\/\n V get(const K& key) const;\n\n \/*!\n * \\brief Retourne la référence de la valeur associée à la clef key si la hash_table contient la clef key, lève une exception dans le cas contraire. O(n)\n * \\param key : la clef\n * \\return la référence de la valeur associée à la clef key\n *\/\n V& get_ref(const K& key) const;\n\n \/*!\n * \\brief Retourne vrai si la hash_table est vide, retourne faux dans le cas contraire. O(1)\n * \\return vrai si la hash_table est vide, sinon faux\n *\/\n bool is_empty() const;\n\n \/*!\n * \\deprecated utiliser to_list()\n * \\brief Retourne un tableau contenant toutes les clefs de la hash_table. O(n)\n * \\return le tableau des clefs\n *\/\n K* keys_array() const;\n\n \/*!\n * \\brief Ajoute un nouveau couple clef-valeur à la hash_table si celle-ci ne contient pas la clef key, si la hash_table contient la clef key alors la valeur associée à la clef sera remplacée par value. O(n)\n * \\param key : la clef\n * \\param value : la valeur associée à la clef\n * \\return vrai si la clef n'était pas présente, sinon faux (la valeur précédente a été écrasée)\n *\/\n bool put(const K& key, const V& value);\n\n \/*!\n * \\brief Supprime le couple clef-valeur associé à la clef key de la hash_table. O(n)\n * \\param key : la clef à supprimer\n * \\return vrai si la clef et la valeur associée ont bien été supprimé, sinon faux\n *\/\n bool remove(const K& key);\n\n \/*!\n * \\brief Retourne la taille de la hash_table. O(1)\n * \\return la taille (le nombre de couples clef-valeur)\n *\/\n int size() const;\n\n \/*!\n * \\brief Charge les élément de la hash_table dans la liste passée en paramètre. O(n)\n * \\param ls : la liste où charger les couples clef-valeur\n *\/\n void to_list(std::list<std::pair<K,V> >& ls) const;\n\n \/*!\n * \\deprecated Utiliser to_list()\n * \\brief Retourne un tableau contenant toutes les valeurs de la hash_table. O(n)\n * \\return le tableau des valeurs\n *\/\n V* values_array() const;\n};\n\ntemplate <typename K, typename V, int S>\nhash_table<K,V,S>::hash_table(): _data(0)\n{\n _data = new map<K,V>[S];\n}\n\ntemplate <typename K, typename V, int S>\nhash_table<K,V,S>::~hash_table()\n{\n delete[] _data;\n}\n\ntemplate <typename K, typename V, int S>\nvoid hash_table<K,V,S>::clear()\n{\n for(int i=0; i<S; i++)\n {\n _data[i].clear();\n }\n}\n\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::contains_key(const K& key) const\n{\n return _data[_hash_fn(key)%S].contains_key(key);\n}\n\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::contains_value(const V& value) const\n{\n for(int i=0; i<S; i++)\n {\n if(_data[i].contains_value(value))\n {\n return true;\n }\n }\n return false;\n}\n\ntemplate <typename K, typename V, int S>\nV hash_table<K,V,S>::get(const K& key) const\n{\n return _data[_hash_fn(key)%S].get(key);\n}\n\ntemplate <typename K, typename V, int S>\nV& hash_table<K,V,S>::get_ref(const K& key) const\n{\n return _data[_hash_fn(key)%S].get(key);\n}\n\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::is_empty() const\n{\n for(int i=0; i<S; i++)\n {\n if(!_data[i].is_empty())\n {\n return false;\n }\n }\n return true;\n}\n\ntemplate <typename K, typename V, int S>\nK* hash_table<K,V,S>::keys_array() const\n{\n K *res = new K[size()];\n int i=0;\n for(int j=0; j<S; j++)\n {\n K *tmp = _data[j].keys_array();\n for(int k=0; k<_data[j].size(); k++)\n {\n res[i] = tmp[k];\n i++;\n }\n delete[] tmp;\n }\n return res;\n}\n\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::put(const K& key, const V& value)\n{\n return _data[_hash_fn(key)%S].put(key,value);\n}\n\ntemplate <typename K, typename V, int S>\nbool hash_table<K,V,S>::remove(const K& key)\n{\n return _data[_hash_fn(key)%S].remove(key);\n}\n\ntemplate <typename K, typename V, int S>\nint hash_table<K,V,S>::size() const\n{\n int res=0;\n for(int i=0; i<S; i++)\n {\n res += _data[i].size();\n }\n return res;\n}\n\ntemplate <typename K, typename V, int S>\nvoid hash_table<K,V,S>::to_list(std::list<std::pair<K,V> >& ls) const\n{\n for(int i=0; i<S; i++)\n {\n _data[i].to_list(ls);\n }\n}\n\ntemplate <typename K, typename V, int S>\nV* hash_table<K,V,S>::values_array() const\n{\n V *res = new V[size()];\n int i=0;\n for(int j=0; j<S; j++)\n {\n V *tmp = _data[j].values_array();\n for(int k=0; k<_data[j].size(); k++)\n {\n res[i] = tmp[k];\n i++;\n }\n delete[] tmp;\n }\n return res;\n}\n\n\/*!\n * \\brief Surchage de l'opérateur de flux pour afficher la map. O(n)\n * \\param os : le flux de sortie\n * \\param m : la map à afficher\n * \\return le flux de sortie\n *\/\ntemplate <typename K, typename V, int S>\nstd::ostream& operator<<(std::ostream& os, const hash_table<K,V,S>& ht)\n{\n std::list<std::pair<K,V> > ls;\n ht.to_list(ls);\n for(typename std::list<std::pair<K,V> >::iterator it=ls.begin(); it != ls.end(); it++)\n {\n os << (*it).first << \" : \" << (*it).second << std::endl;\n }\n return os;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <nix\/hdf5\/Group.hpp>\n\n#include <nix\/util\/util.hpp>\n\n#include <nix\/hdf5\/ExceptionHDF5.hpp>\n#include <nix\/hdf5\/hdf5include.hpp>\n\n\n\nnamespace nix {\nnamespace hdf5 {\n\noptGroup::optGroup(const Group &parent, const std::string &g_name)\n : parent(parent), g_name(g_name)\n{}\n\nboost::optional<Group> optGroup::operator() (bool create) const {\n if (parent.hasGroup(g_name)) {\n g = boost::optional<Group>(parent.openGroup(g_name));\n } else if (create) {\n g = boost::optional<Group>(parent.openGroup(g_name, true));\n }\n return g;\n}\n\n\nGroup::Group() : LocID() {}\n\n\nGroup::Group(hid_t hid) : LocID(hid) {}\n\n\nGroup::Group(const Group &other) : LocID(other) {}\n\n\nbool Group::hasObject(const std::string &name) const {\n \/\/ empty string should return false, not exception (which H5Lexists would)\n if (name.empty()) {\n return false;\n }\n\n HTri res = H5Lexists(hid, name.c_str(), H5P_DEFAULT);\n return res.check(\"Group::hasObject(): H5Lexists failed\");\n}\n\nbool Group::objectOfType(const std::string &name, H5O_type_t type) const {\n H5O_info_t info;\n\n hid_t obj = H5Oopen(hid, name.c_str(), H5P_DEFAULT);\n\n if (!H5Iis_valid(obj)) {\n return false;\n }\n\n HErr err = H5Oget_info(obj, &info);\n err.check(\"Could not obtain object info\");\n\n bool res = info.type == type;\n\n H5Oclose(obj);\n return res;\n}\n\nsize_t Group::objectCount() const {\n hsize_t n_objs;\n HErr res = H5Gget_num_objs(hid, &n_objs);\n res.check(\"Could not get object count\");\n return n_objs;\n}\n\n\nboost::optional<Group> Group::findGroupByAttribute(const std::string &attribute, const std::string &value) const {\n boost::optional<Group> ret;\n\n \/\/ look up first direct sub-group that has given attribute with given value\n for (size_t index = 0; index < objectCount(); index++) {\n std::string obj_name = objectName(index);\n if(hasGroup(obj_name)) {\n Group group = openGroup(obj_name, false);\n if(group.hasAttr(attribute)) {\n std::string attr_value;\n group.getAttr(attribute, attr_value);\n if (attr_value == value) {\n ret = group;\n break;\n }\n }\n }\n }\n\n return ret;\n}\n\n\nboost::optional<DataSet> Group::findDataByAttribute(const std::string &attribute, const std::string &value) const {\n std::vector<DataSet> dsets;\n boost::optional<DataSet> ret;\n\n \/\/ look up all direct sub-datasets that have the given attribute\n for (size_t index = 0; index < objectCount(); index++) {\n std::string obj_name = objectName(index);\n if(hasData(obj_name)) {\n DataSet ds = openData(obj_name);\n\n if (ds.hasAttr(attribute)) {\n dsets.push_back(ds);\n }\n }\n }\n \/\/ look for first dataset with given attribute set to given value\n auto found = std::find_if(dsets.begin(), dsets.end(),\n [value, attribute](DataSet &dset) {\n std::string attr_value;\n dset.getAttr(attribute, attr_value);\n return attr_value == value; });\n if(found != dsets.end()) ret = *found;\n\n return ret;\n}\n\n\nstd::string Group::objectName(size_t index) const {\n \/\/ check if index valid\n if(index > objectCount()) {\n throw OutOfBounds(\"No object at given index\", index);\n }\n\n std::string str_name;\n \/\/ check whether name is found by index\n ssize_t name_len = H5Lget_name_by_idx(hid,\n \".\",\n H5_INDEX_NAME,\n H5_ITER_NATIVE,\n (hsize_t) index,\n NULL,\n 0,\n H5P_DEFAULT);\n if (name_len > 0) {\n char* name = new char[name_len+1];\n name_len = H5Lget_name_by_idx(hid,\n \".\",\n H5_INDEX_NAME,\n H5_ITER_NATIVE,\n (hsize_t) index,\n name,\n name_len+1,\n H5P_DEFAULT);\n str_name = name;\n delete [] name;\n } else {\n throw H5Exception(\"objectName: No object found, H5Lget_name_by_idx returned no name\");\n }\n\n return str_name;\n}\n\n\nbool Group::hasData(const std::string &name) const {\n return hasObject(name) && objectOfType(name, H5O_TYPE_DATASET);\n}\n\n\nvoid Group::removeData(const std::string &name) {\n if (hasData(name)) {\n HErr res = H5Gunlink(hid, name.c_str());\n res.check(\"Group::removeData(): Could not unlink DataSet\");\n }\n}\n\nDataSet Group::createData(const std::string &name,\n DataType dtype,\n const NDSize &size) const\n{\n h5x::DataType fileType = data_type_to_h5_filetype(dtype);\n return createData(name, fileType, size);\n}\n\n\nDataSet Group::createData(const std::string &name,\n const h5x::DataType &fileType,\n const NDSize &size,\n const NDSize &maxsize,\n NDSize chunks,\n bool max_size_unlimited,\n bool guess_chunks) const\n{\n DataSpace space;\n\n if (size) {\n if (maxsize) {\n space = DataSpace::create(size, maxsize);\n } else {\n space = DataSpace::create(size, max_size_unlimited);\n }\n }\n\n BaseHDF5 dcpl = H5Pcreate(H5P_DATASET_CREATE);\n dcpl.check(\"Could not create data creation plist\");\n\n if (!chunks && guess_chunks) {\n chunks = DataSet::guessChunking(size, fileType.size());\n }\n\n if (chunks) {\n int rank = static_cast<int>(chunks.size());\n HErr res = H5Pset_chunk(dcpl.h5id(), rank, chunks.data());\n res.check(\"Could not set chunk size on data set creation plist\");\n }\n\n DataSet ds = H5Dcreate(hid, name.c_str(), fileType.h5id(), space.h5id(), H5P_DEFAULT, dcpl.h5id(), H5P_DEFAULT);\n ds.check(\"Group::createData: Could not create DataSet with name \" + name);\n\n return ds;\n}\n\n\nDataSet Group::openData(const std::string &name) const {\n DataSet ds = H5Dopen(hid, name.c_str(), H5P_DEFAULT);\n ds.check(\"Group::openData(): Could not open DataSet\");\n return ds;\n}\n\n\nbool Group::hasGroup(const std::string &name) const {\n return hasObject(name) && objectOfType(name, H5O_TYPE_GROUP);\n}\n\n\nGroup Group::openGroup(const std::string &name, bool create) const {\n if(!util::nameCheck(name)) throw InvalidName(\"openGroup\");\n Group g;\n if (hasGroup(name)) {\n g = Group(H5Gopen(hid, name.c_str(), H5P_DEFAULT));\n g.check(\"Group::openGroup(): Could not open group: \" + name);\n } else if (create) {\n hid_t gcpl = H5Pcreate(H5P_GROUP_CREATE);\n\n if (gcpl < 0) {\n throw H5Exception(\"Unable to create group with name '\" + name + \"'! (H5Pcreate)\");\n }\n\n \/\/we want hdf5 to keep track of the order in which links were created so that\n \/\/the order for indexed based accessors is stable cf. issue #387\n HErr res = H5Pset_link_creation_order(gcpl, H5P_CRT_ORDER_TRACKED|H5P_CRT_ORDER_INDEXED);\n res.check(\"Unable to create group with name '\" + name + \"'! (H5Pset_link_cr...)\");\n\n g = Group(H5Gcreate2(hid, name.c_str(), H5P_DEFAULT, gcpl, H5P_DEFAULT));\n H5Pclose(gcpl);\n g.check(\"Unable to create group with name '\" + name + \"'! (H5Gcreate2)\");\n\n } else {\n throw H5Exception(\"Unable to open group with name '\" + name + \"'!\");\n }\n return g;\n}\n\n\noptGroup Group::openOptGroup(const std::string &name) {\n if(!util::nameCheck(name)) throw InvalidName(\"openOptGroup\");\n return optGroup(*this, name);\n}\n\n\nvoid Group::removeGroup(const std::string &name) {\n if (hasGroup(name))\n H5Gunlink(hid, name.c_str());\n}\n\n\nvoid Group::renameGroup(const std::string &old_name, const std::string &new_name) {\n if(!util::nameCheck(new_name)) throw InvalidName(\"renameGroup\");\n if (hasGroup(old_name)) {\n H5Gmove(hid, old_name.c_str(), new_name.c_str()); \/\/FIXME: H5Gmove is deprecated\n }\n}\n\n\nGroup Group::createLink(const Group &target, const std::string &link_name) {\n if(!util::nameCheck(link_name)) throw InvalidName(\"createLink\");\n HErr res = H5Lcreate_hard(target.hid, \".\", hid, link_name.c_str(),\n H5L_SAME_LOC, H5L_SAME_LOC);\n res.check(\"Unable to create link \" + link_name);\n return openGroup(link_name, false);\n}\n\n\/\/ TODO implement some kind of roll-back in order to avoid half renamed links.\nbool Group::renameAllLinks(const std::string &old_name, const std::string &new_name) {\n if(!util::nameCheck(new_name)) throw InvalidName(\"renameAllLinks\");\n bool renamed = false;\n\n if (hasGroup(old_name)) {\n std::vector<std::string> links;\n\n Group group = openGroup(old_name, false);\n std::string gname = group.name();\n\n while (! gname.empty()) {\n deleteLink(gname);\n links.push_back(gname);\n gname = group.name();\n }\n\n renamed = links.size() > 0;\n for (std::string curr_name: links) {\n size_t pos = curr_name.find_last_of('\/') + 1;\n\n if (curr_name.substr(pos) == old_name) {\n curr_name.replace(curr_name.begin() + pos, curr_name.end(), new_name.begin(), new_name.end());\n }\n\n HErr res = H5Lcreate_hard(group.hid, \".\", hid, curr_name.c_str(),\n H5L_SAME_LOC, H5L_SAME_LOC);\n renamed = renamed && res;\n }\n }\n\n return renamed;\n}\n\n\/\/ TODO implement some kind of roll-back in order to avoid half removed links.\nbool Group::removeAllLinks(const std::string &name) {\n bool removed = false;\n\n if (hasGroup(name)) {\n Group group = openGroup(name, false);\n\n std::string gname = group.name();\n\n while (! gname.empty()) {\n deleteLink(gname);\n gname = group.name();\n }\n\n removed = true;\n }\n\n return removed;\n}\n\n\nboost::optional<Group> Group::findGroupByNameOrAttribute(std::string const &attr, std::string const &value) const {\n\n if (hasObject(value)) {\n return boost::make_optional(openGroup(value, false));\n } else if (util::looksLikeUUID(value)) {\n return findGroupByAttribute(attr, value);\n } else {\n return boost::optional<Group>();\n }\n}\n\n\nboost::optional<DataSet> Group::findDataByNameOrAttribute(std::string const &attr, std::string const &value) const {\n\n if (hasObject(value)) {\n return boost::make_optional(openData(value));\n } else if (util::looksLikeUUID(value)) {\n return findDataByAttribute(attr, value);\n } else {\n return boost::optional<DataSet>();\n }\n}\n\n\nGroup::~Group()\n{}\n\n} \/\/ namespace hdf5\n} \/\/ namespace nix\n<commit_msg>[h5x] Group::openGroup: use H5 C API for prop list<commit_after>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <nix\/hdf5\/Group.hpp>\n\n#include <nix\/util\/util.hpp>\n\n#include <nix\/hdf5\/ExceptionHDF5.hpp>\n#include <nix\/hdf5\/hdf5include.hpp>\n\n\n\nnamespace nix {\nnamespace hdf5 {\n\noptGroup::optGroup(const Group &parent, const std::string &g_name)\n : parent(parent), g_name(g_name)\n{}\n\nboost::optional<Group> optGroup::operator() (bool create) const {\n if (parent.hasGroup(g_name)) {\n g = boost::optional<Group>(parent.openGroup(g_name));\n } else if (create) {\n g = boost::optional<Group>(parent.openGroup(g_name, true));\n }\n return g;\n}\n\n\nGroup::Group() : LocID() {}\n\n\nGroup::Group(hid_t hid) : LocID(hid) {}\n\n\nGroup::Group(const Group &other) : LocID(other) {}\n\n\nbool Group::hasObject(const std::string &name) const {\n \/\/ empty string should return false, not exception (which H5Lexists would)\n if (name.empty()) {\n return false;\n }\n\n HTri res = H5Lexists(hid, name.c_str(), H5P_DEFAULT);\n return res.check(\"Group::hasObject(): H5Lexists failed\");\n}\n\nbool Group::objectOfType(const std::string &name, H5O_type_t type) const {\n H5O_info_t info;\n\n hid_t obj = H5Oopen(hid, name.c_str(), H5P_DEFAULT);\n\n if (!H5Iis_valid(obj)) {\n return false;\n }\n\n HErr err = H5Oget_info(obj, &info);\n err.check(\"Could not obtain object info\");\n\n bool res = info.type == type;\n\n H5Oclose(obj);\n return res;\n}\n\nsize_t Group::objectCount() const {\n hsize_t n_objs;\n HErr res = H5Gget_num_objs(hid, &n_objs);\n res.check(\"Could not get object count\");\n return n_objs;\n}\n\n\nboost::optional<Group> Group::findGroupByAttribute(const std::string &attribute, const std::string &value) const {\n boost::optional<Group> ret;\n\n \/\/ look up first direct sub-group that has given attribute with given value\n for (size_t index = 0; index < objectCount(); index++) {\n std::string obj_name = objectName(index);\n if(hasGroup(obj_name)) {\n Group group = openGroup(obj_name, false);\n if(group.hasAttr(attribute)) {\n std::string attr_value;\n group.getAttr(attribute, attr_value);\n if (attr_value == value) {\n ret = group;\n break;\n }\n }\n }\n }\n\n return ret;\n}\n\n\nboost::optional<DataSet> Group::findDataByAttribute(const std::string &attribute, const std::string &value) const {\n std::vector<DataSet> dsets;\n boost::optional<DataSet> ret;\n\n \/\/ look up all direct sub-datasets that have the given attribute\n for (size_t index = 0; index < objectCount(); index++) {\n std::string obj_name = objectName(index);\n if(hasData(obj_name)) {\n DataSet ds = openData(obj_name);\n\n if (ds.hasAttr(attribute)) {\n dsets.push_back(ds);\n }\n }\n }\n \/\/ look for first dataset with given attribute set to given value\n auto found = std::find_if(dsets.begin(), dsets.end(),\n [value, attribute](DataSet &dset) {\n std::string attr_value;\n dset.getAttr(attribute, attr_value);\n return attr_value == value; });\n if(found != dsets.end()) ret = *found;\n\n return ret;\n}\n\n\nstd::string Group::objectName(size_t index) const {\n \/\/ check if index valid\n if(index > objectCount()) {\n throw OutOfBounds(\"No object at given index\", index);\n }\n\n std::string str_name;\n \/\/ check whether name is found by index\n ssize_t name_len = H5Lget_name_by_idx(hid,\n \".\",\n H5_INDEX_NAME,\n H5_ITER_NATIVE,\n (hsize_t) index,\n NULL,\n 0,\n H5P_DEFAULT);\n if (name_len > 0) {\n char* name = new char[name_len+1];\n name_len = H5Lget_name_by_idx(hid,\n \".\",\n H5_INDEX_NAME,\n H5_ITER_NATIVE,\n (hsize_t) index,\n name,\n name_len+1,\n H5P_DEFAULT);\n str_name = name;\n delete [] name;\n } else {\n throw H5Exception(\"objectName: No object found, H5Lget_name_by_idx returned no name\");\n }\n\n return str_name;\n}\n\n\nbool Group::hasData(const std::string &name) const {\n return hasObject(name) && objectOfType(name, H5O_TYPE_DATASET);\n}\n\n\nvoid Group::removeData(const std::string &name) {\n if (hasData(name)) {\n HErr res = H5Gunlink(hid, name.c_str());\n res.check(\"Group::removeData(): Could not unlink DataSet\");\n }\n}\n\nDataSet Group::createData(const std::string &name,\n DataType dtype,\n const NDSize &size) const\n{\n h5x::DataType fileType = data_type_to_h5_filetype(dtype);\n return createData(name, fileType, size);\n}\n\n\nDataSet Group::createData(const std::string &name,\n const h5x::DataType &fileType,\n const NDSize &size,\n const NDSize &maxsize,\n NDSize chunks,\n bool max_size_unlimited,\n bool guess_chunks) const\n{\n DataSpace space;\n\n if (size) {\n if (maxsize) {\n space = DataSpace::create(size, maxsize);\n } else {\n space = DataSpace::create(size, max_size_unlimited);\n }\n }\n\n BaseHDF5 dcpl = H5Pcreate(H5P_DATASET_CREATE);\n dcpl.check(\"Could not create data creation plist\");\n\n if (!chunks && guess_chunks) {\n chunks = DataSet::guessChunking(size, fileType.size());\n }\n\n if (chunks) {\n int rank = static_cast<int>(chunks.size());\n HErr res = H5Pset_chunk(dcpl.h5id(), rank, chunks.data());\n res.check(\"Could not set chunk size on data set creation plist\");\n }\n\n DataSet ds = H5Dcreate(hid, name.c_str(), fileType.h5id(), space.h5id(), H5P_DEFAULT, dcpl.h5id(), H5P_DEFAULT);\n ds.check(\"Group::createData: Could not create DataSet with name \" + name);\n\n return ds;\n}\n\n\nDataSet Group::openData(const std::string &name) const {\n DataSet ds = H5Dopen(hid, name.c_str(), H5P_DEFAULT);\n ds.check(\"Group::openData(): Could not open DataSet\");\n return ds;\n}\n\n\nbool Group::hasGroup(const std::string &name) const {\n return hasObject(name) && objectOfType(name, H5O_TYPE_GROUP);\n}\n\n\nGroup Group::openGroup(const std::string &name, bool create) const {\n if(!util::nameCheck(name)) throw InvalidName(\"openGroup\");\n Group g;\n\n if (hasGroup(name)) {\n g = Group(H5Gopen(hid, name.c_str(), H5P_DEFAULT));\n g.check(\"Group::openGroup(): Could not open group: \" + name);\n } else if (create) {\n BaseHDF5 gcpl = H5Pcreate(H5P_GROUP_CREATE);\n gcpl.check(\"Unable to create group with name '\" + name + \"'! (H5Pcreate)\");\n\n \/\/we want hdf5 to keep track of the order in which links were created so that\n \/\/the order for indexed based accessors is stable cf. issue #387\n HErr res = H5Pset_link_creation_order(gcpl.h5id(), H5P_CRT_ORDER_TRACKED|H5P_CRT_ORDER_INDEXED);\n res.check(\"Unable to create group with name '\" + name + \"'! (H5Pset_link_cr...)\");\n\n g = Group(H5Gcreate2(hid, name.c_str(), H5P_DEFAULT, gcpl.h5id(), H5P_DEFAULT));\n g.check(\"Unable to create group with name '\" + name + \"'! (H5Gcreate2)\");\n\n } else {\n throw H5Exception(\"Unable to open group with name '\" + name + \"'!\");\n }\n\n return g;\n}\n\n\noptGroup Group::openOptGroup(const std::string &name) {\n if(!util::nameCheck(name)) throw InvalidName(\"openOptGroup\");\n return optGroup(*this, name);\n}\n\n\nvoid Group::removeGroup(const std::string &name) {\n if (hasGroup(name))\n H5Gunlink(hid, name.c_str());\n}\n\n\nvoid Group::renameGroup(const std::string &old_name, const std::string &new_name) {\n if(!util::nameCheck(new_name)) throw InvalidName(\"renameGroup\");\n if (hasGroup(old_name)) {\n H5Gmove(hid, old_name.c_str(), new_name.c_str()); \/\/FIXME: H5Gmove is deprecated\n }\n}\n\n\nGroup Group::createLink(const Group &target, const std::string &link_name) {\n if(!util::nameCheck(link_name)) throw InvalidName(\"createLink\");\n HErr res = H5Lcreate_hard(target.hid, \".\", hid, link_name.c_str(),\n H5L_SAME_LOC, H5L_SAME_LOC);\n res.check(\"Unable to create link \" + link_name);\n return openGroup(link_name, false);\n}\n\n\/\/ TODO implement some kind of roll-back in order to avoid half renamed links.\nbool Group::renameAllLinks(const std::string &old_name, const std::string &new_name) {\n if(!util::nameCheck(new_name)) throw InvalidName(\"renameAllLinks\");\n bool renamed = false;\n\n if (hasGroup(old_name)) {\n std::vector<std::string> links;\n\n Group group = openGroup(old_name, false);\n std::string gname = group.name();\n\n while (! gname.empty()) {\n deleteLink(gname);\n links.push_back(gname);\n gname = group.name();\n }\n\n renamed = links.size() > 0;\n for (std::string curr_name: links) {\n size_t pos = curr_name.find_last_of('\/') + 1;\n\n if (curr_name.substr(pos) == old_name) {\n curr_name.replace(curr_name.begin() + pos, curr_name.end(), new_name.begin(), new_name.end());\n }\n\n HErr res = H5Lcreate_hard(group.hid, \".\", hid, curr_name.c_str(),\n H5L_SAME_LOC, H5L_SAME_LOC);\n renamed = renamed && res;\n }\n }\n\n return renamed;\n}\n\n\/\/ TODO implement some kind of roll-back in order to avoid half removed links.\nbool Group::removeAllLinks(const std::string &name) {\n bool removed = false;\n\n if (hasGroup(name)) {\n Group group = openGroup(name, false);\n\n std::string gname = group.name();\n\n while (! gname.empty()) {\n deleteLink(gname);\n gname = group.name();\n }\n\n removed = true;\n }\n\n return removed;\n}\n\n\nboost::optional<Group> Group::findGroupByNameOrAttribute(std::string const &attr, std::string const &value) const {\n\n if (hasObject(value)) {\n return boost::make_optional(openGroup(value, false));\n } else if (util::looksLikeUUID(value)) {\n return findGroupByAttribute(attr, value);\n } else {\n return boost::optional<Group>();\n }\n}\n\n\nboost::optional<DataSet> Group::findDataByNameOrAttribute(std::string const &attr, std::string const &value) const {\n\n if (hasObject(value)) {\n return boost::make_optional(openData(value));\n } else if (util::looksLikeUUID(value)) {\n return findDataByAttribute(attr, value);\n } else {\n return boost::optional<DataSet>();\n }\n}\n\n\nGroup::~Group()\n{}\n\n} \/\/ namespace hdf5\n} \/\/ namespace nix\n<|endoftext|>"} {"text":"<commit_before>#include <json.h>\n#include <utf8.h>\n#include <string>\n#include <functional>\n#include <memory>\n#include <iostream>\n\n#include \"json_object.h\"\n#include \"json_loader.h\"\n#include \"shl_exception.h\"\n\nusing std::string;\nusing std::function;\nusing std::shared_ptr;\n\nnamespace shl {\n\nstatic inline void ensure_utf8(const string& str) {\n if (!utf8::is_valid(str.begin(), str.end())) throw InvalidGrammarException(\"grammar file contains invalid UTF-8 character\");\n}\n\nstatic inline void ensure_object(const json_value* value, const string& msg) {\n if (value->type != json_object) throw InvalidGrammarException(msg);\n}\n\nstatic inline void ensure_string(const json_value* value, const string& msg) {\n if (value->type != json_string) throw InvalidGrammarException(msg);\n}\n\nstatic inline void ensure_array(const json_value* value, const string& msg) {\n if (value->type != json_array) throw InvalidGrammarException(msg);\n}\n\nstatic void for_fields(const json_value* value, function<void(const string&, const json_value*)> process ) {\n for(unsigned int i = 0; i < value->u.object.length; i++) {\n process(value->u.object.values[i].name, value->u.object.values[i].value);\n }\n}\n\nstatic void for_each(const json_value* value, function<void(const json_value*)> process) {\n for(unsigned int i = 0; i < value->u.array.length; i++) {\n process(value->u.array.values[i]);\n }\n}\n\n\nstatic inline string get_string(const json_value* value) {\n return value->u.string.ptr;\n}\n\n\nstatic inline map<string, map<string, string> > get_captures(const json_value* value) {\n map<string, map<string, string> > capture_list;\n\n for_fields(value, [&capture_list](const string& key, const json_value* value) {\n ensure_object(value, \"every capture definition should be an object\");\n\n map<string, string> capture;\n for_fields(value, [&capture](const string& key, const json_value* value) {\n capture[key] = get_string(value);\n });\n\n capture_list[key] = capture;\n });\n \n return capture_list;\n}\n\n\nstatic inline shared_ptr<json_value> parse_json(const string& json) {\n json_value* value = json_parse((const json_char*)json.c_str(), json.size());\n if (value == nullptr) throw InvalidGrammarException(\"grammar is not a valid json object\");\n return shared_ptr<json_value>(value, [](json_value* ptr) { json_value_free(ptr); });\n}\n\nJsonObject JsonLoader::load(const string& json) {\n ensure_utf8(json);\n\n JsonObject object;\n auto value = parse_json(json); \/\/ pointer is protected by shared_ptr\n\n process(object, value.get());\n\n\n return object;\n}\n\nvoid JsonLoader::process(JsonObject& root, const json_value* value) {\n ensure_object(value, \"grammar definition file should have only one object as root\");\n\n for_fields(value, [&root](const string& key, const json_value* value){\n if (key == \"include\") {\n ensure_string(value, \"include should be a string\");\n root.include = get_string(value);\n\n } else if (key == \"scopeName\") {\n ensure_string(value, \"scopeName should be a string\");\n root.scope_name = get_string(value);\n\n } else if (key == \"fileTypes\") {\n ensure_array(value, \"fileTypes should be array of String\"); \n for_each(value, [&root](const json_value* value) {\n root.file_types.push_back(get_string(value));\n });\n \n } else if (key == \"name\") {\n ensure_string(value, \"name should be a string\");\n root.name = get_string(value);\n\n } else if (key == \"patterns\") {\n ensure_array(value, \"patterns should be an array\");\n for_each(value, [&root](const json_value* value) {\n ensure_object(value, \"patterns can only contains objects\");\n JsonObject pattern;\n process(pattern, value);\n root.patterns.push_back(pattern);\n });\n \n } else if (key == \"repository\") {\n ensure_object(value, \"repository should be a key-value map\");\n for_fields(value, [&root](const string& key, const json_value* value){\n ensure_object(value, \"repository item can only be an object\");\n JsonObject repo_item;\n process(repo_item, value);\n root.repository[key] = repo_item;\n });\n\n } else if (key == \"match\") {\n ensure_string(value, \"match should be a regex\");\n root.match = get_string(value);\n } else if (key == \"captures\") {\n ensure_object(value, \"captures should be an object\");\n root.captures = get_captures(value);\n } else if (key == \"begin\") {\n ensure_string(value, \"begin pattern should be a regex\");\n root.begin = get_string(value);\n } else if (key == \"begin_captures\") {\n ensure_object(value, \"begin_captures should be an object\");\n root.begin_captures = get_captures(value);\n } else if (key == \"end\") {\n ensure_string(value, \"end pattern should be a regex\");\n root.end = get_string(value);\n } else if (key == \"end_captures\") {\n ensure_object(value, \"end_captures should be an object\");\n root.end_captures = get_captures(value);\n } else if (key == \"content_name\") {\n ensure_string(value, \"content_name should be a string\");\n root.content_name = get_string(value);\n }\n });\n}\n\n}\n<commit_msg>fix wrong object name<commit_after>#include <json.h>\n#include <utf8.h>\n#include <string>\n#include <functional>\n#include <memory>\n#include <iostream>\n\n#include \"json_object.h\"\n#include \"json_loader.h\"\n#include \"shl_exception.h\"\n\nusing std::string;\nusing std::function;\nusing std::shared_ptr;\n\nnamespace shl {\n\nstatic inline void ensure_utf8(const string& str) {\n if (!utf8::is_valid(str.begin(), str.end())) throw InvalidGrammarException(\"grammar file contains invalid UTF-8 character\");\n}\n\nstatic inline void ensure_object(const json_value* value, const string& msg) {\n if (value->type != json_object) throw InvalidGrammarException(msg);\n}\n\nstatic inline void ensure_string(const json_value* value, const string& msg) {\n if (value->type != json_string) throw InvalidGrammarException(msg);\n}\n\nstatic inline void ensure_array(const json_value* value, const string& msg) {\n if (value->type != json_array) throw InvalidGrammarException(msg);\n}\n\nstatic void for_fields(const json_value* value, function<void(const string&, const json_value*)> process ) {\n for(unsigned int i = 0; i < value->u.object.length; i++) {\n process(value->u.object.values[i].name, value->u.object.values[i].value);\n }\n}\n\nstatic void for_each(const json_value* value, function<void(const json_value*)> process) {\n for(unsigned int i = 0; i < value->u.array.length; i++) {\n process(value->u.array.values[i]);\n }\n}\n\n\nstatic inline string get_string(const json_value* value) {\n return value->u.string.ptr;\n}\n\n\nstatic inline map<string, map<string, string> > get_captures(const json_value* value) {\n map<string, map<string, string> > capture_list;\n\n for_fields(value, [&capture_list](const string& key, const json_value* value) {\n ensure_object(value, \"every capture definition should be an object\");\n\n map<string, string> capture;\n for_fields(value, [&capture](const string& key, const json_value* value) {\n capture[key] = get_string(value);\n });\n\n capture_list[key] = capture;\n });\n \n return capture_list;\n}\n\n\nstatic inline shared_ptr<json_value> parse_json(const string& json) {\n json_value* value = json_parse((const json_char*)json.c_str(), json.size());\n if (value == nullptr) throw InvalidGrammarException(\"grammar is not a valid json object\");\n return shared_ptr<json_value>(value, [](json_value* ptr) { json_value_free(ptr); });\n}\n\nJsonObject JsonLoader::load(const string& json) {\n ensure_utf8(json);\n\n JsonObject object;\n auto value = parse_json(json); \/\/ pointer is protected by shared_ptr\n\n process(object, value.get());\n\n\n return object;\n}\n\nvoid JsonLoader::process(JsonObject& root, const json_value* value) {\n ensure_object(value, \"grammar definition file should have only one object as root\");\n\n for_fields(value, [&root](const string& key, const json_value* value){\n if (key == \"include\") {\n ensure_string(value, \"include should be a string\");\n root.include = get_string(value);\n\n } else if (key == \"scopeName\") {\n ensure_string(value, \"scopeName should be a string\");\n root.scope_name = get_string(value);\n\n } else if (key == \"fileTypes\") {\n ensure_array(value, \"fileTypes should be array of String\"); \n for_each(value, [&root](const json_value* value) {\n root.file_types.push_back(get_string(value));\n });\n \n } else if (key == \"name\") {\n ensure_string(value, \"name should be a string\");\n root.name = get_string(value);\n\n } else if (key == \"patterns\") {\n ensure_array(value, \"patterns should be an array\");\n for_each(value, [&root](const json_value* value) {\n ensure_object(value, \"patterns can only contains objects\");\n JsonObject pattern;\n process(pattern, value);\n root.patterns.push_back(pattern);\n });\n \n } else if (key == \"repository\") {\n ensure_object(value, \"repository should be a key-value map\");\n for_fields(value, [&root](const string& key, const json_value* value){\n ensure_object(value, \"repository item can only be an object\");\n JsonObject repo_item;\n process(repo_item, value);\n root.repository[key] = repo_item;\n });\n\n } else if (key == \"match\") {\n ensure_string(value, \"match should be a regex\");\n root.match = get_string(value);\n } else if (key == \"captures\") {\n ensure_object(value, \"captures should be an object\");\n root.captures = get_captures(value);\n } else if (key == \"begin\") {\n ensure_string(value, \"begin pattern should be a regex\");\n root.begin = get_string(value);\n } else if (key == \"beginCaptures\") {\n ensure_object(value, \"begin_captures should be an object\");\n root.begin_captures = get_captures(value);\n } else if (key == \"end\") {\n ensure_string(value, \"end pattern should be a regex\");\n root.end = get_string(value);\n } else if (key == \"endCaptures\") {\n ensure_object(value, \"end_captures should be an object\");\n root.end_captures = get_captures(value);\n } else if (key == \"contentName\") {\n ensure_string(value, \"content_name should be a string\");\n root.content_name = get_string(value);\n }\n });\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <kernel\/rtc.hpp>\n\n#include <kernel\/os.hpp>\n#include <kernel\/timers.hpp>\n#include <hw\/cmos.hpp>\n#include <hertz>\n\nusing timestamp_t = RTC::timestamp_t;\ntimestamp_t RTC::booted_at;\ntimestamp_t RTC::current_time;\nuint64_t RTC::current_ticks;\n\nusing namespace std::chrono;\n\nvoid RTC::init()\n{\n \/\/ Initialize CMOS\n hw::CMOS::init();\n\n \/\/ set current timestamp and ticks\n current_time = hw::CMOS::now().to_epoch();\n current_ticks = OS::cycles_since_boot();\n\n \/\/ set boot timestamp\n booted_at = current_time;\n\n INFO(\"RTC\", \"Enabling regular clock sync with CMOS\");\n \/\/ every minute recalibrate\n Timers::periodic(seconds(60), seconds(60),\n [] (Timers::id_t) {\n static int d = 0;\n printf(\"One minute passed: %d\\n\", ++d);\n current_time = hw::CMOS::now().to_epoch();\n current_ticks = OS::cycles_since_boot();\n });\n}\n\ntimestamp_t RTC::now()\n{\n auto ticks = OS::cycles_since_boot() - current_ticks;\n auto diff = ticks \/ Hz(MHz(OS::cpu_freq())).count();\n\n return current_time + diff;\n}\n<commit_msg>rtc: Remove debugging output<commit_after>#include <kernel\/rtc.hpp>\n\n#include <kernel\/os.hpp>\n#include <kernel\/timers.hpp>\n#include <hw\/cmos.hpp>\n#include <hertz>\n\nusing timestamp_t = RTC::timestamp_t;\ntimestamp_t RTC::booted_at;\ntimestamp_t RTC::current_time;\nuint64_t RTC::current_ticks;\n\nusing namespace std::chrono;\n\nvoid RTC::init()\n{\n \/\/ Initialize CMOS\n hw::CMOS::init();\n\n \/\/ set current timestamp and ticks\n current_time = hw::CMOS::now().to_epoch();\n current_ticks = OS::cycles_since_boot();\n\n \/\/ set boot timestamp\n booted_at = current_time;\n\n INFO(\"RTC\", \"Enabling regular clock sync with CMOS\");\n \/\/ every minute recalibrate\n Timers::periodic(seconds(60), seconds(60),\n [] (Timers::id_t) {\n current_time = hw::CMOS::now().to_epoch();\n current_ticks = OS::cycles_since_boot();\n });\n}\n\ntimestamp_t RTC::now()\n{\n auto ticks = OS::cycles_since_boot() - current_ticks;\n auto diff = ticks \/ Hz(MHz(OS::cpu_freq())).count();\n\n return current_time + diff;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2019, OpenROAD\n\/\/ All rights reserved.\n\/\/\n\/\/ BSD 3-Clause License\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the copyright holder 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 \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"openroad\/OpenRoad.hh\"\n\n#include <iostream>\n\n#include \"utility\/MakeLogger.h\"\n#include \"utility\/Logger.h\"\n\n#include \"opendb\/db.h\"\n#include \"opendb\/wOrder.h\"\n#include \"opendb\/lefin.h\"\n#include \"opendb\/defin.h\"\n#include \"opendb\/defout.h\"\n\n#include \"sta\/VerilogWriter.hh\"\n#include \"sta\/StaMain.hh\"\n\n#include \"db_sta\/dbSta.hh\"\n#include \"db_sta\/MakeDbSta.hh\"\n\n#include \"db_sta\/dbReadVerilog.hh\"\n#include \"db_sta\/dbNetwork.hh\"\n\n#include \"openroad\/InitOpenRoad.hh\"\n#include \"flute3\/flute.h\"\n\n#include \"init_fp\/\/MakeInitFloorplan.hh\"\n#include \"ioplacer\/MakeIoplacer.h\"\n#include \"resizer\/MakeResizer.hh\"\n#include \"gui\/MakeGui.h\"\n#include \"opendp\/MakeOpendp.h\"\n#include \"finale\/MakeFinale.h\"\n#include \"tritonmp\/MakeTritonMp.h\"\n#include \"replace\/MakeReplace.h\"\n#include \"fastroute\/MakeFastRoute.h\"\n#include \"tritoncts\/MakeTritoncts.h\"\n#include \"tapcell\/MakeTapcell.h\"\n#include \"OpenRCX\/MakeOpenRCX.h\"\n#include \"triton_route\/MakeTritonRoute.h\"\n#include \"pdnsim\/MakePDNSim.hh\"\n#include \"antennachecker\/MakeAntennaChecker.hh\"\n#include \"PartitionMgr\/src\/MakePartitionMgr.h\"\n\nnamespace sta {\nextern const char *openroad_tcl_inits[];\n}\n\n\/\/ Swig uses C linkage for init functions.\nextern \"C\" {\nextern int Openroad_Init(Tcl_Interp *interp);\nextern int Opendbtcl_Init(Tcl_Interp *interp);\n}\n\n\/\/ Main.cc set by main()\nextern const char* log_filename;\nextern const char* metrics_filename;\n\nnamespace ord {\n\nusing std::min;\nusing std::max;\n\nusing odb::dbLib;\nusing odb::dbTech;\nusing odb::dbChip;\nusing odb::dbDatabase;\nusing odb::dbBlock;\nusing odb::Rect;\nusing odb::Point;\n\nusing sta::evalTclInit;\nusing sta::dbSta;\nusing sta::Resizer;\n\nOpenRoad::OpenRoad()\n : tcl_interp_(nullptr),\n logger_(nullptr),\n db_(nullptr),\n verilog_network_(nullptr),\n sta_(nullptr),\n resizer_(nullptr),\n ioPlacer_(nullptr),\n opendp_(nullptr),\n finale_(nullptr),\n tritonMp_(nullptr),\n fastRoute_(nullptr),\n tritonCts_(nullptr),\n tapcell_(nullptr),\n extractor_(nullptr),\n detailed_router_(nullptr),\n antenna_checker_(nullptr),\n replace_(nullptr),\n pdnsim_(nullptr), \n partitionMgr_(nullptr) \n{\n db_ = dbDatabase::create();\n}\n\nOpenRoad::~OpenRoad()\n{\n deleteDbVerilogNetwork(verilog_network_);\n deleteDbSta(sta_);\n deleteIoplacer(ioPlacer_);\n deleteResizer(resizer_);\n deleteOpendp(opendp_);\n deleteFastRoute(fastRoute_);\n deleteTritonCts(tritonCts_);\n deleteTapcell(tapcell_);\n deleteTritonMp(tritonMp_);\n deleteOpenRCX(extractor_);\n deleteTritonRoute(detailed_router_);\n deleteReplace(replace_);\n deleteFinale(finale_);\n deleteAntennaChecker(antenna_checker_);\n odb::dbDatabase::destroy(db_);\n deletePartitionMgr(partitionMgr_);\n stt::deleteLUT();\n delete logger_;\n}\n\nvoid\ndeleteAllMemory()\n{\n delete OpenRoad::openRoad();\n sta::Sta::setSta(nullptr);\n sta::deleteAllMemory();\n}\n\nsta::dbNetwork *\nOpenRoad::getDbNetwork()\n{\n return sta_->getDbNetwork();\n}\n\n\/* static *\/\nOpenRoad *OpenRoad::openRoad()\n{\n \/\/ This will be destroyed at application exit\n static OpenRoad o;\n return &o;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\ninitOpenRoad(Tcl_Interp *interp)\n{\n OpenRoad::openRoad()->init(interp);\n}\n\nvoid\nOpenRoad::init(Tcl_Interp *tcl_interp)\n{\n tcl_interp_ = tcl_interp;\n\n \/\/ Make components.\n logger_ = makeLogger(log_filename, metrics_filename);\n db_->setLogger(logger_);\n sta_ = makeDbSta();\n verilog_network_ = makeDbVerilogNetwork();\n ioPlacer_ = makeIoplacer();\n resizer_ = makeResizer();\n opendp_ = makeOpendp();\n finale_ = makeFinale();\n fastRoute_ = makeFastRoute();\n tritonCts_ = makeTritonCts();\n tapcell_ = makeTapcell();\n tritonMp_ = makeTritonMp();\n extractor_ = makeOpenRCX();\n detailed_router_ = makeTritonRoute();\n replace_ = makeReplace();\n pdnsim_ = makePDNSim();\n antenna_checker_ = makeAntennaChecker();\n partitionMgr_ = makePartitionMgr();\n\n \/\/ Init components.\n Openroad_Init(tcl_interp);\n \/\/ Import TCL scripts.\n evalTclInit(tcl_interp, sta::openroad_tcl_inits);\n\n initLogger(logger_, tcl_interp);\n initGui(this); \/\/ first so we can register our sink with the logger\n Opendbtcl_Init(tcl_interp);\n initInitFloorplan(this);\n stt::readLUT();\n initDbSta(this);\n initResizer(this);\n initDbVerilogNetwork(this);\n initIoplacer(this);\n initReplace(this);\n initOpendp(this);\n initFinale(this);\n initFastRoute(this);\n initTritonCts(this);\n initTapcell(this);\n initTritonMp(this);\n initOpenRCX(this);\n initTritonRoute(this);\n initPDNSim(this);\n initAntennaChecker(this);\n initPartitionMgr(this);\n\n \/\/ Import exported commands to global namespace.\n Tcl_Eval(tcl_interp, \"sta::define_sta_cmds\");\n Tcl_Eval(tcl_interp, \"namespace import sta::*\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nOpenRoad::readLef(const char *filename,\n\t\t const char *lib_name,\n\t\t bool make_tech,\n\t\t bool make_library)\n{\n odb::lefin lef_reader(db_, logger_, false);\n dbLib *lib = nullptr;\n dbTech *tech = nullptr;\n if (make_tech && make_library) {\n lib = lef_reader.createTechAndLib(lib_name, filename);\n tech = db_->getTech();\n } else if (make_tech) {\n tech = lef_reader.createTech(filename);\n } else if (make_library) {\n lib = lef_reader.createLib(lib_name, filename);\n }\n\n \/\/ both are null on parser failure\n if (lib != nullptr || tech != nullptr) {\n for (Observer* observer : observers_) {\n observer->postReadLef(tech, lib);\n }\n }\n}\n\nvoid\nOpenRoad::readDef(const char *filename,\n\t\t bool order_wires,\n\t\t bool continue_on_errors)\n{\n odb::defin def_reader(db_,logger_);\n std::vector<odb::dbLib *> search_libs;\n for (odb::dbLib *lib : db_->getLibs())\n search_libs.push_back(lib);\n if (continue_on_errors) {\n def_reader.continueOnErrors();\n }\n dbChip* chip = def_reader.createChip(search_libs, filename);\n if (chip) {\n dbBlock* block = chip->getBlock();\n if (order_wires) {\n odb::orderWires(block,\n nullptr \/* net_name_or_id*\/,\n false \/* force *\/,\n false \/* verbose *\/,\n true \/* quiet *\/);\n }\n\n for (Observer* observer : observers_) {\n observer->postReadDef(block);\n }\n }\n}\n\nstatic odb::defout::Version\nstringToDefVersion(string version)\n{\n if (version == \"5.8\")\n return odb::defout::Version::DEF_5_8;\n else if (version == \"5.6\")\n return odb::defout::Version::DEF_5_6;\n else if (version == \"5.5\")\n return odb::defout::Version::DEF_5_5;\n else if (version == \"5.4\")\n return odb::defout::Version::DEF_5_4;\n else if (version == \"5.3\")\n return odb::defout::Version::DEF_5_3;\n else \n return odb::defout::Version::DEF_5_8;\n}\n\nvoid\nOpenRoad::writeDef(const char *filename,\n\t\t string version)\n{\n odb::dbChip *chip = db_->getChip();\n if (chip) {\n odb::dbBlock *block = chip->getBlock();\n if (block) {\n odb::defout def_writer(logger_);\n def_writer.setVersion(stringToDefVersion(version));\n def_writer.writeBlock(block, filename);\n }\n }\n}\n\nvoid\nOpenRoad::readDb(const char *filename)\n{\n FILE *stream = fopen(filename, \"r\");\n if (stream == nullptr) {\n return;\n }\n\n db_->read(stream);\n fclose(stream);\n\n for (Observer* observer : observers_) {\n observer->postReadDb(db_);\n }\n}\n\nvoid\nOpenRoad::writeDb(const char *filename)\n{\n FILE *stream = fopen(filename, \"w\");\n if (stream) {\n db_->write(stream);\n fclose(stream);\n }\n}\n\nvoid\nOpenRoad::readVerilog(const char *filename)\n{\n dbReadVerilog(filename, verilog_network_);\n}\n\nvoid\nOpenRoad::linkDesign(const char *design_name)\n\n{\n dbLinkDesign(design_name, verilog_network_, db_, logger_);\n for (Observer* observer : observers_) {\n observer->postReadDb(db_);\n }\n}\n\nvoid\nOpenRoad::writeVerilog(const char *filename,\n\t\t bool sort,\n\t\t bool include_pwr_gnd,\n\t\t std::vector<sta::LibertyCell*> *remove_cells)\n{\n sta::writeVerilog(filename, sort, include_pwr_gnd,\n\t\t remove_cells, sta_->network());\n}\n\nbool\nOpenRoad::unitsInitialized()\n{\n \/\/ Units are set by the first liberty library read.\n return getDbNetwork()->defaultLibertyLibrary() != nullptr;\n}\n\nodb::Rect\nOpenRoad::getCore()\n{\n return ord::getCore(db_->getChip()->getBlock());\n}\n\nvoid OpenRoad::addObserver(Observer *observer)\n{\n assert(observer->owner_ == nullptr);\n observer->owner_ = this;\n observers_.insert(observer);\n}\n\nvoid OpenRoad::removeObserver(Observer *observer)\n{\n observer->owner_ = nullptr;\n observers_.erase(observer);\n}\n\nOpenRoad::Observer::~Observer()\n{\n if (owner_) {\n owner_->removeObserver(this);\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Need a header for these functions cherry uses in\n\/\/ InitFloorplan, Resizer, OpenDP.\n\nRect\ngetCore(dbBlock *block)\n{\n odb::Rect core;\n block->getCoreArea(core);\n return core;\n}\n\n\/\/ Return the point inside rect that is closest to pt.\nPoint\nclosestPtInRect(Rect rect,\n\t\tPoint pt)\n{\n return Point(min(max(pt.getX(), rect.xMin()), rect.xMax()),\n min(max(pt.getY(), rect.yMin()), rect.yMax()));\n}\n\nPoint\nclosestPtInRect(Rect rect,\n\t\tint x,\n\t\tint y)\n{\n return Point(min(max(x, rect.xMin()), rect.xMax()),\n min(max(y, rect.yMin()), rect.yMax()));\n}\n\n} \/\/ namespace\n<commit_msg>temporarily disable grt & gpl destruction while they are being debugged<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2019, OpenROAD\n\/\/ All rights reserved.\n\/\/\n\/\/ BSD 3-Clause License\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the copyright holder 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 \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"openroad\/OpenRoad.hh\"\n\n#include <iostream>\n\n#include \"utility\/MakeLogger.h\"\n#include \"utility\/Logger.h\"\n\n#include \"opendb\/db.h\"\n#include \"opendb\/wOrder.h\"\n#include \"opendb\/lefin.h\"\n#include \"opendb\/defin.h\"\n#include \"opendb\/defout.h\"\n\n#include \"sta\/VerilogWriter.hh\"\n#include \"sta\/StaMain.hh\"\n\n#include \"db_sta\/dbSta.hh\"\n#include \"db_sta\/MakeDbSta.hh\"\n\n#include \"db_sta\/dbReadVerilog.hh\"\n#include \"db_sta\/dbNetwork.hh\"\n\n#include \"openroad\/InitOpenRoad.hh\"\n#include \"flute3\/flute.h\"\n\n#include \"init_fp\/\/MakeInitFloorplan.hh\"\n#include \"ioplacer\/MakeIoplacer.h\"\n#include \"resizer\/MakeResizer.hh\"\n#include \"gui\/MakeGui.h\"\n#include \"opendp\/MakeOpendp.h\"\n#include \"finale\/MakeFinale.h\"\n#include \"tritonmp\/MakeTritonMp.h\"\n#include \"replace\/MakeReplace.h\"\n#include \"fastroute\/MakeFastRoute.h\"\n#include \"tritoncts\/MakeTritoncts.h\"\n#include \"tapcell\/MakeTapcell.h\"\n#include \"OpenRCX\/MakeOpenRCX.h\"\n#include \"triton_route\/MakeTritonRoute.h\"\n#include \"pdnsim\/MakePDNSim.hh\"\n#include \"antennachecker\/MakeAntennaChecker.hh\"\n#include \"PartitionMgr\/src\/MakePartitionMgr.h\"\n\nnamespace sta {\nextern const char *openroad_tcl_inits[];\n}\n\n\/\/ Swig uses C linkage for init functions.\nextern \"C\" {\nextern int Openroad_Init(Tcl_Interp *interp);\nextern int Opendbtcl_Init(Tcl_Interp *interp);\n}\n\n\/\/ Main.cc set by main()\nextern const char* log_filename;\nextern const char* metrics_filename;\n\nnamespace ord {\n\nusing std::min;\nusing std::max;\n\nusing odb::dbLib;\nusing odb::dbTech;\nusing odb::dbChip;\nusing odb::dbDatabase;\nusing odb::dbBlock;\nusing odb::Rect;\nusing odb::Point;\n\nusing sta::evalTclInit;\nusing sta::dbSta;\nusing sta::Resizer;\n\nOpenRoad::OpenRoad()\n : tcl_interp_(nullptr),\n logger_(nullptr),\n db_(nullptr),\n verilog_network_(nullptr),\n sta_(nullptr),\n resizer_(nullptr),\n ioPlacer_(nullptr),\n opendp_(nullptr),\n finale_(nullptr),\n tritonMp_(nullptr),\n fastRoute_(nullptr),\n tritonCts_(nullptr),\n tapcell_(nullptr),\n extractor_(nullptr),\n detailed_router_(nullptr),\n antenna_checker_(nullptr),\n replace_(nullptr),\n pdnsim_(nullptr), \n partitionMgr_(nullptr) \n{\n db_ = dbDatabase::create();\n}\n\nOpenRoad::~OpenRoad()\n{\n deleteDbVerilogNetwork(verilog_network_);\n deleteDbSta(sta_);\n deleteIoplacer(ioPlacer_);\n deleteResizer(resizer_);\n deleteOpendp(opendp_);\n \/\/ deleteFastRoute(fastRoute_);\n deleteTritonCts(tritonCts_);\n deleteTapcell(tapcell_);\n deleteTritonMp(tritonMp_);\n deleteOpenRCX(extractor_);\n deleteTritonRoute(detailed_router_);\n \/\/ deleteReplace(replace_);\n deleteFinale(finale_);\n deleteAntennaChecker(antenna_checker_);\n odb::dbDatabase::destroy(db_);\n deletePartitionMgr(partitionMgr_);\n stt::deleteLUT();\n delete logger_;\n}\n\nvoid\ndeleteAllMemory()\n{\n delete OpenRoad::openRoad();\n sta::Sta::setSta(nullptr);\n sta::deleteAllMemory();\n}\n\nsta::dbNetwork *\nOpenRoad::getDbNetwork()\n{\n return sta_->getDbNetwork();\n}\n\n\/* static *\/\nOpenRoad *OpenRoad::openRoad()\n{\n \/\/ This will be destroyed at application exit\n static OpenRoad o;\n return &o;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\ninitOpenRoad(Tcl_Interp *interp)\n{\n OpenRoad::openRoad()->init(interp);\n}\n\nvoid\nOpenRoad::init(Tcl_Interp *tcl_interp)\n{\n tcl_interp_ = tcl_interp;\n\n \/\/ Make components.\n logger_ = makeLogger(log_filename, metrics_filename);\n db_->setLogger(logger_);\n sta_ = makeDbSta();\n verilog_network_ = makeDbVerilogNetwork();\n ioPlacer_ = makeIoplacer();\n resizer_ = makeResizer();\n opendp_ = makeOpendp();\n finale_ = makeFinale();\n fastRoute_ = makeFastRoute();\n tritonCts_ = makeTritonCts();\n tapcell_ = makeTapcell();\n tritonMp_ = makeTritonMp();\n extractor_ = makeOpenRCX();\n detailed_router_ = makeTritonRoute();\n replace_ = makeReplace();\n pdnsim_ = makePDNSim();\n antenna_checker_ = makeAntennaChecker();\n partitionMgr_ = makePartitionMgr();\n\n \/\/ Init components.\n Openroad_Init(tcl_interp);\n \/\/ Import TCL scripts.\n evalTclInit(tcl_interp, sta::openroad_tcl_inits);\n\n initLogger(logger_, tcl_interp);\n initGui(this); \/\/ first so we can register our sink with the logger\n Opendbtcl_Init(tcl_interp);\n initInitFloorplan(this);\n stt::readLUT();\n initDbSta(this);\n initResizer(this);\n initDbVerilogNetwork(this);\n initIoplacer(this);\n initReplace(this);\n initOpendp(this);\n initFinale(this);\n initFastRoute(this);\n initTritonCts(this);\n initTapcell(this);\n initTritonMp(this);\n initOpenRCX(this);\n initTritonRoute(this);\n initPDNSim(this);\n initAntennaChecker(this);\n initPartitionMgr(this);\n\n \/\/ Import exported commands to global namespace.\n Tcl_Eval(tcl_interp, \"sta::define_sta_cmds\");\n Tcl_Eval(tcl_interp, \"namespace import sta::*\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nOpenRoad::readLef(const char *filename,\n\t\t const char *lib_name,\n\t\t bool make_tech,\n\t\t bool make_library)\n{\n odb::lefin lef_reader(db_, logger_, false);\n dbLib *lib = nullptr;\n dbTech *tech = nullptr;\n if (make_tech && make_library) {\n lib = lef_reader.createTechAndLib(lib_name, filename);\n tech = db_->getTech();\n } else if (make_tech) {\n tech = lef_reader.createTech(filename);\n } else if (make_library) {\n lib = lef_reader.createLib(lib_name, filename);\n }\n\n \/\/ both are null on parser failure\n if (lib != nullptr || tech != nullptr) {\n for (Observer* observer : observers_) {\n observer->postReadLef(tech, lib);\n }\n }\n}\n\nvoid\nOpenRoad::readDef(const char *filename,\n\t\t bool order_wires,\n\t\t bool continue_on_errors)\n{\n odb::defin def_reader(db_,logger_);\n std::vector<odb::dbLib *> search_libs;\n for (odb::dbLib *lib : db_->getLibs())\n search_libs.push_back(lib);\n if (continue_on_errors) {\n def_reader.continueOnErrors();\n }\n dbChip* chip = def_reader.createChip(search_libs, filename);\n if (chip) {\n dbBlock* block = chip->getBlock();\n if (order_wires) {\n odb::orderWires(block,\n nullptr \/* net_name_or_id*\/,\n false \/* force *\/,\n false \/* verbose *\/,\n true \/* quiet *\/);\n }\n\n for (Observer* observer : observers_) {\n observer->postReadDef(block);\n }\n }\n}\n\nstatic odb::defout::Version\nstringToDefVersion(string version)\n{\n if (version == \"5.8\")\n return odb::defout::Version::DEF_5_8;\n else if (version == \"5.6\")\n return odb::defout::Version::DEF_5_6;\n else if (version == \"5.5\")\n return odb::defout::Version::DEF_5_5;\n else if (version == \"5.4\")\n return odb::defout::Version::DEF_5_4;\n else if (version == \"5.3\")\n return odb::defout::Version::DEF_5_3;\n else \n return odb::defout::Version::DEF_5_8;\n}\n\nvoid\nOpenRoad::writeDef(const char *filename,\n\t\t string version)\n{\n odb::dbChip *chip = db_->getChip();\n if (chip) {\n odb::dbBlock *block = chip->getBlock();\n if (block) {\n odb::defout def_writer(logger_);\n def_writer.setVersion(stringToDefVersion(version));\n def_writer.writeBlock(block, filename);\n }\n }\n}\n\nvoid\nOpenRoad::readDb(const char *filename)\n{\n FILE *stream = fopen(filename, \"r\");\n if (stream == nullptr) {\n return;\n }\n\n db_->read(stream);\n fclose(stream);\n\n for (Observer* observer : observers_) {\n observer->postReadDb(db_);\n }\n}\n\nvoid\nOpenRoad::writeDb(const char *filename)\n{\n FILE *stream = fopen(filename, \"w\");\n if (stream) {\n db_->write(stream);\n fclose(stream);\n }\n}\n\nvoid\nOpenRoad::readVerilog(const char *filename)\n{\n dbReadVerilog(filename, verilog_network_);\n}\n\nvoid\nOpenRoad::linkDesign(const char *design_name)\n\n{\n dbLinkDesign(design_name, verilog_network_, db_, logger_);\n for (Observer* observer : observers_) {\n observer->postReadDb(db_);\n }\n}\n\nvoid\nOpenRoad::writeVerilog(const char *filename,\n\t\t bool sort,\n\t\t bool include_pwr_gnd,\n\t\t std::vector<sta::LibertyCell*> *remove_cells)\n{\n sta::writeVerilog(filename, sort, include_pwr_gnd,\n\t\t remove_cells, sta_->network());\n}\n\nbool\nOpenRoad::unitsInitialized()\n{\n \/\/ Units are set by the first liberty library read.\n return getDbNetwork()->defaultLibertyLibrary() != nullptr;\n}\n\nodb::Rect\nOpenRoad::getCore()\n{\n return ord::getCore(db_->getChip()->getBlock());\n}\n\nvoid OpenRoad::addObserver(Observer *observer)\n{\n assert(observer->owner_ == nullptr);\n observer->owner_ = this;\n observers_.insert(observer);\n}\n\nvoid OpenRoad::removeObserver(Observer *observer)\n{\n observer->owner_ = nullptr;\n observers_.erase(observer);\n}\n\nOpenRoad::Observer::~Observer()\n{\n if (owner_) {\n owner_->removeObserver(this);\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Need a header for these functions cherry uses in\n\/\/ InitFloorplan, Resizer, OpenDP.\n\nRect\ngetCore(dbBlock *block)\n{\n odb::Rect core;\n block->getCoreArea(core);\n return core;\n}\n\n\/\/ Return the point inside rect that is closest to pt.\nPoint\nclosestPtInRect(Rect rect,\n\t\tPoint pt)\n{\n return Point(min(max(pt.getX(), rect.xMin()), rect.xMax()),\n min(max(pt.getY(), rect.yMin()), rect.yMax()));\n}\n\nPoint\nclosestPtInRect(Rect rect,\n\t\tint x,\n\t\tint y)\n{\n return Point(min(max(x, rect.xMin()), rect.xMax()),\n min(max(y, rect.yMin()), rect.yMax()));\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\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#include <string>\n#include <iostream>\n#include <memory>\n#include <vector>\n#include <unordered_map>\n\n#include <boost\/program_options\/options_description.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\n#include \"assert.hpp\"\n#include \"Options.hpp\"\n\nusing namespace eddic;\n\nnamespace po = boost::program_options;\n\nstruct ConfigValue {\n bool defined;\n boost::any value;\n};\n\nstruct Configuration {\n std::unordered_map<std::string, ConfigValue> values;\n};\n\nstd::shared_ptr<Configuration> configuration;\nstd::unordered_map<std::string, std::vector<std::string>> triggers;\n\nbool desc_init = false;\npo::options_description visible(\"Usage : eddic [options] source.eddi\");\npo::options_description all(\"Usage : eddic [options] source.eddi\");\n\nstd::pair<std::string, std::string> numeric_parser(const std::string& s){\n if (s.find(\"-32\") == 0) {\n return make_pair(\"32\", std::string(\"true\"));\n } else if (s.find(\"-64\") == 0) {\n return make_pair(\"64\", std::string(\"true\"));\n } else {\n return make_pair(std::string(), std::string());\n }\n}\n\nvoid add_trigger(const std::string& option, std::vector<std::string> childs){\n triggers[option] = childs; \n}\n\ninline void trigger_childs(const std::vector<std::string>& childs){\n for(auto& child : childs){\n configuration->values[child].defined = true;\n configuration->values[child].value = std::string(\"true\");\n }\n}\n\nbool eddic::parseOptions(int argc, const char* argv[]) {\n try {\n \/\/Only if the description has not been already defined\n if(!desc_init){\n po::options_description general(\"General options\");\n general.add_options()\n (\"help,h\", \"Generate this help message\")\n (\"assembly,S\", \"Generate only the assembly\")\n (\"keep,k\", \"Keep the assembly file\")\n (\"version\", \"Print the version of eddic\")\n (\"output,o\", po::value<std::string>()->default_value(\"a.out\"), \"Set the name of the executable\")\n \n (\"debug,g\", \"Add debugging symbols\")\n \n (\"32\", \"Force the compilation for 32 bits platform\")\n (\"64\", \"Force the compilation for 64 bits platform\")\n\n (\"warning-all\", \"Enable all the warning messages\")\n (\"warning-unused\", \"Warn about unused variables, parameters and functions\")\n (\"warning-cast\", \"Warn about useless casts\");\n \n po::options_description display(\"Display options\");\n display.add_options()\n (\"ast\", \"Print the Abstract Syntax Tree representation of the source\")\n (\"ast-only\", \"Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)\")\n\n (\"mtac\", \"Print the medium-level Three Address Code representation of the source\")\n (\"mtac-opt\", \"Print the medium-level Three Address Code representation of the source before any optimization has been performed\")\n (\"mtac-only\", \"Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)\")\n\n (\"ltac\", \"Print the low-level Three Address Code representation of the source\")\n (\"ltac-only\", \"Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)\");\n\n po::options_description optimization(\"Optimization options\");\n optimization.add_options()\n (\"Opt,O\", po::value<int>()->implicit_value(0), \"Define the optimization level\")\n (\"O0\", \"Disable all optimizations\")\n (\"O1\", \"Enable low-level optimizations\")\n (\"O2\", \"Enable all optimizations. This can be slow for big programs.\")\n \n (\"fglobal-optimization\", \"Enable optimizer engine\")\n (\"fpeephole-optimization\", \"Enable peephole optimizer\")\n (\"fno-inline-functions\", \"Disable inlining\");\n \n po::options_description backend(\"Backend options\");\n backend.add_options()\n (\"quiet,q\", \"Do not print anything\")\n (\"verbose,v\", \"Make the compiler verbose\")\n (\"dev,d\", \"Activate development mode (very verbose)\")\n (\"perfs\", \"Display performance information\")\n (\"input\", po::value<std::string>(), \"Input file\");\n\n all.add(general).add(display).add(optimization).add(backend);\n visible.add(general).add(display).add(optimization);\n\n add_trigger(\"warning-all\", {\"warning-unused\", \"warning-cast\"});\n \n \/\/TODO Should be a better way to do that\n add_trigger(\"__1\", {\"fpeephole-optimization\"});\n add_trigger(\"__2\", {\"fglobal-optimization\"});\n \n desc_init = true;\n }\n\n \/\/Add the option of the input file\n po::positional_options_description p;\n p.add(\"input\", -1);\n\n \/\/Create a new set of options\n po::variables_map options;\n\n \/\/Create a new configuration\n configuration = std::make_shared<Configuration>();\n\n \/\/Parse the command line options\n po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options);\n po::notify(options);\n\n \/\/Transfer the options in the eddic configuration\n for(auto& option : all.options()){\n ConfigValue value;\n\n if(options.count(option->long_name())){\n value.defined = true;\n value.value = options[option->long_name()].value();\n } else {\n value.defined = false;\n value.value = std::string(\"false\");\n }\n\n configuration->values[option->long_name()] = value;\n }\n\n if(options.count(\"O0\") + options.count(\"O1\") + options.count(\"O2\") > 1){\n std::cout << \"Invalid command line options : only one optimization level should be set\" << std::endl;\n\n return false;\n }\n\n if(options.count(\"64\") && options.count(\"32\")){\n std::cout << \"Invalid command line options : a compilation cannot be both 32 and 64 bits\" << std::endl;\n\n return false;\n }\n\n \/\/TODO Perhaps a more clear way to do that\n if(options.count(\"O0\")){\n configuration->values[\"Opt\"].value = 0;\n } else if(options.count(\"O1\")){\n configuration->values[\"Opt\"].value = 1;\n } else if(options.count(\"O2\")){\n configuration->values[\"Opt\"].value = 2;\n }\n\n \/\/Triggers dependent options\n for(auto& trigger : triggers){\n if(option_defined(trigger.first)){\n trigger_childs(trigger.second);\n }\n }\n\n if(option_int_value(\"Opt\") >= 1){\n trigger_childs(triggers[\"__1\"]);\n } \n \n if(option_int_value(\"Opt\") >= 2){\n trigger_childs(triggers[\"__2\"]);\n }\n } catch (const po::ambiguous_option& e) {\n std::cout << \"Invalid command line options : \" << e.what() << std::endl;\n\n return false;\n } catch (const po::unknown_option& e) {\n std::cout << \"Invalid command line options : \" << e.what() << std::endl;\n\n return false;\n } catch (const po::multiple_occurrences& e) {\n std::cout << \"Only one file can be compiled\" << std::endl;\n\n return false;\n }\n\n return true;\n}\n\nbool eddic::option_defined(const std::string& option_name){\n ASSERT(configuration, \"The configuration have not been initialized\");\n\n return configuration->values[option_name].defined;\n}\n\nstd::string eddic::option_value(const std::string& option_name){\n ASSERT(configuration, \"The configuration have not been initialized\");\n\n return boost::any_cast<std::string>(configuration->values[option_name].value);\n}\n\nint eddic::option_int_value(const std::string& option_name){\n ASSERT(configuration, \"The configuration have not been initialized\");\n\n return boost::any_cast<int>(configuration->values[option_name].value);\n}\n\nvoid eddic::print_help(){\n std::cout << visible << std::endl;\n}\n\nvoid eddic::print_version(){\n std::cout << \"eddic version 1.0.2\" << std::endl;\n}\n<commit_msg>Fix optimization levels<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\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#include <string>\n#include <iostream>\n#include <memory>\n#include <vector>\n#include <unordered_map>\n\n#include <boost\/program_options\/options_description.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\n#include \"assert.hpp\"\n#include \"Options.hpp\"\n\nusing namespace eddic;\n\nnamespace po = boost::program_options;\n\nstruct ConfigValue {\n bool defined;\n boost::any value;\n};\n\nstruct Configuration {\n std::unordered_map<std::string, ConfigValue> values;\n};\n\nstd::shared_ptr<Configuration> configuration;\nstd::unordered_map<std::string, std::vector<std::string>> triggers;\n\nbool desc_init = false;\npo::options_description visible(\"Usage : eddic [options] source.eddi\");\npo::options_description all(\"Usage : eddic [options] source.eddi\");\n\nstd::pair<std::string, std::string> numeric_parser(const std::string& s){\n if (s.find(\"-32\") == 0) {\n return make_pair(\"32\", std::string(\"true\"));\n } else if (s.find(\"-64\") == 0) {\n return make_pair(\"64\", std::string(\"true\"));\n } else {\n return make_pair(std::string(), std::string());\n }\n}\n\nvoid add_trigger(const std::string& option, std::vector<std::string> childs){\n triggers[option] = childs; \n}\n\ninline void trigger_childs(const std::vector<std::string>& childs){\n for(auto& child : childs){\n configuration->values[child].defined = true;\n configuration->values[child].value = std::string(\"true\");\n }\n}\n\nbool eddic::parseOptions(int argc, const char* argv[]) {\n try {\n \/\/Only if the description has not been already defined\n if(!desc_init){\n po::options_description general(\"General options\");\n general.add_options()\n (\"help,h\", \"Generate this help message\")\n (\"assembly,S\", \"Generate only the assembly\")\n (\"keep,k\", \"Keep the assembly file\")\n (\"version\", \"Print the version of eddic\")\n (\"output,o\", po::value<std::string>()->default_value(\"a.out\"), \"Set the name of the executable\")\n \n (\"debug,g\", \"Add debugging symbols\")\n \n (\"32\", \"Force the compilation for 32 bits platform\")\n (\"64\", \"Force the compilation for 64 bits platform\")\n\n (\"warning-all\", \"Enable all the warning messages\")\n (\"warning-unused\", \"Warn about unused variables, parameters and functions\")\n (\"warning-cast\", \"Warn about useless casts\");\n \n po::options_description display(\"Display options\");\n display.add_options()\n (\"ast\", \"Print the Abstract Syntax Tree representation of the source\")\n (\"ast-only\", \"Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)\")\n\n (\"mtac\", \"Print the medium-level Three Address Code representation of the source\")\n (\"mtac-opt\", \"Print the medium-level Three Address Code representation of the source before any optimization has been performed\")\n (\"mtac-only\", \"Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)\")\n\n (\"ltac\", \"Print the low-level Three Address Code representation of the source\")\n (\"ltac-only\", \"Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)\");\n\n po::options_description optimization(\"Optimization options\");\n optimization.add_options()\n (\"Opt,O\", po::value<int>()->implicit_value(0)->default_value(2), \"Define the optimization level\")\n (\"O0\", \"Disable all optimizations\")\n (\"O1\", \"Enable low-level optimizations\")\n (\"O2\", \"Enable all optimizations. This can be slow for big programs.\")\n \n (\"fglobal-optimization\", \"Enable optimizer engine\")\n (\"fpeephole-optimization\", \"Enable peephole optimizer\")\n (\"fno-inline-functions\", \"Disable inlining\");\n \n po::options_description backend(\"Backend options\");\n backend.add_options()\n (\"quiet,q\", \"Do not print anything\")\n (\"verbose,v\", \"Make the compiler verbose\")\n (\"dev,d\", \"Activate development mode (very verbose)\")\n (\"perfs\", \"Display performance information\")\n (\"input\", po::value<std::string>(), \"Input file\");\n\n all.add(general).add(display).add(optimization).add(backend);\n visible.add(general).add(display).add(optimization);\n\n add_trigger(\"warning-all\", {\"warning-unused\", \"warning-cast\"});\n \n \/\/TODO Should be a better way to do that\n add_trigger(\"__1\", {\"fpeephole-optimization\"});\n add_trigger(\"__2\", {\"fglobal-optimization\"});\n \n desc_init = true;\n }\n\n \/\/Add the option of the input file\n po::positional_options_description p;\n p.add(\"input\", -1);\n\n \/\/Create a new set of options\n po::variables_map options;\n\n \/\/Create a new configuration\n configuration = std::make_shared<Configuration>();\n\n \/\/Parse the command line options\n po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options);\n po::notify(options);\n\n \/\/Transfer the options in the eddic configuration\n for(auto& option : all.options()){\n ConfigValue value;\n\n if(options.count(option->long_name())){\n value.defined = true;\n value.value = options[option->long_name()].value();\n } else {\n value.defined = false;\n value.value = std::string(\"false\");\n }\n\n configuration->values[option->long_name()] = value;\n }\n\n if(options.count(\"O0\") + options.count(\"O1\") + options.count(\"O2\") > 1){\n std::cout << \"Invalid command line options : only one optimization level should be set\" << std::endl;\n\n return false;\n }\n\n if(options.count(\"64\") && options.count(\"32\")){\n std::cout << \"Invalid command line options : a compilation cannot be both 32 and 64 bits\" << std::endl;\n\n return false;\n }\n\n \/\/TODO Perhaps a more clear way to do that\n if(options.count(\"O0\")){\n configuration->values[\"Opt\"].value = 0;\n } else if(options.count(\"O1\")){\n configuration->values[\"Opt\"].value = 1;\n } else if(options.count(\"O2\")){\n configuration->values[\"Opt\"].value = 2;\n }\n\n \/\/Triggers dependent options\n for(auto& trigger : triggers){\n if(option_defined(trigger.first)){\n trigger_childs(trigger.second);\n }\n }\n\n if(option_int_value(\"Opt\") >= 1){\n trigger_childs(triggers[\"__1\"]);\n } \n \n if(option_int_value(\"Opt\") >= 2){\n trigger_childs(triggers[\"__2\"]);\n }\n } catch (const po::ambiguous_option& e) {\n std::cout << \"Invalid command line options : \" << e.what() << std::endl;\n\n return false;\n } catch (const po::unknown_option& e) {\n std::cout << \"Invalid command line options : \" << e.what() << std::endl;\n\n return false;\n } catch (const po::multiple_occurrences& e) {\n std::cout << \"Only one file can be compiled\" << std::endl;\n\n return false;\n }\n\n return true;\n}\n\nbool eddic::option_defined(const std::string& option_name){\n ASSERT(configuration, \"The configuration have not been initialized\");\n\n return configuration->values[option_name].defined;\n}\n\nstd::string eddic::option_value(const std::string& option_name){\n ASSERT(configuration, \"The configuration have not been initialized\");\n\n return boost::any_cast<std::string>(configuration->values[option_name].value);\n}\n\nint eddic::option_int_value(const std::string& option_name){\n ASSERT(configuration, \"The configuration have not been initialized\");\n\n return boost::any_cast<int>(configuration->values[option_name].value);\n}\n\nvoid eddic::print_help(){\n std::cout << visible << std::endl;\n}\n\nvoid eddic::print_version(){\n std::cout << \"eddic version 1.0.2\" << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file PhiTiny.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef PHITINY_HPP\n#define PHITINY_HPP\n\n#include <stdint.h>\n#include <vector>\n#include <cassert>\n\nnamespace primecount {\n\n\/\/\/ This class calculates phi(x, a) in constant time for small values\n\/\/\/ of a < 7 using lookup tables. Let pp = prime_products_[a]:\n\/\/\/ phi(x, a) = (x \/ pp) * φ(pp) + phi(x % pp, a).\n\/\/\/\nclass PhiTiny {\npublic:\n PhiTiny()\n {\n phi_cache_[0].push_back(0);\n\n \/\/ Initialize the phi_cache_ lookup tables\n for (int a = 1; is_cached(a); a++)\n {\n phi_cache_[a].reserve(prime_products_[a]);\n for (int x = 0; x < prime_products_[a]; x++)\n phi_cache_[a].push_back(static_cast<int16_t>(phi(x, a - 1) - phi(x \/ primes_[a], a - 1)));\n }\n }\n static bool is_cached(int64_t a)\n {\n return a >= 0 && a < 7;\n }\n \/\/\/ Partial sieve function (a.k.a. Legendre-sum).\n \/\/\/ phi(x, a) counts the numbers <= x that are not divisible\n \/\/\/ by any of the first a primes.\n \/\/\/ @pre is_cached(a) == true.\n \/\/\/\n int64_t phi(int64_t x, int64_t a) const\n {\n assert(is_cached(a));\n assert(x >= 0);\n return (x \/ prime_products_[a]) * totients_[a] + phi_cache_[a][x % prime_products_[a]];\n }\nprivate:\n std::vector<int16_t> phi_cache_[7];\n static const int32_t primes_[7];\n static const int32_t prime_products_[7];\n static const int32_t totients_[7];\n};\n\n} \/\/ namespace primecount\n\n#endif\n<commit_msg>Moved code from PhiTiny.hpp to PhiTiny.cpp<commit_after>\/\/\/\n\/\/\/ @file PhiTiny.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef PHITINY_HPP\n#define PHITINY_HPP\n\n#include <stdint.h>\n#include <vector>\n#include <cassert>\n\nnamespace primecount {\n\n\/\/\/ This class calculates phi(x, a) in constant time for small values\n\/\/\/ of a < 7 using lookup tables. Let pp = prime_products_[a]:\n\/\/\/ phi(x, a) = (x \/ pp) * φ(pp) + phi(x % pp, a).\n\/\/\/\nclass PhiTiny {\npublic:\n PhiTiny();\n static bool is_cached(int64_t a)\n {\n return a >= 0 && a < 7;\n }\n \/\/\/ Partial sieve function (a.k.a. Legendre-sum).\n \/\/\/ phi(x, a) counts the numbers <= x that are not divisible\n \/\/\/ by any of the first a primes.\n \/\/\/ @pre is_cached(a) == true.\n \/\/\/\n int64_t phi(int64_t x, int64_t a) const\n {\n assert(is_cached(a));\n assert(x >= 0);\n return (x \/ prime_products_[a]) * totients_[a] + phi_cache_[a][x % prime_products_[a]];\n }\nprivate:\n std::vector<int16_t> phi_cache_[7];\n static const int32_t primes_[7];\n static const int32_t prime_products_[7];\n static const int32_t totients_[7];\n};\n\n} \/\/ namespace primecount\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include <ncurses.h>\n\n#include \"concat_c.hh\"\n#include \"configuration.hh\"\n#include \"contents.hh\"\n#include \"file_contents.hh\"\n#include \"..\/lib.hh\"\n#include \"key_aliases.hh\"\n#include \"show_message.hh\"\n#include \"vick-move\/lib.hh\"\n#include \"print_contents.hh\"\n\nnamespace vick {\nnamespace insert_mode {\n\nstruct insert_c : public change {\n const std::string track;\n const move_t y, x;\n insert_c(const std::string& track, move_t y, move_t x)\n : track(track)\n , y(y)\n , x(x) {}\n virtual bool is_overriding() const noexcept override {\n return true;\n }\n virtual void undo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) +\n contents.cont[y].substr(x + track.size());\n contents.y = y;\n contents.x = x;\n if (contents.x and contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual void redo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) + track +\n contents.cont[y].substr(x);\n contents.y = y;\n contents.x = x + track.size();\n if (contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override {\n return std::make_shared<insert_c>(track, contents.y,\n contents.x);\n }\n};\n\nstruct newline_c : public change {\n const std::string first, second;\n const move_t y;\n newline_c(const contents& contents)\n : first(contents.cont[contents.y].substr(0, contents.x))\n , second(contents.cont[contents.y].substr(contents.x))\n , y(contents.y) {}\n virtual bool is_overriding() const noexcept override {\n return true;\n }\n virtual void undo(contents& contents) override {\n contents.cont[y] = first + second;\n contents.cont.erase(contents.cont.begin() + y + 1);\n contents.y = y;\n contents.x = first.size();\n }\n virtual void redo(contents& contents) override {\n contents.cont[y] = first;\n contents.cont.insert(contents.cont.begin() + y + 1, second);\n contents.y = y + 1;\n contents.x = 0;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override {\n return std::make_shared<newline_c>(contents);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_insert_mode(contents& contents, boost::optional<int> pref) {\n std::string track;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT--\");\n if (contents.refresh) {\n print_contents(contents);\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (track.size())\n changes.push_back(\n std::make_shared<insert_c>(track, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_insert_mode(contents, pref);\n if (recursed)\n changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n track += ch;\n } else {\n contents.cont[contents.y].insert(contents.x, 1, ch);\n contents.x++;\n track += ch;\n }\n if (contents.refresh) {\n print_contents(contents);\n show_message(\"--INSERT--\");\n }\n }\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<insert_c>(track, contents.y, x));\n}\n\nstruct replace_c : public change {\n const std::string o, n;\n const move_t y, x;\n replace_c(const std::string& o, const std::string& n, move_t y,\n move_t x)\n : o(o)\n , n(n)\n , y(y)\n , x(x) {}\n virtual bool is_overriding() const noexcept override {\n return true;\n }\n virtual void undo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) + o +\n contents.cont[y].substr(x + o.size());\n }\n virtual void redo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) + n +\n contents.cont[y].substr(x + n.size());\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override {\n return std::make_shared<replace_c>(contents.cont[contents.y]\n .substr(contents.x,\n n.size()),\n n, contents.y, contents.x);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_replace_mode(contents& contents, boost::optional<int> pref) {\n std::string o, n;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT (REPLACE)--\");\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT (REPLACE)--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n o = contents.cont[contents.y][contents.x];\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (o.size())\n changes.push_back(\n std::make_shared<replace_c>(o, n, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_replace_mode(contents, pref);\n if (recursed)\n changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n n += ch;\n } else {\n o += contents.cont[contents.y][contents.x];\n n += ch;\n contents.cont[contents.y][contents.x] = ch;\n contents.x++;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT (REPLACE)--\");\n }\n }\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<replace_c>(o, n, contents.y, x));\n}\n\nstruct append_c : public change {\n const std::string track;\n const move_t y, x;\n append_c(const std::string& track, move_t y, move_t x)\n : track(track)\n , y(y)\n , x(x) {}\n virtual bool is_overriding() const noexcept override {\n return true;\n }\n virtual void undo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) +\n contents.cont[y].substr(x + track.size());\n contents.y = y;\n contents.x = x;\n if (contents.x and contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual void redo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) + track +\n contents.cont[y].substr(x);\n contents.y = y;\n contents.x = x + track.size();\n if (contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override {\n return std::make_shared<append_c>(track, contents.y,\n contents.x + 1);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_append_mode(contents& contents, boost::optional<int> pref) {\n if (contents.cont[contents.y].empty())\n return enter_insert_mode(contents, pref);\n contents.x++;\n std::string track;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT--\");\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (track.size())\n changes.push_back(\n std::make_shared<insert_c>(track, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_insert_mode(contents, pref);\n if (recursed)\n changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n track += ch;\n } else {\n contents.cont[contents.y].insert(contents.x, 1, ch);\n contents.x++;\n track += ch;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n }\n showing_message = false;\n \/\/ cancel out ++ from beginning\n if (contents.x != 0)\n contents.x--;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<append_c>(track, contents.y, x));\n}\n}\n}\n<commit_msg>Reorder includes<commit_after>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include <ncurses.h>\n\n#include \"..\/lib.hh\"\n#include \"concat_c.hh\"\n#include \"configuration.hh\"\n#include \"contents.hh\"\n#include \"file_contents.hh\"\n#include \"key_aliases.hh\"\n#include \"print_contents.hh\"\n#include \"show_message.hh\"\n#include \"vick-move\/lib.hh\"\n\nnamespace vick {\nnamespace insert_mode {\n\nstruct insert_c : public change {\n const std::string track;\n const move_t y, x;\n insert_c(const std::string& track, move_t y, move_t x)\n : track(track)\n , y(y)\n , x(x) {}\n virtual bool is_overriding() const noexcept override {\n return true;\n }\n virtual void undo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) +\n contents.cont[y].substr(x + track.size());\n contents.y = y;\n contents.x = x;\n if (contents.x and contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual void redo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) + track +\n contents.cont[y].substr(x);\n contents.y = y;\n contents.x = x + track.size();\n if (contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override {\n return std::make_shared<insert_c>(track, contents.y,\n contents.x);\n }\n};\n\nstruct newline_c : public change {\n const std::string first, second;\n const move_t y;\n newline_c(const contents& contents)\n : first(contents.cont[contents.y].substr(0, contents.x))\n , second(contents.cont[contents.y].substr(contents.x))\n , y(contents.y) {}\n virtual bool is_overriding() const noexcept override {\n return true;\n }\n virtual void undo(contents& contents) override {\n contents.cont[y] = first + second;\n contents.cont.erase(contents.cont.begin() + y + 1);\n contents.y = y;\n contents.x = first.size();\n }\n virtual void redo(contents& contents) override {\n contents.cont[y] = first;\n contents.cont.insert(contents.cont.begin() + y + 1, second);\n contents.y = y + 1;\n contents.x = 0;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override {\n return std::make_shared<newline_c>(contents);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_insert_mode(contents& contents, boost::optional<int> pref) {\n std::string track;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT--\");\n if (contents.refresh) {\n print_contents(contents);\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (track.size())\n changes.push_back(\n std::make_shared<insert_c>(track, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_insert_mode(contents, pref);\n if (recursed)\n changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n track += ch;\n } else {\n contents.cont[contents.y].insert(contents.x, 1, ch);\n contents.x++;\n track += ch;\n }\n if (contents.refresh) {\n print_contents(contents);\n show_message(\"--INSERT--\");\n }\n }\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<insert_c>(track, contents.y, x));\n}\n\nstruct replace_c : public change {\n const std::string o, n;\n const move_t y, x;\n replace_c(const std::string& o, const std::string& n, move_t y,\n move_t x)\n : o(o)\n , n(n)\n , y(y)\n , x(x) {}\n virtual bool is_overriding() const noexcept override {\n return true;\n }\n virtual void undo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) + o +\n contents.cont[y].substr(x + o.size());\n }\n virtual void redo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) + n +\n contents.cont[y].substr(x + n.size());\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override {\n return std::make_shared<replace_c>(contents.cont[contents.y]\n .substr(contents.x,\n n.size()),\n n, contents.y, contents.x);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_replace_mode(contents& contents, boost::optional<int> pref) {\n std::string o, n;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT (REPLACE)--\");\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT (REPLACE)--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n o = contents.cont[contents.y][contents.x];\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (o.size())\n changes.push_back(\n std::make_shared<replace_c>(o, n, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_replace_mode(contents, pref);\n if (recursed)\n changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n n += ch;\n } else {\n o += contents.cont[contents.y][contents.x];\n n += ch;\n contents.cont[contents.y][contents.x] = ch;\n contents.x++;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT (REPLACE)--\");\n }\n }\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<replace_c>(o, n, contents.y, x));\n}\n\nstruct append_c : public change {\n const std::string track;\n const move_t y, x;\n append_c(const std::string& track, move_t y, move_t x)\n : track(track)\n , y(y)\n , x(x) {}\n virtual bool is_overriding() const noexcept override {\n return true;\n }\n virtual void undo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) +\n contents.cont[y].substr(x + track.size());\n contents.y = y;\n contents.x = x;\n if (contents.x and contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual void redo(contents& contents) override {\n contents.cont[y] = contents.cont[y].substr(0, x) + track +\n contents.cont[y].substr(x);\n contents.y = y;\n contents.x = x + track.size();\n if (contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override {\n return std::make_shared<append_c>(track, contents.y,\n contents.x + 1);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_append_mode(contents& contents, boost::optional<int> pref) {\n if (contents.cont[contents.y].empty())\n return enter_insert_mode(contents, pref);\n contents.x++;\n std::string track;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT--\");\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (track.size())\n changes.push_back(\n std::make_shared<insert_c>(track, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_insert_mode(contents, pref);\n if (recursed)\n changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n track += ch;\n } else {\n contents.cont[contents.y].insert(contents.x, 1, ch);\n contents.x++;\n track += ch;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n }\n showing_message = false;\n \/\/ cancel out ++ from beginning\n if (contents.x != 0)\n contents.x--;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<append_c>(track, contents.y, x));\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**********************************************************************************\n\n Infomap software package for multi-level network clustering\n\n Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall\n\n For more information, see <http:\/\/www.mapequation.org>\n\n\n This file is part of Infomap software package.\n\n Infomap software package is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Infomap software package 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 Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with Infomap software package. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n**********************************************************************************\/\n\n\n#include \"version.h\"\n\n#ifdef NS_INFOMAP\nnamespace infomap\n{\n#endif\n\nconst char* INFOMAP_VERSION = \"0.18.4\";\n\n#ifdef NS_INFOMAP\n}\n#endif\n<commit_msg>Bump version<commit_after>\/**********************************************************************************\n\n Infomap software package for multi-level network clustering\n\n Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall\n\n For more information, see <http:\/\/www.mapequation.org>\n\n\n This file is part of Infomap software package.\n\n Infomap software package is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Infomap software package 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 Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with Infomap software package. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n**********************************************************************************\/\n\n\n#include \"version.h\"\n\n#ifdef NS_INFOMAP\nnamespace infomap\n{\n#endif\n\nconst char* INFOMAP_VERSION = \"0.18.5\";\n\n#ifdef NS_INFOMAP\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n *\n * Copyright 2010 VMware, Inc.\n * All Rights Reserved.\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 **************************************************************************\/\n\n#include <windows.h>\n\n#include <assert.h>\n#include <string.h>\n#include <stdio.h>\n\n#include <string>\n\n#include \"os.hpp\"\n#include \"os_string.hpp\"\n\n\nnamespace os {\n\n\n\/* \n * Trick from http:\/\/locklessinc.com\/articles\/pthreads_on_windows\/\n *\/\nstatic CRITICAL_SECTION\ncriticalSection = {\n (PCRITICAL_SECTION_DEBUG)-1, -1, 0, 0, 0, 0\n};\n\n\nvoid\nacquireMutex(void)\n{\n EnterCriticalSection(&criticalSection);\n}\n\n\nvoid\nreleaseMutex(void)\n{\n LeaveCriticalSection(&criticalSection);\n}\n\n\nString\ngetProcessName(void)\n{\n String path;\n size_t size = MAX_PATH;\n char *buf = path.buf(size);\n\n DWORD nWritten = GetModuleFileNameA(NULL, buf, size);\n (void)nWritten;\n\n path.truncate();\n\n return path;\n}\n\nString\ngetCurrentDir(void)\n{\n String path;\n size_t size = MAX_PATH;\n char *buf = path.buf(size);\n \n DWORD ret = GetCurrentDirectoryA(size, buf);\n (void)ret;\n \n buf[size - 1] = 0;\n path.truncate();\n\n return path;\n}\n\nbool\nString::exists(void) const\n{\n DWORD attrs = GetFileAttributesA(str());\n return attrs != INVALID_FILE_ATTRIBUTES;\n}\n\n\/**\n * Determine whether an argument should be quoted.\n *\/\nstatic bool\nneedsQuote(const char *arg)\n{\n char c;\n while (true) {\n c = *arg++;\n if (c == '\\0') {\n break;\n }\n if (c == ' ' || c == '\\t' || c == '\\\"') {\n return true;\n }\n if (c == '\\\\') {\n c = *arg++;\n if (c == '\\0') {\n break;\n }\n if (c == '\"') {\n return true;\n }\n }\n }\n return false;\n}\n\nstatic void\nquoteArg(std::string &s, const char *arg)\n{\n char c;\n unsigned backslashes = 0;\n \n s.push_back('\"');\n while (true) {\n c = *arg++;\n switch (c)\n if (c == '\\0') {\n break;\n } else if (c == '\"') {\n while (backslashes) {\n s.push_back('\\\\');\n --backslashes;\n }\n s.push_back('\\\\');\n } else {\n if (c == '\\\\') {\n ++backslashes;\n } else {\n backslashes = 0;\n }\n }\n s.push_back(c);\n }\n s.push_back('\"');\n}\n\nint execute(char * const * args)\n{\n std::string commandLine;\n \n const char *arg0 = *args;\n const char *arg;\n char sep = 0;\n while ((arg = *args++) != NULL) {\n if (sep) {\n commandLine.push_back(sep);\n }\n\n if (needsQuote(arg)) {\n quoteArg(commandLine, arg);\n } else {\n commandLine.append(arg);\n }\n\n sep = ' ';\n }\n\n STARTUPINFO startupInfo;\n memset(&startupInfo, 0, sizeof(startupInfo));\n startupInfo.cb = sizeof(startupInfo);\n\n PROCESS_INFORMATION processInformation;\n\n if (!CreateProcessA(NULL,\n const_cast<char *>(commandLine.c_str()), \/\/ only modified by CreateProcessW\n 0, \/\/ process attributes\n 0, \/\/ thread attributes\n FALSE, \/\/ inherit handles\n 0, \/\/ creation flags,\n NULL, \/\/ environment\n NULL, \/\/ current directory\n &startupInfo,\n &processInformation\n )) {\n log(\"error: failed to execute %s\\n\", arg0);\n return -1;\n }\n\n WaitForSingleObject(processInformation.hProcess, INFINITE);\n\n DWORD exitCode = ~0;\n GetExitCodeProcess(processInformation.hProcess, &exitCode);\n\n CloseHandle(processInformation.hProcess);\n CloseHandle(processInformation.hThread);\n\n return (int)exitCode;\n}\n\nvoid\nlog(const char *format, ...)\n{\n char buf[4096];\n\n va_list ap;\n va_start(ap, format);\n fflush(stdout);\n vsnprintf(buf, sizeof buf, format, ap);\n va_end(ap);\n\n OutputDebugStringA(buf);\n\n \/*\n * Also write the message to stderr, when a debugger is not present (to\n * avoid duplicate messages in command line debuggers).\n *\/\n#if _WIN32_WINNT > 0x0400\n if (!IsDebuggerPresent()) {\n fflush(stdout);\n fputs(buf, stderr);\n fflush(stderr);\n }\n#endif\n}\n\nlong long\ngetTime(void)\n{\n static LARGE_INTEGER frequency;\n LARGE_INTEGER counter;\n if (!frequency.QuadPart)\n QueryPerformanceFrequency(&frequency);\n QueryPerformanceCounter(&counter);\n return counter.QuadPart*1000000LL\/frequency.QuadPart;\n}\n\nvoid\nabort(void)\n{\n#ifndef NDEBUG\n DebugBreak();\n#else\n ExitProcess(0);\n#endif\n}\n\n\nstatic LPTOP_LEVEL_EXCEPTION_FILTER prevExceptionFilter = NULL;\nstatic void (*gCallback)(void) = NULL;\n\nstatic LONG WINAPI\nunhandledExceptionFilter(PEXCEPTION_POINTERS pExceptionInfo)\n{\n if (gCallback) {\n gCallback();\n }\n\n\tif (prevExceptionFilter) {\n\t\treturn prevExceptionFilter(pExceptionInfo);\n } else {\n\t\treturn EXCEPTION_CONTINUE_SEARCH;\n }\n}\n\nvoid\nsetExceptionCallback(void (*callback)(void))\n{\n assert(!gCallback);\n\n if (!gCallback) {\n gCallback = callback;\n\n assert(!prevExceptionFilter);\n\n \/*\n * TODO: Unfortunately it seems that the CRT will reset the exception\n * handler in certain circumnstances. See\n * http:\/\/www.codeproject.com\/KB\/winsdk\/crash_hook.aspx\n *\/\n prevExceptionFilter = SetUnhandledExceptionFilter(unhandledExceptionFilter);\n }\n}\n\nvoid\nresetExceptionCallback(void)\n{\n gCallback = NULL;\n}\n\n\n} \/* namespace os *\/\n<commit_msg>Use AddVectoredExceptionHandler<commit_after>\/**************************************************************************\n *\n * Copyright 2010 VMware, Inc.\n * All Rights Reserved.\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 **************************************************************************\/\n\n#include <windows.h>\n\n#include <assert.h>\n#include <string.h>\n#include <stdio.h>\n\n#include <string>\n\n#include \"os.hpp\"\n#include \"os_string.hpp\"\n\n\nnamespace os {\n\n\n\/* \n * Trick from http:\/\/locklessinc.com\/articles\/pthreads_on_windows\/\n *\/\nstatic CRITICAL_SECTION\ncriticalSection = {\n (PCRITICAL_SECTION_DEBUG)-1, -1, 0, 0, 0, 0\n};\n\n\nvoid\nacquireMutex(void)\n{\n EnterCriticalSection(&criticalSection);\n}\n\n\nvoid\nreleaseMutex(void)\n{\n LeaveCriticalSection(&criticalSection);\n}\n\n\nString\ngetProcessName(void)\n{\n String path;\n size_t size = MAX_PATH;\n char *buf = path.buf(size);\n\n DWORD nWritten = GetModuleFileNameA(NULL, buf, size);\n (void)nWritten;\n\n path.truncate();\n\n return path;\n}\n\nString\ngetCurrentDir(void)\n{\n String path;\n size_t size = MAX_PATH;\n char *buf = path.buf(size);\n \n DWORD ret = GetCurrentDirectoryA(size, buf);\n (void)ret;\n \n buf[size - 1] = 0;\n path.truncate();\n\n return path;\n}\n\nbool\nString::exists(void) const\n{\n DWORD attrs = GetFileAttributesA(str());\n return attrs != INVALID_FILE_ATTRIBUTES;\n}\n\n\/**\n * Determine whether an argument should be quoted.\n *\/\nstatic bool\nneedsQuote(const char *arg)\n{\n char c;\n while (true) {\n c = *arg++;\n if (c == '\\0') {\n break;\n }\n if (c == ' ' || c == '\\t' || c == '\\\"') {\n return true;\n }\n if (c == '\\\\') {\n c = *arg++;\n if (c == '\\0') {\n break;\n }\n if (c == '\"') {\n return true;\n }\n }\n }\n return false;\n}\n\nstatic void\nquoteArg(std::string &s, const char *arg)\n{\n char c;\n unsigned backslashes = 0;\n \n s.push_back('\"');\n while (true) {\n c = *arg++;\n switch (c)\n if (c == '\\0') {\n break;\n } else if (c == '\"') {\n while (backslashes) {\n s.push_back('\\\\');\n --backslashes;\n }\n s.push_back('\\\\');\n } else {\n if (c == '\\\\') {\n ++backslashes;\n } else {\n backslashes = 0;\n }\n }\n s.push_back(c);\n }\n s.push_back('\"');\n}\n\nint execute(char * const * args)\n{\n std::string commandLine;\n \n const char *arg0 = *args;\n const char *arg;\n char sep = 0;\n while ((arg = *args++) != NULL) {\n if (sep) {\n commandLine.push_back(sep);\n }\n\n if (needsQuote(arg)) {\n quoteArg(commandLine, arg);\n } else {\n commandLine.append(arg);\n }\n\n sep = ' ';\n }\n\n STARTUPINFO startupInfo;\n memset(&startupInfo, 0, sizeof(startupInfo));\n startupInfo.cb = sizeof(startupInfo);\n\n PROCESS_INFORMATION processInformation;\n\n if (!CreateProcessA(NULL,\n const_cast<char *>(commandLine.c_str()), \/\/ only modified by CreateProcessW\n 0, \/\/ process attributes\n 0, \/\/ thread attributes\n FALSE, \/\/ inherit handles\n 0, \/\/ creation flags,\n NULL, \/\/ environment\n NULL, \/\/ current directory\n &startupInfo,\n &processInformation\n )) {\n log(\"error: failed to execute %s\\n\", arg0);\n return -1;\n }\n\n WaitForSingleObject(processInformation.hProcess, INFINITE);\n\n DWORD exitCode = ~0;\n GetExitCodeProcess(processInformation.hProcess, &exitCode);\n\n CloseHandle(processInformation.hProcess);\n CloseHandle(processInformation.hThread);\n\n return (int)exitCode;\n}\n\nvoid\nlog(const char *format, ...)\n{\n char buf[4096];\n\n va_list ap;\n va_start(ap, format);\n fflush(stdout);\n vsnprintf(buf, sizeof buf, format, ap);\n va_end(ap);\n\n OutputDebugStringA(buf);\n\n \/*\n * Also write the message to stderr, when a debugger is not present (to\n * avoid duplicate messages in command line debuggers).\n *\/\n#if _WIN32_WINNT > 0x0400\n if (!IsDebuggerPresent()) {\n fflush(stdout);\n fputs(buf, stderr);\n fflush(stderr);\n }\n#endif\n}\n\nlong long\ngetTime(void)\n{\n static LARGE_INTEGER frequency;\n LARGE_INTEGER counter;\n if (!frequency.QuadPart)\n QueryPerformanceFrequency(&frequency);\n QueryPerformanceCounter(&counter);\n return counter.QuadPart*1000000LL\/frequency.QuadPart;\n}\n\nvoid\nabort(void)\n{\n#ifndef NDEBUG\n DebugBreak();\n#else\n ExitProcess(0);\n#endif\n}\n\n\nstatic PVOID prevExceptionFilter = NULL;\nstatic void (*gCallback)(void) = NULL;\n\nstatic LONG CALLBACK\nunhandledExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)\n{\n PEXCEPTION_RECORD pExceptionRecord = pExceptionInfo->ExceptionRecord;\n\n \/*\n * Ignore OutputDebugStringA exception.\n *\/\n if (pExceptionRecord->ExceptionCode == DBG_PRINTEXCEPTION_C) {\n return EXCEPTION_CONTINUE_SEARCH;\n }\n\n \/*\n * Ignore C++ exceptions\n *\n * http:\/\/support.microsoft.com\/kb\/185294\n * http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2010\/07\/30\/10044061.aspx\n *\/\n if (pExceptionRecord->ExceptionCode == 0xe06d7363) {\n return EXCEPTION_CONTINUE_SEARCH;\n }\n\n \/\/ Clear direction flag\n#ifdef _MSC_VER\n __asm {\n cld\n };\n#else\n asm(\"cld\");\n#endif\n\n log(\"apitrace: warning: caught exception 0x%08lx\\n\", pExceptionRecord->ExceptionCode);\n\n static int recursion_count = 0;\n if (recursion_count) {\n fprintf(stderr, \"apitrace: warning: recursion handling exception\\n\");\n } else {\n if (gCallback) {\n ++recursion_count;\n gCallback();\n --recursion_count;\n }\n }\n\n return EXCEPTION_CONTINUE_SEARCH;\n}\n\nvoid\nsetExceptionCallback(void (*callback)(void))\n{\n assert(!gCallback);\n\n if (!gCallback) {\n gCallback = callback;\n\n assert(!prevExceptionFilter);\n\n prevExceptionFilter = AddVectoredExceptionHandler(0, unhandledExceptionHandler);\n }\n}\n\nvoid\nresetExceptionCallback(void)\n{\n if (gCallback) {\n RemoveVectoredExceptionHandler(prevExceptionFilter);\n gCallback = NULL;\n }\n}\n\n\n} \/* namespace os *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Universite de Sherbrooke nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\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 ANY\nDIRECT, 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\nON ANY 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#include <ros\/ros.h>\n#include <sensor_msgs\/Image.h>\n#include <sensor_msgs\/image_encodings.h>\n#include <cv_bridge\/cv_bridge.h>\n#include <std_msgs\/Empty.h>\n#include <image_transport\/image_transport.h>\n#include <std_srvs\/Empty.h>\n\n#include <rtabmap\/core\/CameraRGB.h>\n#include <rtabmap\/core\/CameraThread.h>\n#include <rtabmap\/core\/CameraEvent.h>\n\n#include <rtabmap\/utilite\/ULogger.h>\n#include <rtabmap\/utilite\/UEventsHandler.h>\n#include <rtabmap\/utilite\/UEventsManager.h>\n#include <rtabmap\/utilite\/UDirectory.h>\n#include <rtabmap\/utilite\/UFile.h>\n\n#include <dynamic_reconfigure\/server.h>\n#include <rtabmap_ros\/CameraConfig.h>\n\nclass CameraWrapper : public UEventsHandler\n{\npublic:\n\t\/\/ Usb device like a Webcam\n\tCameraWrapper(int usbDevice = 0,\n\t\t\t float imageRate = 0,\n\t\t\t\t unsigned int imageWidth = 0,\n\t\t\t\t unsigned int imageHeight = 0) :\n\t\tcameraThread_(0),\n\t\tcamera_(0),\n\t\tframeId_(\"camera\")\n\t{\n\t\tros::NodeHandle nh;\n\t\tros::NodeHandle pnh(\"~\");\n\t\tpnh.param(\"frame_id\", frameId_, frameId_);\n\t\timage_transport::ImageTransport it(nh);\n\t\trosPublisher_ = it.advertise(\"image\", 1);\n\t\tstartSrv_ = nh.advertiseService(\"start_camera\", &CameraWrapper::startSrv, this);\n\t\tstopSrv_ = nh.advertiseService(\"stop_camera\", &CameraWrapper::stopSrv, this);\n\t\tUEventsManager::addHandler(this);\n\t}\n\n\tvirtual ~CameraWrapper()\n\t{\n\t\tif(cameraThread_)\n\t\t{\n\t\t\tcameraThread_->join(true);\n\t\t\tdelete cameraThread_;\n\t\t}\n\t}\n\n\tbool init()\n\t{\n\t\tif(cameraThread_)\n\t\t{\n\t\t\treturn cameraThread_->camera()->init();\n\t\t}\n\t\treturn false;\n\t}\n\n\tvoid start()\n\t{\n\t\tif(cameraThread_)\n\t\t{\n\t\t\treturn cameraThread_->start();\n\t\t}\n\t}\n\n\tbool startSrv(std_srvs::Empty::Request&, std_srvs::Empty::Response&)\n\t{\n\t\tROS_INFO(\"Camera started...\");\n\t\tif(cameraThread_)\n\t\t{\n\t\t\tcameraThread_->start();\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool stopSrv(std_srvs::Empty::Request&, std_srvs::Empty::Response&)\n\t{\n\t\tROS_INFO(\"Camera stopped...\");\n\t\tif(cameraThread_)\n\t\t{\n\t\t\tcameraThread_->kill();\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid setParameters(int deviceId, double frameRate, const std::string & path, bool pause)\n\t{\n\t\tROS_INFO(\"Parameters changed: deviceId=%d, path=%s frameRate=%f pause=%s\",\n\t\t\t\tdeviceId, path.c_str(), frameRate, pause?\"true\":\"false\");\n\t\tif(cameraThread_)\n\t\t{\n\t\t\trtabmap::CameraVideo * videoCam = dynamic_cast<rtabmap::CameraVideo *>(camera_);\n\t\t\trtabmap::CameraImages * imagesCam = dynamic_cast<rtabmap::CameraImages *>(camera_);\n\n\t\t\tif(imagesCam)\n\t\t\t{\n\t\t\t\t\/\/ images\n\t\t\t\tif(!path.empty() && UDirectory::getDir(path+\"\/\").compare(UDirectory::getDir(imagesCam->getPath())) == 0)\n\t\t\t\t{\n\t\t\t\t\timagesCam->setImageRate(frameRate);\n\t\t\t\t\tif(pause && !cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->join(true);\n\t\t\t\t\t}\n\t\t\t\t\telse if(!pause && cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->start();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdelete cameraThread_;\n\t\t\t\t\tcameraThread_ = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(videoCam)\n\t\t\t{\n\t\t\t\tif(!path.empty() && path.compare(videoCam->getFilePath()) == 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ video\n\t\t\t\t\tvideoCam->setImageRate(frameRate);\n\t\t\t\t\tif(pause && !cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->join(true);\n\t\t\t\t\t}\n\t\t\t\t\telse if(!pause && cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->start();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(path.empty() &&\n\t\t\t\t\t\tvideoCam->getFilePath().empty() &&\n\t\t\t\t\t\tvideoCam->getUsbDevice() == deviceId)\n\t\t\t\t{\n\t\t\t\t\t\/\/ usb device\n\t\t\t\t\tvideoCam->setImageRate(frameRate);\n\t\t\t\t\tif(pause && !cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->join(true);\n\t\t\t\t\t}\n\t\t\t\t\telse if(!pause && cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->start();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdelete cameraThread_;\n\t\t\t\t\tcameraThread_ = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tROS_ERROR(\"Wrong camera type ?!?\");\n\t\t\t\tdelete cameraThread_;\n\t\t\t\tcameraThread_ = 0;\n\t\t\t}\n\t\t}\n\n\t\tif(!cameraThread_)\n\t\t{\n\t\t\tif(!path.empty() && UDirectory::exists(path))\n\t\t\t{\n\t\t\t\t\/\/images\n\t\t\t\tcamera_ = new rtabmap::CameraImages(path, frameRate);\n\t\t\t}\n\t\t\telse if(!path.empty() && UFile::exists(path))\n\t\t\t{\n\t\t\t\t\/\/video\n\t\t\t\tcamera_ = new rtabmap::CameraVideo(path, false, frameRate);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(!path.empty() && !UDirectory::exists(path) && !UFile::exists(path))\n\t\t\t\t{\n\t\t\t\t\tROS_ERROR(\"Path \\\"%s\\\" does not exist (or you don't have the permissions to read)... falling back to usb device...\", path.c_str());\n\t\t\t\t}\n\t\t\t\t\/\/usb device\n\t\t\t\tcamera_ = new rtabmap::CameraVideo(deviceId, frameRate);\n\t\t\t}\n\t\t\tcameraThread_ = new rtabmap::CameraThread(camera_);\n\t\t\tinit();\n\t\t\tif(!pause)\n\t\t\t{\n\t\t\t\tstart();\n\t\t\t}\n\t\t}\n\t}\n\nprotected:\n\tvirtual void handleEvent(UEvent * event)\n\t{\n\t\tif(event->getClassName().compare(\"CameraEvent\") == 0)\n\t\t{\n\t\t\trtabmap::CameraEvent * e = (rtabmap::CameraEvent*)event;\n\t\t\tconst cv::Mat & image = e->data().imageRaw();\n\t\t\tif(!image.empty() && image.depth() == CV_8U)\n\t\t\t{\n\t\t\t\tcv_bridge::CvImage img;\n\t\t\t\tif(image.channels() == 1)\n\t\t\t\t{\n\t\t\t\t\timg.encoding = sensor_msgs::image_encodings::MONO8;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\timg.encoding = sensor_msgs::image_encodings::BGR8;\n\t\t\t\t}\n\t\t\t\timg.image = image;\n\t\t\t\tsensor_msgs::ImagePtr rosMsg = img.toImageMsg();\n\t\t\t\trosMsg->header.frame_id = frameId_;\n\t\t\t\trosMsg->header.stamp = ros::Time::now();\n\t\t\t\trosPublisher_.publish(rosMsg);\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\timage_transport::Publisher rosPublisher_;\n\trtabmap::CameraThread * cameraThread_;\n\trtabmap::Camera * camera_;\n\tros::ServiceServer startSrv_;\n\tros::ServiceServer stopSrv_;\n\tstd::string frameId_;\n};\n\nCameraWrapper * camera = 0;\nvoid callback(rtabmap_ros::CameraConfig &config, uint32_t level)\n{\n\tif(camera)\n\t{\n\t\tcamera->setParameters(config.device_id, config.frame_rate, config.video_or_images_path, config.pause);\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\tULogger::setType(ULogger::kTypeConsole);\n\t\/\/ULogger::setLevel(ULogger::kDebug);\n\tULogger::setEventLevel(ULogger::kWarning);\n\n\tros::init(argc, argv, \"camera\");\n\n\tros::NodeHandle nh(\"~\");\n\n\tcamera = new CameraWrapper(); \/\/ webcam device 0\n\n\tdynamic_reconfigure::Server<rtabmap_ros::CameraConfig> server;\n\tdynamic_reconfigure::Server<rtabmap_ros::CameraConfig>::CallbackType f;\n\tf = boost::bind(&callback, _1, _2);\n\tserver.setCallback(f);\n\n\tros::spin();\n\n\t\/\/cleanup\n\tif(camera)\n\t{\n\t\tdelete camera;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Updated CameraVideo interface<commit_after>\/*\nCopyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\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 the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Universite de Sherbrooke nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\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 ANY\nDIRECT, 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\nON ANY 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#include <ros\/ros.h>\n#include <sensor_msgs\/Image.h>\n#include <sensor_msgs\/image_encodings.h>\n#include <cv_bridge\/cv_bridge.h>\n#include <std_msgs\/Empty.h>\n#include <image_transport\/image_transport.h>\n#include <std_srvs\/Empty.h>\n\n#include <rtabmap\/core\/CameraRGB.h>\n#include <rtabmap\/core\/CameraThread.h>\n#include <rtabmap\/core\/CameraEvent.h>\n\n#include <rtabmap\/utilite\/ULogger.h>\n#include <rtabmap\/utilite\/UEventsHandler.h>\n#include <rtabmap\/utilite\/UEventsManager.h>\n#include <rtabmap\/utilite\/UDirectory.h>\n#include <rtabmap\/utilite\/UFile.h>\n\n#include <dynamic_reconfigure\/server.h>\n#include <rtabmap_ros\/CameraConfig.h>\n\nclass CameraWrapper : public UEventsHandler\n{\npublic:\n\t\/\/ Usb device like a Webcam\n\tCameraWrapper(int usbDevice = 0,\n\t\t\t float imageRate = 0,\n\t\t\t\t unsigned int imageWidth = 0,\n\t\t\t\t unsigned int imageHeight = 0) :\n\t\tcameraThread_(0),\n\t\tcamera_(0),\n\t\tframeId_(\"camera\")\n\t{\n\t\tros::NodeHandle nh;\n\t\tros::NodeHandle pnh(\"~\");\n\t\tpnh.param(\"frame_id\", frameId_, frameId_);\n\t\timage_transport::ImageTransport it(nh);\n\t\trosPublisher_ = it.advertise(\"image\", 1);\n\t\tstartSrv_ = nh.advertiseService(\"start_camera\", &CameraWrapper::startSrv, this);\n\t\tstopSrv_ = nh.advertiseService(\"stop_camera\", &CameraWrapper::stopSrv, this);\n\t\tUEventsManager::addHandler(this);\n\t}\n\n\tvirtual ~CameraWrapper()\n\t{\n\t\tif(cameraThread_)\n\t\t{\n\t\t\tcameraThread_->join(true);\n\t\t\tdelete cameraThread_;\n\t\t}\n\t}\n\n\tbool init()\n\t{\n\t\tif(cameraThread_)\n\t\t{\n\t\t\treturn cameraThread_->camera()->init();\n\t\t}\n\t\treturn false;\n\t}\n\n\tvoid start()\n\t{\n\t\tif(cameraThread_)\n\t\t{\n\t\t\treturn cameraThread_->start();\n\t\t}\n\t}\n\n\tbool startSrv(std_srvs::Empty::Request&, std_srvs::Empty::Response&)\n\t{\n\t\tROS_INFO(\"Camera started...\");\n\t\tif(cameraThread_)\n\t\t{\n\t\t\tcameraThread_->start();\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool stopSrv(std_srvs::Empty::Request&, std_srvs::Empty::Response&)\n\t{\n\t\tROS_INFO(\"Camera stopped...\");\n\t\tif(cameraThread_)\n\t\t{\n\t\t\tcameraThread_->kill();\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid setParameters(int deviceId, double frameRate, const std::string & path, bool pause)\n\t{\n\t\tROS_INFO(\"Parameters changed: deviceId=%d, path=%s frameRate=%f pause=%s\",\n\t\t\t\tdeviceId, path.c_str(), frameRate, pause?\"true\":\"false\");\n\t\tif(cameraThread_)\n\t\t{\n\t\t\trtabmap::CameraVideo * videoCam = dynamic_cast<rtabmap::CameraVideo *>(camera_);\n\t\t\trtabmap::CameraImages * imagesCam = dynamic_cast<rtabmap::CameraImages *>(camera_);\n\n\t\t\tif(imagesCam)\n\t\t\t{\n\t\t\t\t\/\/ images\n\t\t\t\tif(!path.empty() && UDirectory::getDir(path+\"\/\").compare(UDirectory::getDir(imagesCam->getPath())) == 0)\n\t\t\t\t{\n\t\t\t\t\timagesCam->setImageRate(frameRate);\n\t\t\t\t\tif(pause && !cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->join(true);\n\t\t\t\t\t}\n\t\t\t\t\telse if(!pause && cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->start();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdelete cameraThread_;\n\t\t\t\t\tcameraThread_ = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(videoCam)\n\t\t\t{\n\t\t\t\tif(!path.empty() && path.compare(videoCam->getFilePath()) == 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ video\n\t\t\t\t\tvideoCam->setImageRate(frameRate);\n\t\t\t\t\tif(pause && !cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->join(true);\n\t\t\t\t\t}\n\t\t\t\t\telse if(!pause && cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->start();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(path.empty() &&\n\t\t\t\t\t\tvideoCam->getFilePath().empty() &&\n\t\t\t\t\t\tvideoCam->getUsbDevice() == deviceId)\n\t\t\t\t{\n\t\t\t\t\t\/\/ usb device\n\t\t\t\t\tvideoCam->setImageRate(frameRate);\n\t\t\t\t\tif(pause && !cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->join(true);\n\t\t\t\t\t}\n\t\t\t\t\telse if(!pause && cameraThread_->isPaused())\n\t\t\t\t\t{\n\t\t\t\t\t\tcameraThread_->start();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdelete cameraThread_;\n\t\t\t\t\tcameraThread_ = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tROS_ERROR(\"Wrong camera type ?!?\");\n\t\t\t\tdelete cameraThread_;\n\t\t\t\tcameraThread_ = 0;\n\t\t\t}\n\t\t}\n\n\t\tif(!cameraThread_)\n\t\t{\n\t\t\tif(!path.empty() && UDirectory::exists(path))\n\t\t\t{\n\t\t\t\t\/\/images\n\t\t\t\tcamera_ = new rtabmap::CameraImages(path, frameRate);\n\t\t\t}\n\t\t\telse if(!path.empty() && UFile::exists(path))\n\t\t\t{\n\t\t\t\t\/\/video\n\t\t\t\tcamera_ = new rtabmap::CameraVideo(path, false, frameRate);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(!path.empty() && !UDirectory::exists(path) && !UFile::exists(path))\n\t\t\t\t{\n\t\t\t\t\tROS_ERROR(\"Path \\\"%s\\\" does not exist (or you don't have the permissions to read)... falling back to usb device...\", path.c_str());\n\t\t\t\t}\n\t\t\t\t\/\/usb device\n\t\t\t\tcamera_ = new rtabmap::CameraVideo(deviceId, false, frameRate);\n\t\t\t}\n\t\t\tcameraThread_ = new rtabmap::CameraThread(camera_);\n\t\t\tinit();\n\t\t\tif(!pause)\n\t\t\t{\n\t\t\t\tstart();\n\t\t\t}\n\t\t}\n\t}\n\nprotected:\n\tvirtual void handleEvent(UEvent * event)\n\t{\n\t\tif(event->getClassName().compare(\"CameraEvent\") == 0)\n\t\t{\n\t\t\trtabmap::CameraEvent * e = (rtabmap::CameraEvent*)event;\n\t\t\tconst cv::Mat & image = e->data().imageRaw();\n\t\t\tif(!image.empty() && image.depth() == CV_8U)\n\t\t\t{\n\t\t\t\tcv_bridge::CvImage img;\n\t\t\t\tif(image.channels() == 1)\n\t\t\t\t{\n\t\t\t\t\timg.encoding = sensor_msgs::image_encodings::MONO8;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\timg.encoding = sensor_msgs::image_encodings::BGR8;\n\t\t\t\t}\n\t\t\t\timg.image = image;\n\t\t\t\tsensor_msgs::ImagePtr rosMsg = img.toImageMsg();\n\t\t\t\trosMsg->header.frame_id = frameId_;\n\t\t\t\trosMsg->header.stamp = ros::Time::now();\n\t\t\t\trosPublisher_.publish(rosMsg);\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\timage_transport::Publisher rosPublisher_;\n\trtabmap::CameraThread * cameraThread_;\n\trtabmap::Camera * camera_;\n\tros::ServiceServer startSrv_;\n\tros::ServiceServer stopSrv_;\n\tstd::string frameId_;\n};\n\nCameraWrapper * camera = 0;\nvoid callback(rtabmap_ros::CameraConfig &config, uint32_t level)\n{\n\tif(camera)\n\t{\n\t\tcamera->setParameters(config.device_id, config.frame_rate, config.video_or_images_path, config.pause);\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\tULogger::setType(ULogger::kTypeConsole);\n\t\/\/ULogger::setLevel(ULogger::kDebug);\n\tULogger::setEventLevel(ULogger::kWarning);\n\n\tros::init(argc, argv, \"camera\");\n\n\tros::NodeHandle nh(\"~\");\n\n\tcamera = new CameraWrapper(); \/\/ webcam device 0\n\n\tdynamic_reconfigure::Server<rtabmap_ros::CameraConfig> server;\n\tdynamic_reconfigure::Server<rtabmap_ros::CameraConfig>::CallbackType f;\n\tf = boost::bind(&callback, _1, _2);\n\tserver.setCallback(f);\n\n\tros::spin();\n\n\t\/\/cleanup\n\tif(camera)\n\t{\n\t\tdelete camera;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2019 ARM Limited\n * SPDX-License-Identifier: Apache-2.0\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 \"drivers\/UARTSerial.h\"\n\n#if (DEVICE_SERIAL && DEVICE_INTERRUPTIN)\n\n#include \"platform\/mbed_poll.h\"\n#include \"platform\/mbed_thread.h\"\n\nnamespace mbed {\n\nUARTSerial::UARTSerial(PinName tx, PinName rx, int baud) :\n SerialBase(tx, rx, baud),\n _blocking(true),\n _tx_irq_enabled(false),\n _rx_irq_enabled(false),\n _tx_enabled(true),\n _rx_enabled(true),\n _dcd_irq(NULL)\n{\n \/* Attatch IRQ routines to the serial device. *\/\n enable_rx_irq();\n}\n\nUARTSerial::~UARTSerial()\n{\n delete _dcd_irq;\n}\n\nvoid UARTSerial::dcd_irq()\n{\n wake();\n}\n\nvoid UARTSerial::set_baud(int baud)\n{\n SerialBase::baud(baud);\n}\n\nvoid UARTSerial::set_data_carrier_detect(PinName dcd_pin, bool active_high)\n{\n delete _dcd_irq;\n _dcd_irq = NULL;\n\n if (dcd_pin != NC) {\n _dcd_irq = new InterruptIn(dcd_pin);\n if (active_high) {\n _dcd_irq->fall(callback(this, &UARTSerial::dcd_irq));\n } else {\n _dcd_irq->rise(callback(this, &UARTSerial::dcd_irq));\n }\n }\n}\n\nvoid UARTSerial::set_format(int bits, Parity parity, int stop_bits)\n{\n api_lock();\n SerialBase::format(bits, parity, stop_bits);\n api_unlock();\n}\n\n#if DEVICE_SERIAL_FC\nvoid UARTSerial::set_flow_control(Flow type, PinName flow1, PinName flow2)\n{\n api_lock();\n SerialBase::set_flow_control(type, flow1, flow2);\n api_unlock();\n}\n#endif\n\nint UARTSerial::close()\n{\n \/* Does not let us pass a file descriptor. So how to close ?\n * Also, does it make sense to close a device type file descriptor*\/\n return 0;\n}\n\nint UARTSerial::isatty()\n{\n return 1;\n\n}\n\noff_t UARTSerial::seek(off_t offset, int whence)\n{\n \/*XXX lseek can be done theoratically, but is it sane to mark positions on a dynamically growing\/shrinking\n * buffer system (from an interrupt context) *\/\n return -ESPIPE;\n}\n\nint UARTSerial::sync()\n{\n api_lock();\n\n while (!_txbuf.empty()) {\n api_unlock();\n \/\/ Doing better than wait would require TxIRQ to also do wake() when becoming empty. Worth it?\n thread_sleep_for(1);\n api_lock();\n }\n\n api_unlock();\n\n return 0;\n}\n\nvoid UARTSerial::sigio(Callback<void()> func)\n{\n core_util_critical_section_enter();\n _sigio_cb = func;\n if (_sigio_cb) {\n short current_events = poll(0x7FFF);\n if (current_events) {\n _sigio_cb();\n }\n }\n core_util_critical_section_exit();\n}\n\n\/* Special synchronous write designed to work from critical section, such\n * as in mbed_error_vprintf.\n *\/\nssize_t UARTSerial::write_unbuffered(const char *buf_ptr, size_t length)\n{\n while (!_txbuf.empty()) {\n tx_irq();\n }\n\n for (size_t data_written = 0; data_written < length; data_written++) {\n SerialBase::_base_putc(*buf_ptr++);\n }\n\n return length;\n}\n\nssize_t UARTSerial::write(const void *buffer, size_t length)\n{\n size_t data_written = 0;\n const char *buf_ptr = static_cast<const char *>(buffer);\n\n if (length == 0) {\n return 0;\n }\n\n if (core_util_in_critical_section()) {\n return write_unbuffered(buf_ptr, length);\n }\n\n api_lock();\n\n \/\/ Unlike read, we should write the whole thing if blocking. POSIX only\n \/\/ allows partial as a side-effect of signal handling; it normally tries to\n \/\/ write everything if blocking. Without signals we can always write all.\n while (data_written < length) {\n\n if (_txbuf.full()) {\n if (!_blocking) {\n break;\n }\n do {\n api_unlock();\n thread_sleep_for(1); \/\/ XXX todo - proper wait?\n api_lock();\n } while (_txbuf.full());\n }\n\n while (data_written < length && !_txbuf.full()) {\n _txbuf.push(*buf_ptr++);\n data_written++;\n }\n\n core_util_critical_section_enter();\n if (_tx_enabled && !_tx_irq_enabled) {\n UARTSerial::tx_irq(); \/\/ only write to hardware in one place\n if (!_txbuf.empty()) {\n enable_tx_irq();\n }\n }\n core_util_critical_section_exit();\n }\n\n api_unlock();\n\n return data_written != 0 ? (ssize_t) data_written : (ssize_t) - EAGAIN;\n}\n\nssize_t UARTSerial::read(void *buffer, size_t length)\n{\n size_t data_read = 0;\n\n char *ptr = static_cast<char *>(buffer);\n\n if (length == 0) {\n return 0;\n }\n\n api_lock();\n\n while (_rxbuf.empty()) {\n if (!_blocking) {\n api_unlock();\n return -EAGAIN;\n }\n api_unlock();\n thread_sleep_for(1); \/\/ XXX todo - proper wait?\n api_lock();\n }\n\n while (data_read < length && !_rxbuf.empty()) {\n _rxbuf.pop(*ptr++);\n data_read++;\n }\n\n core_util_critical_section_enter();\n if (_rx_enabled && !_rx_irq_enabled) {\n UARTSerial::rx_irq(); \/\/ only read from hardware in one place\n if (!_rxbuf.full()) {\n enable_rx_irq();\n }\n }\n core_util_critical_section_exit();\n\n api_unlock();\n\n return data_read;\n}\n\nbool UARTSerial::hup() const\n{\n return _dcd_irq && _dcd_irq->read() != 0;\n}\n\nvoid UARTSerial::wake()\n{\n if (_sigio_cb) {\n _sigio_cb();\n }\n}\n\nshort UARTSerial::poll(short events) const\n{\n\n short revents = 0;\n \/* Check the Circular Buffer if space available for writing out *\/\n\n\n if (!_rxbuf.empty()) {\n revents |= POLLIN;\n }\n\n \/* POLLHUP and POLLOUT are mutually exclusive *\/\n if (hup()) {\n revents |= POLLHUP;\n } else if (!_txbuf.full()) {\n revents |= POLLOUT;\n }\n\n \/*TODO Handle other event types *\/\n\n return revents;\n}\n\nvoid UARTSerial::lock()\n{\n \/\/ This is the override for SerialBase.\n \/\/ No lock required as we only use SerialBase from interrupt or from\n \/\/ inside our own critical section.\n}\n\nvoid UARTSerial::unlock()\n{\n \/\/ This is the override for SerialBase.\n}\n\nvoid UARTSerial::api_lock(void)\n{\n _mutex.lock();\n}\n\nvoid UARTSerial::api_unlock(void)\n{\n _mutex.unlock();\n}\n\nvoid UARTSerial::rx_irq(void)\n{\n bool was_empty = _rxbuf.empty();\n\n \/* Fill in the receive buffer if the peripheral is readable\n * and receive buffer is not full. *\/\n while (!_rxbuf.full() && SerialBase::readable()) {\n char data = SerialBase::_base_getc();\n _rxbuf.push(data);\n }\n\n if (_rx_irq_enabled && _rxbuf.full()) {\n disable_rx_irq();\n }\n\n \/* Report the File handler that data is ready to be read from the buffer. *\/\n if (was_empty && !_rxbuf.empty()) {\n wake();\n }\n}\n\n\/\/ Also called from write to start transfer\nvoid UARTSerial::tx_irq(void)\n{\n bool was_full = _txbuf.full();\n char data;\n\n \/* Write to the peripheral if there is something to write\n * and if the peripheral is available to write. *\/\n while (SerialBase::writeable() && _txbuf.pop(data)) {\n SerialBase::_base_putc(data);\n }\n\n if (_tx_irq_enabled && _txbuf.empty()) {\n disable_tx_irq();\n }\n\n \/* Report the File handler that data can be written to peripheral. *\/\n if (was_full && !_txbuf.full() && !hup()) {\n wake();\n }\n}\n\n\/* These are all called from critical section *\/\nvoid UARTSerial::enable_rx_irq()\n{\n SerialBase::attach(callback(this, &UARTSerial::rx_irq), RxIrq);\n _rx_irq_enabled = true;\n}\n\nvoid UARTSerial::disable_rx_irq()\n{\n SerialBase::attach(NULL, RxIrq);\n _rx_irq_enabled = false;\n}\n\nvoid UARTSerial::enable_tx_irq()\n{\n SerialBase::attach(callback(this, &UARTSerial::tx_irq), TxIrq);\n _tx_irq_enabled = true;\n}\n\nvoid UARTSerial::disable_tx_irq()\n{\n SerialBase::attach(NULL, TxIrq);\n _tx_irq_enabled = false;\n}\n\nint UARTSerial::enable_input(bool enabled)\n{\n api_lock();\n SerialBase::enable_input(enabled);\n api_unlock();\n\n return 0;\n}\n\nint UARTSerial::enable_output(bool enabled)\n{\n api_lock();\n SerialBase::enable_input(enabled);\n api_unlock();\n\n return 0;\n}\n\n} \/\/namespace mbed\n\n#endif \/\/(DEVICE_SERIAL && DEVICE_INTERRUPTIN)\n<commit_msg>Call correct method<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2019 ARM Limited\n * SPDX-License-Identifier: Apache-2.0\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 \"drivers\/UARTSerial.h\"\n\n#if (DEVICE_SERIAL && DEVICE_INTERRUPTIN)\n\n#include \"platform\/mbed_poll.h\"\n#include \"platform\/mbed_thread.h\"\n\nnamespace mbed {\n\nUARTSerial::UARTSerial(PinName tx, PinName rx, int baud) :\n SerialBase(tx, rx, baud),\n _blocking(true),\n _tx_irq_enabled(false),\n _rx_irq_enabled(false),\n _tx_enabled(true),\n _rx_enabled(true),\n _dcd_irq(NULL)\n{\n \/* Attatch IRQ routines to the serial device. *\/\n enable_rx_irq();\n}\n\nUARTSerial::~UARTSerial()\n{\n delete _dcd_irq;\n}\n\nvoid UARTSerial::dcd_irq()\n{\n wake();\n}\n\nvoid UARTSerial::set_baud(int baud)\n{\n SerialBase::baud(baud);\n}\n\nvoid UARTSerial::set_data_carrier_detect(PinName dcd_pin, bool active_high)\n{\n delete _dcd_irq;\n _dcd_irq = NULL;\n\n if (dcd_pin != NC) {\n _dcd_irq = new InterruptIn(dcd_pin);\n if (active_high) {\n _dcd_irq->fall(callback(this, &UARTSerial::dcd_irq));\n } else {\n _dcd_irq->rise(callback(this, &UARTSerial::dcd_irq));\n }\n }\n}\n\nvoid UARTSerial::set_format(int bits, Parity parity, int stop_bits)\n{\n api_lock();\n SerialBase::format(bits, parity, stop_bits);\n api_unlock();\n}\n\n#if DEVICE_SERIAL_FC\nvoid UARTSerial::set_flow_control(Flow type, PinName flow1, PinName flow2)\n{\n api_lock();\n SerialBase::set_flow_control(type, flow1, flow2);\n api_unlock();\n}\n#endif\n\nint UARTSerial::close()\n{\n \/* Does not let us pass a file descriptor. So how to close ?\n * Also, does it make sense to close a device type file descriptor*\/\n return 0;\n}\n\nint UARTSerial::isatty()\n{\n return 1;\n\n}\n\noff_t UARTSerial::seek(off_t offset, int whence)\n{\n \/*XXX lseek can be done theoratically, but is it sane to mark positions on a dynamically growing\/shrinking\n * buffer system (from an interrupt context) *\/\n return -ESPIPE;\n}\n\nint UARTSerial::sync()\n{\n api_lock();\n\n while (!_txbuf.empty()) {\n api_unlock();\n \/\/ Doing better than wait would require TxIRQ to also do wake() when becoming empty. Worth it?\n thread_sleep_for(1);\n api_lock();\n }\n\n api_unlock();\n\n return 0;\n}\n\nvoid UARTSerial::sigio(Callback<void()> func)\n{\n core_util_critical_section_enter();\n _sigio_cb = func;\n if (_sigio_cb) {\n short current_events = poll(0x7FFF);\n if (current_events) {\n _sigio_cb();\n }\n }\n core_util_critical_section_exit();\n}\n\n\/* Special synchronous write designed to work from critical section, such\n * as in mbed_error_vprintf.\n *\/\nssize_t UARTSerial::write_unbuffered(const char *buf_ptr, size_t length)\n{\n while (!_txbuf.empty()) {\n tx_irq();\n }\n\n for (size_t data_written = 0; data_written < length; data_written++) {\n SerialBase::_base_putc(*buf_ptr++);\n }\n\n return length;\n}\n\nssize_t UARTSerial::write(const void *buffer, size_t length)\n{\n size_t data_written = 0;\n const char *buf_ptr = static_cast<const char *>(buffer);\n\n if (length == 0) {\n return 0;\n }\n\n if (core_util_in_critical_section()) {\n return write_unbuffered(buf_ptr, length);\n }\n\n api_lock();\n\n \/\/ Unlike read, we should write the whole thing if blocking. POSIX only\n \/\/ allows partial as a side-effect of signal handling; it normally tries to\n \/\/ write everything if blocking. Without signals we can always write all.\n while (data_written < length) {\n\n if (_txbuf.full()) {\n if (!_blocking) {\n break;\n }\n do {\n api_unlock();\n thread_sleep_for(1); \/\/ XXX todo - proper wait?\n api_lock();\n } while (_txbuf.full());\n }\n\n while (data_written < length && !_txbuf.full()) {\n _txbuf.push(*buf_ptr++);\n data_written++;\n }\n\n core_util_critical_section_enter();\n if (_tx_enabled && !_tx_irq_enabled) {\n UARTSerial::tx_irq(); \/\/ only write to hardware in one place\n if (!_txbuf.empty()) {\n enable_tx_irq();\n }\n }\n core_util_critical_section_exit();\n }\n\n api_unlock();\n\n return data_written != 0 ? (ssize_t) data_written : (ssize_t) - EAGAIN;\n}\n\nssize_t UARTSerial::read(void *buffer, size_t length)\n{\n size_t data_read = 0;\n\n char *ptr = static_cast<char *>(buffer);\n\n if (length == 0) {\n return 0;\n }\n\n api_lock();\n\n while (_rxbuf.empty()) {\n if (!_blocking) {\n api_unlock();\n return -EAGAIN;\n }\n api_unlock();\n thread_sleep_for(1); \/\/ XXX todo - proper wait?\n api_lock();\n }\n\n while (data_read < length && !_rxbuf.empty()) {\n _rxbuf.pop(*ptr++);\n data_read++;\n }\n\n core_util_critical_section_enter();\n if (_rx_enabled && !_rx_irq_enabled) {\n UARTSerial::rx_irq(); \/\/ only read from hardware in one place\n if (!_rxbuf.full()) {\n enable_rx_irq();\n }\n }\n core_util_critical_section_exit();\n\n api_unlock();\n\n return data_read;\n}\n\nbool UARTSerial::hup() const\n{\n return _dcd_irq && _dcd_irq->read() != 0;\n}\n\nvoid UARTSerial::wake()\n{\n if (_sigio_cb) {\n _sigio_cb();\n }\n}\n\nshort UARTSerial::poll(short events) const\n{\n\n short revents = 0;\n \/* Check the Circular Buffer if space available for writing out *\/\n\n\n if (!_rxbuf.empty()) {\n revents |= POLLIN;\n }\n\n \/* POLLHUP and POLLOUT are mutually exclusive *\/\n if (hup()) {\n revents |= POLLHUP;\n } else if (!_txbuf.full()) {\n revents |= POLLOUT;\n }\n\n \/*TODO Handle other event types *\/\n\n return revents;\n}\n\nvoid UARTSerial::lock()\n{\n \/\/ This is the override for SerialBase.\n \/\/ No lock required as we only use SerialBase from interrupt or from\n \/\/ inside our own critical section.\n}\n\nvoid UARTSerial::unlock()\n{\n \/\/ This is the override for SerialBase.\n}\n\nvoid UARTSerial::api_lock(void)\n{\n _mutex.lock();\n}\n\nvoid UARTSerial::api_unlock(void)\n{\n _mutex.unlock();\n}\n\nvoid UARTSerial::rx_irq(void)\n{\n bool was_empty = _rxbuf.empty();\n\n \/* Fill in the receive buffer if the peripheral is readable\n * and receive buffer is not full. *\/\n while (!_rxbuf.full() && SerialBase::readable()) {\n char data = SerialBase::_base_getc();\n _rxbuf.push(data);\n }\n\n if (_rx_irq_enabled && _rxbuf.full()) {\n disable_rx_irq();\n }\n\n \/* Report the File handler that data is ready to be read from the buffer. *\/\n if (was_empty && !_rxbuf.empty()) {\n wake();\n }\n}\n\n\/\/ Also called from write to start transfer\nvoid UARTSerial::tx_irq(void)\n{\n bool was_full = _txbuf.full();\n char data;\n\n \/* Write to the peripheral if there is something to write\n * and if the peripheral is available to write. *\/\n while (SerialBase::writeable() && _txbuf.pop(data)) {\n SerialBase::_base_putc(data);\n }\n\n if (_tx_irq_enabled && _txbuf.empty()) {\n disable_tx_irq();\n }\n\n \/* Report the File handler that data can be written to peripheral. *\/\n if (was_full && !_txbuf.full() && !hup()) {\n wake();\n }\n}\n\n\/* These are all called from critical section *\/\nvoid UARTSerial::enable_rx_irq()\n{\n SerialBase::attach(callback(this, &UARTSerial::rx_irq), RxIrq);\n _rx_irq_enabled = true;\n}\n\nvoid UARTSerial::disable_rx_irq()\n{\n SerialBase::attach(NULL, RxIrq);\n _rx_irq_enabled = false;\n}\n\nvoid UARTSerial::enable_tx_irq()\n{\n SerialBase::attach(callback(this, &UARTSerial::tx_irq), TxIrq);\n _tx_irq_enabled = true;\n}\n\nvoid UARTSerial::disable_tx_irq()\n{\n SerialBase::attach(NULL, TxIrq);\n _tx_irq_enabled = false;\n}\n\nint UARTSerial::enable_input(bool enabled)\n{\n api_lock();\n SerialBase::enable_input(enabled);\n api_unlock();\n\n return 0;\n}\n\nint UARTSerial::enable_output(bool enabled)\n{\n api_lock();\n SerialBase::enable_output(enabled);\n api_unlock();\n\n return 0;\n}\n\n} \/\/namespace mbed\n\n#endif \/\/(DEVICE_SERIAL && DEVICE_INTERRUPTIN)\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2014 Krzysztof Magosa\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 * 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#include \"Teacher.h\"\n#include \"TeacherPlugin.h\"\n\nnamespace microbe {\n void Teacher::setLearningRate(const double value)\n {\n learningRate = value;\n }\n\n double Teacher::getLearningRate(void)\n {\n return learningRate;\n }\n\n void Teacher::setMomentum(const double value)\n {\n momentum = value;\n }\n \n void Teacher::addLearningSet(LearningSet& set)\n {\n learningSets.push_back(&set);\n }\n\n std::vector<LearningSet*> Teacher::getLearningSets(void)\n {\n return learningSets;\n }\n\n double Teacher::getLastEpochError(void)\n {\n return lastEpochError;\n }\n\n double Teacher::calculateSquaredErrorEpoch(void)\n {\n double error = 0;\n\n for (LearningSet* set : learningSets) {\n error += squaredError(*set);\n }\n\n lastEpochError = std::sqrt(error \/ learningSets.size());\n return lastEpochError;\n }\n\n bool Teacher::train(void)\n {\n calculateSquaredErrorEpoch();\n\n while (lastEpochError > goal) {\n firePreEpoch();\n trainEpoch();\n calculateSquaredErrorEpoch();\n firePostEpoch();\n }\n\n return true;\n }\n\n double Teacher::squaredError(LearningSet& set)\n {\n double error = 0.0;\n \n network->setValues(set.getInput());\n network->run();\n \n auto outputs = network->getOutput();\n auto expected = set.getOutput();\n\n for (int i = 0; i < outputs.size(); i++) {\n error += std::pow(outputs.at(i) - expected.at(i), 2);\n }\n\n return error;\n }\n\n void Teacher::registerPlugin(TeacherPlugin& plugin)\n {\n plugin.setTeacher(this);\n plugin.init();\n plugins.push_back(&plugin);\n }\n\n void Teacher::firePreEpoch(void)\n {\n for (TeacherPlugin *plugin : plugins) {\n plugin->preEpoch();\n }\n }\n\n void Teacher::firePostEpoch(void)\n {\n for (TeacherPlugin *plugin : plugins) {\n plugin->postEpoch();\n }\n } \n}\n<commit_msg>Missing body of setGoal() in Teacher class<commit_after>\/**\n * Copyright 2014 Krzysztof Magosa\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 * 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#include \"Teacher.h\"\n#include \"TeacherPlugin.h\"\n\nnamespace microbe {\n void Teacher::setGoal(const double value)\n {\n goal = value;\n }\n\n void Teacher::setLearningRate(const double value)\n {\n learningRate = value;\n }\n\n double Teacher::getLearningRate(void)\n {\n return learningRate;\n }\n\n void Teacher::setMomentum(const double value)\n {\n momentum = value;\n }\n \n void Teacher::addLearningSet(LearningSet& set)\n {\n learningSets.push_back(&set);\n }\n\n std::vector<LearningSet*> Teacher::getLearningSets(void)\n {\n return learningSets;\n }\n\n double Teacher::getLastEpochError(void)\n {\n return lastEpochError;\n }\n\n double Teacher::calculateSquaredErrorEpoch(void)\n {\n double error = 0;\n\n for (LearningSet* set : learningSets) {\n error += squaredError(*set);\n }\n\n lastEpochError = std::sqrt(error \/ learningSets.size());\n return lastEpochError;\n }\n\n bool Teacher::train(void)\n {\n calculateSquaredErrorEpoch();\n\n while (lastEpochError > goal) {\n firePreEpoch();\n trainEpoch();\n calculateSquaredErrorEpoch();\n firePostEpoch();\n }\n\n return true;\n }\n\n double Teacher::squaredError(LearningSet& set)\n {\n double error = 0.0;\n \n network->setValues(set.getInput());\n network->run();\n \n auto outputs = network->getOutput();\n auto expected = set.getOutput();\n\n for (int i = 0; i < outputs.size(); i++) {\n error += std::pow(outputs.at(i) - expected.at(i), 2);\n }\n\n return error;\n }\n\n void Teacher::registerPlugin(TeacherPlugin& plugin)\n {\n plugin.setTeacher(this);\n plugin.init();\n plugins.push_back(&plugin);\n }\n\n void Teacher::firePreEpoch(void)\n {\n for (TeacherPlugin *plugin : plugins) {\n plugin->preEpoch();\n }\n }\n\n void Teacher::firePostEpoch(void)\n {\n for (TeacherPlugin *plugin : plugins) {\n plugin->postEpoch();\n }\n } \n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Tracing.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"runtime\/HalideRuntime.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nint tracing_level() {\n char *trace = getenv(\"HL_TRACE\");\n return trace ? atoi(trace) : 0;\n}\n\nusing std::vector;\nusing std::map;\nusing std::string;\n\nclass InjectTracing : public IRMutator {\npublic:\n const map<string, Function> &env;\n Function output;\n int global_level;\n InjectTracing(const map<string, Function> &e,\n Function o) : env(e),\n output(o),\n global_level(tracing_level()) {}\n\nprivate:\n using IRMutator::visit;\n\n void visit(const Call *op) {\n\n \/\/ Calls inside of an address_of don't count, but we want to\n \/\/ visit the args of the inner call.\n if (op->call_type == Call::Intrinsic && op->name == Call::address_of) {\n internal_assert(op->args.size() == 1);\n const Call *c = op->args[0].as<Call>();\n\n bool unchanged = true;\n vector<Expr> new_args(c->args.size());\n for (size_t i = 0; i < c->args.size(); i++) {\n new_args[i] = mutate(c->args[i]);\n unchanged = unchanged && (new_args[i].same_as(c->args[i]));\n }\n\n if (unchanged) {\n expr = op;\n return;\n } else {\n Expr inner = Call::make(c->type, c->name, new_args, c->call_type,\n c->func, c->value_index, c->image, c->param);\n expr = Call::make(Handle(), Call::address_of, vec(inner), Call::Intrinsic);\n return;\n }\n\n }\n\n\n\n IRMutator::visit(op);\n op = expr.as<Call>();\n internal_assert(op);\n\n if (op->call_type != Call::Halide) {\n return;\n }\n\n Function f = op->func;\n bool inlined = !f.same_as(output) && f.schedule().compute_level().is_inline();\n\n if (f.is_tracing_loads() || (global_level > 2 && !inlined)) {\n\n \/\/ Wrap the load in a call to trace_load\n vector<Expr> args;\n args.push_back(f.name());\n args.push_back(halide_trace_load);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back(op->value_index);\n args.push_back(op);\n args.insert(args.end(), op->args.begin(), op->args.end());\n\n expr = Call::make(op->type, Call::trace_expr, args, Call::Intrinsic);\n }\n\n }\n\n void visit(const Provide *op) {\n IRMutator::visit(op);\n op = stmt.as<Provide>();\n internal_assert(op);\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n bool inlined = !f.same_as(output) && f.schedule().compute_level().is_inline();\n\n if (f.is_tracing_stores() || (global_level > 1 && !inlined)) {\n \/\/ Wrap each expr in a tracing call\n\n const vector<Expr> &values = op->values;\n vector<Expr> traces(op->values.size());\n\n for (size_t i = 0; i < values.size(); i++) {\n vector<Expr> args;\n args.push_back(f.name());\n args.push_back(halide_trace_store);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back((int)i);\n args.push_back(values[i]);\n args.insert(args.end(), op->args.begin(), op->args.end());\n traces[i] = Call::make(values[i].type(), Call::trace_expr, args, Call::Intrinsic);\n }\n\n stmt = Provide::make(op->name, traces, op->args);\n }\n }\n\n void visit(const Realize *op) {\n IRMutator::visit(op);\n op = stmt.as<Realize>();\n internal_assert(op);\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n if (f.is_tracing_realizations() || global_level > 0) {\n\n \/\/ Throw a tracing call before and after the realize body\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(halide_trace_begin_realization); \/\/ event type for begin realization\n args.push_back(0); \/\/ realization id\n \/\/TODO: args.push_back(op->condition);\n\n args.push_back(0); \/\/ value index\n args.push_back(0); \/\/ value\n\n for (size_t i = 0; i < op->bounds.size(); i++) {\n args.push_back(op->bounds[i].min);\n args.push_back(op->bounds[i].extent);\n }\n\n \/\/ Begin realization returns a unique token to pass to further trace calls affecting this buffer.\n\n Expr call_before = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n args[1] = halide_trace_end_realization;\n args[2] = Variable::make(Int(32), op->name + \".trace_id\");\n Expr call_after = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n Stmt new_body = op->body;\n new_body = Block::make(new_body, Evaluate::make(call_after));\n new_body = LetStmt::make(op->name + \".trace_id\", call_before, new_body);\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n } else if (f.is_tracing_stores() || f.is_tracing_loads()) {\n \/\/ We need a trace id defined to pass to the loads and stores\n Stmt new_body = op->body;\n new_body = LetStmt::make(op->name + \".trace_id\", 0, new_body);\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n }\n\n\n }\n\n void visit(const Pipeline *op) {\n IRMutator::visit(op);\n op = stmt.as<Pipeline>();\n internal_assert(op);\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n if (f.is_tracing_realizations() || global_level > 0) {\n \/\/ Throw a tracing call around each pipeline event\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(0);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back(0); \/\/ value index\n args.push_back(0); \/\/ value\n\n \/\/ Use the size of the pure step\n\n for (int i = 0; i < f.dimensions(); i++) {\n Expr min = Variable::make(Int(32), f.name() + \".s0.\" + f.args()[i] + \".min\");\n Expr max = Variable::make(Int(32), f.name() + \".s0.\" + f.args()[i] + \".max\");\n Expr extent = (max + 1) - min;\n args.push_back(min);\n args.push_back(extent);\n }\n\n Expr call;\n Stmt new_update;\n if (op->update.defined()) {\n args[1] = halide_trace_update;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n new_update = Block::make(Evaluate::make(call), op->update);\n }\n\n args[1] = halide_trace_consume;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n Stmt new_consume = Block::make(Evaluate::make(call), op->consume);\n\n args[1] = halide_trace_end_consume;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n new_consume = Block::make(new_consume, Evaluate::make(call));\n\n stmt = Pipeline::make(op->name, op->produce, new_update, new_consume);\n\n args[1] = halide_trace_produce;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n stmt = LetStmt::make(f.name() + \".trace_id\", call, stmt);\n }\n\n }\n};\n\nStmt inject_tracing(Stmt s, const map<string, Function> &env, Function output) {\n Stmt original = s;\n InjectTracing tracing(env, output);\n\n \/\/ Add a dummy realize block for the output buffers\n Region output_region;\n Parameter output_buf = output.output_buffers()[0];\n internal_assert(output_buf.is_buffer());\n for (int i = 0; i < output.dimensions(); i++) {\n string d = int_to_string(i);\n Expr min = Variable::make(Int(32), output_buf.name() + \".min.\" + d);\n Expr extent = Variable::make(Int(32), output_buf.name() + \".extent.\" + d);\n output_region.push_back(Range(min, extent));\n }\n s = Realize::make(output.name(), output.output_types(), output_region, const_true(), s);\n\n \/\/ Inject tracing calls\n s = tracing.mutate(s);\n\n \/\/ Strip off the dummy realize block\n const Realize *r = s.as<Realize>();\n internal_assert(r);\n s = r->body;\n\n \/\/ Unless tracing was a no-op, add a call to shut down the trace\n \/\/ (which flushes the output stream)\n if (!s.same_as(original)) {\n Expr flush = Call::make(Int(32), \"halide_shutdown_trace\", vector<Expr>(), Call::Extern);\n s = Block::make(s, AssertStmt::make(flush == 0, \"Failed to flush trace\", vector<Expr>()));\n }\n return s;\n}\n\n}\n}\n<commit_msg>Not necessary to trace condition of Realize.<commit_after>#include \"Tracing.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"runtime\/HalideRuntime.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nint tracing_level() {\n char *trace = getenv(\"HL_TRACE\");\n return trace ? atoi(trace) : 0;\n}\n\nusing std::vector;\nusing std::map;\nusing std::string;\n\nclass InjectTracing : public IRMutator {\npublic:\n const map<string, Function> &env;\n Function output;\n int global_level;\n InjectTracing(const map<string, Function> &e,\n Function o) : env(e),\n output(o),\n global_level(tracing_level()) {}\n\nprivate:\n using IRMutator::visit;\n\n void visit(const Call *op) {\n\n \/\/ Calls inside of an address_of don't count, but we want to\n \/\/ visit the args of the inner call.\n if (op->call_type == Call::Intrinsic && op->name == Call::address_of) {\n internal_assert(op->args.size() == 1);\n const Call *c = op->args[0].as<Call>();\n\n bool unchanged = true;\n vector<Expr> new_args(c->args.size());\n for (size_t i = 0; i < c->args.size(); i++) {\n new_args[i] = mutate(c->args[i]);\n unchanged = unchanged && (new_args[i].same_as(c->args[i]));\n }\n\n if (unchanged) {\n expr = op;\n return;\n } else {\n Expr inner = Call::make(c->type, c->name, new_args, c->call_type,\n c->func, c->value_index, c->image, c->param);\n expr = Call::make(Handle(), Call::address_of, vec(inner), Call::Intrinsic);\n return;\n }\n\n }\n\n\n\n IRMutator::visit(op);\n op = expr.as<Call>();\n internal_assert(op);\n\n if (op->call_type != Call::Halide) {\n return;\n }\n\n Function f = op->func;\n bool inlined = !f.same_as(output) && f.schedule().compute_level().is_inline();\n\n if (f.is_tracing_loads() || (global_level > 2 && !inlined)) {\n\n \/\/ Wrap the load in a call to trace_load\n vector<Expr> args;\n args.push_back(f.name());\n args.push_back(halide_trace_load);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back(op->value_index);\n args.push_back(op);\n args.insert(args.end(), op->args.begin(), op->args.end());\n\n expr = Call::make(op->type, Call::trace_expr, args, Call::Intrinsic);\n }\n\n }\n\n void visit(const Provide *op) {\n IRMutator::visit(op);\n op = stmt.as<Provide>();\n internal_assert(op);\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n bool inlined = !f.same_as(output) && f.schedule().compute_level().is_inline();\n\n if (f.is_tracing_stores() || (global_level > 1 && !inlined)) {\n \/\/ Wrap each expr in a tracing call\n\n const vector<Expr> &values = op->values;\n vector<Expr> traces(op->values.size());\n\n for (size_t i = 0; i < values.size(); i++) {\n vector<Expr> args;\n args.push_back(f.name());\n args.push_back(halide_trace_store);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back((int)i);\n args.push_back(values[i]);\n args.insert(args.end(), op->args.begin(), op->args.end());\n traces[i] = Call::make(values[i].type(), Call::trace_expr, args, Call::Intrinsic);\n }\n\n stmt = Provide::make(op->name, traces, op->args);\n }\n }\n\n void visit(const Realize *op) {\n IRMutator::visit(op);\n op = stmt.as<Realize>();\n internal_assert(op);\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n if (f.is_tracing_realizations() || global_level > 0) {\n\n \/\/ Throw a tracing call before and after the realize body\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(halide_trace_begin_realization); \/\/ event type for begin realization\n args.push_back(0); \/\/ realization id\n args.push_back(0); \/\/ value index\n args.push_back(0); \/\/ value\n\n for (size_t i = 0; i < op->bounds.size(); i++) {\n args.push_back(op->bounds[i].min);\n args.push_back(op->bounds[i].extent);\n }\n\n \/\/ Begin realization returns a unique token to pass to further trace calls affecting this buffer.\n\n Expr call_before = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n args[1] = halide_trace_end_realization;\n args[2] = Variable::make(Int(32), op->name + \".trace_id\");\n Expr call_after = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n Stmt new_body = op->body;\n new_body = Block::make(new_body, Evaluate::make(call_after));\n new_body = LetStmt::make(op->name + \".trace_id\", call_before, new_body);\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n } else if (f.is_tracing_stores() || f.is_tracing_loads()) {\n \/\/ We need a trace id defined to pass to the loads and stores\n Stmt new_body = op->body;\n new_body = LetStmt::make(op->name + \".trace_id\", 0, new_body);\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n }\n\n\n }\n\n void visit(const Pipeline *op) {\n IRMutator::visit(op);\n op = stmt.as<Pipeline>();\n internal_assert(op);\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n if (f.is_tracing_realizations() || global_level > 0) {\n \/\/ Throw a tracing call around each pipeline event\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(0);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back(0); \/\/ value index\n args.push_back(0); \/\/ value\n\n \/\/ Use the size of the pure step\n\n for (int i = 0; i < f.dimensions(); i++) {\n Expr min = Variable::make(Int(32), f.name() + \".s0.\" + f.args()[i] + \".min\");\n Expr max = Variable::make(Int(32), f.name() + \".s0.\" + f.args()[i] + \".max\");\n Expr extent = (max + 1) - min;\n args.push_back(min);\n args.push_back(extent);\n }\n\n Expr call;\n Stmt new_update;\n if (op->update.defined()) {\n args[1] = halide_trace_update;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n new_update = Block::make(Evaluate::make(call), op->update);\n }\n\n args[1] = halide_trace_consume;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n Stmt new_consume = Block::make(Evaluate::make(call), op->consume);\n\n args[1] = halide_trace_end_consume;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n new_consume = Block::make(new_consume, Evaluate::make(call));\n\n stmt = Pipeline::make(op->name, op->produce, new_update, new_consume);\n\n args[1] = halide_trace_produce;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n stmt = LetStmt::make(f.name() + \".trace_id\", call, stmt);\n }\n\n }\n};\n\nStmt inject_tracing(Stmt s, const map<string, Function> &env, Function output) {\n Stmt original = s;\n InjectTracing tracing(env, output);\n\n \/\/ Add a dummy realize block for the output buffers\n Region output_region;\n Parameter output_buf = output.output_buffers()[0];\n internal_assert(output_buf.is_buffer());\n for (int i = 0; i < output.dimensions(); i++) {\n string d = int_to_string(i);\n Expr min = Variable::make(Int(32), output_buf.name() + \".min.\" + d);\n Expr extent = Variable::make(Int(32), output_buf.name() + \".extent.\" + d);\n output_region.push_back(Range(min, extent));\n }\n s = Realize::make(output.name(), output.output_types(), output_region, const_true(), s);\n\n \/\/ Inject tracing calls\n s = tracing.mutate(s);\n\n \/\/ Strip off the dummy realize block\n const Realize *r = s.as<Realize>();\n internal_assert(r);\n s = r->body;\n\n \/\/ Unless tracing was a no-op, add a call to shut down the trace\n \/\/ (which flushes the output stream)\n if (!s.same_as(original)) {\n Expr flush = Call::make(Int(32), \"halide_shutdown_trace\", vector<Expr>(), Call::Extern);\n s = Block::make(s, AssertStmt::make(flush == 0, \"Failed to flush trace\", vector<Expr>()));\n }\n return s;\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Dielectric.h\"\n#include \"Ray.h\"\n#include \"Hitable.h\"\n#include \"Utilities.h\"\n\nnamespace sol {\n\nDielectric::Dielectric(float ri)\n: refractionIndex(ri) {\n}\n\nbool Dielectric::scatter(const Ray &inRay, const HitRecord &hitRecord, Eigen::Vector3f &attenuation, Ray &scattered) {\n Eigen::Vector3f outwardNormal;\n Eigen::Vector3f reflected = reflect(inRay.getDirection(), hitRecord.normal);\n float niOverNt = 0.0;\n attenuation = Eigen::Vector3f(1.0, 1.0, 1.0);\n Eigen::Vector3f refracted;\n if (inRay.getDirection().dot(hitRecord.normal) > 0) {\n outwardNormal = -hitRecord.normal;\n niOverNt = refractionIndex;\n } else {\n outwardNormal = hitRecord.normal;\n niOverNt = 1.0 \/ refractionIndex;\n }\n if (refract(inRay.getDirection(), outwardNormal, niOverNt, refracted)) {\n scattered = Ray(hitRecord.point, refracted);\n } else {\n scattered = Ray(hitRecord.point, reflected);\n return false;\n }\n return true;\n}\n\n}\n<commit_msg>add schlick function to Dielectric material<commit_after>#include \"Dielectric.h\"\n#include \"Ray.h\"\n#include \"Hitable.h\"\n#include \"Utilities.h\"\n\nnamespace sol {\n\nDielectric::Dielectric(float ri)\n: refractionIndex(ri) {\n}\n\nbool Dielectric::scatter(const Ray &inRay, const HitRecord &hitRecord, Eigen::Vector3f &attenuation, Ray &scattered) {\n Eigen::Vector3f outwardNormal;\n Eigen::Vector3f reflected = reflect(inRay.getDirection(), hitRecord.normal);\n float niOverNt = 0.0;\n attenuation = Eigen::Vector3f(1.0, 1.0, 1.0);\n Eigen::Vector3f refracted;\n float reflectProb = 0.0;\n float cosine = 0.0;\n\n if (inRay.getDirection().dot(hitRecord.normal) > 0) {\n outwardNormal = -hitRecord.normal;\n niOverNt = refractionIndex;\n cosine = refractionIndex * inRay.getDirection().dot(hitRecord.normal) \/ inRay.getDirection().norm();\n } else {\n outwardNormal = hitRecord.normal;\n niOverNt = 1.0 \/ refractionIndex;\n cosine = -inRay.getDirection().dot(hitRecord.normal) \/ inRay.getDirection().norm();\n }\n\n if (refract(inRay.getDirection(), outwardNormal, niOverNt, refracted)) {\n reflectProb = schlick(cosine, refractionIndex);\n } else {\n scattered = Ray(hitRecord.point, reflected);\n reflectProb = 1.0;\n }\n\n if (drand48() < reflectProb) {\n scattered = Ray(hitRecord.point, reflected);\n } else {\n scattered = Ray(hitRecord.point, refracted);\n }\n\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file\n * \n * Copyright (c) 2015 by Travis Gockel. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify it under the terms of the Apache License\n * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later\n * version.\n *\n * \\author Travis Gockel (travis@gockelhut.com)\n**\/\n#include <jsonv\/util.hpp>\n#include <jsonv\/algorithm.hpp>\n#include <jsonv\/string_view.hpp>\n#include <jsonv\/coerce.hpp>\n\n#include <sstream>\n#include <stdexcept>\n\nnamespace jsonv\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Merging \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nmerge_rules::~merge_rules() noexcept = default;\n\ndynamic_merge_rules::dynamic_merge_rules(same_key_function same_key, type_conflict_function type_conflict) :\n same_key(std::move(same_key)),\n type_conflict(std::move(type_conflict))\n{ }\n\ndynamic_merge_rules::~dynamic_merge_rules() noexcept = default;\n\nvalue dynamic_merge_rules::resolve_same_key(path&& current_path, value&& a, value&& b) const\n{\n return same_key(std::move(current_path), std::move(a), std::move(b));\n}\n\nvalue dynamic_merge_rules::resolve_type_conflict(path&& current_path, value&& a, value&& b) const\n{\n return same_key(std::move(current_path), std::move(a), std::move(b));\n}\n\nvalue throwing_merge_rules::resolve_type_conflict(path&& current_path, value&& a, value&& b) const\n{\n throw kind_error(std::string(\"Found different types at path `\") + to_string(current_path) + \"': \"\n + to_string(a.kind()) + \" and \" + to_string(b.kind()));\n}\n\nvalue throwing_merge_rules::resolve_same_key(path&& current_path, value&&, value&&) const\n{\n throw std::logic_error(std::string(\"Cannot merge duplicate key at \\\"\") + to_string(current_path) + \"\\\"\");\n}\n\nvalue recursive_merge_rules::resolve_same_key(path&& current_path, value&& a, value&& b) const\n{\n return merge_explicit(*this, std::move(current_path), std::move(a), std::move(b));\n}\n\nvalue recursive_merge_rules::resolve_type_conflict(path&&, value&& a, value&& b) const\n{\n return coerce_merge(std::move(a), std::move(b));\n}\n\nvalue merge_explicit(const merge_rules& rules,\n path current_path,\n value a,\n value b\n )\n{\n if ( a.kind() != b.kind()\n && !( (a.kind() == kind::integer && b.kind() == kind::decimal)\n || (a.kind() == kind::decimal && b.kind() == kind::integer)\n )\n )\n return rules.resolve_type_conflict(std::move(current_path), std::move(a), std::move(b));\n \n switch (a.kind())\n {\n case kind::object:\n {\n value out = object();\n for (value::object_iterator iter = a.begin_object(); iter != a.end_object(); ++iter)\n {\n auto iter_b = b.find(iter->first);\n if (iter_b == b.end_object())\n {\n out.insert({ iter->first, std::move(iter->second) });\n }\n else\n {\n out.insert({ iter->first,\n rules.resolve_same_key(current_path + iter->first,\n std::move(iter->second),\n std::move(iter_b->second)\n )\n }\n );\n b.erase(iter_b);\n }\n }\n \n for (value::object_iterator iter = b.begin_object(); iter != b.end_object(); ++iter)\n {\n out.insert({ iter->first, std::move(iter->second) });\n }\n \n return out;\n }\n case kind::array:\n a.insert(a.end_array(), std::make_move_iterator(b.begin_array()), std::make_move_iterator(b.end_array()));\n return a;\n case kind::boolean:\n return a.as_boolean() || b.as_boolean();\n case kind::integer:\n if (b.kind() == kind::integer)\n return a.as_integer() + b.as_integer();\n \/\/ fall through to decimal handler if b is a decimal\n case kind::decimal:\n return a.as_decimal() + b.as_decimal();\n case kind::null:\n return a;\n case kind::string:\n return a.as_string() + b.as_string();\n default:\n throw kind_error(std::string(\"Invalid kind \") + to_string(a.kind()));\n }\n}\n\nvalue merge_explicit(const merge_rules&, const path&, value a)\n{\n return a;\n}\n\nvalue merge_explicit(const merge_rules&, const path&)\n{\n return object();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Diff \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ndiff_result diff(value left, value right)\n{\n diff_result result;\n if (left == right)\n {\n result.same = std::move(left);\n }\n else if (left.kind() != right.kind())\n {\n result.left = std::move(left);\n result.right = std::move(right);\n }\n else switch (left.kind())\n {\n case kind::boolean:\n case kind::decimal:\n case kind::integer:\n case kind::null:\n case kind::string:\n result.left = std::move(left);\n result.right = std::move(right);\n break;\n case kind::array:\n result.same = array();\n result.left = array();\n result.right = array();\n for (value::size_type idx = 0; idx < std::min(left.size(), right.size()); ++idx)\n {\n diff_result subresult = diff(std::move(left.at(idx)), std::move(right.at(idx)));\n result.same.push_back(std::move(subresult.same));\n result.left.push_back(std::move(subresult.left));\n result.right.push_back(std::move(subresult.right));\n }\n \n if (left.size() > right.size())\n result.left.insert(result.left.end_array(),\n std::make_move_iterator(left.begin_array() + right.size()),\n std::make_move_iterator(left.end_array())\n );\n else if (left.size() < right.size())\n result.right.insert(result.right.end_array(),\n std::make_move_iterator(right.begin_array() + left.size()),\n std::make_move_iterator(right.end_array())\n );\n break;\n case kind::object:\n result.same = object();\n result.left = object();\n result.right = object();\n for (value::object_iterator liter = left.begin_object();\n liter != left.end_object();\n liter = left.erase(liter)\n )\n {\n auto riter = right.find(liter->first);\n if (riter == right.end_object())\n {\n result.left.insert({ liter->first, std::move(liter->second) });\n }\n else if (liter->second == riter->second)\n {\n result.same[liter->first] = std::move(liter->second);\n right.erase(riter);\n }\n else\n {\n diff_result subresult = diff(std::move(liter->second), std::move(riter->second));\n result.left[liter->first] = std::move(subresult.left);\n result.right[liter->first] = std::move(subresult.right);\n right.erase(riter);\n }\n }\n \n for (value::object_iterator riter = right.begin_object();\n riter != right.end_object();\n riter = right.erase(riter)\n )\n {\n result.right.insert({ riter->first, std::move(riter->second) });\n }\n break;\n }\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Validation \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic std::string validation_error_whatstring(validation_error::code code, const path& p, const value& elem)\n{\n std::ostringstream ss;\n ss << \"Validation error: Got \" << code << \" at path \" << p << \": \" << elem;\n return ss.str();\n}\n\nstd::ostream& operator<<(std::ostream& os, const validation_error::code& code)\n{\n switch (code)\n {\n case validation_error::code::non_finite_number: return os << \"non-finite number\";\n default: return os << \"validation_error::code(\" << static_cast<int>(code) << \")\";\n }\n}\n\nvalidation_error::validation_error(code code_, jsonv::path path_, jsonv::value value_) :\n runtime_error(validation_error_whatstring(code_, path_, value_)),\n _code(code_),\n _path(std::move(path_)),\n _value(std::move(value_))\n{ }\n\nvalidation_error::~validation_error() noexcept = default;\n\nvalidation_error::code validation_error::error_code() const\n{\n return _code;\n}\n\nconst path& validation_error::path() const\n{\n return _path;\n}\n\nconst value& validation_error::value() const\n{\n return _value;\n}\n\nvoid validate(const value& val)\n{\n traverse(val,\n [] (const path& p, const value& elem)\n {\n if (elem.kind() == kind::decimal)\n {\n if (!std::isfinite(elem.as_decimal()))\n throw validation_error(validation_error::code::non_finite_number, p, elem);\n }\n }\n );\n}\n\n}\n<commit_msg>Changes the implementation of merge_explicit for objects to destroy the input while iterating it.<commit_after>\/** \\file\n * \n * Copyright (c) 2015 by Travis Gockel. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify it under the terms of the Apache License\n * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later\n * version.\n *\n * \\author Travis Gockel (travis@gockelhut.com)\n**\/\n#include <jsonv\/util.hpp>\n#include <jsonv\/algorithm.hpp>\n#include <jsonv\/string_view.hpp>\n#include <jsonv\/coerce.hpp>\n\n#include <sstream>\n#include <stdexcept>\n\nnamespace jsonv\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Merging \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nmerge_rules::~merge_rules() noexcept = default;\n\ndynamic_merge_rules::dynamic_merge_rules(same_key_function same_key, type_conflict_function type_conflict) :\n same_key(std::move(same_key)),\n type_conflict(std::move(type_conflict))\n{ }\n\ndynamic_merge_rules::~dynamic_merge_rules() noexcept = default;\n\nvalue dynamic_merge_rules::resolve_same_key(path&& current_path, value&& a, value&& b) const\n{\n return same_key(std::move(current_path), std::move(a), std::move(b));\n}\n\nvalue dynamic_merge_rules::resolve_type_conflict(path&& current_path, value&& a, value&& b) const\n{\n return same_key(std::move(current_path), std::move(a), std::move(b));\n}\n\nvalue throwing_merge_rules::resolve_type_conflict(path&& current_path, value&& a, value&& b) const\n{\n throw kind_error(std::string(\"Found different types at path `\") + to_string(current_path) + \"': \"\n + to_string(a.kind()) + \" and \" + to_string(b.kind()));\n}\n\nvalue throwing_merge_rules::resolve_same_key(path&& current_path, value&&, value&&) const\n{\n throw std::logic_error(std::string(\"Cannot merge duplicate key at \\\"\") + to_string(current_path) + \"\\\"\");\n}\n\nvalue recursive_merge_rules::resolve_same_key(path&& current_path, value&& a, value&& b) const\n{\n return merge_explicit(*this, std::move(current_path), std::move(a), std::move(b));\n}\n\nvalue recursive_merge_rules::resolve_type_conflict(path&&, value&& a, value&& b) const\n{\n return coerce_merge(std::move(a), std::move(b));\n}\n\nvalue merge_explicit(const merge_rules& rules,\n path current_path,\n value a,\n value b\n )\n{\n if ( a.kind() != b.kind()\n && !( (a.kind() == kind::integer && b.kind() == kind::decimal)\n || (a.kind() == kind::decimal && b.kind() == kind::integer)\n )\n )\n return rules.resolve_type_conflict(std::move(current_path), std::move(a), std::move(b));\n \n switch (a.kind())\n {\n case kind::object:\n {\n value out = object();\n for (value::object_iterator iter = a.begin_object(); iter != a.end_object(); iter = a.erase(iter))\n {\n auto iter_b = b.find(iter->first);\n if (iter_b == b.end_object())\n {\n out.insert({ iter->first, std::move(iter->second) });\n }\n else\n {\n out.insert({ iter->first,\n rules.resolve_same_key(current_path + iter->first,\n std::move(iter->second),\n std::move(iter_b->second)\n )\n }\n );\n b.erase(iter_b);\n }\n }\n \n for (value::object_iterator iter = b.begin_object(); iter != b.end_object(); ++iter)\n {\n out.insert({ iter->first, std::move(iter->second) });\n }\n \n return out;\n }\n case kind::array:\n a.insert(a.end_array(), std::make_move_iterator(b.begin_array()), std::make_move_iterator(b.end_array()));\n return a;\n case kind::boolean:\n return a.as_boolean() || b.as_boolean();\n case kind::integer:\n if (b.kind() == kind::integer)\n return a.as_integer() + b.as_integer();\n \/\/ fall through to decimal handler if b is a decimal\n case kind::decimal:\n return a.as_decimal() + b.as_decimal();\n case kind::null:\n return a;\n case kind::string:\n return a.as_string() + b.as_string();\n default:\n throw kind_error(std::string(\"Invalid kind \") + to_string(a.kind()));\n }\n}\n\nvalue merge_explicit(const merge_rules&, const path&, value a)\n{\n return a;\n}\n\nvalue merge_explicit(const merge_rules&, const path&)\n{\n return object();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Diff \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ndiff_result diff(value left, value right)\n{\n diff_result result;\n if (left == right)\n {\n result.same = std::move(left);\n }\n else if (left.kind() != right.kind())\n {\n result.left = std::move(left);\n result.right = std::move(right);\n }\n else switch (left.kind())\n {\n case kind::boolean:\n case kind::decimal:\n case kind::integer:\n case kind::null:\n case kind::string:\n result.left = std::move(left);\n result.right = std::move(right);\n break;\n case kind::array:\n result.same = array();\n result.left = array();\n result.right = array();\n for (value::size_type idx = 0; idx < std::min(left.size(), right.size()); ++idx)\n {\n diff_result subresult = diff(std::move(left.at(idx)), std::move(right.at(idx)));\n result.same.push_back(std::move(subresult.same));\n result.left.push_back(std::move(subresult.left));\n result.right.push_back(std::move(subresult.right));\n }\n \n if (left.size() > right.size())\n result.left.insert(result.left.end_array(),\n std::make_move_iterator(left.begin_array() + right.size()),\n std::make_move_iterator(left.end_array())\n );\n else if (left.size() < right.size())\n result.right.insert(result.right.end_array(),\n std::make_move_iterator(right.begin_array() + left.size()),\n std::make_move_iterator(right.end_array())\n );\n break;\n case kind::object:\n result.same = object();\n result.left = object();\n result.right = object();\n for (value::object_iterator liter = left.begin_object();\n liter != left.end_object();\n liter = left.erase(liter)\n )\n {\n auto riter = right.find(liter->first);\n if (riter == right.end_object())\n {\n result.left.insert({ liter->first, std::move(liter->second) });\n }\n else if (liter->second == riter->second)\n {\n result.same[liter->first] = std::move(liter->second);\n right.erase(riter);\n }\n else\n {\n diff_result subresult = diff(std::move(liter->second), std::move(riter->second));\n result.left[liter->first] = std::move(subresult.left);\n result.right[liter->first] = std::move(subresult.right);\n right.erase(riter);\n }\n }\n \n for (value::object_iterator riter = right.begin_object();\n riter != right.end_object();\n riter = right.erase(riter)\n )\n {\n result.right.insert({ riter->first, std::move(riter->second) });\n }\n break;\n }\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Validation \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic std::string validation_error_whatstring(validation_error::code code, const path& p, const value& elem)\n{\n std::ostringstream ss;\n ss << \"Validation error: Got \" << code << \" at path \" << p << \": \" << elem;\n return ss.str();\n}\n\nstd::ostream& operator<<(std::ostream& os, const validation_error::code& code)\n{\n switch (code)\n {\n case validation_error::code::non_finite_number: return os << \"non-finite number\";\n default: return os << \"validation_error::code(\" << static_cast<int>(code) << \")\";\n }\n}\n\nvalidation_error::validation_error(code code_, jsonv::path path_, jsonv::value value_) :\n runtime_error(validation_error_whatstring(code_, path_, value_)),\n _code(code_),\n _path(std::move(path_)),\n _value(std::move(value_))\n{ }\n\nvalidation_error::~validation_error() noexcept = default;\n\nvalidation_error::code validation_error::error_code() const\n{\n return _code;\n}\n\nconst path& validation_error::path() const\n{\n return _path;\n}\n\nconst value& validation_error::value() const\n{\n return _value;\n}\n\nvoid validate(const value& val)\n{\n traverse(val,\n [] (const path& p, const value& elem)\n {\n if (elem.kind() == kind::decimal)\n {\n if (!std::isfinite(elem.as_decimal()))\n throw validation_error(validation_error::code::non_finite_number, p, elem);\n }\n }\n );\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ =============== BEGIN ASSESSMENT HEADER ================\n\/\/\/ @file Assignment 2\/Executable.cpp\n\/\/\/ @author <Haripriya Vasireddy> [hvasi001@ucr.edu]\n\/\/\/ @date <April 30, 2016>\n\/\/ ================== END ASSESSMENT HEADER ===============\n\n#include \"Executable.h\"\n#include \"LeafCommand.h\"\n#include <signal.h>\n#include <sys\/types.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <iostream>\n#include <sys\/wait.h>\n#include <cerrno>\nusing namespace std;\n\/\/Destructor\nExecutable::~Executable(){}\n\nint Executable::execute(Command *c)\n{\n \/\/errno = 0;\n char **arg = new char*[static_cast<LeafCommand*>(c)->argList->size() + 1];\n copy(static_cast<LeafCommand*>(c)->argList->begin(), static_cast<LeafCommand*>(c)->argList->end(), arg);\n arg[static_cast<LeafCommand*>(c)->argList->size()] = '\\0';\n \n pid_t pid;\n int status;\n \n \/\/fork\n pid = fork(); \n if (pid < 0) \/\/fork failure\n ;\n else if (pid == 0) \/\/child process\n execvp(*arg, arg);\n else \/\/parent waiting for the child\n waitpid(pid, &status, 0);\n \n return status;\n}<commit_msg>Modified to give error message for unrecognized commands<commit_after>\/\/ =============== BEGIN ASSESSMENT HEADER ================\n\/\/\/ @file Assignment 2\/Executable.cpp\n\/\/\/ @author <Haripriya Vasireddy> [hvasi001@ucr.edu]\n\/\/\/ @date <April 30, 2016>\n\/\/ ================== END ASSESSMENT HEADER ===============\n\n#include \"Executable.h\"\n#include \"LeafCommand.h\"\n#include <signal.h>\n#include <sys\/types.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <iostream>\n#include <sys\/wait.h>\n#include <cerrno>\nusing namespace std;\n\/\/Destructor\nExecutable::~Executable(){}\n\nint Executable::execute(Command *c)\n{\n \/\/errno = 0;\n int evp_status;\n char **arg = new char*[static_cast<LeafCommand*>(c)->argList->size() + 1];\n copy(static_cast<LeafCommand*>(c)->argList->begin(), static_cast<LeafCommand*>(c)->argList->end(), arg);\n arg[static_cast<LeafCommand*>(c)->argList->size()] = '\\0';\n \n pid_t pid;\n int status;\n \n \/\/fork\n pid = fork(); \n if (pid < 0) \/\/fork failure\n ;\n else if (pid == 0) \/\/child process\n {\n evp_status = execvp(*arg, arg);\n if(evp_status == -1)\n {\n cout << \"command not found\" << endl;\n }\n }\n else \/\/parent waiting for the child\n waitpid(pid, &status, 0);\n \n return status;\n}<|endoftext|>"} {"text":"<commit_before>#include <GLUI\/GLUI.h>\n#include <GLUIExt.h>\n\nnamespace glui {\n\tnamespace input {\n\t\tstd::string* Input::textString = 0;\n\t\tsize_t Input::textInsertPoint = 0;\n\t\tint Input::mousePosx = -1;\n\t\tint Input::mousePosy = -1;\n\t\tbool Input::mouseLeftDown = false;\n\t\tunsigned char* Input::keys = new unsigned char[GLFW_KEY_LAST];\n\n\t\tvoid Input::init() {\n\t\t\tmemset(Input::keys, 0, sizeof(unsigned char) * GLFW_KEY_LAST);\n\t\t}\n\n\t\tvoid callbacks::mousePosition(int posx, int posy) {\n\t\t\tInput::mousePosx = posx;\n\t\t\tInput::mousePosy = posy;\n\t\t}\n\n\t\tvoid callbacks::mouseButton(int button, int state) {\n\t\t\tif (button == GLFW_MOUSE_BUTTON_LEFT) {\n\t\t\t\tif (state == GLFW_PRESS) {\n\t\t\t\t\tInput::mouseLeftDown = true;\n\t\t\t\t}\n\t\t\t\telse if (state == GLFW_RELEASE) {\n\t\t\t\t\tInput::mouseLeftDown = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tvoid callbacks::key(int key, int state) {\n\t\t\tInput::keys[key] = state;\n\t\t\tif (Input::textString != 0 && key == GLFW_KEY_BACKSPACE && state == GLFW_PRESS && Input::textString->size() != 0) {\n\t\t\t\tInput::textString->replace(Input::textInsertPoint-1, 1, \"\");\n\t\t\t}\n\t\t}\n\n\t\tvoid callbacks::text(unsigned int codepoint) {\n\t\t\tif (Input::textString != 0) {\n\t\t\t\tchar car = (char) codepoint;\n\t\t\t\tInput::textString->insert(Input::textInsertPoint, std::string(&car));\n\t\t\t}\n\t\t}\n\n\t\tvoid keyboard::setTextCallback(std::string* string) {\n\t\t\tInput::textString = string;\n\t\t}\n\n\t\tvoid keyboard::setTextInsertPoint(size_t index) {\n\t\t\tInput::textInsertPoint = index;\n\t\t}\n\t}\n}<commit_msg>fixed mac textbox bug<commit_after>#include <GLUI\/GLUI.h>\n#include <GLUIExt.h>\n\nnamespace glui {\n\tnamespace input {\n\t\tstd::string* Input::textString = 0;\n\t\tsize_t Input::textInsertPoint = 0;\n\t\tint Input::mousePosx = -1;\n\t\tint Input::mousePosy = -1;\n\t\tbool Input::mouseLeftDown = false;\n\t\tunsigned char* Input::keys = new unsigned char[GLFW_KEY_LAST];\n\n\t\tvoid Input::init() {\n\t\t\tmemset(Input::keys, 0, sizeof(unsigned char) * GLFW_KEY_LAST);\n\t\t}\n\n\t\tvoid callbacks::mousePosition(int posx, int posy) {\n\t\t\tInput::mousePosx = posx;\n\t\t\tInput::mousePosy = posy;\n\t\t}\n\n\t\tvoid callbacks::mouseButton(int button, int state) {\n\t\t\tif (button == GLFW_MOUSE_BUTTON_LEFT) {\n\t\t\t\tif (state == GLFW_PRESS) {\n\t\t\t\t\tInput::mouseLeftDown = true;\n\t\t\t\t}\n\t\t\t\telse if (state == GLFW_RELEASE) {\n\t\t\t\t\tInput::mouseLeftDown = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tvoid callbacks::key(int key, int state) {\n\t\t\tInput::keys[key] = state;\n\t\t\tif (Input::textString != 0 && key == GLFW_KEY_BACKSPACE && state == GLFW_PRESS && Input::textString->size() != 0) {\n\t\t\t\tInput::textString->replace(Input::textInsertPoint-1, 1, \"\");\n\t\t\t}\n\t\t}\n\n\t\tvoid callbacks::text(unsigned int codepoint) {\n\t\t\tif (Input::textString != 0) {\n\t\t\t\tchar* insertion = new char[1];\n\t\t\t\tinsertion[0] = (char) codepoint;\n\t\t\t\tInput::textString->insert(Input::textInsertPoint, std::string(insertion));\n\t\t\t}\n\t\t}\n\n\t\tvoid keyboard::setTextCallback(std::string* string) {\n\t\t\tInput::textString = string;\n\t\t}\n\n\t\tvoid keyboard::setTextInsertPoint(size_t index) {\n\t\t\tInput::textInsertPoint = index;\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#ifndef DEF_LAMBDARANK_H\n#define DEF_LAMBDARANK_H\n\/**\n * @file\n * @author David Nemeskey\n * @version 0.1\n *\n * @section LICENSE\n *\n * Copyright [2013] [MTA SZTAKI]\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 * The LambdaRank algorithm. Since it is very closely related to RankNet, we\n * derive it from that class.\n *\/\n\n#include <cmath>\n\n#include \"ranknet_lambda.hpp\"\n#include \"lambdarank_optimize.hpp\"\n\nclass LambdaRank : public RankNetLambda {\npublic:\n \/** @param[in] sigma parameter of the sigmoid. *\/\n LambdaRank(MlModel* model, EvaluationMeasure* eval,\n StoppingCondition stop, LtrRunningPhase phase=TRAINING,\n double sigma=1)\n : RankNetLambda(model, eval, stop, phase, sigma) {\n }\n\n \/****************************** GraphChi stuff ******************************\/\n\n \/** The actual RankNet implementation. *\/\n virtual void compute_gradients(\n graphchi_vertex<TypeVertex, FeatureEdge> &query, Gradient* umodel) {\n std::vector<double> lambdas(query.num_outedges());\n std::vector<double> s_is(query.num_outedges());\n\n \/* First, we compute all the outputs... *\/\n for (int i = 0; i < query.num_outedges(); i++) {\n s_is[i] = get_score(query.outedge(i));\n\/\/ std::cout << \"s[\" << i << \"] == \" << s_is[i] << std::endl;\n }\n \/* ...and the retrieval measure scores. *\/\n opt.compute(query);\n\n\n \/* Now, we compute the errors (lambdas). *\/\n for (int i = 0; i < query.num_outedges() - 1; i++) {\n int rel_i = get_relevance(query.outedge(i));\n for (int j = i + 1; j < query.num_outedges(); j++) {\n int rel_j = get_relevance(query.outedge(j));\n if (rel_i != rel_j) {\n double S_ij = rel_i > rel_j ? 1 : -1;\n double lambda_ij = dC_per_ds_i(S_ij, s_is[i], s_is[j]) *\n fabs(opt.delta(query, i, j));\n \/* lambda_ij = -lambda_ji *\/\n lambdas[i] += lambda_ij;\n lambdas[j] -= lambda_ij;\n }\n }\n }\n\n \/* Finally, the model update. *\/\n for (int i = 0; i < query.num_outedges(); i++) {\n \/\/ -lambdas[i], as C is a utility function in this case\n umodel->update(query.outedge(i)->get_vector()->get_data(), s_is[i], lambdas[i]);\n }\n }\n\nprivate:\n \/**\n * The information retrieval measure we are optimizing for.\n * @todo add more measures.\n *\/\n NdcgOptimizer opt;\n};\n\n#endif\n<commit_msg>Cosmetic change in method docstring. \tmodified: src\/lambdarank.hpp<commit_after>#ifndef DEF_LAMBDARANK_H\n#define DEF_LAMBDARANK_H\n\/**\n * @file\n * @author David Nemeskey\n * @version 0.1\n *\n * @section LICENSE\n *\n * Copyright [2013] [MTA SZTAKI]\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 * The LambdaRank algorithm. Since it is very closely related to RankNet, we\n * derive it from that class.\n *\/\n\n#include <cmath>\n\n#include \"ranknet_lambda.hpp\"\n#include \"lambdarank_optimize.hpp\"\n\nclass LambdaRank : public RankNetLambda {\npublic:\n \/** @param[in] sigma parameter of the sigmoid. *\/\n LambdaRank(MlModel* model, EvaluationMeasure* eval,\n StoppingCondition stop, LtrRunningPhase phase=TRAINING,\n double sigma=1)\n : RankNetLambda(model, eval, stop, phase, sigma) {\n }\n\n \/****************************** GraphChi stuff ******************************\/\n\n \/** The actual LambdaRank implementation. *\/\n virtual void compute_gradients(\n graphchi_vertex<TypeVertex, FeatureEdge> &query, Gradient* umodel) {\n std::vector<double> lambdas(query.num_outedges());\n std::vector<double> s_is(query.num_outedges());\n\n \/* First, we compute all the outputs... *\/\n for (int i = 0; i < query.num_outedges(); i++) {\n s_is[i] = get_score(query.outedge(i));\n\/\/ std::cout << \"s[\" << i << \"] == \" << s_is[i] << std::endl;\n }\n \/* ...and the retrieval measure scores. *\/\n opt.compute(query);\n\n\n \/* Now, we compute the errors (lambdas). *\/\n for (int i = 0; i < query.num_outedges() - 1; i++) {\n int rel_i = get_relevance(query.outedge(i));\n for (int j = i + 1; j < query.num_outedges(); j++) {\n int rel_j = get_relevance(query.outedge(j));\n if (rel_i != rel_j) {\n double S_ij = rel_i > rel_j ? 1 : -1;\n double lambda_ij = dC_per_ds_i(S_ij, s_is[i], s_is[j]) *\n fabs(opt.delta(query, i, j));\n \/* lambda_ij = -lambda_ji *\/\n lambdas[i] += lambda_ij;\n lambdas[j] -= lambda_ij;\n }\n }\n }\n\n \/* Finally, the model update. *\/\n for (int i = 0; i < query.num_outedges(); i++) {\n \/\/ -lambdas[i], as C is a utility function in this case\n umodel->update(query.outedge(i)->get_vector()->get_data(), s_is[i], lambdas[i]);\n }\n }\n\nprivate:\n \/**\n * The information retrieval measure we are optimizing for.\n * @todo add more measures.\n *\/\n NdcgOptimizer opt;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"Game\/Piece.h\"\n\n#include <cctype>\n#include <algorithm>\n#include <cassert>\n#include <array>\n#include <cctype>\n\n#include \"Game\/Square.h\"\n#include \"Game\/Color.h\"\n\n#include \"Moves\/Move.h\"\n#include \"Moves\/Direction.h\"\n#include \"Moves\/Pawn_Move.h\"\n#include \"Moves\/Pawn_Double_Move.h\"\n#include \"Moves\/Pawn_Promotion.h\"\n#include \"Moves\/En_Passant.h\"\n#include \"Moves\/Castle.h\"\n\n#include \"Utility\/Fixed_Capacity_Vector.h\"\n\nconst Piece::piece_code_t Piece::invalid_code = Piece{Piece_Color::BLACK, Piece_Type::KING}.index() + 1;\n\nnamespace\n{\n const std::string pgn_symbols = \"PRNBQK\";\n\n using indexed_move_array = std::array<std::array<Fixed_Capacity_Vector<Fixed_Capacity_Vector<const Move*, 7>, 12>, 64>, 12>;\n\n void add_pawn_moves(indexed_move_array& out, Piece_Color color) noexcept;\n void add_rook_moves(indexed_move_array& out, Piece_Color color, Piece_Type type = Piece_Type::ROOK) noexcept;\n void add_knight_moves(indexed_move_array& out, Piece_Color color) noexcept;\n void add_bishop_moves(indexed_move_array& out, Piece_Color color, Piece_Type type = Piece_Type::BISHOP) noexcept;\n void add_queen_moves(indexed_move_array& out, Piece_Color color) noexcept;\n void add_king_moves(indexed_move_array& out, Piece_Color color) noexcept;\n\n const auto legal_moves =\n []()\n {\n indexed_move_array result;\n for(auto color : {Piece_Color::WHITE, Piece_Color::BLACK})\n {\n add_pawn_moves(result, color);\n add_rook_moves(result, color);\n add_knight_moves(result, color);\n add_bishop_moves(result, color);\n add_queen_moves(result, color);\n add_king_moves(result, color);\n }\n\n return result;\n }();\n\n\n const auto attack_moves =\n []()\n {\n indexed_move_array result;\n for(auto color : {Piece_Color::WHITE, Piece_Color::BLACK})\n {\n for(auto type : {Piece_Type::PAWN, Piece_Type::ROOK, Piece_Type::KNIGHT, Piece_Type::BISHOP, Piece_Type::QUEEN, Piece_Type::KING})\n {\n auto piece = Piece{color, type};\n for(size_t index = 0; index < 64; ++index)\n {\n for(const auto& move_list : legal_moves[piece.index()][index])\n {\n result[piece.index()][index].push_back({});\n\n for(auto move : move_list)\n {\n \/\/ Make list of all capturing moves, excluding all but one type of pawn capture per square.\n if(move->can_capture()\n && ! move->is_en_passant()\n && (move->promotion_piece_symbol() == 'Q' || move->promotion_piece_symbol() == '\\0'))\n {\n result[piece.index()][index].back().push_back(move);\n }\n }\n }\n }\n }\n }\n\n return result;\n }();\n\n\n \/\/ Add a move to the list that is only legal when starting from a certain square\n \/\/ (e.g., castling, pawn double move, promotion, etc.)\n template<typename Move_Type, typename ...Parameters>\n void add_legal_move(indexed_move_array& out, Piece piece, bool blockable, Parameters ... parameters) noexcept\n {\n auto move = new Move_Type(parameters...);\n auto& lists = out[piece.index()][move->start().index()];\n if(lists.empty() || ! blockable)\n {\n lists.push_back({});\n }\n\n if( ! lists.back().empty() && ! same_direction(move->movement(), lists.back().back()->movement()))\n {\n lists.push_back({});\n }\n\n lists.back().push_back(move);\n }\n\n void add_standard_legal_move(indexed_move_array& out, Piece piece, int file_step, int rank_step, bool blockable) noexcept\n {\n for(auto start : Square::all_squares())\n {\n auto end = start + Square_Difference{file_step, rank_step};\n if(end.inside_board())\n {\n add_legal_move<Move>(out, piece, blockable, start, end);\n }\n }\n }\n\n void add_pawn_moves(indexed_move_array& out, Piece_Color color) noexcept\n {\n auto pawn = Piece{color, Piece_Type::PAWN};\n auto base_rank = (color == Piece_Color::WHITE ? 2 : 7);\n auto no_normal_move_rank = (color == Piece_Color::WHITE ? 7 : 2);\n auto rank_change = (color == Piece_Color::WHITE ? 1 : -1);\n for(char file = 'a'; file <= 'h'; ++file)\n {\n for(int rank = base_rank; rank != no_normal_move_rank; rank += rank_change)\n {\n add_legal_move<Pawn_Move>(out, pawn, true, color, Square{file, rank});\n }\n }\n\n for(char file = 'a'; file <= 'h'; ++file)\n {\n add_legal_move<Pawn_Double_Move>(out, pawn, true, color, file);\n }\n\n auto possible_promotions = {Piece_Type::QUEEN, Piece_Type::KNIGHT, Piece_Type::ROOK, Piece_Type::BISHOP};\n\n for(auto dir : {Direction::RIGHT, Direction::LEFT})\n {\n auto first_file = (dir == Direction::RIGHT ? 'a' : 'b');\n auto last_file = (dir == Direction::RIGHT ? 'g' : 'h');\n for(char file = first_file; file <= last_file; ++file)\n {\n for(int rank = base_rank; rank != no_normal_move_rank; rank += rank_change)\n {\n add_legal_move<Pawn_Move>(out, pawn, true, color, Square{file, rank}, dir);\n }\n }\n\n for(char file = first_file; file <= last_file; ++file)\n {\n add_legal_move<En_Passant>(out, pawn, true, color, dir, file);\n }\n\n for(auto promote : possible_promotions)\n {\n for(auto file = first_file; file <= last_file; ++file)\n {\n add_legal_move<Pawn_Promotion>(out, pawn, false, promote, color, file, dir);\n }\n }\n }\n\n for(auto promote : possible_promotions)\n {\n for(auto file = 'a'; file <= 'h'; ++file)\n {\n add_legal_move<Pawn_Promotion>(out, pawn, false, promote, color, file);\n }\n }\n }\n\n void add_rook_moves(indexed_move_array& out, Piece_Color color, Piece_Type type) noexcept\n {\n for(int d_file = -1; d_file <= 1; ++d_file)\n {\n for(int d_rank = -1; d_rank <= 1; ++d_rank)\n {\n if(d_file == 0 && d_rank == 0) { continue; }\n if(d_file != 0 && d_rank != 0) { continue; }\n\n for(int move_size = 1; move_size <= 7; ++move_size)\n {\n add_standard_legal_move(out, {color, type}, move_size*d_file, move_size*d_rank, true);\n }\n }\n }\n }\n\n void add_knight_moves(indexed_move_array& out, Piece_Color color) noexcept\n {\n for(auto d_file : {1, 2})\n {\n auto d_rank = 3 - d_file;\n for(auto file_direction : {-1, 1})\n {\n for(auto rank_direction : {-1, 1})\n {\n add_standard_legal_move(out, {color, Piece_Type::KNIGHT}, d_file*file_direction, d_rank*rank_direction, false);\n }\n }\n }\n }\n\n void add_bishop_moves(indexed_move_array& out, Piece_Color color, Piece_Type type) noexcept\n {\n for(int d_rank : {-1, 1})\n {\n for(int d_file : {-1, 1})\n {\n for(int move_size = 1; move_size <= 7; ++move_size)\n {\n add_standard_legal_move(out, {color, type}, move_size*d_file, move_size*d_rank, true);\n }\n }\n }\n }\n\n void add_queen_moves(indexed_move_array& out, Piece_Color color) noexcept\n {\n add_bishop_moves(out, color, Piece_Type::QUEEN);\n add_rook_moves(out, color, Piece_Type::QUEEN);\n }\n\n void add_king_moves(indexed_move_array& out, Piece_Color color) noexcept\n {\n auto king = Piece{color, Piece_Type::KING};\n auto kingside_castle_added = false;\n auto queenside_castle_added = false;\n int base_rank = (color == Piece_Color::WHITE ? 1 : 8);\n for(int d_rank = -1; d_rank <= 1; ++d_rank)\n {\n for(int d_file = -1; d_file <= 1; ++d_file)\n {\n if(d_rank == 0 && d_file == 0) { continue; }\n\n add_standard_legal_move(out, king, d_file, d_rank, true);\n if(d_rank == 0)\n {\n if(d_file > 0)\n {\n if( ! kingside_castle_added)\n {\n add_legal_move<Castle>(out, king, true, base_rank, Direction::RIGHT);\n kingside_castle_added = true;\n }\n }\n else\n {\n if( ! queenside_castle_added)\n {\n add_legal_move<Castle>(out, king, true, base_rank, Direction::LEFT);\n }\n }\n }\n }\n }\n }\n\n Piece_Type piece_type_from_char(char pgn_symbol)\n {\n auto i = pgn_symbols.find(std::toupper(pgn_symbol));\n if(i == std::string::npos)\n {\n throw std::invalid_argument(pgn_symbol + std::string{\" is not a valid piece PGN symbol.\"});\n }\n return static_cast<Piece_Type>(i);\n }\n}\n\nPiece::Piece() noexcept : piece_code(invalid_code)\n{\n}\n\nPiece::Piece(Piece_Color color, Piece_Type type) noexcept :\n piece_code((static_cast<int>(type) << 1) | static_cast<int>(color))\n{\n \/\/ piece_code layout: 4 bits\n \/\/ 3 most significant bits = Piece_Type (values 0-5)\n \/\/ least significant bit = Piece_Color (0 or 1)\n \/\/\n \/\/ 101 1\n \/\/ ^^^ ^-- Piece_Color::BLACK\n \/\/ +--- Piece_Type::KING\n}\n\nPiece::Piece(char pgn_symbol) : Piece(std::isupper(pgn_symbol) ? Piece_Color::WHITE : Piece_Color::BLACK,\n piece_type_from_char(pgn_symbol))\n{\n}\n\nPiece_Color Piece::color() const noexcept\n{\n assert(*this);\n return static_cast<Piece_Color>(piece_code & 1);\n}\n\nstd::string Piece::pgn_symbol() const noexcept\n{\n assert(*this);\n return type() == Piece_Type::PAWN ? std::string{} : std::string(1, std::toupper(fen_symbol()));\n}\n\nchar Piece::fen_symbol() const noexcept\n{\n assert(*this);\n auto symbol = pgn_symbols[static_cast<int>(type())];\n return (color() == Piece_Color::WHITE ? symbol : std::tolower(symbol));\n}\n\nbool Piece::can_move(const Move* move) const noexcept\n{\n assert(*this);\n for(const auto& moves : move_lists(move->start()))\n {\n if(std::find(moves.begin(), moves.end(), move) != moves.end())\n {\n return true;\n }\n }\n\n return false;\n}\n\nconst Piece::list_of_move_lists& Piece::move_lists(Square square) const noexcept\n{\n assert(*this);\n return legal_moves[index()][square.index()];\n}\n\nPiece_Type Piece::type() const noexcept\n{\n assert(*this);\n return static_cast<Piece_Type>(piece_code >> 1);\n}\n\nPiece::operator bool() const noexcept\n{\n return piece_code != invalid_code;\n}\n\nPiece::piece_code_t Piece::index() const noexcept\n{\n return piece_code;\n}\n\nconst Piece::list_of_move_lists& Piece::attacking_move_lists(Square square) const noexcept\n{\n assert(*this);\n return attack_moves[index()][square.index()];\n}\n\nbool operator==(Piece a, Piece b) noexcept\n{\n return a.index() == b.index();\n}\n\nbool operator!=(Piece a, Piece b) noexcept\n{\n return !(a == b);\n}\n<commit_msg>Iterate through Pieces instead of listing them<commit_after>#include \"Game\/Piece.h\"\n\n#include <cctype>\n#include <algorithm>\n#include <cassert>\n#include <array>\n#include <cctype>\n\n#include \"Game\/Square.h\"\n#include \"Game\/Color.h\"\n\n#include \"Moves\/Move.h\"\n#include \"Moves\/Direction.h\"\n#include \"Moves\/Pawn_Move.h\"\n#include \"Moves\/Pawn_Double_Move.h\"\n#include \"Moves\/Pawn_Promotion.h\"\n#include \"Moves\/En_Passant.h\"\n#include \"Moves\/Castle.h\"\n\n#include \"Utility\/Fixed_Capacity_Vector.h\"\n\nconst Piece::piece_code_t Piece::invalid_code = Piece{Piece_Color::BLACK, Piece_Type::KING}.index() + 1;\n\nnamespace\n{\n const std::string pgn_symbols = \"PRNBQK\";\n\n using indexed_move_array = std::array<std::array<Fixed_Capacity_Vector<Fixed_Capacity_Vector<const Move*, 7>, 12>, 64>, 12>;\n\n void add_pawn_moves(indexed_move_array& out, Piece_Color color) noexcept;\n void add_rook_moves(indexed_move_array& out, Piece_Color color, Piece_Type type = Piece_Type::ROOK) noexcept;\n void add_knight_moves(indexed_move_array& out, Piece_Color color) noexcept;\n void add_bishop_moves(indexed_move_array& out, Piece_Color color, Piece_Type type = Piece_Type::BISHOP) noexcept;\n void add_queen_moves(indexed_move_array& out, Piece_Color color) noexcept;\n void add_king_moves(indexed_move_array& out, Piece_Color color) noexcept;\n\n const auto legal_moves =\n []()\n {\n indexed_move_array result;\n for(auto color : {Piece_Color::WHITE, Piece_Color::BLACK})\n {\n add_pawn_moves(result, color);\n add_rook_moves(result, color);\n add_knight_moves(result, color);\n add_bishop_moves(result, color);\n add_queen_moves(result, color);\n add_king_moves(result, color);\n }\n\n return result;\n }();\n\n\n const auto attack_moves =\n []()\n {\n indexed_move_array result;\n for(auto color : {Piece_Color::WHITE, Piece_Color::BLACK})\n {\n for(auto type_index = 0; type_index <= static_cast<int>(Piece_Type::KING); ++type_index)\n {\n auto piece = Piece{color, static_cast<Piece_Type>(type_index)};\n for(size_t index = 0; index < 64; ++index)\n {\n for(const auto& move_list : legal_moves[piece.index()][index])\n {\n result[piece.index()][index].push_back({});\n\n for(auto move : move_list)\n {\n \/\/ Make list of all capturing moves, excluding all but one type of pawn capture per square.\n if(move->can_capture()\n && ! move->is_en_passant()\n && (move->promotion_piece_symbol() == 'Q' || move->promotion_piece_symbol() == '\\0'))\n {\n result[piece.index()][index].back().push_back(move);\n }\n }\n }\n }\n }\n }\n\n return result;\n }();\n\n\n \/\/ Add a move to the list that is only legal when starting from a certain square\n \/\/ (e.g., castling, pawn double move, promotion, etc.)\n template<typename Move_Type, typename ...Parameters>\n void add_legal_move(indexed_move_array& out, Piece piece, bool blockable, Parameters ... parameters) noexcept\n {\n auto move = new Move_Type(parameters...);\n auto& lists = out[piece.index()][move->start().index()];\n if(lists.empty() || ! blockable)\n {\n lists.push_back({});\n }\n\n if( ! lists.back().empty() && ! same_direction(move->movement(), lists.back().back()->movement()))\n {\n lists.push_back({});\n }\n\n lists.back().push_back(move);\n }\n\n void add_standard_legal_move(indexed_move_array& out, Piece piece, int file_step, int rank_step, bool blockable) noexcept\n {\n for(auto start : Square::all_squares())\n {\n auto end = start + Square_Difference{file_step, rank_step};\n if(end.inside_board())\n {\n add_legal_move<Move>(out, piece, blockable, start, end);\n }\n }\n }\n\n void add_pawn_moves(indexed_move_array& out, Piece_Color color) noexcept\n {\n auto pawn = Piece{color, Piece_Type::PAWN};\n auto base_rank = (color == Piece_Color::WHITE ? 2 : 7);\n auto no_normal_move_rank = (color == Piece_Color::WHITE ? 7 : 2);\n auto rank_change = (color == Piece_Color::WHITE ? 1 : -1);\n for(char file = 'a'; file <= 'h'; ++file)\n {\n for(int rank = base_rank; rank != no_normal_move_rank; rank += rank_change)\n {\n add_legal_move<Pawn_Move>(out, pawn, true, color, Square{file, rank});\n }\n }\n\n for(char file = 'a'; file <= 'h'; ++file)\n {\n add_legal_move<Pawn_Double_Move>(out, pawn, true, color, file);\n }\n\n std::vector<Piece_Type> possible_promotions;\n for(auto type_index = 0; type_index <= static_cast<int>(Piece_Type::KING); ++type_index)\n {\n auto type = static_cast<Piece_Type>(type_index);\n if(type == Piece_Type::PAWN || type == Piece_Type::KING)\n {\n continue;\n }\n possible_promotions.push_back(type);\n }\n\n for(auto dir : {Direction::RIGHT, Direction::LEFT})\n {\n auto first_file = (dir == Direction::RIGHT ? 'a' : 'b');\n auto last_file = (dir == Direction::RIGHT ? 'g' : 'h');\n for(char file = first_file; file <= last_file; ++file)\n {\n for(int rank = base_rank; rank != no_normal_move_rank; rank += rank_change)\n {\n add_legal_move<Pawn_Move>(out, pawn, true, color, Square{file, rank}, dir);\n }\n }\n\n for(char file = first_file; file <= last_file; ++file)\n {\n add_legal_move<En_Passant>(out, pawn, true, color, dir, file);\n }\n\n for(auto promote : possible_promotions)\n {\n for(auto file = first_file; file <= last_file; ++file)\n {\n add_legal_move<Pawn_Promotion>(out, pawn, false, promote, color, file, dir);\n }\n }\n }\n\n for(auto promote : possible_promotions)\n {\n for(auto file = 'a'; file <= 'h'; ++file)\n {\n add_legal_move<Pawn_Promotion>(out, pawn, false, promote, color, file);\n }\n }\n }\n\n void add_rook_moves(indexed_move_array& out, Piece_Color color, Piece_Type type) noexcept\n {\n for(int d_file = -1; d_file <= 1; ++d_file)\n {\n for(int d_rank = -1; d_rank <= 1; ++d_rank)\n {\n if(d_file == 0 && d_rank == 0) { continue; }\n if(d_file != 0 && d_rank != 0) { continue; }\n\n for(int move_size = 1; move_size <= 7; ++move_size)\n {\n add_standard_legal_move(out, {color, type}, move_size*d_file, move_size*d_rank, true);\n }\n }\n }\n }\n\n void add_knight_moves(indexed_move_array& out, Piece_Color color) noexcept\n {\n for(auto d_file : {1, 2})\n {\n auto d_rank = 3 - d_file;\n for(auto file_direction : {-1, 1})\n {\n for(auto rank_direction : {-1, 1})\n {\n add_standard_legal_move(out, {color, Piece_Type::KNIGHT}, d_file*file_direction, d_rank*rank_direction, false);\n }\n }\n }\n }\n\n void add_bishop_moves(indexed_move_array& out, Piece_Color color, Piece_Type type) noexcept\n {\n for(int d_rank : {-1, 1})\n {\n for(int d_file : {-1, 1})\n {\n for(int move_size = 1; move_size <= 7; ++move_size)\n {\n add_standard_legal_move(out, {color, type}, move_size*d_file, move_size*d_rank, true);\n }\n }\n }\n }\n\n void add_queen_moves(indexed_move_array& out, Piece_Color color) noexcept\n {\n add_bishop_moves(out, color, Piece_Type::QUEEN);\n add_rook_moves(out, color, Piece_Type::QUEEN);\n }\n\n void add_king_moves(indexed_move_array& out, Piece_Color color) noexcept\n {\n auto king = Piece{color, Piece_Type::KING};\n auto kingside_castle_added = false;\n auto queenside_castle_added = false;\n int base_rank = (color == Piece_Color::WHITE ? 1 : 8);\n for(int d_rank = -1; d_rank <= 1; ++d_rank)\n {\n for(int d_file = -1; d_file <= 1; ++d_file)\n {\n if(d_rank == 0 && d_file == 0) { continue; }\n\n add_standard_legal_move(out, king, d_file, d_rank, true);\n if(d_rank == 0)\n {\n if(d_file > 0)\n {\n if( ! kingside_castle_added)\n {\n add_legal_move<Castle>(out, king, true, base_rank, Direction::RIGHT);\n kingside_castle_added = true;\n }\n }\n else\n {\n if( ! queenside_castle_added)\n {\n add_legal_move<Castle>(out, king, true, base_rank, Direction::LEFT);\n }\n }\n }\n }\n }\n }\n\n Piece_Type piece_type_from_char(char pgn_symbol)\n {\n auto i = pgn_symbols.find(std::toupper(pgn_symbol));\n if(i == std::string::npos)\n {\n throw std::invalid_argument(pgn_symbol + std::string{\" is not a valid piece PGN symbol.\"});\n }\n return static_cast<Piece_Type>(i);\n }\n}\n\nPiece::Piece() noexcept : piece_code(invalid_code)\n{\n}\n\nPiece::Piece(Piece_Color color, Piece_Type type) noexcept :\n piece_code((static_cast<int>(type) << 1) | static_cast<int>(color))\n{\n \/\/ piece_code layout: 4 bits\n \/\/ 3 most significant bits = Piece_Type (values 0-5)\n \/\/ least significant bit = Piece_Color (0 or 1)\n \/\/\n \/\/ 101 1\n \/\/ ^^^ ^-- Piece_Color::BLACK\n \/\/ +--- Piece_Type::KING\n}\n\nPiece::Piece(char pgn_symbol) : Piece(std::isupper(pgn_symbol) ? Piece_Color::WHITE : Piece_Color::BLACK,\n piece_type_from_char(pgn_symbol))\n{\n}\n\nPiece_Color Piece::color() const noexcept\n{\n assert(*this);\n return static_cast<Piece_Color>(piece_code & 1);\n}\n\nstd::string Piece::pgn_symbol() const noexcept\n{\n assert(*this);\n return type() == Piece_Type::PAWN ? std::string{} : std::string(1, std::toupper(fen_symbol()));\n}\n\nchar Piece::fen_symbol() const noexcept\n{\n assert(*this);\n auto symbol = pgn_symbols[static_cast<int>(type())];\n return (color() == Piece_Color::WHITE ? symbol : std::tolower(symbol));\n}\n\nbool Piece::can_move(const Move* move) const noexcept\n{\n assert(*this);\n for(const auto& moves : move_lists(move->start()))\n {\n if(std::find(moves.begin(), moves.end(), move) != moves.end())\n {\n return true;\n }\n }\n\n return false;\n}\n\nconst Piece::list_of_move_lists& Piece::move_lists(Square square) const noexcept\n{\n assert(*this);\n return legal_moves[index()][square.index()];\n}\n\nPiece_Type Piece::type() const noexcept\n{\n assert(*this);\n return static_cast<Piece_Type>(piece_code >> 1);\n}\n\nPiece::operator bool() const noexcept\n{\n return piece_code != invalid_code;\n}\n\nPiece::piece_code_t Piece::index() const noexcept\n{\n return piece_code;\n}\n\nconst Piece::list_of_move_lists& Piece::attacking_move_lists(Square square) const noexcept\n{\n assert(*this);\n return attack_moves[index()][square.index()];\n}\n\nbool operator==(Piece a, Piece b) noexcept\n{\n return a.index() == b.index();\n}\n\nbool operator!=(Piece a, Piece b) noexcept\n{\n return !(a == b);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_PROFILER_HH_INCLUDED\n#define DUNE_STUFF_PROFILER_HH_INCLUDED\n\n#ifndef DUNE_STUFF_ENABLE_PROFILE_SCOPE\n# define DUNE_STUFF_ENABLE_PROFILE_SCOPE 0\n#endif\n\n#include <string>\n#include <map>\n#include <vector>\n#include <ctime>\n#include <memory>\n#include <iostream>\n#include <mutex>\n\n#include <boost\/noncopyable.hpp>\n#include <boost\/timer\/timer.hpp>\n\n#include <dune\/common\/unused.hh>\n\n#include <dune\/stuff\/common\/parallel\/threadmanager.hh>\n#include <dune\/stuff\/common\/parallel\/threadstorage.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\nclass Profiler;\n\n\/\/! Stuff::Profiler global instance\nProfiler& profiler();\n\n\/\/! wraps name, start- and end time for one timing section\nstruct TimingData\n{\nprivate:\n std::shared_ptr<boost::timer::cpu_timer> timer_;\npublic:\n std::string name;\n\n explicit TimingData(const std::string _name = \"blank\");\n\n void stop();\n\n typedef boost::timer::nanosecond_type TimeType;\n typedef std::array<TimeType, 4> DeltaType;\n\n \/** \\return time elapsed since object construction in milliseconds\n * \\note since typical resolutions for user+system time are 10-15ms the nanosecond results are scaled accordingly\n **\/\n DeltaType delta() const;\n};\n\n\/\/! a utility class to time a limited scope of code\nclass ScopedTiming;\n\n\/** \\brief simple inline profiling class\n * - User can set as many (even nested) named sections whose total (=system+user) time will be computed across all program\n * instances.\\n\n * - Provides csv-conform output of process-averaged runtimes.\n **\/\nclass Profiler\n{\n friend Profiler& profiler();\n\nprivate:\n Profiler();\n ~Profiler();\n\n typedef std::map< std::string, std::pair< bool, PerThreadValue<TimingData> > >\n KnownTimersMap;\n \/\/! section name -> seconds\n typedef std::map< std::string, TimingData::DeltaType >\n Datamap;\n \/\/! \"Run idx\" -> Datamap = section name -> seconds\n typedef std::vector< Datamap >\n DatamapVector;\n\n \/\/! appends int to section name\n long stopTiming(const std::string section_name, const size_t i, const bool use_walltime);\n\n \/\/! appends int to section name\n void startTiming(const std::string section_name, const size_t i);\n\n \/\/! appends int to section name\n void resetTiming(const std::string section_name, const size_t i);\n\n \/\/! appends int to section name\n long getTiming(const std::string section_name, const size_t i, const bool use_walltime ) const;\n \/\/! get runtime of section in run run_number in milliseconds\n long getTimingIdx(const std::string section_name, const size_t run_number, const bool use_walltime) const;\n\npublic:\n \/\/! set this to begin a named section\n void startTiming(const std::string section_name);\n\n \/\/! stop named section's counter\n long stopTiming(const std::string section_name, const bool use_walltime = false);\n\n \/\/! set elapsed time back to 0 for section_name\n void resetTiming(const std::string section_name);\n\n \/\/! get runtime of section in current run in milliseconds\n long getTiming(const std::string section_name, const bool use_walltime = false) const;\n\n \/** output to currently pre-defined (csv) file, does not output individual run results, but average over all recorded\n * results\n **\/\n void outputAveraged(const int refineLevel,\n const long numDofs,\n const double scale_factor = 1.0) const;\n\n \/\/! file-output the named sections only\n void outputTimings(const std::string filename) const;\n void outputTimings(std::ostream& out = std::cout) const;\n void outputTimingsAll(std::ostream& out = std::cout) const;\n\n \/** call this with correct numRuns <b> before <\/b> starting any profiling\n * if you're planning on doing more than one iteration of your code\n * called once fromm ctor with numRuns=1\n **\/\n void reset(const size_t numRuns);\n\n \/\/! simple counter, usable to count how often a single piece of code is called\n void addCount(const size_t num);\n\n \/\/! call this after one iteration of your code has finished. increments current run number and puts new timing data\n \/\/! into the vector\n void nextRun();\n\n void setOutputdir(const std::string dir);\n\nprivate:\n DatamapVector datamaps_;\n size_t current_run_number_;\n \/\/! runtime tables etc go there\n std::string output_dir_;\n \/\/ debug counter, only outputted in debug mode\n std::map< size_t, size_t > counters_;\n\n KnownTimersMap known_timers_map_;\n const std::string csv_sep_;\n std::mutex mutex_;\n\n static Profiler& instance() {\n static Profiler pf;\n return pf;\n }\n\n};\n\n\/\/! global profiler object\ninline Profiler& profiler() {\n return Profiler::instance();\n}\n\nclass ScopedTiming : public boost::noncopyable\n{\nprotected:\n const std::string section_name_;\n\npublic:\n inline ScopedTiming(const std::string& section_name)\n : section_name_(section_name) {\n profiler().startTiming(section_name_);\n }\n\n inline ~ScopedTiming() {\n profiler().stopTiming(section_name_);\n }\n};\n\nstruct OutputScopedTiming : public ScopedTiming {\n OutputScopedTiming(const std::string& section_name, std::ostream& out);\n\n ~OutputScopedTiming();\nprotected:\n std::ostream& out_;\n};\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n\n#define DSC_PROFILER Dune::Stuff::Common::profiler()\n\n\n#if DUNE_STUFF_ENABLE_PROFILE_SCOPE\n# define DUNE_STUFF_PROFILE_SCOPE(section_name) \\\n Dune::Stuff::Common::ScopedTiming DUNE_UNUSED(timer)(section_name)\n#else\n# define DUNE_STUFF_PROFILE_SCOPE(section_name)\n#endif\n\n\n#endif \/\/ DUNE_STUFF_PROFILER_HH_INCLUDED\n<commit_msg>[common.profiler] add DUNE_STUFF_DO_PROFILE<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_PROFILER_HH_INCLUDED\n#define DUNE_STUFF_PROFILER_HH_INCLUDED\n\n#ifndef DUNE_STUFF_DO_PROFILE\n# define DUNE_STUFF_DO_PROFILE 0\n#endif\n#if DUNE_STUFF_DO_PROFILE\n# define DUNE_STUFF_ENABLE_PROFILE_SCOPE 1\n#endif\n\n#ifndef DUNE_STUFF_ENABLE_PROFILE_SCOPE\n# define DUNE_STUFF_ENABLE_PROFILE_SCOPE 0\n#endif\n\n#include <string>\n#include <map>\n#include <vector>\n#include <ctime>\n#include <memory>\n#include <iostream>\n#include <mutex>\n\n#include <boost\/noncopyable.hpp>\n#include <boost\/timer\/timer.hpp>\n\n#include <dune\/common\/unused.hh>\n\n#include <dune\/stuff\/common\/parallel\/threadmanager.hh>\n#include <dune\/stuff\/common\/parallel\/threadstorage.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\nclass Profiler;\n\n\/\/! Stuff::Profiler global instance\nProfiler& profiler();\n\n\/\/! wraps name, start- and end time for one timing section\nstruct TimingData\n{\nprivate:\n std::shared_ptr<boost::timer::cpu_timer> timer_;\npublic:\n std::string name;\n\n explicit TimingData(const std::string _name = \"blank\");\n\n void stop();\n\n typedef boost::timer::nanosecond_type TimeType;\n typedef std::array<TimeType, 4> DeltaType;\n\n \/** \\return time elapsed since object construction in milliseconds\n * \\note since typical resolutions for user+system time are 10-15ms the nanosecond results are scaled accordingly\n **\/\n DeltaType delta() const;\n};\n\n\/\/! a utility class to time a limited scope of code\nclass ScopedTiming;\n\n\/** \\brief simple inline profiling class\n * - User can set as many (even nested) named sections whose total (=system+user) time will be computed across all program\n * instances.\\n\n * - Provides csv-conform output of process-averaged runtimes.\n **\/\nclass Profiler\n{\n friend Profiler& profiler();\n\nprivate:\n Profiler();\n ~Profiler();\n\n typedef std::map< std::string, std::pair< bool, PerThreadValue<TimingData> > >\n KnownTimersMap;\n \/\/! section name -> seconds\n typedef std::map< std::string, TimingData::DeltaType >\n Datamap;\n \/\/! \"Run idx\" -> Datamap = section name -> seconds\n typedef std::vector< Datamap >\n DatamapVector;\n\n \/\/! appends int to section name\n long stopTiming(const std::string section_name, const size_t i, const bool use_walltime);\n\n \/\/! appends int to section name\n void startTiming(const std::string section_name, const size_t i);\n\n \/\/! appends int to section name\n void resetTiming(const std::string section_name, const size_t i);\n\n \/\/! appends int to section name\n long getTiming(const std::string section_name, const size_t i, const bool use_walltime ) const;\n \/\/! get runtime of section in run run_number in milliseconds\n long getTimingIdx(const std::string section_name, const size_t run_number, const bool use_walltime) const;\n\npublic:\n \/\/! set this to begin a named section\n void startTiming(const std::string section_name);\n\n \/\/! stop named section's counter\n long stopTiming(const std::string section_name, const bool use_walltime = false);\n\n \/\/! set elapsed time back to 0 for section_name\n void resetTiming(const std::string section_name);\n\n \/\/! get runtime of section in current run in milliseconds\n long getTiming(const std::string section_name, const bool use_walltime = false) const;\n\n \/** output to currently pre-defined (csv) file, does not output individual run results, but average over all recorded\n * results\n **\/\n void outputAveraged(const int refineLevel,\n const long numDofs,\n const double scale_factor = 1.0) const;\n\n \/\/! file-output the named sections only\n void outputTimings(const std::string filename) const;\n void outputTimings(std::ostream& out = std::cout) const;\n void outputTimingsAll(std::ostream& out = std::cout) const;\n\n \/** call this with correct numRuns <b> before <\/b> starting any profiling\n * if you're planning on doing more than one iteration of your code\n * called once fromm ctor with numRuns=1\n **\/\n void reset(const size_t numRuns);\n\n \/\/! simple counter, usable to count how often a single piece of code is called\n void addCount(const size_t num);\n\n \/\/! call this after one iteration of your code has finished. increments current run number and puts new timing data\n \/\/! into the vector\n void nextRun();\n\n void setOutputdir(const std::string dir);\n\nprivate:\n DatamapVector datamaps_;\n size_t current_run_number_;\n \/\/! runtime tables etc go there\n std::string output_dir_;\n \/\/ debug counter, only outputted in debug mode\n std::map< size_t, size_t > counters_;\n\n KnownTimersMap known_timers_map_;\n const std::string csv_sep_;\n std::mutex mutex_;\n\n static Profiler& instance() {\n static Profiler pf;\n return pf;\n }\n\n};\n\n\/\/! global profiler object\ninline Profiler& profiler() {\n return Profiler::instance();\n}\n\nclass ScopedTiming : public boost::noncopyable\n{\nprotected:\n const std::string section_name_;\n\npublic:\n inline ScopedTiming(const std::string& section_name)\n : section_name_(section_name) {\n profiler().startTiming(section_name_);\n }\n\n inline ~ScopedTiming() {\n profiler().stopTiming(section_name_);\n }\n};\n\nstruct OutputScopedTiming : public ScopedTiming {\n OutputScopedTiming(const std::string& section_name, std::ostream& out);\n\n ~OutputScopedTiming();\nprotected:\n std::ostream& out_;\n};\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n\n#define DSC_PROFILER Dune::Stuff::Common::profiler()\n\n\n#if DUNE_STUFF_ENABLE_PROFILE_SCOPE\n# define DUNE_STUFF_PROFILE_SCOPE(section_name) \\\n Dune::Stuff::Common::ScopedTiming DUNE_UNUSED(timer)(section_name)\n#else\n# define DUNE_STUFF_PROFILE_SCOPE(section_name)\n#endif\n\n\n#endif \/\/ DUNE_STUFF_PROFILER_HH_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 GeunYoung Lim <interruping4dev@gmail.com>\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\/\/ dl_livemap_service_io_manager_boost_impl.cpp\n\/\/ livemap_server\n\/\/\n\/\/ Created by Geon young Lim on 2017. 9. 5..\n\/\/\n\/\/\n\n#include \"dl_livemap_service_io_manager_boost_impl.hpp\"\n#include \"command_binder.hpp\"\n\nnamespace solarcode {\nnamespace livemap {\n dl_livemap_service_io_manager_boost_impl::dl_livemap_service_io_manager_boost_impl(std::weak_ptr<session_base> session, client_node_pool& node_pool)\n :solarcode::livemap::session_io_manager_base(session),\n _mutex_for_buffer(),\n _cv_for_buffer(),\n _io_service(get_shared_io_service()),\n _node_pool(node_pool),\n _buffer(nullptr),\n _buffer_size(0)\n {\n \n \n \n }\n \n \n boost::asio::strand\n dl_livemap_service_io_manager_boost_impl::_strand_for_node_pool\n = boost::asio::strand(get_shared_io_service());\n\n void dl_livemap_service_io_manager_boost_impl::session_read_after_buffer(char *const buffer, const std::size_t buffer_length)\n {\n\n \n auto unsafe_service = [this, buffer, buffer_length]() {\n std::unique_lock<std::mutex> lock_for_buffer(_mutex_for_buffer);\n \n _buffer_size = command_bind(get_session_owner(),_node_pool, buffer, buffer_length, &_buffer);\n \n delete [] buffer;\n \/\/_cv_for_buffer.notify_one();\n \n };\n \n auto safe_service = _strand_for_node_pool.wrap(unsafe_service);\n _io_service.post(safe_service);\n \n }\n \n std::size_t dl_livemap_service_io_manager_boost_impl::session_write_before_buffer(char **buffer)\n {\n std::unique_lock<std::mutex> lock_for_buffer(_mutex_for_buffer);\n \n *buffer = _buffer;\n \n\n _buffer = nullptr;\n std::size_t size_to_return = _buffer_size;\n _buffer_size = 0;\n \n return size_to_return;\n }\n}\n \n}\n<commit_msg>remove unnecessary comment.<commit_after>\/\/ Copyright 2017 GeunYoung Lim <interruping4dev@gmail.com>\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\/\/ dl_livemap_service_io_manager_boost_impl.cpp\n\/\/ livemap_server\n\/\/\n\/\/ Created by Geon young Lim on 2017. 9. 5..\n\/\/\n\/\/\n\n#include \"dl_livemap_service_io_manager_boost_impl.hpp\"\n#include \"command_binder.hpp\"\n\nnamespace solarcode {\nnamespace livemap {\n dl_livemap_service_io_manager_boost_impl::dl_livemap_service_io_manager_boost_impl(std::weak_ptr<session_base> session, client_node_pool& node_pool)\n :solarcode::livemap::session_io_manager_base(session),\n _mutex_for_buffer(),\n _cv_for_buffer(),\n _io_service(get_shared_io_service()),\n _node_pool(node_pool),\n _buffer(nullptr),\n _buffer_size(0)\n {\n \n \n \n }\n \n \n boost::asio::strand\n dl_livemap_service_io_manager_boost_impl::_strand_for_node_pool\n = boost::asio::strand(get_shared_io_service());\n\n void dl_livemap_service_io_manager_boost_impl::session_read_after_buffer(char *const buffer, const std::size_t buffer_length)\n {\n auto unsafe_service = [this, buffer, buffer_length]() {\n std::unique_lock<std::mutex> lock_for_buffer(_mutex_for_buffer);\n \n _buffer_size = command_bind(get_session_owner(),_node_pool, buffer, buffer_length, &_buffer);\n \n delete [] buffer;\n };\n \n auto safe_service = _strand_for_node_pool.wrap(unsafe_service);\n _io_service.post(safe_service);\n }\n \n std::size_t dl_livemap_service_io_manager_boost_impl::session_write_before_buffer(char **buffer)\n {\n std::unique_lock<std::mutex> lock_for_buffer(_mutex_for_buffer);\n \n *buffer = _buffer;\n \n\n _buffer = nullptr;\n std::size_t size_to_return = _buffer_size;\n _buffer_size = 0;\n \n return size_to_return;\n }\n}\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2013 Daniele Bartolini, Michele Rossi\nCopyright (c) 2012 Daniele Bartolini, Simone Boscaratto\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <stdarg.h>\n\n#include \"LuaEnvironment.h\"\n#include \"Assert.h\"\n#include \"StringUtils.h\"\n#include \"LuaStack.h\"\n#include \"Device.h\"\n#include \"LuaResource.h\"\n#include \"ResourceManager.h\"\n\nnamespace crown\n{\n\nextern int vector3_add(lua_State* L);\nextern int vector3_subtract(lua_State* L);\nextern int vector3_multiply(lua_State* L);\nextern int vector3_divide(lua_State* L);\nextern int vector3_negate(lua_State* L);\nextern int vector3(lua_State* L);\n\n\/\/-----------------------------------------------------------------------------\nCE_EXPORT int luaopen_libcrown(lua_State* \/*L*\/)\n{\n\tLuaEnvironment* env = device()->lua_environment();\n\n\tload_int_setting(*env);\n\tload_float_setting(*env);\n\tload_string_setting(*env);\n\n\tload_vector2(*env);\n\tload_vector3(*env);\n\tload_matrix4x4(*env);\n\tload_quaternion(*env);\n\tload_math(*env);\n\tload_window(*env);\n\tload_mouse(*env);\n\tload_keyboard(*env);\n\tload_accelerometer(*env);\n\tload_device(*env);\n\tload_resource_package(*env);\n\n\tload_unit(*env);\n\tload_camera(*env);\n\tload_world(*env);\n\tload_mesh(*env);\n\tload_sprite(*env);\n\n\treturn 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_add(lua_State* L)\n{\n\treturn vector3_add(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_sub(lua_State* L)\n{\n\treturn vector3_subtract(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_mul(lua_State* L)\n{\n\treturn vector3_multiply(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_div(lua_State* L)\n{\n\treturn vector3_divide(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_unm(lua_State* L)\n{\n\treturn vector3_negate(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_require(lua_State* L)\n{\n\tLuaStack stack(L);\n\n\tconst char* filename = stack.get_string(1);\n\n\tconst ResourceId lua_res = device()->resource_manager()->load(\"lua\", filename);\n\tdevice()->resource_manager()->flush();\n\n\tconst LuaResource* lr = (LuaResource*) device()->resource_manager()->data(lua_res);\n\tluaL_loadbuffer(L, (const char*) lr->code(), lr->size(), \"\");\n\n\tdevice()->resource_manager()->unload(lua_res);\n\n\treturn 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nLuaEnvironment::LuaEnvironment()\n\t: m_state(luaL_newstate())\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid LuaEnvironment::init()\n{\n\t\/\/ Open default libraries\n\tluaL_openlibs(m_state);\n\t\/\/ Open Crown library\n\tlua_cpcall(m_state, luaopen_libcrown, NULL);\n\n\t\/\/ Register custom loader\n\tlua_getfield(m_state, LUA_GLOBALSINDEX, \"package\");\n\tlua_getfield(m_state, -1, \"loaders\");\n\tlua_remove(m_state, -2);\n\n\tint num_loaders = 0;\n\tlua_pushnil(m_state);\n\twhile (lua_next(m_state, -2) != 0)\n\t{\n\t\tlua_pop(m_state, 1);\n\t\tnum_loaders++;\n\t}\n\n\tlua_pushinteger(m_state, num_loaders + 1);\n\tlua_pushcfunction(m_state, crown_lua_require);\n\tlua_rawset(m_state, -3);\n\n\tlua_pop(m_state, 1);\n\n\t\/\/ Create metatable for lightuserdata\n\tlua_pushlightuserdata(m_state, (void*)0x0);\n\tluaL_newmetatable(m_state, \"Crown.lightuserdata.metatable\");\n\tlua_setmetatable(m_state, -2);\n\tlua_pop(m_state, 1);\n\n\tluaL_newmetatable(m_state, \"Crown.lightuserdata.metatable\");\n\n\tlua_pushstring(m_state, \"__add\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_add);\n\tlua_settable(m_state, 1);\n\n\tlua_pushstring(m_state, \"__sub\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_sub);\n\tlua_settable(m_state, 1);\n\n\tlua_pushstring(m_state, \"__mul\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_mul);\n\tlua_settable(m_state, 1);\n\n\tlua_pushstring(m_state, \"__div\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_div);\n\tlua_settable(m_state, 1);\n\n\tlua_pushstring(m_state, \"__unm\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_unm);\n\tlua_settable(m_state, 1);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid LuaEnvironment::shutdown()\n{\n\tlua_close(m_state);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool LuaEnvironment::load_and_execute(const char* res_name)\n{\n\tCE_ASSERT_NOT_NULL(res_name);\n\n\tResourceManager* resman = device()->resource_manager();\n\n\t\/\/ Load the resource\n\tResourceId res_id = resman->load(\"lua\", res_name);\n\tresman->flush();\n\tLuaResource* lr = (LuaResource*) resman->data(res_id);\n\t\n\tlua_getglobal(m_state, \"debug\");\n\tlua_getfield(m_state, -1, \"traceback\");\n\tif (luaL_loadbuffer(m_state, (const char*) lr->code(), lr->size(), res_name) == 0)\n\t{\n\t\tif (lua_pcall(m_state, 0, 0, -2) == 0)\n\t\t{\n\t\t\t\/\/ Unloading is OK since the script data has been copied to Lua\n\t\t\tresman->unload(res_id);\n\t\t\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\t\t\treturn true;\n\t\t}\n\t}\n\n\terror();\n\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool LuaEnvironment::execute_string(const char* s)\n{\n\tCE_ASSERT_NOT_NULL(s);\n\n\tlua_getglobal(m_state, \"debug\");\n\tlua_getfield(m_state, -1, \"traceback\");\n\tif (luaL_loadstring(m_state, s) == 0)\n\t{\n\t\tif (lua_pcall(m_state, 0, 0, -2) == 0)\n\t\t{\n\t\t\t\/\/ Unloading is OK since the script data has been copied to Lua\n\t\t\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\t\t\treturn true;\n\t\t}\n\t}\n\n\terror();\n\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid LuaEnvironment::load_module_function(const char* module, const char* name, const lua_CFunction func)\n{\n\tluaL_Reg entry[2];\n\n\tentry[0].name = name;\n\tentry[0].func = func;\n\tentry[1].name = NULL;\n\tentry[1].func = NULL;\n\n\tluaL_register(m_state, module, entry);\n}\n\n\/\/-----------------------------------------------------------\nvoid LuaEnvironment::load_module_enum(const char* \/*module*\/, const char* name, uint32_t value)\n{\n\tlua_pushinteger(m_state, value);\n\tlua_setfield(m_state, -2, name);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool LuaEnvironment::call_global(const char* func, uint8_t argc, ...)\n{\n\tCE_ASSERT_NOT_NULL(func);\n\n\tLuaStack stack(m_state);\n\n\tva_list vl;\n\tva_start(vl, argc);\n\n\tlua_getglobal(m_state, \"debug\");\n\tlua_getfield(m_state, -1, \"traceback\");\n\tlua_getglobal(m_state, func);\n\n\tfor (uint8_t i = 0; i < argc; i++)\n\t{\n\t\tconst int type = va_arg(vl, int);\n\t\tswitch (type)\n\t\t{\n\t\t\tcase ARGUMENT_FLOAT:\n\t\t\t{\n\t\t\t\tstack.push_float(va_arg(vl, double));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tCE_ASSERT(false, \"Oops, lua argument unknown\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tva_end(vl);\n\n\tif (lua_pcall(m_state, argc, 0, -argc - 2) != 0)\n\t{\n\t\terror();\n\t\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\t\treturn false;\n\t}\n\n\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\n\treturn true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid LuaEnvironment::error()\n{\n\tconst char* msg = lua_tostring(m_state, -1);\n\tLog::e(msg);\n\tlua_pop(m_state, 1);\n}\n\n} \/\/ namespace crown<commit_msg>Add metatable to Vector2\/Vector3\/Matrix4x4\/Quaternion in order to prevent engine hackers from injuries of any kind. And also to improve Lua code readability<commit_after>\/*\nCopyright (c) 2013 Daniele Bartolini, Michele Rossi\nCopyright (c) 2012 Daniele Bartolini, Simone Boscaratto\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <stdarg.h>\n\n#include \"LuaEnvironment.h\"\n#include \"Assert.h\"\n#include \"StringUtils.h\"\n#include \"LuaStack.h\"\n#include \"Device.h\"\n#include \"LuaResource.h\"\n#include \"ResourceManager.h\"\n\nnamespace crown\n{\n\nextern int vector3_add(lua_State* L);\nextern int vector3_subtract(lua_State* L);\nextern int vector3_multiply(lua_State* L);\nextern int vector3_divide(lua_State* L);\nextern int vector3_negate(lua_State* L);\nextern int vector2(lua_State* L);\nextern int vector3(lua_State* L);\nextern int matrix4x4(lua_State* L);\nextern int quaternion(lua_State* L);\n\n\/\/-----------------------------------------------------------------------------\nCE_EXPORT int luaopen_libcrown(lua_State* \/*L*\/)\n{\n\tLuaEnvironment* env = device()->lua_environment();\n\n\tload_int_setting(*env);\n\tload_float_setting(*env);\n\tload_string_setting(*env);\n\n\tload_vector2(*env);\n\tload_vector3(*env);\n\tload_matrix4x4(*env);\n\tload_quaternion(*env);\n\tload_math(*env);\n\tload_window(*env);\n\tload_mouse(*env);\n\tload_keyboard(*env);\n\tload_accelerometer(*env);\n\tload_device(*env);\n\tload_resource_package(*env);\n\n\tload_unit(*env);\n\tload_camera(*env);\n\tload_world(*env);\n\tload_mesh(*env);\n\tload_sprite(*env);\n\n\treturn 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_vector2_call(lua_State* L)\n{\n\tlua_remove(L, 1);\n\treturn vector2(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_vector3_call(lua_State* L)\n{\n\tlua_remove(L, 1);\n\treturn vector3(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_matrix4x4_call(lua_State* L)\n{\n\tlua_remove(L, 1);\n\treturn matrix4x4(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_quaternion_call(lua_State* L)\n{\n\tlua_remove(L, 1);\n\treturn quaternion(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_add(lua_State* L)\n{\n\treturn vector3_add(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_sub(lua_State* L)\n{\n\treturn vector3_subtract(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_mul(lua_State* L)\n{\n\treturn vector3_multiply(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_div(lua_State* L)\n{\n\treturn vector3_divide(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_lightuserdata_unm(lua_State* L)\n{\n\treturn vector3_negate(L);\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic int crown_lua_require(lua_State* L)\n{\n\tLuaStack stack(L);\n\n\tconst char* filename = stack.get_string(1);\n\n\tconst ResourceId lua_res = device()->resource_manager()->load(\"lua\", filename);\n\tdevice()->resource_manager()->flush();\n\n\tconst LuaResource* lr = (LuaResource*) device()->resource_manager()->data(lua_res);\n\tluaL_loadbuffer(L, (const char*) lr->code(), lr->size(), \"\");\n\n\tdevice()->resource_manager()->unload(lua_res);\n\n\treturn 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nLuaEnvironment::LuaEnvironment()\n\t: m_state(luaL_newstate())\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid LuaEnvironment::init()\n{\n\t\/\/ Open default libraries\n\tluaL_openlibs(m_state);\n\t\/\/ Open Crown library\n\tlua_cpcall(m_state, luaopen_libcrown, NULL);\n\n\t\/\/ Register custom loader\n\tlua_getfield(m_state, LUA_GLOBALSINDEX, \"package\");\n\tlua_getfield(m_state, -1, \"loaders\");\n\tlua_remove(m_state, -2);\n\n\tint num_loaders = 0;\n\tlua_pushnil(m_state);\n\twhile (lua_next(m_state, -2) != 0)\n\t{\n\t\tlua_pop(m_state, 1);\n\t\tnum_loaders++;\n\t}\n\n\tlua_pushinteger(m_state, num_loaders + 1);\n\tlua_pushcfunction(m_state, crown_lua_require);\n\tlua_rawset(m_state, -3);\n\n\tlua_pop(m_state, 1);\n\n\t\/\/ Create metatable for lightuserdata\n\tlua_pushlightuserdata(m_state, (void*)0x0);\n\tluaL_newmetatable(m_state, \"Lightuserdata_mt\");\n\tlua_setmetatable(m_state, -2);\n\tlua_pop(m_state, 1);\n\n\tluaL_newmetatable(m_state, \"Lightuserdata_mt\");\n\n\tlua_pushstring(m_state, \"__add\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_add);\n\tlua_settable(m_state, 1);\n\n\tlua_pushstring(m_state, \"__sub\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_sub);\n\tlua_settable(m_state, 1);\n\n\tlua_pushstring(m_state, \"__mul\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_mul);\n\tlua_settable(m_state, 1);\n\n\tlua_pushstring(m_state, \"__div\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_div);\n\tlua_settable(m_state, 1);\n\n\tlua_pushstring(m_state, \"__unm\");\n\tlua_pushcfunction(m_state, crown_lua_lightuserdata_unm);\n\tlua_settable(m_state, 1);\n\n\t\/\/ Vector2 metatable\n\tluaL_newmetatable(m_state, \"Vector2_mt\");\n\tlua_pushvalue(m_state, -1);\n\tlua_setfield(m_state, -2, \"__index\");\n\tlua_pushcfunction(m_state, crown_lua_vector2_call);\n\tlua_setfield(m_state, -2, \"__call\");\n\n\tlua_getglobal(m_state, \"Vector2\");\n\tlua_pushvalue(m_state, -2); \/\/ Duplicate metatable\n\tlua_setmetatable(m_state, -2); \/\/ setmetatable(Vector2, Vector2_mt)\n\n\t\/\/ Vector3 metatable\n\tluaL_newmetatable(m_state, \"Vector3_mt\");\n\tlua_pushvalue(m_state, -1);\n\tlua_setfield(m_state, -2, \"__index\");\n\tlua_pushcfunction(m_state, crown_lua_vector3_call);\n\tlua_setfield(m_state, -2, \"__call\");\n\n\tlua_getglobal(m_state, \"Vector3\");\n\tlua_pushvalue(m_state, -2); \/\/ Duplicate metatable\n\tlua_setmetatable(m_state, -2); \/\/ setmetatable(Vector3, Vector3_mt)\n\n\t\/\/ Matrix4x4 metatable\n\tluaL_newmetatable(m_state, \"Matrix4x4_mt\");\n\tlua_pushvalue(m_state, -1);\n\tlua_setfield(m_state, -2, \"__index\");\n\tlua_pushcfunction(m_state, crown_lua_matrix4x4_call);\n\tlua_setfield(m_state, -2, \"__call\");\n\n\tlua_getglobal(m_state, \"Matrix4x4\");\n\tlua_pushvalue(m_state, -2); \/\/ Duplicate metatable\n\tlua_setmetatable(m_state, -2); \/\/ setmetatable(Matrix4x4, Matrix4x4_mt)\n\n\t\/\/ Quaternion metatable\n\tluaL_newmetatable(m_state, \"Quaternion_mt\");\n\tlua_pushvalue(m_state, -1);\n\tlua_setfield(m_state, -2, \"__index\");\n\tlua_pushcfunction(m_state, crown_lua_quaternion_call);\n\tlua_setfield(m_state, -2, \"__call\");\n\n\tlua_getglobal(m_state, \"Quaternion\");\n\tlua_pushvalue(m_state, -2); \/\/ Duplicate metatable\n\tlua_setmetatable(m_state, -2); \/\/ setmetatable(Quaternion, Quaternion_mt)\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid LuaEnvironment::shutdown()\n{\n\tlua_close(m_state);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool LuaEnvironment::load_and_execute(const char* res_name)\n{\n\tCE_ASSERT_NOT_NULL(res_name);\n\n\tResourceManager* resman = device()->resource_manager();\n\n\t\/\/ Load the resource\n\tResourceId res_id = resman->load(\"lua\", res_name);\n\tresman->flush();\n\tLuaResource* lr = (LuaResource*) resman->data(res_id);\n\t\n\tlua_getglobal(m_state, \"debug\");\n\tlua_getfield(m_state, -1, \"traceback\");\n\tif (luaL_loadbuffer(m_state, (const char*) lr->code(), lr->size(), res_name) == 0)\n\t{\n\t\tif (lua_pcall(m_state, 0, 0, -2) == 0)\n\t\t{\n\t\t\t\/\/ Unloading is OK since the script data has been copied to Lua\n\t\t\tresman->unload(res_id);\n\t\t\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\t\t\treturn true;\n\t\t}\n\t}\n\n\terror();\n\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool LuaEnvironment::execute_string(const char* s)\n{\n\tCE_ASSERT_NOT_NULL(s);\n\n\tlua_getglobal(m_state, \"debug\");\n\tlua_getfield(m_state, -1, \"traceback\");\n\tif (luaL_loadstring(m_state, s) == 0)\n\t{\n\t\tif (lua_pcall(m_state, 0, 0, -2) == 0)\n\t\t{\n\t\t\t\/\/ Unloading is OK since the script data has been copied to Lua\n\t\t\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\t\t\treturn true;\n\t\t}\n\t}\n\n\terror();\n\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid LuaEnvironment::load_module_function(const char* module, const char* name, const lua_CFunction func)\n{\n\tluaL_Reg entry[2];\n\n\tentry[0].name = name;\n\tentry[0].func = func;\n\tentry[1].name = NULL;\n\tentry[1].func = NULL;\n\n\tluaL_register(m_state, module, entry);\n}\n\n\/\/-----------------------------------------------------------\nvoid LuaEnvironment::load_module_enum(const char* \/*module*\/, const char* name, uint32_t value)\n{\n\tlua_pushinteger(m_state, value);\n\tlua_setfield(m_state, -2, name);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool LuaEnvironment::call_global(const char* func, uint8_t argc, ...)\n{\n\tCE_ASSERT_NOT_NULL(func);\n\n\tLuaStack stack(m_state);\n\n\tva_list vl;\n\tva_start(vl, argc);\n\n\tlua_getglobal(m_state, \"debug\");\n\tlua_getfield(m_state, -1, \"traceback\");\n\tlua_getglobal(m_state, func);\n\n\tfor (uint8_t i = 0; i < argc; i++)\n\t{\n\t\tconst int type = va_arg(vl, int);\n\t\tswitch (type)\n\t\t{\n\t\t\tcase ARGUMENT_FLOAT:\n\t\t\t{\n\t\t\t\tstack.push_float(va_arg(vl, double));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tCE_ASSERT(false, \"Oops, lua argument unknown\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tva_end(vl);\n\n\tif (lua_pcall(m_state, argc, 0, -argc - 2) != 0)\n\t{\n\t\terror();\n\t\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\t\treturn false;\n\t}\n\n\tlua_pop(m_state, 2); \/\/ Pop debug.traceback\n\n\treturn true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid LuaEnvironment::error()\n{\n\tconst char* msg = lua_tostring(m_state, -1);\n\tLog::e(msg);\n\tlua_pop(m_state, 1);\n}\n\n} \/\/ namespace crown<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012-2013 Samplecount S.L.\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#ifndef METHCLA_MEMORY_HPP_INCLUDED\n#define METHCLA_MEMORY_HPP_INCLUDED\n\n#include <boost\/assert.hpp>\n#include <cstddef>\n#include <cstdint>\n\nnamespace Methcla { namespace Memory {\n\nclass Alignment\n{\npublic:\n Alignment(size_t alignment)\n : m_alignment(std::max(alignment, sizeof(void*)))\n {\n BOOST_ASSERT_MSG( (m_alignment & (m_alignment - 1)) == 0, \"Alignment must be a power of two\" );\n }\n Alignment(const Alignment&) = default;\n\n operator size_t () const\n {\n return m_alignment;\n }\n\n template <typename T> bool isAligned(T size) const\n {\n return isAligned(m_alignment, size);\n }\n\n template <typename T> T align(T size) const\n {\n return align(m_alignment, size);\n }\n\n template <typename T> size_t padding(T size) const\n {\n return padding(m_alignment, size);\n }\n\n \/\/ Aligning pointers\n template <typename T> bool isAligned(T* ptr) const\n {\n return isAligned(reinterpret_cast<uintptr_t>(ptr));\n }\n\n template <typename T> T* align(T* ptr) const\n {\n return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr)));\n }\n\n template <typename T> size_t padding(T* ptr) const\n {\n return padding(reinterpret_cast<uintptr_t>(ptr));\n }\n\n \/\/ Static alignment functions\n template <typename T> static bool isAligned(size_t alignment, T n)\n {\n return (n & ~(alignment-1)) == n;\n }\n\n template <typename T> static T align(size_t alignment, T n)\n {\n return (n + alignment) & ~(alignment-1);\n }\n\n template <typename T> static size_t padding(size_t alignment, T n)\n {\n return align(alignment, n) - n;\n }\n\nprivate:\n size_t m_alignment;\n};\n\n\/\/* Default alignment.\nstatic const Alignment kDefaultAlignment(\n#if defined(__ANDROID__)\n alignof(max_align_t)\n#else\n alignof(std::max_align_t)\n#endif\n );\n\n\/\/* Alignment needed for data accessed by SIMD instructions.\nstatic const Alignment kSIMDAlignment(16);\n\n\/\/* Allocate memory of `size` bytes.\n\/\/\n\/\/ @throw std::invalid_argument\n\/\/ @throw std::bad_alloc\nvoid* alloc(size_t size);\n\n\/\/* Allocate aligned memory of `size` bytes.\n\/\/\n\/\/ @throw std::invalid_argument\n\/\/ @throw std::bad_alloc\nvoid* allocAligned(Alignment align, size_t size);\n\n\/\/* Free memory allocated by this allocator.\nvoid free(void* ptr) noexcept;\n\n\/\/* Allocate memory for `n` elements of type `T`.\n\/\/\n\/\/ @throw std::invalid_argument\n\/\/ @throw std::bad_alloc\ntemplate <typename T> T* allocOf(size_t n=1)\n{\n return static_cast<T*>(alloc(n * sizeof(T)));\n}\n\n\/\/* Allocate aligned memory for `n` elements of type `T`.\n\/\/\n\/\/ @throw std::invalid_argument\n\/\/ @throw std::bad_alloc\ntemplate <typename T> T* allocAlignedOf(Alignment align, size_t n=1)\n{\n return static_cast<T*>(allocAligned(align, n * sizeof(T)));\n}\n\n} }\n\n#endif \/\/ METHCLA_MEMORY_HPP_INCLUDED\n<commit_msg>Add missing include<commit_after>\/\/ Copyright 2012-2013 Samplecount S.L.\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#ifndef METHCLA_MEMORY_HPP_INCLUDED\n#define METHCLA_MEMORY_HPP_INCLUDED\n\n#include <algorithm>\n#include <boost\/assert.hpp>\n#include <cstddef>\n#include <cstdint>\n\nnamespace Methcla { namespace Memory {\n\nclass Alignment\n{\npublic:\n Alignment(size_t alignment)\n : m_alignment(std::max(alignment, sizeof(void*)))\n {\n BOOST_ASSERT_MSG( (m_alignment & (m_alignment - 1)) == 0, \"Alignment must be a power of two\" );\n }\n Alignment(const Alignment&) = default;\n\n operator size_t () const\n {\n return m_alignment;\n }\n\n template <typename T> bool isAligned(T size) const\n {\n return isAligned(m_alignment, size);\n }\n\n template <typename T> T align(T size) const\n {\n return align(m_alignment, size);\n }\n\n template <typename T> size_t padding(T size) const\n {\n return padding(m_alignment, size);\n }\n\n \/\/ Aligning pointers\n template <typename T> bool isAligned(T* ptr) const\n {\n return isAligned(reinterpret_cast<uintptr_t>(ptr));\n }\n\n template <typename T> T* align(T* ptr) const\n {\n return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr)));\n }\n\n template <typename T> size_t padding(T* ptr) const\n {\n return padding(reinterpret_cast<uintptr_t>(ptr));\n }\n\n \/\/ Static alignment functions\n template <typename T> static bool isAligned(size_t alignment, T n)\n {\n return (n & ~(alignment-1)) == n;\n }\n\n template <typename T> static T align(size_t alignment, T n)\n {\n return (n + alignment) & ~(alignment-1);\n }\n\n template <typename T> static size_t padding(size_t alignment, T n)\n {\n return align(alignment, n) - n;\n }\n\nprivate:\n size_t m_alignment;\n};\n\n\/\/* Default alignment.\nstatic const Alignment kDefaultAlignment(\n#if defined(__ANDROID__)\n alignof(max_align_t)\n#else\n alignof(std::max_align_t)\n#endif\n );\n\n\/\/* Alignment needed for data accessed by SIMD instructions.\nstatic const Alignment kSIMDAlignment(16);\n\n\/\/* Allocate memory of `size` bytes.\n\/\/\n\/\/ @throw std::invalid_argument\n\/\/ @throw std::bad_alloc\nvoid* alloc(size_t size);\n\n\/\/* Allocate aligned memory of `size` bytes.\n\/\/\n\/\/ @throw std::invalid_argument\n\/\/ @throw std::bad_alloc\nvoid* allocAligned(Alignment align, size_t size);\n\n\/\/* Free memory allocated by this allocator.\nvoid free(void* ptr) noexcept;\n\n\/\/* Allocate memory for `n` elements of type `T`.\n\/\/\n\/\/ @throw std::invalid_argument\n\/\/ @throw std::bad_alloc\ntemplate <typename T> T* allocOf(size_t n=1)\n{\n return static_cast<T*>(alloc(n * sizeof(T)));\n}\n\n\/\/* Allocate aligned memory for `n` elements of type `T`.\n\/\/\n\/\/ @throw std::invalid_argument\n\/\/ @throw std::bad_alloc\ntemplate <typename T> T* allocAlignedOf(Alignment align, size_t n=1)\n{\n return static_cast<T*>(allocAligned(align, n * sizeof(T)));\n}\n\n} }\n\n#endif \/\/ METHCLA_MEMORY_HPP_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>#include \"physics\/discrete_trajectory_segment_iterator.hpp\"\n\nnamespace principia {\nnamespace physics {\nnamespace internal_discrete_trajectory_segment_iterator {\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>&\nDiscreteTrajectorySegmentIterator<Frame>::operator++() {\n ++iterator_;\n return *this;\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>&\nDiscreteTrajectorySegmentIterator<Frame>::operator--() {\n --iterator_;\n return *this;\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>\nDiscreteTrajectorySegmentIterator<Frame>::operator++(int) {\n return DiscreteTrajectorySegmentIterator(segments_, iterator_++);\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>\nDiscreteTrajectorySegmentIterator<Frame>::operator--(int) {\n return DiscreteTrajectorySegmentIterator(segments_, iterator_--);\n}\n\ntemplate<typename Frame>\ninternal_discrete_trajectory_segment::DiscreteTrajectorySegment<Frame> const&\nDiscreteTrajectorySegmentIterator<Frame>::operator*() const {\n return **iterator_;\n}\n\ntemplate<typename Frame>\ninternal_discrete_trajectory_segment::DiscreteTrajectorySegment<Frame> const*\nDiscreteTrajectorySegmentIterator<Frame>::operator->() const {\n return iterator_->get();\n}\n\ntemplate<typename Frame>\nbool DiscreteTrajectorySegmentIterator<Frame>::operator==(\n DiscreteTrajectorySegmentIterator const& other) const {\n return segments_ == other.segments_ && iterator_ == other.iterator_;\n}\n\ntemplate<typename Frame>\nbool DiscreteTrajectorySegmentIterator<Frame>::operator!=(\n DiscreteTrajectorySegmentIterator const& other) const {\n return !operator==(other);\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>::DiscreteTrajectorySegmentIterator(\n not_null<Segments const*> const segments,\n typename Segments::const_iterator iterator)\n : segments_(segments),\n iterator_(iterator) {}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>\nDiscreteTrajectorySegmentIterator<Frame>::begin() const {\n return DiscreteTrajectorySegmentIterator(segments_, segments_->begin());\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>\nDiscreteTrajectorySegmentIterator<Frame>::end() const {\n return DiscreteTrajectorySegmentIterator(segments_, segments_->end());\n}\n\n} \/\/ namespace internal_discrete_trajectory_segment_iterator\n} \/\/ namespace physics\n} \/\/ namespace principia\n<commit_msg>C++ is stupid. So is the linter.<commit_after>#include \"physics\/discrete_trajectory_segment_iterator.hpp\"\n\nnamespace principia {\nnamespace physics {\nnamespace internal_discrete_trajectory_segment_iterator {\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>&\nDiscreteTrajectorySegmentIterator<Frame>::operator++() {\n ++iterator_;\n return *this;\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>&\nDiscreteTrajectorySegmentIterator<Frame>::operator--() {\n --iterator_;\n return *this;\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>\nDiscreteTrajectorySegmentIterator<Frame>::operator++(int) { \/\/ NOLINT\n return DiscreteTrajectorySegmentIterator(segments_, iterator_++);\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>\nDiscreteTrajectorySegmentIterator<Frame>::operator--(int) { \/\/ NOLINT\n return DiscreteTrajectorySegmentIterator(segments_, iterator_--);\n}\n\ntemplate<typename Frame>\ninternal_discrete_trajectory_segment::DiscreteTrajectorySegment<Frame> const&\nDiscreteTrajectorySegmentIterator<Frame>::operator*() const {\n return **iterator_;\n}\n\ntemplate<typename Frame>\ninternal_discrete_trajectory_segment::DiscreteTrajectorySegment<Frame> const*\nDiscreteTrajectorySegmentIterator<Frame>::operator->() const {\n return iterator_->get();\n}\n\ntemplate<typename Frame>\nbool DiscreteTrajectorySegmentIterator<Frame>::operator==(\n DiscreteTrajectorySegmentIterator const& other) const {\n return segments_ == other.segments_ && iterator_ == other.iterator_;\n}\n\ntemplate<typename Frame>\nbool DiscreteTrajectorySegmentIterator<Frame>::operator!=(\n DiscreteTrajectorySegmentIterator const& other) const {\n return !operator==(other);\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>::DiscreteTrajectorySegmentIterator(\n not_null<Segments const*> const segments,\n typename Segments::const_iterator iterator)\n : segments_(segments),\n iterator_(iterator) {}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>\nDiscreteTrajectorySegmentIterator<Frame>::begin() const {\n return DiscreteTrajectorySegmentIterator(segments_, segments_->begin());\n}\n\ntemplate<typename Frame>\nDiscreteTrajectorySegmentIterator<Frame>\nDiscreteTrajectorySegmentIterator<Frame>::end() const {\n return DiscreteTrajectorySegmentIterator(segments_, segments_->end());\n}\n\n} \/\/ namespace internal_discrete_trajectory_segment_iterator\n} \/\/ namespace physics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <sstream>\n#include <string>\n\nusing namespace std;\nint main()\n{\nstringstream ss;\nint start(0);\nint end(0);\nstring tmp;\n\twhile(std::getline(std::cin,tmp))\n\t{\n\t\tss.str(tmp);\n\t\tss>>start>>end;\n\t\tif(start > end)\n\t\t{\n\t\t\tint tmp(0);\n\t\t\ttmp= start;\n\t\t\tstart= end;\n\t\t\tend= tmp;\n\t\t}\n\t\tint max(0);\n\t\tfor(int i=start;i<=end;i++)\n\t\t{\n\t\t\tint count(1);\n\t\t\tint val= i; \n\t\t\twhile(val!=1)\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\tif(val%2==1) val= val * 3 +1;\n\t\t\t\telse\tval\/=2;\n\t\t\t}\n\t\t\tif(count>max) max= count;\n\t\t}\n\t\tstd::cout<<start<<\" \"<<end<<\" \"<<max<<'\\n';\n\t\tss.clear();\n\t}\nreturn -1;\n}\n<commit_msg>Update 3n+1.cpp<commit_after>#include <iostream>\n#include <sstream>\n#include <string>\n\nusing namespace std;\nint main()\n{\nstringstream ss;\nint start(0);\nint end(0);\nstring tmp;\n\twhile(std::getline(std::cin,tmp))\n\t{\n\t\tss.str(tmp);\n\t\tss>>start>>end;\n\t\tif(start > end)\n\t\t{\n\t\t\tint tmp(0);\n\t\t\ttmp= start;\n\t\t\tstart= end;\n\t\t\tend= tmp;\n\t\t}\n\t\tint max(0);\n\t\tfor(int i=start;i<=end;i++)\n\t\t{\n\t\t\tint count(1);\n\t\t\tint val= i; \n\t\t\twhile(val!=1)\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\tif(val%2==1) val= val * 3 +1;\n\t\t\t\telse\tval\/=2;\n\t\t\t}\n\t\t\tif(count>max) max= count;\n\t\t}\n\t\tstd::cout<<start<<\" \"<<end<<\" \"<<max<<'\\n';\n\t\tss.clear();\n\t}\nreturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"MQTTClient.h\"\n\nvoid messageArrived(MQTT::MessageData& messageData) {\n MQTT::Message &message = messageData.message;\n\n \/\/ null terminate topic to create String object\n int len = messageData.topicName.lenstring.len; \n char topic[len+1];\n memcpy(topic, messageData.topicName.lenstring.data, (size_t)len);\n topic[len] = '\\0';\n\n \/\/ null terminate payload\n char * payload = (char *)message.payload;\n payload[message.payloadlen] = '\\0';\n messageReceived(String(topic), String(payload), (char*)message.payload, (unsigned int)message.payloadlen);\n}\n\nMQTTClient::MQTTClient() {}\n\nboolean MQTTClient::begin(const char * hostname, Client& client) {\n return this->begin(hostname, 1883, client);\n}\n\nboolean MQTTClient::begin(const char * _hostname, int _port, Client& _client) {\n this->client = new MQTT::Client<Network, Timer, MQTT_BUFFER_SIZE, 0>(this->network);\n this->network.setClient(&_client);\n this->client->setDefaultMessageHandler(messageArrived);\n this->hostname = _hostname;\n this->port = _port;\n this->options = MQTTPacket_connectData_initializer;\n\n return true;\n}\n\nvoid MQTTClient::setWill(const char * topic) {\n this->setWill(topic, \"\");\n}\n\nvoid MQTTClient::setWill(const char * topic, const char * payload) {\n this->options.willFlag = 0x1;\n this->options.will.topicName.cstring = (char*)topic;\n this->options.will.message.cstring = (char*)payload;\n}\n\nboolean MQTTClient::connect(const char * clientId) {\n return this->connect(clientId, \"\", \"\");\n}\n\nboolean MQTTClient::connect(const char * clientId, const char * username, const char * password) {\n if(!this->network.connect((char*)this->hostname, this->port)) {\n return false;\n }\n\n this->options.clientID.cstring = (char*)clientId;\n if(username && password) {\n this->options.username.cstring = (char*)username;\n this->options.password.cstring = (char*)password;\n }\n \n return this->client->connect(this->options) == 0;\n}\n\nvoid MQTTClient::publish(String topic) {\n this->publish(topic.c_str(), \"\");\n}\n\nvoid MQTTClient::publish(String topic, String payload) {\n this->publish(topic.c_str(), payload.c_str());\n}\n\nvoid MQTTClient::publish(const char * topic, String payload) {\n this->publish(topic, payload.c_str());\n}\n\nvoid MQTTClient::publish(const char * topic, const char * payload) {\n this->publish(topic, (char*)payload, (unsigned int)strlen(payload));\n}\n\nvoid MQTTClient::publish(const char * topic, char * payload, unsigned int length) {\n MQTT::Message message;\n message.qos = MQTT::QOS0;\n message.retained = false;\n message.dup = false;\n message.payload = payload;\n message.payloadlen = length;\n client->publish(topic, message);\n}\n\nvoid MQTTClient::subscribe(String topic) {\n this->subscribe(topic.c_str());\n}\n\nvoid MQTTClient::subscribe(const char * topic) {\n client->subscribe(topic, MQTT::QOS0, NULL);\n}\n\nvoid MQTTClient::unsubscribe(String topic) {\n this->unsubscribe(topic.c_str());\n}\n\nvoid MQTTClient::unsubscribe(const char * topic) {\n client->unsubscribe(topic);\n}\n \nvoid MQTTClient::loop() {\n this->client->yield();\n}\n\nboolean MQTTClient::connected() {\n return this->client->isConnected();\n}\n\nvoid MQTTClient::disconnect() {\n this->client->disconnect();\n}\n<commit_msg>use NULLs rather than empty strings<commit_after>#include \"MQTTClient.h\"\n\nvoid messageArrived(MQTT::MessageData& messageData) {\n MQTT::Message &message = messageData.message;\n\n \/\/ null terminate topic to create String object\n int len = messageData.topicName.lenstring.len; \n char topic[len+1];\n memcpy(topic, messageData.topicName.lenstring.data, (size_t)len);\n topic[len] = '\\0';\n\n \/\/ null terminate payload\n char * payload = (char *)message.payload;\n payload[message.payloadlen] = '\\0';\n messageReceived(String(topic), String(payload), (char*)message.payload, (unsigned int)message.payloadlen);\n}\n\nMQTTClient::MQTTClient() {}\n\nboolean MQTTClient::begin(const char * hostname, Client& client) {\n return this->begin(hostname, 1883, client);\n}\n\nboolean MQTTClient::begin(const char * _hostname, int _port, Client& _client) {\n this->client = new MQTT::Client<Network, Timer, MQTT_BUFFER_SIZE, 0>(this->network);\n this->network.setClient(&_client);\n this->client->setDefaultMessageHandler(messageArrived);\n this->hostname = _hostname;\n this->port = _port;\n this->options = MQTTPacket_connectData_initializer;\n\n return true;\n}\n\nvoid MQTTClient::setWill(const char * topic) {\n this->setWill(topic, \"\");\n}\n\nvoid MQTTClient::setWill(const char * topic, const char * payload) {\n this->options.willFlag = 0x1;\n this->options.will.topicName.cstring = (char*)topic;\n this->options.will.message.cstring = (char*)payload;\n}\n\nboolean MQTTClient::connect(const char * clientId) {\n return this->connect(clientId, NULL, NULL);\n}\n\nboolean MQTTClient::connect(const char * clientId, const char * username, const char * password) {\n if(!this->network.connect((char*)this->hostname, this->port)) {\n return false;\n }\n\n this->options.clientID.cstring = (char*)clientId;\n if(username && password) {\n this->options.username.cstring = (char*)username;\n this->options.password.cstring = (char*)password;\n }\n \n return this->client->connect(this->options) == 0;\n}\n\nvoid MQTTClient::publish(String topic) {\n this->publish(topic.c_str(), \"\");\n}\n\nvoid MQTTClient::publish(String topic, String payload) {\n this->publish(topic.c_str(), payload.c_str());\n}\n\nvoid MQTTClient::publish(const char * topic, String payload) {\n this->publish(topic, payload.c_str());\n}\n\nvoid MQTTClient::publish(const char * topic, const char * payload) {\n this->publish(topic, (char*)payload, (unsigned int)strlen(payload));\n}\n\nvoid MQTTClient::publish(const char * topic, char * payload, unsigned int length) {\n MQTT::Message message;\n message.qos = MQTT::QOS0;\n message.retained = false;\n message.dup = false;\n message.payload = payload;\n message.payloadlen = length;\n client->publish(topic, message);\n}\n\nvoid MQTTClient::subscribe(String topic) {\n this->subscribe(topic.c_str());\n}\n\nvoid MQTTClient::subscribe(const char * topic) {\n client->subscribe(topic, MQTT::QOS0, NULL);\n}\n\nvoid MQTTClient::unsubscribe(String topic) {\n this->unsubscribe(topic.c_str());\n}\n\nvoid MQTTClient::unsubscribe(const char * topic) {\n client->unsubscribe(topic);\n}\n \nvoid MQTTClient::loop() {\n this->client->yield();\n}\n\nboolean MQTTClient::connected() {\n return this->client->isConnected();\n}\n\nvoid MQTTClient::disconnect() {\n this->client->disconnect();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2009 David Verhasselt <david@crowdway.com>\n * Licensed under The MIT License - http:\/\/gmailcc.crowdway.com\/license.txt\n *\/\n\n#include \"MailRecord.h\"\n\n#include <boost\/filesystem.hpp>\nnamespace bf = boost::filesystem;\n\n#include \"LogSink.h\"\n#include \"MailLink.h\"\n#include \"MailBox.h\"\n\nint MailRecord::number_of_deliveries = 0;\n\nMailRecord::MailRecord()\n{\n\tmarked = false;\n\t\n\tflag_draft = false;\n\tflag_flagged = false;\n\tflag_passed = false;\n\tflag_replied = false;\n\tflag_seen = false;\n\tflag_trashed = false;\n}\n\nMailRecord::~MailRecord()\n{\n\tfor (vector<MailLink*>::iterator iter = this->links.begin(); iter < links.end(); iter++)\n\t{\n\t\tdelete(*iter);\n\t}\t\n}\n\nvoid MailRecord::mark()\n{\n\tmarked = true;\n}\n\nbool MailRecord::get_flag_draft()\n{\n\treturn flag_draft;\n}\n\nvoid MailRecord::set_flag_draft(bool flag_draft)\n{\n\tif (this->flag_draft == flag_draft)\n\t\treturn;\n\t\t\n\tthis->flag_draft = flag_draft;\n}\n\nbool MailRecord::get_flag_flagged()\n{\n\treturn flag_flagged;\n}\n\nvoid MailRecord::set_flag_flagged(bool flag_flagged)\n{\n\tif (this->flag_flagged == flag_flagged)\n\t\treturn;\n\t\n\tthis->flag_flagged = flag_flagged;\n}\n\nbool MailRecord::get_flag_passed()\n{\n\treturn flag_passed;\n}\n\nvoid MailRecord::set_flag_passed(bool flag_passed)\n{\n\tif (this->flag_passed == flag_passed)\n\t\treturn;\n\n\tthis->flag_passed = flag_passed;\n}\n\nbool MailRecord::get_flag_replied()\n{\n\treturn flag_replied;\n}\n\nvoid MailRecord::set_flag_replied(bool flag_replied)\n{\n\tif (this->flag_replied == flag_replied)\n\t\treturn;\n\n\tthis->flag_replied = flag_replied;\n}\n\nbool MailRecord::get_flag_seen()\n{\n\treturn flag_seen;\n}\n\nvoid MailRecord::set_flag_seen(bool flag_seen)\n{\n\tif (this->flag_seen == flag_seen)\n\t\treturn;\n\tLog::info << \"Seen\";\n\tthis->flag_seen = flag_seen;\n}\n\nbool MailRecord::get_flag_trashed()\n{\n\treturn flag_trashed;\n}\n\nvoid MailRecord::set_flag_trashed(bool flag_trashed)\n{\n\tif (this->flag_trashed == flag_trashed)\n\t\treturn;\n\t\n\tthis->flag_trashed = flag_trashed;\n}\n\nvoid MailRecord::save_content(string body)\n{\n\tofstream mfile;\t\n\n\tmfile.open(mainlink->get_path().c_str());\n\t\n\tif (mfile.is_open())\n\t{\n\t\tmfile << body;\n\t\tmfile.close();\n\t}\n\telse Log::error << \"Unable to open file \" << mainlink->get_path() << Log::endl;\n}\n\nMailLink* MailRecord::add_to_mailbox(MailBox* mailbox, unsigned long uid, string path)\n{\n\tMailLink* maillink = find_link(mailbox);\n\t\n\tif (maillink != NULL)\t\t\t\/\/ Existing mail: just update UID\n\t{\n\t\tmaillink->uid = uid;\n\t\t\n\t\tif (!path.empty())\n\t\t{\n\t\t\tif (!rename(maillink->get_path().c_str(), path.c_str()))\n\t\t\t\tperror(\"MailRecord::add_to_mailbox: unable to move link\");\n\t\t\telse\n\t\t\t\tmaillink->set_path(path);\n\t\t}\t\t\n\t}\n\telse\n\t{\t\t\n\t\tmaillink = new MailLink;\n\t\t\n\t\tif (mailbox->primary)\n\t\t\tmainlink = maillink;\n\t\t\t\n\t\tbool exists = false;\n\t\tif (path.empty())\n\t\t\tpath = mailbox->get_path() + \"cur\/\" + generate_md_filename() + get_md_info();\n\t\telse\n\t\t\texists = true;\n\t\t\t\n\t\t\t\n\t\t\n\t\tmaillink->mailrecord = this;\n\t\tmaillink->mailbox = mailbox;\n\t\tmaillink->set_path(path);\n\t\tmaillink->uid = uid;\n\t\t\n\t\tthis->links.push_back(maillink);\n\t\tmailbox->mails.push_back(maillink);\n\t\t\n\t\tif (!exists)\n\t\t{\n\t\t\tif (this->links.size() > 1)\t\/\/ Create a link to the original\n\t\t\t{\n\t\t\t\tstring sourcepath = this->mainlink->get_path().c_str();\n\t\t\t\t\/\/sourcepath.insert(0, \"..\/\");\n\t\t\t\n\t\t\t\tbf::create_hard_link(sourcepath, path);\n\t\t\t\t\/\/\tperror(\"MailRecord::add_to_mailbox: creating symlink failed\");\n\t\t\t}\n\t\t\telse\t\t\t\/\/ \"Touch\" file\n\t\t\t{\n\t\t\t\tofstream mfile;\n\t\t\t\tmfile.open(path.c_str());\n\t\t\t\tmfile << \"\";\n\t\t\t\tmfile.close();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tload_md_info();\n\t\t}\n\t}\n\t\t\t\n\t\n\treturn maillink;\n}\n\nvoid MailRecord::remove_from_mailbox(MailBox* mailbox)\n{\n\tvector<MailLink*>::iterator iter = find_ilink(mailbox);\n\t\n\tif (iter < this->links.end())\n\t{\n\t\tremove_from_mailbox(iter);\n\t\treturn;\t\t\n\t}\n\telse\n\t{\n\t\tcout << \"Whoops, something went wrong here\" << endl;\n\t}\n}\n\nvector<MailLink*>::iterator MailRecord::remove_from_mailbox(vector<MailLink*>::iterator iter)\n{\n\tif (unlink((*iter)->get_path().c_str()) != 0)\n\t\t\tperror(\"MailRecord::remove_from_mailbox: unable to unlink file\");\n\t\t\t\n\t(*iter)->mailbox->dirty();\n\t(*iter)->stale();\n\t\n\treturn this->links.erase(iter);\n}\n\t\n\nvoid MailRecord::remove()\n{\n\tfor (vector<MailLink*>::iterator iter = this->links.begin(); iter < this->links.end(); )\n\t{\n\t\titer = this->remove_from_mailbox(iter);\n\t}\n}\n\nMailLink* MailRecord::find_link(MailBox* mailbox)\n{\n\tvector<MailLink*>::iterator result = find_ilink(mailbox);\n\t\n\tif (result == this->links.end())\n\t\treturn NULL;\n\telse\n\t\treturn *result;\n}\n\nvector<MailLink*>::iterator MailRecord::find_ilink(MailBox* mailbox)\n{\n\tfor (vector<MailLink*>::iterator iter = this->links.begin(); iter < this->links.end(); iter++)\n\t{\n\t\tif ((*iter)->mailbox == mailbox)\n\t\t{\n\t\t\treturn iter;\n\t\t}\n\t}\n\t\n\treturn this->links.end();\n}\n\n\n\n\/**\n * Regenerates the paths of every mail, moves the files\n * of the mails, also of every link. This is useful if one of the\n * files has a different info part because another client changed\n * the flags.\n *\/\nvoid MailRecord::sync_flags()\n{\t\n\tfor (vector<MailLink*>::iterator iter = this->links.begin(); iter < links.end(); iter++)\n\t{\n\t\tstring new_path = (*iter)->get_base_path();\n\n\t\t\n\t\tnew_path.insert(new_path.size(), this->get_md_info());\n\t\t\n\t\tif (new_path.compare((*iter)->get_path()) != 0)\n\t\t{\n\t\t\tif (rename((*iter)->get_path().c_str(), new_path.c_str()) != 0)\n\t\t\t\tperror(\"MailRecord::flags_changed: Unable to rename file\");\n\t\t\telse\n\t\t\t\t(*iter)->set_path(new_path);\n\t\t}\t\t\t\t\n\t}\n}\n\n\nstring MailRecord::generate_md_filename()\n{\n\tchar seconds[20];\tsprintf(seconds, \"%lu\", (unsigned long) time(NULL));\n\n\tchar hostname[99] = \"hostnamex\";\n\tstring shostname;\n\tpid_t pid = getpid();\n\t\n\tif (pid < 0)\n\t\tperror(\"MailRecord::generate_md_filename: unable to get pid\");\n\t\n\tchar spid[20];\tsprintf(spid, \"%d\", pid);\n\t \n\tif (gethostname(hostname, 99) != 0)\n\t{\n\t\tperror(\"MailRecord::generate_md_filename: unable to gethostname()\");\n\t\tperror(hostname);\n\t}\n\t\n \tshostname = hostname;\n\t\n\t\/\/ Replace \"\/\" with \"\\057\"\n\tsize_t index;\n\twhile((index = shostname.find(\"\/\")) != string::npos)\n\t{\n\t\t\tshostname.replace(index, 1, \"\\057\");\n\t}\n\n\t\/\/ Replace \":\" with \"\\072\"\n\twhile((index = shostname.find(\":\")) != string::npos)\n\t{\n\t\t\tshostname.replace(index, 1, \"\\072\");\n\t}\n\t\n\tchar delnum[20];\tsprintf(delnum, \"%d\", MailRecord::number_of_deliveries++);\n\t\n\tstring result;\n\t\n\tresult += seconds;\n\tresult += \".\";\n\tresult += \"P\";\n\tresult += spid;\n\tresult += \"Q\";\n\tresult += delnum;\n\tresult += \".\";\n\tresult += shostname;\n\t\n\treturn result;\t\n}\n\n\/**\n * Generate the \"info\" part of the maildir specification\n * see: http:\/\/cr.yp.to\/proto\/maildir.html\n *\/\nstring MailRecord::get_md_info()\n{\n\tstring result = MD_TAIL;\n\t\n\tif (this->flag_draft) result += \"D\";\n\tif (this->flag_flagged) result += \"F\";\n\tif (this->flag_passed) result += \"P\";\n\tif (this->flag_replied) result += \"R\";\n\tif (this->flag_seen) result += \"S\";\n\tif (this->flag_trashed) result += \"T\";\n\t\n\treturn result;\n}\n\n\/**\n * Extract the \"info\" part from the path and update lfags\n *\/\nvoid MailRecord::load_md_info()\n{\n\tthis->flag_draft = false;\n\tthis->flag_flagged = false;\n\tthis->flag_passed = false;\n\tthis->flag_replied = false;\n\tthis->flag_seen = false;\n\tthis->flag_trashed = false;\n\t\n\tstring path = mainlink->get_path();\t\n\tfor(size_t index = path.rfind(MD_TAIL) + strlen(MD_TAIL); index < path.size(); index++)\n\t{\n\t\t\t\tswitch(path[index])\n\t\t\t\t{\n\t\t\t\t\tcase 'D':\n\t\t\t\t\t\tthis->flag_draft = true; break;\n\t\t\t\t\tcase 'F':\n\t\t\t\t\t\tthis->flag_flagged = true; break;\n\t\t\t\t\tcase 'P':\n\t\t\t\t\t\tthis->flag_passed = true; break;\n\t\t\t\t\tcase 'R':\n\t\t\t\t\t\tthis->flag_replied = true; break;\n\t\t\t\t\tcase 'S':\n\t\t\t\t\t\tthis->flag_seen = true; break;\n\t\t\t\t\tcase 'T':\n\t\t\t\t\t\tthis->flag_trashed = true; break;\n\t\t\t\t}\t\t\t\t\n\t}\n}<commit_msg>Removed a stray debug-message.<commit_after>\/*\n * Copyright (c) 2009 David Verhasselt <david@crowdway.com>\n * Licensed under The MIT License - http:\/\/gmailcc.crowdway.com\/license.txt\n *\/\n\n#include \"MailRecord.h\"\n\n#include <boost\/filesystem.hpp>\nnamespace bf = boost::filesystem;\n\n#include \"LogSink.h\"\n#include \"MailLink.h\"\n#include \"MailBox.h\"\n\nint MailRecord::number_of_deliveries = 0;\n\nMailRecord::MailRecord()\n{\n\tmarked = false;\n\t\n\tflag_draft = false;\n\tflag_flagged = false;\n\tflag_passed = false;\n\tflag_replied = false;\n\tflag_seen = false;\n\tflag_trashed = false;\n}\n\nMailRecord::~MailRecord()\n{\n\tfor (vector<MailLink*>::iterator iter = this->links.begin(); iter < links.end(); iter++)\n\t{\n\t\tdelete(*iter);\n\t}\t\n}\n\nvoid MailRecord::mark()\n{\n\tmarked = true;\n}\n\nbool MailRecord::get_flag_draft()\n{\n\treturn flag_draft;\n}\n\nvoid MailRecord::set_flag_draft(bool flag_draft)\n{\n\tif (this->flag_draft == flag_draft)\n\t\treturn;\n\t\t\n\tthis->flag_draft = flag_draft;\n}\n\nbool MailRecord::get_flag_flagged()\n{\n\treturn flag_flagged;\n}\n\nvoid MailRecord::set_flag_flagged(bool flag_flagged)\n{\n\tif (this->flag_flagged == flag_flagged)\n\t\treturn;\n\t\n\tthis->flag_flagged = flag_flagged;\n}\n\nbool MailRecord::get_flag_passed()\n{\n\treturn flag_passed;\n}\n\nvoid MailRecord::set_flag_passed(bool flag_passed)\n{\n\tif (this->flag_passed == flag_passed)\n\t\treturn;\n\n\tthis->flag_passed = flag_passed;\n}\n\nbool MailRecord::get_flag_replied()\n{\n\treturn flag_replied;\n}\n\nvoid MailRecord::set_flag_replied(bool flag_replied)\n{\n\tif (this->flag_replied == flag_replied)\n\t\treturn;\n\n\tthis->flag_replied = flag_replied;\n}\n\nbool MailRecord::get_flag_seen()\n{\n\treturn flag_seen;\n}\n\nvoid MailRecord::set_flag_seen(bool flag_seen)\n{\n\tif (this->flag_seen == flag_seen)\n\t\treturn;\n\t\t\n\tthis->flag_seen = flag_seen;\n}\n\nbool MailRecord::get_flag_trashed()\n{\n\treturn flag_trashed;\n}\n\nvoid MailRecord::set_flag_trashed(bool flag_trashed)\n{\n\tif (this->flag_trashed == flag_trashed)\n\t\treturn;\n\t\n\tthis->flag_trashed = flag_trashed;\n}\n\nvoid MailRecord::save_content(string body)\n{\n\tofstream mfile;\t\n\n\tmfile.open(mainlink->get_path().c_str());\n\t\n\tif (mfile.is_open())\n\t{\n\t\tmfile << body;\n\t\tmfile.close();\n\t}\n\telse Log::error << \"Unable to open file \" << mainlink->get_path() << Log::endl;\n}\n\nMailLink* MailRecord::add_to_mailbox(MailBox* mailbox, unsigned long uid, string path)\n{\n\tMailLink* maillink = find_link(mailbox);\n\t\n\tif (maillink != NULL)\t\t\t\/\/ Existing mail: just update UID\n\t{\n\t\tmaillink->uid = uid;\n\t\t\n\t\tif (!path.empty())\n\t\t{\n\t\t\tif (!rename(maillink->get_path().c_str(), path.c_str()))\n\t\t\t\tperror(\"MailRecord::add_to_mailbox: unable to move link\");\n\t\t\telse\n\t\t\t\tmaillink->set_path(path);\n\t\t}\t\t\n\t}\n\telse\n\t{\t\t\n\t\tmaillink = new MailLink;\n\t\t\n\t\tif (mailbox->primary)\n\t\t\tmainlink = maillink;\n\t\t\t\n\t\tbool exists = false;\n\t\tif (path.empty())\n\t\t\tpath = mailbox->get_path() + \"cur\/\" + generate_md_filename() + get_md_info();\n\t\telse\n\t\t\texists = true;\n\t\t\t\n\t\t\t\n\t\t\n\t\tmaillink->mailrecord = this;\n\t\tmaillink->mailbox = mailbox;\n\t\tmaillink->set_path(path);\n\t\tmaillink->uid = uid;\n\t\t\n\t\tthis->links.push_back(maillink);\n\t\tmailbox->mails.push_back(maillink);\n\t\t\n\t\tif (!exists)\n\t\t{\n\t\t\tif (this->links.size() > 1)\t\/\/ Create a link to the original\n\t\t\t{\n\t\t\t\tstring sourcepath = this->mainlink->get_path().c_str();\n\t\t\t\t\/\/sourcepath.insert(0, \"..\/\");\n\t\t\t\n\t\t\t\tbf::create_hard_link(sourcepath, path);\n\t\t\t\t\/\/\tperror(\"MailRecord::add_to_mailbox: creating symlink failed\");\n\t\t\t}\n\t\t\telse\t\t\t\/\/ \"Touch\" file\n\t\t\t{\n\t\t\t\tofstream mfile;\n\t\t\t\tmfile.open(path.c_str());\n\t\t\t\tmfile << \"\";\n\t\t\t\tmfile.close();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tload_md_info();\n\t\t}\n\t}\n\t\t\t\n\t\n\treturn maillink;\n}\n\nvoid MailRecord::remove_from_mailbox(MailBox* mailbox)\n{\n\tvector<MailLink*>::iterator iter = find_ilink(mailbox);\n\t\n\tif (iter < this->links.end())\n\t{\n\t\tremove_from_mailbox(iter);\n\t\treturn;\t\t\n\t}\n\telse\n\t{\n\t\tcout << \"Whoops, something went wrong here\" << endl;\n\t}\n}\n\nvector<MailLink*>::iterator MailRecord::remove_from_mailbox(vector<MailLink*>::iterator iter)\n{\n\tif (unlink((*iter)->get_path().c_str()) != 0)\n\t\t\tperror(\"MailRecord::remove_from_mailbox: unable to unlink file\");\n\t\t\t\n\t(*iter)->mailbox->dirty();\n\t(*iter)->stale();\n\t\n\treturn this->links.erase(iter);\n}\n\t\n\nvoid MailRecord::remove()\n{\n\tfor (vector<MailLink*>::iterator iter = this->links.begin(); iter < this->links.end(); )\n\t{\n\t\titer = this->remove_from_mailbox(iter);\n\t}\n}\n\nMailLink* MailRecord::find_link(MailBox* mailbox)\n{\n\tvector<MailLink*>::iterator result = find_ilink(mailbox);\n\t\n\tif (result == this->links.end())\n\t\treturn NULL;\n\telse\n\t\treturn *result;\n}\n\nvector<MailLink*>::iterator MailRecord::find_ilink(MailBox* mailbox)\n{\n\tfor (vector<MailLink*>::iterator iter = this->links.begin(); iter < this->links.end(); iter++)\n\t{\n\t\tif ((*iter)->mailbox == mailbox)\n\t\t{\n\t\t\treturn iter;\n\t\t}\n\t}\n\t\n\treturn this->links.end();\n}\n\n\n\n\/**\n * Regenerates the paths of every mail, moves the files\n * of the mails, also of every link. This is useful if one of the\n * files has a different info part because another client changed\n * the flags.\n *\/\nvoid MailRecord::sync_flags()\n{\t\n\tfor (vector<MailLink*>::iterator iter = this->links.begin(); iter < links.end(); iter++)\n\t{\n\t\tstring new_path = (*iter)->get_base_path();\n\n\t\t\n\t\tnew_path.insert(new_path.size(), this->get_md_info());\n\t\t\n\t\tif (new_path.compare((*iter)->get_path()) != 0)\n\t\t{\n\t\t\tif (rename((*iter)->get_path().c_str(), new_path.c_str()) != 0)\n\t\t\t\tperror(\"MailRecord::flags_changed: Unable to rename file\");\n\t\t\telse\n\t\t\t\t(*iter)->set_path(new_path);\n\t\t}\t\t\t\t\n\t}\n}\n\n\nstring MailRecord::generate_md_filename()\n{\n\tchar seconds[20];\tsprintf(seconds, \"%lu\", (unsigned long) time(NULL));\n\n\tchar hostname[99] = \"hostnamex\";\n\tstring shostname;\n\tpid_t pid = getpid();\n\t\n\tif (pid < 0)\n\t\tperror(\"MailRecord::generate_md_filename: unable to get pid\");\n\t\n\tchar spid[20];\tsprintf(spid, \"%d\", pid);\n\t \n\tif (gethostname(hostname, 99) != 0)\n\t{\n\t\tperror(\"MailRecord::generate_md_filename: unable to gethostname()\");\n\t\tperror(hostname);\n\t}\n\t\n \tshostname = hostname;\n\t\n\t\/\/ Replace \"\/\" with \"\\057\"\n\tsize_t index;\n\twhile((index = shostname.find(\"\/\")) != string::npos)\n\t{\n\t\t\tshostname.replace(index, 1, \"\\057\");\n\t}\n\n\t\/\/ Replace \":\" with \"\\072\"\n\twhile((index = shostname.find(\":\")) != string::npos)\n\t{\n\t\t\tshostname.replace(index, 1, \"\\072\");\n\t}\n\t\n\tchar delnum[20];\tsprintf(delnum, \"%d\", MailRecord::number_of_deliveries++);\n\t\n\tstring result;\n\t\n\tresult += seconds;\n\tresult += \".\";\n\tresult += \"P\";\n\tresult += spid;\n\tresult += \"Q\";\n\tresult += delnum;\n\tresult += \".\";\n\tresult += shostname;\n\t\n\treturn result;\t\n}\n\n\/**\n * Generate the \"info\" part of the maildir specification\n * see: http:\/\/cr.yp.to\/proto\/maildir.html\n *\/\nstring MailRecord::get_md_info()\n{\n\tstring result = MD_TAIL;\n\t\n\tif (this->flag_draft) result += \"D\";\n\tif (this->flag_flagged) result += \"F\";\n\tif (this->flag_passed) result += \"P\";\n\tif (this->flag_replied) result += \"R\";\n\tif (this->flag_seen) result += \"S\";\n\tif (this->flag_trashed) result += \"T\";\n\t\n\treturn result;\n}\n\n\/**\n * Extract the \"info\" part from the path and update lfags\n *\/\nvoid MailRecord::load_md_info()\n{\n\tthis->flag_draft = false;\n\tthis->flag_flagged = false;\n\tthis->flag_passed = false;\n\tthis->flag_replied = false;\n\tthis->flag_seen = false;\n\tthis->flag_trashed = false;\n\t\n\tstring path = mainlink->get_path();\t\n\tfor(size_t index = path.rfind(MD_TAIL) + strlen(MD_TAIL); index < path.size(); index++)\n\t{\n\t\t\t\tswitch(path[index])\n\t\t\t\t{\n\t\t\t\t\tcase 'D':\n\t\t\t\t\t\tthis->flag_draft = true; break;\n\t\t\t\t\tcase 'F':\n\t\t\t\t\t\tthis->flag_flagged = true; break;\n\t\t\t\t\tcase 'P':\n\t\t\t\t\t\tthis->flag_passed = true; break;\n\t\t\t\t\tcase 'R':\n\t\t\t\t\t\tthis->flag_replied = true; break;\n\t\t\t\t\tcase 'S':\n\t\t\t\t\t\tthis->flag_seen = true; break;\n\t\t\t\t\tcase 'T':\n\t\t\t\t\t\tthis->flag_trashed = true; break;\n\t\t\t\t}\t\t\t\t\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * @file MainWindow.h\n * @brief Main window for the Clusterer GUI\n *\/\n\n\/\/ standard headers\n#include <limits>\n\n\/\/ Own headers\n#include \"..\/include\/MainWindow.h\"\n#include \"..\/include\/SettingsDialog.h\"\n#include \"..\/include\/PopulationMember.hpp\"\n#include \"..\/include\/IntegerVectorEncoding.hpp\"\n\n\/\/ External headers\n#include <QMessageBox>\n#include <QFileDialog>\n\n\/\/ Generated headers\n#include \"ui_MainWindow.h\"\n#include \"..\/include\/GlobalBackendController.hpp\"\n#include \"..\/include\/GlobalFileLogger.hpp\"\n\n#define MSEC_60_HZ 16\n\n\nnamespace clusterer\n{\n\nnamespace frontend\n{\n\n\nMainWindow::MainWindow(QWidget* parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n connect(&timer, SIGNAL(timeout()), this, SLOT(updateFrontend()));\n\n setStateAlgoOff();\n \/\/ No graph loaded - cannot start\n ui->pushButton->setEnabled(false);\n ui->pushButton_3->setEnabled(false);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::setStateAlgoOn()\n{\n ui->pushButton->setEnabled(false);\n ui->pushButton_4->setEnabled(true);\n ui->pushButton_2->setEnabled(true);\n ui->pushButton_3->setEnabled(false);\n ui->actionZachary_format->setEnabled(false);\n ui->actionMovielens_format->setEnabled(false);\n ui->actionLoad_Population->setEnabled(false);\n ui->actionSave_Population->setEnabled(false);\n}\n\nvoid MainWindow::setStateAlgoOff()\n{\n ui->pushButton->setEnabled(true);\n ui->pushButton_4->setEnabled(false);\n ui->pushButton_2->setEnabled(false);\n ui->pushButton_3->setEnabled(false);\n ui->actionZachary_format->setEnabled(true);\n ui->actionMovielens_format->setEnabled(true);\n ui->actionLoad_Population->setEnabled(true);\n ui->actionSave_Population->setEnabled(true);\n}\n\nvoid MainWindow::updateFrontend()\n{\n std::pair<clb::PopulationMember<clb::IntegerVectorEncoding, double>, uint64_t> output;\n std::vector<std::pair<clb::PopulationMember<clb::IntegerVectorEncoding, double>, uint64_t>> vector;\n while (clb::GlobalBackendController::instance()->getOutQueue()->popNonWaiting(output))\n {\n vector.push_back(output);\n }\n\n if (!vector.empty())\n {\n bool exitFlag = false;\n std::vector<std::pair<uint64_t, double>> fitnessVec;\n fitnessVec.reserve(vector.size());\n for (auto& e : vector)\n {\n if (std::numeric_limits<uint64_t>::max() - std::numeric_limits<uint64_t>::epsilon() <= e.second)\n {\n \/\/ algo stopped\n setAlgorithmRunning(false);\n setStateAlgoOff();\n exitFlag = true;\n continue;\n }\n fitnessVec.push_back(std::make_pair(e.second, e.first.fitnessValue));\n }\n ui->fitnessPlotter->replotFitness(fitnessVec);\n\n if (exitFlag == true && vector.size() > 1)\n {\n ui->nodePlotter->replotSolution(vector[vector.size() - 2].first.populationEncoding);\n }\n else\n {\n ui->nodePlotter->replotSolution(vector[vector.size() - 1].first.populationEncoding);\n }\n }\n}\n\nvoid MainWindow::setAlgorithmRunning(bool val)\n{\n algorithmRunning = val;\n}\n\nbool MainWindow::isAlgorithmRunning()\n{\n return algorithmRunning;\n}\n\nvoid MainWindow::showAlert(const QString& title, const QString& text)\n{\n QMessageBox::information(this, title, text);\n}\n\nvoid MainWindow::on_pushButton_clicked()\n{\n \/\/Start button\n \/\/ @todo put check condition function into controller and call it here and check\n if (clb::GlobalBackendController::instance()->runAlgorithm(true))\n {\n clb::GlobalBackendController::instance()->runAlgorithm(true);\n timer.start(MSEC_60_HZ);\n this->showAlert(\"Info\", \"Started the algorithm\");\n setStateAlgoOn();\n setAlgorithmRunning(true);\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Could not start the algorithm as you need to load a Graph first.\");\n QMessageBox::critical(this, \"Error\", \"Could not start the algorithm as you need to load a Graph first.\");\n }\n}\n\nvoid MainWindow::on_pushButton_4_clicked()\n{\n \/\/Stop button\n clb::GlobalBackendController::instance()->stopAlgorithm();\n setStateAlgoOff();\n setAlgorithmRunning(true);\n this->showAlert(\"Alert\", \"Stopped the algorithm\");\n}\n\nvoid MainWindow::on_pushButton_2_clicked()\n{\n clb::GlobalBackendController::instance()->stopAlgorithm();\n setStateAlgoOff();\n setAlgorithmRunning(false);\n this->showAlert(\"Alert\", \"Paused algorithm\");\n ui->pushButton_3->setEnabled(true);\n ui->pushButton->setEnabled(true);\n}\n\nvoid MainWindow::on_pushButton_3_clicked()\n{\n clb::GlobalBackendController::instance()->runAlgorithm(false);\n this->showAlert(\"Alert\", \"Resumed execution of the algorithm\");\n setStateAlgoOn();\n setAlgorithmRunning(true);\n}\n\nvoid MainWindow::on_actionSave_Settings_2_triggered()\n{\n \/\/ Save settings\n QString path = QFileDialog::getSaveFileName(this,\n tr(\"Save Settings\"),\n tr(\".\"),\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->saveConfiguration(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Save Settings Success\", \"Successfully saved settings\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Save Settings failed. Failed saving settings.\");\n QMessageBox::critical(this, \"Save Settings failed\", \"Failed saving settings.\");\n }\n }\n}\n\nvoid MainWindow::on_actionLoad_Settings_2_triggered()\n{\n QString path = QFileDialog::getOpenFileName(this,\n tr(\"Open Settings File\"),\n \".\",\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->loadConfiguration(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Load Settings Success\", \"Successfully loaded settings\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Load Settings failed. The file you selected is not a valid configuration file\");\n QMessageBox::critical(this, \"Load Settings failed\", \"The file you selected is not a valid configuration file\");\n }\n }\n}\n\nvoid MainWindow::on_actionSave_Graph_triggered()\n{\n QString path = QFileDialog::getSaveFileName(this,\n tr(\"Save Graph\"),\n tr(\".\"),\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->saveGraphToFile(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Save Graph Success\", \"Successfully saved graph to file.\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Save Graph failed. Unable to save graph\");\n QMessageBox::critical(this, \"Save Graph failed\", \"Unable to save graph\");\n }\n }\n}\n\nvoid MainWindow::on_actionZachary_format_triggered()\n{\n \/\/ Load Zachary Format\n QString path = QFileDialog::getOpenFileName(this,\n tr(\"Open Zachary Karate Club Graph\"),\n \".\",\n tr(\"All Files (*)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->loadGraphTypeVertexPairWeight(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Load Graph Success\", \"Successfully loaded a vertex-pair-weight type graph.\");\n ui->nodePlotter->initGraph();\n ui->pushButton->setEnabled(true);\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Load Graph failed. Unable to load a vertex-pair-weight graph\");\n QMessageBox::critical(this, \"Load Graph failed\", \"Unable to load a vertex-pair-weight graph\");\n }\n }\n}\n\nvoid MainWindow::on_actionMovielens_format_triggered()\n{\n \/\/ Load Movielens Format\n QString path = QFileDialog::getOpenFileName(this,\n tr(\"Open Movielens Graph\"),\n \".\",\n tr(\"All Files (*)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->loadGraphTypeMovieLens(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Load Graph Success\", \"Successfully loaded a Movielens type graph.\");\n ui->nodePlotter->initGraph();\n ui->pushButton->setEnabled(true);\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Load Graph failed. Unable to load a Movielens graph\");\n QMessageBox::critical(this, \"Load Graph failed\", \"Unable to load a Movielens graph\");\n }\n }\n}\n\nvoid MainWindow::on_actionSave_Population_triggered()\n{\n \/\/ Save population\n QString path = QFileDialog::getSaveFileName(this,\n tr(\"Save Population\"),\n tr(\".\"),\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->savePopulation(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Save Population Success\", \"Successfully saved population to file.\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Save Population failed. Unable to save population\");\n QMessageBox::critical(this, \"Save Population failed\", \"Unable to save population\");\n }\n }\n}\n\nvoid MainWindow::on_actionLoad_Population_triggered()\n{\n \/\/ Load population\n QString path = QFileDialog::getOpenFileName(this,\n tr(\"Load Population\"),\n \".\",\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->loadPopulation(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Load Population Success\", \"Successfully loaded a population.\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Load Population failed. Unable to load a population out of this file.\");\n QMessageBox::critical(this, \"Load Population failed\", \"Unable to load a population out of this file.\");\n }\n }\n}\n\n\nvoid MainWindow::on_actionAbout_2_triggered()\n{\n QString info = \"Clustering Social Networks by using Genetic Algorithms\\n\\n\"\n \"Software Project for the Course Software Engineering Lab 2015 at Jacobs University Bremen.\\n\\n\"\n \"Authors: Denis Rochau, Dinesh Kannan, Annu Thapa, Valentin Vasiliu, Radu Homorozan, Kiril Kafadarov\";\n QMessageBox::about(this, \"About this project\", info);\n}\n\nvoid MainWindow::on_actionEdit_Settings_triggered()\n{\n SettingsDialog dialog(this);\n dialog.exec();\n}\n\n}\n}\n<commit_msg>Fixed merging conflicts, added some more button logic<commit_after>\/**\n * @file MainWindow.h\n * @brief Main window for the Clusterer GUI\n *\/\n\n\/\/ standard headers\n#include <limits>\n\n\/\/ Own headers\n#include \"..\/include\/MainWindow.h\"\n#include \"..\/include\/SettingsDialog.h\"\n#include \"..\/include\/PopulationMember.hpp\"\n#include \"..\/include\/IntegerVectorEncoding.hpp\"\n\n\/\/ External headers\n#include <QMessageBox>\n#include <QFileDialog>\n\n\/\/ Generated headers\n#include \"ui_MainWindow.h\"\n#include \"..\/include\/GlobalBackendController.hpp\"\n#include \"..\/include\/GlobalFileLogger.hpp\"\n\n#define MSEC_60_HZ 16\n\n\nnamespace clusterer\n{\n\nnamespace frontend\n{\n\n\nMainWindow::MainWindow(QWidget* parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n connect(&timer, SIGNAL(timeout()), this, SLOT(updateFrontend()));\n\n setStateAlgoOff();\n \/\/ No graph loaded - cannot start\n ui->pushButton->setEnabled(false);\n ui->pushButton_3->setEnabled(false);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::setStateAlgoOn()\n{\n ui->pushButton->setEnabled(false);\n ui->pushButton_4->setEnabled(true);\n ui->pushButton_2->setEnabled(true);\n ui->pushButton_3->setEnabled(false);\n ui->actionZachary_format->setEnabled(false);\n ui->actionMovielens_format->setEnabled(false);\n ui->actionLoad_Population->setEnabled(false);\n ui->actionSave_Population->setEnabled(false);\n}\n\nvoid MainWindow::setStateAlgoOff()\n{\n ui->pushButton->setEnabled(true);\n ui->pushButton_4->setEnabled(false);\n ui->pushButton_2->setEnabled(false);\n ui->pushButton_3->setEnabled(false);\n ui->actionZachary_format->setEnabled(true);\n ui->actionMovielens_format->setEnabled(true);\n ui->actionLoad_Population->setEnabled(true);\n ui->actionSave_Population->setEnabled(true);\n}\n\nvoid MainWindow::updateFrontend()\n{\n std::pair<clb::PopulationMember<clb::IntegerVectorEncoding, double>, uint64_t> output;\n std::vector<std::pair<clb::PopulationMember<clb::IntegerVectorEncoding, double>, uint64_t>> vector;\n while (clb::GlobalBackendController::instance()->getOutQueue()->popNonWaiting(output))\n {\n vector.push_back(output);\n }\n\n if (!vector.empty())\n {\n bool exitFlag = false;\n std::vector<std::pair<uint64_t, double>> fitnessVec;\n fitnessVec.reserve(vector.size());\n for (auto& e : vector)\n {\n if (std::numeric_limits<uint64_t>::max() - std::numeric_limits<uint64_t>::epsilon() <= e.second)\n {\n \/\/ algo stopped\n setAlgorithmRunning(false);\n setStateAlgoOff();\n timer.stop();\n exitFlag = true;\n continue;\n }\n fitnessVec.push_back(std::make_pair(e.second, e.first.fitnessValue));\n }\n ui->fitnessPlotter->replotFitness(fitnessVec);\n\n if (exitFlag == true && vector.size() > 1)\n {\n ui->nodePlotter->replotSolution(vector[vector.size() - 2].first.populationEncoding);\n }\n else\n {\n ui->nodePlotter->replotSolution(vector[vector.size() - 1].first.populationEncoding);\n }\n }\n}\n\nvoid MainWindow::setAlgorithmRunning(bool val)\n{\n algorithmRunning = val;\n}\n\nbool MainWindow::isAlgorithmRunning()\n{\n return algorithmRunning;\n}\n\nvoid MainWindow::showAlert(const QString& title, const QString& text)\n{\n QMessageBox::information(this, title, text);\n}\n\nvoid MainWindow::on_pushButton_clicked()\n{\n \/\/Start button\n \/\/ @todo put check condition function into controller and call it here and check\n if (clb::GlobalBackendController::instance()->runAlgorithm(true))\n {\n clb::GlobalBackendController::instance()->runAlgorithm(true);\n timer.start(MSEC_60_HZ);\n this->showAlert(\"Info\", \"Started the algorithm\");\n setStateAlgoOn();\n setAlgorithmRunning(true);\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Could not start the algorithm as you need to load a Graph first.\");\n QMessageBox::critical(this, \"Error\", \"Could not start the algorithm as you need to load a Graph first.\");\n }\n}\n\nvoid MainWindow::on_pushButton_4_clicked()\n{\n \/\/Stop button\n clb::GlobalBackendController::instance()->stopAlgorithm();\n this->showAlert(\"Alert\", \"Stopped the algorithm\");\n setStateAlgoOff();\n setAlgorithmRunning(true);\n timer.stop();\n}\n\nvoid MainWindow::on_pushButton_2_clicked()\n{\n clb::GlobalBackendController::instance()->stopAlgorithm();\n setStateAlgoOff();\n setAlgorithmRunning(false);\n this->showAlert(\"Alert\", \"Paused algorithm\");\n timer.stop();\n ui->pushButton_3->setEnabled(true);\n ui->pushButton->setEnabled(true);\n}\n\nvoid MainWindow::on_pushButton_3_clicked()\n{\n clb::GlobalBackendController::instance()->runAlgorithm(false);\n this->showAlert(\"Alert\", \"Resumed execution of the algorithm\");\n timer.start(MSEC_60_HZ);\n setStateAlgoOn();\n setAlgorithmRunning(true);\n}\n\nvoid MainWindow::on_actionSave_Settings_2_triggered()\n{\n \/\/ Save settings\n QString path = QFileDialog::getSaveFileName(this,\n tr(\"Save Settings\"),\n tr(\".\"),\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->saveConfiguration(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Save Settings Success\", \"Successfully saved settings\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Save Settings failed. Failed saving settings.\");\n QMessageBox::critical(this, \"Save Settings failed\", \"Failed saving settings.\");\n }\n }\n}\n\nvoid MainWindow::on_actionLoad_Settings_2_triggered()\n{\n QString path = QFileDialog::getOpenFileName(this,\n tr(\"Open Settings File\"),\n \".\",\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->loadConfiguration(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Load Settings Success\", \"Successfully loaded settings\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Load Settings failed. The file you selected is not a valid configuration file\");\n QMessageBox::critical(this, \"Load Settings failed\", \"The file you selected is not a valid configuration file\");\n }\n }\n}\n\nvoid MainWindow::on_actionSave_Graph_triggered()\n{\n QString path = QFileDialog::getSaveFileName(this,\n tr(\"Save Graph\"),\n tr(\".\"),\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->saveGraphToFile(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Save Graph Success\", \"Successfully saved graph to file.\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Save Graph failed. Unable to save graph\");\n QMessageBox::critical(this, \"Save Graph failed\", \"Unable to save graph\");\n }\n }\n}\n\nvoid MainWindow::on_actionZachary_format_triggered()\n{\n \/\/ Load Zachary Format\n QString path = QFileDialog::getOpenFileName(this,\n tr(\"Open Zachary Karate Club Graph\"),\n \".\",\n tr(\"All Files (*)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->loadGraphTypeVertexPairWeight(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Load Graph Success\", \"Successfully loaded a vertex-pair-weight type graph.\");\n ui->nodePlotter->initGraph();\n ui->pushButton->setEnabled(true);\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Load Graph failed. Unable to load a vertex-pair-weight graph\");\n QMessageBox::critical(this, \"Load Graph failed\", \"Unable to load a vertex-pair-weight graph\");\n }\n }\n}\n\nvoid MainWindow::on_actionMovielens_format_triggered()\n{\n \/\/ Load Movielens Format\n QString path = QFileDialog::getOpenFileName(this,\n tr(\"Open Movielens Graph\"),\n \".\",\n tr(\"All Files (*)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->loadGraphTypeMovieLens(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Load Graph Success\", \"Successfully loaded a Movielens type graph.\");\n ui->nodePlotter->initGraph();\n ui->pushButton->setEnabled(true);\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Load Graph failed. Unable to load a Movielens graph\");\n QMessageBox::critical(this, \"Load Graph failed\", \"Unable to load a Movielens graph\");\n }\n }\n}\n\nvoid MainWindow::on_actionSave_Population_triggered()\n{\n \/\/ Save population\n QString path = QFileDialog::getSaveFileName(this,\n tr(\"Save Population\"),\n tr(\".\"),\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->savePopulation(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Save Population Success\", \"Successfully saved population to file.\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Save Population failed. Unable to save population\");\n QMessageBox::critical(this, \"Save Population failed\", \"Unable to save population\");\n }\n }\n}\n\nvoid MainWindow::on_actionLoad_Population_triggered()\n{\n \/\/ Load population\n QString path = QFileDialog::getOpenFileName(this,\n tr(\"Load Population\"),\n \".\",\n tr(\"Text Files (*.txt)\"));\n if (!path.isNull() && !path.isEmpty())\n {\n bool result = clb::GlobalBackendController::instance()->loadPopulation(path.toLocal8Bit().constData());\n if (result == true)\n {\n showAlert(\"Load Population Success\", \"Successfully loaded a population.\");\n }\n else\n {\n clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, \"Load Population failed. Unable to load a population out of this file.\");\n QMessageBox::critical(this, \"Load Population failed\", \"Unable to load a population out of this file.\");\n }\n }\n}\n\n\nvoid MainWindow::on_actionAbout_2_triggered()\n{\n QString info = \"Clustering Social Networks by using Genetic Algorithms\\n\\n\"\n \"Software Project for the Course Software Engineering Lab 2015 at Jacobs University Bremen.\\n\\n\"\n \"Authors: Denis Rochau, Dinesh Kannan, Annu Thapa, Valentin Vasiliu, Radu Homorozan, Kiril Kafadarov\";\n QMessageBox::about(this, \"About this project\", info);\n}\n\nvoid MainWindow::on_actionEdit_Settings_triggered()\n{\n SettingsDialog dialog(this);\n dialog.exec();\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * main.cpp: ActiveX control for VLC\n *****************************************************************************\n * Copyright (C) 2005 the VideoLAN team\n *\n * Authors: Damien Fouilleul <Damien.Fouilleul@laposte.net>\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; 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"plugin.h\"\n#include \"utils.h\"\n\n#include <stdio.h>\n\n#include <comcat.h>\n#include <windows.h>\n#include <shlwapi.h>\n\n#include <tchar.h>\n\n#include <_mingw.h>\n\n#ifdef __MINGW64_VERSION_MAJOR\n\n#include <guiddef.h>\n#include <objsafe.h>\n\n#else \/* ! __MINGW64_VERSION_MAJOR *\/\n\n\/*\n** Widl generated code requires guiddef.h,\n** which is not available under MinGW32\n*\/\n#undef GUID_EXT\n#define GUID_EXT\n#include <initguid.h>\n\n\/*\n** Mingw32 do not declare those\n*\/\nstatic DEFINE_GUID(CATID_SafeForInitializing, \\\n\t0x7DD95802, 0x9882, 0x11CF, 0x9F, 0xA9, 0x00,0xAA,0x00,0x6C,0x42,0xC4);\nstatic DEFINE_GUID(CATID_SafeForScripting, \\\n\t0x7DD95801, 0x9882, 0x11CF, 0x9F, 0xA9, 0x00,0xAA,0x00,0x6C,0x42,0xC4);\n\n#endif \/* __MINGW64_VERSION_MAJOR *\/\n\n\nusing namespace std;\n\n#define COMPANY_STR \"VideoLAN\"\n#define PROGRAM_STR \"VLCPlugin\"\n#define DESCRIPTION \"VLC ActiveX Plugin and IE Web Plugin\"\n\n#define THREADING_MODEL \"Apartment\"\n#define MISC_STATUS \"131473\"\n\n#define PROGID_STR COMPANY_STR\".\"PROGRAM_STR\n\n#define GUID_STRLEN 39\n\nstatic LONG i_class_ref= 0;\nstatic HINSTANCE h_instance= 0;\n\nHMODULE DllGetModule()\n{\n return h_instance;\n};\n\nSTDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)\n{\n HRESULT hr = CLASS_E_CLASSNOTAVAILABLE;\n\n *ppv = NULL;\n\n if( (CLSID_VLCPlugin == rclsid) || (CLSID_VLCPlugin2 == rclsid) )\n {\n VLCPluginClass *plugin =\n new VLCPluginClass(&i_class_ref, h_instance, rclsid);\n hr = plugin->QueryInterface(riid, ppv);\n plugin->Release();\n }\n return hr;\n};\n\nSTDAPI DllCanUnloadNow(VOID)\n{\n return (0 == i_class_ref) ? S_OK: S_FALSE;\n};\n\nstatic inline HKEY keyCreate(HKEY parentKey, LPCTSTR keyName)\n{\n HKEY childKey;\n if( ERROR_SUCCESS == RegCreateKeyEx(parentKey, keyName, 0, NULL,\n REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &childKey, NULL) )\n {\n return childKey;\n }\n return NULL;\n};\n\nstatic inline HKEY keySet(HKEY hKey, LPCTSTR valueName,\n const void *s, size_t len, DWORD dwType = REG_SZ)\n{\n if( NULL != hKey )\n {\n RegSetValueEx(hKey, valueName, 0, dwType, (const BYTE*)s, len);\n }\n return hKey;\n};\n\nstatic inline HKEY keySetDef(HKEY hKey,\n const void *s, size_t len, DWORD dwType = REG_SZ)\n{\n return keySet(hKey, NULL, s, len, dwType);\n};\n\nstatic inline HKEY keySetDef(HKEY hKey, LPCTSTR s)\n{\n return keySetDef(hKey, s, sizeof(TCHAR)*(_tcslen(s)+1), REG_SZ);\n};\n\nstatic inline HKEY keyClose(HKEY hKey)\n{\n if( NULL != hKey )\n {\n RegCloseKey(hKey);\n }\n return NULL;\n};\n\nstatic void UnregisterProgID(REFCLSID rclsid, unsigned int version)\n{\n OLECHAR szCLSID[GUID_STRLEN];\n\n StringFromGUID2(rclsid, szCLSID, GUID_STRLEN);\n\n TCHAR progId[sizeof(PROGID_STR)+16];\n _stprintf(progId, TEXT(\"%s.%u\"), TEXT(PROGID_STR), version);\n\n SHDeleteKey(HKEY_CLASSES_ROOT, progId);\n\n HKEY hClsIDKey;\n if( ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT(\"CLSID\"), 0, KEY_WRITE, &hClsIDKey) )\n {\n SHDeleteKey(hClsIDKey, szCLSID);\n RegCloseKey(hClsIDKey);\n }\n};\n\nSTDAPI DllUnregisterServer(VOID)\n{\n \/\/ unregister type lib from the registry\n UnRegisterTypeLib(LIBID_AXVLC, 1, 0, LOCALE_NEUTRAL, SYS_WIN32);\n\n \/\/ remove component categories we supports\n ICatRegister *pcr;\n if( SUCCEEDED(CoCreateInstance(CLSID_StdComponentCategoriesMgr,\n NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr)) ) {\n CATID implCategories[] = {\n CATID_Control,\n CATID_PersistsToPropertyBag,\n CATID_InternetAware,\n CATID_SafeForInitializing,\n CATID_SafeForScripting,\n };\n\n pcr->UnRegisterClassImplCategories(CLSID_VLCPlugin,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->UnRegisterClassImplCategories(CLSID_VLCPlugin2,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->Release();\n }\n\n SHDeleteKey(HKEY_CLASSES_ROOT, TEXT(PROGID_STR));\n\n UnregisterProgID(CLSID_VLCPlugin, 2);\n UnregisterProgID(CLSID_VLCPlugin2, 1);\n\n return S_OK;\n};\n\nstatic HRESULT RegisterClassID(HKEY hParent, REFCLSID rclsid, unsigned int version, BOOL isDefault, LPCTSTR path, size_t pathLen)\n{\n TCHAR progId[sizeof(PROGID_STR)+16];\n _stprintf(progId, TEXT(\"%s.%u\"), TEXT(PROGID_STR), version);\n\n TCHAR description[sizeof(DESCRIPTION)+16];\n _stprintf(description, TEXT(\"%s v%u\"), TEXT(DESCRIPTION), version);\n\n HKEY hClassKey;\n {\n OLECHAR szCLSID[GUID_STRLEN];\n\n StringFromGUID2(rclsid, szCLSID, GUID_STRLEN);\n\n HKEY hProgKey = keyCreate(HKEY_CLASSES_ROOT, progId);\n if( NULL != hProgKey )\n {\n \/\/ default key value\n keySetDef(hProgKey, description);\n\n keyClose(keySetDef(keyCreate(hProgKey, TEXT(\"CLSID\")),\n szCLSID, sizeof(szCLSID)));\n\n \/\/hSubKey = keyClose(keyCreate(hBaseKey, \"Insertable\"));\n \n RegCloseKey(hProgKey);\n }\n if( isDefault )\n {\n hProgKey = keyCreate(HKEY_CLASSES_ROOT, TEXT(PROGID_STR));\n if( NULL != hProgKey )\n {\n \/\/ default key value\n keySetDef(hProgKey, description);\n\n keyClose(keySetDef(keyCreate(hProgKey, TEXT(\"CLSID\")),\n szCLSID, sizeof(szCLSID)));\n\n keyClose(keySetDef(keyCreate(hProgKey, TEXT(\"CurVer\")),\n progId));\n }\n }\n hClassKey = keyCreate(hParent, szCLSID);\n }\n if( NULL != hClassKey )\n {\n \/\/ default key value\n keySetDef(hClassKey, description);\n\n \/\/ Control key value\n keyClose(keyCreate(hClassKey, TEXT(\"Control\")));\n\n \/\/ Insertable key value\n \/\/keyClose(keyCreate(hClassKey, TEXT(\"Insertable\")));\n\n \/\/ ToolboxBitmap32 key value\n {\n TCHAR iconPath[pathLen+3];\n memcpy(iconPath, path, sizeof(TCHAR)*pathLen);\n _tcscpy(iconPath+pathLen, TEXT(\",1\"));\n keyClose(keySetDef(keyCreate(hClassKey,\n TEXT(\"ToolboxBitmap32\")),\n iconPath, sizeof(iconPath)));\n }\n\n#ifdef BUILD_LOCALSERVER\n \/\/ LocalServer32 key value\n keyClose(keySetDef(keyCreate(hClassKey,\n TEXT(\"LocalServer32\"), path, sizeof(TCHAR)*(pathLen+1))));\n#else\n \/\/ InprocServer32 key value\n {\n HKEY hSubKey = keySetDef(keyCreate(hClassKey,\n TEXT(\"InprocServer32\")),\n path, sizeof(TCHAR)*(pathLen+1));\n keySet(hSubKey,\n TEXT(\"ThreadingModel\"),\n TEXT(THREADING_MODEL), sizeof(TEXT(THREADING_MODEL)));\n keyClose(hSubKey);\n }\n#endif\n\n \/\/ MiscStatus key value\n keyClose(keySetDef(keyCreate(hClassKey,TEXT(\"MiscStatus\\\\1\")),\n TEXT(MISC_STATUS), sizeof(TEXT(MISC_STATUS))));\n\n \/\/ Programmable key value\n keyClose(keyCreate(hClassKey, TEXT(\"Programmable\")));\n\n \/\/ ProgID key value\n keyClose(keySetDef(keyCreate(hClassKey,TEXT(\"ProgID\")),progId));\n\n \/\/ VersionIndependentProgID key value\n keyClose(keySetDef(keyCreate(hClassKey,\n TEXT(\"VersionIndependentProgID\")),\n TEXT(PROGID_STR), sizeof(TEXT(PROGID_STR))));\n\n \/\/ Version key value\n keyClose(keySetDef(keyCreate(hClassKey,TEXT(\"Version\")),TEXT(\"1.0\")));\n\n \/\/ TypeLib key value\n OLECHAR szLIBID[GUID_STRLEN];\n\n StringFromGUID2(LIBID_AXVLC, szLIBID, GUID_STRLEN);\n\n keyClose(keySetDef(keyCreate(hClassKey,TEXT(\"TypeLib\")),\n szLIBID, sizeof(szLIBID)));\n \n RegCloseKey(hClassKey);\n }\n return S_OK;\n}\n\nSTDAPI DllRegisterServer(VOID)\n{\n DllUnregisterServer();\n\n TCHAR DllPath[MAX_PATH];\n DWORD DllPathLen=GetModuleFileName(h_instance, DllPath, MAX_PATH) ;\n if( 0 == DllPathLen )\n return E_UNEXPECTED;\n DllPath[MAX_PATH-1] = '\\0';\n\n HKEY hBaseKey;\n\n if( ERROR_SUCCESS != RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT(\"CLSID\"),\n 0, KEY_CREATE_SUB_KEY, &hBaseKey) )\n return SELFREG_E_CLASS;\n\n RegisterClassID(hBaseKey, CLSID_VLCPlugin, 1, FALSE, DllPath, DllPathLen);\n RegisterClassID(hBaseKey, CLSID_VLCPlugin2, 2, TRUE, DllPath, DllPathLen);\n\n RegCloseKey(hBaseKey);\n\n \/\/ indicate which component categories we support\n ICatRegister *pcr;\n if( SUCCEEDED(CoCreateInstance(CLSID_StdComponentCategoriesMgr,\n NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr)) ) {\n CATID implCategories[] = {\n CATID_Control,\n CATID_PersistsToPropertyBag,\n CATID_InternetAware,\n CATID_SafeForInitializing,\n CATID_SafeForScripting,\n };\n\n pcr->RegisterClassImplCategories(CLSID_VLCPlugin,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->RegisterClassImplCategories(CLSID_VLCPlugin2,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->Release();\n }\n\n#ifdef BUILD_LOCALSERVER\n \/\/ replace .exe by .tlb\n _tcscpy(DllPath+DllPathLen-4, TEXT(\".tlb\"));\n#endif\n\n \/\/ register type lib into the registry\n ITypeLib *typeLib;\n\n HRESULT result = LoadTypeLibEx(DllPath, REGKIND_REGISTER, &typeLib);\n if( SUCCEEDED(result) )\n typeLib->Release();\n\n return result;\n};\n\n#ifdef BUILD_LOCALSERVER\n\n\/*\n** easier to debug an application than a DLL on cygwin GDB :)\n*\/\n#include <iostream>\n\nSTDAPI_(int) WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw)\n{\n MSG msg;\n\n if( FAILED(OleInitialize(NULL)) )\n {\n cerr << \"cannot initialize OLE\" << endl;\n return 1;\n }\n\n h_instance = hInst;\n\n if( FAILED(DllRegisterServer()) )\n {\n cerr << \"cannot register Local Server\" << endl;\n return 1;\n }\n\n IUnknown *classProc = NULL;\n\n if( FAILED(DllGetClassObject(CLSID_VLCPlugin, IID_IUnknown,\n (LPVOID *)&classProc)) )\n return 0;\n \n DWORD dwRegisterClassObject;\n DWORD dwRegisterClassObject2;\n\n if( FAILED(CoRegisterClassObject(CLSID_VLCPlugin, classProc,\n CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &dwRegisterClassObject)) )\n return 0;\n\n DWORD dwRegisterActiveObject;\n\n if( FAILED(RegisterActiveObject(classProc, CLSID_VLCPlugin,\n ACTIVEOBJECT_WEAK, &dwRegisterActiveObject)) )\n return 0;\n\n if( FAILED(RegisterActiveObject(classProc, CLSID_VLCPlugin2,\n ACTIVEOBJECT_WEAK, &dwRegisterActiveObject2)) )\n return 0;\n\n classProc->Release();\n\n \/*\n * Polling messages from event queue\n *\/\n while( S_FALSE == DllCanUnloadNow() )\n {\n while( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )\n {\n if( msg.message == WM_QUIT )\n break; \/\/ break out PeekMessage loop\n\n \/*if(TranslateAccelerator(ghwndApp, ghAccel, &msg))\n continue;*\/\n\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n if(msg.message == WM_QUIT)\n break; \/\/ break out main loop\n\n WaitMessage();\n }\n\n if( SUCCEEDED(RevokeActiveObject(dwRegisterActiveObject, NULL)) )\n CoRevokeClassObject(dwRegisterClassObject);\n\n if( SUCCEEDED(RevokeActiveObject(dwRegisterActiveObject2, NULL)) )\n CoRevokeClassObject(dwRegisterClassObject2);\n\n \/\/ Reached on WM_QUIT message\n OleUninitialize();\n return ((int) msg.wParam);\n};\n\n#else\n\nSTDAPI_(BOOL) DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved )\n{\n switch( fdwReason )\n {\n case DLL_PROCESS_ATTACH:\n h_instance = (HINSTANCE)hModule;\n break;\n\n default:\n break;\n }\n return TRUE;\n};\n\n#endif\n\n<commit_msg>mingw32: fix CATID_InternetAware<commit_after>\/*****************************************************************************\n * main.cpp: ActiveX control for VLC\n *****************************************************************************\n * Copyright (C) 2005 the VideoLAN team\n *\n * Authors: Damien Fouilleul <Damien.Fouilleul@laposte.net>\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; 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. 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, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"plugin.h\"\n#include \"utils.h\"\n\n#include <stdio.h>\n\n#include <comcat.h>\n#include <windows.h>\n#include <shlwapi.h>\n\n#include <tchar.h>\n\n#include <_mingw.h>\n\n#ifdef __MINGW64_VERSION_MAJOR\n\n#include <guiddef.h>\n#include <objsafe.h>\n\n#else \/* ! __MINGW64_VERSION_MAJOR *\/\n\n\/*\n** Widl generated code requires guiddef.h,\n** which is not available under MinGW32\n*\/\n#undef GUID_EXT\n#define GUID_EXT\n#include <initguid.h>\n\n\/*\n** Mingw32 do not declare those\n*\/\n\/* CATID_InternetAware is declared as extern but not present in library *\/\nDEFINE_GUID(CATID_InternetAware, \\\n 0x0DE86A58, 0x2BAA, 0x11CF, 0xA2, 0x29, 0x00,0xAA,0x00,0x3D,0x73,0x52);\nstatic DEFINE_GUID(CATID_SafeForInitializing, \\\n\t0x7DD95802, 0x9882, 0x11CF, 0x9F, 0xA9, 0x00,0xAA,0x00,0x6C,0x42,0xC4);\nstatic DEFINE_GUID(CATID_SafeForScripting, \\\n\t0x7DD95801, 0x9882, 0x11CF, 0x9F, 0xA9, 0x00,0xAA,0x00,0x6C,0x42,0xC4);\n\n#endif \/* __MINGW64_VERSION_MAJOR *\/\n\n\nusing namespace std;\n\n#define COMPANY_STR \"VideoLAN\"\n#define PROGRAM_STR \"VLCPlugin\"\n#define DESCRIPTION \"VLC ActiveX Plugin and IE Web Plugin\"\n\n#define THREADING_MODEL \"Apartment\"\n#define MISC_STATUS \"131473\"\n\n#define PROGID_STR COMPANY_STR\".\"PROGRAM_STR\n\n#define GUID_STRLEN 39\n\nstatic LONG i_class_ref= 0;\nstatic HINSTANCE h_instance= 0;\n\nHMODULE DllGetModule()\n{\n return h_instance;\n};\n\nSTDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)\n{\n HRESULT hr = CLASS_E_CLASSNOTAVAILABLE;\n\n *ppv = NULL;\n\n if( (CLSID_VLCPlugin == rclsid) || (CLSID_VLCPlugin2 == rclsid) )\n {\n VLCPluginClass *plugin =\n new VLCPluginClass(&i_class_ref, h_instance, rclsid);\n hr = plugin->QueryInterface(riid, ppv);\n plugin->Release();\n }\n return hr;\n};\n\nSTDAPI DllCanUnloadNow(VOID)\n{\n return (0 == i_class_ref) ? S_OK: S_FALSE;\n};\n\nstatic inline HKEY keyCreate(HKEY parentKey, LPCTSTR keyName)\n{\n HKEY childKey;\n if( ERROR_SUCCESS == RegCreateKeyEx(parentKey, keyName, 0, NULL,\n REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &childKey, NULL) )\n {\n return childKey;\n }\n return NULL;\n};\n\nstatic inline HKEY keySet(HKEY hKey, LPCTSTR valueName,\n const void *s, size_t len, DWORD dwType = REG_SZ)\n{\n if( NULL != hKey )\n {\n RegSetValueEx(hKey, valueName, 0, dwType, (const BYTE*)s, len);\n }\n return hKey;\n};\n\nstatic inline HKEY keySetDef(HKEY hKey,\n const void *s, size_t len, DWORD dwType = REG_SZ)\n{\n return keySet(hKey, NULL, s, len, dwType);\n};\n\nstatic inline HKEY keySetDef(HKEY hKey, LPCTSTR s)\n{\n return keySetDef(hKey, s, sizeof(TCHAR)*(_tcslen(s)+1), REG_SZ);\n};\n\nstatic inline HKEY keyClose(HKEY hKey)\n{\n if( NULL != hKey )\n {\n RegCloseKey(hKey);\n }\n return NULL;\n};\n\nstatic void UnregisterProgID(REFCLSID rclsid, unsigned int version)\n{\n OLECHAR szCLSID[GUID_STRLEN];\n\n StringFromGUID2(rclsid, szCLSID, GUID_STRLEN);\n\n TCHAR progId[sizeof(PROGID_STR)+16];\n _stprintf(progId, TEXT(\"%s.%u\"), TEXT(PROGID_STR), version);\n\n SHDeleteKey(HKEY_CLASSES_ROOT, progId);\n\n HKEY hClsIDKey;\n if( ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT(\"CLSID\"), 0, KEY_WRITE, &hClsIDKey) )\n {\n SHDeleteKey(hClsIDKey, szCLSID);\n RegCloseKey(hClsIDKey);\n }\n};\n\nSTDAPI DllUnregisterServer(VOID)\n{\n \/\/ unregister type lib from the registry\n UnRegisterTypeLib(LIBID_AXVLC, 1, 0, LOCALE_NEUTRAL, SYS_WIN32);\n\n \/\/ remove component categories we supports\n ICatRegister *pcr;\n if( SUCCEEDED(CoCreateInstance(CLSID_StdComponentCategoriesMgr,\n NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr)) ) {\n CATID implCategories[] = {\n CATID_Control,\n CATID_PersistsToPropertyBag,\n CATID_InternetAware,\n CATID_SafeForInitializing,\n CATID_SafeForScripting,\n };\n\n pcr->UnRegisterClassImplCategories(CLSID_VLCPlugin,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->UnRegisterClassImplCategories(CLSID_VLCPlugin2,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->Release();\n }\n\n SHDeleteKey(HKEY_CLASSES_ROOT, TEXT(PROGID_STR));\n\n UnregisterProgID(CLSID_VLCPlugin, 2);\n UnregisterProgID(CLSID_VLCPlugin2, 1);\n\n return S_OK;\n};\n\nstatic HRESULT RegisterClassID(HKEY hParent, REFCLSID rclsid, unsigned int version, BOOL isDefault, LPCTSTR path, size_t pathLen)\n{\n TCHAR progId[sizeof(PROGID_STR)+16];\n _stprintf(progId, TEXT(\"%s.%u\"), TEXT(PROGID_STR), version);\n\n TCHAR description[sizeof(DESCRIPTION)+16];\n _stprintf(description, TEXT(\"%s v%u\"), TEXT(DESCRIPTION), version);\n\n HKEY hClassKey;\n {\n OLECHAR szCLSID[GUID_STRLEN];\n\n StringFromGUID2(rclsid, szCLSID, GUID_STRLEN);\n\n HKEY hProgKey = keyCreate(HKEY_CLASSES_ROOT, progId);\n if( NULL != hProgKey )\n {\n \/\/ default key value\n keySetDef(hProgKey, description);\n\n keyClose(keySetDef(keyCreate(hProgKey, TEXT(\"CLSID\")),\n szCLSID, sizeof(szCLSID)));\n\n \/\/hSubKey = keyClose(keyCreate(hBaseKey, \"Insertable\"));\n \n RegCloseKey(hProgKey);\n }\n if( isDefault )\n {\n hProgKey = keyCreate(HKEY_CLASSES_ROOT, TEXT(PROGID_STR));\n if( NULL != hProgKey )\n {\n \/\/ default key value\n keySetDef(hProgKey, description);\n\n keyClose(keySetDef(keyCreate(hProgKey, TEXT(\"CLSID\")),\n szCLSID, sizeof(szCLSID)));\n\n keyClose(keySetDef(keyCreate(hProgKey, TEXT(\"CurVer\")),\n progId));\n }\n }\n hClassKey = keyCreate(hParent, szCLSID);\n }\n if( NULL != hClassKey )\n {\n \/\/ default key value\n keySetDef(hClassKey, description);\n\n \/\/ Control key value\n keyClose(keyCreate(hClassKey, TEXT(\"Control\")));\n\n \/\/ Insertable key value\n \/\/keyClose(keyCreate(hClassKey, TEXT(\"Insertable\")));\n\n \/\/ ToolboxBitmap32 key value\n {\n TCHAR iconPath[pathLen+3];\n memcpy(iconPath, path, sizeof(TCHAR)*pathLen);\n _tcscpy(iconPath+pathLen, TEXT(\",1\"));\n keyClose(keySetDef(keyCreate(hClassKey,\n TEXT(\"ToolboxBitmap32\")),\n iconPath, sizeof(iconPath)));\n }\n\n#ifdef BUILD_LOCALSERVER\n \/\/ LocalServer32 key value\n keyClose(keySetDef(keyCreate(hClassKey,\n TEXT(\"LocalServer32\"), path, sizeof(TCHAR)*(pathLen+1))));\n#else\n \/\/ InprocServer32 key value\n {\n HKEY hSubKey = keySetDef(keyCreate(hClassKey,\n TEXT(\"InprocServer32\")),\n path, sizeof(TCHAR)*(pathLen+1));\n keySet(hSubKey,\n TEXT(\"ThreadingModel\"),\n TEXT(THREADING_MODEL), sizeof(TEXT(THREADING_MODEL)));\n keyClose(hSubKey);\n }\n#endif\n\n \/\/ MiscStatus key value\n keyClose(keySetDef(keyCreate(hClassKey,TEXT(\"MiscStatus\\\\1\")),\n TEXT(MISC_STATUS), sizeof(TEXT(MISC_STATUS))));\n\n \/\/ Programmable key value\n keyClose(keyCreate(hClassKey, TEXT(\"Programmable\")));\n\n \/\/ ProgID key value\n keyClose(keySetDef(keyCreate(hClassKey,TEXT(\"ProgID\")),progId));\n\n \/\/ VersionIndependentProgID key value\n keyClose(keySetDef(keyCreate(hClassKey,\n TEXT(\"VersionIndependentProgID\")),\n TEXT(PROGID_STR), sizeof(TEXT(PROGID_STR))));\n\n \/\/ Version key value\n keyClose(keySetDef(keyCreate(hClassKey,TEXT(\"Version\")),TEXT(\"1.0\")));\n\n \/\/ TypeLib key value\n OLECHAR szLIBID[GUID_STRLEN];\n\n StringFromGUID2(LIBID_AXVLC, szLIBID, GUID_STRLEN);\n\n keyClose(keySetDef(keyCreate(hClassKey,TEXT(\"TypeLib\")),\n szLIBID, sizeof(szLIBID)));\n \n RegCloseKey(hClassKey);\n }\n return S_OK;\n}\n\nSTDAPI DllRegisterServer(VOID)\n{\n DllUnregisterServer();\n\n TCHAR DllPath[MAX_PATH];\n DWORD DllPathLen=GetModuleFileName(h_instance, DllPath, MAX_PATH) ;\n if( 0 == DllPathLen )\n return E_UNEXPECTED;\n DllPath[MAX_PATH-1] = '\\0';\n\n HKEY hBaseKey;\n\n if( ERROR_SUCCESS != RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT(\"CLSID\"),\n 0, KEY_CREATE_SUB_KEY, &hBaseKey) )\n return SELFREG_E_CLASS;\n\n RegisterClassID(hBaseKey, CLSID_VLCPlugin, 1, FALSE, DllPath, DllPathLen);\n RegisterClassID(hBaseKey, CLSID_VLCPlugin2, 2, TRUE, DllPath, DllPathLen);\n\n RegCloseKey(hBaseKey);\n\n \/\/ indicate which component categories we support\n ICatRegister *pcr;\n if( SUCCEEDED(CoCreateInstance(CLSID_StdComponentCategoriesMgr,\n NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr)) ) {\n CATID implCategories[] = {\n CATID_Control,\n CATID_PersistsToPropertyBag,\n CATID_InternetAware,\n CATID_SafeForInitializing,\n CATID_SafeForScripting,\n };\n\n pcr->RegisterClassImplCategories(CLSID_VLCPlugin,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->RegisterClassImplCategories(CLSID_VLCPlugin2,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->Release();\n }\n\n#ifdef BUILD_LOCALSERVER\n \/\/ replace .exe by .tlb\n _tcscpy(DllPath+DllPathLen-4, TEXT(\".tlb\"));\n#endif\n\n \/\/ register type lib into the registry\n ITypeLib *typeLib;\n\n HRESULT result = LoadTypeLibEx(DllPath, REGKIND_REGISTER, &typeLib);\n if( SUCCEEDED(result) )\n typeLib->Release();\n\n return result;\n};\n\n#ifdef BUILD_LOCALSERVER\n\n\/*\n** easier to debug an application than a DLL on cygwin GDB :)\n*\/\n#include <iostream>\n\nSTDAPI_(int) WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw)\n{\n MSG msg;\n\n if( FAILED(OleInitialize(NULL)) )\n {\n cerr << \"cannot initialize OLE\" << endl;\n return 1;\n }\n\n h_instance = hInst;\n\n if( FAILED(DllRegisterServer()) )\n {\n cerr << \"cannot register Local Server\" << endl;\n return 1;\n }\n\n IUnknown *classProc = NULL;\n\n if( FAILED(DllGetClassObject(CLSID_VLCPlugin, IID_IUnknown,\n (LPVOID *)&classProc)) )\n return 0;\n \n DWORD dwRegisterClassObject;\n DWORD dwRegisterClassObject2;\n\n if( FAILED(CoRegisterClassObject(CLSID_VLCPlugin, classProc,\n CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &dwRegisterClassObject)) )\n return 0;\n\n DWORD dwRegisterActiveObject;\n\n if( FAILED(RegisterActiveObject(classProc, CLSID_VLCPlugin,\n ACTIVEOBJECT_WEAK, &dwRegisterActiveObject)) )\n return 0;\n\n if( FAILED(RegisterActiveObject(classProc, CLSID_VLCPlugin2,\n ACTIVEOBJECT_WEAK, &dwRegisterActiveObject2)) )\n return 0;\n\n classProc->Release();\n\n \/*\n * Polling messages from event queue\n *\/\n while( S_FALSE == DllCanUnloadNow() )\n {\n while( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )\n {\n if( msg.message == WM_QUIT )\n break; \/\/ break out PeekMessage loop\n\n \/*if(TranslateAccelerator(ghwndApp, ghAccel, &msg))\n continue;*\/\n\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n if(msg.message == WM_QUIT)\n break; \/\/ break out main loop\n\n WaitMessage();\n }\n\n if( SUCCEEDED(RevokeActiveObject(dwRegisterActiveObject, NULL)) )\n CoRevokeClassObject(dwRegisterClassObject);\n\n if( SUCCEEDED(RevokeActiveObject(dwRegisterActiveObject2, NULL)) )\n CoRevokeClassObject(dwRegisterClassObject2);\n\n \/\/ Reached on WM_QUIT message\n OleUninitialize();\n return ((int) msg.wParam);\n};\n\n#else\n\nSTDAPI_(BOOL) DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved )\n{\n switch( fdwReason )\n {\n case DLL_PROCESS_ATTACH:\n h_instance = (HINSTANCE)hModule;\n break;\n\n default:\n break;\n }\n return TRUE;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Properties.cpp\n *\n * Copyright 2002, Log4cpp Project. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"Properties.hh\"\n#include <cstdlib>\n#include \"StringUtil.hh\"\n\nnamespace log4cpp {\n \n Properties::Properties() {\n }\n\n Properties::~Properties() {\n }\n\n void Properties::load(std::istream& in) {\n clear();\n\n std::string fullLine, command;\n std::string leftSide, rightSide;\n char line[256];\n std::string::size_type length;\n bool partiallyRead(false);\t\/\/ fix for bug#137, for strings longer than 256 chars\n\n while (in) {\n \tif (in.getline(line, 256) || !in.bad()) {\n \t\t\/\/ either string is read fully or only partially (logical but not read\/write error)\n \t\tif (partiallyRead)\n \t\t\tfullLine.append(line);\n \t\telse\n \t\t\tfullLine = line;\n \t\tpartiallyRead = (in.fail() && !in.bad());\n \t\tif (partiallyRead && !in.eof()) {\n \t\t\tin.clear(in.rdstate() & ~std::ios::failbit);\n \t\t\tcontinue; \/\/ to get full line\n \t\t}\n \t} else {\n \t\t\tbreak;\n \t}\n \/* if the line contains a # then it is a comment\n if we find it anywhere other than the beginning, then we assume \n there is a command on that line, and it we don't find it at all\n we assume there is a command on the line (we test for valid \n command later) if neither is true, we continue with the next line\n *\/\n length = fullLine.find('#');\n if (length == std::string::npos) {\n command = fullLine;\n } else if (length > 0) {\n command = fullLine.substr(0, length);\n } else {\n continue;\n }\n\n \/\/ check the command and handle it\n length = command.find('=');\n if (length != std::string::npos) {\n leftSide = StringUtil::trim(command.substr(0, length));\n rightSide = StringUtil::trim(command.substr(length + 1, command.size() - length));\n _substituteVariables(rightSide);\n } else {\n continue;\n }\n\n \/* handle the command by determining what object the left side\n refers to and setting the value given on the right\n ASSUMPTIONS: \n 1. first object given on left side is \"log4j\" or \"log4cpp\"\n 2. all class names on right side are ignored because we\n probably cannot resolve them anyway.\n *\/\n\n \/\/ strip off the \"log4j\" or \"log4cpp\"\n length = leftSide.find('.');\n if (leftSide.substr(0, length) == \"log4j\" ||\n leftSide.substr(0, length) == \"log4cpp\")\n leftSide = leftSide.substr(length + 1);\n\n \/\/ add to the map of properties\n insert(value_type(leftSide, rightSide));\n }\n }\n\n void Properties::save(std::ostream& out) {\n for(const_iterator i = begin(); i != end(); ++i) {\n out << (*i).first << \"=\" << (*i).second << std::endl;\n }\n }\n \n int Properties::getInt(const std::string& property, int defaultValue) {\n const_iterator key = find(property);\n return (key == end()) ? defaultValue : std::atoi((*key).second.c_str());\n }\n\n bool Properties::getBool(const std::string& property, bool defaultValue) {\n const_iterator key = find(property);\n return (key == end()) ? defaultValue : ((*key).second == \"true\");\n }\n\n std::string Properties::getString(const std::string& property, \n const char* defaultValue) {\n const_iterator key = find(property);\n return (key == end()) ? std::string(defaultValue) : (*key).second;\n }\n\n void Properties::_substituteVariables(std::string& value) {\n std::string result;\n\n std::string::size_type left = 0;\n std::string::size_type right = value.find(\"${\", left);\n if (right == std::string::npos) {\n \/\/ bail out early for 99% of cases\n return;\n }\n\n while(true) {\n result += value.substr(left, right - left);\n if (right == std::string::npos) {\n break;\n }\n\n left = right + 2;\n right = value.find('}', left);\n if (right == std::string::npos) {\n \/\/ no close tag, use string literally\n result += value.substr(left - 2);\n break;\n } else {\n const std::string key = value.substr(left, right - left);\n if (key == \"${\") {\n result += \"${\";\n } else {\n char* value = std::getenv(key.c_str());\n if (value) {\n result += value;\n } else {\n const_iterator it = find(key);\n if (it == end()) {\n \/\/ not found assume empty;\n } else {\n result += (*it).second;\n }\n }\n }\n left = right + 1;\n }\n\n right = value.find(\"${\", left);\n }\n\n value = result;\n }\n}\n<commit_msg>small rename<commit_after>\/*\n * Properties.cpp\n *\n * Copyright 2002, Log4cpp Project. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"Properties.hh\"\n#include <cstdlib>\n#include \"StringUtil.hh\"\n\nnamespace log4cpp {\n \n Properties::Properties() {\n }\n\n Properties::~Properties() {\n }\n\n void Properties::load(std::istream& in) {\n clear();\n\n std::string fullLine, command;\n std::string leftSide, rightSide;\n char line[256];\n std::string::size_type length;\n bool partiallyRead(false);\t\/\/ fix for bug#137, for strings longer than 256 chars\n\n while (in) {\n \tif (in.getline(line, 256) || !in.bad()) {\n \t\t\/\/ either string is read fully or only partially (logical but not read\/write error)\n \t\tif (partiallyRead)\n \t\t\tfullLine.append(line);\n \t\telse\n \t\t\tfullLine = line;\n \t\tpartiallyRead = (in.fail() && !in.bad());\n \t\tif (partiallyRead && !in.eof()) {\n \t\t\tin.clear(in.rdstate() & ~std::ios::failbit);\n \t\t\tcontinue; \/\/ to get full line\n \t\t}\n \t} else {\n \t\t\tbreak;\n \t}\n \/* if the line contains a # then it is a comment\n if we find it anywhere other than the beginning, then we assume \n there is a command on that line, and it we don't find it at all\n we assume there is a command on the line (we test for valid \n command later) if neither is true, we continue with the next line\n *\/\n length = fullLine.find('#');\n if (length == std::string::npos) {\n command = fullLine;\n } else if (length > 0) {\n command = fullLine.substr(0, length);\n } else {\n continue;\n }\n\n \/\/ check the command and handle it\n length = command.find('=');\n if (length != std::string::npos) {\n leftSide = StringUtil::trim(command.substr(0, length));\n rightSide = StringUtil::trim(command.substr(length + 1, command.size() - length));\n _substituteVariables(rightSide);\n } else {\n continue;\n }\n\n \/* handle the command by determining what object the left side\n refers to and setting the value given on the right\n ASSUMPTIONS: \n 1. first object given on left side is \"log4j\" or \"log4cpp\"\n 2. all class names on right side are ignored because we\n probably cannot resolve them anyway.\n *\/\n\n \/\/ strip off the \"log4j\" or \"log4cpp\"\n length = leftSide.find('.');\n if (leftSide.substr(0, length) == \"log4j\" ||\n leftSide.substr(0, length) == \"log4cpp\")\n leftSide = leftSide.substr(length + 1);\n\n \/\/ add to the map of properties\n insert(value_type(leftSide, rightSide));\n }\n }\n\n void Properties::save(std::ostream& out) {\n for(const_iterator i = begin(); i != end(); ++i) {\n out << (*i).first << \"=\" << (*i).second << std::endl;\n }\n }\n \n int Properties::getInt(const std::string& property, int defaultValue) {\n const_iterator key = find(property);\n return (key == end()) ? defaultValue : std::atoi((*key).second.c_str());\n }\n\n bool Properties::getBool(const std::string& property, bool defaultValue) {\n const_iterator key = find(property);\n return (key == end()) ? defaultValue : ((*key).second == \"true\");\n }\n\n std::string Properties::getString(const std::string& property, \n const char* defaultValue) {\n const_iterator key = find(property);\n return (key == end()) ? std::string(defaultValue) : (*key).second;\n }\n\n void Properties::_substituteVariables(std::string& value) {\n std::string result;\n\n std::string::size_type left = 0;\n std::string::size_type right = value.find(\"${\", left);\n if (right == std::string::npos) {\n \/\/ bail out early for 99% of cases\n return;\n }\n\n while(true) {\n result += value.substr(left, right - left);\n if (right == std::string::npos) {\n break;\n }\n\n left = right + 2;\n right = value.find('}', left);\n if (right == std::string::npos) {\n \/\/ no close tag, use string literally\n result += value.substr(left - 2);\n break;\n } else {\n const std::string key = value.substr(left, right - left);\n if (key == \"${\") {\n result += \"${\";\n } else {\n char* env_value = std::getenv(key.c_str());\n if (env_value) {\n result += env_value;\n } else {\n const_iterator it = find(key);\n if (it == end()) {\n \/\/ not found assume empty;\n } else {\n result += (*it).second;\n }\n }\n }\n left = right + 1;\n }\n\n right = value.find(\"${\", left);\n }\n\n value = result;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Rasterizer.h\"\n#include <limits> \/\/numerics::max\n#include \"Utils.h\" \/\/\n#include <algorithm> \/\/ std::max\nRasterizer::Rasterizer()\n : Renderer() {\n\n}\n\nRasterizer::Rasterizer(World* world)\n : Renderer(world) {\n\n}\n\nRasterizer::~Rasterizer() {\n}\n\n\nvoid Rasterizer::render(const std::string output_path, const uint16_t image_width, const uint16_t image_height) {\n m_pixels = std::vector<RGBColor>(image_height * image_width, BACKGROUND_COLOR);\n m_depth_buffer = std::vector<double>(image_height * image_width, m_camera->get_far_plane());\n\n for (auto& object : m_world->m_objects) {\n const std::vector<Triangle3D> triangles = object->triangulate();\n for (auto& triangle_world : triangles) {\n const Triangle2D triangle_projected = this->project(triangle_world);\n const Triangle2D triangle_raster = this->rasterize(triangle_world);\n const BoundingBox2D bbox_raster = triangle_raster.bbox();\n for (int32_t pixel_raster_x = bbox_raster.min.x; pixel_raster_x <= bbox_raster.max.x; ++pixel_raster_x) {\n for (int32_t pixel_raster_y = bbox_raster.min.y; pixel_raster_y <= bbox_raster.max.y; ++pixel_raster_y) {\n const Point2D pixel_raster = { (double) pixel_raster_x, (double) pixel_raster_y };\n if (triangle_raster.contains(pixel_raster)) {\n const Point2D pixel_projected = this->unproject(pixel_raster);\n const double depth = getDepth(triangle_world, triangle_projected, pixel_projected);\n const Point3D pixel_view = m_camera->projectTransformInv(pixel_projected, depth);\n const Point3D pixel_world = pixel_view;\n \/\/ TODO: const Point3D pixel_world = m_camera->viewTransformInv(pixel_view);\n if (m_camera->insideFrustrum(pixel_raster, depth)) {\n const uint32_t i = pixel_raster_y * image_width + pixel_raster_x;\n if (depth < m_depth_buffer[i]) {\n m_depth_buffer[i] = depth;\n m_pixels[i] = shade(*object, triangle_world, pixel_world);\n }\n }\n }\n }\n }\n }\n }\n\n exportDepthBuffer(m_depth_buffer, \"depth.bmp\", image_width, image_height);\n exportImage(m_pixels, output_path, image_width, image_height);\n}\n\nconst double Rasterizer::getDepth(const Triangle3D& triangle_world, const Triangle2D& triangle_screen, const Point2D& pixel_screen) const {\n const Triangle3D triangle_camera = Triangle3D(\n m_camera->viewTransform(triangle_world.v1),\n m_camera->viewTransform(triangle_world.v2),\n m_camera->viewTransform(triangle_world.v3)\n );\n\n \/\/ Calculate barycentric coords in camera space\n double u, v, w;\n triangle_screen.calculateBarycentricCoords(u, v, w, pixel_screen);\n \/\/ Interpolate Z in 3D using inverse function and barycentric coordinates in 2D\n const float depth = 1 \/ ((1 \/ triangle_camera.v1.z) * u + (1 \/ triangle_camera.v2.z) * v + (1 \/ triangle_camera.v3.z) * w);\n return depth;\n\n}\n\nconst Point2D Rasterizer::rasterize(const Point3D& point_world) const {\n const Point3D point_camera = m_camera->viewTransform(point_world);\n const Point2D point_projected = m_camera->projectTransform(point_camera);\n const Point2D point_ndc = m_camera->ndcTransform(point_projected);\n const Point2D point_raster = m_camera->viewportTransform(point_ndc);\n return point_raster;\n}\n\nconst Triangle2D Rasterizer::rasterize(const Triangle3D& triangle_world) const {\n return Triangle2D(\n rasterize(triangle_world.v1),\n rasterize(triangle_world.v2),\n rasterize(triangle_world.v3)\n );\n}\n\nconst Triangle2D Rasterizer::project(const Triangle3D& triangle_world) const {\n return Triangle2D(\n project(triangle_world.v1),\n project(triangle_world.v2),\n project(triangle_world.v3)\n );\n}\n\nconst Point2D Rasterizer::project(const Point3D& point_world) const {\n const Point3D point_camera = m_camera->viewTransform(point_world);\n const Point2D point_projected = m_camera->projectTransform(point_camera);\n return point_projected;\n}\n\nconst Point2D Rasterizer::unproject(const Point2D& point_raster) const {\n const Point2D point_ndc = m_camera->viewportTransformInv(point_raster);\n const Point2D point_projected = m_camera->ndcTransformInv(point_ndc);\n return point_projected;\n}\n\n\nconst RGBColor Rasterizer::shade(const GeometryObject& object, const Triangle3D& triangle, const Point3D point_in_triangle) const {\n#ifdef _PHONG\n return phongShading(object.m_material, object.m_color, triangle, point_in_triangle);\n#endif \/\/ _PHONG\n\n#ifdef _BLINN_PHONG\n return blinnPhongShading(object.m_material, object.m_color, triangle, point_in_triangle);\n#endif \/\/ _BLINN-PHONG\n}\n\nconst RGBColor Rasterizer::phongShading(const Material& material, const RGBColor& base_color, const Triangle3D& triangle, const Point3D& point_in_triangle) const {\n const RGBColor ambient = AMBIENT_COLOR * k_a;\n\n RGBColor diffuse, specular;\n for (auto& light : m_world->m_lights) {\n const Vector3D L = -(light->getDirectionToPoint(point_in_triangle));\n const Vector3D N = triangle.normal;\n const Vector3D R = 2 * (N * L) * N - L;\n const Vector3D V = -(m_world->m_camera->viewDirection(point_in_triangle));\n\n diffuse += light->getColor() * material.k_d * std::max((L * N), 0.0);\n specular += light->getColor() * material.k_s * pow(std::max((R * V), 0.0), material.k_shininess);\n }\n const RGBColor phong_result = (ambient + diffuse + specular) * base_color;\n return phong_result;\n}\n\nconst RGBColor Rasterizer::blinnPhongShading(const Material& material, const RGBColor& base_color, const Triangle3D& triangle, const Point3D& point_in_triangle) const {\n const RGBColor ambient = AMBIENT_COLOR * k_a;\n\n RGBColor diffuse, specular;\n for (auto& light : m_world->m_lights) {\n const Vector3D L = -(light->getDirectionToPoint(point_in_triangle));\n const Vector3D N = triangle.normal;\n const Vector3D V = -(m_world->m_camera->viewDirection(point_in_triangle));\n \/\/ Halfway calculation: Can be moved outside to increase performance\n Vector3D H = V + L;\n H.normalize();\n float a = (H * V);\n diffuse += light->getColor() * material.k_d * std::max((L * N), 0.0);\n specular += light->getColor() * material.k_s * pow(std::max((H * V), 0.0), material.k_shininess);\n }\n const RGBColor phong_result = (ambient + diffuse + specular) * base_color;\n return phong_result;\n}\n\nvoid Rasterizer::exportDepthBuffer(const std::vector<double>& depth_buffer, const std::string output_path, const uint16_t image_width, const uint16_t image_height) const {\n std::vector<RGBColor> depth_buffer_grey(image_height*image_width, RGBColor(1.0));\n for (int i = 0; i < depth_buffer.size(); ++i) {\n const double depth = depth_buffer[i];\n if (depth != m_camera->get_far_plane()) {\n \/\/ Convert depth in the range [near, far] to [0,1]\n const double slope = 1.0 \/ (m_camera->get_far_plane() - m_camera->get_near_plane());\n const double depth_normalized = slope * (depth - m_camera->get_near_plane());\n depth_buffer_grey[i] = RGBColor(depth_normalized);\n }\n }\n exportImage(depth_buffer_grey, output_path, image_width, image_height);\n}<commit_msg>Added transformation from view to world<commit_after>#include \"Rasterizer.h\"\n#include <limits> \/\/numerics::max\n#include \"Utils.h\" \/\/\n#include <algorithm> \/\/ std::max\nRasterizer::Rasterizer()\n : Renderer() {\n\n}\n\nRasterizer::Rasterizer(World* world)\n : Renderer(world) {\n\n}\n\nRasterizer::~Rasterizer() {\n}\n\n\nvoid Rasterizer::render(const std::string output_path, const uint16_t image_width, const uint16_t image_height) {\n m_pixels = std::vector<RGBColor>(image_height * image_width, BACKGROUND_COLOR);\n m_depth_buffer = std::vector<double>(image_height * image_width, m_camera->get_far_plane());\n\n for (auto& object : m_world->m_objects) {\n const std::vector<Triangle3D> triangles = object->triangulate();\n for (auto& triangle_world : triangles) {\n const Triangle2D triangle_projected = this->project(triangle_world);\n const Triangle2D triangle_raster = this->rasterize(triangle_world);\n const BoundingBox2D bbox_raster = triangle_raster.bbox();\n for (int32_t pixel_raster_x = bbox_raster.min.x; pixel_raster_x <= bbox_raster.max.x; ++pixel_raster_x) {\n for (int32_t pixel_raster_y = bbox_raster.min.y; pixel_raster_y <= bbox_raster.max.y; ++pixel_raster_y) {\n const Point2D pixel_raster = { (double) pixel_raster_x, (double) pixel_raster_y };\n if (triangle_raster.contains(pixel_raster)) {\n const Point2D pixel_projected = this->unproject(pixel_raster);\n const double depth = getDepth(triangle_world, triangle_projected, pixel_projected);\n const Point3D pixel_view = m_camera->projectTransformInv(pixel_projected, depth);\n const Point3D pixel_world = m_camera->viewTransformInv(pixel_view);\n if (m_camera->insideFrustrum(pixel_raster, depth)) {\n const uint32_t i = pixel_raster_y * image_width + pixel_raster_x;\n if (depth < m_depth_buffer[i]) {\n m_depth_buffer[i] = depth;\n m_pixels[i] = shade(*object, triangle_world, pixel_world);\n }\n }\n }\n }\n }\n }\n }\n\n exportDepthBuffer(m_depth_buffer, \"depth.bmp\", image_width, image_height);\n exportImage(m_pixels, output_path, image_width, image_height);\n}\n\nconst double Rasterizer::getDepth(const Triangle3D& triangle_world, const Triangle2D& triangle_screen, const Point2D& pixel_screen) const {\n const Triangle3D triangle_camera = Triangle3D(\n m_camera->viewTransform(triangle_world.v1),\n m_camera->viewTransform(triangle_world.v2),\n m_camera->viewTransform(triangle_world.v3)\n );\n\n \/\/ Calculate barycentric coords in camera space\n double u, v, w;\n triangle_screen.calculateBarycentricCoords(u, v, w, pixel_screen);\n \/\/ Interpolate Z in 3D using inverse function and barycentric coordinates in 2D\n const float depth = 1 \/ ((1 \/ triangle_camera.v1.z) * u + (1 \/ triangle_camera.v2.z) * v + (1 \/ triangle_camera.v3.z) * w);\n return depth;\n\n}\n\nconst Point2D Rasterizer::rasterize(const Point3D& point_world) const {\n const Point3D point_camera = m_camera->viewTransform(point_world);\n const Point2D point_projected = m_camera->projectTransform(point_camera);\n const Point2D point_ndc = m_camera->ndcTransform(point_projected);\n const Point2D point_raster = m_camera->viewportTransform(point_ndc);\n return point_raster;\n}\n\nconst Triangle2D Rasterizer::rasterize(const Triangle3D& triangle_world) const {\n return Triangle2D(\n rasterize(triangle_world.v1),\n rasterize(triangle_world.v2),\n rasterize(triangle_world.v3)\n );\n}\n\nconst Triangle2D Rasterizer::project(const Triangle3D& triangle_world) const {\n return Triangle2D(\n project(triangle_world.v1),\n project(triangle_world.v2),\n project(triangle_world.v3)\n );\n}\n\nconst Point2D Rasterizer::project(const Point3D& point_world) const {\n const Point3D point_camera = m_camera->viewTransform(point_world);\n const Point2D point_projected = m_camera->projectTransform(point_camera);\n return point_projected;\n}\n\nconst Point2D Rasterizer::unproject(const Point2D& point_raster) const {\n const Point2D point_ndc = m_camera->viewportTransformInv(point_raster);\n const Point2D point_projected = m_camera->ndcTransformInv(point_ndc);\n return point_projected;\n}\n\n\nconst RGBColor Rasterizer::shade(const GeometryObject& object, const Triangle3D& triangle, const Point3D point_in_triangle) const {\n#ifdef _PHONG\n return phongShading(object.m_material, object.m_color, triangle, point_in_triangle);\n#endif \/\/ _PHONG\n\n#ifdef _BLINN_PHONG\n return blinnPhongShading(object.m_material, object.m_color, triangle, point_in_triangle);\n#endif \/\/ _BLINN-PHONG\n}\n\nconst RGBColor Rasterizer::phongShading(const Material& material, const RGBColor& base_color, const Triangle3D& triangle, const Point3D& point_in_triangle) const {\n const RGBColor ambient = AMBIENT_COLOR * k_a;\n\n RGBColor diffuse, specular;\n for (auto& light : m_world->m_lights) {\n const Vector3D L = -(light->getDirectionToPoint(point_in_triangle));\n const Vector3D N = triangle.normal;\n const Vector3D R = 2 * (N * L) * N - L;\n const Vector3D V = -(m_world->m_camera->viewDirection(point_in_triangle));\n\n diffuse += light->getColor() * material.k_d * std::max((L * N), 0.0);\n specular += light->getColor() * material.k_s * pow(std::max((R * V), 0.0), material.k_shininess);\n }\n const RGBColor phong_result = (ambient + diffuse + specular) * base_color;\n return phong_result;\n}\n\nconst RGBColor Rasterizer::blinnPhongShading(const Material& material, const RGBColor& base_color, const Triangle3D& triangle, const Point3D& point_in_triangle) const {\n const RGBColor ambient = AMBIENT_COLOR * k_a;\n\n RGBColor diffuse, specular;\n for (auto& light : m_world->m_lights) {\n const Vector3D L = -(light->getDirectionToPoint(point_in_triangle));\n const Vector3D N = triangle.normal;\n const Vector3D V = -(m_world->m_camera->viewDirection(point_in_triangle));\n \/\/ Halfway calculation: Can be moved outside to increase performance\n Vector3D H = V + L;\n H.normalize();\n float a = (H * V);\n diffuse += light->getColor() * material.k_d * std::max((L * N), 0.0);\n specular += light->getColor() * material.k_s * pow(std::max((H * V), 0.0), material.k_shininess);\n }\n const RGBColor phong_result = (ambient + diffuse + specular) * base_color;\n return phong_result;\n}\n\nvoid Rasterizer::exportDepthBuffer(const std::vector<double>& depth_buffer, const std::string output_path, const uint16_t image_width, const uint16_t image_height) const {\n std::vector<RGBColor> depth_buffer_grey(image_height*image_width, RGBColor(1.0));\n for (int i = 0; i < depth_buffer.size(); ++i) {\n const double depth = depth_buffer[i];\n if (depth != m_camera->get_far_plane()) {\n \/\/ Convert depth in the range [near, far] to [0,1]\n const double slope = 1.0 \/ (m_camera->get_far_plane() - m_camera->get_near_plane());\n const double depth_normalized = slope * (depth - m_camera->get_near_plane());\n depth_buffer_grey[i] = RGBColor(depth_normalized);\n }\n }\n exportImage(depth_buffer_grey, output_path, image_width, image_height);\n}<|endoftext|>"} {"text":"<commit_before>#include \"Common.h\"\n#include \"SSEChannel.h\"\n#include \"SSEClient.h\"\n#include \"SSEClientHandler.h\"\n#include \"SSEEvent.h\"\n#include \"SSEConfig.h\"\n#include \"HTTPRequest.h\"\n#include \"HTTPResponse.h\"\n#include <boost\/foreach.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/thread.hpp>\n\nusing namespace std;\nextern int stop;\n\n\/**\n Constructor.\n @param conf Pointer to SSEConfig instance holding our configuration.\n @param id Unique identifier for this channel.\n*\/\nSSEChannel::SSEChannel(ChannelConfig conf, string id) {\n _config = conf;\n _config.id = id;\n\n _efd = epoll_create1(0);\n LOG_IF(FATAL, _efd == -1) << \"epoll_create1 failed.\";\n\n \/\/ Initialize counters.\n _stats.num_clients = 0;\n _stats.num_connects = 0;\n _stats.num_disconnects = 0;\n _stats.num_errors = 0;\n _stats.num_cached_events = 0;\n _stats.num_broadcasted_events = 0;\n _stats.cache_size = _config.cacheLength;\n\n\n LOG(INFO) << \"Initializing channel \" << _config.id;\n LOG(INFO) << \"Cache Adapter: \" << _config.cacheAdapter;\n LOG(INFO) << \"Cache length: \" << _config.cacheLength;\n LOG(INFO) << \"Threads per channel: \" << _config.server->GetValue(\"server.threadsPerChannel\");\n\n _allow_all_origins = (_config.allowedOrigins.size() < 1) ? true : false;\n\n BOOST_FOREACH(const std::string& origin, _config.allowedOrigins) {\n DLOG(INFO) << \"Allowed origin: \" << origin;\n }\n\n \/\/ Internet Explorer has a problem receiving data when using XDomainRequest before it has received 2KB of data.\n \/\/ The polyfills that account for this send a query parameter, evs_preamble to inform the server about this so it can respond with some initial data.\n \/\/ Initialize a buffer containing our response for this case.\n _evs_preamble_data[0] = ':';\n for (int i = 1; i <= 2048; i++) { _evs_preamble_data[i] = '.'; }\n _evs_preamble_data[2049] = '\\n';\n _evs_preamble_data[2050] = '\\n';\n _evs_preamble_data[2051] = '\\0';\n\n InitializeCache();\n InitializeThreads();\n}\n\n\/**\n Destructor.\n*\/\nSSEChannel::~SSEChannel() {\n DLOG(INFO) << \"SSEChannel destructor called.\";\n CleanupThreads();\n}\n\n\/*\n Initialize the configured cacheadapter for this channel\n*\/\nvoid SSEChannel::InitializeCache() {\n const string adapter = _config.cacheAdapter;\n if (adapter == \"redis\") {\n _cache_adapter = new Redis(_config.id, _config);\n } else if (adapter == \"memory\") {\n _cache_adapter = new Memory(_config);\n } else if (adapter == \"leveldb\") {\n _cache_adapter = new LevelDB(_config);\n }\n\n if (_cache_adapter) {\n _stats.num_cached_events = _cache_adapter->GetSizeOfCachedEvents();\n }\n}\n\n\/**\n Initialize client handler threads and also the thread that\n pings all connected clients on _config.red interval.\n*\/\nvoid SSEChannel::InitializeThreads() {\n int i;\n\n _cleanupthread = boost::thread(boost::bind(&SSEChannel::CleanupMain, this));\n\n for (i = 0; i < _config.server->GetValueInt(\"server.threadsPerChannel\"); i++) {\n _clientpool.push_back(ClientHandlerPtr(new SSEClientHandler(i)));\n }\n\n curthread = _clientpool.begin();\n _pingthread = boost::thread(boost::bind(&SSEChannel::Ping, this));\n}\n\n\/**\n Stop and free up all running threads.\n Called by destructor.\n*\/\nvoid SSEChannel::CleanupThreads() {\n pthread_cancel(_pingthread.native_handle());\n pthread_cancel(_cleanupthread.native_handle());\n}\n\n\/**\n Return the id of this channel.\n*\/\nstring SSEChannel::GetId() {\n return _config.id;\n}\n\n\/**\n Set correct CORS headers.\n @param req Request object.\n @param res Response object.\n*\/\nvoid SSEChannel::SetCorsHeaders(HTTPRequest* req, HTTPResponse& res) {\n \/\/ Set allowed headers for the EventSource IE polyfill\n res.SetHeader(\"Access-Control-Allow-Headers\", \"Accept, Cache-Control, X-Requested-With, Last-Event-ID\");\n\n if (_allow_all_origins) {\n DLOG(INFO) << \"All origins allowed.\";\n res.SetHeader(\"Access-Control-Allow-Origin\", \"*\");\n return;\n }\n\n const string& originHeader = req->GetHeader(\"Origin\");\n\n \/\/ If Origin header is not set in the request don't set any CORS headers.\n if (originHeader.empty()) {\n DLOG(INFO) << \"No Origin header in request, not setting cors headers.\";\n return;\n }\n\n \/\/ If Origin matches one of the origins in the allowedOrigins array use that in the CORS header.\n BOOST_FOREACH(const std::string& origin, _config.allowedOrigins) {\n if (originHeader.compare(0, origin.size(), origin) == 0) {\n res.SetHeader(\"Access-Control-Allow-Origin\", origin);\n DLOG(INFO) << \"Referer matches origin \" << origin;\n return;\n }\n }\n}\n\n\/**\n Adds a client to one of the client handlers assigned to the channel.\n Clients is distributed evenly across the client handler threads.\n @param client SSEClient pointer.\n*\/\nvoid SSEChannel::AddClient(SSEClient* client, HTTPRequest* req) {\n HTTPResponse res;\n struct epoll_event ev;\n int ret;\n\n DLOG(INFO) << \"Adding client to channel \" << GetId();\n\n \/\/ Send CORS headers.\n SetCorsHeaders(req, res);\n\n \/\/ Reply with CORS headers when we get a OPTIONS request.\n if (req->GetMethod().compare(\"OPTIONS\") == 0) {\n client->Send(res.Get());\n client->Destroy();\n return;\n }\n\n \/\/ Disallow every other method than GET.\n if (req->GetMethod().compare(\"GET\") != 0) {\n DLOG(INFO) << \"Method: \" << req->GetMethod();\n res.SetStatus(405, \"Method Not Allowed\");\n client->Send(res.Get());\n client->Destroy();\n return;\n }\n\n string lastEventId = req->GetHeader(\"Last-Event-ID\");\n if (lastEventId.empty()) lastEventId = req->GetQueryString(\"evs_last_event_id\");\n if (lastEventId.empty()) lastEventId = req->GetQueryString(\"lastEventId\");\n\n \/\/ Send initial response headers, etc.\n res.SetHeader(\"Content-Type\", \"text\/event-stream\");\n res.SetHeader(\"Cache-Control\", \"no-cache\");\n res.SetHeader(\"Connection\", \"close\");\n res.SetBody(\":ok\\n\\n\");\n\n \/\/ Send preamble if polyfill require it.\n if (!req->GetQueryString(\"evs_preamble\").empty()) {\n res.AppendBody(_evs_preamble_data);\n }\n\n client->Send(res.Get());\n\n \/\/ Apply filters.\n if (!req->GetQueryString(\"filterid\").empty()) client->Subscribe(req->GetQueryString(\"filterid\"), SUBSCRIPTION_ID);\n if (!req->GetQueryString(\"filterevent\").empty()) client->Subscribe(req->GetQueryString(\"filterevent\"), SUBSCRIPTION_EVENT_TYPE);\n\n \/\/ Send event history if requested.\n if (!lastEventId.empty()) {\n SendEventsSince(client, lastEventId);\n } else if (!req->GetQueryString(\"getcache\").empty()) {\n SendCache(client);\n }\n\n client->DeleteHttpReq();\n\n ev.events = EPOLLET | EPOLLOUT | EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR;\n ev.data.ptr = client;\n ret = epoll_ctl(_efd, EPOLL_CTL_ADD, client->Getfd(), &ev);\n\n if (ret == -1) {\n DLOG(ERROR) << \"Failed to add client \" << client->GetIP() << \" to epoll event list.\";\n client->Destroy();\n return;\n }\n\n INC_LONG(_stats.num_connects);\n\n \/\/ Add client to handler thread in a round-robin fashion.\n (*curthread)->AddClient(client);\n curthread++;\n\n if (curthread == _clientpool.end()) curthread = _clientpool.begin();\n}\n\n\/**\n Broadcasts string to all connected clients.\n @param data String to broadcast.\n*\/\nvoid SSEChannel::Broadcast(const string& data) {\n ClientHandlerList::iterator it;\n\n for (it = _clientpool.begin(); it != _clientpool.end(); it++) {\n (*it)->Broadcast(data);\n }\n}\n\n\/**\n Broadcasts SSEvent to all connected clients.\n @param event Event to broadcast.\n*\/\nvoid SSEChannel::BroadcastEvent(SSEEvent& event) {\n Broadcast(event.get());\n INC_LONG(_stats.num_broadcasted_events);\n\n \/\/ Add event to cache if it contains a id field.\n if (!event.getid().empty()) {\n CacheEvent(event);\n }\n}\n\n\/**\n Add event to cache.\n @param event Event to cache.\n*\/\nvoid SSEChannel::CacheEvent(SSEEvent& event) {\n if (_cache_adapter) {\n _cache_adapter->CacheEvent(event);\n _stats.num_cached_events = _cache_adapter->GetSizeOfCachedEvents();\n }\n}\n\n\/**\n Send all events since a given event id to client.\n @param lastId Send all events since this id.\n*\/\nvoid SSEChannel::SendEventsSince(SSEClient* client, string lastId) {\n deque<string>::const_iterator it;\n deque<string> events = _cache_adapter->GetEventsSinceId(lastId);\n\n BOOST_FOREACH(const string& event, events) {\n client->Send(event, SND_NO_FLUSH);\n }\n}\n\n\/**\n Send all cached events to client.\n @param client SSEClient.\n*\/\nvoid SSEChannel::SendCache(SSEClient* client) {\n deque<string>::const_iterator it;\n deque<string> events = _cache_adapter->GetAllEvents();\n\n BOOST_FOREACH(const string& event, events) {\n client->Send(event, SND_NO_FLUSH);\n }\n}\n\n\/**\n Handle client disconnects and errors.\n*\/\nvoid SSEChannel::CleanupMain() {\n boost::shared_ptr<struct epoll_event[]> t_events(new struct epoll_event[1024]);\n\n while(!stop) {\n int n = epoll_wait(_efd, t_events.get(), 1024, -1);\n\n for (int i = 0; i < n; i++) {\n SSEClient* client;\n client = static_cast<SSEClient*>(t_events[i].data.ptr);\n\n if (t_events[i].events & EPOLLIN) {\n char buf[512];\n int rcv_len = client->Read(buf, 512);\n if (rcv_len <= 0) {\n client->MarkAsDead();\n INC_LONG(_stats.num_disconnects);\n }\n } else if ((t_events[i].events & EPOLLHUP) || (t_events[i].events & EPOLLRDHUP)) {\n DLOG(INFO) << \"Channel \" << _config.id << \": Client disconnected.\";\n client->MarkAsDead();\n INC_LONG(_stats.num_disconnects);\n } else if (t_events[i].events & EPOLLERR) {\n \/\/ If an error occurs on a client socket, just drop the connection.\n DLOG(INFO) << \"Channel \" << _config.id << \": Error on client socket: \" << strerror(errno);\n client->MarkAsDead();\n INC_LONG(_stats.num_errors);\n } else if (t_events[i].events & EPOLLOUT) {\n \/\/ Send data present in send buffer,\n DLOG(INFO) << client->GetIP() << \": EPOLLOUT, flushing send buffer.\";\n client->Flush();\n }\n }\n }\n}\n\n\/**\n Sends a ping to all clients connected to this channel.\n*\/\nvoid SSEChannel::Ping() {\n while(!stop) {\n Broadcast(\":\\n\\n\");\n sleep(_config.server->GetValueInt(\"server.pingInterval\"));\n }\n}\n\n\/**\n Returns number of clients connected to this channel.\n*\/\nulong SSEChannel::GetNumClients() {\n ClientHandlerList::iterator it;\n ulong numclients = 0;\n\n for (it = _clientpool.begin(); it != _clientpool.end(); it++) {\n numclients += (*it)->GetNumClients();\n }\n\n return numclients;\n}\n\n\/**\n Fetch various statistics for the channel.\n @param stats Pointer to SSEChannelStats struct which is to be filled with the statistics.\n**\/\nconst SSEChannelStats& SSEChannel::GetStats() {\n _stats.num_clients = GetNumClients();\n return _stats;\n}\n\n\/**\n Returns the ChannelConfig.\n**\/\nconst ChannelConfig& SSEChannel::GetConfig() {\n return _config;\n}\n<commit_msg>Send ping as en event, and not a \"comment\"<commit_after>#include \"Common.h\"\n#include \"SSEChannel.h\"\n#include \"SSEClient.h\"\n#include \"SSEClientHandler.h\"\n#include \"SSEEvent.h\"\n#include \"SSEConfig.h\"\n#include \"HTTPRequest.h\"\n#include \"HTTPResponse.h\"\n#include <boost\/foreach.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/thread.hpp>\n\nusing namespace std;\nextern int stop;\n\n\/**\n Constructor.\n @param conf Pointer to SSEConfig instance holding our configuration.\n @param id Unique identifier for this channel.\n*\/\nSSEChannel::SSEChannel(ChannelConfig conf, string id) {\n _config = conf;\n _config.id = id;\n\n _efd = epoll_create1(0);\n LOG_IF(FATAL, _efd == -1) << \"epoll_create1 failed.\";\n\n \/\/ Initialize counters.\n _stats.num_clients = 0;\n _stats.num_connects = 0;\n _stats.num_disconnects = 0;\n _stats.num_errors = 0;\n _stats.num_cached_events = 0;\n _stats.num_broadcasted_events = 0;\n _stats.cache_size = _config.cacheLength;\n\n\n LOG(INFO) << \"Initializing channel \" << _config.id;\n LOG(INFO) << \"Cache Adapter: \" << _config.cacheAdapter;\n LOG(INFO) << \"Cache length: \" << _config.cacheLength;\n LOG(INFO) << \"Threads per channel: \" << _config.server->GetValue(\"server.threadsPerChannel\");\n\n _allow_all_origins = (_config.allowedOrigins.size() < 1) ? true : false;\n\n BOOST_FOREACH(const std::string& origin, _config.allowedOrigins) {\n DLOG(INFO) << \"Allowed origin: \" << origin;\n }\n\n \/\/ Internet Explorer has a problem receiving data when using XDomainRequest before it has received 2KB of data.\n \/\/ The polyfills that account for this send a query parameter, evs_preamble to inform the server about this so it can respond with some initial data.\n \/\/ Initialize a buffer containing our response for this case.\n _evs_preamble_data[0] = ':';\n for (int i = 1; i <= 2048; i++) { _evs_preamble_data[i] = '.'; }\n _evs_preamble_data[2049] = '\\n';\n _evs_preamble_data[2050] = '\\n';\n _evs_preamble_data[2051] = '\\0';\n\n InitializeCache();\n InitializeThreads();\n}\n\n\/**\n Destructor.\n*\/\nSSEChannel::~SSEChannel() {\n DLOG(INFO) << \"SSEChannel destructor called.\";\n CleanupThreads();\n}\n\n\/*\n Initialize the configured cacheadapter for this channel\n*\/\nvoid SSEChannel::InitializeCache() {\n const string adapter = _config.cacheAdapter;\n if (adapter == \"redis\") {\n _cache_adapter = new Redis(_config.id, _config);\n } else if (adapter == \"memory\") {\n _cache_adapter = new Memory(_config);\n } else if (adapter == \"leveldb\") {\n _cache_adapter = new LevelDB(_config);\n }\n\n if (_cache_adapter) {\n _stats.num_cached_events = _cache_adapter->GetSizeOfCachedEvents();\n }\n}\n\n\/**\n Initialize client handler threads and also the thread that\n pings all connected clients on _config.red interval.\n*\/\nvoid SSEChannel::InitializeThreads() {\n int i;\n\n _cleanupthread = boost::thread(boost::bind(&SSEChannel::CleanupMain, this));\n\n for (i = 0; i < _config.server->GetValueInt(\"server.threadsPerChannel\"); i++) {\n _clientpool.push_back(ClientHandlerPtr(new SSEClientHandler(i)));\n }\n\n curthread = _clientpool.begin();\n _pingthread = boost::thread(boost::bind(&SSEChannel::Ping, this));\n}\n\n\/**\n Stop and free up all running threads.\n Called by destructor.\n*\/\nvoid SSEChannel::CleanupThreads() {\n pthread_cancel(_pingthread.native_handle());\n pthread_cancel(_cleanupthread.native_handle());\n}\n\n\/**\n Return the id of this channel.\n*\/\nstring SSEChannel::GetId() {\n return _config.id;\n}\n\n\/**\n Set correct CORS headers.\n @param req Request object.\n @param res Response object.\n*\/\nvoid SSEChannel::SetCorsHeaders(HTTPRequest* req, HTTPResponse& res) {\n \/\/ Set allowed headers for the EventSource IE polyfill\n res.SetHeader(\"Access-Control-Allow-Headers\", \"Accept, Cache-Control, X-Requested-With, Last-Event-ID\");\n\n if (_allow_all_origins) {\n DLOG(INFO) << \"All origins allowed.\";\n res.SetHeader(\"Access-Control-Allow-Origin\", \"*\");\n return;\n }\n\n const string& originHeader = req->GetHeader(\"Origin\");\n\n \/\/ If Origin header is not set in the request don't set any CORS headers.\n if (originHeader.empty()) {\n DLOG(INFO) << \"No Origin header in request, not setting cors headers.\";\n return;\n }\n\n \/\/ If Origin matches one of the origins in the allowedOrigins array use that in the CORS header.\n BOOST_FOREACH(const std::string& origin, _config.allowedOrigins) {\n if (originHeader.compare(0, origin.size(), origin) == 0) {\n res.SetHeader(\"Access-Control-Allow-Origin\", origin);\n DLOG(INFO) << \"Referer matches origin \" << origin;\n return;\n }\n }\n}\n\n\/**\n Adds a client to one of the client handlers assigned to the channel.\n Clients is distributed evenly across the client handler threads.\n @param client SSEClient pointer.\n*\/\nvoid SSEChannel::AddClient(SSEClient* client, HTTPRequest* req) {\n HTTPResponse res;\n struct epoll_event ev;\n int ret;\n\n DLOG(INFO) << \"Adding client to channel \" << GetId();\n\n \/\/ Send CORS headers.\n SetCorsHeaders(req, res);\n\n \/\/ Reply with CORS headers when we get a OPTIONS request.\n if (req->GetMethod().compare(\"OPTIONS\") == 0) {\n client->Send(res.Get());\n client->Destroy();\n return;\n }\n\n \/\/ Disallow every other method than GET.\n if (req->GetMethod().compare(\"GET\") != 0) {\n DLOG(INFO) << \"Method: \" << req->GetMethod();\n res.SetStatus(405, \"Method Not Allowed\");\n client->Send(res.Get());\n client->Destroy();\n return;\n }\n\n string lastEventId = req->GetHeader(\"Last-Event-ID\");\n if (lastEventId.empty()) lastEventId = req->GetQueryString(\"evs_last_event_id\");\n if (lastEventId.empty()) lastEventId = req->GetQueryString(\"lastEventId\");\n\n \/\/ Send initial response headers, etc.\n res.SetHeader(\"Content-Type\", \"text\/event-stream\");\n res.SetHeader(\"Cache-Control\", \"no-cache\");\n res.SetHeader(\"Connection\", \"close\");\n res.SetBody(\":ok\\n\\n\");\n\n \/\/ Send preamble if polyfill require it.\n if (!req->GetQueryString(\"evs_preamble\").empty()) {\n res.AppendBody(_evs_preamble_data);\n }\n\n client->Send(res.Get());\n\n \/\/ Apply filters.\n if (!req->GetQueryString(\"filterid\").empty()) client->Subscribe(req->GetQueryString(\"filterid\"), SUBSCRIPTION_ID);\n if (!req->GetQueryString(\"filterevent\").empty()) client->Subscribe(req->GetQueryString(\"filterevent\"), SUBSCRIPTION_EVENT_TYPE);\n\n \/\/ Send event history if requested.\n if (!lastEventId.empty()) {\n SendEventsSince(client, lastEventId);\n } else if (!req->GetQueryString(\"getcache\").empty()) {\n SendCache(client);\n }\n\n client->DeleteHttpReq();\n\n ev.events = EPOLLET | EPOLLOUT | EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR;\n ev.data.ptr = client;\n ret = epoll_ctl(_efd, EPOLL_CTL_ADD, client->Getfd(), &ev);\n\n if (ret == -1) {\n DLOG(ERROR) << \"Failed to add client \" << client->GetIP() << \" to epoll event list.\";\n client->Destroy();\n return;\n }\n\n INC_LONG(_stats.num_connects);\n\n \/\/ Add client to handler thread in a round-robin fashion.\n (*curthread)->AddClient(client);\n curthread++;\n\n if (curthread == _clientpool.end()) curthread = _clientpool.begin();\n}\n\n\/**\n Broadcasts string to all connected clients.\n @param data String to broadcast.\n*\/\nvoid SSEChannel::Broadcast(const string& data) {\n ClientHandlerList::iterator it;\n\n for (it = _clientpool.begin(); it != _clientpool.end(); it++) {\n (*it)->Broadcast(data);\n }\n}\n\n\/**\n Broadcasts SSEvent to all connected clients.\n @param event Event to broadcast.\n*\/\nvoid SSEChannel::BroadcastEvent(SSEEvent& event) {\n Broadcast(event.get());\n INC_LONG(_stats.num_broadcasted_events);\n\n \/\/ Add event to cache if it contains a id field.\n if (!event.getid().empty()) {\n CacheEvent(event);\n }\n}\n\n\/**\n Add event to cache.\n @param event Event to cache.\n*\/\nvoid SSEChannel::CacheEvent(SSEEvent& event) {\n if (_cache_adapter) {\n _cache_adapter->CacheEvent(event);\n _stats.num_cached_events = _cache_adapter->GetSizeOfCachedEvents();\n }\n}\n\n\/**\n Send all events since a given event id to client.\n @param lastId Send all events since this id.\n*\/\nvoid SSEChannel::SendEventsSince(SSEClient* client, string lastId) {\n deque<string>::const_iterator it;\n deque<string> events = _cache_adapter->GetEventsSinceId(lastId);\n\n BOOST_FOREACH(const string& event, events) {\n client->Send(event, SND_NO_FLUSH);\n }\n}\n\n\/**\n Send all cached events to client.\n @param client SSEClient.\n*\/\nvoid SSEChannel::SendCache(SSEClient* client) {\n deque<string>::const_iterator it;\n deque<string> events = _cache_adapter->GetAllEvents();\n\n BOOST_FOREACH(const string& event, events) {\n client->Send(event, SND_NO_FLUSH);\n }\n}\n\n\/**\n Handle client disconnects and errors.\n*\/\nvoid SSEChannel::CleanupMain() {\n boost::shared_ptr<struct epoll_event[]> t_events(new struct epoll_event[1024]);\n\n while(!stop) {\n int n = epoll_wait(_efd, t_events.get(), 1024, -1);\n\n for (int i = 0; i < n; i++) {\n SSEClient* client;\n client = static_cast<SSEClient*>(t_events[i].data.ptr);\n\n if (t_events[i].events & EPOLLIN) {\n char buf[512];\n int rcv_len = client->Read(buf, 512);\n if (rcv_len <= 0) {\n client->MarkAsDead();\n INC_LONG(_stats.num_disconnects);\n }\n } else if ((t_events[i].events & EPOLLHUP) || (t_events[i].events & EPOLLRDHUP)) {\n DLOG(INFO) << \"Channel \" << _config.id << \": Client disconnected.\";\n client->MarkAsDead();\n INC_LONG(_stats.num_disconnects);\n } else if (t_events[i].events & EPOLLERR) {\n \/\/ If an error occurs on a client socket, just drop the connection.\n DLOG(INFO) << \"Channel \" << _config.id << \": Error on client socket: \" << strerror(errno);\n client->MarkAsDead();\n INC_LONG(_stats.num_errors);\n } else if (t_events[i].events & EPOLLOUT) {\n \/\/ Send data present in send buffer,\n DLOG(INFO) << client->GetIP() << \": EPOLLOUT, flushing send buffer.\";\n client->Flush();\n }\n }\n }\n}\n\n\/**\n Sends a ping to all clients connected to this channel.\n*\/\nvoid SSEChannel::Ping() {\n while(!stop) {\n Broadcast(\"event:ping\\n\\n\");\n sleep(_config.server->GetValueInt(\"server.pingInterval\"));\n }\n}\n\n\/**\n Returns number of clients connected to this channel.\n*\/\nulong SSEChannel::GetNumClients() {\n ClientHandlerList::iterator it;\n ulong numclients = 0;\n\n for (it = _clientpool.begin(); it != _clientpool.end(); it++) {\n numclients += (*it)->GetNumClients();\n }\n\n return numclients;\n}\n\n\/**\n Fetch various statistics for the channel.\n @param stats Pointer to SSEChannelStats struct which is to be filled with the statistics.\n**\/\nconst SSEChannelStats& SSEChannel::GetStats() {\n _stats.num_clients = GetNumClients();\n return _stats;\n}\n\n\/**\n Returns the ChannelConfig.\n**\/\nconst ChannelConfig& SSEChannel::GetConfig() {\n return _config;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\r\nGPU OPTIMIZED MONTE CARLO (GOMC) 2.51\r\nCopyright (C) 2018 GOMC Group\r\nA copy of the GNU General Public License can be found in the COPYRIGHT.txt\r\nalong with this program, also can be found at <http:\/\/www.gnu.org\/licenses\/>.\r\n********************************************************************************\/\r\n#include \"Simulation.h\"\r\n#include \"Setup.h\" \/\/For setup object\r\n\r\n#include \"EnergyTypes.h\"\r\n#include \"PSFOutput.h\"\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\nSimulation::Simulation(char const*const configFileName, MultiSim const*const& multisim):ms(multisim)\r\n{\r\n startStep = 0;\r\n \/\/NOTE:\r\n \/\/IMPORTANT! Keep this order...\r\n \/\/as system depends on staticValues, and cpu sometimes depends on both.\r\n set.Init(configFileName, multisim);\r\n totalSteps = set.config.sys.step.total;\r\n staticValues = new StaticVals(set);\r\n system = new System(*staticValues);\r\n staticValues->Init(set, *system);\r\n system->Init(set, startStep);\r\n \/\/recal Init for static value for initializing ewald since ewald is\r\n \/\/initialized in system\r\n staticValues->InitOver(set, *system);\r\n cpu = new CPUSide(*system, *staticValues);\r\n cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil,\r\n totalSteps, startStep);\r\n\r\n \/\/Dump combined PSF\r\n PSFOutput psfOut(staticValues->mol, *system, set.mol.kindMap,\r\n set.pdb.atoms.resKindNames);\r\n psfOut.PrintPSF(set.config.out.state.files.psf.name);\r\n std::cout << \"Printed combined psf to file \"\r\n << set.config.out.state.files.psf.name << '\\n';\r\n\r\n if(totalSteps == 0) {\r\n frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name);\r\n }\r\n#if GOMC_LIB_MPI\r\n PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq): NULL;\r\n exchangeResults.resize(ms->worldSize, false);\r\n#endif\r\n}\r\n\r\nSimulation::~Simulation()\r\n{\r\n delete cpu;\r\n delete system;\r\n delete staticValues;\r\n}\r\n\r\nvoid Simulation::RunSimulation(void)\r\n{\r\n double startEnergy = system->potential.totalEnergy.total;\r\n if(totalSteps == 0) {\r\n for(int i = 0; i < frameSteps.size(); i++) {\r\n if(i == 0) {\r\n cpu->Output(frameSteps[0] - 1);\r\n continue;\r\n }\r\n system->RecalculateTrajectory(set, i + 1);\r\n cpu->Output(frameSteps[i] - 1);\r\n }\r\n }\r\n for (ulong step = startStep; step < totalSteps; step++) {\r\n system->moveSettings.AdjustMoves(step);\r\n system->ChooseAndRunMove(step);\r\n cpu->Output(step);\r\n\r\n if((step + 1) == cpu->equilSteps) {\r\n double currEnergy = system->potential.totalEnergy.total;\r\n if(abs(currEnergy - startEnergy) > 1.0e+10) {\r\n printf(\"Info: Recalculating the total energies to insure the accuracy\"\r\n \" of the computed \\n\"\r\n \" running energies.\\n\\n\");\r\n system->calcEwald->Init();\r\n system->potential = system->calcEnergy.SystemTotal();\r\n }\r\n }\r\n #if GOMC_LIB_MPI\r\n\r\n if( staticValues->simEventFreq.parallelTemp && step % staticValues->simEventFreq.parallelTempFreq == 0){\r\n\r\n exchangeResults = PTUtils->evaluateExchangeCriteria(step);\r\n \r\n if (exchangeResults[ms->worldRank] == true){\r\n PTUtils->exchangePositions(system->coordinates, ms, ms->worldRank-1, true);\r\n PTUtils->exchangeCOMs(system->com, ms, ms->worldRank-1, true);\r\n\r\n system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);\r\n for (uint bPick = 0; bPick < BOX_TOTAL; bPick++){\r\n system->calcEwald->BoxReciprocalSetup(bPick, system->coordinates);\r\n system->calcEwald->UpdateRecip(bPick);\r\n }\r\n system->potential = system->calcEnergy.SystemTotal();\r\n\r\n } else if(ms->worldRank+1 != ms->worldSize && exchangeResults[ms->worldRank+1] == true) {\r\n PTUtils->exchangePositions(system->coordinates, ms, ms->worldRank+1, false);\r\n PTUtils->exchangeCOMs(system->com, ms, ms->worldRank+1, false);\r\n\r\n system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);\r\n \r\n for (uint bPick = 0; bPick < BOX_TOTAL; bPick++){\r\n system->calcEwald->BoxReciprocalSetup(bPick, system->coordinates);\r\n system->calcEwald->UpdateRecip(bPick);\r\n }\r\n system->potential = system->calcEnergy.SystemTotal();\r\n\r\n }\r\n\r\n }\r\n #endif\r\n\r\n#ifndef NDEBUG\r\n if((step + 1) % 1000 == 0)\r\n RunningCheck(step);\r\n#endif\r\n }\r\n system->PrintAcceptance();\r\n system->PrintTime();\r\n}\r\n\r\n#ifndef NDEBUG\r\nvoid Simulation::RunningCheck(const uint step)\r\n{\r\n system->calcEwald->UpdateVectorsAndRecipTerms();\r\n SystemPotential pot = system->calcEnergy.SystemTotal();\r\n\r\n std::cout\r\n << \"=================================================================\"\r\n << std::endl << \"-------------------------\" << std::endl\r\n << \" STEP: \" << step + 1\r\n << std::endl << \"-------------------------\" << std::endl\r\n << \"Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP\"\r\n << std::endl\r\n << \"System: \"\r\n << std::setw(12) << system->potential.totalEnergy.intraBond << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.intraNonbond << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.inter << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.tc << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.real << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.self << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.correction << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.recip << std::endl\r\n << \"Recalc: \"\r\n << std::setw(12) << pot.totalEnergy.intraBond << \" | \"\r\n << std::setw(12) << pot.totalEnergy.intraNonbond << \" | \"\r\n << std::setw(12) << pot.totalEnergy.inter << \" | \"\r\n << std::setw(12) << pot.totalEnergy.tc << \" | \"\r\n << std::setw(12) << pot.totalEnergy.real << \" | \"\r\n << std::setw(12) << pot.totalEnergy.self << \" | \"\r\n << std::setw(12) << pot.totalEnergy.correction << \" | \"\r\n << std::setw(12) << pot.totalEnergy.recip << std::endl\r\n << \"================================================================\"\r\n << std::endl << std::endl;\r\n\r\n}\r\n\r\n#endif\r\n<commit_msg>scorched earth ewald<commit_after>\/*******************************************************************************\r\nGPU OPTIMIZED MONTE CARLO (GOMC) 2.51\r\nCopyright (C) 2018 GOMC Group\r\nA copy of the GNU General Public License can be found in the COPYRIGHT.txt\r\nalong with this program, also can be found at <http:\/\/www.gnu.org\/licenses\/>.\r\n********************************************************************************\/\r\n#include \"Simulation.h\"\r\n#include \"Setup.h\" \/\/For setup object\r\n\r\n#include \"EnergyTypes.h\"\r\n#include \"PSFOutput.h\"\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\nSimulation::Simulation(char const*const configFileName, MultiSim const*const& multisim):ms(multisim)\r\n{\r\n startStep = 0;\r\n \/\/NOTE:\r\n \/\/IMPORTANT! Keep this order...\r\n \/\/as system depends on staticValues, and cpu sometimes depends on both.\r\n set.Init(configFileName, multisim);\r\n totalSteps = set.config.sys.step.total;\r\n staticValues = new StaticVals(set);\r\n system = new System(*staticValues);\r\n staticValues->Init(set, *system);\r\n system->Init(set, startStep);\r\n \/\/recal Init for static value for initializing ewald since ewald is\r\n \/\/initialized in system\r\n staticValues->InitOver(set, *system);\r\n cpu = new CPUSide(*system, *staticValues);\r\n cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil,\r\n totalSteps, startStep);\r\n\r\n \/\/Dump combined PSF\r\n PSFOutput psfOut(staticValues->mol, *system, set.mol.kindMap,\r\n set.pdb.atoms.resKindNames);\r\n psfOut.PrintPSF(set.config.out.state.files.psf.name);\r\n std::cout << \"Printed combined psf to file \"\r\n << set.config.out.state.files.psf.name << '\\n';\r\n\r\n if(totalSteps == 0) {\r\n frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name);\r\n }\r\n#if GOMC_LIB_MPI\r\n PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq): NULL;\r\n exchangeResults.resize(ms->worldSize, false);\r\n#endif\r\n}\r\n\r\nSimulation::~Simulation()\r\n{\r\n delete cpu;\r\n delete system;\r\n delete staticValues;\r\n}\r\n\r\nvoid Simulation::RunSimulation(void)\r\n{\r\n double startEnergy = system->potential.totalEnergy.total;\r\n if(totalSteps == 0) {\r\n for(int i = 0; i < frameSteps.size(); i++) {\r\n if(i == 0) {\r\n cpu->Output(frameSteps[0] - 1);\r\n continue;\r\n }\r\n system->RecalculateTrajectory(set, i + 1);\r\n cpu->Output(frameSteps[i] - 1);\r\n }\r\n }\r\n for (ulong step = startStep; step < totalSteps; step++) {\r\n system->moveSettings.AdjustMoves(step);\r\n system->ChooseAndRunMove(step);\r\n cpu->Output(step);\r\n\r\n if((step + 1) == cpu->equilSteps) {\r\n double currEnergy = system->potential.totalEnergy.total;\r\n if(abs(currEnergy - startEnergy) > 1.0e+10) {\r\n printf(\"Info: Recalculating the total energies to insure the accuracy\"\r\n \" of the computed \\n\"\r\n \" running energies.\\n\\n\");\r\n system->calcEwald->Init();\r\n system->potential = system->calcEnergy.SystemTotal();\r\n }\r\n }\r\n #if GOMC_LIB_MPI\r\n\r\n if( staticValues->simEventFreq.parallelTemp && step % staticValues->simEventFreq.parallelTempFreq == 0){\r\n\r\n exchangeResults = PTUtils->evaluateExchangeCriteria(step);\r\n \r\n if (exchangeResults[ms->worldRank] == true){\r\n PTUtils->exchangePositions(system->coordinates, ms, ms->worldRank-1, true);\r\n PTUtils->exchangeCOMs(system->com, ms, ms->worldRank-1, true);\r\n\r\n system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);\r\n\r\n system->calcEwald->UpdateVectorsAndRecipTerms();\r\n\r\n system->potential = system->calcEnergy.SystemTotal();\r\n\r\n } else if(ms->worldRank+1 != ms->worldSize && exchangeResults[ms->worldRank+1] == true) {\r\n PTUtils->exchangePositions(system->coordinates, ms, ms->worldRank+1, false);\r\n PTUtils->exchangeCOMs(system->com, ms, ms->worldRank+1, false);\r\n\r\n system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);\r\n \r\n system->calcEwald->UpdateVectorsAndRecipTerms();\r\n\r\n system->potential = system->calcEnergy.SystemTotal();\r\n\r\n }\r\n\r\n }\r\n #endif\r\n\r\n#ifndef NDEBUG\r\n if((step + 1) % 1000 == 0)\r\n RunningCheck(step);\r\n#endif\r\n }\r\n system->PrintAcceptance();\r\n system->PrintTime();\r\n}\r\n\r\n#ifndef NDEBUG\r\nvoid Simulation::RunningCheck(const uint step)\r\n{\r\n system->calcEwald->UpdateVectorsAndRecipTerms();\r\n SystemPotential pot = system->calcEnergy.SystemTotal();\r\n\r\n std::cout\r\n << \"=================================================================\"\r\n << std::endl << \"-------------------------\" << std::endl\r\n << \" STEP: \" << step + 1\r\n << std::endl << \"-------------------------\" << std::endl\r\n << \"Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP\"\r\n << std::endl\r\n << \"System: \"\r\n << std::setw(12) << system->potential.totalEnergy.intraBond << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.intraNonbond << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.inter << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.tc << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.real << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.self << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.correction << \" | \"\r\n << std::setw(12) << system->potential.totalEnergy.recip << std::endl\r\n << \"Recalc: \"\r\n << std::setw(12) << pot.totalEnergy.intraBond << \" | \"\r\n << std::setw(12) << pot.totalEnergy.intraNonbond << \" | \"\r\n << std::setw(12) << pot.totalEnergy.inter << \" | \"\r\n << std::setw(12) << pot.totalEnergy.tc << \" | \"\r\n << std::setw(12) << pot.totalEnergy.real << \" | \"\r\n << std::setw(12) << pot.totalEnergy.self << \" | \"\r\n << std::setw(12) << pot.totalEnergy.correction << \" | \"\r\n << std::setw(12) << pot.totalEnergy.recip << std::endl\r\n << \"================================================================\"\r\n << std::endl << std::endl;\r\n\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * capture.cpp\n *\n * Created on: 24 juin 2014\n * Author: Maël Valais\n *\n *\tClasse de traitement (contrairement à fenetreprincipale.cpp qui gère l'interface)\n *\tgérant :\n *\t\t- la connexion et déconnexion avec la caméra,\n *\t\t- la capture des images avec la caméra,\n *\t\t- le calcul de la position par corrélation.\n *\n *\tLes résultats des captures sont envoyées à la classe Guidage (grâce au signal\n *\tresultats(...)).\n *\n *\tCette classe gère aussi le diamètre du soleil (on lui envoie les nouveaux diamètres\n *\tou alors elle utilise le calcul du diamètre automatique de diametre_soleil.c)\n *\n *\tL'instance de cette classe doit être exécuté dans un thread différent car dans le cas contraire,\n *\tl'interface serait bloquée.\n *\n *\n *\/\n\n#include <QtCore\/QSettings>\n\/\/ Les paramètres sont enregistrés (sous Linux) dans ~\/.config\/irap\/climso-auto.conf\n\n#include \"capture.h\"\n#include \"diametre_soleil.h\"\n\n\/**\n * Paramètres chargés pour la capture (fichier ~\/.config\/irap\/climso-auto.conf sous linux)\n * On peut modifier les paramètres par défaut en modifiant la valeur du\n * second paramètres de value(): value(\"le-nom-du-parametre\",valeurParDéfaut)\n * Certains de ces paramètres sont aussi modifiables depuis le logiciel (menu > paramètres)\n *\/\nvoid Capture::chargerParametres() {\n\tQSettings parametres(\"irap\", \"climso-auto\");\n\tdiametre = parametres.value(\"diametre-soleil-en-pixel\", 275).toInt(); \/\/ diamètre du soleil en pixels\n\tmodifierDiametre(diametre);\n\temit diametreSoleil(diametre);\n}\n\nvoid Capture::enregistrerParametres() {\n\tQSettings parametres(\"irap\", \"climso-auto\");\n\tparametres.setValue(\"diametre-soleil-en-pixel\", diametre);\n}\n\nCapture::Capture() {\n\tcam = NULL;\n\timg = NULL;\n\tref_lapl = NULL;\n\tposition_c = position_l = 0;\n\tdiametre = 0;\n\tQObject::connect(&timerProchaineCapture,SIGNAL(timeout()),this,SLOT(captureEtPosition()));\n\ttimerProchaineCapture.setSingleShot(true);\n\ttimerProchaineCapture.setInterval(DUREE_ENTRE_CAPTURES);\n\tqRegisterMetaType<EtatCamera>(\"EtatCamera\");\n\tcaptureEtPosition(); \/\/ Lancement de la première capture\n}\n\nCapture::~Capture() {\n\tenregistrerParametres();\n\tdeconnecterCamera();\n\/\/\tif(cam) delete cam; cam=NULL;\n\/\/\tif(img) delete img; img=NULL;\n\/\/\tif(ref_lapl) delete ref_lapl; ref_lapl = NULL;\n\tcout << \"Caméra deconnectée\" <<endl;\n\t\/\/ FIXME: Quand on a fait le quit(), les events sont tous traités ?\n}\n\n\/**\n * Connecte la caméra\n *\/\nvoid Capture::connecterCamera() {\n PAR_ERROR err;\n if(cam != NULL)\n delete cam;\n cam = new CSBIGCam(DEV_USB); \/\/ Creation du device USB\n if ((err = cam->GetError()) != CE_NO_ERROR) {\n emit message(\"Erreur avec la camera lors de la creation de l'objet camera : \"+QString::fromStdString(cam->GetErrorString()));\n etatCamera = CAMERA_CONNEXION_OFF;\n }\n else if ((err=cam->EstablishLink()) != CE_NO_ERROR) { \/\/ Connexion à la camera\n emit message(\"Erreur avec la camera lors de l'etablissement du lien: \"+QString::fromStdString(cam->GetErrorString()));\n etatCamera = CAMERA_CONNEXION_OFF;\n }\n else { \/\/ Pas d'erreurs, on met en binning 3x3\n cam->SetReadoutMode(RM_3X3);\n cam->SetExposureTime(DUREE_EXPOSITION * 0.001);\n cam->SetFastReadout(true);\n cam->SetABGState((ABG_STATE7)ABG_LOW7);\n\n emit message(\"Camera connectee\");\n etatCamera = CAMERA_CONNEXION_ON;\n }\n emit envoiEtatCamera(etatCamera);\n}\n\n\/**\n * Déconnecte la caméra\n *\/\nvoid Capture::deconnecterCamera() {\n if(cam) {\n cam->CloseDevice();\n emit message(\"Camera deconnectee\");\n delete cam; cam = NULL;\n etatCamera = CAMERA_CONNEXION_OFF;\n }\n else {\n emit message(\"Aucune camera n'est connectee\");\n etatCamera = CAMERA_CONNEXION_OFF;\n }\n emit envoiEtatCamera(etatCamera);\n}\n\n\/**\n * Vérifie la bonne connexion avec la caméra\n * @return\n *\/\nbool Capture::cameraConnectee() {\n return cam && cam->EstablishLink() == CE_NO_ERROR;\n}\n\n\/**\n * Méthode appelée régulièrement et permettant de reconnecter\n * la caméra dans le cas d'une déconnexion\n *\/\nvoid Capture::connexionAuto() {\n\tif(!cameraConnectee()) {\n\t\tetatCamera = CAMERA_CONNEXION_OFF;\n\t\temit stopperGuidage();\n\t\tconnecterCamera();\n\t} else {\n\t\tetatCamera = CAMERA_CONNEXION_ON;\n\t}\n\temit envoiEtatCamera(etatCamera);\n}\n\n\/**\n * Conversion d'une Image en QImage pour l'affichage dans la fenêtre principale\n * @param img\n * @return\n *\/\nQImage versQImage(Image* img) {\n\tunsigned char *img_uchar = img->versUchar();\n\t\/\/ Creation de l'index (34 va donner 34...) car Qt ne gère pas les nuances de gris\n\tQImage *temp = new QImage(img_uchar, img->getColonnes(), img->getLignes(),img->getColonnes(), QImage::Format_Indexed8);\n\tfor(int i=0;i<256;++i) { \/\/ Pour construire une image en nuances de gris (n'existe pas sinon sous Qt)\n\t\ttemp->setColor(i, qRgb(i,i,i));\n\t}\n\treturn *temp;\n}\n\n\/**\n * Etape de capture d'une image et de binning 2x2\n * @return\n *\/\nbool Capture::capturerImage() {\n if (!cameraConnectee()) {\n emit message(\"La camera n'est pas connectee\");\n return false;\n }\n CSBIGImg* img_sbig = new CSBIGImg();\n if(cam->GrabImage(img_sbig, SBDF_LIGHT_ONLY) != CE_NO_ERROR) {\n emit message(\"Impossible de lire capturer l'image : \"+QString::fromStdString(cam->GetErrorString()));\n return false;\n }\n Image* img_temp = Image::depuisSBIGImg(*img_sbig);\n delete img_sbig; \/\/ On supprime l'image CSBIGImg\n\n if(img) delete img; \/\/ On supprime la derniere image\n img = img_temp->reduire(2);\n imgPourAffichage = versQImage(img);\n\tdelete img_temp;\n\treturn true;\n}\n\n\n\/**\n * Etape de recherche de position\n *\/\nvoid Capture::trouverPosition() {\n\tif(img == NULL) {\n\t\treturn;\n\t}\n\tImage *obj_lapl = img->convoluerParDerivee();\n\tImage *correl = obj_lapl->correlation_rapide_centree(*ref_lapl, SEUIL_CORRELATION);\n\tcorrel->maxParInterpolation(&position_l, &position_c);\n\tsignalbruit = correl->calculerSignalSurBruit(position_l,position_c);\n\n#if DEBUG\n\timg->versTiff(emplacement+\"t_obj.tif\");\n\tcorrel->versTiff(emplacement+\"t_correl.tif\");\n\tobj_lapl->versTiff(emplacement+\"t_obj_lapl.tif\");\n#endif\n\n\tdelete correl;\n\tdelete obj_lapl;\n}\n\nQTime t; \/\/ pour debug de durée de correl\/capture\n\/**\n * Méthode appelée régulièrement par un timer et lançant\n * la capture puis la recherche de position, et envoyant\n * ensuite le résultat à l'instance de la classe Guidage\n *\/\nvoid Capture::captureEtPosition() {\n\tconnexionAuto();\n\tt.start();\n\tif(capturerImage() && ref_lapl) {\n\t\tcout << \"Temps ecoulé après capture : \" << t.elapsed() << \"ms\" <<endl;\n\t\ttrouverPosition();\n\t\tcout << \"Temps ecoulé après corrélation : \" << t.elapsed() << \"ms\" <<endl;\n\t\t\/\/ ENVOI DES RESULTATS\n\t\temit resultats(imgPourAffichage,position_l,position_c,diametre,signalbruit);\n\t}\n\ttimerProchaineCapture.start();\n}\n\n\/**\n * Slot de modification du diamètre du soleil\n * @param diametre\n *\/\nvoid Capture::modifierDiametre(int diametre) {\n\tif(ref_lapl) delete ref_lapl;\n\tImage *ref = Image::tracerFormeSoleil(diametre);\n\tref_lapl = ref->convoluerParDerivee();\n\n#if DEBUG\n\tref->versTiff(emplacement+\"t_ref.tif\");\n\tref_lapl->versTiff(emplacement+\"t_ref_lapl.tif\");\n#endif\n\n\tdelete ref;\n\tthis->diametre = diametre;\n}\n\n\/**\n * Recherche le meilleur diamètre pour la recherche du centre du soleil,\n * il faut avoir déjà initialisé le diametre car ne recherche qu'autour\n * du diamètre déjà présent (5 pixels autour)\n * @return le diamètre\n *\/\nint Capture::chercherDiametreProche() {\n\tdouble signalbruit_max = 0; \/\/ On recherche le meilleur signal\/bruit possible\n\tdouble diametre_optimise;\n\tImage* ref;\n\tfor(int diam = diametre-5; diam < diametre+5; diam++) {\n\t\tref = Image::tracerFormeSoleil(diam);\n\t\tif(ref_lapl) delete ref_lapl;\n\t\tref_lapl = ref->convoluerParDerivee();\n\t\tdelete ref;\n\t\ttrouverPosition();\n\t\tif(signalbruit > signalbruit_max) {\n\t\t\tsignalbruit_max = signalbruit;\n\t\t\tdiametre_optimise = diam;\n\t\t}\n\t}\n\temit diametreSoleil(diametre_optimise);\n\tmodifierDiametre(diametre_optimise);\n\treturn diametre_optimise;\n}\n<commit_msg>Correction de la fuite de mémoire présumée<commit_after>\/*\n * capture.cpp\n *\n * Created on: 24 juin 2014\n * Author: Maël Valais\n *\n *\tClasse de traitement (contrairement à fenetreprincipale.cpp qui gère l'interface)\n *\tgérant :\n *\t\t- la connexion et déconnexion avec la caméra,\n *\t\t- la capture des images avec la caméra,\n *\t\t- le calcul de la position par corrélation.\n *\n *\tLes résultats des captures sont envoyées à la classe Guidage (grâce au signal\n *\tresultats(...)).\n *\n *\tCette classe gère aussi le diamètre du soleil (on lui envoie les nouveaux diamètres\n *\tou alors elle utilise le calcul du diamètre automatique de diametre_soleil.c)\n *\n *\tL'instance de cette classe doit être exécuté dans un thread différent car dans le cas contraire,\n *\tl'interface serait bloquée.\n *\n *\n *\/\n\n#include <QtCore\/QSettings>\n\/\/ Les paramètres sont enregistrés (sous Linux) dans ~\/.config\/irap\/climso-auto.conf\n\n#include \"capture.h\"\n#include \"diametre_soleil.h\"\n\n\/**\n * Paramètres chargés pour la capture (fichier ~\/.config\/irap\/climso-auto.conf sous linux)\n * On peut modifier les paramètres par défaut en modifiant la valeur du\n * second paramètres de value(): value(\"le-nom-du-parametre\",valeurParDéfaut)\n * Certains de ces paramètres sont aussi modifiables depuis le logiciel (menu > paramètres)\n *\/\nvoid Capture::chargerParametres() {\n\tQSettings parametres(\"irap\", \"climso-auto\");\n\tdiametre = parametres.value(\"diametre-soleil-en-pixel\", 275).toInt(); \/\/ diamètre du soleil en pixels\n\tmodifierDiametre(diametre);\n\temit diametreSoleil(diametre);\n}\n\nvoid Capture::enregistrerParametres() {\n\tQSettings parametres(\"irap\", \"climso-auto\");\n\tparametres.setValue(\"diametre-soleil-en-pixel\", diametre);\n}\n\nCapture::Capture() {\n\tcam = NULL;\n\timg = NULL;\n\tref_lapl = NULL;\n\tposition_c = position_l = 0;\n\tdiametre = 0;\n\tQObject::connect(&timerProchaineCapture,SIGNAL(timeout()),this,SLOT(captureEtPosition()));\n\ttimerProchaineCapture.setSingleShot(true);\n\ttimerProchaineCapture.setInterval(DUREE_ENTRE_CAPTURES);\n\tqRegisterMetaType<EtatCamera>(\"EtatCamera\");\n\tcaptureEtPosition(); \/\/ Lancement de la première capture\n}\n\nCapture::~Capture() {\n\tenregistrerParametres();\n\tdeconnecterCamera();\n\/\/\tif(cam) delete cam; cam=NULL;\n\/\/\tif(img) delete img; img=NULL;\n\/\/\tif(ref_lapl) delete ref_lapl; ref_lapl = NULL;\n\tcout << \"Caméra deconnectée\" <<endl;\n\t\/\/ FIXME: Quand on a fait le quit(), les events sont tous traités ?\n}\n\n\/**\n * Connecte la caméra\n *\/\nvoid Capture::connecterCamera() {\n PAR_ERROR err;\n if(cam != NULL)\n delete cam;\n cam = new CSBIGCam(DEV_USB); \/\/ Creation du device USB\n if ((err = cam->GetError()) != CE_NO_ERROR) {\n emit message(\"Erreur avec la camera lors de la creation de l'objet camera : \"+QString::fromStdString(cam->GetErrorString()));\n etatCamera = CAMERA_CONNEXION_OFF;\n }\n else if ((err=cam->EstablishLink()) != CE_NO_ERROR) { \/\/ Connexion à la camera\n emit message(\"Erreur avec la camera lors de l'etablissement du lien: \"+QString::fromStdString(cam->GetErrorString()));\n etatCamera = CAMERA_CONNEXION_OFF;\n }\n else { \/\/ Pas d'erreurs, on met en binning 3x3\n cam->SetReadoutMode(RM_3X3);\n cam->SetExposureTime(DUREE_EXPOSITION * 0.001);\n cam->SetFastReadout(true);\n cam->SetABGState((ABG_STATE7)ABG_LOW7);\n\n emit message(\"Camera connectee\");\n etatCamera = CAMERA_CONNEXION_ON;\n }\n emit envoiEtatCamera(etatCamera);\n}\n\n\/**\n * Déconnecte la caméra\n *\/\nvoid Capture::deconnecterCamera() {\n if(cam) {\n cam->CloseDevice();\n emit message(\"Camera deconnectee\");\n delete cam; cam = NULL;\n etatCamera = CAMERA_CONNEXION_OFF;\n }\n else {\n emit message(\"Aucune camera n'est connectee\");\n etatCamera = CAMERA_CONNEXION_OFF;\n }\n emit envoiEtatCamera(etatCamera);\n}\n\n\/**\n * Vérifie la bonne connexion avec la caméra\n * @return\n *\/\nbool Capture::cameraConnectee() {\n return cam && cam->EstablishLink() == CE_NO_ERROR;\n}\n\n\/**\n * Méthode appelée régulièrement et permettant de reconnecter\n * la caméra dans le cas d'une déconnexion\n *\/\nvoid Capture::connexionAuto() {\n\tif(!cameraConnectee()) {\n\t\tetatCamera = CAMERA_CONNEXION_OFF;\n\t\temit stopperGuidage();\n\t\tconnecterCamera();\n\t} else {\n\t\tetatCamera = CAMERA_CONNEXION_ON;\n\t}\n\temit envoiEtatCamera(etatCamera);\n}\n\n\/**\n * Conversion d'une Image en QImage pour l'affichage dans la fenêtre principale\n * cette image est \"normalisée\".\n * @param img\n * @return\n *\/\nQImage versQImage(Image* img) {\n\tstatic unsigned char *img_uchar = NULL;\n\tif(img_uchar) delete img_uchar;\n\timg_uchar = img->versUchar();\n\t\/\/ Creation de l'index (34 va donner 34...) car Qt ne gère pas les nuances de gris\n\tQImage *temp = new QImage(img_uchar, img->getColonnes(), img->getLignes(),img->getColonnes(), QImage::Format_Indexed8);\n\tfor(int i=0;i<256;++i) { \/\/ Pour construire une image en nuances de gris (n'existe pas sinon sous Qt)\n\t\ttemp->setColor(i, qRgb(i,i,i));\n\t}\n\treturn *temp;\n}\n\n\/**\n * Etape de capture d'une image et de binning 2x2\n * @return\n *\/\nbool Capture::capturerImage() {\n if (!cameraConnectee()) {\n emit message(\"La camera n'est pas connectee\");\n return false;\n }\n CSBIGImg* img_sbig = new CSBIGImg();\n if(cam->GrabImage(img_sbig, SBDF_LIGHT_ONLY) != CE_NO_ERROR) {\n emit message(\"Impossible de lire capturer l'image : \"+QString::fromStdString(cam->GetErrorString()));\n return false;\n }\n Image* img_temp = Image::depuisSBIGImg(*img_sbig);\n delete img_sbig; \/\/ On supprime l'image CSBIGImg\n\n if(img) delete img; \/\/ On supprime la derniere image\n img = img_temp->reduire(2);\n imgPourAffichage = versQImage(img);\n\tdelete img_temp;\n\treturn true;\n}\n\n\n\/**\n * Etape de recherche de position\n *\/\nvoid Capture::trouverPosition() {\n\tif(img == NULL) {\n\t\treturn;\n\t}\n\tImage *obj_lapl = img->convoluerParDerivee();\n\tImage *correl = obj_lapl->correlation_rapide_centree(*ref_lapl, SEUIL_CORRELATION);\n\tcorrel->maxParInterpolation(&position_l, &position_c);\n\tsignalbruit = correl->calculerSignalSurBruit(position_l,position_c);\n\n#if DEBUG\n\timg->versTiff(emplacement+\"t_obj.tif\");\n\tcorrel->versTiff(emplacement+\"t_correl.tif\");\n\tobj_lapl->versTiff(emplacement+\"t_obj_lapl.tif\");\n#endif\n\n\tdelete correl;\n\tdelete obj_lapl;\n}\n\nQTime t; \/\/ pour debug de durée de correl\/capture\n\/**\n * Méthode appelée régulièrement par un timer et lançant\n * la capture puis la recherche de position, et envoyant\n * ensuite le résultat à l'instance de la classe Guidage\n *\/\nvoid Capture::captureEtPosition() {\n\tconnexionAuto();\n\tt.start();\n\tif(capturerImage() && ref_lapl) {\n\t\tcout << \"Temps ecoulé après capture : \" << t.elapsed() << \"ms\" <<endl;\n\t\ttrouverPosition();\n\t\tcout << \"Temps ecoulé après corrélation : \" << t.elapsed() << \"ms\" <<endl;\n\t\t\/\/ ENVOI DES RESULTATS\n\t\temit resultats(imgPourAffichage,position_l,position_c,diametre,signalbruit);\n\t}\n\ttimerProchaineCapture.start();\n}\n\n\/**\n * Slot de modification du diamètre du soleil\n * @param diametre\n *\/\nvoid Capture::modifierDiametre(int diametre) {\n\tif(ref_lapl) delete ref_lapl;\n\tImage *ref = Image::tracerFormeSoleil(diametre);\n\tref_lapl = ref->convoluerParDerivee();\n\n#if DEBUG\n\tref->versTiff(emplacement+\"t_ref.tif\");\n\tref_lapl->versTiff(emplacement+\"t_ref_lapl.tif\");\n#endif\n\n\tdelete ref;\n\tthis->diametre = diametre;\n}\n\n\/**\n * Recherche le meilleur diamètre pour la recherche du centre du soleil,\n * il faut avoir déjà initialisé le diametre car ne recherche qu'autour\n * du diamètre déjà présent (5 pixels autour)\n * @return le diamètre\n *\/\nint Capture::chercherDiametreProche() {\n\tdouble signalbruit_max = 0; \/\/ On recherche le meilleur signal\/bruit possible\n\tdouble diametre_optimise;\n\tImage* ref;\n\tfor(int diam = diametre-5; diam < diametre+5; diam++) {\n\t\tref = Image::tracerFormeSoleil(diam);\n\t\tif(ref_lapl) delete ref_lapl;\n\t\tref_lapl = ref->convoluerParDerivee();\n\t\tdelete ref;\n\t\ttrouverPosition();\n\t\tif(signalbruit > signalbruit_max) {\n\t\t\tsignalbruit_max = signalbruit;\n\t\t\tdiametre_optimise = diam;\n\t\t}\n\t}\n\temit diametreSoleil(diametre_optimise);\n\tmodifierDiametre(diametre_optimise);\n\treturn diametre_optimise;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <list>\n\n#ifdef DEBUG\n#include <iostream>\n#endif\n\n#ifndef CPX_INFBOUND\n#include <climits>\n#define INFBOUND INT_MAX\n#else\n#define INFBOUND CPX_INFBOUND\n#endif\n\n#include \"cluster.h\"\n#include \"sense.h\"\n#include \"thread.h\"\n#include \"lockingvars.h\"\n#include \"symgroup.h\" \/\/ S[n].size()\n\nCluster::Cluster(int nThreads, int nObj, Sense sense, bool spread_threads,\n int nObjLeft, int * ordering, int ** share_to_, int ** share_from_,\n int ** share_bounds_, int ** share_limit_, std::list<Thread*> & threads,\n Locking_Vars ** locks) {\n if (nThreads == 1) {\n \/\/ Build perm\n int * perm = new int[nObj];\n int i;\n for(i = 0; i < nObj; ++i) {\n perm[i] = ordering[i];\n }\n#ifdef DEBUG\n std::cout << \"Thread \" << threads.size() << \" using permutation \";\n std::cout << perm[0];\n for(int d = 1; d < nObj; ++d) {\n std::cout << \",\" << perm[d];\n }\n std::cout << std::endl;\n#endif\n \/\/ If there is only one objective left to add, then at the previous stage\n \/\/ we must've had 2 objectives left, and 2 threads to use (else the Thread\n \/\/ object would be constructed there), so this thread would have a partner.\n bool has_partner = (nObjLeft == 1);\n \/\/ Build thread\n Thread *t = new Thread(threads.size(), nObj, perm, share_to_, share_from_,\n share_bounds_, share_limit_, locks, has_partner);\n threads.push_back(t);\n\/\/ threads.push_back( new Thread(threads.size(), nObj, perm, shared_limits));\n } else {\n int *my_ordering = new int[nObj];\n#ifdef DEBUG\n std::cout << \"Working with permutation \";\n std::cout << ordering[0];\n for(int d = 1; d < nObj; ++d) {\n std::cout << \",\" << ordering[d];\n }\n std::cout << \" and \" << nObjLeft << \" objectives left.\";\n std::cout << std::endl;\n#endif\n for(int i = 0; i < nObj; ++i) {\n my_ordering[i] = ordering[i];\n }\n int ** share_to = new int*[nObj];\n int ** share_from = new int*[nObj];\n int ** share_limit = new int*[nObj];\n int ** share_bounds = new int*[nObj];\n for(int j = 0; j < nObj; ++j) {\n share_to[j] = share_to_[j];\n share_bounds[j] = share_bounds_[j];\n share_from[j] = share_from_[j];\n share_limit[j] = share_limit_[j];\n }\n \/\/ Work out how many different objectives will occur\n \/\/ in position \"nObjLeft - 1\"\n int ind = nObjLeft;\n int ** new_shares = new int*[nObj] {nullptr};\n int ** new_bounds = new int*[nObj] {nullptr};\n int ** new_limit = new int*[nObj] {nullptr};\n int num_sub_clusters = (ind < nThreads) ? ind : nThreads;\n for(int j = 0; j < num_sub_clusters; ++j) {\n int pos = my_ordering[nObjLeft - j - 1];\n new_shares[pos] = new int;\n new_bounds[pos] = new int;\n new_limit[pos] = new int;\n if (sense == MIN) {\n *new_shares[pos] = INFBOUND;\n *new_bounds[pos] = -INFBOUND;\n *new_limit[pos] = INFBOUND;\n } else {\n *new_shares[pos] = -INFBOUND;\n *new_bounds[pos] = INFBOUND;\n *new_limit[pos] = -INFBOUND;\n }\n }\n\n if (spread_threads) {\n \/\/ Split up threads\n int perCluster = nThreads \/ nObjLeft;\n int withExtra = nThreads % nObjLeft;\n int i;\n for(i = 0; i < withExtra ; ++i) {\n int pos = my_ordering[nObjLeft-1];\n locks[pos] = new Locking_Vars(perCluster + 1);\n int * old_share_to = share_to[pos];\n int * old_share_bounds = share_bounds[pos];\n int * old_share_limit = share_limit[pos];\n int ** old_from = new int*[nObj];\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n old_from[obj] = share_from[obj];\n }\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n if (obj == pos) {\n share_to[obj] = new_shares[obj];\n share_bounds[obj] = new_bounds[obj];\n share_limit[obj] = new_limit[obj];\n } else {\n share_from[obj] = new_shares[obj];\n }\n }\n Cluster(perCluster + 1, nObj, sense, spread_threads, nObjLeft - 1,\n my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks);\n share_to[pos] = old_share_to;\n share_bounds[pos] = old_share_bounds;\n share_limit[pos] = old_share_limit;\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n share_from[obj] = old_from[obj];\n }\n \/\/ Rotate ordering\n int first = my_ordering[0];\n for (int c = 0; c < nObjLeft-1; ++c) {\n my_ordering[c] = my_ordering[c+1];\n }\n my_ordering[nObjLeft - 1] = first;\n locks[pos] = nullptr;\n }\n if (perCluster > 0) {\n for( ; i < nObjLeft ; ++i) {\n int pos = my_ordering[nObjLeft-1];\n int * old_share_to = share_to[pos];\n int * old_share_bounds = share_bounds[pos];\n int * old_share_limit = share_limit[pos];\n locks[pos] = new Locking_Vars(perCluster);\n int ** old_from = new int*[nObj];\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n old_from[obj] = share_from[obj];\n }\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n if (obj == pos) {\n share_to[obj] = new_shares[obj];\n share_bounds[obj] = new_bounds[obj];\n share_limit[obj] = new_limit[obj];\n } else {\n share_from[obj] = new_shares[obj];\n }\n }\n Cluster(perCluster, nObj, sense, spread_threads, nObjLeft - 1,\n my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks);\n share_to[pos] = old_share_to;\n share_bounds[pos] = old_share_bounds;\n share_limit[pos] = old_share_limit;\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n share_from[obj] = old_from[obj];\n }\n \/\/ Rotate ordering\n int first = my_ordering[0];\n for (int c = 0; c < nObjLeft-1; ++c) {\n my_ordering[c] = my_ordering[c+1];\n }\n my_ordering[nObjLeft - 1] = first;\n locks[pos] = nullptr;\n }\n }\n } else { \/\/ grouping threads \"near\" each other\n int threads_remaining = nThreads;\n while (threads_remaining > 0) {\n int threads_to_use = (S[nObjLeft-1].size() > threads_remaining) ? threads_remaining : S[nObjLeft-1].size();\n int pos = my_ordering[nObjLeft-1];\n locks[pos] = new Locking_Vars(threads_to_use);\n int * old_share_to = share_to[pos];\n int * old_share_bounds = share_bounds[pos];\n int * old_share_limit = share_limit[pos];\n int ** old_from = new int*[nObj];\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n old_from[obj] = share_from[obj];\n }\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n if (obj == pos) {\n share_to[obj] = new_shares[obj];\n share_bounds[pos] = new_bounds[obj];\n share_limit[obj] = new_limit[obj];\n } else {\n share_from[obj] = new_shares[obj];\n }\n }\n Cluster(threads_to_use, nObj, sense, spread_threads, nObjLeft - 1,\n my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks);\n threads_remaining -= threads_to_use;\n share_to[pos] = old_share_to;\n share_bounds[pos] = old_share_bounds;\n share_limit[pos] = old_share_limit;\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n share_from[obj] = old_from[obj];\n }\n \/\/ Rotate ordering\n int first = my_ordering[0];\n for (int c = 0; c < nObjLeft-1; ++c) {\n my_ordering[c] = my_ordering[c+1];\n }\n my_ordering[nObjLeft - 1] = first;\n locks[pos] = nullptr;\n }\n }\n delete[] my_ordering;\n delete[] new_shares;\n delete[] new_limit;\n delete[] share_to;\n delete[] share_from;\n delete[] share_limit;\n delete[] share_bounds;\n }\n}\n<commit_msg>Tweak debugging output<commit_after>#include <list>\n\n#ifdef DEBUG\n#include <iostream>\n#endif\n\n#ifndef CPX_INFBOUND\n#include <climits>\n#define INFBOUND INT_MAX\n#else\n#define INFBOUND CPX_INFBOUND\n#endif\n\n#include \"cluster.h\"\n#include \"sense.h\"\n#include \"thread.h\"\n#include \"lockingvars.h\"\n#include \"symgroup.h\" \/\/ S[n].size()\n\nCluster::Cluster(int nThreads, int nObj, Sense sense, bool spread_threads,\n int nObjLeft, int * ordering, int ** share_to_, int ** share_from_,\n int ** share_bounds_, int ** share_limit_, std::list<Thread*> & threads,\n Locking_Vars ** locks) {\n if (nThreads == 1) {\n \/\/ Build perm\n int * perm = new int[nObj];\n int i;\n for(i = 0; i < nObj; ++i) {\n perm[i] = ordering[i];\n }\n#ifdef DEBUG\n std::cout << \"Thread \" << threads.size() << \" using permutation \";\n std::cout << perm[0];\n for(int d = 1; d < nObj; ++d) {\n std::cout << \",\" << perm[d];\n }\n std::cout << std::endl;\n#endif\n \/\/ If there is only one objective left to add, then at the previous stage\n \/\/ we must've had 2 objectives left, and 2 threads to use (else the Thread\n \/\/ object would be constructed there), so this thread would have a partner.\n bool has_partner = (nObjLeft == 1);\n \/\/ Build thread\n Thread *t = new Thread(threads.size(), nObj, perm, share_to_, share_from_,\n share_bounds_, share_limit_, locks, has_partner);\n threads.push_back(t);\n\/\/ threads.push_back( new Thread(threads.size(), nObj, perm, shared_limits));\n } else {\n int *my_ordering = new int[nObj];\n#ifdef DEBUG\n std::cout << \"Working with permutation \";\n std::cout << ordering[0];\n for(int d = 1; d < nObj; ++d) {\n std::cout << \",\" << ordering[d];\n }\n std::cout << \", \" << nThreads << \" threads left,\";\n std::cout << \" and \" << nObjLeft << \" objectives left.\";\n std::cout << std::endl;\n#endif\n for(int i = 0; i < nObj; ++i) {\n my_ordering[i] = ordering[i];\n }\n int ** share_to = new int*[nObj];\n int ** share_from = new int*[nObj];\n int ** share_limit = new int*[nObj];\n int ** share_bounds = new int*[nObj];\n for(int j = 0; j < nObj; ++j) {\n share_to[j] = share_to_[j];\n share_bounds[j] = share_bounds_[j];\n share_from[j] = share_from_[j];\n share_limit[j] = share_limit_[j];\n }\n \/\/ Work out how many different objectives will occur\n \/\/ in position \"nObjLeft - 1\"\n int ind = nObjLeft;\n int ** new_shares = new int*[nObj] {nullptr};\n int ** new_bounds = new int*[nObj] {nullptr};\n int ** new_limit = new int*[nObj] {nullptr};\n int num_sub_clusters = (ind < nThreads) ? ind : nThreads;\n for(int j = 0; j < num_sub_clusters; ++j) {\n int pos = my_ordering[nObjLeft - j - 1];\n new_shares[pos] = new int;\n new_bounds[pos] = new int;\n new_limit[pos] = new int;\n if (sense == MIN) {\n *new_shares[pos] = INFBOUND;\n *new_bounds[pos] = -INFBOUND;\n *new_limit[pos] = INFBOUND;\n } else {\n *new_shares[pos] = -INFBOUND;\n *new_bounds[pos] = INFBOUND;\n *new_limit[pos] = -INFBOUND;\n }\n }\n\n if (spread_threads) {\n \/\/ Split up threads\n int perCluster = nThreads \/ nObjLeft;\n int withExtra = nThreads % nObjLeft;\n int i;\n for(i = 0; i < withExtra ; ++i) {\n int pos = my_ordering[nObjLeft-1];\n locks[pos] = new Locking_Vars(perCluster + 1);\n int * old_share_to = share_to[pos];\n int * old_share_bounds = share_bounds[pos];\n int * old_share_limit = share_limit[pos];\n int ** old_from = new int*[nObj];\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n old_from[obj] = share_from[obj];\n }\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n if (obj == pos) {\n share_to[obj] = new_shares[obj];\n share_bounds[obj] = new_bounds[obj];\n share_limit[obj] = new_limit[obj];\n } else {\n share_from[obj] = new_shares[obj];\n }\n }\n Cluster(perCluster + 1, nObj, sense, spread_threads, nObjLeft - 1,\n my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks);\n share_to[pos] = old_share_to;\n share_bounds[pos] = old_share_bounds;\n share_limit[pos] = old_share_limit;\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n share_from[obj] = old_from[obj];\n }\n \/\/ Rotate ordering\n int first = my_ordering[0];\n for (int c = 0; c < nObjLeft-1; ++c) {\n my_ordering[c] = my_ordering[c+1];\n }\n my_ordering[nObjLeft - 1] = first;\n locks[pos] = nullptr;\n }\n if (perCluster > 0) {\n for( ; i < nObjLeft ; ++i) {\n int pos = my_ordering[nObjLeft-1];\n int * old_share_to = share_to[pos];\n int * old_share_bounds = share_bounds[pos];\n int * old_share_limit = share_limit[pos];\n locks[pos] = new Locking_Vars(perCluster);\n int ** old_from = new int*[nObj];\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n old_from[obj] = share_from[obj];\n }\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n if (obj == pos) {\n share_to[obj] = new_shares[obj];\n share_bounds[obj] = new_bounds[obj];\n share_limit[obj] = new_limit[obj];\n } else {\n share_from[obj] = new_shares[obj];\n }\n }\n Cluster(perCluster, nObj, sense, spread_threads, nObjLeft - 1,\n my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks);\n share_to[pos] = old_share_to;\n share_bounds[pos] = old_share_bounds;\n share_limit[pos] = old_share_limit;\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n share_from[obj] = old_from[obj];\n }\n \/\/ Rotate ordering\n int first = my_ordering[0];\n for (int c = 0; c < nObjLeft-1; ++c) {\n my_ordering[c] = my_ordering[c+1];\n }\n my_ordering[nObjLeft - 1] = first;\n locks[pos] = nullptr;\n }\n }\n } else { \/\/ grouping threads \"near\" each other\n int threads_remaining = nThreads;\n while (threads_remaining > 0) {\n int threads_to_use = (S[nObjLeft-1].size() > threads_remaining) ? threads_remaining : S[nObjLeft-1].size();\n int pos = my_ordering[nObjLeft-1];\n locks[pos] = new Locking_Vars(threads_to_use);\n int * old_share_to = share_to[pos];\n int * old_share_bounds = share_bounds[pos];\n int * old_share_limit = share_limit[pos];\n int ** old_from = new int*[nObj];\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n old_from[obj] = share_from[obj];\n }\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n if (obj == pos) {\n share_to[obj] = new_shares[obj];\n share_bounds[pos] = new_bounds[obj];\n share_limit[obj] = new_limit[obj];\n } else {\n share_from[obj] = new_shares[obj];\n }\n }\n Cluster(threads_to_use, nObj, sense, spread_threads, nObjLeft - 1,\n my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks);\n threads_remaining -= threads_to_use;\n share_to[pos] = old_share_to;\n share_bounds[pos] = old_share_bounds;\n share_limit[pos] = old_share_limit;\n for(int j = 0; j < nObjLeft; ++j) {\n int obj = my_ordering[j];\n share_from[obj] = old_from[obj];\n }\n \/\/ Rotate ordering\n int first = my_ordering[0];\n for (int c = 0; c < nObjLeft-1; ++c) {\n my_ordering[c] = my_ordering[c+1];\n }\n my_ordering[nObjLeft - 1] = first;\n locks[pos] = nullptr;\n }\n }\n delete[] my_ordering;\n delete[] new_shares;\n delete[] new_limit;\n delete[] share_to;\n delete[] share_from;\n delete[] share_limit;\n delete[] share_bounds;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 The Imaging Source Europe 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\n#include <iostream>\n#include <stdexcept>\n\n#include \"UsbHandler.h\"\n#include \"LibusbDevice.h\"\n\n#include \"logging.h\"\n\n#include <cstring>\n\nnamespace tcam\n{\n\nUsbHandler& UsbHandler::get_instance ()\n{\n static UsbHandler instance;\n\n return instance;\n}\n\n\nUsbHandler::UsbHandler ():\n session(new UsbSession())\n{}\n\n\nUsbHandler::~UsbHandler()\n{}\n\n\nstruct libusb_device_handle* UsbHandler::open_device (const std::string& serial)\n{\n struct libusb_device_handle* ret = nullptr;\n\n libusb_device** devs;\n\n int cnt = libusb_get_device_list(this->session->get_session(), &devs);\n\n if (cnt < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device list. \" + std::to_string(cnt));\n }\n\n for (ssize_t i = 0; i < cnt; i++)\n {\n libusb_device_descriptor desc;\n int r = libusb_get_device_descriptor(devs[i], &desc);\n if (r < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device descriptor. \" + std::to_string(cnt));\n }\n\n \/\/ ignore all devices that are not from TIS or otherwise needed\n if (desc.idVendor != 0x199e)\n continue;\n\n if (desc.idProduct != 0x8209 && desc.idProduct != 0x0804)\n continue;\n\n r = libusb_open(devs[i], &ret);\n\n if (r < 0)\n {\n tcam_log(TCAM_LOG_ERROR, \"Unable to open device.\");\n continue;\n }\n\n char tmp_str[sizeof(tcam_device_info::serial_number)];\n\n libusb_get_string_descriptor_ascii(ret, desc.iSerialNumber,\n (unsigned char*)tmp_str,\n sizeof(tcam_device_info::serial_number));\n if (serial.compare(tmp_str) == 0)\n {\n\n break;\n }\n\n libusb_close(ret);\n\n }\n\n libusb_free_device_list(devs, 1);\n\n\n return ret;\n}\n\n\nstd::vector<DeviceInfo> UsbHandler::get_device_list ()\n{\n libusb_device** devs;\n\n int cnt = libusb_get_device_list(this->session->get_session(), &devs);\n\n if (cnt < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device list. \" + std::to_string(cnt));\n }\n\n std::vector<DeviceInfo> ret;\n ret.reserve(5);\n\n for (ssize_t i = 0; i < cnt; i++)\n {\n libusb_device_descriptor desc;\n int r = libusb_get_device_descriptor(devs[i], &desc);\n if (r < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device descriptor. \" + std::to_string(cnt));\n }\n\n \/\/ ignore all devices that are not from TIS or otherwise needed\n if (desc.idVendor != 0x199e)\n continue;\n\n if (desc.idProduct != 0x8209 && desc.idProduct != 0x0804)\n continue;\n\n tcam_device_info d = { };\n\n d.type = TCAM_DEVICE_TYPE_LIBUSB;\n\n \/\/ d.idVendor = desc.idVendor;\n \/\/ d.idProduct = desc.idProduct;\n\n \/\/ strcpy(d.name, \"AFU050\");\n \/\/ strcpy(d.serial_number, \"47614135\");\n \/\/ strcpy(d.additional_identifier, \"9209\");\n\n libusb_device_handle* dh;\n r = libusb_open(devs[i], &dh);\n\n if (r < 0)\n {\n tcam_log(TCAM_LOG_ERROR, \"Unable to open device.\");\n continue;\n }\n\n libusb_get_string_descriptor_ascii(dh, desc.iProduct, (unsigned char*)d.name, sizeof(d.name));\n\n \/\/ libusb_get_string_descriptor_ascii(dh, desc.iManufacturer, (unsigned char*)d.manufacturer, sizeof(d.manufacturer));\n \/\/ int lib_ret = libusb_get_port_numbers(dh, (uint8_t*)d.identifier, sizeof(d.identifier))\n\n libusb_get_string_descriptor_ascii(dh, desc.idProduct, (unsigned char*)d.additional_identifier, sizeof(d.additional_identifier));\n libusb_get_string_descriptor_ascii(dh, desc.iSerialNumber, (unsigned char*)d.serial_number, sizeof(d.serial_number));\n\n libusb_close(dh);\n ret.push_back(DeviceInfo(d));\n }\n\n libusb_free_device_list(devs, 1);\n\n return ret;\n}\n\n\n\/\/ std::shared_ptr<UsbCamera> UsbHandler::open_camera (std::string serial_number)\n\/\/ {\n\/\/ auto list = get_device_list();\n\/\/ device_info d;\n\n\/\/ for (auto& dev : list)\n\/\/ {\n\/\/ \/\/ std::cout << \"Comparing |\" << dev.serial << \"|\" << (unsigned char*)serial_number.c_str() << \"|\" << std::endl;\n\/\/ if (serial_number.compare(dev.serial) == 0)\n\/\/ {\n\/\/ \/\/ std::cout << \"dev.serial \" << dev.serial << \";serial \" << serial_number << std::endl;\n\/\/ d = dev;\n\/\/ break;\n\/\/ }\n\/\/ }\n\n\/\/ camera_type t = find_camera_type(d.idVendor, d.idProduct);\n\n\n\/\/ switch(t.camera_type)\n\/\/ {\n\/\/ case USB33:\n\/\/ return std::make_shared<Usb33Camera>(this->session, d);\n\/\/ case USB3:\n\/\/ return std::make_shared<Usb3Camera>(this->session, d);\n\/\/ case USB2:\n\/\/ return std::make_shared<Usb2Camera>(this->session, d);\n\/\/ case UNKNOWN:\n\/\/ default:\n\/\/ return nullptr;\n\/\/ }\n\/\/ }\n\n\nstd::shared_ptr<UsbSession> UsbHandler::get_session ()\n{\n return this->session;\n}\n\n}; \/* namespace tis *\/\n<commit_msg>Remove dead sections<commit_after>\/*\n * Copyright 2014 The Imaging Source Europe 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\n#include <iostream>\n#include <stdexcept>\n\n#include \"UsbHandler.h\"\n#include \"LibusbDevice.h\"\n\n#include \"logging.h\"\n\n#include <cstring>\n\nnamespace tcam\n{\n\nUsbHandler& UsbHandler::get_instance ()\n{\n static UsbHandler instance;\n\n return instance;\n}\n\n\nUsbHandler::UsbHandler ():\n session(new UsbSession())\n{}\n\n\nUsbHandler::~UsbHandler()\n{}\n\n\nstruct libusb_device_handle* UsbHandler::open_device (const std::string& serial)\n{\n struct libusb_device_handle* ret = nullptr;\n\n libusb_device** devs;\n\n int cnt = libusb_get_device_list(this->session->get_session(), &devs);\n\n if (cnt < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device list. \" + std::to_string(cnt));\n }\n\n for (ssize_t i = 0; i < cnt; i++)\n {\n libusb_device_descriptor desc;\n int r = libusb_get_device_descriptor(devs[i], &desc);\n if (r < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device descriptor. \" + std::to_string(cnt));\n }\n\n \/\/ ignore all devices that are not from TIS or otherwise needed\n if (desc.idVendor != 0x199e)\n continue;\n\n if (desc.idProduct != 0x8209 && desc.idProduct != 0x0804)\n continue;\n\n r = libusb_open(devs[i], &ret);\n\n if (r < 0)\n {\n tcam_log(TCAM_LOG_ERROR, \"Unable to open device.\");\n continue;\n }\n\n char tmp_str[sizeof(tcam_device_info::serial_number)];\n\n libusb_get_string_descriptor_ascii(ret, desc.iSerialNumber,\n (unsigned char*)tmp_str,\n sizeof(tcam_device_info::serial_number));\n if (serial.compare(tmp_str) == 0)\n {\n\n break;\n }\n\n libusb_close(ret);\n\n }\n\n libusb_free_device_list(devs, 1);\n\n\n return ret;\n}\n\n\nstd::vector<DeviceInfo> UsbHandler::get_device_list ()\n{\n libusb_device** devs;\n\n int cnt = libusb_get_device_list(this->session->get_session(), &devs);\n\n if (cnt < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device list. \" + std::to_string(cnt));\n }\n\n std::vector<DeviceInfo> ret;\n ret.reserve(5);\n\n for (ssize_t i = 0; i < cnt; i++)\n {\n libusb_device_descriptor desc;\n int r = libusb_get_device_descriptor(devs[i], &desc);\n if (r < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device descriptor. \" + std::to_string(cnt));\n }\n\n \/\/ ignore all devices that are not from TIS or otherwise needed\n if (desc.idVendor != 0x199e)\n continue;\n\n if (desc.idProduct != 0x8209 && desc.idProduct != 0x0804)\n continue;\n\n tcam_device_info d = { };\n\n d.type = TCAM_DEVICE_TYPE_LIBUSB;\n\n libusb_device_handle* dh;\n r = libusb_open(devs[i], &dh);\n\n if (r < 0)\n {\n tcam_log(TCAM_LOG_ERROR, \"Unable to open device.\");\n continue;\n }\n\n libusb_get_string_descriptor_ascii(dh, desc.iProduct, (unsigned char*)d.name, sizeof(d.name));\n libusb_get_string_descriptor_ascii(dh, desc.idProduct, (unsigned char*)d.additional_identifier, sizeof(d.additional_identifier));\n libusb_get_string_descriptor_ascii(dh, desc.iSerialNumber, (unsigned char*)d.serial_number, sizeof(d.serial_number));\n\n libusb_close(dh);\n ret.push_back(DeviceInfo(d));\n }\n\n libusb_free_device_list(devs, 1);\n\n return ret;\n}\n\n\nstd::shared_ptr<UsbSession> UsbHandler::get_session ()\n{\n return this->session;\n}\n\n}; \/* namespace tis *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"internal.hpp\"\n#include \"external.hpp\"\n#include \"macros.hpp\"\n#include \"message.hpp\"\n\nnamespace CaDiCaL {\n\n\/*------------------------------------------------------------------------*\/\n\n\/\/ Compactifying removes holes generated by inactive variables (fixed,\n\/\/ eliminated or substituted) by mapping active variables indices down to a\n\/\/ contiguous interval of indices.\n\n\/*------------------------------------------------------------------------*\/\n\nbool Internal::compactifying () {\n if (!opts.compact) return false;\n if (stats.conflicts < lim.compact) return false;\n int inactive = max_var - active_variables ();\n assert (inactive >= 0);\n if (!inactive) return false;\n return inactive >= opts.compactlim * max_var;\n}\n\n\/*------------------------------------------------------------------------*\/\n\n\/\/ Map data in old array 'NAME' to new position as given by 'map'.\n\n#define MAP_ARRAY(TYPE,NAME) \\\ndo { \\\n TYPE * TMP = new TYPE [new_vsize]; \\\n for (int SRC = 1; SRC <= max_var; SRC++) { \\\n const int DST = map[SRC]; \\\n if (!DST) continue; \\\n TMP[DST] = NAME[SRC]; \\\n } \\\n memset (TMP, 0, sizeof TMP[0]); \\\n delete [] NAME; \\\n NAME = TMP; \\\n} while (0)\n\n\/*------------------------------------------------------------------------*\/\n\n\/\/ Same as 'MAP_ARRAY' but two sided (positive & negative literal).\n\n#define MAP2_ARRAY(TYPE,NAME) \\\ndo { \\\n TYPE * TMP = new TYPE [2*new_vsize]; \\\n for (int SRC = 1; SRC <= max_var; SRC++) { \\\n const int DST = map[SRC]; \\\n if (!DST) continue; \\\n TMP[2*DST] = NAME[2*SRC]; \\\n TMP[2*DST+1] = NAME[2*SRC+1]; \\\n } \\\n memset (TMP, 0, sizeof TMP[0]); \\\n delete [] NAME; \\\n NAME = TMP; \\\n} while (0)\n\n\/*------------------------------------------------------------------------*\/\n\n\/\/ Map a 'vector<int>' of literals, flush inactive literals, resize and\n\/\/ shrink it to fit its new size after flushing.\n\n#define MAP_AND_FLUSH_INT_VECTOR(V) \\\ndo { \\\n const const_int_iterator end = V.end (); \\\n int_iterator j = V.begin (); \\\n const_int_iterator i; \\\n for (i = j; i != end; i++) { \\\n const int SRC = *i; \\\n int DST = map[abs (SRC)]; \\\n if (!DST) continue; \\\n if (SRC < 0) DST = -DST; \\\n *j++ = DST; \\\n } \\\n V.resize (j - V.begin ()); \\\n shrink_vector (V); \\\n} while (0)\n\n\/*------------------------------------------------------------------------*\/\n\nvoid Internal::compact () {\n START (compact);\n stats.compacts++;\n\n if (level) backtrack ();\n\n assert (!conflict);\n assert (clause.empty ());\n assert (levels.empty ());\n assert (analyzed.empty ());\n assert (minimized.empty ());\n assert (control.size () == 1);\n assert (resolved.empty ());\n\n \/\/ We produce a compactifying garbage collector like map of old 'src' to\n \/\/ new 'dst' variables. Inactive variables are just skipped except for\n \/\/ fixed ones which will be mapped to the first fixed variable (in the\n \/\/ appropriate phase). This avoids to handle the case 'fixed value'\n \/\/ seperately as it is done in Lingeling, where fixed variables are\n \/\/ mapped to the internal variable '1'.\n \/\/\n int * map, dst = 0, first_fixed = 0;\n NEW (map, int, max_var + 1);\n map[0] = 0;\n for (int src = 1; src <= max_var; src++) {\n const Flags & f = flags (src);\n if (f.active ()) map[src] = ++dst;\n else if (!f.fixed () || first_fixed) map[src] = 0;\n else map[first_fixed = src] = ++dst;\n }\n\n if (first_fixed) LOG (\"found first fixed %d\", first_fixed);\n else LOG (\"no variable fixed\");\n\n const int new_max_var = dst;\n const size_t new_vsize = dst + 1;\t\/\/ Adjust to fit 'new_max_var'.\n\n \/*----------------------------------------------------------------------*\/\n \/\/ In this first part we only map stuff without reallocation.\n \/*----------------------------------------------------------------------*\/\n\n \/\/ Flush the external indices. This has to occur before we map 'vals'.\n {\n const int first_fixed_val = first_fixed ? val (first_fixed) : 0;\n for (int eidx = 1; eidx <= external->max_var; eidx++) {\n const int src = external->e2i[eidx];\n int dst, tmp;\n if (!src) dst = 0;\n else if (!(dst = map[src]) && (tmp = val (src))) {\n\tassert (first_fixed_val);\n\tdst = (tmp != first_fixed_val) ? -first_fixed : first_fixed;\n }\n LOG (\"external %d mapped to internal %d\", eidx, dst);\n external->e2i[eidx] = dst;\n }\n }\n\n \/\/ Map the literals in all clauses.\n {\n const const_clause_iterator end = clauses.end ();\n const_clause_iterator i;\n for (i = clauses.begin (); i != end; i++) {\n Clause * c = *i;\n assert (!c->garbage);\n const const_literal_iterator eoc = c->end ();\n literal_iterator j;\n for (j = c->begin (); j != eoc; j++) {\n\tconst int lit = *j;\n\tassert (active (lit));\n\tint dst = map[abs (lit)];\n\tif (lit < 0) dst = -dst;\n\tassert (dst);\n\t*j = dst;\n }\n }\n }\n\n \/\/ Map the blocking literals in all watches.\n \/\/\n if (watches ()) {\n for (int idx = 1; idx <= max_var; idx++) {\n for (int sign = -1; sign <= 1; sign += 2) {\n\tconst int lit = sign*idx;\n\tWatches & ws = watches (lit);\n\tconst const_watch_iterator end = ws.end ();\n\twatch_iterator i;\n\tfor (i = ws.begin (); i != end; i++) {\n\t const int blit = i->blit;\n\t assert (active (blit));\n\t int dst = map[abs (blit)];\n\t if (blit < 0) dst = -dst;\n\t assert (dst);\n\t i->blit = dst;\n\t}\n }\n }\n }\n\n \/\/ We first flush inactive variables and map the links in the queue. This\n \/\/ has to be done before we map the actual links data structure 'ltab'.\n {\n int prev = 0, mapped_prev = 0, next;\n for (int idx = queue.first; idx; idx = next) {\n Link * l = ltab + idx;\n next = l->next;\n if (idx == first_fixed) continue;\n const int dst = map[idx];\n if (!dst) continue;\n assert (active (idx));\n if (prev) ltab[prev].next = dst; else queue.first = dst;\n l->prev = mapped_prev;\n mapped_prev = dst;\n prev = idx;\n }\n if (prev) ltab[prev].next = 0; else queue.first = 0;\n queue.unassigned = queue.last = mapped_prev;\n }\n\n \/*----------------------------------------------------------------------*\/\n \/\/ In this second part we not only map stuff but also reallocate memory.\n \/*----------------------------------------------------------------------*\/\n\n \/\/ Now we continue in reverse order of allocated bytes, e.g., see\n \/\/ 'Internal::enlarge' which reallocates in order of allocated bytes.\n\n MAP_ARRAY (Flags, ftab);\n MAP_ARRAY (signed char, marks);\n MAP_ARRAY (signed char, phases);\n\n \/\/ Special case for 'val' as always since for 'val' we trade branch less\n \/\/ code for memory and always allocated an [-maxvar,...,maxvar] array.\n {\n signed char * new_vals = new signed char [2*new_vsize];\n new_vals += new_vsize;\n for (int src = -max_var; src <= -1; src++)\n new_vals[-map[-src]] = vals[src];\n for (int src = 1; src <= max_var; src++)\n new_vals[map[src]] = vals[src];\n new_vals[0] = 0;\n vals -= vsize;\n delete [] vals;\n vals = new_vals;\n }\n\n MAP_ARRAY (int, i2e);\n MAP2_ARRAY (int, ptab);\n MAP_ARRAY (long, btab);\n if (ntab2) MAP_ARRAY (long, ntab2);\n MAP_ARRAY (Link, ltab);\n MAP_ARRAY (Var, vtab);\n if (ntab) MAP2_ARRAY (long, ntab);\n if (wtab) MAP2_ARRAY (Watches, wtab);\n if (otab) MAP2_ARRAY (Occs, otab);\n if (big) MAP2_ARRAY (Bins, big);\n\n assert (propagated == trail.size ());\n MAP_AND_FLUSH_INT_VECTOR (trail);\n propagated = trail.size ();\n\n if (!probes.empty ()) MAP_AND_FLUSH_INT_VECTOR (probes);\n\n \/\/ The simplest way to map the elimination schedule is to get all elements\n \/\/ from the heap and reinsert them. This could be slightly improved in\n \/\/ terms of speed if we add a 'flush (int * map)' function to 'Heap', but\n \/\/ is pretty complicated and would require that the 'Heap' knows that\n \/\/ mapped elements with 'zero' destination should be flushed. Note that\n \/\/ we use stable heap sorting.\n \/\/\n if (!esched.empty ()) {\n vector<int> saved;\n while (!esched.empty ()) {\n const int src = esched.front ();\n esched.pop_front ();\n const int dst = map [src];\n if (dst && src != first_fixed) saved.push_back (dst);\n }\n esched.clear ();\n const const_int_iterator end = saved.end ();\n const_int_iterator i;\n for (i = saved.begin (); i != end; i++)\n esched.push_back (*i);\n esched.shrink ();\n }\n\n \/*----------------------------------------------------------------------*\/\n\n DEL (map, int, max_var);\n\n VRB (\"compact\", stats.compacts,\n \"reducing internal variables from %d to %d\",\n max_var, new_max_var);\n\n max_var = new_max_var;\n vsize = new_vsize;\n\n stats.now.fixed = first_fixed ? 1 : 0;\n stats.now.substituted = stats.now.eliminated = 0;\n\n inc.compact += opts.compactint;\n lim.compact = stats.conflicts + inc.compact;\n report ('c');\n STOP (compact);\n}\n\n};\n<commit_msg>fixed another compact issue<commit_after>#include \"internal.hpp\"\n#include \"external.hpp\"\n#include \"macros.hpp\"\n#include \"message.hpp\"\n\nnamespace CaDiCaL {\n\n\/*------------------------------------------------------------------------*\/\n\n\/\/ Compactifying removes holes generated by inactive variables (fixed,\n\/\/ eliminated or substituted) by mapping active variables indices down to a\n\/\/ contiguous interval of indices.\n\n\/*------------------------------------------------------------------------*\/\n\nbool Internal::compactifying () {\n if (!opts.compact) return false;\n if (stats.conflicts < lim.compact) return false;\n int inactive = max_var - active_variables ();\n assert (inactive >= 0);\n if (!inactive) return false;\n return inactive >= opts.compactlim * max_var;\n}\n\n\/*------------------------------------------------------------------------*\/\n\n\/\/ Map data in old array 'NAME' to new position as given by 'map'.\n\n#define MAP_ARRAY(TYPE,NAME) \\\ndo { \\\n TYPE * TMP = new TYPE [new_vsize]; \\\n for (int SRC = 1; SRC <= max_var; SRC++) { \\\n const int DST = map[SRC]; \\\n if (!DST) continue; \\\n TMP[DST] = NAME[SRC]; \\\n } \\\n memset (TMP, 0, sizeof TMP[0]); \\\n delete [] NAME; \\\n NAME = TMP; \\\n} while (0)\n\n\/*------------------------------------------------------------------------*\/\n\n\/\/ Same as 'MAP_ARRAY' but two sided (positive & negative literal).\n\n#define MAP2_ARRAY(TYPE,NAME) \\\ndo { \\\n TYPE * TMP = new TYPE [2*new_vsize]; \\\n for (int SRC = 1; SRC <= max_var; SRC++) { \\\n const int DST = map[SRC]; \\\n if (!DST) continue; \\\n TMP[2*DST] = NAME[2*SRC]; \\\n TMP[2*DST+1] = NAME[2*SRC+1]; \\\n } \\\n memset (TMP, 0, sizeof TMP[0]); \\\n delete [] NAME; \\\n NAME = TMP; \\\n} while (0)\n\n\/*------------------------------------------------------------------------*\/\n\n\/\/ Map a 'vector<int>' of literals, flush inactive literals, resize and\n\/\/ shrink it to fit its new size after flushing.\n\n#define MAP_AND_FLUSH_INT_VECTOR(V) \\\ndo { \\\n const const_int_iterator end = V.end (); \\\n int_iterator j = V.begin (); \\\n const_int_iterator i; \\\n for (i = j; i != end; i++) { \\\n const int SRC = *i; \\\n int DST = map[abs (SRC)]; \\\n if (!DST) continue; \\\n if (SRC < 0) DST = -DST; \\\n *j++ = DST; \\\n } \\\n V.resize (j - V.begin ()); \\\n shrink_vector (V); \\\n} while (0)\n\n\/*------------------------------------------------------------------------*\/\n\nvoid Internal::compact () {\n START (compact);\n stats.compacts++;\n\n if (level) backtrack ();\n\n assert (!conflict);\n assert (clause.empty ());\n assert (levels.empty ());\n assert (analyzed.empty ());\n assert (minimized.empty ());\n assert (control.size () == 1);\n assert (resolved.empty ());\n\n \/\/ We produce a compactifying garbage collector like map of old 'src' to\n \/\/ new 'dst' variables. Inactive variables are just skipped except for\n \/\/ fixed ones which will be mapped to the first fixed variable (in the\n \/\/ appropriate phase). This avoids to handle the case 'fixed value'\n \/\/ seperately as it is done in Lingeling, where fixed variables are\n \/\/ mapped to the internal variable '1'.\n \/\/\n int * map, dst = 0, first_fixed = 0;\n NEW (map, int, max_var + 1);\n map[0] = 0;\n for (int src = 1; src <= max_var; src++) {\n const Flags & f = flags (src);\n if (f.active ()) map[src] = ++dst;\n else if (!f.fixed () || first_fixed) map[src] = 0;\n else map[first_fixed = src] = ++dst;\n }\n\n if (first_fixed) LOG (\"found first fixed %d\", first_fixed);\n else LOG (\"no variable fixed\");\n\n const int new_max_var = dst;\n const size_t new_vsize = dst + 1;\t\/\/ Adjust to fit 'new_max_var'.\n\n \/*----------------------------------------------------------------------*\/\n \/\/ In this first part we only map stuff without reallocation.\n \/*----------------------------------------------------------------------*\/\n\n \/\/ Flush the external indices. This has to occur before we map 'vals'.\n {\n const int first_fixed_val = first_fixed ? val (first_fixed) : 0;\n for (int eidx = 1; eidx <= external->max_var; eidx++) {\n const int src = external->e2i[eidx];\n int dst, tmp;\n if (!src) dst = 0;\n else if (!(dst = map[src]) && (tmp = val (src))) {\n\tassert (first_fixed_val);\n\tdst = map[first_fixed];\n\tif (tmp != first_fixed_val) dst = -dst;\n }\n LOG (\"compact %ld maps external %d to internal %d\",\n stats.compacts, eidx, dst);\n external->e2i[eidx] = dst;\n }\n }\n\n \/\/ Map the literals in all clauses.\n {\n const const_clause_iterator end = clauses.end ();\n const_clause_iterator i;\n for (i = clauses.begin (); i != end; i++) {\n Clause * c = *i;\n assert (!c->garbage);\n const const_literal_iterator eoc = c->end ();\n literal_iterator j;\n for (j = c->begin (); j != eoc; j++) {\n\tconst int lit = *j;\n\tassert (active (lit));\n\tint dst = map[abs (lit)];\n\tif (lit < 0) dst = -dst;\n\tassert (dst);\n\t*j = dst;\n }\n }\n }\n\n \/\/ Map the blocking literals in all watches.\n \/\/\n if (watches ()) {\n for (int idx = 1; idx <= max_var; idx++) {\n for (int sign = -1; sign <= 1; sign += 2) {\n\tconst int lit = sign*idx;\n\tWatches & ws = watches (lit);\n\tconst const_watch_iterator end = ws.end ();\n\twatch_iterator i;\n\tfor (i = ws.begin (); i != end; i++) {\n\t const int blit = i->blit;\n\t assert (active (blit));\n\t int dst = map[abs (blit)];\n\t if (blit < 0) dst = -dst;\n\t assert (dst);\n\t i->blit = dst;\n\t}\n }\n }\n }\n\n \/\/ We first flush inactive variables and map the links in the queue. This\n \/\/ has to be done before we map the actual links data structure 'ltab'.\n {\n int prev = 0, mapped_prev = 0, next;\n for (int idx = queue.first; idx; idx = next) {\n Link * l = ltab + idx;\n next = l->next;\n if (idx == first_fixed) continue;\n const int dst = map[idx];\n if (!dst) continue;\n assert (active (idx));\n if (prev) ltab[prev].next = dst; else queue.first = dst;\n l->prev = mapped_prev;\n mapped_prev = dst;\n prev = idx;\n }\n if (prev) ltab[prev].next = 0; else queue.first = 0;\n queue.unassigned = queue.last = mapped_prev;\n }\n\n \/*----------------------------------------------------------------------*\/\n \/\/ In this second part we not only map stuff but also reallocate memory.\n \/*----------------------------------------------------------------------*\/\n\n \/\/ Now we continue in reverse order of allocated bytes, e.g., see\n \/\/ 'Internal::enlarge' which reallocates in order of allocated bytes.\n\n MAP_ARRAY (Flags, ftab);\n MAP_ARRAY (signed char, marks);\n MAP_ARRAY (signed char, phases);\n\n \/\/ Special case for 'val' as always since for 'val' we trade branch less\n \/\/ code for memory and always allocated an [-maxvar,...,maxvar] array.\n {\n signed char * new_vals = new signed char [2*new_vsize];\n new_vals += new_vsize;\n for (int src = -max_var; src <= -1; src++)\n new_vals[-map[-src]] = vals[src];\n for (int src = 1; src <= max_var; src++)\n new_vals[map[src]] = vals[src];\n new_vals[0] = 0;\n vals -= vsize;\n delete [] vals;\n vals = new_vals;\n }\n\n MAP_ARRAY (int, i2e);\n MAP2_ARRAY (int, ptab);\n MAP_ARRAY (long, btab);\n if (ntab2) MAP_ARRAY (long, ntab2);\n MAP_ARRAY (Link, ltab);\n MAP_ARRAY (Var, vtab);\n if (ntab) MAP2_ARRAY (long, ntab);\n if (wtab) MAP2_ARRAY (Watches, wtab);\n if (otab) MAP2_ARRAY (Occs, otab);\n if (big) MAP2_ARRAY (Bins, big);\n\n assert (propagated == trail.size ());\n MAP_AND_FLUSH_INT_VECTOR (trail);\n propagated = trail.size ();\n\n if (!probes.empty ()) MAP_AND_FLUSH_INT_VECTOR (probes);\n\n \/\/ The simplest way to map the elimination schedule is to get all elements\n \/\/ from the heap and reinsert them. This could be slightly improved in\n \/\/ terms of speed if we add a 'flush (int * map)' function to 'Heap', but\n \/\/ is pretty complicated and would require that the 'Heap' knows that\n \/\/ mapped elements with 'zero' destination should be flushed. Note that\n \/\/ we use stable heap sorting.\n \/\/\n if (!esched.empty ()) {\n vector<int> saved;\n while (!esched.empty ()) {\n const int src = esched.front ();\n esched.pop_front ();\n const int dst = map [src];\n if (dst && src != first_fixed) saved.push_back (dst);\n }\n esched.clear ();\n const const_int_iterator end = saved.end ();\n const_int_iterator i;\n for (i = saved.begin (); i != end; i++)\n esched.push_back (*i);\n esched.shrink ();\n }\n\n \/*----------------------------------------------------------------------*\/\n\n DEL (map, int, max_var);\n\n VRB (\"compact\", stats.compacts,\n \"reducing internal variables from %d to %d\",\n max_var, new_max_var);\n\n max_var = new_max_var;\n vsize = new_vsize;\n\n stats.now.fixed = first_fixed ? 1 : 0;\n stats.now.substituted = stats.now.eliminated = 0;\n\n inc.compact += opts.compactint;\n lim.compact = stats.conflicts + inc.compact;\n report ('c');\n STOP (compact);\n}\n\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other 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\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"amr_includes.H\"\n\n#include \"amr_forestclaw.H\"\n#include \"amr_utils.H\"\n#include \"fclaw2d_typedefs.h\"\n#include \"amr_regrid.H\"\n\n\/* -----------------------------------------------------------------\n Callback routine for tagging\n ----------------------------------------------------------------- *\/\nstatic\nvoid cb_tag4refinement(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx,\n void *user)\n{\n const amr_options_t *gparms = get_domain_parms(domain);\n\n int maxlevel = gparms->maxlevel;\n int level = this_patch->level;\n\n if (level < maxlevel)\n {\n fclaw2d_regrid_functions_t* rf = get_regrid_functions(domain);\n\n int initflag = 0;\n fclaw_bool refine_patch =\n (rf->f_patch_tag4refinement)(domain,this_patch,this_block_idx,\n this_patch_idx,initflag);\n if (refine_patch)\n {\n fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx);\n }\n }\n}\n\n\/* Tag family for coarsening *\/\nstatic\nvoid cb_tag4coarsening(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *fine_patches,\n int blockno,\n int fine0_patchno,\n void *user)\n{\n const amr_options_t *gparms = get_domain_parms(domain);\n int minlevel = gparms->minlevel;\n\n int level = fine_patches[0].level;\n\n if (level > minlevel)\n {\n \/* --------------------------------------------------------------\n Create temporary patch to hold coarsened data that we will use\n to determine if we need to coarsen data\n ----------------------------------------------------------------- *\/\n\n fclaw2d_patch_t *temp_coarse_patch = FCLAW2D_ALLOC(fclaw2d_patch_t,1);\n init_patch_data(temp_coarse_patch);\n\n temp_coarse_patch->xlower = fine_patches[0].xlower;\n temp_coarse_patch->ylower = fine_patches[0].ylower;\n temp_coarse_patch->xupper = fine_patches[NumSiblings-1].xupper;\n temp_coarse_patch->yupper = fine_patches[NumSiblings-1].yupper;\n temp_coarse_patch->level = level;\n int coarse_patchno = -1;\n\n set_clawpatch(domain,temp_coarse_patch,blockno,coarse_patchno);\n\n \/\/ One-time setup of patch\n fclaw2d_solver_functions_t *sf = get_solver_functions(domain);\n (sf->f_patch_setup)(domain,temp_coarse_patch,blockno,coarse_patchno);\n\n fclaw2d_regrid_functions_t *rf = get_regrid_functions(domain);\n (rf->f_patch_average2coarse)(domain,fine_patches,temp_coarse_patch,\n blockno,coarse_patchno, fine0_patchno);\n\n \/* --------------------------------------------------------------\n Test to see if temporary patch needs refining. If so, then we\n shouldn't coarsen it.\n ----------------------------------------------------------------- *\/\n fclaw_bool patch_coarsened =\n (rf->f_patch_tag4coarsening)(domain, temp_coarse_patch, blockno,\n coarse_patchno);\n\n delete_clawpatch(domain, temp_coarse_patch);\n delete_patch_data(temp_coarse_patch);\n FCLAW2D_FREE(temp_coarse_patch);\n\n if (patch_coarsened)\n {\n for (int igrid = 0; igrid < NumSiblings; igrid++)\n {\n int fine_patchno = fine0_patchno + igrid;\n fclaw2d_patch_mark_coarsen(domain, blockno, fine_patchno);\n }\n }\n }\n}\n\n\nstatic\nvoid cb_domain_adapt(fclaw2d_domain_t * old_domain,\n fclaw2d_patch_t * old_patch,\n fclaw2d_domain_t * new_domain,\n fclaw2d_patch_t * new_patch,\n fclaw2d_patch_relation_t newsize,\n int blockno,\n int old_patchno, int new_patchno,\n void *user)\n{\n if (newsize == FCLAW2D_PATCH_SAMESIZE)\n {\n \/\/ Grid doesn't change\n \/\/ set_clawpatch(new_domain,new_patch,blockno,new_patchno);\n\n \/\/ Setup new patch using solver specific routine\n \/\/ fclaw2d_solver_functions_t *sf = get_solver_functions(old_domain);\n \/\/ (sf->f_patch_setup)(new_domain,new_patch,blockno,new_patchno);\n\n \/\/ Need a copy function in regrid_functions\n fclaw2d_regrid_functions_t *rf = get_regrid_functions(old_domain);\n (rf->f_patch_copy2samesize)(new_domain,old_patch,new_patch,blockno,old_patchno,\n new_patchno);\n }\n else if (newsize == FCLAW2D_PATCH_HALFSIZE)\n {\n \/\/ Old grid is the coarse patch; new grids are the finer patches\n\n fclaw2d_patch_t *coarse_patch = old_patch;\n int coarse_patchno = old_patchno;\n\n fclaw2d_patch_t *fine_siblings = new_patch;\n\n \/\/ Loop over four siblings (z-ordering)\n for (int igrid = 0; igrid < NumSiblings; igrid++)\n {\n fclaw2d_patch_t *fine_patch = &fine_siblings[igrid];\n int fine_patchno = new_patchno + igrid;\n\n \/\/ Create new ClawPatch and assign patch pointer to it.\n \/\/ set_clawpatch(new_domain, fine_patch, blockno, fine_patchno);\n\n \/\/ Do one-time setup on new patch\n \/\/ fclaw2d_solver_functions_t *sf = get_solver_functions(old_domain);\n \/\/ (sf->f_patch_setup)(new_domain,fine_patch,blockno,fine_patchno);\n\n \/\/ Initialize new fine patch by either calling an init function or\n \/\/ by interpolating from coarser grid.\n fclaw2d_regrid_functions_t *rf = get_regrid_functions(old_domain);\n (rf->f_patch_interpolate2fine)(new_domain,coarse_patch,fine_patch,\n blockno,coarse_patchno,fine_patchno,igrid);\n }\n }\n else if (newsize == FCLAW2D_PATCH_DOUBLESIZE)\n {\n \/\/ Old grids are the finer grids; new grid is the coarsened grid\n fclaw2d_patch_t *fine_siblings = old_patch;\n int fine_patchno = old_patchno;\n\n fclaw2d_patch_t *coarse_patch = new_patch;\n int coarse_patchno = new_patchno;\n\n \/\/ set_clawpatch(new_domain,coarse_patch,blockno,coarse_patchno);\n\n \/\/ fclaw2d_solver_functions_t *sf = get_solver_functions(old_domain);\n \/\/ (sf->f_patch_setup)(new_domain,coarse_patch,blockno,coarse_patchno);\n\n fclaw2d_regrid_functions_t *rf = get_regrid_functions(old_domain);\n (rf->f_patch_average2coarse)(new_domain,fine_siblings,coarse_patch,\n blockno,coarse_patchno, fine_patchno);\n }\n else\n {\n printf(\"cb_adapt_domain : newsize not recognized\\n\");\n exit(1);\n }\n}\n\n\nvoid regrid(fclaw2d_domain_t **domain)\n{\n#if 0\n const amr_options_t *gparms = get_domain_parms(*domain);\n \/\/ double t = get_domain_time(*domain);\n#endif\n\n fclaw2d_domain_data_t* ddata = get_domain_data(*domain);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID]);\n\n \/\/ First determine which families should be coarsened.\n fclaw2d_domain_iterate_families(*domain, cb_tag4coarsening,\n (void*) NULL);\n\n \/\/ Then refine.\n fclaw2d_domain_iterate_patches(*domain, cb_tag4refinement,\n (void *) NULL);\n\n \/\/ Rebuild domain if necessary\n \/\/ Will return be NULL if no refining was done\n fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain);\n fclaw_bool have_new_refinement = new_domain != NULL;\n\n \/\/ Domain data may go out of scope now.\n ddata = NULL;\n\n if (have_new_refinement)\n {\n \/\/ allocate memory for user patch data and user domain data in the new\n \/\/ domain; copy data from the old to new the domain.\n rebuild_domain(*domain, new_domain);\n \/\/ Average to new coarse grids and interpolate to new fine grids\n fclaw2d_domain_iterate_adapted(*domain, new_domain,cb_domain_adapt,\n (void *) NULL);\n \n \/* TODO: can we use global min\/maxlevels here? *\/\n \/* DAC : I am not sure - The coarse\/fine exchanges will\n probably break if passed levels on which there are no\n patches. This could of course be fixed, but it doesn't\n seem necessary at this point.\n *\/\n \/\/ Do a level exchange to make sure all data is valid;\n \/\/ Coarse and fine grid exchanges will happen during time stepping as needed.\n#if 0\n \/* currently unused *\/\n minlevel = new_domain->global_minlevel;\n maxlevel = new_domain->global_maxlevel;\n#endif\n\n \/\/ free memory associated with old domain\n amrreset(domain);\n *domain = new_domain;\n new_domain = NULL;\n\n \/\/ Repartition for load balancing\n repartition_domain(domain, -1);\n\n \/* Update all ghost patches and ghost cells *\/\n update_ghost_all_levels (*domain,FCLAW2D_TIMER_REGRID);\n \n \/\/ Print global minimum and maximum levels\n if ((*domain)->mpirank == 0) {\n printf (\"Global minlevel %d maxlevel %d\\n\",\n (*domain)->global_minlevel, (*domain)->global_maxlevel);\n }\n }\n\n \/\/ Stop timer\n ddata = get_domain_data(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID]);\n\n \/\/ Count calls to this function\n ++ddata->count_amr_regrid;\n}\n<commit_msg>add brief comment about regridding strategy<commit_after>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other 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\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"amr_includes.H\"\n\n#include \"amr_forestclaw.H\"\n#include \"amr_utils.H\"\n#include \"fclaw2d_typedefs.h\"\n#include \"amr_regrid.H\"\n\n\/* -----------------------------------------------------------------\n Callback routine for tagging\n ----------------------------------------------------------------- *\/\nstatic\nvoid cb_tag4refinement(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx,\n void *user)\n{\n const amr_options_t *gparms = get_domain_parms(domain);\n\n int maxlevel = gparms->maxlevel;\n int level = this_patch->level;\n\n if (level < maxlevel)\n {\n fclaw2d_regrid_functions_t* rf = get_regrid_functions(domain);\n\n int initflag = 0;\n fclaw_bool refine_patch =\n (rf->f_patch_tag4refinement)(domain,this_patch,this_block_idx,\n this_patch_idx,initflag);\n if (refine_patch)\n {\n fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx);\n \/* refine all of the neighbors *\/\n }\n }\n}\n\n\/* Tag family for coarsening *\/\nstatic\nvoid cb_tag4coarsening(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *fine_patches,\n int blockno,\n int fine0_patchno,\n void *user)\n{\n const amr_options_t *gparms = get_domain_parms(domain);\n int minlevel = gparms->minlevel;\n\n int level = fine_patches[0].level;\n\n if (level > minlevel)\n {\n \/* --------------------------------------------------------------\n Create temporary patch to hold coarsened data that we will use\n to determine if we need to coarsen data\n ----------------------------------------------------------------- *\/\n\n fclaw2d_patch_t *temp_coarse_patch = FCLAW2D_ALLOC(fclaw2d_patch_t,1);\n init_patch_data(temp_coarse_patch);\n\n temp_coarse_patch->xlower = fine_patches[0].xlower;\n temp_coarse_patch->ylower = fine_patches[0].ylower;\n temp_coarse_patch->xupper = fine_patches[NumSiblings-1].xupper;\n temp_coarse_patch->yupper = fine_patches[NumSiblings-1].yupper;\n temp_coarse_patch->level = level;\n int coarse_patchno = -1;\n\n set_clawpatch(domain,temp_coarse_patch,blockno,coarse_patchno);\n\n \/\/ One-time setup of patch\n fclaw2d_solver_functions_t *sf = get_solver_functions(domain);\n (sf->f_patch_setup)(domain,temp_coarse_patch,blockno,coarse_patchno);\n\n fclaw2d_regrid_functions_t *rf = get_regrid_functions(domain);\n (rf->f_patch_average2coarse)(domain,fine_patches,temp_coarse_patch,\n blockno,coarse_patchno, fine0_patchno);\n\n \/* --------------------------------------------------------------\n Test to see if temporary patch needs refining. If so, then we\n shouldn't coarsen it.\n ----------------------------------------------------------------- *\/\n fclaw_bool patch_coarsened =\n (rf->f_patch_tag4coarsening)(domain, temp_coarse_patch, blockno,\n coarse_patchno);\n\n delete_clawpatch(domain, temp_coarse_patch);\n delete_patch_data(temp_coarse_patch);\n FCLAW2D_FREE(temp_coarse_patch);\n\n if (patch_coarsened)\n {\n for (int igrid = 0; igrid < NumSiblings; igrid++)\n {\n int fine_patchno = fine0_patchno + igrid;\n fclaw2d_patch_mark_coarsen(domain, blockno, fine_patchno);\n }\n }\n }\n}\n\n\nstatic\nvoid cb_domain_adapt(fclaw2d_domain_t * old_domain,\n fclaw2d_patch_t * old_patch,\n fclaw2d_domain_t * new_domain,\n fclaw2d_patch_t * new_patch,\n fclaw2d_patch_relation_t newsize,\n int blockno,\n int old_patchno, int new_patchno,\n void *user)\n{\n if (newsize == FCLAW2D_PATCH_SAMESIZE)\n {\n \/\/ Grid doesn't change\n \/\/ set_clawpatch(new_domain,new_patch,blockno,new_patchno);\n\n \/\/ Setup new patch using solver specific routine\n \/\/ fclaw2d_solver_functions_t *sf = get_solver_functions(old_domain);\n \/\/ (sf->f_patch_setup)(new_domain,new_patch,blockno,new_patchno);\n\n \/\/ Need a copy function in regrid_functions\n fclaw2d_regrid_functions_t *rf = get_regrid_functions(old_domain);\n (rf->f_patch_copy2samesize)(new_domain,old_patch,new_patch,blockno,old_patchno,\n new_patchno);\n }\n else if (newsize == FCLAW2D_PATCH_HALFSIZE)\n {\n \/\/ Old grid is the coarse patch; new grids are the finer patches\n\n fclaw2d_patch_t *coarse_patch = old_patch;\n int coarse_patchno = old_patchno;\n\n fclaw2d_patch_t *fine_siblings = new_patch;\n\n \/\/ Loop over four siblings (z-ordering)\n for (int igrid = 0; igrid < NumSiblings; igrid++)\n {\n fclaw2d_patch_t *fine_patch = &fine_siblings[igrid];\n int fine_patchno = new_patchno + igrid;\n\n \/\/ Create new ClawPatch and assign patch pointer to it.\n \/\/ set_clawpatch(new_domain, fine_patch, blockno, fine_patchno);\n\n \/\/ Do one-time setup on new patch\n \/\/ fclaw2d_solver_functions_t *sf = get_solver_functions(old_domain);\n \/\/ (sf->f_patch_setup)(new_domain,fine_patch,blockno,fine_patchno);\n\n \/\/ Initialize new fine patch by either calling an init function or\n \/\/ by interpolating from coarser grid.\n fclaw2d_regrid_functions_t *rf = get_regrid_functions(old_domain);\n (rf->f_patch_interpolate2fine)(new_domain,coarse_patch,fine_patch,\n blockno,coarse_patchno,fine_patchno,igrid);\n }\n }\n else if (newsize == FCLAW2D_PATCH_DOUBLESIZE)\n {\n \/\/ Old grids are the finer grids; new grid is the coarsened grid\n fclaw2d_patch_t *fine_siblings = old_patch;\n int fine_patchno = old_patchno;\n\n fclaw2d_patch_t *coarse_patch = new_patch;\n int coarse_patchno = new_patchno;\n\n \/\/ set_clawpatch(new_domain,coarse_patch,blockno,coarse_patchno);\n\n \/\/ fclaw2d_solver_functions_t *sf = get_solver_functions(old_domain);\n \/\/ (sf->f_patch_setup)(new_domain,coarse_patch,blockno,coarse_patchno);\n\n fclaw2d_regrid_functions_t *rf = get_regrid_functions(old_domain);\n (rf->f_patch_average2coarse)(new_domain,fine_siblings,coarse_patch,\n blockno,coarse_patchno, fine_patchno);\n }\n else\n {\n printf(\"cb_adapt_domain : newsize not recognized\\n\");\n exit(1);\n }\n}\n\n\nvoid regrid(fclaw2d_domain_t **domain)\n{\n#if 0\n const amr_options_t *gparms = get_domain_parms(*domain);\n \/\/ double t = get_domain_time(*domain);\n#endif\n\n fclaw2d_domain_data_t* ddata = get_domain_data(*domain);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID]);\n\n \/\/ First determine which families should be coarsened.\n fclaw2d_domain_iterate_families(*domain, cb_tag4coarsening,\n (void*) NULL);\n\n \/\/ Then refine.\n fclaw2d_domain_iterate_patches(*domain, cb_tag4refinement,\n (void *) NULL);\n\n \/\/ Rebuild domain if necessary\n \/\/ Will return be NULL if no refining was done\n fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain);\n fclaw_bool have_new_refinement = new_domain != NULL;\n\n \/\/ Domain data may go out of scope now.\n ddata = NULL;\n\n if (have_new_refinement)\n {\n \/\/ allocate memory for user patch data and user domain data in the new\n \/\/ domain; copy data from the old to new the domain.\n rebuild_domain(*domain, new_domain);\n \/\/ Average to new coarse grids and interpolate to new fine grids\n fclaw2d_domain_iterate_adapted(*domain, new_domain,cb_domain_adapt,\n (void *) NULL);\n\n \/* TODO: can we use global min\/maxlevels here? *\/\n \/* DAC : I am not sure - The coarse\/fine exchanges will\n probably break if passed levels on which there are no\n patches. This could of course be fixed, but it doesn't\n seem necessary at this point.\n *\/\n \/\/ Do a level exchange to make sure all data is valid;\n \/\/ Coarse and fine grid exchanges will happen during time stepping as needed.\n#if 0\n \/* currently unused *\/\n minlevel = new_domain->global_minlevel;\n maxlevel = new_domain->global_maxlevel;\n#endif\n\n \/\/ free memory associated with old domain\n amrreset(domain);\n *domain = new_domain;\n new_domain = NULL;\n\n \/\/ Repartition for load balancing\n repartition_domain(domain, -1);\n\n \/* Update all ghost patches and ghost cells *\/\n update_ghost_all_levels (*domain,FCLAW2D_TIMER_REGRID);\n\n \/\/ Print global minimum and maximum levels\n if ((*domain)->mpirank == 0) {\n printf (\"Global minlevel %d maxlevel %d\\n\",\n (*domain)->global_minlevel, (*domain)->global_maxlevel);\n }\n }\n\n \/\/ Stop timer\n ddata = get_domain_data(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID]);\n\n \/\/ Count calls to this function\n ++ddata->count_amr_regrid;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef HEADER_GUARD_CLASS_CONTENTS_H\n#define HEADER_GUARD_CLASS_CONTENTS_H\n\n#include <vector>\n#include <string>\n#include <memory>\n\n#include \"change.hh\"\n#include \"mode.hh\"\n\nnamespace vick {\n\n\/*!\n * \\file contents.hh\n *\n * \\brief Defines the class contents, which contains all the\n * information about the buffer.\n *\/\n\n\/*!\n * \\brief Define \\c move_t so that code can be more descriptive and\n * can change it from one place.\n *\/\nusing move_t = unsigned long;\n\n\/*!\n * \\brief Define \\c move_ts to be a signed version of \\c move_t\n *\n * \\see move_t\n *\/\nusing move_ts = long;\n\n\/*!\n * \\class contents contents.hh \"..\/..\/..\/src\/contents.hh\"\n *\n * \\brief Defines all the information about the buffer.\n *\/\nclass contents {\npublic:\n std::map < char, std::function < boost::optional< std::shared_ptr<change> >\n (contents&, boost::optional<int>) > >\n normal_map \/*!< \\brief The contents buffer (file) specfic\n * normal mode character mappings. *\/,\n insert_map \/*!< \\brief The contents buffer (file) specfic\n * insert mode character mappings. *\/;\n\n \/*!\n * \\brief The type of file the buffer is.\n *\n * Default mode is fundamental;\n *\/\n mode* buffer_mode;\n\n \/*!\n * \\brief The literal contents of the buffer\n *\/\n std::vector<std::string> cont;\n\n \/*!\n * \\brief The list of changes to the buffer. This is public so\n * that treed-undo (a la Emacs) can be implemented the same as\n * linear is.\n *\/\n std::vector<std::shared_ptr<change> > changes;\n\n \/*!\n * \\brief The current change the buffer is in\n *\/\n size_t changes_i = 0;\n\n move_t\n y = 0 \/*!< \\brief The y (vertical) position in the buffer. *\/,\n x = 0 \/*!< \\brief The x (horizontal) position in the buffer. *\/,\n desired_x = 0 \/*!< \\brief This will be set to the x value we\n * want when you move to a different line but\n * the line you move to is too short\n *\n * \\see waiting_for_desired *\/,\n y_offset = 0 \/*!< \\brief The number of lines that are not\n * displayed (off the top) *\/,\n max_y \/*!< \\brief The vertical height the buffer has been\n * allocated - [0, max_y) *\/,\n max_x \/*!< \\brief The horizontal width the buffer has been\n * allocated - [0, max_x) *\/;\n\n bool waiting_for_desired = false \/*!< \\brief Controls if the x\n * value will try to adjust to\n * desired_x\n *\n * \\see desired_x *\/,\n refresh = true \/*!< \\brief Controls if the screen should\n * refresh everytime something happens *\/,\n delete_mode = false \/*!< \\brief Controls if the private mode\n * pointer variable will be deleted in the\n * destructor *\/,\n is_inserting = false \/*!< \\brief Will be true if the user is\n * currently inserting text into the\n * buffer. This will cause the\n * print_contents method to not have\n * undefined behavior if x is too\n * large. *\/,\n windows_file_endings = false \/*!< \\brief If true, then when\n * saving, appends the byte 13 to\n * each line. We use this to\n * maintain plugin consistency\n * across platforms. (The buffer\n * is in no way affected by this\n * variable)\n *\/;\n\n explicit contents(std::vector<std::string> cont = std::vector<std::string>(),\n mode* buffer_mode = &fundamental_mode);\n explicit contents(mode* buffer_mode);\n contents(move_t y, move_t x, mode* buffer_mode = &fundamental_mode);\n\n \/*!\n * \\brief Constructs this contents object as a copy of the other\n * contents object.\n *\n * This forces the private mode member to make a deep copy.\n *\/\n contents(const contents&);\n contents(contents&&) = default;\n\n \/*!\n * \\brief If delete_mode is true, then it will delete the private\n * mode pointer member.\n *\n * \\see delete_mode\n *\/\n ~contents();\n\n \/*!\n * \\brief Constructs this contents object as a copy of the other\n * contents object.\n *\n * This forces the private mode member to make a deep copy.\n *\/\n contents& operator=(const contents&);\n contents& operator=(contents&&);\n\n bool operator()(char);\n\n \/*!\n * \\brief Updates the values of ``max_y`` and ``max_x``\n *\n * \\see max_y\n * \\see max_x\n *\/\n void refreshmaxyx();\n\n \/*!\n * \\brief Calls ``cont.push_back(str)``\n *\n * \\see cont\n *\n * \\param str The string to be put at the end of the vector of strings, cont\n *\/\n void push_back(const std::string& str);\n};\n\n}\n\n#endif\n<commit_msg>Add documentation to contents::operator()<commit_after>#ifndef HEADER_GUARD_CLASS_CONTENTS_H\n#define HEADER_GUARD_CLASS_CONTENTS_H\n\n#include <vector>\n#include <string>\n#include <memory>\n\n#include \"change.hh\"\n#include \"mode.hh\"\n\nnamespace vick {\n\n\/*!\n * \\file contents.hh\n *\n * \\brief Defines the class contents, which contains all the\n * information about the buffer.\n *\/\n\n\/*!\n * \\brief Define \\c move_t so that code can be more descriptive and\n * can change it from one place.\n *\/\nusing move_t = unsigned long;\n\n\/*!\n * \\brief Define \\c move_ts to be a signed version of \\c move_t\n *\n * \\see move_t\n *\/\nusing move_ts = long;\n\n\/*!\n * \\class contents contents.hh \"..\/..\/..\/src\/contents.hh\"\n *\n * \\brief Defines all the information about the buffer.\n *\/\nclass contents {\npublic:\n std::map < char, std::function < boost::optional< std::shared_ptr<change> >\n (contents&, boost::optional<int>) > >\n normal_map \/*!< \\brief The contents buffer (file) specfic\n * normal mode character mappings. *\/,\n insert_map \/*!< \\brief The contents buffer (file) specfic\n * insert mode character mappings. *\/;\n\n \/*!\n * \\brief The type of file the buffer is.\n *\n * Default mode is fundamental;\n *\/\n mode* buffer_mode;\n\n \/*!\n * \\brief The literal contents of the buffer\n *\/\n std::vector<std::string> cont;\n\n \/*!\n * \\brief The list of changes to the buffer. This is public so\n * that treed-undo (a la Emacs) can be implemented the same as\n * linear is.\n *\/\n std::vector<std::shared_ptr<change> > changes;\n\n \/*!\n * \\brief The current change the buffer is in\n *\/\n size_t changes_i = 0;\n\n move_t\n y = 0 \/*!< \\brief The y (vertical) position in the buffer. *\/,\n x = 0 \/*!< \\brief The x (horizontal) position in the buffer. *\/,\n desired_x = 0 \/*!< \\brief This will be set to the x value we\n * want when you move to a different line but\n * the line you move to is too short\n *\n * \\see waiting_for_desired *\/,\n y_offset = 0 \/*!< \\brief The number of lines that are not\n * displayed (off the top) *\/,\n max_y \/*!< \\brief The vertical height the buffer has been\n * allocated - [0, max_y) *\/,\n max_x \/*!< \\brief The horizontal width the buffer has been\n * allocated - [0, max_x) *\/;\n\n bool waiting_for_desired = false \/*!< \\brief Controls if the x\n * value will try to adjust to\n * desired_x\n *\n * \\see desired_x *\/,\n refresh = true \/*!< \\brief Controls if the screen should\n * refresh everytime something happens *\/,\n delete_mode = false \/*!< \\brief Controls if the private mode\n * pointer variable will be deleted in the\n * destructor *\/,\n is_inserting = false \/*!< \\brief Will be true if the user is\n * currently inserting text into the\n * buffer. This will cause the\n * print_contents method to not have\n * undefined behavior if x is too\n * large. *\/,\n windows_file_endings = false \/*!< \\brief If true, then when\n * saving, appends the byte 13 to\n * each line. We use this to\n * maintain plugin consistency\n * across platforms. (The buffer\n * is in no way affected by this\n * variable)\n *\/;\n\n explicit contents(std::vector<std::string> cont = std::vector<std::string>(),\n mode* buffer_mode = &fundamental_mode);\n explicit contents(mode* buffer_mode);\n contents(move_t y, move_t x, mode* buffer_mode = &fundamental_mode);\n\n \/*!\n * \\brief Constructs this contents object as a copy of the other\n * contents object.\n *\n * This forces the private mode member to make a deep copy.\n *\/\n contents(const contents&);\n contents(contents&&) = default;\n\n \/*!\n * \\brief If delete_mode is true, then it will delete the private\n * mode pointer member.\n *\n * \\see delete_mode\n *\/\n ~contents();\n\n \/*!\n * \\brief Constructs this contents object as a copy of the other\n * contents object.\n *\n * This forces the private mode member to make a deep copy.\n *\/\n contents& operator=(const contents&);\n contents& operator=(contents&&);\n\n \/*!\n * \\brief Calls the private mode member's `operator()` with\n * `*this` and the character given to this function.\n *\/\n bool operator()(char);\n\n \/*!\n * \\brief Updates the values of ``max_y`` and ``max_x``\n *\n * \\see max_y\n * \\see max_x\n *\/\n void refreshmaxyx();\n\n \/*!\n * \\brief Calls ``cont.push_back(str)``\n *\n * \\see cont\n *\n * \\param str The string to be put at the end of the vector of strings, cont\n *\/\n void push_back(const std::string& str);\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.\n * License: https:\/\/github.com\/taylor001\/crown\/blob\/master\/LICENSE\n *\/\n\n#include \"dynamic_string.h\"\n#include \"os.h\"\n#include \"string_stream.h\"\n#include \"temp_allocator.h\"\n#include \"vector.h\"\n#include <string.h> \/\/ strcmp\n\n#if CROWN_PLATFORM_POSIX\n\t#include <dirent.h> \/\/ opendir, readdir\n#endif\n\nnamespace crown\n{\nnamespace os\n{\n\tvoid list_files(const char* path, Vector<DynamicString>& files)\n\t{\n#if CROWN_PLATFORM_POSIX\n\t\tDIR *dir;\n\t\tstruct dirent *entry;\n\n\t\tif (!(dir = opendir(path)))\n\t\t\treturn;\n\n\t\twhile ((entry = readdir(dir)))\n\t\t{\n\t\t\tconst char* dname = entry->d_name;\n\n\t\t\tif (!strcmp(dname, \".\") || !strcmp(dname, \"..\"))\n\t\t\t\tcontinue;\n\n\t\t\tTempAllocator512 ta;\n\t\t\tDynamicString fname(ta);\n\t\t\tfname.set(dname, strlen32(dname));\n\t\t\tvector::push_back(files, fname);\n\t\t}\n\n\t\tclosedir(dir);\n#elif CROWN_PLATFORM_WINDOWS\n\t\tTempAllocator1024 ta;\n\t\tDynamicString cur_path(ta);\n\t\tcur_path += path;\n\t\tcur_path += \"\\\\*\";\n\n\t\tWIN32_FIND_DATA ffd;\n\t\tHANDLE file = FindFirstFile(cur_path.c_str(), &ffd);\n\t\tif (file == INVALID_HANDLE_VALUE)\n\t\t\treturn;\n\n\t\tdo\n\t\t{\n\t\t\tconst char* filename = ffd.cFileName;\n\n\t\t\tif (!strcmp(fname, \".\") || !strcmp(fname, \"..\"))\n\t\t\t\tcontinue;\n\n\t\t\tTempAllocator512 ta;\n\t\t\tDynamicString fname(ta);\n\t\t\tfname.set(filename, strlen32(filename));\n\t\t\tvector::push_back(files, fname);\n\t\t}\n\t\twhile (FindNextFile(file, &ffd) != 0);\n\n\t\tFindClose(file);\n#endif\n\t}\n\n\tint execute_process(const char* path, const char* args, StringStream& output)\n\t{\n#if CROWN_PLATFORM_POSIX\n\t\tTempAllocator512 ta;\n\t\tDynamicString cmd(ta);\n\t\tcmd += path;\n\t\tcmd += \" 2>&1 \";\n\t\tcmd += args;\n\t\tFILE* file = popen(cmd.c_str(), \"r\");\n\n\t\tchar buf[1024];\n\t\twhile (fgets(buf, sizeof(buf), file) != NULL)\n\t\t\toutput << buf;\n\n\t\treturn pclose(file);\n#elif CROWN_PLATFORM_WINDOWS\n\t\tSTARTUPINFO info;\n\t\tmemset(&info, 0, sizeof(info));\n\t\tinfo.cb = sizeof(info);\n\n\t\tPROCESS_INFORMATION process;\n\t\tmemset(&process, 0, sizeof(process));\n\n\t\tint err = CreateProcess(path, (LPSTR)args, NULL, NULL, TRUE, 0, NULL, NULL, &info, &process);\n\t\tCE_ASSERT(err != 0, \"CreateProcess: GetLastError = %d\", GetLastError());\n\t\tCE_UNUSED(err);\n\n\t\tDWORD exitcode = 1;\n\t\t::WaitForSingleObject(process.hProcess, INFINITE);\n \t\tGetExitCodeProcess(process.hProcess, &exitcode);\n\t\tCloseHandle(process.hProcess);\n\t\tCloseHandle(process.hThread);\n\t\treturn (int)exitcode;\n#endif\n\t}\n} \/\/ namespace os\n\n} \/\/ namespace crown\n<commit_msg>Fix build<commit_after>\/*\n * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.\n * License: https:\/\/github.com\/taylor001\/crown\/blob\/master\/LICENSE\n *\/\n\n#include \"dynamic_string.h\"\n#include \"os.h\"\n#include \"string_stream.h\"\n#include \"temp_allocator.h\"\n#include \"vector.h\"\n#include <string.h> \/\/ strcmp\n\n#if CROWN_PLATFORM_POSIX\n\t#include <dirent.h> \/\/ opendir, readdir\n#endif\n\nnamespace crown\n{\nnamespace os\n{\n\tvoid list_files(const char* path, Vector<DynamicString>& files)\n\t{\n#if CROWN_PLATFORM_POSIX\n\t\tDIR *dir;\n\t\tstruct dirent *entry;\n\n\t\tif (!(dir = opendir(path)))\n\t\t\treturn;\n\n\t\twhile ((entry = readdir(dir)))\n\t\t{\n\t\t\tconst char* dname = entry->d_name;\n\n\t\t\tif (!strcmp(dname, \".\") || !strcmp(dname, \"..\"))\n\t\t\t\tcontinue;\n\n\t\t\tTempAllocator512 ta;\n\t\t\tDynamicString fname(ta);\n\t\t\tfname.set(dname, strlen32(dname));\n\t\t\tvector::push_back(files, fname);\n\t\t}\n\n\t\tclosedir(dir);\n#elif CROWN_PLATFORM_WINDOWS\n\t\tTempAllocator1024 ta;\n\t\tDynamicString cur_path(ta);\n\t\tcur_path += path;\n\t\tcur_path += \"\\\\*\";\n\n\t\tWIN32_FIND_DATA ffd;\n\t\tHANDLE file = FindFirstFile(cur_path.c_str(), &ffd);\n\t\tif (file == INVALID_HANDLE_VALUE)\n\t\t\treturn;\n\n\t\tdo\n\t\t{\n\t\t\tconst char* dname = ffd.cFileName;\n\n\t\t\tif (!strcmp(dname, \".\") || !strcmp(dname, \"..\"))\n\t\t\t\tcontinue;\n\n\t\t\tTempAllocator512 ta;\n\t\t\tDynamicString fname(ta);\n\t\t\tfname.set(dname, strlen32(dname));\n\t\t\tvector::push_back(files, fname);\n\t\t}\n\t\twhile (FindNextFile(file, &ffd) != 0);\n\n\t\tFindClose(file);\n#endif\n\t}\n\n\tint execute_process(const char* path, const char* args, StringStream& output)\n\t{\n#if CROWN_PLATFORM_POSIX\n\t\tTempAllocator512 ta;\n\t\tDynamicString cmd(ta);\n\t\tcmd += path;\n\t\tcmd += \" 2>&1 \";\n\t\tcmd += args;\n\t\tFILE* file = popen(cmd.c_str(), \"r\");\n\n\t\tchar buf[1024];\n\t\twhile (fgets(buf, sizeof(buf), file) != NULL)\n\t\t\toutput << buf;\n\n\t\treturn pclose(file);\n#elif CROWN_PLATFORM_WINDOWS\n\t\tSTARTUPINFO info;\n\t\tmemset(&info, 0, sizeof(info));\n\t\tinfo.cb = sizeof(info);\n\n\t\tPROCESS_INFORMATION process;\n\t\tmemset(&process, 0, sizeof(process));\n\n\t\tint err = CreateProcess(path, (LPSTR)args, NULL, NULL, TRUE, 0, NULL, NULL, &info, &process);\n\t\tCE_ASSERT(err != 0, \"CreateProcess: GetLastError = %d\", GetLastError());\n\t\tCE_UNUSED(err);\n\n\t\tDWORD exitcode = 1;\n\t\t::WaitForSingleObject(process.hProcess, INFINITE);\n \t\tGetExitCodeProcess(process.hProcess, &exitcode);\n\t\tCloseHandle(process.hProcess);\n\t\tCloseHandle(process.hThread);\n\t\treturn (int)exitcode;\n#endif\n\t}\n} \/\/ namespace os\n\n} \/\/ namespace crown\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <cstring>\n\n#include <csimsbw.h>\n\n#include \"csim\/model.h\"\n#include \"csim\/executable_functions.h\"\n#include \"csim\/error_codes.h\"\n#include \"xmlutils.h\"\n\n#define CSIM_SUCCESS 0\n#define CSIM_FAILED 1\n\n\/\/ assuming we only deal with one model at a time\nclass CsimWrapper {\npublic:\n CsimWrapper() : model(NULL) {}\n ~CsimWrapper() {\n if (model) delete model;\n }\n\n csim::Model* model;\n};\n\nstatic CsimWrapper* _csim = NULL;\n\nint csim_loadCellml(const char* modelString)\n{\n if (_csim) delete _csim;\n _csim = new CsimWrapper();\n _csim->model = new csim::Model();\n return _csim->model->loadCellmlModelFromString(modelString);\n}\n\nint csim_reset()\n{\n return CSIM_SUCCESS;\n}\n\nint csim_setValue(const char* variableId, double value)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_getVariables(char** *outArray, int *outLength)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_getValues(double* *outArray, int *outLength)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_steadyState()\n{\n return CSIM_SUCCESS;\n}\n\nint csim_simulate(\n double initialTime, double startTime, double endTime, int numSteps,\n double** *outMatrix, int* outRows, int *outCols)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_oneStep(double step)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_setTolerances(double aTol, double rTol, int maxSteps)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_sayHello(char* *outString, int *outLength)\n{\n *outLength = 11;\n *outString = strdup(\"Hello World\");\n return CSIM_SUCCESS;\n}\n\nint csim_serialiseCellmlFromUrl(const char* url,\n char* *outString, int *outLength)\n{\n XmlDoc xml;\n int code = xml.parseDocument(url);\n if (code != 0)\n {\n std::cerr << \"Error parsing document at the URL: \" << url << std::endl;\n return CSIM_FAILED;\n }\n xml.setXmlBase(url);\n std::string model = xml.dumpString();\n *outLength = model.length();\n *outString = strdup(model.c_str());\n return CSIM_SUCCESS;\n}\n\n\/\/! Frees a vector previously allocated by this library.\nvoid csim_freeVector(void* vector)\n{\n if (vector) free(vector);\n}\n\n\/\/! Frees a matrix previously allocated by this library.\nvoid csim_freeMatrix(void** matrix, int numRows)\n{\n\n}\n<commit_msg>instantiate the model once it loads successfully<commit_after>#include <iostream>\n#include <vector>\n#include <cstring>\n\n#include <csimsbw.h>\n\n#include \"csim\/model.h\"\n#include \"csim\/executable_functions.h\"\n#include \"csim\/error_codes.h\"\n#include \"xmlutils.h\"\n\n#define CSIM_SUCCESS 0\n#define CSIM_FAILED 1\n\n\/\/ assuming we only deal with one model at a time\nclass CsimWrapper {\npublic:\n CsimWrapper() : model(NULL) {}\n ~CsimWrapper() {\n if (model) delete model;\n }\n\n csim::Model* model;\n};\n\nstatic CsimWrapper* _csim = NULL;\n\nint csim_loadCellml(const char* modelString)\n{\n if (_csim) delete _csim;\n _csim = new CsimWrapper();\n _csim->model = new csim::Model();\n int code = _csim->model->loadCellmlModelFromString(modelString);\n if (code != csim::CSIM_OK)\n {\n std::cerr << \"Error loading the model from a string\" << std::endl;\n return CSIM_FAILED;\n }\n code = _csim->model->instantiate();\n if (code != csim::CSIM_OK)\n {\n std::cerr << \"Error instantiating model\" << std::endl;\n return CSIM_FAILED;\n }\n return CSIM_SUCCESS;\n}\n\nint csim_reset()\n{\n return CSIM_SUCCESS;\n}\n\nint csim_setValue(const char* variableId, double value)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_getVariables(char** *outArray, int *outLength)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_getValues(double* *outArray, int *outLength)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_steadyState()\n{\n return CSIM_SUCCESS;\n}\n\nint csim_simulate(\n double initialTime, double startTime, double endTime, int numSteps,\n double** *outMatrix, int* outRows, int *outCols)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_oneStep(double step)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_setTolerances(double aTol, double rTol, int maxSteps)\n{\n return CSIM_SUCCESS;\n}\n\nint csim_sayHello(char* *outString, int *outLength)\n{\n *outLength = 11;\n *outString = strdup(\"Hello World\");\n return CSIM_SUCCESS;\n}\n\nint csim_serialiseCellmlFromUrl(const char* url,\n char* *outString, int *outLength)\n{\n XmlDoc xml;\n int code = xml.parseDocument(url);\n if (code != 0)\n {\n std::cerr << \"Error parsing document at the URL: \" << url << std::endl;\n return CSIM_FAILED;\n }\n xml.setXmlBase(url);\n std::string model = xml.dumpString();\n *outLength = model.length();\n *outString = strdup(model.c_str());\n return CSIM_SUCCESS;\n}\n\n\/\/! Frees a vector previously allocated by this library.\nvoid csim_freeVector(void* vector)\n{\n if (vector) free(vector);\n}\n\n\/\/! Frees a matrix previously allocated by this library.\nvoid csim_freeMatrix(void** matrix, int numRows)\n{\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2014 Jarryd Beck\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*\/\n\n#include <regex>\n#include <set>\n#include <map>\n#include <exception>\n#include <boost\/any.hpp>\n#include <sstream>\n\nnamespace cxxopts\n{\n using boost::any;\n\n class Value\n {\n public:\n\n virtual void\n parse(const std::string& text) const = 0;\n\n virtual bool\n has_arg() const = 0;\n };\n\n namespace values\n {\n template <typename T>\n void\n parse_value(const std::string& text, T& value)\n {\n std::istringstream is(text);\n is >> value;\n }\n\n template <typename T>\n struct value_has_arg\n {\n static constexpr bool value = true;\n };\n\n template <>\n struct value_has_arg<bool>\n {\n static constexpr bool value = false;\n };\n\n template <typename T>\n class default_value : public Value\n {\n public:\n default_value()\n : m_result(std::make_shared<T>())\n , m_store(m_result.get())\n {\n }\n\n default_value(T* t)\n : m_store(t)\n {\n }\n\n void\n parse(const std::string& text) const\n {\n parse_value(text, *m_store);\n }\n\n bool\n has_arg() const\n {\n return value_has_arg<T>::value;\n }\n\n const T&\n get() const\n {\n if (m_store == nullptr)\n {\n return *m_result;\n }\n else\n {\n return *m_store;\n }\n }\n\n private:\n std::shared_ptr<T> m_result;\n T* m_store;\n };\n\n }\n\n template <typename T>\n std::shared_ptr<Value>\n value()\n {\n return std::make_shared<values::default_value<T>>();\n }\n\n class OptionException : public std::exception\n {\n public:\n OptionException(const std::string& message)\n : m_message(message)\n {\n }\n\n virtual const char*\n what() const noexcept\n {\n return m_message.c_str();\n }\n\n private:\n std::string m_message;\n };\n\n class OptionSpecException : public OptionException\n {\n public:\n\n OptionSpecException(const std::string& message)\n : OptionException(message)\n {\n }\n };\n\n class OptionParseException : public OptionException\n {\n public:\n OptionParseException(const std::string& message)\n : OptionException(message)\n {\n }\n };\n\n class option_exists_error : public OptionSpecException\n {\n public:\n option_exists_error(const std::string& option)\n : OptionSpecException(u8\"Option ‘\" + option + u8\"’ already exists\")\n {\n }\n };\n\n class invalid_option_format_error : public OptionSpecException\n {\n public:\n invalid_option_format_error(const std::string& format)\n : OptionSpecException(u8\"Invalid option format ‘\" + format + u8\"’\")\n {\n }\n };\n\n class option_not_exists_exception : public OptionParseException\n {\n public:\n option_not_exists_exception(const std::string& option)\n : OptionParseException(u8\"Option ‘\" + option + u8\"’ does not exist\")\n {\n }\n };\n\n class missing_argument_exception : public OptionParseException\n {\n public:\n missing_argument_exception(const std::string& option)\n : OptionParseException(u8\"Option ‘\" + option + u8\"’ is missing an argument\")\n {\n }\n };\n\n class option_requires_argument_exception : public OptionParseException\n {\n public:\n option_requires_argument_exception(const std::string& option)\n : OptionParseException(u8\"Option ‘\" + option + u8\"’ requires an argument\")\n {\n }\n };\n\n class option_not_has_argument_exception : public OptionParseException\n {\n public:\n option_not_has_argument_exception\n (\n const std::string& option, \n const std::string& arg\n )\n : OptionParseException(\n u8\"Option ‘\" + option + u8\"’ does not take an argument, but argument‘\"\n + arg + \"’ given\")\n {\n }\n };\n\n class option_not_present_exception : public OptionParseException\n {\n public:\n option_not_present_exception(const std::string& option)\n : OptionParseException(u8\"Option ‘\" + option + u8\"’ not present\")\n {\n }\n };\n\n class OptionAdder;\n\n class OptionDetails\n {\n public:\n OptionDetails\n (\n const std::string& description,\n std::shared_ptr<const Value> value\n )\n : m_desc(description)\n , m_value(value)\n , m_count(0)\n {\n }\n\n const std::string& \n description() const\n {\n return m_desc;\n }\n\n bool\n has_arg() const\n {\n return m_value->has_arg();\n }\n\n void\n parse(const std::string& text)\n {\n m_value->parse(text);\n ++m_count;\n }\n\n int\n count() const\n {\n return m_count;\n }\n\n template <typename T>\n const T&\n as() const\n {\n return dynamic_cast<const values::default_value<T>&>(*m_value).get();\n }\n\n private:\n std::string m_desc;\n std::shared_ptr<const Value> m_value;\n int m_count;\n };\n\n class Options\n {\n public:\n\n void\n parse(int& argc, char**& argv);\n\n OptionAdder\n add_options();\n\n int\n count(const std::string& o) const\n {\n auto iter = m_options.find(o);\n if (iter == m_options.end())\n {\n return 0;\n }\n\n return iter->second->count();\n }\n\n const OptionDetails&\n operator[](const std::string& option) const\n {\n auto iter = m_options.find(option);\n\n if (iter == m_options.end())\n {\n throw option_not_present_exception(option);\n }\n\n return *iter->second;\n }\n\n private:\n friend class OptionAdder;\n\n void\n parse_option\n (\n std::shared_ptr<OptionDetails> value,\n const std::string& name, \n const std::string& arg = \"\"\n );\n \n void\n checked_parse_arg\n (\n int argc,\n char* argv[],\n int argPos,\n std::shared_ptr<OptionDetails> value,\n const std::string& name\n );\n\n\n std::map<std::string, std::shared_ptr<OptionDetails>> m_options;\n };\n\n class OptionAdder\n {\n public:\n\n OptionAdder(Options& options)\n : m_options(options)\n {\n }\n\n OptionAdder&\n operator()\n ( \n const std::string& opts, \n const std::string& desc,\n std::shared_ptr<const Value> value\n = ::cxxopts::value<bool>()\n );\n\n private:\n Options& m_options;\n };\n\n}\n<commit_msg>remove boost dependency<commit_after>\/*\n\nCopyright (c) 2014 Jarryd Beck\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*\/\n\n#include <regex>\n#include <set>\n#include <map>\n#include <exception>\n#include <sstream>\n\nnamespace cxxopts\n{\n class Value\n {\n public:\n\n virtual void\n parse(const std::string& text) const = 0;\n\n virtual bool\n has_arg() const = 0;\n };\n\n namespace values\n {\n template <typename T>\n void\n parse_value(const std::string& text, T& value)\n {\n std::istringstream is(text);\n is >> value;\n }\n\n template <typename T>\n struct value_has_arg\n {\n static constexpr bool value = true;\n };\n\n template <>\n struct value_has_arg<bool>\n {\n static constexpr bool value = false;\n };\n\n template <typename T>\n class default_value : public Value\n {\n public:\n default_value()\n : m_result(std::make_shared<T>())\n , m_store(m_result.get())\n {\n }\n\n default_value(T* t)\n : m_store(t)\n {\n }\n\n void\n parse(const std::string& text) const\n {\n parse_value(text, *m_store);\n }\n\n bool\n has_arg() const\n {\n return value_has_arg<T>::value;\n }\n\n const T&\n get() const\n {\n if (m_store == nullptr)\n {\n return *m_result;\n }\n else\n {\n return *m_store;\n }\n }\n\n private:\n std::shared_ptr<T> m_result;\n T* m_store;\n };\n\n }\n\n template <typename T>\n std::shared_ptr<Value>\n value()\n {\n return std::make_shared<values::default_value<T>>();\n }\n\n class OptionException : public std::exception\n {\n public:\n OptionException(const std::string& message)\n : m_message(message)\n {\n }\n\n virtual const char*\n what() const noexcept\n {\n return m_message.c_str();\n }\n\n private:\n std::string m_message;\n };\n\n class OptionSpecException : public OptionException\n {\n public:\n\n OptionSpecException(const std::string& message)\n : OptionException(message)\n {\n }\n };\n\n class OptionParseException : public OptionException\n {\n public:\n OptionParseException(const std::string& message)\n : OptionException(message)\n {\n }\n };\n\n class option_exists_error : public OptionSpecException\n {\n public:\n option_exists_error(const std::string& option)\n : OptionSpecException(u8\"Option ‘\" + option + u8\"’ already exists\")\n {\n }\n };\n\n class invalid_option_format_error : public OptionSpecException\n {\n public:\n invalid_option_format_error(const std::string& format)\n : OptionSpecException(u8\"Invalid option format ‘\" + format + u8\"’\")\n {\n }\n };\n\n class option_not_exists_exception : public OptionParseException\n {\n public:\n option_not_exists_exception(const std::string& option)\n : OptionParseException(u8\"Option ‘\" + option + u8\"’ does not exist\")\n {\n }\n };\n\n class missing_argument_exception : public OptionParseException\n {\n public:\n missing_argument_exception(const std::string& option)\n : OptionParseException(u8\"Option ‘\" + option + u8\"’ is missing an argument\")\n {\n }\n };\n\n class option_requires_argument_exception : public OptionParseException\n {\n public:\n option_requires_argument_exception(const std::string& option)\n : OptionParseException(u8\"Option ‘\" + option + u8\"’ requires an argument\")\n {\n }\n };\n\n class option_not_has_argument_exception : public OptionParseException\n {\n public:\n option_not_has_argument_exception\n (\n const std::string& option, \n const std::string& arg\n )\n : OptionParseException(\n u8\"Option ‘\" + option + u8\"’ does not take an argument, but argument‘\"\n + arg + \"’ given\")\n {\n }\n };\n\n class option_not_present_exception : public OptionParseException\n {\n public:\n option_not_present_exception(const std::string& option)\n : OptionParseException(u8\"Option ‘\" + option + u8\"’ not present\")\n {\n }\n };\n\n class OptionAdder;\n\n class OptionDetails\n {\n public:\n OptionDetails\n (\n const std::string& description,\n std::shared_ptr<const Value> value\n )\n : m_desc(description)\n , m_value(value)\n , m_count(0)\n {\n }\n\n const std::string& \n description() const\n {\n return m_desc;\n }\n\n bool\n has_arg() const\n {\n return m_value->has_arg();\n }\n\n void\n parse(const std::string& text)\n {\n m_value->parse(text);\n ++m_count;\n }\n\n int\n count() const\n {\n return m_count;\n }\n\n template <typename T>\n const T&\n as() const\n {\n return dynamic_cast<const values::default_value<T>&>(*m_value).get();\n }\n\n private:\n std::string m_desc;\n std::shared_ptr<const Value> m_value;\n int m_count;\n };\n\n class Options\n {\n public:\n\n void\n parse(int& argc, char**& argv);\n\n OptionAdder\n add_options();\n\n int\n count(const std::string& o) const\n {\n auto iter = m_options.find(o);\n if (iter == m_options.end())\n {\n return 0;\n }\n\n return iter->second->count();\n }\n\n const OptionDetails&\n operator[](const std::string& option) const\n {\n auto iter = m_options.find(option);\n\n if (iter == m_options.end())\n {\n throw option_not_present_exception(option);\n }\n\n return *iter->second;\n }\n\n private:\n friend class OptionAdder;\n\n void\n parse_option\n (\n std::shared_ptr<OptionDetails> value,\n const std::string& name, \n const std::string& arg = \"\"\n );\n \n void\n checked_parse_arg\n (\n int argc,\n char* argv[],\n int argPos,\n std::shared_ptr<OptionDetails> value,\n const std::string& name\n );\n\n\n std::map<std::string, std::shared_ptr<OptionDetails>> m_options;\n };\n\n class OptionAdder\n {\n public:\n\n OptionAdder(Options& options)\n : m_options(options)\n {\n }\n\n OptionAdder&\n operator()\n ( \n const std::string& opts, \n const std::string& desc,\n std::shared_ptr<const Value> value\n = ::cxxopts::value<bool>()\n );\n\n private:\n Options& m_options;\n };\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: libmesh.C,v 1.32 2005-05-11 23:11:58 benkirk Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n \n\n\/\/ C++ includes\n#include <iostream>\n\n\/\/ Local includes\n#include \"libmesh.h\"\n#include \"auto_ptr.h\"\n#include \"getpot.h\"\n#include \"reference_counter.h\"\n\n\n\n\n#if defined(HAVE_MPI)\n# include <mpi.h>\n# if defined(HAVE_PETSC)\n# ifndef USE_COMPLEX_NUMBERS\nextern \"C\" {\n# include <petsc.h>\n# include <petscerror.h>\n}\n# else\n# include <petsc.h>\n# include <petscerror.h>\n# endif\n# endif \/\/ #if defined(HAVE_PETSC)\n# if defined(HAVE_SLEPC)\n# ifndef USE_COMPLEX_NUMBERS\nextern \"C\" \n{\n# include <slepc.h>\n}\n# else\n# include <slepc.h>\n# endif\n# endif \/\/ #if defined(HAVE_SLEPC)\n#endif \/\/ #if defined(HAVE_MPI)\n\n\n\/\/ --------------------------------------------------------\n\/\/ Local anonymous namespace to hold miscelaneous variables\nnamespace {\n AutoPtr<GetPot> command_line (NULL);\n bool libmesh_initialized_mpi = false;\n}\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ libMesh data initialization\n#ifdef HAVE_MPI\nMPI_Comm libMesh::COMM_WORLD = MPI_COMM_NULL;\n#endif\n\nPerfLog libMesh::perflog (\"libMesh\",\n#ifdef ENABLE_PERFORMANCE_LOGGING\n\t\t\t\t true\n#else\n\t\t\t\t false\n#endif\n\t\t\t\t );\n\n\nconst Real libMesh::pi = 3.1415926535897932384626433832795029L;\n\n#ifdef USE_COMPLEX_NUMBERS\nconst Number libMesh::imaginary (0., 1.);\nconst Number libMesh::zero (0., 0.);\n#else\nconst Number libMesh::zero = 0.;\n#endif\n\nconst unsigned int libMesh::invalid_uint = static_cast<unsigned int>(-1);\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ libMesh::libMeshPrivateData data initialization\nint libMesh::libMeshPrivateData::_n_processors = 1;\nint libMesh::libMeshPrivateData::_processor_id = 0;\nbool libMesh::libMeshPrivateData::_is_initialized = false;\nSolverPackage libMesh::libMeshPrivateData::_solver_package =\n#if defined(HAVE_PETSC) \/\/ PETSc is the default\n PETSC_SOLVERS;\n#elif defined(HAVE_LASPACK) \/\/ Use LASPACK if PETSc isn't there\n LASPACK_SOLVERS;\n#else \/\/ No valid linear solver package at compile time\n INVALID_SOLVER_PACKAGE;\n#endif\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ libMesh functions\n#ifndef HAVE_MPI\nvoid libMesh::init (int &argc, char** & argv)\n#else\nvoid libMesh::init (int &argc, char** & argv,\n\t\t MPI_Comm COMM_WORLD_IN)\n#endif\n{\n \/\/ should _not_ be initialized already.\n assert (!libMesh::initialized());\n \n \/\/ Build a command-line parser.\n command_line.reset(new GetPot (argc, argv));\n\n\n#if defined(HAVE_MPI)\n\n \/\/ Allow the user to bypass PETSc initialization\n if (!libMesh::on_command_line (\"--disable-mpi\"))\n {\n int flag;\n MPI_Initialized (&flag);\n\n if (!flag)\n\t{\n\t MPI_Init (&argc, &argv);\n\t libmesh_initialized_mpi = true;\n\t}\n \n \/\/ Duplicate the input communicator for internal use\n MPI_Comm_dup (COMM_WORLD_IN, &libMesh::COMM_WORLD);\n MPI_Comm_set_name (libMesh::COMM_WORLD, \"libMesh::COMM_WORLD\");\n \n MPI_Comm_rank (libMesh::COMM_WORLD, &libMeshPrivateData::_processor_id);\n MPI_Comm_size (libMesh::COMM_WORLD, &libMeshPrivateData::_n_processors);\n \n# if defined(HAVE_PETSC)\n \n if (!libMesh::on_command_line (\"--disable-petsc\"))\n\t{\n\t int ierr=0;\n\t ierr = PetscSetCommWorld (libMesh::COMM_WORLD);\n\t CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n# if defined(HAVE_SLEPC)\n\t ierr = SlepcInitialize (&argc, &argv, NULL, NULL);\n\t CHKERRABORT(libMesh::COMM_WORLD,ierr);\n# else\n\t ierr = PetscInitialize (&argc, &argv, NULL, NULL);\n\t CHKERRABORT(libMesh::COMM_WORLD,ierr);\n# endif\n\t}\n# endif\n }\n#else\n\n \/\/ No MPI, can only be uniprocessor\n assert (libMeshPrivateData::_n_processors == 1);\n assert (libMeshPrivateData::_processor_id == 0);\n \n#endif\n \n \/\/ Could we have gotten bad values from the above calls?\n assert (libMeshPrivateData::_n_processors > 0);\n assert (libMeshPrivateData::_processor_id >= 0);\n\n \/\/ Re-parse the command-line arguments. Note that PETSc and MPI\n \/\/ initialization above may have removed command line arguments\n \/\/ that are not relevant to this application in the above calls.\n \/\/ We don't want a false-positive by detecting those arguments.\n command_line->parse_command_line (argc, argv);\n\n \/\/ The following line is an optimization when simultaneous\n \/\/ C and C++ style access to output streams is not required.\n \/\/ The amount of benefit which occurs is probably implementation\n \/\/ defined, and may be nothing. On the other hand, I have seen\n \/\/ some IO tests where IO peformance improves by a factor of two.\n if (!libMesh::on_command_line (\"--sync-with-stdio\"))\n std::ios::sync_with_stdio(false);\n \n \/\/ redirect std::cout to nothing on all\n \/\/ other processors unless explicitly told\n \/\/ not to via the --keep-cout command-line argument.\n if (libMesh::processor_id() != 0)\n if (!libMesh::on_command_line (\"--keep-cout\"))\n std::cout.rdbuf (NULL);\n\n \n \/\/ The library is now ready for use\n libMeshPrivateData::_is_initialized = true;\n\n \n \/\/ Make sure these work. Library methods\n \/\/ depend on these being implemented properly,\n \/\/ so this is a good time to test them!\n assert (libMesh::initialized());\n assert (!libMesh::closed());\n}\n\n\n\nint libMesh::close ()\n{\n\n#if defined(HAVE_MPI)\n \/\/ Allow the user to bypass MPI finalization\n if (!libMesh::on_command_line (\"--disable-mpi\"))\n {\n# if defined(HAVE_PETSC) \n\n \/\/ Allow the user to bypass PETSc finalization\n if (!libMesh::on_command_line (\"--disable-petsc\"))\n\t{\n# if defined(HAVE_SLEPC)\n\t SlepcFinalize();\n# else\n\t PetscFinalize();\n# endif\n\t}\n# endif\n MPI_Comm_free (&libMesh::COMM_WORLD);\n\n if (libmesh_initialized_mpi)\n\tMPI_Finalize();\n }\n#endif\n\n \/\/ Force the \\p ReferenceCounter to print\n \/\/ its reference count information. This allows\n \/\/ us to find memory leaks. By default the\n \/\/ \\p ReferenceCounter only prints its information\n \/\/ when the last created object has been destroyed.\n \/\/ That does no good if we are leaking memory!\n ReferenceCounter::print_info ();\n \n\n \/\/ Print an informative message if we detect a memory leak\n if (ReferenceCounter::n_objects() != 0)\n {\n std::cerr << \"Memory leak detected!\"\n\t\t<< std::endl;\n \n#if !defined(ENABLE_REFERENCE_COUNTING) || defined(NDEBUG)\n\n std::cerr << \"Compile in DEBUG mode with --enable-reference-counting\"\n\t\t<< std::endl\n\t\t<< \"for more information\"\n\t\t<< std::endl;\n#endif\n \n }\n\n\n \/\/ Reconnect the output streams\n \/\/ (don't do this, or we will get messages from objects\n \/\/ that go out of scope after the following return)\n \/\/std::cout.rdbuf(std::cerr.rdbuf());\n\n \n \/\/ Set the initialized() flag to false\n libMeshPrivateData::_is_initialized = false;\n \n\n \/\/ Return the number of outstanding objects.\n \/\/ This is equivalent to return 0 if all of\n \/\/ the reference counted objects have been\n \/\/ deleted.\n return static_cast<int>(ReferenceCounter::n_objects());\n}\n\n\n\nbool libMesh::on_command_line (const std::string& arg)\n{\n \/\/ Make sure the command line parser is ready for use\n assert (command_line.get() != NULL);\n \n return command_line->search (arg);\n}\n\n\n\nSolverPackage libMesh::default_solver_package ()\n{\n assert (libMesh::initialized());\n \n static bool called = false;\n\n \/\/ Check the command line. Since the command line is\n \/\/ unchanging it is sufficient to do this only once.\n if (!called)\n {\n called = true;\n\n#ifdef HAVE_PETSC\n if (libMesh::on_command_line (\"--use-petsc\"))\n\tlibMeshPrivateData::_solver_package = PETSC_SOLVERS;\n#endif\n \n#ifdef HAVE_LASPACK\n if (libMesh::on_command_line (\"--use-laspack\" ) ||\n\t libMesh::on_command_line (\"--disable-petsc\"))\n\tlibMeshPrivateData::_solver_package = LASPACK_SOLVERS;\n#endif\n \n }\n \n \n return libMeshPrivateData::_solver_package; \n}\n<commit_msg>removed deprecated PetscSetCommWorld<commit_after>\/\/ $Id: libmesh.C,v 1.33 2005-05-17 15:56:45 benkirk Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n \n\n\/\/ C++ includes\n#include <iostream>\n\n\/\/ Local includes\n#include \"libmesh.h\"\n#include \"auto_ptr.h\"\n#include \"getpot.h\"\n#include \"reference_counter.h\"\n\n\n\n\n#if defined(HAVE_MPI)\n# include <mpi.h>\n# if defined(HAVE_PETSC)\n# ifndef USE_COMPLEX_NUMBERS\nextern \"C\" {\n# include <petsc.h>\n# include <petscerror.h>\n}\n# else\n# include <petsc.h>\n# include <petscerror.h>\n# endif\n# endif \/\/ #if defined(HAVE_PETSC)\n# if defined(HAVE_SLEPC)\n# ifndef USE_COMPLEX_NUMBERS\nextern \"C\" \n{\n# include <slepc.h>\n}\n# else\n# include <slepc.h>\n# endif\n# endif \/\/ #if defined(HAVE_SLEPC)\n#endif \/\/ #if defined(HAVE_MPI)\n\n\n\/\/ --------------------------------------------------------\n\/\/ Local anonymous namespace to hold miscelaneous variables\nnamespace {\n AutoPtr<GetPot> command_line (NULL);\n bool libmesh_initialized_mpi = false;\n}\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ libMesh data initialization\n#ifdef HAVE_MPI\nMPI_Comm libMesh::COMM_WORLD = MPI_COMM_NULL;\n#endif\n\nPerfLog libMesh::perflog (\"libMesh\",\n#ifdef ENABLE_PERFORMANCE_LOGGING\n\t\t\t\t true\n#else\n\t\t\t\t false\n#endif\n\t\t\t\t );\n\n\nconst Real libMesh::pi = 3.1415926535897932384626433832795029L;\n\n#ifdef USE_COMPLEX_NUMBERS\nconst Number libMesh::imaginary (0., 1.);\nconst Number libMesh::zero (0., 0.);\n#else\nconst Number libMesh::zero = 0.;\n#endif\n\nconst unsigned int libMesh::invalid_uint = static_cast<unsigned int>(-1);\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ libMesh::libMeshPrivateData data initialization\nint libMesh::libMeshPrivateData::_n_processors = 1;\nint libMesh::libMeshPrivateData::_processor_id = 0;\nbool libMesh::libMeshPrivateData::_is_initialized = false;\nSolverPackage libMesh::libMeshPrivateData::_solver_package =\n#if defined(HAVE_PETSC) \/\/ PETSc is the default\n PETSC_SOLVERS;\n#elif defined(HAVE_LASPACK) \/\/ Use LASPACK if PETSc isn't there\n LASPACK_SOLVERS;\n#else \/\/ No valid linear solver package at compile time\n INVALID_SOLVER_PACKAGE;\n#endif\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ libMesh functions\n#ifndef HAVE_MPI\nvoid libMesh::init (int &argc, char** & argv)\n#else\nvoid libMesh::init (int &argc, char** & argv,\n\t\t MPI_Comm COMM_WORLD_IN)\n#endif\n{\n \/\/ should _not_ be initialized already.\n assert (!libMesh::initialized());\n \n \/\/ Build a command-line parser.\n command_line.reset(new GetPot (argc, argv));\n\n\n#if defined(HAVE_MPI)\n\n \/\/ Allow the user to bypass PETSc initialization\n if (!libMesh::on_command_line (\"--disable-mpi\"))\n {\n int flag;\n MPI_Initialized (&flag);\n\n if (!flag)\n\t{\n\t MPI_Init (&argc, &argv);\n\t libmesh_initialized_mpi = true;\n\t}\n \n \/\/ Duplicate the input communicator for internal use\n MPI_Comm_dup (COMM_WORLD_IN, &libMesh::COMM_WORLD);\n MPI_Comm_set_name (libMesh::COMM_WORLD, \"libMesh::COMM_WORLD\");\n \n MPI_Comm_rank (libMesh::COMM_WORLD, &libMeshPrivateData::_processor_id);\n MPI_Comm_size (libMesh::COMM_WORLD, &libMeshPrivateData::_n_processors);\n \n# if defined(HAVE_PETSC)\n \n if (!libMesh::on_command_line (\"--disable-petsc\"))\n\t{\t \n\t PETSC_COMM_WORLD = libMesh::COMM_WORLD;\n\n# if defined(HAVE_SLEPC)\n\t ierr = SlepcInitialize (&argc, &argv, NULL, NULL);\n\t CHKERRABORT(libMesh::COMM_WORLD,ierr);\n# else\n\t ierr = PetscInitialize (&argc, &argv, NULL, NULL);\n\t CHKERRABORT(libMesh::COMM_WORLD,ierr);\n# endif\n\t}\n# endif\n }\n#else\n\n \/\/ No MPI, can only be uniprocessor\n assert (libMeshPrivateData::_n_processors == 1);\n assert (libMeshPrivateData::_processor_id == 0);\n \n#endif\n \n \/\/ Could we have gotten bad values from the above calls?\n assert (libMeshPrivateData::_n_processors > 0);\n assert (libMeshPrivateData::_processor_id >= 0);\n\n \/\/ Re-parse the command-line arguments. Note that PETSc and MPI\n \/\/ initialization above may have removed command line arguments\n \/\/ that are not relevant to this application in the above calls.\n \/\/ We don't want a false-positive by detecting those arguments.\n command_line->parse_command_line (argc, argv);\n\n \/\/ The following line is an optimization when simultaneous\n \/\/ C and C++ style access to output streams is not required.\n \/\/ The amount of benefit which occurs is probably implementation\n \/\/ defined, and may be nothing. On the other hand, I have seen\n \/\/ some IO tests where IO peformance improves by a factor of two.\n if (!libMesh::on_command_line (\"--sync-with-stdio\"))\n std::ios::sync_with_stdio(false);\n \n \/\/ redirect std::cout to nothing on all\n \/\/ other processors unless explicitly told\n \/\/ not to via the --keep-cout command-line argument.\n if (libMesh::processor_id() != 0)\n if (!libMesh::on_command_line (\"--keep-cout\"))\n std::cout.rdbuf (NULL);\n\n \n \/\/ The library is now ready for use\n libMeshPrivateData::_is_initialized = true;\n\n \n \/\/ Make sure these work. Library methods\n \/\/ depend on these being implemented properly,\n \/\/ so this is a good time to test them!\n assert (libMesh::initialized());\n assert (!libMesh::closed());\n}\n\n\n\nint libMesh::close ()\n{\n\n#if defined(HAVE_MPI)\n \/\/ Allow the user to bypass MPI finalization\n if (!libMesh::on_command_line (\"--disable-mpi\"))\n {\n# if defined(HAVE_PETSC) \n\n \/\/ Allow the user to bypass PETSc finalization\n if (!libMesh::on_command_line (\"--disable-petsc\"))\n\t{\n# if defined(HAVE_SLEPC)\n\t SlepcFinalize();\n# else\n\t PetscFinalize();\n# endif\n\t}\n# endif\n MPI_Comm_free (&libMesh::COMM_WORLD);\n\n if (libmesh_initialized_mpi)\n\tMPI_Finalize();\n }\n#endif\n\n \/\/ Force the \\p ReferenceCounter to print\n \/\/ its reference count information. This allows\n \/\/ us to find memory leaks. By default the\n \/\/ \\p ReferenceCounter only prints its information\n \/\/ when the last created object has been destroyed.\n \/\/ That does no good if we are leaking memory!\n ReferenceCounter::print_info ();\n \n\n \/\/ Print an informative message if we detect a memory leak\n if (ReferenceCounter::n_objects() != 0)\n {\n std::cerr << \"Memory leak detected!\"\n\t\t<< std::endl;\n \n#if !defined(ENABLE_REFERENCE_COUNTING) || defined(NDEBUG)\n\n std::cerr << \"Compile in DEBUG mode with --enable-reference-counting\"\n\t\t<< std::endl\n\t\t<< \"for more information\"\n\t\t<< std::endl;\n#endif\n \n }\n\n\n \/\/ Reconnect the output streams\n \/\/ (don't do this, or we will get messages from objects\n \/\/ that go out of scope after the following return)\n \/\/std::cout.rdbuf(std::cerr.rdbuf());\n\n \n \/\/ Set the initialized() flag to false\n libMeshPrivateData::_is_initialized = false;\n \n\n \/\/ Return the number of outstanding objects.\n \/\/ This is equivalent to return 0 if all of\n \/\/ the reference counted objects have been\n \/\/ deleted.\n return static_cast<int>(ReferenceCounter::n_objects());\n}\n\n\n\nbool libMesh::on_command_line (const std::string& arg)\n{\n \/\/ Make sure the command line parser is ready for use\n assert (command_line.get() != NULL);\n \n return command_line->search (arg);\n}\n\n\n\nSolverPackage libMesh::default_solver_package ()\n{\n assert (libMesh::initialized());\n \n static bool called = false;\n\n \/\/ Check the command line. Since the command line is\n \/\/ unchanging it is sufficient to do this only once.\n if (!called)\n {\n called = true;\n\n#ifdef HAVE_PETSC\n if (libMesh::on_command_line (\"--use-petsc\"))\n\tlibMeshPrivateData::_solver_package = PETSC_SOLVERS;\n#endif\n \n#ifdef HAVE_LASPACK\n if (libMesh::on_command_line (\"--use-laspack\" ) ||\n\t libMesh::on_command_line (\"--disable-petsc\"))\n\tlibMeshPrivateData::_solver_package = LASPACK_SOLVERS;\n#endif\n \n }\n \n \n return libMeshPrivateData::_solver_package; \n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993-2010 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"Score.h\"\n#include \"bzfsAPI.h\"\n#include \"WorldEventManager.h\"\n\n\/\/ bzflag library headers\n#include \"Pack.h\"\n\n\/\/ API headers for notification\n\nfloat Score::tkKickRatio = 3.0;\nint Score::score = 999;\nbool Score::randomRanking = false;\n\nbool Score::KeepPlayerScores = true;\nbool Score::KeepTeamScores = true;\n\nScore::Score(): wins(0), losses(0), tks(0) {\n playerID = -1;\n}\n\nvoid Score::dump() {\n std::cout << wins << '-' << losses;\n}\n\nfloat Score::ranking() {\n if (randomRanking)\n return (float)bzfrand();\n\n \/\/ otherwise do score-based ranking\n int sum = wins + losses;\n if (sum == 0)\n return 0.5;\n float average = (float)wins\/(float)sum;\n \/\/ IIRC that is how wide is the gaussian\n float penalty = (1.0f - 0.5f \/ sqrt((float)sum));\n return average * penalty;\n}\n\nbool Score::isTK() {\n \/\/ arbitrary 3\n return (tks >= 3) && (tkKickRatio > 0)\n && ((wins == 0) || (tks * 100 \/ wins > tkKickRatio));\n}\n\nvoid Score::tK() {\n if (KeepPlayerScores)\n {\n ++tks;\n worldEventManager.callEvents(bz_PlayerScoreChangeEventData_V1(playerID,bz_eTKs, tks-1, tks));\n }\n}\n\nvoid Score::killedBy() {\n if (KeepPlayerScores)\n {\n ++losses;\n worldEventManager.callEvents(bz_PlayerScoreChangeEventData_V1(playerID,bz_eLosses, losses-1, losses));\n }\n}\n\nvoid Score::kill() {\n if (KeepPlayerScores)\n {\n ++wins;\n worldEventManager.callEvents(bz_PlayerScoreChangeEventData_V1(playerID,bz_eWins, wins-1, wins));\n }\n}\n\nvoid *Score::pack(void *buf) {\n buf = nboPackUShort(buf, wins);\n buf = nboPackUShort(buf, losses);\n buf = nboPackUShort(buf, tks);\n return buf;\n}\n\nbool Score::reached() {\n return wins - losses >= score;\n}\n\nvoid Score::setTeamKillRatio(int _tkKickRatio) {\n tkKickRatio = (float)_tkKickRatio;\n}\n\nvoid Score::setWinLimit(int _score) {\n score = _score;\n}\n\nvoid Score::setRandomRanking() {\n randomRanking = true;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>ws<commit_after>\/* bzflag\n * Copyright (c) 1993-2010 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"Score.h\"\n#include \"bzfsAPI.h\"\n#include \"WorldEventManager.h\"\n\n\/\/ bzflag library headers\n#include \"Pack.h\"\n\n\/\/ API headers for notification\n\nfloat Score::tkKickRatio = 3.0;\nint Score::score = 999;\nbool Score::randomRanking = false;\n\nbool Score::KeepPlayerScores = true;\nbool Score::KeepTeamScores = true;\n\nScore::Score(): wins(0), losses(0), tks(0) {\n playerID = -1;\n}\n\nvoid Score::dump() {\n std::cout << wins << '-' << losses;\n}\n\nfloat Score::ranking() {\n if (randomRanking)\n return (float)bzfrand();\n\n \/\/ otherwise do score-based ranking\n int sum = wins + losses;\n if (sum == 0)\n return 0.5;\n float average = (float)wins\/(float)sum;\n \/\/ IIRC that is how wide is the gaussian\n float penalty = (1.0f - 0.5f \/ sqrt((float)sum));\n return average * penalty;\n}\n\nbool Score::isTK() {\n \/\/ arbitrary 3\n return (tks >= 3) && (tkKickRatio > 0)\n && ((wins == 0) || (tks * 100 \/ wins > tkKickRatio));\n}\n\nvoid Score::tK() {\n if (KeepPlayerScores) {\n ++tks;\n worldEventManager.callEvents(bz_PlayerScoreChangeEventData_V1(playerID,bz_eTKs, tks-1, tks));\n }\n}\n\nvoid Score::killedBy() {\n if (KeepPlayerScores) {\n ++losses;\n worldEventManager.callEvents(bz_PlayerScoreChangeEventData_V1(playerID,bz_eLosses, losses-1, losses));\n }\n}\n\nvoid Score::kill() {\n if (KeepPlayerScores) {\n ++wins;\n worldEventManager.callEvents(bz_PlayerScoreChangeEventData_V1(playerID,bz_eWins, wins-1, wins));\n }\n}\n\nvoid *Score::pack(void *buf) {\n buf = nboPackUShort(buf, wins);\n buf = nboPackUShort(buf, losses);\n buf = nboPackUShort(buf, tks);\n return buf;\n}\n\nbool Score::reached() {\n return wins - losses >= score;\n}\n\nvoid Score::setTeamKillRatio(int _tkKickRatio) {\n tkKickRatio = (float)_tkKickRatio;\n}\n\nvoid Score::setWinLimit(int _score) {\n score = _score;\n}\n\nvoid Score::setRandomRanking() {\n randomRanking = true;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2019 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\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 *\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\n * distribution.\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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Client.hxx\"\n#include \"Error.hxx\"\n#include \"Parser.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"pool\/LeakDetector.hxx\"\n#include \"istream\/Handler.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"istream\/Pointer.hxx\"\n#include \"istream\/istream_null.hxx\"\n#include \"http\/HeaderParser.hxx\"\n#include \"stopwatch.hxx\"\n#include \"strmap.hxx\"\n#include \"HttpResponseHandler.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"util\/Cast.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"util\/DestructObserver.hxx\"\n#include \"util\/Exception.hxx\"\n\n#include <string.h>\n#include <stdlib.h>\n\nclass CGIClient final : PoolLeakDetector, Istream, IstreamHandler, Cancellable, DestructAnchor {\n const StopwatchPtr stopwatch;\n\n IstreamPointer input;\n SliceFifoBuffer buffer;\n\n CGIParser parser;\n\n \/**\n * This flag is true while cgi_parse_headers() is calling\n * HttpResponseHandler::InvokeResponse(). In this case,\n * istream_read(cgi->input) is already up in the stack, and must\n * not be called again.\n *\/\n bool in_response_callback;\n\n bool had_input, had_output;\n\n HttpResponseHandler &handler;\n\npublic:\n CGIClient(struct pool &_pool, StopwatchPtr &&_stopwatch,\n UnusedIstreamPtr _input,\n HttpResponseHandler &_handler,\n CancellablePointer &cancel_ptr);\n\n \/**\n * @return false if the connection has been closed\n *\/\n bool ReturnResponse();\n\n \/**\n * Feed data into the input buffer and continue parsing response\n * headers from it. After this function returns, the response may\n * have been delivered to the response handler, and the caller should\n * post the rest of the specified buffer to the response body stream.\n *\n * Caller must hold pool reference.\n *\n * @return the number of bytes consumed from the specified buffer\n * (moved to the input buffer), 0 if the object has been closed\n *\/\n size_t FeedHeaders(const void *data, size_t length);\n\n \/**\n * Call FeedHeaders() in a loop, to parse as much as possible.\n *\n * Caller must hold pool reference.\n *\/\n size_t FeedHeadersLoop(const char *data, size_t length);\n\n \/**\n * Caller must hold pool reference.\n *\/\n size_t FeedHeadersCheck(const char *data, size_t length);\n\n size_t FeedBody(const char *data, size_t length);\n\n \/* virtual methods from class Cancellable *\/\n void Cancel() noexcept override;\n\n \/* virtual methods from class Istream *\/\n off_t _GetAvailable(bool partial) noexcept override;\n void _Read() noexcept override;\n void _Close() noexcept override;\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) noexcept override;\n ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override;\n void OnEof() noexcept override;\n void OnError(std::exception_ptr ep) noexcept override;\n};\n\ninline bool\nCGIClient::ReturnResponse()\n{\n http_status_t status = parser.GetStatus();\n StringMap &headers = parser.GetHeaders();\n\n if (http_status_is_empty(status)) {\n \/* this response does not have a response body, as indicated\n by the HTTP status code *\/\n\n stopwatch.RecordEvent(\"empty\");\n\n buffer.Free();\n input.ClearAndClose();\n handler.InvokeResponse(status, std::move(headers), UnusedIstreamPtr());\n Destroy();\n return false;\n } else if (parser.IsEOF()) {\n \/* the response body is empty *\/\n\n stopwatch.RecordEvent(\"empty\");\n\n buffer.Free();\n input.ClearAndClose();\n handler.InvokeResponse(status, std::move(headers),\n istream_null_new(GetPool()));\n Destroy();\n return false;\n } else {\n stopwatch.RecordEvent(\"headers\");\n\n const DestructObserver destructed(*this);\n\n in_response_callback = true;\n handler.InvokeResponse(status, std::move(headers),\n UnusedIstreamPtr(this));\n if (destructed)\n return false;\n\n in_response_callback = false;\n return true;\n }\n}\n\ninline size_t\nCGIClient::FeedHeaders(const void *data, size_t length)\ntry {\n assert(!parser.AreHeadersFinished());\n\n auto w = buffer.Write();\n assert(!w.empty());\n\n if (length > w.size)\n length = w.size;\n\n memcpy(w.data, data, length);\n buffer.Append(length);\n\n switch (parser.FeedHeaders(GetPool(), buffer)) {\n case Completion::DONE:\n \/* the DONE status can only be triggered by new data that\n was just received; therefore, the amount of data still in\n the buffer (= response body) must be smaller *\/\n assert(buffer.GetAvailable() < length);\n\n if (!ReturnResponse())\n return 0;\n\n \/* don't consider data still in the buffer (= response body)\n as \"consumed\"; the caller will attempt to submit it to the\n response body handler *\/\n return length - buffer.GetAvailable();\n\n case Completion::MORE:\n return length;\n\n case Completion::CLOSED:\n \/* unreachable *\/\n assert(false);\n return 0;\n }\n\n \/* unreachable *\/\n assert(false);\n return 0;\n} catch (...) {\n buffer.Free();\n input.ClearAndClose();\n handler.InvokeError(std::current_exception());\n Destroy();\n return 0;\n}\n\ninline size_t\nCGIClient::FeedHeadersLoop(const char *data, size_t length)\n{\n assert(length > 0);\n assert(!parser.AreHeadersFinished());\n\n const DestructObserver destructed(*this);\n size_t consumed = 0;\n\n do {\n size_t nbytes = FeedHeaders(data + consumed, length - consumed);\n if (nbytes == 0)\n break;\n\n consumed += nbytes;\n } while (consumed < length && !parser.AreHeadersFinished());\n\n if (destructed)\n return 0;\n\n return consumed;\n}\n\ninline size_t\nCGIClient::FeedHeadersCheck(const char *data, size_t length)\n{\n size_t nbytes = FeedHeadersLoop(data, length);\n\n assert(nbytes == 0 || input.IsDefined());\n assert(nbytes == 0 ||\n !parser.AreHeadersFinished() ||\n !parser.IsEOF());\n\n return nbytes;\n}\n\ninline size_t\nCGIClient::FeedBody(const char *data, size_t length)\n{\n if (parser.IsTooMuch(length)) {\n stopwatch.RecordEvent(\"malformed\");\n\n buffer.Free();\n input.ClearAndClose();\n\n DestroyError(std::make_exception_ptr(CgiError(\"too much data from CGI script\")));\n return 0;\n }\n\n had_output = true;\n\n size_t nbytes = InvokeData(data, length);\n if (nbytes > 0 && parser.BodyConsumed(nbytes)) {\n stopwatch.RecordEvent(\"end\");\n\n buffer.Free();\n input.ClearAndClose();\n DestroyEof();\n return 0;\n }\n\n return nbytes;\n}\n\n\/*\n * input handler\n *\n *\/\n\nsize_t\nCGIClient::OnData(const void *data, size_t length) noexcept\n{\n assert(input.IsDefined());\n\n had_input = true;\n\n if (!parser.AreHeadersFinished()) {\n size_t nbytes = FeedHeadersCheck((const char *)data, length);\n\n if (nbytes > 0 && nbytes < length &&\n parser.AreHeadersFinished()) {\n \/* the headers are finished; now begin sending the\n response body *\/\n const DestructObserver destructed(*this);\n size_t nbytes2 = FeedBody((const char *)data + nbytes,\n length - nbytes);\n if (nbytes2 > 0)\n \/* more data was consumed *\/\n nbytes += nbytes2;\n else if (destructed)\n \/* the connection was closed, must return 0 *\/\n nbytes = 0;\n }\n\n return nbytes;\n } else {\n return FeedBody((const char *)data, length);\n }\n}\n\nssize_t\nCGIClient::OnDirect(FdType type, int fd, size_t max_length) noexcept\n{\n assert(parser.AreHeadersFinished());\n\n had_input = true;\n had_output = true;\n\n if (parser.KnownLength() &&\n (off_t)max_length > parser.GetAvailable())\n max_length = (size_t)parser.GetAvailable();\n\n ssize_t nbytes = InvokeDirect(type, fd, max_length);\n if (nbytes > 0 && parser.BodyConsumed(nbytes)) {\n stopwatch.RecordEvent(\"end\");\n\n buffer.Free();\n input.Close();\n DestroyEof();\n return ISTREAM_RESULT_CLOSED;\n }\n\n return nbytes;\n}\n\nvoid\nCGIClient::OnEof() noexcept\n{\n input.Clear();\n\n if (!parser.AreHeadersFinished()) {\n stopwatch.RecordEvent(\"malformed\");\n\n assert(!HasHandler());\n\n buffer.Free();\n\n handler.InvokeError(std::make_exception_ptr(CgiError(\"premature end of headers from CGI script\")));\n Destroy();\n } else if (parser.DoesRequireMore()) {\n stopwatch.RecordEvent(\"malformed\");\n\n buffer.Free();\n\n DestroyError(std::make_exception_ptr(CgiError(\"premature end of response body from CGI script\")));\n } else {\n stopwatch.RecordEvent(\"end\");\n\n buffer.Free();\n DestroyEof();\n }\n}\n\nvoid\nCGIClient::OnError(std::exception_ptr ep) noexcept\n{\n stopwatch.RecordEvent(\"error\");\n\n input.Clear();\n\n if (!parser.AreHeadersFinished()) {\n \/* the response hasn't been sent yet: notify the response\n handler *\/\n assert(!HasHandler());\n\n buffer.Free();\n\n handler.InvokeError(NestException(ep,\n std::runtime_error(\"CGI request body failed\")));\n Destroy();\n } else {\n \/* response has been sent: abort only the output stream *\/\n buffer.Free();\n DestroyError(ep);\n }\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nCGIClient::_GetAvailable(bool partial) noexcept\n{\n if (parser.KnownLength())\n return parser.GetAvailable();\n\n if (!input.IsDefined())\n return 0;\n\n if (in_response_callback)\n \/* this condition catches the case in cgi_parse_headers():\n HttpResponseHandler::InvokeResponse() might\n recursively call istream_read(input) *\/\n return (off_t)-1;\n\n return input.GetAvailable(partial);\n}\n\nvoid\nCGIClient::_Read() noexcept\n{\n if (input.IsDefined()) {\n input.SetDirect(GetHandlerDirect());\n\n \/* this condition catches the case in cgi_parse_headers():\n HttpResponseHandler::InvokeResponse() might\n recursively call input.Read() *\/\n if (in_response_callback) {\n return;\n }\n\n const DestructObserver destructed(*this);\n\n had_output = false;\n do {\n had_input = false;\n input.Read();\n } while (!destructed && input.IsDefined() && had_input && !had_output);\n }\n}\n\nvoid\nCGIClient::_Close() noexcept\n{\n buffer.Free();\n\n if (input.IsDefined())\n input.ClearAndClose();\n\n Destroy();\n}\n\n\/*\n * async operation\n *\n *\/\n\nvoid\nCGIClient::Cancel() noexcept\n{\n assert(input.IsDefined());\n\n buffer.Free();\n input.Close();\n Destroy();\n}\n\n\n\/*\n * constructor\n *\n *\/\n\ninline\nCGIClient::CGIClient(struct pool &_pool, StopwatchPtr &&_stopwatch,\n UnusedIstreamPtr _input,\n HttpResponseHandler &_handler,\n CancellablePointer &cancel_ptr)\n :PoolLeakDetector(_pool), Istream(_pool),\n stopwatch(std::move(_stopwatch)),\n input(std::move(_input), *this),\n buffer(fb_pool_get()),\n parser(_pool),\n handler(_handler)\n{\n cancel_ptr = *this;\n\n input.Read();\n}\n\nvoid\ncgi_client_new(struct pool &pool, StopwatchPtr stopwatch,\n UnusedIstreamPtr input,\n HttpResponseHandler &handler,\n CancellablePointer &cancel_ptr)\n{\n NewFromPool<CGIClient>(pool, pool, std::move(stopwatch),\n std::move(input),\n handler, cancel_ptr);\n}\n<commit_msg>cgi\/Client: destroy before invoking the handler<commit_after>\/*\n * Copyright 2007-2019 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\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 *\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\n * distribution.\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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Client.hxx\"\n#include \"Error.hxx\"\n#include \"Parser.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"pool\/LeakDetector.hxx\"\n#include \"istream\/Handler.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"istream\/Pointer.hxx\"\n#include \"istream\/istream_null.hxx\"\n#include \"http\/HeaderParser.hxx\"\n#include \"stopwatch.hxx\"\n#include \"strmap.hxx\"\n#include \"HttpResponseHandler.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"util\/Cast.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"util\/DestructObserver.hxx\"\n#include \"util\/Exception.hxx\"\n\n#include <string.h>\n#include <stdlib.h>\n\nclass CGIClient final : PoolLeakDetector, Istream, IstreamHandler, Cancellable, DestructAnchor {\n const StopwatchPtr stopwatch;\n\n IstreamPointer input;\n SliceFifoBuffer buffer;\n\n CGIParser parser;\n\n \/**\n * This flag is true while cgi_parse_headers() is calling\n * HttpResponseHandler::InvokeResponse(). In this case,\n * istream_read(cgi->input) is already up in the stack, and must\n * not be called again.\n *\/\n bool in_response_callback;\n\n bool had_input, had_output;\n\n HttpResponseHandler &handler;\n\npublic:\n CGIClient(struct pool &_pool, StopwatchPtr &&_stopwatch,\n UnusedIstreamPtr _input,\n HttpResponseHandler &_handler,\n CancellablePointer &cancel_ptr);\n\n \/**\n * @return false if the connection has been closed\n *\/\n bool ReturnResponse();\n\n \/**\n * Feed data into the input buffer and continue parsing response\n * headers from it. After this function returns, the response may\n * have been delivered to the response handler, and the caller should\n * post the rest of the specified buffer to the response body stream.\n *\n * Caller must hold pool reference.\n *\n * @return the number of bytes consumed from the specified buffer\n * (moved to the input buffer), 0 if the object has been closed\n *\/\n size_t FeedHeaders(const void *data, size_t length);\n\n \/**\n * Call FeedHeaders() in a loop, to parse as much as possible.\n *\n * Caller must hold pool reference.\n *\/\n size_t FeedHeadersLoop(const char *data, size_t length);\n\n \/**\n * Caller must hold pool reference.\n *\/\n size_t FeedHeadersCheck(const char *data, size_t length);\n\n size_t FeedBody(const char *data, size_t length);\n\n \/* virtual methods from class Cancellable *\/\n void Cancel() noexcept override;\n\n \/* virtual methods from class Istream *\/\n off_t _GetAvailable(bool partial) noexcept override;\n void _Read() noexcept override;\n void _Close() noexcept override;\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) noexcept override;\n ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override;\n void OnEof() noexcept override;\n void OnError(std::exception_ptr ep) noexcept override;\n};\n\ninline bool\nCGIClient::ReturnResponse()\n{\n http_status_t status = parser.GetStatus();\n StringMap &headers = parser.GetHeaders();\n\n if (http_status_is_empty(status)) {\n \/* this response does not have a response body, as indicated\n by the HTTP status code *\/\n\n stopwatch.RecordEvent(\"empty\");\n\n buffer.Free();\n input.ClearAndClose();\n\n auto &_handler = handler;\n Destroy();\n _handler.InvokeResponse(status, std::move(headers), UnusedIstreamPtr());\n return false;\n } else if (parser.IsEOF()) {\n \/* the response body is empty *\/\n\n stopwatch.RecordEvent(\"empty\");\n\n buffer.Free();\n input.ClearAndClose();\n auto &_handler = handler;\n Destroy();\n _handler.InvokeResponse(status, std::move(headers),\n istream_null_new(GetPool()));\n return false;\n } else {\n stopwatch.RecordEvent(\"headers\");\n\n const DestructObserver destructed(*this);\n\n in_response_callback = true;\n handler.InvokeResponse(status, std::move(headers),\n UnusedIstreamPtr(this));\n if (destructed)\n return false;\n\n in_response_callback = false;\n return true;\n }\n}\n\ninline size_t\nCGIClient::FeedHeaders(const void *data, size_t length)\ntry {\n assert(!parser.AreHeadersFinished());\n\n auto w = buffer.Write();\n assert(!w.empty());\n\n if (length > w.size)\n length = w.size;\n\n memcpy(w.data, data, length);\n buffer.Append(length);\n\n switch (parser.FeedHeaders(GetPool(), buffer)) {\n case Completion::DONE:\n \/* the DONE status can only be triggered by new data that\n was just received; therefore, the amount of data still in\n the buffer (= response body) must be smaller *\/\n assert(buffer.GetAvailable() < length);\n\n if (!ReturnResponse())\n return 0;\n\n \/* don't consider data still in the buffer (= response body)\n as \"consumed\"; the caller will attempt to submit it to the\n response body handler *\/\n return length - buffer.GetAvailable();\n\n case Completion::MORE:\n return length;\n\n case Completion::CLOSED:\n \/* unreachable *\/\n assert(false);\n return 0;\n }\n\n \/* unreachable *\/\n assert(false);\n return 0;\n} catch (...) {\n buffer.Free();\n input.ClearAndClose();\n auto &_handler = handler;\n Destroy();\n _handler.InvokeError(std::current_exception());\n return 0;\n}\n\ninline size_t\nCGIClient::FeedHeadersLoop(const char *data, size_t length)\n{\n assert(length > 0);\n assert(!parser.AreHeadersFinished());\n\n const DestructObserver destructed(*this);\n size_t consumed = 0;\n\n do {\n size_t nbytes = FeedHeaders(data + consumed, length - consumed);\n if (nbytes == 0)\n break;\n\n consumed += nbytes;\n } while (consumed < length && !parser.AreHeadersFinished());\n\n if (destructed)\n return 0;\n\n return consumed;\n}\n\ninline size_t\nCGIClient::FeedHeadersCheck(const char *data, size_t length)\n{\n size_t nbytes = FeedHeadersLoop(data, length);\n\n assert(nbytes == 0 || input.IsDefined());\n assert(nbytes == 0 ||\n !parser.AreHeadersFinished() ||\n !parser.IsEOF());\n\n return nbytes;\n}\n\ninline size_t\nCGIClient::FeedBody(const char *data, size_t length)\n{\n if (parser.IsTooMuch(length)) {\n stopwatch.RecordEvent(\"malformed\");\n\n buffer.Free();\n input.ClearAndClose();\n\n DestroyError(std::make_exception_ptr(CgiError(\"too much data from CGI script\")));\n return 0;\n }\n\n had_output = true;\n\n size_t nbytes = InvokeData(data, length);\n if (nbytes > 0 && parser.BodyConsumed(nbytes)) {\n stopwatch.RecordEvent(\"end\");\n\n buffer.Free();\n input.ClearAndClose();\n DestroyEof();\n return 0;\n }\n\n return nbytes;\n}\n\n\/*\n * input handler\n *\n *\/\n\nsize_t\nCGIClient::OnData(const void *data, size_t length) noexcept\n{\n assert(input.IsDefined());\n\n had_input = true;\n\n if (!parser.AreHeadersFinished()) {\n size_t nbytes = FeedHeadersCheck((const char *)data, length);\n\n if (nbytes > 0 && nbytes < length &&\n parser.AreHeadersFinished()) {\n \/* the headers are finished; now begin sending the\n response body *\/\n const DestructObserver destructed(*this);\n size_t nbytes2 = FeedBody((const char *)data + nbytes,\n length - nbytes);\n if (nbytes2 > 0)\n \/* more data was consumed *\/\n nbytes += nbytes2;\n else if (destructed)\n \/* the connection was closed, must return 0 *\/\n nbytes = 0;\n }\n\n return nbytes;\n } else {\n return FeedBody((const char *)data, length);\n }\n}\n\nssize_t\nCGIClient::OnDirect(FdType type, int fd, size_t max_length) noexcept\n{\n assert(parser.AreHeadersFinished());\n\n had_input = true;\n had_output = true;\n\n if (parser.KnownLength() &&\n (off_t)max_length > parser.GetAvailable())\n max_length = (size_t)parser.GetAvailable();\n\n ssize_t nbytes = InvokeDirect(type, fd, max_length);\n if (nbytes > 0 && parser.BodyConsumed(nbytes)) {\n stopwatch.RecordEvent(\"end\");\n\n buffer.Free();\n input.Close();\n DestroyEof();\n return ISTREAM_RESULT_CLOSED;\n }\n\n return nbytes;\n}\n\nvoid\nCGIClient::OnEof() noexcept\n{\n input.Clear();\n\n if (!parser.AreHeadersFinished()) {\n stopwatch.RecordEvent(\"malformed\");\n\n assert(!HasHandler());\n\n buffer.Free();\n\n auto &_handler = handler;\n Destroy();\n _handler.InvokeError(std::make_exception_ptr(CgiError(\"premature end of headers from CGI script\")));\n } else if (parser.DoesRequireMore()) {\n stopwatch.RecordEvent(\"malformed\");\n\n buffer.Free();\n\n DestroyError(std::make_exception_ptr(CgiError(\"premature end of response body from CGI script\")));\n } else {\n stopwatch.RecordEvent(\"end\");\n\n buffer.Free();\n DestroyEof();\n }\n}\n\nvoid\nCGIClient::OnError(std::exception_ptr ep) noexcept\n{\n stopwatch.RecordEvent(\"error\");\n\n input.Clear();\n\n if (!parser.AreHeadersFinished()) {\n \/* the response hasn't been sent yet: notify the response\n handler *\/\n assert(!HasHandler());\n\n buffer.Free();\n\n auto &_handler = handler;\n Destroy();\n _handler.InvokeError(NestException(ep,\n std::runtime_error(\"CGI request body failed\")));\n } else {\n \/* response has been sent: abort only the output stream *\/\n buffer.Free();\n DestroyError(ep);\n }\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nCGIClient::_GetAvailable(bool partial) noexcept\n{\n if (parser.KnownLength())\n return parser.GetAvailable();\n\n if (!input.IsDefined())\n return 0;\n\n if (in_response_callback)\n \/* this condition catches the case in cgi_parse_headers():\n HttpResponseHandler::InvokeResponse() might\n recursively call istream_read(input) *\/\n return (off_t)-1;\n\n return input.GetAvailable(partial);\n}\n\nvoid\nCGIClient::_Read() noexcept\n{\n if (input.IsDefined()) {\n input.SetDirect(GetHandlerDirect());\n\n \/* this condition catches the case in cgi_parse_headers():\n HttpResponseHandler::InvokeResponse() might\n recursively call input.Read() *\/\n if (in_response_callback) {\n return;\n }\n\n const DestructObserver destructed(*this);\n\n had_output = false;\n do {\n had_input = false;\n input.Read();\n } while (!destructed && input.IsDefined() && had_input && !had_output);\n }\n}\n\nvoid\nCGIClient::_Close() noexcept\n{\n buffer.Free();\n\n if (input.IsDefined())\n input.ClearAndClose();\n\n Destroy();\n}\n\n\/*\n * async operation\n *\n *\/\n\nvoid\nCGIClient::Cancel() noexcept\n{\n assert(input.IsDefined());\n\n buffer.Free();\n input.Close();\n Destroy();\n}\n\n\n\/*\n * constructor\n *\n *\/\n\ninline\nCGIClient::CGIClient(struct pool &_pool, StopwatchPtr &&_stopwatch,\n UnusedIstreamPtr _input,\n HttpResponseHandler &_handler,\n CancellablePointer &cancel_ptr)\n :PoolLeakDetector(_pool), Istream(_pool),\n stopwatch(std::move(_stopwatch)),\n input(std::move(_input), *this),\n buffer(fb_pool_get()),\n parser(_pool),\n handler(_handler)\n{\n cancel_ptr = *this;\n\n input.Read();\n}\n\nvoid\ncgi_client_new(struct pool &pool, StopwatchPtr stopwatch,\n UnusedIstreamPtr input,\n HttpResponseHandler &handler,\n CancellablePointer &cancel_ptr)\n{\n NewFromPool<CGIClient>(pool, pool, std::move(stopwatch),\n std::move(input),\n handler, cancel_ptr);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Autocomplete popup should show up when clicking or pressing the up\/down key in a text-field, even if the text-field is not empty.<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef VIENNAGRID_IO_SERIALIZATION_HPP\n#define VIENNAGRID_IO_SERIALIZATION_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2012, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n\n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n\/** @file serialization.hpp\n * @brief A domain wrapper class which models the Boost Serialization concept: http:\/\/www.boost.org\/libs\/serialization\/\n *\/\n\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/serialization\/base_object.hpp>\n#include <boost\/serialization\/utility.hpp>\n#include <boost\/serialization\/list.hpp>\n#include <boost\/serialization\/assume_abstract.hpp>\n#include <boost\/shared_ptr.hpp>\n\nnamespace viennagrid\n{\n namespace io\n {\n \/** @brief Domain wrapper which models the Boost serialization concept\n *\n *\/\n template<typename DomainT>\n struct domain_serializer\n {\n typedef boost::shared_ptr<DomainT> DomainSPT;\n private:\n typedef typename DomainT::config_type ConfigType;\n typedef typename DomainT::segment_type SegmentType;\n typedef typename ConfigType::cell_tag CellTag;\n typedef typename viennagrid::result_of::const_ncell_range<DomainT, 0>::type VertexRange;\n typedef typename viennagrid::result_of::iterator<VertexRange>::type VertexIterator;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::ncell<ConfigType, 0>::type VertexType;\n typedef typename viennagrid::result_of::ncell<ConfigType, CellTag::dim>::type CellType;\n typedef typename viennagrid::result_of::ncell_range<SegmentType, CellTag::dim>::type CellRange;\n typedef typename viennagrid::result_of::iterator<CellRange>::type CellIterator;\n typedef typename viennagrid::result_of::ncell_range<CellType, 0>::type VertexOnCellRange;\n typedef typename viennagrid::result_of::iterator<VertexOnCellRange>::type VertexOnCellIterator;\n\n static const int DIMG = ConfigType::coordinate_system_tag::dim;\n\n friend class boost::serialization::access;\n\n \/** @brief Save function is used to 'read' the data from the domain *\/\n template<class Archive>\n void save(Archive & ar, const unsigned int version) const\n {\n \/\/ -----------------------------------------------\n \/\/ the geometry is read and transmitted\n \/\/\n std::size_t point_size = viennagrid::ncells<0>(*domainsp).size();\n ar & point_size;\n VertexRange vertices = viennagrid::ncells<0>(*domainsp);\n for (VertexIterator vit = vertices.begin();\n vit != vertices.end(); ++vit)\n {\n for(int d = 0; d < DIMG; d++) ar & vit->point()[d];\n }\n \/\/ -----------------------------------------------\n\n \/\/ -----------------------------------------------\n \/\/ the segment size is read and transmitted\n \/\/\n std::size_t segment_size = (*domainsp).segments().size();\n ar & segment_size;\n \/\/ -----------------------------------------------\n\n \/\/ -----------------------------------------------\n \/\/ the segment specific cells are read and transmitted\n \/\/\n for (std::size_t si = 0; si < segment_size; si++)\n {\n SegmentType & seg = (*domainsp).segments()[si];\n CellRange cells = viennagrid::ncells<CellTag::dim>(seg);\n\n std::size_t cell_size = viennagrid::ncells<CellTag::dim>(seg).size();\n ar & cell_size;\n\n for (CellIterator cit = cells.begin();\n cit != cells.end(); ++cit)\n {\n VertexOnCellRange vertices_on_cell = viennagrid::ncells<0>(*cit);\n\n for (VertexOnCellIterator vocit = vertices_on_cell.begin();\n vocit != vertices_on_cell.end();\n ++vocit)\n {\n std::size_t id = vocit->id();\n ar & id;\n }\n }\n }\n \/\/ -----------------------------------------------\n }\n\n \/** @brief Load function is used to 'write' the data to the domain *\/\n template<class Archive>\n void load(Archive & ar, const unsigned int version)\n {\n \/\/ -----------------------------------------------\n \/\/ the geometry is received and stored\n \/\/\n std::size_t point_size;\n ar & point_size;\n\n for(std::size_t i = 0; i < point_size; i++)\n {\n VertexType vertex;\n for(int d = 0; d < DIMG; d++)\n ar & vertex.point()[d];\n (*domainsp).push_back(vertex);\n }\n \/\/ -----------------------------------------------\n\n \/\/ -----------------------------------------------\n \/\/ the segments are received and created\n \/\/\n std::size_t segment_size;\n ar & segment_size;\n (*domainsp).segments().resize(segment_size);\n \/\/ -----------------------------------------------\n\n \/\/ -----------------------------------------------\n \/\/ the segment specific cells are received and stored\n \/\/\n for (std::size_t si = 0; si < segment_size; si++)\n {\n SegmentType & seg = (*domainsp).segments()[si];\n std::size_t cell_size;\n ar & cell_size;\n for(std::size_t ci = 0; ci < cell_size; ci++)\n {\n VertexType *vertices[viennagrid::topology::bndcells<CellTag, 0>::num];\n\n for (int j=0; j<viennagrid::topology::bndcells<CellTag, 0>::num; ++j)\n {\n std::size_t id;\n ar & id;\n vertices[j] = &(viennagrid::ncells<0>(*domainsp)[id]);\n }\n CellType cell;\n cell.vertices(vertices);\n seg.push_back(cell);\n }\n }\n \/\/ -----------------------------------------------\n }\n\n \/\/ -----------------------------------------------\n \/\/ notify Boost Serialization that the save and load\n \/\/ procedures differ\n \/\/\n BOOST_SERIALIZATION_SPLIT_MEMBER()\n \/\/ -----------------------------------------------\n public:\n \/** @brief The default constructor*\/\n domain_serializer() : domainsp(new DomainT) {}\n\n \/** @brief The constructor expects a shared pointer on a domain object and sets the state *\/\n domain_serializer(DomainSPT& domainsp) : domainsp(domainsp) {}\n\n \/** @brief The load function enables to associate a domain with the serialzer after\n a serializer object has been constructed. *\/\n inline void load(DomainSPT other) { domainsp = other; }\n\n \/** @brief The get function enables to retrieve the domain pointer\n *\/\n inline DomainSPT get() { return domainsp; }\n\n \/** @brief The functor returns a reference to the domain state*\/\n DomainT& operator()() { return *domainsp; }\n\n \/** @brief The state holds a shared pointer to the domain *\/\n DomainSPT domainsp;\n \/\/DomainT& domain;\n };\n\n } \/\/namespace io\n} \/\/namespace viennagrid\n\n#endif\n\n<commit_msg>Adapted to new ViennaGrid, work in progress<commit_after>#ifndef VIENNAGRID_IO_SERIALIZATION_HPP\n#define VIENNAGRID_IO_SERIALIZATION_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2012, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n\n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n\/** @file serialization.hpp\n * @brief A domain wrapper class which models the Boost Serialization concept: http:\/\/www.boost.org\/libs\/serialization\/\n *\/\n\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/serialization\/base_object.hpp>\n#include <boost\/serialization\/utility.hpp>\n#include <boost\/serialization\/list.hpp>\n#include <boost\/serialization\/assume_abstract.hpp>\n#include <boost\/shared_ptr.hpp>\n\nnamespace viennagrid\n{\n namespace io\n {\n \/** @brief Domain wrapper which models the Boost serialization concept\n *\n *\/\n template<typename DomainT, typename SegmentationT>\n struct domain_serializer\n {\n typedef boost::shared_ptr<DomainT> DomainSPT;\n typedef boost::shared_ptr<SegmentationT> SegmentationSPT;\n \n private:\n typedef typename viennagrid::result_of::segment<SegmentationT>::type SegmentType;\n typedef typename viennagrid::result_of::cell_tag<DomainT>::type CellTag;\n typedef typename viennagrid::result_of::vertex_range<DomainT>::type VertexRange;\n typedef typename viennagrid::result_of::iterator<VertexRange>::type VertexIterator;\n typedef typename viennagrid::result_of::point<DomainT>::type PointType;\n typedef typename viennagrid::result_of::vertex<DomainT>::type VertexType;\n typedef typename viennagrid::result_of::cell<DomainT>::type CellType;\n typedef typename viennagrid::result_of::cell_range<SegmentType>::type CellRange;\n typedef typename viennagrid::result_of::iterator<CellRange>::type CellIterator;\n typedef typename viennagrid::result_of::vertex_range<CellType>::type VertexOnCellRange;\n typedef typename viennagrid::result_of::iterator<VertexOnCellRange>::type VertexOnCellIterator;\n\n static const int DIMG = PointType::dim;\n\n friend class boost::serialization::access;\n\n \/** @brief Save function is used to 'read' the data from the domain *\/\n template<class Archive>\n void save(Archive & ar, const unsigned int version) const\n {\n \/\/ -----------------------------------------------\n \/\/ the geometry is read and transmitted\n \/\/\n std::size_t point_size = viennagrid::vertices(*domainsp).size();\n ar & point_size;\n VertexRange vertices = viennagrid::elements(*domainsp);\n for (VertexIterator vit = vertices.begin();\n vit != vertices.end(); ++vit)\n {\n for(int d = 0; d < DIMG; d++)\n ar & viennagrid::point(*vit)[d];\n }\n \/\/ -----------------------------------------------\n\n \/\/ -----------------------------------------------\n \/\/ the segment size is read and transmitted\n \/\/\n std::size_t segment_size = (*domainsp).segments().size();\n ar & segment_size;\n \/\/ -----------------------------------------------\n\n \/\/ -----------------------------------------------\n \/\/ the segment specific cells are read and transmitted\n \/\/\n for (std::size_t si = 0; si < segment_size; si++)\n {\n SegmentType & seg = (*domainsp).segments()[si];\n CellRange cells = viennagrid::elements(seg);\n\n std::size_t cell_size = viennagrid::cells(seg).size();\n ar & cell_size;\n\n for (CellIterator cit = cells.begin();\n cit != cells.end(); ++cit)\n {\n VertexOnCellRange vertices_on_cell = viennagrid::elements(*cit);\n\n for (VertexOnCellIterator vocit = vertices_on_cell.begin();\n vocit != vertices_on_cell.end();\n ++vocit)\n {\n std::size_t id = vocit->id().get();\n ar & id;\n }\n }\n }\n \/\/ -----------------------------------------------\n }\n\n \/** @brief Load function is used to 'write' the data to the domain *\/\n template<class Archive>\n void load(Archive & ar, const unsigned int version)\n {\n \/\/ -----------------------------------------------\n \/\/ the geometry is received and stored\n \/\/\n std::size_t point_size;\n ar & point_size;\n\n for(std::size_t i = 0; i < point_size; i++)\n {\n PointType p;\n for(int d = 0; d < DIMG; d++)\n ar & p[d];\n \n viennagrid::make_vertex( *domainsp, p );\n }\n \/\/ -----------------------------------------------\n\n \/\/ -----------------------------------------------\n \/\/ the segments are received and created\n \/\/\n std::size_t segment_size;\n ar & segment_size;\n (*domainsp).segments().resize(segment_size);\n \/\/ -----------------------------------------------\n\n \/\/ -----------------------------------------------\n \/\/ the segment specific cells are received and stored\n \/\/\n for (std::size_t si = 0; si < segment_size; si++)\n {\n SegmentType & seg = (*domainsp).segments()[si];\n std::size_t cell_size;\n ar & cell_size;\n for(std::size_t ci = 0; ci < cell_size; ci++)\n {\n VertexType *vertices[viennagrid::topology::bndcells<CellTag, 0>::num];\n\n for (int j=0; j<viennagrid::topology::bndcells<CellTag, 0>::num; ++j)\n {\n std::size_t id;\n ar & id;\n vertices[j] = &(viennagrid::ncells<0>(*domainsp)[id]);\n }\n CellType cell;\n cell.vertices(vertices);\n seg.push_back(cell);\n }\n }\n \/\/ -----------------------------------------------\n }\n\n \/\/ -----------------------------------------------\n \/\/ notify Boost Serialization that the save and load\n \/\/ procedures differ\n \/\/\n BOOST_SERIALIZATION_SPLIT_MEMBER()\n \/\/ -----------------------------------------------\n public:\n \/** @brief The default constructor*\/\n domain_serializer() : domainsp(new DomainT) {}\n\n \/** @brief The constructor expects a shared pointer on a domain object and sets the state *\/\n domain_serializer(DomainSPT& domainsp) : domainsp(domainsp) {}\n\n \/** @brief The load function enables to associate a domain with the serialzer after\n a serializer object has been constructed. *\/\n inline void load(DomainSPT other) { domainsp = other; }\n\n \/** @brief The get function enables to retrieve the domain pointer\n *\/\n inline DomainSPT get() { return domainsp; }\n\n \/** @brief The functor returns a reference to the domain state*\/\n DomainT& operator()() { return *domainsp; }\n\n \/** @brief The state holds a shared pointer to the domain *\/\n DomainSPT domainsp;\n \/\/DomainT& domain;\n };\n\n } \/\/namespace io\n} \/\/namespace viennagrid\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\n\/\/ Blueberry\n#include <berryISelectionService.h>\n#include <berryIWorkbenchWindow.h>\n\n\/\/ Qmitk\n#include \"QmitkRegionGrowingView.h\"\n\n\/\/! [cpp-includes]\n\/\/ Qmitk\n#include \"QmitkPointListWidget.h\"\n#include \"QmitkRenderWindow.h\"\n\n\/\/ MITK\n#include \"mitkImageAccessByItk.h\"\n#include \"mitkITKImageImport.h\"\n#include \"mitkProperties.h\"\n#include \"mitkColorProperty.h\"\n\n\/\/ ITK\n#include <itkConnectedThresholdImageFilter.h>\n\/\/! [cpp-includes]\n\n\/\/ Qt\n#include <QMessageBox>\n\n\nconst std::string QmitkRegionGrowingView::VIEW_ID = \"org.mitk.views.example.regiongrowing\";\n\nQmitkRegionGrowingView::QmitkRegionGrowingView()\n : m_PointListWidget(NULL)\n{\n}\n\nvoid QmitkRegionGrowingView::SetFocus()\n{\n m_Controls.buttonPerformImageProcessing->setFocus();\n}\n\nvoid QmitkRegionGrowingView::CreateQtPartControl( QWidget *parent )\n{\n \/\/ create GUI widgets from the Qt Designer's .ui file\n m_Controls.setupUi( parent );\n connect( m_Controls.buttonPerformImageProcessing, SIGNAL(clicked()), this, SLOT(DoImageProcessing()) );\n\n \/\/! [cpp-createqtpartcontrol]\n \/\/ create a QmitkPointListWidget and add it to the widget created from .ui file\n m_PointListWidget = new QmitkPointListWidget();\n m_Controls.verticalLayout->addWidget(m_PointListWidget, 1);\n\n \/\/ retrieve a possibly existing IRenderWindowPart\n if (mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart())\n {\n \/\/ let the point set widget know about the render window part (crosshair updates)\n RenderWindowPartActivated(renderWindowPart);\n }\n\n \/\/ create a new DataNode containing a PointSet with some interaction\n m_PointSet = mitk::PointSet::New();\n mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();\n pointSetNode->SetData( m_PointSet );\n pointSetNode->SetName(\"seed points for region growing\");\n pointSetNode->SetProperty(\"helper object\", mitk::BoolProperty::New(true) );\n pointSetNode->SetProperty(\"layer\", mitk::IntProperty::New(1024) );\n\n \/\/ add the pointset to the data storage (for rendering and access by other modules)\n GetDataStorage()->Add( pointSetNode );\n\n \/\/ tell the GUI widget about the point set\n m_PointListWidget->SetPointSetNode( pointSetNode );\n \/\/! [cpp-createqtpartcontrol]\n}\n\nvoid QmitkRegionGrowingView::OnSelectionChanged( berry::IWorkbenchPart::Pointer \/*source*\/,\n const QList<mitk::DataNode::Pointer>& nodes )\n{\n \/\/ iterate all selected objects, adjust warning visibility\n foreach( mitk::DataNode::Pointer node, nodes )\n {\n if( node.IsNotNull() && dynamic_cast<mitk::Image*>(node->GetData()) )\n {\n m_Controls.labelWarning->setVisible( false );\n m_Controls.buttonPerformImageProcessing->setEnabled( true );\n return;\n }\n }\n\n m_Controls.labelWarning->setVisible( true );\n m_Controls.buttonPerformImageProcessing->setEnabled( false );\n}\n\nvoid QmitkRegionGrowingView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)\n{\n \/\/ let the point set widget know about the slice navigation controllers\n \/\/ in the active render window part (crosshair updates)\n foreach(QmitkRenderWindow* renderWindow, renderWindowPart->GetQmitkRenderWindows().values())\n {\n m_PointListWidget->AddSliceNavigationController(renderWindow->GetSliceNavigationController());\n }\n}\n\nvoid QmitkRegionGrowingView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart)\n{\n foreach(QmitkRenderWindow* renderWindow, renderWindowPart->GetQmitkRenderWindows().values())\n {\n m_PointListWidget->RemoveSliceNavigationController(renderWindow->GetSliceNavigationController());\n }\n}\n\nvoid QmitkRegionGrowingView::DoImageProcessing()\n{\n QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();\n if (nodes.empty()) return;\n\n mitk::DataNode* node = nodes.front();\n\n if (!node)\n {\n \/\/ Nothing selected. Inform the user and return\n QMessageBox::information( NULL, \"Template\", \"Please load and select an image before starting image processing.\");\n return;\n }\n\n \/\/ here we have a valid mitk::DataNode\n\n \/\/ a node itself is not very useful, we need its data item (the image)\n mitk::BaseData* data = node->GetData();\n if (data)\n {\n \/\/ test if this data item is an image or not (could also be a surface or something totally different)\n mitk::Image* image = dynamic_cast<mitk::Image*>( data );\n if (image)\n {\n \/\/! [cpp-doimageprocessing]\n \/\/ So we have an image. Let's see if the user has set some seed points already\n if (m_PointSet->GetSize() == 0)\n {\n \/\/ no points there. Not good for region growing\n QMessageBox::information( NULL,\n \"Region growing functionality\",\n \"Please set some seed points inside the image first.\\n\"\n \"(hold Shift key and click left mouse button inside the image.)\"\n );\n return;\n }\n\n \/\/ actually perform region growing. Here we have both an image and some seed points\n AccessByItk_1( image, ItkImageProcessing, image->GetGeometry() ) \/\/ some magic to call the correctly templated function\n \/\/! [cpp-doimageprocessing]\n }\n }\n}\n\n\/\/! [cpp-itkimageaccess]\ntemplate < typename TPixel, unsigned int VImageDimension >\nvoid QmitkRegionGrowingView::ItkImageProcessing( itk::Image< TPixel, VImageDimension >* itkImage, mitk::BaseGeometry* imageGeometry )\n{\n typedef itk::Image< TPixel, VImageDimension > InputImageType;\n typedef typename InputImageType::IndexType IndexType;\n\n \/\/ instantiate an ITK region growing filter, set its parameters\n typedef itk::ConnectedThresholdImageFilter<InputImageType, InputImageType> RegionGrowingFilterType;\n typename RegionGrowingFilterType::Pointer regionGrower = RegionGrowingFilterType::New();\n regionGrower->SetInput( itkImage ); \/\/ don't forget this\n\n \/\/ determine a thresholding interval\n IndexType seedIndex;\n TPixel min( std::numeric_limits<TPixel>::max() );\n TPixel max( std::numeric_limits<TPixel>::min() );\n mitk::PointSet::PointsContainer* points = m_PointSet->GetPointSet()->GetPoints();\n for ( mitk::PointSet::PointsConstIterator pointsIterator = points->Begin();\n pointsIterator != points->End();\n ++pointsIterator )\n {\n \/\/ first test if this point is inside the image at all\n if ( !imageGeometry->IsInside( pointsIterator.Value()) )\n {\n continue;\n }\n\n \/\/ convert world coordinates to image indices\n imageGeometry->WorldToIndex( pointsIterator.Value(), seedIndex);\n\n \/\/ get the pixel value at this point\n TPixel currentPixelValue = itkImage->GetPixel( seedIndex );\n\n \/\/ adjust minimum and maximum values\n if (currentPixelValue > max)\n max = currentPixelValue;\n\n if (currentPixelValue < min)\n min = currentPixelValue;\n\n regionGrower->AddSeed( seedIndex );\n }\n\n MITK_INFO << \"Values between \" << min << \" and \" << max;\n\n min -= 30;\n max += 30;\n\n \/\/ set thresholds and execute filter\n regionGrower->SetLower( min );\n regionGrower->SetUpper( max );\n\n regionGrower->Update();\n\n mitk::Image::Pointer resultImage = mitk::ImportItkImage( regionGrower->GetOutput() );\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n newNode->SetData( resultImage );\n\n \/\/ set some properties\n newNode->SetProperty(\"binary\", mitk::BoolProperty::New(true));\n newNode->SetProperty(\"name\", mitk::StringProperty::New(\"dumb segmentation\"));\n newNode->SetProperty(\"color\", mitk::ColorProperty::New(1.0,0.0,0.0));\n newNode->SetProperty(\"volumerendering\", mitk::BoolProperty::New(true));\n newNode->SetProperty(\"layer\", mitk::IntProperty::New(1));\n newNode->SetProperty(\"opacity\", mitk::FloatProperty::New(0.5));\n\n \/\/ add result to data tree\n this->GetDataStorage()->Add( newNode );\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\/\/! [cpp-itkimageaccess]\n<commit_msg>Replace ImportItkImage by CastToMitkImage to allow out-of-scope memory management.<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\n\/\/ Blueberry\n#include <berryISelectionService.h>\n#include <berryIWorkbenchWindow.h>\n\n\/\/ Qmitk\n#include \"QmitkRegionGrowingView.h\"\n\n\/\/! [cpp-includes]\n\/\/ Qmitk\n#include \"QmitkPointListWidget.h\"\n#include \"QmitkRenderWindow.h\"\n\n\/\/ MITK\n#include \"mitkImageAccessByItk.h\"\n#include \"mitkITKImageImport.h\"\n#include \"mitkProperties.h\"\n#include \"mitkColorProperty.h\"\n#include \"mitkImageCast.h\"\n\n\/\/ ITK\n#include <itkConnectedThresholdImageFilter.h>\n\/\/! [cpp-includes]\n\n\/\/ Qt\n#include <QMessageBox>\n\n\nconst std::string QmitkRegionGrowingView::VIEW_ID = \"org.mitk.views.example.regiongrowing\";\n\nQmitkRegionGrowingView::QmitkRegionGrowingView()\n : m_PointListWidget(NULL)\n{\n}\n\nvoid QmitkRegionGrowingView::SetFocus()\n{\n m_Controls.buttonPerformImageProcessing->setFocus();\n}\n\nvoid QmitkRegionGrowingView::CreateQtPartControl( QWidget *parent )\n{\n \/\/ create GUI widgets from the Qt Designer's .ui file\n m_Controls.setupUi( parent );\n connect( m_Controls.buttonPerformImageProcessing, SIGNAL(clicked()), this, SLOT(DoImageProcessing()) );\n\n \/\/! [cpp-createqtpartcontrol]\n \/\/ create a QmitkPointListWidget and add it to the widget created from .ui file\n m_PointListWidget = new QmitkPointListWidget();\n m_Controls.verticalLayout->addWidget(m_PointListWidget, 1);\n\n \/\/ retrieve a possibly existing IRenderWindowPart\n if (mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart())\n {\n \/\/ let the point set widget know about the render window part (crosshair updates)\n RenderWindowPartActivated(renderWindowPart);\n }\n\n \/\/ create a new DataNode containing a PointSet with some interaction\n m_PointSet = mitk::PointSet::New();\n mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();\n pointSetNode->SetData( m_PointSet );\n pointSetNode->SetName(\"seed points for region growing\");\n pointSetNode->SetProperty(\"helper object\", mitk::BoolProperty::New(true) );\n pointSetNode->SetProperty(\"layer\", mitk::IntProperty::New(1024) );\n\n \/\/ add the pointset to the data storage (for rendering and access by other modules)\n GetDataStorage()->Add( pointSetNode );\n\n \/\/ tell the GUI widget about the point set\n m_PointListWidget->SetPointSetNode( pointSetNode );\n \/\/! [cpp-createqtpartcontrol]\n}\n\nvoid QmitkRegionGrowingView::OnSelectionChanged( berry::IWorkbenchPart::Pointer \/*source*\/,\n const QList<mitk::DataNode::Pointer>& nodes )\n{\n \/\/ iterate all selected objects, adjust warning visibility\n foreach( mitk::DataNode::Pointer node, nodes )\n {\n if( node.IsNotNull() && dynamic_cast<mitk::Image*>(node->GetData()) )\n {\n m_Controls.labelWarning->setVisible( false );\n m_Controls.buttonPerformImageProcessing->setEnabled( true );\n return;\n }\n }\n\n m_Controls.labelWarning->setVisible( true );\n m_Controls.buttonPerformImageProcessing->setEnabled( false );\n}\n\nvoid QmitkRegionGrowingView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)\n{\n \/\/ let the point set widget know about the slice navigation controllers\n \/\/ in the active render window part (crosshair updates)\n foreach(QmitkRenderWindow* renderWindow, renderWindowPart->GetQmitkRenderWindows().values())\n {\n m_PointListWidget->AddSliceNavigationController(renderWindow->GetSliceNavigationController());\n }\n}\n\nvoid QmitkRegionGrowingView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart)\n{\n foreach(QmitkRenderWindow* renderWindow, renderWindowPart->GetQmitkRenderWindows().values())\n {\n m_PointListWidget->RemoveSliceNavigationController(renderWindow->GetSliceNavigationController());\n }\n}\n\nvoid QmitkRegionGrowingView::DoImageProcessing()\n{\n QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();\n if (nodes.empty()) return;\n\n mitk::DataNode* node = nodes.front();\n\n if (!node)\n {\n \/\/ Nothing selected. Inform the user and return\n QMessageBox::information( NULL, \"Template\", \"Please load and select an image before starting image processing.\");\n return;\n }\n\n \/\/ here we have a valid mitk::DataNode\n\n \/\/ a node itself is not very useful, we need its data item (the image)\n mitk::BaseData* data = node->GetData();\n if (data)\n {\n \/\/ test if this data item is an image or not (could also be a surface or something totally different)\n mitk::Image* image = dynamic_cast<mitk::Image*>( data );\n if (image)\n {\n \/\/! [cpp-doimageprocessing]\n \/\/ So we have an image. Let's see if the user has set some seed points already\n if (m_PointSet->GetSize() == 0)\n {\n \/\/ no points there. Not good for region growing\n QMessageBox::information( NULL,\n \"Region growing functionality\",\n \"Please set some seed points inside the image first.\\n\"\n \"(hold Shift key and click left mouse button inside the image.)\"\n );\n return;\n }\n\n \/\/ actually perform region growing. Here we have both an image and some seed points\n AccessByItk_1( image, ItkImageProcessing, image->GetGeometry() ) \/\/ some magic to call the correctly templated function\n \/\/! [cpp-doimageprocessing]\n }\n }\n}\n\n\/\/! [cpp-itkimageaccess]\ntemplate < typename TPixel, unsigned int VImageDimension >\nvoid QmitkRegionGrowingView::ItkImageProcessing( itk::Image< TPixel, VImageDimension >* itkImage, mitk::BaseGeometry* imageGeometry )\n{\n typedef itk::Image< TPixel, VImageDimension > InputImageType;\n typedef typename InputImageType::IndexType IndexType;\n\n \/\/ instantiate an ITK region growing filter, set its parameters\n typedef itk::ConnectedThresholdImageFilter<InputImageType, InputImageType> RegionGrowingFilterType;\n typename RegionGrowingFilterType::Pointer regionGrower = RegionGrowingFilterType::New();\n regionGrower->SetInput( itkImage ); \/\/ don't forget this\n\n \/\/ determine a thresholding interval\n IndexType seedIndex;\n TPixel min( std::numeric_limits<TPixel>::max() );\n TPixel max( std::numeric_limits<TPixel>::min() );\n mitk::PointSet::PointsContainer* points = m_PointSet->GetPointSet()->GetPoints();\n for ( mitk::PointSet::PointsConstIterator pointsIterator = points->Begin();\n pointsIterator != points->End();\n ++pointsIterator )\n {\n \/\/ first test if this point is inside the image at all\n if ( !imageGeometry->IsInside( pointsIterator.Value()) )\n {\n continue;\n }\n\n \/\/ convert world coordinates to image indices\n imageGeometry->WorldToIndex( pointsIterator.Value(), seedIndex);\n\n \/\/ get the pixel value at this point\n TPixel currentPixelValue = itkImage->GetPixel( seedIndex );\n\n \/\/ adjust minimum and maximum values\n if (currentPixelValue > max)\n max = currentPixelValue;\n\n if (currentPixelValue < min)\n min = currentPixelValue;\n\n regionGrower->AddSeed( seedIndex );\n }\n\n MITK_INFO << \"Values between \" << min << \" and \" << max;\n\n min -= 30;\n max += 30;\n\n \/\/ set thresholds and execute filter\n regionGrower->SetLower( min );\n regionGrower->SetUpper( max );\n\n regionGrower->Update();\n\n mitk::Image::Pointer resultImage;\n mitk::CastToMitkImage( regionGrower->GetOutput(), resultImage );\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n newNode->SetData( resultImage );\n\n \/\/ set some properties\n newNode->SetProperty(\"binary\", mitk::BoolProperty::New(true));\n newNode->SetProperty(\"name\", mitk::StringProperty::New(\"dumb segmentation\"));\n newNode->SetProperty(\"color\", mitk::ColorProperty::New(1.0,0.0,0.0));\n newNode->SetProperty(\"volumerendering\", mitk::BoolProperty::New(true));\n newNode->SetProperty(\"layer\", mitk::IntProperty::New(1));\n newNode->SetProperty(\"opacity\", mitk::FloatProperty::New(0.5));\n\n \/\/ add result to data tree\n this->GetDataStorage()->Add( newNode );\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\/\/! [cpp-itkimageaccess]\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtTest\/QtTest>\n#include <QDebug>\n\n#include <multimedia\/qmediaserviceprovider.h>\n\nclass MockMediaServiceProvider : public QMediaServiceProvider\n{\n QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &)\n {\n Q_UNUSED(type);\n return 0;\n }\n\n void releaseService(QMediaService *service)\n {\n Q_UNUSED(service);\n }\n};\n\n\nclass tst_QMediaServiceProvider : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void testDefaultProviderAvailable();\n void testObtainService();\n void testHasSupport();\n void testDevices();\n void testProviderHints();\n};\n\nvoid tst_QMediaServiceProvider::testDefaultProviderAvailable()\n{\n \/\/ Must always be a default provider available\n QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0);\n}\n\nvoid tst_QMediaServiceProvider::testObtainService()\n{\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n QMediaService *service = 0;\n\n \/\/ Player\n service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER);\n QVERIFY(service != 0);\n provider->releaseService(service);\n}\n\nvoid tst_QMediaServiceProvider::testHasSupport()\n{\n MockMediaServiceProvider mockProvider;\n QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/ogv\", QStringList()),\n QtMedia::MaybeSupported);\n\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/ogv\", QStringList()),\n QtMedia::MaybeSupported);\n\n QCOMPARE(provider->hasSupport(QByteArray(\"non existing service\"), \"video\/ogv\", QStringList()),\n QtMedia::NotSupported);\n}\n\nvoid tst_QMediaServiceProvider::testDevices()\n{\n MockMediaServiceProvider mockProvider;\n QVERIFY(mockProvider.devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());\n QVERIFY(mockProvider.deviceDescription(QByteArray(Q_MEDIASERVICE_CAMERA),\n QByteArray()).isEmpty());\n\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n \/\/how to test this properly?\n \/\/it depends on plugins installed\n \/\/QVERIFY(!provider->devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());\n\n QVERIFY(provider->devices(QByteArray(\"non existing service\")).isEmpty());\n}\n\n\nvoid tst_QMediaServiceProvider::testProviderHints()\n{\n {\n QMediaServiceProviderHint hint;\n QVERIFY(hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::Null);\n QVERIFY(hint.device().isEmpty());\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), 0);\n }\n\n {\n QByteArray deviceName(QByteArray(\"testDevice\"));\n QMediaServiceProviderHint hint(deviceName);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::Device);\n QCOMPARE(hint.device(), deviceName);\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), 0);\n }\n\n {\n QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures);\n QVERIFY(hint.device().isEmpty());\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback);\n }\n\n {\n QString mimeType(QLatin1String(\"video\/ogg\"));\n QStringList codecs;\n codecs << \"theora\" << \"vorbis\";\n\n QMediaServiceProviderHint hint(mimeType,codecs);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint.device().isEmpty());\n QCOMPARE(hint.mimeType(), mimeType);\n QCOMPARE(hint.codecs(), codecs);\n\n QMediaServiceProviderHint hint2(hint);\n\n QVERIFY(!hint2.isNull());\n QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint2.device().isEmpty());\n QCOMPARE(hint2.mimeType(), mimeType);\n QCOMPARE(hint2.codecs(), codecs);\n\n QMediaServiceProviderHint hint3;\n QVERIFY(hint3.isNull());\n hint3 = hint;\n QVERIFY(!hint3.isNull());\n QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint3.device().isEmpty());\n QCOMPARE(hint3.mimeType(), mimeType);\n QCOMPARE(hint3.codecs(), codecs);\n\n QCOMPARE(hint, hint2);\n QCOMPARE(hint3, hint2);\n\n QMediaServiceProviderHint hint4(mimeType,codecs);\n QCOMPARE(hint, hint4);\n\n QMediaServiceProviderHint hint5(mimeType,QStringList());\n QVERIFY(hint != hint5);\n }\n}\n\nQTEST_MAIN(tst_QMediaServiceProvider)\n\n#include \"tst_qmediaserviceprovider.moc\"\n<commit_msg>Test for QMediaServiceProvider::hasSupport() with set of mock plugins<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtTest\/QtTest>\n#include <QDebug>\n\n#include <multimedia\/qmediaserviceprovider.h>\n#include <multimedia\/qmediaserviceproviderplugin.h>\n#include <multimedia\/qmediapluginloader_p.h>\n#include <multimedia\/qmediaobject.h>\n#include <multimedia\/qmediaservice.h>\n#include <multimedia\/qmediaplayer.h>\n\nclass MockMediaService : public QMediaService\n{\n Q_OBJECT\npublic:\n MockMediaService(const QString& name, QObject *parent = 0) : QMediaService(parent)\n { setObjectName(name); }\n ~MockMediaService() {}\n\n QMediaControl* control(const char *) const {return 0;}\n};\n\nclass MockServicePlugin1 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedFormatsInterface,\n public QMediaServiceSupportedDevicesInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedFormatsInterface)\n Q_INTERFACES(QMediaServiceSupportedDevicesInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() <<\n QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) <<\n QLatin1String(Q_MEDIASERVICE_CAMERA);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin1\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const\n { \n if (codecs.contains(QLatin1String(\"mpeg4\")))\n return QtMedia::NotSupported;\n\n if (mimeType == \"audio\/ogg\") { \n return QtMedia::ProbablySupported;\n }\n\n return QtMedia::MaybeSupported;\n }\n\n QList<QByteArray> devices(const QByteArray &service) const\n {\n QList<QByteArray> res;\n if (service == QByteArray(Q_MEDIASERVICE_CAMERA))\n res << \"camera1\" << \"camera2\"; \n return res;\n }\n\n QString deviceDescription(const QByteArray &service, const QByteArray &device)\n {\n if (devices(service).contains(device))\n return QString(device)+\" description\";\n else\n return QString();\n }\n};\n\nclass MockServicePlugin2 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedFormatsInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedFormatsInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin2\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const\n {\n Q_UNUSED(codecs);\n\n if (mimeType == \"audio\/wav\")\n return QtMedia::PreferedService; \n\n return QtMedia::NotSupported;\n }\n};\n\n\nclass MockServicePlugin3 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedDevicesInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedDevicesInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() <<\n QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) <<\n QLatin1String(Q_MEDIASERVICE_CAMERA) <<\n QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin3\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QList<QByteArray> devices(const QByteArray &service) const\n {\n QList<QByteArray> res;\n if (service == QByteArray(Q_MEDIASERVICE_CAMERA))\n res << \"camera3\" << \"camera4\";\n else if (service == QByteArray(Q_MEDIASERVICE_AUDIOSOURCE))\n res << \"audiosource1\" << \"audiosource2\";\n\n return res;\n }\n\n QString deviceDescription(const QByteArray &service, const QByteArray &device)\n {\n if (devices(service).contains(device))\n return QString(device)+\" description\";\n else\n return QString();\n }\n};\n\n\n\nclass MockMediaServiceProvider : public QMediaServiceProvider\n{\n QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &)\n {\n Q_UNUSED(type);\n return 0;\n }\n\n void releaseService(QMediaService *service)\n {\n Q_UNUSED(service);\n }\n};\n\n\nclass tst_QMediaServiceProvider : public QObject\n{\n Q_OBJECT\n\npublic slots:\n void initTestCase();\n\nprivate slots: \n void testDefaultProviderAvailable();\n void testObtainService();\n void testHasSupport();\n void testDevices();\n void testProviderHints();\n\nprivate:\n QObjectList plugins;\n};\n\nvoid tst_QMediaServiceProvider::initTestCase()\n{\n plugins << new MockServicePlugin1;\n plugins << new MockServicePlugin2;\n plugins << new MockServicePlugin3;\n\n QMediaPluginLoader::setStaticPlugins(QLatin1String(\"\/mediaservice\"), plugins);\n}\n\nvoid tst_QMediaServiceProvider::testDefaultProviderAvailable()\n{\n \/\/ Must always be a default provider available \n QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0);\n}\n\nvoid tst_QMediaServiceProvider::testObtainService()\n{\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n QMediaService *service = 0;\n\n QTest::ignoreMessage(QtWarningMsg, \"Load static plugins for \\\"\/mediaservice\/\\\" \");\n \/\/ Player\n service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER);\n QVERIFY(service != 0);\n provider->releaseService(service);\n}\n\nvoid tst_QMediaServiceProvider::testHasSupport()\n{\n MockMediaServiceProvider mockProvider;\n QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/ogv\", QStringList()),\n QtMedia::MaybeSupported);\n\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/ogv\", QStringList()),\n QtMedia::MaybeSupported);\n\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"audio\/ogg\", QStringList()),\n QtMedia::ProbablySupported);\n\n \/\/while the service returns PreferredService, provider should return ProbablySupported\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"audio\/wav\", QStringList()),\n QtMedia::ProbablySupported);\n\n \/\/even while all the plugins with \"hasSupport\" returned NotSupported,\n \/\/MockServicePlugin3 has no \"hasSupport\" interface, so MaybeSupported\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/avi\",\n QStringList() << \"mpeg4\"),\n QtMedia::MaybeSupported);\n\n QCOMPARE(provider->hasSupport(QByteArray(\"non existing service\"), \"video\/ogv\", QStringList()),\n QtMedia::NotSupported);\n\n QCOMPARE(QMediaPlayer::hasSupport(\"video\/ogv\"), QtMedia::MaybeSupported); \n QCOMPARE(QMediaPlayer::hasSupport(\"audio\/ogg\"), QtMedia::ProbablySupported);\n QCOMPARE(QMediaPlayer::hasSupport(\"audio\/wav\"), QtMedia::ProbablySupported);\n}\n\nvoid tst_QMediaServiceProvider::testDevices()\n{\n MockMediaServiceProvider mockProvider;\n QVERIFY(mockProvider.devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());\n QVERIFY(mockProvider.deviceDescription(QByteArray(Q_MEDIASERVICE_CAMERA),\n QByteArray()).isEmpty());\n\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n QVERIFY(!provider->devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());\n\n QVERIFY(provider->devices(QByteArray(\"non existing service\")).isEmpty());\n}\n\n\nvoid tst_QMediaServiceProvider::testProviderHints()\n{\n {\n QMediaServiceProviderHint hint;\n QVERIFY(hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::Null);\n QVERIFY(hint.device().isEmpty());\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), 0);\n }\n\n {\n QByteArray deviceName(QByteArray(\"testDevice\"));\n QMediaServiceProviderHint hint(deviceName);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::Device);\n QCOMPARE(hint.device(), deviceName);\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), 0);\n }\n\n {\n QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures);\n QVERIFY(hint.device().isEmpty());\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback);\n }\n\n {\n QString mimeType(QLatin1String(\"video\/ogg\"));\n QStringList codecs;\n codecs << \"theora\" << \"vorbis\";\n\n QMediaServiceProviderHint hint(mimeType,codecs);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint.device().isEmpty());\n QCOMPARE(hint.mimeType(), mimeType);\n QCOMPARE(hint.codecs(), codecs);\n\n QMediaServiceProviderHint hint2(hint);\n\n QVERIFY(!hint2.isNull());\n QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint2.device().isEmpty());\n QCOMPARE(hint2.mimeType(), mimeType);\n QCOMPARE(hint2.codecs(), codecs);\n\n QMediaServiceProviderHint hint3;\n QVERIFY(hint3.isNull());\n hint3 = hint;\n QVERIFY(!hint3.isNull());\n QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint3.device().isEmpty());\n QCOMPARE(hint3.mimeType(), mimeType);\n QCOMPARE(hint3.codecs(), codecs);\n\n QCOMPARE(hint, hint2);\n QCOMPARE(hint3, hint2);\n\n QMediaServiceProviderHint hint4(mimeType,codecs);\n QCOMPARE(hint, hint4);\n\n QMediaServiceProviderHint hint5(mimeType,QStringList());\n QVERIFY(hint != hint5);\n }\n}\n\nQTEST_MAIN(tst_QMediaServiceProvider)\n\n#include \"tst_qmediaserviceprovider.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_Private_PatchingDataStructures_LinkedList_inl_\n#define _Stroika_Foundation_Containers_Private_PatchingDataStructures_LinkedList_inl_ 1\n\n\n#include \"..\/..\/..\/Debug\/Assertions.h\"\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Containers {\n namespace Private {\n namespace PatchingDataStructures {\n\n\n \/*\n ********************************************************************************\n ***************************** LinkedList_Patch<T> ******************************\n ********************************************************************************\n *\/\n template <typename T>\n inline LinkedList_Patch<T>::LinkedList_Patch ()\n : inherited ()\n , fActiveIteratorsListHead_ (nullptr)\n {\n Invariant ();\n }\n template <typename T>\n inline LinkedList_Patch<T>::LinkedList_Patch (const LinkedList_Patch<T>& from)\n : inherited (from)\n , fActiveIteratorsListHead_ (nullptr) \/\/ Don't copy the list of iterators - would be trouble with backpointers!\n \/\/ Could clone but that would do no good, since nobody else would have pointers to them\n {\n Invariant ();\n }\n template <typename T>\n inline LinkedList_Patch<T>::~LinkedList_Patch ()\n {\n Require (fActiveIteratorsListHead_ == nullptr);\n }\n template <typename T>\n inline void LinkedList_Patch<T>::Invariant () const\n {\n#if qDebug\n Invariant_ ();\n InvariantOnIterators_ ();\n#endif\n }\n template <typename T>\n inline bool LinkedList_Patch<T>::HasActiveIterators () const\n {\n return bool (fActiveIteratorsListHead_ != nullptr);\n }\n template <typename T>\n inline void LinkedList_Patch<T>::PatchViewsAdd (const Link* link) const\n {\n RequireNotNull (link);\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n v->PatchAdd (link);\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::PatchViewsRemove (const Link* link) const\n {\n RequireNotNull (link);\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n v->PatchRemove (link);\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::PatchViewsRemoveAll () const\n {\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n v->PatchRemoveAll ();\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::TwoPhaseIteratorPatcherPass1 (Link* oldI, Memory::SmallStackBuffer<ForwardIterator*>* items2Patch) const\n {\n for (auto ai = fActiveIteratorsListHead_; ai != nullptr; ai = ai->_fNextActiveIterator) {\n ai->TwoPhaseIteratorPatcherPass1 (oldI, items2Patch);\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::TwoPhaseIteratorPatcherPass2 (const Memory::SmallStackBuffer<ForwardIterator*>* items2Patch, Link* newI)\n {\n for (size_t i = 0; i < items2Patch->GetSize (); ++i) {\n (*items2Patch)[i]->TwoPhaseIteratorPatcherPass2 (newI);\n }\n }\n template <typename T>\n inline LinkedList_Patch<T>& LinkedList_Patch<T>::operator= (const LinkedList_Patch<T>& rhs)\n {\n \/*\n * Don't copy the rhs iterators, and don't do assignments when we have active iterators.\n * If this is to be supported at some future date, well need to work on our patching.\n *\/\n Assert (not (HasActiveIterators ())); \/\/ cuz copy of LinkedList does not copy iterators...\n inherited::operator= (rhs);\n return (*this);\n }\n template <typename T>\n inline void LinkedList_Patch<T>::Prepend (T item)\n {\n Invariant ();\n inherited::Prepend (item);\n PatchViewsAdd (this->_fHead);\n Invariant ();\n }\n \/\/tmphack - must fix to have in base class and just hook for patch here\n template <typename T>\n inline void LinkedList_Patch<T>::Append (T item)\n {\n if (this->_fHead == nullptr) {\n Prepend (item);\n }\n else {\n Link* last = this->_fHead;\n for (; last->fNext != nullptr; last = last->fNext)\n ;\n Assert (last != nullptr);\n Assert (last->fNext == nullptr);\n last->fNext = new Link (item, nullptr);\n PatchViewsAdd (last->fNext);\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::RemoveFirst ()\n {\n Invariant ();\n PatchViewsRemove (this->_fHead);\n inherited::RemoveFirst ();\n Invariant ();\n }\n template <typename T>\n inline void LinkedList_Patch<T>::RemoveAll ()\n {\n Invariant ();\n inherited::RemoveAll ();\n PatchViewsRemoveAll ();\n Invariant ();\n }\n template <typename T>\n void LinkedList_Patch<T>::Remove (T item)\n {\n Invariant ();\n T current;\n for (ForwardIterator it (*this); it.More (¤t, true); ) {\n if (current == item) {\n this->RemoveAt (it);\n break;\n }\n }\n Invariant ();\n }\n template <typename T>\n void LinkedList_Patch<T>::RemoveAt (const ForwardIterator& i)\n {\n Require (not i.Done ());\n Invariant ();\n Memory::SmallStackBuffer<ForwardIterator*> items2Patch (0);\n TwoPhaseIteratorPatcherPass1 (const_cast<Link*> (i._fCurrent), &items2Patch);\n Link* next = i._fCurrent->fNext;\n this->inherited::RemoveAt (i);\n TwoPhaseIteratorPatcherPass2 (&items2Patch, next);\n Invariant ();\n }\n template <typename T>\n void LinkedList_Patch<T>::AddBefore (const ForwardIterator& i, T newValue)\n {\n Invariant ();\n\n \/\/tmphack\n const Link* prev = nullptr;\n if ((this->_fHead != nullptr) and (this->_fHead != i._fCurrent)) {\n for (prev = this->_fHead; prev->fNext != i._fCurrent; prev = prev->fNext) {\n AssertNotNull (prev); \/\/ cuz that would mean _fCurrent not in DoublyLinkedList!!!\n }\n }\n\n bool isPrevNull = (prev == nullptr);\n inherited::AddBefore (i, newValue);\n \/\/\/ WAG - VERY LIKELY WRONG BELOIW - MUST CLENAUP - LGP -2013-06-17\n if (isPrevNull) {\n this->PatchViewsAdd (this->_fHead); \/\/ Will adjust fPrev\n }\n else {\n this->PatchViewsAdd (prev->fNext); \/\/ Will adjust fPrev\n }\n Invariant ();\n }\n template <typename T>\n void LinkedList_Patch<T>::AddAfter (const ForwardIterator& i, T newValue)\n {\n Invariant ();\n inherited::AddAfter (i, newValue);\n this->PatchViewsAdd (i._fCurrent->fNext);\n Invariant ();\n }\n#if qDebug\n template <typename T>\n void LinkedList_Patch<T>::Invariant_ () const\n {\n inherited::Invariant_ ();\n \/*\n * Be sure each iterator points back to us. Thats about all we can test from\n * here since we cannot call each iterators Invariant(). That would be\n * nice, but sadly when this Invariant_ () is called from LinkedList<T> the\n * iterators themselves may not have been patched, so they'll be out of\n * date. Instead, so that in local shadow of Invariant() done in LinkedList_Patch<T>\n * so only called when WE call Invariant().\n *\/\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n Assert (v->_fData == this);\n }\n }\n template <typename T>\n void LinkedList_Patch<T>::InvariantOnIterators_ () const\n {\n \/*\n * Only here can we iterate over each iterator and calls its Invariant()\n * since now we've completed any needed patching.\n *\/\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n Assert (v->_fData == this);\n v->Invariant ();\n }\n }\n#endif\n\n\n \/*\n ********************************************************************************\n ******************** LinkedList_Patch<T>::ForwardIterator **********************\n ********************************************************************************\n *\/\n template <typename T>\n inline LinkedList_Patch<T>::ForwardIterator::ForwardIterator (const LinkedList_Patch<T>& data)\n : inherited (data)\n , _fNextActiveIterator (data.fActiveIteratorsListHead_)\n \/\/, fPrev (nullptr) \/\/ means invalid or fData->_fHead == _fCurrent ...\n {\n const_cast<LinkedList_Patch<T>*> (&data)->fActiveIteratorsListHead_ = this;\n this->Invariant ();\n }\n template <typename T>\n inline LinkedList_Patch<T>::ForwardIterator::ForwardIterator (const ForwardIterator& from)\n : inherited (from)\n , _fNextActiveIterator (from.GetPatchingContainer_ ().fActiveIteratorsListHead_)\n \/\/, fPrev (from.fPrev)\n {\n from.Invariant ();\n GetPatchingContainer_ ().fActiveIteratorsListHead_ = this;\n this->Invariant ();\n }\n template <typename T>\n inline LinkedList_Patch<T>::ForwardIterator::~ForwardIterator ()\n {\n this->Invariant ();\n if (GetPatchingContainer_ ().fActiveIteratorsListHead_ == this) {\n GetPatchingContainer_ ().fActiveIteratorsListHead_ = _fNextActiveIterator;\n }\n else {\n auto v = GetPatchingContainer_ ().fActiveIteratorsListHead_;\n for (; v->_fNextActiveIterator != this; v = v->_fNextActiveIterator) {\n AssertNotNull (v);\n AssertNotNull (v->_fNextActiveIterator);\n }\n AssertNotNull (v);\n Assert (v->_fNextActiveIterator == this);\n v->_fNextActiveIterator = _fNextActiveIterator;\n }\n }\n template <typename T>\n inline typename LinkedList_Patch<T>::ForwardIterator& LinkedList_Patch<T>::ForwardIterator::operator= (const ForwardIterator& rhs)\n {\n this->Invariant ();\n\n \/*\n * If the fData field has not changed, then we can leave alone our iterator linkage.\n * Otherwise, we must remove ourselves from the old, and add ourselves to the new.\n *\/\n if (&GetPatchingContainer_ () != &rhs.GetPatchingContainer_ ()) {\n\n \/*\n * Remove from old.\n *\/\n if (GetPatchingContainer_ ().fActiveIteratorsListHead_ == this) {\n GetPatchingContainer_ ().fActiveIteratorsListHead_ = _fNextActiveIterator;\n }\n else {\n auto v = GetPatchingContainer_ ().fActiveIteratorsListHead_;\n for (; v->_fNextActiveIterator != this; v = v->_fNextActiveIterator) {\n AssertNotNull (v);\n AssertNotNull (v->_fNextActiveIterator);\n }\n AssertNotNull (v);\n Assert (v->_fNextActiveIterator == this);\n v->_fNextActiveIterator = _fNextActiveIterator;\n }\n\n \/*\n * Add to new.\n *\/\n fData = rhs.fData;\n _fNextActiveIterator = rhs.GetPatchingContainer_ ().fActiveIteratorsListHead_;\n GetPatchingContainer_ ().fActiveIteratorsListHead_ = this;\n }\n\n fData = rhs.fData;\n \/\/fPrev = rhs.fPrev;\n\n inherited::operator= (rhs);\n\n this->Invariant ();\n return *this;\n }\n template <typename T>\n inline bool LinkedList_Patch<T>::ForwardIterator::More (T* current, bool advance)\n {\n this->Invariant ();\n\n if (advance) {\n \/*\n * We could already be done since after the last Done() call, we could\n * have done a removeall.\n *\/\n if (not this->_fSuppressMore and this->_fCurrent != nullptr) {\n \/\/fPrev = this->_fCurrent;\n this->_fCurrent = this->_fCurrent->fNext;\n\n }\n this->_fSuppressMore = false;\n }\n this->Invariant ();\n if ((current != nullptr) and (not this->Done ())) {\n *current = this->_fCurrent->fItem;\n }\n return (not this->Done ());\n }\n template <typename T>\n inline void LinkedList_Patch<T>::ForwardIterator::PatchAdd (const Link* link)\n {\n \/*\n * link is the new link just added. If it was just after current, then\n * there is no problem - we will soon hit it. If it was well before current\n * (ie before prev) then there is still no problem. If it is the new\n * previous, we just adjust our previous.\n *\/\n RequireNotNull (link);\n if (link->fNext == this->_fCurrent) {\n \/\/fPrev = link;\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::ForwardIterator::PatchRemove (const Link* link)\n {\n RequireNotNull (link);\n\n \/*\n * There are basicly three cases:\n *\n * (1) We remove the current. In this case, we just advance current to the next\n * item (prev is already all set), and set _fSuppressMore since we are advanced\n * to the next item.\n * (2) We remove our previous. Technically this poses no problems, except then\n * our previos pointer is invalid. We could recompute it, but that would\n * involve rescanning the list from the beginning - slow. And we probably\n * will never need the next pointer (unless we get a remove current call).\n * So just set it to nullptr, which conventionally means no valid value.\n * It will be recomputed if needed.\n * (3) We are deleting some other value. No probs.\n *\/\n if (this->_fCurrent == link) {\n this->_fCurrent = this->_fCurrent->fNext;\n \/\/ fPrev remains the same - right now it points to a bad item, since\n \/\/ PatchRemove() called before the actual removal, but right afterwards\n \/\/ it will point to our new _fCurrent.\n this->_fSuppressMore = true; \/\/ Since we advanced cursor...\n }\n \/\/else if (fPrev == link) {\n \/\/ fPrev = nullptr; \/\/ real value recomputed later, if needed\n \/\/}\n }\n template <typename T>\n inline void LinkedList_Patch<T>::ForwardIterator::PatchRemoveAll ()\n {\n this->_fCurrent = nullptr;\n \/\/fPrev = nullptr;\n Ensure (this->Done ());\n }\n template <typename T>\n void LinkedList_Patch<T>::ForwardIterator::TwoPhaseIteratorPatcherPass1 (Link* oldI, Memory::SmallStackBuffer<ForwardIterator*>* items2Patch)\n {\n if (this->_fCurrent == oldI) {\n items2Patch->push_back (this);\n }\n }\n template <typename T>\n void LinkedList_Patch<T>::ForwardIterator::TwoPhaseIteratorPatcherPass2 (Link* newI)\n {\n this->_fSuppressMore = true;\n this->_fCurrent = newI;\n }\n template <typename T>\n inline const LinkedList_Patch<T>& LinkedList_Patch<T>::ForwardIterator::GetPatchingContainer_ () const\n {\n AssertMember (this->_fData, LinkedList_Patch<T>);\n return *static_cast<const LinkedList_Patch<T>*> (this->_fData);\n }\n template <typename T>\n inline LinkedList_Patch<T>& LinkedList_Patch<T>::ForwardIterator::GetPatchingContainer_ ()\n {\n AssertMember (this->_fData, LinkedList_Patch<T>);\n return *static_cast<LinkedList_Patch<T>*> (const_cast<DataStructures::LinkedList<T>*> (this->_fData));\n }\n#if qDebug\n template <typename T>\n void LinkedList_Patch<T>::ForwardIterator::Invariant_ () const\n {\n inherited::Invariant_ ();\n\n \/*\n * fPrev could be nullptr, but if it isn't then its next must be _fCurrent.\n *\/\n \/\/Assert ((fPrev == nullptr) or (fPrev->fNext == this->_fCurrent));\n }\n#endif\n\n\n }\n }\n }\n }\n}\n#endif \/* _Stroika_Foundation_Containers_Private_PatchingDataStructures_LinkedList_inl_ *\/\n<commit_msg>nearly done with this pass of LinkedList<T> cleanups<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_Private_PatchingDataStructures_LinkedList_inl_\n#define _Stroika_Foundation_Containers_Private_PatchingDataStructures_LinkedList_inl_ 1\n\n\n#include \"..\/..\/..\/Debug\/Assertions.h\"\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Containers {\n namespace Private {\n namespace PatchingDataStructures {\n\n\n \/*\n ********************************************************************************\n ***************************** LinkedList_Patch<T> ******************************\n ********************************************************************************\n *\/\n template <typename T>\n inline LinkedList_Patch<T>::LinkedList_Patch ()\n : inherited ()\n , fActiveIteratorsListHead_ (nullptr)\n {\n Invariant ();\n }\n template <typename T>\n inline LinkedList_Patch<T>::LinkedList_Patch (const LinkedList_Patch<T>& from)\n : inherited (from)\n , fActiveIteratorsListHead_ (nullptr) \/\/ Don't copy the list of iterators - would be trouble with backpointers!\n \/\/ Could clone but that would do no good, since nobody else would have pointers to them\n {\n Invariant ();\n }\n template <typename T>\n inline LinkedList_Patch<T>::~LinkedList_Patch ()\n {\n Require (fActiveIteratorsListHead_ == nullptr);\n }\n template <typename T>\n inline void LinkedList_Patch<T>::Invariant () const\n {\n#if qDebug\n Invariant_ ();\n InvariantOnIterators_ ();\n#endif\n }\n template <typename T>\n inline bool LinkedList_Patch<T>::HasActiveIterators () const\n {\n return bool (fActiveIteratorsListHead_ != nullptr);\n }\n template <typename T>\n inline void LinkedList_Patch<T>::PatchViewsAdd (const Link* link) const\n {\n RequireNotNull (link);\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n v->PatchAdd (link);\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::PatchViewsRemove (const Link* link) const\n {\n RequireNotNull (link);\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n v->PatchRemove (link);\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::PatchViewsRemoveAll () const\n {\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n v->PatchRemoveAll ();\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::TwoPhaseIteratorPatcherPass1 (Link* oldI, Memory::SmallStackBuffer<ForwardIterator*>* items2Patch) const\n {\n for (auto ai = fActiveIteratorsListHead_; ai != nullptr; ai = ai->_fNextActiveIterator) {\n ai->TwoPhaseIteratorPatcherPass1 (oldI, items2Patch);\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::TwoPhaseIteratorPatcherPass2 (const Memory::SmallStackBuffer<ForwardIterator*>* items2Patch, Link* newI)\n {\n for (size_t i = 0; i < items2Patch->GetSize (); ++i) {\n (*items2Patch)[i]->TwoPhaseIteratorPatcherPass2 (newI);\n }\n }\n template <typename T>\n inline LinkedList_Patch<T>& LinkedList_Patch<T>::operator= (const LinkedList_Patch<T>& rhs)\n {\n \/*\n * Don't copy the rhs iterators, and don't do assignments when we have active iterators.\n * If this is to be supported at some future date, well need to work on our patching.\n *\/\n Assert (not (HasActiveIterators ())); \/\/ cuz copy of LinkedList does not copy iterators...\n inherited::operator= (rhs);\n return (*this);\n }\n template <typename T>\n inline void LinkedList_Patch<T>::Prepend (T item)\n {\n Invariant ();\n inherited::Prepend (item);\n PatchViewsAdd (this->_fHead);\n Invariant ();\n }\n \/\/tmphack - must fix to have in base class and just hook for patch here\n template <typename T>\n inline void LinkedList_Patch<T>::Append (T item)\n {\n if (this->_fHead == nullptr) {\n Prepend (item);\n }\n else {\n Link* last = this->_fHead;\n for (; last->fNext != nullptr; last = last->fNext)\n ;\n Assert (last != nullptr);\n Assert (last->fNext == nullptr);\n last->fNext = new Link (item, nullptr);\n PatchViewsAdd (last->fNext);\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::RemoveFirst ()\n {\n Invariant ();\n PatchViewsRemove (this->_fHead);\n inherited::RemoveFirst ();\n Invariant ();\n }\n template <typename T>\n inline void LinkedList_Patch<T>::RemoveAll ()\n {\n Invariant ();\n inherited::RemoveAll ();\n PatchViewsRemoveAll ();\n Invariant ();\n }\n template <typename T>\n void LinkedList_Patch<T>::Remove (T item)\n {\n Invariant ();\n T current;\n for (ForwardIterator it (*this); it.More (¤t, true); ) {\n if (current == item) {\n this->RemoveAt (it);\n break;\n }\n }\n Invariant ();\n }\n template <typename T>\n void LinkedList_Patch<T>::RemoveAt (const ForwardIterator& i)\n {\n Require (not i.Done ());\n Invariant ();\n Memory::SmallStackBuffer<ForwardIterator*> items2Patch (0);\n TwoPhaseIteratorPatcherPass1 (const_cast<Link*> (i._fCurrent), &items2Patch);\n Link* next = i._fCurrent->fNext;\n this->inherited::RemoveAt (i);\n TwoPhaseIteratorPatcherPass2 (&items2Patch, next);\n Invariant ();\n }\n template <typename T>\n void LinkedList_Patch<T>::AddBefore (const ForwardIterator& i, T newValue)\n {\n Invariant ();\n\n \/\/tmphack\n const Link* prev = nullptr;\n if ((this->_fHead != nullptr) and (this->_fHead != i._fCurrent)) {\n for (prev = this->_fHead; prev->fNext != i._fCurrent; prev = prev->fNext) {\n AssertNotNull (prev); \/\/ cuz that would mean _fCurrent not in DoublyLinkedList!!!\n }\n }\n\n bool isPrevNull = (prev == nullptr);\n inherited::AddBefore (i, newValue);\n \/\/\/ WAG - VERY LIKELY WRONG BELOIW - MUST CLENAUP - LGP -2013-06-17\n if (isPrevNull) {\n this->PatchViewsAdd (this->_fHead); \/\/ Will adjust fPrev\n }\n else {\n this->PatchViewsAdd (prev->fNext); \/\/ Will adjust fPrev\n }\n Invariant ();\n }\n template <typename T>\n void LinkedList_Patch<T>::AddAfter (const ForwardIterator& i, T newValue)\n {\n Invariant ();\n inherited::AddAfter (i, newValue);\n this->PatchViewsAdd (i._fCurrent->fNext);\n Invariant ();\n }\n#if qDebug\n template <typename T>\n void LinkedList_Patch<T>::Invariant_ () const\n {\n inherited::Invariant_ ();\n \/*\n * Be sure each iterator points back to us. Thats about all we can test from\n * here since we cannot call each iterators Invariant(). That would be\n * nice, but sadly when this Invariant_ () is called from LinkedList<T> the\n * iterators themselves may not have been patched, so they'll be out of\n * date. Instead, so that in local shadow of Invariant() done in LinkedList_Patch<T>\n * so only called when WE call Invariant().\n *\/\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n Assert (v->_fData == this);\n }\n }\n template <typename T>\n void LinkedList_Patch<T>::InvariantOnIterators_ () const\n {\n \/*\n * Only here can we iterate over each iterator and calls its Invariant()\n * since now we've completed any needed patching.\n *\/\n for (auto v = fActiveIteratorsListHead_; v != nullptr; v = v->_fNextActiveIterator) {\n Assert (v->_fData == this);\n v->Invariant ();\n }\n }\n#endif\n\n\n \/*\n ********************************************************************************\n ******************** LinkedList_Patch<T>::ForwardIterator **********************\n ********************************************************************************\n *\/\n template <typename T>\n inline LinkedList_Patch<T>::ForwardIterator::ForwardIterator (const LinkedList_Patch<T>& data)\n : inherited (data)\n , _fNextActiveIterator (data.fActiveIteratorsListHead_)\n \/\/, fPrev (nullptr) \/\/ means invalid or fData->_fHead == _fCurrent ...\n {\n const_cast<LinkedList_Patch<T>*> (&data)->fActiveIteratorsListHead_ = this;\n this->Invariant ();\n }\n template <typename T>\n inline LinkedList_Patch<T>::ForwardIterator::ForwardIterator (const ForwardIterator& from)\n : inherited (from)\n , _fNextActiveIterator (from.GetPatchingContainer_ ().fActiveIteratorsListHead_)\n \/\/, fPrev (from.fPrev)\n {\n from.Invariant ();\n GetPatchingContainer_ ().fActiveIteratorsListHead_ = this;\n this->Invariant ();\n }\n template <typename T>\n inline LinkedList_Patch<T>::ForwardIterator::~ForwardIterator ()\n {\n this->Invariant ();\n if (GetPatchingContainer_ ().fActiveIteratorsListHead_ == this) {\n GetPatchingContainer_ ().fActiveIteratorsListHead_ = _fNextActiveIterator;\n }\n else {\n auto v = GetPatchingContainer_ ().fActiveIteratorsListHead_;\n for (; v->_fNextActiveIterator != this; v = v->_fNextActiveIterator) {\n AssertNotNull (v);\n AssertNotNull (v->_fNextActiveIterator);\n }\n AssertNotNull (v);\n Assert (v->_fNextActiveIterator == this);\n v->_fNextActiveIterator = _fNextActiveIterator;\n }\n }\n template <typename T>\n inline typename LinkedList_Patch<T>::ForwardIterator& LinkedList_Patch<T>::ForwardIterator::operator= (const ForwardIterator& rhs)\n {\n this->Invariant ();\n\n \/*\n * If the fData field has not changed, then we can leave alone our iterator linkage.\n * Otherwise, we must remove ourselves from the old, and add ourselves to the new.\n *\/\n if (&GetPatchingContainer_ () != &rhs.GetPatchingContainer_ ()) {\n\n \/*\n * Remove from old.\n *\/\n if (GetPatchingContainer_ ().fActiveIteratorsListHead_ == this) {\n GetPatchingContainer_ ().fActiveIteratorsListHead_ = _fNextActiveIterator;\n }\n else {\n auto v = GetPatchingContainer_ ().fActiveIteratorsListHead_;\n for (; v->_fNextActiveIterator != this; v = v->_fNextActiveIterator) {\n AssertNotNull (v);\n AssertNotNull (v->_fNextActiveIterator);\n }\n AssertNotNull (v);\n Assert (v->_fNextActiveIterator == this);\n v->_fNextActiveIterator = _fNextActiveIterator;\n }\n\n \/*\n * Add to new.\n *\/\n _fNextActiveIterator = rhs.GetPatchingContainer_ ().fActiveIteratorsListHead_;\n GetPatchingContainer_ ().fActiveIteratorsListHead_ = this;\n }\n\n \/\/fPrev = rhs.fPrev;\n\n inherited::operator= (rhs);\n\n this->Invariant ();\n return *this;\n }\n template <typename T>\n inline bool LinkedList_Patch<T>::ForwardIterator::More (T* current, bool advance)\n {\n this->Invariant ();\n\n if (advance) {\n \/*\n * We could already be done since after the last Done() call, we could\n * have done a removeall.\n *\/\n if (not this->_fSuppressMore and this->_fCurrent != nullptr) {\n \/\/fPrev = this->_fCurrent;\n this->_fCurrent = this->_fCurrent->fNext;\n\n }\n this->_fSuppressMore = false;\n }\n this->Invariant ();\n if ((current != nullptr) and (not this->Done ())) {\n *current = this->_fCurrent->fItem;\n }\n return (not this->Done ());\n }\n template <typename T>\n inline void LinkedList_Patch<T>::ForwardIterator::PatchAdd (const Link* link)\n {\n \/*\n * link is the new link just added. If it was just after current, then\n * there is no problem - we will soon hit it. If it was well before current\n * (ie before prev) then there is still no problem. If it is the new\n * previous, we just adjust our previous.\n *\/\n RequireNotNull (link);\n if (link->fNext == this->_fCurrent) {\n \/\/fPrev = link;\n }\n }\n template <typename T>\n inline void LinkedList_Patch<T>::ForwardIterator::PatchRemove (const Link* link)\n {\n RequireNotNull (link);\n\n \/*\n * There are basicly three cases:\n *\n * (1) We remove the current. In this case, we just advance current to the next\n * item (prev is already all set), and set _fSuppressMore since we are advanced\n * to the next item.\n * (2) We remove our previous. Technically this poses no problems, except then\n * our previos pointer is invalid. We could recompute it, but that would\n * involve rescanning the list from the beginning - slow. And we probably\n * will never need the next pointer (unless we get a remove current call).\n * So just set it to nullptr, which conventionally means no valid value.\n * It will be recomputed if needed.\n * (3) We are deleting some other value. No probs.\n *\/\n if (this->_fCurrent == link) {\n this->_fCurrent = this->_fCurrent->fNext;\n \/\/ fPrev remains the same - right now it points to a bad item, since\n \/\/ PatchRemove() called before the actual removal, but right afterwards\n \/\/ it will point to our new _fCurrent.\n this->_fSuppressMore = true; \/\/ Since we advanced cursor...\n }\n \/\/else if (fPrev == link) {\n \/\/ fPrev = nullptr; \/\/ real value recomputed later, if needed\n \/\/}\n }\n template <typename T>\n inline void LinkedList_Patch<T>::ForwardIterator::PatchRemoveAll ()\n {\n this->_fCurrent = nullptr;\n \/\/fPrev = nullptr;\n Ensure (this->Done ());\n }\n template <typename T>\n void LinkedList_Patch<T>::ForwardIterator::TwoPhaseIteratorPatcherPass1 (Link* oldI, Memory::SmallStackBuffer<ForwardIterator*>* items2Patch)\n {\n if (this->_fCurrent == oldI) {\n items2Patch->push_back (this);\n }\n }\n template <typename T>\n void LinkedList_Patch<T>::ForwardIterator::TwoPhaseIteratorPatcherPass2 (Link* newI)\n {\n this->_fSuppressMore = true;\n this->_fCurrent = newI;\n }\n template <typename T>\n inline const LinkedList_Patch<T>& LinkedList_Patch<T>::ForwardIterator::GetPatchingContainer_ () const\n {\n AssertMember (this->_fData, LinkedList_Patch<T>);\n return *static_cast<const LinkedList_Patch<T>*> (this->_fData);\n }\n template <typename T>\n inline LinkedList_Patch<T>& LinkedList_Patch<T>::ForwardIterator::GetPatchingContainer_ ()\n {\n AssertMember (this->_fData, LinkedList_Patch<T>);\n return *static_cast<LinkedList_Patch<T>*> (const_cast<DataStructures::LinkedList<T>*> (this->_fData));\n }\n#if qDebug\n template <typename T>\n void LinkedList_Patch<T>::ForwardIterator::Invariant_ () const\n {\n inherited::Invariant_ ();\n\n \/*\n * fPrev could be nullptr, but if it isn't then its next must be _fCurrent.\n *\/\n \/\/Assert ((fPrev == nullptr) or (fPrev->fNext == this->_fCurrent));\n }\n#endif\n\n\n }\n }\n }\n }\n}\n#endif \/* _Stroika_Foundation_Containers_Private_PatchingDataStructures_LinkedList_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix the build of view_examples for Linux.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Listener on a control datagram socket.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"lb_control.hxx\"\n#include \"lb_instance.hxx\"\n#include \"lb_config.hxx\"\n#include \"lb_stats.hxx\"\n#include \"control_server.hxx\"\n#include \"address_edit.h\"\n#include \"failure.hxx\"\n#include \"tpool.hxx\"\n#include \"pool.hxx\"\n\n#include <daemon\/log.h>\n#include <socket\/address.h>\n\n#include <string.h>\n#include <stdlib.h>\n\nstatic void\nenable_node(const struct lb_instance *instance,\n const char *payload, size_t length)\n{\n const char *colon = (const char *)memchr(payload, ':', length);\n if (colon == NULL || colon == payload || colon == payload + length - 1) {\n daemon_log(3, \"malformed FADE_NODE control packet: no port\\n\");\n return;\n }\n\n const AutoRewindPool auto_rewind(*tpool);\n\n char *node_name = p_strndup(tpool, payload, length);\n char *port_string = node_name + (colon - payload);\n *port_string++ = 0;\n\n const lb_node_config *node = instance->config->FindNode(node_name);\n if (node == NULL) {\n daemon_log(3, \"unknown node in FADE_NODE control packet\\n\");\n return;\n }\n\n char *endptr;\n unsigned port = strtoul(port_string, &endptr, 10);\n if (port == 0 || *endptr != 0) {\n daemon_log(3, \"malformed FADE_NODE control packet: port is not a number\\n\");\n return;\n }\n\n const struct sockaddr *with_port =\n sockaddr_set_port(tpool,\n node->address, node->address.GetSize(),\n port);\n\n char buffer[64];\n socket_address_to_string(buffer, sizeof(buffer), with_port,\n node->address.GetSize());\n daemon_log(4, \"enabling node %s (%s)\\n\", node_name, buffer);\n\n failure_unset({with_port, node->address.GetSize()}, FAILURE_OK);\n}\n\nstatic void\nfade_node(const struct lb_instance *instance,\n const char *payload, size_t length)\n{\n const char *colon = (const char *)memchr(payload, ':', length);\n if (colon == NULL || colon == payload || colon == payload + length - 1) {\n daemon_log(3, \"malformed FADE_NODE control packet: no port\\n\");\n return;\n }\n\n const AutoRewindPool auto_rewind(*tpool);\n\n char *node_name = p_strndup(tpool, payload, length);\n char *port_string = node_name + (colon - payload);\n *port_string++ = 0;\n\n const lb_node_config *node = instance->config->FindNode(node_name);\n if (node == NULL) {\n daemon_log(3, \"unknown node in FADE_NODE control packet\\n\");\n return;\n }\n\n char *endptr;\n unsigned port = strtoul(port_string, &endptr, 10);\n if (port == 0 || *endptr != 0) {\n daemon_log(3, \"malformed FADE_NODE control packet: port is not a number\\n\");\n return;\n }\n\n const struct sockaddr *with_port =\n sockaddr_set_port(tpool,\n node->address, node->address.GetSize(),\n port);\n\n char buffer[64];\n socket_address_to_string(buffer, sizeof(buffer), with_port,\n node->address.GetSize());\n daemon_log(4, \"fading node %s (%s)\\n\", node_name, buffer);\n\n \/* set status \"FADE\" for 3 hours *\/\n failure_set({with_port, node->address.GetSize()}, FAILURE_FADE, 3 * 3600);\n}\n\nG_GNUC_CONST\nstatic const char *\nfailure_status_to_string(enum failure_status status)\n{\n switch (status) {\n case FAILURE_OK:\n return \"ok\";\n\n case FAILURE_FADE:\n return \"fade\";\n\n case FAILURE_RESPONSE:\n case FAILURE_FAILED:\n case FAILURE_MONITOR:\n break;\n }\n\n return \"error\";\n}\n\nstatic bool\nnode_status_response(ControlServer *server, struct pool *pool,\n SocketAddress address,\n const char *payload, size_t length, const char *status,\n GError **error_r)\n{\n size_t status_length = strlen(status);\n\n size_t response_length = length + 1 + status_length;\n char *response = PoolAlloc<char>(*tpool, response_length);\n memcpy(response, payload, length);\n response[length] = 0;\n memcpy(response + length + 1, status, status_length);\n\n return control_server_reply(server, pool, address,\n CONTROL_NODE_STATUS, response, response_length,\n error_r);\n}\n\nstatic void\nquery_node_status(LbControl *control,\n const char *payload, size_t length,\n SocketAddress address)\n{\n if (address.GetSize() == 0) {\n daemon_log(3, \"got NODE_STATUS from unbound client socket\\n\");\n return;\n }\n\n const char *colon = (const char *)memchr(payload, ':', length);\n if (colon == NULL || colon == payload || colon == payload + length - 1) {\n node_status_response(control->server, tpool, address,\n payload, length, \"malformed\", NULL);\n daemon_log(3, \"malformed NODE_STATUS control packet: no port\\n\");\n return;\n }\n\n const AutoRewindPool auto_rewind(*tpool);\n\n char *node_name = p_strndup(tpool, payload, length);\n char *port_string = node_name + (colon - payload);\n *port_string++ = 0;\n\n const lb_node_config *node =\n control->instance->config->FindNode(node_name);\n if (node == NULL) {\n node_status_response(control->server, tpool, address,\n payload, length, \"unknown\", NULL);\n daemon_log(3, \"unknown node in NODE_STATUS control packet\\n\");\n return;\n }\n\n char *endptr;\n unsigned port = strtoul(port_string, &endptr, 10);\n if (port == 0 || *endptr != 0) {\n node_status_response(control->server, tpool, address,\n payload, length, \"malformed\", NULL);\n daemon_log(3, \"malformed NODE_STATUS control packet: port is not a number\\n\");\n return;\n }\n\n const struct sockaddr *with_port =\n sockaddr_set_port(tpool,\n node->address, node->address.GetSize(),\n port);\n\n char buffer[64];\n socket_address_to_string(buffer, sizeof(buffer), with_port,\n node->address.GetSize());\n\n enum failure_status status =\n failure_get_status({with_port, node->address.GetSize()});\n const char *s = failure_status_to_string(status);\n\n GError *error = NULL;\n if (!node_status_response(control->server, tpool, address,\n payload, length, s,\n &error)) {\n daemon_log(3, \"%s\\n\", error->message);\n g_error_free(error);\n }\n}\n\nstatic void\nquery_stats(LbControl *control, SocketAddress address)\n{\n struct beng_control_stats stats;\n lb_get_stats(control->instance, &stats);\n\n const AutoRewindPool auto_rewind(*tpool);\n\n GError *error = NULL;\n if (!control_server_reply(control->server, tpool,\n address,\n CONTROL_STATS, &stats, sizeof(stats),\n &error)) {\n daemon_log(3, \"%s\\n\", error->message);\n g_error_free(error);\n }\n}\n\nstatic void\nlb_control_packet(enum beng_control_command command,\n const void *payload, size_t payload_length,\n SocketAddress address,\n void *ctx)\n{\n auto *control = (LbControl *)ctx;\n\n switch (command) {\n case CONTROL_NOP:\n case CONTROL_TCACHE_INVALIDATE:\n case CONTROL_FADE_CHILDREN:\n break;\n\n case CONTROL_ENABLE_NODE:\n enable_node(control->instance, (const char *)payload, payload_length);\n break;\n\n case CONTROL_FADE_NODE:\n fade_node(control->instance, (const char *)payload, payload_length);\n break;\n\n case CONTROL_NODE_STATUS:\n query_node_status(control, (const char *)payload, payload_length,\n address);\n break;\n\n case CONTROL_DUMP_POOLS:\n pool_dump_tree(control->instance->pool);\n break;\n\n case CONTROL_STATS:\n query_stats(control, address);\n break;\n\n case CONTROL_VERBOSE:\n if (payload_length == 1)\n daemon_log_config.verbose = *(const uint8_t *)payload;\n break;\n }\n}\n\nstatic void\nlb_control_error(GError *error, gcc_unused void *ctx)\n{\n daemon_log(2, \"%s\\n\", error->message);\n g_error_free(error);\n}\n\nstatic constexpr struct control_handler lb_control_handler = {\n nullptr,\n lb_control_packet,\n lb_control_error,\n};\n\nLbControl *\nlb_control_new(struct lb_instance *instance,\n const struct lb_control_config *config,\n GError **error_r)\n{\n auto *control = new LbControl();\n control->instance = instance;\n\n control->server =\n control_server_new(config->bind_address,\n &lb_control_handler, control,\n error_r);\n if (control->server == NULL) {\n delete control;\n return NULL;\n }\n\n return control;\n}\n\nvoid\nlb_control_free(LbControl *control)\n{\n control_server_free(control->server);\n\n delete control;\n}\n\nvoid\nlb_control_enable(LbControl *control)\n{\n control_server_enable(control->server);\n}\n\nvoid\nlb_control_disable(LbControl *control)\n{\n control_server_disable(control->server);\n}\n<commit_msg>lb_control: use nullptr instead of NULL<commit_after>\/*\n * Listener on a control datagram socket.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"lb_control.hxx\"\n#include \"lb_instance.hxx\"\n#include \"lb_config.hxx\"\n#include \"lb_stats.hxx\"\n#include \"control_server.hxx\"\n#include \"address_edit.h\"\n#include \"failure.hxx\"\n#include \"tpool.hxx\"\n#include \"pool.hxx\"\n\n#include <daemon\/log.h>\n#include <socket\/address.h>\n\n#include <string.h>\n#include <stdlib.h>\n\nstatic void\nenable_node(const struct lb_instance *instance,\n const char *payload, size_t length)\n{\n const char *colon = (const char *)memchr(payload, ':', length);\n if (colon == nullptr || colon == payload || colon == payload + length - 1) {\n daemon_log(3, \"malformed FADE_NODE control packet: no port\\n\");\n return;\n }\n\n const AutoRewindPool auto_rewind(*tpool);\n\n char *node_name = p_strndup(tpool, payload, length);\n char *port_string = node_name + (colon - payload);\n *port_string++ = 0;\n\n const lb_node_config *node = instance->config->FindNode(node_name);\n if (node == nullptr) {\n daemon_log(3, \"unknown node in FADE_NODE control packet\\n\");\n return;\n }\n\n char *endptr;\n unsigned port = strtoul(port_string, &endptr, 10);\n if (port == 0 || *endptr != 0) {\n daemon_log(3, \"malformed FADE_NODE control packet: port is not a number\\n\");\n return;\n }\n\n const struct sockaddr *with_port =\n sockaddr_set_port(tpool,\n node->address, node->address.GetSize(),\n port);\n\n char buffer[64];\n socket_address_to_string(buffer, sizeof(buffer), with_port,\n node->address.GetSize());\n daemon_log(4, \"enabling node %s (%s)\\n\", node_name, buffer);\n\n failure_unset({with_port, node->address.GetSize()}, FAILURE_OK);\n}\n\nstatic void\nfade_node(const struct lb_instance *instance,\n const char *payload, size_t length)\n{\n const char *colon = (const char *)memchr(payload, ':', length);\n if (colon == nullptr || colon == payload || colon == payload + length - 1) {\n daemon_log(3, \"malformed FADE_NODE control packet: no port\\n\");\n return;\n }\n\n const AutoRewindPool auto_rewind(*tpool);\n\n char *node_name = p_strndup(tpool, payload, length);\n char *port_string = node_name + (colon - payload);\n *port_string++ = 0;\n\n const lb_node_config *node = instance->config->FindNode(node_name);\n if (node == nullptr) {\n daemon_log(3, \"unknown node in FADE_NODE control packet\\n\");\n return;\n }\n\n char *endptr;\n unsigned port = strtoul(port_string, &endptr, 10);\n if (port == 0 || *endptr != 0) {\n daemon_log(3, \"malformed FADE_NODE control packet: port is not a number\\n\");\n return;\n }\n\n const struct sockaddr *with_port =\n sockaddr_set_port(tpool,\n node->address, node->address.GetSize(),\n port);\n\n char buffer[64];\n socket_address_to_string(buffer, sizeof(buffer), with_port,\n node->address.GetSize());\n daemon_log(4, \"fading node %s (%s)\\n\", node_name, buffer);\n\n \/* set status \"FADE\" for 3 hours *\/\n failure_set({with_port, node->address.GetSize()}, FAILURE_FADE, 3 * 3600);\n}\n\nG_GNUC_CONST\nstatic const char *\nfailure_status_to_string(enum failure_status status)\n{\n switch (status) {\n case FAILURE_OK:\n return \"ok\";\n\n case FAILURE_FADE:\n return \"fade\";\n\n case FAILURE_RESPONSE:\n case FAILURE_FAILED:\n case FAILURE_MONITOR:\n break;\n }\n\n return \"error\";\n}\n\nstatic bool\nnode_status_response(ControlServer *server, struct pool *pool,\n SocketAddress address,\n const char *payload, size_t length, const char *status,\n GError **error_r)\n{\n size_t status_length = strlen(status);\n\n size_t response_length = length + 1 + status_length;\n char *response = PoolAlloc<char>(*tpool, response_length);\n memcpy(response, payload, length);\n response[length] = 0;\n memcpy(response + length + 1, status, status_length);\n\n return control_server_reply(server, pool, address,\n CONTROL_NODE_STATUS, response, response_length,\n error_r);\n}\n\nstatic void\nquery_node_status(LbControl *control,\n const char *payload, size_t length,\n SocketAddress address)\n{\n if (address.GetSize() == 0) {\n daemon_log(3, \"got NODE_STATUS from unbound client socket\\n\");\n return;\n }\n\n const char *colon = (const char *)memchr(payload, ':', length);\n if (colon == nullptr || colon == payload || colon == payload + length - 1) {\n node_status_response(control->server, tpool, address,\n payload, length, \"malformed\", nullptr);\n daemon_log(3, \"malformed NODE_STATUS control packet: no port\\n\");\n return;\n }\n\n const AutoRewindPool auto_rewind(*tpool);\n\n char *node_name = p_strndup(tpool, payload, length);\n char *port_string = node_name + (colon - payload);\n *port_string++ = 0;\n\n const lb_node_config *node =\n control->instance->config->FindNode(node_name);\n if (node == nullptr) {\n node_status_response(control->server, tpool, address,\n payload, length, \"unknown\", nullptr);\n daemon_log(3, \"unknown node in NODE_STATUS control packet\\n\");\n return;\n }\n\n char *endptr;\n unsigned port = strtoul(port_string, &endptr, 10);\n if (port == 0 || *endptr != 0) {\n node_status_response(control->server, tpool, address,\n payload, length, \"malformed\", nullptr);\n daemon_log(3, \"malformed NODE_STATUS control packet: port is not a number\\n\");\n return;\n }\n\n const struct sockaddr *with_port =\n sockaddr_set_port(tpool,\n node->address, node->address.GetSize(),\n port);\n\n char buffer[64];\n socket_address_to_string(buffer, sizeof(buffer), with_port,\n node->address.GetSize());\n\n enum failure_status status =\n failure_get_status({with_port, node->address.GetSize()});\n const char *s = failure_status_to_string(status);\n\n GError *error = nullptr;\n if (!node_status_response(control->server, tpool, address,\n payload, length, s,\n &error)) {\n daemon_log(3, \"%s\\n\", error->message);\n g_error_free(error);\n }\n}\n\nstatic void\nquery_stats(LbControl *control, SocketAddress address)\n{\n struct beng_control_stats stats;\n lb_get_stats(control->instance, &stats);\n\n const AutoRewindPool auto_rewind(*tpool);\n\n GError *error = nullptr;\n if (!control_server_reply(control->server, tpool,\n address,\n CONTROL_STATS, &stats, sizeof(stats),\n &error)) {\n daemon_log(3, \"%s\\n\", error->message);\n g_error_free(error);\n }\n}\n\nstatic void\nlb_control_packet(enum beng_control_command command,\n const void *payload, size_t payload_length,\n SocketAddress address,\n void *ctx)\n{\n auto *control = (LbControl *)ctx;\n\n switch (command) {\n case CONTROL_NOP:\n case CONTROL_TCACHE_INVALIDATE:\n case CONTROL_FADE_CHILDREN:\n break;\n\n case CONTROL_ENABLE_NODE:\n enable_node(control->instance, (const char *)payload, payload_length);\n break;\n\n case CONTROL_FADE_NODE:\n fade_node(control->instance, (const char *)payload, payload_length);\n break;\n\n case CONTROL_NODE_STATUS:\n query_node_status(control, (const char *)payload, payload_length,\n address);\n break;\n\n case CONTROL_DUMP_POOLS:\n pool_dump_tree(control->instance->pool);\n break;\n\n case CONTROL_STATS:\n query_stats(control, address);\n break;\n\n case CONTROL_VERBOSE:\n if (payload_length == 1)\n daemon_log_config.verbose = *(const uint8_t *)payload;\n break;\n }\n}\n\nstatic void\nlb_control_error(GError *error, gcc_unused void *ctx)\n{\n daemon_log(2, \"%s\\n\", error->message);\n g_error_free(error);\n}\n\nstatic constexpr struct control_handler lb_control_handler = {\n nullptr,\n lb_control_packet,\n lb_control_error,\n};\n\nLbControl *\nlb_control_new(struct lb_instance *instance,\n const struct lb_control_config *config,\n GError **error_r)\n{\n auto *control = new LbControl();\n control->instance = instance;\n\n control->server =\n control_server_new(config->bind_address,\n &lb_control_handler, control,\n error_r);\n if (control->server == nullptr) {\n delete control;\n return nullptr;\n }\n\n return control;\n}\n\nvoid\nlb_control_free(LbControl *control)\n{\n control_server_free(control->server);\n\n delete control;\n}\n\nvoid\nlb_control_enable(LbControl *control)\n{\n control_server_enable(control->server);\n}\n\nvoid\nlb_control_disable(LbControl *control)\n{\n control_server_disable(control->server);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"lexer\/lexer.h\"\n\nLexer::Lexer(const char *file, bool f) {\n file_ = true;\n std::ifstream infile(file);\n file_name_ = file;\n int length = 0;\n if (infile.fail()) {\n ERROR(std::string, \"cannot open file\");\n f = false;\n err_msg_ = file + std::string(\": file doesn't exist\\n\");\n return;\n }\n infile.seekg(0, infile.end);\n length = (size_t)infile.tellg();\n infile.seekg(0, infile.beg);\n code_.resize(length + 2, ' ');\n infile.read(&*(code_.begin()), length);\n infile.close();\n size_ = length;\n end_ = length;\n seek_ = 0;\n tok_ = nullptr;\n eos_ = false;\n}\n\nToken *Lexer::NextToken() {\n char ch, ch2, ch3;\n TokenType tok;\n Position pos;\n\n if (!buffer_.empty()) {\n Token *tok = buffer_.back();\n buffer_.pop_back();\n return tok;\n }\n\n ch = NextCharacter();\n \/\/ skip whitespaces\n while (ch != EOF && (ch == ' ' || ch == '\\n' || ch == '\\t'))\n ch = NextCharacter();\n\n \/\/ skip comments\n while (ch != EOF &&\n ((ch == '\/' && LookAhead() == '\/') || (ch == '\/' && LookAhead() == '*')))\n StripComments(ch);\n\n \/\/ note the current position as we are about to parse\n \/\/ a valid(may be) token from this position\n pos = position_;\n\n if (ch != EOF) {\n\n \/\/ handle keywords, identifiers and numbers\n while (isalnum(ch) || ch == '_')\n return Characterize(ch, pos);\n\n if (LookAhead() == EOF || LookAhead() == '\\0' || LookAhead() == ' ' ||\n LookAhead() == '\\t' || LookAhead() == '\\n')\n goto one;\n \/\/ else ch is a symbol\n ch2 = NextCharacter();\n\n if (LookAhead() == EOF || LookAhead() == '\\0' || LookAhead() == ' ' ||\n LookAhead() == '\\t' || LookAhead() == '\\n')\n goto two;\n ch3 = NextCharacter();\n\n \/\/ check if there is a three character symbol\n tok = ThreeCharacterSymbol(ch, ch2, ch3);\n if (tok != INVALID) {\n return new Token(std::string({ch, ch2, ch3}), tok,\n TOKENS[tok].precedance_, pos);\n }\n \/\/ as we have gone ahead one character so time to go back\n GoBack();\n two:\n \/\/ so now check whether we are at position of two character symbol\n tok = TwoCharacterSymbol(ch, ch2);\n if (tok != INVALID) {\n return new Token(std::string({ch, ch2}), tok, TOKENS[tok].precedance_,\n pos);\n }\n\n \/\/ No! Let's go back one character\n GoBack();\n\n one:\n \/\/ Only possibility left\n tok = OneCharacterSymbol(ch);\n if (tok != INVALID) {\n return new Token(std::string({ch}), tok, TOKENS[tok].precedance_, pos);\n } else \/\/ oops! something went wrong, token is invalid!\n return new Token(std::string({ch}), INVALID, 0, pos);\n }\n\n \/\/ finally reached at the end of the given string\n return new Token(std::string({ch}), EOS, -1, pos);\n}\n\nvoid Lexer::StripComments(char &ch) { \/\/ skips all the comments from the string\n char last = '\\0';\n \/\/ skip the comments - single line comment\n if (ch != EOF && (ch == '\/' && LookAhead() == '\/')) {\n ch = NextCharacter();\n while (ch != '\\n' || ch == EOF)\n ch = NextCharacter();\n ch = NextCharacter();\n }\n\n \/\/ multiline comment, \/* *\/ type\n if (ch != EOF && (ch == '\/' && LookAhead() == '*')) {\n last = ch;\n ch = NextCharacter();\n while (ch != EOF && !(last == '*' && ch == '\/')) {\n last = ch;\n ch = NextCharacter();\n }\n ch = NextCharacter();\n }\n\n while (ch != EOF && (ch == ' ' || ch == '\\n' || ch == '\\t'))\n ch = NextCharacter();\n}\n\nvoid Lexer::GoBack() { \/\/ go back one character back\n --seek_;\n if (position_.col_ - 1 < 0) { \/\/ we don't want our col_ to be negative\n position_.row_--; \/\/ needed\n position_.col_ = lastColNumber_;\n } else { \/\/ okay, so simply decrement col_ member\n position_.col_--;\n }\n}\n\nchar Lexer::NextCharacter() { \/\/ returns the next character from the string\n if (seek_ <= end_) { \/\/ if eos_ flag has not been set\n char ch = code_[seek_++];\n if (ch == '\\0') { \/\/ if we are not processing EOF file character\n ch = EOF;\n eos_ = true;\n }\n if (ch == '\\n') { \/\/ change the position\n position_.row_++;\n lastColNumber_ = position_.col_;\n position_.col_ = 0;\n } else {\n position_.col_++;\n }\n return ch;\n }\n return EOF;\n}\n\nToken *Lexer::Characterize(char ch,\n Position &pos)\n{\n std::string buffer;\n if (isdigit(ch))\n return ParseNumber(ch, pos);\n\n if (isalpha(ch) || ch == '_' || ch == '$')\n return ParseIdentifierOrKeyWord(ch, pos);\n\n \/\/ if none of both then we have to return a invalid token\n return new Token(std::string(\"\"), INVALID, -1, pos);\n}\n\nToken *\nLexer::ParseNumber(char ch,\n Position &pos) { \/\/ parses the number from the current position\n std::string buffer; \/\/ buffer to store the parsed number\n while (isdigit(ch)) {\n buffer += ch;\n ch = NextCharacter();\n }\n \/\/ possible floating point number\n if (ch == '.' || ch == 'e' || ch == 'E') {\n buffer += ch;\n ch = NextCharacter();\n while (isdigit(ch)) {\n buffer += ch;\n ch = NextCharacter();\n }\n }\n \/\/ we've gone one character ahead, so go back\n GoBack();\n\n return new Token(buffer, DIGIT, -1, pos);\n}\n\nToken *Lexer::ParseIdentifierOrKeyWord(\n char ch,\n Position &\n pos) { \/\/ parses the identifier or a keyword from the current position\n std::string buffer;\n \/\/ possibly it is an identifier\n while (isalnum(ch) || ch == '_' || ch == '$') {\n buffer += ch;\n ch = NextCharacter();\n }\n \/\/ again went a character ahead\n GoBack();\n \/\/ check for KeyWord\n if (buffer[0] != '_' || buffer[0] != '$') {\n for (int i = LET; i <= RET; i++)\n if (buffer[0] == TOKENS[i].value_[0] && buffer == TOKENS[i].value_)\n return new Token(buffer, i, 0, pos);\n }\n return new Token(buffer, IDENT, -1, pos);\n}\n\n\/\/ although not required because of no use\nToken *Lexer::ParseStringLiteral(\n char ch, Position &pos) { \/\/ parses the string literal from the string\n std::string str = \"\";\n if (ch == '\"') { \/\/ string surrounded by \"\n ch = NextCharacter();\n while (ch != '\"') {\n str += ch;\n ch = NextCharacter();\n }\n } else if (ch == '\\'') { \/\/ string surrounded by '\n ch = NextCharacter();\n while (ch != '\\'') {\n str += ch;\n ch = NextCharacter();\n }\n }\n return new Token(str, STRING, -1, pos);\n}\n\nchar parsehex(char ch) {\n if (ch >= '0' && ch <= '9')\n return ch - '0';\n else if ((ch >= 'a' && ch <= 'f')) {\n return 10 + ch - 'a';\n } else if (ch >= 'A' && ch <= 'F') {\n return 10 + ch - 'A';\n }\n throw std::runtime_error(\"wrong hexadecimal digits\");\n}\n\nchar parseoct(char ch) {\n if (ch >= '0' && ch <= '8')\n return ch - '0';\n throw std::runtime_error(\"wrong octal digits\");\n}\n\nchar escape_code(std::string str) {\n if (str[0] != '\\\\')\n return str[0];\n if (str[1] == 'x') {\n char ret = 0;\n ret |= parsehex(str[2]);\n ret <<= 4;\n ret |= parsehex(str[3]);\n return ret;\n } else if (str[1] == 'n')\n return '\\n';\n else if (str[1] == 'b')\n return '\\b';\n else if (str[1] == 'r')\n return '\\r';\n else if (str[1] == 'a')\n return '\\a';\n else if (str[1] == 't')\n return '\\t';\n else if (str[1] == '\"')\n return '\"';\n else if (str[1] == '\\'')\n return '\\'';\n else throw std::runtime_error(\"unknown escape code\");\n}\n\n\/\/ this function should be used instead of above function\n\/\/ when we found a token of \" or ' that means we are about\n\/\/ to parse the string from the current position\nstd::string Lexer::GetStringLiteral() { \/\/ returns all the string until it finds \"\n\n \/\/ create a buffer\n std::string str = \"\";\n char ch = NextCharacter();\n while (ch != EOF && (ch != '\"' && ch != '\\'')) {\n if (ch == '\\\\') {\n \/\/ a possible escape code\n std::string tmp = \"\";\n tmp += ch;\n ch = NextCharacter();\n tmp += ch;\n if (ch == 'x') {\n ch = NextCharacter();\n tmp += ch;\n ch = NextCharacter();\n tmp += ch;\n }\n ch = escape_code(tmp);\n }\n str += ch; \/\/ fill the buffer\n ch = NextCharacter();\n }\n return str;\n}\n\nTokenType Lexer::OneCharacterSymbol(\n char ch) { \/\/ returns the type of token from the given symbol\n switch (ch) {\n case '(':\n return LPAR;\n case ')':\n return RPAR;\n case '{':\n return LBRACE;\n case '}':\n return RBRACE;\n case '[':\n return LSQB;\n case ']':\n return RSQB;\n case ':':\n return COLON;\n case ';':\n return SCOLON;\n case '\"':\n case '\\'':\n return STRING;\n case '.':\n return DOT;\n case ',':\n return COMMA;\n case '?':\n return CONDITION;\n case '+':\n return PLUS;\n case '-':\n return MINUS;\n case '\/':\n return DIV;\n case '*':\n return MUL;\n case '%':\n return MOD;\n case '>':\n return GT;\n case '<':\n return LT;\n case '=':\n return ASSIGN;\n case '^':\n return XOR;\n case '|':\n return BOR;\n case '&':\n return BAND;\n case '!':\n return NOT;\n case '~':\n return BNOT;\n default:\n return INVALID;\n }\n}\n\nTokenType\nLexer::TwoCharacterSymbol(char ch1,\n char ch2) { \/\/ returns the type of symbol of two characters\n switch (ch2) {\n case '=':\n switch (ch1) {\n case '+':\n return PLUSEQ;\n case '-':\n return MINUSEQ;\n case '*':\n return MULEQ;\n case '\/':\n return DIVEQ;\n case '%':\n return MODEQ;\n case '^':\n return XOREQ;\n case '&':\n return BANDEQ;\n case '|':\n return BOREQ;\n case '>':\n return GTE;\n case '<':\n return LTE;\n case '=':\n return EQUAL;\n case '!':\n return NOTEQ;\n }\n return INVALID;\n case '|':\n if (ch1 == '|')\n return OR;\n return INVALID;\n case '&':\n if (ch1 == '&')\n return AND;\n return INVALID;\n case '+':\n if (ch1 == '+')\n return INC;\n return INVALID;\n case '-':\n if (ch1 == '-')\n return DEC;\n return INVALID;\n case '<':\n if (ch1 == '<')\n return SHL;\n return INVALID;\n case '>':\n if (ch1 == '>')\n return SHR;\n default:\n return INVALID;\n }\n}\n\nbool Lexer::IsFile() const { return file_; }\nstd::string Lexer::GetFileName() { return file_name_; }\n\nTokenType Lexer::ThreeCharacterSymbol(\n char ch1, char ch2,\n char ch3) { \/\/ returns the type of symbol of three characters\n switch (ch3) {\n case '=':\n if (ch1 == '>' && ch2 == '>')\n return SHREQ;\n if (ch1 == '<' && ch2 == '<')\n return SHLEQ;\n default:\n return INVALID;\n }\n}\n\nvoid Lexer::PutBack(Token *tok) { \/\/ put in the buffer for one token lookahead\n \/\/ required by parser\n buffer_.push_back(tok);\n}\n\n\/\/ move to next token\nvoid Lexer::advance()\n{\n tok_ = NextToken();\n}\n\ndouble Lexer::GetNumber()\n{\n double result = 0.0;\n try {\n result = std::stod(tok_->GetValue());\n } catch (std::exception &e) {\n std::cerr << e.what() << std::endl;\n }\n\n return result;\n}\n\n<commit_msg>Fix: raspberry pi build issue<commit_after>#include \"lexer\/lexer.h\"\n#include <stdexcept>\n\nLexer::Lexer(const char *file, bool f) {\n file_ = true;\n std::ifstream infile(file);\n file_name_ = file;\n int length = 0;\n if (infile.fail()) {\n ERROR(std::string, \"cannot open file\");\n f = false;\n err_msg_ = file + std::string(\": file doesn't exist\\n\");\n return;\n }\n infile.seekg(0, infile.end);\n length = (size_t)infile.tellg();\n infile.seekg(0, infile.beg);\n code_.resize(length + 2, ' ');\n infile.read(&*(code_.begin()), length);\n infile.close();\n size_ = length;\n end_ = length;\n seek_ = 0;\n tok_ = nullptr;\n eos_ = false;\n}\n\nToken *Lexer::NextToken() {\n char ch, ch2, ch3;\n TokenType tok;\n Position pos;\n\n if (!buffer_.empty()) {\n Token *tok = buffer_.back();\n buffer_.pop_back();\n return tok;\n }\n\n ch = NextCharacter();\n \/\/ skip whitespaces\n while (ch != EOF && (ch == ' ' || ch == '\\n' || ch == '\\t'))\n ch = NextCharacter();\n\n \/\/ skip comments\n while (ch != EOF &&\n ((ch == '\/' && LookAhead() == '\/') || (ch == '\/' && LookAhead() == '*')))\n StripComments(ch);\n\n \/\/ note the current position as we are about to parse\n \/\/ a valid(may be) token from this position\n pos = position_;\n\n if (ch != EOF) {\n\n \/\/ handle keywords, identifiers and numbers\n while (isalnum(ch) || ch == '_')\n return Characterize(ch, pos);\n\n if (LookAhead() == EOF || LookAhead() == '\\0' || LookAhead() == ' ' ||\n LookAhead() == '\\t' || LookAhead() == '\\n')\n goto one;\n \/\/ else ch is a symbol\n ch2 = NextCharacter();\n\n if (LookAhead() == EOF || LookAhead() == '\\0' || LookAhead() == ' ' ||\n LookAhead() == '\\t' || LookAhead() == '\\n')\n goto two;\n ch3 = NextCharacter();\n\n \/\/ check if there is a three character symbol\n tok = ThreeCharacterSymbol(ch, ch2, ch3);\n if (tok != INVALID) {\n return new Token(std::string({ch, ch2, ch3}), tok,\n TOKENS[tok].precedance_, pos);\n }\n \/\/ as we have gone ahead one character so time to go back\n GoBack();\n two:\n \/\/ so now check whether we are at position of two character symbol\n tok = TwoCharacterSymbol(ch, ch2);\n if (tok != INVALID) {\n return new Token(std::string({ch, ch2}), tok, TOKENS[tok].precedance_,\n pos);\n }\n\n \/\/ No! Let's go back one character\n GoBack();\n\n one:\n \/\/ Only possibility left\n tok = OneCharacterSymbol(ch);\n if (tok != INVALID) {\n return new Token(std::string({ch}), tok, TOKENS[tok].precedance_, pos);\n } else \/\/ oops! something went wrong, token is invalid!\n return new Token(std::string({ch}), INVALID, 0, pos);\n }\n\n \/\/ finally reached at the end of the given string\n return new Token(std::string({ch}), EOS, -1, pos);\n}\n\nvoid Lexer::StripComments(char &ch) { \/\/ skips all the comments from the string\n char last = '\\0';\n \/\/ skip the comments - single line comment\n if (ch != EOF && (ch == '\/' && LookAhead() == '\/')) {\n ch = NextCharacter();\n while (ch != '\\n' || ch == EOF)\n ch = NextCharacter();\n ch = NextCharacter();\n }\n\n \/\/ multiline comment, \/* *\/ type\n if (ch != EOF && (ch == '\/' && LookAhead() == '*')) {\n last = ch;\n ch = NextCharacter();\n while (ch != EOF && !(last == '*' && ch == '\/')) {\n last = ch;\n ch = NextCharacter();\n }\n ch = NextCharacter();\n }\n\n while (ch != EOF && (ch == ' ' || ch == '\\n' || ch == '\\t'))\n ch = NextCharacter();\n}\n\nvoid Lexer::GoBack() { \/\/ go back one character back\n --seek_;\n if (position_.col_ - 1 < 0) { \/\/ we don't want our col_ to be negative\n position_.row_--; \/\/ needed\n position_.col_ = lastColNumber_;\n } else { \/\/ okay, so simply decrement col_ member\n position_.col_--;\n }\n}\n\nchar Lexer::NextCharacter() { \/\/ returns the next character from the string\n if (seek_ <= end_) { \/\/ if eos_ flag has not been set\n char ch = code_[seek_++];\n if (ch == '\\0') { \/\/ if we are not processing EOF file character\n ch = EOF;\n eos_ = true;\n }\n if (ch == '\\n') { \/\/ change the position\n position_.row_++;\n lastColNumber_ = position_.col_;\n position_.col_ = 0;\n } else {\n position_.col_++;\n }\n return ch;\n }\n return EOF;\n}\n\nToken *Lexer::Characterize(char ch,\n Position &pos)\n{\n std::string buffer;\n if (isdigit(ch))\n return ParseNumber(ch, pos);\n\n if (isalpha(ch) || ch == '_' || ch == '$')\n return ParseIdentifierOrKeyWord(ch, pos);\n\n \/\/ if none of both then we have to return a invalid token\n return new Token(std::string(\"\"), INVALID, -1, pos);\n}\n\nToken *\nLexer::ParseNumber(char ch,\n Position &pos) { \/\/ parses the number from the current position\n std::string buffer; \/\/ buffer to store the parsed number\n while (isdigit(ch)) {\n buffer += ch;\n ch = NextCharacter();\n }\n \/\/ possible floating point number\n if (ch == '.' || ch == 'e' || ch == 'E') {\n buffer += ch;\n ch = NextCharacter();\n while (isdigit(ch)) {\n buffer += ch;\n ch = NextCharacter();\n }\n }\n \/\/ we've gone one character ahead, so go back\n GoBack();\n\n return new Token(buffer, DIGIT, -1, pos);\n}\n\nToken *Lexer::ParseIdentifierOrKeyWord(\n char ch,\n Position &\n pos) { \/\/ parses the identifier or a keyword from the current position\n std::string buffer;\n \/\/ possibly it is an identifier\n while (isalnum(ch) || ch == '_' || ch == '$') {\n buffer += ch;\n ch = NextCharacter();\n }\n \/\/ again went a character ahead\n GoBack();\n \/\/ check for KeyWord\n if (buffer[0] != '_' || buffer[0] != '$') {\n for (int i = LET; i <= RET; i++)\n if (buffer[0] == TOKENS[i].value_[0] && buffer == TOKENS[i].value_)\n return new Token(buffer, i, 0, pos);\n }\n return new Token(buffer, IDENT, -1, pos);\n}\n\n\/\/ although not required because of no use\nToken *Lexer::ParseStringLiteral(\n char ch, Position &pos) { \/\/ parses the string literal from the string\n std::string str = \"\";\n if (ch == '\"') { \/\/ string surrounded by \"\n ch = NextCharacter();\n while (ch != '\"') {\n str += ch;\n ch = NextCharacter();\n }\n } else if (ch == '\\'') { \/\/ string surrounded by '\n ch = NextCharacter();\n while (ch != '\\'') {\n str += ch;\n ch = NextCharacter();\n }\n }\n return new Token(str, STRING, -1, pos);\n}\n\nchar parsehex(char ch) {\n if (ch >= '0' && ch <= '9')\n return ch - '0';\n else if ((ch >= 'a' && ch <= 'f')) {\n return 10 + ch - 'a';\n } else if (ch >= 'A' && ch <= 'F') {\n return 10 + ch - 'A';\n }\n throw std::runtime_error(\"wrong hexadecimal digits\");\n}\n\nchar parseoct(char ch) {\n if (ch >= '0' && ch <= '8')\n return ch - '0';\n throw std::runtime_error(\"wrong octal digits\");\n}\n\nchar escape_code(std::string str) {\n if (str[0] != '\\\\')\n return str[0];\n if (str[1] == 'x') {\n char ret = 0;\n ret |= parsehex(str[2]);\n ret <<= 4;\n ret |= parsehex(str[3]);\n return ret;\n } else if (str[1] == 'n')\n return '\\n';\n else if (str[1] == 'b')\n return '\\b';\n else if (str[1] == 'r')\n return '\\r';\n else if (str[1] == 'a')\n return '\\a';\n else if (str[1] == 't')\n return '\\t';\n else if (str[1] == '\"')\n return '\"';\n else if (str[1] == '\\'')\n return '\\'';\n else throw std::runtime_error(\"unknown escape code\");\n}\n\n\/\/ this function should be used instead of above function\n\/\/ when we found a token of \" or ' that means we are about\n\/\/ to parse the string from the current position\nstd::string Lexer::GetStringLiteral() { \/\/ returns all the string until it finds \"\n\n \/\/ create a buffer\n std::string str = \"\";\n char ch = NextCharacter();\n while (ch != EOF && (ch != '\"' && ch != '\\'')) {\n if (ch == '\\\\') {\n \/\/ a possible escape code\n std::string tmp = \"\";\n tmp += ch;\n ch = NextCharacter();\n tmp += ch;\n if (ch == 'x') {\n ch = NextCharacter();\n tmp += ch;\n ch = NextCharacter();\n tmp += ch;\n }\n ch = escape_code(tmp);\n }\n str += ch; \/\/ fill the buffer\n ch = NextCharacter();\n }\n return str;\n}\n\nTokenType Lexer::OneCharacterSymbol(\n char ch) { \/\/ returns the type of token from the given symbol\n switch (ch) {\n case '(':\n return LPAR;\n case ')':\n return RPAR;\n case '{':\n return LBRACE;\n case '}':\n return RBRACE;\n case '[':\n return LSQB;\n case ']':\n return RSQB;\n case ':':\n return COLON;\n case ';':\n return SCOLON;\n case '\"':\n case '\\'':\n return STRING;\n case '.':\n return DOT;\n case ',':\n return COMMA;\n case '?':\n return CONDITION;\n case '+':\n return PLUS;\n case '-':\n return MINUS;\n case '\/':\n return DIV;\n case '*':\n return MUL;\n case '%':\n return MOD;\n case '>':\n return GT;\n case '<':\n return LT;\n case '=':\n return ASSIGN;\n case '^':\n return XOR;\n case '|':\n return BOR;\n case '&':\n return BAND;\n case '!':\n return NOT;\n case '~':\n return BNOT;\n default:\n return INVALID;\n }\n}\n\nTokenType\nLexer::TwoCharacterSymbol(char ch1,\n char ch2) { \/\/ returns the type of symbol of two characters\n switch (ch2) {\n case '=':\n switch (ch1) {\n case '+':\n return PLUSEQ;\n case '-':\n return MINUSEQ;\n case '*':\n return MULEQ;\n case '\/':\n return DIVEQ;\n case '%':\n return MODEQ;\n case '^':\n return XOREQ;\n case '&':\n return BANDEQ;\n case '|':\n return BOREQ;\n case '>':\n return GTE;\n case '<':\n return LTE;\n case '=':\n return EQUAL;\n case '!':\n return NOTEQ;\n }\n return INVALID;\n case '|':\n if (ch1 == '|')\n return OR;\n return INVALID;\n case '&':\n if (ch1 == '&')\n return AND;\n return INVALID;\n case '+':\n if (ch1 == '+')\n return INC;\n return INVALID;\n case '-':\n if (ch1 == '-')\n return DEC;\n return INVALID;\n case '<':\n if (ch1 == '<')\n return SHL;\n return INVALID;\n case '>':\n if (ch1 == '>')\n return SHR;\n default:\n return INVALID;\n }\n}\n\nbool Lexer::IsFile() const { return file_; }\nstd::string Lexer::GetFileName() { return file_name_; }\n\nTokenType Lexer::ThreeCharacterSymbol(\n char ch1, char ch2,\n char ch3) { \/\/ returns the type of symbol of three characters\n switch (ch3) {\n case '=':\n if (ch1 == '>' && ch2 == '>')\n return SHREQ;\n if (ch1 == '<' && ch2 == '<')\n return SHLEQ;\n default:\n return INVALID;\n }\n}\n\nvoid Lexer::PutBack(Token *tok) { \/\/ put in the buffer for one token lookahead\n \/\/ required by parser\n buffer_.push_back(tok);\n}\n\n\/\/ move to next token\nvoid Lexer::advance()\n{\n tok_ = NextToken();\n}\n\ndouble Lexer::GetNumber()\n{\n double result = 0.0;\n try {\n result = std::stod(tok_->GetValue());\n } catch (std::exception &e) {\n std::cerr << e.what() << std::endl;\n }\n\n return result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: cdouthdl.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 08:23:19 $\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 _XMLOFF_PROPERTYHANDLER_CROSSEDOUTTYPES_HXX\n#include <cdouthdl.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \"xmltoken.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include \"xmluconv.hxx\"\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_FONTSTRIKEOUT_HPP\n#include <com\/sun\/star\/awt\/FontStrikeout.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include <com\/sun\/star\/uno\/Any.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLEMENT_HXX\n#include \"xmlelement.hxx\"\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::awt;\nusing namespace ::xmloff::token;\n\nSvXMLEnumMapEntry pXML_CrossedoutType_Enum[] =\n{\n { XML_NONE, FontStrikeout::NONE },\n { XML_SINGLE, FontStrikeout::SINGLE },\n { XML_DOUBLE, FontStrikeout::DOUBLE },\n { XML_SINGLE, FontStrikeout::BOLD },\n { XML_SINGLE, FontStrikeout::SLASH },\n { XML_SINGLE, FontStrikeout::X },\n { XML_TOKEN_INVALID, 0 }\n};\n\nSvXMLEnumMapEntry pXML_CrossedoutStyle_Enum[] =\n{\n { XML_NONE, FontStrikeout::NONE },\n { XML_SOLID, FontStrikeout::SINGLE },\n { XML_SOLID, FontStrikeout::DOUBLE },\n { XML_SOLID, FontStrikeout::BOLD },\n { XML_SOLID, FontStrikeout::SLASH },\n { XML_SOLID, FontStrikeout::X },\n { XML_DOTTED, FontStrikeout::SINGLE },\n { XML_DASH, FontStrikeout::SINGLE },\n { XML_LONG_DASH, FontStrikeout::SINGLE },\n { XML_DOT_DASH, FontStrikeout::SINGLE },\n { XML_DOT_DOT_DASH, FontStrikeout::SINGLE },\n { XML_WAVE, FontStrikeout::SINGLE },\n { XML_TOKEN_INVALID, 0 }\n};\n\nSvXMLEnumMapEntry pXML_CrossedoutWidth_Enum[] =\n{\n { XML_AUTO, FontStrikeout::NONE },\n { XML_AUTO, FontStrikeout::SINGLE },\n { XML_AUTO, FontStrikeout::DOUBLE },\n { XML_BOLD, FontStrikeout::BOLD },\n { XML_AUTO, FontStrikeout::SLASH },\n { XML_AUTO, FontStrikeout::X },\n { XML_THIN, FontStrikeout::NONE },\n { XML_MEDIUM, FontStrikeout::NONE },\n { XML_THICK, FontStrikeout::NONE },\n { XML_TOKEN_INVALID, 0 }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLCrossedOutTypePropHdl\n\/\/\n\nXMLCrossedOutTypePropHdl::~XMLCrossedOutTypePropHdl()\n{\n \/\/ nothing to do\n}\n\nsal_Bool XMLCrossedOutTypePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 eNewStrikeout;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,\n pXML_CrossedoutType_Enum ) ) )\n {\n \/\/ multi property: style and width might be set already.\n \/\/ If the old value is NONE, the new is used unchanged.\n sal_Int16 eStrikeout;\n if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )\n {\n switch( eNewStrikeout )\n {\n case FontStrikeout::NONE:\n case FontStrikeout::SINGLE:\n \/\/ keep existing line style\n eNewStrikeout = eStrikeout;\n break;\n case FontStrikeout::DOUBLE:\n \/\/ A double line style has priority over a solid or a bold\n \/\/ line style,\n \/\/ but not about any other line style\n switch( eStrikeout )\n {\n case FontStrikeout::SINGLE:\n case FontStrikeout::BOLD:\n break;\n default:\n \/\/ If a double line style is not supported for the existing\n \/\/ value, keep the new one\n eNewStrikeout = eStrikeout;\n break;\n }\n break;\n default:\n OSL_ENSURE( bRet, \"unexpected line type value\" );\n break;\n }\n if( eNewStrikeout != eStrikeout )\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n else\n {\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n }\n\n return bRet;\n}\n\nsal_Bool XMLCrossedOutTypePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nValue;\n OUStringBuffer aOut;\n\n if( (rValue >>= nValue) && FontStrikeout::DOUBLE==nValue )\n {\n if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue, pXML_CrossedoutType_Enum ) ) )\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLCrossedOutStylePropHdl\n\/\/\n\nXMLCrossedOutStylePropHdl::~XMLCrossedOutStylePropHdl()\n{\n \/\/ nothing to do\n}\n\nsal_Bool XMLCrossedOutStylePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 eNewStrikeout;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,\n pXML_CrossedoutStyle_Enum ) ) )\n {\n \/\/ multi property: style and width might be set already.\n \/\/ If the old value is NONE, the new is used unchanged.\n sal_Int16 eStrikeout;\n if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )\n {\n \/\/ one NONE a SINGLE are possible new values. For both, the\n \/\/ existing value is kept.\n }\n else\n {\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n }\n\n return bRet;\n}\n\nsal_Bool XMLCrossedOutStylePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nValue;\n OUStringBuffer aOut;\n\n if( rValue >>= nValue )\n {\n if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue,\n pXML_CrossedoutStyle_Enum ) ) )\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLCrossedOutWidthPropHdl\n\/\/\n\nXMLCrossedOutWidthPropHdl::~XMLCrossedOutWidthPropHdl()\n{\n \/\/ nothing to do\n}\n\nsal_Bool XMLCrossedOutWidthPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 eNewStrikeout;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,\n pXML_CrossedoutWidth_Enum ) ) )\n {\n \/\/ multi property: style and width might be set already.\n \/\/ If the old value is NONE, the new is used unchanged.\n sal_Int16 eStrikeout;\n if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )\n {\n switch( eNewStrikeout )\n {\n case FontStrikeout::NONE:\n \/\/ keep existing line style\n eNewStrikeout = eStrikeout;\n break;\n case FontStrikeout::BOLD:\n switch( eStrikeout )\n {\n case FontStrikeout::SINGLE:\n break;\n default:\n \/\/ If a double line style is not supported for the existing\n \/\/ value, keep the new one\n eNewStrikeout = eStrikeout;\n break;\n }\n default:\n OSL_ENSURE( bRet, \"unexpected line type value\" );\n break;\n }\n if( eNewStrikeout != eStrikeout )\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n else\n {\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n }\n\n return bRet;\n}\n\nsal_Bool XMLCrossedOutWidthPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nValue;\n OUStringBuffer aOut;\n\n if( (rValue >>= nValue) && (FontStrikeout::BOLD == nValue) )\n {\n if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue,\n pXML_CrossedoutWidth_Enum ) ) )\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLCrossedOutTextPropHdl\n\/\/\n\nXMLCrossedOutTextPropHdl::~XMLCrossedOutTextPropHdl()\n{\n \/\/ nothing to do\n}\n\nsal_Bool XMLCrossedOutTextPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n\n if( rStrImpValue.getLength() )\n {\n sal_Int16 eStrikeout = ('\/' == rStrImpValue[0]\n ? FontStrikeout::SLASH\n : FontStrikeout::X);\n rValue <<= (sal_Int16)eStrikeout;\n bRet = sal_True;\n }\n\n return bRet;\n}\n\nsal_Bool XMLCrossedOutTextPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nValue;\n\n if( (rValue >>= nValue) &&\n (FontStrikeout::SLASH == nValue || FontStrikeout::X == nValue) )\n {\n rStrExpValue = OUString::valueOf(\n static_cast< sal_Unicode>( FontStrikeout::SLASH == nValue ? '\/'\n : 'X' ) );\n bRet = sal_True;\n }\n\n return bRet;\n}\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.298); FILE MERGED 2005\/09\/05 14:39:22 rt 1.4.298.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cdouthdl.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 14:38:15 $\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 _XMLOFF_PROPERTYHANDLER_CROSSEDOUTTYPES_HXX\n#include <cdouthdl.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \"xmltoken.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include \"xmluconv.hxx\"\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_FONTSTRIKEOUT_HPP\n#include <com\/sun\/star\/awt\/FontStrikeout.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include <com\/sun\/star\/uno\/Any.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLEMENT_HXX\n#include \"xmlelement.hxx\"\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::awt;\nusing namespace ::xmloff::token;\n\nSvXMLEnumMapEntry pXML_CrossedoutType_Enum[] =\n{\n { XML_NONE, FontStrikeout::NONE },\n { XML_SINGLE, FontStrikeout::SINGLE },\n { XML_DOUBLE, FontStrikeout::DOUBLE },\n { XML_SINGLE, FontStrikeout::BOLD },\n { XML_SINGLE, FontStrikeout::SLASH },\n { XML_SINGLE, FontStrikeout::X },\n { XML_TOKEN_INVALID, 0 }\n};\n\nSvXMLEnumMapEntry pXML_CrossedoutStyle_Enum[] =\n{\n { XML_NONE, FontStrikeout::NONE },\n { XML_SOLID, FontStrikeout::SINGLE },\n { XML_SOLID, FontStrikeout::DOUBLE },\n { XML_SOLID, FontStrikeout::BOLD },\n { XML_SOLID, FontStrikeout::SLASH },\n { XML_SOLID, FontStrikeout::X },\n { XML_DOTTED, FontStrikeout::SINGLE },\n { XML_DASH, FontStrikeout::SINGLE },\n { XML_LONG_DASH, FontStrikeout::SINGLE },\n { XML_DOT_DASH, FontStrikeout::SINGLE },\n { XML_DOT_DOT_DASH, FontStrikeout::SINGLE },\n { XML_WAVE, FontStrikeout::SINGLE },\n { XML_TOKEN_INVALID, 0 }\n};\n\nSvXMLEnumMapEntry pXML_CrossedoutWidth_Enum[] =\n{\n { XML_AUTO, FontStrikeout::NONE },\n { XML_AUTO, FontStrikeout::SINGLE },\n { XML_AUTO, FontStrikeout::DOUBLE },\n { XML_BOLD, FontStrikeout::BOLD },\n { XML_AUTO, FontStrikeout::SLASH },\n { XML_AUTO, FontStrikeout::X },\n { XML_THIN, FontStrikeout::NONE },\n { XML_MEDIUM, FontStrikeout::NONE },\n { XML_THICK, FontStrikeout::NONE },\n { XML_TOKEN_INVALID, 0 }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLCrossedOutTypePropHdl\n\/\/\n\nXMLCrossedOutTypePropHdl::~XMLCrossedOutTypePropHdl()\n{\n \/\/ nothing to do\n}\n\nsal_Bool XMLCrossedOutTypePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 eNewStrikeout;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,\n pXML_CrossedoutType_Enum ) ) )\n {\n \/\/ multi property: style and width might be set already.\n \/\/ If the old value is NONE, the new is used unchanged.\n sal_Int16 eStrikeout;\n if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )\n {\n switch( eNewStrikeout )\n {\n case FontStrikeout::NONE:\n case FontStrikeout::SINGLE:\n \/\/ keep existing line style\n eNewStrikeout = eStrikeout;\n break;\n case FontStrikeout::DOUBLE:\n \/\/ A double line style has priority over a solid or a bold\n \/\/ line style,\n \/\/ but not about any other line style\n switch( eStrikeout )\n {\n case FontStrikeout::SINGLE:\n case FontStrikeout::BOLD:\n break;\n default:\n \/\/ If a double line style is not supported for the existing\n \/\/ value, keep the new one\n eNewStrikeout = eStrikeout;\n break;\n }\n break;\n default:\n OSL_ENSURE( bRet, \"unexpected line type value\" );\n break;\n }\n if( eNewStrikeout != eStrikeout )\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n else\n {\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n }\n\n return bRet;\n}\n\nsal_Bool XMLCrossedOutTypePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nValue;\n OUStringBuffer aOut;\n\n if( (rValue >>= nValue) && FontStrikeout::DOUBLE==nValue )\n {\n if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue, pXML_CrossedoutType_Enum ) ) )\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLCrossedOutStylePropHdl\n\/\/\n\nXMLCrossedOutStylePropHdl::~XMLCrossedOutStylePropHdl()\n{\n \/\/ nothing to do\n}\n\nsal_Bool XMLCrossedOutStylePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 eNewStrikeout;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,\n pXML_CrossedoutStyle_Enum ) ) )\n {\n \/\/ multi property: style and width might be set already.\n \/\/ If the old value is NONE, the new is used unchanged.\n sal_Int16 eStrikeout;\n if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )\n {\n \/\/ one NONE a SINGLE are possible new values. For both, the\n \/\/ existing value is kept.\n }\n else\n {\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n }\n\n return bRet;\n}\n\nsal_Bool XMLCrossedOutStylePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nValue;\n OUStringBuffer aOut;\n\n if( rValue >>= nValue )\n {\n if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue,\n pXML_CrossedoutStyle_Enum ) ) )\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLCrossedOutWidthPropHdl\n\/\/\n\nXMLCrossedOutWidthPropHdl::~XMLCrossedOutWidthPropHdl()\n{\n \/\/ nothing to do\n}\n\nsal_Bool XMLCrossedOutWidthPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 eNewStrikeout;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,\n pXML_CrossedoutWidth_Enum ) ) )\n {\n \/\/ multi property: style and width might be set already.\n \/\/ If the old value is NONE, the new is used unchanged.\n sal_Int16 eStrikeout;\n if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )\n {\n switch( eNewStrikeout )\n {\n case FontStrikeout::NONE:\n \/\/ keep existing line style\n eNewStrikeout = eStrikeout;\n break;\n case FontStrikeout::BOLD:\n switch( eStrikeout )\n {\n case FontStrikeout::SINGLE:\n break;\n default:\n \/\/ If a double line style is not supported for the existing\n \/\/ value, keep the new one\n eNewStrikeout = eStrikeout;\n break;\n }\n default:\n OSL_ENSURE( bRet, \"unexpected line type value\" );\n break;\n }\n if( eNewStrikeout != eStrikeout )\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n else\n {\n rValue <<= (sal_Int16)eNewStrikeout;\n }\n }\n\n return bRet;\n}\n\nsal_Bool XMLCrossedOutWidthPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nValue;\n OUStringBuffer aOut;\n\n if( (rValue >>= nValue) && (FontStrikeout::BOLD == nValue) )\n {\n if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue,\n pXML_CrossedoutWidth_Enum ) ) )\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLCrossedOutTextPropHdl\n\/\/\n\nXMLCrossedOutTextPropHdl::~XMLCrossedOutTextPropHdl()\n{\n \/\/ nothing to do\n}\n\nsal_Bool XMLCrossedOutTextPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n\n if( rStrImpValue.getLength() )\n {\n sal_Int16 eStrikeout = ('\/' == rStrImpValue[0]\n ? FontStrikeout::SLASH\n : FontStrikeout::X);\n rValue <<= (sal_Int16)eStrikeout;\n bRet = sal_True;\n }\n\n return bRet;\n}\n\nsal_Bool XMLCrossedOutTextPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nValue;\n\n if( (rValue >>= nValue) &&\n (FontStrikeout::SLASH == nValue || FontStrikeout::X == nValue) )\n {\n rStrExpValue = OUString::valueOf(\n static_cast< sal_Unicode>( FontStrikeout::SLASH == nValue ? '\/'\n : 'X' ) );\n bRet = sal_True;\n }\n\n return bRet;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Filename: collisionHandlerQueue.cxx\n\/\/ Created by: drose (16Mar02)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/www.panda3d.org\/license.txt .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d@yahoogroups.com .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"collisionHandlerQueue.h\"\n#include \"config_collide.h\"\n\nTypeHandle CollisionHandlerQueue::_type_handle;\n\n\/\/ This class is used in sort_entries(), below.\nclass CollisionEntrySorter {\npublic:\n CollisionEntrySorter(CollisionEntry *entry) {\n _entry = entry;\n LVector3f vec =\n entry->get_from_intersection_point() -\n entry->get_from()->get_collision_origin();\n _dist2 = vec.length_squared();\n }\n bool operator < (const CollisionEntrySorter &other) const {\n return _dist2 < other._dist2;\n }\n\n CollisionEntry *_entry;\n float _dist2;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::Constructor\n\/\/ Access: Public\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCollisionHandlerQueue::\nCollisionHandlerQueue() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::begin_group\n\/\/ Access: Public, Virtual\n\/\/ Description: Will be called by the CollisionTraverser before a new\n\/\/ traversal is begun. It instructs the handler to\n\/\/ reset itself in preparation for a number of\n\/\/ CollisionEntries to be sent.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionHandlerQueue::\nbegin_group() {\n _entries.clear();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::add_entry\n\/\/ Access: Public, Virtual\n\/\/ Description: Called between a begin_group() .. end_group()\n\/\/ sequence for each collision that is detected.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionHandlerQueue::\nadd_entry(CollisionEntry *entry) {\n nassertv(entry != (CollisionEntry *)NULL);\n _entries.push_back(entry);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::sort_entries\n\/\/ Access: Public\n\/\/ Description: Sorts all the detected collisions front-to-back by\n\/\/ from_intersection_point() so that those intersection\n\/\/ points closest to the collider's origin (e.g., the\n\/\/ center of the CollisionSphere, or the point_a of a\n\/\/ CollisionSegment) appear first.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionHandlerQueue::\nsort_entries() {\n \/\/ Build up a temporary vector of entries so we can sort the\n \/\/ pointers. This uses the class defined above.\n typedef pvector<CollisionEntrySorter> Sorter;\n Sorter sorter;\n sorter.reserve(_entries.size());\n\n Entries::const_iterator ei;\n for (ei = _entries.begin(); ei != _entries.end(); ++ei) {\n sorter.push_back(CollisionEntrySorter(*ei));\n }\n\n sort(sorter.begin(), sorter.end());\n nassertv(sorter.size() == _entries.size());\n\n \/\/ Now that they're sorted, get them back. We do this in two steps,\n \/\/ building up a temporary vector first, so we don't accidentally\n \/\/ delete all the entries when the pointers go away.\n Entries sorted_entries;\n sorted_entries.reserve(sorter.size());\n Sorter::const_iterator si;\n for (si = sorter.begin(); si != sorter.end(); ++si) {\n sorted_entries.push_back((*si)._entry);\n }\n\n _entries.swap(sorted_entries);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::clear_entries\n\/\/ Access: Public\n\/\/ Description: Removes all the entries from the queue.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionHandlerQueue::\nclear_entries() {\n _entries.clear();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::get_num_entries\n\/\/ Access: Public\n\/\/ Description: Returns the number of CollisionEntries detected last\n\/\/ pass.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CollisionHandlerQueue::\nget_num_entries() const {\n return _entries.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::get_entry\n\/\/ Access: Public\n\/\/ Description: Returns the nth CollisionEntry detected last pass.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCollisionEntry *CollisionHandlerQueue::\nget_entry(int n) const {\n nassertr(n >= 0 && n < (int)_entries.size(), NULL);\n return _entries[n];\n}\n<commit_msg>use new interface<commit_after>\/\/ Filename: collisionHandlerQueue.cxx\n\/\/ Created by: drose (16Mar02)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/www.panda3d.org\/license.txt .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d@yahoogroups.com .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"collisionHandlerQueue.h\"\n#include \"config_collide.h\"\n\nTypeHandle CollisionHandlerQueue::_type_handle;\n\n\/\/ This class is used in sort_entries(), below.\nclass CollisionEntrySorter {\npublic:\n CollisionEntrySorter(CollisionEntry *entry) {\n _entry = entry;\n LVector3f vec =\n entry->get_surface_point(entry->get_from_node_path()) -\n entry->get_from()->get_collision_origin();\n _dist2 = vec.length_squared();\n }\n bool operator < (const CollisionEntrySorter &other) const {\n return _dist2 < other._dist2;\n }\n\n CollisionEntry *_entry;\n float _dist2;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::Constructor\n\/\/ Access: Public\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCollisionHandlerQueue::\nCollisionHandlerQueue() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::begin_group\n\/\/ Access: Public, Virtual\n\/\/ Description: Will be called by the CollisionTraverser before a new\n\/\/ traversal is begun. It instructs the handler to\n\/\/ reset itself in preparation for a number of\n\/\/ CollisionEntries to be sent.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionHandlerQueue::\nbegin_group() {\n _entries.clear();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::add_entry\n\/\/ Access: Public, Virtual\n\/\/ Description: Called between a begin_group() .. end_group()\n\/\/ sequence for each collision that is detected.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionHandlerQueue::\nadd_entry(CollisionEntry *entry) {\n nassertv(entry != (CollisionEntry *)NULL);\n _entries.push_back(entry);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::sort_entries\n\/\/ Access: Public\n\/\/ Description: Sorts all the detected collisions front-to-back by\n\/\/ from_intersection_point() so that those intersection\n\/\/ points closest to the collider's origin (e.g., the\n\/\/ center of the CollisionSphere, or the point_a of a\n\/\/ CollisionSegment) appear first.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionHandlerQueue::\nsort_entries() {\n \/\/ Build up a temporary vector of entries so we can sort the\n \/\/ pointers. This uses the class defined above.\n typedef pvector<CollisionEntrySorter> Sorter;\n Sorter sorter;\n sorter.reserve(_entries.size());\n\n Entries::const_iterator ei;\n for (ei = _entries.begin(); ei != _entries.end(); ++ei) {\n sorter.push_back(CollisionEntrySorter(*ei));\n }\n\n sort(sorter.begin(), sorter.end());\n nassertv(sorter.size() == _entries.size());\n\n \/\/ Now that they're sorted, get them back. We do this in two steps,\n \/\/ building up a temporary vector first, so we don't accidentally\n \/\/ delete all the entries when the pointers go away.\n Entries sorted_entries;\n sorted_entries.reserve(sorter.size());\n Sorter::const_iterator si;\n for (si = sorter.begin(); si != sorter.end(); ++si) {\n sorted_entries.push_back((*si)._entry);\n }\n\n _entries.swap(sorted_entries);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::clear_entries\n\/\/ Access: Public\n\/\/ Description: Removes all the entries from the queue.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionHandlerQueue::\nclear_entries() {\n _entries.clear();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::get_num_entries\n\/\/ Access: Public\n\/\/ Description: Returns the number of CollisionEntries detected last\n\/\/ pass.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CollisionHandlerQueue::\nget_num_entries() const {\n return _entries.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionHandlerQueue::get_entry\n\/\/ Access: Public\n\/\/ Description: Returns the nth CollisionEntry detected last pass.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCollisionEntry *CollisionHandlerQueue::\nget_entry(int n) const {\n nassertr(n >= 0 && n < (int)_entries.size(), NULL);\n return _entries[n];\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>cppcheck: redundantAssignment<commit_after><|endoftext|>"} {"text":"<commit_before>#define DEFINE_GLOBALS\n#include\"all_defines.hpp\"\n\n#ifndef single_threaded\n\tbool single_threaded;\n#endif\n\n#include\"symbols.hpp\"\n\nboost::scoped_ptr<SymbolsTable> symbols;\nSymbol* symbol_sym;\nSymbol* symbol_int;\nSymbol* symbol_char;\nSymbol* symbol_cons;\nSymbol* symbol_pid;\nSymbol* symbol_fn;\nSymbol* symbol_string;\nSymbol* symbol_unspecified;\nSymbol* symbol_num;\nSymbol* symbol_array;\nSymbol* symbol_table;\nSymbol* symbol_container;\n\nvoid initialize_globals(void) {\n\tsymbols.reset(new SymbolsTable());\n\tsymbol_sym = symbols->lookup(\"<hl>sym\");\n\tsymbol_sym = symbols->lookup(\"<hl>int\");\n\tsymbol_sym = symbols->lookup(\"<hl>char\");\n\tsymbol_cons = symbols->lookup(\"<hl>cons\");\n\tsymbol_pid = symbols->lookup(\"<hl>pid\");\n\tsymbol_fn = symbols->lookup(\"<hl>fn\");\n\tsymbol_string = symbols->lookup(\"<hl>string\");\n\tsymbol_unspecified = symbols->lookup(\"<hl>unpsecified\");\n\tsymbol_num = symbols->lookup(\"<hl>num\");\n\tsymbol_array = symbols->lookup(\"<hl>array\");\n\tsymbol_table = symbols->lookup(\"<hl>table\");\n\tsymbol_container = symbols->lookup(\"<hl>container\");\n}\n\n<commit_msg>src\/globals.cpp: Some rearrangement of code<commit_after>#define DEFINE_GLOBALS\n#include\"all_defines.hpp\"\n\n#ifndef single_threaded\n\tbool single_threaded;\n#endif\n\nclass Symbol;\n\nSymbol* symbol_sym;\nSymbol* symbol_int;\nSymbol* symbol_char;\nSymbol* symbol_cons;\nSymbol* symbol_pid;\nSymbol* symbol_fn;\nSymbol* symbol_string;\nSymbol* symbol_unspecified;\nSymbol* symbol_num;\nSymbol* symbol_array;\nSymbol* symbol_table;\nSymbol* symbol_container;\n\n#include\"symbols.hpp\"\n\nboost::scoped_ptr<SymbolsTable> symbols;\n\nvoid initialize_globals(void) {\n\tsymbols.reset(new SymbolsTable());\n\tsymbol_sym = symbols->lookup(\"<hl>sym\");\n\tsymbol_sym = symbols->lookup(\"<hl>int\");\n\tsymbol_sym = symbols->lookup(\"<hl>char\");\n\tsymbol_cons = symbols->lookup(\"<hl>cons\");\n\tsymbol_pid = symbols->lookup(\"<hl>pid\");\n\tsymbol_fn = symbols->lookup(\"<hl>fn\");\n\tsymbol_string = symbols->lookup(\"<hl>string\");\n\tsymbol_unspecified = symbols->lookup(\"<hl>unpsecified\");\n\tsymbol_num = symbols->lookup(\"<hl>num\");\n\tsymbol_array = symbols->lookup(\"<hl>array\");\n\tsymbol_table = symbols->lookup(\"<hl>table\");\n\tsymbol_container = symbols->lookup(\"<hl>container\");\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"adjacencyMatrix.h\"\n#include <vector>\nusing namespace std;\n\n\nadjacencyMatrix::adjacencyMatrix()\n{\n\/**\n * Constructor\n *\/\n max_id_=0;\n}\n\nbool adjacencyMatrix::Get(int id1, int id2){\n\/**\n * Gets the id of the edges connecting two nodes in the graph. Returns true if the edge exists, false otherwise.\n * \\param[in] id1 ID of the first node\n * \\param[in] id2 ID of the second node\n *\/\n int id1_s=max(id1,id2);\n int id2_s=min(id1,id2);\n\tint n=mat_.size();\n\tif( (id1_s>n-1) || (id2_s<0) ){\n return false;\n\t}else{\n int val=mat_.at(id1_s).at(id2_s);\n if (val==0){\n return false;\n } else {\n return true;\n }\n\t}\n}\n\nbool adjacencyMatrix::Get(int id1, int id2, int& ide){\n\/**\n * Gets the id of the edges connecting two nodes in the graph. Returns true if the edge exists, false otherwise.\n * \\param[in] id1 ID of the first node\n * \\param[in] id2 ID of the second node\n * \\param[out] ide edge ID, if it exists in the adjacency matrix\n *\/\n int id1_s=max(id1,id2);\n int id2_s=min(id1,id2);\n\tint n=mat_.size();\n\tif( (id1_s>n-1) || (id2_s<0) ){\n return false;\n\t}else{\n int val=mat_.at(id1_s).at(id2_s);\n if (val==0){\n return false;\n } else {\n if(id1>id2){\n ide=val;\n }else{\n ide=-val;\n }\n return true;\n }\n\t}\n}\n\nvoid resize(vector<vector<int> >& mat,int nNew){\n\/**\n * Enlarges the adjacency matrix.\n * \\param[in,out] mat matrix to be enlarged\n * \\param[in] New size of the matrix\n *\/\n int nOld=mat.size();\n int i;\n for(i=nOld;i<nNew;i++){\n vector<int> bottom(i,0);\n mat.push_back(bottom);\n }\n}\n\nint adjacencyMatrix::Set(int id1,int id2){\n\/**\n * Add new entry to the adjacency matrix and returns the edge ID. If the entry already exists, it returns the corresponding ID; otherwise, it increments the max ID and uses it.\n * If any of the imput argument is negative, it increments the max ID but returns 0.\n * \\param[in] id1 ID of the first node\n * \\param[in] id2 ID of the second node\n *\/\n int ide;\n if ( (id1<0) || (id2<0) ){ \/\/ Any negative input index\n max_id_++;\n ide=max_id_;\n } else { \/\/ Both positive\n if( !( Get(id1,id2,ide) ) ){ \/\/ If the entry already exists, it just gets the edge ID\n max_id_++;\n if(id1>id2){\n resize(mat_,id1+1);\n mat_.at(id1).at(id2)=max_id_;\n }else{\n resize(mat_,id2+1);\n mat_.at(id2).at(id1)=-max_id_;\n }\n ide=max_id_;\n }\n }\n\treturn ide;\n}\n\n\nint adjacencyMatrix::size(){\n\/**\n * Gets the size of the adjacency matrix.\n *\/\n return mat_.size();\n}\n\nadjacencyMatrix::~adjacencyMatrix()\n{\n\/**\n * Destructor\n *\/\n}\n<commit_msg>Allow self loops<commit_after>#include \"adjacencyMatrix.h\"\n#include <vector>\nusing namespace std;\n\n\nadjacencyMatrix::adjacencyMatrix()\n{\n\/**\n * Constructor\n *\/\n max_id_=0;\n}\n\nbool adjacencyMatrix::Get(int id1, int id2){\n\/**\n * Gets the id of the edges connecting two nodes in the graph. Returns true if the edge exists, false otherwise.\n * \\param[in] id1 ID of the first node\n * \\param[in] id2 ID of the second node\n *\/\n \tint id1_s=max(id1,id2);\n\tint id2_s=min(id1,id2);\n\tint n=mat_.size();\n\tif( (id1_s>n-1) || (id2_s<0) ){\n \treturn false;\n\t} else {\n \tint val=mat_.at(id1_s).at(id2_s);\n \tif (val==0){\n \t\treturn false;\n \t} else {\n \t\treturn true;\n \t}\n\t}\n}\n\nbool adjacencyMatrix::Get(int id1, int id2, int& ide){\n\/**\n * Gets the id of the edges connecting two nodes in the graph. Returns true if the edge exists, false otherwise.\n * \\param[in] id1 ID of the first node\n * \\param[in] id2 ID of the second node\n * \\param[out] ide edge ID, if it exists in the adjacency matrix\n *\/\n\tint id1_s=max(id1,id2);\n\tint id2_s=min(id1,id2);\n\tint n=mat_.size();\n\tif( (id1_s>n-1) || (id2_s<0) ){\n \treturn false;\n\t} else {\n\t\tint val=mat_.at(id1_s).at(id2_s);\n\t\tif (val==0){\n\t\t\treturn false;\n \t} else {\n\t\t\tif(id1>=id2){\n\t\t\t\tide=val;\n\t\t\t}else{\n\t\t\t\tide=-val;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n}\n\nvoid resize(vector<vector<int> >& mat,int nNew){\n\/**\n * Enlarges the adjacency matrix.\n * \\param[in,out] mat matrix to be enlarged\n * \\param[in] New size of the matrix\n *\/\n int nOld=mat.size();\n int i;\n for(i=nOld;i<nNew;i++){\n vector<int> bottom(i,0);\n mat.push_back(bottom);\n }\n}\n\nint adjacencyMatrix::Set(int id1,int id2){\n\/**\n * Add new entry to the adjacency matrix and returns the edge ID. If the entry already exists, it returns the corresponding ID; otherwise, it increments the max ID and uses it.\n * If any of the imput argument is negative, it increments the max ID but returns 0.\n * \\param[in] id1 ID of the first node\n * \\param[in] id2 ID of the second node\n *\/\n\tint ide;\n\tif ( (id1<0) || (id2<0) ){ \/\/ Any negative input index\n\t\tmax_id_++;\n\t\tide=max_id_;\n\t} else { \/\/ Both positive\n\t\tif( !( Get(id1,id2,ide) ) ){ \/\/ If the entry already exists, it just gets the edge ID\n\t\t\tmax_id_++;\n\t\t\tif(id1>=id2){\n\t\t\t\tresize(mat_,id1+1);\n\t\t\t\tmat_.at(id1).at(id2)=max_id_;\n\t\t\t} else {\n\t\t\t\tresize(mat_,id2+1);\n\t\t\t\tmat_.at(id2).at(id1)=-max_id_;\n\t\t\t}\n\t\t\tide=max_id_;\n\t\t}\n\t}\n\treturn ide;\n}\n\n\nint adjacencyMatrix::size(){\n\/**\n * Gets the size of the adjacency matrix.\n *\/\n return mat_.size();\n}\n\nadjacencyMatrix::~adjacencyMatrix()\n{\n\/**\n * Destructor\n *\/\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/imgproc.hpp\"\n\n#include \"cvui.h\"\n\n#define WINDOW_NAME\t\t\"CVUI Test\"\n\nint main(int argc, const char *argv[])\n{\n\tcv::Mat aFrame = cv::Mat(800, 600, CV_8UC3);\n\tbool aChecked = false;\n\tint aCount = 0;\n\n\tcv::namedWindow(WINDOW_NAME);\n\tcvui::init(WINDOW_NAME);\n\n\twhile (true) {\n\t\t\/\/ Fill the frame with a nice color\n\t\taFrame = cv::Scalar(49, 52, 49);\n\n\t\t\/\/ Check if ESC key was pressed\n\t\tif (cv::waitKey(10) == 27) {\n\t\t\tbreak;\n\t\t}\n\n\t\tcvui::text(aFrame, 50, 30, \"Hey there!\", 0.4);\n\n\t\tif (cvui::button(aFrame, 50, 50, \"Button\")) {\n\t\t\tstd::cout << \"Button clicked!\" << std::endl;\n\t\t}\n\n\t\tcvui::checkbox(aFrame, 50, 100, \"Checkbox test\", &aChecked);\n\t\tcvui::window(aFrame, 50, 150, 120, 100, \"My Window\");\n\t\tcvui::counter(aFrame, 50, 280, &aCount);\n\n\t\tcvui::update();\n\n\t\t\/\/ Show everything on the screen\n\t\timshow(WINDOW_NAME, aFrame);\n\t}\n\n\treturn 0;\n}<commit_msg>Add a bit of comments<commit_after>\/*\nThis is a demo application to showcase the UI components of cvui.\n\nCopyright (c) 2016 Fernando Bevilacqua <dovyski@gmail.com>\nLicensed under the MIT license.\n*\/\n\n#include <iostream>\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/imgproc.hpp\"\n\n#include \"cvui.h\"\n\n#define WINDOW_NAME\t\t\"CVUI Test\"\n\nint main(int argc, const char *argv[])\n{\n\tcv::Mat frame = cv::Mat(250, 600, CV_8UC3);\n\tbool checked = false;\n\tbool checked2 = true;\n\tint count = 0;\n\n\t\/\/ Init a OpenCV window and tell cvui to use it.\n\t\/\/ If cv::namedWindow() is not used, mouse events will\n\t\/\/ not be captured by cvui.\n\tcv::namedWindow(WINDOW_NAME);\n\tcvui::init(WINDOW_NAME);\n\n\twhile (true) {\n\t\t\/\/ Fill the frame with a nice color\n\t\tframe = cv::Scalar(49, 52, 49);\n\n\t\t\/\/ Check if ESC key was pressed\n\t\tif (cv::waitKey(10) == 27) {\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Show some pieces of text. You can also specify the size of the\n\t\t\/\/ text and its color (using hex 0xRRGGBB CSS-like style).\n\t\tcvui::text(frame, 50, 30, \"Hey there!\");\n\t\tcvui::text(frame, 200, 30, \"Use hex 0xRRGGBB colors easily\", 0.4, 0xff0000);\n\n\t\t\/\/ Buttons will return true if they were clicked, which makes\n\t\t\/\/ handling clicks a breeze.\n\t\tif (cvui::button(frame, 50, 50, \"Button\")) {\n\t\t\tstd::cout << \"Button clicked!\" << std::endl;\n\t\t}\n\n\t\t\/\/ If you do not specify the button width\/height, the size will be\n\t\t\/\/ automatically adjusted to properly house the label.\n\t\tcvui::button(frame, 200, 50, \"Button with large label\");\n\t\t\/\/ You can tell the width and height you want\n\t\tcvui::button(frame, 410, 50, 15, 15, \"x\");\n\n\t\t\/\/ Window components are useful to create HUDs and similars. At the\n\t\t\/\/ moment, there is no implementation to constraint content within a\n\t\t\/\/ a window.\n\t\tcvui::window(frame, 50, 100, 120, 100, \"Window\");\n\t\t\n\t\t\/\/ The counter component can be used to alter int variables. Use\n\t\t\/\/ the 4th parameter of the function to point it to the variable\n\t\t\/\/ to be changed.\n\t\tcvui::counter(frame, 200, 100, &count);\n\t\t\n\t\t\/\/ Checkboxes also accept a pointer to a variable that controls\n\t\t\/\/ the state of the checkbox (checked or not). cvui::checkbox() will\n\t\t\/\/ automatically update the value of the boolean after all\n\t\t\/\/ interactions, but you can also change it by yourself. Just\n\t\t\/\/ do \"checked = true\" somewhere and the checkbox will change\n\t\t\/\/ its appearance.\n\t\tcvui::checkbox(frame, 200, 150, \"Checkbox\", &checked);\n\t\tcvui::checkbox(frame, 200, 180, \"A checked checkbox\", &checked2);\n\n\t\t\/\/ This function must be called *AFTER* all UI components. It does\n\t\t\/\/ all the behind the scenes magic to handle mouse clicks, etc.\n\t\tcvui::update();\n\n\t\t\/\/ Show everything on the screen\n\t\tcv::imshow(WINDOW_NAME, frame);\n\t}\n\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include \"AgentProtocol.h\"\n#include \"NetworkManager.hh\"\n#include \"IConnector.hh\"\n#include \"TCPConnector.h\"\n#include \"UDPConnector.hh\"\n\n\nconst std::string AgentProtocol::TCP_KEY = \"TCP\";\nconst std::string AgentProtocol::UDP_KEY = \"UDP\";\n\n\nAgentProtocol::AgentProtocol(Network::NetworkManager &networkAdapter)\n : AProtocol(networkAdapter)\n{\n Network::IConnector *connector = new Network::TCPConnector();\n _networkAdapter.setConnector(AgentProtocol::TCP_KEY, connector);\n _networkAdapter.setConnector(AgentProtocol::UDP_KEY, new Network::UDPConnector());\n}\n\nAgentProtocol::~AgentProtocol()\n{\n}\n\nvoid AgentProtocol::setAgent(IAgent *agent, Slam &slam)\n{\n this->registerCallback(\"SetGoalPosEvent\", [agent](pcl::PointXYZ pos) {dynamic_cast<Agent *>(agent)->setGoalPos(pos);});\n this->registerCallback(\"SetPosEvent\", [agent](pcl::PointXYZ pos) {agent->setPos(pos);});\n agent->registerCallback(\"SendPacketEvent\", [this](IAgent * agent) {sendPacketEvent(agent);});\n agent->registerCallback(\"SendStatusEvent\", [this](std::string const & status) {sendStatusEvent(status);});\n \/\/\/@todo: Register in the factory (process data)\n agent->registerCallback(\"SendCloudEvent\", [this](pcl::PointCloud<pcl::PointXYZ> const & cloud) {sendCloudEvent(cloud);});\n slam.registerCallback(\"SendNewLandmarkEvent\", [this](std::vector<Landmarks::Landmark *> &nl) {sendNewLandmarkEvent(nl);});\n}\n\nvoid AgentProtocol::sendCloudEvent(pcl::PointCloud<pcl::PointXYZ> const &cloud)\n{\n for (size_t i = 0; i < cloud.points.size (); ++i)\n std::cout << \" \" << cloud.points[i].x\n << \" \" << cloud.points[i].y\n << \" \" << cloud.points[i].z << std::endl;\n\n _factory.processData(cloud);\n int i = 0;\n bool is_ready = true;\n std::string toSend = \"\";\n while (_factory.isFullChunkReady())\n {\n if (is_ready) {\n ++i;\n toSend = _factory.getChunk();\n }\n is_ready = _networkAdapter.send(toSend, AgentProtocol::UDP_KEY);\n usleep(100);\n }\n std::cerr << \"Send cloud event \" << i << std::endl;\n\n Json::Value reply;\n\n reply[\"data\"][\"exit\"] = 0;\n reply[\"status\"][\"code\"] = 0;\n reply[\"status\"][\"message\"] = \"ok\";\n this->sendDataTcp(reply);\n exit(1);\n}\n\nvoid AgentProtocol::sendNewLandmarkEvent(std::vector<Landmarks::Landmark *> &nl)\n{\n _factory.processData(nl);\n while (_factory.isFullChunkReady())\n {\n std::string toSend = _factory.getChunk();\n _networkAdapter.send(toSend, AgentProtocol::UDP_KEY);\n }\n}\n\nvoid AgentProtocol::sendDataTcp(Json::Value &root)\n{\n _outPacket.clear();\n std::string buffer = root.toStyledString();\n \/\/ buffer.erase(std::remove_if(buffer.begin(),\n \/\/ buffer.end(),\n \/\/ [](char x){return std::isspace(x);}),\n \/\/ buffer.end());\n _outPacket.append(buffer.c_str(), buffer.size());\n \/\/ std::cout << \"data sent == \" << buffer << std::endl;\n _networkAdapter.send(_outPacket, AgentProtocol::TCP_KEY);\n \/\/ std::cout << \"in send data:: magic = \" << (char)_outPacket.getPacketHeader().magic << \" -- packetsize == \" << _outPacket.getPacketHeader().packetSize << \" -- version == \" << _outPacket.getPacketHeader().version << \" -- header size == \" << _outPacket.getPacketHeader().headerSize << std::endl;\n _outPacket.clear();\n}\n\/**\n * @brief Function called when a connector is connected to the server\n * @todo: Change the function to get in param the key of the connector (maybe)\n *\/\nvoid AgentProtocol::connectedEvent(IAgent *agent)\n{\n \/\/ std::cout << \"connected event \" << std::endl;\n Json::Value reply;\n\n reply[\"data\"][\"name\"] = agent->name();\n reply[\"data\"][\"position\"][\"x\"] = agent->getPos().x;\n reply[\"data\"][\"position\"][\"y\"] = agent->getPos().y;\n reply[\"data\"][\"position\"][\"z\"] = agent->getPos().z;\n reply[\"status\"][\"code\"] = 0;\n reply[\"status\"][\"message\"] = \"ok\";\n this->sendDataTcp(reply);\n}\n\nvoid AgentProtocol::sendStatusEvent(std::string const &status)\n{\n Json::Value root;\n\n std::cout << \"Send status event \" << std::endl;\n root[\"status\"][\"code\"] = 0;\n root[\"status\"][\"message\"] = \"ok\";\n root[\"data\"][\"state\"] = status;\n this->sendDataTcp(root);\n}\n\nvoid AgentProtocol::sendPacketEvent(IAgent *agent)\n{\n Json::Value root;\n\n std::cout << \"Send movement event \" << std::endl;\n root[\"data\"][\"position\"][\"x\"] = agent->getPos().x;\n root[\"data\"][\"position\"][\"y\"] = agent->getPos().y;\n root[\"data\"][\"position\"][\"z\"] = agent->getPos().z;\n root[\"data\"][\"battery\"] = (agent->getBattery() * 100) \/ Agent::DEFAULTBATTERY;\n root[\"status\"][\"code\"] = 0;\n root[\"status\"][\"message\"] = \"ok\";\n this->sendDataTcp(root);\n}\n\nvoid PrintJSONValue( const Json::Value &val )\n{\n if ( val.isString() ) {\n printf( \"string(%s)\", val.asString().c_str() );\n } else if ( val.isBool() ) {\n printf( \"bool(%d)\", val.asBool() );\n } else if ( val.isInt() ) {\n printf( \"int(%d)\", val.asInt() );\n } else if ( val.isUInt() ) {\n printf( \"uint(%u)\", val.asUInt() );\n } else if ( val.isDouble() ) {\n printf( \"double(%f)\", val.asDouble() );\n }\n else\n {\n printf( \"unknown type=[%d]\", val.type() );\n }\n}\n\nbool PrintJSONTree( const Json::Value &root, unsigned short depth \/* = 0 *\/)\n{\n depth += 1;\n printf( \" {type=[%d], size=%d}\", root.type(), root.size() );\n\n if ( root.size() > 0 ) {\n printf(\"\\n\");\n for ( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {\n \/\/ Print depth.\n for ( int tab = 0 ; tab < depth; tab++) {\n printf(\"-\");\n }\n printf(\" subvalue(\");\n PrintJSONValue(itr.key());\n printf(\") -\");\n PrintJSONTree( *itr, depth);\n }\n return true;\n } else {\n printf(\" \");\n PrintJSONValue(root);\n printf( \"\\n\" );\n }\n return true;\n}\n\npcl::PointXYZ AgentProtocol::getPosFromJson(Json::Value const &root)\n{\n return ((pcl::PointXYZ) {\n root.get(\"x\", 0.0).asFloat(),\n root.get(\"y\", 0.0).asFloat(),\n root.get(\"z\", 0.0).asFloat()\n });\n}\n\nvoid AgentProtocol::receivePacketEvent(Network::ComPacket *packet) \/\/ only for test 4 now, will change\n{\n Json::Reader reader;\n Json::Value root;\n std::string serverReply((const char *)packet->data() + sizeof(Network::s_ComPacketHeader), packet->getPacketSize() - sizeof(Network::s_ComPacketHeader));\n\n std::cout << \"received message from serveur \" << serverReply << std::endl;\n if (reader.parse(serverReply, root, false) == true)\n {\n \/\/ std::cout << \"received a data \" << serverReply << std::endl;\n Json::Value data = root[\"data\"];\n Json::Value status = root[\"status\"];\n int status_code = status.get(\"code\", 0).asInt();\n \/\/ std::cout << \"Status code == \" << status_code << std::endl;\n if (status_code == 0 && data.empty() == false)\n {\n \/\/ std::cout << \"Data found == \" << data << std::endl;\n for (Json::ValueIterator it = data.begin(); it != data.end(); ++it)\n {\n std::string command = it.memberName();\n pcl::PointXYZ pos;\n if (command == \"order\")\n {\n pos = this->getPosFromJson(*it);\n std::cout << \"Order goal pos got == \" << pos << std::endl;\n this->dispatch(\"SetGoalPosEvent\", pos);\n }\n else if (command == \"position\")\n {\n pos = this->getPosFromJson(*it);\n this->dispatch(\"SetPosEvent\", pos);\n }\n else\n std::cout << \"Command not known: \" << command << std::endl;\n }\n }\n else\n {\n if (status_code != 0)\n std::cerr << \"Status error recieved: [\" << status_code << \"]: \" << status.get(\"message\", \"\").asString() << std::endl;\n \/\/ else\n \/\/ std::cerr << \"No data recieved but good status: \" << status.get(\"message\", \"\").asString() << std::endl;\n }\n }\n else\n std::cerr << \"error while parsing order \" << serverReply << \": \" << reader.getFormatedErrorMessages() << std::endl;\n}\n\nvoid AgentProtocol::disconnectEvent()\n{\n\n}\n<commit_msg>Packaging: comment test lines in AgentProtocol<commit_after>#include <string>\n\n#include \"AgentProtocol.h\"\n#include \"NetworkManager.hh\"\n#include \"IConnector.hh\"\n#include \"TCPConnector.h\"\n#include \"UDPConnector.hh\"\n\n\nconst std::string AgentProtocol::TCP_KEY = \"TCP\";\nconst std::string AgentProtocol::UDP_KEY = \"UDP\";\n\n\nAgentProtocol::AgentProtocol(Network::NetworkManager &networkAdapter)\n : AProtocol(networkAdapter)\n{\n Network::IConnector *connector = new Network::TCPConnector();\n _networkAdapter.setConnector(AgentProtocol::TCP_KEY, connector);\n _networkAdapter.setConnector(AgentProtocol::UDP_KEY, new Network::UDPConnector());\n}\n\nAgentProtocol::~AgentProtocol()\n{\n}\n\nvoid AgentProtocol::setAgent(IAgent *agent, Slam &slam)\n{\n this->registerCallback(\"SetGoalPosEvent\", [agent](pcl::PointXYZ pos) {dynamic_cast<Agent *>(agent)->setGoalPos(pos);});\n this->registerCallback(\"SetPosEvent\", [agent](pcl::PointXYZ pos) {agent->setPos(pos);});\n agent->registerCallback(\"SendPacketEvent\", [this](IAgent * agent) {sendPacketEvent(agent);});\n agent->registerCallback(\"SendStatusEvent\", [this](std::string const & status) {sendStatusEvent(status);});\n \/\/\/@todo: Register in the factory (process data)\n agent->registerCallback(\"SendCloudEvent\", [this](pcl::PointCloud<pcl::PointXYZ> const & cloud) {sendCloudEvent(cloud);});\n slam.registerCallback(\"SendNewLandmarkEvent\", [this](std::vector<Landmarks::Landmark *> &nl) {sendNewLandmarkEvent(nl);});\n}\n\nvoid AgentProtocol::sendCloudEvent(pcl::PointCloud<pcl::PointXYZ> const &cloud)\n{\n \/\/ To decomment to see the cloud to be send\n \/\/ for (size_t i = 0; i < cloud.points.size (); ++i)\n \/\/ std::cout << \" \" << cloud.points[i].x\n \/\/ << \" \" << cloud.points[i].y\n \/\/ << \" \" << cloud.points[i].z << std::endl;\n\n _factory.processData(cloud);\n int i = 0;\n bool is_ready = true;\n std::string toSend = \"\";\n while (_factory.isFullChunkReady())\n {\n if (is_ready) {\n ++i;\n toSend = _factory.getChunk();\n }\n is_ready = _networkAdapter.send(toSend, AgentProtocol::UDP_KEY);\n usleep(100);\n }\n std::cerr << \"Send cloud event \" << i << std::endl;\n\n \/\/To uncomment if you want to send only one cloud\n \/\/ Json::Value reply;\n\n \/\/ reply[\"data\"][\"exit\"] = 0;\n \/\/ reply[\"status\"][\"code\"] = 0;\n \/\/ reply[\"status\"][\"message\"] = \"ok\";\n \/\/ this->sendDataTcp(reply);\n \/\/ exit(1);\n}\n\nvoid AgentProtocol::sendNewLandmarkEvent(std::vector<Landmarks::Landmark *> &nl)\n{\n _factory.processData(nl);\n while (_factory.isFullChunkReady())\n {\n std::string toSend = _factory.getChunk();\n _networkAdapter.send(toSend, AgentProtocol::UDP_KEY);\n }\n}\n\nvoid AgentProtocol::sendDataTcp(Json::Value &root)\n{\n _outPacket.clear();\n std::string buffer = root.toStyledString();\n \/\/ buffer.erase(std::remove_if(buffer.begin(),\n \/\/ buffer.end(),\n \/\/ [](char x){return std::isspace(x);}),\n \/\/ buffer.end());\n _outPacket.append(buffer.c_str(), buffer.size());\n \/\/ std::cout << \"data sent == \" << buffer << std::endl;\n _networkAdapter.send(_outPacket, AgentProtocol::TCP_KEY);\n \/\/ std::cout << \"in send data:: magic = \" << (char)_outPacket.getPacketHeader().magic << \" -- packetsize == \" << _outPacket.getPacketHeader().packetSize << \" -- version == \" << _outPacket.getPacketHeader().version << \" -- header size == \" << _outPacket.getPacketHeader().headerSize << std::endl;\n _outPacket.clear();\n}\n\/**\n * @brief Function called when a connector is connected to the server\n * @todo: Change the function to get in param the key of the connector (maybe)\n *\/\nvoid AgentProtocol::connectedEvent(IAgent *agent)\n{\n \/\/ std::cout << \"connected event \" << std::endl;\n Json::Value reply;\n\n reply[\"data\"][\"name\"] = agent->name();\n reply[\"data\"][\"position\"][\"x\"] = agent->getPos().x;\n reply[\"data\"][\"position\"][\"y\"] = agent->getPos().y;\n reply[\"data\"][\"position\"][\"z\"] = agent->getPos().z;\n reply[\"status\"][\"code\"] = 0;\n reply[\"status\"][\"message\"] = \"ok\";\n this->sendDataTcp(reply);\n}\n\nvoid AgentProtocol::sendStatusEvent(std::string const &status)\n{\n Json::Value root;\n\n std::cout << \"Send status event \" << std::endl;\n root[\"status\"][\"code\"] = 0;\n root[\"status\"][\"message\"] = \"ok\";\n root[\"data\"][\"state\"] = status;\n this->sendDataTcp(root);\n}\n\nvoid AgentProtocol::sendPacketEvent(IAgent *agent)\n{\n Json::Value root;\n\n std::cout << \"Send movement event \" << std::endl;\n root[\"data\"][\"position\"][\"x\"] = agent->getPos().x;\n root[\"data\"][\"position\"][\"y\"] = agent->getPos().y;\n root[\"data\"][\"position\"][\"z\"] = agent->getPos().z;\n root[\"data\"][\"battery\"] = (agent->getBattery() * 100) \/ Agent::DEFAULTBATTERY;\n root[\"status\"][\"code\"] = 0;\n root[\"status\"][\"message\"] = \"ok\";\n this->sendDataTcp(root);\n}\n\nvoid PrintJSONValue( const Json::Value &val )\n{\n if ( val.isString() ) {\n printf( \"string(%s)\", val.asString().c_str() );\n } else if ( val.isBool() ) {\n printf( \"bool(%d)\", val.asBool() );\n } else if ( val.isInt() ) {\n printf( \"int(%d)\", val.asInt() );\n } else if ( val.isUInt() ) {\n printf( \"uint(%u)\", val.asUInt() );\n } else if ( val.isDouble() ) {\n printf( \"double(%f)\", val.asDouble() );\n }\n else\n {\n printf( \"unknown type=[%d]\", val.type() );\n }\n}\n\nbool PrintJSONTree( const Json::Value &root, unsigned short depth \/* = 0 *\/)\n{\n depth += 1;\n printf( \" {type=[%d], size=%d}\", root.type(), root.size() );\n\n if ( root.size() > 0 ) {\n printf(\"\\n\");\n for ( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {\n \/\/ Print depth.\n for ( int tab = 0 ; tab < depth; tab++) {\n printf(\"-\");\n }\n printf(\" subvalue(\");\n PrintJSONValue(itr.key());\n printf(\") -\");\n PrintJSONTree( *itr, depth);\n }\n return true;\n } else {\n printf(\" \");\n PrintJSONValue(root);\n printf( \"\\n\" );\n }\n return true;\n}\n\npcl::PointXYZ AgentProtocol::getPosFromJson(Json::Value const &root)\n{\n return ((pcl::PointXYZ) {\n root.get(\"x\", 0.0).asFloat(),\n root.get(\"y\", 0.0).asFloat(),\n root.get(\"z\", 0.0).asFloat()\n });\n}\n\nvoid AgentProtocol::receivePacketEvent(Network::ComPacket *packet) \/\/ only for test 4 now, will change\n{\n Json::Reader reader;\n Json::Value root;\n std::string serverReply((const char *)packet->data() + sizeof(Network::s_ComPacketHeader), packet->getPacketSize() - sizeof(Network::s_ComPacketHeader));\n\n std::cout << \"received message from serveur \" << serverReply << std::endl;\n if (reader.parse(serverReply, root, false) == true)\n {\n \/\/ std::cout << \"received a data \" << serverReply << std::endl;\n Json::Value data = root[\"data\"];\n Json::Value status = root[\"status\"];\n int status_code = status.get(\"code\", 0).asInt();\n \/\/ std::cout << \"Status code == \" << status_code << std::endl;\n if (status_code == 0 && data.empty() == false)\n {\n \/\/ std::cout << \"Data found == \" << data << std::endl;\n for (Json::ValueIterator it = data.begin(); it != data.end(); ++it)\n {\n std::string command = it.memberName();\n pcl::PointXYZ pos;\n if (command == \"order\")\n {\n pos = this->getPosFromJson(*it);\n std::cout << \"Order goal pos got == \" << pos << std::endl;\n this->dispatch(\"SetGoalPosEvent\", pos);\n }\n else if (command == \"position\")\n {\n pos = this->getPosFromJson(*it);\n this->dispatch(\"SetPosEvent\", pos);\n }\n else\n std::cout << \"Command not known: \" << command << std::endl;\n }\n }\n else\n {\n if (status_code != 0)\n std::cerr << \"Status error recieved: [\" << status_code << \"]: \" << status.get(\"message\", \"\").asString() << std::endl;\n \/\/ else\n \/\/ std::cerr << \"No data recieved but good status: \" << status.get(\"message\", \"\").asString() << std::endl;\n }\n }\n else\n std::cerr << \"error while parsing order \" << serverReply << \": \" << reader.getFormatedErrorMessages() << std::endl;\n}\n\nvoid AgentProtocol::disconnectEvent()\n{\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015, Google Inc.\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:\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 disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. 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 *\/\n\n#include <node.h>\n\n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/log.h\"\n#include \"server_credentials.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing Nan::Callback;\nusing Nan::EscapableHandleScope;\nusing Nan::HandleScope;\nusing Nan::Maybe;\nusing Nan::MaybeLocal;\nusing Nan::ObjectWrap;\nusing Nan::Persistent;\nusing Nan::Utf8String;\n\nusing v8::Array;\nusing v8::Exception;\nusing v8::External;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nNan::Callback *ServerCredentials::constructor;\nPersistent<FunctionTemplate> ServerCredentials::fun_tpl;\n\nServerCredentials::ServerCredentials(grpc_server_credentials *credentials)\n : wrapped_credentials(credentials) {}\n\nServerCredentials::~ServerCredentials() {\n grpc_server_credentials_release(wrapped_credentials);\n}\n\nvoid ServerCredentials::Init(Local<Object> exports) {\n Nan::HandleScope scope;\n Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);\n tpl->SetClassName(Nan::New(\"ServerCredentials\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n Local<Function> ctr = tpl->GetFunction();\n Nan::Set(ctr, Nan::New(\"createSsl\").ToLocalChecked(),\n Nan::GetFunction(\n Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked());\n Nan::Set(ctr, Nan::New(\"createInsecure\").ToLocalChecked(),\n Nan::GetFunction(\n Nan::New<FunctionTemplate>(CreateInsecure)).ToLocalChecked());\n fun_tpl.Reset(tpl);\n constructor = new Nan::Callback(ctr);\n Nan::Set(exports, Nan::New(\"ServerCredentials\").ToLocalChecked(), ctr);\n}\n\nbool ServerCredentials::HasInstance(Local<Value> val) {\n Nan::HandleScope scope;\n return Nan::New(fun_tpl)->HasInstance(val);\n}\n\nLocal<Value> ServerCredentials::WrapStruct(\n grpc_server_credentials *credentials) {\n Nan::EscapableHandleScope scope;\n const int argc = 1;\n Local<Value> argv[argc] = {\n Nan::New<External>(reinterpret_cast<void *>(credentials))};\n MaybeLocal<Object> maybe_instance = Nan::NewInstance(\n constructor->GetFunction(), argc, argv);\n if (maybe_instance.IsEmpty()) {\n return scope.Escape(Nan::Null());\n } else {\n return scope.Escape(maybe_instance.ToLocalChecked());\n }\n}\n\ngrpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() {\n return wrapped_credentials;\n}\n\nNAN_METHOD(ServerCredentials::New) {\n if (info.IsConstructCall()) {\n if (!info[0]->IsExternal()) {\n return Nan::ThrowTypeError(\n \"ServerCredentials can only be created with the provided functions\");\n }\n Local<External> ext = info[0].As<External>();\n grpc_server_credentials *creds_value =\n reinterpret_cast<grpc_server_credentials *>(ext->Value());\n ServerCredentials *credentials = new ServerCredentials(creds_value);\n credentials->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ This should never be called directly\n return Nan::ThrowTypeError(\n \"ServerCredentials can only be created with the provided functions\");\n }\n}\n\nNAN_METHOD(ServerCredentials::CreateSsl) {\n Nan::HandleScope scope;\n char *root_certs = NULL;\n if (::node::Buffer::HasInstance(info[0])) {\n root_certs = ::node::Buffer::Data(info[0]);\n } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) {\n return Nan::ThrowTypeError(\n \"createSSl's first argument must be a Buffer if provided\");\n }\n if (!info[1]->IsArray()) {\n return Nan::ThrowTypeError(\n \"createSsl's second argument must be a list of objects\");\n }\n\n \/\/ Default to not requesting the client certificate\n grpc_ssl_client_certificate_request_type client_certificate_request =\n GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE;\n if (info[2]->IsBoolean()) {\n client_certificate_request =\n Nan::To<bool>(info[2]).FromJust()\n ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY\n : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE;\n } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) {\n return Nan::ThrowTypeError(\n \"createSsl's third argument must be a boolean if provided\");\n }\n Local<Array> pair_list = Local<Array>::Cast(info[1]);\n uint32_t key_cert_pair_count = pair_list->Length();\n grpc_ssl_pem_key_cert_pair *key_cert_pairs = new grpc_ssl_pem_key_cert_pair[\n key_cert_pair_count];\n\n Local<String> key_key = Nan::New(\"private_key\").ToLocalChecked();\n Local<String> cert_key = Nan::New(\"cert_chain\").ToLocalChecked();\n\n for(uint32_t i = 0; i < key_cert_pair_count; i++) {\n Local<Value> pair_val = Nan::Get(pair_list, i).ToLocalChecked();\n if (!pair_val->IsObject()) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"Key\/cert pairs must be objects\");\n }\n Local<Object> pair_obj = Nan::To<Object>(pair_val).ToLocalChecked();\n Local<Value> maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked();\n Local<Value> maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked();\n if (!::node::Buffer::HasInstance(maybe_key)) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"private_key must be a Buffer\");\n }\n if (!::node::Buffer::HasInstance(maybe_cert)) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"cert_chain must be a Buffer\");\n }\n key_cert_pairs[i].private_key = ::node::Buffer::Data(maybe_key);\n key_cert_pairs[i].cert_chain = ::node::Buffer::Data(maybe_cert);\n }\n grpc_server_credentials *creds = grpc_ssl_server_credentials_create_ex(\n root_certs, key_cert_pairs, key_cert_pair_count,\n client_certificate_request, NULL);\n delete key_cert_pairs;\n if (creds == NULL) {\n info.GetReturnValue().SetNull();\n } else {\n info.GetReturnValue().Set(WrapStruct(creds));\n }\n}\n\nNAN_METHOD(ServerCredentials::CreateInsecure) {\n info.GetReturnValue().Set(WrapStruct(NULL));\n}\n\n} \/\/ namespace node\n} \/\/ namespace grpc\n<commit_msg>Fix mismatched new[] and delete in Node extension code<commit_after>\/*\n *\n * Copyright 2015, Google Inc.\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:\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 disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. 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 *\/\n\n#include <node.h>\n\n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/log.h\"\n#include \"server_credentials.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing Nan::Callback;\nusing Nan::EscapableHandleScope;\nusing Nan::HandleScope;\nusing Nan::Maybe;\nusing Nan::MaybeLocal;\nusing Nan::ObjectWrap;\nusing Nan::Persistent;\nusing Nan::Utf8String;\n\nusing v8::Array;\nusing v8::Exception;\nusing v8::External;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nNan::Callback *ServerCredentials::constructor;\nPersistent<FunctionTemplate> ServerCredentials::fun_tpl;\n\nServerCredentials::ServerCredentials(grpc_server_credentials *credentials)\n : wrapped_credentials(credentials) {}\n\nServerCredentials::~ServerCredentials() {\n grpc_server_credentials_release(wrapped_credentials);\n}\n\nvoid ServerCredentials::Init(Local<Object> exports) {\n Nan::HandleScope scope;\n Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);\n tpl->SetClassName(Nan::New(\"ServerCredentials\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n Local<Function> ctr = tpl->GetFunction();\n Nan::Set(ctr, Nan::New(\"createSsl\").ToLocalChecked(),\n Nan::GetFunction(\n Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked());\n Nan::Set(ctr, Nan::New(\"createInsecure\").ToLocalChecked(),\n Nan::GetFunction(\n Nan::New<FunctionTemplate>(CreateInsecure)).ToLocalChecked());\n fun_tpl.Reset(tpl);\n constructor = new Nan::Callback(ctr);\n Nan::Set(exports, Nan::New(\"ServerCredentials\").ToLocalChecked(), ctr);\n}\n\nbool ServerCredentials::HasInstance(Local<Value> val) {\n Nan::HandleScope scope;\n return Nan::New(fun_tpl)->HasInstance(val);\n}\n\nLocal<Value> ServerCredentials::WrapStruct(\n grpc_server_credentials *credentials) {\n Nan::EscapableHandleScope scope;\n const int argc = 1;\n Local<Value> argv[argc] = {\n Nan::New<External>(reinterpret_cast<void *>(credentials))};\n MaybeLocal<Object> maybe_instance = Nan::NewInstance(\n constructor->GetFunction(), argc, argv);\n if (maybe_instance.IsEmpty()) {\n return scope.Escape(Nan::Null());\n } else {\n return scope.Escape(maybe_instance.ToLocalChecked());\n }\n}\n\ngrpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() {\n return wrapped_credentials;\n}\n\nNAN_METHOD(ServerCredentials::New) {\n if (info.IsConstructCall()) {\n if (!info[0]->IsExternal()) {\n return Nan::ThrowTypeError(\n \"ServerCredentials can only be created with the provided functions\");\n }\n Local<External> ext = info[0].As<External>();\n grpc_server_credentials *creds_value =\n reinterpret_cast<grpc_server_credentials *>(ext->Value());\n ServerCredentials *credentials = new ServerCredentials(creds_value);\n credentials->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ This should never be called directly\n return Nan::ThrowTypeError(\n \"ServerCredentials can only be created with the provided functions\");\n }\n}\n\nNAN_METHOD(ServerCredentials::CreateSsl) {\n Nan::HandleScope scope;\n char *root_certs = NULL;\n if (::node::Buffer::HasInstance(info[0])) {\n root_certs = ::node::Buffer::Data(info[0]);\n } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) {\n return Nan::ThrowTypeError(\n \"createSSl's first argument must be a Buffer if provided\");\n }\n if (!info[1]->IsArray()) {\n return Nan::ThrowTypeError(\n \"createSsl's second argument must be a list of objects\");\n }\n\n \/\/ Default to not requesting the client certificate\n grpc_ssl_client_certificate_request_type client_certificate_request =\n GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE;\n if (info[2]->IsBoolean()) {\n client_certificate_request =\n Nan::To<bool>(info[2]).FromJust()\n ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY\n : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE;\n } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) {\n return Nan::ThrowTypeError(\n \"createSsl's third argument must be a boolean if provided\");\n }\n Local<Array> pair_list = Local<Array>::Cast(info[1]);\n uint32_t key_cert_pair_count = pair_list->Length();\n grpc_ssl_pem_key_cert_pair *key_cert_pairs = new grpc_ssl_pem_key_cert_pair[\n key_cert_pair_count];\n\n Local<String> key_key = Nan::New(\"private_key\").ToLocalChecked();\n Local<String> cert_key = Nan::New(\"cert_chain\").ToLocalChecked();\n\n for(uint32_t i = 0; i < key_cert_pair_count; i++) {\n Local<Value> pair_val = Nan::Get(pair_list, i).ToLocalChecked();\n if (!pair_val->IsObject()) {\n delete[] key_cert_pairs;\n return Nan::ThrowTypeError(\"Key\/cert pairs must be objects\");\n }\n Local<Object> pair_obj = Nan::To<Object>(pair_val).ToLocalChecked();\n Local<Value> maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked();\n Local<Value> maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked();\n if (!::node::Buffer::HasInstance(maybe_key)) {\n delete[] key_cert_pairs;\n return Nan::ThrowTypeError(\"private_key must be a Buffer\");\n }\n if (!::node::Buffer::HasInstance(maybe_cert)) {\n delete[] key_cert_pairs;\n return Nan::ThrowTypeError(\"cert_chain must be a Buffer\");\n }\n key_cert_pairs[i].private_key = ::node::Buffer::Data(maybe_key);\n key_cert_pairs[i].cert_chain = ::node::Buffer::Data(maybe_cert);\n }\n grpc_server_credentials *creds = grpc_ssl_server_credentials_create_ex(\n root_certs, key_cert_pairs, key_cert_pair_count,\n client_certificate_request, NULL);\n delete[] key_cert_pairs;\n if (creds == NULL) {\n info.GetReturnValue().SetNull();\n } else {\n info.GetReturnValue().Set(WrapStruct(creds));\n }\n}\n\nNAN_METHOD(ServerCredentials::CreateInsecure) {\n info.GetReturnValue().Set(WrapStruct(NULL));\n}\n\n} \/\/ namespace node\n} \/\/ namespace grpc\n<|endoftext|>"} {"text":"<commit_before>#include <functional>\n\n#include \"SLABasePool.hpp\"\n#include \"ExPolygon.hpp\"\n#include \"TriangleMesh.hpp\"\n#include <numeric>\n#include \"ClipperUtils.hpp\"\n#include \"boost\/log\/trivial.hpp\"\n\n\/\/#include \"SVG.hpp\"\n\nnamespace Slic3r { namespace sla {\n\nnamespace {\n\nusing coord_t = Point::coord_type;\ninline coord_t mm(double v) { return coord_t(v\/SCALING_FACTOR); }\n\ninline coord_t x(const Point& p) { return p.x; }\ninline coord_t y(const Point& p) { return p.y; }\n\nstruct Contour3D {\n Pointf3s points;\n std::vector<Point3> indices;\n\n void merge(const Contour3D& ctr) {\n auto s3 = coord_t(points.size());\n auto s = coord_t(indices.size());\n\n points.insert(points.end(), ctr.points.begin(), ctr.points.end());\n indices.insert(indices.end(), ctr.indices.begin(), ctr.indices.end());\n\n for(auto n = s; n < indices.size(); n++) {\n auto& idx = indices[n]; idx.x += s3; idx.y += s3; idx.z += s3;\n }\n }\n};\n\ninline Contour3D convert(const Polygons& triangles, coord_t z, bool dir) {\n\n Pointf3s points;\n points.reserve(3*triangles.size());\n std::vector<Point3> indices;\n indices.reserve(points.size());\n\n for(auto& tr : triangles) {\n auto c = coord_t(points.size()), b = c++, a = c++;\n if(dir) indices.emplace_back(a, b, c);\n else indices.emplace_back(c, b, a);\n for(auto& p : tr.points) {\n points.emplace_back(Pointf3::new_unscale(x(p), y(p), z));\n }\n }\n\n return {points, indices};\n}\n\ninline Contour3D roofs(const ExPolygon& poly, coord_t z_distance) {\n Polygons triangles;\n poly.triangulate_pp(&triangles);\n\n auto lower = convert(triangles, 0, false);\n auto upper = convert(triangles, z_distance, true);\n lower.merge(upper);\n return lower;\n}\n\ninline Contour3D inner_bed(const ExPolygon& poly, coord_t depth) {\n Polygons triangles;\n poly.triangulate_p2t(&triangles);\n\n auto bottom = convert(triangles, -depth, false);\n auto lines = poly.lines();\n\n \/\/ Generate outer walls\n auto fp = [](const Point& p, Point::coord_type z) {\n return Pointf3::new_unscale(x(p), y(p), z);\n };\n\n for(auto& l : lines) {\n auto s = coord_t(bottom.points.size());\n\n bottom.points.emplace_back(fp(l.a, -depth));\n bottom.points.emplace_back(fp(l.b, -depth));\n bottom.points.emplace_back(fp(l.a, 0));\n bottom.points.emplace_back(fp(l.b, 0));\n\n bottom.indices.emplace_back(s, s + 1, s + 3);\n bottom.indices.emplace_back(s, s + 3, s + 2);\n }\n\n return bottom;\n}\n\ninline TriangleMesh mesh(const Contour3D& ctour) {\n return {ctour.points, ctour.indices};\n}\n\ninline TriangleMesh mesh(Contour3D&& ctour) {\n return {std::move(ctour.points), std::move(ctour.indices)};\n}\n\ninline void offset(ExPolygon& sh, coord_t distance) {\n using ClipperLib::ClipperOffset;\n using ClipperLib::jtRound;\n using ClipperLib::etClosedPolygon;\n using ClipperLib::Paths;\n using ClipperLib::Path;\n\n auto&& ctour = Slic3rMultiPoint_to_ClipperPath(sh.contour);\n auto&& holes = Slic3rMultiPoints_to_ClipperPaths(sh.holes);\n\n \/\/ If the input is not at least a triangle, we can not do this algorithm\n if(ctour.size() < 3 ||\n std::any_of(holes.begin(), holes.end(),\n [](const Path& p) { return p.size() < 3; })\n ) {\n BOOST_LOG_TRIVIAL(error) << \"Invalid geometry for offsetting!\";\n return;\n }\n\n ClipperOffset offs;\n offs.ArcTolerance = 0.05*mm(1);\n Paths result;\n offs.AddPath(ctour, jtRound, etClosedPolygon);\n offs.AddPaths(holes, jtRound, etClosedPolygon);\n offs.Execute(result, static_cast<double>(distance));\n\n \/\/ Offsetting reverts the orientation and also removes the last vertex\n \/\/ so boost will not have a closed polygon.\n\n bool found_the_contour = false;\n sh.holes.clear();\n for(auto& r : result) {\n if(ClipperLib::Orientation(r)) {\n \/\/ We don't like if the offsetting generates more than one contour\n \/\/ but throwing would be an overkill. Instead, we should warn the\n \/\/ caller about the inability to create correct geometries\n if(!found_the_contour) {\n auto rr = ClipperPath_to_Slic3rPolygon(r);\n sh.contour.points.swap(rr.points);\n found_the_contour = true;\n } else {\n BOOST_LOG_TRIVIAL(warning)\n << \"Warning: offsetting result is invalid!\";\n }\n } else {\n \/\/ TODO If there are multiple contours we can't be sure which hole\n \/\/ belongs to the first contour. (But in this case the situation is\n \/\/ bad enough to let it go...)\n sh.holes.emplace_back(ClipperPath_to_Slic3rPolygon(r));\n }\n }\n}\n\ninline ExPolygons unify(const ExPolygons& shapes) {\n ExPolygons retv;\n\n bool closed = true;\n bool valid = true;\n\n ClipperLib::Clipper clipper;\n\n for(auto& path : shapes) {\n auto clipperpath = Slic3rMultiPoint_to_ClipperPath(path.contour);\n valid &= clipper.AddPath(clipperpath, ClipperLib::ptSubject, closed);\n\n auto clipperholes = Slic3rMultiPoints_to_ClipperPaths(path.holes);\n for(auto& hole : clipperholes) {\n valid &= clipper.AddPath(hole, ClipperLib::ptSubject, closed);\n }\n }\n\n if(!valid) BOOST_LOG_TRIVIAL(warning) << \"Unification of invalid shapes!\";\n\n ClipperLib::PolyTree result;\n clipper.Execute(ClipperLib::ctUnion, result, ClipperLib::pftNonZero);\n\n retv.reserve(static_cast<size_t>(result.Total()));\n\n \/\/ Now we will recursively traverse the polygon tree and serialize it\n \/\/ into an ExPolygon with holes. The polygon tree has the clipper-ish\n \/\/ PolyTree structure which alternates its nodes as contours and holes\n\n \/\/ A \"declaration\" of function for traversing leafs which are holes\n std::function<void(ClipperLib::PolyNode*, ExPolygon&)> processHole;\n\n \/\/ Process polygon which calls processHoles which than calls processPoly\n \/\/ again until no leafs are left.\n auto processPoly = [&retv, &processHole](ClipperLib::PolyNode *pptr) {\n ExPolygon poly;\n poly.contour.points = ClipperPath_to_Slic3rPolygon(pptr->Contour);\n for(auto h : pptr->Childs) { processHole(h, poly); }\n retv.push_back(poly);\n };\n\n \/\/ Body of the processHole function\n processHole = [&processPoly](ClipperLib::PolyNode *pptr, ExPolygon& poly)\n {\n poly.holes.emplace_back();\n poly.holes.back().points = ClipperPath_to_Slic3rPolygon(pptr->Contour);\n for(auto c : pptr->Childs) processPoly(c);\n };\n\n \/\/ Wrapper for traversing.\n auto traverse = [&processPoly] (ClipperLib::PolyNode *node)\n {\n for(auto ch : node->Childs) {\n processPoly(ch);\n }\n };\n\n \/\/ Here is the actual traverse\n traverse(&result);\n\n return retv;\n}\n\ninline Point centroid(Points& pp) {\n Polygon p;\n p.points.swap(pp);\n Point c = p.centroid();\n pp.swap(p.points);\n return c;\n}\n\ninline Point centroid(const ExPolygon& poly) {\n return poly.contour.centroid();\n}\n\ninline ExPolygon concave_hull(const ExPolygons& polys) {\n if(polys.empty()) return ExPolygon();\n\n ExPolygons punion = unify(polys);\n\n ExPolygon ret;\n\n if(punion.size() == 1) return punion.front();\n\n \/\/ We get the centroids of all the islands in the 2D slice\n Points centroids; centroids.reserve(punion.size());\n std::transform(punion.begin(), punion.end(), std::back_inserter(centroids),\n [](const ExPolygon& poly) { return centroid(poly); });\n\n \/\/ Centroid of the centroids of islands. This is where the additional\n \/\/ connector sticks are routed.\n Point cc = centroid(centroids);\n\n punion.reserve(punion.size() + centroids.size());\n\n std::transform(centroids.begin(), centroids.end(),\n std::back_inserter(punion),\n [cc](const Point& c) {\n\n double dx = x(c) - x(cc), dy = y(c) - y(cc);\n double l = std::sqrt(dx * dx + dy * dy);\n double nx = dx \/ l, ny = dy \/ l;\n\n ExPolygon r;\n auto& ctour = r.contour.points;\n\n ctour.reserve(3);\n ctour.emplace_back(cc);\n\n Point d(coord_t(mm(1)*nx), coord_t(mm(1)*ny));\n ctour.emplace_back(c + Point( -y(d), x(d) ));\n ctour.emplace_back(c + Point( y(d), -x(d) ));\n offset(r, mm(1));\n\n return r;\n });\n\n punion = unify(punion);\n\n if(punion.size() != 1)\n BOOST_LOG_TRIVIAL(error) << \"Cannot generate correct SLA base pool!\";\n\n if(!punion.empty()) ret = punion.front();\n\n return ret;\n}\n\n}\n\nvoid ground_layer(const TriangleMesh &mesh, ExPolygons &output, float h)\n{\n TriangleMesh m = mesh;\n TriangleMeshSlicer slicer(&m);\n\n std::vector<ExPolygons> tmp;\n\n slicer.slice({h}, &tmp);\n\n output = tmp.front();\n}\n\nvoid create_base_pool(const ExPolygons &ground_layer, TriangleMesh& out,\n double min_wall_thickness_mm,\n double min_wall_height_mm)\n{\n \/\/ 1: Offset the ground layer\n auto concaveh = concave_hull(ground_layer);\n if(concaveh.contour.points.empty()) return;\n concaveh.holes.clear();\n\n BoundingBox bb(concaveh);\n coord_t w = bb.max.x - bb.min.x;\n coord_t h = bb.max.y - bb.min.y;\n\n auto wall_thickness = coord_t(std::pow((w+h)*0.1, 0.8));\n\n const coord_t WALL_THICKNESS = mm(min_wall_thickness_mm) + wall_thickness;\n const coord_t WALL_DISTANCE = coord_t(0.3*WALL_THICKNESS);\n const coord_t HEIGHT = mm(min_wall_height_mm);\n\n auto outer_base = concaveh;\n offset(outer_base, WALL_THICKNESS+WALL_DISTANCE);\n auto inner_base = outer_base;\n offset(inner_base, -WALL_THICKNESS);\n inner_base.holes.clear(); outer_base.holes.clear();\n\n ExPolygon top_poly;\n top_poly.contour = outer_base.contour;\n top_poly.holes.emplace_back(inner_base.contour);\n auto& tph = top_poly.holes.back().points;\n std::reverse(tph.begin(), tph.end());\n\n Contour3D pool;\n\n Polygons top_triangles, bottom_triangles;\n top_poly.triangulate_p2t(&top_triangles);\n outer_base.triangulate_p2t(&bottom_triangles);\n auto top_plate = convert(top_triangles, 0, false);\n auto bottom_plate = convert(bottom_triangles, -HEIGHT, true);\n auto innerbed = inner_bed(inner_base, HEIGHT\/2);\n\n \/\/ Generate outer walls\n auto fp = [](const Point& p, coord_t z) {\n return Pointf3::new_unscale(x(p), y(p), z);\n };\n\n auto lines = outer_base.lines();\n for(auto& l : lines) {\n auto s = coord_t(pool.points.size());\n\n pool.points.emplace_back(fp(l.a, -HEIGHT));\n pool.points.emplace_back(fp(l.b, -HEIGHT));\n pool.points.emplace_back(fp(l.a, 0));\n pool.points.emplace_back(fp(l.b, 0));\n\n pool.indices.emplace_back(s, s + 3, s + 1);\n pool.indices.emplace_back(s, s + 2, s + 3);\n }\n\n pool.merge(top_plate);\n pool.merge(bottom_plate);\n pool.merge(innerbed);\n\n out = mesh(pool);\n}\n\n}\n}\n<commit_msg>Comments mostly<commit_after>#include <functional>\n#include <numeric>\n\n#include \"SLABasePool.hpp\"\n#include \"ExPolygon.hpp\"\n#include \"TriangleMesh.hpp\"\n#include \"ClipperUtils.hpp\"\n#include \"boost\/log\/trivial.hpp\"\n\n\/\/#include \"SVG.hpp\"\n\nnamespace Slic3r { namespace sla {\n\nnamespace {\n\nusing coord_t = Point::coord_type;\n\n\/\/\/ get the scaled clipper units for a millimeter value\ninline coord_t mm(double v) { return coord_t(v\/SCALING_FACTOR); }\n\n\/\/\/ Get x and y coordinates (because we are eigenizing...)\ninline coord_t x(const Point& p) { return p.x; }\ninline coord_t y(const Point& p) { return p.y; }\n\n\/\/\/ Intermediate struct for a 3D mesh\nstruct Contour3D {\n Pointf3s points;\n std::vector<Point3> indices;\n\n void merge(const Contour3D& ctr) {\n auto s3 = coord_t(points.size());\n auto s = coord_t(indices.size());\n\n points.insert(points.end(), ctr.points.begin(), ctr.points.end());\n indices.insert(indices.end(), ctr.indices.begin(), ctr.indices.end());\n\n for(auto n = s; n < indices.size(); n++) {\n auto& idx = indices[n]; idx.x += s3; idx.y += s3; idx.z += s3;\n }\n }\n};\n\n\/\/\/ Convert the triangulation output to an intermediate mesh.\ninline Contour3D convert(const Polygons& triangles, coord_t z, bool dir) {\n\n Pointf3s points;\n points.reserve(3*triangles.size());\n std::vector<Point3> indices;\n indices.reserve(points.size());\n\n for(auto& tr : triangles) {\n auto c = coord_t(points.size()), b = c++, a = c++;\n if(dir) indices.emplace_back(a, b, c);\n else indices.emplace_back(c, b, a);\n for(auto& p : tr.points) {\n points.emplace_back(Pointf3::new_unscale(x(p), y(p), z));\n }\n }\n\n return {points, indices};\n}\n\n\/\/\/ Only a debug function to generate top and bottom plates from a 2D shape.\n\/\/\/ It is not used in the algorithm directly.\ninline Contour3D roofs(const ExPolygon& poly, coord_t z_distance) {\n Polygons triangles;\n poly.triangulate_pp(&triangles);\n\n auto lower = convert(triangles, 0, false);\n auto upper = convert(triangles, z_distance, true);\n lower.merge(upper);\n return lower;\n}\n\n\/\/\/ Generating the concave part of the 3D pool with the bottom plate and the\n\/\/\/ side walls.\ninline Contour3D inner_bed(const ExPolygon& poly, coord_t depth) {\n Polygons triangles;\n poly.triangulate_p2t(&triangles);\n\n auto bottom = convert(triangles, -depth, false);\n auto lines = poly.lines();\n\n \/\/ Generate outer walls\n auto fp = [](const Point& p, Point::coord_type z) {\n return Pointf3::new_unscale(x(p), y(p), z);\n };\n\n for(auto& l : lines) {\n auto s = coord_t(bottom.points.size());\n\n bottom.points.emplace_back(fp(l.a, -depth));\n bottom.points.emplace_back(fp(l.b, -depth));\n bottom.points.emplace_back(fp(l.a, 0));\n bottom.points.emplace_back(fp(l.b, 0));\n\n bottom.indices.emplace_back(s, s + 1, s + 3);\n bottom.indices.emplace_back(s, s + 3, s + 2);\n }\n\n return bottom;\n}\n\n\/\/\/ Mesh from an existing contour.\ninline TriangleMesh mesh(const Contour3D& ctour) {\n return {ctour.points, ctour.indices};\n}\n\n\/\/\/ Mesh from an evaporating 3D contour\ninline TriangleMesh mesh(Contour3D&& ctour) {\n return {std::move(ctour.points), std::move(ctour.indices)};\n}\n\n\/\/\/ Offsetting with clipper and smoothing the edges into a curvature.\ninline void offset(ExPolygon& sh, coord_t distance) {\n using ClipperLib::ClipperOffset;\n using ClipperLib::jtRound;\n using ClipperLib::etClosedPolygon;\n using ClipperLib::Paths;\n using ClipperLib::Path;\n\n auto&& ctour = Slic3rMultiPoint_to_ClipperPath(sh.contour);\n auto&& holes = Slic3rMultiPoints_to_ClipperPaths(sh.holes);\n\n \/\/ If the input is not at least a triangle, we can not do this algorithm\n if(ctour.size() < 3 ||\n std::any_of(holes.begin(), holes.end(),\n [](const Path& p) { return p.size() < 3; })\n ) {\n BOOST_LOG_TRIVIAL(error) << \"Invalid geometry for offsetting!\";\n return;\n }\n\n ClipperOffset offs;\n offs.ArcTolerance = 0.05*mm(1);\n Paths result;\n offs.AddPath(ctour, jtRound, etClosedPolygon);\n offs.AddPaths(holes, jtRound, etClosedPolygon);\n offs.Execute(result, static_cast<double>(distance));\n\n \/\/ Offsetting reverts the orientation and also removes the last vertex\n \/\/ so boost will not have a closed polygon.\n\n bool found_the_contour = false;\n sh.holes.clear();\n for(auto& r : result) {\n if(ClipperLib::Orientation(r)) {\n \/\/ We don't like if the offsetting generates more than one contour\n \/\/ but throwing would be an overkill. Instead, we should warn the\n \/\/ caller about the inability to create correct geometries\n if(!found_the_contour) {\n auto rr = ClipperPath_to_Slic3rPolygon(r);\n sh.contour.points.swap(rr.points);\n found_the_contour = true;\n } else {\n BOOST_LOG_TRIVIAL(warning)\n << \"Warning: offsetting result is invalid!\";\n }\n } else {\n \/\/ TODO If there are multiple contours we can't be sure which hole\n \/\/ belongs to the first contour. (But in this case the situation is\n \/\/ bad enough to let it go...)\n sh.holes.emplace_back(ClipperPath_to_Slic3rPolygon(r));\n }\n }\n}\n\n\/\/\/ Unification of polygons (with clipper) preserving holes as well.\ninline ExPolygons unify(const ExPolygons& shapes) {\n ExPolygons retv;\n\n bool closed = true;\n bool valid = true;\n\n ClipperLib::Clipper clipper;\n\n for(auto& path : shapes) {\n auto clipperpath = Slic3rMultiPoint_to_ClipperPath(path.contour);\n valid &= clipper.AddPath(clipperpath, ClipperLib::ptSubject, closed);\n\n auto clipperholes = Slic3rMultiPoints_to_ClipperPaths(path.holes);\n for(auto& hole : clipperholes) {\n valid &= clipper.AddPath(hole, ClipperLib::ptSubject, closed);\n }\n }\n\n if(!valid) BOOST_LOG_TRIVIAL(warning) << \"Unification of invalid shapes!\";\n\n ClipperLib::PolyTree result;\n clipper.Execute(ClipperLib::ctUnion, result, ClipperLib::pftNonZero);\n\n retv.reserve(static_cast<size_t>(result.Total()));\n\n \/\/ Now we will recursively traverse the polygon tree and serialize it\n \/\/ into an ExPolygon with holes. The polygon tree has the clipper-ish\n \/\/ PolyTree structure which alternates its nodes as contours and holes\n\n \/\/ A \"declaration\" of function for traversing leafs which are holes\n std::function<void(ClipperLib::PolyNode*, ExPolygon&)> processHole;\n\n \/\/ Process polygon which calls processHoles which than calls processPoly\n \/\/ again until no leafs are left.\n auto processPoly = [&retv, &processHole](ClipperLib::PolyNode *pptr) {\n ExPolygon poly;\n poly.contour.points = ClipperPath_to_Slic3rPolygon(pptr->Contour);\n for(auto h : pptr->Childs) { processHole(h, poly); }\n retv.push_back(poly);\n };\n\n \/\/ Body of the processHole function\n processHole = [&processPoly](ClipperLib::PolyNode *pptr, ExPolygon& poly)\n {\n poly.holes.emplace_back();\n poly.holes.back().points = ClipperPath_to_Slic3rPolygon(pptr->Contour);\n for(auto c : pptr->Childs) processPoly(c);\n };\n\n \/\/ Wrapper for traversing.\n auto traverse = [&processPoly] (ClipperLib::PolyNode *node)\n {\n for(auto ch : node->Childs) {\n processPoly(ch);\n }\n };\n\n \/\/ Here is the actual traverse\n traverse(&result);\n\n return retv;\n}\n\ninline Point centroid(Points& pp) {\n Polygon p;\n p.points.swap(pp);\n Point c = p.centroid();\n pp.swap(p.points);\n return c;\n}\n\ninline Point centroid(const ExPolygon& poly) {\n return poly.contour.centroid();\n}\n\n\/\/\/ A fake concave hull that is constructed by connecting separate shapes\n\/\/\/ with explicit bridges. Bridges are generated from each shape's centroid\n\/\/\/ to the center of the \"scene\" which is the centroid calculated from the shape\n\/\/\/ centroids (a star is created...)\ninline ExPolygon concave_hull(const ExPolygons& polys) {\n if(polys.empty()) return ExPolygon();\n\n ExPolygons punion = unify(polys);\n\n ExPolygon ret;\n\n if(punion.size() == 1) return punion.front();\n\n \/\/ We get the centroids of all the islands in the 2D slice\n Points centroids; centroids.reserve(punion.size());\n std::transform(punion.begin(), punion.end(), std::back_inserter(centroids),\n [](const ExPolygon& poly) { return centroid(poly); });\n\n \/\/ Centroid of the centroids of islands. This is where the additional\n \/\/ connector sticks are routed.\n Point cc = centroid(centroids);\n\n punion.reserve(punion.size() + centroids.size());\n\n std::transform(centroids.begin(), centroids.end(),\n std::back_inserter(punion),\n [cc](const Point& c) {\n\n double dx = x(c) - x(cc), dy = y(c) - y(cc);\n double l = std::sqrt(dx * dx + dy * dy);\n double nx = dx \/ l, ny = dy \/ l;\n\n ExPolygon r;\n auto& ctour = r.contour.points;\n\n ctour.reserve(3);\n ctour.emplace_back(cc);\n\n Point d(coord_t(mm(1)*nx), coord_t(mm(1)*ny));\n ctour.emplace_back(c + Point( -y(d), x(d) ));\n ctour.emplace_back(c + Point( y(d), -x(d) ));\n offset(r, mm(1));\n\n return r;\n });\n\n punion = unify(punion);\n\n if(punion.size() != 1)\n BOOST_LOG_TRIVIAL(error) << \"Cannot generate correct SLA base pool!\";\n\n if(!punion.empty()) ret = punion.front();\n\n return ret;\n}\n\n}\n\nvoid ground_layer(const TriangleMesh &mesh, ExPolygons &output, float h)\n{\n TriangleMesh m = mesh;\n TriangleMeshSlicer slicer(&m);\n\n std::vector<ExPolygons> tmp;\n\n slicer.slice({h}, &tmp);\n\n output = tmp.front();\n}\n\nvoid create_base_pool(const ExPolygons &ground_layer, TriangleMesh& out,\n double min_wall_thickness_mm,\n double min_wall_height_mm)\n{\n \/\/ 1: Offset the ground layer\n auto concaveh = concave_hull(ground_layer);\n if(concaveh.contour.points.empty()) return;\n concaveh.holes.clear();\n\n BoundingBox bb(concaveh);\n coord_t w = bb.max.x - bb.min.x;\n coord_t h = bb.max.y - bb.min.y;\n\n auto wall_thickness = coord_t(std::pow((w+h)*0.1, 0.8));\n\n const coord_t WALL_THICKNESS = mm(min_wall_thickness_mm) + wall_thickness;\n const coord_t WALL_DISTANCE = coord_t(0.3*WALL_THICKNESS);\n const coord_t HEIGHT = mm(min_wall_height_mm);\n\n auto outer_base = concaveh;\n offset(outer_base, WALL_THICKNESS+WALL_DISTANCE);\n auto inner_base = outer_base;\n offset(inner_base, -WALL_THICKNESS);\n inner_base.holes.clear(); outer_base.holes.clear();\n\n ExPolygon top_poly;\n top_poly.contour = outer_base.contour;\n top_poly.holes.emplace_back(inner_base.contour);\n auto& tph = top_poly.holes.back().points;\n std::reverse(tph.begin(), tph.end());\n\n Contour3D pool;\n\n Polygons top_triangles, bottom_triangles;\n top_poly.triangulate_p2t(&top_triangles);\n outer_base.triangulate_p2t(&bottom_triangles);\n auto top_plate = convert(top_triangles, 0, false);\n auto bottom_plate = convert(bottom_triangles, -HEIGHT, true);\n auto innerbed = inner_bed(inner_base, HEIGHT\/2);\n\n \/\/ Generate outer walls\n auto fp = [](const Point& p, coord_t z) {\n return Pointf3::new_unscale(x(p), y(p), z);\n };\n\n auto lines = outer_base.lines();\n for(auto& l : lines) {\n auto s = coord_t(pool.points.size());\n\n pool.points.emplace_back(fp(l.a, -HEIGHT));\n pool.points.emplace_back(fp(l.b, -HEIGHT));\n pool.points.emplace_back(fp(l.a, 0));\n pool.points.emplace_back(fp(l.b, 0));\n\n pool.indices.emplace_back(s, s + 3, s + 1);\n pool.indices.emplace_back(s, s + 2, s + 3);\n }\n\n pool.merge(top_plate);\n pool.merge(bottom_plate);\n pool.merge(innerbed);\n\n out = mesh(pool);\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <queue>\n#include <map>\n#include <set>\n#include <stack>\n#include <cstring>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <cmath>\n#include <list>\n#include <bitset>\n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pair<int, int>pii;\ntypedef pair<ll, ll>pll;\ntypedef pair<double, double>pdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<<endl;\n#define IOS ios::sync_with_stdio(0);cin.tie(0);\n\n\nconst int maxn = 222222; \nint MAX[maxn<<2]; \n\n\nvoid PushUP(int id) { \n MAX[id] = max(MAX[id<<1] , MAX[id<<1|1]); \n} \n\n\nvoid build(int l,int r,int id) { \n if (l == r) { \n scanf(\"%d\",&MAX[id]); \n return ; \n } \n int mid = (l + r) >> 1; \n build(lson); \n build(rson); \n PushUP(id); \n} \nvoid update(int p,int sc,int l,int r,int id) { \n if (l == r) { \n MAX[id] = sc; \n return ; \n } \n int mid = (l + r) >> 1; \n if (p <= m) update(p , sc , lson); \n else update(p , sc , rson); \n PushUP(id); \n} \nint query(int L,int R,int l,int r,int id) { \n if (L <= l && r <= R) { \n return MAX[id]; \n } \n int mid = (l + r) >> 1; \n int ret = 0; \n if (L <= m) ret = max(ret , query(L , R , lson)); \n if (R > m) ret = max(ret , query(L , R , rson)); \n return ret; \n} \nint n , m; \n\n\nvoid Init(){\n\n\tbuild(1 , n , 1); \n\treturn ;\n}\n\nvoid Solve(){\n\t\n\twhile (m --) { \n char op[2]; \n int a , b; \n scanf(\"%s%d%d\",op,&a,&b); \n if (op[0] == 'Q') printf(\"%d\\n\",query(a , b , 1 , n , 1)); \n else update(a , b , 1 , n , 1); \n } \n\treturn ;\n}\n\nint main(){\n#ifdef LOCAL\n\tfreopen(\"hdu1754.in\",\"r\",stdin);\n#endif\n\n\twhile (~scanf(\"%d%d\",&n,&m))\n\tInit(),Solve();\n\treturn 0;\n}hdu1754.cp<commit_msg>update hdu1754<commit_after>#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <queue>\n#include <map>\n#include <set>\n#include <stack>\n#include <cstring>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <cmath>\n#include <list>\n#include <bitset>\n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pair<int, int>pii;\ntypedef pair<ll, ll>pll;\ntypedef pair<double, double>pdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<<endl;\n#define IOS ios::sync_with_stdio(0);cin.tie(0);\n\n\nconst int maxn = 222222; \nint MAX[maxn<<2]; \n\n\nvoid PushUP(int id) { \n MAX[id] = max(MAX[id<<1] , MAX[id<<1|1]); \n} \n\n\nvoid build(int l,int r,int id) { \n if (l == r) { \n scanf(\"%d\",&MAX[id]); \n return ; \n } \n int mid = (l + r) >> 1; \n build(lson); \n build(rson); \n PushUP(id); \n} \nvoid update(int p,int sc,int l,int r,int id) { \n if (l == r) { \n MAX[id] = sc; \n return ; \n } \n int mid = (l + r) >> 1; \n if (p <= mid) update(p , sc , lson); \n else update(p , sc , rson); \n PushUP(id); \n} \nint query(int L,int R,int l,int r,int id) { \n if (L <= l && r <= R) { \n return MAX[id]; \n } \n int mid = (l + r) >> 1; \n int ret = 0; \n if (L <= mid) ret = max(ret , query(L , R , lson)); \n if (R > mid) ret = max(ret , query(L , R , rson)); \n return ret; \n} \nint n , m; \n\n\nvoid Init(){\n\n\tbuild(1 , n , 1); \n\treturn ;\n}\n\nvoid Solve(){\n\t\n\twhile (m --) { \n char op[2]; \n int a , b; \n scanf(\"%s%d%d\",op,&a,&b); \n if (op[0] == 'Q') printf(\"%d\\n\",query(a , b , 1 , n , 1)); \n else update(a , b , 1 , n , 1); \n } \n\treturn ;\n}\n\nint main(){\n#ifdef LOCAL\n\tfreopen(\"hdu1754.in\",\"r\",stdin);\n#endif\n\n\twhile (~scanf(\"%d%d\",&n,&m))\n\tInit(),Solve();\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>#define _USE_MATH_DEFINES\n#include <cmath>\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <time.h>\n\n#include \"edflib.h\"\n#include \"eeg_spectrogram.h\"\n\n#define max(a,b) \\\n ({ __typeof__ (a) _a = (a); \\\n __typeof__ (b) _b = (b); \\\n _a > _b ? _a : _b; })\n\n#define min(a,b) \\\n ({ __typeof__ (a) _a = (a); \\\n __typeof__ (b) _b = (b); \\\n _a < _b ? _a : _b; })\n\n#include <time.h>\n#include <sys\/time.h>\n\n#define N 10\n\n\/\/ should use a hashmap + linked list implementation if the\n\/\/ list traversal becomes a bottleneck\nvoid print_hdr_cache()\n{\n printf(\"[\\n\");\n for (int i = 0; i < EDFLIB_MAXFILES; i++)\n {\n if (EDF_HDR_CACHE[i] == NULL)\n {\n printf(\"-,\");\n }\n else\n {\n printf(\"%s,\\n\", EDF_HDR_CACHE[i]->path);\n }\n }\n printf(\"]\\n\");\n}\n\nedf_hdr_struct* get_hdr_cache(const char *filename)\n{\n for (int i = 0; i < EDFLIB_MAXFILES; i++)\n {\n if (EDF_HDR_CACHE[i] != NULL)\n {\n if (!(strcmp(filename, EDF_HDR_CACHE[i]->path)))\n {\n edf_hdr_struct* hdr = EDF_HDR_CACHE[i];\n \/\/ TODO(joshblum): probably remove this once\n \/\/ windowing is fully implemented\n for (int signal = 0; signal < hdr->edfsignals; signal++)\n {\n edfrewind(hdr->handle, signal);\n }\n return hdr;\n }\n }\n }\n\n return NULL;\n}\n\nvoid set_hdr_cache(edf_hdr_struct* hdr)\n{\n for (int i = 0; i < EDFLIB_MAXFILES; i++)\n {\n if (EDF_HDR_CACHE[i] == NULL)\n {\n EDF_HDR_CACHE[i] = hdr;\n break;\n }\n }\n}\n\nvoid pop_hdr_cache(const char* filename)\n{\n for (int i = 0; i < EDFLIB_MAXFILES; i++)\n {\n if (EDF_HDR_CACHE[i] != NULL)\n {\n if (!(strcmp(filename, EDF_HDR_CACHE[i]->path)))\n {\n free(EDF_HDR_CACHE[i]);\n EDF_HDR_CACHE[i] = NULL;\n }\n }\n }\n}\n\nunsigned long long getticks()\n{\n struct timeval t;\n gettimeofday(&t, 0);\n return t.tv_sec * 1000000ULL + t.tv_usec;\n}\n\ndouble ticks_to_seconds(unsigned long long ticks)\n{\n return ticks * 1.0e-6;\n}\n\n\nvoid log_time_diff(unsigned long long ticks)\n{\n double diff = ticks_to_seconds(ticks);\n printf(\"Time taken %.2f seconds\\n\", diff);\n}\n\nvoid print_spec_params_t(spec_params_t* spec_params)\n{\n printf(\"spec_params: {\\n\");\n printf(\"\\tfilename: %s\\n\", spec_params->filename);\n printf(\"\\tduration: %.2f\\n\", spec_params->duration);\n printf(\"\\thdl: %d\\n\", spec_params->hdl);\n printf(\"\\tnfft: %d\\n\", spec_params->nfft);\n printf(\"\\tnstep: %d\\n\", spec_params->nstep);\n printf(\"\\tshift: %d\\n\", spec_params->shift);\n printf(\"\\tnsamples: %d\\n\", spec_params->nsamples);\n printf(\"\\tnblocks: %d\\n\", spec_params->nblocks);\n printf(\"\\tnfreqs: %d\\n\", spec_params->nfreqs);\n printf(\"\\tspec_len: %d\\n\", spec_params->spec_len);\n printf(\"\\tfs: %d\\n\", spec_params->fs);\n printf(\"}\\n\");\n}\n\nint get_data_len(edf_hdr_struct* hdr)\n{\n \/\/ assume all signals have a uniform sample rate\n return hdr->signalparam[0].smp_in_file;\n}\n\nint get_nfft(int shift, int pad)\n{\n return max(get_next_pow_2(shift) + pad, shift);\n}\n\nint get_nsamples(int data_len, int fs, float duration)\n{\n return min(data_len, fs * 60 * 60 * duration);\n}\n\nint get_nblocks(int nsamples, int nfft, int shift)\n{\n return (nsamples - nfft) \/ shift + 1;\n}\n\nint get_nfreqs(int nfft)\n{\n return nfft \/ 2 + 1;\n}\n\nint get_next_pow_2(unsigned int v)\n{\n v--;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v++;\n return v;\n}\n\nint get_fs(edf_hdr_struct* hdr)\n{\n return ((double)hdr->signalparam[0].smp_in_datarecord \/ (double)hdr->datarecord_duration) * EDFLIB_TIME_DIMENSION;\n}\n\nvoid get_eeg_spectrogram_params(spec_params_t* spec_params,\n char* filename, float duration)\n{\n \/\/ TODO(joshblum): implement full multitaper method\n \/\/ and remove hard coding\n spec_params->filename = filename;\n spec_params->duration = duration;\n\n edf_hdr_struct hdr;\n load_edf(&hdr, filename);\n spec_params->hdl = hdr.handle;\n\n spec_params->fs = get_fs(&hdr);\n\n int data_len = get_data_len(&hdr);\n int pad = 0;\n spec_params->shift = spec_params->fs * 4;\n spec_params->nstep = spec_params->fs * 1;\n spec_params->nfft = get_nfft(spec_params->shift, pad);\n spec_params->nsamples = get_nsamples(data_len, spec_params->fs, duration);\n spec_params->nblocks = get_nblocks(spec_params->nsamples,\n spec_params->shift, spec_params->nstep);\n spec_params->nfreqs = get_nfreqs(spec_params->nfft);\n spec_params->spec_len = spec_params->nsamples \/ spec_params->fs;\n}\n\nvoid load_edf(edf_hdr_struct* hdr, char* filename)\n{\n edf_hdr_struct* cached_hdr = get_hdr_cache(filename);\n if (cached_hdr != NULL)\n {\n \/\/ get the file from the cache\n hdr = cached_hdr;\n return;\n }\n if (edfopen_file_readonly(filename, hdr, EDFLIB_READ_ALL_ANNOTATIONS))\n {\n switch (hdr->filetype)\n {\n case EDFLIB_MALLOC_ERROR :\n printf(\"\\nmalloc error\\n\\n\");\n break;\n case EDFLIB_NO_SUCH_FILE_OR_DIRECTORY :\n printf(\"\\ncannot open file, no such file or directory: %s\\n\\n\", filename);\n break;\n case EDFLIB_FILE_CONTAINS_FORMAT_ERRORS :\n printf(\"\\nthe file is not EDF(+) or BDF(+) compliant\\n\"\n \"(it contains format errors)\\n\\n\");\n break;\n case EDFLIB_MAXFILES_REACHED :\n printf(\"\\nto many files opened\\n\\n\");\n break;\n case EDFLIB_FILE_READ_ERROR :\n printf(\"\\na read error occurred\\n\\n\");\n break;\n case EDFLIB_FILE_ALREADY_OPENED :\n printf(\"\\nfile has already been opened\\n\\n\");\n break;\n default :\n printf(\"\\nunknown error\\n\\n\");\n break;\n }\n exit(1);\n }\n \/\/ set the file in the cache\n set_hdr_cache(hdr);\n}\n\n\/\/ TODO(joshblum): implement a call to this on websocket close\nvoid close_edf(char* filename)\n{\n edf_hdr_struct* hdr = get_hdr_cache(filename);\n edfclose_file(hdr->handle);\n pop_hdr_cache(filename);\n}\n\ndouble* create_buffer(int n, int hdl)\n{\n double* buf = (double * ) malloc(sizeof(double[n]));\n if (buf == NULL)\n {\n printf(\"\\nmalloc error\\n\");\n edfclose_file(hdl);\n exit(1);\n }\n return buf;\n}\n\nint read_samples(int hdl, int ch, int n, double *buf)\n{\n int bytes_read = edfread_physical_samples(hdl, ch, n, buf);\n\n if (bytes_read == -1)\n {\n printf(\"\\nerror: edf_read_physical_samples()\\n\");\n edfclose_file(hdl);\n free(buf);\n exit(1);\n }\n \/\/ clear buffer in case we didn't read as much as we expected to\n for (int i = bytes_read; i < n; i++) {\n buf[i] = 0.0;\n }\n return bytes_read;\n}\n\n\/\/ Create a hamming window of windowLength samples in buffer\nvoid hamming(int windowLength, double* buffer)\n{\n for (int i = 0; i < windowLength; i++)\n {\n buffer[i] = 0.54 - (0.46 * cos( 2 * M_PI * (i \/ ((windowLength - 1) * 1.0))));\n }\n}\n\nstatic inline double abs(fftw_complex* arr, int i)\n{\n return sqrt(arr[i][0] * arr[i][0] + arr[i][1] * arr[i][1]);\n}\n\n\/\/ copy pasta http:\/\/ofdsp.blogspot.co.il\/2011\/08\/short-time-fourier-transform-with-fftw3.html\n\/*\n * Fill the `specs` matrix with values for the spectrogram for the given diff.\n * `specs` is expected to be initialized and the results are added to allow averaging\n *\/\nvoid STFT(arma::rowvec& diff, spec_params_t* spec_params, arma::mat& specs)\n{\n fftw_complex *data, *fft_result;\n fftw_plan plan_forward;\n int nfft = spec_params->nfft;\n\n int nstep = spec_params->nstep;\n\n int nblocks = spec_params->nblocks;\n int nfreqs = spec_params->nfreqs;\n int nsamples = spec_params->nsamples;\n\n data = ( fftw_complex* ) fftw_malloc( sizeof( fftw_complex ) * nfft);\n fft_result = ( fftw_complex* ) fftw_malloc( sizeof( fftw_complex ) * nfft);\n \/\/ TODO keep plans in memory until end, create plans once and cache?\n plan_forward = fftw_plan_dft_1d(nfft, data, fft_result,\n FFTW_FORWARD, FFTW_ESTIMATE);\n\n \/\/ Create a hamming window of appropriate length\n double window[nfft];\n hamming(nfft, window);\n\n for (int idx = 0; idx < nblocks; idx++)\n {\n \/\/ get the last chunk\n if (idx * nstep + nfft > nsamples)\n {\n int upper_bound = nsamples - idx * nstep;\n for (int i = 0; i < upper_bound; i++)\n {\n data[i][0] = diff(idx * nstep + i) * window[i];\n data[i][1] = 0.0;\n\n }\n for (int i = upper_bound; i < nfft; i++)\n {\n data[i][0] = 0.0;\n data[i][1] = 0.0;\n }\n break;\n }\n else\n {\n for (int i = 0; i < nfft; i++)\n {\n \/\/ TODO vector multiplication?\n data[i][0] = diff(idx * nstep + i) * window[i];\n data[i][1] = 0.0;\n }\n }\n\n \/\/ Perform the FFT on our chunk\n fftw_execute( plan_forward );\n\n \/\/ TODO: change maybe?\n \/\/ http:\/\/www.fftw.org\/fftw2_doc\/fftw_2.html\n for (int i = 0; i < nfreqs; i++)\n {\n specs(i, idx) += abs(fft_result, i) \/ nfft;\n }\n\n \/\/ Uncomment to see the raw-data output from the FFT calculation\n \/\/ printf(\"[ \");\n \/\/ for (int i = 0 ; i < 10 ; i++ )\n \/\/ {\n \/\/ printf(\"%2.2f \", specs(i, idx));\n \/\/ }\n \/\/ printf(\"]\\n\");\n }\n\n fftw_destroy_plan( plan_forward );\n\n fftw_free( data );\n fftw_free( fft_result );\n}\n\nvoid eeg_file_spectrogram_handler(char* filename, float duration, int ch, float* out)\n{\n spec_params_t spec_params;\n get_eeg_spectrogram_params(&spec_params, filename, duration);\n print_spec_params_t(&spec_params);\n eeg_spectrogram_handler(&spec_params, ch, out);\n}\n\nvoid eeg_spectrogram_handler(spec_params_t* spec_params, int ch, float* out)\n{\n if (out == NULL)\n {\n out = (float *) malloc(sizeof(float) * spec_params->nblocks * spec_params->nfreqs);\n }\n eeg_spectrogram(spec_params, ch, out);\n}\n\nvoid eeg_spectrogram(spec_params_t* spec_params, int ch, float* out)\n{\n \/\/ TODO reuse buffers\n \/\/ TODO chunking?\n \/\/ write edf method to do diff on the fly?\n int nsamples = spec_params->nsamples;\n double* buf1 = create_buffer(nsamples, spec_params->hdl);\n double* buf2 = create_buffer(nsamples, spec_params->hdl);\n\n \/\/ nfreqs x nblocks matrix\n arma::mat specs(spec_params->nfreqs, spec_params->nblocks);\n specs.fill(0);\n\n int ch_idx1, ch_idx2;\n ch_idx1 = DIFFERENCE_PAIRS[ch].ch_idx[0];\n read_samples(spec_params->hdl, ch_idx1, nsamples, buf1);\n for (int i = 1; i < NUM_DIFFS; i++)\n {\n ch_idx2 = DIFFERENCE_PAIRS[ch].ch_idx[i];\n read_samples(spec_params->hdl, ch_idx2, nsamples, buf2);\n\n \/\/ TODO use arma::rowvec::fixed with fixed size chunks\n arma::rowvec v1 = arma::rowvec(buf1, nsamples);\n arma::rowvec v2 = arma::rowvec(buf2, nsamples);\n arma::rowvec diff = v2 - v1;\n\n \/\/ fill in the spec matrix with fft values\n STFT(diff, spec_params, specs);\n std::swap(buf1, buf2);\n }\n \/\/ TODO serialize specs output for each channel\n specs \/= (NUM_DIFFS - 1); \/\/ average diff spectrograms\n\n \/\/ tranpose the output\n for (int i = 0; i < spec_params->nfreqs; i++)\n {\n for (int j = 0; j < spec_params->nblocks; j++)\n {\n *(out + i + j*spec_params->nfreqs) = (float) specs(i, j);\n }\n }\n\n}\n<commit_msg>dont exit!<commit_after>#define _USE_MATH_DEFINES\n#include <cmath>\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <time.h>\n\n#include \"edflib.h\"\n#include \"eeg_spectrogram.h\"\n\n#define max(a,b) \\\n ({ __typeof__ (a) _a = (a); \\\n __typeof__ (b) _b = (b); \\\n _a > _b ? _a : _b; })\n\n#define min(a,b) \\\n ({ __typeof__ (a) _a = (a); \\\n __typeof__ (b) _b = (b); \\\n _a < _b ? _a : _b; })\n\n#include <time.h>\n#include <sys\/time.h>\n\n#define N 10\n\n\/\/ should use a hashmap + linked list implementation if the\n\/\/ list traversal becomes a bottleneck\nvoid print_hdr_cache()\n{\n printf(\"[\\n\");\n for (int i = 0; i < EDFLIB_MAXFILES; i++)\n {\n if (EDF_HDR_CACHE[i] == NULL)\n {\n printf(\"-,\");\n }\n else\n {\n printf(\"%s,\\n\", EDF_HDR_CACHE[i]->path);\n }\n }\n printf(\"]\\n\");\n}\n\nedf_hdr_struct* get_hdr_cache(const char *filename)\n{\n for (int i = 0; i < EDFLIB_MAXFILES; i++)\n {\n if (EDF_HDR_CACHE[i] != NULL)\n {\n if (!(strcmp(filename, EDF_HDR_CACHE[i]->path)))\n {\n edf_hdr_struct* hdr = EDF_HDR_CACHE[i];\n \/\/ TODO(joshblum): probably remove this once\n \/\/ windowing is fully implemented\n for (int signal = 0; signal < hdr->edfsignals; signal++)\n {\n edfrewind(hdr->handle, signal);\n }\n return hdr;\n }\n }\n }\n\n return NULL;\n}\n\nvoid set_hdr_cache(edf_hdr_struct* hdr)\n{\n for (int i = 0; i < EDFLIB_MAXFILES; i++)\n {\n if (EDF_HDR_CACHE[i] == NULL)\n {\n EDF_HDR_CACHE[i] = hdr;\n break;\n }\n }\n}\n\nvoid pop_hdr_cache(const char* filename)\n{\n for (int i = 0; i < EDFLIB_MAXFILES; i++)\n {\n if (EDF_HDR_CACHE[i] != NULL)\n {\n if (!(strcmp(filename, EDF_HDR_CACHE[i]->path)))\n {\n free(EDF_HDR_CACHE[i]);\n EDF_HDR_CACHE[i] = NULL;\n }\n }\n }\n}\n\nunsigned long long getticks()\n{\n struct timeval t;\n gettimeofday(&t, 0);\n return t.tv_sec * 1000000ULL + t.tv_usec;\n}\n\ndouble ticks_to_seconds(unsigned long long ticks)\n{\n return ticks * 1.0e-6;\n}\n\n\nvoid log_time_diff(unsigned long long ticks)\n{\n double diff = ticks_to_seconds(ticks);\n printf(\"Time taken %.2f seconds\\n\", diff);\n}\n\nvoid print_spec_params_t(spec_params_t* spec_params)\n{\n printf(\"spec_params: {\\n\");\n printf(\"\\tfilename: %s\\n\", spec_params->filename);\n printf(\"\\tduration: %.2f\\n\", spec_params->duration);\n printf(\"\\thdl: %d\\n\", spec_params->hdl);\n printf(\"\\tnfft: %d\\n\", spec_params->nfft);\n printf(\"\\tnstep: %d\\n\", spec_params->nstep);\n printf(\"\\tshift: %d\\n\", spec_params->shift);\n printf(\"\\tnsamples: %d\\n\", spec_params->nsamples);\n printf(\"\\tnblocks: %d\\n\", spec_params->nblocks);\n printf(\"\\tnfreqs: %d\\n\", spec_params->nfreqs);\n printf(\"\\tspec_len: %d\\n\", spec_params->spec_len);\n printf(\"\\tfs: %d\\n\", spec_params->fs);\n printf(\"}\\n\");\n}\n\nint get_data_len(edf_hdr_struct* hdr)\n{\n \/\/ assume all signals have a uniform sample rate\n return hdr->signalparam[0].smp_in_file;\n}\n\nint get_nfft(int shift, int pad)\n{\n return max(get_next_pow_2(shift) + pad, shift);\n}\n\nint get_nsamples(int data_len, int fs, float duration)\n{\n return min(data_len, fs * 60 * 60 * duration);\n}\n\nint get_nblocks(int nsamples, int nfft, int shift)\n{\n return (nsamples - nfft) \/ shift + 1;\n}\n\nint get_nfreqs(int nfft)\n{\n return nfft \/ 2 + 1;\n}\n\nint get_next_pow_2(unsigned int v)\n{\n v--;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v++;\n return v;\n}\n\nint get_fs(edf_hdr_struct* hdr)\n{\n return ((double)hdr->signalparam[0].smp_in_datarecord \/ (double)hdr->datarecord_duration) * EDFLIB_TIME_DIMENSION;\n}\n\nvoid get_eeg_spectrogram_params(spec_params_t* spec_params,\n char* filename, float duration)\n{\n \/\/ TODO(joshblum): implement full multitaper method\n \/\/ and remove hard coding\n spec_params->filename = filename;\n spec_params->duration = duration;\n\n edf_hdr_struct hdr;\n load_edf(&hdr, filename);\n spec_params->hdl = hdr.handle;\n\n spec_params->fs = get_fs(&hdr);\n\n int data_len = get_data_len(&hdr);\n int pad = 0;\n spec_params->shift = spec_params->fs * 4;\n spec_params->nstep = spec_params->fs * 1;\n spec_params->nfft = get_nfft(spec_params->shift, pad);\n spec_params->nsamples = get_nsamples(data_len, spec_params->fs, duration);\n spec_params->nblocks = get_nblocks(spec_params->nsamples,\n spec_params->shift, spec_params->nstep);\n spec_params->nfreqs = get_nfreqs(spec_params->nfft);\n spec_params->spec_len = spec_params->nsamples \/ spec_params->fs;\n}\n\nvoid load_edf(edf_hdr_struct* hdr, char* filename)\n{\n edf_hdr_struct* cached_hdr = get_hdr_cache(filename);\n if (cached_hdr != NULL)\n {\n \/\/ get the file from the cache\n hdr = cached_hdr;\n return;\n }\n if (edfopen_file_readonly(filename, hdr, EDFLIB_READ_ALL_ANNOTATIONS))\n {\n switch (hdr->filetype)\n {\n case EDFLIB_MALLOC_ERROR :\n printf(\"\\nmalloc error\\n\\n\");\n break;\n case EDFLIB_NO_SUCH_FILE_OR_DIRECTORY :\n printf(\"\\ncannot open file, no such file or directory: %s\\n\\n\", filename);\n break;\n case EDFLIB_FILE_CONTAINS_FORMAT_ERRORS :\n printf(\"\\nthe file is not EDF(+) or BDF(+) compliant\\n\"\n \"(it contains format errors)\\n\\n\");\n break;\n case EDFLIB_MAXFILES_REACHED :\n printf(\"\\nto many files opened\\n\\n\");\n break;\n case EDFLIB_FILE_READ_ERROR :\n printf(\"\\na read error occurred\\n\\n\");\n break;\n case EDFLIB_FILE_ALREADY_OPENED :\n printf(\"\\nfile has already been opened\\n\\n\");\n break;\n default :\n printf(\"\\nunknown error\\n\\n\");\n break;\n }\n }\n \/\/ set the file in the cache\n set_hdr_cache(hdr);\n}\n\n\/\/ TODO(joshblum): implement a call to this on websocket close\nvoid close_edf(char* filename)\n{\n edf_hdr_struct* hdr = get_hdr_cache(filename);\n edfclose_file(hdr->handle);\n pop_hdr_cache(filename);\n}\n\ndouble* create_buffer(int n, int hdl)\n{\n double* buf = (double * ) malloc(sizeof(double[n]));\n if (buf == NULL)\n {\n printf(\"\\nmalloc error\\n\");\n edfclose_file(hdl);\n }\n return buf;\n}\n\nint read_samples(int hdl, int ch, int n, double *buf)\n{\n int bytes_read = edfread_physical_samples(hdl, ch, n, buf);\n\n if (bytes_read == -1)\n {\n printf(\"\\nerror: edf_read_physical_samples()\\n\");\n edfclose_file(hdl);\n free(buf);\n exit(1);\n }\n \/\/ clear buffer in case we didn't read as much as we expected to\n for (int i = bytes_read; i < n; i++) {\n buf[i] = 0.0;\n }\n return bytes_read;\n}\n\n\/\/ Create a hamming window of windowLength samples in buffer\nvoid hamming(int windowLength, double* buffer)\n{\n for (int i = 0; i < windowLength; i++)\n {\n buffer[i] = 0.54 - (0.46 * cos( 2 * M_PI * (i \/ ((windowLength - 1) * 1.0))));\n }\n}\n\nstatic inline double abs(fftw_complex* arr, int i)\n{\n return sqrt(arr[i][0] * arr[i][0] + arr[i][1] * arr[i][1]);\n}\n\n\/\/ copy pasta http:\/\/ofdsp.blogspot.co.il\/2011\/08\/short-time-fourier-transform-with-fftw3.html\n\/*\n * Fill the `specs` matrix with values for the spectrogram for the given diff.\n * `specs` is expected to be initialized and the results are added to allow averaging\n *\/\nvoid STFT(arma::rowvec& diff, spec_params_t* spec_params, arma::mat& specs)\n{\n fftw_complex *data, *fft_result;\n fftw_plan plan_forward;\n int nfft = spec_params->nfft;\n\n int nstep = spec_params->nstep;\n\n int nblocks = spec_params->nblocks;\n int nfreqs = spec_params->nfreqs;\n int nsamples = spec_params->nsamples;\n\n data = ( fftw_complex* ) fftw_malloc( sizeof( fftw_complex ) * nfft);\n fft_result = ( fftw_complex* ) fftw_malloc( sizeof( fftw_complex ) * nfft);\n \/\/ TODO keep plans in memory until end, create plans once and cache?\n plan_forward = fftw_plan_dft_1d(nfft, data, fft_result,\n FFTW_FORWARD, FFTW_ESTIMATE);\n\n \/\/ Create a hamming window of appropriate length\n double window[nfft];\n hamming(nfft, window);\n\n for (int idx = 0; idx < nblocks; idx++)\n {\n \/\/ get the last chunk\n if (idx * nstep + nfft > nsamples)\n {\n int upper_bound = nsamples - idx * nstep;\n for (int i = 0; i < upper_bound; i++)\n {\n data[i][0] = diff(idx * nstep + i) * window[i];\n data[i][1] = 0.0;\n\n }\n for (int i = upper_bound; i < nfft; i++)\n {\n data[i][0] = 0.0;\n data[i][1] = 0.0;\n }\n break;\n }\n else\n {\n for (int i = 0; i < nfft; i++)\n {\n \/\/ TODO vector multiplication?\n data[i][0] = diff(idx * nstep + i) * window[i];\n data[i][1] = 0.0;\n }\n }\n\n \/\/ Perform the FFT on our chunk\n fftw_execute( plan_forward );\n\n \/\/ TODO: change maybe?\n \/\/ http:\/\/www.fftw.org\/fftw2_doc\/fftw_2.html\n for (int i = 0; i < nfreqs; i++)\n {\n specs(i, idx) += abs(fft_result, i) \/ nfft;\n }\n\n \/\/ Uncomment to see the raw-data output from the FFT calculation\n \/\/ printf(\"[ \");\n \/\/ for (int i = 0 ; i < 10 ; i++ )\n \/\/ {\n \/\/ printf(\"%2.2f \", specs(i, idx));\n \/\/ }\n \/\/ printf(\"]\\n\");\n }\n\n fftw_destroy_plan( plan_forward );\n\n fftw_free( data );\n fftw_free( fft_result );\n}\n\nvoid eeg_file_spectrogram_handler(char* filename, float duration, int ch, float* out)\n{\n spec_params_t spec_params;\n get_eeg_spectrogram_params(&spec_params, filename, duration);\n print_spec_params_t(&spec_params);\n eeg_spectrogram_handler(&spec_params, ch, out);\n}\n\nvoid eeg_spectrogram_handler(spec_params_t* spec_params, int ch, float* out)\n{\n if (out == NULL)\n {\n out = (float *) malloc(sizeof(float) * spec_params->nblocks * spec_params->nfreqs);\n }\n eeg_spectrogram(spec_params, ch, out);\n}\n\nvoid eeg_spectrogram(spec_params_t* spec_params, int ch, float* out)\n{\n \/\/ TODO reuse buffers\n \/\/ TODO chunking?\n \/\/ write edf method to do diff on the fly?\n int nsamples = spec_params->nsamples;\n double* buf1 = create_buffer(nsamples, spec_params->hdl);\n double* buf2 = create_buffer(nsamples, spec_params->hdl);\n\n \/\/ nfreqs x nblocks matrix\n arma::mat specs(spec_params->nfreqs, spec_params->nblocks);\n specs.fill(0);\n\n int ch_idx1, ch_idx2;\n ch_idx1 = DIFFERENCE_PAIRS[ch].ch_idx[0];\n read_samples(spec_params->hdl, ch_idx1, nsamples, buf1);\n for (int i = 1; i < NUM_DIFFS; i++)\n {\n ch_idx2 = DIFFERENCE_PAIRS[ch].ch_idx[i];\n read_samples(spec_params->hdl, ch_idx2, nsamples, buf2);\n\n \/\/ TODO use arma::rowvec::fixed with fixed size chunks\n arma::rowvec v1 = arma::rowvec(buf1, nsamples);\n arma::rowvec v2 = arma::rowvec(buf2, nsamples);\n arma::rowvec diff = v2 - v1;\n\n \/\/ fill in the spec matrix with fft values\n STFT(diff, spec_params, specs);\n std::swap(buf1, buf2);\n }\n \/\/ TODO serialize specs output for each channel\n specs \/= (NUM_DIFFS - 1); \/\/ average diff spectrograms\n\n \/\/ tranpose the output\n for (int i = 0; i < spec_params->nfreqs; i++)\n {\n for (int j = 0; j < spec_params->nblocks; j++)\n {\n *(out + i + j*spec_params->nfreqs) = (float) specs(i, j);\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"httprpc.h\"\n\n#include \"base58.h\"\n#include \"chainparams.h\"\n#include \"httpserver.h\"\n#include \"rpc\/protocol.h\"\n#include \"rpc\/server.h\"\n#include \"random.h\"\n#include \"sync.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include \"ui_interface.h\"\n#include \"crypto\/hmac_sha256.h\"\n#include <stdio.h>\n#include \"utilstrencodings.h\"\n\n#include <boost\/algorithm\/string.hpp> \/\/ boost::trim\n#include <boost\/foreach.hpp> \/\/BOOST_FOREACH\n\n\/** WWW-Authenticate to present with 401 Unauthorized response *\/\nstatic const char* WWW_AUTH_HEADER_DATA = \"Basic realm=\\\"jsonrpc\\\"\";\n\n\/** Simple one-shot callback timer to be used by the RPC mechanism to e.g.\n * re-lock the wallet.\n *\/\nclass HTTPRPCTimer : public RPCTimerBase\n{\npublic:\n HTTPRPCTimer(struct event_base* eventBase, boost::function<void(void)>& func, int64_t millis) :\n ev(eventBase, false, func)\n {\n struct timeval tv;\n tv.tv_sec = millis\/1000;\n tv.tv_usec = (millis%1000)*1000;\n ev.trigger(&tv);\n }\nprivate:\n HTTPEvent ev;\n};\n\nclass HTTPRPCTimerInterface : public RPCTimerInterface\n{\npublic:\n HTTPRPCTimerInterface(struct event_base* _base) : base(_base)\n {\n }\n const char* Name()\n {\n return \"HTTP\";\n }\n RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis)\n {\n return new HTTPRPCTimer(base, func, millis);\n }\nprivate:\n struct event_base* base;\n};\n\n\n\/* Pre-base64-encoded authentication token *\/\nstatic std::string strRPCUserColonPass;\n\/* Stored RPC timer interface (for unregistration) *\/\nstatic HTTPRPCTimerInterface* httpRPCTimerInterface = 0;\n\nstatic void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)\n{\n \/\/ Send error reply from json-rpc error object\n int nStatus = HTTP_INTERNAL_SERVER_ERROR;\n int code = find_value(objError, \"code\").get_int();\n\n if (code == RPC_INVALID_REQUEST)\n nStatus = HTTP_BAD_REQUEST;\n else if (code == RPC_METHOD_NOT_FOUND)\n nStatus = HTTP_NOT_FOUND;\n\n std::string strReply = JSONRPCReply(NullUniValue, objError, id);\n\n req->WriteHeader(\"Content-Type\", \"application\/json\");\n req->WriteReply(nStatus, strReply);\n}\n\n\/\/This function checks username and password against -rpcauth\n\/\/entries from config file.\nstatic bool multiUserAuthorized(std::string strUserPass)\n{ \n if (strUserPass.find(\":\") == std::string::npos) {\n return false;\n }\n std::string strUser = strUserPass.substr(0, strUserPass.find(\":\"));\n std::string strPass = strUserPass.substr(strUserPass.find(\":\") + 1);\n\n if (mapMultiArgs.count(\"-rpcauth\") > 0) {\n \/\/Search for multi-user login\/pass \"rpcauth\" from config\n BOOST_FOREACH(std::string strRPCAuth, mapMultiArgs.at(\"-rpcauth\"))\n {\n std::vector<std::string> vFields;\n boost::split(vFields, strRPCAuth, boost::is_any_of(\":$\"));\n if (vFields.size() != 3) {\n \/\/Incorrect formatting in config file\n continue;\n }\n\n std::string strName = vFields[0];\n if (!TimingResistantEqual(strName, strUser)) {\n continue;\n }\n\n std::string strSalt = vFields[1];\n std::string strHash = vFields[2];\n\n unsigned int KEY_SIZE = 32;\n unsigned char out[KEY_SIZE];\n\n CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.c_str()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.c_str()), strPass.size()).Finalize(out);\n std::vector<unsigned char> hexvec(out, out+KEY_SIZE);\n std::string strHashFromPass = HexStr(hexvec);\n\n if (TimingResistantEqual(strHashFromPass, strHash)) {\n return true;\n }\n }\n }\n return false;\n}\n\nstatic bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)\n{\n if (strRPCUserColonPass.empty()) \/\/ Belt-and-suspenders measure if InitRPCAuthentication was not called\n return false;\n if (strAuth.substr(0, 6) != \"Basic \")\n return false;\n std::string strUserPass64 = strAuth.substr(6);\n boost::trim(strUserPass64);\n std::string strUserPass = DecodeBase64(strUserPass64);\n\n if (strUserPass.find(\":\") != std::string::npos)\n strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(\":\"));\n\n \/\/Check if authorized under single-user field\n if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {\n return true;\n }\n return multiUserAuthorized(strUserPass);\n}\n\nstatic bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)\n{\n \/\/ JSONRPC handles only POST\n if (req->GetRequestMethod() != HTTPRequest::POST) {\n req->WriteReply(HTTP_BAD_METHOD, \"JSONRPC server handles only POST requests\");\n return false;\n }\n \/\/ Check authorization\n std::pair<bool, std::string> authHeader = req->GetHeader(\"authorization\");\n if (!authHeader.first) {\n req->WriteHeader(\"WWW-Authenticate\", WWW_AUTH_HEADER_DATA);\n req->WriteReply(HTTP_UNAUTHORIZED);\n return false;\n }\n\n JSONRPCRequest jreq;\n if (!RPCAuthorized(authHeader.second, jreq.authUser)) {\n LogPrintf(\"ThreadRPCServer incorrect password attempt from %s\\n\", req->GetPeer().ToString());\n\n \/* Deter brute-forcing\n If this results in a DoS the user really\n shouldn't have their RPC port exposed. *\/\n MilliSleep(250);\n\n req->WriteHeader(\"WWW-Authenticate\", WWW_AUTH_HEADER_DATA);\n req->WriteReply(HTTP_UNAUTHORIZED);\n return false;\n }\n\n try {\n \/\/ Parse request\n UniValue valRequest;\n if (!valRequest.read(req->ReadBody()))\n throw JSONRPCError(RPC_PARSE_ERROR, \"Parse error\");\n\n \/\/ Set the URI\n jreq.URI = req->GetURI();\n\n std::string strReply;\n \/\/ singleton request\n if (valRequest.isObject()) {\n jreq.parse(valRequest);\n\n UniValue result = tableRPC.execute(jreq);\n\n \/\/ Send reply\n strReply = JSONRPCReply(result, NullUniValue, jreq.id);\n\n \/\/ array of requests\n } else if (valRequest.isArray())\n strReply = JSONRPCExecBatch(valRequest.get_array());\n else\n throw JSONRPCError(RPC_PARSE_ERROR, \"Top-level object parse error\");\n\n req->WriteHeader(\"Content-Type\", \"application\/json\");\n req->WriteReply(HTTP_OK, strReply);\n } catch (const UniValue& objError) {\n JSONErrorReply(req, objError, jreq.id);\n return false;\n } catch (const std::exception& e) {\n JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);\n return false;\n }\n return true;\n}\n\nstatic bool InitRPCAuthentication()\n{\n if (GetArg(\"-rpcpassword\", \"\") == \"\")\n {\n LogPrintf(\"No rpcpassword set - using random cookie authentication\\n\");\n if (!GenerateAuthCookie(&strRPCUserColonPass)) {\n uiInterface.ThreadSafeMessageBox(\n _(\"Error: A fatal internal error occurred, see debug.log for details\"), \/\/ Same message as AbortNode\n \"\", CClientUIInterface::MSG_ERROR);\n return false;\n }\n } else {\n LogPrintf(\"Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share\/rpcuser for rpcauth auth generation.\\n\");\n strRPCUserColonPass = GetArg(\"-rpcuser\", \"\") + \":\" + GetArg(\"-rpcpassword\", \"\");\n }\n return true;\n}\n\nbool StartHTTPRPC()\n{\n LogPrint(\"rpc\", \"Starting HTTP RPC server\\n\");\n if (!InitRPCAuthentication())\n return false;\n\n RegisterHTTPHandler(\"\/\", true, HTTPReq_JSONRPC);\n\n assert(EventBase());\n httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());\n RPCSetTimerInterface(httpRPCTimerInterface);\n return true;\n}\n\nvoid InterruptHTTPRPC()\n{\n LogPrint(\"rpc\", \"Interrupting HTTP RPC server\\n\");\n}\n\nvoid StopHTTPRPC()\n{\n LogPrint(\"rpc\", \"Stopping HTTP RPC server\\n\");\n UnregisterHTTPHandler(\"\/\", true);\n if (httpRPCTimerInterface) {\n RPCUnsetTimerInterface(httpRPCTimerInterface);\n delete httpRPCTimerInterface;\n httpRPCTimerInterface = 0;\n }\n}\n<commit_msg>Make KEY_SIZE a compile-time constant<commit_after>\/\/ Copyright (c) 2015-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"httprpc.h\"\n\n#include \"base58.h\"\n#include \"chainparams.h\"\n#include \"httpserver.h\"\n#include \"rpc\/protocol.h\"\n#include \"rpc\/server.h\"\n#include \"random.h\"\n#include \"sync.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include \"ui_interface.h\"\n#include \"crypto\/hmac_sha256.h\"\n#include <stdio.h>\n#include \"utilstrencodings.h\"\n\n#include <boost\/algorithm\/string.hpp> \/\/ boost::trim\n#include <boost\/foreach.hpp> \/\/BOOST_FOREACH\n\n\/** WWW-Authenticate to present with 401 Unauthorized response *\/\nstatic const char* WWW_AUTH_HEADER_DATA = \"Basic realm=\\\"jsonrpc\\\"\";\n\n\/** Simple one-shot callback timer to be used by the RPC mechanism to e.g.\n * re-lock the wallet.\n *\/\nclass HTTPRPCTimer : public RPCTimerBase\n{\npublic:\n HTTPRPCTimer(struct event_base* eventBase, boost::function<void(void)>& func, int64_t millis) :\n ev(eventBase, false, func)\n {\n struct timeval tv;\n tv.tv_sec = millis\/1000;\n tv.tv_usec = (millis%1000)*1000;\n ev.trigger(&tv);\n }\nprivate:\n HTTPEvent ev;\n};\n\nclass HTTPRPCTimerInterface : public RPCTimerInterface\n{\npublic:\n HTTPRPCTimerInterface(struct event_base* _base) : base(_base)\n {\n }\n const char* Name()\n {\n return \"HTTP\";\n }\n RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis)\n {\n return new HTTPRPCTimer(base, func, millis);\n }\nprivate:\n struct event_base* base;\n};\n\n\n\/* Pre-base64-encoded authentication token *\/\nstatic std::string strRPCUserColonPass;\n\/* Stored RPC timer interface (for unregistration) *\/\nstatic HTTPRPCTimerInterface* httpRPCTimerInterface = 0;\n\nstatic void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)\n{\n \/\/ Send error reply from json-rpc error object\n int nStatus = HTTP_INTERNAL_SERVER_ERROR;\n int code = find_value(objError, \"code\").get_int();\n\n if (code == RPC_INVALID_REQUEST)\n nStatus = HTTP_BAD_REQUEST;\n else if (code == RPC_METHOD_NOT_FOUND)\n nStatus = HTTP_NOT_FOUND;\n\n std::string strReply = JSONRPCReply(NullUniValue, objError, id);\n\n req->WriteHeader(\"Content-Type\", \"application\/json\");\n req->WriteReply(nStatus, strReply);\n}\n\n\/\/This function checks username and password against -rpcauth\n\/\/entries from config file.\nstatic bool multiUserAuthorized(std::string strUserPass)\n{ \n if (strUserPass.find(\":\") == std::string::npos) {\n return false;\n }\n std::string strUser = strUserPass.substr(0, strUserPass.find(\":\"));\n std::string strPass = strUserPass.substr(strUserPass.find(\":\") + 1);\n\n if (mapMultiArgs.count(\"-rpcauth\") > 0) {\n \/\/Search for multi-user login\/pass \"rpcauth\" from config\n BOOST_FOREACH(std::string strRPCAuth, mapMultiArgs.at(\"-rpcauth\"))\n {\n std::vector<std::string> vFields;\n boost::split(vFields, strRPCAuth, boost::is_any_of(\":$\"));\n if (vFields.size() != 3) {\n \/\/Incorrect formatting in config file\n continue;\n }\n\n std::string strName = vFields[0];\n if (!TimingResistantEqual(strName, strUser)) {\n continue;\n }\n\n std::string strSalt = vFields[1];\n std::string strHash = vFields[2];\n\n static const unsigned int KEY_SIZE = 32;\n unsigned char out[KEY_SIZE];\n\n CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.c_str()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.c_str()), strPass.size()).Finalize(out);\n std::vector<unsigned char> hexvec(out, out+KEY_SIZE);\n std::string strHashFromPass = HexStr(hexvec);\n\n if (TimingResistantEqual(strHashFromPass, strHash)) {\n return true;\n }\n }\n }\n return false;\n}\n\nstatic bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)\n{\n if (strRPCUserColonPass.empty()) \/\/ Belt-and-suspenders measure if InitRPCAuthentication was not called\n return false;\n if (strAuth.substr(0, 6) != \"Basic \")\n return false;\n std::string strUserPass64 = strAuth.substr(6);\n boost::trim(strUserPass64);\n std::string strUserPass = DecodeBase64(strUserPass64);\n\n if (strUserPass.find(\":\") != std::string::npos)\n strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(\":\"));\n\n \/\/Check if authorized under single-user field\n if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {\n return true;\n }\n return multiUserAuthorized(strUserPass);\n}\n\nstatic bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)\n{\n \/\/ JSONRPC handles only POST\n if (req->GetRequestMethod() != HTTPRequest::POST) {\n req->WriteReply(HTTP_BAD_METHOD, \"JSONRPC server handles only POST requests\");\n return false;\n }\n \/\/ Check authorization\n std::pair<bool, std::string> authHeader = req->GetHeader(\"authorization\");\n if (!authHeader.first) {\n req->WriteHeader(\"WWW-Authenticate\", WWW_AUTH_HEADER_DATA);\n req->WriteReply(HTTP_UNAUTHORIZED);\n return false;\n }\n\n JSONRPCRequest jreq;\n if (!RPCAuthorized(authHeader.second, jreq.authUser)) {\n LogPrintf(\"ThreadRPCServer incorrect password attempt from %s\\n\", req->GetPeer().ToString());\n\n \/* Deter brute-forcing\n If this results in a DoS the user really\n shouldn't have their RPC port exposed. *\/\n MilliSleep(250);\n\n req->WriteHeader(\"WWW-Authenticate\", WWW_AUTH_HEADER_DATA);\n req->WriteReply(HTTP_UNAUTHORIZED);\n return false;\n }\n\n try {\n \/\/ Parse request\n UniValue valRequest;\n if (!valRequest.read(req->ReadBody()))\n throw JSONRPCError(RPC_PARSE_ERROR, \"Parse error\");\n\n \/\/ Set the URI\n jreq.URI = req->GetURI();\n\n std::string strReply;\n \/\/ singleton request\n if (valRequest.isObject()) {\n jreq.parse(valRequest);\n\n UniValue result = tableRPC.execute(jreq);\n\n \/\/ Send reply\n strReply = JSONRPCReply(result, NullUniValue, jreq.id);\n\n \/\/ array of requests\n } else if (valRequest.isArray())\n strReply = JSONRPCExecBatch(valRequest.get_array());\n else\n throw JSONRPCError(RPC_PARSE_ERROR, \"Top-level object parse error\");\n\n req->WriteHeader(\"Content-Type\", \"application\/json\");\n req->WriteReply(HTTP_OK, strReply);\n } catch (const UniValue& objError) {\n JSONErrorReply(req, objError, jreq.id);\n return false;\n } catch (const std::exception& e) {\n JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);\n return false;\n }\n return true;\n}\n\nstatic bool InitRPCAuthentication()\n{\n if (GetArg(\"-rpcpassword\", \"\") == \"\")\n {\n LogPrintf(\"No rpcpassword set - using random cookie authentication\\n\");\n if (!GenerateAuthCookie(&strRPCUserColonPass)) {\n uiInterface.ThreadSafeMessageBox(\n _(\"Error: A fatal internal error occurred, see debug.log for details\"), \/\/ Same message as AbortNode\n \"\", CClientUIInterface::MSG_ERROR);\n return false;\n }\n } else {\n LogPrintf(\"Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share\/rpcuser for rpcauth auth generation.\\n\");\n strRPCUserColonPass = GetArg(\"-rpcuser\", \"\") + \":\" + GetArg(\"-rpcpassword\", \"\");\n }\n return true;\n}\n\nbool StartHTTPRPC()\n{\n LogPrint(\"rpc\", \"Starting HTTP RPC server\\n\");\n if (!InitRPCAuthentication())\n return false;\n\n RegisterHTTPHandler(\"\/\", true, HTTPReq_JSONRPC);\n\n assert(EventBase());\n httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());\n RPCSetTimerInterface(httpRPCTimerInterface);\n return true;\n}\n\nvoid InterruptHTTPRPC()\n{\n LogPrint(\"rpc\", \"Interrupting HTTP RPC server\\n\");\n}\n\nvoid StopHTTPRPC()\n{\n LogPrint(\"rpc\", \"Stopping HTTP RPC server\\n\");\n UnregisterHTTPHandler(\"\/\", true);\n if (httpRPCTimerInterface) {\n RPCUnsetTimerInterface(httpRPCTimerInterface);\n delete httpRPCTimerInterface;\n httpRPCTimerInterface = 0;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ TODO: handle --stop specially in ibb.cpp. it should wait for the server to shut down.\n\n#include <stdio.h>\n#include <string.h>\n#include <stdarg.h>\n\n#ifdef _WIN32\n\n#define WIN32_LEAN_AND_MEAN\n#define STRICT\n#define UNICODE\n#include <winsock2.h>\n#include <shellapi.h>\n#include <shlwapi.h>\n\n\/\/ UTF-16\n\n#define PSTR(x) L ## x\n\ntypedef wchar_t pchar;\nsize_t pstrlen(const pchar* p) {\n return wcslen(p);\n}\nint pprintf(const pchar* format, ...) {\n va_list arg;\n va_start(arg, format);\n int result = vwprintf(format, arg);\n va_end(arg);\n return result;\n}\n\n#else\n\n#include <unistd.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\ntypedef int SOCKET; \/\/ old-school\nconst SOCKET INVALID_SOCKET = -1;\nconst ssize_t SOCKET_ERROR = -1;\nint closesocket(SOCKET socket) {\n return close(socket);\n}\n\n\/\/ UTF-8\n\n#define PSTR(x) x\ntypedef char pchar;\nsize_t pstrlen(const pchar* p) {\n return strlen(p);\n}\nint pprintf(const pchar* format, ...) {\n va_list arg;\n va_start(arg, format);\n int result = vprintf(format, arg);\n va_end(arg);\n return result;\n}\n\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <wchar.h>\n\n\/\/ int(md5.md5('ibb').hexdigest()[-4:], 16)\nconst int IBB_PORT = 26830;\n\nint error(const char* msg) {\n fprintf(stderr, \"ibb *** error: %s\\n\", msg);\n return 1;\n}\n\nbool openServerConnection(SOCKET* s) {\n *s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (*s == INVALID_SOCKET) {\n \/\/ TODO: print error code\n error(\"Failed to create socket\");\n return false;\n }\n\n sockaddr_in address;\n address.sin_family = AF_INET;\n address.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n address.sin_port = htons(IBB_PORT);\n \n int result = connect(*s, reinterpret_cast<sockaddr*>(&address), sizeof(address));\n if (result) {\n return false;\n }\n\n return true;\n}\n\n#ifdef _WIN32\n\nbool startServer() {\n WCHAR executable_path[MAX_PATH * 2];\n DWORD length = GetModuleFileNameW(GetModuleHandle(NULL), executable_path, MAX_PATH);\n if (length == 0 || length == MAX_PATH) {\n fprintf(stderr, \"ibb *** failed to get executable path\\n\");\n return false;\n }\n\n wchar_t* last_slash = wcsrchr(executable_path, '\\\\');\n if (last_slash) {\n *last_slash = 0;\n } else {\n last_slash = executable_path;\n }\n wcsncpy(last_slash, L\"\\\\ibb_server.exe\", MAX_PATH);\n\n if (PathFileExists(executable_path)) {\n \/\/ Launch server executable directly.\n \n \/\/ TODO: use CreateProcess instead of ShellExecute\n \/\/ TODO: print error code\n HINSTANCE result = ShellExecuteW(0, L\"open\", executable_path, executable_path, NULL, SW_SHOW);\n return result > reinterpret_cast<HINSTANCE>(32);\n } else {\n \/\/ Launch server from Python.\n\n WCHAR python_path[MAX_PATH + 1] = {0};\n LONG size = sizeof(python_path);\n LONG success = RegQueryValueW(\n HKEY_LOCAL_MACHINE,\n L\"SOFTWARE\\\\Python\\\\PythonCore\\\\3.1\\\\InstallPath\",\n python_path,\n &size);\n if (!success) {\n \/\/ TODO: print error\n fprintf(stderr, \"ibb *** failed to locate Python 3.1\\n\");\n return false;\n }\n\n \/\/ TODO: use safe strings\n wcsncat(python_path, L\"\\\\python.exe\", MAX_PATH);\n \n wcsncpy(last_slash, L\"\\\\src\\\\ibb.py\", MAX_PATH);\n \n \/\/ TODO: use CreateProcess instead of ShellExecute\n \/\/ TODO: print error code\n HINSTANCE result = ShellExecuteW(0, L\"open\", python_path, executable_path, NULL, SW_SHOW);\n return result > reinterpret_cast<HINSTANCE>(32);\n }\n}\n\n#else\n\n\/\/ Mac\n#include <mach-o\/dyld.h>\n\nbool startServer() {\n uint32_t pathSize = 0;\n \/\/ should return -1\n _NSGetExecutablePath(0, &pathSize);\n\n char executablePath[pathSize];\n if (0 != _NSGetExecutablePath(executablePath, &pathSize)) {\n fprintf(stderr, \"ibb *** failed to get executable path\\n\");\n return false;\n }\n\n \/\/ TODO: Mac deployment (port to Python 2?)\n \/*\n wchar_t* last_slash = wcsrchr(executable_path, '\\\\');\n if (last_slash) {\n *last_slash = 0;\n } else {\n last_slash = executable_path;\n }\n wcsncpy(last_slash, L\"\\\\ibb_server.exe\", MAX_PATH);\n\n if (PathFileExists(executable_path)) {\n \/\/ Launch server executable directly.\n \n \/\/ TODO: use CreateProcess instead of ShellExecute\n \/\/ TODO: print error code\n HINSTANCE result = ShellExecuteW(0, L\"open\", executable_path, executable_path, NULL, SW_SHOW);\n return result > reinterpret_cast<HINSTANCE>(32);\n } else {\n *\/\n\n \/\/ Launch server from Python.\n \/\/ TODO: check for python3\n\n if (0 != system(\"python3 src\/ibb.py &\")) {\n fprintf(stderr, \"ibb *** failed to run ibb.py\\n\");\n return false;\n }\n\n \/\/ TODO: how do you wait for a process to be ready to accept connections?\n\n return true;\n}\n\n#endif\n\nvoid sendString(SOCKET connection, const pchar* begin, const pchar* end = 0) {\n if (!end) {\n end = begin + pstrlen(begin);\n }\n \n \/\/ UTF-16 over the wire on Windows\n \/\/ UTF-32 on Linux and Mac\n send(\n connection,\n reinterpret_cast<const char*>(begin),\n (end - begin) * sizeof(pchar),\n 0);\n\n \/\/ TODO: error checking\n}\n\nstruct ScopedFree {\n explicit ScopedFree(char* p)\n : p(p)\n {}\n\n ~ScopedFree() {\n free(p);\n }\n\nprivate:\n char* p;\n};\n\nbool sendBuild(SOCKET connection, int argc, const pchar* argv[], clock_t start) {\n sendString(connection, PSTR(\"version: 1\\n\"));\n\n sendString(connection, PSTR(\"cwd: \"));\n\n #ifdef _WIN32\n WCHAR current_directory[MAX_PATH] = {0};\n GetCurrentDirectoryW(MAX_PATH, current_directory);\n #else\n char* current_directory = getcwd(0, 0);\n ScopedFree scoped_free(current_directory);\n #endif\n\n sendString(connection, current_directory);\n sendString(connection, PSTR(\"\\n\"));\n\n for (int i = 0; i < argc; ++i) {\n sendString(connection, PSTR(\"arg: \"));\n sendString(connection, argv[i]);\n sendString(connection, PSTR(\"\\n\"));\n }\n\n sendString(connection, PSTR(\"build\\n\"));\n\n \/\/printf(\"Build sent in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n\n for (;;) {\n const int BUFFER_LENGTH = 1024;\n pchar buffer[BUFFER_LENGTH + 1];\n const int bytes = recv(\n connection,\n reinterpret_cast<char*>(buffer),\n sizeof(pchar) * BUFFER_LENGTH,\n 0);\n if (0 == bytes) {\n break;\n }\n if (SOCKET_ERROR == bytes) {\n error(\"Broken connection\");\n break;\n }\n const int chars = bytes \/ sizeof(pchar); \/\/ TODO: handle odd bytes values\n buffer[chars] = 0;\n pprintf(PSTR(\"%s\"), buffer); \/\/ %*s sometimes wrote extra crap at the end\n }\n\n \/\/printf(\"Result recieved in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n\n return true;\n}\n\nint pmain(int argc, const pchar* argv[]) {\n clock_t start = clock();\n\n#ifdef _WIN32\n WSADATA wsadata;\n if (0 != WSAStartup(2, &wsadata)) {\n return error(\"Failed to initialize winsock\");\n }\n\n struct cleanup_t {\n cleanup_t() {}\n ~cleanup_t() { WSACleanup(); }\n } cleanup;\n#endif\n\n \/\/printf(\"Started winsock in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n\n SOCKET connection;\n if (!openServerConnection(&connection)) {\n if (!startServer()) {\n return error(\"Failed to start server\");\n }\n if (!openServerConnection(&connection)) {\n return error(\"Failed to connect to server\");\n }\n }\n\n \/\/printf(\"Opened connection in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n\n if (!sendBuild(connection, argc, argv, start)) {\n return error(\"Failed to submit build\");\n }\n\n closesocket(connection);\n\n \/\/printf(\"Socket closed in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n return 0;\n}\n\n\/\/ hack around mingw's lack of wmain support\n#ifdef _WIN32\n\nint main() {\n int argc;\n WCHAR** argv = CommandLineToArgvW(\n GetCommandLineW(),\n &argc);\n return pmain(argc, const_cast<const wchar_t**>(argv));\n}\n\n#else\n\nint main(int argc, const char* argv[]) {\n return pmain(argc, argv);\n}\n\n#endif\n<commit_msg>make server startup a bit more reliable<commit_after>\/\/ TODO: handle --stop specially in ibb.cpp. it should wait for the server to shut down.\n\n#include <algorithm>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <wchar.h>\n\n#ifdef _WIN32\n\n#define WIN32_LEAN_AND_MEAN\n#define STRICT\n#define UNICODE\n#include <winsock2.h>\n#include <shellapi.h>\n#include <shlwapi.h>\n\n\/\/ UTF-16\n\n#define PSTR(x) L ## x\n\ntypedef wchar_t pchar;\nsize_t pstrlen(const pchar* p) {\n return wcslen(p);\n}\nint pprintf(const pchar* format, ...) {\n va_list arg;\n va_start(arg, format);\n int result = vwprintf(format, arg);\n va_end(arg);\n return result;\n}\n\n#else\n\n#include <unistd.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\ntypedef int SOCKET; \/\/ old-school\nconst SOCKET INVALID_SOCKET = -1;\nconst ssize_t SOCKET_ERROR = -1;\nint closesocket(SOCKET socket) {\n return close(socket);\n}\n\n\/\/ UTF-8\n\n#define PSTR(x) x\ntypedef char pchar;\nsize_t pstrlen(const pchar* p) {\n return strlen(p);\n}\nint pprintf(const pchar* format, ...) {\n va_list arg;\n va_start(arg, format);\n int result = vprintf(format, arg);\n va_end(arg);\n return result;\n}\n\n#endif\n\n\/\/ int(md5.md5('ibb').hexdigest()[-4:], 16)\nconst int IBB_PORT = 26830;\n\nint error(const char* msg) {\n fprintf(stderr, \"ibb *** error: %s\\n\", msg);\n return 1;\n}\n\nenum ConnectionRetry {\n NO_RETRY,\n RETRY\n};\n\nint MAX_RETRY_TIME = 30; \/\/ seconds\n\nbool openServerConnection(SOCKET* s, ConnectionRetry retry) {\n *s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (*s == INVALID_SOCKET) {\n \/\/ TODO: print error code\n error(\"Failed to create socket\");\n return false;\n }\n\n sockaddr_in address;\n address.sin_family = AF_INET;\n address.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n address.sin_port = htons(IBB_PORT);\n \n time_t now = time(0);\n unsigned sleep = 10; \/\/ milliseconds\n for (;;) {\n int result = connect(*s, reinterpret_cast<sockaddr*>(&address), sizeof(address));\n if (result) {\n return false;\n }\n if (retry == RETRY && (time(0) - now) < MAX_RETRY_TIME) {\n usleep(sleep * 1000);\n sleep = std::min(100u, sleep + sleep \/ 2);\n } else {\n break;\n }\n }\n\n return true;\n}\n\n#ifdef _WIN32\n\nbool startServer() {\n WCHAR executable_path[MAX_PATH * 2];\n DWORD length = GetModuleFileNameW(GetModuleHandle(NULL), executable_path, MAX_PATH);\n if (length == 0 || length == MAX_PATH) {\n fprintf(stderr, \"ibb *** failed to get executable path\\n\");\n return false;\n }\n\n wchar_t* last_slash = wcsrchr(executable_path, '\\\\');\n if (last_slash) {\n *last_slash = 0;\n } else {\n last_slash = executable_path;\n }\n wcsncpy(last_slash, L\"\\\\ibb_server.exe\", MAX_PATH);\n\n if (PathFileExists(executable_path)) {\n \/\/ Launch server executable directly.\n \n \/\/ TODO: use CreateProcess instead of ShellExecute\n \/\/ TODO: print error code\n HINSTANCE result = ShellExecuteW(0, L\"open\", executable_path, executable_path, NULL, SW_SHOW);\n return result > reinterpret_cast<HINSTANCE>(32);\n } else {\n \/\/ Launch server from Python.\n\n WCHAR python_path[MAX_PATH + 1] = {0};\n LONG size = sizeof(python_path);\n LONG success = RegQueryValueW(\n HKEY_LOCAL_MACHINE,\n L\"SOFTWARE\\\\Python\\\\PythonCore\\\\3.1\\\\InstallPath\",\n python_path,\n &size);\n if (!success) {\n \/\/ TODO: print error\n fprintf(stderr, \"ibb *** failed to locate Python 3.1\\n\");\n return false;\n }\n\n \/\/ TODO: use safe strings\n wcsncat(python_path, L\"\\\\python.exe\", MAX_PATH);\n \n wcsncpy(last_slash, L\"\\\\src\\\\ibb.py\", MAX_PATH);\n \n \/\/ TODO: use CreateProcess instead of ShellExecute\n \/\/ TODO: print error code\n HINSTANCE result = ShellExecuteW(0, L\"open\", python_path, executable_path, NULL, SW_SHOW);\n return result > reinterpret_cast<HINSTANCE>(32);\n }\n}\n\n#else\n\n\/\/ Mac\n#include <mach-o\/dyld.h>\n\nbool startServer() {\n uint32_t pathSize = 0;\n \/\/ should return -1\n _NSGetExecutablePath(0, &pathSize);\n\n char executablePath[pathSize];\n if (0 != _NSGetExecutablePath(executablePath, &pathSize)) {\n fprintf(stderr, \"ibb *** failed to get executable path\\n\");\n return false;\n }\n\n \/\/ TODO: Mac deployment (port to Python 2?)\n \/*\n wchar_t* last_slash = wcsrchr(executable_path, '\\\\');\n if (last_slash) {\n *last_slash = 0;\n } else {\n last_slash = executable_path;\n }\n wcsncpy(last_slash, L\"\\\\ibb_server.exe\", MAX_PATH);\n\n if (PathFileExists(executable_path)) {\n \/\/ Launch server executable directly.\n \n \/\/ TODO: use CreateProcess instead of ShellExecute\n \/\/ TODO: print error code\n HINSTANCE result = ShellExecuteW(0, L\"open\", executable_path, executable_path, NULL, SW_SHOW);\n return result > reinterpret_cast<HINSTANCE>(32);\n } else {\n *\/\n\n \/\/ Launch server from Python.\n \/\/ TODO: check for python3\n\n \/\/ TODO: figure out how to spawn python3 directory\n \/\/ without going through system()\n \/*\n pid_t child = fork();\n if (child == 0) {\n \/\/ TODO: src\/ibb.py relative to this directory\n execl(\"python3\", \"src\/ibb.py\", static_cast<char*>(0));\n abort(); \/\/ unreachable under success\n } else if (child == -1) {\n return false;\n } else {\n return true;\n }\n *\/\n\n system(\"python3 src\/ibb.py &\");\n\n \/\/ TODO: how do you wait for a process to be ready to accept connections?\n \/\/ TODO: the internet seems to think \"just try to connect for a while\"\n\n return true;\n}\n\n#endif\n\nvoid sendString(SOCKET connection, const pchar* begin, const pchar* end = 0) {\n if (!end) {\n end = begin + pstrlen(begin);\n }\n \n \/\/ UTF-16 over the wire on Windows\n \/\/ UTF-32 on Linux and Mac\n send(\n connection,\n reinterpret_cast<const char*>(begin),\n (end - begin) * sizeof(pchar),\n 0);\n\n \/\/ TODO: error checking\n}\n\nstruct ScopedFree {\n explicit ScopedFree(char* p)\n : p(p)\n {}\n\n ~ScopedFree() {\n free(p);\n }\n\nprivate:\n char* p;\n};\n\nbool sendBuild(SOCKET connection, int argc, const pchar* argv[], clock_t start) {\n sendString(connection, PSTR(\"version: 1\\n\"));\n\n sendString(connection, PSTR(\"cwd: \"));\n\n #ifdef _WIN32\n WCHAR current_directory[MAX_PATH] = {0};\n GetCurrentDirectoryW(MAX_PATH, current_directory);\n #else\n char* current_directory = getcwd(0, 0);\n ScopedFree scoped_free(current_directory);\n #endif\n\n sendString(connection, current_directory);\n sendString(connection, PSTR(\"\\n\"));\n\n for (int i = 0; i < argc; ++i) {\n sendString(connection, PSTR(\"arg: \"));\n sendString(connection, argv[i]);\n sendString(connection, PSTR(\"\\n\"));\n }\n\n sendString(connection, PSTR(\"build\\n\"));\n\n \/\/printf(\"Build sent in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n\n for (;;) {\n const int BUFFER_LENGTH = 1024;\n pchar buffer[BUFFER_LENGTH + 1];\n const int bytes = recv(\n connection,\n reinterpret_cast<char*>(buffer),\n sizeof(pchar) * BUFFER_LENGTH,\n 0);\n if (0 == bytes) {\n break;\n }\n if (SOCKET_ERROR == bytes) {\n error(\"Broken connection\");\n break;\n }\n const int chars = bytes \/ sizeof(pchar); \/\/ TODO: handle odd bytes values\n buffer[chars] = 0;\n pprintf(PSTR(\"%s\"), buffer); \/\/ %*s sometimes wrote extra crap at the end\n }\n\n \/\/printf(\"Result recieved in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n\n return true;\n}\n\nint pmain(int argc, const pchar* argv[]) {\n clock_t start = clock();\n\n#ifdef _WIN32\n WSADATA wsadata;\n if (0 != WSAStartup(2, &wsadata)) {\n return error(\"Failed to initialize winsock\");\n }\n\n struct cleanup_t {\n cleanup_t() {}\n ~cleanup_t() { WSACleanup(); }\n } cleanup;\n#endif\n\n \/\/printf(\"Started winsock in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n\n SOCKET connection;\n if (!openServerConnection(&connection, NO_RETRY)) {\n if (!startServer()) {\n return error(\"Failed to start server\");\n }\n if (!openServerConnection(&connection, RETRY)) {\n return error(\"Failed to connect to server\");\n }\n }\n\n \/\/printf(\"Opened connection in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n\n if (!sendBuild(connection, argc, argv, start)) {\n return error(\"Failed to submit build\");\n }\n\n closesocket(connection);\n\n \/\/printf(\"Socket closed in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n \/\/fflush(stdout);\n return 0;\n}\n\n\/\/ hack around mingw's lack of wmain support\n#ifdef _WIN32\n\nint main() {\n int argc;\n WCHAR** argv = CommandLineToArgvW(\n GetCommandLineW(),\n &argc);\n return pmain(argc, const_cast<const wchar_t**>(argv));\n}\n\n#else\n\nint main(int argc, const char* argv[]) {\n return pmain(argc, argv);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\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#include \"otbComputePolylineFeatureFromImage.h\"\n\n#include <iostream>\n#include \"otbCommandLineArgumentParser.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n\n#include \"otbVectorData.h\"\n#include \"otbVectorDataFileReader.h\"\n#include \"otbVectorDataFileWriter.h\"\n#include \"itkPreOrderTreeIterator.h\"\n\n#include \"otbVectorDataIntoImageProjectionFilter.h\"\n#include \"otbVectorDataProjectionFilter.h\"\n#include \"otbVectorDataTransformFilter.h\"\n#include \"itkAffineTransform.h\"\n\n#include \"otbParserConditionDataNodeFeatureFunction.h\"\n#include \"otbNDVIDataNodeFeatureFunction.h\"\n\nnamespace otb\n{\n\nint ComputePolylineFeatureFromImage::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"ComputePolylineFeatureFromImage\");\n descriptor->SetDescription(\"Compute a polyline feature from an input image: part of the polyline pixels that verify the FeatureExpression\");\n descriptor->AddOption(\"InputImage\", \"An image from which to compute description\",\n \"img\", 1, true, ApplicationDescriptor::InputImage);\n descriptor->AddOption(\"InputVectorData\", \"Vector Data containing the polylines onto which the feature will be computed\",\n \"vdin\", 1, true, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"FeatureExpression\", \"The feature formula (b1 > 0.3)\",\n \"expr\", 1, true, ApplicationDescriptor::String);\n descriptor->AddOption(\"FieldName\", \"The feature name (NONDVI, ROADSA...)\",\n \"field\", 1, true, ApplicationDescriptor::String);\n descriptor->AddOption(\"OutputVectorData\", \"The output Vector Data containing the feature\",\n \"out\", 1, true, ApplicationDescriptor::FileName);\n\n descriptor->AddOption(\"DEMDirectory\", \"DEM directory\",\n \"dem\", 1, false, ApplicationDescriptor::DirectoryName);\n\n return EXIT_SUCCESS;\n}\n\nint ComputePolylineFeatureFromImage::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n \/\/ Images\n typedef float PixelType;\n typedef VectorImage<PixelType, 2> ImageType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n\n \/\/ VectorData\n typedef VectorData<> VectorDataType;\n typedef VectorDataType::DataNodeType DataNodeType;\n typedef DataNodeType::ValuePrecisionType PrecisionType;\n typedef DataNodeType::PrecisionType CoordRepType;\n typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType>\n TreeIteratorType;\n typedef VectorDataFileReader<VectorDataType> VectorDataReaderType;\n typedef VectorDataFileWriter<VectorDataType> VectorDataWriterType;\n\n typedef VectorDataIntoImageProjectionFilter\n <VectorDataType, ImageType> VectorDataIntoImageProjType;\n typedef VectorDataProjectionFilter\n <VectorDataType, VectorDataType> VectorDataProjectionFilterType;\n\n typedef ParserConditionDataNodeFeatureFunction<ImageType, CoordRepType, PrecisionType>\n ParserConditionFeatureFunctionType;\n\n \/\/ Vector Data into Image projection\n \/\/\/\/ Read the Image\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(parseResult->GetParameterString(\"InputImage\"));\n reader->UpdateOutputInformation();\n reader->Update();\n ImageType::Pointer inputImage = reader->GetOutput();\n \/\/\/\/ Read the Vectordata\n VectorDataReaderType::Pointer vdreader = VectorDataReaderType::New();\n vdreader->SetFileName(parseResult->GetParameterString(\"InputVectorData\"));\n vdreader->Update();\n \/\/\/\/ Projection\n VectorDataIntoImageProjType::Pointer vprojIm = VectorDataIntoImageProjType::New();\n vprojIm->SetInputVectorData(vdreader->GetOutput());\n vprojIm->SetInputImage(inputImage);\n if( parseResult->IsOptionPresent(\"DEMDirectory\") )\n {\n vprojIm->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n }\n vprojIm->SetUseOutputSpacingAndOriginFromImage(true); \/\/ we want index as input;\n vprojIm->Update();\n\n \/\/ Add description\n ParserConditionFeatureFunctionType::Pointer vdescriptor = ParserConditionFeatureFunctionType::New();\n vdescriptor->SetExpression(parseResult->GetParameterString(\"FeatureExpression\"));\n vdescriptor->SetInputImage(inputImage);\n\n VectorDataType::Pointer outVD = VectorDataType::New();\n \/\/ Retrieving root node\n DataNodeType::Pointer root = outVD->GetDataTree()->GetRoot()->Get();\n \/\/ Create the document node\n DataNodeType::Pointer document = DataNodeType::New();\n document->SetNodeType(otb::DOCUMENT);\n \/\/ Adding the layer to the data tree\n outVD->GetDataTree()->Add(document, root);\n \/\/ Create the folder node\n DataNodeType::Pointer folder = DataNodeType::New();\n folder->SetNodeType(otb::FOLDER);\n \/\/ Adding the layer to the data tree\n outVD->GetDataTree()->Add(folder, document);\n\n TreeIteratorType itVector(vprojIm->GetOutput()->GetDataTree());\n itVector.GoToBegin();\n\n while (!itVector.IsAtEnd())\n {\n vdescriptor->SetInputImage(reader->GetOutput());\n if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())\n {\n DataNodeType::Pointer currentGeometry = itVector.Get();\n currentGeometry->SetFieldAsDouble(parseResult->GetParameterString(\"FieldName\"),\n (double)(vdescriptor->Evaluate(*(currentGeometry.GetPointer()))[0]));\n\n outVD->GetDataTree()->Add(currentGeometry, folder);\n }\n ++itVector;\n }\n\n \/*\n * Reprojection of the output VectorData\n *\n * The output of VectorDataToRoadDescription is in image index coordinates\n *\n * 3 cases :\n * - input image has no geo-information : pass through\n * - input image is in cartographic projection : apply image spacing and origin, and set the ProjectionRef\n * - input image is in sensor model geometry : reproject in WGS84\n *\n *\/\n\n std::string projRef = inputImage->GetProjectionRef();\n ImageKeywordlist kwl;\n itk::ExposeMetaData<ImageKeywordlist>(inputImage->GetMetaDataDictionary(),\n MetaDataKey::OSSIMKeywordlistKey,\n kwl);\n\n VectorDataType::Pointer projectedVD;\n\n if ( !projRef.empty() )\n {\n \/\/ image is in cartographic projection\n \/\/ apply spacing and origin + set projection WKT\n \/\/ The VectorData in output of the chain is in image index coordinate,\n \/\/ and the projection information is lost\n \/\/ Apply an affine transform to apply image origin and spacing,\n \/\/ and arbitrarily set the ProjectionRef to the input image ProjectionRef\n\n typedef itk::AffineTransform<VectorDataType::PrecisionType, 2> TransformType;\n typedef otb::VectorDataTransformFilter<VectorDataType, VectorDataType> VDTransformType;\n\n TransformType::ParametersType params;\n params.SetSize(6);\n params[0] = inputImage->GetSpacing()[0];\n params[1] = 0;\n params[2] = 0;\n params[3] = inputImage->GetSpacing()[1];\n params[4] = inputImage->GetOrigin()[0];\n params[5] = inputImage->GetOrigin()[1];\n\n TransformType::Pointer transform = TransformType::New();\n transform->SetParameters(params);\n\n VDTransformType::Pointer vdTransform = VDTransformType::New();\n vdTransform->SetTransform(transform);\n vdTransform->SetInput(outVD);\n vdTransform->Update();\n\n projectedVD = vdTransform->GetOutput();\n\n projectedVD->SetProjectionRef(inputImage->GetProjectionRef());\n }\n else if ( kwl.GetSize() > 0 )\n {\n \/\/ image is in sensor model geometry\n\n \/\/ Reproject VectorData in image projection\n VectorDataProjectionFilterType::Pointer vproj = VectorDataProjectionFilterType::New();\n vproj->SetInput(outVD);\n\n vproj->SetOutputKeywordList(inputImage->GetImageKeywordlist());\n vproj->SetOutputProjectionRef(inputImage->GetProjectionRef());\n vproj->SetOutputOrigin(inputImage->GetOrigin());\n vproj->SetOutputSpacing(inputImage->GetSpacing());\n\n if( parseResult->IsOptionPresent(\"DEMDirectory\") )\n {\n vproj->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n }\n\n vproj->Update();\n projectedVD = vproj->GetOutput();\n }\n else\n {\n \/\/ no georeferencing information\n\n projectedVD = outVD;\n\n }\n\n \/\/ Write vectordata with description\n VectorDataWriterType::Pointer vdwriter = VectorDataWriterType::New();\n vdwriter->SetFileName(parseResult->GetParameterString(\"OutputVectorData\"));\n vdwriter->SetInput(projectedVD);\n vdwriter->Update();\n\n return EXIT_SUCCESS;\n}\n\n}\n\n\n<commit_msg>DOC:improve documentation of cartographic db validation framework applications<commit_after>\/*=========================================================================\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#include \"otbComputePolylineFeatureFromImage.h\"\n\n#include <iostream>\n#include \"otbCommandLineArgumentParser.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n\n#include \"otbVectorData.h\"\n#include \"otbVectorDataFileReader.h\"\n#include \"otbVectorDataFileWriter.h\"\n#include \"itkPreOrderTreeIterator.h\"\n\n#include \"otbVectorDataIntoImageProjectionFilter.h\"\n#include \"otbVectorDataProjectionFilter.h\"\n#include \"otbVectorDataTransformFilter.h\"\n#include \"itkAffineTransform.h\"\n\n#include \"otbParserConditionDataNodeFeatureFunction.h\"\n#include \"otbNDVIDataNodeFeatureFunction.h\"\n\nnamespace otb\n{\n\nint ComputePolylineFeatureFromImage::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"ComputePolylineFeatureFromImage\");\n descriptor->SetDescription(\"Compute a polyline feature descriptors from an input image which are part of the polyline pixels that verify the FeatureExpression\");\n descriptor->AddOption(\"InputImage\", \"An image from which to compute description\",\n \"img\", 1, true, ApplicationDescriptor::InputImage);\n descriptor->AddOption(\"InputVectorData\", \"Vector data containing the polylines onto which the feature will be computed\",\n \"vdin\", 1, true, ApplicationDescriptor::FileName);\n descriptor->AddOption(\"FeatureExpression\", \"The feature formula (b1 > 0.3)\",\n \"expr\", 1, true, ApplicationDescriptor::String);\n descriptor->AddOption(\"FieldName\", \"The feature name (NONDVI, ROADSA...)\",\n \"field\", 1, true, ApplicationDescriptor::String);\n descriptor->AddOption(\"OutputVectorData\", \"The output vector data containing the feature\",\n \"out\", 1, true, ApplicationDescriptor::FileName);\n\n descriptor->AddOption(\"DEMDirectory\", \"DEM directory\",\n \"dem\", 1, false, ApplicationDescriptor::DirectoryName);\n\n return EXIT_SUCCESS;\n}\n\nint ComputePolylineFeatureFromImage::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n \/\/ Images\n typedef float PixelType;\n typedef VectorImage<PixelType, 2> ImageType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n\n \/\/ VectorData\n typedef VectorData<> VectorDataType;\n typedef VectorDataType::DataNodeType DataNodeType;\n typedef DataNodeType::ValuePrecisionType PrecisionType;\n typedef DataNodeType::PrecisionType CoordRepType;\n typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType>\n TreeIteratorType;\n typedef VectorDataFileReader<VectorDataType> VectorDataReaderType;\n typedef VectorDataFileWriter<VectorDataType> VectorDataWriterType;\n\n typedef VectorDataIntoImageProjectionFilter\n <VectorDataType, ImageType> VectorDataIntoImageProjType;\n typedef VectorDataProjectionFilter\n <VectorDataType, VectorDataType> VectorDataProjectionFilterType;\n\n typedef ParserConditionDataNodeFeatureFunction<ImageType, CoordRepType, PrecisionType>\n ParserConditionFeatureFunctionType;\n\n \/\/ Vector Data into Image projection\n \/\/\/\/ Read the Image\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(parseResult->GetParameterString(\"InputImage\"));\n reader->UpdateOutputInformation();\n reader->Update();\n ImageType::Pointer inputImage = reader->GetOutput();\n \/\/\/\/ Read the Vectordata\n VectorDataReaderType::Pointer vdreader = VectorDataReaderType::New();\n vdreader->SetFileName(parseResult->GetParameterString(\"InputVectorData\"));\n vdreader->Update();\n \/\/\/\/ Projection\n VectorDataIntoImageProjType::Pointer vprojIm = VectorDataIntoImageProjType::New();\n vprojIm->SetInputVectorData(vdreader->GetOutput());\n vprojIm->SetInputImage(inputImage);\n if( parseResult->IsOptionPresent(\"DEMDirectory\") )\n {\n vprojIm->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n }\n vprojIm->SetUseOutputSpacingAndOriginFromImage(true); \/\/ we want index as input;\n vprojIm->Update();\n\n \/\/ Add description\n ParserConditionFeatureFunctionType::Pointer vdescriptor = ParserConditionFeatureFunctionType::New();\n vdescriptor->SetExpression(parseResult->GetParameterString(\"FeatureExpression\"));\n vdescriptor->SetInputImage(inputImage);\n\n VectorDataType::Pointer outVD = VectorDataType::New();\n \/\/ Retrieving root node\n DataNodeType::Pointer root = outVD->GetDataTree()->GetRoot()->Get();\n \/\/ Create the document node\n DataNodeType::Pointer document = DataNodeType::New();\n document->SetNodeType(otb::DOCUMENT);\n \/\/ Adding the layer to the data tree\n outVD->GetDataTree()->Add(document, root);\n \/\/ Create the folder node\n DataNodeType::Pointer folder = DataNodeType::New();\n folder->SetNodeType(otb::FOLDER);\n \/\/ Adding the layer to the data tree\n outVD->GetDataTree()->Add(folder, document);\n\n TreeIteratorType itVector(vprojIm->GetOutput()->GetDataTree());\n itVector.GoToBegin();\n\n while (!itVector.IsAtEnd())\n {\n vdescriptor->SetInputImage(reader->GetOutput());\n if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())\n {\n DataNodeType::Pointer currentGeometry = itVector.Get();\n currentGeometry->SetFieldAsDouble(parseResult->GetParameterString(\"FieldName\"),\n (double)(vdescriptor->Evaluate(*(currentGeometry.GetPointer()))[0]));\n\n outVD->GetDataTree()->Add(currentGeometry, folder);\n }\n ++itVector;\n }\n\n \/*\n * Reprojection of the output VectorData\n *\n * The output of VectorDataToRoadDescription is in image index coordinates\n *\n * 3 cases :\n * - input image has no geo-information : pass through\n * - input image is in cartographic projection : apply image spacing and origin, and set the ProjectionRef\n * - input image is in sensor model geometry : reproject in WGS84\n *\n *\/\n\n std::string projRef = inputImage->GetProjectionRef();\n ImageKeywordlist kwl;\n itk::ExposeMetaData<ImageKeywordlist>(inputImage->GetMetaDataDictionary(),\n MetaDataKey::OSSIMKeywordlistKey,\n kwl);\n\n VectorDataType::Pointer projectedVD;\n\n if ( !projRef.empty() )\n {\n \/\/ image is in cartographic projection\n \/\/ apply spacing and origin + set projection WKT\n \/\/ The VectorData in output of the chain is in image index coordinate,\n \/\/ and the projection information is lost\n \/\/ Apply an affine transform to apply image origin and spacing,\n \/\/ and arbitrarily set the ProjectionRef to the input image ProjectionRef\n\n typedef itk::AffineTransform<VectorDataType::PrecisionType, 2> TransformType;\n typedef otb::VectorDataTransformFilter<VectorDataType, VectorDataType> VDTransformType;\n\n TransformType::ParametersType params;\n params.SetSize(6);\n params[0] = inputImage->GetSpacing()[0];\n params[1] = 0;\n params[2] = 0;\n params[3] = inputImage->GetSpacing()[1];\n params[4] = inputImage->GetOrigin()[0];\n params[5] = inputImage->GetOrigin()[1];\n\n TransformType::Pointer transform = TransformType::New();\n transform->SetParameters(params);\n\n VDTransformType::Pointer vdTransform = VDTransformType::New();\n vdTransform->SetTransform(transform);\n vdTransform->SetInput(outVD);\n vdTransform->Update();\n\n projectedVD = vdTransform->GetOutput();\n\n projectedVD->SetProjectionRef(inputImage->GetProjectionRef());\n }\n else if ( kwl.GetSize() > 0 )\n {\n \/\/ image is in sensor model geometry\n\n \/\/ Reproject VectorData in image projection\n VectorDataProjectionFilterType::Pointer vproj = VectorDataProjectionFilterType::New();\n vproj->SetInput(outVD);\n\n vproj->SetOutputKeywordList(inputImage->GetImageKeywordlist());\n vproj->SetOutputProjectionRef(inputImage->GetProjectionRef());\n vproj->SetOutputOrigin(inputImage->GetOrigin());\n vproj->SetOutputSpacing(inputImage->GetSpacing());\n\n if( parseResult->IsOptionPresent(\"DEMDirectory\") )\n {\n vproj->SetDEMDirectory(parseResult->GetParameterString(\"DEMDirectory\"));\n }\n\n vproj->Update();\n projectedVD = vproj->GetOutput();\n }\n else\n {\n \/\/ no georeferencing information\n\n projectedVD = outVD;\n\n }\n\n \/\/ Write vectordata with description\n VectorDataWriterType::Pointer vdwriter = VectorDataWriterType::New();\n vdwriter->SetFileName(parseResult->GetParameterString(\"OutputVectorData\"));\n vdwriter->SetInput(projectedVD);\n vdwriter->Update();\n\n return EXIT_SUCCESS;\n}\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\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#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbMultiToMonoChannelExtractROI.h\"\n#include \"otbGenericRSResampleImageFilter.h\"\n#include \"otbGridResampleImageFilter.h\"\n#include \"otbImportGeoInformationImageFilter.h\"\n#include \"otbBCOInterpolateImageFunction.h\"\n#include \"otbSimpleRcsPanSharpeningFusionImageFilter.h\"\n#include \"itkFixedArray.h\"\n\n\/\/ Elevation handler\n#include \"otbWrapperElevationParametersHandler.h\"\n\n#include \"otbPleiadesPToXSAffineTransformCalculator.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\nclass BundleToPerfectSensor : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef BundleToPerfectSensor Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(BundleToPerfectSensor, otb::Application);\n\nprivate:\n\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"BundleToPerfectSensor\");\n SetDescription(\"Perform P+XS pansharpening\");\n\n \/\/ Documentation\n SetDocName(\"Bundle to perfect sensor\");\n SetDocLongDescription(\"This application performs P+XS pansharpening. The default mode use Pan and XS sensor models to estimate the transformation to superimpose XS over Pan before the fusion (\\\"default mode\\\"). The application provides also a PHR mode for Pleiades images which does not use sensor models as Pan and XS products are already coregistered but only estimate an affine transformation to superimpose XS over the Pan.Note that this option is automatically activated in case Pleiades images are detected as input.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(Tags::Geometry);\n AddDocTag(Tags::Pansharpening);\n\n AddParameter(ParameterType_InputImage, \"inp\", \"Input PAN Image\");\n SetParameterDescription(\"inp\",\" Input panchromatic image.\");\n AddParameter(ParameterType_InputImage, \"inxs\", \"Input XS Image\");\n SetParameterDescription(\"inxs\",\" Input XS image.\");\n\n \/\/ Elevation\n ElevationParametersHandler::AddElevationParameters(this, \"elev\");\n\n \/\/ Superposition mode\n AddParameter(ParameterType_Choice,\"mode\", \"Mode\");\n SetParameterDescription(\"mode\", \"Superimposition mode\");\n \n AddChoice(\"mode.default\", \"Default mode\");\n SetParameterDescription(\"mode.default\", \"Default superimposition mode : \"\n \"uses any projection reference or sensor model found in the images\");\n \n AddChoice(\"mode.phr\", \"Pleiades mode\");\n SetParameterDescription(\"mode.phr\", \"Pleiades superimposition mode, \"\n \"designed for the case of a P+XS bundle in SENSOR geometry. It uses\"\n \" a simple transform on the XS image : a scaling and a residual \"\n \"translation.\");\n \n AddParameter(ParameterType_Float, \"lms\", \"Spacing of the deformation field\");\n SetParameterDescription(\"lms\",\" Spacing of the deformation field. Default is 10 times the PAN image spacing.\");\n AddParameter(ParameterType_OutputImage, \"out\", \"Output image\");\n SetParameterDescription(\"out\",\" Output image.\");\n AddRAMParameter();\n\n MandatoryOff(\"lms\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"inp\", \"QB_Toulouse_Ortho_PAN.tif\");\n SetDocExampleParameterValue(\"inxs\", \"QB_Toulouse_Ortho_XS.tif\");\n SetDocExampleParameterValue(\"out\", \"BundleToPerfectSensor.png uchar\");\n\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {\n if(!HasUserValue(\"mode\") && HasValue(\"inp\") && HasValue(\"inxs\") && otb::PleiadesPToXSAffineTransformCalculator::CanCompute(GetParameterImage(\"inp\"),GetParameterImage(\"inxs\")))\n {\n otbAppLogWARNING(\"Forcing PHR mode with PHR data. You need to add \\\"-mode default\\\" to force the default mode with PHR images.\");\n SetParameterString(\"mode\",\"phr\");\n }\n }\n\n void DoExecute() ITK_OVERRIDE\n {\n FloatVectorImageType* panchroV = GetParameterImage(\"inp\");\n FloatVectorImageType* xs = GetParameterImage(\"inxs\");\n\n if ( panchroV->GetNumberOfComponentsPerPixel() != 1 )\n {\n itkExceptionMacro(<< \"The panchromatic image must be a single channel image\")\n }\n\n \/\/ Transform the PAN image to otb::Image\n typedef otb::Image<FloatVectorImageType::InternalPixelType> InternalImageType;\n typedef otb::MultiToMonoChannelExtractROI<float,float> ExtractFilterType;\n\n ExtractFilterType::Pointer channelSelect = ExtractFilterType::New();\n m_Ref.push_back(channelSelect.GetPointer());\n channelSelect->SetChannel(1);\n channelSelect->SetInput(panchroV);\n channelSelect->UpdateOutputInformation();\n InternalImageType::Pointer panchro = channelSelect->GetOutput();\n\n typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType;\n typedef otb::GenericRSResampleImageFilter<FloatVectorImageType, FloatVectorImageType> ResamplerType;\n typedef otb::GridResampleImageFilter<FloatVectorImageType, FloatVectorImageType> BasicResamplerType;\n typedef otb::ImportGeoInformationImageFilter<FloatVectorImageType,InternalImageType> ImportGeoInformationFilterType;\n typedef otb::SimpleRcsPanSharpeningFusionImageFilter<InternalImageType, FloatVectorImageType, FloatVectorImageType> FusionFilterType;\n\n \/\/ Resample filter\n ResamplerType::Pointer resampler = ResamplerType::New();\n m_Ref.push_back(resampler.GetPointer());\n \n BasicResamplerType::Pointer basicResampler = BasicResamplerType::New();\n m_Ref.push_back(basicResampler.GetPointer());\n\n ImportGeoInformationFilterType::Pointer geoImport = ImportGeoInformationFilterType::New();\n m_Ref.push_back(geoImport.GetPointer());\n\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n resampler->SetInterpolator(interpolator);\n basicResampler->SetInterpolator(interpolator);\n\n \/\/ Fusion filter\n FusionFilterType::Pointer fusionFilter = FusionFilterType::New();\n m_Ref.push_back(fusionFilter.GetPointer());\n fusionFilter->SetPanInput(panchro);\n \n \/\/ Setup the DEM Handler\n otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,\"elev\");\n\n \/\/ Set up output image information\n FloatVectorImageType::SpacingType spacing = panchro->GetSpacing();\n FloatVectorImageType::IndexType start = panchro->GetLargestPossibleRegion().GetIndex();\n FloatVectorImageType::SizeType size = panchro->GetLargestPossibleRegion().GetSize();\n FloatVectorImageType::PointType origin = panchro->GetOrigin();\n\n FloatVectorImageType::PixelType defaultValue;\n itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, xs->GetNumberOfComponentsPerPixel());\n\n if(GetParameterString(\"mode\") == \"default\")\n {\n otbAppLogINFO(\"Using the default mode\");\n if(IsParameterEnabled(\"lms\") && HasValue(\"lms\"))\n {\n double defScalarSpacing = GetParameterFloat(\"lms\");\n otbAppLogINFO(<< \"Generating coarse deformation field (spacing=\"<<defScalarSpacing<<\")\" << std::endl);\n FloatVectorImageType::SpacingType defSpacing;\n \n defSpacing[0] = defScalarSpacing;\n defSpacing[1] = defScalarSpacing;\n \n resampler->SetDisplacementFieldSpacing(defSpacing);\n }\n else\n {\n FloatVectorImageType::SpacingType defSpacing;\n defSpacing[0]=10*spacing[0];\n defSpacing[1]=10*spacing[1];\n resampler->SetDisplacementFieldSpacing(defSpacing);\n }\n \n resampler->SetInput(xs);\n resampler->SetOutputOrigin(origin);\n resampler->SetOutputSpacing(spacing);\n resampler->SetOutputSize(size);\n resampler->SetOutputStartIndex(start);\n resampler->SetOutputKeywordList(panchro->GetImageKeywordlist());\n resampler->SetOutputProjectionRef(panchro->GetProjectionRef());\n resampler->SetEdgePaddingValue(defaultValue);\n fusionFilter->SetXsInput(resampler->GetOutput());\n }\n else if(GetParameterString(\"mode\")==\"phr\")\n {\n otbAppLogINFO(\"Using the PHR mode\");\n \n otb::PleiadesPToXSAffineTransformCalculator::TransformType::OffsetType offset\n = otb::PleiadesPToXSAffineTransformCalculator::ComputeOffset(GetParameterImage(\"inp\"),\n GetParameterImage(\"inxs\"));\n\n origin+=offset;\n origin[0]=origin[0]\/4;\n origin[1]=origin[1]\/4;\n \n basicResampler->SetOutputOrigin(origin);\n basicResampler->SetInput(xs);\n basicResampler->SetOutputOrigin(origin);\n\n FloatVectorImageType::SpacingType xsSpacing = GetParameterImage(\"inxs\")->GetSpacing();\n xsSpacing*=0.25;\n \n basicResampler->SetOutputSpacing(xsSpacing);\n basicResampler->SetOutputSize(size);\n basicResampler->SetOutputStartIndex(start);\n basicResampler->SetEdgePaddingValue(defaultValue);\n\n geoImport->SetInput(basicResampler->GetOutput());\n geoImport->SetSource(panchro);\n\n fusionFilter->SetXsInput(geoImport->GetOutput());\n\n \/\/ Set the profRef & Keywordlist from Pan into the resampled XS image\n basicResampler->UpdateOutputInformation();\n itk::MetaDataDictionary& dict = basicResampler->GetOutput()->GetMetaDataDictionary();\n itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey,\n panchro->GetProjectionRef());\n itk::EncapsulateMetaData<ImageKeywordlist>(dict, MetaDataKey::OSSIMKeywordlistKey,\n panchro->GetImageKeywordlist());\n }\n else\n {\n otbAppLogWARNING(\"Unknown mode\");\n }\n \n SetParameterOutputImage(\"out\", fusionFilter->GetOutput());\n }\n\n std::vector<itk::ProcessObject::Pointer> m_Ref;\n\n};\n\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::BundleToPerfectSensor)\n<commit_msg>BUG: Mantis-1237: fix parameter order<commit_after>\/*=========================================================================\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#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbMultiToMonoChannelExtractROI.h\"\n#include \"otbGenericRSResampleImageFilter.h\"\n#include \"otbGridResampleImageFilter.h\"\n#include \"otbImportGeoInformationImageFilter.h\"\n#include \"otbBCOInterpolateImageFunction.h\"\n#include \"otbSimpleRcsPanSharpeningFusionImageFilter.h\"\n#include \"itkFixedArray.h\"\n\n\/\/ Elevation handler\n#include \"otbWrapperElevationParametersHandler.h\"\n\n#include \"otbPleiadesPToXSAffineTransformCalculator.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\nclass BundleToPerfectSensor : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef BundleToPerfectSensor Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(BundleToPerfectSensor, otb::Application);\n\nprivate:\n\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"BundleToPerfectSensor\");\n SetDescription(\"Perform P+XS pansharpening\");\n\n \/\/ Documentation\n SetDocName(\"Bundle to perfect sensor\");\n SetDocLongDescription(\"This application performs P+XS pansharpening. The default mode use Pan and XS sensor models to estimate the transformation to superimpose XS over Pan before the fusion (\\\"default mode\\\"). The application provides also a PHR mode for Pleiades images which does not use sensor models as Pan and XS products are already coregistered but only estimate an affine transformation to superimpose XS over the Pan.Note that this option is automatically activated in case Pleiades images are detected as input.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(Tags::Geometry);\n AddDocTag(Tags::Pansharpening);\n\n AddParameter(ParameterType_InputImage, \"inp\", \"Input PAN Image\");\n SetParameterDescription(\"inp\",\" Input panchromatic image.\");\n AddParameter(ParameterType_InputImage, \"inxs\", \"Input XS Image\");\n SetParameterDescription(\"inxs\",\" Input XS image.\");\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output image\");\n SetParameterDescription(\"out\",\" Output image.\");\n\n \/\/ Elevation\n ElevationParametersHandler::AddElevationParameters(this, \"elev\");\n\n \/\/ Superposition mode\n AddParameter(ParameterType_Choice,\"mode\", \"Mode\");\n SetParameterDescription(\"mode\", \"Superimposition mode\");\n \n AddChoice(\"mode.default\", \"Default mode\");\n SetParameterDescription(\"mode.default\", \"Default superimposition mode : \"\n \"uses any projection reference or sensor model found in the images\");\n \n AddChoice(\"mode.phr\", \"Pleiades mode\");\n SetParameterDescription(\"mode.phr\", \"Pleiades superimposition mode, \"\n \"designed for the case of a P+XS bundle in SENSOR geometry. It uses\"\n \" a simple transform on the XS image : a scaling and a residual \"\n \"translation.\");\n \n AddParameter(ParameterType_Float, \"lms\", \"Spacing of the deformation field\");\n SetParameterDescription(\"lms\",\" Spacing of the deformation field. Default is 10 times the PAN image spacing.\");\n\n AddRAMParameter();\n\n MandatoryOff(\"lms\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"inp\", \"QB_Toulouse_Ortho_PAN.tif\");\n SetDocExampleParameterValue(\"inxs\", \"QB_Toulouse_Ortho_XS.tif\");\n SetDocExampleParameterValue(\"out\", \"BundleToPerfectSensor.png uchar\");\n\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {\n if(!HasUserValue(\"mode\") && HasValue(\"inp\") && HasValue(\"inxs\") && otb::PleiadesPToXSAffineTransformCalculator::CanCompute(GetParameterImage(\"inp\"),GetParameterImage(\"inxs\")))\n {\n otbAppLogWARNING(\"Forcing PHR mode with PHR data. You need to add \\\"-mode default\\\" to force the default mode with PHR images.\");\n SetParameterString(\"mode\",\"phr\");\n }\n }\n\n void DoExecute() ITK_OVERRIDE\n {\n FloatVectorImageType* panchroV = GetParameterImage(\"inp\");\n FloatVectorImageType* xs = GetParameterImage(\"inxs\");\n\n if ( panchroV->GetNumberOfComponentsPerPixel() != 1 )\n {\n itkExceptionMacro(<< \"The panchromatic image must be a single channel image\")\n }\n\n \/\/ Transform the PAN image to otb::Image\n typedef otb::Image<FloatVectorImageType::InternalPixelType> InternalImageType;\n typedef otb::MultiToMonoChannelExtractROI<float,float> ExtractFilterType;\n\n ExtractFilterType::Pointer channelSelect = ExtractFilterType::New();\n m_Ref.push_back(channelSelect.GetPointer());\n channelSelect->SetChannel(1);\n channelSelect->SetInput(panchroV);\n channelSelect->UpdateOutputInformation();\n InternalImageType::Pointer panchro = channelSelect->GetOutput();\n\n typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType;\n typedef otb::GenericRSResampleImageFilter<FloatVectorImageType, FloatVectorImageType> ResamplerType;\n typedef otb::GridResampleImageFilter<FloatVectorImageType, FloatVectorImageType> BasicResamplerType;\n typedef otb::ImportGeoInformationImageFilter<FloatVectorImageType,InternalImageType> ImportGeoInformationFilterType;\n typedef otb::SimpleRcsPanSharpeningFusionImageFilter<InternalImageType, FloatVectorImageType, FloatVectorImageType> FusionFilterType;\n\n \/\/ Resample filter\n ResamplerType::Pointer resampler = ResamplerType::New();\n m_Ref.push_back(resampler.GetPointer());\n \n BasicResamplerType::Pointer basicResampler = BasicResamplerType::New();\n m_Ref.push_back(basicResampler.GetPointer());\n\n ImportGeoInformationFilterType::Pointer geoImport = ImportGeoInformationFilterType::New();\n m_Ref.push_back(geoImport.GetPointer());\n\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n resampler->SetInterpolator(interpolator);\n basicResampler->SetInterpolator(interpolator);\n\n \/\/ Fusion filter\n FusionFilterType::Pointer fusionFilter = FusionFilterType::New();\n m_Ref.push_back(fusionFilter.GetPointer());\n fusionFilter->SetPanInput(panchro);\n \n \/\/ Setup the DEM Handler\n otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,\"elev\");\n\n \/\/ Set up output image information\n FloatVectorImageType::SpacingType spacing = panchro->GetSpacing();\n FloatVectorImageType::IndexType start = panchro->GetLargestPossibleRegion().GetIndex();\n FloatVectorImageType::SizeType size = panchro->GetLargestPossibleRegion().GetSize();\n FloatVectorImageType::PointType origin = panchro->GetOrigin();\n\n FloatVectorImageType::PixelType defaultValue;\n itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, xs->GetNumberOfComponentsPerPixel());\n\n if(GetParameterString(\"mode\") == \"default\")\n {\n otbAppLogINFO(\"Using the default mode\");\n if(IsParameterEnabled(\"lms\") && HasValue(\"lms\"))\n {\n double defScalarSpacing = GetParameterFloat(\"lms\");\n otbAppLogINFO(<< \"Generating coarse deformation field (spacing=\"<<defScalarSpacing<<\")\" << std::endl);\n FloatVectorImageType::SpacingType defSpacing;\n \n defSpacing[0] = defScalarSpacing;\n defSpacing[1] = defScalarSpacing;\n \n resampler->SetDisplacementFieldSpacing(defSpacing);\n }\n else\n {\n FloatVectorImageType::SpacingType defSpacing;\n defSpacing[0]=10*spacing[0];\n defSpacing[1]=10*spacing[1];\n resampler->SetDisplacementFieldSpacing(defSpacing);\n }\n \n resampler->SetInput(xs);\n resampler->SetOutputOrigin(origin);\n resampler->SetOutputSpacing(spacing);\n resampler->SetOutputSize(size);\n resampler->SetOutputStartIndex(start);\n resampler->SetOutputKeywordList(panchro->GetImageKeywordlist());\n resampler->SetOutputProjectionRef(panchro->GetProjectionRef());\n resampler->SetEdgePaddingValue(defaultValue);\n fusionFilter->SetXsInput(resampler->GetOutput());\n }\n else if(GetParameterString(\"mode\")==\"phr\")\n {\n otbAppLogINFO(\"Using the PHR mode\");\n \n otb::PleiadesPToXSAffineTransformCalculator::TransformType::OffsetType offset\n = otb::PleiadesPToXSAffineTransformCalculator::ComputeOffset(GetParameterImage(\"inp\"),\n GetParameterImage(\"inxs\"));\n\n origin+=offset;\n origin[0]=origin[0]\/4;\n origin[1]=origin[1]\/4;\n \n basicResampler->SetOutputOrigin(origin);\n basicResampler->SetInput(xs);\n basicResampler->SetOutputOrigin(origin);\n\n FloatVectorImageType::SpacingType xsSpacing = GetParameterImage(\"inxs\")->GetSpacing();\n xsSpacing*=0.25;\n \n basicResampler->SetOutputSpacing(xsSpacing);\n basicResampler->SetOutputSize(size);\n basicResampler->SetOutputStartIndex(start);\n basicResampler->SetEdgePaddingValue(defaultValue);\n\n geoImport->SetInput(basicResampler->GetOutput());\n geoImport->SetSource(panchro);\n\n fusionFilter->SetXsInput(geoImport->GetOutput());\n\n \/\/ Set the profRef & Keywordlist from Pan into the resampled XS image\n basicResampler->UpdateOutputInformation();\n itk::MetaDataDictionary& dict = basicResampler->GetOutput()->GetMetaDataDictionary();\n itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey,\n panchro->GetProjectionRef());\n itk::EncapsulateMetaData<ImageKeywordlist>(dict, MetaDataKey::OSSIMKeywordlistKey,\n panchro->GetImageKeywordlist());\n }\n else\n {\n otbAppLogWARNING(\"Unknown mode\");\n }\n \n SetParameterOutputImage(\"out\", fusionFilter->GetOutput());\n }\n\n std::vector<itk::ProcessObject::Pointer> m_Ref;\n\n};\n\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::BundleToPerfectSensor)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. 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#ifndef __PERF_HPP__\n#define __PERF_HPP__\n\n#include <unistd.h>\n\n#include <set>\n#include <string>\n\n#include <process\/future.hpp>\n\n#include <stout\/duration.hpp>\n#include <stout\/hashmap.hpp>\n\n\/\/ For PerfStatistics protobuf.\n#include \"mesos\/mesos.hpp\"\n\nnamespace perf {\n\n\/\/ Sample the perf events for process(es) in the perf_event cgroups\n\/\/ for duration. The returned hashmap is keyed by cgroup.\n\/\/ NOTE: cgroups should be relative to the perf_event subsystem mount,\n\/\/ e.g., mesos\/test for \/sys\/fs\/cgroup\/perf_event\/mesos\/test.\nprocess::Future<hashmap<std::string, mesos::PerfStatistics>> sample(\n const std::set<std::string>& events,\n const std::set<std::string>& cgroups,\n const Duration& duration);\n\n\n\/\/ Validate a set of events are accepted by `perf stat`.\nbool valid(const std::set<std::string>& events);\n\n\n\/\/ Returns whether perf is supported on this host. Returns false if\n\/\/ the kernel is too old (requires >= 2.6.39).\nbool supported();\n\n\n\/\/ Note: The parse function is exposed to allow testing of the\n\/\/ multiple supported perf stat output formats.\nTry<hashmap<std::string, mesos::PerfStatistics>> parse(\n const std::string& output,\n const Version& version);\n\n} \/\/ namespace perf {\n\n#endif \/\/ __PERF_HPP__\n<commit_msg>Added missing header `version.hpp` in `src\/linux\/perf.hpp`.<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. 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#ifndef __PERF_HPP__\n#define __PERF_HPP__\n\n#include <unistd.h>\n\n#include <set>\n#include <string>\n\n#include <process\/future.hpp>\n\n#include <stout\/duration.hpp>\n#include <stout\/hashmap.hpp>\n#include <stout\/version.hpp>\n\n\/\/ For PerfStatistics protobuf.\n#include \"mesos\/mesos.hpp\"\n\nnamespace perf {\n\n\/\/ Sample the perf events for process(es) in the perf_event cgroups\n\/\/ for duration. The returned hashmap is keyed by cgroup.\n\/\/ NOTE: cgroups should be relative to the perf_event subsystem mount,\n\/\/ e.g., mesos\/test for \/sys\/fs\/cgroup\/perf_event\/mesos\/test.\nprocess::Future<hashmap<std::string, mesos::PerfStatistics>> sample(\n const std::set<std::string>& events,\n const std::set<std::string>& cgroups,\n const Duration& duration);\n\n\n\/\/ Validate a set of events are accepted by `perf stat`.\nbool valid(const std::set<std::string>& events);\n\n\n\/\/ Returns whether perf is supported on this host. Returns false if\n\/\/ the kernel is too old (requires >= 2.6.39).\nbool supported();\n\n\n\/\/ Note: The parse function is exposed to allow testing of the\n\/\/ multiple supported perf stat output formats.\nTry<hashmap<std::string, mesos::PerfStatistics>> parse(\n const std::string& output,\n const Version& version);\n\n} \/\/ namespace perf {\n\n#endif \/\/ __PERF_HPP__\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2015-2018 Baldur Karlsson\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\n#include \"vk_core.h\"\n#include \"vk_replay.h\"\n\nstatic int dllLocator = 0;\n\nvoid VulkanReplay::OutputWindow::SetWindowHandle(WindowingData window)\n{\n RDCASSERT(window.system == WindowingSystem::Win32, window.system);\n wnd = window.win32.window;\n}\n\nvoid VulkanReplay::OutputWindow::CreateSurface(VkInstance inst)\n{\n VkWin32SurfaceCreateInfoKHR createInfo;\n\n createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;\n createInfo.pNext = NULL;\n createInfo.flags = 0;\n createInfo.hwnd = wnd;\n\n GetModuleHandleExA(\n GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,\n (const char *)&dllLocator, (HMODULE *)&createInfo.hinstance);\n\n VkResult vkr = ObjDisp(inst)->CreateWin32SurfaceKHR(Unwrap(inst), &createInfo, NULL, &surface);\n RDCASSERTEQUAL(vkr, VK_SUCCESS);\n}\n\nvoid VulkanReplay::GetOutputWindowDimensions(uint64_t id, int32_t &w, int32_t &h)\n{\n if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end())\n return;\n\n OutputWindow &outw = m_OutputWindows[id];\n\n RECT rect = {0};\n GetClientRect(outw.wnd, &rect);\n w = rect.right - rect.left;\n h = rect.bottom - rect.top;\n}\n\nbool VulkanReplay::IsOutputWindowVisible(uint64_t id)\n{\n if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end())\n return false;\n\n return (IsWindowVisible(m_OutputWindows[id].wnd) == TRUE);\n}\n\nvoid WrappedVulkan::AddRequiredExtensions(bool instance, vector<string> &extensionList,\n const std::set<string> &supportedExtensions)\n{\n bool device = !instance;\n\n if(instance)\n {\n \/\/ for windows we require both extensions as there's no alternative\n if(supportedExtensions.find(VK_KHR_SURFACE_EXTENSION_NAME) == supportedExtensions.end())\n {\n RDCERR(\"Unsupported required instance extension '%s'\", VK_KHR_SURFACE_EXTENSION_NAME);\n }\n else\n {\n \/\/ don't add duplicates\n if(std::find(extensionList.begin(), extensionList.end(), VK_KHR_SURFACE_EXTENSION_NAME) ==\n extensionList.end())\n extensionList.push_back(VK_KHR_SURFACE_EXTENSION_NAME);\n }\n\n if(supportedExtensions.find(VK_KHR_WIN32_SURFACE_EXTENSION_NAME) == supportedExtensions.end())\n {\n RDCERR(\"Unsupported required instance extension '%s'\", VK_KHR_WIN32_SURFACE_EXTENSION_NAME);\n }\n else\n {\n if(std::find(extensionList.begin(), extensionList.end(),\n VK_KHR_WIN32_SURFACE_EXTENSION_NAME) == extensionList.end())\n extensionList.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);\n }\n }\n else if(device)\n {\n if(supportedExtensions.find(VK_KHR_SWAPCHAIN_EXTENSION_NAME) == supportedExtensions.end())\n {\n RDCERR(\"Unsupported required device extension '%s'\", VK_KHR_SWAPCHAIN_EXTENSION_NAME);\n }\n else\n {\n \/\/ don't add duplicates\n if(std::find(extensionList.begin(), extensionList.end(), VK_KHR_SWAPCHAIN_EXTENSION_NAME) ==\n extensionList.end())\n extensionList.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);\n }\n }\n}\n\n#if !defined(VK_USE_PLATFORM_WIN32_KHR)\n#error \"Win32 KHR platform not defined\"\n#endif\n\nVkResult WrappedVulkan::vkCreateWin32SurfaceKHR(VkInstance instance,\n const VkWin32SurfaceCreateInfoKHR *pCreateInfo,\n const VkAllocationCallbacks *pAllocator,\n VkSurfaceKHR *pSurface)\n{\n \/\/ should not come in here at all on replay\n RDCASSERT(IsCaptureMode(m_State));\n\n VkResult ret =\n ObjDisp(instance)->CreateWin32SurfaceKHR(Unwrap(instance), pCreateInfo, pAllocator, pSurface);\n\n if(ret == VK_SUCCESS)\n {\n GetResourceManager()->WrapResource(Unwrap(instance), *pSurface);\n\n WrappedVkSurfaceKHR *wrapped = GetWrapped(*pSurface);\n\n \/\/ since there's no point in allocating a full resource record and storing the window\n \/\/ handle under there somewhere, we just cast. We won't use the resource record for anything\n wrapped->record = (VkResourceRecord *)pCreateInfo->hwnd;\n\n Keyboard::AddInputWindow((void *)pCreateInfo->hwnd);\n }\n\n return ret;\n}\n\nVkBool32 WrappedVulkan::vkGetPhysicalDeviceWin32PresentationSupportKHR(VkPhysicalDevice physicalDevice,\n uint32_t queueFamilyIndex)\n{\n return ObjDisp(physicalDevice)\n ->GetPhysicalDeviceWin32PresentationSupportKHR(Unwrap(physicalDevice), queueFamilyIndex);\n}\n\nconst char *VulkanLibraryName = \"vulkan-1.dll\";\n\nstd::wstring GetJSONPath(bool wow6432)\n{\n wchar_t curFile[1024];\n GetModuleFileNameW(NULL, curFile, 1024);\n\n wchar_t *lastSlash = wcsrchr(curFile, '\\\\');\n if(lastSlash)\n *(lastSlash + 1) = 0;\n\n if(wow6432)\n wcscat_s(curFile, L\"x86\\\\\");\n\n wcscat_s(curFile, L\"renderdoc.json\");\n\n return curFile;\n}\n\nstatic HKEY GetImplicitLayersKey(bool writeable, bool wow6432)\n{\n std::string basepath = \"SOFTWARE\\\\\";\n\n if(wow6432)\n basepath += \"Wow6432Node\\\\\";\n\n basepath += \"Khronos\\\\Vulkan\\\\ImplicitLayers\";\n\n HKEY key = NULL;\n LSTATUS ret = ERROR_SUCCESS;\n\n if(writeable)\n ret = RegCreateKeyExA(HKEY_LOCAL_MACHINE, basepath.c_str(), 0, NULL, 0, KEY_READ | KEY_WRITE,\n NULL, &key, NULL);\n else\n ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, basepath.c_str(), 0, KEY_READ, &key);\n\n if(ret != ERROR_SUCCESS)\n {\n if(key)\n RegCloseKey(key);\n\n \/\/ find to fail to open for read, the key may not exist\n if(writeable)\n RDCERR(\"Couldn't open %s for write\", basepath.c_str());\n\n return NULL;\n }\n\n return key;\n}\n\nbool ProcessImplicitLayersKey(HKEY key, const std::wstring &path,\n std::vector<std::string> *otherJSONs, bool deleteOthers)\n{\n bool thisRegistered = false;\n\n wchar_t name[1025] = {};\n DWORD nameSize = 1024;\n DWORD idx = 0;\n\n LONG ret = RegEnumValueW(key, idx++, name, &nameSize, NULL, NULL, NULL, NULL);\n\n std::wstring myJSON = path;\n for(size_t i = 0; i < myJSON.size(); i++)\n myJSON[i] = towlower(myJSON[i]);\n\n while(ret == ERROR_SUCCESS)\n {\n \/\/ convert the name here so we preserve casing\n std::string utf8name = StringFormat::Wide2UTF8(name);\n\n for(DWORD i = 0; i <= nameSize && name[i]; i++)\n name[i] = towlower(name[i]);\n\n if(wcscmp(name, myJSON.c_str()) == 0)\n {\n thisRegistered = true;\n }\n else if(wcsstr(name, L\"renderdoc.json\") != NULL)\n {\n if(otherJSONs)\n otherJSONs->push_back(utf8name);\n\n if(deleteOthers)\n RegDeleteValueW(key, name);\n }\n\n nameSize = 1024;\n ret = RegEnumValueW(key, idx++, name, &nameSize, NULL, NULL, NULL, NULL);\n }\n\n return thisRegistered;\n}\n\nbool VulkanReplay::CheckVulkanLayer(VulkanLayerFlags &flags, std::vector<std::string> &myJSONs,\n std::vector<std::string> &otherJSONs)\n{\n std::wstring normalPath = GetJSONPath(false);\n myJSONs.push_back(StringFormat::Wide2UTF8(normalPath));\n\n#if ENABLED(RDOC_X64)\n std::wstring wow6432Path = GetJSONPath(true);\n myJSONs.push_back(StringFormat::Wide2UTF8(wow6432Path));\n#endif\n\n HKEY key = GetImplicitLayersKey(false, false);\n\n \/\/ if we couldn't even get the ImplicitLayers reg key the system doesn't have the\n \/\/ vulkan runtime, so we return as if we are not registered (as that's the case).\n \/\/ People not using vulkan can either ignore the message, or click to set it up\n \/\/ and it will go away as we'll have rights to create it.\n if(!key)\n {\n flags = VulkanLayerFlags::NeedElevation | VulkanLayerFlags::RegisterAll;\n return true;\n }\n\n bool thisRegistered = ProcessImplicitLayersKey(key, normalPath, &otherJSONs, false);\n\n RegCloseKey(key);\n\n#if ENABLED(RDOC_X64)\n {\n key = GetImplicitLayersKey(false, true);\n\n \/\/ if we're on 64-bit, the layer isn't registered unless both keys are registered.\n thisRegistered = false;\n\n if(key)\n {\n thisRegistered = ProcessImplicitLayersKey(key, wow6432Path, &otherJSONs, false);\n\n RegCloseKey(key);\n }\n }\n#endif\n\n flags = VulkanLayerFlags::NeedElevation | VulkanLayerFlags::RegisterAll;\n\n if(thisRegistered)\n flags |= VulkanLayerFlags::ThisInstallRegistered;\n\n if(!otherJSONs.empty())\n flags |= VulkanLayerFlags::OtherInstallsRegistered;\n\n \/\/ return true if any changes are needed\n return !otherJSONs.empty() || !thisRegistered;\n}\n\nvoid VulkanReplay::InstallVulkanLayer(bool systemLevel)\n{\n HKEY key = GetImplicitLayersKey(true, false);\n\n const DWORD zero = 0;\n\n if(key)\n {\n std::wstring path = GetJSONPath(false);\n\n \/\/ this function will delete all non-matching renderdoc.json values, and return true if our own\n \/\/ is registered\n bool thisRegistered = ProcessImplicitLayersKey(key, path, NULL, true);\n\n if(!thisRegistered)\n RegSetValueExW(key, path.c_str(), 0, REG_DWORD, (const BYTE *)&zero, sizeof(zero));\n\n RegCloseKey(key);\n }\n\n\/\/ if we're a 64-bit process, update the 32-bit key\n#if ENABLED(RDOC_X64)\n {\n key = GetImplicitLayersKey(true, true);\n\n if(key)\n {\n std::wstring path = GetJSONPath(true);\n\n \/\/ this function will delete all non-matching renderdoc.json values, and return true if our\n \/\/ own is registered\n bool thisRegistered = ProcessImplicitLayersKey(key, path, NULL, true);\n\n if(!thisRegistered)\n RegSetValueExW(key, path.c_str(), 0, REG_DWORD, (const BYTE *)&zero, sizeof(zero));\n\n RegCloseKey(key);\n }\n }\n#endif\n}\n<commit_msg>Don't allow registered x86 layer to hide a non-registered x64 layer<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2015-2018 Baldur Karlsson\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\n#include \"vk_core.h\"\n#include \"vk_replay.h\"\n\nstatic int dllLocator = 0;\n\nvoid VulkanReplay::OutputWindow::SetWindowHandle(WindowingData window)\n{\n RDCASSERT(window.system == WindowingSystem::Win32, window.system);\n wnd = window.win32.window;\n}\n\nvoid VulkanReplay::OutputWindow::CreateSurface(VkInstance inst)\n{\n VkWin32SurfaceCreateInfoKHR createInfo;\n\n createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;\n createInfo.pNext = NULL;\n createInfo.flags = 0;\n createInfo.hwnd = wnd;\n\n GetModuleHandleExA(\n GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,\n (const char *)&dllLocator, (HMODULE *)&createInfo.hinstance);\n\n VkResult vkr = ObjDisp(inst)->CreateWin32SurfaceKHR(Unwrap(inst), &createInfo, NULL, &surface);\n RDCASSERTEQUAL(vkr, VK_SUCCESS);\n}\n\nvoid VulkanReplay::GetOutputWindowDimensions(uint64_t id, int32_t &w, int32_t &h)\n{\n if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end())\n return;\n\n OutputWindow &outw = m_OutputWindows[id];\n\n RECT rect = {0};\n GetClientRect(outw.wnd, &rect);\n w = rect.right - rect.left;\n h = rect.bottom - rect.top;\n}\n\nbool VulkanReplay::IsOutputWindowVisible(uint64_t id)\n{\n if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end())\n return false;\n\n return (IsWindowVisible(m_OutputWindows[id].wnd) == TRUE);\n}\n\nvoid WrappedVulkan::AddRequiredExtensions(bool instance, vector<string> &extensionList,\n const std::set<string> &supportedExtensions)\n{\n bool device = !instance;\n\n if(instance)\n {\n \/\/ for windows we require both extensions as there's no alternative\n if(supportedExtensions.find(VK_KHR_SURFACE_EXTENSION_NAME) == supportedExtensions.end())\n {\n RDCERR(\"Unsupported required instance extension '%s'\", VK_KHR_SURFACE_EXTENSION_NAME);\n }\n else\n {\n \/\/ don't add duplicates\n if(std::find(extensionList.begin(), extensionList.end(), VK_KHR_SURFACE_EXTENSION_NAME) ==\n extensionList.end())\n extensionList.push_back(VK_KHR_SURFACE_EXTENSION_NAME);\n }\n\n if(supportedExtensions.find(VK_KHR_WIN32_SURFACE_EXTENSION_NAME) == supportedExtensions.end())\n {\n RDCERR(\"Unsupported required instance extension '%s'\", VK_KHR_WIN32_SURFACE_EXTENSION_NAME);\n }\n else\n {\n if(std::find(extensionList.begin(), extensionList.end(),\n VK_KHR_WIN32_SURFACE_EXTENSION_NAME) == extensionList.end())\n extensionList.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);\n }\n }\n else if(device)\n {\n if(supportedExtensions.find(VK_KHR_SWAPCHAIN_EXTENSION_NAME) == supportedExtensions.end())\n {\n RDCERR(\"Unsupported required device extension '%s'\", VK_KHR_SWAPCHAIN_EXTENSION_NAME);\n }\n else\n {\n \/\/ don't add duplicates\n if(std::find(extensionList.begin(), extensionList.end(), VK_KHR_SWAPCHAIN_EXTENSION_NAME) ==\n extensionList.end())\n extensionList.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);\n }\n }\n}\n\n#if !defined(VK_USE_PLATFORM_WIN32_KHR)\n#error \"Win32 KHR platform not defined\"\n#endif\n\nVkResult WrappedVulkan::vkCreateWin32SurfaceKHR(VkInstance instance,\n const VkWin32SurfaceCreateInfoKHR *pCreateInfo,\n const VkAllocationCallbacks *pAllocator,\n VkSurfaceKHR *pSurface)\n{\n \/\/ should not come in here at all on replay\n RDCASSERT(IsCaptureMode(m_State));\n\n VkResult ret =\n ObjDisp(instance)->CreateWin32SurfaceKHR(Unwrap(instance), pCreateInfo, pAllocator, pSurface);\n\n if(ret == VK_SUCCESS)\n {\n GetResourceManager()->WrapResource(Unwrap(instance), *pSurface);\n\n WrappedVkSurfaceKHR *wrapped = GetWrapped(*pSurface);\n\n \/\/ since there's no point in allocating a full resource record and storing the window\n \/\/ handle under there somewhere, we just cast. We won't use the resource record for anything\n wrapped->record = (VkResourceRecord *)pCreateInfo->hwnd;\n\n Keyboard::AddInputWindow((void *)pCreateInfo->hwnd);\n }\n\n return ret;\n}\n\nVkBool32 WrappedVulkan::vkGetPhysicalDeviceWin32PresentationSupportKHR(VkPhysicalDevice physicalDevice,\n uint32_t queueFamilyIndex)\n{\n return ObjDisp(physicalDevice)\n ->GetPhysicalDeviceWin32PresentationSupportKHR(Unwrap(physicalDevice), queueFamilyIndex);\n}\n\nconst char *VulkanLibraryName = \"vulkan-1.dll\";\n\nstd::wstring GetJSONPath(bool wow6432)\n{\n wchar_t curFile[1024];\n GetModuleFileNameW(NULL, curFile, 1024);\n\n wchar_t *lastSlash = wcsrchr(curFile, '\\\\');\n if(lastSlash)\n *(lastSlash + 1) = 0;\n\n if(wow6432)\n wcscat_s(curFile, L\"x86\\\\\");\n\n wcscat_s(curFile, L\"renderdoc.json\");\n\n return curFile;\n}\n\nstatic HKEY GetImplicitLayersKey(bool writeable, bool wow6432)\n{\n std::string basepath = \"SOFTWARE\\\\\";\n\n if(wow6432)\n basepath += \"Wow6432Node\\\\\";\n\n basepath += \"Khronos\\\\Vulkan\\\\ImplicitLayers\";\n\n HKEY key = NULL;\n LSTATUS ret = ERROR_SUCCESS;\n\n if(writeable)\n ret = RegCreateKeyExA(HKEY_LOCAL_MACHINE, basepath.c_str(), 0, NULL, 0, KEY_READ | KEY_WRITE,\n NULL, &key, NULL);\n else\n ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, basepath.c_str(), 0, KEY_READ, &key);\n\n if(ret != ERROR_SUCCESS)\n {\n if(key)\n RegCloseKey(key);\n\n \/\/ find to fail to open for read, the key may not exist\n if(writeable)\n RDCERR(\"Couldn't open %s for write\", basepath.c_str());\n\n return NULL;\n }\n\n return key;\n}\n\nbool ProcessImplicitLayersKey(HKEY key, const std::wstring &path,\n std::vector<std::string> *otherJSONs, bool deleteOthers)\n{\n bool thisRegistered = false;\n\n wchar_t name[1025] = {};\n DWORD nameSize = 1024;\n DWORD idx = 0;\n\n LONG ret = RegEnumValueW(key, idx++, name, &nameSize, NULL, NULL, NULL, NULL);\n\n std::wstring myJSON = path;\n for(size_t i = 0; i < myJSON.size(); i++)\n myJSON[i] = towlower(myJSON[i]);\n\n while(ret == ERROR_SUCCESS)\n {\n \/\/ convert the name here so we preserve casing\n std::string utf8name = StringFormat::Wide2UTF8(name);\n\n for(DWORD i = 0; i <= nameSize && name[i]; i++)\n name[i] = towlower(name[i]);\n\n if(wcscmp(name, myJSON.c_str()) == 0)\n {\n thisRegistered = true;\n }\n else if(wcsstr(name, L\"renderdoc.json\") != NULL)\n {\n if(otherJSONs)\n otherJSONs->push_back(utf8name);\n\n if(deleteOthers)\n RegDeleteValueW(key, name);\n }\n\n nameSize = 1024;\n ret = RegEnumValueW(key, idx++, name, &nameSize, NULL, NULL, NULL, NULL);\n }\n\n return thisRegistered;\n}\n\nbool VulkanReplay::CheckVulkanLayer(VulkanLayerFlags &flags, std::vector<std::string> &myJSONs,\n std::vector<std::string> &otherJSONs)\n{\n std::wstring normalPath = GetJSONPath(false);\n myJSONs.push_back(StringFormat::Wide2UTF8(normalPath));\n\n#if ENABLED(RDOC_X64)\n std::wstring wow6432Path = GetJSONPath(true);\n myJSONs.push_back(StringFormat::Wide2UTF8(wow6432Path));\n#endif\n\n HKEY key = GetImplicitLayersKey(false, false);\n\n \/\/ if we couldn't even get the ImplicitLayers reg key the system doesn't have the\n \/\/ vulkan runtime, so we return as if we are not registered (as that's the case).\n \/\/ People not using vulkan can either ignore the message, or click to set it up\n \/\/ and it will go away as we'll have rights to create it.\n if(!key)\n {\n flags = VulkanLayerFlags::NeedElevation | VulkanLayerFlags::RegisterAll;\n return true;\n }\n\n bool thisRegistered = ProcessImplicitLayersKey(key, normalPath, &otherJSONs, false);\n\n RegCloseKey(key);\n\n#if ENABLED(RDOC_X64)\n {\n key = GetImplicitLayersKey(false, true);\n\n if(key)\n {\n \/\/ if we're on 64-bit, the layer isn't registered unless both keys are registered.\n thisRegistered &= ProcessImplicitLayersKey(key, wow6432Path, &otherJSONs, false);\n\n RegCloseKey(key);\n }\n else\n {\n flags = VulkanLayerFlags::NeedElevation | VulkanLayerFlags::RegisterAll;\n return true;\n }\n }\n#endif\n\n flags = VulkanLayerFlags::NeedElevation | VulkanLayerFlags::RegisterAll;\n\n if(thisRegistered)\n flags |= VulkanLayerFlags::ThisInstallRegistered;\n\n if(!otherJSONs.empty())\n flags |= VulkanLayerFlags::OtherInstallsRegistered;\n\n \/\/ return true if any changes are needed\n return !otherJSONs.empty() || !thisRegistered;\n}\n\nvoid VulkanReplay::InstallVulkanLayer(bool systemLevel)\n{\n HKEY key = GetImplicitLayersKey(true, false);\n\n const DWORD zero = 0;\n\n if(key)\n {\n std::wstring path = GetJSONPath(false);\n\n \/\/ this function will delete all non-matching renderdoc.json values, and return true if our own\n \/\/ is registered\n bool thisRegistered = ProcessImplicitLayersKey(key, path, NULL, true);\n\n if(!thisRegistered)\n RegSetValueExW(key, path.c_str(), 0, REG_DWORD, (const BYTE *)&zero, sizeof(zero));\n\n RegCloseKey(key);\n }\n\n\/\/ if we're a 64-bit process, update the 32-bit key\n#if ENABLED(RDOC_X64)\n {\n key = GetImplicitLayersKey(true, true);\n\n if(key)\n {\n std::wstring path = GetJSONPath(true);\n\n \/\/ this function will delete all non-matching renderdoc.json values, and return true if our\n \/\/ own is registered\n bool thisRegistered = ProcessImplicitLayersKey(key, path, NULL, true);\n\n if(!thisRegistered)\n RegSetValueExW(key, path.c_str(), 0, REG_DWORD, (const BYTE *)&zero, sizeof(zero));\n\n RegCloseKey(key);\n }\n }\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ AliFemtoCorrFctnPairFractions - A correlation function that analyzes \/\/\n\/\/ two particle correlations with respect to the azimuthal angle (phi) \/\/\n\/\/ and pseudorapidity (eta) difference \/\/\n\/\/ \/\/\n\/\/ Authors: Malgorzata Janik, majanik@cern.ch \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliFemtoCorrFctnPairFractions.h\"\n#include \"AliFemtoModelHiddenInfo.h\"\n\/\/#include \"AliFemtoHisto.hh\"\n#include <cstdio>\n#include <TMath.h>\n\n#ifdef __ROOT__ \nClassImp(AliFemtoCorrFctnPairFractions)\n#endif\n \n#define PIH 1.57079632679489656\n#define PIT 6.28318530717958623\n\n\/\/____________________________\nAliFemtoCorrFctnPairFractions::AliFemtoCorrFctnPairFractions(char* title):\nAliFemtoCorrFctn(),\n fPairFractions(0),\n fphiL(0),\n fphiT(0)\n{\n\n \/\/fphiL = (-(int)(aPhiBins\/4)+0.5)*2.*TMath::Pi()\/aPhiBins;\n \/\/fphiT = 2*TMath::Pi()+(-(int)(aPhiBins\/4)+0.5)*2.*TMath::Pi()\/aPhiBins;\n\n TString hname = \"hPairFraction\"; hname+= title;\n TString htitle = \"Pair Fraction \"; htitle+= title;\n fPairFractions = new TH1F(hname.Data(),htitle.Data(), 7, 0, 7);\n fPairFractions->GetXaxis()->SetBinLabel(1,\"#pi#pi, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(2,\"KK, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(3,\"pp, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(4,\"#pi K, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(5,\"#pi p, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(6,\"Kp, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(7,\"Other, MC\");\n\n\n \/\/ to enable error bar calculation...\n\n fPairFractions->Sumw2();\n fPairFractions->Sumw2();\n}\n\n\/\/____________________________\nAliFemtoCorrFctnPairFractions::AliFemtoCorrFctnPairFractions(const AliFemtoCorrFctnPairFractions& aCorrFctn) :\n AliFemtoCorrFctn(),\n fPairFractions(0),\n fphiL(0),\n fphiT(0)\n{\n \/\/ copy constructor\n if (aCorrFctn.fPairFractions)\n fPairFractions = new TH1F(*aCorrFctn.fPairFractions);\n else\n fPairFractions = 0;\n\n if (aCorrFctn.fPairFractions)\n fPairFractions = new TH1F(*aCorrFctn.fPairFractions);\n else\n fPairFractions = 0;\n\n fphiL = aCorrFctn.fphiL;\n fphiT = aCorrFctn.fphiT;\n\n\n}\n\/\/____________________________\nAliFemtoCorrFctnPairFractions::~AliFemtoCorrFctnPairFractions(){\n \/\/ destructor\n delete fPairFractions;\n delete fPairFractions;\n}\n\/\/_________________________\nAliFemtoCorrFctnPairFractions& AliFemtoCorrFctnPairFractions::operator=(const AliFemtoCorrFctnPairFractions& aCorrFctn)\n{\n \/\/ assignment operator\n if (this == &aCorrFctn)\n return *this;\n\n if (aCorrFctn.fPairFractions)\n fPairFractions = new TH1F(*aCorrFctn.fPairFractions);\n else\n fPairFractions = 0;\n\n \n fphiL = aCorrFctn.fphiL;\n fphiT = aCorrFctn.fphiT;\n\n return *this;\n}\n\/\/_________________________\nvoid AliFemtoCorrFctnPairFractions::Finish(){\n \/\/ here is where we should normalize, fit, etc...\n \/\/ we should NOT Draw() the histos (as I had done it below),\n \/\/ since we want to insulate ourselves from root at this level\n \/\/ of the code. Do it instead at root command line with browser.\n \/\/ mShareNumerator->Draw();\n \/\/ mShareDenominator->Draw();\n \/\/ mRatio->Draw();\n\n}\n\n\/\/____________________________\nAliFemtoString AliFemtoCorrFctnPairFractions::Report(){\n \/\/ create report\n string stemp = \"Pair Fractions Correlation Function Report:\\n\";\n char ctemp[100];\n snprintf(ctemp , 100, \"Number of entries in numerator:\\t%E\\n\",fPairFractions->GetEntries());\n stemp += ctemp;\n snprintf(ctemp , 100, \"Number of entries in denominator:\\t%E\\n\",fPairFractions->GetEntries());\n stemp += ctemp;\n \/\/ stemp += mCoulombWeight->Report();\n AliFemtoString returnThis = stemp;\n return returnThis;\n}\n\/\/____________________________\nvoid AliFemtoCorrFctnPairFractions::AddRealPair( AliFemtoPair* pair){\n \/\/ add real (effect) pair\n\n \/\/Applying pair cuts\n if (fPairCut)\n if (!fPairCut->Pass(pair)) return;\n\n\n\n Int_t pdg1=0;\n AliFemtoModelHiddenInfo *info1 = ( AliFemtoModelHiddenInfo *) pair->Track1()->GetHiddenInfo();\n if(info1)pdg1 = info1->GetPDGPid();\n\n Int_t pdg2=0;\n AliFemtoModelHiddenInfo *info2 = ( AliFemtoModelHiddenInfo *) pair->Track2()->GetHiddenInfo();\n if(info2)pdg2 = info2->GetPDGPid();\n\n if(abs(pdg1)==211 && abs(pdg2)==211) \/\/pi pi\n fPairFractions->Fill(0.5);\n else if(abs(pdg1)==321 && abs(pdg2)==321)\/\/ K K\n fPairFractions->Fill(1.5);\n else if(abs(pdg1)==2212 && abs(pdg2)==2212)\/\/ p p\n fPairFractions->Fill(2.5);\n else if(abs(pdg1)==211 && abs(pdg2)==321)\/\/ pi K\n fPairFractions->Fill(3.5);\n else if(abs(pdg1)==211 && abs(pdg2)==2212)\/\/ pi p\n fPairFractions->Fill(4.5);\n else if(abs(pdg1)==321 && abs(pdg2)==2212)\/\/K p\n fPairFractions->Fill(5.5);\n else \/\/other\n fPairFractions->Fill(6.5);\n\n \/*double phi1 = pair->Track1()->Track()->P().Phi();\n double phi2 = pair->Track2()->Track()->P().Phi();\n double eta1 = pair->Track1()->Track()->P().PseudoRapidity();\n double eta2 = pair->Track2()->Track()->P().PseudoRapidity();\n\n double phi1 = pair->Track1()->FourMomentum().Phi();\n double phi2 = pair->Track2()->FourMomentum().Phi();\n double eta1 = pair->Track1()->FourMomentum().PseudoRapidity();\n double eta2 = pair->Track2()->FourMomentum().PseudoRapidity();\n\n double dphi = phi1 - phi2;\n while (dphi<fphiL) dphi+=PIT;\n while (dphi>fphiT) dphi-=PIT;\n\n double deta = eta1 - eta2;\n\n double px1 = pair->Track1()->Track()->P().x();\n double py1 = pair->Track1()->Track()->P().y();\n double px2 = pair->Track2()->Track()->P().x();\n double py2 = pair->Track2()->Track()->P().y();\n double pt1 = TMath::Hypot(px1, py1);\n double pt2 = TMath::Hypot(px2, py2);\n\n\n double PionMass = 0.13956995;*\/\n \n}\n\/\/____________________________\nvoid AliFemtoCorrFctnPairFractions::AddMixedPair( AliFemtoPair* pair){\n \/\/ add mixed (background) pair\n if (fPairCut)\n if (!fPairCut->Pass(pair)) return;\n\n}\n\n\nvoid AliFemtoCorrFctnPairFractions::WriteHistos()\n{\n \/\/ Write out result histograms\n fPairFractions->Write();\n}\n\nTList* AliFemtoCorrFctnPairFractions::GetOutputList()\n{\n \/\/ Prepare the list of objects to be written to the output\n TList *tOutputList = new TList();\n\n tOutputList->Add(fPairFractions);\n\n\n return tOutputList;\n\n}\n<commit_msg>correction to new pair fraction correlation function<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ AliFemtoCorrFctnPairFractions - A correlation function that analyzes \/\/\n\/\/ two particle correlations with respect to the azimuthal angle (phi) \/\/\n\/\/ and pseudorapidity (eta) difference \/\/\n\/\/ \/\/\n\/\/ Authors: Malgorzata Janik, majanik@cern.ch \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliFemtoCorrFctnPairFractions.h\"\n#include \"AliFemtoModelHiddenInfo.h\"\n\/\/#include \"AliFemtoHisto.hh\"\n#include <cstdio>\n#include <TMath.h>\n\n#ifdef __ROOT__ \nClassImp(AliFemtoCorrFctnPairFractions)\n#endif\n \n#define PIH 1.57079632679489656\n#define PIT 6.28318530717958623\n\n\/\/____________________________\nAliFemtoCorrFctnPairFractions::AliFemtoCorrFctnPairFractions(char* title):\nAliFemtoCorrFctn(),\n fPairFractions(0),\n fphiL(0),\n fphiT(0)\n{\n\n \/\/fphiL = (-(int)(aPhiBins\/4)+0.5)*2.*TMath::Pi()\/aPhiBins;\n \/\/fphiT = 2*TMath::Pi()+(-(int)(aPhiBins\/4)+0.5)*2.*TMath::Pi()\/aPhiBins;\n\n TString hname = \"hPairFraction\"; hname+= title;\n TString htitle = \"Pair Fraction \"; htitle+= title;\n fPairFractions = new TH1F(hname.Data(),htitle.Data(), 7, 0, 7);\n fPairFractions->GetXaxis()->SetBinLabel(1,\"#pi#pi, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(2,\"KK, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(3,\"pp, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(4,\"#pi K, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(5,\"#pi p, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(6,\"Kp, MC\");\n fPairFractions->GetXaxis()->SetBinLabel(7,\"Other, MC\");\n\n\n \/\/ to enable error bar calculation...\n\n fPairFractions->Sumw2();\n fPairFractions->Sumw2();\n}\n\n\/\/____________________________\nAliFemtoCorrFctnPairFractions::AliFemtoCorrFctnPairFractions(const AliFemtoCorrFctnPairFractions& aCorrFctn) :\n AliFemtoCorrFctn(),\n fPairFractions(0),\n fphiL(0),\n fphiT(0)\n{\n \/\/ copy constructor\n if (aCorrFctn.fPairFractions)\n fPairFractions = new TH1F(*aCorrFctn.fPairFractions);\n else\n fPairFractions = 0;\n\n if (aCorrFctn.fPairFractions)\n fPairFractions = new TH1F(*aCorrFctn.fPairFractions);\n else\n fPairFractions = 0;\n\n fphiL = aCorrFctn.fphiL;\n fphiT = aCorrFctn.fphiT;\n\n\n}\n\/\/____________________________\nAliFemtoCorrFctnPairFractions::~AliFemtoCorrFctnPairFractions(){\n \/\/ destructor\n if(fPairFractions)\n delete fPairFractions;\n \n}\n\/\/_________________________\nAliFemtoCorrFctnPairFractions& AliFemtoCorrFctnPairFractions::operator=(const AliFemtoCorrFctnPairFractions& aCorrFctn)\n{\n \/\/ assignment operator\n if (this == &aCorrFctn)\n return *this;\n\n if (aCorrFctn.fPairFractions)\n fPairFractions = new TH1F(*aCorrFctn.fPairFractions);\n else\n fPairFractions = 0;\n\n \n fphiL = aCorrFctn.fphiL;\n fphiT = aCorrFctn.fphiT;\n\n return *this;\n}\n\/\/_________________________\nvoid AliFemtoCorrFctnPairFractions::Finish(){\n \/\/ here is where we should normalize, fit, etc...\n \/\/ we should NOT Draw() the histos (as I had done it below),\n \/\/ since we want to insulate ourselves from root at this level\n \/\/ of the code. Do it instead at root command line with browser.\n \/\/ mShareNumerator->Draw();\n \/\/ mShareDenominator->Draw();\n \/\/ mRatio->Draw();\n\n}\n\n\/\/____________________________\nAliFemtoString AliFemtoCorrFctnPairFractions::Report(){\n \/\/ create report\n string stemp = \"Pair Fractions Correlation Function Report:\\n\";\n char ctemp[100];\n snprintf(ctemp , 100, \"Number of entries in numerator:\\t%E\\n\",fPairFractions->GetEntries());\n stemp += ctemp;\n snprintf(ctemp , 100, \"Number of entries in denominator:\\t%E\\n\",fPairFractions->GetEntries());\n stemp += ctemp;\n \/\/ stemp += mCoulombWeight->Report();\n AliFemtoString returnThis = stemp;\n return returnThis;\n}\n\/\/____________________________\nvoid AliFemtoCorrFctnPairFractions::AddRealPair( AliFemtoPair* pair){\n \/\/ add real (effect) pair\n\n \/\/Applying pair cuts\n if (fPairCut)\n if (!fPairCut->Pass(pair)) return;\n\n\n\n Int_t pdg1=0;\n AliFemtoModelHiddenInfo *info1 = ( AliFemtoModelHiddenInfo *) pair->Track1()->GetHiddenInfo();\n if(info1)pdg1 = info1->GetPDGPid();\n\n Int_t pdg2=0;\n AliFemtoModelHiddenInfo *info2 = ( AliFemtoModelHiddenInfo *) pair->Track2()->GetHiddenInfo();\n if(info2)pdg2 = info2->GetPDGPid();\n\n if(abs(pdg1)==211 && abs(pdg2)==211) \/\/pi pi\n fPairFractions->Fill(0.5);\n else if(abs(pdg1)==321 && abs(pdg2)==321)\/\/ K K\n fPairFractions->Fill(1.5);\n else if(abs(pdg1)==2212 && abs(pdg2)==2212)\/\/ p p\n fPairFractions->Fill(2.5);\n else if(abs(pdg1)==211 && abs(pdg2)==321)\/\/ pi K\n fPairFractions->Fill(3.5);\n else if(abs(pdg1)==211 && abs(pdg2)==2212)\/\/ pi p\n fPairFractions->Fill(4.5);\n else if(abs(pdg1)==321 && abs(pdg2)==2212)\/\/K p\n fPairFractions->Fill(5.5);\n else \/\/other\n fPairFractions->Fill(6.5);\n\n \/*double phi1 = pair->Track1()->Track()->P().Phi();\n double phi2 = pair->Track2()->Track()->P().Phi();\n double eta1 = pair->Track1()->Track()->P().PseudoRapidity();\n double eta2 = pair->Track2()->Track()->P().PseudoRapidity();\n\n double phi1 = pair->Track1()->FourMomentum().Phi();\n double phi2 = pair->Track2()->FourMomentum().Phi();\n double eta1 = pair->Track1()->FourMomentum().PseudoRapidity();\n double eta2 = pair->Track2()->FourMomentum().PseudoRapidity();\n\n double dphi = phi1 - phi2;\n while (dphi<fphiL) dphi+=PIT;\n while (dphi>fphiT) dphi-=PIT;\n\n double deta = eta1 - eta2;\n\n double px1 = pair->Track1()->Track()->P().x();\n double py1 = pair->Track1()->Track()->P().y();\n double px2 = pair->Track2()->Track()->P().x();\n double py2 = pair->Track2()->Track()->P().y();\n double pt1 = TMath::Hypot(px1, py1);\n double pt2 = TMath::Hypot(px2, py2);\n\n\n double PionMass = 0.13956995;*\/\n \n}\n\/\/____________________________\nvoid AliFemtoCorrFctnPairFractions::AddMixedPair( AliFemtoPair* pair){\n \/\/ add mixed (background) pair\n if (fPairCut)\n if (!fPairCut->Pass(pair)) return;\n\n}\n\n\nvoid AliFemtoCorrFctnPairFractions::WriteHistos()\n{\n \/\/ Write out result histograms\n fPairFractions->Write();\n}\n\nTList* AliFemtoCorrFctnPairFractions::GetOutputList()\n{\n \/\/ Prepare the list of objects to be written to the output\n TList *tOutputList = new TList();\n\n tOutputList->Add(fPairFractions);\n\n\n return tOutputList;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ runV0ChCorrelations.C\n\/\/\n\/\/ AddTask for AliAnalysisTaskV0ChCorrelations task\n\/\/\nAliAnalysisTaskV0ChCorrelations *AddTaskV0ChCorrelations(const Bool_t bMCtruth=kFALSE)\n{\n \/\/ Creates a V0Ch correlations analysis task and adds it to the analysis manager.\n\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskV0ChCorrelations\", \"No analysis manager to connect to.\");\n return NULL;\n }\n\n \/\/ mc event handlerrunEx01.C\n if(bMCtruth) {\n AliMCEventHandler* mchandler = new AliMCEventHandler();\n \/\/ Not reading track references\n mchandler->SetReadTR(kFALSE);\n mgr->SetMCtruthEventHandler(mchandler);\n } \n\n\t\/\/ create task\n AliAnalysisTaskV0ChCorrelations* task = new AliAnalysisTaskV0ChCorrelations(\"V0ChCorrelations_task\");\n mgr->AddTask(task);\n \n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName = \"list.grid.v0ch.root\";\n\n \/\/ create containers for input\/output\n AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"coutput1\", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);\n \n \/\/ connect input\/output\n mgr->ConnectInput(task, 0, cinput);\n mgr->ConnectOutput(task, 1, coutput1);\n \n \/\/ Return task pointer at the end\n return task;\n}\n\n<commit_msg><commit_after>\/\/ runV0ChCorrelations.C\n\/\/\n\/\/ AddTask for AliAnalysisTaskV0ChCorrelations task\n\/\/\nAliAnalysisTaskV0ChCorrelations *AddTaskV0ChCorrelations(const Bool_t bMCtruth=kFALSE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Float_t DcaDToPV = 0.5,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Float_t DcaV0D = 0.1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n{\n \/\/ Creates a V0Ch correlations analysis task and adds it to the analysis manager.\n\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskV0ChCorrelations\", \"No analysis manager to connect to.\");\n return NULL;\n }\n\n \/\/ mc event handlerrunEx01.C\n if(bMCtruth) {\n AliMCEventHandler* mchandler = new AliMCEventHandler();\n \/\/ Not reading track references\n mchandler->SetReadTR(kFALSE);\n mgr->SetMCtruthEventHandler(mchandler);\n } \n\n\t\/\/ create task\n AliAnalysisTaskV0ChCorrelations* task = new AliAnalysisTaskV0ChCorrelations(\"V0ChCorrelations_task\");\n\ttask->SetDcaDToPV(DcaDToPV);\n\ttask->SetDcaV0D(DcaV0D);\n mgr->AddTask(task);\n \n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName = \"list.grid.v0ch.root\";\n\n \/\/ create containers for input\/output\n AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"coutput1\", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);\n \n \/\/ connect input\/output\n mgr->ConnectInput(task, 0, cinput);\n mgr->ConnectOutput(task, 1, coutput1);\n \n \/\/ Return task pointer at the end\n return task;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, 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\/magnet_uri.hpp\"\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/torrent_handle.hpp\"\n#include \"libtorrent\/escape_string.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\n#include <string>\n\nnamespace libtorrent\n{\n\tstd::string make_magnet_uri(torrent_handle const& handle)\n\t{\n\t\tif (!handle.is_valid()) return \"\";\n\n\t\tchar ret[1024];\n\t\tsha1_hash const& ih = handle.info_hash();\n\t\tint num_chars = snprintf(ret, sizeof(ret), \"magnet:?xt=urn:btih:%s\"\n\t\t\t, base32encode(std::string((char const*)&ih[0], 20)).c_str());\n\n\t\tstd::string name = handle.name();\n\n\t\tif (!name.empty())\n\t\t\tnum_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, \"&dn=%s\"\n\t\t\t\t, escape_string(name.c_str(), name.length()).c_str());\n\n\t\tstd::string tracker;\n\t\ttorrent_status st = handle.status();\n\t\tif (!st.current_tracker.empty())\n\t\t{\n\t\t\ttracker = st.current_tracker;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::vector<announce_entry> const& tr = handle.trackers();\n\t\t\tif (!tr.empty()) tracker = tr[0].url;\n\t\t}\n\t\tif (!tracker.empty())\n\t\t\tnum_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, \"&tr=%s\"\n\t\t\t\t, escape_string(tracker.c_str(), tracker.size()).c_str());\n\n\t\treturn ret;\n\t}\n\n\tstd::string make_magnet_uri(torrent_info const& info)\n\t{\n\t\tchar ret[1024];\n\t\tsha1_hash const& ih = info.info_hash();\n\t\tint num_chars = snprintf(ret, sizeof(ret), \"magnet:?xt=urn:btih:%s\"\n\t\t\t, base32encode(std::string((char*)&ih[0], 20)).c_str());\n\n\t\tstd::string const& name = info.name();\n\n\t\tif (!name.empty())\n\t\t\tnum_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, \"&dn=%s\"\n\t\t\t\t, escape_string(name.c_str(), name.length()).c_str());\n\n\t\tstd::vector<announce_entry> const& tr = info.trackers();\n\t\tif (!tr.empty())\n\t\t{\n\t\t\tnum_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, \"&tr=%s\"\n\t\t\t\t, escape_string(tr[0].url.c_str(), tr[0].url.length()).c_str());\n\t\t}\n\n\t\treturn ret;\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n#ifndef TORRENT_NO_DEPRECATE\n\ttorrent_handle add_magnet_uri(session& ses, std::string const& uri\n\t\t, std::string const& save_path\n\t\t, storage_mode_t storage_mode\n\t\t, bool paused\n\t\t, storage_constructor_type sc\n\t\t, void* userdata)\n\t{\n\t\tstd::string name;\n\t\tstd::string tracker;\n\n\t\terror_code ec;\n\t\tstd::string display_name = url_has_argument(uri, \"dn\");\n\t\tif (!display_name.empty()) name = unescape_string(display_name.c_str(), ec);\n\t\tstd::string tracker_string = url_has_argument(uri, \"tr\");\n\t\tif (!tracker_string.empty()) tracker = unescape_string(tracker_string.c_str(), ec);\n\t\n\t\tstd::string btih = url_has_argument(uri, \"xt\");\n\t\tif (btih.empty()) return torrent_handle();\n\n\t\tif (btih.compare(0, 9, \"urn:btih:\") != 0) return torrent_handle();\n\n\t\tsha1_hash info_hash;\n\t\tif (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);\n\t\telse info_hash.assign(base32decode(btih.substr(9)));\n\n\t\treturn ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash\n\t\t\t, name.empty() ? 0 : name.c_str(), save_path, entry()\n\t\t\t, storage_mode, paused, sc, userdata);\n\t}\n#endif\n\n\ttorrent_handle add_magnet_uri(session& ses, std::string const& uri\n\t\t, add_torrent_params p)\n\t{\n\t\terror_code ec;\n\t\ttorrent_handle ret = add_magnet_uri(ses, uri, p, ec);\n\t\tif (ec) throw libtorrent_exception(ec);\n\t\treturn ret;\n\t}\n#endif\n\n\ttorrent_handle add_magnet_uri(session& ses, std::string const& uri\n\t\t, add_torrent_params p, error_code& ec)\n\t{\n\t\tparse_magnet_uri(uri, p, ec);\n\t\tif (ec) return torrent_handle();\n\t\treturn ses.add_torrent(p, ec);\n\t}\n\n\tvoid parse_magnet_uri(std::string const& uri, add_torrent_params& p, error_code& ec)\n\t{\n\t\tstd::string name;\n\t\tstd::string tracker;\n\n\t\terror_code e;\n\t\tstd::string display_name = url_has_argument(uri, \"dn\");\n\t\tif (!display_name.empty()) name = unescape_string(display_name.c_str(), e);\n\n\t\t\/\/ parse trackers out of the magnet link\n\t\tstd::string::size_type pos = std::string::npos;\n\t\tstd::string url = url_has_argument(uri, \"tr\", &pos);\n\t\twhile (pos != std::string::npos)\n\t\t{\n\t\t\terror_code e;\n\t\t\turl = unescape_string(url, e);\n\t\t\tif (e) continue;\n\t\t\tp.trackers.push_back(url);\n\t\t\tpos = uri.find(\"&tr=\", pos);\n\t\t\tif (pos == std::string::npos) break;\n\t\t\tpos += 4;\n\t\t\turl = uri.substr(pos, uri.find('&', pos) - pos);\n\t\t}\n\t\n\t\tstd::string btih = url_has_argument(uri, \"xt\");\n\t\tif (btih.empty())\n\t\t{\n\t\t\tec = errors::missing_info_hash_in_uri;\n\t\t\treturn;\n\t\t}\n\n\t\tif (btih.compare(0, 9, \"urn:btih:\") != 0)\n\t\t{\n\t\t\tec = errors::missing_info_hash_in_uri;\n\t\t\treturn;\n\t\t}\n\n#ifndef TORRENT_DISABLE_DHT\n\t\tstd::string::size_type node_pos = std::string::npos;\n\t\tstd::string node = url_has_argument(uri, \"dht\", &node_pos);\n\t\twhile (!node.empty())\n\t\t{\n\t\t\tstd::string::size_type divider = node.find_last_of(':');\n\t\t\tif (divider != std::string::npos)\n\t\t\t{\n\t\t\t\tint port = atoi(node.c_str()+divider+1);\n\t\t\t\tif (port != 0)\n\t\t\t\t\tp.dht_nodes.push_back(std::make_pair(node.substr(0, divider), port));\n\t\t\t}\n\t\t\t\n\t\t\tnode_pos = uri.find(\"&dht=\", node_pos);\n\t\t\tif (node_pos == std::string::npos) break;\n\t\t\tnode_pos += 5;\n\t\t\tnode = uri.substr(node_pos, uri.find('&', node_pos) - node_pos);\n\t\t}\n#endif\n\n\t\tsha1_hash info_hash;\n\t\tif (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);\n\t\telse info_hash.assign(base32decode(btih.substr(9)));\n\n\t\tp.info_hash = info_hash;\n\t\tif (!name.empty()) p.name = name;\n\t}\n}\n\n\n<commit_msg>fix build without deprecated functions<commit_after>\/*\n\nCopyright (c) 2007, 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\/magnet_uri.hpp\"\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/torrent_handle.hpp\"\n#include \"libtorrent\/escape_string.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\n#include <string>\n\nnamespace libtorrent\n{\n\tstd::string make_magnet_uri(torrent_handle const& handle)\n\t{\n\t\tif (!handle.is_valid()) return \"\";\n\n\t\tchar ret[1024];\n\t\tsha1_hash const& ih = handle.info_hash();\n\t\tint num_chars = snprintf(ret, sizeof(ret), \"magnet:?xt=urn:btih:%s\"\n\t\t\t, base32encode(std::string((char const*)&ih[0], 20)).c_str());\n\n\t\tstd::string name = handle.name();\n\n\t\tif (!name.empty())\n\t\t\tnum_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, \"&dn=%s\"\n\t\t\t\t, escape_string(name.c_str(), name.length()).c_str());\n\n\t\tstd::string tracker;\n\t\ttorrent_status st = handle.status();\n\t\tif (!st.current_tracker.empty())\n\t\t{\n\t\t\ttracker = st.current_tracker;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::vector<announce_entry> const& tr = handle.trackers();\n\t\t\tif (!tr.empty()) tracker = tr[0].url;\n\t\t}\n\t\tif (!tracker.empty())\n\t\t\tnum_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, \"&tr=%s\"\n\t\t\t\t, escape_string(tracker.c_str(), tracker.size()).c_str());\n\n\t\treturn ret;\n\t}\n\n\tstd::string make_magnet_uri(torrent_info const& info)\n\t{\n\t\tchar ret[1024];\n\t\tsha1_hash const& ih = info.info_hash();\n\t\tint num_chars = snprintf(ret, sizeof(ret), \"magnet:?xt=urn:btih:%s\"\n\t\t\t, base32encode(std::string((char*)&ih[0], 20)).c_str());\n\n\t\tstd::string const& name = info.name();\n\n\t\tif (!name.empty())\n\t\t\tnum_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, \"&dn=%s\"\n\t\t\t\t, escape_string(name.c_str(), name.length()).c_str());\n\n\t\tstd::vector<announce_entry> const& tr = info.trackers();\n\t\tif (!tr.empty())\n\t\t{\n\t\t\tnum_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, \"&tr=%s\"\n\t\t\t\t, escape_string(tr[0].url.c_str(), tr[0].url.length()).c_str());\n\t\t}\n\n\t\treturn ret;\n\t}\n\n#ifndef TORRENT_NO_DEPRECATE\n#ifndef BOOST_NO_EXCEPTIONS\n\ttorrent_handle add_magnet_uri(session& ses, std::string const& uri\n\t\t, std::string const& save_path\n\t\t, storage_mode_t storage_mode\n\t\t, bool paused\n\t\t, storage_constructor_type sc\n\t\t, void* userdata)\n\t{\n\t\tstd::string name;\n\t\tstd::string tracker;\n\n\t\terror_code ec;\n\t\tstd::string display_name = url_has_argument(uri, \"dn\");\n\t\tif (!display_name.empty()) name = unescape_string(display_name.c_str(), ec);\n\t\tstd::string tracker_string = url_has_argument(uri, \"tr\");\n\t\tif (!tracker_string.empty()) tracker = unescape_string(tracker_string.c_str(), ec);\n\t\n\t\tstd::string btih = url_has_argument(uri, \"xt\");\n\t\tif (btih.empty()) return torrent_handle();\n\n\t\tif (btih.compare(0, 9, \"urn:btih:\") != 0) return torrent_handle();\n\n\t\tsha1_hash info_hash;\n\t\tif (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);\n\t\telse info_hash.assign(base32decode(btih.substr(9)));\n\n\t\treturn ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash\n\t\t\t, name.empty() ? 0 : name.c_str(), save_path, entry()\n\t\t\t, storage_mode, paused, sc, userdata);\n\t}\n\n\ttorrent_handle add_magnet_uri(session& ses, std::string const& uri\n\t\t, add_torrent_params p)\n\t{\n\t\terror_code ec;\n\t\ttorrent_handle ret = add_magnet_uri(ses, uri, p, ec);\n\t\tif (ec) throw libtorrent_exception(ec);\n\t\treturn ret;\n\t}\n#endif \/\/ BOOST_NO_EXCEPTIONS\n\n\ttorrent_handle add_magnet_uri(session& ses, std::string const& uri\n\t\t, add_torrent_params p, error_code& ec)\n\t{\n\t\tparse_magnet_uri(uri, p, ec);\n\t\tif (ec) return torrent_handle();\n\t\treturn ses.add_torrent(p, ec);\n\t}\n\n#endif \/\/ TORRENT_NO_DEPRECATE\n\n\tvoid parse_magnet_uri(std::string const& uri, add_torrent_params& p, error_code& ec)\n\t{\n\t\tstd::string name;\n\t\tstd::string tracker;\n\n\t\terror_code e;\n\t\tstd::string display_name = url_has_argument(uri, \"dn\");\n\t\tif (!display_name.empty()) name = unescape_string(display_name.c_str(), e);\n\n\t\t\/\/ parse trackers out of the magnet link\n\t\tstd::string::size_type pos = std::string::npos;\n\t\tstd::string url = url_has_argument(uri, \"tr\", &pos);\n\t\twhile (pos != std::string::npos)\n\t\t{\n\t\t\terror_code e;\n\t\t\turl = unescape_string(url, e);\n\t\t\tif (e) continue;\n\t\t\tp.trackers.push_back(url);\n\t\t\tpos = uri.find(\"&tr=\", pos);\n\t\t\tif (pos == std::string::npos) break;\n\t\t\tpos += 4;\n\t\t\turl = uri.substr(pos, uri.find('&', pos) - pos);\n\t\t}\n\t\n\t\tstd::string btih = url_has_argument(uri, \"xt\");\n\t\tif (btih.empty())\n\t\t{\n\t\t\tec = errors::missing_info_hash_in_uri;\n\t\t\treturn;\n\t\t}\n\n\t\tif (btih.compare(0, 9, \"urn:btih:\") != 0)\n\t\t{\n\t\t\tec = errors::missing_info_hash_in_uri;\n\t\t\treturn;\n\t\t}\n\n#ifndef TORRENT_DISABLE_DHT\n\t\tstd::string::size_type node_pos = std::string::npos;\n\t\tstd::string node = url_has_argument(uri, \"dht\", &node_pos);\n\t\twhile (!node.empty())\n\t\t{\n\t\t\tstd::string::size_type divider = node.find_last_of(':');\n\t\t\tif (divider != std::string::npos)\n\t\t\t{\n\t\t\t\tint port = atoi(node.c_str()+divider+1);\n\t\t\t\tif (port != 0)\n\t\t\t\t\tp.dht_nodes.push_back(std::make_pair(node.substr(0, divider), port));\n\t\t\t}\n\t\t\t\n\t\t\tnode_pos = uri.find(\"&dht=\", node_pos);\n\t\t\tif (node_pos == std::string::npos) break;\n\t\t\tnode_pos += 5;\n\t\t\tnode = uri.substr(node_pos, uri.find('&', node_pos) - node_pos);\n\t\t}\n#endif\n\n\t\tsha1_hash info_hash;\n\t\tif (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);\n\t\telse info_hash.assign(base32decode(btih.substr(9)));\n\n\t\tp.info_hash = info_hash;\n\t\tif (!name.empty()) p.name = name;\n\t}\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2012-2020, Intel Corporation\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ written by Roman Dementiev\n#define HACK_TO_REMOVE_DUPLICATE_ERROR\n#include \"cpucounters.h\"\n#ifdef _MSC_VER\n#include <windows.h>\n#include \"..\/PCM_Win\/windriver.h\"\n#else\n#include <unistd.h>\n#endif\n#include <iostream>\n#include <stdlib.h>\n#include <iomanip>\n#include <string.h>\n#ifdef _MSC_VER\n#include \"freegetopt\/getopt.h\"\n#endif\n\nuint64 read_number(char * str)\n{\n std::istringstream stream(str);\n if (strstr(str, \"x\")) stream >> std::hex;\n uint64 result = 0;\n stream >> result;\n return result;\n}\n\nvoid print_usage(const char * progname)\n{\n std::cout << \"Usage \" << progname << \" [-w value] [-c core] [-d] msr\\n\\n\";\n std::cout << \" Reads specified msr (model specific register) \\n\";\n std::cout << \" -w value : write the value before reading \\n\";\n std::cout << \" -c core : perform msr read\/write on specified core (default is 0)\\n\";\n std::cout << \" -d : output all numbers in dec (default is hex)\\n\";\n std::cout << \" -a : perform msr read\/write operations on all cores\\n\";\n std::cout << \"\\n\";\n}\n\nint main(int argc, char * argv[])\n{\n std::cout << \"\\n Processor Counter Monitor \" << PCM_VERSION << std::endl;\n\n std::cout << \"\\n MSR read\/write utility\\n\\n\";\n\n uint64 value = 0;\n bool write = false;\n int core = 0;\n int msr = -1;\n bool dec = false;\n\n int my_opt = -1;\n while ((my_opt = getopt(argc, argv, \"w:c:d:a\")) != -1)\n {\n switch (my_opt)\n {\n case 'w':\n write = true;\n value = read_number(optarg);\n break;\n case 'c':\n core = (int)read_number(optarg);\n break;\n case 'd':\n dec = true;\n break;\n case 'a':\n core = -1;\n break;\n default:\n print_usage(argv[0]);\n return -1;\n }\n }\n\n if (optind >= argc)\n {\n print_usage(argv[0]);\n return -1;\n }\n\n msr = (int)read_number(argv[optind]);\n\n #ifdef _MSC_VER\n \/\/ Increase the priority a bit to improve context switching delays on Windows\n SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);\n\n \/\/ WARNING: This driver code (msr.sys) is only for testing purposes, not for production use\n Driver drv = Driver(Driver::msrLocalPath());\n \/\/ drv.stop(); \/\/ restart driver (usually not needed)\n if (!drv.start())\n {\n std::wcerr << \"Can not load MSR driver.\" << std::endl;\n std::wcerr << \"You must have a signed driver at \" << drv.driverPath() << \" and have administrator rights to run this program\" << std::endl;\n return -1;\n }\n #endif\n auto doOne = [&dec, &write, &msr](int core, uint64 value)\n {\n try {\n MsrHandle h(core);\n if (!dec) std::cout << std::hex << std::showbase;\n if (write)\n {\n std::cout << \" Writing \" << value << \" to MSR \" << msr << \" on core \" << core << std::endl;\n if (h.write(msr, value) != 8)\n {\n std::cout << \" Write error!\" << std::endl;\n }\n }\n value = 0;\n if (h.read(msr, &value) == 8)\n {\n std::cout << \" Read value \" << value << \" from MSR \" << msr << \" on core \" << core << \"\\n\" << std::endl;\n }\n else\n {\n std::cout << \" Read error!\" << std::endl;\n }\n }\n catch (std::exception & e)\n {\n std::cerr << \"Error accessing MSRs: \" << e.what() << std::endl;\n std::cerr << \"Please check if the program can access MSR drivers.\" << std::endl;\n }\n };\n if (core >= 0)\n {\n doOne(core, value);\n }\n else\n {\n set_signal_handlers();\n auto m = PCM::getInstance();\n for (uint32 i = 0; i < m->getNumCores(); ++i)\n {\n if (m->isCoreOnline(i))\n {\n doOne(i, value);\n }\n }\n }\n}\n<commit_msg>Replace endl with \\n to get rid of many unnecessary flushes<commit_after>\/*\nCopyright (c) 2012-2020, Intel Corporation\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ written by Roman Dementiev\n#define HACK_TO_REMOVE_DUPLICATE_ERROR\n#include \"cpucounters.h\"\n#ifdef _MSC_VER\n#include <windows.h>\n#include \"..\/PCM_Win\/windriver.h\"\n#else\n#include <unistd.h>\n#endif\n#include <iostream>\n#include <stdlib.h>\n#include <iomanip>\n#include <string.h>\n#ifdef _MSC_VER\n#include \"freegetopt\/getopt.h\"\n#endif\n\nuint64 read_number(char * str)\n{\n std::istringstream stream(str);\n if (strstr(str, \"x\")) stream >> std::hex;\n uint64 result = 0;\n stream >> result;\n return result;\n}\n\nvoid print_usage(const char * progname)\n{\n std::cout << \"Usage \" << progname << \" [-w value] [-c core] [-d] msr\\n\\n\";\n std::cout << \" Reads specified msr (model specific register) \\n\";\n std::cout << \" -w value : write the value before reading \\n\";\n std::cout << \" -c core : perform msr read\/write on specified core (default is 0)\\n\";\n std::cout << \" -d : output all numbers in dec (default is hex)\\n\";\n std::cout << \" -a : perform msr read\/write operations on all cores\\n\";\n std::cout << \"\\n\";\n}\n\nint main(int argc, char * argv[])\n{\n std::cout << \"\\n Processor Counter Monitor \" << PCM_VERSION << \"\\n\";\n\n std::cout << \"\\n MSR read\/write utility\\n\\n\";\n\n uint64 value = 0;\n bool write = false;\n int core = 0;\n int msr = -1;\n bool dec = false;\n\n int my_opt = -1;\n while ((my_opt = getopt(argc, argv, \"w:c:d:a\")) != -1)\n {\n switch (my_opt)\n {\n case 'w':\n write = true;\n value = read_number(optarg);\n break;\n case 'c':\n core = (int)read_number(optarg);\n break;\n case 'd':\n dec = true;\n break;\n case 'a':\n core = -1;\n break;\n default:\n print_usage(argv[0]);\n return -1;\n }\n }\n\n if (optind >= argc)\n {\n print_usage(argv[0]);\n return -1;\n }\n\n msr = (int)read_number(argv[optind]);\n\n #ifdef _MSC_VER\n \/\/ Increase the priority a bit to improve context switching delays on Windows\n SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);\n\n \/\/ WARNING: This driver code (msr.sys) is only for testing purposes, not for production use\n Driver drv = Driver(Driver::msrLocalPath());\n \/\/ drv.stop(); \/\/ restart driver (usually not needed)\n if (!drv.start())\n {\n std::wcerr << \"Can not load MSR driver.\\n\";\n std::wcerr << \"You must have a signed driver at \" << drv.driverPath() << \" and have administrator rights to run this program\\n\";\n return -1;\n }\n #endif\n auto doOne = [&dec, &write, &msr](int core, uint64 value)\n {\n try {\n MsrHandle h(core);\n if (!dec) std::cout << std::hex << std::showbase;\n if (write)\n {\n std::cout << \" Writing \" << value << \" to MSR \" << msr << \" on core \" << core << \"\\n\";\n if (h.write(msr, value) != 8)\n {\n std::cout << \" Write error!\\n\";\n }\n }\n value = 0;\n if (h.read(msr, &value) == 8)\n {\n std::cout << \" Read value \" << value << \" from MSR \" << msr << \" on core \" << core << \"\\n\\n\";\n }\n else\n {\n std::cout << \" Read error!\\n\";\n }\n }\n catch (std::exception & e)\n {\n std::cerr << \"Error accessing MSRs: \" << e.what() << \"\\n\";\n std::cerr << \"Please check if the program can access MSR drivers.\\n\";\n }\n };\n if (core >= 0)\n {\n doOne(core, value);\n }\n else\n {\n set_signal_handlers();\n auto m = PCM::getInstance();\n for (uint32 i = 0; i < m->getNumCores(); ++i)\n {\n if (m->isCoreOnline(i))\n {\n doOne(i, value);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"cardreader.h\"\n#include \"shoppinglist.h\"\n\n#include <QGridLayout>\n#include <QLabel>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QStatusBar>\n#include <QTimer>\n#include <QApplication>\n\nMainWindow::MainWindow(QWidget *parent)\n{\n\tQVBoxLayout *layout = new QVBoxLayout(this);\n\n\tQPushButton *addTestItems = new QPushButton(tr(\"Add test items\"));\n\tconnect(addTestItems, SIGNAL(clicked()), SLOT(addTestItems()));\n\tlayout->addWidget(addTestItems);\n\n\t\/\/status message widget\n\tstatusBar = new StatusBar;\n\tlayout->addWidget(statusBar);\n\n\t\/\/install cardReader as an filter which intercepts _all_ keyboard events to the application\n\tcardReader = new CardReader(this);\n\tconnect(cardReader, SIGNAL(newCardNumber(QString)), SLOT(triggerTransaction(QString)));\n\n\t\/\/shoppinglist and associated view\n\tshoppingList = new ShoppingList(this);\n\n\tShoppingListWidget *shoppingListWidget = new ShoppingListWidget(shoppingList);\n\tlayout->addWidget(shoppingListWidget);\n\n\t\/\/daemon client\n\ttransactionDaemon = new DaemonClient(this);\n\tconnect(transactionDaemon, SIGNAL(transactionFeedback(QString, float, DaemonClient::TransactionStatus)), SLOT(receiveTransactionFeedback(QString, float, DaemonClient::TransactionStatus)));\n}\n\nvoid MainWindow::addTestItems()\n{\n\tshoppingList->newItem(\"Brus\", 15, 2);\n\tshoppingList->newItem(\"Godterisopp\", 2, 35);\n\tshoppingList->newItem(\"Kvikklunsj\", 10, 1);\n\tshoppingList->newItem(\"Ragni spesial\", 788.5, 3);\n}\n\nvoid MainWindow::triggerTransaction(QString cardNumber)\n{\n\tif (shoppingList->numItems() > 0) {\n\t\tthis->setEnabled(false);\n\t\tdouble totalPrice = shoppingList->getTotalPrice();\n\t\ttransactionDaemon->processTransaction(cardNumber, totalPrice);\n\t}\n}\n\nvoid MainWindow::receiveTransactionFeedback(QString username, float newBalance, DaemonClient::TransactionStatus status)\n{\n\tif (status == DaemonClient::TRANSACTION_SUCCESSFUL) {\n\t\tstatusBar->showMessage(tr(\"Transaction processed. New balance: kr \") + QString::number(newBalance), StatusBar::SUCCESS_ICON);\n\t\tshoppingList->wipeList();\n\t} else {\n\t\tstatusBar->showMessage(DaemonClient::errorMessage(status), StatusBar::ERROR_ICON);\n\t}\n\tthis->setEnabled(true);\n}\n\nStatusBar::StatusBar(QObject *parent)\n{\n\tQHBoxLayout *layout = new QHBoxLayout(this);\n\ttext = new QLabel;\n\ticon = new QLabel;\n\ttimer = new QTimer(this);\n\n\tlayout->addWidget(icon);\n\tlayout->addWidget(text, Qt::AlignLeft);\n\n\tconnect(timer, SIGNAL(timeout()), SLOT(clearMessage()));\n}\n\nvoid StatusBar::showMessage(QString message, StatusIcon icon, int timeout)\n{\n\ttimer->stop();\n\n\t\/\/status text\n\ttext->setText(message.simplified());\n\n\t\/\/status icon\n\tQSize iconSize = text->size();\n\tswitch (icon) {\n\t\tcase ERROR_ICON:\n\t\t\tthis->icon->setPixmap(qApp->style()->standardIcon(QStyle::SP_MessageBoxCritical).pixmap(iconSize));\n\t\t\tbreak;\n\t\tcase SUCCESS_ICON:\n\t\t\tthis->icon->setPixmap(qApp->style()->standardIcon(QStyle::SP_DialogApplyButton).pixmap(iconSize));\n\t\t\tbreak;\n\t}\n\n\ttimer->start(timeout);\n}\n\nvoid StatusBar::clearMessage()\n{\n\ttext->clear();\n\ticon->clear();\n\ttimer->stop();\n}\n<commit_msg>Display username.<commit_after>#include \"mainwindow.h\"\n#include \"cardreader.h\"\n#include \"shoppinglist.h\"\n\n#include <QGridLayout>\n#include <QLabel>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QStatusBar>\n#include <QTimer>\n#include <QApplication>\n\nMainWindow::MainWindow(QWidget *parent)\n{\n\tQVBoxLayout *layout = new QVBoxLayout(this);\n\n\tQPushButton *addTestItems = new QPushButton(tr(\"Add test items\"));\n\tconnect(addTestItems, SIGNAL(clicked()), SLOT(addTestItems()));\n\tlayout->addWidget(addTestItems);\n\n\t\/\/status message widget\n\tstatusBar = new StatusBar;\n\tlayout->addWidget(statusBar);\n\n\t\/\/install cardReader as an filter which intercepts _all_ keyboard events to the application\n\tcardReader = new CardReader(this);\n\tconnect(cardReader, SIGNAL(newCardNumber(QString)), SLOT(triggerTransaction(QString)));\n\n\t\/\/shoppinglist and associated view\n\tshoppingList = new ShoppingList(this);\n\n\tShoppingListWidget *shoppingListWidget = new ShoppingListWidget(shoppingList);\n\tlayout->addWidget(shoppingListWidget);\n\n\t\/\/daemon client\n\ttransactionDaemon = new DaemonClient(this);\n\tconnect(transactionDaemon, SIGNAL(transactionFeedback(QString, float, DaemonClient::TransactionStatus)), SLOT(receiveTransactionFeedback(QString, float, DaemonClient::TransactionStatus)));\n}\n\nvoid MainWindow::addTestItems()\n{\n\tshoppingList->newItem(\"Brus\", 15, 2);\n\tshoppingList->newItem(\"Godterisopp\", 2, 35);\n\tshoppingList->newItem(\"Kvikklunsj\", 10, 1);\n\tshoppingList->newItem(\"Ragni spesial\", 788.5, 3);\n}\n\nvoid MainWindow::triggerTransaction(QString cardNumber)\n{\n\tif (shoppingList->numItems() > 0) {\n\t\tthis->setEnabled(false);\n\t\tdouble totalPrice = shoppingList->getTotalPrice();\n\t\ttransactionDaemon->processTransaction(cardNumber, totalPrice);\n\t}\n}\n\nvoid MainWindow::receiveTransactionFeedback(QString username, float newBalance, DaemonClient::TransactionStatus status)\n{\n\tif (status == DaemonClient::TRANSACTION_SUCCESSFUL) {\n\t\tstatusBar->showMessage(tr(\"Transaction processed. New balance for \") + username + \": kr \" + QString::number(newBalance), StatusBar::SUCCESS_ICON);\n\t\tshoppingList->wipeList();\n\t} else {\n\t\tstatusBar->showMessage(DaemonClient::errorMessage(status), StatusBar::ERROR_ICON);\n\t}\n\tthis->setEnabled(true);\n}\n\nStatusBar::StatusBar(QObject *parent)\n{\n\tQHBoxLayout *layout = new QHBoxLayout(this);\n\ttext = new QLabel;\n\ticon = new QLabel;\n\ttimer = new QTimer(this);\n\n\tlayout->addWidget(icon);\n\tlayout->addWidget(text, Qt::AlignLeft);\n\n\tconnect(timer, SIGNAL(timeout()), SLOT(clearMessage()));\n}\n\nvoid StatusBar::showMessage(QString message, StatusIcon icon, int timeout)\n{\n\ttimer->stop();\n\n\t\/\/status text\n\ttext->setText(message.simplified());\n\n\t\/\/status icon\n\tQSize iconSize = text->size();\n\tswitch (icon) {\n\t\tcase ERROR_ICON:\n\t\t\tthis->icon->setPixmap(qApp->style()->standardIcon(QStyle::SP_MessageBoxCritical).pixmap(iconSize));\n\t\t\tbreak;\n\t\tcase SUCCESS_ICON:\n\t\t\tthis->icon->setPixmap(qApp->style()->standardIcon(QStyle::SP_DialogApplyButton).pixmap(iconSize));\n\t\t\tbreak;\n\t}\n\n\ttimer->start(timeout);\n}\n\nvoid StatusBar::clearMessage()\n{\n\ttext->clear();\n\ticon->clear();\n\ttimer->stop();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * WIN32 Events for POSIX\n * Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>\n * Copyright (C) 2011 - 2012 by NeoSmart Technologies\n * This code is released under the terms of the MIT License\n *\/\n\n#include \"pevents.h\"\n#include <assert.h>\n#include <errno.h>\n#include <sys\/time.h>\n#ifdef WFMO\n#include <vector>\n#include <deque>\n#endif\n\nnamespace neosmart\n{\n#ifdef WFMO\n\tstruct neosmart_wfmo_t_\n\t{\n\t\tpthread_mutex_t Mutex;\n\t\tpthread_cond_t CVariable;\n\t\tstd::vector<bool> EventStatus;\n\t\tbool StillWaiting;\n\t\tint RefCount;\n\t\tbool WaitAll;\n\t\t\n\t\tvoid Destroy()\n\t\t{\n\t\t\tpthread_mutex_destroy(&Mutex);\n\t\t\tpthread_cond_destroy(&CVariable);\n\t\t}\n\t};\n\ttypedef neosmart_wfmo_t_ *neosmart_wfmo_t;\n\t\n\tstruct neosmart_wfmo_info_t_\n\t{\n\t\tneosmart_wfmo_t Waiter;\n\t\tint WaitIndex;\n\t};\n\ttypedef neosmart_wfmo_info_t_ *neosmart_wfmo_info_t;\n#endif\n\t\n\tstruct neosmart_event_t_\n\t{\n\t\tbool AutoReset;\n\t\tpthread_cond_t CVariable;\n\t\tpthread_mutex_t Mutex;\n\t\tbool State;\n#ifdef WFMO\n\t\tstd::deque<neosmart_wfmo_info_t_> RegisteredWaits;\n#endif\n\t};\n\t\n\tneosmart_event_t CreateEvent(bool manualReset, bool initialState)\n\t{\n\t\tneosmart_event_t event = new neosmart_event_t_;\n\t\t\n\t\tint result = pthread_cond_init(&event->CVariable, 0);\n\t\tif(result != 0)\n\t\t\treturn NULL;\n\t\t\n\t\tresult = pthread_mutex_init(&event->Mutex, 0);\n\t\tif(result != 0)\n\t\t\treturn NULL;\n\t\t\n\t\tevent->State = false;\n\t\tevent->AutoReset = !manualReset;\n\t\t\n\t\tif(initialState && SetEvent(event) != 0)\n\t\t\treturn NULL; \/\/Shouldn't ever happen\n\t\t\n\t\treturn event;\n\t}\n\t\n\tint UnlockedWaitForEvent(neosmart_event_t event, uint64_t milliseconds)\n\t{\n\t\tint result = 0;\n\t\tif(!event->State)\n\t\t{\t\n\t\t\t\/\/Zero-timeout event state check optimization\n\t\t\tif(milliseconds == 0)\n\t\t\t{\n\t\t\t\treturn ETIMEDOUT;\n\t\t\t}\n\t\t\t\n\t\t\ttimespec ts;\n\t\t\tif(milliseconds != (uint64_t) -1)\n\t\t\t{\n\t\t\t\ttimeval tv;\n\t\t\t\tgettimeofday(&tv, NULL);\n\t\t\t\t\n\t\t\t\tuint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;\n\t\t\t\t\n\t\t\t\tts.tv_sec = nanoseconds \/ 1000 \/ 1000 \/ 1000;\n\t\t\t\tts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);\n\t\t\t}\n\t\t\t\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\/\/Regardless of whether it's an auto-reset or manual-reset event:\n\t\t\t\t\/\/wait to obtain the event, then lock anyone else out\n\t\t\t\tif(milliseconds != (uint64_t) -1)\n\t\t\t\t{\n\t\t\t\t\tresult = pthread_cond_timedwait(&event->CVariable, &event->Mutex, &ts);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tresult = pthread_cond_wait(&event->CVariable, &event->Mutex);\n\t\t\t\t}\n\t\t\t} while(result == 0 && !event->State);\n\t\t\t\n\t\t\tif(result == 0 && event->AutoReset)\n\t\t\t{\n\t\t\t\t\/\/We've only accquired the event if the wait succeeded\n\t\t\t\tevent->State = false;\n\t\t\t}\n\t\t}\n\t\telse if(event->AutoReset)\n\t\t{\n\t\t\t\/\/It's an auto-reset event that's currently available;\n\t\t\t\/\/we need to stop anyone else from using it\n\t\t\tresult = 0;\n\t\t\tevent->State = false;\n\t\t}\n\t\t\/\/Else we're trying to obtain a manual reset event with a signalled state;\n\t\t\/\/don't do anything\n\t\t\n\t\treturn result;\n\t}\n\t\n\tint WaitForEvent(neosmart_event_t event, uint64_t milliseconds)\n\t{\n\t\tint result = pthread_mutex_lock(&event->Mutex);\n\t\tif(result != 0)\n\t\t\treturn result;\n \n\t\tresult = UnlockedWaitForEvent(event, milliseconds);\n\t\t\n\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\n\t\treturn result;\n\t}\n\t\n#ifdef WFMO\n\tint WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds)\n\t{\n\t\tint unused;\n\t\treturn WaitForMultipleEvents(events, count, waitAll, milliseconds, unused);\n\t}\n\t\n\tint WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &waitIndex)\n\t{\n\t\tneosmart_wfmo_t wfmo = new neosmart_wfmo_t_;\n\t\t\n\t\tint result = pthread_mutex_init(&wfmo->Mutex, 0);\n\t\tif(result != 0)\n\t\t{\n\t\t\tdelete wfmo;\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tresult = pthread_cond_init(&wfmo->CVariable, 0);\n\t\tif(result != 0)\n\t\t{\n\t\t\tdelete wfmo;\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tneosmart_wfmo_info_t_ waitInfo;\n\t\twaitInfo.Waiter = wfmo;\n\t\twaitInfo.WaitIndex = -1;\n\t\t\n\t\twfmo->WaitAll = waitAll;\n\t\twfmo->StillWaiting = true;\n\t\twfmo->RefCount = 1;\n\t\twfmo->EventStatus.resize(count, false);\n\t\t\n\t\tpthread_mutex_lock(&wfmo->Mutex);\n\t\t\n\t\tbool done = false;\n\t\twaitIndex = -1;\n\t\t\n\t\tfor(int i = 0; i < count; ++i)\n\t\t{\n\t\t\twaitInfo.WaitIndex = i;\n\t\t\t\n\t\t\t\/\/Must not release lock until RegisteredWait is potentially added\n\t\t\tint result = pthread_mutex_lock(&events[i]->Mutex);\n\t\t\tif(result != 0)\n\t\t\t{\n\t\t\t\tdelete wfmo;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\t\n\t\t\tif(UnlockedWaitForEvent(events[i], 0) == 0)\n\t\t\t{\n\t\t\t\tresult = pthread_mutex_unlock(&events[i]->Mutex);\n\t\t\t\tif(result != 0)\n\t\t\t\t{\n\t\t\t\t\tdelete wfmo;\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\twfmo->EventStatus[i] = true;\n\t\t\t\tif(!waitAll)\n\t\t\t\t{\n\t\t\t\t\twaitIndex = i;\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\t\t\t\n\t\t\t\tevents[i]->RegisteredWaits.push_back(waitInfo);\n\t\t\t\t++wfmo->RefCount;\n\t\t\t\t\n\t\t\t\tpthread_mutex_unlock(&events[i]->Mutex);\n\t\t\t}\n\t\t}\n\t\t\n\t\ttimespec ts;\n\t\tif(!done)\n\t\t{\n\t\t\tif(milliseconds == 0)\n\t\t\t{\n\t\t\t\tresult = ETIMEDOUT;\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t\telse if(milliseconds != (uint64_t) -1)\n\t\t\t{\n\t\t\t\ttimeval tv;\n\t\t\t\tgettimeofday(&tv, NULL);\n\t\t\t\t\n\t\t\t\tuint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;\n\t\t\t\t\n\t\t\t\tts.tv_sec = nanoseconds \/ 1000 \/ 1000 \/ 1000;\n\t\t\t\tts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);\n\t\t\t}\n\t\t}\n\t\t\n\t\twhile(!done)\n\t\t{\n\t\t\t\/\/One (or more) of the events we're monitoring has been triggered?\n\t\t\t\n\t\t\t\/\/If we're waiting for all events, assume we're done and check if there's an event that hasn't fired\n\t\t\t\/\/But if we're waiting for just one event, assume we're not done until we find a fired event\n\t\t\tdone = waitAll;\n\t\t\tfor(int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tif(!waitAll && wfmo->EventStatus[i])\n\t\t\t\t{\n\t\t\t\t\tdone = true;\n\t\t\t\t\twaitIndex = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(waitAll && !wfmo->EventStatus[i])\n\t\t\t\t{\n\t\t\t\t\tdone = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(!done)\n\t\t\t{\n\t\t\t\tif(milliseconds != (uint64_t) -1)\n\t\t\t\t{\n\t\t\t\t\tresult = pthread_cond_timedwait(&wfmo->CVariable, &wfmo->Mutex, &ts);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tresult = pthread_cond_wait(&wfmo->CVariable, &wfmo->Mutex);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(result != 0)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\twfmo->StillWaiting = false;\n\t\t\n\t\t--wfmo->RefCount;\n\t\tif(wfmo->RefCount == 0)\n\t\t{\n\t\t\twfmo->Destroy();\n\t\t\tdelete wfmo;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpthread_mutex_unlock(&wfmo->Mutex);\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n#endif\n\t\n\tint DestroyEvent(neosmart_event_t event)\n\t{\n\t\tint result = pthread_cond_destroy(&event->CVariable);\n\t\tif(result != 0)\n\t\t\treturn result;\n \n\t\tresult = pthread_mutex_destroy(&event->Mutex);\n\t\tif(result != 0)\n\t\t\treturn result;\n\t\t\n\t\tdelete event;\n\t\t\n\t\treturn 0;\n\t}\n\t\n\tint SetEvent(neosmart_event_t event)\n\t{\n\t\tint result = pthread_mutex_lock(&event->Mutex);\n\t\tif(result != 0)\n\t\t\treturn result;\n\t\t\n\t\tevent->State = true;\n\t\t\n\t\t\/\/Depending on the event type, we either trigger everyone or only one\n\t\tif(event->AutoReset)\n\t\t{\n#ifdef WFMO\n\t\t\twhile(!event->RegisteredWaits.empty())\n\t\t\t{\n\t\t\t\tneosmart_wfmo_info_t i = &event->RegisteredWaits.front();\n\t\t\t\tpthread_mutex_lock(&i->Waiter->Mutex);\n\t\t\t\t--i->Waiter->RefCount;\n\t\t\t\tif(!i->Waiter->StillWaiting)\n\t\t\t\t{\n\t\t\t\t\tif(i->Waiter->RefCount == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\ti->Waiter->Destroy();\n\t\t\t\t\t\tdelete i->Waiter;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpthread_mutex_unlock(&i->Waiter->Mutex);\n\t\t\t\t\t}\n\t\t\t\t\tevent->RegisteredWaits.pop_front();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tevent->State = false;\n\t\t\t\ti->Waiter->EventStatus[i->WaitIndex] = true;\n\t\t\t\tif(!i->Waiter->WaitAll)\n\t\t\t\t\ti->Waiter->StillWaiting = false;\n\t\t\t\tpthread_mutex_unlock(&i->Waiter->Mutex);\n\t\t\t\tresult = pthread_cond_signal(&i->Waiter->CVariable);\n\t\t\t\tevent->RegisteredWaits.pop_front();\n\t\t\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\t\t\n\t\t\t\treturn result;\n\t\t\t}\n#endif\n\t\t\t\/\/event->State can be false if compiled with WFMO support\n\t\t\tif(event->State)\n\t\t\t{\n\t\t\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\t\tresult = pthread_cond_signal(&event->CVariable);\n\t\t\t\t\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n#ifdef WFMO\n\t\t\tfor(size_t i = 0; i < event->RegisteredWaits.size(); ++i)\n\t\t\t{\n\t\t\t\tneosmart_wfmo_info_t info = &event->RegisteredWaits[i];\n\t\t\t\tpthread_mutex_lock(&info->Waiter->Mutex);\n\t\t\t\t--info->Waiter->RefCount;\n\t\t\t\tif(!info->Waiter->StillWaiting)\n\t\t\t\t{\n\t\t\t\t\tif(info->Waiter->RefCount == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tinfo->Waiter->Destroy();\n\t\t\t\t\t\tdelete info->Waiter;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpthread_mutex_unlock(&info->Waiter->Mutex);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tinfo->Waiter->EventStatus[info->WaitIndex] = true;\n\t\t\t\tpthread_mutex_unlock(&info->Waiter->Mutex);\n\t\t\t\tpthread_cond_signal(&info->Waiter->CVariable);\n\t\t\t}\n\t\t\tevent->RegisteredWaits.clear();\n#endif\n\t\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\tresult = pthread_cond_broadcast(&event->CVariable);\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\tint ResetEvent(neosmart_event_t event)\n\t{\n\t\tint result = pthread_mutex_lock(&event->Mutex);\n\t\tif(result != 0)\n\t\t\treturn result;\n\t\t\n\t\tevent->State = false;\n\t\t\n\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\n\t\treturn result;\n\t}\n}\n<commit_msg>Better ensure signals for manual reset events aren't lost<commit_after>\/*\n * WIN32 Events for POSIX\n * Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>\n * Copyright (C) 2011 - 2012 by NeoSmart Technologies\n * This code is released under the terms of the MIT License\n *\/\n\n#include \"pevents.h\"\n#include <assert.h>\n#include <errno.h>\n#include <sys\/time.h>\n#ifdef WFMO\n#include <vector>\n#include <deque>\n#endif\n\nnamespace neosmart\n{\n#ifdef WFMO\n\tstruct neosmart_wfmo_t_\n\t{\n\t\tpthread_mutex_t Mutex;\n\t\tpthread_cond_t CVariable;\n\t\tstd::vector<bool> EventStatus;\n\t\tbool StillWaiting;\n\t\tint RefCount;\n\t\tbool WaitAll;\n\t\t\n\t\tvoid Destroy()\n\t\t{\n\t\t\tpthread_mutex_destroy(&Mutex);\n\t\t\tpthread_cond_destroy(&CVariable);\n\t\t}\n\t};\n\ttypedef neosmart_wfmo_t_ *neosmart_wfmo_t;\n\t\n\tstruct neosmart_wfmo_info_t_\n\t{\n\t\tneosmart_wfmo_t Waiter;\n\t\tint WaitIndex;\n\t};\n\ttypedef neosmart_wfmo_info_t_ *neosmart_wfmo_info_t;\n#endif\n\t\n\tstruct neosmart_event_t_\n\t{\n\t\tbool AutoReset;\n\t\tpthread_cond_t CVariable;\n\t\tpthread_mutex_t Mutex;\n\t\tbool State;\n#ifdef WFMO\n\t\tstd::deque<neosmart_wfmo_info_t_> RegisteredWaits;\n#endif\n\t};\n\t\n\tneosmart_event_t CreateEvent(bool manualReset, bool initialState)\n\t{\n\t\tneosmart_event_t event = new neosmart_event_t_;\n\t\t\n\t\tint result = pthread_cond_init(&event->CVariable, 0);\n\t\tif(result != 0)\n\t\t\treturn NULL;\n\t\t\n\t\tresult = pthread_mutex_init(&event->Mutex, 0);\n\t\tif(result != 0)\n\t\t\treturn NULL;\n\t\t\n\t\tevent->State = false;\n\t\tevent->AutoReset = !manualReset;\n\t\t\n\t\tif(initialState && SetEvent(event) != 0)\n\t\t\treturn NULL; \/\/Shouldn't ever happen\n\t\t\n\t\treturn event;\n\t}\n\t\n\tint UnlockedWaitForEvent(neosmart_event_t event, uint64_t milliseconds)\n\t{\n\t\tint result = 0;\n\t\tif(!event->State)\n\t\t{\t\n\t\t\t\/\/Zero-timeout event state check optimization\n\t\t\tif(milliseconds == 0)\n\t\t\t{\n\t\t\t\treturn ETIMEDOUT;\n\t\t\t}\n\t\t\t\n\t\t\ttimespec ts;\n\t\t\tif(milliseconds != (uint64_t) -1)\n\t\t\t{\n\t\t\t\ttimeval tv;\n\t\t\t\tgettimeofday(&tv, NULL);\n\t\t\t\t\n\t\t\t\tuint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;\n\t\t\t\t\n\t\t\t\tts.tv_sec = nanoseconds \/ 1000 \/ 1000 \/ 1000;\n\t\t\t\tts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);\n\t\t\t}\n\t\t\t\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\/\/Regardless of whether it's an auto-reset or manual-reset event:\n\t\t\t\t\/\/wait to obtain the event, then lock anyone else out\n\t\t\t\tif(milliseconds != (uint64_t) -1)\n\t\t\t\t{\n\t\t\t\t\tresult = pthread_cond_timedwait(&event->CVariable, &event->Mutex, &ts);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tresult = pthread_cond_wait(&event->CVariable, &event->Mutex);\n\t\t\t\t}\n\t\t\t} while(result == 0 && !event->State);\n\t\t\t\n\t\t\tif(result == 0 && event->AutoReset)\n\t\t\t{\n\t\t\t\t\/\/We've only accquired the event if the wait succeeded\n\t\t\t\tevent->State = false;\n\t\t\t}\n\t\t}\n\t\telse if(event->AutoReset)\n\t\t{\n\t\t\t\/\/It's an auto-reset event that's currently available;\n\t\t\t\/\/we need to stop anyone else from using it\n\t\t\tresult = 0;\n\t\t\tevent->State = false;\n\t\t}\n\t\t\/\/Else we're trying to obtain a manual reset event with a signalled state;\n\t\t\/\/don't do anything\n\t\t\n\t\treturn result;\n\t}\n\t\n\tint WaitForEvent(neosmart_event_t event, uint64_t milliseconds)\n\t{\n\t\tint result = pthread_mutex_lock(&event->Mutex);\n\t\tif(result != 0)\n\t\t\treturn result;\n \n\t\tresult = UnlockedWaitForEvent(event, milliseconds);\n\t\t\n\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\n\t\treturn result;\n\t}\n\t\n#ifdef WFMO\n\tint WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds)\n\t{\n\t\tint unused;\n\t\treturn WaitForMultipleEvents(events, count, waitAll, milliseconds, unused);\n\t}\n\t\n\tint WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &waitIndex)\n\t{\n\t\tneosmart_wfmo_t wfmo = new neosmart_wfmo_t_;\n\t\t\n\t\tint result = pthread_mutex_init(&wfmo->Mutex, 0);\n\t\tif(result != 0)\n\t\t{\n\t\t\tdelete wfmo;\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tresult = pthread_cond_init(&wfmo->CVariable, 0);\n\t\tif(result != 0)\n\t\t{\n\t\t\tdelete wfmo;\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tneosmart_wfmo_info_t_ waitInfo;\n\t\twaitInfo.Waiter = wfmo;\n\t\twaitInfo.WaitIndex = -1;\n\t\t\n\t\twfmo->WaitAll = waitAll;\n\t\twfmo->StillWaiting = true;\n\t\twfmo->RefCount = 1;\n\t\twfmo->EventStatus.resize(count, false);\n\t\t\n\t\tpthread_mutex_lock(&wfmo->Mutex);\n\t\t\n\t\tbool done = false;\n\t\twaitIndex = -1;\n\t\t\n\t\tfor(int i = 0; i < count; ++i)\n\t\t{\n\t\t\twaitInfo.WaitIndex = i;\n\t\t\t\n\t\t\t\/\/Must not release lock until RegisteredWait is potentially added\n\t\t\tint result = pthread_mutex_lock(&events[i]->Mutex);\n\t\t\tif(result != 0)\n\t\t\t{\n\t\t\t\tdelete wfmo;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\t\n\t\t\tif(UnlockedWaitForEvent(events[i], 0) == 0)\n\t\t\t{\n\t\t\t\tresult = pthread_mutex_unlock(&events[i]->Mutex);\n\t\t\t\tif(result != 0)\n\t\t\t\t{\n\t\t\t\t\tdelete wfmo;\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\twfmo->EventStatus[i] = true;\n\t\t\t\tif(!waitAll)\n\t\t\t\t{\n\t\t\t\t\twaitIndex = i;\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\t\t\t\n\t\t\t\tevents[i]->RegisteredWaits.push_back(waitInfo);\n\t\t\t\t++wfmo->RefCount;\n\t\t\t\t\n\t\t\t\tpthread_mutex_unlock(&events[i]->Mutex);\n\t\t\t}\n\t\t}\n\t\t\n\t\ttimespec ts;\n\t\tif(!done)\n\t\t{\n\t\t\tif(milliseconds == 0)\n\t\t\t{\n\t\t\t\tresult = ETIMEDOUT;\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t\telse if(milliseconds != (uint64_t) -1)\n\t\t\t{\n\t\t\t\ttimeval tv;\n\t\t\t\tgettimeofday(&tv, NULL);\n\t\t\t\t\n\t\t\t\tuint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;\n\t\t\t\t\n\t\t\t\tts.tv_sec = nanoseconds \/ 1000 \/ 1000 \/ 1000;\n\t\t\t\tts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);\n\t\t\t}\n\t\t}\n\t\t\n\t\twhile(!done)\n\t\t{\n\t\t\t\/\/One (or more) of the events we're monitoring has been triggered?\n\t\t\t\n\t\t\t\/\/If we're waiting for all events, assume we're done and check if there's an event that hasn't fired\n\t\t\t\/\/But if we're waiting for just one event, assume we're not done until we find a fired event\n\t\t\tdone = waitAll;\n\t\t\tfor(int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tif(!waitAll && wfmo->EventStatus[i])\n\t\t\t\t{\n\t\t\t\t\tdone = true;\n\t\t\t\t\twaitIndex = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(waitAll && !wfmo->EventStatus[i])\n\t\t\t\t{\n\t\t\t\t\tdone = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(!done)\n\t\t\t{\n\t\t\t\tif(milliseconds != (uint64_t) -1)\n\t\t\t\t{\n\t\t\t\t\tresult = pthread_cond_timedwait(&wfmo->CVariable, &wfmo->Mutex, &ts);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tresult = pthread_cond_wait(&wfmo->CVariable, &wfmo->Mutex);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(result != 0)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\twfmo->StillWaiting = false;\n\t\t\n\t\t--wfmo->RefCount;\n\t\tif(wfmo->RefCount == 0)\n\t\t{\n\t\t\twfmo->Destroy();\n\t\t\tdelete wfmo;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpthread_mutex_unlock(&wfmo->Mutex);\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n#endif\n\t\n\tint DestroyEvent(neosmart_event_t event)\n\t{\n\t\tint result = pthread_cond_destroy(&event->CVariable);\n\t\tif(result != 0)\n\t\t\treturn result;\n \n\t\tresult = pthread_mutex_destroy(&event->Mutex);\n\t\tif(result != 0)\n\t\t\treturn result;\n\t\t\n\t\tdelete event;\n\t\t\n\t\treturn 0;\n\t}\n\t\n\tint SetEvent(neosmart_event_t event)\n\t{\n\t\tint result = pthread_mutex_lock(&event->Mutex);\n\t\tif(result != 0)\n\t\t\treturn result;\n\t\t\n\t\tevent->State = true;\n\t\t\n\t\t\/\/Depending on the event type, we either trigger everyone or only one\n\t\tif(event->AutoReset)\n\t\t{\n#ifdef WFMO\n\t\t\twhile(!event->RegisteredWaits.empty())\n\t\t\t{\n\t\t\t\tneosmart_wfmo_info_t i = &event->RegisteredWaits.front();\n\t\t\t\tpthread_mutex_lock(&i->Waiter->Mutex);\n\t\t\t\t--i->Waiter->RefCount;\n\t\t\t\tif(!i->Waiter->StillWaiting)\n\t\t\t\t{\n\t\t\t\t\tif(i->Waiter->RefCount == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\ti->Waiter->Destroy();\n\t\t\t\t\t\tdelete i->Waiter;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpthread_mutex_unlock(&i->Waiter->Mutex);\n\t\t\t\t\t}\n\t\t\t\t\tevent->RegisteredWaits.pop_front();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tevent->State = false;\n\t\t\t\ti->Waiter->EventStatus[i->WaitIndex] = true;\n\t\t\t\tif(!i->Waiter->WaitAll)\n\t\t\t\t\ti->Waiter->StillWaiting = false;\n\t\t\t\tpthread_mutex_unlock(&i->Waiter->Mutex);\n\t\t\t\tresult = pthread_cond_signal(&i->Waiter->CVariable);\n\t\t\t\tevent->RegisteredWaits.pop_front();\n\t\t\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\t\t\n\t\t\t\treturn result;\n\t\t\t}\n#endif\n\t\t\t\/\/event->State can be false if compiled with WFMO support\n\t\t\tif(event->State)\n\t\t\t{\n\t\t\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\t\tresult = pthread_cond_signal(&event->CVariable);\n\t\t\t\t\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n#ifdef WFMO\n\t\t\tfor(size_t i = 0; i < event->RegisteredWaits.size(); ++i)\n\t\t\t{\n\t\t\t\tneosmart_wfmo_info_t info = &event->RegisteredWaits[i];\n\t\t\t\tpthread_mutex_lock(&info->Waiter->Mutex);\n\t\t\t\t--info->Waiter->RefCount;\n\t\t\t\tif(!info->Waiter->StillWaiting)\n\t\t\t\t{\n\t\t\t\t\tif(info->Waiter->RefCount == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tinfo->Waiter->Destroy();\n\t\t\t\t\t\tdelete info->Waiter;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpthread_mutex_unlock(&info->Waiter->Mutex);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tinfo->Waiter->EventStatus[info->WaitIndex] = true;\n\t\t\t\tif(!info->Waiter->WaitAll)\n\t\t\t\t\tinfo->Waiter->StillWaiting = false;\n\t\t\t\tpthread_mutex_unlock(&info->Waiter->Mutex);\n\t\t\t\tpthread_cond_signal(&info->Waiter->CVariable);\n\t\t\t}\n\t\t\tevent->RegisteredWaits.clear();\n#endif\n\t\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\tresult = pthread_cond_broadcast(&event->CVariable);\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\tint ResetEvent(neosmart_event_t event)\n\t{\n\t\tint result = pthread_mutex_lock(&event->Mutex);\n\t\tif(result != 0)\n\t\t\treturn result;\n\t\t\n\t\tevent->State = false;\n\t\t\n\t\tpthread_mutex_unlock(&event->Mutex);\n\t\t\n\t\treturn result;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstddef>\n#include <cstring>\n#include <array>\n#include <fallbacks\/optional.hpp>\n#include <algorithm.hpp>\n#include <cube.hpp>\nusing namespace std;\nusing namespace InsertionFinder;\n\n\nnamespace {\n constexpr int corner_twist_table[24][8] = {\n {0, 3, 6, 9, 12, 15, 18, 21},\n {9, 0, 3, 6, 12, 15, 18, 21},\n {6, 9, 0, 3, 12, 15, 18, 21},\n {3, 6, 9, 0, 12, 15, 18, 21},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {0, 3, 6, 9, 15, 18, 21, 12},\n {0, 3, 6, 9, 18, 21, 12, 15},\n {0, 3, 6, 9, 21, 12, 15, 18},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {0, 3, 11, 22, 12, 15, 7, 20},\n {0, 3, 21, 18, 12, 15, 9, 6},\n {0, 3, 20, 7, 12, 15, 22, 11},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {5, 16, 6, 9, 1, 14, 18, 21},\n {15, 12, 6, 9, 3, 0, 18, 21},\n {14, 1, 6, 9, 16, 5, 18, 21},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {0, 8, 19, 9, 12, 4, 17, 21},\n {0, 18, 15, 9, 12, 6, 3, 21},\n {0, 17, 4, 9, 12, 19, 8, 21},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {13, 3, 6, 2, 23, 15, 18, 10},\n {21, 3, 6, 12, 9, 15, 18, 0},\n {10, 3, 6, 23, 2, 15, 18, 13}\n };\n\n constexpr int edge_twist_table[24][12] = {\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {6, 0, 2, 4, 8, 10, 12, 14, 16, 18, 20, 22},\n {4, 6, 0, 2, 8, 10, 12, 14, 16, 18, 20, 22},\n {2, 4, 6, 0, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 2, 4, 6, 10, 12, 14, 8, 16, 18, 20, 22},\n {0, 2, 4, 6, 12, 14, 8, 10, 16, 18, 20, 22},\n {0, 2, 4, 6, 14, 8, 10, 12, 16, 18, 20, 22},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 2, 4, 22, 8, 10, 12, 20, 16, 18, 6, 14},\n {0, 2, 4, 14, 8, 10, 12, 6, 16, 18, 22, 20},\n {0, 2, 4, 20, 8, 10, 12, 22, 16, 18, 14, 6},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 18, 4, 6, 8, 16, 12, 14, 2, 10, 20, 22},\n {0, 10, 4, 6, 8, 2, 12, 14, 18, 16, 20, 22},\n {0, 16, 4, 6, 8, 18, 12, 14, 10, 2, 20, 22},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 2, 21, 6, 8, 10, 19, 14, 16, 5, 13, 22},\n {0, 2, 12, 6, 8, 10, 4, 14, 16, 20, 18, 22},\n {0, 2, 19, 6, 8, 10, 21, 14, 16, 13, 5, 22},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {17, 2, 4, 6, 23, 10, 12, 14, 9, 18, 20, 1},\n {8, 2, 4, 6, 0, 10, 12, 14, 22, 18, 20, 16},\n {23, 2, 4, 6, 17, 10, 12, 14, 1, 18, 20, 9}\n };\n};\n\n\nconst array<Cube, 24> Cube::twist_cube = Cube::generate_twist_cube_table();\n\narray<Cube, 24> Cube::generate_twist_cube_table() noexcept {\n array<Cube, 24> twist_cube;\n for (int i = 0; i < 24; ++i) {\n memcpy(twist_cube[i].corner, corner_twist_table[i], 8 * sizeof(int));\n memcpy(twist_cube[i].edge, edge_twist_table[i], 12 * sizeof(int));\n }\n return twist_cube;\n}\n\n\nvoid Cube::twist(int twist, byte flags) {\n this->twist(twist_cube[twist], flags);\n}\n\nvoid Cube::twist(const Algorithm& algorithm, byte flags) noexcept {\n this->twist(algorithm, 0, algorithm.length(), flags);\n}\n\nvoid Cube::twist(\n const Algorithm& algorithm,\n size_t begin, size_t end,\n byte flags\n) {\n if (static_cast<bool>(flags & CubeTwist::reversed)) {\n this->rotate(Cube::inverse_center[algorithm.cube_rotation()]);\n for (size_t i = end; i-- != begin;) {\n this->twist(\n Algorithm::inverse_twist[algorithm[i]],\n flags\n );\n }\n } else {\n for (size_t i = begin; i < end; ++i) {\n this->twist(algorithm[i], flags);\n }\n this->rotate(algorithm.cube_rotation());\n }\n}\n\nvoid Cube::twist(const Cube& cube, byte flags) noexcept {\n if (static_cast<bool>(flags & CubeTwist::corners)) {\n for (int& item: this->corner) {\n int transform = cube.corner[item \/ 3];\n item = transform - transform % 3 + (item + transform) % 3;\n }\n }\n if (static_cast<bool>(flags & CubeTwist::edges)) {\n for (int& item: this->edge) {\n item = cube.edge[item >> 1] ^ (item & 1);\n }\n }\n if (static_cast<bool>(flags & CubeTwist::centers)) {\n this->_placement = Cube::center_transform[this->_placement][cube._placement];\n }\n}\n\n\nvoid Cube::twist_before(int twist, byte flags) {\n this->twist_before(twist_cube[twist], flags);\n}\n\nvoid Cube::twist_before(const Cube& cube, byte flags) noexcept {\n if (static_cast<bool>(flags & CubeTwist::corners)) {\n int corner[8];\n for (int i = 0; i < 8; ++i) {\n int item = cube.corner[i];\n int transform = this->corner[item \/ 3];\n corner[i] = transform - transform % 3 + (item + transform) % 3;\n }\n memcpy(this->corner, corner, 8 * sizeof(int));\n }\n if (static_cast<bool>(flags & CubeTwist::edges)) {\n int edge[12];\n for (int i = 0; i < 12; ++i) {\n int item = cube.edge[i];\n edge[i] = this->edge[item >> 1] ^ (item & 1);\n }\n memcpy(this->edge, edge, 12 * sizeof(int));\n }\n if (static_cast<bool>(flags & CubeTwist::centers)) {\n this->_placement = Cube::center_transform[cube._placement][this->_placement];\n }\n}\n\n\noptional<Cube> Cube::twist_effectively(\n const Cube& cube, byte flags\n) const noexcept {\n Cube result = *this;\n if (static_cast<bool>(flags & CubeTwist::corners)) {\n for (int i = 0; i < 8; ++i) {\n int item = this->corner[i];\n int transform = cube.corner[item \/ 3];\n int new_corner = transform - transform % 3 + (item + transform) % 3;\n if (new_corner \/ 3 == i && new_corner % 3 && new_corner != item) {\n return nullopt;\n }\n result.corner[i] = new_corner;\n }\n }\n if (static_cast<bool>(flags & CubeTwist::edges)) {\n for (int i = 0; i < 12; ++i) {\n int item = this->edge[i];\n int new_edge = cube.edge[item >> 1] ^ (item & 1);\n if (new_edge == (i << 1 | 1) && new_edge != item) {\n return nullopt;\n }\n result.edge[i] = new_edge;\n }\n }\n if (static_cast<bool>(flags & CubeTwist::centers)) {\n if (this->_placement == 0) {\n return nullopt;\n }\n result._placement = Cube::center_transform[this->_placement][cube._placement];\n }\n return result;\n}\n\n\nvoid Cube::rotate(int rotation) {\n if (rotation == 0) {\n return;\n }\n this->twist(Cube::rotation_cube[rotation]);\n}\n<commit_msg>improve performance with less copies<commit_after>#include <cstddef>\n#include <cstring>\n#include <array>\n#include <fallbacks\/optional.hpp>\n#include <algorithm.hpp>\n#include <cube.hpp>\nusing namespace std;\nusing namespace InsertionFinder;\n\n\nnamespace {\n constexpr int corner_twist_table[24][8] = {\n {0, 3, 6, 9, 12, 15, 18, 21},\n {9, 0, 3, 6, 12, 15, 18, 21},\n {6, 9, 0, 3, 12, 15, 18, 21},\n {3, 6, 9, 0, 12, 15, 18, 21},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {0, 3, 6, 9, 15, 18, 21, 12},\n {0, 3, 6, 9, 18, 21, 12, 15},\n {0, 3, 6, 9, 21, 12, 15, 18},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {0, 3, 11, 22, 12, 15, 7, 20},\n {0, 3, 21, 18, 12, 15, 9, 6},\n {0, 3, 20, 7, 12, 15, 22, 11},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {5, 16, 6, 9, 1, 14, 18, 21},\n {15, 12, 6, 9, 3, 0, 18, 21},\n {14, 1, 6, 9, 16, 5, 18, 21},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {0, 8, 19, 9, 12, 4, 17, 21},\n {0, 18, 15, 9, 12, 6, 3, 21},\n {0, 17, 4, 9, 12, 19, 8, 21},\n {0, 3, 6, 9, 12, 15, 18, 21},\n {13, 3, 6, 2, 23, 15, 18, 10},\n {21, 3, 6, 12, 9, 15, 18, 0},\n {10, 3, 6, 23, 2, 15, 18, 13}\n };\n\n constexpr int edge_twist_table[24][12] = {\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {6, 0, 2, 4, 8, 10, 12, 14, 16, 18, 20, 22},\n {4, 6, 0, 2, 8, 10, 12, 14, 16, 18, 20, 22},\n {2, 4, 6, 0, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 2, 4, 6, 10, 12, 14, 8, 16, 18, 20, 22},\n {0, 2, 4, 6, 12, 14, 8, 10, 16, 18, 20, 22},\n {0, 2, 4, 6, 14, 8, 10, 12, 16, 18, 20, 22},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 2, 4, 22, 8, 10, 12, 20, 16, 18, 6, 14},\n {0, 2, 4, 14, 8, 10, 12, 6, 16, 18, 22, 20},\n {0, 2, 4, 20, 8, 10, 12, 22, 16, 18, 14, 6},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 18, 4, 6, 8, 16, 12, 14, 2, 10, 20, 22},\n {0, 10, 4, 6, 8, 2, 12, 14, 18, 16, 20, 22},\n {0, 16, 4, 6, 8, 18, 12, 14, 10, 2, 20, 22},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {0, 2, 21, 6, 8, 10, 19, 14, 16, 5, 13, 22},\n {0, 2, 12, 6, 8, 10, 4, 14, 16, 20, 18, 22},\n {0, 2, 19, 6, 8, 10, 21, 14, 16, 13, 5, 22},\n {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22},\n {17, 2, 4, 6, 23, 10, 12, 14, 9, 18, 20, 1},\n {8, 2, 4, 6, 0, 10, 12, 14, 22, 18, 20, 16},\n {23, 2, 4, 6, 17, 10, 12, 14, 1, 18, 20, 9}\n };\n};\n\n\nconst array<Cube, 24> Cube::twist_cube = Cube::generate_twist_cube_table();\n\narray<Cube, 24> Cube::generate_twist_cube_table() noexcept {\n array<Cube, 24> twist_cube;\n for (int i = 0; i < 24; ++i) {\n memcpy(twist_cube[i].corner, corner_twist_table[i], 8 * sizeof(int));\n memcpy(twist_cube[i].edge, edge_twist_table[i], 12 * sizeof(int));\n }\n return twist_cube;\n}\n\n\nvoid Cube::twist(int twist, byte flags) {\n this->twist(twist_cube[twist], flags);\n}\n\nvoid Cube::twist(const Algorithm& algorithm, byte flags) noexcept {\n this->twist(algorithm, 0, algorithm.length(), flags);\n}\n\nvoid Cube::twist(\n const Algorithm& algorithm,\n size_t begin, size_t end,\n byte flags\n) {\n if (static_cast<bool>(flags & CubeTwist::reversed)) {\n this->rotate(Cube::inverse_center[algorithm.cube_rotation()]);\n for (size_t i = end; i-- != begin;) {\n this->twist(\n Algorithm::inverse_twist[algorithm[i]],\n flags\n );\n }\n } else {\n for (size_t i = begin; i < end; ++i) {\n this->twist(algorithm[i], flags);\n }\n this->rotate(algorithm.cube_rotation());\n }\n}\n\nvoid Cube::twist(const Cube& cube, byte flags) noexcept {\n if (static_cast<bool>(flags & CubeTwist::corners)) {\n for (int& item: this->corner) {\n int transform = cube.corner[item \/ 3];\n item = transform - transform % 3 + (item + transform) % 3;\n }\n }\n if (static_cast<bool>(flags & CubeTwist::edges)) {\n for (int& item: this->edge) {\n item = cube.edge[item >> 1] ^ (item & 1);\n }\n }\n if (static_cast<bool>(flags & CubeTwist::centers)) {\n this->_placement = Cube::center_transform[this->_placement][cube._placement];\n }\n}\n\n\nvoid Cube::twist_before(int twist, byte flags) {\n this->twist_before(twist_cube[twist], flags);\n}\n\nvoid Cube::twist_before(const Cube& cube, byte flags) noexcept {\n if (static_cast<bool>(flags & CubeTwist::corners)) {\n int corner[8];\n for (int i = 0; i < 8; ++i) {\n int item = cube.corner[i];\n int transform = this->corner[item \/ 3];\n corner[i] = transform - transform % 3 + (item + transform) % 3;\n }\n memcpy(this->corner, corner, 8 * sizeof(int));\n }\n if (static_cast<bool>(flags & CubeTwist::edges)) {\n int edge[12];\n for (int i = 0; i < 12; ++i) {\n int item = cube.edge[i];\n edge[i] = this->edge[item >> 1] ^ (item & 1);\n }\n memcpy(this->edge, edge, 12 * sizeof(int));\n }\n if (static_cast<bool>(flags & CubeTwist::centers)) {\n this->_placement = Cube::center_transform[cube._placement][this->_placement];\n }\n}\n\n\noptional<Cube> Cube::twist_effectively(\n const Cube& cube, byte flags\n) const noexcept {\n bool corners_filled = false;\n bool edges_filled = false;\n bool centers_filled = false;\n Cube result(nullopt);\n if (static_cast<bool>(flags & CubeTwist::corners)) {\n for (int i = 0; i < 8; ++i) {\n int item = this->corner[i];\n int transform = cube.corner[item \/ 3];\n int new_corner = transform - transform % 3 + (item + transform) % 3;\n if (new_corner \/ 3 == i && new_corner % 3 && new_corner != item) {\n return nullopt;\n }\n result.corner[i] = new_corner;\n }\n corners_filled = true;\n }\n if (static_cast<bool>(flags & CubeTwist::edges)) {\n for (int i = 0; i < 12; ++i) {\n int item = this->edge[i];\n int new_edge = cube.edge[item >> 1] ^ (item & 1);\n if (new_edge == (i << 1 | 1) && new_edge != item) {\n return nullopt;\n }\n result.edge[i] = new_edge;\n }\n edges_filled = true;\n }\n if (static_cast<bool>(flags & CubeTwist::centers)) {\n if (this->_placement == 0) {\n return nullopt;\n }\n result._placement = Cube::center_transform[this->_placement][cube._placement];\n centers_filled = true;\n }\n if (!corners_filled) {\n memcpy(result.corner, this->corner, 8 * sizeof(int));\n }\n if (!edges_filled) {\n memcpy(result.edge, this->edge, 12 * sizeof(int));\n }\n if (!centers_filled) {\n result._placement = this->_placement;\n }\n return result;\n}\n\n\nvoid Cube::rotate(int rotation) {\n if (rotation == 0) {\n return;\n }\n this->twist(Cube::rotation_cube[rotation]);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"RemovableDriveManager.hpp\"\n#include <iostream>\n#include \"boost\/nowide\/convert.hpp\"\n\n#if _WIN32\n#include <windows.h>\n#include <tchar.h>\n#include <winioctl.h>\n#include <shlwapi.h>\nDEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE,\n\t0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED);\n#else\n\/\/linux includes\n#include <errno.h>\n#include <sys\/mount.h>\n#include <sys\/stat.h>\n#include <glob.h>\n#include <libgen.h>\n#include <pwd.h>\n#endif\n\nnamespace Slic3r {\nnamespace GUI { \n\/\/std::vector<DriveData> RemovableDriveManager::m_current_drives;\n\/\/std::vector<std::function<void()>> RemovableDriveManager::m_callbacks;\n\n\n#if _WIN32\nvoid RemovableDriveManager::search_for_drives()\n{\n\tm_current_drives.clear();\n\tm_current_drives.reserve(26);\n\tDWORD drives_mask = GetLogicalDrives();\n\tfor (size_t i = 0; i < 26; i++)\n\t{\n\t\tif(drives_mask & (1 << i))\n\t\t{\n\t\t\tstd::string path (1,(char)('A' + i));\n\t\t\tpath+=\":\";\n\t\t\tUINT drive_type = GetDriveTypeA(path.c_str());\n\t\t\t\/\/std::cout << \"found drive\" << (char)('A' + i) << \": type:\" <<driveType << \"\\n\";\n\t\t\tif (drive_type == DRIVE_REMOVABLE)\n\t\t\t{\n\t\t\t\t\/\/ get name of drive\n\t\t\t\tstd::wstring wpath = std::wstring(path.begin(), path.end());\n\t\t\t\tstd::wstring volume_name;\n\t\t\t\tvolume_name.resize(1024);\n\t\t\t\tstd::wstring file_system_name;\n\t\t\t\tfile_system_name.resize(1024);\n\t\t\t\tLPWSTR lp_volume_name_buffer = new wchar_t;\n\t\t\t\tBOOL error = GetVolumeInformationW(wpath.c_str(), &volume_name[0], sizeof(volume_name), NULL, NULL, NULL, &file_system_name[0], sizeof(file_system_name));\n\t\t\t\tif(error != 0)\n\t\t\t\t{\n\t\t\t\t\tif (volume_name == L\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tvolume_name = L\"REMOVABLE DRIVE\";\n\t\t\t\t\t}\n\t\t\t\t\tif (file_system_name != L\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tULARGE_INTEGER free_space;\n\t\t\t\t\t\tGetDiskFreeSpaceExA(path.c_str(), &free_space, NULL, NULL);\n\t\t\t\t\t\t\/\/std::cout << std::string(volumeName.begin(), volumeName.end()) << \" \" << std::string(fileSystemName.begin(), fileSystemName.end()) << \" \" << freeSpace.QuadPart << \"\\n\";\n\t\t\t\t\t\tif (free_space.QuadPart > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath += \"\\\\\";\n\t\t\t\t\t\t\tm_current_drives.push_back(DriveData(boost::nowide::narrow(volume_name), path));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/std::cout << \"found drives:\" << m_current_drives.size() << \"\\n\";\n}\nvoid RemovableDriveManager::eject_drive(const std::string &path)\n{\n\n\t\/\/if (!update() || !is_drive_mounted(path))\n\tif(m_current_drives.empty())\n\t\treturn;\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tif ((*it).path == path)\n\t\t{\n\t\t\tstd::string mpath = \"\\\\\\\\.\\\\\" + path;\n\t\t\tmpath = mpath.substr(0, mpath.size() - 1);\n\t\t\tstd::cout << \"Ejecting \" << mpath << \"\\n\";\n\t\t\tHANDLE handle = CreateFileA(mpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);\n\t\t\tif (handle == INVALID_HANDLE_VALUE)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Ejecting \" << mpath << \" failed \" << GetLastError() << \" \\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tDWORD deviceControlRetVal(0);\n\t\t\tBOOL error = DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, nullptr, 0, nullptr, 0, &deviceControlRetVal, nullptr);\n\t\t\tCloseHandle(handle);\n\t\t\tif (error == 0)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Ejecting \" << mpath << \" failed \" << deviceControlRetVal << \" \" << GetLastError() << \" \\n\";\n\t\t\t\treturn;\n\t\t\t}\n\n\n\t\t\tm_current_drives.erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n}\nbool RemovableDriveManager::is_path_on_removable_drive(const std::string &path)\n{\n\tif (m_current_drives.empty())\n\t\treturn false;\n\tint letter = PathGetDriveNumberA(path.c_str());\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tchar drive = (*it).path[0];\n\t\tif (drive == ('A' + letter))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\nvoid RemovableDriveManager::register_window()\n{\n\t\/*\n\tWNDCLASSEX wndClass;\n\n\twndClass.cbSize = sizeof(WNDCLASSEX);\n\twndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;\n\twndClass.hInstance = reinterpret_cast<HINSTANCE>(GetModuleHandle(0));\n\twndClass.lpfnWndProc = reinterpret_cast<WNDPROC>(WinProcCallback);\n\twndClass.cbClsExtra = 0;\n\twndClass.cbWndExtra = 0;\n\twndClass.hIcon = LoadIcon(0, IDI_APPLICATION);\n\twndClass.hbrBackground = CreateSolidBrush(RGB(192, 192, 192));\n\twndClass.hCursor = LoadCursor(0, IDC_ARROW);\n\twndClass.lpszClassName = L\"SlicerWindowClass\";\n\twndClass.lpszMenuName = NULL;\n\twndClass.hIconSm = wndClass.hIcon;\n\t*\/\n}\n#else\nvoid RemovableDriveManager::search_for_drives()\n{\n \n\tm_current_drives.clear();\n\tm_current_drives.reserve(26);\n\n \/\/search \/media\/* folder\n\tsearch_path(\"\/media\/*\", \"\/media\");\n\n std::string path(std::getenv(\"USER\"));\n\tstd::string pp(path);\n\t\/\/std::cout << \"user: \"<< path << \"\\n\";\n\tif(path == \"root\"){ \/\/if program is run with sudo, we have to search for all users \n\t\twhile (true) {\n\t passwd* entry = getpwent();\n\t if (!entry) {\n\t break;\n\t }\n\t path = entry->pw_name;\n\t pp = path;\n\t \/\/search \/media\/USERNAME\/* folder\n\t\t\tpp = \"\/media\/\"+pp;\n\t\t\tpath = \"\/media\/\" + path + \"\/*\";\n\t\t\tsearch_path(path, pp);\n\n\t\t\t\/\/search \/run\/media\/USERNAME\/* folder\n\t\t\tpath = \"\/run\" + path;\n\t\t\tpp = \"\/run\"+pp;\n\t\t\tsearch_path(path, pp);\n\t }\n\t endpwent();\n\t}else\n\t{\n\t\t\/\/search \/media\/USERNAME\/* folder\n\t\tpp = \"\/media\/\"+pp;\n\t\tpath = \"\/media\/\" + path + \"\/*\";\n\t\tsearch_path(path, pp);\n\n\t\t\/\/search \/run\/media\/USERNAME\/* folder\n\t\tpath = \"\/run\" + path;\n\t\tpp = \"\/run\"+pp;\n\t\tsearch_path(path, pp);\n\n\t}\n\t\n\t\/\/std::cout << \"found drives:\" <<m_current_drives.size() << \"\\n\";\n}\nvoid RemovableDriveManager::search_path(const std::string &path,const std::string &parent_path)\n{\n glob_t globbuf;\n\tglobbuf.gl_offs = 2;\n\tint error = glob(path.c_str(), GLOB_TILDE, NULL, &globbuf);\n\tif(error == 0) \n\t{\n\t\tfor(size_t i = 0; i < globbuf.gl_pathc; i++)\n\t\t{\n\t\t\t\/\/if not same file system - could be removable drive\n\t\t\tif(!compare_filesystem_id(globbuf.gl_pathv[i], parent_path))\n\t\t\t{\n\t\t\t\tstd::string name = basename(globbuf.gl_pathv[i]);\n\t m_current_drives.push_back(DriveData(name,globbuf.gl_pathv[i]));\n\t\t\t}\n\t\t}\n\t}else\n\t{\n\t\t\/\/if error - path probably doesnt exists so function just exits\n\t\t\/\/std::cout<<\"glob error \"<< error<< \"\\n\";\n\t}\n\t\n\tglobfree(&globbuf);\n}\n\nbool RemovableDriveManager::compare_filesystem_id(const std::string &path_a, const std::string &path_b)\n{\n\tstruct stat buf;\n\tstat(path_a.c_str() ,&buf);\n\tdev_t id_a = buf.st_dev;\n\tstat(path_b.c_str() ,&buf);\n\tdev_t id_b = buf.st_dev;\n\treturn id_a == id_b;\n}\nvoid RemovableDriveManager::eject_drive(const std::string &path)\n{\n\tif (m_current_drives.empty())\n\t\treturn;\n\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tif((*it).path == path)\n\t\t{\n std::cout<<\"Ejecting \"<<(*it).name<<\" from \"<< (*it).path<<\"\\n\";\n std::string command = \"umount \";\n command += (*it).path;\n int err = system(command.c_str());\n if(err)\n {\n std::cerr<<\"Ejecting failed\\n\";\n return;\n }\n m_current_drives.erase(it);\n \t\t\n break;\n\t\t}\n\n\t}\n\n}\nbool RemovableDriveManager::is_path_on_removable_drive(const std::string &path)\n{\n\tif (m_current_drives.empty())\n\t\treturn false;\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tif(compare_filesystem_id(path, (*it).path))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n#endif\nbool RemovableDriveManager::update(long time)\n{\n\tstatic long last_update = 0;\n\tif(last_update == 0)\n\t{\n\t\t\/\/add_callback(std::bind(&RemovableDriveManager::print, RemovableDriveManager::getInstance()));\n\t\tadd_callback([](void) { RemovableDriveManager::get_instance().print(); });\n#if _WIN32\n\t\tregister_window();\n#endif\n\t}\n\tif(time != 0) \/\/time = 0 is forced update\n\t{\n\t\tlong diff = last_update - time;\n\t\tif(diff <= -2)\n\t\t{\n\t\t\tlast_update = time;\n\t\t}else\n\t\t{\n\t\t\treturn false; \/\/ return value shouldnt matter if update didnt run\n\t\t}\n\t}\n\tsearch_for_drives();\n\tcheck_and_notify();\n\treturn !m_current_drives.empty();\n}\n\n\nbool RemovableDriveManager::is_drive_mounted(const std::string &path)\n{\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tif ((*it).path == path)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nstd::string RemovableDriveManager::get_last_drive_path()\n{\n\tif (!m_current_drives.empty())\n\t{\n\/\/#if _WIN32\n\/\/\t\treturn m_current_drives.back().path + \"\\\\\";\n\/\/#else\n\t\treturn m_current_drives.back().path;\n\/\/#endif\t\n\t}\n\treturn \"\";\n}\nstd::vector<DriveData> RemovableDriveManager::get_all_drives()\n{\n\treturn m_current_drives;\n}\nvoid RemovableDriveManager::check_and_notify()\n{\n\t\/\/std::cout<<\"drives count: \"<<m_drives_count;\n\tif(m_drives_count != m_current_drives.size())\n\t{\n\t\t\/\/std::cout<<\" vs \"<< m_current_drives.size();\n\t\tfor (auto it = m_callbacks.begin(); it != m_callbacks.end(); ++it)\n\t\t{\n\t\t\t(*it)();\n\t\t}\n\t\tm_drives_count = m_current_drives.size();\n\t}\n\t\/\/std::cout<<\"\\n\";\n}\nvoid RemovableDriveManager::add_callback(std::function<void()> callback)\n{\n\tm_callbacks.push_back(callback);\n}\nvoid RemovableDriveManager::print()\n{\n\tstd::cout << \"notified\\n\";\n}\n}}\/\/namespace Slicer::Gui::<commit_msg>osx search for drives<commit_after>#include \"RemovableDriveManager.hpp\"\n#include <iostream>\n#include \"boost\/nowide\/convert.hpp\"\n\n#if _WIN32\n#include <windows.h>\n#include <tchar.h>\n#include <winioctl.h>\n#include <shlwapi.h>\nDEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE,\n\t0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED);\n#else\n\/\/linux includes\n#include <errno.h>\n#include <sys\/mount.h>\n#include <sys\/stat.h>\n#include <glob.h>\n#include <libgen.h>\n#include <pwd.h>\n#endif\n\nnamespace Slic3r {\nnamespace GUI { \n\/\/std::vector<DriveData> RemovableDriveManager::m_current_drives;\n\/\/std::vector<std::function<void()>> RemovableDriveManager::m_callbacks;\n\n\n#if _WIN32\nvoid RemovableDriveManager::search_for_drives()\n{\n\tm_current_drives.clear();\n\tm_current_drives.reserve(26);\n\tDWORD drives_mask = GetLogicalDrives();\n\tfor (size_t i = 0; i < 26; i++)\n\t{\n\t\tif(drives_mask & (1 << i))\n\t\t{\n\t\t\tstd::string path (1,(char)('A' + i));\n\t\t\tpath+=\":\";\n\t\t\tUINT drive_type = GetDriveTypeA(path.c_str());\n\t\t\t\/\/std::cout << \"found drive\" << (char)('A' + i) << \": type:\" <<driveType << \"\\n\";\n\t\t\tif (drive_type == DRIVE_REMOVABLE)\n\t\t\t{\n\t\t\t\t\/\/ get name of drive\n\t\t\t\tstd::wstring wpath = std::wstring(path.begin(), path.end());\n\t\t\t\tstd::wstring volume_name;\n\t\t\t\tvolume_name.resize(1024);\n\t\t\t\tstd::wstring file_system_name;\n\t\t\t\tfile_system_name.resize(1024);\n\t\t\t\tLPWSTR lp_volume_name_buffer = new wchar_t;\n\t\t\t\tBOOL error = GetVolumeInformationW(wpath.c_str(), &volume_name[0], sizeof(volume_name), NULL, NULL, NULL, &file_system_name[0], sizeof(file_system_name));\n\t\t\t\tif(error != 0)\n\t\t\t\t{\n\t\t\t\t\tif (volume_name == L\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tvolume_name = L\"REMOVABLE DRIVE\";\n\t\t\t\t\t}\n\t\t\t\t\tif (file_system_name != L\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tULARGE_INTEGER free_space;\n\t\t\t\t\t\tGetDiskFreeSpaceExA(path.c_str(), &free_space, NULL, NULL);\n\t\t\t\t\t\t\/\/std::cout << std::string(volumeName.begin(), volumeName.end()) << \" \" << std::string(fileSystemName.begin(), fileSystemName.end()) << \" \" << freeSpace.QuadPart << \"\\n\";\n\t\t\t\t\t\tif (free_space.QuadPart > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath += \"\\\\\";\n\t\t\t\t\t\t\tm_current_drives.push_back(DriveData(boost::nowide::narrow(volume_name), path));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/std::cout << \"found drives:\" << m_current_drives.size() << \"\\n\";\n}\nvoid RemovableDriveManager::eject_drive(const std::string &path)\n{\n\n\t\/\/if (!update() || !is_drive_mounted(path))\n\tif(m_current_drives.empty())\n\t\treturn;\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tif ((*it).path == path)\n\t\t{\n\t\t\tstd::string mpath = \"\\\\\\\\.\\\\\" + path;\n\t\t\tmpath = mpath.substr(0, mpath.size() - 1);\n\t\t\tstd::cout << \"Ejecting \" << mpath << \"\\n\";\n\t\t\tHANDLE handle = CreateFileA(mpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);\n\t\t\tif (handle == INVALID_HANDLE_VALUE)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Ejecting \" << mpath << \" failed \" << GetLastError() << \" \\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tDWORD deviceControlRetVal(0);\n\t\t\tBOOL error = DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, nullptr, 0, nullptr, 0, &deviceControlRetVal, nullptr);\n\t\t\tCloseHandle(handle);\n\t\t\tif (error == 0)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Ejecting \" << mpath << \" failed \" << deviceControlRetVal << \" \" << GetLastError() << \" \\n\";\n\t\t\t\treturn;\n\t\t\t}\n\n\n\t\t\tm_current_drives.erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n}\nbool RemovableDriveManager::is_path_on_removable_drive(const std::string &path)\n{\n\tif (m_current_drives.empty())\n\t\treturn false;\n\tint letter = PathGetDriveNumberA(path.c_str());\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tchar drive = (*it).path[0];\n\t\tif (drive == ('A' + letter))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\nvoid RemovableDriveManager::register_window()\n{\n\t\/*\n\tWNDCLASSEX wndClass;\n\n\twndClass.cbSize = sizeof(WNDCLASSEX);\n\twndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;\n\twndClass.hInstance = reinterpret_cast<HINSTANCE>(GetModuleHandle(0));\n\twndClass.lpfnWndProc = reinterpret_cast<WNDPROC>(WinProcCallback);\n\twndClass.cbClsExtra = 0;\n\twndClass.cbWndExtra = 0;\n\twndClass.hIcon = LoadIcon(0, IDI_APPLICATION);\n\twndClass.hbrBackground = CreateSolidBrush(RGB(192, 192, 192));\n\twndClass.hCursor = LoadCursor(0, IDC_ARROW);\n\twndClass.lpszClassName = L\"SlicerWindowClass\";\n\twndClass.lpszMenuName = NULL;\n\twndClass.hIconSm = wndClass.hIcon;\n\t*\/\n}\n#else\nvoid RemovableDriveManager::search_for_drives()\n{\n \n\tm_current_drives.clear();\n\tm_current_drives.reserve(26);\n\n \/\/search \/media\/* folder\n\tsearch_path(\"\/media\/*\", \"\/media\");\n\n\t\/\/search \/Volumes\/* folder (OSX)\n\tsearch_path(\"\/Volumes\/*\", \"\/Volumes\");\n\n std::string path(std::getenv(\"USER\"));\n\tstd::string pp(path);\n\t\/\/std::cout << \"user: \"<< path << \"\\n\";\n\tif(path == \"root\"){ \/\/if program is run with sudo, we have to search for all users \n\t\twhile (true) {\n\t passwd* entry = getpwent();\n\t if (!entry) {\n\t break;\n\t }\n\t path = entry->pw_name;\n\t pp = path;\n\t \/\/search \/media\/USERNAME\/* folder\n\t\t\tpp = \"\/media\/\"+pp;\n\t\t\tpath = \"\/media\/\" + path + \"\/*\";\n\t\t\tsearch_path(path, pp);\n\n\t\t\t\/\/search \/run\/media\/USERNAME\/* folder\n\t\t\tpath = \"\/run\" + path;\n\t\t\tpp = \"\/run\"+pp;\n\t\t\tsearch_path(path, pp);\n\t }\n\t endpwent();\n\t}else\n\t{\n\t\t\/\/search \/media\/USERNAME\/* folder\n\t\tpp = \"\/media\/\"+pp;\n\t\tpath = \"\/media\/\" + path + \"\/*\";\n\t\tsearch_path(path, pp);\n\n\t\t\/\/search \/run\/media\/USERNAME\/* folder\n\t\tpath = \"\/run\" + path;\n\t\tpp = \"\/run\"+pp;\n\t\tsearch_path(path, pp);\n\n\t}\n\t\n\t\/\/std::cout << \"found drives:\" <<m_current_drives.size() << \"\\n\";\n}\nvoid RemovableDriveManager::search_path(const std::string &path,const std::string &parent_path)\n{\n glob_t globbuf;\n\tglobbuf.gl_offs = 2;\n\tint error = glob(path.c_str(), GLOB_TILDE, NULL, &globbuf);\n\tif(error == 0) \n\t{\n\t\tfor(size_t i = 0; i < globbuf.gl_pathc; i++)\n\t\t{\n\t\t\t\/\/if not same file system - could be removable drive\n\t\t\tif(!compare_filesystem_id(globbuf.gl_pathv[i], parent_path))\n\t\t\t{\n\t\t\t\tstd::string name = basename(globbuf.gl_pathv[i]);\n\t m_current_drives.push_back(DriveData(name,globbuf.gl_pathv[i]));\n\t\t\t}\n\t\t}\n\t}else\n\t{\n\t\t\/\/if error - path probably doesnt exists so function just exits\n\t\t\/\/std::cout<<\"glob error \"<< error<< \"\\n\";\n\t}\n\t\n\tglobfree(&globbuf);\n}\n\nbool RemovableDriveManager::compare_filesystem_id(const std::string &path_a, const std::string &path_b)\n{\n\tstruct stat buf;\n\tstat(path_a.c_str() ,&buf);\n\tdev_t id_a = buf.st_dev;\n\tstat(path_b.c_str() ,&buf);\n\tdev_t id_b = buf.st_dev;\n\treturn id_a == id_b;\n}\nvoid RemovableDriveManager::eject_drive(const std::string &path)\n{\n\tif (m_current_drives.empty())\n\t\treturn;\n\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tif((*it).path == path)\n\t\t{\n std::cout<<\"Ejecting \"<<(*it).name<<\" from \"<< (*it).path<<\"\\n\";\n std::string command = \"umount \";\n command += (*it).path;\n int err = system(command.c_str());\n if(err)\n {\n std::cerr<<\"Ejecting failed\\n\";\n return;\n }\n m_current_drives.erase(it);\n \t\t\n break;\n\t\t}\n\n\t}\n\n}\nbool RemovableDriveManager::is_path_on_removable_drive(const std::string &path)\n{\n\tif (m_current_drives.empty())\n\t\treturn false;\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tif(compare_filesystem_id(path, (*it).path))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n#endif\nbool RemovableDriveManager::update(long time)\n{\n\tstatic long last_update = 0;\n\tif(last_update == 0)\n\t{\n\t\t\/\/add_callback(std::bind(&RemovableDriveManager::print, RemovableDriveManager::getInstance()));\n\t\tadd_callback([](void) { RemovableDriveManager::get_instance().print(); });\n#if _WIN32\n\t\tregister_window();\n#endif\n\t}\n\tif(time != 0) \/\/time = 0 is forced update\n\t{\n\t\tlong diff = last_update - time;\n\t\tif(diff <= -2)\n\t\t{\n\t\t\tlast_update = time;\n\t\t}else\n\t\t{\n\t\t\treturn false; \/\/ return value shouldnt matter if update didnt run\n\t\t}\n\t}\n\tsearch_for_drives();\n\tcheck_and_notify();\n\treturn !m_current_drives.empty();\n}\n\n\nbool RemovableDriveManager::is_drive_mounted(const std::string &path)\n{\n\tfor (auto it = m_current_drives.begin(); it != m_current_drives.end(); ++it)\n\t{\n\t\tif ((*it).path == path)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nstd::string RemovableDriveManager::get_last_drive_path()\n{\n\tif (!m_current_drives.empty())\n\t{\n\/\/#if _WIN32\n\/\/\t\treturn m_current_drives.back().path + \"\\\\\";\n\/\/#else\n\t\treturn m_current_drives.back().path;\n\/\/#endif\t\n\t}\n\treturn \"\";\n}\nstd::vector<DriveData> RemovableDriveManager::get_all_drives()\n{\n\treturn m_current_drives;\n}\nvoid RemovableDriveManager::check_and_notify()\n{\n\t\/\/std::cout<<\"drives count: \"<<m_drives_count;\n\tif(m_drives_count != m_current_drives.size())\n\t{\n\t\t\/\/std::cout<<\" vs \"<< m_current_drives.size();\n\t\tfor (auto it = m_callbacks.begin(); it != m_callbacks.end(); ++it)\n\t\t{\n\t\t\t(*it)();\n\t\t}\n\t\tm_drives_count = m_current_drives.size();\n\t}\n\t\/\/std::cout<<\"\\n\";\n}\nvoid RemovableDriveManager::add_callback(std::function<void()> callback)\n{\n\tm_callbacks.push_back(callback);\n}\nvoid RemovableDriveManager::print()\n{\n\tstd::cout << \"notified\\n\";\n}\n}}\/\/namespace Slicer::Gui::<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This 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 \n * Foundation. See file COPYING.\n * \n *\/\n\n#include \"Elector.h\"\n#include \"Monitor.h\"\n\n#include \"common\/Timer.h\"\n#include \"MonitorStore.h\"\n#include \"messages\/MMonElection.h\"\n\n#include \"config.h\"\n\n#define DOUT_SUBSYS mon\n#undef dout_prefix\n#define dout_prefix _prefix(mon, epoch)\nstatic ostream& _prefix(Monitor *mon, epoch_t epoch) {\n return *_dout << dbeginl\n\t\t<< \"mon\" << mon->whoami\n\t\t<< (mon->is_starting() ? (const char*)\"(starting)\":(mon->is_leader() ? (const char*)\"(leader)\":(mon->is_peon() ? (const char*)\"(peon)\":(const char*)\"(?\\?)\")))\n\t\t<< \".elector(\" << epoch << \") \";\n}\n\n\nvoid Elector::init()\n{\n epoch = mon->store->get_int(\"election_epoch\");\n if (!epoch)\n epoch = 1;\n dout(1) << \"init, last seen epoch \" << epoch << dendl;\n}\n\nvoid Elector::shutdown()\n{\n if (expire_event)\n mon->timer.cancel_event(expire_event);\n}\n\nvoid Elector::bump_epoch(epoch_t e) \n{\n dout(10) << \"bump_epoch \" << epoch << \" to \" << e << dendl;\n assert(epoch < e);\n epoch = e;\n mon->store->put_int(epoch, \"election_epoch\");\n\n \/\/ clear up some state\n electing_me = false;\n acked_me.clear();\n leader_acked = -1;\n}\n\n\nvoid Elector::start()\n{\n dout(5) << \"start -- can i be leader?\" << dendl;\n \n \/\/ start by trying to elect me\n if (epoch % 2 == 0) \n bump_epoch(epoch+1); \/\/ odd == election cycle\n start_stamp = g_clock.now();\n electing_me = true;\n acked_me.insert(whoami);\n \n \/\/ bcast to everyone else\n for (unsigned i=0; i<mon->monmap->size(); ++i) {\n if ((int)i == whoami) continue;\n mon->messenger->send_message(new MMonElection(MMonElection::OP_PROPOSE, epoch, mon->monmap),\n\t\t\t\t mon->monmap->get_inst(i));\n }\n \n reset_timer();\n}\n\nvoid Elector::defer(int who)\n{\n dout(5) << \"defer to \" << who << dendl;\n\n if (electing_me) {\n \/\/ drop out\n acked_me.clear();\n electing_me = false;\n }\n\n \/\/ ack them\n leader_acked = who;\n ack_stamp = g_clock.now();\n mon->messenger->send_message(new MMonElection(MMonElection::OP_ACK, epoch, mon->monmap),\n\t\t\t mon->monmap->get_inst(who));\n \n \/\/ set a timer\n reset_timer(1.0); \/\/ give the leader some extra time to declare victory\n}\n\n\nvoid Elector::reset_timer(double plus)\n{\n \/\/ set the timer\n cancel_timer();\n expire_event = new C_ElectionExpire(this);\n mon->timer.add_event_after(g_conf.mon_lease + plus,\n\t\t\t expire_event);\n}\n\n\nvoid Elector::cancel_timer()\n{\n if (expire_event) {\n mon->timer.cancel_event(expire_event);\n expire_event = 0;\n }\n}\n\nvoid Elector::expire()\n{\n dout(5) << \"election timer expired\" << dendl;\n \n \/\/ did i win?\n if (electing_me &&\n acked_me.size() > (unsigned)(mon->monmap->size() \/ 2)) {\n \/\/ i win\n victory();\n } else {\n \/\/ whoever i deferred to didn't declare victory quickly enough.\n start();\n }\n}\n\n\nvoid Elector::victory()\n{\n leader_acked = -1;\n electing_me = false;\n set<int> quorum = acked_me;\n \n cancel_timer();\n \n assert(epoch % 2 == 1); \/\/ election\n bump_epoch(epoch+1); \/\/ is over!\n \n \/\/ tell everyone\n for (set<int>::iterator p = quorum.begin();\n p != quorum.end();\n ++p) {\n if (*p == whoami) continue;\n MMonElection *m = new MMonElection(MMonElection::OP_VICTORY, epoch, mon->monmap);\n m->quorum = quorum;\n mon->messenger->send_message(m, mon->monmap->get_inst(*p));\n }\n \n \/\/ tell monitor\n mon->win_election(epoch, quorum);\n}\n\n\nvoid Elector::handle_propose(MMonElection *m)\n{\n dout(5) << \"handle_propose from \" << m->get_source() << dendl;\n int from = m->get_source().num();\n\n assert(m->epoch % 2 == 1); \/\/ election\n if (m->epoch > epoch) {\n bump_epoch(m->epoch);\n }\n else if (m->epoch < epoch) {\n \/\/ got an \"old\" propose,\n if (epoch % 2 == 0 && \/\/ in a non-election cycle\n\tmon->quorum.count(from) == 0) { \/\/ from someone outside the quorum\n \/\/ a mon just started up, call a new election so they can rejoin!\n dout(5) << \" got propose from old epoch, quorum is \" << mon->quorum \n\t << \", \" << m->get_source() << \" must have just started\" << dendl;\n mon->call_election(false);\/\/start();\n } else {\n dout(5) << \" ignoring old propose\" << dendl;\n delete m;\n return;\n }\n }\n\n if (whoami < from) {\n \/\/ i would win over them.\n if (leader_acked >= 0) { \/\/ we already acked someone\n assert(leader_acked < from); \/\/ and they still win, of course\n dout(5) << \"no, we already acked \" << leader_acked << dendl;\n } else {\n \/\/ wait, i should win!\n if (!electing_me)\n\tmon->call_election(false);\/\/start();\n }\n } else {\n \/\/ they would win over me\n if (leader_acked < 0 || \/\/ haven't acked anyone yet, or\n\tleader_acked > from || \/\/ they would win over who you did ack, or\n\tleader_acked == from) { \/\/ this is the guy we're already deferring to\n defer(from);\n } else {\n \/\/ ignore them!\n dout(5) << \"no, we already acked \" << leader_acked << dendl;\n }\n }\n \n delete m;\n}\n \nvoid Elector::handle_ack(MMonElection *m)\n{\n dout(5) << \"handle_ack from \" << m->get_source() << dendl;\n int from = m->get_source().num();\n \n assert(m->epoch % 2 == 1); \/\/ election\n if (m->epoch > epoch) {\n dout(5) << \"woah, that's a newer epoch, i must have rebooted. bumping and re-starting!\" << dendl;\n bump_epoch(m->epoch);\n mon->call_election(false);\/\/start();\n delete m;\n return;\n }\n assert(m->epoch == epoch);\n \n if (electing_me) {\n \/\/ thanks\n acked_me.insert(from);\n dout(5) << \" so far i have \" << acked_me << dendl;\n \n \/\/ is that _everyone_?\n if (acked_me.size() == mon->monmap->size()) {\n \/\/ if yes, shortcut to election finish\n victory();\n }\n } else {\n \/\/ ignore, i'm deferring already.\n assert(leader_acked >= 0);\n }\n \n delete m;\n}\n\n\nvoid Elector::handle_victory(MMonElection *m)\n{\n dout(5) << \"handle_victory from \" << m->get_source() << dendl;\n int from = m->get_source().num();\n\n assert(from < whoami);\n assert(m->epoch % 2 == 0); \n\n \/\/ i should have seen this election if i'm getting the victory.\n if (m->epoch != epoch + 1) { \n dout(5) << \"woah, that's a funny epoch, i must have rebooted. bumping and re-starting!\" << dendl;\n bump_epoch(m->epoch);\n mon->call_election(true);\/\/start();\n delete m;\n return;\n }\n\n bump_epoch(m->epoch);\n \n \/\/ they win\n mon->lose_election(epoch, m->quorum, from);\n \n \/\/ cancel my timer\n cancel_timer();\t\n delete m;\n}\n\n\n\n\nvoid Elector::dispatch(Message *m)\n{\n switch (m->get_type()) {\n \n case MSG_MON_ELECTION:\n {\n MMonElection *em = (MMonElection*)m;\n\n MonMap *peermap = new MonMap;\n peermap->decode(em->monmap_bl);\n if (peermap->epoch > mon->monmap->epoch) {\n\tdout(0) << m->get_source_inst() << \" has newer monmap epoch \" << peermap->epoch\n\t\t<< \" > my epoch \" << mon->monmap->epoch \n\t\t<< \", taking it\"\n\t\t<< dendl;\n\tdelete mon->monmap;\n\tmon->monmap = peermap;\n\tmon->store->put_bl_sn(em->monmap_bl, \"monmap\", peermap->epoch);\n\tmon->store->put_bl_ss(em->monmap_bl, \"monmap\", \"latest\");\n } else {\n\tif (peermap->epoch < mon->monmap->epoch) {\n\t dout(0) << m->get_source_inst() << \" has older monmap epoch \" << peermap->epoch\n\t\t << \" < my epoch \" << mon->monmap->epoch \n\t\t << dendl;\n\t}\n\tdelete peermap;\n } \n\n switch (em->op) {\n case MMonElection::OP_PROPOSE:\n\thandle_propose(em);\n\treturn;\n }\n\n if (em->epoch < epoch) {\n\tdout(5) << \"old epoch, dropping\" << dendl;\n\tdelete em;\n\tbreak;\n }\n\n switch (em->op) {\n case MMonElection::OP_ACK:\n\thandle_ack(em);\n\treturn;\n case MMonElection::OP_VICTORY:\n\thandle_victory(em);\n\treturn;\n default:\n\tassert(0);\n }\n }\n break;\n \n default: \n assert(0);\n }\n}\n\n\n\n\n<commit_msg>elector: off by one check<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This 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 \n * Foundation. See file COPYING.\n * \n *\/\n\n#include \"Elector.h\"\n#include \"Monitor.h\"\n\n#include \"common\/Timer.h\"\n#include \"MonitorStore.h\"\n#include \"messages\/MMonElection.h\"\n\n#include \"config.h\"\n\n#define DOUT_SUBSYS mon\n#undef dout_prefix\n#define dout_prefix _prefix(mon, epoch)\nstatic ostream& _prefix(Monitor *mon, epoch_t epoch) {\n return *_dout << dbeginl\n\t\t<< \"mon\" << mon->whoami\n\t\t<< (mon->is_starting() ? (const char*)\"(starting)\":(mon->is_leader() ? (const char*)\"(leader)\":(mon->is_peon() ? (const char*)\"(peon)\":(const char*)\"(?\\?)\")))\n\t\t<< \".elector(\" << epoch << \") \";\n}\n\n\nvoid Elector::init()\n{\n epoch = mon->store->get_int(\"election_epoch\");\n if (!epoch)\n epoch = 1;\n dout(1) << \"init, last seen epoch \" << epoch << dendl;\n}\n\nvoid Elector::shutdown()\n{\n if (expire_event)\n mon->timer.cancel_event(expire_event);\n}\n\nvoid Elector::bump_epoch(epoch_t e) \n{\n dout(10) << \"bump_epoch \" << epoch << \" to \" << e << dendl;\n assert(epoch <= e);\n epoch = e;\n mon->store->put_int(epoch, \"election_epoch\");\n\n \/\/ clear up some state\n electing_me = false;\n acked_me.clear();\n leader_acked = -1;\n}\n\n\nvoid Elector::start()\n{\n dout(5) << \"start -- can i be leader?\" << dendl;\n \n \/\/ start by trying to elect me\n if (epoch % 2 == 0) \n bump_epoch(epoch+1); \/\/ odd == election cycle\n start_stamp = g_clock.now();\n electing_me = true;\n acked_me.insert(whoami);\n \n \/\/ bcast to everyone else\n for (unsigned i=0; i<mon->monmap->size(); ++i) {\n if ((int)i == whoami) continue;\n mon->messenger->send_message(new MMonElection(MMonElection::OP_PROPOSE, epoch, mon->monmap),\n\t\t\t\t mon->monmap->get_inst(i));\n }\n \n reset_timer();\n}\n\nvoid Elector::defer(int who)\n{\n dout(5) << \"defer to \" << who << dendl;\n\n if (electing_me) {\n \/\/ drop out\n acked_me.clear();\n electing_me = false;\n }\n\n \/\/ ack them\n leader_acked = who;\n ack_stamp = g_clock.now();\n mon->messenger->send_message(new MMonElection(MMonElection::OP_ACK, epoch, mon->monmap),\n\t\t\t mon->monmap->get_inst(who));\n \n \/\/ set a timer\n reset_timer(1.0); \/\/ give the leader some extra time to declare victory\n}\n\n\nvoid Elector::reset_timer(double plus)\n{\n \/\/ set the timer\n cancel_timer();\n expire_event = new C_ElectionExpire(this);\n mon->timer.add_event_after(g_conf.mon_lease + plus,\n\t\t\t expire_event);\n}\n\n\nvoid Elector::cancel_timer()\n{\n if (expire_event) {\n mon->timer.cancel_event(expire_event);\n expire_event = 0;\n }\n}\n\nvoid Elector::expire()\n{\n dout(5) << \"election timer expired\" << dendl;\n \n \/\/ did i win?\n if (electing_me &&\n acked_me.size() > (unsigned)(mon->monmap->size() \/ 2)) {\n \/\/ i win\n victory();\n } else {\n \/\/ whoever i deferred to didn't declare victory quickly enough.\n start();\n }\n}\n\n\nvoid Elector::victory()\n{\n leader_acked = -1;\n electing_me = false;\n set<int> quorum = acked_me;\n \n cancel_timer();\n \n assert(epoch % 2 == 1); \/\/ election\n bump_epoch(epoch+1); \/\/ is over!\n \n \/\/ tell everyone\n for (set<int>::iterator p = quorum.begin();\n p != quorum.end();\n ++p) {\n if (*p == whoami) continue;\n MMonElection *m = new MMonElection(MMonElection::OP_VICTORY, epoch, mon->monmap);\n m->quorum = quorum;\n mon->messenger->send_message(m, mon->monmap->get_inst(*p));\n }\n \n \/\/ tell monitor\n mon->win_election(epoch, quorum);\n}\n\n\nvoid Elector::handle_propose(MMonElection *m)\n{\n dout(5) << \"handle_propose from \" << m->get_source() << dendl;\n int from = m->get_source().num();\n\n assert(m->epoch % 2 == 1); \/\/ election\n if (m->epoch > epoch) {\n bump_epoch(m->epoch);\n }\n else if (m->epoch < epoch) {\n \/\/ got an \"old\" propose,\n if (epoch % 2 == 0 && \/\/ in a non-election cycle\n\tmon->quorum.count(from) == 0) { \/\/ from someone outside the quorum\n \/\/ a mon just started up, call a new election so they can rejoin!\n dout(5) << \" got propose from old epoch, quorum is \" << mon->quorum \n\t << \", \" << m->get_source() << \" must have just started\" << dendl;\n mon->call_election(false);\/\/start();\n } else {\n dout(5) << \" ignoring old propose\" << dendl;\n delete m;\n return;\n }\n }\n\n if (whoami < from) {\n \/\/ i would win over them.\n if (leader_acked >= 0) { \/\/ we already acked someone\n assert(leader_acked < from); \/\/ and they still win, of course\n dout(5) << \"no, we already acked \" << leader_acked << dendl;\n } else {\n \/\/ wait, i should win!\n if (!electing_me)\n\tmon->call_election(false);\/\/start();\n }\n } else {\n \/\/ they would win over me\n if (leader_acked < 0 || \/\/ haven't acked anyone yet, or\n\tleader_acked > from || \/\/ they would win over who you did ack, or\n\tleader_acked == from) { \/\/ this is the guy we're already deferring to\n defer(from);\n } else {\n \/\/ ignore them!\n dout(5) << \"no, we already acked \" << leader_acked << dendl;\n }\n }\n \n delete m;\n}\n \nvoid Elector::handle_ack(MMonElection *m)\n{\n dout(5) << \"handle_ack from \" << m->get_source() << dendl;\n int from = m->get_source().num();\n \n assert(m->epoch % 2 == 1); \/\/ election\n if (m->epoch > epoch) {\n dout(5) << \"woah, that's a newer epoch, i must have rebooted. bumping and re-starting!\" << dendl;\n bump_epoch(m->epoch);\n mon->call_election(false);\/\/start();\n delete m;\n return;\n }\n assert(m->epoch == epoch);\n \n if (electing_me) {\n \/\/ thanks\n acked_me.insert(from);\n dout(5) << \" so far i have \" << acked_me << dendl;\n \n \/\/ is that _everyone_?\n if (acked_me.size() == mon->monmap->size()) {\n \/\/ if yes, shortcut to election finish\n victory();\n }\n } else {\n \/\/ ignore, i'm deferring already.\n assert(leader_acked >= 0);\n }\n \n delete m;\n}\n\n\nvoid Elector::handle_victory(MMonElection *m)\n{\n dout(5) << \"handle_victory from \" << m->get_source() << dendl;\n int from = m->get_source().num();\n\n assert(from < whoami);\n assert(m->epoch % 2 == 0); \n\n \/\/ i should have seen this election if i'm getting the victory.\n if (m->epoch != epoch + 1) { \n dout(5) << \"woah, that's a funny epoch, i must have rebooted. bumping and re-starting!\" << dendl;\n bump_epoch(m->epoch);\n mon->call_election(true);\/\/start();\n delete m;\n return;\n }\n\n bump_epoch(m->epoch);\n \n \/\/ they win\n mon->lose_election(epoch, m->quorum, from);\n \n \/\/ cancel my timer\n cancel_timer();\t\n delete m;\n}\n\n\n\n\nvoid Elector::dispatch(Message *m)\n{\n switch (m->get_type()) {\n \n case MSG_MON_ELECTION:\n {\n MMonElection *em = (MMonElection*)m;\n\n MonMap *peermap = new MonMap;\n peermap->decode(em->monmap_bl);\n if (peermap->epoch > mon->monmap->epoch) {\n\tdout(0) << m->get_source_inst() << \" has newer monmap epoch \" << peermap->epoch\n\t\t<< \" > my epoch \" << mon->monmap->epoch \n\t\t<< \", taking it\"\n\t\t<< dendl;\n\tdelete mon->monmap;\n\tmon->monmap = peermap;\n\tmon->store->put_bl_sn(em->monmap_bl, \"monmap\", peermap->epoch);\n\tmon->store->put_bl_ss(em->monmap_bl, \"monmap\", \"latest\");\n } else {\n\tif (peermap->epoch < mon->monmap->epoch) {\n\t dout(0) << m->get_source_inst() << \" has older monmap epoch \" << peermap->epoch\n\t\t << \" < my epoch \" << mon->monmap->epoch \n\t\t << dendl;\n\t}\n\tdelete peermap;\n } \n\n switch (em->op) {\n case MMonElection::OP_PROPOSE:\n\thandle_propose(em);\n\treturn;\n }\n\n if (em->epoch < epoch) {\n\tdout(5) << \"old epoch, dropping\" << dendl;\n\tdelete em;\n\tbreak;\n }\n\n switch (em->op) {\n case MMonElection::OP_ACK:\n\thandle_ack(em);\n\treturn;\n case MMonElection::OP_VICTORY:\n\thandle_victory(em);\n\treturn;\n default:\n\tassert(0);\n }\n }\n break;\n \n default: \n assert(0);\n }\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <map>\n\n#include \"nameplacer.h\"\n#include \"util\/font.h\"\n#include \"factory\/font_factory.h\"\n#include \"globals.h\"\n\nNamePlacer * NamePlacer::placer = NULL;\nvoid NamePlacer::getPlacement( int & x, int & y, int & id ){\n\n\tif ( placer == NULL )\n\t\tplacer = new NamePlacer();\n\n\tplacer->doPlacement( x, y, id );\n}\n\nvoid NamePlacer::destroy(){\n\tif ( placer != NULL ){\n\t\tdelete placer;\n\t\tplacer = NULL;\n\t}\n}\n\t\nNamePlacer::NamePlacer(){\n\tcur_id = 0;\n}\n\nvoid NamePlacer::doPlacement( int & x, int & y, int & id ){\n\n\tif ( id == -1 || places[ id ] == 0 )\n\t\tid = cur_id++;\n\n\tfor ( map< int, int >::iterator it = places.begin(); it != places.end(); it++ ){\n\t\tint & second = (*it).second;\n\t\tif ( second > 0 )\n\t\t\tsecond--;\n\t}\n\n\tint count = 0;\n\tfor ( map<int,int>::iterator it = places.begin(); it != places.end() && it != places.find( id ); it++){\n\t\tif ( (*it).second > 0 )\n\t\t\tcount++;\n\t}\n\t\/* give the place some buffer room to go away *\/\n\tplaces[ id ] = 10;\n\tconst Font & ft = Font::getFont( \"data\/fonts\/arial.ttf\" );\n\tx = 1 + (count&1) * 170;\n\ty = 1 + (count\/2) * ft.getHeight();\n}\n<commit_msg>dont space out names to far<commit_after>#include <map>\n\n#include \"nameplacer.h\"\n#include \"util\/font.h\"\n#include \"factory\/font_factory.h\"\n#include \"globals.h\"\n\nNamePlacer * NamePlacer::placer = NULL;\nvoid NamePlacer::getPlacement( int & x, int & y, int & id ){\n\n\tif ( placer == NULL )\n\t\tplacer = new NamePlacer();\n\n\tplacer->doPlacement( x, y, id );\n}\n\nvoid NamePlacer::destroy(){\n\tif ( placer != NULL ){\n\t\tdelete placer;\n\t\tplacer = NULL;\n\t}\n}\n\t\nNamePlacer::NamePlacer(){\n\tcur_id = 0;\n}\n\nvoid NamePlacer::doPlacement( int & x, int & y, int & id ){\n\n\tif ( id == -1 || places[ id ] == 0 )\n\t\tid = cur_id++;\n\n\tfor ( map< int, int >::iterator it = places.begin(); it != places.end(); it++ ){\n\t\tint & second = (*it).second;\n\t\tif ( second > 0 )\n\t\t\tsecond--;\n\t}\n\n\tint count = 0;\n\tfor ( map<int,int>::iterator it = places.begin(); it != places.end() && it != places.find( id ); it++){\n\t\tif ( (*it).second > 0 )\n\t\t\tcount++;\n\t}\n\t\/* give the place some buffer room to go away *\/\n\tplaces[ id ] = 10;\n\tconst Font & ft = Font::getFont( \"data\/fonts\/arial.ttf\" );\n\tx = 1 + (count&1) * 170;\n\ty = 1 + (count\/2) * ft.getHeight() \/ 2;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n#include <object\/symbols.hh>\n#include <urbi\/object\/date.hh>\n#include <urbi\/object\/duration.hh>\n#include <urbi\/object\/global.hh>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\nnamespace urbi\n{\n namespace object\n {\n \/*---------------.\n | Construction. |\n `---------------*\/\n\n Date::Date()\n : time_(0)\n {\n proto_add(proto ? proto : Object::proto);\n }\n\n Date::Date(value_type t)\n : time_(t)\n {\n proto_add(proto ? proto : Object::proto);\n }\n\n Date::Date(rDate time)\n : time_(time->time_)\n {\n CAPTURE_GLOBAL(Orderable);\n proto_add(Orderable);\n proto_add(proto);\n }\n\n void\n Date::init(const objects_type& args)\n {\n check_arg_count(args.size(), 0, 1);\n\n if (args.empty())\n {\n time_ = 0;\n return;\n }\n\n if (rString str = args[0]->as<object::String>())\n {\n boost::posix_time::ptime t\n (boost::posix_time::time_from_string(str->value_get()));\n tm timeinfo = boost::posix_time::to_tm(t);\n time_ = mktime (&timeinfo);\n\n return;\n }\n\n time_ = from_urbi<unsigned>(args[0]);\n }\n\n \/*-------------.\n | Comparison. |\n `-------------*\/\n\n bool\n Date::operator ==(rDate rhs) const\n {\n return time_ == rhs->time_;\n }\n\n bool\n Date::operator <(rDate rhs) const\n {\n return time_ < rhs->time_;\n }\n\n \/*-------------.\n | Operations. |\n `-------------*\/\n\n rDuration\n Date::operator - (rDate rhs) const\n {\n return new Duration(time_ - rhs->time_);\n }\n\n Date&\n Date::operator += (rDuration rhs)\n {\n time_ += static_cast<value_type>(rhs->seconds());\n return *this;\n }\n\n rDate\n Date::operator + (rDuration rhs) const\n {\n rDate res = new Date(time_);\n *res += rhs;\n return res;\n }\n\n \/*--------------.\n | Conversions. |\n `--------------*\/\n\n std::string\n Date::as_string() const\n {\n struct tm date;\n localtime_r(&time_, &date);\n return libport::format(\"%04s-%02s-%02s %02s:%02s:%02s\",\n 1900 + date.tm_year,\n date.tm_mon + 1,\n date.tm_mday,\n date.tm_hour,\n date.tm_min,\n date.tm_sec);\n }\n\n libport::ufloat\n Date::asFloat () const\n {\n return time_;\n }\n\n libport::ufloat\n Date::timestamp () const\n {\n return asFloat ();\n }\n\n \/*--------.\n | Dates. |\n `--------*\/\n\n rDate\n Date::now ()\n {\n return new Date(time(0));\n }\n\n rDate\n Date::epoch ()\n {\n return new Date(0);\n }\n\n\n \/*-----------------.\n | Binding system. |\n `-----------------*\/\n\n void\n Date::initialize(CxxObject::Binder<Date>& bind)\n {\n bind(SYMBOL(EQ_EQ), &Date::operator ==);\n bind(SYMBOL(LT), (bool (Date::*)(rDate rhs) const)&Date::operator <);\n bind(SYMBOL(MINUS), &Date::operator -);\n bind(SYMBOL(PLUS), &Date::operator +);\n bind(SYMBOL(asString), &Date::as_string);\n bind(SYMBOL(epoch), &Date::epoch);\n bind(SYMBOL(init), &Date::init);\n bind(SYMBOL(now), &Date::now);\n bind(SYMBOL(timestamp), &Date::timestamp);\n }\n\n URBI_CXX_OBJECT_REGISTER(Date)\n : time_(0)\n {}\n }\n}\n<commit_msg>date: fix.<commit_after>\/*\n * Copyright (C) 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n#include <object\/symbols.hh>\n#include <urbi\/object\/date.hh>\n#include <urbi\/object\/duration.hh>\n#include <urbi\/object\/global.hh>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\nnamespace urbi\n{\n namespace object\n {\n \/*---------------.\n | Construction. |\n `---------------*\/\n\n Date::Date()\n : time_(0)\n {\n proto_add(proto ? proto : Object::proto);\n }\n\n Date::Date(value_type t)\n : time_(t)\n {\n proto_add(proto ? proto : Object::proto);\n }\n\n Date::Date(rDate time)\n : time_(time->time_)\n {\n CAPTURE_GLOBAL(Orderable);\n proto_add(Orderable);\n proto_add(proto);\n }\n\n void\n Date::init(const objects_type& args)\n {\n check_arg_count(args.size(), 0, 1);\n\n if (args.empty())\n {\n time_ = 0;\n return;\n }\n\n if (rString str = args[0]->as<object::String>())\n {\n boost::posix_time::ptime t\n (boost::posix_time::time_from_string(str->value_get()));\n tm timeinfo = boost::posix_time::to_tm(t);\n time_ = mktime (&timeinfo);\n\n return;\n }\n\n time_ = from_urbi<unsigned>(args[0]);\n }\n\n \/*-------------.\n | Comparison. |\n `-------------*\/\n\n bool\n Date::operator ==(rDate rhs) const\n {\n return time_ == rhs->time_;\n }\n\n bool\n Date::operator <(rDate rhs) const\n {\n return time_ < rhs->time_;\n }\n\n \/*-------------.\n | Operations. |\n `-------------*\/\n\n rDuration\n Date::operator - (rDate rhs) const\n {\n return new Duration(time_ - rhs->time_);\n }\n\n Date&\n Date::operator += (rDuration rhs)\n {\n time_ += static_cast<value_type>(rhs->seconds());\n return *this;\n }\n\n rDate\n Date::operator + (rDuration rhs) const\n {\n rDate res = new Date(time_);\n *res += rhs;\n return res;\n }\n\n \/*--------------.\n | Conversions. |\n `--------------*\/\n\n std::string\n Date::as_string() const\n {\n struct tm date;\n localtime_r(&time_, &date);\n return libport::format(\"%04s-%02s-%02s %02s:%02s:%02s\",\n 1900 + date.tm_year,\n date.tm_mon + 1,\n date.tm_mday,\n date.tm_hour,\n date.tm_min,\n date.tm_sec);\n }\n\n libport::ufloat\n Date::asFloat() const\n {\n return time_;\n }\n\n libport::ufloat\n Date::timestamp() const\n {\n return asFloat ();\n }\n\n \/*--------.\n | Dates. |\n `--------*\/\n\n rDate\n Date::now ()\n {\n return new Date(time(0));\n }\n\n rDate\n Date::epoch ()\n {\n return new Date(0);\n }\n\n\n \/*-----------------.\n | Binding system. |\n `-----------------*\/\n\n void\n Date::initialize(CxxObject::Binder<Date>& bind)\n {\n bind(SYMBOL(EQ_EQ), &Date::operator ==);\n bind(SYMBOL(LT), (bool (Date::*)(rDate rhs) const)&Date::operator <);\n bind(SYMBOL(MINUS), &Date::operator -);\n bind(SYMBOL(PLUS), &Date::operator +);\n bind(SYMBOL(asFloat), &Date::asFloat);\n bind(SYMBOL(asString), &Date::as_string);\n bind(SYMBOL(epoch), &Date::epoch);\n bind(SYMBOL(init), &Date::init);\n bind(SYMBOL(now), &Date::now);\n bind(SYMBOL(timestamp), &Date::timestamp);\n }\n\n URBI_CXX_OBJECT_REGISTER(Date)\n : time_(0)\n {}\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Mesh.hxx\"\n#include \"Functional.hxx\"\n\n#include \"..\/ostream_vector.hxx\"\n\n\/\/ We convert the optimization problem into a regular linear\n\/\/ programming problem.\n\/\/\n\/\/ 1) Each polynomial in Block::polys adds two variables. The\n\/\/ weights of those polynomials are unbounded, while linear\n\/\/ programming requires a strictly positive variable. So we\n\/\/ substitute W_n = w_n+ - w_n+, where both w_n+ and w_n- are\n\/\/ strictly positive. All blocks should have the same number of\n\/\/ polynomials, so we only need to look at the first one.\n\/\/\n\/\/ 2) Each constraint adds one 'slack' variable s_n. There is one\n\/\/ constraint per coordinate 'x', with each block having multiple,\n\/\/ separate coordinates.\n\/\/\n\/\/ 3) One more global variable delta, which gives the linear\n\/\/ program something to minimize.\n\/\/\n\/\/ This turns the problem\n\/\/\n\/\/ A_0 . W > 0\n\/\/ A_1 . W > 0\n\/\/ ...\n\/\/\n\/\/ into\n\/\/\n\/\/ min delta\n\/\/\n\/\/ where\n\/\/\n\/\/ A_0 . (w_+ - w_-) + delta - s_0 = 0\n\/\/ A_1 . (w_+ - w_-) + delta - s_1 = 0\n\/\/ ...\n\/\/ w_n+, w_n-, s_n, delta >= 0\n\/\/\n\/\/ There is a constraint for every point that is sampled. At the\n\/\/ beginning, we sample the min and max for each block, so there are\n\/\/ 2*num_blocks constraints. In general\n\/\/\n\/\/ => num_rows == num_constraints\n\/\/ => num_columns == 2*num_weights + num_constraints + 1\n\nstd::vector<El::BigFloat> get_new_points(const Mesh &mesh);\nEl::BigFloat max_value(const Mesh &mesh);\n\nvoid solve_LP(const El::Matrix<El::BigFloat> &A,\n const El::Matrix<El::BigFloat> &b,\n const El::Matrix<El::BigFloat> &c,\n std::vector<El::BigFloat> &weights);\n\nint main(int argc, char **argv)\n{\n El::Environment env(argc, argv);\n const int64_t precision(1024);\n El::gmp::SetPrecision(precision);\n\n Functional functional(\"test\/toy_polys\", \"\", false);\n size_t num_weights(functional.blocks.at(0).polys.size());\n\n const size_t num_blocks(functional.blocks.size());\n const El::BigFloat min_x(0.0), max_x(100.0);\n std::vector<El::BigFloat> scale(num_blocks);\n std::vector<El::BigFloat> weights(num_weights, 1);\n for(size_t block(0); block != num_blocks; ++block)\n {\n scale[block]\n = Abs(functional.blocks[block].eval_weighted(max_x, weights));\n }\n\n std::vector<std::vector<El::BigFloat>> points(num_blocks, {min_x}),\n new_points(num_blocks, {max_x});\n\n bool has_new_points(true);\n while(has_new_points)\n {\n has_new_points = false;\n size_t num_constraints(0);\n for(size_t block(0); block != num_blocks; ++block)\n {\n for(auto &point : new_points.at(block))\n {\n points.at(block).emplace_back(point);\n }\n num_constraints += points.at(block).size();\n }\n \n const size_t num_rows(num_constraints),\n num_columns(2 * weights.size() + num_constraints + 1);\n\n El::Matrix<El::BigFloat> A(num_rows, num_columns);\n El::Zero(A);\n\n size_t row(0);\n for(size_t block(0); block != num_blocks; ++block)\n {\n \/\/ One constraint per point\n for(size_t point(0); point != points.at(block).size(); ++point)\n {\n \/\/ delta term\n A(row, 0) = 1;\n \/\/ slack term\n A(row, 2 * weights.size() + row + 1) = -1;\n\n const El::BigFloat &x(points.at(block)[point]);\n for(size_t poly_index(0);\n poly_index != functional.blocks.at(block).polys.size();\n ++poly_index)\n {\n A(row, 2 * poly_index + 1)\n = functional.blocks.at(block).polys.at(poly_index)(x);\n A(row, 2 * poly_index + 2) = -A(row, 2 * poly_index + 1);\n }\n ++row;\n }\n }\n\n El::Matrix<El::BigFloat> b(num_rows, 1), c(num_columns, 1);\n El::Zero(b);\n El::Zero(c);\n c(0, 0) = 1;\n\n \/\/ std::cout << \"A: \"\n \/\/ << A.Height() << \" \"\n \/\/ << A.Width() << \" \"\n \/\/ << b.Height() << \" \"\n \/\/ << b.Width() << \" \"\n \/\/ << c.Height() << \" \"\n \/\/ << c.Width() << \" \"\n \/\/ << \"\\n\";\n\n \/\/ El::Print(A, \"A\");\n \/\/ El::Print(b, \"\\nb\");\n \/\/ El::Print(c, \"\\nc\");\n \/\/ std::cout << \"\\n\";\n\n solve_LP(A, b, c, weights);\n\n std::cout << \"weight: \" << weights << \"\\n\";\n for(size_t block(0); block != num_blocks; ++block)\n {\n \/\/ std::cout.precision(precision \/ 3.3);\n \/\/ std::cout << \"solve: \" << points.at(block).size() << \" \" << weights\n \/\/ << \"\\n\";\n\n \/\/ 0.01 should be a small enough relative error so that we are\n \/\/ in the regime of convergence. Then the error estimates will\n \/\/ work\n Mesh mesh(min_x, max_x,\n [&](const El::BigFloat &x) {\n return functional.blocks.at(block).eval_weighted(\n x, weights);\n },\n 0.01);\n new_points.at(block) = get_new_points(mesh);\n std::cout << \"new: \" << new_points.at(block) << \"\\n\";\n scale.at(block) = max_value(mesh);\n has_new_points = has_new_points || !new_points.at(block).empty();\n }\n }\n \/\/ std::cout.precision(precision \/ 3.3);\n std::cout << \"weights: \" << weights << \"\\n\";\n}\n<commit_msg>Use poles<commit_after>#include \"Mesh.hxx\"\n#include \"Functional.hxx\"\n\n#include \"..\/ostream_vector.hxx\"\n\n\/\/ We convert the optimization problem into a regular linear\n\/\/ programming problem.\n\/\/\n\/\/ 1) Each polynomial in Block::polys adds two variables. The\n\/\/ weights of those polynomials are unbounded, while linear\n\/\/ programming requires a strictly positive variable. So we\n\/\/ substitute W_n = w_n+ - w_n+, where both w_n+ and w_n- are\n\/\/ strictly positive. All blocks should have the same number of\n\/\/ polynomials, so we only need to look at the first one.\n\/\/\n\/\/ 2) Each constraint adds one 'slack' variable s_n. There is one\n\/\/ constraint per coordinate 'x', with each block having multiple,\n\/\/ separate coordinates.\n\/\/\n\/\/ 3) One more global variable delta, which gives the linear\n\/\/ program something to minimize.\n\/\/\n\/\/ This turns the problem\n\/\/\n\/\/ A_0 . W > 0\n\/\/ A_1 . W > 0\n\/\/ ...\n\/\/\n\/\/ into\n\/\/\n\/\/ min delta\n\/\/\n\/\/ where\n\/\/\n\/\/ A_0 . (w_+ - w_-) + delta - s_0 = 0\n\/\/ A_1 . (w_+ - w_-) + delta - s_1 = 0\n\/\/ ...\n\/\/ w_n+, w_n-, s_n, delta >= 0\n\/\/\n\/\/ There is a constraint for every point that is sampled. At the\n\/\/ beginning, we sample the min and max for each block, so there are\n\/\/ 2*num_blocks constraints. In general\n\/\/\n\/\/ => num_rows == num_constraints\n\/\/ => num_columns == 2*num_weights + num_constraints + 1\n\nstd::vector<El::BigFloat> get_new_points(const Mesh &mesh);\nEl::BigFloat max_value(const Mesh &mesh);\n\nvoid solve_LP(const El::Matrix<El::BigFloat> &A,\n const El::Matrix<El::BigFloat> &b,\n const El::Matrix<El::BigFloat> &c,\n std::vector<El::BigFloat> &weights);\n\nint main(int argc, char **argv)\n{\n El::Environment env(argc, argv);\n const int64_t precision(1024);\n El::gmp::SetPrecision(precision);\n\n \/\/ Functional functional(\"polys\", \"test\/single_corr_poles\");\n \/\/ Functional functional(\"test\/single_corr_polys\", \"test\/single_corr_poles\");\n Functional functional(\"test\/toy_polys\", \"\");\n size_t num_weights(functional.blocks.at(0).polys.size());\n\n \/\/ for(auto &pole: functional.blocks[0].poles)\n \/\/ {\n \/\/ std::cout << \"pole: \" << pole << \"\\n\";\n \/\/ }\n\n \/\/ std::cout << \"prefactor: \"\n \/\/ << (functional.prefactor(1.44) *\n \/\/ functional.blocks[0].pole_prefactor(1.44)) << \" \"\n \/\/ << functional.blocks.at(0).polys.at(0)(1.44) << \" \"\n \/\/ << \"\\n\";\n \/\/ \/\/ std::cout << functional.blocks.at(0).polys.at(0) << \"\\n\";\n\n \/\/ for(size_t index(0); index<functional.blocks[0].polys.size(); ++index)\n \/\/ {\n \/\/ std::cout << index << \" \"\n \/\/ << (functional.blocks.at(0).polys.at(index)(0.0)\n \/\/ * functional.prefactor(0.0)\n \/\/ * functional.blocks[0].pole_prefactor(0.0))\n \/\/ << \"\\n\";\n \/\/ }\n \/\/ exit(0);\n\n const size_t num_blocks(functional.blocks.size());\n const El::BigFloat min_x(0.0), max_x(100.0);\n std::vector<El::BigFloat> scale(num_blocks);\n std::vector<El::BigFloat> weights(num_weights, 1);\n\n const El::BigFloat prefactor(functional.prefactor(max_x));\n for(size_t block(0); block != num_blocks; ++block)\n {\n scale[block] = Abs(\n prefactor * functional.blocks[block].eval_weighted(max_x, weights));\n }\n\n \/\/ const El::BigFloat scalar_gap(1.44);\n \/\/ std::vector<std::vector<El::BigFloat>> points(num_blocks,\n \/\/ {min_x, scalar_gap}),\n std::vector<std::vector<El::BigFloat>> points(num_blocks,\n {min_x}),\n new_points(num_blocks, {max_x});\n\n bool has_new_points(true);\n while(has_new_points)\n {\n has_new_points = false;\n size_t num_constraints(0);\n for(size_t block(0); block != num_blocks; ++block)\n {\n for(auto &point : new_points.at(block))\n {\n points.at(block).emplace_back(point);\n }\n num_constraints += points.at(block).size();\n }\n\n const size_t num_rows(num_constraints),\n num_columns(2 * weights.size() + num_constraints + 1);\n\n El::Matrix<El::BigFloat> A(num_rows, num_columns);\n El::Zero(A);\n\n size_t row(0);\n for(size_t block(0); block != num_blocks; ++block)\n {\n \/\/ One constraint per point\n for(size_t point(0); point != points.at(block).size(); ++point)\n {\n \/\/ delta term\n A(row, 0) = 1;\n \/\/ slack term\n A(row, 2 * weights.size() + row + 1) = -1;\n\n const El::BigFloat &x(points.at(block)[point]);\n const El::BigFloat prefactor(\n functional.prefactor(x)\n * functional.blocks.at(block).pole_prefactor(x));\n for(size_t poly_index(0);\n poly_index != functional.blocks.at(block).polys.size();\n ++poly_index)\n {\n A(row, 2 * poly_index + 1)\n = prefactor\n * functional.blocks.at(block).polys.at(poly_index)(x);\n A(row, 2 * poly_index + 2) = -A(row, 2 * poly_index + 1);\n }\n ++row;\n }\n }\n\n El::Matrix<El::BigFloat> b(num_rows, 1), c(num_columns, 1);\n El::Zero(b);\n El::Zero(c);\n c(0, 0) = 1;\n\n \/\/ std::cout << \"A: \"\n \/\/ << A.Height() << \" \"\n \/\/ << A.Width() << \" \"\n \/\/ << b.Height() << \" \"\n \/\/ << b.Width() << \" \"\n \/\/ << c.Height() << \" \"\n \/\/ << c.Width() << \" \"\n \/\/ << \"\\n\";\n\n \/\/ El::Print(A, \"A\");\n \/\/ El::Print(b, \"\\nb\");\n \/\/ El::Print(c, \"\\nc\");\n \/\/ std::cout << \"\\n\";\n\n solve_LP(A, b, c, weights);\n\n std::cout << \"weight: \" << weights << \"\\n\";\n for(size_t block(0); block != num_blocks; ++block)\n {\n \/\/ std::cout.precision(precision \/ 3.3);\n \/\/ std::cout << \"solve: \" << points.at(block).size() << \" \" << weights\n \/\/ << \"\\n\";\n\n \/\/ 0.01 should be a small enough relative error so that we are\n \/\/ in the regime of convergence. Then the error estimates will\n \/\/ work\n Mesh mesh(min_x, max_x,\n [&](const El::BigFloat &x) {\n return functional.prefactor(x)\n * functional.blocks.at(block).eval_weighted(\n x, weights);\n },\n 0.01);\n new_points.at(block) = get_new_points(mesh);\n std::cout << \"new: \" << block << \" \" << new_points.at(block) << \"\\n\";\n scale.at(block) = max_value(mesh);\n has_new_points = has_new_points || !new_points.at(block).empty();\n }\n }\n \/\/ std::cout.precision(precision \/ 3.3);\n std::cout << \"weights: \" << weights << \"\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010-2012 Jeremy Lainé\n * Contact: http:\/\/code.google.com\/p\/qdjango\/\n *\n * This file is part of the QDjango Library.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation, either version 3 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. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <QCoreApplication>\n#include <QDateTime>\n#include <QDebug>\n#include <QSqlDriver>\n#include <QSqlError>\n#include <QSqlQuery>\n#include <QStringList>\n#include <QThread>\n\n#include \"QDjango.h\"\n\nstatic const char *connectionPrefix = \"_qdjango_\";\n\nQMap<QString, QDjangoMetaModel> globalMetaModels = QMap<QString, QDjangoMetaModel>();\nstatic QDjangoDatabase *globalDatabase = 0;\nstatic bool globalDebugEnabled = false;\n\nQDjangoDatabase::QDjangoDatabase(QObject *parent)\n : QObject(parent), connectionId(0)\n{\n}\n\nvoid QDjangoDatabase::threadFinished()\n{\n QThread *thread = qobject_cast<QThread*>(sender());\n if (!thread)\n return;\n\n \/\/ cleanup database connection for the thread\n QMutexLocker locker(&mutex);\n disconnect(thread, SIGNAL(finished()), this, SLOT(threadFinished()));\n const QString connectionName = copies.value(thread).connectionName();\n copies.remove(thread);\n if (connectionName.startsWith(QLatin1String(connectionPrefix)))\n QSqlDatabase::removeDatabase(connectionName);\n}\n\nstatic void closeDatabase()\n{\n delete globalDatabase;\n}\n\nQDjangoQuery::QDjangoQuery(QSqlDatabase db)\n : QSqlQuery(db)\n{\n}\n\nvoid QDjangoQuery::addBindValue(const QVariant &val, QSql::ParamType paramType)\n{\n \/\/ this hack is required so that we do not store a mix of local\n \/\/ and UTC times\n if (val.type() == QVariant::DateTime)\n QSqlQuery::addBindValue(val.toDateTime().toLocalTime(), paramType);\n else\n QSqlQuery::addBindValue(val, paramType);\n}\n\nbool QDjangoQuery::exec()\n{\n if (globalDebugEnabled) {\n qDebug() << \"SQL query\" << lastQuery();\n QMapIterator<QString, QVariant> i(boundValues());\n while (i.hasNext()) {\n i.next();\n qDebug() << \"SQL \" << i.key().toAscii().data() << \"=\"\n << i.value().toString().toAscii().data();\n }\n }\n if (!QSqlQuery::exec()) {\n if (globalDebugEnabled)\n qWarning() << \"SQL error\" << lastError();\n return false;\n }\n return true;\n}\n\nbool QDjangoQuery::exec(const QString &query)\n{\n if (globalDebugEnabled)\n qDebug() << \"SQL query\" << query;\n if (!QSqlQuery::exec(query)) {\n if (globalDebugEnabled)\n qWarning() << \"SQL error\" << lastError();\n return false;\n }\n return true;\n}\n\n\/*! \\mainpage\n *\n * QDjango is a simple yet powerful Object Relation Mapper (ORM) built\n * on top of the Qt library. Where possible it tries to follow django's\n * ORM API, hence its name.\n *\n * \\sa QDjango\n * \\sa QDjangoModel\n * \\sa QDjangoWhere\n * \\sa QDjangoQuerySet\n *\/\n\n\n\/** Returns the database used by QDjango.\n *\n * If you call this method from any thread but the application's main thread,\n * a new connection to the database will be created. The connection will\n * automatically be torn down once the thread finishes.\n *\n * \\sa setDatabase()\n *\/\nQSqlDatabase QDjango::database()\n{\n Q_ASSERT(globalDatabase != 0);\n QThread *thread = QThread::currentThread();\n\n \/\/ if we are in the main thread, return reference connection\n if (thread == globalDatabase->thread())\n return globalDatabase->reference;\n\n \/\/ if we have a connection for this thread, return it\n QMutexLocker locker(&globalDatabase->mutex);\n if (globalDatabase->copies.contains(thread))\n return globalDatabase->copies[thread];\n\n \/\/ create a new connection for this thread\n QObject::connect(thread, SIGNAL(finished()), globalDatabase, SLOT(threadFinished()));\n QSqlDatabase db = QSqlDatabase::cloneDatabase(globalDatabase->reference,\n QLatin1String(connectionPrefix) + QString::number(globalDatabase->connectionId++));\n db.open();\n globalDatabase->copies.insert(thread, db);\n return db;\n}\n\n\/** Sets the database used by QDjango.\n *\n * You must call this method from your application's main thread.\n *\n * \\sa database()\n *\/\nvoid QDjango::setDatabase(QSqlDatabase database)\n{\n if (database.driverName() != QLatin1String(\"QSQLITE\") &&\n database.driverName() != QLatin1String(\"QSQLITE2\") &&\n database.driverName() != QLatin1String(\"QMYSQL\") &&\n database.driverName() != QLatin1String(\"QPSQL\"))\n {\n qWarning() << \"Unsupported database driver\" << database.driverName();\n }\n if (!globalDatabase)\n {\n globalDatabase = new QDjangoDatabase();\n qAddPostRoutine(closeDatabase);\n }\n globalDatabase->reference = database;\n}\n\n\/** Returns whether debugging information should be printed.\n *\n * \\sa setDebugEnabled()\n *\/\nbool QDjango::isDebugEnabled()\n{\n return globalDebugEnabled;\n}\n\n\/** Sets whether debugging information should be printed.\n *\n * \\sa isDebugEnabled()\n *\/\nvoid QDjango::setDebugEnabled(bool enabled)\n{\n globalDebugEnabled = enabled;\n}\n\n\/** Creates the database tables for all registered models.\n *\/\nbool QDjango::createTables()\n{\n bool ret = true;\n foreach (const QString &key, globalMetaModels.keys())\n if (!globalMetaModels[key].createTable())\n ret = false;\n return ret;\n}\n\n\/** Drops the database tables for all registered models.\n *\/\nbool QDjango::dropTables()\n{\n bool ret = true;\n foreach (const QString &key, globalMetaModels.keys())\n if (!globalMetaModels[key].dropTable())\n ret = false;\n return ret;\n}\n\n\/** Returns the QDjangoMetaModel with the given name.\n *\n * \\param name\n *\/\nQDjangoMetaModel QDjango::metaModel(const QString &name)\n{\n return globalMetaModels.value(name);\n}\n\nQDjangoMetaModel QDjango::registerModel(const QObject *model)\n{\n const QString name = model->metaObject()->className();\n if (!globalMetaModels.contains(name))\n globalMetaModels.insert(name, QDjangoMetaModel(model));\n return globalMetaModels[name];\n}\n\n\/** Returns the empty SQL limit clause.\n *\/\nQString QDjango::noLimitSql()\n{\n const QString driverName = QDjango::database().driverName();\n if (driverName == QLatin1String(\"QSQLITE\") ||\n driverName == QLatin1String(\"QSQLITE2\"))\n return QLatin1String(\" LIMIT -1\");\n else if (driverName == QLatin1String(\"QMYSQL\"))\n \/\/ 2^64 - 1, as recommended by the MySQL documentation\n return QLatin1String(\" LIMIT 18446744073709551615\");\n else\n return QString();\n}\n\n<commit_msg>silence doc warnings<commit_after>\/*\n * Copyright (C) 2010-2012 Jeremy Lainé\n * Contact: http:\/\/code.google.com\/p\/qdjango\/\n *\n * This file is part of the QDjango Library.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation, either version 3 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. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <QCoreApplication>\n#include <QDateTime>\n#include <QDebug>\n#include <QSqlDriver>\n#include <QSqlError>\n#include <QSqlQuery>\n#include <QStringList>\n#include <QThread>\n\n#include \"QDjango.h\"\n\nstatic const char *connectionPrefix = \"_qdjango_\";\n\nQMap<QString, QDjangoMetaModel> globalMetaModels = QMap<QString, QDjangoMetaModel>();\nstatic QDjangoDatabase *globalDatabase = 0;\nstatic bool globalDebugEnabled = false;\n\n\/\/\/ \\cond\n\nQDjangoDatabase::QDjangoDatabase(QObject *parent)\n : QObject(parent), connectionId(0)\n{\n}\n\nvoid QDjangoDatabase::threadFinished()\n{\n QThread *thread = qobject_cast<QThread*>(sender());\n if (!thread)\n return;\n\n \/\/ cleanup database connection for the thread\n QMutexLocker locker(&mutex);\n disconnect(thread, SIGNAL(finished()), this, SLOT(threadFinished()));\n const QString connectionName = copies.value(thread).connectionName();\n copies.remove(thread);\n if (connectionName.startsWith(QLatin1String(connectionPrefix)))\n QSqlDatabase::removeDatabase(connectionName);\n}\n\nstatic void closeDatabase()\n{\n delete globalDatabase;\n}\n\nQDjangoQuery::QDjangoQuery(QSqlDatabase db)\n : QSqlQuery(db)\n{\n}\n\nvoid QDjangoQuery::addBindValue(const QVariant &val, QSql::ParamType paramType)\n{\n \/\/ this hack is required so that we do not store a mix of local\n \/\/ and UTC times\n if (val.type() == QVariant::DateTime)\n QSqlQuery::addBindValue(val.toDateTime().toLocalTime(), paramType);\n else\n QSqlQuery::addBindValue(val, paramType);\n}\n\nbool QDjangoQuery::exec()\n{\n if (globalDebugEnabled) {\n qDebug() << \"SQL query\" << lastQuery();\n QMapIterator<QString, QVariant> i(boundValues());\n while (i.hasNext()) {\n i.next();\n qDebug() << \"SQL \" << i.key().toAscii().data() << \"=\"\n << i.value().toString().toAscii().data();\n }\n }\n if (!QSqlQuery::exec()) {\n if (globalDebugEnabled)\n qWarning() << \"SQL error\" << lastError();\n return false;\n }\n return true;\n}\n\nbool QDjangoQuery::exec(const QString &query)\n{\n if (globalDebugEnabled)\n qDebug() << \"SQL query\" << query;\n if (!QSqlQuery::exec(query)) {\n if (globalDebugEnabled)\n qWarning() << \"SQL error\" << lastError();\n return false;\n }\n return true;\n}\n\n\/\/\/ \\endcond\n\n\/*! \\mainpage\n *\n * QDjango is a simple yet powerful Object Relation Mapper (ORM) built\n * on top of the Qt library. Where possible it tries to follow django's\n * ORM API, hence its name.\n *\n * \\sa QDjango\n * \\sa QDjangoModel\n * \\sa QDjangoWhere\n * \\sa QDjangoQuerySet\n *\/\n\n\n\/** Returns the database used by QDjango.\n *\n * If you call this method from any thread but the application's main thread,\n * a new connection to the database will be created. The connection will\n * automatically be torn down once the thread finishes.\n *\n * \\sa setDatabase()\n *\/\nQSqlDatabase QDjango::database()\n{\n Q_ASSERT(globalDatabase != 0);\n QThread *thread = QThread::currentThread();\n\n \/\/ if we are in the main thread, return reference connection\n if (thread == globalDatabase->thread())\n return globalDatabase->reference;\n\n \/\/ if we have a connection for this thread, return it\n QMutexLocker locker(&globalDatabase->mutex);\n if (globalDatabase->copies.contains(thread))\n return globalDatabase->copies[thread];\n\n \/\/ create a new connection for this thread\n QObject::connect(thread, SIGNAL(finished()), globalDatabase, SLOT(threadFinished()));\n QSqlDatabase db = QSqlDatabase::cloneDatabase(globalDatabase->reference,\n QLatin1String(connectionPrefix) + QString::number(globalDatabase->connectionId++));\n db.open();\n globalDatabase->copies.insert(thread, db);\n return db;\n}\n\n\/** Sets the database used by QDjango.\n *\n * You must call this method from your application's main thread.\n *\n * \\sa database()\n *\/\nvoid QDjango::setDatabase(QSqlDatabase database)\n{\n if (database.driverName() != QLatin1String(\"QSQLITE\") &&\n database.driverName() != QLatin1String(\"QSQLITE2\") &&\n database.driverName() != QLatin1String(\"QMYSQL\") &&\n database.driverName() != QLatin1String(\"QPSQL\"))\n {\n qWarning() << \"Unsupported database driver\" << database.driverName();\n }\n if (!globalDatabase)\n {\n globalDatabase = new QDjangoDatabase();\n qAddPostRoutine(closeDatabase);\n }\n globalDatabase->reference = database;\n}\n\n\/** Returns whether debugging information should be printed.\n *\n * \\sa setDebugEnabled()\n *\/\nbool QDjango::isDebugEnabled()\n{\n return globalDebugEnabled;\n}\n\n\/** Sets whether debugging information should be printed.\n *\n * \\sa isDebugEnabled()\n *\/\nvoid QDjango::setDebugEnabled(bool enabled)\n{\n globalDebugEnabled = enabled;\n}\n\n\/** Creates the database tables for all registered models.\n *\/\nbool QDjango::createTables()\n{\n bool ret = true;\n foreach (const QString &key, globalMetaModels.keys())\n if (!globalMetaModels[key].createTable())\n ret = false;\n return ret;\n}\n\n\/** Drops the database tables for all registered models.\n *\/\nbool QDjango::dropTables()\n{\n bool ret = true;\n foreach (const QString &key, globalMetaModels.keys())\n if (!globalMetaModels[key].dropTable())\n ret = false;\n return ret;\n}\n\n\/** Returns the QDjangoMetaModel with the given name.\n *\n * \\param name\n *\/\nQDjangoMetaModel QDjango::metaModel(const QString &name)\n{\n return globalMetaModels.value(name);\n}\n\nQDjangoMetaModel QDjango::registerModel(const QObject *model)\n{\n const QString name = model->metaObject()->className();\n if (!globalMetaModels.contains(name))\n globalMetaModels.insert(name, QDjangoMetaModel(model));\n return globalMetaModels[name];\n}\n\n\/** Returns the empty SQL limit clause.\n *\/\nQString QDjango::noLimitSql()\n{\n const QString driverName = QDjango::database().driverName();\n if (driverName == QLatin1String(\"QSQLITE\") ||\n driverName == QLatin1String(\"QSQLITE2\"))\n return QLatin1String(\" LIMIT -1\");\n else if (driverName == QLatin1String(\"QMYSQL\"))\n \/\/ 2^64 - 1, as recommended by the MySQL documentation\n return QLatin1String(\" LIMIT 18446744073709551615\");\n else\n return QString();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2008 Matthew Graham\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#include \"dispatcher.h\"\n#include \"action.h\"\n#include \"protocol.h\"\n#include \"request.h\"\n#include \"response.h\"\n#include \"..\/message\/message.h\"\n#include <iostream>\n\n\ndispatcher_c::dispatcher_c( server_queue_i &queue )\n: m_queue( queue )\n, m_protocol()\n{}\n\ndispatcher_c::~dispatcher_c() {}\n\n\nvoid dispatcher_c::add_protocol( short port, protocol_c &protocol )\n{\n\tm_protocol[ port ] = &protocol;\n}\n\n\nbool dispatcher_c::main_loop()\n{\n\tbool success( false );\n\tfor (;;) {\n\t\tstd::auto_ptr< request_message_i > msg( m_queue.pop() );\n\t\tif ( ! msg.get() ) {\n\t\t\t\/\/ sleep or yield or something, then reiterate\n\t\t\tcontinue;\n\t\t}\n\n\t\tdispatch( *req, *resp );\n\t}\n\n\treturn success;\n}\n\nvoid request_router_c::dispatch( const request_c &req, response_c &resp )\n{\n\tbool success( false );\n\tstd::auto_ptr< response_c > resp( new response_c() );\n\n\tprotocol_c *protocol = find_protocol( port );\n\tif ( ! protocol ) {\n\t\t\/\/ can't do anything.\n\t\t\/\/ write to the response and return\n\t\tstd::ostringstream err;\n\t\terr << \"No protocol for port \" << port;\n\t\tresp.err( err.str() );\n\t\treturn;\n\t}\n\n\taction_i *action = protocol->action( req.type() );\n\tif ( ! action ) {\n\t\tstd::cerr << \"no request processor for \" << req.type()\n\t\t\t<< std::endl;\n\t\tresp.err( \"unknown request type: '\"+ req.type()\n\t\t +\"'\" );\n\t\treturn;\n\t}\n\n\taction->execute( req, resp );\n\n\tif ( ! protocol->silent() ) {\n\t\tm_queue.push( resp.release() );\n\t}\n}\n\nprotocol_i * request_router_c::find_protocol( int port )\n{\n\tprotocol_iterator it( m_protocol.find( port ) );\n\tif ( it == m_protocol.end() ) {\n\t\tstd::cerr << \"port \" << port << \" has no protocol\\n\";\n\t\t\/\/ maybe should close this connection also?\n\t\treturn NULL;\n\t}\n\treturn it->second;\n}\n\n<commit_msg>fixed the include path for dispatcher now that everything is back in the same directory.<commit_after>\/**\n * Copyright 2008 Matthew Graham\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#include \"dispatcher.h\"\n#include \"action.h\"\n#include \"protocol.h\"\n#include \"request.h\"\n#include \"response.h\"\n#include \"message.h\"\n#include <iostream>\n\n\ndispatcher_c::dispatcher_c( server_queue_i &queue )\n: m_queue( queue )\n, m_protocol()\n{}\n\ndispatcher_c::~dispatcher_c() {}\n\n\nvoid dispatcher_c::add_protocol( short port, protocol_c &protocol )\n{\n\tm_protocol[ port ] = &protocol;\n}\n\n\nbool dispatcher_c::main_loop()\n{\n\tbool success( false );\n\tfor (;;) {\n\t\tstd::auto_ptr< request_message_i > msg( m_queue.pop() );\n\t\tif ( ! msg.get() ) {\n\t\t\t\/\/ sleep or yield or something, then reiterate\n\t\t\tcontinue;\n\t\t}\n\n\t\tdispatch( *req, *resp );\n\t}\n\n\treturn success;\n}\n\nvoid request_router_c::dispatch( const request_c &req, response_c &resp )\n{\n\tbool success( false );\n\tstd::auto_ptr< response_c > resp( new response_c() );\n\n\tprotocol_c *protocol = find_protocol( port );\n\tif ( ! protocol ) {\n\t\t\/\/ can't do anything.\n\t\t\/\/ write to the response and return\n\t\tstd::ostringstream err;\n\t\terr << \"No protocol for port \" << port;\n\t\tresp.err( err.str() );\n\t\treturn;\n\t}\n\n\taction_i *action = protocol->action( req.type() );\n\tif ( ! action ) {\n\t\tstd::cerr << \"no request processor for \" << req.type()\n\t\t\t<< std::endl;\n\t\tresp.err( \"unknown request type: '\"+ req.type()\n\t\t +\"'\" );\n\t\treturn;\n\t}\n\n\taction->execute( req, resp );\n\n\tif ( ! protocol->silent() ) {\n\t\tm_queue.push( resp.release() );\n\t}\n}\n\nprotocol_i * request_router_c::find_protocol( int port )\n{\n\tprotocol_iterator it( m_protocol.find( port ) );\n\tif ( it == m_protocol.end() ) {\n\t\tstd::cerr << \"port \" << port << \" has no protocol\\n\";\n\t\t\/\/ maybe should close this connection also?\n\t\treturn NULL;\n\t}\n\treturn it->second;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <policy\/rbf.h>\n#include <util\/rbf.h>\n\nRBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool)\n{\n AssertLockHeld(pool.cs);\n\n CTxMemPool::setEntries setAncestors;\n\n \/\/ First check the transaction itself.\n if (SignalsOptInRBF(tx)) {\n return RBFTransactionState::REPLACEABLE_BIP125;\n }\n\n \/\/ If this transaction is not in our mempool, then we can't be sure\n \/\/ we will know about all its inputs.\n if (!pool.exists(tx.GetHash())) {\n return RBFTransactionState::UNKNOWN;\n }\n\n \/\/ If all the inputs have nSequence >= maxint-1, it still might be\n \/\/ signaled for RBF if any unconfirmed parents have signaled.\n uint64_t noLimit = std::numeric_limits<uint64_t>::max();\n std::string dummy;\n CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());\n pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);\n\n for (CTxMemPool::txiter it : setAncestors) {\n if (SignalsOptInRBF(it->GetTx())) {\n return RBFTransactionState::REPLACEABLE_BIP125;\n }\n }\n return RBFTransactionState::FINAL;\n}\n\/\/ SYSCOIN\nRBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool, CTxMemPool::setEntries &setAncestors)\n{\n AssertLockHeld(pool.cs);\n\n\n \/\/ First check the transaction itself.\n if (SignalsOptInRBF(tx)) {\n return RBFTransactionState::REPLACEABLE_BIP125;\n }\n\n \/\/ If this transaction is not in our mempool, then we can't be sure\n \/\/ we will know about all its inputs.\n if (!pool.exists(tx.GetHash())) {\n return RBFTransactionState::UNKNOWN;\n }\n\n \/\/ If all the inputs have nSequence >= maxint-1, it still might be\n \/\/ signaled for RBF if any unconfirmed parents have signaled.\n uint64_t noLimit = std::numeric_limits<uint64_t>::max();\n std::string dummy;\n CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());\n pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);\n\n for (CTxMemPool::txiter it : setAncestors) {\n if (SignalsOptInRBF(it->GetTx())) {\n return RBFTransactionState::REPLACEABLE_BIP125;\n }\n }\n return RBFTransactionState::FINAL;\n\nRBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx)\n{\n \/\/ If we don't have a local mempool we can only check the transaction itself.\n return SignalsOptInRBF(tx) ? RBFTransactionState::REPLACEABLE_BIP125 : RBFTransactionState::UNKNOWN;\n}\n<commit_msg>compile<commit_after>\/\/ Copyright (c) 2016-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <policy\/rbf.h>\n#include <util\/rbf.h>\n\nRBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool)\n{\n AssertLockHeld(pool.cs);\n\n CTxMemPool::setEntries setAncestors;\n\n \/\/ First check the transaction itself.\n if (SignalsOptInRBF(tx)) {\n return RBFTransactionState::REPLACEABLE_BIP125;\n }\n\n \/\/ If this transaction is not in our mempool, then we can't be sure\n \/\/ we will know about all its inputs.\n if (!pool.exists(tx.GetHash())) {\n return RBFTransactionState::UNKNOWN;\n }\n\n \/\/ If all the inputs have nSequence >= maxint-1, it still might be\n \/\/ signaled for RBF if any unconfirmed parents have signaled.\n uint64_t noLimit = std::numeric_limits<uint64_t>::max();\n std::string dummy;\n CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());\n pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);\n\n for (CTxMemPool::txiter it : setAncestors) {\n if (SignalsOptInRBF(it->GetTx())) {\n return RBFTransactionState::REPLACEABLE_BIP125;\n }\n }\n return RBFTransactionState::FINAL;\n}\n\/\/ SYSCOIN\nRBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool, CTxMemPool::setEntries &setAncestors)\n{\n AssertLockHeld(pool.cs);\n\n\n \/\/ First check the transaction itself.\n if (SignalsOptInRBF(tx)) {\n return RBFTransactionState::REPLACEABLE_BIP125;\n }\n\n \/\/ If this transaction is not in our mempool, then we can't be sure\n \/\/ we will know about all its inputs.\n if (!pool.exists(tx.GetHash())) {\n return RBFTransactionState::UNKNOWN;\n }\n\n \/\/ If all the inputs have nSequence >= maxint-1, it still might be\n \/\/ signaled for RBF if any unconfirmed parents have signaled.\n uint64_t noLimit = std::numeric_limits<uint64_t>::max();\n std::string dummy;\n CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());\n pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);\n\n for (CTxMemPool::txiter it : setAncestors) {\n if (SignalsOptInRBF(it->GetTx())) {\n return RBFTransactionState::REPLACEABLE_BIP125;\n }\n }\n return RBFTransactionState::FINAL;\n}\nRBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx)\n{\n \/\/ If we don't have a local mempool we can only check the transaction itself.\n return SignalsOptInRBF(tx) ? RBFTransactionState::REPLACEABLE_BIP125 : RBFTransactionState::UNKNOWN;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file primecount.cpp\n\/\/\/ @brief primecount C++ API\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount-internal.hpp>\n#include <primecount.hpp>\n#include <calculator.hpp>\n#include <int128.hpp>\n#include <pmath.hpp>\n\n#include <algorithm>\n#include <ctime>\n#include <cmath>\n#include <limits>\n#include <sstream>\n#include <string>\n#include <stdint.h>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\n#ifdef HAVE_MPI\n\n#include <mpi.h>\n\nnamespace primecount {\n\nint mpi_num_procs()\n{\n int procs;\n MPI_Comm_size(MPI_COMM_WORLD, &procs);\n return procs;\n}\n\nint mpi_proc_id()\n{\n int proc_id;\n MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);\n return proc_id;\n}\n\nint mpi_master_proc_id()\n{\n return 0;\n}\n\nbool is_mpi_master_proc()\n{\n return mpi_proc_id() == mpi_master_proc_id();\n}\n\n} \/\/ namespace\n\n#endif\n\nusing namespace std;\n\nnamespace {\n\n#ifdef _OPENMP\n int threads_ = max(1, omp_get_max_threads());\n#else\n int threads_ = 1;\n#endif\n\nint status_precision_ = -1;\n\ndouble alpha_ = -1;\n\n\/\/ Below 10^7 the Deleglise-Rivat algorithm is slower than LMO\nconst int deleglise_rivat_threshold = 10000000;\n\n}\n\nnamespace primecount {\n\nint64_t pi(int64_t x)\n{\n return pi(x, threads_);\n}\n\nint64_t pi(int64_t x, int threads)\n{\n if (x < deleglise_rivat_threshold)\n return pi_lmo(x, threads);\n else\n return pi_deleglise_rivat(x, threads);\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t pi(int128_t x)\n{\n return pi(x, threads_);\n}\n\nint128_t pi(int128_t x, int threads)\n{\n \/\/ use 64-bit if possible\n if (x <= numeric_limits<int64_t>::max())\n return pi((int64_t) x, threads);\n else\n return pi_deleglise_rivat(x, threads);\n}\n\n#endif\n\n\/\/\/ Alias for the fastest prime counting function in primecount.\n\/\/\/ @param x integer arithmetic expression e.g. \"10^12\".\n\/\/\/ @pre x <= get_max_x().\n\/\/\/\nstring pi(const string& x)\n{\n return pi(x, threads_);\n}\n\n\/\/\/ Alias for the fastest prime counting function in primecount.\n\/\/\/ @param x integer arithmetic expression e.g. \"10^12\".\n\/\/\/ @pre x <= get_max_x().\n\/\/\/\nstring pi(const string& x, int threads)\n{\n maxint_t pi_x = pi(to_maxint(x), threads);\n ostringstream oss;\n oss << pi_x;\n return oss.str();\n}\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint64_t pi_deleglise_rivat(int64_t x)\n{\n return pi_deleglise_rivat(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint64_t pi_deleglise_rivat(int64_t x, int threads)\n{\n return pi_deleglise_rivat_parallel2(x, threads);\n}\n\n#ifdef HAVE_INT128_T\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint128_t pi_deleglise_rivat(int128_t x)\n{\n return pi_deleglise_rivat(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint128_t pi_deleglise_rivat(int128_t x, int threads)\n{\n \/\/ use 64-bit if possible\n if (x <= numeric_limits<int64_t>::max())\n return pi_deleglise_rivat((int64_t) x, threads);\n else\n return pi_deleglise_rivat_parallel3(x, threads);\n}\n\n#endif\n\n\/\/\/ Calculate the number of primes below x using Legendre's formula.\n\/\/\/ Run time: O(x) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_legendre(int64_t x)\n{\n return pi_legendre(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using Lehmer's formula.\n\/\/\/ Run time: O(x\/(log x)^4) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_lehmer(int64_t x)\n{\n return pi_lehmer(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Lagarias-Miller-Odlyzko algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ log x) operations, O(x^(1\/3) * (log x)^2) space.\n\/\/\/\nint64_t pi_lmo(int64_t x)\n{\n return pi_lmo(x, threads_);\n}\n\n\/\/\/ Parallel implementation of the Lagarias-Miller-Odlyzko\n\/\/\/ prime counting algorithm using OpenMP.\n\/\/\/ Run time: O(x^(2\/3) \/ log x) operations, O(x^(1\/3) * (log x)^2) space.\n\/\/\/\nint64_t pi_lmo(int64_t x, int threads)\n{\n return pi_lmo_parallel3(x, threads);\n}\n\n\/\/\/ Calculate the number of primes below x using Meissel's formula.\n\/\/\/ Run time: O(x\/(log x)^3) operations, O(x^(1\/2) \/ log x) space.\n\/\/\/\nint64_t pi_meissel(int64_t x)\n{\n return pi_meissel(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using an optimized \n\/\/\/ segmented sieve of Eratosthenes implementation.\n\/\/\/ Run time: O(x log log x) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_primesieve(int64_t x)\n{\n return pi_primesieve(x, threads_);\n}\n\n\/\/\/ Calculate the nth prime using a combination of the prime\n\/\/\/ counting function and the sieve of Eratosthenes.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t nth_prime(int64_t n)\n{\n return nth_prime(n, threads_);\n}\n\n\/\/\/ Partial sieve function (a.k.a. Legendre-sum).\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible\n\/\/\/ by any of the first a primes.\n\/\/\/\nint64_t phi(int64_t x, int64_t a)\n{\n return phi(x, a, threads_);\n}\n\n\/\/\/ Returns the largest integer that can be used with\n\/\/\/ pi(string x). The return type is a string as max can be a 128-bit\n\/\/\/ integer which is not supported by all compilers.\n\/\/\/\nstring get_max_x(double alpha)\n{\n ostringstream oss;\n\n#ifdef HAVE_INT128_T\n \/\/ primecount is limited by:\n \/\/ z < 2^62, with z = x^(2\/3) \/ alpha\n \/\/ x^(2\/3) \/ alpha < 2^62\n \/\/ x < (2^62 * alpha)^(3\/2)\n\n \/\/ safety buffer: use 61 instead of 62 \n double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 \/ 2.0);\n oss << (int128_t) max_x; \n#else\n unused_param(alpha); \n oss << numeric_limits<int64_t>::max();\n#endif\n\n return oss.str();\n}\n\n\/\/\/ Get the wall time in seconds.\ndouble get_wtime()\n{\n#ifdef _OPENMP\n return omp_get_wtime();\n#else\n return (double) (std::clock() \/ CLOCKS_PER_SEC);\n#endif\n}\n\nint ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)\n{\n thread_threshold = max((int64_t) 1, thread_threshold);\n threads = (int) min((int64_t) threads, sieve_limit \/ thread_threshold);\n threads = max(1, threads);\n return threads;\n}\n\nvoid set_alpha(double alpha)\n{\n alpha_ = alpha;\n}\n\ndouble get_alpha()\n{\n return alpha_;\n}\n\ndouble get_alpha(maxint_t x, int64_t y)\n{\n \/\/ y = x13 * alpha, thus alpha = y \/ x13\n double x13 = (double) iroot<3>(x);\n return (double) y \/ x13;\n}\n\n\/\/\/ Calculate the Lagarias-Miller-Odlyzko alpha tuning factor.\n\/\/\/ alpha = a log(x)^2 + b log(x) + c\n\/\/\/ a, b and c are constants that should be determined empirically.\n\/\/\/ @see ..\/doc\/alpha-factor-tuning.pdf\n\/\/\/\ndouble get_alpha_lmo(maxint_t x)\n{\n double alpha = get_alpha();\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha < 1)\n {\n double a = 0.00156512;\n double b = -0.0261411;\n double c = 0.990948;\n double logx = log((double) x);\n\n alpha = a * pow(logx, 2) + b * logx + c;\n }\n\n return in_between(1, alpha, iroot<6>(x));\n}\n\n\/\/\/ Calculate the Deleglise-Rivat alpha tuning factor.\n\/\/\/ alpha = a log(x)^3 + b log(x)^2 + c log(x) + d\n\/\/\/ a, b, c and d are constants that should be determined empirically.\n\/\/\/ @see ..\/doc\/alpha-tuning-factor.pdf\n\/\/\/\ndouble get_alpha_deleglise_rivat(maxint_t x)\n{\n double alpha = get_alpha();\n double x2 = (double) x;\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha < 1)\n {\n if (x2 <= 1e21)\n {\n double a = 0.000711339;\n double b = -0.0160586;\n double c = 0.123034;\n double d = 0.802942;\n double logx = log(x2);\n\n alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;\n }\n else\n {\n \/\/ Because of CPU cache misses sieving (S2_hard(x) and P2(x))\n \/\/ becomes the main bottleneck above 10^21 . Hence we use a\n \/\/ different alpha formula when x > 10^21 which returns a larger\n \/\/ alpha which reduces sieving but increases S2_easy(x) work.\n double a = 0.00149066;\n double b = -0.0375705;\n double c = 0.282139;\n double d = 0.591972;\n double logx = log(x2);\n\n alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;\n }\n }\n\n return in_between(1, alpha, iroot<6>(x));\n}\n\nvoid set_num_threads(int threads)\n{\n#ifdef _OPENMP\n int threads_ = in_between(1, threads, omp_get_max_threads());\n#else\n unused_param(threads);\n#endif\n}\n\nint get_num_threads()\n{\n return threads_;\n}\n\nvoid set_status_precision(int precision)\n{\n status_precision_ = in_between(0, precision, 5);\n}\n\nint get_status_precision(maxint_t x)\n{\n \/\/ use default precision when no command-line precision provided\n if (status_precision_ < 0)\n {\n if ((double) x >= 1e23)\n return 2;\n if ((double) x >= 1e21)\n return 1;\n }\n\n return (status_precision_ > 0) ? status_precision_ : 0;\n}\n\nmaxint_t to_maxint(const string& expr)\n{\n maxint_t n = calculator::eval<maxint_t>(expr);\n return n;\n}\n\n\/\/\/ Get the primecount version number, in the form “i.j”.\nstring primecount_version()\n{\n return PRIMECOUNT_VERSION;\n}\n\n} \/\/ namespace\n<commit_msg>Fix typo<commit_after>\/\/\/\n\/\/\/ @file primecount.cpp\n\/\/\/ @brief primecount C++ API\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount-internal.hpp>\n#include <primecount.hpp>\n#include <calculator.hpp>\n#include <int128.hpp>\n#include <pmath.hpp>\n\n#include <algorithm>\n#include <ctime>\n#include <cmath>\n#include <limits>\n#include <sstream>\n#include <string>\n#include <stdint.h>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\n#ifdef HAVE_MPI\n\n#include <mpi.h>\n\nnamespace primecount {\n\nint mpi_num_procs()\n{\n int procs;\n MPI_Comm_size(MPI_COMM_WORLD, &procs);\n return procs;\n}\n\nint mpi_proc_id()\n{\n int proc_id;\n MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);\n return proc_id;\n}\n\nint mpi_master_proc_id()\n{\n return 0;\n}\n\nbool is_mpi_master_proc()\n{\n return mpi_proc_id() == mpi_master_proc_id();\n}\n\n} \/\/ namespace\n\n#endif\n\nusing namespace std;\n\nnamespace {\n\n#ifdef _OPENMP\n int threads_ = max(1, omp_get_max_threads());\n#else\n int threads_ = 1;\n#endif\n\nint status_precision_ = -1;\n\ndouble alpha_ = -1;\n\n\/\/ Below 10^7 the Deleglise-Rivat algorithm is slower than LMO\nconst int deleglise_rivat_threshold = 10000000;\n\n}\n\nnamespace primecount {\n\nint64_t pi(int64_t x)\n{\n return pi(x, threads_);\n}\n\nint64_t pi(int64_t x, int threads)\n{\n if (x < deleglise_rivat_threshold)\n return pi_lmo(x, threads);\n else\n return pi_deleglise_rivat(x, threads);\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t pi(int128_t x)\n{\n return pi(x, threads_);\n}\n\nint128_t pi(int128_t x, int threads)\n{\n \/\/ use 64-bit if possible\n if (x <= numeric_limits<int64_t>::max())\n return pi((int64_t) x, threads);\n else\n return pi_deleglise_rivat(x, threads);\n}\n\n#endif\n\n\/\/\/ Alias for the fastest prime counting function in primecount.\n\/\/\/ @param x integer arithmetic expression e.g. \"10^12\".\n\/\/\/ @pre x <= get_max_x().\n\/\/\/\nstring pi(const string& x)\n{\n return pi(x, threads_);\n}\n\n\/\/\/ Alias for the fastest prime counting function in primecount.\n\/\/\/ @param x integer arithmetic expression e.g. \"10^12\".\n\/\/\/ @pre x <= get_max_x().\n\/\/\/\nstring pi(const string& x, int threads)\n{\n maxint_t pi_x = pi(to_maxint(x), threads);\n ostringstream oss;\n oss << pi_x;\n return oss.str();\n}\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint64_t pi_deleglise_rivat(int64_t x)\n{\n return pi_deleglise_rivat(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint64_t pi_deleglise_rivat(int64_t x, int threads)\n{\n return pi_deleglise_rivat_parallel2(x, threads);\n}\n\n#ifdef HAVE_INT128_T\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint128_t pi_deleglise_rivat(int128_t x)\n{\n return pi_deleglise_rivat(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint128_t pi_deleglise_rivat(int128_t x, int threads)\n{\n \/\/ use 64-bit if possible\n if (x <= numeric_limits<int64_t>::max())\n return pi_deleglise_rivat((int64_t) x, threads);\n else\n return pi_deleglise_rivat_parallel3(x, threads);\n}\n\n#endif\n\n\/\/\/ Calculate the number of primes below x using Legendre's formula.\n\/\/\/ Run time: O(x) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_legendre(int64_t x)\n{\n return pi_legendre(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using Lehmer's formula.\n\/\/\/ Run time: O(x\/(log x)^4) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_lehmer(int64_t x)\n{\n return pi_lehmer(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Lagarias-Miller-Odlyzko algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ log x) operations, O(x^(1\/3) * (log x)^2) space.\n\/\/\/\nint64_t pi_lmo(int64_t x)\n{\n return pi_lmo(x, threads_);\n}\n\n\/\/\/ Parallel implementation of the Lagarias-Miller-Odlyzko\n\/\/\/ prime counting algorithm using OpenMP.\n\/\/\/ Run time: O(x^(2\/3) \/ log x) operations, O(x^(1\/3) * (log x)^2) space.\n\/\/\/\nint64_t pi_lmo(int64_t x, int threads)\n{\n return pi_lmo_parallel3(x, threads);\n}\n\n\/\/\/ Calculate the number of primes below x using Meissel's formula.\n\/\/\/ Run time: O(x\/(log x)^3) operations, O(x^(1\/2) \/ log x) space.\n\/\/\/\nint64_t pi_meissel(int64_t x)\n{\n return pi_meissel(x, threads_);\n}\n\n\/\/\/ Calculate the number of primes below x using an optimized \n\/\/\/ segmented sieve of Eratosthenes implementation.\n\/\/\/ Run time: O(x log log x) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_primesieve(int64_t x)\n{\n return pi_primesieve(x, threads_);\n}\n\n\/\/\/ Calculate the nth prime using a combination of the prime\n\/\/\/ counting function and the sieve of Eratosthenes.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t nth_prime(int64_t n)\n{\n return nth_prime(n, threads_);\n}\n\n\/\/\/ Partial sieve function (a.k.a. Legendre-sum).\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible\n\/\/\/ by any of the first a primes.\n\/\/\/\nint64_t phi(int64_t x, int64_t a)\n{\n return phi(x, a, threads_);\n}\n\n\/\/\/ Returns the largest integer that can be used with\n\/\/\/ pi(string x). The return type is a string as max can be a 128-bit\n\/\/\/ integer which is not supported by all compilers.\n\/\/\/\nstring get_max_x(double alpha)\n{\n ostringstream oss;\n\n#ifdef HAVE_INT128_T\n \/\/ primecount is limited by:\n \/\/ z < 2^62, with z = x^(2\/3) \/ alpha\n \/\/ x^(2\/3) \/ alpha < 2^62\n \/\/ x < (2^62 * alpha)^(3\/2)\n\n \/\/ safety buffer: use 61 instead of 62 \n double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 \/ 2.0);\n oss << (int128_t) max_x; \n#else\n unused_param(alpha); \n oss << numeric_limits<int64_t>::max();\n#endif\n\n return oss.str();\n}\n\n\/\/\/ Get the wall time in seconds.\ndouble get_wtime()\n{\n#ifdef _OPENMP\n return omp_get_wtime();\n#else\n return (double) (std::clock() \/ CLOCKS_PER_SEC);\n#endif\n}\n\nint ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)\n{\n thread_threshold = max((int64_t) 1, thread_threshold);\n threads = (int) min((int64_t) threads, sieve_limit \/ thread_threshold);\n threads = max(1, threads);\n return threads;\n}\n\nvoid set_alpha(double alpha)\n{\n alpha_ = alpha;\n}\n\ndouble get_alpha()\n{\n return alpha_;\n}\n\ndouble get_alpha(maxint_t x, int64_t y)\n{\n \/\/ y = x13 * alpha, thus alpha = y \/ x13\n double x13 = (double) iroot<3>(x);\n return (double) y \/ x13;\n}\n\n\/\/\/ Calculate the Lagarias-Miller-Odlyzko alpha tuning factor.\n\/\/\/ alpha = a log(x)^2 + b log(x) + c\n\/\/\/ a, b and c are constants that should be determined empirically.\n\/\/\/ @see ..\/doc\/alpha-factor-tuning.pdf\n\/\/\/\ndouble get_alpha_lmo(maxint_t x)\n{\n double alpha = get_alpha();\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha < 1)\n {\n double a = 0.00156512;\n double b = -0.0261411;\n double c = 0.990948;\n double logx = log((double) x);\n\n alpha = a * pow(logx, 2) + b * logx + c;\n }\n\n return in_between(1, alpha, iroot<6>(x));\n}\n\n\/\/\/ Calculate the Deleglise-Rivat alpha tuning factor.\n\/\/\/ alpha = a log(x)^3 + b log(x)^2 + c log(x) + d\n\/\/\/ a, b, c and d are constants that should be determined empirically.\n\/\/\/ @see ..\/doc\/alpha-tuning-factor.pdf\n\/\/\/\ndouble get_alpha_deleglise_rivat(maxint_t x)\n{\n double alpha = get_alpha();\n double x2 = (double) x;\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha < 1)\n {\n if (x2 <= 1e21)\n {\n double a = 0.000711339;\n double b = -0.0160586;\n double c = 0.123034;\n double d = 0.802942;\n double logx = log(x2);\n\n alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;\n }\n else\n {\n \/\/ Because of CPU cache misses sieving (S2_hard(x) and P2(x))\n \/\/ becomes the main bottleneck above 10^21 . Hence we use a\n \/\/ different alpha formula when x > 10^21 which returns a larger\n \/\/ alpha which reduces sieving but increases S2_easy(x) work.\n double a = 0.00149066;\n double b = -0.0375705;\n double c = 0.282139;\n double d = 0.591972;\n double logx = log(x2);\n\n alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;\n }\n }\n\n return in_between(1, alpha, iroot<6>(x));\n}\n\nvoid set_num_threads(int threads)\n{\n#ifdef _OPENMP\n threads_ = in_between(1, threads, omp_get_max_threads());\n#else\n unused_param(threads);\n#endif\n}\n\nint get_num_threads()\n{\n return threads_;\n}\n\nvoid set_status_precision(int precision)\n{\n status_precision_ = in_between(0, precision, 5);\n}\n\nint get_status_precision(maxint_t x)\n{\n \/\/ use default precision when no command-line precision provided\n if (status_precision_ < 0)\n {\n if ((double) x >= 1e23)\n return 2;\n if ((double) x >= 1e21)\n return 1;\n }\n\n return (status_precision_ > 0) ? status_precision_ : 0;\n}\n\nmaxint_t to_maxint(const string& expr)\n{\n maxint_t n = calculator::eval<maxint_t>(expr);\n return n;\n}\n\n\/\/\/ Get the primecount version number, in the form “i.j”.\nstring primecount_version()\n{\n return PRIMECOUNT_VERSION;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 1999-2016 Vaclav Slavik\n * Copyright (C) 2005 Olivier Sannier\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"edlistctrl.h\"\n\n#include \"hidpi.h\"\n#include \"language.h\"\n#include \"cat_sorting.h\"\n#include \"colorscheme.h\"\n#include \"unicode_helpers.h\"\n#include \"utility.h\"\n\n#include <wx\/wx.h>\n#include <wx\/imaglist.h>\n#include <wx\/artprov.h>\n#include <wx\/dcmemory.h>\n#include <wx\/image.h>\n#include <wx\/wupdlock.h>\n\n#ifdef __WXMSW__\n#include <wx\/headerctrl.h>\n#include <wx\/itemattr.h>\n#include <wx\/msw\/uxtheme.h>\n#include <vssym32.h>\n#endif\n\n#include <algorithm>\n\n\nnamespace\n{\n\nclass SelectionPreserver\n{\npublic:\n SelectionPreserver(PoeditListCtrl *list_) : list(list_), focus(-1)\n {\n if (!list)\n return;\n selection = list->GetSelectedCatalogItemIndexes();\n focus = list->ListItemToCatalogIndex(list->GetCurrentItem());\n }\n\n ~SelectionPreserver()\n {\n if (!list)\n return;\n if (!selection.empty())\n list->SetSelectedCatalogItemIndexes(selection);\n if (focus != -1)\n {\n auto item = list->CatalogIndexToListItem(focus);\n list->EnsureVisible(item);\n list->SetCurrentItem(item);\n }\n }\n\nprivate:\n PoeditListCtrl *list;\n std::vector<int> selection;\n int focus;\n};\n\n} \/\/ anonymous namespace\n\n\n\nPoeditListCtrl::Model::Model(TextDirection appTextDir, wxVisualAttributes visual)\n : m_sourceTextDir(TextDirection::LTR),\n m_transTextDir(TextDirection::LTR),\n m_appTextDir(appTextDir)\n{\n sortOrder = SortOrder::Default();\n\n \/\/ configure items colors & fonts:\n\n m_clrID = ColorScheme::Get(Color::ItemID, visual);\n m_clrFuzzy = ColorScheme::Get(Color::ItemFuzzy, visual);\n m_clrInvalid = ColorScheme::Get(Color::ItemError, visual);\n\n m_iconPreTranslated = wxArtProvider::GetBitmap(\"poedit-status-automatic\");\n m_iconComment = wxArtProvider::GetBitmap(\"poedit-status-comment\");\n m_iconBookmark = wxArtProvider::GetBitmap(\"poedit-status-bookmark\");\n}\n\n\nvoid PoeditListCtrl::Model::SetCatalog(CatalogPtr catalog)\n{\n m_catalog = catalog;\n\n if (!catalog)\n {\n Reset(0);\n return;\n }\n\n auto srclang = catalog->GetSourceLanguage();\n auto lang = catalog->GetLanguage();\n m_sourceTextDir = srclang.Direction();\n m_transTextDir = lang.Direction();\n\n \/\/ sort catalog items, create indexes mapping\n CreateSortMap();\n\n Reset(catalog->GetCount());\n}\n\n\nvoid PoeditListCtrl::Model::UpdateSort()\n{\n if (!m_catalog)\n return;\n CreateSortMap();\n Reset(m_catalog->GetCount());\n}\n\n\nwxString PoeditListCtrl::Model::GetColumnType(unsigned int col) const\n{\n switch (col)\n {\n case Col_ID:\n return \"string\";\n\n case Col_Icon:\n return \"wxBitmap\";\n\n case Col_Source:\n case Col_Translation:\n return \"string\";\n\n default:\n return \"null\";\n }\n}\n\n\nvoid PoeditListCtrl::Model::GetValueByRow(wxVariant& variant, unsigned row, unsigned col) const\n{\n auto d = Item(row);\n wxCHECK_RET(d, \"invalid row\");\n\n switch (col)\n {\n case Col_ID:\n {\n variant = wxString::Format(\"%d\", d->GetId());\n break;\n }\n\n case Col_Icon:\n {\n if (d->GetBookmark() != NO_BOOKMARK)\n variant << m_iconBookmark;\n else if (d->HasComment() || d->HasExtractedComments())\n variant << m_iconComment;\n else if (d->IsPreTranslated())\n variant << m_iconPreTranslated;\n else\n variant = wxNullVariant;\n break;\n }\n\n case Col_Source:\n {\n wxString orig;\n#if wxCHECK_VERSION(3,1,1)\n if (d->HasContext())\n {\n \/\/ Work around a problem with GTK+'s coloring of markup that begins with colorizing <span>:\n #ifdef __WXGTK__\n #define MARKUP(x) L\"\\u200B\" L##x\n #else\n #define MARKUP(x) x\n #endif\n orig.Printf(MARKUP(\"<span style=\\\"italic\\\" color=\\\"#2B6F16\\\">[%s]<\/span> %s\"),\n EscapeMarkup(d->GetContext()), EscapeMarkup(d->GetString()));\n }\n else\n {\n orig = EscapeMarkup(d->GetString());\n }\n#else \/\/ wx 3.0\n if (d->HasContext())\n orig.Printf(\"[%s] %s\", d->GetContext(), d->GetString());\n else\n orig = d->GetString();\n#endif\n\n \/\/ FIXME: use syntax highlighting or typographic marks\n orig.Replace(\"\\n\", \" \");\n\n \/\/ Add RTL Unicode mark to render bidi texts correctly\n if (m_appTextDir != m_sourceTextDir)\n variant = bidi::mark_direction(orig, m_sourceTextDir);\n else\n variant = orig;\n break;\n }\n\n case Col_Translation:\n {\n auto trans = d->GetTranslation();\n\n \/\/ FIXME: use syntax highlighting or typographic marks\n trans.Replace(\"\\n\", \" \");\n\n \/\/ Add RTL Unicode mark to render bidi texts correctly\n if (m_appTextDir != m_transTextDir)\n variant = bidi::mark_direction(trans, m_transTextDir);\n else\n variant = trans;\n break;\n }\n\n default:\n variant.Clear();\n break;\n };\n}\n\nbool PoeditListCtrl::Model::SetValueByRow(const wxVariant&, unsigned, unsigned)\n{\n wxFAIL_MSG(\"setting values in dataview not implemented\");\n return false;\n}\n\nbool PoeditListCtrl::Model::GetAttrByRow(unsigned row, unsigned col, wxDataViewItemAttr& attr) const\n{\n if (!m_catalog)\n return false;\n\n switch (col)\n {\n case Col_ID:\n {\n attr.SetColour(m_clrID);\n return true;\n }\n\n case Col_Source:\n case Col_Translation:\n {\n auto d = Item(row);\n if (d->GetValidity() == CatalogItem::Val_Invalid)\n {\n attr.SetColour(m_clrInvalid);\n return true;\n }\n else if (d->IsFuzzy())\n {\n attr.SetColour(m_clrFuzzy);\n return true;\n }\n else\n {\n return false;\n }\n }\n\n default:\n return false;\n }\n}\n\n\nvoid PoeditListCtrl::Model::CreateSortMap()\n{\n \/\/ FIXME: Use native wxDataViewCtrl sorting instead\n\n int count = (int)m_catalog->GetCount();\n\n m_mapListToCatalog.resize(count);\n m_mapCatalogToList.resize(count);\n\n \/\/ First create identity mapping for the sort order.\n for ( int i = 0; i < count; i++ )\n m_mapListToCatalog[i] = i;\n\n \/\/ m_mapListToCatalog will hold our desired sort order. Sort it in place\n \/\/ now, using the desired sort criteria.\n CatalogItemsComparator comparator(*m_catalog, sortOrder);\n std::sort\n (\n m_mapListToCatalog.begin(),\n m_mapListToCatalog.end(),\n std::ref(comparator)\n );\n\n \/\/ Finally, construct m_mapCatalogToList to be the inverse mapping to\n \/\/ m_mapListToCatalog.\n for ( int i = 0; i < count; i++ )\n m_mapCatalogToList[m_mapListToCatalog[i]] = i;\n}\n\n\n\n\nPoeditListCtrl::PoeditListCtrl(wxWindow *parent, wxWindowID id, bool dispIDs)\n : wxDataViewCtrl(parent, id, wxDefaultPosition, wxDefaultSize, wxDV_MULTIPLE | wxDV_ROW_LINES | wxNO_BORDER, wxDefaultValidator, \"translations list\")\n{\n m_displayIDs = dispIDs;\n\n m_appTextDir = (wxTheApp->GetLayoutDirection() == wxLayout_RightToLeft) ? TextDirection::RTL : TextDirection::LTR;\n\n m_model.reset(new Model(m_appTextDir, GetDefaultAttributes()));\n AssociateModel(m_model.get());\n\n CreateColumns();\n\n UpdateHeaderAttrs();\n\n Bind(wxEVT_SIZE, &PoeditListCtrl::OnSize, this);\n}\n\nPoeditListCtrl::~PoeditListCtrl()\n{\n sortOrder().Save();\n}\n\nvoid PoeditListCtrl::UpdateHeaderAttrs()\n{\n#ifdef __WXMSW__\n \/\/ Setup custom header font & color on Windows 10, where the default look is a bit odd\n if (IsWindows10OrGreater())\n {\n \/\/ Use the same text color as Explorer's headers use\n const wxUxThemeEngine* theme = wxUxThemeEngine::GetIfActive();\n if (theme)\n {\n wxUxThemeHandle hTheme(this->GetParent(), L\"ItemsView::Header\");\n COLORREF clr;\n HRESULT hr = theme->GetThemeColor(hTheme, HP_HEADERITEM, 0, TMT_TEXTCOLOR, &clr);\n if (SUCCEEDED(hr))\n {\n wxItemAttr headerAttr;\n headerAttr.SetTextColour(wxRGBToColour(clr));\n SetHeaderAttr(headerAttr);\n }\n }\n\n \/\/ Standard header has smaller height than Explorer's and it isn't\n \/\/ separated from the content well -- especially in HiDPI modes.\n \/\/ Match Explorer's header size too:\n int headerHeight = HiDPIScalingFactor() > 1.0 ? PX(26) : PX(25);\n GenericGetHeader()->SetMinSize(wxSize(-1, headerHeight));\n }\n#endif \/\/ __WXMSW__\n}\n\nvoid PoeditListCtrl::SetCustomFont(wxFont font_)\n{\n wxFont font(font_);\n\n if ( !font.IsOk() )\n font = GetDefaultAttributes().font;\n\n SetFont(font);\n\n UpdateHeaderAttrs();\n CreateColumns();\n}\n\nvoid PoeditListCtrl::SetDisplayLines(bool dl)\n{\n m_displayIDs = dl;\n CreateColumns();\n}\n\nvoid PoeditListCtrl::CreateColumns()\n{\n if (GetColumnCount() > 0)\n ClearColumns();\n\n m_colID = m_colIcon = m_colSource = m_colTrans = nullptr;\n\n Language srclang, lang;\n if (m_catalog)\n {\n srclang = m_catalog->GetSourceLanguage();\n lang = m_catalog->GetLanguage();\n }\n\n auto isRTL = lang.IsRTL();\n#ifdef __WXMSW__\n \/\/ a quirk of wx API: if the current locale is RTL, the meaning of L and R is reversed\n if (m_appTextDir == TextDirection::RTL)\n isRTL = !isRTL;\n#endif\n\n m_colIcon = AppendBitmapColumn(L\"∙\", Model::Col_Icon, wxDATAVIEW_CELL_INERT, wxCOL_WIDTH_AUTOSIZE, wxALIGN_CENTER, 0);\n\n wxString sourceTitle = srclang.IsValid()\n ? wxString::Format(_(L\"Source text — %s\"), srclang.DisplayName())\n : _(\"Source text\");\n auto sourceRenderer = new wxDataViewTextRenderer();\n sourceRenderer->EnableEllipsize(wxELLIPSIZE_END);\n#if wxCHECK_VERSION(3,1,1)\n sourceRenderer->EnableMarkup();\n#endif\n m_colSource = new wxDataViewColumn(sourceTitle, sourceRenderer, Model::Col_Source, wxCOL_WIDTH_DEFAULT, wxALIGN_LEFT, 0);\n AppendColumn(m_colSource);\n\n if (m_model->m_catalog && m_model->m_catalog->HasCapability(Catalog::Cap::Translations))\n {\n wxString langname = lang.IsValid() ? lang.DisplayName() : _(\"unknown language\");;\n wxString transTitle = wxString::Format(_(L\"Translation — %s\"), langname);\n auto transRenderer = new wxDataViewTextRenderer();\n transRenderer->EnableEllipsize(wxELLIPSIZE_END);\n m_colTrans = new wxDataViewColumn(transTitle, transRenderer, Model::Col_Translation, wxCOL_WIDTH_DEFAULT, isRTL ? wxALIGN_RIGHT : wxALIGN_LEFT, 0);\n AppendColumn(m_colTrans);\n }\n\n if (m_displayIDs)\n {\n m_colID = AppendTextColumn(_(\"ID\"), Model::Col_ID, wxDATAVIEW_CELL_INERT, wxCOL_WIDTH_AUTOSIZE, wxALIGN_RIGHT, 0);\n }\n\n \/\/ wxDVC insists on having an expander column, but we really don't want one:\n auto fake = AppendTextColumn(\"\", Model::Col_ID);\n fake->SetHidden(true);\n SetExpanderColumn(fake);\n\n#ifdef __WXMSW__\n if (m_appTextDir == TextDirection::RTL)\n m_colSource->SetAlignment(wxALIGN_RIGHT);\n#endif\n\n SizeColumns();\n\n#ifdef __WXGTK__\n \/\/ wxGTK has delayed sizing computation, apparently\n CallAfter([=]{ SizeColumns(); });\n#endif\n}\n\nvoid PoeditListCtrl::SizeColumns()\n{\n int w = GetClientSize().x;\n\n#if defined(__WXOSX__)\n w -= (GetColumnCount() - 1) * 3;\n#elif defined(__WXGTK__)\n w -= 2;\n#endif\n\n if (m_colIcon)\n w -= m_colIcon->GetWidth();\n\n if (m_colID)\n w -= m_colID->GetWidth();\n\n if (m_colTrans)\n {\n m_colSource->SetWidth(w \/ 2);\n m_colTrans->SetWidth(w - w \/ 2);\n }\n else\n {\n m_colSource->SetWidth(w);\n }\n}\n\n\nvoid PoeditListCtrl::CatalogChanged(const CatalogPtr& catalog)\n{\n wxWindowUpdateLocker no_updates(this);\n\n const int oldCount = m_catalog ? m_catalog->GetCount() : 0;\n const int newCount = catalog ? catalog->GetCount() : 0;\n const bool isSameCatalog = (catalog == m_catalog);\n const bool sizeOrCatalogChanged = !isSameCatalog || (oldCount != newCount);\n\n SelectionPreserver preserve(!sizeOrCatalogChanged ? this : nullptr);\n\n \/\/ now read the new catalog:\n m_catalog = catalog;\n m_model->SetCatalog(catalog);\n\n if (!m_catalog)\n return;\n\n CreateColumns();\n\n if (sizeOrCatalogChanged && GetItemCount() > 0)\n CallAfter([=]{ SelectAndFocus(0); });\n}\n\n\nvoid PoeditListCtrl::Sort()\n{\n if (!m_catalog)\n return;\n\n SelectionPreserver preserve(this);\n m_model->UpdateSort();\n}\n\n\nvoid PoeditListCtrl::OnSize(wxSizeEvent& event)\n{\n wxWindowUpdateLocker lock(this);\n\n SizeColumns();\n event.Skip();\n}\n<commit_msg>Fix columns sizing under GTK+<commit_after>\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 1999-2016 Vaclav Slavik\n * Copyright (C) 2005 Olivier Sannier\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"edlistctrl.h\"\n\n#include \"hidpi.h\"\n#include \"language.h\"\n#include \"cat_sorting.h\"\n#include \"colorscheme.h\"\n#include \"unicode_helpers.h\"\n#include \"utility.h\"\n\n#include <wx\/wx.h>\n#include <wx\/imaglist.h>\n#include <wx\/artprov.h>\n#include <wx\/dcmemory.h>\n#include <wx\/image.h>\n#include <wx\/wupdlock.h>\n\n#ifdef __WXMSW__\n#include <wx\/headerctrl.h>\n#include <wx\/itemattr.h>\n#include <wx\/msw\/uxtheme.h>\n#include <vssym32.h>\n#endif\n\n#include <algorithm>\n\n\nnamespace\n{\n\nclass SelectionPreserver\n{\npublic:\n SelectionPreserver(PoeditListCtrl *list_) : list(list_), focus(-1)\n {\n if (!list)\n return;\n selection = list->GetSelectedCatalogItemIndexes();\n focus = list->ListItemToCatalogIndex(list->GetCurrentItem());\n }\n\n ~SelectionPreserver()\n {\n if (!list)\n return;\n if (!selection.empty())\n list->SetSelectedCatalogItemIndexes(selection);\n if (focus != -1)\n {\n auto item = list->CatalogIndexToListItem(focus);\n list->EnsureVisible(item);\n list->SetCurrentItem(item);\n }\n }\n\nprivate:\n PoeditListCtrl *list;\n std::vector<int> selection;\n int focus;\n};\n\n} \/\/ anonymous namespace\n\n\n\nPoeditListCtrl::Model::Model(TextDirection appTextDir, wxVisualAttributes visual)\n : m_sourceTextDir(TextDirection::LTR),\n m_transTextDir(TextDirection::LTR),\n m_appTextDir(appTextDir)\n{\n sortOrder = SortOrder::Default();\n\n \/\/ configure items colors & fonts:\n\n m_clrID = ColorScheme::Get(Color::ItemID, visual);\n m_clrFuzzy = ColorScheme::Get(Color::ItemFuzzy, visual);\n m_clrInvalid = ColorScheme::Get(Color::ItemError, visual);\n\n m_iconPreTranslated = wxArtProvider::GetBitmap(\"poedit-status-automatic\");\n m_iconComment = wxArtProvider::GetBitmap(\"poedit-status-comment\");\n m_iconBookmark = wxArtProvider::GetBitmap(\"poedit-status-bookmark\");\n}\n\n\nvoid PoeditListCtrl::Model::SetCatalog(CatalogPtr catalog)\n{\n m_catalog = catalog;\n\n if (!catalog)\n {\n Reset(0);\n return;\n }\n\n auto srclang = catalog->GetSourceLanguage();\n auto lang = catalog->GetLanguage();\n m_sourceTextDir = srclang.Direction();\n m_transTextDir = lang.Direction();\n\n \/\/ sort catalog items, create indexes mapping\n CreateSortMap();\n\n Reset(catalog->GetCount());\n}\n\n\nvoid PoeditListCtrl::Model::UpdateSort()\n{\n if (!m_catalog)\n return;\n CreateSortMap();\n Reset(m_catalog->GetCount());\n}\n\n\nwxString PoeditListCtrl::Model::GetColumnType(unsigned int col) const\n{\n switch (col)\n {\n case Col_ID:\n return \"string\";\n\n case Col_Icon:\n return \"wxBitmap\";\n\n case Col_Source:\n case Col_Translation:\n return \"string\";\n\n default:\n return \"null\";\n }\n}\n\n\nvoid PoeditListCtrl::Model::GetValueByRow(wxVariant& variant, unsigned row, unsigned col) const\n{\n auto d = Item(row);\n wxCHECK_RET(d, \"invalid row\");\n\n switch (col)\n {\n case Col_ID:\n {\n variant = wxString::Format(\"%d\", d->GetId());\n break;\n }\n\n case Col_Icon:\n {\n if (d->GetBookmark() != NO_BOOKMARK)\n variant << m_iconBookmark;\n else if (d->HasComment() || d->HasExtractedComments())\n variant << m_iconComment;\n else if (d->IsPreTranslated())\n variant << m_iconPreTranslated;\n else\n variant = wxNullVariant;\n break;\n }\n\n case Col_Source:\n {\n wxString orig;\n#if wxCHECK_VERSION(3,1,1)\n if (d->HasContext())\n {\n \/\/ Work around a problem with GTK+'s coloring of markup that begins with colorizing <span>:\n #ifdef __WXGTK__\n #define MARKUP(x) L\"\\u200B\" L##x\n #else\n #define MARKUP(x) x\n #endif\n orig.Printf(MARKUP(\"<span style=\\\"italic\\\" color=\\\"#2B6F16\\\">[%s]<\/span> %s\"),\n EscapeMarkup(d->GetContext()), EscapeMarkup(d->GetString()));\n }\n else\n {\n orig = EscapeMarkup(d->GetString());\n }\n#else \/\/ wx 3.0\n if (d->HasContext())\n orig.Printf(\"[%s] %s\", d->GetContext(), d->GetString());\n else\n orig = d->GetString();\n#endif\n\n \/\/ FIXME: use syntax highlighting or typographic marks\n orig.Replace(\"\\n\", \" \");\n\n \/\/ Add RTL Unicode mark to render bidi texts correctly\n if (m_appTextDir != m_sourceTextDir)\n variant = bidi::mark_direction(orig, m_sourceTextDir);\n else\n variant = orig;\n break;\n }\n\n case Col_Translation:\n {\n auto trans = d->GetTranslation();\n\n \/\/ FIXME: use syntax highlighting or typographic marks\n trans.Replace(\"\\n\", \" \");\n\n \/\/ Add RTL Unicode mark to render bidi texts correctly\n if (m_appTextDir != m_transTextDir)\n variant = bidi::mark_direction(trans, m_transTextDir);\n else\n variant = trans;\n break;\n }\n\n default:\n variant.Clear();\n break;\n };\n}\n\nbool PoeditListCtrl::Model::SetValueByRow(const wxVariant&, unsigned, unsigned)\n{\n wxFAIL_MSG(\"setting values in dataview not implemented\");\n return false;\n}\n\nbool PoeditListCtrl::Model::GetAttrByRow(unsigned row, unsigned col, wxDataViewItemAttr& attr) const\n{\n if (!m_catalog)\n return false;\n\n switch (col)\n {\n case Col_ID:\n {\n attr.SetColour(m_clrID);\n return true;\n }\n\n case Col_Source:\n case Col_Translation:\n {\n auto d = Item(row);\n if (d->GetValidity() == CatalogItem::Val_Invalid)\n {\n attr.SetColour(m_clrInvalid);\n return true;\n }\n else if (d->IsFuzzy())\n {\n attr.SetColour(m_clrFuzzy);\n return true;\n }\n else\n {\n return false;\n }\n }\n\n default:\n return false;\n }\n}\n\n\nvoid PoeditListCtrl::Model::CreateSortMap()\n{\n \/\/ FIXME: Use native wxDataViewCtrl sorting instead\n\n int count = (int)m_catalog->GetCount();\n\n m_mapListToCatalog.resize(count);\n m_mapCatalogToList.resize(count);\n\n \/\/ First create identity mapping for the sort order.\n for ( int i = 0; i < count; i++ )\n m_mapListToCatalog[i] = i;\n\n \/\/ m_mapListToCatalog will hold our desired sort order. Sort it in place\n \/\/ now, using the desired sort criteria.\n CatalogItemsComparator comparator(*m_catalog, sortOrder);\n std::sort\n (\n m_mapListToCatalog.begin(),\n m_mapListToCatalog.end(),\n std::ref(comparator)\n );\n\n \/\/ Finally, construct m_mapCatalogToList to be the inverse mapping to\n \/\/ m_mapListToCatalog.\n for ( int i = 0; i < count; i++ )\n m_mapCatalogToList[m_mapListToCatalog[i]] = i;\n}\n\n\n\n\nPoeditListCtrl::PoeditListCtrl(wxWindow *parent, wxWindowID id, bool dispIDs)\n : wxDataViewCtrl(parent, id, wxDefaultPosition, wxDefaultSize, wxDV_MULTIPLE | wxDV_ROW_LINES | wxNO_BORDER, wxDefaultValidator, \"translations list\")\n{\n m_displayIDs = dispIDs;\n\n m_appTextDir = (wxTheApp->GetLayoutDirection() == wxLayout_RightToLeft) ? TextDirection::RTL : TextDirection::LTR;\n\n m_model.reset(new Model(m_appTextDir, GetDefaultAttributes()));\n AssociateModel(m_model.get());\n\n CreateColumns();\n\n UpdateHeaderAttrs();\n\n Bind(wxEVT_SIZE, &PoeditListCtrl::OnSize, this);\n}\n\nPoeditListCtrl::~PoeditListCtrl()\n{\n sortOrder().Save();\n}\n\nvoid PoeditListCtrl::UpdateHeaderAttrs()\n{\n#ifdef __WXMSW__\n \/\/ Setup custom header font & color on Windows 10, where the default look is a bit odd\n if (IsWindows10OrGreater())\n {\n \/\/ Use the same text color as Explorer's headers use\n const wxUxThemeEngine* theme = wxUxThemeEngine::GetIfActive();\n if (theme)\n {\n wxUxThemeHandle hTheme(this->GetParent(), L\"ItemsView::Header\");\n COLORREF clr;\n HRESULT hr = theme->GetThemeColor(hTheme, HP_HEADERITEM, 0, TMT_TEXTCOLOR, &clr);\n if (SUCCEEDED(hr))\n {\n wxItemAttr headerAttr;\n headerAttr.SetTextColour(wxRGBToColour(clr));\n SetHeaderAttr(headerAttr);\n }\n }\n\n \/\/ Standard header has smaller height than Explorer's and it isn't\n \/\/ separated from the content well -- especially in HiDPI modes.\n \/\/ Match Explorer's header size too:\n int headerHeight = HiDPIScalingFactor() > 1.0 ? PX(26) : PX(25);\n GenericGetHeader()->SetMinSize(wxSize(-1, headerHeight));\n }\n#endif \/\/ __WXMSW__\n}\n\nvoid PoeditListCtrl::SetCustomFont(wxFont font_)\n{\n wxFont font(font_);\n\n if ( !font.IsOk() )\n font = GetDefaultAttributes().font;\n\n SetFont(font);\n\n UpdateHeaderAttrs();\n CreateColumns();\n}\n\nvoid PoeditListCtrl::SetDisplayLines(bool dl)\n{\n m_displayIDs = dl;\n CreateColumns();\n}\n\nvoid PoeditListCtrl::CreateColumns()\n{\n if (GetColumnCount() > 0)\n ClearColumns();\n\n m_colID = m_colIcon = m_colSource = m_colTrans = nullptr;\n\n Language srclang, lang;\n if (m_catalog)\n {\n srclang = m_catalog->GetSourceLanguage();\n lang = m_catalog->GetLanguage();\n }\n\n auto isRTL = lang.IsRTL();\n#ifdef __WXMSW__\n \/\/ a quirk of wx API: if the current locale is RTL, the meaning of L and R is reversed\n if (m_appTextDir == TextDirection::RTL)\n isRTL = !isRTL;\n#endif\n\n m_colIcon = AppendBitmapColumn(L\"∙\", Model::Col_Icon, wxDATAVIEW_CELL_INERT, wxCOL_WIDTH_AUTOSIZE, wxALIGN_CENTER, 0);\n\n wxString sourceTitle = srclang.IsValid()\n ? wxString::Format(_(L\"Source text — %s\"), srclang.DisplayName())\n : _(\"Source text\");\n auto sourceRenderer = new wxDataViewTextRenderer();\n sourceRenderer->EnableEllipsize(wxELLIPSIZE_END);\n#if wxCHECK_VERSION(3,1,1)\n sourceRenderer->EnableMarkup();\n#endif\n m_colSource = new wxDataViewColumn(sourceTitle, sourceRenderer, Model::Col_Source, wxCOL_WIDTH_DEFAULT, wxALIGN_LEFT, 0);\n AppendColumn(m_colSource);\n\n if (m_model->m_catalog && m_model->m_catalog->HasCapability(Catalog::Cap::Translations))\n {\n wxString langname = lang.IsValid() ? lang.DisplayName() : _(\"unknown language\");;\n wxString transTitle = wxString::Format(_(L\"Translation — %s\"), langname);\n auto transRenderer = new wxDataViewTextRenderer();\n transRenderer->EnableEllipsize(wxELLIPSIZE_END);\n m_colTrans = new wxDataViewColumn(transTitle, transRenderer, Model::Col_Translation, wxCOL_WIDTH_DEFAULT, isRTL ? wxALIGN_RIGHT : wxALIGN_LEFT, 0);\n AppendColumn(m_colTrans);\n }\n\n if (m_displayIDs)\n {\n m_colID = AppendTextColumn(_(\"ID\"), Model::Col_ID, wxDATAVIEW_CELL_INERT, wxCOL_WIDTH_AUTOSIZE, wxALIGN_RIGHT, 0);\n }\n\n \/\/ wxDVC insists on having an expander column, but we really don't want one:\n auto fake = AppendTextColumn(\"\", Model::Col_ID);\n fake->SetHidden(true);\n SetExpanderColumn(fake);\n\n#ifdef __WXMSW__\n if (m_appTextDir == TextDirection::RTL)\n m_colSource->SetAlignment(wxALIGN_RIGHT);\n#endif\n\n SizeColumns();\n\n#ifdef __WXGTK__\n \/\/ wxGTK has delayed sizing computation, apparently\n CallAfter([=]{ SizeColumns(); });\n#endif\n}\n\nvoid PoeditListCtrl::SizeColumns()\n{\n int w = GetClientSize().x;\n\n#if defined(__WXOSX__)\n w -= (GetColumnCount() - 1) * 3;\n#elif defined(__WXGTK__)\n w -= 2;\n#endif\n\n if (m_colIcon)\n w -= m_colIcon->GetWidth();\n\n if (m_colID)\n {\n w -= m_colID->GetWidth();\n#ifdef __WXGTK__\n w += 2;\n#endif\n }\n\n if (m_colTrans)\n {\n m_colSource->SetWidth(w \/ 2);\n m_colTrans->SetWidth(w - w \/ 2);\n }\n else\n {\n m_colSource->SetWidth(w);\n }\n}\n\n\nvoid PoeditListCtrl::CatalogChanged(const CatalogPtr& catalog)\n{\n wxWindowUpdateLocker no_updates(this);\n\n const int oldCount = m_catalog ? m_catalog->GetCount() : 0;\n const int newCount = catalog ? catalog->GetCount() : 0;\n const bool isSameCatalog = (catalog == m_catalog);\n const bool sizeOrCatalogChanged = !isSameCatalog || (oldCount != newCount);\n\n SelectionPreserver preserve(!sizeOrCatalogChanged ? this : nullptr);\n\n \/\/ now read the new catalog:\n m_catalog = catalog;\n m_model->SetCatalog(catalog);\n\n if (!m_catalog)\n return;\n\n CreateColumns();\n\n if (sizeOrCatalogChanged && GetItemCount() > 0)\n CallAfter([=]{ SelectAndFocus(0); });\n}\n\n\nvoid PoeditListCtrl::Sort()\n{\n if (!m_catalog)\n return;\n\n SelectionPreserver preserve(this);\n m_model->UpdateSort();\n}\n\n\nvoid PoeditListCtrl::OnSize(wxSizeEvent& event)\n{\n wxWindowUpdateLocker lock(this);\n\n SizeColumns();\n event.Skip();\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/detail\/memory\/unique_ptr.hpp>\n#include <agency\/cuda\/memory\/allocator.hpp>\n#include <stdexcept>\n#include <cassert>\n#include <utility>\n#include <type_traits>\n#include <memory>\n\n\nnamespace agency\n{\nnamespace detail\n{\n\n\nclass bad_function_call : public std::exception\n{\n public:\n virtual const char* what() const noexcept\n {\n return \"bad_function_call: unique_function has no target\";\n }\n};\n\n\nnamespace unique_function_detail\n{\n\n\n__AGENCY_ANNOTATION\ninline void throw_bad_function_call()\n{\n#ifdef __CUDA_ARCH__\n printf(\"bad_function_call: unique_function has no target\\n\");\n assert(0);\n#else\n throw bad_function_call();\n#endif\n}\n\n\n} \/\/ end unique_function_detail\n\n\ntemplate<class>\nclass unique_function;\n\ntemplate<class Result, class... Args>\nclass unique_function<Result(Args...)>\n{\n public:\n using result_type = Result;\n\n __AGENCY_ANNOTATION\n unique_function() = default;\n\n __AGENCY_ANNOTATION\n unique_function(std::nullptr_t)\n : f_ptr_(nullptr)\n {}\n\n __AGENCY_ANNOTATION\n unique_function(unique_function&& other) = default;\n\n template<class Function>\n __AGENCY_ANNOTATION\n unique_function(Function&& f)\n : unique_function(std::allocator_arg, default_allocator<typename std::decay<Function>::type>{}, std::forward<Function>(f))\n {}\n\n template<class Alloc>\n __AGENCY_ANNOTATION\n unique_function(std::allocator_arg_t, const Alloc& alloc, std::nullptr_t)\n : unique_function(nullptr)\n {}\n\n template<class Alloc>\n __AGENCY_ANNOTATION\n unique_function(std::allocator_arg_t, const Alloc& alloc)\n : unique_function(std::allocator_arg, alloc, nullptr)\n {}\n\n template<class Alloc>\n __AGENCY_ANNOTATION\n unique_function(std::allocator_arg_t, const Alloc& alloc, unique_function&& other)\n : f_ptr_(std::move(other.f_ptr_))\n {}\n\n template<class Alloc, class Function>\n __AGENCY_ANNOTATION\n unique_function(std::allocator_arg_t, const Alloc& alloc, Function&& f)\n : f_ptr_(allocate_function_pointer(alloc, std::forward<Function>(f)))\n {}\n\n __AGENCY_ANNOTATION\n unique_function& operator=(unique_function&& other) = default;\n\n __AGENCY_ANNOTATION\n Result operator()(Args... args) const\n {\n if(!*this)\n {\n unique_function_detail::throw_bad_function_call();\n }\n\n return (*f_ptr_)(args...);\n }\n\n __AGENCY_ANNOTATION\n operator bool () const\n {\n return f_ptr_;\n }\n\n private:\n \/\/ this is the abstract base class for a type\n \/\/ which is both\n \/\/ 1. callable like a function and\n \/\/ 2. deallocates itself inside its destructor\n struct callable_self_deallocator_base\n {\n using self_deallocate_function_type = void(*)(callable_self_deallocator_base*);\n\n self_deallocate_function_type self_deallocate_function;\n\n template<class Function>\n __AGENCY_ANNOTATION\n callable_self_deallocator_base(Function callback)\n : self_deallocate_function(callback)\n {}\n\n __AGENCY_ANNOTATION\n virtual ~callable_self_deallocator_base()\n {\n self_deallocate_function(this);\n }\n\n __AGENCY_ANNOTATION\n virtual Result operator()(Args... args) const = 0;\n };\n\n template<class Function, class Alloc>\n struct callable : callable_self_deallocator_base\n {\n using super_t = callable_self_deallocator_base;\n using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<callable>;\n\n mutable Function f_;\n\n template<class OtherFunction,\n class = typename std::enable_if<\n std::is_constructible<Function,OtherFunction&&>::value\n >::type>\n __AGENCY_ANNOTATION\n callable(const Alloc& alloc, OtherFunction&& f)\n : super_t(deallocate),\n f_(std::forward<OtherFunction>(f))\n {}\n\n __AGENCY_ANNOTATION\n virtual Result operator()(Args... args) const\n {\n return f_(args...);\n }\n\n __AGENCY_ANNOTATION\n static void deallocate(callable_self_deallocator_base* ptr)\n {\n \/\/ upcast to the right type of pointer\n callable* self = static_cast<callable*>(ptr);\n\n \/\/ XXX seems like creating a new allocator here is cheating\n \/\/ we should use some member allocator, but it's not clear where to put it\n allocator_type alloc_;\n alloc_.deallocate(self, 1);\n }\n };\n\n \/\/ this deleter calls the destructor of its argument but does not\n \/\/ deallocate the ptr\n \/\/ T will deallocate itself inside ~T()\n struct self_deallocator_deleter\n {\n template<class T>\n __AGENCY_ANNOTATION\n void operator()(T* ptr) const\n {\n ptr->~T();\n }\n };\n\n using function_pointer = detail::unique_ptr<callable_self_deallocator_base, self_deallocator_deleter>;\n\n template<class Alloc, class Function>\n __AGENCY_ANNOTATION\n static function_pointer allocate_function_pointer(const Alloc& alloc, Function&& f)\n {\n using concrete_function_type = callable<typename std::decay<Function>::type, Alloc>;\n return agency::detail::allocate_unique_with_deleter<concrete_function_type>(alloc, self_deallocator_deleter(), alloc, std::forward<Function>(f));\n }\n\n template<class T>\n struct default_allocator\n {\n using value_type = T;\n\n __AGENCY_ANNOTATION\n default_allocator() = default;\n\n __AGENCY_ANNOTATION\n default_allocator(const default_allocator&) = default;\n\n template<class U>\n __AGENCY_ANNOTATION\n default_allocator(const default_allocator<U>&) {}\n\n \/\/ XXX we have to implement this member function superfluously because\n \/\/ agency::detail::allocate_unique calls it directly instead of using std::allocator_traits\n template<class U, class... OtherArgs>\n __AGENCY_ANNOTATION\n void construct(U* ptr, OtherArgs&&... args)\n {\n ::new(ptr) U(std::forward<OtherArgs>(args)...);\n }\n\n __AGENCY_ANNOTATION\n value_type* allocate(size_t n)\n {\n#ifdef __CUDA_ARCH__\n agency::cuda::detail::allocator<T> alloc;\n#else\n std::allocator<T> alloc;\n#endif\n return alloc.allocate(n);\n }\n\n __AGENCY_ANNOTATION\n void deallocate(value_type* ptr, std::size_t n)\n {\n#ifdef __CUDA_ARCH__\n agency::cuda::detail::allocator<value_type> alloc;\n#else\n std::allocator<value_type> alloc;\n#endif\n alloc.deallocate(ptr, n);\n }\n };\n\n\n function_pointer f_ptr_; \n};\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<commit_msg>Eliminate dependencies on the cuda-specific headers from unique_function<commit_after>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/detail\/memory\/unique_ptr.hpp>\n#include <stdexcept>\n#include <cassert>\n#include <utility>\n#include <type_traits>\n#include <memory>\n\n\nnamespace agency\n{\nnamespace detail\n{\n\n\nclass bad_function_call : public std::exception\n{\n public:\n virtual const char* what() const noexcept\n {\n return \"bad_function_call: unique_function has no target\";\n }\n};\n\n\nnamespace unique_function_detail\n{\n\n\n__AGENCY_ANNOTATION\ninline void throw_bad_function_call()\n{\n#ifdef __CUDA_ARCH__\n printf(\"bad_function_call: unique_function has no target\\n\");\n assert(0);\n#else\n throw bad_function_call();\n#endif\n}\n\n\n} \/\/ end unique_function_detail\n\n\ntemplate<class>\nclass unique_function;\n\ntemplate<class Result, class... Args>\nclass unique_function<Result(Args...)>\n{\n public:\n using result_type = Result;\n\n __AGENCY_ANNOTATION\n unique_function() = default;\n\n __AGENCY_ANNOTATION\n unique_function(std::nullptr_t)\n : f_ptr_(nullptr)\n {}\n\n __AGENCY_ANNOTATION\n unique_function(unique_function&& other) = default;\n\n template<class Function>\n __AGENCY_ANNOTATION\n unique_function(Function&& f)\n : unique_function(std::allocator_arg, default_allocator<typename std::decay<Function>::type>{}, std::forward<Function>(f))\n {}\n\n template<class Alloc>\n __AGENCY_ANNOTATION\n unique_function(std::allocator_arg_t, const Alloc& alloc, std::nullptr_t)\n : unique_function(nullptr)\n {}\n\n template<class Alloc>\n __AGENCY_ANNOTATION\n unique_function(std::allocator_arg_t, const Alloc& alloc)\n : unique_function(std::allocator_arg, alloc, nullptr)\n {}\n\n template<class Alloc>\n __AGENCY_ANNOTATION\n unique_function(std::allocator_arg_t, const Alloc& alloc, unique_function&& other)\n : f_ptr_(std::move(other.f_ptr_))\n {}\n\n template<class Alloc, class Function>\n __AGENCY_ANNOTATION\n unique_function(std::allocator_arg_t, const Alloc& alloc, Function&& f)\n : f_ptr_(allocate_function_pointer(alloc, std::forward<Function>(f)))\n {}\n\n __AGENCY_ANNOTATION\n unique_function& operator=(unique_function&& other) = default;\n\n __AGENCY_ANNOTATION\n Result operator()(Args... args) const\n {\n if(!*this)\n {\n unique_function_detail::throw_bad_function_call();\n }\n\n return (*f_ptr_)(args...);\n }\n\n __AGENCY_ANNOTATION\n operator bool () const\n {\n return f_ptr_;\n }\n\n private:\n \/\/ this is the abstract base class for a type\n \/\/ which is both\n \/\/ 1. callable like a function and\n \/\/ 2. deallocates itself inside its destructor\n struct callable_self_deallocator_base\n {\n using self_deallocate_function_type = void(*)(callable_self_deallocator_base*);\n\n self_deallocate_function_type self_deallocate_function;\n\n template<class Function>\n __AGENCY_ANNOTATION\n callable_self_deallocator_base(Function callback)\n : self_deallocate_function(callback)\n {}\n\n __AGENCY_ANNOTATION\n virtual ~callable_self_deallocator_base()\n {\n self_deallocate_function(this);\n }\n\n __AGENCY_ANNOTATION\n virtual Result operator()(Args... args) const = 0;\n };\n\n template<class Function, class Alloc>\n struct callable : callable_self_deallocator_base\n {\n using super_t = callable_self_deallocator_base;\n using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<callable>;\n\n mutable Function f_;\n\n template<class OtherFunction,\n class = typename std::enable_if<\n std::is_constructible<Function,OtherFunction&&>::value\n >::type>\n __AGENCY_ANNOTATION\n callable(const Alloc& alloc, OtherFunction&& f)\n : super_t(deallocate),\n f_(std::forward<OtherFunction>(f))\n {}\n\n __AGENCY_ANNOTATION\n virtual Result operator()(Args... args) const\n {\n return f_(args...);\n }\n\n __AGENCY_ANNOTATION\n static void deallocate(callable_self_deallocator_base* ptr)\n {\n \/\/ upcast to the right type of pointer\n callable* self = static_cast<callable*>(ptr);\n\n \/\/ XXX seems like creating a new allocator here is cheating\n \/\/ we should use some member allocator, but it's not clear where to put it\n allocator_type alloc_;\n alloc_.deallocate(self, 1);\n }\n };\n\n \/\/ this deleter calls the destructor of its argument but does not\n \/\/ deallocate the ptr\n \/\/ T will deallocate itself inside ~T()\n struct self_deallocator_deleter\n {\n template<class T>\n __AGENCY_ANNOTATION\n void operator()(T* ptr) const\n {\n ptr->~T();\n }\n };\n\n using function_pointer = detail::unique_ptr<callable_self_deallocator_base, self_deallocator_deleter>;\n\n template<class Alloc, class Function>\n __AGENCY_ANNOTATION\n static function_pointer allocate_function_pointer(const Alloc& alloc, Function&& f)\n {\n using concrete_function_type = callable<typename std::decay<Function>::type, Alloc>;\n return agency::detail::allocate_unique_with_deleter<concrete_function_type>(alloc, self_deallocator_deleter(), alloc, std::forward<Function>(f));\n }\n\n template<class T>\n struct default_allocator\n {\n using value_type = T;\n\n __AGENCY_ANNOTATION\n default_allocator() = default;\n\n __AGENCY_ANNOTATION\n default_allocator(const default_allocator&) = default;\n\n template<class U>\n __AGENCY_ANNOTATION\n default_allocator(const default_allocator<U>&) {}\n\n \/\/ XXX we have to implement this member function superfluously because\n \/\/ agency::detail::allocate_unique calls it directly instead of using std::allocator_traits\n template<class U, class... OtherArgs>\n __AGENCY_ANNOTATION\n void construct(U* ptr, OtherArgs&&... args)\n {\n ::new(ptr) U(std::forward<OtherArgs>(args)...);\n }\n\n value_type* allocate(size_t n)\n {\n std::allocator<T> alloc;\n return alloc.allocate(n);\n }\n\n void deallocate(value_type* ptr, std::size_t n)\n {\n std::allocator<value_type> alloc;\n alloc.deallocate(ptr, n);\n }\n };\n\n\n function_pointer f_ptr_; \n};\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * W.J. van der Laan 2011-2012\n *\/\n#include \"bitcoingui.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n\n#include \"init.h\"\n#include \"ui_interface.h\"\n#include \"qtipcserver.h\"\n\n#include <QApplication>\n#include <QMessageBox>\n#include <QTextCodec>\n#include <QLocale>\n#include <QTranslator>\n#include <QSplashScreen>\n#include <QLibraryInfo>\n\n#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)\n#define _BITCOIN_QT_PLUGINS_INCLUDED\n#define __INSURE__\n#include <QtPlugin>\nQ_IMPORT_PLUGIN(qcncodecs)\nQ_IMPORT_PLUGIN(qjpcodecs)\nQ_IMPORT_PLUGIN(qtwcodecs)\nQ_IMPORT_PLUGIN(qkrcodecs)\nQ_IMPORT_PLUGIN(qtaccessiblewidgets)\n#endif\n\n\/\/ Need a global reference for the notifications to find the GUI\nstatic BitcoinGUI *guiref;\nstatic QSplashScreen *splashref;\n\nstatic void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)\n{\n \/\/ Message from network thread\n if(guiref)\n {\n bool modal = (style & CClientUIInterface::MODAL);\n \/\/ in case of modal message, use blocking connection to wait for user to click OK\n QMetaObject::invokeMethod(guiref, \"error\",\n modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,\n Q_ARG(QString, QString::fromStdString(caption)),\n Q_ARG(QString, QString::fromStdString(message)),\n Q_ARG(bool, modal));\n }\n else\n {\n printf(\"%s: %s\\n\", caption.c_str(), message.c_str());\n fprintf(stderr, \"%s: %s\\n\", caption.c_str(), message.c_str());\n }\n}\n\nstatic bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)\n{\n if(!guiref)\n return false;\n if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)\n return true;\n bool payFee = false;\n\n QMetaObject::invokeMethod(guiref, \"askFee\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(qint64, nFeeRequired),\n Q_ARG(bool*, &payFee));\n\n return payFee;\n}\n\nstatic void ThreadSafeHandleURI(const std::string& strURI)\n{\n if(!guiref)\n return;\n\n QMetaObject::invokeMethod(guiref, \"handleURI\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(QString, QString::fromStdString(strURI)));\n}\n\nstatic void InitMessage(const std::string &message)\n{\n if(splashref)\n {\n splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));\n QApplication::instance()->processEvents();\n }\n}\n\nstatic void QueueShutdown()\n{\n QMetaObject::invokeMethod(QCoreApplication::instance(), \"quit\", Qt::QueuedConnection);\n}\n\n\/*\n Translate string to current locale using Qt.\n *\/\nstatic std::string Translate(const char* psz)\n{\n return QCoreApplication::translate(\"bitcoin-core\", psz).toStdString();\n}\n\n\/* Handle runaway exceptions. Shows a message box with the problem and quits the program.\n *\/\nstatic void handleRunawayException(std::exception *e)\n{\n PrintExceptionContinue(e, \"Runaway exception\");\n QMessageBox::critical(0, \"Runaway exception\", BitcoinGUI::tr(\"A fatal error occurred. Bitcoin can no longer continue safely and will quit.\") + QString(\"\\n\\n\") + QString::fromStdString(strMiscWarning));\n exit(1);\n}\n\n#ifndef BITCOIN_QT_TEST\nint main(int argc, char *argv[])\n{\n \/\/ Do this early as we don't want to bother initializing if we are just calling IPC\n ipcScanRelay(argc, argv);\n\n \/\/ Internal string conversion is all UTF-8\n QTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());\n\n Q_INIT_RESOURCE(bitcoin);\n QApplication app(argc, argv);\n\n \/\/ Install global event filter that makes sure that long tooltips can be word-wrapped\n app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));\n\n \/\/ Command-line options take precedence:\n ParseParameters(argc, argv);\n\n \/\/ ... then bitcoin.conf:\n if (!boost::filesystem::is_directory(GetDataDir(false)))\n {\n fprintf(stderr, \"Error: Specified directory does not exist\\n\");\n return 1;\n }\n ReadConfigFile(mapArgs, mapMultiArgs);\n\n \/\/ Application identification (must be set before OptionsModel is initialized,\n \/\/ as it is used to locate QSettings)\n app.setOrganizationName(\"Bitcoin\");\n app.setOrganizationDomain(\"bitcoin.org\");\n if(GetBoolArg(\"-testnet\")) \/\/ Separate UI settings for testnet\n app.setApplicationName(\"Bitcoin-Qt-testnet\");\n else\n app.setApplicationName(\"Bitcoin-Qt\");\n\n \/\/ ... then GUI settings:\n OptionsModel optionsModel;\n\n \/\/ Get desired locale (e.g. \"de_DE\") from command line or use system locale\n QString lang_territory = QString::fromStdString(GetArg(\"-lang\", QLocale::system().name().toStdString()));\n QString lang = lang_territory;\n \/\/ Convert to \"de\" only by truncating \"_DE\"\n lang.truncate(lang_territory.lastIndexOf('_'));\n\n QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;\n \/\/ Load language files for configured locale:\n \/\/ - First load the translator for the base language, without territory\n \/\/ - Then load the more specific locale translator\n\n \/\/ Load e.g. qt_de.qm\n if (qtTranslatorBase.load(\"qt_\" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n app.installTranslator(&qtTranslatorBase);\n\n \/\/ Load e.g. qt_de_DE.qm\n if (qtTranslator.load(\"qt_\" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n app.installTranslator(&qtTranslator);\n\n \/\/ Load e.g. bitcoin_de.qm (shortcut \"de\" needs to be defined in bitcoin.qrc)\n if (translatorBase.load(lang, \":\/translations\/\"))\n app.installTranslator(&translatorBase);\n\n \/\/ Load e.g. bitcoin_de_DE.qm (shortcut \"de_DE\" needs to be defined in bitcoin.qrc)\n if (translator.load(lang_territory, \":\/translations\/\"))\n app.installTranslator(&translator);\n\n \/\/ Subscribe to global signals from core\n uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);\n uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);\n uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);\n uiInterface.InitMessage.connect(InitMessage);\n uiInterface.QueueShutdown.connect(QueueShutdown);\n uiInterface.Translate.connect(Translate);\n\n \/\/ Show help message immediately after parsing command-line options (for \"-lang\") and setting locale,\n \/\/ but before showing splash screen.\n if (mapArgs.count(\"-?\") || mapArgs.count(\"--help\"))\n {\n GUIUtil::HelpMessageBox help;\n help.showOrPrint();\n return 1;\n }\n\n QSplashScreen splash(QPixmap(\":\/images\/splash\"), 0);\n if (GetBoolArg(\"-splash\", true) && !GetBoolArg(\"-min\"))\n {\n splash.show();\n splash.setAutoFillBackground(true);\n splashref = &splash;\n }\n\n app.processEvents();\n\n app.setQuitOnLastWindowClosed(false);\n\n try\n {\n \/\/ Regenerate startup link, to fix links to old versions\n if (GUIUtil::GetStartOnSystemStartup())\n GUIUtil::SetStartOnSystemStartup(true);\n\n BitcoinGUI window;\n guiref = &window;\n if(AppInit2())\n {\n {\n \/\/ Put this in a block, so that the Model objects are cleaned up before\n \/\/ calling Shutdown().\n\n optionsModel.Upgrade(); \/\/ Must be done after AppInit2\n\n if (splashref)\n splash.finish(&window);\n\n ClientModel clientModel(&optionsModel);\n WalletModel walletModel(pwalletMain, &optionsModel);\n\n window.setClientModel(&clientModel);\n window.setWalletModel(&walletModel);\n\n \/\/ If -min option passed, start window minimized.\n if(GetBoolArg(\"-min\"))\n {\n window.showMinimized();\n }\n else\n {\n window.show();\n }\n\n \/\/ Place this here as guiref has to be defined if we don't want to lose URIs\n ipcInit(argc, argv);\n\n app.exec();\n\n window.hide();\n window.setClientModel(0);\n window.setWalletModel(0);\n guiref = 0;\n }\n \/\/ Shutdown the core and its threads, but don't exit Bitcoin-Qt here\n Shutdown(NULL);\n }\n else\n {\n return 1;\n }\n } catch (std::exception& e) {\n handleRunawayException(&e);\n } catch (...) {\n handleRunawayException(NULL);\n }\n return 0;\n}\n#endif \/\/ BITCOIN_QT_TEST\n<commit_msg>When datadir missing, show messagebox instead of printing error to stderr<commit_after>\/*\n * W.J. van der Laan 2011-2012\n *\/\n#include \"bitcoingui.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n\n#include \"init.h\"\n#include \"ui_interface.h\"\n#include \"qtipcserver.h\"\n\n#include <QApplication>\n#include <QMessageBox>\n#include <QTextCodec>\n#include <QLocale>\n#include <QTranslator>\n#include <QSplashScreen>\n#include <QLibraryInfo>\n\n#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)\n#define _BITCOIN_QT_PLUGINS_INCLUDED\n#define __INSURE__\n#include <QtPlugin>\nQ_IMPORT_PLUGIN(qcncodecs)\nQ_IMPORT_PLUGIN(qjpcodecs)\nQ_IMPORT_PLUGIN(qtwcodecs)\nQ_IMPORT_PLUGIN(qkrcodecs)\nQ_IMPORT_PLUGIN(qtaccessiblewidgets)\n#endif\n\n\/\/ Need a global reference for the notifications to find the GUI\nstatic BitcoinGUI *guiref;\nstatic QSplashScreen *splashref;\n\nstatic void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)\n{\n \/\/ Message from network thread\n if(guiref)\n {\n bool modal = (style & CClientUIInterface::MODAL);\n \/\/ in case of modal message, use blocking connection to wait for user to click OK\n QMetaObject::invokeMethod(guiref, \"error\",\n modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,\n Q_ARG(QString, QString::fromStdString(caption)),\n Q_ARG(QString, QString::fromStdString(message)),\n Q_ARG(bool, modal));\n }\n else\n {\n printf(\"%s: %s\\n\", caption.c_str(), message.c_str());\n fprintf(stderr, \"%s: %s\\n\", caption.c_str(), message.c_str());\n }\n}\n\nstatic bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)\n{\n if(!guiref)\n return false;\n if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)\n return true;\n bool payFee = false;\n\n QMetaObject::invokeMethod(guiref, \"askFee\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(qint64, nFeeRequired),\n Q_ARG(bool*, &payFee));\n\n return payFee;\n}\n\nstatic void ThreadSafeHandleURI(const std::string& strURI)\n{\n if(!guiref)\n return;\n\n QMetaObject::invokeMethod(guiref, \"handleURI\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(QString, QString::fromStdString(strURI)));\n}\n\nstatic void InitMessage(const std::string &message)\n{\n if(splashref)\n {\n splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));\n QApplication::instance()->processEvents();\n }\n}\n\nstatic void QueueShutdown()\n{\n QMetaObject::invokeMethod(QCoreApplication::instance(), \"quit\", Qt::QueuedConnection);\n}\n\n\/*\n Translate string to current locale using Qt.\n *\/\nstatic std::string Translate(const char* psz)\n{\n return QCoreApplication::translate(\"bitcoin-core\", psz).toStdString();\n}\n\n\/* Handle runaway exceptions. Shows a message box with the problem and quits the program.\n *\/\nstatic void handleRunawayException(std::exception *e)\n{\n PrintExceptionContinue(e, \"Runaway exception\");\n QMessageBox::critical(0, \"Runaway exception\", BitcoinGUI::tr(\"A fatal error occurred. Bitcoin can no longer continue safely and will quit.\") + QString(\"\\n\\n\") + QString::fromStdString(strMiscWarning));\n exit(1);\n}\n\n#ifndef BITCOIN_QT_TEST\nint main(int argc, char *argv[])\n{\n \/\/ Do this early as we don't want to bother initializing if we are just calling IPC\n ipcScanRelay(argc, argv);\n\n \/\/ Internal string conversion is all UTF-8\n QTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());\n\n Q_INIT_RESOURCE(bitcoin);\n QApplication app(argc, argv);\n\n \/\/ Install global event filter that makes sure that long tooltips can be word-wrapped\n app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));\n\n \/\/ Command-line options take precedence:\n ParseParameters(argc, argv);\n\n \/\/ ... then bitcoin.conf:\n if (!boost::filesystem::is_directory(GetDataDir(false)))\n {\n \/\/ This message can not be translated, as translation is not initialized yet\n \/\/ (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)\n QMessageBox::critical(0, \"Bitcoin\",\n QString(\"Error: Specified data directory \\\"%1\\\" does not exist.\").arg(QString::fromStdString(mapArgs[\"-datadir\"])));\n return 1;\n }\n ReadConfigFile(mapArgs, mapMultiArgs);\n\n \/\/ Application identification (must be set before OptionsModel is initialized,\n \/\/ as it is used to locate QSettings)\n app.setOrganizationName(\"Bitcoin\");\n app.setOrganizationDomain(\"bitcoin.org\");\n if(GetBoolArg(\"-testnet\")) \/\/ Separate UI settings for testnet\n app.setApplicationName(\"Bitcoin-Qt-testnet\");\n else\n app.setApplicationName(\"Bitcoin-Qt\");\n\n \/\/ ... then GUI settings:\n OptionsModel optionsModel;\n\n \/\/ Get desired locale (e.g. \"de_DE\") from command line or use system locale\n QString lang_territory = QString::fromStdString(GetArg(\"-lang\", QLocale::system().name().toStdString()));\n QString lang = lang_territory;\n \/\/ Convert to \"de\" only by truncating \"_DE\"\n lang.truncate(lang_territory.lastIndexOf('_'));\n\n QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;\n \/\/ Load language files for configured locale:\n \/\/ - First load the translator for the base language, without territory\n \/\/ - Then load the more specific locale translator\n\n \/\/ Load e.g. qt_de.qm\n if (qtTranslatorBase.load(\"qt_\" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n app.installTranslator(&qtTranslatorBase);\n\n \/\/ Load e.g. qt_de_DE.qm\n if (qtTranslator.load(\"qt_\" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n app.installTranslator(&qtTranslator);\n\n \/\/ Load e.g. bitcoin_de.qm (shortcut \"de\" needs to be defined in bitcoin.qrc)\n if (translatorBase.load(lang, \":\/translations\/\"))\n app.installTranslator(&translatorBase);\n\n \/\/ Load e.g. bitcoin_de_DE.qm (shortcut \"de_DE\" needs to be defined in bitcoin.qrc)\n if (translator.load(lang_territory, \":\/translations\/\"))\n app.installTranslator(&translator);\n\n \/\/ Subscribe to global signals from core\n uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);\n uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);\n uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);\n uiInterface.InitMessage.connect(InitMessage);\n uiInterface.QueueShutdown.connect(QueueShutdown);\n uiInterface.Translate.connect(Translate);\n\n \/\/ Show help message immediately after parsing command-line options (for \"-lang\") and setting locale,\n \/\/ but before showing splash screen.\n if (mapArgs.count(\"-?\") || mapArgs.count(\"--help\"))\n {\n GUIUtil::HelpMessageBox help;\n help.showOrPrint();\n return 1;\n }\n\n QSplashScreen splash(QPixmap(\":\/images\/splash\"), 0);\n if (GetBoolArg(\"-splash\", true) && !GetBoolArg(\"-min\"))\n {\n splash.show();\n splash.setAutoFillBackground(true);\n splashref = &splash;\n }\n\n app.processEvents();\n\n app.setQuitOnLastWindowClosed(false);\n\n try\n {\n \/\/ Regenerate startup link, to fix links to old versions\n if (GUIUtil::GetStartOnSystemStartup())\n GUIUtil::SetStartOnSystemStartup(true);\n\n BitcoinGUI window;\n guiref = &window;\n if(AppInit2())\n {\n {\n \/\/ Put this in a block, so that the Model objects are cleaned up before\n \/\/ calling Shutdown().\n\n optionsModel.Upgrade(); \/\/ Must be done after AppInit2\n\n if (splashref)\n splash.finish(&window);\n\n ClientModel clientModel(&optionsModel);\n WalletModel walletModel(pwalletMain, &optionsModel);\n\n window.setClientModel(&clientModel);\n window.setWalletModel(&walletModel);\n\n \/\/ If -min option passed, start window minimized.\n if(GetBoolArg(\"-min\"))\n {\n window.showMinimized();\n }\n else\n {\n window.show();\n }\n\n \/\/ Place this here as guiref has to be defined if we don't want to lose URIs\n ipcInit(argc, argv);\n\n app.exec();\n\n window.hide();\n window.setClientModel(0);\n window.setWalletModel(0);\n guiref = 0;\n }\n \/\/ Shutdown the core and its threads, but don't exit Bitcoin-Qt here\n Shutdown(NULL);\n }\n else\n {\n return 1;\n }\n } catch (std::exception& e) {\n handleRunawayException(&e);\n } catch (...) {\n handleRunawayException(NULL);\n }\n return 0;\n}\n#endif \/\/ BITCOIN_QT_TEST\n<|endoftext|>"} {"text":"<commit_before>#include \"res2hutils.hpp\"\n\n#include <fstream>\n\n\nuint32_t calculateAdler32(const unsigned char * data, const size_t dataSize, uint32_t adler)\n{\n\tuint32_t s1 = adler & 0xffff;\n\tuint32_t s2 = (adler >> 16) & 0xffff;\n\t\/\/calculate checksum for buffer\n\tfor (std::streamsize n = 0; n < dataSize; n++) {\n\t\ts1 = (s1 + data[n]) % 65521;\n\t\ts2 = (s2 + s1) % 65521;\n\t}\n\t\/\/build final checksum\n\treturn (s2 << 16) + s1;\n}\n\nuint32_t calculateAdler32(const std::string & filePath, const size_t dataSize, uint32_t adler)\n{\n\t\/\/open file\n\tstd::ifstream inStream;\n\tinStream.open(filePath, std::ifstream::in | std::ifstream::binary);\n\tif (inStream.is_open() && inStream.good()) {\n\t\t\/\/loop until EOF or dataSize reached\n\t\tstd::streamsize rollingSize = 0;\n\t\twhile (!inStream.eof() && inStream.good()) {\n\t\t\tchar buffer[1024];\n\t\t\tstd::streamsize readSize = sizeof(buffer);\n\t\t\ttry {\n\t\t\t\t\/\/try reading data from input file\n\t\t\t\tinStream.read(reinterpret_cast<char *>(&buffer), sizeof(buffer));\n\t\t\t}\n\t\t\tcatch (std::ios_base::failure) { \/*reading didn't work properly. salvage what we can.*\/ }\n\t\t\t\/\/store how many bytes were actually read\n\t\t\treadSize = inStream.gcount();\n\t\t\t\/\/clamp to dataSize\n\t\t\tif (rollingSize + readSize > dataSize) {\n\t\t\t\treadSize = dataSize - rollingSize;\n\t\t\t}\n\t\t\t\/\/calculate checksum for buffer\n\t\t\tadler = calculateAdler32(buffer, (size_t)readSize, adler);\n\t\t\t\/\/update size already read\n\t\t\trollingSize += readSize;\n\t\t\tif (rollingSize >= dataSize) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\/\/close file\n\t\tinStream.close();\n\t}\n\treturn adler;\n}\n<commit_msg>Fix checksum function<commit_after>#include \"res2hutils.hpp\"\n\n#include <fstream>\n\n\nuint32_t calculateAdler32(const unsigned char * data, const size_t dataSize, uint32_t adler)\n{\n\tuint32_t s1 = adler & 0xffff;\n\tuint32_t s2 = (adler >> 16) & 0xffff;\n\t\/\/calculate checksum for buffer\n\tfor (std::streamsize n = 0; n < dataSize; n++) {\n\t\ts1 = (s1 + data[n]) % 65521;\n\t\ts2 = (s2 + s1) % 65521;\n\t}\n\t\/\/build final checksum\n\treturn (s2 << 16) + s1;\n}\n\nuint32_t calculateAdler32(const std::string & filePath, const size_t dataSize, uint32_t adler)\n{\n\t\/\/open file\n\tstd::ifstream inStream;\n\tinStream.open(filePath, std::ifstream::in | std::ifstream::binary);\n\tif (inStream.is_open() && inStream.good()) {\n\t\t\/\/loop until EOF or dataSize reached\n\t\tstd::streamsize rollingSize = 0;\n\t\twhile (!inStream.eof() && inStream.good()) {\n\t\t\tunsigned char buffer[1024];\n\t\t\tstd::streamsize readSize = sizeof(buffer);\n\t\t\ttry {\n\t\t\t\t\/\/try reading data from input file\n\t\t\t\tinStream.read(reinterpret_cast<char *>(&buffer), sizeof(buffer));\n\t\t\t}\n\t\t\tcatch (std::ios_base::failure) { \/*reading didn't work properly. salvage what we can.*\/ }\n\t\t\t\/\/store how many bytes were actually read\n\t\t\treadSize = inStream.gcount();\n\t\t\t\/\/clamp to dataSize if the caller wants to checksum only part of the file\n\t\t\tif (dataSize > 0 && rollingSize + readSize > dataSize) {\n\t\t\t\treadSize = dataSize - rollingSize;\n\t\t\t}\n\t\t\t\/\/calculate checksum for buffer\n\t\t\tadler = calculateAdler32((const unsigned char*)&buffer, (size_t)readSize, adler);\n\t\t\t\/\/update size already read\n\t\t\trollingSize += readSize;\n\t\t\tif (dataSize > 0 && rollingSize >= dataSize) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\/\/close file\n\t\tinStream.close();\n\t}\n\treturn adler;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Launch and manage FastCGI child processes.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"Stock.hxx\"\n#include \"Quark.hxx\"\n#include \"stock\/MapStock.hxx\"\n#include \"stock\/Class.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"child_stock.hxx\"\n#include \"child_manager.hxx\"\n#include \"spawn\/Prepared.hxx\"\n#include \"spawn\/ChildOptions.hxx\"\n#include \"spawn\/JailConfig.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"event\/Event.hxx\"\n#include \"event\/Callback.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include <daemon\/log.h>\n\n#include <glib.h>\n\n#include <assert.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <string.h>\n\n#ifdef __linux\n#include <sched.h>\n#endif\n\nstruct FcgiStock {\n StockMap *hstock;\n StockMap *child_stock;\n\n void FadeAll() {\n hstock_fade_all(*hstock);\n hstock_fade_all(*child_stock);\n }\n};\n\nstruct FcgiChildParams {\n const char *executable_path;\n\n ConstBuffer<const char *> args;\n\n const ChildOptions *options;\n\n const char *GetStockKey(struct pool &pool) const;\n};\n\nstruct FcgiConnection final : PoolStockItem {\n JailParams jail_params;\n\n struct jail_config jail_config;\n\n StockItem *child = nullptr;\n\n int fd = -1;\n Event event;\n\n \/**\n * Is this a fresh connection to the FastCGI child process?\n *\/\n bool fresh;\n\n \/**\n * Shall the FastCGI child process be killed?\n *\/\n bool kill;\n\n \/**\n * Was the current request aborted by the fcgi_client caller?\n *\/\n bool aborted;\n\n explicit FcgiConnection(struct pool &_pool, CreateStockItem c)\n :PoolStockItem(_pool, c) {}\n\n gcc_pure\n const char *GetStockKey() const {\n return child_stock_item_key(child);\n }\n\n void EventCallback(evutil_socket_t fd, short events);\n\n \/* virtual methods from class StockItem *\/\n bool Borrow(gcc_unused void *ctx) override;\n bool Release(gcc_unused void *ctx) override;\n void Destroy(void *ctx) override;\n};\n\nconst char *\nFcgiChildParams::GetStockKey(struct pool &pool) const\n{\n const char *key = executable_path;\n\n for (auto i : args)\n key = p_strcat(&pool, key, \" \", i, nullptr);\n\n for (auto i : options->env)\n key = p_strcat(&pool, key, \"$\", i, nullptr);\n\n char options_buffer[4096];\n *options->MakeId(options_buffer) = 0;\n if (*options_buffer != 0)\n key = p_strcat(&pool, key, options_buffer, nullptr);\n\n return key;\n}\n\n\/*\n * libevent callback\n *\n *\/\n\ninline void\nFcgiConnection::EventCallback(evutil_socket_t _fd, short events)\n{\n assert(_fd == fd);\n\n if ((events & EV_TIMEOUT) == 0) {\n char buffer;\n ssize_t nbytes = recv(_fd, &buffer, sizeof(buffer), MSG_DONTWAIT);\n if (nbytes < 0)\n daemon_log(2, \"error on idle FastCGI connection '%s': %s\\n\",\n GetStockKey(), strerror(errno));\n else if (nbytes > 0)\n daemon_log(2, \"unexpected data from idle FastCGI connection '%s'\\n\",\n GetStockKey());\n }\n\n InvokeIdleDisconnect();\n pool_commit();\n}\n\n\/*\n * child_stock class\n *\n *\/\n\nstatic bool\nfcgi_child_stock_prepare(gcc_unused const char *key, void *info, int fd,\n PreparedChildProcess &p, GError **error_r)\n{\n const auto ¶ms = *(const FcgiChildParams *)info;\n const ChildOptions &options = *params.options;\n\n p.stdin_fd = fd;\n\n \/* the FastCGI protocol defines a channel for stderr, so we could\n close its \"real\" stderr here, but many FastCGI applications\n don't use the FastCGI protocol to send error messages, so we\n just keep it open *\/\n\n int null_fd = open(\"\/dev\/null\", O_WRONLY|O_CLOEXEC|O_NOCTTY);\n if (null_fd >= 0)\n p.stdout_fd = null_fd;\n\n p.Append(params.executable_path);\n for (auto i : params.args)\n p.Append(i);\n\n return options.CopyTo(p, true, nullptr, error_r);\n}\n\nstatic const ChildStockClass fcgi_child_stock_class = {\n .shutdown_signal = SIGUSR1,\n .socket_type = nullptr,\n .prepare = fcgi_child_stock_prepare,\n};\n\n\/*\n * stock class\n *\n *\/\n\nstatic void\nfcgi_stock_create(void *ctx, struct pool &parent_pool, CreateStockItem c,\n const char *key, void *info,\n gcc_unused struct pool &caller_pool,\n gcc_unused struct async_operation_ref &async_ref)\n{\n FcgiStock *fcgi_stock = (FcgiStock *)ctx;\n FcgiChildParams *params = (FcgiChildParams *)info;\n\n assert(key != nullptr);\n assert(params != nullptr);\n assert(params->executable_path != nullptr);\n\n auto &pool = *pool_new_linear(&parent_pool, \"fcgi_connection\", 2048);\n auto *connection = NewFromPool<FcgiConnection>(pool, pool, c);\n\n const ChildOptions *const options = params->options;\n if (options->jail.enabled) {\n connection->jail_params.CopyFrom(pool, options->jail);\n\n if (!jail_config_load(&connection->jail_config,\n \"\/etc\/cm4all\/jailcgi\/jail.conf\", &pool)) {\n GError *error = g_error_new(fcgi_quark(), 0,\n \"Failed to load \/etc\/cm4all\/jailcgi\/jail.conf\");\n connection->InvokeCreateError(error);\n return;\n }\n } else\n connection->jail_params.enabled = false;\n\n GError *error = nullptr;\n connection->child = hstock_get_now(*fcgi_stock->child_stock, pool,\n key, params, &error);\n if (connection->child == nullptr) {\n g_prefix_error(&error, \"failed to start to FastCGI server '%s': \",\n key);\n connection->InvokeCreateError(error);\n return;\n }\n\n connection->fd = child_stock_item_connect(connection->child, &error);\n if (connection->fd < 0) {\n g_prefix_error(&error, \"failed to connect to FastCGI server '%s': \",\n key);\n\n connection->kill = true;\n connection->InvokeCreateError(error);\n return;\n }\n\n connection->fresh = true;\n connection->kill = false;\n connection->aborted = false;\n\n connection->event.Set(connection->fd, EV_READ|EV_TIMEOUT,\n MakeEventCallback(FcgiConnection, EventCallback),\n connection);\n\n connection->InvokeCreateSuccess();\n}\n\nbool\nFcgiConnection::Borrow(gcc_unused void *ctx)\n{\n \/* check the connection status before using it, just in case the\n FastCGI server has decided to close the connection before\n fcgi_connection_event_callback() got invoked *\/\n char buffer;\n ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);\n if (nbytes > 0) {\n daemon_log(2, \"unexpected data from idle FastCGI connection '%s'\\n\",\n GetStockKey());\n return false;\n } else if (nbytes == 0) {\n \/* connection closed (not worth a log message) *\/\n return false;\n } else if (errno != EAGAIN) {\n daemon_log(2, \"error on idle FastCGI connection '%s': %s\\n\",\n GetStockKey(), strerror(errno));\n return false;\n }\n\n event.Delete();\n aborted = false;\n return true;\n}\n\nbool\nFcgiConnection::Release(gcc_unused void *ctx)\n{\n static constexpr struct timeval tv = {\n .tv_sec = 300,\n .tv_usec = 0,\n };\n\n fresh = false;\n event.Add(tv);\n return true;\n}\n\nvoid\nFcgiConnection::Destroy(void *ctx)\n{\n FcgiStock *fcgi_stock = (FcgiStock *)ctx;\n\n if (fd >= 0) {\n event.Delete();\n close(fd);\n }\n\n if (child != nullptr)\n child_stock_put(fcgi_stock->child_stock, child, kill);\n\n PoolStockItem::Destroy(ctx);\n}\n\nstatic constexpr StockClass fcgi_stock_class = {\n .create = fcgi_stock_create,\n};\n\n\n\/*\n * interface\n *\n *\/\n\nFcgiStock *\nfcgi_stock_new(struct pool *pool, unsigned limit, unsigned max_idle)\n{\n auto fcgi_stock = NewFromPool<FcgiStock>(*pool);\n fcgi_stock->child_stock = child_stock_new(pool, limit, max_idle,\n &fcgi_child_stock_class);\n fcgi_stock->hstock = hstock_new(*pool, fcgi_stock_class, fcgi_stock,\n limit, max_idle);\n\n return fcgi_stock;\n}\n\nvoid\nfcgi_stock_free(FcgiStock *fcgi_stock)\n{\n hstock_free(fcgi_stock->hstock);\n hstock_free(fcgi_stock->child_stock);\n}\n\nvoid\nfcgi_stock_fade_all(FcgiStock &fs)\n{\n fs.FadeAll();\n}\n\nStockItem *\nfcgi_stock_get(FcgiStock *fcgi_stock, struct pool *pool,\n const ChildOptions &options,\n const char *executable_path,\n ConstBuffer<const char *> args,\n GError **error_r)\n{\n auto params = NewFromPool<FcgiChildParams>(*pool);\n params->executable_path = executable_path;\n params->args = args;\n params->options = &options;\n\n return hstock_get_now(*fcgi_stock->hstock, *pool,\n params->GetStockKey(*pool), params,\n error_r);\n}\n\nint\nfcgi_stock_item_get_domain(gcc_unused const StockItem &item)\n{\n return AF_UNIX;\n}\n\nint\nfcgi_stock_item_get(const StockItem &item)\n{\n const auto *connection = (const FcgiConnection *)&item;\n\n assert(connection->fd >= 0);\n\n return connection->fd;\n}\n\nconst char *\nfcgi_stock_translate_path(const StockItem &item,\n const char *path, struct pool *pool)\n{\n const auto *connection = (const FcgiConnection *)&item;\n\n if (!connection->jail_params.enabled)\n \/* no JailCGI - application's namespace is the same as ours,\n no translation needed *\/\n return path;\n\n const char *jailed = jail_translate_path(&connection->jail_config, path,\n connection->jail_params.home_directory,\n pool);\n return jailed != nullptr ? jailed : path;\n}\n\nvoid\nfcgi_stock_put(FcgiStock *fcgi_stock, StockItem &item,\n bool destroy)\n{\n auto *connection = (FcgiConnection *)&item;\n\n if (connection->fresh && connection->aborted && destroy)\n \/* the fcgi_client caller has aborted the request before the\n first response on a fresh connection was received: better\n kill the child process, it may be failing on us\n completely *\/\n connection->kill = true;\n\n hstock_put(*fcgi_stock->hstock, connection->GetStockKey(),\n item, destroy);\n}\n\nvoid\nfcgi_stock_aborted(StockItem &item)\n{\n auto *connection = (FcgiConnection *)&item;\n\n connection->aborted = true;\n}\n<commit_msg>fcgi\/Stock: pass caller_pool to hstock_get_now()<commit_after>\/*\n * Launch and manage FastCGI child processes.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"Stock.hxx\"\n#include \"Quark.hxx\"\n#include \"stock\/MapStock.hxx\"\n#include \"stock\/Class.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"child_stock.hxx\"\n#include \"child_manager.hxx\"\n#include \"spawn\/Prepared.hxx\"\n#include \"spawn\/ChildOptions.hxx\"\n#include \"spawn\/JailConfig.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"event\/Event.hxx\"\n#include \"event\/Callback.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include <daemon\/log.h>\n\n#include <glib.h>\n\n#include <assert.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <string.h>\n\n#ifdef __linux\n#include <sched.h>\n#endif\n\nstruct FcgiStock {\n StockMap *hstock;\n StockMap *child_stock;\n\n void FadeAll() {\n hstock_fade_all(*hstock);\n hstock_fade_all(*child_stock);\n }\n};\n\nstruct FcgiChildParams {\n const char *executable_path;\n\n ConstBuffer<const char *> args;\n\n const ChildOptions *options;\n\n const char *GetStockKey(struct pool &pool) const;\n};\n\nstruct FcgiConnection final : PoolStockItem {\n JailParams jail_params;\n\n struct jail_config jail_config;\n\n StockItem *child = nullptr;\n\n int fd = -1;\n Event event;\n\n \/**\n * Is this a fresh connection to the FastCGI child process?\n *\/\n bool fresh;\n\n \/**\n * Shall the FastCGI child process be killed?\n *\/\n bool kill;\n\n \/**\n * Was the current request aborted by the fcgi_client caller?\n *\/\n bool aborted;\n\n explicit FcgiConnection(struct pool &_pool, CreateStockItem c)\n :PoolStockItem(_pool, c) {}\n\n gcc_pure\n const char *GetStockKey() const {\n return child_stock_item_key(child);\n }\n\n void EventCallback(evutil_socket_t fd, short events);\n\n \/* virtual methods from class StockItem *\/\n bool Borrow(gcc_unused void *ctx) override;\n bool Release(gcc_unused void *ctx) override;\n void Destroy(void *ctx) override;\n};\n\nconst char *\nFcgiChildParams::GetStockKey(struct pool &pool) const\n{\n const char *key = executable_path;\n\n for (auto i : args)\n key = p_strcat(&pool, key, \" \", i, nullptr);\n\n for (auto i : options->env)\n key = p_strcat(&pool, key, \"$\", i, nullptr);\n\n char options_buffer[4096];\n *options->MakeId(options_buffer) = 0;\n if (*options_buffer != 0)\n key = p_strcat(&pool, key, options_buffer, nullptr);\n\n return key;\n}\n\n\/*\n * libevent callback\n *\n *\/\n\ninline void\nFcgiConnection::EventCallback(evutil_socket_t _fd, short events)\n{\n assert(_fd == fd);\n\n if ((events & EV_TIMEOUT) == 0) {\n char buffer;\n ssize_t nbytes = recv(_fd, &buffer, sizeof(buffer), MSG_DONTWAIT);\n if (nbytes < 0)\n daemon_log(2, \"error on idle FastCGI connection '%s': %s\\n\",\n GetStockKey(), strerror(errno));\n else if (nbytes > 0)\n daemon_log(2, \"unexpected data from idle FastCGI connection '%s'\\n\",\n GetStockKey());\n }\n\n InvokeIdleDisconnect();\n pool_commit();\n}\n\n\/*\n * child_stock class\n *\n *\/\n\nstatic bool\nfcgi_child_stock_prepare(gcc_unused const char *key, void *info, int fd,\n PreparedChildProcess &p, GError **error_r)\n{\n const auto ¶ms = *(const FcgiChildParams *)info;\n const ChildOptions &options = *params.options;\n\n p.stdin_fd = fd;\n\n \/* the FastCGI protocol defines a channel for stderr, so we could\n close its \"real\" stderr here, but many FastCGI applications\n don't use the FastCGI protocol to send error messages, so we\n just keep it open *\/\n\n int null_fd = open(\"\/dev\/null\", O_WRONLY|O_CLOEXEC|O_NOCTTY);\n if (null_fd >= 0)\n p.stdout_fd = null_fd;\n\n p.Append(params.executable_path);\n for (auto i : params.args)\n p.Append(i);\n\n return options.CopyTo(p, true, nullptr, error_r);\n}\n\nstatic const ChildStockClass fcgi_child_stock_class = {\n .shutdown_signal = SIGUSR1,\n .socket_type = nullptr,\n .prepare = fcgi_child_stock_prepare,\n};\n\n\/*\n * stock class\n *\n *\/\n\nstatic void\nfcgi_stock_create(void *ctx, struct pool &parent_pool, CreateStockItem c,\n const char *key, void *info,\n struct pool &caller_pool,\n gcc_unused struct async_operation_ref &async_ref)\n{\n FcgiStock *fcgi_stock = (FcgiStock *)ctx;\n FcgiChildParams *params = (FcgiChildParams *)info;\n\n assert(key != nullptr);\n assert(params != nullptr);\n assert(params->executable_path != nullptr);\n\n auto &pool = *pool_new_linear(&parent_pool, \"fcgi_connection\", 2048);\n auto *connection = NewFromPool<FcgiConnection>(pool, pool, c);\n\n const ChildOptions *const options = params->options;\n if (options->jail.enabled) {\n connection->jail_params.CopyFrom(pool, options->jail);\n\n if (!jail_config_load(&connection->jail_config,\n \"\/etc\/cm4all\/jailcgi\/jail.conf\", &pool)) {\n GError *error = g_error_new(fcgi_quark(), 0,\n \"Failed to load \/etc\/cm4all\/jailcgi\/jail.conf\");\n connection->InvokeCreateError(error);\n return;\n }\n } else\n connection->jail_params.enabled = false;\n\n GError *error = nullptr;\n connection->child = hstock_get_now(*fcgi_stock->child_stock, caller_pool,\n key, params, &error);\n if (connection->child == nullptr) {\n g_prefix_error(&error, \"failed to start to FastCGI server '%s': \",\n key);\n connection->InvokeCreateError(error);\n return;\n }\n\n connection->fd = child_stock_item_connect(connection->child, &error);\n if (connection->fd < 0) {\n g_prefix_error(&error, \"failed to connect to FastCGI server '%s': \",\n key);\n\n connection->kill = true;\n connection->InvokeCreateError(error);\n return;\n }\n\n connection->fresh = true;\n connection->kill = false;\n connection->aborted = false;\n\n connection->event.Set(connection->fd, EV_READ|EV_TIMEOUT,\n MakeEventCallback(FcgiConnection, EventCallback),\n connection);\n\n connection->InvokeCreateSuccess();\n}\n\nbool\nFcgiConnection::Borrow(gcc_unused void *ctx)\n{\n \/* check the connection status before using it, just in case the\n FastCGI server has decided to close the connection before\n fcgi_connection_event_callback() got invoked *\/\n char buffer;\n ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);\n if (nbytes > 0) {\n daemon_log(2, \"unexpected data from idle FastCGI connection '%s'\\n\",\n GetStockKey());\n return false;\n } else if (nbytes == 0) {\n \/* connection closed (not worth a log message) *\/\n return false;\n } else if (errno != EAGAIN) {\n daemon_log(2, \"error on idle FastCGI connection '%s': %s\\n\",\n GetStockKey(), strerror(errno));\n return false;\n }\n\n event.Delete();\n aborted = false;\n return true;\n}\n\nbool\nFcgiConnection::Release(gcc_unused void *ctx)\n{\n static constexpr struct timeval tv = {\n .tv_sec = 300,\n .tv_usec = 0,\n };\n\n fresh = false;\n event.Add(tv);\n return true;\n}\n\nvoid\nFcgiConnection::Destroy(void *ctx)\n{\n FcgiStock *fcgi_stock = (FcgiStock *)ctx;\n\n if (fd >= 0) {\n event.Delete();\n close(fd);\n }\n\n if (child != nullptr)\n child_stock_put(fcgi_stock->child_stock, child, kill);\n\n PoolStockItem::Destroy(ctx);\n}\n\nstatic constexpr StockClass fcgi_stock_class = {\n .create = fcgi_stock_create,\n};\n\n\n\/*\n * interface\n *\n *\/\n\nFcgiStock *\nfcgi_stock_new(struct pool *pool, unsigned limit, unsigned max_idle)\n{\n auto fcgi_stock = NewFromPool<FcgiStock>(*pool);\n fcgi_stock->child_stock = child_stock_new(pool, limit, max_idle,\n &fcgi_child_stock_class);\n fcgi_stock->hstock = hstock_new(*pool, fcgi_stock_class, fcgi_stock,\n limit, max_idle);\n\n return fcgi_stock;\n}\n\nvoid\nfcgi_stock_free(FcgiStock *fcgi_stock)\n{\n hstock_free(fcgi_stock->hstock);\n hstock_free(fcgi_stock->child_stock);\n}\n\nvoid\nfcgi_stock_fade_all(FcgiStock &fs)\n{\n fs.FadeAll();\n}\n\nStockItem *\nfcgi_stock_get(FcgiStock *fcgi_stock, struct pool *pool,\n const ChildOptions &options,\n const char *executable_path,\n ConstBuffer<const char *> args,\n GError **error_r)\n{\n auto params = NewFromPool<FcgiChildParams>(*pool);\n params->executable_path = executable_path;\n params->args = args;\n params->options = &options;\n\n return hstock_get_now(*fcgi_stock->hstock, *pool,\n params->GetStockKey(*pool), params,\n error_r);\n}\n\nint\nfcgi_stock_item_get_domain(gcc_unused const StockItem &item)\n{\n return AF_UNIX;\n}\n\nint\nfcgi_stock_item_get(const StockItem &item)\n{\n const auto *connection = (const FcgiConnection *)&item;\n\n assert(connection->fd >= 0);\n\n return connection->fd;\n}\n\nconst char *\nfcgi_stock_translate_path(const StockItem &item,\n const char *path, struct pool *pool)\n{\n const auto *connection = (const FcgiConnection *)&item;\n\n if (!connection->jail_params.enabled)\n \/* no JailCGI - application's namespace is the same as ours,\n no translation needed *\/\n return path;\n\n const char *jailed = jail_translate_path(&connection->jail_config, path,\n connection->jail_params.home_directory,\n pool);\n return jailed != nullptr ? jailed : path;\n}\n\nvoid\nfcgi_stock_put(FcgiStock *fcgi_stock, StockItem &item,\n bool destroy)\n{\n auto *connection = (FcgiConnection *)&item;\n\n if (connection->fresh && connection->aborted && destroy)\n \/* the fcgi_client caller has aborted the request before the\n first response on a fresh connection was received: better\n kill the child process, it may be failing on us\n completely *\/\n connection->kill = true;\n\n hstock_put(*fcgi_stock->hstock, connection->GetStockKey(),\n item, destroy);\n}\n\nvoid\nfcgi_stock_aborted(StockItem &item)\n{\n auto *connection = (FcgiConnection *)&item;\n\n connection->aborted = true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Rust garbage collection.\n\n#include <utility>\n#include <stdint.h>\n\n#include \"rust_gc.h\"\n#include \"rust_internal.h\"\n\n#ifdef __WIN32__\n#include <windows.h>\n#else\n#include <dlfcn.h>\n#endif\n\nnamespace gc {\n\nstruct root {\n intptr_t frame_offset;\n uintptr_t dynamic; \/\/ 0 = static, 1 = dynamic\n type_desc *tydesc;\n};\n\nstruct safe_point {\n uintptr_t n_roots;\n root roots[0];\n};\n\nclass safe_point_map {\n uintptr_t n_safe_points;\n const std::pair<void *,const safe_point *> *index;\n const safe_point *safe_points;\n\npublic:\n safe_point_map() {\n const uintptr_t *data = get_safe_point_data();\n n_safe_points = *data++;\n index = (const std::pair<void *,const safe_point *> *)data;\n data += n_safe_points * 2;\n safe_points = (const safe_point *)data;\n }\n\n static const uintptr_t *get_safe_point_data() {\n static bool init = false;\n static const uintptr_t *data;\n if (!init) {\n#ifdef __WIN32__\n data = (const uintptr_t *)GetProcAddress(GetModuleHandle(NULL),\n \"rust_gc_safe_points\");\n#else\n data = (const uintptr_t *)dlsym(RTLD_DEFAULT,\n \"rust_gc_safe_points\");\n#endif\n init = true;\n }\n return data;\n }\n};\n\nvoid\ngc(rust_task *task) {\n safe_point_map map;\n\n \/\/ TODO\n}\n\nvoid\nmaybe_gc(rust_task *task) {\n if (safe_point_map::get_safe_point_data() == NULL)\n return;\n\n \/\/ FIXME: We ought to lock this.\n static int zeal = -1;\n if (zeal == -1) {\n char *ev = getenv(\"RUST_GC_ZEAL\");\n zeal = ev && ev[0] != '\\0' && ev[0] != '0';\n }\n\n if (zeal)\n gc(task);\n}\n\n}\n\n<commit_msg>rt: Attempt to put out burning tinderbox by fully qualifying gc::gc().<commit_after>\/\/ Rust garbage collection.\n\n#include <utility>\n#include <stdint.h>\n\n#include \"rust_gc.h\"\n#include \"rust_internal.h\"\n\n#ifdef __WIN32__\n#include <windows.h>\n#else\n#include <dlfcn.h>\n#endif\n\nnamespace gc {\n\nstruct root {\n intptr_t frame_offset;\n uintptr_t dynamic; \/\/ 0 = static, 1 = dynamic\n type_desc *tydesc;\n};\n\nstruct safe_point {\n uintptr_t n_roots;\n root roots[0];\n};\n\nclass safe_point_map {\n uintptr_t n_safe_points;\n const std::pair<void *,const safe_point *> *index;\n const safe_point *safe_points;\n\npublic:\n safe_point_map() {\n const uintptr_t *data = get_safe_point_data();\n n_safe_points = *data++;\n index = (const std::pair<void *,const safe_point *> *)data;\n data += n_safe_points * 2;\n safe_points = (const safe_point *)data;\n }\n\n static const uintptr_t *get_safe_point_data() {\n static bool init = false;\n static const uintptr_t *data;\n if (!init) {\n#ifdef __WIN32__\n data = (const uintptr_t *)GetProcAddress(GetModuleHandle(NULL),\n \"rust_gc_safe_points\");\n#else\n data = (const uintptr_t *)dlsym(RTLD_DEFAULT,\n \"rust_gc_safe_points\");\n#endif\n init = true;\n }\n return data;\n }\n};\n\nvoid\ngc(rust_task *task) {\n safe_point_map map;\n\n \/\/ TODO\n}\n\nvoid\nmaybe_gc(rust_task *task) {\n if (safe_point_map::get_safe_point_data() == NULL)\n return;\n\n \/\/ FIXME: We ought to lock this.\n static int zeal = -1;\n if (zeal == -1) {\n char *ev = getenv(\"RUST_GC_ZEAL\");\n zeal = ev && ev[0] != '\\0' && ev[0] != '0';\n }\n\n if (zeal)\n gc::gc(task);\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2014 The Regents of the University of California (Regents).\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of The Regents or University of California nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Please contact the author of this library if you have any questions.\n\/\/ Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include <Eigen\/Core>\n#include <glog\/logging.h>\n#include <gflags\/gflags.h>\n#include <theia\/theia.h>\n#include <string>\n#include <vector>\n\n#ifdef __APPLE__\n#include <OpenGL\/OpenGL.h>\n#ifdef FREEGLUT\n#include <GL\/freeglut.h>\n#else\n#include <GLUT\/glut.h>\n#endif\n#else\n#ifdef _WIN32\n#include <windows.h>\n#endif\n#define GL_GLEXT_PROTOTYPES 1\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n#include <GL\/glut.h>\n#endif\n\nDEFINE_string(reconstruction, \"\", \"Reconstruction file to be viewed.\");\n\n\/\/ Containers for the data.\nstd::vector<theia::Camera> cameras;\nstd::vector<Eigen::Vector3d> world_points;\nstd::vector<int> num_views_for_track;\n\n\/\/ Parameters for OpenGL.\nint mouse_down_x[3], mouse_down_y[3];\nfloat rot_x = 0.0f, rot_y = 0.0f;\nfloat prev_x, prev_y;\nfloat distance = 100.0;\nEigen::Vector3d origin = Eigen::Vector3d::Zero();\nbool mouse_rotates = false, mouse_moves = false;\nbool draw_cameras = true;\nbool draw_axes = false;\n\nfloat point_size = 1.0;\nfloat normalized_focal_length = 1.0;\nint min_num_views_for_track = 2;\nvoid GetPerspectiveParams(double* aspect_ratio, double* fovy) {\n int width = 800;\n int height = 600;\n double focal_length = 600.0;\n *aspect_ratio = static_cast<double>(width) \/ static_cast<double>(height);\n *fovy = 2 * atan(height \/ (2.0 * focal_length)) * 180.0 \/ M_PI;\n}\n\nvoid ChangeSize(int w, int h) {\n \/\/ Prevent a divide by zero, when window is too short\n \/\/ (you cant make a window of zero width).\n if (h == 0) h = 1;\n\n \/\/ Use the Projection Matrix\n glMatrixMode(GL_PROJECTION);\n\n \/\/ Reset Matrix\n glLoadIdentity();\n\n \/\/ Set the viewport to be the entire window\n double aspect_ratio, fovy;\n GetPerspectiveParams(&aspect_ratio, &fovy);\n glViewport(0, 0, w, h);\n\n \/\/ Set the correct perspective.\n gluPerspective(fovy, aspect_ratio, 0.01f, 100000.0f);\n\n \/\/ Get Back to the Reconstructionview\n glMatrixMode(GL_MODELVIEW);\n}\n\nvoid DrawAxes(float length) {\n glPushAttrib(GL_POLYGON_BIT | GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);\n\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n glDisable(GL_LIGHTING);\n\n glBegin(GL_LINES);\n glColor3f(1.0, 0.0, 0.0);\n glVertex3f(0, 0, 0);\n glVertex3f(length, 0, 0);\n\n glColor3f(0.0, 1.0, 0.0);\n glVertex3f(0, 0, 0);\n glVertex3f(0, length, 0);\n\n glColor3f(0.0, 0.0, 1.0);\n glVertex3f(0, 0, 0);\n glVertex3f(0, 0, length);\n glEnd();\n\n glPopAttrib();\n}\n\nvoid DrawCamera(const theia::Camera& camera) {\n glPushMatrix();\n Eigen::Matrix4d transformation_matrix;\n transformation_matrix.block<3, 3>(0, 0) =\n camera.GetOrientationAsRotationMatrix().transpose();\n transformation_matrix.col(3).head<3>() = camera.GetPosition();\n transformation_matrix(3, 3) = 1.0;\n\n \/\/ Apply world pose transformation.\n glMultMatrixd(reinterpret_cast<GLdouble*>(transformation_matrix.data()));\n\n \/\/ Draw Cameras.\n glColor3f(1.0, 0.0, 0.0);\n\n \/\/ Create the camera wireframe. If intrinsic parameters are not set then use\n \/\/ the focal length as a guess.\n const double principal_point_x = (camera.PrincipalPointX() == 0)\n ? 0.6 * camera.FocalLength()\n : camera.PrincipalPointX();\n const double principal_point_y = (camera.PrincipalPointY() == 0)\n ? 0.6 * camera.FocalLength()\n : camera.PrincipalPointY();\n const double image_width =\n (camera.ImageWidth() == 0) ? 2 * principal_point_x : camera.ImageWidth();\n const double image_height = (camera.ImageHeight() == 0)\n ? 2 * principal_point_y\n : camera.ImageHeight();\n\n \/\/ Use the camera calibration to display the cameras.\n Eigen::Matrix3d calibration_matrix;\n camera.GetCalibrationMatrix(&calibration_matrix);\n const Eigen::Matrix3d inv_calibration = calibration_matrix.inverse();\n const Eigen::Vector3d top_left =\n normalized_focal_length * (inv_calibration * Eigen::Vector3d(0, 0, 1));\n const Eigen::Vector3d top_right =\n normalized_focal_length *\n (inv_calibration * Eigen::Vector3d(image_width, 0, 1));\n const Eigen::Vector3d bottom_right =\n normalized_focal_length *\n (inv_calibration * Eigen::Vector3d(image_width, image_height, 1));\n const Eigen::Vector3d bottom_left =\n normalized_focal_length *\n (inv_calibration * Eigen::Vector3d(0, image_height, 1));\n\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n glBegin(GL_TRIANGLE_FAN);\n glVertex3f(0.0, 0.0, 0.0);\n glVertex3f(top_right[0], top_right[1], top_right[2]);\n glVertex3f(top_left[0], top_left[1], top_left[2]);\n glVertex3f(bottom_left[0], bottom_left[1], bottom_left[2]);\n glVertex3f(bottom_right[0], bottom_right[1], bottom_right[2]);\n glVertex3f(top_right[0], top_right[1], top_right[2]);\n glEnd();\n glPopMatrix();\n}\n\nvoid RenderScene() {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n glTranslatef(-origin[0], -origin[1], -distance);\n glRotatef(180.0f + rot_x, 1.0f, 0.0f, 0.0f);\n glRotatef(-rot_y, 0.0f, 1.0f, 0.0f);\n glClearColor(1.0f, 1.0f, 1.0f, 0.0f);\n\n if (draw_axes) {\n DrawAxes(1.0);\n }\n\n \/\/ Plot the point cloud.\n glDisable(GL_LIGHTING);\n glEnable(GL_MULTISAMPLE);\n glEnable(GL_BLEND);\n glEnable(GL_POINT_SMOOTH);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glPointSize(point_size);\n\n \/\/ the coordinates for calculating point attenuation:\n GLfloat point_size_coords[3];\n point_size_coords[0] = 1.0f;\n point_size_coords[1] = 0.055f;\n point_size_coords[2] = 0.0f;\n glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, point_size_coords);\n\n \/\/ Draw the points.\n glColor3f(0.01, 0.01, 0.01);\n glBegin(GL_POINTS);\n for (int i = 0; i < world_points.size(); i++) {\n if (num_views_for_track[i] < min_num_views_for_track) {\n continue;\n }\n glVertex3d(world_points[i].x(), world_points[i].y(), world_points[i].z());\n }\n glEnd();\n\n \/\/ Draw the cameras.\n if (draw_cameras) {\n for (int i = 0; i < cameras.size(); i++) {\n DrawCamera(cameras[i]);\n }\n }\n glutSwapBuffers();\n}\n\nvoid MouseButton(int button, int state, int x, int y) {\n \/\/ button down: save coordinates\n if (state == GLUT_DOWN && button <= 2) {\n mouse_down_x[button] = x;\n mouse_down_y[button] = y;\n prev_x = x;\n prev_y = y;\n\n if (button == GLUT_RIGHT_BUTTON) {\n mouse_rotates = true;\n } else if (button == GLUT_LEFT_BUTTON) {\n mouse_moves = true;\n }\n return;\n }\n\n if (state == GLUT_UP && button == GLUT_RIGHT_BUTTON) {\n mouse_rotates = false;\n }\n\n if (state == GLUT_UP && button == GLUT_LEFT_BUTTON) {\n mouse_moves = false;\n }\n\n \/\/ scroll event - wheel reports as button 3 (scroll up) and button 4 (scroll\n \/\/ down)\n if ((button == 3) || (button == 4)) {\n \/\/ Each wheel event reports like a button click, GLUT_DOWN then GLUT_UP\n if (state == GLUT_UP) return; \/\/ Disregard redundant GLUT_UP events\n if (button == 3)\n distance \/= 1.5f;\n else\n distance *= 1.5f;\n }\n}\n\nvoid MouseMove(int x, int y) {\n if (mouse_rotates) {\n const double rotate_factor = 0.5f;\n \/\/ notice x & y difference (i.e., changes in x are to rotate about y-axis)\n rot_x -= rotate_factor * (y - prev_y);\n rot_y -= rotate_factor * (x - prev_x);\n prev_x = x;\n prev_y = y;\n } else if (mouse_moves) {\n const double mouse_factor = 0.03f;\n origin.x() -= mouse_factor * (x - prev_x);\n origin.y() += mouse_factor * (y - prev_y);\n prev_x = x;\n prev_y = y;\n }\n}\n\nvoid Keyboard(unsigned char key, int x, int y) {\n switch (key) {\n case 'r': \/\/ reset viewpoint\n distance = 100.0f;\n rot_x = 0.0f;\n rot_y = 0.0f;\n point_size = 1.0;\n origin = Eigen::Vector3d::Zero();\n break;\n case 'z':\n distance \/= 1.2f;\n break;\n case 'Z':\n distance *= 1.2f;\n break;\n case 'p':\n point_size \/= 1.2;\n break;\n case 'P':\n point_size *= 1.2;\n break;\n case 'f':\n normalized_focal_length \/= 1.2;\n break;\n case 'F':\n normalized_focal_length *= 1.2;\n break;\n case 'c':\n draw_cameras = !draw_cameras;\n break;\n case 'a':\n draw_axes = !draw_axes;\n break;\n case 't':\n ++min_num_views_for_track;\n break;\n case 'T':\n --min_num_views_for_track;\n break;\n }\n}\n\n\/\/ initialize viewport etc.\nvoid Init() {\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n\n double aspect_ratio, fovy; \/\/ set the correct perspective.\n GetPerspectiveParams(&aspect_ratio, &fovy);\n gluPerspective(fovy, 1.0, .01, 100000.0);\n\n glMatrixMode(GL_MODELVIEW);\n}\n\nvoid CenterReconstruction() {\n Eigen::Vector3d mean_camera = Eigen::Vector3d::Zero();\n for (int i = 0; i < cameras.size(); i++) {\n mean_camera += cameras[i].GetPosition();\n }\n mean_camera \/= static_cast<double>(cameras.size());\n\n for (int i = 0; i < cameras.size(); i++) {\n const Eigen::Vector3d old_position = cameras[i].GetPosition();\n cameras[i].SetPosition(old_position - mean_camera);\n }\n for (int i = 0; i < world_points.size(); i++) {\n world_points[i] -= mean_camera;\n }\n}\n\nint main(int argc, char* argv[]) {\n THEIA_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n\n \/\/ Output as a binary file.\n std::unique_ptr<theia::Reconstruction> reconstruction(\n new theia::Reconstruction());\n CHECK(ReadReconstruction(FLAGS_reconstruction, reconstruction.get()))\n << \"Could not read reconstruction file.\";\n\n \/\/ Set up camera drawing.\n cameras.reserve(reconstruction->NumViews());\n for (const theia::ViewId view_id : reconstruction->ViewIds()) {\n const auto* view = reconstruction->View(view_id);\n if (view == nullptr || !view->IsEstimated()) {\n continue;\n }\n cameras.emplace_back(view->Camera());\n }\n\n \/\/ Set up world points.\n world_points.reserve(reconstruction->NumTracks());\n for (const theia::TrackId track_id : reconstruction->TrackIds()) {\n const auto* track = reconstruction->Track(track_id);\n if (track == nullptr || !track->IsEstimated()) {\n continue;\n }\n world_points.emplace_back(track->Point().hnormalized());\n num_views_for_track.emplace_back(track->NumViews());\n }\n\n CenterReconstruction();\n\n reconstruction.release();\n\n \/\/ Set up opengl and glut.\n glutInit(&argc, argv);\n glutInitWindowPosition(600, 600);\n glutInitWindowSize(1200, 800);\n glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);\n glutCreateWindow(\"Theia Reconstruction Viewer\");\n\n \/\/ Set the camera\n gluLookAt(0.0f, 0.0f, -6.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);\n\n \/\/ register callbacks\n glutDisplayFunc(RenderScene);\n glutReshapeFunc(ChangeSize);\n glutMouseFunc(MouseButton);\n glutMotionFunc(MouseMove);\n glutKeyboardFunc(Keyboard);\n glutIdleFunc(RenderScene);\n\n \/\/ enter GLUT event processing loop\n glutMainLoop();\n\n return 0;\n}\n<commit_msg>Better display of camera wireframe<commit_after>\/\/ Copyright (C) 2014 The Regents of the University of California (Regents).\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:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\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\/\/\n\/\/ * Neither the name of The Regents or University of California nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Please contact the author of this library if you have any questions.\n\/\/ Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include <Eigen\/Core>\n#include <glog\/logging.h>\n#include <gflags\/gflags.h>\n#include <theia\/theia.h>\n#include <string>\n#include <vector>\n\n#ifdef __APPLE__\n#include <OpenGL\/OpenGL.h>\n#ifdef FREEGLUT\n#include <GL\/freeglut.h>\n#else\n#include <GLUT\/glut.h>\n#endif\n#else\n#ifdef _WIN32\n#include <windows.h>\n#endif\n#define GL_GLEXT_PROTOTYPES 1\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n#include <GL\/glut.h>\n#endif\n\nDEFINE_string(reconstruction, \"\", \"Reconstruction file to be viewed.\");\n\n\/\/ Containers for the data.\nstd::vector<theia::Camera> cameras;\nstd::vector<Eigen::Vector3d> world_points;\nstd::vector<int> num_views_for_track;\n\n\/\/ Parameters for OpenGL.\nint mouse_down_x[3], mouse_down_y[3];\nfloat rot_x = 0.0f, rot_y = 0.0f;\nfloat prev_x, prev_y;\nfloat distance = 100.0;\nEigen::Vector3d origin = Eigen::Vector3d::Zero();\nbool mouse_rotates = false, mouse_moves = false;\nbool draw_cameras = true;\nbool draw_axes = false;\n\nfloat point_size = 1.0;\nfloat normalized_focal_length = 1.0;\nint min_num_views_for_track = 2;\nvoid GetPerspectiveParams(double* aspect_ratio, double* fovy) {\n int width = 800;\n int height = 600;\n double focal_length = 600.0;\n *aspect_ratio = static_cast<double>(width) \/ static_cast<double>(height);\n *fovy = 2 * atan(height \/ (2.0 * focal_length)) * 180.0 \/ M_PI;\n}\n\nvoid ChangeSize(int w, int h) {\n \/\/ Prevent a divide by zero, when window is too short\n \/\/ (you cant make a window of zero width).\n if (h == 0) h = 1;\n\n \/\/ Use the Projection Matrix\n glMatrixMode(GL_PROJECTION);\n\n \/\/ Reset Matrix\n glLoadIdentity();\n\n \/\/ Set the viewport to be the entire window\n double aspect_ratio, fovy;\n GetPerspectiveParams(&aspect_ratio, &fovy);\n glViewport(0, 0, w, h);\n\n \/\/ Set the correct perspective.\n gluPerspective(fovy, aspect_ratio, 0.01f, 100000.0f);\n\n \/\/ Get Back to the Reconstructionview\n glMatrixMode(GL_MODELVIEW);\n}\n\nvoid DrawAxes(float length) {\n glPushAttrib(GL_POLYGON_BIT | GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);\n\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n glDisable(GL_LIGHTING);\n\n glBegin(GL_LINES);\n glColor3f(1.0, 0.0, 0.0);\n glVertex3f(0, 0, 0);\n glVertex3f(length, 0, 0);\n\n glColor3f(0.0, 1.0, 0.0);\n glVertex3f(0, 0, 0);\n glVertex3f(0, length, 0);\n\n glColor3f(0.0, 0.0, 1.0);\n glVertex3f(0, 0, 0);\n glVertex3f(0, 0, length);\n glEnd();\n\n glPopAttrib();\n}\n\nvoid DrawCamera(const theia::Camera& camera) {\n glPushMatrix();\n Eigen::Matrix4d transformation_matrix;\n transformation_matrix.block<3, 3>(0, 0) =\n camera.GetOrientationAsRotationMatrix().transpose();\n transformation_matrix.col(3).head<3>() = camera.GetPosition();\n transformation_matrix(3, 3) = 1.0;\n\n \/\/ Apply world pose transformation.\n glMultMatrixd(reinterpret_cast<GLdouble*>(transformation_matrix.data()));\n\n \/\/ Draw Cameras.\n glColor3f(1.0, 0.0, 0.0);\n\n \/\/ Create the camera wireframe. If intrinsic parameters are not set then use\n \/\/ the focal length as a guess.\n\n \/\/ Use the camera calibration to display the cameras.\n Eigen::Matrix3d calibration;\n camera.GetCalibrationMatrix(&calibration);\n calibration \/= camera.FocalLength();\n calibration(2, 2) = 1.0;\n\n const Eigen::Vector3d top_left =\n normalized_focal_length * (calibration * Eigen::Vector3d(-1, -1, 1));\n const Eigen::Vector3d top_right =\n normalized_focal_length * (calibration * Eigen::Vector3d(1, -1, 1));\n const Eigen::Vector3d bottom_right =\n normalized_focal_length * (calibration * Eigen::Vector3d(1, 1, 1));\n const Eigen::Vector3d bottom_left =\n normalized_focal_length * (calibration * Eigen::Vector3d(-1, 1, 1));\n\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n glBegin(GL_TRIANGLE_FAN);\n glVertex3f(0.0, 0.0, 0.0);\n glVertex3f(top_right[0], top_right[1], top_right[2]);\n glVertex3f(top_left[0], top_left[1], top_left[2]);\n glVertex3f(bottom_left[0], bottom_left[1], bottom_left[2]);\n glVertex3f(bottom_right[0], bottom_right[1], bottom_right[2]);\n glVertex3f(top_right[0], top_right[1], top_right[2]);\n glEnd();\n glPopMatrix();\n}\n\nvoid RenderScene() {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n glTranslatef(-origin[0], -origin[1], -distance);\n glRotatef(180.0f + rot_x, 1.0f, 0.0f, 0.0f);\n glRotatef(-rot_y, 0.0f, 1.0f, 0.0f);\n glClearColor(1.0f, 1.0f, 1.0f, 0.0f);\n\n if (draw_axes) {\n DrawAxes(1.0);\n }\n\n \/\/ Plot the point cloud.\n glDisable(GL_LIGHTING);\n glEnable(GL_MULTISAMPLE);\n glEnable(GL_BLEND);\n glEnable(GL_POINT_SMOOTH);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glPointSize(point_size);\n\n \/\/ the coordinates for calculating point attenuation:\n GLfloat point_size_coords[3];\n point_size_coords[0] = 1.0f;\n point_size_coords[1] = 0.055f;\n point_size_coords[2] = 0.0f;\n glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, point_size_coords);\n\n \/\/ Draw the points.\n glColor3f(0.01, 0.01, 0.01);\n glBegin(GL_POINTS);\n for (int i = 0; i < world_points.size(); i++) {\n if (num_views_for_track[i] < min_num_views_for_track) {\n continue;\n }\n glVertex3d(world_points[i].x(), world_points[i].y(), world_points[i].z());\n }\n glEnd();\n\n \/\/ Draw the cameras.\n if (draw_cameras) {\n for (int i = 0; i < cameras.size(); i++) {\n DrawCamera(cameras[i]);\n }\n }\n glutSwapBuffers();\n}\n\nvoid MouseButton(int button, int state, int x, int y) {\n \/\/ button down: save coordinates\n if (state == GLUT_DOWN && button <= 2) {\n mouse_down_x[button] = x;\n mouse_down_y[button] = y;\n prev_x = x;\n prev_y = y;\n\n if (button == GLUT_RIGHT_BUTTON) {\n mouse_rotates = true;\n } else if (button == GLUT_LEFT_BUTTON) {\n mouse_moves = true;\n }\n return;\n }\n\n if (state == GLUT_UP && button == GLUT_RIGHT_BUTTON) {\n mouse_rotates = false;\n }\n\n if (state == GLUT_UP && button == GLUT_LEFT_BUTTON) {\n mouse_moves = false;\n }\n\n \/\/ scroll event - wheel reports as button 3 (scroll up) and button 4 (scroll\n \/\/ down)\n if ((button == 3) || (button == 4)) {\n \/\/ Each wheel event reports like a button click, GLUT_DOWN then GLUT_UP\n if (state == GLUT_UP) return; \/\/ Disregard redundant GLUT_UP events\n if (button == 3)\n distance \/= 1.5f;\n else\n distance *= 1.5f;\n }\n}\n\nvoid MouseMove(int x, int y) {\n if (mouse_rotates) {\n const double rotate_factor = 0.5f;\n \/\/ notice x & y difference (i.e., changes in x are to rotate about y-axis)\n rot_x -= rotate_factor * (y - prev_y);\n rot_y -= rotate_factor * (x - prev_x);\n prev_x = x;\n prev_y = y;\n } else if (mouse_moves) {\n const double mouse_factor = 0.03f;\n origin.x() -= mouse_factor * (x - prev_x);\n origin.y() += mouse_factor * (y - prev_y);\n prev_x = x;\n prev_y = y;\n }\n}\n\nvoid Keyboard(unsigned char key, int x, int y) {\n switch (key) {\n case 'r': \/\/ reset viewpoint\n distance = 100.0f;\n rot_x = 0.0f;\n rot_y = 0.0f;\n point_size = 1.0;\n origin = Eigen::Vector3d::Zero();\n break;\n case 'z':\n distance \/= 1.2f;\n break;\n case 'Z':\n distance *= 1.2f;\n break;\n case 'p':\n point_size \/= 1.2;\n break;\n case 'P':\n point_size *= 1.2;\n break;\n case 'f':\n normalized_focal_length \/= 1.2;\n break;\n case 'F':\n normalized_focal_length *= 1.2;\n break;\n case 'c':\n draw_cameras = !draw_cameras;\n break;\n case 'a':\n draw_axes = !draw_axes;\n break;\n case 't':\n ++min_num_views_for_track;\n break;\n case 'T':\n --min_num_views_for_track;\n break;\n }\n}\n\n\/\/ initialize viewport etc.\nvoid Init() {\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n\n double aspect_ratio, fovy; \/\/ set the correct perspective.\n GetPerspectiveParams(&aspect_ratio, &fovy);\n gluPerspective(fovy, 1.0, .01, 100000.0);\n\n glMatrixMode(GL_MODELVIEW);\n}\n\nvoid CenterReconstruction() {\n Eigen::Vector3d mean_camera = Eigen::Vector3d::Zero();\n for (int i = 0; i < cameras.size(); i++) {\n mean_camera += cameras[i].GetPosition();\n }\n mean_camera \/= static_cast<double>(cameras.size());\n\n for (int i = 0; i < cameras.size(); i++) {\n const Eigen::Vector3d old_position = cameras[i].GetPosition();\n cameras[i].SetPosition(old_position - mean_camera);\n }\n for (int i = 0; i < world_points.size(); i++) {\n world_points[i] -= mean_camera;\n }\n}\n\nint main(int argc, char* argv[]) {\n THEIA_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n\n \/\/ Output as a binary file.\n std::unique_ptr<theia::Reconstruction> reconstruction(\n new theia::Reconstruction());\n CHECK(ReadReconstruction(FLAGS_reconstruction, reconstruction.get()))\n << \"Could not read reconstruction file.\";\n\n \/\/ Set up camera drawing.\n cameras.reserve(reconstruction->NumViews());\n for (const theia::ViewId view_id : reconstruction->ViewIds()) {\n const auto* view = reconstruction->View(view_id);\n if (view == nullptr || !view->IsEstimated()) {\n continue;\n }\n cameras.emplace_back(view->Camera());\n }\n\n \/\/ Set up world points.\n world_points.reserve(reconstruction->NumTracks());\n for (const theia::TrackId track_id : reconstruction->TrackIds()) {\n const auto* track = reconstruction->Track(track_id);\n if (track == nullptr || !track->IsEstimated()) {\n continue;\n }\n world_points.emplace_back(track->Point().hnormalized());\n num_views_for_track.emplace_back(track->NumViews());\n }\n\n CenterReconstruction();\n\n reconstruction.release();\n\n \/\/ Set up opengl and glut.\n glutInit(&argc, argv);\n glutInitWindowPosition(600, 600);\n glutInitWindowSize(1200, 800);\n glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);\n glutCreateWindow(\"Theia Reconstruction Viewer\");\n\n \/\/ Set the camera\n gluLookAt(0.0f, 0.0f, -6.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);\n\n \/\/ register callbacks\n glutDisplayFunc(RenderScene);\n glutReshapeFunc(ChangeSize);\n glutMouseFunc(MouseButton);\n glutMotionFunc(MouseMove);\n glutKeyboardFunc(Keyboard);\n glutIdleFunc(RenderScene);\n\n \/\/ enter GLUT event processing loop\n glutMainLoop();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Name: xstring\n Copyright: Copyright (C) 2003-2017 SIL International.\n Documentation: \n Description: \n Create Date: 27 Aug 2012\n\n Modified Date: 27 Aug 2012\n Authors: mcdurdin\n Related Files: \n Dependencies: \n\n Bugs: \n Todo: \n Notes: \n History: 27 Aug 2012 - mcdurdin - I3439 - V9.0 - Refactor xstring support in C++ code\n*\/\n#include \"pch.h\"\n\n\n\/*\n*\tint xstrlen( LPBYTE p );\n*\n*\tParameters:\tp\tPointer to string to get length of\n*\n*\tReturns: length of string\n*\n* Called by: various functions\n*\n*\txstrlen calculates the length of a string, ignoring some special chars.\n*\/\n\nPWSTR incxstr(PWSTR p)\n{\n\tif(*p == 0) return p;\n\tif(*p != UC_SENTINEL)\n\t{\n\t\tif(*p >= 0xD800 && *p <= 0xDBFF && *(p+1) >= 0xDC00 && *(p+1) <= 0xDFFF) return p+2;\n\t\treturn p+1;\n\t}\n\n\tp+=2;\n\tswitch(*(p-1))\n\t{\n\t\tcase CODE_ANY:\t\t\treturn p+1;\n\t\tcase CODE_NOTANY: return p+1;\n\t\tcase CODE_INDEX:\t\treturn p+2;\n\t\tcase CODE_USE:\t\t\treturn p+1;\n\t\tcase CODE_DEADKEY:\t\treturn p+1;\n\t\tcase CODE_EXTENDED:\t\tp += 2; while(*p != UC_SENTINEL_EXTENDEDEND) p++; return p+1;\n\t\tcase CODE_CLEARCONTEXT: return p+1;\n\t\tcase CODE_CALL:\t\t\treturn p+1;\n\t\tcase CODE_CONTEXTEX:\treturn p+1;\n case CODE_IFOPT: return p+3;\n case CODE_IFSYSTEMSTORE: return p+3;\n case CODE_SETOPT: return p+2;\n case CODE_SETSYSTEMSTORE: return p+2;\n case CODE_RESETOPT: return p+1;\n case CODE_SAVEOPT: return p+1;\n\t\tdefault:\t\t\t\treturn p;\n\t}\n}\n\nPWSTR decxstr(PWSTR p, PWSTR pStart)\n{\n if (p <= pStart) {\n assert(\"Attempted to move prior to start of string\");\n return NULL;\n }\n\n p--;\n\tif(*p == UC_SENTINEL_EXTENDEDEND)\n\t{\n\t\tint n = 0;\n\t\twhile(*p != UC_SENTINEL && n < 10) { p--; n++; }\n\n if (p < pStart) {\n \/\/ May be a malformed virtual key\n return pStart;\n }\n return p;\n\t}\n\n if (p == pStart) return p; \/\/ Don't allow test before pStart\n\n if(*p >= 0xDC00 && *p <= 0xDFFF && *(p-1) >= 0xD800 && *(p-1) <= 0xDBFF)\n\t{\n\t\treturn p-1;\n\t}\n\telse if(*(p-1) == UC_SENTINEL) return p-1;\n\telse if(p > pStart + 1 && *(p-2) == UC_SENTINEL)\n\t{\n\t\tswitch(*(p-1))\n\t\t{\n\t\t\tcase CODE_ANY:\n\t\t\tcase CODE_NOTANY:\n\t\t\tcase CODE_USE:\n\t\t\tcase CODE_DEADKEY:\n\t\t\tcase CODE_CLEARCONTEXT:\n\t\t\tcase CODE_CALL:\n\t\t\tcase CODE_CONTEXTEX:\n case CODE_RESETOPT: \n case CODE_SAVEOPT: \n return p-2;\n\t\t}\n\t}\n\telse if(p > pStart + 2 && *(p-3) == UC_SENTINEL)\n\t{\n\t\tswitch(*(p-2))\n\t\t{\n\t\t\tcase CODE_INDEX:\n case CODE_SETOPT: \n case CODE_SETSYSTEMSTORE:\n\t\t\t\treturn p-3;\n\t\t}\n\t}\n else if(p > pStart + 3 && *(p-4) == UC_SENTINEL)\n {\n switch(*(p-3))\n {\n case CODE_IFOPT:\n case CODE_IFSYSTEMSTORE: \/\/ I3432\n return p-4;\n }\n }\n\treturn p;\n}\n\nint xstrlen_ignoreifopt(PWSTR p)\n{\n int i;\n for(i = 0; *p; i++, p=incxstr(p))\n {\n if(*p == UC_SENTINEL && (*(p+1) == CODE_IFOPT || *(p+1) == CODE_IFSYSTEMSTORE)) i--; \/\/ I3432\n }\n return i;\n}\n\nint xstrlen(PWSTR p)\n{\n\tint i;\n\tfor(i = 0; *p; i++, p=incxstr(p));\n\treturn i;\n}\n\nint xstrpos(PWSTR p1, PWSTR p)\n{\n int i;\n\tfor(i = 0; p < p1; p = incxstr(p), i++);\n\treturn i;\n}\n\n\/*PWSTR xstrchr(PWSTR buf, int x)\n{\n\tint clow, chigh;\n\tif(x < 0x10000) { chigh = x; clow = -1; }\n\telse { chigh = Uni_UTF32ToSurrogate1(x); clow = Uni_UTF32ToSurrogate2(x); }\n\n\tfor(; *buf; buf = incxstr(buf))\n\t\tif(*buf == chigh && (*(buf+1) == clow || clow == -1)) return buf;\n\treturn NULL;\n}*\/\n\nPWSTR xstrchr(PWSTR buf, PWSTR chr)\n{\n for(PWSTR q = incxstr(buf); *buf; buf = q, q = incxstr(buf))\n if(!wcsncmp(buf, chr, (int)(q-buf)))\n return buf;\n return NULL;\n}\n\nint xchrcmp(PWSTR ch1, PWSTR ch2)\n{\n PWSTR nch1 = incxstr(ch1);\n if(nch1 == ch1) return *ch2 - *ch1; \/* comparing *ch2 to nul *\/\n return wcsncmp(ch1, ch2, (int)(nch1-ch1));\n}\n<commit_msg>fix(windows): pointer casts for x64<commit_after>\/*\n Name: xstring\n Copyright: Copyright (C) 2003-2017 SIL International.\n Documentation:\n Description:\n Create Date: 27 Aug 2012\n\n Modified Date: 27 Aug 2012\n Authors: mcdurdin\n Related Files:\n Dependencies:\n\n Bugs:\n Todo:\n Notes:\n History: 27 Aug 2012 - mcdurdin - I3439 - V9.0 - Refactor xstring support in C++ code\n*\/\n#include \"pch.h\"\n\n\n\/*\n*\tint xstrlen( LPBYTE p );\n*\n*\tParameters:\tp\tPointer to string to get length of\n*\n*\tReturns: length of string\n*\n* Called by: various functions\n*\n*\txstrlen calculates the length of a string, ignoring some special chars.\n*\/\n\nPWSTR incxstr(PWSTR p)\n{\n\tif(*p == 0) return p;\n\tif(*p != UC_SENTINEL)\n\t{\n\t\tif(*p >= 0xD800 && *p <= 0xDBFF && *(p+1) >= 0xDC00 && *(p+1) <= 0xDFFF) return p+2;\n\t\treturn p+1;\n\t}\n\n\tp+=2;\n\tswitch(*(p-1))\n\t{\n\t\tcase CODE_ANY:\t\t\treturn p+1;\n\t\tcase CODE_NOTANY: return p+1;\n\t\tcase CODE_INDEX:\t\treturn p+2;\n\t\tcase CODE_USE:\t\t\treturn p+1;\n\t\tcase CODE_DEADKEY:\t\treturn p+1;\n\t\tcase CODE_EXTENDED:\t\tp += 2; while(*p != UC_SENTINEL_EXTENDEDEND) p++; return p+1;\n\t\tcase CODE_CLEARCONTEXT: return p+1;\n\t\tcase CODE_CALL:\t\t\treturn p+1;\n\t\tcase CODE_CONTEXTEX:\treturn p+1;\n case CODE_IFOPT: return p+3;\n case CODE_IFSYSTEMSTORE: return p+3;\n case CODE_SETOPT: return p+2;\n case CODE_SETSYSTEMSTORE: return p+2;\n case CODE_RESETOPT: return p+1;\n case CODE_SAVEOPT: return p+1;\n\t\tdefault:\t\t\t\treturn p;\n\t}\n}\n\nPWSTR decxstr(PWSTR p, PWSTR pStart)\n{\n if (p <= pStart) {\n assert(\"Attempted to move prior to start of string\");\n return NULL;\n }\n\n p--;\n\tif(*p == UC_SENTINEL_EXTENDEDEND)\n\t{\n\t\tint n = 0;\n\t\twhile(*p != UC_SENTINEL && n < 10) { p--; n++; }\n\n if (p < pStart) {\n \/\/ May be a malformed virtual key\n return pStart;\n }\n return p;\n\t}\n\n if (p == pStart) return p; \/\/ Don't allow test before pStart\n\n if(*p >= 0xDC00 && *p <= 0xDFFF && *(p-1) >= 0xD800 && *(p-1) <= 0xDBFF)\n\t{\n\t\treturn p-1;\n\t}\n\telse if(*(p-1) == UC_SENTINEL) return p-1;\n\telse if(p > pStart + 1 && *(p-2) == UC_SENTINEL)\n\t{\n\t\tswitch(*(p-1))\n\t\t{\n\t\t\tcase CODE_ANY:\n\t\t\tcase CODE_NOTANY:\n\t\t\tcase CODE_USE:\n\t\t\tcase CODE_DEADKEY:\n\t\t\tcase CODE_CLEARCONTEXT:\n\t\t\tcase CODE_CALL:\n\t\t\tcase CODE_CONTEXTEX:\n case CODE_RESETOPT:\n case CODE_SAVEOPT:\n return p-2;\n\t\t}\n\t}\n\telse if(p > pStart + 2 && *(p-3) == UC_SENTINEL)\n\t{\n\t\tswitch(*(p-2))\n\t\t{\n\t\t\tcase CODE_INDEX:\n case CODE_SETOPT:\n case CODE_SETSYSTEMSTORE:\n\t\t\t\treturn p-3;\n\t\t}\n\t}\n else if(p > pStart + 3 && *(p-4) == UC_SENTINEL)\n {\n switch(*(p-3))\n {\n case CODE_IFOPT:\n case CODE_IFSYSTEMSTORE: \/\/ I3432\n return p-4;\n }\n }\n\treturn p;\n}\n\nint xstrlen_ignoreifopt(PWSTR p)\n{\n int i;\n for(i = 0; *p; i++, p=incxstr(p))\n {\n if(*p == UC_SENTINEL && (*(p+1) == CODE_IFOPT || *(p+1) == CODE_IFSYSTEMSTORE)) i--; \/\/ I3432\n }\n return i;\n}\n\nint xstrlen(PWSTR p)\n{\n\tint i;\n\tfor(i = 0; *p; i++, p=incxstr(p));\n\treturn i;\n}\n\nint xstrpos(PWSTR p1, PWSTR p)\n{\n int i;\n\tfor(i = 0; p < p1; p = incxstr(p), i++);\n\treturn i;\n}\n\n\/*PWSTR xstrchr(PWSTR buf, int x)\n{\n\tint clow, chigh;\n\tif(x < 0x10000) { chigh = x; clow = -1; }\n\telse { chigh = Uni_UTF32ToSurrogate1(x); clow = Uni_UTF32ToSurrogate2(x); }\n\n\tfor(; *buf; buf = incxstr(buf))\n\t\tif(*buf == chigh && (*(buf+1) == clow || clow == -1)) return buf;\n\treturn NULL;\n}*\/\n\nPWSTR xstrchr(PWSTR buf, PWSTR chr)\n{\n for(PWSTR q = incxstr(buf); *buf; buf = q, q = incxstr(buf))\n if(!wcsncmp(buf, chr, (intptr_t)(q-buf)))\n return buf;\n return NULL;\n}\n\nint xchrcmp(PWSTR ch1, PWSTR ch2)\n{\n PWSTR nch1 = incxstr(ch1);\n if(nch1 == ch1) return *ch2 - *ch1; \/* comparing *ch2 to nul *\/\n return wcsncmp(ch1, ch2, (intptr_t)(nch1-ch1));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <SFML\/Graphics\/Color.hpp>\n#include <SFML\/Graphics\/RectangleShape.hpp>\n#include <SFML\/Graphics\/RenderTarget.hpp>\n#include <SFML\/Window\/Event.hpp>\n\n#include \"gui\/cursor.hpp\"\n#include \"gui\/scene.hpp\"\n\n#include \"engine\/board.hpp\"\n\n#include \"eventsystem\/eventsystem.hpp\"\n#include \"eventsystem\/inputevents.hpp\"\n\n#include \"foundation\/spritecomponent.hpp\"\n\n#include \"game\/events.hpp\"\n\nnamespace qrw\n{\n\nCursor::Cursor()\n\t: SquareMarker(),\n\t EventHandler()\n{}\n\nCursor::~Cursor()\n{\n}\n\nbool Cursor::handleEvent(const IEvent& event)\n{\n\tif(event.getName() == MouseMovedEvent::name)\n {\n\t\tconst MouseMovedEvent& moveEvent = static_cast<const MouseMovedEvent&>(event);\n\n sf::Vector2f newPosition;\n\t\tsf::Vector2f size = m_spriteComponent->getSize();\n\n\t\tnewPosition.x = moveEvent.worldCoordinates.x - (moveEvent.worldCoordinates.x % (int)size.x);\n\t\tnewPosition.y = moveEvent.worldCoordinates.y - (moveEvent.worldCoordinates.y % (int)size.y);\n\n Coordinates newBoardPosition((int)newPosition.x \/ size.x, (int)newPosition.y \/ size.y);\n\n\t\tif(newBoardPosition != m_boardPosition)\n {\n\t\t\tBoard* board = g_scene.getSingleGameObject<Board>();\n\t\t\tif(board->isOnBoard(newBoardPosition))\n {\n\t\t\t\tsetBoardPosition(newBoardPosition);\n\t\t\t\t setVisible(true);\n }\n else\n {\n\t\t\t\tsetVisible(false);\n }\n\n\t\t\tCursorMovedEvent* event = new CursorMovedEvent(m_boardPosition);\n\t\t\tg_eventSystem.pushEvent(event);\n }\n }\n\telse if(isVisible())\n\t{\n\t\tif(event.getName() == LeftMouseButtonPressedEvent::name)\n\t\t\tg_eventSystem.pushEvent(new CursorLeftClickedEvent(m_boardPosition));\n\t\telse if(event.getName() == RightMouseButtonPressedEvent::name)\n\t\t\tg_eventSystem.pushEvent(new CursorRightClickedEvent(m_boardPosition));\n\t}\n\n\treturn false;\n}\n\n} \/\/ namespace qrwar\n<commit_msg>Fix cursor visibility toggle on board borders<commit_after>#include <iostream>\n#include <math.h>\n\n#include <SFML\/Graphics\/Color.hpp>\n#include <SFML\/Graphics\/RectangleShape.hpp>\n#include <SFML\/Graphics\/RenderTarget.hpp>\n#include <SFML\/Window\/Event.hpp>\n\n#include \"gui\/cursor.hpp\"\n#include \"gui\/scene.hpp\"\n\n#include \"engine\/board.hpp\"\n\n#include \"eventsystem\/eventsystem.hpp\"\n#include \"eventsystem\/inputevents.hpp\"\n\n#include \"foundation\/spritecomponent.hpp\"\n\n#include \"game\/events.hpp\"\n\nnamespace qrw\n{\n\nCursor::Cursor()\n\t: SquareMarker(),\n\t EventHandler()\n{}\n\nCursor::~Cursor()\n{\n}\n\nbool Cursor::handleEvent(const IEvent& event)\n{\n\tstatic int counter = 0;\n\n\tif(event.getName() == MouseMovedEvent::name)\n {\n\t\tconst MouseMovedEvent& moveEvent = static_cast<const MouseMovedEvent&>(event);\n\n\t\tsf::Vector2f size = m_spriteComponent->getSize();\n\n Coordinates newBoardPosition(\n\t\t\tfloor(moveEvent.worldCoordinates.x \/ size.x),\n\t\t\tfloor(moveEvent.worldCoordinates.y \/ size.y));\n\n\t\tif(newBoardPosition != m_boardPosition)\n {\n\t\t\tBoard* board = g_scene.getSingleGameObject<Board>();\n\t\t\tif(board->isOnBoard(newBoardPosition))\n {\n\t\t\t\tsetBoardPosition(newBoardPosition);\n\t\t\t\tsetVisible(true);\n }\n else\n {\n\t\t\t\tm_boardPosition = {-1, -1};\n\t\t\t\tsetVisible(false);\n }\n\n\t\t\tCursorMovedEvent* event = new CursorMovedEvent(m_boardPosition);\n\t\t\tg_eventSystem.pushEvent(event);\n }\n }\n\telse if(isVisible())\n\t{\n\t\tif(event.getName() == LeftMouseButtonPressedEvent::name)\n\t\t\tg_eventSystem.pushEvent(new CursorLeftClickedEvent(m_boardPosition));\n\t\telse if(event.getName() == RightMouseButtonPressedEvent::name)\n\t\t\tg_eventSystem.pushEvent(new CursorRightClickedEvent(m_boardPosition));\n\t}\n\n\treturn false;\n}\n\n} \/\/ namespace qrwar\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsensormanager.h\"\n#include <QDebug>\n#include \"qsensorpluginloader_p.h\"\n#include \"qsensorplugin.h\"\n#include <QSettings>\n#include \"sensorlog_p.h\"\n\nQTM_BEGIN_NAMESPACE\n\nQ_GLOBAL_STATIC_WITH_ARGS(QSensorPluginLoader, pluginLoader, (QSensorPluginInterface_iid, QLatin1String(\"\/sensors\")))\n\ntypedef QHash<QByteArray,QSensorBackendFactory*> FactoryForIdentifierMap;\ntypedef QHash<QByteArray,FactoryForIdentifierMap> BackendIdentifiersForTypeMap;\n\nclass QSensorManagerPrivate\n{\npublic:\n QSensorManagerPrivate()\n : pluginsLoaded(false)\n {\n }\n\n bool pluginsLoaded;\n\n QList<CreatePluginFunc> staticRegistrations;\n\n \/\/ Holds a mapping from type to available identifiers (and from there to the factory)\n BackendIdentifiersForTypeMap backendsByType;\n\n \/\/ Holds the first identifier for each type\n QHash<QByteArray, QByteArray> firstIdentifierForType;\n};\n\nQ_GLOBAL_STATIC(QSensorManagerPrivate, sensorManagerPrivate)\n\nstatic void loadPlugins()\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n d->pluginsLoaded = true;\n\n SENSORLOG() << \"initializing static plugins\";\n Q_FOREACH (CreatePluginFunc func, d->staticRegistrations) {\n QSensorPluginInterface *plugin = func();\n plugin->registerSensors();\n }\n\n SENSORLOG() << \"initializing plugins\";\n Q_FOREACH (QSensorPluginInterface *plugin, pluginLoader()->plugins()) {\n plugin->registerSensors();\n }\n}\n\n\/\/ =====================================================================\n\n\/*!\n \\class QSensorManager\n \\ingroup sensors_backend\n\n \\preliminary\n \\brief The QSensorManager class handles registration and creation of sensor backends.\n\n Sensor plugins register backends using the registerBackend() function.\n\n When QSensor::connect() is called, the createBackend() function will be called.\n*\/\n\n\/*!\n Register a sensor for \\a type. The \\a identifier must be unique.\n\n The \\a factory will be asked to create instances of the backend.\n*\/\nvoid QSensorManager::registerBackend(const QByteArray &type, const QByteArray &identifier, QSensorBackendFactory *factory)\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->backendsByType.contains(type)) {\n (void)d->backendsByType[type];\n d->firstIdentifierForType[type] = identifier;\n }\n SENSORLOG() << \"registering backend for type\" << type << \"identifier\" << identifier;\/\/ << \"factory\" << QString().sprintf(\"0x%08x\", (unsigned int)factory);\n FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type];\n factoryByIdentifier[identifier] = factory;\n}\n\n\/*!\n \\internal\n*\/\nvoid QSensorManager::registerStaticPlugin(CreatePluginFunc func)\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n d->staticRegistrations.append(func);\n}\n\n\/*!\n Create a backend for \\a sensor. Returns null if no suitable backend exists.\n*\/\nQSensorBackend *QSensorManager::createBackend(QSensor *sensor)\n{\n Q_ASSERT(sensor);\n\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->pluginsLoaded)\n loadPlugins();\n\n SENSORLOG() << \"QSensorManager::createBackend\" << \"type\" << sensor->type() << \"identifier\" << sensor->identifier();\n\n if (!d->backendsByType.contains(sensor->type())) {\n SENSORLOG() << \"no backends of type\" << sensor->type() << \"have been registered.\";\n return 0;\n }\n\n const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[sensor->type()];\n QSensorBackendFactory *factory;\n QSensorBackend *backend;\n\n if (sensor->identifier().isEmpty()) {\n QByteArray defaultIdentifier = QSensor::defaultSensorForType(sensor->type());\n SENSORLOG() << \"Trying the default\" << defaultIdentifier;\n \/\/ No identifier set, try the default\n factory = factoryByIdentifier[defaultIdentifier];\n SENSORLOG() << \"factory\" << QString().sprintf(\"0x%08x\", (unsigned int)factory);\n sensor->setIdentifier(defaultIdentifier); \/\/ the factory requires this\n backend = factory->createBackend(sensor);\n if (backend) return backend; \/\/ Got it!\n\n \/\/ The default failed to instantiate so try any other registered sensors for this type\n Q_FOREACH (const QByteArray &identifier, factoryByIdentifier.keys()) {\n SENSORLOG() << \"Trying\" << identifier;\n if (identifier == defaultIdentifier) continue; \/\/ Don't do the default one again\n factory = factoryByIdentifier[identifier];\n SENSORLOG() << \"factory\" << QString().sprintf(\"0x%08x\", (unsigned int)factory);\n sensor->setIdentifier(identifier); \/\/ the factory requires this\n backend = factory->createBackend(sensor);\n if (backend) return backend; \/\/ Got it!\n }\n SENSORLOG() << \"FAILED\";\n sensor->setIdentifier(QByteArray()); \/\/ clear the identifier\n } else {\n if (!factoryByIdentifier.contains(sensor->identifier())) {\n SENSORLOG() << \"no backend with identifier\" << sensor->identifier() << \"for type\" << sensor->type();\n return 0;\n }\n\n \/\/ We were given an explicit identifier so don't substitute other backends if it fails to instantiate\n factory = factoryByIdentifier[sensor->identifier()];\n SENSORLOG() << \"factory\" << QString().sprintf(\"0x%08x\", (unsigned int)factory);\n backend = factory->createBackend(sensor);\n if (backend) return backend; \/\/ Got it!\n }\n\n SENSORLOG() << \"no suitable backend found for requested identifier\" << sensor->identifier() << \"and type\" << sensor->type();\n return 0;\n}\n\n\/\/ =====================================================================\n\n\/*!\n Returns a list of all sensor types.\n*\/\nQList<QByteArray> QSensor::sensorTypes()\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->pluginsLoaded)\n loadPlugins();\n\n return d->backendsByType.keys();\n}\n\n\/*!\n Returns a list of ids for each of the sensors for \\a type.\n If there are no sensors of that type available the list will be empty.\n*\/\nQList<QByteArray> QSensor::sensorsForType(const QByteArray &type)\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->pluginsLoaded)\n loadPlugins();\n\n \/\/ no sensors of that type exist\n if (!d->backendsByType.contains(type))\n return QList<QByteArray>();\n\n return d->backendsByType[type].keys();\n}\n\n\/*!\n Returns the default sensor identifier for \\a type.\n This is set in a config file and can be overridden if required.\n If no default is available the system will return the first registered\n sensor for \\a type.\n*\/\nQByteArray QSensor::defaultSensorForType(const QByteArray &type)\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->pluginsLoaded)\n loadPlugins();\n\n \/\/ no sensors of that type exist\n if (!d->backendsByType.contains(type))\n return QByteArray();\n\n QSettings settings(QLatin1String(\"Nokia\"), QLatin1String(\"Sensors\"));\n QVariant value = settings.value(QString(QLatin1String(\"Default\/%1\")).arg(QString::fromLatin1(type)));\n if (!value.isNull()) {\n QByteArray defaultIdentifier = value.toByteArray();\n if (d->backendsByType[type].contains(defaultIdentifier)) \/\/ Don't return a value that we can't use!\n return defaultIdentifier;\n }\n\n \/\/ This is our fallback\n return d->firstIdentifierForType[type];\n}\n\n\/\/ =====================================================================\n\n\/*!\n \\class QSensorBackendFactory\n \\ingroup sensors_backend\n\n \\preliminary\n \\brief The QSensorBackendFactory class instantiates instances of\n QSensorBackend.\n\n This interface must be implemented in order to register a sensor backend.\n\n \\sa {Creating a sensor plugin}\n*\/\n\n\/*!\n \\fn QSensorBackendFactory::~QSensorBackendFactory()\n \\internal\n*\/\n\n\/*!\n \\fn QSensorBackendFactory::createBackend(QSensor *sensor)\n\n Instantiate a backend. If the factory handles multiple identifiers\n it should check with the \\a sensor to see which one is requested.\n\n If the factory cannot create a backend it should return 0.\n*\/\n\n\/*!\n \\macro REGISTER_STATIC_PLUGIN(pluginname)\n \\relates QSensorManager\n\n Registers a static plugin, \\a pluginname.\n\n Note that this macro relies on static initialization so it may not be appropriate\n for use in a library and may not work on all platforms.\n\n \\sa {Creating a sensor plugin}\n*\/\n\nQTM_END_NAMESPACE\n\n<commit_msg>disable these logs because they break on 64-bit builds.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsensormanager.h\"\n#include <QDebug>\n#include \"qsensorpluginloader_p.h\"\n#include \"qsensorplugin.h\"\n#include <QSettings>\n#include \"sensorlog_p.h\"\n\nQTM_BEGIN_NAMESPACE\n\nQ_GLOBAL_STATIC_WITH_ARGS(QSensorPluginLoader, pluginLoader, (QSensorPluginInterface_iid, QLatin1String(\"\/sensors\")))\n\ntypedef QHash<QByteArray,QSensorBackendFactory*> FactoryForIdentifierMap;\ntypedef QHash<QByteArray,FactoryForIdentifierMap> BackendIdentifiersForTypeMap;\n\nclass QSensorManagerPrivate\n{\npublic:\n QSensorManagerPrivate()\n : pluginsLoaded(false)\n {\n }\n\n bool pluginsLoaded;\n\n QList<CreatePluginFunc> staticRegistrations;\n\n \/\/ Holds a mapping from type to available identifiers (and from there to the factory)\n BackendIdentifiersForTypeMap backendsByType;\n\n \/\/ Holds the first identifier for each type\n QHash<QByteArray, QByteArray> firstIdentifierForType;\n};\n\nQ_GLOBAL_STATIC(QSensorManagerPrivate, sensorManagerPrivate)\n\nstatic void loadPlugins()\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n d->pluginsLoaded = true;\n\n SENSORLOG() << \"initializing static plugins\";\n Q_FOREACH (CreatePluginFunc func, d->staticRegistrations) {\n QSensorPluginInterface *plugin = func();\n plugin->registerSensors();\n }\n\n SENSORLOG() << \"initializing plugins\";\n Q_FOREACH (QSensorPluginInterface *plugin, pluginLoader()->plugins()) {\n plugin->registerSensors();\n }\n}\n\n\/\/ =====================================================================\n\n\/*!\n \\class QSensorManager\n \\ingroup sensors_backend\n\n \\preliminary\n \\brief The QSensorManager class handles registration and creation of sensor backends.\n\n Sensor plugins register backends using the registerBackend() function.\n\n When QSensor::connect() is called, the createBackend() function will be called.\n*\/\n\n\/*!\n Register a sensor for \\a type. The \\a identifier must be unique.\n\n The \\a factory will be asked to create instances of the backend.\n*\/\nvoid QSensorManager::registerBackend(const QByteArray &type, const QByteArray &identifier, QSensorBackendFactory *factory)\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->backendsByType.contains(type)) {\n (void)d->backendsByType[type];\n d->firstIdentifierForType[type] = identifier;\n }\n SENSORLOG() << \"registering backend for type\" << type << \"identifier\" << identifier;\/\/ << \"factory\" << QString().sprintf(\"0x%08x\", (unsigned int)factory);\n FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type];\n factoryByIdentifier[identifier] = factory;\n}\n\n\/*!\n \\internal\n*\/\nvoid QSensorManager::registerStaticPlugin(CreatePluginFunc func)\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n d->staticRegistrations.append(func);\n}\n\n\/*!\n Create a backend for \\a sensor. Returns null if no suitable backend exists.\n*\/\nQSensorBackend *QSensorManager::createBackend(QSensor *sensor)\n{\n Q_ASSERT(sensor);\n\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->pluginsLoaded)\n loadPlugins();\n\n SENSORLOG() << \"QSensorManager::createBackend\" << \"type\" << sensor->type() << \"identifier\" << sensor->identifier();\n\n if (!d->backendsByType.contains(sensor->type())) {\n SENSORLOG() << \"no backends of type\" << sensor->type() << \"have been registered.\";\n return 0;\n }\n\n const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[sensor->type()];\n QSensorBackendFactory *factory;\n QSensorBackend *backend;\n\n if (sensor->identifier().isEmpty()) {\n QByteArray defaultIdentifier = QSensor::defaultSensorForType(sensor->type());\n SENSORLOG() << \"Trying the default\" << defaultIdentifier;\n \/\/ No identifier set, try the default\n factory = factoryByIdentifier[defaultIdentifier];\n \/\/SENSORLOG() << \"factory\" << QString().sprintf(\"0x%08x\", (unsigned int)factory);\n sensor->setIdentifier(defaultIdentifier); \/\/ the factory requires this\n backend = factory->createBackend(sensor);\n if (backend) return backend; \/\/ Got it!\n\n \/\/ The default failed to instantiate so try any other registered sensors for this type\n Q_FOREACH (const QByteArray &identifier, factoryByIdentifier.keys()) {\n SENSORLOG() << \"Trying\" << identifier;\n if (identifier == defaultIdentifier) continue; \/\/ Don't do the default one again\n factory = factoryByIdentifier[identifier];\n \/\/SENSORLOG() << \"factory\" << QString().sprintf(\"0x%08x\", (unsigned int)factory);\n sensor->setIdentifier(identifier); \/\/ the factory requires this\n backend = factory->createBackend(sensor);\n if (backend) return backend; \/\/ Got it!\n }\n SENSORLOG() << \"FAILED\";\n sensor->setIdentifier(QByteArray()); \/\/ clear the identifier\n } else {\n if (!factoryByIdentifier.contains(sensor->identifier())) {\n SENSORLOG() << \"no backend with identifier\" << sensor->identifier() << \"for type\" << sensor->type();\n return 0;\n }\n\n \/\/ We were given an explicit identifier so don't substitute other backends if it fails to instantiate\n factory = factoryByIdentifier[sensor->identifier()];\n \/\/SENSORLOG() << \"factory\" << QString().sprintf(\"0x%08x\", (unsigned int)factory);\n backend = factory->createBackend(sensor);\n if (backend) return backend; \/\/ Got it!\n }\n\n SENSORLOG() << \"no suitable backend found for requested identifier\" << sensor->identifier() << \"and type\" << sensor->type();\n return 0;\n}\n\n\/\/ =====================================================================\n\n\/*!\n Returns a list of all sensor types.\n*\/\nQList<QByteArray> QSensor::sensorTypes()\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->pluginsLoaded)\n loadPlugins();\n\n return d->backendsByType.keys();\n}\n\n\/*!\n Returns a list of ids for each of the sensors for \\a type.\n If there are no sensors of that type available the list will be empty.\n*\/\nQList<QByteArray> QSensor::sensorsForType(const QByteArray &type)\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->pluginsLoaded)\n loadPlugins();\n\n \/\/ no sensors of that type exist\n if (!d->backendsByType.contains(type))\n return QList<QByteArray>();\n\n return d->backendsByType[type].keys();\n}\n\n\/*!\n Returns the default sensor identifier for \\a type.\n This is set in a config file and can be overridden if required.\n If no default is available the system will return the first registered\n sensor for \\a type.\n*\/\nQByteArray QSensor::defaultSensorForType(const QByteArray &type)\n{\n QSensorManagerPrivate *d = sensorManagerPrivate();\n if (!d->pluginsLoaded)\n loadPlugins();\n\n \/\/ no sensors of that type exist\n if (!d->backendsByType.contains(type))\n return QByteArray();\n\n QSettings settings(QLatin1String(\"Nokia\"), QLatin1String(\"Sensors\"));\n QVariant value = settings.value(QString(QLatin1String(\"Default\/%1\")).arg(QString::fromLatin1(type)));\n if (!value.isNull()) {\n QByteArray defaultIdentifier = value.toByteArray();\n if (d->backendsByType[type].contains(defaultIdentifier)) \/\/ Don't return a value that we can't use!\n return defaultIdentifier;\n }\n\n \/\/ This is our fallback\n return d->firstIdentifierForType[type];\n}\n\n\/\/ =====================================================================\n\n\/*!\n \\class QSensorBackendFactory\n \\ingroup sensors_backend\n\n \\preliminary\n \\brief The QSensorBackendFactory class instantiates instances of\n QSensorBackend.\n\n This interface must be implemented in order to register a sensor backend.\n\n \\sa {Creating a sensor plugin}\n*\/\n\n\/*!\n \\fn QSensorBackendFactory::~QSensorBackendFactory()\n \\internal\n*\/\n\n\/*!\n \\fn QSensorBackendFactory::createBackend(QSensor *sensor)\n\n Instantiate a backend. If the factory handles multiple identifiers\n it should check with the \\a sensor to see which one is requested.\n\n If the factory cannot create a backend it should return 0.\n*\/\n\n\/*!\n \\macro REGISTER_STATIC_PLUGIN(pluginname)\n \\relates QSensorManager\n\n Registers a static plugin, \\a pluginname.\n\n Note that this macro relies on static initialization so it may not be appropriate\n for use in a library and may not work on all platforms.\n\n \\sa {Creating a sensor plugin}\n*\/\n\nQTM_END_NAMESPACE\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 Steinwurf ApS\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 met:\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 the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Steinwurf ApS nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY 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\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"buffer.hpp\"\n\n#include <algorithm>\n\nnamespace sak\n{\n\n buffer::buffer()\n : m_size(0)\n { }\n\n buffer::buffer(uint32_t capacity)\n : m_size(0)\n {\n m_vector.resize(capacity);\n }\n\n void buffer::append(const uint8_t* data, uint32_t size)\n {\n assert(data != 0);\n assert(size > 0);\n\n if (m_size + size > m_vector.size())\n {\n m_vector.resize(m_size + size);\n }\n\n std::copy_n(data, size, &m_vector[m_size]);\n m_size += size;\n }\n\n void buffer::append(const uint8_t* data_start, const uint8_t* data_end)\n {\n assert(data_start != 0);\n assert(data_end != 0);\n assert(data_start < data_end);\n\n uint32_t size = static_cast<uint32_t>(data_end - data_start);\n append(data_start, size);\n }\n\n const uint8_t* buffer::data() const\n {\n return &m_vector[0];\n }\n\n uint8_t* buffer::data()\n {\n return &m_vector[0];\n }\n\n uint32_t buffer::size() const\n {\n return m_size;\n }\n\n void buffer::resize(uint32_t size)\n {\n \/\/ Currently our re-allocation strategy is not\n \/\/ to \"shrink\" the buffer. If at some point this\n \/\/ should become important in an application\n \/\/ we could add that possibility as a reallocation-policy\n\n if (size <= m_vector.size())\n {\n m_size = size;\n }\n else\n {\n m_vector.resize(size);\n m_size = size;\n }\n }\n\n void buffer::clear()\n {\n m_size = 0;\n }\n\n}\n<commit_msg>Test buffer::append overload<commit_after>\/\/ Copyright (c) 2012 Steinwurf ApS\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 met:\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 the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Steinwurf ApS nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY 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\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"buffer.hpp\"\n\n#include <algorithm>\n\nnamespace sak\n{\n\n buffer::buffer()\n : m_size(0)\n { }\n\n buffer::buffer(uint32_t capacity)\n : m_size(0)\n {\n m_vector.resize(capacity);\n }\n\n void buffer::append(const uint8_t* data, uint32_t size)\n {\n assert(data != 0);\n assert(size > 0);\n\n if (m_size + size > m_vector.size())\n {\n m_vector.resize(m_size + size);\n }\n\n std::copy_n(data, size, &m_vector[m_size]);\n m_size += size;\n }\n\n\/\/ void buffer::append(const uint8_t* data_start, const uint8_t* data_end)\n\/\/ {\n\/\/ assert(data_start != 0);\n\/\/ assert(data_end != 0);\n\/\/ assert(data_start < data_end);\n\/\/\n\/\/ uint32_t size = static_cast<uint32_t>(data_end - data_start);\n\/\/ append(data_start, size);\n\/\/ }\n\n const uint8_t* buffer::data() const\n {\n return &m_vector[0];\n }\n\n uint8_t* buffer::data()\n {\n return &m_vector[0];\n }\n\n uint32_t buffer::size() const\n {\n return m_size;\n }\n\n void buffer::resize(uint32_t size)\n {\n \/\/ Currently our re-allocation strategy is not\n \/\/ to \"shrink\" the buffer. If at some point this\n \/\/ should become important in an application\n \/\/ we could add that possibility as a reallocation-policy\n\n if (size <= m_vector.size())\n {\n m_size = size;\n }\n else\n {\n m_vector.resize(size);\n m_size = size;\n }\n }\n\n void buffer::clear()\n {\n m_size = 0;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"nAIControl.hpp\"\n\n#include <typeindex>\n#include <algorithm>\n#include <iostream>\n#include <random>\n\n#include \"cAIControl.hpp\"\n#include \"cLiving.hpp\"\n#include \"..\/ec\/cPosition.hpp\"\n#include \"..\/ec\/cVelocity.hpp\"\n#include \"AI\/pathFinder.hpp\"\n#include \"..\/context.hpp\"\n#include \"utility.hpp\"\n#include \"cPathFinderRef.hpp\"\n#include \"cPowerup.hpp\"\n#include \"cPickup.hpp\"\n#include \"..\/ec\/engine.hpp\"\n#include \"direction.hpp\"\n#include \"cWIndicator.hpp\"\n#include \"cBalloon.hpp\"\n\nnAIControl::nAIControl() :\ncontrol(nullptr),\nliving(nullptr),\npos(nullptr),\nvel(nullptr),\nprevDest(-1)\n{}\n\nbool nAIControl::checkEntity(Entity& entity)\n{\n return entity.hasComponent(std::type_index(typeid(cAIControl))) &&\n entity.hasComponent(std::type_index(typeid(cLiving))) &&\n entity.hasComponent(std::type_index(typeid(cPosition))) &&\n entity.hasComponent(std::type_index(typeid(cVelocity))) &&\n entity.hasComponent(std::type_index(typeid(cPathFinderRef)));\n}\n\nstd::unique_ptr<Node> nAIControl::getNewNode()\n{\n return std::unique_ptr<Node>(new nAIControl);\n}\n\nvoid nAIControl::getCReferencesFromEntity(Entity& entity)\n{\n control = static_cast<cAIControl*>(entity.getComponent(std::type_index(typeid(cAIControl))));\n living = static_cast<cLiving*>(entity.getComponent(std::type_index(typeid(cLiving))));\n pos = static_cast<cPosition*>(entity.getComponent(std::type_index(typeid(cPosition))));\n vel = static_cast<cVelocity*>(entity.getComponent(std::type_index(typeid(cVelocity))));\n pfref = static_cast<cPathFinderRef*>(entity.getComponent(std::type_index(typeid(cPathFinderRef))));\n entityRemoved = &entity.removed;\n}\n\nvoid nAIControl::update(sf::Time dt, Context context)\n{\n if(*entityRemoved)\n return;\n\n bool justPlacedBalloon = false;\n control->timer -= dt.asSeconds();\n if(control->timer <= 0.0f || control->currentAction == AI::NONE)\n {\n control->timer = control->aiTickTime;\n control->currentAction = control->ai.determineAction(*pos, *living, *control->pf, *context.ecEngine, *context.rGen);\n if(living->kickUpgrade == 0)\n paths = control->pf->getValidDestinations(*pos, *context.ecEngine, 0x16);\n else\n paths = control->pf->getValidDestinations(*pos, *context.ecEngine, 0x14);\n\n const unsigned char* grid = control->pf->getValidGrid(*context.ecEngine);\n\n int xy = (int)((pos->x + (float)(-GRID_OFFSET_X + GRID_SQUARE_SIZE \/ 2)) \/ GRID_SQUARE_SIZE) + (int)((pos->y + (float)(-GRID_OFFSET_Y + GRID_SQUARE_SIZE \/ 2)) \/ GRID_SQUARE_SIZE) * GRID_WIDTH;\n int prev, destination = -1;\n std::uniform_int_distribution<> dist(0,paths.size() - 1);\n int r = dist(*context.rGen);\n\n std::clog << \"STATE: \" << control->currentAction << '\\n';\n vel->x = 0.0f;\n vel->y = 0.0f;\n\n if(prevDest == -1)\n {\n switch(control->currentAction)\n {\n case AI::PLACE_BALLOON:\n justPlacedBalloon = true;\n Utility::createBalloon(pos->x, pos->y, *living, context, control->ID, &control->fired, *pfref);\n control->timer = 0.0f;\n control->pf->invalidateValidGrid();\n break;\n case AI::GET_POWERUP:\n break;\n case AI::MOVE_TO_ENEMY:\n break;\n case AI::MOVE_TO_BREAKABLE:\n destination = -1;\n for(auto iter = paths.begin(); iter != paths.end(); ++iter)\n {\n if((iter->first % GRID_WIDTH != 0 && (grid[iter->first - 1] & 0x4) != 0) ||\n (iter->first % GRID_WIDTH != GRID_WIDTH - 1 && (grid[iter->first + 1] & 0x4) != 0) ||\n (iter->first - GRID_WIDTH >= 0 && (grid[iter->first - GRID_WIDTH] & 0x4) != 0) ||\n (iter->first + GRID_WIDTH < GRID_TOTAL && (grid[iter->first + GRID_WIDTH] & 0x4) != 0))\n {\n destination = iter->first;\n if(r <= 0)\n break;\n }\n --r;\n }\n if(destination == -1)\n {\n std::clog << \"WARNING: failed to find adjacent breakable\\n\";\n control->timer = 0.0f;\n break;\n }\n break;\n case AI::MOVE_TO_SAFETY:\n destination = -1;\n for(auto iter = paths.begin(); iter != paths.end(); ++iter)\n {\n if((grid[iter->first] & 0x36) == 0)\n {\n destination = iter->first;\n if(r <= 0)\n break;\n }\n --r;\n }\n if(destination == -1)\n {\n std::clog << \"WARNING: failed to find safe spot\\n\";\n control->timer = 0.0f;\n break;\n }\n break;\n case AI::KICK_BALLOON:\n break;\n case AI::PANIC:\n break;\n case AI::WAIT:\n control->timer = BALLOON_ALIVE_TIME;\n break;\n default:\n break;\n }\n }\n if(destination != -1 || prevDest != -1)\n {\n if(prevDest != -1)\n destination = prevDest;\n Direction::Direction prevDir = Direction::NONE;\n Direction::Direction destDir = Direction::NONE;\n if(destination != xy && Utility::isAligned(pos->x, pos->y))\n {\n std::map<int,int> rpaths;\n int dest = destination;\n prevDest = destination;\n while(destination != xy)\n {\n rpaths.insert(std::make_pair(paths[destination], destination));\n destination = paths[destination];\n }\n\n int i = GRID_TOTAL;\n destination = xy;\n prev = destination;\n while(destination != dest)\n {\n destination = rpaths[destination];\n if(destination % GRID_WIDTH == prev % GRID_WIDTH)\n {\n destDir = Direction::VERTICAL;\n }\n else\n {\n destDir = Direction::HORIZONTAL;\n }\n\n if(prevDir == Direction::NONE)\n prevDir = destDir;\n else if(prevDir != destDir)\n break;\n prev = destination;\n\n if(i-- == 0)\n break;\n }\n if(prevDir == Direction::NONE)\n prevDir = destDir;\n if(destination == prevDest)\n prevDest = -1;\n }\n else\n prevDir = Direction::PLUS;\n\n if(prevDir == Direction::VERTICAL)\n {\n if(prev < xy)\n {\n vel->x = 0.0f;\n vel->y = -DEFAULT_SPEED - SPEED_UP_MULT * (float)living->speedUp;\n control->timer = (float)((xy \/ GRID_WIDTH - prev \/ GRID_WIDTH) * GRID_SQUARE_SIZE) \/ -vel->y;\n }\n else\n {\n vel->x = 0.0f;\n vel->y = DEFAULT_SPEED + SPEED_UP_MULT * (float)living->speedUp;\n if(prev == xy)\n control->timer = 0.0f;\n else\n control->timer = (float)((prev \/ GRID_WIDTH - xy \/ GRID_WIDTH) * GRID_SQUARE_SIZE) \/ vel->y;\n }\n }\n else if(prevDir == Direction::HORIZONTAL)\n {\n if(prev < xy)\n {\n vel->x = -DEFAULT_SPEED - SPEED_UP_MULT * (float)living->speedUp;\n vel->y = 0.0f;\n control->timer = (float)((xy - prev) * GRID_SQUARE_SIZE) \/ -vel->x;\n }\n else\n {\n vel->x = DEFAULT_SPEED + SPEED_UP_MULT * (float)living->speedUp;\n vel->y = 0.0f;\n if(prev == xy)\n control->timer = 0.0f;\n else\n control->timer = (float)((prev - xy) * GRID_SQUARE_SIZE) \/ vel->x;\n }\n }\n else if(prevDir == Direction::PLUS)\n {\n float offsetx = (pos->x - (float)GRID_OFFSET_X) \/ (float)GRID_SQUARE_SIZE;\n float offsety = (pos->y - (float)GRID_OFFSET_Y) \/ (float)GRID_SQUARE_SIZE;\n float x = xy % GRID_WIDTH;\n float y = xy \/ GRID_WIDTH;\n if(offsetx < x)\n {\n vel->x = -DEFAULT_SPEED - SPEED_UP_MULT * (float)living->speedUp;\n vel->y = 0.0f;\n control->timer = (pos->x - offsetx) \/ -vel->x;\n }\n else if(offsetx > x)\n {\n vel->x = DEFAULT_SPEED + SPEED_UP_MULT * (float)living->speedUp;\n vel->y = 0.0f;\n control->timer = (offsetx - pos->x) \/ vel->x;\n }\n else if(offsety < y)\n {\n vel->x = 0.0f;\n vel->y = -DEFAULT_SPEED - SPEED_UP_MULT * (float)living->speedUp;\n control->timer = (pos->y - offsety) \/ -vel->y;\n }\n else if(offsety >= y)\n {\n vel->x = 0.0f;\n vel->y = DEFAULT_SPEED + SPEED_UP_MULT * (float)living->speedUp;\n if(offsety != y)\n control->timer = (offsety - pos->y) \/ vel->y;\n else\n control->timer = 0.0f;\n }\n }\n else\n {\n std::cerr << \"ERROR: Failed to validate next tile on move\\n\";\n std::clog << \"prev is \" << prev << '\\n';\n control->timer = 0.0f;\n }\n }\n }\n\n HitInfo powerinfo = Utility::collideAgainstComponent(pos->x, pos->y, std::type_index(typeid(cPickup)), *context.ecEngine);\n for(auto piter = powerinfo.hit.begin(); piter != powerinfo.hit.end(); ++piter)\n {\n cPowerup* powerup = static_cast<cPowerup*>((*piter)->getComponent(std::type_index(typeid(cPowerup))));\n\n switch(powerup->powerup)\n {\n case cPowerup::BALLOON_UP:\n ++(living->balloonUp);\n break;\n case cPowerup::RANGE_UP:\n ++(living->rangeUp);\n break;\n case cPowerup::SPEED_UP:\n ++(living->speedUp);\n break;\n case cPowerup::KICK_UPGRADE:\n ++(living->kickUpgrade);\n break;\n case cPowerup::RCONTROL_UPGRADE:\n ++(living->rControlUpgrade);\n break;\n case cPowerup::SBALLOON_UPGRADE:\n ++(living->sBalloonUpgrade);\n break;\n case cPowerup::PIERCE_UPGRADE:\n ++(living->pierceUpgrade);\n break;\n case cPowerup::SPREAD_UPGRADE:\n ++(living->spreadUpgrade);\n break;\n case cPowerup::GHOST_UPGRADE:\n ++(living->ghostUpgrade);\n break;\n default:\n break;\n }\n\n context.ecEngine->removeEntity((*piter)->getID());\n }\n\n if(living->rControlUpgrade > 0)\n {\n bool inDanger = Utility::collidesAgainstComponent(pos->x, pos->y, std::type_index(typeid(cWIndicator)), *context.ecEngine);\n if(justPlacedBalloon || inDanger)\n {\n control->fired = false;\n }\n else if(!justPlacedBalloon && !inDanger)\n {\n control->fired = true;\n }\n }\n}\n<commit_msg>minor fixes<commit_after>\n#include \"nAIControl.hpp\"\n\n#include <typeindex>\n#include <algorithm>\n#include <iostream>\n#include <random>\n\n#include \"cAIControl.hpp\"\n#include \"cLiving.hpp\"\n#include \"..\/ec\/cPosition.hpp\"\n#include \"..\/ec\/cVelocity.hpp\"\n#include \"AI\/pathFinder.hpp\"\n#include \"..\/context.hpp\"\n#include \"utility.hpp\"\n#include \"cPathFinderRef.hpp\"\n#include \"cPowerup.hpp\"\n#include \"cPickup.hpp\"\n#include \"..\/ec\/engine.hpp\"\n#include \"direction.hpp\"\n#include \"cWIndicator.hpp\"\n#include \"cBalloon.hpp\"\n\nnAIControl::nAIControl() :\ncontrol(nullptr),\nliving(nullptr),\npos(nullptr),\nvel(nullptr),\nprevDest(-1)\n{}\n\nbool nAIControl::checkEntity(Entity& entity)\n{\n return entity.hasComponent(std::type_index(typeid(cAIControl))) &&\n entity.hasComponent(std::type_index(typeid(cLiving))) &&\n entity.hasComponent(std::type_index(typeid(cPosition))) &&\n entity.hasComponent(std::type_index(typeid(cVelocity))) &&\n entity.hasComponent(std::type_index(typeid(cPathFinderRef)));\n}\n\nstd::unique_ptr<Node> nAIControl::getNewNode()\n{\n return std::unique_ptr<Node>(new nAIControl);\n}\n\nvoid nAIControl::getCReferencesFromEntity(Entity& entity)\n{\n control = static_cast<cAIControl*>(entity.getComponent(std::type_index(typeid(cAIControl))));\n living = static_cast<cLiving*>(entity.getComponent(std::type_index(typeid(cLiving))));\n pos = static_cast<cPosition*>(entity.getComponent(std::type_index(typeid(cPosition))));\n vel = static_cast<cVelocity*>(entity.getComponent(std::type_index(typeid(cVelocity))));\n pfref = static_cast<cPathFinderRef*>(entity.getComponent(std::type_index(typeid(cPathFinderRef))));\n entityRemoved = &entity.removed;\n}\n\nvoid nAIControl::update(sf::Time dt, Context context)\n{\n if(*entityRemoved)\n return;\n\n bool justPlacedBalloon = false;\n control->timer -= dt.asSeconds();\n if(control->timer <= 0.0f || control->currentAction == AI::NONE)\n {\n control->timer = control->aiTickTime;\n control->currentAction = control->ai.determineAction(*pos, *living, *control->pf, *context.ecEngine, *context.rGen);\n if(Utility::collidesAgainstComponent(pos->x, pos->y, std::type_index(typeid(cWIndicator)), *context.ecEngine))\n {\n if(living->kickUpgrade == 0)\n paths = control->pf->getValidDestinations(*pos, *context.ecEngine, 0x16);\n else\n paths = control->pf->getValidDestinations(*pos, *context.ecEngine, 0x14);\n }\n else\n {\n if(living->kickUpgrade == 0)\n paths = control->pf->getValidDestinations(*pos, *context.ecEngine, 0x36);\n else\n paths = control->pf->getValidDestinations(*pos, *context.ecEngine, 0x34);\n }\n\n const unsigned char* grid = control->pf->getValidGrid(*context.ecEngine);\n\n int xy = (int)((pos->x + (float)(-GRID_OFFSET_X + GRID_SQUARE_SIZE \/ 2)) \/ GRID_SQUARE_SIZE) + (int)((pos->y + (float)(-GRID_OFFSET_Y + GRID_SQUARE_SIZE \/ 2)) \/ GRID_SQUARE_SIZE) * GRID_WIDTH;\n int prev, destination = -1;\n std::uniform_int_distribution<> dist(0,paths.size() - 1);\n int r = dist(*context.rGen);\n\n std::clog << \"STATE: \" << control->currentAction << '\\n';\n vel->x = 0.0f;\n vel->y = 0.0f;\n\n if(prevDest == -1)\n {\n switch(control->currentAction)\n {\n case AI::PLACE_BALLOON:\n justPlacedBalloon = true;\n Utility::createBalloon(pos->x, pos->y, *living, context, control->ID, &control->fired, *pfref);\n control->timer = 0.0f;\n control->pf->invalidateValidGrid();\n break;\n case AI::GET_POWERUP:\n destination = -1;\n for(auto iter = paths.begin(); iter != paths.end(); ++iter)\n {\n if((grid[iter->first] & 0x8) != 0)\n {\n destination = iter->first;\n if(r <= 0)\n break;\n }\n --r;\n }\n if(destination == -1)\n {\n std::clog << \"WARNING: failed to find valid powerup path\\n\";\n control->timer = 0.0f;\n break;\n }\n break;\n case AI::MOVE_TO_ENEMY:\n break;\n case AI::MOVE_TO_BREAKABLE:\n destination = -1;\n for(auto iter = paths.begin(); iter != paths.end(); ++iter)\n {\n if((iter->first % GRID_WIDTH != 0 && (grid[iter->first - 1] & 0x4) != 0) ||\n (iter->first % GRID_WIDTH != GRID_WIDTH - 1 && (grid[iter->first + 1] & 0x4) != 0) ||\n (iter->first - GRID_WIDTH >= 0 && (grid[iter->first - GRID_WIDTH] & 0x4) != 0) ||\n (iter->first + GRID_WIDTH < GRID_TOTAL && (grid[iter->first + GRID_WIDTH] & 0x4) != 0))\n {\n destination = iter->first;\n if(r <= 0)\n break;\n }\n --r;\n }\n if(destination == -1)\n {\n std::clog << \"WARNING: failed to find adjacent breakable\\n\";\n control->timer = 0.0f;\n break;\n }\n break;\n case AI::MOVE_TO_SAFETY:\n destination = -1;\n for(auto iter = paths.begin(); iter != paths.end(); ++iter)\n {\n if((grid[iter->first] & 0x36) == 0)\n {\n destination = iter->first;\n if(r <= 0)\n break;\n }\n --r;\n }\n if(destination == -1)\n {\n std::clog << \"WARNING: failed to find safe spot\\n\";\n control->timer = 0.0f;\n break;\n }\n break;\n case AI::KICK_BALLOON:\n break;\n case AI::PANIC:\n break;\n case AI::WAIT:\n control->timer = BALLOON_ALIVE_TIME;\n break;\n default:\n break;\n }\n }\n if(destination != -1 || prevDest != -1)\n {\n if(prevDest != -1)\n destination = prevDest;\n Direction::Direction prevDir = Direction::NONE;\n Direction::Direction destDir = Direction::NONE;\n if(destination != xy && Utility::isAligned(pos->x, pos->y))\n {\n std::map<int,int> rpaths;\n int dest = destination;\n prevDest = destination;\n while(destination != xy)\n {\n if(paths.find(destination) == paths.end())\n break;\n rpaths.insert(std::make_pair(paths[destination], destination));\n destination = paths[destination];\n }\n\n int i = GRID_TOTAL;\n destination = xy;\n prev = destination;\n while(destination != dest)\n {\n destination = rpaths[destination];\n if(destination % GRID_WIDTH == prev % GRID_WIDTH)\n {\n destDir = Direction::VERTICAL;\n }\n else\n {\n destDir = Direction::HORIZONTAL;\n }\n\n if(prevDir == Direction::NONE)\n prevDir = destDir;\n else if(prevDir != destDir)\n break;\n prev = destination;\n\n if(i-- == 0)\n break;\n }\n if(prevDir == Direction::NONE)\n prevDir = destDir;\n if(destination == prevDest)\n prevDest = -1;\n }\n else\n prevDir = Direction::PLUS;\n\n if(prevDir == Direction::VERTICAL)\n {\n if(prev < xy)\n {\n vel->x = 0.0f;\n vel->y = -DEFAULT_SPEED - SPEED_UP_MULT * (float)living->speedUp;\n control->timer = (float)((xy \/ GRID_WIDTH - prev \/ GRID_WIDTH) * GRID_SQUARE_SIZE) \/ -vel->y;\n }\n else\n {\n vel->x = 0.0f;\n vel->y = DEFAULT_SPEED + SPEED_UP_MULT * (float)living->speedUp;\n if(prev == xy)\n control->timer = 0.0f;\n else\n control->timer = (float)((prev \/ GRID_WIDTH - xy \/ GRID_WIDTH) * GRID_SQUARE_SIZE) \/ vel->y;\n }\n }\n else if(prevDir == Direction::HORIZONTAL)\n {\n if(prev < xy)\n {\n vel->x = -DEFAULT_SPEED - SPEED_UP_MULT * (float)living->speedUp;\n vel->y = 0.0f;\n control->timer = (float)((xy - prev) * GRID_SQUARE_SIZE) \/ -vel->x;\n }\n else\n {\n vel->x = DEFAULT_SPEED + SPEED_UP_MULT * (float)living->speedUp;\n vel->y = 0.0f;\n if(prev == xy)\n control->timer = 0.0f;\n else\n control->timer = (float)((prev - xy) * GRID_SQUARE_SIZE) \/ vel->x;\n }\n }\n else if(prevDir == Direction::PLUS)\n {\n float offsetx = (pos->x - (float)GRID_OFFSET_X) \/ (float)GRID_SQUARE_SIZE;\n float offsety = (pos->y - (float)GRID_OFFSET_Y) \/ (float)GRID_SQUARE_SIZE;\n float x = xy % GRID_WIDTH;\n float y = xy \/ GRID_WIDTH;\n if(offsetx < x)\n {\n vel->x = -DEFAULT_SPEED - SPEED_UP_MULT * (float)living->speedUp;\n vel->y = 0.0f;\n control->timer = (pos->x - offsetx) \/ -vel->x;\n }\n else if(offsetx > x)\n {\n vel->x = DEFAULT_SPEED + SPEED_UP_MULT * (float)living->speedUp;\n vel->y = 0.0f;\n control->timer = (offsetx - pos->x) \/ vel->x;\n }\n else if(offsety < y)\n {\n vel->x = 0.0f;\n vel->y = -DEFAULT_SPEED - SPEED_UP_MULT * (float)living->speedUp;\n control->timer = (pos->y - offsety) \/ -vel->y;\n }\n else if(offsety >= y)\n {\n vel->x = 0.0f;\n vel->y = DEFAULT_SPEED + SPEED_UP_MULT * (float)living->speedUp;\n if(offsety != y)\n control->timer = (offsety - pos->y) \/ vel->y;\n else\n control->timer = 0.0f;\n }\n }\n else\n {\n std::cerr << \"ERROR: Failed to validate next tile on move\\n\";\n std::clog << \"prev is \" << prev << '\\n';\n control->timer = 0.0f;\n }\n }\n }\n\n HitInfo powerinfo = Utility::collideAgainstComponent(pos->x, pos->y, std::type_index(typeid(cPickup)), *context.ecEngine);\n for(auto piter = powerinfo.hit.begin(); piter != powerinfo.hit.end(); ++piter)\n {\n cPowerup* powerup = static_cast<cPowerup*>((*piter)->getComponent(std::type_index(typeid(cPowerup))));\n\n switch(powerup->powerup)\n {\n case cPowerup::BALLOON_UP:\n ++(living->balloonUp);\n break;\n case cPowerup::RANGE_UP:\n ++(living->rangeUp);\n break;\n case cPowerup::SPEED_UP:\n ++(living->speedUp);\n break;\n case cPowerup::KICK_UPGRADE:\n ++(living->kickUpgrade);\n break;\n case cPowerup::RCONTROL_UPGRADE:\n ++(living->rControlUpgrade);\n break;\n case cPowerup::SBALLOON_UPGRADE:\n ++(living->sBalloonUpgrade);\n break;\n case cPowerup::PIERCE_UPGRADE:\n ++(living->pierceUpgrade);\n break;\n case cPowerup::SPREAD_UPGRADE:\n ++(living->spreadUpgrade);\n break;\n case cPowerup::GHOST_UPGRADE:\n ++(living->ghostUpgrade);\n break;\n default:\n break;\n }\n\n context.ecEngine->removeEntity((*piter)->getID());\n }\n\n if(living->rControlUpgrade > 0)\n {\n bool inDanger = Utility::collidesAgainstComponent(pos->x, pos->y, std::type_index(typeid(cWIndicator)), *context.ecEngine);\n if(justPlacedBalloon || inDanger)\n {\n control->fired = false;\n }\n else if(!justPlacedBalloon && !inDanger)\n {\n control->fired = true;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"scanner.h\"\n\n#include <algorithm>\n\n#include \"exp.h\"\n#include \"stream.h\"\n#include \"yaml-cpp\/exceptions.h\" \/\/ IWYU pragma: keep\n\nnamespace YAML {\n\nint Scanner::MatchScalarEmpty(Exp::Source<4>) {\n \/\/ This is checked by !INPUT as well\n return -1;\n}\n\nint Scanner::MatchScalarSingleQuoted(Exp::Source<4> in) {\n using namespace Exp;\n return (Matcher<Char<'\\''>>::Matches(in) &&\n !EscSingleQuote::Matches(in)) ? 1 : -1;\n}\n\nint Scanner::MatchScalarDoubleQuoted(Exp::Source<4> in) {\n using namespace Exp;\n return Matcher<Char<'\\\"'>>::Match(in);\n}\n\nint Scanner::MatchScalarEnd(Exp::Source<4> in) {\n using namespace Exp;\n using ScalarEnd = Matcher<\n OR < SEQ < Char<':'>,\n OR < detail::BlankOrBreak, Empty>>,\n SEQ < detail::BlankOrBreak,\n detail::Comment>>>;\n\n return ScalarEnd::Match(in);\n}\n\nint Scanner::MatchScalarEndInFlow(Exp::Source<4> in) {\n using namespace Exp;\n using ScalarEndInFlow = Matcher <\n OR < SEQ < Char<':'>,\n OR < detail::Blank,\n Char<','>,\n Char<']'>,\n Char<'}'>,\n detail::Break,\n Empty >>,\n Char<','>,\n Char<'?'>,\n Char<'['>,\n Char<']'>,\n Char<'{'>,\n Char<'}'>,\n SEQ < detail::BlankOrBreak,\n detail::Comment>>>;\n\n return ScalarEndInFlow::Match(in);\n}\n\nint Scanner::MatchScalarIndent(Exp::Source<4> in) {\n using namespace Exp;\n using ScalarEndInFlow = Matcher <\n SEQ < detail::Blank,\n detail::Comment>>;\n\n return ScalarEndInFlow::Match(in);\n}\n\nstatic bool MatchDocIndicator(const Stream& in) {\n using namespace Exp;\n using DocIndicator = Matcher<OR <detail::DocStart, detail::DocEnd>>;\n\n return DocIndicator::Matches(in);\n}\n\n\nstruct ScanResult {\n bool foundNonEmptyLine = false;\n bool escapedNewline = false;\n int endMatch = -1;\n std::size_t lastNonWhitespaceChar;\n std::size_t lastEscapedChar = std::string::npos;\n};\n\nstatic void EatToIndentation(Stream& INPUT, ScanScalarParams& params, bool foundEmptyLine);\n\nstatic void EatAfterIndentation(Stream& INPUT, ScanScalarParams& params);\n\nstatic void PostProcess(std::string& scalar, ScanScalarParams& params, size_t lastEscapedChar);\n\nstatic int HandleFolding(std::string& scalar, const ScanScalarParams& params,\n int column, bool escapedNewline,\n bool emptyLine, bool moreIndented,\n bool nextEmptyLine, bool nextMoreIndented,\n bool foundNonEmptyLine,\n bool foldedNewlineStartedMoreIndented,\n int foldedNewlineCount);\n\nstatic void ScanLine(Stream& INPUT, const ScanScalarParams& params,\n std::string& scalar, ScanResult& out);\n\/\/#define TEST_NO_INLINE __attribute__((noinline))\n#define TEST_NO_INLINE\n\n\/\/ ScanScalar\n\/\/ . This is where the scalar magic happens.\n\/\/\n\/\/ . We do the scanning in three phases:\n\/\/ 1. Scan until newline\n\/\/ 2. Eat newline\n\/\/ 3. Scan leading blanks.\n\/\/\n\/\/ . Depending on the parameters given, we store or stop\n\/\/ and different places in the above flow.\nstd::string Scanner::ScanScalar(ScanScalarParams& params) {\n\n bool emptyLine = false;\n bool moreIndented = false;\n bool foldedNewlineStartedMoreIndented = false;\n bool pastOpeningBreak = (params.fold == FOLD_FLOW);\n\n int foldedNewlineCount = 0;\n std::string scalar;\n\n ScanResult r;\n\n params.leadingSpaces = false;\n\n while (INPUT) {\n \/\/ ********************************\n \/\/ Phase #1: scan until line ending\n\n ScanLine(INPUT, params, scalar, r);\n pastOpeningBreak |= r.foundNonEmptyLine;\n\n \/\/ eof? if we're looking to eat something, then we throw\n if (!INPUT) {\n if (params.eatEnd) {\n throw ParserException(INPUT.mark(), ErrorMsg::EOF_IN_SCALAR);\n }\n break;\n }\n\n \/\/ doc indicator?\n if (params.onDocIndicator == BREAK && INPUT.column() == 0) {\n if (MatchDocIndicator(INPUT)) {\n break;\n }\n }\n\n \/\/ are we done via character match?\n if (r.endMatch >= 0) {\n if (params.eatEnd) {\n INPUT.eat(r.endMatch);\n }\n break;\n }\n\n \/\/ do we remove trailing whitespace?\n if (params.fold == FOLD_FLOW) {\n if (r.lastNonWhitespaceChar < scalar.size()) {\n scalar.erase(r.lastNonWhitespaceChar);\n }\n }\n \/\/ ********************************\n \/\/ Phase #2: eat line ending\n assert(INPUT.EatLineBreak());\n\n \/\/ ********************************\n \/\/ Phase #3: scan initial spaces\n\n EatToIndentation(INPUT, params, !r.foundNonEmptyLine);\n\n \/\/ update indent if we're auto-detecting\n if (params.detectIndent && !r.foundNonEmptyLine) {\n params.indent = std::max(params.indent, INPUT.column());\n }\n\n \/\/ and then the rest of the whitespace\n if (INPUT.peek() == ' ' || INPUT.peek() == '\\t') {\n EatAfterIndentation(INPUT, params);\n }\n\n \/\/ was this an empty line?\n Exp::Source<4> input;\n INPUT.LookaheadBuffer(input);\n bool nextEmptyLine = Exp::Break::Matches(input);\n bool nextMoreIndented = Exp::Blank::Matches(input);\n if (params.fold == FOLD_BLOCK && foldedNewlineCount == 0 && nextEmptyLine)\n foldedNewlineStartedMoreIndented = moreIndented;\n\n if (pastOpeningBreak) {\n foldedNewlineCount = HandleFolding(scalar, params, INPUT.column(),\n r.escapedNewline,\n emptyLine, moreIndented,\n nextEmptyLine, nextMoreIndented,\n r.foundNonEmptyLine,\n foldedNewlineStartedMoreIndented,\n foldedNewlineCount);\n }\n\n emptyLine = nextEmptyLine;\n moreIndented = nextMoreIndented;\n pastOpeningBreak = true;\n\n \/\/ are we done via indentation?\n if (!emptyLine && INPUT.column() < params.indent) {\n params.leadingSpaces = true;\n break;\n }\n }\n\n PostProcess(scalar, params, r.lastEscapedChar);\n\n return scalar;\n}\n\n\nTEST_NO_INLINE\nstatic void ScanLine(Stream& INPUT, const ScanScalarParams& params,\n std::string& scalar, ScanResult& out) {\n\n const size_t bufferSize = 256;\n char buffer[bufferSize];\n size_t bufferFill = 0;\n size_t scalarLength = scalar.length();\n\n out.lastNonWhitespaceChar = scalarLength;\n out.escapedNewline = false;\n\n while (INPUT) {\n\n \/\/ find break posiion\n Exp::Source<4> input;\n INPUT.LookaheadBuffer(input);\n\n \/\/ space 0x20 : 0010000ß\n \/\/ tab 0x09 : 00001001\n \/\/ LF 0x0A : 00001010\n \/\/ CR 0x0D : 00001101\n bool isWhiteSpace = false;\n\n if ((input[0] & 0x28) != 0) {\n isWhiteSpace = Exp::Blank::Matches(input);\n if (!isWhiteSpace) {\n if (Exp::Break::Matches(input)) {\n break;\n }\n \/\/ document indicator?\n if (unlikely(INPUT.column() == 0) &&\n MatchDocIndicator(INPUT)) {\n\n if (params.onDocIndicator == BREAK) {\n break;\n } else if (params.onDocIndicator == THROW) {\n throw ParserException(INPUT.mark(), ErrorMsg::DOC_IN_SCALAR);\n }\n }\n }\n }\n\n \/\/ keep end posiion\n if ((out.endMatch = params.end(input)) >= 0) {\n break;\n }\n\n out.foundNonEmptyLine = true;\n\n if (likely(params.escape != input[0])) {\n \/\/ just add the character\n if (unlikely(bufferFill == bufferSize)) {\n scalar.insert(scalar.size(), buffer, bufferSize);\n bufferFill = 0;\n }\n\n buffer[bufferFill++] = input[0];\n\n scalarLength++;\n\n INPUT.eat();\n\n if (!isWhiteSpace) {\n out.lastNonWhitespaceChar = scalarLength;\n }\n\n } else {\n \/\/ escaped newline? (only if we're escaping on slash)\n if (params.escape == '\\\\' && Exp::EscBreak::Matches(input)) {\n \/\/ eat escape character and get out (but preserve trailing whitespace!)\n INPUT.eat();\n out.lastEscapedChar = out.lastNonWhitespaceChar = scalarLength;\n out.escapedNewline = true;\n break;\n\n } else {\n if (bufferFill > 0) {\n scalar.insert(scalar.size(), buffer, bufferFill);\n bufferFill = 0;\n }\n\n scalar += Exp::Escape(INPUT);\n scalarLength = scalar.size();\n\n out.lastEscapedChar = out.lastNonWhitespaceChar = scalarLength;\n }\n }\n }\n\n if (bufferFill > 0) {\n scalar.insert(scalar.size(), buffer, bufferFill);\n }\n}\n\nTEST_NO_INLINE\nstatic void EatToIndentation(Stream& INPUT, ScanScalarParams& params, bool foundEmptyLine) {\n\n using namespace Exp;\n\n using _ = Char<' '>;\n\n using SpaceInvaders = Matcher<Count<_,_,_,_,_,_,_,_>>;\n\n \/\/ first the required indentation\n \/\/ This can be:\n \/\/ - BlockScalar (detectIndent\/colum<indent)\n \/\/ - PlainScalar (colum<indent) \/\n int max = params.indent - INPUT.column();\n if (params.detectIndent && foundEmptyLine) {\n max = std::numeric_limits<int>::max();\n }\n\n \/\/ Don't eat the whitespace before comments\n while (max > 0) {\n\n auto input = INPUT.GetLookaheadBuffer(8);\n\n int pos = SpaceInvaders::Match(input);\n\n \/\/ No, nothing to eat!\n if (pos == 0) { break; }\n\n \/\/ Pos can be up to 8. Dont eat before potential comment.\n if (params.indentFn && (pos == 8 || input[pos] == '#')) {\n pos -= 1;\n }\n if (max < pos) { pos = max; }\n\n \/\/ Eat spaces\n for (int i = 0; i < pos; i++) {\n INPUT.eat();\n }\n\n if (pos < 7 || input[7] != ' ') {\n break;\n }\n max -= pos;\n }\n}\n\nTEST_NO_INLINE\nstatic void EatAfterIndentation(Stream& INPUT, ScanScalarParams& params) {\n\n for (char c = INPUT.peek(); (c == ' ' || c == '\\t'); c = INPUT.peek()) {\n \/\/ we check for tabs that masquerade as indentation\n if (c == '\\t' && INPUT.column() < params.indent &&\n params.onTabInIndentation == THROW) {\n throw ParserException(INPUT.mark(), ErrorMsg::TAB_IN_INDENTATION);\n }\n\n if (!params.eatLeadingWhitespace) {\n break;\n }\n \/\/ FIXME: 2\n Exp::Source<4> input;\n INPUT.LookaheadBuffer(input);\n if (params.indentFn && params.indentFn(input) >= 0) {\n break;\n }\n \/\/printf(\"check 2\\n\");\n\n INPUT.eat();\n }\n}\n\nTEST_NO_INLINE\nstatic int HandleFolding(std::string& scalar,\n const ScanScalarParams& params,\n int column, bool escapedNewline,\n bool emptyLine, bool moreIndented,\n bool nextEmptyLine, bool nextMoreIndented,\n bool foundNonEmptyLine,\n bool foldedNewlineStartedMoreIndented,\n int foldedNewlineCount) {\n\n \/\/ for block scalars, we always start with a newline, so we should ignore it\n \/\/ (not fold or keep)\n switch (params.fold) {\n case DONT_FOLD:\n scalar += '\\n';\n break;\n case FOLD_BLOCK:\n if (!emptyLine && !nextEmptyLine && !moreIndented &&\n !nextMoreIndented && column >= params.indent) {\n scalar += ' ';\n } else if (nextEmptyLine) {\n foldedNewlineCount++;\n } else {\n scalar += '\\n';\n }\n\n if (!nextEmptyLine && foldedNewlineCount > 0) {\n scalar += std::string(foldedNewlineCount - 1, '\\n');\n if (foldedNewlineStartedMoreIndented ||\n nextMoreIndented | !foundNonEmptyLine) {\n scalar += '\\n';\n }\n foldedNewlineCount = 0;\n }\n break;\n case FOLD_FLOW:\n if (nextEmptyLine) {\n scalar += '\\n';\n } else if (!emptyLine && !nextEmptyLine && !escapedNewline) {\n scalar += ' ';\n }\n break;\n }\n return foldedNewlineCount;\n}\n\nTEST_NO_INLINE\nstatic void PostProcess(std::string& scalar, ScanScalarParams& params, size_t lastEscapedChar) {\n \/\/ post-processing\n if (params.trimTrailingSpaces) {\n std::size_t pos = scalar.size()-1;\n while (pos != std::string::npos && scalar[pos] == ' ') { pos--; }\n \/\/std::size_t pos = scalar.find_last_not_of(' ');\n\n if (lastEscapedChar != std::string::npos) {\n if (pos < lastEscapedChar || pos == std::string::npos) {\n pos = lastEscapedChar;\n }\n }\n if (pos < scalar.size()) {\n scalar.erase(pos + 1);\n }\n }\n\n switch (params.chomp) {\n case CLIP: {\n std::size_t pos = scalar.find_last_not_of('\\n');\n if (lastEscapedChar != std::string::npos) {\n if (pos < lastEscapedChar || pos == std::string::npos) {\n pos = lastEscapedChar;\n }\n }\n if (pos == std::string::npos) {\n scalar.erase();\n } else if (pos + 1 < scalar.size()) {\n scalar.erase(pos + 2);\n }\n } break;\n case STRIP: {\n std::size_t pos = scalar.find_last_not_of('\\n');\n if (lastEscapedChar != std::string::npos) {\n if (pos < lastEscapedChar || pos == std::string::npos) {\n pos = lastEscapedChar;\n }\n }\n if (pos == std::string::npos) {\n scalar.erase();\n } else if (pos < scalar.size()) {\n scalar.erase(pos + 1);\n }\n } break;\n default:\n break;\n }\n}\n\n}\n<commit_msg>cleanup ScanScalar<commit_after>#include \"scanner.h\"\n\n#include <algorithm>\n\n#include \"exp.h\"\n#include \"stream.h\"\n#include \"yaml-cpp\/exceptions.h\" \/\/ IWYU pragma: keep\n\nnamespace YAML {\n\nint Scanner::MatchScalarEmpty(Exp::Source<4>) {\n \/\/ This is checked by !INPUT as well\n return -1;\n}\n\nint Scanner::MatchScalarSingleQuoted(Exp::Source<4> in) {\n using namespace Exp;\n return (Matcher<Char<'\\''>>::Matches(in) &&\n !EscSingleQuote::Matches(in)) ? 1 : -1;\n}\n\nint Scanner::MatchScalarDoubleQuoted(Exp::Source<4> in) {\n using namespace Exp;\n return Matcher<Char<'\\\"'>>::Match(in);\n}\n\nint Scanner::MatchScalarEnd(Exp::Source<4> in) {\n using namespace Exp;\n using ScalarEnd = Matcher<\n OR < SEQ < Char<':'>,\n OR < detail::BlankOrBreak, Empty>>,\n SEQ < detail::BlankOrBreak,\n detail::Comment>>>;\n\n return ScalarEnd::Match(in);\n}\n\nint Scanner::MatchScalarEndInFlow(Exp::Source<4> in) {\n using namespace Exp;\n using ScalarEndInFlow = Matcher <\n OR < SEQ < Char<':'>,\n OR < detail::Blank,\n Char<','>,\n Char<']'>,\n Char<'}'>,\n detail::Break,\n Empty >>,\n Char<','>,\n Char<'?'>,\n Char<'['>,\n Char<']'>,\n Char<'{'>,\n Char<'}'>,\n SEQ < detail::BlankOrBreak,\n detail::Comment>>>;\n\n return ScalarEndInFlow::Match(in);\n}\n\nint Scanner::MatchScalarIndent(Exp::Source<4> in) {\n using namespace Exp;\n using ScalarEndInFlow = Matcher <\n SEQ < detail::Blank,\n detail::Comment>>;\n\n return ScalarEndInFlow::Match(in);\n}\n\nstatic bool MatchDocIndicator(const Stream& in) {\n using namespace Exp;\n using DocIndicator = Matcher<OR <detail::DocStart, detail::DocEnd>>;\n\n return DocIndicator::Matches(in);\n}\n\n\nstruct ScanResult {\n bool foundNonEmptyLine = false;\n bool escapedNewline = false;\n int endMatch = -1;\n std::size_t lastNonWhitespaceChar;\n std::size_t lastEscapedChar = std::string::npos;\n};\n\nstatic void EatToIndentation(Stream& INPUT, ScanScalarParams& params, bool foundEmptyLine);\n\nstatic void EatAfterIndentation(Stream& INPUT, ScanScalarParams& params);\n\nstatic void PostProcess(std::string& scalar, ScanScalarParams& params, size_t lastEscapedChar);\n\nstatic int HandleFolding(std::string& scalar, const ScanScalarParams& params,\n int column, bool escapedNewline,\n bool emptyLine, bool moreIndented,\n bool nextEmptyLine, bool nextMoreIndented,\n bool foundNonEmptyLine,\n bool foldedNewlineStartedMoreIndented,\n int foldedNewlineCount);\n\nstatic void ScanLine(Stream& INPUT, const ScanScalarParams& params,\n std::string& scalar, ScanResult& out);\n\/\/#define TEST_NO_INLINE __attribute__((noinline))\n#define TEST_NO_INLINE\n\n\/\/ ScanScalar\n\/\/ . This is where the scalar magic happens.\n\/\/\n\/\/ . We do the scanning in three phases:\n\/\/ 1. Scan until newline\n\/\/ 2. Eat newline\n\/\/ 3. Scan leading blanks.\n\/\/\n\/\/ . Depending on the parameters given, we store or stop\n\/\/ and different places in the above flow.\nstd::string Scanner::ScanScalar(ScanScalarParams& params) {\n\n bool emptyLine = false;\n bool moreIndented = false;\n bool foldedNewlineStartedMoreIndented = false;\n bool pastOpeningBreak = (params.fold == FOLD_FLOW);\n\n int foldedNewlineCount = 0;\n std::string scalar;\n\n ScanResult r;\n\n params.leadingSpaces = false;\n\n while (INPUT) {\n \/\/ ********************************\n \/\/ Phase #1: scan until line ending\n\n ScanLine(INPUT, params, scalar, r);\n pastOpeningBreak |= r.foundNonEmptyLine;\n\n \/\/ eof? if we're looking to eat something, then we throw\n if (!INPUT) {\n if (params.eatEnd) {\n throw ParserException(INPUT.mark(), ErrorMsg::EOF_IN_SCALAR);\n }\n break;\n }\n\n \/\/ doc indicator?\n if (params.onDocIndicator == BREAK && INPUT.column() == 0) {\n if (MatchDocIndicator(INPUT)) {\n break;\n }\n }\n\n \/\/ are we done via character match?\n if (r.endMatch >= 0) {\n if (params.eatEnd) {\n INPUT.eat(r.endMatch);\n }\n break;\n }\n\n \/\/ do we remove trailing whitespace?\n if (params.fold == FOLD_FLOW) {\n if (r.lastNonWhitespaceChar < scalar.size()) {\n scalar.erase(r.lastNonWhitespaceChar);\n }\n }\n \/\/ ********************************\n \/\/ Phase #2: eat line ending\n assert(INPUT.EatLineBreak());\n\n \/\/ ********************************\n \/\/ Phase #3: scan initial spaces\n\n EatToIndentation(INPUT, params, !r.foundNonEmptyLine);\n\n \/\/ update indent if we're auto-detecting\n if (params.detectIndent && !r.foundNonEmptyLine) {\n params.indent = std::max(params.indent, INPUT.column());\n }\n\n \/\/ and then the rest of the whitespace\n if (INPUT.peek() == ' ' || INPUT.peek() == '\\t') {\n EatAfterIndentation(INPUT, params);\n }\n\n \/\/ was this an empty line?\n Exp::Source<4> input;\n INPUT.LookaheadBuffer(input);\n bool nextEmptyLine = Exp::Break::Matches(input);\n bool nextMoreIndented = Exp::Blank::Matches(input);\n if (params.fold == FOLD_BLOCK && foldedNewlineCount == 0 && nextEmptyLine)\n foldedNewlineStartedMoreIndented = moreIndented;\n\n if (pastOpeningBreak) {\n foldedNewlineCount = HandleFolding(scalar, params, INPUT.column(),\n r.escapedNewline,\n emptyLine, moreIndented,\n nextEmptyLine, nextMoreIndented,\n r.foundNonEmptyLine,\n foldedNewlineStartedMoreIndented,\n foldedNewlineCount);\n }\n\n emptyLine = nextEmptyLine;\n moreIndented = nextMoreIndented;\n pastOpeningBreak = true;\n\n \/\/ are we done via indentation?\n if (!emptyLine && INPUT.column() < params.indent) {\n params.leadingSpaces = true;\n break;\n }\n }\n\n PostProcess(scalar, params, r.lastEscapedChar);\n\n return scalar;\n}\n\n\nTEST_NO_INLINE\nstatic void ScanLine(Stream& INPUT, const ScanScalarParams& params,\n std::string& scalar, ScanResult& out) {\n\n const size_t bufferSize = 256;\n char buffer[bufferSize];\n size_t bufferFill = 0;\n size_t scalarLength = scalar.length();\n\n out.lastNonWhitespaceChar = scalarLength;\n out.escapedNewline = false;\n\n while (INPUT) {\n\n Exp::Source<4> input;\n INPUT.LookaheadBuffer(input);\n\n bool isWhiteSpace = Exp::Blank::Matches(input);\n\n if (!isWhiteSpace) {\n if (Exp::Break::Matches(input)) { break; }\n\n \/\/ document indicator?\n if (unlikely(INPUT.column() == 0) &&\n MatchDocIndicator(INPUT)) {\n if (params.onDocIndicator == BREAK) {\n break;\n } else if (params.onDocIndicator == THROW) {\n throw ParserException(INPUT.mark(), ErrorMsg::DOC_IN_SCALAR);\n }\n }\n }\n\n \/\/ keep end posiion\n if ((out.endMatch = params.end(input)) >= 0) {\n break;\n }\n\n out.foundNonEmptyLine = true;\n\n if (likely(params.escape != input[0])) {\n \/\/ just add the character\n if (unlikely(bufferFill == bufferSize)) {\n scalar.insert(scalar.size(), buffer, bufferSize);\n bufferFill = 0;\n }\n\n buffer[bufferFill++] = input[0];\n\n scalarLength++;\n\n INPUT.eat();\n\n if (!isWhiteSpace) {\n out.lastNonWhitespaceChar = scalarLength;\n }\n\n } else {\n \/\/ escaped newline? (only if we're escaping on slash)\n if (params.escape == '\\\\' && Exp::EscBreak::Matches(input)) {\n \/\/ eat escape character and get out (but preserve trailing whitespace!)\n INPUT.eat();\n out.lastEscapedChar = out.lastNonWhitespaceChar = scalarLength;\n out.escapedNewline = true;\n break;\n\n } else {\n if (bufferFill > 0) {\n scalar.insert(scalar.size(), buffer, bufferFill);\n bufferFill = 0;\n }\n\n scalar += Exp::Escape(INPUT);\n scalarLength = scalar.size();\n\n out.lastEscapedChar = out.lastNonWhitespaceChar = scalarLength;\n }\n }\n }\n\n if (bufferFill > 0) {\n scalar.insert(scalar.size(), buffer, bufferFill);\n }\n}\n\nTEST_NO_INLINE\nstatic void EatToIndentation(Stream& INPUT, ScanScalarParams& params, bool foundEmptyLine) {\n\n using namespace Exp;\n\n using _ = Char<' '>;\n\n using SpaceInvaders = Matcher<Count<_,_,_,_,_,_,_,_>>;\n\n \/\/ first the required indentation\n \/\/ This can be:\n \/\/ - BlockScalar (detectIndent\/colum<indent)\n \/\/ - PlainScalar (colum<indent) \/\n int max = params.indent - INPUT.column();\n if (params.detectIndent && foundEmptyLine) {\n max = std::numeric_limits<int>::max();\n }\n\n \/\/ Don't eat the whitespace before comments\n while (max > 0) {\n\n auto input = INPUT.GetLookaheadBuffer(8);\n\n int pos = SpaceInvaders::Match(input);\n\n \/\/ No, nothing to eat!\n if (pos == 0) { break; }\n\n \/\/ Pos can be up to 8. Dont eat before potential comment.\n if (params.indentFn && (pos == 8 || input[pos] == '#')) {\n pos -= 1;\n }\n if (max < pos) { pos = max; }\n\n \/\/ Eat spaces\n for (int i = 0; i < pos; i++) {\n INPUT.eat();\n }\n\n if (pos < 7 || input[7] != ' ') {\n break;\n }\n max -= pos;\n }\n}\n\nTEST_NO_INLINE\nstatic void EatAfterIndentation(Stream& INPUT, ScanScalarParams& params) {\n\n for (char c = INPUT.peek(); (c == ' ' || c == '\\t'); c = INPUT.peek()) {\n \/\/ we check for tabs that masquerade as indentation\n if (c == '\\t' && INPUT.column() < params.indent &&\n params.onTabInIndentation == THROW) {\n throw ParserException(INPUT.mark(), ErrorMsg::TAB_IN_INDENTATION);\n }\n\n if (!params.eatLeadingWhitespace) {\n break;\n }\n \/\/ FIXME: 2\n Exp::Source<4> input;\n INPUT.LookaheadBuffer(input);\n if (params.indentFn && params.indentFn(input) >= 0) {\n break;\n }\n \/\/printf(\"check 2\\n\");\n\n INPUT.eat();\n }\n}\n\nTEST_NO_INLINE\nstatic int HandleFolding(std::string& scalar,\n const ScanScalarParams& params,\n int column, bool escapedNewline,\n bool emptyLine, bool moreIndented,\n bool nextEmptyLine, bool nextMoreIndented,\n bool foundNonEmptyLine,\n bool foldedNewlineStartedMoreIndented,\n int foldedNewlineCount) {\n\n \/\/ for block scalars, we always start with a newline, so we should ignore it\n \/\/ (not fold or keep)\n switch (params.fold) {\n case DONT_FOLD:\n scalar += '\\n';\n break;\n case FOLD_BLOCK:\n if (!emptyLine && !nextEmptyLine && !moreIndented &&\n !nextMoreIndented && column >= params.indent) {\n scalar += ' ';\n } else if (nextEmptyLine) {\n foldedNewlineCount++;\n } else {\n scalar += '\\n';\n }\n\n if (!nextEmptyLine && foldedNewlineCount > 0) {\n scalar += std::string(foldedNewlineCount - 1, '\\n');\n if (foldedNewlineStartedMoreIndented ||\n nextMoreIndented | !foundNonEmptyLine) {\n scalar += '\\n';\n }\n foldedNewlineCount = 0;\n }\n break;\n case FOLD_FLOW:\n if (nextEmptyLine) {\n scalar += '\\n';\n } else if (!emptyLine && !nextEmptyLine && !escapedNewline) {\n scalar += ' ';\n }\n break;\n }\n return foldedNewlineCount;\n}\n\nTEST_NO_INLINE\nstatic void PostProcess(std::string& scalar, ScanScalarParams& params, size_t lastEscapedChar) {\n \/\/ post-processing\n if (params.trimTrailingSpaces) {\n std::size_t pos = scalar.size()-1;\n while (pos != std::string::npos && scalar[pos] == ' ') { pos--; }\n \/\/std::size_t pos = scalar.find_last_not_of(' ');\n\n if (lastEscapedChar != std::string::npos) {\n if (pos < lastEscapedChar || pos == std::string::npos) {\n pos = lastEscapedChar;\n }\n }\n if (pos < scalar.size()) {\n scalar.erase(pos + 1);\n }\n }\n\n switch (params.chomp) {\n case CLIP: {\n std::size_t pos = scalar.find_last_not_of('\\n');\n if (lastEscapedChar != std::string::npos) {\n if (pos < lastEscapedChar || pos == std::string::npos) {\n pos = lastEscapedChar;\n }\n }\n if (pos == std::string::npos) {\n scalar.erase();\n } else if (pos + 1 < scalar.size()) {\n scalar.erase(pos + 2);\n }\n } break;\n case STRIP: {\n std::size_t pos = scalar.find_last_not_of('\\n');\n if (lastEscapedChar != std::string::npos) {\n if (pos < lastEscapedChar || pos == std::string::npos) {\n pos = lastEscapedChar;\n }\n }\n if (pos == std::string::npos) {\n scalar.erase();\n } else if (pos < scalar.size()) {\n scalar.erase(pos + 1);\n }\n } break;\n default:\n break;\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"crt.h\"\n#include \"scanscalar.h\"\n#include \"scanner.h\"\n#include \"exp.h\"\n#include \"exceptions.h\"\n#include \"token.h\"\n\nnamespace YAML\n{\n\t\/\/ ScanScalar\n\t\/\/ . This is where the scalar magic happens.\n\t\/\/\n\t\/\/ . We do the scanning in three phases:\n\t\/\/ 1. Scan until newline\n\t\/\/ 2. Eat newline\n\t\/\/ 3. Scan leading blanks.\n\t\/\/\n\t\/\/ . Depending on the parameters given, we store or stop\n\t\/\/ and different places in the above flow.\n\tstd::string ScanScalar(Stream& INPUT, ScanScalarParams& params)\n\t{\n\t\tbool foundNonEmptyLine = false, pastOpeningBreak = false;\n\t\tbool emptyLine = false, moreIndented = false;\n\t\tstd::string scalar;\n\t\tparams.leadingSpaces = false;\n\n\t\twhile(INPUT) {\n\t\t\t\/\/ ********************************\n\t\t\t\/\/ Phase #1: scan until line ending\n\t\t\twhile(!params.end.Matches(INPUT) && !Exp::Break.Matches(INPUT)) {\n\t\t\t\tif(!INPUT)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\/\/ document indicator?\n\t\t\t\tif(INPUT.column() == 0 && Exp::DocIndicator.Matches(INPUT)) {\n\t\t\t\t\tif(params.onDocIndicator == BREAK)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse if(params.onDocIndicator == THROW)\n\t\t\t\t\t\tthrow ParserException(INPUT.mark(), ErrorMsg::DOC_IN_SCALAR);\n\t\t\t\t}\n\n\t\t\t\tfoundNonEmptyLine = true;\n\t\t\t\tpastOpeningBreak = true;\n\n\t\t\t\t\/\/ escaped newline? (only if we're escaping on slash)\n\t\t\t\tif(params.escape == '\\\\' && Exp::EscBreak.Matches(INPUT)) {\n\t\t\t\t\tint n = Exp::EscBreak.Match(INPUT);\n\t\t\t\t\tINPUT.eat(n);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ escape this?\n\t\t\t\tif(INPUT.peek() == params.escape) {\n\t\t\t\t\tscalar += Exp::Escape(INPUT);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ otherwise, just add the damn character\n\t\t\t\tscalar += INPUT.get();\n\t\t\t}\n\n\t\t\t\/\/ eof? if we're looking to eat something, then we throw\n\t\t\tif(!INPUT) {\n\t\t\t\tif(params.eatEnd)\n\t\t\t\t\tthrow ParserException(INPUT.mark(), ErrorMsg::EOF_IN_SCALAR);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ doc indicator?\n\t\t\tif(params.onDocIndicator == BREAK && INPUT.column() == 0 && Exp::DocIndicator.Matches(INPUT))\n\t\t\t\tbreak;\n\n\t\t\t\/\/ are we done via character match?\n\t\t\tint n = params.end.Match(INPUT);\n\t\t\tif(n >= 0) {\n\t\t\t\tif(params.eatEnd)\n\t\t\t\t\tINPUT.eat(n);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ ********************************\n\t\t\t\/\/ Phase #2: eat line ending\n\t\t\tn = Exp::Break.Match(INPUT);\n\t\t\tINPUT.eat(n);\n\n\t\t\t\/\/ ********************************\n\t\t\t\/\/ Phase #3: scan initial spaces\n\n\t\t\t\/\/ first the required indentation\n\t\t\twhile(INPUT.peek() == ' ' && (INPUT.column() < params.indent || (params.detectIndent && !foundNonEmptyLine)))\n\t\t\t\tINPUT.eat(1);\n\n\t\t\t\/\/ update indent if we're auto-detecting\n\t\t\tif(params.detectIndent && !foundNonEmptyLine)\n\t\t\t\tparams.indent = std::max(params.indent, INPUT.column());\n\n\t\t\t\/\/ and then the rest of the whitespace\n\t\t\twhile(Exp::Blank.Matches(INPUT)) {\n\t\t\t\t\/\/ we check for tabs that masquerade as indentation\n\t\t\t\tif(INPUT.peek() == '\\t'&& INPUT.column() < params.indent && params.onTabInIndentation == THROW)\n\t\t\t\t\tthrow ParserException(INPUT.mark(), ErrorMsg::TAB_IN_INDENTATION);\n\n\t\t\t\tif(!params.eatLeadingWhitespace)\n\t\t\t\t\tbreak;\n\n\t\t\t\tINPUT.eat(1);\n\t\t\t}\n\n\t\t\t\/\/ was this an empty line?\n\t\t\tbool nextEmptyLine = Exp::Break.Matches(INPUT);\n\t\t\tbool nextMoreIndented = (INPUT.peek() == ' ');\n\n\t\t\t\/\/ for block scalars, we always start with a newline, so we should ignore it (not fold or keep)\n\t\t\tif(pastOpeningBreak) {\n\t\t\t\tif(params.fold && !emptyLine && !nextEmptyLine && !moreIndented && !nextMoreIndented && INPUT.column() >= params.indent)\n\t\t\t\t\tscalar += \" \";\n\t\t\t\telse\n\t\t\t\t\tscalar += \"\\n\";\n\t\t\t}\n\n\t\t\temptyLine = nextEmptyLine;\n\t\t\tmoreIndented = nextMoreIndented;\n\t\t\tpastOpeningBreak = true;\n\n\t\t\t\/\/ are we done via indentation?\n\t\t\tif(!emptyLine && INPUT.column() < params.indent) {\n\t\t\t\tparams.leadingSpaces = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ post-processing\n\t\tif(params.trimTrailingSpaces) {\n\t\t\tstd::size_t pos = scalar.find_last_not_of(' ');\n\t\t\tif(pos < scalar.size())\n\t\t\t\tscalar.erase(pos + 1);\n\t\t}\n\n\t\tif(params.chomp == STRIP || params.chomp == CLIP) {\n\t\t\tstd::size_t pos = scalar.find_last_not_of('\\n');\n\t\t\tif(params.chomp == CLIP && pos + 1 < scalar.size())\n\t\t\t\tscalar.erase(pos + 2);\n\t\t\telse if(params.chomp == STRIP && pos < scalar.size())\n\t\t\t\tscalar.erase(pos + 1);\n\t\t}\n\n\t\treturn scalar;\n\t}\n}\n<commit_msg>Fixed newlines in folded scalars bug<commit_after>#include \"crt.h\"\n#include \"scanscalar.h\"\n#include \"scanner.h\"\n#include \"exp.h\"\n#include \"exceptions.h\"\n#include \"token.h\"\n\nnamespace YAML\n{\n\t\/\/ ScanScalar\n\t\/\/ . This is where the scalar magic happens.\n\t\/\/\n\t\/\/ . We do the scanning in three phases:\n\t\/\/ 1. Scan until newline\n\t\/\/ 2. Eat newline\n\t\/\/ 3. Scan leading blanks.\n\t\/\/\n\t\/\/ . Depending on the parameters given, we store or stop\n\t\/\/ and different places in the above flow.\n\tstd::string ScanScalar(Stream& INPUT, ScanScalarParams& params)\n\t{\n\t\tbool foundNonEmptyLine = false, pastOpeningBreak = false;\n\t\tbool emptyLine = false, moreIndented = false;\n\t\tint foldedNewlineCount = 0;\n\t\tbool foldedNewlineStartedMoreIndented = false;\n\t\tstd::string scalar;\n\t\tparams.leadingSpaces = false;\n\n\t\twhile(INPUT) {\n\t\t\t\/\/ ********************************\n\t\t\t\/\/ Phase #1: scan until line ending\n\t\t\twhile(!params.end.Matches(INPUT) && !Exp::Break.Matches(INPUT)) {\n\t\t\t\tif(!INPUT)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\/\/ document indicator?\n\t\t\t\tif(INPUT.column() == 0 && Exp::DocIndicator.Matches(INPUT)) {\n\t\t\t\t\tif(params.onDocIndicator == BREAK)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse if(params.onDocIndicator == THROW)\n\t\t\t\t\t\tthrow ParserException(INPUT.mark(), ErrorMsg::DOC_IN_SCALAR);\n\t\t\t\t}\n\n\t\t\t\tfoundNonEmptyLine = true;\n\t\t\t\tpastOpeningBreak = true;\n\n\t\t\t\t\/\/ escaped newline? (only if we're escaping on slash)\n\t\t\t\tif(params.escape == '\\\\' && Exp::EscBreak.Matches(INPUT)) {\n\t\t\t\t\tint n = Exp::EscBreak.Match(INPUT);\n\t\t\t\t\tINPUT.eat(n);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ escape this?\n\t\t\t\tif(INPUT.peek() == params.escape) {\n\t\t\t\t\tscalar += Exp::Escape(INPUT);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ otherwise, just add the damn character\n\t\t\t\tscalar += INPUT.get();\n\t\t\t}\n\n\t\t\t\/\/ eof? if we're looking to eat something, then we throw\n\t\t\tif(!INPUT) {\n\t\t\t\tif(params.eatEnd)\n\t\t\t\t\tthrow ParserException(INPUT.mark(), ErrorMsg::EOF_IN_SCALAR);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ doc indicator?\n\t\t\tif(params.onDocIndicator == BREAK && INPUT.column() == 0 && Exp::DocIndicator.Matches(INPUT))\n\t\t\t\tbreak;\n\n\t\t\t\/\/ are we done via character match?\n\t\t\tint n = params.end.Match(INPUT);\n\t\t\tif(n >= 0) {\n\t\t\t\tif(params.eatEnd)\n\t\t\t\t\tINPUT.eat(n);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ ********************************\n\t\t\t\/\/ Phase #2: eat line ending\n\t\t\tn = Exp::Break.Match(INPUT);\n\t\t\tINPUT.eat(n);\n\n\t\t\t\/\/ ********************************\n\t\t\t\/\/ Phase #3: scan initial spaces\n\n\t\t\t\/\/ first the required indentation\n\t\t\twhile(INPUT.peek() == ' ' && (INPUT.column() < params.indent || (params.detectIndent && !foundNonEmptyLine)))\n\t\t\t\tINPUT.eat(1);\n\n\t\t\t\/\/ update indent if we're auto-detecting\n\t\t\tif(params.detectIndent && !foundNonEmptyLine)\n\t\t\t\tparams.indent = std::max(params.indent, INPUT.column());\n\n\t\t\t\/\/ and then the rest of the whitespace\n\t\t\twhile(Exp::Blank.Matches(INPUT)) {\n\t\t\t\t\/\/ we check for tabs that masquerade as indentation\n\t\t\t\tif(INPUT.peek() == '\\t'&& INPUT.column() < params.indent && params.onTabInIndentation == THROW)\n\t\t\t\t\tthrow ParserException(INPUT.mark(), ErrorMsg::TAB_IN_INDENTATION);\n\n\t\t\t\tif(!params.eatLeadingWhitespace)\n\t\t\t\t\tbreak;\n\n\t\t\t\tINPUT.eat(1);\n\t\t\t}\n\n\t\t\t\/\/ was this an empty line?\n\t\t\tbool nextEmptyLine = Exp::Break.Matches(INPUT);\n\t\t\tbool nextMoreIndented = (INPUT.peek() == ' ');\n\t\t\tif(params.fold && foldedNewlineCount == 0 && nextEmptyLine)\n\t\t\t\tfoldedNewlineStartedMoreIndented = moreIndented;\n\n\t\t\t\/\/ for block scalars, we always start with a newline, so we should ignore it (not fold or keep)\n\t\t\tif(pastOpeningBreak) {\n\t\t\t\tif(params.fold) {\n\t\t\t\t\tif(!emptyLine && !nextEmptyLine && !moreIndented && !nextMoreIndented && INPUT.column() >= params.indent)\n\t\t\t\t\t\tscalar += \" \";\n\t\t\t\t\telse if(nextEmptyLine)\n\t\t\t\t\t\tfoldedNewlineCount++;\n\t\t\t\t\telse\n\t\t\t\t\t\tscalar += \"\\n\";\n\t\t\t\t\t\n\t\t\t\t\tif(!nextEmptyLine && foldedNewlineCount > 0) {\n\t\t\t\t\t\tif(foldedNewlineStartedMoreIndented || nextMoreIndented)\n\t\t\t\t\t\t\tscalar += std::string(\"\\n\", foldedNewlineCount);\n\t\t\t\t\t\tfoldedNewlineCount = 0;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tscalar += \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\temptyLine = nextEmptyLine;\n\t\t\tmoreIndented = nextMoreIndented;\n\t\t\tpastOpeningBreak = true;\n\n\t\t\t\/\/ are we done via indentation?\n\t\t\tif(!emptyLine && INPUT.column() < params.indent) {\n\t\t\t\tparams.leadingSpaces = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ post-processing\n\t\tif(params.trimTrailingSpaces) {\n\t\t\tstd::size_t pos = scalar.find_last_not_of(' ');\n\t\t\tif(pos < scalar.size())\n\t\t\t\tscalar.erase(pos + 1);\n\t\t}\n\n\t\tif(params.chomp == STRIP || params.chomp == CLIP) {\n\t\t\tstd::size_t pos = scalar.find_last_not_of('\\n');\n\t\t\tif(params.chomp == CLIP && pos + 1 < scalar.size())\n\t\t\t\tscalar.erase(pos + 2);\n\t\t\telse if(params.chomp == STRIP && pos < scalar.size())\n\t\t\t\tscalar.erase(pos + 1);\n\t\t}\n\n\t\treturn scalar;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ TODO(carpenter): move this into test\/unit\/command\n\/\/ it's here now because it won't compile there\n\n#include <gtest\/gtest.h>\n#include <stan\/lang\/compiler.hpp>\n#include <stan\/command\/stanc_helper.hpp>\n#include <test\/unit\/util.hpp>\n#include <fstream>\n#include <sstream>\n\nvoid expect_find(const std::string& str, const std::string& target) {\n EXPECT_TRUE(str.find(target) != std::string::npos)\n << str << \" does not contain \" << target << std::endl;\n}\n\nTEST(commandStancHelper, printVersion) {\n std::stringstream ss;\n print_version(&ss);\n expect_find(ss.str(), \"stanc version 2.\");\n}\n\nTEST(commandStancHelper, printStancHelp) {\n std::stringstream ss;\n print_stanc_help(&ss);\n expect_find(ss.str(), \"USAGE: stanc [options] <model_file>\");\n expect_find(ss.str(), \"OPTIONS:\");\n}\n\nbool create_test_file(const std::string& path, const std::string& program) {\n std::string cmd_setup = \"mkdir -p test\/test-models\";\n system(cmd_setup.c_str());\n std::string cmd = \"echo \";\n cmd += \"\\\"\";\n cmd += program;\n cmd += \"\\\"\";\n cmd += \" > \";\n cmd += path;\n int return_code = system(cmd.c_str());\n return return_code == 0;\n}\n\nbool create_test_file() {\n std::string program = \"parameters { real y; } model { y ~ normal(0, 1); }\";\n return create_test_file(\"test\/test-models\/temp-bar.stan\", program);\n}\n\nTEST(commandStancHelper, deleteFile) {\n if (!create_test_file())\n return;\n std::stringstream ss;\n delete_file(&ss, \"test\/test-models\/temp-bar.stan\");\n \/\/ test there's no error message\n EXPECT_EQ(0, ss.str().size());\n \/\/ and then test the file stream can't be opened\n std::fstream fs;\n fs.open(\"test\/test-models\/temp-bar.stan\", std::fstream::in);\n EXPECT_FALSE(fs.is_open());\n fs.close();\n}\n\nint run_helper(const std::string& path, std::ostream& out, std::ostream& err) {\n int argc = 2;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(path.c_str());\n const char** argv = &argv_vec[0];\n return stanc_helper(argc, argv, &out, &err);\n}\n\nTEST(commandStancHelper, readOnlyOK) {\n std::stringstream out;\n std::stringstream err;\n int rc = run_helper(\"src\/test\/test-models\/good\/stanc_helper.stan\", out, err);\n EXPECT_EQ(0, rc) << \"out=\" << out.str() << std::endl\n << \"err=\" << err.str() << std::endl;\n expect_find(out.str(), \"Model name=stanc_helper_model\");\n expect_find(out.str(),\n \"Input file=src\/test\/test-models\/good\/stanc_helper.stan\");\n expect_find(out.str(), \"Output file=stanc_helper_model.cpp\");\n delete_file(&err, \"stanc_helper_model.cpp\");\n EXPECT_EQ(0, err.str().size()) << \"error=\" << err.str() << std::endl;\n}\n\nTEST(commandStancHelper, failRC) {\n std::stringstream out;\n std::stringstream err;\n int rc = run_helper(\"src\/test\/test-models\/bad\/stanc_helper.stan\", out, err);\n\n \/\/ TODO(carpenter): This should be -2 but it's -3 so\n \/\/ I only tested that it's != 0 to contrast with earlier success\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, noSuchFile) {\n std::stringstream out;\n std::stringstream err;\n int argc = 2;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"src\/test\/test-models\/good\/nosuchfile.stan\");\n const char** argv = &argv_vec[0];\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_GT(err.str().size(), 10) << \"error=\" << err.str() << std::endl;\n expect_find(err.str(), \"Failed to open model file\");\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, readOnlyDirReadFile) {\n std::stringstream out;\n std::stringstream err;\n int argc = 4;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--name=m1\");\n argv_vec.push_back(\"--o=src\/test\/test-models\/m1.cpp\");\n argv_vec.push_back(\"src\/test\/test-models\/bad\/read_only\/m1.stan\");\n const char** argv = &argv_vec[0];\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc == 0);\n delete_file(&err, \"src\/test\/test-models\/m1.cpp\");\n EXPECT_EQ(0, err.str().size()) << \"error=\" << err.str() << std::endl;\n}\n\nTEST(commandStancHelper, readOnlyDirWriteFile) {\n std::stringstream out;\n std::stringstream err;\n int argc = 4;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--name=m1\");\n argv_vec.push_back(\"--o=src\/test\/test-models\/read_only\/m1.cpp\");\n argv_vec.push_back(\"src\/test\/test-models\/bad\/read_only\/m1.stan\");\n const char** argv = &argv_vec[0];\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, readOnlyDirBadFile) {\n std::stringstream out;\n std::stringstream err;\n int argc = 2;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"src\/test\/test-models\/bad\/read_only\/nosuchfile.stan\");\n const char** argv = &argv_vec[0];\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, includeSinglePathGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--include_paths=src\/test\/test-models\/included\/\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc == 0);\n}\n\nTEST(commandStancHelper, includeMultPathSimpleGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--include_paths=foo,src\/test\/test-models\/included\/,baz\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc == 0);\n}\n\nTEST(commandStancHelper, includeMultPathSingleQuoteGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\n \"--include_paths='path,with,commas',src\/test\/test-models\/included\/\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc == 0);\n}\n\nTEST(commandStancHelper, includeMultPathDoubleQuoteGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\n \"--include_paths=\\\"path,with,commas\\\",src\/test\/test-models\/included\/\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_EQ(0, rc);\n}\n\nTEST(commandStancHelper, includeMultPathEscapedCommaGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\n \"--include_paths=path\\\\,with\\\\,commas,src\/test\/test-models\/included\/\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_EQ(0, rc);\n}\n\nTEST(commandStancHelper, includeMultPathBad) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--include_paths=foo,baz\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, includeNoPathBad) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc != 0);\n}\n<commit_msg>fix ignoring return value<commit_after>\/\/ TODO(carpenter): move this into test\/unit\/command\n\/\/ it's here now because it won't compile there\n\n#include <gtest\/gtest.h>\n#include <stan\/lang\/compiler.hpp>\n#include <stan\/command\/stanc_helper.hpp>\n#include <test\/unit\/util.hpp>\n#include <fstream>\n#include <sstream>\n\nvoid expect_find(const std::string& str, const std::string& target) {\n EXPECT_TRUE(str.find(target) != std::string::npos)\n << str << \" does not contain \" << target << std::endl;\n}\n\nTEST(commandStancHelper, printVersion) {\n std::stringstream ss;\n print_version(&ss);\n expect_find(ss.str(), \"stanc version 2.\");\n}\n\nTEST(commandStancHelper, printStancHelp) {\n std::stringstream ss;\n print_stanc_help(&ss);\n expect_find(ss.str(), \"USAGE: stanc [options] <model_file>\");\n expect_find(ss.str(), \"OPTIONS:\");\n}\n\nbool create_test_file(const std::string& path, const std::string& program) {\n std::string cmd_setup = \"mkdir -p test\/test-models\";\n int return_code = system(cmd_setup.c_str());\n std::string cmd = \"echo \";\n cmd += \"\\\"\";\n cmd += program;\n cmd += \"\\\"\";\n cmd += \" > \";\n cmd += path;\n return_code = system(cmd.c_str());\n return return_code == 0;\n}\n\nbool create_test_file() {\n std::string program = \"parameters { real y; } model { y ~ normal(0, 1); }\";\n return create_test_file(\"test\/test-models\/temp-bar.stan\", program);\n}\n\nTEST(commandStancHelper, deleteFile) {\n if (!create_test_file())\n return;\n std::stringstream ss;\n delete_file(&ss, \"test\/test-models\/temp-bar.stan\");\n \/\/ test there's no error message\n EXPECT_EQ(0, ss.str().size());\n \/\/ and then test the file stream can't be opened\n std::fstream fs;\n fs.open(\"test\/test-models\/temp-bar.stan\", std::fstream::in);\n EXPECT_FALSE(fs.is_open());\n fs.close();\n}\n\nint run_helper(const std::string& path, std::ostream& out, std::ostream& err) {\n int argc = 2;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(path.c_str());\n const char** argv = &argv_vec[0];\n return stanc_helper(argc, argv, &out, &err);\n}\n\nTEST(commandStancHelper, readOnlyOK) {\n std::stringstream out;\n std::stringstream err;\n int rc = run_helper(\"src\/test\/test-models\/good\/stanc_helper.stan\", out, err);\n EXPECT_EQ(0, rc) << \"out=\" << out.str() << std::endl\n << \"err=\" << err.str() << std::endl;\n expect_find(out.str(), \"Model name=stanc_helper_model\");\n expect_find(out.str(),\n \"Input file=src\/test\/test-models\/good\/stanc_helper.stan\");\n expect_find(out.str(), \"Output file=stanc_helper_model.cpp\");\n delete_file(&err, \"stanc_helper_model.cpp\");\n EXPECT_EQ(0, err.str().size()) << \"error=\" << err.str() << std::endl;\n}\n\nTEST(commandStancHelper, failRC) {\n std::stringstream out;\n std::stringstream err;\n int rc = run_helper(\"src\/test\/test-models\/bad\/stanc_helper.stan\", out, err);\n\n \/\/ TODO(carpenter): This should be -2 but it's -3 so\n \/\/ I only tested that it's != 0 to contrast with earlier success\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, noSuchFile) {\n std::stringstream out;\n std::stringstream err;\n int argc = 2;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"src\/test\/test-models\/good\/nosuchfile.stan\");\n const char** argv = &argv_vec[0];\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_GT(err.str().size(), 10) << \"error=\" << err.str() << std::endl;\n expect_find(err.str(), \"Failed to open model file\");\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, readOnlyDirReadFile) {\n std::stringstream out;\n std::stringstream err;\n int argc = 4;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--name=m1\");\n argv_vec.push_back(\"--o=src\/test\/test-models\/m1.cpp\");\n argv_vec.push_back(\"src\/test\/test-models\/bad\/read_only\/m1.stan\");\n const char** argv = &argv_vec[0];\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc == 0);\n delete_file(&err, \"src\/test\/test-models\/m1.cpp\");\n EXPECT_EQ(0, err.str().size()) << \"error=\" << err.str() << std::endl;\n}\n\nTEST(commandStancHelper, readOnlyDirWriteFile) {\n std::stringstream out;\n std::stringstream err;\n int argc = 4;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--name=m1\");\n argv_vec.push_back(\"--o=src\/test\/test-models\/read_only\/m1.cpp\");\n argv_vec.push_back(\"src\/test\/test-models\/bad\/read_only\/m1.stan\");\n const char** argv = &argv_vec[0];\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, readOnlyDirBadFile) {\n std::stringstream out;\n std::stringstream err;\n int argc = 2;\n std::vector<const char*> argv_vec;\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"src\/test\/test-models\/bad\/read_only\/nosuchfile.stan\");\n const char** argv = &argv_vec[0];\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, includeSinglePathGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--include_paths=src\/test\/test-models\/included\/\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc == 0);\n}\n\nTEST(commandStancHelper, includeMultPathSimpleGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--include_paths=foo,src\/test\/test-models\/included\/,baz\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc == 0);\n}\n\nTEST(commandStancHelper, includeMultPathSingleQuoteGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\n \"--include_paths='path,with,commas',src\/test\/test-models\/included\/\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc == 0);\n}\n\nTEST(commandStancHelper, includeMultPathDoubleQuoteGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\n \"--include_paths=\\\"path,with,commas\\\",src\/test\/test-models\/included\/\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_EQ(0, rc);\n}\n\nTEST(commandStancHelper, includeMultPathEscapedCommaGood) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\n \"--include_paths=path\\\\,with\\\\,commas,src\/test\/test-models\/included\/\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_EQ(0, rc);\n}\n\nTEST(commandStancHelper, includeMultPathBad) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\"--include_paths=foo,baz\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc != 0);\n}\n\nTEST(commandStancHelper, includeNoPathBad) {\n std::stringstream out;\n std::stringstream err;\n std::vector<const char*> argv_vec;\n\n argv_vec.push_back(\"main\");\n argv_vec.push_back(\n \"src\/test\/test-models\/include_path_test\/stanc_helper_with_include.stan\");\n\n int argc = argv_vec.size();\n const char** argv = &argv_vec[0];\n\n int rc = stanc_helper(argc, argv, &out, &err);\n EXPECT_TRUE(rc != 0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <vector>\n#include <set>\n#include <functional>\n\n#include <opengm\/graphicalmodel\/graphicalmodel.hxx>\n#include <opengm\/operations\/adder.hxx>\n#include <opengm\/operations\/multiplier.hxx>\n#include <opengm\/operations\/minimizer.hxx>\n#include <opengm\/operations\/maximizer.hxx>\n#include <opengm\/inference\/graphcut.hxx>\n\n#include <opengm\/unittests\/blackboxtester.hxx>\n#include <opengm\/unittests\/blackboxtests\/blackboxtestgrid.hxx>\n#include <opengm\/unittests\/blackboxtests\/blackboxtestfull.hxx>\n#include <opengm\/unittests\/blackboxtests\/blackboxteststar.hxx>\n\n#ifdef WITH_BOOST\n# ifdef NDEBUG\n# include <opengm\/inference\/auxiliary\/minstcutboost.hxx>\n# else\n# define NDEBUG \/\/Hot-fix to deal with floating point assert problem in boost\n# include <opengm\/inference\/auxiliary\/minstcutboost.hxx>\n# undefine NDEBUG\n# endif\n#endif\n#ifdef WITH_MAXFLOW\n# include <opengm\/inference\/auxiliary\/minstcutkolmogorov.hxx>\n#endif\n#ifdef WITH_MAXFLOW_IBFS\n# include <opengm\/inference\/auxiliary\/minstcutibfs.hxx>\n#endif\n\nint main() {\n typedef opengm::GraphicalModel<float, opengm::Adder> GraphicalModelType;\n typedef opengm::GraphicalModel<float, opengm::Adder, \n opengm::ExplicitFunction<float,unsigned short, unsigned char>, \n opengm::DiscreteSpace<unsigned short, unsigned char> > SumGmType2;\n typedef opengm::BlackBoxTestGrid<SumGmType2> SumGridTest2;\n typedef opengm::BlackBoxTestFull<SumGmType2> SumFullTest2;\n typedef opengm::BlackBoxTestStar<SumGmType2> SumStarTest2;\n typedef opengm::BlackBoxTestGrid<GraphicalModelType> GridTest;\n typedef opengm::BlackBoxTestFull<GraphicalModelType> FullTest;\n typedef opengm::BlackBoxTestStar<GraphicalModelType> StarTest;\n \n opengm::InferenceBlackBoxTester<SumGmType2> minTester2;\n minTester2.addTest(new SumGridTest2(4, 4, 2, false, true, SumGridTest2::POTTS, opengm::OPTIMAL, 1));\n \n opengm::InferenceBlackBoxTester<GraphicalModelType> minTester;\n minTester.addTest(new GridTest(4, 4, 2, false, true, GridTest::POTTS, opengm::OPTIMAL, 10));\n minTester.addTest(new GridTest(3, 3, 2, false, true, GridTest::POTTS, opengm::OPTIMAL, 10));\n minTester.addTest(new GridTest(3, 3, 2, false, false,GridTest::POTTS, opengm::OPTIMAL, 10));\n minTester.addTest(new StarTest(5, 2, false, true, StarTest::POTTS, opengm::OPTIMAL, 10));\n minTester.addTest(new FullTest(5, 2, false, 3, FullTest::POTTS, opengm::OPTIMAL, 10));\n \n opengm::InferenceBlackBoxTester<GraphicalModelType> maxTester;\n maxTester.addTest(new GridTest(4, 4, 2, false, true, GridTest::IPOTTS, opengm::OPTIMAL, 1));\n maxTester.addTest(new GridTest(3, 3, 2, false, true, GridTest::IPOTTS, opengm::OPTIMAL, 3));\n maxTester.addTest(new GridTest(3, 3, 2, false, false,GridTest::IPOTTS, opengm::OPTIMAL, 3));\n maxTester.addTest(new StarTest(5, 2, false, true, StarTest::IPOTTS, opengm::OPTIMAL, 3));\n maxTester.addTest(new FullTest(5, 2, false, 3, FullTest::IPOTTS, opengm::OPTIMAL, 3));\n\n std::cout << \"Test Graphcut ...\" << std::endl;\n\n#ifdef WITH_MAXFLOW_IBFS\n std::cout << \" * Test Min-Sum with IBFS (int)\" << std::endl;\n {\n typedef opengm::external::MinSTCutIBFS<int, int> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para(10000);\n minTester.test<MinGraphCut>(para);\n }\n#endif\n\n#ifdef WITH_MAXFLOW\n std::cout << \" * Test Min-Sum with Kolmogorov\" << std::endl;\n {\n typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester.test<MinGraphCut>(para);\n }\n std::cout << \" * Test Min-Sum with Kolmogorov (float,uint16,uint8) \" << std::endl;\n {\n typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;\n typedef opengm::GraphCut<SumGmType2, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester2.test<MinGraphCut>(para);\n }\n#endif\n\n#ifdef WITH_BOOST\n std::cout << \" * Test Min-Sum with BOOST-Push-Relabel\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::PUSH_RELABEL> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester.test<MinGraphCut>(para);\n } \n std::cout << \" * Test Min-Sum with Interegr-BOOST-Push-Relabel\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, long, opengm::PUSH_RELABEL> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para(1000000);\n minTester.test<MinGraphCut>(para);\n }\n std::cout << \" * Test Min-Sum with BOOST-Edmonds-Karp\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::EDMONDS_KARP> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester.test<MinGraphCut>(para);\n }\n std::cout << \" * Test Min-Sum with BOOST-Kolmogorov\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::KOLMOGOROV> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester.test<MinGraphCut>(para);\n }\n#endif\n \n#ifdef WITH_MAXFLOW_IBFS\n std::cout << \" * Test Max-Sum with IBFS (int)\" << std::endl;\n {\n typedef opengm::external::MinSTCutIBFS<int, int> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para(10000);\n maxTester.test<MaxGraphCut>(para);\n\n }\n#endif\n \n#ifdef WITH_MAXFLOW\n std::cout << \" * Test Max-Sum with Kolmogorov\" << std::endl;\n {\n typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para;\n maxTester.test<MaxGraphCut>(para);\n\n }\n#endif\n\n#ifdef WITH_BOOST\n std::cout << \" * Test Max-Sum with BOOST-Push-Relabel\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::PUSH_RELABEL> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para;\n maxTester.test<MaxGraphCut>(para);\n }\n \/\/This test might fail due to overflow with int\n \/*\n std::cout << \" * Test Max-Sum with Integer-BOOST-Push-Relabel\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, int, opengm::PUSH_RELABEL> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para(1000000);\n maxTester.test<MaxGraphCut>(para);\n }\n *\/\n std::cout << \" * Test Max-Sum with BOOST-Edmonds-Karp\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::EDMONDS_KARP> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para;\n maxTester.test<MaxGraphCut>(para);\n }\n std::cout << \" * Test Max-Sum with BOOST-Kolmogorov\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::KOLMOGOROV> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para;\n maxTester.test<MaxGraphCut>(para);\n }\n#endif\n\n return 0;\n}\n<commit_msg>s\/undefine\/undef in macro checks<commit_after>#include <stdlib.h>\n#include <vector>\n#include <set>\n#include <functional>\n\n#include <opengm\/graphicalmodel\/graphicalmodel.hxx>\n#include <opengm\/operations\/adder.hxx>\n#include <opengm\/operations\/multiplier.hxx>\n#include <opengm\/operations\/minimizer.hxx>\n#include <opengm\/operations\/maximizer.hxx>\n#include <opengm\/inference\/graphcut.hxx>\n\n#include <opengm\/unittests\/blackboxtester.hxx>\n#include <opengm\/unittests\/blackboxtests\/blackboxtestgrid.hxx>\n#include <opengm\/unittests\/blackboxtests\/blackboxtestfull.hxx>\n#include <opengm\/unittests\/blackboxtests\/blackboxteststar.hxx>\n\n#ifdef WITH_BOOST\n# ifdef NDEBUG\n# include <opengm\/inference\/auxiliary\/minstcutboost.hxx>\n# else\n# define NDEBUG \/\/Hot-fix to deal with floating point assert problem in boost\n# include <opengm\/inference\/auxiliary\/minstcutboost.hxx>\n# undef NDEBUG\n# endif\n#endif\n#ifdef WITH_MAXFLOW\n# include <opengm\/inference\/auxiliary\/minstcutkolmogorov.hxx>\n#endif\n#ifdef WITH_MAXFLOW_IBFS\n# include <opengm\/inference\/auxiliary\/minstcutibfs.hxx>\n#endif\n\nint main() {\n typedef opengm::GraphicalModel<float, opengm::Adder> GraphicalModelType;\n typedef opengm::GraphicalModel<float, opengm::Adder, \n opengm::ExplicitFunction<float,unsigned short, unsigned char>, \n opengm::DiscreteSpace<unsigned short, unsigned char> > SumGmType2;\n typedef opengm::BlackBoxTestGrid<SumGmType2> SumGridTest2;\n typedef opengm::BlackBoxTestFull<SumGmType2> SumFullTest2;\n typedef opengm::BlackBoxTestStar<SumGmType2> SumStarTest2;\n typedef opengm::BlackBoxTestGrid<GraphicalModelType> GridTest;\n typedef opengm::BlackBoxTestFull<GraphicalModelType> FullTest;\n typedef opengm::BlackBoxTestStar<GraphicalModelType> StarTest;\n \n opengm::InferenceBlackBoxTester<SumGmType2> minTester2;\n minTester2.addTest(new SumGridTest2(4, 4, 2, false, true, SumGridTest2::POTTS, opengm::OPTIMAL, 1));\n \n opengm::InferenceBlackBoxTester<GraphicalModelType> minTester;\n minTester.addTest(new GridTest(4, 4, 2, false, true, GridTest::POTTS, opengm::OPTIMAL, 10));\n minTester.addTest(new GridTest(3, 3, 2, false, true, GridTest::POTTS, opengm::OPTIMAL, 10));\n minTester.addTest(new GridTest(3, 3, 2, false, false,GridTest::POTTS, opengm::OPTIMAL, 10));\n minTester.addTest(new StarTest(5, 2, false, true, StarTest::POTTS, opengm::OPTIMAL, 10));\n minTester.addTest(new FullTest(5, 2, false, 3, FullTest::POTTS, opengm::OPTIMAL, 10));\n \n opengm::InferenceBlackBoxTester<GraphicalModelType> maxTester;\n maxTester.addTest(new GridTest(4, 4, 2, false, true, GridTest::IPOTTS, opengm::OPTIMAL, 1));\n maxTester.addTest(new GridTest(3, 3, 2, false, true, GridTest::IPOTTS, opengm::OPTIMAL, 3));\n maxTester.addTest(new GridTest(3, 3, 2, false, false,GridTest::IPOTTS, opengm::OPTIMAL, 3));\n maxTester.addTest(new StarTest(5, 2, false, true, StarTest::IPOTTS, opengm::OPTIMAL, 3));\n maxTester.addTest(new FullTest(5, 2, false, 3, FullTest::IPOTTS, opengm::OPTIMAL, 3));\n\n std::cout << \"Test Graphcut ...\" << std::endl;\n\n#ifdef WITH_MAXFLOW_IBFS\n std::cout << \" * Test Min-Sum with IBFS (int)\" << std::endl;\n {\n typedef opengm::external::MinSTCutIBFS<int, int> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para(10000);\n minTester.test<MinGraphCut>(para);\n }\n#endif\n\n#ifdef WITH_MAXFLOW\n std::cout << \" * Test Min-Sum with Kolmogorov\" << std::endl;\n {\n typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester.test<MinGraphCut>(para);\n }\n std::cout << \" * Test Min-Sum with Kolmogorov (float,uint16,uint8) \" << std::endl;\n {\n typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;\n typedef opengm::GraphCut<SumGmType2, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester2.test<MinGraphCut>(para);\n }\n#endif\n\n#ifdef WITH_BOOST\n std::cout << \" * Test Min-Sum with BOOST-Push-Relabel\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::PUSH_RELABEL> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester.test<MinGraphCut>(para);\n } \n std::cout << \" * Test Min-Sum with Interegr-BOOST-Push-Relabel\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, long, opengm::PUSH_RELABEL> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para(1000000);\n minTester.test<MinGraphCut>(para);\n }\n std::cout << \" * Test Min-Sum with BOOST-Edmonds-Karp\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::EDMONDS_KARP> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester.test<MinGraphCut>(para);\n }\n std::cout << \" * Test Min-Sum with BOOST-Kolmogorov\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::KOLMOGOROV> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;\n MinGraphCut::Parameter para;\n minTester.test<MinGraphCut>(para);\n }\n#endif\n \n#ifdef WITH_MAXFLOW_IBFS\n std::cout << \" * Test Max-Sum with IBFS (int)\" << std::endl;\n {\n typedef opengm::external::MinSTCutIBFS<int, int> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para(10000);\n maxTester.test<MaxGraphCut>(para);\n\n }\n#endif\n \n#ifdef WITH_MAXFLOW\n std::cout << \" * Test Max-Sum with Kolmogorov\" << std::endl;\n {\n typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para;\n maxTester.test<MaxGraphCut>(para);\n\n }\n#endif\n\n#ifdef WITH_BOOST\n std::cout << \" * Test Max-Sum with BOOST-Push-Relabel\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::PUSH_RELABEL> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para;\n maxTester.test<MaxGraphCut>(para);\n }\n \/\/This test might fail due to overflow with int\n \/*\n std::cout << \" * Test Max-Sum with Integer-BOOST-Push-Relabel\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, int, opengm::PUSH_RELABEL> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para(1000000);\n maxTester.test<MaxGraphCut>(para);\n }\n *\/\n std::cout << \" * Test Max-Sum with BOOST-Edmonds-Karp\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::EDMONDS_KARP> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para;\n maxTester.test<MaxGraphCut>(para);\n }\n std::cout << \" * Test Max-Sum with BOOST-Kolmogorov\" << std::endl;\n {\n typedef opengm::MinSTCutBoost<size_t, float, opengm::KOLMOGOROV> MinStCutType;\n typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;\n MaxGraphCut::Parameter para;\n maxTester.test<MaxGraphCut>(para);\n }\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode:linux -*- *\/\n\/**\n * \\file main.cc\n *\n *\n *\n * \\author Ethan Burns\n * \\date 2008-10-08\n *\/\n\n#include <iostream>\n#include <vector>\n#include <string.h>\n#include <stdlib.h>\n\n#include \"state.h\"\n#include \"a_star.h\"\n#include \"cost_bound_dfs.h\"\n#include \"ida_star.h\"\n#include \"kbfs.h\"\n#include \"h_zero.h\"\n#include \"grid\/grid_world.h\"\n\nusing namespace std;\n\nSearch *get_search(int argc, char *argv[])\n{\n\tif (argc > 1 && strcmp(argv[1], \"astar\") == 0) {\n\t\treturn new AStar();\n\t} else if (argc > 1 && strcmp(argv[1], \"idastar\") == 0) {\n\t\treturn new IDAStar();\n\t} else if (argc > 2 && strcmp(argv[1], \"costbounddfs\") == 0) {\n\t\treturn new CostBoundDFS(atoi(argv[2]));\n\t} else if (argc > 1 && strcmp(argv[1], \"kbfs\") == 0) {\n\t\treturn new KBFS();\n\t} else {\n\t\tcout << \"Must supply a search algorithm:\" << endl;\n\t\tcout << \"\\tastar, idastar, costbounddfs, kbfs\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\tvector<const State *> *path;\n\tGridWorld g(cin);\n\tGridWorld::ManhattanDist manhattan(&g);\n\tHZero hzero(&g);\n\tSearch *search = get_search(argc, argv);\n\n\tg.set_heuristic(&manhattan);\n\/\/\tg.set_heuristic(&hzero);\n\tpath = search->search(g.initial_state());\n\/\/\tg.print(cout, path);\n\n\tcout << \"generated: \" << search->get_generated() << endl;\n\tcout << \"expanded: \" << search->get_expanded() << endl;\n\tif (path) {\n\t\tcout << \"cost: \" << path->at(0)->get_g() << endl;\n\t\tfor (unsigned int i = 0; i < path->size(); i += 1)\n\t\t\tdelete path->at(i);\n\t\tdelete path;\n\t} else {\n\t\tcout << \"No Solution\" << endl;\n\t}\n\n\tdelete search;\n\n#if ENABLE_IMAGES\n\tg.export_eps(\"output.eps\");\n#endif\t\/\/ ENABLE_IMAGES\n\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>Check the command line arguments before creating the SearchDomain. This way we can report erroneous command line arguments before we attempt to read in a GridWorld.<commit_after>\/* -*- mode:linux -*- *\/\n\/**\n * \\file main.cc\n *\n *\n *\n * \\author Ethan Burns\n * \\date 2008-10-08\n *\/\n\n#include <iostream>\n#include <vector>\n#include <string.h>\n#include <stdlib.h>\n\n#include \"state.h\"\n#include \"a_star.h\"\n#include \"cost_bound_dfs.h\"\n#include \"ida_star.h\"\n#include \"kbfs.h\"\n#include \"h_zero.h\"\n#include \"grid\/grid_world.h\"\n\nusing namespace std;\n\nSearch *get_search(int argc, char *argv[])\n{\n\tif (argc > 1 && strcmp(argv[1], \"astar\") == 0) {\n\t\treturn new AStar();\n\t} else if (argc > 1 && strcmp(argv[1], \"idastar\") == 0) {\n\t\treturn new IDAStar();\n\t} else if (argc > 2 && strcmp(argv[1], \"costbounddfs\") == 0) {\n\t\treturn new CostBoundDFS(atoi(argv[2]));\n\t} else if (argc > 1 && strcmp(argv[1], \"kbfs\") == 0) {\n\t\treturn new KBFS();\n\t} else {\n\t\tcout << \"Must supply a search algorithm:\" << endl;\n\t\tcout << \"\\tastar, idastar, costbounddfs, kbfs\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\tvector<const State *> *path;\n\tSearch *search = get_search(argc, argv);\n\tGridWorld g(cin);\n\tGridWorld::ManhattanDist manhattan(&g);\n\tHZero hzero(&g);\n\n\tg.set_heuristic(&manhattan);\n\/\/\tg.set_heuristic(&hzero);\n\tpath = search->search(g.initial_state());\n\/\/\tg.print(cout, path);\n\n\tcout << \"generated: \" << search->get_generated() << endl;\n\tcout << \"expanded: \" << search->get_expanded() << endl;\n\tif (path) {\n\t\tcout << \"cost: \" << path->at(0)->get_g() << endl;\n\t\tfor (unsigned int i = 0; i < path->size(); i += 1)\n\t\t\tdelete path->at(i);\n\t\tdelete path;\n\t} else {\n\t\tcout << \"No Solution\" << endl;\n\t}\n\n\tdelete search;\n\n#if ENABLE_IMAGES\n\tg.export_eps(\"output.eps\");\n#endif\t\/\/ ENABLE_IMAGES\n\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of qjson\n *\n * Copyright (C) 2009 Till Adam <adam@kde.org>\n * Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>\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 *\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"serializer.h\"\n\n#include <QtCore\/QDataStream>\n#include <QtCore\/QStringList>\n#include <QtCore\/QVariant>\n\n#include <cmath>\n\n#ifdef _MSC_VER \/\/ using MSVC compiler\n#include <float.h>\n#endif\n\nusing namespace QJson;\n\nclass Serializer::SerializerPrivate {\n public:\n SerializerPrivate() :\n specialNumbersAllowed(false),\n indentMode(QJson::IndentNone),\n doublePrecision(6) {\n errorMessage.clear();\n }\n QString errorMessage;\n bool specialNumbersAllowed;\n IndentMode indentMode;\n int doublePrecision;\n QByteArray buildIndent(int spaces);\n QByteArray serialize( const QVariant &v, bool *ok, int indentLevel = 0);\n QString sanitizeString( QString str );\n QByteArray join( const QList<QByteArray>& list, const QByteArray& sep );\n};\n\nQByteArray Serializer::SerializerPrivate::join( const QList<QByteArray>& list, const QByteArray& sep ) {\n QByteArray res;\n Q_FOREACH( const QByteArray& i, list ) {\n if ( !res.isEmpty() )\n res += sep;\n res += i;\n }\n return res;\n}\n\nQByteArray Serializer::SerializerPrivate::serialize( const QVariant &v, bool *ok, int indentLevel)\n{\n QByteArray str;\n bool error = false;\n QByteArray indent;\n\n if ( ! v.isValid() ) { \/\/ invalid or null?\n str = \"null\";\n } else if (( v.type() == QVariant::List ) || ( v.type() == QVariant::StringList )){ \/\/ an array or a stringlist?\n const QVariantList list = v.toList();\n QList<QByteArray> values;\n Q_FOREACH( const QVariant& var, list )\n {\n indentLevel++;\n QByteArray serializedValue = serialize( var, ok, indentLevel);\n indentLevel--;\n if ( !*ok ) {\n break;\n }\n values << serializedValue;\n }\n\n if (indentMode == QJson::IndentMinimum) {\n QByteArray indent = buildIndent(indentLevel - 1);\n str = \"[\\n\" + join( values, \",\\n\" ) + \"\\n\" + indent + \"]\";\n }\n else if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n str = \"[\\n\" + join( values, \",\\n\" ) + \"\\n\" + indent + \"]\";\n }\n else if (indentMode == QJson::IndentCompact) {\n str = \"[\" + join( values, \",\" ) + \"]\";\n }\n else {\n str = \"[ \" + join( values, \", \" ) + \" ]\";\n }\n\n } else if ( v.type() == QVariant::Map ) { \/\/ variant is a map?\n const QVariantMap vmap = v.toMap();\n QMapIterator<QString, QVariant> it( vmap );\n\n if (indentMode == QJson::IndentMinimum) {\n QByteArray indent = buildIndent(indentLevel);\n str = indent + \"{ \";\n }\n else if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n QByteArray nextindent = buildIndent(indentLevel + 1);\n str = indent + \"{\\n\" + nextindent;\n }\n else if (indentMode == QJson::IndentCompact) {\n str = \"{\";\n }\n else {\n str = \"{ \";\n }\n\n QList<QByteArray> pairs;\n while ( it.hasNext() ) {\n it.next();\n indentLevel++;\n QByteArray serializedValue = serialize( it.value(), ok, indentLevel);\n indentLevel--;\n if ( !*ok ) {\n break;\n }\n QByteArray key = sanitizeString( it.key() ).toUtf8();\n QByteArray value = serializedValue;\n if (indentMode == QJson::IndentCompact) {\n pairs << key + \":\" + value;\n } else {\n pairs << key + \" : \" + value;\n }\n }\n\n if (indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel + 1);\n str += join( pairs, \",\\n\" + indent);\n }\n else if (indentMode == QJson::IndentCompact) {\n str += join( pairs, \",\" );\n }\n else {\n str += join( pairs, \", \" );\n }\n\n if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n str += \"\\n\" + indent + \"}\";\n }\n else if (indentMode == QJson::IndentCompact) {\n str += \"}\";\n }\n else {\n str += \" }\";\n }\n\n } else if ( v.type() == QVariant::Hash ) { \/\/ variant is a hash?\n const QVariantHash vhash = v.toHash();\n QHashIterator<QString, QVariant> it( vhash );\n\n if (indentMode == QJson::IndentMinimum) {\n QByteArray indent = buildIndent(indentLevel);\n str = indent + \"{ \";\n }\n else if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n QByteArray nextindent = buildIndent(indentLevel + 1);\n str = indent + \"{\\n\" + nextindent;\n }\n else if (indentMode == QJson::IndentCompact) {\n str = \"{\";\n }\n else {\n str = \"{ \";\n }\n\n QList<QByteArray> pairs;\n while ( it.hasNext() ) {\n it.next();\n indentLevel++;\n QByteArray serializedValue = serialize( it.value(), ok, indentLevel);\n indentLevel--;\n if ( !*ok ) {\n break;\n }\n QByteArray key = sanitizeString( it.key() ).toUtf8();\n QByteArray value = serializedValue;\n if (indentMode == QJson::IndentCompact) {\n pairs << key + \":\" + value;\n } else {\n pairs << key + \" : \" + value;\n }\n }\n\n if (indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel + 1);\n str += join( pairs, \",\\n\" + indent);\n }\n else if (indentMode == QJson::IndentCompact) {\n str += join( pairs, \",\" );\n }\n else {\n str += join( pairs, \", \" );\n }\n\n if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n str += \"\\n\" + indent + \"}\";\n }\n else if (indentMode == QJson::IndentCompact) {\n str += \"}\";\n }\n else {\n str += \" }\";\n }\n\n } else if (( v.type() == QVariant::String ) || ( v.type() == QVariant::ByteArray )) { \/\/ a string or a byte array?\n str = sanitizeString( v.toString() ).toUtf8();\n } else if (( v.type() == QVariant::Double) || ((QMetaType::Type)v.type() == QMetaType::Float)) { \/\/ a double or a float?\n const double value = v.toDouble();\n#if defined _WIN32 && !defined(Q_OS_SYMBIAN)\n const bool special = _isnan(value) || !_finite(value);\n#elif defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID)\n const bool special = isnan(value) || isinf(value);\n#else\n const bool special = std::isnan(value) || std::isinf(value);\n#endif\n if (special) {\n if (specialNumbersAllowed) {\n#if defined _WIN32 && !defined(Q_OS_SYMBIAN)\n if (_isnan(value)) {\n#elif defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID)\n if (isnan(value)) {\n#else\n if (std::isnan(value)) {\n#endif\n str += \"NaN\";\n } else {\n if (value<0) {\n str += '-';\n }\n str += \"Infinity\";\n }\n } else {\n errorMessage += QLatin1String(\"Attempt to write NaN or infinity, which is not supported by json\\n\");\n *ok = false;\n }\n } else {\n str = QByteArray::number( value , 'g', doublePrecision);\n if( ! str.contains( \".\" ) && ! str.contains( \"e\" ) ) {\n str += \".0\";\n }\n }\n } else if ( v.type() == QVariant::Bool ) { \/\/ boolean value?\n str = ( v.toBool() ? \"true\" : \"false\" );\n } else if ( v.type() == QVariant::ULongLong ) { \/\/ large unsigned number?\n str = QByteArray::number( v.value<qulonglong>() );\n } else if ( v.type() == QVariant::UInt ) { \/\/ unsigned int number?\n str = QByteArray::number( v.value<quint32>() );\n } else if ( v.canConvert<qlonglong>() ) { \/\/ any signed number?\n str = QByteArray::number( v.value<qlonglong>() );\n } else if ( v.canConvert<int>() ) { \/\/ unsigned short number?\n str = QByteArray::number( v.value<int>() );\n } else if ( v.canConvert<QString>() ){ \/\/ can value be converted to string?\n \/\/ this will catch QDate, QDateTime, QUrl, ...\n str = sanitizeString( v.toString() ).toUtf8();\n \/\/TODO: catch other values like QImage, QRect, ...\n } else {\n *ok = false;\n errorMessage += QLatin1String(\"Cannot serialize \");\n errorMessage += v.toString();\n errorMessage += QLatin1String(\" because type \");\n errorMessage += QLatin1String(v.typeName());\n errorMessage += QLatin1String(\" is not supported by QJson\\n\");\n }\n if ( *ok )\n {\n return str;\n }\n else\n return QByteArray();\n}\n\nQByteArray Serializer::SerializerPrivate::buildIndent(int spaces)\n{\n QByteArray indent;\n if (spaces < 0) {\n spaces = 0;\n }\n for (int i = 0; i < spaces; i++ ) {\n indent += \" \";\n }\n return indent;\n}\n\nQString Serializer::SerializerPrivate::sanitizeString( QString str )\n{\n str.replace( QLatin1String( \"\\\\\" ), QLatin1String( \"\\\\\\\\\" ) );\n\n \/\/ escape unicode chars\n QString result;\n const ushort* unicode = str.utf16();\n unsigned int i = 0;\n\n while ( unicode[ i ] ) {\n if ( unicode[ i ] < 128 ) {\n result.append( QChar( unicode[ i ] ) );\n }\n else {\n QString hexCode = QString::number( unicode[ i ], 16 ).rightJustified( 4,\n QLatin1Char('0') );\n\n result.append( QLatin1String (\"\\\\u\") ).append( hexCode );\n }\n ++i;\n }\n str = result;\n\n str.replace( QLatin1String( \"\\\"\" ), QLatin1String( \"\\\\\\\"\" ) );\n str.replace( QLatin1String( \"\\b\" ), QLatin1String( \"\\\\b\" ) );\n str.replace( QLatin1String( \"\\f\" ), QLatin1String( \"\\\\f\" ) );\n str.replace( QLatin1String( \"\\n\" ), QLatin1String( \"\\\\n\" ) );\n str.replace( QLatin1String( \"\\r\" ), QLatin1String( \"\\\\r\" ) );\n str.replace( QLatin1String( \"\\t\" ), QLatin1String( \"\\\\t\" ) );\n\n return QString( QLatin1String( \"\\\"%1\\\"\" ) ).arg( str );\n}\n\nSerializer::Serializer()\n : d( new SerializerPrivate )\n{\n}\n\nSerializer::~Serializer() {\n delete d;\n}\n\nvoid Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok)\n{\n Q_ASSERT( io );\n *ok = true;\n\n if (!io->isOpen()) {\n if (!io->open(QIODevice::WriteOnly)) {\n d->errorMessage = QLatin1String(\"Error opening device\");\n *ok = false;\n return;\n }\n }\n\n if (!io->isWritable()) {\n d->errorMessage = QLatin1String(\"Device is not readable\");\n io->close();\n *ok = false;\n return;\n }\n\n const QByteArray str = serialize( v, ok);\n if (*ok && (io->write(str) != str.count())) {\n *ok = false;\n d->errorMessage = QLatin1String(\"Something went wrong while writing to IO device\");\n }\n}\n\nQByteArray Serializer::serialize( const QVariant &v)\n{\n bool ok;\n\n return serialize(v, &ok);\n}\n\nQByteArray Serializer::serialize( const QVariant &v, bool *ok)\n{\n bool _ok = true;\n d->errorMessage.clear();\n\n if (ok) {\n *ok = true;\n } else {\n ok = &_ok;\n }\n\n return d->serialize(v, ok);\n}\n\nvoid QJson::Serializer::allowSpecialNumbers(bool allow) {\n d->specialNumbersAllowed = allow;\n}\n\nbool QJson::Serializer::specialNumbersAllowed() const {\n return d->specialNumbersAllowed;\n}\n\nvoid QJson::Serializer::setIndentMode(IndentMode mode) {\n d->indentMode = mode;\n}\n\nvoid QJson::Serializer::setDoublePrecision(int precision) {\n d->doublePrecision = precision;\n}\n\nIndentMode QJson::Serializer::indentMode() const {\n return d->indentMode;\n}\n\nQString QJson::Serializer::errorMessage() const {\n return d->errorMessage;\n}\n\n<commit_msg>Compile fix with -Wall -Werror -Wextra<commit_after>\/* This file is part of qjson\n *\n * Copyright (C) 2009 Till Adam <adam@kde.org>\n * Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>\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 License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"serializer.h\"\n\n#include <QtCore\/QDataStream>\n#include <QtCore\/QStringList>\n#include <QtCore\/QVariant>\n\n#include <cmath>\n\n#ifdef _MSC_VER \/\/ using MSVC compiler\n#include <float.h>\n#endif\n\nusing namespace QJson;\n\nclass Serializer::SerializerPrivate {\n public:\n SerializerPrivate() :\n specialNumbersAllowed(false),\n indentMode(QJson::IndentNone),\n doublePrecision(6) {\n errorMessage.clear();\n }\n QString errorMessage;\n bool specialNumbersAllowed;\n IndentMode indentMode;\n int doublePrecision;\n QByteArray buildIndent(int spaces);\n QByteArray serialize( const QVariant &v, bool *ok, int indentLevel = 0);\n QString sanitizeString( QString str );\n QByteArray join( const QList<QByteArray>& list, const QByteArray& sep );\n};\n\nQByteArray Serializer::SerializerPrivate::join( const QList<QByteArray>& list, const QByteArray& sep ) {\n QByteArray res;\n Q_FOREACH( const QByteArray& i, list ) {\n if ( !res.isEmpty() )\n res += sep;\n res += i;\n }\n return res;\n}\n\nQByteArray Serializer::SerializerPrivate::serialize( const QVariant &v, bool *ok, int indentLevel)\n{\n QByteArray str;\n\n if ( ! v.isValid() ) { \/\/ invalid or null?\n str = \"null\";\n } else if (( v.type() == QVariant::List ) || ( v.type() == QVariant::StringList )){ \/\/ an array or a stringlist?\n const QVariantList list = v.toList();\n QList<QByteArray> values;\n Q_FOREACH( const QVariant& var, list )\n {\n indentLevel++;\n QByteArray serializedValue = serialize( var, ok, indentLevel);\n indentLevel--;\n if ( !*ok ) {\n break;\n }\n values << serializedValue;\n }\n\n if (indentMode == QJson::IndentMinimum) {\n QByteArray indent = buildIndent(indentLevel - 1);\n str = \"[\\n\" + join( values, \",\\n\" ) + \"\\n\" + indent + \"]\";\n }\n else if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n str = \"[\\n\" + join( values, \",\\n\" ) + \"\\n\" + indent + \"]\";\n }\n else if (indentMode == QJson::IndentCompact) {\n str = \"[\" + join( values, \",\" ) + \"]\";\n }\n else {\n str = \"[ \" + join( values, \", \" ) + \" ]\";\n }\n\n } else if ( v.type() == QVariant::Map ) { \/\/ variant is a map?\n const QVariantMap vmap = v.toMap();\n QMapIterator<QString, QVariant> it( vmap );\n\n if (indentMode == QJson::IndentMinimum) {\n QByteArray indent = buildIndent(indentLevel);\n str = indent + \"{ \";\n }\n else if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n QByteArray nextindent = buildIndent(indentLevel + 1);\n str = indent + \"{\\n\" + nextindent;\n }\n else if (indentMode == QJson::IndentCompact) {\n str = \"{\";\n }\n else {\n str = \"{ \";\n }\n\n QList<QByteArray> pairs;\n while ( it.hasNext() ) {\n it.next();\n indentLevel++;\n QByteArray serializedValue = serialize( it.value(), ok, indentLevel);\n indentLevel--;\n if ( !*ok ) {\n break;\n }\n QByteArray key = sanitizeString( it.key() ).toUtf8();\n QByteArray value = serializedValue;\n if (indentMode == QJson::IndentCompact) {\n pairs << key + \":\" + value;\n } else {\n pairs << key + \" : \" + value;\n }\n }\n\n if (indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel + 1);\n str += join( pairs, \",\\n\" + indent);\n }\n else if (indentMode == QJson::IndentCompact) {\n str += join( pairs, \",\" );\n }\n else {\n str += join( pairs, \", \" );\n }\n\n if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n str += \"\\n\" + indent + \"}\";\n }\n else if (indentMode == QJson::IndentCompact) {\n str += \"}\";\n }\n else {\n str += \" }\";\n }\n\n } else if ( v.type() == QVariant::Hash ) { \/\/ variant is a hash?\n const QVariantHash vhash = v.toHash();\n QHashIterator<QString, QVariant> it( vhash );\n\n if (indentMode == QJson::IndentMinimum) {\n QByteArray indent = buildIndent(indentLevel);\n str = indent + \"{ \";\n }\n else if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n QByteArray nextindent = buildIndent(indentLevel + 1);\n str = indent + \"{\\n\" + nextindent;\n }\n else if (indentMode == QJson::IndentCompact) {\n str = \"{\";\n }\n else {\n str = \"{ \";\n }\n\n QList<QByteArray> pairs;\n while ( it.hasNext() ) {\n it.next();\n indentLevel++;\n QByteArray serializedValue = serialize( it.value(), ok, indentLevel);\n indentLevel--;\n if ( !*ok ) {\n break;\n }\n QByteArray key = sanitizeString( it.key() ).toUtf8();\n QByteArray value = serializedValue;\n if (indentMode == QJson::IndentCompact) {\n pairs << key + \":\" + value;\n } else {\n pairs << key + \" : \" + value;\n }\n }\n\n if (indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel + 1);\n str += join( pairs, \",\\n\" + indent);\n }\n else if (indentMode == QJson::IndentCompact) {\n str += join( pairs, \",\" );\n }\n else {\n str += join( pairs, \", \" );\n }\n\n if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {\n QByteArray indent = buildIndent(indentLevel);\n str += \"\\n\" + indent + \"}\";\n }\n else if (indentMode == QJson::IndentCompact) {\n str += \"}\";\n }\n else {\n str += \" }\";\n }\n\n } else if (( v.type() == QVariant::String ) || ( v.type() == QVariant::ByteArray )) { \/\/ a string or a byte array?\n str = sanitizeString( v.toString() ).toUtf8();\n } else if (( v.type() == QVariant::Double) || ((QMetaType::Type)v.type() == QMetaType::Float)) { \/\/ a double or a float?\n const double value = v.toDouble();\n#if defined _WIN32 && !defined(Q_OS_SYMBIAN)\n const bool special = _isnan(value) || !_finite(value);\n#elif defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID)\n const bool special = isnan(value) || isinf(value);\n#else\n const bool special = std::isnan(value) || std::isinf(value);\n#endif\n if (special) {\n if (specialNumbersAllowed) {\n#if defined _WIN32 && !defined(Q_OS_SYMBIAN)\n if (_isnan(value)) {\n#elif defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID)\n if (isnan(value)) {\n#else\n if (std::isnan(value)) {\n#endif\n str += \"NaN\";\n } else {\n if (value<0) {\n str += '-';\n }\n str += \"Infinity\";\n }\n } else {\n errorMessage += QLatin1String(\"Attempt to write NaN or infinity, which is not supported by json\\n\");\n *ok = false;\n }\n } else {\n str = QByteArray::number( value , 'g', doublePrecision);\n if( ! str.contains( \".\" ) && ! str.contains( \"e\" ) ) {\n str += \".0\";\n }\n }\n } else if ( v.type() == QVariant::Bool ) { \/\/ boolean value?\n str = ( v.toBool() ? \"true\" : \"false\" );\n } else if ( v.type() == QVariant::ULongLong ) { \/\/ large unsigned number?\n str = QByteArray::number( v.value<qulonglong>() );\n } else if ( v.type() == QVariant::UInt ) { \/\/ unsigned int number?\n str = QByteArray::number( v.value<quint32>() );\n } else if ( v.canConvert<qlonglong>() ) { \/\/ any signed number?\n str = QByteArray::number( v.value<qlonglong>() );\n } else if ( v.canConvert<int>() ) { \/\/ unsigned short number?\n str = QByteArray::number( v.value<int>() );\n } else if ( v.canConvert<QString>() ){ \/\/ can value be converted to string?\n \/\/ this will catch QDate, QDateTime, QUrl, ...\n str = sanitizeString( v.toString() ).toUtf8();\n \/\/TODO: catch other values like QImage, QRect, ...\n } else {\n *ok = false;\n errorMessage += QLatin1String(\"Cannot serialize \");\n errorMessage += v.toString();\n errorMessage += QLatin1String(\" because type \");\n errorMessage += QLatin1String(v.typeName());\n errorMessage += QLatin1String(\" is not supported by QJson\\n\");\n }\n if ( *ok )\n {\n return str;\n }\n else\n return QByteArray();\n}\n\nQByteArray Serializer::SerializerPrivate::buildIndent(int spaces)\n{\n QByteArray indent;\n if (spaces < 0) {\n spaces = 0;\n }\n for (int i = 0; i < spaces; i++ ) {\n indent += \" \";\n }\n return indent;\n}\n\nQString Serializer::SerializerPrivate::sanitizeString( QString str )\n{\n str.replace( QLatin1String( \"\\\\\" ), QLatin1String( \"\\\\\\\\\" ) );\n\n \/\/ escape unicode chars\n QString result;\n const ushort* unicode = str.utf16();\n unsigned int i = 0;\n\n while ( unicode[ i ] ) {\n if ( unicode[ i ] < 128 ) {\n result.append( QChar( unicode[ i ] ) );\n }\n else {\n QString hexCode = QString::number( unicode[ i ], 16 ).rightJustified( 4,\n QLatin1Char('0') );\n\n result.append( QLatin1String (\"\\\\u\") ).append( hexCode );\n }\n ++i;\n }\n str = result;\n\n str.replace( QLatin1String( \"\\\"\" ), QLatin1String( \"\\\\\\\"\" ) );\n str.replace( QLatin1String( \"\\b\" ), QLatin1String( \"\\\\b\" ) );\n str.replace( QLatin1String( \"\\f\" ), QLatin1String( \"\\\\f\" ) );\n str.replace( QLatin1String( \"\\n\" ), QLatin1String( \"\\\\n\" ) );\n str.replace( QLatin1String( \"\\r\" ), QLatin1String( \"\\\\r\" ) );\n str.replace( QLatin1String( \"\\t\" ), QLatin1String( \"\\\\t\" ) );\n\n return QString( QLatin1String( \"\\\"%1\\\"\" ) ).arg( str );\n}\n\nSerializer::Serializer()\n : d( new SerializerPrivate )\n{\n}\n\nSerializer::~Serializer() {\n delete d;\n}\n\nvoid Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok)\n{\n Q_ASSERT( io );\n *ok = true;\n\n if (!io->isOpen()) {\n if (!io->open(QIODevice::WriteOnly)) {\n d->errorMessage = QLatin1String(\"Error opening device\");\n *ok = false;\n return;\n }\n }\n\n if (!io->isWritable()) {\n d->errorMessage = QLatin1String(\"Device is not readable\");\n io->close();\n *ok = false;\n return;\n }\n\n const QByteArray str = serialize( v, ok);\n if (*ok && (io->write(str) != str.count())) {\n *ok = false;\n d->errorMessage = QLatin1String(\"Something went wrong while writing to IO device\");\n }\n}\n\nQByteArray Serializer::serialize( const QVariant &v)\n{\n bool ok;\n\n return serialize(v, &ok);\n}\n\nQByteArray Serializer::serialize( const QVariant &v, bool *ok)\n{\n bool _ok = true;\n d->errorMessage.clear();\n\n if (ok) {\n *ok = true;\n } else {\n ok = &_ok;\n }\n\n return d->serialize(v, ok);\n}\n\nvoid QJson::Serializer::allowSpecialNumbers(bool allow) {\n d->specialNumbersAllowed = allow;\n}\n\nbool QJson::Serializer::specialNumbersAllowed() const {\n return d->specialNumbersAllowed;\n}\n\nvoid QJson::Serializer::setIndentMode(IndentMode mode) {\n d->indentMode = mode;\n}\n\nvoid QJson::Serializer::setDoublePrecision(int precision) {\n d->doublePrecision = precision;\n}\n\nIndentMode QJson::Serializer::indentMode() const {\n return d->indentMode;\n}\n\nQString QJson::Serializer::errorMessage() const {\n return d->errorMessage;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\r\n#include <stdio.h>\r\n\r\n#include \"httpServer.h\"\r\n#include \"logging.h\"\r\n\r\nHttpServer::HttpServer(int portNr)\r\n{\r\n listenSocket.listen(portNr);\r\n selector.add(listenSocket);\r\n}\r\n\r\nHttpServer::~HttpServer()\r\n{\r\n listenSocket.close();\r\n for(unsigned int n=0; n<connections.size(); n++)\r\n delete connections[n];\r\n for(unsigned int n=0; n<handlers.size(); n++)\r\n delete handlers[n];\r\n}\r\n\r\nvoid HttpServer::update(float delta)\r\n{\r\n if (selector.wait(sf::microseconds(1)))\r\n {\r\n if (selector.isReady(listenSocket))\r\n {\r\n HttpServerConnection* connection = new HttpServerConnection(this);\r\n if (listenSocket.accept(connection->socket) == sf::Socket::Done)\r\n {\r\n connections.push_back(connection);\r\n selector.add(connection->socket);\r\n }else{\r\n delete connection;\r\n }\r\n }\r\n for(unsigned int n=0; n<connections.size(); n++)\r\n {\r\n if (selector.isReady(connections[n]->socket))\r\n {\r\n if (!connections[n]->read())\r\n {\r\n selector.remove(connections[n]->socket);\r\n delete connections[n];\r\n connections.erase(connections.begin() + n);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nHttpServerConnection::HttpServerConnection(HttpServer* server)\n: server(server)\r\n{\r\n recvBufferCount = 0;\r\n status = METHOD;\r\n}\r\n\r\nbool HttpServerConnection::read()\r\n{\r\n char buffer[1024];\r\n size_t size;\r\n if (socket.receive(buffer, sizeof(buffer), size) != sf::Socket::Done)\r\n return false;\r\n if (recvBufferCount + size > recvBufferSize)\r\n size = recvBufferSize - recvBufferCount;\r\n if (size < 1)\r\n return false;\r\n memcpy(recvBuffer + recvBufferCount, buffer, size);\r\n recvBufferCount += size;\r\n\r\n while(true)\r\n {\r\n char* ptr = (char*)memchr(recvBuffer, '\\n', recvBufferCount);\r\n if (!ptr)\r\n break;\n *ptr = '\\0';\n string line(recvBuffer);\r\n ptr++;\n size_t len = ptr - recvBuffer;\r\n recvBufferCount -= len;\n memmove(recvBuffer, ptr, recvBufferCount);\n if (line.endswith(\"\\r\"))\n line = line.substr(0, -1);\r\n if (!handleLine(line))\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\nstring HttpServerConnection::UriDecode(const string & sSrc)\r\n{\r\n \/\/ Note from RFC1630: \"Sequences which start with a percent\r\n \/\/ sign but are not followed by two hexadecimal characters\r\n \/\/ (0-9, A-F) are reserved for future extension\"\r\n\r\n const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();\r\n const int SRC_LEN = sSrc.length();\r\n const unsigned char * const SRC_END = pSrc + SRC_LEN;\r\n \/\/ const char DEC2HEX[16 + 1] = \"0123456789ABCDEF\";\r\n \/\/ last decodable '%'\r\n const unsigned char * const SRC_LAST_DEC = SRC_END - 2;\r\n\r\n char * const pStart = new char[SRC_LEN];\r\n char * pEnd = pStart;\r\n\r\n while (pSrc < SRC_LAST_DEC)\r\n {\r\n if (*pSrc == '%')\r\n {\r\n char dec1, dec2;\r\n if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])\r\n && -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))\r\n {\r\n *pEnd++ = (dec1 << 4) + dec2;\r\n pSrc += 3;\r\n continue;\r\n }\r\n }\r\n\r\n *pEnd++ = *pSrc++;\r\n }\r\n\r\n \/\/ the last 2- chars\r\n while (pSrc < SRC_END)\r\n *pEnd++ = *pSrc++;\r\n\r\n std::string sResult(pStart, pEnd);\r\n delete [] pStart;\r\n return (string) sResult;\r\n}\r\n\r\nvoid HttpServerConnection::parseUri(const string & sSrc)\r\n{\r\n string uri = UriDecode(sSrc);\r\n std::size_t found = uri.find('?');\r\n if (found==std::string::npos)\r\n {\r\n request.path = uri;\r\n return;\r\n }\r\n else\r\n {\r\n std::vector<string> parts = uri.split(\"?\", 1);\r\n request.path = parts[0];\r\n\r\n std::vector<string> parameters = parts[1].split(\"&\");\r\n for (unsigned int n=0; n<parameters.size(); n++)\r\n {\r\n string param = parameters[n];\r\n std::size_t found = param.find('=');\r\n if (found==std::string::npos)\r\n {\r\n request.parameters[param] = sFALSE;\r\n LOG(DEBUG) << \"HTTP Parameter: \" << param;\r\n }\r\n else\r\n {\r\n if (param.endswith('='))\r\n {\r\n request.parameters[param.substr(0, param.length()-1)] = sFALSE;\r\n LOG(DEBUG) << \"HTTP Parameter: \" << param.substr(0, param.length()-1);\r\n }\r\n else\r\n {\r\n std::vector<string> items = param.split(\"=\", 1);\r\n request.parameters[items[0]] = items[1];\r\n LOG(DEBUG) << \"HTTP Parameter: \" << items[0] << \" = \" << items[1];\r\n }\r\n }\r\n }\r\n }\r\n LOG(DEBUG) << \"HTTP Path: \" << request.path;\r\n}\r\n\r\nbool HttpServerConnection::handleLine(string line)\r\n{\n switch(status)\r\n {\r\n case METHOD:{\n std::vector<string> parts = line.split();\n if (parts.size() != 3)\n return false;\n request.method = parts[0];\r\n parseUri(parts[1]);\n \/\/request.path = parts[1];\n status = HEADERS;\n }break;\r\n case HEADERS:\r\n if (line.length() == 0)\r\n {\n request.post_data = \"\";\n if (request.method == \"POST\")\n {\n if (request.headers.find(\"content-length\") != request.headers.end())\n {\n unsigned int body_length = request.headers[\"content-length\"].toInt();\n if (body_length > recvBufferSize)\n return false;\n while (body_length > recvBufferCount)\n {\n size_t received;\n if (socket.receive(recvBuffer + recvBufferCount, body_length - recvBufferCount, received) != sf::Socket::Done)\r\n return false;\n recvBufferCount += received;\n }\n request.post_data = string(recvBuffer, body_length);\n recvBufferCount -= body_length;\n memmove(recvBuffer, recvBuffer + body_length, recvBufferCount);\n }\n }\r\n status = METHOD;\n LOG(DEBUG) << \"HTTP request: \" << request.path;\r\n#ifdef DEBUG\r\n for (std::map<string, string>::iterator iter = request.headers.begin(); iter != request.headers.end(); iter++)\r\n {\r\n string key=iter->first;\r\n string value=iter->second;\r\n LOG(DEBUG) << \"HTTP header: (\" << key << \", \" << value << \")\";\r\n }\r\n#endif \/\/ DEBUG\n handleRequest();\r\n }else{\n std::vector<string> parts = line.split(\":\", 1);\n if (parts.size() != 2)\n LOG(WARNING) << \"Invalid HTTP header: \" << line;\n else\r\n request.headers[parts[0].strip().lower()] = parts[1];\r\n }\r\n break;\r\n }\r\n return true;\r\n}\r\n\r\nvoid HttpServerConnection::handleRequest()\r\n{\n reply_code = 200;\n headers_send = false;\n\n for(unsigned int n=0; n<server->handlers.size(); n++)\n {\n if (server->handlers[n]->handleRequest(request, this))\n break;\n if (headers_send)\n break;\n }\n\n if (!headers_send)\n {\n reply_code = 404;\r\n string replyData = \"File not found\";\n sendData(replyData.c_str(), replyData.size());\r\n }\n string end_chunk = \"0\\r\\n\\r\\n\";\n socket.send(end_chunk.c_str(), end_chunk.size());\r\n request.parameters.clear();\r\n}\n\nvoid HttpServerConnection::sendHeaders()\n{\n string reply = string(\"HTTP\/1.1 \") + string(reply_code) + \" OK\\r\\n\";\r\n reply += \"Content-type: text\/html\\r\\n\";\r\n reply += \"Connection: Keep-Alive\\r\\n\";\r\n reply += \"Transfer-Encoding: chunked\\r\\n\";\r\n reply += \"\\r\\n\";\r\n socket.send(reply.c_str(), reply.size());\n headers_send = true;\r\n}\r\n\nvoid HttpServerConnection::sendData(const char* data, size_t data_length)\n{\n if (!headers_send)\n sendHeaders();\n if (data_length < 1)\n return;\n string chunk_len_string = string::hex(data_length) + \"\\r\\n\";\n socket.send(chunk_len_string.c_str(), chunk_len_string.size());\n socket.send(data, data_length);\n socket.send(\"\\r\\n\", 2);\n}\r\n\r\nconst char HttpServerConnection::HEX2DEC[256] =\r\n{\r\n \/* 0 1 2 3 4 5 6 7 8 9 A B C D E F *\/\r\n \/* 0 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 1 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 2 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 3 *\/ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* 4 *\/ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 5 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 6 *\/ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 7 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* 8 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 9 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* A *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* B *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* C *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* D *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* E *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* F *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1\r\n};\n\nbool HttpRequestFileHandler::handleRequest(HttpRequest& request, HttpServerConnection* connection)\n{\n string replyData = \"\";\r\n FILE* f = NULL;\r\n if (request.path == \"\/\")\r\n request.path = \"\/index.html\";\r\n if (request.path.find(\"..\") != -1)\r\n return false;\r\n\r\n string fullPath = base_path + request.path;\r\n f = fopen(fullPath.c_str(), \"rb\");\r\n if (!f)\r\n return false;\r\n\n while(true)\r\n {\r\n char buffer[1024];\r\n size_t n = fread(buffer, 1, sizeof(buffer), f);\r\n if (n < 1)\r\n break;\r\n connection->sendData(buffer, n);\r\n }\r\n fclose(f);\r\n return true;\n}\n<commit_msg>Added documentation<commit_after>#include <string.h>\r\n#include <stdio.h>\r\n\r\n#include \"httpServer.h\"\r\n#include \"logging.h\"\r\n\r\nHttpServer::HttpServer(int portNr)\r\n{\r\n listenSocket.listen(portNr);\r\n selector.add(listenSocket);\r\n}\r\n\r\nHttpServer::~HttpServer()\r\n{\r\n listenSocket.close();\r\n for(unsigned int n=0; n<connections.size(); n++)\r\n delete connections[n];\r\n for(unsigned int n=0; n<handlers.size(); n++)\r\n delete handlers[n];\r\n}\r\n\r\nvoid HttpServer::update(float delta)\r\n{\r\n if (selector.wait(sf::microseconds(1)))\r\n {\r\n if (selector.isReady(listenSocket))\r\n {\r\n HttpServerConnection* connection = new HttpServerConnection(this);\r\n if (listenSocket.accept(connection->socket) == sf::Socket::Done)\r\n {\r\n connections.push_back(connection);\r\n selector.add(connection->socket);\r\n }else{\r\n delete connection;\r\n }\r\n }\r\n for(unsigned int n=0; n<connections.size(); n++)\r\n {\r\n if (selector.isReady(connections[n]->socket))\r\n {\r\n if (!connections[n]->read())\r\n {\r\n selector.remove(connections[n]->socket);\r\n delete connections[n];\r\n connections.erase(connections.begin() + n);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nHttpServerConnection::HttpServerConnection(HttpServer* server)\n: server(server)\r\n{\r\n recvBufferCount = 0;\r\n status = METHOD;\r\n}\r\n\r\nbool HttpServerConnection::read()\r\n{\r\n char buffer[1024];\r\n size_t size;\r\n if (socket.receive(buffer, sizeof(buffer), size) != sf::Socket::Done)\r\n return false;\r\n if (recvBufferCount + size > recvBufferSize)\r\n size = recvBufferSize - recvBufferCount;\r\n if (size < 1)\r\n return false;\r\n memcpy(recvBuffer + recvBufferCount, buffer, size);\r\n recvBufferCount += size;\r\n\r\n while(true)\r\n {\r\n char* ptr = (char*)memchr(recvBuffer, '\\n', recvBufferCount);\r\n if (!ptr)\r\n break;\n *ptr = '\\0';\n string line(recvBuffer);\r\n ptr++;\n size_t len = ptr - recvBuffer;\r\n recvBufferCount -= len;\n memmove(recvBuffer, ptr, recvBufferCount);\n if (line.endswith(\"\\r\"))\n line = line.substr(0, -1);\r\n if (!handleLine(line))\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\n\/** \\brief Decode a percent-encoded URI\r\n * Uri decoding according to RFC1630, RFC1738, RFC2396\r\n * Credits: Jin Qing\r\n * \\param sSrc const string& Percent-encoded URI\r\n * \\return string Decoded URI-string\r\n *\r\n *\/\r\nstring HttpServerConnection::UriDecode(const string & sSrc)\r\n{\r\n \/\/ Note from RFC1630: \"Sequences which start with a percent\r\n \/\/ sign but are not followed by two hexadecimal characters\r\n \/\/ (0-9, A-F) are reserved for future extension\"\r\n\r\n const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();\r\n const int SRC_LEN = sSrc.length();\r\n const unsigned char * const SRC_END = pSrc + SRC_LEN;\r\n \/\/ last decodable '%'\r\n const unsigned char * const SRC_LAST_DEC = SRC_END - 2;\r\n\r\n char * const pStart = new char[SRC_LEN];\r\n char * pEnd = pStart;\r\n\r\n while (pSrc < SRC_LAST_DEC)\r\n {\r\n if (*pSrc == '%')\r\n {\r\n char dec1, dec2;\r\n if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])\r\n && -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))\r\n {\r\n *pEnd++ = (dec1 << 4) + dec2;\r\n pSrc += 3;\r\n continue;\r\n }\r\n }\r\n\r\n *pEnd++ = *pSrc++;\r\n }\r\n\r\n \/\/ the last 2- chars\r\n while (pSrc < SRC_END)\r\n *pEnd++ = *pSrc++;\r\n\r\n std::string sResult(pStart, pEnd);\r\n delete [] pStart;\r\n return (string) sResult;\r\n}\r\n\r\n\r\n\/**< Map to convert between character encodings *\/\r\nconst char HttpServerConnection::HEX2DEC[256] =\r\n{\r\n \/* 0 1 2 3 4 5 6 7 8 9 A B C D E F *\/\r\n \/* 0 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 1 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 2 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 3 *\/ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* 4 *\/ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 5 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 6 *\/ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 7 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* 8 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 9 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* A *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* B *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* C *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* D *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* E *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* F *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1\r\n};\r\n\r\n\r\n\/** \\brief Parse a URL, splitting it in its part and optional parameters\r\n *\r\n * \\param sSrc const string& URL\r\n * \\return void\r\n *\r\n *\/\r\nvoid HttpServerConnection::parseUri(const string & sSrc)\r\n{\r\n string uri = UriDecode(sSrc);\r\n std::size_t found = uri.find('?');\r\n if (found==std::string::npos)\r\n {\r\n request.path = uri;\r\n return;\r\n }\r\n else\r\n {\r\n std::vector<string> parts = uri.split(\"?\", 1);\r\n request.path = parts[0];\r\n\r\n std::vector<string> parameters = parts[1].split(\"&\");\r\n for (unsigned int n=0; n<parameters.size(); n++)\r\n {\r\n string param = parameters[n];\r\n std::size_t found = param.find('=');\r\n if (found==std::string::npos)\r\n {\r\n request.parameters[param] = sFALSE;\r\n LOG(DEBUG) << \"HTTP Parameter: \" << param;\r\n }\r\n else\r\n {\r\n if (param.endswith('='))\r\n {\r\n request.parameters[param.substr(0, param.length()-1)] = sFALSE;\r\n LOG(DEBUG) << \"HTTP Parameter: \" << param.substr(0, param.length()-1);\r\n }\r\n else\r\n {\r\n std::vector<string> items = param.split(\"=\", 1);\r\n request.parameters[items[0]] = items[1];\r\n LOG(DEBUG) << \"HTTP Parameter: \" << items[0] << \" = \" << items[1];\r\n }\r\n }\r\n }\r\n }\r\n LOG(DEBUG) << \"HTTP Path: \" << request.path;\r\n}\r\n\r\nbool HttpServerConnection::handleLine(string line)\r\n{\n switch(status)\r\n {\r\n case METHOD:{\n std::vector<string> parts = line.split();\n if (parts.size() != 3)\n return false;\n request.method = parts[0];\r\n parseUri(parts[1]);\n \/\/request.path = parts[1];\n status = HEADERS;\n }break;\r\n case HEADERS:\r\n if (line.length() == 0)\r\n {\n request.post_data = \"\";\n if (request.method == \"POST\")\n {\n if (request.headers.find(\"content-length\") != request.headers.end())\n {\n unsigned int body_length = request.headers[\"content-length\"].toInt();\n if (body_length > recvBufferSize)\n return false;\n while (body_length > recvBufferCount)\n {\n size_t received;\n if (socket.receive(recvBuffer + recvBufferCount, body_length - recvBufferCount, received) != sf::Socket::Done)\r\n return false;\n recvBufferCount += received;\n }\n request.post_data = string(recvBuffer, body_length);\n recvBufferCount -= body_length;\n memmove(recvBuffer, recvBuffer + body_length, recvBufferCount);\n }\n }\r\n status = METHOD;\r\n#ifdef DEBUG\r\n for (std::map<string, string>::iterator iter = request.headers.begin(); iter != request.headers.end(); iter++)\r\n {\r\n string key=iter->first;\r\n string value=iter->second;\r\n LOG(DEBUG) << \"HTTP header: (\" << key << \", \" << value << \")\";\r\n }\r\n#endif \/\/ DEBUG\n handleRequest();\r\n }else{\n std::vector<string> parts = line.split(\":\", 1);\n if (parts.size() != 2)\n LOG(WARNING) << \"Invalid HTTP header: \" << line;\n else\r\n request.headers[parts[0].strip().lower()] = parts[1];\r\n }\r\n break;\r\n }\r\n return true;\r\n}\r\n\r\nvoid HttpServerConnection::handleRequest()\r\n{\n reply_code = 200;\n headers_send = false;\n\n for(unsigned int n=0; n<server->handlers.size(); n++)\n {\n if (server->handlers[n]->handleRequest(request, this))\n break;\n if (headers_send)\n break;\n }\n\n if (!headers_send)\n {\n reply_code = 404;\r\n string replyData = \"File not found\";\n sendData(replyData.c_str(), replyData.size());\r\n }\n string end_chunk = \"0\\r\\n\\r\\n\";\n socket.send(end_chunk.c_str(), end_chunk.size());\r\n request.parameters.clear();\r\n}\n\nvoid HttpServerConnection::sendHeaders()\n{\n string reply = string(\"HTTP\/1.1 \") + string(reply_code) + \" OK\\r\\n\";\r\n reply += \"Content-type: text\/html\\r\\n\";\r\n reply += \"Connection: Keep-Alive\\r\\n\";\r\n reply += \"Transfer-Encoding: chunked\\r\\n\";\r\n reply += \"\\r\\n\";\r\n socket.send(reply.c_str(), reply.size());\n headers_send = true;\r\n}\r\n\nvoid HttpServerConnection::sendData(const char* data, size_t data_length)\n{\n if (!headers_send)\n sendHeaders();\n if (data_length < 1)\n return;\n string chunk_len_string = string::hex(data_length) + \"\\r\\n\";\n socket.send(chunk_len_string.c_str(), chunk_len_string.size());\n socket.send(data, data_length);\n socket.send(\"\\r\\n\", 2);\n}\n\nbool HttpRequestFileHandler::handleRequest(HttpRequest& request, HttpServerConnection* connection)\n{\n string replyData = \"\";\r\n FILE* f = NULL;\r\n if (request.path == \"\/\")\r\n request.path = \"\/index.html\";\r\n if (request.path.find(\"..\") != -1)\r\n return false;\r\n\r\n string fullPath = base_path + request.path;\r\n f = fopen(fullPath.c_str(), \"rb\");\r\n if (!f)\r\n return false;\r\n\n while(true)\r\n {\r\n char buffer[1024];\r\n size_t n = fread(buffer, 1, sizeof(buffer), f);\r\n if (n < 1)\r\n break;\r\n connection->sendData(buffer, n);\r\n }\r\n fclose(f);\r\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SSL and TLS filter.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"ssl_filter.hxx\"\n#include \"ssl_factory.hxx\"\n#include \"ssl_config.hxx\"\n#include \"ssl_quark.hxx\"\n#include \"thread_socket_filter.hxx\"\n#include \"pool.hxx\"\n#include \"gerrno.h\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n\n#include <openssl\/ssl.h>\n#include <openssl\/err.h>\n\n#include <assert.h>\n#include <string.h>\n\nstruct ssl_filter {\n \/**\n * Buffers which can be accessed from within the thread without\n * holding locks. These will be copied to\/from the accordding\n * #thread_socket_filter buffers.\n *\/\n SliceFifoBuffer decrypted_input, plain_output;\n\n \/**\n * Memory BIOs for passing data to\/from OpenSSL.\n *\/\n BIO *encrypted_input, *encrypted_output;\n\n SSL *ssl;\n\n bool handshaking;\n\n char *peer_subject, *peer_issuer_subject;\n};\n\nstatic void\nssl_set_error(GError **error_r)\n{\n if (error_r == NULL)\n return;\n\n unsigned long error = ERR_get_error();\n char buffer[120];\n g_set_error(error_r, ssl_quark(), 0, \"%s\",\n ERR_error_string(error, buffer));\n}\n\n\/**\n * Move data from #src to #dest.\n *\/\nstatic void\nMove(ForeignFifoBuffer<uint8_t> &dest, ForeignFifoBuffer<uint8_t> &src)\n{\n auto r = src.Read();\n if (r.IsEmpty())\n return;\n\n auto w = dest.Write();\n if (w.IsEmpty())\n return;\n\n size_t nbytes = std::min(r.size, w.size);\n\n memcpy(w.data, r.data, nbytes);\n dest.Append(nbytes);\n src.Consume(nbytes);\n}\n\n\/**\n * Move data from #src to #dest.\n *\/\nstatic void\nMove(BIO *dest, ForeignFifoBuffer<uint8_t> &src)\n{\n auto r = src.Read();\n if (r.IsEmpty())\n return;\n\n int nbytes = BIO_write(dest, r.data, r.size);\n if (nbytes > 0)\n src.Consume(nbytes);\n}\n\nstatic void\nMove(ForeignFifoBuffer<uint8_t> &dest, BIO *src)\n{\n while (true) {\n auto w = dest.Write();\n if (w.IsEmpty())\n return;\n\n int nbytes = BIO_read(src, w.data, w.size);\n if (nbytes <= 0)\n return;\n\n dest.Append(nbytes);\n }\n}\n\nstatic char *\nformat_name(X509_NAME *name)\n{\n if (name == NULL)\n return NULL;\n\n BIO *bio = BIO_new(BIO_s_mem());\n if (bio == NULL)\n return NULL;\n\n X509_NAME_print_ex(bio, name, 0,\n ASN1_STRFLGS_UTF8_CONVERT | XN_FLAG_SEP_COMMA_PLUS);\n char buffer[1024];\n int length = BIO_read(bio, buffer, sizeof(buffer) - 1);\n BIO_free(bio);\n\n return strndup(buffer, length);\n}\n\nstatic char *\nformat_subject_name(X509 *cert)\n{\n return format_name(X509_get_subject_name(cert));\n}\n\nstatic char *\nformat_issuer_subject_name(X509 *cert)\n{\n return format_name(X509_get_issuer_name(cert));\n}\n\ngcc_const\nstatic bool\nis_ssl_error(SSL *ssl, int ret)\n{\n switch (SSL_get_error(ssl, ret)) {\n case SSL_ERROR_NONE:\n case SSL_ERROR_WANT_READ:\n case SSL_ERROR_WANT_WRITE:\n case SSL_ERROR_WANT_CONNECT:\n case SSL_ERROR_WANT_ACCEPT:\n return false;\n\n default:\n return true;\n }\n}\n\nstatic bool\ncheck_ssl_error(SSL *ssl, int result, GError **error_r)\n{\n if (is_ssl_error(ssl, result)) {\n ssl_set_error(error_r);\n return false;\n } else\n return true;\n}\n\n\/**\n * @return false on error\n *\/\nstatic bool\nssl_decrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer, GError **error_r)\n{\n \/* SSL_read() must be called repeatedly until there is no more\n data (or until the buffer is full) *\/\n\n while (true) {\n auto w = buffer.Write();\n if (w.IsEmpty())\n return 0;\n\n int result = SSL_read(ssl, w.data, w.size);\n if (result <= 0)\n return result == 0 || check_ssl_error(ssl, result, error_r);\n\n buffer.Append(result);\n }\n}\n\n\/**\n * @return false on error\n *\/\nstatic bool\nssl_encrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer, GError **error_r)\n{\n auto r = buffer.Read();\n if (r.IsEmpty())\n return true;\n\n int result = SSL_write(ssl, r.data, r.size);\n if (result < 0 && !check_ssl_error(ssl, result, error_r))\n return false;\n\n if (result > 0)\n buffer.Consume(result);\n\n return true;\n}\n\n\/*\n * thread_socket_filter_handler\n *\n *\/\n\nstatic bool\nssl_thread_socket_filter_run(ThreadSocketFilter &f, GError **error_r,\n void *ctx)\n{\n struct ssl_filter *ssl = (struct ssl_filter *)ctx;\n\n \/* copy input (and output to make room for more output) *\/\n\n pthread_mutex_lock(&f.mutex);\n Move(f.decrypted_input, ssl->decrypted_input);\n Move(ssl->plain_output, f.plain_output);\n Move(ssl->encrypted_input, f.encrypted_input);\n Move(f.encrypted_output, ssl->encrypted_output);\n pthread_mutex_unlock(&f.mutex);\n\n \/* let OpenSSL work *\/\n\n ERR_clear_error();\n\n if (gcc_unlikely(ssl->handshaking)) {\n int result = SSL_do_handshake(ssl->ssl);\n if (result == 1) {\n ssl->handshaking = false;\n\n X509 *cert = SSL_get_peer_certificate(ssl->ssl);\n if (cert != nullptr) {\n ssl->peer_subject = format_subject_name(cert);\n ssl->peer_issuer_subject = format_issuer_subject_name(cert);\n X509_free(cert);\n }\n } else if (result == 0) {\n ssl_set_error(error_r);\n return false;\n } else if (!check_ssl_error(ssl->ssl, result, error_r))\n return false;\n }\n\n if (gcc_likely(!ssl->handshaking) &&\n (!ssl_encrypt(ssl->ssl, ssl->plain_output, error_r) ||\n !ssl_decrypt(ssl->ssl, ssl->decrypted_input, error_r)))\n return false;\n\n \/* copy output *\/\n\n pthread_mutex_lock(&f.mutex);\n Move(f.decrypted_input, ssl->decrypted_input);\n Move(f.encrypted_output, ssl->encrypted_output);\n f.drained = ssl->plain_output.IsEmpty() &&\n BIO_eof(ssl->encrypted_output);\n pthread_mutex_unlock(&f.mutex);\n\n return true;\n}\n\nstatic void\nssl_thread_socket_filter_destroy(gcc_unused ThreadSocketFilter &f, void *ctx)\n{\n struct ssl_filter *ssl = (struct ssl_filter *)ctx;\n\n if (ssl->ssl != NULL)\n SSL_free(ssl->ssl);\n\n ssl->decrypted_input.Free(fb_pool_get());\n ssl->plain_output.Free(fb_pool_get());\n\n free(ssl->peer_subject);\n free(ssl->peer_issuer_subject);\n}\n\nconst struct ThreadSocketFilterHandler ssl_thread_socket_filter = {\n ssl_thread_socket_filter_run,\n ssl_thread_socket_filter_destroy,\n};\n\n\/*\n * constructor\n *\n *\/\n\nstruct ssl_filter *\nssl_filter_new(struct pool *pool, ssl_factory &factory,\n GError **error_r)\n{\n assert(pool != NULL);\n\n ssl_filter *ssl = NewFromPool<ssl_filter>(*pool);\n\n ssl->ssl = ssl_factory_make(factory);\n if (ssl->ssl == NULL) {\n g_set_error(error_r, ssl_quark(), 0, \"SSL_new() failed\");\n return NULL;\n }\n\n ssl->decrypted_input.Allocate(fb_pool_get());\n ssl->plain_output.Allocate(fb_pool_get());\n ssl->encrypted_input = BIO_new(BIO_s_mem());\n ssl->encrypted_output = BIO_new(BIO_s_mem());\n\n SSL_set_bio(ssl->ssl, ssl->encrypted_input, ssl->encrypted_output);\n\n ssl->peer_subject = NULL;\n ssl->peer_issuer_subject = NULL;\n ssl->handshaking = true;\n\n return ssl;\n}\n\nconst char *\nssl_filter_get_peer_subject(struct ssl_filter *ssl)\n{\n assert(ssl != NULL);\n\n return ssl->peer_subject;\n}\n\nconst char *\nssl_filter_get_peer_issuer_subject(struct ssl_filter *ssl)\n{\n assert(ssl != NULL);\n\n return ssl->peer_issuer_subject;\n}\n<commit_msg>ssl_filter: fix comment typo<commit_after>\/*\n * SSL and TLS filter.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"ssl_filter.hxx\"\n#include \"ssl_factory.hxx\"\n#include \"ssl_config.hxx\"\n#include \"ssl_quark.hxx\"\n#include \"thread_socket_filter.hxx\"\n#include \"pool.hxx\"\n#include \"gerrno.h\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n\n#include <openssl\/ssl.h>\n#include <openssl\/err.h>\n\n#include <assert.h>\n#include <string.h>\n\nstruct ssl_filter {\n \/**\n * Buffers which can be accessed from within the thread without\n * holding locks. These will be copied to\/from the according\n * #thread_socket_filter buffers.\n *\/\n SliceFifoBuffer decrypted_input, plain_output;\n\n \/**\n * Memory BIOs for passing data to\/from OpenSSL.\n *\/\n BIO *encrypted_input, *encrypted_output;\n\n SSL *ssl;\n\n bool handshaking;\n\n char *peer_subject, *peer_issuer_subject;\n};\n\nstatic void\nssl_set_error(GError **error_r)\n{\n if (error_r == NULL)\n return;\n\n unsigned long error = ERR_get_error();\n char buffer[120];\n g_set_error(error_r, ssl_quark(), 0, \"%s\",\n ERR_error_string(error, buffer));\n}\n\n\/**\n * Move data from #src to #dest.\n *\/\nstatic void\nMove(ForeignFifoBuffer<uint8_t> &dest, ForeignFifoBuffer<uint8_t> &src)\n{\n auto r = src.Read();\n if (r.IsEmpty())\n return;\n\n auto w = dest.Write();\n if (w.IsEmpty())\n return;\n\n size_t nbytes = std::min(r.size, w.size);\n\n memcpy(w.data, r.data, nbytes);\n dest.Append(nbytes);\n src.Consume(nbytes);\n}\n\n\/**\n * Move data from #src to #dest.\n *\/\nstatic void\nMove(BIO *dest, ForeignFifoBuffer<uint8_t> &src)\n{\n auto r = src.Read();\n if (r.IsEmpty())\n return;\n\n int nbytes = BIO_write(dest, r.data, r.size);\n if (nbytes > 0)\n src.Consume(nbytes);\n}\n\nstatic void\nMove(ForeignFifoBuffer<uint8_t> &dest, BIO *src)\n{\n while (true) {\n auto w = dest.Write();\n if (w.IsEmpty())\n return;\n\n int nbytes = BIO_read(src, w.data, w.size);\n if (nbytes <= 0)\n return;\n\n dest.Append(nbytes);\n }\n}\n\nstatic char *\nformat_name(X509_NAME *name)\n{\n if (name == NULL)\n return NULL;\n\n BIO *bio = BIO_new(BIO_s_mem());\n if (bio == NULL)\n return NULL;\n\n X509_NAME_print_ex(bio, name, 0,\n ASN1_STRFLGS_UTF8_CONVERT | XN_FLAG_SEP_COMMA_PLUS);\n char buffer[1024];\n int length = BIO_read(bio, buffer, sizeof(buffer) - 1);\n BIO_free(bio);\n\n return strndup(buffer, length);\n}\n\nstatic char *\nformat_subject_name(X509 *cert)\n{\n return format_name(X509_get_subject_name(cert));\n}\n\nstatic char *\nformat_issuer_subject_name(X509 *cert)\n{\n return format_name(X509_get_issuer_name(cert));\n}\n\ngcc_const\nstatic bool\nis_ssl_error(SSL *ssl, int ret)\n{\n switch (SSL_get_error(ssl, ret)) {\n case SSL_ERROR_NONE:\n case SSL_ERROR_WANT_READ:\n case SSL_ERROR_WANT_WRITE:\n case SSL_ERROR_WANT_CONNECT:\n case SSL_ERROR_WANT_ACCEPT:\n return false;\n\n default:\n return true;\n }\n}\n\nstatic bool\ncheck_ssl_error(SSL *ssl, int result, GError **error_r)\n{\n if (is_ssl_error(ssl, result)) {\n ssl_set_error(error_r);\n return false;\n } else\n return true;\n}\n\n\/**\n * @return false on error\n *\/\nstatic bool\nssl_decrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer, GError **error_r)\n{\n \/* SSL_read() must be called repeatedly until there is no more\n data (or until the buffer is full) *\/\n\n while (true) {\n auto w = buffer.Write();\n if (w.IsEmpty())\n return 0;\n\n int result = SSL_read(ssl, w.data, w.size);\n if (result <= 0)\n return result == 0 || check_ssl_error(ssl, result, error_r);\n\n buffer.Append(result);\n }\n}\n\n\/**\n * @return false on error\n *\/\nstatic bool\nssl_encrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer, GError **error_r)\n{\n auto r = buffer.Read();\n if (r.IsEmpty())\n return true;\n\n int result = SSL_write(ssl, r.data, r.size);\n if (result < 0 && !check_ssl_error(ssl, result, error_r))\n return false;\n\n if (result > 0)\n buffer.Consume(result);\n\n return true;\n}\n\n\/*\n * thread_socket_filter_handler\n *\n *\/\n\nstatic bool\nssl_thread_socket_filter_run(ThreadSocketFilter &f, GError **error_r,\n void *ctx)\n{\n struct ssl_filter *ssl = (struct ssl_filter *)ctx;\n\n \/* copy input (and output to make room for more output) *\/\n\n pthread_mutex_lock(&f.mutex);\n Move(f.decrypted_input, ssl->decrypted_input);\n Move(ssl->plain_output, f.plain_output);\n Move(ssl->encrypted_input, f.encrypted_input);\n Move(f.encrypted_output, ssl->encrypted_output);\n pthread_mutex_unlock(&f.mutex);\n\n \/* let OpenSSL work *\/\n\n ERR_clear_error();\n\n if (gcc_unlikely(ssl->handshaking)) {\n int result = SSL_do_handshake(ssl->ssl);\n if (result == 1) {\n ssl->handshaking = false;\n\n X509 *cert = SSL_get_peer_certificate(ssl->ssl);\n if (cert != nullptr) {\n ssl->peer_subject = format_subject_name(cert);\n ssl->peer_issuer_subject = format_issuer_subject_name(cert);\n X509_free(cert);\n }\n } else if (result == 0) {\n ssl_set_error(error_r);\n return false;\n } else if (!check_ssl_error(ssl->ssl, result, error_r))\n return false;\n }\n\n if (gcc_likely(!ssl->handshaking) &&\n (!ssl_encrypt(ssl->ssl, ssl->plain_output, error_r) ||\n !ssl_decrypt(ssl->ssl, ssl->decrypted_input, error_r)))\n return false;\n\n \/* copy output *\/\n\n pthread_mutex_lock(&f.mutex);\n Move(f.decrypted_input, ssl->decrypted_input);\n Move(f.encrypted_output, ssl->encrypted_output);\n f.drained = ssl->plain_output.IsEmpty() &&\n BIO_eof(ssl->encrypted_output);\n pthread_mutex_unlock(&f.mutex);\n\n return true;\n}\n\nstatic void\nssl_thread_socket_filter_destroy(gcc_unused ThreadSocketFilter &f, void *ctx)\n{\n struct ssl_filter *ssl = (struct ssl_filter *)ctx;\n\n if (ssl->ssl != NULL)\n SSL_free(ssl->ssl);\n\n ssl->decrypted_input.Free(fb_pool_get());\n ssl->plain_output.Free(fb_pool_get());\n\n free(ssl->peer_subject);\n free(ssl->peer_issuer_subject);\n}\n\nconst struct ThreadSocketFilterHandler ssl_thread_socket_filter = {\n ssl_thread_socket_filter_run,\n ssl_thread_socket_filter_destroy,\n};\n\n\/*\n * constructor\n *\n *\/\n\nstruct ssl_filter *\nssl_filter_new(struct pool *pool, ssl_factory &factory,\n GError **error_r)\n{\n assert(pool != NULL);\n\n ssl_filter *ssl = NewFromPool<ssl_filter>(*pool);\n\n ssl->ssl = ssl_factory_make(factory);\n if (ssl->ssl == NULL) {\n g_set_error(error_r, ssl_quark(), 0, \"SSL_new() failed\");\n return NULL;\n }\n\n ssl->decrypted_input.Allocate(fb_pool_get());\n ssl->plain_output.Allocate(fb_pool_get());\n ssl->encrypted_input = BIO_new(BIO_s_mem());\n ssl->encrypted_output = BIO_new(BIO_s_mem());\n\n SSL_set_bio(ssl->ssl, ssl->encrypted_input, ssl->encrypted_output);\n\n ssl->peer_subject = NULL;\n ssl->peer_issuer_subject = NULL;\n ssl->handshaking = true;\n\n return ssl;\n}\n\nconst char *\nssl_filter_get_peer_subject(struct ssl_filter *ssl)\n{\n assert(ssl != NULL);\n\n return ssl->peer_subject;\n}\n\nconst char *\nssl_filter_get_peer_issuer_subject(struct ssl_filter *ssl)\n{\n assert(ssl != NULL);\n\n return ssl->peer_issuer_subject;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkImageToImageAffineMeanSquaresGradientDescentRegistrationTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include \"itkPhysicalImage.h\"\n#include \"itkSimpleImageRegionIterator.h\"\n#include \"itkImageToImageAffineMeanSquaresGradientDescentRegistration.h\"\n\n\/** \n * This test uses two 2D-Gaussians (standard deviation RegionSize\/2)\n * One is shifted by 7,3 pixels from the other.\n * therefore the solution of the registration is |-7 -3|\n * This test uses LevenbergMarquart Optimizer but\n * conjugate gradient optimizer tolerances are also defined\n * in the itkImageToImageAffineMeanSquaresGradientDescentRegistration.txx file\n * (you need to change the type of the optimizer in the header file\n * ie itkImageToImageAffineMeanSquaresGradientDescentRegistration.h)\n *\/ \n\nint main()\n{\n\n\n \/*Allocate Images*\/\n typedef itk::PhysicalImage<unsigned char,2> ReferenceType;\n typedef itk::PhysicalImage<unsigned char,2> TargetType;\n\n typedef itk::ImageToImageAffineMeanSquaresGradientDescentRegistration<ReferenceType,TargetType> RegistrationType;\n\n ReferenceType::SizeType size = {{100,100}};\n ReferenceType::IndexType index = {{0,0}};\n ReferenceType::RegionType region;\n region.SetSize( size );\n region.SetIndex( index );\n\n ReferenceType::Pointer imgReference = ReferenceType::New();\n imgReference->SetLargestPossibleRegion( region );\n imgReference->SetBufferedRegion( region );\n imgReference->SetRequestedRegion( region );\n imgReference->Allocate();\n\n TargetType::Pointer imgTarget = TargetType::New();\n imgTarget->SetLargestPossibleRegion( region );\n imgTarget->SetBufferedRegion( region );\n imgTarget->SetRequestedRegion( region );\n imgTarget->Allocate();\n\n \/* Fill images with a 2D gaussian*\/\n typedef itk::SimpleImageRegionIterator<ReferenceType> ReferenceIteratorType;\n\n typedef itk::SimpleImageRegionIterator<TargetType> TargetIteratorType;\n\n\n itk::Point<double,2> center;\n center[0] = (double)region.GetSize()[0]\/2.0;\n center[1] = (double)region.GetSize()[1]\/2.0;\n\n const double s = (double)region.GetSize()[0]\/2.0;\n\n itk::Point<double,2> p;\n itk::Vector<double,2> d;\n\n \/* Set the displacement *\/\n itk::Vector<double,2> displacement;\n displacement[0] = 7;\n displacement[1] = 3;\n\n ReferenceIteratorType ri(imgReference,region);\n TargetIteratorType ti(imgTarget,region);\n ri.Begin();\n while(!ri.IsAtEnd())\n {\n p[0] = ri.GetIndex()[0];\n p[1] = ri.GetIndex()[1];\n d = p-center;\n d += displacement;\n const double x = d[0];\n const double y = d[1];\n ri.Set( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) );\n ++ri;\n }\n\n\n ti.Begin();\n while(!ti.IsAtEnd())\n {\n p[0] = ti.GetIndex()[0];\n p[1] = ti.GetIndex()[1];\n d = p-center;\n const double x = d[0];\n const double y = d[1];\n ti.Set( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) );\n ++ti;\n }\n\n \n\n RegistrationType::Pointer registrationMethod = RegistrationType::New();\n\n registrationMethod->SetReference(imgReference);\n registrationMethod->SetTarget(imgTarget);\n registrationMethod->SetTranslationScale( 1e4 );\n\n registrationMethod->GetOptimizer()->SetLearningRate(0.01);\n registrationMethod->GetOptimizer()->SetNumberOfIterations(20);\n\n registrationMethod->StartRegistration();\n\n \/\/ get the results\n RegistrationType::ParametersType solution = \n registrationMethod->GetOptimizer()->GetCurrentPosition();\n\n std::cout << \"Solution is: \" << solution << std::endl;\n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n bool pass = true;\n double trueParameters[6] = { 1, 0, 0, 1, -7, -3 };\n for( unsigned int j = 0; j < 4; j++ )\n {\n if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 )\n pass = false;\n }\n for( unsigned int j = 4; j < 6; j++ )\n {\n if( vnl_math_abs( solution[j] - trueParameters[j] ) > 1.0 )\n pass = false;\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n\n\n\n}\n<commit_msg>ERR: More iterations added. Test corrected for translation scale<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkImageToImageAffineMeanSquaresGradientDescentRegistrationTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include \"itkPhysicalImage.h\"\n#include \"itkSimpleImageRegionIterator.h\"\n#include \"itkImageToImageAffineMeanSquaresGradientDescentRegistration.h\"\n\n\/** \n * This test uses two 2D-Gaussians (standard deviation RegionSize\/2)\n * One is shifted by 7,3 pixels from the other.\n * therefore the solution of the registration is |-7 -3|\n * This test uses LevenbergMarquart Optimizer but\n * conjugate gradient optimizer tolerances are also defined\n * in the itkImageToImageAffineMeanSquaresGradientDescentRegistration.txx file\n * (you need to change the type of the optimizer in the header file\n * ie itkImageToImageAffineMeanSquaresGradientDescentRegistration.h)\n *\/ \n\nint main()\n{\n\n\n \/*Allocate Images*\/\n typedef itk::PhysicalImage<unsigned char,2> ReferenceType;\n typedef itk::PhysicalImage<unsigned char,2> TargetType;\n\n typedef itk::ImageToImageAffineMeanSquaresGradientDescentRegistration<ReferenceType,TargetType> RegistrationType;\n\n ReferenceType::SizeType size = {{100,100}};\n ReferenceType::IndexType index = {{0,0}};\n ReferenceType::RegionType region;\n region.SetSize( size );\n region.SetIndex( index );\n\n ReferenceType::Pointer imgReference = ReferenceType::New();\n imgReference->SetLargestPossibleRegion( region );\n imgReference->SetBufferedRegion( region );\n imgReference->SetRequestedRegion( region );\n imgReference->Allocate();\n\n TargetType::Pointer imgTarget = TargetType::New();\n imgTarget->SetLargestPossibleRegion( region );\n imgTarget->SetBufferedRegion( region );\n imgTarget->SetRequestedRegion( region );\n imgTarget->Allocate();\n\n \/* Fill images with a 2D gaussian*\/\n typedef itk::SimpleImageRegionIterator<ReferenceType> ReferenceIteratorType;\n\n typedef itk::SimpleImageRegionIterator<TargetType> TargetIteratorType;\n\n\n itk::Point<double,2> center;\n center[0] = (double)region.GetSize()[0]\/2.0;\n center[1] = (double)region.GetSize()[1]\/2.0;\n\n const double s = (double)region.GetSize()[0]\/2.0;\n\n itk::Point<double,2> p;\n itk::Vector<double,2> d;\n\n \/* Set the displacement *\/\n itk::Vector<double,2> displacement;\n displacement[0] = 7;\n displacement[1] = 3;\n\n ReferenceIteratorType ri(imgReference,region);\n TargetIteratorType ti(imgTarget,region);\n ri.Begin();\n while(!ri.IsAtEnd())\n {\n p[0] = ri.GetIndex()[0];\n p[1] = ri.GetIndex()[1];\n d = p-center;\n d += displacement;\n const double x = d[0];\n const double y = d[1];\n ri.Set( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) );\n ++ri;\n }\n\n\n ti.Begin();\n while(!ti.IsAtEnd())\n {\n p[0] = ti.GetIndex()[0];\n p[1] = ti.GetIndex()[1];\n d = p-center;\n const double x = d[0];\n const double y = d[1];\n ti.Set( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) );\n ++ti;\n }\n\n \n\n RegistrationType::Pointer registrationMethod = RegistrationType::New();\n\n const double translationScale = 1e4;\n\n registrationMethod->SetReference(imgReference);\n registrationMethod->SetTarget(imgTarget);\n registrationMethod->SetTranslationScale( translationScale );\n\n registrationMethod->GetOptimizer()->SetLearningRate(0.01);\n registrationMethod->GetOptimizer()->SetNumberOfIterations(50);\n\n registrationMethod->StartRegistration();\n\n \/\/ get the results\n RegistrationType::ParametersType solution = \n registrationMethod->GetOptimizer()->GetCurrentPosition();\n\n std::cout << \"Solution is: \" << solution << std::endl;\n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n bool pass = true;\n double trueParameters[6] = { 1, 0, 0, 1, -7, -3 };\n for( unsigned int j = 0; j < 4; j++ )\n {\n if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 )\n pass = false;\n }\n for( unsigned int j = 4; j < 6; j++ )\n {\n if( vnl_math_abs( solution[j] * translationScale - trueParameters[j] ) > 1.0 )\n pass = false;\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n\n\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix refracted objects drawing order (#2577)<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"Synchronizer.h\"\n\n#include \"Connector.h\"\n\nusing namespace ru::org::codingteam::styx;\n\nSynchronizer::Synchronizer()\n\t: _state(SynchronizerState::NotConnected)\n{\n}\n\nvoid Synchronizer::dispatchConnected(Connector &connector, WsaSocket &socket)\n{\n\t_state = SynchronizerState::Handshake;\n\tconnector.sendLogin(socket);\n}\n\nvoid Synchronizer::dispatchMessage(Connector &connector, WsaSocket &socket, const Message &message)\n{\n\tswitch (_state)\n\t{\n\tcase SynchronizerState::Hashing:\n\t\t\/\/ TODO: Check current contact and message contact, invalidate some chunks if needed.\n\t\tbreak;\n\tcase SynchronizerState::Messaging:\n\t\tconnector.sendMessage(socket, message);\n\t\tbreak;\n\t}\n}\n\nvoid Synchronizer::dispatchMessage(Connector &connector, WsaSocket &socket, const LoginResult &message)\n{\n\tif (!message.logged())\n\t{\n\t\tthrow std::exception(\"Cannot log in\");\n\t}\n\n\tswitch (_state)\n\t{\n\tcase SynchronizerState::Handshake:\n\t\t_state = SynchronizerState::Hashing;\n\t\thashingStep(connector, socket);\n\t\tbreak;\n\tdefault:\n\t\tthrow std::exception(\"Invalid synchronizer state\");\n\t}\n}\n\nvoid Synchronizer::hashingStep(Connector &connector, WsaSocket &socket)\n{\n\t\/\/ TODO: do single hashing step.\n}<commit_msg>Add logging.<commit_after>#include \"Synchronizer.h\"\n\n#include <boost\/log\/trivial.hpp>\n\n#include \"Connector.h\"\n\nusing namespace ru::org::codingteam::styx;\n\nSynchronizer::Synchronizer()\n\t: _state(SynchronizerState::NotConnected)\n{\n}\n\nvoid Synchronizer::dispatchConnected(Connector &connector, WsaSocket &socket)\n{\n\t_state = SynchronizerState::Handshake;\n\tconnector.sendLogin(socket);\n}\n\nvoid Synchronizer::dispatchMessage(Connector &connector, WsaSocket &socket, const Message &message)\n{\n\tswitch (_state)\n\t{\n\tcase SynchronizerState::Hashing:\n\t\t\/\/ TODO: Check current contact and message contact, invalidate some chunks if needed.\n\t\tbreak;\n\tcase SynchronizerState::Messaging:\n\t\tconnector.sendMessage(socket, message);\n\t\tbreak;\n\t}\n}\n\nvoid Synchronizer::dispatchMessage(Connector &connector, WsaSocket &socket, const LoginResult &message)\n{\n\tif (!message.logged())\n\t{\n\t\tthrow std::exception(\"Cannot log in\");\n\t}\n\n\tswitch (_state)\n\t{\n\tcase SynchronizerState::Handshake:\n\t\t_state = SynchronizerState::Hashing;\n\t\tBOOST_LOG_TRIVIAL(info) << \"Successfully logged in\";\n\t\thashingStep(connector, socket);\n\t\tbreak;\n\tdefault:\n\t\tthrow std::exception(\"Invalid synchronizer state\");\n\t}\n}\n\nvoid Synchronizer::hashingStep(Connector &connector, WsaSocket &socket)\n{\n\t\/\/ TODO: do single hashing step.\n}<|endoftext|>"} {"text":"<commit_before>#include <ncurses.h>\n\n#include \"..\/..\/..\/src\/configuration.hh\"\n#include \"..\/..\/..\/src\/concat_c.hh\"\n#include \"..\/..\/..\/src\/contents.hh\"\n#include \"..\/..\/..\/src\/key_aliases.hh\"\n#include \"..\/..\/..\/src\/show_message.hh\"\n#include \"..\/..\/vick-move\/src\/move.hh\"\n\nnamespace vick {\nnamespace insert_mode {\n\nstruct insert_c : public change {\n const std::string track;\n const move_t y, x;\n insert_c(const std::string& track, move_t y, move_t x)\n : track(track)\n , y(y)\n , x(x)\n {\n }\n virtual bool is_overriding() override { return true; }\n virtual void undo(contents& contents) override\n {\n contents.cont[y] = contents.cont[y].substr(0, x) +\n contents.cont[y].substr(x + track.size());\n contents.y = y;\n contents.x = x;\n if (contents.x && contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual void redo(contents& contents) override\n {\n contents.cont[y] =\n contents.cont[y].substr(0, x) + track + contents.cont[y].substr(x);\n contents.y = y;\n contents.x = x + track.size();\n if (contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override\n {\n return std::make_shared<insert_c>(track, contents.y, contents.x);\n }\n};\n\nstruct newline_c : public change {\n const std::string first, second;\n const int y;\n newline_c(const contents& contents)\n : first(contents.cont[contents.y].substr(0, contents.x))\n , second(contents.cont[contents.y].substr(contents.x))\n , y(contents.y)\n {\n }\n virtual bool is_overriding() { return true; }\n virtual void undo(contents& contents)\n {\n contents.cont[y] = first + second;\n contents.cont.erase(contents.cont.begin() + y + 1);\n contents.y = y;\n contents.x = first.size();\n }\n virtual void redo(contents& contents)\n {\n contents.cont[y] = first;\n contents.cont.insert(contents.cont.begin() + y + 1, second);\n contents.y = y + 1;\n contents.x = 0;\n }\n virtual std::shared_ptr<change> regenerate(const contents& contents) const\n {\n return std::make_shared<newline_c>(contents);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_insert_mode(contents& contents, boost::optional<int> pref)\n{\n std::string track;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT--\");\n contents.is_inserting = true;\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (track.size())\n changes.push_back(\n std::make_shared<insert_c>(track, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_insert_mode(contents, pref);\n if (recursed) changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n track += ch;\n }\n else {\n contents.cont[contents.y].insert(contents.x, 1, ch);\n contents.x++;\n track += ch;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n }\n contents.is_inserting = false;\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<insert_c>(track, contents.y, x));\n}\n\nstruct replace_c : public change {\n const std::string o, n;\n const move_t y, x;\n replace_c(const std::string& o, const std::string& n, move_t y, move_t x)\n : o(o)\n , n(n)\n , y(y)\n , x(x)\n {\n }\n virtual bool is_overriding() override { return true; }\n virtual void undo(contents& contents) override\n {\n contents.cont[y] = contents.cont[y].substr(0, x) + o +\n contents.cont[y].substr(x + o.size());\n }\n virtual void redo(contents& contents) override\n {\n contents.cont[y] = contents.cont[y].substr(0, x) + n +\n contents.cont[y].substr(x + n.size());\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override\n {\n return std::make_shared<replace_c>(\n contents.cont[contents.y].substr(contents.x, n.size()), n,\n contents.y, contents.x);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_replace_mode(contents& contents, boost::optional<int> pref)\n{\n std::string o, n;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT (REPLACE)--\");\n contents.is_inserting = true;\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT (REPLACE)--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n o = contents.cont[contents.y][contents.x];\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (o.size())\n changes.push_back(\n std::make_shared<replace_c>(o, n, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_replace_mode(contents, pref);\n if (recursed) changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n n += ch;\n }\n else {\n o += contents.cont[contents.y][contents.x];\n n += ch;\n contents.cont[contents.y][contents.x] = ch;\n contents.x++;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT (REPLACE)--\");\n }\n }\n contents.is_inserting = false;\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<replace_c>(o, n, contents.y, x));\n}\n\nstruct append_c : public change {\n const std::string track; \n const move_t y, x;\n append_c(const std::string& track, move_t y, move_t x)\n : track(track)\n , y(y)\n , x(x)\n {\n }\n virtual bool is_overriding() override { return true; }\n virtual void undo(contents& contents) override\n {\n contents.cont[y] = contents.cont[y].substr(0, x) +\n contents.cont[y].substr(x + track.size());\n contents.y = y;\n contents.x = x;\n if (contents.x && contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual void redo(contents& contents) override\n {\n contents.cont[y] =\n contents.cont[y].substr(0, x) + track + contents.cont[y].substr(x);\n contents.y = y;\n contents.x = x + track.size();\n if (contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override\n {\n return std::make_shared<append_c>(track, contents.y, contents.x + 1);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_append_mode(contents& contents, boost::optional<int> pref)\n{\n if (contents.cont[contents.y].size() == 0)\n return enter_insert_mode(contents, pref);\n contents.x++;\n std::string track;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT--\");\n contents.is_inserting = true;\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (track.size())\n changes.push_back(\n std::make_shared<insert_c>(track, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_insert_mode(contents, pref);\n if (recursed) changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n track += ch;\n }\n else {\n contents.cont[contents.y].insert(contents.x, 1, ch);\n contents.x++;\n track += ch;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n }\n contents.is_inserting = false;\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<append_c>(track, contents.y, x));\n}\n\n}\n}\n<commit_msg>Remove miscellanious space at end of line<commit_after>#include <ncurses.h>\n\n#include \"..\/..\/..\/src\/configuration.hh\"\n#include \"..\/..\/..\/src\/concat_c.hh\"\n#include \"..\/..\/..\/src\/contents.hh\"\n#include \"..\/..\/..\/src\/key_aliases.hh\"\n#include \"..\/..\/..\/src\/show_message.hh\"\n#include \"..\/..\/vick-move\/src\/move.hh\"\n\nnamespace vick {\nnamespace insert_mode {\n\nstruct insert_c : public change {\n const std::string track;\n const move_t y, x;\n insert_c(const std::string& track, move_t y, move_t x)\n : track(track)\n , y(y)\n , x(x)\n {\n }\n virtual bool is_overriding() override { return true; }\n virtual void undo(contents& contents) override\n {\n contents.cont[y] = contents.cont[y].substr(0, x) +\n contents.cont[y].substr(x + track.size());\n contents.y = y;\n contents.x = x;\n if (contents.x && contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual void redo(contents& contents) override\n {\n contents.cont[y] =\n contents.cont[y].substr(0, x) + track + contents.cont[y].substr(x);\n contents.y = y;\n contents.x = x + track.size();\n if (contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override\n {\n return std::make_shared<insert_c>(track, contents.y, contents.x);\n }\n};\n\nstruct newline_c : public change {\n const std::string first, second;\n const int y;\n newline_c(const contents& contents)\n : first(contents.cont[contents.y].substr(0, contents.x))\n , second(contents.cont[contents.y].substr(contents.x))\n , y(contents.y)\n {\n }\n virtual bool is_overriding() { return true; }\n virtual void undo(contents& contents)\n {\n contents.cont[y] = first + second;\n contents.cont.erase(contents.cont.begin() + y + 1);\n contents.y = y;\n contents.x = first.size();\n }\n virtual void redo(contents& contents)\n {\n contents.cont[y] = first;\n contents.cont.insert(contents.cont.begin() + y + 1, second);\n contents.y = y + 1;\n contents.x = 0;\n }\n virtual std::shared_ptr<change> regenerate(const contents& contents) const\n {\n return std::make_shared<newline_c>(contents);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_insert_mode(contents& contents, boost::optional<int> pref)\n{\n std::string track;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT--\");\n contents.is_inserting = true;\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (track.size())\n changes.push_back(\n std::make_shared<insert_c>(track, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_insert_mode(contents, pref);\n if (recursed) changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n track += ch;\n }\n else {\n contents.cont[contents.y].insert(contents.x, 1, ch);\n contents.x++;\n track += ch;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n }\n contents.is_inserting = false;\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<insert_c>(track, contents.y, x));\n}\n\nstruct replace_c : public change {\n const std::string o, n;\n const move_t y, x;\n replace_c(const std::string& o, const std::string& n, move_t y, move_t x)\n : o(o)\n , n(n)\n , y(y)\n , x(x)\n {\n }\n virtual bool is_overriding() override { return true; }\n virtual void undo(contents& contents) override\n {\n contents.cont[y] = contents.cont[y].substr(0, x) + o +\n contents.cont[y].substr(x + o.size());\n }\n virtual void redo(contents& contents) override\n {\n contents.cont[y] = contents.cont[y].substr(0, x) + n +\n contents.cont[y].substr(x + n.size());\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override\n {\n return std::make_shared<replace_c>(\n contents.cont[contents.y].substr(contents.x, n.size()), n,\n contents.y, contents.x);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_replace_mode(contents& contents, boost::optional<int> pref)\n{\n std::string o, n;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT (REPLACE)--\");\n contents.is_inserting = true;\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT (REPLACE)--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n o = contents.cont[contents.y][contents.x];\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (o.size())\n changes.push_back(\n std::make_shared<replace_c>(o, n, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_replace_mode(contents, pref);\n if (recursed) changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n n += ch;\n }\n else {\n o += contents.cont[contents.y][contents.x];\n n += ch;\n contents.cont[contents.y][contents.x] = ch;\n contents.x++;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT (REPLACE)--\");\n }\n }\n contents.is_inserting = false;\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<replace_c>(o, n, contents.y, x));\n}\n\nstruct append_c : public change {\n const std::string track;\n const move_t y, x;\n append_c(const std::string& track, move_t y, move_t x)\n : track(track)\n , y(y)\n , x(x)\n {\n }\n virtual bool is_overriding() override { return true; }\n virtual void undo(contents& contents) override\n {\n contents.cont[y] = contents.cont[y].substr(0, x) +\n contents.cont[y].substr(x + track.size());\n contents.y = y;\n contents.x = x;\n if (contents.x && contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual void redo(contents& contents) override\n {\n contents.cont[y] =\n contents.cont[y].substr(0, x) + track + contents.cont[y].substr(x);\n contents.y = y;\n contents.x = x + track.size();\n if (contents.x >= contents.cont[y].size())\n contents.x = contents.cont[y].size() - 1;\n }\n virtual std::shared_ptr<change>\n regenerate(const contents& contents) const override\n {\n return std::make_shared<append_c>(track, contents.y, contents.x + 1);\n }\n};\n\nboost::optional<std::shared_ptr<change> >\nenter_append_mode(contents& contents, boost::optional<int> pref)\n{\n if (contents.cont[contents.y].size() == 0)\n return enter_insert_mode(contents, pref);\n contents.x++;\n std::string track;\n auto x = contents.x;\n char ch;\n show_message(\"--INSERT--\");\n contents.is_inserting = true;\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != QUIT_KEY) {\n if (ch == '\\n') {\n std::vector<std::shared_ptr<change> > changes;\n changes.reserve(3);\n if (track.size())\n changes.push_back(\n std::make_shared<insert_c>(track, contents.y, x));\n changes.push_back(std::make_shared<newline_c>(contents));\n changes.back()->redo(contents);\n auto recursed = enter_insert_mode(contents, pref);\n if (recursed) changes.push_back(recursed.get());\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<concat_c>(changes));\n }\n if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n track += ch;\n }\n else {\n contents.cont[contents.y].insert(contents.x, 1, ch);\n contents.x++;\n track += ch;\n }\n if (get_contents().refresh) {\n print_contents(get_contents());\n show_message(\"--INSERT--\");\n }\n }\n contents.is_inserting = false;\n showing_message = false;\n return boost::optional<std::shared_ptr<change> >(\n std::make_shared<append_c>(track, contents.y, x));\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\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#include \"global_notifier.hpp\"\n\n#include \"admin_realm.hpp\"\n\n#include \"impl\/realm_coordinator.hpp\"\n#include \"impl\/transact_log_handler.hpp\"\n#include \"object_schema.hpp\"\n#include \"object_store.hpp\"\n#include \"results.hpp\"\n#include \"util\/event_loop_dispatcher.hpp\"\n#include \"util\/event_loop_signal.hpp\"\n\n#include \"sync\/sync_manager.hpp\"\n#include \"sync\/sync_user.hpp\"\n#include \"sync\/sync_session.hpp\"\n\n#include <realm\/lang_bind_helper.hpp>\n#include <realm\/util\/file.hpp>\n#include <realm\/util\/scope_exit.hpp>\n\n#include <json.hpp>\n\n#include <condition_variable>\n#include <mutex>\n#include <queue>\n#include <stdexcept>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing namespace realm;\nusing namespace realm::_impl;\n\nnamespace realm {\nstatic void to_json(nlohmann::json& j, VersionID v)\n{\n j = {{\"version\", v.version}, {\"index\", v.index}};\n}\nstatic void from_json(nlohmann::json const& j, VersionID& v)\n{\n v.version = j[\"version\"];\n v.index = j[\"index\"];\n}\n\nnamespace sync {\nstatic void to_json(nlohmann::json& j, ObjectID id)\n{\n j = id.to_string();\n}\nstatic void from_json(nlohmann::json const& j, ObjectID& v)\n{\n std::string str = j;\n v = ObjectID::from_string(str);\n}\n}\n}\n\nclass GlobalNotifier::Impl final : public AdminRealmListener {\npublic:\n Impl(std::unique_ptr<Callback>,\n std::string local_root_dir, SyncConfig sync_config_template);\n\n util::Optional<ChangeNotification> next_changed_realm();\n void release_version(sync::ObjectID id, VersionID old_version, VersionID new_version);\n\npublic:\n void register_realm(sync::ObjectID, StringData virtual_path) override;\n void unregister_realm(sync::ObjectID, StringData) override;\n void error(std::exception_ptr err) override { m_target->error(err); }\n void download_complete() override { m_target->download_complete(); }\n\n const std::unique_ptr<util::Logger> m_logger;\n const std::unique_ptr<Callback> m_target;\n\n std::mutex m_work_queue_mutex;\n struct RealmToCalculate {\n sync::ObjectID realm_id;\n std::string virtual_path;\n std::shared_ptr<_impl::RealmCoordinator> coordinator;\n std::unique_ptr<Replication> history;\n std::unique_ptr<SharedGroup> shared_group;\n std::queue<VersionID> versions;\n bool pending_deletion = false;\n\n \/\/ constructor to make GCC 4.9 happy\n RealmToCalculate(sync::ObjectID realm_id, std::string virtual_path)\n : realm_id(realm_id)\n , virtual_path(std::move(virtual_path))\n {\n }\n };\n std::queue<RealmToCalculate*> m_work_queue;\n std::unordered_map<sync::ObjectID, RealmToCalculate> m_realms;\n\n struct SignalCallback {\n std::weak_ptr<Impl> notifier;\n void operator()()\n {\n if (auto alive = notifier.lock()) {\n GlobalNotifier notifier(alive);\n alive->m_target->realm_changed(¬ifier);\n }\n }\n };\n\n std::shared_ptr<util::EventLoopSignal<SignalCallback>> m_signal;\n};\n\nGlobalNotifier::Impl::Impl(std::unique_ptr<Callback> async_target,\n std::string local_root_dir, SyncConfig sync_config_template)\n: AdminRealmListener(local_root_dir, std::move(sync_config_template))\n, m_logger(SyncManager::shared().make_logger())\n, m_target(std::move(async_target))\n{\n}\n\nvoid GlobalNotifier::Impl::register_realm(sync::ObjectID id, StringData path) {\n auto info = &m_realms.emplace(id, RealmToCalculate{id, path}).first->second;\n m_realms.emplace(id, RealmToCalculate{id, path});\n\n auto strid = id.to_string();\n if (!m_target->realm_available(strid, path)) {\n m_logger->trace(\"Global notifier: not watching %1\", path);\n return;\n }\n if (info->coordinator) {\n m_logger->trace(\"Global notifier: already watching %1\", path);\n return;\n }\n\n m_logger->trace(\"Global notifier: watching %1\", path);\n auto config = get_config(path, strid);\n info->coordinator = _impl::RealmCoordinator::get_coordinator(config);\n\n std::weak_ptr<Impl> weak_self = std::static_pointer_cast<Impl>(shared_from_this());\n info->coordinator->set_transaction_callback([=, weak_self = std::move(weak_self)](VersionID old_version, VersionID new_version) {\n auto self = weak_self.lock();\n if (!self)\n return;\n\n std::lock_guard<std::mutex> l(m_work_queue_mutex);\n if (info->shared_group) {\n m_logger->trace(\"Global notifier: sync transaction on (%1): Realm already open\", info->virtual_path);\n }\n else {\n m_logger->trace(\"Global notifier: sync transaction on (%1): opening Realm\", info->virtual_path);\n std::unique_ptr<Group> read_only_group;\n auto config = info->coordinator->get_config();\n config.force_sync_history = true; \/\/ FIXME: needed?\n config.schema = util::none;\n Realm::open_with_config(config, info->history, info->shared_group, read_only_group, nullptr);\n info->shared_group->begin_read(old_version);\n }\n info->versions.push(new_version);\n if (info->versions.size() == 1) {\n m_logger->trace(\"Global notifier: Signaling main thread\");\n m_work_queue.push(info);\n m_signal->notify();\n }\n });\n}\n\nvoid GlobalNotifier::Impl::unregister_realm(sync::ObjectID id, StringData path) {\n auto realm = m_realms.find(id);\n if (realm == m_realms.end()) {\n m_logger->trace(\"Global notifier: unwatched Realm at (%1) was deleted\", path);\n return;\n }\n\n std::lock_guard<std::mutex> l(m_work_queue_mutex);\n \/\/ Otherwise we need to defer closing the Realm until we're done with our current work.\n m_logger->trace(\"Global notifier: enqueuing deletion of Realm at (%1)\", path);\n if (realm->second.coordinator)\n realm->second.coordinator->set_transaction_callback(nullptr);\n realm->second.pending_deletion = true;\n\n if (realm->second.versions.empty()) {\n m_work_queue.push(&realm->second);\n m_signal->notify();\n }\n}\n\nvoid GlobalNotifier::Impl::release_version(sync::ObjectID id, VersionID old_version, VersionID new_version)\n{\n std::lock_guard<std::mutex> l(m_work_queue_mutex);\n\n auto it = m_realms.find(id);\n REALM_ASSERT(it != m_realms.end());\n auto& info = it->second;\n\n if (info.pending_deletion && old_version == VersionID()) {\n m_logger->trace(\"Global notifier: completing pending deletion of (%1)\", info.virtual_path);\n if (info.coordinator) {\n std::string path = info.coordinator->get_config().path;\n m_realms.erase(it);\n if (File::exists(path)) {\n File::remove(path);\n }\n }\n else {\n m_realms.erase(it);\n }\n }\n else {\n auto& sg = info.shared_group;\n REALM_ASSERT(sg->get_version_of_current_transaction() == old_version);\n\n REALM_ASSERT(!info.versions.empty() && info.versions.front() == new_version);\n info.versions.pop();\n\n if (info.versions.empty()) {\n info.shared_group = nullptr;\n info.history = nullptr;\n m_logger->trace(\"Global notifier: release version on (%1): no pending versions\", info.virtual_path);\n\n if (info.pending_deletion) {\n m_logger->trace(\"Global notifier: enqueuing deletion notification for (%1)\", info.virtual_path);\n m_work_queue.push(&info);\n }\n }\n else {\n LangBindHelper::advance_read(*sg, new_version);\n m_work_queue.push(&info);\n m_logger->trace(\"Global notifier: release version on (%1): enqueuing next version\", info.virtual_path);\n }\n }\n\n if (!m_work_queue.empty()) {\n m_logger->trace(\"Global notifier: Signaling main thread\");\n m_signal->notify();\n }\n}\n\nGlobalNotifier::GlobalNotifier(std::unique_ptr<Callback> async_target,\n std::string local_root_dir, SyncConfig sync_config_template)\n: m_impl(std::make_shared<GlobalNotifier::Impl>(std::move(async_target),\n std::move(local_root_dir),\n std::move(sync_config_template)))\n{\n std::weak_ptr<GlobalNotifier::Impl> weak_impl = m_impl;\n m_impl->m_signal = std::make_shared<util::EventLoopSignal<Impl::SignalCallback>>(Impl::SignalCallback{weak_impl});\n}\n\nvoid GlobalNotifier::start()\n{\n m_impl->m_logger->trace(\"Global notifier: start()\");\n m_impl->start();\n}\n\nGlobalNotifier::~GlobalNotifier() = default;\n\nutil::Optional<GlobalNotifier::ChangeNotification> GlobalNotifier::next_changed_realm()\n{\n std::lock_guard<std::mutex> l(m_impl->m_work_queue_mutex);\n if (m_impl->m_work_queue.empty()) {\n m_impl->m_logger->trace(\"Global notifier: next_changed_realm(): no realms pending\");\n return util::none;\n }\n\n auto next = m_impl->m_work_queue.front();\n m_impl->m_work_queue.pop();\n m_impl->m_logger->trace(\"Global notifier: notifying for realm at %1\", next->virtual_path);\n\n if (next->versions.empty() && next->pending_deletion) {\n return ChangeNotification(m_impl, next->virtual_path, next->realm_id);\n }\n\n auto old_version = next->shared_group->get_version_of_current_transaction();\n return ChangeNotification(m_impl, next->virtual_path, next->realm_id,\n next->coordinator->get_config(),\n old_version, next->versions.front());\n}\n\nGlobalNotifier::Callback& GlobalNotifier::target()\n{\n return *m_impl->m_target;\n}\n\nGlobalNotifier::ChangeNotification::ChangeNotification(std::shared_ptr<GlobalNotifier::Impl> notifier,\n std::string virtual_path,\n sync::ObjectID realm_id,\n Realm::Config config,\n VersionID old_version,\n VersionID new_version)\n: realm_path(std::move(virtual_path))\n, type(Type::Change)\n, m_realm_id(realm_id)\n, m_config(std::move(config))\n, m_old_version(old_version)\n, m_new_version(new_version)\n, m_notifier(std::move(notifier))\n{\n}\n\nGlobalNotifier::ChangeNotification::ChangeNotification(std::shared_ptr<GlobalNotifier::Impl> notifier,\n std::string virtual_path,\n sync::ObjectID realm_id)\n: realm_path(std::move(virtual_path))\n, type(Type::Delete)\n, m_realm_id(realm_id)\n, m_notifier(std::move(notifier))\n{\n}\n\nGlobalNotifier::ChangeNotification::~ChangeNotification()\n{\n if (m_notifier)\n m_notifier->release_version(m_realm_id, m_old_version, m_new_version);\n if (m_old_realm)\n m_old_realm->close();\n if (m_new_realm)\n m_new_realm->close();\n}\n\nstd::string GlobalNotifier::ChangeNotification::serialize() const\n{\n nlohmann::json ret;\n ret[\"virtual_path\"] = realm_path;\n ret[\"realm_id\"] = m_realm_id;\n if (type == Type::Change) {\n ret[\"path\"] = m_config.path;\n ret[\"old_version\"] = m_old_version;\n ret[\"new_version\"] = m_new_version;\n ret[\"is_change\"] = true;\n }\n return ret.dump();\n}\n\nGlobalNotifier::ChangeNotification::ChangeNotification(std::string const& serialized)\n{\n auto parsed = nlohmann::json::parse(serialized);\n realm_path = parsed[\"virtual_path\"];\n m_realm_id = parsed[\"realm_id\"];\n\n if (!parsed[\"is_change\"].is_null()) {\n type = Type::Change;\n m_old_version = parsed[\"old_version\"];\n m_new_version = parsed[\"new_version\"];\n\n m_config.path = parsed[\"path\"];\n m_config.force_sync_history = true;\n m_config.schema_mode = SchemaMode::Additive;\n m_config.cache = false;\n m_config.automatic_change_notifications = false;\n }\n else {\n type = Type::Delete;\n }\n}\n\nSharedRealm GlobalNotifier::ChangeNotification::get_old_realm() const\n{\n if (const_cast<VersionID&>(m_old_version) == VersionID{})\n return nullptr;\n if (m_old_realm)\n return m_old_realm;\n\n m_old_realm = Realm::get_shared_realm(m_config);\n Realm::Internal::begin_read(*m_old_realm, m_old_version);\n return m_old_realm;\n}\n\nSharedRealm GlobalNotifier::ChangeNotification::get_new_realm() const\n{\n if (m_new_realm)\n return m_new_realm;\n m_new_realm = Realm::get_shared_realm(m_config);\n Realm::Internal::begin_read(*m_new_realm, m_new_version);\n return m_new_realm;\n}\n\nstd::unordered_map<std::string, CollectionChangeSet> const& GlobalNotifier::ChangeNotification::get_changes() const\n{\n if (m_have_calculated_changes)\n return m_changes;\n\n Realm::Config config;\n config.path = m_config.path;\n config.cache = false;\n config.force_sync_history = true;\n config.automatic_change_notifications = false;\n\n auto realm = Realm::get_shared_realm(config);\n\n auto& sg = Realm::Internal::get_shared_group(*realm);\n Realm::Internal::begin_read(*realm, m_old_version);\n Group const& g = realm->read_group();\n\n _impl::TransactionChangeInfo info;\n info.track_all = true;\n _impl::transaction::advance(*sg, info, m_new_version);\n\n m_changes.reserve(info.tables.size());\n for (size_t i = 0; i < info.tables.size(); ++i) {\n auto& change = info.tables[i];\n if (!change.empty()) {\n auto name = ObjectStore::object_type_for_table_name(g.get_table_name(i));\n if (name) {\n m_changes[name] = std::move(change).finalize();\n }\n }\n }\n\n m_have_calculated_changes = true;\n return m_changes;\n}\n\nGlobalNotifier::Callback::~Callback() = default;\n<commit_msg>fix removing of file<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\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#include \"global_notifier.hpp\"\n\n#include \"admin_realm.hpp\"\n\n#include \"impl\/realm_coordinator.hpp\"\n#include \"impl\/transact_log_handler.hpp\"\n#include \"object_schema.hpp\"\n#include \"object_store.hpp\"\n#include \"results.hpp\"\n#include \"util\/event_loop_dispatcher.hpp\"\n#include \"util\/event_loop_signal.hpp\"\n\n#include \"sync\/sync_manager.hpp\"\n#include \"sync\/sync_user.hpp\"\n#include \"sync\/sync_session.hpp\"\n\n#include <realm\/lang_bind_helper.hpp>\n#include <realm\/util\/file.hpp>\n#include <realm\/util\/scope_exit.hpp>\n\n#include <json.hpp>\n\n#include <condition_variable>\n#include <mutex>\n#include <queue>\n#include <stdexcept>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing namespace realm;\nusing namespace realm::_impl;\n\nnamespace realm {\nstatic void to_json(nlohmann::json& j, VersionID v)\n{\n j = {{\"version\", v.version}, {\"index\", v.index}};\n}\nstatic void from_json(nlohmann::json const& j, VersionID& v)\n{\n v.version = j[\"version\"];\n v.index = j[\"index\"];\n}\n\nnamespace sync {\nstatic void to_json(nlohmann::json& j, ObjectID id)\n{\n j = id.to_string();\n}\nstatic void from_json(nlohmann::json const& j, ObjectID& v)\n{\n std::string str = j;\n v = ObjectID::from_string(str);\n}\n}\n}\n\nclass GlobalNotifier::Impl final : public AdminRealmListener {\npublic:\n Impl(std::unique_ptr<Callback>,\n std::string local_root_dir, SyncConfig sync_config_template);\n\n util::Optional<ChangeNotification> next_changed_realm();\n void release_version(sync::ObjectID id, VersionID old_version, VersionID new_version);\n\npublic:\n void register_realm(sync::ObjectID, StringData virtual_path) override;\n void unregister_realm(sync::ObjectID, StringData) override;\n void error(std::exception_ptr err) override { m_target->error(err); }\n void download_complete() override { m_target->download_complete(); }\n\n const std::unique_ptr<util::Logger> m_logger;\n const std::unique_ptr<Callback> m_target;\n\n std::mutex m_work_queue_mutex;\n struct RealmToCalculate {\n sync::ObjectID realm_id;\n std::string virtual_path;\n std::shared_ptr<_impl::RealmCoordinator> coordinator;\n std::unique_ptr<Replication> history;\n std::unique_ptr<SharedGroup> shared_group;\n std::queue<VersionID> versions;\n bool pending_deletion = false;\n\n \/\/ constructor to make GCC 4.9 happy\n RealmToCalculate(sync::ObjectID realm_id, std::string virtual_path)\n : realm_id(realm_id)\n , virtual_path(std::move(virtual_path))\n {\n }\n };\n std::queue<RealmToCalculate*> m_work_queue;\n std::unordered_map<sync::ObjectID, RealmToCalculate> m_realms;\n\n struct SignalCallback {\n std::weak_ptr<Impl> notifier;\n void operator()()\n {\n if (auto alive = notifier.lock()) {\n GlobalNotifier notifier(alive);\n alive->m_target->realm_changed(¬ifier);\n }\n }\n };\n\n std::shared_ptr<util::EventLoopSignal<SignalCallback>> m_signal;\n};\n\nGlobalNotifier::Impl::Impl(std::unique_ptr<Callback> async_target,\n std::string local_root_dir, SyncConfig sync_config_template)\n: AdminRealmListener(local_root_dir, std::move(sync_config_template))\n, m_logger(SyncManager::shared().make_logger())\n, m_target(std::move(async_target))\n{\n}\n\nvoid GlobalNotifier::Impl::register_realm(sync::ObjectID id, StringData path) {\n auto info = &m_realms.emplace(id, RealmToCalculate{id, path}).first->second;\n m_realms.emplace(id, RealmToCalculate{id, path});\n\n auto strid = id.to_string();\n if (!m_target->realm_available(strid, path)) {\n m_logger->trace(\"Global notifier: not watching %1\", path);\n return;\n }\n if (info->coordinator) {\n m_logger->trace(\"Global notifier: already watching %1\", path);\n return;\n }\n\n m_logger->trace(\"Global notifier: watching %1\", path);\n auto config = get_config(path, strid);\n info->coordinator = _impl::RealmCoordinator::get_coordinator(config);\n\n std::weak_ptr<Impl> weak_self = std::static_pointer_cast<Impl>(shared_from_this());\n info->coordinator->set_transaction_callback([=, weak_self = std::move(weak_self)](VersionID old_version, VersionID new_version) {\n auto self = weak_self.lock();\n if (!self)\n return;\n\n std::lock_guard<std::mutex> l(m_work_queue_mutex);\n if (info->shared_group) {\n m_logger->trace(\"Global notifier: sync transaction on (%1): Realm already open\", info->virtual_path);\n }\n else {\n m_logger->trace(\"Global notifier: sync transaction on (%1): opening Realm\", info->virtual_path);\n std::unique_ptr<Group> read_only_group;\n auto config = info->coordinator->get_config();\n config.force_sync_history = true; \/\/ FIXME: needed?\n config.schema = util::none;\n Realm::open_with_config(config, info->history, info->shared_group, read_only_group, nullptr);\n info->shared_group->begin_read(old_version);\n }\n info->versions.push(new_version);\n if (info->versions.size() == 1) {\n m_logger->trace(\"Global notifier: Signaling main thread\");\n m_work_queue.push(info);\n m_signal->notify();\n }\n });\n}\n\nvoid GlobalNotifier::Impl::unregister_realm(sync::ObjectID id, StringData path) {\n auto realm = m_realms.find(id);\n if (realm == m_realms.end()) {\n m_logger->trace(\"Global notifier: unwatched Realm at (%1) was deleted\", path);\n return;\n }\n\n std::lock_guard<std::mutex> l(m_work_queue_mutex);\n \/\/ Otherwise we need to defer closing the Realm until we're done with our current work.\n m_logger->trace(\"Global notifier: enqueuing deletion of Realm at (%1)\", path);\n if (realm->second.coordinator)\n realm->second.coordinator->set_transaction_callback(nullptr);\n realm->second.pending_deletion = true;\n\n if (realm->second.versions.empty()) {\n m_work_queue.push(&realm->second);\n m_signal->notify();\n }\n}\n\nvoid GlobalNotifier::Impl::release_version(sync::ObjectID id, VersionID old_version, VersionID new_version)\n{\n std::lock_guard<std::mutex> l(m_work_queue_mutex);\n\n auto it = m_realms.find(id);\n REALM_ASSERT(it != m_realms.end());\n auto& info = it->second;\n\n if (info.pending_deletion && old_version == VersionID()) {\n m_logger->trace(\"Global notifier: completing pending deletion of (%1)\", info.virtual_path);\n if (info.coordinator) {\n std::string path = info.coordinator->get_config().path;\n m_realms.erase(it);\n File::try_remove(path);\n }\n else {\n m_realms.erase(it);\n }\n }\n else {\n auto& sg = info.shared_group;\n REALM_ASSERT(sg->get_version_of_current_transaction() == old_version);\n\n REALM_ASSERT(!info.versions.empty() && info.versions.front() == new_version);\n info.versions.pop();\n\n if (info.versions.empty()) {\n info.shared_group = nullptr;\n info.history = nullptr;\n m_logger->trace(\"Global notifier: release version on (%1): no pending versions\", info.virtual_path);\n\n if (info.pending_deletion) {\n m_logger->trace(\"Global notifier: enqueuing deletion notification for (%1)\", info.virtual_path);\n m_work_queue.push(&info);\n }\n }\n else {\n LangBindHelper::advance_read(*sg, new_version);\n m_work_queue.push(&info);\n m_logger->trace(\"Global notifier: release version on (%1): enqueuing next version\", info.virtual_path);\n }\n }\n\n if (!m_work_queue.empty()) {\n m_logger->trace(\"Global notifier: Signaling main thread\");\n m_signal->notify();\n }\n}\n\nGlobalNotifier::GlobalNotifier(std::unique_ptr<Callback> async_target,\n std::string local_root_dir, SyncConfig sync_config_template)\n: m_impl(std::make_shared<GlobalNotifier::Impl>(std::move(async_target),\n std::move(local_root_dir),\n std::move(sync_config_template)))\n{\n std::weak_ptr<GlobalNotifier::Impl> weak_impl = m_impl;\n m_impl->m_signal = std::make_shared<util::EventLoopSignal<Impl::SignalCallback>>(Impl::SignalCallback{weak_impl});\n}\n\nvoid GlobalNotifier::start()\n{\n m_impl->m_logger->trace(\"Global notifier: start()\");\n m_impl->start();\n}\n\nGlobalNotifier::~GlobalNotifier() = default;\n\nutil::Optional<GlobalNotifier::ChangeNotification> GlobalNotifier::next_changed_realm()\n{\n std::lock_guard<std::mutex> l(m_impl->m_work_queue_mutex);\n if (m_impl->m_work_queue.empty()) {\n m_impl->m_logger->trace(\"Global notifier: next_changed_realm(): no realms pending\");\n return util::none;\n }\n\n auto next = m_impl->m_work_queue.front();\n m_impl->m_work_queue.pop();\n m_impl->m_logger->trace(\"Global notifier: notifying for realm at %1\", next->virtual_path);\n\n if (next->versions.empty() && next->pending_deletion) {\n return ChangeNotification(m_impl, next->virtual_path, next->realm_id);\n }\n\n auto old_version = next->shared_group->get_version_of_current_transaction();\n return ChangeNotification(m_impl, next->virtual_path, next->realm_id,\n next->coordinator->get_config(),\n old_version, next->versions.front());\n}\n\nGlobalNotifier::Callback& GlobalNotifier::target()\n{\n return *m_impl->m_target;\n}\n\nGlobalNotifier::ChangeNotification::ChangeNotification(std::shared_ptr<GlobalNotifier::Impl> notifier,\n std::string virtual_path,\n sync::ObjectID realm_id,\n Realm::Config config,\n VersionID old_version,\n VersionID new_version)\n: realm_path(std::move(virtual_path))\n, type(Type::Change)\n, m_realm_id(realm_id)\n, m_config(std::move(config))\n, m_old_version(old_version)\n, m_new_version(new_version)\n, m_notifier(std::move(notifier))\n{\n}\n\nGlobalNotifier::ChangeNotification::ChangeNotification(std::shared_ptr<GlobalNotifier::Impl> notifier,\n std::string virtual_path,\n sync::ObjectID realm_id)\n: realm_path(std::move(virtual_path))\n, type(Type::Delete)\n, m_realm_id(realm_id)\n, m_notifier(std::move(notifier))\n{\n}\n\nGlobalNotifier::ChangeNotification::~ChangeNotification()\n{\n if (m_notifier)\n m_notifier->release_version(m_realm_id, m_old_version, m_new_version);\n if (m_old_realm)\n m_old_realm->close();\n if (m_new_realm)\n m_new_realm->close();\n}\n\nstd::string GlobalNotifier::ChangeNotification::serialize() const\n{\n nlohmann::json ret;\n ret[\"virtual_path\"] = realm_path;\n ret[\"realm_id\"] = m_realm_id;\n if (type == Type::Change) {\n ret[\"path\"] = m_config.path;\n ret[\"old_version\"] = m_old_version;\n ret[\"new_version\"] = m_new_version;\n ret[\"is_change\"] = true;\n }\n return ret.dump();\n}\n\nGlobalNotifier::ChangeNotification::ChangeNotification(std::string const& serialized)\n{\n auto parsed = nlohmann::json::parse(serialized);\n realm_path = parsed[\"virtual_path\"];\n m_realm_id = parsed[\"realm_id\"];\n\n if (!parsed[\"is_change\"].is_null()) {\n type = Type::Change;\n m_old_version = parsed[\"old_version\"];\n m_new_version = parsed[\"new_version\"];\n\n m_config.path = parsed[\"path\"];\n m_config.force_sync_history = true;\n m_config.schema_mode = SchemaMode::Additive;\n m_config.cache = false;\n m_config.automatic_change_notifications = false;\n }\n else {\n type = Type::Delete;\n }\n}\n\nSharedRealm GlobalNotifier::ChangeNotification::get_old_realm() const\n{\n if (const_cast<VersionID&>(m_old_version) == VersionID{})\n return nullptr;\n if (m_old_realm)\n return m_old_realm;\n\n m_old_realm = Realm::get_shared_realm(m_config);\n Realm::Internal::begin_read(*m_old_realm, m_old_version);\n return m_old_realm;\n}\n\nSharedRealm GlobalNotifier::ChangeNotification::get_new_realm() const\n{\n if (m_new_realm)\n return m_new_realm;\n m_new_realm = Realm::get_shared_realm(m_config);\n Realm::Internal::begin_read(*m_new_realm, m_new_version);\n return m_new_realm;\n}\n\nstd::unordered_map<std::string, CollectionChangeSet> const& GlobalNotifier::ChangeNotification::get_changes() const\n{\n if (m_have_calculated_changes)\n return m_changes;\n\n Realm::Config config;\n config.path = m_config.path;\n config.cache = false;\n config.force_sync_history = true;\n config.automatic_change_notifications = false;\n\n auto realm = Realm::get_shared_realm(config);\n\n auto& sg = Realm::Internal::get_shared_group(*realm);\n Realm::Internal::begin_read(*realm, m_old_version);\n Group const& g = realm->read_group();\n\n _impl::TransactionChangeInfo info;\n info.track_all = true;\n _impl::transaction::advance(*sg, info, m_new_version);\n\n m_changes.reserve(info.tables.size());\n for (size_t i = 0; i < info.tables.size(); ++i) {\n auto& change = info.tables[i];\n if (!change.empty()) {\n auto name = ObjectStore::object_type_for_table_name(g.get_table_name(i));\n if (name) {\n m_changes[name] = std::move(change).finalize();\n }\n }\n }\n\n m_have_calculated_changes = true;\n return m_changes;\n}\n\nGlobalNotifier::Callback::~Callback() = default;\n<|endoftext|>"} {"text":"<commit_before>\/***\nCopyright 2017 Yaohai XU\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n***\/\n\n\/**\n FastLSH\n StdThreadComputer.cpp\n Purpose: This is the source file for StdThread computing functions\n\n @author Peter Yaohai XU\n @version 1.0 4\/07\/17\n*\/\n\n\n#include <cmath>\n#include <thread>\n#include <algorithm>\n#include <iostream>\n#include \"..\/..\/include\/otherClasses\/Computer.h\"\n\nvector2D ComputerStdThread::computeHash(vector2D dataset, size_t pointNum){\n vector2D hashMatrix;\n \/\/pre-allocate memory space\n for (int i = 0; i < pointNum; ++i) {\n vector1D vL(ph.L,0);\n hashMatrix.push_back(vL);\n }\n\n \/\/ a implementation of nested loop to stdthread\n const size_t nthreads = std::thread::hardware_concurrency();\n const size_t outloop = pointNum;\n const size_t inloop = ph.L;\n const size_t nloop = outloop*inloop;\n\n \/\/ vector of threads\n std::vector<std::thread> threads(nthreads);\n for(int t = 0;t<nthreads;t++)\n {\n threads[t] = std::thread(std::bind(\n [&](const int bi, const int ei, const int t)\n {\n \/\/ loop over all items\n for(int i = bi;i<ei;i++)\n {\n \/\/ inner loop\n {\n int n = i\/inloop; \/\/retrive outer loop index\n int l = i%inloop; \/\/retrive inner loop index\n \/\/ (optional) make output critical\n double hashFinalValue = 0;\n \/\/loop through the inner of a hash function group\n for (int k = 0; k < ph.K; ++k) {\n double dTemp = 0;\n \/\/loop through all the dimensions\n for (int d = 0; d < ph.D; ++d) {\n \/\/vector(math) multiply to make projection\n dTemp += dataset[n][d]*ph.randomLine[l][k][d];\n }\n \/\/assign hashvalue into bucket\n double hashvalue = floor(dTemp\/ph.W);\n \/\/merge hash group results **see documentation\n hashFinalValue = hashvalue*ph.randomVector[k] + hashFinalValue;\n }\n hashMatrix[n][l] = hashFinalValue;\n\n }\n }\n \/\/allocate different index to threads\n },t*nloop\/nthreads,(t+1)==nthreads?nloop:(t+1)*nloop\/nthreads,t));\n }\n\n \/\/lambda to start threads\n std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\n\n return hashMatrix;\n}\n\n\n\nvector2D ComputerStdThreadNormal::computeCollision(vector2D hMatrixN, vector2D hMatrixQ){\n \/\/pre-allocate memory space\n vector2D collisionMatrix;\n for (int i = 0; i < ph.Q ; ++i) {\n vector1D singleLine(ph.N, 0);\n collisionMatrix.push_back(singleLine);\n }\n\n \/\/ a implementation of nested loop to stdthread\n const size_t nthreads = std::thread::hardware_concurrency();\n const size_t outloop = ph.Q;\n const size_t inloop = ph.N;\n const size_t nloop = outloop*inloop;\n std::vector<std::thread> threads(nthreads);\n for(int t = 0;t<nthreads;t++)\n {\n threads[t] = std::thread(std::bind(\n [&](const int bi, const int ei, const int t)\n {\n \/\/ loop over all items\n for(int i = bi;i<ei;i++)\n {\n \/\/ inner loop\n {\n int q = i\/inloop;\n int n = i%inloop;\n for (int hash_id = 0; hash_id < ph.L; ++hash_id) {\n \/\/cast to int for comparision, reduce double compare risk\n if (hMatrixN[n][hash_id] == hMatrixQ[q][hash_id])\n collisionMatrix[q][n]++;\n }\n\n\n }\n }\n \/\/allocate different index to threads\n },t*nloop\/nthreads,(t+1)==nthreads?nloop:(t+1)*nloop\/nthreads,t));\n }\n \/\/lambda to start threads\n std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\n return collisionMatrix;\n}\n\n\n\nvector2D ComputerStdThreadNormal::computeCandidate(vector2D collisionMatrix){\n \/\/pre-allocate memory space\n vector2D candidateSet;\n for (int i = 0; i < ph.Q; ++i) {\n vector1D temp(0,0);\n candidateSet.push_back(temp);\n }\n\n \/\/ a implementation of nested loop to stdthread\n const size_t nthreads = std::thread::hardware_concurrency();\n const size_t nloop = ph.Q;\n std::vector<std::thread> threads(nthreads);\n\n for(int t = 0;t<nthreads;t++)\n {\n threads[t] = std::thread(std::bind(\n [&](const int bi, const int ei, const int t)\n {\n \/\/ loop over all items\n for(int i = bi;i<ei;i++)\n {\n vector1D candidates;\n for (int j = 0; j < ph.N; ++j) {\n if(collisionMatrix[i][j]>=ph.T)\n candidates.push_back((double &&) j);\n }\n candidateSet[i] = candidates;\n }\n \/\/allocate different index to threads\n },t*nloop\/nthreads,(t+1)==nthreads?nloop:(t+1)*nloop\/nthreads,t));\n }\n \/\/lambda to start threads\n std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\n return candidateSet;\n}\n\n\n\n\n\/\/by quick mode, it means get candidateset directly, skip the collision table\nvector2D ComputerStdThreadQuick::computeCandidate(vector2D hMatrixN, vector2D hMatrixQ){\n vector2D candidateSet;\n \/\/Prepare set to store candidates\n for (int i = 0; i < ph.Q; ++i) {\n vector1D temp(0,0);\n candidateSet.push_back(temp);\n }\n\n \/\/ a implementation of nested loop to stdthread\n const size_t nthreads = std::thread::hardware_concurrency();\n const size_t nloop = ph.Q;\n std::vector<std::thread> threads(nthreads);\n\n for(int t = 0;t<nthreads;t++)\n {\n threads[t] = std::thread(std::bind(\n [&](const int bi, const int ei, const int t)\n {\n \/\/ loop over all items\n for(int i = bi;i<ei;i++)\n {\n vector1D singleRow(0, 0);\n for (int n = 0; n <ph.N ; ++n){\n int colliNum = 0;\n for (int hash_id = 0; hash_id < ph.L; ++hash_id) {\n if (hMatrixN[n][hash_id] == hMatrixQ[i][hash_id]) {\n colliNum++;\n if(colliNum>=ph.T){\n singleRow.push_back((double &&) n);\n break;\n }\n }\n }\n }\n candidateSet[i] = singleRow;\n }\n \/\/allocate different index to threads\n },t*nloop\/nthreads,(t+1)==nthreads?nloop:(t+1)*nloop\/nthreads,t));\n }\n \/\/lambda to start threads\n std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\n return candidateSet;\n}\n\n\nvoid ComputerStdThread::printThreadMode(){\n std::cout<< \"Pthread\";\n}\nvoid ComputerStdThreadNormal::printComputeMode(){\n std::cout<< \"Normal\";\n}\nvoid ComputerStdThreadQuick::printComputeMode(){\n std::cout<< \"Quick\";\n}\n\n\n<commit_msg>Fix: error: ‘bind’ is not a member of ‘std’<commit_after>\/***\nCopyright 2017 Yaohai XU\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n***\/\n\n\/**\n FastLSH\n StdThreadComputer.cpp\n Purpose: This is the source file for StdThread computing functions\n\n @author Peter Yaohai XU\n @version 1.0 4\/07\/17\n*\/\n\n\n#include <cmath>\n#include <thread>\n#include <algorithm>\n#include <iostream>\n#include <functional>\n#include \"..\/..\/include\/otherClasses\/Computer.h\"\n\nvector2D ComputerStdThread::computeHash(vector2D dataset, size_t pointNum){\n vector2D hashMatrix;\n \/\/pre-allocate memory space\n for (int i = 0; i < pointNum; ++i) {\n vector1D vL(ph.L,0);\n hashMatrix.push_back(vL);\n }\n\n \/\/ a implementation of nested loop to stdthread\n const size_t nthreads = std::thread::hardware_concurrency();\n const size_t outloop = pointNum;\n const size_t inloop = ph.L;\n const size_t nloop = outloop*inloop;\n\n \/\/ vector of threads\n std::vector<std::thread> threads(nthreads);\n for(int t = 0;t<nthreads;t++)\n {\n threads[t] = std::thread(std::bind(\n [&](const int bi, const int ei, const int t)\n {\n \/\/ loop over all items\n for(int i = bi;i<ei;i++)\n {\n \/\/ inner loop\n {\n int n = i\/inloop; \/\/retrive outer loop index\n int l = i%inloop; \/\/retrive inner loop index\n \/\/ (optional) make output critical\n double hashFinalValue = 0;\n \/\/loop through the inner of a hash function group\n for (int k = 0; k < ph.K; ++k) {\n double dTemp = 0;\n \/\/loop through all the dimensions\n for (int d = 0; d < ph.D; ++d) {\n \/\/vector(math) multiply to make projection\n dTemp += dataset[n][d]*ph.randomLine[l][k][d];\n }\n \/\/assign hashvalue into bucket\n double hashvalue = floor(dTemp\/ph.W);\n \/\/merge hash group results **see documentation\n hashFinalValue = hashvalue*ph.randomVector[k] + hashFinalValue;\n }\n hashMatrix[n][l] = hashFinalValue;\n\n }\n }\n \/\/allocate different index to threads\n },t*nloop\/nthreads,(t+1)==nthreads?nloop:(t+1)*nloop\/nthreads,t));\n }\n\n \/\/lambda to start threads\n std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\n\n return hashMatrix;\n}\n\n\n\nvector2D ComputerStdThreadNormal::computeCollision(vector2D hMatrixN, vector2D hMatrixQ){\n \/\/pre-allocate memory space\n vector2D collisionMatrix;\n for (int i = 0; i < ph.Q ; ++i) {\n vector1D singleLine(ph.N, 0);\n collisionMatrix.push_back(singleLine);\n }\n\n \/\/ a implementation of nested loop to stdthread\n const size_t nthreads = std::thread::hardware_concurrency();\n const size_t outloop = ph.Q;\n const size_t inloop = ph.N;\n const size_t nloop = outloop*inloop;\n std::vector<std::thread> threads(nthreads);\n for(int t = 0;t<nthreads;t++)\n {\n threads[t] = std::thread(std::bind(\n [&](const int bi, const int ei, const int t)\n {\n \/\/ loop over all items\n for(int i = bi;i<ei;i++)\n {\n \/\/ inner loop\n {\n int q = i\/inloop;\n int n = i%inloop;\n for (int hash_id = 0; hash_id < ph.L; ++hash_id) {\n \/\/cast to int for comparision, reduce double compare risk\n if (hMatrixN[n][hash_id] == hMatrixQ[q][hash_id])\n collisionMatrix[q][n]++;\n }\n\n\n }\n }\n \/\/allocate different index to threads\n },t*nloop\/nthreads,(t+1)==nthreads?nloop:(t+1)*nloop\/nthreads,t));\n }\n \/\/lambda to start threads\n std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\n return collisionMatrix;\n}\n\n\n\nvector2D ComputerStdThreadNormal::computeCandidate(vector2D collisionMatrix){\n \/\/pre-allocate memory space\n vector2D candidateSet;\n for (int i = 0; i < ph.Q; ++i) {\n vector1D temp(0,0);\n candidateSet.push_back(temp);\n }\n\n \/\/ a implementation of nested loop to stdthread\n const size_t nthreads = std::thread::hardware_concurrency();\n const size_t nloop = ph.Q;\n std::vector<std::thread> threads(nthreads);\n\n for(int t = 0;t<nthreads;t++)\n {\n threads[t] = std::thread(std::bind(\n [&](const int bi, const int ei, const int t)\n {\n \/\/ loop over all items\n for(int i = bi;i<ei;i++)\n {\n vector1D candidates;\n for (int j = 0; j < ph.N; ++j) {\n if(collisionMatrix[i][j]>=ph.T)\n candidates.push_back((double &&) j);\n }\n candidateSet[i] = candidates;\n }\n \/\/allocate different index to threads\n },t*nloop\/nthreads,(t+1)==nthreads?nloop:(t+1)*nloop\/nthreads,t));\n }\n \/\/lambda to start threads\n std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\n return candidateSet;\n}\n\n\n\n\n\/\/by quick mode, it means get candidateset directly, skip the collision table\nvector2D ComputerStdThreadQuick::computeCandidate(vector2D hMatrixN, vector2D hMatrixQ){\n vector2D candidateSet;\n \/\/Prepare set to store candidates\n for (int i = 0; i < ph.Q; ++i) {\n vector1D temp(0,0);\n candidateSet.push_back(temp);\n }\n\n \/\/ a implementation of nested loop to stdthread\n const size_t nthreads = std::thread::hardware_concurrency();\n const size_t nloop = ph.Q;\n std::vector<std::thread> threads(nthreads);\n\n for(int t = 0;t<nthreads;t++)\n {\n threads[t] = std::thread(std::bind(\n [&](const int bi, const int ei, const int t)\n {\n \/\/ loop over all items\n for(int i = bi;i<ei;i++)\n {\n vector1D singleRow(0, 0);\n for (int n = 0; n <ph.N ; ++n){\n int colliNum = 0;\n for (int hash_id = 0; hash_id < ph.L; ++hash_id) {\n if (hMatrixN[n][hash_id] == hMatrixQ[i][hash_id]) {\n colliNum++;\n if(colliNum>=ph.T){\n singleRow.push_back((double &&) n);\n break;\n }\n }\n }\n }\n candidateSet[i] = singleRow;\n }\n \/\/allocate different index to threads\n },t*nloop\/nthreads,(t+1)==nthreads?nloop:(t+1)*nloop\/nthreads,t));\n }\n \/\/lambda to start threads\n std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\n return candidateSet;\n}\n\n\nvoid ComputerStdThread::printThreadMode(){\n std::cout<< \"Pthread\";\n}\nvoid ComputerStdThreadNormal::printComputeMode(){\n std::cout<< \"Normal\";\n}\nvoid ComputerStdThreadQuick::printComputeMode(){\n std::cout<< \"Quick\";\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include \"riemann_solver.h\"\n\nusing namespace std;\n\nvoid Solve(Discrete_Records &result, Status &s1, Status &s2);\nvoid PrintResult(Discrete_Records &result);\n\nint main(int argc, int argv) {\n\n\tStatus s1, s2;\n\tDiscrete_Records result;\n\t\n\n\ts1.pressure = 1.0;\n\ts1.density = 1.0;\n\ts1.velocity = 0.0;\n\n\ts2.pressure = 0.1;\n\ts2.density = 0.125;\n\ts2.velocity = 0.0;\n\n\tresult.records = new Status[201];\n\tresult.time = 0.14;\n\tresult.size = 201;\n\tresult.dx = 2.0 \/ (201 - 1);\n\n\tSolve(result, s1, s2);\n\n\tPrintResult(result);\n\n\tdelete[] result.records;\n\n\treturn 0;\n}\n\nvoid Solve(Discrete_Records &result,Status &s1, Status &s2) {\n\tRiemann_Solver solver(s1,s2);\n\tsolver.Solver();\n\tsolver.Get_Result(result);\n}\n\nvoid PrintResult(Discrete_Records &result) {\n\n\tofstream file(\"output.dat\");\n\n\tfile << \"VARIABLES = \\\"X\\\", \\\"Pressure\\\", \\\"Density\\\", \\\"Velocity\\\"\" << '\\n';\n\tfile << \"ZONE I=201, DATAPACKING=BLOCK\" << '\\n';\n\n\tfile.precision(10);\n\tfile.setf(ios::fixed, ios::floatfield);\n\n\tfor (int i = 0; i < result.size; i++)\n\t{\n\t\tfile << i * result.dx - 1.0 << '\\t';\n\t}\n\tfile << '\\n';\n\tfor (int i = 0; i < result.size; i++)\n\t{\n\t\tfile << result.records[i].pressure << '\\t';\n\t}\n\tfile << '\\n';\n\tfor (int i = 0; i < result.size; i++)\n\t{\n\t\tfile << result.records[i].density << '\\t';\n\t}\n\tfile << '\\n';\n\tfor (int i = 0; i < result.size; i++)\n\t{\n\t\tfile << result.records[i].velocity << '\\t';\n\t}\n\tfile << endl;\n}<commit_msg>a few mistake corrected<commit_after>#include <fstream>\n#include \"riemann_solver.h\"\n\nusing namespace std;\n\nvoid Solve(Discrete_Records &result, Status &s1, Status &s2);\nvoid PrintResult(Discrete_Records &result);\n\nint main(int argc, char **argv) {\n\n\tStatus s1, s2;\n\tDiscrete_Records result;\n\t\n\n\ts1.pressure = 1.0;\n\ts1.density = 1.0;\n\ts1.velocity = 0.0;\n\n\ts2.pressure = 0.1;\n\ts2.density = 0.125;\n\ts2.velocity = 0.0;\n\n\tresult.records = new Status[201];\n\tresult.time = 0.14;\n\tresult.size = 201;\n\tresult.dx = 2.0 \/ (201 - 1);\n\n\tSolve(result, s1, s2);\n\n\tPrintResult(result);\n\n\tdelete[] result.records;\n\n\treturn 0;\n}\n\nvoid Solve(Discrete_Records &result,Status &s1, Status &s2) {\n\tRiemann_Solver solver(s1,s2);\n\tsolver.Solver();\n\tsolver.Get_Result(result);\n}\n\nvoid PrintResult(Discrete_Records &result) {\n\n\tofstream file(\"output.dat\");\n\n\tfile << \"VARIABLES = \\\"X\\\", \\\"Pressure\\\", \\\"Density\\\", \\\"Velocity\\\"\" << '\\n';\n\tfile << \"ZONE I=201, DATAPACKING=BLOCK\" << '\\n';\n\n\tfile.precision(10);\n\tfile.setf(ios::fixed, ios::floatfield);\n\n\tfor (int i = 0; i < result.size; i++)\n\t{\n\t\tfile << i * result.dx - 1.0 << '\\t';\n\t}\n\tfile << '\\n';\n\tfor (int i = 0; i < result.size; i++)\n\t{\n\t\tfile << result.records[i].pressure << '\\t';\n\t}\n\tfile << '\\n';\n\tfor (int i = 0; i < result.size; i++)\n\t{\n\t\tfile << result.records[i].density << '\\t';\n\t}\n\tfile << '\\n';\n\tfor (int i = 0; i < result.size; i++)\n\t{\n\t\tfile << result.records[i].velocity << '\\t';\n\t}\n\tfile << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n* Copyright 2016 ROBOTIS CO., LTD.\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\/* Authors: Hye-Jong KIM *\/\n\n#ifndef OMMATH_HPP_\n#define OMMATH_HPP_\n\n#include \"..\/..\/include\/open_manipulator\/OMDebug.hpp\"\n\n#include <Eigen.h> \/\/ Calls main Eigen matrix class library\n#include <Eigen\/LU> \/\/ Calls inverse, determinant, LU decomp., etc.\n\n#include <math.h>\n\n#define DEG2RAD (M_PI \/ 180.0)\n#define RAD2DEG (180.0 \/ M_PI)\n\n#define ZERO_VECTOR Eigen::Vector3f::Zero()\n#define IDENTITY_MATRIX Eigen::Matrix3f::Identity(3,3)\n\nclass OMMath\n{\n public:\n OMMath(){}\n ~OMMath(){}\n\n float sign(float number)\n {\n if (number >= 0.0)\n {\n return 1.0;\n }\n else\n {\n return -1.0;\n }\n }\n\n Eigen::Vector3f makeEigenVector3(float v1, float v2, float v3)\n {\n Eigen::Vector3f temp;\n temp << v1, v2, v3;\n return temp;\n }\n\n Eigen::Matrix3f makeEigenMatrix3(float m11, float m12, float m13, float m21, float m22, float m23, float m31, float m32, float m33)\n {\n Eigen::Matrix3f temp;\n temp << m11, m12, m13, m21, m22, m23, m31, m32, m33;\n return temp;\n }\n \n Eigen::Matrix3f makeRotationMatrix(float roll, float pitch, float yaw)\n {\n Eigen::Matrix3f rotation_matrix;\n Eigen::Matrix3f roll_matrix;\n Eigen::Matrix3f pitch_matrix;\n Eigen::Matrix3f yaw_matrix;\n\n roll_matrix << 1.000, 0.000, 0.000,\n 0.000, cos(roll), sin(roll),\n 0.000, -sin(roll), cos(roll);\n\n pitch_matrix << cos(pitch), 0.000, sin(pitch),\n 0.000, 1.000, 0.000,\n -sin(pitch), 0.000, cos(pitch);\n\n yaw_matrix << cos(yaw), -sin(yaw), 0.000,\n sin(yaw), cos(yaw), 0.000,\n 0.000, 0.000, 1.000;\n \n rotation_matrix = roll_matrix * pitch_matrix * yaw_matrix;\n\n return rotation_matrix;\n }\n\n Eigen::Matrix3f makeRotationMatrix(Eigen::Vector3f rotation_vector)\n {\n Eigen::Matrix3f rotation_matrix;\n rotation_matrix = makeRotationMatrix(rotation_vector(0), rotation_vector(1), rotation_vector(2));\n return rotation_matrix;\n }\n \n Eigen::Vector3f makeRotationVector(Eigen::Matrix3f rotation_matrix)\n {\n Eigen::Matrix3f R = rotation_matrix;\n Eigen::Vector3f l = Eigen::Vector3f::Zero();\n Eigen::Vector3f rotation_vector = Eigen::Vector3f::Zero();\n\n float theta = 0.0;\n float diag = 0.0;\n bool diagonal_matrix = true;\n\n l << R(2,1) - R(1,2),\n R(0,2) - R(2,0),\n R(1,0) - R(0,1);\n theta = atan2(l.norm(), R(0,0) + R(1,1) + R(2,2) - 1);\n diag = R(0,0) + R(1,1) + R(2,2);\n\n for (int8_t i = 0; i < 3; i++)\n {\n for (int8_t j = 0; j < 3; j++)\n {\n if (i != j)\n {\n if (R(i, j) != 0)\n {\n diagonal_matrix = false;\n }\n }\n }\n }\n if (R == Eigen::Matrix3f::Identity())\n {\n rotation_vector = Eigen::Vector3f::Zero();\n }\n else if (diagonal_matrix == true)\n {\n rotation_vector << R(0,0) + 1, R(1,1) + 1, R(2,2) + 1;\n rotation_vector = rotation_vector * M_PI_2;\n }\n else\n {\n rotation_vector = theta * (l \/ l.norm());\n }\n return rotation_vector;\n }\n\n Eigen::Matrix3f skewSymmetricMatrix(Eigen::Vector3f v)\n {\n Eigen::Matrix3f skew_symmetric_matrix = Eigen::Matrix3f::Zero();\n\n skew_symmetric_matrix << 0, -v(2), v(1),\n v(2), 0, -v(0),\n -v(1), v(0), 0;\n\n return skew_symmetric_matrix;\n }\n\n Eigen::Matrix3f rodriguesRotationMatrix(Eigen::Vector3f axis, float angle)\n {\n Eigen::Matrix3f skew_symmetric_matrix = Eigen::Matrix3f::Zero();\n Eigen::Matrix3f rotation_matrix = Eigen::Matrix3f::Zero();\n Eigen::Matrix3f Identity_matrix = Eigen::Matrix3f::Identity();\n\n skew_symmetric_matrix = skewSymmetricMatrix(axis);\n rotation_matrix = Identity_matrix +\n skew_symmetric_matrix * sin(angle) +\n skew_symmetric_matrix * skew_symmetric_matrix * (1 - cos(angle));\n\n return rotation_matrix;\n }\n \n Eigen::Vector3f differentialPosition(Eigen::Vector3f desired_position, Eigen::Vector3f present_position)\n {\n Eigen::Vector3f differential_position;\n differential_position = desired_position - present_position;\n\n return differential_position;\n }\n\n Eigen::Vector3f differentialOrientation(Eigen::Matrix3f desired_orientation, Eigen::Matrix3f present_orientation)\n {\n Eigen::Vector3f differential_orientation;\n differential_orientation = present_orientation * makeRotationVector(present_orientation.transpose() * desired_orientation);\n\n return differential_orientation;\n }\n\n\n Eigen::VectorXf differentialPose(Eigen::Vector3f desired_position, Eigen::Vector3f present_position, Eigen::Matrix3f desired_orientation, Eigen::Matrix3f present_orientation)\n {\n Eigen::Vector3f differential_position;\n Eigen::Vector3f differential_orientation;\n Eigen::VectorXf differential_pose(6);\n\n differential_position = differentialPosition(desired_position, present_position);\n differential_orientation = differentialOrientation(desired_orientation, present_orientation);\n differential_pose << differential_position(0), \n differential_position(1), \n differential_position(2), \n differential_orientation(0), \n differential_orientation(1), \n differential_orientation(2);\n return differential_pose;\n }\n};\n\n#endif \/\/ OMMATH_HPP_\n<commit_msg>fix makerotation vec,matrix function<commit_after>\/*******************************************************************************\n* Copyright 2016 ROBOTIS CO., LTD.\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\/* Authors: Hye-Jong KIM *\/\n\n#ifndef OMMATH_HPP_\n#define OMMATH_HPP_\n\n#include \"..\/..\/include\/open_manipulator\/OMDebug.hpp\"\n\n#include <Eigen.h> \/\/ Calls main Eigen matrix class library\n#include <Eigen\/LU> \/\/ Calls inverse, determinant, LU decomp., etc.\n\n#include <math.h>\n\n#define DEG2RAD (M_PI \/ 180.0)\n#define RAD2DEG (180.0 \/ M_PI)\n\n#define ZERO_VECTOR Eigen::Vector3f::Zero()\n#define IDENTITY_MATRIX Eigen::Matrix3f::Identity(3,3)\n\nclass OMMath\n{\n public:\n OMMath(){}\n ~OMMath(){}\n\n float sign(float number)\n {\n if (number >= 0.0)\n {\n return 1.0;\n }\n else\n {\n return -1.0;\n }\n }\n\n Eigen::Vector3f makeEigenVector3(float v1, float v2, float v3)\n {\n Eigen::Vector3f temp;\n temp << v1, v2, v3;\n return temp;\n }\n\n Eigen::Matrix3f makeEigenMatrix3(float m11, float m12, float m13, float m21, float m22, float m23, float m31, float m32, float m33)\n {\n Eigen::Matrix3f temp;\n temp << m11, m12, m13, m21, m22, m23, m31, m32, m33;\n return temp;\n }\n \n Eigen::Vector3f matrixLogarithm(Eigen::Matrix3f rotation_matrix)\n {\n Eigen::Matrix3f R = rotation_matrix;\n Eigen::Vector3f l = Eigen::Vector3f::Zero();\n Eigen::Vector3f rotation_vector = Eigen::Vector3f::Zero();\n\n float theta = 0.0;\n float diag = 0.0;\n bool diagonal_matrix = true;\n\n l << R(2,1) - R(1,2),\n R(0,2) - R(2,0),\n R(1,0) - R(0,1);\n theta = atan2(l.norm(), R(0,0) + R(1,1) + R(2,2) - 1);\n diag = R(0,0) + R(1,1) + R(2,2);\n\n for (int8_t i = 0; i < 3; i++)\n {\n for (int8_t j = 0; j < 3; j++)\n {\n if (i != j)\n {\n if (R(i, j) != 0)\n {\n diagonal_matrix = false;\n }\n }\n }\n }\n if (R == Eigen::Matrix3f::Identity())\n {\n rotation_vector = Eigen::Vector3f::Zero();\n }\n else if (diagonal_matrix == true)\n {\n rotation_vector << R(0,0) + 1, R(1,1) + 1, R(2,2) + 1;\n rotation_vector = rotation_vector * M_PI_2;\n }\n else\n {\n rotation_vector = theta * (l \/ l.norm());\n }\n return rotation_vector;\n }\n\n Eigen::Matrix3f skewSymmetricMatrix(Eigen::Vector3f v)\n {\n Eigen::Matrix3f skew_symmetric_matrix = Eigen::Matrix3f::Zero();\n\n skew_symmetric_matrix << 0, -v(2), v(1),\n v(2), 0, -v(0),\n -v(1), v(0), 0;\n\n return skew_symmetric_matrix;\n }\n\n Eigen::Matrix3f rodriguesRotationMatrix(Eigen::Vector3f axis, float angle)\n {\n Eigen::Matrix3f skew_symmetric_matrix = Eigen::Matrix3f::Zero();\n Eigen::Matrix3f rotation_matrix = Eigen::Matrix3f::Zero();\n Eigen::Matrix3f Identity_matrix = Eigen::Matrix3f::Identity();\n\n skew_symmetric_matrix = skewSymmetricMatrix(axis);\n rotation_matrix = Identity_matrix +\n skew_symmetric_matrix * sin(angle) +\n skew_symmetric_matrix * skew_symmetric_matrix * (1 - cos(angle));\n\n return rotation_matrix;\n }\n \n Eigen::Matrix3f makeRotationMatrix(Eigen::Vector3f rotation_vector)\n {\n Eigen::Matrix3f rotation_matrix;\n Eigen::Vector3f axis;\n float angle;\n\n angle = rotation_vector.norm();\n axis(0) = rotation_vector(0) \/ angle;\n axis(1) = rotation_vector(1) \/ angle;\n axis(2) = rotation_vector(2) \/ angle;\n\n rotation_matrix = rodriguesRotationMatrix(axis, angle);\n return rotation_matrix;\n }\n\n Eigen::Vector3f makeRotationVector(Eigen::Matrix3f rotation_matrix)\n {\n return matrixLogarithm(rotation_matrix);\n }\n\n Eigen::Vector3f differentialPosition(Eigen::Vector3f desired_position, Eigen::Vector3f present_position)\n {\n Eigen::Vector3f differential_position;\n differential_position = desired_position - present_position;\n\n return differential_position;\n }\n\n Eigen::Vector3f differentialOrientation(Eigen::Matrix3f desired_orientation, Eigen::Matrix3f present_orientation)\n {\n Eigen::Vector3f differential_orientation;\n differential_orientation = present_orientation * makeRotationVector(present_orientation.transpose() * desired_orientation);\n\n return differential_orientation;\n }\n\n\n Eigen::VectorXf differentialPose(Eigen::Vector3f desired_position, Eigen::Vector3f present_position, Eigen::Matrix3f desired_orientation, Eigen::Matrix3f present_orientation)\n {\n Eigen::Vector3f differential_position;\n Eigen::Vector3f differential_orientation;\n Eigen::VectorXf differential_pose(6);\n\n differential_position = differentialPosition(desired_position, present_position);\n differential_orientation = differentialOrientation(desired_orientation, present_orientation);\n differential_pose << differential_position(0), \n differential_position(1), \n differential_position(2), \n differential_orientation(0), \n differential_orientation(1), \n differential_orientation(2);\n return differential_pose;\n }\n};\n\n#endif \/\/ OMMATH_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <osre\/App\/AppBase.h>\n#include <osre\/Properties\/Settings.h>\n#include <osre\/Common\/Logger.h>\n#include <osre\/Scene\/GeometryBuilder.h>\n#include <osre\/Scene\/Stage.h>\n#include <osre\/Scene\/Node.h>\n#include <osre\/RenderBackend\/RenderCommon.h>\n\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\nusing namespace OSRE;\nusing namespace OSRE::RenderBackend;\n\n\/\/ to identify local log entries \nstatic const String Tag = \"HelloWorld\"; \n\nglm::mat4 P = glm::mat4( 1 );\nglm::mat4 M = glm::mat4( 1 );\nglm::mat4 V = glm::mat4( 1 );\n\nclass HelloWorldApp : public App::AppBase {\n Scene::Stage *m_stage;\n TransformMatrixBlock m_transformMatrix;\n\npublic:\n HelloWorldApp( int argc, char *argv[] )\n : AppBase( argc, argv )\n , m_stage( nullptr ) {\n\n }\n\n virtual ~HelloWorldApp() {\n\n }\n\nprotected:\n virtual bool onCreate( Properties::Settings *config = nullptr ) {\n AppBase::getConfig()->setString( Properties::Settings::WindowsTitle, \"HelloWorld!\" );\n\n if( !AppBase::onCreate( config ) ) {\n return false;\n }\n\n m_stage = AppBase::createStage( \"HelloWorld\" );\n Scene::Node *geoNode = m_stage->addNode( \"geo\", nullptr );\n Scene::GeometryBuilder myBuilder;\n RenderBackend::Geometry *geo = myBuilder.createTriangle();\n if( nullptr != geo ) {\n\t\t\tm_transformMatrix.m_model = glm::rotate(m_transformMatrix.m_model, 0.0f, glm::vec3(1, 1, 0));\n\n\t\t\tParameter *parameter = Parameter::create(\"MVP\", PT_Mat4);\n\t\t\t::memcpy(parameter->m_data.m_data, glm::value_ptr(m_transformMatrix.m_projection*m_transformMatrix.m_view*m_transformMatrix.m_model), sizeof(glm::mat4));\n\n\t\t\tgeo->m_parameter = parameter;\n\t\t\tgeo->m_numParameter++;\n\n\t\t\tgeoNode->addGeometry(geo);\n\t\t}\n\n return true;\n }\n\n virtual void onUpdate() {\n m_stage->update();\n }\n};\n\nint main( int argc, char *argv[] ) {\n HelloWorldApp myApp( argc, argv );\n if( !myApp.create() ) {\n osre_error(Tag, \"Cannot create application instance.\" );\n return 1;\n }\n \n \/\/ handle events until application will be terminated\n while( myApp.handleEvents() ) {\n \n \/\/ update application data\n myApp.update();\n\n \/\/ request next frame rendering\n myApp.requestNextFrame();\n }\n myApp.destroy();\n\n return 0;\n}\n<commit_msg>Sample: remove unused code.<commit_after>#include <osre\/App\/AppBase.h>\n#include <osre\/Properties\/Settings.h>\n#include <osre\/Common\/Logger.h>\n#include <osre\/Scene\/GeometryBuilder.h>\n#include <osre\/Scene\/Stage.h>\n#include <osre\/Scene\/Node.h>\n#include <osre\/RenderBackend\/RenderCommon.h>\n\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\nusing namespace OSRE;\nusing namespace OSRE::RenderBackend;\n\n\/\/ to identify local log entries \nstatic const String Tag = \"HelloWorld\"; \n\nclass HelloWorldApp : public App::AppBase {\n Scene::Stage *m_stage;\n TransformMatrixBlock m_transformMatrix;\n\npublic:\n HelloWorldApp( int argc, char *argv[] )\n : AppBase( argc, argv )\n , m_stage( nullptr ) {\n\n }\n\n virtual ~HelloWorldApp() {\n\n }\n\nprotected:\n virtual bool onCreate( Properties::Settings *config = nullptr ) {\n AppBase::getConfig()->setString( Properties::Settings::WindowsTitle, \"HelloWorld!\" );\n\n if( !AppBase::onCreate( config ) ) {\n return false;\n }\n\n m_stage = AppBase::createStage( \"HelloWorld\" );\n Scene::Node *geoNode = m_stage->addNode( \"geo\", nullptr );\n Scene::GeometryBuilder myBuilder;\n RenderBackend::Geometry *geo = myBuilder.createTriangle();\n if( nullptr != geo ) {\n\t\t\tm_transformMatrix.m_model = glm::rotate(m_transformMatrix.m_model, 0.0f, glm::vec3(1, 1, 0));\n\n\t\t\tParameter *parameter = Parameter::create(\"MVP\", PT_Mat4);\n\t\t\t::memcpy(parameter->m_data.m_data, glm::value_ptr(m_transformMatrix.m_projection*m_transformMatrix.m_view*m_transformMatrix.m_model), sizeof(glm::mat4));\n\n\t\t\tgeo->m_parameter = parameter;\n\t\t\tgeo->m_numParameter++;\n\n\t\t\tgeoNode->addGeometry(geo);\n\t\t}\n\n return true;\n }\n\n virtual void onUpdate() {\n m_stage->update();\n }\n};\n\nint main( int argc, char *argv[] ) {\n HelloWorldApp myApp( argc, argv );\n if( !myApp.create() ) {\n osre_error(Tag, \"Cannot create application instance.\" );\n return 1;\n }\n \n \/\/ handle events until application will be terminated\n while( myApp.handleEvents() ) {\n \n \/\/ update application data\n myApp.update();\n\n \/\/ request next frame rendering\n myApp.requestNextFrame();\n }\n myApp.destroy();\n\n return 0;\n}\n<|endoftext|>"}